{"text":"<commit_before>\/*\nCopyright 2020 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage generator\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"k8s.io\/kube-state-metrics\/pkg\/allow\"\n\t\"k8s.io\/kube-state-metrics\/pkg\/metric\"\n)\n\nfunc TestFilterMetricFamiliesLabels(t *testing.T) {\n\ttests := []struct {\n\t\tname             string\n\t\tallowLabels      allow.Labels\n\t\tfamilyGenerators []FamilyGenerator\n\t\tresults          []FamilyGenerator\n\t}{\n\t\t{\n\t\t\tname:        \"Returns all the metric's keys and values if not annotation\/label metric by default\",\n\t\t\tallowLabels: allow.Labels(map[string][]string{}),\n\t\t\tfamilyGenerators: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_info\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\", \"three\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\", \"value-three\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tresults: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_info\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\", \"three\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\", \"value-three\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:        \"Returns no labels if it's an annotation metric and no allowed labels specified\",\n\t\t\tallowLabels: allow.Labels(map[string][]string{}),\n\t\t\tfamilyGenerators: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_annotations\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\", \"three\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\", \"value-three\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tresults: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_annotations\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tValue: 1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:        \"Returns no labels if it's an label metric and no allowed labels specified\",\n\t\t\tallowLabels: allow.Labels(map[string][]string{}),\n\t\t\tfamilyGenerators: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_labels\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\", \"three\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\", \"value-three\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tresults: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_labels\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tValue: 1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Returns allowed labels for metric and label and value pairs are correct\",\n\t\t\tallowLabels: allow.Labels(map[string][]string{\n\t\t\t\t\"node_info\": {\n\t\t\t\t\t\"two\",\n\t\t\t\t\t\"one\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tfamilyGenerators: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_info\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\", \"three\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\", \"value-three\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tresults: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_info\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"two\", \"one\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-two\", \"value-one\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Returns allowed labels for metric\",\n\t\t\tallowLabels: allow.Labels(map[string][]string{\n\t\t\t\t\"node_labels\": {\n\t\t\t\t\t\"one\",\n\t\t\t\t\t\"two\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tfamilyGenerators: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_labels\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\", \"three\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\", \"value-three\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tresults: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_labels\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tresults := FilterMetricFamiliesLabels(test.allowLabels, test.familyGenerators)\n\t\t\tif len(results) != len(test.results) {\n\t\t\t\tt.Fatalf(\"expected %v, got %v\", len(test.results), len(results))\n\t\t\t}\n\n\t\t\tfor i := range results {\n\t\t\t\tresult := results[i].GenerateFunc(nil)\n\t\t\t\texpected := test.results[i].GenerateFunc(nil)\n\t\t\t\tif !reflect.DeepEqual(result, expected) {\n\t\t\t\t\tt.Fatalf(\"Families don't equal, got %v, expected %v\", result, expected)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n<commit_msg>Fix test as sometimes metrics keys and values are generated in different order<commit_after>\/*\nCopyright 2020 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage generator\n\nimport (\n\t\"reflect\"\n\t\"sort\"\n\t\"testing\"\n\n\t\"k8s.io\/kube-state-metrics\/pkg\/allow\"\n\t\"k8s.io\/kube-state-metrics\/pkg\/metric\"\n)\n\nfunc TestFilterMetricFamiliesLabels(t *testing.T) {\n\ttests := []struct {\n\t\tname             string\n\t\tallowLabels      allow.Labels\n\t\tfamilyGenerators []FamilyGenerator\n\t\tresults          []FamilyGenerator\n\t}{\n\t\t{\n\t\t\tname:        \"Returns all the metric's keys and values if not annotation\/label metric by default\",\n\t\t\tallowLabels: allow.Labels(map[string][]string{}),\n\t\t\tfamilyGenerators: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_info\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\", \"three\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\", \"value-three\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tresults: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_info\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\", \"three\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\", \"value-three\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:        \"Returns no labels if it's an annotation metric and no allowed labels specified\",\n\t\t\tallowLabels: allow.Labels(map[string][]string{}),\n\t\t\tfamilyGenerators: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_annotations\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\", \"three\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\", \"value-three\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tresults: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_annotations\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tValue: 1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:        \"Returns no labels if it's an label metric and no allowed labels specified\",\n\t\t\tallowLabels: allow.Labels(map[string][]string{}),\n\t\t\tfamilyGenerators: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_labels\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\", \"three\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\", \"value-three\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tresults: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_labels\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tValue: 1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Returns allowed labels for metric and label and value pairs are correct\",\n\t\t\tallowLabels: allow.Labels(map[string][]string{\n\t\t\t\t\"node_info\": {\n\t\t\t\t\t\"two\",\n\t\t\t\t\t\"one\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tfamilyGenerators: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_info\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\", \"three\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\", \"value-three\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tresults: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_info\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"two\", \"one\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-two\", \"value-one\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Returns allowed labels for metric\",\n\t\t\tallowLabels: allow.Labels(map[string][]string{\n\t\t\t\t\"node_labels\": {\n\t\t\t\t\t\"one\",\n\t\t\t\t\t\"two\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\tfamilyGenerators: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_labels\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\", \"three\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\", \"value-three\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tresults: []FamilyGenerator{\n\t\t\t\t{\n\t\t\t\t\tName: \"node_labels\",\n\t\t\t\t\tHelp: \"some help\",\n\t\t\t\t\tType: metric.Gauge,\n\t\t\t\t\tGenerateFunc: func(obj interface{}) *metric.Family {\n\t\t\t\t\t\treturn &metric.Family{\n\t\t\t\t\t\t\tMetrics: []*metric.Metric{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tLabelKeys:   []string{\"one\", \"two\"},\n\t\t\t\t\t\t\t\t\tLabelValues: []string{\"value-one\", \"value-two\"},\n\t\t\t\t\t\t\t\t\tValue:       1,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tresults := FilterMetricFamiliesLabels(test.allowLabels, test.familyGenerators)\n\t\t\tif len(results) != len(test.results) {\n\t\t\t\tt.Fatalf(\"expected %v, got %v\", len(test.results), len(results))\n\t\t\t}\n\n\t\t\tfor i := range results {\n\t\t\t\tresult := results[i].GenerateFunc(nil)\n\t\t\t\texpected := test.results[i].GenerateFunc(nil)\n\t\t\t\tfor _, resultMetric := range result.Metrics {\n\t\t\t\t\tfor _, expectedMetric := range expected.Metrics {\n\t\t\t\t\t\tassertEqualSlices(t, expectedMetric.LabelKeys, resultMetric.LabelKeys, \"keys\")\n\t\t\t\t\t\tassertEqualSlices(t, expectedMetric.LabelValues, resultMetric.LabelValues, \"values\")\n\n\t\t\t\t\t\tif expectedMetric.Value != resultMetric.Value {\n\t\t\t\t\t\t\tt.Fatalf(\"value - expected %v, got %v\", expectedMetric.Value, resultMetric.Value)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc assertEqualSlices(t *testing.T, expected, actual []string, kind string) {\n\tsort.Strings(expected)\n\tsort.Strings(actual)\n\tif !reflect.DeepEqual(expected, actual) {\n\t\tt.Fatalf(\"%s - expected %v, got %v\", kind, expected, actual)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package camli\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"time\"\n\n\t\"camlistore.org\/pkg\/blob\"\n\t\"camlistore.org\/pkg\/client\"\n\t\"camlistore.org\/pkg\/schema\"\n\t\"camlistore.org\/pkg\/search\"\n)\n\n\/\/ Repo is our Camlistore scheme to model the state of a\n\/\/ particular repo at a particular point in time.\ntype Repo struct {\n\tName      string\n\tParent    string\n\tRetrieved time.Time\n\tRefs      map[string]string\n\tPackfiles []string\n}\n\n\/\/ PutRepo stores a Repo in Camlistore.\nfunc (u *Uploader) PutRepo(r *Repo) error {\n\tbb := schema.NewBuilder()\n\tbb.SetType(\"git-repo\")\n\tbb.SetRawStringField(\"parent\", r.Parent)\n\tbb.SetRawStringField(\"retrieved\", schema.RFC3339FromTime(r.Retrieved))\n\tif refs, err := json.Marshal(r.Refs); err == nil {\n\t\t\/\/ TODO The builder just escapes this. We need the actual map as a\n\t\t\/\/ json object.\n\t\tbb.SetRawStringField(\"refs\", string(refs))\n\t} else {\n\t\treturn err\n\t}\n\tif packfiles, err := json.Marshal(r.Packfiles); err == nil {\n\t\t\/\/ TODO The builder just escapes this. We need the actual map as a\n\t\t\/\/ json object.\n\t\tbb.SetRawStringField(\"packfiles\", string(packfiles))\n\t} else {\n\t\treturn err\n\t}\n\n\tj := bb.Blob().JSON()\n\treporef := blob.SHA1FromString(j)\n\t_, err := uploadString(u.c, reporef, j)\n\n\tlog.Printf(\"stored repo: %s on %s\", r.Name, reporef)\n\n\t\/\/ Update or create its permanode.\n\tpn, _, err := u.findRepo(r.Name)\n\tif err != nil {\n\t\t\/\/ Create a new one.\n\t\tres, err := u.c.UploadNewPermanode()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpn = res.BlobRef\n\t\tlog.Printf(\"created permanode: %s\", pn)\n\n\t\ttitleattr := schema.NewSetAttributeClaim(pn, \"title\", r.Name)\n\t\tclaimTime := time.Now()\n\t\ttitleattr.SetClaimDate(claimTime)\n\t\tsigner, err := u.c.Signer()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsigned, err := titleattr.SignAt(signer, claimTime)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't to sign title claim\")\n\t\t}\n\t\t_, err = u.c.Upload(client.NewUploadHandleFromString(signed))\n\t}\n\tcontentattr := schema.NewSetAttributeClaim(pn, \"camliContent\", reporef.String())\n\tclaimTime := time.Now()\n\tcontentattr.SetClaimDate(claimTime)\n\tsigner, err := u.c.Signer()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsigned, err := contentattr.SignAt(signer, claimTime)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't to sign content claim\")\n\t}\n\t_, err = u.c.Upload(client.NewUploadHandleFromString(signed))\n\treturn err\n}\n\nvar repoNotFoundErr = errors.New(\"repo not found\")\n\nfunc (u *Uploader) findRepo(name string) (blob.Ref, search.MetaMap, error) {\n\tres, err := u.c.Query(&search.SearchQuery{\n\t\tLimit: 1,\n\t\tConstraint: &search.Constraint{\n\t\t\tPermanode: &search.PermanodeConstraint{\n\t\t\t\tAttr: \"title\", Value: name,\n\t\t\t},\n\t\t},\n\t\tDescribe: &search.DescribeRequest{},\n\t})\n\tif err != nil {\n\t\treturn blob.Ref{}, nil, err\n\t}\n\tif len(res.Blobs) < 1 {\n\t\treturn blob.Ref{}, nil, repoNotFoundErr\n\t}\n\treturn res.Blobs[0].Blob, res.Describe.Meta, nil\n}\n\n\/\/ GetRepo querys for a repo permanode with name, and returns its\n\/\/ Repo object.\nfunc (u *Uploader) GetRepo(name string) (*Repo, error) {\n\tpn, meta, err := u.findRepo(name)\n\tif err == repoNotFoundErr {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\tref, ok := meta[pn.String()].ContentRef()\n\tif !ok {\n\t\treturn nil, errors.New(\"couldn't find repo data (but there's a permanode)\")\n\t}\n\tr, _, err := u.c.Fetch(ref)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbody, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar repo Repo\n\terr = json.Unmarshal(body, &repo)\n\treturn &repo, err\n}\n<commit_msg>camli: use bb.SetRawStringField<commit_after>package camli\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"time\"\n\n\t\"camlistore.org\/pkg\/blob\"\n\t\"camlistore.org\/pkg\/client\"\n\t\"camlistore.org\/pkg\/schema\"\n\t\"camlistore.org\/pkg\/search\"\n)\n\n\/\/ Repo is our Camlistore scheme to model the state of a\n\/\/ particular repo at a particular point in time.\ntype Repo struct {\n\tName      string\n\tParent    string\n\tRetrieved time.Time\n\tRefs      map[string]string\n\tPackfiles []string\n}\n\n\/\/ PutRepo stores a Repo in Camlistore.\nfunc (u *Uploader) PutRepo(r *Repo) error {\n\tbb := schema.NewBuilder()\n\tbb.SetType(\"git-repo\")\n\tbb.SetRawStringField(\"parent\", r.Parent)\n\tbb.SetRawStringField(\"retrieved\", schema.RFC3339FromTime(r.Retrieved))\n\tif refs, err := schema.NewJSONObject(r.Refs); err == nil {\n\t\tbb.SetRawField(\"refs\", refs)\n\t} else {\n\t\treturn err\n\t}\n\tif packfiles, err := schema.NewJSONObject(r.Packfiles); err == nil {\n\t\tbb.SetRawField(\"packfiles\", packfiles)\n\t} else {\n\t\treturn err\n\t}\n\n\tj := bb.Blob().JSON()\n\treporef := blob.SHA1FromString(j)\n\t_, err := uploadString(u.c, reporef, j)\n\n\tlog.Printf(\"stored repo: %s on %s\", r.Name, reporef)\n\n\t\/\/ Update or create its permanode.\n\tpn, _, err := u.findRepo(r.Name)\n\tif err != nil {\n\t\t\/\/ Create a new one.\n\t\tres, err := u.c.UploadNewPermanode()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpn = res.BlobRef\n\t\tlog.Printf(\"created permanode: %s\", pn)\n\n\t\ttitleattr := schema.NewSetAttributeClaim(pn, \"title\", r.Name)\n\t\tclaimTime := time.Now()\n\t\ttitleattr.SetClaimDate(claimTime)\n\t\tsigner, err := u.c.Signer()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsigned, err := titleattr.SignAt(signer, claimTime)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't to sign title claim\")\n\t\t}\n\t\t_, err = u.c.Upload(client.NewUploadHandleFromString(signed))\n\t}\n\tcontentattr := schema.NewSetAttributeClaim(pn, \"camliContent\", reporef.String())\n\tclaimTime := time.Now()\n\tcontentattr.SetClaimDate(claimTime)\n\tsigner, err := u.c.Signer()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsigned, err := contentattr.SignAt(signer, claimTime)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't to sign content claim\")\n\t}\n\t_, err = u.c.Upload(client.NewUploadHandleFromString(signed))\n\treturn err\n}\n\nvar repoNotFoundErr = errors.New(\"repo not found\")\n\nfunc (u *Uploader) findRepo(name string) (blob.Ref, search.MetaMap, error) {\n\tres, err := u.c.Query(&search.SearchQuery{\n\t\tLimit: 1,\n\t\tConstraint: &search.Constraint{\n\t\t\tPermanode: &search.PermanodeConstraint{\n\t\t\t\tAttr: \"title\", Value: name,\n\t\t\t},\n\t\t},\n\t\tDescribe: &search.DescribeRequest{},\n\t})\n\tif err != nil {\n\t\treturn blob.Ref{}, nil, err\n\t}\n\tif len(res.Blobs) < 1 {\n\t\treturn blob.Ref{}, nil, repoNotFoundErr\n\t}\n\treturn res.Blobs[0].Blob, res.Describe.Meta, nil\n}\n\n\/\/ GetRepo querys for a repo permanode with name, and returns its\n\/\/ Repo object.\nfunc (u *Uploader) GetRepo(name string) (*Repo, error) {\n\tpn, meta, err := u.findRepo(name)\n\tif err == repoNotFoundErr {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\tref, ok := meta[pn.String()].ContentRef()\n\tif !ok {\n\t\treturn nil, errors.New(\"couldn't find repo data (but there's a permanode)\")\n\t}\n\tr, _, err := u.c.Fetch(ref)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbody, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar repo Repo\n\terr = json.Unmarshal(body, &repo)\n\treturn &repo, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2021 Steve Francia <spf@spf13.com>.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage tpl\n\nfunc MainTemplate() []byte {\n\treturn []byte(`\/*\n{{ .Copyright }}\n{{ if .Legal.Header }}{{ .Legal.Header }}{{ end }}\n*\/\npackage main\n\nimport \"{{ .PkgName }}\/cmd\"\n\nfunc main() {\n\tcmd.Execute()\n}\n`)\n}\n\nfunc RootTemplate() []byte {\n\treturn []byte(`\/*\n{{ .Copyright }}\n{{ if .Legal.Header }}{{ .Legal.Header }}{{ end }}\n*\/\npackage cmd\n\nimport (\n{{- if .Viper }}\n\t\"fmt\"\n\t\"os\"\n{{ end }}\n\t\"github.com\/spf13\/cobra\"\n{{- if .Viper }}\n\t\"github.com\/spf13\/viper\"{{ end }}\n)\n\n{{ if .Viper -}}\nvar cfgFile string\n{{- end }}\n\n\/\/ rootCmd represents the base command when called without any subcommands\nvar rootCmd = &cobra.Command{\n\tUse:   \"{{ .AppName }}\",\n\tShort: \"A brief description of your application\",\n\tLong: ` + \"`\" + `A longer description that spans multiple lines and likely contains\nexamples and usage of using your application. For example:\n\nCobra is a CLI library for Go that empowers applications.\nThis application is a tool to generate the needed files\nto quickly create a Cobra application.` + \"`\" + `,\n\t\/\/ Uncomment the following line if your bare application\n\t\/\/ has an action associated with it:\n\t\/\/ Run: func(cmd *cobra.Command, args []string) { },\n}\n\n\/\/ Execute adds all child commands to the root command and sets flags appropriately.\n\/\/ This is called by main.main(). It only needs to happen once to the rootCmd.\nfunc Execute() {\n\tcobra.CheckErr(rootCmd.Execute())\n}\n\nfunc init() {\n{{- if .Viper }}\n\tcobra.OnInitialize(initConfig)\n{{ end }}\n\t\/\/ Here you will define your flags and configuration settings.\n\t\/\/ Cobra supports persistent flags, which, if defined here,\n\t\/\/ will be global for your application.\n{{ if .Viper }}\n\trootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME\/.{{ .AppName }}.yaml)\")\n{{ else }}\n\t\/\/ rootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME\/.{{ .AppName }}.yaml)\")\n{{ end }}\n\t\/\/ Cobra also supports local flags, which will only run\n\t\/\/ when this action is called directly.\n\trootCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n}\n\n{{ if .Viper -}}\n\/\/ initConfig reads in config file and ENV variables if set.\nfunc initConfig() {\n\tif cfgFile != \"\" {\n\t\t\/\/ Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t\/\/ Find home directory.\n\t\thome, err := os.UserHomeDir()\n\t\tcobra.CheckErr(err)\n\n\t\t\/\/ Search config in home directory with name \".{{ .AppName }}\" (without extension).\n\t\tviper.AddConfigPath(home)\n\t\tviper.SetConfigType(\"yaml\")\n\t\tviper.SetConfigName(\".{{ .AppName }}\")\n\t}\n\n\tviper.AutomaticEnv() \/\/ read in environment variables that match\n\n\t\/\/ If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Fprintln(os.Stderr, \"Using config file:\", viper.ConfigFileUsed())\n\t}\n}\n{{- end }}\n`)\n}\n\nfunc AddCommandTemplate() []byte {\n\treturn []byte(`\/*\n{{ .Project.Copyright }}\n{{ if .Legal.Header }}{{ .Legal.Header }}{{ end }}\n*\/\npackage cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ {{ .CmdName }}Cmd represents the {{ .CmdName }} command\nvar {{ .CmdName }}Cmd = &cobra.Command{\n\tUse:   \"{{ .CmdName }}\",\n\tShort: \"A brief description of your command\",\n\tLong: ` + \"`\" + `A longer description that spans multiple lines and likely contains examples\nand usage of using your command. For example:\n\nCobra is a CLI library for Go that empowers applications.\nThis application is a tool to generate the needed files\nto quickly create a Cobra application.` + \"`\" + `,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tfmt.Println(\"{{ .CmdName }} called\")\n\t},\n}\n\nfunc init() {\n\t{{ .CmdParent }}.AddCommand({{ .CmdName }}Cmd)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\n\t\/\/ Cobra supports Persistent Flags which will work for this command\n\t\/\/ and all subcommands, e.g.:\n\t\/\/ {{ .CmdName }}Cmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t\/\/ Cobra supports local flags which will only run when this command\n\t\/\/ is called directly, e.g.:\n\t\/\/ {{ .CmdName }}Cmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n}\n`)\n}\n<commit_msg>fix: Duplicate error message from cobra init boilerplates (#1463)<commit_after>\/\/ Copyright © 2021 Steve Francia <spf@spf13.com>.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage tpl\n\nfunc MainTemplate() []byte {\n\treturn []byte(`\/*\n{{ .Copyright }}\n{{ if .Legal.Header }}{{ .Legal.Header }}{{ end }}\n*\/\npackage main\n\nimport \"{{ .PkgName }}\/cmd\"\n\nfunc main() {\n\tcmd.Execute()\n}\n`)\n}\n\nfunc RootTemplate() []byte {\n\treturn []byte(`\/*\n{{ .Copyright }}\n{{ if .Legal.Header }}{{ .Legal.Header }}{{ end }}\n*\/\npackage cmd\n\nimport (\n{{- if .Viper }}\n\t\"fmt\"\n\t\"os\"\n{{ end }}\n\t\"github.com\/spf13\/cobra\"\n{{- if .Viper }}\n\t\"github.com\/spf13\/viper\"{{ end }}\n)\n\n{{ if .Viper -}}\nvar cfgFile string\n{{- end }}\n\n\/\/ rootCmd represents the base command when called without any subcommands\nvar rootCmd = &cobra.Command{\n\tUse:   \"{{ .AppName }}\",\n\tShort: \"A brief description of your application\",\n\tLong: ` + \"`\" + `A longer description that spans multiple lines and likely contains\nexamples and usage of using your application. For example:\n\nCobra is a CLI library for Go that empowers applications.\nThis application is a tool to generate the needed files\nto quickly create a Cobra application.` + \"`\" + `,\n\t\/\/ Uncomment the following line if your bare application\n\t\/\/ has an action associated with it:\n\t\/\/ Run: func(cmd *cobra.Command, args []string) { },\n}\n\n\/\/ Execute adds all child commands to the root command and sets flags appropriately.\n\/\/ This is called by main.main(). It only needs to happen once to the rootCmd.\nfunc Execute() {\n\terr := rootCmd.Execute()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc init() {\n{{- if .Viper }}\n\tcobra.OnInitialize(initConfig)\n{{ end }}\n\t\/\/ Here you will define your flags and configuration settings.\n\t\/\/ Cobra supports persistent flags, which, if defined here,\n\t\/\/ will be global for your application.\n{{ if .Viper }}\n\trootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME\/.{{ .AppName }}.yaml)\")\n{{ else }}\n\t\/\/ rootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME\/.{{ .AppName }}.yaml)\")\n{{ end }}\n\t\/\/ Cobra also supports local flags, which will only run\n\t\/\/ when this action is called directly.\n\trootCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n}\n\n{{ if .Viper -}}\n\/\/ initConfig reads in config file and ENV variables if set.\nfunc initConfig() {\n\tif cfgFile != \"\" {\n\t\t\/\/ Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t\/\/ Find home directory.\n\t\thome, err := os.UserHomeDir()\n\t\tcobra.CheckErr(err)\n\n\t\t\/\/ Search config in home directory with name \".{{ .AppName }}\" (without extension).\n\t\tviper.AddConfigPath(home)\n\t\tviper.SetConfigType(\"yaml\")\n\t\tviper.SetConfigName(\".{{ .AppName }}\")\n\t}\n\n\tviper.AutomaticEnv() \/\/ read in environment variables that match\n\n\t\/\/ If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Fprintln(os.Stderr, \"Using config file:\", viper.ConfigFileUsed())\n\t}\n}\n{{- end }}\n`)\n}\n\nfunc AddCommandTemplate() []byte {\n\treturn []byte(`\/*\n{{ .Project.Copyright }}\n{{ if .Legal.Header }}{{ .Legal.Header }}{{ end }}\n*\/\npackage cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ {{ .CmdName }}Cmd represents the {{ .CmdName }} command\nvar {{ .CmdName }}Cmd = &cobra.Command{\n\tUse:   \"{{ .CmdName }}\",\n\tShort: \"A brief description of your command\",\n\tLong: ` + \"`\" + `A longer description that spans multiple lines and likely contains examples\nand usage of using your command. For example:\n\nCobra is a CLI library for Go that empowers applications.\nThis application is a tool to generate the needed files\nto quickly create a Cobra application.` + \"`\" + `,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tfmt.Println(\"{{ .CmdName }} called\")\n\t},\n}\n\nfunc init() {\n\t{{ .CmdParent }}.AddCommand({{ .CmdName }}Cmd)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\n\t\/\/ Cobra supports Persistent Flags which will work for this command\n\t\/\/ and all subcommands, e.g.:\n\t\/\/ {{ .CmdName }}Cmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t\/\/ Cobra supports local flags which will only run when this command\n\t\/\/ is called directly, e.g.:\n\t\/\/ {{ .CmdName }}Cmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n}\n`)\n}\n<|endoftext|>"}
{"text":"<commit_before>package a\n\nimport (\n\t. \"github.com\/alecthomas\/chroma\" \/\/ nolint\n\t\"github.com\/alecthomas\/chroma\/lexers\/internal\"\n)\n\n\/\/ Al lexer.\nvar Al = internal.Register(MustNewLazyLexer(\n\t&Config{\n\t\tName:            \"AL\",\n\t\tAliases:         []string{\"al\"},\n\t\tFilenames:       []string{\"*.al\", \"*.dal\"},\n\t\tMimeTypes:       []string{\"text\/x-al\"},\n\t\tDotAll:          true,\n\t\tCaseInsensitive: true,\n\t},\n\talRules,\n))\n\n\/\/ https:\/\/github.com\/microsoft\/AL\/blob\/master\/grammar\/alsyntax.tmlanguage\nfunc alRules() Rules {\n\treturn Rules{\n\t\t\"root\": {\n\t\t\t{`\\s+`, TextWhitespace, nil},\n\t\t\t{`(?s)\\\/\\*.*?\\\\*\\*\\\/`, CommentMultiline, nil},\n\t\t\t{`(?s)\/\/.*?\\n`, CommentSingle, nil},\n\t\t\t{`\\\"([^\\\"])*\\\"`, Text, nil},\n\t\t\t{`'([^'])*'`, LiteralString, nil},\n\t\t\t{`\\b(?i:(ARRAY|ASSERTERROR|BEGIN|BREAK|CASE|DO|DOWNTO|ELSE|END|EVENT|EXIT|FOR|FOREACH|FUNCTION|IF|IMPLEMENTS|IN|INDATASET|INTERFACE|INTERNAL|LOCAL|OF|PROCEDURE|PROGRAM|PROTECTED|REPEAT|RUNONCLIENT|SECURITYFILTERING|SUPPRESSDISPOSE|TEMPORARY|THEN|TO|TRIGGER|UNTIL|VAR|WHILE|WITH|WITHEVENTS))\\b`, Keyword, nil},\n\t\t\t{`\\b(?i:(AND|DIV|MOD|NOT|OR|XOR))\\b`, OperatorWord, nil},\n\t\t\t{`\\b(?i:(AVERAGE|CONST|COUNT|EXIST|FIELD|FILTER|LOOKUP|MAX|MIN|ORDER|SORTING|SUM|TABLEDATA|UPPERLIMIT|WHERE|ASCENDING|DESCENDING))\\b`, Keyword, nil},\n\t\t\t\/\/ Added new objects types of BC 2021 wave 1 (REPORTEXTENSION|Entitlement|PermissionSet|PermissionSetExtension)\n\t\t\t{`\\b(?i:(CODEUNIT|PAGE|PAGEEXTENSION|PAGECUSTOMIZATION|DOTNET|ENUM|ENUMEXTENSION|VALUE|QUERY|REPORT|TABLE|TABLEEXTENSION|XMLPORT|PROFILE|CONTROLADDIN|REPORTEXTENSION|Entitlement|PermissionSet|PermissionSetExtension))\\b`, Keyword, nil},\n\t\t\t{`\\b(?i:(Action|Array|Automation|BigInteger|BigText|Blob|Boolean|Byte|Char|ClientType|Code|Codeunit|CompletionTriggerErrorLevel|ConnectionType|Database|DataClassification|DataScope|Date|DateFormula|DateTime|Decimal|DefaultLayout|Dialog|Dictionary|DotNet|DotNetAssembly|DotNetTypeDeclaration|Duration|Enum|ErrorInfo|ErrorType|ExecutionContext|ExecutionMode|FieldClass|FieldRef|FieldType|File|FilterPageBuilder|Guid|InStream|Integer|Joker|KeyRef|List|ModuleDependencyInfo|ModuleInfo|None|Notification|NotificationScope|ObjectType|Option|OutStream|Page|PageResult|Query|Record|RecordId|RecordRef|Report|ReportFormat|SecurityFilter|SecurityFiltering|Table|TableConnectionType|TableFilter|TestAction|TestField|TestFilterField|TestPage|TestPermissions|TestRequestPage|Text|TextBuilder|TextConst|TextEncoding|Time|TransactionModel|TransactionType|Variant|Verbosity|Version|XmlPort|HttpContent|HttpHeaders|HttpClient|HttpRequestMessage|HttpResponseMessage|JsonToken|JsonValue|JsonArray|JsonObject|View|Views|XmlAttribute|XmlAttributeCollection|XmlComment|XmlCData|XmlDeclaration|XmlDocument|XmlDocumentType|XmlElement|XmlNamespaceManager|XmlNameTable|XmlNode|XmlNodeList|XmlProcessingInstruction|XmlReadOptions|XmlText|XmlWriteOptions|WebServiceActionContext|WebServiceActionResultCode|SessionSettings))\\b`, Keyword, nil},\n\t\t\t{`\\b([<>]=|<>|<|>)\\b?`, Operator, nil},\n\t\t\t{`\\b(\\-|\\+|\\\/|\\*)\\b`, Operator, nil},\n\t\t\t{`\\s*(\\:=|\\+=|-=|\\\/=|\\*=)\\s*?`, Operator, nil},\n\t\t\t{`\\b(?i:(ADDFIRST|ADDLAST|ADDAFTER|ADDBEFORE|ACTION|ACTIONS|AREA|ASSEMBLY|CHARTPART|CUEGROUP|CUSTOMIZES|COLUMN|DATAITEM|DATASET|ELEMENTS|EXTENDS|FIELD|FIELDGROUP|FIELDATTRIBUTE|FIELDELEMENT|FIELDGROUPS|FIELDS|FILTER|FIXED|GRID|GROUP|MOVEAFTER|MOVEBEFORE|KEY|KEYS|LABEL|LABELS|LAYOUT|MODIFY|MOVEFIRST|MOVELAST|MOVEBEFORE|MOVEAFTER|PART|REPEATER|USERCONTROL|REQUESTPAGE|SCHEMA|SEPARATOR|SYSTEMPART|TABLEELEMENT|TEXTATTRIBUTE|TEXTELEMENT|TYPE))\\b`, Keyword, nil},\n\t\t\t{`\\s*[(\\.\\.)&\\|]\\s*`, Operator, nil},\n\t\t\t{`\\b((0(x|X)[0-9a-fA-F]*)|(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))((e|E)(\\+|-)?[0-9]+)?)(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?\\b`, LiteralNumber, nil},\n\t\t\t{`[;:,]`, Punctuation, nil},\n\t\t\t{`#[ \\t]*(if|else|elif|endif|define|undef|region|endregion|pragma)\\b.*?\\n`, CommentPreproc, nil},\n\t\t\t{`\\w+`, Text, nil},\n\t\t\t{`.`, Text, nil},\n\t\t},\n\t}\n}\n<commit_msg>Update to the last version of microsoft grammar file<commit_after>package a\n\nimport (\n\t. \"github.com\/alecthomas\/chroma\" \/\/ nolint\n\t\"github.com\/alecthomas\/chroma\/lexers\/internal\"\n)\n\n\/\/ Al lexer.\nvar Al = internal.Register(MustNewLazyLexer(\n\t&Config{\n\t\tName:            \"AL\",\n\t\tAliases:         []string{\"al\"},\n\t\tFilenames:       []string{\"*.al\", \"*.dal\"},\n\t\tMimeTypes:       []string{\"text\/x-al\"},\n\t\tDotAll:          true,\n\t\tCaseInsensitive: true,\n\t},\n\talRules,\n))\n\n\/\/ https:\/\/github.com\/microsoft\/AL\/blob\/master\/grammar\/alsyntax.tmlanguage\nfunc alRules() Rules {\n\treturn Rules{\n\t\t\"root\": {\n\t\t\t{`\\s+`, TextWhitespace, nil},\n\t\t\t{`(?s)\\\/\\*.*?\\\\*\\*\\\/`, CommentMultiline, nil},\n\t\t\t{`(?s)\/\/.*?\\n`, CommentSingle, nil},\n\t\t\t{`\\\"([^\\\"])*\\\"`, Text, nil},\n\t\t\t{`'([^'])*'`, LiteralString, nil},\n\t\t\t{`\\b(?i:(ARRAY|ASSERTERROR|BEGIN|BREAK|CASE|DO|DOWNTO|ELSE|END|EVENT|EXIT|FOR|FOREACH|FUNCTION|IF|IMPLEMENTS|IN|INDATASET|INTERFACE|INTERNAL|LOCAL|OF|PROCEDURE|PROGRAM|PROTECTED|REPEAT|RUNONCLIENT|SECURITYFILTERING|SUPPRESSDISPOSE|TEMPORARY|THEN|TO|TRIGGER|UNTIL|VAR|WHILE|WITH|WITHEVENTS))\\b`, Keyword, nil},\n\t\t\t{`\\b(?i:(AND|DIV|MOD|NOT|OR|XOR))\\b`, OperatorWord, nil},\n\t\t\t{`\\b(?i:(AVERAGE|CONST|COUNT|EXIST|FIELD|FILTER|LOOKUP|MAX|MIN|ORDER|SORTING|SUM|TABLEDATA|UPPERLIMIT|WHERE|ASCENDING|DESCENDING))\\b`, Keyword, nil},\n\t\t\t{`\\b(?i:(CODEUNIT|PAGE|PAGEEXTENSION|PAGECUSTOMIZATION|DOTNET|ENUM|ENUMEXTENSION|VALUE|QUERY|REPORT|TABLE|TABLEEXTENSION|XMLPORT|PROFILE|CONTROLADDIN|REPORTEXTENSION|INTERFACE|PERMISSIONSET|PERMISSIONSETEXTENSION|ENTITLEMENT))\\b`, Keyword, nil},\n\t\t\t{`\\b(?i:(Action|Array|Automation|BigInteger|BigText|Blob|Boolean|Byte|Char|ClientType|Code|Codeunit|CompletionTriggerErrorLevel|ConnectionType|Database|DataClassification|DataScope|Date|DateFormula|DateTime|Decimal|DefaultLayout|Dialog|Dictionary|DotNet|DotNetAssembly|DotNetTypeDeclaration|Duration|Enum|ErrorInfo|ErrorType|ExecutionContext|ExecutionMode|FieldClass|FieldRef|FieldType|File|FilterPageBuilder|Guid|InStream|Integer|Joker|KeyRef|List|ModuleDependencyInfo|ModuleInfo|None|Notification|NotificationScope|ObjectType|Option|OutStream|Page|PageResult|Query|Record|RecordId|RecordRef|Report|ReportFormat|SecurityFilter|SecurityFiltering|Table|TableConnectionType|TableFilter|TestAction|TestField|TestFilterField|TestPage|TestPermissions|TestRequestPage|Text|TextBuilder|TextConst|TextEncoding|Time|TransactionModel|TransactionType|Variant|Verbosity|Version|XmlPort|HttpContent|HttpHeaders|HttpClient|HttpRequestMessage|HttpResponseMessage|JsonToken|JsonValue|JsonArray|JsonObject|View|Views|XmlAttribute|XmlAttributeCollection|XmlComment|XmlCData|XmlDeclaration|XmlDocument|XmlDocumentType|XmlElement|XmlNamespaceManager|XmlNameTable|XmlNode|XmlNodeList|XmlProcessingInstruction|XmlReadOptions|XmlText|XmlWriteOptions|WebServiceActionContext|WebServiceActionResultCode|SessionSettings))\\b`, Keyword, nil},\n\t\t\t{`\\b([<>]=|<>|<|>)\\b?`, Operator, nil},\n\t\t\t{`\\b(\\-|\\+|\\\/|\\*)\\b`, Operator, nil},\n\t\t\t{`\\s*(\\:=|\\+=|-=|\\\/=|\\*=)\\s*?`, Operator, nil},\n\t\t\t{`\\b(?i:(ADD|ADDFIRST|ADDLAST|ADDAFTER|ADDBEFORE|ACTION|ACTIONS|AREA|ASSEMBLY|CHARTPART|CUEGROUP|CUSTOMIZES|COLUMN|DATAITEM|DATASET|ELEMENTS|EXTENDS|FIELD|FIELDGROUP|FIELDATTRIBUTE|FIELDELEMENT|FIELDGROUPS|FIELDS|FILTER|FIXED|GRID|GROUP|MOVEAFTER|MOVEBEFORE|KEY|KEYS|LABEL|LABELS|LAYOUT|MODIFY|MOVEFIRST|MOVELAST|MOVEBEFORE|MOVEAFTER|PART|REPEATER|USERCONTROL|REQUESTPAGE|SCHEMA|SEPARATOR|SYSTEMPART|TABLEELEMENT|TEXTATTRIBUTE|TEXTELEMENT|TYPE))\\b`, Keyword, nil},\n\t\t\t{`\\s*[(\\.\\.)&\\|]\\s*`, Operator, nil},\n\t\t\t{`\\b((0(x|X)[0-9a-fA-F]*)|(([0-9]+\\.?[0-9]*)|(\\.[0-9]+))((e|E)(\\+|-)?[0-9]+)?)(L|l|UL|ul|u|U|F|f|ll|LL|ull|ULL)?\\b`, LiteralNumber, nil},\n\t\t\t{`[;:,]`, Punctuation, nil},\n\t\t\t{`#[ \\t]*(if|else|elif|endif|define|undef|region|endregion|pragma)\\b.*?\\n`, CommentPreproc, nil},\n\t\t\t{`\\w+`, Text, nil},\n\t\t\t{`.`, Text, nil},\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/NebulousLabs\/Sia\/build\"\n\t\"github.com\/NebulousLabs\/Sia\/crypto\"\n\t\"github.com\/NebulousLabs\/Sia\/types\"\n)\n\n\/\/ TestIntegrationHosting tests that the host correctly receives payment for\n\/\/ hosting files.\nfunc TestIntegrationHosting(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\n\tst, err := createServerTester(\"TestIntegrationHosting\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ announce the host\n\terr = st.stdGetAPI(\"\/host\/announce?address=\" + string(st.host.Address()))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t\/\/ we need to announce twice, or the renter will complain about not having enough hosts\n\tloopAddr := \"127.0.0.1:\" + st.host.Address().Port()\n\terr = st.stdGetAPI(\"\/host\/announce?address=\" + loopAddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ wait for announcement to register\n\tst.miner.AddBlock()\n\tvar hosts ActiveHosts\n\tst.getAPI(\"\/hostdb\/hosts\/active\", &hosts)\n\tif len(hosts.Hosts) == 0 {\n\t\tt.Fatal(\"host announcement not seen\")\n\t}\n\n\t\/\/ create a file\n\tpath := filepath.Join(build.SiaTestingDir, \"api\", \"TestIntegrationHosting\", \"test.dat\")\n\tdata, err := crypto.RandBytes(1024)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = ioutil.WriteFile(path, data, 0600)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ upload to host\n\terr = st.stdGetAPI(\"\/renter\/files\/upload?nickname=test&duration=10&source=\" + path)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar fi []FileInfo\n\tvar loops int\n\tfor len(fi) != 1 || fi[0].UploadProgress != 100 {\n\t\tst.getAPI(\"\/renter\/files\/list\", &fi)\n\t\ttime.Sleep(3 * time.Second)\n\t\tloops++\n\t}\n\n\t\/\/ mine blocks until storage proof is complete\n\tfor i := 0; i < 50+int(types.MaturityDelay); i++ {\n\t\tst.miner.AddBlock()\n\t}\n\n\t\/\/ check balance\n\tvar wi WalletGET\n\tst.getAPI(\"\/wallet\", &wi)\n\texpBal := \"16499494999617870000000002429474\"\n\tif wi.ConfirmedSiacoinBalance.String() != expBal {\n\t\tt.Fatalf(\"host's balance was not affected: expected %v, got %v\", expBal, wi.ConfirmedSiacoinBalance)\n\t}\n}\n<commit_msg>use host.Profit in host test instead of wallet<commit_after>package api\n\nimport (\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/NebulousLabs\/Sia\/build\"\n\t\"github.com\/NebulousLabs\/Sia\/crypto\"\n\t\"github.com\/NebulousLabs\/Sia\/modules\"\n\t\"github.com\/NebulousLabs\/Sia\/types\"\n)\n\n\/\/ TestIntegrationHosting tests that the host correctly receives payment for\n\/\/ hosting files.\nfunc TestIntegrationHosting(t *testing.T) {\n\tif testing.Short() {\n\t\tt.SkipNow()\n\t}\n\n\tst, err := createServerTester(\"TestIntegrationHosting\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ announce the host\n\terr = st.stdGetAPI(\"\/host\/announce?address=\" + string(st.host.Address()))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t\/\/ we need to announce twice, or the renter will complain about not having enough hosts\n\tloopAddr := \"127.0.0.1:\" + st.host.Address().Port()\n\terr = st.stdGetAPI(\"\/host\/announce?address=\" + loopAddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ wait for announcement to register\n\tst.miner.AddBlock()\n\tvar hosts ActiveHosts\n\tst.getAPI(\"\/hostdb\/hosts\/active\", &hosts)\n\tif len(hosts.Hosts) == 0 {\n\t\tt.Fatal(\"host announcement not seen\")\n\t}\n\n\t\/\/ create a file\n\tpath := filepath.Join(build.SiaTestingDir, \"api\", \"TestIntegrationHosting\", \"test.dat\")\n\tdata, err := crypto.RandBytes(1024)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = ioutil.WriteFile(path, data, 0600)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ upload to host\n\terr = st.stdGetAPI(\"\/renter\/files\/upload?nickname=test&duration=10&source=\" + path)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar fi []FileInfo\n\tfor len(fi) != 1 || fi[0].UploadProgress != 100 {\n\t\tst.getAPI(\"\/renter\/files\/list\", &fi)\n\t\ttime.Sleep(3 * time.Second)\n\t}\n\n\t\/\/ mine blocks until storage proof is complete\n\tfor i := 0; i < 20+int(types.MaturityDelay); i++ {\n\t\tst.miner.AddBlock()\n\t}\n\n\t\/\/ check profit\n\tvar hi modules.HostInfo\n\tst.getAPI(\"\/host\/status\", &hi)\n\texpProfit := \"382129999999997570526\"\n\tif hi.Profit.String() != expProfit {\n\t\tt.Log(hi)\n\t\tt.Fatalf(\"host's profit was not affected: expected %v, got %v\", expProfit, hi.Profit)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package manager\n\nimport (\n\t\"github.com\/rancher\/types\/apis\/management.cattle.io\/v3\"\n\t\"github.com\/sirupsen\/logrus\"\n\tkerrors \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\nfunc (m *Manager) Sync(key string, obj *v3.Catalog) error {\n\tif obj == nil {\n\t\treturn nil\n\t}\n\tif obj.DeletionTimestamp != nil {\n\t\ttemplates, err := m.getTemplateMap(obj.Name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttvToDelete := map[string]struct{}{}\n\t\tfor _, t := range templates {\n\t\t\ttvs, err := m.getTemplateVersion(t.Name)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor k := range tvs {\n\t\t\t\ttvToDelete[k] = struct{}{}\n\t\t\t}\n\t\t}\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tfor k := range templates {\n\t\t\t\t\tif err := m.templateClient.Delete(k, &metav1.DeleteOptions{}); err != nil && !kerrors.IsNotFound(err) {\n\t\t\t\t\t\tlogrus.Warnf(\"Deleting template %v doesn't succeed. Continue loop\", k)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor k := range tvToDelete {\n\t\t\t\t\tif err := m.templateVersionClient.Delete(k, &metav1.DeleteOptions{}); err != nil && !kerrors.IsNotFound(err) {\n\t\t\t\t\t\tlogrus.Warnf(\"Deleting templateVersion %v doesn't succeed. Continue loop\", k)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}()\n\t\treturn nil\n\t}\n\n\t\/\/ always get a refresh catalog from etcd\n\tcatalog, err := m.catalogClient.Get(key, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trepoPath, commit, err := m.prepareRepoPath(*catalog)\n\tif err != nil {\n\t\tv3.CatalogConditionRefreshed.False(catalog)\n\t\tv3.CatalogConditionRefreshed.ReasonAndMessageFromError(catalog, err)\n\t\tm.catalogClient.Update(catalog)\n\t\treturn err\n\t}\n\n\tif commit == catalog.Status.Commit {\n\t\tlogrus.Debugf(\"Catalog %s is already up to date\", catalog.Name)\n\t\tif v3.CatalogConditionRefreshed.IsUnknown(catalog) {\n\t\t\tv3.CatalogConditionRefreshed.True(catalog)\n\t\t\tv3.CatalogConditionRefreshed.Reason(catalog, \"\")\n\t\t\tm.catalogClient.Update(catalog)\n\t\t}\n\t\treturn nil\n\t}\n\n\tlogrus.Infof(\"Updating catalog %s\", catalog.Name)\n\treturn m.traverseAndUpdate(repoPath, commit, catalog)\n}\n<commit_msg>check nil when deleting catalog<commit_after>package manager\n\nimport (\n\t\"github.com\/rancher\/types\/apis\/management.cattle.io\/v3\"\n\t\"github.com\/sirupsen\/logrus\"\n\tkerrors \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\nfunc (m *Manager) Sync(key string, obj *v3.Catalog) error {\n\tif obj == nil {\n\t\ttemplates, err := m.getTemplateMap(key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttvToDelete := map[string]struct{}{}\n\t\tfor _, t := range templates {\n\t\t\ttvs, err := m.getTemplateVersion(t.Name)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor k := range tvs {\n\t\t\t\ttvToDelete[k] = struct{}{}\n\t\t\t}\n\t\t}\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tfor k := range templates {\n\t\t\t\t\tif err := m.templateClient.Delete(k, &metav1.DeleteOptions{}); err != nil && !kerrors.IsNotFound(err) {\n\t\t\t\t\t\tlogrus.Warnf(\"Deleting template %v doesn't succeed. Continue loop\", k)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor k := range tvToDelete {\n\t\t\t\t\tif err := m.templateVersionClient.Delete(k, &metav1.DeleteOptions{}); err != nil && !kerrors.IsNotFound(err) {\n\t\t\t\t\t\tlogrus.Warnf(\"Deleting templateVersion %v doesn't succeed. Continue loop\", k)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}()\n\t\treturn nil\n\t}\n\n\t\/\/ always get a refresh catalog from etcd\n\tcatalog, err := m.catalogClient.Get(key, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trepoPath, commit, err := m.prepareRepoPath(*catalog)\n\tif err != nil {\n\t\tv3.CatalogConditionRefreshed.False(catalog)\n\t\tv3.CatalogConditionRefreshed.ReasonAndMessageFromError(catalog, err)\n\t\tm.catalogClient.Update(catalog)\n\t\treturn err\n\t}\n\n\tif commit == catalog.Status.Commit {\n\t\tlogrus.Debugf(\"Catalog %s is already up to date\", catalog.Name)\n\t\tif v3.CatalogConditionRefreshed.IsUnknown(catalog) {\n\t\t\tv3.CatalogConditionRefreshed.True(catalog)\n\t\t\tv3.CatalogConditionRefreshed.Reason(catalog, \"\")\n\t\t\tm.catalogClient.Update(catalog)\n\t\t}\n\t\treturn nil\n\t}\n\n\tlogrus.Infof(\"Updating catalog %s\", catalog.Name)\n\treturn m.traverseAndUpdate(repoPath, commit, catalog)\n}\n<|endoftext|>"}
{"text":"<commit_before>package fsutil\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto\/sha512\"\n\t\"fmt\"\n\t\"io\"\n)\n\nfunc newChecksumReader(reader io.Reader) *ChecksumReader {\n\tr := new(ChecksumReader)\n\tr.checksummer = sha512.New()\n\tif _, ok := reader.(io.ByteReader); !ok {\n\t\tr.reader = bufio.NewReader(reader)\n\t} else {\n\t\tr.reader = reader\n\t}\n\treturn r\n}\n\nfunc (r *ChecksumReader) read(p []byte) (int, error) {\n\tnRead, err := r.reader.Read(p)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t_, err = r.checksummer.Write(p[:nRead])\n\treturn nRead, err\n}\n\nfunc (r *ChecksumReader) readByte() (byte, error) {\n\tbuf := make([]byte, 1)\n\t_, err := r.read(buf)\n\treturn buf[0], err\n}\n\nfunc (r *ChecksumReader) verifyChecksum() error {\n\tbuf := make([]byte, r.checksummer.Size())\n\tnRead, err := r.reader.Read(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif nRead != r.checksummer.Size() {\n\t\treturn fmt.Errorf(\n\t\t\t\"ChecksumReader.Checksum(): expected: %d got: %d bytes\",\n\t\t\tr.checksummer.Size(), nRead)\n\t}\n\tif !bytes.Equal(buf, r.checksummer.Sum(nil)) {\n\t\treturn ErrorChecksumMismatch\n\t}\n\treturn nil\n}\n\nfunc newChecksumWriter(writer io.Writer) *ChecksumWriter {\n\tw := new(ChecksumWriter)\n\tw.checksummer = sha512.New()\n\tw.writer = writer\n\treturn w\n}\n\nfunc (w *ChecksumWriter) write(p []byte) (int, error) {\n\tif _, err := w.checksummer.Write(p); err != nil {\n\t\treturn 0, err\n\t}\n\treturn w.writer.Write(p)\n}\n\nfunc (w *ChecksumWriter) writeChecksum() error {\n\t_, err := w.writer.Write(w.checksummer.Sum(nil))\n\treturn err\n}\n<commit_msg>Fix short read bug in lib\/fsutil.ChecksumReader.VerifyChecksum().<commit_after>package fsutil\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto\/sha512\"\n\t\"fmt\"\n\t\"io\"\n)\n\nfunc newChecksumReader(reader io.Reader) *ChecksumReader {\n\tr := new(ChecksumReader)\n\tr.checksummer = sha512.New()\n\tif _, ok := reader.(io.ByteReader); !ok {\n\t\tr.reader = bufio.NewReader(reader)\n\t} else {\n\t\tr.reader = reader\n\t}\n\treturn r\n}\n\nfunc (r *ChecksumReader) read(p []byte) (int, error) {\n\tnRead, err := r.reader.Read(p)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t_, err = r.checksummer.Write(p[:nRead])\n\treturn nRead, err\n}\n\nfunc (r *ChecksumReader) readByte() (byte, error) {\n\tbuf := make([]byte, 1)\n\t_, err := r.read(buf)\n\treturn buf[0], err\n}\n\nfunc (r *ChecksumReader) verifyChecksum() error {\n\tbuf := make([]byte, r.checksummer.Size())\n\tnRead, err := io.ReadAtLeast(r.reader, buf, len(buf))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif nRead != r.checksummer.Size() {\n\t\treturn fmt.Errorf(\n\t\t\t\"ChecksumReader.Checksum(): expected: %d got: %d bytes\",\n\t\t\tr.checksummer.Size(), nRead)\n\t}\n\tif !bytes.Equal(buf, r.checksummer.Sum(nil)) {\n\t\treturn ErrorChecksumMismatch\n\t}\n\treturn nil\n}\n\nfunc newChecksumWriter(writer io.Writer) *ChecksumWriter {\n\tw := new(ChecksumWriter)\n\tw.checksummer = sha512.New()\n\tw.writer = writer\n\treturn w\n}\n\nfunc (w *ChecksumWriter) write(p []byte) (int, error) {\n\tif _, err := w.checksummer.Write(p); err != nil {\n\t\treturn 0, err\n\t}\n\treturn w.writer.Write(p)\n}\n\nfunc (w *ChecksumWriter) writeChecksum() error {\n\t_, err := w.writer.Write(w.checksummer.Sum(nil))\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ (c) 2019-2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage timestampvm\n\nimport (\n\t\"errors\"\n\t\"net\/http\"\n\n\t\"github.com\/ava-labs\/gecko\/ids\"\n\n\t\"github.com\/ava-labs\/gecko\/utils\/formatting\"\n)\n\nvar (\n\terrDBError     = errors.New(\"error getting data from database\")\n\terrBadData     = errors.New(\"data must be base 58 repr. of 32 bytes\")\n\terrNoSuchBlock = errors.New(\"couldn't get block from database. Does it exist?\")\n)\n\n\/\/ Service is the API service for this VM\ntype Service struct{ vm *VM }\n\n\/\/ ProposeBlockArgs are the arguments to function ProposeValue\ntype ProposeBlockArgs struct {\n\t\/\/ Data in the block. Must be base 58 encoding of 32 bytes.\n\tData string `json:\"data\"`\n}\n\n\/\/ ProposeBlockReply is the reply from function ProposeBlock\ntype ProposeBlockReply struct{ Success bool }\n\n\/\/ ProposeBlock is an API method to propose a new block whose data is [args].Data.\n\/\/ [args].Data must be a string repr. of a 32 byte array\nfunc (s *Service) ProposeBlock(_ *http.Request, args *ProposeBlockArgs, reply *ProposeBlockReply) error {\n\tbyteFormatter := formatting.CB58{}\n\tif err := byteFormatter.FromString(args.Data); err != nil {\n\t\treturn errBadData\n\t}\n\tdataSlice := byteFormatter.Bytes\n\tif len(dataSlice) != dataLen {\n\t\treturn errBadData\n\t}\n\tvar data [dataLen]byte             \/\/ The data as an array of bytes\n\tcopy(data[:], dataSlice[:dataLen]) \/\/ Copy the bytes in dataSlice to data\n\ts.vm.proposeBlock(data)\n\treply.Success = true\n\treturn nil\n}\n\n\/\/ APIBlock is the API representation of a block\ntype APIBlock struct {\n\tTimestamp int64  `json:\"timestamp\"` \/\/ Timestamp of most recent block\n\tData      string `json:\"data\"`      \/\/ Data in the most recent block. Base 58 repr. of 5 bytes.\n\tID        string `json:\"id\"`        \/\/ String repr. of ID of the most recent block\n\tParentID  string `json:\"parentID\"`  \/\/ String repr. of ID of the most recent block's parent\n}\n\n\/\/ GetBlockArgs are the arguments to GetBlock\ntype GetBlockArgs struct {\n\t\/\/ ID of the block we're getting.\n\t\/\/ If left blank, gets the latest block\n\tID string\n}\n\n\/\/ GetBlockReply is the reply from GetBlock\ntype GetBlockReply struct {\n\tAPIBlock\n}\n\n\/\/ GetBlock gets the block whose ID is [args.ID]\n\/\/ If [args.ID] is empty, get the latest block\nfunc (s *Service) GetBlock(_ *http.Request, args *GetBlockArgs, reply *GetBlockReply) error {\n\tvar ID ids.ID\n\tvar err error\n\tif args.ID == \"\" {\n\t\tID = s.vm.LastAccepted()\n\t} else {\n\t\tID, err = ids.FromString(args.ID)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"problem parsing ID\")\n\t\t}\n\t}\n\n\tblockInterface, err := s.vm.GetBlock(ID)\n\tif err != nil {\n\t\treturn errDatabase\n\t}\n\n\tblock, ok := blockInterface.(*Block)\n\tif !ok {\n\t\treturn errBadData\n\t}\n\n\treply.APIBlock.ID = block.ID().String()\n\treply.APIBlock.Timestamp = block.Timestamp\n\treply.APIBlock.ParentID = block.ParentID().String()\n\tbyteFormatter := formatting.CB58{Bytes: block.Data[:]}\n\treply.Data = byteFormatter.String()\n\n\treturn nil\n}\n<commit_msg>getBlock returns timestamp with quotes<commit_after>\/\/ (c) 2019-2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage timestampvm\n\nimport (\n\t\"errors\"\n\t\"net\/http\"\n\n\t\"github.com\/ava-labs\/gecko\/ids\"\n\t\"github.com\/ava-labs\/gecko\/utils\/json\"\n\n\t\"github.com\/ava-labs\/gecko\/utils\/formatting\"\n)\n\nvar (\n\terrDBError     = errors.New(\"error getting data from database\")\n\terrBadData     = errors.New(\"data must be base 58 repr. of 32 bytes\")\n\terrNoSuchBlock = errors.New(\"couldn't get block from database. Does it exist?\")\n)\n\n\/\/ Service is the API service for this VM\ntype Service struct{ vm *VM }\n\n\/\/ ProposeBlockArgs are the arguments to function ProposeValue\ntype ProposeBlockArgs struct {\n\t\/\/ Data in the block. Must be base 58 encoding of 32 bytes.\n\tData string `json:\"data\"`\n}\n\n\/\/ ProposeBlockReply is the reply from function ProposeBlock\ntype ProposeBlockReply struct{ Success bool }\n\n\/\/ ProposeBlock is an API method to propose a new block whose data is [args].Data.\n\/\/ [args].Data must be a string repr. of a 32 byte array\nfunc (s *Service) ProposeBlock(_ *http.Request, args *ProposeBlockArgs, reply *ProposeBlockReply) error {\n\tbyteFormatter := formatting.CB58{}\n\tif err := byteFormatter.FromString(args.Data); err != nil {\n\t\treturn errBadData\n\t}\n\tdataSlice := byteFormatter.Bytes\n\tif len(dataSlice) != dataLen {\n\t\treturn errBadData\n\t}\n\tvar data [dataLen]byte             \/\/ The data as an array of bytes\n\tcopy(data[:], dataSlice[:dataLen]) \/\/ Copy the bytes in dataSlice to data\n\ts.vm.proposeBlock(data)\n\treply.Success = true\n\treturn nil\n}\n\n\/\/ APIBlock is the API representation of a block\ntype APIBlock struct {\n\tTimestamp json.Uint64 `json:\"timestamp\"` \/\/ Timestamp of most recent block\n\tData      string      `json:\"data\"`      \/\/ Data in the most recent block. Base 58 repr. of 5 bytes.\n\tID        string      `json:\"id\"`        \/\/ String repr. of ID of the most recent block\n\tParentID  string      `json:\"parentID\"`  \/\/ String repr. of ID of the most recent block's parent\n}\n\n\/\/ GetBlockArgs are the arguments to GetBlock\ntype GetBlockArgs struct {\n\t\/\/ ID of the block we're getting.\n\t\/\/ If left blank, gets the latest block\n\tID string\n}\n\n\/\/ GetBlockReply is the reply from GetBlock\ntype GetBlockReply struct {\n\tAPIBlock\n}\n\n\/\/ GetBlock gets the block whose ID is [args.ID]\n\/\/ If [args.ID] is empty, get the latest block\nfunc (s *Service) GetBlock(_ *http.Request, args *GetBlockArgs, reply *GetBlockReply) error {\n\tvar ID ids.ID\n\tvar err error\n\tif args.ID == \"\" {\n\t\tID = s.vm.LastAccepted()\n\t} else {\n\t\tID, err = ids.FromString(args.ID)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"problem parsing ID\")\n\t\t}\n\t}\n\n\tblockInterface, err := s.vm.GetBlock(ID)\n\tif err != nil {\n\t\treturn errDatabase\n\t}\n\n\tblock, ok := blockInterface.(*Block)\n\tif !ok {\n\t\treturn errBadData\n\t}\n\n\treply.APIBlock.ID = block.ID().String()\n\treply.APIBlock.Timestamp = json.Uint64(block.Timestamp)\n\treply.APIBlock.ParentID = block.ParentID().String()\n\tbyteFormatter := formatting.CB58{Bytes: block.Data[:]}\n\treply.Data = byteFormatter.String()\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package sdees\n\nimport (\n\t\"math\/rand\"\n\t\"os\"\n\t\"regexp\"\n\t\"time\"\n)\n\n\/\/ timeTrack from https:\/\/coderwall.com\/p\/cp5fya\/measuring-execution-time-in-go\nfunc timeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tlogger.Debug(\"%s took %s\", name, elapsed)\n}\n\n\/\/ RandStringBytesMaskImprSrc generates a random string using a alphabet and seed\n\/\/ from SO\nconst letterBytes = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\nconst (\n\tletterIdxBits = 6                    \/\/ 6 bits to represent a letter index\n\tletterIdxMask = 1<<letterIdxBits - 1 \/\/ All 1-bits, as many as letterIdxBits\n\tletterIdxMax  = 63 \/ letterIdxBits   \/\/ # of letter indices fitting in 63 bits\n)\n\nfunc RandStringBytesMaskImprSrc(n int, seed int64) string {\n\tsrc := rand.NewSource(seed)\n\tb := make([]byte, n)\n\t\/\/ A src.Int63() generates 63 random bits, enough for letterIdxMax characters!\n\tfor i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {\n\t\tif remain == 0 {\n\t\t\tcache, remain = src.Int63(), letterIdxMax\n\t\t}\n\t\tif idx := int(cache & letterIdxMask); idx < len(letterBytes) {\n\t\t\tb[i] = letterBytes[idx]\n\t\t\ti--\n\t\t}\n\t\tcache >>= letterIdxBits\n\t\tremain--\n\t}\n\n\treturn string(b)\n}\n\n\/\/ exists returns whether the given file or directory exists or not\n\/\/ from http:\/\/stackoverflow.com\/questions\/10510691\/how-to-check-whether-a-file-or-directory-denoted-by-a-path-exists-in-golang\nfunc exists(path string) bool {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ Shred writes random data to the file before erasing it\nfunc Shred(fileName string) error {\n\tf, err := os.OpenFile(fileName, os.O_RDWR|os.O_APPEND, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfileData, err := f.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\tb := make([]byte, fileData.Size())\n\t_, err = rand.Read(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = f.WriteAt(b, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tf.Close()\n\terr = os.Remove(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc GetWordsFromText(text string) []string {\n\twords := regexp.MustCompile(\"\\\\w+\")\n\treturn words.FindAllString(text, -1)\n}\n<commit_msg>Added GetRandomMD5Hash<commit_after>package sdees\n\nimport (\n\t\"math\/rand\"\n\t\"os\"\n\t\"regexp\"\n\t\"time\"\n)\n\n\/\/ timeTrack from https:\/\/coderwall.com\/p\/cp5fya\/measuring-execution-time-in-go\nfunc timeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tlogger.Debug(\"%s took %s\", name, elapsed)\n}\n\nfunc GetRandomMD5Hash() string {\n\thasher := md5.New()\n\thasher.Write([]byte(RandStringBytesMaskImprSrc(10, time.Now().UnixNano())))\n\treturn hex.EncodeToString(hasher.Sum(nil))[0:8]\n}\n\n\/\/ RandStringBytesMaskImprSrc generates a random string using a alphabet and seed\n\/\/ from SO\nconst letterBytes = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"\nconst (\n\tletterIdxBits = 6                    \/\/ 6 bits to represent a letter index\n\tletterIdxMask = 1<<letterIdxBits - 1 \/\/ All 1-bits, as many as letterIdxBits\n\tletterIdxMax  = 63 \/ letterIdxBits   \/\/ # of letter indices fitting in 63 bits\n)\n\nfunc RandStringBytesMaskImprSrc(n int, seed int64) string {\n\tsrc := rand.NewSource(seed)\n\tb := make([]byte, n)\n\t\/\/ A src.Int63() generates 63 random bits, enough for letterIdxMax characters!\n\tfor i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {\n\t\tif remain == 0 {\n\t\t\tcache, remain = src.Int63(), letterIdxMax\n\t\t}\n\t\tif idx := int(cache & letterIdxMask); idx < len(letterBytes) {\n\t\t\tb[i] = letterBytes[idx]\n\t\t\ti--\n\t\t}\n\t\tcache >>= letterIdxBits\n\t\tremain--\n\t}\n\n\treturn string(b)\n}\n\n\/\/ exists returns whether the given file or directory exists or not\n\/\/ from http:\/\/stackoverflow.com\/questions\/10510691\/how-to-check-whether-a-file-or-directory-denoted-by-a-path-exists-in-golang\nfunc exists(path string) bool {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ Shred writes random data to the file before erasing it\nfunc Shred(fileName string) error {\n\tf, err := os.OpenFile(fileName, os.O_RDWR|os.O_APPEND, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfileData, err := f.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\tb := make([]byte, fileData.Size())\n\t_, err = rand.Read(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = f.WriteAt(b, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tf.Close()\n\terr = os.Remove(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc GetWordsFromText(text string) []string {\n\twords := regexp.MustCompile(\"\\\\w+\")\n\treturn words.FindAllString(text, -1)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"time\"\n\n\t\"github.com\/Comcast\/webpa-common\/concurrent\"\n\t\"github.com\/Comcast\/webpa-common\/secure\"\n\t\"github.com\/Comcast\/webpa-common\/secure\/handler\"\n\t\"github.com\/Comcast\/webpa-common\/secure\/key\"\n\t\"github.com\/Comcast\/webpa-common\/server\"\n\t\"github.com\/Comcast\/webpa-common\/webhook\"\n\t\"github.com\/SermoDigital\/jose\/jwt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/justinas\/alice\"\n\t\"github.com\/spf13\/pflag\"\n\t\"github.com\/spf13\/viper\"\n)\n\nconst (\n\tapplicationName = \"caduceus\"\n\tDEFAULT_KEY_ID  = \"current\"\n)\n\n\/\/ getValidator returns validator for JWT tokens\nfunc getValidator(v *viper.Viper) (validator secure.Validator, err error) {\n\tdefault_validators := make(secure.Validators, 0, 0)\n\tvar jwtVals []JWTValidator\n\n\tv.UnmarshalKey(\"jwtValidators\", &jwtVals)\n\n\t\/\/ make sure there is at least one jwtValidator supplied\n\tif len(jwtVals) < 1 {\n\t\tvalidator = default_validators\n\t\treturn\n\t}\n\n\t\/\/ if a JWTKeys section was supplied, configure a JWS validator\n\t\/\/ and append it to the chain of validators\n\tvalidators := make(secure.Validators, 0, len(jwtVals))\n\n\tfor _, validatorDescriptor := range jwtVals {\n\t\tvar keyResolver key.Resolver\n\t\tkeyResolver, err = validatorDescriptor.Keys.NewResolver()\n\t\tif err != nil {\n\t\t\tvalidator = validators\n\t\t\treturn\n\t\t}\n\n\t\tvalidators = append(\n\t\t\tvalidators,\n\t\t\tsecure.JWSValidator{\n\t\t\t\tDefaultKeyId:  DEFAULT_KEY_ID,\n\t\t\t\tResolver:      keyResolver,\n\t\t\t\tJWTValidators: []*jwt.Validator{validatorDescriptor.Custom.New()},\n\t\t\t},\n\t\t)\n\t}\n\n\t\/\/ TODO: This should really be part of the unmarshalled validators somehow\n\tbasicAuth := v.GetStringSlice(\"authHeader\")\n\tfor _, authValue := range basicAuth {\n\t\tvalidators = append(\n\t\t\tvalidators,\n\t\t\tsecure.ExactMatchValidator(authValue),\n\t\t)\n\t}\n\n\tvalidator = validators\n\n\treturn\n}\n\n\/\/ caduceus is the driver function for Caduceus.  It performs everything main() would do,\n\/\/ except for obtaining the command-line arguments (which are passed to it).\nfunc caduceus(arguments []string) int {\n\ttotalTime := time.Now()\n\n\tvar (\n\t\tf = pflag.NewFlagSet(applicationName, pflag.ContinueOnError)\n\t\tv = viper.New()\n\n\t\tlogger, webPA, err = server.Initialize(applicationName, arguments, f, v)\n\t)\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to initialize Viper environment: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tlogger.Info(\"Using configuration file: %s\", v.ConfigFileUsed())\n\n\tcaduceusConfig := new(CaduceusConfig)\n\terr = v.Unmarshal(caduceusConfig)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to unmarshal configuration data into struct: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tworkerPool := WorkerPoolFactory{\n\t\tNumWorkers: caduceusConfig.NumWorkerThreads,\n\t\tQueueSize:  caduceusConfig.JobQueueSize,\n\t}.New()\n\n\tmainCaduceusProfilerFactory := ServerProfilerFactory{\n\t\tFrequency: caduceusConfig.ProfilerFrequency,\n\t\tDuration:  caduceusConfig.ProfilerDuration,\n\t\tQueueSize: caduceusConfig.ProfilerQueueSize,\n\t\tLogger:    logger,\n\t}\n\n\t\/\/ here we create a profiler specifically for our main server handler\n\tcaduceusHandlerProfiler, err := mainCaduceusProfilerFactory.New(\"main\")\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to profiler for main caduceus handler: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tchildCaduceusProfilerFactory := mainCaduceusProfilerFactory\n\tchildCaduceusProfilerFactory.Parent = caduceusHandlerProfiler\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig:       &tls.Config{InsecureSkipVerify: true},\n\t\tMaxIdleConnsPerHost:   caduceusConfig.SenderNumWorkersPerSender,\n\t\tResponseHeaderTimeout: 10 * time.Second, \/\/ TODO Make this configurable\n\t}\n\n\ttimeout := time.Duration(caduceusConfig.SenderClientTimeout) * time.Second\n\n\t\/\/ declare a new sender wrapper and pass it a profiler factory so that it can create\n\t\/\/ unique profilers on a per outboundSender basis\n\tcaduceusSenderWrapper, err := SenderWrapperFactory{\n\t\tNumWorkersPerSender: caduceusConfig.SenderNumWorkersPerSender,\n\t\tQueueSizePerSender:  caduceusConfig.SenderQueueSizePerSender,\n\t\tCutOffPeriod:        time.Duration(caduceusConfig.SenderCutOffPeriod) * time.Second,\n\t\tLinger:              time.Duration(caduceusConfig.SenderLinger) * time.Second,\n\t\tProfilerFactory:     childCaduceusProfilerFactory,\n\t\tLogger:              logger,\n\t\tClient:              &http.Client{Transport: tr, Timeout: timeout},\n\t}.New()\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to initialize new caduceus sender wrapper: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tserverWrapper := &ServerHandler{\n\t\tLogger: logger,\n\t\tcaduceusHandler: &CaduceusHandler{\n\t\t\thandlerProfiler: caduceusHandlerProfiler,\n\t\t\tsenderWrapper:   caduceusSenderWrapper,\n\t\t\tLogger:          logger,\n\t\t},\n\t\tdoJob: workerPool.Send,\n\t}\n\n\tprofileWrapper := &ProfileHandler{\n\t\tprofilerData: caduceusHandlerProfiler,\n\t\tLogger:       logger,\n\t}\n\n\tvalidator, err := getValidator(v)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Validator error: %v\\n\", err)\n\t\treturn 1\n\t}\n\n\tauthHandler := handler.AuthorizationHandler{\n\t\tHeaderName:          \"Authorization\",\n\t\tForbiddenStatusCode: 403,\n\t\tValidator:           validator,\n\t\tLogger:              logger,\n\t}\n\n\tcaduceusHandler := alice.New(authHandler.Decorate)\n\n\tmux := mux.NewRouter()\n\tmux.Handle(\"\/api\/v1\/notify\", caduceusHandler.Then(serverWrapper))\n\tmux.Handle(\"\/api\/v1\/profile\", caduceusHandler.Then(profileWrapper))\n\n\t\/\/ Support the old endpoint too.\n\tmux.Handle(\"\/api\/v2\/notify\/{deviceid}\/event\/{eventtype:.*}\", caduceusHandler.Then(serverWrapper))\n\n\twebhookFactory, err := webhook.NewFactory(v)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error creating new webhook factory: %s\\n\", err)\n\t\treturn 1\n\t}\n\twebhookRegistry, webhookHandler := webhookFactory.NewRegistryAndHandler()\n\twebhookFactory.SetExternalUpdate(caduceusSenderWrapper.Update)\n\n\t\/\/ register webhook end points for api\n\tmux.Handle(\"\/hook\", caduceusHandler.ThenFunc(webhookRegistry.UpdateRegistry))\n\tmux.Handle(\"\/hooks\", caduceusHandler.ThenFunc(webhookRegistry.GetRegistry))\n\n\tselfURL := &url.URL{\n\t\tScheme: \"https\",\n\t\tHost:   v.GetString(\"fqdn\") + v.GetString(\"primary.address\"),\n\t}\n\n\twebhookFactory.Initialize(mux, selfURL, webhookHandler, logger, nil)\n\n\tcaduceusHealth := &CaduceusHealth{}\n\tvar runnable concurrent.Runnable\n\n\tcaduceusHealth.Monitor, runnable = webPA.Prepare(logger, nil, mux)\n\tserverWrapper.caduceusHealth = caduceusHealth\n\n\twaitGroup, shutdown, err := concurrent.Execute(runnable)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to start device manager: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tlogger.Debug(\"calling webhookFactory.PrepareAndStart\")\n\tnow := time.Now()\n\twebhookFactory.PrepareAndStart()\n\tlogger.Debug(\"webhookFactory.PrepareAndStart done. elapsed time: %v\", time.Since(now))\n\n\t\/\/ Attempt to obtain the current listener list from current system without having to wait for listener reregistration.\n\tlogger.Debug(\"Attempting to obtain current listener list from %v\", v.GetString(\"start.apiPath\"))\n\tnow = time.Now()\n\tstartChan := make(chan webhook.Result, 1)\n\twebhookFactory.Start.GetCurrentSystemsHooks(startChan)\n\tvar webhookStartResults webhook.Result = <-startChan\n\tif webhookStartResults.Error != nil {\n\t\tlogger.Error(webhookStartResults.Error)\n\t} else {\n\t\t\/\/ todo: add message\n\t\twebhookFactory.SetList(webhook.NewList(webhookStartResults.Hooks))\n\t\tcaduceusSenderWrapper.Update(webhookStartResults.Hooks)\n\t}\n\tlogger.Debug(\"current listener retrieval, elapsed time: %v\", time.Since(now))\n\n\tlogger.Info(\"Caduceus is up and running! elapsed time: %v\", time.Since(totalTime))\n\n\tvar (\n\t\tsignals = make(chan os.Signal, 1)\n\t)\n\n\tsignal.Notify(signals)\n\t<-signals\n\tclose(shutdown)\n\twaitGroup.Wait()\n\n\t\/\/ shutdown the sender wrapper gently so that all queued messages get serviced\n\tcaduceusSenderWrapper.Shutdown(true)\n\n\treturn 0\n}\n\nfunc main() {\n\tos.Exit(caduceus(os.Args))\n}\n<commit_msg>Change the new api to be v3 vs v1.<commit_after>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"time\"\n\n\t\"github.com\/Comcast\/webpa-common\/concurrent\"\n\t\"github.com\/Comcast\/webpa-common\/secure\"\n\t\"github.com\/Comcast\/webpa-common\/secure\/handler\"\n\t\"github.com\/Comcast\/webpa-common\/secure\/key\"\n\t\"github.com\/Comcast\/webpa-common\/server\"\n\t\"github.com\/Comcast\/webpa-common\/webhook\"\n\t\"github.com\/SermoDigital\/jose\/jwt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/justinas\/alice\"\n\t\"github.com\/spf13\/pflag\"\n\t\"github.com\/spf13\/viper\"\n)\n\nconst (\n\tapplicationName = \"caduceus\"\n\tDEFAULT_KEY_ID  = \"current\"\n)\n\n\/\/ getValidator returns validator for JWT tokens\nfunc getValidator(v *viper.Viper) (validator secure.Validator, err error) {\n\tdefault_validators := make(secure.Validators, 0, 0)\n\tvar jwtVals []JWTValidator\n\n\tv.UnmarshalKey(\"jwtValidators\", &jwtVals)\n\n\t\/\/ make sure there is at least one jwtValidator supplied\n\tif len(jwtVals) < 1 {\n\t\tvalidator = default_validators\n\t\treturn\n\t}\n\n\t\/\/ if a JWTKeys section was supplied, configure a JWS validator\n\t\/\/ and append it to the chain of validators\n\tvalidators := make(secure.Validators, 0, len(jwtVals))\n\n\tfor _, validatorDescriptor := range jwtVals {\n\t\tvar keyResolver key.Resolver\n\t\tkeyResolver, err = validatorDescriptor.Keys.NewResolver()\n\t\tif err != nil {\n\t\t\tvalidator = validators\n\t\t\treturn\n\t\t}\n\n\t\tvalidators = append(\n\t\t\tvalidators,\n\t\t\tsecure.JWSValidator{\n\t\t\t\tDefaultKeyId:  DEFAULT_KEY_ID,\n\t\t\t\tResolver:      keyResolver,\n\t\t\t\tJWTValidators: []*jwt.Validator{validatorDescriptor.Custom.New()},\n\t\t\t},\n\t\t)\n\t}\n\n\t\/\/ TODO: This should really be part of the unmarshalled validators somehow\n\tbasicAuth := v.GetStringSlice(\"authHeader\")\n\tfor _, authValue := range basicAuth {\n\t\tvalidators = append(\n\t\t\tvalidators,\n\t\t\tsecure.ExactMatchValidator(authValue),\n\t\t)\n\t}\n\n\tvalidator = validators\n\n\treturn\n}\n\n\/\/ caduceus is the driver function for Caduceus.  It performs everything main() would do,\n\/\/ except for obtaining the command-line arguments (which are passed to it).\nfunc caduceus(arguments []string) int {\n\ttotalTime := time.Now()\n\n\tvar (\n\t\tf = pflag.NewFlagSet(applicationName, pflag.ContinueOnError)\n\t\tv = viper.New()\n\n\t\tlogger, webPA, err = server.Initialize(applicationName, arguments, f, v)\n\t)\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to initialize Viper environment: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tlogger.Info(\"Using configuration file: %s\", v.ConfigFileUsed())\n\n\tcaduceusConfig := new(CaduceusConfig)\n\terr = v.Unmarshal(caduceusConfig)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to unmarshal configuration data into struct: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tworkerPool := WorkerPoolFactory{\n\t\tNumWorkers: caduceusConfig.NumWorkerThreads,\n\t\tQueueSize:  caduceusConfig.JobQueueSize,\n\t}.New()\n\n\tmainCaduceusProfilerFactory := ServerProfilerFactory{\n\t\tFrequency: caduceusConfig.ProfilerFrequency,\n\t\tDuration:  caduceusConfig.ProfilerDuration,\n\t\tQueueSize: caduceusConfig.ProfilerQueueSize,\n\t\tLogger:    logger,\n\t}\n\n\t\/\/ here we create a profiler specifically for our main server handler\n\tcaduceusHandlerProfiler, err := mainCaduceusProfilerFactory.New(\"main\")\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to profiler for main caduceus handler: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tchildCaduceusProfilerFactory := mainCaduceusProfilerFactory\n\tchildCaduceusProfilerFactory.Parent = caduceusHandlerProfiler\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig:       &tls.Config{InsecureSkipVerify: true},\n\t\tMaxIdleConnsPerHost:   caduceusConfig.SenderNumWorkersPerSender,\n\t\tResponseHeaderTimeout: 10 * time.Second, \/\/ TODO Make this configurable\n\t}\n\n\ttimeout := time.Duration(caduceusConfig.SenderClientTimeout) * time.Second\n\n\t\/\/ declare a new sender wrapper and pass it a profiler factory so that it can create\n\t\/\/ unique profilers on a per outboundSender basis\n\tcaduceusSenderWrapper, err := SenderWrapperFactory{\n\t\tNumWorkersPerSender: caduceusConfig.SenderNumWorkersPerSender,\n\t\tQueueSizePerSender:  caduceusConfig.SenderQueueSizePerSender,\n\t\tCutOffPeriod:        time.Duration(caduceusConfig.SenderCutOffPeriod) * time.Second,\n\t\tLinger:              time.Duration(caduceusConfig.SenderLinger) * time.Second,\n\t\tProfilerFactory:     childCaduceusProfilerFactory,\n\t\tLogger:              logger,\n\t\tClient:              &http.Client{Transport: tr, Timeout: timeout},\n\t}.New()\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to initialize new caduceus sender wrapper: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tserverWrapper := &ServerHandler{\n\t\tLogger: logger,\n\t\tcaduceusHandler: &CaduceusHandler{\n\t\t\thandlerProfiler: caduceusHandlerProfiler,\n\t\t\tsenderWrapper:   caduceusSenderWrapper,\n\t\t\tLogger:          logger,\n\t\t},\n\t\tdoJob: workerPool.Send,\n\t}\n\n\tprofileWrapper := &ProfileHandler{\n\t\tprofilerData: caduceusHandlerProfiler,\n\t\tLogger:       logger,\n\t}\n\n\tvalidator, err := getValidator(v)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Validator error: %v\\n\", err)\n\t\treturn 1\n\t}\n\n\tauthHandler := handler.AuthorizationHandler{\n\t\tHeaderName:          \"Authorization\",\n\t\tForbiddenStatusCode: 403,\n\t\tValidator:           validator,\n\t\tLogger:              logger,\n\t}\n\n\tcaduceusHandler := alice.New(authHandler.Decorate)\n\n\tmux := mux.NewRouter()\n\tmux.Handle(\"\/api\/v3\/notify\", caduceusHandler.Then(serverWrapper))\n\tmux.Handle(\"\/api\/v3\/profile\", caduceusHandler.Then(profileWrapper))\n\n\t\/\/ Support the old endpoint too.\n\tmux.Handle(\"\/api\/v2\/notify\/{deviceid}\/event\/{eventtype:.*}\", caduceusHandler.Then(serverWrapper))\n\n\twebhookFactory, err := webhook.NewFactory(v)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error creating new webhook factory: %s\\n\", err)\n\t\treturn 1\n\t}\n\twebhookRegistry, webhookHandler := webhookFactory.NewRegistryAndHandler()\n\twebhookFactory.SetExternalUpdate(caduceusSenderWrapper.Update)\n\n\t\/\/ register webhook end points for api\n\tmux.Handle(\"\/hook\", caduceusHandler.ThenFunc(webhookRegistry.UpdateRegistry))\n\tmux.Handle(\"\/hooks\", caduceusHandler.ThenFunc(webhookRegistry.GetRegistry))\n\n\tselfURL := &url.URL{\n\t\tScheme: \"https\",\n\t\tHost:   v.GetString(\"fqdn\") + v.GetString(\"primary.address\"),\n\t}\n\n\twebhookFactory.Initialize(mux, selfURL, webhookHandler, logger, nil)\n\n\tcaduceusHealth := &CaduceusHealth{}\n\tvar runnable concurrent.Runnable\n\n\tcaduceusHealth.Monitor, runnable = webPA.Prepare(logger, nil, mux)\n\tserverWrapper.caduceusHealth = caduceusHealth\n\n\twaitGroup, shutdown, err := concurrent.Execute(runnable)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to start device manager: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tlogger.Debug(\"calling webhookFactory.PrepareAndStart\")\n\tnow := time.Now()\n\twebhookFactory.PrepareAndStart()\n\tlogger.Debug(\"webhookFactory.PrepareAndStart done. elapsed time: %v\", time.Since(now))\n\n\t\/\/ Attempt to obtain the current listener list from current system without having to wait for listener reregistration.\n\tlogger.Debug(\"Attempting to obtain current listener list from %v\", v.GetString(\"start.apiPath\"))\n\tnow = time.Now()\n\tstartChan := make(chan webhook.Result, 1)\n\twebhookFactory.Start.GetCurrentSystemsHooks(startChan)\n\tvar webhookStartResults webhook.Result = <-startChan\n\tif webhookStartResults.Error != nil {\n\t\tlogger.Error(webhookStartResults.Error)\n\t} else {\n\t\t\/\/ todo: add message\n\t\twebhookFactory.SetList(webhook.NewList(webhookStartResults.Hooks))\n\t\tcaduceusSenderWrapper.Update(webhookStartResults.Hooks)\n\t}\n\tlogger.Debug(\"current listener retrieval, elapsed time: %v\", time.Since(now))\n\n\tlogger.Info(\"Caduceus is up and running! elapsed time: %v\", time.Since(totalTime))\n\n\tvar (\n\t\tsignals = make(chan os.Signal, 1)\n\t)\n\n\tsignal.Notify(signals)\n\t<-signals\n\tclose(shutdown)\n\twaitGroup.Wait()\n\n\t\/\/ shutdown the sender wrapper gently so that all queued messages get serviced\n\tcaduceusSenderWrapper.Shutdown(true)\n\n\treturn 0\n}\n\nfunc main() {\n\tos.Exit(caduceus(os.Args))\n}\n<|endoftext|>"}
{"text":"<commit_before>package stick\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestF(t *testing.T) {\n\terr := F(\"foo %d\", 42)\n\n\tstr := err.Error()\n\tassert.Equal(t, `foo 42`, str)\n\n\tstr = fmt.Sprintf(\"%s\", err)\n\tassert.Equal(t, `foo 42`, str)\n\n\tstr = fmt.Sprintf(\"%v\", err)\n\tassert.Equal(t, `foo 42`, str)\n\n\tstr = fmt.Sprintf(\"%+v\", err)\n\tassert.Equal(t, []string{\n\t\t\"foo 42\",\n\t\t\"github.com\/256dpi\/fire\/stick.F\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.TestF\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error_test.go:LN\",\n\t\t\"testing.tRunner\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/testing\/testing.go:LN\",\n\t\t\"runtime.goexit\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/runtime\/asm_amd64.s:LN\",\n\t}, splitTrace(str))\n}\n\nfunc TestWF(t *testing.T) {\n\terr := F(\"foo\")\n\terr = WF(err, \"bar %d\", 42)\n\n\tstr := err.Error()\n\tassert.Equal(t, `bar 42: foo`, str)\n\n\tstr = fmt.Sprintf(\"%s\", err)\n\tassert.Equal(t, `bar 42: foo`, str)\n\n\tstr = fmt.Sprintf(\"%v\", err)\n\tassert.Equal(t, `bar 42: foo`, str)\n\n\tstr = fmt.Sprintf(\"%+v\", err)\n\tassert.Equal(t, []string{\n\t\t\"foo\",\n\t\t\"github.com\/256dpi\/fire\/stick.F\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.TestWF\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error_test.go:LN\",\n\t\t\"testing.tRunner\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/testing\/testing.go:LN\",\n\t\t\"runtime.goexit\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/runtime\/asm_amd64.s:LN\",\n\t\t\"bar 42\",\n\t\t\"github.com\/256dpi\/fire\/stick.WF\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.TestWF\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error_test.go:LN\",\n\t\t\"testing.tRunner\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/testing\/testing.go:LN\",\n\t\t\"runtime.goexit\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/runtime\/asm_amd64.s:LN\",\n\t}, splitTrace(str))\n}\n\nfunc TestE(t *testing.T) {\n\terr := E(\"foo\")\n\tassert.True(t, IsSafe(err))\n\n\tstr := err.Error()\n\tassert.Equal(t, `foo`, str)\n\n\tstr = fmt.Sprintf(\"%s\", err)\n\tassert.Equal(t, `foo`, str)\n\n\tstr = fmt.Sprintf(\"%v\", err)\n\tassert.Equal(t, `foo`, str)\n\n\tstr = fmt.Sprintf(\"%+v\", err)\n\tassert.Equal(t, []string{\n\t\t\"foo\",\n\t\t\"github.com\/256dpi\/fire\/stick.F\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.E\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.TestE\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error_test.go:LN\",\n\t\t\"testing.tRunner\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/testing\/testing.go:LN\",\n\t\t\"runtime.goexit\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/runtime\/asm_amd64.s:LN\",\n\t}, splitTrace(str))\n\n\t\/* wrapped *\/\n\n\terr = WF(err, \"bar\")\n\tassert.True(t, IsSafe(err))\n\n\tstr = err.Error()\n\tassert.Equal(t, `bar: foo`, str)\n\n\tstr = fmt.Sprintf(\"%s\", err)\n\tassert.Equal(t, `bar: foo`, str)\n\n\tstr = fmt.Sprintf(\"%v\", err)\n\tassert.Equal(t, `bar: foo`, str)\n\n\tstr = fmt.Sprintf(\"%+v\", err)\n\tassert.Equal(t, []string{\n\t\t\"foo\",\n\t\t\"github.com\/256dpi\/fire\/stick.F\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.E\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.TestE\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error_test.go:LN\",\n\t\t\"testing.tRunner\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/testing\/testing.go:LN\",\n\t\t\"runtime.goexit\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/runtime\/asm_amd64.s:LN\",\n\t\t\"bar\",\n\t\t\"github.com\/256dpi\/fire\/stick.WF\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.TestE\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/error_test.go:LN\",\n\t\t\"testing.tRunner\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/testing\/testing.go:LN\",\n\t\t\"runtime.goexit\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/runtime\/asm_amd64.s:LN\",\n\t}, splitTrace(str))\n}\n\nfunc TestSafeError(t *testing.T) {\n\terr1 := F(\"foo\")\n\tassert.False(t, IsSafe(err1))\n\tassert.Equal(t, \"foo\", err1.Error())\n\tassert.Nil(t, AsSafe(err1))\n\n\terr2 := Safe(err1)\n\tassert.True(t, IsSafe(err2))\n\tassert.Equal(t, \"foo\", err2.Error())\n\tassert.Equal(t, err2, AsSafe(err2))\n\n\terr3 := WF(err2, \"bar\")\n\tassert.True(t, IsSafe(err3))\n\tassert.Equal(t, \"bar: foo\", err3.Error())\n\tassert.Equal(t, err2, AsSafe(err3))\n}\n\nfunc splitTrace(str string) []string {\n\tstr = strings.ReplaceAll(str, \"\\t\", \"  \")\n\tstr = regexp.MustCompile(\":\\\\d+\").ReplaceAllString(str, \":LN\")\n\treturn strings.Split(str, \"\\n\")\n}\n<commit_msg>fix test<commit_after>package stick\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestF(t *testing.T) {\n\terr := F(\"foo %d\", 42)\n\n\tstr := err.Error()\n\tassert.Equal(t, `foo 42`, str)\n\n\tstr = fmt.Sprintf(\"%s\", err)\n\tassert.Equal(t, `foo 42`, str)\n\n\tstr = fmt.Sprintf(\"%v\", err)\n\tassert.Equal(t, `foo 42`, str)\n\n\tstr = fmt.Sprintf(\"%+v\", err)\n\tassert.Equal(t, []string{\n\t\t\"foo 42\",\n\t\t\"github.com\/256dpi\/fire\/stick.F\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.TestF\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors_test.go:LN\",\n\t\t\"testing.tRunner\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/testing\/testing.go:LN\",\n\t\t\"runtime.goexit\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/runtime\/asm_amd64.s:LN\",\n\t}, splitTrace(str))\n}\n\nfunc TestWF(t *testing.T) {\n\terr := F(\"foo\")\n\terr = WF(err, \"bar %d\", 42)\n\n\tstr := err.Error()\n\tassert.Equal(t, `bar 42: foo`, str)\n\n\tstr = fmt.Sprintf(\"%s\", err)\n\tassert.Equal(t, `bar 42: foo`, str)\n\n\tstr = fmt.Sprintf(\"%v\", err)\n\tassert.Equal(t, `bar 42: foo`, str)\n\n\tstr = fmt.Sprintf(\"%+v\", err)\n\tassert.Equal(t, []string{\n\t\t\"foo\",\n\t\t\"github.com\/256dpi\/fire\/stick.F\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.TestWF\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors_test.go:LN\",\n\t\t\"testing.tRunner\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/testing\/testing.go:LN\",\n\t\t\"runtime.goexit\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/runtime\/asm_amd64.s:LN\",\n\t\t\"bar 42\",\n\t\t\"github.com\/256dpi\/fire\/stick.WF\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.TestWF\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors_test.go:LN\",\n\t\t\"testing.tRunner\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/testing\/testing.go:LN\",\n\t\t\"runtime.goexit\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/runtime\/asm_amd64.s:LN\",\n\t}, splitTrace(str))\n}\n\nfunc TestE(t *testing.T) {\n\terr := E(\"foo\")\n\tassert.True(t, IsSafe(err))\n\n\tstr := err.Error()\n\tassert.Equal(t, `foo`, str)\n\n\tstr = fmt.Sprintf(\"%s\", err)\n\tassert.Equal(t, `foo`, str)\n\n\tstr = fmt.Sprintf(\"%v\", err)\n\tassert.Equal(t, `foo`, str)\n\n\tstr = fmt.Sprintf(\"%+v\", err)\n\tassert.Equal(t, []string{\n\t\t\"foo\",\n\t\t\"github.com\/256dpi\/fire\/stick.F\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.E\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.TestE\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors_test.go:LN\",\n\t\t\"testing.tRunner\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/testing\/testing.go:LN\",\n\t\t\"runtime.goexit\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/runtime\/asm_amd64.s:LN\",\n\t}, splitTrace(str))\n\n\t\/* wrapped *\/\n\n\terr = WF(err, \"bar\")\n\tassert.True(t, IsSafe(err))\n\n\tstr = err.Error()\n\tassert.Equal(t, `bar: foo`, str)\n\n\tstr = fmt.Sprintf(\"%s\", err)\n\tassert.Equal(t, `bar: foo`, str)\n\n\tstr = fmt.Sprintf(\"%v\", err)\n\tassert.Equal(t, `bar: foo`, str)\n\n\tstr = fmt.Sprintf(\"%+v\", err)\n\tassert.Equal(t, []string{\n\t\t\"foo\",\n\t\t\"github.com\/256dpi\/fire\/stick.F\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.E\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.TestE\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors_test.go:LN\",\n\t\t\"testing.tRunner\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/testing\/testing.go:LN\",\n\t\t\"runtime.goexit\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/runtime\/asm_amd64.s:LN\",\n\t\t\"bar\",\n\t\t\"github.com\/256dpi\/fire\/stick.WF\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors.go:LN\",\n\t\t\"github.com\/256dpi\/fire\/stick.TestE\",\n\t\t\"  \/Users\/256dpi\/Development\/GitHub\/256dpi\/fire\/stick\/errors_test.go:LN\",\n\t\t\"testing.tRunner\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/testing\/testing.go:LN\",\n\t\t\"runtime.goexit\",\n\t\t\"  \/usr\/local\/Cellar\/go\/1.14.1\/libexec\/src\/runtime\/asm_amd64.s:LN\",\n\t}, splitTrace(str))\n}\n\nfunc TestSafeError(t *testing.T) {\n\terr1 := F(\"foo\")\n\tassert.False(t, IsSafe(err1))\n\tassert.Equal(t, \"foo\", err1.Error())\n\tassert.Nil(t, AsSafe(err1))\n\n\terr2 := Safe(err1)\n\tassert.True(t, IsSafe(err2))\n\tassert.Equal(t, \"foo\", err2.Error())\n\tassert.Equal(t, err2, AsSafe(err2))\n\n\terr3 := WF(err2, \"bar\")\n\tassert.True(t, IsSafe(err3))\n\tassert.Equal(t, \"bar: foo\", err3.Error())\n\tassert.Equal(t, err2, AsSafe(err3))\n}\n\nfunc splitTrace(str string) []string {\n\tstr = strings.ReplaceAll(str, \"\\t\", \"  \")\n\tstr = regexp.MustCompile(\":\\\\d+\").ReplaceAllString(str, \":LN\")\n\treturn strings.Split(str, \"\\n\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2021 Gravitational, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage events\n\nimport (\n\t\"github.com\/gravitational\/teleport\/api\/types\/events\"\n\t\"github.com\/gravitational\/teleport\/lib\/utils\"\n\t\"github.com\/gravitational\/trace\"\n\n\t\"encoding\/json\"\n)\n\n\/\/ FromEventFields converts from the typed dynamic representation\n\/\/ to the new typed interface-style representation.\n\/\/\n\/\/ This is mainly used to convert from the backend format used by\n\/\/ our various event backends.\nfunc FromEventFields(fields EventFields) (AuditEvent, error) {\n\tdata, err := json.Marshal(fields)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\teventType := fields.GetString(EventType)\n\n\tswitch eventType {\n\tcase SessionPrintEvent:\n\t\tvar e events.SessionPrint\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionStartEvent:\n\t\tvar e events.SessionStart\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionEndEvent:\n\t\tvar e events.SessionEnd\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionUploadEvent:\n\t\tvar e events.SessionUpload\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionJoinEvent:\n\t\tvar e events.SessionJoin\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionLeaveEvent:\n\t\tvar e events.SessionLeave\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionDataEvent:\n\t\tvar e events.SessionData\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase ClientDisconnectEvent:\n\t\tvar e events.ClientDisconnect\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase UserLoginEvent:\n\t\tvar e events.UserLogin\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase UserDeleteEvent:\n\t\tvar e events.UserDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase UserCreateEvent:\n\t\tvar e events.UserCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase UserUpdatedEvent:\n\t\t\/\/ note: user.update is a custom code applied on top of the same data as the user.create event\n\t\t\/\/       and they are thus functionally identical. There exists no direct gRPC version of user.update.\n\t\tvar e events.UserCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase UserPasswordChangeEvent:\n\t\tvar e events.UserPasswordChange\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase AccessRequestCreateEvent:\n\t\tvar e events.AccessRequestCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase AccessRequestUpdateEvent:\n\t\tvar e events.AccessRequestCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase BillingCardCreateEvent:\n\t\tvar e events.BillingCardCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase BillingCardUpdateEvent:\n\t\tvar e events.BillingCardCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase BillingCardDeleteEvent:\n\t\tvar e events.BillingCardDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase BillingInformationUpdateEvent:\n\t\tvar e events.BillingInformationUpdate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase ResetPasswordTokenCreateEvent:\n\t\tvar e events.ResetPasswordTokenCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase ExecEvent:\n\t\tvar e events.Exec\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SubsystemEvent:\n\t\tvar e events.Subsystem\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase X11ForwardEvent:\n\t\tvar e events.X11Forward\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase PortForwardEvent:\n\t\tvar e events.PortForward\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase AuthAttemptEvent:\n\t\tvar e events.AuthAttempt\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SCPEvent:\n\t\tvar e events.SCP\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase ResizeEvent:\n\t\tvar e events.Resize\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionCommandEvent:\n\t\tvar e events.SessionCommand\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionDiskEvent:\n\t\tvar e events.SessionDisk\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionNetworkEvent:\n\t\tvar e events.SessionNetwork\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase RoleCreatedEvent:\n\t\tvar e events.RoleCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase RoleDeletedEvent:\n\t\tvar e events.RoleDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase TrustedClusterCreateEvent:\n\t\tvar e events.TrustedClusterCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase TrustedClusterDeleteEvent:\n\t\tvar e events.TrustedClusterDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase TrustedClusterTokenCreateEvent:\n\t\tvar e events.TrustedClusterTokenCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase GithubConnectorCreatedEvent:\n\t\tvar e events.GithubConnectorCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase GithubConnectorDeletedEvent:\n\t\tvar e events.GithubConnectorDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase OIDCConnectorCreatedEvent:\n\t\tvar e events.OIDCConnectorCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase OIDCConnectorDeletedEvent:\n\t\tvar e events.OIDCConnectorDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SAMLConnectorCreatedEvent:\n\t\tvar e events.SAMLConnectorCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SAMLConnectorDeletedEvent:\n\t\tvar e events.SAMLConnectorDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionRejectedEvent:\n\t\tvar e events.SessionReject\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase AppSessionStartEvent:\n\t\tvar e events.AppSessionStart\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase AppSessionChunkEvent:\n\t\tvar e events.AppSessionChunk\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase AppSessionRequestEvent:\n\t\tvar e events.AppSessionRequest\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase DatabaseSessionStartEvent:\n\t\tvar e events.DatabaseSessionStart\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase DatabaseSessionEndEvent:\n\t\tvar e events.DatabaseSessionEnd\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase DatabaseSessionQueryEvent:\n\t\tvar e events.DatabaseSessionQuery\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase KubeRequestEvent:\n\t\tvar e events.KubeRequest\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase MFADeviceAddEvent:\n\t\tvar e events.MFADeviceAdd\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase MFADeviceDeleteEvent:\n\t\tvar e events.MFADeviceDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tdefault:\n\t\treturn nil, trace.BadParameter(\"unknown event type: %q\", eventType)\n\t}\n}\n\n\/\/ GetSessionID pulls the session ID from the events that have a\n\/\/ SessionMetadata. For other events an empty string is returned.\nfunc GetSessionID(event AuditEvent) string {\n\tvar sessionID string\n\n\tif g, ok := event.(SessionMetadataGetter); ok {\n\t\tsessionID = g.GetSessionID()\n\t}\n\n\treturn sessionID\n}\n\n\/\/ ToEventFields converts from the typed interface-style event representation\n\/\/ to the old dynamic map style representation in order to provide outer compatibility\n\/\/ with existing public API routes when the backend is updated with the typed events.\nfunc ToEventFields(event AuditEvent) (EventFields, error) {\n\tvar fields EventFields\n\tif err := utils.ObjectToStruct(event, &fields); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\treturn fields, nil\n}\n<commit_msg>Add event handler for access request review event (#6966)<commit_after>\/*\nCopyright 2021 Gravitational, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage events\n\nimport (\n\t\"github.com\/gravitational\/teleport\/api\/types\/events\"\n\t\"github.com\/gravitational\/teleport\/lib\/utils\"\n\t\"github.com\/gravitational\/trace\"\n\n\t\"encoding\/json\"\n)\n\n\/\/ FromEventFields converts from the typed dynamic representation\n\/\/ to the new typed interface-style representation.\n\/\/\n\/\/ This is mainly used to convert from the backend format used by\n\/\/ our various event backends.\nfunc FromEventFields(fields EventFields) (AuditEvent, error) {\n\tdata, err := json.Marshal(fields)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\teventType := fields.GetString(EventType)\n\n\tswitch eventType {\n\tcase SessionPrintEvent:\n\t\tvar e events.SessionPrint\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionStartEvent:\n\t\tvar e events.SessionStart\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionEndEvent:\n\t\tvar e events.SessionEnd\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionUploadEvent:\n\t\tvar e events.SessionUpload\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionJoinEvent:\n\t\tvar e events.SessionJoin\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionLeaveEvent:\n\t\tvar e events.SessionLeave\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionDataEvent:\n\t\tvar e events.SessionData\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase ClientDisconnectEvent:\n\t\tvar e events.ClientDisconnect\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase UserLoginEvent:\n\t\tvar e events.UserLogin\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase UserDeleteEvent:\n\t\tvar e events.UserDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase UserCreateEvent:\n\t\tvar e events.UserCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase UserUpdatedEvent:\n\t\t\/\/ note: user.update is a custom code applied on top of the same data as the user.create event\n\t\t\/\/       and they are thus functionally identical. There exists no direct gRPC version of user.update.\n\t\tvar e events.UserCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase UserPasswordChangeEvent:\n\t\tvar e events.UserPasswordChange\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase AccessRequestCreateEvent:\n\t\tvar e events.AccessRequestCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase AccessRequestReviewEvent:\n\t\t\/\/ note: access_request.review is a custom code applied on top of the same data as the access_request.create event\n\t\t\/\/       and they are thus functionally identical. There exists no direct gRPC version of access_request.review.\n\t\tvar e events.AccessRequestCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase AccessRequestUpdateEvent:\n\t\tvar e events.AccessRequestCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase BillingCardCreateEvent:\n\t\tvar e events.BillingCardCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase BillingCardUpdateEvent:\n\t\tvar e events.BillingCardCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase BillingCardDeleteEvent:\n\t\tvar e events.BillingCardDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase BillingInformationUpdateEvent:\n\t\tvar e events.BillingInformationUpdate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase ResetPasswordTokenCreateEvent:\n\t\tvar e events.ResetPasswordTokenCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase ExecEvent:\n\t\tvar e events.Exec\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SubsystemEvent:\n\t\tvar e events.Subsystem\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase X11ForwardEvent:\n\t\tvar e events.X11Forward\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase PortForwardEvent:\n\t\tvar e events.PortForward\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase AuthAttemptEvent:\n\t\tvar e events.AuthAttempt\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SCPEvent:\n\t\tvar e events.SCP\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase ResizeEvent:\n\t\tvar e events.Resize\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionCommandEvent:\n\t\tvar e events.SessionCommand\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionDiskEvent:\n\t\tvar e events.SessionDisk\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionNetworkEvent:\n\t\tvar e events.SessionNetwork\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase RoleCreatedEvent:\n\t\tvar e events.RoleCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase RoleDeletedEvent:\n\t\tvar e events.RoleDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase TrustedClusterCreateEvent:\n\t\tvar e events.TrustedClusterCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase TrustedClusterDeleteEvent:\n\t\tvar e events.TrustedClusterDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase TrustedClusterTokenCreateEvent:\n\t\tvar e events.TrustedClusterTokenCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase GithubConnectorCreatedEvent:\n\t\tvar e events.GithubConnectorCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase GithubConnectorDeletedEvent:\n\t\tvar e events.GithubConnectorDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase OIDCConnectorCreatedEvent:\n\t\tvar e events.OIDCConnectorCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase OIDCConnectorDeletedEvent:\n\t\tvar e events.OIDCConnectorDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SAMLConnectorCreatedEvent:\n\t\tvar e events.SAMLConnectorCreate\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SAMLConnectorDeletedEvent:\n\t\tvar e events.SAMLConnectorDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase SessionRejectedEvent:\n\t\tvar e events.SessionReject\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase AppSessionStartEvent:\n\t\tvar e events.AppSessionStart\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase AppSessionChunkEvent:\n\t\tvar e events.AppSessionChunk\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase AppSessionRequestEvent:\n\t\tvar e events.AppSessionRequest\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase DatabaseSessionStartEvent:\n\t\tvar e events.DatabaseSessionStart\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase DatabaseSessionEndEvent:\n\t\tvar e events.DatabaseSessionEnd\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase DatabaseSessionQueryEvent:\n\t\tvar e events.DatabaseSessionQuery\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase KubeRequestEvent:\n\t\tvar e events.KubeRequest\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase MFADeviceAddEvent:\n\t\tvar e events.MFADeviceAdd\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tcase MFADeviceDeleteEvent:\n\t\tvar e events.MFADeviceDelete\n\t\tif err := utils.FastUnmarshal(data, &e); err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn &e, nil\n\tdefault:\n\t\treturn nil, trace.BadParameter(\"unknown event type: %q\", eventType)\n\t}\n}\n\n\/\/ GetSessionID pulls the session ID from the events that have a\n\/\/ SessionMetadata. For other events an empty string is returned.\nfunc GetSessionID(event AuditEvent) string {\n\tvar sessionID string\n\n\tif g, ok := event.(SessionMetadataGetter); ok {\n\t\tsessionID = g.GetSessionID()\n\t}\n\n\treturn sessionID\n}\n\n\/\/ ToEventFields converts from the typed interface-style event representation\n\/\/ to the old dynamic map style representation in order to provide outer compatibility\n\/\/ with existing public API routes when the backend is updated with the typed events.\nfunc ToEventFields(event AuditEvent) (EventFields, error) {\n\tvar fields EventFields\n\tif err := utils.ObjectToStruct(event, &fields); err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\treturn fields, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build testtools\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/github\/git-lfs\/httputil\"\n\t\"github.com\/github\/git-lfs\/progress\"\n\t\"github.com\/github\/git-lfs\/tools\"\n)\n\n\/\/ This test custom adapter just acts as a bridge for uploads\/downloads\n\/\/ in order to demonstrate & test the custom transfer adapter protocols\n\/\/ All we actually do is relay the requests back to the normal storage URLs\n\/\/ of our test server for simplicity, but this proves the principle\nfunc main() {\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\twriter := bufio.NewWriter(os.Stdout)\n\terrWriter := bufio.NewWriter(os.Stderr)\n\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tvar req request\n\t\tif err := json.Unmarshal([]byte(line), &req); err != nil {\n\t\t\twriteToStderr(fmt.Sprintf(\"Unable to parse request: %v\\n\", line), errWriter)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch req.Id {\n\t\tcase \"init\":\n\t\t\twriteToStderr(fmt.Sprintf(\"Initialised test custom adapter for %s\\n\", req.Operation), errWriter)\n\t\t\tresp := &initResponse{}\n\t\t\tsendResponse(resp, writer, errWriter)\n\t\tcase \"download\":\n\t\t\twriteToStderr(fmt.Sprintf(\"Received download request for %s\\n\", req.Oid), errWriter)\n\t\t\tperformDownload(req.Oid, req.Size, req.Action, writer, errWriter)\n\t\tcase \"upload\":\n\t\t\twriteToStderr(fmt.Sprintf(\"Received upload request for %s\\n\", req.Oid), errWriter)\n\t\t\tperformUpload(req.Oid, req.Size, req.Action, req.Path, writer, errWriter)\n\t\tcase \"terminate\":\n\t\t\twriteToStderr(\"Terminating test custom adapter gracefully.\\n\", errWriter)\n\t\t\tbreak\n\t\t}\n\t}\n\n}\n\nfunc writeToStderr(msg string, errWriter *bufio.Writer) {\n\tif !strings.HasSuffix(msg, \"\\n\") {\n\t\tmsg = msg + \"\\n\"\n\t}\n\terrWriter.WriteString(msg)\n\terrWriter.Flush()\n}\n\nfunc sendResponse(r interface{}, writer, errWriter *bufio.Writer) error {\n\tb, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ Line oriented JSON\n\tb = append(b, '\\n')\n\t_, err = writer.Write(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\twriter.Flush()\n\twriteToStderr(fmt.Sprintf(\"Sent message %v\", string(b)), errWriter)\n\treturn nil\n}\n\nfunc sendTransferError(oid string, code int, message string, writer, errWriter *bufio.Writer) {\n\tresp := &transferResponse{\"complete\", oid, \"\", &transferError{code, message}}\n\terr := sendResponse(resp, writer, errWriter)\n\tif err != nil {\n\t\twriteToStderr(fmt.Sprintf(\"Unable to send transfer error: %v\\n\", err), errWriter)\n\t}\n}\n\nfunc sendProgress(oid string, bytesSoFar int64, bytesSinceLast int, writer, errWriter *bufio.Writer) {\n\tresp := &progressResponse{\"progress\", oid, bytesSoFar, bytesSinceLast}\n\terr := sendResponse(resp, writer, errWriter)\n\tif err != nil {\n\t\twriteToStderr(fmt.Sprintf(\"Unable to send progress update: %v\\n\", err), errWriter)\n\t}\n}\n\nfunc performDownload(oid string, size int64, a *action, writer, errWriter *bufio.Writer) {\n\t\/\/ We just use the URLs we're given, so we're just a proxy for the direct method\n\t\/\/ but this is enough to test intermediate custom adapters\n\treq, err := httputil.NewHttpRequest(\"GET\", a.Href, a.Header)\n\tif err != nil {\n\t\tsendTransferError(oid, 2, err.Error(), writer, errWriter)\n\t\treturn\n\t}\n\tres, err := httputil.DoHttpRequest(req, true)\n\tif err != nil {\n\t\tsendTransferError(oid, res.StatusCode, err.Error(), writer, errWriter)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\n\tdlFile, err := ioutil.TempFile(\"\", \"lfscustomdl\")\n\tif err != nil {\n\t\tsendTransferError(oid, 3, err.Error(), writer, errWriter)\n\t\treturn\n\t}\n\tdefer dlFile.Close()\n\tdlfilename := dlFile.Name()\n\t\/\/ Wrap callback to give name context\n\tcb := func(totalSize int64, readSoFar int64, readSinceLast int) error {\n\t\tsendProgress(oid, readSoFar, readSinceLast, writer, errWriter)\n\t\treturn nil\n\t}\n\t_, err = tools.CopyWithCallback(dlFile, res.Body, res.ContentLength, cb)\n\tif err != nil {\n\t\tsendTransferError(oid, 4, fmt.Sprintf(\"cannot write data to tempfile %q: %v\", dlfilename, err), writer, errWriter)\n\t\tos.Remove(dlfilename)\n\t\treturn\n\t}\n\tif err := dlFile.Close(); err != nil {\n\t\tsendTransferError(oid, 5, fmt.Sprintf(\"can't close tempfile %q: %v\", dlfilename, err), writer, errWriter)\n\t\tos.Remove(dlfilename)\n\t\treturn\n\t}\n\n\t\/\/ completed\n\tcomplete := &transferResponse{\"complete\", oid, dlfilename, nil}\n\terr = sendResponse(complete, writer, errWriter)\n\tif err != nil {\n\t\twriteToStderr(fmt.Sprintf(\"Unable to send completion message: %v\\n\", err), errWriter)\n\t}\n}\n\nfunc performUpload(oid string, size int64, a *action, fromPath string, writer, errWriter *bufio.Writer) {\n\t\/\/ We just use the URLs we're given, so we're just a proxy for the direct method\n\t\/\/ but this is enough to test intermediate custom adapters\n\treq, err := httputil.NewHttpRequest(\"PUT\", a.Href, a.Header)\n\tif err != nil {\n\t\tsendTransferError(oid, 2, err.Error(), writer, errWriter)\n\t\treturn\n\t}\n\n\tif len(req.Header.Get(\"Content-Type\")) == 0 {\n\t\treq.Header.Set(\"Content-Type\", \"application\/octet-stream\")\n\t}\n\n\tif req.Header.Get(\"Transfer-Encoding\") == \"chunked\" {\n\t\treq.TransferEncoding = []string{\"chunked\"}\n\t} else {\n\t\treq.Header.Set(\"Content-Length\", strconv.FormatInt(size, 10))\n\t}\n\n\treq.ContentLength = size\n\n\tf, err := os.OpenFile(fromPath, os.O_RDONLY, 0644)\n\tif err != nil {\n\t\tsendTransferError(oid, 3, fmt.Sprintf(\"Cannot read data from %q: %v\", fromPath, err), writer, errWriter)\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t\/\/ Ensure progress callbacks made while uploading\n\t\/\/ Wrap callback to give name context\n\tcb := func(totalSize int64, readSoFar int64, readSinceLast int) error {\n\t\tsendProgress(oid, readSoFar, readSinceLast, writer, errWriter)\n\t\treturn nil\n\t}\n\tvar reader io.Reader\n\treader = &progress.CallbackReader{\n\t\tC:         cb,\n\t\tTotalSize: size,\n\t\tReader:    f,\n\t}\n\n\treq.Body = ioutil.NopCloser(reader)\n\n\tres, err := httputil.DoHttpRequest(req, true)\n\tif err != nil {\n\t\tsendTransferError(oid, res.StatusCode, fmt.Sprintf(\"Error uploading data for %s: %v\", oid, err), writer, errWriter)\n\t\treturn\n\t}\n\n\tif res.StatusCode > 299 {\n\t\tsendTransferError(oid, res.StatusCode, fmt.Sprintf(\"Invalid status for %s: %d\", httputil.TraceHttpReq(req), res.StatusCode), writer, errWriter)\n\t\treturn\n\t}\n\n\tio.Copy(ioutil.Discard, res.Body)\n\tres.Body.Close()\n\n\t\/\/ completed\n\tcomplete := &transferResponse{\"complete\", oid, \"\", nil}\n\terr = sendResponse(complete, writer, errWriter)\n\tif err != nil {\n\t\twriteToStderr(fmt.Sprintf(\"Unable to send completion message: %v\\n\", err), errWriter)\n\t}\n\n}\n\n\/\/ Structs reimplemented so closer to a real external implementation\ntype header struct {\n\tKey   string `json:\"key\"`\n\tValue string `json:\"value\"`\n}\ntype action struct {\n\tHref      string            `json:\"href\"`\n\tHeader    map[string]string `json:\"header,omitempty\"`\n\tExpiresAt time.Time         `json:\"expires_at,omitempty\"`\n}\ntype transferError struct {\n\tCode    int    `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\n\/\/ Combined request struct which can accept anything\ntype request struct {\n\tId                  string  `json:\"id\"`\n\tOperation           string  `json:\"operation\"`\n\tConcurrent          bool    `json:\"concurrent\"`\n\tConcurrentTransfers int     `json:\"concurrenttransfers\"`\n\tOid                 string  `json:\"oid\"`\n\tSize                int64   `json:\"size\"`\n\tPath                string  `json:\"path\"`\n\tAction              *action `json:\"action\"`\n}\n\ntype initResponse struct {\n\tError *transferError `json:\"error,omitempty\"`\n}\ntype transferResponse struct {\n\tId    string         `json:\"id\"`\n\tOid   string         `json:\"oid\"`\n\tPath  string         `json:\"path,omitempty\"` \/\/ always blank for upload\n\tError *transferError `json:\"error,omitempty\"`\n}\ntype progressResponse struct {\n\tId             string `json:\"id\"`\n\tOid            string `json:\"oid\"`\n\tBytesSoFar     int64  `json:\"bytesSoFar\"`\n\tBytesSinceLast int    `json:\"bytesSinceLast\"`\n}\n<commit_msg>Comment fixes<commit_after>\/\/ +build testtools\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/github\/git-lfs\/httputil\"\n\t\"github.com\/github\/git-lfs\/progress\"\n\t\"github.com\/github\/git-lfs\/tools\"\n)\n\n\/\/ This test custom adapter just acts as a bridge for uploads\/downloads\n\/\/ in order to demonstrate & test the custom transfer adapter protocols\n\/\/ All we actually do is relay the requests back to the normal storage URLs\n\/\/ of our test server for simplicity, but this proves the principle\nfunc main() {\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\twriter := bufio.NewWriter(os.Stdout)\n\terrWriter := bufio.NewWriter(os.Stderr)\n\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tvar req request\n\t\tif err := json.Unmarshal([]byte(line), &req); err != nil {\n\t\t\twriteToStderr(fmt.Sprintf(\"Unable to parse request: %v\\n\", line), errWriter)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch req.Id {\n\t\tcase \"init\":\n\t\t\twriteToStderr(fmt.Sprintf(\"Initialised test custom adapter for %s\\n\", req.Operation), errWriter)\n\t\t\tresp := &initResponse{}\n\t\t\tsendResponse(resp, writer, errWriter)\n\t\tcase \"download\":\n\t\t\twriteToStderr(fmt.Sprintf(\"Received download request for %s\\n\", req.Oid), errWriter)\n\t\t\tperformDownload(req.Oid, req.Size, req.Action, writer, errWriter)\n\t\tcase \"upload\":\n\t\t\twriteToStderr(fmt.Sprintf(\"Received upload request for %s\\n\", req.Oid), errWriter)\n\t\t\tperformUpload(req.Oid, req.Size, req.Action, req.Path, writer, errWriter)\n\t\tcase \"terminate\":\n\t\t\twriteToStderr(\"Terminating test custom adapter gracefully.\\n\", errWriter)\n\t\t\tbreak\n\t\t}\n\t}\n\n}\n\nfunc writeToStderr(msg string, errWriter *bufio.Writer) {\n\tif !strings.HasSuffix(msg, \"\\n\") {\n\t\tmsg = msg + \"\\n\"\n\t}\n\terrWriter.WriteString(msg)\n\terrWriter.Flush()\n}\n\nfunc sendResponse(r interface{}, writer, errWriter *bufio.Writer) error {\n\tb, err := json.Marshal(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ Line oriented JSON\n\tb = append(b, '\\n')\n\t_, err = writer.Write(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\twriter.Flush()\n\twriteToStderr(fmt.Sprintf(\"Sent message %v\", string(b)), errWriter)\n\treturn nil\n}\n\nfunc sendTransferError(oid string, code int, message string, writer, errWriter *bufio.Writer) {\n\tresp := &transferResponse{\"complete\", oid, \"\", &transferError{code, message}}\n\terr := sendResponse(resp, writer, errWriter)\n\tif err != nil {\n\t\twriteToStderr(fmt.Sprintf(\"Unable to send transfer error: %v\\n\", err), errWriter)\n\t}\n}\n\nfunc sendProgress(oid string, bytesSoFar int64, bytesSinceLast int, writer, errWriter *bufio.Writer) {\n\tresp := &progressResponse{\"progress\", oid, bytesSoFar, bytesSinceLast}\n\terr := sendResponse(resp, writer, errWriter)\n\tif err != nil {\n\t\twriteToStderr(fmt.Sprintf(\"Unable to send progress update: %v\\n\", err), errWriter)\n\t}\n}\n\nfunc performDownload(oid string, size int64, a *action, writer, errWriter *bufio.Writer) {\n\t\/\/ We just use the URLs we're given, so we're just a proxy for the direct method\n\t\/\/ but this is enough to test intermediate custom adapters\n\treq, err := httputil.NewHttpRequest(\"GET\", a.Href, a.Header)\n\tif err != nil {\n\t\tsendTransferError(oid, 2, err.Error(), writer, errWriter)\n\t\treturn\n\t}\n\tres, err := httputil.DoHttpRequest(req, true)\n\tif err != nil {\n\t\tsendTransferError(oid, res.StatusCode, err.Error(), writer, errWriter)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\n\tdlFile, err := ioutil.TempFile(\"\", \"lfscustomdl\")\n\tif err != nil {\n\t\tsendTransferError(oid, 3, err.Error(), writer, errWriter)\n\t\treturn\n\t}\n\tdefer dlFile.Close()\n\tdlfilename := dlFile.Name()\n\t\/\/ Turn callback into progress messages\n\tcb := func(totalSize int64, readSoFar int64, readSinceLast int) error {\n\t\tsendProgress(oid, readSoFar, readSinceLast, writer, errWriter)\n\t\treturn nil\n\t}\n\t_, err = tools.CopyWithCallback(dlFile, res.Body, res.ContentLength, cb)\n\tif err != nil {\n\t\tsendTransferError(oid, 4, fmt.Sprintf(\"cannot write data to tempfile %q: %v\", dlfilename, err), writer, errWriter)\n\t\tos.Remove(dlfilename)\n\t\treturn\n\t}\n\tif err := dlFile.Close(); err != nil {\n\t\tsendTransferError(oid, 5, fmt.Sprintf(\"can't close tempfile %q: %v\", dlfilename, err), writer, errWriter)\n\t\tos.Remove(dlfilename)\n\t\treturn\n\t}\n\n\t\/\/ completed\n\tcomplete := &transferResponse{\"complete\", oid, dlfilename, nil}\n\terr = sendResponse(complete, writer, errWriter)\n\tif err != nil {\n\t\twriteToStderr(fmt.Sprintf(\"Unable to send completion message: %v\\n\", err), errWriter)\n\t}\n}\n\nfunc performUpload(oid string, size int64, a *action, fromPath string, writer, errWriter *bufio.Writer) {\n\t\/\/ We just use the URLs we're given, so we're just a proxy for the direct method\n\t\/\/ but this is enough to test intermediate custom adapters\n\treq, err := httputil.NewHttpRequest(\"PUT\", a.Href, a.Header)\n\tif err != nil {\n\t\tsendTransferError(oid, 2, err.Error(), writer, errWriter)\n\t\treturn\n\t}\n\n\tif len(req.Header.Get(\"Content-Type\")) == 0 {\n\t\treq.Header.Set(\"Content-Type\", \"application\/octet-stream\")\n\t}\n\n\tif req.Header.Get(\"Transfer-Encoding\") == \"chunked\" {\n\t\treq.TransferEncoding = []string{\"chunked\"}\n\t} else {\n\t\treq.Header.Set(\"Content-Length\", strconv.FormatInt(size, 10))\n\t}\n\n\treq.ContentLength = size\n\n\tf, err := os.OpenFile(fromPath, os.O_RDONLY, 0644)\n\tif err != nil {\n\t\tsendTransferError(oid, 3, fmt.Sprintf(\"Cannot read data from %q: %v\", fromPath, err), writer, errWriter)\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t\/\/ Turn callback into progress messages\n\tcb := func(totalSize int64, readSoFar int64, readSinceLast int) error {\n\t\tsendProgress(oid, readSoFar, readSinceLast, writer, errWriter)\n\t\treturn nil\n\t}\n\tvar reader io.Reader\n\treader = &progress.CallbackReader{\n\t\tC:         cb,\n\t\tTotalSize: size,\n\t\tReader:    f,\n\t}\n\n\treq.Body = ioutil.NopCloser(reader)\n\n\tres, err := httputil.DoHttpRequest(req, true)\n\tif err != nil {\n\t\tsendTransferError(oid, res.StatusCode, fmt.Sprintf(\"Error uploading data for %s: %v\", oid, err), writer, errWriter)\n\t\treturn\n\t}\n\n\tif res.StatusCode > 299 {\n\t\tsendTransferError(oid, res.StatusCode, fmt.Sprintf(\"Invalid status for %s: %d\", httputil.TraceHttpReq(req), res.StatusCode), writer, errWriter)\n\t\treturn\n\t}\n\n\tio.Copy(ioutil.Discard, res.Body)\n\tres.Body.Close()\n\n\t\/\/ completed\n\tcomplete := &transferResponse{\"complete\", oid, \"\", nil}\n\terr = sendResponse(complete, writer, errWriter)\n\tif err != nil {\n\t\twriteToStderr(fmt.Sprintf(\"Unable to send completion message: %v\\n\", err), errWriter)\n\t}\n\n}\n\n\/\/ Structs reimplemented so closer to a real external implementation\ntype header struct {\n\tKey   string `json:\"key\"`\n\tValue string `json:\"value\"`\n}\ntype action struct {\n\tHref      string            `json:\"href\"`\n\tHeader    map[string]string `json:\"header,omitempty\"`\n\tExpiresAt time.Time         `json:\"expires_at,omitempty\"`\n}\ntype transferError struct {\n\tCode    int    `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\n\/\/ Combined request struct which can accept anything\ntype request struct {\n\tId                  string  `json:\"id\"`\n\tOperation           string  `json:\"operation\"`\n\tConcurrent          bool    `json:\"concurrent\"`\n\tConcurrentTransfers int     `json:\"concurrenttransfers\"`\n\tOid                 string  `json:\"oid\"`\n\tSize                int64   `json:\"size\"`\n\tPath                string  `json:\"path\"`\n\tAction              *action `json:\"action\"`\n}\n\ntype initResponse struct {\n\tError *transferError `json:\"error,omitempty\"`\n}\ntype transferResponse struct {\n\tId    string         `json:\"id\"`\n\tOid   string         `json:\"oid\"`\n\tPath  string         `json:\"path,omitempty\"` \/\/ always blank for upload\n\tError *transferError `json:\"error,omitempty\"`\n}\ntype progressResponse struct {\n\tId             string `json:\"id\"`\n\tOid            string `json:\"oid\"`\n\tBytesSoFar     int64  `json:\"bytesSoFar\"`\n\tBytesSinceLast int    `json:\"bytesSinceLast\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2014 The Camlistore Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/mpl\/scancabimport\/third_party\/github.com\/golang\/oauth2\"\n\t\"github.com\/mpl\/scancabimport\/third_party\/github.com\/golang\/oauth2\/google\"\n\t\"github.com\/mpl\/scancabimport\/third_party\/google.golang.org\/cloud\/datastore\"\n)\n\n\/*\nTo get blobs, already tried:\n1) gcs with google.golang.org\/cloud\/storage -> getting a 403. Plus that wouldn't work anyway\nas the blobs don't seem to be in the bucket when I ls with gsutil.\n2) oauth2 with code.google.com\/p\/goauth2\/oauth + GET on \/resource -> getting redirected.\n3) oauth2 with github.com\/golang\/oauth2 + GET on \/resource -> same thing.\n4) oauth with github.com\/garyburd\/go-oauth\/oauth -> getting a 400, but maybe I half-assed it.\n5) went back to github.com\/golang\/oauth2, and added X-AppEngine-User-Email header -> not better.\n6) go doc hinted at the problem: there's still a login: required in app.yaml, that oauth does not override. need to test and confirm (that we're ok without it).\n7) back to approach in 1): was getting 403 because GCS JSON API was needed too. Getting 404s now.\nBut looked through API explorer at https:\/\/developers.google.com\/apis-explorer\/#p\/storage\/v1\/storage.objects.list\nwhich shows same as with gsutil, i.e. not my files. So probably no go that way.\n8) back to 6). -> yep, that works.\n*\/\n\nvar (\n\tprojectId      = \"scancabcamli\"\n\tserviceAccount = \"886924983567-uiln6pus9iuumdq3i0vav0ntveodas0r@developer.gserviceaccount.com\"\n\tmyEmail        = \"mathieu.lonjaret@gmail.com\"\n\tds             *datastore.Dataset\n\tcl             *http.Client\n\tclientId       = \"886924983567-hnd1dertfvi2g0lpjs72aae8hi35k364.apps.googleusercontent.com\"\n\tclientSecret   = \"nope\"\n\ttokenCacheFile = filepath.Join(os.Getenv(\"HOME\"), \"tokencache.json\")\n)\n\n\/\/ UserInfo represents the metadata associated with the Google User\n\/\/ currently logged-in to the app\ntype UserInfo struct {\n\t\/\/ User stores the email address of the currently logged-in user\n\t\/\/ this is used as the primary key\n\tUser string\n\n\t\/\/ MediaObjects is a count of the MediaObjects currently associated with this user\n\tMediaObjects int64\n\n\t\/\/ UploadPassword is a plain-text string that protects the scan upload API\n\tUploadPassword string\n}\n\n\/\/ MediaObject represents the metadata associated with each individual uploaded scan\ntype MediaObject struct {\n\t\/\/ Owner is the key of the UserInfo of the user that uploaded the file\n\tOwner *datastore.Key\n\n\t\/\/ IntID is the entity ID of the key associated with this MediaObject struct\n\t\/\/ Not stored in datastore but filled on each get()\n\t\/\/\tIntID int64 `datastore:\"-\"`\n\tResourceId int64 `datastore:\"-\"`\n\n\t\/\/ Blob is the key of blobstore entry with this uploaded file\n\tBlob string\n\n\t\/\/ Creation the time when this struct was originally created\n\tCreation time.Time\n\n\t\/\/ ContentType is the MIME-type of the uploaded file.\n\t\/\/ As the mime\/multipart package does not detect Content-Type\n\t\/\/ before sending the file in the command line client, this is\n\t\/\/ detected in the webapp and so this field may differ from the\n\t\/\/ content-type for the associated blob in the blobstore\n\tContentType string\n\n\t\/\/ Filename is the name of the file when it was uploaded\n\tFilename string\n\n\t\/\/ Size in bytes of the uploaded file\n\tSize int64\n\n\t\/\/ Document is the key of the associated Document struct.\n\t\/\/ A Document has many MediaObjects. When newly uploaded,\n\t\/\/ a MediaObject is not associated with a Document.\n\tDocument *datastore.Key\n\n\t\/\/ LacksDocument is false when this MediaObject is associated with a Document.\n\t\/\/ When newly uploaded, a MediaObject is not associated with a Document.\n\tLacksDocument bool\n}\n\n\/\/ Document is a structure that groups scans into a logical unit.\n\/\/ A letter (Stored as a document) could have several pages\n\/\/ (each is a MediaObject), for example.\ntype Document struct {\n\t\/\/ Owner is the key of the UserInfo of the user that created the Document\n\tOwner *datastore.Key\n\n\t\/\/ Pages are the keys of each Media Object that contitute this Document\n\tPages []*datastore.Key\n\n\t\/\/ IntID is the entity ID of the key associated with this Document struct\n\t\/\/ Not stored in datastore but filled on each get()\n\tIntID int64 `datastore:\"-\"`\n\n\t\/\/ DocDate is the user-nominated date associated with this document. It can\n\t\/\/ store any date the user likes but is intended to be when the document was\n\t\/\/ received, or, perhaps, written or sent\n\tDocDate time.Time\n\n\t\/\/ NoDate is false when DocDate has been set by the user\n\tNoDate bool\n\n\t\/\/ Creation is the date the Document struct was created\n\tCreation time.Time\n\n\t\/\/ Title is the user-nominated title of the document\n\tTitle string\n\n\t\/\/ Description is the user-nominated description of the document\n\tDescription string\n\n\t\/\/ Tags is the slice of zero or more tags associated with the document by the user\n\tTags string\n\n\t\/\/ LowercaseTags is the content of Tags but stored lowercase as a\n\t\/\/ canonical version so searches on tags can be case-insensitive\n\tLowercaseTags string\n\n\t\/\/ NoTags is true when Tags is empty\n\tNoTags bool\n\n\t\/\/ PhysicalLocation is the user-nominated description of the location\n\t\/\/ of the physical document of which the MediaObjects associated with this\n\t\/\/ Document are scans\n\tPhysicalLocation string\n\n\t\/\/ DueDate is the user-nominated date that the document is \"due\". The\n\t\/\/ meaning of what \"due\" means in relation to each particular document\n\t\/\/ is up to the user\n\tDueDate time.Time\n}\n\nconst (\n\tscansRequestLimit = 5\n\tdocsRequestLimit  = 5\n)\n\nfunc getScans() ([]*MediaObject, error) {\n\tvar scans []*MediaObject\n\tquery := ds.NewQuery(\"MediaObject\")\n\tquery = query.Limit(scansRequestLimit)\n\tfor {\n\t\tsc := make([]*MediaObject, scansRequestLimit)\n\t\tkeys, next, err := ds.RunQuery(query, sc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ get the key id and store it in the media object because we'll need it\n\t\t\/\/ to fetch the corresponding file from the blobstore later.\n\t\tfor i, obj := range sc {\n\t\t\tif obj == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tobj.ResourceId = keys[i].ID()\n\t\t}\n\t\tscans = append(scans, sc...)\n\t\t\/\/\t\tfor _, v := range keys {\n\t\t\/\/\t\t\tfmt.Printf(\"key: %v, \", v)\n\t\t\/\/\t\t}\n\t\tif next == nil {\n\t\t\tbreak\n\t\t}\n\t\tquery = next\n\t}\n\treturn scans, nil\n}\n\nfunc getDocuments() ([]*Document, error) {\n\tvar docs []*Document\n\tquery := ds.NewQuery(\"Document\")\n\tquery = query.Limit(scansRequestLimit)\n\tfor {\n\t\tdc := make([]*Document, docsRequestLimit)\n\t\t\/\/\t\tkeys, next, err := ds.RunQuery(query, dc)\n\t\t_, next, err := ds.RunQuery(query, dc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdocs = append(docs, dc...)\n\t\t\/\/\t\tfor _, v := range keys {\n\t\t\/\/\t\t\tfmt.Printf(\"key: %v, \", v)\n\t\t\/\/\t\t}\n\t\tif next == nil {\n\t\t\tbreak\n\t\t}\n\t\tquery = next\n\t}\n\treturn docs, nil\n}\n\nfunc getScannedFile(key, filename string) error {\n\t\/\/\t\"https:\/\/scancabcamli.appspot.com\/resource\/5066549580791808\/glenda.png\"\n\t\/*\n\t\treq, err := http.NewRequest(\"GET\", \"https:\/\/scancabcamli.appspot.com\/resource\/\"+key+\"\/glenda.png\", nil)\n\t\treq.Header.Add(\"X-AppEngine-User-Email\", \"mathieu.lonjaret@gmail.com\")\n\t\tresp, err := cl.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t*\/\n\tresp, err := cl.Get(\"https:\/\/\" + projectId + \".appspot.com\/resource\/\" + key + \"\/\" + filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"Status %v\", resp.Status)\n\t}\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(filename, body, 0700)\n}\n\nfunc cacheToken(tok *oauth2.Token) error {\n\tfile, err := os.OpenFile(tokenCacheFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err := file.Close(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\tif err := json.NewEncoder(file).Encode(tok); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc cachedToken() (*oauth2.Token, error) {\n\tfile, err := os.Open(tokenCacheFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\ttok := &oauth2.Token{}\n\tif err := json.NewDecoder(file).Decode(tok); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tok, nil\n}\n\nfunc transportFromAPIKey() (*oauth2.Transport, error) {\n\tconf, err := oauth2.NewConfig(&oauth2.Options{\n\t\tScopes: []string{\"https:\/\/www.googleapis.com\/auth\/appengine.admin\",\n\t\t\t\"https:\/\/www.googleapis.com\/auth\/userinfo.email\"},\n\t\tClientID:     clientId,\n\t\tClientSecret: clientSecret,\n\t\tRedirectURL:  \"urn:ietf:wg:oauth:2.0:oob\",\n\t},\n\t\t\"https:\/\/accounts.google.com\/o\/oauth2\/auth\",\n\t\t\"https:\/\/accounts.google.com\/o\/oauth2\/token\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttoken, err := cachedToken()\n\tif err == nil {\n\t\ttr := conf.NewTransport()\n\t\ttr.SetToken(token)\n\t\treturn tr, nil\n\t}\n\n\t\/\/ Redirect user to consent page to ask for permission\n\t\/\/ for the scopes specified above.\n\turl := conf.AuthCodeURL(\"state\", \"online\", \"auto\")\n\t\/\/      url := conf.AuthCodeURL(\"state\", \"offline\", \"auto\")\n\tfmt.Printf(\"Visit the URL for the auth dialog: %v\\n\", url)\n\n\tinput := bufio.NewReader(os.Stdin)\n\tline, _, err := input.ReadLine()\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to read line: %v\", err)\n\t}\n\tauthorizationCode := strings.TrimSpace(string(line))\n\ttr, err := conf.NewTransportWithCode(authorizationCode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := cacheToken(tr.Token()); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tr, nil\n}\n\nfunc main() {\n\n\tpemKeyBytes, err := ioutil.ReadFile(\"\/home\/mpl\/scancabcamli-496f5f6eb01b.pem\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ TODO(mpl): try using an authed transport from transportFromAPIKey, so we don't\n\t\/\/ have to setup two different auth.\n\t\/\/ The contrary is not possible (i.e. using transportFromServiceAccount for getting\n\t\/\/ the blobs\/files) because the server would see the service account email as the userinfo,\n\t\/\/ instead of our own joe user email, who is the owner of the objects in the datastore.\n\tds, err = datastore.NewDataset(projectId, serviceAccount, pemKeyBytes)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tscans, err := getScans()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttr, err := transportFromAPIKey()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcl = &http.Client{Transport: tr}\n\tdocuments := make(map[int64]*Document)\n\tusers := make(map[int64]*UserInfo)\n\tfor _, v := range scans {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%v\\n\", v)\n\t\tif v.Owner != nil {\n\t\t\tuserId := v.Owner.ID()\n\t\t\tif _, ok := users[userId]; !ok {\n\t\t\t\tuserInfo := &UserInfo{}\n\t\t\t\tif err := ds.Get(v.Owner, userInfo); err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\tusers[userId] = userInfo\n\t\t\t\tfmt.Printf(\"Owner: %v\\n\", userInfo)\n\t\t\t}\n\t\t}\n\t\t\/\/ TODO(mpl): skip if file already exists, or if any of v.ResourceId, v.Filename not good.\n\t\tif err := getScannedFile(fmt.Sprintf(\"%d\", v.ResourceId), v.Filename); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif v != nil && !v.LacksDocument && v.Document != nil {\n\t\t\tprintln(\"HAS DOCUMENT\")\n\t\t\tdocId := v.Document.ID()\n\t\t\tif _, ok := documents[docId]; ok {\n\t\t\t\tprintln(\"already got it: \" + fmt.Sprintf(\"%d\", docId))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdocument := &Document{}\n\t\t\tif err := ds.Get(v.Document, document); err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tdocuments[docId] = document\n\t\t\tfmt.Printf(\"Document: %v\\n\", document)\n\t\t}\n\t}\n\treturn\n\n\t\/*\n\t\t\/\/ TODO(mpl): rm getDocuments, as we should have gotten them all from the scans.\n\t\tdocs, err := getDocuments()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfor _, v := range docs {\n\t\t\tfmt.Printf(\"%v\\n\", v)\n\t\t}\n\t\treturn\n\n\t\t\/\/ TODO(mpl): tokencache\n\t\ttr, err := transportFromAPIKey()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tcl = &http.Client{Transport: tr}\n\t\tscanBlobKey := \"5066549580791808\"\n\t\tif err := getScannedFile(scanBlobKey, \"glenda.png\"); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t*\/\n\n}\n\nfunc transportFromServiceAccount() (*oauth2.Transport, error) {\n\tpemKeyBytes, err := ioutil.ReadFile(\"\/home\/mpl\/scancabcamli-496f5f6eb01b.pem\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconf, err := google.NewServiceAccountConfig(&oauth2.JWTOptions{\n\t\tEmail:      serviceAccount,\n\t\tPrivateKey: pemKeyBytes,\n\t\tScopes: []string{\n\t\t\t\/\/\t\t\tgcstorage2.ScopeFullControl,\n\t\t\t\"https:\/\/www.googleapis.com\/auth\/appengine.admin\",\n\t\t\t\"https:\/\/www.googleapis.com\/auth\/userinfo.email\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn conf.NewTransport(), nil\n}\n<commit_msg>cleanup<commit_after>\/*\nCopyright 2014 The Camlistore Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/mpl\/scancabimport\/third_party\/github.com\/golang\/oauth2\"\n\t\"github.com\/mpl\/scancabimport\/third_party\/google.golang.org\/cloud\/datastore\"\n)\n\n\/*\nTo get blobs, already tried:\n1) gcs with google.golang.org\/cloud\/storage -> getting a 403. Plus that wouldn't work anyway\nas the blobs don't seem to be in the bucket when I ls with gsutil.\n2) oauth2 with code.google.com\/p\/goauth2\/oauth + GET on \/resource -> getting redirected.\n3) oauth2 with github.com\/golang\/oauth2 + GET on \/resource -> same thing.\n4) oauth with github.com\/garyburd\/go-oauth\/oauth -> getting a 400, but maybe I half-assed it.\n5) went back to github.com\/golang\/oauth2, and added X-AppEngine-User-Email header -> not better.\n6) go doc hinted at the problem: there's still a login: required in app.yaml, that oauth does not override. need to test and confirm (that we're ok without it).\n7) back to approach in 1): was getting 403 because GCS JSON API was needed too. Getting 404s now.\nBut looked through API explorer at https:\/\/developers.google.com\/apis-explorer\/#p\/storage\/v1\/storage.objects.list\nwhich shows same as with gsutil, i.e. not my files. So probably no go that way.\n8) back to 6). -> yep, that works.\n*\/\n\nvar (\n\tverbose = flag.Bool(\"v\", false, \"verbose\")\n)\n\nvar (\n\t\/\/ for the datastore, where we get the scans and documents metadata.\n\tprojectId      = \"scancabcamli\"\n\tserviceAccount = \"886924983567-uiln6pus9iuumdq3i0vav0ntveodas0r@developer.gserviceaccount.com\"\n\tpemFile        = \"scancabcamli-496f5f6eb01b.pem\"\n\tds             *datastore.Dataset\n\n\t\/\/ we get the scans themselves, which are in the blobstore, through hitting the app itself.\n\tcl             *http.Client\n\tclientId       = \"886924983567-hnd1dertfvi2g0lpjs72aae8hi35k364.apps.googleusercontent.com\"\n\tclientSecret   = \"nope\"\n\ttokenCacheFile = \"tokencache.json\"\n\tscansDir       = \"scans\"\n)\n\n\/\/ UserInfo represents the metadata associated with the Google User\n\/\/ currently logged-in to the app\ntype UserInfo struct {\n\t\/\/ User stores the email address of the currently logged-in user\n\t\/\/ this is used as the primary key\n\tUser string\n\n\t\/\/ MediaObjects is a count of the MediaObjects currently associated with this user\n\tMediaObjects int64\n\n\t\/\/ UploadPassword is a plain-text string that protects the scan upload API\n\tUploadPassword string\n}\n\n\/\/ MediaObject represents the metadata associated with each individual uploaded scan\ntype MediaObject struct {\n\t\/\/ Owner is the key of the UserInfo of the user that uploaded the file\n\tOwner *datastore.Key\n\n\t\/\/ IntID is the entity ID of the key associated with this MediaObject struct\n\t\/\/ Not stored in datastore but filled on each get()\n\t\/\/\tIntID int64 `datastore:\"-\"`\n\tResourceId int64 `datastore:\"-\"`\n\n\t\/\/ Blob is the key of blobstore entry with this uploaded file\n\tBlob string\n\n\t\/\/ Creation the time when this struct was originally created\n\tCreation time.Time\n\n\t\/\/ ContentType is the MIME-type of the uploaded file.\n\t\/\/ As the mime\/multipart package does not detect Content-Type\n\t\/\/ before sending the file in the command line client, this is\n\t\/\/ detected in the webapp and so this field may differ from the\n\t\/\/ content-type for the associated blob in the blobstore\n\tContentType string\n\n\t\/\/ Filename is the name of the file when it was uploaded\n\tFilename string\n\n\t\/\/ Size in bytes of the uploaded file\n\tSize int64\n\n\t\/\/ Document is the key of the associated Document struct.\n\t\/\/ A Document has many MediaObjects. When newly uploaded,\n\t\/\/ a MediaObject is not associated with a Document.\n\tDocument *datastore.Key\n\n\t\/\/ LacksDocument is false when this MediaObject is associated with a Document.\n\t\/\/ When newly uploaded, a MediaObject is not associated with a Document.\n\tLacksDocument bool\n}\n\n\/\/ Document is a structure that groups scans into a logical unit.\n\/\/ A letter (Stored as a document) could have several pages\n\/\/ (each is a MediaObject), for example.\ntype Document struct {\n\t\/\/ Owner is the key of the UserInfo of the user that created the Document\n\tOwner *datastore.Key\n\n\t\/\/ Pages are the keys of each Media Object that contitute this Document\n\tPages []*datastore.Key\n\n\t\/\/ IntID is the entity ID of the key associated with this Document struct\n\t\/\/ Not stored in datastore but filled on each get()\n\tIntID int64 `datastore:\"-\"`\n\n\t\/\/ DocDate is the user-nominated date associated with this document. It can\n\t\/\/ store any date the user likes but is intended to be when the document was\n\t\/\/ received, or, perhaps, written or sent\n\tDocDate time.Time\n\n\t\/\/ NoDate is false when DocDate has been set by the user\n\tNoDate bool\n\n\t\/\/ Creation is the date the Document struct was created\n\tCreation time.Time\n\n\t\/\/ Title is the user-nominated title of the document\n\tTitle string\n\n\t\/\/ Description is the user-nominated description of the document\n\tDescription string\n\n\t\/\/ Tags is the slice of zero or more tags associated with the document by the user\n\tTags string\n\n\t\/\/ LowercaseTags is the content of Tags but stored lowercase as a\n\t\/\/ canonical version so searches on tags can be case-insensitive\n\tLowercaseTags string\n\n\t\/\/ NoTags is true when Tags is empty\n\tNoTags bool\n\n\t\/\/ PhysicalLocation is the user-nominated description of the location\n\t\/\/ of the physical document of which the MediaObjects associated with this\n\t\/\/ Document are scans\n\tPhysicalLocation string\n\n\t\/\/ DueDate is the user-nominated date that the document is \"due\". The\n\t\/\/ meaning of what \"due\" means in relation to each particular document\n\t\/\/ is up to the user\n\tDueDate time.Time\n}\n\nconst (\n\t\/\/ TODO(mpl): figure out how high these can be cranked up.\n\tscansRequestLimit = 5\n\tdocsRequestLimit  = 5\n)\n\nfunc getScans() ([]*MediaObject, error) {\n\tvar scans []*MediaObject\n\tquery := ds.NewQuery(\"MediaObject\")\n\tquery = query.Limit(scansRequestLimit)\n\tfor {\n\t\tsc := make([]*MediaObject, scansRequestLimit)\n\t\tkeys, next, err := ds.RunQuery(query, sc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ get the key id and store it in the media object because we'll need it\n\t\t\/\/ to fetch the corresponding file from the blobstore later.\n\t\tfor i, obj := range sc {\n\t\t\tif obj == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tobj.ResourceId = keys[i].ID()\n\t\t}\n\t\tscans = append(scans, sc...)\n\t\tif next == nil {\n\t\t\tbreak\n\t\t}\n\t\tquery = next\n\t}\n\treturn scans, nil\n}\n\nfunc getDocuments() ([]*Document, error) {\n\tvar docs []*Document\n\tquery := ds.NewQuery(\"Document\")\n\tquery = query.Limit(scansRequestLimit)\n\tfor {\n\t\tdc := make([]*Document, docsRequestLimit)\n\t\t\/\/\t\tkeys, next, err := ds.RunQuery(query, dc)\n\t\t_, next, err := ds.RunQuery(query, dc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdocs = append(docs, dc...)\n\t\tif next == nil {\n\t\t\tbreak\n\t\t}\n\t\tquery = next\n\t}\n\treturn docs, nil\n}\n\nfunc getScannedFile(resourceId, filename string) error {\n\tif resourceId == \"\" {\n\t\tlog.Printf(\"WARNING: Not fetching scan because empty resourceId\")\n\t\treturn nil\n\t}\n\tif resourceId == \"\" {\n\t\tlog.Printf(\"WARNING: Not fetching scan because empty filename\")\n\t\treturn nil\n\t}\n\tfilePath := filepath.Join(scansDir, filename)\n\tif _, err := os.Stat(filePath); err == nil {\n\t\tlog.Printf(\"%s already exists, skipping download.\", filePath)\n\t\treturn nil\n\t}\n\tresp, err := cl.Get(\"https:\/\/\" + projectId + \".appspot.com\/resource\/\" + resourceId + \"\/\" + filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"Status %v\", resp.Status)\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(filePath, body, 0700)\n}\n\nfunc cacheToken(tok *oauth2.Token) error {\n\tfile, err := os.OpenFile(tokenCacheFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err := file.Close(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\tif err := json.NewEncoder(file).Encode(tok); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc cachedToken() (*oauth2.Token, error) {\n\tfile, err := os.Open(tokenCacheFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\ttok := &oauth2.Token{}\n\tif err := json.NewDecoder(file).Decode(tok); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tok, nil\n}\n\nfunc transportFromAPIKey() (*oauth2.Transport, error) {\n\tconf, err := oauth2.NewConfig(&oauth2.Options{\n\t\tScopes: []string{\"https:\/\/www.googleapis.com\/auth\/appengine.admin\",\n\t\t\t\"https:\/\/www.googleapis.com\/auth\/userinfo.email\"},\n\t\tClientID:     clientId,\n\t\tClientSecret: clientSecret,\n\t\tRedirectURL:  \"urn:ietf:wg:oauth:2.0:oob\",\n\t},\n\t\t\"https:\/\/accounts.google.com\/o\/oauth2\/auth\",\n\t\t\"https:\/\/accounts.google.com\/o\/oauth2\/token\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttoken, err := cachedToken()\n\tif err == nil {\n\t\ttr := conf.NewTransport()\n\t\ttr.SetToken(token)\n\t\treturn tr, nil\n\t}\n\n\t\/\/ Redirect user to consent page to ask for permission\n\t\/\/ for the scopes specified above.\n\turl := conf.AuthCodeURL(\"state\", \"online\", \"auto\")\n\t\/\/ url := conf.AuthCodeURL(\"state\", \"offline\", \"auto\")\n\tfmt.Printf(\"Visit the URL for the auth dialog: %v\\n\", url)\n\tfmt.Println(\"And enter the authorization string displayed in your browser:\")\n\n\tinput := bufio.NewReader(os.Stdin)\n\tline, _, err := input.ReadLine()\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to read line: %v\", err)\n\t}\n\tauthorizationCode := strings.TrimSpace(string(line))\n\ttr, err := conf.NewTransportWithCode(authorizationCode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := cacheToken(tr.Token()); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tr, nil\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif err := os.MkdirAll(scansDir, 0700); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tpemKeyBytes, err := ioutil.ReadFile(pemFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ TODO(mpl): try using an authed transport from transportFromAPIKey, so we don't\n\t\/\/ have to setup two different auth.\n\t\/\/ The contrary is not possible (i.e. using transportFromServiceAccount for getting\n\t\/\/ the blobs\/files) because the server would see the service account email as the userinfo,\n\t\/\/ instead of our own joe user email, who is the owner of the objects in the datastore.\n\tds, err = datastore.NewDataset(projectId, serviceAccount, pemKeyBytes)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ TODO(mpl): write scans + docs on json files\n\tscans, err := getScans()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttr, err := transportFromAPIKey()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcl = &http.Client{Transport: tr}\n\n\tdocuments := make(map[int64]*Document)\n\tusers := make(map[int64]*UserInfo)\n\tfor _, v := range scans {\n\t\tif v == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif *verbose {\n\t\t\tfmt.Printf(\"%v\\n\", v)\n\t\t}\n\t\tif v.Owner != nil {\n\t\t\tuserId := v.Owner.ID()\n\t\t\tif _, ok := users[userId]; !ok {\n\t\t\t\tuserInfo := &UserInfo{}\n\t\t\t\tif err := ds.Get(v.Owner, userInfo); err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\tusers[userId] = userInfo\n\t\t\t\tif *verbose {\n\t\t\t\t\tfmt.Printf(\"Owner: %v\\n\", userInfo)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err := getScannedFile(fmt.Sprintf(\"%d\", v.ResourceId), v.Filename); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif v != nil && !v.LacksDocument && v.Document != nil {\n\t\t\tdocId := v.Document.ID()\n\t\t\tif _, ok := documents[docId]; ok {\n\t\t\t\tif *verbose {\n\t\t\t\t\tfmt.Printf(\"Document cache hit: %d\\n\", docId)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdocument := &Document{}\n\t\t\tif err := ds.Get(v.Document, document); err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tdocuments[docId] = document\n\t\t\tif *verbose {\n\t\t\t\tfmt.Printf(\"Document: %v\\n\", document)\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/heqzha\/dcache\"\n)\n\nfunc TestDCacheString(t *testing.T) {\n\tpool := dcache.GetCliPoolInst()\n\tcli, err := pool.GetOrAdd(\"127.0.0.1:11000\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tkey := \"test12\"\n\tstrVal := \"\"\n\tif err := cli.Get(\"default\", key, &strVal); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Log(strVal)\n\tif err := cli.Set(\"default\", key, \"Hello World\"); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tif err := cli.Get(\"default\", key, &strVal); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Log(strVal)\n\n\tif err := cli.Del(\"default\", key, &strVal); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Log(strVal)\n}\n\ntype TestObj struct {\n\tName string\n\tAge  int\n\tTs   time.Time\n}\n\nfunc TestDCacheObjGetSet(t *testing.T) {\n\tpool := dcache.GetCliPoolInst()\n\tcli, err := pool.GetOrAdd(\"127.0.0.1:11001\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tkey := \"test1\"\n\n\toldObj := TestObj{}\n\tif err := cli.Get(\"default\", key, &oldObj); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Log(oldObj)\n\n\tobj := TestObj{\n\t\tName: \"abc\",\n\t\tAge:  11,\n\t\tTs:   time.Now(),\n\t}\n\tif err := cli.Set(\"default\", key, obj); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tnewObj := TestObj{}\n\tif err := cli.Get(\"default\", key, &newObj); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Log(newObj)\n}\n\nfunc TestDCacheObjDel(t *testing.T) {\n\tpool := dcache.GetCliPoolInst()\n\tcli, err := pool.GetOrAdd(\"127.0.0.1:11001\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tkey := \"test1\"\n\n\tobj := TestObj{\n\t\tName: \"abc\",\n\t\tAge:  11,\n\t\tTs:   time.Now(),\n\t}\n\tif err := cli.Set(\"default\", key, obj); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tdelObj := TestObj{}\n\tif err := cli.Del(\"default\", key, &delObj); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Log(delObj)\n}\n<commit_msg>Add TestDCacheObjGetIfExist test codes<commit_after>package test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/heqzha\/dcache\"\n)\n\nfunc TestDCacheString(t *testing.T) {\n\tpool := dcache.GetCliPoolInst()\n\tcli, err := pool.GetOrAdd(\"127.0.0.1:11000\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tkey := \"test12\"\n\tstrVal := \"\"\n\tif err := cli.Get(\"default\", key, &strVal); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Log(strVal)\n\tif err := cli.Set(\"default\", key, \"Hello World\"); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tif err := cli.Get(\"default\", key, &strVal); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Log(strVal)\n\n\tif err := cli.Del(\"default\", key, &strVal); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Log(strVal)\n}\n\ntype TestObj struct {\n\tName string\n\tAge  int\n\tTs   time.Time\n}\n\nfunc TestDCacheObjGetSet(t *testing.T) {\n\tpool := dcache.GetCliPoolInst()\n\tcli, err := pool.GetOrAdd(\"127.0.0.1:11000\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tkey := \"test1\"\n\n\toldObj := TestObj{}\n\tif err := cli.Get(\"default\", key, &oldObj); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Log(oldObj)\n\n\tobj := TestObj{\n\t\tName: \"abc\",\n\t\tAge:  11,\n\t\tTs:   time.Now(),\n\t}\n\tif err := cli.Set(\"default\", key, obj); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tnewObj := TestObj{}\n\tif err := cli.Get(\"default\", key, &newObj); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Log(newObj)\n}\n\nfunc TestDCacheObjDel(t *testing.T) {\n\tpool := dcache.GetCliPoolInst()\n\tcli, err := pool.GetOrAdd(\"127.0.0.1:11000\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tkey := \"test1\"\n\n\tobj := TestObj{\n\t\tName: \"abc\",\n\t\tAge:  11,\n\t\tTs:   time.Now(),\n\t}\n\tif err := cli.Set(\"default\", key, obj); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tdelObj := TestObj{}\n\tif err := cli.Del(\"default\", key, &delObj); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tt.Log(delObj)\n}\n\nfunc TestDCacheObjGetIfExist(t *testing.T) {\n\tpool := dcache.GetCliPoolInst()\n\tcli, err := pool.GetOrAdd(\"127.0.0.1:11000\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tgroup := \"default\"\n\tkey := \"key1\"\n\tobj := TestObj{\n\t\tName: \"abc\",\n\t\tAge:  11,\n\t\tTs:   time.Now(),\n\t}\n\tif err := cli.SetWithExpire(group, key, obj, 10*time.Second); err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tfor {\n\t\tnewObj := TestObj{}\n\t\tif err := cli.GetIfExist(group, key, &newObj); err != nil {\n\t\t\tif err == dcache.KeyNotExistError {\n\t\t\t\tfmt.Println(\"Done\")\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tt.Error(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tfmt.Println(newObj)\n\t\ttime.Sleep(time.Second)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/  Copyright 2022 Google Inc. All Rights Reserved.\n\/\/\n\/\/  Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/  you may not use this file except in compliance with the License.\n\/\/  You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/  Unless required by applicable law or agreed to in writing, software\n\/\/  distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/  See the License for the specific language governing permissions and\n\/\/  limitations under the License.\n\npackage daisyutils\n\nimport (\n\tdaisy \"github.com\/GoogleCloudPlatform\/compute-daisy\"\n\tcomputeBeta \"google.golang.org\/api\/compute\/v0.beta\"\n\t\"google.golang.org\/api\/compute\/v1\"\n)\n\n\/\/ EnableNestedVirtualizationHook is a WorkflowHook that updates CreateInstances in a\n\/\/ daisy workflow such that they will be created with nested virtualization enabled.\n\/\/\n\/\/ For more info on nested virtualization see:\n\/\/\n\/\/\thttps:\/\/cloud.google.com\/compute\/docs\/instances\/nested-virtualization\/overview\ntype EnableNestedVirtualizationHook struct{}\n\n\/\/ PreRunHook updates the CreateInstances steps so that they won't have an external IP.\nfunc (t *EnableNestedVirtualizationHook) PreRunHook(wf *daisy.Workflow) error {\n\twf.IterateWorkflowSteps(func(step *daisy.Step) {\n\t\tif step.CreateInstances != nil {\n\t\t\tfor _, instance := range step.CreateInstances.Instances {\n\t\t\t\tif instance.AdvancedMachineFeatures == nil {\n\t\t\t\t\tinstance.AdvancedMachineFeatures = &compute.AdvancedMachineFeatures{}\n\t\t\t\t}\n\t\t\t\tinstance.AdvancedMachineFeatures.EnableNestedVirtualization = true\n\t\t\t}\n\t\t\tfor _, instance := range step.CreateInstances.InstancesBeta {\n\t\t\t\tif instance.AdvancedMachineFeatures == nil {\n\t\t\t\t\tinstance.AdvancedMachineFeatures = &computeBeta.AdvancedMachineFeatures{}\n\t\t\t\t}\n\t\t\t\tinstance.AdvancedMachineFeatures.EnableNestedVirtualization = true\n\t\t\t}\n\n\t\t}\n\t})\n\treturn nil\n}\n<commit_msg>Fix comment. (#76)<commit_after>\/\/  Copyright 2022 Google Inc. All Rights Reserved.\n\/\/\n\/\/  Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/  you may not use this file except in compliance with the License.\n\/\/  You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/  Unless required by applicable law or agreed to in writing, software\n\/\/  distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/  See the License for the specific language governing permissions and\n\/\/  limitations under the License.\n\npackage daisyutils\n\nimport (\n\tdaisy \"github.com\/GoogleCloudPlatform\/compute-daisy\"\n\tcomputeBeta \"google.golang.org\/api\/compute\/v0.beta\"\n\t\"google.golang.org\/api\/compute\/v1\"\n)\n\n\/\/ EnableNestedVirtualizationHook is a WorkflowHook that updates CreateInstances in a\n\/\/ daisy workflow such that they will be created with nested virtualization enabled.\n\/\/\n\/\/ For more info on nested virtualization see:\n\/\/\n\/\/\thttps:\/\/cloud.google.com\/compute\/docs\/instances\/nested-virtualization\/overview\ntype EnableNestedVirtualizationHook struct{}\n\n\/\/ PreRunHook updates the CreateInstances steps so that they will be created with\n\/\/ nested virtualization enabled.\nfunc (t *EnableNestedVirtualizationHook) PreRunHook(wf *daisy.Workflow) error {\n\twf.IterateWorkflowSteps(func(step *daisy.Step) {\n\t\tif step.CreateInstances != nil {\n\t\t\tfor _, instance := range step.CreateInstances.Instances {\n\t\t\t\tif instance.AdvancedMachineFeatures == nil {\n\t\t\t\t\tinstance.AdvancedMachineFeatures = &compute.AdvancedMachineFeatures{}\n\t\t\t\t}\n\t\t\t\tinstance.AdvancedMachineFeatures.EnableNestedVirtualization = true\n\t\t\t}\n\t\t\tfor _, instance := range step.CreateInstances.InstancesBeta {\n\t\t\t\tif instance.AdvancedMachineFeatures == nil {\n\t\t\t\t\tinstance.AdvancedMachineFeatures = &computeBeta.AdvancedMachineFeatures{}\n\t\t\t\t}\n\t\t\t\tinstance.AdvancedMachineFeatures.EnableNestedVirtualization = true\n\t\t\t}\n\n\t\t}\n\t})\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/gemnasium\/logrus-hooks\/graylog\"\n\t\"github.com\/plumbum\/mgorus\"\n\t\"time\"\n)\n\nfunc main() {\n\n\t\/\/ log.SetFormatter(&log.JSONFormatter{})\n\t\/\/ log.SetOutput(os.Stderr)\n\n\tlog := logrus.New()\n\tlog.Level = logrus.DebugLevel\n\thook := graylog.NewGraylogHook(\"127.0.0.1:12201\", \"myFacility\", map[string]interface{}{\"startTime\": time.Now().String()})\n\tlog.Hooks.Add(hook)\n\n\thooker, err := mgorus.NewHooker(\"localhost:27017\", \"logrus\", \"log\")\n\tif err == nil {\n\t\tlog.Hooks.Add(hooker)\n\t\tlog.Info(\"MongoDB log ok\")\n\t}\n\n\tlog.Print(\"Simple print\")\n\tlog.Warn(\"warn\")\n\tlog.Info(\"some logging message\")\n\tlog.Debug(\"debug\")\n\tlog.Error(\"Is great error\")\n\tlog.Print(\"Сообщение на русском\")\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"name\": \"zhangsan\",\n\t\t\"age\":  28,\n\t}).Error(\"Hello world!\")\n\n\tlog.WithField(\"extra\", \"Is extra message\").WithField(\"date\", time.Now().String()).Info(\"Item\")\n\n\ttime.Sleep(time.Second) \/\/ Ждём одну секунду, что бы логи вывалились в graylog\n\n}\n<commit_msg>logrus write to sentry<commit_after>package main\n\nimport (\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/evalphobia\/logrus_sentry\"\n\t\"github.com\/getsentry\/raven-go\"\n\t\"github.com\/plumbum\/mgorus\"\n\t\"time\"\n)\n\ntype HS map[string]string\n\nfunc main() {\n\n\t\/\/ log.SetFormatter(&log.JSONFormatter{})\n\t\/\/ log.SetOutput(os.Stderr)\n\n\tlog := logrus.New()\n\tlog.Level = logrus.DebugLevel\n\t\/*\n\t\thook := graylog.NewGraylogHook(\"127.0.0.1:12201\", \"myFacility\", map[string]interface{}{\"startTime\": time.Now().String()})\n\t\tlog.Hooks.Add(hook)\n\t*\/\n\n\travenClient, err := raven.New(\"http:\/\/78d5df1b220e47958c28fbab30ac92d5:db59624047fd4616939520e684a62dd7@172.17.0.5:9000\/2\")\n\tif err == nil {\n\t\travenClient.CaptureMessage(\"Запущен Sentry\", HS{\"tag1\": \"one\", \"tag2\": \"two\"})\n\t\thookSentry, err := logrus_sentry.NewWithClientSentryHook(\n\t\t\travenClient,\n\t\t\t[]logrus.Level{\n\t\t\t\tlogrus.PanicLevel,\n\t\t\t\tlogrus.FatalLevel,\n\t\t\t\tlogrus.ErrorLevel,\n\t\t\t})\n\t\tif err == nil {\n\t\t\tlog.Hooks.Add(hookSentry)\n\t\t\tlog.Info(\"Sentry logger OK\")\n\t\t\travenClient.CaptureMessage(\"Подключили Sentry к логу\", HS{\"tag1\": \"one\", \"tag2\": \"two\"})\n\t\t} else {\n\t\t\tlog.Warn(\"Can't create Sentry hook: \", err)\n\t\t}\n\n\n\t\travenClient.CapturePanic(func () {\n\t\t\tpanic(\"Здесь перехватываем панику\")\n\t\t}, HS{\"status\": \"panic\"})\n\n\t\travenClient.\n\n\t} else {\n\t\tlog.Warn(\"Can't connect to Sentry: \", err)\n\t}\n\n\thookMongo, err := mgorus.NewHooker(\"localhost:27017\", \"logrus\", \"log\")\n\tif err == nil {\n\t\tlog.Hooks.Add(hookMongo)\n\t\tlog.Info(\"MongoDB logger OK\")\n\t} else {\n\t\tlog.Warn(\"Can't create Mongo hook\", err)\n\t}\n\n\tlog.Print(\"Simple print\")\n\tlog.Warn(\"warn\")\n\tlog.Info(\"some logging message\")\n\tlog.Debug(\"debug\")\n\ttime.Sleep(time.Second) \/\/ Ждём одну секунду, что бы логи вывалились в graylog\n\tlog.Error(\"Is great error\")\n\tlog.WithField(\"lang\", \"ru-RU\").Print(\"Сообщение на русском\")\n\n\tlog.WithFields(logrus.Fields{\n\t\t\"name\": \"zhangsan\",\n\t\t\"age\":  28,\n\t}).Error(\"Hello world!\")\n\n\tlog.WithField(\"extra\", \"Is extra message\").WithField(\"date\", time.Now().String()).Info(\"Item\")\n\n\travenClient.Wait()\n\ttime.Sleep(time.Second) \/\/ Ждём одну секунду, что бы логи вывалились в graylog\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cluster\n\nimport (\n\t\"github.com\/docker\/machine\/drivers\/vmwarefusion\"\n\t\"github.com\/docker\/machine\/libmachine\/drivers\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/constants\"\n)\n\nfunc createVMwareFusionHost(config MachineConfig) drivers.Driver {\n\td := vmwarefusion.NewDriver(constants.MachineName, constants.Minipath).(*vmwarefusion.Driver)\n\td.Boot2DockerURL = config.GetISOFileURI()\n\td.Memory = config.Memory\n\td.CPU = config.CPUs\n\n\t\/\/ TODO(philips): push these defaults upstream to fixup this driver\n\td.SSHPort = 22\n\td.ISO = d.ResolveStorePath(\"boot2docker.iso\")\n\treturn d\n}\n\ntype xhyveDriver struct {\n\t*drivers.BaseDriver\n\tBoot2DockerURL string\n\tBootCmd        string\n\tCPU            int\n\tCaCertPath     string\n\tDiskSize       int64\n\tMacAddr        string\n\tMemory         int\n\tPrivateKeyPath string\n\tUUID           string\n\tNFSShare       bool\n\tDiskNumber     int\n\tVirtio9p       bool\n\tVirtio9pFolder string\n}\n\nfunc createXhyveHost(config MachineConfig) *xhyveDriver {\n\treturn &xhyveDriver{\n\t\tBaseDriver: &drivers.BaseDriver{\n\t\t\tMachineName: constants.MachineName,\n\t\t\tStorePath:   constants.Minipath,\n\t\t},\n\t\tMemory:         config.Memory,\n\t\tCPU:            config.CPUs,\n\t\tBoot2DockerURL: config.GetISOFileURI(),\n\t\tBootCmd:        \"loglevel=3 user=docker console=ttyS0 console=tty0 noembed nomodeset norestore waitusb=10 base host=boot2docker\",\n\t\tDiskSize:       int64(config.DiskSize),\n\t\tVirtio9p:       true,\n\t\tVirtio9pFolder: \"\/Users\",\n\t}\n}\n<commit_msg>Ensures that we get the same IP between start\/delete<commit_after>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cluster\n\nimport (\n\t\"github.com\/docker\/machine\/drivers\/vmwarefusion\"\n\t\"github.com\/docker\/machine\/libmachine\/drivers\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/constants\"\n)\n\n\/\/ Ensures that we get assigned the same IP across deletes\/starts\nconst xhyveUUID = \"57FD2012-FA4A-4FF7-AEFF-26E1A1D76847\"\n\nfunc createVMwareFusionHost(config MachineConfig) drivers.Driver {\n\td := vmwarefusion.NewDriver(constants.MachineName, constants.Minipath).(*vmwarefusion.Driver)\n\td.Boot2DockerURL = config.GetISOFileURI()\n\td.Memory = config.Memory\n\td.CPU = config.CPUs\n\n\t\/\/ TODO(philips): push these defaults upstream to fixup this driver\n\td.SSHPort = 22\n\td.ISO = d.ResolveStorePath(\"boot2docker.iso\")\n\treturn d\n}\n\ntype xhyveDriver struct {\n\t*drivers.BaseDriver\n\tBoot2DockerURL string\n\tBootCmd        string\n\tCPU            int\n\tCaCertPath     string\n\tDiskSize       int64\n\tMacAddr        string\n\tMemory         int\n\tPrivateKeyPath string\n\tUUID           string\n\tNFSShare       bool\n\tDiskNumber     int\n\tVirtio9p       bool\n\tVirtio9pFolder string\n}\n\nfunc createXhyveHost(config MachineConfig) *xhyveDriver {\n\treturn &xhyveDriver{\n\t\tBaseDriver: &drivers.BaseDriver{\n\t\t\tMachineName: constants.MachineName,\n\t\t\tStorePath:   constants.Minipath,\n\t\t},\n\t\tMemory:         config.Memory,\n\t\tCPU:            config.CPUs,\n\t\tBoot2DockerURL: config.GetISOFileURI(),\n\t\tBootCmd:        \"loglevel=3 user=docker console=ttyS0 console=tty0 noembed nomodeset norestore waitusb=10 base host=boot2docker\",\n\t\tDiskSize:       int64(config.DiskSize),\n\t\tVirtio9p:       true,\n\t\tVirtio9pFolder: \"\/Users\",\n\t\tUUID:           xhyveUUID,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package lfs\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar (\n\tv1Aliases = []string{\n\t\t\"http:\/\/git-media.io\/v\/2\",            \/\/ alpha\n\t\t\"https:\/\/hawser.github.com\/spec\/v1\",  \/\/ pre-release\n\t\t\"https:\/\/git-lfs.github.com\/spec\/v1\", \/\/ public launch\n\t}\n\tlatest      = \"https:\/\/git-lfs.github.com\/spec\/v1\"\n\toidType     = \"sha256\"\n\toidRE       = regexp.MustCompile(`\\A[[:alnum:]]{64}`)\n\tmatcherRE   = regexp.MustCompile(\"git-media|hawser|git-lfs\")\n\textRE       = regexp.MustCompile(`\\Aext-\\d{1}-\\w+`)\n\tpointerKeys = []string{\"version\", \"oid\", \"size\"}\n)\n\ntype Pointer struct {\n\tVersion    string\n\tOid        string\n\tSize       int64\n\tOidType    string\n\tExtensions []*PointerExtension\n}\n\n\/\/ A PointerExtension is parsed from the Git LFS Pointer file.\ntype PointerExtension struct {\n\tName     string\n\tPriority int\n\tOid      string\n\tOidType  string\n}\n\ntype ByPriority []*PointerExtension\n\nfunc (p ByPriority) Len() int           { return len(p) }\nfunc (p ByPriority) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }\nfunc (p ByPriority) Less(i, j int) bool { return p[i].Priority < p[j].Priority }\n\nfunc NewPointer(oid string, size int64, exts []*PointerExtension) *Pointer {\n\treturn &Pointer{latest, oid, size, oidType, exts}\n}\n\nfunc NewPointerExtension(name string, priority int, oid string) *PointerExtension {\n\treturn &PointerExtension{name, priority, oid, oidType}\n}\n\nfunc (p *Pointer) Smudge(writer io.Writer, workingfile string, download bool, cb CopyCallback) error {\n\treturn PointerSmudge(writer, p, workingfile, download, cb)\n}\n\nfunc (p *Pointer) Encode(writer io.Writer) (int, error) {\n\treturn EncodePointer(writer, p)\n}\n\nfunc (p *Pointer) Encoded() string {\n\tvar buffer bytes.Buffer\n\tif p.Size != 0 {\n\t\tbuffer.WriteString(fmt.Sprintf(\"version %s\\n\", latest))\n\t\tfor _, ext := range p.Extensions {\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"ext-%d-%s %s:%s\\n\", ext.Priority, ext.Name, ext.OidType, ext.Oid))\n\t\t}\n\t\tbuffer.WriteString(fmt.Sprintf(\"oid %s:%s\\n\", p.OidType, p.Oid))\n\t\tbuffer.WriteString(fmt.Sprintf(\"size %d\\n\", p.Size))\n\t}\n\treturn buffer.String()\n}\n\nfunc EncodePointer(writer io.Writer, pointer *Pointer) (int, error) {\n\treturn writer.Write([]byte(pointer.Encoded()))\n}\n\nfunc DecodePointerFromFile(file string) (*Pointer, error) {\n\t\/\/ Check size before reading\n\tstat, err := os.Stat(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif stat.Size() > blobSizeCutoff {\n\t\treturn nil, newNotAPointerError(nil)\n\t}\n\tf, err := os.OpenFile(file, os.O_RDONLY, 0644)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treturn DecodePointer(f)\n}\nfunc DecodePointer(reader io.Reader) (*Pointer, error) {\n\t_, p, err := DecodeFrom(reader)\n\treturn p, err\n}\n\nfunc DecodeFrom(reader io.Reader) ([]byte, *Pointer, error) {\n\tbuf := make([]byte, blobSizeCutoff)\n\twritten, err := reader.Read(buf)\n\toutput := buf[0:written]\n\n\tif err != nil {\n\t\treturn output, nil, err\n\t}\n\n\tp, err := decodeKV(bytes.TrimSpace(output))\n\treturn output, p, err\n}\n\nfunc verifyVersion(version string) error {\n\tif len(version) == 0 {\n\t\treturn newNotAPointerError(errors.New(\"Missing version\"))\n\t}\n\n\tfor _, v := range v1Aliases {\n\t\tif v == version {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn errors.New(\"Invalid version: \" + version)\n}\n\nfunc decodeKV(data []byte) (*Pointer, error) {\n\tkvps, exts, err := decodeKVData(data)\n\tif err != nil {\n\t\tif IsBadPointerKeyError(err) {\n\t\t\tbadErr := err.(badPointerKeyError)\n\t\t\tif badErr.Expected == \"version\" {\n\t\t\t\treturn nil, newNotAPointerError(err)\n\t\t\t}\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif err := verifyVersion(kvps[\"version\"]); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalue, ok := kvps[\"oid\"]\n\tif !ok {\n\t\treturn nil, errors.New(\"Invalid Oid\")\n\t}\n\n\toid, err := parseOid(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalue, ok = kvps[\"size\"]\n\tsize, err := strconv.ParseInt(value, 10, 0)\n\tif err != nil || size < 0 {\n\t\treturn nil, fmt.Errorf(\"Invalid size: %q\", value)\n\t}\n\n\tvar extensions []*PointerExtension\n\tif exts != nil {\n\t\tfor key, value := range exts {\n\t\t\text, err := parsePointerExtension(key, value)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\textensions = append(extensions, ext)\n\t\t}\n\t\tif err = validatePointerExtensions(extensions); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsort.Sort(ByPriority(extensions))\n\t}\n\n\treturn NewPointer(oid, size, extensions), nil\n}\n\nfunc parseOid(value string) (string, error) {\n\tparts := strings.SplitN(value, \":\", 2)\n\tif len(parts) != 2 {\n\t\treturn \"\", errors.New(\"Invalid Oid value: \" + value)\n\t}\n\tif parts[0] != oidType {\n\t\treturn \"\", errors.New(\"Invalid Oid type: \" + parts[0])\n\t}\n\toid := parts[1]\n\tif !oidRE.Match([]byte(oid)) {\n\t\treturn \"\", errors.New(\"Invalid Oid: \" + oid)\n\t}\n\treturn oid, nil\n}\n\nfunc parsePointerExtension(key string, value string) (*PointerExtension, error) {\n\tkeyParts := strings.SplitN(key, \"-\", 3)\n\tif len(keyParts) != 3 || keyParts[0] != \"ext\" {\n\t\treturn nil, errors.New(\"Invalid extension value: \" + value)\n\t}\n\n\tp, err := strconv.Atoi(keyParts[1])\n\tif err != nil || p < 0 {\n\t\treturn nil, errors.New(\"Invalid priority: \" + keyParts[1])\n\t}\n\n\tname := keyParts[2]\n\n\toid, err := parseOid(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewPointerExtension(name, p, oid), nil\n}\n\nfunc validatePointerExtensions(exts []*PointerExtension) error {\n\tm := make(map[int]struct{})\n\tfor _, ext := range exts {\n\t\tif _, exist := m[ext.Priority]; exist {\n\t\t\treturn fmt.Errorf(\"Duplicate priority found: %d\", ext.Priority)\n\t\t}\n\t\tm[ext.Priority] = struct{}{}\n\t}\n\treturn nil\n}\n\nfunc decodeKVData(data []byte) (kvps map[string]string, exts map[string]string, err error) {\n\tkvps = make(map[string]string)\n\n\tif !matcherRE.Match(data) {\n\t\terr = newNotAPointerError(err)\n\t\treturn\n\t}\n\n\tscanner := bufio.NewScanner(bytes.NewBuffer(data))\n\tline := 0\n\tnumKeys := len(pointerKeys)\n\tfor scanner.Scan() {\n\t\ttext := scanner.Text()\n\t\tif len(text) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := strings.SplitN(text, \" \", 2)\n\t\tif len(parts) < 2 {\n\t\t\terr = fmt.Errorf(\"Error reading line %d: %s\", line, text)\n\t\t\treturn\n\t\t}\n\n\t\tkey := parts[0]\n\t\tvalue := parts[1]\n\n\t\tif numKeys <= line {\n\t\t\terr = fmt.Errorf(\"Extra line: %s\", text)\n\t\t\treturn\n\t\t}\n\n\t\tif expected := pointerKeys[line]; key != expected {\n\t\t\tif !extRE.Match([]byte(key)) {\n\t\t\t\terr = newBadPointerKeyError(expected, key)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif exts == nil {\n\t\t\t\texts = make(map[string]string)\n\t\t\t}\n\t\t\texts[key] = value\n\t\t\tcontinue\n\t\t}\n\n\t\tline += 1\n\t\tkvps[key] = value\n\t}\n\n\terr = scanner.Err()\n\treturn\n}\n<commit_msg>Return empty buffer early on empty string<commit_after>package lfs\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar (\n\tv1Aliases = []string{\n\t\t\"http:\/\/git-media.io\/v\/2\",            \/\/ alpha\n\t\t\"https:\/\/hawser.github.com\/spec\/v1\",  \/\/ pre-release\n\t\t\"https:\/\/git-lfs.github.com\/spec\/v1\", \/\/ public launch\n\t}\n\tlatest      = \"https:\/\/git-lfs.github.com\/spec\/v1\"\n\toidType     = \"sha256\"\n\toidRE       = regexp.MustCompile(`\\A[[:alnum:]]{64}`)\n\tmatcherRE   = regexp.MustCompile(\"git-media|hawser|git-lfs\")\n\textRE       = regexp.MustCompile(`\\Aext-\\d{1}-\\w+`)\n\tpointerKeys = []string{\"version\", \"oid\", \"size\"}\n)\n\ntype Pointer struct {\n\tVersion    string\n\tOid        string\n\tSize       int64\n\tOidType    string\n\tExtensions []*PointerExtension\n}\n\n\/\/ A PointerExtension is parsed from the Git LFS Pointer file.\ntype PointerExtension struct {\n\tName     string\n\tPriority int\n\tOid      string\n\tOidType  string\n}\n\ntype ByPriority []*PointerExtension\n\nfunc (p ByPriority) Len() int           { return len(p) }\nfunc (p ByPriority) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }\nfunc (p ByPriority) Less(i, j int) bool { return p[i].Priority < p[j].Priority }\n\nfunc NewPointer(oid string, size int64, exts []*PointerExtension) *Pointer {\n\treturn &Pointer{latest, oid, size, oidType, exts}\n}\n\nfunc NewPointerExtension(name string, priority int, oid string) *PointerExtension {\n\treturn &PointerExtension{name, priority, oid, oidType}\n}\n\nfunc (p *Pointer) Smudge(writer io.Writer, workingfile string, download bool, cb CopyCallback) error {\n\treturn PointerSmudge(writer, p, workingfile, download, cb)\n}\n\nfunc (p *Pointer) Encode(writer io.Writer) (int, error) {\n\treturn EncodePointer(writer, p)\n}\n\nfunc (p *Pointer) Encoded() string {\n\tvar buffer bytes.Buffer\n\tif p.Size == 0 {\n\t\treturn buffer.String()\n\t}\n\n\tbuffer.WriteString(fmt.Sprintf(\"version %s\\n\", latest))\n\tfor _, ext := range p.Extensions {\n\t\tbuffer.WriteString(fmt.Sprintf(\"ext-%d-%s %s:%s\\n\", ext.Priority, ext.Name, ext.OidType, ext.Oid))\n\t}\n\tbuffer.WriteString(fmt.Sprintf(\"oid %s:%s\\n\", p.OidType, p.Oid))\n\tbuffer.WriteString(fmt.Sprintf(\"size %d\\n\", p.Size))\n\treturn buffer.String()\n}\n\nfunc EncodePointer(writer io.Writer, pointer *Pointer) (int, error) {\n\treturn writer.Write([]byte(pointer.Encoded()))\n}\n\nfunc DecodePointerFromFile(file string) (*Pointer, error) {\n\t\/\/ Check size before reading\n\tstat, err := os.Stat(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif stat.Size() > blobSizeCutoff {\n\t\treturn nil, newNotAPointerError(nil)\n\t}\n\tf, err := os.OpenFile(file, os.O_RDONLY, 0644)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\treturn DecodePointer(f)\n}\nfunc DecodePointer(reader io.Reader) (*Pointer, error) {\n\t_, p, err := DecodeFrom(reader)\n\treturn p, err\n}\n\nfunc DecodeFrom(reader io.Reader) ([]byte, *Pointer, error) {\n\tbuf := make([]byte, blobSizeCutoff)\n\twritten, err := reader.Read(buf)\n\toutput := buf[0:written]\n\n\tif err != nil {\n\t\treturn output, nil, err\n\t}\n\n\tp, err := decodeKV(bytes.TrimSpace(output))\n\treturn output, p, err\n}\n\nfunc verifyVersion(version string) error {\n\tif len(version) == 0 {\n\t\treturn newNotAPointerError(errors.New(\"Missing version\"))\n\t}\n\n\tfor _, v := range v1Aliases {\n\t\tif v == version {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn errors.New(\"Invalid version: \" + version)\n}\n\nfunc decodeKV(data []byte) (*Pointer, error) {\n\tkvps, exts, err := decodeKVData(data)\n\tif err != nil {\n\t\tif IsBadPointerKeyError(err) {\n\t\t\tbadErr := err.(badPointerKeyError)\n\t\t\tif badErr.Expected == \"version\" {\n\t\t\t\treturn nil, newNotAPointerError(err)\n\t\t\t}\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif err := verifyVersion(kvps[\"version\"]); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalue, ok := kvps[\"oid\"]\n\tif !ok {\n\t\treturn nil, errors.New(\"Invalid Oid\")\n\t}\n\n\toid, err := parseOid(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvalue, ok = kvps[\"size\"]\n\tsize, err := strconv.ParseInt(value, 10, 0)\n\tif err != nil || size < 0 {\n\t\treturn nil, fmt.Errorf(\"Invalid size: %q\", value)\n\t}\n\n\tvar extensions []*PointerExtension\n\tif exts != nil {\n\t\tfor key, value := range exts {\n\t\t\text, err := parsePointerExtension(key, value)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\textensions = append(extensions, ext)\n\t\t}\n\t\tif err = validatePointerExtensions(extensions); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsort.Sort(ByPriority(extensions))\n\t}\n\n\treturn NewPointer(oid, size, extensions), nil\n}\n\nfunc parseOid(value string) (string, error) {\n\tparts := strings.SplitN(value, \":\", 2)\n\tif len(parts) != 2 {\n\t\treturn \"\", errors.New(\"Invalid Oid value: \" + value)\n\t}\n\tif parts[0] != oidType {\n\t\treturn \"\", errors.New(\"Invalid Oid type: \" + parts[0])\n\t}\n\toid := parts[1]\n\tif !oidRE.Match([]byte(oid)) {\n\t\treturn \"\", errors.New(\"Invalid Oid: \" + oid)\n\t}\n\treturn oid, nil\n}\n\nfunc parsePointerExtension(key string, value string) (*PointerExtension, error) {\n\tkeyParts := strings.SplitN(key, \"-\", 3)\n\tif len(keyParts) != 3 || keyParts[0] != \"ext\" {\n\t\treturn nil, errors.New(\"Invalid extension value: \" + value)\n\t}\n\n\tp, err := strconv.Atoi(keyParts[1])\n\tif err != nil || p < 0 {\n\t\treturn nil, errors.New(\"Invalid priority: \" + keyParts[1])\n\t}\n\n\tname := keyParts[2]\n\n\toid, err := parseOid(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewPointerExtension(name, p, oid), nil\n}\n\nfunc validatePointerExtensions(exts []*PointerExtension) error {\n\tm := make(map[int]struct{})\n\tfor _, ext := range exts {\n\t\tif _, exist := m[ext.Priority]; exist {\n\t\t\treturn fmt.Errorf(\"Duplicate priority found: %d\", ext.Priority)\n\t\t}\n\t\tm[ext.Priority] = struct{}{}\n\t}\n\treturn nil\n}\n\nfunc decodeKVData(data []byte) (kvps map[string]string, exts map[string]string, err error) {\n\tkvps = make(map[string]string)\n\n\tif !matcherRE.Match(data) {\n\t\terr = newNotAPointerError(err)\n\t\treturn\n\t}\n\n\tscanner := bufio.NewScanner(bytes.NewBuffer(data))\n\tline := 0\n\tnumKeys := len(pointerKeys)\n\tfor scanner.Scan() {\n\t\ttext := scanner.Text()\n\t\tif len(text) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := strings.SplitN(text, \" \", 2)\n\t\tif len(parts) < 2 {\n\t\t\terr = fmt.Errorf(\"Error reading line %d: %s\", line, text)\n\t\t\treturn\n\t\t}\n\n\t\tkey := parts[0]\n\t\tvalue := parts[1]\n\n\t\tif numKeys <= line {\n\t\t\terr = fmt.Errorf(\"Extra line: %s\", text)\n\t\t\treturn\n\t\t}\n\n\t\tif expected := pointerKeys[line]; key != expected {\n\t\t\tif !extRE.Match([]byte(key)) {\n\t\t\t\terr = newBadPointerKeyError(expected, key)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif exts == nil {\n\t\t\t\texts = make(map[string]string)\n\t\t\t}\n\t\t\texts[key] = value\n\t\t\tcontinue\n\t\t}\n\n\t\tline += 1\n\t\tkvps[key] = value\n\t}\n\n\terr = scanner.Err()\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/imdario\/mergo\"\n\t\"github.com\/mitchellh\/go-homedir\"\n\t\"github.com\/zackbloom\/go-ini\"\n\t\"github.com\/zackbloom\/goamz\/aws\"\n\t\"github.com\/zackbloom\/goamz\/cloudfront\"\n\t\"github.com\/zackbloom\/goamz\/iam\"\n\t\"github.com\/zackbloom\/goamz\/route53\"\n\t\"github.com\/zackbloom\/goamz\/s3\"\n\t\"gopkg.in\/yaml.v1\"\n)\n\nconst (\n\tLIMITED = 60\n\tFOREVER = 31556926\n)\n\nvar s3Session *s3.S3\nvar iamSession *iam.IAM\nvar r53Session *route53.Route53\nvar cfSession *cloudfront.CloudFront\n\nfunc getRegion(region string) aws.Region {\n\tregionS, ok := aws.Regions[region]\n\tif !ok {\n\t\tpanic(\"Region not found\")\n\t}\n\treturn regionS\n}\n\nfunc openS3(key, secret, region string) *s3.S3 {\n\tregionS := getRegion(region)\n\n\tauth := aws.Auth{\n\t\tAccessKey: key,\n\t\tSecretKey: secret,\n\t}\n\treturn s3.New(auth, regionS)\n}\n\nfunc openIAM(key, secret, region string) *iam.IAM {\n\tregionS := getRegion(region)\n\n\tauth := aws.Auth{\n\t\tAccessKey: key,\n\t\tSecretKey: secret,\n\t}\n\treturn iam.New(auth, regionS)\n}\n\nfunc openCloudFront(key, secret string) *cloudfront.CloudFront {\n\tauth := aws.Auth{\n\t\tAccessKey: key,\n\t\tSecretKey: secret,\n\t}\n\treturn cloudfront.NewCloudFront(auth)\n}\n\nfunc openRoute53(key, secret string) *route53.Route53 {\n\tauth := aws.Auth{\n\t\tAccessKey: key,\n\t\tSecretKey: secret,\n\t}\n\n\tr53, _ := route53.NewRoute53(auth)\n\treturn r53\n}\n\nfunc panicIf(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\nfunc must(val interface{}, err error) interface{} {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn val\n}\nfunc mustString(val string, err error) string {\n\tpanicIf(err)\n\treturn val\n}\nfunc mustInt(val int, err error) int {\n\tpanicIf(err)\n\treturn val\n}\n\ntype Options struct {\n\tFiles      string `yaml:\"files\"`\n\tRoot       string `yaml:\"root\"`\n\tDest       string `yaml:\"dest\"`\n\tConfigFile string `yaml:\"-\"`\n\tEnv        string `yaml:\"-\"`\n\tBucket     string `yaml:\"bucket\"`\n\tAWSKey     string `yaml:\"key\"`\n\tAWSSecret  string `yaml:\"secret\"`\n\tAWSRegion  string `yaml:\"region\"`\n\tNoUser     bool   `yaml:\"-\"`\n}\n\nfunc parseOptions() (o Options, set *flag.FlagSet) {\n\tset = flag.NewFlagSet(os.Args[1], flag.ExitOnError)\n\t\/\/TODO: Set set.Usage\n\n\tset.StringVar(&o.Files, \"files\", \"*\", \"Comma-seperated glob patterns of files to deploy (within root)\")\n\tset.StringVar(&o.Root, \"root\", \".\/\", \"The local directory to deploy\")\n\tset.StringVar(&o.Dest, \"dest\", \".\/\", \"The destination directory to write files to in the S3 bucket\")\n\tset.StringVar(&o.ConfigFile, \"config\", \"\", \"A yaml file to read configuration from\")\n\tset.StringVar(&o.Env, \"env\", \"\", \"The env to read from the config file\")\n\tset.StringVar(&o.Bucket, \"bucket\", \"\", \"The bucket to deploy to\")\n\tset.StringVar(&o.AWSKey, \"key\", \"\", \"The AWS key to use\")\n\tset.StringVar(&o.AWSSecret, \"secret\", \"\", \"The AWS secret of the provided key\")\n\tset.StringVar(&o.AWSRegion, \"region\", \"us-east-1\", \"The AWS region the S3 bucket is in\")\n\tset.BoolVar(&o.NoUser, \"no-user\", false, \"When creating, should we make a user account?\")\n\n\tset.Parse(os.Args[2:])\n\n\treturn\n}\n\ntype ConfigFile map[string]Options\n\nfunc loadConfigFile(o *Options) {\n\tisDefault := false\n\tconfigPath := o.ConfigFile\n\tif o.ConfigFile == \"\" {\n\t\tisDefault = true\n\t\tconfigPath = \".\/deploy.yaml\"\n\t}\n\n\tdata, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) && isDefault {\n\t\t\treturn\n\t\t}\n\n\t\tpanic(err)\n\t}\n\n\tvar file ConfigFile\n\terr = yaml.Unmarshal(data, &file)\n\tpanicIf(err)\n\n\tvar envCfg Options\n\tif o.Env != \"\" {\n\t\tvar ok bool\n\t\tenvCfg, ok = file[o.Env]\n\t\tif !ok {\n\t\t\tpanic(\"Config for specified env not found\")\n\t\t}\n\t}\n\n\tdefCfg, _ := file[\"default\"]\n\n\tpanicIf(mergo.Merge(o, defCfg))\n\tpanicIf(mergo.Merge(o, envCfg))\n}\n\nfunc addAWSConfig(o *Options) {\n\tif o.AWSKey == \"\" && o.AWSSecret == \"\" {\n\t\to.AWSKey, o.AWSSecret = loadAWSConfig()\n\t}\n}\n\ntype AWSConfig struct {\n\tDefault struct {\n\t\tAccessKey string `ini:\"aws_access_key_id\"`\n\t\tSecretKey string `ini:\"aws_secret_access_key\"`\n\t} `ini:\"[default]\"`\n}\n\nfunc loadAWSConfig() (access string, secret string) {\n\tcfg := AWSConfig{}\n\n\tpath, err := homedir.Expand(\"~\/.aws\/config\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tini.Unmarshal(content, &cfg)\n\n\treturn cfg.Default.AccessKey, cfg.Default.SecretKey\n}\n\nfunc copyFile(bucket *s3.Bucket, from string, to string, contentType string, maxAge int) {\n\tcopyOpts := s3.CopyOptions{\n\t\tMetadataDirective: \"REPLACE\",\n\t\tContentType:       contentType,\n\t\tOptions: s3.Options{\n\t\t\tCacheControl:    fmt.Sprintf(\"public, max-age=%d\", maxAge),\n\t\t\tContentEncoding: \"gzip\",\n\t\t},\n\t}\n\n\t_, err := bucket.PutCopy(to, s3.PublicRead, copyOpts, joinPath(bucket.Name, from))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nvar pathRe = regexp.MustCompile(\"\/{2,}\")\n\nfunc joinPath(parts ...string) string {\n\t\/\/ Like filepath.Join, but always uses '\/'\n\tout := filepath.Join(parts...)\n\n\tif os.PathSeparator != '\/' {\n\t\tout = strings.Replace(out, string(os.PathSeparator), \"\/\", -1)\n\t}\n\n\treturn out\n}\n<commit_msg>Also look in AWS Credentials file<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/imdario\/mergo\"\n\t\"github.com\/mitchellh\/go-homedir\"\n\t\"github.com\/zackbloom\/go-ini\"\n\t\"github.com\/zackbloom\/goamz\/aws\"\n\t\"github.com\/zackbloom\/goamz\/cloudfront\"\n\t\"github.com\/zackbloom\/goamz\/iam\"\n\t\"github.com\/zackbloom\/goamz\/route53\"\n\t\"github.com\/zackbloom\/goamz\/s3\"\n\t\"gopkg.in\/yaml.v1\"\n)\n\nconst (\n\tLIMITED = 60\n\tFOREVER = 31556926\n)\n\nvar s3Session *s3.S3\nvar iamSession *iam.IAM\nvar r53Session *route53.Route53\nvar cfSession *cloudfront.CloudFront\n\nfunc getRegion(region string) aws.Region {\n\tregionS, ok := aws.Regions[region]\n\tif !ok {\n\t\tpanic(\"Region not found\")\n\t}\n\treturn regionS\n}\n\nfunc openS3(key, secret, region string) *s3.S3 {\n\tregionS := getRegion(region)\n\n\tauth := aws.Auth{\n\t\tAccessKey: key,\n\t\tSecretKey: secret,\n\t}\n\treturn s3.New(auth, regionS)\n}\n\nfunc openIAM(key, secret, region string) *iam.IAM {\n\tregionS := getRegion(region)\n\n\tauth := aws.Auth{\n\t\tAccessKey: key,\n\t\tSecretKey: secret,\n\t}\n\treturn iam.New(auth, regionS)\n}\n\nfunc openCloudFront(key, secret string) *cloudfront.CloudFront {\n\tauth := aws.Auth{\n\t\tAccessKey: key,\n\t\tSecretKey: secret,\n\t}\n\treturn cloudfront.NewCloudFront(auth)\n}\n\nfunc openRoute53(key, secret string) *route53.Route53 {\n\tauth := aws.Auth{\n\t\tAccessKey: key,\n\t\tSecretKey: secret,\n\t}\n\n\tr53, _ := route53.NewRoute53(auth)\n\treturn r53\n}\n\nfunc panicIf(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\nfunc must(val interface{}, err error) interface{} {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn val\n}\nfunc mustString(val string, err error) string {\n\tpanicIf(err)\n\treturn val\n}\nfunc mustInt(val int, err error) int {\n\tpanicIf(err)\n\treturn val\n}\n\ntype Options struct {\n\tFiles      string `yaml:\"files\"`\n\tRoot       string `yaml:\"root\"`\n\tDest       string `yaml:\"dest\"`\n\tConfigFile string `yaml:\"-\"`\n\tEnv        string `yaml:\"-\"`\n\tBucket     string `yaml:\"bucket\"`\n\tAWSKey     string `yaml:\"key\"`\n\tAWSSecret  string `yaml:\"secret\"`\n\tAWSRegion  string `yaml:\"region\"`\n\tNoUser     bool   `yaml:\"-\"`\n}\n\nfunc parseOptions() (o Options, set *flag.FlagSet) {\n\tset = flag.NewFlagSet(os.Args[1], flag.ExitOnError)\n\t\/\/TODO: Set set.Usage\n\n\tset.StringVar(&o.Files, \"files\", \"*\", \"Comma-seperated glob patterns of files to deploy (within root)\")\n\tset.StringVar(&o.Root, \"root\", \".\/\", \"The local directory to deploy\")\n\tset.StringVar(&o.Dest, \"dest\", \".\/\", \"The destination directory to write files to in the S3 bucket\")\n\tset.StringVar(&o.ConfigFile, \"config\", \"\", \"A yaml file to read configuration from\")\n\tset.StringVar(&o.Env, \"env\", \"\", \"The env to read from the config file\")\n\tset.StringVar(&o.Bucket, \"bucket\", \"\", \"The bucket to deploy to\")\n\tset.StringVar(&o.AWSKey, \"key\", \"\", \"The AWS key to use\")\n\tset.StringVar(&o.AWSSecret, \"secret\", \"\", \"The AWS secret of the provided key\")\n\tset.StringVar(&o.AWSRegion, \"region\", \"us-east-1\", \"The AWS region the S3 bucket is in\")\n\tset.BoolVar(&o.NoUser, \"no-user\", false, \"When creating, should we make a user account?\")\n\n\tset.Parse(os.Args[2:])\n\n\treturn\n}\n\ntype ConfigFile map[string]Options\n\nfunc loadConfigFile(o *Options) {\n\tisDefault := false\n\tconfigPath := o.ConfigFile\n\tif o.ConfigFile == \"\" {\n\t\tisDefault = true\n\t\tconfigPath = \".\/deploy.yaml\"\n\t}\n\n\tdata, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) && isDefault {\n\t\t\treturn\n\t\t}\n\n\t\tpanic(err)\n\t}\n\n\tvar file ConfigFile\n\terr = yaml.Unmarshal(data, &file)\n\tpanicIf(err)\n\n\tvar envCfg Options\n\tif o.Env != \"\" {\n\t\tvar ok bool\n\t\tenvCfg, ok = file[o.Env]\n\t\tif !ok {\n\t\t\tpanic(\"Config for specified env not found\")\n\t\t}\n\t}\n\n\tdefCfg, _ := file[\"default\"]\n\n\tpanicIf(mergo.Merge(o, defCfg))\n\tpanicIf(mergo.Merge(o, envCfg))\n}\n\nfunc addAWSConfig(o *Options) {\n\tif o.AWSKey == \"\" && o.AWSSecret == \"\" {\n\t\to.AWSKey, o.AWSSecret = loadAWSConfig()\n\t}\n}\n\ntype AWSConfig struct {\n\tDefault struct {\n\t\tAccessKey string `ini:\"aws_access_key_id\"`\n\t\tSecretKey string `ini:\"aws_secret_access_key\"`\n\t} `ini:\"[default]\"`\n}\n\nfunc loadAWSConfig() (access string, secret string) {\n\tcfg := AWSConfig{}\n\n\tfor _, file := range []string{\"~\/.aws\/config\", \"~\/.aws\/credentials\"} {\n\t\tpath, err := homedir.Expand(file)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tcontent, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tini.Unmarshal(content, &cfg)\n\n\t\tif cfg.Default.AccessKey != \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn cfg.Default.AccessKey, cfg.Default.SecretKey\n}\n\nfunc copyFile(bucket *s3.Bucket, from string, to string, contentType string, maxAge int) {\n\tcopyOpts := s3.CopyOptions{\n\t\tMetadataDirective: \"REPLACE\",\n\t\tContentType:       contentType,\n\t\tOptions: s3.Options{\n\t\t\tCacheControl:    fmt.Sprintf(\"public, max-age=%d\", maxAge),\n\t\t\tContentEncoding: \"gzip\",\n\t\t},\n\t}\n\n\t_, err := bucket.PutCopy(to, s3.PublicRead, copyOpts, joinPath(bucket.Name, from))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nvar pathRe = regexp.MustCompile(\"\/{2,}\")\n\nfunc joinPath(parts ...string) string {\n\t\/\/ Like filepath.Join, but always uses '\/'\n\tout := filepath.Join(parts...)\n\n\tif os.PathSeparator != '\/' {\n\t\tout = strings.Replace(out, string(os.PathSeparator), \"\/\", -1)\n\t}\n\n\treturn out\n}\n<|endoftext|>"}
{"text":"<commit_before>package app\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/ugorji\/go\/codec\"\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/weaveworks\/scope\/common\/mtime\"\n\t\"github.com\/weaveworks\/scope\/report\"\n)\n\n\/\/ Reporter is something that can produce reports on demand. It's a convenient\n\/\/ interface for parts of the app, and several experimental components.\ntype Reporter interface {\n\tReport(context.Context) (report.Report, error)\n\tWaitOn(context.Context, chan struct{})\n\tUnWait(context.Context, chan struct{})\n}\n\n\/\/ Adder is something that can accept reports. It's a convenient interface for\n\/\/ parts of the app, and several experimental components.\ntype Adder interface {\n\tAdd(context.Context, report.Report) error\n}\n\n\/\/ A Collector is a Reporter and an Adder\ntype Collector interface {\n\tReporter\n\tAdder\n}\n\n\/\/ Collector receives published reports from multiple producers. It yields a\n\/\/ single merged report, representing all collected reports.\ntype collector struct {\n\tmtx        sync.Mutex\n\treports    []report.Report\n\ttimestamps []time.Time\n\twindow     time.Duration\n\tcached     *report.Report\n\tmerger     Merger\n\twaitableCondition\n}\n\ntype waitableCondition struct {\n\tsync.Mutex\n\twaiters map[chan struct{}]struct{}\n}\n\nfunc (wc *waitableCondition) WaitOn(_ context.Context, waiter chan struct{}) {\n\twc.Lock()\n\twc.waiters[waiter] = struct{}{}\n\twc.Unlock()\n}\n\nfunc (wc *waitableCondition) UnWait(_ context.Context, waiter chan struct{}) {\n\twc.Lock()\n\tdelete(wc.waiters, waiter)\n\twc.Unlock()\n}\n\nfunc (wc *waitableCondition) Broadcast() {\n\twc.Lock()\n\tfor waiter := range wc.waiters {\n\t\t\/\/ Non-block write to channel\n\t\tselect {\n\t\tcase waiter <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n\twc.Unlock()\n}\n\n\/\/ NewCollector returns a collector ready for use.\nfunc NewCollector(window time.Duration) Collector {\n\treturn &collector{\n\t\twindow: window,\n\t\twaitableCondition: waitableCondition{\n\t\t\twaiters: map[chan struct{}]struct{}{},\n\t\t},\n\t\tmerger: NewSmartMerger(),\n\t}\n}\n\n\/\/ Add adds a report to the collector's internal state. It implements Adder.\nfunc (c *collector) Add(_ context.Context, rpt report.Report) error {\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\tc.reports = append(c.reports, rpt)\n\tc.timestamps = append(c.timestamps, mtime.Now())\n\n\tc.clean()\n\tc.cached = nil\n\tif rpt.Shortcut {\n\t\tc.Broadcast()\n\t}\n\treturn nil\n}\n\n\/\/ Report returns a merged report over all added reports. It implements\n\/\/ Reporter.\nfunc (c *collector) Report(_ context.Context) (report.Report, error) {\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\n\t\/\/ If the oldest report is still within range,\n\t\/\/ and there is a cached report, return that.\n\tif c.cached != nil && len(c.reports) > 0 {\n\t\toldest := mtime.Now().Add(-c.window)\n\t\tif c.timestamps[0].After(oldest) {\n\t\t\treturn *c.cached, nil\n\t\t}\n\t}\n\n\tc.clean()\n\treturn c.merger.Merge(c.reports), nil\n}\n\nfunc (c *collector) clean() {\n\tvar (\n\t\tcleanedReports    = make([]report.Report, 0, len(c.reports))\n\t\tcleanedTimestamps = make([]time.Time, 0, len(c.timestamps))\n\t\toldest            = mtime.Now().Add(-c.window)\n\t)\n\tfor i, r := range c.reports {\n\t\tif c.timestamps[i].After(oldest) {\n\t\t\tcleanedReports = append(cleanedReports, r)\n\t\t\tcleanedTimestamps = append(cleanedTimestamps, c.timestamps[i])\n\t\t}\n\t}\n\tc.reports = cleanedReports\n\tc.timestamps = cleanedTimestamps\n}\n\n\/\/ StaticCollector always returns the given report.\ntype StaticCollector report.Report\n\n\/\/ Report returns a merged report over all added reports. It implements\n\/\/ Reporter.\nfunc (c StaticCollector) Report(context.Context) (report.Report, error) { return report.Report(c), nil }\n\n\/\/ Add adds a report to the collector's internal state. It implements Adder.\nfunc (c StaticCollector) Add(context.Context, report.Report) error { return nil }\n\n\/\/ WaitOn lets other conponents wait on a new report being received. It\n\/\/ implements Reporter.\nfunc (c StaticCollector) WaitOn(context.Context, chan struct{}) {}\n\n\/\/ UnWait lets other conponents stop waiting on a new report being received. It\n\/\/ implements Reporter.\nfunc (c StaticCollector) UnWait(context.Context, chan struct{}) {}\n\n\/\/ NewFileCollector reads and json parses the given path, returning a collector\n\/\/ which always returns that report.\nfunc NewFileCollector(path string) (Collector, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tvar (\n\t\trpt     report.Report\n\t\thandle  codec.Handle\n\t\tgzipped bool\n\t)\n\tfileType := filepath.Ext(path)\n\tif fileType == \".gz\" {\n\t\tgzipped = true\n\t\tfileType = filepath.Ext(strings.TrimSuffix(path, fileType))\n\t}\n\tswitch fileType {\n\tcase \".json\":\n\t\thandle = &codec.JsonHandle{}\n\tcase \".msgpack\":\n\t\thandle = &codec.MsgpackHandle{}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unsupported file extension: %v\", fileType)\n\t}\n\n\tif err := rpt.ReadBinary(f, gzipped, handle); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn StaticCollector(rpt), nil\n}\n<commit_msg>Review Feedback<commit_after>package app\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/ugorji\/go\/codec\"\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/weaveworks\/scope\/common\/mtime\"\n\t\"github.com\/weaveworks\/scope\/report\"\n)\n\n\/\/ Reporter is something that can produce reports on demand. It's a convenient\n\/\/ interface for parts of the app, and several experimental components.\ntype Reporter interface {\n\tReport(context.Context) (report.Report, error)\n\tWaitOn(context.Context, chan struct{})\n\tUnWait(context.Context, chan struct{})\n}\n\n\/\/ Adder is something that can accept reports. It's a convenient interface for\n\/\/ parts of the app, and several experimental components.\ntype Adder interface {\n\tAdd(context.Context, report.Report) error\n}\n\n\/\/ A Collector is a Reporter and an Adder\ntype Collector interface {\n\tReporter\n\tAdder\n}\n\n\/\/ Collector receives published reports from multiple producers. It yields a\n\/\/ single merged report, representing all collected reports.\ntype collector struct {\n\tmtx        sync.Mutex\n\treports    []report.Report\n\ttimestamps []time.Time\n\twindow     time.Duration\n\tcached     *report.Report\n\tmerger     Merger\n\twaitableCondition\n}\n\ntype waitableCondition struct {\n\tsync.Mutex\n\twaiters map[chan struct{}]struct{}\n}\n\nfunc (wc *waitableCondition) WaitOn(_ context.Context, waiter chan struct{}) {\n\twc.Lock()\n\twc.waiters[waiter] = struct{}{}\n\twc.Unlock()\n}\n\nfunc (wc *waitableCondition) UnWait(_ context.Context, waiter chan struct{}) {\n\twc.Lock()\n\tdelete(wc.waiters, waiter)\n\twc.Unlock()\n}\n\nfunc (wc *waitableCondition) Broadcast() {\n\twc.Lock()\n\tfor waiter := range wc.waiters {\n\t\t\/\/ Non-block write to channel\n\t\tselect {\n\t\tcase waiter <- struct{}{}:\n\t\tdefault:\n\t\t}\n\t}\n\twc.Unlock()\n}\n\n\/\/ NewCollector returns a collector ready for use.\nfunc NewCollector(window time.Duration) Collector {\n\treturn &collector{\n\t\twindow: window,\n\t\twaitableCondition: waitableCondition{\n\t\t\twaiters: map[chan struct{}]struct{}{},\n\t\t},\n\t\tmerger: NewSmartMerger(),\n\t}\n}\n\n\/\/ Add adds a report to the collector's internal state. It implements Adder.\nfunc (c *collector) Add(_ context.Context, rpt report.Report) error {\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\tc.reports = append(c.reports, rpt)\n\tc.timestamps = append(c.timestamps, mtime.Now())\n\n\tc.clean()\n\tc.cached = nil\n\tif rpt.Shortcut {\n\t\tc.Broadcast()\n\t}\n\treturn nil\n}\n\n\/\/ Report returns a merged report over all added reports. It implements\n\/\/ Reporter.\nfunc (c *collector) Report(_ context.Context) (report.Report, error) {\n\tc.mtx.Lock()\n\tdefer c.mtx.Unlock()\n\n\t\/\/ If the oldest report is still within range,\n\t\/\/ and there is a cached report, return that.\n\tif c.cached != nil && len(c.reports) > 0 {\n\t\toldest := mtime.Now().Add(-c.window)\n\t\tif c.timestamps[0].After(oldest) {\n\t\t\treturn *c.cached, nil\n\t\t}\n\t}\n\n\tc.clean()\n\treturn c.merger.Merge(c.reports), nil\n}\n\nfunc (c *collector) clean() {\n\tvar (\n\t\tcleanedReports    = make([]report.Report, 0, len(c.reports))\n\t\tcleanedTimestamps = make([]time.Time, 0, len(c.timestamps))\n\t\toldest            = mtime.Now().Add(-c.window)\n\t)\n\tfor i, r := range c.reports {\n\t\tif c.timestamps[i].After(oldest) {\n\t\t\tcleanedReports = append(cleanedReports, r)\n\t\t\tcleanedTimestamps = append(cleanedTimestamps, c.timestamps[i])\n\t\t}\n\t}\n\tc.reports = cleanedReports\n\tc.timestamps = cleanedTimestamps\n}\n\n\/\/ StaticCollector always returns the given report.\ntype StaticCollector report.Report\n\n\/\/ Report returns a merged report over all added reports. It implements\n\/\/ Reporter.\nfunc (c StaticCollector) Report(context.Context) (report.Report, error) { return report.Report(c), nil }\n\n\/\/ Add adds a report to the collector's internal state. It implements Adder.\nfunc (c StaticCollector) Add(context.Context, report.Report) error { return nil }\n\n\/\/ WaitOn lets other components wait on a new report being received. It\n\/\/ implements Reporter.\nfunc (c StaticCollector) WaitOn(context.Context, chan struct{}) {}\n\n\/\/ UnWait lets other components stop waiting on a new report being received. It\n\/\/ implements Reporter.\nfunc (c StaticCollector) UnWait(context.Context, chan struct{}) {}\n\n\/\/ NewFileCollector reads and parses the given path, returning a collector\n\/\/ which always returns that report.\nfunc NewFileCollector(path string) (Collector, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tvar (\n\t\trpt     report.Report\n\t\thandle  codec.Handle\n\t\tgzipped bool\n\t)\n\tfileType := filepath.Ext(path)\n\tif fileType == \".gz\" {\n\t\tgzipped = true\n\t\tfileType = filepath.Ext(strings.TrimSuffix(path, fileType))\n\t}\n\tswitch fileType {\n\tcase \".json\":\n\t\thandle = &codec.JsonHandle{}\n\tcase \".msgpack\":\n\t\thandle = &codec.MsgpackHandle{}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unsupported file extension: %v\", fileType)\n\t}\n\n\tif err := rpt.ReadBinary(f, gzipped, handle); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn StaticCollector(rpt), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright 2017 Comcast Cable Communications Management, LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\npackage main\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"time\"\n\n\t\"github.com\/Comcast\/webpa-common\/concurrent\"\n\t\"github.com\/Comcast\/webpa-common\/logging\"\n\t\"github.com\/Comcast\/webpa-common\/secure\"\n\t\"github.com\/Comcast\/webpa-common\/secure\/handler\"\n\t\"github.com\/Comcast\/webpa-common\/secure\/key\"\n\t\"github.com\/Comcast\/webpa-common\/server\"\n\t\"github.com\/Comcast\/webpa-common\/webhook\"\n\t\"github.com\/SermoDigital\/jose\/jwt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/justinas\/alice\"\n\t\"github.com\/spf13\/pflag\"\n\t\"github.com\/spf13\/viper\"\n)\n\nconst (\n\tapplicationName = \"caduceus\"\n\tDEFAULT_KEY_ID  = \"current\"\n)\n\n\/\/ getValidator returns validator for JWT tokens\nfunc getValidator(v *viper.Viper) (validator secure.Validator, err error) {\n\tdefault_validators := make(secure.Validators, 0, 0)\n\tvar jwtVals []JWTValidator\n\n\tv.UnmarshalKey(\"jwtValidators\", &jwtVals)\n\n\t\/\/ make sure there is at least one jwtValidator supplied\n\tif len(jwtVals) < 1 {\n\t\tvalidator = default_validators\n\t\treturn\n\t}\n\n\t\/\/ if a JWTKeys section was supplied, configure a JWS validator\n\t\/\/ and append it to the chain of validators\n\tvalidators := make(secure.Validators, 0, len(jwtVals))\n\n\tfor _, validatorDescriptor := range jwtVals {\n\t\tvar keyResolver key.Resolver\n\t\tkeyResolver, err = validatorDescriptor.Keys.NewResolver()\n\t\tif err != nil {\n\t\t\tvalidator = validators\n\t\t\treturn\n\t\t}\n\n\t\tvalidators = append(\n\t\t\tvalidators,\n\t\t\tsecure.JWSValidator{\n\t\t\t\tDefaultKeyId:  DEFAULT_KEY_ID,\n\t\t\t\tResolver:      keyResolver,\n\t\t\t\tJWTValidators: []*jwt.Validator{validatorDescriptor.Custom.New()},\n\t\t\t},\n\t\t)\n\t}\n\n\t\/\/ TODO: This should really be part of the unmarshalled validators somehow\n\tbasicAuth := v.GetStringSlice(\"authHeader\")\n\tfor _, authValue := range basicAuth {\n\t\tvalidators = append(\n\t\t\tvalidators,\n\t\t\tsecure.ExactMatchValidator(authValue),\n\t\t)\n\t}\n\n\tvalidator = validators\n\n\treturn\n}\n\n\/\/ caduceus is the driver function for Caduceus.  It performs everything main() would do,\n\/\/ except for obtaining the command-line arguments (which are passed to it).\n\nfunc caduceus(arguments []string) int {\n\tbeginCaduceus := time.Now()\n\n\tvar (\n\t\tf = pflag.NewFlagSet(applicationName, pflag.ContinueOnError)\n\t\tv = viper.New()\n\n\t\tlogger, metricsRegistry, webPA, err = server.Initialize(applicationName, arguments, f, v)\n\t)\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to initialize Viper environment: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tvar (\n\t\tinfoLog  = logging.Info(logger)\n\t\terrorLog = logging.Error(logger)\n\t\tdebugLog = logging.Debug(logger)\n\t)\n\n\tinfoLog.Log(\"configurationFile\", v.ConfigFileUsed())\n\n\tcaduceusConfig := new(CaduceusConfig)\n\terr = v.Unmarshal(caduceusConfig)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to unmarshal configuration data into struct: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tworkerPool := WorkerPoolFactory{\n\t\tNumWorkers: caduceusConfig.NumWorkerThreads,\n\t\tQueueSize:  caduceusConfig.JobQueueSize,\n\t}.New()\n\n\tmainCaduceusProfilerFactory := ServerProfilerFactory{\n\t\tFrequency: caduceusConfig.ProfilerFrequency,\n\t\tDuration:  caduceusConfig.ProfilerDuration,\n\t\tQueueSize: caduceusConfig.ProfilerQueueSize,\n\t\tLogger:    logger,\n\t}\n\n\t\/\/ here we create a profiler specifically for our main server handler\n\tcaduceusHandlerProfiler, err := mainCaduceusProfilerFactory.New(\"main\")\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to profiler for main caduceus handler: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tchildCaduceusProfilerFactory := mainCaduceusProfilerFactory\n\tchildCaduceusProfilerFactory.Parent = caduceusHandlerProfiler\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig:       &tls.Config{InsecureSkipVerify: true},\n\t\tMaxIdleConnsPerHost:   caduceusConfig.SenderNumWorkersPerSender,\n\t\tResponseHeaderTimeout: 10 * time.Second, \/\/ TODO Make this configurable\n\t}\n\n\ttimeout := time.Duration(caduceusConfig.SenderClientTimeout) * time.Second\n\n\t\/\/ declare a new sender wrapper and pass it a profiler factory so that it can create\n\t\/\/ unique profilers on a per outboundSender basis\n\tcaduceusSenderWrapper, err := SenderWrapperFactory{\n\t\tNumWorkersPerSender: caduceusConfig.SenderNumWorkersPerSender,\n\t\tQueueSizePerSender:  caduceusConfig.SenderQueueSizePerSender,\n\t\tCutOffPeriod:        time.Duration(caduceusConfig.SenderCutOffPeriod) * time.Second,\n\t\tLinger:              time.Duration(caduceusConfig.SenderLinger) * time.Second,\n\t\tProfilerFactory:     childCaduceusProfilerFactory,\n\t\tLogger:              logger,\n\t\tClient:              &http.Client{Transport: tr, Timeout: timeout},\n\t}.New()\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to initialize new caduceus sender wrapper: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tserverWrapper := &ServerHandler{\n\t\tLogger: logger,\n\t\tcaduceusHandler: &CaduceusHandler{\n\t\t\thandlerProfiler: caduceusHandlerProfiler,\n\t\t\tsenderWrapper:   caduceusSenderWrapper,\n\t\t\tLogger:          logger,\n\t\t},\n\t\tdoJob: workerPool.Send,\n\t}\n\n\tprofileWrapper := &ProfileHandler{\n\t\tprofilerData: caduceusHandlerProfiler,\n\t\tLogger:       logger,\n\t}\n\n\tvalidator, err := getValidator(v)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Validator error: %v\\n\", err)\n\t\treturn 1\n\t}\n\n\tauthHandler := handler.AuthorizationHandler{\n\t\tHeaderName:          \"Authorization\",\n\t\tForbiddenStatusCode: 403,\n\t\tValidator:           validator,\n\t\tLogger:              logger,\n\t}\n\n\tcaduceusHandler := alice.New(authHandler.Decorate, TrackEmptyRequestBody(metricsRegistry))\n\n\trouter := mux.NewRouter()\n\n\trouter = configServerRouter(router, caduceusHandler, serverWrapper)\n\n\trouter.Handle(\"\/api\/v3\/profile\", caduceusHandler.Then(profileWrapper))\n\n\twebhookFactory, err := webhook.NewFactory(v)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error creating new webhook factory: %s\\n\", err)\n\t\treturn 1\n\t}\n\twebhookRegistry, webhookHandler := webhookFactory.NewRegistryAndHandler()\n\twebhookFactory.SetExternalUpdate(caduceusSenderWrapper.Update)\n\n\t\/\/ register webhook end points for api\n\trouter.Handle(\"\/hook\", caduceusHandler.ThenFunc(webhookRegistry.UpdateRegistry))\n\trouter.Handle(\"\/hooks\", caduceusHandler.ThenFunc(webhookRegistry.GetRegistry))\n\n\tselfURL := &url.URL{\n\t\tScheme: \"https\",\n\t\tHost:   v.GetString(\"fqdn\") + v.GetString(\"primary.address\"),\n\t}\n\n\twebhookFactory.Initialize(router, selfURL, webhookHandler, logger, nil)\n\n\tcaduceusHealth := &CaduceusHealth{}\n\tvar runnable concurrent.Runnable\n\n\tcaduceusHealth.Monitor, runnable = webPA.Prepare(logger, nil, metricsRegistry, router)\n\tserverWrapper.caduceusHealth = caduceusHealth\n\n\twaitGroup, shutdown, err := concurrent.Execute(runnable)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to start device manager: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tvar messageKey = logging.MessageKey()\n\n\tdebugLog.Log(messageKey, \"Calling webhookFactory.PrepareAndStart\")\n\tbeginPrepStart := time.Now()\n\twebhookFactory.PrepareAndStart()\n\tdebugLog.Log(messageKey, \"WebhookFactory.PrepareAndStart done.\", \"elapsedTime\", time.Since(beginPrepStart))\n\n\t\/\/ Attempt to obtain the current listener list from current system without having to wait for listener reregistration.\n\tdebugLog.Log(messageKey, \"Attempting to obtain current listener list from source\", \"source\",\n\t\tv.GetString(\"start.apiPath\"))\n\tbeginObtainList := time.Now()\n\tstartChan := make(chan webhook.Result, 1)\n\twebhookFactory.Start.GetCurrentSystemsHooks(startChan)\n\tvar webhookStartResults webhook.Result = <-startChan\n\tif webhookStartResults.Error != nil {\n\t\terrorLog.Log(logging.ErrorKey(), webhookStartResults.Error)\n\t} else {\n\t\t\/\/ todo: add message\n\t\twebhookFactory.SetList(webhook.NewList(webhookStartResults.Hooks))\n\t\tcaduceusSenderWrapper.Update(webhookStartResults.Hooks)\n\t}\n\tdebugLog.Log(messageKey, \"Current listener retrieval.\", \"elapsedTime\", time.Since(beginObtainList))\n\n\tinfoLog.Log(messageKey, \"Caduceus is up and running!\", \"elapsedTime\", time.Since(beginCaduceus))\n\n\tvar (\n\t\tsignals = make(chan os.Signal, 1)\n\t)\n\n\tsignal.Notify(signals)\n\t<-signals\n\tclose(shutdown)\n\twaitGroup.Wait()\n\n\t\/\/ shutdown the sender wrapper gently so that all queued messages get serviced\n\tcaduceusSenderWrapper.Shutdown(true)\n\n\treturn 0\n}\n\nfunc configServerRouter(router *mux.Router, caduceusHandler alice.Chain, serverWrapper *ServerHandler) *mux.Router {\n\tvar singleContentType = func(r *http.Request, _ *mux.RouteMatch) bool {\n\t\treturn len(r.Header[\"Content-Type\"]) == 1 \/\/require single specification for Content-Type Header\n\t}\n\n\trouter.Handle(\"\/api\/v3\/notify\", caduceusHandler.Then(serverWrapper)).Methods(\"POST\").\n\t\tHeadersRegexp(\"Content-Type\", \"application\/(json|msgpack)\").MatcherFunc(singleContentType)\n\n\t\/\/ Support the old endpoint too.\n\trouter.Handle(\"\/api\/v2\/notify\/{deviceid}\/event\/{eventtype:.*}\", caduceusHandler.Then(serverWrapper)).\n\t\tMethods(\"POST\").HeadersRegexp(\"Content-Type\", \"application\/(json|msgpack)\").\n\t\tMatcherFunc(singleContentType)\n\n\treturn router\n}\n\nfunc main() {\n\tos.Exit(caduceus(os.Args))\n}\n<commit_msg>Forgot this: add the module metrics<commit_after>\/**\n * Copyright 2017 Comcast Cable Communications Management, LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\npackage main\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"time\"\n\n\t\"github.com\/Comcast\/webpa-common\/concurrent\"\n\t\"github.com\/Comcast\/webpa-common\/logging\"\n\t\"github.com\/Comcast\/webpa-common\/secure\"\n\t\"github.com\/Comcast\/webpa-common\/secure\/handler\"\n\t\"github.com\/Comcast\/webpa-common\/secure\/key\"\n\t\"github.com\/Comcast\/webpa-common\/server\"\n\t\"github.com\/Comcast\/webpa-common\/webhook\"\n\t\"github.com\/SermoDigital\/jose\/jwt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/justinas\/alice\"\n\t\"github.com\/spf13\/pflag\"\n\t\"github.com\/spf13\/viper\"\n)\n\nconst (\n\tapplicationName = \"caduceus\"\n\tDEFAULT_KEY_ID  = \"current\"\n)\n\n\/\/ getValidator returns validator for JWT tokens\nfunc getValidator(v *viper.Viper) (validator secure.Validator, err error) {\n\tdefault_validators := make(secure.Validators, 0, 0)\n\tvar jwtVals []JWTValidator\n\n\tv.UnmarshalKey(\"jwtValidators\", &jwtVals)\n\n\t\/\/ make sure there is at least one jwtValidator supplied\n\tif len(jwtVals) < 1 {\n\t\tvalidator = default_validators\n\t\treturn\n\t}\n\n\t\/\/ if a JWTKeys section was supplied, configure a JWS validator\n\t\/\/ and append it to the chain of validators\n\tvalidators := make(secure.Validators, 0, len(jwtVals))\n\n\tfor _, validatorDescriptor := range jwtVals {\n\t\tvar keyResolver key.Resolver\n\t\tkeyResolver, err = validatorDescriptor.Keys.NewResolver()\n\t\tif err != nil {\n\t\t\tvalidator = validators\n\t\t\treturn\n\t\t}\n\n\t\tvalidators = append(\n\t\t\tvalidators,\n\t\t\tsecure.JWSValidator{\n\t\t\t\tDefaultKeyId:  DEFAULT_KEY_ID,\n\t\t\t\tResolver:      keyResolver,\n\t\t\t\tJWTValidators: []*jwt.Validator{validatorDescriptor.Custom.New()},\n\t\t\t},\n\t\t)\n\t}\n\n\t\/\/ TODO: This should really be part of the unmarshalled validators somehow\n\tbasicAuth := v.GetStringSlice(\"authHeader\")\n\tfor _, authValue := range basicAuth {\n\t\tvalidators = append(\n\t\t\tvalidators,\n\t\t\tsecure.ExactMatchValidator(authValue),\n\t\t)\n\t}\n\n\tvalidator = validators\n\n\treturn\n}\n\n\/\/ caduceus is the driver function for Caduceus.  It performs everything main() would do,\n\/\/ except for obtaining the command-line arguments (which are passed to it).\n\nfunc caduceus(arguments []string) int {\n\tbeginCaduceus := time.Now()\n\n\tvar (\n\t\tf = pflag.NewFlagSet(applicationName, pflag.ContinueOnError)\n\t\tv = viper.New()\n\n\t\tlogger, metricsRegistry, webPA, err = server.Initialize(applicationName, arguments, f, v, Metrics)\n\t)\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to initialize Viper environment: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tvar (\n\t\tinfoLog  = logging.Info(logger)\n\t\terrorLog = logging.Error(logger)\n\t\tdebugLog = logging.Debug(logger)\n\t)\n\n\tinfoLog.Log(\"configurationFile\", v.ConfigFileUsed())\n\n\tcaduceusConfig := new(CaduceusConfig)\n\terr = v.Unmarshal(caduceusConfig)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to unmarshal configuration data into struct: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tworkerPool := WorkerPoolFactory{\n\t\tNumWorkers: caduceusConfig.NumWorkerThreads,\n\t\tQueueSize:  caduceusConfig.JobQueueSize,\n\t}.New()\n\n\tmainCaduceusProfilerFactory := ServerProfilerFactory{\n\t\tFrequency: caduceusConfig.ProfilerFrequency,\n\t\tDuration:  caduceusConfig.ProfilerDuration,\n\t\tQueueSize: caduceusConfig.ProfilerQueueSize,\n\t\tLogger:    logger,\n\t}\n\n\t\/\/ here we create a profiler specifically for our main server handler\n\tcaduceusHandlerProfiler, err := mainCaduceusProfilerFactory.New(\"main\")\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to profiler for main caduceus handler: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tchildCaduceusProfilerFactory := mainCaduceusProfilerFactory\n\tchildCaduceusProfilerFactory.Parent = caduceusHandlerProfiler\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig:       &tls.Config{InsecureSkipVerify: true},\n\t\tMaxIdleConnsPerHost:   caduceusConfig.SenderNumWorkersPerSender,\n\t\tResponseHeaderTimeout: 10 * time.Second, \/\/ TODO Make this configurable\n\t}\n\n\ttimeout := time.Duration(caduceusConfig.SenderClientTimeout) * time.Second\n\n\t\/\/ declare a new sender wrapper and pass it a profiler factory so that it can create\n\t\/\/ unique profilers on a per outboundSender basis\n\tcaduceusSenderWrapper, err := SenderWrapperFactory{\n\t\tNumWorkersPerSender: caduceusConfig.SenderNumWorkersPerSender,\n\t\tQueueSizePerSender:  caduceusConfig.SenderQueueSizePerSender,\n\t\tCutOffPeriod:        time.Duration(caduceusConfig.SenderCutOffPeriod) * time.Second,\n\t\tLinger:              time.Duration(caduceusConfig.SenderLinger) * time.Second,\n\t\tProfilerFactory:     childCaduceusProfilerFactory,\n\t\tLogger:              logger,\n\t\tClient:              &http.Client{Transport: tr, Timeout: timeout},\n\t}.New()\n\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to initialize new caduceus sender wrapper: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tserverWrapper := &ServerHandler{\n\t\tLogger: logger,\n\t\tcaduceusHandler: &CaduceusHandler{\n\t\t\thandlerProfiler: caduceusHandlerProfiler,\n\t\t\tsenderWrapper:   caduceusSenderWrapper,\n\t\t\tLogger:          logger,\n\t\t},\n\t\tdoJob: workerPool.Send,\n\t}\n\n\tprofileWrapper := &ProfileHandler{\n\t\tprofilerData: caduceusHandlerProfiler,\n\t\tLogger:       logger,\n\t}\n\n\tvalidator, err := getValidator(v)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Validator error: %v\\n\", err)\n\t\treturn 1\n\t}\n\n\tauthHandler := handler.AuthorizationHandler{\n\t\tHeaderName:          \"Authorization\",\n\t\tForbiddenStatusCode: 403,\n\t\tValidator:           validator,\n\t\tLogger:              logger,\n\t}\n\n\tcaduceusHandler := alice.New(authHandler.Decorate, TrackEmptyRequestBody(metricsRegistry))\n\n\trouter := mux.NewRouter()\n\n\trouter = configServerRouter(router, caduceusHandler, serverWrapper)\n\n\trouter.Handle(\"\/api\/v3\/profile\", caduceusHandler.Then(profileWrapper))\n\n\twebhookFactory, err := webhook.NewFactory(v)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error creating new webhook factory: %s\\n\", err)\n\t\treturn 1\n\t}\n\twebhookRegistry, webhookHandler := webhookFactory.NewRegistryAndHandler()\n\twebhookFactory.SetExternalUpdate(caduceusSenderWrapper.Update)\n\n\t\/\/ register webhook end points for api\n\trouter.Handle(\"\/hook\", caduceusHandler.ThenFunc(webhookRegistry.UpdateRegistry))\n\trouter.Handle(\"\/hooks\", caduceusHandler.ThenFunc(webhookRegistry.GetRegistry))\n\n\tselfURL := &url.URL{\n\t\tScheme: \"https\",\n\t\tHost:   v.GetString(\"fqdn\") + v.GetString(\"primary.address\"),\n\t}\n\n\twebhookFactory.Initialize(router, selfURL, webhookHandler, logger, nil)\n\n\tcaduceusHealth := &CaduceusHealth{}\n\tvar runnable concurrent.Runnable\n\n\tcaduceusHealth.Monitor, runnable = webPA.Prepare(logger, nil, metricsRegistry, router)\n\tserverWrapper.caduceusHealth = caduceusHealth\n\n\twaitGroup, shutdown, err := concurrent.Execute(runnable)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to start device manager: %s\\n\", err)\n\t\treturn 1\n\t}\n\n\tvar messageKey = logging.MessageKey()\n\n\tdebugLog.Log(messageKey, \"Calling webhookFactory.PrepareAndStart\")\n\tbeginPrepStart := time.Now()\n\twebhookFactory.PrepareAndStart()\n\tdebugLog.Log(messageKey, \"WebhookFactory.PrepareAndStart done.\", \"elapsedTime\", time.Since(beginPrepStart))\n\n\t\/\/ Attempt to obtain the current listener list from current system without having to wait for listener reregistration.\n\tdebugLog.Log(messageKey, \"Attempting to obtain current listener list from source\", \"source\",\n\t\tv.GetString(\"start.apiPath\"))\n\tbeginObtainList := time.Now()\n\tstartChan := make(chan webhook.Result, 1)\n\twebhookFactory.Start.GetCurrentSystemsHooks(startChan)\n\tvar webhookStartResults webhook.Result = <-startChan\n\tif webhookStartResults.Error != nil {\n\t\terrorLog.Log(logging.ErrorKey(), webhookStartResults.Error)\n\t} else {\n\t\t\/\/ todo: add message\n\t\twebhookFactory.SetList(webhook.NewList(webhookStartResults.Hooks))\n\t\tcaduceusSenderWrapper.Update(webhookStartResults.Hooks)\n\t}\n\tdebugLog.Log(messageKey, \"Current listener retrieval.\", \"elapsedTime\", time.Since(beginObtainList))\n\n\tinfoLog.Log(messageKey, \"Caduceus is up and running!\", \"elapsedTime\", time.Since(beginCaduceus))\n\n\tvar (\n\t\tsignals = make(chan os.Signal, 1)\n\t)\n\n\tsignal.Notify(signals)\n\t<-signals\n\tclose(shutdown)\n\twaitGroup.Wait()\n\n\t\/\/ shutdown the sender wrapper gently so that all queued messages get serviced\n\tcaduceusSenderWrapper.Shutdown(true)\n\n\treturn 0\n}\n\nfunc configServerRouter(router *mux.Router, caduceusHandler alice.Chain, serverWrapper *ServerHandler) *mux.Router {\n\tvar singleContentType = func(r *http.Request, _ *mux.RouteMatch) bool {\n\t\treturn len(r.Header[\"Content-Type\"]) == 1 \/\/require single specification for Content-Type Header\n\t}\n\n\trouter.Handle(\"\/api\/v3\/notify\", caduceusHandler.Then(serverWrapper)).Methods(\"POST\").\n\t\tHeadersRegexp(\"Content-Type\", \"application\/(json|msgpack)\").MatcherFunc(singleContentType)\n\n\t\/\/ Support the old endpoint too.\n\trouter.Handle(\"\/api\/v2\/notify\/{deviceid}\/event\/{eventtype:.*}\", caduceusHandler.Then(serverWrapper)).\n\t\tMethods(\"POST\").HeadersRegexp(\"Content-Type\", \"application\/(json|msgpack)\").\n\t\tMatcherFunc(singleContentType)\n\n\treturn router\n}\n\nfunc main() {\n\tos.Exit(caduceus(os.Args))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"testing\"\n)\n\n\/\/ Copyright (c) 2015 Uber Technologies, Inc.\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n\/\/ This test ensures that the code generator generates valid code that can be built\n\/\/ in combination with Thrift's autogenerated code.\n\nfunc TestAllThrift(t *testing.T) {\n\tfiles, err := ioutil.ReadDir(\"test_files\")\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot read test_files directory: %v\", err)\n\t}\n\n\tfor _, f := range files {\n\t\tfname := f.Name()\n\t\tif filepath.Ext(fname) != \".thrift\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := runTest(t, filepath.Join(\"test_files\", f.Name())); err != nil {\n\t\t\tt.Errorf(\"Thrift file %v failed: %v\", f.Name(), err)\n\t\t}\n\t}\n}\n\nfunc copyFile(src, dst string) error {\n\tf, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\twriteF, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer writeF.Close()\n\n\t_, err = io.Copy(writeF, f)\n\treturn err\n}\n\nfunc setupDirectory(thriftFile string) (string, string, error) {\n\t\/\/ Create a temporary directory\n\ttempDir, err := ioutil.TempDir(\"\", \"thrift-gen\")\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\t\/\/ Copy the .thrift file to the directory\n\toutFile := filepath.Join(tempDir, \"test.thrift\")\n\treturn tempDir, outFile, copyFile(thriftFile, outFile)\n}\n\nfunc runTest(t *testing.T, thriftFile string) error {\n\ttempDir, thriftFile, err := setupDirectory(thriftFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Run generate.sh for the given directory\n\tt.Logf(\"runTest in %v\", tempDir)\n\tif err := processFile(true \/* generateThrift *\/, thriftFile, \"\"); err != nil {\n\t\treturn fmt.Errorf(\"processFile(%s) failed: %v\", thriftFile, err)\n\t}\n\n\t\/\/ If the generate is successful, run go build in the directory.\n\tcmd := exec.Command(\"go\", \"build\", \".\")\n\tcmd.Dir = filepath.Join(tempDir, \"gen-go\", \"test\")\n\tif output, err := cmd.CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"Build failed. Output = \\n%v\\n\", string(output))\n\t}\n\n\t\/\/ Only delete the temp directory on success.\n\tos.RemoveAll(tempDir)\n\treturn nil\n}\n<commit_msg>minor comment updates<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"testing\"\n)\n\n\/\/ Copyright (c) 2015 Uber Technologies, Inc.\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n\/\/ This test ensures that the code generator generates valid code that can be built\n\/\/ in combination with Thrift's autogenerated code.\n\nfunc TestAllThrift(t *testing.T) {\n\tfiles, err := ioutil.ReadDir(\"test_files\")\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot read test_files directory: %v\", err)\n\t}\n\n\tfor _, f := range files {\n\t\tfname := f.Name()\n\t\tif filepath.Ext(fname) != \".thrift\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := runTest(t, filepath.Join(\"test_files\", f.Name())); err != nil {\n\t\t\tt.Errorf(\"Thrift file %v failed: %v\", f.Name(), err)\n\t\t}\n\t}\n}\n\nfunc copyFile(src, dst string) error {\n\tf, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\twriteF, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer writeF.Close()\n\n\t_, err = io.Copy(writeF, f)\n\treturn err\n}\n\n\/\/ setupDirectory creates a temporary directory and copies the Thrift file into that directory.\nfunc setupDirectory(thriftFile string) (string, string, error) {\n\ttempDir, err := ioutil.TempDir(\"\", \"thrift-gen\")\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\toutFile := filepath.Join(tempDir, \"test.thrift\")\n\treturn tempDir, outFile, copyFile(thriftFile, outFile)\n}\n\nfunc runTest(t *testing.T, thriftFile string) error {\n\ttempDir, thriftFile, err := setupDirectory(thriftFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Generate code from the Thrift file.\n\tt.Logf(\"runTest in %v\", tempDir)\n\tif err := processFile(true \/* generateThrift *\/, thriftFile, \"\"); err != nil {\n\t\treturn fmt.Errorf(\"processFile(%s) failed: %v\", thriftFile, err)\n\t}\n\n\t\/\/ Run go build to ensure that the generated code builds.\n\tcmd := exec.Command(\"go\", \"build\", \".\")\n\tcmd.Dir = filepath.Join(tempDir, \"gen-go\", \"test\")\n\tif output, err := cmd.CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"Build failed. Output = \\n%v\\n\", string(output))\n\t}\n\n\t\/\/ Only delete the temp directory on success.\n\tos.RemoveAll(tempDir)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package path_matcher\n\nimport (\n\t\"strings\"\n)\n\nfunc NewMultiPathMatcher(PathMatchers ...PathMatcher) PathMatcher {\n\tif len(PathMatchers) == 0 {\n\t\tpanic(\"the multi path matcher cannot be initialized without any matcher\")\n\t}\n\n\treturn &MultiPathMatcher{PathMatchers: PathMatchers}\n}\n\ntype MultiPathMatcher struct {\n\tPathMatchers []PathMatcher\n}\n\nfunc (f *MultiPathMatcher) IsDirOrSubmodulePathMatched(path string) bool {\n\treturn f.IsPathMatched(path) || f.ShouldGoThrough(path)\n}\n\nfunc (m *MultiPathMatcher) IsPathMatched(path string) bool {\n\tfor _, matcher := range m.PathMatchers {\n\t\tif !matcher.IsPathMatched(path) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (m *MultiPathMatcher) ShouldGoThrough(path string) bool {\n\tfor _, matcher := range m.PathMatchers {\n\t\tif !matcher.ShouldGoThrough(path) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (m *MultiPathMatcher) TrimFileBaseFilepath(path string) string {\n\treturn m.PathMatchers[0].TrimFileBaseFilepath(path)\n}\n\nfunc (m *MultiPathMatcher) BaseFilepath() string {\n\treturn m.PathMatchers[0].BaseFilepath()\n}\n\nfunc (m *MultiPathMatcher) String() string {\n\tvar result []string\n\tfor _, matcher := range m.PathMatchers {\n\t\tresult = append(result, matcher.String())\n\t}\n\n\treturn strings.Join(result, \"; \")\n}\n<commit_msg>[path_matcher] Update multiPathMatcher string format<commit_after>package path_matcher\n\nimport (\n\t\"strings\"\n)\n\nfunc NewMultiPathMatcher(PathMatchers ...PathMatcher) PathMatcher {\n\tif len(PathMatchers) == 0 {\n\t\tpanic(\"the multi path matcher cannot be initialized without any matcher\")\n\t}\n\n\treturn &MultiPathMatcher{PathMatchers: PathMatchers}\n}\n\ntype MultiPathMatcher struct {\n\tPathMatchers []PathMatcher\n}\n\nfunc (f *MultiPathMatcher) IsDirOrSubmodulePathMatched(path string) bool {\n\treturn f.IsPathMatched(path) || f.ShouldGoThrough(path)\n}\n\nfunc (m *MultiPathMatcher) IsPathMatched(path string) bool {\n\tfor _, matcher := range m.PathMatchers {\n\t\tif !matcher.IsPathMatched(path) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (m *MultiPathMatcher) ShouldGoThrough(path string) bool {\n\tfor _, matcher := range m.PathMatchers {\n\t\tif !matcher.ShouldGoThrough(path) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (m *MultiPathMatcher) TrimFileBaseFilepath(path string) string {\n\treturn m.PathMatchers[0].TrimFileBaseFilepath(path)\n}\n\nfunc (m *MultiPathMatcher) BaseFilepath() string {\n\treturn m.PathMatchers[0].BaseFilepath()\n}\n\nfunc (m *MultiPathMatcher) String() string {\n\tvar result []string\n\tfor _, matcher := range m.PathMatchers {\n\t\tresult = append(result, matcher.String())\n\t}\n\n\treturn strings.Join(result, \" && \")\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"time\"\n\n\t\"github.com\/hellofresh\/logging-go\"\n\t\"github.com\/kelseyhightower\/envconfig\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ Specification for basic configurations\ntype Specification struct {\n\tPort                 int           `envconfig:\"PORT\"`\n\tDebug                bool          `envconfig:\"DEBUG\"`\n\tGraceTimeOut         int64         `envconfig:\"GRACE_TIMEOUT\"`\n\tMaxIdleConnsPerHost  int           `envconfig:\"MAX_IDLE_CONNS_PER_HOST\"`\n\tBackendFlushInterval time.Duration `envconfig:\"BACKEND_FLUSH_INTERVAL\"`\n\tCloseIdleConnsPeriod time.Duration `envconfig:\"CLOSE_IDLE_CONNS_PERIOD\"`\n\tLog                  logging.LogConfig\n\tWeb                  Web\n\tDatabase             Database\n\tStorage              Storage\n\tStats                Stats\n\tTracing              Tracing\n\tTLS                  TLS\n}\n\n\/\/ Web represents the API configurations\ntype Web struct {\n\tPort        int  `envconfig:\"API_PORT\"`\n\tReadOnly    bool `envconfig:\"API_READONLY\"`\n\tCredentials Credentials\n\tTLS         TLS\n}\n\n\/\/ TLS represents the TLS configurations\ntype TLS struct {\n\tPort     int    `envconfig:\"PORT\"`\n\tCertFile string `envconfig:\"CERT_PATH\"`\n\tKeyFile  string `envconfig:\"KEY_PATH\"`\n\tRedirect bool   `envconfig:\"REDIRECT\"`\n}\n\n\/\/ IsHTTPS checks if you have https enabled\nfunc (s *TLS) IsHTTPS() bool {\n\treturn s.CertFile != \"\" && s.KeyFile != \"\"\n}\n\n\/\/ Storage holds the configuration for a storage\ntype Storage struct {\n\tDSN string `envconfig:\"STORAGE_DSN\"`\n}\n\n\/\/ Database holds the configuration for a database\ntype Database struct {\n\tDSN string `envconfig:\"DATABASE_DSN\"`\n}\n\n\/\/ Stats holds the configuration for stats\ntype Stats struct {\n\tDSN                   string   `envconfig:\"STATS_DSN\"`\n\tPrefix                string   `envconfig:\"STATS_PREFIX\"`\n\tIDs                   string   `envconfig:\"STATS_IDS\"`\n\tAutoDiscoverThreshold uint     `envconfig:\"STATS_AUTO_DISCOVER_THRESHOLD\"`\n\tAutoDiscoverWhiteList []string `envconfig:\"STATS_AUTO_DISCOVER_WHITE_LIST\"`\n\tErrorsSection         string   `envconfig:\"STATS_ERRORS_SECTION\"`\n}\n\n\/\/ Credentials represents the credentials that are going to be\n\/\/ used by admin JWT configuration\ntype Credentials struct {\n\t\/\/ Algorithm defines admin JWT signing algorithm.\n\t\/\/ Currently the following algorithms are supported: HS256, HS384, HS512.\n\tAlgorithm string `envconfig:\"ALGORITHM\"`\n\tSecret    string `envconfig:\"SECRET\"`\n\tUsername  string `envconfig:\"ADMIN_USERNAME\"`\n\tPassword  string `envconfig:\"ADMIN_PASSWORD\"`\n}\n\n\/\/ GoogleCloudTracing holds the Google Application Default Credentials\ntype GoogleCloudTracing struct {\n\tProjectID    string `envconfig:\"TRACING_GC_PROJECT_ID\"`\n\tEmail        string `envconfig:\"TRACING_GC_EMAIL\"`\n\tPrivateKey   string `envconfig:\"TRACING_GC_PRIVATE_KEY\"`\n\tPrivateKeyID string `envconfig:\"TRACING_GC_PRIVATE_ID\"`\n}\n\n\/\/ AppdashTracing holds the Appdash tracing configuration\ntype AppdashTracing struct {\n\tDSN string `envconfig:\"TRACING_APPDASH_DSN\"`\n\tURL string `envconfig:\"TRACING_APPDASH_URL\"`\n}\n\n\/\/ Tracing represents the distributed tracing configuration\ntype Tracing struct {\n\tGoogleCloudTracing GoogleCloudTracing `mapstructure:\"googleCloud\"`\n\tAppdashTracing     AppdashTracing     `mapstructure:\"appdash\"`\n}\n\n\/\/ IsGoogleCloudEnabled checks if google cloud is enabled\nfunc (t Tracing) IsGoogleCloudEnabled() bool {\n\treturn len(t.GoogleCloudTracing.Email) > 0 && len(t.GoogleCloudTracing.PrivateKey) > 0 && len(t.GoogleCloudTracing.PrivateKeyID) > 0 && len(t.GoogleCloudTracing.ProjectID) > 0\n}\n\n\/\/ IsAppdashEnabled checks if appdash is enabled\nfunc (t Tracing) IsAppdashEnabled() bool {\n\treturn len(t.AppdashTracing.DSN) > 0\n}\n\nfunc init() {\n\tviper.SetDefault(\"port\", \"8080\")\n\tviper.SetDefault(\"tls.port\", \"8433\")\n\tviper.SetDefault(\"tls.redirect\", true)\n\tviper.SetDefault(\"backendFlushInterval\", \"20ms\")\n\tviper.SetDefault(\"database.dsn\", \"file:\/\/\/etc\/janus\")\n\tviper.SetDefault(\"storage.dsn\", \"memory:\/\/localhost\")\n\tviper.SetDefault(\"web.port\", \"8081\")\n\tviper.SetDefault(\"web.tls.port\", \"8444\")\n\tviper.SetDefault(\"web.tls.redisrect\", true)\n\tviper.SetDefault(\"web.credentials.algorithm\", \"HS256\")\n\tviper.SetDefault(\"web.credentials.username\", \"admin\")\n\tviper.SetDefault(\"web.credentials.password\", \"admin\")\n\tviper.SetDefault(\"stats.dsn\", \"log:\/\/\")\n\tviper.SetDefault(\"stats.errorsSection\", \"error-log\")\n\n\tlogging.InitDefaults(viper.GetViper(), \"log\")\n}\n\n\/\/Load configuration variables\nfunc Load(configFile string) (*Specification, error) {\n\tif configFile != \"\" {\n\t\tviper.SetConfigFile(configFile)\n\t} else {\n\t\tviper.SetConfigName(\"janus\")\n\t\tviper.AddConfigPath(\"\/etc\/janus\")\n\t\tviper.AddConfigPath(\".\")\n\t}\n\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tlog.WithError(err).Warn(\"No config file found\")\n\t\treturn LoadEnv()\n\t}\n\n\tvar config Specification\n\tif err := viper.Unmarshal(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}\n\n\/\/LoadEnv loads configuration from environment variables\nfunc LoadEnv() (*Specification, error) {\n\tvar config Specification\n\n\tif err := viper.Unmarshal(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\terr := envconfig.Process(\"\", &config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}\n<commit_msg>Added github configuration<commit_after>package config\n\nimport (\n\t\"time\"\n\n\t\"github.com\/hellofresh\/logging-go\"\n\t\"github.com\/kelseyhightower\/envconfig\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ Specification for basic configurations\ntype Specification struct {\n\tPort                 int           `envconfig:\"PORT\"`\n\tDebug                bool          `envconfig:\"DEBUG\"`\n\tGraceTimeOut         int64         `envconfig:\"GRACE_TIMEOUT\"`\n\tMaxIdleConnsPerHost  int           `envconfig:\"MAX_IDLE_CONNS_PER_HOST\"`\n\tBackendFlushInterval time.Duration `envconfig:\"BACKEND_FLUSH_INTERVAL\"`\n\tCloseIdleConnsPeriod time.Duration `envconfig:\"CLOSE_IDLE_CONNS_PERIOD\"`\n\tLog                  logging.LogConfig\n\tWeb                  Web\n\tDatabase             Database\n\tStorage              Storage\n\tStats                Stats\n\tTracing              Tracing\n\tTLS                  TLS\n}\n\n\/\/ Web represents the API configurations\ntype Web struct {\n\tPort        int  `envconfig:\"API_PORT\"`\n\tReadOnly    bool `envconfig:\"API_READONLY\"`\n\tCredentials Credentials\n\tTLS         TLS\n}\n\n\/\/ TLS represents the TLS configurations\ntype TLS struct {\n\tPort     int    `envconfig:\"PORT\"`\n\tCertFile string `envconfig:\"CERT_PATH\"`\n\tKeyFile  string `envconfig:\"KEY_PATH\"`\n\tRedirect bool   `envconfig:\"REDIRECT\"`\n}\n\n\/\/ IsHTTPS checks if you have https enabled\nfunc (s *TLS) IsHTTPS() bool {\n\treturn s.CertFile != \"\" && s.KeyFile != \"\"\n}\n\n\/\/ Storage holds the configuration for a storage\ntype Storage struct {\n\tDSN string `envconfig:\"STORAGE_DSN\"`\n}\n\n\/\/ Database holds the configuration for a database\ntype Database struct {\n\tDSN string `envconfig:\"DATABASE_DSN\"`\n}\n\n\/\/ Stats holds the configuration for stats\ntype Stats struct {\n\tDSN                   string   `envconfig:\"STATS_DSN\"`\n\tPrefix                string   `envconfig:\"STATS_PREFIX\"`\n\tIDs                   string   `envconfig:\"STATS_IDS\"`\n\tAutoDiscoverThreshold uint     `envconfig:\"STATS_AUTO_DISCOVER_THRESHOLD\"`\n\tAutoDiscoverWhiteList []string `envconfig:\"STATS_AUTO_DISCOVER_WHITE_LIST\"`\n\tErrorsSection         string   `envconfig:\"STATS_ERRORS_SECTION\"`\n}\n\n\/\/ Credentials represents the credentials that are going to be\n\/\/ used by admin JWT configuration\ntype Credentials struct {\n\t\/\/ Algorithm defines admin JWT signing algorithm.\n\t\/\/ Currently the following algorithms are supported: HS256, HS384, HS512.\n\tAlgorithm string `envconfig:\"ALGORITHM\"`\n\tSecret    string `envconfig:\"SECRET\"`\n\tGithub    Github\n}\n\n\/\/ Github holds the github configurations\ntype Github struct {\n\tOrganizations []string           `envconfig:\"GITHUB_ORGANIZATIONS\"`\n\tTeams         []GitHubTeamConfig `envconfig:\"GITHUB_TEAMS\"`\n}\n\n\/\/ GitHubTeamConfig represents a team configuration\ntype GitHubTeamConfig struct {\n\tOrganizationName string `json:\"organization_name,omitempty\"`\n\tTeamName         string `json:\"team_name,omitempty\"`\n}\n\n\/\/ IsConfigured checks if github is enabled\nfunc (auth *Github) IsConfigured() bool {\n\treturn len(auth.Organizations) > 0 ||\n\t\tlen(auth.Teams) > 0\n}\n\n\/\/ GoogleCloudTracing holds the Google Application Default Credentials\ntype GoogleCloudTracing struct {\n\tProjectID    string `envconfig:\"TRACING_GC_PROJECT_ID\"`\n\tEmail        string `envconfig:\"TRACING_GC_EMAIL\"`\n\tPrivateKey   string `envconfig:\"TRACING_GC_PRIVATE_KEY\"`\n\tPrivateKeyID string `envconfig:\"TRACING_GC_PRIVATE_ID\"`\n}\n\n\/\/ AppdashTracing holds the Appdash tracing configuration\ntype AppdashTracing struct {\n\tDSN string `envconfig:\"TRACING_APPDASH_DSN\"`\n\tURL string `envconfig:\"TRACING_APPDASH_URL\"`\n}\n\n\/\/ Tracing represents the distributed tracing configuration\ntype Tracing struct {\n\tGoogleCloudTracing GoogleCloudTracing `mapstructure:\"googleCloud\"`\n\tAppdashTracing     AppdashTracing     `mapstructure:\"appdash\"`\n}\n\n\/\/ IsGoogleCloudEnabled checks if google cloud is enabled\nfunc (t Tracing) IsGoogleCloudEnabled() bool {\n\treturn len(t.GoogleCloudTracing.Email) > 0 && len(t.GoogleCloudTracing.PrivateKey) > 0 && len(t.GoogleCloudTracing.PrivateKeyID) > 0 && len(t.GoogleCloudTracing.ProjectID) > 0\n}\n\n\/\/ IsAppdashEnabled checks if appdash is enabled\nfunc (t Tracing) IsAppdashEnabled() bool {\n\treturn len(t.AppdashTracing.DSN) > 0\n}\n\nfunc init() {\n\tviper.SetDefault(\"port\", \"8080\")\n\tviper.SetDefault(\"tls.port\", \"8433\")\n\tviper.SetDefault(\"tls.redirect\", true)\n\tviper.SetDefault(\"backendFlushInterval\", \"20ms\")\n\tviper.SetDefault(\"database.dsn\", \"file:\/\/\/etc\/janus\")\n\tviper.SetDefault(\"storage.dsn\", \"memory:\/\/localhost\")\n\tviper.SetDefault(\"web.port\", \"8081\")\n\tviper.SetDefault(\"web.tls.port\", \"8444\")\n\tviper.SetDefault(\"web.tls.redisrect\", true)\n\tviper.SetDefault(\"web.credentials.algorithm\", \"HS256\")\n\tviper.SetDefault(\"web.credentials.username\", \"admin\")\n\tviper.SetDefault(\"web.credentials.password\", \"admin\")\n\tviper.SetDefault(\"stats.dsn\", \"log:\/\/\")\n\tviper.SetDefault(\"stats.errorsSection\", \"error-log\")\n\n\tlogging.InitDefaults(viper.GetViper(), \"log\")\n}\n\n\/\/Load configuration variables\nfunc Load(configFile string) (*Specification, error) {\n\tif configFile != \"\" {\n\t\tviper.SetConfigFile(configFile)\n\t} else {\n\t\tviper.SetConfigName(\"janus\")\n\t\tviper.AddConfigPath(\"\/etc\/janus\")\n\t\tviper.AddConfigPath(\".\")\n\t}\n\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tlog.WithError(err).Warn(\"No config file found\")\n\t\treturn LoadEnv()\n\t}\n\n\tvar config Specification\n\tif err := viper.Unmarshal(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}\n\n\/\/LoadEnv loads configuration from environment variables\nfunc LoadEnv() (*Specification, error) {\n\tvar config Specification\n\n\tif err := viper.Unmarshal(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\terr := envconfig.Process(\"\", &config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package filesystem\n\nimport (\n\t\"github.com\/Symantec\/Dominator\/lib\/hash\"\n\t\"io\"\n)\n\ntype NumLinksTable map[uint64]int\n\ntype GenericInode interface {\n\tList(w io.Writer, name string, numLinksTable NumLinksTable,\n\t\tnumLinks int) error\n}\n\ntype InodeTable map[uint64]GenericInode\ntype InodeToFilenamesTable map[uint64][]string\ntype HashToInodesTable map[hash.Hash][]uint64\n\ntype FileSystem struct {\n\tInodeTable            InodeTable\n\tInodeToFilenamesTable InodeToFilenamesTable\n\tHashToInodesTable     HashToInodesTable\n\tNumRegularInodes      uint64\n\tTotalDataBytes        uint64\n\tDirectoryCount        uint64\n\tDirectoryInode\n}\n\nfunc (fs *FileSystem) RebuildInodePointers() {\n\tfs.rebuildInodePointers()\n}\n\nfunc (fs *FileSystem) BuildInodeToFilenamesTable() {\n\tfs.buildInodeToFilenamesTable()\n}\n\nfunc (fs *FileSystem) BuildHashToInodesTable() {\n\tfs.buildHashToInodesTable()\n}\n\nfunc (fs *FileSystem) ComputeTotalDataBytes() {\n\tfs.computeTotalDataBytes()\n}\n\nfunc (fs *FileSystem) List(w io.Writer) error {\n\treturn fs.list(w)\n}\n\ntype DirectoryInode struct {\n\tEntryList     []*DirectoryEntry\n\tEntriesByName map[string]*DirectoryEntry\n\tMode          FileMode\n\tUid           uint32\n\tGid           uint32\n}\n\nfunc (directory *DirectoryInode) BuildEntryMap() {\n\tdirectory.buildEntryMap()\n}\n\nfunc (inode *DirectoryInode) List(w io.Writer, name string,\n\tnumLinksTable NumLinksTable, numLinks int) error {\n\treturn inode.list(w, name, numLinksTable, numLinks)\n}\n\ntype DirectoryEntry struct {\n\tName        string\n\tInodeNumber uint64\n\tinode       GenericInode \/\/ Keep private to avoid encoding\/transmission.\n}\n\nfunc (dirent *DirectoryEntry) Inode() GenericInode {\n\treturn dirent.inode\n}\n\nfunc (dirent *DirectoryEntry) SetInode(inode GenericInode) {\n\tdirent.inode = inode\n}\n\nfunc (dirent *DirectoryEntry) String() string {\n\treturn dirent.Name\n}\n\ntype RegularInode struct {\n\tMode             FileMode\n\tUid              uint32\n\tGid              uint32\n\tMtimeNanoSeconds int32\n\tMtimeSeconds     int64\n\tSize             uint64\n\tHash             hash.Hash\n}\n\nfunc (inode *RegularInode) List(w io.Writer, name string,\n\tnumLinksTable NumLinksTable, numLinks int) error {\n\treturn inode.list(w, name, numLinksTable, numLinks)\n}\n\ntype SymlinkInode struct {\n\tUid     uint32\n\tGid     uint32\n\tSymlink string\n}\n\nfunc (inode *SymlinkInode) List(w io.Writer, name string,\n\tnumLinksTable NumLinksTable, numLinks int) error {\n\treturn inode.list(w, name, numLinksTable, numLinks)\n}\n\ntype SpecialInode struct {\n\tMode             FileMode\n\tUid              uint32\n\tGid              uint32\n\tMtimeNanoSeconds int32\n\tMtimeSeconds     int64\n\tRdev             uint64\n}\n\nfunc (inode *SpecialInode) List(w io.Writer, name string,\n\tnumLinksTable NumLinksTable, numLinks int) error {\n\treturn inode.list(w, name, numLinksTable, numLinks)\n}\n\ntype FileMode uint32\n\nfunc (mode FileMode) String() string {\n\treturn mode.string()\n}\n\nfunc CompareFileSystems(left, right *FileSystem, logWriter io.Writer) bool {\n\treturn compareFileSystems(left, right, logWriter)\n}\n\nfunc CompareDirectoryInodes(left, right *DirectoryInode,\n\tlogWriter io.Writer) bool {\n\treturn compareDirectoryInodes(left, right, logWriter)\n}\n\nfunc CompareDirectoriesMetadata(left, right *DirectoryInode,\n\tlogWriter io.Writer) bool {\n\treturn compareDirectoriesMetadata(left, right, logWriter)\n}\n\nfunc CompareDirectoryEntries(left, right *DirectoryEntry,\n\tlogWriter io.Writer) bool {\n\treturn compareDirectoryEntries(left, right, logWriter)\n}\n\nfunc CompareInodes(left, right GenericInode, logWriter io.Writer) (\n\tsameType, sameMetadata, sameData bool) {\n\treturn compareInodes(left, right, logWriter)\n}\n\nfunc CompareRegularInodes(left, right *RegularInode, logWriter io.Writer) bool {\n\treturn compareRegularInodes(left, right, logWriter)\n}\n\nfunc CompareRegularInodesMetadata(left, right *RegularInode,\n\tlogWriter io.Writer) bool {\n\treturn compareRegularInodesMetadata(left, right, logWriter)\n}\n\nfunc CompareRegularInodesData(left, right *RegularInode,\n\tlogWriter io.Writer) bool {\n\treturn compareRegularInodesData(left, right, logWriter)\n}\n\nfunc CompareSymlinkInodes(left, right *SymlinkInode, logWriter io.Writer) bool {\n\treturn compareSymlinkInodes(left, right, logWriter)\n}\n\nfunc CompareSymlinkInodesMetadata(left, right *SymlinkInode,\n\tlogWriter io.Writer) bool {\n\treturn compareSymlinkInodesMetadata(left, right, logWriter)\n}\n\nfunc CompareSymlinkInodesData(left, right *SymlinkInode,\n\tlogWriter io.Writer) bool {\n\treturn compareSymlinkInodesData(left, right, logWriter)\n}\n\nfunc CompareSpecialInodes(left, right *SpecialInode, logWriter io.Writer) bool {\n\treturn compareSpecialInodes(left, right, logWriter)\n}\n\nfunc CompareSpecialInodesMetadata(left, right *SpecialInode,\n\tlogWriter io.Writer) bool {\n\treturn compareSpecialInodesMetadata(left, right, logWriter)\n}\n\nfunc CompareSpecialInodesData(left, right *SpecialInode,\n\tlogWriter io.Writer) bool {\n\treturn compareSpecialInodesData(left, right, logWriter)\n}\n<commit_msg>Add GetUid() and GetGid() methods to GenericInode interface.<commit_after>package filesystem\n\nimport (\n\t\"github.com\/Symantec\/Dominator\/lib\/hash\"\n\t\"io\"\n)\n\ntype NumLinksTable map[uint64]int\n\ntype GenericInode interface {\n\tGetUid() uint32\n\tGetGid() uint32\n\tList(w io.Writer, name string, numLinksTable NumLinksTable,\n\t\tnumLinks int) error\n}\n\ntype InodeTable map[uint64]GenericInode\ntype InodeToFilenamesTable map[uint64][]string\ntype HashToInodesTable map[hash.Hash][]uint64\n\ntype FileSystem struct {\n\tInodeTable            InodeTable\n\tInodeToFilenamesTable InodeToFilenamesTable\n\tHashToInodesTable     HashToInodesTable\n\tNumRegularInodes      uint64\n\tTotalDataBytes        uint64\n\tDirectoryCount        uint64\n\tDirectoryInode\n}\n\nfunc (fs *FileSystem) RebuildInodePointers() {\n\tfs.rebuildInodePointers()\n}\n\nfunc (fs *FileSystem) BuildInodeToFilenamesTable() {\n\tfs.buildInodeToFilenamesTable()\n}\n\nfunc (fs *FileSystem) BuildHashToInodesTable() {\n\tfs.buildHashToInodesTable()\n}\n\nfunc (fs *FileSystem) ComputeTotalDataBytes() {\n\tfs.computeTotalDataBytes()\n}\n\nfunc (fs *FileSystem) List(w io.Writer) error {\n\treturn fs.list(w)\n}\n\ntype DirectoryInode struct {\n\tEntryList     []*DirectoryEntry\n\tEntriesByName map[string]*DirectoryEntry\n\tMode          FileMode\n\tUid           uint32\n\tGid           uint32\n}\n\nfunc (directory *DirectoryInode) BuildEntryMap() {\n\tdirectory.buildEntryMap()\n}\n\nfunc (inode *DirectoryInode) GetUid() uint32 {\n\treturn inode.Uid\n}\n\nfunc (inode *DirectoryInode) GetGid() uint32 {\n\treturn inode.Gid\n}\n\nfunc (inode *DirectoryInode) List(w io.Writer, name string,\n\tnumLinksTable NumLinksTable, numLinks int) error {\n\treturn inode.list(w, name, numLinksTable, numLinks)\n}\n\ntype DirectoryEntry struct {\n\tName        string\n\tInodeNumber uint64\n\tinode       GenericInode \/\/ Keep private to avoid encoding\/transmission.\n}\n\nfunc (dirent *DirectoryEntry) Inode() GenericInode {\n\treturn dirent.inode\n}\n\nfunc (dirent *DirectoryEntry) SetInode(inode GenericInode) {\n\tdirent.inode = inode\n}\n\nfunc (dirent *DirectoryEntry) String() string {\n\treturn dirent.Name\n}\n\ntype RegularInode struct {\n\tMode             FileMode\n\tUid              uint32\n\tGid              uint32\n\tMtimeNanoSeconds int32\n\tMtimeSeconds     int64\n\tSize             uint64\n\tHash             hash.Hash\n}\n\nfunc (inode *RegularInode) GetUid() uint32 {\n\treturn inode.Uid\n}\n\nfunc (inode *RegularInode) GetGid() uint32 {\n\treturn inode.Gid\n}\n\nfunc (inode *RegularInode) List(w io.Writer, name string,\n\tnumLinksTable NumLinksTable, numLinks int) error {\n\treturn inode.list(w, name, numLinksTable, numLinks)\n}\n\ntype SymlinkInode struct {\n\tUid     uint32\n\tGid     uint32\n\tSymlink string\n}\n\nfunc (inode *SymlinkInode) GetUid() uint32 {\n\treturn inode.Uid\n}\n\nfunc (inode *SymlinkInode) GetGid() uint32 {\n\treturn inode.Gid\n}\n\nfunc (inode *SymlinkInode) List(w io.Writer, name string,\n\tnumLinksTable NumLinksTable, numLinks int) error {\n\treturn inode.list(w, name, numLinksTable, numLinks)\n}\n\ntype SpecialInode struct {\n\tMode             FileMode\n\tUid              uint32\n\tGid              uint32\n\tMtimeNanoSeconds int32\n\tMtimeSeconds     int64\n\tRdev             uint64\n}\n\nfunc (inode *SpecialInode) GetUid() uint32 {\n\treturn inode.Uid\n}\n\nfunc (inode *SpecialInode) GetGid() uint32 {\n\treturn inode.Gid\n}\n\nfunc (inode *SpecialInode) List(w io.Writer, name string,\n\tnumLinksTable NumLinksTable, numLinks int) error {\n\treturn inode.list(w, name, numLinksTable, numLinks)\n}\n\ntype FileMode uint32\n\nfunc (mode FileMode) String() string {\n\treturn mode.string()\n}\n\nfunc CompareFileSystems(left, right *FileSystem, logWriter io.Writer) bool {\n\treturn compareFileSystems(left, right, logWriter)\n}\n\nfunc CompareDirectoryInodes(left, right *DirectoryInode,\n\tlogWriter io.Writer) bool {\n\treturn compareDirectoryInodes(left, right, logWriter)\n}\n\nfunc CompareDirectoriesMetadata(left, right *DirectoryInode,\n\tlogWriter io.Writer) bool {\n\treturn compareDirectoriesMetadata(left, right, logWriter)\n}\n\nfunc CompareDirectoryEntries(left, right *DirectoryEntry,\n\tlogWriter io.Writer) bool {\n\treturn compareDirectoryEntries(left, right, logWriter)\n}\n\nfunc CompareInodes(left, right GenericInode, logWriter io.Writer) (\n\tsameType, sameMetadata, sameData bool) {\n\treturn compareInodes(left, right, logWriter)\n}\n\nfunc CompareRegularInodes(left, right *RegularInode, logWriter io.Writer) bool {\n\treturn compareRegularInodes(left, right, logWriter)\n}\n\nfunc CompareRegularInodesMetadata(left, right *RegularInode,\n\tlogWriter io.Writer) bool {\n\treturn compareRegularInodesMetadata(left, right, logWriter)\n}\n\nfunc CompareRegularInodesData(left, right *RegularInode,\n\tlogWriter io.Writer) bool {\n\treturn compareRegularInodesData(left, right, logWriter)\n}\n\nfunc CompareSymlinkInodes(left, right *SymlinkInode, logWriter io.Writer) bool {\n\treturn compareSymlinkInodes(left, right, logWriter)\n}\n\nfunc CompareSymlinkInodesMetadata(left, right *SymlinkInode,\n\tlogWriter io.Writer) bool {\n\treturn compareSymlinkInodesMetadata(left, right, logWriter)\n}\n\nfunc CompareSymlinkInodesData(left, right *SymlinkInode,\n\tlogWriter io.Writer) bool {\n\treturn compareSymlinkInodesData(left, right, logWriter)\n}\n\nfunc CompareSpecialInodes(left, right *SpecialInode, logWriter io.Writer) bool {\n\treturn compareSpecialInodes(left, right, logWriter)\n}\n\nfunc CompareSpecialInodesMetadata(left, right *SpecialInode,\n\tlogWriter io.Writer) bool {\n\treturn compareSpecialInodesMetadata(left, right, logWriter)\n}\n\nfunc CompareSpecialInodesData(left, right *SpecialInode,\n\tlogWriter io.Writer) bool {\n\treturn compareSpecialInodesData(left, right, logWriter)\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/driusan\/dgit\/git\"\n\t\"os\"\n)\n\nfunc Branch(c *git.Client, args []string) {\n\tflags := flag.NewFlagSet(\"branch\", flag.ExitOnError)\n\tflags.SetOutput(flag.CommandLine.Output())\n\tflags.Usage = func() {\n\t\tflag.Usage()\n\t\tfmt.Fprintf(flag.CommandLine.Output(), \"\\n\\nOptions:\\n\")\n\t\tflags.PrintDefaults()\n\t}\n\n\t\/\/ These flags can be moved out of these lists and below as proper flags as they are implemented\n\tfor _, bf := range []string{\"d\", \"delete\", \"D\", \"create-reflog\", \"f\", \"force\", \"m\", \"move\", \"M\", \"c\", \"copy\", \"C\", \"no-color\", \"i\", \"ignore-case\", \"no-column\", \"r\", \"remotes\", \"a\", \"all\", \"v\", \"vv\", \"verbose\", \"q\", \"quiet\", \"no-abbrev\", \"no-track\", \"unset-upstream\", \"edit-description\"} {\n\t\tflags.Var(newNotimplBoolValue(), bf, \"Not implemented\")\n\t}\n\tfor _, sf := range []string{\"color\", \"abbrev\", \"column\", \"sort\", \"no-merged\", \"contains\", \"no-contains\", \"points-at\", \"format\", \"set-upstream-to\", \"u\"} {\n\t\tflags.Var(newNotimplStringValue(), sf, \"Not implemented\")\n\t}\n\n\tflags.Parse(args)\n\n\tswitch flags.NArg() {\n\tcase 0:\n\t\tbranches, err := c.GetBranches()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, \"Could not get list of branches.\")\n\t\t\treturn\n\t\t}\n\t\thead := c.GetHeadBranch()\n\t\tfor _, b := range branches {\n\t\t\tif head == b {\n\t\t\t\tfmt.Print(\"* \")\n\t\t\t} else {\n\t\t\t\tfmt.Print(\"  \")\n\t\t\t}\n\t\t\tfmt.Println(b.BranchName())\n\t\t}\n\tcase 1:\n\t\theadref, err := git.SymbolicRefGet(c, git.SymbolicRefOptions{}, \"HEAD\")\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb := git.Branch(headref)\n\t\tif err := c.CreateBranch(flags.Arg(0), b); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Could not create branch (%v): %v\\n\", flags.Arg(0), err)\n\t\t}\n\tdefault:\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n}\n<commit_msg>Added the ability to create a branch at a startpoint<commit_after>package cmd\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/driusan\/dgit\/git\"\n\t\"os\"\n)\n\nfunc Branch(c *git.Client, args []string) {\n\tflags := flag.NewFlagSet(\"branch\", flag.ExitOnError)\n\tflags.SetOutput(flag.CommandLine.Output())\n\tflags.Usage = func() {\n\t\tflag.Usage()\n\t\tfmt.Fprintf(flag.CommandLine.Output(), \"\\n\\nOptions:\\n\")\n\t\tflags.PrintDefaults()\n\t}\n\n\t\/\/ These flags can be moved out of these lists and below as proper flags as they are implemented\n\tfor _, bf := range []string{\"d\", \"delete\", \"D\", \"create-reflog\", \"f\", \"force\", \"m\", \"move\", \"M\", \"c\", \"copy\", \"C\", \"no-color\", \"i\", \"ignore-case\", \"no-column\", \"r\", \"remotes\", \"a\", \"all\", \"v\", \"vv\", \"verbose\", \"q\", \"quiet\", \"no-abbrev\", \"no-track\", \"unset-upstream\", \"edit-description\"} {\n\t\tflags.Var(newNotimplBoolValue(), bf, \"Not implemented\")\n\t}\n\tfor _, sf := range []string{\"color\", \"abbrev\", \"column\", \"sort\", \"no-merged\", \"contains\", \"no-contains\", \"points-at\", \"format\", \"set-upstream-to\", \"u\"} {\n\t\tflags.Var(newNotimplStringValue(), sf, \"Not implemented\")\n\t}\n\n\tflags.Parse(args)\n\n\tswitch flags.NArg() {\n\tcase 0:\n\t\tbranches, err := c.GetBranches()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, \"Could not get list of branches.\")\n\t\t\treturn\n\t\t}\n\t\thead := c.GetHeadBranch()\n\t\tfor _, b := range branches {\n\t\t\tif head == b {\n\t\t\t\tfmt.Print(\"* \")\n\t\t\t} else {\n\t\t\t\tfmt.Print(\"  \")\n\t\t\t}\n\t\t\tfmt.Println(b.BranchName())\n\t\t}\n\tcase 1:\n\t\theadref, err := git.SymbolicRefGet(c, git.SymbolicRefOptions{}, \"HEAD\")\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb := git.Branch(headref)\n\t\tif err := c.CreateBranch(flags.Arg(0), b); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Could not create branch (%v): %v\\n\", flags.Arg(0), err)\n\t\t}\n\tcase 2:\n\t\tstartpoint, err := git.RevParseCommitish(c, &git.RevParseOptions{}, flags.Arg(1))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif err := c.CreateBranch(flags.Arg(0), startpoint); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Could not create branch (%v): %v\\n\", flags.Arg(0), err)\n\t\t}\n\tdefault:\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package asciidocgo\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\ntype testSubstDocumentAble struct {\n}\n\nfunc (tsd *testSubstDocumentAble) Attr(name string, defaultValue interface{}, inherit bool) interface{} {\n\treturn \"mathtest\"\n}\nfunc (tsd *testSubstDocumentAble) Basebackend(base interface{}) bool {\n\treturn true\n}\n\nfunc TestSubstitutor(t *testing.T) {\n\n\tConvey(\"A substitutors can be initialized\", t, func() {\n\n\t\tConvey(\"By default, a substitutors can be created\", func() {\n\t\t\tSo(&substitutors{}, ShouldNotBeNil)\n\t\t})\n\n\t\tConvey(\"A substitutors has an empty passthroughs array\", func() {\n\t\t\ts := substitutors{}\n\t\t\tSo(len(s.passthroughs), ShouldEqual, 0)\n\t\t})\n\t})\n\n\tConvey(\"A substitutors has subs type\", t, func() {\n\t\tSo(len(subs[sub.basic]), ShouldEqual, 1)\n\t\tSo(len(subs[sub.normal]), ShouldEqual, 6)\n\t\tSo(len(subs[sub.verbatim]), ShouldEqual, 2)\n\t\tSo(len(subs[sub.title]), ShouldEqual, 6)\n\t\tSo(len(subs[sub.header]), ShouldEqual, 2)\n\t\tSo(len(subs[sub.pass]), ShouldEqual, 0)\n\t\tSo(len(subs[sub.unknown]), ShouldEqual, 0)\n\t})\n\n\tConvey(\"A substitutors can apply substitutions\", t, func() {\n\n\t\tsource := \"test\"\n\t\ts := &substitutors{}\n\n\t\tConvey(\"By default, no substitution or a pass subs will return source unchanged\", func() {\n\t\t\tSo(s.ApplySubs(source, nil), ShouldEqual, source)\n\t\t\tSo(s.ApplySubs(source, subArray{sub.pass}), ShouldResemble, source)\n\t\t\tSo(len(s.ApplySubs(source, subArray{sub.unknown})), ShouldEqual, 0)\n\t\t\tSo(s.ApplySubs(source, subArray{sub.title}), ShouldEqual, \"test\")\n\t\t})\n\n\t\tConvey(\"A normal substition will use normal substitution modes\", func() {\n\t\t\ttestsub = \"test_ApplySubs_allsubs\"\n\t\t\tSo(s.ApplySubs(source, subArray{sub.normal}), ShouldEqual, \"[specialcharacters quotes attributes replacements macros post_replacements]\")\n\t\t\tSo(s.ApplySubs(source, subArray{sub.title}), ShouldEqual, \"[title]\")\n\t\t\ttestsub = \"\"\n\t\t})\n\t\tConvey(\"A macros substition will call extractPassthroughs\", func() {\n\t\t\ttestsub = \"test_ApplySubs_extractPassthroughs\"\n\t\t\tSo(s.ApplySubs(source, subArray{subValue.macros}), ShouldEqual, \"test\")\n\t\t\ttestsub = \"\"\n\t\t})\n\n\t})\n\n\tConvey(\"A substitutors can Extract the passthrough text from the document for reinsertion without processing if escaped\", t, func() {\n\t\tsource := `test \\+++for\n\t\ta\n\t\tpassthrough+++ by test2 \\$$text\n\t\t\tmultiple\n\t\t\tline$$ for\n\t\t\ttest3 \\pass:quotes[text\n\t\t\tline2\n\t\t\tline3] end test4`\n\t\ts := &substitutors{}\n\t\tSo(s.ApplySubs(source, subArray{subValue.macros}), ShouldEqual, `test +++for\n\t\ta\n\t\tpassthrough+++ by test2 $$text\n\t\t\tmultiple\n\t\t\tline$$ for\n\t\t\ttest3 pass:quotes[text\n\t\t\tline2\n\t\t\tline3] end test4`)\n\t})\n\n\tConvey(\"A substitutors can Extract the passthrough text from the document for reinsertion after processing\", t, func() {\n\t\tsource := `test +++for\n\t\ta\n\t\tpassthrough+++ by test2 $$text\n\t\t\tmultiple\n\t\t\tline$$ for\n\t\t\ttest3 pass:quotes[text\n\t\t\tline2\n\t\t\tline3] end test4`\n\t\ts := &substitutors{}\n\n\t\tConvey(\"If no inline macros substitution detected, return text unchanged\", func() {\n\t\t\tSo(s.ApplySubs(\"test ++ nosub\", subArray{subValue.macros}), ShouldEqual, \"test ++ nosub\")\n\t\t})\n\n\t\tSo(s.ApplySubs(source, subArray{subValue.macros}), ShouldEqual, fmt.Sprintf(`test %s0%s by test2 %s1%s for\n\t\t\ttest3 %s2%s end test4`, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END))\n\t})\n\tConvey(\"A substitutors can unescape escaped branckets\", t, func() {\n\t\tSo(unescapeBrackets(\"\"), ShouldEqual, \"\")\n\t\tSo(unescapeBrackets(`a\\]b]c\\]`), ShouldEqual, `a]b]c]`)\n\t})\n\n\tConvey(\"A substitutors can Extract inline text\", t, func() {\n\t\tsource := \"`a few <\\\\{monospaced\\\\}> words`\" +\n\t\t\t\"[input]`A few <\\\\{monospaced\\\\}> words`\\n\" +\n\t\t\t\"\\\\[input]`a few <monospaced> words`\\n\" +\n\t\t\t\"\\\\[input]\\\\`a few <monospaced> words`\\n\" +\n\t\t\t\"`a few\\n<\\\\{monospaced\\\\}> words`\" +\n\t\t\t\"\\\\[input]`a few &lt;monospaced&gt; words`\\n\" +\n\t\t\t\"the text `asciimath:[x = y]` should be passed through as `literal` text\\n\" +\n\t\t\t\"`Here`s Johnny!\"\n\t\ts := &substitutors{}\n\n\t\tSo(s.ApplySubs(source, subArray{subValue.macros}), ShouldEqual, fmt.Sprintf(`%s0%s[input]%s1%s\n[input]%s2%s\n\\input`+\"`\"+`a few <monospaced> words`+\"`\"+` : \\`+\"`\"+`a few <monospaced> words`+\"`\"+`\n%s3%s[input]%s4%s\nthe text %s5%s should be passed through as %s6%s text\n`+\"`\"+`Here`+\"`\"+`s Johnny!`, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END))\n\n\t\tConvey(\"If no literal text substitution detected, return text unchanged\", func() {\n\t\t\tSo(s.ApplySubs(\"test`nosub\", subArray{subValue.macros}), ShouldEqual, \"test`nosub\")\n\t\t})\n\t})\n\n\tConvey(\"A substitutors can Extract math inline text\", t, func() {\n\t\tsource := `math:[x != 0]\n   \\math:[x != 0]\n   asciimath:[x != 0]\n   latexmath:abc[\\sqrt{4} = 2]`\n\t\ts := &substitutors{document: &testSubstDocumentAble{}}\n\n\t\tSo(s.ApplySubs(source, subArray{subValue.macros}), ShouldEqual, fmt.Sprintf(`%s0%s\n   math:[x != 0]\n   %s1%s\n   %s2%s`, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END))\n\n\t\tConvey(\"If no math literal substitution detected, return text unchanged\", func() {\n\t\t\tSo(s.ApplySubs(\"math:nosub\", subArray{subValue.macros}), ShouldEqual, \"math:nosub\")\n\t\t})\n\t})\n}\n<commit_msg>Test subsitutors with nil (Subst)Document(able).<commit_after>package asciidocgo\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\ntype testSubstDocumentAble struct {\n}\n\nfunc (tsd *testSubstDocumentAble) Attr(name string, defaultValue interface{}, inherit bool) interface{} {\n\treturn \"mathtest\"\n}\nfunc (tsd *testSubstDocumentAble) Basebackend(base interface{}) bool {\n\treturn true\n}\n\nfunc TestSubstitutor(t *testing.T) {\n\n\tConvey(\"A substitutors can be initialized\", t, func() {\n\n\t\tConvey(\"By default, a substitutors can be created\", func() {\n\t\t\tSo(&substitutors{}, ShouldNotBeNil)\n\t\t})\n\n\t\tConvey(\"A substitutors has an empty passthroughs array\", func() {\n\t\t\ts := substitutors{}\n\t\t\tSo(len(s.passthroughs), ShouldEqual, 0)\n\t\t})\n\t})\n\n\tConvey(\"A substitutors has subs type\", t, func() {\n\t\tSo(len(subs[sub.basic]), ShouldEqual, 1)\n\t\tSo(len(subs[sub.normal]), ShouldEqual, 6)\n\t\tSo(len(subs[sub.verbatim]), ShouldEqual, 2)\n\t\tSo(len(subs[sub.title]), ShouldEqual, 6)\n\t\tSo(len(subs[sub.header]), ShouldEqual, 2)\n\t\tSo(len(subs[sub.pass]), ShouldEqual, 0)\n\t\tSo(len(subs[sub.unknown]), ShouldEqual, 0)\n\t})\n\n\tConvey(\"A substitutors can apply substitutions\", t, func() {\n\n\t\tsource := \"test\"\n\t\ts := &substitutors{}\n\n\t\tConvey(\"By default, no substitution or a pass subs will return source unchanged\", func() {\n\t\t\tSo(s.ApplySubs(source, nil), ShouldEqual, source)\n\t\t\tSo(s.ApplySubs(source, subArray{sub.pass}), ShouldResemble, source)\n\t\t\tSo(len(s.ApplySubs(source, subArray{sub.unknown})), ShouldEqual, 0)\n\t\t\tSo(s.ApplySubs(source, subArray{sub.title}), ShouldEqual, \"test\")\n\t\t})\n\n\t\tConvey(\"A normal substition will use normal substitution modes\", func() {\n\t\t\ttestsub = \"test_ApplySubs_allsubs\"\n\t\t\tSo(s.ApplySubs(source, subArray{sub.normal}), ShouldEqual, \"[specialcharacters quotes attributes replacements macros post_replacements]\")\n\t\t\tSo(s.ApplySubs(source, subArray{sub.title}), ShouldEqual, \"[title]\")\n\t\t\ttestsub = \"\"\n\t\t})\n\t\tConvey(\"A macros substition will call extractPassthroughs\", func() {\n\t\t\ttestsub = \"test_ApplySubs_extractPassthroughs\"\n\t\t\tSo(s.ApplySubs(source, subArray{subValue.macros}), ShouldEqual, \"test\")\n\t\t\ttestsub = \"\"\n\t\t})\n\n\t})\n\n\tConvey(\"A substitutors can Extract the passthrough text from the document for reinsertion without processing if escaped\", t, func() {\n\t\tsource := `test \\+++for\n\t\ta\n\t\tpassthrough+++ by test2 \\$$text\n\t\t\tmultiple\n\t\t\tline$$ for\n\t\t\ttest3 \\pass:quotes[text\n\t\t\tline2\n\t\t\tline3] end test4`\n\t\ts := &substitutors{}\n\t\tSo(s.ApplySubs(source, subArray{subValue.macros}), ShouldEqual, `test +++for\n\t\ta\n\t\tpassthrough+++ by test2 $$text\n\t\t\tmultiple\n\t\t\tline$$ for\n\t\t\ttest3 pass:quotes[text\n\t\t\tline2\n\t\t\tline3] end test4`)\n\t})\n\n\tConvey(\"A substitutors can Extract the passthrough text from the document for reinsertion after processing\", t, func() {\n\t\tsource := `test +++for\n\t\ta\n\t\tpassthrough+++ by test2 $$text\n\t\t\tmultiple\n\t\t\tline$$ for\n\t\t\ttest3 pass:quotes[text\n\t\t\tline2\n\t\t\tline3] end test4`\n\t\ts := &substitutors{}\n\n\t\tConvey(\"If no inline macros substitution detected, return text unchanged\", func() {\n\t\t\tSo(s.ApplySubs(\"test ++ nosub\", subArray{subValue.macros}), ShouldEqual, \"test ++ nosub\")\n\t\t})\n\n\t\tSo(s.ApplySubs(source, subArray{subValue.macros}), ShouldEqual, fmt.Sprintf(`test %s0%s by test2 %s1%s for\n\t\t\ttest3 %s2%s end test4`, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END))\n\t})\n\tConvey(\"A substitutors can unescape escaped branckets\", t, func() {\n\t\tSo(unescapeBrackets(\"\"), ShouldEqual, \"\")\n\t\tSo(unescapeBrackets(`a\\]b]c\\]`), ShouldEqual, `a]b]c]`)\n\t})\n\n\tConvey(\"A substitutors can Extract inline text\", t, func() {\n\t\tsource := \"`a few <\\\\{monospaced\\\\}> words`\" +\n\t\t\t\"[input]`A few <\\\\{monospaced\\\\}> words`\\n\" +\n\t\t\t\"\\\\[input]`a few <monospaced> words`\\n\" +\n\t\t\t\"\\\\[input]\\\\`a few <monospaced> words`\\n\" +\n\t\t\t\"`a few\\n<\\\\{monospaced\\\\}> words`\" +\n\t\t\t\"\\\\[input]`a few &lt;monospaced&gt; words`\\n\" +\n\t\t\t\"the text `asciimath:[x = y]` should be passed through as `literal` text\\n\" +\n\t\t\t\"`Here`s Johnny!\"\n\t\ts := &substitutors{}\n\n\t\tSo(s.ApplySubs(source, subArray{subValue.macros}), ShouldEqual, fmt.Sprintf(`%s0%s[input]%s1%s\n[input]%s2%s\n\\input`+\"`\"+`a few <monospaced> words`+\"`\"+` : \\`+\"`\"+`a few <monospaced> words`+\"`\"+`\n%s3%s[input]%s4%s\nthe text %s5%s should be passed through as %s6%s text\n`+\"`\"+`Here`+\"`\"+`s Johnny!`, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END))\n\n\t\tConvey(\"If no literal text substitution detected, return text unchanged\", func() {\n\t\t\tSo(s.ApplySubs(\"test`nosub\", subArray{subValue.macros}), ShouldEqual, \"test`nosub\")\n\t\t})\n\t})\n\n\tConvey(\"A substitutors can Extract math inline text\", t, func() {\n\t\tsource := `math:[x != 0]\n   \\math:[x != 0]\n   asciimath:[x != 0]\n   latexmath:abc[\\sqrt{4} = 2]`\n\t\ts := &substitutors{}\n\n\t\tSo(s.ApplySubs(source, subArray{subValue.macros}), ShouldEqual, fmt.Sprintf(`%s0%s\n   math:[x != 0]\n   %s1%s\n   %s2%s`, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END))\n\n\t\ts.document = &testSubstDocumentAble{}\n\n\t\tSo(s.ApplySubs(source, subArray{subValue.macros}), ShouldEqual, fmt.Sprintf(`%s3%s\n   math:[x != 0]\n   %s4%s\n   %s5%s`, subPASS_START, subPASS_END, subPASS_START, subPASS_END, subPASS_START, subPASS_END))\n\n\t\tConvey(\"If no math literal substitution detected, return text unchanged\", func() {\n\t\t\tSo(s.ApplySubs(\"math:nosub\", subArray{subValue.macros}), ShouldEqual, \"math:nosub\")\n\t\t})\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package triggerbuild\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/concourse\/atc\/builder\"\n\t\"github.com\/concourse\/atc\/db\"\n\t\"github.com\/pivotal-golang\/lager\"\n\t\"github.com\/tedsuo\/rata\"\n\n\t\"github.com\/concourse\/atc\/config\"\n\t\"github.com\/concourse\/atc\/server\/routes\"\n)\n\ntype handler struct {\n\tlogger lager.Logger\n\n\tjobs config.Jobs\n\n\tdb      db.DB\n\tbuilder builder.Builder\n}\n\nfunc NewHandler(\n\tlogger lager.Logger,\n\tjobs config.Jobs,\n\tdb db.DB,\n\tbuilder builder.Builder,\n) http.Handler {\n\treturn &handler{\n\t\tlogger: logger,\n\n\t\tjobs: jobs,\n\n\t\tdb:      db,\n\t\tbuilder: builder,\n\t}\n}\n\nfunc (handler *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tjob, found := handler.jobs.Lookup(r.FormValue(\":job\"))\n\tif !found {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tlog := handler.logger.Session(\"trigger-build\", lager.Data{\n\t\t\"job\": job.Name,\n\t})\n\n\tlog.Debug(\"triggering\")\n\n\tbuild, err := handler.db.CreateBuild(job.Name)\n\tif err != nil {\n\t\tlog.Error(\"failed-to-create-build\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\terr = handler.builder.Build(build, job, nil)\n\tif err != nil {\n\t\tlog.Error(\"triggering-failed\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tredirectPath, err := routes.Routes.CreatePathForRoute(routes.GetBuild, rata.Params{\n\t\t\"job\":   job.Name,\n\t\t\"build\": fmt.Sprintf(\"%d\", build.ID),\n\t})\n\tif err != nil {\n\t\tlog.Fatal(\"failed-to-construct-redirect-uri\", err, lager.Data{\n\t\t\t\"build\": build.ID,\n\t\t})\n\t}\n\n\thttp.Redirect(w, r, redirectPath, 302)\n}\n<commit_msg>when triggering, don't sidestep passed: config<commit_after>package triggerbuild\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/concourse\/atc\/builder\"\n\t\"github.com\/concourse\/atc\/builds\"\n\t\"github.com\/concourse\/atc\/db\"\n\t\"github.com\/pivotal-golang\/lager\"\n\t\"github.com\/tedsuo\/rata\"\n\n\t\"github.com\/concourse\/atc\/config\"\n\t\"github.com\/concourse\/atc\/server\/routes\"\n)\n\ntype handler struct {\n\tlogger lager.Logger\n\n\tjobs config.Jobs\n\n\tdb      db.DB\n\tbuilder builder.Builder\n}\n\nfunc NewHandler(\n\tlogger lager.Logger,\n\tjobs config.Jobs,\n\tdb db.DB,\n\tbuilder builder.Builder,\n) http.Handler {\n\treturn &handler{\n\t\tlogger: logger,\n\n\t\tjobs: jobs,\n\n\t\tdb:      db,\n\t\tbuilder: builder,\n\t}\n}\n\nfunc (handler *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tjob, found := handler.jobs.Lookup(r.FormValue(\":job\"))\n\tif !found {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tlog := handler.logger.Session(\"trigger-build\", lager.Data{\n\t\t\"job\": job.Name,\n\t})\n\n\tlog.Debug(\"triggering\")\n\n\tbuild, err := handler.db.CreateBuild(job.Name)\n\tif err != nil {\n\t\tlog.Error(\"failed-to-create-build\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tpassedInputs := []config.Input{}\n\tfor _, input := range job.Inputs {\n\t\tif len(input.Passed) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tpassedInputs = append(passedInputs, input)\n\t}\n\n\tvar inputs builds.VersionedResources\n\n\tif len(passedInputs) > 0 {\n\t\tinputs, err = handler.db.GetLatestInputVersions(passedInputs)\n\t\tif err != nil {\n\t\t\tlog.Error(\"failed-to-get-build-inputs\", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\n\terr = handler.builder.Build(build, job, inputs)\n\tif err != nil {\n\t\tlog.Error(\"triggering-failed\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tredirectPath, err := routes.Routes.CreatePathForRoute(routes.GetBuild, rata.Params{\n\t\t\"job\":   job.Name,\n\t\t\"build\": fmt.Sprintf(\"%d\", build.ID),\n\t})\n\tif err != nil {\n\t\tlog.Fatal(\"failed-to-construct-redirect-uri\", err, lager.Data{\n\t\t\t\"build\": build.ID,\n\t\t})\n\t}\n\n\thttp.Redirect(w, r, redirectPath, 302)\n}\n<|endoftext|>"}
{"text":"<commit_before>package cache\n\nimport (\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"sync\"\n)\n\nvar blobNameSHA256 = regexp.MustCompile(\"^\/?(ac\/|cas\/)?([a-f0-9]{64})$\")\n\n\/\/ HTTPCache ...\ntype HTTPCache interface {\n\tServe()\n}\n\ntype httpCache struct {\n\taddr              string\n\tcache             Cache\n\tensureSpacer      EnsureSpacer\n\tongoingUploads    map[string]*sync.Mutex\n\tongoingUploadsMux *sync.Mutex\n}\n\n\/\/ NewHTTPCache ...\nfunc NewHTTPCache(listenAddr string, cacheDir string, maxBytes int64, ensureSpacer EnsureSpacer) HTTPCache {\n\tensureCacheDir(cacheDir)\n\tcache := NewCache(cacheDir, maxBytes)\n\tloadFilesIntoCache(cache)\n\treturn &httpCache{listenAddr, cache, ensureSpacer, make(map[string]*sync.Mutex), &sync.Mutex{}}\n}\n\n\/\/ Serve ...\nfunc (h *httpCache) Serve() {\n\ts := &http.Server{\n\t\tAddr:    h.addr,\n\t\tHandler: h,\n\t}\n\tlog.Fatal(s.ListenAndServe())\n}\n\nfunc ensureCacheDir(path string) {\n\td, err := os.Open(path)\n\tif err != nil {\n\t\terr := os.MkdirAll(path, os.FileMode(0644))\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\td.Close()\n}\n\nfunc loadFilesIntoCache(cache Cache) {\n\tfilepath.Walk(cache.Dir(), func(name string, info os.FileInfo, err error) error {\n\t\tif !info.IsDir() {\n\t\t\tcache.AddFile(filepath.Base(name), info.Size())\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc (h *httpCache) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tparts, err := parseURL(r.URL.Path)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar hash string\n\tvar verifyHash bool\n\tif len(parts) == 1 {\n\t\t\/\/ For backwards compatibiliy with older Bazel version's that don't\n\t\t\/\/ support {cas,actioncache} prefixes.\n\t\tverifyHash = false\n\t\thash = parts[0]\n\t} else {\n\t\tverifyHash = parts[0] == \"cas\/\"\n\t\thash = parts[1]\n\t}\n\n\tswitch m := r.Method; m {\n\tcase http.MethodGet:\n\t\tif !h.cache.ContainsFile(hash) {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\thttp.ServeFile(w, r, h.filePath(hash))\n\tcase http.MethodPut:\n\t\tif h.cache.ContainsFile(hash) {\n\t\t\th.discardUpload(w, r.Body)\n\t\t\treturn\n\t\t}\n\t\tuploadMux := h.startUpload(hash)\n\t\tuploadMux.Lock()\n\t\tdefer h.stopUpload(hash)\n\t\tdefer uploadMux.Unlock()\n\t\tif h.cache.ContainsFile(hash) {\n\t\t\th.discardUpload(w, r.Body)\n\t\t\treturn\n\t\t}\n\t\tif !h.ensureSpacer.EnsureSpace(h.cache, r.ContentLength) {\n\t\t\thttp.Error(w, \"The disk is full. File could not be uploaded.\",\n\t\t\t\thttp.StatusInsufficientStorage)\n\t\t\treturn\n\t\t}\n\t\twritten, err := h.saveToDisk(r.Body, hash, verifyHash)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\th.cache.AddFile(hash, written)\n\t\tw.WriteHeader(http.StatusOK)\n\tcase http.MethodHead:\n\t\tif !h.cache.ContainsFile(hash) {\n\t\t\thttp.Error(w, err.Error(), http.StatusNotFound)\n\t\t}\n\t\tw.WriteHeader(http.StatusOK)\n\tdefault:\n\t\tmsg := fmt.Sprintf(\"Method '%s' not supported.\", m)\n\t\thttp.Error(w, msg, http.StatusMethodNotAllowed)\n\t}\n}\n\nfunc (h *httpCache) startUpload(hash string) *sync.Mutex {\n\th.ongoingUploadsMux.Lock()\n\tdefer h.ongoingUploadsMux.Unlock()\n\tmux, ok := h.ongoingUploads[hash]\n\tif !ok {\n\t\tmux = &sync.Mutex{}\n\t\th.ongoingUploads[hash] = mux\n\t\treturn mux\n\t}\n\treturn mux\n}\n\nfunc (h *httpCache) stopUpload(hash string) {\n\th.ongoingUploadsMux.Lock()\n\tdefer h.ongoingUploadsMux.Unlock()\n\tdelete(h.ongoingUploads, hash)\n}\n\nfunc (h *httpCache) discardUpload(w http.ResponseWriter, r io.Reader) {\n\tio.Copy(ioutil.Discard, r)\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc parseURL(url string) ([]string, error) {\n\tm := blobNameSHA256.FindStringSubmatch(url)\n\tif m == nil {\n\t\tmsg := fmt.Sprintf(\"Resource name must be a SHA256 hash in hex. \"+\n\t\t\t\"Got '%s'.\", url)\n\t\treturn nil, errors.New(msg)\n\t}\n\treturn m[1:], nil\n}\n\nfunc (h *httpCache) saveToDisk(content io.Reader, hash string, verifyHash bool) (written int64, err error) {\n\tf, err := ioutil.TempFile(h.cache.Dir(), \"upload\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttmpName := f.Name()\n\tif verifyHash {\n\t\thasher := sha256.New()\n\t\twritten, err = io.Copy(io.MultiWriter(f, hasher), content)\n\t\tactualHash := hex.EncodeToString(hasher.Sum(nil))\n\t\tif hash != actualHash {\n\t\t\tos.Remove(tmpName)\n\t\t\tmsg := fmt.Sprintf(\"Hashes don't match. Provided '%s', Actual '%s'.\",\n\t\t\t\thash, actualHash)\n\t\t\treturn 0, errors.New(msg)\n\t\t}\n\t} else {\n\t\twritten, err = io.Copy(f, content)\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\terr = f.Sync()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tf.Close()\n\terr2 := os.Rename(tmpName, h.filePath(hash))\n\tif err2 != nil {\n\t\treturn 0, err2\n\t}\n\treturn written, nil\n}\n\nfunc (h httpCache) filePath(hash string) string {\n\treturn fmt.Sprintf(\"%s%c%s\", h.cache.Dir(), os.PathSeparator, hash)\n}\n<commit_msg>cache\/http: fix potential XSS vulnerability<commit_after>package cache\n\nimport (\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"sync\"\n)\n\nvar blobNameSHA256 = regexp.MustCompile(\"^\/?(ac\/|cas\/)?([a-f0-9]{64})$\")\n\n\/\/ HTTPCache ...\ntype HTTPCache interface {\n\tServe()\n}\n\ntype httpCache struct {\n\taddr              string\n\tcache             Cache\n\tensureSpacer      EnsureSpacer\n\tongoingUploads    map[string]*sync.Mutex\n\tongoingUploadsMux *sync.Mutex\n}\n\n\/\/ NewHTTPCache ...\nfunc NewHTTPCache(listenAddr string, cacheDir string, maxBytes int64, ensureSpacer EnsureSpacer) HTTPCache {\n\tensureCacheDir(cacheDir)\n\tcache := NewCache(cacheDir, maxBytes)\n\tloadFilesIntoCache(cache)\n\treturn &httpCache{listenAddr, cache, ensureSpacer, make(map[string]*sync.Mutex), &sync.Mutex{}}\n}\n\n\/\/ Serve ...\nfunc (h *httpCache) Serve() {\n\ts := &http.Server{\n\t\tAddr:    h.addr,\n\t\tHandler: h,\n\t}\n\tlog.Fatal(s.ListenAndServe())\n}\n\nfunc ensureCacheDir(path string) {\n\td, err := os.Open(path)\n\tif err != nil {\n\t\terr := os.MkdirAll(path, os.FileMode(0644))\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\td.Close()\n}\n\nfunc loadFilesIntoCache(cache Cache) {\n\tfilepath.Walk(cache.Dir(), func(name string, info os.FileInfo, err error) error {\n\t\tif !info.IsDir() {\n\t\t\tcache.AddFile(filepath.Base(name), info.Size())\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc (h *httpCache) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tparts, err := parseURL(r.URL.Path)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar hash string\n\tvar verifyHash bool\n\tif len(parts) == 1 {\n\t\t\/\/ For backwards compatibiliy with older Bazel version's that don't\n\t\t\/\/ support {cas,actioncache} prefixes.\n\t\tverifyHash = false\n\t\thash = parts[0]\n\t} else {\n\t\tverifyHash = parts[0] == \"cas\/\"\n\t\thash = parts[1]\n\t}\n\n\tswitch m := r.Method; m {\n\tcase http.MethodGet:\n\t\tif !h.cache.ContainsFile(hash) {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\thttp.ServeFile(w, r, h.filePath(hash))\n\tcase http.MethodPut:\n\t\tif h.cache.ContainsFile(hash) {\n\t\t\th.discardUpload(w, r.Body)\n\t\t\treturn\n\t\t}\n\t\tuploadMux := h.startUpload(hash)\n\t\tuploadMux.Lock()\n\t\tdefer h.stopUpload(hash)\n\t\tdefer uploadMux.Unlock()\n\t\tif h.cache.ContainsFile(hash) {\n\t\t\th.discardUpload(w, r.Body)\n\t\t\treturn\n\t\t}\n\t\tif !h.ensureSpacer.EnsureSpace(h.cache, r.ContentLength) {\n\t\t\thttp.Error(w, \"The disk is full. File could not be uploaded.\",\n\t\t\t\thttp.StatusInsufficientStorage)\n\t\t\treturn\n\t\t}\n\t\twritten, err := h.saveToDisk(r.Body, hash, verifyHash)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\th.cache.AddFile(hash, written)\n\t\tw.WriteHeader(http.StatusOK)\n\tcase http.MethodHead:\n\t\tif !h.cache.ContainsFile(hash) {\n\t\t\thttp.Error(w, err.Error(), http.StatusNotFound)\n\t\t}\n\t\tw.WriteHeader(http.StatusOK)\n\tdefault:\n\t\tmsg := fmt.Sprintf(\"Method '%s' not supported.\", html.EscapeString(m))\n\t\thttp.Error(w, msg, http.StatusMethodNotAllowed)\n\t}\n}\n\nfunc (h *httpCache) startUpload(hash string) *sync.Mutex {\n\th.ongoingUploadsMux.Lock()\n\tdefer h.ongoingUploadsMux.Unlock()\n\tmux, ok := h.ongoingUploads[hash]\n\tif !ok {\n\t\tmux = &sync.Mutex{}\n\t\th.ongoingUploads[hash] = mux\n\t\treturn mux\n\t}\n\treturn mux\n}\n\nfunc (h *httpCache) stopUpload(hash string) {\n\th.ongoingUploadsMux.Lock()\n\tdefer h.ongoingUploadsMux.Unlock()\n\tdelete(h.ongoingUploads, hash)\n}\n\nfunc (h *httpCache) discardUpload(w http.ResponseWriter, r io.Reader) {\n\tio.Copy(ioutil.Discard, r)\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc parseURL(url string) ([]string, error) {\n\tm := blobNameSHA256.FindStringSubmatch(url)\n\tif m == nil {\n\t\tmsg := fmt.Sprintf(\"Resource name must be a SHA256 hash in hex. \"+\n\t\t\t\"Got '%s'.\", html.EscapeString(url))\n\t\treturn nil, errors.New(msg)\n\t}\n\treturn m[1:], nil\n}\n\nfunc (h *httpCache) saveToDisk(content io.Reader, hash string, verifyHash bool) (written int64, err error) {\n\tf, err := ioutil.TempFile(h.cache.Dir(), \"upload\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ttmpName := f.Name()\n\tif verifyHash {\n\t\thasher := sha256.New()\n\t\twritten, err = io.Copy(io.MultiWriter(f, hasher), content)\n\t\tactualHash := hex.EncodeToString(hasher.Sum(nil))\n\t\tif hash != actualHash {\n\t\t\tos.Remove(tmpName)\n\t\t\tmsg := fmt.Sprintf(\"Hashes don't match. Provided '%s', Actual '%s'.\",\n\t\t\t\thash, html.EscapeString(actualHash))\n\t\t\treturn 0, errors.New(msg)\n\t\t}\n\t} else {\n\t\twritten, err = io.Copy(f, content)\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\terr = f.Sync()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tf.Close()\n\terr2 := os.Rename(tmpName, h.filePath(hash))\n\tif err2 != nil {\n\t\treturn 0, err2\n\t}\n\treturn written, nil\n}\n\nfunc (h httpCache) filePath(hash string) string {\n\treturn fmt.Sprintf(\"%s%c%s\", h.cache.Dir(), os.PathSeparator, hash)\n}\n<|endoftext|>"}
{"text":"<commit_before>package nsf\n\ntype Apu struct {\n\tS1, S2 Square\n\tTriangle\n\n\tOdd        bool\n\tFC         byte\n\tFT         byte\n\tIrqDisable bool\n}\n\ntype Triangle struct {\n\tLinear\n\tTimer\n\tLength\n\tSI int \/\/ sequence index\n\n\tEnable bool\n}\n\ntype Linear struct {\n\tReload  byte\n\tHalt    bool\n\tFlag    bool\n\tCounter byte\n}\n\ntype Square struct {\n\tEnvelope\n\tTimer\n\tLength\n\tSweep\n\tDuty\n\n\tEnable bool\n}\n\ntype Duty struct {\n\tType    byte\n\tCounter byte\n}\n\ntype Sweep struct {\n\tShift     byte\n\tNegate    bool\n\tPeriod    byte\n\tEnable    bool\n\tDivider   byte\n\tReset     bool\n\tNegOffset int\n}\n\ntype Envelope struct {\n\tVolume   byte\n\tDivider  byte\n\tCounter  byte\n\tLoop     bool\n\tConstant bool\n\tStart    bool\n}\n\ntype Timer struct {\n\tTick   uint16\n\tLength uint16\n}\n\ntype Length struct {\n\tHalt    bool\n\tCounter byte\n}\n\nfunc (a *Apu) Init() {\n\ta.S1.Sweep.NegOffset = -1\n\tfor i := uint16(0x4000); i <= 0x400f; i++ {\n\t\ta.Write(i, 0)\n\t}\n\ta.Write(0x4010, 0x10)\n\ta.Write(0x4011, 0)\n\ta.Write(0x4012, 0)\n\ta.Write(0x4013, 0)\n\ta.Write(0x4015, 0xf)\n\ta.Write(0x4017, 0)\n}\n\nfunc (a *Apu) Write(v uint16, b byte) {\n\tswitch v & 0xff {\n\tcase 0x00:\n\t\ta.S1.Control1(b)\n\tcase 0x01:\n\t\ta.S1.Control2(b)\n\tcase 0x02:\n\t\ta.S1.Control3(b)\n\tcase 0x03:\n\t\ta.S1.Control4(b)\n\tcase 0x04:\n\t\ta.S2.Control1(b)\n\tcase 0x05:\n\t\ta.S2.Control2(b)\n\tcase 0x06:\n\t\ta.S2.Control3(b)\n\tcase 0x07:\n\t\ta.S2.Control4(b)\n\tcase 0x08:\n\t\ta.Triangle.Control1(b)\n\tcase 0x0a:\n\t\ta.Triangle.Control2(b)\n\tcase 0x0b:\n\t\ta.Triangle.Control3(b)\n\tcase 0x15:\n\t\ta.S1.Disable(b&0x1 == 0)\n\t\ta.S2.Disable(b&0x2 == 0)\n\t\ta.Triangle.Disable(b&0x4 == 0)\n\tcase 0x17:\n\t\ta.FT = 0\n\t\tif b&0x80 != 0 {\n\t\t\ta.FC = 5\n\t\t\ta.FrameStep()\n\t\t} else {\n\t\t\ta.FC = 4\n\t\t}\n\t\ta.IrqDisable = b&0x40 != 0\n\t}\n}\n\nfunc (t *Triangle) Control1(b byte) {\n\tt.Linear.Control(b)\n\tt.Length.Halt = b&0x80 != 0\n}\n\nfunc (l *Linear) Control(b byte) {\n\tl.Flag = b&0x80 != 0\n\tl.Reload = b & 0x7f\n}\n\nfunc (t *Triangle) Control2(b byte) {\n\tt.Timer.Length &= 0xff00\n\tt.Timer.Length |= uint16(b)\n}\n\nfunc (t *Triangle) Control3(b byte) {\n\tt.Timer.Length &= 0xff\n\tt.Timer.Length |= uint16(b&0x7) << 8\n\tt.Length.Set(b >> 3)\n\tt.Linear.Halt = true\n}\n\nfunc (s *Square) Control1(b byte) {\n\ts.Envelope.Control(b)\n\ts.Duty.Control(b)\n\ts.Length.Halt = b&0x20 != 0\n}\n\nfunc (s *Square) Control2(b byte) {\n\ts.Sweep.Control(b)\n}\n\nfunc (s *Square) Control3(b byte) {\n\ts.Timer.Length &= 0xff00\n\ts.Timer.Length |= uint16(b)\n}\n\nfunc (s *Square) Control4(b byte) {\n\ts.Timer.Length &= 0xff\n\ts.Timer.Length |= uint16(b&0x7) << 8\n\ts.Length.Set(b >> 3)\n\n\ts.Envelope.Start = true\n\ts.Duty.Counter = 0\n}\n\nfunc (d *Duty) Control(b byte) {\n\td.Type = b >> 6\n}\n\nfunc (s *Sweep) Control(b byte) {\n\ts.Shift = b & 0x7\n\ts.Negate = b&0x8 != 0\n\ts.Period = (b >> 4) & 0x7\n\ts.Enable = b&0x80 != 0\n\ts.Reset = true\n}\n\nfunc (e *Envelope) Control(b byte) {\n\te.Volume = b & 0xf\n\te.Constant = b&0x10 != 0\n\te.Loop = b&0x20 != 0\n}\n\nfunc (l *Length) Set(b byte) {\n\tif !l.Halt {\n\t\tl.Counter = LenLookup[b]\n\t}\n}\n\nfunc (l *Length) Enabled() bool {\n\treturn l.Counter != 0\n}\n\nfunc (s *Square) Disable(b bool) {\n\ts.Enable = !b\n\tif b {\n\t\ts.Length.Counter = 0\n\t}\n}\n\nfunc (t *Triangle) Disable(b bool) {\n\tt.Enable = !b\n\tif b {\n\t\tt.Length.Counter = 0\n\t}\n}\n\nfunc (a *Apu) Read(v uint16) byte {\n\tvar b byte\n\tif v == 0x4015 {\n\t\tif a.S1.Length.Counter > 0 {\n\t\t\tb |= 0x1\n\t\t}\n\t\tif a.S2.Length.Counter > 0 {\n\t\t\tb |= 0x2\n\t\t}\n\t\tif a.Triangle.Length.Counter > 0 {\n\t\t\tb |= 0x4\n\t\t}\n\t}\n\treturn b\n}\n\nfunc (d *Duty) Clock() {\n\tif d.Counter == 0 {\n\t\td.Counter = 7\n\t} else {\n\t\td.Counter--\n\t}\n}\n\nfunc (s *Sweep) Clock() (r bool) {\n\tif s.Divider == 0 {\n\t\ts.Divider = s.Period\n\t\tr = true\n\t} else {\n\t\ts.Divider--\n\t}\n\tif s.Reset {\n\t\ts.Divider = 0\n\t\ts.Reset = false\n\t}\n\treturn\n}\n\nfunc (e *Envelope) Clock() {\n\tif e.Start {\n\t\te.Start = false\n\t\te.Counter = 15\n\t} else {\n\t\tif e.Divider == 0 {\n\t\t\te.Divider = e.Volume\n\t\t\tif e.Counter != 0 {\n\t\t\t\te.Counter--\n\t\t\t} else if e.Loop {\n\t\t\t\te.Counter = 15\n\t\t\t}\n\t\t} else {\n\t\t\te.Divider--\n\t\t}\n\t}\n}\n\nfunc (t *Timer) Clock() bool {\n\tif t.Tick == 0 {\n\t\tt.Tick = t.Length\n\t} else {\n\t\tt.Tick--\n\t}\n\treturn t.Tick == t.Length\n}\n\nfunc (s *Square) Clock() {\n\tif s.Timer.Clock() {\n\t\ts.Duty.Clock()\n\t}\n}\n\nfunc (t *Triangle) Clock() {\n\tif t.Timer.Clock() && t.Length.Counter > 0 && t.Linear.Counter > 0 {\n\t\tif t.SI == 31 {\n\t\t\tt.SI = 0\n\t\t} else {\n\t\t\tt.SI++\n\t\t}\n\t}\n}\n\nfunc (a *Apu) Step() {\n\tif a.Odd {\n\t\tif a.S1.Enable {\n\t\t\ta.S1.Clock()\n\t\t}\n\t\tif a.S2.Enable {\n\t\t\ta.S2.Clock()\n\t\t}\n\t}\n\ta.Odd = !a.Odd\n\tif a.Triangle.Enable {\n\t\ta.Triangle.Clock()\n\t}\n}\n\nfunc (a *Apu) FrameStep() {\n\ta.FT++\n\tif a.FT == a.FC {\n\t\ta.FT = 0\n\t}\n\tif a.FT <= 3 {\n\t\ta.S1.Envelope.Clock()\n\t\ta.Triangle.Linear.Clock()\n\t}\n\tif a.FT == 1 || a.FT == 3 {\n\t\ta.S1.FrameStep()\n\t\ta.S2.FrameStep()\n\t\ta.Triangle.Length.Clock()\n\t}\n\tif a.FC == 4 && a.FT == 3 && !a.IrqDisable {\n\t\t\/\/ todo: assert cpu irq line\n\t}\n}\n\nfunc (l *Linear) Clock() {\n\tif l.Halt {\n\t\tl.Counter = l.Reload\n\t} else if l.Counter != 0 {\n\t\tl.Counter--\n\t}\n\tif !l.Flag {\n\t\tl.Halt = false\n\t}\n}\n\nfunc (s *Square) FrameStep() {\n\ts.Length.Clock()\n\tif s.Sweep.Clock() && s.Sweep.Enable && s.Sweep.Shift > 0 {\n\t\tr := s.SweepResult()\n\t\tif r <= 0x7ff {\n\t\t\ts.Timer.Tick = r\n\t\t}\n\t}\n}\n\nfunc (l *Length) Clock() {\n\tif !l.Halt && l.Counter > 0 {\n\t\tl.Counter--\n\t}\n}\n\nfunc (a *Apu) Volume() float32 {\n\tp := PulseOut[a.S1.Volume()+a.S2.Volume()]\n\tt := TndOut[3*a.Triangle.Volume()]\n\treturn p + t\n}\n\nfunc (t *Triangle) Volume() uint8 {\n\tif t.Enable && t.Linear.Counter > 0 && t.Length.Counter > 0 {\n\t\treturn TriLookup[t.SI]\n\t}\n\treturn 0\n}\n\nfunc (s *Square) Volume() uint8 {\n\tif s.Enable && s.Duty.Enabled() && s.Length.Enabled() && s.Timer.Tick >= 8 && s.SweepResult() <= 0x7ff {\n\t\treturn s.Envelope.Output()\n\t}\n\treturn 0\n}\n\nfunc (e *Envelope) Output() byte {\n\tif e.Constant {\n\t\treturn e.Volume\n\t}\n\treturn e.Counter\n}\n\nfunc (s *Square) SweepResult() uint16 {\n\tr := int(s.Timer.Tick >> s.Sweep.Shift)\n\tif s.Sweep.Negate {\n\t\tr = -r\n\t}\n\tr += int(s.Timer.Tick)\n\tif r > 0x7ff {\n\t\tr = 0x800\n\t}\n\treturn uint16(r)\n}\n\nfunc (d *Duty) Enabled() bool {\n\treturn DutyCycle[d.Type][d.Counter] == 1\n}\n\nvar (\n\tPulseOut  [31]float32\n\tTndOut    [203]float32\n\tDutyCycle = [4][8]byte{\n\t\t{0, 1, 0, 0, 0, 0, 0, 0},\n\t\t{0, 1, 1, 0, 0, 0, 0, 0},\n\t\t{0, 1, 1, 1, 1, 0, 0, 0},\n\t\t{1, 0, 0, 1, 1, 1, 1, 1},\n\t}\n\tLenLookup = [...]byte{\n\t\t0x0a, 0xfe, 0x14, 0x02,\n\t\t0x28, 0x04, 0x50, 0x06,\n\t\t0xa0, 0x08, 0x3c, 0x0a,\n\t\t0x0e, 0x0c, 0x1a, 0x0e,\n\t\t0x0c, 0x10, 0x18, 0x12,\n\t\t0x30, 0x14, 0x60, 0x16,\n\t\t0xc0, 0x18, 0x48, 0x1a,\n\t\t0x10, 0x1c, 0x20, 0x1e,\n\t}\n\tTriLookup = [...]byte{\n\t\t0xF, 0xE, 0xD, 0xC,\n\t\t0xB, 0xA, 0x9, 0x8,\n\t\t0x7, 0x6, 0x5, 0x4,\n\t\t0x3, 0x2, 0x1, 0x0,\n\t\t0x0, 0x1, 0x2, 0x3,\n\t\t0x4, 0x5, 0x6, 0x7,\n\t\t0x8, 0x9, 0xA, 0xB,\n\t\t0xC, 0xD, 0xE, 0xF,\n\t}\n)\n\nfunc init() {\n\tfor i := range PulseOut {\n\t\tPulseOut[i] = 95.88 \/ (8128\/float32(i) + 100)\n\t}\n\tfor i := range TndOut {\n\t\tTndOut[i] = 163.67 \/ (24329\/float32(i) + 100)\n\t}\n}\n<commit_msg>Allow setting of length counter when halted<commit_after>package nsf\n\ntype Apu struct {\n\tS1, S2 Square\n\tTriangle\n\n\tOdd        bool\n\tFC         byte\n\tFT         byte\n\tIrqDisable bool\n}\n\ntype Triangle struct {\n\tLinear\n\tTimer\n\tLength\n\tSI int \/\/ sequence index\n\n\tEnable bool\n}\n\ntype Linear struct {\n\tReload  byte\n\tHalt    bool\n\tFlag    bool\n\tCounter byte\n}\n\ntype Square struct {\n\tEnvelope\n\tTimer\n\tLength\n\tSweep\n\tDuty\n\n\tEnable bool\n}\n\ntype Duty struct {\n\tType    byte\n\tCounter byte\n}\n\ntype Sweep struct {\n\tShift     byte\n\tNegate    bool\n\tPeriod    byte\n\tEnable    bool\n\tDivider   byte\n\tReset     bool\n\tNegOffset int\n}\n\ntype Envelope struct {\n\tVolume   byte\n\tDivider  byte\n\tCounter  byte\n\tLoop     bool\n\tConstant bool\n\tStart    bool\n}\n\ntype Timer struct {\n\tTick   uint16\n\tLength uint16\n}\n\ntype Length struct {\n\tHalt    bool\n\tCounter byte\n}\n\nfunc (a *Apu) Init() {\n\ta.S1.Sweep.NegOffset = -1\n\tfor i := uint16(0x4000); i <= 0x400f; i++ {\n\t\ta.Write(i, 0)\n\t}\n\ta.Write(0x4010, 0x10)\n\ta.Write(0x4011, 0)\n\ta.Write(0x4012, 0)\n\ta.Write(0x4013, 0)\n\ta.Write(0x4015, 0xf)\n\ta.Write(0x4017, 0)\n}\n\nfunc (a *Apu) Write(v uint16, b byte) {\n\tswitch v & 0xff {\n\tcase 0x00:\n\t\ta.S1.Control1(b)\n\tcase 0x01:\n\t\ta.S1.Control2(b)\n\tcase 0x02:\n\t\ta.S1.Control3(b)\n\tcase 0x03:\n\t\ta.S1.Control4(b)\n\tcase 0x04:\n\t\ta.S2.Control1(b)\n\tcase 0x05:\n\t\ta.S2.Control2(b)\n\tcase 0x06:\n\t\ta.S2.Control3(b)\n\tcase 0x07:\n\t\ta.S2.Control4(b)\n\tcase 0x08:\n\t\ta.Triangle.Control1(b)\n\tcase 0x0a:\n\t\ta.Triangle.Control2(b)\n\tcase 0x0b:\n\t\ta.Triangle.Control3(b)\n\tcase 0x15:\n\t\ta.S1.Disable(b&0x1 == 0)\n\t\ta.S2.Disable(b&0x2 == 0)\n\t\ta.Triangle.Disable(b&0x4 == 0)\n\tcase 0x17:\n\t\ta.FT = 0\n\t\tif b&0x80 != 0 {\n\t\t\ta.FC = 5\n\t\t\ta.FrameStep()\n\t\t} else {\n\t\t\ta.FC = 4\n\t\t}\n\t\ta.IrqDisable = b&0x40 != 0\n\t}\n}\n\nfunc (t *Triangle) Control1(b byte) {\n\tt.Linear.Control(b)\n\tt.Length.Halt = b&0x80 != 0\n}\n\nfunc (l *Linear) Control(b byte) {\n\tl.Flag = b&0x80 != 0\n\tl.Reload = b & 0x7f\n}\n\nfunc (t *Triangle) Control2(b byte) {\n\tt.Timer.Length &= 0xff00\n\tt.Timer.Length |= uint16(b)\n}\n\nfunc (t *Triangle) Control3(b byte) {\n\tt.Timer.Length &= 0xff\n\tt.Timer.Length |= uint16(b&0x7) << 8\n\tt.Length.Set(b >> 3)\n\tt.Linear.Halt = true\n}\n\nfunc (s *Square) Control1(b byte) {\n\ts.Envelope.Control(b)\n\ts.Duty.Control(b)\n\ts.Length.Halt = b&0x20 != 0\n}\n\nfunc (s *Square) Control2(b byte) {\n\ts.Sweep.Control(b)\n}\n\nfunc (s *Square) Control3(b byte) {\n\ts.Timer.Length &= 0xff00\n\ts.Timer.Length |= uint16(b)\n}\n\nfunc (s *Square) Control4(b byte) {\n\ts.Timer.Length &= 0xff\n\ts.Timer.Length |= uint16(b&0x7) << 8\n\ts.Length.Set(b >> 3)\n\n\ts.Envelope.Start = true\n\ts.Duty.Counter = 0\n}\n\nfunc (d *Duty) Control(b byte) {\n\td.Type = b >> 6\n}\n\nfunc (s *Sweep) Control(b byte) {\n\ts.Shift = b & 0x7\n\ts.Negate = b&0x8 != 0\n\ts.Period = (b >> 4) & 0x7\n\ts.Enable = b&0x80 != 0\n\ts.Reset = true\n}\n\nfunc (e *Envelope) Control(b byte) {\n\te.Volume = b & 0xf\n\te.Constant = b&0x10 != 0\n\te.Loop = b&0x20 != 0\n}\n\nfunc (l *Length) Set(b byte) {\n\tl.Counter = LenLookup[b]\n}\n\nfunc (l *Length) Enabled() bool {\n\treturn l.Counter != 0\n}\n\nfunc (s *Square) Disable(b bool) {\n\ts.Enable = !b\n\tif b {\n\t\ts.Length.Counter = 0\n\t}\n}\n\nfunc (t *Triangle) Disable(b bool) {\n\tt.Enable = !b\n\tif b {\n\t\tt.Length.Counter = 0\n\t}\n}\n\nfunc (a *Apu) Read(v uint16) byte {\n\tvar b byte\n\tif v == 0x4015 {\n\t\tif a.S1.Length.Counter > 0 {\n\t\t\tb |= 0x1\n\t\t}\n\t\tif a.S2.Length.Counter > 0 {\n\t\t\tb |= 0x2\n\t\t}\n\t\tif a.Triangle.Length.Counter > 0 {\n\t\t\tb |= 0x4\n\t\t}\n\t}\n\treturn b\n}\n\nfunc (d *Duty) Clock() {\n\tif d.Counter == 0 {\n\t\td.Counter = 7\n\t} else {\n\t\td.Counter--\n\t}\n}\n\nfunc (s *Sweep) Clock() (r bool) {\n\tif s.Divider == 0 {\n\t\ts.Divider = s.Period\n\t\tr = true\n\t} else {\n\t\ts.Divider--\n\t}\n\tif s.Reset {\n\t\ts.Divider = 0\n\t\ts.Reset = false\n\t}\n\treturn\n}\n\nfunc (e *Envelope) Clock() {\n\tif e.Start {\n\t\te.Start = false\n\t\te.Counter = 15\n\t} else {\n\t\tif e.Divider == 0 {\n\t\t\te.Divider = e.Volume\n\t\t\tif e.Counter != 0 {\n\t\t\t\te.Counter--\n\t\t\t} else if e.Loop {\n\t\t\t\te.Counter = 15\n\t\t\t}\n\t\t} else {\n\t\t\te.Divider--\n\t\t}\n\t}\n}\n\nfunc (t *Timer) Clock() bool {\n\tif t.Tick == 0 {\n\t\tt.Tick = t.Length\n\t} else {\n\t\tt.Tick--\n\t}\n\treturn t.Tick == t.Length\n}\n\nfunc (s *Square) Clock() {\n\tif s.Timer.Clock() {\n\t\ts.Duty.Clock()\n\t}\n}\n\nfunc (t *Triangle) Clock() {\n\tif t.Timer.Clock() && t.Length.Counter > 0 && t.Linear.Counter > 0 {\n\t\tif t.SI == 31 {\n\t\t\tt.SI = 0\n\t\t} else {\n\t\t\tt.SI++\n\t\t}\n\t}\n}\n\nfunc (a *Apu) Step() {\n\tif a.Odd {\n\t\tif a.S1.Enable {\n\t\t\ta.S1.Clock()\n\t\t}\n\t\tif a.S2.Enable {\n\t\t\ta.S2.Clock()\n\t\t}\n\t}\n\ta.Odd = !a.Odd\n\tif a.Triangle.Enable {\n\t\ta.Triangle.Clock()\n\t}\n}\n\nfunc (a *Apu) FrameStep() {\n\ta.FT++\n\tif a.FT == a.FC {\n\t\ta.FT = 0\n\t}\n\tif a.FT <= 3 {\n\t\ta.S1.Envelope.Clock()\n\t\ta.Triangle.Linear.Clock()\n\t}\n\tif a.FT == 1 || a.FT == 3 {\n\t\ta.S1.FrameStep()\n\t\ta.S2.FrameStep()\n\t\ta.Triangle.Length.Clock()\n\t}\n\tif a.FC == 4 && a.FT == 3 && !a.IrqDisable {\n\t\t\/\/ todo: assert cpu irq line\n\t}\n}\n\nfunc (l *Linear) Clock() {\n\tif l.Halt {\n\t\tl.Counter = l.Reload\n\t} else if l.Counter != 0 {\n\t\tl.Counter--\n\t}\n\tif !l.Flag {\n\t\tl.Halt = false\n\t}\n}\n\nfunc (s *Square) FrameStep() {\n\ts.Length.Clock()\n\tif s.Sweep.Clock() && s.Sweep.Enable && s.Sweep.Shift > 0 {\n\t\tr := s.SweepResult()\n\t\tif r <= 0x7ff {\n\t\t\ts.Timer.Tick = r\n\t\t}\n\t}\n}\n\nfunc (l *Length) Clock() {\n\tif !l.Halt && l.Counter > 0 {\n\t\tl.Counter--\n\t}\n}\n\nfunc (a *Apu) Volume() float32 {\n\tp := PulseOut[a.S1.Volume()+a.S2.Volume()]\n\tt := TndOut[3*a.Triangle.Volume()]\n\treturn p + t\n}\n\nfunc (t *Triangle) Volume() uint8 {\n\tif t.Enable && t.Linear.Counter > 0 && t.Length.Counter > 0 {\n\t\treturn TriLookup[t.SI]\n\t}\n\treturn 0\n}\n\nfunc (s *Square) Volume() uint8 {\n\tif s.Enable && s.Duty.Enabled() && s.Length.Enabled() && s.Timer.Tick >= 8 && s.SweepResult() <= 0x7ff {\n\t\treturn s.Envelope.Output()\n\t}\n\treturn 0\n}\n\nfunc (e *Envelope) Output() byte {\n\tif e.Constant {\n\t\treturn e.Volume\n\t}\n\treturn e.Counter\n}\n\nfunc (s *Square) SweepResult() uint16 {\n\tr := int(s.Timer.Tick >> s.Sweep.Shift)\n\tif s.Sweep.Negate {\n\t\tr = -r\n\t}\n\tr += int(s.Timer.Tick)\n\tif r > 0x7ff {\n\t\tr = 0x800\n\t}\n\treturn uint16(r)\n}\n\nfunc (d *Duty) Enabled() bool {\n\treturn DutyCycle[d.Type][d.Counter] == 1\n}\n\nvar (\n\tPulseOut  [31]float32\n\tTndOut    [203]float32\n\tDutyCycle = [4][8]byte{\n\t\t{0, 1, 0, 0, 0, 0, 0, 0},\n\t\t{0, 1, 1, 0, 0, 0, 0, 0},\n\t\t{0, 1, 1, 1, 1, 0, 0, 0},\n\t\t{1, 0, 0, 1, 1, 1, 1, 1},\n\t}\n\tLenLookup = [...]byte{\n\t\t0x0a, 0xfe, 0x14, 0x02,\n\t\t0x28, 0x04, 0x50, 0x06,\n\t\t0xa0, 0x08, 0x3c, 0x0a,\n\t\t0x0e, 0x0c, 0x1a, 0x0e,\n\t\t0x0c, 0x10, 0x18, 0x12,\n\t\t0x30, 0x14, 0x60, 0x16,\n\t\t0xc0, 0x18, 0x48, 0x1a,\n\t\t0x10, 0x1c, 0x20, 0x1e,\n\t}\n\tTriLookup = [...]byte{\n\t\t0xF, 0xE, 0xD, 0xC,\n\t\t0xB, 0xA, 0x9, 0x8,\n\t\t0x7, 0x6, 0x5, 0x4,\n\t\t0x3, 0x2, 0x1, 0x0,\n\t\t0x0, 0x1, 0x2, 0x3,\n\t\t0x4, 0x5, 0x6, 0x7,\n\t\t0x8, 0x9, 0xA, 0xB,\n\t\t0xC, 0xD, 0xE, 0xF,\n\t}\n)\n\nfunc init() {\n\tfor i := range PulseOut {\n\t\tPulseOut[i] = 95.88 \/ (8128\/float32(i) + 100)\n\t}\n\tfor i := range TndOut {\n\t\tTndOut[i] = 163.67 \/ (24329\/float32(i) + 100)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage test\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"path\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\t\"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\/unstructured\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/api\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/framework\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/state\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/util\"\n)\n\nconst (\n\tnamePlaceholder  = \"Name\"\n\tindexPlaceholder = \"Index\"\n)\n\ntype simpleTestExecutor struct{}\n\nfunc createSimpleTestExecutor() TestExecutor {\n\treturn &simpleTestExecutor{}\n}\n\n\/\/ ExecuteTest executes test based on provided configuration.\nfunc (ste *simpleTestExecutor) ExecuteTest(ctx Context, conf *api.Config) *util.ErrorList {\n\tdefer cleanupResources(ctx)\n\tctx.GetTickerFactory().Init(conf.TuningSets)\n\tautomanagedNamespacesList, err := ctx.GetFramework().ListAutomanagedNamespaces()\n\tif err != nil {\n\t\treturn util.NewErrorList(fmt.Errorf(\"automanaged namespaces listing failed: %v\", err))\n\t}\n\tif len(automanagedNamespacesList) > 0 {\n\t\treturn util.NewErrorList(fmt.Errorf(\"pre-existing automanaged namespaces found\"))\n\t}\n\terr = ctx.GetFramework().CreateAutomanagedNamespaces(int(conf.AutomanagedNamespaces))\n\tif err != nil {\n\t\treturn util.NewErrorList(fmt.Errorf(\"automanaged namespaces creation failed: %v\", err))\n\t}\n\n\terrList := util.NewErrorList()\n\tfor i := range conf.Steps {\n\t\tif stepErrList := ste.ExecuteStep(ctx, &conf.Steps[i]); !stepErrList.IsEmpty() {\n\t\t\terrList.Concat(stepErrList)\n\t\t\tif isErrsCritical(stepErrList) {\n\t\t\t\treturn errList\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, summary := range ctx.GetMeasurementManager().GetSummaries() {\n\t\tsummaryText, err := summary.PrintSummary()\n\t\tif err != nil {\n\t\t\terrList.Append(fmt.Errorf(\"printing summary %s error: %v\", summary.SummaryName(), err))\n\t\t\tcontinue\n\t\t}\n\t\tif ctx.GetClusterLoaderConfig().ReportDir == \"\" {\n\t\t\tglog.Infof(\"%v: %v\", summary.SummaryName(), summaryText)\n\t\t} else {\n\t\t\t\/\/ TODO(krzysied): Remeber to keep original filename style for backward compatibility.\n\t\t\tfilePath := path.Join(ctx.GetClusterLoaderConfig().ReportDir, summary.SummaryName()+\"_\"+conf.Name+\"_\"+time.Now().Format(time.RFC3339)+\".txt\")\n\t\t\tif err := ioutil.WriteFile(filePath, []byte(summaryText), 0644); err != nil {\n\t\t\t\terrList.Append(fmt.Errorf(\"writing to file %v error: %v\", filePath, err))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\treturn errList\n}\n\n\/\/ ExecuteStep executes single test step based on provided step configuration.\nfunc (ste *simpleTestExecutor) ExecuteStep(ctx Context, step *api.Step) *util.ErrorList {\n\tvar wg wait.Group\n\t\/\/ TODO(krzysied): Consider moving lock and errList to separate structure.\n\terrList := util.NewErrorList()\n\tif len(step.Measurements) > 0 {\n\t\tfor i := range step.Measurements {\n\t\t\t\/\/ index is created to make i value unchangeable during thread execution.\n\t\t\tindex := i\n\t\t\twg.Start(func() {\n\t\t\t\terr := ctx.GetMeasurementManager().Execute(step.Measurements[index].Method, step.Measurements[index].Identifier, step.Measurements[index].Params)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrList.Append(fmt.Errorf(\"measurement call %s - %s error: %v\", step.Measurements[index].Method, step.Measurements[index].Identifier, err))\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t} else {\n\t\tfor i := range step.Phases {\n\t\t\tphase := &step.Phases[i]\n\t\t\twg.Start(func() {\n\t\t\t\tif phaseErrList := ste.ExecutePhase(ctx, phase); !phaseErrList.IsEmpty() {\n\t\t\t\t\terrList.Concat(phaseErrList)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\twg.Wait()\n\treturn errList\n}\n\n\/\/ ExecutePhase executes single test phase based on provided phase configuration.\nfunc (ste *simpleTestExecutor) ExecutePhase(ctx Context, phase *api.Phase) *util.ErrorList {\n\t\/\/ TODO: add tuning set\n\terrList := util.NewErrorList()\n\tnsList := createNamespacesList(phase.NamespaceRange)\n\tticker, err := ctx.GetTickerFactory().CreateTicker(phase.TuningSet)\n\tif err != nil {\n\t\treturn util.NewErrorList(fmt.Errorf(\"ticker creation error: %v\", err))\n\t}\n\tdefer ticker.Stop()\n\tfor _, nsName := range nsList {\n\t\tinstancesStates := make([]*state.InstancesState, 0)\n\t\t\/\/ Updating state (DesiredReplicaCount) of every object in object bundle.\n\t\tfor j := range phase.ObjectBundle {\n\t\t\tid, err := getIdentifier(ctx, &phase.ObjectBundle[j])\n\t\t\tif err != nil {\n\t\t\t\terrList.Append(err)\n\t\t\t\treturn errList\n\t\t\t}\n\t\t\tinstances, exists := ctx.GetState().Get(nsName, id)\n\t\t\tif !exists {\n\t\t\t\tinstances = &state.InstancesState{\n\t\t\t\t\tDesiredReplicaCount: 0,\n\t\t\t\t\tCurrentReplicaCount: 0,\n\t\t\t\t\tObject:              phase.ObjectBundle[j],\n\t\t\t\t}\n\t\t\t}\n\t\t\tinstances.DesiredReplicaCount = phase.ReplicasPerNamespace\n\t\t\tctx.GetState().Set(nsName, id, instances)\n\t\t\tinstancesStates = append(instancesStates, instances)\n\t\t}\n\n\t\t\/\/ Calculating maximal replica count of objects from object bundle.\n\t\tvar maxCurrentReplicaCount int32\n\t\tfor j := range instancesStates {\n\t\t\tif instancesStates[j].CurrentReplicaCount > maxCurrentReplicaCount {\n\t\t\t\tmaxCurrentReplicaCount = instancesStates[j].CurrentReplicaCount\n\t\t\t}\n\t\t}\n\t\t\/\/ Deleting objects with index greater or equal requested replicas per namespace number.\n\t\t\/\/ Objects will be deleted in reversed order.\n\t\tfor replicaIndex := phase.ReplicasPerNamespace; replicaIndex < maxCurrentReplicaCount; replicaIndex++ {\n\t\t\tfor j := len(phase.ObjectBundle) - 1; j >= 0; j-- {\n\t\t\t\tif replicaIndex < instancesStates[j].CurrentReplicaCount {\n\t\t\t\t\t<-ticker.C\n\t\t\t\t\tif objectErrList := ste.ExecuteObject(ctx, &phase.ObjectBundle[j], nsName, replicaIndex, DELETE_OBJECT); !objectErrList.IsEmpty() {\n\t\t\t\t\t\terrList.Concat(objectErrList)\n\t\t\t\t\t\tif isErrsCritical(objectErrList) {\n\t\t\t\t\t\t\treturn errList\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\/\/ Handling for update\/create objects.\n\t\tfor replicaIndex := int32(0); replicaIndex < phase.ReplicasPerNamespace; replicaIndex++ {\n\t\t\tfor j := range phase.ObjectBundle {\n\t\t\t\tif instancesStates[j].CurrentReplicaCount == phase.ReplicasPerNamespace {\n\t\t\t\t\t<-ticker.C\n\t\t\t\t\tif objectErrList := ste.ExecuteObject(ctx, &phase.ObjectBundle[j], nsName, replicaIndex, PATCH_OBJECT); !objectErrList.IsEmpty() {\n\t\t\t\t\t\terrList.Concat(objectErrList)\n\t\t\t\t\t\tif isErrsCritical(objectErrList) {\n\t\t\t\t\t\t\treturn errList\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ If error then skip this bundle\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t} else if replicaIndex >= instancesStates[j].CurrentReplicaCount {\n\t\t\t\t\t<-ticker.C\n\t\t\t\t\tif objectErrList := ste.ExecuteObject(ctx, &phase.ObjectBundle[j], nsName, replicaIndex, CREATE_OBJECT); !objectErrList.IsEmpty() {\n\t\t\t\t\t\terrList.Concat(objectErrList)\n\t\t\t\t\t\tif isErrsCritical(objectErrList) {\n\t\t\t\t\t\t\treturn errList\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ If error then skip this bundle\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\/\/ Updating state (CurrentReplicaCount) of every object in object bundle.\n\t\tfor j := range phase.ObjectBundle {\n\t\t\tid, _ := getIdentifier(ctx, &phase.ObjectBundle[j])\n\t\t\tinstancesStates[j].CurrentReplicaCount = instancesStates[j].DesiredReplicaCount\n\t\t\tctx.GetState().Set(nsName, id, instancesStates[j])\n\t\t}\n\t}\n\treturn errList\n}\n\n\/\/ ExecuteObject executes single test object operation based on provided object configuration.\nfunc (ste *simpleTestExecutor) ExecuteObject(ctx Context, object *api.Object, namespace string, replicaIndex int32, operation OperationType) *util.ErrorList {\n\tobjName := fmt.Sprintf(\"%v-%d\", object.Basename, replicaIndex)\n\tvar err error\n\tvar obj *unstructured.Unstructured\n\tswitch operation {\n\tcase CREATE_OBJECT, PATCH_OBJECT:\n\t\tvar mapping map[string]interface{}\n\t\tif object.TemplateFillMap == nil {\n\t\t\tmapping = make(map[string]interface{})\n\t\t} else {\n\t\t\tmapping = object.TemplateFillMap\n\t\t}\n\t\tmapping[namePlaceholder] = objName\n\t\tmapping[indexPlaceholder] = replicaIndex\n\t\tobj, err = ctx.GetTemplateProvider().TemplateToObject(object.ObjectTemplatePath, mapping)\n\t\tif err != nil {\n\t\t\treturn util.NewErrorList(fmt.Errorf(\"reading template (%v) error: %v\", object.ObjectTemplatePath, err))\n\t\t}\n\tcase DELETE_OBJECT:\n\t\tobj, err = ctx.GetTemplateProvider().RawToObject(object.ObjectTemplatePath)\n\t\tif err != nil {\n\t\t\treturn util.NewErrorList(fmt.Errorf(\"reading template (%v) for deletion error: %v\", object.ObjectTemplatePath, err))\n\t\t}\n\tdefault:\n\t\treturn util.NewErrorList(fmt.Errorf(\"unsupported operation %v for namespace %v object %v\", operation, namespace, objName))\n\t}\n\tgvk := obj.GroupVersionKind()\n\n\terrList := util.NewErrorList()\n\tif namespace == \"\" {\n\t\t\/\/ TODO: handle cluster level object\n\t} else {\n\t\tswitch operation {\n\t\tcase CREATE_OBJECT:\n\t\t\tif err := ctx.GetFramework().CreateObject(namespace, objName, obj); err != nil {\n\t\t\t\terrList.Append(fmt.Errorf(\"namespace %v object %v creation error: %v\", namespace, objName, err))\n\t\t\t}\n\t\tcase PATCH_OBJECT:\n\t\t\tif err := ctx.GetFramework().PatchObject(namespace, objName, obj); err != nil {\n\t\t\t\terrList.Append(fmt.Errorf(\"namespace %v object %v updating error: %v\", namespace, objName, err))\n\t\t\t}\n\t\tcase DELETE_OBJECT:\n\t\t\tif err := ctx.GetFramework().DeleteObject(gvk, namespace, objName); err != nil {\n\t\t\t\terrList.Append(fmt.Errorf(\"namespace %v object %v deletion error: %v\", namespace, objName, err))\n\t\t\t}\n\t\t}\n\t}\n\treturn errList\n}\n\nfunc getIdentifier(ctx Context, object *api.Object) (state.InstancesIdentifier, error) {\n\tobjName := fmt.Sprintf(\"%v-%d\", object.Basename, 0)\n\tvar mapping map[string]interface{}\n\tif object.TemplateFillMap == nil {\n\t\tmapping = make(map[string]interface{})\n\t} else {\n\t\tmapping = object.TemplateFillMap\n\t}\n\tmapping[namePlaceholder] = objName\n\tmapping[indexPlaceholder] = 0\n\tobj, err := ctx.GetTemplateProvider().RawToObject(object.ObjectTemplatePath)\n\tif err != nil {\n\t\treturn state.InstancesIdentifier{}, fmt.Errorf(\"reading template (%v) for identifier error: %v\", object.ObjectTemplatePath, err)\n\t}\n\tgvk := obj.GroupVersionKind()\n\treturn state.InstancesIdentifier{\n\t\tBasename:   object.Basename,\n\t\tObjectKind: gvk.Kind,\n\t\tApiGroup:   gvk.Group,\n\t}, nil\n}\n\nfunc createNamespacesList(namespaceRange *api.NamespaceRange) []string {\n\tif namespaceRange == nil {\n\t\treturn []string{\"\"}\n\t}\n\n\tnsList := make([]string, 0)\n\tnsBasename := framework.AutomanagedNamespaceName\n\tif namespaceRange.Basename != nil {\n\t\tnsBasename = *namespaceRange.Basename\n\t}\n\n\tfor i := namespaceRange.Min; i <= namespaceRange.Max; i++ {\n\t\tnsList = append(nsList, fmt.Sprintf(\"%v-%d\", nsBasename, i))\n\t}\n\treturn nsList\n}\n\nfunc isErrsCritical(*util.ErrorList) bool {\n\t\/\/ TODO: define critical errors\n\treturn false\n}\n\nfunc cleanupResources(ctx Context) {\n\tcleanupStartTime := time.Now()\n\tif errList := ctx.GetFramework().DeleteAutomanagedNamespaces(); !errList.IsEmpty() {\n\t\tglog.Errorf(\"Resource cleanup error: %v\", errList.String())\n\t\treturn\n\t}\n\tglog.Infof(\"Resources cleanup time: %v\", time.Since(cleanupStartTime))\n}\n<commit_msg>adding parallelism to test executor<commit_after>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage test\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"path\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\t\"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\/unstructured\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/api\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/framework\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/state\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/util\"\n)\n\nconst (\n\tnamePlaceholder  = \"Name\"\n\tindexPlaceholder = \"Index\"\n)\n\ntype simpleTestExecutor struct{}\n\nfunc createSimpleTestExecutor() TestExecutor {\n\treturn &simpleTestExecutor{}\n}\n\n\/\/ ExecuteTest executes test based on provided configuration.\nfunc (ste *simpleTestExecutor) ExecuteTest(ctx Context, conf *api.Config) *util.ErrorList {\n\tdefer cleanupResources(ctx)\n\tctx.GetTickerFactory().Init(conf.TuningSets)\n\tautomanagedNamespacesList, err := ctx.GetFramework().ListAutomanagedNamespaces()\n\tif err != nil {\n\t\treturn util.NewErrorList(fmt.Errorf(\"automanaged namespaces listing failed: %v\", err))\n\t}\n\tif len(automanagedNamespacesList) > 0 {\n\t\treturn util.NewErrorList(fmt.Errorf(\"pre-existing automanaged namespaces found\"))\n\t}\n\terr = ctx.GetFramework().CreateAutomanagedNamespaces(int(conf.AutomanagedNamespaces))\n\tif err != nil {\n\t\treturn util.NewErrorList(fmt.Errorf(\"automanaged namespaces creation failed: %v\", err))\n\t}\n\n\terrList := util.NewErrorList()\n\tfor i := range conf.Steps {\n\t\tif stepErrList := ste.ExecuteStep(ctx, &conf.Steps[i]); !stepErrList.IsEmpty() {\n\t\t\terrList.Concat(stepErrList)\n\t\t\tif isErrsCritical(stepErrList) {\n\t\t\t\treturn errList\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, summary := range ctx.GetMeasurementManager().GetSummaries() {\n\t\tsummaryText, err := summary.PrintSummary()\n\t\tif err != nil {\n\t\t\terrList.Append(fmt.Errorf(\"printing summary %s error: %v\", summary.SummaryName(), err))\n\t\t\tcontinue\n\t\t}\n\t\tif ctx.GetClusterLoaderConfig().ReportDir == \"\" {\n\t\t\tglog.Infof(\"%v: %v\", summary.SummaryName(), summaryText)\n\t\t} else {\n\t\t\t\/\/ TODO(krzysied): Remeber to keep original filename style for backward compatibility.\n\t\t\tfilePath := path.Join(ctx.GetClusterLoaderConfig().ReportDir, summary.SummaryName()+\"_\"+conf.Name+\"_\"+time.Now().Format(time.RFC3339)+\".txt\")\n\t\t\tif err := ioutil.WriteFile(filePath, []byte(summaryText), 0644); err != nil {\n\t\t\t\terrList.Append(fmt.Errorf(\"writing to file %v error: %v\", filePath, err))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\treturn errList\n}\n\n\/\/ ExecuteStep executes single test step based on provided step configuration.\nfunc (ste *simpleTestExecutor) ExecuteStep(ctx Context, step *api.Step) *util.ErrorList {\n\tvar wg wait.Group\n\t\/\/ TODO(krzysied): Consider moving lock and errList to separate structure.\n\terrList := util.NewErrorList()\n\tif len(step.Measurements) > 0 {\n\t\tfor i := range step.Measurements {\n\t\t\t\/\/ index is created to make i value unchangeable during thread execution.\n\t\t\tindex := i\n\t\t\twg.Start(func() {\n\t\t\t\terr := ctx.GetMeasurementManager().Execute(step.Measurements[index].Method, step.Measurements[index].Identifier, step.Measurements[index].Params)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrList.Append(fmt.Errorf(\"measurement call %s - %s error: %v\", step.Measurements[index].Method, step.Measurements[index].Identifier, err))\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t} else {\n\t\tfor i := range step.Phases {\n\t\t\tphase := &step.Phases[i]\n\t\t\twg.Start(func() {\n\t\t\t\tif phaseErrList := ste.ExecutePhase(ctx, phase); !phaseErrList.IsEmpty() {\n\t\t\t\t\terrList.Concat(phaseErrList)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\twg.Wait()\n\treturn errList\n}\n\n\/\/ ExecutePhase executes single test phase based on provided phase configuration.\nfunc (ste *simpleTestExecutor) ExecutePhase(ctx Context, phase *api.Phase) *util.ErrorList {\n\t\/\/ TODO: add tuning set\n\terrList := util.NewErrorList()\n\tnsList := createNamespacesList(phase.NamespaceRange)\n\tticker, err := ctx.GetTickerFactory().CreateTicker(phase.TuningSet)\n\tif err != nil {\n\t\treturn util.NewErrorList(fmt.Errorf(\"ticker creation error: %v\", err))\n\t}\n\tdefer ticker.Stop()\n\tvar wg wait.Group\n\tfor namespaceIndex := range nsList {\n\t\tnsName := nsList[namespaceIndex]\n\t\twg.Start(func() {\n\t\t\tinstancesStates := make([]*state.InstancesState, 0)\n\t\t\t\/\/ Updating state (DesiredReplicaCount) of every object in object bundle.\n\t\t\tfor j := range phase.ObjectBundle {\n\t\t\t\tid, err := getIdentifier(ctx, &phase.ObjectBundle[j])\n\t\t\t\tif err != nil {\n\t\t\t\t\terrList.Append(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tinstances, exists := ctx.GetState().Get(nsName, id)\n\t\t\t\tif !exists {\n\t\t\t\t\tinstances = &state.InstancesState{\n\t\t\t\t\t\tDesiredReplicaCount: 0,\n\t\t\t\t\t\tCurrentReplicaCount: 0,\n\t\t\t\t\t\tObject:              phase.ObjectBundle[j],\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tinstances.DesiredReplicaCount = phase.ReplicasPerNamespace\n\t\t\t\tctx.GetState().Set(nsName, id, instances)\n\t\t\t\tinstancesStates = append(instancesStates, instances)\n\t\t\t}\n\n\t\t\t\/\/ Calculating maximal replica count of objects from object bundle.\n\t\t\tvar maxCurrentReplicaCount int32\n\t\t\tfor j := range instancesStates {\n\t\t\t\tif instancesStates[j].CurrentReplicaCount > maxCurrentReplicaCount {\n\t\t\t\t\tmaxCurrentReplicaCount = instancesStates[j].CurrentReplicaCount\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar namespaceWG wait.Group\n\t\t\t\/\/ Deleting objects with index greater or equal requested replicas per namespace number.\n\t\t\t\/\/ Objects will be deleted in reversed order.\n\t\t\tfor replicaCounter := phase.ReplicasPerNamespace; replicaCounter < maxCurrentReplicaCount; replicaCounter++ {\n\t\t\t\treplicaIndex := replicaCounter\n\t\t\t\tnamespaceWG.Start(func() {\n\t\t\t\t\tfor j := len(phase.ObjectBundle) - 1; j >= 0; j-- {\n\t\t\t\t\t\tif replicaIndex < instancesStates[j].CurrentReplicaCount {\n\t\t\t\t\t\t\t<-ticker.C\n\t\t\t\t\t\t\tif objectErrList := ste.ExecuteObject(ctx, &phase.ObjectBundle[j], nsName, replicaIndex, DELETE_OBJECT); !objectErrList.IsEmpty() {\n\t\t\t\t\t\t\t\terrList.Concat(objectErrList)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t\t\/\/ Handling for update\/create objects.\n\t\t\tfor replicaCounter := int32(0); replicaCounter < phase.ReplicasPerNamespace; replicaCounter++ {\n\t\t\t\treplicaIndex := replicaCounter\n\t\t\t\tnamespaceWG.Start(func() {\n\t\t\t\t\tfor j := range phase.ObjectBundle {\n\t\t\t\t\t\tif instancesStates[j].CurrentReplicaCount == phase.ReplicasPerNamespace {\n\t\t\t\t\t\t\t<-ticker.C\n\t\t\t\t\t\t\tif objectErrList := ste.ExecuteObject(ctx, &phase.ObjectBundle[j], nsName, replicaIndex, PATCH_OBJECT); !objectErrList.IsEmpty() {\n\t\t\t\t\t\t\t\terrList.Concat(objectErrList)\n\t\t\t\t\t\t\t\t\/\/ If error then skip this bundle\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if replicaIndex >= instancesStates[j].CurrentReplicaCount {\n\t\t\t\t\t\t\t<-ticker.C\n\t\t\t\t\t\t\tif objectErrList := ste.ExecuteObject(ctx, &phase.ObjectBundle[j], nsName, replicaIndex, CREATE_OBJECT); !objectErrList.IsEmpty() {\n\t\t\t\t\t\t\t\terrList.Concat(objectErrList)\n\t\t\t\t\t\t\t\t\/\/ If error then skip this bundle\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t\tnamespaceWG.Wait()\n\t\t\t\/\/ Updating state (CurrentReplicaCount) of every object in object bundle.\n\t\t\tfor j := range phase.ObjectBundle {\n\t\t\t\tid, _ := getIdentifier(ctx, &phase.ObjectBundle[j])\n\t\t\t\tinstancesStates[j].CurrentReplicaCount = instancesStates[j].DesiredReplicaCount\n\t\t\t\tctx.GetState().Set(nsName, id, instancesStates[j])\n\t\t\t}\n\t\t})\n\t}\n\twg.Wait()\n\treturn errList\n}\n\n\/\/ ExecuteObject executes single test object operation based on provided object configuration.\nfunc (ste *simpleTestExecutor) ExecuteObject(ctx Context, object *api.Object, namespace string, replicaIndex int32, operation OperationType) *util.ErrorList {\n\tobjName := fmt.Sprintf(\"%v-%d\", object.Basename, replicaIndex)\n\tvar err error\n\tvar obj *unstructured.Unstructured\n\tswitch operation {\n\tcase CREATE_OBJECT, PATCH_OBJECT:\n\t\tvar mapping map[string]interface{}\n\t\tif object.TemplateFillMap == nil {\n\t\t\tmapping = make(map[string]interface{})\n\t\t} else {\n\t\t\tmapping = object.TemplateFillMap\n\t\t}\n\t\tmapping[namePlaceholder] = objName\n\t\tmapping[indexPlaceholder] = replicaIndex\n\t\tobj, err = ctx.GetTemplateProvider().TemplateToObject(object.ObjectTemplatePath, mapping)\n\t\tif err != nil {\n\t\t\treturn util.NewErrorList(fmt.Errorf(\"reading template (%v) error: %v\", object.ObjectTemplatePath, err))\n\t\t}\n\tcase DELETE_OBJECT:\n\t\tobj, err = ctx.GetTemplateProvider().RawToObject(object.ObjectTemplatePath)\n\t\tif err != nil {\n\t\t\treturn util.NewErrorList(fmt.Errorf(\"reading template (%v) for deletion error: %v\", object.ObjectTemplatePath, err))\n\t\t}\n\tdefault:\n\t\treturn util.NewErrorList(fmt.Errorf(\"unsupported operation %v for namespace %v object %v\", operation, namespace, objName))\n\t}\n\tgvk := obj.GroupVersionKind()\n\n\terrList := util.NewErrorList()\n\tif namespace == \"\" {\n\t\t\/\/ TODO: handle cluster level object\n\t} else {\n\t\tswitch operation {\n\t\tcase CREATE_OBJECT:\n\t\t\tif err := ctx.GetFramework().CreateObject(namespace, objName, obj); err != nil {\n\t\t\t\terrList.Append(fmt.Errorf(\"namespace %v object %v creation error: %v\", namespace, objName, err))\n\t\t\t}\n\t\tcase PATCH_OBJECT:\n\t\t\tif err := ctx.GetFramework().PatchObject(namespace, objName, obj); err != nil {\n\t\t\t\terrList.Append(fmt.Errorf(\"namespace %v object %v updating error: %v\", namespace, objName, err))\n\t\t\t}\n\t\tcase DELETE_OBJECT:\n\t\t\tif err := ctx.GetFramework().DeleteObject(gvk, namespace, objName); err != nil {\n\t\t\t\terrList.Append(fmt.Errorf(\"namespace %v object %v deletion error: %v\", namespace, objName, err))\n\t\t\t}\n\t\t}\n\t}\n\treturn errList\n}\n\nfunc getIdentifier(ctx Context, object *api.Object) (state.InstancesIdentifier, error) {\n\tobjName := fmt.Sprintf(\"%v-%d\", object.Basename, 0)\n\tvar mapping map[string]interface{}\n\tif object.TemplateFillMap == nil {\n\t\tmapping = make(map[string]interface{})\n\t} else {\n\t\tmapping = object.TemplateFillMap\n\t}\n\tmapping[namePlaceholder] = objName\n\tmapping[indexPlaceholder] = 0\n\tobj, err := ctx.GetTemplateProvider().RawToObject(object.ObjectTemplatePath)\n\tif err != nil {\n\t\treturn state.InstancesIdentifier{}, fmt.Errorf(\"reading template (%v) for identifier error: %v\", object.ObjectTemplatePath, err)\n\t}\n\tgvk := obj.GroupVersionKind()\n\treturn state.InstancesIdentifier{\n\t\tBasename:   object.Basename,\n\t\tObjectKind: gvk.Kind,\n\t\tApiGroup:   gvk.Group,\n\t}, nil\n}\n\nfunc createNamespacesList(namespaceRange *api.NamespaceRange) []string {\n\tif namespaceRange == nil {\n\t\treturn []string{\"\"}\n\t}\n\n\tnsList := make([]string, 0)\n\tnsBasename := framework.AutomanagedNamespaceName\n\tif namespaceRange.Basename != nil {\n\t\tnsBasename = *namespaceRange.Basename\n\t}\n\n\tfor i := namespaceRange.Min; i <= namespaceRange.Max; i++ {\n\t\tnsList = append(nsList, fmt.Sprintf(\"%v-%d\", nsBasename, i))\n\t}\n\treturn nsList\n}\n\nfunc isErrsCritical(*util.ErrorList) bool {\n\t\/\/ TODO: define critical errors\n\treturn false\n}\n\nfunc cleanupResources(ctx Context) {\n\tcleanupStartTime := time.Now()\n\tif errList := ctx.GetFramework().DeleteAutomanagedNamespaces(); !errList.IsEmpty() {\n\t\tglog.Errorf(\"Resource cleanup error: %v\", errList.String())\n\t\treturn\n\t}\n\tglog.Infof(\"Resources cleanup time: %v\", time.Since(cleanupStartTime))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Ninep Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage srv\n\nimport (\n\t\"log\"\n\t\"sync\/atomic\"\n\n\t\"github.com\/lionkov\/ninep\"\n)\n\nfunc (srv *Srv) version(req *Req) {\n\ttc := req.Tc\n\tconn := req.Conn\n\n\tif tc.Msize < ninep.IOHDRSZ {\n\t\treq.RespondError(&ninep.Error{\"msize too small\", ninep.EINVAL})\n\t\treturn\n\t}\n\n\tif tc.Msize < conn.Msize {\n\t\tconn.Msize = tc.Msize\n\t}\n\n\tconn.Dotu = tc.Version == \"9P2000.u\" && srv.Dotu\n\tver := \"9P2000\"\n\tif conn.Dotu {\n\t\tver = \"9P2000.u\"\n\t}\n\n\t\/* make sure that the responses of all current requests will be ignored *\/\n\tconn.Lock()\n\tfor tag, r := range conn.Reqs {\n\t\tif tag == ninep.NOTAG {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor rr := r; rr != nil; rr = rr.next {\n\t\t\trr.Lock()\n\t\t\trr.status |= reqFlush\n\t\t\trr.Unlock()\n\t\t}\n\t}\n\tconn.Unlock()\n\n\tatomic.AddUint32(&srv.Versioned, 1)\n\treq.RespondRversion(conn.Msize, ver)\n}\n\nfunc (srv *Srv) auth(req *Req) {\n\ttc := req.Tc\n\tconn := req.Conn\n\tif tc.Afid == ninep.NOFID {\n\t\treq.RespondError(Eunknownfid)\n\t\treturn\n\t}\n\n\treq.Afid = conn.FidNew(tc.Afid)\n\tif req.Afid == nil {\n\t\tlog.Printf(\"in auth(): Fid %v in use?\", tc.Afid)\n\t\treq.RespondError(Einuse)\n\t\treturn\n\t}\n\n\tvar user ninep.User = nil\n\tif tc.Unamenum != ninep.NOUID || conn.Dotu {\n\t\tuser = srv.Upool.Uid2User(int(tc.Unamenum))\n\t} else if tc.Uname != \"\" {\n\t\tuser = srv.Upool.Uname2User(tc.Uname)\n\t}\n\n\tif user == nil {\n\t\treq.RespondError(Enouser)\n\t\treturn\n\t}\n\n\treq.Afid.User = user\n\treq.Afid.Type = ninep.QTAUTH\n\tif aop, ok := (srv.ops).(AuthOps); ok {\n\t\taqid, err := aop.AuthInit(req.Afid, tc.Aname)\n\t\tif err != nil {\n\t\t\treq.RespondError(err)\n\t\t} else {\n\t\t\taqid.Type |= ninep.QTAUTH \/\/ just in case\n\t\t\treq.RespondRauth(aqid)\n\t\t}\n\t} else {\n\t\treq.RespondError(Enoauth)\n\t}\n\n}\n\nfunc (srv *Srv) authPost(req *Req) {\n\tif req.Rc != nil && req.Rc.Type == ninep.Rauth {\n\t\treq.Afid.IncRef()\n\t}\n}\n\nfunc (srv *Srv) attach(req *Req) {\n\ttc := req.Tc\n\tconn := req.Conn\n\tif tc.Fid == ninep.NOFID {\n\t\treq.RespondError(Eunknownfid)\n\t\treturn\n\t}\n\n\treq.Fid = conn.FidNew(tc.Fid)\n\tif req.Fid == nil {\n\t\tlog.Printf(\"attach: Fid %v in use? \", tc.Fid)\n\t\treq.RespondError(Einuse)\n\t\treturn\n\t}\n\n\tif tc.Afid != ninep.NOFID {\n\t\treq.Afid = conn.FidGet(tc.Afid)\n\t\tif req.Afid == nil {\n\t\t\treq.RespondError(Eunknownfid)\n\t\t}\n\t}\n\n\tvar user ninep.User = nil\n\tif tc.Unamenum != ninep.NOUID || conn.Dotu {\n\t\tuser = srv.Upool.Uid2User(int(tc.Unamenum))\n\t} else if tc.Uname != \"\" {\n\t\tuser = srv.Upool.Uname2User(tc.Uname)\n\t}\n\n\tif user == nil {\n\t\treq.RespondError(Enouser)\n\t\treturn\n\t}\n\n\treq.Fid.User = user\n\tif aop, ok := (srv.ops).(AuthOps); ok {\n\t\terr := aop.AuthCheck(req.Fid, req.Afid, tc.Aname)\n\t\tif err != nil {\n\t\t\treq.RespondError(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t(srv.ops).(ReqOps).Attach(req)\n}\n\nfunc (srv *Srv) attachPost(req *Req) {\n\tif req.Rc != nil && req.Rc.Type == ninep.Rattach {\n\t\treq.Fid.Type = req.Rc.Qid.Type\n\t\treq.Fid.IncRef()\n\t}\n}\n\nfunc (srv *Srv) flush(req *Req) {\n\tconn := req.Conn\n\ttag := req.Tc.Oldtag\n\tninep.PackRflush(req.Rc)\n\tconn.Lock()\n\tr := conn.Reqs[tag]\n\tif r != nil {\n\t\treq.flushreq = r.flushreq\n\t\tr.flushreq = req\n\t}\n\tconn.Unlock()\n\n\tif r == nil {\n\t\t\/\/ there are no requests with that tag\n\t\treq.Respond()\n\t\treturn\n\t}\n\n\tr.Lock()\n\tstatus := r.status\n\tif (status & (reqWork | reqSaved)) == 0 {\n\t\t\/* the request is not worked on yet *\/\n\t\tr.status |= reqFlush\n\t}\n\tr.Unlock()\n\n\tif (status & (reqWork | reqSaved)) == 0 {\n\t\tr.Respond()\n\t} else {\n\t\tif op, ok := (srv.ops).(FlushOp); ok {\n\t\t\top.Flush(r)\n\t\t}\n\t}\n}\n\nfunc (srv *Srv) walk(req *Req) {\n\tconn := req.Conn\n\ttc := req.Tc\n\tfid := req.Fid\n\n\t\/* we can't walk regular files, only clone them *\/\n\tif len(tc.Wname) > 0 && (fid.Type&ninep.QTDIR) == 0 {\n\t\treq.RespondError(Enotdir)\n\t\treturn\n\t}\n\n\t\/* we can't walk open files *\/\n\tif fid.opened {\n\t\treq.RespondError(Ebaduse)\n\t\treturn\n\t}\n\n\tif tc.Fid != tc.Newfid {\n\t\treq.Newfid = conn.FidNew(tc.Newfid)\n\t\tif req.Newfid == nil {\n\t\t\tlog.Printf(\"walk: fid %v in use? \", tc.Newfid)\n\t\t\treq.RespondError(Einuse)\n\t\t\treturn\n\t\t}\n\n\t\treq.Newfid.User = fid.User\n\t\treq.Newfid.Type = fid.Type\n\t} else {\n\t\treq.Newfid = req.Fid\n\t\treq.Newfid.IncRef()\n\t}\n\n\t(req.Conn.Srv.ops).(ReqOps).Walk(req)\n}\n\nfunc (srv *Srv) walkPost(req *Req) {\n\trc := req.Rc\n\tif rc == nil || rc.Type != ninep.Rwalk || req.Newfid == nil {\n\t\treturn\n\t}\n\n\tn := len(rc.Wqid)\n\tif n > 0 {\n\t\treq.Newfid.Type = rc.Wqid[n-1].Type\n\t} else {\n\t\treq.Newfid.Type = req.Fid.Type\n\t}\n\n\t\/\/ Don't retain the fid if only a partial walk succeeded\n\tif n != len(req.Tc.Wname) {\n\t\treturn\n\t}\n\n\tif req.Newfid.fid != req.Fid.fid {\n\t\treq.Newfid.IncRef()\n\t}\n}\n\nfunc (srv *Srv) open(req *Req) {\n\tfid := req.Fid\n\ttc := req.Tc\n\tif fid.opened {\n\t\treq.RespondError(Eopen)\n\t\treturn\n\t}\n\n\tif (fid.Type&ninep.QTDIR) != 0 && tc.Mode != ninep.OREAD {\n\t\treq.RespondError(Eperm)\n\t\treturn\n\t}\n\n\tfid.Omode = tc.Mode\n\t(req.Conn.Srv.ops).(ReqOps).Open(req)\n}\n\nfunc (srv *Srv) openPost(req *Req) {\n\tif req.Fid != nil {\n\t\treq.Fid.opened = req.Rc != nil && req.Rc.Type == ninep.Ropen\n\t}\n}\n\nfunc (srv *Srv) create(req *Req) {\n\tfid := req.Fid\n\ttc := req.Tc\n\tif fid.opened {\n\t\treq.RespondError(Eopen)\n\t\treturn\n\t}\n\n\tif (fid.Type & ninep.QTDIR) == 0 {\n\t\treq.RespondError(Enotdir)\n\t\treturn\n\t}\n\n\t\/* can't open directories for other than reading *\/\n\tif (tc.Perm&ninep.DMDIR) != 0 && tc.Mode != ninep.OREAD {\n\t\treq.RespondError(Eperm)\n\t\treturn\n\t}\n\n\t\/* can't create special files if not 9P2000.u *\/\n\tif (tc.Perm&(ninep.DMNAMEDPIPE|ninep.DMSYMLINK|ninep.DMLINK|ninep.DMDEVICE|ninep.DMSOCKET)) != 0 && !req.Conn.Dotu {\n\t\treq.RespondError(Eperm)\n\t\treturn\n\t}\n\n\tfid.Omode = tc.Mode\n\t(req.Conn.Srv.ops).(ReqOps).Create(req)\n}\n\nfunc (srv *Srv) createPost(req *Req) {\n\tif req.Rc != nil && req.Rc.Type == ninep.Rcreate && req.Fid != nil {\n\t\treq.Fid.Type = req.Rc.Qid.Type\n\t\treq.Fid.opened = true\n\t}\n}\n\nfunc (srv *Srv) read(req *Req) {\n\ttc := req.Tc\n\tfid := req.Fid\n\tif tc.Count+ninep.IOHDRSZ > req.Conn.Msize {\n\t\treq.RespondError(Etoolarge)\n\t\treturn\n\t}\n\n\tif (fid.Type & ninep.QTAUTH) != 0 {\n\t\tvar n int\n\n\t\trc := req.Rc\n\t\terr := ninep.InitRread(rc, tc.Count)\n\t\tif err != nil {\n\t\t\treq.RespondError(err)\n\t\t\treturn\n\t\t}\n\n\t\tif op, ok := (req.Conn.Srv.ops).(AuthOps); ok {\n\t\t\tn, err = op.AuthRead(fid, tc.Offset, rc.Data)\n\t\t\tif err != nil {\n\t\t\t\treq.RespondError(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tninep.SetRreadCount(rc, uint32(n))\n\t\t\treq.Respond()\n\t\t} else {\n\t\t\treq.RespondError(Enotimpl)\n\t\t}\n\n\t\treturn\n\t}\n\n\tif (fid.Type & ninep.QTDIR) != 0 {\n\t\tfid.Lock()\n\t\tif tc.Offset == 0 {\n\t\t\tfid.Diroffset = 0\n\t\t} else if tc.Offset != fid.Diroffset {\n\t\t\t\/\/ This used to be an error, at this\n\t\t\t\/\/ level. But maybe the provider can handle\n\t\t\t\/\/ offsets that change. In one version of 9p\n\t\t\t\/\/ we were able to support arbitrary\n\t\t\t\/\/ offsets. At the least, we're going to let\n\t\t\t\/\/ the provider decide if this is an error.\n\t\t\tfid.Diroffset = tc.Offset\n\t\t}\n\t\tfid.Unlock()\n\t}\n\n\t(req.Conn.Srv.ops).(ReqOps).Read(req)\n}\n\nfunc (srv *Srv) readPost(req *Req) {\n\tif req.Rc != nil && req.Rc.Type == ninep.Rread && (req.Fid.Type&ninep.QTDIR) != 0 {\n\t\treq.Fid.Lock()\n\t\treq.Fid.Diroffset += uint64(req.Rc.Count)\n\t\treq.Fid.Unlock()\n\t}\n}\n\nfunc (srv *Srv) write(req *Req) {\n\tfid := req.Fid\n\ttc := req.Tc\n\tif (fid.Type & ninep.QTAUTH) != 0 {\n\t\ttc := req.Tc\n\t\tif op, ok := (req.Conn.Srv.ops).(AuthOps); ok {\n\t\t\tn, err := op.AuthWrite(req.Fid, tc.Offset, tc.Data)\n\t\t\tif err != nil {\n\t\t\t\treq.RespondError(err)\n\t\t\t} else {\n\t\t\t\treq.RespondRwrite(uint32(n))\n\t\t\t}\n\t\t} else {\n\t\t\treq.RespondError(Enotimpl)\n\t\t}\n\n\t\treturn\n\t}\n\n\tif !fid.opened || (fid.Type&ninep.QTDIR) != 0 || (fid.Omode&3) == ninep.OREAD {\n\t\treq.RespondError(Ebaduse)\n\t\treturn\n\t}\n\n\tif tc.Count+ninep.IOHDRSZ > req.Conn.Msize {\n\t\treq.RespondError(Etoolarge)\n\t\treturn\n\t}\n\n\t(req.Conn.Srv.ops).(ReqOps).Write(req)\n}\n\nfunc (srv *Srv) clunk(req *Req) {\n\tfid := req.Fid\n\tif (fid.Type & ninep.QTAUTH) != 0 {\n\t\tif op, ok := (req.Conn.Srv.ops).(AuthOps); ok {\n\t\t\top.AuthDestroy(fid)\n\t\t\treq.RespondRclunk()\n\t\t} else {\n\t\t\treq.RespondError(Enotimpl)\n\t\t}\n\n\t\treturn\n\t}\n\n\t(req.Conn.Srv.ops).(ReqOps).Clunk(req)\n}\n\nfunc (srv *Srv) clunkPost(req *Req) {\n\tif req.Rc != nil && req.Rc.Type == ninep.Rclunk && req.Fid != nil {\n\t\treq.Fid.DecRef()\n\t}\n}\n\nfunc (srv *Srv) remove(req *Req) { (req.Conn.Srv.ops).(ReqOps).Remove(req) }\n\nfunc (srv *Srv) removePost(req *Req) {\n\tif req.Rc != nil && req.Fid != nil {\n\t\treq.Fid.DecRef()\n\t}\n}\n\nfunc (srv *Srv) stat(req *Req) { (req.Conn.Srv.ops).(ReqOps).Stat(req) }\n\nfunc (srv *Srv) wstat(req *Req) {\n\t\/*\n\t\tfid := req.Fid\n\t\td := &req.Tc.Dir\n\t\tif d.Type != uint16(0xFFFF) || d.Dev != uint32(0xFFFFFFFF) || d.Version != uint32(0xFFFFFFFF) ||\n\t\t\td.Path != uint64(0xFFFFFFFFFFFFFFFF) {\n\t\t\treq.RespondError(Eperm)\n\t\t\treturn\n\t\t}\n\n\t\tif (d.Mode != 0xFFFFFFFF) && (((fid.Type&ninep.QTDIR) != 0 && (d.Mode&ninep.DMDIR) == 0) ||\n\t\t\t((d.Type&ninep.QTDIR) == 0 && (d.Mode&ninep.DMDIR) != 0)) {\n\t\t\treq.RespondError(Edirchange)\n\t\t\treturn\n\t\t}\n\t*\/\n\n\t(req.Conn.Srv.ops).(ReqOps).Wstat(req)\n}\n<commit_msg>Restage \"Check that a fid has been opened in read\"<commit_after>\/\/ Copyright 2009 The Ninep Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage srv\n\nimport (\n\t\"log\"\n\t\"sync\/atomic\"\n\n\t\"github.com\/lionkov\/ninep\"\n)\n\nfunc (srv *Srv) version(req *Req) {\n\ttc := req.Tc\n\tconn := req.Conn\n\n\tif tc.Msize < ninep.IOHDRSZ {\n\t\treq.RespondError(&ninep.Error{\"msize too small\", ninep.EINVAL})\n\t\treturn\n\t}\n\n\tif tc.Msize < conn.Msize {\n\t\tconn.Msize = tc.Msize\n\t}\n\n\tconn.Dotu = tc.Version == \"9P2000.u\" && srv.Dotu\n\tver := \"9P2000\"\n\tif conn.Dotu {\n\t\tver = \"9P2000.u\"\n\t}\n\n\t\/* make sure that the responses of all current requests will be ignored *\/\n\tconn.Lock()\n\tfor tag, r := range conn.Reqs {\n\t\tif tag == ninep.NOTAG {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor rr := r; rr != nil; rr = rr.next {\n\t\t\trr.Lock()\n\t\t\trr.status |= reqFlush\n\t\t\trr.Unlock()\n\t\t}\n\t}\n\tconn.Unlock()\n\n\tatomic.AddUint32(&srv.Versioned, 1)\n\treq.RespondRversion(conn.Msize, ver)\n}\n\nfunc (srv *Srv) auth(req *Req) {\n\ttc := req.Tc\n\tconn := req.Conn\n\tif tc.Afid == ninep.NOFID {\n\t\treq.RespondError(Eunknownfid)\n\t\treturn\n\t}\n\n\treq.Afid = conn.FidNew(tc.Afid)\n\tif req.Afid == nil {\n\t\tlog.Printf(\"in auth(): Fid %v in use?\", tc.Afid)\n\t\treq.RespondError(Einuse)\n\t\treturn\n\t}\n\n\tvar user ninep.User = nil\n\tif tc.Unamenum != ninep.NOUID || conn.Dotu {\n\t\tuser = srv.Upool.Uid2User(int(tc.Unamenum))\n\t} else if tc.Uname != \"\" {\n\t\tuser = srv.Upool.Uname2User(tc.Uname)\n\t}\n\n\tif user == nil {\n\t\treq.RespondError(Enouser)\n\t\treturn\n\t}\n\n\treq.Afid.User = user\n\treq.Afid.Type = ninep.QTAUTH\n\tif aop, ok := (srv.ops).(AuthOps); ok {\n\t\taqid, err := aop.AuthInit(req.Afid, tc.Aname)\n\t\tif err != nil {\n\t\t\treq.RespondError(err)\n\t\t} else {\n\t\t\taqid.Type |= ninep.QTAUTH \/\/ just in case\n\t\t\treq.RespondRauth(aqid)\n\t\t}\n\t} else {\n\t\treq.RespondError(Enoauth)\n\t}\n\n}\n\nfunc (srv *Srv) authPost(req *Req) {\n\tif req.Rc != nil && req.Rc.Type == ninep.Rauth {\n\t\treq.Afid.IncRef()\n\t}\n}\n\nfunc (srv *Srv) attach(req *Req) {\n\ttc := req.Tc\n\tconn := req.Conn\n\tif tc.Fid == ninep.NOFID {\n\t\treq.RespondError(Eunknownfid)\n\t\treturn\n\t}\n\n\treq.Fid = conn.FidNew(tc.Fid)\n\tif req.Fid == nil {\n\t\tlog.Printf(\"attach: Fid %v in use? \", tc.Fid)\n\t\treq.RespondError(Einuse)\n\t\treturn\n\t}\n\n\tif tc.Afid != ninep.NOFID {\n\t\treq.Afid = conn.FidGet(tc.Afid)\n\t\tif req.Afid == nil {\n\t\t\treq.RespondError(Eunknownfid)\n\t\t}\n\t}\n\n\tvar user ninep.User = nil\n\tif tc.Unamenum != ninep.NOUID || conn.Dotu {\n\t\tuser = srv.Upool.Uid2User(int(tc.Unamenum))\n\t} else if tc.Uname != \"\" {\n\t\tuser = srv.Upool.Uname2User(tc.Uname)\n\t}\n\n\tif user == nil {\n\t\treq.RespondError(Enouser)\n\t\treturn\n\t}\n\n\treq.Fid.User = user\n\tif aop, ok := (srv.ops).(AuthOps); ok {\n\t\terr := aop.AuthCheck(req.Fid, req.Afid, tc.Aname)\n\t\tif err != nil {\n\t\t\treq.RespondError(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t(srv.ops).(ReqOps).Attach(req)\n}\n\nfunc (srv *Srv) attachPost(req *Req) {\n\tif req.Rc != nil && req.Rc.Type == ninep.Rattach {\n\t\treq.Fid.Type = req.Rc.Qid.Type\n\t\treq.Fid.IncRef()\n\t}\n}\n\nfunc (srv *Srv) flush(req *Req) {\n\tconn := req.Conn\n\ttag := req.Tc.Oldtag\n\tninep.PackRflush(req.Rc)\n\tconn.Lock()\n\tr := conn.Reqs[tag]\n\tif r != nil {\n\t\treq.flushreq = r.flushreq\n\t\tr.flushreq = req\n\t}\n\tconn.Unlock()\n\n\tif r == nil {\n\t\t\/\/ there are no requests with that tag\n\t\treq.Respond()\n\t\treturn\n\t}\n\n\tr.Lock()\n\tstatus := r.status\n\tif (status & (reqWork | reqSaved)) == 0 {\n\t\t\/* the request is not worked on yet *\/\n\t\tr.status |= reqFlush\n\t}\n\tr.Unlock()\n\n\tif (status & (reqWork | reqSaved)) == 0 {\n\t\tr.Respond()\n\t} else {\n\t\tif op, ok := (srv.ops).(FlushOp); ok {\n\t\t\top.Flush(r)\n\t\t}\n\t}\n}\n\nfunc (srv *Srv) walk(req *Req) {\n\tconn := req.Conn\n\ttc := req.Tc\n\tfid := req.Fid\n\n\t\/* we can't walk regular files, only clone them *\/\n\tif len(tc.Wname) > 0 && (fid.Type&ninep.QTDIR) == 0 {\n\t\treq.RespondError(Enotdir)\n\t\treturn\n\t}\n\n\t\/* we can't walk open files *\/\n\tif fid.opened {\n\t\treq.RespondError(Ebaduse)\n\t\treturn\n\t}\n\n\tif tc.Fid != tc.Newfid {\n\t\treq.Newfid = conn.FidNew(tc.Newfid)\n\t\tif req.Newfid == nil {\n\t\t\tlog.Printf(\"walk: fid %v in use? \", tc.Newfid)\n\t\t\treq.RespondError(Einuse)\n\t\t\treturn\n\t\t}\n\n\t\treq.Newfid.User = fid.User\n\t\treq.Newfid.Type = fid.Type\n\t} else {\n\t\treq.Newfid = req.Fid\n\t\treq.Newfid.IncRef()\n\t}\n\n\t(req.Conn.Srv.ops).(ReqOps).Walk(req)\n}\n\nfunc (srv *Srv) walkPost(req *Req) {\n\trc := req.Rc\n\tif rc == nil || rc.Type != ninep.Rwalk || req.Newfid == nil {\n\t\treturn\n\t}\n\n\tn := len(rc.Wqid)\n\tif n > 0 {\n\t\treq.Newfid.Type = rc.Wqid[n-1].Type\n\t} else {\n\t\treq.Newfid.Type = req.Fid.Type\n\t}\n\n\t\/\/ Don't retain the fid if only a partial walk succeeded\n\tif n != len(req.Tc.Wname) {\n\t\treturn\n\t}\n\n\tif req.Newfid.fid != req.Fid.fid {\n\t\treq.Newfid.IncRef()\n\t}\n}\n\nfunc (srv *Srv) open(req *Req) {\n\tfid := req.Fid\n\ttc := req.Tc\n\tif fid.opened {\n\t\treq.RespondError(Eopen)\n\t\treturn\n\t}\n\n\tif (fid.Type&ninep.QTDIR) != 0 && tc.Mode != ninep.OREAD {\n\t\treq.RespondError(Eperm)\n\t\treturn\n\t}\n\n\tfid.Omode = tc.Mode\n\t(req.Conn.Srv.ops).(ReqOps).Open(req)\n}\n\nfunc (srv *Srv) openPost(req *Req) {\n\tif req.Fid != nil {\n\t\treq.Fid.opened = req.Rc != nil && req.Rc.Type == ninep.Ropen\n\t}\n}\n\nfunc (srv *Srv) create(req *Req) {\n\tfid := req.Fid\n\ttc := req.Tc\n\tif fid.opened {\n\t\treq.RespondError(Eopen)\n\t\treturn\n\t}\n\n\tif (fid.Type & ninep.QTDIR) == 0 {\n\t\treq.RespondError(Enotdir)\n\t\treturn\n\t}\n\n\t\/* can't open directories for other than reading *\/\n\tif (tc.Perm&ninep.DMDIR) != 0 && tc.Mode != ninep.OREAD {\n\t\treq.RespondError(Eperm)\n\t\treturn\n\t}\n\n\t\/* can't create special files if not 9P2000.u *\/\n\tif (tc.Perm&(ninep.DMNAMEDPIPE|ninep.DMSYMLINK|ninep.DMLINK|ninep.DMDEVICE|ninep.DMSOCKET)) != 0 && !req.Conn.Dotu {\n\t\treq.RespondError(Eperm)\n\t\treturn\n\t}\n\n\tfid.Omode = tc.Mode\n\t(req.Conn.Srv.ops).(ReqOps).Create(req)\n}\n\nfunc (srv *Srv) createPost(req *Req) {\n\tif req.Rc != nil && req.Rc.Type == ninep.Rcreate && req.Fid != nil {\n\t\treq.Fid.Type = req.Rc.Qid.Type\n\t\treq.Fid.opened = true\n\t}\n}\n\nfunc (srv *Srv) read(req *Req) {\n\ttc := req.Tc\n\tfid := req.Fid\n\tif tc.Count+ninep.IOHDRSZ > req.Conn.Msize {\n\t\treq.RespondError(Etoolarge)\n\t\treturn\n\t}\n\n\tif (fid.Type & ninep.QTAUTH) != 0 {\n\t\tvar n int\n\n\t\trc := req.Rc\n\t\terr := ninep.InitRread(rc, tc.Count)\n\t\tif err != nil {\n\t\t\treq.RespondError(err)\n\t\t\treturn\n\t\t}\n\n\t\tif op, ok := (req.Conn.Srv.ops).(AuthOps); ok {\n\t\t\tn, err = op.AuthRead(fid, tc.Offset, rc.Data)\n\t\t\tif err != nil {\n\t\t\t\treq.RespondError(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tninep.SetRreadCount(rc, uint32(n))\n\t\t\treq.Respond()\n\t\t} else {\n\t\t\treq.RespondError(Enotimpl)\n\t\t}\n\n\t\treturn\n\t}\n\n\tif !fid.opened || (fid.Omode&3) == ninep.OWRITE {\n\t\treq.RespondError(Ebaduse)\n\t\treturn\n\t}\n\n\tif (fid.Type & ninep.QTDIR) != 0 {\n\t\tfid.Lock()\n\t\tif tc.Offset == 0 {\n\t\t\tfid.Diroffset = 0\n\t\t} else if tc.Offset != fid.Diroffset {\n\t\t\t\/\/ This used to be an error, at this\n\t\t\t\/\/ level. But maybe the provider can handle\n\t\t\t\/\/ offsets that change. In one version of 9p\n\t\t\t\/\/ we were able to support arbitrary\n\t\t\t\/\/ offsets. At the least, we're going to let\n\t\t\t\/\/ the provider decide if this is an error.\n\t\t\tfid.Diroffset = tc.Offset\n\t\t}\n\t\tfid.Unlock()\n\t}\n\n\t(req.Conn.Srv.ops).(ReqOps).Read(req)\n}\n\nfunc (srv *Srv) readPost(req *Req) {\n\tif req.Rc != nil && req.Rc.Type == ninep.Rread && (req.Fid.Type&ninep.QTDIR) != 0 {\n\t\treq.Fid.Lock()\n\t\treq.Fid.Diroffset += uint64(req.Rc.Count)\n\t\treq.Fid.Unlock()\n\t}\n}\n\nfunc (srv *Srv) write(req *Req) {\n\tfid := req.Fid\n\ttc := req.Tc\n\tif (fid.Type & ninep.QTAUTH) != 0 {\n\t\ttc := req.Tc\n\t\tif op, ok := (req.Conn.Srv.ops).(AuthOps); ok {\n\t\t\tn, err := op.AuthWrite(req.Fid, tc.Offset, tc.Data)\n\t\t\tif err != nil {\n\t\t\t\treq.RespondError(err)\n\t\t\t} else {\n\t\t\t\treq.RespondRwrite(uint32(n))\n\t\t\t}\n\t\t} else {\n\t\t\treq.RespondError(Enotimpl)\n\t\t}\n\n\t\treturn\n\t}\n\n\tif !fid.opened || (fid.Type&ninep.QTDIR) != 0 || (fid.Omode&3) == ninep.OREAD {\n\t\treq.RespondError(Ebaduse)\n\t\treturn\n\t}\n\n\tif tc.Count+ninep.IOHDRSZ > req.Conn.Msize {\n\t\treq.RespondError(Etoolarge)\n\t\treturn\n\t}\n\n\t(req.Conn.Srv.ops).(ReqOps).Write(req)\n}\n\nfunc (srv *Srv) clunk(req *Req) {\n\tfid := req.Fid\n\tif (fid.Type & ninep.QTAUTH) != 0 {\n\t\tif op, ok := (req.Conn.Srv.ops).(AuthOps); ok {\n\t\t\top.AuthDestroy(fid)\n\t\t\treq.RespondRclunk()\n\t\t} else {\n\t\t\treq.RespondError(Enotimpl)\n\t\t}\n\n\t\treturn\n\t}\n\n\t(req.Conn.Srv.ops).(ReqOps).Clunk(req)\n}\n\nfunc (srv *Srv) clunkPost(req *Req) {\n\tif req.Rc != nil && req.Rc.Type == ninep.Rclunk && req.Fid != nil {\n\t\treq.Fid.DecRef()\n\t}\n}\n\nfunc (srv *Srv) remove(req *Req) { (req.Conn.Srv.ops).(ReqOps).Remove(req) }\n\nfunc (srv *Srv) removePost(req *Req) {\n\tif req.Rc != nil && req.Fid != nil {\n\t\treq.Fid.DecRef()\n\t}\n}\n\nfunc (srv *Srv) stat(req *Req) { (req.Conn.Srv.ops).(ReqOps).Stat(req) }\n\nfunc (srv *Srv) wstat(req *Req) {\n\t\/*\n\t\tfid := req.Fid\n\t\td := &req.Tc.Dir\n\t\tif d.Type != uint16(0xFFFF) || d.Dev != uint32(0xFFFFFFFF) || d.Version != uint32(0xFFFFFFFF) ||\n\t\t\td.Path != uint64(0xFFFFFFFFFFFFFFFF) {\n\t\t\treq.RespondError(Eperm)\n\t\t\treturn\n\t\t}\n\n\t\tif (d.Mode != 0xFFFFFFFF) && (((fid.Type&ninep.QTDIR) != 0 && (d.Mode&ninep.DMDIR) == 0) ||\n\t\t\t((d.Type&ninep.QTDIR) == 0 && (d.Mode&ninep.DMDIR) != 0)) {\n\t\t\treq.RespondError(Edirchange)\n\t\t\treturn\n\t\t}\n\t*\/\n\n\t(req.Conn.Srv.ops).(ReqOps).Wstat(req)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"fmt\"\n\nvar allocs int\n\nfunc my_append(slice []int, items ...int) []int {\n\ttotal := len(slice)+len(items)\n\n\tif total > cap(slice) {\n\t\tnewSlice := make([]int, len(slice), total*2+1)\n\t\tcopy(newSlice, slice)\n\t\tslice = newSlice\n\t\tallocs++\n\t}\n\n\tn := len(slice)\n\tslice = slice[:total]\n\tcopy(slice[n:], items)\n\treturn slice\n}\n\nfunc main() {\n\tvar s []int\n\n\tfor i := 0; i < 20; i++ {\n\t\tfmt.Println(\"i =\", i, \"s =\", s)\n\t\ts = my_append(s, i)\n\t}\n\n\tfmt.Println(\"Finished, s =\", s)\n\ts = my_append(s, s...)\n\tfmt.Println(\"After appending to itself:\", s)\n\tfmt.Println(\"Total allocations:\", allocs)\n}\n<commit_msg>Updated my_append() example description<commit_after>\/* A small example demonstrating how append() is implemented\n *\n * Based on the ideas exposed in http:\/\/blog.golang.org\/slices\n *\/\n\npackage main\n\nimport \"fmt\"\n\nvar allocs int\n\nfunc my_append(slice []int, items ...int) []int {\n\ttotal := len(slice)+len(items)\n\n\tif total > cap(slice) {\n\t\tnewSlice := make([]int, len(slice), total*2+1)\n\t\tcopy(newSlice, slice)\n\t\tslice = newSlice\n\t\tallocs++\n\t}\n\n\tn := len(slice)\n\tslice = slice[:total]\n\tcopy(slice[n:], items)\n\treturn slice\n}\n\nfunc main() {\n\tvar s []int\n\n\tfor i := 0; i < 20; i++ {\n\t\tfmt.Println(\"i =\", i, \"s =\", s)\n\t\ts = my_append(s, i)\n\t}\n\n\tfmt.Println(\"Finished, s =\", s)\n\ts = my_append(s, s...)\n\tfmt.Println(\"After appending to itself:\", s)\n\tfmt.Println(\"Total allocations:\", allocs)\n}\n<|endoftext|>"}
{"text":"<commit_before>package services\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/url\"\n\n\t\"github.com\/gravitational\/teleport\/lib\/utils\"\n\n\t\"github.com\/coreos\/go-oidc\/jose\"\n\t\"github.com\/gravitational\/trace\"\n)\n\n\/\/ OIDCConnector specifies configuration for Open ID Connect compatible external\n\/\/ identity provider, e.g. google in some organisation\ntype OIDCConnector interface {\n\t\/\/ Name is a provider name, 'e.g.' google, used internally\n\tGetName() string\n\t\/\/ Issuer URL is the endpoint of the provider, e.g. https:\/\/accounts.google.com\n\tGetIssuerURL() string\n\t\/\/ ClientID is id for authentication client (in our case it's our Auth server)\n\tGetClientID() string\n\t\/\/ ClientSecret is used to authenticate our client and should not\n\t\/\/ be visible to end user\n\tGetClientSecret() string\n\t\/\/ RedirectURL - Identity provider will use this URL to redirect\n\t\/\/ client's browser back to it after successfull authentication\n\t\/\/ Should match the URL on Provider's side\n\tGetRedirectURL() string\n\t\/\/ Display - Friendly name for this provider.\n\tGetDisplay() string\n\t\/\/ Scope is additional scopes set by provder\n\tGetScope() []string\n\t\/\/ ClaimsToRoles specifies dynamic mapping from claims to roles\n\tGetClaimsToRoles() []ClaimMapping\n\t\/\/ GetClaims returns list of claims expected by mappings\n\tGetClaims() []string\n\t\/\/ MapClaims maps claims to roles\n\tMapClaims(claims jose.Claims) []string\n\t\/\/ Check checks OIDC connector for errors\n\tCheck() error\n\t\/\/ SetClientSecret sets client secret to some value\n\tSetClientSecret(secret string)\n}\n\nvar connectorMarshaler OIDCConnectorMarshaler = &TeleportOIDCConnectorMarshaler{}\n\n\/\/ SetOIDCConnectorMarshaler sets global user marshaler\nfunc SetOIDCConnectorMarshaler(m OIDCConnectorMarshaler) {\n\tmarshalerMutex.Lock()\n\tdefer marshalerMutex.Unlock()\n\tconnectorMarshaler = m\n}\n\n\/\/ GetOIDCConnectorMarshaler returns currently set user marshaler\nfunc GetOIDCConnectorMarshaler() OIDCConnectorMarshaler {\n\tmarshalerMutex.RLock()\n\tdefer marshalerMutex.RUnlock()\n\treturn connectorMarshaler\n}\n\n\/\/ OIDCConnectorMarshaler implements marshal\/unmarshal of User implementations\n\/\/ mostly adds support for extended versions\ntype OIDCConnectorMarshaler interface {\n\t\/\/ UnmarshalOIDCConnector unmarshals connector from binary representation\n\tUnmarshalOIDCConnector(bytes []byte) (OIDCConnector, error)\n\t\/\/ MarshalOIDCConnector marshals connector to binary representation\n\tMarshalOIDCConnector(c OIDCConnector, opts ...MarshalOption) ([]byte, error)\n}\n\n\/\/ GetOIDCConnectorSchema returns schema for OIDCConnector\nfunc GetOIDCConnectorSchema() string {\n\treturn fmt.Sprintf(OIDCConnectorV2SchemaTemplate, MetadataSchema, OIDCConnectorSpecV2Schema)\n}\n\ntype TeleportOIDCConnectorMarshaler struct{}\n\n\/\/ UnmarshalOIDCConnector unmarshals connector from\nfunc (*TeleportOIDCConnectorMarshaler) UnmarshalOIDCConnector(bytes []byte) (OIDCConnector, error) {\n\tvar h ResourceHeader\n\terr := json.Unmarshal(bytes, &h)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tswitch h.Version {\n\tcase \"\":\n\t\tvar c OIDCConnectorV1\n\t\terr := json.Unmarshal(bytes, &c)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn c.V2(), nil\n\tcase V2:\n\t\tvar c OIDCConnectorV2\n\t\tif err := utils.UnmarshalWithSchema(GetOIDCConnectorSchema(), &c, bytes); err != nil {\n\t\t\treturn nil, trace.BadParameter(err.Error())\n\t\t}\n\t\treturn &c, nil\n\t}\n\n\treturn nil, trace.BadParameter(\"OIDC connector resource version %v is not supported\", h.Version)\n}\n\n\/\/ MarshalUser marshals OIDC connector into JSON\nfunc (*TeleportOIDCConnectorMarshaler) MarshalOIDCConnector(c OIDCConnector, opts ...MarshalOption) ([]byte, error) {\n\tcfg, err := collectOptions(opts)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\ttype connv1 interface {\n\t\tV1() *OIDCConnectorV1\n\t}\n\n\ttype connv2 interface {\n\t\tV2() *OIDCConnectorV2\n\t}\n\tversion := cfg.GetVersion()\n\tswitch version {\n\tcase V1:\n\t\tv, ok := c.(connv1)\n\t\tif !ok {\n\t\t\treturn nil, trace.BadParameter(\"don't know how to marshal %v\", V1)\n\t\t}\n\t\treturn json.Marshal(v.V1())\n\tcase V2:\n\t\tv, ok := c.(connv2)\n\t\tif !ok {\n\t\t\treturn nil, trace.BadParameter(\"don't know how to marshal %v\", V2)\n\t\t}\n\t\treturn json.Marshal(v.V2())\n\tdefault:\n\t\treturn nil, trace.BadParameter(\"version %v is not supported\", version)\n\t}\n}\n\n\/\/ OIDCConnectorV2 is version 1 resource spec for OIDC connector\ntype OIDCConnectorV2 struct {\n\t\/\/ Kind is a resource kind\n\tKind string `json:\"kind\"`\n\t\/\/ Version is version\n\tVersion string `json:\"version\"`\n\t\/\/ Metadata is connector metadata\n\tMetadata Metadata `json:\"metadata\"`\n\t\/\/ Spec contains connector specification\n\tSpec OIDCConnectorSpecV2 `json:\"spec\"`\n}\n\n\/\/ V2 returns V2 version of the resource\nfunc (o *OIDCConnectorV2) V2() *OIDCConnectorV2 {\n\treturn o\n}\n\n\/\/ V1 converts OIDCConnectorV2 to OIDCConnectorV1 format\nfunc (o *OIDCConnectorV2) V1() *OIDCConnectorV1 {\n\treturn &OIDCConnectorV1{\n\t\tID:            o.Metadata.Name,\n\t\tIssuerURL:     o.Spec.IssuerURL,\n\t\tClientID:      o.Spec.ClientID,\n\t\tClientSecret:  o.Spec.ClientSecret,\n\t\tRedirectURL:   o.Spec.RedirectURL,\n\t\tDisplay:       o.Spec.Display,\n\t\tScope:         o.Spec.Scope,\n\t\tClaimsToRoles: o.Spec.ClaimsToRoles,\n\t}\n}\n\n\/\/ SetClientSecret sets client secret to some value\nfunc (o *OIDCConnectorV2) SetClientSecret(secret string) {\n\to.Spec.ClientSecret = secret\n}\n\n\/\/ ID is a provider id, 'e.g.' google, used internally\nfunc (o *OIDCConnectorV2) GetName() string {\n\treturn o.Metadata.Name\n}\n\n\/\/ Issuer URL is the endpoint of the provider, e.g. https:\/\/accounts.google.com\nfunc (o *OIDCConnectorV2) GetIssuerURL() string {\n\treturn o.Spec.IssuerURL\n}\n\n\/\/ ClientID is id for authentication client (in our case it's our Auth server)\nfunc (o *OIDCConnectorV2) GetClientID() string {\n\treturn o.Spec.ClientID\n}\n\n\/\/ ClientSecret is used to authenticate our client and should not\n\/\/ be visible to end user\nfunc (o *OIDCConnectorV2) GetClientSecret() string {\n\treturn o.Spec.ClientSecret\n}\n\n\/\/ RedirectURL - Identity provider will use this URL to redirect\n\/\/ client's browser back to it after successfull authentication\n\/\/ Should match the URL on Provider's side\nfunc (o *OIDCConnectorV2) GetRedirectURL() string {\n\treturn o.Spec.RedirectURL\n}\n\n\/\/ Display - Friendly name for this provider.\nfunc (o *OIDCConnectorV2) GetDisplay() string {\n\tif o.Spec.Display != \"\" {\n\t\treturn o.Spec.Display\n\t}\n\treturn o.GetName()\n}\n\n\/\/ Scope is additional scopes set by provder\nfunc (o *OIDCConnectorV2) GetScope() []string {\n\treturn o.Spec.Scope\n}\n\n\/\/ ClaimsToRoles specifies dynamic mapping from claims to roles\nfunc (o *OIDCConnectorV2) GetClaimsToRoles() []ClaimMapping {\n\treturn o.Spec.ClaimsToRoles\n}\n\n\/\/ GetClaims returns list of claims expected by mappings\nfunc (o *OIDCConnectorV2) GetClaims() []string {\n\tvar out []string\n\tfor _, mapping := range o.Spec.ClaimsToRoles {\n\t\tout = append(out, mapping.Claim)\n\t}\n\treturn utils.Deduplicate(out)\n}\n\n\/\/ MapClaims maps claims to roles\nfunc (o *OIDCConnectorV2) MapClaims(claims jose.Claims) []string {\n\tvar roles []string\n\tfor _, mapping := range o.Spec.ClaimsToRoles {\n\t\tfor claimName := range claims {\n\t\t\tif claimName != mapping.Claim {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tclaimValue, ok, _ := claims.StringClaim(claimName)\n\t\t\tif ok && claimValue == mapping.Value {\n\t\t\t\troles = append(roles, mapping.Roles...)\n\t\t\t}\n\t\t\tclaimValues, ok, _ := claims.StringsClaim(claimName)\n\t\t\tif ok {\n\t\t\t\tfor _, claimValue := range claimValues {\n\t\t\t\t\tif claimValue == mapping.Value {\n\t\t\t\t\t\troles = append(roles, mapping.Roles...)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn utils.Deduplicate(roles)\n}\n\n\/\/ Check returns nil if all parameters are great, err otherwise\nfunc (o *OIDCConnectorV2) Check() error {\n\tif o.Metadata.Name == \"\" {\n\t\treturn trace.BadParameter(\"ID: missing connector name\")\n\t}\n\tif _, err := url.Parse(o.Spec.IssuerURL); err != nil {\n\t\treturn trace.BadParameter(\"IssuerURL: bad url: '%v'\", o.Spec.IssuerURL)\n\t}\n\tif _, err := url.Parse(o.Spec.RedirectURL); err != nil {\n\t\treturn trace.BadParameter(\"RedirectURL: bad url: '%v'\", o.Spec.RedirectURL)\n\t}\n\tif o.Spec.ClientID == \"\" {\n\t\treturn trace.BadParameter(\"ClientID: missing client id\")\n\t}\n\tif o.Spec.ClientSecret == \"\" {\n\t\treturn trace.BadParameter(\"ClientSecret: missing client secret\")\n\t}\n\treturn nil\n}\n\n\/\/ OIDCConnectorV2SchemaTemplate is a template JSON Schema for user\nconst OIDCConnectorV2SchemaTemplate = `{\n  \"type\": \"object\",\n  \"additionalProperties\": false,\n  \"required\": [\"kind\", \"spec\", \"metadata\", \"version\"],\n  \"properties\": {\n    \"kind\": {\"type\": \"string\"},\n    \"version\": {\"type\": \"string\", \"default\": \"v1\"},\n    \"metadata\": %v,\n    \"spec\": %v\n  }\n}`\n\n\/\/ OIDCConnectorSpecV2 specifies configuration for Open ID Connect compatible external\n\/\/ identity provider, e.g. google in some organisation\ntype OIDCConnectorSpecV2 struct {\n\t\/\/ Issuer URL is the endpoint of the provider, e.g. https:\/\/accounts.google.com\n\tIssuerURL string `json:\"issuer_url\"`\n\t\/\/ ClientID is id for authentication client (in our case it's our Auth server)\n\tClientID string `json:\"client_id\"`\n\t\/\/ ClientSecret is used to authenticate our client and should not\n\t\/\/ be visible to end user\n\tClientSecret string `json:\"client_secret\"`\n\t\/\/ RedirectURL - Identity provider will use this URL to redirect\n\t\/\/ client's browser back to it after successfull authentication\n\t\/\/ Should match the URL on Provider's side\n\tRedirectURL string `json:\"redirect_url\"`\n\t\/\/ Display - Friendly name for this provider.\n\tDisplay string `json:\"display,omitempty\"`\n\t\/\/ Scope is additional scopes set by provder\n\tScope []string `json:\"scope,omitempty\"`\n\t\/\/ ClaimsToRoles specifies dynamic mapping from claims to roles\n\tClaimsToRoles []ClaimMapping `json:\"claims_to_roles,omitempty\"`\n}\n\n\/\/ OIDCConnectorSpecV2Schema is a JSON Schema for OIDC Connector\nvar OIDCConnectorSpecV2Schema = fmt.Sprintf(`{\n  \"type\": \"object\",\n  \"additionalProperties\": false,\n  \"required\": [\"issuer_url\", \"client_id\", \"client_secret\", \"redirect_url\"],\n  \"properties\": {\n    \"issuer_url\": {\"type\": \"string\"},\n    \"client_id\": {\"type\": \"string\"},\n    \"client_secret\": {\"type\": \"string\"},\n    \"redirect_url\": {\"type\": \"string\"},\n    \"scope\": {\n      \"type\": \"array\",\n      \"items\": {\n        \"type\": \"string\"\n      }\n    },\n    \"claims_to_roles\": {\n      \"type\": \"array\",\n      \"items\": %v\n    }\n  }\n}`, ClaimMappingSchema)\n\n\/\/ GetClaimNames returns a list of claim names from the claim values\nfunc GetClaimNames(claims jose.Claims) []string {\n\tvar out []string\n\tfor claim := range claims {\n\t\tout = append(out, claim)\n\t}\n\treturn out\n}\n\n\/\/ ClaimMapping is OIDC claim mapping that maps\n\/\/ claim name to teleport roles\ntype ClaimMapping struct {\n\t\/\/ Claim is OIDC claim name\n\tClaim string `json:\"claim\"`\n\t\/\/ Value is claim value to match\n\tValue string `json:\"value\"`\n\t\/\/ Roles is a list of teleport roles to match\n\tRoles []string `json:\"roles\"`\n}\n\n\/\/ ClaimMappingSchema is JSON schema for claim mapping\nconst ClaimMappingSchema = `{\n  \"type\": \"object\",\n  \"additionalProperties\": false,\n  \"required\": [\"claim\", \"value\", \"roles\"],\n  \"properties\": {\n     \"claim\": {\"type\": \"string\"}, \n     \"value\": {\"type\": \"string\"},\n     \"roles\": {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"string\"\n        }\n      }\n   }\n}`\n\n\/\/ OIDCConnectorV1 specifies configuration for Open ID Connect compatible external\n\/\/ identity provider, e.g. google in some organisation\ntype OIDCConnectorV1 struct {\n\t\/\/ ID is a provider id, 'e.g.' google, used internally\n\tID string `json:\"id\"`\n\t\/\/ Issuer URL is the endpoint of the provider, e.g. https:\/\/accounts.google.com\n\tIssuerURL string `json:\"issuer_url\"`\n\t\/\/ ClientID is id for authentication client (in our case it's our Auth server)\n\tClientID string `json:\"client_id\"`\n\t\/\/ ClientSecret is used to authenticate our client and should not\n\t\/\/ be visible to end user\n\tClientSecret string `json:\"client_secret\"`\n\t\/\/ RedirectURL - Identity provider will use this URL to redirect\n\t\/\/ client's browser back to it after successfull authentication\n\t\/\/ Should match the URL on Provider's side\n\tRedirectURL string `json:\"redirect_url\"`\n\t\/\/ Display - Friendly name for this provider.\n\tDisplay string `json:\"display\"`\n\t\/\/ Scope is additional scopes set by provder\n\tScope []string `json:\"scope\"`\n\t\/\/ ClaimsToRoles specifies dynamic mapping from claims to roles\n\tClaimsToRoles []ClaimMapping `json:\"claims_to_roles\"`\n}\n\n\/\/ V1 returns V1 version of the resource\nfunc (o *OIDCConnectorV1) V1() *OIDCConnectorV1 {\n\treturn o\n}\n\n\/\/ V2 returns V2 version of the connector\nfunc (o *OIDCConnectorV1) V2() *OIDCConnectorV2 {\n\treturn &OIDCConnectorV2{\n\t\tKind:    KindOIDCConnector,\n\t\tVersion: V2,\n\t\tMetadata: Metadata{\n\t\t\tName: o.ID,\n\t\t},\n\t\tSpec: OIDCConnectorSpecV2{\n\t\t\tIssuerURL:     o.IssuerURL,\n\t\t\tClientID:      o.ClientID,\n\t\t\tClientSecret:  o.ClientSecret,\n\t\t\tRedirectURL:   o.RedirectURL,\n\t\t\tDisplay:       o.Display,\n\t\t\tScope:         o.Scope,\n\t\t\tClaimsToRoles: o.ClaimsToRoles,\n\t\t},\n\t}\n}\n<commit_msg>add interfaces<commit_after>package services\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/url\"\n\n\t\"github.com\/gravitational\/teleport\/lib\/utils\"\n\n\t\"github.com\/coreos\/go-oidc\/jose\"\n\t\"github.com\/gravitational\/trace\"\n)\n\n\/\/ OIDCConnector specifies configuration for Open ID Connect compatible external\n\/\/ identity provider, e.g. google in some organisation\ntype OIDCConnector interface {\n\t\/\/ Name is a provider name, 'e.g.' google, used internally\n\tGetName() string\n\t\/\/ Issuer URL is the endpoint of the provider, e.g. https:\/\/accounts.google.com\n\tGetIssuerURL() string\n\t\/\/ ClientID is id for authentication client (in our case it's our Auth server)\n\tGetClientID() string\n\t\/\/ ClientSecret is used to authenticate our client and should not\n\t\/\/ be visible to end user\n\tGetClientSecret() string\n\t\/\/ RedirectURL - Identity provider will use this URL to redirect\n\t\/\/ client's browser back to it after successfull authentication\n\t\/\/ Should match the URL on Provider's side\n\tGetRedirectURL() string\n\t\/\/ Display - Friendly name for this provider.\n\tGetDisplay() string\n\t\/\/ Scope is additional scopes set by provder\n\tGetScope() []string\n\t\/\/ ClaimsToRoles specifies dynamic mapping from claims to roles\n\tGetClaimsToRoles() []ClaimMapping\n\t\/\/ GetClaims returns list of claims expected by mappings\n\tGetClaims() []string\n\t\/\/ MapClaims maps claims to roles\n\tMapClaims(claims jose.Claims) []string\n\t\/\/ Check checks OIDC connector for errors\n\tCheck() error\n\t\/\/ SetClientSecret sets client secret to some value\n\tSetClientSecret(secret string)\n\t\/\/ SetClientID sets id for authentication client (in our case it's our Auth server)\n\tSetClientID(string)\n\t\/\/ SetName sets a provider name\n\tSetName(string)\n\t\/\/ SetIssuerURL sets the endpoint of the provider\n\tSetIssuerURL(string)\n\t\/\/ SetRedirectURL sets RedirectURL\n\tSetRedirectURL(string)\n\t\/\/ SetScope sets additional scopes set by provider\n\tSetScope([]string)\n\t\/\/ SetClaimsToRoles sets dynamic mapping from claims to roles\n\tSetClaimsToRoles([]ClaimMapping)\n\t\/\/ SetDisplay sets friendly name for this provider.\n\tSetDisplay(string)\n}\n\nvar connectorMarshaler OIDCConnectorMarshaler = &TeleportOIDCConnectorMarshaler{}\n\n\/\/ SetOIDCConnectorMarshaler sets global user marshaler\nfunc SetOIDCConnectorMarshaler(m OIDCConnectorMarshaler) {\n\tmarshalerMutex.Lock()\n\tdefer marshalerMutex.Unlock()\n\tconnectorMarshaler = m\n}\n\n\/\/ GetOIDCConnectorMarshaler returns currently set user marshaler\nfunc GetOIDCConnectorMarshaler() OIDCConnectorMarshaler {\n\tmarshalerMutex.RLock()\n\tdefer marshalerMutex.RUnlock()\n\treturn connectorMarshaler\n}\n\n\/\/ OIDCConnectorMarshaler implements marshal\/unmarshal of User implementations\n\/\/ mostly adds support for extended versions\ntype OIDCConnectorMarshaler interface {\n\t\/\/ UnmarshalOIDCConnector unmarshals connector from binary representation\n\tUnmarshalOIDCConnector(bytes []byte) (OIDCConnector, error)\n\t\/\/ MarshalOIDCConnector marshals connector to binary representation\n\tMarshalOIDCConnector(c OIDCConnector, opts ...MarshalOption) ([]byte, error)\n}\n\n\/\/ GetOIDCConnectorSchema returns schema for OIDCConnector\nfunc GetOIDCConnectorSchema() string {\n\treturn fmt.Sprintf(OIDCConnectorV2SchemaTemplate, MetadataSchema, OIDCConnectorSpecV2Schema)\n}\n\ntype TeleportOIDCConnectorMarshaler struct{}\n\n\/\/ UnmarshalOIDCConnector unmarshals connector from\nfunc (*TeleportOIDCConnectorMarshaler) UnmarshalOIDCConnector(bytes []byte) (OIDCConnector, error) {\n\tvar h ResourceHeader\n\terr := json.Unmarshal(bytes, &h)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tswitch h.Version {\n\tcase \"\":\n\t\tvar c OIDCConnectorV1\n\t\terr := json.Unmarshal(bytes, &c)\n\t\tif err != nil {\n\t\t\treturn nil, trace.Wrap(err)\n\t\t}\n\t\treturn c.V2(), nil\n\tcase V2:\n\t\tvar c OIDCConnectorV2\n\t\tif err := utils.UnmarshalWithSchema(GetOIDCConnectorSchema(), &c, bytes); err != nil {\n\t\t\treturn nil, trace.BadParameter(err.Error())\n\t\t}\n\t\treturn &c, nil\n\t}\n\n\treturn nil, trace.BadParameter(\"OIDC connector resource version %v is not supported\", h.Version)\n}\n\n\/\/ MarshalUser marshals OIDC connector into JSON\nfunc (*TeleportOIDCConnectorMarshaler) MarshalOIDCConnector(c OIDCConnector, opts ...MarshalOption) ([]byte, error) {\n\tcfg, err := collectOptions(opts)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\ttype connv1 interface {\n\t\tV1() *OIDCConnectorV1\n\t}\n\n\ttype connv2 interface {\n\t\tV2() *OIDCConnectorV2\n\t}\n\tversion := cfg.GetVersion()\n\tswitch version {\n\tcase V1:\n\t\tv, ok := c.(connv1)\n\t\tif !ok {\n\t\t\treturn nil, trace.BadParameter(\"don't know how to marshal %v\", V1)\n\t\t}\n\t\treturn json.Marshal(v.V1())\n\tcase V2:\n\t\tv, ok := c.(connv2)\n\t\tif !ok {\n\t\t\treturn nil, trace.BadParameter(\"don't know how to marshal %v\", V2)\n\t\t}\n\t\treturn json.Marshal(v.V2())\n\tdefault:\n\t\treturn nil, trace.BadParameter(\"version %v is not supported\", version)\n\t}\n}\n\n\/\/ OIDCConnectorV2 is version 1 resource spec for OIDC connector\ntype OIDCConnectorV2 struct {\n\t\/\/ Kind is a resource kind\n\tKind string `json:\"kind\"`\n\t\/\/ Version is version\n\tVersion string `json:\"version\"`\n\t\/\/ Metadata is connector metadata\n\tMetadata Metadata `json:\"metadata\"`\n\t\/\/ Spec contains connector specification\n\tSpec OIDCConnectorSpecV2 `json:\"spec\"`\n}\n\n\/\/ V2 returns V2 version of the resource\nfunc (o *OIDCConnectorV2) V2() *OIDCConnectorV2 {\n\treturn o\n}\n\n\/\/ V1 converts OIDCConnectorV2 to OIDCConnectorV1 format\nfunc (o *OIDCConnectorV2) V1() *OIDCConnectorV1 {\n\treturn &OIDCConnectorV1{\n\t\tID:            o.Metadata.Name,\n\t\tIssuerURL:     o.Spec.IssuerURL,\n\t\tClientID:      o.Spec.ClientID,\n\t\tClientSecret:  o.Spec.ClientSecret,\n\t\tRedirectURL:   o.Spec.RedirectURL,\n\t\tDisplay:       o.Spec.Display,\n\t\tScope:         o.Spec.Scope,\n\t\tClaimsToRoles: o.Spec.ClaimsToRoles,\n\t}\n}\n\n\/\/ SetDisplay sets friendly name for this provider.\nfunc (o *OIDCConnectorV2) SetDisplay(display string) {\n\to.Spec.Display = display\n}\n\n\/\/ SetName sets client secret to some value\nfunc (o *OIDCConnectorV2) SetName(name string) {\n\to.Metadata.Name = name\n}\n\n\/\/ SetIssuerURL sets client secret to some value\nfunc (o *OIDCConnectorV2) SetIssuerURL(issuerURL string) {\n\to.Spec.IssuerURL = issuerURL\n}\n\n\/\/ SetRedirectURL sets client secret to some value\nfunc (o *OIDCConnectorV2) SetRedirectURL(redirectURL string) {\n\to.Spec.RedirectURL = redirectURL\n}\n\n\/\/ SetScope sets additional scopes set by provider\nfunc (o *OIDCConnectorV2) SetScope(scope []string) {\n\to.Spec.Scope = scope\n}\n\n\/\/ SetClaimsToRoles sets dynamic mapping from claims to roles\nfunc (o *OIDCConnectorV2) SetClaimsToRoles(claims []ClaimMapping) {\n\to.Spec.ClaimsToRoles = claims\n}\n\n\/\/ SetClientID sets id for authentication client (in our case it's our Auth server)\nfunc (o *OIDCConnectorV2) SetClientID(clintID string) {\n\to.Spec.ClientID = clintID\n}\n\n\/\/ SetClientSecret sets client secret to some value\nfunc (o *OIDCConnectorV2) SetClientSecret(secret string) {\n\to.Spec.ClientSecret = secret\n}\n\n\/\/ ID is a provider id, 'e.g.' google, used internally\nfunc (o *OIDCConnectorV2) GetName() string {\n\treturn o.Metadata.Name\n}\n\n\/\/ Issuer URL is the endpoint of the provider, e.g. https:\/\/accounts.google.com\nfunc (o *OIDCConnectorV2) GetIssuerURL() string {\n\treturn o.Spec.IssuerURL\n}\n\n\/\/ ClientID is id for authentication client (in our case it's our Auth server)\nfunc (o *OIDCConnectorV2) GetClientID() string {\n\treturn o.Spec.ClientID\n}\n\n\/\/ ClientSecret is used to authenticate our client and should not\n\/\/ be visible to end user\nfunc (o *OIDCConnectorV2) GetClientSecret() string {\n\treturn o.Spec.ClientSecret\n}\n\n\/\/ RedirectURL - Identity provider will use this URL to redirect\n\/\/ client's browser back to it after successfull authentication\n\/\/ Should match the URL on Provider's side\nfunc (o *OIDCConnectorV2) GetRedirectURL() string {\n\treturn o.Spec.RedirectURL\n}\n\n\/\/ Display - Friendly name for this provider.\nfunc (o *OIDCConnectorV2) GetDisplay() string {\n\tif o.Spec.Display != \"\" {\n\t\treturn o.Spec.Display\n\t}\n\treturn o.GetName()\n}\n\n\/\/ Scope is additional scopes set by provder\nfunc (o *OIDCConnectorV2) GetScope() []string {\n\treturn o.Spec.Scope\n}\n\n\/\/ ClaimsToRoles specifies dynamic mapping from claims to roles\nfunc (o *OIDCConnectorV2) GetClaimsToRoles() []ClaimMapping {\n\treturn o.Spec.ClaimsToRoles\n}\n\n\/\/ GetClaims returns list of claims expected by mappings\nfunc (o *OIDCConnectorV2) GetClaims() []string {\n\tvar out []string\n\tfor _, mapping := range o.Spec.ClaimsToRoles {\n\t\tout = append(out, mapping.Claim)\n\t}\n\treturn utils.Deduplicate(out)\n}\n\n\/\/ MapClaims maps claims to roles\nfunc (o *OIDCConnectorV2) MapClaims(claims jose.Claims) []string {\n\tvar roles []string\n\tfor _, mapping := range o.Spec.ClaimsToRoles {\n\t\tfor claimName := range claims {\n\t\t\tif claimName != mapping.Claim {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tclaimValue, ok, _ := claims.StringClaim(claimName)\n\t\t\tif ok && claimValue == mapping.Value {\n\t\t\t\troles = append(roles, mapping.Roles...)\n\t\t\t}\n\t\t\tclaimValues, ok, _ := claims.StringsClaim(claimName)\n\t\t\tif ok {\n\t\t\t\tfor _, claimValue := range claimValues {\n\t\t\t\t\tif claimValue == mapping.Value {\n\t\t\t\t\t\troles = append(roles, mapping.Roles...)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn utils.Deduplicate(roles)\n}\n\n\/\/ Check returns nil if all parameters are great, err otherwise\nfunc (o *OIDCConnectorV2) Check() error {\n\tif o.Metadata.Name == \"\" {\n\t\treturn trace.BadParameter(\"ID: missing connector name\")\n\t}\n\tif _, err := url.Parse(o.Spec.IssuerURL); err != nil {\n\t\treturn trace.BadParameter(\"IssuerURL: bad url: '%v'\", o.Spec.IssuerURL)\n\t}\n\tif _, err := url.Parse(o.Spec.RedirectURL); err != nil {\n\t\treturn trace.BadParameter(\"RedirectURL: bad url: '%v'\", o.Spec.RedirectURL)\n\t}\n\tif o.Spec.ClientID == \"\" {\n\t\treturn trace.BadParameter(\"ClientID: missing client id\")\n\t}\n\tif o.Spec.ClientSecret == \"\" {\n\t\treturn trace.BadParameter(\"ClientSecret: missing client secret\")\n\t}\n\treturn nil\n}\n\n\/\/ OIDCConnectorV2SchemaTemplate is a template JSON Schema for user\nconst OIDCConnectorV2SchemaTemplate = `{\n  \"type\": \"object\",\n  \"additionalProperties\": false,\n  \"required\": [\"kind\", \"spec\", \"metadata\", \"version\"],\n  \"properties\": {\n    \"kind\": {\"type\": \"string\"},\n    \"version\": {\"type\": \"string\", \"default\": \"v1\"},\n    \"metadata\": %v,\n    \"spec\": %v\n  }\n}`\n\n\/\/ OIDCConnectorSpecV2 specifies configuration for Open ID Connect compatible external\n\/\/ identity provider, e.g. google in some organisation\ntype OIDCConnectorSpecV2 struct {\n\t\/\/ Issuer URL is the endpoint of the provider, e.g. https:\/\/accounts.google.com\n\tIssuerURL string `json:\"issuer_url\"`\n\t\/\/ ClientID is id for authentication client (in our case it's our Auth server)\n\tClientID string `json:\"client_id\"`\n\t\/\/ ClientSecret is used to authenticate our client and should not\n\t\/\/ be visible to end user\n\tClientSecret string `json:\"client_secret\"`\n\t\/\/ RedirectURL - Identity provider will use this URL to redirect\n\t\/\/ client's browser back to it after successfull authentication\n\t\/\/ Should match the URL on Provider's side\n\tRedirectURL string `json:\"redirect_url\"`\n\t\/\/ Display - Friendly name for this provider.\n\tDisplay string `json:\"display,omitempty\"`\n\t\/\/ Scope is additional scopes set by provder\n\tScope []string `json:\"scope,omitempty\"`\n\t\/\/ ClaimsToRoles specifies dynamic mapping from claims to roles\n\tClaimsToRoles []ClaimMapping `json:\"claims_to_roles,omitempty\"`\n}\n\n\/\/ OIDCConnectorSpecV2Schema is a JSON Schema for OIDC Connector\nvar OIDCConnectorSpecV2Schema = fmt.Sprintf(`{\n  \"type\": \"object\",\n  \"additionalProperties\": false,\n  \"required\": [\"issuer_url\", \"client_id\", \"client_secret\", \"redirect_url\"],\n  \"properties\": {\n    \"issuer_url\": {\"type\": \"string\"},\n    \"client_id\": {\"type\": \"string\"},\n    \"client_secret\": {\"type\": \"string\"},\n    \"redirect_url\": {\"type\": \"string\"},\n    \"scope\": {\n      \"type\": \"array\",\n      \"items\": {\n        \"type\": \"string\"\n      }\n    },\n    \"claims_to_roles\": {\n      \"type\": \"array\",\n      \"items\": %v\n    }\n  }\n}`, ClaimMappingSchema)\n\n\/\/ GetClaimNames returns a list of claim names from the claim values\nfunc GetClaimNames(claims jose.Claims) []string {\n\tvar out []string\n\tfor claim := range claims {\n\t\tout = append(out, claim)\n\t}\n\treturn out\n}\n\n\/\/ ClaimMapping is OIDC claim mapping that maps\n\/\/ claim name to teleport roles\ntype ClaimMapping struct {\n\t\/\/ Claim is OIDC claim name\n\tClaim string `json:\"claim\"`\n\t\/\/ Value is claim value to match\n\tValue string `json:\"value\"`\n\t\/\/ Roles is a list of teleport roles to match\n\tRoles []string `json:\"roles\"`\n}\n\n\/\/ ClaimMappingSchema is JSON schema for claim mapping\nconst ClaimMappingSchema = `{\n  \"type\": \"object\",\n  \"additionalProperties\": false,\n  \"required\": [\"claim\", \"value\", \"roles\"],\n  \"properties\": {\n     \"claim\": {\"type\": \"string\"}, \n     \"value\": {\"type\": \"string\"},\n     \"roles\": {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"string\"\n        }\n      }\n   }\n}`\n\n\/\/ OIDCConnectorV1 specifies configuration for Open ID Connect compatible external\n\/\/ identity provider, e.g. google in some organisation\ntype OIDCConnectorV1 struct {\n\t\/\/ ID is a provider id, 'e.g.' google, used internally\n\tID string `json:\"id\"`\n\t\/\/ Issuer URL is the endpoint of the provider, e.g. https:\/\/accounts.google.com\n\tIssuerURL string `json:\"issuer_url\"`\n\t\/\/ ClientID is id for authentication client (in our case it's our Auth server)\n\tClientID string `json:\"client_id\"`\n\t\/\/ ClientSecret is used to authenticate our client and should not\n\t\/\/ be visible to end user\n\tClientSecret string `json:\"client_secret\"`\n\t\/\/ RedirectURL - Identity provider will use this URL to redirect\n\t\/\/ client's browser back to it after successfull authentication\n\t\/\/ Should match the URL on Provider's side\n\tRedirectURL string `json:\"redirect_url\"`\n\t\/\/ Display - Friendly name for this provider.\n\tDisplay string `json:\"display\"`\n\t\/\/ Scope is additional scopes set by provder\n\tScope []string `json:\"scope\"`\n\t\/\/ ClaimsToRoles specifies dynamic mapping from claims to roles\n\tClaimsToRoles []ClaimMapping `json:\"claims_to_roles\"`\n}\n\n\/\/ V1 returns V1 version of the resource\nfunc (o *OIDCConnectorV1) V1() *OIDCConnectorV1 {\n\treturn o\n}\n\n\/\/ V2 returns V2 version of the connector\nfunc (o *OIDCConnectorV1) V2() *OIDCConnectorV2 {\n\treturn &OIDCConnectorV2{\n\t\tKind:    KindOIDCConnector,\n\t\tVersion: V2,\n\t\tMetadata: Metadata{\n\t\t\tName: o.ID,\n\t\t},\n\t\tSpec: OIDCConnectorSpecV2{\n\t\t\tIssuerURL:     o.IssuerURL,\n\t\t\tClientID:      o.ClientID,\n\t\t\tClientSecret:  o.ClientSecret,\n\t\t\tRedirectURL:   o.RedirectURL,\n\t\t\tDisplay:       o.Display,\n\t\t\tScope:         o.Scope,\n\t\t\tClaimsToRoles: o.ClaimsToRoles,\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package wats\n\nimport (\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/cf\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/generator\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/helpers\"\n)\n\nvar _ = Describe(\"An application printing a bunch of output\", func() {\n\tvar appName string\n\n\tBeforeEach(func() {\n\t\tappName = generator.RandomName()\n\n\t\tEventually(pushNora(appName), CF_PUSH_TIMEOUT).Should(Succeed())\n\t\tenableDiego(appName)\n\t\tdisableSsh(appName)\n\t\tEventually(runCf(\"start\", appName), CF_PUSH_TIMEOUT).Should(Succeed())\n\t})\n\n\tAfterEach(func() {\n\t\tEventually(cf.Cf(\"logs\", appName, \"--recent\")).Should(Exit())\n\t\tEventually(cf.Cf(\"delete\", appName, \"-f\")).Should(Exit(0))\n\t})\n\n\tXIt(\"doesn't die when printing 32MB\", func() {\n\t\tbeforeId := helpers.CurlApp(appName, \"\/id\")\n\n\t\tExpect(helpers.CurlAppWithTimeout(appName, \"\/logspew\/32000\", DEFAULT_TIMEOUT)).\n\t\t\tTo(ContainSubstring(\"Just wrote 32000 kbytes to the log\"))\n\n\t\tConsistently(func() string {\n\t\t\treturn helpers.CurlApp(appName, \"\/id\")\n\t\t}, \"10s\").Should(Equal(beforeId))\n\t})\n})\n<commit_msg>Enable the output volume test<commit_after>package wats\n\nimport (\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/cf\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/generator\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/helpers\"\n)\n\nvar _ = Describe(\"An application printing a bunch of output\", func() {\n\tvar appName string\n\n\tBeforeEach(func() {\n\t\tappName = generator.RandomName()\n\n\t\tEventually(pushNora(appName), CF_PUSH_TIMEOUT).Should(Succeed())\n\t\tenableDiego(appName)\n\t\tdisableSsh(appName)\n\t\tEventually(runCf(\"start\", appName), CF_PUSH_TIMEOUT).Should(Succeed())\n\t})\n\n\tAfterEach(func() {\n\t\tEventually(cf.Cf(\"logs\", appName, \"--recent\")).Should(Exit())\n\t\tEventually(cf.Cf(\"delete\", appName, \"-f\")).Should(Exit(0))\n\t})\n\n\tIt(\"doesn't die when printing 32MB\", func() {\n\t\tbeforeId := helpers.CurlApp(appName, \"\/id\")\n\n\t\tExpect(helpers.CurlAppWithTimeout(appName, \"\/logspew\/32000\", DEFAULT_TIMEOUT)).\n\t\t\tTo(ContainSubstring(\"Just wrote 32000 kbytes to the log\"))\n\n\t\tConsistently(func() string {\n\t\t\treturn helpers.CurlApp(appName, \"\/id\")\n\t\t}, \"10s\").Should(Equal(beforeId))\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/sai-lab\/mouryou\/lib\/apache\"\n\t\"github.com\/sai-lab\/mouryou\/lib\/logger\"\n)\n\ntype VirtualMachine struct {\n\tId   int    `json:\"id\"`\n\tName string `json:\"name\"`\n\tHost string `json:\"host\"`\n\t\/\/ スループットの平均値\n\tAverage int `json:\"average\"`\n\t\/\/ 基準の重さ\n\tBasicWeight int `json:\"basic_weight\"`\n\t\/\/ 現在の重さ\n\tWeight int `json:\"weight\"`\n\t\/\/ is start machine\n\tIsStartMachine bool `json:\"is_start_machine\"`\n\t\/\/ ハイパーバイザ\n\tHypervisor *HypervisorStruct `json:\"-\"`\n\t\/\/ ベンダー\n\tVendor *VendorStruct `json:\"-\"`\n}\n\n\/\/ ServerState はapache.Scoreboardから負荷状況を受け取り返却します。\nfunc (machine VirtualMachine) ServerStatus() apache.ServerStatus {\n\tvar status apache.ServerStatus\n\n\tboard, err := apache.Scoreboard(machine.Host)\n\tif err != nil {\n\t\t\/\/ errがあった場合、timeoutしていると判断します。\n\t\tstatus.HostName = machine.Name\n\t\tstatus.Other = \"Connection is timeout.\"\n\t} else {\n\t\terr = json.Unmarshal(board, &status)\n\t\tif err != nil {\n\t\t\tlogger.PrintPlace(fmt.Sprint(err))\n\t\t}\n\t}\n\tstatus.Id = machine.Id\n\n\treturn status\n}\n\n\/\/ Bootup はVMの起動処理を行います。\n\/\/ 現在は実際に起動停止は行わないため起動にかかる時間分sleepします。\nfunc (machine VirtualMachine) Bootup(sleep time.Duration) string {\n\t\/\/ connection, err := machine.Hypervisor.Connect()\n\t\/\/ if err != nil {\n\t\/\/ \tpower <- err.Error()\n\t\/\/ \treturn\n\t\/\/ }\n\t\/\/ defer connection.CloseConnection()\n\n\t\/\/ domain, err := connection.LookupDomainByName(machine.Name)\n\t\/\/ if err != nil {\n\t\/\/ \tpower <- err.Error()\n\t\/\/ \treturn\n\t\/\/ }\n\n\t\/\/ err = domain.Create()\n\t\/\/ if err != nil {\n\t\/\/ \tpower <- err.Error()\n\t\/\/ \treturn\n\t\/\/ }\n\n\ttime.Sleep(sleep * time.Second)\n\n\treturn \"booted up\"\n}\n\n\/\/ Bootup はVMの起動処理を行います。\n\/\/ 現在は実際に起動停止は行わないため停止にかかる時間分sleepします。\nfunc (machine VirtualMachine) Shutdown(sleep time.Duration) string {\n\t\/\/ connection, err :=  machine.Hypervisor.Connect() \/\/ here?\n\n\t\/\/ if err != nil {\n\t\/\/ \tpower <- err.Error()\n\t\/\/ \treturn\n\t\/\/ }\n\t\/\/ defer connection.CloseConnection()\n\n\t\/\/ domain, err := connection.LookupDomainByName(machine.Name)\n\t\/\/ if err != nil {\n\t\/\/ \tpower <- err.Error()\n\t\/\/ \treturn\n\t\/\/ }\n\n\t\/\/ time.Sleep(sleep * time.Second)\n\t\/\/ err = domain.Shutdown()\n\t\/\/ if err != nil {\n\t\/\/ \tpower <- err.Error()\n\t\/\/ \tlogger.PrintPlace(fmt.Sprint(err.Error))\n\t\/\/ \treturn\n\t\/\/ }\n\n\ttime.Sleep(sleep * time.Second)\n\n\treturn \"shutted down\"\n}\n<commit_msg>VirtualMachineにOperationを追加<commit_after>package models\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/sai-lab\/mouryou\/lib\/apache\"\n\t\"github.com\/sai-lab\/mouryou\/lib\/logger\"\n)\n\ntype VirtualMachine struct {\n\tId        int    `json:\"id\"`\n\tName      string `json:\"name\"`\n\tHost      string `json:\"host\"`\n\tOperation string `json:\"operation\"`\n\t\/\/ スループットの平均値\n\tAverage int `json:\"average\"`\n\t\/\/ 基準の重さ\n\tBasicWeight int `json:\"basic_weight\"`\n\t\/\/ 現在の重さ\n\tWeight int `json:\"weight\"`\n\t\/\/ is start machine\n\tIsStartMachine bool `json:\"is_start_machine\"`\n\t\/\/ ハイパーバイザ\n\tHypervisor *HypervisorStruct `json:\"-\"`\n\t\/\/ ベンダー\n\tVendor *VendorStruct `json:\"-\"`\n}\n\n\/\/ ServerState はapache.Scoreboardから負荷状況を受け取り返却します。\nfunc (machine VirtualMachine) ServerStatus() apache.ServerStatus {\n\tvar status apache.ServerStatus\n\n\tboard, err := apache.Scoreboard(machine.Host)\n\tif err != nil {\n\t\t\/\/ errがあった場合、timeoutしていると判断します。\n\t\tstatus.HostName = machine.Name\n\t\tstatus.Other = \"Connection is timeout.\"\n\t} else {\n\t\terr = json.Unmarshal(board, &status)\n\t\tif err != nil {\n\t\t\tlogger.PrintPlace(fmt.Sprint(err))\n\t\t}\n\t}\n\tstatus.Id = machine.Id\n\n\treturn status\n}\n\n\/\/ Bootup はVMの起動処理を行います。\n\/\/ 現在は実際に起動停止は行わないため起動にかかる時間分sleepします。\nfunc (machine VirtualMachine) Bootup(sleep time.Duration) string {\n\t\/\/ connection, err := machine.Hypervisor.Connect()\n\t\/\/ if err != nil {\n\t\/\/ \tpower <- err.Error()\n\t\/\/ \treturn\n\t\/\/ }\n\t\/\/ defer connection.CloseConnection()\n\n\t\/\/ domain, err := connection.LookupDomainByName(machine.Name)\n\t\/\/ if err != nil {\n\t\/\/ \tpower <- err.Error()\n\t\/\/ \treturn\n\t\/\/ }\n\n\t\/\/ err = domain.Create()\n\t\/\/ if err != nil {\n\t\/\/ \tpower <- err.Error()\n\t\/\/ \treturn\n\t\/\/ }\n\n\ttime.Sleep(sleep * time.Second)\n\n\treturn \"booted up\"\n}\n\n\/\/ Bootup はVMの起動処理を行います。\n\/\/ 現在は実際に起動停止は行わないため停止にかかる時間分sleepします。\nfunc (machine VirtualMachine) Shutdown(sleep time.Duration) string {\n\t\/\/ connection, err :=  machine.Hypervisor.Connect() \/\/ here?\n\n\t\/\/ if err != nil {\n\t\/\/ \tpower <- err.Error()\n\t\/\/ \treturn\n\t\/\/ }\n\t\/\/ defer connection.CloseConnection()\n\n\t\/\/ domain, err := connection.LookupDomainByName(machine.Name)\n\t\/\/ if err != nil {\n\t\/\/ \tpower <- err.Error()\n\t\/\/ \treturn\n\t\/\/ }\n\n\t\/\/ time.Sleep(sleep * time.Second)\n\t\/\/ err = domain.Shutdown()\n\t\/\/ if err != nil {\n\t\/\/ \tpower <- err.Error()\n\t\/\/ \tlogger.PrintPlace(fmt.Sprint(err.Error))\n\t\/\/ \treturn\n\t\/\/ }\n\n\ttime.Sleep(sleep * time.Second)\n\n\treturn \"shutted down\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package pelican\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"regexp\"\n)\n\nvar validIPv4addr = regexp.MustCompile(`^[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+$`)\n\nvar privateIPv4addr = regexp.MustCompile(`(^127\\.0\\.0\\.1)|(^10\\.)|(^172\\.1[6-9]\\.)|(^172\\.2[0-9]\\.)|(^172\\.3[0-1]\\.)|(^192\\.168\\.)`)\n\nfunc IsRoutableIPv4(ip string) bool {\n\tmatch := privateIPv4addr.FindStringSubmatch(ip)\n\tif match != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc GetExternalIP() string {\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvalid := []string{}\n\n\tfor _, a := range addrs {\n\t\tif ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\n\t\t\taddr := ipnet.IP.String()\n\t\t\tmatch := validIPv4addr.FindStringSubmatch(addr)\n\t\t\tif match != nil {\n\t\t\t\tif addr != \"127.0.0.1\" {\n\t\t\t\t\tvalid = append(valid, addr)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tswitch len(valid) {\n\tcase 0:\n\t\treturn \"127.0.0.1\"\n\tcase 1:\n\t\treturn valid[0]\n\tdefault:\n\t\t\/\/ try to get a routable ip if possible.\n\t\tfor _, ip := range valid {\n\t\t\tif IsRoutableIPv4(ip) {\n\t\t\t\treturn ip\n\t\t\t}\n\t\t}\n\t\t\/\/ give up, just return the first.\n\t\treturn valid[0]\n\t}\n}\n\nfunc GetExternalIPAsInt() int {\n\ts := GetExternalIP()\n\tip := net.ParseIP(s).To4()\n\tif ip == nil {\n\t\treturn 0\n\t}\n\tsum := 0\n\tfor i := 0; i < 4; i++ {\n\t\tmult := 1 << (8 * uint64(3-i))\n\t\t\/\/fmt.Printf(\"mult = %d\\n\", mult)\n\t\tsum += int(mult) * int(ip[i])\n\t\t\/\/fmt.Printf(\"sum = %d\\n\", sum)\n\t}\n\t\/\/fmt.Printf(\"GetExternalIPAsInt() returns %d\\n\", sum)\n\treturn sum\n}\n\n\/\/ sure there's a race here, but should be okay.\n\/\/ :0 asks the OS to give us a free port.\nfunc GetAvailPort() int {\n\tl, _ := net.Listen(\"tcp\", \":0\")\n\tr := l.Addr()\n\tl.Close()\n\treturn r.(*net.TCPAddr).Port\n}\n\nfunc GenAddress() string {\n\tport := GetAvailPort()\n\tip := GetExternalIP()\n\ts := fmt.Sprintf(\"tcp:\/\/%s:%d\", ip, port)\n\t\/\/fmt.Printf(\"GenAddress returning '%s'\\n\", s)\n\treturn s\n}\n\n\/\/ reduce `tcp:\/\/blah:port` to `blah:port`\nvar validSplitOffProto = regexp.MustCompile(`^[^:]*:\/\/(.*)$`)\n\nfunc StripNanomsgAddressPrefix(nanomsgAddr string) (suffix string, err error) {\n\n\tmatch := validSplitOffProto.FindStringSubmatch(nanomsgAddr)\n\tif match == nil || len(match) != 2 {\n\t\treturn \"\", fmt.Errorf(\"could not strip prefix tcp:\/\/ from nanomsg address '%s'\", nanomsgAddr)\n\t}\n\treturn match[1], nil\n}\n<commit_msg>docs++<commit_after>package pelican\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"regexp\"\n)\n\nvar validIPv4addr = regexp.MustCompile(`^[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+$`)\n\nvar privateIPv4addr = regexp.MustCompile(`(^127\\.0\\.0\\.1)|(^10\\.)|(^172\\.1[6-9]\\.)|(^172\\.2[0-9]\\.)|(^172\\.3[0-1]\\.)|(^192\\.168\\.)`)\n\n\/\/ IsRoutableIPv4 returns true if the string in ip represents an IPv4 address that is not\n\/\/ private. See http:\/\/en.wikipedia.org\/wiki\/Private_network#Private_IPv4_address_spaces\n\/\/ for the numeric ranges that are private. 127.0.0.1, 192.168.0.1, and 172.16.0.1 are\n\/\/ examples of non-routables IP addresses.\nfunc IsRoutableIPv4(ip string) bool {\n\tmatch := privateIPv4addr.FindStringSubmatch(ip)\n\tif match != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ GetExternalIP tries to determine the external IP address\n\/\/ used on this host.\nfunc GetExternalIP() string {\n\taddrs, err := net.InterfaceAddrs()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvalid := []string{}\n\n\tfor _, a := range addrs {\n\t\tif ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\n\t\t\taddr := ipnet.IP.String()\n\t\t\tmatch := validIPv4addr.FindStringSubmatch(addr)\n\t\t\tif match != nil {\n\t\t\t\tif addr != \"127.0.0.1\" {\n\t\t\t\t\tvalid = append(valid, addr)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tswitch len(valid) {\n\tcase 0:\n\t\treturn \"127.0.0.1\"\n\tcase 1:\n\t\treturn valid[0]\n\tdefault:\n\t\t\/\/ try to get a routable ip if possible.\n\t\tfor _, ip := range valid {\n\t\t\tif IsRoutableIPv4(ip) {\n\t\t\t\treturn ip\n\t\t\t}\n\t\t}\n\t\t\/\/ give up, just return the first.\n\t\treturn valid[0]\n\t}\n}\n\n\/\/ GetExternalIPAsInt calls GetExternalIP() and then converts\n\/\/ the resulting IPv4 string into an integer.\nfunc GetExternalIPAsInt() int {\n\ts := GetExternalIP()\n\tip := net.ParseIP(s).To4()\n\tif ip == nil {\n\t\treturn 0\n\t}\n\tsum := 0\n\tfor i := 0; i < 4; i++ {\n\t\tmult := 1 << (8 * uint64(3-i))\n\t\t\/\/fmt.Printf(\"mult = %d\\n\", mult)\n\t\tsum += int(mult) * int(ip[i])\n\t\t\/\/fmt.Printf(\"sum = %d\\n\", sum)\n\t}\n\t\/\/fmt.Printf(\"GetExternalIPAsInt() returns %d\\n\", sum)\n\treturn sum\n}\n\n\/\/ GetAvailPort asks the OS for an unused port.\n\/\/ There's a race here, where the port could be grabbed by someone else\n\/\/ before the caller gets to Listen on it, but in practice such races\n\/\/ are rare. Uses net.Listen(\"tcp\", \":0\") to determine a free port, then\n\/\/ releases it back to the OS with Listener.Close().\nfunc GetAvailPort() int {\n\tl, _ := net.Listen(\"tcp\", \":0\")\n\tr := l.Addr()\n\tl.Close()\n\treturn r.(*net.TCPAddr).Port\n}\n\n\/\/ GenAddress generates a local address by calling GetAvailPort() and\n\/\/ GetExternalIP(), then prefixing them with 'tcp:\/\/'.\nfunc GenAddress() string {\n\tport := GetAvailPort()\n\tip := GetExternalIP()\n\ts := fmt.Sprintf(\"tcp:\/\/%s:%d\", ip, port)\n\t\/\/fmt.Printf(\"GenAddress returning '%s'\\n\", s)\n\treturn s\n}\n\n\/\/ reduce `tcp:\/\/blah:port` to `blah:port`\nvar validSplitOffProto = regexp.MustCompile(`^[^:]*:\/\/(.*)$`)\n\n\/\/ StripNanomsgAddressPrefix removes the 'tcp:\/\/' prefix from\n\/\/ nanomsgAddr.\nfunc StripNanomsgAddressPrefix(nanomsgAddr string) (suffix string, err error) {\n\n\tmatch := validSplitOffProto.FindStringSubmatch(nanomsgAddr)\n\tif match == nil || len(match) != 2 {\n\t\treturn \"\", fmt.Errorf(\"could not strip prefix tcp:\/\/ from nanomsg address '%s'\", nanomsgAddr)\n\t}\n\treturn match[1], nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package concat\n\nfunc canFormArray(arr []int, pcs [][]int) bool {\n\treturn false\n}\n<commit_msg>solve 1640 use hashmap<commit_after>package concat\n\nfunc canFormArray(arr []int, pcs [][]int) bool {\n\treturn useHashmap(arr, pcs)\n}\n\n\/\/ useHashmap time complexity O(N) where (N is the length of arr), space compelxity O(N)\nfunc useHashmap(arr []int, pcs [][]int) bool {\n\tn := len(arr)\n\tset := make(map[int]int, n)\n\tfor i := range arr {\n\t\tset[arr[i]] = i\n\t}\n\tfor i := range pcs {\n\t\tcur := pcs[i]\n\t\tif len(cur) == 1 {\n\t\t\tif _, exists := set[cur[0]]; !exists {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tstart := -1\n\t\tcj := 0\n\t\tfor j := range cur {\n\t\t\tif p, exists := set[cur[j]]; exists {\n\t\t\t\tif start == -1 {\n\t\t\t\t\tstart = p\n\t\t\t\t} else {\n\t\t\t\t\tif j-cj != p-start {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>package acceptance_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/lib\/pq\"\n\t\"github.com\/pivotal-golang\/lager\/lagertest\"\n\t\"github.com\/sclevine\/agouti\"\n\t\"github.com\/tedsuo\/ifrit\"\n\t\"github.com\/tedsuo\/ifrit\/ginkgomon\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\t. \"github.com\/sclevine\/agouti\/matchers\"\n\n\t\"github.com\/cloudfoundry\/gunk\/urljoiner\"\n\t\"github.com\/concourse\/atc\"\n\t\"github.com\/concourse\/atc\/db\"\n)\n\nvar _ = Describe(\"Resource Pausing\", func() {\n\tvar atcProcess ifrit.Process\n\tvar dbListener *pq.Listener\n\tvar atcPort uint16\n\n\tBeforeEach(func() {\n\t\tatcBin, err := gexec.Build(\"github.com\/concourse\/atc\/cmd\/atc\")\n\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\tdbLogger := lagertest.NewTestLogger(\"test\")\n\t\tpostgresRunner.CreateTestDB()\n\t\tdbConn = postgresRunner.Open()\n\t\tdbListener = pq.NewListener(postgresRunner.DataSourceName(), time.Second, time.Minute, nil)\n\t\tbus := db.NewNotificationsBus(dbListener)\n\t\tsqlDB = db.NewSQL(dbLogger, dbConn, bus)\n\t\tΩ(err).ShouldNot(HaveOccurred())\n\t\tatcProcess, atcPort = startATC(atcBin, 1)\n\t})\n\n\tAfterEach(func() {\n\t\tginkgomon.Interrupt(atcProcess)\n\n\t\tΩ(dbConn.Close()).Should(Succeed())\n\t\tΩ(dbListener.Close()).Should(Succeed())\n\n\t\tpostgresRunner.DropTestDB()\n\t})\n\n\tDescribe(\"pausing a resource\", func() {\n\t\tvar page *agouti.Page\n\n\t\tBeforeEach(func() {\n\t\t\tvar err error\n\t\t\tpage, err = agoutiDriver.NewPage()\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t})\n\n\t\tAfterEach(func() {\n\t\t\tExpect(page.Destroy()).To(Succeed())\n\t\t})\n\n\t\thomepage := func() string {\n\t\t\treturn fmt.Sprintf(\"http:\/\/127.0.0.1:%d\/pipelines\/%s\", atcPort, atc.DefaultPipelineName)\n\t\t}\n\n\t\twithPath := func(path string) string {\n\t\t\treturn urljoiner.Join(homepage(), path)\n\t\t}\n\n\t\tContext(\"with a resource in the configuration\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\t\/\/ job build data\n\t\t\t\tΩ(sqlDB.SaveConfig(atc.DefaultPipelineName, atc.Config{\n\t\t\t\t\tJobs: atc.JobConfigs{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"job-name\",\n\t\t\t\t\t\t\tPlan: atc.PlanSequence{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tGet: \"resource-name\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tResources: atc.ResourceConfigs{\n\t\t\t\t\t\t{Name: \"resource-name\"},\n\t\t\t\t\t},\n\t\t\t\t}, db.ConfigVersion(1))).Should(Succeed())\n\t\t\t})\n\n\t\t\tIt(\"can view the resource\", func() {\n\t\t\t\t\/\/ homepage -> resource detail\n\t\t\t\tExpect(page.Navigate(homepage())).To(Succeed())\n\t\t\t\tEventually(page.FindByLink(\"resource-name\")).Should(BeFound())\n\t\t\t\tExpect(page.FindByLink(\"resource-name\").Click()).To(Succeed())\n\n\t\t\t\t\/\/ resource detail -> paused resource detail\n\t\t\t\tExpect(page).Should(HaveURL(withPath(\"\/resources\/resource-name\")))\n\t\t\t\tExpect(page.Find(\"h1\")).To(HaveText(\"resource-name\"))\n\n\t\t\t\tAuthenticate(page, \"admin\", \"password\")\n\n\t\t\t\tExpect(page.Find(\".js-pauseUnpause\").Click()).To(Succeed())\n\t\t\t\tEventually(page.Find(\".header h3\")).Should(HaveText(\"checking paused\"))\n\n\t\t\t\tpage.Refresh()\n\n\t\t\t\tEventually(page.Find(\".header h3\")).Should(HaveText(\"checking paused\"))\n\t\t\t})\n\t\t})\n\t})\n})\n<commit_msg>qualify the pause button by js-resource<commit_after>package acceptance_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/lib\/pq\"\n\t\"github.com\/pivotal-golang\/lager\/lagertest\"\n\t\"github.com\/sclevine\/agouti\"\n\t\"github.com\/tedsuo\/ifrit\"\n\t\"github.com\/tedsuo\/ifrit\/ginkgomon\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\t. \"github.com\/sclevine\/agouti\/matchers\"\n\n\t\"github.com\/cloudfoundry\/gunk\/urljoiner\"\n\t\"github.com\/concourse\/atc\"\n\t\"github.com\/concourse\/atc\/db\"\n)\n\nvar _ = Describe(\"Resource Pausing\", func() {\n\tvar atcProcess ifrit.Process\n\tvar dbListener *pq.Listener\n\tvar atcPort uint16\n\n\tBeforeEach(func() {\n\t\tatcBin, err := gexec.Build(\"github.com\/concourse\/atc\/cmd\/atc\")\n\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\tdbLogger := lagertest.NewTestLogger(\"test\")\n\t\tpostgresRunner.CreateTestDB()\n\t\tdbConn = postgresRunner.Open()\n\t\tdbListener = pq.NewListener(postgresRunner.DataSourceName(), time.Second, time.Minute, nil)\n\t\tbus := db.NewNotificationsBus(dbListener)\n\t\tsqlDB = db.NewSQL(dbLogger, dbConn, bus)\n\t\tΩ(err).ShouldNot(HaveOccurred())\n\t\tatcProcess, atcPort = startATC(atcBin, 1)\n\t})\n\n\tAfterEach(func() {\n\t\tginkgomon.Interrupt(atcProcess)\n\n\t\tΩ(dbConn.Close()).Should(Succeed())\n\t\tΩ(dbListener.Close()).Should(Succeed())\n\n\t\tpostgresRunner.DropTestDB()\n\t})\n\n\tDescribe(\"pausing a resource\", func() {\n\t\tvar page *agouti.Page\n\n\t\tBeforeEach(func() {\n\t\t\tvar err error\n\t\t\tpage, err = agoutiDriver.NewPage()\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t})\n\n\t\tAfterEach(func() {\n\t\t\tExpect(page.Destroy()).To(Succeed())\n\t\t})\n\n\t\thomepage := func() string {\n\t\t\treturn fmt.Sprintf(\"http:\/\/127.0.0.1:%d\/pipelines\/%s\", atcPort, atc.DefaultPipelineName)\n\t\t}\n\n\t\twithPath := func(path string) string {\n\t\t\treturn urljoiner.Join(homepage(), path)\n\t\t}\n\n\t\tContext(\"with a resource in the configuration\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\t\/\/ job build data\n\t\t\t\tΩ(sqlDB.SaveConfig(atc.DefaultPipelineName, atc.Config{\n\t\t\t\t\tJobs: atc.JobConfigs{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"job-name\",\n\t\t\t\t\t\t\tPlan: atc.PlanSequence{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tGet: \"resource-name\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tResources: atc.ResourceConfigs{\n\t\t\t\t\t\t{Name: \"resource-name\"},\n\t\t\t\t\t},\n\t\t\t\t}, db.ConfigVersion(1))).Should(Succeed())\n\t\t\t})\n\n\t\t\tIt(\"can view the resource\", func() {\n\t\t\t\t\/\/ homepage -> resource detail\n\t\t\t\tExpect(page.Navigate(homepage())).To(Succeed())\n\t\t\t\tEventually(page.FindByLink(\"resource-name\")).Should(BeFound())\n\t\t\t\tExpect(page.FindByLink(\"resource-name\").Click()).To(Succeed())\n\n\t\t\t\t\/\/ resource detail -> paused resource detail\n\t\t\t\tExpect(page).Should(HaveURL(withPath(\"\/resources\/resource-name\")))\n\t\t\t\tExpect(page.Find(\"h1\")).To(HaveText(\"resource-name\"))\n\n\t\t\t\tAuthenticate(page, \"admin\", \"password\")\n\n\t\t\t\tExpect(page.Find(\".js-resource .js-pauseUnpause\").Click()).To(Succeed())\n\t\t\t\tEventually(page.Find(\".header h3\")).Should(HaveText(\"checking paused\"))\n\n\t\t\t\tpage.Refresh()\n\n\t\t\t\tEventually(page.Find(\".header h3\")).Should(HaveText(\"checking paused\"))\n\t\t\t})\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"net\/url\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\/\/ start when there is no config should report that fact right away\nfunc TestStartWithoutConfig(t *testing.T) {\n\tdone := start(\"\/not\/notaconfig.conf\")\n\tmessage := <- done\n\tif message != \"Could not read file at \/not\/notaconfig.conf\" {\n\t\tt.Errorf(\"did not report the file that was missing\")\n\t}\n}\n\n\/\/ start when there is a bad config should report that fact right away\nfunc TestStartWithBadConfig(t *testing.T) {\n\tdone := start(\".\/test_bad.conf\")\n\tmessage := <- done\n\tif message != \"Could not decode config\" {\n\t\tt.Errorf(\"incorrect bad config mesage\\n\\\"%s\\\"\", message)\n\t}\n}\n\n\/\/ start with a valid file should not be done right away\nfunc TestStartWithGoodConfig(t *testing.T) {\n\tdone := start(\".\/test_good.conf\")\n\tselect {\n\tcase message := <-done:\n\t\tt.Errorf(\"done with message\\n \\\"%s\\\"\", message)\n\tcase <-time.After(time.Millisecond * 50):\n\t\tfmt.Print(\"Stayed up with good config\\n\")\n\t}\n}\n\n\/\/ Stabilizer.ServeHTTP should return the first good response\nfunc TestStabilizerReturnsFirstResponse(t *testing.T) {\n\t\/\/ mock handler that first errors, then takes a long time then returns a\n\t\/\/ a good response\n\treqCount := 0\n\tmockHandler := func(w http.ResponseWriter, r *http.Request) {\n\t\treqCount++\n\t\tif reqCount % 3 == 1 {\n\t\t\thttp.Error(w, \"test error\", 1234567890)\n\t\t}\n\t\tif reqCount % 3 == 2 {\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\tfmt.Fprintf(w, \"slow response\")\n\t\t}\n\t\tif reqCount % 3 == 0 {\n\t\t\tfmt.Fprintf(w, \"fast response\")\n\t\t}\n\t}\n\n\tmockUnstableBackend := httptest.NewServer(http.HandlerFunc(mockHandler))\n\tdefer mockUnstableBackend.Close()\n\tu, err := url.Parse(mockUnstableBackend.URL)\n\tif err != nil { t.Errorf(\"error parsing backend url test broken\") }\n\ttestStabilizer := &Stabilizer{u, 4}\n\ttestStableServer := httptest.NewServer(\n\t\thttp.TimeoutHandler(testStabilizer, 5 * time.Second, \"timeout\"),\n\t)\n\tdefer testStableServer.Close()\n\n\t\/\/ make many requests and make sure they are all the fast response\n\tfor i := 0; i < 10; i++ {\n\t\tres, err := http.Get(testStableServer.URL)\n\t\tif err != nil { t.Errorf(\"error response from stable server\") }\n\n\t\tmessage, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil { t.Errorf(\"error reading response body from stable server\") }\n\t\tres.Body.Close()\n\n\t\t\/\/ ensure that all responses are the fast response\n\t\tif string(message) != \"fast response\" {\n\t\t\tt.Errorf(string(message))\n\t\t}\n\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n}\n\n\/\/ TestCanPass proves that tests are running\nfunc TestCanPass(t *testing.T) {\n\tif true != true {\n\t\tt.Errorf(\"true is not true,\\ncheck your premises,\\n consider clojure?\")\n\t}\n}\n<commit_msg>tests are gentler on the system now<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"net\/url\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\/\/ start when there is no config should report that fact right away\nfunc TestStartWithoutConfig(t *testing.T) {\n\tdone := start(\"\/not\/notaconfig.conf\")\n\tmessage := <- done\n\tif message != \"Could not read file at \/not\/notaconfig.conf\" {\n\t\tt.Errorf(\"did not report the file that was missing\")\n\t}\n}\n\n\/\/ start when there is a bad config should report that fact right away\nfunc TestStartWithBadConfig(t *testing.T) {\n\tdone := start(\".\/test_bad.conf\")\n\tmessage := <- done\n\tif message != \"Could not decode config\" {\n\t\tt.Errorf(\"incorrect bad config mesage\\n\\\"%s\\\"\", message)\n\t}\n}\n\n\/\/ start with a valid file should not be done right away\nfunc TestStartWithGoodConfig(t *testing.T) {\n\tdone := start(\".\/test_good.conf\")\n\tselect {\n\tcase message := <-done:\n\t\tt.Errorf(\"done with message\\n \\\"%s\\\"\", message)\n\tcase <-time.After(time.Millisecond * 50):\n\t\tfmt.Print(\"Stayed up with good config\\n\")\n\t}\n}\n\n\/\/ Stabilizer.ServeHTTP should return the first good response\nfunc TestStabilizerReturnsFirstResponse(t *testing.T) {\n\t\/\/ mock handler that first errors, then takes a long time then returns a\n\t\/\/ a good response\n\treqCount := 0\n\tmockHandler := func(w http.ResponseWriter, r *http.Request) {\n\t\treqCount++\n\t\tif reqCount % 3 == 1 {\n\t\t\thttp.Error(w, \"test error\", 1234567890)\n\t\t}\n\t\tif reqCount % 3 == 2 {\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\tfmt.Fprintf(w, \"slow response\")\n\t\t}\n\t\tif reqCount % 3 == 0 {\n\t\t\tfmt.Fprintf(w, \"fast response\")\n\t\t}\n\t}\n\n\tmockUnstableBackend := httptest.NewServer(http.HandlerFunc(mockHandler))\n\tdefer mockUnstableBackend.Close()\n\tu, err := url.Parse(mockUnstableBackend.URL)\n\tif err != nil { t.Errorf(\"error parsing backend url test broken\") }\n\ttestStabilizer := &Stabilizer{u, 4}\n\ttestStableServer := httptest.NewServer(\n\t\thttp.TimeoutHandler(testStabilizer, 5 * time.Second, \"timeout\"),\n\t)\n\tdefer testStableServer.Close()\n\n\t\/\/ make many requests and make sure they are all the fast response\n\tfor i := 0; i < 3; i++ {\n\t\tres, err := http.Get(testStableServer.URL)\n\t\tif err != nil { t.Errorf(\"error response from stable server\") }\n\n\t\tmessage, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil { t.Errorf(\"error reading response body from stable server\") }\n\t\tres.Body.Close()\n\n\t\t\/\/ ensure that all responses are the fast response\n\t\tif string(message) != \"fast response\" {\n\t\t\tt.Errorf(string(message))\n\t\t}\n\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}\n\n\/\/ TestCanPass proves that tests are running\nfunc TestCanPass(t *testing.T) {\n\tif true != true {\n\t\tt.Errorf(\"true is not true,\\ncheck your premises,\\n consider clojure?\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2022 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/go:build go1.18\n\/\/ +build go1.18\n\npackage vulncheck\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/google\/go-cmp\/cmp\"\n\t\"github.com\/google\/go-cmp\/cmp\/cmpopts\"\n\t\"golang.org\/x\/tools\/go\/packages\"\n\t\"golang.org\/x\/tools\/gopls\/internal\/lsp\/cache\"\n\t\"golang.org\/x\/tools\/gopls\/internal\/lsp\/fake\"\n\t\"golang.org\/x\/tools\/gopls\/internal\/lsp\/source\"\n\t\"golang.org\/x\/tools\/gopls\/internal\/lsp\/tests\"\n\t\"golang.org\/x\/vuln\/client\"\n\t\"golang.org\/x\/vuln\/osv\"\n)\n\nfunc TestCmd_Run(t *testing.T) {\n\trunTest(t, workspace1, proxy1, func(ctx context.Context, snapshot source.Snapshot) {\n\t\tcmd := &cmd{Client: testClient1}\n\t\tcfg := packagesCfg(ctx, snapshot)\n\t\tresult, err := cmd.Run(ctx, cfg, \".\/...\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t\/\/ Check that we find the right number of vulnerabilities.\n\t\t\/\/ There should be three entries as there are three vulnerable\n\t\t\/\/ symbols in the two import-reachable OSVs.\n\t\tvar got []report\n\t\tfor _, v := range result {\n\t\t\tgot = append(got, toReport(v))\n\t\t}\n\t\t\/\/ drop the workspace root directory path included in the summary.\n\t\tcwd := cfg.Dir\n\t\tfor _, g := range got {\n\t\t\tfor i, summary := range g.CallStackSummaries {\n\t\t\t\tg.CallStackSummaries[i] = strings.ReplaceAll(summary, cwd, \".\")\n\t\t\t}\n\t\t}\n\n\t\tvar want = []report{\n\t\t\t{\n\t\t\t\tVuln: Vuln{\n\t\t\t\t\tID:             \"GO-2022-01\",\n\t\t\t\t\tSymbol:         \"VulnData.Vuln1\",\n\t\t\t\t\tPkgPath:        \"golang.org\/amod\/avuln\",\n\t\t\t\t\tModPath:        \"golang.org\/amod\",\n\t\t\t\t\tURL:            \"https:\/\/pkg.go.dev\/vuln\/GO-2022-01\",\n\t\t\t\t\tCurrentVersion: \"v1.1.3\",\n\t\t\t\t\tFixedVersion:   \"v1.0.4\",\n\t\t\t\t\tCallStackSummaries: []string{\n\t\t\t\t\t\t\"golang.org\/entry\/x.X calls golang.org\/amod\/avuln.VulnData.Vuln1\",\n\t\t\t\t\t\t\"golang.org\/entry\/x.X calls golang.org\/cmod\/c.C1, which eventually calls golang.org\/amod\/avuln.VulnData.Vuln2\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCallStacksStr: []string{\n\t\t\t\t\t\"golang.org\/entry\/x.X [approx.] (x.go:8)\\n\" +\n\t\t\t\t\t\t\"golang.org\/amod\/avuln.VulnData.Vuln1 (avuln.go:3)\\n\",\n\t\t\t\t\t\"golang.org\/entry\/x.X (x.go:8)\\n\" +\n\t\t\t\t\t\t\"golang.org\/cmod\/c.C1 (c.go:13)\\n\" +\n\t\t\t\t\t\t\"golang.org\/amod\/avuln.VulnData.Vuln2 (avuln.go:4)\\n\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tVuln: Vuln{\n\t\t\t\t\tID:                 \"GO-2022-02\",\n\t\t\t\t\tSymbol:             \"Vuln\",\n\t\t\t\t\tPkgPath:            \"golang.org\/bmod\/bvuln\",\n\t\t\t\t\tModPath:            \"golang.org\/bmod\",\n\t\t\t\t\tURL:                \"https:\/\/pkg.go.dev\/vuln\/GO-2022-02\",\n\t\t\t\t\tCurrentVersion:     \"v0.5.0\",\n\t\t\t\t\tCallStackSummaries: []string{\"golang.org\/entry\/y.Y calls golang.org\/bmod\/bvuln.Vuln\"},\n\t\t\t\t},\n\t\t\t\tCallStacksStr: []string{\n\t\t\t\t\t\"golang.org\/entry\/y.Y [approx.] (y.go:5)\\n\" +\n\t\t\t\t\t\t\"golang.org\/bmod\/bvuln.Vuln (bvuln.go:2)\\n\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tVuln: Vuln{\n\t\t\t\t\tID:           \"GO-2022-03\",\n\t\t\t\t\tDetails:      \"unaffecting vulnerability\",\n\t\t\t\t\tModPath:      \"golang.org\/amod\",\n\t\t\t\t\tURL:          \"https:\/\/pkg.go.dev\/vuln\/GO-2022-03\",\n\t\t\t\t\tFixedVersion: \"v1.0.4\",\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t\/\/ sort reports for stability before comparison.\n\t\tfor _, rpts := range [][]report{got, want} {\n\t\t\tsort.Slice(rpts, func(i, j int) bool {\n\t\t\t\ta, b := rpts[i], rpts[j]\n\t\t\t\tif a.ID != b.ID {\n\t\t\t\t\treturn a.ID < b.ID\n\t\t\t\t}\n\t\t\t\tif a.PkgPath != b.PkgPath {\n\t\t\t\t\treturn a.PkgPath < b.PkgPath\n\t\t\t\t}\n\t\t\t\treturn a.Symbol < b.Symbol\n\t\t\t})\n\t\t}\n\t\tif diff := cmp.Diff(want, got, cmpopts.IgnoreFields(report{}, \"Vuln.CallStacks\")); diff != \"\" {\n\t\t\tt.Error(diff)\n\t\t}\n\n\t})\n}\n\ntype report struct {\n\tVuln\n\t\/\/ Trace is stringified Vuln.CallStacks\n\tCallStacksStr []string\n}\n\nfunc toReport(v Vuln) report {\n\tvar r = report{Vuln: v}\n\tfor _, s := range v.CallStacks {\n\t\tr.CallStacksStr = append(r.CallStacksStr, CallStackString(s))\n\t}\n\treturn r\n}\n\nfunc CallStackString(callstack CallStack) string {\n\tvar b bytes.Buffer\n\tfor _, entry := range callstack {\n\t\tfname := filepath.Base(entry.URI.SpanURI().Filename())\n\t\tfmt.Fprintf(&b, \"%v (%v:%d)\\n\", entry.Name, fname, entry.Pos.Line)\n\t}\n\treturn b.String()\n}\n\nconst workspace1 = `\n-- go.mod --\nmodule golang.org\/entry\n\nrequire (\n\tgolang.org\/cmod v1.1.3\n)\ngo 1.18\n-- x\/x.go --\npackage x\n\nimport \t(\n   \"golang.org\/cmod\/c\"\n   \"golang.org\/entry\/y\"\n)\n\nfunc X() {\n\tc.C1().Vuln1() \/\/ vuln use: X -> Vuln1\n}\n\nfunc CallY() {\n\ty.Y()  \/\/ vuln use: CallY -> y.Y -> bvuln.Vuln \n}\n\n-- y\/y.go --\npackage y\n\nimport \"golang.org\/cmod\/c\"\n\nfunc Y() {\n\tc.C2()() \/\/ vuln use: Y -> bvuln.Vuln\n}\n`\n\nconst proxy1 = `\n-- golang.org\/cmod@v1.1.3\/go.mod --\nmodule golang.org\/cmod\n\ngo 1.12\n-- golang.org\/cmod@v1.1.3\/c\/c.go --\npackage c\n\nimport (\n\t\"golang.org\/amod\/avuln\"\n\t\"golang.org\/bmod\/bvuln\"\n)\n\ntype I interface {\n\tVuln1()\n}\n\nfunc C1() I {\n\tv := avuln.VulnData{}\n\tv.Vuln2() \/\/ vuln use\n\treturn v\n}\n\nfunc C2() func() {\n\treturn bvuln.Vuln\n}\n-- golang.org\/amod@v1.1.3\/go.mod --\nmodule golang.org\/amod\n\ngo 1.14\n-- golang.org\/amod@v1.1.3\/avuln\/avuln.go --\npackage avuln\n\ntype VulnData struct {}\nfunc (v VulnData) Vuln1() {}\nfunc (v VulnData) Vuln2() {}\n-- golang.org\/bmod@v0.5.0\/go.mod --\nmodule golang.org\/bmod\n\ngo 1.14\n-- golang.org\/bmod@v0.5.0\/bvuln\/bvuln.go --\npackage bvuln\n\nfunc Vuln() {\n\t\/\/ something evil\n}\n`\n\n\/\/ testClient contains the following test vulnerabilities\n\/\/\n\/\/\tgolang.org\/amod\/avuln.{VulnData.Vuln1, vulnData.Vuln2}\n\/\/\tgolang.org\/bmod\/bvuln.{Vuln}\nvar testClient1 = &mockClient{\n\tret: map[string][]*osv.Entry{\n\t\t\"golang.org\/amod\": {\n\t\t\t{\n\t\t\t\tID: \"GO-2022-01\",\n\t\t\t\tReferences: []osv.Reference{\n\t\t\t\t\t{\n\t\t\t\t\t\tType: \"href\",\n\t\t\t\t\t\tURL:  \"pkg.go.dev\/vuln\/GO-2022-01\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tAffected: []osv.Affected{{\n\t\t\t\t\tPackage: osv.Package{Name: \"golang.org\/amod\"},\n\t\t\t\t\tRanges:  osv.Affects{{Type: osv.TypeSemver, Events: []osv.RangeEvent{{Introduced: \"1.0.0\"}, {Fixed: \"1.0.4\"}, {Introduced: \"1.1.2\"}}}},\n\t\t\t\t\tEcosystemSpecific: osv.EcosystemSpecific{\n\t\t\t\t\t\tImports: []osv.EcosystemSpecificImport{{\n\t\t\t\t\t\t\tPath:    \"golang.org\/amod\/avuln\",\n\t\t\t\t\t\t\tSymbols: []string{\"VulnData.Vuln1\", \"VulnData.Vuln2\"}}},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t\t{\n\t\t\t\tID:      \"GO-2022-03\",\n\t\t\t\tDetails: \"unaffecting vulnerability\",\n\t\t\t\tReferences: []osv.Reference{\n\t\t\t\t\t{\n\t\t\t\t\t\tType: \"href\",\n\t\t\t\t\t\tURL:  \"pkg.go.dev\/vuln\/GO-2022-01\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tAffected: []osv.Affected{{\n\t\t\t\t\tPackage: osv.Package{Name: \"golang.org\/amod\"},\n\t\t\t\t\tRanges:  osv.Affects{{Type: osv.TypeSemver, Events: []osv.RangeEvent{{Introduced: \"1.0.0\"}, {Fixed: \"1.0.4\"}, {Introduced: \"1.1.2\"}}}},\n\t\t\t\t\tEcosystemSpecific: osv.EcosystemSpecific{\n\t\t\t\t\t\tImports: []osv.EcosystemSpecificImport{{\n\t\t\t\t\t\t\tPath:    \"golang.org\/amod\/avuln\",\n\t\t\t\t\t\t\tSymbols: []string{\"nonExisting\"}}},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t},\n\t\t\"golang.org\/bmod\": {\n\t\t\t{\n\t\t\t\tID: \"GO-2022-02\",\n\t\t\t\tAffected: []osv.Affected{{\n\t\t\t\t\tPackage: osv.Package{Name: \"golang.org\/bmod\"},\n\t\t\t\t\tRanges:  osv.Affects{{Type: osv.TypeSemver}},\n\t\t\t\t\tEcosystemSpecific: osv.EcosystemSpecific{\n\t\t\t\t\t\tImports: []osv.EcosystemSpecificImport{{\n\t\t\t\t\t\t\tPath:    \"golang.org\/bmod\/bvuln\",\n\t\t\t\t\t\t\tSymbols: []string{\"Vuln\"}}},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t},\n\t},\n}\n\ntype mockClient struct {\n\tclient.Client\n\tret map[string][]*osv.Entry\n}\n\nfunc (mc *mockClient) GetByModule(ctx context.Context, a string) ([]*osv.Entry, error) {\n\treturn mc.ret[a], nil\n}\n\nfunc runTest(t *testing.T, workspaceData, proxyData string, test func(context.Context, source.Snapshot)) {\n\tws, err := fake.NewSandbox(&fake.SandboxConfig{\n\t\tFiles:      fake.UnpackTxt(workspaceData),\n\t\tProxyFiles: fake.UnpackTxt(proxyData),\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer ws.Close()\n\n\tctx := tests.Context(t)\n\n\t\/\/ get the module cache populated and the go.sum file at the root auto-generated.\n\tdir := ws.Workdir.RootURI().SpanURI().Filename()\n\tif err := ws.RunGoCommand(ctx, dir, \"list\", []string{\"-mod=mod\", \"...\"}, true); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcache := cache.New(nil, nil, nil)\n\tsession := cache.NewSession(ctx)\n\toptions := source.DefaultOptions().Clone()\n\ttests.DefaultOptions(options)\n\tsession.SetOptions(options)\n\tenvs := []string{}\n\tfor k, v := range ws.GoEnv() {\n\t\tenvs = append(envs, k+\"=\"+v)\n\t}\n\toptions.SetEnvSlice(envs)\n\tname := ws.RootDir()\n\tfolder := ws.Workdir.RootURI().SpanURI()\n\tview, snapshot, release, err := session.NewView(ctx, name, folder, options)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefer func() {\n\t\t\/\/ The snapshot must be released before calling view.Shutdown, to avoid a\n\t\t\/\/ deadlock.\n\t\trelease()\n\t\tview.Shutdown(ctx)\n\t}()\n\n\ttest(ctx, snapshot)\n}\n\n\/\/ TODO: expose this as a method of Snapshot.\nfunc packagesCfg(ctx context.Context, snapshot source.Snapshot) *packages.Config {\n\tview := snapshot.View()\n\tviewBuildFlags := view.Options().BuildFlags\n\tvar viewEnv []string\n\tif e := view.Options().EnvSlice(); e != nil {\n\t\tviewEnv = append(os.Environ(), e...)\n\t}\n\treturn &packages.Config{\n\t\t\/\/ Mode will be set by cmd.Run.\n\t\tContext:    ctx,\n\t\tTests:      true,\n\t\tBuildFlags: viewBuildFlags,\n\t\tEnv:        viewEnv,\n\t\tDir:        view.Folder().Filename(),\n\t}\n}\n<commit_msg>gopls\/internal\/vulncheck: use vulntest for test database creation<commit_after>\/\/ Copyright 2022 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/go:build go1.18\n\/\/ +build go1.18\n\npackage vulncheck\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/google\/go-cmp\/cmp\"\n\t\"github.com\/google\/go-cmp\/cmp\/cmpopts\"\n\t\"golang.org\/x\/tools\/go\/packages\"\n\t\"golang.org\/x\/tools\/gopls\/internal\/lsp\/cache\"\n\t\"golang.org\/x\/tools\/gopls\/internal\/lsp\/fake\"\n\t\"golang.org\/x\/tools\/gopls\/internal\/lsp\/source\"\n\t\"golang.org\/x\/tools\/gopls\/internal\/lsp\/tests\"\n\t\"golang.org\/x\/tools\/gopls\/internal\/vulncheck\/vulntest\"\n)\n\nfunc TestCmd_Run(t *testing.T) {\n\trunTest(t, workspace1, proxy1, func(ctx context.Context, snapshot source.Snapshot) {\n\t\tdb, err := vulntest.NewDatabase(ctx, []byte(vulnsData))\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer db.Clean()\n\t\tcli, err := vulntest.NewClient(db)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tcmd := &cmd{Client: cli}\n\t\tcfg := packagesCfg(ctx, snapshot)\n\t\tresult, err := cmd.Run(ctx, cfg, \".\/...\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\t\/\/ Check that we find the right number of vulnerabilities.\n\t\t\/\/ There should be three entries as there are three vulnerable\n\t\t\/\/ symbols in the two import-reachable OSVs.\n\t\tvar got []report\n\t\tfor _, v := range result {\n\t\t\tgot = append(got, toReport(v))\n\t\t}\n\t\t\/\/ drop the workspace root directory path included in the summary.\n\t\tcwd := cfg.Dir\n\t\tfor _, g := range got {\n\t\t\tfor i, summary := range g.CallStackSummaries {\n\t\t\t\tg.CallStackSummaries[i] = strings.ReplaceAll(summary, cwd, \".\")\n\t\t\t}\n\t\t}\n\n\t\tvar want = []report{\n\t\t\t{\n\t\t\t\tVuln: Vuln{\n\t\t\t\t\tID:             \"GO-2022-01\",\n\t\t\t\t\tDetails:        \"Something.\\n\",\n\t\t\t\t\tSymbol:         \"VulnData.Vuln1\",\n\t\t\t\t\tPkgPath:        \"golang.org\/amod\/avuln\",\n\t\t\t\t\tModPath:        \"golang.org\/amod\",\n\t\t\t\t\tURL:            \"https:\/\/pkg.go.dev\/vuln\/GO-2022-01\",\n\t\t\t\t\tCurrentVersion: \"v1.1.3\",\n\t\t\t\t\tFixedVersion:   \"v1.0.4\",\n\t\t\t\t\tCallStackSummaries: []string{\n\t\t\t\t\t\t\"golang.org\/entry\/x.X calls golang.org\/amod\/avuln.VulnData.Vuln1\",\n\t\t\t\t\t\t\"golang.org\/entry\/x.X calls golang.org\/cmod\/c.C1, which eventually calls golang.org\/amod\/avuln.VulnData.Vuln2\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCallStacksStr: []string{\n\t\t\t\t\t\"golang.org\/entry\/x.X [approx.] (x.go:8)\\n\" +\n\t\t\t\t\t\t\"golang.org\/amod\/avuln.VulnData.Vuln1 (avuln.go:3)\\n\",\n\t\t\t\t\t\"golang.org\/entry\/x.X (x.go:8)\\n\" +\n\t\t\t\t\t\t\"golang.org\/cmod\/c.C1 (c.go:13)\\n\" +\n\t\t\t\t\t\t\"golang.org\/amod\/avuln.VulnData.Vuln2 (avuln.go:4)\\n\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tVuln: Vuln{\n\t\t\t\t\tID:                 \"GO-2022-02\",\n\t\t\t\t\tSymbol:             \"Vuln\",\n\t\t\t\t\tPkgPath:            \"golang.org\/bmod\/bvuln\",\n\t\t\t\t\tModPath:            \"golang.org\/bmod\",\n\t\t\t\t\tURL:                \"https:\/\/pkg.go.dev\/vuln\/GO-2022-02\",\n\t\t\t\t\tCurrentVersion:     \"v0.5.0\",\n\t\t\t\t\tCallStackSummaries: []string{\"golang.org\/entry\/y.Y calls golang.org\/bmod\/bvuln.Vuln\"},\n\t\t\t\t},\n\t\t\t\tCallStacksStr: []string{\n\t\t\t\t\t\"golang.org\/entry\/y.Y [approx.] (y.go:5)\\n\" +\n\t\t\t\t\t\t\"golang.org\/bmod\/bvuln.Vuln (bvuln.go:2)\\n\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tVuln: Vuln{\n\t\t\t\t\tID:           \"GO-2022-03\",\n\t\t\t\t\tDetails:      \"unaffecting vulnerability.\\n\",\n\t\t\t\t\tModPath:      \"golang.org\/amod\",\n\t\t\t\t\tURL:          \"https:\/\/pkg.go.dev\/vuln\/GO-2022-03\",\n\t\t\t\t\tFixedVersion: \"v1.0.4\",\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\t\/\/ sort reports for stability before comparison.\n\t\tfor _, rpts := range [][]report{got, want} {\n\t\t\tsort.Slice(rpts, func(i, j int) bool {\n\t\t\t\ta, b := rpts[i], rpts[j]\n\t\t\t\tif a.ID != b.ID {\n\t\t\t\t\treturn a.ID < b.ID\n\t\t\t\t}\n\t\t\t\tif a.PkgPath != b.PkgPath {\n\t\t\t\t\treturn a.PkgPath < b.PkgPath\n\t\t\t\t}\n\t\t\t\treturn a.Symbol < b.Symbol\n\t\t\t})\n\t\t}\n\t\tif diff := cmp.Diff(want, got, cmpopts.IgnoreFields(report{}, \"Vuln.CallStacks\")); diff != \"\" {\n\t\t\tt.Error(diff)\n\t\t}\n\n\t})\n}\n\ntype report struct {\n\tVuln\n\t\/\/ Trace is stringified Vuln.CallStacks\n\tCallStacksStr []string\n}\n\nfunc toReport(v Vuln) report {\n\tvar r = report{Vuln: v}\n\tfor _, s := range v.CallStacks {\n\t\tr.CallStacksStr = append(r.CallStacksStr, CallStackString(s))\n\t}\n\treturn r\n}\n\nfunc CallStackString(callstack CallStack) string {\n\tvar b bytes.Buffer\n\tfor _, entry := range callstack {\n\t\tfname := filepath.Base(entry.URI.SpanURI().Filename())\n\t\tfmt.Fprintf(&b, \"%v (%v:%d)\\n\", entry.Name, fname, entry.Pos.Line)\n\t}\n\treturn b.String()\n}\n\nconst workspace1 = `\n-- go.mod --\nmodule golang.org\/entry\n\nrequire (\n\tgolang.org\/cmod v1.1.3\n)\ngo 1.18\n-- x\/x.go --\npackage x\n\nimport \t(\n   \"golang.org\/cmod\/c\"\n   \"golang.org\/entry\/y\"\n)\n\nfunc X() {\n\tc.C1().Vuln1() \/\/ vuln use: X -> Vuln1\n}\n\nfunc CallY() {\n\ty.Y()  \/\/ vuln use: CallY -> y.Y -> bvuln.Vuln \n}\n\n-- y\/y.go --\npackage y\n\nimport \"golang.org\/cmod\/c\"\n\nfunc Y() {\n\tc.C2()() \/\/ vuln use: Y -> bvuln.Vuln\n}\n`\n\nconst proxy1 = `\n-- golang.org\/cmod@v1.1.3\/go.mod --\nmodule golang.org\/cmod\n\ngo 1.12\n-- golang.org\/cmod@v1.1.3\/c\/c.go --\npackage c\n\nimport (\n\t\"golang.org\/amod\/avuln\"\n\t\"golang.org\/bmod\/bvuln\"\n)\n\ntype I interface {\n\tVuln1()\n}\n\nfunc C1() I {\n\tv := avuln.VulnData{}\n\tv.Vuln2() \/\/ vuln use\n\treturn v\n}\n\nfunc C2() func() {\n\treturn bvuln.Vuln\n}\n-- golang.org\/amod@v1.1.3\/go.mod --\nmodule golang.org\/amod\n\ngo 1.14\n-- golang.org\/amod@v1.1.3\/avuln\/avuln.go --\npackage avuln\n\ntype VulnData struct {}\nfunc (v VulnData) Vuln1() {}\nfunc (v VulnData) Vuln2() {}\n-- golang.org\/bmod@v0.5.0\/go.mod --\nmodule golang.org\/bmod\n\ngo 1.14\n-- golang.org\/bmod@v0.5.0\/bvuln\/bvuln.go --\npackage bvuln\n\nfunc Vuln() {\n\t\/\/ something evil\n}\n`\n\nconst vulnsData = `\n-- GO-2022-01.yaml --\nmodules:\n  - module: golang.org\/amod\n    versions:\n      - introduced: 1.0.0\n      - fixed: 1.0.4\n      - introduced: 1.1.2\n    packages:\n      - package: golang.org\/amod\/avuln\n        symbols:\n          - VulnData.Vuln1\n          - VulnData.Vuln2\ndescription: |\n    Something.\nreferences:\n  - href: pkg.go.dev\/vuln\/GO-2022-01\n\n-- GO-2022-03.yaml --\nmodules:\n  - module: golang.org\/amod\n    versions:\n      - introduced: 1.0.0\n      - fixed: 1.0.4\n      - introduced: 1.1.2\n    packages:\n      - package: golang.org\/amod\/avuln\n        symbols:\n          - nonExisting\ndescription: |\n    unaffecting vulnerability.\n\n-- GO-2022-02.yaml --\nmodules:\n  - module: golang.org\/bmod\n    packages:\n      - package: golang.org\/bmod\/bvuln\n        symbols:\n          - Vuln\n`\n\nfunc runTest(t *testing.T, workspaceData, proxyData string, test func(context.Context, source.Snapshot)) {\n\tws, err := fake.NewSandbox(&fake.SandboxConfig{\n\t\tFiles:      fake.UnpackTxt(workspaceData),\n\t\tProxyFiles: fake.UnpackTxt(proxyData),\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer ws.Close()\n\n\tctx := tests.Context(t)\n\n\t\/\/ get the module cache populated and the go.sum file at the root auto-generated.\n\tdir := ws.Workdir.RootURI().SpanURI().Filename()\n\tif err := ws.RunGoCommand(ctx, dir, \"list\", []string{\"-mod=mod\", \"...\"}, true); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcache := cache.New(nil, nil, nil)\n\tsession := cache.NewSession(ctx)\n\toptions := source.DefaultOptions().Clone()\n\ttests.DefaultOptions(options)\n\tsession.SetOptions(options)\n\tenvs := []string{}\n\tfor k, v := range ws.GoEnv() {\n\t\tenvs = append(envs, k+\"=\"+v)\n\t}\n\toptions.SetEnvSlice(envs)\n\tname := ws.RootDir()\n\tfolder := ws.Workdir.RootURI().SpanURI()\n\tview, snapshot, release, err := session.NewView(ctx, name, folder, options)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tdefer func() {\n\t\t\/\/ The snapshot must be released before calling view.Shutdown, to avoid a\n\t\t\/\/ deadlock.\n\t\trelease()\n\t\tview.Shutdown(ctx)\n\t}()\n\n\ttest(ctx, snapshot)\n}\n\n\/\/ TODO: expose this as a method of Snapshot.\nfunc packagesCfg(ctx context.Context, snapshot source.Snapshot) *packages.Config {\n\tview := snapshot.View()\n\tviewBuildFlags := view.Options().BuildFlags\n\tvar viewEnv []string\n\tif e := view.Options().EnvSlice(); e != nil {\n\t\tviewEnv = append(os.Environ(), e...)\n\t}\n\treturn &packages.Config{\n\t\t\/\/ Mode will be set by cmd.Run.\n\t\tContext:    ctx,\n\t\tTests:      true,\n\t\tBuildFlags: viewBuildFlags,\n\t\tEnv:        viewEnv,\n\t\tDir:        view.Folder().Filename(),\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package sqlstore\n\nimport (\n\t\"testing\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n\n\tm \"github.com\/grafana\/grafana\/pkg\/models\"\n)\n\n\/*\ntype UpdatePlaylistCommand struct {\n\tOrgId    int64             `json:\"-\"`\n\tId       int64             `json:\"id\" binding:\"Required\"`\n\tName     string            `json:\"name\" binding:\"Required\"`\n\tType     string            `json:\"type\"`\n\tInterval string            `json:\"interval\"`\n\tItems    []PlaylistItemDTO `json:\"items\"`\n\n\tResult *PlaylistDTO\n}\n\ntype CreatePlaylistCommand struct {\n\tName     string            `json:\"name\" binding:\"Required\"`\n\tInterval string            `json:\"interval\"`\n\tData     []int64           `json:\"data\"`\n\tItems    []PlaylistItemDTO `json:\"items\"`\n\n\tOrgId  int64 `json:\"-\"`\n\tResult *Playlist\n}\n\ntype DeletePlaylistCommand struct {\n\tId    int64\n\tOrgId int64\n}\n\n*\/\n\nfunc TestPlaylistDataAccess(t *testing.T) {\n\n\tConvey(\"Testing Playlist data access\", t, func() {\n\t\tInitTestDB(t)\n\n\t\tConvey(\"Can create playlist\", func() {\n\t\t\titems := []m.PlaylistItemDTO{\n\t\t\t\tm.PlaylistItemDTO{Title: \"graphite\", Value: \"graphite\", Type: \"dashboard_by_tag\"},\n\t\t\t\tm.PlaylistItemDTO{Title: \"Backend response times\", Value: \"3\", Type: \"dashboard_by_id\"},\n\t\t\t}\n\t\t\tcmd := m.CreatePlaylistCommand{Name: \"NYC office\", Interval: \"10m\", OrgId: 1, Items: items}\n\t\t\terr := CreatePlaylist(&cmd)\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tConvey(\"can update playlist\", func() {\n\t\t\t\titems := []m.PlaylistItemDTO{\n\t\t\t\t\tm.PlaylistItemDTO{Title: \"influxdb\", Value: \"influxdb\", Type: \"dashboard_by_tag\"},\n\t\t\t\t\tm.PlaylistItemDTO{Title: \"Backend response times\", Value: \"2\", Type: \"dashboard_by_id\"},\n\t\t\t\t}\n\t\t\t\tquery := m.UpdatePlaylistCommand{Name: \"NYC office \", OrgId: 1, Id: 1, Interval: \"10s\", Items: items}\n\t\t\t\terr = UpdatePlaylist(&query)\n\n\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\tConvey(\"can remove playlist\", func() {\n\t\t\t\t\tquery := m.DeletePlaylistCommand{Id: 1}\n\t\t\t\t\terr = DeletePlaylist(&query)\n\n\t\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n}\n<commit_msg>chore(playlist): remove commented code<commit_after>package sqlstore\n\nimport (\n\t\"testing\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n\n\tm \"github.com\/grafana\/grafana\/pkg\/models\"\n)\n\nfunc TestPlaylistDataAccess(t *testing.T) {\n\n\tConvey(\"Testing Playlist data access\", t, func() {\n\t\tInitTestDB(t)\n\n\t\tConvey(\"Can create playlist\", func() {\n\t\t\titems := []m.PlaylistItemDTO{\n\t\t\t\t{Title: \"graphite\", Value: \"graphite\", Type: \"dashboard_by_tag\"},\n\t\t\t\t{Title: \"Backend response times\", Value: \"3\", Type: \"dashboard_by_id\"},\n\t\t\t}\n\t\t\tcmd := m.CreatePlaylistCommand{Name: \"NYC office\", Interval: \"10m\", OrgId: 1, Items: items}\n\t\t\terr := CreatePlaylist(&cmd)\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tConvey(\"can update playlist\", func() {\n\t\t\t\titems := []m.PlaylistItemDTO{\n\t\t\t\t\t{Title: \"influxdb\", Value: \"influxdb\", Type: \"dashboard_by_tag\"},\n\t\t\t\t\t{Title: \"Backend response times\", Value: \"2\", Type: \"dashboard_by_id\"},\n\t\t\t\t}\n\t\t\t\tquery := m.UpdatePlaylistCommand{Name: \"NYC office \", OrgId: 1, Id: 1, Interval: \"10s\", Items: items}\n\t\t\t\terr = UpdatePlaylist(&query)\n\n\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\tConvey(\"can remove playlist\", func() {\n\t\t\t\t\tquery := m.DeletePlaylistCommand{Id: 1}\n\t\t\t\t\terr = DeletePlaylist(&query)\n\n\t\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package couchdb\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/cozy\/checkup\"\n\t\"github.com\/cozy\/cozy-stack\/pkg\/config\"\n\t\"github.com\/cozy\/cozy-stack\/pkg\/couchdb\/mango\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestErrors(t *testing.T) {\n\terr := Error{StatusCode: 404, Name: \"not_found\", Reason: \"missing\"}\n\tassert.Contains(t, err.Error(), \"404\")\n\tassert.Contains(t, err.Error(), \"missing\")\n}\n\nconst TestDoctype = \"io.cozy.testobject\"\n\nvar TestPrefix = SimpleDatabasePrefix(\"couchdb-tests\")\n\ntype testDoc struct {\n\tTestID  string `json:\"_id,omitempty\"`\n\tTestRev string `json:\"_rev,omitempty\"`\n\tTest    string `json:\"test\"`\n\tFieldA  string `json:\"fieldA,omitempty\"`\n\tFieldB  int    `json:\"fieldB,omitempty\"`\n}\n\nfunc (t *testDoc) ID() string {\n\treturn t.TestID\n}\n\nfunc (t *testDoc) Rev() string {\n\treturn t.TestRev\n}\n\nfunc (t *testDoc) DocType() string {\n\treturn TestDoctype\n}\n\nfunc (t *testDoc) SetID(id string) {\n\tt.TestID = id\n}\n\nfunc (t *testDoc) SetRev(rev string) {\n\tt.TestRev = rev\n}\n\nfunc makeTestDoc() Doc {\n\treturn &testDoc{\n\t\tTest: \"somevalue\",\n\t}\n}\n\nfunc TestCreateDoc(t *testing.T) {\n\tvar err error\n\n\tvar doc = makeTestDoc()\n\tassert.Empty(t, doc.Rev(), doc.ID())\n\n\t\/\/ Create the document\n\terr = CreateDoc(TestPrefix, doc)\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, doc.Rev(), doc.ID())\n\n\tdocType, id := doc.DocType(), doc.ID()\n\n\t\/\/ Fetch it and see if its match\n\tfetched := &testDoc{}\n\terr = GetDoc(TestPrefix, docType, id, fetched)\n\tassert.NoError(t, err)\n\tassert.Equal(t, doc.ID(), fetched.ID())\n\tassert.Equal(t, doc.Rev(), fetched.Rev())\n\tassert.Equal(t, \"somevalue\", fetched.Test)\n\n\trevBackup := fetched.Rev()\n\n\t\/\/ Update it\n\tupdated := fetched\n\tupdated.Test = \"changedvalue\"\n\terr = UpdateDoc(TestPrefix, updated)\n\tassert.NoError(t, err)\n\tassert.NotEqual(t, revBackup, updated.Rev())\n\tassert.Equal(t, \"changedvalue\", updated.Test)\n\n\t\/\/ Refetch it and see if its match\n\tfetched2 := &testDoc{}\n\terr = GetDoc(TestPrefix, docType, id, fetched2)\n\tassert.NoError(t, err)\n\tassert.Equal(t, doc.ID(), fetched2.ID())\n\tassert.Equal(t, updated.Rev(), fetched2.Rev())\n\tassert.Equal(t, \"changedvalue\", fetched2.Test)\n\n\t\/\/ Delete it\n\terr = DeleteDoc(TestPrefix, updated)\n\tassert.NoError(t, err)\n\n\tfetched3 := &testDoc{}\n\terr = GetDoc(TestPrefix, docType, id, fetched3)\n\tassert.Error(t, err)\n\tcoucherr, iscoucherr := err.(*Error)\n\tif assert.True(t, iscoucherr) {\n\t\tassert.Equal(t, coucherr.Reason, \"deleted\")\n\t}\n\n}\n\nfunc TestGetAllDocs(t *testing.T) {\n\tdoc1 := &testDoc{Test: \"all_1\"}\n\tdoc2 := &testDoc{Test: \"all_2\"}\n\tCreateDoc(TestPrefix, doc1)\n\tCreateDoc(TestPrefix, doc2)\n\n\tvar results []*testDoc\n\terr := GetAllDocs(TestPrefix, TestDoctype, &AllDocsRequest{Limit: 2}, &results)\n\tif assert.NoError(t, err) {\n\t\tassert.Len(t, results, 2)\n\t\tassert.Equal(t, results[0].Test, \"all_1\")\n\t\tassert.Equal(t, results[1].Test, \"all_2\")\n\t}\n}\n\nfunc TestDefineIndex(t *testing.T) {\n\terr := DefineIndex(TestPrefix, TestDoctype, mango.IndexOnFields(\"fieldA\", \"fieldB\"))\n\tassert.NoError(t, err)\n\n\t\/\/ if I try to define the same index several time\n\terr2 := DefineIndex(TestPrefix, TestDoctype, mango.IndexOnFields(\"fieldA\", \"fieldB\"))\n\tassert.NoError(t, err2)\n}\n\nfunc TestQuery(t *testing.T) {\n\n\t\/\/ create a few docs for testing\n\tdoc1 := testDoc{FieldA: \"value1\", FieldB: 100}\n\tdoc2 := testDoc{FieldA: \"value2\", FieldB: 1000}\n\tdoc3 := testDoc{FieldA: \"value2\", FieldB: 300}\n\tdoc4 := testDoc{FieldA: \"value13\", FieldB: 1500}\n\tdocs := []*testDoc{&doc1, &doc2, &doc3, &doc4}\n\tfor _, doc := range docs {\n\t\terr := CreateDoc(TestPrefix, doc)\n\t\tif !assert.NoError(t, err) || doc.ID() == \"\" {\n\t\t\tt.FailNow()\n\t\t\treturn\n\t\t}\n\t}\n\n\terr := DefineIndex(TestPrefix, TestDoctype, mango.IndexOnFields(\"fieldA\", \"fieldB\"))\n\tif !assert.NoError(t, err) {\n\t\tt.FailNow()\n\t\treturn\n\t}\n\tvar out []testDoc\n\treq := &FindRequest{Selector: mango.Equal(\"fieldA\", \"value2\")}\n\terr = FindDocs(TestPrefix, TestDoctype, req, &out)\n\tif assert.NoError(t, err) {\n\t\tassert.Len(t, out, 2, \"should get 2 results\")\n\t\t\/\/ if fieldA are equaly, docs will be ordered by fieldB\n\t\tassert.Equal(t, doc3.ID(), out[0].ID())\n\t\tassert.Equal(t, \"value2\", out[0].FieldA)\n\t\tassert.Equal(t, doc2.ID(), out[1].ID())\n\t\tassert.Equal(t, \"value2\", out[1].FieldA)\n\t}\n\n\tvar out2 []testDoc\n\treq2 := &FindRequest{Selector: mango.StartWith(\"fieldA\", \"value1\")}\n\terr = FindDocs(TestPrefix, TestDoctype, req2, &out2)\n\tif assert.NoError(t, err) {\n\t\tassert.Len(t, out, 2, \"should get 2 results\")\n\t\t\/\/ if we do as startWith, docs will be ordered by the rest of fieldA\n\t\tassert.Equal(t, doc1.ID(), out2[0].ID())\n\t\tassert.Equal(t, doc4.ID(), out2[1].ID())\n\t}\n\n}\n\nfunc TestChangesSuccess(t *testing.T) {\n\terr := ResetDB(TestPrefix, TestDoctype)\n\tassert.NoError(t, err)\n\n\tvar request = &ChangesRequest{\n\t\tDocType: TestDoctype,\n\t}\n\tresponse, err := GetChanges(TestPrefix, request)\n\tvar seqnoAfterCreates = response.LastSeq\n\tassert.NoError(t, err)\n\tassert.Len(t, response.Results, 0)\n\n\tdoc1 := makeTestDoc()\n\tdoc2 := makeTestDoc()\n\tdoc3 := makeTestDoc()\n\tCreateDoc(TestPrefix, doc1)\n\tCreateDoc(TestPrefix, doc2)\n\tCreateDoc(TestPrefix, doc3)\n\n\trequest = &ChangesRequest{\n\t\tDocType: TestDoctype,\n\t\tSince:   seqnoAfterCreates,\n\t}\n\n\tresponse, err = GetChanges(TestPrefix, request)\n\tassert.NoError(t, err)\n\tassert.Len(t, response.Results, 3)\n\n\trequest = &ChangesRequest{\n\t\tDocType: TestDoctype,\n\t\tSince:   seqnoAfterCreates,\n\t\tLimit:   2,\n\t}\n\n\tresponse, err = GetChanges(TestPrefix, request)\n\tassert.NoError(t, err)\n\tassert.Len(t, response.Results, 2)\n\n\tseqnoAfterCreates = response.LastSeq\n\n\tdoc4 := makeTestDoc()\n\tCreateDoc(TestPrefix, doc4)\n\n\trequest = &ChangesRequest{\n\t\tDocType: TestDoctype,\n\t\tSince:   seqnoAfterCreates,\n\t}\n\tresponse, err = GetChanges(TestPrefix, request)\n\tassert.NoError(t, err)\n\tassert.Len(t, response.Results, 2)\n}\n\nfunc TestMain(m *testing.M) {\n\tconfig.UseTestFile()\n\n\t\/\/ First we make sure couchdb is started\n\tdb, err := checkup.HTTPChecker{URL: config.CouchURL()}.Check()\n\tif err != nil || db.Status() != checkup.Healthy {\n\t\tfmt.Println(\"This test need couchdb to run.\")\n\t\tos.Exit(1)\n\t}\n\n\terr = ResetDB(TestPrefix, TestDoctype)\n\tif err != nil {\n\t\tfmt.Printf(\"Cant reset db (%s, %s) %s\\n\", TestPrefix, TestDoctype, err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tres := m.Run()\n\n\tDeleteDB(TestPrefix, TestDoctype)\n\n\tos.Exit(res)\n}\n<commit_msg>Fix tests<commit_after>package couchdb\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/cozy\/checkup\"\n\t\"github.com\/cozy\/cozy-stack\/pkg\/config\"\n\t\"github.com\/cozy\/cozy-stack\/pkg\/couchdb\/mango\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestErrors(t *testing.T) {\n\terr := Error{StatusCode: 404, Name: \"not_found\", Reason: \"missing\"}\n\tassert.Contains(t, err.Error(), \"not_found\")\n\tassert.Contains(t, err.Error(), \"missing\")\n}\n\nconst TestDoctype = \"io.cozy.testobject\"\n\nvar TestPrefix = SimpleDatabasePrefix(\"couchdb-tests\")\n\ntype testDoc struct {\n\tTestID  string `json:\"_id,omitempty\"`\n\tTestRev string `json:\"_rev,omitempty\"`\n\tTest    string `json:\"test\"`\n\tFieldA  string `json:\"fieldA,omitempty\"`\n\tFieldB  int    `json:\"fieldB,omitempty\"`\n}\n\nfunc (t *testDoc) ID() string {\n\treturn t.TestID\n}\n\nfunc (t *testDoc) Rev() string {\n\treturn t.TestRev\n}\n\nfunc (t *testDoc) DocType() string {\n\treturn TestDoctype\n}\n\nfunc (t *testDoc) SetID(id string) {\n\tt.TestID = id\n}\n\nfunc (t *testDoc) SetRev(rev string) {\n\tt.TestRev = rev\n}\n\nfunc makeTestDoc() Doc {\n\treturn &testDoc{\n\t\tTest: \"somevalue\",\n\t}\n}\n\nfunc TestCreateDoc(t *testing.T) {\n\tvar err error\n\n\tvar doc = makeTestDoc()\n\tassert.Empty(t, doc.Rev(), doc.ID())\n\n\t\/\/ Create the document\n\terr = CreateDoc(TestPrefix, doc)\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, doc.Rev(), doc.ID())\n\n\tdocType, id := doc.DocType(), doc.ID()\n\n\t\/\/ Fetch it and see if its match\n\tfetched := &testDoc{}\n\terr = GetDoc(TestPrefix, docType, id, fetched)\n\tassert.NoError(t, err)\n\tassert.Equal(t, doc.ID(), fetched.ID())\n\tassert.Equal(t, doc.Rev(), fetched.Rev())\n\tassert.Equal(t, \"somevalue\", fetched.Test)\n\n\trevBackup := fetched.Rev()\n\n\t\/\/ Update it\n\tupdated := fetched\n\tupdated.Test = \"changedvalue\"\n\terr = UpdateDoc(TestPrefix, updated)\n\tassert.NoError(t, err)\n\tassert.NotEqual(t, revBackup, updated.Rev())\n\tassert.Equal(t, \"changedvalue\", updated.Test)\n\n\t\/\/ Refetch it and see if its match\n\tfetched2 := &testDoc{}\n\terr = GetDoc(TestPrefix, docType, id, fetched2)\n\tassert.NoError(t, err)\n\tassert.Equal(t, doc.ID(), fetched2.ID())\n\tassert.Equal(t, updated.Rev(), fetched2.Rev())\n\tassert.Equal(t, \"changedvalue\", fetched2.Test)\n\n\t\/\/ Delete it\n\terr = DeleteDoc(TestPrefix, updated)\n\tassert.NoError(t, err)\n\n\tfetched3 := &testDoc{}\n\terr = GetDoc(TestPrefix, docType, id, fetched3)\n\tassert.Error(t, err)\n\tcoucherr, iscoucherr := err.(*Error)\n\tif assert.True(t, iscoucherr) {\n\t\tassert.Equal(t, coucherr.Reason, \"deleted\")\n\t}\n\n}\n\nfunc TestGetAllDocs(t *testing.T) {\n\tdoc1 := &testDoc{Test: \"all_1\"}\n\tdoc2 := &testDoc{Test: \"all_2\"}\n\tCreateDoc(TestPrefix, doc1)\n\tCreateDoc(TestPrefix, doc2)\n\n\tvar results []*testDoc\n\terr := GetAllDocs(TestPrefix, TestDoctype, &AllDocsRequest{Limit: 2}, &results)\n\tif assert.NoError(t, err) {\n\t\tassert.Len(t, results, 2)\n\t\tassert.Equal(t, results[0].Test, \"all_1\")\n\t\tassert.Equal(t, results[1].Test, \"all_2\")\n\t}\n}\n\nfunc TestDefineIndex(t *testing.T) {\n\terr := DefineIndex(TestPrefix, TestDoctype, mango.IndexOnFields(\"fieldA\", \"fieldB\"))\n\tassert.NoError(t, err)\n\n\t\/\/ if I try to define the same index several time\n\terr2 := DefineIndex(TestPrefix, TestDoctype, mango.IndexOnFields(\"fieldA\", \"fieldB\"))\n\tassert.NoError(t, err2)\n}\n\nfunc TestQuery(t *testing.T) {\n\n\t\/\/ create a few docs for testing\n\tdoc1 := testDoc{FieldA: \"value1\", FieldB: 100}\n\tdoc2 := testDoc{FieldA: \"value2\", FieldB: 1000}\n\tdoc3 := testDoc{FieldA: \"value2\", FieldB: 300}\n\tdoc4 := testDoc{FieldA: \"value13\", FieldB: 1500}\n\tdocs := []*testDoc{&doc1, &doc2, &doc3, &doc4}\n\tfor _, doc := range docs {\n\t\terr := CreateDoc(TestPrefix, doc)\n\t\tif !assert.NoError(t, err) || doc.ID() == \"\" {\n\t\t\tt.FailNow()\n\t\t\treturn\n\t\t}\n\t}\n\n\terr := DefineIndex(TestPrefix, TestDoctype, mango.IndexOnFields(\"fieldA\", \"fieldB\"))\n\tif !assert.NoError(t, err) {\n\t\tt.FailNow()\n\t\treturn\n\t}\n\tvar out []testDoc\n\treq := &FindRequest{Selector: mango.Equal(\"fieldA\", \"value2\")}\n\terr = FindDocs(TestPrefix, TestDoctype, req, &out)\n\tif assert.NoError(t, err) {\n\t\tassert.Len(t, out, 2, \"should get 2 results\")\n\t\t\/\/ if fieldA are equaly, docs will be ordered by fieldB\n\t\tassert.Equal(t, doc3.ID(), out[0].ID())\n\t\tassert.Equal(t, \"value2\", out[0].FieldA)\n\t\tassert.Equal(t, doc2.ID(), out[1].ID())\n\t\tassert.Equal(t, \"value2\", out[1].FieldA)\n\t}\n\n\tvar out2 []testDoc\n\treq2 := &FindRequest{Selector: mango.StartWith(\"fieldA\", \"value1\")}\n\terr = FindDocs(TestPrefix, TestDoctype, req2, &out2)\n\tif assert.NoError(t, err) {\n\t\tassert.Len(t, out, 2, \"should get 2 results\")\n\t\t\/\/ if we do as startWith, docs will be ordered by the rest of fieldA\n\t\tassert.Equal(t, doc1.ID(), out2[0].ID())\n\t\tassert.Equal(t, doc4.ID(), out2[1].ID())\n\t}\n\n}\n\nfunc TestChangesSuccess(t *testing.T) {\n\terr := ResetDB(TestPrefix, TestDoctype)\n\tassert.NoError(t, err)\n\n\tvar request = &ChangesRequest{\n\t\tDocType: TestDoctype,\n\t}\n\tresponse, err := GetChanges(TestPrefix, request)\n\tvar seqnoAfterCreates = response.LastSeq\n\tassert.NoError(t, err)\n\tassert.Len(t, response.Results, 0)\n\n\tdoc1 := makeTestDoc()\n\tdoc2 := makeTestDoc()\n\tdoc3 := makeTestDoc()\n\tCreateDoc(TestPrefix, doc1)\n\tCreateDoc(TestPrefix, doc2)\n\tCreateDoc(TestPrefix, doc3)\n\n\trequest = &ChangesRequest{\n\t\tDocType: TestDoctype,\n\t\tSince:   seqnoAfterCreates,\n\t}\n\n\tresponse, err = GetChanges(TestPrefix, request)\n\tassert.NoError(t, err)\n\tassert.Len(t, response.Results, 3)\n\n\trequest = &ChangesRequest{\n\t\tDocType: TestDoctype,\n\t\tSince:   seqnoAfterCreates,\n\t\tLimit:   2,\n\t}\n\n\tresponse, err = GetChanges(TestPrefix, request)\n\tassert.NoError(t, err)\n\tassert.Len(t, response.Results, 2)\n\n\tseqnoAfterCreates = response.LastSeq\n\n\tdoc4 := makeTestDoc()\n\tCreateDoc(TestPrefix, doc4)\n\n\trequest = &ChangesRequest{\n\t\tDocType: TestDoctype,\n\t\tSince:   seqnoAfterCreates,\n\t}\n\tresponse, err = GetChanges(TestPrefix, request)\n\tassert.NoError(t, err)\n\tassert.Len(t, response.Results, 2)\n}\n\nfunc TestMain(m *testing.M) {\n\tconfig.UseTestFile()\n\n\t\/\/ First we make sure couchdb is started\n\tdb, err := checkup.HTTPChecker{URL: config.CouchURL()}.Check()\n\tif err != nil || db.Status() != checkup.Healthy {\n\t\tfmt.Println(\"This test need couchdb to run.\")\n\t\tos.Exit(1)\n\t}\n\n\terr = ResetDB(TestPrefix, TestDoctype)\n\tif err != nil {\n\t\tfmt.Printf(\"Cant reset db (%s, %s) %s\\n\", TestPrefix, TestDoctype, err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tres := m.Run()\n\n\tDeleteDB(TestPrefix, TestDoctype)\n\n\tos.Exit(res)\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"github.com\/couchbaselabs\/sgload\/sgload\"\n\t\"github.com\/inconshreveable\/log15\"\n)\n\nconst (\n\tNUM_READERS_CMD_NAME    = \"numreaders\"\n\tNUM_READERS_CMD_DEFAULT = 100\n\tNUM_READERS_CMD_DESC    = \"The number of unique readers that will read documents.  Each reader runs concurrently in it's own goroutine\"\n\n\tNUM_WRITERS_CMD_NAME    = \"numwriters\"\n\tNUM_WRITERS_CMD_DEFAULT = 100\n\tNUM_WRITERS_CMD_DESC    = \"The number of unique users that will write documents.  Each writer runs concurrently in it's own goroutine\"\n\n\tCREATE_WRITERS_CMD_NAME    = \"createwriters\"\n\tCREATE_WRITERS_CMD_DEFAULT = false\n\tCREATE_WRITERS_CMD_DESC    = \"Add this flag if you need the test to create SG users for writers.\"\n\n\tNUM_CHANS_PER_READER_CMD_NAME    = \"num-chans-per-reader\"\n\tNUM_CHANS_PER_READER_CMD_DEFAULT = 1\n\tNUM_CHANS_PER_READER_CMD_DESC    = \"The number of channels that each reader has access to.\"\n\n\tCREATE_READERS_CMD_NAME    = \"createreaders\"\n\tCREATE_READERS_CMD_DEFAULT = false\n\tCREATE_READERS_CMD_DESC    = \"Add this flag if you need the test to create SG users for readers.\"\n\n\tSKIP_WRITELOAD_CMD_NAME    = \"skipwriteload\"\n\tSKIP_WRITELOAD_CMD_DEFAULT = false\n\tSKIP_WRITELOAD_CMD_DESC    = \"By default will first run the corresponding writeload, so that it has documents to read, but set this flag if you've run that step separately\"\n\n\tNUM_UPDATERS_CMD_NAME    = \"numupdaters\"\n\tNUM_UPDATERS_CMD_DEFAULT = 100\n\tNUM_UPDATERS_CMD_DESC    = \"The number of unique users that will update documents.  Each updater runs concurrently in it's own goroutine\"\n\n\tNUM_REVS_PER_DOC_CMD_NAME    = \"numrevsperdoc\"\n\tNUM_REVS_PER_DOC_CMD_DEFAULT = 100\n\tNUM_REVS_PER_DOC_CMD_DESC    = \"The number of updates per doc (total revs will be numrevsperdoc * numrevsperupdate)\"\n\n\tNUM_REVS_PER_UPDATE_CMD_NAME    = \"numrevsperupdate\"\n\tNUM_REVS_PER_UPDATE_CMD_DEFAULT = 1\n\tNUM_REVS_PER_UPDATE_CMD_DESC    = \"The number of revisions per doc to add in each update\"\n)\n\nfunc createLoadSpecFromArgs() sgload.LoadSpec {\n\n\tloadSpec := sgload.LoadSpec{\n\t\tSyncGatewayUrl:        *sgUrl,\n\t\tSyncGatewayAdminPort:  *sgAdminPort,\n\t\tMockDataStore:         *mockDataStore,\n\t\tStatsdEnabled:         *statsdEnabled,\n\t\tStatsdEndpoint:        *statsdEndpoint,\n\t\tTestSessionID:         *testSessionID,\n\t\tBatchSize:             *batchSize,\n\t\tNumChannels:           *numChannels,\n\t\tDocSizeBytes:          *docSizeBytes,\n\t\tNumDocs:               *numDocs,\n\t\tCompressionEnabled:    *compressionEnabled,\n\t\tExpvarProgressEnabled: *expvarProgressEnabled,\n\t}\n\n\tswitch *logLevelStr {\n\tcase \"critical\":\n\t\tloadSpec.LogLevel = log15.LvlCrit\n\tcase \"error\":\n\t\tloadSpec.LogLevel = log15.LvlError\n\tcase \"warn\":\n\t\tloadSpec.LogLevel = log15.LvlWarn\n\tcase \"info\":\n\t\tloadSpec.LogLevel = log15.LvlInfo\n\tcase \"debug\":\n\t\tloadSpec.LogLevel = log15.LvlDebug\n\t}\n\n\tloadSpec.TestSessionID = sgload.NewUuid()\n\treturn loadSpec\n}\n<commit_msg>Change default numrevsperdoc from 100 -> 5<commit_after>package cmd\n\nimport (\n\t\"github.com\/couchbaselabs\/sgload\/sgload\"\n\t\"github.com\/inconshreveable\/log15\"\n)\n\nconst (\n\tNUM_READERS_CMD_NAME    = \"numreaders\"\n\tNUM_READERS_CMD_DEFAULT = 100\n\tNUM_READERS_CMD_DESC    = \"The number of unique readers that will read documents.  Each reader runs concurrently in it's own goroutine\"\n\n\tNUM_WRITERS_CMD_NAME    = \"numwriters\"\n\tNUM_WRITERS_CMD_DEFAULT = 100\n\tNUM_WRITERS_CMD_DESC    = \"The number of unique users that will write documents.  Each writer runs concurrently in it's own goroutine\"\n\n\tCREATE_WRITERS_CMD_NAME    = \"createwriters\"\n\tCREATE_WRITERS_CMD_DEFAULT = false\n\tCREATE_WRITERS_CMD_DESC    = \"Add this flag if you need the test to create SG users for writers.\"\n\n\tNUM_CHANS_PER_READER_CMD_NAME    = \"num-chans-per-reader\"\n\tNUM_CHANS_PER_READER_CMD_DEFAULT = 1\n\tNUM_CHANS_PER_READER_CMD_DESC    = \"The number of channels that each reader has access to.\"\n\n\tCREATE_READERS_CMD_NAME    = \"createreaders\"\n\tCREATE_READERS_CMD_DEFAULT = false\n\tCREATE_READERS_CMD_DESC    = \"Add this flag if you need the test to create SG users for readers.\"\n\n\tSKIP_WRITELOAD_CMD_NAME    = \"skipwriteload\"\n\tSKIP_WRITELOAD_CMD_DEFAULT = false\n\tSKIP_WRITELOAD_CMD_DESC    = \"By default will first run the corresponding writeload, so that it has documents to read, but set this flag if you've run that step separately\"\n\n\tNUM_UPDATERS_CMD_NAME    = \"numupdaters\"\n\tNUM_UPDATERS_CMD_DEFAULT = 100\n\tNUM_UPDATERS_CMD_DESC    = \"The number of unique users that will update documents.  Each updater runs concurrently in it's own goroutine\"\n\n\tNUM_REVS_PER_DOC_CMD_NAME    = \"numrevsperdoc\"\n\tNUM_REVS_PER_DOC_CMD_DEFAULT = 5\n\tNUM_REVS_PER_DOC_CMD_DESC    = \"The number of updates per doc (total revs will be numrevsperdoc * numrevsperupdate)\"\n\n\tNUM_REVS_PER_UPDATE_CMD_NAME    = \"numrevsperupdate\"\n\tNUM_REVS_PER_UPDATE_CMD_DEFAULT = 1\n\tNUM_REVS_PER_UPDATE_CMD_DESC    = \"The number of revisions per doc to add in each update\"\n)\n\nfunc createLoadSpecFromArgs() sgload.LoadSpec {\n\n\tloadSpec := sgload.LoadSpec{\n\t\tSyncGatewayUrl:        *sgUrl,\n\t\tSyncGatewayAdminPort:  *sgAdminPort,\n\t\tMockDataStore:         *mockDataStore,\n\t\tStatsdEnabled:         *statsdEnabled,\n\t\tStatsdEndpoint:        *statsdEndpoint,\n\t\tTestSessionID:         *testSessionID,\n\t\tBatchSize:             *batchSize,\n\t\tNumChannels:           *numChannels,\n\t\tDocSizeBytes:          *docSizeBytes,\n\t\tNumDocs:               *numDocs,\n\t\tCompressionEnabled:    *compressionEnabled,\n\t\tExpvarProgressEnabled: *expvarProgressEnabled,\n\t}\n\n\tswitch *logLevelStr {\n\tcase \"critical\":\n\t\tloadSpec.LogLevel = log15.LvlCrit\n\tcase \"error\":\n\t\tloadSpec.LogLevel = log15.LvlError\n\tcase \"warn\":\n\t\tloadSpec.LogLevel = log15.LvlWarn\n\tcase \"info\":\n\t\tloadSpec.LogLevel = log15.LvlInfo\n\tcase \"debug\":\n\t\tloadSpec.LogLevel = log15.LvlDebug\n\t}\n\n\tloadSpec.TestSessionID = sgload.NewUuid()\n\treturn loadSpec\n}\n<|endoftext|>"}
{"text":"<commit_before>package uncertainty\n\nimport (\n\t\"errors\"\n\t\"math\"\n\n\t\"github.com\/ready-steady\/linear\/matrix\"\n\t\"github.com\/ready-steady\/probability\/distribution\"\n\t\"github.com\/turing-complete\/laboratory\/src\/internal\/config\"\n\t\"github.com\/turing-complete\/laboratory\/src\/internal\/support\"\n\t\"github.com\/turing-complete\/laboratory\/src\/internal\/system\"\n\n\tscorrelation \"github.com\/ready-steady\/statistics\/correlation\"\n\ticorrelation \"github.com\/turing-complete\/laboratory\/src\/internal\/correlation\"\n\tidistribution \"github.com\/turing-complete\/laboratory\/src\/internal\/distribution\"\n)\n\nvar (\n\tepsilon          = math.Nextafter(1.0, 2.0) - 1.0\n\tstandardGaussian = distribution.NewGaussian(0.0, 1.0)\n)\n\ntype base struct {\n\ttasks []uint\n\tlower []float64\n\tupper []float64\n\n\tnt uint\n\tnu uint\n\tnz uint\n\n\tcorrelation *correlation\n\tmarginals   []distribution.Continuous\n}\n\ntype correlation struct {\n\tR []float64\n\tC []float64 \/\/ x = C * z\n\tD []float64 \/\/ z = D * x\n\tP []float64 \/\/ R^(-1) - I\n\n\tdetR float64\n}\n\nfunc newBase(system *system.System, reference []float64,\n\tconfig *config.Uncertainty) (*base, error) {\n\n\tnt := uint(len(reference))\n\n\ttasks, err := support.ParseNaturalIndex(config.Tasks, 0, nt-1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnu := uint(len(tasks))\n\n\tlower := make([]float64, nt)\n\tupper := make([]float64, nt)\n\n\tcopy(lower, reference)\n\tcopy(upper, reference)\n\n\tfor _, tid := range tasks {\n\t\tlower[tid] -= config.Deviation * reference[tid]\n\t\tupper[tid] += config.Deviation * reference[tid]\n\t}\n\n\tif nu == 0 {\n\t\treturn &base{\n\t\t\ttasks: tasks,\n\t\t\tlower: lower,\n\t\t\tupper: upper,\n\n\t\t\tnt: nt,\n\t\t}, nil\n\t}\n\n\tcorrelation, err := correlate(system, config, tasks)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnz := uint(len(correlation.C)) \/ nu\n\n\tmarginalizer, err := idistribution.Parse(config.Distribution)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmarginals := make([]distribution.Continuous, nu)\n\tfor i, tid := range tasks {\n\t\tmarginals[i] = marginalizer(lower[tid], upper[tid])\n\t}\n\n\treturn &base{\n\t\ttasks: tasks,\n\t\tlower: lower,\n\t\tupper: upper,\n\n\t\tnt: nt,\n\t\tnu: nu,\n\t\tnz: nz,\n\n\t\tcorrelation: correlation,\n\t\tmarginals:   marginals,\n\t}, nil\n}\n\nfunc (self *base) Mapping() (uint, uint) {\n\treturn self.nz, self.nt\n}\n\nfunc (self *base) Evaluate(ω []float64) float64 {\n\tnu, nz := self.nu, self.nz\n\n\tif nu != nz {\n\t\tpanic(\"model-order reduction is not supported\")\n\t}\n\n\tu := make([]float64, nu)\n\n\t\/\/ Dependent desired to dependent uniform\n\tfor i, tid := range self.tasks {\n\t\tu[i] = self.marginals[i].Cumulate(ω[tid])\n\t}\n\n\t\/\/ Dependent uniform to dependent Gaussian\n\tfor i := range u {\n\t\tu[i] = standardGaussian.Invert(u[i])\n\t}\n\n\texponent := -0.5 * quadratic(self.correlation.P, u, nu)\n\n\tamplitude := 1.0\n\tfor i, tid := range self.tasks {\n\t\tamplitude *= self.marginals[i].Weigh(ω[tid])\n\t}\n\n\tnormalization := math.Sqrt(self.correlation.detR)\n\n\treturn amplitude * math.Exp(exponent) \/ normalization\n}\n\nfunc (self *base) Forward(ω []float64) []float64 {\n\tnu, nz := self.nu, self.nz\n\n\tz := make([]float64, nz)\n\tu := make([]float64, nu)\n\n\t\/\/ Dependent desired to dependent uniform\n\tfor i, tid := range self.tasks {\n\t\tu[i] = self.marginals[i].Cumulate(ω[tid])\n\t}\n\n\t\/\/ Dependent uniform to dependent Gaussian\n\tfor i := range u {\n\t\tu[i] = standardGaussian.Invert(u[i])\n\t}\n\n\t\/\/ Dependent Gaussian to independent Gaussian\n\tn := multiply(self.correlation.D, u, nz, nu)\n\n\t\/\/ Independent Gaussian to independent uniform\n\tfor i := range n {\n\t\tz[i] = standardGaussian.Cumulate(n[i])\n\t}\n\n\treturn z\n}\n\nfunc (self *base) Backward(z []float64) []float64 {\n\tnu, nz := self.nu, self.nz\n\n\tω := append([]float64(nil), self.lower...)\n\tn := make([]float64, nz)\n\n\t\/\/ Independent uniform to independent Gaussian\n\tfor i := range n {\n\t\tn[i] = standardGaussian.Invert(z[i])\n\t}\n\n\t\/\/ Independent Gaussian to dependent Gaussian\n\tu := multiply(self.correlation.C, n, nu, nz)\n\n\t\/\/ Dependent Gaussian to dependent uniform\n\tfor i := range u {\n\t\tu[i] = standardGaussian.Cumulate(u[i])\n\t}\n\n\t\/\/ Dependent uniform to dependent desired\n\tfor i, tid := range self.tasks {\n\t\tω[tid] = self.marginals[i].Invert(u[i])\n\t}\n\n\treturn ω\n}\n\nfunc correlate(system *system.System, config *config.Uncertainty,\n\ttasks []uint) (*correlation, error) {\n\n\tε := math.Sqrt(epsilon)\n\n\tnu := uint(len(tasks))\n\n\tif config.Correlation == 0.0 {\n\t\treturn &correlation{\n\t\t\tR: matrix.Identity(nu),\n\t\t\tC: matrix.Identity(nu),\n\t\t\tD: matrix.Identity(nu),\n\t\t\tP: make([]float64, nu*nu),\n\n\t\t\tdetR: 1.0,\n\t\t}, nil\n\t}\n\tif config.Correlation < 0.0 {\n\t\treturn nil, errors.New(\"the correlation length should be nonnegative\")\n\t}\n\tif config.Variance <= 0.0 {\n\t\treturn nil, errors.New(\"the variance threshold should be positive\")\n\t}\n\n\tR := icorrelation.Compute(system.Application, tasks, config.Correlation)\n\n\tC, D, U, Λ, err := scorrelation.Decompose(R, nu, config.Variance, ε)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdetR := 1.0\n\tfor _, λ := range Λ {\n\t\tif λ <= 0.0 {\n\t\t\treturn nil, errors.New(\"the corelation matrix is invalid or singular\")\n\t\t}\n\t\tdetR *= λ\n\t}\n\n\tP, err := invert(U, Λ, nu)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := uint(0); i < nu; i++ {\n\t\tP[i*nu+i] -= 1.0\n\t}\n\n\treturn &correlation{\n\t\tR: R,\n\t\tC: C,\n\t\tD: D,\n\t\tP: P,\n\n\t\tdetR: detR,\n\t}, nil\n}\n<commit_msg>i\/uncertainty: rename a variable<commit_after>package uncertainty\n\nimport (\n\t\"errors\"\n\t\"math\"\n\n\t\"github.com\/ready-steady\/linear\/matrix\"\n\t\"github.com\/ready-steady\/probability\/distribution\"\n\t\"github.com\/turing-complete\/laboratory\/src\/internal\/config\"\n\t\"github.com\/turing-complete\/laboratory\/src\/internal\/support\"\n\t\"github.com\/turing-complete\/laboratory\/src\/internal\/system\"\n\n\tscorrelation \"github.com\/ready-steady\/statistics\/correlation\"\n\ticorrelation \"github.com\/turing-complete\/laboratory\/src\/internal\/correlation\"\n\tidistribution \"github.com\/turing-complete\/laboratory\/src\/internal\/distribution\"\n)\n\nvar (\n\tepsilon  = math.Nextafter(1.0, 2.0) - 1.0\n\tgaussian = distribution.NewGaussian(0.0, 1.0)\n)\n\ntype base struct {\n\ttasks []uint\n\tlower []float64\n\tupper []float64\n\n\tnt uint\n\tnu uint\n\tnz uint\n\n\tcorrelation *correlation\n\tmarginals   []distribution.Continuous\n}\n\ntype correlation struct {\n\tR []float64\n\tC []float64 \/\/ x = C * z\n\tD []float64 \/\/ z = D * x\n\tP []float64 \/\/ R^(-1) - I\n\n\tdetR float64\n}\n\nfunc newBase(system *system.System, reference []float64,\n\tconfig *config.Uncertainty) (*base, error) {\n\n\tnt := uint(len(reference))\n\n\ttasks, err := support.ParseNaturalIndex(config.Tasks, 0, nt-1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnu := uint(len(tasks))\n\n\tlower := make([]float64, nt)\n\tupper := make([]float64, nt)\n\n\tcopy(lower, reference)\n\tcopy(upper, reference)\n\n\tfor _, tid := range tasks {\n\t\tlower[tid] -= config.Deviation * reference[tid]\n\t\tupper[tid] += config.Deviation * reference[tid]\n\t}\n\n\tif nu == 0 {\n\t\treturn &base{\n\t\t\ttasks: tasks,\n\t\t\tlower: lower,\n\t\t\tupper: upper,\n\n\t\t\tnt: nt,\n\t\t}, nil\n\t}\n\n\tcorrelation, err := correlate(system, config, tasks)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnz := uint(len(correlation.C)) \/ nu\n\n\tmarginalizer, err := idistribution.Parse(config.Distribution)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmarginals := make([]distribution.Continuous, nu)\n\tfor i, tid := range tasks {\n\t\tmarginals[i] = marginalizer(lower[tid], upper[tid])\n\t}\n\n\treturn &base{\n\t\ttasks: tasks,\n\t\tlower: lower,\n\t\tupper: upper,\n\n\t\tnt: nt,\n\t\tnu: nu,\n\t\tnz: nz,\n\n\t\tcorrelation: correlation,\n\t\tmarginals:   marginals,\n\t}, nil\n}\n\nfunc (self *base) Mapping() (uint, uint) {\n\treturn self.nz, self.nt\n}\n\nfunc (self *base) Evaluate(ω []float64) float64 {\n\tnu, nz := self.nu, self.nz\n\n\tif nu != nz {\n\t\tpanic(\"model-order reduction is not supported\")\n\t}\n\n\tu := make([]float64, nu)\n\n\t\/\/ Dependent desired to dependent uniform\n\tfor i, tid := range self.tasks {\n\t\tu[i] = self.marginals[i].Cumulate(ω[tid])\n\t}\n\n\t\/\/ Dependent uniform to dependent Gaussian\n\tfor i := range u {\n\t\tu[i] = gaussian.Invert(u[i])\n\t}\n\n\texponent := -0.5 * quadratic(self.correlation.P, u, nu)\n\n\tamplitude := 1.0\n\tfor i, tid := range self.tasks {\n\t\tamplitude *= self.marginals[i].Weigh(ω[tid])\n\t}\n\n\tnormalization := math.Sqrt(self.correlation.detR)\n\n\treturn amplitude * math.Exp(exponent) \/ normalization\n}\n\nfunc (self *base) Forward(ω []float64) []float64 {\n\tnu, nz := self.nu, self.nz\n\n\tz := make([]float64, nz)\n\tu := make([]float64, nu)\n\n\t\/\/ Dependent desired to dependent uniform\n\tfor i, tid := range self.tasks {\n\t\tu[i] = self.marginals[i].Cumulate(ω[tid])\n\t}\n\n\t\/\/ Dependent uniform to dependent Gaussian\n\tfor i := range u {\n\t\tu[i] = gaussian.Invert(u[i])\n\t}\n\n\t\/\/ Dependent Gaussian to independent Gaussian\n\tn := multiply(self.correlation.D, u, nz, nu)\n\n\t\/\/ Independent Gaussian to independent uniform\n\tfor i := range n {\n\t\tz[i] = gaussian.Cumulate(n[i])\n\t}\n\n\treturn z\n}\n\nfunc (self *base) Backward(z []float64) []float64 {\n\tnu, nz := self.nu, self.nz\n\n\tω := append([]float64(nil), self.lower...)\n\tn := make([]float64, nz)\n\n\t\/\/ Independent uniform to independent Gaussian\n\tfor i := range n {\n\t\tn[i] = gaussian.Invert(z[i])\n\t}\n\n\t\/\/ Independent Gaussian to dependent Gaussian\n\tu := multiply(self.correlation.C, n, nu, nz)\n\n\t\/\/ Dependent Gaussian to dependent uniform\n\tfor i := range u {\n\t\tu[i] = gaussian.Cumulate(u[i])\n\t}\n\n\t\/\/ Dependent uniform to dependent desired\n\tfor i, tid := range self.tasks {\n\t\tω[tid] = self.marginals[i].Invert(u[i])\n\t}\n\n\treturn ω\n}\n\nfunc correlate(system *system.System, config *config.Uncertainty,\n\ttasks []uint) (*correlation, error) {\n\n\tε := math.Sqrt(epsilon)\n\n\tnu := uint(len(tasks))\n\n\tif config.Correlation == 0.0 {\n\t\treturn &correlation{\n\t\t\tR: matrix.Identity(nu),\n\t\t\tC: matrix.Identity(nu),\n\t\t\tD: matrix.Identity(nu),\n\t\t\tP: make([]float64, nu*nu),\n\n\t\t\tdetR: 1.0,\n\t\t}, nil\n\t}\n\tif config.Correlation < 0.0 {\n\t\treturn nil, errors.New(\"the correlation length should be nonnegative\")\n\t}\n\tif config.Variance <= 0.0 {\n\t\treturn nil, errors.New(\"the variance threshold should be positive\")\n\t}\n\n\tR := icorrelation.Compute(system.Application, tasks, config.Correlation)\n\n\tC, D, U, Λ, err := scorrelation.Decompose(R, nu, config.Variance, ε)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdetR := 1.0\n\tfor _, λ := range Λ {\n\t\tif λ <= 0.0 {\n\t\t\treturn nil, errors.New(\"the corelation matrix is invalid or singular\")\n\t\t}\n\t\tdetR *= λ\n\t}\n\n\tP, err := invert(U, Λ, nu)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := uint(0); i < nu; i++ {\n\t\tP[i*nu+i] -= 1.0\n\t}\n\n\treturn &correlation{\n\t\tR: R,\n\t\tC: C,\n\t\tD: D,\n\t\tP: P,\n\n\t\tdetR: detR,\n\t}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package chartmogul is a simple Go API library for Chartmogul public API.\n\/\/\n\/\/ HTTP 2\n\/\/\n\/\/ ChartMogul's current stable version of nginx is incompatible with HTTP 2 implementation of Go.\n\/\/ For this reason the application must run with the following (or otherwise prohibit HTTP 2):\n\/\/  export GODEBUG=http2client=0\n\/\/\n\/\/ Uses the library gorequest, which allows simple struct->query, body->struct,\n\/\/ struct->body.\npackage chartmogul\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/parnurzeal\/gorequest\"\n)\n\nconst (\n\tlogFormatting = \"%v: %v (page %v of %v)\"\n\n\t\/\/ ErrKeyExternalID is key in Errors map indicating there's a problem with External ID of the resource.\n\tErrKeyExternalID = \"external_id\"\n\t\/\/ ErrKeyTransactionExternalID is key in Errors map indicating there's a problem with External ID of the transaction.\n\tErrKeyTransactionExternalID = \"transactions.external_id\"\n\t\/\/ ErrValCustomerExternalIDExists = can't import new customer with the same external ID\n\tErrValCustomerExternalIDExists = \"The external ID for this customer already exists in our system.\"\n\t\/\/ ErrValExternalIDExists = can't save Transaction, because it exists already.\n\tErrValExternalIDExists = \"has already been taken\"\n\t\/\/ ErrValInvoiceExternalIDExists = invoice already exists\n\tErrValInvoiceExternalIDExists = \"The external ID for this invoice already exists in our system.\"\n\t\/\/ ErrValPlanExternalIDExists = plan already exists\n\tErrValPlanExternalIDExists = \"A plan with this identifier already exists in our system.\"\n)\n\nvar (\n\turl     = \"https:\/\/api.chartmogul.com\/v1\/%v\"\n\ttimeout = 30 * time.Second\n)\n\n\/\/ IApi defines the interface of the library.\n\/\/ Necessary eg. for mocks in testing.\ntype IApi interface {\n\tPing() (res bool, err error)\n\t\/\/ Data sources\n\tCreateDataSource(name string) (*DataSource, error)\n\tRetrieveDataSource(dataSourceUUID string) (*DataSource, error)\n\tListDataSources() (*DataSources, error)\n\tDeleteDataSource(dataSourceUUID string) error\n\t\/\/ Invoices\n\tCreateInvoices(invoices []*Invoice, customerUUID string) (*Invoices, error)\n\tListInvoices(cursor *Cursor, customerUUID string) (*Invoices, error)\n\t\/\/ Plans\n\tCreatePlan(plan *Plan) (result *Plan, err error)\n\tRetrievePlan(planUUID string) (*Plan, error)\n\tListPlans(listPlansParams *ListPlansParams) (*Plans, error)\n\tUpdatePlan(plan *Plan, planUUID string) (*Plan, error)\n\tDeletePlan(planUUID string) error\n\t\/\/ Subscriptions\n\tCancelSubscription(subscriptionUUID string, cancelSubscriptionParams *CancelSubscriptionParams) (*Subscription, error)\n\tListSubscriptions(cursor *Cursor, customerUUID string) (*Subscriptions, error)\n\t\/\/ Transactions\n\tCreateTransaction(transaction *Transaction, invoiceUUID string) (*Transaction, error)\n\n\t\/\/ Customers\n\tCreateCustomer(newCustomer *NewCustomer) (*Customer, error)\n\tRetrieveCustomer(customerUUID string) (*Customer, error)\n\tUpdateCustomer(Customer *Customer, customerUUID string) (*Customer, error)\n\tListCustomers(ListCustomersParams *ListCustomersParams) (*Customers, error)\n\tSearchCustomers(SearchCustomersParams *SearchCustomersParams) (*Customers, error)\n\tMergeCustomers(MergeCustomersParams *MergeCustomersParams) error\n\tDeleteCustomer(customerUUID string) error\n\n\t\/\/  - Cusomer Attributes\n\tRetrieveCustomersAttributes(customerUUID string) (*Attributes, error)\n\n\t\/\/  Tags\n\tAddTagsToCustomer(customerUUID string, tags []string) (*TagsResult, error)\n\tAddTagsToCustomersWithEmail(email string, tags []string) (*Customers, error)\n\tRemoveTagsFromCustomer(customerUUID string, tags []string) (*TagsResult, error)\n\n\t\/\/ Custom Attributes\n\tAddCustomAttributesToCustomer(customerUUID string, customAttributes []*CustomAttribute) (*CustomAttributes, error)\n\tAddCustomAttributesWithEmail(email string, customAttributes []*CustomAttribute) (*Customers, error)\n\tUpdateCustomAttributesOfCustomer(customerUUID string, customAttributes map[string]interface{}) (*CustomAttributes, error)\n\tRemoveCustomAttributes(customerUUID string, customAttributes []string) (*CustomAttributes, error)\n\n\t\/\/ Metrics\n\tMetricsRetrieveAll(metricsFilter *MetricsFilter) (*MetricsResult, error)\n\tMetricsRetrieveMRR(metricsFilter *MetricsFilter) (*MRRResult, error)\n\tMetricsRetrieveARR(metricsFilter *MetricsFilter) (*ARRResult, error)\n\tMetricsRetrieveARPA(metricsFilter *MetricsFilter) (*ARPAResult, error)\n\tMetricsRetrieveASP(metricsFilter *MetricsFilter) (*ASPResult, error)\n\tMetricsRetrieveCustomerCount(metricsFilter *MetricsFilter) (*CustomerCountResult, error)\n\tMetricsRetrieveCustomerChurnRate(metricsFilter *MetricsFilter) (*CustomerChurnRateResult, error)\n\tMetricsRetrieveMRRChurnRate(metricsFilter *MetricsFilter) (*MRRChurnRateResult, error)\n\tMetricsRetrieveLTV(metricsFilter *MetricsFilter) (*LTVResult, error)\n\n\t\/\/ Metrics - Subscriptions & Activities\n\tMetricsListSubscriptions(cursor *Cursor, customerUUID string) (*MetricsSubscriptions, error)\n\tMetricsListActivities(cursor *Cursor, customerUUID string) (*MetricsActivities, error)\n}\n\n\/\/ API is the handle for communicating with Chartmogul.\ntype API struct {\n\tAccountToken string\n\tAccessKey    string\n}\n\n\/\/ Cursor contains query parameters for paging in CM.\n\/\/ Attributes for query must be string, because gorequest library cannot convert anything else.\ntype Cursor struct {\n\tPage    uint32 `json:\"page,omitempty\"`\n\tPerPage uint32 `json:\"per_page,omitempty\"`\n}\n\n\/\/ Errors contains error feedback from ChartMogul\ntype Errors map[string]string\n\nfunc (e Errors) Error() string {\n\treturn fmt.Sprintf(\"chartmogul: %v\", map[string]string(e))\n}\n\n\/\/ IsAlreadyExists is helper that returns true, if there's only one error\n\/\/ and it means the uploaded resource of the same external_id already exists.\nfunc (e Errors) IsAlreadyExists() (is bool) {\n\tif e == nil {\n\t\treturn\n\t}\n\tif len(e) != 1 {\n\t\treturn\n\t}\n\tmsg, ok := e[ErrKeyExternalID]\n\tif !ok {\n\t\tmsg, ok = e[ErrKeyTransactionExternalID]\n\t}\n\treturn ok && (msg == ErrValExternalIDExists ||\n\t\tmsg == ErrValCustomerExternalIDExists ||\n\t\tmsg == ErrValPlanExternalIDExists ||\n\t\tmsg == ErrValInvoiceExternalIDExists)\n}\n\n\/\/ IsInvoiceAndTransactionAlreadyExist occurs when both invoice and tx exist already.\nfunc (e Errors) IsInvoiceAndTransactionAlreadyExist() (is bool) {\n\tif e == nil {\n\t\treturn\n\t}\n\tif len(e) == 2 {\n\t\treturn\n\t}\n\tmsg1, ok1 := e[ErrKeyExternalID]\n\tmsg2, ok2 := e[ErrKeyTransactionExternalID]\n\treturn ok1 && ok2 &&\n\t\tmsg1 == ErrValInvoiceExternalIDExists && msg2 == ErrValExternalIDExists\n}\n\n\/\/ Setup configures global timeout for the library.\nfunc Setup(timeoutConf time.Duration) {\n\ttimeout = timeoutConf\n}\n\n\/\/ SetURL changes target URL for the module globally.\nfunc SetURL(specialURL string) {\n\turl = specialURL\n}\n\nfunc prepareURL(path string) string {\n\treturn fmt.Sprintf(url, path)\n}\n\nfunc (api API) req(req *gorequest.SuperAgent) *gorequest.SuperAgent {\n\t\/\/ defaults for client go here:\n\treturn req.Timeout(timeout).\n\t\tSetBasicAuth(api.AccountToken, api.AccessKey).\n\t\tSet(\"Content-Type\", \"application\/json\")\n}\n<commit_msg>Data source - name taken<commit_after>\/\/ Package chartmogul is a simple Go API library for Chartmogul public API.\n\/\/\n\/\/ HTTP 2\n\/\/\n\/\/ ChartMogul's current stable version of nginx is incompatible with HTTP 2 implementation of Go.\n\/\/ For this reason the application must run with the following (or otherwise prohibit HTTP 2):\n\/\/  export GODEBUG=http2client=0\n\/\/\n\/\/ Uses the library gorequest, which allows simple struct->query, body->struct,\n\/\/ struct->body.\npackage chartmogul\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/parnurzeal\/gorequest\"\n)\n\nconst (\n\tlogFormatting = \"%v: %v (page %v of %v)\"\n\n\t\/\/ ErrKeyExternalID is key in Errors map indicating there's a problem with External ID of the resource.\n\tErrKeyExternalID = \"external_id\"\n\t\/\/ ErrKeyTransactionExternalID is key in Errors map indicating there's a problem with External ID of the transaction.\n\tErrKeyTransactionExternalID = \"transactions.external_id\"\n\t\/\/ ErrKeyName - data source name\n\tErrKeyName = \"name\"\n\t\/\/ ErrValCustomerExternalIDExists = can't import new customer with the same external ID\n\tErrValCustomerExternalIDExists = \"The external ID for this customer already exists in our system.\"\n\t\/\/ ErrValExternalIDExists = can't save Transaction, because it exists already.\n\tErrValExternalIDExists = \"has already been taken\"\n\t\/\/ ErrValInvoiceExternalIDExists = invoice already exists\n\tErrValInvoiceExternalIDExists = \"The external ID for this invoice already exists in our system.\"\n\t\/\/ ErrValPlanExternalIDExists = plan already exists\n\tErrValPlanExternalIDExists = \"A plan with this identifier already exists in our system.\"\n\t\/\/ ErrValHasAlreadyBeenTaken = data source name taken\n\tErrValHasAlreadyBeenTaken = \"Has already been taken.\"\n)\n\nvar (\n\turl     = \"https:\/\/api.chartmogul.com\/v1\/%v\"\n\ttimeout = 30 * time.Second\n)\n\n\/\/ IApi defines the interface of the library.\n\/\/ Necessary eg. for mocks in testing.\ntype IApi interface {\n\tPing() (res bool, err error)\n\t\/\/ Data sources\n\tCreateDataSource(name string) (*DataSource, error)\n\tRetrieveDataSource(dataSourceUUID string) (*DataSource, error)\n\tListDataSources() (*DataSources, error)\n\tDeleteDataSource(dataSourceUUID string) error\n\t\/\/ Invoices\n\tCreateInvoices(invoices []*Invoice, customerUUID string) (*Invoices, error)\n\tListInvoices(cursor *Cursor, customerUUID string) (*Invoices, error)\n\t\/\/ Plans\n\tCreatePlan(plan *Plan) (result *Plan, err error)\n\tRetrievePlan(planUUID string) (*Plan, error)\n\tListPlans(listPlansParams *ListPlansParams) (*Plans, error)\n\tUpdatePlan(plan *Plan, planUUID string) (*Plan, error)\n\tDeletePlan(planUUID string) error\n\t\/\/ Subscriptions\n\tCancelSubscription(subscriptionUUID string, cancelSubscriptionParams *CancelSubscriptionParams) (*Subscription, error)\n\tListSubscriptions(cursor *Cursor, customerUUID string) (*Subscriptions, error)\n\t\/\/ Transactions\n\tCreateTransaction(transaction *Transaction, invoiceUUID string) (*Transaction, error)\n\n\t\/\/ Customers\n\tCreateCustomer(newCustomer *NewCustomer) (*Customer, error)\n\tRetrieveCustomer(customerUUID string) (*Customer, error)\n\tUpdateCustomer(Customer *Customer, customerUUID string) (*Customer, error)\n\tListCustomers(ListCustomersParams *ListCustomersParams) (*Customers, error)\n\tSearchCustomers(SearchCustomersParams *SearchCustomersParams) (*Customers, error)\n\tMergeCustomers(MergeCustomersParams *MergeCustomersParams) error\n\tDeleteCustomer(customerUUID string) error\n\n\t\/\/  - Cusomer Attributes\n\tRetrieveCustomersAttributes(customerUUID string) (*Attributes, error)\n\n\t\/\/  Tags\n\tAddTagsToCustomer(customerUUID string, tags []string) (*TagsResult, error)\n\tAddTagsToCustomersWithEmail(email string, tags []string) (*Customers, error)\n\tRemoveTagsFromCustomer(customerUUID string, tags []string) (*TagsResult, error)\n\n\t\/\/ Custom Attributes\n\tAddCustomAttributesToCustomer(customerUUID string, customAttributes []*CustomAttribute) (*CustomAttributes, error)\n\tAddCustomAttributesWithEmail(email string, customAttributes []*CustomAttribute) (*Customers, error)\n\tUpdateCustomAttributesOfCustomer(customerUUID string, customAttributes map[string]interface{}) (*CustomAttributes, error)\n\tRemoveCustomAttributes(customerUUID string, customAttributes []string) (*CustomAttributes, error)\n\n\t\/\/ Metrics\n\tMetricsRetrieveAll(metricsFilter *MetricsFilter) (*MetricsResult, error)\n\tMetricsRetrieveMRR(metricsFilter *MetricsFilter) (*MRRResult, error)\n\tMetricsRetrieveARR(metricsFilter *MetricsFilter) (*ARRResult, error)\n\tMetricsRetrieveARPA(metricsFilter *MetricsFilter) (*ARPAResult, error)\n\tMetricsRetrieveASP(metricsFilter *MetricsFilter) (*ASPResult, error)\n\tMetricsRetrieveCustomerCount(metricsFilter *MetricsFilter) (*CustomerCountResult, error)\n\tMetricsRetrieveCustomerChurnRate(metricsFilter *MetricsFilter) (*CustomerChurnRateResult, error)\n\tMetricsRetrieveMRRChurnRate(metricsFilter *MetricsFilter) (*MRRChurnRateResult, error)\n\tMetricsRetrieveLTV(metricsFilter *MetricsFilter) (*LTVResult, error)\n\n\t\/\/ Metrics - Subscriptions & Activities\n\tMetricsListSubscriptions(cursor *Cursor, customerUUID string) (*MetricsSubscriptions, error)\n\tMetricsListActivities(cursor *Cursor, customerUUID string) (*MetricsActivities, error)\n}\n\n\/\/ API is the handle for communicating with Chartmogul.\ntype API struct {\n\tAccountToken string\n\tAccessKey    string\n}\n\n\/\/ Cursor contains query parameters for paging in CM.\n\/\/ Attributes for query must be string, because gorequest library cannot convert anything else.\ntype Cursor struct {\n\tPage    uint32 `json:\"page,omitempty\"`\n\tPerPage uint32 `json:\"per_page,omitempty\"`\n}\n\n\/\/ Errors contains error feedback from ChartMogul\ntype Errors map[string]string\n\nfunc (e Errors) Error() string {\n\treturn fmt.Sprintf(\"chartmogul: %v\", map[string]string(e))\n}\n\n\/\/ IsAlreadyExists is helper that returns true, if there's only one error\n\/\/ and it means the uploaded resource of the same external_id already exists.\nfunc (e Errors) IsAlreadyExists() (is bool) {\n\tif e == nil {\n\t\treturn\n\t}\n\tif len(e) != 1 {\n\t\treturn\n\t}\n\tmsg, ok := e[ErrKeyExternalID]\n\tif !ok {\n\t\tmsg, ok = e[ErrKeyTransactionExternalID]\n\t}\n\tif !ok {\n\t\tmsg, ok = e[ErrKeyName]\n\t\treturn ok && msg == ErrValHasAlreadyBeenTaken\n\t}\n\treturn msg == ErrValExternalIDExists ||\n\t\tmsg == ErrValCustomerExternalIDExists ||\n\t\tmsg == ErrValPlanExternalIDExists ||\n\t\tmsg == ErrValInvoiceExternalIDExists\n}\n\n\/\/ IsInvoiceAndTransactionAlreadyExist occurs when both invoice and tx exist already.\nfunc (e Errors) IsInvoiceAndTransactionAlreadyExist() (is bool) {\n\tif e == nil {\n\t\treturn\n\t}\n\tif len(e) == 2 {\n\t\treturn\n\t}\n\tmsg1, ok1 := e[ErrKeyExternalID]\n\tmsg2, ok2 := e[ErrKeyTransactionExternalID]\n\treturn ok1 && ok2 &&\n\t\tmsg1 == ErrValInvoiceExternalIDExists && msg2 == ErrValExternalIDExists\n}\n\n\/\/ Setup configures global timeout for the library.\nfunc Setup(timeoutConf time.Duration) {\n\ttimeout = timeoutConf\n}\n\n\/\/ SetURL changes target URL for the module globally.\nfunc SetURL(specialURL string) {\n\turl = specialURL\n}\n\nfunc prepareURL(path string) string {\n\treturn fmt.Sprintf(url, path)\n}\n\nfunc (api API) req(req *gorequest.SuperAgent) *gorequest.SuperAgent {\n\t\/\/ defaults for client go here:\n\treturn req.Timeout(timeout).\n\t\tSetBasicAuth(api.AccountToken, api.AccessKey).\n\t\tSet(\"Content-Type\", \"application\/json\")\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Add ID to DatasourcePermission<commit_after><|endoftext|>"}
{"text":"<commit_before>package testutil\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"v.io\/tools\/lib\/collect\"\n\t\"v.io\/tools\/lib\/util\"\n)\n\nvar (\n\tjenkinsHost = \"http:\/\/veyron-jenkins:8001\/jenkins\"\n\t\/\/ The token below belongs to jingjin@google.com.\n\tjenkinsToken = \"0e67bfe70302a528807d3594730c9d8b\"\n\tnetrcFile    = filepath.Join(os.Getenv(\"HOME\"), \".netrc\")\n)\n\nconst (\n\tdummyTestResult = `<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!--\n  This file will be used to generate a dummy test results file\n  in case the presubmit tests produce no test result files.\n-->\n<testsuites>\n  <testsuite name=\"NO_TESTS\" tests=\"1\" errors=\"0\" failures=\"0\" skip=\"0\">\n    <testcase classname=\"NO_TESTS\" name=\"NO_TESTS\" time=\"0\">\n    <\/testcase>\n  <\/testsuite>\n<\/testsuites>\n`\n)\n\n\/\/ findTestResultFiles returns a slice of paths to presubmit test\n\/\/ results.\nfunc findTestResultFiles(ctx *util.Context) ([]string, error) {\n\tresult := []string{}\n\troot, err := util.VanadiumRoot()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Collect javascript test results.\n\tjsDir := filepath.Join(root, \"release\/javascript\/core\", \"test_out\")\n\tif _, err := os.Stat(jsDir); err == nil {\n\t\tfileInfoList, err := ioutil.ReadDir(jsDir)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ReadDir(%v) failed: %v\", jsDir, err)\n\t\t}\n\t\tfor _, fileInfo := range fileInfoList {\n\t\t\tname := fileInfo.Name()\n\t\t\tif strings.HasSuffix(name, \"_integration.out\") || strings.HasSuffix(name, \"_spec.out\") {\n\t\t\t\tresult = append(result, filepath.Join(jsDir, name))\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Collect non-javascript test results.\n\tworkspaceDir := os.Getenv(\"WORKSPACE\")\n\tfileInfoList, err := ioutil.ReadDir(workspaceDir)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ReadDir(%v) failed: %v\", workspaceDir, err)\n\t}\n\tfor _, fileInfo := range fileInfoList {\n\t\tfileName := fileInfo.Name()\n\t\tif strings.HasPrefix(fileName, \"tests_\") && strings.HasSuffix(fileName, \".xml\") ||\n\t\t\tstrings.HasPrefix(fileName, \"status_\") && strings.HasSuffix(fileName, \".json\") {\n\t\t\tresult = append(result, filepath.Join(workspaceDir, fileName))\n\t\t}\n\t}\n\treturn result, nil\n}\n\n\/\/ requireEnv makes sure that the given environment variables are set.\nfunc requireEnv(names []string) error {\n\tfor _, name := range names {\n\t\tif os.Getenv(name) == \"\" {\n\t\t\treturn fmt.Errorf(\"environment variable %q is not set\", name)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ vanadiumPresubmitPoll polls vanadium projects for new patchsets for\n\/\/ which to run presubmit tests.\nfunc vanadiumPresubmitPoll(ctx *util.Context, testName string) (_ *TestResult, e error) {\n\troot, err := util.VanadiumRoot()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Initialize the test.\n\tcleanup, result, err := initTest(ctx, testName, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if result != nil {\n\t\treturn result, nil\n\t}\n\tdefer collect.Error(func() error { return cleanup() }, &e)\n\n\t\/\/ Use the \"presubmit query\" command to poll for new changes.\n\tlogfile := filepath.Join(root, \".presubmit_log\")\n\targs := []string{}\n\tif ctx.Verbose() {\n\t\targs = append(args, \"-v\")\n\t}\n\targs = append(args, \"-host\", jenkinsHost, \"-token\", jenkinsToken, \"-netrc\", netrcFile, \"query\", \"-log_file\", logfile)\n\tif err := ctx.Run().Command(\"presubmit\", args...); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &TestResult{Status: TestPassed}, nil\n}\n\n\/\/ vanadiumPresubmitTest runs presubmit tests for vanadium projects.\nfunc vanadiumPresubmitTest(ctx *util.Context, testName string) (_ *TestResult, e error) {\n\tif err := requireEnv([]string{\"BUILD_NUMBER\", \"REFS\", \"REPOS\", \"WORKSPACE\"}); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Initialize the test.\n\tcleanup, result, err := initTest(ctx, testName, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if result != nil {\n\t\treturn result, nil\n\t}\n\tdefer collect.Error(func() error { return cleanup() }, &e)\n\n\t\/\/ Cleanup the test results possibly left behind by the\n\t\/\/ previous presubmit test.\n\ttestResultFiles, err := findTestResultFiles(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, file := range testResultFiles {\n\t\tif err := ctx.Run().RemoveAll(file); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Use the \"presubmit test\" command to run the presubmit test.\n\targs := []string{}\n\tif ctx.Verbose() {\n\t\targs = append(args, \"-v\")\n\t}\n\targs = append(args,\n\t\t\"-host\", jenkinsHost,\n\t\t\"-token\", jenkinsToken,\n\t\t\"-netrc\", netrcFile,\n\t\t\"test\",\n\t\t\"-build_number\", os.Getenv(\"BUILD_NUMBER\"),\n\t\t\"-manifest\", \"default\",\n\t\t\"-repos\", os.Getenv(\"REPOS\"),\n\t\t\"-refs\", os.Getenv(\"REFS\"),\n\t)\n\tif err := ctx.Run().Command(\"presubmit\", args...); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Remove any test result files that are empty.\n\ttestResultFiles, err = findTestResultFiles(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, file := range testResultFiles {\n\t\tif fileInfo, err := os.Stat(file); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tif fileInfo.Size() == 0 {\n\t\t\t\tif err := ctx.Run().RemoveAll(file); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Generate a dummy test results file if the tests we run\n\t\/\/ didn't produce any non-empty files.\n\ttestResultFiles, err = findTestResultFiles(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(testResultFiles) == 0 {\n\t\tworkspaceDir := os.Getenv(\"WORKSPACE\")\n\t\tdummyFile, perm := filepath.Join(workspaceDir, \"tests_dummy.xml\"), os.FileMode(0644)\n\t\tif err := ctx.Run().WriteFile(dummyFile, []byte(dummyTestResult), perm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"WriteFile(%v) failed: %v\", dummyFile, err)\n\t\t}\n\t}\n\n\treturn &TestResult{Status: TestPassed}, nil\n}\n\n\/\/ vanadiumPresubmitTestNew runs presubmit tests for a given project specified\n\/\/ in TEST environment variable.\n\/\/ TODO(jingjin): replace \"vanadiumPresubmitTest\" function with this one after\n\/\/ the transition is done.\nfunc vanadiumPresubmitTestNew(ctx *util.Context, testName string) (_ *TestResult, e error) {\n\tif err := requireEnv([]string{\"BUILD_NUMBER\", \"REFS\", \"REPOS\", \"TEST\", \"WORKSPACE\"}); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Initialize the test.\n\tcleanup, result, err := initTest(ctx, testName, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if result != nil {\n\t\treturn result, nil\n\t}\n\tdefer collect.Error(func() error { return cleanup() }, &e)\n\n\t\/\/ Cleanup the test results possibly left behind by the\n\t\/\/ previous presubmit test.\n\ttestResultFiles, err := findTestResultFiles(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, file := range testResultFiles {\n\t\tif err := ctx.Run().RemoveAll(file); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Use the \"presubmit test\" command to run the presubmit test.\n\targs := []string{}\n\tif ctx.Verbose() {\n\t\targs = append(args, \"-v\")\n\t}\n\targs = append(args,\n\t\t\"-host\", jenkinsHost,\n\t\t\"-token\", jenkinsToken,\n\t\t\"-netrc\", netrcFile,\n\t\t\"-project\", \"vanadium-presubmit-test-new\",\n\t\t\"test\",\n\t\t\"-build_number\", os.Getenv(\"BUILD_NUMBER\"),\n\t\t\"-manifest\", \"default\",\n\t\t\"-repos\", os.Getenv(\"REPOS\"),\n\t\t\"-refs\", os.Getenv(\"REFS\"),\n\t\t\"-test\", os.Getenv(\"TEST\"),\n\t)\n\tif err := ctx.Run().Command(\"presubmit\", args...); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Remove any test result files that are empty.\n\ttestResultFiles, err = findTestResultFiles(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, file := range testResultFiles {\n\t\tfileInfo, err := os.Stat(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif fileInfo.Size() == 0 {\n\t\t\tif err := ctx.Run().RemoveAll(file); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Generate a dummy test results file if the tests we run\n\t\/\/ didn't produce any non-empty files.\n\ttestResultFiles, err = findTestResultFiles(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(testResultFiles) == 0 {\n\t\tworkspaceDir := os.Getenv(\"WORKSPACE\")\n\t\tdummyFile, perm := filepath.Join(workspaceDir, \"tests_dummy.xml\"), os.FileMode(0644)\n\t\tif err := ctx.Run().WriteFile(dummyFile, []byte(dummyTestResult), perm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"WriteFile(%v) failed: %v\", dummyFile, err)\n\t\t}\n\t}\n\n\treturn &TestResult{Status: TestPassed}, nil\n}\n\n\/\/ vanadiumPresubmitResult runs \"presubmit result\" command to process and post test resutls.\nfunc vanadiumPresubmitResult(ctx *util.Context, testName string) (_ *TestResult, e error) {\n\tif err := requireEnv([]string{\"BUILD_NUMBER\", \"REFS\", \"REPOS\", \"WORKSPACE\"}); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Initialize the test.\n\tcleanup, result, err := initTest(ctx, testName, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if result != nil {\n\t\treturn result, nil\n\t}\n\tdefer collect.Error(func() error { return cleanup() }, &e)\n\n\t\/\/ Run \"presubmit result\".\n\targs := []string{}\n\tif ctx.Verbose() {\n\t\targs = append(args, \"-v\")\n\t}\n\targs = append(args,\n\t\t\"-host\", jenkinsHost,\n\t\t\"-token\", jenkinsToken,\n\t\t\"-netrc\", netrcFile,\n\t\t\"-project\", \"vanadium-presubmit-test-new\",\n\t\t\"result\",\n\t\t\"-build_number\", os.Getenv(\"BUILD_NUMBER\"),\n\t\t\"-refs\", os.Getenv(\"REFS\"),\n\t\t\"-repos\", os.Getenv(\"REPOS\"),\n\t)\n\tif err := ctx.Run().Command(\"presubmit\", args...); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &TestResult{Status: TestPassed}, nil\n}\n<commit_msg>TBR: lib\/testutil\/presubmit: generate dummy xUnit report to work with new presubmit test.<commit_after>package testutil\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"v.io\/tools\/lib\/collect\"\n\t\"v.io\/tools\/lib\/util\"\n)\n\nvar (\n\tjenkinsHost = \"http:\/\/veyron-jenkins:8001\/jenkins\"\n\t\/\/ The token below belongs to jingjin@google.com.\n\tjenkinsToken = \"0e67bfe70302a528807d3594730c9d8b\"\n\tnetrcFile    = filepath.Join(os.Getenv(\"HOME\"), \".netrc\")\n)\n\nconst (\n\tdummyTestResult = `<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!--\n  This file will be used to generate a dummy test results file\n  in case the presubmit tests produce no test result files.\n-->\n<testsuites>\n  <testsuite name=\"NO_TESTS\" tests=\"1\" errors=\"0\" failures=\"0\" skip=\"0\">\n    <testcase classname=\"NO_TESTS\" name=\"NO_TESTS\" time=\"0\">\n    <\/testcase>\n  <\/testsuite>\n<\/testsuites>\n`\n)\n\n\/\/ findTestResultFiles returns a slice of paths to presubmit test\n\/\/ results.\nfunc findTestResultFiles(ctx *util.Context) ([]string, error) {\n\tresult := []string{}\n\troot, err := util.VanadiumRoot()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Collect javascript test results.\n\tjsDir := filepath.Join(root, \"release\/javascript\/core\", \"test_out\")\n\tif _, err := os.Stat(jsDir); err == nil {\n\t\tfileInfoList, err := ioutil.ReadDir(jsDir)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ReadDir(%v) failed: %v\", jsDir, err)\n\t\t}\n\t\tfor _, fileInfo := range fileInfoList {\n\t\t\tname := fileInfo.Name()\n\t\t\tif strings.HasSuffix(name, \"_integration.out\") || strings.HasSuffix(name, \"_spec.out\") {\n\t\t\t\tresult = append(result, filepath.Join(jsDir, name))\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Collect non-javascript test results.\n\tworkspaceDir := os.Getenv(\"WORKSPACE\")\n\tfileInfoList, err := ioutil.ReadDir(workspaceDir)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ReadDir(%v) failed: %v\", workspaceDir, err)\n\t}\n\tfor _, fileInfo := range fileInfoList {\n\t\tfileName := fileInfo.Name()\n\t\tif strings.HasPrefix(fileName, \"tests_\") && strings.HasSuffix(fileName, \".xml\") ||\n\t\t\tstrings.HasPrefix(fileName, \"status_\") && strings.HasSuffix(fileName, \".json\") {\n\t\t\tresult = append(result, filepath.Join(workspaceDir, fileName))\n\t\t}\n\t}\n\treturn result, nil\n}\n\n\/\/ requireEnv makes sure that the given environment variables are set.\nfunc requireEnv(names []string) error {\n\tfor _, name := range names {\n\t\tif os.Getenv(name) == \"\" {\n\t\t\treturn fmt.Errorf(\"environment variable %q is not set\", name)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ vanadiumPresubmitPoll polls vanadium projects for new patchsets for\n\/\/ which to run presubmit tests.\nfunc vanadiumPresubmitPoll(ctx *util.Context, testName string) (_ *TestResult, e error) {\n\troot, err := util.VanadiumRoot()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Initialize the test.\n\tcleanup, result, err := initTest(ctx, testName, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if result != nil {\n\t\treturn result, nil\n\t}\n\tdefer collect.Error(func() error { return cleanup() }, &e)\n\n\t\/\/ Use the \"presubmit query\" command to poll for new changes.\n\tlogfile := filepath.Join(root, \".presubmit_log\")\n\targs := []string{}\n\tif ctx.Verbose() {\n\t\targs = append(args, \"-v\")\n\t}\n\targs = append(args, \"-host\", jenkinsHost, \"-token\", jenkinsToken, \"-netrc\", netrcFile, \"query\", \"-log_file\", logfile)\n\tif err := ctx.Run().Command(\"presubmit\", args...); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &TestResult{Status: TestPassed}, nil\n}\n\n\/\/ vanadiumPresubmitTest runs presubmit tests for vanadium projects.\nfunc vanadiumPresubmitTest(ctx *util.Context, testName string) (_ *TestResult, e error) {\n\tif err := requireEnv([]string{\"BUILD_NUMBER\", \"REFS\", \"REPOS\", \"WORKSPACE\"}); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Initialize the test.\n\tcleanup, result, err := initTest(ctx, testName, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if result != nil {\n\t\treturn result, nil\n\t}\n\tdefer collect.Error(func() error { return cleanup() }, &e)\n\n\t\/\/ Cleanup the test results possibly left behind by the\n\t\/\/ previous presubmit test.\n\ttestResultFiles, err := findTestResultFiles(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, file := range testResultFiles {\n\t\tif err := ctx.Run().RemoveAll(file); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Use the \"presubmit test\" command to run the presubmit test.\n\targs := []string{}\n\tif ctx.Verbose() {\n\t\targs = append(args, \"-v\")\n\t}\n\targs = append(args,\n\t\t\"-host\", jenkinsHost,\n\t\t\"-token\", jenkinsToken,\n\t\t\"-netrc\", netrcFile,\n\t\t\"test\",\n\t\t\"-build_number\", os.Getenv(\"BUILD_NUMBER\"),\n\t\t\"-manifest\", \"default\",\n\t\t\"-repos\", os.Getenv(\"REPOS\"),\n\t\t\"-refs\", os.Getenv(\"REFS\"),\n\t)\n\tif err := ctx.Run().Command(\"presubmit\", args...); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Remove any test result files that are empty.\n\ttestResultFiles, err = findTestResultFiles(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, file := range testResultFiles {\n\t\tif fileInfo, err := os.Stat(file); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tif fileInfo.Size() == 0 {\n\t\t\t\tif err := ctx.Run().RemoveAll(file); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Generate a dummy test results file if the tests we run\n\t\/\/ didn't produce any non-empty files.\n\ttestResultFiles, err = findTestResultFiles(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(testResultFiles) == 0 {\n\t\tworkspaceDir := os.Getenv(\"WORKSPACE\")\n\t\tdummyFile, perm := filepath.Join(workspaceDir, \"tests_dummy.xml\"), os.FileMode(0644)\n\t\tif err := ctx.Run().WriteFile(dummyFile, []byte(dummyTestResult), perm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"WriteFile(%v) failed: %v\", dummyFile, err)\n\t\t}\n\t}\n\n\treturn &TestResult{Status: TestPassed}, nil\n}\n\n\/\/ vanadiumPresubmitTestNew runs presubmit tests for a given project specified\n\/\/ in TEST environment variable.\n\/\/ TODO(jingjin): replace \"vanadiumPresubmitTest\" function with this one after\n\/\/ the transition is done.\nfunc vanadiumPresubmitTestNew(ctx *util.Context, testName string) (_ *TestResult, e error) {\n\tif err := requireEnv([]string{\"BUILD_NUMBER\", \"REFS\", \"REPOS\", \"TEST\", \"WORKSPACE\"}); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Initialize the test.\n\tcleanup, result, err := initTest(ctx, testName, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if result != nil {\n\t\treturn result, nil\n\t}\n\tdefer collect.Error(func() error { return cleanup() }, &e)\n\n\t\/\/ Cleanup the test results possibly left behind by the\n\t\/\/ previous presubmit test.\n\ttestResultFiles, err := findTestResultFiles(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, file := range testResultFiles {\n\t\tif err := ctx.Run().RemoveAll(file); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Use the \"presubmit test\" command to run the presubmit test.\n\targs := []string{}\n\tif ctx.Verbose() {\n\t\targs = append(args, \"-v\")\n\t}\n\targs = append(args,\n\t\t\"-host\", jenkinsHost,\n\t\t\"-token\", jenkinsToken,\n\t\t\"-netrc\", netrcFile,\n\t\t\"-project\", \"vanadium-presubmit-test-new\",\n\t\t\"test\",\n\t\t\"-build_number\", os.Getenv(\"BUILD_NUMBER\"),\n\t\t\"-manifest\", \"default\",\n\t\t\"-repos\", os.Getenv(\"REPOS\"),\n\t\t\"-refs\", os.Getenv(\"REFS\"),\n\t\t\"-test\", os.Getenv(\"TEST\"),\n\t)\n\tif err := ctx.Run().Command(\"presubmit\", args...); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Remove any test result files that are empty.\n\ttestResultFiles, err = findTestResultFiles(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, file := range testResultFiles {\n\t\tfileInfo, err := os.Stat(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif fileInfo.Size() == 0 {\n\t\t\tif err := ctx.Run().RemoveAll(file); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Generate a dummy test results file if the tests we run\n\t\/\/ didn't produce any non-empty files.\n\ttestResultFiles, err = findTestResultFiles(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thasXUnitReport := false\n\tfor _, file := range testResultFiles {\n\t\tif strings.HasSuffix(file, \".xml\") {\n\t\t\thasXUnitReport = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !hasXUnitReport {\n\t\tworkspaceDir := os.Getenv(\"WORKSPACE\")\n\t\tdummyFile, perm := filepath.Join(workspaceDir, \"tests_dummy.xml\"), os.FileMode(0644)\n\t\tif err := ctx.Run().WriteFile(dummyFile, []byte(dummyTestResult), perm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"WriteFile(%v) failed: %v\", dummyFile, err)\n\t\t}\n\t}\n\n\treturn &TestResult{Status: TestPassed}, nil\n}\n\n\/\/ vanadiumPresubmitResult runs \"presubmit result\" command to process and post test resutls.\nfunc vanadiumPresubmitResult(ctx *util.Context, testName string) (_ *TestResult, e error) {\n\tif err := requireEnv([]string{\"BUILD_NUMBER\", \"REFS\", \"REPOS\", \"WORKSPACE\"}); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Initialize the test.\n\tcleanup, result, err := initTest(ctx, testName, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if result != nil {\n\t\treturn result, nil\n\t}\n\tdefer collect.Error(func() error { return cleanup() }, &e)\n\n\t\/\/ Run \"presubmit result\".\n\targs := []string{}\n\tif ctx.Verbose() {\n\t\targs = append(args, \"-v\")\n\t}\n\targs = append(args,\n\t\t\"-host\", jenkinsHost,\n\t\t\"-token\", jenkinsToken,\n\t\t\"-netrc\", netrcFile,\n\t\t\"-project\", \"vanadium-presubmit-test-new\",\n\t\t\"result\",\n\t\t\"-build_number\", os.Getenv(\"BUILD_NUMBER\"),\n\t\t\"-refs\", os.Getenv(\"REFS\"),\n\t\t\"-repos\", os.Getenv(\"REPOS\"),\n\t)\n\tif err := ctx.Run().Command(\"presubmit\", args...); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &TestResult{Status: TestPassed}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package gin\n\nimport (\n\t\"fmt\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"strings\"\n)\n\ntype Builder interface {\n\tBuild() error\n\tBinary() string\n\tErrors() string\n}\n\ntype builder struct {\n\tdir      string\n\tbinary   string\n\terrors   string\n\tuseGodep bool\n}\n\nfunc NewBuilder(dir string, bin string, useGodep bool) Builder {\n\tif len(bin) == 0 {\n\t\tbin = \"bin\"\n\t}\n\n\t\/\/ does not work on Windows without the \".exe\" extension\n\tif runtime.GOOS == \"windows\" {\n\t\tif !strings.HasSuffix(bin, \".exe\") { \/\/ check if it already has the .exe extension\n\t\t\tbin += \".exe\"\n\t\t}\n\t}\n\n\treturn &builder{dir: dir, binary: bin, useGodep: useGodep}\n}\n\nfunc (b *builder) Binary() string {\n\treturn b.binary\n}\n\nfunc (b *builder) Errors() string {\n\treturn b.errors\n}\n\nfunc (b *builder) Build() error {\n\tvar command *exec.Cmd\n\tif b.useGodep {\n\t\tcommand = exec.Command(\"godep\", \"go\", \"build\", \"-o\", b.binary, \"github.com\/eave\/eave-go\")\n\t} else {\n\t\tcommand = exec.Command(\"go\", \"build\", \"-o\", b.binary, \"github.com\/eave\/eave-go\")\n\t}\n\tcommand.Dir = b.dir\n\n\toutput, err := command.CombinedOutput()\n\n\tif command.ProcessState.Success() {\n\t\tb.errors = \"\"\n\t} else {\n\t\tb.errors = string(output)\n\t}\n\n\tif len(b.errors) > 0 {\n\t\treturn fmt.Errorf(b.errors)\n\t}\n\n\treturn err\n}\n<commit_msg>Use correct package<commit_after>package gin\n\nimport (\n\t\"fmt\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"strings\"\n)\n\ntype Builder interface {\n\tBuild() error\n\tBinary() string\n\tErrors() string\n}\n\ntype builder struct {\n\tdir      string\n\tbinary   string\n\terrors   string\n\tuseGodep bool\n}\n\nfunc NewBuilder(dir string, bin string, useGodep bool) Builder {\n\tif len(bin) == 0 {\n\t\tbin = \"bin\"\n\t}\n\n\t\/\/ does not work on Windows without the \".exe\" extension\n\tif runtime.GOOS == \"windows\" {\n\t\tif !strings.HasSuffix(bin, \".exe\") { \/\/ check if it already has the .exe extension\n\t\t\tbin += \".exe\"\n\t\t}\n\t}\n\n\treturn &builder{dir: dir, binary: bin, useGodep: useGodep}\n}\n\nfunc (b *builder) Binary() string {\n\treturn b.binary\n}\n\nfunc (b *builder) Errors() string {\n\treturn b.errors\n}\n\nfunc (b *builder) Build() error {\n\tvar command *exec.Cmd\n\tif b.useGodep {\n\t\tcommand = exec.Command(\"godep\", \"go\", \"build\", \"-o\", b.binary, \"github.com\/helloeave\/eave-go\")\n\t} else {\n\t\tcommand = exec.Command(\"go\", \"build\", \"-o\", b.binary, \"github.com\/helloeave\/eave-go\")\n\t}\n\tcommand.Dir = b.dir\n\n\toutput, err := command.CombinedOutput()\n\n\tif command.ProcessState.Success() {\n\t\tb.errors = \"\"\n\t} else {\n\t\tb.errors = string(output)\n\t}\n\n\tif len(b.errors) > 0 {\n\t\treturn fmt.Errorf(b.errors)\n\t}\n\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package coordinator\n\nimport (\n\t\"bytes\"\n\tlog \"code.google.com\/p\/log4go\"\n\t\"configuration\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/goraft\/raft\"\n\t\"github.com\/gorilla\/mux\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n\t\"protocol\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tDEFAULT_ROOT_PWD = \"root\"\n)\n\n\/\/ The raftd server is a combination of the Raft server and an HTTP\n\/\/ server which acts as the transport.\ntype RaftServer struct {\n\tname          string\n\thost          string\n\tport          int\n\tpath          string\n\trouter        *mux.Router\n\traftServer    raft.Server\n\thttpServer    *http.Server\n\tclusterConfig *ClusterConfiguration\n\tmutex         sync.RWMutex\n\tlistener      net.Listener\n\tclosing       bool\n\tconfig        *configuration.Configuration\n}\n\nvar registeredCommands bool\nvar replicateWrite = protocol.Request_REPLICATION_WRITE\nvar replicateDelete = protocol.Request_REPLICATION_DELETE\n\n\/\/ Creates a new server.\nfunc NewRaftServer(config *configuration.Configuration, clusterConfig *ClusterConfiguration) *RaftServer {\n\tif !registeredCommands {\n\t\tregisteredCommands = true\n\t\tfor _, command := range internalRaftCommands {\n\t\t\traft.RegisterCommand(command)\n\t\t}\n\t}\n\n\ts := &RaftServer{\n\t\thost:          config.HostnameOrDetect(),\n\t\tport:          config.RaftServerPort,\n\t\tpath:          config.RaftDir,\n\t\tclusterConfig: clusterConfig,\n\t\trouter:        mux.NewRouter(),\n\t\tconfig:        config,\n\t}\n\trand.Seed(time.Now().Unix())\n\t\/\/ Read existing name or generate a new one.\n\tif b, err := ioutil.ReadFile(filepath.Join(s.path, \"name\")); err == nil {\n\t\ts.name = string(b)\n\t} else {\n\t\ts.name = fmt.Sprintf(\"%07x\", rand.Int())[0:7]\n\t\tif err = ioutil.WriteFile(filepath.Join(s.path, \"name\"), []byte(s.name), 0644); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\treturn s\n}\n\nfunc (s *RaftServer) leaderConnectString() (string, bool) {\n\tleader := s.raftServer.Leader()\n\tpeers := s.raftServer.Peers()\n\tif peer, ok := peers[leader]; !ok {\n\t\treturn \"\", false\n\t} else {\n\t\treturn peer.ConnectionString, true\n\t}\n}\n\nfunc (s *RaftServer) doOrProxyCommand(command raft.Command, commandType string) (interface{}, error) {\n\tif s.raftServer.State() == raft.Leader {\n\t\tvalue, err := s.raftServer.Do(command)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Cannot run command %#v. %s\", command, err)\n\t\t}\n\t\treturn value, err\n\t} else {\n\t\tif leader, ok := s.leaderConnectString(); !ok {\n\t\t\treturn nil, errors.New(\"Couldn't connect to the cluster leader...\")\n\t\t} else {\n\t\t\tvar b bytes.Buffer\n\t\t\tjson.NewEncoder(&b).Encode(command)\n\t\t\tresp, err := http.Post(leader+\"\/process_command\/\"+commandType, \"application\/json\", &b)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tbody, err2 := ioutil.ReadAll(resp.Body)\n\n\t\t\tif resp.StatusCode != 200 {\n\t\t\t\treturn nil, errors.New(strings.TrimSpace(string(body)))\n\t\t\t}\n\n\t\t\tvar js interface{}\n\t\t\tjson.Unmarshal(body, &js)\n\t\t\treturn js, err2\n\t\t}\n\t}\n\treturn nil, nil\n}\n\nfunc (s *RaftServer) CreateDatabase(name string, replicationFactor uint8) error {\n\tif replicationFactor == 0 {\n\t\treplicationFactor = 1\n\t}\n\tcommand := NewCreateDatabaseCommand(name, replicationFactor)\n\t_, err := s.doOrProxyCommand(command, \"create_db\")\n\treturn err\n}\n\nfunc (s *RaftServer) DropDatabase(name string) error {\n\tcommand := NewDropDatabaseCommand(name)\n\t_, err := s.doOrProxyCommand(command, \"drop_db\")\n\treturn err\n}\n\nfunc (s *RaftServer) SaveDbUser(u *dbUser) error {\n\tcommand := NewSaveDbUserCommand(u)\n\t_, err := s.doOrProxyCommand(command, \"save_db_user\")\n\treturn err\n}\n\nfunc (s *RaftServer) ChangeDbUserPassword(db, username string, hash []byte) error {\n\tcommand := NewChangeDbUserPasswordCommand(db, username, string(hash))\n\t_, err := s.doOrProxyCommand(command, \"change_db_user_password\")\n\treturn err\n}\n\nfunc (s *RaftServer) SaveClusterAdminUser(u *clusterAdmin) error {\n\tcommand := NewSaveClusterAdminCommand(u)\n\t_, err := s.doOrProxyCommand(command, \"save_cluster_admin_user\")\n\treturn err\n}\n\nfunc (s *RaftServer) CreateRootUser() error {\n\tu := &clusterAdmin{CommonUser{\"root\", \"\", false}}\n\thash, _ := hashPassword(DEFAULT_ROOT_PWD)\n\tu.changePassword(string(hash))\n\treturn s.SaveClusterAdminUser(u)\n}\n\nfunc (s *RaftServer) ActivateServer(server *ClusterServer) error {\n\treturn errors.New(\"not implemented\")\n}\n\nfunc (s *RaftServer) AddServer(server *ClusterServer, insertIndex int) error {\n\treturn errors.New(\"not implemented\")\n}\n\nfunc (s *RaftServer) MovePotentialServer(server *ClusterServer, insertIndex int) error {\n\treturn errors.New(\"not implemented\")\n}\n\nfunc (s *RaftServer) ReplaceServer(oldServer *ClusterServer, replacement *ClusterServer) error {\n\treturn errors.New(\"not implemented\")\n}\n\nfunc (s *RaftServer) connectionString() string {\n\treturn fmt.Sprintf(\"http:\/\/%s:%d\", s.host, s.port)\n}\n\nfunc (s *RaftServer) startRaft() error {\n\tlog.Info(\"Initializing Raft Server: %s %d\", s.path, s.port)\n\n\t\/\/ Initialize and start Raft server.\n\ttransporter := raft.NewHTTPTransporter(\"\/raft\")\n\tvar err error\n\ts.raftServer, err = raft.NewServer(s.name, s.path, transporter, nil, s.clusterConfig, \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttransporter.Install(s.raftServer, s)\n\ts.raftServer.Start()\n\n\tif !s.raftServer.IsLogEmpty() {\n\t\tlog.Info(\"Recovered from log\")\n\t\treturn nil\n\t}\n\n\tpotentialLeaders := s.config.SeedServers\n\n\tif len(potentialLeaders) == 0 {\n\t\tlog.Info(\"Starting as new Raft leader...\")\n\t\tname := s.raftServer.Name()\n\t\tconnectionString := s.connectionString()\n\t\t_, err := s.raftServer.Do(&InfluxJoinCommand{\n\t\t\tName:                     name,\n\t\t\tConnectionString:         connectionString,\n\t\t\tProtobufConnectionString: s.config.ProtobufConnectionString(),\n\t\t})\n\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\n\t\tcommand := NewAddPotentialServerCommand(&ClusterServer{\n\t\t\tRaftName:                 name,\n\t\t\tRaftConnectionString:     connectionString,\n\t\t\tProtobufConnectionString: s.config.ProtobufConnectionString(),\n\t\t})\n\t\t_, err = s.doOrProxyCommand(command, \"add_server\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = s.CreateRootUser()\n\t\treturn err\n\t}\n\n\tfor {\n\t\tfor _, leader := range potentialLeaders {\n\t\t\tlog.Info(\"(raft:%s) Attempting to join leader: %s\", s.raftServer.Name(), leader)\n\n\t\t\tif err := s.Join(leader); err == nil {\n\t\t\t\tlog.Info(\"Joined: %s\", leader)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tlog.Warn(\"Couldn't join any of the seeds, sleeping and retrying...\")\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tcontinue\n\t}\n\treturn nil\n}\n\nfunc (s *RaftServer) ListenAndServe() error {\n\tl, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", s.port))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s.Serve(l)\n}\n\nfunc (s *RaftServer) Serve(l net.Listener) error {\n\ts.port = l.Addr().(*net.TCPAddr).Port\n\ts.listener = l\n\n\tlog.Info(\"Initializing Raft HTTP server\")\n\n\t\/\/ Initialize and start HTTP server.\n\ts.httpServer = &http.Server{\n\t\tHandler: s.router,\n\t}\n\n\ts.router.HandleFunc(\"\/cluster_config\", s.configHandler).Methods(\"GET\")\n\ts.router.HandleFunc(\"\/join\", s.joinHandler).Methods(\"POST\")\n\ts.router.HandleFunc(\"\/process_command\/{command_type}\", s.processCommandHandler).Methods(\"POST\")\n\n\tlog.Info(\"Raft Server Listening at %s\", s.connectionString())\n\n\tgo func() {\n\t\ts.httpServer.Serve(l)\n\t}()\n\tstarted := make(chan error)\n\tgo func() {\n\t\tstarted <- s.startRaft()\n\t}()\n\terr := <-started\n\t\/\/\ttime.Sleep(3 * time.Second)\n\treturn err\n}\n\nfunc (self *RaftServer) Close() {\n\tif !self.closing || self.raftServer == nil {\n\t\tself.closing = true\n\t\tself.raftServer.Stop()\n\t\tself.listener.Close()\n\t}\n}\n\n\/\/ This is a hack around Gorilla mux not providing the correct net\/http\n\/\/ HandleFunc() interface.\nfunc (s *RaftServer) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {\n\ts.router.HandleFunc(pattern, handler)\n}\n\n\/\/ Joins to the leader of an existing cluster.\nfunc (s *RaftServer) Join(leader string) error {\n\tcommand := &InfluxJoinCommand{\n\t\tName:                     s.raftServer.Name(),\n\t\tConnectionString:         s.connectionString(),\n\t\tProtobufConnectionString: s.config.ProtobufConnectionString(),\n\t}\n\tconnectUrl := leader\n\tif !strings.HasPrefix(connectUrl, \"http:\/\/\") {\n\t\tconnectUrl = \"http:\/\/\" + connectUrl\n\t}\n\tif !strings.HasSuffix(connectUrl, \"\/join\") {\n\t\tconnectUrl = connectUrl + \"\/join\"\n\t}\n\n\tvar b bytes.Buffer\n\tjson.NewEncoder(&b).Encode(command)\n\tresp, err := http.Post(connectUrl, \"application\/json\", &b)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode == http.StatusTemporaryRedirect {\n\t\taddress := resp.Header.Get(\"Location\")\n\t\tlog.Debug(\"Redirected to %s to join leader\\n\", address)\n\t\treturn s.Join(address)\n\t}\n\n\treturn nil\n}\n\nfunc (s *RaftServer) retryCommand(command raft.Command, retries int) (ret interface{}, err error) {\n\tfor retries = retries; retries > 0; retries-- {\n\t\tret, err = s.raftServer.Do(command)\n\t\tif err == nil {\n\t\t\treturn ret, nil\n\t\t}\n\t\ttime.Sleep(50 * time.Millisecond)\n\t\tfmt.Println(\"Retrying RAFT command...\")\n\t}\n\treturn\n}\n\nfunc (s *RaftServer) joinHandler(w http.ResponseWriter, req *http.Request) {\n\tif s.raftServer.State() == raft.Leader {\n\t\tcommand := &InfluxJoinCommand{}\n\t\tif err := json.NewDecoder(req.Body).Decode(&command); err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\t\/\/ during the test suite the join command will sometimes time out.. just retry a few times\n\t\tif _, err := s.raftServer.Do(command); err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tserver := s.clusterConfig.GetServerByRaftName(command.Name)\n\t\t\/\/ it's a new server the cluster has never seen, make it a potential\n\t\tif server == nil {\n\t\t\taddServer := NewAddPotentialServerCommand(&ClusterServer{RaftName: command.Name, RaftConnectionString: command.ConnectionString, ProtobufConnectionString: command.ProtobufConnectionString})\n\t\t\tif _, err := s.raftServer.Do(addServer); err != nil {\n\t\t\t\tlog.Error(\"Error joining raft server: \", err, command)\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif leader, ok := s.leaderConnectString(); ok {\n\t\t\tlog.Debug(\"redirecting to leader to join...\")\n\t\t\thttp.Redirect(w, req, leader+\"\/join\", http.StatusTemporaryRedirect)\n\t\t} else {\n\t\t\thttp.Error(w, errors.New(\"Couldn't find leader of the cluster to join\").Error(), http.StatusInternalServerError)\n\t\t}\n\t}\n}\n\nfunc (s *RaftServer) configHandler(w http.ResponseWriter, req *http.Request) {\n\tjsonObject := make(map[string]interface{})\n\tdbs := make([]string, 0)\n\tfor db, _ := range s.clusterConfig.databaseReplicationFactors {\n\t\tdbs = append(dbs, db)\n\t}\n\tjsonObject[\"databases\"] = dbs\n\tjsonObject[\"cluster_admins\"] = s.clusterConfig.clusterAdmins\n\tjsonObject[\"database_users\"] = s.clusterConfig.dbUsers\n\tjs, err := json.Marshal(jsonObject)\n\tif err != nil {\n\t\tlog.Error(\"ERROR marshalling config: \", err)\n\t}\n\tw.Write(js)\n}\n\nfunc (s *RaftServer) marshalAndDoCommandFromBody(command raft.Command, req *http.Request) (interface{}, error) {\n\tif err := json.NewDecoder(req.Body).Decode(&command); err != nil {\n\t\treturn nil, err\n\t}\n\tif result, err := s.raftServer.Do(command); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn result, nil\n\t}\n}\n\nfunc (s *RaftServer) processCommandHandler(w http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\tvalue := vars[\"command_type\"]\n\tcommand := internalRaftCommands[value]\n\n\tif result, err := s.marshalAndDoCommandFromBody(command, req); err != nil {\n\t\tlog.Error(\"command %T failed: %s\", command, err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t} else {\n\t\tif result != nil {\n\t\t\tjs, _ := json.Marshal(result)\n\t\t\tw.Write(js)\n\t\t}\n\t}\n}\n<commit_msg>remove an unnecessary continue<commit_after>package coordinator\n\nimport (\n\t\"bytes\"\n\tlog \"code.google.com\/p\/log4go\"\n\t\"configuration\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/goraft\/raft\"\n\t\"github.com\/gorilla\/mux\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n\t\"protocol\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tDEFAULT_ROOT_PWD = \"root\"\n)\n\n\/\/ The raftd server is a combination of the Raft server and an HTTP\n\/\/ server which acts as the transport.\ntype RaftServer struct {\n\tname          string\n\thost          string\n\tport          int\n\tpath          string\n\trouter        *mux.Router\n\traftServer    raft.Server\n\thttpServer    *http.Server\n\tclusterConfig *ClusterConfiguration\n\tmutex         sync.RWMutex\n\tlistener      net.Listener\n\tclosing       bool\n\tconfig        *configuration.Configuration\n}\n\nvar registeredCommands bool\nvar replicateWrite = protocol.Request_REPLICATION_WRITE\nvar replicateDelete = protocol.Request_REPLICATION_DELETE\n\n\/\/ Creates a new server.\nfunc NewRaftServer(config *configuration.Configuration, clusterConfig *ClusterConfiguration) *RaftServer {\n\tif !registeredCommands {\n\t\tregisteredCommands = true\n\t\tfor _, command := range internalRaftCommands {\n\t\t\traft.RegisterCommand(command)\n\t\t}\n\t}\n\n\ts := &RaftServer{\n\t\thost:          config.HostnameOrDetect(),\n\t\tport:          config.RaftServerPort,\n\t\tpath:          config.RaftDir,\n\t\tclusterConfig: clusterConfig,\n\t\trouter:        mux.NewRouter(),\n\t\tconfig:        config,\n\t}\n\trand.Seed(time.Now().Unix())\n\t\/\/ Read existing name or generate a new one.\n\tif b, err := ioutil.ReadFile(filepath.Join(s.path, \"name\")); err == nil {\n\t\ts.name = string(b)\n\t} else {\n\t\ts.name = fmt.Sprintf(\"%07x\", rand.Int())[0:7]\n\t\tif err = ioutil.WriteFile(filepath.Join(s.path, \"name\"), []byte(s.name), 0644); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\treturn s\n}\n\nfunc (s *RaftServer) leaderConnectString() (string, bool) {\n\tleader := s.raftServer.Leader()\n\tpeers := s.raftServer.Peers()\n\tif peer, ok := peers[leader]; !ok {\n\t\treturn \"\", false\n\t} else {\n\t\treturn peer.ConnectionString, true\n\t}\n}\n\nfunc (s *RaftServer) doOrProxyCommand(command raft.Command, commandType string) (interface{}, error) {\n\tif s.raftServer.State() == raft.Leader {\n\t\tvalue, err := s.raftServer.Do(command)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Cannot run command %#v. %s\", command, err)\n\t\t}\n\t\treturn value, err\n\t} else {\n\t\tif leader, ok := s.leaderConnectString(); !ok {\n\t\t\treturn nil, errors.New(\"Couldn't connect to the cluster leader...\")\n\t\t} else {\n\t\t\tvar b bytes.Buffer\n\t\t\tjson.NewEncoder(&b).Encode(command)\n\t\t\tresp, err := http.Post(leader+\"\/process_command\/\"+commandType, \"application\/json\", &b)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tbody, err2 := ioutil.ReadAll(resp.Body)\n\n\t\t\tif resp.StatusCode != 200 {\n\t\t\t\treturn nil, errors.New(strings.TrimSpace(string(body)))\n\t\t\t}\n\n\t\t\tvar js interface{}\n\t\t\tjson.Unmarshal(body, &js)\n\t\t\treturn js, err2\n\t\t}\n\t}\n\treturn nil, nil\n}\n\nfunc (s *RaftServer) CreateDatabase(name string, replicationFactor uint8) error {\n\tif replicationFactor == 0 {\n\t\treplicationFactor = 1\n\t}\n\tcommand := NewCreateDatabaseCommand(name, replicationFactor)\n\t_, err := s.doOrProxyCommand(command, \"create_db\")\n\treturn err\n}\n\nfunc (s *RaftServer) DropDatabase(name string) error {\n\tcommand := NewDropDatabaseCommand(name)\n\t_, err := s.doOrProxyCommand(command, \"drop_db\")\n\treturn err\n}\n\nfunc (s *RaftServer) SaveDbUser(u *dbUser) error {\n\tcommand := NewSaveDbUserCommand(u)\n\t_, err := s.doOrProxyCommand(command, \"save_db_user\")\n\treturn err\n}\n\nfunc (s *RaftServer) ChangeDbUserPassword(db, username string, hash []byte) error {\n\tcommand := NewChangeDbUserPasswordCommand(db, username, string(hash))\n\t_, err := s.doOrProxyCommand(command, \"change_db_user_password\")\n\treturn err\n}\n\nfunc (s *RaftServer) SaveClusterAdminUser(u *clusterAdmin) error {\n\tcommand := NewSaveClusterAdminCommand(u)\n\t_, err := s.doOrProxyCommand(command, \"save_cluster_admin_user\")\n\treturn err\n}\n\nfunc (s *RaftServer) CreateRootUser() error {\n\tu := &clusterAdmin{CommonUser{\"root\", \"\", false}}\n\thash, _ := hashPassword(DEFAULT_ROOT_PWD)\n\tu.changePassword(string(hash))\n\treturn s.SaveClusterAdminUser(u)\n}\n\nfunc (s *RaftServer) ActivateServer(server *ClusterServer) error {\n\treturn errors.New(\"not implemented\")\n}\n\nfunc (s *RaftServer) AddServer(server *ClusterServer, insertIndex int) error {\n\treturn errors.New(\"not implemented\")\n}\n\nfunc (s *RaftServer) MovePotentialServer(server *ClusterServer, insertIndex int) error {\n\treturn errors.New(\"not implemented\")\n}\n\nfunc (s *RaftServer) ReplaceServer(oldServer *ClusterServer, replacement *ClusterServer) error {\n\treturn errors.New(\"not implemented\")\n}\n\nfunc (s *RaftServer) connectionString() string {\n\treturn fmt.Sprintf(\"http:\/\/%s:%d\", s.host, s.port)\n}\n\nfunc (s *RaftServer) startRaft() error {\n\tlog.Info(\"Initializing Raft Server: %s %d\", s.path, s.port)\n\n\t\/\/ Initialize and start Raft server.\n\ttransporter := raft.NewHTTPTransporter(\"\/raft\")\n\tvar err error\n\ts.raftServer, err = raft.NewServer(s.name, s.path, transporter, nil, s.clusterConfig, \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttransporter.Install(s.raftServer, s)\n\ts.raftServer.Start()\n\n\tif !s.raftServer.IsLogEmpty() {\n\t\tlog.Info(\"Recovered from log\")\n\t\treturn nil\n\t}\n\n\tpotentialLeaders := s.config.SeedServers\n\n\tif len(potentialLeaders) == 0 {\n\t\tlog.Info(\"Starting as new Raft leader...\")\n\t\tname := s.raftServer.Name()\n\t\tconnectionString := s.connectionString()\n\t\t_, err := s.raftServer.Do(&InfluxJoinCommand{\n\t\t\tName:                     name,\n\t\t\tConnectionString:         connectionString,\n\t\t\tProtobufConnectionString: s.config.ProtobufConnectionString(),\n\t\t})\n\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\n\t\tcommand := NewAddPotentialServerCommand(&ClusterServer{\n\t\t\tRaftName:                 name,\n\t\t\tRaftConnectionString:     connectionString,\n\t\t\tProtobufConnectionString: s.config.ProtobufConnectionString(),\n\t\t})\n\t\t_, err = s.doOrProxyCommand(command, \"add_server\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = s.CreateRootUser()\n\t\treturn err\n\t}\n\n\tfor {\n\t\tfor _, leader := range potentialLeaders {\n\t\t\tlog.Info(\"(raft:%s) Attempting to join leader: %s\", s.raftServer.Name(), leader)\n\n\t\t\tif err := s.Join(leader); err == nil {\n\t\t\t\tlog.Info(\"Joined: %s\", leader)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tlog.Warn(\"Couldn't join any of the seeds, sleeping and retrying...\")\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\treturn nil\n}\n\nfunc (s *RaftServer) ListenAndServe() error {\n\tl, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", s.port))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s.Serve(l)\n}\n\nfunc (s *RaftServer) Serve(l net.Listener) error {\n\ts.port = l.Addr().(*net.TCPAddr).Port\n\ts.listener = l\n\n\tlog.Info(\"Initializing Raft HTTP server\")\n\n\t\/\/ Initialize and start HTTP server.\n\ts.httpServer = &http.Server{\n\t\tHandler: s.router,\n\t}\n\n\ts.router.HandleFunc(\"\/cluster_config\", s.configHandler).Methods(\"GET\")\n\ts.router.HandleFunc(\"\/join\", s.joinHandler).Methods(\"POST\")\n\ts.router.HandleFunc(\"\/process_command\/{command_type}\", s.processCommandHandler).Methods(\"POST\")\n\n\tlog.Info(\"Raft Server Listening at %s\", s.connectionString())\n\n\tgo func() {\n\t\ts.httpServer.Serve(l)\n\t}()\n\tstarted := make(chan error)\n\tgo func() {\n\t\tstarted <- s.startRaft()\n\t}()\n\terr := <-started\n\t\/\/\ttime.Sleep(3 * time.Second)\n\treturn err\n}\n\nfunc (self *RaftServer) Close() {\n\tif !self.closing || self.raftServer == nil {\n\t\tself.closing = true\n\t\tself.raftServer.Stop()\n\t\tself.listener.Close()\n\t}\n}\n\n\/\/ This is a hack around Gorilla mux not providing the correct net\/http\n\/\/ HandleFunc() interface.\nfunc (s *RaftServer) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {\n\ts.router.HandleFunc(pattern, handler)\n}\n\n\/\/ Joins to the leader of an existing cluster.\nfunc (s *RaftServer) Join(leader string) error {\n\tcommand := &InfluxJoinCommand{\n\t\tName:                     s.raftServer.Name(),\n\t\tConnectionString:         s.connectionString(),\n\t\tProtobufConnectionString: s.config.ProtobufConnectionString(),\n\t}\n\tconnectUrl := leader\n\tif !strings.HasPrefix(connectUrl, \"http:\/\/\") {\n\t\tconnectUrl = \"http:\/\/\" + connectUrl\n\t}\n\tif !strings.HasSuffix(connectUrl, \"\/join\") {\n\t\tconnectUrl = connectUrl + \"\/join\"\n\t}\n\n\tvar b bytes.Buffer\n\tjson.NewEncoder(&b).Encode(command)\n\tresp, err := http.Post(connectUrl, \"application\/json\", &b)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode == http.StatusTemporaryRedirect {\n\t\taddress := resp.Header.Get(\"Location\")\n\t\tlog.Debug(\"Redirected to %s to join leader\\n\", address)\n\t\treturn s.Join(address)\n\t}\n\n\treturn nil\n}\n\nfunc (s *RaftServer) retryCommand(command raft.Command, retries int) (ret interface{}, err error) {\n\tfor retries = retries; retries > 0; retries-- {\n\t\tret, err = s.raftServer.Do(command)\n\t\tif err == nil {\n\t\t\treturn ret, nil\n\t\t}\n\t\ttime.Sleep(50 * time.Millisecond)\n\t\tfmt.Println(\"Retrying RAFT command...\")\n\t}\n\treturn\n}\n\nfunc (s *RaftServer) joinHandler(w http.ResponseWriter, req *http.Request) {\n\tif s.raftServer.State() == raft.Leader {\n\t\tcommand := &InfluxJoinCommand{}\n\t\tif err := json.NewDecoder(req.Body).Decode(&command); err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\t\/\/ during the test suite the join command will sometimes time out.. just retry a few times\n\t\tif _, err := s.raftServer.Do(command); err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tserver := s.clusterConfig.GetServerByRaftName(command.Name)\n\t\t\/\/ it's a new server the cluster has never seen, make it a potential\n\t\tif server == nil {\n\t\t\taddServer := NewAddPotentialServerCommand(&ClusterServer{RaftName: command.Name, RaftConnectionString: command.ConnectionString, ProtobufConnectionString: command.ProtobufConnectionString})\n\t\t\tif _, err := s.raftServer.Do(addServer); err != nil {\n\t\t\t\tlog.Error(\"Error joining raft server: \", err, command)\n\t\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif leader, ok := s.leaderConnectString(); ok {\n\t\t\tlog.Debug(\"redirecting to leader to join...\")\n\t\t\thttp.Redirect(w, req, leader+\"\/join\", http.StatusTemporaryRedirect)\n\t\t} else {\n\t\t\thttp.Error(w, errors.New(\"Couldn't find leader of the cluster to join\").Error(), http.StatusInternalServerError)\n\t\t}\n\t}\n}\n\nfunc (s *RaftServer) configHandler(w http.ResponseWriter, req *http.Request) {\n\tjsonObject := make(map[string]interface{})\n\tdbs := make([]string, 0)\n\tfor db, _ := range s.clusterConfig.databaseReplicationFactors {\n\t\tdbs = append(dbs, db)\n\t}\n\tjsonObject[\"databases\"] = dbs\n\tjsonObject[\"cluster_admins\"] = s.clusterConfig.clusterAdmins\n\tjsonObject[\"database_users\"] = s.clusterConfig.dbUsers\n\tjs, err := json.Marshal(jsonObject)\n\tif err != nil {\n\t\tlog.Error(\"ERROR marshalling config: \", err)\n\t}\n\tw.Write(js)\n}\n\nfunc (s *RaftServer) marshalAndDoCommandFromBody(command raft.Command, req *http.Request) (interface{}, error) {\n\tif err := json.NewDecoder(req.Body).Decode(&command); err != nil {\n\t\treturn nil, err\n\t}\n\tif result, err := s.raftServer.Do(command); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\treturn result, nil\n\t}\n}\n\nfunc (s *RaftServer) processCommandHandler(w http.ResponseWriter, req *http.Request) {\n\tvars := mux.Vars(req)\n\tvalue := vars[\"command_type\"]\n\tcommand := internalRaftCommands[value]\n\n\tif result, err := s.marshalAndDoCommandFromBody(command, req); err != nil {\n\t\tlog.Error(\"command %T failed: %s\", command, err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t} else {\n\t\tif result != nil {\n\t\t\tjs, _ := json.Marshal(result)\n\t\t\tw.Write(js)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package compiler\n\nimport (\n\t\"bytecode\"\n\t\"bytecode\/eval\"\n\t\"bytecode\/ir\"\n\t\"dt\"\n\t\"fmt\"\n\t\"go\/types\"\n\t\"lisp\"\n\t\"sexp\"\n\t\"tu\"\n)\n\n\/\/ These operations have opcode for 2 operands.\n\/\/ For 2+ operands ordinary function call is used.\nvar opNames = [...]lisp.Symbol{\n\tir.OpNumAdd: \"+\",\n\tir.OpNumSub: \"-\",\n\tir.OpNumMul: \"*\",\n\tir.OpNumQuo: \"\/\",\n\tir.OpNumGt:  \">\",\n\tir.OpNumLt:  \"<\",\n\tir.OpNumEq:  \"=\",\n}\n\n\/\/ #FIXME: either make compiler object reusable,\n\/\/ or make it private type and expose Compile as a\n\/\/ free standing function.\n\n\/\/ Compiler converts Sexp forms into bytecode objects.\ntype Compiler struct {\n\tcode      *code\n\tconstPool dt.ConstPool\n\tsymPool   dt.SymbolPool\n}\n\nfunc New() *Compiler {\n\treturn &Compiler{\n\t\tcode: newCode(),\n\t}\n}\n\nfunc (cl *Compiler) CompileFunc(f *tu.Func) *bytecode.Func {\n\tfor _, param := range f.Params {\n\t\tcl.symPool.Insert(param)\n\t}\n\n\tcl.compileStmtList(f.Body)\n\n\tobject := cl.createObject()\n\teval.Object(&object, len(f.Params))\n\tcl.ensureTrailingReturn()\n\n\treturn &bytecode.Func{\n\t\tObject:   object,\n\t\tArgsDesc: argsDescriptor(len(f.Params), f.Variadic),\n\t}\n}\n\n\/\/ Insert trailing \"return\" opcode if its not already there.\nfunc (cl *Compiler) ensureTrailingReturn() {\n\tlastInstr := cl.code.lastInstr()\n\n\tif lastInstr.Op != ir.OpReturn {\n\t\t\/\/ Check is needed to avoid generation of \"dead\" return.\n\t\tif lastInstr.Op != ir.OpPanic {\n\t\t\tcl.emit(ir.Return)\n\t\t}\n\t}\n}\n\nfunc (cl *Compiler) compileStmt(form sexp.Form) {\n\tswitch form := form.(type) {\n\tcase *sexp.Return:\n\t\tcl.compileReturn(form)\n\tcase *sexp.If:\n\t\tcl.compileIf(form)\n\tcase *sexp.Block:\n\t\tcl.compileBlock(form)\n\tcase *sexp.FormList:\n\t\tcl.compileStmtList(form.Forms)\n\tcase *sexp.Bind:\n\t\tcl.compileBind(form)\n\tcase *sexp.Rebind:\n\t\tcl.compileRebind(form)\n\tcase *sexp.MapSet:\n\t\tcl.compileMapSet(form)\n\tcase sexp.ExprStmt:\n\t\tcl.compileExprStmt(form.Form)\n\tcase *sexp.Panic:\n\t\tcl.compilePanic(form.ErrorData)\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unexpected stmt: %#v\\n\", form))\n\t}\n}\n\nfunc (cl *Compiler) compileExpr(form sexp.Form) {\n\tswitch form := form.(type) {\n\tcase *sexp.NumAdd:\n\t\tcl.compileAddSub(ir.OpNumAdd, form.Args)\n\tcase *sexp.NumSub:\n\t\tcl.compileAddSub(ir.OpNumSub, form.Args)\n\tcase *sexp.NumMul:\n\t\tcl.compileOp(ir.OpNumMul, form.Args)\n\tcase *sexp.NumQuo:\n\t\tcl.compileOp(ir.OpNumQuo, form.Args)\n\tcase *sexp.NumGt:\n\t\tcl.compileOp(ir.OpNumGt, form.Args)\n\tcase *sexp.NumLt:\n\t\tcl.compileOp(ir.OpNumLt, form.Args)\n\tcase *sexp.NumEq:\n\t\tcl.compileOp(ir.OpNumEq, form.Args)\n\tcase *sexp.Concat:\n\t\tcl.compileConcat(form)\n\n\tcase sexp.Int:\n\t\tcl.emitConst(cl.constPool.InsertInt(form.Val))\n\tcase sexp.Float:\n\t\tcl.emitConst(cl.constPool.InsertFloat(form.Val))\n\tcase sexp.String:\n\t\tcl.emitConst(cl.constPool.InsertString(form.Val))\n\tcase sexp.Symbol:\n\t\tcl.emitConst(cl.constPool.InsertSym(lisp.Symbol(form.Val)))\n\tcase sexp.Bool:\n\t\tcl.compileBool(form)\n\n\tcase sexp.Var:\n\t\tcl.compileVar(form)\n\n\tcase *sexp.Call:\n\t\tcl.compileCall(lisp.Symbol(form.Fn), form.Args...)\n\n\tcase sexp.MakeMap:\n\t\tcl.compileMakeMap(form)\n\n\tcase *sexp.TypeAssert:\n\t\tcl.compileTypeAssert(form)\n\tcase *sexp.LispTypeAssert:\n\t\tcl.compileLispTypeAssert(form)\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unexpected expr: %#v\\n\", form))\n\t}\n}\n\nfunc (cl *Compiler) compileOp(op ir.Opcode, args []sexp.Form) {\n\tif len(args) == 2 {\n\t\tcl.compileExprList(args)\n\t\tcl.emit(ir.Instr{Op: op})\n\t} else {\n\t\tcl.compileCall(opNames[op], args...)\n\t}\n}\n\nfunc (cl *Compiler) compileCall(fn lisp.Symbol, args ...sexp.Form) {\n\tif !optCall(cl, fn, args) {\n\t\tcl.emitConst(cl.constPool.InsertSym(fn))\n\t\tcl.compileExprList(args)\n\t\tcl.emit(ir.Call(len(args)))\n\t}\n}\n\nfunc (cl *Compiler) compileReturn(form *sexp.Return) {\n\tswitch len(form.Results) {\n\tcase 0:\n\t\tcl.emit(ir.Return)\n\tcase 1:\n\t\tcl.compileExpr(form.Results[0])\n\t\tcl.emit(ir.Return)\n\n\tdefault:\n\t\tpanic(\"unimplemented\") \/\/ #REFS: 1.\n\t}\n}\n\nfunc (cl *Compiler) compileIf(form *sexp.If) {\n\tcl.compileExpr(form.Test)\n\tlabel := cl.emitJmp(ir.OpJmpNil, \"then\")\n\tcl.compileStmtList(form.Then.Forms)\n\tlabel.bind(\"else\")\n\tif form.Else != nil {\n\t\tcl.compileStmt(form.Else)\n\t}\n}\n\nfunc (cl *Compiler) compileBlock(form *sexp.Block) {\n\tcl.compileStmtList(form.Forms)\n\tcl.symPool.Drop(form.Scope.Len())\n\tcl.emit(ir.Instr{Op: ir.OpScopeExit, Data: uint16(form.Scope.Len())})\n}\n\nfunc (cl *Compiler) compileBind(form *sexp.Bind) {\n\tcl.compileExpr(form.Init)\n\tid := cl.symPool.Insert(form.Name)\n\tcl.emit(ir.LocalBind(id))\n}\n\nfunc (cl *Compiler) compileRebind(form *sexp.Rebind) {\n\tcl.compileExpr(form.Expr)\n\tid := cl.symPool.Find(form.Name)\n\tcl.emit(ir.LocalSet(id))\n}\n\nfunc (cl *Compiler) compileMakeMap(form sexp.MakeMap) {\n\tcl.compileCall(\n\t\t\"make-hash-table\",\n\t\tsym(\":size\"), form.SizeHint,\n\t\tsym(\":test\"), sym(\"equal\"),\n\t)\n}\n\nfunc (cl *Compiler) compileMapSet(form *sexp.MapSet) {\n\tcl.compileCall(\"puthash\", form.Key, form.Val, form.Map)\n\tcl.emit(ir.Drop(1)) \/\/ Discard expression result.\n}\n\nfunc (cl *Compiler) compilePanic(errorData sexp.Form) {\n\tcl.emitConst(cl.constPool.InsertSym(\"Go--panic\"))\n\tcl.compileExpr(errorData)\n\tcl.emit(ir.Panic)\n\tcl.code.pushBlock(\"panic\")\n}\n\nfunc (cl *Compiler) compileVar(form sexp.Var) {\n\t\/\/ #FIXME: it could be a global var.\n\tid := cl.symPool.Find(form.Name)\n\tcl.code.pushInstr(ir.LocalRef(id))\n}\n\nfunc (cl *Compiler) compileTypeAssert(form *sexp.TypeAssert) {\n\tpanic(\"unimplemented\")\n}\n\nfunc (cl *Compiler) compileLispTypeAssert(form *sexp.LispTypeAssert) {\n\tif types.Identical(lisp.Types.Bool, form.Type) {\n\t\treturn\n\t}\n\n\tvar checker ir.Instr\n\tvar blamer lisp.Symbol\n\tif types.Identical(lisp.Types.Int, form.Type) {\n\t\tchecker = ir.IsInt\n\t\tblamer = \"Go--!object-int\"\n\t} else if types.Identical(lisp.Types.String, form.Type) {\n\t\tchecker = ir.IsString\n\t\tblamer = \"Go--!object-string\"\n\t} else if types.Identical(lisp.Types.Symbol, form.Type) {\n\t\tchecker = ir.IsSymbol\n\t\tblamer = \"Go--!object-symbol\"\n\t} else {\n\t\tpanic(\"unimplemented\")\n\t}\n\n\tcl.compileExpr(form.Expr) \/\/ Arg to assert.\n\tcl.emit(ir.StackRef(0))   \/\/ Preserve arg (dup).\n\tcl.emit(checker)          \/\/ Type check.\n\tlabel := cl.emitJmp(ir.OpJmpNotNil, \"lisp-type-assert-fail\")\n\t{\n\t\tcl.emitConst(cl.constPool.InsertSym(blamer))\n\t\tcl.emit(ir.StackRef(1)) \/\/ Value that failed assertion.\n\t\tcl.emit(ir.NoreturnCall(1))\n\t}\n\tlabel.bind(\"lisp-type-assert-pass\")\n}\n\nfunc (cl *Compiler) compileConcat(form *sexp.Concat) {\n\tcl.compileExprList(form.Args)\n\tcl.emit(ir.Concat(len(form.Args)))\n}\n\nfunc (cl *Compiler) compileAddSub(op ir.Opcode, args []sexp.Form) {\n\tif !optAddSub(cl, op, args) {\n\t\tcl.compileOp(op, args)\n\t}\n}\n\nfunc (cl *Compiler) compileBool(form sexp.Bool) {\n\tif form.Val {\n\t\tcl.emitConst(cl.constPool.InsertSym(\"t\"))\n\t} else {\n\t\tcl.emitConst(cl.constPool.InsertSym(\"nil\"))\n\t}\n}\n\nfunc (cl *Compiler) compileExprStmt(form sexp.Form) {\n\tcl.compileExpr(form)\n\tcl.emit(ir.Drop(1)) \/\/ Discard expression result.\n}\n\nfunc (cl *Compiler) compileInstr(instr ir.Instr, argc int, args []sexp.Form) {\n\tif len(args) != argc {\n\t\t\/\/ #FIXME: need better error handling here.\n\t\tpanic(fmt.Sprintf(\"%s expected %d args, got %d\",\n\t\t\tinstr.Op, argc, len(args)))\n\t}\n\tcl.compileExprList(args)\n\tcl.emit(instr)\n}\n\nfunc (cl *Compiler) compileStmtList(forms []sexp.Form) {\n\tfor _, form := range forms {\n\t\tcl.compileStmt(form)\n\t}\n}\n\nfunc (cl *Compiler) compileExprList(forms []sexp.Form) {\n\tfor _, form := range forms {\n\t\tcl.compileExpr(form)\n\t}\n}\n\nfunc (cl *Compiler) emit(instr ir.Instr) {\n\tcl.code.pushInstr(instr)\n}\n\nfunc (cl *Compiler) emitConst(cpIndex int) {\n\tcl.emit(ir.ConstRef(cpIndex))\n}\n\nfunc (cl *Compiler) emitJmp(op ir.Opcode, branchName string) jmpLabel {\n\tlabel := cl.code.pushJmp(op)\n\tcl.code.pushBlock(branchName)\n\treturn label\n}\n\nfunc (cl *Compiler) pushBlock(name string) {\n\tcl.code.pushBlock(name)\n}\n\nfunc (cl *Compiler) createObject() bytecode.Object {\n\treturn bytecode.Object{\n\t\tBlocks:    cl.code.blocks,\n\t\tConstPool: cl.constPool,\n\t\tLocals:    cl.symPool.Symbols(),\n\t}\n}\n<commit_msg>lisp type assertion for floats<commit_after>package compiler\n\nimport (\n\t\"bytecode\"\n\t\"bytecode\/eval\"\n\t\"bytecode\/ir\"\n\t\"dt\"\n\t\"fmt\"\n\t\"go\/types\"\n\t\"lisp\"\n\t\"sexp\"\n\t\"tu\"\n)\n\n\/\/ These operations have opcode for 2 operands.\n\/\/ For 2+ operands ordinary function call is used.\nvar opNames = [...]lisp.Symbol{\n\tir.OpNumAdd: \"+\",\n\tir.OpNumSub: \"-\",\n\tir.OpNumMul: \"*\",\n\tir.OpNumQuo: \"\/\",\n\tir.OpNumGt:  \">\",\n\tir.OpNumLt:  \"<\",\n\tir.OpNumEq:  \"=\",\n}\n\n\/\/ #FIXME: either make compiler object reusable,\n\/\/ or make it private type and expose Compile as a\n\/\/ free standing function.\n\n\/\/ Compiler converts Sexp forms into bytecode objects.\ntype Compiler struct {\n\tcode      *code\n\tconstPool dt.ConstPool\n\tsymPool   dt.SymbolPool\n}\n\nfunc New() *Compiler {\n\treturn &Compiler{\n\t\tcode: newCode(),\n\t}\n}\n\nfunc (cl *Compiler) CompileFunc(f *tu.Func) *bytecode.Func {\n\tfor _, param := range f.Params {\n\t\tcl.symPool.Insert(param)\n\t}\n\n\tcl.compileStmtList(f.Body)\n\n\tobject := cl.createObject()\n\teval.Object(&object, len(f.Params))\n\tcl.ensureTrailingReturn()\n\n\treturn &bytecode.Func{\n\t\tObject:   object,\n\t\tArgsDesc: argsDescriptor(len(f.Params), f.Variadic),\n\t}\n}\n\n\/\/ Insert trailing \"return\" opcode if its not already there.\nfunc (cl *Compiler) ensureTrailingReturn() {\n\tlastInstr := cl.code.lastInstr()\n\n\tif lastInstr.Op != ir.OpReturn {\n\t\t\/\/ Check is needed to avoid generation of \"dead\" return.\n\t\tif lastInstr.Op != ir.OpPanic {\n\t\t\tcl.emit(ir.Return)\n\t\t}\n\t}\n}\n\nfunc (cl *Compiler) compileStmt(form sexp.Form) {\n\tswitch form := form.(type) {\n\tcase *sexp.Return:\n\t\tcl.compileReturn(form)\n\tcase *sexp.If:\n\t\tcl.compileIf(form)\n\tcase *sexp.Block:\n\t\tcl.compileBlock(form)\n\tcase *sexp.FormList:\n\t\tcl.compileStmtList(form.Forms)\n\tcase *sexp.Bind:\n\t\tcl.compileBind(form)\n\tcase *sexp.Rebind:\n\t\tcl.compileRebind(form)\n\tcase *sexp.MapSet:\n\t\tcl.compileMapSet(form)\n\tcase sexp.ExprStmt:\n\t\tcl.compileExprStmt(form.Form)\n\tcase *sexp.Panic:\n\t\tcl.compilePanic(form.ErrorData)\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unexpected stmt: %#v\\n\", form))\n\t}\n}\n\nfunc (cl *Compiler) compileExpr(form sexp.Form) {\n\tswitch form := form.(type) {\n\tcase *sexp.NumAdd:\n\t\tcl.compileAddSub(ir.OpNumAdd, form.Args)\n\tcase *sexp.NumSub:\n\t\tcl.compileAddSub(ir.OpNumSub, form.Args)\n\tcase *sexp.NumMul:\n\t\tcl.compileOp(ir.OpNumMul, form.Args)\n\tcase *sexp.NumQuo:\n\t\tcl.compileOp(ir.OpNumQuo, form.Args)\n\tcase *sexp.NumGt:\n\t\tcl.compileOp(ir.OpNumGt, form.Args)\n\tcase *sexp.NumLt:\n\t\tcl.compileOp(ir.OpNumLt, form.Args)\n\tcase *sexp.NumEq:\n\t\tcl.compileOp(ir.OpNumEq, form.Args)\n\tcase *sexp.Concat:\n\t\tcl.compileConcat(form)\n\n\tcase sexp.Int:\n\t\tcl.emitConst(cl.constPool.InsertInt(form.Val))\n\tcase sexp.Float:\n\t\tcl.emitConst(cl.constPool.InsertFloat(form.Val))\n\tcase sexp.String:\n\t\tcl.emitConst(cl.constPool.InsertString(form.Val))\n\tcase sexp.Symbol:\n\t\tcl.emitConst(cl.constPool.InsertSym(lisp.Symbol(form.Val)))\n\tcase sexp.Bool:\n\t\tcl.compileBool(form)\n\n\tcase sexp.Var:\n\t\tcl.compileVar(form)\n\n\tcase *sexp.Call:\n\t\tcl.compileCall(lisp.Symbol(form.Fn), form.Args...)\n\n\tcase sexp.MakeMap:\n\t\tcl.compileMakeMap(form)\n\n\tcase *sexp.TypeAssert:\n\t\tcl.compileTypeAssert(form)\n\tcase *sexp.LispTypeAssert:\n\t\tcl.compileLispTypeAssert(form)\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unexpected expr: %#v\\n\", form))\n\t}\n}\n\nfunc (cl *Compiler) compileOp(op ir.Opcode, args []sexp.Form) {\n\tif len(args) == 2 {\n\t\tcl.compileExprList(args)\n\t\tcl.emit(ir.Instr{Op: op})\n\t} else {\n\t\tcl.compileCall(opNames[op], args...)\n\t}\n}\n\nfunc (cl *Compiler) compileCall(fn lisp.Symbol, args ...sexp.Form) {\n\tif !optCall(cl, fn, args) {\n\t\tcl.emitConst(cl.constPool.InsertSym(fn))\n\t\tcl.compileExprList(args)\n\t\tcl.emit(ir.Call(len(args)))\n\t}\n}\n\nfunc (cl *Compiler) compileReturn(form *sexp.Return) {\n\tswitch len(form.Results) {\n\tcase 0:\n\t\tcl.emit(ir.Return)\n\tcase 1:\n\t\tcl.compileExpr(form.Results[0])\n\t\tcl.emit(ir.Return)\n\n\tdefault:\n\t\tpanic(\"unimplemented\") \/\/ #REFS: 1.\n\t}\n}\n\nfunc (cl *Compiler) compileIf(form *sexp.If) {\n\tcl.compileExpr(form.Test)\n\tlabel := cl.emitJmp(ir.OpJmpNil, \"then\")\n\tcl.compileStmtList(form.Then.Forms)\n\tlabel.bind(\"else\")\n\tif form.Else != nil {\n\t\tcl.compileStmt(form.Else)\n\t}\n}\n\nfunc (cl *Compiler) compileBlock(form *sexp.Block) {\n\tcl.compileStmtList(form.Forms)\n\tcl.symPool.Drop(form.Scope.Len())\n\tcl.emit(ir.Instr{Op: ir.OpScopeExit, Data: uint16(form.Scope.Len())})\n}\n\nfunc (cl *Compiler) compileBind(form *sexp.Bind) {\n\tcl.compileExpr(form.Init)\n\tid := cl.symPool.Insert(form.Name)\n\tcl.emit(ir.LocalBind(id))\n}\n\nfunc (cl *Compiler) compileRebind(form *sexp.Rebind) {\n\tcl.compileExpr(form.Expr)\n\tid := cl.symPool.Find(form.Name)\n\tcl.emit(ir.LocalSet(id))\n}\n\nfunc (cl *Compiler) compileMakeMap(form sexp.MakeMap) {\n\tcl.compileCall(\n\t\t\"make-hash-table\",\n\t\tsym(\":size\"), form.SizeHint,\n\t\tsym(\":test\"), sym(\"equal\"),\n\t)\n}\n\nfunc (cl *Compiler) compileMapSet(form *sexp.MapSet) {\n\tcl.compileCall(\"puthash\", form.Key, form.Val, form.Map)\n\tcl.emit(ir.Drop(1)) \/\/ Discard expression result.\n}\n\nfunc (cl *Compiler) compilePanic(errorData sexp.Form) {\n\tcl.emitConst(cl.constPool.InsertSym(\"Go--panic\"))\n\tcl.compileExpr(errorData)\n\tcl.emit(ir.Panic)\n\tcl.code.pushBlock(\"panic\")\n}\n\nfunc (cl *Compiler) compileVar(form sexp.Var) {\n\t\/\/ #FIXME: it could be a global var.\n\tid := cl.symPool.Find(form.Name)\n\tcl.code.pushInstr(ir.LocalRef(id))\n}\n\nfunc (cl *Compiler) compileTypeAssert(form *sexp.TypeAssert) {\n\tpanic(\"unimplemented\")\n}\n\nfunc (cl *Compiler) compileLispTypeAssert(form *sexp.LispTypeAssert) {\n\t\/\/ Bool type needs no assertion at all.\n\tif types.Identical(lisp.Types.Bool, form.Type) {\n\t\treturn\n\t}\n\n\tvar blamer lisp.Symbol \/\/ Panic trigger\n\n\tcl.compileExpr(form.Expr) \/\/ Arg to assert.\n\n\tif types.Identical(lisp.Types.Float, form.Type) {\n\t\t\/\/ For floats we do not have floatp opcode.\n\t\tcl.emitConst(cl.constPool.InsertSym(\"floatp\"))\n\t\tcl.emit(ir.StackRef(1)) \/\/ Preserve arg (dup).\n\t\tcl.emit(ir.Call(1))\n\t\tblamer = \"Go--!object-float\"\n\t} else {\n\t\tvar checker ir.Instr\n\t\tif types.Identical(lisp.Types.Int, form.Type) {\n\t\t\tchecker = ir.IsInt\n\t\t\tblamer = \"Go--!object-int\"\n\t\t} else if types.Identical(lisp.Types.String, form.Type) {\n\t\t\tchecker = ir.IsString\n\t\t\tblamer = \"Go--!object-string\"\n\t\t} else if types.Identical(lisp.Types.Symbol, form.Type) {\n\t\t\tchecker = ir.IsSymbol\n\t\t\tblamer = \"Go--!object-symbol\"\n\t\t} else {\n\t\t\tpanic(\"unimplemented\")\n\t\t}\n\n\t\tcl.emit(ir.StackRef(0)) \/\/ Preserve arg (dup).\n\t\tcl.emit(checker)        \/\/ Type check.\n\t}\n\n\tlabel := cl.emitJmp(ir.OpJmpNotNil, \"lisp-type-assert-fail\")\n\t{\n\t\tcl.emitConst(cl.constPool.InsertSym(blamer))\n\t\tcl.emit(ir.StackRef(1)) \/\/ Value that failed assertion.\n\t\tcl.emit(ir.NoreturnCall(1))\n\t}\n\tlabel.bind(\"lisp-type-assert-pass\")\n}\n\nfunc (cl *Compiler) compileConcat(form *sexp.Concat) {\n\tcl.compileExprList(form.Args)\n\tcl.emit(ir.Concat(len(form.Args)))\n}\n\nfunc (cl *Compiler) compileAddSub(op ir.Opcode, args []sexp.Form) {\n\tif !optAddSub(cl, op, args) {\n\t\tcl.compileOp(op, args)\n\t}\n}\n\nfunc (cl *Compiler) compileBool(form sexp.Bool) {\n\tif form.Val {\n\t\tcl.emitConst(cl.constPool.InsertSym(\"t\"))\n\t} else {\n\t\tcl.emitConst(cl.constPool.InsertSym(\"nil\"))\n\t}\n}\n\nfunc (cl *Compiler) compileExprStmt(form sexp.Form) {\n\tcl.compileExpr(form)\n\tcl.emit(ir.Drop(1)) \/\/ Discard expression result.\n}\n\nfunc (cl *Compiler) compileInstr(instr ir.Instr, argc int, args []sexp.Form) {\n\tif len(args) != argc {\n\t\t\/\/ #FIXME: need better error handling here.\n\t\tpanic(fmt.Sprintf(\"%s expected %d args, got %d\",\n\t\t\tinstr.Op, argc, len(args)))\n\t}\n\tcl.compileExprList(args)\n\tcl.emit(instr)\n}\n\nfunc (cl *Compiler) compileStmtList(forms []sexp.Form) {\n\tfor _, form := range forms {\n\t\tcl.compileStmt(form)\n\t}\n}\n\nfunc (cl *Compiler) compileExprList(forms []sexp.Form) {\n\tfor _, form := range forms {\n\t\tcl.compileExpr(form)\n\t}\n}\n\nfunc (cl *Compiler) emit(instr ir.Instr) {\n\tcl.code.pushInstr(instr)\n}\n\nfunc (cl *Compiler) emitConst(cpIndex int) {\n\tcl.emit(ir.ConstRef(cpIndex))\n}\n\nfunc (cl *Compiler) emitJmp(op ir.Opcode, branchName string) jmpLabel {\n\tlabel := cl.code.pushJmp(op)\n\tcl.code.pushBlock(branchName)\n\treturn label\n}\n\nfunc (cl *Compiler) pushBlock(name string) {\n\tcl.code.pushBlock(name)\n}\n\nfunc (cl *Compiler) createObject() bytecode.Object {\n\treturn bytecode.Object{\n\t\tBlocks:    cl.code.blocks,\n\t\tConstPool: cl.constPool,\n\t\tLocals:    cl.symPool.Symbols(),\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package isolation_segments\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t. \"github.com\/cloudfoundry\/cf-acceptance-tests\/cats_suite_helpers\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gbytes\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/cf\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/helpers\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/workflowhelpers\"\n\t\"github.com\/cloudfoundry\/cf-acceptance-tests\/helpers\/app_helpers\"\n\t\"github.com\/cloudfoundry\/cf-acceptance-tests\/helpers\/assets\"\n\t\"github.com\/cloudfoundry\/cf-acceptance-tests\/helpers\/config\"\n\t\"github.com\/cloudfoundry\/cf-acceptance-tests\/helpers\/random_name\"\n)\n\nconst (\n\tSHARED_ISOLATION_SEGMENT_GUID = \"933b4c58-120b-499a-b85d-4b6fc9e2903b\"\n\tbinaryHi                      = \"Hello from a binary\"\n)\n\nfunc entitleOrgToIsolationSegment(orgGuid, isoSegGuid string) {\n\tEventually(cf.Cf(\"curl\",\n\t\tfmt.Sprintf(\"\/v3\/isolation_segments\/%s\/relationships\/organizations\", isoSegGuid),\n\t\t\"-X\",\n\t\t\"POST\",\n\t\t\"-d\",\n\t\tfmt.Sprintf(`{\"data\":[{ \"guid\":\"%s\" }]}`, orgGuid)),\n\t\tConfig.DefaultTimeoutDuration()).Should(Exit(0))\n}\n\nfunc assignIsolationSegmentToSpace(spaceGuid, isoSegGuid string) {\n\tEventually(cf.Cf(\"curl\", fmt.Sprintf(\"\/v3\/spaces\/%s\/relationships\/isolation_segment\", spaceGuid),\n\t\t\"-X\",\n\t\t\"PATCH\",\n\t\t\"-d\",\n\t\tfmt.Sprintf(`{\"data\":{\"guid\":\"%s\"}}`, isoSegGuid)),\n\t\tConfig.DefaultTimeoutDuration()).Should(Exit(0))\n}\n\nfunc setDefaultIsolationSegment(orgGuid, isoSegGuid string) {\n\tEventually(cf.Cf(\"curl\",\n\t\tfmt.Sprintf(\"\/v3\/organizations\/%s\/relationships\/default_isolation_segment\", orgGuid),\n\t\t\"-X\",\n\t\t\"PATCH\",\n\t\t\"-d\",\n\t\tfmt.Sprintf(`{\"data\":{\"guid\":\"%s\"}}`, isoSegGuid)),\n\t\tConfig.DefaultTimeoutDuration()).Should(Exit(0))\n}\n\nfunc getGuid(response []byte) string {\n\ttype resource struct {\n\t\tGuid string `json:\"guid\"`\n\t}\n\tvar GetResponse struct {\n\t\tResources []resource `json:\"resources\"`\n\t}\n\n\terr := json.Unmarshal(response, &GetResponse)\n\tExpect(err).ToNot(HaveOccurred())\n\n\tif len(GetResponse.Resources) == 0 {\n\t\tFail(\"No guid found for response\")\n\t}\n\n\treturn GetResponse.Resources[0].Guid\n}\n\nfunc getIsolationSegmentGuid(name string) string {\n\tsession := cf.Cf(\"curl\", fmt.Sprintf(\"\/v3\/isolation_segments?names=%s\", name))\n\tbytes := session.Wait(Config.DefaultTimeoutDuration()).Out.Contents()\n\treturn getGuid(bytes)\n}\n\nfunc isolationSegmentExists(name string) bool {\n\tsession := cf.Cf(\"curl\", fmt.Sprintf(\"\/v3\/isolation_segments?names=%s\", name))\n\tbytes := session.Wait(Config.DefaultTimeoutDuration()).Out.Contents()\n\ttype resource struct {\n\t\tGuid string `json:\"guid\"`\n\t}\n\tvar GetResponse struct {\n\t\tResources []resource `json:\"resources\"`\n\t}\n\n\terr := json.Unmarshal(bytes, &GetResponse)\n\tExpect(err).ToNot(HaveOccurred())\n\treturn len(GetResponse.Resources) > 0\n}\n\nfunc createIsolationSegment(name string) string {\n\tsession := cf.Cf(\"curl\", \"\/v3\/isolation_segments\", \"-X\", \"POST\", \"-d\", fmt.Sprintf(`{\"name\":\"%s\"}`, name))\n\tbytes := session.Wait(Config.DefaultTimeoutDuration()).Out.Contents()\n\n\tvar isolation_segment struct {\n\t\tGuid string `json:\"guid\"`\n\t}\n\terr := json.Unmarshal(bytes, &isolation_segment)\n\tExpect(err).ToNot(HaveOccurred())\n\n\treturn isolation_segment.Guid\n}\n\nfunc deleteIsolationSegment(guid string) {\n\tEventually(cf.Cf(\"curl\", fmt.Sprintf(\"\/v3\/isolation_segments\/%s\", guid), \"-X\", \"DELETE\"), Config.DefaultTimeoutDuration()).Should(Exit(0))\n}\n\nfunc createOrGetIsolationSegment(name string) string {\n\tvar isoSegGuid string\n\tif isolationSegmentExists(name) {\n\t\tisoSegGuid = getIsolationSegmentGuid(name)\n\t} else {\n\t\tisoSegGuid = createIsolationSegment(name)\n\t}\n\treturn isoSegGuid\n}\n\nvar _ = IsolationSegmentsDescribe(\"IsolationSegments\", func() {\n\tvar orgGuid, orgName string\n\tvar spaceGuid, spaceName string\n\tvar isoSegGuid, isoSegName string\n\tvar testSetup *workflowhelpers.ReproducibleTestSuiteSetup\n\n\tBeforeEach(func() {\n\t\t\/\/ New up a organization since we will be assigning isolation segments.\n\t\t\/\/ This has a potential to cause other tests to fail if running in parallel mode.\n\t\tcfg, _ := config.NewCatsConfig(os.Getenv(\"CONFIG\"))\n\t\ttestSetup = workflowhelpers.NewTestSuiteSetup(cfg)\n\t\ttestSetup.Setup()\n\n\t\torgName = testSetup.RegularUserContext().Org\n\t\tspaceName = testSetup.RegularUserContext().Space\n\t\tisoSegName = Config.GetIsolationSegmentName()\n\n\t\tsession := cf.Cf(\"curl\", fmt.Sprintf(\"\/v3\/organizations?names=%s\", orgName))\n\t\tbytes := session.Wait(Config.DefaultTimeoutDuration()).Out.Contents()\n\t\torgGuid = getGuid(bytes)\n\t})\n\n\tAfterEach(func() {\n\t\ttestSetup.Teardown()\n\n\t\tif isoSegGuid != \"\" {\n\t\t\tworkflowhelpers.AsUser(testSetup.AdminUserContext(), testSetup.ShortTimeout(), func() {\n\t\t\t\tdeleteIsolationSegment(isoSegGuid)\n\t\t\t})\n\t\t\tisoSegGuid = \"\"\n\t\t}\n\t})\n\n\tContext(\"When an organization has the shared segment as its default\", func() {\n\t\tBeforeEach(func() {\n\t\t\tentitleOrgToIsolationSegment(orgGuid, SHARED_ISOLATION_SEGMENT_GUID)\n\t\t})\n\n\t\tIt(\"can run an app to a space with no assigned segment\", func() {\n\t\t\tappName := random_name.CATSRandomName(\"APP\")\n\t\t\tEventually(cf.Cf(\n\t\t\t\t\"push\", appName,\n\t\t\t\t\"-p\", assets.NewAssets().Binary,\n\t\t\t\t\"--no-start\",\n\t\t\t\t\"-m\", DEFAULT_MEMORY_LIMIT,\n\t\t\t\t\"-b\", \"binary_buildpack\",\n\t\t\t\t\"-d\", Config.GetAppsDomain(),\n\t\t\t\t\"-c\", \".\/app\"),\n\t\t\t\tConfig.CfPushTimeoutDuration()).Should(Exit(0))\n\n\t\t\tapp_helpers.EnableDiego(appName)\n\t\t\tEventually(cf.Cf(\"start\", appName), Config.CfPushTimeoutDuration()).Should(Exit(0))\n\t\t\tEventually(helpers.CurlingAppRoot(Config, appName), Config.DefaultTimeoutDuration()).Should(ContainSubstring(binaryHi))\n\t\t})\n\t})\n\n\tContext(\"When the user-provided Isolation Segment has an associated cell\", func() {\n\t\tBeforeEach(func() {\n\t\t\tworkflowhelpers.AsUser(testSetup.AdminUserContext(), testSetup.ShortTimeout(), func() {\n\t\t\t\tisoSegGuid = createOrGetIsolationSegment(isoSegName)\n\t\t\t\tentitleOrgToIsolationSegment(orgGuid, isoSegGuid)\n\t\t\t\tsetDefaultIsolationSegment(orgGuid, isoSegGuid)\n\t\t\t})\n\t\t})\n\n\t\tIt(\"can run an app to an org where the default is the user-provided isolation segment\", func() {\n\t\t\tappName := random_name.CATSRandomName(\"APP\")\n\t\t\tEventually(cf.Cf(\n\t\t\t\t\"push\", appName,\n\t\t\t\t\"-p\", assets.NewAssets().Binary,\n\t\t\t\t\"--no-start\",\n\t\t\t\t\"-m\", DEFAULT_MEMORY_LIMIT,\n\t\t\t\t\"-b\", \"binary_buildpack\",\n\t\t\t\t\"-d\", Config.GetAppsDomain(),\n\t\t\t\t\"-c\", \".\/app\"),\n\t\t\t\tConfig.CfPushTimeoutDuration()).Should(Exit(0))\n\n\t\t\tapp_helpers.EnableDiego(appName)\n\t\t\tEventually(cf.Cf(\"start\", appName), Config.CfPushTimeoutDuration()).Should(Exit(0))\n\t\t\tEventually(helpers.CurlingAppRoot(Config, appName), Config.DefaultTimeoutDuration()).Should(ContainSubstring(binaryHi))\n\t\t})\n\t})\n\n\tContext(\"When the Isolation Segment has no associated cells\", func() {\n\t\tBeforeEach(func() {\n\t\t\tworkflowhelpers.AsUser(testSetup.AdminUserContext(), testSetup.ShortTimeout(), func() {\n\t\t\t\tisoSegGuid = createIsolationSegment(random_name.CATSRandomName(\"fake-iso-seg\"))\n\t\t\t\tentitleOrgToIsolationSegment(orgGuid, isoSegGuid)\n\t\t\t\tsetDefaultIsolationSegment(orgGuid, isoSegGuid)\n\t\t\t})\n\t\t})\n\n\t\tIt(\"fails to start an app in the Isolation Segment\", func() {\n\t\t\tappName := random_name.CATSRandomName(\"APP\")\n\t\t\tEventually(cf.Cf(\n\t\t\t\t\"push\", appName,\n\t\t\t\t\"-p\", assets.NewAssets().Binary,\n\t\t\t\t\"--no-start\",\n\t\t\t\t\"-m\", DEFAULT_MEMORY_LIMIT,\n\t\t\t\t\"-b\", \"binary_buildpack\",\n\t\t\t\t\"-d\", Config.GetAppsDomain(),\n\t\t\t\t\"-c\", \".\/app\"),\n\t\t\t\tConfig.CfPushTimeoutDuration()).Should(Exit(0))\n\n\t\t\tapp_helpers.EnableDiego(appName)\n\t\t\tEventually(cf.Cf(\"start\", appName), Config.CfPushTimeoutDuration()).Should(Exit(1))\n\t\t})\n\t})\n\n\tContext(\"When the organization has not been entitled to the Isolation Segment\", func() {\n\t\tBeforeEach(func() {\n\t\t\tworkflowhelpers.AsUser(testSetup.AdminUserContext(), testSetup.ShortTimeout(), func() {\n\t\t\t\tisoSegGuid = createOrGetIsolationSegment(isoSegName)\n\t\t\t})\n\t\t})\n\n\t\tIt(\"fails to set the isolation segment as the default\", func() {\n\t\t\tworkflowhelpers.AsUser(TestSetup.AdminUserContext(), Config.DefaultTimeoutDuration(), func() {\n\t\t\t\tsession := cf.Cf(\"curl\",\n\t\t\t\t\tfmt.Sprintf(\"\/v3\/organizations\/%s\/relationships\/default_isolation_segment\", orgGuid),\n\t\t\t\t\t\"-X\",\n\t\t\t\t\t\"PATCH\",\n\t\t\t\t\t\"-d\",\n\t\t\t\t\tfmt.Sprintf(`{\"data\":{\"guid\":\"%s\"}}`, isoSegGuid)).Wait(Config.DefaultTimeoutDuration())\n\t\t\t\tExpect(session).To(Exit(0))\n\t\t\t\tExpect(session).To(Say(\"Ensure it has been entitled to this organization\"))\n\t\t\t})\n\t\t})\n\t})\n\n\tContext(\"When the space has been assigned an Isolation Segment\", func() {\n\t\tBeforeEach(func() {\n\t\t\tworkflowhelpers.AsUser(testSetup.AdminUserContext(), testSetup.ShortTimeout(), func() {\n\t\t\t\tisoSegGuid = createOrGetIsolationSegment(isoSegName)\n\t\t\t\tentitleOrgToIsolationSegment(orgGuid, isoSegGuid)\n\t\t\t\tsession := cf.Cf(\"curl\", fmt.Sprintf(\"\/v3\/spaces?names=%s\", spaceName))\n\t\t\t\tbytes := session.Wait(Config.DefaultTimeoutDuration()).Out.Contents()\n\t\t\t\tspaceGuid = getGuid(bytes)\n\t\t\t\tassignIsolationSegmentToSpace(spaceGuid, isoSegGuid)\n\t\t\t})\n\t\t})\n\n\t\tIt(\"can run an app in that isolation segment\", func() {\n\t\t\tappName := random_name.CATSRandomName(\"APP\")\n\t\t\tEventually(cf.Cf(\n\t\t\t\t\"push\", appName,\n\t\t\t\t\"-p\", assets.NewAssets().Binary,\n\t\t\t\t\"--no-start\",\n\t\t\t\t\"-m\", DEFAULT_MEMORY_LIMIT,\n\t\t\t\t\"-b\", \"binary_buildpack\",\n\t\t\t\t\"-d\", Config.GetAppsDomain(),\n\t\t\t\t\"-c\", \".\/app\"),\n\t\t\t\tConfig.CfPushTimeoutDuration()).Should(Exit(0))\n\n\t\t\tapp_helpers.EnableDiego(appName)\n\t\t\tEventually(cf.Cf(\"start\", appName), Config.CfPushTimeoutDuration()).Should(Exit(0))\n\t\t\tEventually(helpers.CurlingAppRoot(Config, appName), Config.DefaultTimeoutDuration()).Should(ContainSubstring(binaryHi))\n\t\t})\n\t})\n})\n<commit_msg>update set default iso seg fail message<commit_after>package isolation_segments\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t. \"github.com\/cloudfoundry\/cf-acceptance-tests\/cats_suite_helpers\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gbytes\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/cf\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/helpers\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/workflowhelpers\"\n\t\"github.com\/cloudfoundry\/cf-acceptance-tests\/helpers\/app_helpers\"\n\t\"github.com\/cloudfoundry\/cf-acceptance-tests\/helpers\/assets\"\n\t\"github.com\/cloudfoundry\/cf-acceptance-tests\/helpers\/config\"\n\t\"github.com\/cloudfoundry\/cf-acceptance-tests\/helpers\/random_name\"\n)\n\nconst (\n\tSHARED_ISOLATION_SEGMENT_GUID = \"933b4c58-120b-499a-b85d-4b6fc9e2903b\"\n\tbinaryHi                      = \"Hello from a binary\"\n)\n\nfunc entitleOrgToIsolationSegment(orgGuid, isoSegGuid string) {\n\tEventually(cf.Cf(\"curl\",\n\t\tfmt.Sprintf(\"\/v3\/isolation_segments\/%s\/relationships\/organizations\", isoSegGuid),\n\t\t\"-X\",\n\t\t\"POST\",\n\t\t\"-d\",\n\t\tfmt.Sprintf(`{\"data\":[{ \"guid\":\"%s\" }]}`, orgGuid)),\n\t\tConfig.DefaultTimeoutDuration()).Should(Exit(0))\n}\n\nfunc assignIsolationSegmentToSpace(spaceGuid, isoSegGuid string) {\n\tEventually(cf.Cf(\"curl\", fmt.Sprintf(\"\/v3\/spaces\/%s\/relationships\/isolation_segment\", spaceGuid),\n\t\t\"-X\",\n\t\t\"PATCH\",\n\t\t\"-d\",\n\t\tfmt.Sprintf(`{\"data\":{\"guid\":\"%s\"}}`, isoSegGuid)),\n\t\tConfig.DefaultTimeoutDuration()).Should(Exit(0))\n}\n\nfunc setDefaultIsolationSegment(orgGuid, isoSegGuid string) {\n\tEventually(cf.Cf(\"curl\",\n\t\tfmt.Sprintf(\"\/v3\/organizations\/%s\/relationships\/default_isolation_segment\", orgGuid),\n\t\t\"-X\",\n\t\t\"PATCH\",\n\t\t\"-d\",\n\t\tfmt.Sprintf(`{\"data\":{\"guid\":\"%s\"}}`, isoSegGuid)),\n\t\tConfig.DefaultTimeoutDuration()).Should(Exit(0))\n}\n\nfunc getGuid(response []byte) string {\n\ttype resource struct {\n\t\tGuid string `json:\"guid\"`\n\t}\n\tvar GetResponse struct {\n\t\tResources []resource `json:\"resources\"`\n\t}\n\n\terr := json.Unmarshal(response, &GetResponse)\n\tExpect(err).ToNot(HaveOccurred())\n\n\tif len(GetResponse.Resources) == 0 {\n\t\tFail(\"No guid found for response\")\n\t}\n\n\treturn GetResponse.Resources[0].Guid\n}\n\nfunc getIsolationSegmentGuid(name string) string {\n\tsession := cf.Cf(\"curl\", fmt.Sprintf(\"\/v3\/isolation_segments?names=%s\", name))\n\tbytes := session.Wait(Config.DefaultTimeoutDuration()).Out.Contents()\n\treturn getGuid(bytes)\n}\n\nfunc isolationSegmentExists(name string) bool {\n\tsession := cf.Cf(\"curl\", fmt.Sprintf(\"\/v3\/isolation_segments?names=%s\", name))\n\tbytes := session.Wait(Config.DefaultTimeoutDuration()).Out.Contents()\n\ttype resource struct {\n\t\tGuid string `json:\"guid\"`\n\t}\n\tvar GetResponse struct {\n\t\tResources []resource `json:\"resources\"`\n\t}\n\n\terr := json.Unmarshal(bytes, &GetResponse)\n\tExpect(err).ToNot(HaveOccurred())\n\treturn len(GetResponse.Resources) > 0\n}\n\nfunc createIsolationSegment(name string) string {\n\tsession := cf.Cf(\"curl\", \"\/v3\/isolation_segments\", \"-X\", \"POST\", \"-d\", fmt.Sprintf(`{\"name\":\"%s\"}`, name))\n\tbytes := session.Wait(Config.DefaultTimeoutDuration()).Out.Contents()\n\n\tvar isolation_segment struct {\n\t\tGuid string `json:\"guid\"`\n\t}\n\terr := json.Unmarshal(bytes, &isolation_segment)\n\tExpect(err).ToNot(HaveOccurred())\n\n\treturn isolation_segment.Guid\n}\n\nfunc deleteIsolationSegment(guid string) {\n\tEventually(cf.Cf(\"curl\", fmt.Sprintf(\"\/v3\/isolation_segments\/%s\", guid), \"-X\", \"DELETE\"), Config.DefaultTimeoutDuration()).Should(Exit(0))\n}\n\nfunc createOrGetIsolationSegment(name string) string {\n\tvar isoSegGuid string\n\tif isolationSegmentExists(name) {\n\t\tisoSegGuid = getIsolationSegmentGuid(name)\n\t} else {\n\t\tisoSegGuid = createIsolationSegment(name)\n\t}\n\treturn isoSegGuid\n}\n\nvar _ = IsolationSegmentsDescribe(\"IsolationSegments\", func() {\n\tvar orgGuid, orgName string\n\tvar spaceGuid, spaceName string\n\tvar isoSegGuid, isoSegName string\n\tvar testSetup *workflowhelpers.ReproducibleTestSuiteSetup\n\n\tBeforeEach(func() {\n\t\t\/\/ New up a organization since we will be assigning isolation segments.\n\t\t\/\/ This has a potential to cause other tests to fail if running in parallel mode.\n\t\tcfg, _ := config.NewCatsConfig(os.Getenv(\"CONFIG\"))\n\t\ttestSetup = workflowhelpers.NewTestSuiteSetup(cfg)\n\t\ttestSetup.Setup()\n\n\t\torgName = testSetup.RegularUserContext().Org\n\t\tspaceName = testSetup.RegularUserContext().Space\n\t\tisoSegName = Config.GetIsolationSegmentName()\n\n\t\tsession := cf.Cf(\"curl\", fmt.Sprintf(\"\/v3\/organizations?names=%s\", orgName))\n\t\tbytes := session.Wait(Config.DefaultTimeoutDuration()).Out.Contents()\n\t\torgGuid = getGuid(bytes)\n\t})\n\n\tAfterEach(func() {\n\t\ttestSetup.Teardown()\n\n\t\tif isoSegGuid != \"\" {\n\t\t\tworkflowhelpers.AsUser(testSetup.AdminUserContext(), testSetup.ShortTimeout(), func() {\n\t\t\t\tdeleteIsolationSegment(isoSegGuid)\n\t\t\t})\n\t\t\tisoSegGuid = \"\"\n\t\t}\n\t})\n\n\tContext(\"When an organization has the shared segment as its default\", func() {\n\t\tBeforeEach(func() {\n\t\t\tentitleOrgToIsolationSegment(orgGuid, SHARED_ISOLATION_SEGMENT_GUID)\n\t\t})\n\n\t\tIt(\"can run an app to a space with no assigned segment\", func() {\n\t\t\tappName := random_name.CATSRandomName(\"APP\")\n\t\t\tEventually(cf.Cf(\n\t\t\t\t\"push\", appName,\n\t\t\t\t\"-p\", assets.NewAssets().Binary,\n\t\t\t\t\"--no-start\",\n\t\t\t\t\"-m\", DEFAULT_MEMORY_LIMIT,\n\t\t\t\t\"-b\", \"binary_buildpack\",\n\t\t\t\t\"-d\", Config.GetAppsDomain(),\n\t\t\t\t\"-c\", \".\/app\"),\n\t\t\t\tConfig.CfPushTimeoutDuration()).Should(Exit(0))\n\n\t\t\tapp_helpers.EnableDiego(appName)\n\t\t\tEventually(cf.Cf(\"start\", appName), Config.CfPushTimeoutDuration()).Should(Exit(0))\n\t\t\tEventually(helpers.CurlingAppRoot(Config, appName), Config.DefaultTimeoutDuration()).Should(ContainSubstring(binaryHi))\n\t\t})\n\t})\n\n\tContext(\"When the user-provided Isolation Segment has an associated cell\", func() {\n\t\tBeforeEach(func() {\n\t\t\tworkflowhelpers.AsUser(testSetup.AdminUserContext(), testSetup.ShortTimeout(), func() {\n\t\t\t\tisoSegGuid = createOrGetIsolationSegment(isoSegName)\n\t\t\t\tentitleOrgToIsolationSegment(orgGuid, isoSegGuid)\n\t\t\t\tsetDefaultIsolationSegment(orgGuid, isoSegGuid)\n\t\t\t})\n\t\t})\n\n\t\tIt(\"can run an app to an org where the default is the user-provided isolation segment\", func() {\n\t\t\tappName := random_name.CATSRandomName(\"APP\")\n\t\t\tEventually(cf.Cf(\n\t\t\t\t\"push\", appName,\n\t\t\t\t\"-p\", assets.NewAssets().Binary,\n\t\t\t\t\"--no-start\",\n\t\t\t\t\"-m\", DEFAULT_MEMORY_LIMIT,\n\t\t\t\t\"-b\", \"binary_buildpack\",\n\t\t\t\t\"-d\", Config.GetAppsDomain(),\n\t\t\t\t\"-c\", \".\/app\"),\n\t\t\t\tConfig.CfPushTimeoutDuration()).Should(Exit(0))\n\n\t\t\tapp_helpers.EnableDiego(appName)\n\t\t\tEventually(cf.Cf(\"start\", appName), Config.CfPushTimeoutDuration()).Should(Exit(0))\n\t\t\tEventually(helpers.CurlingAppRoot(Config, appName), Config.DefaultTimeoutDuration()).Should(ContainSubstring(binaryHi))\n\t\t})\n\t})\n\n\tContext(\"When the Isolation Segment has no associated cells\", func() {\n\t\tBeforeEach(func() {\n\t\t\tworkflowhelpers.AsUser(testSetup.AdminUserContext(), testSetup.ShortTimeout(), func() {\n\t\t\t\tisoSegGuid = createIsolationSegment(random_name.CATSRandomName(\"fake-iso-seg\"))\n\t\t\t\tentitleOrgToIsolationSegment(orgGuid, isoSegGuid)\n\t\t\t\tsetDefaultIsolationSegment(orgGuid, isoSegGuid)\n\t\t\t})\n\t\t})\n\n\t\tIt(\"fails to start an app in the Isolation Segment\", func() {\n\t\t\tappName := random_name.CATSRandomName(\"APP\")\n\t\t\tEventually(cf.Cf(\n\t\t\t\t\"push\", appName,\n\t\t\t\t\"-p\", assets.NewAssets().Binary,\n\t\t\t\t\"--no-start\",\n\t\t\t\t\"-m\", DEFAULT_MEMORY_LIMIT,\n\t\t\t\t\"-b\", \"binary_buildpack\",\n\t\t\t\t\"-d\", Config.GetAppsDomain(),\n\t\t\t\t\"-c\", \".\/app\"),\n\t\t\t\tConfig.CfPushTimeoutDuration()).Should(Exit(0))\n\n\t\t\tapp_helpers.EnableDiego(appName)\n\t\t\tEventually(cf.Cf(\"start\", appName), Config.CfPushTimeoutDuration()).Should(Exit(1))\n\t\t})\n\t})\n\n\tContext(\"When the organization has not been entitled to the Isolation Segment\", func() {\n\t\tBeforeEach(func() {\n\t\t\tworkflowhelpers.AsUser(testSetup.AdminUserContext(), testSetup.ShortTimeout(), func() {\n\t\t\t\tisoSegGuid = createOrGetIsolationSegment(isoSegName)\n\t\t\t})\n\t\t})\n\n\t\tIt(\"fails to set the isolation segment as the default\", func() {\n\t\t\tworkflowhelpers.AsUser(TestSetup.AdminUserContext(), Config.DefaultTimeoutDuration(), func() {\n\t\t\t\tsession := cf.Cf(\"curl\",\n\t\t\t\t\tfmt.Sprintf(\"\/v3\/organizations\/%s\/relationships\/default_isolation_segment\", orgGuid),\n\t\t\t\t\t\"-X\",\n\t\t\t\t\t\"PATCH\",\n\t\t\t\t\t\"-d\",\n\t\t\t\t\tfmt.Sprintf(`{\"data\":{\"guid\":\"%s\"}}`, isoSegGuid)).Wait(Config.DefaultTimeoutDuration())\n\t\t\t\tExpect(session).To(Exit(0))\n\t\t\t\tExpect(session).To(Say(\"Ensure it has been entitled to the organization\"))\n\t\t\t})\n\t\t})\n\t})\n\n\tContext(\"When the space has been assigned an Isolation Segment\", func() {\n\t\tBeforeEach(func() {\n\t\t\tworkflowhelpers.AsUser(testSetup.AdminUserContext(), testSetup.ShortTimeout(), func() {\n\t\t\t\tisoSegGuid = createOrGetIsolationSegment(isoSegName)\n\t\t\t\tentitleOrgToIsolationSegment(orgGuid, isoSegGuid)\n\t\t\t\tsession := cf.Cf(\"curl\", fmt.Sprintf(\"\/v3\/spaces?names=%s\", spaceName))\n\t\t\t\tbytes := session.Wait(Config.DefaultTimeoutDuration()).Out.Contents()\n\t\t\t\tspaceGuid = getGuid(bytes)\n\t\t\t\tassignIsolationSegmentToSpace(spaceGuid, isoSegGuid)\n\t\t\t})\n\t\t})\n\n\t\tIt(\"can run an app in that isolation segment\", func() {\n\t\t\tappName := random_name.CATSRandomName(\"APP\")\n\t\t\tEventually(cf.Cf(\n\t\t\t\t\"push\", appName,\n\t\t\t\t\"-p\", assets.NewAssets().Binary,\n\t\t\t\t\"--no-start\",\n\t\t\t\t\"-m\", DEFAULT_MEMORY_LIMIT,\n\t\t\t\t\"-b\", \"binary_buildpack\",\n\t\t\t\t\"-d\", Config.GetAppsDomain(),\n\t\t\t\t\"-c\", \".\/app\"),\n\t\t\t\tConfig.CfPushTimeoutDuration()).Should(Exit(0))\n\n\t\t\tapp_helpers.EnableDiego(appName)\n\t\t\tEventually(cf.Cf(\"start\", appName), Config.CfPushTimeoutDuration()).Should(Exit(0))\n\t\t\tEventually(helpers.CurlingAppRoot(Config, appName), Config.DefaultTimeoutDuration()).Should(ContainSubstring(binaryHi))\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package db\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/bosssauce\/ponzu\/content\"\n\t\"github.com\/bosssauce\/ponzu\/management\/editor\"\n\t\"github.com\/bosssauce\/ponzu\/management\/manager\"\n\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/gorilla\/schema\"\n)\n\n\/\/ SetContent inserts or updates values in the database.\n\/\/ The `target` argument is a string made up of namespace:id (string:int)\nfunc SetContent(target string, data url.Values) (int, error) {\n\tt := strings.Split(target, \":\")\n\tns, id := t[0], t[1]\n\n\t\/\/ check if content id == -1 (indicating new post).\n\t\/\/ if so, run an insert which will assign the next auto incremented int.\n\t\/\/ this is done because boltdb begins its bucket auto increment value at 0,\n\t\/\/ which is the zero-value of an int in the Item struct field for ID.\n\t\/\/ this is a problem when the original first post (with auto ID = 0) gets\n\t\/\/ overwritten by any new post, originally having no ID, defauting to 0.\n\tif id == \"-1\" {\n\t\treturn insert(ns, data)\n\t}\n\n\treturn update(ns, id, data)\n}\n\nfunc update(ns, id string, data url.Values) (int, error) {\n\tvar specifier string \/\/ i.e. _pending, _sorted, etc.\n\tif strings.Contains(ns, \"_\") {\n\t\tspec := strings.Split(ns, \"_\")\n\t\tns = spec[0]\n\t\tspecifier = \"_\" + spec[1]\n\t}\n\n\tcid, err := strconv.Atoi(id)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\terr = store.Update(func(tx *bolt.Tx) error {\n\t\tb, err := tx.CreateBucketIfNotExists([]byte(ns + specifier))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tj, err := postToJSON(ns, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = b.Put([]byte(fmt.Sprintf(\"%d\", cid)), j)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tif specifier == \"\" {\n\t\tgo SortContent(ns)\n\t}\n\n\treturn cid, nil\n}\n\nfunc insert(ns string, data url.Values) (int, error) {\n\tvar effectedID int\n\tvar specifier string \/\/ i.e. _pending, _sorted, etc.\n\tif strings.Contains(ns, \"_\") {\n\t\tspec := strings.Split(ns, \"_\")\n\t\tns = spec[0]\n\t\tspecifier = \"_\" + spec[1]\n\t}\n\n\terr := store.Update(func(tx *bolt.Tx) error {\n\t\tb, err := tx.CreateBucketIfNotExists([]byte(ns + specifier))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ get the next available ID and convert to string\n\t\t\/\/ also set effectedID to int of ID\n\t\tid, err := b.NextSequence()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcid := strconv.FormatUint(id, 10)\n\t\teffectedID, err = strconv.Atoi(cid)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdata.Set(\"id\", cid)\n\n\t\tj, err := postToJSON(ns, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = b.Put([]byte(cid), j)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif specifier == \"\" {\n\t\tgo SortContent(ns)\n\t}\n\n\treturn effectedID, nil\n}\n\n\/\/ DeleteContent removes an item from the database. Deleting a non-existent item\n\/\/ will return a nil error.\nfunc DeleteContent(target string) error {\n\tt := strings.Split(target, \":\")\n\tns, id := t[0], t[1]\n\n\terr := store.Update(func(tx *bolt.Tx) error {\n\t\ttx.Bucket([]byte(ns)).Delete([]byte(id))\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ exception to typical \"run in goroutine\" pattern:\n\t\/\/ we want to have an updated admin view as soon as this is deleted, so\n\t\/\/ in some cases, the delete and redirect is faster than the sort,\n\t\/\/ thus still showing a deleted post in the admin view.\n\tSortContent(ns)\n\n\treturn nil\n}\n\n\/\/ Content retrives one item from the database. Non-existent values will return an empty []byte\n\/\/ The `target` argument is a string made up of namespace:id (string:int)\nfunc Content(target string) ([]byte, error) {\n\tt := strings.Split(target, \":\")\n\tns, id := t[0], t[1]\n\n\tval := &bytes.Buffer{}\n\terr := store.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(ns))\n\t\t_, err := val.Write(b.Get([]byte(id)))\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn val.Bytes(), nil\n}\n\n\/\/ ContentAll retrives all items from the database within the provided namespace\nfunc ContentAll(namespace string) [][]byte {\n\tvar posts [][]byte\n\tstore.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(namespace))\n\n\t\tif b == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tnumKeys := b.Stats().KeyN\n\t\tposts = make([][]byte, 0, numKeys)\n\n\t\tb.ForEach(func(k, v []byte) error {\n\t\t\tposts = append(posts, v)\n\n\t\t\treturn nil\n\t\t})\n\n\t\treturn nil\n\t})\n\n\treturn posts\n}\n\n\/\/ QueryOptions holds options for a query\ntype QueryOptions struct {\n\tCount  int\n\tOffset int\n\tOrder  string\n}\n\n\/\/ Query retrieves a set of content from the db based on options\nfunc Query(namespace string, opts QueryOptions) [][]byte {\n\tvar posts [][]byte\n\tstore.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(namespace))\n\t\tc := b.Cursor()\n\t\tn := b.Stats().KeyN\n\n\t\tvar start, end int\n\t\tswitch opts.Count {\n\t\tcase -1:\n\t\t\tstart = 0\n\t\t\tend = n\n\n\t\tdefault:\n\t\t\tstart = opts.Count * opts.Offset\n\t\t\tend = start + opts.Count\n\t\t}\n\n\t\t\/\/ bounds check on posts given the start & end count\n\t\tif start > n {\n\t\t\tstart = n - opts.Count\n\t\t}\n\t\tif end > n {\n\t\t\tend = n\n\t\t}\n\n\t\ti := 0   \/\/ count of num posts added\n\t\tcur := 0 \/\/ count of where cursor is\n\t\tswitch opts.Order {\n\t\tcase \"asc\":\n\t\t\tfor k, v := c.Last(); k != nil; c.Prev() {\n\t\t\t\tif cur < end {\n\t\t\t\t\tcur++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif cur >= start {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif i >= opts.Count {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tposts = append(posts, v)\n\t\t\t\ti++\n\t\t\t\tcur++\n\t\t\t}\n\n\t\tcase \"desc\":\n\t\t\tfor k, v := c.First(); k != nil; c.Next() {\n\t\t\t\tif cur < start {\n\t\t\t\t\tcur++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif cur >= end {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif i >= opts.Count {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tposts = append(posts, v)\n\t\t\t\ti++\n\t\t\t\tcur++\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\t\/\/ if opts.order == \"asc\" {\n\t\/\/ \tposts = []json.RawMessage{}\n\t\/\/ \tfor i := len(posts) - 1; i >= 0; i-- {\n\t\/\/ \t\tposts = append(all, posts[i])\n\t\/\/ \t}\n\t\/\/ }\n\n\treturn posts\n}\n\n\/\/ SortContent sorts all content of the type supplied as the namespace by time,\n\/\/ in descending order, from most recent to least recent\n\/\/ Should be called from a goroutine after SetContent is successful\nfunc SortContent(namespace string) {\n\t\/\/ only sort main content types i.e. Post\n\tif strings.Contains(namespace, \"_\") {\n\t\treturn\n\t}\n\n\tall := ContentAll(namespace)\n\n\tvar posts sortablePosts\n\t\/\/ decode each (json) into type to then sort\n\tfor i := range all {\n\t\tj := all[i]\n\t\tpost := content.Types[namespace]()\n\n\t\terr := json.Unmarshal(j, &post)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error decoding json while sorting\", namespace, \":\", err)\n\t\t\treturn\n\t\t}\n\n\t\tposts = append(posts, post.(editor.Sortable))\n\t}\n\n\t\/\/ sort posts\n\tsort.Sort(posts)\n\n\t\/\/ store in <namespace>_sorted bucket, first delete existing\n\terr := store.Update(func(tx *bolt.Tx) error {\n\t\tbname := []byte(namespace + \"_sorted\")\n\t\terr := tx.DeleteBucket(bname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tb, err := tx.CreateBucketIfNotExists(bname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ encode to json and store as 'i:post.Time()':post\n\t\tfor i := range posts {\n\t\t\tj, err := json.Marshal(posts[i])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcid := fmt.Sprintf(\"%d:%d\", i, posts[i].Time())\n\t\t\terr = b.Put([]byte(cid), j)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Println(\"Error while updating db with sorted\", namespace, err)\n\t}\n\n}\n\ntype sortablePosts []editor.Sortable\n\nfunc (s sortablePosts) Len() int {\n\treturn len(s)\n}\n\nfunc (s sortablePosts) Less(i, j int) bool {\n\treturn s[i].Time() > s[j].Time()\n}\n\nfunc (s sortablePosts) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\nfunc postToJSON(ns string, data url.Values) ([]byte, error) {\n\t\/\/ find the content type and decode values into it\n\tns = strings.TrimSuffix(ns, \"_external\")\n\tt, ok := content.Types[ns]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(content.ErrTypeNotRegistered, ns)\n\t}\n\tpost := t()\n\n\tdec := schema.NewDecoder()\n\tdec.SetAliasTag(\"json\")     \/\/ allows simpler struct tagging when creating a content type\n\tdec.IgnoreUnknownKeys(true) \/\/ will skip over form values submitted, but not in struct\n\terr := dec.Decode(post, data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tslug, err := manager.Slug(post.(editor.Editable))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpost.(editor.Editable).SetSlug(slug)\n\n\t\/\/ marshall content struct to json for db storage\n\tj, err := json.Marshal(post)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn j, nil\n}\n<commit_msg>reassigning k, v with next or prev record<commit_after>package db\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/bosssauce\/ponzu\/content\"\n\t\"github.com\/bosssauce\/ponzu\/management\/editor\"\n\t\"github.com\/bosssauce\/ponzu\/management\/manager\"\n\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/gorilla\/schema\"\n)\n\n\/\/ SetContent inserts or updates values in the database.\n\/\/ The `target` argument is a string made up of namespace:id (string:int)\nfunc SetContent(target string, data url.Values) (int, error) {\n\tt := strings.Split(target, \":\")\n\tns, id := t[0], t[1]\n\n\t\/\/ check if content id == -1 (indicating new post).\n\t\/\/ if so, run an insert which will assign the next auto incremented int.\n\t\/\/ this is done because boltdb begins its bucket auto increment value at 0,\n\t\/\/ which is the zero-value of an int in the Item struct field for ID.\n\t\/\/ this is a problem when the original first post (with auto ID = 0) gets\n\t\/\/ overwritten by any new post, originally having no ID, defauting to 0.\n\tif id == \"-1\" {\n\t\treturn insert(ns, data)\n\t}\n\n\treturn update(ns, id, data)\n}\n\nfunc update(ns, id string, data url.Values) (int, error) {\n\tvar specifier string \/\/ i.e. _pending, _sorted, etc.\n\tif strings.Contains(ns, \"_\") {\n\t\tspec := strings.Split(ns, \"_\")\n\t\tns = spec[0]\n\t\tspecifier = \"_\" + spec[1]\n\t}\n\n\tcid, err := strconv.Atoi(id)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\terr = store.Update(func(tx *bolt.Tx) error {\n\t\tb, err := tx.CreateBucketIfNotExists([]byte(ns + specifier))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tj, err := postToJSON(ns, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = b.Put([]byte(fmt.Sprintf(\"%d\", cid)), j)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\n\tif specifier == \"\" {\n\t\tgo SortContent(ns)\n\t}\n\n\treturn cid, nil\n}\n\nfunc insert(ns string, data url.Values) (int, error) {\n\tvar effectedID int\n\tvar specifier string \/\/ i.e. _pending, _sorted, etc.\n\tif strings.Contains(ns, \"_\") {\n\t\tspec := strings.Split(ns, \"_\")\n\t\tns = spec[0]\n\t\tspecifier = \"_\" + spec[1]\n\t}\n\n\terr := store.Update(func(tx *bolt.Tx) error {\n\t\tb, err := tx.CreateBucketIfNotExists([]byte(ns + specifier))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ get the next available ID and convert to string\n\t\t\/\/ also set effectedID to int of ID\n\t\tid, err := b.NextSequence()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcid := strconv.FormatUint(id, 10)\n\t\teffectedID, err = strconv.Atoi(cid)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdata.Set(\"id\", cid)\n\n\t\tj, err := postToJSON(ns, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = b.Put([]byte(cid), j)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif specifier == \"\" {\n\t\tgo SortContent(ns)\n\t}\n\n\treturn effectedID, nil\n}\n\n\/\/ DeleteContent removes an item from the database. Deleting a non-existent item\n\/\/ will return a nil error.\nfunc DeleteContent(target string) error {\n\tt := strings.Split(target, \":\")\n\tns, id := t[0], t[1]\n\n\terr := store.Update(func(tx *bolt.Tx) error {\n\t\ttx.Bucket([]byte(ns)).Delete([]byte(id))\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ exception to typical \"run in goroutine\" pattern:\n\t\/\/ we want to have an updated admin view as soon as this is deleted, so\n\t\/\/ in some cases, the delete and redirect is faster than the sort,\n\t\/\/ thus still showing a deleted post in the admin view.\n\tSortContent(ns)\n\n\treturn nil\n}\n\n\/\/ Content retrives one item from the database. Non-existent values will return an empty []byte\n\/\/ The `target` argument is a string made up of namespace:id (string:int)\nfunc Content(target string) ([]byte, error) {\n\tt := strings.Split(target, \":\")\n\tns, id := t[0], t[1]\n\n\tval := &bytes.Buffer{}\n\terr := store.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(ns))\n\t\t_, err := val.Write(b.Get([]byte(id)))\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn val.Bytes(), nil\n}\n\n\/\/ ContentAll retrives all items from the database within the provided namespace\nfunc ContentAll(namespace string) [][]byte {\n\tvar posts [][]byte\n\tstore.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(namespace))\n\n\t\tif b == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tnumKeys := b.Stats().KeyN\n\t\tposts = make([][]byte, 0, numKeys)\n\n\t\tb.ForEach(func(k, v []byte) error {\n\t\t\tposts = append(posts, v)\n\n\t\t\treturn nil\n\t\t})\n\n\t\treturn nil\n\t})\n\n\treturn posts\n}\n\n\/\/ QueryOptions holds options for a query\ntype QueryOptions struct {\n\tCount  int\n\tOffset int\n\tOrder  string\n}\n\n\/\/ Query retrieves a set of content from the db based on options\nfunc Query(namespace string, opts QueryOptions) [][]byte {\n\tvar posts [][]byte\n\tstore.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(namespace))\n\t\tc := b.Cursor()\n\t\tn := b.Stats().KeyN\n\n\t\tvar start, end int\n\t\tswitch opts.Count {\n\t\tcase -1:\n\t\t\tstart = 0\n\t\t\tend = n\n\n\t\tdefault:\n\t\t\tstart = opts.Count * opts.Offset\n\t\t\tend = start + opts.Count\n\t\t}\n\n\t\t\/\/ bounds check on posts given the start & end count\n\t\tif start > n {\n\t\t\tstart = n - opts.Count\n\t\t}\n\t\tif end > n {\n\t\t\tend = n\n\t\t}\n\n\t\ti := 0   \/\/ count of num posts added\n\t\tcur := 0 \/\/ count of where cursor is\n\t\tswitch opts.Order {\n\t\tcase \"asc\":\n\t\t\tfor k, v := c.Last(); k != nil; k, v = c.Prev() {\n\t\t\t\tif cur < end {\n\t\t\t\t\tcur++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif cur >= start {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif i >= opts.Count {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tposts = append(posts, v)\n\t\t\t\ti++\n\t\t\t\tcur++\n\t\t\t}\n\n\t\tcase \"desc\":\n\t\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\t\tif cur < start {\n\t\t\t\t\tcur++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif cur >= end {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif i >= opts.Count {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tposts = append(posts, v)\n\t\t\t\ti++\n\t\t\t\tcur++\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\t\/\/ if opts.order == \"asc\" {\n\t\/\/ \tposts = []json.RawMessage{}\n\t\/\/ \tfor i := len(posts) - 1; i >= 0; i-- {\n\t\/\/ \t\tposts = append(all, posts[i])\n\t\/\/ \t}\n\t\/\/ }\n\n\treturn posts\n}\n\n\/\/ SortContent sorts all content of the type supplied as the namespace by time,\n\/\/ in descending order, from most recent to least recent\n\/\/ Should be called from a goroutine after SetContent is successful\nfunc SortContent(namespace string) {\n\t\/\/ only sort main content types i.e. Post\n\tif strings.Contains(namespace, \"_\") {\n\t\treturn\n\t}\n\n\tall := ContentAll(namespace)\n\n\tvar posts sortablePosts\n\t\/\/ decode each (json) into type to then sort\n\tfor i := range all {\n\t\tj := all[i]\n\t\tpost := content.Types[namespace]()\n\n\t\terr := json.Unmarshal(j, &post)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error decoding json while sorting\", namespace, \":\", err)\n\t\t\treturn\n\t\t}\n\n\t\tposts = append(posts, post.(editor.Sortable))\n\t}\n\n\t\/\/ sort posts\n\tsort.Sort(posts)\n\n\t\/\/ store in <namespace>_sorted bucket, first delete existing\n\terr := store.Update(func(tx *bolt.Tx) error {\n\t\tbname := []byte(namespace + \"_sorted\")\n\t\terr := tx.DeleteBucket(bname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tb, err := tx.CreateBucketIfNotExists(bname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ encode to json and store as 'i:post.Time()':post\n\t\tfor i := range posts {\n\t\t\tj, err := json.Marshal(posts[i])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcid := fmt.Sprintf(\"%d:%d\", i, posts[i].Time())\n\t\t\terr = b.Put([]byte(cid), j)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Println(\"Error while updating db with sorted\", namespace, err)\n\t}\n\n}\n\ntype sortablePosts []editor.Sortable\n\nfunc (s sortablePosts) Len() int {\n\treturn len(s)\n}\n\nfunc (s sortablePosts) Less(i, j int) bool {\n\treturn s[i].Time() > s[j].Time()\n}\n\nfunc (s sortablePosts) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\nfunc postToJSON(ns string, data url.Values) ([]byte, error) {\n\t\/\/ find the content type and decode values into it\n\tns = strings.TrimSuffix(ns, \"_external\")\n\tt, ok := content.Types[ns]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(content.ErrTypeNotRegistered, ns)\n\t}\n\tpost := t()\n\n\tdec := schema.NewDecoder()\n\tdec.SetAliasTag(\"json\")     \/\/ allows simpler struct tagging when creating a content type\n\tdec.IgnoreUnknownKeys(true) \/\/ will skip over form values submitted, but not in struct\n\terr := dec.Decode(post, data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tslug, err := manager.Slug(post.(editor.Editable))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpost.(editor.Editable).SetSlug(slug)\n\n\t\/\/ marshall content struct to json for db storage\n\tj, err := json.Marshal(post)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn j, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2014 CoreOS, Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage transport\n\nimport (\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestWriteReadTimeoutListener(t *testing.T) {\n\tln, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected listen error: %v\", err)\n\t}\n\twln := rwTimeoutListener{\n\t\tListener:   ln,\n\t\twtimeoutd:  10 * time.Millisecond,\n\t\trdtimeoutd: 10 * time.Millisecond,\n\t}\n\tstop := make(chan struct{})\n\n\tblocker := func() {\n\t\tconn, err := net.Dial(\"tcp\", ln.Addr().String())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"unexpected dail error: %v\", err)\n\t\t}\n\t\tdefer conn.Close()\n\t\t\/\/ block the receiver until the writer timeout\n\t\t<-stop\n\t}\n\tgo blocker()\n\n\tconn, err := wln.Accept()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected accept error: %v\", err)\n\t}\n\tdefer conn.Close()\n\n\t\/\/ fill the socket buffer\n\tdata := make([]byte, 5*1024*1024)\n\ttimer := time.AfterFunc(wln.wtimeoutd*5, func() {\n\t\tt.Fatal(\"wait timeout\")\n\t})\n\tdefer timer.Stop()\n\n\t_, err = conn.Write(data)\n\tif operr, ok := err.(*net.OpError); !ok || operr.Op != \"write\" || !operr.Timeout() {\n\t\tt.Errorf(\"err = %v, want write i\/o timeout error\", err)\n\t}\n\tstop <- struct{}{}\n\n\ttimer.Reset(wln.rdtimeoutd * 5)\n\tgo blocker()\n\n\tconn, err = wln.Accept()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected accept error: %v\", err)\n\t}\n\tbuf := make([]byte, 10)\n\t_, err = conn.Read(buf)\n\tif operr, ok := err.(*net.OpError); !ok || operr.Op != \"read\" || !operr.Timeout() {\n\t\tt.Errorf(\"err = %v, want write i\/o timeout error\", err)\n\t}\n\tstop <- struct{}{}\n}\n<commit_msg>pkg\/transport: add NewTimeoutListener test<commit_after>\/*\n   Copyright 2014 CoreOS, Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage transport\n\nimport (\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/ TestNewTimeoutListener tests that NewTimeoutListener returns a\n\/\/ rwTimeoutListener struct with timeouts set.\nfunc TestNewTimeoutListener(t *testing.T) {\n\tl, err := NewTimeoutListener(\":0\", \"http\", TLSInfo{}, time.Hour, time.Hour)\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected NewTimeoutListener error: %v\", err)\n\t}\n\tdefer l.Close()\n\ttln := l.(*rwTimeoutListener)\n\tif tln.rdtimeoutd != time.Hour {\n\t\tt.Errorf(\"read timeout = %s, want %s\", tln.rdtimeoutd, time.Hour)\n\t}\n\tif tln.wtimeoutd != time.Hour {\n\t\tt.Errorf(\"write timeout = %s, want %s\", tln.wtimeoutd, time.Hour)\n\t}\n}\n\nfunc TestWriteReadTimeoutListener(t *testing.T) {\n\tln, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected listen error: %v\", err)\n\t}\n\twln := rwTimeoutListener{\n\t\tListener:   ln,\n\t\twtimeoutd:  10 * time.Millisecond,\n\t\trdtimeoutd: 10 * time.Millisecond,\n\t}\n\tstop := make(chan struct{})\n\n\tblocker := func() {\n\t\tconn, err := net.Dial(\"tcp\", ln.Addr().String())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"unexpected dail error: %v\", err)\n\t\t}\n\t\tdefer conn.Close()\n\t\t\/\/ block the receiver until the writer timeout\n\t\t<-stop\n\t}\n\tgo blocker()\n\n\tconn, err := wln.Accept()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected accept error: %v\", err)\n\t}\n\tdefer conn.Close()\n\n\t\/\/ fill the socket buffer\n\tdata := make([]byte, 5*1024*1024)\n\ttimer := time.AfterFunc(wln.wtimeoutd*5, func() {\n\t\tt.Fatal(\"wait timeout\")\n\t})\n\tdefer timer.Stop()\n\n\t_, err = conn.Write(data)\n\tif operr, ok := err.(*net.OpError); !ok || operr.Op != \"write\" || !operr.Timeout() {\n\t\tt.Errorf(\"err = %v, want write i\/o timeout error\", err)\n\t}\n\tstop <- struct{}{}\n\n\ttimer.Reset(wln.rdtimeoutd * 5)\n\tgo blocker()\n\n\tconn, err = wln.Accept()\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected accept error: %v\", err)\n\t}\n\tbuf := make([]byte, 10)\n\t_, err = conn.Read(buf)\n\tif operr, ok := err.(*net.OpError); !ok || operr.Op != \"read\" || !operr.Timeout() {\n\t\tt.Errorf(\"err = %v, want write i\/o timeout error\", err)\n\t}\n\tstop <- struct{}{}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 The cert-manager Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage vault\n\nimport (\n\t\"crypto\/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\tvault \"github.com\/hashicorp\/vault\/api\"\n\t\"github.com\/hashicorp\/vault\/sdk\/helper\/certutil\"\n\tcorelisters \"k8s.io\/client-go\/listers\/core\/v1\"\n\n\tv1 \"github.com\/jetstack\/cert-manager\/pkg\/apis\/certmanager\/v1\"\n\t\"github.com\/jetstack\/cert-manager\/pkg\/util\/pki\"\n)\n\nvar _ Interface = &Vault{}\n\n\/\/ ClientBuilder is a function type that returns a new Interface.\n\/\/ Can be used in tests to create a mock signer of Vault certificate requests.\ntype ClientBuilder func(namespace string, secretsLister corelisters.SecretLister,\n\tissuer v1.GenericIssuer) (Interface, error)\n\n\/\/ Interface implements various high level functionality related to connecting\n\/\/ with a Vault server, verifying its status and signing certificate request for\n\/\/ Vault's certificate.\n\/\/ TODO: Sys() is duplicated here and in Client interface\ntype Interface interface {\n\tSign(csrPEM []byte, duration time.Duration) (certPEM []byte, caPEM []byte, err error)\n\tSys() *vault.Sys\n\tIsVaultInitializedAndUnsealed() error\n}\n\n\/\/ Client implements functionality to talk to a Vault server.\ntype Client interface {\n\tNewRequest(method, requestPath string) *vault.Request\n\tRawRequest(r *vault.Request) (*vault.Response, error)\n\tSetToken(v string)\n\tToken() string\n\tSys() *vault.Sys\n}\n\n\/\/ Vault implements Interface and holds a Vault issuer, secrets lister and a\n\/\/ Vault client.\ntype Vault struct {\n\tsecretsLister corelisters.SecretLister\n\tissuer        v1.GenericIssuer\n\tnamespace     string\n\n\tclient Client\n}\n\n\/\/ New returns a new Vault instance with the given namespace, issuer and\n\/\/ secrets lister.\n\/\/ Returned errors may be network failures and should be considered for\n\/\/ retrying.\nfunc New(namespace string, secretsLister corelisters.SecretLister, issuer v1.GenericIssuer) (Interface, error) {\n\tv := &Vault{\n\t\tsecretsLister: secretsLister,\n\t\tnamespace:     namespace,\n\t\tissuer:        issuer,\n\t}\n\n\tcfg, err := v.newConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient, err := vault.NewClient(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error initializing Vault client: %s\", err.Error())\n\t}\n\n\tif err := v.setToken(client); err != nil {\n\t\treturn nil, err\n\t}\n\n\tv.client = client\n\n\treturn v, nil\n}\n\n\/\/ Sign will connect to a Vault instance to sign a certificate signing request.\nfunc (v *Vault) Sign(csrPEM []byte, duration time.Duration) (cert []byte, ca []byte, err error) {\n\tcsr, err := pki.DecodeX509CertificateRequestBytes(csrPEM)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode CSR for signing: %s\", err)\n\t}\n\n\tparameters := map[string]string{\n\t\t\"common_name\": csr.Subject.CommonName,\n\t\t\"alt_names\":   strings.Join(csr.DNSNames, \",\"),\n\t\t\"ip_sans\":     strings.Join(pki.IPAddressesToString(csr.IPAddresses), \",\"),\n\t\t\"uri_sans\":    strings.Join(pki.URLsToString(csr.URIs), \",\"),\n\t\t\"ttl\":         duration.String(),\n\t\t\"csr\":         string(csrPEM),\n\n\t\t\"exclude_cn_from_sans\": \"true\",\n\t}\n\n\tvaultIssuer := v.issuer.GetSpec().Vault\n\turl := path.Join(\"\/v1\", vaultIssuer.Path)\n\n\trequest := v.client.NewRequest(\"POST\", url)\n\n\tv.addVaultNamespaceToRequest(request)\n\n\tif err := request.SetJSONBody(parameters); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to build vault request: %s\", err)\n\t}\n\n\tresp, err := v.client.RawRequest(request)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to sign certificate by vault: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\tvaultResult := certutil.Secret{}\n\terr = resp.DecodeJSON(&vaultResult)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode response returned by vault: %s\", err)\n\t}\n\n\treturn extractCertificatesFromVaultCertificateSecret(&vaultResult)\n}\n\nfunc (v *Vault) setToken(client Client) error {\n\ttokenRef := v.issuer.GetSpec().Vault.Auth.TokenSecretRef\n\tif tokenRef != nil {\n\t\ttoken, err := v.tokenRef(tokenRef.Name, v.namespace, tokenRef.Key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclient.SetToken(token)\n\n\t\treturn nil\n\t}\n\n\tappRole := v.issuer.GetSpec().Vault.Auth.AppRole\n\tif appRole != nil {\n\t\ttoken, err := v.requestTokenWithAppRoleRef(client, appRole)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclient.SetToken(token)\n\n\t\treturn nil\n\t}\n\n\tkubernetesAuth := v.issuer.GetSpec().Vault.Auth.Kubernetes\n\tif kubernetesAuth != nil {\n\t\ttoken, err := v.requestTokenWithKubernetesAuth(client, kubernetesAuth)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading Kubernetes service account token from %s: %s\", kubernetesAuth.SecretRef.Name, err.Error())\n\t\t}\n\t\tclient.SetToken(token)\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"error initializing Vault client: tokenSecretRef, appRoleSecretRef, or Kubernetes auth role not set\")\n}\n\nfunc (v *Vault) newConfig() (*vault.Config, error) {\n\tcfg := vault.DefaultConfig()\n\tcfg.Address = v.issuer.GetSpec().Vault.Server\n\n\tcerts := v.issuer.GetSpec().Vault.CABundle\n\tif len(certs) == 0 {\n\t\treturn cfg, nil\n\t}\n\n\tcaCertPool := x509.NewCertPool()\n\tok := caCertPool.AppendCertsFromPEM(certs)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"error loading Vault CA bundle\")\n\t}\n\n\tcfg.HttpClient.Transport.(*http.Transport).TLSClientConfig.RootCAs = caCertPool\n\n\treturn cfg, nil\n}\n\nfunc (v *Vault) tokenRef(name, namespace, key string) (string, error) {\n\tsecret, err := v.secretsLister.Secrets(namespace).Get(name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif key == \"\" {\n\t\tkey = v1.DefaultVaultTokenAuthSecretKey\n\t}\n\n\tkeyBytes, ok := secret.Data[key]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"no data for %q in secret '%s\/%s'\", key, name, namespace)\n\t}\n\n\ttoken := string(keyBytes)\n\ttoken = strings.TrimSpace(token)\n\n\treturn token, nil\n}\n\nfunc (v *Vault) appRoleRef(appRole *v1.VaultAppRole) (roleId, secretId string, err error) {\n\troleId = strings.TrimSpace(appRole.RoleId)\n\n\tsecret, err := v.secretsLister.Secrets(v.namespace).Get(appRole.SecretRef.Name)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tkey := appRole.SecretRef.Key\n\n\tkeyBytes, ok := secret.Data[key]\n\tif !ok {\n\t\treturn \"\", \"\", fmt.Errorf(\"no data for %q in secret '%s\/%s'\", key, v.namespace, appRole.SecretRef.Name)\n\t}\n\n\tsecretId = string(keyBytes)\n\tsecretId = strings.TrimSpace(secretId)\n\n\treturn roleId, secretId, nil\n}\n\nfunc (v *Vault) requestTokenWithAppRoleRef(client Client, appRole *v1.VaultAppRole) (string, error) {\n\troleId, secretId, err := v.appRoleRef(appRole)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tparameters := map[string]string{\n\t\t\"role_id\":   roleId,\n\t\t\"secret_id\": secretId,\n\t}\n\n\tauthPath := appRole.Path\n\tif authPath == \"\" {\n\t\tauthPath = \"approle\"\n\t}\n\n\turl := path.Join(\"\/v1\", \"auth\", authPath, \"login\")\n\n\trequest := client.NewRequest(\"POST\", url)\n\n\terr = request.SetJSONBody(parameters)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error encoding Vault parameters: %s\", err.Error())\n\t}\n\n\tv.addVaultNamespaceToRequest(request)\n\n\tresp, err := client.RawRequest(request)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error logging in to Vault server: %s\", err.Error())\n\t}\n\n\tdefer resp.Body.Close()\n\n\tvaultResult := vault.Secret{}\n\tif err := resp.DecodeJSON(&vaultResult); err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to decode JSON payload: %s\", err.Error())\n\t}\n\n\ttoken, err := vaultResult.TokenID()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to read token: %s\", err.Error())\n\t}\n\n\tif token == \"\" {\n\t\treturn \"\", errors.New(\"no token returned\")\n\t}\n\n\treturn token, nil\n}\n\nfunc (v *Vault) requestTokenWithKubernetesAuth(client Client, kubernetesAuth *v1.VaultKubernetesAuth) (string, error) {\n\tsecret, err := v.secretsLister.Secrets(v.namespace).Get(kubernetesAuth.SecretRef.Name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkey := kubernetesAuth.SecretRef.Key\n\tif key == \"\" {\n\t\tkey = v1.DefaultVaultTokenAuthSecretKey\n\t}\n\n\tkeyBytes, ok := secret.Data[key]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"no data for %q in secret '%s\/%s'\", key, v.namespace, kubernetesAuth.SecretRef.Name)\n\t}\n\n\tjwt := string(keyBytes)\n\n\tparameters := map[string]string{\n\t\t\"role\": kubernetesAuth.Role,\n\t\t\"jwt\":  jwt,\n\t}\n\n\tmountPath := kubernetesAuth.Path\n\tif mountPath == \"\" {\n\t\tmountPath = v1.DefaultVaultKubernetesAuthMountPath\n\t}\n\n\turl := filepath.Join(mountPath, \"login\")\n\trequest := client.NewRequest(\"POST\", url)\n\terr = request.SetJSONBody(parameters)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error encoding Vault parameters: %s\", err.Error())\n\t}\n\n\tv.addVaultNamespaceToRequest(request)\n\n\tresp, err := client.RawRequest(request)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error calling Vault server: %s\", err.Error())\n\t}\n\n\tdefer resp.Body.Close()\n\tvaultResult := vault.Secret{}\n\terr = resp.DecodeJSON(&vaultResult)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to decode JSON payload: %s\", err.Error())\n\t}\n\n\ttoken, err := vaultResult.TokenID()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to read token: %s\", err.Error())\n\t}\n\n\treturn token, nil\n}\n\nfunc (v *Vault) Sys() *vault.Sys {\n\treturn v.client.Sys()\n}\n\nfunc extractCertificatesFromVaultCertificateSecret(secret *certutil.Secret) ([]byte, []byte, error) {\n\tparsedBundle, err := certutil.ParsePKIMap(secret.Data)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode response returned by vault: %s\", err)\n\t}\n\n\tvbundle, err := parsedBundle.ToCertBundle()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"unable to convert certificate bundle to PEM bundle: %s\", err.Error())\n\t}\n\n\tbundle, err := pki.ParseSingleCertificateChainPEM([]byte(\n\t\tstrings.Join(append(\n\t\t\tvbundle.CAChain,\n\t\t\tvbundle.IssuingCA,\n\t\t\tvbundle.Certificate,\n\t\t), \"\\n\")))\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse certificate chain from vault: %w\", err)\n\t}\n\n\treturn bundle.ChainPEM, bundle.CAPEM, nil\n}\n\nfunc (v *Vault) IsVaultInitializedAndUnsealed() error {\n\thealthURL := path.Join(\"\/v1\", \"sys\", \"health\")\n\thealthRequest := v.client.NewRequest(\"GET\", healthURL)\n\thealthResp, err := v.client.RawRequest(healthRequest)\n\t\/\/ 429 = if unsealed and standby\n\t\/\/ 472 = if disaster recovery mode replication secondary and active\n\t\/\/ 473 = if performance standby\n\tif err != nil && healthResp.StatusCode != 429 && healthResp.StatusCode != 472 && healthResp.StatusCode != 473 {\n\t\treturn err\n\t}\n\tdefer healthResp.Body.Close()\n\treturn nil\n}\n\nfunc (v *Vault) addVaultNamespaceToRequest(request *vault.Request) {\n\tvaultIssuer := v.issuer.GetSpec().Vault\n\tif vaultIssuer != nil && vaultIssuer.Namespace != \"\" {\n\t\tif request.Headers != nil {\n\t\t\trequest.Headers.Add(\"X-VAULT-NAMESPACE\", vaultIssuer.Namespace)\n\t\t} else {\n\t\t\tvaultReqHeaders := http.Header{}\n\t\t\tvaultReqHeaders.Add(\"X-VAULT-NAMESPACE\", vaultIssuer.Namespace)\n\t\t\trequest.Headers = vaultReqHeaders\n\t\t}\n\t}\n}\n<commit_msg>Vault internal client should check health conn err before checking response status<commit_after>\/*\nCopyright 2020 The cert-manager Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage vault\n\nimport (\n\t\"crypto\/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\tvault \"github.com\/hashicorp\/vault\/api\"\n\t\"github.com\/hashicorp\/vault\/sdk\/helper\/certutil\"\n\tcorelisters \"k8s.io\/client-go\/listers\/core\/v1\"\n\n\tv1 \"github.com\/jetstack\/cert-manager\/pkg\/apis\/certmanager\/v1\"\n\t\"github.com\/jetstack\/cert-manager\/pkg\/util\/pki\"\n)\n\nvar _ Interface = &Vault{}\n\n\/\/ ClientBuilder is a function type that returns a new Interface.\n\/\/ Can be used in tests to create a mock signer of Vault certificate requests.\ntype ClientBuilder func(namespace string, secretsLister corelisters.SecretLister,\n\tissuer v1.GenericIssuer) (Interface, error)\n\n\/\/ Interface implements various high level functionality related to connecting\n\/\/ with a Vault server, verifying its status and signing certificate request for\n\/\/ Vault's certificate.\n\/\/ TODO: Sys() is duplicated here and in Client interface\ntype Interface interface {\n\tSign(csrPEM []byte, duration time.Duration) (certPEM []byte, caPEM []byte, err error)\n\tSys() *vault.Sys\n\tIsVaultInitializedAndUnsealed() error\n}\n\n\/\/ Client implements functionality to talk to a Vault server.\ntype Client interface {\n\tNewRequest(method, requestPath string) *vault.Request\n\tRawRequest(r *vault.Request) (*vault.Response, error)\n\tSetToken(v string)\n\tToken() string\n\tSys() *vault.Sys\n}\n\n\/\/ Vault implements Interface and holds a Vault issuer, secrets lister and a\n\/\/ Vault client.\ntype Vault struct {\n\tsecretsLister corelisters.SecretLister\n\tissuer        v1.GenericIssuer\n\tnamespace     string\n\n\tclient Client\n}\n\n\/\/ New returns a new Vault instance with the given namespace, issuer and\n\/\/ secrets lister.\n\/\/ Returned errors may be network failures and should be considered for\n\/\/ retrying.\nfunc New(namespace string, secretsLister corelisters.SecretLister, issuer v1.GenericIssuer) (Interface, error) {\n\tv := &Vault{\n\t\tsecretsLister: secretsLister,\n\t\tnamespace:     namespace,\n\t\tissuer:        issuer,\n\t}\n\n\tcfg, err := v.newConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient, err := vault.NewClient(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error initializing Vault client: %s\", err.Error())\n\t}\n\n\tif err := v.setToken(client); err != nil {\n\t\treturn nil, err\n\t}\n\n\tv.client = client\n\n\treturn v, nil\n}\n\n\/\/ Sign will connect to a Vault instance to sign a certificate signing request.\nfunc (v *Vault) Sign(csrPEM []byte, duration time.Duration) (cert []byte, ca []byte, err error) {\n\tcsr, err := pki.DecodeX509CertificateRequestBytes(csrPEM)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode CSR for signing: %s\", err)\n\t}\n\n\tparameters := map[string]string{\n\t\t\"common_name\": csr.Subject.CommonName,\n\t\t\"alt_names\":   strings.Join(csr.DNSNames, \",\"),\n\t\t\"ip_sans\":     strings.Join(pki.IPAddressesToString(csr.IPAddresses), \",\"),\n\t\t\"uri_sans\":    strings.Join(pki.URLsToString(csr.URIs), \",\"),\n\t\t\"ttl\":         duration.String(),\n\t\t\"csr\":         string(csrPEM),\n\n\t\t\"exclude_cn_from_sans\": \"true\",\n\t}\n\n\tvaultIssuer := v.issuer.GetSpec().Vault\n\turl := path.Join(\"\/v1\", vaultIssuer.Path)\n\n\trequest := v.client.NewRequest(\"POST\", url)\n\n\tv.addVaultNamespaceToRequest(request)\n\n\tif err := request.SetJSONBody(parameters); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to build vault request: %s\", err)\n\t}\n\n\tresp, err := v.client.RawRequest(request)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to sign certificate by vault: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\tvaultResult := certutil.Secret{}\n\terr = resp.DecodeJSON(&vaultResult)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode response returned by vault: %s\", err)\n\t}\n\n\treturn extractCertificatesFromVaultCertificateSecret(&vaultResult)\n}\n\nfunc (v *Vault) setToken(client Client) error {\n\ttokenRef := v.issuer.GetSpec().Vault.Auth.TokenSecretRef\n\tif tokenRef != nil {\n\t\ttoken, err := v.tokenRef(tokenRef.Name, v.namespace, tokenRef.Key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclient.SetToken(token)\n\n\t\treturn nil\n\t}\n\n\tappRole := v.issuer.GetSpec().Vault.Auth.AppRole\n\tif appRole != nil {\n\t\ttoken, err := v.requestTokenWithAppRoleRef(client, appRole)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclient.SetToken(token)\n\n\t\treturn nil\n\t}\n\n\tkubernetesAuth := v.issuer.GetSpec().Vault.Auth.Kubernetes\n\tif kubernetesAuth != nil {\n\t\ttoken, err := v.requestTokenWithKubernetesAuth(client, kubernetesAuth)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading Kubernetes service account token from %s: %s\", kubernetesAuth.SecretRef.Name, err.Error())\n\t\t}\n\t\tclient.SetToken(token)\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"error initializing Vault client: tokenSecretRef, appRoleSecretRef, or Kubernetes auth role not set\")\n}\n\nfunc (v *Vault) newConfig() (*vault.Config, error) {\n\tcfg := vault.DefaultConfig()\n\tcfg.Address = v.issuer.GetSpec().Vault.Server\n\n\tcerts := v.issuer.GetSpec().Vault.CABundle\n\tif len(certs) == 0 {\n\t\treturn cfg, nil\n\t}\n\n\tcaCertPool := x509.NewCertPool()\n\tok := caCertPool.AppendCertsFromPEM(certs)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"error loading Vault CA bundle\")\n\t}\n\n\tcfg.HttpClient.Transport.(*http.Transport).TLSClientConfig.RootCAs = caCertPool\n\n\treturn cfg, nil\n}\n\nfunc (v *Vault) tokenRef(name, namespace, key string) (string, error) {\n\tsecret, err := v.secretsLister.Secrets(namespace).Get(name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif key == \"\" {\n\t\tkey = v1.DefaultVaultTokenAuthSecretKey\n\t}\n\n\tkeyBytes, ok := secret.Data[key]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"no data for %q in secret '%s\/%s'\", key, name, namespace)\n\t}\n\n\ttoken := string(keyBytes)\n\ttoken = strings.TrimSpace(token)\n\n\treturn token, nil\n}\n\nfunc (v *Vault) appRoleRef(appRole *v1.VaultAppRole) (roleId, secretId string, err error) {\n\troleId = strings.TrimSpace(appRole.RoleId)\n\n\tsecret, err := v.secretsLister.Secrets(v.namespace).Get(appRole.SecretRef.Name)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\n\tkey := appRole.SecretRef.Key\n\n\tkeyBytes, ok := secret.Data[key]\n\tif !ok {\n\t\treturn \"\", \"\", fmt.Errorf(\"no data for %q in secret '%s\/%s'\", key, v.namespace, appRole.SecretRef.Name)\n\t}\n\n\tsecretId = string(keyBytes)\n\tsecretId = strings.TrimSpace(secretId)\n\n\treturn roleId, secretId, nil\n}\n\nfunc (v *Vault) requestTokenWithAppRoleRef(client Client, appRole *v1.VaultAppRole) (string, error) {\n\troleId, secretId, err := v.appRoleRef(appRole)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tparameters := map[string]string{\n\t\t\"role_id\":   roleId,\n\t\t\"secret_id\": secretId,\n\t}\n\n\tauthPath := appRole.Path\n\tif authPath == \"\" {\n\t\tauthPath = \"approle\"\n\t}\n\n\turl := path.Join(\"\/v1\", \"auth\", authPath, \"login\")\n\n\trequest := client.NewRequest(\"POST\", url)\n\n\terr = request.SetJSONBody(parameters)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error encoding Vault parameters: %s\", err.Error())\n\t}\n\n\tv.addVaultNamespaceToRequest(request)\n\n\tresp, err := client.RawRequest(request)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error logging in to Vault server: %s\", err.Error())\n\t}\n\n\tdefer resp.Body.Close()\n\n\tvaultResult := vault.Secret{}\n\tif err := resp.DecodeJSON(&vaultResult); err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to decode JSON payload: %s\", err.Error())\n\t}\n\n\ttoken, err := vaultResult.TokenID()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to read token: %s\", err.Error())\n\t}\n\n\tif token == \"\" {\n\t\treturn \"\", errors.New(\"no token returned\")\n\t}\n\n\treturn token, nil\n}\n\nfunc (v *Vault) requestTokenWithKubernetesAuth(client Client, kubernetesAuth *v1.VaultKubernetesAuth) (string, error) {\n\tsecret, err := v.secretsLister.Secrets(v.namespace).Get(kubernetesAuth.SecretRef.Name)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tkey := kubernetesAuth.SecretRef.Key\n\tif key == \"\" {\n\t\tkey = v1.DefaultVaultTokenAuthSecretKey\n\t}\n\n\tkeyBytes, ok := secret.Data[key]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"no data for %q in secret '%s\/%s'\", key, v.namespace, kubernetesAuth.SecretRef.Name)\n\t}\n\n\tjwt := string(keyBytes)\n\n\tparameters := map[string]string{\n\t\t\"role\": kubernetesAuth.Role,\n\t\t\"jwt\":  jwt,\n\t}\n\n\tmountPath := kubernetesAuth.Path\n\tif mountPath == \"\" {\n\t\tmountPath = v1.DefaultVaultKubernetesAuthMountPath\n\t}\n\n\turl := filepath.Join(mountPath, \"login\")\n\trequest := client.NewRequest(\"POST\", url)\n\terr = request.SetJSONBody(parameters)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error encoding Vault parameters: %s\", err.Error())\n\t}\n\n\tv.addVaultNamespaceToRequest(request)\n\n\tresp, err := client.RawRequest(request)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error calling Vault server: %s\", err.Error())\n\t}\n\n\tdefer resp.Body.Close()\n\tvaultResult := vault.Secret{}\n\terr = resp.DecodeJSON(&vaultResult)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to decode JSON payload: %s\", err.Error())\n\t}\n\n\ttoken, err := vaultResult.TokenID()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to read token: %s\", err.Error())\n\t}\n\n\treturn token, nil\n}\n\nfunc (v *Vault) Sys() *vault.Sys {\n\treturn v.client.Sys()\n}\n\nfunc extractCertificatesFromVaultCertificateSecret(secret *certutil.Secret) ([]byte, []byte, error) {\n\tparsedBundle, err := certutil.ParsePKIMap(secret.Data)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode response returned by vault: %s\", err)\n\t}\n\n\tvbundle, err := parsedBundle.ToCertBundle()\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"unable to convert certificate bundle to PEM bundle: %s\", err.Error())\n\t}\n\n\tbundle, err := pki.ParseSingleCertificateChainPEM([]byte(\n\t\tstrings.Join(append(\n\t\t\tvbundle.CAChain,\n\t\t\tvbundle.IssuingCA,\n\t\t\tvbundle.Certificate,\n\t\t), \"\\n\")))\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to parse certificate chain from vault: %w\", err)\n\t}\n\n\treturn bundle.ChainPEM, bundle.CAPEM, nil\n}\n\nfunc (v *Vault) IsVaultInitializedAndUnsealed() error {\n\thealthURL := path.Join(\"\/v1\", \"sys\", \"health\")\n\thealthRequest := v.client.NewRequest(\"GET\", healthURL)\n\thealthResp, err := v.client.RawRequest(healthRequest)\n\n\tif healthResp != nil {\n\t\tdefer healthResp.Body.Close()\n\t}\n\n\t\/\/ 429 = if unsealed and standby\n\t\/\/ 472 = if disaster recovery mode replication secondary and active\n\t\/\/ 473 = if performance standby\n\tif err != nil {\n\t\tswitch {\n\t\tcase healthResp == nil:\n\t\t\treturn err\n\t\tcase healthResp.StatusCode == 429, healthResp.StatusCode == 472, healthResp.StatusCode == 473:\n\t\t\treturn nil\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"error calling Vault %s: %w\", healthURL, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (v *Vault) addVaultNamespaceToRequest(request *vault.Request) {\n\tvaultIssuer := v.issuer.GetSpec().Vault\n\tif vaultIssuer != nil && vaultIssuer.Namespace != \"\" {\n\t\tif request.Headers != nil {\n\t\t\trequest.Headers.Add(\"X-VAULT-NAMESPACE\", vaultIssuer.Namespace)\n\t\t} else {\n\t\t\tvaultReqHeaders := http.Header{}\n\t\t\tvaultReqHeaders.Add(\"X-VAULT-NAMESPACE\", vaultIssuer.Namespace)\n\t\t\trequest.Headers = vaultReqHeaders\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/nextgearcapital\/pepper\/pkg\/device42\"\n\t\"github.com\/nextgearcapital\/pepper\/pkg\/log\"\n\t\"github.com\/nextgearcapital\/pepper\/pkg\/salt\"\n\t\"github.com\/nextgearcapital\/pepper\/template\/vsphere\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tprofile    string\n\troles      string\n\tosTemplate string\n\tipam       bool\n)\n\nfunc init() {\n\tRootCmd.AddCommand(deployCmd)\n\n\tdeployCmd.Flags().StringVarP(&profile, \"profile\", \"p\", \"\", \"Profile to generate and output to \/etc\/salt\/cloud.profiles.d for salt-cloud to use\")\n\tdeployCmd.Flags().StringVarP(&roles, \"roles\", \"r\", \"\", \"List of roles to assign to the host in D42 [eg: dcos,dcos-master]\")\n\tdeployCmd.Flags().StringVarP(&osTemplate, \"template\", \"t\", \"\", \"Which OS template you want to use [eg: Ubuntu, CentOS, someothertemplatename]\")\n\tdeployCmd.Flags().BoolVarP(&ipam, \"no-ipam\", \"\", false, \"Whether or not to use Device42 IPAM [This is only used internally]\")\n\tdeployCmd.Flags().BoolVarP(&log.IsDebugging, \"debug\", \"d\", false, \"Turn debugging on\")\n}\n\nvar deployCmd = &cobra.Command{\n\tUse:   \"deploy\",\n\tShort: \"Deploy VM's via salt-cloud\",\n\tLong: `pepper is a wrapper around salt-cloud that will generate salt-cloud profiles based on information you provide in profile configs.\nProfile configs live in \"\/etc\/pepper\/config.d\/{platform}\/{environment}. Pepper is opinionated and looks at the profile you pass in as it's source\nof truth. For example: If you pass in \"vmware-dev-large\" as the profile, it will look for your profile config in \"\/etc\/pepper\/config.d\/vmware\/large.yaml\".\nThis allows for maximum flexibility due to the fact that everyone has different environments and may have some sort of naming scheme associated with them\nso Pepper makes no assumptions on that. Pepper does however make assumptions on your instance type. [eg: nano, micro, small, medium, etc] Although these\noptions are available to you, you are free to override them as you see fit.\nFor example:\n\nProvision new host web01 (Ubuntu) in the dev environment from the nano profile using vmware as a provider:\n\n$ pepper deploy -p vmware-dev-nano -t Ubuntu web01\n\nOr alternatively:\n\n$ pepper deploy --profile vmware-dev-nano --template Ubuntu web01\n\nProvision new host web02 (CentOS) in the prd environment from the large profile using vmware as a provider:\n\n$ pepper deploy -p vmware-prd-large -t CentOS web02\n\nProvision new host web03 (Ubuntu) in the uat environment from the hyper profile using vmware as a provider:\n\n$ pepper deploy -p vmware-uat-hyper -t Ubuntu web03\n\nAre you getting this yet?\n\n$ pepper deploy -p vmware-prd-mid -t Ubuntu -r dcos,dcos-master dcos01 dcos02 dcos03`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tif profile == \"\" {\n\t\t\tlog.Die(\"You didn't specify a profile.\")\n\t\t} else if osTemplate == \"\" {\n\t\t\tlog.Die(\"You didn't specify an OS template.\")\n\t\t} else if len(args) == 0 {\n\t\t\tlog.Die(\"You didn't specify any hosts.\")\n\t\t}\n\n\t\tsplitProfile := strings.Split(profile, \"-\")\n\n\t\t\/\/ These will be the basis for how the profile gets generated.\n\t\tplatform := splitProfile[0]\n\t\tenvironment := splitProfile[1]\n\t\tinstancetype := splitProfile[2]\n\n\t\t\/\/ Nothing really gained here it just makes the code more readable.\n\t\thosts := args\n\n\t\tvar ipAddress string\n\t\tvar serviceLevel string\n\n\t\tfor _, host := range hosts {\n\t\t\tif ipam != true {\n\t\t\t\tif err := device42.ReadConfig(environment); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\t\/\/ Get a new IP\n\t\t\t\tnewIP, err := device42.GetNextIP(device42.IPRange)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tipAddress = newIP\n\t\t\t\t\/\/ Create the Device\n\t\t\t\tif err := device42.CreateDevice(host, serviceLevel); err != nil {\n\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\t\/\/ Reserve IP\n\t\t\t\tif err := device42.ReserveIP(newIP, host); err != nil {\n\t\t\t\t\tif err = device42.CleanDeviceAndIP(newIP, host); err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\t\/\/ Update custom fields\n\t\t\t\tif err := device42.UpdateCustomFields(host, \"roles\", roles); err != nil {\n\t\t\t\t\tif err = device42.CleanDeviceAndIP(newIP, host); err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch platform {\n\t\t\tcase \"vmware\":\n\t\t\t\tvar vsphere vsphere.ProfileConfig\n\t\t\t\tif err := vsphere.Prepare(platform, environment, instancetype, osTemplate, ipAddress); err != nil {\n\t\t\t\t\tif err = device42.CleanDeviceAndIP(ipAddress, host); err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif err := vsphere.Generate(); err != nil {\n\t\t\t\t\tif err = device42.CleanDeviceAndIP(ipAddress, host); err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif err := salt.Provision(profile, host); err != nil {\n\t\t\t\t\tif err = device42.CleanDeviceAndIP(ipAddress, host); err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif err := vsphere.Remove(); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlog.Die(\"I don't recognize this platform!\")\n\t\t\t}\n\t\t}\n\t},\n}\n<commit_msg>Keep variable consistent<commit_after>package cmd\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/nextgearcapital\/pepper\/pkg\/device42\"\n\t\"github.com\/nextgearcapital\/pepper\/pkg\/log\"\n\t\"github.com\/nextgearcapital\/pepper\/pkg\/salt\"\n\t\"github.com\/nextgearcapital\/pepper\/template\/vsphere\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tprofile    string\n\troles      string\n\tosTemplate string\n\tipam       bool\n)\n\nfunc init() {\n\tRootCmd.AddCommand(deployCmd)\n\n\tdeployCmd.Flags().StringVarP(&profile, \"profile\", \"p\", \"\", \"Profile to generate and output to \/etc\/salt\/cloud.profiles.d for salt-cloud to use\")\n\tdeployCmd.Flags().StringVarP(&roles, \"roles\", \"r\", \"\", \"List of roles to assign to the host in D42 [eg: dcos,dcos-master]\")\n\tdeployCmd.Flags().StringVarP(&osTemplate, \"template\", \"t\", \"\", \"Which OS template you want to use [eg: Ubuntu, CentOS, someothertemplatename]\")\n\tdeployCmd.Flags().BoolVarP(&ipam, \"no-ipam\", \"\", false, \"Whether or not to use Device42 IPAM [This is only used internally]\")\n\tdeployCmd.Flags().BoolVarP(&log.IsDebugging, \"debug\", \"d\", false, \"Turn debugging on\")\n}\n\nvar deployCmd = &cobra.Command{\n\tUse:   \"deploy\",\n\tShort: \"Deploy VM's via salt-cloud\",\n\tLong: `pepper is a wrapper around salt-cloud that will generate salt-cloud profiles based on information you provide in profile configs.\nProfile configs live in \"\/etc\/pepper\/config.d\/{platform}\/{environment}. Pepper is opinionated and looks at the profile you pass in as it's source\nof truth. For example: If you pass in \"vmware-dev-large\" as the profile, it will look for your profile config in \"\/etc\/pepper\/config.d\/vmware\/large.yaml\".\nThis allows for maximum flexibility due to the fact that everyone has different environments and may have some sort of naming scheme associated with them\nso Pepper makes no assumptions on that. Pepper does however make assumptions on your instance type. [eg: nano, micro, small, medium, etc] Although these\noptions are available to you, you are free to override them as you see fit.\nFor example:\n\nProvision new host web01 (Ubuntu) in the dev environment from the nano profile using vmware as a provider:\n\n$ pepper deploy -p vmware-dev-nano -t Ubuntu web01\n\nOr alternatively:\n\n$ pepper deploy --profile vmware-dev-nano --template Ubuntu web01\n\nProvision new host web02 (CentOS) in the prd environment from the large profile using vmware as a provider:\n\n$ pepper deploy -p vmware-prd-large -t CentOS web02\n\nProvision new host web03 (Ubuntu) in the uat environment from the hyper profile using vmware as a provider:\n\n$ pepper deploy -p vmware-uat-hyper -t Ubuntu web03\n\nAre you getting this yet?\n\n$ pepper deploy -p vmware-prd-mid -t Ubuntu -r dcos,dcos-master dcos01 dcos02 dcos03`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tif profile == \"\" {\n\t\t\tlog.Die(\"You didn't specify a profile.\")\n\t\t} else if osTemplate == \"\" {\n\t\t\tlog.Die(\"You didn't specify an OS template.\")\n\t\t} else if len(args) == 0 {\n\t\t\tlog.Die(\"You didn't specify any hosts.\")\n\t\t}\n\n\t\tsplitProfile := strings.Split(profile, \"-\")\n\n\t\t\/\/ These will be the basis for how the profile gets generated.\n\t\tplatform := splitProfile[0]\n\t\tenvironment := splitProfile[1]\n\t\tinstancetype := splitProfile[2]\n\n\t\t\/\/ Nothing really gained here it just makes the code more readable.\n\t\thosts := args\n\n\t\tvar ipAddress string\n\t\tvar serviceLevel string\n\n\t\tfor _, host := range hosts {\n\t\t\tif ipam != true {\n\t\t\t\tif err := device42.ReadConfig(environment); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\t\/\/ Get a new IP\n\t\t\t\tnewIP, err := device42.GetNextIP(device42.IPRange)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tipAddress = newIP\n\t\t\t\t\/\/ Create the Device\n\t\t\t\tif err := device42.CreateDevice(host, serviceLevel); err != nil {\n\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\t\/\/ Reserve IP\n\t\t\t\tif err := device42.ReserveIP(ipAddress, host); err != nil {\n\t\t\t\t\tif err = device42.CleanDeviceAndIP(ipAddress, host); err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\t\/\/ Update custom fields\n\t\t\t\tif err := device42.UpdateCustomFields(host, \"roles\", roles); err != nil {\n\t\t\t\t\tif err = device42.CleanDeviceAndIP(ipAddress, host); err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch platform {\n\t\t\tcase \"vmware\":\n\t\t\t\tvar vsphere vsphere.ProfileConfig\n\t\t\t\tif err := vsphere.Prepare(platform, environment, instancetype, osTemplate, ipAddress); err != nil {\n\t\t\t\t\tif err = device42.CleanDeviceAndIP(ipAddress, host); err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif err := vsphere.Generate(); err != nil {\n\t\t\t\t\tif err = device42.CleanDeviceAndIP(ipAddress, host); err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif err := salt.Provision(profile, host); err != nil {\n\t\t\t\t\tif err = device42.CleanDeviceAndIP(ipAddress, host); err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif err := vsphere.Remove(); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlog.Die(\"I don't recognize this platform!\")\n\t\t\t}\n\t\t}\n\t},\n}\n<|endoftext|>"}
{"text":"<commit_before>package lwcache\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestSetAndGet(t *testing.T) {\n\tassert := assert.New(t)\n\tc := New(\"test-1\")\n\n\tkey := \"test-1\"\n\texpect := \"test-1-value\"\n\n\tc.Set(key, expect, 500*time.Millisecond)\n\tactual, ok := c.Get(key)\n\tassert.True(ok)\n\tassert.Equal(expect, actual)\n\n\t\/\/ after expire\n\ttime.Sleep(550 * time.Millisecond)\n\tactual, ok = c.Get(key)\n\tassert.False(ok)\n\tassert.Equal(nil, actual)\n}\n\nfunc TestSetExpire(t *testing.T) {\n\tassert := assert.New(t)\n\tc := New(\"test-2\")\n\n\tkey := \"test-2\"\n\texpect := \"test-1-value\"\n\n\tc.Set(key, expect, 500*time.Millisecond)\n\tactual, ok := c.Get(key)\n\tassert.True(ok)\n\tassert.Equal(expect, actual)\n\n\tc.SetExpire(key, 1*time.Second)\n\t\/\/ after first expiration\n\ttime.Sleep(550 * time.Millisecond)\n\tactual, ok = c.Get(key)\n\tassert.True(ok)\n\tassert.Equal(expect, actual)\n}\n\nfunc TestSetRefresher(t *testing.T) {\n\tassert := assert.New(t)\n\tc := New(\"test-4\")\n\n\tkey := \"test-4\"\n\texpect := 0\n\trefresher := func(c Cache, key interface{}, currentValue interface{}) (interface{}, error) {\n\t\tnum, ok := currentValue.(int)\n\t\tif ok {\n\t\t\treturn num + 1, nil\n\t\t}\n\t\treturn 0, errors.New(\"refresh failed\")\n\t}\n\n\tc.Set(key, expect, 10*time.Second)\n\tc.SetRefresher(refresher)\n\tc.StartRefresher(key, 1*time.Second)\n\n\tfor i := 0; i < 5; i++ {\n\t\tactual, ok := c.Get(key)\n\t\tassert.True(ok)\n\t\tassert.Equal(expect, actual, fmt.Sprintf(\"Test No. %d\", i+1))\n\t\ttime.Sleep(1050 * time.Millisecond)\n\t\texpect++\n\t}\n}\n\nfunc TestSetRefresher_OnExpired(t *testing.T) {\n\tassert := assert.New(t)\n\tc := New(\"test-5\")\n\n\tkey := \"test-5\"\n\texpect := 0\n\trefresher := func(c Cache, key interface{}, currentValue interface{}) (interface{}, error) {\n\t\tnum, ok := currentValue.(int)\n\t\tif ok {\n\t\t\treturn num + 1, nil\n\t\t}\n\t\treturn 0, errors.New(\"refresh failed\")\n\t}\n\n\tc.Set(key, expect, 2*time.Second)\n\tc.SetRefresher(refresher)\n\tc.StartRefresher(key, 1*time.Second)\n\n\tactual, ok := c.Get(key)\n\tassert.True(ok)\n\tassert.Equal(expect, actual)\n\ttime.Sleep(1500 * time.Millisecond)\n\n\t\/\/ refresh\n\tactual, ok = c.Get(key)\n\tassert.True(ok)\n\tassert.Equal(expect+1, actual)\n\ttime.Sleep(1500 * time.Millisecond)\n\n\t\/\/ expire\n\tactual, ok = c.Get(key)\n\tassert.False(ok)\n\tassert.Equal(nil, actual)\n}\n\nfunc TestSetRefresher_OnRefreshError(t *testing.T) {\n\tassert := assert.New(t)\n\tc := New(\"test-3\")\n\n\tkey := \"test-3\"\n\texpect := 0\n\trefresher := func(c Cache, key interface{}, currentValue interface{}) (interface{}, error) {\n\t\treturn 0, errors.New(\"refresh failed\")\n\t}\n\n\tc.Set(key, expect, 10*time.Second)\n\tc.SetRefresher(refresher)\n\tc.StartRefresher(key, 1*time.Second)\n\n\tfor i := 0; i < 5; i++ {\n\t\tactual, ok := c.Get(key)\n\t\tassert.True(ok)\n\t\tassert.Equal(expect, actual, fmt.Sprintf(\"Test No. %d\", i+1))\n\t\ttime.Sleep(1050 * time.Millisecond)\n\t}\n}\n<commit_msg>modify test<commit_after>package lwcache\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestSetAndGet(t *testing.T) {\n\tassert := assert.New(t)\n\tc := New(\"test-1\")\n\n\tkey := \"test-1\"\n\texpect := \"test-1-value\"\n\n\tc.Set(key, expect, 500*time.Millisecond)\n\tactual, ok := c.Get(key)\n\tassert.True(ok)\n\tassert.Equal(expect, actual)\n\n\t\/\/ after expire\n\ttime.Sleep(550 * time.Millisecond)\n\tactual, ok = c.Get(key)\n\tassert.False(ok)\n\tassert.Equal(nil, actual)\n}\n\nfunc TestSetExpire(t *testing.T) {\n\tassert := assert.New(t)\n\tc := New(\"test-2\")\n\n\tkey := \"test-2\"\n\texpect := \"test-1-value\"\n\n\tc.Set(key, expect, 500*time.Millisecond)\n\tactual, ok := c.Get(key)\n\tassert.True(ok)\n\tassert.Equal(expect, actual)\n\n\tc.SetExpire(key, 1*time.Second)\n\t\/\/ after first expiration\n\ttime.Sleep(550 * time.Millisecond)\n\tactual, ok = c.Get(key)\n\tassert.True(ok)\n\tassert.Equal(expect, actual)\n}\n\nfunc TestSetRefresher(t *testing.T) {\n\tassert := assert.New(t)\n\tc := New(\"test-4\")\n\n\tkey := \"test-4\"\n\texpect := 0\n\trefresher := func(c Cache, key interface{}, currentValue interface{}) (interface{}, error) {\n\t\tnum, ok := currentValue.(int)\n\t\tif ok {\n\t\t\treturn num + 1, nil\n\t\t}\n\t\treturn 0, errors.New(\"refresh failed\")\n\t}\n\n\tc.Set(key, expect, 10*time.Second)\n\tc.SetRefresher(refresher)\n\tc.StartRefresher(key, 1*time.Second)\n\n\tfor i := 0; i < 5; i++ {\n\t\tactual, ok := c.Get(key)\n\t\tassert.True(ok)\n\t\tassert.Equal(expect, actual, fmt.Sprintf(\"Test No. %d\", i+1))\n\t\ttime.Sleep(1050 * time.Millisecond)\n\t\texpect++\n\t}\n\n\tc.StopRefresher(key)\n\tfor i := 0; i < 2; i++ {\n\t\ttime.Sleep(1050 * time.Millisecond)\n\t\tactual, ok := c.Get(key)\n\t\tassert.True(ok)\n\t\tassert.Equal(expect, actual) \/\/ expect not changed\n\t}\n}\n\nfunc TestSetRefresher_OnExpired(t *testing.T) {\n\tassert := assert.New(t)\n\tc := New(\"test-5\")\n\n\tkey := \"test-5\"\n\texpect := 0\n\trefresher := func(c Cache, key interface{}, currentValue interface{}) (interface{}, error) {\n\t\tnum, ok := currentValue.(int)\n\t\tif ok {\n\t\t\treturn num + 1, nil\n\t\t}\n\t\treturn 0, errors.New(\"refresh failed\")\n\t}\n\n\tc.Set(key, expect, 2*time.Second)\n\tc.SetRefresher(refresher)\n\tc.StartRefresher(key, 1*time.Second)\n\n\tactual, ok := c.Get(key)\n\tassert.True(ok)\n\tassert.Equal(expect, actual)\n\ttime.Sleep(1500 * time.Millisecond)\n\n\t\/\/ refresh\n\tactual, ok = c.Get(key)\n\tassert.True(ok)\n\tassert.Equal(expect+1, actual)\n\ttime.Sleep(1500 * time.Millisecond)\n\n\t\/\/ expire\n\tactual, ok = c.Get(key)\n\tassert.False(ok)\n\tassert.Equal(nil, actual)\n}\n\nfunc TestSetRefresher_OnRefreshError(t *testing.T) {\n\tassert := assert.New(t)\n\tc := New(\"test-3\")\n\n\tkey := \"test-3\"\n\texpect := 0\n\trefresher := func(c Cache, key interface{}, currentValue interface{}) (interface{}, error) {\n\t\treturn 0, errors.New(\"refresh failed\")\n\t}\n\n\tc.Set(key, expect, 10*time.Second)\n\tc.SetRefresher(refresher)\n\tc.StartRefresher(key, 1*time.Second)\n\n\tfor i := 0; i < 5; i++ {\n\t\tactual, ok := c.Get(key)\n\t\tassert.True(ok)\n\t\tassert.Equal(expect, actual, fmt.Sprintf(\"Test No. %d\", i+1))\n\t\ttime.Sleep(1050 * time.Millisecond)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package chip8\n\nimport \"testing\"\n\nfunc checkHex(t *testing.T, subject string, got, want uint16) {\n\tif got != want {\n\t\tt.Errorf(\"%s => 0x%04X; want 0x%04X\", subject, got, want)\n\t}\n}\n\nfunc TestCPU_Step(t *testing.T) {\n\tc := NewCPU(nil)\n\tc.Memory[200] = 0xA1\n\tc.Memory[201] = 0x00\n\n\tif err := c.Step(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcheckHex(t, \"PC\", c.PC, uint16(202))\n}\n\nfunc TestCPU_Dispatch(t *testing.T) {\n\ttests := []struct {\n\t\top     uint16\n\t\tbefore func(*CPU)\n\t\tcheck  func(*CPU)\n\t}{\n\t\t{\n\t\t\tuint16(0x2100),\n\t\t\tnil,\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"Stack[0]\", c.Stack[0], uint16(0xC8))\n\t\t\t\tcheckHex(t, \"SP\", uint16(c.SP), uint16(0x1))\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(0x100))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x3123),\n\t\t\tnil,\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(200))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x3103),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(202))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x4123),\n\t\t\tnil,\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(202))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x4103),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(200))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x5120),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t\tc.V[2] = 0x04\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(200))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x5120),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t\tc.V[2] = 0x03\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(202))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x6102),\n\t\t\tnil,\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x02))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x7102),\n\t\t\tnil,\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x02))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x7102),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x01\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x03))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8120),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[2] = 0x01\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x01))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8121),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x10\n\t\t\t\tc.V[2] = 0x01\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x11))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8122),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x10\n\t\t\t\tc.V[2] = 0x01\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x00))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8123),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x01\n\t\t\t\tc.V[2] = 0x01\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x00))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8124),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x01\n\t\t\t\tc.V[2] = 0x01\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x2))\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x0))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8124),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0xFF\n\t\t\t\tc.V[2] = 0x03\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x2))\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x1))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8125),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0xFF\n\t\t\t\tc.V[2] = 0x03\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x1))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0xFC))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8125),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x02\n\t\t\t\tc.V[2] = 0x03\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x0))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0xFF))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8126),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x1))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x1))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8126),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x02\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x0))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x1))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8127),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t\tc.V[2] = 0xFF\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x1))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0xFC))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8127),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t\tc.V[2] = 0x02\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x0))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0xFF))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x812E),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x01\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x0))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x2))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x812E),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x81\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x1))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x2))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x9120),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x01\n\t\t\t\tc.V[2] = 0x02\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(202))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x9120),\n\t\t\tfunc(c *CPU) {\n\t\t\t\tc.V[1] = 0x01\n\t\t\t\tc.V[2] = 0x01\n\t\t\t},\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(200))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0xA100),\n\t\t\tnil,\n\t\t\tfunc(c *CPU) {\n\t\t\t\tcheckHex(t, \"I\", c.I, uint16(0x100))\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tc := NewCPU(nil)\n\t\tif tt.before != nil {\n\t\t\ttt.before(c)\n\t\t}\n\t\tc.Dispatch(tt.op)\n\t\ttt.check(c)\n\n\t\tif t.Failed() {\n\t\t\tt.Logf(\"==============\")\n\t\t\tt.Logf(\"Opcode: 0x%04X\", tt.op)\n\t\t\tt.Logf(\"CPU: %v\", c)\n\t\t\tt.Logf(\"==============\")\n\t\t\tt.FailNow()\n\t\t}\n\t}\n}\n\nfunc TestCPU_op(t *testing.T) {\n\tc := NewCPU(nil)\n\tc.Memory[200] = 0xA2\n\tc.Memory[201] = 0xF0\n\n\tcheckHex(t, \"op\", c.op(), uint16(0xA2F0))\n}\n<commit_msg>Cleanup tests.<commit_after>package chip8\n\nimport \"testing\"\n\nvar opcodeTests = map[string][]struct {\n\top     uint16\n\tbefore func(*testing.T, *CPU)\n\tcheck  func(*testing.T, *CPU)\n}{\n\t\"2nnn - CALL addr\": {\n\t\t{\n\t\t\tuint16(0x2100),\n\t\t\tnil,\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"Stack[0]\", c.Stack[0], uint16(0xC8))\n\t\t\t\tcheckHex(t, \"SP\", uint16(c.SP), uint16(0x1))\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(0x100))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"3xkk - SE Vx, byte\": {\n\t\t{\n\t\t\tuint16(0x3123),\n\t\t\tnil,\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(200))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x3103),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(202))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"4xkk - SNE Vx, byte\": {\n\t\t{\n\t\t\tuint16(0x4123),\n\t\t\tnil,\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(202))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x4103),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(200))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"5xy0 - SE Vx, Vy\": {\n\t\t{\n\t\t\tuint16(0x5120),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t\tc.V[2] = 0x04\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(200))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x5120),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t\tc.V[2] = 0x03\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(202))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"6xkk - LD Vx, byte\": {\n\t\t{\n\t\t\tuint16(0x6102),\n\t\t\tnil,\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x02))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"7xkk - ADD Vx, byte\": {\n\t\t{\n\t\t\tuint16(0x7102),\n\t\t\tnil,\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x02))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x7102),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x01\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x03))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"8xy0 - LD Vx, Vy\": {\n\t\t{\n\t\t\tuint16(0x8120),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[2] = 0x01\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x01))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"8xy1 - OR Vx, Vy\": {\n\t\t{\n\t\t\tuint16(0x8121),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x10\n\t\t\t\tc.V[2] = 0x01\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x11))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"8xy2 - AND Vx, Vy\": {\n\t\t{\n\t\t\tuint16(0x8122),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x10\n\t\t\t\tc.V[2] = 0x01\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x00))\n\t\t\t},\n\t\t},\n\t},\n\n\t\/\/ TODO\n\t\"Set Vx = Vx AND Vy\": {\n\t\t{\n\t\t\tuint16(0x8123),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x01\n\t\t\t\tc.V[2] = 0x01\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x00))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"8xy4 - ADD Vx, Vy\": {\n\t\t{\n\t\t\tuint16(0x8124),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x01\n\t\t\t\tc.V[2] = 0x01\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x2))\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x0))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8124),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0xFF\n\t\t\t\tc.V[2] = 0x03\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x2))\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x1))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"8xy5 - SUB Vx, Vy\": {\n\t\t{\n\t\t\tuint16(0x8125),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0xFF\n\t\t\t\tc.V[2] = 0x03\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x1))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0xFC))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8125),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x02\n\t\t\t\tc.V[2] = 0x03\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x0))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0xFF))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"8xy6 - SHR Vx {, Vy}\": {\n\t\t{\n\t\t\tuint16(0x8126),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x1))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x1))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8126),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x02\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x0))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x1))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"8xy7 - SUBN Vx, Vy\": {\n\t\t{\n\t\t\tuint16(0x8127),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t\tc.V[2] = 0xFF\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x1))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0xFC))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x8127),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x03\n\t\t\t\tc.V[2] = 0x02\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x0))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0xFF))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"8xyE - SHL Vx {, Vy}\": {\n\t\t{\n\t\t\tuint16(0x812E),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x01\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x0))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x2))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x812E),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x81\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"VF\", uint16(c.V[0xF]), uint16(0x1))\n\t\t\t\tcheckHex(t, \"V[1]\", uint16(c.V[1]), uint16(0x2))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"9xy0 - SNE Vx, Vy\": {\n\t\t{\n\t\t\tuint16(0x9120),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x01\n\t\t\t\tc.V[2] = 0x02\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(202))\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tuint16(0x9120),\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tc.V[1] = 0x01\n\t\t\t\tc.V[2] = 0x01\n\t\t\t},\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"PC\", c.PC, uint16(200))\n\t\t\t},\n\t\t},\n\t},\n\n\t\"Annn - LD I, addr\": {\n\t\t{\n\t\t\tuint16(0xA100),\n\t\t\tnil,\n\t\t\tfunc(t *testing.T, c *CPU) {\n\t\t\t\tcheckHex(t, \"I\", c.I, uint16(0x100))\n\t\t\t},\n\t\t},\n\t},\n}\n\nfunc checkHex(t *testing.T, subject string, got, want uint16) {\n\tif got != want {\n\t\tt.Errorf(\"%s => 0x%04X; want 0x%04X\", subject, got, want)\n\t}\n}\n\nfunc TestCPU_Step(t *testing.T) {\n\tc := NewCPU(nil)\n\tc.Memory[200] = 0xA1\n\tc.Memory[201] = 0x00\n\n\tif err := c.Step(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcheckHex(t, \"PC\", c.PC, uint16(202))\n}\n\nfunc TestOpcodes(t *testing.T) {\n\tfor i, tests := range opcodeTests {\n\t\tfor _, tt := range tests {\n\t\t\tc := NewCPU(nil)\n\t\t\tif tt.before != nil {\n\t\t\t\ttt.before(t, c)\n\t\t\t}\n\t\t\tc.Dispatch(tt.op)\n\t\t\ttt.check(t, c)\n\n\t\t\tif t.Failed() {\n\t\t\t\tt.Logf(\"==============\")\n\t\t\t\tt.Logf(\"Instruction: %s\", i)\n\t\t\t\tt.Logf(\"Opcode: 0x%04X\", tt.op)\n\t\t\t\tt.Logf(\"CPU: %v\", c)\n\t\t\t\tt.Logf(\"==============\")\n\t\t\t\tt.FailNow()\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestCPU_op(t *testing.T) {\n\tc := NewCPU(nil)\n\tc.Memory[200] = 0xA2\n\tc.Memory[201] = 0xF0\n\n\tcheckHex(t, \"op\", c.op(), uint16(0xA2F0))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017, OpenCensus Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n\/*\nPackage stats contains support for OpenCensus stats collection.\n\nOpenCensus allows users to create typed measures, record measurements,\naggregate the collected data, and export the aggregated data.\n\nMeasures\n\nA measure represents a type of metric to be tracked and recorded.\nFor example, latency, request Mb\/s, and response Mb\/s are measures\nto collect from a server.\n\nEach measure needs to be registered before being used. Measure\nconstructors such as NewMeasureInt64 and NewMeasureFloat64 automatically\nregisters the measure by the given name. Each registered measure needs\nto be unique by name. Measures also have a description and a unit.\n\nLibraries can define and export measures for their end users to\ncreate views and collect instrumentation data.\n\nRecording measurements\n\nMeasurement is a data point to be collected for a measure. For example,\nfor a latency (ms) measure, 100 is a measurement that represents a 100ms\nlatency event. Users collect data points on the existing measures with\nthe current context. Tags from the current context is recorded with the\nmeasurements if they are any.\n\nRecorded measurements are dropped immediately if user is not aggregating\nthem via views. Users don't necessarily need to conditionally enable\/disable\nrecording to reduce cost. Recording of measurements is cheap.\n\nLibraries can always record measurements, and end-user can later decide\non which measurements they want to collect by registering views. This allows\nlibraries to turn on the instrumentation by default.\n\nViews\n\nIn order to collect measurements, views need to be defined and registered.\nA view allows recorded measurements to be filtered and aggregated over a time window.\n\nAll recorded measurements can be filtered by a list of tags.\n\nOpenCensus provides several aggregation methods: count, distribution, sum and mean.\nCount aggregation only counts the number of measurement points. Distribution\naggregation provides statistical summary of the aggregated data. Sum distribution\nsums up the measurement points. Mean provides the mean of the recorded measurements.\nAggregations can either happen cumulatively or over an interval.\n\nUsers can dynamically create and delete views.\n\nLibraries can export their own views and claim the view names\nby registering them themselves.\n\nExporting\n\nCollected and aggregated data can be exported to a metric collection\nbackend by registering its exporter.\n\nMultiple exporters can be registered to upload the data to various\ndifferent backends. Users need to unregister the exporters once they\nno longer are needed.\n*\/\npackage stats \/\/ import \"go.opencensus.io\/stats\"\n\n\/\/ TODO(acetechnologist): Add a link to the language independent OpenCensus\n\/\/ spec when it is available.\n<commit_msg>Fix minor stats\/doc.go typos (#266)<commit_after>\/\/ Copyright 2017, OpenCensus Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n\/*\nPackage stats contains support for OpenCensus stats collection.\n\nOpenCensus allows users to create typed measures, record measurements,\naggregate the collected data, and export the aggregated data.\n\nMeasures\n\nA measure represents a type of metric to be tracked and recorded.\nFor example, latency, request Mb\/s, and response Mb\/s are measures\nto collect from a server.\n\nEach measure needs to be registered before being used. Measure\nconstructors such as NewMeasureInt64 and NewMeasureFloat64 automatically\nregister the measure by the given name. Each registered measure needs\nto be unique by name. Measures also have a description and a unit.\n\nLibraries can define and export measures for their end users to\ncreate views and collect instrumentation data.\n\nRecording measurements\n\nMeasurement is a data point to be collected for a measure. For example,\nfor a latency (ms) measure, 100 is a measurement that represents a 100ms\nlatency event. Users collect data points on the existing measures with\nthe current context. Tags from the current context are recorded with the\nmeasurements if they are any.\n\nRecorded measurements are dropped immediately if user is not aggregating\nthem via views. Users don't necessarily need to conditionally enable\/disable\nrecording to reduce cost. Recording of measurements is cheap.\n\nLibraries can always record measurements, and end-users can later decide\non which measurements they want to collect by registering views. This allows\nlibraries to turn on the instrumentation by default.\n\nViews\n\nIn order to collect measurements, views need to be defined and registered.\nA view allows recorded measurements to be filtered and aggregated over a time window.\n\nAll recorded measurements can be filtered by a list of tags.\n\nOpenCensus provides several aggregation methods: count, distribution, sum and mean.\nCount aggregation only counts the number of measurement points. Distribution\naggregation provides statistical summary of the aggregated data. Sum distribution\nsums up the measurement points. Mean provides the mean of the recorded measurements.\nAggregations can either happen cumulatively or over an interval.\n\nUsers can dynamically create and delete views.\n\nLibraries can export their own views and claim the view names\nby registering them themselves.\n\nExporting\n\nCollected and aggregated data can be exported to a metric collection\nbackend by registering its exporter.\n\nMultiple exporters can be registered to upload the data to various\ndifferent backends. Users need to unregister the exporters once they\nno longer are needed.\n*\/\npackage stats \/\/ import \"go.opencensus.io\/stats\"\n\n\/\/ TODO(acetechnologist): Add a link to the language independent OpenCensus\n\/\/ spec when it is available.\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Keybase Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD\n\/\/ license that can be found in the LICENSE file.\n\npackage libkbfs\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n\t\"github.com\/keybase\/kbfs\/kbfscrypto\"\n\n\t\"github.com\/keybase\/kbfs\/tlf\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ journalMDOps is an implementation of MDOps that delegates to a\n\/\/ TLF's mdJournal, if one exists. Specifically, it intercepts put\n\/\/ calls to write to the journal instead of the MDServer, where\n\/\/ something else is presumably flushing the journal to the MDServer.\n\/\/\n\/\/ It then intercepts get calls to provide a combined view of the MDs\n\/\/ from the journal and the server when the journal is\n\/\/ non-empty. Specifically, if rev is the earliest revision in the\n\/\/ journal, and BID is the branch ID of the journal (which can only\n\/\/ have one), then any requests for revisions >= rev on BID will be\n\/\/ served from the journal instead of the server. If BID is empty,\n\/\/ i.e. the journal is holding merged revisions, then this means that\n\/\/ all merged revisions on the server from rev are hidden.\n\/\/\n\/\/ TODO: This makes server updates meaningless for revisions >=\n\/\/ rev. Fix this.\ntype journalMDOps struct {\n\tMDOps\n\tjServer *JournalServer\n}\n\nvar _ MDOps = journalMDOps{}\n\n\/\/ convertImmutableBareRMDToIRMD decrypts the bare MD into a\n\/\/ full-fledged RMD.\nfunc (j journalMDOps) convertImmutableBareRMDToIRMD(ctx context.Context,\n\tibrmd ImmutableBareRootMetadata, handle *TlfHandle,\n\tuid keybase1.UID, key kbfscrypto.VerifyingKey) (\n\tImmutableRootMetadata, error) {\n\t\/\/ TODO: Avoid having to do this type assertion.\n\tbrmd, ok := ibrmd.BareRootMetadata.(MutableBareRootMetadata)\n\tif !ok {\n\t\treturn ImmutableRootMetadata{}, MutableBareRootMetadataNoImplError{}\n\t}\n\n\trmd := makeRootMetadata(brmd, ibrmd.extra, handle)\n\n\tconfig := j.jServer.config\n\tpmd, err := decryptMDPrivateData(ctx, config.Codec(), config.Crypto(),\n\t\tconfig.BlockCache(), config.BlockOps(), config.KeyManager(),\n\t\tuid, rmd.GetSerializedPrivateMetadata(), rmd, rmd)\n\tif err != nil {\n\t\treturn ImmutableRootMetadata{}, err\n\t}\n\n\trmd.data = pmd\n\tirmd := MakeImmutableRootMetadata(\n\t\trmd, key, ibrmd.mdID, ibrmd.localTimestamp)\n\treturn irmd, nil\n}\n\n\/\/ getHeadFromJournal returns the head RootMetadata for the TLF with\n\/\/ the given ID stored in the journal, assuming it exists and matches\n\/\/ the given branch ID and merge status. As a special case, if bid is\n\/\/ NullBranchID and mStatus is Unmerged, the branch ID check is\n\/\/ skipped.\nfunc (j journalMDOps) getHeadFromJournal(\n\tctx context.Context, id tlf.ID, bid BranchID, mStatus MergeStatus,\n\thandle *TlfHandle) (\n\tImmutableRootMetadata, error) {\n\ttlfJournal, ok := j.jServer.getTLFJournal(id)\n\tif !ok {\n\t\treturn ImmutableRootMetadata{}, nil\n\t}\n\n\thead, err := tlfJournal.getMDHead(ctx)\n\tif err == errTLFJournalDisabled {\n\t\treturn ImmutableRootMetadata{}, nil\n\t} else if err != nil {\n\t\treturn ImmutableRootMetadata{}, err\n\t}\n\n\tif head == (ImmutableBareRootMetadata{}) {\n\t\treturn ImmutableRootMetadata{}, nil\n\t}\n\n\tif head.MergedStatus() != mStatus {\n\t\treturn ImmutableRootMetadata{}, nil\n\t}\n\n\tif mStatus == Unmerged && bid != NullBranchID && bid != head.BID() {\n\t\t\/\/ The given branch ID doesn't match the one in the\n\t\t\/\/ journal, which can only be an error.\n\t\treturn ImmutableRootMetadata{},\n\t\t\tfmt.Errorf(\"Expected branch ID %s, got %s\",\n\t\t\t\tbid, head.BID())\n\t}\n\n\theadBareHandle, err := head.MakeBareTlfHandleWithExtra()\n\tif err != nil {\n\t\treturn ImmutableRootMetadata{}, err\n\t}\n\n\tif handle == nil {\n\t\thandle, err = MakeTlfHandle(\n\t\t\tctx, headBareHandle, j.jServer.config.KBPKI())\n\t\tif err != nil {\n\t\t\treturn ImmutableRootMetadata{}, err\n\t\t}\n\t} else {\n\t\t\/\/ Check for mutual handle resolution.\n\t\theadHandle, err := MakeTlfHandle(ctx, headBareHandle,\n\t\t\tj.jServer.config.KBPKI())\n\t\tif err != nil {\n\t\t\treturn ImmutableRootMetadata{}, err\n\t\t}\n\n\t\tif err := headHandle.MutuallyResolvesTo(ctx, j.jServer.config.Codec(),\n\t\t\tj.jServer.config.KBPKI(), *handle, head.RevisionNumber(),\n\t\t\thead.TlfID(), j.jServer.log); err != nil {\n\t\t\treturn ImmutableRootMetadata{}, err\n\t\t}\n\t}\n\n\tirmd, err := j.convertImmutableBareRMDToIRMD(\n\t\tctx, head, handle, tlfJournal.uid, tlfJournal.key)\n\tif err != nil {\n\t\treturn ImmutableRootMetadata{}, err\n\t}\n\n\treturn irmd, nil\n}\n\nfunc (j journalMDOps) getRangeFromJournal(\n\tctx context.Context, id tlf.ID, bid BranchID, mStatus MergeStatus,\n\tstart, stop MetadataRevision) (\n\t[]ImmutableRootMetadata, error) {\n\ttlfJournal, ok := j.jServer.getTLFJournal(id)\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\tibrmds, err := tlfJournal.getMDRange(ctx, start, stop)\n\tif err == errTLFJournalDisabled {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(ibrmds) == 0 {\n\t\treturn nil, nil\n\t}\n\n\thead := ibrmds[len(ibrmds)-1]\n\n\tif head.MergedStatus() != mStatus {\n\t\treturn nil, nil\n\t}\n\n\tif mStatus == Unmerged && bid != NullBranchID && bid != head.BID() {\n\t\t\/\/ The given branch ID doesn't match the one in the\n\t\t\/\/ journal, which can only be an error.\n\t\treturn nil, fmt.Errorf(\"Expected branch ID %s, got %s\",\n\t\t\tbid, head.BID())\n\t}\n\n\tbareHandle, err := head.MakeBareTlfHandleWithExtra()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thandle, err := MakeTlfHandle(ctx, bareHandle, j.jServer.config.KBPKI())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tirmds := make([]ImmutableRootMetadata, 0, len(ibrmds))\n\n\tfor _, ibrmd := range ibrmds {\n\t\tirmd, err := j.convertImmutableBareRMDToIRMD(\n\t\t\tctx, ibrmd, handle, tlfJournal.uid, tlfJournal.key)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tirmds = append(irmds, irmd)\n\t}\n\n\treturn irmds, nil\n}\n\nfunc (j journalMDOps) GetForHandle(\n\tctx context.Context, handle *TlfHandle, mStatus MergeStatus) (\n\ttlf.ID, ImmutableRootMetadata, error) {\n\t\/\/ Need to always consult the server to get the tlfID. No need to\n\t\/\/ optimize this, since all subsequent lookups will be by\n\t\/\/ TLF. Although if we did want to, we could store a handle -> TLF\n\t\/\/ ID mapping with the journals.  If we are looking for an\n\t\/\/ unmerged head, that exists only in the journal, so check the\n\t\/\/ remote server only to get the TLF ID.\n\tremoteMStatus := mStatus\n\tif mStatus == Unmerged {\n\t\tremoteMStatus = Merged\n\t}\n\ttlfID, rmd, err := j.MDOps.GetForHandle(ctx, handle, remoteMStatus)\n\tif err != nil {\n\t\treturn tlf.ID{}, ImmutableRootMetadata{}, err\n\t}\n\n\tif rmd != (ImmutableRootMetadata{}) && (rmd.TlfID() != tlfID) {\n\t\treturn tlf.ID{}, ImmutableRootMetadata{},\n\t\t\tfmt.Errorf(\"Expected RMD to have TLF ID %s, but got %s\",\n\t\t\t\ttlfID, rmd.TlfID())\n\t}\n\n\t\/\/ If the journal has a head, use that.\n\tirmd, err := j.getHeadFromJournal(\n\t\tctx, tlfID, NullBranchID, mStatus, handle)\n\tif err != nil {\n\t\treturn tlf.ID{}, ImmutableRootMetadata{}, err\n\t}\n\tif irmd != (ImmutableRootMetadata{}) {\n\t\treturn tlf.ID{}, irmd, nil\n\t}\n\tif remoteMStatus != mStatus {\n\t\treturn tlfID, ImmutableRootMetadata{}, nil\n\t}\n\n\t\/\/ Otherwise, use the server's head.\n\treturn tlfID, rmd, nil\n}\n\n\/\/ TODO: Combine the two GetForTLF functions in MDOps to avoid the\n\/\/ need for this helper function.\nfunc (j journalMDOps) getForTLF(\n\tctx context.Context, id tlf.ID, bid BranchID, mStatus MergeStatus,\n\tdelegateFn func(context.Context, tlf.ID) (ImmutableRootMetadata, error)) (\n\tImmutableRootMetadata, error) {\n\t\/\/ If the journal has a head, use that.\n\tirmd, err := j.getHeadFromJournal(ctx, id, bid, mStatus, nil)\n\tif err != nil {\n\t\treturn ImmutableRootMetadata{}, err\n\t}\n\tif irmd != (ImmutableRootMetadata{}) {\n\t\treturn irmd, nil\n\t}\n\n\t\/\/ Otherwise, consult the server instead.\n\treturn delegateFn(ctx, id)\n}\n\nfunc (j journalMDOps) GetForTLF(\n\tctx context.Context, id tlf.ID) (ImmutableRootMetadata, error) {\n\treturn j.getForTLF(ctx, id, NullBranchID, Merged, j.MDOps.GetForTLF)\n}\n\nfunc (j journalMDOps) GetUnmergedForTLF(\n\tctx context.Context, id tlf.ID, bid BranchID) (\n\tImmutableRootMetadata, error) {\n\tdelegateFn := func(ctx context.Context, id tlf.ID) (\n\t\tImmutableRootMetadata, error) {\n\t\treturn j.MDOps.GetUnmergedForTLF(ctx, id, bid)\n\t}\n\treturn j.getForTLF(ctx, id, bid, Unmerged, delegateFn)\n}\n\n\/\/ TODO: Combine the two GetRange functions in MDOps to avoid the need\n\/\/ for this helper function.\nfunc (j journalMDOps) getRange(\n\tctx context.Context, id tlf.ID, bid BranchID, mStatus MergeStatus,\n\tstart, stop MetadataRevision,\n\tdelegateFn func(ctx context.Context, id tlf.ID,\n\t\tstart, stop MetadataRevision) (\n\t\t[]ImmutableRootMetadata, error)) (\n\t[]ImmutableRootMetadata, error) {\n\t\/\/ Grab the range from the journal first.\n\tjirmds, err := j.getRangeFromJournal(ctx, id, bid, mStatus, start, stop)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ If it's empty or disabled, just fall back to the server.\n\tif len(jirmds) == 0 || err == errTLFJournalDisabled {\n\t\treturn delegateFn(ctx, id, start, stop)\n\t}\n\n\t\/\/ If the first revision from the journal is the first\n\t\/\/ revision we asked for, then just return the range from the\n\t\/\/ journal.\n\tif jirmds[0].Revision() == start {\n\t\treturn jirmds, nil\n\t}\n\n\t\/\/ Otherwise, fetch the rest from the server and prepend them.\n\tserverStop := jirmds[0].Revision() - 1\n\tirmds, err := delegateFn(ctx, id, start, serverStop)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(irmds) == 0 {\n\t\treturn jirmds, nil\n\t}\n\n\tlastRev := irmds[len(irmds)-1].Revision()\n\tif lastRev != serverStop {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"Expected last server rev %d, got %d\",\n\t\t\tserverStop, lastRev)\n\t}\n\n\treturn append(irmds, jirmds...), nil\n}\n\nfunc (j journalMDOps) GetRange(\n\tctx context.Context, id tlf.ID, start, stop MetadataRevision) (\n\t[]ImmutableRootMetadata, error) {\n\treturn j.getRange(ctx, id, NullBranchID, Merged, start, stop,\n\t\tj.MDOps.GetRange)\n}\n\nfunc (j journalMDOps) GetUnmergedRange(\n\tctx context.Context, id tlf.ID, bid BranchID,\n\tstart, stop MetadataRevision) ([]ImmutableRootMetadata, error) {\n\tdelegateFn := func(ctx context.Context, id tlf.ID,\n\t\tstart, stop MetadataRevision) (\n\t\t[]ImmutableRootMetadata, error) {\n\t\treturn j.MDOps.GetUnmergedRange(ctx, id, bid, start, stop)\n\t}\n\treturn j.getRange(ctx, id, bid, Unmerged, start, stop,\n\t\tdelegateFn)\n}\n\nfunc (j journalMDOps) Put(ctx context.Context, rmd *RootMetadata) (\n\tMdID, error) {\n\tif tlfJournal, ok := j.jServer.getTLFJournal(rmd.TlfID()); ok {\n\t\t\/\/ Just route to the journal.\n\t\tmdID, err := tlfJournal.putMD(ctx, rmd)\n\t\tif err != errTLFJournalDisabled {\n\t\t\treturn mdID, err\n\t\t}\n\t}\n\n\treturn j.MDOps.Put(ctx, rmd)\n}\n\nfunc (j journalMDOps) PutUnmerged(ctx context.Context, rmd *RootMetadata) (\n\tMdID, error) {\n\tif tlfJournal, ok := j.jServer.getTLFJournal(rmd.TlfID()); ok {\n\t\trmd.SetUnmerged()\n\t\tmdID, err := tlfJournal.putMD(ctx, rmd)\n\t\tif err != errTLFJournalDisabled {\n\t\t\treturn mdID, err\n\t\t}\n\t}\n\n\treturn j.MDOps.PutUnmerged(ctx, rmd)\n}\n\nfunc (j journalMDOps) PruneBranch(\n\tctx context.Context, id tlf.ID, bid BranchID) error {\n\tif tlfJournal, ok := j.jServer.getTLFJournal(id); ok {\n\t\t\/\/ Prune the journal, too.\n\t\terr := tlfJournal.clearMDs(ctx, bid)\n\t\tif err != nil && err != errTLFJournalDisabled {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn j.MDOps.PruneBranch(ctx, id, bid)\n}\n\nfunc (j journalMDOps) ResolveBranch(\n\tctx context.Context, id tlf.ID, bid BranchID,\n\tblocksToDelete []BlockID, rmd *RootMetadata) (MdID, error) {\n\tif tlfJournal, ok := j.jServer.getTLFJournal(id); ok {\n\t\tmdID, err := tlfJournal.resolveBranch(\n\t\t\tctx, bid, blocksToDelete, rmd, rmd.extra)\n\t\tif err != errTLFJournalDisabled {\n\t\t\treturn mdID, err\n\t\t}\n\t}\n\n\treturn j.MDOps.ResolveBranch(ctx, id, bid, blocksToDelete, rmd)\n}\n<commit_msg>journal_md_ops: don't return an err if journal is disabled<commit_after>\/\/ Copyright 2016 Keybase Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD\n\/\/ license that can be found in the LICENSE file.\n\npackage libkbfs\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n\t\"github.com\/keybase\/kbfs\/kbfscrypto\"\n\n\t\"github.com\/keybase\/kbfs\/tlf\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ journalMDOps is an implementation of MDOps that delegates to a\n\/\/ TLF's mdJournal, if one exists. Specifically, it intercepts put\n\/\/ calls to write to the journal instead of the MDServer, where\n\/\/ something else is presumably flushing the journal to the MDServer.\n\/\/\n\/\/ It then intercepts get calls to provide a combined view of the MDs\n\/\/ from the journal and the server when the journal is\n\/\/ non-empty. Specifically, if rev is the earliest revision in the\n\/\/ journal, and BID is the branch ID of the journal (which can only\n\/\/ have one), then any requests for revisions >= rev on BID will be\n\/\/ served from the journal instead of the server. If BID is empty,\n\/\/ i.e. the journal is holding merged revisions, then this means that\n\/\/ all merged revisions on the server from rev are hidden.\n\/\/\n\/\/ TODO: This makes server updates meaningless for revisions >=\n\/\/ rev. Fix this.\ntype journalMDOps struct {\n\tMDOps\n\tjServer *JournalServer\n}\n\nvar _ MDOps = journalMDOps{}\n\n\/\/ convertImmutableBareRMDToIRMD decrypts the bare MD into a\n\/\/ full-fledged RMD.\nfunc (j journalMDOps) convertImmutableBareRMDToIRMD(ctx context.Context,\n\tibrmd ImmutableBareRootMetadata, handle *TlfHandle,\n\tuid keybase1.UID, key kbfscrypto.VerifyingKey) (\n\tImmutableRootMetadata, error) {\n\t\/\/ TODO: Avoid having to do this type assertion.\n\tbrmd, ok := ibrmd.BareRootMetadata.(MutableBareRootMetadata)\n\tif !ok {\n\t\treturn ImmutableRootMetadata{}, MutableBareRootMetadataNoImplError{}\n\t}\n\n\trmd := makeRootMetadata(brmd, ibrmd.extra, handle)\n\n\tconfig := j.jServer.config\n\tpmd, err := decryptMDPrivateData(ctx, config.Codec(), config.Crypto(),\n\t\tconfig.BlockCache(), config.BlockOps(), config.KeyManager(),\n\t\tuid, rmd.GetSerializedPrivateMetadata(), rmd, rmd)\n\tif err != nil {\n\t\treturn ImmutableRootMetadata{}, err\n\t}\n\n\trmd.data = pmd\n\tirmd := MakeImmutableRootMetadata(\n\t\trmd, key, ibrmd.mdID, ibrmd.localTimestamp)\n\treturn irmd, nil\n}\n\n\/\/ getHeadFromJournal returns the head RootMetadata for the TLF with\n\/\/ the given ID stored in the journal, assuming it exists and matches\n\/\/ the given branch ID and merge status. As a special case, if bid is\n\/\/ NullBranchID and mStatus is Unmerged, the branch ID check is\n\/\/ skipped.\nfunc (j journalMDOps) getHeadFromJournal(\n\tctx context.Context, id tlf.ID, bid BranchID, mStatus MergeStatus,\n\thandle *TlfHandle) (\n\tImmutableRootMetadata, error) {\n\ttlfJournal, ok := j.jServer.getTLFJournal(id)\n\tif !ok {\n\t\treturn ImmutableRootMetadata{}, nil\n\t}\n\n\thead, err := tlfJournal.getMDHead(ctx)\n\tif err == errTLFJournalDisabled {\n\t\treturn ImmutableRootMetadata{}, nil\n\t} else if err != nil {\n\t\treturn ImmutableRootMetadata{}, err\n\t}\n\n\tif head == (ImmutableBareRootMetadata{}) {\n\t\treturn ImmutableRootMetadata{}, nil\n\t}\n\n\tif head.MergedStatus() != mStatus {\n\t\treturn ImmutableRootMetadata{}, nil\n\t}\n\n\tif mStatus == Unmerged && bid != NullBranchID && bid != head.BID() {\n\t\t\/\/ The given branch ID doesn't match the one in the\n\t\t\/\/ journal, which can only be an error.\n\t\treturn ImmutableRootMetadata{},\n\t\t\tfmt.Errorf(\"Expected branch ID %s, got %s\",\n\t\t\t\tbid, head.BID())\n\t}\n\n\theadBareHandle, err := head.MakeBareTlfHandleWithExtra()\n\tif err != nil {\n\t\treturn ImmutableRootMetadata{}, err\n\t}\n\n\tif handle == nil {\n\t\thandle, err = MakeTlfHandle(\n\t\t\tctx, headBareHandle, j.jServer.config.KBPKI())\n\t\tif err != nil {\n\t\t\treturn ImmutableRootMetadata{}, err\n\t\t}\n\t} else {\n\t\t\/\/ Check for mutual handle resolution.\n\t\theadHandle, err := MakeTlfHandle(ctx, headBareHandle,\n\t\t\tj.jServer.config.KBPKI())\n\t\tif err != nil {\n\t\t\treturn ImmutableRootMetadata{}, err\n\t\t}\n\n\t\tif err := headHandle.MutuallyResolvesTo(ctx, j.jServer.config.Codec(),\n\t\t\tj.jServer.config.KBPKI(), *handle, head.RevisionNumber(),\n\t\t\thead.TlfID(), j.jServer.log); err != nil {\n\t\t\treturn ImmutableRootMetadata{}, err\n\t\t}\n\t}\n\n\tirmd, err := j.convertImmutableBareRMDToIRMD(\n\t\tctx, head, handle, tlfJournal.uid, tlfJournal.key)\n\tif err != nil {\n\t\treturn ImmutableRootMetadata{}, err\n\t}\n\n\treturn irmd, nil\n}\n\nfunc (j journalMDOps) getRangeFromJournal(\n\tctx context.Context, id tlf.ID, bid BranchID, mStatus MergeStatus,\n\tstart, stop MetadataRevision) (\n\t[]ImmutableRootMetadata, error) {\n\ttlfJournal, ok := j.jServer.getTLFJournal(id)\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\tibrmds, err := tlfJournal.getMDRange(ctx, start, stop)\n\tif err == errTLFJournalDisabled {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(ibrmds) == 0 {\n\t\treturn nil, nil\n\t}\n\n\thead := ibrmds[len(ibrmds)-1]\n\n\tif head.MergedStatus() != mStatus {\n\t\treturn nil, nil\n\t}\n\n\tif mStatus == Unmerged && bid != NullBranchID && bid != head.BID() {\n\t\t\/\/ The given branch ID doesn't match the one in the\n\t\t\/\/ journal, which can only be an error.\n\t\treturn nil, fmt.Errorf(\"Expected branch ID %s, got %s\",\n\t\t\tbid, head.BID())\n\t}\n\n\tbareHandle, err := head.MakeBareTlfHandleWithExtra()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thandle, err := MakeTlfHandle(ctx, bareHandle, j.jServer.config.KBPKI())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tirmds := make([]ImmutableRootMetadata, 0, len(ibrmds))\n\n\tfor _, ibrmd := range ibrmds {\n\t\tirmd, err := j.convertImmutableBareRMDToIRMD(\n\t\t\tctx, ibrmd, handle, tlfJournal.uid, tlfJournal.key)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tirmds = append(irmds, irmd)\n\t}\n\n\treturn irmds, nil\n}\n\nfunc (j journalMDOps) GetForHandle(\n\tctx context.Context, handle *TlfHandle, mStatus MergeStatus) (\n\ttlf.ID, ImmutableRootMetadata, error) {\n\t\/\/ Need to always consult the server to get the tlfID. No need to\n\t\/\/ optimize this, since all subsequent lookups will be by\n\t\/\/ TLF. Although if we did want to, we could store a handle -> TLF\n\t\/\/ ID mapping with the journals.  If we are looking for an\n\t\/\/ unmerged head, that exists only in the journal, so check the\n\t\/\/ remote server only to get the TLF ID.\n\tremoteMStatus := mStatus\n\tif mStatus == Unmerged {\n\t\tremoteMStatus = Merged\n\t}\n\ttlfID, rmd, err := j.MDOps.GetForHandle(ctx, handle, remoteMStatus)\n\tif err != nil {\n\t\treturn tlf.ID{}, ImmutableRootMetadata{}, err\n\t}\n\n\tif rmd != (ImmutableRootMetadata{}) && (rmd.TlfID() != tlfID) {\n\t\treturn tlf.ID{}, ImmutableRootMetadata{},\n\t\t\tfmt.Errorf(\"Expected RMD to have TLF ID %s, but got %s\",\n\t\t\t\ttlfID, rmd.TlfID())\n\t}\n\n\t\/\/ If the journal has a head, use that.\n\tirmd, err := j.getHeadFromJournal(\n\t\tctx, tlfID, NullBranchID, mStatus, handle)\n\tif err != nil {\n\t\treturn tlf.ID{}, ImmutableRootMetadata{}, err\n\t}\n\tif irmd != (ImmutableRootMetadata{}) {\n\t\treturn tlf.ID{}, irmd, nil\n\t}\n\tif remoteMStatus != mStatus {\n\t\treturn tlfID, ImmutableRootMetadata{}, nil\n\t}\n\n\t\/\/ Otherwise, use the server's head.\n\treturn tlfID, rmd, nil\n}\n\n\/\/ TODO: Combine the two GetForTLF functions in MDOps to avoid the\n\/\/ need for this helper function.\nfunc (j journalMDOps) getForTLF(\n\tctx context.Context, id tlf.ID, bid BranchID, mStatus MergeStatus,\n\tdelegateFn func(context.Context, tlf.ID) (ImmutableRootMetadata, error)) (\n\tImmutableRootMetadata, error) {\n\t\/\/ If the journal has a head, use that.\n\tirmd, err := j.getHeadFromJournal(ctx, id, bid, mStatus, nil)\n\tif err != nil {\n\t\treturn ImmutableRootMetadata{}, err\n\t}\n\tif irmd != (ImmutableRootMetadata{}) {\n\t\treturn irmd, nil\n\t}\n\n\t\/\/ Otherwise, consult the server instead.\n\treturn delegateFn(ctx, id)\n}\n\nfunc (j journalMDOps) GetForTLF(\n\tctx context.Context, id tlf.ID) (ImmutableRootMetadata, error) {\n\treturn j.getForTLF(ctx, id, NullBranchID, Merged, j.MDOps.GetForTLF)\n}\n\nfunc (j journalMDOps) GetUnmergedForTLF(\n\tctx context.Context, id tlf.ID, bid BranchID) (\n\tImmutableRootMetadata, error) {\n\tdelegateFn := func(ctx context.Context, id tlf.ID) (\n\t\tImmutableRootMetadata, error) {\n\t\treturn j.MDOps.GetUnmergedForTLF(ctx, id, bid)\n\t}\n\treturn j.getForTLF(ctx, id, bid, Unmerged, delegateFn)\n}\n\n\/\/ TODO: Combine the two GetRange functions in MDOps to avoid the need\n\/\/ for this helper function.\nfunc (j journalMDOps) getRange(\n\tctx context.Context, id tlf.ID, bid BranchID, mStatus MergeStatus,\n\tstart, stop MetadataRevision,\n\tdelegateFn func(ctx context.Context, id tlf.ID,\n\t\tstart, stop MetadataRevision) (\n\t\t[]ImmutableRootMetadata, error)) (\n\t[]ImmutableRootMetadata, error) {\n\t\/\/ Grab the range from the journal first.\n\tjirmds, err := j.getRangeFromJournal(ctx, id, bid, mStatus, start, stop)\n\tif err != nil && err != errTLFJournalDisabled {\n\t\treturn nil, err\n\t}\n\n\t\/\/ If it's empty or disabled, just fall back to the server.\n\tif len(jirmds) == 0 || err == errTLFJournalDisabled {\n\t\treturn delegateFn(ctx, id, start, stop)\n\t}\n\n\t\/\/ If the first revision from the journal is the first\n\t\/\/ revision we asked for, then just return the range from the\n\t\/\/ journal.\n\tif jirmds[0].Revision() == start {\n\t\treturn jirmds, nil\n\t}\n\n\t\/\/ Otherwise, fetch the rest from the server and prepend them.\n\tserverStop := jirmds[0].Revision() - 1\n\tirmds, err := delegateFn(ctx, id, start, serverStop)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(irmds) == 0 {\n\t\treturn jirmds, nil\n\t}\n\n\tlastRev := irmds[len(irmds)-1].Revision()\n\tif lastRev != serverStop {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"Expected last server rev %d, got %d\",\n\t\t\tserverStop, lastRev)\n\t}\n\n\treturn append(irmds, jirmds...), nil\n}\n\nfunc (j journalMDOps) GetRange(\n\tctx context.Context, id tlf.ID, start, stop MetadataRevision) (\n\t[]ImmutableRootMetadata, error) {\n\treturn j.getRange(ctx, id, NullBranchID, Merged, start, stop,\n\t\tj.MDOps.GetRange)\n}\n\nfunc (j journalMDOps) GetUnmergedRange(\n\tctx context.Context, id tlf.ID, bid BranchID,\n\tstart, stop MetadataRevision) ([]ImmutableRootMetadata, error) {\n\tdelegateFn := func(ctx context.Context, id tlf.ID,\n\t\tstart, stop MetadataRevision) (\n\t\t[]ImmutableRootMetadata, error) {\n\t\treturn j.MDOps.GetUnmergedRange(ctx, id, bid, start, stop)\n\t}\n\treturn j.getRange(ctx, id, bid, Unmerged, start, stop,\n\t\tdelegateFn)\n}\n\nfunc (j journalMDOps) Put(ctx context.Context, rmd *RootMetadata) (\n\tMdID, error) {\n\tif tlfJournal, ok := j.jServer.getTLFJournal(rmd.TlfID()); ok {\n\t\t\/\/ Just route to the journal.\n\t\tmdID, err := tlfJournal.putMD(ctx, rmd)\n\t\tif err != errTLFJournalDisabled {\n\t\t\treturn mdID, err\n\t\t}\n\t}\n\n\treturn j.MDOps.Put(ctx, rmd)\n}\n\nfunc (j journalMDOps) PutUnmerged(ctx context.Context, rmd *RootMetadata) (\n\tMdID, error) {\n\tif tlfJournal, ok := j.jServer.getTLFJournal(rmd.TlfID()); ok {\n\t\trmd.SetUnmerged()\n\t\tmdID, err := tlfJournal.putMD(ctx, rmd)\n\t\tif err != errTLFJournalDisabled {\n\t\t\treturn mdID, err\n\t\t}\n\t}\n\n\treturn j.MDOps.PutUnmerged(ctx, rmd)\n}\n\nfunc (j journalMDOps) PruneBranch(\n\tctx context.Context, id tlf.ID, bid BranchID) error {\n\tif tlfJournal, ok := j.jServer.getTLFJournal(id); ok {\n\t\t\/\/ Prune the journal, too.\n\t\terr := tlfJournal.clearMDs(ctx, bid)\n\t\tif err != nil && err != errTLFJournalDisabled {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn j.MDOps.PruneBranch(ctx, id, bid)\n}\n\nfunc (j journalMDOps) ResolveBranch(\n\tctx context.Context, id tlf.ID, bid BranchID,\n\tblocksToDelete []BlockID, rmd *RootMetadata) (MdID, error) {\n\tif tlfJournal, ok := j.jServer.getTLFJournal(id); ok {\n\t\tmdID, err := tlfJournal.resolveBranch(\n\t\t\tctx, bid, blocksToDelete, rmd, rmd.extra)\n\t\tif err != errTLFJournalDisabled {\n\t\t\treturn mdID, err\n\t\t}\n\t}\n\n\treturn j.MDOps.ResolveBranch(ctx, id, bid, blocksToDelete, rmd)\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>S종목별_일일_가격정보_모음 함수 변경<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nHist shows the history of a given file, using Arq backups.\n\n    usage: hist [-d] [-h host] [-m mtpt] [-s yyyy\/mmdd] file ...\n\nThe -d flag causes it to show diffs between successive versions.\n\nBy default, hist assumes backups are mounted at mtpt\/host, where\nmtpt defaults to \/mnt\/arq and host is the first element of the local host name.\nHist starts the file list with the present copy of the file.\n\nThe -h and -s flags override these assumptions.\n\n*\/\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar usageString = `usage: hist [-d] [-h host] [-m mtpt] [-s yyyy\/mmdd] file ...\n\nHist lists the known versions of the given file.\nThe -d flag causes it to show diffs between successive versions.\n\nBy default, hist assumes backups are mounted at mtpt\/host, where\nmtpt defaults to \/mnt\/arq and host is the first element of the local host name.\nHist starts the file list with the present copy of the file.\n\nThe -h and -s flags override these assumptions.\n`\n\nvar (\n\tdiff = flag.Bool(\"d\", false, \"diff\")\n\thost = flag.String(\"h\", defaultHost(), \"host name\")\n\tmtpt = flag.String(\"m\", \"\/mnt\/arq\", \"mount point\")\n\tvers = flag.String(\"s\", \"\", \"version\")\n)\n\nfunc defaultHost() string {\n\tname, _ := os.Hostname()\n\tif name == \"\" {\n\t\tname = \"gnot\"\n\t}\n\tif i := strings.Index(name, \".\"); i >= 0 {\n\t\tname = name[:i]\n\t}\n\treturn name\n}\n\nfunc main() {\n\tflag.Usage = func() {\n\t\tfmt.Fprint(os.Stderr, usageString)\n\t\tos.Exit(2)\n\t}\n\t\n\tflag.Parse()\n\targs := flag.Args()\n\tif len(args) == 0 {\n\t\tflag.Usage()\n\t}\n\t\n\tdates := loadDates()\n\tfor _, file := range args {\n\t\tlist(dates, file)\n\t}\n}\n\nvar (\n\tyyyy = regexp.MustCompile(`^\\d{4}$`)\n\tmmdd = regexp.MustCompile(`^\\d{4}(\\.\\d+)?$`)\n)\n\nfunc loadDates() []string {\n\tvar all []string\n\tydir, err := ioutil.ReadDir(filepath.Join(*mtpt, *host))\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(3)\n\t}\n\tfor _, y := range ydir {\n\t\tif !y.IsDir() || !yyyy.MatchString(y.Name()) {\n\t\t\tcontinue\n\t\t}\n\t\tddir, err := ioutil.ReadDir(filepath.Join(*mtpt, *host, y.Name()))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, d := range ddir {\n\t\t\tif !d.IsDir() || !mmdd.MatchString(d.Name()) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdate := y.Name() + \"\/\" + d.Name()\n\t\t\tif *vers > date {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tall = append(all, filepath.Join(*mtpt, *host, date))\n\t\t}\n\t}\n\treturn all\n}\t\t\n\nconst timeFormat = \"Jan 02 15:04:05 MST 2006\"\n\nfunc list(dates []string, file string) {\n\tvar (\n\t\tlast os.FileInfo\n\t\tlastPath string\n\t)\n\n\tfi, err := os.Stat(file)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"hist: warning: %s: %v\\n\", file, err)\n\t} else {\n\t\tfmt.Printf(\"%s %s %d\\n\", fi.ModTime().Format(timeFormat), file, fi.Size())\n\t\tlast = fi\n\t\tlastPath = file\n\t}\n\t\n\tfile, err = filepath.Abs(file)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"hist: abs: %v\\n\", err)\n\t\treturn\n\t}\n\n\tfor i := len(dates)-1; i >= 0; i-- {\n\t\tp := filepath.Join(dates[i], file)\n\t\tfi, err := os.Stat(p)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif last != nil && fi.ModTime() == last.ModTime() && fi.Size() == last.Size() {\n\t\t\tcontinue\n\t\t}\n\t\tif *diff {\n\t\t\tcmd := exec.Command(\"diff\", lastPath, p)\n\t\t\tcmd.Stdout = os.Stdout\n\t\t\tcmd.Stderr = os.Stderr\n\t\t\tif err := cmd.Start(); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err)\n\t\t\t}\n\t\t\tcmd.Wait()\n\t\t}\n\t\tfmt.Printf(\"%s %s %d\\n\", fi.ModTime().Format(timeFormat), file, fi.Size())\n\t\tlast = fi\n\t\tlastPath = p\n\t}\n}\n\n<commit_msg>arq\/hist: fix print<commit_after>\/\/ Copyright 2012 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nHist shows the history of a given file, using Arq backups.\n\n    usage: hist [-d] [-h host] [-m mtpt] [-s yyyy\/mmdd] file ...\n\nThe -d flag causes it to show diffs between successive versions.\n\nBy default, hist assumes backups are mounted at mtpt\/host, where\nmtpt defaults to \/mnt\/arq and host is the first element of the local host name.\nHist starts the file list with the present copy of the file.\n\nThe -h and -s flags override these assumptions.\n\n*\/\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar usageString = `usage: hist [-d] [-h host] [-m mtpt] [-s yyyy\/mmdd] file ...\n\nHist lists the known versions of the given file.\nThe -d flag causes it to show diffs between successive versions.\n\nBy default, hist assumes backups are mounted at mtpt\/host, where\nmtpt defaults to \/mnt\/arq and host is the first element of the local host name.\nHist starts the file list with the present copy of the file.\n\nThe -h and -s flags override these assumptions.\n`\n\nvar (\n\tdiff = flag.Bool(\"d\", false, \"diff\")\n\thost = flag.String(\"h\", defaultHost(), \"host name\")\n\tmtpt = flag.String(\"m\", \"\/mnt\/arq\", \"mount point\")\n\tvers = flag.String(\"s\", \"\", \"version\")\n)\n\nfunc defaultHost() string {\n\tname, _ := os.Hostname()\n\tif name == \"\" {\n\t\tname = \"gnot\"\n\t}\n\tif i := strings.Index(name, \".\"); i >= 0 {\n\t\tname = name[:i]\n\t}\n\treturn name\n}\n\nfunc main() {\n\tflag.Usage = func() {\n\t\tfmt.Fprint(os.Stderr, usageString)\n\t\tos.Exit(2)\n\t}\n\t\n\tflag.Parse()\n\targs := flag.Args()\n\tif len(args) == 0 {\n\t\tflag.Usage()\n\t}\n\t\n\tdates := loadDates()\n\tfor _, file := range args {\n\t\tlist(dates, file)\n\t}\n}\n\nvar (\n\tyyyy = regexp.MustCompile(`^\\d{4}$`)\n\tmmdd = regexp.MustCompile(`^\\d{4}(\\.\\d+)?$`)\n)\n\nfunc loadDates() []string {\n\tvar all []string\n\tydir, err := ioutil.ReadDir(filepath.Join(*mtpt, *host))\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(3)\n\t}\n\tfor _, y := range ydir {\n\t\tif !y.IsDir() || !yyyy.MatchString(y.Name()) {\n\t\t\tcontinue\n\t\t}\n\t\tddir, err := ioutil.ReadDir(filepath.Join(*mtpt, *host, y.Name()))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, d := range ddir {\n\t\t\tif !d.IsDir() || !mmdd.MatchString(d.Name()) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdate := y.Name() + \"\/\" + d.Name()\n\t\t\tif *vers > date {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tall = append(all, filepath.Join(*mtpt, *host, date))\n\t\t}\n\t}\n\treturn all\n}\t\t\n\nconst timeFormat = \"Jan 02 15:04:05 MST 2006\"\n\nfunc list(dates []string, file string) {\n\tvar (\n\t\tlast os.FileInfo\n\t\tlastPath string\n\t)\n\n\tfi, err := os.Stat(file)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"hist: warning: %s: %v\\n\", file, err)\n\t} else {\n\t\tfmt.Printf(\"%s %s %d\\n\", fi.ModTime().Format(timeFormat), file, fi.Size())\n\t\tlast = fi\n\t\tlastPath = file\n\t}\n\t\n\tfile, err = filepath.Abs(file)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"hist: abs: %v\\n\", err)\n\t\treturn\n\t}\n\n\tfor i := len(dates)-1; i >= 0; i-- {\n\t\tp := filepath.Join(dates[i], file)\n\t\tfi, err := os.Stat(p)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif last != nil && fi.ModTime() == last.ModTime() && fi.Size() == last.Size() {\n\t\t\tcontinue\n\t\t}\n\t\tif *diff {\n\t\t\tcmd := exec.Command(\"diff\", lastPath, p)\n\t\t\tcmd.Stdout = os.Stdout\n\t\t\tcmd.Stderr = os.Stderr\n\t\t\tif err := cmd.Start(); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err)\n\t\t\t}\n\t\t\tcmd.Wait()\n\t\t}\n\t\tfmt.Printf(\"%s %s %d\\n\", fi.ModTime().Format(timeFormat), p, fi.Size())\n\t\tlast = fi\n\t\tlastPath = p\n\t}\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nfunc main()              {}\nfunc sink(id int, v interface{}) {}\n\nfunc link(from interface{}, into interface{}) {}\n\nfunc newSource(id int) interface{} {\n\treturn nil\n}\n<commit_msg>Fix go autoformat<commit_after>package main\n\nfunc main()                      {}\nfunc sink(id int, v interface{}) {}\n\nfunc link(from interface{}, into interface{}) {}\n\nfunc newSource(id int) interface{} {\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package make\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n)\n\ntype SolrCore struct {\n\tAddress  string\n\tName     string\n\tTemplate string\n\tPath     string\n\tLegacy   bool\n}\n\nfunc logSolrInstall() bool {\n\tif verifySolrInstall() {\n\t\tlog.Infoln(\"Found Solr installation\")\n\t\treturn true\n\t} else {\n\t\tlog.Errorln(\"Could not find Solr installation\")\n\t\treturn false\n\t}\n}\nfunc logSolrCLI() bool {\n\tif verifySolrCLI() {\n\t\tlog.Infoln(\"Found Solr command-line tools\")\n\t\treturn true\n\t} else {\n\t\tlog.Warnln(\"Could not find Solr command-line tools\")\n\t\treturn false\n\t}\n}\nfunc logResources(Template string) bool {\n\tif verifyResources(Template) {\n\t\tlog.Infoln(\"Found configuration folder\")\n\t\treturn true\n\t} else {\n\t\tlog.Errorln(\"Could not find configuration folder\")\n\t\treturn false\n\t}\n}\nfunc logSolrCore(SolrCore *SolrCore) bool {\n\tif verifySolrCore(SolrCore) {\n\t\tlog.Infoln(\"Solr core is installed.\")\n\t\treturn true\n\t} else {\n\t\tlog.Warnln(\"Solr core is not installed.\")\n\t\treturn false\n\t}\n}\nfunc verifySolrInstall() bool {\n\t_, err := os.Stat(\"\/opt\/solr\")\n\tif err == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\nfunc verifySolrCLI() bool {\n\t_, err := os.Stat(\"\/opt\/solr\/bin\/solr\")\n\tif err == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\nfunc verifyResources(Template string) bool {\n\t_, err := os.Stat(Template)\n\tif err == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\nfunc verifySolrCore(SolrCore *SolrCore) bool {\n\tcurlResponse, err := exec.Command(\"curl\", SolrCore.Address+\"\/solr\/admin\/cores?action=STATUS\").Output()\n\tif err == nil {\n\t\tif strings.Contains(string(curlResponse), `<str name=\"name\">`+SolrCore.Name+`<\/str>`) == true {\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\tlog.Errorln(\"Solr could not be accessed using CURL:\", err.Error())\n\t}\n\treturn false\n}\n\nfunc NewCore(Address, Name, Template, Path string) SolrCore {\n\treturn SolrCore{Address, Name, Template, Path, false}\n}\n\nfunc (SolrCore *SolrCore) Install() {\n\tif logSolrInstall() && logResources(SolrCore.Template) {\n\t\tlog.Infoln(\"All checks have passed.\")\n\t\tdataDir := \"\"\n\t\tif SolrCore.Legacy {\n\t\t\tlog.Infoln(\"Installing legacy file system for Solr < 5.0\")\n\t\t\tdataDir = SolrCore.Path + \"\/\" + SolrCore.Name + \"\/conf\/\"\n\t\t} else {\n\t\t\tdataDir = SolrCore.Path + \"\/data\/\" + SolrCore.Name + \"\/conf\/\"\n\t\t}\n\n\t\t\/\/ Create data directories\n\t\terr := os.MkdirAll(dataDir, 0777)\n\t\tif err == nil {\n\t\t\tlog.Infoln(\"Directory has been created.\", dataDir)\n\t\t} else {\n\t\t\tlog.Errorln(\"Directory has not been created:\", err.Error())\n\t\t}\n\n\t\t\/\/ Sync\n\t\t_, err = exec.Command(\"rsync\", \"-a\", SolrCore.Template+\"\/\", dataDir).Output()\n\t\tif err == nil {\n\t\t\tlog.Infoln(\"Configuration has been synced with boilerplate resources.\")\n\t\t} else {\n\t\t\tlog.Errorln(\"Configuration could not be synced with boilerplate resources:\", err.Error())\n\t\t}\n\n\t\tif logSolrCLI() == true {\n\t\t\t\/\/ Install core via CLI\n\t\t\tcliOut, err := exec.Command(\"\/opt\/solr\/bin\/solr\", \"create\", \"-c\", SolrCore.Name).Output()\n\t\t\tif err == nil && strings.Contains(string(cliOut), \"Unable to create core\") == false {\n\t\t\t\tif verifySolrCore(SolrCore) {\n\t\t\t\t\tlog.Infoln(\"Core has been installed and verified successfully.\")\n\t\t\t\t} else {\n\t\t\t\t\tlog.Errorln(\"Core could not be installed, check logs for details.\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Errorln(\"Core could not be installed:\", err.Error(), string(cliOut))\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Install core via CURL\n\t\t\t_, err = exec.Command(\"curl\", SolrCore.Address+\"\/solr\/admin\/cores?action=CREATE&name=\"+SolrCore.Name+\"&instanceDir=\"+SolrCore.Name+\"&dataDir=data&config=solrconfig.xml&schema=schema.xml\").Output()\n\t\t\tif err == nil {\n\t\t\t\tlog.Infoln(\"Core has been successfully installed.\")\n\t\t\t} else {\n\t\t\t\tlog.Errorln(\"Core could not be installed:\", err)\n\t\t\t}\n\t\t}\n\t}\n\tverifySolrCore(SolrCore)\n}\n\nfunc (SolrCore *SolrCore) Uninstall() {\n\tif verifySolrInstall() && verifySolrCLI() {\n\t\t_, err := exec.Command(\"sh\", \"-c\", \"\/opt\/solr\/bin\/solr\", \"delete\", \"-c\", SolrCore.Name).Output()\n\t\tif err == nil {\n\t\t\tlog.Infoln(\"Core has been successfully uninstalled.\")\n\t\t} else {\n\t\t\tlog.Errorln(\"Core could not be uninstalled:\", err)\n\t\t}\n\t} else if verifySolrInstall() && !verifySolrCLI() {\n\t\t_, err := exec.Command(\"curl\", SolrCore.Address+\"\/solr\/admin\/cores?action=UNLOAD&core=\"+SolrCore.Name).Output()\n\t\tif err == nil {\n\t\t\tlog.Infoln(\"Core has been successfully uninstalled.\")\n\t\t} else {\n\t\t\tlog.Errorln(\"Core could not be uninstalled:\", err)\n\t\t}\n\t}\n\terr := os.RemoveAll(SolrCore.Path + \"\/\" + SolrCore.Name)\n\tif err == nil {\n\t\tlog.Infoln(\"Core resources have been removed.\")\n\t} else {\n\t\tlog.Errorln(\"Core resources could not be removed:\", err)\n\t}\n}\n<commit_msg>Fallback to curl as a fixed solution for creating and deleting cores.<commit_after>package make\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n)\n\ntype SolrCore struct {\n\tAddress  string\n\tName     string\n\tTemplate string\n\tPath     string\n\tLegacy   bool\n}\n\nfunc logSolrInstall() bool {\n\tif verifySolrInstall() {\n\t\tlog.Infoln(\"Found Solr installation\")\n\t\treturn true\n\t} else {\n\t\tlog.Errorln(\"Could not find Solr installation\")\n\t\treturn false\n\t}\n}\nfunc logSolrCLI() bool {\n\tif verifySolrCLI() {\n\t\tlog.Infoln(\"Found Solr command-line tools\")\n\t\treturn true\n\t} else {\n\t\tlog.Warnln(\"Could not find Solr command-line tools\")\n\t\treturn false\n\t}\n}\nfunc logResources(Template string) bool {\n\tif verifyResources(Template) {\n\t\tlog.Infoln(\"Found configuration folder\")\n\t\treturn true\n\t} else {\n\t\tlog.Errorln(\"Could not find configuration folder\")\n\t\treturn false\n\t}\n}\nfunc logSolrCore(SolrCore *SolrCore) bool {\n\tif verifySolrCore(SolrCore) {\n\t\tlog.Infoln(\"Solr core is installed.\")\n\t\treturn true\n\t} else {\n\t\tlog.Warnln(\"Solr core is not installed.\")\n\t\treturn false\n\t}\n}\nfunc verifySolrInstall() bool {\n\t_, err := os.Stat(\"\/opt\/solr\")\n\tif err == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\nfunc verifySolrCLI() bool {\n\t_, err := os.Stat(\"\/opt\/solr\/bin\/solr\")\n\tif err == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\nfunc verifyResources(Template string) bool {\n\t_, err := os.Stat(Template)\n\tif err == nil {\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\nfunc verifySolrCore(SolrCore *SolrCore) bool {\n\tcurlResponse, err := exec.Command(\"curl\", SolrCore.Address+\"\/solr\/admin\/cores?action=STATUS\").Output()\n\tif err == nil {\n\t\tif strings.Contains(string(curlResponse), `<str name=\"name\">`+SolrCore.Name+`<\/str>`) == true {\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\tlog.Errorln(\"Solr could not be accessed using CURL:\", err.Error())\n\t}\n\treturn false\n}\n\nfunc NewCore(Address, Name, Template, Path string) SolrCore {\n\treturn SolrCore{Address, Name, Template, Path, false}\n}\n\nfunc (SolrCore *SolrCore) Install() {\n\tif logSolrInstall() && logResources(SolrCore.Template) {\n\t\tlog.Infoln(\"All checks have passed.\")\n\t\tdataDir := \"\"\n\t\tif SolrCore.Legacy {\n\t\t\tlog.Infoln(\"Installing legacy file system for Solr < 5.0\")\n\t\t\tdataDir = SolrCore.Path + \"\/\" + SolrCore.Name + \"\/conf\/\"\n\t\t} else {\n\t\t\tdataDir = SolrCore.Path + \"\/data\/\" + SolrCore.Name + \"\/conf\/\"\n\t\t}\n\n\t\t\/\/ Create data directories\n\t\terr := os.MkdirAll(dataDir, 0777)\n\t\tif err == nil {\n\t\t\tlog.Infoln(\"Directory has been created.\", dataDir)\n\t\t} else {\n\t\t\tlog.Errorln(\"Directory has not been created:\", err.Error())\n\t\t}\n\n\t\t\/\/ Sync\n\t\t_, err = exec.Command(\"rsync\", \"-a\", SolrCore.Template+\"\/\", dataDir).Output()\n\t\tif err == nil {\n\t\t\tlog.Infoln(\"Configuration has been synced with boilerplate resources.\")\n\t\t} else {\n\t\t\tlog.Errorln(\"Configuration could not be synced with boilerplate resources:\", err.Error())\n\t\t}\n\n\t\t_, err = exec.Command(\"curl\", SolrCore.Address+\"\/solr\/admin\/cores?action=CREATE&name=\"+SolrCore.Name+\"&instanceDir=\"+SolrCore.Name+\"&dataDir=data&config=solrconfig.xml&schema=schema.xml\").Output()\n\t\tif err == nil {\n\t\t\tlog.Infoln(\"Core has been successfully installed.\")\n\t\t} else {\n\t\t\tlog.Errorln(\"Core could not be installed:\", err)\n\t\t}\n\t}\n\tverifySolrCore(SolrCore)\n}\n\nfunc (SolrCore *SolrCore) Uninstall() {\n\t_, err := exec.Command(\"curl\", SolrCore.Address+\"\/solr\/admin\/cores?action=UNLOAD&core=\"+SolrCore.Name).Output()\n\tif err == nil {\n\t\tlog.Infoln(\"Core has been successfully uninstalled.\")\n\t} else {\n\t\tlog.Errorln(\"Core could not be uninstalled:\", err)\n\t}\n\terr = os.RemoveAll(SolrCore.Path + \"\/\" + SolrCore.Name)\n\tif err == nil {\n\t\tlog.Infoln(\"Core resources have been removed.\")\n\t} else {\n\t\tlog.Errorln(\"Core resources could not be removed:\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package libcontainer\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"runtime\/debug\"\n\t\"strconv\"\n\n\tsecurejoin \"github.com\/cyphar\/filepath-securejoin\"\n\t\"github.com\/moby\/sys\/mountinfo\"\n\t\"golang.org\/x\/sys\/unix\"\n\n\t\"github.com\/opencontainers\/runc\/libcontainer\/cgroups\/manager\"\n\t\"github.com\/opencontainers\/runc\/libcontainer\/configs\"\n\t\"github.com\/opencontainers\/runc\/libcontainer\/configs\/validate\"\n\t\"github.com\/opencontainers\/runc\/libcontainer\/intelrdt\"\n\t\"github.com\/opencontainers\/runc\/libcontainer\/utils\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nconst (\n\tstateFilename    = \"state.json\"\n\texecFifoFilename = \"exec.fifo\"\n)\n\nvar idRegex = regexp.MustCompile(`^[\\w+-\\.]+$`)\n\n\/\/ InitArgs returns an options func to configure a LinuxFactory with the\n\/\/ provided init binary path and arguments.\nfunc InitArgs(args ...string) func(*LinuxFactory) error {\n\treturn func(l *LinuxFactory) (err error) {\n\t\tif len(args) > 0 {\n\t\t\t\/\/ Resolve relative paths to ensure that its available\n\t\t\t\/\/ after directory changes.\n\t\t\tif args[0], err = filepath.Abs(args[0]); err != nil {\n\t\t\t\t\/\/ The only error returned from filepath.Abs is\n\t\t\t\t\/\/ the one from os.Getwd, i.e. a system error.\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tl.InitArgs = args\n\t\treturn nil\n\t}\n}\n\n\/\/ IntelRdtfs is an options func to configure a LinuxFactory to return\n\/\/ containers that use the Intel RDT \"resource control\" filesystem to\n\/\/ create and manage Intel RDT resources (e.g., L3 cache, memory bandwidth).\nfunc IntelRdtFs(l *LinuxFactory) error {\n\tif !intelrdt.IsCATEnabled() && !intelrdt.IsMBAEnabled() {\n\t\tl.NewIntelRdtManager = nil\n\t} else {\n\t\tl.NewIntelRdtManager = func(config *configs.Config, id string, path string) intelrdt.Manager {\n\t\t\treturn intelrdt.NewManager(config, id, path)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ TmpfsRoot is an option func to mount LinuxFactory.Root to tmpfs.\nfunc TmpfsRoot(l *LinuxFactory) error {\n\tmounted, err := mountinfo.Mounted(l.Root)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !mounted {\n\t\tif err := mount(\"tmpfs\", l.Root, \"\", \"tmpfs\", 0, \"\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ CriuPath returns an option func to configure a LinuxFactory with the\n\/\/ provided criupath\nfunc CriuPath(criupath string) func(*LinuxFactory) error {\n\treturn func(l *LinuxFactory) error {\n\t\tl.CriuPath = criupath\n\t\treturn nil\n\t}\n}\n\n\/\/ New returns a linux based container factory based in the root directory and\n\/\/ configures the factory with the provided option funcs.\nfunc New(root string, options ...func(*LinuxFactory) error) (Factory, error) {\n\tif root != \"\" {\n\t\tif err := os.MkdirAll(root, 0o700); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tl := &LinuxFactory{\n\t\tRoot:      root,\n\t\tInitPath:  \"\/proc\/self\/exe\",\n\t\tInitArgs:  []string{os.Args[0], \"init\"},\n\t\tValidator: validate.New(),\n\t\tCriuPath:  \"criu\",\n\t}\n\n\tfor _, opt := range options {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := opt(l); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn l, nil\n}\n\n\/\/ LinuxFactory implements the default factory interface for linux based systems.\ntype LinuxFactory struct {\n\t\/\/ Root directory for the factory to store state.\n\tRoot string\n\n\t\/\/ InitPath is the path for calling the init responsibilities for spawning\n\t\/\/ a container.\n\tInitPath string\n\n\t\/\/ InitArgs are arguments for calling the init responsibilities for spawning\n\t\/\/ a container.\n\tInitArgs []string\n\n\t\/\/ CriuPath is the path to the criu binary used for checkpoint and restore of\n\t\/\/ containers.\n\tCriuPath string\n\n\t\/\/ New{u,g}idmapPath is the path to the binaries used for mapping with\n\t\/\/ rootless containers.\n\tNewuidmapPath string\n\tNewgidmapPath string\n\n\t\/\/ Validator provides validation to container configurations.\n\tValidator validate.Validator\n\n\t\/\/ NewIntelRdtManager returns an initialized Intel RDT manager for a single container.\n\tNewIntelRdtManager func(config *configs.Config, id string, path string) intelrdt.Manager\n}\n\nfunc (l *LinuxFactory) Create(id string, config *configs.Config) (Container, error) {\n\tif l.Root == \"\" {\n\t\treturn nil, errors.New(\"root not set\")\n\t}\n\tif err := l.validateID(id); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := l.Validator.Validate(config); err != nil {\n\t\treturn nil, err\n\t}\n\tcontainerRoot, err := securejoin.SecureJoin(l.Root, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err := os.Stat(containerRoot); err == nil {\n\t\treturn nil, ErrExist\n\t} else if !os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\tcm, err := manager.New(config.Cgroups)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Check that cgroup does not exist or empty (no processes).\n\t\/\/ Note for cgroup v1 this check is not thorough, as there are multiple\n\t\/\/ separate hierarchies, while both Exists() and GetAllPids() only use\n\t\/\/ one for \"devices\" controller (assuming others are the same, which is\n\t\/\/ probably true in almost all scenarios). Checking all the hierarchies\n\t\/\/ would be too expensive.\n\tif cm.Exists() {\n\t\tpids, err := cm.GetAllPids()\n\t\t\/\/ Reading PIDs can race with cgroups removal, so ignore ENOENT and ENODEV.\n\t\tif err != nil && !errors.Is(err, os.ErrNotExist) && !errors.Is(err, unix.ENODEV) {\n\t\t\treturn nil, fmt.Errorf(\"unable to get cgroup PIDs: %w\", err)\n\t\t}\n\t\tif len(pids) != 0 {\n\t\t\t\/\/ TODO: return an error.\n\t\t\tlogrus.Warnf(\"container's cgroup is not empty: %d process(es) found\", len(pids))\n\t\t\tlogrus.Warn(\"DEPRECATED: running container in a non-empty cgroup won't be supported in runc 1.2; https:\/\/github.com\/opencontainers\/runc\/issues\/3132\")\n\t\t}\n\t}\n\n\t\/\/ Check that cgroup is not frozen. Do not use Exists() here\n\t\/\/ since in cgroup v1 it only checks \"devices\" controller.\n\tst, err := cm.GetFreezerState()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get cgroup freezer state: %w\", err)\n\t}\n\tif st == configs.Frozen {\n\t\treturn nil, errors.New(\"container's cgroup unexpectedly frozen\")\n\t}\n\n\tif err := os.MkdirAll(containerRoot, 0o711); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := os.Chown(containerRoot, unix.Geteuid(), unix.Getegid()); err != nil {\n\t\treturn nil, err\n\t}\n\tc := &linuxContainer{\n\t\tid:            id,\n\t\troot:          containerRoot,\n\t\tconfig:        config,\n\t\tinitPath:      l.InitPath,\n\t\tinitArgs:      l.InitArgs,\n\t\tcriuPath:      l.CriuPath,\n\t\tnewuidmapPath: l.NewuidmapPath,\n\t\tnewgidmapPath: l.NewgidmapPath,\n\t\tcgroupManager: cm,\n\t}\n\tif l.NewIntelRdtManager != nil {\n\t\tc.intelRdtManager = l.NewIntelRdtManager(config, id, \"\")\n\t}\n\tc.state = &stoppedState{c: c}\n\treturn c, nil\n}\n\nfunc (l *LinuxFactory) Load(id string) (Container, error) {\n\tif l.Root == \"\" {\n\t\treturn nil, errors.New(\"root not set\")\n\t}\n\t\/\/ when load, we need to check id is valid or not.\n\tif err := l.validateID(id); err != nil {\n\t\treturn nil, err\n\t}\n\tcontainerRoot, err := securejoin.SecureJoin(l.Root, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstate, err := l.loadState(containerRoot)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := &nonChildProcess{\n\t\tprocessPid:       state.InitProcessPid,\n\t\tprocessStartTime: state.InitProcessStartTime,\n\t\tfds:              state.ExternalDescriptors,\n\t}\n\tcm, err := manager.NewWithPaths(state.Config.Cgroups, state.CgroupPaths)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &linuxContainer{\n\t\tinitProcess:          r,\n\t\tinitProcessStartTime: state.InitProcessStartTime,\n\t\tid:                   id,\n\t\tconfig:               &state.Config,\n\t\tinitPath:             l.InitPath,\n\t\tinitArgs:             l.InitArgs,\n\t\tcriuPath:             l.CriuPath,\n\t\tnewuidmapPath:        l.NewuidmapPath,\n\t\tnewgidmapPath:        l.NewgidmapPath,\n\t\tcgroupManager:        cm,\n\t\troot:                 containerRoot,\n\t\tcreated:              state.Created,\n\t}\n\tif l.NewIntelRdtManager != nil {\n\t\tc.intelRdtManager = l.NewIntelRdtManager(&state.Config, id, state.IntelRdtPath)\n\t}\n\tc.state = &loadedState{c: c}\n\tif err := c.refreshState(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}\n\nfunc (l *LinuxFactory) Type() string {\n\treturn \"libcontainer\"\n}\n\n\/\/ StartInitialization loads a container by opening the pipe fd from the parent to read the configuration and state\n\/\/ This is a low level implementation detail of the reexec and should not be consumed externally\nfunc (l *LinuxFactory) StartInitialization() (err error) {\n\t\/\/ Get the INITPIPE.\n\tenvInitPipe := os.Getenv(\"_LIBCONTAINER_INITPIPE\")\n\tpipefd, err := strconv.Atoi(envInitPipe)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable to convert _LIBCONTAINER_INITPIPE: %w\", err)\n\t\tlogrus.Error(err)\n\t\treturn err\n\t}\n\tpipe := os.NewFile(uintptr(pipefd), \"pipe\")\n\tdefer pipe.Close()\n\n\tdefer func() {\n\t\t\/\/ We have an error during the initialization of the container's init,\n\t\t\/\/ send it back to the parent process in the form of an initError.\n\t\tif werr := writeSync(pipe, procError); werr != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\treturn\n\t\t}\n\t\tif werr := utils.WriteJSON(pipe, &initError{Message: err.Error()}); werr != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\treturn\n\t\t}\n\t}()\n\n\t\/\/ Only init processes have FIFOFD.\n\tfifofd := -1\n\tenvInitType := os.Getenv(\"_LIBCONTAINER_INITTYPE\")\n\tit := initType(envInitType)\n\tif it == initStandard {\n\t\tenvFifoFd := os.Getenv(\"_LIBCONTAINER_FIFOFD\")\n\t\tif fifofd, err = strconv.Atoi(envFifoFd); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to convert _LIBCONTAINER_FIFOFD: %w\", err)\n\t\t}\n\t}\n\n\tvar consoleSocket *os.File\n\tif envConsole := os.Getenv(\"_LIBCONTAINER_CONSOLE\"); envConsole != \"\" {\n\t\tconsole, err := strconv.Atoi(envConsole)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to convert _LIBCONTAINER_CONSOLE: %w\", err)\n\t\t}\n\t\tconsoleSocket = os.NewFile(uintptr(console), \"console-socket\")\n\t\tdefer consoleSocket.Close()\n\t}\n\n\tlogPipeFdStr := os.Getenv(\"_LIBCONTAINER_LOGPIPE\")\n\tlogPipeFd, err := strconv.Atoi(logPipeFdStr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to convert _LIBCONTAINER_LOGPIPE: %w\", err)\n\t}\n\n\t\/\/ Get mount files (O_PATH).\n\tmountFds, err := parseMountFds()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ clear the current process's environment to clean any libcontainer\n\t\/\/ specific env vars.\n\tos.Clearenv()\n\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"panic from initialization: %w, %v\", e, string(debug.Stack()))\n\t\t}\n\t}()\n\n\ti, err := newContainerInit(it, pipe, consoleSocket, fifofd, logPipeFd, mountFds)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ If Init succeeds, syscall.Exec will not return, hence none of the defers will be called.\n\treturn i.Init()\n}\n\nfunc (l *LinuxFactory) loadState(root string) (*State, error) {\n\tstateFilePath, err := securejoin.SecureJoin(root, stateFilename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf, err := os.Open(stateFilePath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, ErrNotExist\n\t\t}\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tvar state *State\n\tif err := json.NewDecoder(f).Decode(&state); err != nil {\n\t\treturn nil, err\n\t}\n\treturn state, nil\n}\n\nfunc (l *LinuxFactory) validateID(id string) error {\n\tif !idRegex.MatchString(id) || string(os.PathSeparator)+id != utils.CleanPath(string(os.PathSeparator)+id) {\n\t\treturn ErrInvalidID\n\t}\n\n\treturn nil\n}\n\n\/\/ NewuidmapPath returns an option func to configure a LinuxFactory with the\n\/\/ provided ..\nfunc NewuidmapPath(newuidmapPath string) func(*LinuxFactory) error {\n\treturn func(l *LinuxFactory) error {\n\t\tl.NewuidmapPath = newuidmapPath\n\t\treturn nil\n\t}\n}\n\n\/\/ NewgidmapPath returns an option func to configure a LinuxFactory with the\n\/\/ provided ..\nfunc NewgidmapPath(newgidmapPath string) func(*LinuxFactory) error {\n\treturn func(l *LinuxFactory) error {\n\t\tl.NewgidmapPath = newgidmapPath\n\t\treturn nil\n\t}\n}\n\nfunc parseMountFds() ([]int, error) {\n\tfdsJson := os.Getenv(\"_LIBCONTAINER_MOUNT_FDS\")\n\tif fdsJson == \"\" {\n\t\t\/\/ Always return the nil slice if no fd is present.\n\t\treturn nil, nil\n\t}\n\n\tvar mountFds []int\n\tif err := json.Unmarshal([]byte(fdsJson), &mountFds); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error unmarshalling _LIBCONTAINER_MOUNT_FDS: %w\", err)\n\t}\n\n\treturn mountFds, nil\n}\n<commit_msg>libct: Create: rm unneeded chown<commit_after>package libcontainer\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"runtime\/debug\"\n\t\"strconv\"\n\n\tsecurejoin \"github.com\/cyphar\/filepath-securejoin\"\n\t\"github.com\/moby\/sys\/mountinfo\"\n\t\"golang.org\/x\/sys\/unix\"\n\n\t\"github.com\/opencontainers\/runc\/libcontainer\/cgroups\/manager\"\n\t\"github.com\/opencontainers\/runc\/libcontainer\/configs\"\n\t\"github.com\/opencontainers\/runc\/libcontainer\/configs\/validate\"\n\t\"github.com\/opencontainers\/runc\/libcontainer\/intelrdt\"\n\t\"github.com\/opencontainers\/runc\/libcontainer\/utils\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nconst (\n\tstateFilename    = \"state.json\"\n\texecFifoFilename = \"exec.fifo\"\n)\n\nvar idRegex = regexp.MustCompile(`^[\\w+-\\.]+$`)\n\n\/\/ InitArgs returns an options func to configure a LinuxFactory with the\n\/\/ provided init binary path and arguments.\nfunc InitArgs(args ...string) func(*LinuxFactory) error {\n\treturn func(l *LinuxFactory) (err error) {\n\t\tif len(args) > 0 {\n\t\t\t\/\/ Resolve relative paths to ensure that its available\n\t\t\t\/\/ after directory changes.\n\t\t\tif args[0], err = filepath.Abs(args[0]); err != nil {\n\t\t\t\t\/\/ The only error returned from filepath.Abs is\n\t\t\t\t\/\/ the one from os.Getwd, i.e. a system error.\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tl.InitArgs = args\n\t\treturn nil\n\t}\n}\n\n\/\/ IntelRdtfs is an options func to configure a LinuxFactory to return\n\/\/ containers that use the Intel RDT \"resource control\" filesystem to\n\/\/ create and manage Intel RDT resources (e.g., L3 cache, memory bandwidth).\nfunc IntelRdtFs(l *LinuxFactory) error {\n\tif !intelrdt.IsCATEnabled() && !intelrdt.IsMBAEnabled() {\n\t\tl.NewIntelRdtManager = nil\n\t} else {\n\t\tl.NewIntelRdtManager = func(config *configs.Config, id string, path string) intelrdt.Manager {\n\t\t\treturn intelrdt.NewManager(config, id, path)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ TmpfsRoot is an option func to mount LinuxFactory.Root to tmpfs.\nfunc TmpfsRoot(l *LinuxFactory) error {\n\tmounted, err := mountinfo.Mounted(l.Root)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !mounted {\n\t\tif err := mount(\"tmpfs\", l.Root, \"\", \"tmpfs\", 0, \"\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ CriuPath returns an option func to configure a LinuxFactory with the\n\/\/ provided criupath\nfunc CriuPath(criupath string) func(*LinuxFactory) error {\n\treturn func(l *LinuxFactory) error {\n\t\tl.CriuPath = criupath\n\t\treturn nil\n\t}\n}\n\n\/\/ New returns a linux based container factory based in the root directory and\n\/\/ configures the factory with the provided option funcs.\nfunc New(root string, options ...func(*LinuxFactory) error) (Factory, error) {\n\tif root != \"\" {\n\t\tif err := os.MkdirAll(root, 0o700); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tl := &LinuxFactory{\n\t\tRoot:      root,\n\t\tInitPath:  \"\/proc\/self\/exe\",\n\t\tInitArgs:  []string{os.Args[0], \"init\"},\n\t\tValidator: validate.New(),\n\t\tCriuPath:  \"criu\",\n\t}\n\n\tfor _, opt := range options {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := opt(l); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn l, nil\n}\n\n\/\/ LinuxFactory implements the default factory interface for linux based systems.\ntype LinuxFactory struct {\n\t\/\/ Root directory for the factory to store state.\n\tRoot string\n\n\t\/\/ InitPath is the path for calling the init responsibilities for spawning\n\t\/\/ a container.\n\tInitPath string\n\n\t\/\/ InitArgs are arguments for calling the init responsibilities for spawning\n\t\/\/ a container.\n\tInitArgs []string\n\n\t\/\/ CriuPath is the path to the criu binary used for checkpoint and restore of\n\t\/\/ containers.\n\tCriuPath string\n\n\t\/\/ New{u,g}idmapPath is the path to the binaries used for mapping with\n\t\/\/ rootless containers.\n\tNewuidmapPath string\n\tNewgidmapPath string\n\n\t\/\/ Validator provides validation to container configurations.\n\tValidator validate.Validator\n\n\t\/\/ NewIntelRdtManager returns an initialized Intel RDT manager for a single container.\n\tNewIntelRdtManager func(config *configs.Config, id string, path string) intelrdt.Manager\n}\n\nfunc (l *LinuxFactory) Create(id string, config *configs.Config) (Container, error) {\n\tif l.Root == \"\" {\n\t\treturn nil, errors.New(\"root not set\")\n\t}\n\tif err := l.validateID(id); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := l.Validator.Validate(config); err != nil {\n\t\treturn nil, err\n\t}\n\tcontainerRoot, err := securejoin.SecureJoin(l.Root, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err := os.Stat(containerRoot); err == nil {\n\t\treturn nil, ErrExist\n\t} else if !os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\tcm, err := manager.New(config.Cgroups)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Check that cgroup does not exist or empty (no processes).\n\t\/\/ Note for cgroup v1 this check is not thorough, as there are multiple\n\t\/\/ separate hierarchies, while both Exists() and GetAllPids() only use\n\t\/\/ one for \"devices\" controller (assuming others are the same, which is\n\t\/\/ probably true in almost all scenarios). Checking all the hierarchies\n\t\/\/ would be too expensive.\n\tif cm.Exists() {\n\t\tpids, err := cm.GetAllPids()\n\t\t\/\/ Reading PIDs can race with cgroups removal, so ignore ENOENT and ENODEV.\n\t\tif err != nil && !errors.Is(err, os.ErrNotExist) && !errors.Is(err, unix.ENODEV) {\n\t\t\treturn nil, fmt.Errorf(\"unable to get cgroup PIDs: %w\", err)\n\t\t}\n\t\tif len(pids) != 0 {\n\t\t\t\/\/ TODO: return an error.\n\t\t\tlogrus.Warnf(\"container's cgroup is not empty: %d process(es) found\", len(pids))\n\t\t\tlogrus.Warn(\"DEPRECATED: running container in a non-empty cgroup won't be supported in runc 1.2; https:\/\/github.com\/opencontainers\/runc\/issues\/3132\")\n\t\t}\n\t}\n\n\t\/\/ Check that cgroup is not frozen. Do not use Exists() here\n\t\/\/ since in cgroup v1 it only checks \"devices\" controller.\n\tst, err := cm.GetFreezerState()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get cgroup freezer state: %w\", err)\n\t}\n\tif st == configs.Frozen {\n\t\treturn nil, errors.New(\"container's cgroup unexpectedly frozen\")\n\t}\n\n\tif err := os.MkdirAll(containerRoot, 0o711); err != nil {\n\t\treturn nil, err\n\t}\n\tc := &linuxContainer{\n\t\tid:            id,\n\t\troot:          containerRoot,\n\t\tconfig:        config,\n\t\tinitPath:      l.InitPath,\n\t\tinitArgs:      l.InitArgs,\n\t\tcriuPath:      l.CriuPath,\n\t\tnewuidmapPath: l.NewuidmapPath,\n\t\tnewgidmapPath: l.NewgidmapPath,\n\t\tcgroupManager: cm,\n\t}\n\tif l.NewIntelRdtManager != nil {\n\t\tc.intelRdtManager = l.NewIntelRdtManager(config, id, \"\")\n\t}\n\tc.state = &stoppedState{c: c}\n\treturn c, nil\n}\n\nfunc (l *LinuxFactory) Load(id string) (Container, error) {\n\tif l.Root == \"\" {\n\t\treturn nil, errors.New(\"root not set\")\n\t}\n\t\/\/ when load, we need to check id is valid or not.\n\tif err := l.validateID(id); err != nil {\n\t\treturn nil, err\n\t}\n\tcontainerRoot, err := securejoin.SecureJoin(l.Root, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstate, err := l.loadState(containerRoot)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := &nonChildProcess{\n\t\tprocessPid:       state.InitProcessPid,\n\t\tprocessStartTime: state.InitProcessStartTime,\n\t\tfds:              state.ExternalDescriptors,\n\t}\n\tcm, err := manager.NewWithPaths(state.Config.Cgroups, state.CgroupPaths)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &linuxContainer{\n\t\tinitProcess:          r,\n\t\tinitProcessStartTime: state.InitProcessStartTime,\n\t\tid:                   id,\n\t\tconfig:               &state.Config,\n\t\tinitPath:             l.InitPath,\n\t\tinitArgs:             l.InitArgs,\n\t\tcriuPath:             l.CriuPath,\n\t\tnewuidmapPath:        l.NewuidmapPath,\n\t\tnewgidmapPath:        l.NewgidmapPath,\n\t\tcgroupManager:        cm,\n\t\troot:                 containerRoot,\n\t\tcreated:              state.Created,\n\t}\n\tif l.NewIntelRdtManager != nil {\n\t\tc.intelRdtManager = l.NewIntelRdtManager(&state.Config, id, state.IntelRdtPath)\n\t}\n\tc.state = &loadedState{c: c}\n\tif err := c.refreshState(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}\n\nfunc (l *LinuxFactory) Type() string {\n\treturn \"libcontainer\"\n}\n\n\/\/ StartInitialization loads a container by opening the pipe fd from the parent to read the configuration and state\n\/\/ This is a low level implementation detail of the reexec and should not be consumed externally\nfunc (l *LinuxFactory) StartInitialization() (err error) {\n\t\/\/ Get the INITPIPE.\n\tenvInitPipe := os.Getenv(\"_LIBCONTAINER_INITPIPE\")\n\tpipefd, err := strconv.Atoi(envInitPipe)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"unable to convert _LIBCONTAINER_INITPIPE: %w\", err)\n\t\tlogrus.Error(err)\n\t\treturn err\n\t}\n\tpipe := os.NewFile(uintptr(pipefd), \"pipe\")\n\tdefer pipe.Close()\n\n\tdefer func() {\n\t\t\/\/ We have an error during the initialization of the container's init,\n\t\t\/\/ send it back to the parent process in the form of an initError.\n\t\tif werr := writeSync(pipe, procError); werr != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\treturn\n\t\t}\n\t\tif werr := utils.WriteJSON(pipe, &initError{Message: err.Error()}); werr != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\treturn\n\t\t}\n\t}()\n\n\t\/\/ Only init processes have FIFOFD.\n\tfifofd := -1\n\tenvInitType := os.Getenv(\"_LIBCONTAINER_INITTYPE\")\n\tit := initType(envInitType)\n\tif it == initStandard {\n\t\tenvFifoFd := os.Getenv(\"_LIBCONTAINER_FIFOFD\")\n\t\tif fifofd, err = strconv.Atoi(envFifoFd); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to convert _LIBCONTAINER_FIFOFD: %w\", err)\n\t\t}\n\t}\n\n\tvar consoleSocket *os.File\n\tif envConsole := os.Getenv(\"_LIBCONTAINER_CONSOLE\"); envConsole != \"\" {\n\t\tconsole, err := strconv.Atoi(envConsole)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to convert _LIBCONTAINER_CONSOLE: %w\", err)\n\t\t}\n\t\tconsoleSocket = os.NewFile(uintptr(console), \"console-socket\")\n\t\tdefer consoleSocket.Close()\n\t}\n\n\tlogPipeFdStr := os.Getenv(\"_LIBCONTAINER_LOGPIPE\")\n\tlogPipeFd, err := strconv.Atoi(logPipeFdStr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to convert _LIBCONTAINER_LOGPIPE: %w\", err)\n\t}\n\n\t\/\/ Get mount files (O_PATH).\n\tmountFds, err := parseMountFds()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ clear the current process's environment to clean any libcontainer\n\t\/\/ specific env vars.\n\tos.Clearenv()\n\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"panic from initialization: %w, %v\", e, string(debug.Stack()))\n\t\t}\n\t}()\n\n\ti, err := newContainerInit(it, pipe, consoleSocket, fifofd, logPipeFd, mountFds)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ If Init succeeds, syscall.Exec will not return, hence none of the defers will be called.\n\treturn i.Init()\n}\n\nfunc (l *LinuxFactory) loadState(root string) (*State, error) {\n\tstateFilePath, err := securejoin.SecureJoin(root, stateFilename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tf, err := os.Open(stateFilePath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, ErrNotExist\n\t\t}\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tvar state *State\n\tif err := json.NewDecoder(f).Decode(&state); err != nil {\n\t\treturn nil, err\n\t}\n\treturn state, nil\n}\n\nfunc (l *LinuxFactory) validateID(id string) error {\n\tif !idRegex.MatchString(id) || string(os.PathSeparator)+id != utils.CleanPath(string(os.PathSeparator)+id) {\n\t\treturn ErrInvalidID\n\t}\n\n\treturn nil\n}\n\n\/\/ NewuidmapPath returns an option func to configure a LinuxFactory with the\n\/\/ provided ..\nfunc NewuidmapPath(newuidmapPath string) func(*LinuxFactory) error {\n\treturn func(l *LinuxFactory) error {\n\t\tl.NewuidmapPath = newuidmapPath\n\t\treturn nil\n\t}\n}\n\n\/\/ NewgidmapPath returns an option func to configure a LinuxFactory with the\n\/\/ provided ..\nfunc NewgidmapPath(newgidmapPath string) func(*LinuxFactory) error {\n\treturn func(l *LinuxFactory) error {\n\t\tl.NewgidmapPath = newgidmapPath\n\t\treturn nil\n\t}\n}\n\nfunc parseMountFds() ([]int, error) {\n\tfdsJson := os.Getenv(\"_LIBCONTAINER_MOUNT_FDS\")\n\tif fdsJson == \"\" {\n\t\t\/\/ Always return the nil slice if no fd is present.\n\t\treturn nil, nil\n\t}\n\n\tvar mountFds []int\n\tif err := json.Unmarshal([]byte(fdsJson), &mountFds); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error unmarshalling _LIBCONTAINER_MOUNT_FDS: %w\", err)\n\t}\n\n\treturn mountFds, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/Shopify\/themekit\/src\/cmdutil\"\n\t\"github.com\/Shopify\/themekit\/src\/colors\"\n\t\"github.com\/Shopify\/themekit\/src\/file\"\n\t\"github.com\/Shopify\/themekit\/src\/shopify\"\n)\n\nconst settingsDataKey = \"config\/settings_data.json\"\n\nvar (\n\tdeployCmd = &cobra.Command{\n\t\tUse:   \"deploy <filenames>\",\n\t\tShort: \"deploy files to shopify\",\n\t\tLong: `Deploy will overwrite specific files if provided with file names.\n If deploy is not provided with file names then it will deploy all\n the files on shopify with your local files. Any files that do not\n exist on your local machine will be removed from shopify unless the --soft\n flag is passed\n\n For more documentation please see http:\/\/shopify.github.io\/themekit\/commands\/#deploy\n `,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn cmdutil.ForEachClient(flags, args, deploy)\n\t\t},\n\t}\n\n\treplaceCmd = &cobra.Command{\n\t\tUse:   \"replace <filenames>\",\n\t\tShort: \"Overwrite theme file(s)\",\n\t\tLong: `Replace will overwrite specific files if provided with file names.\n If replace is not provided with file names then it will replace all\n the files on shopify with your local files. Any files that do not\n exist on your local machine will be removed from shopify.\n\n  Deprecation Notice: This command is deprecated in v0.8.0 and will be removed in\n\tv0.8.1. Please use the 'deploy' command instead.\n\n For more documentation please see http:\/\/shopify.github.io\/themekit\/commands\/#replace\n `,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcolors.ColorStdOut.Printf(\"[%s] replace has been deprecated please use `deploy` instead\", colors.Yellow(\"WARN\"))\n\t\t\treturn cmdutil.ForEachClient(flags, args, deploy)\n\t\t},\n\t}\n\n\tuploadCmd = &cobra.Command{\n\t\tUse:   \"upload <filenames>\",\n\t\tShort: \"Upload theme file(s) to shopify\",\n\t\tLong: `Upload will upload specific files to shopify servers if provided file names.\n If no filenames are provided then upload will upload every file in the project\n to shopify.\n\n  Deprecation Notice: This command is deprecated in v0.8.0 and will be removed in\n\tv0.8.1. Please use the 'deploy' command instead.\n\n For more documentation please see http:\/\/shopify.github.io\/themekit\/commands\/#upload\n `,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcolors.ColorStdOut.Printf(\"[%s] upload has been deprecated please use `deploy` with the --nodelete flag instead\", colors.Yellow(\"WARN\"))\n\t\t\tflags.NoDelete = true\n\t\t\treturn cmdutil.ForEachClient(flags, args, deploy)\n\t\t},\n\t}\n)\n\nfunc deploy(ctx cmdutil.Ctx) error {\n\tif ctx.Env.ReadOnly {\n\t\treturn fmt.Errorf(\"[%s] environment is readonly\", colors.Green(ctx.Env.Name))\n\t}\n\n\tassetsActions, err := generateActions(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar deployGroup sync.WaitGroup\n\tctx.StartProgress(len(assetsActions))\n\tfor path, op := range assetsActions {\n\t\tif path == settingsDataKey {\n\t\t\tdefer perform(ctx, path, op)\n\t\t\tcontinue\n\t\t}\n\t\tdeployGroup.Add(1)\n\t\tgo func(path string, op file.Op) {\n\t\t\tdefer deployGroup.Done()\n\t\t\tperform(ctx, path, op)\n\t\t}(path, op)\n\t}\n\n\tdeployGroup.Wait()\n\treturn nil\n}\n\nfunc generateActions(ctx cmdutil.Ctx) (map[string]file.Op, error) {\n\tassetsActions := map[string]file.Op{}\n\n\tif len(ctx.Args) == 0 && !ctx.Flags.NoDelete {\n\t\tremoteFiles, err := ctx.Client.GetAllAssets()\n\t\tif err != nil {\n\t\t\treturn assetsActions, err\n\t\t}\n\t\tfor _, filename := range remoteFiles {\n\t\t\tassetsActions[filename] = file.Remove\n\t\t}\n\t}\n\n\tlocalAssets, err := shopify.FindAssets(ctx.Env, ctx.Args...)\n\tif err != nil {\n\t\treturn assetsActions, err\n\t}\n\n\tfor _, path := range localAssets {\n\t\tassetsActions[path] = file.Update\n\t}\n\treturn assetsActions, nil\n}\n<commit_msg>Fixing windows deploy filepaths<commit_after>package cmd\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"sync\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/Shopify\/themekit\/src\/cmdutil\"\n\t\"github.com\/Shopify\/themekit\/src\/colors\"\n\t\"github.com\/Shopify\/themekit\/src\/file\"\n\t\"github.com\/Shopify\/themekit\/src\/shopify\"\n)\n\nconst settingsDataKey = \"config\/settings_data.json\"\n\nvar (\n\tdeployCmd = &cobra.Command{\n\t\tUse:   \"deploy <filenames>\",\n\t\tShort: \"deploy files to shopify\",\n\t\tLong: `Deploy will overwrite specific files if provided with file names.\n If deploy is not provided with file names then it will deploy all\n the files on shopify with your local files. Any files that do not\n exist on your local machine will be removed from shopify unless the --soft\n flag is passed\n\n For more documentation please see http:\/\/shopify.github.io\/themekit\/commands\/#deploy\n `,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn cmdutil.ForEachClient(flags, args, deploy)\n\t\t},\n\t}\n\n\treplaceCmd = &cobra.Command{\n\t\tUse:   \"replace <filenames>\",\n\t\tShort: \"Overwrite theme file(s)\",\n\t\tLong: `Replace will overwrite specific files if provided with file names.\n If replace is not provided with file names then it will replace all\n the files on shopify with your local files. Any files that do not\n exist on your local machine will be removed from shopify.\n\n  Deprecation Notice: This command is deprecated in v0.8.0 and will be removed in\n\tv0.8.1. Please use the 'deploy' command instead.\n\n For more documentation please see http:\/\/shopify.github.io\/themekit\/commands\/#replace\n `,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcolors.ColorStdOut.Printf(\"[%s] replace has been deprecated please use `deploy` instead\", colors.Yellow(\"WARN\"))\n\t\t\treturn cmdutil.ForEachClient(flags, args, deploy)\n\t\t},\n\t}\n\n\tuploadCmd = &cobra.Command{\n\t\tUse:   \"upload <filenames>\",\n\t\tShort: \"Upload theme file(s) to shopify\",\n\t\tLong: `Upload will upload specific files to shopify servers if provided file names.\n If no filenames are provided then upload will upload every file in the project\n to shopify.\n\n  Deprecation Notice: This command is deprecated in v0.8.0 and will be removed in\n\tv0.8.1. Please use the 'deploy' command instead.\n\n For more documentation please see http:\/\/shopify.github.io\/themekit\/commands\/#upload\n `,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tcolors.ColorStdOut.Printf(\"[%s] upload has been deprecated please use `deploy` with the --nodelete flag instead\", colors.Yellow(\"WARN\"))\n\t\t\tflags.NoDelete = true\n\t\t\treturn cmdutil.ForEachClient(flags, args, deploy)\n\t\t},\n\t}\n)\n\nfunc deploy(ctx cmdutil.Ctx) error {\n\tif ctx.Env.ReadOnly {\n\t\treturn fmt.Errorf(\"[%s] environment is readonly\", colors.Green(ctx.Env.Name))\n\t}\n\n\tassetsActions, err := generateActions(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar deployGroup sync.WaitGroup\n\tctx.StartProgress(len(assetsActions))\n\tfor path, op := range assetsActions {\n\t\tif path == settingsDataKey {\n\t\t\tdefer perform(ctx, path, op)\n\t\t\tcontinue\n\t\t}\n\t\tdeployGroup.Add(1)\n\t\tgo func(path string, op file.Op) {\n\t\t\tdefer deployGroup.Done()\n\t\t\tperform(ctx, path, op)\n\t\t}(path, op)\n\t}\n\n\tdeployGroup.Wait()\n\treturn nil\n}\n\nfunc generateActions(ctx cmdutil.Ctx) (map[string]file.Op, error) {\n\tassetsActions := map[string]file.Op{}\n\n\tif len(ctx.Args) == 0 && !ctx.Flags.NoDelete {\n\t\tremoteFiles, err := ctx.Client.GetAllAssets()\n\t\tif err != nil {\n\t\t\treturn assetsActions, err\n\t\t}\n\t\tfor _, filename := range remoteFiles {\n\t\t\tassetsActions[filepath.ToSlash(filename)] = file.Remove\n\t\t}\n\t}\n\n\tlocalAssets, err := shopify.FindAssets(ctx.Env, ctx.Args...)\n\tif err != nil {\n\t\treturn assetsActions, err\n\t}\n\n\tfor _, path := range localAssets {\n\t\tassetsActions[path] = file.Update\n\t}\n\treturn assetsActions, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package tls\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/bosssauce\/ponzu\/system\/db\"\n\n\t\"golang.org\/x\/crypto\/acme\/autocert\"\n)\n\nvar m autocert.Manager\n\n\/\/ setup attempts to locate or create the cert cache directory and the certs for TLS encryption\nfunc setup() {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalln(\"Couldn't find working directory to locate or save certificates.\")\n\t}\n\n\tcache := autocert.DirCache(filepath.Join(pwd, \"system\", \"tls\", \"certs\"))\n\tif _, err := os.Stat(string(cache)); os.IsNotExist(err) {\n\t\terr := os.MkdirAll(string(cache), os.ModePerm|os.ModeDir)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Couldn't create cert directory at\", cache)\n\t\t}\n\t}\n\n\t\/\/ get host\/domain and email from Config to use for TLS request to Let's encryption.\n\t\/\/ we will fail fatally if either are not found since Let's Encrypt will rate-limit\n\t\/\/ and sending incomplete requests is wasteful and guarenteed to fail its check\n\thost, err := db.Config(\"domain\")\n\tif err != nil {\n\t\tlog.Fatalln(\"Error identifying host\/domain during TLS set-up.\", err)\n\t}\n\n\tif host == nil {\n\t\tlog.Fatalln(\"No 'domain' field set in Configuration. Please add a domain before attempting to make certificates.\")\n\t}\n\tfmt.Println(\"Using\", host, \"as host\/domain for certificate...\")\n\tfmt.Println(\"NOTE: if the host\/domain is not configured properly or is unreachable, HTTPS set-up will fail.\")\n\n\temail, err := db.Config(\"admin_email\")\n\tif err != nil {\n\t\tlog.Fatalln(\"Error identifying admin email during TLS set-up.\", err)\n\t}\n\n\tif email == nil {\n\t\tlog.Fatalln(\"No 'admin_email' field set in Configuration. Please add an admin email before attempting to make certificates.\")\n\t}\n\tfmt.Println(\"Using\", email, \"as contact email for certificate...\")\n\n\tm = autocert.Manager{\n\t\tPrompt:      autocert.AcceptTOS,\n\t\tCache:       cache,\n\t\tHostPolicy:  autocert.HostWhitelist(string(host)),\n\t\tRenewBefore: time.Hour * 24 * 30,\n\t\tEmail:       string(email),\n\t}\n\n}\n\n\/\/ Enable runs the setup for creating or locating certificates and starts the TLS server\nfunc Enable() {\n\tsetup()\n\n\tserver := &http.Server{\n\t\tAddr:      \":443\",\n\t\tTLSConfig: &tls.Config{GetCertificate: m.GetCertificate},\n\t}\n\n\tgo log.Fatalln(server.ListenAndServeTLS(\"\", \"\"))\n\tfmt.Println(\"Server listening for HTTPS requests...\")\n}\n<commit_msg>casting var to strings for printing in shell<commit_after>package tls\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/bosssauce\/ponzu\/system\/db\"\n\n\t\"golang.org\/x\/crypto\/acme\/autocert\"\n)\n\nvar m autocert.Manager\n\n\/\/ setup attempts to locate or create the cert cache directory and the certs for TLS encryption\nfunc setup() {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalln(\"Couldn't find working directory to locate or save certificates.\")\n\t}\n\n\tcache := autocert.DirCache(filepath.Join(pwd, \"system\", \"tls\", \"certs\"))\n\tif _, err := os.Stat(string(cache)); os.IsNotExist(err) {\n\t\terr := os.MkdirAll(string(cache), os.ModePerm|os.ModeDir)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Couldn't create cert directory at\", cache)\n\t\t}\n\t}\n\n\t\/\/ get host\/domain and email from Config to use for TLS request to Let's encryption.\n\t\/\/ we will fail fatally if either are not found since Let's Encrypt will rate-limit\n\t\/\/ and sending incomplete requests is wasteful and guarenteed to fail its check\n\thost, err := db.Config(\"domain\")\n\tif err != nil {\n\t\tlog.Fatalln(\"Error identifying host\/domain during TLS set-up.\", err)\n\t}\n\n\tif host == nil {\n\t\tlog.Fatalln(\"No 'domain' field set in Configuration. Please add a domain before attempting to make certificates.\")\n\t}\n\tfmt.Println(\"Using\", string(host), \"as host\/domain for certificate...\")\n\tfmt.Println(\"NOTE: if the host\/domain is not configured properly or is unreachable, HTTPS set-up will fail.\")\n\n\temail, err := db.Config(\"admin_email\")\n\tif err != nil {\n\t\tlog.Fatalln(\"Error identifying admin email during TLS set-up.\", err)\n\t}\n\n\tif email == nil {\n\t\tlog.Fatalln(\"No 'admin_email' field set in Configuration. Please add an admin email before attempting to make certificates.\")\n\t}\n\tfmt.Println(\"Using\", string(email), \"as contact email for certificate...\")\n\n\tm = autocert.Manager{\n\t\tPrompt:      autocert.AcceptTOS,\n\t\tCache:       cache,\n\t\tHostPolicy:  autocert.HostWhitelist(string(host)),\n\t\tRenewBefore: time.Hour * 24 * 30,\n\t\tEmail:       string(email),\n\t}\n\n}\n\n\/\/ Enable runs the setup for creating or locating certificates and starts the TLS server\nfunc Enable() {\n\tsetup()\n\n\tserver := &http.Server{\n\t\tAddr:      \":443\",\n\t\tTLSConfig: &tls.Config{GetCertificate: m.GetCertificate},\n\t}\n\n\tgo log.Fatalln(server.ListenAndServeTLS(\"\", \"\"))\n\tfmt.Println(\"Server listening for HTTPS requests...\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cryptolib\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/crypto\/openpgp\"\n\t\"golang.org\/x\/crypto\/openpgp\/armor\"\n)\n\ntype pgpVerifierImpl struct{}\n\n\/\/ verifyPgp verifies a PGP signature using a public key and outputs the\n\/\/ payload that was signed. `signature` is an ASCII-armored \"attached\"\n\/\/ signature, generated by `gpg --armor --sign --output signature payload`.\n\/\/ `publicKey` is an ASCII-armored PGP key.\nfunc (v pgpVerifierImpl) verifyPgp(signature, publicKey []byte) ([]byte, error) {\n\tkeyring, err := openpgp.ReadArmoredKeyRing(bytes.NewReader(publicKey))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error reading armored key ring\")\n\t}\n\n\tarmorBlock, err := armor.Decode(bytes.NewReader(signature))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error decoding armored signature\")\n\t}\n\n\tmessageDetails, err := openpgp.ReadMessage(armorBlock.Body, keyring, nil, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error reading armor signature\")\n\t}\n\n\t\/\/ MessageDetails.UnverifiedBody signature is not verified until we read it.\n\t\/\/ This will call PublicKey.VerifySignature for the keys in the keyring.\n\tpayload, err := ioutil.ReadAll(messageDetails.UnverifiedBody)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error reading message contents\")\n\t}\n\n\t\/\/ Make sure after reading the UnverifiedBody above that the Signature\n\t\/\/ exists and there is no SignatureError.\n\tif messageDetails.SignatureError != nil {\n\t\treturn nil, errors.Wrap(messageDetails.SignatureError, \"failed to validate: signature error\")\n\t}\n\tif messageDetails.Signature == nil {\n\t\treturn nil, fmt.Errorf(\"failed to validate: signature missing\")\n\t}\n\treturn payload, nil\n}\n\ntype pgpSigner struct {\n\tprivateEntity *openpgp.Entity\n\tpublicKeyID   string\n}\n\n\/\/ NewPgpSigner creates a Signer interface for PGP Attestations. `privateKey`\n\/\/ contains the ASCII-armored private key.\nfunc NewPgpSigner(privateKey []byte) (Signer, error) {\n\tkeyring, err := openpgp.ReadArmoredKeyRing(bytes.NewReader(privateKey))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error reading armored private key\")\n\t}\n\tif len(keyring) != 1 {\n\t\treturn nil, fmt.Errorf(\"expected 1 key in keyring, got %d\", len(keyring))\n\t}\n\tprivateEntity := keyring[0]\n\treturn &pgpSigner{\n\t\tprivateEntity: privateEntity,\n\t\tpublicKeyID:   fmt.Sprintf(\"%X\", privateEntity.PrimaryKey.Fingerprint),\n\t}, nil\n}\n\n\/\/ CreateAttestation creates a signed PGP Attestation. The Attestation's\n\/\/ publicKeyID will be derived from the private key. See Signer for more\n\/\/ details.\nfunc (s *pgpSigner) CreateAttestation(payload []byte) (*Attestation, error) {\n\t\/\/ Create a buffer to store the signature\n\tsignature := bytes.Buffer{}\n\n\t\/\/ Armor-encode the signature before writing to the buffer\n\tarmorBuffer, err := armor.Encode(&signature, openpgp.SignatureType, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error creating armor buffer\")\n\t}\n\n\tarmorWriter, err := openpgp.Sign(armorBuffer, s.privateEntity, nil, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error signing payload\")\n\t}\n\n\t_, err = armorWriter.Write(payload)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error writing payload to armor writer\")\n\t}\n\n\t\/\/ The payload is not signed until the armor writer is closed. This will\n\t\/\/ call Signature.Sign to sign the payload.\n\tarmorWriter.Close()\n\t\/\/ The CRC checksum is not written until the armor buffer is closed.\n\tarmorBuffer.Close()\n\treturn &Attestation{\n\t\tPublicKeyID: s.publicKeyID,\n\t\tSignature:   signature.Bytes(),\n\t}, nil\n}\n<commit_msg>Address round 2 comments<commit_after>\/*\nCopyright 2020 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cryptolib\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/crypto\/openpgp\"\n\t\"golang.org\/x\/crypto\/openpgp\/armor\"\n)\n\ntype pgpVerifierImpl struct{}\n\n\/\/ verifyPgp verifies a PGP signature using a public key and outputs the\n\/\/ payload that was signed. `signature` is an ASCII-armored \"attached\"\n\/\/ signature, generated by `gpg --armor --sign --output signature payload`.\n\/\/ `publicKey` is an ASCII-armored PGP key.\nfunc (v pgpVerifierImpl) verifyPgp(signature, publicKey []byte) ([]byte, error) {\n\tkeyring, err := openpgp.ReadArmoredKeyRing(bytes.NewReader(publicKey))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error reading armored key ring\")\n\t}\n\n\tarmorBlock, err := armor.Decode(bytes.NewReader(signature))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error decoding armored signature\")\n\t}\n\n\tmessageDetails, err := openpgp.ReadMessage(armorBlock.Body, keyring, nil, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error reading armor signature\")\n\t}\n\n\t\/\/ MessageDetails.UnverifiedBody signature is not verified until we read it.\n\t\/\/ This will call PublicKey.VerifySignature for the keys in the keyring.\n\tpayload, err := ioutil.ReadAll(messageDetails.UnverifiedBody)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error reading message contents\")\n\t}\n\n\t\/\/ Make sure after reading the UnverifiedBody above that the Signature\n\t\/\/ exists and there is no SignatureError.\n\tif messageDetails.SignatureError != nil {\n\t\treturn nil, errors.Wrap(messageDetails.SignatureError, \"failed to validate: signature error\")\n\t}\n\tif messageDetails.Signature == nil {\n\t\treturn nil, fmt.Errorf(\"failed to validate: signature missing\")\n\t}\n\treturn payload, nil\n}\n\ntype pgpSigner struct {\n\tprivateKey  *openpgp.Entity\n\tpublicKeyID string\n}\n\n\/\/ NewPgpSigner creates a Signer interface for PGP Attestations. `privateKey`\n\/\/ contains the ASCII-armored private key.\nfunc NewPgpSigner(privateKey []byte) (Signer, error) {\n\tkeyring, err := openpgp.ReadArmoredKeyRing(bytes.NewReader(privateKey))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error reading armored private key\")\n\t}\n\tif len(keyring) != 1 {\n\t\treturn nil, fmt.Errorf(\"expected 1 key in keyring, got %d\", len(keyring))\n\t}\n\tkey := keyring[0]\n\treturn &pgpSigner{\n\t\tprivateKey:  key,\n\t\tpublicKeyID: fmt.Sprintf(\"%X\", key.PrimaryKey.Fingerprint),\n\t}, nil\n}\n\n\/\/ CreateAttestation creates a signed PGP Attestation. The Attestation's\n\/\/ publicKeyID will be derived from the private key. See Signer for more\n\/\/ details.\nfunc (s *pgpSigner) CreateAttestation(payload []byte) (*Attestation, error) {\n\t\/\/ Create a buffer to store the signature\n\tarmoredSignature := bytes.Buffer{}\n\n\t\/\/ Armor-encode the signature before writing to the buffer\n\tarmorWriter, err := armor.Encode(&armoredSignature, openpgp.SignatureType, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error creating armor buffer\")\n\t}\n\n\tsignatureWriter, err := openpgp.Sign(armorWriter, s.privateKey, nil, nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error signing payload\")\n\t}\n\n\t_, err = signatureWriter.Write(payload)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error writing payload to armor writer\")\n\t}\n\n\t\/\/ The payload is not signed until the armor writer is closed. This will\n\t\/\/ call Signature.Sign to sign the payload.\n\tsignatureWriter.Close()\n\t\/\/ The CRC checksum is not written until the armor buffer is closed.\n\tarmorWriter.Close()\n\treturn &Attestation{\n\t\tPublicKeyID: s.publicKeyID,\n\t\tSignature:   armoredSignature.Bytes(),\n\t}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n\t\"strconv\"\n\n\t\"github.com\/ptt\/pttweb\/article\"\n\t\"github.com\/ptt\/pttweb\/atomfeed\"\n\t\"github.com\/ptt\/pttweb\/cache\"\n\t\"github.com\/ptt\/pttweb\/pttbbs\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\nconst (\n\tEntryPerPage = 20\n\n\tCtxKeyBoardname = `ContextBoardname`\n)\n\ntype BbsIndexRequest struct {\n\tBrd  pttbbs.Board\n\tPage int\n}\n\nfunc (r *BbsIndexRequest) String() string {\n\treturn fmt.Sprintf(\"pttweb:bbsindex\/%v\/%v\", r.Brd.BrdName, r.Page)\n}\n\nfunc generateBbsIndex(key cache.Key) (cache.Cacheable, error) {\n\tr := key.(*BbsIndexRequest)\n\tpage := r.Page\n\n\tbbsindex := &BbsIndex{\n\t\tBoard:   r.Brd,\n\t\tIsValid: true,\n\t}\n\n\t\/\/ Handle paging\n\tpaging := NewPaging(EntryPerPage, r.Brd.NumPosts)\n\tif page == 0 {\n\t\tpage = paging.LastPageNo()\n\t\tpaging.SetPageNo(page)\n\t} else if err := paging.SetPageNo(page); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Fetch article list\n\tvar err error\n\tbbsindex.Articles, err = ptt.GetArticleList(r.Brd.Ref(), paging.Cursor(), EntryPerPage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Fetch bottoms when at last page\n\tif page == paging.LastPageNo() {\n\t\tbbsindex.Bottoms, err = ptt.GetBottomList(r.Brd.Ref())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Page links\n\tif u, err := router.Get(\"bbsindex\").URLPath(\"brdname\", r.Brd.BrdName); err == nil {\n\t\tbbsindex.LastPage = u.String()\n\t}\n\tpageLink := func(n int) string {\n\t\tu, err := router.Get(\"bbsindex_page\").URLPath(\"brdname\", r.Brd.BrdName, \"page\", strconv.Itoa(n))\n\t\tif err != nil {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn u.String()\n\t}\n\tbbsindex.FirstPage = pageLink(1)\n\tif page > 1 {\n\t\tbbsindex.PrevPage = pageLink(page - 1)\n\t}\n\tif page < paging.LastPageNo() {\n\t\tbbsindex.NextPage = pageLink(page + 1)\n\t}\n\n\treturn bbsindex, nil\n}\n\ntype BbsSearchRequest struct {\n\tBrd   pttbbs.Board\n\tPage  int\n\tQuery string\n\tPreds []pttbbs.SearchPredicate\n}\n\nfunc (r *BbsSearchRequest) String() string {\n\treturn fmt.Sprintf(\"pttweb:bbssearch\/%v\/%v\/%v\", r.Brd.BrdName, r.Page, r.Query)\n}\n\nfunc generateBbsSearch(key cache.Key) (cache.Cacheable, error) {\n\tr := key.(*BbsSearchRequest)\n\tpage := r.Page\n\tif page == 0 {\n\t\tpage = 1\n\t}\n\toffset := -EntryPerPage * page\n\n\tbbsindex := &BbsIndex{\n\t\tBoard:   r.Brd,\n\t\tQuery:   r.Query,\n\t\tIsValid: true,\n\t}\n\n\t\/\/ Search articles\n\tarticles, totalPosts, err := pttSearch.Search(r.Brd.Ref(), r.Preds, offset, EntryPerPage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Handle paging\n\tpaging := NewPaging(EntryPerPage, totalPosts)\n\tif lastPage := paging.LastPageNo(); page > lastPage {\n\t\tarticles = nil\n\t\tbbsindex.IsValid = false\n\t} else if page == lastPage {\n\t\t\/\/ We may get extra entries for last page.\n\t\tn := totalPosts % EntryPerPage\n\t\tif n < len(articles) {\n\t\t\tarticles = articles[:n]\n\t\t}\n\t}\n\n\t\/\/ Show the page in reverse order.\n\tfor i, j := 0, len(articles)-1; i < j; i, j = i+1, j-1 {\n\t\tarticles[i], articles[j] = articles[j], articles[i]\n\t}\n\tbbsindex.Articles = articles\n\n\t\/\/ Page links, in newest first order.\n\tpageLink := func(n int) string {\n\t\tu, err := router.Get(\"bbssearch\").URLPath(\"brdname\", r.Brd.BrdName)\n\t\tif err != nil {\n\t\t\treturn \"\"\n\t\t}\n\t\tq := url.Values{}\n\t\tq.Set(\"q\", r.Query)\n\t\tq.Set(\"page\", strconv.Itoa(n))\n\t\tu.RawQuery = q.Encode()\n\t\treturn u.String()\n\t}\n\tbbsindex.FirstPage = pageLink(paging.LastPageNo())\n\tbbsindex.LastPage = pageLink(1)\n\tif page > 1 {\n\t\tbbsindex.NextPage = pageLink(page - 1)\n\t}\n\tif page < paging.LastPageNo() {\n\t\tbbsindex.PrevPage = pageLink(page + 1)\n\t}\n\n\treturn bbsindex, nil\n}\n\ntype BoardAtomFeedRequest struct {\n\tBrd pttbbs.Board\n}\n\nfunc (r *BoardAtomFeedRequest) String() string {\n\treturn fmt.Sprintf(\"pttweb:atomfeed\/%v\", r.Brd.BrdName)\n}\n\nfunc generateBoardAtomFeed(key cache.Key) (cache.Cacheable, error) {\n\tr := key.(*BoardAtomFeedRequest)\n\n\tif atomConverter == nil {\n\t\treturn nil, errors.New(\"atom feed not configured\")\n\t}\n\n\t\/\/ Fetch article list\n\tarticles, err := ptt.GetArticleList(r.Brd.Ref(), -EntryPerPage, EntryPerPage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Fetch snippets and contruct posts.\n\tvar posts []*atomfeed.PostEntry\n\tfor _, article := range articles {\n\t\t\/\/ Use an empty string when error.\n\t\tsnippet, _ := getArticleSnippet(r.Brd, article.FileName)\n\t\tposts = append(posts, &atomfeed.PostEntry{\n\t\t\tArticle: article,\n\t\t\tSnippet: snippet,\n\t\t})\n\t}\n\n\tfeed, err := atomConverter.Convert(r.Brd, posts)\n\tif err != nil {\n\t\tlog.Println(\"atomfeed: Convert:\", err)\n\t\t\/\/ Don't return error but cache that it's invalid.\n\t}\n\treturn &BoardAtomFeed{\n\t\tFeed:    feed,\n\t\tIsValid: err == nil,\n\t}, nil\n}\n\nconst SnippetHeadSize = 16 * 1024 \/\/ Enough for 8 pages of 80x24.\n\nfunc getArticleSnippet(brd pttbbs.Board, filename string) (string, error) {\n\tp, err := ptt.GetArticleSelect(brd.Ref(), pttbbs.SelectHead, filename, \"\", 0, SnippetHeadSize)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(p.Content) == 0 {\n\t\treturn \"\", pttbbs.ErrNotFound\n\t}\n\n\tra, err := article.Render(article.WithContent(p.Content))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn ra.PreviewContent(), nil\n}\n\nconst (\n\tTruncateSize    = 1048576\n\tTruncateMaxScan = 1024\n\n\tHeadSize = 100 * 1024\n\tTailSize = 50 * 1024\n)\n\ntype ArticleRequest struct {\n\tNamespace string\n\tBrd       pttbbs.Board\n\tFilename  string\n\tSelect    func(m pttbbs.SelectMethod, offset, maxlen int) (*pttbbs.ArticlePart, error)\n}\n\nfunc (r *ArticleRequest) String() string {\n\treturn fmt.Sprintf(\"pttweb:%v\/%v\/%v\", r.Namespace, r.Brd.BrdName, r.Filename)\n}\n\nfunc (r *ArticleRequest) Boardname() string {\n\treturn r.Brd.BrdName\n}\n\nfunc generateArticle(key cache.Key) (cache.Cacheable, error) {\n\tr := key.(*ArticleRequest)\n\tctx := context.WithValue(context.TODO(), CtxKeyBoardname, r)\n\n\tp, err := r.Select(pttbbs.SelectHead, 0, HeadSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ We don't want head and tail have duplicate content\n\tif p.FileSize > HeadSize && p.FileSize <= HeadSize+TailSize {\n\t\tp, err = r.Select(pttbbs.SelectPart, 0, p.FileSize)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif len(p.Content) == 0 {\n\t\treturn nil, pttbbs.ErrNotFound\n\t}\n\n\ta := new(Article)\n\n\ta.IsPartial = p.Length < p.FileSize\n\ta.IsTruncated = a.IsPartial\n\n\tif a.IsPartial {\n\t\t\/\/ Get and render tail\n\t\tptail, err := r.Select(pttbbs.SelectTail, -TailSize, TailSize)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(ptail.Content) > 0 {\n\t\t\tra, err := article.Render(\n\t\t\t\tarticle.WithContent(ptail.Content),\n\t\t\t\tarticle.WithContext(ctx),\n\t\t\t\tarticle.WithDisableArticleHeader(),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ta.ContentTailHtml = ra.HTML()\n\t\t}\n\t\ta.CacheKey = ptail.CacheKey\n\t\ta.NextOffset = ptail.FileSize - TailSize + ptail.Offset + ptail.Length\n\t} else {\n\t\ta.CacheKey = p.CacheKey\n\t\ta.NextOffset = p.Length\n\t}\n\n\tra, err := article.Render(\n\t\tarticle.WithContent(p.Content),\n\t\tarticle.WithContext(ctx),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta.ParsedTitle = ra.ParsedTitle()\n\ta.PreviewContent = ra.PreviewContent()\n\ta.ContentHtml = ra.HTML()\n\ta.IsValid = true\n\treturn a, nil\n}\n\ntype ArticlePartRequest struct {\n\tBrd      pttbbs.Board\n\tFilename string\n\tCacheKey string\n\tOffset   int\n}\n\nfunc (r *ArticlePartRequest) String() string {\n\treturn fmt.Sprintf(\"pttweb:bbs\/%v\/%v#%v,%v\", r.Brd.BrdName, r.Filename, r.CacheKey, r.Offset)\n}\n\nfunc (r *ArticlePartRequest) Boardname() string {\n\treturn r.Brd.BrdName\n}\n\nfunc generateArticlePart(key cache.Key) (cache.Cacheable, error) {\n\tr := key.(*ArticlePartRequest)\n\tctx := context.WithValue(context.TODO(), CtxKeyBoardname, r)\n\n\tp, err := ptt.GetArticleSelect(r.Brd.Ref(), pttbbs.SelectHead, r.Filename, r.CacheKey, r.Offset, -1)\n\tif err == pttbbs.ErrNotFound {\n\t\t\/\/ Returns an invalid result\n\t\treturn new(ArticlePart), nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tap := new(ArticlePart)\n\tap.IsValid = true\n\tap.CacheKey = p.CacheKey\n\tap.NextOffset = r.Offset + p.Offset + p.Length\n\n\tif len(p.Content) > 0 {\n\t\tra, err := article.Render(\n\t\t\tarticle.WithContent(p.Content),\n\t\t\tarticle.WithContext(ctx),\n\t\t\tarticle.WithDisableArticleHeader(),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tap.ContentHtml = string(ra.HTML())\n\t}\n\n\treturn ap, nil\n}\n\nfunc truncateLargeContent(content []byte, size, maxScan int) []byte {\n\tif len(content) <= size {\n\t\treturn content\n\t}\n\tfor i := size - 1; i >= size-maxScan && i >= 0; i-- {\n\t\tif content[i] == '\\n' {\n\t\t\treturn content[:i+1]\n\t\t}\n\t}\n\treturn content[:size]\n}\n<commit_msg>Change query part of memcache key to base64(sha256(query)).<commit_after>package main\n\nimport (\n\t\"crypto\/sha256\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n\t\"strconv\"\n\n\t\"github.com\/ptt\/pttweb\/article\"\n\t\"github.com\/ptt\/pttweb\/atomfeed\"\n\t\"github.com\/ptt\/pttweb\/cache\"\n\t\"github.com\/ptt\/pttweb\/pttbbs\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\nconst (\n\tEntryPerPage = 20\n\n\tCtxKeyBoardname = `ContextBoardname`\n)\n\ntype BbsIndexRequest struct {\n\tBrd  pttbbs.Board\n\tPage int\n}\n\nfunc (r *BbsIndexRequest) String() string {\n\treturn fmt.Sprintf(\"pttweb:bbsindex\/%v\/%v\", r.Brd.BrdName, r.Page)\n}\n\nfunc generateBbsIndex(key cache.Key) (cache.Cacheable, error) {\n\tr := key.(*BbsIndexRequest)\n\tpage := r.Page\n\n\tbbsindex := &BbsIndex{\n\t\tBoard:   r.Brd,\n\t\tIsValid: true,\n\t}\n\n\t\/\/ Handle paging\n\tpaging := NewPaging(EntryPerPage, r.Brd.NumPosts)\n\tif page == 0 {\n\t\tpage = paging.LastPageNo()\n\t\tpaging.SetPageNo(page)\n\t} else if err := paging.SetPageNo(page); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Fetch article list\n\tvar err error\n\tbbsindex.Articles, err = ptt.GetArticleList(r.Brd.Ref(), paging.Cursor(), EntryPerPage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Fetch bottoms when at last page\n\tif page == paging.LastPageNo() {\n\t\tbbsindex.Bottoms, err = ptt.GetBottomList(r.Brd.Ref())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Page links\n\tif u, err := router.Get(\"bbsindex\").URLPath(\"brdname\", r.Brd.BrdName); err == nil {\n\t\tbbsindex.LastPage = u.String()\n\t}\n\tpageLink := func(n int) string {\n\t\tu, err := router.Get(\"bbsindex_page\").URLPath(\"brdname\", r.Brd.BrdName, \"page\", strconv.Itoa(n))\n\t\tif err != nil {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn u.String()\n\t}\n\tbbsindex.FirstPage = pageLink(1)\n\tif page > 1 {\n\t\tbbsindex.PrevPage = pageLink(page - 1)\n\t}\n\tif page < paging.LastPageNo() {\n\t\tbbsindex.NextPage = pageLink(page + 1)\n\t}\n\n\treturn bbsindex, nil\n}\n\ntype BbsSearchRequest struct {\n\tBrd   pttbbs.Board\n\tPage  int\n\tQuery string\n\tPreds []pttbbs.SearchPredicate\n}\n\nfunc (r *BbsSearchRequest) String() string {\n\tqueryHash := sha256.Sum256([]byte(r.Query))\n\tquery := base64.URLEncoding.EncodeToString(queryHash[:])\n\treturn fmt.Sprintf(\"pttweb:bbssearch\/%v\/%v\/%v\", r.Brd.BrdName, r.Page, query)\n}\n\nfunc generateBbsSearch(key cache.Key) (cache.Cacheable, error) {\n\tr := key.(*BbsSearchRequest)\n\tpage := r.Page\n\tif page == 0 {\n\t\tpage = 1\n\t}\n\toffset := -EntryPerPage * page\n\n\tbbsindex := &BbsIndex{\n\t\tBoard:   r.Brd,\n\t\tQuery:   r.Query,\n\t\tIsValid: true,\n\t}\n\n\t\/\/ Search articles\n\tarticles, totalPosts, err := pttSearch.Search(r.Brd.Ref(), r.Preds, offset, EntryPerPage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Handle paging\n\tpaging := NewPaging(EntryPerPage, totalPosts)\n\tif lastPage := paging.LastPageNo(); page > lastPage {\n\t\tarticles = nil\n\t\tbbsindex.IsValid = false\n\t} else if page == lastPage {\n\t\t\/\/ We may get extra entries for last page.\n\t\tn := totalPosts % EntryPerPage\n\t\tif n < len(articles) {\n\t\t\tarticles = articles[:n]\n\t\t}\n\t}\n\n\t\/\/ Show the page in reverse order.\n\tfor i, j := 0, len(articles)-1; i < j; i, j = i+1, j-1 {\n\t\tarticles[i], articles[j] = articles[j], articles[i]\n\t}\n\tbbsindex.Articles = articles\n\n\t\/\/ Page links, in newest first order.\n\tpageLink := func(n int) string {\n\t\tu, err := router.Get(\"bbssearch\").URLPath(\"brdname\", r.Brd.BrdName)\n\t\tif err != nil {\n\t\t\treturn \"\"\n\t\t}\n\t\tq := url.Values{}\n\t\tq.Set(\"q\", r.Query)\n\t\tq.Set(\"page\", strconv.Itoa(n))\n\t\tu.RawQuery = q.Encode()\n\t\treturn u.String()\n\t}\n\tbbsindex.FirstPage = pageLink(paging.LastPageNo())\n\tbbsindex.LastPage = pageLink(1)\n\tif page > 1 {\n\t\tbbsindex.NextPage = pageLink(page - 1)\n\t}\n\tif page < paging.LastPageNo() {\n\t\tbbsindex.PrevPage = pageLink(page + 1)\n\t}\n\n\treturn bbsindex, nil\n}\n\ntype BoardAtomFeedRequest struct {\n\tBrd pttbbs.Board\n}\n\nfunc (r *BoardAtomFeedRequest) String() string {\n\treturn fmt.Sprintf(\"pttweb:atomfeed\/%v\", r.Brd.BrdName)\n}\n\nfunc generateBoardAtomFeed(key cache.Key) (cache.Cacheable, error) {\n\tr := key.(*BoardAtomFeedRequest)\n\n\tif atomConverter == nil {\n\t\treturn nil, errors.New(\"atom feed not configured\")\n\t}\n\n\t\/\/ Fetch article list\n\tarticles, err := ptt.GetArticleList(r.Brd.Ref(), -EntryPerPage, EntryPerPage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Fetch snippets and contruct posts.\n\tvar posts []*atomfeed.PostEntry\n\tfor _, article := range articles {\n\t\t\/\/ Use an empty string when error.\n\t\tsnippet, _ := getArticleSnippet(r.Brd, article.FileName)\n\t\tposts = append(posts, &atomfeed.PostEntry{\n\t\t\tArticle: article,\n\t\t\tSnippet: snippet,\n\t\t})\n\t}\n\n\tfeed, err := atomConverter.Convert(r.Brd, posts)\n\tif err != nil {\n\t\tlog.Println(\"atomfeed: Convert:\", err)\n\t\t\/\/ Don't return error but cache that it's invalid.\n\t}\n\treturn &BoardAtomFeed{\n\t\tFeed:    feed,\n\t\tIsValid: err == nil,\n\t}, nil\n}\n\nconst SnippetHeadSize = 16 * 1024 \/\/ Enough for 8 pages of 80x24.\n\nfunc getArticleSnippet(brd pttbbs.Board, filename string) (string, error) {\n\tp, err := ptt.GetArticleSelect(brd.Ref(), pttbbs.SelectHead, filename, \"\", 0, SnippetHeadSize)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(p.Content) == 0 {\n\t\treturn \"\", pttbbs.ErrNotFound\n\t}\n\n\tra, err := article.Render(article.WithContent(p.Content))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn ra.PreviewContent(), nil\n}\n\nconst (\n\tTruncateSize    = 1048576\n\tTruncateMaxScan = 1024\n\n\tHeadSize = 100 * 1024\n\tTailSize = 50 * 1024\n)\n\ntype ArticleRequest struct {\n\tNamespace string\n\tBrd       pttbbs.Board\n\tFilename  string\n\tSelect    func(m pttbbs.SelectMethod, offset, maxlen int) (*pttbbs.ArticlePart, error)\n}\n\nfunc (r *ArticleRequest) String() string {\n\treturn fmt.Sprintf(\"pttweb:%v\/%v\/%v\", r.Namespace, r.Brd.BrdName, r.Filename)\n}\n\nfunc (r *ArticleRequest) Boardname() string {\n\treturn r.Brd.BrdName\n}\n\nfunc generateArticle(key cache.Key) (cache.Cacheable, error) {\n\tr := key.(*ArticleRequest)\n\tctx := context.WithValue(context.TODO(), CtxKeyBoardname, r)\n\n\tp, err := r.Select(pttbbs.SelectHead, 0, HeadSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ We don't want head and tail have duplicate content\n\tif p.FileSize > HeadSize && p.FileSize <= HeadSize+TailSize {\n\t\tp, err = r.Select(pttbbs.SelectPart, 0, p.FileSize)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif len(p.Content) == 0 {\n\t\treturn nil, pttbbs.ErrNotFound\n\t}\n\n\ta := new(Article)\n\n\ta.IsPartial = p.Length < p.FileSize\n\ta.IsTruncated = a.IsPartial\n\n\tif a.IsPartial {\n\t\t\/\/ Get and render tail\n\t\tptail, err := r.Select(pttbbs.SelectTail, -TailSize, TailSize)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(ptail.Content) > 0 {\n\t\t\tra, err := article.Render(\n\t\t\t\tarticle.WithContent(ptail.Content),\n\t\t\t\tarticle.WithContext(ctx),\n\t\t\t\tarticle.WithDisableArticleHeader(),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ta.ContentTailHtml = ra.HTML()\n\t\t}\n\t\ta.CacheKey = ptail.CacheKey\n\t\ta.NextOffset = ptail.FileSize - TailSize + ptail.Offset + ptail.Length\n\t} else {\n\t\ta.CacheKey = p.CacheKey\n\t\ta.NextOffset = p.Length\n\t}\n\n\tra, err := article.Render(\n\t\tarticle.WithContent(p.Content),\n\t\tarticle.WithContext(ctx),\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ta.ParsedTitle = ra.ParsedTitle()\n\ta.PreviewContent = ra.PreviewContent()\n\ta.ContentHtml = ra.HTML()\n\ta.IsValid = true\n\treturn a, nil\n}\n\ntype ArticlePartRequest struct {\n\tBrd      pttbbs.Board\n\tFilename string\n\tCacheKey string\n\tOffset   int\n}\n\nfunc (r *ArticlePartRequest) String() string {\n\treturn fmt.Sprintf(\"pttweb:bbs\/%v\/%v#%v,%v\", r.Brd.BrdName, r.Filename, r.CacheKey, r.Offset)\n}\n\nfunc (r *ArticlePartRequest) Boardname() string {\n\treturn r.Brd.BrdName\n}\n\nfunc generateArticlePart(key cache.Key) (cache.Cacheable, error) {\n\tr := key.(*ArticlePartRequest)\n\tctx := context.WithValue(context.TODO(), CtxKeyBoardname, r)\n\n\tp, err := ptt.GetArticleSelect(r.Brd.Ref(), pttbbs.SelectHead, r.Filename, r.CacheKey, r.Offset, -1)\n\tif err == pttbbs.ErrNotFound {\n\t\t\/\/ Returns an invalid result\n\t\treturn new(ArticlePart), nil\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tap := new(ArticlePart)\n\tap.IsValid = true\n\tap.CacheKey = p.CacheKey\n\tap.NextOffset = r.Offset + p.Offset + p.Length\n\n\tif len(p.Content) > 0 {\n\t\tra, err := article.Render(\n\t\t\tarticle.WithContent(p.Content),\n\t\t\tarticle.WithContext(ctx),\n\t\t\tarticle.WithDisableArticleHeader(),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tap.ContentHtml = string(ra.HTML())\n\t}\n\n\treturn ap, nil\n}\n\nfunc truncateLargeContent(content []byte, size, maxScan int) []byte {\n\tif len(content) <= size {\n\t\treturn content\n\t}\n\tfor i := size - 1; i >= size-maxScan && i >= 0; i-- {\n\t\tif content[i] == '\\n' {\n\t\t\treturn content[:i+1]\n\t\t}\n\t}\n\treturn content[:size]\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"flag\"\n\n\t\"github.com\/cloudflare\/cfssl\/config\"\n\t\"github.com\/cloudflare\/cfssl\/helpers\"\n\t\"github.com\/cloudflare\/cfssl\/signer\/pkcs11\"\n\t\"github.com\/cloudflare\/cfssl\/signer\/universal\"\n)\n\n\/\/ Config is a type to hold flag values used by cfssl commands.\ntype Config struct {\n\tHostname          string\n\tCertFile          string\n\tCSRFile           string\n\tCAFile            string\n\tCAKeyFile         string\n\tKeyFile           string\n\tIntermediatesFile string\n\tCABundleFile      string\n\tIntBundleFile     string\n\tAddress           string\n\tPort              int\n\tPassword          string\n\tConfigFile        string\n\tCFG               *config.Config\n\tProfile           string\n\tIsCA              bool\n\tIntDir            string\n\tFlavor            string\n\tMetadata          string\n\tDomain            string\n\tIP                string\n\tRemote            string\n\tLabel             string\n\tAuthKey           string\n\tModule            string\n\tToken             string\n\tPIN               string\n\tPKCS11Label       string\n\tResponderFile     string\n\tStatus            string\n\tReason            int\n\tRevokedAt         string\n\tInterval          int64\n\tList              bool\n\tFamily            string\n\tScanner           string\n\tResponses         string\n\tPath              string\n\tUseLocal          bool\n}\n\n\/\/ registerFlags defines all cfssl command flags and associates their values with variables.\nfunc registerFlags(c *Config, f *flag.FlagSet) {\n\tf.StringVar(&c.Hostname, \"hostname\", \"\", \"Hostname for the cert, could be a comma-separated hostname list\")\n\tf.StringVar(&c.CertFile, \"cert\", \"\", \"Client certificate that contains the public key\")\n\tf.StringVar(&c.CSRFile, \"csr\", \"\", \"Certificate signature request file for new public key\")\n\tf.StringVar(&c.CAFile, \"ca\", \"ca.pem\", \"CA used to sign the new certificate\")\n\tf.StringVar(&c.CAKeyFile, \"ca-key\", \"ca-key.pem\", \"CA private key\")\n\tf.StringVar(&c.KeyFile, \"key\", \"\", \"private key for the certificate\")\n\tf.StringVar(&c.IntermediatesFile, \"intermediates\", \"\", \"intermediate certs\")\n\tf.StringVar(&c.CABundleFile, \"ca-bundle\", \"\/etc\/cfssl\/ca-bundle.crt\", \"Bundle to be used for root certificates pool\")\n\tf.StringVar(&c.IntBundleFile, \"int-bundle\", \"\/etc\/cfssl\/int-bundle.crt\", \"Bundle to be used for intermediate certificates pool\")\n\tf.StringVar(&c.Address, \"address\", \"127.0.0.1\", \"Address to bind\")\n\tf.IntVar(&c.Port, \"port\", 8888, \"Port to bind\")\n\tf.StringVar(&c.ConfigFile, \"config\", \"\", \"path to configuration file\")\n\tf.StringVar(&c.Profile, \"profile\", \"\", \"signing profile to use\")\n\tf.BoolVar(&c.IsCA, \"initca\", false, \"initialise new CA\")\n\tf.StringVar(&c.IntDir, \"int-dir\", \"\/etc\/cfssl\/intermediates\", \"specify intermediates directory\")\n\tf.StringVar(&c.Flavor, \"flavor\", \"ubiquitous\", \"Bundle Flavor: ubiquitous, optimal and force.\")\n\tf.StringVar(&c.Metadata, \"metadata\", \"\/etc\/cfssl\/ca-bundle.crt.metadata\", \"Metadata file for root certificate presence. The content of the file is a json dictionary (k,v): each key k is SHA-1 digest of a root certificate while value v is a list of key store filenames.\")\n\tf.StringVar(&c.Domain, \"domain\", \"\", \"remote server domain name\")\n\tf.StringVar(&c.IP, \"ip\", \"\", \"remote server ip\")\n\tf.StringVar(&c.Remote, \"remote\", \"\", \"remote CFSSL server\")\n\tf.StringVar(&c.Label, \"label\", \"\", \"key label to use in remote CFSSL server\")\n\tf.StringVar(&c.AuthKey, \"authkey\", \"\", \"key to authenticate requests to remote CFSSL server\")\n\tf.StringVar(&c.ResponderFile, \"responder\", \"\", \"Certificate for OCSP responder\")\n\tf.StringVar(&c.Status, \"status\", \"good\", \"Status of the certificate: good, revoked, unknown\")\n\tf.IntVar(&c.Reason, \"reason\", 0, \"Reason code for revocation\")\n\tf.StringVar(&c.RevokedAt, \"revoked-at\", \"now\", \"Date of revocation (YYYY-MM-DD)\")\n\tf.Int64Var(&c.Interval, \"interval\", int64(4*helpers.OneDay), \"Interval between OCSP updates, in seconds (default: 4 days)\")\n\tf.BoolVar(&c.List, \"list\", false, \"list possible scanners\")\n\tf.StringVar(&c.Family, \"family\", \"\", \"scanner family regular expression\")\n\tf.StringVar(&c.Scanner, \"scanner\", \"\", \"scanner regular expression\")\n\tf.StringVar(&c.Responses, \"responses\", \"\", \"file to load OCSP responses from\")\n\tf.StringVar(&c.Path, \"path\", \"\/\", \"Path on which the server will listen\")\n\tf.StringVar(&c.Password, \"password\", \"\", \"Password for accessing PKCS #12 data passed to bundler\")\n\tf.BoolVar(&c.UseLocal, \"uselocal\", false, \"serve local static files as opposed to compiled ones\")\n\n\tif pkcs11.Enabled {\n\t\tf.StringVar(&c.Module, \"pkcs11-module\", \"\", \"PKCS #11 module\")\n\t\tf.StringVar(&c.Token, \"pkcs11-token\", \"\", \"PKCS #11 token\")\n\t\tf.StringVar(&c.PIN, \"pkcs11-pin\", \"\", \"PKCS #11 user PIN\")\n\t\tf.StringVar(&c.PKCS11Label, \"pkcs11-label\", \"\", \"PKCS #11 label\")\n\t}\n}\n\n\/\/ RootFromConfig returns a universal signer Root structure that can\n\/\/ be used to produce a signer.\nfunc RootFromConfig(c *Config) universal.Root {\n\treturn universal.Root{\n\t\tConfig: map[string]string{\n\t\t\t\"pkcs11-module\":   c.Module,\n\t\t\t\"pkcs11-token\":    c.Token,\n\t\t\t\"pkcs11-label\":    c.PKCS11Label,\n\t\t\t\"pkcs11-user-pin\": c.PIN,\n\t\t\t\"cert-file\":       c.CAFile,\n\t\t\t\"key-file\":        c.CAKeyFile,\n\t\t},\n\t\tForceRemote: c.Remote != \"\",\n\t}\n}\n<commit_msg>Set pkcs11 user pin in environment<commit_after>package cli\n\nimport (\n\t\"flag\"\n\t\"os\"\n\n\t\"github.com\/cloudflare\/cfssl\/config\"\n\t\"github.com\/cloudflare\/cfssl\/helpers\"\n\t\"github.com\/cloudflare\/cfssl\/signer\/pkcs11\"\n\t\"github.com\/cloudflare\/cfssl\/signer\/universal\"\n)\n\n\/\/ Config is a type to hold flag values used by cfssl commands.\ntype Config struct {\n\tHostname          string\n\tCertFile          string\n\tCSRFile           string\n\tCAFile            string\n\tCAKeyFile         string\n\tKeyFile           string\n\tIntermediatesFile string\n\tCABundleFile      string\n\tIntBundleFile     string\n\tAddress           string\n\tPort              int\n\tPassword          string\n\tConfigFile        string\n\tCFG               *config.Config\n\tProfile           string\n\tIsCA              bool\n\tIntDir            string\n\tFlavor            string\n\tMetadata          string\n\tDomain            string\n\tIP                string\n\tRemote            string\n\tLabel             string\n\tAuthKey           string\n\tModule            string\n\tToken             string\n\tPIN               string\n\tPKCS11Label       string\n\tResponderFile     string\n\tStatus            string\n\tReason            int\n\tRevokedAt         string\n\tInterval          int64\n\tList              bool\n\tFamily            string\n\tScanner           string\n\tResponses         string\n\tPath              string\n\tUseLocal          bool\n}\n\n\/\/ registerFlags defines all cfssl command flags and associates their values with variables.\nfunc registerFlags(c *Config, f *flag.FlagSet) {\n\tf.StringVar(&c.Hostname, \"hostname\", \"\", \"Hostname for the cert, could be a comma-separated hostname list\")\n\tf.StringVar(&c.CertFile, \"cert\", \"\", \"Client certificate that contains the public key\")\n\tf.StringVar(&c.CSRFile, \"csr\", \"\", \"Certificate signature request file for new public key\")\n\tf.StringVar(&c.CAFile, \"ca\", \"ca.pem\", \"CA used to sign the new certificate\")\n\tf.StringVar(&c.CAKeyFile, \"ca-key\", \"ca-key.pem\", \"CA private key\")\n\tf.StringVar(&c.KeyFile, \"key\", \"\", \"private key for the certificate\")\n\tf.StringVar(&c.IntermediatesFile, \"intermediates\", \"\", \"intermediate certs\")\n\tf.StringVar(&c.CABundleFile, \"ca-bundle\", \"\/etc\/cfssl\/ca-bundle.crt\", \"Bundle to be used for root certificates pool\")\n\tf.StringVar(&c.IntBundleFile, \"int-bundle\", \"\/etc\/cfssl\/int-bundle.crt\", \"Bundle to be used for intermediate certificates pool\")\n\tf.StringVar(&c.Address, \"address\", \"127.0.0.1\", \"Address to bind\")\n\tf.IntVar(&c.Port, \"port\", 8888, \"Port to bind\")\n\tf.StringVar(&c.ConfigFile, \"config\", \"\", \"path to configuration file\")\n\tf.StringVar(&c.Profile, \"profile\", \"\", \"signing profile to use\")\n\tf.BoolVar(&c.IsCA, \"initca\", false, \"initialise new CA\")\n\tf.StringVar(&c.IntDir, \"int-dir\", \"\/etc\/cfssl\/intermediates\", \"specify intermediates directory\")\n\tf.StringVar(&c.Flavor, \"flavor\", \"ubiquitous\", \"Bundle Flavor: ubiquitous, optimal and force.\")\n\tf.StringVar(&c.Metadata, \"metadata\", \"\/etc\/cfssl\/ca-bundle.crt.metadata\", \"Metadata file for root certificate presence. The content of the file is a json dictionary (k,v): each key k is SHA-1 digest of a root certificate while value v is a list of key store filenames.\")\n\tf.StringVar(&c.Domain, \"domain\", \"\", \"remote server domain name\")\n\tf.StringVar(&c.IP, \"ip\", \"\", \"remote server ip\")\n\tf.StringVar(&c.Remote, \"remote\", \"\", \"remote CFSSL server\")\n\tf.StringVar(&c.Label, \"label\", \"\", \"key label to use in remote CFSSL server\")\n\tf.StringVar(&c.AuthKey, \"authkey\", \"\", \"key to authenticate requests to remote CFSSL server\")\n\tf.StringVar(&c.ResponderFile, \"responder\", \"\", \"Certificate for OCSP responder\")\n\tf.StringVar(&c.Status, \"status\", \"good\", \"Status of the certificate: good, revoked, unknown\")\n\tf.IntVar(&c.Reason, \"reason\", 0, \"Reason code for revocation\")\n\tf.StringVar(&c.RevokedAt, \"revoked-at\", \"now\", \"Date of revocation (YYYY-MM-DD)\")\n\tf.Int64Var(&c.Interval, \"interval\", int64(4*helpers.OneDay), \"Interval between OCSP updates, in seconds (default: 4 days)\")\n\tf.BoolVar(&c.List, \"list\", false, \"list possible scanners\")\n\tf.StringVar(&c.Family, \"family\", \"\", \"scanner family regular expression\")\n\tf.StringVar(&c.Scanner, \"scanner\", \"\", \"scanner regular expression\")\n\tf.StringVar(&c.Responses, \"responses\", \"\", \"file to load OCSP responses from\")\n\tf.StringVar(&c.Path, \"path\", \"\/\", \"Path on which the server will listen\")\n\tf.StringVar(&c.Password, \"password\", \"\", \"Password for accessing PKCS #12 data passed to bundler\")\n\tf.BoolVar(&c.UseLocal, \"uselocal\", false, \"serve local static files as opposed to compiled ones\")\n\n\tif pkcs11.Enabled {\n\t\tf.StringVar(&c.Module, \"pkcs11-module\", \"\", \"PKCS #11 module\")\n\t\tf.StringVar(&c.Token, \"pkcs11-token\", \"\", \"PKCS #11 token\")\n\t\tf.StringVar(&c.PIN, \"pkcs11-pin\", os.Getenv(\"USER_PIN\"), \"PKCS #11 user PIN\")\n\t\tf.StringVar(&c.PKCS11Label, \"pkcs11-label\", \"\", \"PKCS #11 label\")\n\t}\n}\n\n\/\/ RootFromConfig returns a universal signer Root structure that can\n\/\/ be used to produce a signer.\nfunc RootFromConfig(c *Config) universal.Root {\n\treturn universal.Root{\n\t\tConfig: map[string]string{\n\t\t\t\"pkcs11-module\":   c.Module,\n\t\t\t\"pkcs11-token\":    c.Token,\n\t\t\t\"pkcs11-label\":    c.PKCS11Label,\n\t\t\t\"pkcs11-user-pin\": c.PIN,\n\t\t\t\"cert-file\":       c.CAFile,\n\t\t\t\"key-file\":        c.CAKeyFile,\n\t\t},\n\t\tForceRemote: c.Remote != \"\",\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2015 Scaleway. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE.md file.\n\npackage cli\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\n\t\"github.com\/scaleway\/scaleway-cli\/pkg\/api\"\n\t\"github.com\/scaleway\/scaleway-cli\/pkg\/scwversion\"\n)\n\nvar cmdUserdata = &Command{\n\tExec:        runUserdata,\n\tUsageLine:   \"_userdata [OPTIONS] SERVER [FIELD[=VALUE]]\",\n\tDescription: \"\",\n\tHidden:      true,\n\tHelp:        \"List, read and write and delete server's userdata\",\n\tExamples: `\n    $ scw _userdata myserver\n    $ scw _userdata myserver key\n    $ scw _userdata myserver key=value\n    $ scw _userdata myserver key=\"\"\n`,\n}\n\nfunc init() {\n\tcmdUserdata.Flag.BoolVar(&userdataHelp, []string{\"h\", \"-help\"}, false, \"Print usage\")\n}\n\n\/\/ Flags\nvar userdataHelp bool \/\/ -h, --help flag\n\nfunc runUserdata(cmd *Command, args []string) error {\n\tif userdataHelp {\n\t\treturn cmd.PrintUsage()\n\t}\n\tif len(args) < 1 {\n\t\treturn cmd.PrintShortUsage()\n\t}\n\tmetadata := false\n\tctx := cmd.GetContext(args)\n\tvar API *api.ScalewayAPI\n\tvar err error\n\tvar serverID string\n\tif args[0] == \"local\" {\n\t\tAPI, err = api.NewScalewayAPI(\"\", \"\", scwversion.UserAgent())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmetadata = true\n\t} else {\n\t\tif ctx.API == nil {\n\t\t\treturn fmt.Errorf(\"You need to login first: 'scw login'\")\n\t\t}\n\t\tserverID, err = ctx.API.GetServerID(args[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tAPI = ctx.API\n\t}\n\n\tswitch len(args) {\n\tcase 1:\n\t\t\/\/ List userdata\n\t\tres, err := API.GetUserdatas(serverID, metadata)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, key := range res.UserData {\n\t\t\tfmt.Fprintln(ctx.Stdout, key)\n\t\t}\n\tdefault:\n\t\tparts := strings.Split(args[1], \"=\")\n\t\tkey := parts[0]\n\t\tswitch len(parts) {\n\t\tcase 1:\n\t\t\t\/\/ Get userdatas\n\t\t\tres, err := API.GetUserdata(serverID, key, metadata)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfmt.Fprintf(ctx.Stdout, \"%s\\n\", res.String())\n\t\tdefault:\n\t\t\tvalue := args[1][len(parts[0])+1:]\n\t\t\tif value != \"\" {\n\t\t\t\tvar data []byte\n\t\t\t\t\/\/ Set userdata\n\t\t\t\tif value[0] == '@' {\n\t\t\t\t\tdata, err = ioutil.ReadFile(value[1:])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tdata = []byte(value)\n\t\t\t\t}\n\t\t\t\terr := API.PatchUserdata(serverID, key, data, metadata)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Fprintln(ctx.Stdout, key)\n\t\t\t} else {\n\t\t\t\t\/\/ Delete userdata\n\t\t\t\terr := API.DeleteUserdata(serverID, key, metadata)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>_userdata: handles USERDATA=@~\/path\/to\/file<commit_after>\/\/ Copyright (C) 2015 Scaleway. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE.md file.\n\npackage cli\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\n\t\"github.com\/scaleway\/scaleway-cli\/pkg\/api\"\n\t\"github.com\/scaleway\/scaleway-cli\/pkg\/config\"\n\t\"github.com\/scaleway\/scaleway-cli\/pkg\/scwversion\"\n)\n\nvar cmdUserdata = &Command{\n\tExec:        runUserdata,\n\tUsageLine:   \"_userdata [OPTIONS] SERVER [FIELD[=VALUE]]\",\n\tDescription: \"\",\n\tHidden:      true,\n\tHelp:        \"List, read and write and delete server's userdata\",\n\tExamples: `\n    $ scw _userdata myserver\n    $ scw _userdata myserver key\n    $ scw _userdata myserver key=value\n    $ scw _userdata myserver key=\"\"\n`,\n}\n\nfunc init() {\n\tcmdUserdata.Flag.BoolVar(&userdataHelp, []string{\"h\", \"-help\"}, false, \"Print usage\")\n}\n\n\/\/ Flags\nvar userdataHelp bool \/\/ -h, --help flag\n\nfunc runUserdata(cmd *Command, args []string) error {\n\tif userdataHelp {\n\t\treturn cmd.PrintUsage()\n\t}\n\tif len(args) < 1 {\n\t\treturn cmd.PrintShortUsage()\n\t}\n\tmetadata := false\n\tctx := cmd.GetContext(args)\n\tvar API *api.ScalewayAPI\n\tvar err error\n\tvar serverID string\n\tif args[0] == \"local\" {\n\t\tAPI, err = api.NewScalewayAPI(\"\", \"\", scwversion.UserAgent())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmetadata = true\n\t} else {\n\t\tif ctx.API == nil {\n\t\t\treturn fmt.Errorf(\"You need to login first: 'scw login'\")\n\t\t}\n\t\tserverID, err = ctx.API.GetServerID(args[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tAPI = ctx.API\n\t}\n\n\tswitch len(args) {\n\tcase 1:\n\t\t\/\/ List userdata\n\t\tres, err := API.GetUserdatas(serverID, metadata)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, key := range res.UserData {\n\t\t\tfmt.Fprintln(ctx.Stdout, key)\n\t\t}\n\tdefault:\n\t\tparts := strings.Split(args[1], \"=\")\n\t\tkey := parts[0]\n\t\tswitch len(parts) {\n\t\tcase 1:\n\t\t\t\/\/ Get userdatas\n\t\t\tres, err := API.GetUserdata(serverID, key, metadata)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfmt.Fprintf(ctx.Stdout, \"%s\\n\", res.String())\n\t\tdefault:\n\t\t\tvalue := args[1][len(parts[0])+1:]\n\t\t\tif value != \"\" {\n\t\t\t\tvar data []byte\n\t\t\t\t\/\/ Set userdata\n\t\t\t\tif value[0] == '@' {\n\t\t\t\t\tif len(value) > 1 && value[1] == '~' {\n\t\t\t\t\t\thome, err := config.GetHomeDir()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalue = \"@\" + home + value[2:]\n\t\t\t\t\t}\n\t\t\t\t\tdata, err = ioutil.ReadFile(value[1:])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tdata = []byte(value)\n\t\t\t\t}\n\t\t\t\terr := API.PatchUserdata(serverID, key, data, metadata)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Fprintln(ctx.Stdout, key)\n\t\t\t} else {\n\t\t\t\t\/\/ Delete userdata\n\t\t\t\terr := API.DeleteUserdata(serverID, key, metadata)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package assets\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/yosssi\/gcss\"\n)\n\n\/\/ CompileJavascripts compiles a set of JS files into a single large file by\n\/\/ appending them all to each other. Files are appended in alphabetical order\n\/\/ so we depend on the fact that there aren't too many interdependencies\n\/\/ between files. A common requirement can be given an underscore prefix to be\n\/\/ loaded first.\nfunc CompileJavascripts(inPath, outPath string) error {\n\tstart := time.Now()\n\tdefer func() {\n\t\tlog.Debugf(\"Compiled script assets in %v.\", time.Now().Sub(start))\n\t}()\n\n\tlog.Debugf(\"Building: %v\", outPath)\n\n\tjavascriptInfos, err := ioutil.ReadDir(inPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toutFile, err := os.Create(outPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\tfor _, javascriptInfo := range javascriptInfos {\n\t\tif isHidden(javascriptInfo.Name()) {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Debugf(\"Including: %v\", javascriptInfo.Name())\n\n\t\tinFile, err := os.Open(path.Join(inPath, javascriptInfo.Name()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\toutFile.WriteString(\"\/* \" + javascriptInfo.Name() + \" *\/\\n\\n\")\n\t\toutFile.WriteString(\"(function() {\\n\\n\")\n\n\t\t_, err = io.Copy(outFile, inFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\toutFile.WriteString(\"\\n\\n\")\n\t\toutFile.WriteString(\"}).call(this);\\n\\n\")\n\t}\n\n\treturn nil\n}\n\n\/\/ CompileStylesheets compiles a set of stylesheet files into a single large\n\/\/ file by appending them all to each other. Files are appended in alphabetical\n\/\/ order so we depend on the fact that there aren't too many interdependencies\n\/\/ between files. CSS reset in particular is given an underscore prefix so that\n\/\/ it gets to load first.\n\/\/\n\/\/ If a file has a \".sass\" suffix, we attempt to render it as GCSS. This isn't\n\/\/ a perfect symmetry, but works well enough for these cases.\nfunc CompileStylesheets(inPath, outPath string) error {\n\tstart := time.Now()\n\tdefer func() {\n\t\tlog.Debugf(\"Compiled stylesheet assets in %v.\", time.Now().Sub(start))\n\t}()\n\n\tlog.Debugf(\"Building: %v\", outPath)\n\n\tstylesheetInfos, err := ioutil.ReadDir(inPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toutFile, err := os.Create(outPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\tfor _, stylesheetInfo := range stylesheetInfos {\n\t\tif isHidden(stylesheetInfo.Name()) {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Debugf(\"Including: %v\", stylesheetInfo.Name())\n\n\t\tinFile, err := os.Open(path.Join(inPath, stylesheetInfo.Name()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\toutFile.WriteString(\"\/* \" + stylesheetInfo.Name() + \" *\/\\n\\n\")\n\n\t\tif strings.HasSuffix(stylesheetInfo.Name(), \".sass\") {\n\t\t\t_, err := gcss.Compile(outFile, inFile)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error compiling %v: %v\",\n\t\t\t\t\tstylesheetInfo.Name(), err)\n\t\t\t}\n\t\t} else {\n\t\t\t_, err := io.Copy(outFile, inFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\toutFile.WriteString(\"\\n\\n\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Detects a hidden file, i.e. one that starts with a dot.\nfunc isHidden(file string) bool {\n\treturn strings.HasPrefix(file, \".\")\n}\n<commit_msg>Ignore non-JS files files in content\/javascripts\/<commit_after>package assets\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/yosssi\/gcss\"\n)\n\n\/\/ CompileJavascripts compiles a set of JS files into a single large file by\n\/\/ appending them all to each other. Files are appended in alphabetical order\n\/\/ so we depend on the fact that there aren't too many interdependencies\n\/\/ between files. A common requirement can be given an underscore prefix to be\n\/\/ loaded first.\nfunc CompileJavascripts(inPath, outPath string) error {\n\tstart := time.Now()\n\tdefer func() {\n\t\tlog.Debugf(\"Compiled script assets in %v.\", time.Now().Sub(start))\n\t}()\n\n\tlog.Debugf(\"Building: %v\", outPath)\n\n\tjavascriptInfos, err := ioutil.ReadDir(inPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toutFile, err := os.Create(outPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\tfor _, javascriptInfo := range javascriptInfos {\n\t\tif isHidden(javascriptInfo.Name()) {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Debugf(\"Including: %v\", javascriptInfo.Name())\n\n\t\tinFile, err := os.Open(path.Join(inPath, javascriptInfo.Name()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\toutFile.WriteString(\"\/* \" + javascriptInfo.Name() + \" *\/\\n\\n\")\n\t\toutFile.WriteString(\"(function() {\\n\\n\")\n\n\t\t\/\/ Ignore non-JS files in the directory (I have a README in there)\n\t\tif strings.HasSuffix(javascriptInfo.Name(), \".js\") {\n\t\t\t_, err = io.Copy(outFile, inFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\toutFile.WriteString(\"\\n\\n\")\n\t\toutFile.WriteString(\"}).call(this);\\n\\n\")\n\t}\n\n\treturn nil\n}\n\n\/\/ CompileStylesheets compiles a set of stylesheet files into a single large\n\/\/ file by appending them all to each other. Files are appended in alphabetical\n\/\/ order so we depend on the fact that there aren't too many interdependencies\n\/\/ between files. CSS reset in particular is given an underscore prefix so that\n\/\/ it gets to load first.\n\/\/\n\/\/ If a file has a \".sass\" suffix, we attempt to render it as GCSS. This isn't\n\/\/ a perfect symmetry, but works well enough for these cases.\nfunc CompileStylesheets(inPath, outPath string) error {\n\tstart := time.Now()\n\tdefer func() {\n\t\tlog.Debugf(\"Compiled stylesheet assets in %v.\", time.Now().Sub(start))\n\t}()\n\n\tlog.Debugf(\"Building: %v\", outPath)\n\n\tstylesheetInfos, err := ioutil.ReadDir(inPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toutFile, err := os.Create(outPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer outFile.Close()\n\n\tfor _, stylesheetInfo := range stylesheetInfos {\n\t\tif isHidden(stylesheetInfo.Name()) {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Debugf(\"Including: %v\", stylesheetInfo.Name())\n\n\t\tinFile, err := os.Open(path.Join(inPath, stylesheetInfo.Name()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\toutFile.WriteString(\"\/* \" + stylesheetInfo.Name() + \" *\/\\n\\n\")\n\n\t\tif strings.HasSuffix(stylesheetInfo.Name(), \".sass\") {\n\t\t\t_, err := gcss.Compile(outFile, inFile)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error compiling %v: %v\",\n\t\t\t\t\tstylesheetInfo.Name(), err)\n\t\t\t}\n\t\t} else {\n\t\t\t_, err := io.Copy(outFile, inFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\toutFile.WriteString(\"\\n\\n\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Detects a hidden file, i.e. one that starts with a dot.\nfunc isHidden(file string) bool {\n\treturn strings.HasPrefix(file, \".\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package commands\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/github\/hub\/ui\"\n\t\"github.com\/github\/hub\/utils\"\n)\n\nvar cmdAlias = &Command{\n\tRun:   alias,\n\tUsage: \"alias [-s] [<SHELL>]\",\n\tLong: `Show shell instructions for wrapping git.\n\n## Options\n\t-s\n\t\tOutput shell script suitable for 'eval'.\n\n\t<SHELL>\n\t\tSpecify the type of shell (default: \"$SHELL\" environment variable).\n\n## See also:\n\nhub(1)\n`,\n}\n\nvar flagAliasScript bool\n\nfunc init() {\n\tcmdAlias.Flag.BoolVarP(&flagAliasScript, \"script\", \"s\", false, \"SCRIPT\")\n\tCmdRunner.Use(cmdAlias)\n}\n\nfunc alias(command *Command, args *Args) {\n\tvar shell string\n\tif args.ParamsSize() > 0 {\n\t\tshell = args.FirstParam()\n\t} else {\n\t\tshell = os.Getenv(\"SHELL\")\n\t}\n\n\tif shell == \"\" {\n\t\tcmd := \"hub alias <shell>\"\n\t\tif flagAliasScript {\n\t\t\tcmd = \"hub alias -s <shell>\"\n\t\t}\n\t\tutils.Check(fmt.Errorf(\"Error: couldn't detect shell type. Please specify your shell with `%s`\", cmd))\n\t}\n\n\tshells := []string{\"bash\", \"zsh\", \"sh\", \"ksh\", \"csh\", \"tcsh\", \"fish\"}\n\tshell = filepath.Base(shell)\n\tvar validShell bool\n\tfor _, s := range shells {\n\t\tif s == shell {\n\t\t\tvalidShell = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !validShell {\n\t\terr := fmt.Errorf(\"hub alias: unsupported shell\\nsupported shells: %s\", strings.Join(shells, \" \"))\n\t\tutils.Check(err)\n\t}\n\n\tif flagAliasScript {\n\t\tvar alias string\n\t\tswitch shell {\n\t\tcase \"csh\", \"tcsh\":\n\t\t\talias = \"alias git hub\"\n\t\tdefault:\n\t\t\talias = \"alias git=hub\"\n\t\t}\n\n\t\tui.Println(alias)\n\t} else {\n\t\tvar profile string\n\t\tswitch shell {\n\t\tcase \"bash\":\n\t\t\tprofile = \"~\/.bash_profile\"\n\t\tcase \"zsh\":\n\t\t\tprofile = \"~\/.zshrc\"\n\t\tcase \"ksh\":\n\t\t\tprofile = \"~\/.profile\"\n\t\tcase \"fish\":\n\t\t\tprofile = \"~\/.config\/fish\/functions\/git.fish\"\n\t\tcase \"csh\":\n\t\t\tprofile = \"~\/.cshrc\"\n\t\tcase \"tcsh\":\n\t\t\tprofile = \"~\/.tcshrc\"\n\t\tdefault:\n\t\t\tprofile = \"your profile\"\n\t\t}\n\n\t\tmsg := fmt.Sprintf(\"# Wrap git automatically by adding the following to %s:\\n\", profile)\n\t\tui.Println(msg)\n\n\t\tvar eval string\n\t\tswitch shell {\n\t\tcase \"fish\":\n\t\t\teval = `function git --description 'Alias for hub, which wraps git to provide extra functionality with GitHub.'\n\thub $argv\nend`\n\t\tcase \"csh\", \"tcsh\":\n\t\t\teval = \"eval \\\"`hub alias -s`\\\"\"\n\t\tdefault:\n\t\t\teval = `eval \"$(hub alias -s)\"`\n\t\t}\n\n\t\tindent := regexp.MustCompile(`(?m)^\\t+`)\n\t\teval = indent.ReplaceAllStringFunc(eval, func(match string) string {\n\t\t\treturn strings.Repeat(\" \", len(match) * 4)\n\t\t})\n\n\t\tui.Println(eval)\n\t}\n\n\tos.Exit(0)\n}\n<commit_msg>go fmt<commit_after>package commands\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/github\/hub\/ui\"\n\t\"github.com\/github\/hub\/utils\"\n)\n\nvar cmdAlias = &Command{\n\tRun:   alias,\n\tUsage: \"alias [-s] [<SHELL>]\",\n\tLong: `Show shell instructions for wrapping git.\n\n## Options\n\t-s\n\t\tOutput shell script suitable for 'eval'.\n\n\t<SHELL>\n\t\tSpecify the type of shell (default: \"$SHELL\" environment variable).\n\n## See also:\n\nhub(1)\n`,\n}\n\nvar flagAliasScript bool\n\nfunc init() {\n\tcmdAlias.Flag.BoolVarP(&flagAliasScript, \"script\", \"s\", false, \"SCRIPT\")\n\tCmdRunner.Use(cmdAlias)\n}\n\nfunc alias(command *Command, args *Args) {\n\tvar shell string\n\tif args.ParamsSize() > 0 {\n\t\tshell = args.FirstParam()\n\t} else {\n\t\tshell = os.Getenv(\"SHELL\")\n\t}\n\n\tif shell == \"\" {\n\t\tcmd := \"hub alias <shell>\"\n\t\tif flagAliasScript {\n\t\t\tcmd = \"hub alias -s <shell>\"\n\t\t}\n\t\tutils.Check(fmt.Errorf(\"Error: couldn't detect shell type. Please specify your shell with `%s`\", cmd))\n\t}\n\n\tshells := []string{\"bash\", \"zsh\", \"sh\", \"ksh\", \"csh\", \"tcsh\", \"fish\"}\n\tshell = filepath.Base(shell)\n\tvar validShell bool\n\tfor _, s := range shells {\n\t\tif s == shell {\n\t\t\tvalidShell = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !validShell {\n\t\terr := fmt.Errorf(\"hub alias: unsupported shell\\nsupported shells: %s\", strings.Join(shells, \" \"))\n\t\tutils.Check(err)\n\t}\n\n\tif flagAliasScript {\n\t\tvar alias string\n\t\tswitch shell {\n\t\tcase \"csh\", \"tcsh\":\n\t\t\talias = \"alias git hub\"\n\t\tdefault:\n\t\t\talias = \"alias git=hub\"\n\t\t}\n\n\t\tui.Println(alias)\n\t} else {\n\t\tvar profile string\n\t\tswitch shell {\n\t\tcase \"bash\":\n\t\t\tprofile = \"~\/.bash_profile\"\n\t\tcase \"zsh\":\n\t\t\tprofile = \"~\/.zshrc\"\n\t\tcase \"ksh\":\n\t\t\tprofile = \"~\/.profile\"\n\t\tcase \"fish\":\n\t\t\tprofile = \"~\/.config\/fish\/functions\/git.fish\"\n\t\tcase \"csh\":\n\t\t\tprofile = \"~\/.cshrc\"\n\t\tcase \"tcsh\":\n\t\t\tprofile = \"~\/.tcshrc\"\n\t\tdefault:\n\t\t\tprofile = \"your profile\"\n\t\t}\n\n\t\tmsg := fmt.Sprintf(\"# Wrap git automatically by adding the following to %s:\\n\", profile)\n\t\tui.Println(msg)\n\n\t\tvar eval string\n\t\tswitch shell {\n\t\tcase \"fish\":\n\t\t\teval = `function git --description 'Alias for hub, which wraps git to provide extra functionality with GitHub.'\n\thub $argv\nend`\n\t\tcase \"csh\", \"tcsh\":\n\t\t\teval = \"eval \\\"`hub alias -s`\\\"\"\n\t\tdefault:\n\t\t\teval = `eval \"$(hub alias -s)\"`\n\t\t}\n\n\t\tindent := regexp.MustCompile(`(?m)^\\t+`)\n\t\teval = indent.ReplaceAllStringFunc(eval, func(match string) string {\n\t\t\treturn strings.Repeat(\" \", len(match)*4)\n\t\t})\n\n\t\tui.Println(eval)\n\t}\n\n\tos.Exit(0)\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/jamesnetherton\/homehub-cli\/service\"\n)\n\n\/\/ NewRebootCommand creates a new command to invoke the Hub Reboot function\nfunc NewRebootCommand(authenticatingCommand *GenericCommand) *AuthenticationRequiringCommand {\n\treturn &AuthenticationRequiringCommand{\n\t\tGenericCommand: GenericCommand{\n\t\t\tName:        \"Reboot\",\n\t\t\tDescription: \"Reboots the Home Hub\",\n\t\t\tExec: func(context *CommandContext) {\n\t\t\t\tcontext.SetResult(nil, service.GetHub().Reboot())\n\t\t\t},\n\t\t\tPostExec: func(context *CommandContext) {\n\t\t\t\tfmt.Print(\"\\nWaiting for Home Hub to reboot...\")\n\t\t\t\tattempts := 0\n\t\t\t\tfor {\n\t\t\t\t\tattempts++\n\t\t\t\t\tresponse, err := http.Get(service.GetHub().URL)\n\t\t\t\t\tif err != nil || response.StatusCode != 200 {\n\t\t\t\t\t\tif attempts == 24 {\n\t\t\t\t\t\t\tfmt.Println(\"\\nGave up waiting for Home Hub to become available\")\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfmt.Print(\".\")\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Println()\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\ttime.Sleep(5000 * time.Millisecond)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tAuthenticatingCommand: authenticatingCommand,\n\t}\n}\n<commit_msg>Add sleep after sending reboot command<commit_after>package cmd\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/jamesnetherton\/homehub-cli\/service\"\n)\n\n\/\/ NewRebootCommand creates a new command to invoke the Hub Reboot function\nfunc NewRebootCommand(authenticatingCommand *GenericCommand) *AuthenticationRequiringCommand {\n\treturn &AuthenticationRequiringCommand{\n\t\tGenericCommand: GenericCommand{\n\t\t\tName:        \"Reboot\",\n\t\t\tDescription: \"Reboots the Home Hub\",\n\t\t\tExec: func(context *CommandContext) {\n\t\t\t\tcontext.SetResult(nil, service.GetHub().Reboot())\n\t\t\t},\n\t\t\tPostExec: func(context *CommandContext) {\n\t\t\t\tfmt.Print(\"\\nWaiting for Home Hub to reboot...\")\n\n\t\t\t\t\/\/ Give the hub a chance to initialise its reboot sequence\n\t\t\t\ttime.Sleep(10000 * time.Millisecond)\n\n\t\t\t\tattempts := 0\n\t\t\t\tfor {\n\t\t\t\t\tattempts++\n\t\t\t\t\tresponse, err := http.Get(service.GetHub().URL)\n\t\t\t\t\tif err != nil || response.StatusCode != 200 {\n\t\t\t\t\t\tif attempts == 25 {\n\t\t\t\t\t\t\tfmt.Println(\"\\nGave up waiting for Home Hub to become available\")\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfmt.Print(\".\")\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Println()\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\ttime.Sleep(5000 * time.Millisecond)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tAuthenticatingCommand: authenticatingCommand,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Andreas Koch. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage mapper\n\nimport (\n\t\"fmt\"\n\t\"github.com\/andreaskoch\/allmark\/converter\"\n\t\"github.com\/andreaskoch\/allmark\/parser\"\n\t\"github.com\/andreaskoch\/allmark\/path\"\n\t\"github.com\/andreaskoch\/allmark\/repository\"\n\t\"github.com\/andreaskoch\/allmark\/view\"\n\t\"regexp\"\n\t\"time\"\n)\n\n\/\/ Pattern which matches all HTML\/XML tags\nvar HtmlTagPattern = regexp.MustCompile(`\\<[^\\>]*\\>`)\n\nfunc createMessageMapperFunc(pathProvider *path.Provider, targetFormat string) Mapper {\n\treturn func(item *repository.Item) view.Model {\n\n\t\tparsed, err := converter.Convert(item, targetFormat)\n\t\tif err != nil {\n\t\t\treturn view.Error(fmt.Sprintf(\"%s\", err))\n\t\t}\n\n\t\treturn view.Model{\n\t\t\tPath:        pathProvider.GetWebRoute(item),\n\t\t\tTitle:       getTitle(parsed),\n\t\t\tDescription: getDescription(parsed),\n\t\t\tContent:     parsed.ConvertedContent,\n\t\t\tLanguageTag: getTwoLetterLanguageCode(parsed.MetaData.Language),\n\t\t}\n\t}\n}\n\nfunc getDescription(parsedResult *parser.Result) string {\n\treturn parsedResult.MetaData.Date.Format(time.RFC850)\n}\n\nfunc getTitle(parsedResult *parser.Result) string {\n\ttext := HtmlTagPattern.ReplaceAllString(parsedResult.ConvertedContent, \"\")\n\texcerpt := getTextExcerpt(text, 30)\n\ttime := parsedResult.MetaData.Date.Format(time.RFC850)\n\n\treturn fmt.Sprintf(\"%s ◦ %s\", excerpt, time)\n}\n\nfunc getTextExcerpt(text string, length int) string {\n\n\tif len(text) <= length {\n\t\treturn text\n\t}\n\n\treturn text[0:length] + \" ...\"\n}\n<commit_msg>Changed the title format for messages<commit_after>\/\/ Copyright 2013 Andreas Koch. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage mapper\n\nimport (\n\t\"fmt\"\n\t\"github.com\/andreaskoch\/allmark\/converter\"\n\t\"github.com\/andreaskoch\/allmark\/parser\"\n\t\"github.com\/andreaskoch\/allmark\/path\"\n\t\"github.com\/andreaskoch\/allmark\/repository\"\n\t\"github.com\/andreaskoch\/allmark\/view\"\n\t\"regexp\"\n\t\"time\"\n)\n\n\/\/ Pattern which matches all HTML\/XML tags\nvar HtmlTagPattern = regexp.MustCompile(`\\<[^\\>]*\\>`)\n\nfunc createMessageMapperFunc(pathProvider *path.Provider, targetFormat string) Mapper {\n\treturn func(item *repository.Item) view.Model {\n\n\t\tparsed, err := converter.Convert(item, targetFormat)\n\t\tif err != nil {\n\t\t\treturn view.Error(fmt.Sprintf(\"%s\", err))\n\t\t}\n\n\t\treturn view.Model{\n\t\t\tPath:        pathProvider.GetWebRoute(item),\n\t\t\tTitle:       getTitle(parsed),\n\t\t\tDescription: getDescription(parsed),\n\t\t\tContent:     parsed.ConvertedContent,\n\t\t\tLanguageTag: getTwoLetterLanguageCode(parsed.MetaData.Language),\n\t\t}\n\t}\n}\n\nfunc getDescription(parsedResult *parser.Result) string {\n\treturn parsedResult.MetaData.Date.Format(time.RFC850)\n}\n\nfunc getTitle(parsedResult *parser.Result) string {\n\ttext := HtmlTagPattern.ReplaceAllString(parsedResult.ConvertedContent, \"\")\n\texcerpt := getTextExcerpt(text, 30)\n\ttime := parsedResult.MetaData.Date.Format(time.RFC850)\n\n\treturn fmt.Sprintf(\"%s: %s\", time, excerpt)\n}\n\nfunc getTextExcerpt(text string, length int) string {\n\n\tif len(text) <= length {\n\t\treturn text\n\t}\n\n\treturn text[0:length] + \" ...\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package caddy\n\nimport (\n\t\"net\"\n\t\"strconv\"\n\t\"testing\"\n)\n\n\/*\n\/\/ TODO\nfunc TestCaddyStartStop(t *testing.T) {\n\tcaddyfile := \"localhost:1984\"\n\n\tfor i := 0; i < 2; i++ {\n\t\t_, err := Start(CaddyfileInput{Contents: []byte(caddyfile)})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error starting, iteration %d: %v\", i, err)\n\t\t}\n\n\t\tclient := http.Client{\n\t\t\tTimeout: time.Duration(2 * time.Second),\n\t\t}\n\t\tresp, err := client.Get(\"http:\/\/localhost:1984\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected GET request to succeed (iteration %d), but it failed: %v\", i, err)\n\t\t}\n\t\tresp.Body.Close()\n\n\t\terr = Stop()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error stopping, iteration %d: %v\", i, err)\n\t\t}\n\t}\n}\n*\/\n\nfunc TestIsLoopback(t *testing.T) {\n\tfor i, test := range []struct {\n\t\tinput  string\n\t\texpect bool\n\t}{\n\t\t{\"example.com\", false},\n\t\t{\"localhost\", true},\n\t\t{\"localhost:1234\", true},\n\t\t{\"localhost:\", true},\n\t\t{\"127.0.0.1\", true},\n\t\t{\"127.0.0.1:443\", true},\n\t\t{\"127.0.1.5\", true},\n\t\t{\"10.0.0.5\", false},\n\t\t{\"12.7.0.1\", false},\n\t\t{\"[::1]\", true},\n\t\t{\"[::1]:1234\", true},\n\t\t{\"::1\", true},\n\t\t{\"::\", false},\n\t\t{\"[::]\", false},\n\t\t{\"local\", false},\n\t} {\n\t\tif got, want := IsLoopback(test.input), test.expect; got != want {\n\t\t\tt.Errorf(\"Test %d (%s): expected %v but was %v\", i, test.input, want, got)\n\t\t}\n\t}\n}\n\nfunc TestListenerAddrEqual(t *testing.T) {\n\tln1, err := net.Listen(\"tcp\", \"[::]:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer ln1.Close()\n\n\tln1port := strconv.Itoa(ln1.Addr().(*net.TCPAddr).Port)\n\n\tln2, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer ln2.Close()\n\n\tln2port := strconv.Itoa(ln2.Addr().(*net.TCPAddr).Port)\n\n\tfor i, test := range []struct {\n\t\tln     net.Listener\n\t\taddr   string\n\t\texpect bool\n\t}{\n\t\t{ln1, \":1234\", false},\n\t\t{ln1, \"0.0.0.0:1234\", false},\n\t\t{ln1, \":\" + ln1port + \"\", true},\n\t\t{ln1, \"0.0.0.0:\" + ln1port + \"\", true},\n\t\t{ln2, \"127.0.0.1:1234\", false},\n\t\t{ln2, \":\" + ln2port + \"\", false},\n\t\t{ln2, \"127.0.0.1:\" + ln2port + \"\", true},\n\t} {\n\t\tif got, want := listenerAddrEqual(test.ln, test.addr), test.expect; got != want {\n\t\t\tt.Errorf(\"Test %d (%s == %s): expected %v but was %v\", i, test.addr, test.ln.Addr().String(), want, got)\n\t\t}\n\t}\n}\n<commit_msg>Increase code coverage<commit_after>package caddy\n\nimport (\n\t\"net\"\n\t\"strconv\"\n\t\"testing\"\n)\n\n\/*\n\/\/ TODO\nfunc TestCaddyStartStop(t *testing.T) {\n\tcaddyfile := \"localhost:1984\"\n\n\tfor i := 0; i < 2; i++ {\n\t\t_, err := Start(CaddyfileInput{Contents: []byte(caddyfile)})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error starting, iteration %d: %v\", i, err)\n\t\t}\n\n\t\tclient := http.Client{\n\t\t\tTimeout: time.Duration(2 * time.Second),\n\t\t}\n\t\tresp, err := client.Get(\"http:\/\/localhost:1984\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected GET request to succeed (iteration %d), but it failed: %v\", i, err)\n\t\t}\n\t\tresp.Body.Close()\n\n\t\terr = Stop()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error stopping, iteration %d: %v\", i, err)\n\t\t}\n\t}\n}\n*\/\n\nfunc TestIsLoopback(t *testing.T) {\n\tfor i, test := range []struct {\n\t\tinput  string\n\t\texpect bool\n\t}{\n\t\t{\"example.com\", false},\n\t\t{\"localhost\", true},\n\t\t{\"localhost:1234\", true},\n\t\t{\"localhost:\", true},\n\t\t{\"127.0.0.1\", true},\n\t\t{\"127.0.0.1:443\", true},\n\t\t{\"127.0.1.5\", true},\n\t\t{\"10.0.0.5\", false},\n\t\t{\"12.7.0.1\", false},\n\t\t{\"[::1]\", true},\n\t\t{\"[::1]:1234\", true},\n\t\t{\"::1\", true},\n\t\t{\"::\", false},\n\t\t{\"[::]\", false},\n\t\t{\"local\", false},\n\t} {\n\t\tif got, want := IsLoopback(test.input), test.expect; got != want {\n\t\t\tt.Errorf(\"Test %d (%s): expected %v but was %v\", i, test.input, want, got)\n\t\t}\n\t}\n}\n\nfunc TestListenerAddrEqual(t *testing.T) {\n\tln1, err := net.Listen(\"tcp\", \"[::]:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer ln1.Close()\n\n\tln1port := strconv.Itoa(ln1.Addr().(*net.TCPAddr).Port)\n\n\tln2, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer ln2.Close()\n\n\tln2port := strconv.Itoa(ln2.Addr().(*net.TCPAddr).Port)\n\n\tfor i, test := range []struct {\n\t\tln     net.Listener\n\t\taddr   string\n\t\texpect bool\n\t}{\n\t\t{ln1, \":1234\", false},\n\t\t{ln1, \"0.0.0.0:1234\", false},\n\t\t{ln1, \"0.0.0.0\", false},\n\t\t{ln1, \":\" + ln1port + \"\", true},\n\t\t{ln1, \"0.0.0.0:\" + ln1port + \"\", true},\n\t\t{ln2, \":\" + ln2port + \"\", false},\n\t\t{ln2, \"127.0.0.1:1234\", false},\n\t\t{ln2, \"127.0.0.1\", false},\n\t\t{ln2, \"127.0.0.1:\" + ln2port + \"\", true},\n\t} {\n\t\tif got, want := listenerAddrEqual(test.ln, test.addr), test.expect; got != want {\n\t\t\tt.Errorf(\"Test %d (%s == %s): expected %v but was %v\", i, test.addr, test.ln.Addr().String(), want, got)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"time\"\n\n\tcfg \"github.com\/flynn\/flynn\/cli\/config\"\n\t\"github.com\/flynn\/flynn\/controller\/client\"\n\tct \"github.com\/flynn\/flynn\/controller\/types\"\n\t\"github.com\/flynn\/flynn\/host\/types\"\n\t\"github.com\/flynn\/flynn\/pkg\/backup\"\n\t\"github.com\/flynn\/go-docopt\"\n)\n\nfunc init() {\n\tregister(\"docker\", runDocker, `\nusage: flynn docker set-push-url [<url>]\n       flynn docker login\n       flynn docker logout\n       flynn docker push <image>\n\nDeploy Docker images to a Flynn cluster.\n\nCommands:\n\tset-push-url  set the Docker push URL (defaults to https:\/\/docker.$CLUSTER_DOMAIN)\n\n\tlogin         run \"docker login\" against the cluster's docker-receive app\n\n\tlogout        run \"docker logout\" against the cluster's docker-receive app\n\n\tpush          push and release a Docker image to the cluster\n\nExample:\n\n\tAssuming you have a Docker image tagged \"my-custom-image:v2\":\n\n\t$ flynn docker push my-custom-image:v2\n\tflynn: getting image config with \"docker inspect -f {{ json .Config }} my-custom-image:v2\"\n\tflynn: tagging Docker image with \"docker tag --force my-custom-image:v2 docker.1.localflynn.com\/my-app:latest\"\n\tflynn: pushing Docker image with \"docker push docker.1.localflynn.com\/my-app:latest\"\n\tThe push refers to a repository [docker.1.localflynn.com\/my-app] (len: 1)\n\ta8eb754d1a89: Pushed\n\t...\n\t3059b4820522: Pushed\n\tlatest: digest: sha256:1752ca12bbedb99734ca1ba3ec35720768a95ad83b7b6c371fc37a28b98ea351 size: 61216\n\tflynn: image pushed, waiting for artifact creation\n\tflynn: deploying release using artifact URI http:\/\/docker-receive.discoverd?name=my-app&id=sha256:1752ca12bbedb99734ca1ba3ec35720768a95ad83b7b6c371fc37a28b98ea351\n\tflynn: image deployed, scale it with 'flynn scale app=N'\n`)\n}\n\nfunc runDocker(args *docopt.Args, client controller.Client) error {\n\tif args.Bool[\"set-push-url\"] {\n\t\treturn runDockerSetPushURL(args)\n\t} else if args.Bool[\"login\"] {\n\t\treturn runDockerLogin()\n\t} else if args.Bool[\"logout\"] {\n\t\treturn runDockerLogout()\n\t} else if args.Bool[\"push\"] {\n\t\treturn runDockerPush(args, client)\n\t}\n\treturn errors.New(\"unknown docker subcommand\")\n}\n\nfunc runDockerSetPushURL(args *docopt.Args) error {\n\tcluster, err := getCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\turl := args.String[\"<url>\"]\n\tif url == \"\" {\n\t\tif cluster.DockerPushURL != \"\" {\n\t\t\treturn fmt.Errorf(\"ERROR: refusing to overwrite current Docker push URL %q with a default one. To overwrite the existing URL, set one explicitly with 'flynn docker set-push-url URL'\", cluster.DockerPushURL)\n\t\t}\n\t\tif !strings.Contains(cluster.ControllerURL, \"controller\") {\n\t\t\treturn errors.New(\"ERROR: unable to determine default Docker push URL, set one explicitly with 'flynn docker set-push-url URL'\")\n\t\t}\n\t\turl = strings.Replace(cluster.ControllerURL, \"controller\", \"docker\", 1)\n\t}\n\tif !strings.HasPrefix(url, \"https:\/\/\") {\n\t\turl = \"https:\/\/\" + url\n\t}\n\tcluster.DockerPushURL = url\n\treturn config.SaveTo(configPath())\n}\n\nfunc runDockerLogin() error {\n\tcluster, err := getCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, err := cluster.DockerPushHost()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = dockerLogin(host, cluster.Key)\n\tif e, ok := err.(*exec.Error); ok && e.Err == exec.ErrNotFound {\n\t\terr = errors.New(\"Executable 'docker' was not found.\")\n\t} else if err == ErrDockerTLSError {\n\t\tprintDockerTLSWarning(host, cfg.CACertPath(cluster.Name))\n\t\terr = errors.New(\"Error configuring docker, follow the above instructions and try again.\")\n\t}\n\treturn err\n}\n\nfunc runDockerLogout() error {\n\tcluster, err := getCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, err := cluster.DockerPushHost()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd := dockerLogoutCmd(host)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}\n\nvar ErrDockerTLSError = errors.New(\"docker TLS error\")\n\nfunc dockerLogin(host, key string) error {\n\tvar out bytes.Buffer\n\tcmd := exec.Command(\"docker\", \"login\", \"--email=user@\"+host, \"--username=user\", \"--password=\"+key, host)\n\tcmd.Stdout = &out\n\tcmd.Stderr = &out\n\terr := cmd.Run()\n\tif strings.Contains(out.String(), \"certificate signed by unknown authority\") {\n\t\terr = ErrDockerTLSError\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"error running `docker login`: %s - output: %q\", err, out)\n\t}\n\treturn nil\n}\n\nfunc dockerLogout(host string) error {\n\treturn dockerLogoutCmd(host).Run()\n}\n\nfunc dockerLogoutCmd(host string) *exec.Cmd {\n\treturn exec.Command(\"docker\", \"logout\", host)\n}\n\nfunc printDockerTLSWarning(host, caPath string) {\n\tfmt.Printf(`\nWARN: docker configuration failed with a TLS error.\nWARN:\nWARN: Copy the TLS CA certificate %s\nWARN: to \/etc\/docker\/certs.d\/%s\/ca.crt\nWARN: on the docker daemon's host and restart docker.\nWARN:\nWARN: If using Docker for Mac, go to Docker -> Preferences\nWARN: -> Advanced, add %q as an\nWARN: Insecure Registry and hit \"Apply & Restart\".\n\n`[1:], caPath, host, host)\n}\n\nfunc runDockerPush(args *docopt.Args, client controller.Client) error {\n\tcluster, err := getCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdockerHost, err := cluster.DockerPushHost()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timage := args.String[\"<image>\"]\n\n\tprevRelease, err := client.GetAppRelease(mustApp())\n\tif err == controller.ErrNotFound {\n\t\tprevRelease = &ct.Release{}\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"error getting current app release: %s\", err)\n\t}\n\n\t\/\/ get the image config to determine Cmd, Entrypoint and Env\n\tcmd := exec.Command(\"docker\", \"inspect\", \"-f\", \"{{ json .Config }}\", image)\n\tlog.Printf(\"flynn: getting image config with %q\", strings.Join(cmd.Args, \" \"))\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\tvar config struct {\n\t\tCmd        []string `json:\"Cmd\"`\n\t\tEntrypoint []string `json:\"Entrypoint\"`\n\t\tEnv        []string `json:\"Env\"`\n\t}\n\tif err := json.NewDecoder(stdout).Decode(&config); err != nil {\n\t\treturn err\n\t}\n\tif err := cmd.Wait(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ tag the docker image ready to be pushed\n\ttag := fmt.Sprintf(\"%s\/%s:latest\", dockerHost, mustApp())\n\tcmd = exec.Command(\"docker\", \"tag\", image, tag)\n\tlog.Printf(\"flynn: tagging Docker image with %q\", strings.Join(cmd.Args, \" \"))\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn err\n\t}\n\n\tartifact, err := dockerPush(client, mustApp(), tag)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ create and deploy a release with the image config and created artifact\n\tlog.Printf(\"flynn: deploying release using artifact URI %s\", artifact.URI)\n\trelease := &ct.Release{\n\t\tArtifactIDs: []string{artifact.ID},\n\t\tProcesses:   prevRelease.Processes,\n\t\tEnv:         prevRelease.Env,\n\t\tMeta:        prevRelease.Meta,\n\t}\n\n\tproc, ok := release.Processes[\"app\"]\n\tif !ok {\n\t\tproc = ct.ProcessType{}\n\t}\n\tproc.Args = append(config.Entrypoint, config.Cmd...)\n\tif len(proc.Ports) == 0 {\n\t\tproc.Ports = []ct.Port{{\n\t\t\tPort:  8080,\n\t\t\tProto: \"tcp\",\n\t\t\tService: &host.Service{\n\t\t\t\tName:   mustApp() + \"-web\",\n\t\t\t\tCreate: true,\n\t\t\t},\n\t\t}}\n\t}\n\tif release.Processes == nil {\n\t\trelease.Processes = make(map[string]ct.ProcessType, 1)\n\t}\n\trelease.Processes[\"app\"] = proc\n\n\tif len(config.Env) > 0 && release.Env == nil {\n\t\trelease.Env = make(map[string]string, len(config.Env))\n\t}\n\tfor _, v := range config.Env {\n\t\tkeyVal := strings.SplitN(v, \"=\", 2)\n\t\tif len(keyVal) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ only set the key if it doesn't exist so variables set with\n\t\t\/\/ `flynn env set` are not overwritten\n\t\tif _, ok := release.Env[keyVal[0]]; !ok {\n\t\t\trelease.Env[keyVal[0]] = keyVal[1]\n\t\t}\n\t}\n\n\tif release.Meta == nil {\n\t\trelease.Meta = make(map[string]string, 1)\n\t}\n\trelease.Meta[\"docker-receive\"] = \"true\"\n\n\tif err := client.CreateRelease(release); err != nil {\n\t\treturn err\n\t}\n\tif err := client.DeployAppRelease(mustApp(), release.ID, nil); err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"flynn: image deployed, scale it with 'flynn scale app=N'\")\n\treturn nil\n}\n\nfunc dockerPush(client controller.Client, repo, tag string) (*ct.Artifact, error) {\n\t\/\/ subscribe to artifact events\n\tevents := make(chan *ct.Event)\n\tstream, err := client.StreamEvents(ct.StreamEventsOptions{\n\t\tObjectTypes: []ct.EventType{ct.EventTypeArtifact},\n\t}, events)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer stream.Close()\n\n\t\/\/ push the Docker image to docker-receive\n\tcmd := exec.Command(\"docker\", \"push\", tag)\n\tlog.Printf(\"flynn: pushing Docker image with %q\", strings.Join(cmd.Args, \" \"))\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ wait for an artifact to be created\n\tlog.Printf(\"flynn: image pushed, waiting for artifact creation\")\n\tfor {\n\t\tselect {\n\t\tcase event, ok := <-events:\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"event stream closed unexpectedly: %s\", stream.Err())\n\t\t\t}\n\t\t\tvar artifact ct.Artifact\n\t\t\tif err := json.Unmarshal(event.Data, &artifact); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif artifact.Meta[\"docker-receive.repository\"] == repo {\n\t\t\t\treturn &artifact, nil\n\t\t\t}\n\t\tcase <-time.After(30 * time.Second):\n\t\t\treturn nil, fmt.Errorf(\"timed out waiting for artifact creation\")\n\t\t}\n\t}\n\n}\n\nfunc dockerPull(repo, digest string) error {\n\tcluster, err := getCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, err := cluster.DockerPushHost()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd := exec.Command(\"docker\", \"pull\", fmt.Sprintf(\"%s\/%s@%s\", host, repo, digest))\n\tlog.Printf(\"flynn: pulling Docker image with %q\", strings.Join(cmd.Args, \" \"))\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}\n\nfunc dockerSave(tag string, tw *backup.TarWriter, progress backup.ProgressBar) error {\n\ttmp, err := ioutil.TempFile(\"\", \"flynn-docker-save\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating temp file: %s\", err)\n\t}\n\tdefer tmp.Close()\n\tdefer os.Remove(tmp.Name())\n\n\tcmd := exec.Command(\"docker\", \"save\", tag)\n\tcmd.Stdout = tmp\n\tif progress != nil {\n\t\tcmd.Stdout = io.MultiWriter(tmp, progress)\n\t}\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn err\n\t}\n\n\tlength, err := tmp.Seek(0, os.SEEK_CUR)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := tw.WriteHeader(\"docker-image.tar\", int(length)); err != nil {\n\t\treturn err\n\t}\n\tif _, err := tmp.Seek(0, os.SEEK_SET); err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(tw, tmp)\n\treturn err\n}\n<commit_msg>cli: Remove --force flag from docker push example<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"time\"\n\n\tcfg \"github.com\/flynn\/flynn\/cli\/config\"\n\t\"github.com\/flynn\/flynn\/controller\/client\"\n\tct \"github.com\/flynn\/flynn\/controller\/types\"\n\t\"github.com\/flynn\/flynn\/host\/types\"\n\t\"github.com\/flynn\/flynn\/pkg\/backup\"\n\t\"github.com\/flynn\/go-docopt\"\n)\n\nfunc init() {\n\tregister(\"docker\", runDocker, `\nusage: flynn docker set-push-url [<url>]\n       flynn docker login\n       flynn docker logout\n       flynn docker push <image>\n\nDeploy Docker images to a Flynn cluster.\n\nCommands:\n\tset-push-url  set the Docker push URL (defaults to https:\/\/docker.$CLUSTER_DOMAIN)\n\n\tlogin         run \"docker login\" against the cluster's docker-receive app\n\n\tlogout        run \"docker logout\" against the cluster's docker-receive app\n\n\tpush          push and release a Docker image to the cluster\n\nExample:\n\n\tAssuming you have a Docker image tagged \"my-custom-image:v2\":\n\n\t$ flynn docker push my-custom-image:v2\n\tflynn: getting image config with \"docker inspect -f {{ json .Config }} my-custom-image:v2\"\n\tflynn: tagging Docker image with \"docker tag my-custom-image:v2 docker.1.localflynn.com\/my-app:latest\"\n\tflynn: pushing Docker image with \"docker push docker.1.localflynn.com\/my-app:latest\"\n\tThe push refers to a repository [docker.1.localflynn.com\/my-app] (len: 1)\n\ta8eb754d1a89: Pushed\n\t...\n\t3059b4820522: Pushed\n\tlatest: digest: sha256:1752ca12bbedb99734ca1ba3ec35720768a95ad83b7b6c371fc37a28b98ea351 size: 61216\n\tflynn: image pushed, waiting for artifact creation\n\tflynn: deploying release using artifact URI http:\/\/docker-receive.discoverd?name=my-app&id=sha256:1752ca12bbedb99734ca1ba3ec35720768a95ad83b7b6c371fc37a28b98ea351\n\tflynn: image deployed, scale it with 'flynn scale app=N'\n`)\n}\n\nfunc runDocker(args *docopt.Args, client controller.Client) error {\n\tif args.Bool[\"set-push-url\"] {\n\t\treturn runDockerSetPushURL(args)\n\t} else if args.Bool[\"login\"] {\n\t\treturn runDockerLogin()\n\t} else if args.Bool[\"logout\"] {\n\t\treturn runDockerLogout()\n\t} else if args.Bool[\"push\"] {\n\t\treturn runDockerPush(args, client)\n\t}\n\treturn errors.New(\"unknown docker subcommand\")\n}\n\nfunc runDockerSetPushURL(args *docopt.Args) error {\n\tcluster, err := getCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\turl := args.String[\"<url>\"]\n\tif url == \"\" {\n\t\tif cluster.DockerPushURL != \"\" {\n\t\t\treturn fmt.Errorf(\"ERROR: refusing to overwrite current Docker push URL %q with a default one. To overwrite the existing URL, set one explicitly with 'flynn docker set-push-url URL'\", cluster.DockerPushURL)\n\t\t}\n\t\tif !strings.Contains(cluster.ControllerURL, \"controller\") {\n\t\t\treturn errors.New(\"ERROR: unable to determine default Docker push URL, set one explicitly with 'flynn docker set-push-url URL'\")\n\t\t}\n\t\turl = strings.Replace(cluster.ControllerURL, \"controller\", \"docker\", 1)\n\t}\n\tif !strings.HasPrefix(url, \"https:\/\/\") {\n\t\turl = \"https:\/\/\" + url\n\t}\n\tcluster.DockerPushURL = url\n\treturn config.SaveTo(configPath())\n}\n\nfunc runDockerLogin() error {\n\tcluster, err := getCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, err := cluster.DockerPushHost()\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = dockerLogin(host, cluster.Key)\n\tif e, ok := err.(*exec.Error); ok && e.Err == exec.ErrNotFound {\n\t\terr = errors.New(\"Executable 'docker' was not found.\")\n\t} else if err == ErrDockerTLSError {\n\t\tprintDockerTLSWarning(host, cfg.CACertPath(cluster.Name))\n\t\terr = errors.New(\"Error configuring docker, follow the above instructions and try again.\")\n\t}\n\treturn err\n}\n\nfunc runDockerLogout() error {\n\tcluster, err := getCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, err := cluster.DockerPushHost()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd := dockerLogoutCmd(host)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}\n\nvar ErrDockerTLSError = errors.New(\"docker TLS error\")\n\nfunc dockerLogin(host, key string) error {\n\tvar out bytes.Buffer\n\tcmd := exec.Command(\"docker\", \"login\", \"--email=user@\"+host, \"--username=user\", \"--password=\"+key, host)\n\tcmd.Stdout = &out\n\tcmd.Stderr = &out\n\terr := cmd.Run()\n\tif strings.Contains(out.String(), \"certificate signed by unknown authority\") {\n\t\terr = ErrDockerTLSError\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"error running `docker login`: %s - output: %q\", err, out)\n\t}\n\treturn nil\n}\n\nfunc dockerLogout(host string) error {\n\treturn dockerLogoutCmd(host).Run()\n}\n\nfunc dockerLogoutCmd(host string) *exec.Cmd {\n\treturn exec.Command(\"docker\", \"logout\", host)\n}\n\nfunc printDockerTLSWarning(host, caPath string) {\n\tfmt.Printf(`\nWARN: docker configuration failed with a TLS error.\nWARN:\nWARN: Copy the TLS CA certificate %s\nWARN: to \/etc\/docker\/certs.d\/%s\/ca.crt\nWARN: on the docker daemon's host and restart docker.\nWARN:\nWARN: If using Docker for Mac, go to Docker -> Preferences\nWARN: -> Advanced, add %q as an\nWARN: Insecure Registry and hit \"Apply & Restart\".\n\n`[1:], caPath, host, host)\n}\n\nfunc runDockerPush(args *docopt.Args, client controller.Client) error {\n\tcluster, err := getCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdockerHost, err := cluster.DockerPushHost()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timage := args.String[\"<image>\"]\n\n\tprevRelease, err := client.GetAppRelease(mustApp())\n\tif err == controller.ErrNotFound {\n\t\tprevRelease = &ct.Release{}\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"error getting current app release: %s\", err)\n\t}\n\n\t\/\/ get the image config to determine Cmd, Entrypoint and Env\n\tcmd := exec.Command(\"docker\", \"inspect\", \"-f\", \"{{ json .Config }}\", image)\n\tlog.Printf(\"flynn: getting image config with %q\", strings.Join(cmd.Args, \" \"))\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\tvar config struct {\n\t\tCmd        []string `json:\"Cmd\"`\n\t\tEntrypoint []string `json:\"Entrypoint\"`\n\t\tEnv        []string `json:\"Env\"`\n\t}\n\tif err := json.NewDecoder(stdout).Decode(&config); err != nil {\n\t\treturn err\n\t}\n\tif err := cmd.Wait(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ tag the docker image ready to be pushed\n\ttag := fmt.Sprintf(\"%s\/%s:latest\", dockerHost, mustApp())\n\tcmd = exec.Command(\"docker\", \"tag\", image, tag)\n\tlog.Printf(\"flynn: tagging Docker image with %q\", strings.Join(cmd.Args, \" \"))\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn err\n\t}\n\n\tartifact, err := dockerPush(client, mustApp(), tag)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ create and deploy a release with the image config and created artifact\n\tlog.Printf(\"flynn: deploying release using artifact URI %s\", artifact.URI)\n\trelease := &ct.Release{\n\t\tArtifactIDs: []string{artifact.ID},\n\t\tProcesses:   prevRelease.Processes,\n\t\tEnv:         prevRelease.Env,\n\t\tMeta:        prevRelease.Meta,\n\t}\n\n\tproc, ok := release.Processes[\"app\"]\n\tif !ok {\n\t\tproc = ct.ProcessType{}\n\t}\n\tproc.Args = append(config.Entrypoint, config.Cmd...)\n\tif len(proc.Ports) == 0 {\n\t\tproc.Ports = []ct.Port{{\n\t\t\tPort:  8080,\n\t\t\tProto: \"tcp\",\n\t\t\tService: &host.Service{\n\t\t\t\tName:   mustApp() + \"-web\",\n\t\t\t\tCreate: true,\n\t\t\t},\n\t\t}}\n\t}\n\tif release.Processes == nil {\n\t\trelease.Processes = make(map[string]ct.ProcessType, 1)\n\t}\n\trelease.Processes[\"app\"] = proc\n\n\tif len(config.Env) > 0 && release.Env == nil {\n\t\trelease.Env = make(map[string]string, len(config.Env))\n\t}\n\tfor _, v := range config.Env {\n\t\tkeyVal := strings.SplitN(v, \"=\", 2)\n\t\tif len(keyVal) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ only set the key if it doesn't exist so variables set with\n\t\t\/\/ `flynn env set` are not overwritten\n\t\tif _, ok := release.Env[keyVal[0]]; !ok {\n\t\t\trelease.Env[keyVal[0]] = keyVal[1]\n\t\t}\n\t}\n\n\tif release.Meta == nil {\n\t\trelease.Meta = make(map[string]string, 1)\n\t}\n\trelease.Meta[\"docker-receive\"] = \"true\"\n\n\tif err := client.CreateRelease(release); err != nil {\n\t\treturn err\n\t}\n\tif err := client.DeployAppRelease(mustApp(), release.ID, nil); err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"flynn: image deployed, scale it with 'flynn scale app=N'\")\n\treturn nil\n}\n\nfunc dockerPush(client controller.Client, repo, tag string) (*ct.Artifact, error) {\n\t\/\/ subscribe to artifact events\n\tevents := make(chan *ct.Event)\n\tstream, err := client.StreamEvents(ct.StreamEventsOptions{\n\t\tObjectTypes: []ct.EventType{ct.EventTypeArtifact},\n\t}, events)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer stream.Close()\n\n\t\/\/ push the Docker image to docker-receive\n\tcmd := exec.Command(\"docker\", \"push\", tag)\n\tlog.Printf(\"flynn: pushing Docker image with %q\", strings.Join(cmd.Args, \" \"))\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ wait for an artifact to be created\n\tlog.Printf(\"flynn: image pushed, waiting for artifact creation\")\n\tfor {\n\t\tselect {\n\t\tcase event, ok := <-events:\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"event stream closed unexpectedly: %s\", stream.Err())\n\t\t\t}\n\t\t\tvar artifact ct.Artifact\n\t\t\tif err := json.Unmarshal(event.Data, &artifact); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif artifact.Meta[\"docker-receive.repository\"] == repo {\n\t\t\t\treturn &artifact, nil\n\t\t\t}\n\t\tcase <-time.After(30 * time.Second):\n\t\t\treturn nil, fmt.Errorf(\"timed out waiting for artifact creation\")\n\t\t}\n\t}\n\n}\n\nfunc dockerPull(repo, digest string) error {\n\tcluster, err := getCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\thost, err := cluster.DockerPushHost()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd := exec.Command(\"docker\", \"pull\", fmt.Sprintf(\"%s\/%s@%s\", host, repo, digest))\n\tlog.Printf(\"flynn: pulling Docker image with %q\", strings.Join(cmd.Args, \" \"))\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}\n\nfunc dockerSave(tag string, tw *backup.TarWriter, progress backup.ProgressBar) error {\n\ttmp, err := ioutil.TempFile(\"\", \"flynn-docker-save\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating temp file: %s\", err)\n\t}\n\tdefer tmp.Close()\n\tdefer os.Remove(tmp.Name())\n\n\tcmd := exec.Command(\"docker\", \"save\", tag)\n\tcmd.Stdout = tmp\n\tif progress != nil {\n\t\tcmd.Stdout = io.MultiWriter(tmp, progress)\n\t}\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn err\n\t}\n\n\tlength, err := tmp.Seek(0, os.SEEK_CUR)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := tw.WriteHeader(\"docker-image.tar\", int(length)); err != nil {\n\t\treturn err\n\t}\n\tif _, err := tmp.Seek(0, os.SEEK_SET); err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(tw, tmp)\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package dialer\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n\n\t\"github.com\/rancher\/rancher\/pkg\/encryptedstore\"\n\t\"github.com\/rancher\/rancher\/pkg\/nodeconfig\"\n\t\"github.com\/rancher\/rancher\/pkg\/remotedialer\"\n\t\"github.com\/rancher\/rancher\/pkg\/tunnelserver\"\n\t\"github.com\/rancher\/types\/apis\/management.cattle.io\/v3\"\n\t\"github.com\/rancher\/types\/config\"\n\t\"github.com\/rancher\/types\/config\/dialer\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n)\n\nfunc NewFactory(apiContext *config.ScaledContext) (dialer.Factory, error) {\n\tauthorizer := tunnelserver.NewAuthorizer(apiContext)\n\ttunneler := tunnelserver.NewTunnelServer(apiContext, authorizer)\n\n\tsecretStore, err := nodeconfig.NewStore(apiContext.Core.Namespaces(\"\"), apiContext.K8sClient.CoreV1())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiContext.Management.Nodes(\"local\").Controller().Informer().AddIndexers(cache.Indexers{\n\t\tnodeAccessIndexer: nodeIndexer,\n\t})\n\n\treturn &Factory{\n\t\tclusterLister:       apiContext.Management.Clusters(\"\").Controller().Lister(),\n\t\tlocalNodeController: apiContext.Management.Nodes(\"local\").Controller(),\n\t\tnodeLister:          apiContext.Management.Nodes(\"\").Controller().Lister(),\n\t\tTunnelServer:        tunneler,\n\t\tTunnelAuthorizer:    authorizer,\n\t\tstore:               secretStore,\n\t}, nil\n}\n\ntype Factory struct {\n\tlocalNodeController v3.NodeController\n\tnodeLister          v3.NodeLister\n\tclusterLister       v3.ClusterLister\n\tTunnelServer        *remotedialer.Server\n\tTunnelAuthorizer    *tunnelserver.Authorizer\n\tstore               *encryptedstore.GenericEncryptedStore\n}\n\nfunc (f *Factory) ClusterDialer(clusterName string) (dialer.Dialer, error) {\n\treturn func(network, address string) (net.Conn, error) {\n\t\td, err := f.clusterDialer(clusterName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn d(network, address)\n\t}, nil\n}\n\nfunc (f *Factory) clusterDialer(clusterName string) (dialer.Dialer, error) {\n\tcluster, err := f.clusterLister.Get(\"\", clusterName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif f.TunnelServer.HasSession(cluster.Name) {\n\t\treturn f.TunnelServer.Dialer(cluster.Name, 15*time.Second), nil\n\t}\n\n\tnodes, err := f.nodeLister.List(cluster.Name, labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, node := range nodes {\n\t\tif node.DeletionTimestamp == nil && v3.NodeConditionProvisioned.IsTrue(node) {\n\t\t\tif nodeDialer, err := f.nodeDialer(clusterName, node.Name); err == nil {\n\t\t\t\treturn nodeDialer, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn net.Dial, nil\n}\n\nfunc (f *Factory) DockerDialer(clusterName, machineName string) (dialer.Dialer, error) {\n\tmachine, err := f.nodeLister.Get(clusterName, machineName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif f.TunnelServer.HasSession(machine.Name) {\n\t\td := f.TunnelServer.Dialer(machine.Name, 15*time.Second)\n\t\treturn func(string, string) (net.Conn, error) {\n\t\t\treturn d(\"unix\", \"\/var\/run\/docker.sock\")\n\t\t}, nil\n\t}\n\n\tif machine.Spec.CustomConfig != nil && machine.Spec.CustomConfig.Address != \"\" && machine.Spec.CustomConfig.SSHKey != \"\" {\n\t\treturn f.sshDialer(machine)\n\t}\n\n\tif machine.Spec.NodeTemplateName != \"\" {\n\t\treturn f.tlsDialer(machine)\n\t}\n\n\treturn nil, fmt.Errorf(\"can not build dialer to %s:%s\", clusterName, machineName)\n}\n\nfunc (f *Factory) NodeDialer(clusterName, machineName string) (dialer.Dialer, error) {\n\treturn func(network, address string) (net.Conn, error) {\n\t\td, err := f.nodeDialer(clusterName, machineName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn d(network, address)\n\t}, nil\n}\n\nfunc (f *Factory) nodeDialer(clusterName, machineName string) (dialer.Dialer, error) {\n\tmachine, err := f.nodeLister.Get(clusterName, machineName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif f.TunnelServer.HasSession(machine.Name) {\n\t\td := f.TunnelServer.Dialer(machine.Name, 15*time.Second)\n\t\treturn dialer.Dialer(d), nil\n\t}\n\n\tif machine.Spec.CustomConfig != nil && machine.Spec.CustomConfig.Address != \"\" && machine.Spec.CustomConfig.SSHKey != \"\" {\n\t\treturn f.sshLocalDialer(machine)\n\t}\n\n\tif machine.Spec.NodeTemplateName != \"\" {\n\t\treturn f.sshLocalDialer(machine)\n\t}\n\n\treturn nil, fmt.Errorf(\"can not build dialer to %s:%s\", clusterName, machineName)\n}\n<commit_msg>Timeout in Dial<commit_after>package dialer\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n\n\t\"github.com\/rancher\/rancher\/pkg\/encryptedstore\"\n\t\"github.com\/rancher\/rancher\/pkg\/nodeconfig\"\n\t\"github.com\/rancher\/rancher\/pkg\/remotedialer\"\n\t\"github.com\/rancher\/rancher\/pkg\/tunnelserver\"\n\t\"github.com\/rancher\/types\/apis\/management.cattle.io\/v3\"\n\t\"github.com\/rancher\/types\/config\"\n\t\"github.com\/rancher\/types\/config\/dialer\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n)\n\nfunc NewFactory(apiContext *config.ScaledContext) (dialer.Factory, error) {\n\tauthorizer := tunnelserver.NewAuthorizer(apiContext)\n\ttunneler := tunnelserver.NewTunnelServer(apiContext, authorizer)\n\n\tsecretStore, err := nodeconfig.NewStore(apiContext.Core.Namespaces(\"\"), apiContext.K8sClient.CoreV1())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiContext.Management.Nodes(\"local\").Controller().Informer().AddIndexers(cache.Indexers{\n\t\tnodeAccessIndexer: nodeIndexer,\n\t})\n\n\treturn &Factory{\n\t\tclusterLister:       apiContext.Management.Clusters(\"\").Controller().Lister(),\n\t\tlocalNodeController: apiContext.Management.Nodes(\"local\").Controller(),\n\t\tnodeLister:          apiContext.Management.Nodes(\"\").Controller().Lister(),\n\t\tTunnelServer:        tunneler,\n\t\tTunnelAuthorizer:    authorizer,\n\t\tstore:               secretStore,\n\t}, nil\n}\n\ntype Factory struct {\n\tlocalNodeController v3.NodeController\n\tnodeLister          v3.NodeLister\n\tclusterLister       v3.ClusterLister\n\tTunnelServer        *remotedialer.Server\n\tTunnelAuthorizer    *tunnelserver.Authorizer\n\tstore               *encryptedstore.GenericEncryptedStore\n}\n\nfunc (f *Factory) ClusterDialer(clusterName string) (dialer.Dialer, error) {\n\treturn func(network, address string) (net.Conn, error) {\n\t\td, err := f.clusterDialer(clusterName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn d(network, address)\n\t}, nil\n}\n\nfunc (f *Factory) clusterDialer(clusterName string) (dialer.Dialer, error) {\n\tcluster, err := f.clusterLister.Get(\"\", clusterName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif f.TunnelServer.HasSession(cluster.Name) {\n\t\treturn f.TunnelServer.Dialer(cluster.Name, 15*time.Second), nil\n\t}\n\n\tnodes, err := f.nodeLister.List(cluster.Name, labels.Everything())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, node := range nodes {\n\t\tif node.DeletionTimestamp == nil && v3.NodeConditionProvisioned.IsTrue(node) {\n\t\t\tif nodeDialer, err := f.nodeDialer(clusterName, node.Name); err == nil {\n\t\t\t\treturn nodeDialer, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn func(network, address string) (net.Conn, error) {\n\t\treturn net.DialTimeout(network, address, 30*time.Second)\n\t}, nil\n}\n\nfunc (f *Factory) DockerDialer(clusterName, machineName string) (dialer.Dialer, error) {\n\tmachine, err := f.nodeLister.Get(clusterName, machineName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif f.TunnelServer.HasSession(machine.Name) {\n\t\td := f.TunnelServer.Dialer(machine.Name, 15*time.Second)\n\t\treturn func(string, string) (net.Conn, error) {\n\t\t\treturn d(\"unix\", \"\/var\/run\/docker.sock\")\n\t\t}, nil\n\t}\n\n\tif machine.Spec.CustomConfig != nil && machine.Spec.CustomConfig.Address != \"\" && machine.Spec.CustomConfig.SSHKey != \"\" {\n\t\treturn f.sshDialer(machine)\n\t}\n\n\tif machine.Spec.NodeTemplateName != \"\" {\n\t\treturn f.tlsDialer(machine)\n\t}\n\n\treturn nil, fmt.Errorf(\"can not build dialer to %s:%s\", clusterName, machineName)\n}\n\nfunc (f *Factory) NodeDialer(clusterName, machineName string) (dialer.Dialer, error) {\n\treturn func(network, address string) (net.Conn, error) {\n\t\td, err := f.nodeDialer(clusterName, machineName)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn d(network, address)\n\t}, nil\n}\n\nfunc (f *Factory) nodeDialer(clusterName, machineName string) (dialer.Dialer, error) {\n\tmachine, err := f.nodeLister.Get(clusterName, machineName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif f.TunnelServer.HasSession(machine.Name) {\n\t\td := f.TunnelServer.Dialer(machine.Name, 15*time.Second)\n\t\treturn dialer.Dialer(d), nil\n\t}\n\n\tif machine.Spec.CustomConfig != nil && machine.Spec.CustomConfig.Address != \"\" && machine.Spec.CustomConfig.SSHKey != \"\" {\n\t\treturn f.sshLocalDialer(machine)\n\t}\n\n\tif machine.Spec.NodeTemplateName != \"\" {\n\t\treturn f.sshLocalDialer(machine)\n\t}\n\n\treturn nil, fmt.Errorf(\"can not build dialer to %s:%s\", clusterName, machineName)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 The etcd Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build !windows\n\npackage logutil\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/coreos\/go-systemd\/journal\"\n\t\"go.uber.org\/zap\/zapcore\"\n)\n\n\/\/ NewJournaldWriter wraps \"io.Writer\" to redirect log output\n\/\/ to the local systemd journal. If journald send fails, it fails\n\/\/ back to writing to the original writer.\n\/\/ The decode overhead is only <30µs per write.\n\/\/ Reference: https:\/\/github.com\/coreos\/pkg\/blob\/master\/capnslog\/journald_formatter.go\nfunc NewJournaldWriter(wr io.Writer) io.Writer {\n\treturn &journaldWriter{Writer: wr}\n}\n\ntype journaldWriter struct {\n\tio.Writer\n}\n\n\/\/ WARN: assume that etcd uses default field names in zap encoder config\n\/\/ make sure to keep this up-to-date!\ntype logLine struct {\n\tLevel  string `json:\"level\"`\n\tCaller string `json:\"caller\"`\n}\n\nfunc (w *journaldWriter) Write(p []byte) (int, error) {\n\tline := &logLine{}\n\tif err := json.NewDecoder(bytes.NewReader(p)).Decode(line); err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar pri journal.Priority\n\tswitch line.Level {\n\tcase zapcore.DebugLevel.String():\n\t\tpri = journal.PriDebug\n\tcase zapcore.InfoLevel.String():\n\t\tpri = journal.PriInfo\n\n\tcase zapcore.WarnLevel.String():\n\t\tpri = journal.PriWarning\n\tcase zapcore.ErrorLevel.String():\n\t\tpri = journal.PriErr\n\n\tcase zapcore.DPanicLevel.String():\n\t\tpri = journal.PriCrit\n\tcase zapcore.PanicLevel.String():\n\t\tpri = journal.PriCrit\n\tcase zapcore.FatalLevel.String():\n\t\tpri = journal.PriCrit\n\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown log level: %q\", line.Level))\n\t}\n\n\terr := journal.Send(string(p), pri, map[string]string{\n\t\t\"PACKAGE\":           filepath.Dir(line.Caller),\n\t\t\"SYSLOG_IDENTIFIER\": filepath.Base(os.Args[0]),\n\t})\n\tif err != nil {\n\t\tfmt.Println(\"FAILED TO WRITE TO JOURNALD\", err, string(p))\n\t\treturn w.Writer.Write(p)\n\t}\n\treturn 0, nil\n}\n<commit_msg>pkg\/logutil: do not print error message on journaldWriter<commit_after>\/\/ Copyright 2018 The etcd Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build !windows\n\npackage logutil\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/coreos\/go-systemd\/journal\"\n\t\"go.uber.org\/zap\/zapcore\"\n)\n\n\/\/ NewJournaldWriter wraps \"io.Writer\" to redirect log output\n\/\/ to the local systemd journal. If journald send fails, it fails\n\/\/ back to writing to the original writer.\n\/\/ The decode overhead is only <30µs per write.\n\/\/ Reference: https:\/\/github.com\/coreos\/pkg\/blob\/master\/capnslog\/journald_formatter.go\nfunc NewJournaldWriter(wr io.Writer) io.Writer {\n\treturn &journaldWriter{Writer: wr}\n}\n\ntype journaldWriter struct {\n\tio.Writer\n}\n\n\/\/ WARN: assume that etcd uses default field names in zap encoder config\n\/\/ make sure to keep this up-to-date!\ntype logLine struct {\n\tLevel  string `json:\"level\"`\n\tCaller string `json:\"caller\"`\n}\n\nfunc (w *journaldWriter) Write(p []byte) (int, error) {\n\tline := &logLine{}\n\tif err := json.NewDecoder(bytes.NewReader(p)).Decode(line); err != nil {\n\t\treturn 0, err\n\t}\n\n\tvar pri journal.Priority\n\tswitch line.Level {\n\tcase zapcore.DebugLevel.String():\n\t\tpri = journal.PriDebug\n\tcase zapcore.InfoLevel.String():\n\t\tpri = journal.PriInfo\n\n\tcase zapcore.WarnLevel.String():\n\t\tpri = journal.PriWarning\n\tcase zapcore.ErrorLevel.String():\n\t\tpri = journal.PriErr\n\n\tcase zapcore.DPanicLevel.String():\n\t\tpri = journal.PriCrit\n\tcase zapcore.PanicLevel.String():\n\t\tpri = journal.PriCrit\n\tcase zapcore.FatalLevel.String():\n\t\tpri = journal.PriCrit\n\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown log level: %q\", line.Level))\n\t}\n\n\terr := journal.Send(string(p), pri, map[string]string{\n\t\t\"PACKAGE\":           filepath.Dir(line.Caller),\n\t\t\"SYSLOG_IDENTIFIER\": filepath.Base(os.Args[0]),\n\t})\n\tif err != nil {\n\t\treturn w.Writer.Write(p)\n\t}\n\treturn 0, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/evandroflores\/claimr\/messages\"\n\t\"github.com\/evandroflores\/claimr\/model\"\n\t\"github.com\/shomali11\/slacker\"\n)\n\nfunc init() {\n\tRegister(\"remove <container-name>\", \"Removes a container from your channel.\", remove)\n}\n\nfunc remove(request *slacker.Request, response slacker.ResponseWriter) {\n\tresponse.Typing()\n\n\tevent := getEvent(request)\n\tif direct, err := isDirect(event.Channel); direct {\n\t\tresponse.Reply(err.Error())\n\t\treturn\n\t}\n\tcontainerName := request.Param(\"container-name\")\n\n\tcontainer, err := model.GetContainer(event.Team, event.Channel, containerName)\n\n\tif err != nil {\n\t\tresponse.Reply(err.Error())\n\t\treturn\n\t}\n\n\tchecks := []Check{\n\t\t{container == (model.Container{}), fmt.Sprintf(messages.Get(\"container-not-found-on-channel\"), containerName, event.Channel)},\n\t\t{container.InUseBy != \"\", fmt.Sprintf(messages.Get(\"container-in-use-by-this\"), containerName, container.InUseBy, container.UpdatedAt.Format(time.RFC1123))},\n\t\t{container.CreatedByUser != event.User, fmt.Sprintf(messages.Get(\"only-owner-can-remove\"), containerName, container.CreatedByUser)},\n\t}\n\n\terr = RunChecks(checks)\n\tif err != nil {\n\t\tresponse.Reply(err.Error())\n\t\treturn\n\t}\n\n\terr = container.Delete()\n\tif err != nil {\n\t\tresponse.Reply(err.Error())\n\t\treturn\n\t}\n\n\tresponse.Reply(fmt.Sprintf(messages.Get(\"container-removed\"), containerName))\n}\n<commit_msg>migrate cmd\/remove<commit_after>package cmd\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/evandroflores\/claimr\/messages\"\n\t\"github.com\/evandroflores\/claimr\/model\"\n\t\"github.com\/shomali11\/slacker\"\n)\n\nfunc init() {\n\tRegister(\"remove <container-name>\", \"Removes a container from your channel.\", remove)\n}\n\nfunc remove(request *slacker.Request, response slacker.ResponseWriter) {\n\tresponse.Typing()\n\n\tevent := getEvent(request)\n\tcontainerName := request.Param(\"container-name\")\n\n\terr := validateInput(event.Channel, containerName)\n\tif err != nil {\n\t\tresponse.Reply(err.Error())\n\t\treturn\n\t}\n\n\tcontainer, err := model.GetContainer(event.Team, event.Channel, containerName)\n\n\tif err != nil {\n\t\tresponse.Reply(err.Error())\n\t\treturn\n\t}\n\n\tchecks := []Check{\n\t\t{container == (model.Container{}), fmt.Sprintf(messages.Get(\"container-not-found-on-channel\"), containerName, event.Channel)},\n\t\t{container.InUseBy != \"\", fmt.Sprintf(messages.Get(\"container-in-use-by-this\"), containerName, container.InUseBy, container.UpdatedAt.Format(time.RFC1123))},\n\t\t{container.CreatedByUser != event.User, fmt.Sprintf(messages.Get(\"only-owner-can-remove\"), containerName, container.CreatedByUser)},\n\t}\n\n\terr = RunChecks(checks)\n\tif err != nil {\n\t\tresponse.Reply(err.Error())\n\t\treturn\n\t}\n\n\terr = container.Delete()\n\tif err != nil {\n\t\tresponse.Reply(err.Error())\n\t\treturn\n\t}\n\n\tresponse.Reply(fmt.Sprintf(messages.Get(\"container-removed\"), containerName))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\"\n\t\"crypto\/rand\"\n\t\"crypto\/rsa\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar testTaPriKey crypto.PrivateKey\nvar testTaPubKey crypto.PublicKey\n\nvar testTa *ta\n\nfunc init() {\n\tpriKey, err := rsa.GenerateKey(rand.Reader, 1024)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttestTaPriKey = priKey\n\ttestTaPubKey = &priKey.PublicKey\n\n\ttestTa = newTa(\n\t\t\"testta\",\n\t\t\"testtaname\",\n\t\tmap[string]bool{\n\t\t\t\"https:\/\/testta.example.org\/\":             true,\n\t\t\t\"https:\/\/testta.example.org\/redirect\/uri\": true,\n\t\t},\n\t\tmap[string]crypto.PublicKey{\n\t\t\t\"\": testTaPubKey,\n\t\t})\n\ttestTa.Upd = testTa.Upd.Add(-(time.Duration(testTa.Upd.Nanosecond()) % time.Millisecond)) \/\/ mongodb の粒度がミリ秒のため。\n}\n\nfunc testTaContainer(t *testing.T, taCont taContainer) {\n\tif ta_, err := taCont.get(testTa.id()); err != nil {\n\t\tt.Fatal(err)\n\t} else if !reflect.DeepEqual(ta_, testTa) {\n\t\tt.Error(ta_, testTa)\n\t}\n\n\tif ta_, err := taCont.get(testTa.id() + \"a\"); err != nil {\n\t\tt.Fatal(err)\n\t} else if ta_ != nil {\n\t\tt.Error(ta_)\n\t}\n}\n<commit_msg>テスト用の鍵 ID を付けた<commit_after>package main\n\nimport (\n\t\"crypto\"\n\t\"crypto\/rand\"\n\t\"crypto\/rsa\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar testTaPriKey crypto.PrivateKey\nvar testTaPubKey crypto.PublicKey\nvar testTaKid = \"testkey\"\n\nvar testTa *ta\n\nfunc init() {\n\tpriKey, err := rsa.GenerateKey(rand.Reader, 1024)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttestTaPriKey = priKey\n\ttestTaPubKey = &priKey.PublicKey\n\n\ttestTa = newTa(\n\t\t\"testta\",\n\t\t\"testtaname\",\n\t\tmap[string]bool{\n\t\t\t\"https:\/\/testta.example.org\/\":             true,\n\t\t\t\"https:\/\/testta.example.org\/redirect\/uri\": true,\n\t\t},\n\t\tmap[string]crypto.PublicKey{\n\t\t\ttestTaKid: testTaPubKey,\n\t\t})\n\ttestTa.Upd = testTa.Upd.Add(-(time.Duration(testTa.Upd.Nanosecond()) % time.Millisecond)) \/\/ mongodb の粒度がミリ秒のため。\n}\n\nfunc testTaContainer(t *testing.T, taCont taContainer) {\n\tif ta_, err := taCont.get(testTa.id()); err != nil {\n\t\tt.Fatal(err)\n\t} else if !reflect.DeepEqual(ta_, testTa) {\n\t\tt.Error(ta_, testTa)\n\t}\n\n\tif ta_, err := taCont.get(testTa.id() + \"a\"); err != nil {\n\t\tt.Fatal(err)\n\t} else if ta_ != nil {\n\t\tt.Error(ta_)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package mapping\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"os\"\n\n\t\"github.com\/omniscale\/imposm3\/element\"\n)\n\ntype Field struct {\n\tName string                 `json:\"name\"`\n\tKey  Key                    `json:\"key\"`\n\tType string                 `json:\"type\"`\n\tArgs map[string]interface{} `json:\"args\"`\n}\n\ntype Table struct {\n\tName         string\n\tType         TableType             `json:\"type\"`\n\tMapping      map[Key][]Value       `json:\"mapping\"`\n\tMappings     map[string]SubMapping `json:\"mappings\"`\n\tTypeMappings TypeMappings          `json:\"type_mappings\"`\n\tFields       []*Field              `json:\"columns\"`\n\tOldFields    []*Field              `json:\"fields\"`\n\tFilters      *Filters              `json:\"filters\"`\n}\n\ntype GeneralizedTable struct {\n\tName            string\n\tSourceTableName string  `json:\"source\"`\n\tTolerance       float64 `json:\"tolerance\"`\n\tSqlFilter       string  `json:\"sql_filter\"`\n}\n\ntype Filters struct {\n\tExcludeTags *[][2]string `json:\"exclude_tags\"`\n}\n\ntype Tables map[string]*Table\n\ntype GeneralizedTables map[string]*GeneralizedTable\n\ntype Mapping struct {\n\tTables            Tables            `json:\"tables\"`\n\tGeneralizedTables GeneralizedTables `json:\"generalized_tables\"`\n\tTags              Tags              `json:\"tags\"`\n\t\/\/ SingleIdSpace mangles the overlapping node\/way\/relation IDs\n\t\/\/ to be unique (nodes positive, ways negative, relations negative -1e17)\n\tSingleIdSpace bool `json:\"use_single_id_space\"`\n}\n\ntype Tags struct {\n\tLoadAll bool  `json:\"load_all\"`\n\tExclude []Key `json:\"exclude\"`\n}\n\ntype SubMapping struct {\n\tMapping map[Key][]Value\n}\n\ntype TypeMappings struct {\n\tPoints      map[Key][]Value `json:\"points\"`\n\tLineStrings map[Key][]Value `json:\"linestrings\"`\n\tPolygons    map[Key][]Value `json:\"polygons\"`\n}\n\ntype ElementFilter func(tags *element.Tags) bool\n\ntype TagTables map[Key]map[Value][]DestTable\n\ntype DestTable struct {\n\tName       string\n\tSubMapping string\n}\n\ntype TableType string\n\nfunc (tt *TableType) UnmarshalJSON(data []byte) error {\n\tswitch string(data) {\n\tcase \"\":\n\t\treturn errors.New(\"missing table type\")\n\tcase `\"point\"`:\n\t\t*tt = PointTable\n\tcase `\"linestring\"`:\n\t\t*tt = LineStringTable\n\tcase `\"polygon\"`:\n\t\t*tt = PolygonTable\n\tcase `\"geometry\"`:\n\t\t*tt = GeometryTable\n\tdefault:\n\t\treturn errors.New(\"unknown type \" + string(data))\n\t}\n\treturn nil\n}\n\nconst (\n\tPolygonTable    TableType = \"polygon\"\n\tLineStringTable TableType = \"linestring\"\n\tPointTable      TableType = \"point\"\n\tGeometryTable   TableType = \"geometry\"\n)\n\nfunc NewMapping(filename string) (*Mapping, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tdecoder := json.NewDecoder(f)\n\n\tmapping := Mapping{}\n\terr = decoder.Decode(&mapping)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = mapping.prepare()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &mapping, nil\n}\n\nfunc (t *Table) ExtraTags() map[Key]bool {\n\ttags := make(map[Key]bool)\n\tfor _, field := range t.Fields {\n\t\tif field.Key != \"\" {\n\t\t\ttags[field.Key] = true\n\t\t}\n\t}\n\treturn tags\n}\n\nfunc (m *Mapping) prepare() error {\n\tfor name, t := range m.Tables {\n\t\tt.Name = name\n\t\tif t.OldFields != nil {\n\t\t\t\/\/ todo deprecate 'fields'\n\t\t\tt.Fields = t.OldFields\n\t\t}\n\t}\n\n\tfor name, t := range m.GeneralizedTables {\n\t\tt.Name = name\n\t}\n\treturn nil\n}\n\nfunc (tt TagTables) addFromMapping(mapping map[Key][]Value, table DestTable) {\n\tfor key, vals := range mapping {\n\t\tfor _, v := range vals {\n\t\t\tvals, ok := tt[key]\n\t\t\tif ok {\n\t\t\t\tvals[v] = append(vals[v], table)\n\t\t\t} else {\n\t\t\t\ttt[key] = make(map[Value][]DestTable)\n\t\t\t\ttt[key][v] = append(tt[key][v], table)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Mapping) mappings(tableType TableType, mappings TagTables) {\n\tfor name, t := range m.Tables {\n\t\tif t.Type != GeometryTable && t.Type != tableType {\n\t\t\tcontinue\n\t\t}\n\t\tmappings.addFromMapping(t.Mapping, DestTable{name, \"\"})\n\n\t\tfor subMappingName, subMapping := range t.Mappings {\n\t\t\tmappings.addFromMapping(subMapping.Mapping, DestTable{name, subMappingName})\n\t\t}\n\n\t\tswitch tableType {\n\t\tcase PointTable:\n\t\t\tmappings.addFromMapping(t.TypeMappings.Points, DestTable{name, \"\"})\n\t\tcase LineStringTable:\n\t\t\tmappings.addFromMapping(t.TypeMappings.LineStrings, DestTable{name, \"\"})\n\t\tcase PolygonTable:\n\t\t\tmappings.addFromMapping(t.TypeMappings.Polygons, DestTable{name, \"\"})\n\t\t}\n\t}\n}\n\nfunc (m *Mapping) tables(tableType TableType) map[string]*TableFields {\n\tresult := make(map[string]*TableFields)\n\tfor name, t := range m.Tables {\n\t\tif t.Type == tableType || t.Type == \"geometry\" {\n\t\t\tresult[name] = t.TableFields()\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (m *Mapping) extraTags(tableType TableType, tags map[Key]bool) {\n\tfor _, t := range m.Tables {\n\t\tif t.Type != tableType {\n\t\t\tcontinue\n\t\t}\n\t\tfor key, _ := range t.ExtraTags() {\n\t\t\ttags[key] = true\n\t\t}\n\t\tif t.Filters != nil && t.Filters.ExcludeTags != nil {\n\t\t\tfor _, keyVal := range *t.Filters.ExcludeTags {\n\t\t\t\ttags[Key(keyVal[0])] = true\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Mapping) ElementFilters() map[string][]ElementFilter {\n\tresult := make(map[string][]ElementFilter)\n\tfor name, t := range m.Tables {\n\t\tif t.Filters == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif t.Filters.ExcludeTags != nil {\n\t\t\tfor _, filterKeyVal := range *t.Filters.ExcludeTags {\n\t\t\t\tf := func(tags *element.Tags) bool {\n\t\t\t\t\tif v, ok := (*tags)[filterKeyVal[0]]; ok {\n\t\t\t\t\t\tif filterKeyVal[1] == \"__any__\" || v == filterKeyVal[1] {\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\tresult[name] = append(result[name], f)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n<commit_msg>add TODO note<commit_after>package mapping\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"os\"\n\n\t\"github.com\/omniscale\/imposm3\/element\"\n)\n\ntype Field struct {\n\tName string                 `json:\"name\"`\n\tKey  Key                    `json:\"key\"`\n\tType string                 `json:\"type\"`\n\tArgs map[string]interface{} `json:\"args\"`\n}\n\ntype Table struct {\n\tName         string\n\tType         TableType             `json:\"type\"`\n\tMapping      map[Key][]Value       `json:\"mapping\"`\n\tMappings     map[string]SubMapping `json:\"mappings\"`\n\tTypeMappings TypeMappings          `json:\"type_mappings\"`\n\tFields       []*Field              `json:\"columns\"` \/\/ TODO rename Fields internaly to Columns\n\tOldFields    []*Field              `json:\"fields\"`\n\tFilters      *Filters              `json:\"filters\"`\n}\n\ntype GeneralizedTable struct {\n\tName            string\n\tSourceTableName string  `json:\"source\"`\n\tTolerance       float64 `json:\"tolerance\"`\n\tSqlFilter       string  `json:\"sql_filter\"`\n}\n\ntype Filters struct {\n\tExcludeTags *[][2]string `json:\"exclude_tags\"`\n}\n\ntype Tables map[string]*Table\n\ntype GeneralizedTables map[string]*GeneralizedTable\n\ntype Mapping struct {\n\tTables            Tables            `json:\"tables\"`\n\tGeneralizedTables GeneralizedTables `json:\"generalized_tables\"`\n\tTags              Tags              `json:\"tags\"`\n\t\/\/ SingleIdSpace mangles the overlapping node\/way\/relation IDs\n\t\/\/ to be unique (nodes positive, ways negative, relations negative -1e17)\n\tSingleIdSpace bool `json:\"use_single_id_space\"`\n}\n\ntype Tags struct {\n\tLoadAll bool  `json:\"load_all\"`\n\tExclude []Key `json:\"exclude\"`\n}\n\ntype SubMapping struct {\n\tMapping map[Key][]Value\n}\n\ntype TypeMappings struct {\n\tPoints      map[Key][]Value `json:\"points\"`\n\tLineStrings map[Key][]Value `json:\"linestrings\"`\n\tPolygons    map[Key][]Value `json:\"polygons\"`\n}\n\ntype ElementFilter func(tags *element.Tags) bool\n\ntype TagTables map[Key]map[Value][]DestTable\n\ntype DestTable struct {\n\tName       string\n\tSubMapping string\n}\n\ntype TableType string\n\nfunc (tt *TableType) UnmarshalJSON(data []byte) error {\n\tswitch string(data) {\n\tcase \"\":\n\t\treturn errors.New(\"missing table type\")\n\tcase `\"point\"`:\n\t\t*tt = PointTable\n\tcase `\"linestring\"`:\n\t\t*tt = LineStringTable\n\tcase `\"polygon\"`:\n\t\t*tt = PolygonTable\n\tcase `\"geometry\"`:\n\t\t*tt = GeometryTable\n\tdefault:\n\t\treturn errors.New(\"unknown type \" + string(data))\n\t}\n\treturn nil\n}\n\nconst (\n\tPolygonTable    TableType = \"polygon\"\n\tLineStringTable TableType = \"linestring\"\n\tPointTable      TableType = \"point\"\n\tGeometryTable   TableType = \"geometry\"\n)\n\nfunc NewMapping(filename string) (*Mapping, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tdecoder := json.NewDecoder(f)\n\n\tmapping := Mapping{}\n\terr = decoder.Decode(&mapping)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = mapping.prepare()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &mapping, nil\n}\n\nfunc (t *Table) ExtraTags() map[Key]bool {\n\ttags := make(map[Key]bool)\n\tfor _, field := range t.Fields {\n\t\tif field.Key != \"\" {\n\t\t\ttags[field.Key] = true\n\t\t}\n\t}\n\treturn tags\n}\n\nfunc (m *Mapping) prepare() error {\n\tfor name, t := range m.Tables {\n\t\tt.Name = name\n\t\tif t.OldFields != nil {\n\t\t\t\/\/ todo deprecate 'fields'\n\t\t\tt.Fields = t.OldFields\n\t\t}\n\t}\n\n\tfor name, t := range m.GeneralizedTables {\n\t\tt.Name = name\n\t}\n\treturn nil\n}\n\nfunc (tt TagTables) addFromMapping(mapping map[Key][]Value, table DestTable) {\n\tfor key, vals := range mapping {\n\t\tfor _, v := range vals {\n\t\t\tvals, ok := tt[key]\n\t\t\tif ok {\n\t\t\t\tvals[v] = append(vals[v], table)\n\t\t\t} else {\n\t\t\t\ttt[key] = make(map[Value][]DestTable)\n\t\t\t\ttt[key][v] = append(tt[key][v], table)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Mapping) mappings(tableType TableType, mappings TagTables) {\n\tfor name, t := range m.Tables {\n\t\tif t.Type != GeometryTable && t.Type != tableType {\n\t\t\tcontinue\n\t\t}\n\t\tmappings.addFromMapping(t.Mapping, DestTable{name, \"\"})\n\n\t\tfor subMappingName, subMapping := range t.Mappings {\n\t\t\tmappings.addFromMapping(subMapping.Mapping, DestTable{name, subMappingName})\n\t\t}\n\n\t\tswitch tableType {\n\t\tcase PointTable:\n\t\t\tmappings.addFromMapping(t.TypeMappings.Points, DestTable{name, \"\"})\n\t\tcase LineStringTable:\n\t\t\tmappings.addFromMapping(t.TypeMappings.LineStrings, DestTable{name, \"\"})\n\t\tcase PolygonTable:\n\t\t\tmappings.addFromMapping(t.TypeMappings.Polygons, DestTable{name, \"\"})\n\t\t}\n\t}\n}\n\nfunc (m *Mapping) tables(tableType TableType) map[string]*TableFields {\n\tresult := make(map[string]*TableFields)\n\tfor name, t := range m.Tables {\n\t\tif t.Type == tableType || t.Type == \"geometry\" {\n\t\t\tresult[name] = t.TableFields()\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (m *Mapping) extraTags(tableType TableType, tags map[Key]bool) {\n\tfor _, t := range m.Tables {\n\t\tif t.Type != tableType {\n\t\t\tcontinue\n\t\t}\n\t\tfor key, _ := range t.ExtraTags() {\n\t\t\ttags[key] = true\n\t\t}\n\t\tif t.Filters != nil && t.Filters.ExcludeTags != nil {\n\t\t\tfor _, keyVal := range *t.Filters.ExcludeTags {\n\t\t\t\ttags[Key(keyVal[0])] = true\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *Mapping) ElementFilters() map[string][]ElementFilter {\n\tresult := make(map[string][]ElementFilter)\n\tfor name, t := range m.Tables {\n\t\tif t.Filters == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif t.Filters.ExcludeTags != nil {\n\t\t\tfor _, filterKeyVal := range *t.Filters.ExcludeTags {\n\t\t\t\tf := func(tags *element.Tags) bool {\n\t\t\t\t\tif v, ok := (*tags)[filterKeyVal[0]]; ok {\n\t\t\t\t\t\tif filterKeyVal[1] == \"__any__\" || v == filterKeyVal[1] {\n\t\t\t\t\t\t\treturn false\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t\tresult[name] = append(result[name], f)\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n<|endoftext|>"}
{"text":"<commit_before>package commands\n\nimport (\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/github\/hub\/github\"\n\t\"github.com\/github\/hub\/utils\"\n)\n\nvar cmdClone = &Command{\n\tRun:          clone,\n\tGitExtension: true,\n\tUsage:        \"clone [-p] OPTIONS [USER\/]REPOSITORY DIRECTORY\",\n\tShort:        \"Clone a remote repository into a new directory\",\n\tLong: `Clone repository \"git:\/\/github.com\/USER\/REPOSITORY.git\" into\nDIRECTORY as with git-clone(1). When USER\/ is omitted, assumes\nyour GitHub login. With -p, clone private repositories over SSH.\nFor repositories under your GitHub login, -p is implicit.\n`,\n}\n\nfunc init() {\n\tCmdRunner.Use(cmdClone)\n}\n\n\/**\n  $ gh clone jingweno\/gh\n  > git clone git:\/\/github.com\/jingweno\/gh.git\n\n  $ gh clone -p jingweno\/gh\n  > git clone git@github.com:jingweno\/gh.git\n\n  $ gh clone jekyll_and_hyde\n  > git clone git:\/\/github.com\/YOUR_LOGIN\/jekyll_and_hyde.git\n\n  $ gh clone -p jekyll_and_hyde\n  > git clone git@github.com:YOUR_LOGIN\/jekyll_and_hyde.git\n*\/\nfunc clone(command *Command, args *Args) {\n\tif !args.IsParamsEmpty() {\n\t\ttransformCloneArgs(args)\n\t}\n}\n\nfunc transformCloneArgs(args *Args) {\n\tisSSH := parseClonePrivateFlag(args)\n\thasValueRegxp := regexp.MustCompile(\"^(--(upload-pack|template|depth|origin|branch|reference|name)|-[ubo])$\")\n\tnameWithOwnerRegexp := regexp.MustCompile(NameWithOwnerRe)\n\tfor i := 0; i < args.ParamsSize(); i++ {\n\t\ta := args.Params[i]\n\n\t\tif strings.HasPrefix(a, \"-\") {\n\t\t\tif hasValueRegxp.MatchString(a) {\n\t\t\t\ti++\n\t\t\t}\n\t\t} else {\n\t\t\tif nameWithOwnerRegexp.MatchString(a) && !isDir(a) {\n\t\t\t\tname, owner := parseCloneNameAndOwner(a)\n\t\t\t\tvar host *github.Host\n\t\t\t\tif owner == \"\" {\n\t\t\t\t\tconfigs := github.CurrentConfigs()\n\t\t\t\t\th, err := configs.DefaultHost()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tutils.Check(github.FormatError(\"cloning repository\", err))\n\t\t\t\t\t}\n\n\t\t\t\t\thost = h\n\t\t\t\t\towner = host.User\n\t\t\t\t}\n\n\t\t\t\tvar hostStr string\n\t\t\t\tif host != nil {\n\t\t\t\t\thostStr = host.Host\n\t\t\t\t}\n\n\t\t\t\tproject := github.NewProject(owner, name, hostStr)\n\t\t\t\tif !isSSH &&\n\t\t\t\t\targs.Command != \"submodule\" &&\n\t\t\t\t\t!args.Noop &&\n\t\t\t\t\t!github.IsHttpsProtocol() {\n\t\t\t\t\tclient := github.NewClient(project.Host)\n\t\t\t\t\trepo, err := client.Repository(project)\n\t\t\t\t\tisSSH = (err == nil) && (repo.Private || repo.Permissions.Push)\n\t\t\t\t}\n\n\t\t\t\turl := project.GitURL(name, owner, isSSH)\n\t\t\t\targs.ReplaceParam(i, url)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc parseClonePrivateFlag(args *Args) bool {\n\tif i := args.IndexOfParam(\"-p\"); i != -1 {\n\t\targs.RemoveParam(i)\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc parseCloneNameAndOwner(arg string) (name, owner string) {\n\tname, owner = arg, \"\"\n\tif strings.Contains(arg, \"\/\") {\n\t\tsplit := strings.SplitN(arg, \"\/\", 2)\n\t\tname = split[1]\n\t\towner = split[0]\n\t}\n\n\treturn\n}\n<commit_msg>Clone with noop still works<commit_after>package commands\n\nimport (\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/github\/hub\/github\"\n\t\"github.com\/github\/hub\/utils\"\n)\n\nvar cmdClone = &Command{\n\tRun:          clone,\n\tGitExtension: true,\n\tUsage:        \"clone [-p] OPTIONS [USER\/]REPOSITORY DIRECTORY\",\n\tShort:        \"Clone a remote repository into a new directory\",\n\tLong: `Clone repository \"git:\/\/github.com\/USER\/REPOSITORY.git\" into\nDIRECTORY as with git-clone(1). When USER\/ is omitted, assumes\nyour GitHub login. With -p, clone private repositories over SSH.\nFor repositories under your GitHub login, -p is implicit.\n`,\n}\n\nfunc init() {\n\tCmdRunner.Use(cmdClone)\n}\n\n\/**\n  $ gh clone jingweno\/gh\n  > git clone git:\/\/github.com\/jingweno\/gh.git\n\n  $ gh clone -p jingweno\/gh\n  > git clone git@github.com:jingweno\/gh.git\n\n  $ gh clone jekyll_and_hyde\n  > git clone git:\/\/github.com\/YOUR_LOGIN\/jekyll_and_hyde.git\n\n  $ gh clone -p jekyll_and_hyde\n  > git clone git@github.com:YOUR_LOGIN\/jekyll_and_hyde.git\n*\/\nfunc clone(command *Command, args *Args) {\n\tif !args.IsParamsEmpty() {\n\t\ttransformCloneArgs(args)\n\t}\n}\n\nfunc transformCloneArgs(args *Args) {\n\tisSSH := parseClonePrivateFlag(args)\n\thasValueRegxp := regexp.MustCompile(\"^(--(upload-pack|template|depth|origin|branch|reference|name)|-[ubo])$\")\n\tnameWithOwnerRegexp := regexp.MustCompile(NameWithOwnerRe)\n\tfor i := 0; i < args.ParamsSize(); i++ {\n\t\ta := args.Params[i]\n\n\t\tif strings.HasPrefix(a, \"-\") {\n\t\t\tif hasValueRegxp.MatchString(a) {\n\t\t\t\ti++\n\t\t\t}\n\t\t} else {\n\t\t\tif nameWithOwnerRegexp.MatchString(a) && !isDir(a) {\n\t\t\t\tname, owner := parseCloneNameAndOwner(a)\n\t\t\t\tvar host *github.Host\n\t\t\t\tif owner == \"\" {\n\t\t\t\t\tconfigs := github.CurrentConfigs()\n\t\t\t\t\th, err := configs.DefaultHost()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tutils.Check(github.FormatError(\"cloning repository\", err))\n\t\t\t\t\t}\n\n\t\t\t\t\thost = h\n\t\t\t\t\towner = host.User\n\t\t\t\t}\n\n\t\t\t\tvar hostStr string\n\t\t\t\tif host != nil {\n\t\t\t\t\thostStr = host.Host\n\t\t\t\t}\n\n\t\t\t\tproject := github.NewProject(owner, name, hostStr)\n\t\t\t\tif !isSSH &&\n\t\t\t\t\targs.Command != \"submodule\" &&\n\t\t\t\t\t!github.IsHttpsProtocol() {\n\t\t\t\t\tclient := github.NewClient(project.Host)\n\t\t\t\t\trepo, err := client.Repository(project)\n\t\t\t\t\tisSSH = (err == nil) && (repo.Private || repo.Permissions.Push)\n\t\t\t\t}\n\n\t\t\t\turl := project.GitURL(name, owner, isSSH)\n\t\t\t\targs.ReplaceParam(i, url)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc parseClonePrivateFlag(args *Args) bool {\n\tif i := args.IndexOfParam(\"-p\"); i != -1 {\n\t\targs.RemoveParam(i)\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc parseCloneNameAndOwner(arg string) (name, owner string) {\n\tname, owner = arg, \"\"\n\tif strings.Contains(arg, \"\/\") {\n\t\tsplit := strings.SplitN(arg, \"\/\", 2)\n\t\tname = split[1]\n\t\towner = split[0]\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package clc\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\n\t\"github.com\/mikebeyer\/env\"\n)\n\ntype Config struct {\n\tUser    User\n\tAlias   string\n\tBaseURL string\n}\n\nfunc EnvConfig() Config {\n\treturn Config{\n\t\tUser: User{\n\t\t\tUsername: env.MustString(\"CLC_USERNAME\"),\n\t\t\tPassword: env.MustString(\"CLC_PASSWORD\"),\n\t\t},\n\t\tAlias:   env.MustString(\"CLC_ALIAS\"),\n\t\tBaseURL: env.String(\"CLC_BASE_URL\", \"https:\/\/api.ctl.io\/v2\"),\n\t}\n}\n\ntype Client struct {\n\tconfig  Config\n\tclient  *http.Client\n\tbaseURL string\n}\n\nfunc New(config Config) *Client {\n\turl := config.BaseURL\n\tif url == \"\" {\n\t\turl = \"https:\/\/api.ctl.io\/v2\"\n\t}\n\treturn &Client{\n\t\tconfig:  config,\n\t\tclient:  http.DefaultClient,\n\t\tbaseURL: url,\n\t}\n}\n\nfunc (c *Client) Auth() (string, error) {\n\turl := fmt.Sprintf(\"%s\/authentication\/login\", c.baseURL)\n\tb, err := json.Marshal(&c.config.User)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresp, err := http.Post(url, \"application\/json\", ioutil.NopCloser(bytes.NewReader(b)))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tauth := &Auth{}\n\tif err := json.NewDecoder(resp.Body).Decode(auth); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn auth.Token, nil\n}\n\nfunc (c *Client) get(url string, resp interface{}) error {\n\treturn c.do(\"GET\", url, nil, resp)\n}\n\nfunc (c *Client) do(method, url string, body io.Reader, resp interface{}) error {\n\treq, err := http.NewRequest(method, url, body)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.NewDecoder(res.Body).Decode(resp)\n}\n\ntype User struct {\n\tUsername string `json:\"username\"`\n\tPassword string `json:\"password\"`\n}\n\ntype Auth struct {\n\tUsername string   `json:\"userName\"`\n\tAlias    string   `json:\"accountAlias\"`\n\tLocation string   `json:\"locationAlias\"`\n\tRoles    []string `json:\"roles\"`\n\tToken    string   `json:\"bearerToken\"`\n}\n<commit_msg>evaluate server response for non-success error codes<commit_after>package clc\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\n\t\"github.com\/mikebeyer\/env\"\n)\n\ntype Config struct {\n\tUser    User\n\tAlias   string\n\tBaseURL string\n}\n\nfunc EnvConfig() Config {\n\treturn Config{\n\t\tUser: User{\n\t\t\tUsername: env.MustString(\"CLC_USERNAME\"),\n\t\t\tPassword: env.MustString(\"CLC_PASSWORD\"),\n\t\t},\n\t\tAlias:   env.MustString(\"CLC_ALIAS\"),\n\t\tBaseURL: env.String(\"CLC_BASE_URL\", \"https:\/\/api.ctl.io\/v2\"),\n\t}\n}\n\ntype Client struct {\n\tconfig  Config\n\tclient  *http.Client\n\tbaseURL string\n}\n\nfunc New(config Config) *Client {\n\turl := config.BaseURL\n\tif url == \"\" {\n\t\turl = \"https:\/\/api.ctl.io\/v2\"\n\t}\n\treturn &Client{\n\t\tconfig:  config,\n\t\tclient:  http.DefaultClient,\n\t\tbaseURL: url,\n\t}\n}\n\nfunc (c *Client) Auth() (string, error) {\n\turl := fmt.Sprintf(\"%s\/authentication\/login\", c.baseURL)\n\tb, err := json.Marshal(&c.config.User)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresp, err := http.Post(url, \"application\/json\", ioutil.NopCloser(bytes.NewReader(b)))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tauth := &Auth{}\n\tif err := json.NewDecoder(resp.Body).Decode(auth); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn auth.Token, nil\n}\n\nfunc (c *Client) get(url string, resp interface{}) error {\n\treturn c.do(\"GET\", url, nil, resp)\n}\n\nfunc (c *Client) do(method, url string, body io.Reader, resp interface{}) error {\n\treq, err := http.NewRequest(method, url, body)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\tres, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif res.StatusCode >= 300 {\n\t\treturn errors.New(fmt.Sprintf(\"http error: %s\", res.Status))\n\t}\n\n\treturn json.NewDecoder(res.Body).Decode(resp)\n}\n\ntype User struct {\n\tUsername string `json:\"username\"`\n\tPassword string `json:\"password\"`\n}\n\ntype Auth struct {\n\tUsername string   `json:\"userName\"`\n\tAlias    string   `json:\"accountAlias\"`\n\tLocation string   `json:\"locationAlias\"`\n\tRoles    []string `json:\"roles\"`\n\tToken    string   `json:\"bearerToken\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\n\/\/ WriteDemoConfig writes a toml file with the given values.\n\/\/ It returns the RootDir the config.toml file is stored in,\n\/\/ or an error if writing was impossible\nfunc WriteDemoConfig(vals map[string]string) (string, error) {\n\tcdir, err := ioutil.TempDir(\"\", \"test-cli\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdata := \"\"\n\tfor k, v := range vals {\n\t\tdata = data + fmt.Sprintf(\"%s = \\\"%s\\\"\\n\", k, v)\n\t}\n\tcfile := filepath.Join(cdir, \"config.toml\")\n\terr = ioutil.WriteFile(cfile, []byte(data), 0666)\n\treturn cdir, err\n}\n\n\/\/ RunWithArgs executes the given command with the specified command line args\n\/\/ and environmental variables set. It returns any error returned from cmd.Execute()\nfunc RunWithArgs(cmd Executable, args []string, env map[string]string) error {\n\toargs := os.Args\n\toenv := map[string]string{}\n\t\/\/ defer returns the environment back to normal\n\tdefer func() {\n\t\tos.Args = oargs\n\t\tfor k, v := range oenv {\n\t\t\tos.Setenv(k, v)\n\t\t}\n\t}()\n\n\t\/\/ set the args and env how we want them\n\tos.Args = args\n\tfor k, v := range env {\n\t\t\/\/ backup old value if there, to restore at end\n\t\toenv[k] = os.Getenv(k)\n\t\terr := os.Setenv(k, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ and finally run the command\n\treturn cmd.Execute()\n}\n\n\/\/ RunCaptureWithArgs executes the given command with the specified command\n\/\/ line args and environmental variables set. It returns string fields\n\/\/ representing output written to stdout and stderr, additionally any error\n\/\/ from cmd.Execute() is also returned\nfunc RunCaptureWithArgs(cmd Executable, args []string, env map[string]string) (stdout, stderr string, err error) {\n\toldout, olderr := os.Stdout, os.Stderr \/\/ keep backup of the real stdout\n\trOut, wOut, _ := os.Pipe()\n\trErr, wErr, _ := os.Pipe()\n\tos.Stdout, os.Stderr = wOut, wErr\n\tdefer func() {\n\t\tos.Stdout, os.Stderr = oldout, olderr \/\/ restoring the real stdout\n\t}()\n\n\t\/\/ copy the output in a separate goroutine so printing can't block indefinitely\n\tcopyStd := func(reader *os.File) *(chan string) {\n\t\tstdC := make(chan string)\n\t\tgo func() {\n\t\t\tvar buf bytes.Buffer\n\t\t\t\/\/ io.Copy will end when we call reader.Close() below\n\t\t\tio.Copy(&buf, *reader)\n\t\t\tstdC <- buf.String()\n\t\t}()\n\t\treturn stdC\n\t}\n\toutC := copyStd(&rOut)\n\terrC := copyStd(&rErr)\n\n\t\/\/ now run the command\n\terr = RunWithArgs(cmd, args, env)\n\n\t\/\/ and grab the stdout to return\n\twOut.Close()\n\twErr.Close()\n\tstdout = <-outC\n\tstderr = <-errC\n\treturn stdout, stderr, err\n}\n<commit_msg>quickfix<commit_after>package cli\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\n\/\/ WriteDemoConfig writes a toml file with the given values.\n\/\/ It returns the RootDir the config.toml file is stored in,\n\/\/ or an error if writing was impossible\nfunc WriteDemoConfig(vals map[string]string) (string, error) {\n\tcdir, err := ioutil.TempDir(\"\", \"test-cli\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdata := \"\"\n\tfor k, v := range vals {\n\t\tdata = data + fmt.Sprintf(\"%s = \\\"%s\\\"\\n\", k, v)\n\t}\n\tcfile := filepath.Join(cdir, \"config.toml\")\n\terr = ioutil.WriteFile(cfile, []byte(data), 0666)\n\treturn cdir, err\n}\n\n\/\/ RunWithArgs executes the given command with the specified command line args\n\/\/ and environmental variables set. It returns any error returned from cmd.Execute()\nfunc RunWithArgs(cmd Executable, args []string, env map[string]string) error {\n\toargs := os.Args\n\toenv := map[string]string{}\n\t\/\/ defer returns the environment back to normal\n\tdefer func() {\n\t\tos.Args = oargs\n\t\tfor k, v := range oenv {\n\t\t\tos.Setenv(k, v)\n\t\t}\n\t}()\n\n\t\/\/ set the args and env how we want them\n\tos.Args = args\n\tfor k, v := range env {\n\t\t\/\/ backup old value if there, to restore at end\n\t\toenv[k] = os.Getenv(k)\n\t\terr := os.Setenv(k, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ and finally run the command\n\treturn cmd.Execute()\n}\n\n\/\/ RunCaptureWithArgs executes the given command with the specified command\n\/\/ line args and environmental variables set. It returns string fields\n\/\/ representing output written to stdout and stderr, additionally any error\n\/\/ from cmd.Execute() is also returned\nfunc RunCaptureWithArgs(cmd Executable, args []string, env map[string]string) (stdout, stderr string, err error) {\n\toldout, olderr := os.Stdout, os.Stderr \/\/ keep backup of the real stdout\n\trOut, wOut, _ := os.Pipe()\n\trErr, wErr, _ := os.Pipe()\n\tos.Stdout, os.Stderr = wOut, wErr\n\tdefer func() {\n\t\tos.Stdout, os.Stderr = oldout, olderr \/\/ restoring the real stdout\n\t}()\n\n\t\/\/ copy the output in a separate goroutine so printing can't block indefinitely\n\tcopyStd := func(reader *os.File) *(chan string) {\n\t\tstdC := make(chan string)\n\t\tgo func() {\n\t\t\tvar buf bytes.Buffer\n\t\t\t\/\/ io.Copy will end when we call reader.Close() below\n\t\t\tio.Copy(&buf, reader)\n\t\t\tstdC <- buf.String()\n\t\t}()\n\t\treturn &stdC\n\t}\n\toutC := copyStd(rOut)\n\terrC := copyStd(rErr)\n\n\t\/\/ now run the command\n\terr = RunWithArgs(cmd, args, env)\n\n\t\/\/ and grab the stdout to return\n\twOut.Close()\n\twErr.Close()\n\tstdout = <-*outC\n\tstderr = <-*errC\n\treturn stdout, stderr, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package kafka\n\nimport (\n\t\"github.com\/Shopify\/sarama\"\n\tlog \"github.com\/funkygao\/log4go\"\n)\n\n\/\/ Producer is a kafka producer that is transparent for sync\/async mode.\ntype Producer struct {\n\tcf      *Config\n\tname    string\n\tbrokers []string\n\tstopper chan struct{}\n\n\tp  sarama.SyncProducer\n\tap sarama.AsyncProducer\n\n\tsendMessage func(*sarama.ProducerMessage) error\n\n\tonError   func(*sarama.ProducerError)\n\tonSuccess func(*sarama.ProducerMessage)\n}\n\nfunc NewProducer(name string, brokers []string, cf *Config) *Producer {\n\tp := &Producer{\n\t\tname:    name,\n\t\tbrokers: brokers,\n\t\tcf:      cf,\n\t\tstopper: make(chan struct{}),\n\t}\n\n\treturn p\n}\n\nfunc (p *Producer) Start() error {\n\tvar err error\n\tif p.cf.async {\n\t\tp.ap, err = sarama.NewAsyncProducer(p.brokers, p.cf.Sarama)\n\t\tp.sendMessage = p.asyncSend\n\t} else {\n\t\tp.p, err = sarama.NewSyncProducer(p.brokers, p.cf.Sarama)\n\t\tp.sendMessage = p.syncSend\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !p.cf.async {\n\t\treturn nil\n\t}\n\n\tif p.onError == nil || p.onSuccess == nil {\n\t\treturn ErrNotReady\n\t}\n\n\tgo func() {\n\t\t\/\/ loop till Producer success channel closed\n\t\terrChan := p.ap.Errors()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase msg, ok := <-p.ap.Successes():\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Trace(\"[%s] success chan closed\", p.name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tp.onSuccess(msg)\n\n\t\t\tcase err, ok := <-errChan:\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Trace(\"[%s] err chan closed\", p.name)\n\t\t\t\t\terrChan = nil\n\t\t\t\t}\n\n\t\t\t\tp.onError(err)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil\n}\n\n\/\/ Close will drain and close the Producer.\nfunc (p *Producer) Close() error {\n\tclose(p.stopper)\n\n\tif p.cf.async {\n\t\tp.ap.AsyncClose()\n\n\t\t\/\/ drain successes\n\t\tif p.onSuccess != nil {\n\t\t\tfor msg := range p.ap.Successes() {\n\t\t\t\tp.onSuccess(msg)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ drain errors\n\t\tif p.onError != nil {\n\t\t\tfor err := range p.ap.Errors() {\n\t\t\t\tp.onError(err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn p.p.Close()\n}\n\nfunc (p *Producer) ClientID() string {\n\treturn p.cf.Sarama.ClientID\n}\n\nfunc (p *Producer) SetErrorHandler(f func(err *sarama.ProducerError)) error {\n\tif !p.cf.async {\n\t\treturn ErrNotAllowed\n\t}\n\n\tif f == nil {\n\t\tp.cf.Sarama.Producer.Return.Errors = false\n\t}\n\tp.onError = f\n\treturn nil\n}\n\nfunc (p *Producer) SetSuccessHandler(f func(err *sarama.ProducerMessage)) error {\n\tif !p.cf.async {\n\t\treturn ErrNotAllowed\n\t}\n\n\tif f == nil {\n\t\tp.cf.Sarama.Producer.Return.Successes = false\n\t}\n\tp.onSuccess = f\n\treturn nil\n}\n\n\/\/ Send will send a kafka message.\nfunc (p *Producer) Send(m *sarama.ProducerMessage) error {\n\treturn p.sendMessage(m)\n}\n\nfunc (p *Producer) asyncSend(m *sarama.ProducerMessage) error {\n\tlog.Debug(\"[%s] async sending: %+v\", p.name, m)\n\n\tselect {\n\tcase <-p.stopper:\n\t\treturn ErrStopping\n\n\tcase p.ap.Input() <- m:\n\t}\n\treturn nil\n}\n\nfunc (p *Producer) syncSend(m *sarama.ProducerMessage) error {\n\tlog.Debug(\"[%s] sync sending: %+v\", p.name, m)\n\n\t_, _, err := p.p.SendMessage(m)\n\treturn err\n}\n<commit_msg>BUG FIX: when shutdown, err handler receives nil err<commit_after>package kafka\n\nimport (\n\t\"github.com\/Shopify\/sarama\"\n\tlog \"github.com\/funkygao\/log4go\"\n)\n\n\/\/ Producer is a kafka producer that is transparent for sync\/async mode.\ntype Producer struct {\n\tcf      *Config\n\tname    string\n\tbrokers []string\n\tstopper chan struct{}\n\n\tp  sarama.SyncProducer\n\tap sarama.AsyncProducer\n\n\tsendMessage func(*sarama.ProducerMessage) error\n\n\tonError   func(*sarama.ProducerError)\n\tonSuccess func(*sarama.ProducerMessage)\n}\n\nfunc NewProducer(name string, brokers []string, cf *Config) *Producer {\n\tp := &Producer{\n\t\tname:    name,\n\t\tbrokers: brokers,\n\t\tcf:      cf,\n\t\tstopper: make(chan struct{}),\n\t}\n\n\treturn p\n}\n\nfunc (p *Producer) Start() error {\n\tvar err error\n\tif p.cf.async {\n\t\tp.ap, err = sarama.NewAsyncProducer(p.brokers, p.cf.Sarama)\n\t\tp.sendMessage = p.asyncSend\n\t} else {\n\t\tp.p, err = sarama.NewSyncProducer(p.brokers, p.cf.Sarama)\n\t\tp.sendMessage = p.syncSend\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !p.cf.async {\n\t\treturn nil\n\t}\n\n\tif p.onError == nil || p.onSuccess == nil {\n\t\treturn ErrNotReady\n\t}\n\n\tgo func() {\n\t\t\/\/ loop till Producer success channel closed\n\t\terrChan := p.ap.Errors()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase msg, ok := <-p.ap.Successes():\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Trace(\"[%s] success chan closed\", p.name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tp.onSuccess(msg)\n\n\t\t\tcase err, ok := <-errChan:\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Trace(\"[%s] err chan closed\", p.name)\n\t\t\t\t\terrChan = nil\n\t\t\t\t} else {\n\t\t\t\t\tp.onError(err)\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil\n}\n\n\/\/ Close will drain and close the Producer.\nfunc (p *Producer) Close() error {\n\tclose(p.stopper)\n\n\tif p.cf.async {\n\t\tp.ap.AsyncClose()\n\n\t\t\/\/ drain successes\n\t\tif p.onSuccess != nil {\n\t\t\tfor msg := range p.ap.Successes() {\n\t\t\t\tp.onSuccess(msg)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ drain errors\n\t\tif p.onError != nil {\n\t\t\tfor err := range p.ap.Errors() {\n\t\t\t\tp.onError(err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn p.p.Close()\n}\n\nfunc (p *Producer) ClientID() string {\n\treturn p.cf.Sarama.ClientID\n}\n\n\/\/ SetErrorHandler setup the async producer unretriable errors, e.g:\n\/\/ ErrInvalidPartition, ErrMessageSizeTooLarge, ErrIncompleteResponse\n\/\/ ErrBreakerOpen(e,g. update leader fails)\nfunc (p *Producer) SetErrorHandler(f func(err *sarama.ProducerError)) error {\n\tif !p.cf.async {\n\t\treturn ErrNotAllowed\n\t}\n\n\tif f == nil {\n\t\tp.cf.Sarama.Producer.Return.Errors = false\n\t}\n\tp.onError = f\n\treturn nil\n}\n\nfunc (p *Producer) SetSuccessHandler(f func(err *sarama.ProducerMessage)) error {\n\tif !p.cf.async {\n\t\treturn ErrNotAllowed\n\t}\n\n\tif f == nil {\n\t\tp.cf.Sarama.Producer.Return.Successes = false\n\t}\n\tp.onSuccess = f\n\treturn nil\n}\n\n\/\/ Send will send a kafka message.\nfunc (p *Producer) Send(m *sarama.ProducerMessage) error {\n\treturn p.sendMessage(m)\n}\n\nfunc (p *Producer) asyncSend(m *sarama.ProducerMessage) error {\n\tlog.Debug(\"[%s] async sending: %+v\", p.name, m)\n\n\tselect {\n\tcase <-p.stopper:\n\t\treturn ErrStopping\n\n\tcase p.ap.Input() <- m:\n\t}\n\treturn nil\n}\n\nfunc (p *Producer) syncSend(m *sarama.ProducerMessage) error {\n\tlog.Debug(\"[%s] sync sending: %+v\", p.name, m)\n\n\t_, _, err := p.p.SendMessage(m)\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package model\n\nimport (\n\t\"encoding\/json\"\n\t\"testing\"\n)\n\nfunc makeRowsEvent() *RowsEvent {\n\treturn &RowsEvent{\n\t\tLog:       \"mysql-bin.0001\",\n\t\tPosition:  498876,\n\t\tSchema:    \"mydabase\",\n\t\tTable:     \"user_account\",\n\t\tAction:    \"I\",\n\t\tTimestamp: 1486554654,\n\t\tRows:      [][]interface{}{{\"user\", 15, \"hello world\"}},\n\t}\n}\n\nfunc TestRowsEventEncode(t *testing.T) {\n\tr := makeRowsEvent()\n\tb, err := r.Encode()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif string(b) != `{\"log\":\"mysql-bin.0001\",\"pos\":498876,\"db\":\"mydabase\",\"tbl\":\"user_account\",\"dml\":\"I\",\"ts\":1486554654,\"rows\":[[\"user\",15,\"hello world\"]]}` {\n\t\tt.Fatal(\"encoded wrong:\" + string(b))\n\t}\n}\n\nfunc BenchmarkRowsEventEncode(b *testing.B) {\n\tr := makeRowsEvent()\n\tfor i := 0; i < b.N; i++ {\n\t\tr.Encode()\n\t}\n}\n\nfunc BenchmarkRowsEventLength(b *testing.B) {\n\tr := makeRowsEvent()\n\tfor i := 0; i < b.N; i++ {\n\t\tr.Length()\n\t}\n}\n\nfunc BenchmarkJsonEncodeRowsEvent(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tr := makeRowsEvent()\n\t\tjson.Marshal(r)\n\t}\n}\n\nfunc BenchmarkRowsEventJsonMarshalFF(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tr := makeRowsEvent()\n\t\tr.MarshalJSON()\n\t}\n}\n<commit_msg>msgpack have little gains compared with ffjson<commit_after>package model\n\nimport (\n\t\"encoding\/json\"\n\t\"testing\"\n\n\t\"gopkg.in\/vmihailenco\/msgpack.v2\"\n)\n\nfunc makeRowsEvent() *RowsEvent {\n\treturn &RowsEvent{\n\t\tLog:       \"mysql-bin.0001\",\n\t\tPosition:  498876,\n\t\tSchema:    \"mydabase\",\n\t\tTable:     \"user_account\",\n\t\tAction:    \"I\",\n\t\tTimestamp: 1486554654,\n\t\tRows:      [][]interface{}{{\"user\", 15, \"hello world\"}},\n\t}\n}\n\nfunc TestRowsEventEncode(t *testing.T) {\n\tr := makeRowsEvent()\n\tb, err := r.Encode()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif string(b) != `{\"log\":\"mysql-bin.0001\",\"pos\":498876,\"db\":\"mydabase\",\"tbl\":\"user_account\",\"dml\":\"I\",\"ts\":1486554654,\"rows\":[[\"user\",15,\"hello world\"]]}` {\n\t\tt.Fatal(\"encoded wrong:\" + string(b))\n\t}\n}\n\nfunc BenchmarkRowsEventEncode(b *testing.B) {\n\tr := makeRowsEvent()\n\tfor i := 0; i < b.N; i++ {\n\t\tr.Encode()\n\t}\n}\n\nfunc BenchmarkRowsEventLength(b *testing.B) {\n\tr := makeRowsEvent()\n\tfor i := 0; i < b.N; i++ {\n\t\tr.Length()\n\t}\n}\n\nfunc BenchmarkJsonEncodeRowsEvent(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tr := makeRowsEvent()\n\t\tjson.Marshal(r)\n\t}\n}\n\nfunc BenchmarkMsgpackEncodeRowsEvent(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tr := makeRowsEvent()\n\t\tmsgpack.Marshal(r)\n\t}\n}\n\nfunc BenchmarkRowsEventJsonMarshalFF(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\tr := makeRowsEvent()\n\t\tr.MarshalJSON()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package ticker\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/bitfinexcom\/bitfinex-api-go\/pkg\/convert\"\n)\n\ntype Ticker struct {\n\tSymbol          string\n\tFrr             float64\n\tBid             float64\n\tBidPeriod       int64\n\tBidSize         float64\n\tAsk             float64\n\tAskPeriod       int64\n\tAskSize         float64\n\tDailyChange     float64\n\tDailyChangePerc float64\n\tLastPrice       float64\n\tVolume          float64\n\tHigh            float64\n\tLow             float64\n}\n\ntype Update Ticker\ntype Snapshot struct {\n\tSnapshot []*Ticker\n}\n\nfunc SnapshotFromRaw(symbol string, raw [][]interface{}) (*Snapshot, error) {\n\tif len(raw) == 0 {\n\t\treturn nil, fmt.Errorf(\"data slice too short for ticker snapshot: %#v\", raw)\n\t}\n\n\tsnap := make([]*Ticker, 0)\n\tfor _, f := range raw {\n\t\tc, err := FromRaw(symbol, f)\n\t\tif err == nil {\n\t\t\tsnap = append(snap, c)\n\t\t}\n\t}\n\n\treturn &Snapshot{Snapshot: snap}, nil\n}\n\nfunc FromRaw(symbol string, raw []interface{}) (t *Ticker, err error) {\n\tif len(raw) < 10 {\n\t\treturn t, fmt.Errorf(\"data slice too short for ticker, expected %d got %d: %#v\", 10, len(raw), raw)\n\t}\n\n\t\/\/ funding currency ticker\n\t\/\/ ignore bid\/ask period for now\n\tif len(raw) == 13 {\n\t\tt = &Ticker{\n\t\t\tSymbol:          symbol,\n\t\t\tBid:             convert.F64ValOrZero(raw[1]),\n\t\t\tBidSize:         convert.F64ValOrZero(raw[2]),\n\t\t\tAsk:             convert.F64ValOrZero(raw[4]),\n\t\t\tAskSize:         convert.F64ValOrZero(raw[5]),\n\t\t\tDailyChange:     convert.F64ValOrZero(raw[7]),\n\t\t\tDailyChangePerc: convert.F64ValOrZero(raw[8]),\n\t\t\tLastPrice:       convert.F64ValOrZero(raw[9]),\n\t\t\tVolume:          convert.F64ValOrZero(raw[10]),\n\t\t\tHigh:            convert.F64ValOrZero(raw[11]),\n\t\t\tLow:             convert.F64ValOrZero(raw[12]),\n\t\t}\n\t\treturn\n\t}\n\n\tif len(raw) == 16 {\n\t\tt = &Ticker{\n\t\t\tSymbol:          symbol,\n\t\t\tFrr:             convert.F64ValOrZero(raw[0]),\n\t\t\tBid:             convert.F64ValOrZero(raw[1]),\n\t\t\tBidPeriod:       convert.I64ValOrZero(raw[2]),\n\t\t\tBidSize:         convert.F64ValOrZero(raw[3]),\n\t\t\tAsk:             convert.F64ValOrZero(raw[4]),\n\t\t\tAskPeriod:       convert.I64ValOrZero(raw[5]),\n\t\t\tAskSize:         convert.F64ValOrZero(raw[6]),\n\t\t\tDailyChange:     convert.F64ValOrZero(raw[7]),\n\t\t\tDailyChangePerc: convert.F64ValOrZero(raw[8]),\n\t\t\tLastPrice:       convert.F64ValOrZero(raw[9]),\n\t\t\tVolume:          convert.F64ValOrZero(raw[10]),\n\t\t\tHigh:            convert.F64ValOrZero(raw[11]),\n\t\t\tLow:             convert.F64ValOrZero(raw[12]),\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ all other tickers\n\t\/\/ on trading pairs (ex. tBTCUSD)\n\tt = &Ticker{\n\t\tSymbol:          symbol,\n\t\tBid:             convert.F64ValOrZero(raw[0]),\n\t\tBidSize:         convert.F64ValOrZero(raw[1]),\n\t\tAsk:             convert.F64ValOrZero(raw[2]),\n\t\tAskSize:         convert.F64ValOrZero(raw[3]),\n\t\tDailyChange:     convert.F64ValOrZero(raw[4]),\n\t\tDailyChangePerc: convert.F64ValOrZero(raw[5]),\n\t\tLastPrice:       convert.F64ValOrZero(raw[6]),\n\t\tVolume:          convert.F64ValOrZero(raw[7]),\n\t\tHigh:            convert.F64ValOrZero(raw[8]),\n\t\tLow:             convert.F64ValOrZero(raw[9]),\n\t}\n\treturn\n}\n\nfunc FromRestRaw(raw []interface{}) (t *Ticker, err error) {\n\tif len(raw) == 0 {\n\t\treturn t, fmt.Errorf(\"data slice too short for ticker\")\n\t}\n\n\treturn FromRaw(raw[0].(string), raw[1:])\n}\n<commit_msg>updating ticker model key\/value pairs and mapping logic as per docs<commit_after>package ticker\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/bitfinexcom\/bitfinex-api-go\/pkg\/convert\"\n)\n\ntype Ticker struct {\n\tSymbol              string\n\tFrr                 float64\n\tBid                 float64\n\tBidPeriod           int64\n\tBidSize             float64\n\tAsk                 float64\n\tAskPeriod           int64\n\tAskSize             float64\n\tDailyChange         float64\n\tDailyChangeRelative float64\n\tLastPrice           float64\n\tVolume              float64\n\tHigh                float64\n\tLow                 float64\n\t\/\/ PLACEHOLDER,\n\t\/\/ PLACEHOLDER,\n\tFrrAmountAvailable float64\n}\n\ntype Update Ticker\ntype Snapshot struct {\n\tSnapshot []*Ticker\n}\n\nfunc SnapshotFromRaw(symbol string, raw [][]interface{}) (*Snapshot, error) {\n\tif len(raw) == 0 {\n\t\treturn nil, fmt.Errorf(\"data slice too short for ticker snapshot: %#v\", raw)\n\t}\n\n\tsnap := make([]*Ticker, 0)\n\tfor _, f := range raw {\n\t\tc, err := FromRaw(symbol, f)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsnap = append(snap, c)\n\t}\n\n\treturn &Snapshot{Snapshot: snap}, nil\n}\n\nfunc FromRaw(symbol string, raw []interface{}) (t *Ticker, err error) {\n\tif strings.HasPrefix(symbol, \"t\") && len(raw) >= 10 {\n\t\tt = &Ticker{\n\t\t\tSymbol:              symbol,\n\t\t\tBid:                 convert.F64ValOrZero(raw[0]),\n\t\t\tBidSize:             convert.F64ValOrZero(raw[1]),\n\t\t\tAsk:                 convert.F64ValOrZero(raw[2]),\n\t\t\tAskSize:             convert.F64ValOrZero(raw[3]),\n\t\t\tDailyChange:         convert.F64ValOrZero(raw[4]),\n\t\t\tDailyChangeRelative: convert.F64ValOrZero(raw[5]),\n\t\t\tLastPrice:           convert.F64ValOrZero(raw[6]),\n\t\t\tVolume:              convert.F64ValOrZero(raw[7]),\n\t\t\tHigh:                convert.F64ValOrZero(raw[8]),\n\t\t\tLow:                 convert.F64ValOrZero(raw[9]),\n\t\t}\n\t\treturn\n\t}\n\n\tif strings.HasPrefix(symbol, \"f\") && len(raw) >= 16 {\n\t\tt = &Ticker{\n\t\t\tSymbol:              symbol,\n\t\t\tFrr:                 convert.F64ValOrZero(raw[0]),\n\t\t\tBid:                 convert.F64ValOrZero(raw[1]),\n\t\t\tBidPeriod:           convert.I64ValOrZero(raw[2]),\n\t\t\tBidSize:             convert.F64ValOrZero(raw[3]),\n\t\t\tAsk:                 convert.F64ValOrZero(raw[4]),\n\t\t\tAskPeriod:           convert.I64ValOrZero(raw[5]),\n\t\t\tAskSize:             convert.F64ValOrZero(raw[6]),\n\t\t\tDailyChange:         convert.F64ValOrZero(raw[7]),\n\t\t\tDailyChangeRelative: convert.F64ValOrZero(raw[8]),\n\t\t\tLastPrice:           convert.F64ValOrZero(raw[9]),\n\t\t\tVolume:              convert.F64ValOrZero(raw[10]),\n\t\t\tHigh:                convert.F64ValOrZero(raw[11]),\n\t\t\tLow:                 convert.F64ValOrZero(raw[12]),\n\t\t\tFrrAmountAvailable:  convert.F64ValOrZero(raw[15]),\n\t\t}\n\t\treturn\n\t}\n\n\terr = fmt.Errorf(\"unrecognized data slice format for pair:%s, date:%#v\", symbol, raw)\n\treturn\n}\n\nfunc FromRestRaw(raw []interface{}) (t *Ticker, err error) {\n\tif len(raw) == 0 {\n\t\treturn t, fmt.Errorf(\"data slice too short for ticker\")\n\t}\n\n\treturn FromRaw(raw[0].(string), raw[1:])\n}\n\n\/\/ FromWSRaw - based on condition will return snapshot of trades or single trade\nfunc FromWSRaw(symbol string, data []interface{}) (interface{}, error) {\n\t_, isSnapshot := data[0].([]interface{})\n\tif isSnapshot {\n\t\treturn SnapshotFromRaw(symbol, convert.ToInterfaceArray(data))\n\t}\n\treturn FromRaw(symbol, data)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage nfs\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/container-storage-interface\/spec\/lib\/go\/csi\"\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\/codes\"\n\t\"google.golang.org\/grpc\/status\"\n\t\"k8s.io\/klog\/v2\"\n\t\"k8s.io\/kubernetes\/pkg\/volume\"\n\t\"k8s.io\/utils\/mount\"\n)\n\n\/\/ NodeServer driver\ntype NodeServer struct {\n\tDriver  *Driver\n\tmounter mount.Interface\n}\n\n\/\/ NodePublishVolume mount the volume\nfunc (ns *NodeServer) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) {\n\tif req.GetVolumeCapability() == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Volume capability missing in request\")\n\t}\n\tvolumeID := req.GetVolumeId()\n\tif len(volumeID) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Volume ID missing in request\")\n\t}\n\ttargetPath := req.GetTargetPath()\n\tif len(targetPath) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Target path not provided\")\n\t}\n\n\tnotMnt, err := ns.mounter.IsLikelyNotMountPoint(targetPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(targetPath, 0750); err != nil {\n\t\t\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t\t\t}\n\t\t\tnotMnt = true\n\t\t} else {\n\t\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t\t}\n\t}\n\tif !notMnt {\n\t\treturn &csi.NodePublishVolumeResponse{}, nil\n\t}\n\n\tmountOptions := req.GetVolumeCapability().GetMount().GetMountFlags()\n\tif req.GetReadonly() {\n\t\tmountOptions = append(mountOptions, \"ro\")\n\t}\n\n\ts := req.GetVolumeContext()[paramServer]\n\tep := req.GetVolumeContext()[paramShare]\n\tsource := fmt.Sprintf(\"%s:%s\", s, ep)\n\n\tklog.V(2).Infof(\"NodePublishVolume: volumeID(%v) source(%s) targetPath(%s) mountflags(%v)\", volumeID, source, targetPath, mountOptions)\n\terr = ns.mounter.Mount(source, targetPath, \"nfs\", mountOptions)\n\tif err != nil {\n\t\tif os.IsPermission(err) {\n\t\t\treturn nil, status.Error(codes.PermissionDenied, err.Error())\n\t\t}\n\t\tif strings.Contains(err.Error(), \"invalid argument\") {\n\t\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tif ns.Driver.perm != nil {\n\t\tif err := os.Chmod(targetPath, os.FileMode(*ns.Driver.perm)); err != nil {\n\t\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t\t}\n\t}\n\n\treturn &csi.NodePublishVolumeResponse{}, nil\n}\n\n\/\/ NodeUnpublishVolume unmount the volume\nfunc (ns *NodeServer) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) {\n\tvolumeID := req.GetVolumeId()\n\tif len(volumeID) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Volume ID missing in request\")\n\t}\n\ttargetPath := req.GetTargetPath()\n\tif len(targetPath) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Target path missing in request\")\n\t}\n\tnotMnt, err := ns.mounter.IsLikelyNotMountPoint(targetPath)\n\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, status.Error(codes.NotFound, \"Targetpath not found\")\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\tif notMnt {\n\t\treturn nil, status.Error(codes.NotFound, \"Volume not mounted\")\n\t}\n\n\tklog.V(2).Infof(\"NodeUnpublishVolume: CleanupMountPoint %s on volumeID(%s)\", targetPath, volumeID)\n\terr = mount.CleanupMountPoint(targetPath, ns.mounter, false)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &csi.NodeUnpublishVolumeResponse{}, nil\n}\n\n\/\/ NodeGetInfo return info of the node on which this plugin is running\nfunc (ns *NodeServer) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {\n\treturn &csi.NodeGetInfoResponse{\n\t\tNodeId: ns.Driver.nodeID,\n\t}, nil\n}\n\n\/\/ NodeGetCapabilities return the capabilities of the Node plugin\nfunc (ns *NodeServer) NodeGetCapabilities(ctx context.Context, req *csi.NodeGetCapabilitiesRequest) (*csi.NodeGetCapabilitiesResponse, error) {\n\treturn &csi.NodeGetCapabilitiesResponse{\n\t\tCapabilities: ns.Driver.nscap,\n\t}, nil\n}\n\n\/\/ NodeGetVolumeStats get volume stats\nfunc (ns *NodeServer) NodeGetVolumeStats(ctx context.Context, req *csi.NodeGetVolumeStatsRequest) (*csi.NodeGetVolumeStatsResponse, error) {\n\tif len(req.VolumeId) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"NodeGetVolumeStats volume ID was empty\")\n\t}\n\tif len(req.VolumePath) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"NodeGetVolumeStats volume path was empty\")\n\t}\n\n\t_, err := os.Stat(req.VolumePath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, status.Errorf(codes.NotFound, \"path %s does not exist\", req.VolumePath)\n\t\t}\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to stat file %s: %v\", req.VolumePath, err)\n\t}\n\n\tvolumeMetrics, err := volume.NewMetricsStatFS(req.VolumePath).GetMetrics()\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to get metrics: %v\", err)\n\t}\n\n\tavailable, ok := volumeMetrics.Available.AsInt64()\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to transform volume available size(%v)\", volumeMetrics.Available)\n\t}\n\tcapacity, ok := volumeMetrics.Capacity.AsInt64()\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to transform volume capacity size(%v)\", volumeMetrics.Capacity)\n\t}\n\tused, ok := volumeMetrics.Used.AsInt64()\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to transform volume used size(%v)\", volumeMetrics.Used)\n\t}\n\n\tinodesFree, ok := volumeMetrics.InodesFree.AsInt64()\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to transform disk inodes free(%v)\", volumeMetrics.InodesFree)\n\t}\n\tinodes, ok := volumeMetrics.Inodes.AsInt64()\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to transform disk inodes(%v)\", volumeMetrics.Inodes)\n\t}\n\tinodesUsed, ok := volumeMetrics.InodesUsed.AsInt64()\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to transform disk inodes used(%v)\", volumeMetrics.InodesUsed)\n\t}\n\n\treturn &csi.NodeGetVolumeStatsResponse{\n\t\tUsage: []*csi.VolumeUsage{\n\t\t\t{\n\t\t\t\tUnit:      csi.VolumeUsage_BYTES,\n\t\t\t\tAvailable: available,\n\t\t\t\tTotal:     capacity,\n\t\t\t\tUsed:      used,\n\t\t\t},\n\t\t\t{\n\t\t\t\tUnit:      csi.VolumeUsage_INODES,\n\t\t\t\tAvailable: inodesFree,\n\t\t\t\tTotal:     inodes,\n\t\t\t\tUsed:      inodesUsed,\n\t\t\t},\n\t\t},\n\t}, nil\n}\n\n\/\/ NodeUnstageVolume unstage volume\nfunc (ns *NodeServer) NodeUnstageVolume(ctx context.Context, req *csi.NodeUnstageVolumeRequest) (*csi.NodeUnstageVolumeResponse, error) {\n\treturn &csi.NodeUnstageVolumeResponse{}, nil\n}\n\n\/\/ NodeStageVolume stage volume\nfunc (ns *NodeServer) NodeStageVolume(ctx context.Context, req *csi.NodeStageVolumeRequest) (*csi.NodeStageVolumeResponse, error) {\n\treturn &csi.NodeStageVolumeResponse{}, nil\n}\n\n\/\/ NodeExpandVolume node expand volume\nfunc (ns *NodeServer) NodeExpandVolume(ctx context.Context, req *csi.NodeExpandVolumeRequest) (*csi.NodeExpandVolumeResponse, error) {\n\treturn nil, status.Error(codes.Unimplemented, \"\")\n}\n\nfunc makeDir(pathname string) error {\n\terr := os.MkdirAll(pathname, os.FileMode(0755))\n\tif err != nil {\n\t\tif !os.IsExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>cleanup: disable NodeStageVolume<commit_after>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage nfs\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/container-storage-interface\/spec\/lib\/go\/csi\"\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\/codes\"\n\t\"google.golang.org\/grpc\/status\"\n\t\"k8s.io\/klog\/v2\"\n\t\"k8s.io\/kubernetes\/pkg\/volume\"\n\t\"k8s.io\/utils\/mount\"\n)\n\n\/\/ NodeServer driver\ntype NodeServer struct {\n\tDriver  *Driver\n\tmounter mount.Interface\n}\n\n\/\/ NodePublishVolume mount the volume\nfunc (ns *NodeServer) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) {\n\tif req.GetVolumeCapability() == nil {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Volume capability missing in request\")\n\t}\n\tvolumeID := req.GetVolumeId()\n\tif len(volumeID) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Volume ID missing in request\")\n\t}\n\ttargetPath := req.GetTargetPath()\n\tif len(targetPath) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Target path not provided\")\n\t}\n\n\tnotMnt, err := ns.mounter.IsLikelyNotMountPoint(targetPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif err := os.MkdirAll(targetPath, 0750); err != nil {\n\t\t\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t\t\t}\n\t\t\tnotMnt = true\n\t\t} else {\n\t\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t\t}\n\t}\n\tif !notMnt {\n\t\treturn &csi.NodePublishVolumeResponse{}, nil\n\t}\n\n\tmountOptions := req.GetVolumeCapability().GetMount().GetMountFlags()\n\tif req.GetReadonly() {\n\t\tmountOptions = append(mountOptions, \"ro\")\n\t}\n\n\ts := req.GetVolumeContext()[paramServer]\n\tep := req.GetVolumeContext()[paramShare]\n\tsource := fmt.Sprintf(\"%s:%s\", s, ep)\n\n\tklog.V(2).Infof(\"NodePublishVolume: volumeID(%v) source(%s) targetPath(%s) mountflags(%v)\", volumeID, source, targetPath, mountOptions)\n\terr = ns.mounter.Mount(source, targetPath, \"nfs\", mountOptions)\n\tif err != nil {\n\t\tif os.IsPermission(err) {\n\t\t\treturn nil, status.Error(codes.PermissionDenied, err.Error())\n\t\t}\n\t\tif strings.Contains(err.Error(), \"invalid argument\") {\n\t\t\treturn nil, status.Error(codes.InvalidArgument, err.Error())\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\tif ns.Driver.perm != nil {\n\t\tif err := os.Chmod(targetPath, os.FileMode(*ns.Driver.perm)); err != nil {\n\t\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t\t}\n\t}\n\n\treturn &csi.NodePublishVolumeResponse{}, nil\n}\n\n\/\/ NodeUnpublishVolume unmount the volume\nfunc (ns *NodeServer) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) {\n\tvolumeID := req.GetVolumeId()\n\tif len(volumeID) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Volume ID missing in request\")\n\t}\n\ttargetPath := req.GetTargetPath()\n\tif len(targetPath) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"Target path missing in request\")\n\t}\n\tnotMnt, err := ns.mounter.IsLikelyNotMountPoint(targetPath)\n\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, status.Error(codes.NotFound, \"Targetpath not found\")\n\t\t}\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\tif notMnt {\n\t\treturn nil, status.Error(codes.NotFound, \"Volume not mounted\")\n\t}\n\n\tklog.V(2).Infof(\"NodeUnpublishVolume: CleanupMountPoint %s on volumeID(%s)\", targetPath, volumeID)\n\terr = mount.CleanupMountPoint(targetPath, ns.mounter, false)\n\tif err != nil {\n\t\treturn nil, status.Error(codes.Internal, err.Error())\n\t}\n\n\treturn &csi.NodeUnpublishVolumeResponse{}, nil\n}\n\n\/\/ NodeGetInfo return info of the node on which this plugin is running\nfunc (ns *NodeServer) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {\n\treturn &csi.NodeGetInfoResponse{\n\t\tNodeId: ns.Driver.nodeID,\n\t}, nil\n}\n\n\/\/ NodeGetCapabilities return the capabilities of the Node plugin\nfunc (ns *NodeServer) NodeGetCapabilities(ctx context.Context, req *csi.NodeGetCapabilitiesRequest) (*csi.NodeGetCapabilitiesResponse, error) {\n\treturn &csi.NodeGetCapabilitiesResponse{\n\t\tCapabilities: ns.Driver.nscap,\n\t}, nil\n}\n\n\/\/ NodeGetVolumeStats get volume stats\nfunc (ns *NodeServer) NodeGetVolumeStats(ctx context.Context, req *csi.NodeGetVolumeStatsRequest) (*csi.NodeGetVolumeStatsResponse, error) {\n\tif len(req.VolumeId) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"NodeGetVolumeStats volume ID was empty\")\n\t}\n\tif len(req.VolumePath) == 0 {\n\t\treturn nil, status.Error(codes.InvalidArgument, \"NodeGetVolumeStats volume path was empty\")\n\t}\n\n\t_, err := os.Stat(req.VolumePath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, status.Errorf(codes.NotFound, \"path %s does not exist\", req.VolumePath)\n\t\t}\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to stat file %s: %v\", req.VolumePath, err)\n\t}\n\n\tvolumeMetrics, err := volume.NewMetricsStatFS(req.VolumePath).GetMetrics()\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to get metrics: %v\", err)\n\t}\n\n\tavailable, ok := volumeMetrics.Available.AsInt64()\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to transform volume available size(%v)\", volumeMetrics.Available)\n\t}\n\tcapacity, ok := volumeMetrics.Capacity.AsInt64()\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to transform volume capacity size(%v)\", volumeMetrics.Capacity)\n\t}\n\tused, ok := volumeMetrics.Used.AsInt64()\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to transform volume used size(%v)\", volumeMetrics.Used)\n\t}\n\n\tinodesFree, ok := volumeMetrics.InodesFree.AsInt64()\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to transform disk inodes free(%v)\", volumeMetrics.InodesFree)\n\t}\n\tinodes, ok := volumeMetrics.Inodes.AsInt64()\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to transform disk inodes(%v)\", volumeMetrics.Inodes)\n\t}\n\tinodesUsed, ok := volumeMetrics.InodesUsed.AsInt64()\n\tif !ok {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to transform disk inodes used(%v)\", volumeMetrics.InodesUsed)\n\t}\n\n\treturn &csi.NodeGetVolumeStatsResponse{\n\t\tUsage: []*csi.VolumeUsage{\n\t\t\t{\n\t\t\t\tUnit:      csi.VolumeUsage_BYTES,\n\t\t\t\tAvailable: available,\n\t\t\t\tTotal:     capacity,\n\t\t\t\tUsed:      used,\n\t\t\t},\n\t\t\t{\n\t\t\t\tUnit:      csi.VolumeUsage_INODES,\n\t\t\t\tAvailable: inodesFree,\n\t\t\t\tTotal:     inodes,\n\t\t\t\tUsed:      inodesUsed,\n\t\t\t},\n\t\t},\n\t}, nil\n}\n\n\/\/ NodeUnstageVolume unstage volume\nfunc (ns *NodeServer) NodeUnstageVolume(ctx context.Context, req *csi.NodeUnstageVolumeRequest) (*csi.NodeUnstageVolumeResponse, error) {\n\treturn nil, status.Error(codes.Unimplemented, \"\")\n}\n\n\/\/ NodeStageVolume stage volume\nfunc (ns *NodeServer) NodeStageVolume(ctx context.Context, req *csi.NodeStageVolumeRequest) (*csi.NodeStageVolumeResponse, error) {\n\treturn nil, status.Error(codes.Unimplemented, \"\")\n}\n\n\/\/ NodeExpandVolume node expand volume\nfunc (ns *NodeServer) NodeExpandVolume(ctx context.Context, req *csi.NodeExpandVolumeRequest) (*csi.NodeExpandVolumeResponse, error) {\n\treturn nil, status.Error(codes.Unimplemented, \"\")\n}\n\nfunc makeDir(pathname string) error {\n\terr := os.MkdirAll(pathname, os.FileMode(0755))\n\tif err != nil {\n\t\tif !os.IsExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ SPDX-License-Identifier: Apache-2.0\n\/\/ Copyright Authors of Cilium\n\npackage modules\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t. \"gopkg.in\/check.v1\"\n\n\t\"github.com\/cilium\/cilium\/pkg\/checker\"\n)\n\nconst (\n\tmodulesContent = `ebtable_nat 16384 1 - Live 0x0000000000000000\nebtable_broute 16384 1 - Live 0x0000000000000000\nbridge 172032 1 ebtable_broute, Live 0x0000000000000000\nip6table_nat 16384 1 - Live 0x0000000000000000\nnf_nat_ipv6 16384 1 ip6table_nat, Live 0x0000000000000000\nip6table_mangle 16384 1 - Live 0x0000000000000000\nip6table_raw 16384 1 - Live 0x0000000000000000\nip6table_security 16384 1 - Live 0x0000000000000000\niptable_nat 16384 1 - Live 0x0000000000000000\nnf_nat_ipv4 16384 1 iptable_nat, Live 0x0000000000000000\niptable_mangle 16384 1 - Live 0x0000000000000000\niptable_raw 16384 1 - Live 0x0000000000000000\niptable_security 16384 1 - Live 0x0000000000000000\nebtable_filter 16384 1 - Live 0x0000000000000000\nebtables 36864 3 ebtable_nat,ebtable_broute,ebtable_filter, Live 0x0000000000000000\nip6table_filter 16384 1 - Live 0x0000000000000000\nip6_tables 28672 5 ip6table_nat,ip6table_mangle,ip6table_raw,ip6table_security,ip6table_filter, Live 0x0000000000000000\niptable_filter 16384 1 - Live 0x0000000000000000\nip_tables 28672 5 iptable_nat,iptable_mangle,iptable_raw,iptable_security,iptable_filter, Live 0x0000000000000000\nx_tables 40960 23 xt_multiport,xt_nat,xt_addrtype,xt_mark,xt_comment,xt_CHECKSUM,ipt_MASQUERADE,xt_tcpudp,ip6t_rpfilter,ip6t_REJECT,ipt_REJECT,xt_conntrack,ip6table_mangle,ip6table_raw,ip6table_security,iptable_mangle,iptable_raw,iptable_security,ebtables,ip6table_filter,ip6_tables,iptable_filter,ip_tables, Live 0x0000000000000000`\n)\n\n\/\/ Hook up gocheck into the \"go test\" runner.\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype ModulesTestSuite struct{}\n\nvar _ = Suite(&ModulesTestSuite{})\n\nfunc (s *ModulesTestSuite) TestInit(c *C) {\n\tmanager := &ModulesManager{}\n\tc.Assert(manager.modulesList, IsNil)\n\terr := manager.Init()\n\tc.Assert(err, IsNil)\n\tc.Assert(manager.modulesList, NotNil)\n}\n\nfunc (s *ModulesTestSuite) TestFindModules(c *C) {\n\tmanager := &ModulesManager{\n\t\tmodulesList: []string{\n\t\t\t\"ip6_tables\",\n\t\t\t\"ip6table_mangle\",\n\t\t\t\"ip6table_filter\",\n\t\t\t\"ip6table_security\",\n\t\t\t\"ip6table_raw\",\n\t\t\t\"ip6table_nat\",\n\t\t},\n\t}\n\ttestCases := []struct {\n\t\tmodulesToFind []string\n\t\tisSubset      bool\n\t\texpectedDiff  []string\n\t}{\n\t\t{\n\t\t\tmodulesToFind: []string{\n\t\t\t\t\"ip6_tables\",\n\t\t\t\t\"ip6table_mangle\",\n\t\t\t\t\"ip6table_filter\",\n\t\t\t\t\"ip6table_security\",\n\t\t\t\t\"ip6table_raw\",\n\t\t\t\t\"ip6table_nat\",\n\t\t\t},\n\t\t\tisSubset:     true,\n\t\t\texpectedDiff: nil,\n\t\t},\n\t\t{\n\t\t\tmodulesToFind: []string{\n\t\t\t\t\"ip6_tables\",\n\t\t\t\t\"ip6table_mangle\",\n\t\t\t\t\"ip6table_raw\",\n\t\t\t},\n\t\t\tisSubset:     true,\n\t\t\texpectedDiff: nil,\n\t\t},\n\t\t{\n\t\t\tmodulesToFind: []string{\n\t\t\t\t\"ip6_tables\",\n\t\t\t\t\"ip6table_mangle\",\n\t\t\t\t\"ip6table_raw\",\n\t\t\t\t\"foo_module\",\n\t\t\t},\n\t\t\tisSubset:     false,\n\t\t\texpectedDiff: []string{\"foo_module\"},\n\t\t},\n\t\t{\n\t\t\tmodulesToFind: []string{\n\t\t\t\t\"foo_module\",\n\t\t\t\t\"bar_module\",\n\t\t\t},\n\t\t\tisSubset:     false,\n\t\t\texpectedDiff: []string{\"foo_module\", \"bar_module\"},\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tfound, diff := manager.FindModules(tc.modulesToFind...)\n\t\tc.Assert(found, Equals, tc.isSubset)\n\t\tc.Assert(diff, checker.DeepEquals, tc.expectedDiff)\n\t}\n}\n\nfunc (s *ModulesTestSuite) TestParseModuleFile(c *C) {\n\texpectedLength := 20\n\texpectedModules := []string{\n\t\t\"ebtable_nat\",\n\t\t\"ebtable_broute\",\n\t\t\"bridge\",\n\t\t\"ip6table_nat\",\n\t\t\"nf_nat_ipv6\",\n\t\t\"ip6table_mangle\",\n\t\t\"ip6table_raw\",\n\t\t\"ip6table_security\",\n\t\t\"iptable_nat\",\n\t\t\"nf_nat_ipv4\",\n\t\t\"iptable_mangle\",\n\t\t\"iptable_raw\",\n\t\t\"iptable_security\",\n\t\t\"ebtable_filter\",\n\t\t\"ebtables\",\n\t\t\"ip6table_filter\",\n\t\t\"ip6_tables\",\n\t\t\"iptable_filter\",\n\t\t\"ip_tables\",\n\t\t\"x_tables\",\n\t}\n\n\tr := bytes.NewBuffer([]byte(modulesContent))\n\tmoduleInfos, err := parseModulesFile(r)\n\tc.Assert(err, IsNil)\n\tc.Assert(moduleInfos, HasLen, expectedLength)\n\tc.Assert(moduleInfos, checker.DeepEquals, expectedModules)\n}\n\nfunc (s *ModulesTestSuite) TestListModules(c *C) {\n\t_, err := listModules()\n\tc.Assert(err, IsNil)\n}\n<commit_msg>modules: pass TestInit on kernels without kernel modules<commit_after>\/\/ SPDX-License-Identifier: Apache-2.0\n\/\/ Copyright Authors of Cilium\n\npackage modules\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t. \"gopkg.in\/check.v1\"\n\n\t\"github.com\/cilium\/cilium\/pkg\/checker\"\n)\n\nconst (\n\tmodulesContent = `ebtable_nat 16384 1 - Live 0x0000000000000000\nebtable_broute 16384 1 - Live 0x0000000000000000\nbridge 172032 1 ebtable_broute, Live 0x0000000000000000\nip6table_nat 16384 1 - Live 0x0000000000000000\nnf_nat_ipv6 16384 1 ip6table_nat, Live 0x0000000000000000\nip6table_mangle 16384 1 - Live 0x0000000000000000\nip6table_raw 16384 1 - Live 0x0000000000000000\nip6table_security 16384 1 - Live 0x0000000000000000\niptable_nat 16384 1 - Live 0x0000000000000000\nnf_nat_ipv4 16384 1 iptable_nat, Live 0x0000000000000000\niptable_mangle 16384 1 - Live 0x0000000000000000\niptable_raw 16384 1 - Live 0x0000000000000000\niptable_security 16384 1 - Live 0x0000000000000000\nebtable_filter 16384 1 - Live 0x0000000000000000\nebtables 36864 3 ebtable_nat,ebtable_broute,ebtable_filter, Live 0x0000000000000000\nip6table_filter 16384 1 - Live 0x0000000000000000\nip6_tables 28672 5 ip6table_nat,ip6table_mangle,ip6table_raw,ip6table_security,ip6table_filter, Live 0x0000000000000000\niptable_filter 16384 1 - Live 0x0000000000000000\nip_tables 28672 5 iptable_nat,iptable_mangle,iptable_raw,iptable_security,iptable_filter, Live 0x0000000000000000\nx_tables 40960 23 xt_multiport,xt_nat,xt_addrtype,xt_mark,xt_comment,xt_CHECKSUM,ipt_MASQUERADE,xt_tcpudp,ip6t_rpfilter,ip6t_REJECT,ipt_REJECT,xt_conntrack,ip6table_mangle,ip6table_raw,ip6table_security,iptable_mangle,iptable_raw,iptable_security,ebtables,ip6table_filter,ip6_tables,iptable_filter,ip_tables, Live 0x0000000000000000`\n)\n\n\/\/ Hook up gocheck into the \"go test\" runner.\nfunc Test(t *testing.T) {\n\tTestingT(t)\n}\n\ntype ModulesTestSuite struct{}\n\nvar _ = Suite(&ModulesTestSuite{})\n\nfunc (s *ModulesTestSuite) TestInit(c *C) {\n\tvar manager ModulesManager\n\tc.Assert(manager.Init(), IsNil)\n}\n\nfunc (s *ModulesTestSuite) TestFindModules(c *C) {\n\tmanager := &ModulesManager{\n\t\tmodulesList: []string{\n\t\t\t\"ip6_tables\",\n\t\t\t\"ip6table_mangle\",\n\t\t\t\"ip6table_filter\",\n\t\t\t\"ip6table_security\",\n\t\t\t\"ip6table_raw\",\n\t\t\t\"ip6table_nat\",\n\t\t},\n\t}\n\ttestCases := []struct {\n\t\tmodulesToFind []string\n\t\tisSubset      bool\n\t\texpectedDiff  []string\n\t}{\n\t\t{\n\t\t\tmodulesToFind: []string{\n\t\t\t\t\"ip6_tables\",\n\t\t\t\t\"ip6table_mangle\",\n\t\t\t\t\"ip6table_filter\",\n\t\t\t\t\"ip6table_security\",\n\t\t\t\t\"ip6table_raw\",\n\t\t\t\t\"ip6table_nat\",\n\t\t\t},\n\t\t\tisSubset:     true,\n\t\t\texpectedDiff: nil,\n\t\t},\n\t\t{\n\t\t\tmodulesToFind: []string{\n\t\t\t\t\"ip6_tables\",\n\t\t\t\t\"ip6table_mangle\",\n\t\t\t\t\"ip6table_raw\",\n\t\t\t},\n\t\t\tisSubset:     true,\n\t\t\texpectedDiff: nil,\n\t\t},\n\t\t{\n\t\t\tmodulesToFind: []string{\n\t\t\t\t\"ip6_tables\",\n\t\t\t\t\"ip6table_mangle\",\n\t\t\t\t\"ip6table_raw\",\n\t\t\t\t\"foo_module\",\n\t\t\t},\n\t\t\tisSubset:     false,\n\t\t\texpectedDiff: []string{\"foo_module\"},\n\t\t},\n\t\t{\n\t\t\tmodulesToFind: []string{\n\t\t\t\t\"foo_module\",\n\t\t\t\t\"bar_module\",\n\t\t\t},\n\t\t\tisSubset:     false,\n\t\t\texpectedDiff: []string{\"foo_module\", \"bar_module\"},\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tfound, diff := manager.FindModules(tc.modulesToFind...)\n\t\tc.Assert(found, Equals, tc.isSubset)\n\t\tc.Assert(diff, checker.DeepEquals, tc.expectedDiff)\n\t}\n}\n\nfunc (s *ModulesTestSuite) TestParseModuleFile(c *C) {\n\texpectedLength := 20\n\texpectedModules := []string{\n\t\t\"ebtable_nat\",\n\t\t\"ebtable_broute\",\n\t\t\"bridge\",\n\t\t\"ip6table_nat\",\n\t\t\"nf_nat_ipv6\",\n\t\t\"ip6table_mangle\",\n\t\t\"ip6table_raw\",\n\t\t\"ip6table_security\",\n\t\t\"iptable_nat\",\n\t\t\"nf_nat_ipv4\",\n\t\t\"iptable_mangle\",\n\t\t\"iptable_raw\",\n\t\t\"iptable_security\",\n\t\t\"ebtable_filter\",\n\t\t\"ebtables\",\n\t\t\"ip6table_filter\",\n\t\t\"ip6_tables\",\n\t\t\"iptable_filter\",\n\t\t\"ip_tables\",\n\t\t\"x_tables\",\n\t}\n\n\tr := bytes.NewBuffer([]byte(modulesContent))\n\tmoduleInfos, err := parseModulesFile(r)\n\tc.Assert(err, IsNil)\n\tc.Assert(moduleInfos, HasLen, expectedLength)\n\tc.Assert(moduleInfos, checker.DeepEquals, expectedModules)\n}\n\nfunc (s *ModulesTestSuite) TestListModules(c *C) {\n\t_, err := listModules()\n\tc.Assert(err, IsNil)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016-2018 Authors of Cilium\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage manager\n\nimport (\n\t\"math\"\n\t\"time\"\n\n\t\"github.com\/cilium\/cilium\/pkg\/datapath\"\n\t\"github.com\/cilium\/cilium\/pkg\/lock\"\n\t\"github.com\/cilium\/cilium\/pkg\/metrics\"\n\t\"github.com\/cilium\/cilium\/pkg\/node\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\nvar (\n\tbaseBackgroundSyncInterval = time.Minute\n)\n\ntype nodeEntry struct {\n\t\/\/ mutex serves two purposes:\n\t\/\/ 1. Serialize any direct access to the node field in this entry.\n\t\/\/ 2. Serialize all calls do the datapath layer for a particular node.\n\t\/\/\n\t\/\/ See description of Manager.mutex for more details\n\t\/\/\n\t\/\/ If both the nodeEntry.mutex and Manager.mutex must be held, then the\n\t\/\/ Manager.mutex must *always* be acquired first.\n\tmutex lock.Mutex\n\tnode  node.Node\n}\n\n\/\/ Manager is the entity that manages a collection of nodes\ntype Manager struct {\n\t\/\/ mutex is the lock protecting access to the nodes map. The mutex must\n\t\/\/ be held for any access of the nodes map.\n\t\/\/\n\t\/\/ The manager mutex works together with the entry mutex in the\n\t\/\/ following way to minimize the duration the manager mutex is held:\n\t\/\/\n\t\/\/ 1. Acquire manager mutex to safely access nodes map and to retrieve\n\t\/\/    node entry.\n\t\/\/ 2. Acquire mutex of the entry while the manager mutex is still held.\n\t\/\/    This guarantees that no change to the entry has happened.\n\t\/\/ 3. Release of the manager mutex to unblock changes or reads to other\n\t\/\/    node entries.\n\t\/\/ 4. Change of entry data or performing of datapath interactions\n\t\/\/ 5. Release of the entry mutex\n\t\/\/\n\t\/\/ If both the nodeEntry.mutex and Manager.mutex must be held, then the\n\t\/\/ Manager.mutex must *always* be acquired first.\n\tmutex lock.RWMutex\n\n\t\/\/ nodes is the list of nodes. Access must be protected via mutex.\n\tnodes map[node.Identity]*nodeEntry\n\n\t\/\/ datapath is the interface responsible for this node manager\n\tdatapath datapath.NodeHandler\n\n\t\/\/ closeChan is closed when the manager is closed\n\tcloseChan chan struct{}\n\n\t\/\/ name is the name of the manager. It must be unique and feasibility\n\t\/\/ to be used a prometheus metric name.\n\tname string\n\n\t\/\/ metricEventsReceived is the prometheus metric to track the number of\n\t\/\/ node events received\n\tmetricEventsReceived *prometheus.CounterVec\n\n\t\/\/ metricNumNodes is the prometheus metric to track the number of nodes\n\t\/\/ being managed\n\tmetricNumNodes prometheus.Gauge\n\n\t\/\/ metricDatapathValidations is the prometheus metric to track the\n\t\/\/ number of datapath node validation calls\n\tmetricDatapathValidations prometheus.Counter\n}\n\n\/\/ NewManager returns a new node manager\nfunc NewManager(name string, datapath datapath.NodeHandler) (*Manager, error) {\n\tm := &Manager{\n\t\tname:      name,\n\t\tnodes:     map[node.Identity]*nodeEntry{},\n\t\tdatapath:  datapath,\n\t\tcloseChan: make(chan struct{}),\n\t}\n\n\tm.metricEventsReceived = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tNamespace: metrics.Namespace,\n\t\tSubsystem: \"nodes\",\n\t\tName:      name + \"_events_received_total\",\n\t\tHelp:      \"Number of node events received\",\n\t}, []string{\"eventType\", \"source\"})\n\n\tm.metricNumNodes = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: metrics.Namespace,\n\t\tSubsystem: \"nodes\",\n\t\tName:      name + \"_num\",\n\t\tHelp:      \"Number of nodes managed\",\n\t})\n\n\tm.metricDatapathValidations = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: metrics.Namespace,\n\t\tSubsystem: \"nodes\",\n\t\tName:      name + \"_datapath_validations_total\",\n\t\tHelp:      \"Number of validation calls to implement the datapath implemention of a node\",\n\t})\n\n\terr := metrics.RegisterList([]prometheus.Collector{m.metricDatapathValidations, m.metricEventsReceived, m.metricNumNodes})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgo m.backgroundSync()\n\n\treturn m, nil\n}\n\n\/\/ Close shuts down a node manager\nfunc (m *Manager) Close() {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tclose(m.closeChan)\n\n\tmetrics.Unregister(m.metricNumNodes)\n\tmetrics.Unregister(m.metricEventsReceived)\n\tmetrics.Unregister(m.metricDatapathValidations)\n\n\t\/\/ delete all nodes to clean up the datapath for each node\n\tfor _, n := range m.nodes {\n\t\tn.mutex.Lock()\n\t\tm.datapath.NodeDelete(n.node)\n\t\tn.mutex.Unlock()\n\t}\n}\n\n\/\/ ClusterSizeDependantInterval returns a time.Duration that is dependant on\n\/\/ the cluster size, i.e. the number of nodes that have been discovered. This\n\/\/ can be used to control sync intervals of shared or centralized resources to\n\/\/ avoid overloading these resources as the cluster grows.\n\/\/\n\/\/ Example sync interval with baseInterval = 1 * time.Minute\n\/\/\n\/\/ nodes | sync interval\n\/\/ ------+-----------------\n\/\/ 1     |   41.588830833s\n\/\/ 2     | 1m05.916737320s\n\/\/ 4     | 1m36.566274746s\n\/\/ 8     | 2m11.833474640s\n\/\/ 16    | 2m49.992800643s\n\/\/ 32    | 3m29.790453687s\n\/\/ 64    | 4m10.463236193s\n\/\/ 128   | 4m51.588744261s\n\/\/ 256   | 5m32.944565093s\n\/\/ 512   | 6m14.416550710s\n\/\/ 1024  | 6m55.946873494s\n\/\/ 2048  | 7m37.506428894s\n\/\/ 4096  | 8m19.080616652s\n\/\/ 8192  | 9m00.662124608s\n\/\/ 16384 | 9m42.247293667s\nfunc (m *Manager) ClusterSizeDependantInterval(baseInterval time.Duration) time.Duration {\n\tm.mutex.RLock()\n\tnumNodes := len(m.nodes)\n\tm.mutex.RUnlock()\n\n\t\/\/ no nodes are being managed, no work will be performed, return\n\t\/\/ baseInterval to check again in a reasonable timeframe\n\tif numNodes == 0 {\n\t\treturn baseInterval\n\t}\n\n\twaitNanoseconds := float64(baseInterval.Nanoseconds()) * math.Log1p(float64(numNodes))\n\treturn time.Duration(int64(waitNanoseconds))\n\n}\n\nfunc (m *Manager) backgroundSyncInterval() time.Duration {\n\treturn m.ClusterSizeDependantInterval(baseBackgroundSyncInterval)\n}\n\nfunc (m *Manager) backgroundSync() {\n\tfor {\n\t\tsyncInterval := m.backgroundSyncInterval()\n\t\tlog.WithField(\"syncInterval\", syncInterval.String()).Debug(\"Performing regular background work\")\n\n\t\t\/\/ get a copy of the node identities to avoid locking the entire manager\n\t\t\/\/ throughout the process of running the datapath validation.\n\t\tnodes := m.GetNodeIdentities()\n\t\tfor _, nodeIdentity := range nodes {\n\t\t\t\/\/ Retrieve latest node information in case any event\n\t\t\t\/\/ changed the node since the call to GetNodes()\n\t\t\tm.mutex.RLock()\n\t\t\tentry, ok := m.nodes[nodeIdentity]\n\t\t\tif !ok {\n\t\t\t\tm.mutex.RUnlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tentry.mutex.Lock()\n\t\t\tm.mutex.RUnlock()\n\t\t\tm.datapath.NodeValidateImplementation(entry.node)\n\t\t\tentry.mutex.Unlock()\n\n\t\t\tm.metricDatapathValidations.Inc()\n\t\t}\n\n\t\tselect {\n\t\tcase <-m.closeChan:\n\t\t\treturn\n\t\tcase <-time.After(syncInterval):\n\t\t}\n\t}\n}\n\n\/\/ overwriteAllowed returns true if an update from newSource can overwrite a node owned by oldSource.\nfunc overwriteAllowed(oldSource, newSource node.Source) bool {\n\tswitch newSource {\n\t\/\/ the local node always takes precedence\n\tcase node.FromLocalNode:\n\t\treturn true\n\n\t\/\/ agent local updates can overwrite everything except for the local\n\t\/\/ node\n\tcase node.FromAgentLocal:\n\t\treturn oldSource != node.FromLocalNode\n\n\t\/\/ kvstore updates can overwrite everything except agent local updates and local node\n\tcase node.FromKVStore:\n\t\treturn oldSource != node.FromAgentLocal && oldSource != node.FromLocalNode\n\n\t\/\/ kubernetes updates can only overwrite kubernetes nodes\n\tcase node.FromKubernetes:\n\t\treturn oldSource != node.FromAgentLocal && oldSource != node.FromLocalNode && oldSource != node.FromKVStore\n\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\/\/ NodeSoftUpdated is called after the information of a node has be upated but\n\/\/ unlike a NodeUpdated does not require the datapath to be updated.\nfunc (m *Manager) NodeSoftUpdated(n node.Node) {\n\tlog.Debugf(\"Received soft node update event from %s: %#v\", n.Source, n)\n\tm.nodeUpdated(n, false)\n}\n\n\/\/ NodeUpdated is called after the information of a node has been updated. The\n\/\/ node in the manager is added or updated if the source is allowed to update\n\/\/ the node. If an update or addition has occurred, NodeUpdate() of the datapath\n\/\/ interface is invoked.\nfunc (m *Manager) NodeUpdated(n node.Node) {\n\tlog.Debugf(\"Received node update event from %s: %#v\", n.Source, n)\n\tm.nodeUpdated(n, true)\n}\n\nfunc (m *Manager) nodeUpdated(n node.Node, dpUpdate bool) {\n\tnodeIdentity := n.Identity()\n\n\tm.mutex.Lock()\n\tentry, oldNodeExists := m.nodes[nodeIdentity]\n\tif oldNodeExists {\n\t\tm.metricEventsReceived.WithLabelValues(\"update\", string(n.Source)).Inc()\n\n\t\tif !overwriteAllowed(entry.node.Source, n.Source) {\n\t\t\tm.mutex.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\tentry.mutex.Lock()\n\t\tm.mutex.Unlock()\n\t\toldNode := entry.node\n\t\tentry.node = n\n\t\tif dpUpdate {\n\t\t\tm.datapath.NodeUpdate(oldNode, entry.node)\n\t\t}\n\t\tentry.mutex.Unlock()\n\t} else {\n\t\tm.metricEventsReceived.WithLabelValues(\"add\", string(n.Source)).Inc()\n\t\tm.metricNumNodes.Inc()\n\n\t\tentry = &nodeEntry{node: n}\n\t\tentry.mutex.Lock()\n\t\tm.nodes[nodeIdentity] = entry\n\t\tm.mutex.Unlock()\n\t\tif dpUpdate {\n\t\t\tm.datapath.NodeAdd(entry.node)\n\t\t}\n\t\tentry.mutex.Unlock()\n\t}\n}\n\n\/\/ NodeDeleted is called after a node has been deleted. It removes the node\n\/\/ from the manager if the node is still owned by the source of which the event\n\/\/ orgins from. If the node was removed, NodeDelete() is invoked of the\n\/\/ datapath interface.\nfunc (m *Manager) NodeDeleted(n node.Node) {\n\tm.metricEventsReceived.WithLabelValues(\"delete\", string(n.Source)).Inc()\n\n\tlog.Debugf(\"Received node delete event from %s\", n.Source)\n\n\tnodeIdentity := n.Identity()\n\n\tm.mutex.Lock()\n\tentry, oldNodeExists := m.nodes[nodeIdentity]\n\tif !oldNodeExists {\n\t\tm.mutex.Unlock()\n\t\treturn\n\t}\n\n\t\/\/ If the source is Kubernetes and the node is the node we are running on\n\t\/\/ Kubernetes is giving us a hint it is about to delete our node. Close down\n\t\/\/ the agent gracefully in this case.\n\tif n.Source != entry.node.Source {\n\t\tm.mutex.Unlock()\n\t\tif n.IsLocal() && n.Source == node.FromKubernetes {\n\t\t\tlog.Debugf(\"Kubernetes is deleting local node, close manager\")\n\t\t\tm.Close()\n\t\t} else {\n\t\t\tlog.Debugf(\"Ignoring delete event of node %s from source %s. The node is owned by %s\",\n\t\t\t\tn.Name, n.Source, entry.node.Source)\n\t\t}\n\t\treturn\n\t}\n\n\tm.metricNumNodes.Dec()\n\n\tentry.mutex.Lock()\n\tdelete(m.nodes, nodeIdentity)\n\tm.mutex.Unlock()\n\tm.datapath.NodeDelete(n)\n\tentry.mutex.Unlock()\n}\n\n\/\/ Exists returns true if a node with the name exists\nfunc (m *Manager) Exists(id node.Identity) bool {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\t_, ok := m.nodes[id]\n\treturn ok\n}\n\n\/\/ GetNodeIdentities returns a list of all node identities store in node\n\/\/ manager.\nfunc (m *Manager) GetNodeIdentities() []node.Identity {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\n\tnodes := make([]node.Identity, 0, len(m.nodes))\n\tfor nodeIdentity := range m.nodes {\n\t\tnodes = append(nodes, nodeIdentity)\n\t}\n\n\treturn nodes\n}\n\n\/\/ GetNodes returns a copy of all of the nodes as a map from Identity to Node.\nfunc (m *Manager) GetNodes() map[node.Identity]node.Node {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\n\tnodes := make(map[node.Identity]node.Node)\n\tfor nodeIdentity, entry := range m.nodes {\n\t\tentry.mutex.Lock()\n\t\tnodes[nodeIdentity] = entry.node\n\t\tentry.mutex.Unlock()\n\t}\n\n\treturn nodes\n}\n\n\/\/ DeleteAllNodes deletes all nodes from the node maanger.\nfunc (m *Manager) DeleteAllNodes() {\n\tm.mutex.Lock()\n\tfor _, entry := range m.nodes {\n\t\tentry.mutex.Lock()\n\t\tm.datapath.NodeDelete(entry.node)\n\t\tentry.mutex.Unlock()\n\t}\n\tm.nodes = map[node.Identity]*nodeEntry{}\n\tm.mutex.Unlock()\n}\n<commit_msg>node\/manager: add a subscription event based mechanism for node events<commit_after>\/\/ Copyright 2016-2019 Authors of Cilium\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage manager\n\nimport (\n\t\"math\"\n\t\"time\"\n\n\t\"github.com\/cilium\/cilium\/pkg\/datapath\"\n\t\"github.com\/cilium\/cilium\/pkg\/lock\"\n\t\"github.com\/cilium\/cilium\/pkg\/metrics\"\n\t\"github.com\/cilium\/cilium\/pkg\/node\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\nvar (\n\tbaseBackgroundSyncInterval = time.Minute\n)\n\ntype nodeEntry struct {\n\t\/\/ mutex serves two purposes:\n\t\/\/ 1. Serialize any direct access to the node field in this entry.\n\t\/\/ 2. Serialize all calls do the datapath layer for a particular node.\n\t\/\/\n\t\/\/ See description of Manager.mutex for more details\n\t\/\/\n\t\/\/ If both the nodeEntry.mutex and Manager.mutex must be held, then the\n\t\/\/ Manager.mutex must *always* be acquired first.\n\tmutex lock.Mutex\n\tnode  node.Node\n}\n\n\/\/ Manager is the entity that manages a collection of nodes\ntype Manager struct {\n\t\/\/ mutex is the lock protecting access to the nodes map. The mutex must\n\t\/\/ be held for any access of the nodes map.\n\t\/\/\n\t\/\/ The manager mutex works together with the entry mutex in the\n\t\/\/ following way to minimize the duration the manager mutex is held:\n\t\/\/\n\t\/\/ 1. Acquire manager mutex to safely access nodes map and to retrieve\n\t\/\/    node entry.\n\t\/\/ 2. Acquire mutex of the entry while the manager mutex is still held.\n\t\/\/    This guarantees that no change to the entry has happened.\n\t\/\/ 3. Release of the manager mutex to unblock changes or reads to other\n\t\/\/    node entries.\n\t\/\/ 4. Change of entry data or performing of datapath interactions\n\t\/\/ 5. Release of the entry mutex\n\t\/\/\n\t\/\/ If both the nodeEntry.mutex and Manager.mutex must be held, then the\n\t\/\/ Manager.mutex must *always* be acquired first.\n\tmutex lock.RWMutex\n\n\t\/\/ nodes is the list of nodes. Access must be protected via mutex.\n\tnodes map[node.Identity]*nodeEntry\n\n\t\/\/ nodeHandlersMu protects the nodeHandlers map against concurrent access.\n\tnodeHandlersMu lock.RWMutex\n\t\/\/ nodeHandlers has a slice containing all node handlers subscribed to node\n\t\/\/ events.\n\tnodeHandlers map[datapath.NodeHandler]struct{}\n\n\t\/\/ closeChan is closed when the manager is closed\n\tcloseChan chan struct{}\n\n\t\/\/ name is the name of the manager. It must be unique and feasibility\n\t\/\/ to be used a prometheus metric name.\n\tname string\n\n\t\/\/ metricEventsReceived is the prometheus metric to track the number of\n\t\/\/ node events received\n\tmetricEventsReceived *prometheus.CounterVec\n\n\t\/\/ metricNumNodes is the prometheus metric to track the number of nodes\n\t\/\/ being managed\n\tmetricNumNodes prometheus.Gauge\n\n\t\/\/ metricDatapathValidations is the prometheus metric to track the\n\t\/\/ number of datapath node validation calls\n\tmetricDatapathValidations prometheus.Counter\n}\n\n\/\/ Subscribe subscribes the given node handler to node events.\nfunc (m *Manager) Subscribe(nh datapath.NodeHandler) {\n\tm.nodeHandlersMu.Lock()\n\tm.nodeHandlers[nh] = struct{}{}\n\tm.nodeHandlersMu.Unlock()\n\t\/\/ Add all nodes already received by the manager.\n\tfor _, v := range m.nodes {\n\t\tv.mutex.Lock()\n\t\tnh.NodeAdd(v.node)\n\t\tv.mutex.Unlock()\n\t}\n}\n\n\/\/ Unsubscribe unsubscribes the given node handler with node events.\nfunc (m *Manager) Unsubscribe(nh datapath.NodeHandler) {\n\tm.nodeHandlersMu.Lock()\n\tdelete(m.nodeHandlers, nh)\n\tm.nodeHandlersMu.Unlock()\n}\n\n\/\/ Iter executes the given function in all subscribed node handlers.\nfunc (m *Manager) Iter(f func(nh datapath.NodeHandler)) {\n\tm.nodeHandlersMu.RLock()\n\tdefer m.nodeHandlersMu.RUnlock()\n\n\tfor nh := range m.nodeHandlers {\n\t\tf(nh)\n\t}\n}\n\n\/\/ NewManager returns a new node manager\nfunc NewManager(name string, dp datapath.NodeHandler) (*Manager, error) {\n\tm := &Manager{\n\t\tname:         name,\n\t\tnodes:        map[node.Identity]*nodeEntry{},\n\t\tnodeHandlers: map[datapath.NodeHandler]struct{}{},\n\t\tcloseChan:    make(chan struct{}),\n\t}\n\tm.Subscribe(dp)\n\n\tm.metricEventsReceived = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tNamespace: metrics.Namespace,\n\t\tSubsystem: \"nodes\",\n\t\tName:      name + \"_events_received_total\",\n\t\tHelp:      \"Number of node events received\",\n\t}, []string{\"eventType\", \"source\"})\n\n\tm.metricNumNodes = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace: metrics.Namespace,\n\t\tSubsystem: \"nodes\",\n\t\tName:      name + \"_num\",\n\t\tHelp:      \"Number of nodes managed\",\n\t})\n\n\tm.metricDatapathValidations = prometheus.NewCounter(prometheus.CounterOpts{\n\t\tNamespace: metrics.Namespace,\n\t\tSubsystem: \"nodes\",\n\t\tName:      name + \"_datapath_validations_total\",\n\t\tHelp:      \"Number of validation calls to implement the datapath implemention of a node\",\n\t})\n\n\terr := metrics.RegisterList([]prometheus.Collector{m.metricDatapathValidations, m.metricEventsReceived, m.metricNumNodes})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgo m.backgroundSync()\n\n\treturn m, nil\n}\n\n\/\/ Close shuts down a node manager\nfunc (m *Manager) Close() {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\n\tclose(m.closeChan)\n\n\tmetrics.Unregister(m.metricNumNodes)\n\tmetrics.Unregister(m.metricEventsReceived)\n\tmetrics.Unregister(m.metricDatapathValidations)\n\n\t\/\/ delete all nodes to clean up the datapath for each node\n\tfor _, n := range m.nodes {\n\t\tn.mutex.Lock()\n\t\tm.Iter(func(nh datapath.NodeHandler) {\n\t\t\tnh.NodeDelete(n.node)\n\t\t})\n\t\tn.mutex.Unlock()\n\t}\n}\n\n\/\/ ClusterSizeDependantInterval returns a time.Duration that is dependant on\n\/\/ the cluster size, i.e. the number of nodes that have been discovered. This\n\/\/ can be used to control sync intervals of shared or centralized resources to\n\/\/ avoid overloading these resources as the cluster grows.\n\/\/\n\/\/ Example sync interval with baseInterval = 1 * time.Minute\n\/\/\n\/\/ nodes | sync interval\n\/\/ ------+-----------------\n\/\/ 1     |   41.588830833s\n\/\/ 2     | 1m05.916737320s\n\/\/ 4     | 1m36.566274746s\n\/\/ 8     | 2m11.833474640s\n\/\/ 16    | 2m49.992800643s\n\/\/ 32    | 3m29.790453687s\n\/\/ 64    | 4m10.463236193s\n\/\/ 128   | 4m51.588744261s\n\/\/ 256   | 5m32.944565093s\n\/\/ 512   | 6m14.416550710s\n\/\/ 1024  | 6m55.946873494s\n\/\/ 2048  | 7m37.506428894s\n\/\/ 4096  | 8m19.080616652s\n\/\/ 8192  | 9m00.662124608s\n\/\/ 16384 | 9m42.247293667s\nfunc (m *Manager) ClusterSizeDependantInterval(baseInterval time.Duration) time.Duration {\n\tm.mutex.RLock()\n\tnumNodes := len(m.nodes)\n\tm.mutex.RUnlock()\n\n\t\/\/ no nodes are being managed, no work will be performed, return\n\t\/\/ baseInterval to check again in a reasonable timeframe\n\tif numNodes == 0 {\n\t\treturn baseInterval\n\t}\n\n\twaitNanoseconds := float64(baseInterval.Nanoseconds()) * math.Log1p(float64(numNodes))\n\treturn time.Duration(int64(waitNanoseconds))\n\n}\n\nfunc (m *Manager) backgroundSyncInterval() time.Duration {\n\treturn m.ClusterSizeDependantInterval(baseBackgroundSyncInterval)\n}\n\nfunc (m *Manager) backgroundSync() {\n\tfor {\n\t\tsyncInterval := m.backgroundSyncInterval()\n\t\tlog.WithField(\"syncInterval\", syncInterval.String()).Debug(\"Performing regular background work\")\n\n\t\t\/\/ get a copy of the node identities to avoid locking the entire manager\n\t\t\/\/ throughout the process of running the datapath validation.\n\t\tnodes := m.GetNodeIdentities()\n\t\tfor _, nodeIdentity := range nodes {\n\t\t\t\/\/ Retrieve latest node information in case any event\n\t\t\t\/\/ changed the node since the call to GetNodes()\n\t\t\tm.mutex.RLock()\n\t\t\tentry, ok := m.nodes[nodeIdentity]\n\t\t\tif !ok {\n\t\t\t\tm.mutex.RUnlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tentry.mutex.Lock()\n\t\t\tm.mutex.RUnlock()\n\t\t\tm.Iter(func(nh datapath.NodeHandler) {\n\t\t\t\tnh.NodeValidateImplementation(entry.node)\n\t\t\t})\n\t\t\tentry.mutex.Unlock()\n\n\t\t\tm.metricDatapathValidations.Inc()\n\t\t}\n\n\t\tselect {\n\t\tcase <-m.closeChan:\n\t\t\treturn\n\t\tcase <-time.After(syncInterval):\n\t\t}\n\t}\n}\n\n\/\/ overwriteAllowed returns true if an update from newSource can overwrite a node owned by oldSource.\nfunc overwriteAllowed(oldSource, newSource node.Source) bool {\n\tswitch newSource {\n\t\/\/ the local node always takes precedence\n\tcase node.FromLocalNode:\n\t\treturn true\n\n\t\/\/ agent local updates can overwrite everything except for the local\n\t\/\/ node\n\tcase node.FromAgentLocal:\n\t\treturn oldSource != node.FromLocalNode\n\n\t\/\/ kvstore updates can overwrite everything except agent local updates and local node\n\tcase node.FromKVStore:\n\t\treturn oldSource != node.FromAgentLocal && oldSource != node.FromLocalNode\n\n\t\/\/ kubernetes updates can only overwrite kubernetes nodes\n\tcase node.FromKubernetes:\n\t\treturn oldSource != node.FromAgentLocal && oldSource != node.FromLocalNode && oldSource != node.FromKVStore\n\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\/\/ NodeSoftUpdated is called after the information of a node has be upated but\n\/\/ unlike a NodeUpdated does not require the datapath to be updated.\nfunc (m *Manager) NodeSoftUpdated(n node.Node) {\n\tlog.Debugf(\"Received soft node update event from %s: %#v\", n.Source, n)\n\tm.nodeUpdated(n, false)\n}\n\n\/\/ NodeUpdated is called after the information of a node has been updated. The\n\/\/ node in the manager is added or updated if the source is allowed to update\n\/\/ the node. If an update or addition has occurred, NodeUpdate() of the datapath\n\/\/ interface is invoked.\nfunc (m *Manager) NodeUpdated(n node.Node) {\n\tlog.Debugf(\"Received node update event from %s: %#v\", n.Source, n)\n\tm.nodeUpdated(n, true)\n}\n\nfunc (m *Manager) nodeUpdated(n node.Node, dpUpdate bool) {\n\tnodeIdentity := n.Identity()\n\n\tm.mutex.Lock()\n\tentry, oldNodeExists := m.nodes[nodeIdentity]\n\tif oldNodeExists {\n\t\tm.metricEventsReceived.WithLabelValues(\"update\", string(n.Source)).Inc()\n\n\t\tif !overwriteAllowed(entry.node.Source, n.Source) {\n\t\t\tm.mutex.Unlock()\n\t\t\treturn\n\t\t}\n\n\t\tentry.mutex.Lock()\n\t\tm.mutex.Unlock()\n\t\toldNode := entry.node\n\t\tentry.node = n\n\t\tif dpUpdate {\n\t\t\tm.Iter(func(nh datapath.NodeHandler) {\n\t\t\t\tnh.NodeUpdate(oldNode, entry.node)\n\t\t\t})\n\t\t}\n\t\tentry.mutex.Unlock()\n\t} else {\n\t\tm.metricEventsReceived.WithLabelValues(\"add\", string(n.Source)).Inc()\n\t\tm.metricNumNodes.Inc()\n\n\t\tentry = &nodeEntry{node: n}\n\t\tentry.mutex.Lock()\n\t\tm.nodes[nodeIdentity] = entry\n\t\tm.mutex.Unlock()\n\t\tif dpUpdate {\n\t\t\tm.Iter(func(nh datapath.NodeHandler) {\n\t\t\t\tnh.NodeAdd(entry.node)\n\t\t\t})\n\t\t}\n\t\tentry.mutex.Unlock()\n\t}\n}\n\n\/\/ NodeDeleted is called after a node has been deleted. It removes the node\n\/\/ from the manager if the node is still owned by the source of which the event\n\/\/ orgins from. If the node was removed, NodeDelete() is invoked of the\n\/\/ datapath interface.\nfunc (m *Manager) NodeDeleted(n node.Node) {\n\tm.metricEventsReceived.WithLabelValues(\"delete\", string(n.Source)).Inc()\n\n\tlog.Debugf(\"Received node delete event from %s\", n.Source)\n\n\tnodeIdentity := n.Identity()\n\n\tm.mutex.Lock()\n\tentry, oldNodeExists := m.nodes[nodeIdentity]\n\tif !oldNodeExists {\n\t\tm.mutex.Unlock()\n\t\treturn\n\t}\n\n\t\/\/ If the source is Kubernetes and the node is the node we are running on\n\t\/\/ Kubernetes is giving us a hint it is about to delete our node. Close down\n\t\/\/ the agent gracefully in this case.\n\tif n.Source != entry.node.Source {\n\t\tm.mutex.Unlock()\n\t\tif n.IsLocal() && n.Source == node.FromKubernetes {\n\t\t\tlog.Debugf(\"Kubernetes is deleting local node, close manager\")\n\t\t\tm.Close()\n\t\t} else {\n\t\t\tlog.Debugf(\"Ignoring delete event of node %s from source %s. The node is owned by %s\",\n\t\t\t\tn.Name, n.Source, entry.node.Source)\n\t\t}\n\t\treturn\n\t}\n\n\tm.metricNumNodes.Dec()\n\n\tentry.mutex.Lock()\n\tdelete(m.nodes, nodeIdentity)\n\tm.mutex.Unlock()\n\tm.Iter(func(nh datapath.NodeHandler) {\n\t\tnh.NodeDelete(n)\n\t})\n\tentry.mutex.Unlock()\n}\n\n\/\/ Exists returns true if a node with the name exists\nfunc (m *Manager) Exists(id node.Identity) bool {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\t_, ok := m.nodes[id]\n\treturn ok\n}\n\n\/\/ GetNodeIdentities returns a list of all node identities store in node\n\/\/ manager.\nfunc (m *Manager) GetNodeIdentities() []node.Identity {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\n\tnodes := make([]node.Identity, 0, len(m.nodes))\n\tfor nodeIdentity := range m.nodes {\n\t\tnodes = append(nodes, nodeIdentity)\n\t}\n\n\treturn nodes\n}\n\n\/\/ GetNodes returns a copy of all of the nodes as a map from Identity to Node.\nfunc (m *Manager) GetNodes() map[node.Identity]node.Node {\n\tm.mutex.RLock()\n\tdefer m.mutex.RUnlock()\n\n\tnodes := make(map[node.Identity]node.Node)\n\tfor nodeIdentity, entry := range m.nodes {\n\t\tentry.mutex.Lock()\n\t\tnodes[nodeIdentity] = entry.node\n\t\tentry.mutex.Unlock()\n\t}\n\n\treturn nodes\n}\n\n\/\/ DeleteAllNodes deletes all nodes from the node maanger.\nfunc (m *Manager) DeleteAllNodes() {\n\tm.mutex.Lock()\n\tfor _, entry := range m.nodes {\n\t\tentry.mutex.Lock()\n\t\tm.Iter(func(nh datapath.NodeHandler) {\n\t\t\tnh.NodeDelete(entry.node)\n\t\t})\n\t\tentry.mutex.Unlock()\n\t}\n\tm.nodes = map[node.Identity]*nodeEntry{}\n\tm.mutex.Unlock()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2014 Google Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage scheduler\n\nimport (\n\t\"math\"\n\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/labels\"\n\t\"github.com\/golang\/glog\"\n)\n\n\/\/ the unused capacity is calculated on a scale of 0-10\n\/\/ 0 being the lowest priority and 10 being the highest\nfunc calculateScore(requested, capacity int64, node string) int {\n\tif capacity == 0 {\n\t\treturn 0\n\t}\n\tif requested > capacity {\n\t\tglog.Errorf(\"Combined requested resources from existing pods exceeds capacity on minion: %s\", node)\n\t\treturn 0\n\t}\n\treturn int(((capacity - requested) * 10) \/ capacity)\n}\n\n\/\/ Calculate the occupancy on a node.  'node' has information about the resources on the node.\n\/\/ 'pods' is a list of pods currently scheduled on the node.\nfunc calculateOccupancy(pod api.Pod, node api.Node, pods []api.Pod) HostPriority {\n\ttotalMilliCPU := int64(0)\n\ttotalMemory := int64(0)\n\tfor _, existingPod := range pods {\n\t\tfor _, container := range existingPod.Spec.Containers {\n\t\t\ttotalMilliCPU += container.Resources.Limits.Cpu().MilliValue()\n\t\t\ttotalMemory += container.Resources.Limits.Memory().Value()\n\t\t}\n\t}\n\t\/\/ Add the resources requested by the current pod being scheduled.\n\t\/\/ This also helps differentiate between differently sized, but empty, minions.\n\tfor _, container := range pod.Spec.Containers {\n\t\ttotalMilliCPU += container.Resources.Limits.Cpu().MilliValue()\n\t\ttotalMemory += container.Resources.Limits.Memory().Value()\n\t}\n\n\tcapacityMilliCPU := node.Status.Capacity.Cpu().MilliValue()\n\tcapacityMemory := node.Status.Capacity.Memory().Value()\n\n\tcpuScore := calculateScore(totalMilliCPU, capacityMilliCPU, node.Name)\n\tmemoryScore := calculateScore(totalMemory, capacityMemory, node.Name)\n\tglog.V(4).Infof(\n\t\t\"%v -> %v: Least Requested Priority, AbsoluteRequested: (%d, %d) \/ (%d, %d) Score: (%d, %d)\",\n\t\tpod.Name, node.Name,\n\t\ttotalMilliCPU, totalMemory,\n\t\tcapacityMilliCPU, capacityMemory,\n\t\tcpuScore, memoryScore,\n\t)\n\n\treturn HostPriority{\n\t\thost:  node.Name,\n\t\tscore: int((cpuScore + memoryScore) \/ 2),\n\t}\n}\n\n\/\/ LeastRequestedPriority is a priority function that favors nodes with fewer requested resources.\n\/\/ It calculates the percentage of memory and CPU requested by pods scheduled on the node, and prioritizes\n\/\/ based on the minimum of the average of the fraction of requested to capacity.\n\/\/ Details: (Sum(requested cpu) \/ Capacity + Sum(requested memory) \/ Capacity) * 50\nfunc LeastRequestedPriority(pod api.Pod, podLister PodLister, minionLister MinionLister) (HostPriorityList, error) {\n\tnodes, err := minionLister.List()\n\tif err != nil {\n\t\treturn HostPriorityList{}, err\n\t}\n\tpodsToMachines, err := MapPodsToMachines(podLister)\n\n\tlist := HostPriorityList{}\n\tfor _, node := range nodes.Items {\n\t\tlist = append(list, calculateOccupancy(pod, node, podsToMachines[node.Name]))\n\t}\n\treturn list, nil\n}\n\ntype NodeLabelPrioritizer struct {\n\tlabel    string\n\tpresence bool\n}\n\nfunc NewNodeLabelPriority(label string, presence bool) PriorityFunction {\n\tlabelPrioritizer := &NodeLabelPrioritizer{\n\t\tlabel:    label,\n\t\tpresence: presence,\n\t}\n\treturn labelPrioritizer.CalculateNodeLabelPriority\n}\n\n\/\/ CalculateNodeLabelPriority checks whether a particular label exists on a minion or not, regardless of its value.\n\/\/ If presence is true, prioritizes minions that have the specified label, regardless of value.\n\/\/ If presence is false, prioritizes minions that do not have the specified label.\nfunc (n *NodeLabelPrioritizer) CalculateNodeLabelPriority(pod api.Pod, podLister PodLister, minionLister MinionLister) (HostPriorityList, error) {\n\tvar score int\n\tminions, err := minionLister.List()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlabeledMinions := map[string]bool{}\n\tfor _, minion := range minions.Items {\n\t\texists := labels.Set(minion.Labels).Has(n.label)\n\t\tlabeledMinions[minion.Name] = (exists && n.presence) || (!exists && !n.presence)\n\t}\n\n\tresult := []HostPriority{}\n\t\/\/score int - scale of 0-10\n\t\/\/ 0 being the lowest priority and 10 being the highest\n\tfor minionName, success := range labeledMinions {\n\t\tif success {\n\t\t\tscore = 10\n\t\t} else {\n\t\t\tscore = 0\n\t\t}\n\t\tresult = append(result, HostPriority{host: minionName, score: score})\n\t}\n\treturn result, nil\n}\n\n\/\/ BalancedResourceAllocation favors nodes with balanced resource usage rate.\n\/\/ BalancedResourceAllocation should **NOT** be used alone, and **MUST** be used together with LeastRequestedPriority.\n\/\/ It calculates the difference between the cpu and memory fracion of capacity, and prioritizes the host based on how\n\/\/ close the two metrics are to each other.\n\/\/ Detail: score = 10 - abs(cpuFraction-memoryFraction)*10. The algorithm is partly inspired by:\n\/\/ \"Wei Huang et al. An Energy Efficient Virtual Machine Placement Algorithm with Balanced Resource Utilization\"\nfunc BalancedResourceAllocation(pod api.Pod, podLister PodLister, minionLister MinionLister) (HostPriorityList, error) {\n\tnodes, err := minionLister.List()\n\tif err != nil {\n\t\treturn HostPriorityList{}, err\n\t}\n\tpodsToMachines, err := MapPodsToMachines(podLister)\n\n\tlist := HostPriorityList{}\n\tfor _, node := range nodes.Items {\n\t\tlist = append(list, calculateBalancedResourceAllocation(pod, node, podsToMachines[node.Name]))\n\t}\n\treturn list, nil\n}\n\nfunc calculateBalancedResourceAllocation(pod api.Pod, node api.Node, pods []api.Pod) HostPriority {\n\ttotalMilliCPU := int64(0)\n\ttotalMemory := int64(0)\n\tscore := int(0)\n\tfor _, existingPod := range pods {\n\t\tfor _, container := range existingPod.Spec.Containers {\n\t\t\ttotalMilliCPU += container.Resources.Limits.Cpu().MilliValue()\n\t\t\ttotalMemory += container.Resources.Limits.Memory().Value()\n\t\t}\n\t}\n\t\/\/ Add the resources requested by the current pod being scheduled.\n\t\/\/ This also helps differentiate between differently sized, but empty, minions.\n\tfor _, container := range pod.Spec.Containers {\n\t\ttotalMilliCPU += container.Resources.Limits.Cpu().MilliValue()\n\t\ttotalMemory += container.Resources.Limits.Memory().Value()\n\t}\n\n\tcapacityMilliCPU := node.Status.Capacity.Cpu().MilliValue()\n\tcapacityMemory := node.Status.Capacity.Memory().Value()\n\n\tcpuFraction := fractionOfCapacity(totalMilliCPU, capacityMilliCPU, node.Name)\n\tmemoryFraction := fractionOfCapacity(totalMemory, capacityMemory, node.Name)\n\tif cpuFraction >= 1 || memoryFraction >= 1 {\n\t\t\/\/ if requested >= capacity, the corresponding host should never be preferrred.\n\t\tscore = 0\n\t} else {\n\t\t\/\/ Upper and lower boundary of difference between cpuFraction and memoryFraction are -1 and 1\n\t\t\/\/ respectively. Multilying the absolute value of the difference by 10 scales the value to\n\t\t\/\/ 0-10 with 0 representing well balanced allocation and 10 poorly balanced. Subtracting it from\n\t\t\/\/ 10 leads to the score which also scales from 0 to 10 while 10 representing well balanced.\n\t\tdiff := math.Abs(cpuFraction - memoryFraction)\n\t\tscore = int(10 - diff*10)\n\t}\n\tglog.V(4).Infof(\n\t\t\"%v -> %v: Balanced Resource Allocation, Absolute\/Requested: (%d, %d) \/ (%d, %d) Score: (%d)\",\n\t\tpod.Name, node.Name,\n\t\ttotalMilliCPU, totalMemory,\n\t\tcapacityMilliCPU, capacityMemory,\n\t\tscore,\n\t)\n\n\treturn HostPriority{\n\t\thost:  node.Name,\n\t\tscore: score,\n\t}\n}\n\nfunc fractionOfCapacity(requested, capacity int64, node string) float64 {\n\tif capacity == 0 {\n\t\treturn 1\n\t}\n\treturn float64(requested) \/ float64(capacity)\n}\n<commit_msg>Update priorities.go<commit_after>\/*\nCopyright 2014 Google Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage scheduler\n\nimport (\n\t\"math\"\n\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/labels\"\n\t\"github.com\/golang\/glog\"\n)\n\n\/\/ the unused capacity is calculated on a scale of 0-10\n\/\/ 0 being the lowest priority and 10 being the highest\nfunc calculateScore(requested, capacity int64, node string) int {\n\tif capacity == 0 {\n\t\treturn 0\n\t}\n\tif requested > capacity {\n\t\tglog.Infof(\"Combined requested resources from existing pods exceeds capacity on minion: %s\", node)\n\t\treturn 0\n\t}\n\treturn int(((capacity - requested) * 10) \/ capacity)\n}\n\n\/\/ Calculate the occupancy on a node.  'node' has information about the resources on the node.\n\/\/ 'pods' is a list of pods currently scheduled on the node.\nfunc calculateOccupancy(pod api.Pod, node api.Node, pods []api.Pod) HostPriority {\n\ttotalMilliCPU := int64(0)\n\ttotalMemory := int64(0)\n\tfor _, existingPod := range pods {\n\t\tfor _, container := range existingPod.Spec.Containers {\n\t\t\ttotalMilliCPU += container.Resources.Limits.Cpu().MilliValue()\n\t\t\ttotalMemory += container.Resources.Limits.Memory().Value()\n\t\t}\n\t}\n\t\/\/ Add the resources requested by the current pod being scheduled.\n\t\/\/ This also helps differentiate between differently sized, but empty, minions.\n\tfor _, container := range pod.Spec.Containers {\n\t\ttotalMilliCPU += container.Resources.Limits.Cpu().MilliValue()\n\t\ttotalMemory += container.Resources.Limits.Memory().Value()\n\t}\n\n\tcapacityMilliCPU := node.Status.Capacity.Cpu().MilliValue()\n\tcapacityMemory := node.Status.Capacity.Memory().Value()\n\n\tcpuScore := calculateScore(totalMilliCPU, capacityMilliCPU, node.Name)\n\tmemoryScore := calculateScore(totalMemory, capacityMemory, node.Name)\n\tglog.V(4).Infof(\n\t\t\"%v -> %v: Least Requested Priority, Absolute\/Requested: (%d, %d) \/ (%d, %d) Score: (%d, %d)\",\n\t\tpod.Name, node.Name,\n\t\ttotalMilliCPU, totalMemory,\n\t\tcapacityMilliCPU, capacityMemory,\n\t\tcpuScore, memoryScore,\n\t)\n\n\treturn HostPriority{\n\t\thost:  node.Name,\n\t\tscore: int((cpuScore + memoryScore) \/ 2),\n\t}\n}\n\n\/\/ LeastRequestedPriority is a priority function that favors nodes with fewer requested resources.\n\/\/ It calculates the percentage of memory and CPU requested by pods scheduled on the node, and prioritizes\n\/\/ based on the minimum of the average of the fraction of requested to capacity.\n\/\/ Details: (Sum(requested cpu) \/ Capacity + Sum(requested memory) \/ Capacity) * 50\nfunc LeastRequestedPriority(pod api.Pod, podLister PodLister, minionLister MinionLister) (HostPriorityList, error) {\n\tnodes, err := minionLister.List()\n\tif err != nil {\n\t\treturn HostPriorityList{}, err\n\t}\n\tpodsToMachines, err := MapPodsToMachines(podLister)\n\n\tlist := HostPriorityList{}\n\tfor _, node := range nodes.Items {\n\t\tlist = append(list, calculateOccupancy(pod, node, podsToMachines[node.Name]))\n\t}\n\treturn list, nil\n}\n\ntype NodeLabelPrioritizer struct {\n\tlabel    string\n\tpresence bool\n}\n\nfunc NewNodeLabelPriority(label string, presence bool) PriorityFunction {\n\tlabelPrioritizer := &NodeLabelPrioritizer{\n\t\tlabel:    label,\n\t\tpresence: presence,\n\t}\n\treturn labelPrioritizer.CalculateNodeLabelPriority\n}\n\n\/\/ CalculateNodeLabelPriority checks whether a particular label exists on a minion or not, regardless of its value.\n\/\/ If presence is true, prioritizes minions that have the specified label, regardless of value.\n\/\/ If presence is false, prioritizes minions that do not have the specified label.\nfunc (n *NodeLabelPrioritizer) CalculateNodeLabelPriority(pod api.Pod, podLister PodLister, minionLister MinionLister) (HostPriorityList, error) {\n\tvar score int\n\tminions, err := minionLister.List()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlabeledMinions := map[string]bool{}\n\tfor _, minion := range minions.Items {\n\t\texists := labels.Set(minion.Labels).Has(n.label)\n\t\tlabeledMinions[minion.Name] = (exists && n.presence) || (!exists && !n.presence)\n\t}\n\n\tresult := []HostPriority{}\n\t\/\/score int - scale of 0-10\n\t\/\/ 0 being the lowest priority and 10 being the highest\n\tfor minionName, success := range labeledMinions {\n\t\tif success {\n\t\t\tscore = 10\n\t\t} else {\n\t\t\tscore = 0\n\t\t}\n\t\tresult = append(result, HostPriority{host: minionName, score: score})\n\t}\n\treturn result, nil\n}\n\n\/\/ BalancedResourceAllocation favors nodes with balanced resource usage rate.\n\/\/ BalancedResourceAllocation should **NOT** be used alone, and **MUST** be used together with LeastRequestedPriority.\n\/\/ It calculates the difference between the cpu and memory fracion of capacity, and prioritizes the host based on how\n\/\/ close the two metrics are to each other.\n\/\/ Detail: score = 10 - abs(cpuFraction-memoryFraction)*10. The algorithm is partly inspired by:\n\/\/ \"Wei Huang et al. An Energy Efficient Virtual Machine Placement Algorithm with Balanced Resource Utilization\"\nfunc BalancedResourceAllocation(pod api.Pod, podLister PodLister, minionLister MinionLister) (HostPriorityList, error) {\n\tnodes, err := minionLister.List()\n\tif err != nil {\n\t\treturn HostPriorityList{}, err\n\t}\n\tpodsToMachines, err := MapPodsToMachines(podLister)\n\n\tlist := HostPriorityList{}\n\tfor _, node := range nodes.Items {\n\t\tlist = append(list, calculateBalancedResourceAllocation(pod, node, podsToMachines[node.Name]))\n\t}\n\treturn list, nil\n}\n\nfunc calculateBalancedResourceAllocation(pod api.Pod, node api.Node, pods []api.Pod) HostPriority {\n\ttotalMilliCPU := int64(0)\n\ttotalMemory := int64(0)\n\tscore := int(0)\n\tfor _, existingPod := range pods {\n\t\tfor _, container := range existingPod.Spec.Containers {\n\t\t\ttotalMilliCPU += container.Resources.Limits.Cpu().MilliValue()\n\t\t\ttotalMemory += container.Resources.Limits.Memory().Value()\n\t\t}\n\t}\n\t\/\/ Add the resources requested by the current pod being scheduled.\n\t\/\/ This also helps differentiate between differently sized, but empty, minions.\n\tfor _, container := range pod.Spec.Containers {\n\t\ttotalMilliCPU += container.Resources.Limits.Cpu().MilliValue()\n\t\ttotalMemory += container.Resources.Limits.Memory().Value()\n\t}\n\n\tcapacityMilliCPU := node.Status.Capacity.Cpu().MilliValue()\n\tcapacityMemory := node.Status.Capacity.Memory().Value()\n\n\tcpuFraction := fractionOfCapacity(totalMilliCPU, capacityMilliCPU, node.Name)\n\tmemoryFraction := fractionOfCapacity(totalMemory, capacityMemory, node.Name)\n\tif cpuFraction >= 1 || memoryFraction >= 1 {\n\t\t\/\/ if requested >= capacity, the corresponding host should never be preferrred.\n\t\tscore = 0\n\t} else {\n\t\t\/\/ Upper and lower boundary of difference between cpuFraction and memoryFraction are -1 and 1\n\t\t\/\/ respectively. Multilying the absolute value of the difference by 10 scales the value to\n\t\t\/\/ 0-10 with 0 representing well balanced allocation and 10 poorly balanced. Subtracting it from\n\t\t\/\/ 10 leads to the score which also scales from 0 to 10 while 10 representing well balanced.\n\t\tdiff := math.Abs(cpuFraction - memoryFraction)\n\t\tscore = int(10 - diff*10)\n\t}\n\tglog.V(4).Infof(\n\t\t\"%v -> %v: Balanced Resource Allocation, Absolute\/Requested: (%d, %d) \/ (%d, %d) Score: (%d)\",\n\t\tpod.Name, node.Name,\n\t\ttotalMilliCPU, totalMemory,\n\t\tcapacityMilliCPU, capacityMemory,\n\t\tscore,\n\t)\n\n\treturn HostPriority{\n\t\thost:  node.Name,\n\t\tscore: score,\n\t}\n}\n\nfunc fractionOfCapacity(requested, capacity int64, node string) float64 {\n\tif capacity == 0 {\n\t\treturn 1\n\t}\n\treturn float64(requested) \/ float64(capacity)\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/bitrise-io\/bitrise\/bitrise\"\n\tmodels \"github.com\/bitrise-io\/bitrise\/models\/models_1_0_0\"\n\tenvmanModels \"github.com\/bitrise-io\/envman\/models\"\n\t\"github.com\/bitrise-io\/go-pathutil\/pathutil\"\n\t\"github.com\/bitrise-io\/goinp\/goinp\"\n\tstepmanModels \"github.com\/bitrise-io\/stepman\/models\"\n\t\"github.com\/codegangsta\/cli\"\n)\n\nconst (\n\tdefaultStepLibSource = \"https:\/\/bitbucket.org\/bitrise-team\/bitrise-new-steps-spec\"\n\t\/\/\n\tdefaultSecretsContent = `envs:\n- MY_HOME: $HOME\n- MY_SECRET_PASSWORD: XyZ\n  opts:\n    # You can include some options as well if you\n    #  want to change how the value is passed to a command.\n    is_expand: no\n    # For example you can use is_expand: no\n    #  if you want to make it sure that\n    #  the value is preserved as-it-is, and won't be\n    #  expanded before use.\n    # For example if your password contains the dollar sign ($)\n    #  it would (by default) be expanded as an environment variable,\n    #  just like $HOME would be expanded\/replaced with your home\n    #  directory path.\n    # You can prevent this with is_expand: no`\n)\n\nfunc doInit(c *cli.Context) {\n\tPrintBitriseHeaderASCIIArt()\n\n\tbitriseConfigFileRelPath := \".\/\" + DefaultBitriseConfigFileName\n\tbitriseSecretsFileRelPath := \".\/\" + DefaultSecretsFileName\n\n\tif exists, err := pathutil.IsPathExists(bitriseConfigFileRelPath); err != nil {\n\t\tlog.Fatalln(\"Error:\", err)\n\t} else if exists {\n\t\task := fmt.Sprintf(\"A config file already exists at %s - do you want to overwrite it?\", bitriseConfigFileRelPath)\n\t\tif val, err := goinp.AskForBool(ask); err != nil {\n\t\t\tlog.Fatalln(\"Error:\", err)\n\t\t} else if !val {\n\t\t\tlog.Infoln(\"Init canceled, existing file won't be overwritten.\")\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tdefaultExpand := true\n\tprojectSettingsEnvs := []envmanModels.EnvironmentItemModel{}\n\tif val, err := goinp.AskForString(\"What's the BITRISE_PROJECT_TITLE?\"); err != nil {\n\t\tlog.Fatalln(err)\n\t} else {\n\t\tprojectTitleEnv := envmanModels.EnvironmentItemModel{\n\t\t\t\"BITRISE_PROJECT_TITLE\": val,\n\t\t\t\"opts\": envmanModels.EnvironmentItemOptionsModel{\n\t\t\t\tIsExpand: &defaultExpand,\n\t\t\t},\n\t\t}\n\t\tprojectSettingsEnvs = append(projectSettingsEnvs, projectTitleEnv)\n\t}\n\tif val, err := goinp.AskForString(\"What's your primary development branch's name?\"); err != nil {\n\t\tlog.Fatalln(err)\n\t} else {\n\t\tdevBranchEnv := envmanModels.EnvironmentItemModel{\n\t\t\t\"BITRISE_DEV_BRANCH\": val,\n\t\t\t\"opts\": envmanModels.EnvironmentItemOptionsModel{\n\t\t\t\tIsExpand: &defaultExpand,\n\t\t\t},\n\t\t}\n\t\tprojectSettingsEnvs = append(projectSettingsEnvs, devBranchEnv)\n\t}\n\n\t\/\/ TODO:\n\t\/\/  generate a couple of base steps\n\t\/\/  * timestamp gen\n\t\/\/  * bash script - hello world\n\n\tscriptStepTitle := \"Hello Bitrise!\"\n\tscriptStepContent := `#!\/bin\/bash\necho \"Welcome to Bitrise!\"`\n\tbitriseConf := models.BitriseDataModel{\n\t\tFormatVersion:        c.App.Version,\n\t\tDefaultStepLibSource: defaultStepLibSource,\n\t\tApp: models.AppModel{\n\t\t\tEnvironments: projectSettingsEnvs,\n\t\t},\n\t\tWorkflows: map[string]models.WorkflowModel{\n\t\t\t\"primary\": models.WorkflowModel{\n\t\t\t\tSteps: []models.StepListItemModel{\n\t\t\t\t\tmodels.StepListItemModel{\n\t\t\t\t\t\t\"script\": stepmanModels.StepModel{\n\t\t\t\t\t\t\tTitle: &scriptStepTitle,\n\t\t\t\t\t\t\tInputs: []envmanModels.EnvironmentItemModel{\n\t\t\t\t\t\t\t\tenvmanModels.EnvironmentItemModel{\n\t\t\t\t\t\t\t\t\t\"content\": scriptStepContent,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tif err := bitrise.SaveConfigToFile(bitriseConfigFileRelPath, bitriseConf); err != nil {\n\t\tlog.Fatalln(\"Failed to init the bitrise config file:\", err)\n\t} else {\n\t\tfmt.Println()\n\t\tfmt.Println(\"# NOTES about the \" + DefaultBitriseConfigFileName + \" config file:\")\n\t\tfmt.Println()\n\t\tfmt.Println(\"We initialized a \" + DefaultBitriseConfigFileName + \" config file for you.\")\n\t\tfmt.Println(\"If you're in this folder you can use this config file\")\n\t\tfmt.Println(\" with bitrise automatically, you don't have to\")\n\t\tfmt.Println(\" specify it's path.\")\n\t\tfmt.Println()\n\t}\n\n\tif initialized, err := saveSecretsToFile(bitriseSecretsFileRelPath, defaultSecretsContent); err != nil {\n\t\tlog.Fatalln(\"Failed to init the secrets file:\", err)\n\t} else if initialized {\n\t\tfmt.Println()\n\t\tfmt.Println(\"# NOTES about the \" + DefaultSecretsFileName + \" secrets file:\")\n\t\tfmt.Println()\n\t\tfmt.Println(\"We also created a \" + DefaultSecretsFileName + \" file\")\n\t\tfmt.Println(\" in this directory, to keep your passwords, absolute path configurations\")\n\t\tfmt.Println(\" and other secrets separate from your\")\n\t\tfmt.Println(\" main configuration file.\")\n\t\tfmt.Println(\"This way you can safely commit and share your configuration file\")\n\t\tfmt.Println(\" and ignore this secrets file, so nobody else will\")\n\t\tfmt.Println(\" know about your secrets.\")\n\t\tfmt.Println(\"You should NEVER commit this secrets file into your repository!!\")\n\t\tfmt.Println()\n\t}\n\n\tfmt.Println()\n\tfmt.Println(\"Hurray, you're good to go!\")\n\tfmt.Println(\"You can simply run:\")\n\tfmt.Println(\"-> bitrise run primary\")\n\tfmt.Println(\"to test the sample configuration (which contains\")\n\tfmt.Println(\"an example workflow called 'primary').\")\n\tfmt.Println()\n\tfmt.Println(\"Once you tested this sample setup you can\")\n\tfmt.Println(\" open the \" + DefaultBitriseConfigFileName + \" config file,\")\n\tfmt.Println(\" modify it and then run a workflow with:\")\n\tfmt.Println(\"-> bitrise run YOUR-WORKFLOW-NAME\")\n}\n\nfunc saveSecretsToFile(pth, secretsStr string) (bool, error) {\n\tif exists, err := pathutil.IsPathExists(pth); err != nil {\n\t\treturn false, err\n\t} else if exists {\n\t\task := fmt.Sprintf(\"A secrets file already exists at %s - do you want to overwrite it?\", pth)\n\t\tif val, err := goinp.AskForBool(ask); err != nil {\n\t\t\treturn false, err\n\t\t} else if !val {\n\t\t\tlog.Infoln(\"Init canceled, existing file (\" + pth + \") won't be overwritten.\")\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\tif err := bitrise.WriteStringToFile(pth, secretsStr); err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}\n<commit_msg>init highligth<commit_after>package cli\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/bitrise-io\/bitrise\/bitrise\"\n\t\"github.com\/bitrise-io\/bitrise\/colorstring\"\n\tmodels \"github.com\/bitrise-io\/bitrise\/models\/models_1_0_0\"\n\tenvmanModels \"github.com\/bitrise-io\/envman\/models\"\n\t\"github.com\/bitrise-io\/go-pathutil\/pathutil\"\n\t\"github.com\/bitrise-io\/goinp\/goinp\"\n\tstepmanModels \"github.com\/bitrise-io\/stepman\/models\"\n\t\"github.com\/codegangsta\/cli\"\n)\n\nconst (\n\tdefaultStepLibSource = \"https:\/\/bitbucket.org\/bitrise-team\/bitrise-new-steps-spec\"\n\t\/\/\n\tdefaultSecretsContent = `envs:\n- MY_HOME: $HOME\n- MY_SECRET_PASSWORD: XyZ\n  opts:\n    # You can include some options as well if you\n    #  want to change how the value is passed to a command.\n    is_expand: no\n    # For example you can use is_expand: no\n    #  if you want to make it sure that\n    #  the value is preserved as-it-is, and won't be\n    #  expanded before use.\n    # For example if your password contains the dollar sign ($)\n    #  it would (by default) be expanded as an environment variable,\n    #  just like $HOME would be expanded\/replaced with your home\n    #  directory path.\n    # You can prevent this with is_expand: no`\n)\n\nfunc doInit(c *cli.Context) {\n\tPrintBitriseHeaderASCIIArt()\n\n\tbitriseConfigFileRelPath := \".\/\" + DefaultBitriseConfigFileName\n\tbitriseSecretsFileRelPath := \".\/\" + DefaultSecretsFileName\n\n\tif exists, err := pathutil.IsPathExists(bitriseConfigFileRelPath); err != nil {\n\t\tlog.Fatalln(\"Error:\", err)\n\t} else if exists {\n\t\task := fmt.Sprintf(\"A config file already exists at %s - do you want to overwrite it?\", bitriseConfigFileRelPath)\n\t\tif val, err := goinp.AskForBool(ask); err != nil {\n\t\t\tlog.Fatalln(\"Error:\", err)\n\t\t} else if !val {\n\t\t\tlog.Infoln(\"Init canceled, existing file won't be overwritten.\")\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tdefaultExpand := true\n\tprojectSettingsEnvs := []envmanModels.EnvironmentItemModel{}\n\tif val, err := goinp.AskForString(\"What's the BITRISE_PROJECT_TITLE?\"); err != nil {\n\t\tlog.Fatalln(err)\n\t} else {\n\t\tprojectTitleEnv := envmanModels.EnvironmentItemModel{\n\t\t\t\"BITRISE_PROJECT_TITLE\": val,\n\t\t\t\"opts\": envmanModels.EnvironmentItemOptionsModel{\n\t\t\t\tIsExpand: &defaultExpand,\n\t\t\t},\n\t\t}\n\t\tprojectSettingsEnvs = append(projectSettingsEnvs, projectTitleEnv)\n\t}\n\tif val, err := goinp.AskForString(\"What's your primary development branch's name?\"); err != nil {\n\t\tlog.Fatalln(err)\n\t} else {\n\t\tdevBranchEnv := envmanModels.EnvironmentItemModel{\n\t\t\t\"BITRISE_DEV_BRANCH\": val,\n\t\t\t\"opts\": envmanModels.EnvironmentItemOptionsModel{\n\t\t\t\tIsExpand: &defaultExpand,\n\t\t\t},\n\t\t}\n\t\tprojectSettingsEnvs = append(projectSettingsEnvs, devBranchEnv)\n\t}\n\n\t\/\/ TODO:\n\t\/\/  generate a couple of base steps\n\t\/\/  * timestamp gen\n\t\/\/  * bash script - hello world\n\n\tscriptStepTitle := \"Hello Bitrise!\"\n\tscriptStepContent := `#!\/bin\/bash\necho \"Welcome to Bitrise!\"`\n\tbitriseConf := models.BitriseDataModel{\n\t\tFormatVersion:        c.App.Version,\n\t\tDefaultStepLibSource: defaultStepLibSource,\n\t\tApp: models.AppModel{\n\t\t\tEnvironments: projectSettingsEnvs,\n\t\t},\n\t\tWorkflows: map[string]models.WorkflowModel{\n\t\t\t\"primary\": models.WorkflowModel{\n\t\t\t\tSteps: []models.StepListItemModel{\n\t\t\t\t\tmodels.StepListItemModel{\n\t\t\t\t\t\t\"script\": stepmanModels.StepModel{\n\t\t\t\t\t\t\tTitle: &scriptStepTitle,\n\t\t\t\t\t\t\tInputs: []envmanModels.EnvironmentItemModel{\n\t\t\t\t\t\t\t\tenvmanModels.EnvironmentItemModel{\n\t\t\t\t\t\t\t\t\t\"content\": scriptStepContent,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tif err := bitrise.SaveConfigToFile(bitriseConfigFileRelPath, bitriseConf); err != nil {\n\t\tlog.Fatalln(\"Failed to init the bitrise config file:\", err)\n\t} else {\n\t\tfmt.Println()\n\t\tfmt.Println(\"# NOTES about the \" + DefaultBitriseConfigFileName + \" config file:\")\n\t\tfmt.Println()\n\t\tfmt.Println(\"We initialized a \" + DefaultBitriseConfigFileName + \" config file for you.\")\n\t\tfmt.Println(\"If you're in this folder you can use this config file\")\n\t\tfmt.Println(\" with bitrise automatically, you don't have to\")\n\t\tfmt.Println(\" specify it's path.\")\n\t\tfmt.Println()\n\t}\n\n\tif initialized, err := saveSecretsToFile(bitriseSecretsFileRelPath, defaultSecretsContent); err != nil {\n\t\tlog.Fatalln(\"Failed to init the secrets file:\", err)\n\t} else if initialized {\n\t\tfmt.Println()\n\t\tfmt.Println(\"# NOTES about the \" + DefaultSecretsFileName + \" secrets file:\")\n\t\tfmt.Println()\n\t\tfmt.Println(\"We also created a \" + DefaultSecretsFileName + \" file\")\n\t\tfmt.Println(\" in this directory, to keep your passwords, absolute path configurations\")\n\t\tfmt.Println(\" and other secrets separate from your\")\n\t\tfmt.Println(\" main configuration file.\")\n\t\tfmt.Println(\"This way you can safely commit and share your configuration file\")\n\t\tfmt.Println(\" and ignore this secrets file, so nobody else will\")\n\t\tfmt.Println(\" know about your secrets.\")\n\t\tfmt.Println(colorstring.Yellow(\"You should NEVER commit this secrets file into your repository!!\"))\n\t\tfmt.Println()\n\t}\n\n\tfmt.Println()\n\tfmt.Println(\"Hurray, you're good to go!\")\n\tfmt.Println(\"You can simply run:\")\n\tfmt.Println(\"-> bitrise run primary\")\n\tfmt.Println(\"to test the sample configuration (which contains\")\n\tfmt.Println(\"an example workflow called 'primary').\")\n\tfmt.Println()\n\tfmt.Println(\"Once you tested this sample setup you can\")\n\tfmt.Println(\" open the \" + DefaultBitriseConfigFileName + \" config file,\")\n\tfmt.Println(\" modify it and then run a workflow with:\")\n\tfmt.Println(\"-> bitrise run YOUR-WORKFLOW-NAME\")\n}\n\nfunc saveSecretsToFile(pth, secretsStr string) (bool, error) {\n\tif exists, err := pathutil.IsPathExists(pth); err != nil {\n\t\treturn false, err\n\t} else if exists {\n\t\task := fmt.Sprintf(\"A secrets file already exists at %s - do you want to overwrite it?\", pth)\n\t\tif val, err := goinp.AskForBool(ask); err != nil {\n\t\t\treturn false, err\n\t\t} else if !val {\n\t\t\tlog.Infoln(\"Init canceled, existing file (\" + pth + \") won't be overwritten.\")\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\tif err := bitrise.WriteStringToFile(pth, secretsStr); err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Package ep is a collection of structures and functions for working with the EPrints REST API\n\/\/\n\/\/ @author R. S. Doiel, <rsdoiel@caltech.edu>\n\/\/\n\/\/ Copyright (c) 2017, Caltech\n\/\/ All rights not granted herein are expressly reserved by Caltech.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\/\/ Caltech Library Packages\n\t\"github.com\/caltechlibrary\/cli\"\n\tep \"github.com\/caltechlibrary\/eprinttools\"\n)\n\nvar (\n\t\/\/ cli help text\n\tusage = `USAGE %s [OPTIONS] [EP_EPRINTS_URL|ONE_OR_MORE_EPRINT_ID]`\n\n\tdescription = `\nSYNOPSIS\n\n%s wraps the REST API for EPrints 3.3 or better. It can return a list \nof uri, a JSON view of the XML presentation as well as generates feeds \nand web pages.\n\nCONFIGURATION\n\nep can be configured with following environment variables\n\nEP_EPRINTS_URL the URL to your EPrints installation\n\nEP_DATASET the dataset and collection name for exporting, site building, and content retrieval`\n\n\texamples = `\nEXAMPLE\n\n    %s -export all\n\nWould export the entire EPrints repository public content defined by the\nenvironment virables EP_API_URL, EP_DATASET.\n\n    %s -export 2000\n\nWould export 2000 EPrints from the repository with the heighest ID values.\n\n   %s -export-modified 2017-07-01\n\nWould export the EPrint records modified since July 1, 2017.\n\n   %s -export-modified 2017-07-01,2017-07-31 \\\n      -export-save-keys=july-keys.txt \n\nWould export the EPrint records with modified times in July 2017 and\nsave the keys for the records exported with one key per line. \n`\n\n\t\/\/ Standard Options\n\tshowHelp     bool\n\tshowVersion  bool\n\tshowLicense  bool\n\tshowExamples bool\n\toutputFName  string\n\tverbose      bool\n\n\t\/\/ App Options\n\tuseAPI      bool\n\tprettyPrint bool\n\n\tapiURL      string\n\tdatasetName string\n\n\tupdatedSince          string\n\texportEPrints         string\n\texportEPrintsModified string\n\texportSaveKeys        string\n\tfeedSize              int\n\n\tauthMethod string\n\tuserName   string\n\tuserSecret string\n)\n\nfunc init() {\n\t\/\/ Setup options\n\tfeedSize = ep.DefaultFeedSize\n\n\tflag.BoolVar(&showHelp, \"h\", false, \"display help\")\n\tflag.BoolVar(&showHelp, \"help\", false, \"display help\")\n\tflag.BoolVar(&showLicense, \"l\", false, \"display license\")\n\tflag.BoolVar(&showLicense, \"license\", false, \"display license\")\n\tflag.BoolVar(&showVersion, \"v\", false, \"display version\")\n\tflag.BoolVar(&showVersion, \"version\", false, \"display version\")\n\tflag.BoolVar(&showExamples, \"example\", false, \"display example(s)\")\n\tflag.StringVar(&outputFName, \"o\", \"\", \"output filename (logging)\")\n\tflag.StringVar(&outputFName, \"output\", \"\", \"output filename (logging)\")\n\tflag.BoolVar(&verbose, \"verbose\", true, \"verbose logging\")\n\n\t\/\/ App Specific options\n\tflag.StringVar(&authMethod, \"auth\", \"\", \"set the authentication method (e.g. none, basic, oauth, shib)\")\n\tflag.StringVar(&userName, \"username\", \"\", \"set the username\")\n\tflag.StringVar(&userName, \"un\", \"\", \"set the username\")\n\tflag.StringVar(&userSecret, \"pw\", \"\", \"set the password\")\n\n\tflag.StringVar(&apiURL, \"api\", \"\", \"url for EPrints API\")\n\tflag.StringVar(&datasetName, \"dataset\", \"\", \"dataset\/collection name\")\n\n\tflag.BoolVar(&prettyPrint, \"p\", false, \"pretty print JSON output\")\n\tflag.BoolVar(&prettyPrint, \"pretty\", false, \"pretty print JSON output\")\n\tflag.BoolVar(&useAPI, \"read-api\", false, \"read the contents from the API without saving in the database\")\n\tflag.StringVar(&exportEPrints, \"export\", \"\", \"export N EPrints from highest ID to lowest\")\n\tflag.StringVar(&exportEPrintsModified, \"export-modified\", \"\", \"export records by date or date range (e.g. 2017-07-01)\")\n\tflag.StringVar(&exportSaveKeys, \"export-save-keys\", \"\", \"save the keys exported in a file with provided filename\")\n\tflag.StringVar(&updatedSince, \"updated-since\", \"\", \"list EPrint IDs updated since a given date (e.g 2017-07-01)\")\n}\n\nfunc check(cfg *cli.Config, key, value string) string {\n\tif value == \"\" {\n\t\tlog.Fatalf(\"Missing %s_%s\", cfg.EnvPrefix, strings.ToUpper(key))\n\t\treturn \"\"\n\t}\n\treturn value\n}\n\nfunc main() {\n\tappName := path.Base(os.Args[0])\n\tflag.Parse()\n\targs := flag.Args()\n\n\t\/\/ Populate cfg from the environment\n\tcfg := cli.New(appName, \"EP\", ep.Version)\n\tcfg.LicenseText = fmt.Sprintf(ep.LicenseText, appName, ep.Version)\n\tcfg.UsageText = fmt.Sprintf(usage, appName)\n\tcfg.DescriptionText = fmt.Sprintf(description, appName, appName)\n\tcfg.OptionText = \"OPTIONS\"\n\tcfg.ExampleText = fmt.Sprintf(examples, appName, appName)\n\n\t\/\/ Handle the default options\n\tif showHelp == true {\n\t\tif len(args) > 0 {\n\t\t\tfmt.Println(cfg.Help(args...))\n\t\t} else {\n\t\t\tfmt.Println(cfg.Usage())\n\t\t}\n\t\tos.Exit(0)\n\t}\n\n\tif showExamples == true {\n\t\tif len(args) > 0 {\n\t\t\tfmt.Println(cfg.Example(args...))\n\t\t} else {\n\t\t\tfmt.Println(cfg.ExampleText)\n\t\t}\n\t\tos.Exit(0)\n\t}\n\n\tif showVersion == true {\n\t\tfmt.Println(cfg.Version())\n\t\tos.Exit(0)\n\t}\n\tif showLicense == true {\n\t\tfmt.Println(cfg.License())\n\t\tos.Exit(0)\n\t}\n\n\tout, err := cli.Create(outputFName, os.Stdout)\n\tif err != nil {\n\t\tfmt.Fprint(os.Stderr, \"%s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tdefer cli.CloseFile(outputFName, out)\n\n\t\/\/ Log to out\n\tlog.SetOutput(out)\n\n\t\/\/ Required configuration\n\tapiURL = check(cfg, \"eprint_url\", cfg.MergeEnv(\"eprint_url\", apiURL))\n\tdatasetName = check(cfg, \"dataset\", cfg.MergeEnv(\"dataset\", datasetName))\n\n\t\/\/ Optional configuration\n\tauthMethod = cfg.MergeEnv(\"auth_method\", authMethod)\n\tuserName = cfg.MergeEnv(\"username\", userName)\n\tuserSecret = cfg.MergeEnv(\"password\", userSecret)\n\n\t\/\/ This will read in any settings from the environment\n\tapi, err := ep.New(cfg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif exportEPrints != \"\" {\n\t\tt0 := time.Now()\n\t\texportNo := -1\n\t\tif exportEPrints != \"all\" {\n\t\t\texportNo, err = strconv.Atoi(exportEPrints)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Export count should be %q or an integer, %s\", exportEPrints, err)\n\t\t\t}\n\t\t}\n\t\tlog.Printf(\"%s %s (pid %d)\", appName, ep.Version, os.Getpid())\n\t\tlog.Printf(\"Export started, %s\", t0)\n\t\tif err := api.ExportEPrints(exportNo, exportSaveKeys, verbose); err != nil {\n\t\t\tlog.Printf(\"%s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tlog.Printf(\"Export completed, running time %s\", time.Now().Sub(t0))\n\t\tos.Exit(0)\n\t}\n\tif exportEPrintsModified != \"\" {\n\t\ts := exportEPrintsModified\n\t\te := time.Now().Format(\"2006-01-02\")\n\t\tif strings.Contains(s, \",\") {\n\t\t\tp := strings.SplitN(s, \",\", 2)\n\t\t\ts, e = p[0], p[1]\n\t\t}\n\t\tstart, err := time.Parse(\"2006-01-02\", s)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tend, err := time.Parse(\"2006-01-02\", e)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tt0 := time.Now()\n\t\tlog.Printf(\"%s %s (pid %d)\", appName, ep.Version, os.Getpid())\n\t\tlog.Printf(\"Export from %s to %s, started %s\", start.Format(\"2006-01-02\"), end.Format(\"2006-01-02\"), t0.Format(\"2006-01-02 15:04:05 MST\"))\n\t\tif err := api.ExportModifiedEPrints(start, end, exportSaveKeys, verbose); err != nil {\n\t\t\tlog.Printf(\"%s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tlog.Printf(\"Export completed, running time %s\", time.Now().Sub(t0))\n\t\tos.Exit(0)\n\t}\n\n\t\/\/\n\t\/\/ Generate JSON output\n\t\/\/\n\tvar (\n\t\tsrc  []byte\n\t\tdata interface{}\n\t)\n\tswitch {\n\tcase updatedSince != \"\":\n\t\t\/\/ date should be formatted YYYY-MM-DD, 2006-01-02\n\t\tend := time.Now()\n\t\tstart, err := time.Parse(\"2006-01-02\", updatedSince)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"updated since %q, %s\", updatedSince, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tdata, err = api.ListModifiedEPrintURI(start, end, verbose)\n\tcase useAPI == true:\n\t\tif len(args) == 1 {\n\t\t\tdata, _, err = api.GetEPrint(args[0])\n\t\t} else {\n\t\t\tdata, err = api.ListEPrintsURI()\n\t\t}\n\tdefault:\n\t\tif len(args) == 1 {\n\t\t\tdata, err = api.Get(args[0])\n\t\t} else if len(args) > 1 {\n\t\t\trecords := []*ep.Record{}\n\t\t\tfor _, id := range args {\n\t\t\t\tif rec, err := api.Get(id); err == nil {\n\t\t\t\t\trecords = append(records, rec)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(os.Stderr, \"Can't read EPrint id %s, %s\\n\", id, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tdata = records\n\t\t} else {\n\t\t\tdata, err = api.ListID(0, -1)\n\t\t}\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif prettyPrint == true {\n\t\tsrc, _ = json.MarshalIndent(data, \"\", \"    \")\n\t} else {\n\t\tsrc, _ = json.Marshal(data)\n\t}\n\tfmt.Printf(\"%s\", src)\n}\n<commit_msg>fixed formatting<commit_after>\/\/\n\/\/ Package ep is a collection of structures and functions for working with the EPrints REST API\n\/\/\n\/\/ @author R. S. Doiel, <rsdoiel@caltech.edu>\n\/\/\n\/\/ Copyright (c) 2017, Caltech\n\/\/ All rights not granted herein are expressly reserved by Caltech.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\/\/ Caltech Library Packages\n\t\"github.com\/caltechlibrary\/cli\"\n\tep \"github.com\/caltechlibrary\/eprinttools\"\n)\n\nvar (\n\t\/\/ cli help text\n\tusage = `USAGE %s [OPTIONS] [EP_EPRINTS_URL|ONE_OR_MORE_EPRINT_ID]`\n\n\tdescription = `\nSYNOPSIS\n\n%s wraps the REST API for EPrints 3.3 or better. It can return a list \nof uri, a JSON view of the XML presentation as well as generates feeds \nand web pages.\n\nCONFIGURATION\n\nep can be configured with following environment variables\n\nEP_EPRINTS_URL the URL to your EPrints installation\n\nEP_DATASET the dataset and collection name for exporting, site building, and content retrieval`\n\n\texamples = `\nEXAMPLE\n\n    %s -export all\n\nWould export the entire EPrints repository public content defined by the\nenvironment virables EP_API_URL, EP_DATASET.\n\n    %s -export 2000\n\nWould export 2000 EPrints from the repository with the heighest ID values.\n\n   %s -export-modified 2017-07-01\n\nWould export the EPrint records modified since July 1, 2017.\n\n   %s -export-modified 2017-07-01,2017-07-31 \\\n      -export-save-keys=july-keys.txt \n\nWould export the EPrint records with modified times in July 2017 and\nsave the keys for the records exported with one key per line. \n`\n\n\t\/\/ Standard Options\n\tshowHelp     bool\n\tshowVersion  bool\n\tshowLicense  bool\n\tshowExamples bool\n\toutputFName  string\n\tverbose      bool\n\n\t\/\/ App Options\n\tuseAPI      bool\n\tprettyPrint bool\n\n\tapiURL      string\n\tdatasetName string\n\n\tupdatedSince          string\n\texportEPrints         string\n\texportEPrintsModified string\n\texportSaveKeys        string\n\tfeedSize              int\n\n\tauthMethod string\n\tuserName   string\n\tuserSecret string\n)\n\nfunc init() {\n\t\/\/ Setup options\n\tfeedSize = ep.DefaultFeedSize\n\n\tflag.BoolVar(&showHelp, \"h\", false, \"display help\")\n\tflag.BoolVar(&showHelp, \"help\", false, \"display help\")\n\tflag.BoolVar(&showLicense, \"l\", false, \"display license\")\n\tflag.BoolVar(&showLicense, \"license\", false, \"display license\")\n\tflag.BoolVar(&showVersion, \"v\", false, \"display version\")\n\tflag.BoolVar(&showVersion, \"version\", false, \"display version\")\n\tflag.BoolVar(&showExamples, \"example\", false, \"display example(s)\")\n\tflag.StringVar(&outputFName, \"o\", \"\", \"output filename (logging)\")\n\tflag.StringVar(&outputFName, \"output\", \"\", \"output filename (logging)\")\n\tflag.BoolVar(&verbose, \"verbose\", true, \"verbose logging\")\n\n\t\/\/ App Specific options\n\tflag.StringVar(&authMethod, \"auth\", \"\", \"set the authentication method (e.g. none, basic, oauth, shib)\")\n\tflag.StringVar(&userName, \"username\", \"\", \"set the username\")\n\tflag.StringVar(&userName, \"un\", \"\", \"set the username\")\n\tflag.StringVar(&userSecret, \"pw\", \"\", \"set the password\")\n\n\tflag.StringVar(&apiURL, \"api\", \"\", \"url for EPrints API\")\n\tflag.StringVar(&datasetName, \"dataset\", \"\", \"dataset\/collection name\")\n\n\tflag.BoolVar(&prettyPrint, \"p\", false, \"pretty print JSON output\")\n\tflag.BoolVar(&prettyPrint, \"pretty\", false, \"pretty print JSON output\")\n\tflag.BoolVar(&useAPI, \"read-api\", false, \"read the contents from the API without saving in the database\")\n\tflag.StringVar(&exportEPrints, \"export\", \"\", \"export N EPrints from highest ID to lowest\")\n\tflag.StringVar(&exportEPrintsModified, \"export-modified\", \"\", \"export records by date or date range (e.g. 2017-07-01)\")\n\tflag.StringVar(&exportSaveKeys, \"export-save-keys\", \"\", \"save the keys exported in a file with provided filename\")\n\tflag.StringVar(&updatedSince, \"updated-since\", \"\", \"list EPrint IDs updated since a given date (e.g 2017-07-01)\")\n}\n\nfunc check(cfg *cli.Config, key, value string) string {\n\tif value == \"\" {\n\t\tlog.Fatalf(\"Missing %s_%s\", cfg.EnvPrefix, strings.ToUpper(key))\n\t\treturn \"\"\n\t}\n\treturn value\n}\n\nfunc main() {\n\tappName := path.Base(os.Args[0])\n\tflag.Parse()\n\targs := flag.Args()\n\n\t\/\/ Populate cfg from the environment\n\tcfg := cli.New(appName, \"EP\", ep.Version)\n\tcfg.LicenseText = fmt.Sprintf(ep.LicenseText, appName, ep.Version)\n\tcfg.UsageText = fmt.Sprintf(usage, appName)\n\tcfg.DescriptionText = fmt.Sprintf(description, appName, appName)\n\tcfg.OptionText = \"OPTIONS\"\n\tcfg.ExampleText = fmt.Sprintf(examples, appName, appName, appName, appName)\n\n\t\/\/ Handle the default options\n\tif showHelp == true {\n\t\tif len(args) > 0 {\n\t\t\tfmt.Println(cfg.Help(args...))\n\t\t} else {\n\t\t\tfmt.Println(cfg.Usage())\n\t\t}\n\t\tos.Exit(0)\n\t}\n\n\tif showExamples == true {\n\t\tif len(args) > 0 {\n\t\t\tfmt.Println(cfg.Example(args...))\n\t\t} else {\n\t\t\tfmt.Println(cfg.ExampleText)\n\t\t}\n\t\tos.Exit(0)\n\t}\n\n\tif showVersion == true {\n\t\tfmt.Println(cfg.Version())\n\t\tos.Exit(0)\n\t}\n\tif showLicense == true {\n\t\tfmt.Println(cfg.License())\n\t\tos.Exit(0)\n\t}\n\n\tout, err := cli.Create(outputFName, os.Stdout)\n\tif err != nil {\n\t\tfmt.Fprint(os.Stderr, \"%s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tdefer cli.CloseFile(outputFName, out)\n\n\t\/\/ Log to out\n\tlog.SetOutput(out)\n\n\t\/\/ Required configuration\n\tapiURL = check(cfg, \"eprint_url\", cfg.MergeEnv(\"eprint_url\", apiURL))\n\tdatasetName = check(cfg, \"dataset\", cfg.MergeEnv(\"dataset\", datasetName))\n\n\t\/\/ Optional configuration\n\tauthMethod = cfg.MergeEnv(\"auth_method\", authMethod)\n\tuserName = cfg.MergeEnv(\"username\", userName)\n\tuserSecret = cfg.MergeEnv(\"password\", userSecret)\n\n\t\/\/ This will read in any settings from the environment\n\tapi, err := ep.New(cfg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif exportEPrints != \"\" {\n\t\tt0 := time.Now()\n\t\texportNo := -1\n\t\tif exportEPrints != \"all\" {\n\t\t\texportNo, err = strconv.Atoi(exportEPrints)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Export count should be %q or an integer, %s\", exportEPrints, err)\n\t\t\t}\n\t\t}\n\t\tlog.Printf(\"%s %s (pid %d)\", appName, ep.Version, os.Getpid())\n\t\tlog.Printf(\"Export started, %s\", t0)\n\t\tif err := api.ExportEPrints(exportNo, exportSaveKeys, verbose); err != nil {\n\t\t\tlog.Printf(\"%s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tlog.Printf(\"Export completed, running time %s\", time.Now().Sub(t0))\n\t\tos.Exit(0)\n\t}\n\tif exportEPrintsModified != \"\" {\n\t\ts := exportEPrintsModified\n\t\te := time.Now().Format(\"2006-01-02\")\n\t\tif strings.Contains(s, \",\") {\n\t\t\tp := strings.SplitN(s, \",\", 2)\n\t\t\ts, e = p[0], p[1]\n\t\t}\n\t\tstart, err := time.Parse(\"2006-01-02\", s)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tend, err := time.Parse(\"2006-01-02\", e)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tt0 := time.Now()\n\t\tlog.Printf(\"%s %s (pid %d)\", appName, ep.Version, os.Getpid())\n\t\tlog.Printf(\"Export from %s to %s, started %s\", start.Format(\"2006-01-02\"), end.Format(\"2006-01-02\"), t0.Format(\"2006-01-02 15:04:05 MST\"))\n\t\tif err := api.ExportModifiedEPrints(start, end, exportSaveKeys, verbose); err != nil {\n\t\t\tlog.Printf(\"%s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tlog.Printf(\"Export completed, running time %s\", time.Now().Sub(t0))\n\t\tos.Exit(0)\n\t}\n\n\t\/\/\n\t\/\/ Generate JSON output\n\t\/\/\n\tvar (\n\t\tsrc  []byte\n\t\tdata interface{}\n\t)\n\tswitch {\n\tcase updatedSince != \"\":\n\t\t\/\/ date should be formatted YYYY-MM-DD, 2006-01-02\n\t\tend := time.Now()\n\t\tstart, err := time.Parse(\"2006-01-02\", updatedSince)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"updated since %q, %s\", updatedSince, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tdata, err = api.ListModifiedEPrintURI(start, end, verbose)\n\tcase useAPI == true:\n\t\tif len(args) == 1 {\n\t\t\tdata, _, err = api.GetEPrint(args[0])\n\t\t} else {\n\t\t\tdata, err = api.ListEPrintsURI()\n\t\t}\n\tdefault:\n\t\tif len(args) == 1 {\n\t\t\tdata, err = api.Get(args[0])\n\t\t} else if len(args) > 1 {\n\t\t\trecords := []*ep.Record{}\n\t\t\tfor _, id := range args {\n\t\t\t\tif rec, err := api.Get(id); err == nil {\n\t\t\t\t\trecords = append(records, rec)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(os.Stderr, \"Can't read EPrint id %s, %s\\n\", id, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tdata = records\n\t\t} else {\n\t\t\tdata, err = api.ListID(0, -1)\n\t\t}\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif prettyPrint == true {\n\t\tsrc, _ = json.MarshalIndent(data, \"\", \"    \")\n\t} else {\n\t\tsrc, _ = json.Marshal(data)\n\t}\n\tfmt.Printf(\"%s\", src)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017 Uber Technologies, Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\npackage matcher\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/m3db\/m3cluster\/client\"\n\t\"github.com\/m3db\/m3cluster\/kv\"\n\t\"github.com\/m3db\/m3metrics\/filters\"\n\t\"github.com\/m3db\/m3metrics\/metric\/id\"\n\t\"github.com\/m3db\/m3metrics\/metric\/id\/m3\"\n\t\"github.com\/m3db\/m3metrics\/policy\"\n\t\"github.com\/m3db\/m3metrics\/rules\"\n\t\"github.com\/m3db\/m3x\/clock\"\n\t\"github.com\/m3db\/m3x\/instrument\"\n\t\"github.com\/m3db\/m3x\/pool\"\n)\n\n\/\/ Configuration is config used to create a Matcher.\ntype Configuration struct {\n\tInitWatchTimeout      time.Duration                        `yaml:\"initWatchTimeout\"`\n\tRulesKVConfig         kv.Configuration                     `yaml:\"rulesKVConfig\"`\n\tNamespacesKey         string                               `yaml:\"namespacesKey\" validate:\"nonzero\"`\n\tRuleSetKeyFmt         string                               `yaml:\"ruleSetKeyFmt\" validate:\"nonzero\"`\n\tNamespaceTag          string                               `yaml:\"namespaceTag\" validate:\"nonzero\"`\n\tDefaultNamespace      string                               `yaml:\"defaultNamespace\" validate:\"nonzero\"`\n\tNameTagKey            string                               `yaml:\"nameTagKey\" validate:\"nonzero\"`\n\tMatchRangePast        *time.Duration                       `yaml:\"matchRangePast\"`\n\tSortedTagIteratorPool pool.ObjectPoolConfiguration         `yaml:\"sortedTagIteratorPool\"`\n\tAggregationTypes      policy.AggregationTypesConfiguration `yaml:\"aggregationTypes\"`\n}\n\n\/\/ NewNamespaces creates a matcher.Namespaces.\nfunc (cfg *Configuration) NewNamespaces(\n\tkvCluster client.Client,\n\tclockOpts clock.Options,\n\tinstrumentOpts instrument.Options,\n) (Namespaces, error) {\n\topts, err := cfg.NewOptions(kvCluster, clockOpts, instrumentOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnamespaces := NewNamespaces(opts.NamespacesKey(), opts)\n\treturn namespaces, nil\n}\n\n\/\/ NewMatcher creates a Matcher.\nfunc (cfg *Configuration) NewMatcher(\n\tcache Cache,\n\tkvCluster client.Client,\n\tclockOpts clock.Options,\n\tinstrumentOpts instrument.Options,\n) (Matcher, error) {\n\topts, err := cfg.NewOptions(kvCluster, clockOpts, instrumentOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewMatcher(cache, opts)\n}\n\n\/\/ NewOptions creates a Options.\nfunc (cfg *Configuration) NewOptions(\n\tkvCluster client.Client,\n\tclockOpts clock.Options,\n\tinstrumentOpts instrument.Options,\n) (Options, error) {\n\t\/\/ Configure rules kv store.\n\tkvOpts, err := cfg.RulesKVConfig.NewOptions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := kvOpts.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\trulesStore, err := kvCluster.Store(kvOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Configure rules options.\n\tscope := instrumentOpts.MetricsScope().SubScope(\"sorted-tag-iterator-pool\")\n\tpoolOpts := cfg.SortedTagIteratorPool.NewObjectPoolOptions(instrumentOpts.SetMetricsScope(scope))\n\tsortedTagIteratorPool := id.NewSortedTagIteratorPool(poolOpts)\n\tsortedTagIteratorPool.Init(func() id.SortedTagIterator {\n\t\treturn m3.NewPooledSortedTagIterator(nil, sortedTagIteratorPool)\n\t})\n\tsortedTagIteratorFn := func(tagPairs []byte) id.SortedTagIterator {\n\t\tit := sortedTagIteratorPool.Get()\n\t\tit.Reset(tagPairs)\n\t\treturn it\n\t}\n\ttagsFilterOptions := filters.TagsFilterOptions{\n\t\tNameTagKey:          []byte(cfg.NameTagKey),\n\t\tNameAndTagsFn:       m3.NameAndTags,\n\t\tSortedTagIteratorFn: sortedTagIteratorFn,\n\t}\n\n\tisRollupIDFn := func(name []byte, tags []byte) bool {\n\t\treturn m3.IsRollupID(name, tags, sortedTagIteratorPool)\n\t}\n\n\taggTypeOpts, err := cfg.AggregationTypes.NewOptions(instrumentOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\truleSetOpts := rules.NewOptions().\n\t\tSetTagsFilterOptions(tagsFilterOptions).\n\t\tSetNewRollupIDFn(m3.NewRollupID).\n\t\tSetIsRollupIDFn(isRollupIDFn).\n\t\tSetAggregationTypesOptions(aggTypeOpts)\n\n\t\/\/ Configure ruleset key function.\n\truleSetKeyFn := func(namespace []byte) string {\n\t\treturn fmt.Sprintf(cfg.RuleSetKeyFmt, namespace)\n\t}\n\n\topts := NewOptions().\n\t\tSetClockOptions(clockOpts).\n\t\tSetInstrumentOptions(instrumentOpts).\n\t\tSetRuleSetOptions(ruleSetOpts).\n\t\tSetKVStore(rulesStore).\n\t\tSetNamespacesKey(cfg.NamespacesKey).\n\t\tSetRuleSetKeyFn(ruleSetKeyFn).\n\t\tSetNamespaceTag([]byte(cfg.NamespaceTag)).\n\t\tSetDefaultNamespace([]byte(cfg.DefaultNamespace))\n\n\tif cfg.InitWatchTimeout != 0 {\n\t\topts = opts.SetInitWatchTimeout(cfg.InitWatchTimeout)\n\t}\n\tif cfg.MatchRangePast != nil {\n\t\topts = opts.SetMatchRangePast(*cfg.MatchRangePast)\n\t}\n\n\treturn opts, nil\n}\n<commit_msg>Remove options validation since it's done inside m3cluster (#118)<commit_after>\/\/ Copyright (c) 2017 Uber Technologies, Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\npackage matcher\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/m3db\/m3cluster\/client\"\n\t\"github.com\/m3db\/m3cluster\/kv\"\n\t\"github.com\/m3db\/m3metrics\/filters\"\n\t\"github.com\/m3db\/m3metrics\/metric\/id\"\n\t\"github.com\/m3db\/m3metrics\/metric\/id\/m3\"\n\t\"github.com\/m3db\/m3metrics\/policy\"\n\t\"github.com\/m3db\/m3metrics\/rules\"\n\t\"github.com\/m3db\/m3x\/clock\"\n\t\"github.com\/m3db\/m3x\/instrument\"\n\t\"github.com\/m3db\/m3x\/pool\"\n)\n\n\/\/ Configuration is config used to create a Matcher.\ntype Configuration struct {\n\tInitWatchTimeout      time.Duration                        `yaml:\"initWatchTimeout\"`\n\tRulesKVConfig         kv.Configuration                     `yaml:\"rulesKVConfig\"`\n\tNamespacesKey         string                               `yaml:\"namespacesKey\" validate:\"nonzero\"`\n\tRuleSetKeyFmt         string                               `yaml:\"ruleSetKeyFmt\" validate:\"nonzero\"`\n\tNamespaceTag          string                               `yaml:\"namespaceTag\" validate:\"nonzero\"`\n\tDefaultNamespace      string                               `yaml:\"defaultNamespace\" validate:\"nonzero\"`\n\tNameTagKey            string                               `yaml:\"nameTagKey\" validate:\"nonzero\"`\n\tMatchRangePast        *time.Duration                       `yaml:\"matchRangePast\"`\n\tSortedTagIteratorPool pool.ObjectPoolConfiguration         `yaml:\"sortedTagIteratorPool\"`\n\tAggregationTypes      policy.AggregationTypesConfiguration `yaml:\"aggregationTypes\"`\n}\n\n\/\/ NewNamespaces creates a matcher.Namespaces.\nfunc (cfg *Configuration) NewNamespaces(\n\tkvCluster client.Client,\n\tclockOpts clock.Options,\n\tinstrumentOpts instrument.Options,\n) (Namespaces, error) {\n\topts, err := cfg.NewOptions(kvCluster, clockOpts, instrumentOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnamespaces := NewNamespaces(opts.NamespacesKey(), opts)\n\treturn namespaces, nil\n}\n\n\/\/ NewMatcher creates a Matcher.\nfunc (cfg *Configuration) NewMatcher(\n\tcache Cache,\n\tkvCluster client.Client,\n\tclockOpts clock.Options,\n\tinstrumentOpts instrument.Options,\n) (Matcher, error) {\n\topts, err := cfg.NewOptions(kvCluster, clockOpts, instrumentOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewMatcher(cache, opts)\n}\n\n\/\/ NewOptions creates a Options.\nfunc (cfg *Configuration) NewOptions(\n\tkvCluster client.Client,\n\tclockOpts clock.Options,\n\tinstrumentOpts instrument.Options,\n) (Options, error) {\n\t\/\/ Configure rules kv store.\n\tkvOpts, err := cfg.RulesKVConfig.NewOptions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trulesStore, err := kvCluster.Store(kvOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Configure rules options.\n\tscope := instrumentOpts.MetricsScope().SubScope(\"sorted-tag-iterator-pool\")\n\tpoolOpts := cfg.SortedTagIteratorPool.NewObjectPoolOptions(instrumentOpts.SetMetricsScope(scope))\n\tsortedTagIteratorPool := id.NewSortedTagIteratorPool(poolOpts)\n\tsortedTagIteratorPool.Init(func() id.SortedTagIterator {\n\t\treturn m3.NewPooledSortedTagIterator(nil, sortedTagIteratorPool)\n\t})\n\tsortedTagIteratorFn := func(tagPairs []byte) id.SortedTagIterator {\n\t\tit := sortedTagIteratorPool.Get()\n\t\tit.Reset(tagPairs)\n\t\treturn it\n\t}\n\ttagsFilterOptions := filters.TagsFilterOptions{\n\t\tNameTagKey:          []byte(cfg.NameTagKey),\n\t\tNameAndTagsFn:       m3.NameAndTags,\n\t\tSortedTagIteratorFn: sortedTagIteratorFn,\n\t}\n\n\tisRollupIDFn := func(name []byte, tags []byte) bool {\n\t\treturn m3.IsRollupID(name, tags, sortedTagIteratorPool)\n\t}\n\n\taggTypeOpts, err := cfg.AggregationTypes.NewOptions(instrumentOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\truleSetOpts := rules.NewOptions().\n\t\tSetTagsFilterOptions(tagsFilterOptions).\n\t\tSetNewRollupIDFn(m3.NewRollupID).\n\t\tSetIsRollupIDFn(isRollupIDFn).\n\t\tSetAggregationTypesOptions(aggTypeOpts)\n\n\t\/\/ Configure ruleset key function.\n\truleSetKeyFn := func(namespace []byte) string {\n\t\treturn fmt.Sprintf(cfg.RuleSetKeyFmt, namespace)\n\t}\n\n\topts := NewOptions().\n\t\tSetClockOptions(clockOpts).\n\t\tSetInstrumentOptions(instrumentOpts).\n\t\tSetRuleSetOptions(ruleSetOpts).\n\t\tSetKVStore(rulesStore).\n\t\tSetNamespacesKey(cfg.NamespacesKey).\n\t\tSetRuleSetKeyFn(ruleSetKeyFn).\n\t\tSetNamespaceTag([]byte(cfg.NamespaceTag)).\n\t\tSetDefaultNamespace([]byte(cfg.DefaultNamespace))\n\n\tif cfg.InitWatchTimeout != 0 {\n\t\topts = opts.SetInitWatchTimeout(cfg.InitWatchTimeout)\n\t}\n\tif cfg.MatchRangePast != nil {\n\t\topts = opts.SetMatchRangePast(*cfg.MatchRangePast)\n\t}\n\n\treturn opts, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"gopkg.in\/yaml.v2\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/bitrise-io\/bitrise-cli\/bitrise\"\n\tmodels \"github.com\/bitrise-io\/bitrise-cli\/models\/models_1_0_0\"\n\t\"github.com\/bitrise-io\/go-pathutil\/pathutil\"\n\t\"github.com\/bitrise-io\/goinp\/goinp\"\n\t\"github.com\/codegangsta\/cli\"\n)\n\nvar defaultSecretsContent = `envs:\n- MY_HOME: $HOME\n- MY_SECRET_PASSWORD: XyZ\n  is_expand: no\n  # Hint: You can use is_expand: no\n  #  if you want to make it sure that\n  #  the value is preserved as-it-is, and won't be\n  #  expanded before use.\n  # For example if your password contains the dollar sign ($)\n  #  it would (by default) be expanded as an environment variable.\n  # You can prevent this with is_expand: no`\n\nfunc doInit(c *cli.Context) {\n\tbitriseConfigFileRelPath := \".\/\" + DefaultBitriseConfigFileName\n\tbitriseSecretsFileRelPath := \".\/\" + DefaultSecretsFileName\n\n\tif exists, err := pathutil.IsPathExists(bitriseConfigFileRelPath); err != nil {\n\t\tlog.Fatalln(\"Error:\", err)\n\t} else if exists {\n\t\task := fmt.Sprintf(\"A config file already exists at %s - do you want to overwrite it?\", bitriseConfigFileRelPath)\n\t\tif val, err := goinp.AskForBool(ask); err != nil {\n\t\t\tlog.Fatalln(\"Error:\", err)\n\t\t} else if !val {\n\t\t\tlog.Infoln(\"Init canceled, existing file won't be overwritten.\")\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tdefaultExpand := true\n\tprojectSettingsEnvs := []models.InputModel{}\n\tif val, err := goinp.AskForString(\"What's the BITRISE_PROJECT_TITLE?\"); err != nil {\n\t\tlog.Fatalln(err)\n\t} else {\n\t\tprojectTitleEnv := models.InputModel{MappedTo: \"BITRISE_PROJECT_TITLE\", Value: val, IsExpand: &defaultExpand}\n\t\tprojectSettingsEnvs = append(projectSettingsEnvs, projectTitleEnv)\n\t}\n\tif val, err := goinp.AskForString(\"What's your primary development branch's name?\"); err != nil {\n\t\tlog.Fatalln(err)\n\t} else {\n\t\tdevBranchEnv := models.InputModel{MappedTo: \"BITRISE_DEV_BRANCH\", Value: val, IsExpand: &defaultExpand}\n\t\tprojectSettingsEnvs = append(projectSettingsEnvs, devBranchEnv)\n\t}\n\n\t\/\/ TODO:\n\t\/\/  generate a couple of base steps\n\t\/\/  * timestamp gen\n\t\/\/  * bash script - hello world\n\n\tbitriseConf := models.BitriseConfigModel{\n\t\tFormatVersion: \"1.0.0\", \/\/ TODO: move this into a project config file!\n\t\tApp: models.AppModel{\n\t\t\tEnvironments: projectSettingsEnvs,\n\t\t},\n\t\tWorkflows: map[string]models.WorkflowModel{\n\t\t\t\"primary\": models.WorkflowModel{},\n\t\t},\n\t}\n\n\tif err := saveConfigToFile(bitriseConfigFileRelPath, bitriseConf); err != nil {\n\t\tlog.Fatalln(\"Failed to init the bitrise config file:\", err)\n\t} else {\n\t\tfmt.Println()\n\t\tfmt.Println(\"# NOTES about the \" + DefaultBitriseConfigFileName + \" config file:\")\n\t\tfmt.Println()\n\t\tfmt.Println(\"We initialized a \" + DefaultBitriseConfigFileName + \" config file for you.\")\n\t\tfmt.Println(\"If you're in this folder you can use this config file\")\n\t\tfmt.Println(\" with bitrise-cli automatically, you don't have to\")\n\t\tfmt.Println(\" specify it's path.\")\n\t\tfmt.Println()\n\t}\n\n\tif initialized, err := saveSecretsToFile(bitriseSecretsFileRelPath, defaultSecretsContent); err != nil {\n\t\tlog.Fatalln(\"Failed to init the secrets file:\", err)\n\t} else if initialized {\n\t\tfmt.Println()\n\t\tfmt.Println(\"# NOTES about the \" + DefaultSecretsFileName + \" secrets file:\")\n\t\tfmt.Println()\n\t\tfmt.Println(\"We also created a \" + DefaultSecretsFileName + \" file\")\n\t\tfmt.Println(\" in this directory, to keep your passwords, absolute path configurations\")\n\t\tfmt.Println(\" and other secrets separate from your\")\n\t\tfmt.Println(\" main configuration file.\")\n\t\tfmt.Println(\"This way you can safely commit and share your configuration file\")\n\t\tfmt.Println(\" and ignore this secrets file, so nobody else will\")\n\t\tfmt.Println(\" know about your secrets.\")\n\t\tfmt.Println(\"You should NEVER commit this secrets file into your repository!!\")\n\t\tfmt.Println()\n\t}\n\n\tfmt.Println()\n\tfmt.Println(\"Hurray, you're good to go!\")\n\tfmt.Println(\"You can simply run:\")\n\tfmt.Println(\"-> bitrise-cli run primary\")\n\tfmt.Println(\"to test the sample configuration (which contains\")\n\tfmt.Println(\"an example workflow called 'primary').\")\n\tfmt.Println()\n\tfmt.Println(\"Once you tested this sample setup you can\")\n\tfmt.Println(\" open the \" + DefaultBitriseConfigFileName + \" config file,\")\n\tfmt.Println(\" modify it and then run a workflow with:\")\n\tfmt.Println(\"-> bitrise-cli run YOUR-WORKFLOW-NAME\")\n}\n\nfunc saveSecretsToFile(pth, secretsStr string) (bool, error) {\n\tif exists, err := pathutil.IsPathExists(pth); err != nil {\n\t\treturn false, err\n\t} else if exists {\n\t\task := fmt.Sprintf(\"A secrets file already exists at %s - do you want to overwrite it?\", pth)\n\t\tif val, err := goinp.AskForBool(ask); err != nil {\n\t\t\treturn false, err\n\t\t} else if !val {\n\t\t\tlog.Infoln(\"Init canceled, existing file (\" + pth + \") won't be overwritten.\")\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\tif err := bitrise.WriteStringToFile(pth, secretsStr); err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}\n\nfunc saveConfigToFile(pth string, bitriseConf models.BitriseConfigModel) error {\n\tcontBytes, err := generateYAML(bitriseConf)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := bitrise.WriteBytesToFile(pth, contBytes); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println()\n\tlog.Infoln(\"=> Init success!\")\n\tlog.Infoln(\"File created at path:\", pth)\n\tlog.Infoln(\"With the content:\")\n\tlog.Infoln(string(contBytes))\n\n\treturn nil\n}\n\nfunc generateYAML(v interface{}) ([]byte, error) {\n\tbytes, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\treturn bytes, nil\n}\n<commit_msg>code style<commit_after>package cli\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"gopkg.in\/yaml.v2\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/bitrise-io\/bitrise-cli\/bitrise\"\n\tmodels \"github.com\/bitrise-io\/bitrise-cli\/models\/models_1_0_0\"\n\t\"github.com\/bitrise-io\/go-pathutil\/pathutil\"\n\t\"github.com\/bitrise-io\/goinp\/goinp\"\n\t\"github.com\/codegangsta\/cli\"\n)\n\nvar defaultSecretsContent = `envs:\n- MY_HOME: $HOME\n- MY_SECRET_PASSWORD: XyZ\n  is_expand: no\n  # Hint: You can use is_expand: no\n  #  if you want to make it sure that\n  #  the value is preserved as-it-is, and won't be\n  #  expanded before use.\n  # For example if your password contains the dollar sign ($)\n  #  it would (by default) be expanded as an environment variable.\n  # You can prevent this with is_expand: no`\n\nfunc doInit(c *cli.Context) {\n\tbitriseConfigFileRelPath := \".\/\" + DefaultBitriseConfigFileName\n\tbitriseSecretsFileRelPath := \".\/\" + DefaultSecretsFileName\n\n\tif exists, err := pathutil.IsPathExists(bitriseConfigFileRelPath); err != nil {\n\t\tlog.Fatalln(\"Error:\", err)\n\t} else if exists {\n\t\task := fmt.Sprintf(\"A config file already exists at %s - do you want to overwrite it?\", bitriseConfigFileRelPath)\n\t\tif val, err := goinp.AskForBool(ask); err != nil {\n\t\t\tlog.Fatalln(\"Error:\", err)\n\t\t} else if !val {\n\t\t\tlog.Infoln(\"Init canceled, existing file won't be overwritten.\")\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tdefaultExpand := true\n\tprojectSettingsEnvs := []models.InputModel{}\n\tif val, err := goinp.AskForString(\"What's the BITRISE_PROJECT_TITLE?\"); err != nil {\n\t\tlog.Fatalln(err)\n\t} else {\n\t\tprojectTitleEnv := models.InputModel{\n\t\t\tMappedTo: \"BITRISE_PROJECT_TITLE\",\n\t\t\tValue:    val,\n\t\t\tIsExpand: &defaultExpand,\n\t\t}\n\t\tprojectSettingsEnvs = append(projectSettingsEnvs, projectTitleEnv)\n\t}\n\tif val, err := goinp.AskForString(\"What's your primary development branch's name?\"); err != nil {\n\t\tlog.Fatalln(err)\n\t} else {\n\t\tdevBranchEnv := models.InputModel{\n\t\t\tMappedTo: \"BITRISE_DEV_BRANCH\",\n\t\t\tValue:    val,\n\t\t\tIsExpand: &defaultExpand,\n\t\t}\n\t\tprojectSettingsEnvs = append(projectSettingsEnvs, devBranchEnv)\n\t}\n\n\t\/\/ TODO:\n\t\/\/  generate a couple of base steps\n\t\/\/  * timestamp gen\n\t\/\/  * bash script - hello world\n\n\tbitriseConf := models.BitriseConfigModel{\n\t\tFormatVersion: \"1.0.0\", \/\/ TODO: move this into a project config file!\n\t\tApp: models.AppModel{\n\t\t\tEnvironments: projectSettingsEnvs,\n\t\t},\n\t\tWorkflows: map[string]models.WorkflowModel{\n\t\t\t\"primary\": models.WorkflowModel{},\n\t\t},\n\t}\n\n\tif err := saveConfigToFile(bitriseConfigFileRelPath, bitriseConf); err != nil {\n\t\tlog.Fatalln(\"Failed to init the bitrise config file:\", err)\n\t} else {\n\t\tfmt.Println()\n\t\tfmt.Println(\"# NOTES about the \" + DefaultBitriseConfigFileName + \" config file:\")\n\t\tfmt.Println()\n\t\tfmt.Println(\"We initialized a \" + DefaultBitriseConfigFileName + \" config file for you.\")\n\t\tfmt.Println(\"If you're in this folder you can use this config file\")\n\t\tfmt.Println(\" with bitrise-cli automatically, you don't have to\")\n\t\tfmt.Println(\" specify it's path.\")\n\t\tfmt.Println()\n\t}\n\n\tif initialized, err := saveSecretsToFile(bitriseSecretsFileRelPath, defaultSecretsContent); err != nil {\n\t\tlog.Fatalln(\"Failed to init the secrets file:\", err)\n\t} else if initialized {\n\t\tfmt.Println()\n\t\tfmt.Println(\"# NOTES about the \" + DefaultSecretsFileName + \" secrets file:\")\n\t\tfmt.Println()\n\t\tfmt.Println(\"We also created a \" + DefaultSecretsFileName + \" file\")\n\t\tfmt.Println(\" in this directory, to keep your passwords, absolute path configurations\")\n\t\tfmt.Println(\" and other secrets separate from your\")\n\t\tfmt.Println(\" main configuration file.\")\n\t\tfmt.Println(\"This way you can safely commit and share your configuration file\")\n\t\tfmt.Println(\" and ignore this secrets file, so nobody else will\")\n\t\tfmt.Println(\" know about your secrets.\")\n\t\tfmt.Println(\"You should NEVER commit this secrets file into your repository!!\")\n\t\tfmt.Println()\n\t}\n\n\tfmt.Println()\n\tfmt.Println(\"Hurray, you're good to go!\")\n\tfmt.Println(\"You can simply run:\")\n\tfmt.Println(\"-> bitrise-cli run primary\")\n\tfmt.Println(\"to test the sample configuration (which contains\")\n\tfmt.Println(\"an example workflow called 'primary').\")\n\tfmt.Println()\n\tfmt.Println(\"Once you tested this sample setup you can\")\n\tfmt.Println(\" open the \" + DefaultBitriseConfigFileName + \" config file,\")\n\tfmt.Println(\" modify it and then run a workflow with:\")\n\tfmt.Println(\"-> bitrise-cli run YOUR-WORKFLOW-NAME\")\n}\n\nfunc saveSecretsToFile(pth, secretsStr string) (bool, error) {\n\tif exists, err := pathutil.IsPathExists(pth); err != nil {\n\t\treturn false, err\n\t} else if exists {\n\t\task := fmt.Sprintf(\"A secrets file already exists at %s - do you want to overwrite it?\", pth)\n\t\tif val, err := goinp.AskForBool(ask); err != nil {\n\t\t\treturn false, err\n\t\t} else if !val {\n\t\t\tlog.Infoln(\"Init canceled, existing file (\" + pth + \") won't be overwritten.\")\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\tif err := bitrise.WriteStringToFile(pth, secretsStr); err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}\n\nfunc saveConfigToFile(pth string, bitriseConf models.BitriseConfigModel) error {\n\tcontBytes, err := generateYAML(bitriseConf)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := bitrise.WriteBytesToFile(pth, contBytes); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println()\n\tlog.Infoln(\"=> Init success!\")\n\tlog.Infoln(\"File created at path:\", pth)\n\tlog.Infoln(\"With the content:\")\n\tlog.Infoln(string(contBytes))\n\n\treturn nil\n}\n\nfunc generateYAML(v interface{}) ([]byte, error) {\n\tbytes, err := yaml.Marshal(v)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\treturn bytes, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (C) 2015 Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage cmds\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"path\/filepath\"\n\n\t\"github.com\/fabric8io\/gofabric8\/util\"\n\t\"github.com\/kardianos\/osext\"\n\t\"github.com\/spf13\/cobra\"\n\tclient \"k8s.io\/kubernetes\/pkg\/client\/unversioned\"\n\tcmdutil \"k8s.io\/kubernetes\/pkg\/kubectl\/cmd\/util\"\n)\n\nconst (\n\tmemory   = \"memory\"\n\tvmDriver = \"vm-driver\"\n\tcpus     = \"cpus\"\n\tconsole  = \"console\"\n\tipaas    = \"ipaas\"\n\tdiskSize = \"disk-size\"\n)\n\n\/\/ NewCmdStart starts a local cloud environment\nfunc NewCmdStart(f *cmdutil.Factory) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"start\",\n\t\tShort: \"Starts a local cloud development environment\",\n\t\tLong:  `Starts a local cloud development environment`,\n\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tflag := cmd.Flags().Lookup(minishift)\n\t\t\tisOpenshift := false\n\t\t\tif flag != nil {\n\t\t\t\tisOpenshift = flag.Value.String() == \"true\"\n\t\t\t}\n\n\t\t\tflag = cmd.Flags().Lookup(ipaas)\n\t\t\tisIPaaS := false\n\t\t\tif flag != nil && flag.Value.String() == \"true\" {\n\t\t\t\tisOpenshift = true\n\t\t\t\tisIPaaS = true\n\t\t\t}\n\n\t\t\tif !isInstalled(isOpenshift) {\n\t\t\t\tinstall(isOpenshift)\n\t\t\t}\n\t\t\tkubeBinary := minikube\n\t\t\tif isOpenshift {\n\t\t\t\tkubeBinary = minishift\n\t\t\t}\n\n\t\t\tif runtime.GOOS == \"windows\" && !strings.HasSuffix(kubeBinary, \".exe\") {\n\t\t\t\tkubeBinary += \".exe\"\n\t\t\t}\n\n\t\t\tbinaryFile := resolveBinaryLocation(kubeBinary)\n\n\t\t\t\/\/ check if already running\n\t\t\tout, err := exec.Command(binaryFile, \"status\").Output()\n\t\t\tif err != nil {\n\t\t\t\tutil.Fatalf(\"Unable to get status %v\", err)\n\t\t\t}\n\n\t\t\tif err == nil && strings.Contains(string(out), \"Running\") {\n\t\t\t\t\/\/ already running\n\t\t\t\tutil.Successf(\"%s already running\\n\", kubeBinary)\n\n\t\t\t\tkubectlBinaryFile := resolveBinaryLocation(kubectl)\n\n\t\t\t\t\/\/ setting context\n\t\t\t\tif kubeBinary == minikube {\n\t\t\t\t\te := exec.Command(kubectlBinaryFile, \"config\", \"use-context\", kubeBinary)\n\t\t\t\t\te.Stdout = os.Stdout\n\t\t\t\t\te.Stderr = os.Stderr\n\t\t\t\t\terr = e.Run()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tutil.Errorf(\"Unable to start %v\", err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ minishift context has changed, we need to work it out now\n\t\t\t\t\tutil.Info(\"minishift is already running, you can switch to the context\\n\")\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\targs := []string{\"start\"}\n\n\t\t\t\tvmDriverValue := cmd.Flags().Lookup(vmDriver).Value.String()\n\t\t\t\tif len(vmDriverValue) == 0 {\n\t\t\t\t\tswitch runtime.GOOS {\n\t\t\t\t\tcase \"darwin\":\n\t\t\t\t\t\tvmDriverValue = \"xhyve\"\n\t\t\t\t\tcase \"windows\":\n\t\t\t\t\t\tvmDriverValue = \"hyperv\"\n\t\t\t\t\tcase \"linux\":\n\t\t\t\t\t\tvmDriverValue = \"kvm\"\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tvmDriverValue = \"virtualbox\"\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\targs = append(args, \"--vm-driver=\"+vmDriverValue)\n\n\t\t\t\t\/\/ set memory flag\n\t\t\t\tmemoryValue := cmd.Flags().Lookup(memory).Value.String()\n\t\t\t\targs = append(args, \"--memory=\"+memoryValue)\n\n\t\t\t\t\/\/ set cpu flag\n\t\t\t\tcpusValue := cmd.Flags().Lookup(cpus).Value.String()\n\t\t\t\targs = append(args, \"--cpus=\"+cpusValue)\n\n\t\t\t\t\/\/ set disk-size flag\n\t\t\t\tdiskSizeValue := cmd.Flags().Lookup(diskSize).Value.String()\n\t\t\t\targs = append(args, \"--disk-size=\"+diskSizeValue)\n\n\t\t\t\t\/\/ start the local VM\n\t\t\t\tlogCommand(binaryFile, args)\n\t\t\t\te := exec.Command(binaryFile, args...)\n\t\t\t\te.Stdout = os.Stdout\n\t\t\t\te.Stderr = os.Stderr\n\t\t\t\terr = e.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.Errorf(\"Unable to start %v\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif isOpenshift {\n\t\t\t\t\/\/ deploy fabric8\n\t\t\t\te := exec.Command(\"oc\", \"login\", \"--username=\"+minishiftDefaultUsername, \"--password=\"+minishiftDefaultPassword)\n\t\t\t\te.Stdout = os.Stdout\n\t\t\t\te.Stderr = os.Stderr\n\t\t\t\terr = e.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.Errorf(\"Unable to login %v\", err)\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t\/\/ now check that fabric8 is running, if not deploy it\n\t\t\tc, err := keepTryingToGetClient(f)\n\t\t\tif err != nil {\n\t\t\t\tutil.Fatalf(\"Unable to connect to %s %v\", kubeBinary, err)\n\t\t\t}\n\n\t\t\t\/\/ deploy fabric8 if its not already running\n\t\t\tns, _, _ := f.DefaultNamespace()\n\t\t\t_, err = c.Services(ns).Get(\"fabric8\")\n\t\t\tif err != nil {\n\n\t\t\t\t\/\/ deploy fabric8\n\t\t\t\td := GetDefaultFabric8Deployment()\n\t\t\t\tflag := cmd.Flags().Lookup(console)\n\t\t\t\tif isIPaaS {\n\t\t\t\t\td.packageName = \"ipaas\"\n\t\t\t\t} else if flag != nil && flag.Value.String() == \"true\" {\n\t\t\t\t\td.packageName = \"console\"\n\t\t\t\t} else {\n\t\t\t\t\td.packageName = cmd.Flags().Lookup(packageFlag).Value.String()\n\t\t\t\t}\n\t\t\t\td.versionPlatform = cmd.Flags().Lookup(versionPlatformFlag).Value.String()\n\t\t\t\td.versioniPaaS = cmd.Flags().Lookup(versioniPaaSFlag).Value.String()\n\t\t\t\td.pv = cmd.Flags().Lookup(pvFlag).Value.String() == \"true\"\n\t\t\t\td.useIngress = cmd.Flags().Lookup(useIngressFlag).Value.String() == \"true\"\n\t\t\t\td.useLoadbalancer = cmd.Flags().Lookup(useLoadbalancerFlag).Value.String() == \"true\"\n\t\t\t\tdeploy(f, d)\n\n\t\t\t} else {\n\t\t\t\topenService(ns, \"fabric8\", c, false)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.PersistentFlags().BoolP(minishift, \"\", false, \"start the openshift flavour of Kubernetes\")\n\tcmd.PersistentFlags().BoolP(console, \"\", false, \"start only the fabric8 console\")\n\tcmd.PersistentFlags().BoolP(ipaas, \"\", false, \"start the fabric8 iPaaS\")\n\tcmd.PersistentFlags().StringP(memory, \"\", \"6144\", \"amount of RAM allocated to the VM\")\n\tcmd.PersistentFlags().StringP(vmDriver, \"\", \"\", \"the VM driver used to spin up the VM. Possible values (hyperv, xhyve, kvm, virtualbox, vmwarefusion)\")\n\tcmd.PersistentFlags().StringP(diskSize, \"\", \"20g\", \"the size of the disk allocated to the VM\")\n\tcmd.PersistentFlags().StringP(cpus, \"\", \"1\", \"number of CPUs allocated to the VM\")\n\tcmd.PersistentFlags().String(packageFlag, \"platform\", \"The name of the package to startup such as 'platform', 'console', 'ipaas'. Otherwise specify a URL or local file of the YAML to install\")\n\tcmd.PersistentFlags().String(versionPlatformFlag, \"latest\", \"The version to use for the Fabric8 Platform packages\")\n\tcmd.PersistentFlags().String(versioniPaaSFlag, \"latest\", \"The version to use for the Fabric8 iPaaS templates\")\n\tcmd.PersistentFlags().Bool(pvFlag, true, \"if false will convert deployments to use Kubernetes emptyDir and disable persistence for core apps\")\n\tcmd.PersistentFlags().Bool(useIngressFlag, true, \"Should Ingress NGINX controller be enabled by default when deploying to Kubernetes?\")\n\tcmd.PersistentFlags().Bool(useLoadbalancerFlag, false, \"Should Cloud Provider LoadBalancer be used to expose services when running to Kubernetes? (overrides ingress)\")\n\treturn cmd\n}\n\nfunc logCommand(executable string, args []string) {\n\tutil.Infof(\"running: %s %s\\n\", executable, strings.Join(args, \" \"))\n}\n\n\/\/ lets find the executable on the PATH or in the fabric8 directory\nfunc resolveBinaryLocation(executable string) string {\n\tpath, err := exec.LookPath(executable)\n\tif err != nil || fileNotExist(path) {\n\t\thome := os.Getenv(\"HOME\")\n\t\tif home == \"\" {\n\t\t\tutil.Error(\"No $HOME environment variable found\")\n\t\t}\n\t\twriteFileLocation := getFabric8BinLocation()\n\n\t\t\/\/ lets try in the fabric8 folder\n\t\tpath = filepath.Join(writeFileLocation, executable)\n\t\tif fileNotExist(path) {\n\t\t\tpath = executable\n\t\t\t\/\/ lets try in the folder where we found the gofabric8 executable\n\t\t\tfolder, err := osext.ExecutableFolder()\n\t\t\tif err != nil {\n\t\t\t\tutil.Errorf(\"Failed to find executable folder: %v\\n\", err)\n\t\t\t} else {\n\t\t\t\tpath = filepath.Join(folder, executable)\n\t\t\t\tif fileNotExist(path) {\n\t\t\t\t\tutil.Infof(\"Could not find executable at %v\\n\", path)\n\t\t\t\t\tpath = executable\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tutil.Infof(\"using the executable %s\\n\", path)\n\treturn path\n}\n\nfunc findExecutable(file string) error {\n\td, err := os.Stat(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif m := d.Mode(); !m.IsDir() {\n\t\treturn nil\n\t}\n\treturn os.ErrPermission\n}\n\nfunc fileNotExist(path string) bool {\n\treturn findExecutable(path) != nil\n}\n\nfunc keepTryingToGetClient(f *cmdutil.Factory) (*client.Client, error) {\n\ttimeout := time.After(2 * time.Minute)\n\ttick := time.Tick(1 * time.Second)\n\t\/\/ Keep trying until we're timed out or got a result or got an error\n\tfor {\n\t\tselect {\n\t\t\/\/ Got a timeout! fail with a timeout error\n\t\tcase <-timeout:\n\t\t\treturn nil, errors.New(\"timed out\")\n\t\t\/\/ Got a tick, try and get teh client\n\t\tcase <-tick:\n\t\t\tc, _ := getClient(f)\n\t\t\t\/\/ return if we have a client\n\t\t\tif c != nil {\n\t\t\t\treturn c, nil\n\t\t\t}\n\t\t\tutil.Info(\"Cannot connect to api server, retrying...\\n\")\n\t\t\t\/\/ retry\n\t\t}\n\t}\n}\n\nfunc getClient(f *cmdutil.Factory) (*client.Client, error) {\n\tvar err error\n\tcfg, err := f.ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := client.New(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}\n<commit_msg>lets allow the opening of the console to be optional<commit_after>\/**\n * Copyright (C) 2015 Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage cmds\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"path\/filepath\"\n\n\t\"github.com\/fabric8io\/gofabric8\/util\"\n\t\"github.com\/kardianos\/osext\"\n\t\"github.com\/spf13\/cobra\"\n\tclient \"k8s.io\/kubernetes\/pkg\/client\/unversioned\"\n\tcmdutil \"k8s.io\/kubernetes\/pkg\/kubectl\/cmd\/util\"\n)\n\nconst (\n\tmemory   = \"memory\"\n\tvmDriver = \"vm-driver\"\n\tcpus     = \"cpus\"\n\tconsole  = \"console\"\n\tipaas    = \"ipaas\"\n\tdiskSize = \"disk-size\"\n\n\topenConsoleFlag = \"open-console\"\n)\n\n\/\/ NewCmdStart starts a local cloud environment\nfunc NewCmdStart(f *cmdutil.Factory) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"start\",\n\t\tShort: \"Starts a local cloud development environment\",\n\t\tLong:  `Starts a local cloud development environment`,\n\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tflag := cmd.Flags().Lookup(minishift)\n\t\t\tisOpenshift := false\n\t\t\tif flag != nil {\n\t\t\t\tisOpenshift = flag.Value.String() == \"true\"\n\t\t\t}\n\n\t\t\tflag = cmd.Flags().Lookup(ipaas)\n\t\t\tisIPaaS := false\n\t\t\tif flag != nil && flag.Value.String() == \"true\" {\n\t\t\t\tisOpenshift = true\n\t\t\t\tisIPaaS = true\n\t\t\t}\n\n\t\t\tif !isInstalled(isOpenshift) {\n\t\t\t\tinstall(isOpenshift)\n\t\t\t}\n\t\t\tkubeBinary := minikube\n\t\t\tif isOpenshift {\n\t\t\t\tkubeBinary = minishift\n\t\t\t}\n\n\t\t\tif runtime.GOOS == \"windows\" && !strings.HasSuffix(kubeBinary, \".exe\") {\n\t\t\t\tkubeBinary += \".exe\"\n\t\t\t}\n\n\t\t\tbinaryFile := resolveBinaryLocation(kubeBinary)\n\n\t\t\t\/\/ check if already running\n\t\t\tout, err := exec.Command(binaryFile, \"status\").Output()\n\t\t\tif err != nil {\n\t\t\t\tutil.Fatalf(\"Unable to get status %v\", err)\n\t\t\t}\n\n\t\t\tif err == nil && strings.Contains(string(out), \"Running\") {\n\t\t\t\t\/\/ already running\n\t\t\t\tutil.Successf(\"%s already running\\n\", kubeBinary)\n\n\t\t\t\tkubectlBinaryFile := resolveBinaryLocation(kubectl)\n\n\t\t\t\t\/\/ setting context\n\t\t\t\tif kubeBinary == minikube {\n\t\t\t\t\te := exec.Command(kubectlBinaryFile, \"config\", \"use-context\", kubeBinary)\n\t\t\t\t\te.Stdout = os.Stdout\n\t\t\t\t\te.Stderr = os.Stderr\n\t\t\t\t\terr = e.Run()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tutil.Errorf(\"Unable to start %v\", err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ minishift context has changed, we need to work it out now\n\t\t\t\t\tutil.Info(\"minishift is already running, you can switch to the context\\n\")\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\targs := []string{\"start\"}\n\n\t\t\t\tvmDriverValue := cmd.Flags().Lookup(vmDriver).Value.String()\n\t\t\t\tif len(vmDriverValue) == 0 {\n\t\t\t\t\tswitch runtime.GOOS {\n\t\t\t\t\tcase \"darwin\":\n\t\t\t\t\t\tvmDriverValue = \"xhyve\"\n\t\t\t\t\tcase \"windows\":\n\t\t\t\t\t\tvmDriverValue = \"hyperv\"\n\t\t\t\t\tcase \"linux\":\n\t\t\t\t\t\tvmDriverValue = \"kvm\"\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tvmDriverValue = \"virtualbox\"\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t\targs = append(args, \"--vm-driver=\"+vmDriverValue)\n\n\t\t\t\t\/\/ set memory flag\n\t\t\t\tmemoryValue := cmd.Flags().Lookup(memory).Value.String()\n\t\t\t\targs = append(args, \"--memory=\"+memoryValue)\n\n\t\t\t\t\/\/ set cpu flag\n\t\t\t\tcpusValue := cmd.Flags().Lookup(cpus).Value.String()\n\t\t\t\targs = append(args, \"--cpus=\"+cpusValue)\n\n\t\t\t\t\/\/ set disk-size flag\n\t\t\t\tdiskSizeValue := cmd.Flags().Lookup(diskSize).Value.String()\n\t\t\t\targs = append(args, \"--disk-size=\"+diskSizeValue)\n\n\t\t\t\t\/\/ start the local VM\n\t\t\t\tlogCommand(binaryFile, args)\n\t\t\t\te := exec.Command(binaryFile, args...)\n\t\t\t\te.Stdout = os.Stdout\n\t\t\t\te.Stderr = os.Stderr\n\t\t\t\terr = e.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.Errorf(\"Unable to start %v\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif isOpenshift {\n\t\t\t\t\/\/ deploy fabric8\n\t\t\t\te := exec.Command(\"oc\", \"login\", \"--username=\"+minishiftDefaultUsername, \"--password=\"+minishiftDefaultPassword)\n\t\t\t\te.Stdout = os.Stdout\n\t\t\t\te.Stderr = os.Stderr\n\t\t\t\terr = e.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.Errorf(\"Unable to login %v\", err)\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t\/\/ now check that fabric8 is running, if not deploy it\n\t\t\tc, err := keepTryingToGetClient(f)\n\t\t\tif err != nil {\n\t\t\t\tutil.Fatalf(\"Unable to connect to %s %v\", kubeBinary, err)\n\t\t\t}\n\n\t\t\t\/\/ deploy fabric8 if its not already running\n\t\t\tns, _, _ := f.DefaultNamespace()\n\t\t\t_, err = c.Services(ns).Get(\"fabric8\")\n\t\t\tif err != nil {\n\n\t\t\t\t\/\/ deploy fabric8\n\t\t\t\td := GetDefaultFabric8Deployment()\n\t\t\t\tflag := cmd.Flags().Lookup(console)\n\t\t\t\tif isIPaaS {\n\t\t\t\t\td.packageName = \"ipaas\"\n\t\t\t\t} else if flag != nil && flag.Value.String() == \"true\" {\n\t\t\t\t\td.packageName = \"console\"\n\t\t\t\t} else {\n\t\t\t\t\td.packageName = cmd.Flags().Lookup(packageFlag).Value.String()\n\t\t\t\t}\n\t\t\t\td.versionPlatform = cmd.Flags().Lookup(versionPlatformFlag).Value.String()\n\t\t\t\td.versioniPaaS = cmd.Flags().Lookup(versioniPaaSFlag).Value.String()\n\t\t\t\td.pv = cmd.Flags().Lookup(pvFlag).Value.String() == \"true\"\n\t\t\t\td.useIngress = cmd.Flags().Lookup(useIngressFlag).Value.String() == \"true\"\n\t\t\t\td.useLoadbalancer = cmd.Flags().Lookup(useLoadbalancerFlag).Value.String() == \"true\"\n\t\t\t\tdeploy(f, d)\n\n\t\t\t} else {\n\t\t\t\tflag := cmd.Flags().Lookup(openConsoleFlag)\n\t\t\t\tif flag != nil && flag.Value.String() == \"true\" {\n\t\t\t\t\topenService(ns, \"fabric8\", c, false)\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}\n\tcmd.PersistentFlags().BoolP(minishift, \"\", false, \"start the openshift flavour of Kubernetes\")\n\tcmd.PersistentFlags().BoolP(console, \"\", false, \"start only the fabric8 console\")\n\tcmd.PersistentFlags().BoolP(ipaas, \"\", false, \"start the fabric8 iPaaS\")\n\tcmd.PersistentFlags().StringP(memory, \"\", \"6144\", \"amount of RAM allocated to the VM\")\n\tcmd.PersistentFlags().StringP(vmDriver, \"\", \"\", \"the VM driver used to spin up the VM. Possible values (hyperv, xhyve, kvm, virtualbox, vmwarefusion)\")\n\tcmd.PersistentFlags().StringP(diskSize, \"\", \"20g\", \"the size of the disk allocated to the VM\")\n\tcmd.PersistentFlags().StringP(cpus, \"\", \"1\", \"number of CPUs allocated to the VM\")\n\tcmd.PersistentFlags().String(packageFlag, \"platform\", \"The name of the package to startup such as 'platform', 'console', 'ipaas'. Otherwise specify a URL or local file of the YAML to install\")\n\tcmd.PersistentFlags().String(versionPlatformFlag, \"latest\", \"The version to use for the Fabric8 Platform packages\")\n\tcmd.PersistentFlags().String(versioniPaaSFlag, \"latest\", \"The version to use for the Fabric8 iPaaS templates\")\n\tcmd.PersistentFlags().Bool(pvFlag, true, \"if false will convert deployments to use Kubernetes emptyDir and disable persistence for core apps\")\n\tcmd.PersistentFlags().Bool(useIngressFlag, true, \"Should Ingress NGINX controller be enabled by default when deploying to Kubernetes?\")\n\tcmd.PersistentFlags().Bool(useLoadbalancerFlag, false, \"Should Cloud Provider LoadBalancer be used to expose services when running to Kubernetes? (overrides ingress)\")\n\tcmd.PersistentFlags().Bool(openConsoleFlag, true, \"Should we wait an open the console?\")\n\treturn cmd\n}\n\nfunc logCommand(executable string, args []string) {\n\tutil.Infof(\"running: %s %s\\n\", executable, strings.Join(args, \" \"))\n}\n\n\/\/ lets find the executable on the PATH or in the fabric8 directory\nfunc resolveBinaryLocation(executable string) string {\n\tpath, err := exec.LookPath(executable)\n\tif err != nil || fileNotExist(path) {\n\t\thome := os.Getenv(\"HOME\")\n\t\tif home == \"\" {\n\t\t\tutil.Error(\"No $HOME environment variable found\")\n\t\t}\n\t\twriteFileLocation := getFabric8BinLocation()\n\n\t\t\/\/ lets try in the fabric8 folder\n\t\tpath = filepath.Join(writeFileLocation, executable)\n\t\tif fileNotExist(path) {\n\t\t\tpath = executable\n\t\t\t\/\/ lets try in the folder where we found the gofabric8 executable\n\t\t\tfolder, err := osext.ExecutableFolder()\n\t\t\tif err != nil {\n\t\t\t\tutil.Errorf(\"Failed to find executable folder: %v\\n\", err)\n\t\t\t} else {\n\t\t\t\tpath = filepath.Join(folder, executable)\n\t\t\t\tif fileNotExist(path) {\n\t\t\t\t\tutil.Infof(\"Could not find executable at %v\\n\", path)\n\t\t\t\t\tpath = executable\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tutil.Infof(\"using the executable %s\\n\", path)\n\treturn path\n}\n\nfunc findExecutable(file string) error {\n\td, err := os.Stat(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif m := d.Mode(); !m.IsDir() {\n\t\treturn nil\n\t}\n\treturn os.ErrPermission\n}\n\nfunc fileNotExist(path string) bool {\n\treturn findExecutable(path) != nil\n}\n\nfunc keepTryingToGetClient(f *cmdutil.Factory) (*client.Client, error) {\n\ttimeout := time.After(2 * time.Minute)\n\ttick := time.Tick(1 * time.Second)\n\t\/\/ Keep trying until we're timed out or got a result or got an error\n\tfor {\n\t\tselect {\n\t\t\/\/ Got a timeout! fail with a timeout error\n\t\tcase <-timeout:\n\t\t\treturn nil, errors.New(\"timed out\")\n\t\t\/\/ Got a tick, try and get teh client\n\t\tcase <-tick:\n\t\t\tc, _ := getClient(f)\n\t\t\t\/\/ return if we have a client\n\t\t\tif c != nil {\n\t\t\t\treturn c, nil\n\t\t\t}\n\t\t\tutil.Info(\"Cannot connect to api server, retrying...\\n\")\n\t\t\t\/\/ retry\n\t\t}\n\t}\n}\n\nfunc getClient(f *cmdutil.Factory) (*client.Client, error) {\n\tvar err error\n\tcfg, err := f.ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := client.New(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Stuart Glenn, OMRF. All rights reserved.\n\/\/ Use of this code is governed by a 3 clause BSD style license\n\/\/ Full license details in LICENSE file distributed with this software\n\npackage matcher\n\nimport (\n\t\"encoding\/csv\"\n\t\"io\"\n\t\"strconv\"\n)\n\n\/\/ A Record holds a data to be matched based on attributes in Atts\ntype Record struct {\n\tID   string\n\tAtts []Atter\n}\n\n\/\/ IsMatch returns true if Record a matches b exactly in columns given by positions\nfunc (a *Record) IsMatch(b *Record, positions ...int) bool {\n\tif len(positions) <= 0 {\n\t\tpositions = make([]int, len(a.Atts))\n\t\tfor i := range positions {\n\t\t\tpositions[i] = i\n\t\t}\n\t}\n\te := make([]Atter, len(positions))\n\treturn a.IsMatchWithRanges(b, e, positions...)\n}\n\n\/\/ IsMatchWithRanges returns true if Record a matches b in columns specified in\n\/\/ positions. e is a slice of Atters to use for +\/- range comparisons in columns\n\/\/ of the same index\nfunc (a *Record) IsMatchWithRanges(b *Record, e []Atter, positions ...int) bool {\n\tif len(a.Atts) != len(b.Atts) {\n\t\treturn false\n\t}\n\tif len(positions) <= 0 {\n\t\tpositions = make([]int, len(a.Atts))\n\t\tfor i := range positions {\n\t\t\tpositions[i] = i\n\t\t}\n\t}\n\tif len(positions) > len(e) {\n\t\treturn false\n\t}\n\tmatches := make([]bool, len(positions))\n\tfor i, n := range positions {\n\t\tmatches[i] = a.isMatchAt(b, e[i], n)\n\t}\n\tfor _, m := range matches {\n\t\tif !m {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ isMatchAt returns true if single attribute column in i matches between\n\/\/ a & b with given +\/- range e\nfunc (a *Record) isMatchAt(b *Record, e Atter, i int) bool {\n\tif i >= 0 && i < len(a.Atts) && i < len(b.Atts) {\n\t\treturn a.Atts[i].Equal(b.Atts[i], e)\n\t}\n\treturn false\n}\n\n\/\/ Records is just a slice of Record types\ntype Records []Record\n\n\/\/NewRecordsFromCSV parses an CSV formatted io.Reader to create\n\/\/Records for matching. We assume the first line is a header row which\n\/\/is skipped.\n\/\/TODO we should make this more robust with checking number of columns etc\nfunc NewRecordsFromCSV(in io.Reader, skipHeader bool) (r Records, err error) {\n\tcsv := csv.NewReader(in)\n\tlineno := 0\n\n\tfor {\n\t\tlineno++\n\t\tline, err := csv.Read()\n\t\tif io.EOF == err {\n\t\t\terr = nil\n\t\t\tbreak\n\t\t} else if nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tif skipHeader && 1 == lineno {\n\t\t\tcontinue \/\/skip header\n\t\t}\n\t\ta := []Atter{}\n\t\tfor _, v := range line[1:] {\n\t\t\tn, err := strconv.ParseFloat(v, 64)\n\t\t\tif nil == err {\n\t\t\t\ta = append(a, NumericAtt{n})\n\t\t\t} else {\n\t\t\t\ta = append(a, TextAtt{v})\n\t\t\t}\n\t\t}\n\t\tr = append(r, Record{ID: line[0], Atts: a})\n\t}\n\n\treturn r, nil\n}\n\nfunc (r *Records) Get(t string) Record {\n\tfor _, v := range *r {\n\t\tif v.ID == t {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn Record{}\n}\n\n\/\/ MatchesAll returns a slice containing the indices of r that match to a with\n\/\/ the given +\/- ranges in e\nfunc (a *Record) MatchesAll(r Records, e ...Atter) []int {\n\tpositions := make([]int, len(a.Atts))\n\tfor i := range a.Atts {\n\t\tpositions[i] = i\n\t}\n\treturn a.Matches(r, positions, e...)\n}\n\n\/\/ Matches retruns a slice containing the indices from r that match to a at\n\/\/ attributes in positions with any given +\/- ranges in e\nfunc (a *Record) Matches(r Records, positions []int, e ...Atter) (matches []int) {\n\tif len(e) <= 0 {\n\t\te = make([]Atter, len(positions))\n\t}\n\tfor i, b := range r {\n\t\tif a.IsMatchWithRanges(&b, e, positions...) {\n\t\t\tmatches = append(matches, i)\n\t\t}\n\t}\n\treturn\n}\n<commit_msg>Add a new Reader wrapper to make CRs into LFs<commit_after>\/\/ Copyright 2015 Stuart Glenn, OMRF. All rights reserved.\n\/\/ Use of this code is governed by a 3 clause BSD style license\n\/\/ Full license details in LICENSE file distributed with this software\n\npackage matcher\n\nimport (\n\t\"bufio\"\n\t\"encoding\/csv\"\n\t\"io\"\n\t\"strconv\"\n)\n\n\/\/ A Record holds a data to be matched based on attributes in Atts\ntype Record struct {\n\tID   string\n\tAtts []Atter\n}\n\n\/\/ IsMatch returns true if Record a matches b exactly in columns given by positions\nfunc (a *Record) IsMatch(b *Record, positions ...int) bool {\n\tif len(positions) <= 0 {\n\t\tpositions = make([]int, len(a.Atts))\n\t\tfor i := range positions {\n\t\t\tpositions[i] = i\n\t\t}\n\t}\n\te := make([]Atter, len(positions))\n\treturn a.IsMatchWithRanges(b, e, positions...)\n}\n\n\/\/ IsMatchWithRanges returns true if Record a matches b in columns specified in\n\/\/ positions. e is a slice of Atters to use for +\/- range comparisons in columns\n\/\/ of the same index\nfunc (a *Record) IsMatchWithRanges(b *Record, e []Atter, positions ...int) bool {\n\tif len(a.Atts) != len(b.Atts) {\n\t\treturn false\n\t}\n\tif len(positions) <= 0 {\n\t\tpositions = make([]int, len(a.Atts))\n\t\tfor i := range positions {\n\t\t\tpositions[i] = i\n\t\t}\n\t}\n\tif len(positions) > len(e) {\n\t\treturn false\n\t}\n\tmatches := make([]bool, len(positions))\n\tfor i, n := range positions {\n\t\tmatches[i] = a.isMatchAt(b, e[i], n)\n\t}\n\tfor _, m := range matches {\n\t\tif !m {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ isMatchAt returns true if single attribute column in i matches between\n\/\/ a & b with given +\/- range e\nfunc (a *Record) isMatchAt(b *Record, e Atter, i int) bool {\n\tif i >= 0 && i < len(a.Atts) && i < len(b.Atts) {\n\t\treturn a.Atts[i].Equal(b.Atts[i], e)\n\t}\n\treturn false\n}\n\n\/\/ Records is just a slice of Record types\ntype Records []Record\n\ntype crReader struct {\n\tr *bufio.Reader\n}\n\nfunc newcrReader(r io.Reader) io.Reader {\n\treturn crReader{bufio.NewReader(r)}\n}\n\nfunc (r crReader) Read(b []byte) (int, error) {\n\tn, err := r.r.Read(b)\n\tif n <= 0 {\n\t\treturn n, err\n\t}\n\tb = b[:n]\n\tfor i := range b {\n\t\tif b[i] == '\\r' {\n\t\t\tvar next byte\n\t\t\tif j := i + 1; j < len(b) {\n\t\t\t\tnext = b[j]\n\t\t\t} else {\n\t\t\t\tnext, err = r.r.ReadByte()\n\t\t\t\tif err == nil {\n\t\t\t\t\tr.r.UnreadByte()\n\t\t\t\t}\n\t\t\t}\n\t\t\tif next != '\\n' {\n\t\t\t\tb[i] = '\\n'\n\t\t\t}\n\t\t}\n\t}\n\treturn n, err\n}\n\n\/\/NewRecordsFromCSV parses an CSV formatted io.Reader to create\n\/\/Records for matching. We assume the first line is a header row which\n\/\/is skipped.\n\/\/TODO we should make this more robust with checking number of columns etc\nfunc NewRecordsFromCSV(in io.Reader, skipHeader bool) (r Records, err error) {\n\tcsv := csv.NewReader(newcrReader(in))\n\tlineno := 0\n\n\tfor {\n\t\tlineno++\n\t\tline, err := csv.Read()\n\t\tif io.EOF == err {\n\t\t\terr = nil\n\t\t\tbreak\n\t\t} else if nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tif skipHeader && 1 == lineno {\n\t\t\tcontinue \/\/skip header\n\t\t}\n\t\ta := []Atter{}\n\t\tfor _, v := range line[1:] {\n\t\t\tn, err := strconv.ParseFloat(v, 64)\n\t\t\tif nil == err {\n\t\t\t\ta = append(a, NumericAtt{n})\n\t\t\t} else {\n\t\t\t\ta = append(a, TextAtt{v})\n\t\t\t}\n\t\t}\n\t\tr = append(r, Record{ID: line[0], Atts: a})\n\t}\n\n\treturn r, nil\n}\n\nfunc (r *Records) Get(t string) Record {\n\tfor _, v := range *r {\n\t\tif v.ID == t {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn Record{}\n}\n\n\/\/ MatchesAll returns a slice containing the indices of r that match to a with\n\/\/ the given +\/- ranges in e\nfunc (a *Record) MatchesAll(r Records, e ...Atter) []int {\n\tpositions := make([]int, len(a.Atts))\n\tfor i := range a.Atts {\n\t\tpositions[i] = i\n\t}\n\treturn a.Matches(r, positions, e...)\n}\n\n\/\/ Matches retruns a slice containing the indices from r that match to a at\n\/\/ attributes in positions with any given +\/- ranges in e\nfunc (a *Record) Matches(r Records, positions []int, e ...Atter) (matches []int) {\n\tif len(e) <= 0 {\n\t\te = make([]Atter, len(positions))\n\t}\n\tfor i, b := range r {\n\t\tif a.IsMatchWithRanges(&b, e, positions...) {\n\t\t\tmatches = append(matches, i)\n\t\t}\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage core\n\nimport (\n\t\"github.com\/pingcap\/parser\/ast\"\n\t\"github.com\/pingcap\/parser\/model\"\n\t\"github.com\/pingcap\/tidb\/kv\"\n\t\"github.com\/pingcap\/tidb\/sessionctx\"\n\tutilhint \"github.com\/pingcap\/tidb\/util\/hint\"\n)\n\n\/\/ GenHintsFromPhysicalPlan generates hints from physical plan.\nfunc GenHintsFromPhysicalPlan(p Plan) []*ast.TableOptimizerHint {\n\tvar hints []*ast.TableOptimizerHint\n\tswitch pp := p.(type) {\n\tcase *Explain:\n\t\treturn GenHintsFromPhysicalPlan(pp.TargetPlan)\n\tcase *Update:\n\t\thints = genHintsFromPhysicalPlan(pp.SelectPlan, utilhint.TypeUpdate)\n\tcase *Delete:\n\t\thints = genHintsFromPhysicalPlan(pp.SelectPlan, utilhint.TypeDelete)\n\t\/\/ For Insert, we only generate hints that would be used in select query block.\n\tcase *Insert:\n\t\thints = genHintsFromPhysicalPlan(pp.SelectPlan, utilhint.TypeSelect)\n\tcase PhysicalPlan:\n\t\thints = genHintsFromPhysicalPlan(pp, utilhint.TypeSelect)\n\t}\n\treturn hints\n}\n\nfunc getTableName(tblName model.CIStr, asName *model.CIStr) model.CIStr {\n\tif asName != nil && asName.L != \"\" {\n\t\treturn *asName\n\t}\n\treturn tblName\n}\n\nfunc extractTableAsName(p PhysicalPlan) (*model.CIStr, *model.CIStr) {\n\t_, isProj := p.(*PhysicalProjection)\n\t_, isUnionScan := p.(*PhysicalUnionScan)\n\tif isProj || isUnionScan {\n\t\treturn extractTableAsName(p.Children()[0])\n\t}\n\tif len(p.Children()) > 1 {\n\t\treturn nil, nil\n\t}\n\tswitch x := p.(type) {\n\tcase *PhysicalTableReader:\n\t\tts := x.TablePlans[0].(*PhysicalTableScan)\n\t\tif ts.TableAsName.L != \"\" {\n\t\t\treturn &ts.DBName, ts.TableAsName\n\t\t}\n\t\treturn &ts.DBName, &ts.Table.Name\n\tcase *PhysicalIndexReader:\n\t\tis := x.IndexPlans[0].(*PhysicalIndexScan)\n\t\tif is.TableAsName.L != \"\" {\n\t\t\treturn &is.DBName, is.TableAsName\n\t\t}\n\t\treturn &is.DBName, &is.Table.Name\n\tcase *PhysicalIndexLookUpReader:\n\t\tis := x.IndexPlans[0].(*PhysicalIndexScan)\n\t\tif is.TableAsName.L != \"\" {\n\t\t\treturn &is.DBName, is.TableAsName\n\t\t}\n\t\treturn &is.DBName, &is.Table.Name\n\t}\n\treturn nil, nil\n}\n\nfunc getJoinHints(sctx sessionctx.Context, joinType string, parentOffset int, nodeType utilhint.NodeType, children ...PhysicalPlan) (res []*ast.TableOptimizerHint) {\n\tif parentOffset == -1 {\n\t\treturn res\n\t}\n\tfor _, child := range children {\n\t\tblockOffset := child.SelectBlockOffset()\n\t\tif blockOffset == -1 {\n\t\t\tcontinue\n\t\t}\n\t\tvar dbName, tableName *model.CIStr\n\t\tif child.SelectBlockOffset() != parentOffset {\n\t\t\thintTable := sctx.GetSessionVars().PlannerSelectBlockAsName[child.SelectBlockOffset()]\n\t\t\t\/\/ For sub-queries like `(select * from t) t1`, t1 should belong to its surrounding select block.\n\t\t\tdbName, tableName, blockOffset = &hintTable.DBName, &hintTable.TableName, parentOffset\n\t\t} else {\n\t\t\tdbName, tableName = extractTableAsName(child)\n\t\t}\n\t\tif tableName == nil || tableName.L == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tqbName, err := utilhint.GenerateQBName(nodeType, blockOffset)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(joinType),\n\t\t\tTables:   []ast.HintTable{{DBName: *dbName, TableName: *tableName}},\n\t\t})\n\t\tbreak\n\t}\n\treturn res\n}\n\nfunc genHintsFromPhysicalPlan(p PhysicalPlan, nodeType utilhint.NodeType) (res []*ast.TableOptimizerHint) {\n\tif p == nil {\n\t\treturn res\n\t}\n\tfor _, child := range p.Children() {\n\t\tres = append(res, genHintsFromPhysicalPlan(child, nodeType)...)\n\t}\n\tqbName, err := utilhint.GenerateQBName(nodeType, p.SelectBlockOffset())\n\tif err != nil {\n\t\treturn res\n\t}\n\tswitch pp := p.(type) {\n\tcase *PhysicalTableReader:\n\t\ttbl := pp.TablePlans[0].(*PhysicalTableScan)\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(HintUseIndex),\n\t\t\tTables:   []ast.HintTable{{DBName: tbl.DBName, TableName: getTableName(tbl.Table.Name, tbl.TableAsName)}},\n\t\t})\n\t\tif tbl.StoreType == kv.TiFlash {\n\t\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\t\tQBName:   qbName,\n\t\t\t\tHintName: model.NewCIStr(HintReadFromStorage),\n\t\t\t\tHintData: model.NewCIStr(kv.TiFlash.Name()),\n\t\t\t\tTables:   []ast.HintTable{{DBName: tbl.DBName, TableName: getTableName(tbl.Table.Name, tbl.TableAsName)}},\n\t\t\t})\n\t\t}\n\tcase *PhysicalIndexLookUpReader:\n\t\tindex := pp.IndexPlans[0].(*PhysicalIndexScan)\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(HintUseIndex),\n\t\t\tTables:   []ast.HintTable{{DBName: index.DBName, TableName: getTableName(index.Table.Name, index.TableAsName)}},\n\t\t\tIndexes:  []model.CIStr{index.Index.Name},\n\t\t})\n\tcase *PhysicalIndexReader:\n\t\tindex := pp.IndexPlans[0].(*PhysicalIndexScan)\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(HintUseIndex),\n\t\t\tTables:   []ast.HintTable{{DBName: index.DBName, TableName: getTableName(index.Table.Name, index.TableAsName)}},\n\t\t\tIndexes:  []model.CIStr{index.Index.Name},\n\t\t})\n\tcase *PhysicalIndexMergeReader:\n\t\tIndexs := make([]model.CIStr, 0, 2)\n\t\tvar tableName model.CIStr\n\t\tvar tableAsName *model.CIStr\n\t\tfor _, partialPlan := range pp.PartialPlans {\n\t\t\tif index, ok := partialPlan[0].(*PhysicalIndexScan); ok {\n\t\t\t\tIndexs = append(Indexs, index.Index.Name)\n\t\t\t\ttableName = index.Table.Name\n\t\t\t\ttableAsName = index.TableAsName\n\t\t\t} else {\n\t\t\t\tindexName := model.NewCIStr(\"PRIMARY\")\n\t\t\t\tIndexs = append(Indexs, indexName)\n\t\t\t}\n\t\t}\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(HintIndexMerge),\n\t\t\tTables:   []ast.HintTable{{TableName: getTableName(tableName, tableAsName)}},\n\t\t\tIndexes:  Indexs,\n\t\t})\n\tcase *PhysicalHashAgg:\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(HintHashAgg),\n\t\t})\n\tcase *PhysicalStreamAgg:\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(HintStreamAgg),\n\t\t})\n\tcase *PhysicalMergeJoin:\n\t\tres = append(res, getJoinHints(p.SCtx(), HintSMJ, p.SelectBlockOffset(), nodeType, pp.children...)...)\n\tcase *PhysicalHashJoin:\n\t\tres = append(res, getJoinHints(p.SCtx(), HintHJ, p.SelectBlockOffset(), nodeType, pp.children...)...)\n\tcase *PhysicalIndexJoin:\n\t\tres = append(res, getJoinHints(p.SCtx(), HintINLJ, p.SelectBlockOffset(), nodeType, pp.children[pp.InnerChildIdx])...)\n\tcase *PhysicalIndexMergeJoin:\n\t\tres = append(res, getJoinHints(p.SCtx(), HintINLMJ, p.SelectBlockOffset(), nodeType, pp.children[pp.InnerChildIdx])...)\n\tcase *PhysicalIndexHashJoin:\n\t\tres = append(res, getJoinHints(p.SCtx(), HintINLHJ, p.SelectBlockOffset(), nodeType, pp.children[pp.InnerChildIdx])...)\n\t}\n\treturn res\n}\n<commit_msg>planner: avoid potential panic when generating hints from joins (#22515)<commit_after>\/\/ Copyright 2019 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage core\n\nimport (\n\t\"github.com\/pingcap\/parser\/ast\"\n\t\"github.com\/pingcap\/parser\/model\"\n\t\"github.com\/pingcap\/tidb\/kv\"\n\t\"github.com\/pingcap\/tidb\/sessionctx\"\n\tutilhint \"github.com\/pingcap\/tidb\/util\/hint\"\n)\n\n\/\/ GenHintsFromPhysicalPlan generates hints from physical plan.\nfunc GenHintsFromPhysicalPlan(p Plan) []*ast.TableOptimizerHint {\n\tvar hints []*ast.TableOptimizerHint\n\tswitch pp := p.(type) {\n\tcase *Explain:\n\t\treturn GenHintsFromPhysicalPlan(pp.TargetPlan)\n\tcase *Update:\n\t\thints = genHintsFromPhysicalPlan(pp.SelectPlan, utilhint.TypeUpdate)\n\tcase *Delete:\n\t\thints = genHintsFromPhysicalPlan(pp.SelectPlan, utilhint.TypeDelete)\n\t\/\/ For Insert, we only generate hints that would be used in select query block.\n\tcase *Insert:\n\t\thints = genHintsFromPhysicalPlan(pp.SelectPlan, utilhint.TypeSelect)\n\tcase PhysicalPlan:\n\t\thints = genHintsFromPhysicalPlan(pp, utilhint.TypeSelect)\n\t}\n\treturn hints\n}\n\nfunc getTableName(tblName model.CIStr, asName *model.CIStr) model.CIStr {\n\tif asName != nil && asName.L != \"\" {\n\t\treturn *asName\n\t}\n\treturn tblName\n}\n\nfunc extractTableAsName(p PhysicalPlan) (*model.CIStr, *model.CIStr) {\n\t_, isProj := p.(*PhysicalProjection)\n\t_, isUnionScan := p.(*PhysicalUnionScan)\n\tif isProj || isUnionScan {\n\t\treturn extractTableAsName(p.Children()[0])\n\t}\n\tif len(p.Children()) > 1 {\n\t\treturn nil, nil\n\t}\n\tswitch x := p.(type) {\n\tcase *PhysicalTableReader:\n\t\tts := x.TablePlans[0].(*PhysicalTableScan)\n\t\tif ts.TableAsName.L != \"\" {\n\t\t\treturn &ts.DBName, ts.TableAsName\n\t\t}\n\t\treturn &ts.DBName, &ts.Table.Name\n\tcase *PhysicalIndexReader:\n\t\tis := x.IndexPlans[0].(*PhysicalIndexScan)\n\t\tif is.TableAsName.L != \"\" {\n\t\t\treturn &is.DBName, is.TableAsName\n\t\t}\n\t\treturn &is.DBName, &is.Table.Name\n\tcase *PhysicalIndexLookUpReader:\n\t\tis := x.IndexPlans[0].(*PhysicalIndexScan)\n\t\tif is.TableAsName.L != \"\" {\n\t\t\treturn &is.DBName, is.TableAsName\n\t\t}\n\t\treturn &is.DBName, &is.Table.Name\n\t}\n\treturn nil, nil\n}\n\nfunc getJoinHints(sctx sessionctx.Context, joinType string, parentOffset int, nodeType utilhint.NodeType, children ...PhysicalPlan) (res []*ast.TableOptimizerHint) {\n\tif parentOffset == -1 {\n\t\treturn res\n\t}\n\tfor _, child := range children {\n\t\tblockOffset := child.SelectBlockOffset()\n\t\tif blockOffset == -1 {\n\t\t\tcontinue\n\t\t}\n\t\tvar dbName, tableName *model.CIStr\n\t\tif blockOffset != parentOffset {\n\t\t\tblockAsNames := sctx.GetSessionVars().PlannerSelectBlockAsName\n\t\t\tif blockOffset >= len(blockAsNames) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\thintTable := blockAsNames[blockOffset]\n\t\t\t\/\/ For sub-queries like `(select * from t) t1`, t1 should belong to its surrounding select block.\n\t\t\tdbName, tableName, blockOffset = &hintTable.DBName, &hintTable.TableName, parentOffset\n\t\t} else {\n\t\t\tdbName, tableName = extractTableAsName(child)\n\t\t}\n\t\tif tableName == nil || tableName.L == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tqbName, err := utilhint.GenerateQBName(nodeType, blockOffset)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(joinType),\n\t\t\tTables:   []ast.HintTable{{DBName: *dbName, TableName: *tableName}},\n\t\t})\n\t\tbreak\n\t}\n\treturn res\n}\n\nfunc genHintsFromPhysicalPlan(p PhysicalPlan, nodeType utilhint.NodeType) (res []*ast.TableOptimizerHint) {\n\tif p == nil {\n\t\treturn res\n\t}\n\tfor _, child := range p.Children() {\n\t\tres = append(res, genHintsFromPhysicalPlan(child, nodeType)...)\n\t}\n\tqbName, err := utilhint.GenerateQBName(nodeType, p.SelectBlockOffset())\n\tif err != nil {\n\t\treturn res\n\t}\n\tswitch pp := p.(type) {\n\tcase *PhysicalTableReader:\n\t\ttbl := pp.TablePlans[0].(*PhysicalTableScan)\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(HintUseIndex),\n\t\t\tTables:   []ast.HintTable{{DBName: tbl.DBName, TableName: getTableName(tbl.Table.Name, tbl.TableAsName)}},\n\t\t})\n\t\tif tbl.StoreType == kv.TiFlash {\n\t\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\t\tQBName:   qbName,\n\t\t\t\tHintName: model.NewCIStr(HintReadFromStorage),\n\t\t\t\tHintData: model.NewCIStr(kv.TiFlash.Name()),\n\t\t\t\tTables:   []ast.HintTable{{DBName: tbl.DBName, TableName: getTableName(tbl.Table.Name, tbl.TableAsName)}},\n\t\t\t})\n\t\t}\n\tcase *PhysicalIndexLookUpReader:\n\t\tindex := pp.IndexPlans[0].(*PhysicalIndexScan)\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(HintUseIndex),\n\t\t\tTables:   []ast.HintTable{{DBName: index.DBName, TableName: getTableName(index.Table.Name, index.TableAsName)}},\n\t\t\tIndexes:  []model.CIStr{index.Index.Name},\n\t\t})\n\tcase *PhysicalIndexReader:\n\t\tindex := pp.IndexPlans[0].(*PhysicalIndexScan)\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(HintUseIndex),\n\t\t\tTables:   []ast.HintTable{{DBName: index.DBName, TableName: getTableName(index.Table.Name, index.TableAsName)}},\n\t\t\tIndexes:  []model.CIStr{index.Index.Name},\n\t\t})\n\tcase *PhysicalIndexMergeReader:\n\t\tIndexs := make([]model.CIStr, 0, 2)\n\t\tvar tableName model.CIStr\n\t\tvar tableAsName *model.CIStr\n\t\tfor _, partialPlan := range pp.PartialPlans {\n\t\t\tif index, ok := partialPlan[0].(*PhysicalIndexScan); ok {\n\t\t\t\tIndexs = append(Indexs, index.Index.Name)\n\t\t\t\ttableName = index.Table.Name\n\t\t\t\ttableAsName = index.TableAsName\n\t\t\t} else {\n\t\t\t\tindexName := model.NewCIStr(\"PRIMARY\")\n\t\t\t\tIndexs = append(Indexs, indexName)\n\t\t\t}\n\t\t}\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(HintIndexMerge),\n\t\t\tTables:   []ast.HintTable{{TableName: getTableName(tableName, tableAsName)}},\n\t\t\tIndexes:  Indexs,\n\t\t})\n\tcase *PhysicalHashAgg:\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(HintHashAgg),\n\t\t})\n\tcase *PhysicalStreamAgg:\n\t\tres = append(res, &ast.TableOptimizerHint{\n\t\t\tQBName:   qbName,\n\t\t\tHintName: model.NewCIStr(HintStreamAgg),\n\t\t})\n\tcase *PhysicalMergeJoin:\n\t\tres = append(res, getJoinHints(p.SCtx(), HintSMJ, p.SelectBlockOffset(), nodeType, pp.children...)...)\n\tcase *PhysicalHashJoin:\n\t\tres = append(res, getJoinHints(p.SCtx(), HintHJ, p.SelectBlockOffset(), nodeType, pp.children...)...)\n\tcase *PhysicalIndexJoin:\n\t\tres = append(res, getJoinHints(p.SCtx(), HintINLJ, p.SelectBlockOffset(), nodeType, pp.children[pp.InnerChildIdx])...)\n\tcase *PhysicalIndexMergeJoin:\n\t\tres = append(res, getJoinHints(p.SCtx(), HintINLMJ, p.SelectBlockOffset(), nodeType, pp.children[pp.InnerChildIdx])...)\n\tcase *PhysicalIndexHashJoin:\n\t\tres = append(res, getJoinHints(p.SCtx(), HintINLHJ, p.SelectBlockOffset(), nodeType, pp.children[pp.InnerChildIdx])...)\n\t}\n\treturn res\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"google.golang.org\/grpc\/grpclog\"\n)\n\n\/\/ TODO - needs to be integrated with the CLI output stream (*cli.OutStream)\n\/\/ to suppress any terminal formatting codes when not attached to a tty;\n\/\/ then add terminal formatting (color) support for CLI info\/warn\/success\/fail functions.\n\n\/\/ Logger is a simple logger for the Atomiq CLI that also implements grpclog.Logger\ntype Logger struct {\n\tout     *OutStream\n\tverbose bool\n}\n\nfunc init() {\n\t\/\/ Creates an instance of Logger for grpc logging\n\t\/\/ WARNING: the grpc logger can only be set during init()\n\t\/\/ https:\/\/godoc.org\/google.golang.org\/grpc\/grpclog#SetLogger\n\t\/\/ TODO: set verbose to false after testing\n\tgrpclog.SetLogger(Logger{out: NewOutStream(os.Stdout), verbose: true})\n}\n\n\/\/ NewLogger creates a CLI Logger instance that writes to the provided stream.\nfunc NewLogger(out *OutStream, verbose bool) *Logger {\n\treturn &Logger{out: out, verbose: verbose}\n}\n\n\/\/ Verbose returns whether the logger is verbose\nfunc (l Logger) Verbose() bool {\n\treturn l.verbose\n}\n\n\/\/ OutStream return the underlying output stream\nfunc (l Logger) OutStream() *OutStream {\n\treturn l.out\n}\n\n\/\/ Fatal is equivalent to fmt.Print() followed by a call to os.Exit(1).\nfunc (l Logger) Fatal(args ...interface{}) {\n\tl.Print(args)\n\tos.Exit(1)\n}\n\n\/\/ Fatalf is equivalent to fmt.Printf() followed by a call to os.Exit(1).\nfunc (l Logger) Fatalf(format string, args ...interface{}) {\n\tl.Printf(format, args)\n\tos.Exit(1)\n}\n\n\/\/ Fatalln is equivalent to fmt.Println() followed by a call to os.Exit(1).\nfunc (l Logger) Fatalln(args ...interface{}) {\n\tl.Println(args)\n\tos.Exit(1)\n}\n\n\/\/ Print is equivalent to fmt.Print() if verbose mode.\n\/\/ Arguments are handled in the manner of fmt.Printf.\nfunc (l Logger) Print(args ...interface{}) {\n\tif l.verbose {\n\t\tfmt.Fprint(l.out, args)\n\t}\n}\n\n\/\/ Printf is equivalent to fmt.Printf() if verbose mode.\nfunc (l Logger) Printf(format string, args ...interface{}) {\n\tif l.verbose {\n\t\tfmt.Fprintf(l.out, format, args)\n\t}\n}\n\n\/\/ Println is equivalent to fmt.Println() if verbose mode.\nfunc (l Logger) Println(args ...interface{}) {\n\tif l.verbose {\n\t\tfmt.Fprintln(l.out, args)\n\t}\n}\n<commit_msg>Set CLI logger to non verbose (#1429)<commit_after>package cli\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"google.golang.org\/grpc\/grpclog\"\n)\n\n\/\/ TODO - needs to be integrated with the CLI output stream (*cli.OutStream)\n\/\/ to suppress any terminal formatting codes when not attached to a tty;\n\/\/ then add terminal formatting (color) support for CLI info\/warn\/success\/fail functions.\n\n\/\/ Logger is a simple logger for the Atomiq CLI that also implements grpclog.Logger\ntype Logger struct {\n\tout     *OutStream\n\tverbose bool\n}\n\nfunc init() {\n\t\/\/ Creates an instance of Logger for grpc logging\n\t\/\/ WARNING: the grpc logger can only be set during init()\n\t\/\/ https:\/\/godoc.org\/google.golang.org\/grpc\/grpclog#SetLogger\n\tgrpclog.SetLogger(Logger{out: NewOutStream(os.Stdout), verbose: false})\n}\n\n\/\/ NewLogger creates a CLI Logger instance that writes to the provided stream.\nfunc NewLogger(out *OutStream, verbose bool) *Logger {\n\treturn &Logger{out: out, verbose: verbose}\n}\n\n\/\/ Verbose returns whether the logger is verbose\nfunc (l Logger) Verbose() bool {\n\treturn l.verbose\n}\n\n\/\/ OutStream return the underlying output stream\nfunc (l Logger) OutStream() *OutStream {\n\treturn l.out\n}\n\n\/\/ Fatal is equivalent to fmt.Print() followed by a call to os.Exit(1).\nfunc (l Logger) Fatal(args ...interface{}) {\n\tl.Print(args)\n\tos.Exit(1)\n}\n\n\/\/ Fatalf is equivalent to fmt.Printf() followed by a call to os.Exit(1).\nfunc (l Logger) Fatalf(format string, args ...interface{}) {\n\tl.Printf(format, args)\n\tos.Exit(1)\n}\n\n\/\/ Fatalln is equivalent to fmt.Println() followed by a call to os.Exit(1).\nfunc (l Logger) Fatalln(args ...interface{}) {\n\tl.Println(args)\n\tos.Exit(1)\n}\n\n\/\/ Print is equivalent to fmt.Print() if verbose mode.\n\/\/ Arguments are handled in the manner of fmt.Printf.\nfunc (l Logger) Print(args ...interface{}) {\n\tif l.verbose {\n\t\tfmt.Fprint(l.out, args)\n\t}\n}\n\n\/\/ Printf is equivalent to fmt.Printf() if verbose mode.\nfunc (l Logger) Printf(format string, args ...interface{}) {\n\tif l.verbose {\n\t\tfmt.Fprintf(l.out, format, args)\n\t}\n}\n\n\/\/ Println is equivalent to fmt.Println() if verbose mode.\nfunc (l Logger) Println(args ...interface{}) {\n\tif l.verbose {\n\t\tfmt.Fprintln(l.out, args)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport \"fmt\"\n\ntype API struct {\n\tSchema    string `valid:\"required\"`\n\tHost      string `valid:\"host,required\"`\n\tPort      string `valid:\"port,required\"`\n\tApiPrefix string `valid:\"required\"`\n}\n\nfunc (a API) URL() string {\n\treturn fmt.Sprintf(\"%s:\/\/%s:%d\/%s\/policy\", a.Schema, a.Host, a.Port, a.ApiPrefix)\n}\n\nfunc (a API) ListenAddr() string {\n\treturn fmt.Sprintf(\"%s:%d\", a.Host, a.Port)\n}\n<commit_msg>Remove accidentaly not moved package<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2011 The Camlistore Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ Package mysql provides an implementation of sorted.KeyValue\n\/\/ on top of MySQL.\npackage mysql\n\nimport (\n\t\"database\/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"camlistore.org\/pkg\/env\"\n\t\"camlistore.org\/pkg\/sorted\"\n\t\"camlistore.org\/pkg\/sorted\/sqlkv\"\n\t_ \"camlistore.org\/third_party\/github.com\/go-sql-driver\/mysql\"\n\t\"go4.org\/jsonconfig\"\n)\n\nfunc init() {\n\tsorted.RegisterKeyValue(\"mysql\", newKeyValueFromJSONConfig)\n}\n\nfunc newKeyValueFromJSONConfig(cfg jsonconfig.Obj) (sorted.KeyValue, error) {\n\tvar (\n\t\tuser     = cfg.RequiredString(\"user\")\n\t\tdatabase = cfg.RequiredString(\"database\")\n\t\thost     = cfg.OptionalString(\"host\", \"\")\n\t\tpassword = cfg.OptionalString(\"password\", \"\")\n\t)\n\tif err := cfg.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tvar err error\n\tif host != \"\" {\n\t\thost, err = maybeRemapCloudSQL(host)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !strings.Contains(host, \":\") {\n\t\t\thost += \":3306\"\n\t\t}\n\t\thost = \"tcp(\" + host + \")\"\n\t}\n\t\/\/ The DSN does NOT have a database name in it so it's\n\t\/\/ cacheable and can be shared between different queues & the\n\t\/\/ index, all sharing the same database server, cutting down\n\t\/\/ number of TCP connections required. We add the database\n\t\/\/ name in queries instead.\n\tdsn := fmt.Sprintf(\"%s:%s@%s\/\", user, password, host)\n\n\tdb, err := openOrCachedDB(dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := CreateDB(db, database); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, tableSQL := range SQLCreateTables() {\n\t\ttableSQL = strings.Replace(tableSQL, \"\/*DB*\/\", database, -1)\n\t\tif _, err := db.Exec(tableSQL); err != nil {\n\t\t\terrMsg := \"error creating table with %q: %v.\"\n\t\t\tcreateError := err\n\t\t\tsv, err := serverVersion(db)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif !hasLargeVarchar(sv) {\n\t\t\t\terrMsg += \"\\nYour MySQL server is too old (< 5.0.3) to support VARCHAR larger than 255.\"\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(errMsg, tableSQL, createError)\n\t\t}\n\t}\n\tif _, err := db.Exec(fmt.Sprintf(`REPLACE INTO %s.meta VALUES ('version', '%d')`, database, SchemaVersion())); err != nil {\n\t\treturn nil, fmt.Errorf(\"error setting schema version: %v\", err)\n\t}\n\n\tkv := &keyValue{\n\t\tdb: db,\n\t\tKeyValue: &sqlkv.KeyValue{\n\t\t\tDB:          db,\n\t\t\tTablePrefix: database + \".\",\n\t\t},\n\t}\n\tif err := kv.ping(); err != nil {\n\t\treturn nil, fmt.Errorf(\"MySQL db unreachable: %v\", err)\n\t}\n\tversion, err := kv.SchemaVersion()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting schema version (need to init database?): %v\", err)\n\t}\n\tif version != requiredSchemaVersion {\n\t\tif version == 20 && requiredSchemaVersion == 21 {\n\t\t\tfmt.Fprintf(os.Stderr, fixSchema20to21)\n\t\t}\n\t\tif env.IsDev() {\n\t\t\t\/\/ Good signal that we're using the devcam server, so help out\n\t\t\t\/\/ the user with a more useful tip:\n\t\t\treturn nil, fmt.Errorf(\"database schema version is %d; expect %d (run \\\"devcam server --wipe\\\" to wipe both your blobs and re-populate the database schema)\", version, requiredSchemaVersion)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"database schema version is %d; expect %d (need to re-init\/upgrade database?)\",\n\t\t\tversion, requiredSchemaVersion)\n\t}\n\n\treturn kv, nil\n}\n\n\/\/ CreateDB creates the named database if it does not already exist.\nfunc CreateDB(db *sql.DB, dbname string) error {\n\tif dbname == \"\" {\n\t\treturn errors.New(\"can not create database: database name is missing\")\n\t}\n\tif _, err := db.Exec(fmt.Sprintf(\"CREATE DATABASE IF NOT EXISTS %s\", dbname)); err != nil {\n\t\treturn fmt.Errorf(\"error creating database %v: %v\", dbname, err)\n\t}\n\treturn nil\n}\n\n\/\/ We keep a cache of open database handles.\nvar (\n\tdbsmu sync.Mutex\n\tdbs   = map[string]*sql.DB{} \/\/ DSN -> db\n)\n\nfunc openOrCachedDB(dsn string) (*sql.DB, error) {\n\tdbsmu.Lock()\n\tdefer dbsmu.Unlock()\n\tif db, ok := dbs[dsn]; ok {\n\t\treturn db, nil\n\t}\n\tdb, err := sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdbs[dsn] = db\n\treturn db, nil\n}\n\ntype keyValue struct {\n\t*sqlkv.KeyValue\n\n\tdb *sql.DB\n}\n\nfunc (kv *keyValue) ping() error {\n\t\/\/ TODO(bradfitz): something more efficient here?\n\t_, err := kv.SchemaVersion()\n\treturn err\n}\n\nfunc (kv *keyValue) SchemaVersion() (version int, err error) {\n\terr = kv.db.QueryRow(\"SELECT value FROM \" + kv.KeyValue.TablePrefix + \"meta WHERE metakey='version'\").Scan(&version)\n\treturn\n}\n\nconst fixSchema20to21 = `Character set in tables changed to binary, you can fix your tables with:\nALTER TABLE rows CONVERT TO CHARACTER SET binary;\nALTER TABLE meta CONVERT TO CHARACTER SET binary;\nUPDATE meta SET value=21 WHERE metakey='version' AND value=20;\n`\n\n\/\/ serverVersion returns the MySQL server version as []int{major, minor, revision}.\nfunc serverVersion(db *sql.DB) ([]int, error) {\n\tversionRx := regexp.MustCompile(`([0-9]+)\\.([0-9]+)\\.([0-9]+)-.*`)\n\tvar version string\n\tif err := db.QueryRow(\"SELECT VERSION()\").Scan(&version); err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting MySQL server version: %v\", err)\n\t}\n\tm := versionRx.FindStringSubmatch(version)\n\tif len(m) < 4 {\n\t\treturn nil, fmt.Errorf(\"bogus MySQL server version: %v\", version)\n\t}\n\tmajor, _ := strconv.Atoi(m[1])\n\tminor, _ := strconv.Atoi(m[2])\n\trev, _ := strconv.Atoi(m[3])\n\treturn []int{major, minor, rev}, nil\n}\n\n\/\/ hasLargeVarchar returns whether the given version (as []int{major, minor, revision})\n\/\/ supports VARCHAR larger than 255.\nfunc hasLargeVarchar(version []int) bool {\n\tif len(version) < 3 {\n\t\tpanic(fmt.Sprintf(\"bogus mysql server version %v: \", version))\n\t}\n\tif version[0] < 5 {\n\t\treturn false\n\t}\n\tif version[1] > 0 {\n\t\treturn true\n\t}\n\treturn version[0] == 5 && version[1] == 0 && version[2] >= 3\n}\n<commit_msg>sorted\/mysql: remove DB from pool when closing<commit_after>\/*\nCopyright 2011 The Camlistore Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ Package mysql provides an implementation of sorted.KeyValue\n\/\/ on top of MySQL.\npackage mysql\n\nimport (\n\t\"database\/sql\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"camlistore.org\/pkg\/env\"\n\t\"camlistore.org\/pkg\/sorted\"\n\t\"camlistore.org\/pkg\/sorted\/sqlkv\"\n\t_ \"camlistore.org\/third_party\/github.com\/go-sql-driver\/mysql\"\n\t\"go4.org\/jsonconfig\"\n)\n\nfunc init() {\n\tsorted.RegisterKeyValue(\"mysql\", newKeyValueFromJSONConfig)\n}\n\nfunc newKeyValueFromJSONConfig(cfg jsonconfig.Obj) (sorted.KeyValue, error) {\n\tvar (\n\t\tuser     = cfg.RequiredString(\"user\")\n\t\tdatabase = cfg.RequiredString(\"database\")\n\t\thost     = cfg.OptionalString(\"host\", \"\")\n\t\tpassword = cfg.OptionalString(\"password\", \"\")\n\t)\n\tif err := cfg.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tvar err error\n\tif host != \"\" {\n\t\thost, err = maybeRemapCloudSQL(host)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !strings.Contains(host, \":\") {\n\t\t\thost += \":3306\"\n\t\t}\n\t\thost = \"tcp(\" + host + \")\"\n\t}\n\t\/\/ The DSN does NOT have a database name in it so it's\n\t\/\/ cacheable and can be shared between different queues & the\n\t\/\/ index, all sharing the same database server, cutting down\n\t\/\/ number of TCP connections required. We add the database\n\t\/\/ name in queries instead.\n\tdsn := fmt.Sprintf(\"%s:%s@%s\/\", user, password, host)\n\n\tdb, err := openOrCachedDB(dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := CreateDB(db, database); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, tableSQL := range SQLCreateTables() {\n\t\ttableSQL = strings.Replace(tableSQL, \"\/*DB*\/\", database, -1)\n\t\tif _, err := db.Exec(tableSQL); err != nil {\n\t\t\terrMsg := \"error creating table with %q: %v.\"\n\t\t\tcreateError := err\n\t\t\tsv, err := serverVersion(db)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif !hasLargeVarchar(sv) {\n\t\t\t\terrMsg += \"\\nYour MySQL server is too old (< 5.0.3) to support VARCHAR larger than 255.\"\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(errMsg, tableSQL, createError)\n\t\t}\n\t}\n\tif _, err := db.Exec(fmt.Sprintf(`REPLACE INTO %s.meta VALUES ('version', '%d')`, database, SchemaVersion())); err != nil {\n\t\treturn nil, fmt.Errorf(\"error setting schema version: %v\", err)\n\t}\n\n\tkv := &keyValue{\n\t\tdsn: dsn,\n\t\tdb:  db,\n\t\tKeyValue: &sqlkv.KeyValue{\n\t\t\tDB:          db,\n\t\t\tTablePrefix: database + \".\",\n\t\t},\n\t}\n\tif err := kv.ping(); err != nil {\n\t\treturn nil, fmt.Errorf(\"MySQL db unreachable: %v\", err)\n\t}\n\tversion, err := kv.SchemaVersion()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting schema version (need to init database?): %v\", err)\n\t}\n\tif version != requiredSchemaVersion {\n\t\tif version == 20 && requiredSchemaVersion == 21 {\n\t\t\tfmt.Fprintf(os.Stderr, fixSchema20to21)\n\t\t}\n\t\tif env.IsDev() {\n\t\t\t\/\/ Good signal that we're using the devcam server, so help out\n\t\t\t\/\/ the user with a more useful tip:\n\t\t\treturn nil, fmt.Errorf(\"database schema version is %d; expect %d (run \\\"devcam server --wipe\\\" to wipe both your blobs and re-populate the database schema)\", version, requiredSchemaVersion)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"database schema version is %d; expect %d (need to re-init\/upgrade database?)\",\n\t\t\tversion, requiredSchemaVersion)\n\t}\n\n\treturn kv, nil\n}\n\n\/\/ CreateDB creates the named database if it does not already exist.\nfunc CreateDB(db *sql.DB, dbname string) error {\n\tif dbname == \"\" {\n\t\treturn errors.New(\"can not create database: database name is missing\")\n\t}\n\tif _, err := db.Exec(fmt.Sprintf(\"CREATE DATABASE IF NOT EXISTS %s\", dbname)); err != nil {\n\t\treturn fmt.Errorf(\"error creating database %v: %v\", dbname, err)\n\t}\n\treturn nil\n}\n\n\/\/ We keep a cache of open database handles.\nvar (\n\tdbsmu sync.Mutex\n\tdbs   = map[string]*sql.DB{} \/\/ DSN -> db\n)\n\nfunc openOrCachedDB(dsn string) (*sql.DB, error) {\n\tdbsmu.Lock()\n\tdefer dbsmu.Unlock()\n\tif db, ok := dbs[dsn]; ok {\n\t\treturn db, nil\n\t}\n\tdb, err := sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdbs[dsn] = db\n\treturn db, nil\n}\n\ntype keyValue struct {\n\t*sqlkv.KeyValue\n\n\tdsn string\n\tdb  *sql.DB\n}\n\n\/\/ Close overrides KeyValue.Close because we need to remove the DB from the pool\n\/\/ when closing.\nfunc (kv *keyValue) Close() error {\n\tdbsmu.Lock()\n\tdefer dbsmu.Unlock()\n\tdelete(dbs, kv.dsn)\n\treturn kv.DB.Close()\n}\n\nfunc (kv *keyValue) ping() error {\n\t\/\/ TODO(bradfitz): something more efficient here?\n\t_, err := kv.SchemaVersion()\n\treturn err\n}\n\nfunc (kv *keyValue) SchemaVersion() (version int, err error) {\n\terr = kv.db.QueryRow(\"SELECT value FROM \" + kv.KeyValue.TablePrefix + \"meta WHERE metakey='version'\").Scan(&version)\n\treturn\n}\n\nconst fixSchema20to21 = `Character set in tables changed to binary, you can fix your tables with:\nALTER TABLE rows CONVERT TO CHARACTER SET binary;\nALTER TABLE meta CONVERT TO CHARACTER SET binary;\nUPDATE meta SET value=21 WHERE metakey='version' AND value=20;\n`\n\n\/\/ serverVersion returns the MySQL server version as []int{major, minor, revision}.\nfunc serverVersion(db *sql.DB) ([]int, error) {\n\tversionRx := regexp.MustCompile(`([0-9]+)\\.([0-9]+)\\.([0-9]+)-.*`)\n\tvar version string\n\tif err := db.QueryRow(\"SELECT VERSION()\").Scan(&version); err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting MySQL server version: %v\", err)\n\t}\n\tm := versionRx.FindStringSubmatch(version)\n\tif len(m) < 4 {\n\t\treturn nil, fmt.Errorf(\"bogus MySQL server version: %v\", version)\n\t}\n\tmajor, _ := strconv.Atoi(m[1])\n\tminor, _ := strconv.Atoi(m[2])\n\trev, _ := strconv.Atoi(m[3])\n\treturn []int{major, minor, rev}, nil\n}\n\n\/\/ hasLargeVarchar returns whether the given version (as []int{major, minor, revision})\n\/\/ supports VARCHAR larger than 255.\nfunc hasLargeVarchar(version []int) bool {\n\tif len(version) < 3 {\n\t\tpanic(fmt.Sprintf(\"bogus mysql server version %v: \", version))\n\t}\n\tif version[0] < 5 {\n\t\treturn false\n\t}\n\tif version[1] > 0 {\n\t\treturn true\n\t}\n\treturn version[0] == 5 && version[1] == 0 && version[2] >= 3\n}\n<|endoftext|>"}
{"text":"<commit_before>package common\n\nimport (\n\t\"sync\/atomic\"\n\n\t\"github.com\/mdlayher\/wavepipe\/data\"\n)\n\nvar (\n\t\/\/ rxBytes is the total number of bytes received over the network\n\trxBytes int64\n\t\/\/ txBytes is the total number of bytes received over the network\n\ttxBytes int64\n)\n\n\/\/ Metrics represents a variety of metrics about the current wavepipe instance, and contains several\n\/\/ nested structs which contain more specific metrics\ntype Metrics struct {\n\tDatabase *DatabaseMetrics `json:\"database\"`\n\tNetwork  *NetworkMetrics  `json:\"network\"`\n}\n\n\/\/ DatabaseMetrics represents metrics regarding the wavepipe database, including total numbers\n\/\/ of specific objects, and the time when the database was last updated\ntype DatabaseMetrics struct {\n\tUpdated int64 `json:\"updated\"`\n\n\tArtists int64 `json:\"artists\"`\n\tAlbums  int64 `json:\"albums\"`\n\tSongs   int64 `json:\"songs\"`\n\tFolders int64 `json:\"folders\"`\n\tArt     int64 `json:\"art\"`\n}\n\n\/\/ NetworkMetrics represents metrics regarding wavepipe network traffic, including total traffic\n\/\/ received and transmitted in bytes\ntype NetworkMetrics struct {\n\tRXBytes int64 `json:\"totalRxBytes\"`\n\tTXBytes int64 `json:\"totalTxBytes\"`\n}\n\n\/\/ GetDatabaseMetrics returns a variety of metrics about the wavepipe database, including\n\/\/ total numbers of specific objects, and the time when the database was last updated\nfunc GetDatabaseMetrics() (*DatabaseMetrics, error) {\n\t\/\/ Fetch total artists\n\tartists, err := data.DB.CountArtists()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Fetch total albums\n\talbums, err := data.DB.CountAlbums()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Fetch total songs\n\tsongs, err := data.DB.CountSongs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Fetch total folders\n\tfolders, err := data.DB.CountFolders()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Fetch total art\n\tart, err := data.DB.CountArt()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Combine all metrics\n\treturn &DatabaseMetrics{\n\t\tUpdated: ScanTime(),\n\t\tArtists: artists,\n\t\tAlbums:  albums,\n\t\tSongs:   songs,\n\t\tArt:     art,\n\t\tFolders: folders,\n\t}, nil\n}\n\n\/\/ AddRXBytes atomically increments the rxBytes counter by the amount specified\nfunc AddRXBytes(count int64) {\n\tatomic.AddInt64(&rxBytes, count)\n}\n\n\/\/ AddTXBytes atomically increments the txBytes counter by the amount specified\nfunc AddTXBytes(count int64) {\n\tatomic.AddInt64(&txBytes, count)\n}\n\n\/\/ RXBytes returns the total number of bytes received over the network\nfunc RXBytes() int64 {\n\treturn atomic.LoadInt64(&rxBytes)\n}\n\n\/\/ TXBytes returns the total number of bytes transmitted over the network\nfunc TXBytes() int64 {\n\treturn atomic.LoadInt64(&txBytes)\n}\n<commit_msg>common\/metrics: fix field names on NetworkMetrics<commit_after>package common\n\nimport (\n\t\"sync\/atomic\"\n\n\t\"github.com\/mdlayher\/wavepipe\/data\"\n)\n\nvar (\n\t\/\/ rxBytes is the total number of bytes received over the network\n\trxBytes int64\n\t\/\/ txBytes is the total number of bytes received over the network\n\ttxBytes int64\n)\n\n\/\/ Metrics represents a variety of metrics about the current wavepipe instance, and contains several\n\/\/ nested structs which contain more specific metrics\ntype Metrics struct {\n\tDatabase *DatabaseMetrics `json:\"database\"`\n\tNetwork  *NetworkMetrics  `json:\"network\"`\n}\n\n\/\/ DatabaseMetrics represents metrics regarding the wavepipe database, including total numbers\n\/\/ of specific objects, and the time when the database was last updated\ntype DatabaseMetrics struct {\n\tUpdated int64 `json:\"updated\"`\n\n\tArtists int64 `json:\"artists\"`\n\tAlbums  int64 `json:\"albums\"`\n\tSongs   int64 `json:\"songs\"`\n\tFolders int64 `json:\"folders\"`\n\tArt     int64 `json:\"art\"`\n}\n\n\/\/ NetworkMetrics represents metrics regarding wavepipe network traffic, including total traffic\n\/\/ received and transmitted in bytes\ntype NetworkMetrics struct {\n\tRXBytes int64 `json:\"rxBytes\"`\n\tTXBytes int64 `json:\"txBytes\"`\n}\n\n\/\/ GetDatabaseMetrics returns a variety of metrics about the wavepipe database, including\n\/\/ total numbers of specific objects, and the time when the database was last updated\nfunc GetDatabaseMetrics() (*DatabaseMetrics, error) {\n\t\/\/ Fetch total artists\n\tartists, err := data.DB.CountArtists()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Fetch total albums\n\talbums, err := data.DB.CountAlbums()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Fetch total songs\n\tsongs, err := data.DB.CountSongs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Fetch total folders\n\tfolders, err := data.DB.CountFolders()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Fetch total art\n\tart, err := data.DB.CountArt()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Combine all metrics\n\treturn &DatabaseMetrics{\n\t\tUpdated: ScanTime(),\n\t\tArtists: artists,\n\t\tAlbums:  albums,\n\t\tSongs:   songs,\n\t\tArt:     art,\n\t\tFolders: folders,\n\t}, nil\n}\n\n\/\/ AddRXBytes atomically increments the rxBytes counter by the amount specified\nfunc AddRXBytes(count int64) {\n\tatomic.AddInt64(&rxBytes, count)\n}\n\n\/\/ AddTXBytes atomically increments the txBytes counter by the amount specified\nfunc AddTXBytes(count int64) {\n\tatomic.AddInt64(&txBytes, count)\n}\n\n\/\/ RXBytes returns the total number of bytes received over the network\nfunc RXBytes() int64 {\n\treturn atomic.LoadInt64(&rxBytes)\n}\n\n\/\/ TXBytes returns the total number of bytes transmitted over the network\nfunc TXBytes() int64 {\n\treturn atomic.LoadInt64(&txBytes)\n}\n<|endoftext|>"}
{"text":"<commit_before>package list\n\nimport (\n\t\"errors\"\n)\n\n\/\/ Node is a node of the list\ntype Node struct {\n\tnext  *Node       \/\/ The node after this node in the list\n\tlist  *LinkedList \/\/ The list to which this element belongs\n\tValue interface{} \/\/ The value stored with this node\n}\n\n\/\/ Next returns the next node or nil\nfunc (n *Node) Next() *Node {\n\tif i := n.next; n.list != nil {\n\t\treturn i\n\t}\n\n\treturn nil\n}\n\n\/\/ LinkedList is a single linked list\ntype LinkedList struct {\n\tfirst *Node \/\/ The first node of the list\n\tlast  *Node \/\/ The last node of the list\n\tlen   int   \/\/ The current list length\n}\n\n\/\/ New returns an initialized list\nfunc New() *LinkedList {\n\treturn new(LinkedList).init()\n}\n\n\/\/ init initializes or clears the list\nfunc (l *LinkedList) init() *LinkedList {\n\tl.Clear()\n\n\treturn l\n}\n\n\/\/ Clear removes all nodes from the list\nfunc (l *LinkedList) Clear() {\n\ti := l.first\n\n\tfor i != nil {\n\t\tj := i.Next()\n\n\t\ti.list = nil\n\t\ti.next = nil\n\n\t\ti = j\n\t}\n\n\tl.first = nil\n\tl.last = nil\n\tl.len = 0\n}\n\n\/\/ Len returns the curren list length\nfunc (l *LinkedList) Len() int {\n\treturn l.len\n}\n\n\/\/ First returns the first node of the list or nil\nfunc (l *LinkedList) First() *Node {\n\treturn l.first\n}\n\n\/\/ Last returns the last node of the list or nil\nfunc (l *LinkedList) Last() *Node {\n\treturn l.last\n}\n\n\/\/ Get returns the node with the given index or nil\nfunc (l *LinkedList) Get(i int) (*Node, error) {\n\tif i < 0 || i >= l.len {\n\t\treturn nil, errors.New(\"index bounds out of range\")\n\t}\n\n\tj := 0\n\n\tfor n := l.First(); n != nil; n = n.Next() {\n\t\tif i == j {\n\t\t\treturn n, nil\n\t\t}\n\n\t\tj++\n\t}\n\n\tpanic(\"there is something wrong with the internal structure\")\n}\n\n\/\/ Set replaces the value in the list with the given value\nfunc (l *LinkedList) Set(i int, v interface{}) error {\n\tif i < 0 || i >= l.len {\n\t\treturn errors.New(\"index bounds out of range\")\n\t}\n\n\tj := 0\n\n\tfor n := l.First(); n != nil; n = n.Next() {\n\t\tif i == j {\n\t\t\tn.Value = v\n\n\t\t\treturn nil\n\t\t}\n\n\t\tj++\n\t}\n\n\tpanic(\"there is something wrong with the internal structure\")\n}\n\n\/\/ Copy returns an exact copy of the list\nfunc (l *LinkedList) Copy() *LinkedList {\n\tn := New()\n\n\tfor i := l.First(); i != nil; i = i.Next() {\n\t\tn.Push(i.Value)\n\t}\n\n\treturn n\n}\n\n\/\/ ToArray returns a copy of the list as slice\nfunc (l *LinkedList) ToArray() []interface{} {\n\ta := make([]interface{}, l.len)\n\n\tj := 0\n\n\tfor i := l.First(); i != nil; i = i.Next() {\n\t\ta[j] = i.Value\n\n\t\tj++\n\t}\n\n\treturn a\n}\n\n\/\/ newNode initializes a new node for the list\nfunc (l *LinkedList) newNode(v interface{}) *Node {\n\treturn &Node{\n\t\tlist:  l,\n\t\tValue: v,\n\t}\n}\n\n\/\/ findParent returns the parent to a given node or nil\nfunc (l *LinkedList) findParent(c *Node) *Node {\n\tif c == nil || c.list != l {\n\t\treturn nil\n\t}\n\n\tvar p *Node\n\n\tfor i := l.First(); i != nil; i = i.Next() {\n\t\tif i == c {\n\t\t\treturn p\n\t\t}\n\n\t\tp = i\n\t}\n\n\tpanic(\"there is something wrong with the internal structure\")\n}\n\n\/\/ InsertAfter creates a new node from a value, inserts it after a given node and returns the new one\nfunc (l *LinkedList) InsertAfter(v interface{}, p *Node) *Node {\n\tif (p == nil && l.len != 0) || (p != nil && p.list != l) {\n\t\treturn nil\n\t}\n\n\tn := l.newNode(v)\n\n\t\/\/ insert first node\n\tif p == nil {\n\t\tl.first = n\n\t\tl.last = n\n\t} else {\n\t\tn.next = p.next\n\t\tp.next = n\n\n\t\tif p == l.last {\n\t\t\tl.last = n\n\t\t}\n\t}\n\n\tl.len++\n\n\treturn n\n}\n\n\/\/ InsertBefore creates a new node from a value, inserts it before a given node and returns the new one\nfunc (l *LinkedList) InsertBefore(v interface{}, p *Node) *Node {\n\tif (p == nil && l.len != 0) || (p != nil && p.list != l) {\n\t\treturn nil\n\t}\n\n\tn := l.newNode(v)\n\n\t\/\/ insert first node\n\tif p == nil {\n\t\tl.first = n\n\t\tl.last = n\n\t} else {\n\t\tif p == l.first {\n\t\t\tl.first = n\n\t\t} else {\n\t\t\tpp := l.findParent(p)\n\n\t\t\tpp.next = n\n\t\t}\n\n\t\tn.next = p\n\t}\n\n\tl.len++\n\n\treturn n\n}\n\n\/\/ InsertAt creates a new mnode from a value, inserts it at the exact index which must be in range of the list and returns the new node\nfunc (l *LinkedList) InsertAt(i int, v interface{}) (*Node, error) {\n\tif i < 0 || i > l.len {\n\t\treturn nil, errors.New(\"index bounds out of range\")\n\t}\n\n\tn := l.newNode(v)\n\n\tif i == 0 {\n\t\tn.next = l.first\n\t\tl.first = n\n\t} else if i == l.len {\n\t\tl.last.next = n\n\t\tl.last = n\n\t} else {\n\t\tp, _ := l.Get(i - 1)\n\n\t\tn.next = p.next\n\t\tp.next = n\n\t}\n\n\tl.len++\n\n\treturn n, nil\n}\n\n\/\/ remove removes a given node from the list using the provided parent p\nfunc (l *LinkedList) remove(c *Node, p *Node) *Node {\n\tif c == nil || c.list != l || l.len == 0 {\n\t\treturn nil\n\t}\n\n\tif c == l.first {\n\t\tl.first = c.next\n\n\t\t\/\/ c is the last node\n\t\tif c == l.last {\n\t\t\tl.last = nil\n\t\t}\n\t} else {\n\t\tif p == nil {\n\t\t\tp = l.findParent(c)\n\t\t}\n\n\t\tp.next = c.next\n\n\t\tif c == l.last {\n\t\t\tl.last = p\n\t\t}\n\t}\n\n\tc.list = nil\n\tc.next = nil\n\n\tl.len--\n\n\treturn c\n}\n\n\/\/ Remove removes a given node from the list\nfunc (l *LinkedList) Remove(c *Node) *Node {\n\treturn l.remove(c, nil)\n}\n\n\/\/ RemoveAt removes a node from the list at the given index\nfunc (l *LinkedList) RemoveAt(i int) (*Node, error) {\n\tswitch {\n\tcase i < 0 || i >= l.len:\n\t\treturn nil, errors.New(\"index bounds out of range\")\n\tcase i == 0:\n\t\treturn l.remove(l.first, nil), nil\n\tdefault:\n\t\tp, _ := l.Get(i - 1)\n\n\t\treturn l.remove(p.next, p), nil\n\t}\n}\n\n\/\/ RemoveFirstOccurrence removes the first node with the given value from the list and returns it or nil\nfunc (l *LinkedList) RemoveFirstOccurrence(v interface{}) *Node {\n\tvar c, p *Node\n\n\tfor i := l.First(); i != nil; i = i.Next() {\n\t\tif i.Value == v {\n\t\t\tc = i\n\n\t\t\tbreak\n\t\t}\n\n\t\tp = i\n\t}\n\n\tif c != nil {\n\t\tl.remove(c, p)\n\t}\n\n\treturn c\n}\n\n\/\/ RemoveLastOccurrence removes the last node with the given value from the list and returns it or nil\nfunc (l *LinkedList) RemoveLastOccurrence(v interface{}) *Node {\n\tvar c, p, pp *Node\n\n\tfor i := l.First(); i != nil; i = i.Next() {\n\t\tif i.Value == v {\n\t\t\tc = i\n\t\t\tp = pp\n\t\t}\n\n\t\tpp = i\n\t}\n\n\tif c != nil {\n\t\tl.remove(c, p)\n\t}\n\n\treturn c\n}\n\n\/\/ Pop removes and returns the last node or nil\nfunc (l *LinkedList) Pop() *Node {\n\treturn l.Remove(l.last)\n}\n\n\/\/ Push creates a new node from a value, inserts it as the last node and returns it\nfunc (l *LinkedList) Push(v interface{}) *Node {\n\treturn l.InsertAfter(v, l.last)\n}\n\n\/\/ PushList adds the values of a list to the end of the list\nfunc (l *LinkedList) PushList(l2 *LinkedList) {\n\tfor i := l2.First(); i != nil; i = i.Next() {\n\t\tl.Push(i.Value)\n\t}\n}\n\n\/\/ Shift removes and returns the first node or nil\nfunc (l *LinkedList) Shift() *Node {\n\treturn l.Remove(l.first)\n}\n\n\/\/ Unshift creates a new node from a value, inserts it as the first node and returns it\nfunc (l *LinkedList) Unshift(v interface{}) *Node {\n\treturn l.InsertBefore(v, l.first)\n}\n\n\/\/ UnshiftList adds the values of a list to the front of the list\nfunc (l *LinkedList) UnshiftList(l2 *LinkedList) {\n\tfor i := l2.First(); i != nil; i = i.Next() {\n\t\tl.Unshift(i.Value)\n\t}\n}\n\n\/\/ Contains returns true if the value exists in the list\nfunc (l *LinkedList) Contains(v interface{}) bool {\n\t_, ok := l.IndexOf(v)\n\n\treturn ok\n}\n\n\/\/ IndexOf returns the first index of an occurence of the given value and true or -1 and false if the value does not exist\nfunc (l *LinkedList) IndexOf(v interface{}) (int, bool) {\n\ti := 0\n\n\tfor n := l.First(); n != nil; n = n.Next() {\n\t\tif n.Value == v {\n\t\t\treturn i, true\n\t\t}\n\n\t\ti++\n\t}\n\n\treturn -1, false\n}\n\n\/\/ LastIndexOf returns the last index of an occurence of the given value and true or -1 and false if the value does not exist\nfunc (l *LinkedList) LastIndexOf(v interface{}) (int, bool) {\n\ti := 0\n\tj := -1\n\n\tfor n := l.First(); n != nil; n = n.Next() {\n\t\tif n.Value == v {\n\t\t\tj = i\n\t\t}\n\n\t\ti++\n\t}\n\n\treturn j, j != -1\n}\n\nfunc (l *LinkedList) MoveAfter(n, p *Node) {\n\tif n.list != l || p.list != l || n == p {\n\t\treturn\n\t}\n\n\tl.InsertAfter(l.Remove(n).Value, p)\n}\n\nfunc (l *LinkedList) MoveBefore(n, p *Node) {\n\tif n.list != l || p.list != l || n == p {\n\t\treturn\n\t}\n\n\tl.InsertBefore(l.Remove(n).Value, p)\n}\n\nfunc (l *LinkedList) MoveToBack(n *Node) {\n\tl.MoveAfter(n, l.last)\n}\n\nfunc (l *LinkedList) MoveToFront(n *Node) {\n\tl.MoveBefore(n, l.first)\n}\n<commit_msg>InsertAt can use other functions<commit_after>package list\n\nimport (\n\t\"errors\"\n)\n\n\/\/ Node is a node of the list\ntype Node struct {\n\tnext  *Node       \/\/ The node after this node in the list\n\tlist  *LinkedList \/\/ The list to which this element belongs\n\tValue interface{} \/\/ The value stored with this node\n}\n\n\/\/ Next returns the next node or nil\nfunc (n *Node) Next() *Node {\n\tif i := n.next; n.list != nil {\n\t\treturn i\n\t}\n\n\treturn nil\n}\n\n\/\/ LinkedList is a single linked list\ntype LinkedList struct {\n\tfirst *Node \/\/ The first node of the list\n\tlast  *Node \/\/ The last node of the list\n\tlen   int   \/\/ The current list length\n}\n\n\/\/ New returns an initialized list\nfunc New() *LinkedList {\n\treturn new(LinkedList).init()\n}\n\n\/\/ init initializes or clears the list\nfunc (l *LinkedList) init() *LinkedList {\n\tl.Clear()\n\n\treturn l\n}\n\n\/\/ Clear removes all nodes from the list\nfunc (l *LinkedList) Clear() {\n\ti := l.first\n\n\tfor i != nil {\n\t\tj := i.Next()\n\n\t\ti.list = nil\n\t\ti.next = nil\n\n\t\ti = j\n\t}\n\n\tl.first = nil\n\tl.last = nil\n\tl.len = 0\n}\n\n\/\/ Len returns the curren list length\nfunc (l *LinkedList) Len() int {\n\treturn l.len\n}\n\n\/\/ First returns the first node of the list or nil\nfunc (l *LinkedList) First() *Node {\n\treturn l.first\n}\n\n\/\/ Last returns the last node of the list or nil\nfunc (l *LinkedList) Last() *Node {\n\treturn l.last\n}\n\n\/\/ Get returns the node with the given index or nil\nfunc (l *LinkedList) Get(i int) (*Node, error) {\n\tif i < 0 || i >= l.len {\n\t\treturn nil, errors.New(\"index bounds out of range\")\n\t}\n\n\tj := 0\n\n\tfor n := l.First(); n != nil; n = n.Next() {\n\t\tif i == j {\n\t\t\treturn n, nil\n\t\t}\n\n\t\tj++\n\t}\n\n\tpanic(\"there is something wrong with the internal structure\")\n}\n\n\/\/ Set replaces the value in the list with the given value\nfunc (l *LinkedList) Set(i int, v interface{}) error {\n\tif i < 0 || i >= l.len {\n\t\treturn errors.New(\"index bounds out of range\")\n\t}\n\n\tj := 0\n\n\tfor n := l.First(); n != nil; n = n.Next() {\n\t\tif i == j {\n\t\t\tn.Value = v\n\n\t\t\treturn nil\n\t\t}\n\n\t\tj++\n\t}\n\n\tpanic(\"there is something wrong with the internal structure\")\n}\n\n\/\/ Copy returns an exact copy of the list\nfunc (l *LinkedList) Copy() *LinkedList {\n\tn := New()\n\n\tfor i := l.First(); i != nil; i = i.Next() {\n\t\tn.Push(i.Value)\n\t}\n\n\treturn n\n}\n\n\/\/ ToArray returns a copy of the list as slice\nfunc (l *LinkedList) ToArray() []interface{} {\n\ta := make([]interface{}, l.len)\n\n\tj := 0\n\n\tfor i := l.First(); i != nil; i = i.Next() {\n\t\ta[j] = i.Value\n\n\t\tj++\n\t}\n\n\treturn a\n}\n\n\/\/ newNode initializes a new node for the list\nfunc (l *LinkedList) newNode(v interface{}) *Node {\n\treturn &Node{\n\t\tlist:  l,\n\t\tValue: v,\n\t}\n}\n\n\/\/ findParent returns the parent to a given node or nil\nfunc (l *LinkedList) findParent(c *Node) *Node {\n\tif c == nil || c.list != l {\n\t\treturn nil\n\t}\n\n\tvar p *Node\n\n\tfor i := l.First(); i != nil; i = i.Next() {\n\t\tif i == c {\n\t\t\treturn p\n\t\t}\n\n\t\tp = i\n\t}\n\n\tpanic(\"there is something wrong with the internal structure\")\n}\n\n\/\/ InsertAfter creates a new node from a value, inserts it after a given node and returns the new one\nfunc (l *LinkedList) InsertAfter(v interface{}, p *Node) *Node {\n\tif (p == nil && l.len != 0) || (p != nil && p.list != l) {\n\t\treturn nil\n\t}\n\n\tn := l.newNode(v)\n\n\t\/\/ insert first node\n\tif p == nil {\n\t\tl.first = n\n\t\tl.last = n\n\t} else {\n\t\tn.next = p.next\n\t\tp.next = n\n\n\t\tif p == l.last {\n\t\t\tl.last = n\n\t\t}\n\t}\n\n\tl.len++\n\n\treturn n\n}\n\n\/\/ InsertBefore creates a new node from a value, inserts it before a given node and returns the new one\nfunc (l *LinkedList) InsertBefore(v interface{}, p *Node) *Node {\n\tif (p == nil && l.len != 0) || (p != nil && p.list != l) {\n\t\treturn nil\n\t}\n\n\tn := l.newNode(v)\n\n\t\/\/ insert first node\n\tif p == nil {\n\t\tl.first = n\n\t\tl.last = n\n\t} else {\n\t\tif p == l.first {\n\t\t\tl.first = n\n\t\t} else {\n\t\t\tpp := l.findParent(p)\n\n\t\t\tpp.next = n\n\t\t}\n\n\t\tn.next = p\n\t}\n\n\tl.len++\n\n\treturn n\n}\n\n\/\/ InsertAt creates a new mnode from a value, inserts it at the exact index which must be in range of the list and returns the new node\nfunc (l *LinkedList) InsertAt(i int, v interface{}) (*Node, error) {\n\tif i < 0 || i > l.len {\n\t\treturn nil, errors.New(\"index bounds out of range\")\n\t}\n\n\tif i == 0 {\n\t\treturn l.Unshift(v), nil\n\t} else if i == l.len {\n\t\treturn l.Push(v), nil\n\t}\n\n\tp, _ := l.Get(i)\n\n\treturn l.InsertBefore(v, p), nil\n}\n\n\/\/ remove removes a given node from the list using the provided parent p\nfunc (l *LinkedList) remove(c *Node, p *Node) *Node {\n\tif c == nil || c.list != l || l.len == 0 {\n\t\treturn nil\n\t}\n\n\tif c == l.first {\n\t\tl.first = c.next\n\n\t\t\/\/ c is the last node\n\t\tif c == l.last {\n\t\t\tl.last = nil\n\t\t}\n\t} else {\n\t\tif p == nil {\n\t\t\tp = l.findParent(c)\n\t\t}\n\n\t\tp.next = c.next\n\n\t\tif c == l.last {\n\t\t\tl.last = p\n\t\t}\n\t}\n\n\tc.list = nil\n\tc.next = nil\n\n\tl.len--\n\n\treturn c\n}\n\n\/\/ Remove removes a given node from the list\nfunc (l *LinkedList) Remove(c *Node) *Node {\n\treturn l.remove(c, nil)\n}\n\n\/\/ RemoveAt removes a node from the list at the given index\nfunc (l *LinkedList) RemoveAt(i int) (*Node, error) {\n\tswitch {\n\tcase i < 0 || i >= l.len:\n\t\treturn nil, errors.New(\"index bounds out of range\")\n\tcase i == 0:\n\t\treturn l.remove(l.first, nil), nil\n\tdefault:\n\t\tp, _ := l.Get(i - 1)\n\n\t\treturn l.remove(p.next, p), nil\n\t}\n}\n\n\/\/ RemoveFirstOccurrence removes the first node with the given value from the list and returns it or nil\nfunc (l *LinkedList) RemoveFirstOccurrence(v interface{}) *Node {\n\tvar c, p *Node\n\n\tfor i := l.First(); i != nil; i = i.Next() {\n\t\tif i.Value == v {\n\t\t\tc = i\n\n\t\t\tbreak\n\t\t}\n\n\t\tp = i\n\t}\n\n\tif c != nil {\n\t\tl.remove(c, p)\n\t}\n\n\treturn c\n}\n\n\/\/ RemoveLastOccurrence removes the last node with the given value from the list and returns it or nil\nfunc (l *LinkedList) RemoveLastOccurrence(v interface{}) *Node {\n\tvar c, p, pp *Node\n\n\tfor i := l.First(); i != nil; i = i.Next() {\n\t\tif i.Value == v {\n\t\t\tc = i\n\t\t\tp = pp\n\t\t}\n\n\t\tpp = i\n\t}\n\n\tif c != nil {\n\t\tl.remove(c, p)\n\t}\n\n\treturn c\n}\n\n\/\/ Pop removes and returns the last node or nil\nfunc (l *LinkedList) Pop() *Node {\n\treturn l.Remove(l.last)\n}\n\n\/\/ Push creates a new node from a value, inserts it as the last node and returns it\nfunc (l *LinkedList) Push(v interface{}) *Node {\n\treturn l.InsertAfter(v, l.last)\n}\n\n\/\/ PushList adds the values of a list to the end of the list\nfunc (l *LinkedList) PushList(l2 *LinkedList) {\n\tfor i := l2.First(); i != nil; i = i.Next() {\n\t\tl.Push(i.Value)\n\t}\n}\n\n\/\/ Shift removes and returns the first node or nil\nfunc (l *LinkedList) Shift() *Node {\n\treturn l.Remove(l.first)\n}\n\n\/\/ Unshift creates a new node from a value, inserts it as the first node and returns it\nfunc (l *LinkedList) Unshift(v interface{}) *Node {\n\treturn l.InsertBefore(v, l.first)\n}\n\n\/\/ UnshiftList adds the values of a list to the front of the list\nfunc (l *LinkedList) UnshiftList(l2 *LinkedList) {\n\tfor i := l2.First(); i != nil; i = i.Next() {\n\t\tl.Unshift(i.Value)\n\t}\n}\n\n\/\/ Contains returns true if the value exists in the list\nfunc (l *LinkedList) Contains(v interface{}) bool {\n\t_, ok := l.IndexOf(v)\n\n\treturn ok\n}\n\n\/\/ IndexOf returns the first index of an occurence of the given value and true or -1 and false if the value does not exist\nfunc (l *LinkedList) IndexOf(v interface{}) (int, bool) {\n\ti := 0\n\n\tfor n := l.First(); n != nil; n = n.Next() {\n\t\tif n.Value == v {\n\t\t\treturn i, true\n\t\t}\n\n\t\ti++\n\t}\n\n\treturn -1, false\n}\n\n\/\/ LastIndexOf returns the last index of an occurence of the given value and true or -1 and false if the value does not exist\nfunc (l *LinkedList) LastIndexOf(v interface{}) (int, bool) {\n\ti := 0\n\tj := -1\n\n\tfor n := l.First(); n != nil; n = n.Next() {\n\t\tif n.Value == v {\n\t\t\tj = i\n\t\t}\n\n\t\ti++\n\t}\n\n\treturn j, j != -1\n}\n\nfunc (l *LinkedList) MoveAfter(n, p *Node) {\n\tif n.list != l || p.list != l || n == p {\n\t\treturn\n\t}\n\n\tl.InsertAfter(l.Remove(n).Value, p)\n}\n\nfunc (l *LinkedList) MoveBefore(n, p *Node) {\n\tif n.list != l || p.list != l || n == p {\n\t\treturn\n\t}\n\n\tl.InsertBefore(l.Remove(n).Value, p)\n}\n\nfunc (l *LinkedList) MoveToBack(n *Node) {\n\tl.MoveAfter(n, l.last)\n}\n\nfunc (l *LinkedList) MoveToFront(n *Node) {\n\tl.MoveBefore(n, l.first)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nconst kernelSource = `\nstatic inline ulong rotr64( __const ulong w, __const unsigned c ) { return ( w >> c ) | ( w << ( 64 - c ) ); }\n\n__constant static const uchar blake2b_sigma[12][16] = {\n\t{ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15 } ,\n\t{ 14, 10, 4,  8,  9,  15, 13, 6,  1,  12, 0,  2,  11, 7,  5,  3  } ,\n\t{ 11, 8,  12, 0,  5,  2,  15, 13, 10, 14, 3,  6,  7,  1,  9,  4  } ,\n\t{ 7,  9,  3,  1,  13, 12, 11, 14, 2,  6,  5,  10, 4,  0,  15, 8  } ,\n\t{ 9,  0,  5,  7,  2,  4,  10, 15, 14, 1,  11, 12, 6,  8,  3,  13 } ,\n\t{ 2,  12, 6,  10, 0,  11, 8,  3,  4,  13, 7,  5,  15, 14, 1,  9  } ,\n\t{ 12, 5,  1,  15, 14, 13, 4,  10, 0,  7,  6,  3,  9,  2,  8,  11 } ,\n\t{ 13, 11, 7,  14, 12, 1,  3,  9,  5,  0,  15, 4,  8,  6,  2,  10 } ,\n\t{ 6,  15, 14, 9,  11, 3,  0,  8,  12, 2,  13, 7,  1,  4,  10, 5  } ,\n\t{ 10, 2,  8,  4,  7,  6,  1,  5,  15, 11, 9,  14, 3,  12, 13, 0  } ,\n\t{ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15 } ,\n\t{ 14, 10, 4,  8,  9,  15, 13, 6,  1,  12, 0,  2,  11, 7,  5,  3  } };\n\n\/\/ Target is passed in via headerIn[32 - 29]\n__kernel void nonceGrind(__global ulong *headerIn, __global ulong *nonceOut) {\n\tulong target = headerIn[4];\n\tulong m[16] = {\theaderIn[0], headerIn[1],\n\t                headerIn[2], headerIn[3],\n\t                (ulong)get_global_id(0), headerIn[5],\n\t                headerIn[6], headerIn[7],\n\t                headerIn[8], headerIn[9], 0, 0, 0, 0, 0, 0 };\n\n\tulong v[16] = { 0x6a09e667f2bdc928, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,\n\t                0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,\n\t                0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,\n\t                0x510e527fade68281, 0x9b05688c2b3e6c1f, 0xe07c265404be4294, 0x5be0cd19137e2179 };\n\n\n\n#define G(r,i,a,b,c,d) \\\n\ta = a + b + m[blake2b_sigma[r][2*i]]; \\\n\td = rotr64(d ^ a, 32); \\\n\tc = c + d; \\\n\tb = rotr64(b ^ c, 24); \\\n\ta = a + b + m[blake2b_sigma[r][2*i+1]]; \\\n\td = rotr64(d ^ a, 16); \\\n\tc = c + d; \\\n\tb = rotr64(b ^ c, 63);\n\n#define ROUND(r)                    \\\n\tG(r,0,v[ 0],v[ 4],v[ 8],v[12]); \\\n\tG(r,1,v[ 1],v[ 5],v[ 9],v[13]); \\\n\tG(r,2,v[ 2],v[ 6],v[10],v[14]); \\\n\tG(r,3,v[ 3],v[ 7],v[11],v[15]); \\\n\tG(r,4,v[ 0],v[ 5],v[10],v[15]); \\\n\tG(r,5,v[ 1],v[ 6],v[11],v[12]); \\\n\tG(r,6,v[ 2],v[ 7],v[ 8],v[13]); \\\n\tG(r,7,v[ 3],v[ 4],v[ 9],v[14]);\n\n\tROUND( 0 );\n\tROUND( 1 );\n\tROUND( 2 );\n\tROUND( 3 );\n\tROUND( 4 );\n\tROUND( 5 );\n\tROUND( 6 );\n\tROUND( 7 );\n\tROUND( 8 );\n\tROUND( 9 );\n\tROUND( 10 );\n\tROUND( 11 );\n#undef G\n#undef ROUND\n\n\tif (as_ulong(as_uchar8(0x6a09e667f2bdc928 ^ v[0] ^ v[8]).s76543210) < target) {\n\t\t*nonceOut = m[4];\n\t\treturn;\n\t}\n}\n`\n<commit_msg>uint2 math<commit_after>package main\n\nconst kernelSource = `\n\ninline static uint2 ror64(const uint2 x, const uint y)\n{\n    return (uint2)(((x).x>>y)^((x).y<<(32-y)),((x).y>>y)^((x).x<<(32-y)));\n}\n\ninline static uint2 ror64_2(const uint2 x, const uint y)\n{\n    return (uint2)(((x).y>>(y-32))^((x).x<<(64-y)),((x).x>>(y-32))^((x).y<<(64-y)));\n}\n\n\n__constant static const uchar blake2b_sigma[12][16] = {\n\t{ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15 } ,\n\t{ 14, 10, 4,  8,  9,  15, 13, 6,  1,  12, 0,  2,  11, 7,  5,  3  } ,\n\t{ 11, 8,  12, 0,  5,  2,  15, 13, 10, 14, 3,  6,  7,  1,  9,  4  } ,\n\t{ 7,  9,  3,  1,  13, 12, 11, 14, 2,  6,  5,  10, 4,  0,  15, 8  } ,\n\t{ 9,  0,  5,  7,  2,  4,  10, 15, 14, 1,  11, 12, 6,  8,  3,  13 } ,\n\t{ 2,  12, 6,  10, 0,  11, 8,  3,  4,  13, 7,  5,  15, 14, 1,  9  } ,\n\t{ 12, 5,  1,  15, 14, 13, 4,  10, 0,  7,  6,  3,  9,  2,  8,  11 } ,\n\t{ 13, 11, 7,  14, 12, 1,  3,  9,  5,  0,  15, 4,  8,  6,  2,  10 } ,\n\t{ 6,  15, 14, 9,  11, 3,  0,  8,  12, 2,  13, 7,  1,  4,  10, 5  } ,\n\t{ 10, 2,  8,  4,  7,  6,  1,  5,  15, 11, 9,  14, 3,  12, 13, 0  } ,\n\t{ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15 } ,\n\t{ 14, 10, 4,  8,  9,  15, 13, 6,  1,  12, 0,  2,  11, 7,  5,  3  } };\n\n\/\/ Target is passed in via headerIn[32 - 29]\n__kernel void nonceGrind(__global ulong *headerIn, __global ulong *nonceOut) {\n\tulong target = headerIn[4];\n\tulong m[16] = {\theaderIn[0], headerIn[1],\n\t                headerIn[2], headerIn[3],\n\t                (ulong)get_global_id(0), headerIn[5],\n\t                headerIn[6], headerIn[7],\n\t                headerIn[8], headerIn[9], 0, 0, 0, 0, 0, 0 };\n\n\tulong v[16] = { 0x6a09e667f2bdc928, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,\n\t                0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,\n\t                0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,\n\t                0x510e527fade68281, 0x9b05688c2b3e6c1f, 0xe07c265404be4294, 0x5be0cd19137e2179 };\n\n\n\n#define G(r,i,a,b,c,d) \\\n\ta = a + b + m[ blake2b_sigma[r][2*i] ]; \\\n\t((uint2*)&d)[0] = ((uint2*)&d)[0].yx ^ ((uint2*)&a)[0].yx; \\\n\tc = c + d; \\\n\t((uint2*)&b)[0] = ror64( ((uint2*)&b)[0] ^ ((uint2*)&c)[0], 24U); \\\n\ta = a + b + m[ blake2b_sigma[r][2*i+1] ]; \\\n\t((uint2*)&d)[0] = ror64( ((uint2*)&d)[0] ^ ((uint2*)&a)[0], 16U); \\\n\tc = c + d; \\\n    ((uint2*)&b)[0] = ror64_2( ((uint2*)&b)[0] ^ ((uint2*)&c)[0], 63U);\n\n\n#define ROUND(r)                    \\\n\tG(r,0,v[ 0],v[ 4],v[ 8],v[12]); \\\n\tG(r,1,v[ 1],v[ 5],v[ 9],v[13]); \\\n\tG(r,2,v[ 2],v[ 6],v[10],v[14]); \\\n\tG(r,3,v[ 3],v[ 7],v[11],v[15]); \\\n\tG(r,4,v[ 0],v[ 5],v[10],v[15]); \\\n\tG(r,5,v[ 1],v[ 6],v[11],v[12]); \\\n\tG(r,6,v[ 2],v[ 7],v[ 8],v[13]); \\\n\tG(r,7,v[ 3],v[ 4],v[ 9],v[14]);\n\n\tROUND( 0 );\n\tROUND( 1 );\n\tROUND( 2 );\n\tROUND( 3 );\n\tROUND( 4 );\n\tROUND( 5 );\n\tROUND( 6 );\n\tROUND( 7 );\n\tROUND( 8 );\n\tROUND( 9 );\n\tROUND( 10 );\n\tROUND( 11 );\n#undef G\n#undef ROUND\n\n\tif (as_ulong(as_uchar8(0x6a09e667f2bdc928 ^ v[0] ^ v[8]).s76543210) < target) {\n\t\t*nonceOut = m[4];\n\t\treturn;\n\t}\n}\n`\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2020 Docker, Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage azure\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/Azure\/azure-sdk-for-go\/services\/containerinstance\/mgmt\/2018-10-01\/containerinstance\"\n\t\"github.com\/Azure\/go-autorest\/autorest\/to\"\n\t\"github.com\/compose-spec\/compose-go\/cli\"\n\t\"github.com\/compose-spec\/compose-go\/types\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\n\t\"github.com\/docker\/api\/azure\/convert\"\n\t\"github.com\/docker\/api\/azure\/login\"\n\t\"github.com\/docker\/api\/backend\"\n\t\"github.com\/docker\/api\/compose\"\n\t\"github.com\/docker\/api\/containers\"\n\tapicontext \"github.com\/docker\/api\/context\"\n\t\"github.com\/docker\/api\/context\/cloud\"\n\t\"github.com\/docker\/api\/context\/store\"\n\t\"github.com\/docker\/api\/errdefs\"\n)\n\nconst (\n\tsingleContainerName       = \"single--container--aci\"\n\tcomposeContainerSeparator = \"_\"\n)\n\n\/\/ ErrNoSuchContainer is returned when the mentioned container does not exist\nvar ErrNoSuchContainer = errors.New(\"no such container\")\n\nfunc init() {\n\tbackend.Register(\"aci\", \"aci\", service, getCloudService)\n}\n\nfunc service(ctx context.Context) (backend.Service, error) {\n\tcontextStore := store.ContextStore(ctx)\n\tcurrentContext := apicontext.CurrentContext(ctx)\n\tvar aciContext store.AciContext\n\n\tif err := contextStore.GetEndpoint(currentContext, &aciContext); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn getAciAPIService(aciContext), nil\n}\n\nfunc getCloudService() (cloud.Service, error) {\n\tservice, err := login.NewAzureLoginService()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &aciCloudService{\n\t\tloginService: service,\n\t}, nil\n}\n\nfunc getAciAPIService(aciCtx store.AciContext) *aciAPIService {\n\treturn &aciAPIService{\n\t\taciContainerService: &aciContainerService{\n\t\t\tctx: aciCtx,\n\t\t},\n\t\taciComposeService: &aciComposeService{\n\t\t\tctx: aciCtx,\n\t\t},\n\t}\n}\n\ntype aciAPIService struct {\n\t*aciContainerService\n\t*aciComposeService\n}\n\nfunc (a *aciAPIService) ContainerService() containers.Service {\n\treturn a.aciContainerService\n}\n\nfunc (a *aciAPIService) ComposeService() compose.Service {\n\treturn a.aciComposeService\n}\n\ntype aciContainerService struct {\n\tctx store.AciContext\n}\n\nfunc (cs *aciContainerService) List(ctx context.Context, _ bool) ([]containers.Container, error) {\n\tgroupsClient, err := getContainerGroupsClient(cs.ctx.SubscriptionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar containerGroups []containerinstance.ContainerGroup\n\tresult, err := groupsClient.ListByResourceGroup(ctx, cs.ctx.ResourceGroup)\n\tif err != nil {\n\t\treturn []containers.Container{}, err\n\t}\n\n\tfor result.NotDone() {\n\t\tcontainerGroups = append(containerGroups, result.Values()...)\n\t\tif err := result.NextWithContext(ctx); err != nil {\n\t\t\treturn []containers.Container{}, err\n\t\t}\n\t}\n\n\tvar res []containers.Container\n\tfor _, containerGroup := range containerGroups {\n\t\tgroup, err := groupsClient.Get(ctx, cs.ctx.ResourceGroup, *containerGroup.Name)\n\t\tif err != nil {\n\t\t\treturn []containers.Container{}, err\n\t\t}\n\n\t\tfor _, container := range *group.Containers {\n\t\t\tvar containerID string\n\t\t\t\/\/ don't list sidecar container\n\t\t\tif *container.Name == convert.ComposeDNSSidecarName {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif *container.Name == singleContainerName {\n\t\t\t\tcontainerID = *containerGroup.Name\n\t\t\t} else {\n\t\t\t\tcontainerID = *containerGroup.Name + composeContainerSeparator + *container.Name\n\t\t\t}\n\t\t\tstatus := \"Unknown\"\n\t\t\tif container.InstanceView != nil && container.InstanceView.CurrentState != nil {\n\t\t\t\tstatus = *container.InstanceView.CurrentState.State\n\t\t\t}\n\n\t\t\tres = append(res, containers.Container{\n\t\t\t\tID:     containerID,\n\t\t\t\tImage:  *container.Image,\n\t\t\t\tStatus: status,\n\t\t\t\tPorts:  convert.ToPorts(group.IPAddress, *container.Ports),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn res, nil\n}\n\nfunc (cs *aciContainerService) Run(ctx context.Context, r containers.ContainerConfig) error {\n\tif strings.Contains(r.ID, composeContainerSeparator) {\n\t\treturn errors.New(fmt.Sprintf(\"invalid container name. ACI container name cannot include %q\", composeContainerSeparator))\n\t}\n\n\tvar ports []types.ServicePortConfig\n\tfor _, p := range r.Ports {\n\t\tports = append(ports, types.ServicePortConfig{\n\t\t\tTarget:    p.ContainerPort,\n\t\t\tPublished: p.HostPort,\n\t\t})\n\t}\n\n\tprojectVolumes, serviceConfigVolumes, err := convert.GetRunVolumes(r.Volumes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tproject := types.Project{\n\t\tName: r.ID,\n\t\tServices: []types.ServiceConfig{\n\t\t\t{\n\t\t\t\tName:    singleContainerName,\n\t\t\t\tImage:   r.Image,\n\t\t\t\tPorts:   ports,\n\t\t\t\tLabels:  r.Labels,\n\t\t\t\tVolumes: serviceConfigVolumes,\n\t\t\t\tDeploy: &types.DeployConfig{\n\t\t\t\t\tResources: types.Resources{\n\t\t\t\t\t\tLimits: &types.Resource{\n\t\t\t\t\t\t\tNanoCPUs:    fmt.Sprintf(\"%f\", r.CPULimit),\n\t\t\t\t\t\t\tMemoryBytes: types.UnitBytes(r.MemLimit.Value()),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tVolumes: projectVolumes,\n\t}\n\n\tlogrus.Debugf(\"Running container %q with name %q\\n\", r.Image, r.ID)\n\tgroupDefinition, err := convert.ToContainerGroup(cs.ctx, project)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn createACIContainers(ctx, cs.ctx, groupDefinition)\n}\n\nfunc (cs *aciContainerService) Stop(ctx context.Context, containerName string, timeout *uint32) error {\n\treturn errdefs.ErrNotImplemented\n}\n\nfunc getGroupAndContainerName(containerID string) (groupName string, containerName string) {\n\ttokens := strings.Split(containerID, composeContainerSeparator)\n\tgroupName = tokens[0]\n\tif len(tokens) > 1 {\n\t\tcontainerName = tokens[len(tokens)-1]\n\t\tgroupName = containerID[:len(containerID)-(len(containerName)+1)]\n\t} else {\n\t\tcontainerName = singleContainerName\n\t}\n\treturn groupName, containerName\n}\n\nfunc (cs *aciContainerService) Exec(ctx context.Context, name string, command string, reader io.Reader, writer io.Writer) error {\n\tgroupName, containerAciName := getGroupAndContainerName(name)\n\tcontainerExecResponse, err := execACIContainer(ctx, cs.ctx, command, groupName, containerAciName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn exec(\n\t\tcontext.Background(),\n\t\t*containerExecResponse.WebSocketURI,\n\t\t*containerExecResponse.Password,\n\t\treader,\n\t\twriter,\n\t)\n}\n\nfunc (cs *aciContainerService) Logs(ctx context.Context, containerName string, req containers.LogsRequest) error {\n\tgroupName, containerAciName := getGroupAndContainerName(containerName)\n\tvar tail *int32\n\n\tif req.Follow {\n\t\treturn streamLogs(ctx, cs.ctx, groupName, containerAciName, req.Writer)\n\t}\n\n\tif req.Tail != \"all\" {\n\t\treqTail, err := strconv.Atoi(req.Tail)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ti32 := int32(reqTail)\n\t\ttail = &i32\n\t}\n\n\tlogs, err := getACIContainerLogs(ctx, cs.ctx, groupName, containerAciName, tail)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = fmt.Fprint(req.Writer, logs)\n\treturn err\n}\n\nfunc (cs *aciContainerService) Delete(ctx context.Context, containerID string, _ bool) error {\n\tgroupName, containerName := getGroupAndContainerName(containerID)\n\tif groupName != containerID {\n\t\treturn errors.New(fmt.Sprintf(`cannot delete service \"%s\" from compose app \"%s\", you must delete the entire compose app with docker compose down`, containerName, groupName))\n\t}\n\tcg, err := deleteACIContainerGroup(ctx, cs.ctx, groupName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif cg.StatusCode == http.StatusNoContent {\n\t\treturn ErrNoSuchContainer\n\t}\n\n\treturn err\n}\n\nfunc (cs *aciContainerService) Inspect(ctx context.Context, containerID string) (containers.Container, error) {\n\tgroupName, containerName := getGroupAndContainerName(containerID)\n\n\tcg, err := getACIContainerGroup(ctx, cs.ctx, groupName)\n\tif err != nil {\n\t\treturn containers.Container{}, err\n\t}\n\tif cg.StatusCode == http.StatusNoContent {\n\t\treturn containers.Container{}, ErrNoSuchContainer\n\t}\n\n\tvar cc containerinstance.Container\n\tvar found = false\n\tfor _, c := range *cg.Containers {\n\t\tif to.String(c.Name) == containerName {\n\t\t\tcc = c\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn containers.Container{}, ErrNoSuchContainer\n\t}\n\n\treturn convert.ContainerGroupToContainer(containerID, cg, cc)\n}\n\ntype aciComposeService struct {\n\tctx store.AciContext\n}\n\nfunc (cs *aciComposeService) Up(ctx context.Context, opts cli.ProjectOptions) error {\n\tproject, err := cli.ProjectFromOptions(&opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogrus.Debugf(\"Up on project with name %q\\n\", project.Name)\n\tgroupDefinition, err := convert.ToContainerGroup(cs.ctx, *project)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn createOrUpdateACIContainers(ctx, cs.ctx, groupDefinition)\n}\n\nfunc (cs *aciComposeService) Down(ctx context.Context, opts cli.ProjectOptions) error {\n\tvar project types.Project\n\n\tif opts.Name != \"\" {\n\t\tproject = types.Project{Name: opts.Name}\n\t} else {\n\t\tfullProject, err := cli.ProjectFromOptions(&opts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tproject = *fullProject\n\t}\n\tlogrus.Debugf(\"Down on project with name %q\\n\", project.Name)\n\n\tcg, err := deleteACIContainerGroup(ctx, cs.ctx, project.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif cg.StatusCode == http.StatusNoContent {\n\t\treturn ErrNoSuchContainer\n\t}\n\n\treturn err\n}\n\ntype aciCloudService struct {\n\tloginService login.AzureLoginService\n}\n\nfunc (cs *aciCloudService) Login(ctx context.Context, params map[string]string) error {\n\treturn cs.loginService.Login(ctx, params[login.TenantIDLoginParam])\n}\n\nfunc (cs *aciCloudService) CreateContextData(ctx context.Context, params map[string]string) (interface{}, string, error) {\n\tcontextHelper := newContextCreateHelper()\n\treturn contextHelper.createContextData(ctx, params)\n}\n<commit_msg>@gtardif @rumpl Use %q instead of \\\"%s\\\"<commit_after>\/*\n   Copyright 2020 Docker, Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage azure\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/Azure\/azure-sdk-for-go\/services\/containerinstance\/mgmt\/2018-10-01\/containerinstance\"\n\t\"github.com\/Azure\/go-autorest\/autorest\/to\"\n\t\"github.com\/compose-spec\/compose-go\/cli\"\n\t\"github.com\/compose-spec\/compose-go\/types\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\n\t\"github.com\/docker\/api\/azure\/convert\"\n\t\"github.com\/docker\/api\/azure\/login\"\n\t\"github.com\/docker\/api\/backend\"\n\t\"github.com\/docker\/api\/compose\"\n\t\"github.com\/docker\/api\/containers\"\n\tapicontext \"github.com\/docker\/api\/context\"\n\t\"github.com\/docker\/api\/context\/cloud\"\n\t\"github.com\/docker\/api\/context\/store\"\n\t\"github.com\/docker\/api\/errdefs\"\n)\n\nconst (\n\tsingleContainerName       = \"single--container--aci\"\n\tcomposeContainerSeparator = \"_\"\n)\n\n\/\/ ErrNoSuchContainer is returned when the mentioned container does not exist\nvar ErrNoSuchContainer = errors.New(\"no such container\")\n\nfunc init() {\n\tbackend.Register(\"aci\", \"aci\", service, getCloudService)\n}\n\nfunc service(ctx context.Context) (backend.Service, error) {\n\tcontextStore := store.ContextStore(ctx)\n\tcurrentContext := apicontext.CurrentContext(ctx)\n\tvar aciContext store.AciContext\n\n\tif err := contextStore.GetEndpoint(currentContext, &aciContext); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn getAciAPIService(aciContext), nil\n}\n\nfunc getCloudService() (cloud.Service, error) {\n\tservice, err := login.NewAzureLoginService()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &aciCloudService{\n\t\tloginService: service,\n\t}, nil\n}\n\nfunc getAciAPIService(aciCtx store.AciContext) *aciAPIService {\n\treturn &aciAPIService{\n\t\taciContainerService: &aciContainerService{\n\t\t\tctx: aciCtx,\n\t\t},\n\t\taciComposeService: &aciComposeService{\n\t\t\tctx: aciCtx,\n\t\t},\n\t}\n}\n\ntype aciAPIService struct {\n\t*aciContainerService\n\t*aciComposeService\n}\n\nfunc (a *aciAPIService) ContainerService() containers.Service {\n\treturn a.aciContainerService\n}\n\nfunc (a *aciAPIService) ComposeService() compose.Service {\n\treturn a.aciComposeService\n}\n\ntype aciContainerService struct {\n\tctx store.AciContext\n}\n\nfunc (cs *aciContainerService) List(ctx context.Context, _ bool) ([]containers.Container, error) {\n\tgroupsClient, err := getContainerGroupsClient(cs.ctx.SubscriptionID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar containerGroups []containerinstance.ContainerGroup\n\tresult, err := groupsClient.ListByResourceGroup(ctx, cs.ctx.ResourceGroup)\n\tif err != nil {\n\t\treturn []containers.Container{}, err\n\t}\n\n\tfor result.NotDone() {\n\t\tcontainerGroups = append(containerGroups, result.Values()...)\n\t\tif err := result.NextWithContext(ctx); err != nil {\n\t\t\treturn []containers.Container{}, err\n\t\t}\n\t}\n\n\tvar res []containers.Container\n\tfor _, containerGroup := range containerGroups {\n\t\tgroup, err := groupsClient.Get(ctx, cs.ctx.ResourceGroup, *containerGroup.Name)\n\t\tif err != nil {\n\t\t\treturn []containers.Container{}, err\n\t\t}\n\n\t\tfor _, container := range *group.Containers {\n\t\t\tvar containerID string\n\t\t\t\/\/ don't list sidecar container\n\t\t\tif *container.Name == convert.ComposeDNSSidecarName {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif *container.Name == singleContainerName {\n\t\t\t\tcontainerID = *containerGroup.Name\n\t\t\t} else {\n\t\t\t\tcontainerID = *containerGroup.Name + composeContainerSeparator + *container.Name\n\t\t\t}\n\t\t\tstatus := \"Unknown\"\n\t\t\tif container.InstanceView != nil && container.InstanceView.CurrentState != nil {\n\t\t\t\tstatus = *container.InstanceView.CurrentState.State\n\t\t\t}\n\n\t\t\tres = append(res, containers.Container{\n\t\t\t\tID:     containerID,\n\t\t\t\tImage:  *container.Image,\n\t\t\t\tStatus: status,\n\t\t\t\tPorts:  convert.ToPorts(group.IPAddress, *container.Ports),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn res, nil\n}\n\nfunc (cs *aciContainerService) Run(ctx context.Context, r containers.ContainerConfig) error {\n\tif strings.Contains(r.ID, composeContainerSeparator) {\n\t\treturn errors.New(fmt.Sprintf(\"invalid container name. ACI container name cannot include %q\", composeContainerSeparator))\n\t}\n\n\tvar ports []types.ServicePortConfig\n\tfor _, p := range r.Ports {\n\t\tports = append(ports, types.ServicePortConfig{\n\t\t\tTarget:    p.ContainerPort,\n\t\t\tPublished: p.HostPort,\n\t\t})\n\t}\n\n\tprojectVolumes, serviceConfigVolumes, err := convert.GetRunVolumes(r.Volumes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tproject := types.Project{\n\t\tName: r.ID,\n\t\tServices: []types.ServiceConfig{\n\t\t\t{\n\t\t\t\tName:    singleContainerName,\n\t\t\t\tImage:   r.Image,\n\t\t\t\tPorts:   ports,\n\t\t\t\tLabels:  r.Labels,\n\t\t\t\tVolumes: serviceConfigVolumes,\n\t\t\t\tDeploy: &types.DeployConfig{\n\t\t\t\t\tResources: types.Resources{\n\t\t\t\t\t\tLimits: &types.Resource{\n\t\t\t\t\t\t\tNanoCPUs:    fmt.Sprintf(\"%f\", r.CPULimit),\n\t\t\t\t\t\t\tMemoryBytes: types.UnitBytes(r.MemLimit.Value()),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tVolumes: projectVolumes,\n\t}\n\n\tlogrus.Debugf(\"Running container %q with name %q\\n\", r.Image, r.ID)\n\tgroupDefinition, err := convert.ToContainerGroup(cs.ctx, project)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn createACIContainers(ctx, cs.ctx, groupDefinition)\n}\n\nfunc (cs *aciContainerService) Stop(ctx context.Context, containerName string, timeout *uint32) error {\n\treturn errdefs.ErrNotImplemented\n}\n\nfunc getGroupAndContainerName(containerID string) (groupName string, containerName string) {\n\ttokens := strings.Split(containerID, composeContainerSeparator)\n\tgroupName = tokens[0]\n\tif len(tokens) > 1 {\n\t\tcontainerName = tokens[len(tokens)-1]\n\t\tgroupName = containerID[:len(containerID)-(len(containerName)+1)]\n\t} else {\n\t\tcontainerName = singleContainerName\n\t}\n\treturn groupName, containerName\n}\n\nfunc (cs *aciContainerService) Exec(ctx context.Context, name string, command string, reader io.Reader, writer io.Writer) error {\n\tgroupName, containerAciName := getGroupAndContainerName(name)\n\tcontainerExecResponse, err := execACIContainer(ctx, cs.ctx, command, groupName, containerAciName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn exec(\n\t\tcontext.Background(),\n\t\t*containerExecResponse.WebSocketURI,\n\t\t*containerExecResponse.Password,\n\t\treader,\n\t\twriter,\n\t)\n}\n\nfunc (cs *aciContainerService) Logs(ctx context.Context, containerName string, req containers.LogsRequest) error {\n\tgroupName, containerAciName := getGroupAndContainerName(containerName)\n\tvar tail *int32\n\n\tif req.Follow {\n\t\treturn streamLogs(ctx, cs.ctx, groupName, containerAciName, req.Writer)\n\t}\n\n\tif req.Tail != \"all\" {\n\t\treqTail, err := strconv.Atoi(req.Tail)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ti32 := int32(reqTail)\n\t\ttail = &i32\n\t}\n\n\tlogs, err := getACIContainerLogs(ctx, cs.ctx, groupName, containerAciName, tail)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = fmt.Fprint(req.Writer, logs)\n\treturn err\n}\n\nfunc (cs *aciContainerService) Delete(ctx context.Context, containerID string, _ bool) error {\n\tgroupName, containerName := getGroupAndContainerName(containerID)\n\tif groupName != containerID {\n\t\treturn errors.New(fmt.Sprintf(\"cannot delete service %q from compose app %q, you must delete the entire compose app with docker compose down\", containerName, groupName))\n\t}\n\tcg, err := deleteACIContainerGroup(ctx, cs.ctx, groupName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif cg.StatusCode == http.StatusNoContent {\n\t\treturn ErrNoSuchContainer\n\t}\n\n\treturn err\n}\n\nfunc (cs *aciContainerService) Inspect(ctx context.Context, containerID string) (containers.Container, error) {\n\tgroupName, containerName := getGroupAndContainerName(containerID)\n\n\tcg, err := getACIContainerGroup(ctx, cs.ctx, groupName)\n\tif err != nil {\n\t\treturn containers.Container{}, err\n\t}\n\tif cg.StatusCode == http.StatusNoContent {\n\t\treturn containers.Container{}, ErrNoSuchContainer\n\t}\n\n\tvar cc containerinstance.Container\n\tvar found = false\n\tfor _, c := range *cg.Containers {\n\t\tif to.String(c.Name) == containerName {\n\t\t\tcc = c\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn containers.Container{}, ErrNoSuchContainer\n\t}\n\n\treturn convert.ContainerGroupToContainer(containerID, cg, cc)\n}\n\ntype aciComposeService struct {\n\tctx store.AciContext\n}\n\nfunc (cs *aciComposeService) Up(ctx context.Context, opts cli.ProjectOptions) error {\n\tproject, err := cli.ProjectFromOptions(&opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogrus.Debugf(\"Up on project with name %q\\n\", project.Name)\n\tgroupDefinition, err := convert.ToContainerGroup(cs.ctx, *project)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn createOrUpdateACIContainers(ctx, cs.ctx, groupDefinition)\n}\n\nfunc (cs *aciComposeService) Down(ctx context.Context, opts cli.ProjectOptions) error {\n\tvar project types.Project\n\n\tif opts.Name != \"\" {\n\t\tproject = types.Project{Name: opts.Name}\n\t} else {\n\t\tfullProject, err := cli.ProjectFromOptions(&opts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tproject = *fullProject\n\t}\n\tlogrus.Debugf(\"Down on project with name %q\\n\", project.Name)\n\n\tcg, err := deleteACIContainerGroup(ctx, cs.ctx, project.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif cg.StatusCode == http.StatusNoContent {\n\t\treturn ErrNoSuchContainer\n\t}\n\n\treturn err\n}\n\ntype aciCloudService struct {\n\tloginService login.AzureLoginService\n}\n\nfunc (cs *aciCloudService) Login(ctx context.Context, params map[string]string) error {\n\treturn cs.loginService.Login(ctx, params[login.TenantIDLoginParam])\n}\n\nfunc (cs *aciCloudService) CreateContextData(ctx context.Context, params map[string]string) (interface{}, string, error) {\n\tcontextHelper := newContextCreateHelper()\n\treturn contextHelper.createContextData(ctx, params)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Message struct {\n\tText     string   `json:\"text\" firestore:\"text\"`\n\tAudience []string `json:\"audience\" firestore:\"audience\"`\n\tBingo    bool     `json:\"bingo\" firestore:\"bingo\"`\n}\n\nfunc (m *Message) SetText(t string, args ...interface{}) {\n\tm.Text = fmt.Sprintf(t, args...)\n}\n\nfunc (m *Message) SetAudience(a ...string) {\n\tm.Audience = a\n}\n\n\/\/ Game is the master structure for the game\ntype Game struct {\n\tID     string `json:\"id\"`\n\tName   string `json:\"name\"`\n\tMaster Master `json:\"master\" firestore:\"-\"`\n\tActive bool   `json:\"active\"`\n}\n\n\/\/ NewBoard creates a new board for a user.\nfunc (g *Game) NewBoard(p Player) Board {\n\tb := Board{}\n\tb.Game = g.ID\n\tb.Player = p\n\tb.Load(g.Master.Phrases())\n\treturn b\n\n}\n\n\/\/ JSON Returns the given Board struct as a JSON string\nfunc (g Game) JSON() (string, error) {\n\n\tbytes, err := json.Marshal(g)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not marshal json for response: %s\", err)\n\t}\n\n\treturn string(bytes), nil\n}\n\n\/\/ Master is the collection of all of the people who have selected which\n\/\/ element in the game\ntype Master struct {\n\tRecords []Record `json:\"record\"`\n}\n\n\/\/ Load adds the master list of phrases to the game.\nfunc (m *Master) Load(p []Phrase) {\n\tfor _, v := range p {\n\t\tr := Record{}\n\t\tr.Phrase = v\n\t\tm.Records = append(m.Records, r)\n\t}\n}\n\n\/\/ Phrases returns the List of phrases to populate boards.\nfunc (m Master) Phrases() []Phrase {\n\tresult := []Phrase{}\n\tfor _, v := range m.Records {\n\t\tresult = append(result, v.Phrase)\n\t}\n\treturn result\n}\n\n\/\/ Select marks a phrase as selected by one or more players\nfunc (m *Master) Select(ph Phrase, pl Player) Record {\n\tr := Record{}\n\tfor i, v := range m.Records {\n\n\t\tif v.Phrase.ID == ph.ID {\n\t\t\tif v.Players.IsMember(pl) {\n\t\t\t\tfmt.Printf(\"Was member, removing.  \\n\")\n\t\t\t\tnew := v.Players.Remove(pl)\n\t\t\t\tv.Players = new\n\n\t\t\t\tif len(new) == 0 {\n\t\t\t\t\tv.Phrase.Selected = false\n\t\t\t\t}\n\t\t\t\tm.Records[i] = v\n\t\t\t\treturn v\n\t\t\t}\n\t\t\tfmt.Printf(\"Was not member, adding.  \\n\")\n\t\t\tv.Phrase.Selected = true\n\t\t\tv.Players = append(v.Players, pl)\n\t\t\tm.Records[i] = v\n\t\t\treturn v\n\t\t}\n\t}\n\treturn r\n}\n\n\/\/ Record is a structure that keeps track of who has selected which Phrase\ntype Record struct {\n\tID      string  `json:\"id\"`\n\tPhrase  Phrase  `json:\"phrase\"`\n\tPlayers Players `json:\"players\"`\n}\n\n\/\/ Player is a human user who is playing the game.\ntype Player struct {\n\tName  string `json:\"name\"`\n\tEmail string `json:\"email\"`\n\tAdmin bool   `json:\"admin\"`\n}\n\n\/\/ Players is a slice of Player.\ntype Players []Player\n\n\/\/ IsMember checks to see if a player is in the collection already\nfunc (ps Players) IsMember(p Player) bool {\n\tfor _, v := range ps {\n\t\tif v.Email == p.Email {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Remove removes a particular player from the list.\nfunc (ps *Players) Remove(p Player) Players {\n\tout := Players{}\n\tfor _, v := range *ps {\n\t\tif v.Email != p.Email {\n\t\t\tout = append(out, v)\n\t\t}\n\t}\n\treturn out\n}\n\n\/\/ Add adds a particular player from the list.\nfunc (ps *Players) Add(p Player) {\n\tout := Players{}\n\tout = append(out, p)\n\tps = &out\n\treturn\n}\n\n\/\/ Board is an individual board that the players use to play bingo\ntype Board struct {\n\tID            string   `json:\"id\"`\n\tGame          string   `json:\"game\"`\n\tPlayer        Player   `json:\"player\"`\n\tBingoDeclared bool     `json:\"bingodeclared\"`\n\tPhrases       []Phrase `json:\"phrases\" firestore:\"-\"`\n}\n\n\/\/ Bingo determins if the correct sequence of items have been Selected to\n\/\/ make bingo on this board.\nfunc (b *Board) Bingo() bool {\n\tdiag1 := []string{\"B1\", \"I2\", \"N3\", \"G4\", \"O5\"}\n\tdiag2 := []string{\"B5\", \"I4\", \"N3\", \"G2\", \"O1\"}\n\tcounts := make(map[string]int)\n\n\tfor _, v := range b.Phrases {\n\t\tif v.Selected {\n\t\t\tcounts[v.Column]++\n\t\t\tcounts[v.Row]++\n\t\t}\n\n\t\tfor _, sub := range diag1 {\n\t\t\tif sub == v.Position() {\n\t\t\t\tcounts[\"diag1\"]++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tfor _, sub := range diag2 {\n\t\t\tif sub == v.Position() {\n\t\t\t\tcounts[\"diag2\"]++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, v := range counts {\n\t\tif v == 5 {\n\t\t\tfmt.Printf(\"Bingo Declared\\n\")\n\t\t\tb.BingoDeclared = true\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Select records if a phrase on the board has been selected.\nfunc (b *Board) Select(ph Phrase) Phrase {\n\tfor i, v := range b.Phrases {\n\t\tif v.ID == ph.ID {\n\t\t\tif v.Selected {\n\t\t\t\tv.Selected = false\n\t\t\t\tb.Phrases[i] = v\n\t\t\t\treturn v\n\t\t\t}\n\t\t\tv.Selected = true\n\t\t\tb.Phrases[i] = v\n\t\t\treturn v\n\t\t}\n\t}\n\treturn ph\n}\n\n\/\/ Load adds the phrases to the board and randomly orders them.\nfunc (b *Board) Load(p []Phrase) {\n\trand.Seed(randseedfunc())\n\trand.Shuffle(len(p), func(i, j int) { p[i], p[j] = p[j], p[i] })\n\n\tfor i, v := range p {\n\t\tv.Selected = false\n\t\tv.Column, v.Row = b.CalcColumnsRows(i + 1)\n\t\tv.DisplayOrder = i\n\t\tp[i] = v\n\t}\n\tb.Phrases = p\n}\n\nfunc (b *Board) CalcColumnsRows(i int) (string, string) {\n\tcolumn := \"\"\n\trow := \"\"\n\n\tswitch i % 5 {\n\tcase 1:\n\t\tcolumn = \"B\"\n\tcase 2:\n\t\tcolumn = \"I\"\n\tcase 3:\n\t\tcolumn = \"N\"\n\tcase 4:\n\t\tcolumn = \"G\"\n\tdefault:\n\t\tcolumn = \"O\"\n\t}\n\n\trow = strconv.Itoa(int(math.Round(float64((i - 1) \/ 5))))\n\n\treturn column, row\n}\n\n\/\/ JSON Returns the given Board struct as a JSON string\nfunc (b Board) JSON() (string, error) {\n\n\tbytes, err := json.Marshal(b)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not marshal json for response: %s\", err)\n\t}\n\n\treturn string(bytes), nil\n}\n\nfunc randomseed() int64 {\n\treturn time.Now().UnixNano()\n}\n\n\/\/ Phrase represents a statement, event or other such thing that we are on the\n\/\/ lookout for in this game of bingo.\ntype Phrase struct {\n\tID           string `json:\"id\"`\n\tText         string `json:\"text\"`\n\tSelected     bool   `json:\"selected\"`\n\tRow          string `json:\"row\"`\n\tColumn       string `json:\"column\"`\n\tDisplayOrder int    `json:\"display_order\"`\n}\n\n\/\/ Position returns the combined Row and Column of the Phrase\nfunc (p Phrase) Position() string {\n\treturn p.Column + p.Row\n}\n<commit_msg>Everyboard gets free by default now.<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Message struct {\n\tText     string   `json:\"text\" firestore:\"text\"`\n\tAudience []string `json:\"audience\" firestore:\"audience\"`\n\tBingo    bool     `json:\"bingo\" firestore:\"bingo\"`\n}\n\nfunc (m *Message) SetText(t string, args ...interface{}) {\n\tm.Text = fmt.Sprintf(t, args...)\n}\n\nfunc (m *Message) SetAudience(a ...string) {\n\tm.Audience = a\n}\n\n\/\/ Game is the master structure for the game\ntype Game struct {\n\tID     string `json:\"id\"`\n\tName   string `json:\"name\"`\n\tMaster Master `json:\"master\" firestore:\"-\"`\n\tActive bool   `json:\"active\"`\n}\n\n\/\/ NewBoard creates a new board for a user.\nfunc (g *Game) NewBoard(p Player) Board {\n\tb := Board{}\n\tb.Game = g.ID\n\tb.Player = p\n\tb.Load(g.Master.Phrases())\n\treturn b\n\n}\n\n\/\/ JSON Returns the given Board struct as a JSON string\nfunc (g Game) JSON() (string, error) {\n\n\tbytes, err := json.Marshal(g)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not marshal json for response: %s\", err)\n\t}\n\n\treturn string(bytes), nil\n}\n\n\/\/ Master is the collection of all of the people who have selected which\n\/\/ element in the game\ntype Master struct {\n\tRecords []Record `json:\"record\"`\n}\n\n\/\/ Load adds the master list of phrases to the game.\nfunc (m *Master) Load(p []Phrase) {\n\tfor _, v := range p {\n\t\tr := Record{}\n\t\tr.Phrase = v\n\t\tm.Records = append(m.Records, r)\n\t}\n}\n\n\/\/ Phrases returns the List of phrases to populate boards.\nfunc (m Master) Phrases() []Phrase {\n\tresult := []Phrase{}\n\tfor _, v := range m.Records {\n\t\tresult = append(result, v.Phrase)\n\t}\n\treturn result\n}\n\n\/\/ Select marks a phrase as selected by one or more players\nfunc (m *Master) Select(ph Phrase, pl Player) Record {\n\tr := Record{}\n\tfor i, v := range m.Records {\n\n\t\tif v.Phrase.ID == ph.ID {\n\t\t\tif v.Players.IsMember(pl) {\n\t\t\t\tfmt.Printf(\"Was member, removing.  \\n\")\n\t\t\t\tnew := v.Players.Remove(pl)\n\t\t\t\tv.Players = new\n\n\t\t\t\tif len(new) == 0 {\n\t\t\t\t\tv.Phrase.Selected = false\n\t\t\t\t}\n\t\t\t\tm.Records[i] = v\n\t\t\t\treturn v\n\t\t\t}\n\t\t\tfmt.Printf(\"Was not member, adding.  \\n\")\n\t\t\tv.Phrase.Selected = true\n\t\t\tv.Players = append(v.Players, pl)\n\t\t\tm.Records[i] = v\n\t\t\treturn v\n\t\t}\n\t}\n\treturn r\n}\n\n\/\/ Record is a structure that keeps track of who has selected which Phrase\ntype Record struct {\n\tID      string  `json:\"id\"`\n\tPhrase  Phrase  `json:\"phrase\"`\n\tPlayers Players `json:\"players\"`\n}\n\n\/\/ Player is a human user who is playing the game.\ntype Player struct {\n\tName  string `json:\"name\"`\n\tEmail string `json:\"email\"`\n\tAdmin bool   `json:\"admin\"`\n}\n\n\/\/ Players is a slice of Player.\ntype Players []Player\n\n\/\/ IsMember checks to see if a player is in the collection already\nfunc (ps Players) IsMember(p Player) bool {\n\tfor _, v := range ps {\n\t\tif v.Email == p.Email {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Remove removes a particular player from the list.\nfunc (ps *Players) Remove(p Player) Players {\n\tout := Players{}\n\tfor _, v := range *ps {\n\t\tif v.Email != p.Email {\n\t\t\tout = append(out, v)\n\t\t}\n\t}\n\treturn out\n}\n\n\/\/ Add adds a particular player from the list.\nfunc (ps *Players) Add(p Player) {\n\tout := Players{}\n\tout = append(out, p)\n\tps = &out\n\treturn\n}\n\n\/\/ Board is an individual board that the players use to play bingo\ntype Board struct {\n\tID            string   `json:\"id\"`\n\tGame          string   `json:\"game\"`\n\tPlayer        Player   `json:\"player\"`\n\tBingoDeclared bool     `json:\"bingodeclared\"`\n\tPhrases       []Phrase `json:\"phrases\" firestore:\"-\"`\n}\n\n\/\/ Bingo determins if the correct sequence of items have been Selected to\n\/\/ make bingo on this board.\nfunc (b *Board) Bingo() bool {\n\tdiag1 := []string{\"B1\", \"I2\", \"N3\", \"G4\", \"O5\"}\n\tdiag2 := []string{\"B5\", \"I4\", \"N3\", \"G2\", \"O1\"}\n\tcounts := make(map[string]int)\n\n\tfor _, v := range b.Phrases {\n\t\tif v.Selected {\n\t\t\tcounts[v.Column]++\n\t\t\tcounts[v.Row]++\n\t\t}\n\n\t\tfor _, sub := range diag1 {\n\t\t\tif sub == v.Position() {\n\t\t\t\tcounts[\"diag1\"]++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tfor _, sub := range diag2 {\n\t\t\tif sub == v.Position() {\n\t\t\t\tcounts[\"diag2\"]++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, v := range counts {\n\t\tif v == 5 {\n\t\t\tfmt.Printf(\"Bingo Declared\\n\")\n\t\t\tb.BingoDeclared = true\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Select records if a phrase on the board has been selected.\nfunc (b *Board) Select(ph Phrase) Phrase {\n\tfor i, v := range b.Phrases {\n\t\tif v.ID == ph.ID {\n\t\t\tif v.Selected {\n\t\t\t\tv.Selected = false\n\t\t\t\tb.Phrases[i] = v\n\t\t\t\treturn v\n\t\t\t}\n\t\t\tv.Selected = true\n\t\t\tb.Phrases[i] = v\n\t\t\treturn v\n\t\t}\n\t}\n\treturn ph\n}\n\n\/\/ Load adds the phrases to the board and randomly orders them.\nfunc (b *Board) Load(p []Phrase) {\n\trand.Seed(randseedfunc())\n\trand.Shuffle(len(p), func(i, j int) { p[i], p[j] = p[j], p[i] })\n\n\tfree := 0\n\tcenter := 12\n\n\tfor i, v := range p {\n\n\t\tv.Selected = false\n\t\tv.Column, v.Row = b.CalcColumnsRows(i + 1)\n\t\tv.DisplayOrder = i\n\n\t\tif v.Text == \"FREE\" {\n\t\t\tfree = i\n\t\t\tv.Selected = true\n\t\t}\n\t\tp[i] = v\n\n\t}\n\n\tp[free], p[center] = p[center], p[free]\n\n\tb.Phrases = p\n}\n\nfunc (b *Board) CalcColumnsRows(i int) (string, string) {\n\tcolumn := \"\"\n\trow := \"\"\n\n\tswitch i % 5 {\n\tcase 1:\n\t\tcolumn = \"B\"\n\tcase 2:\n\t\tcolumn = \"I\"\n\tcase 3:\n\t\tcolumn = \"N\"\n\tcase 4:\n\t\tcolumn = \"G\"\n\tdefault:\n\t\tcolumn = \"O\"\n\t}\n\n\trow = strconv.Itoa(int(math.Round(float64((i - 1) \/ 5))))\n\n\treturn column, row\n}\n\n\/\/ JSON Returns the given Board struct as a JSON string\nfunc (b Board) JSON() (string, error) {\n\n\tbytes, err := json.Marshal(b)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not marshal json for response: %s\", err)\n\t}\n\n\treturn string(bytes), nil\n}\n\nfunc randomseed() int64 {\n\treturn time.Now().UnixNano()\n}\n\n\/\/ Phrase represents a statement, event or other such thing that we are on the\n\/\/ lookout for in this game of bingo.\ntype Phrase struct {\n\tID           string `json:\"id\"`\n\tText         string `json:\"text\"`\n\tSelected     bool   `json:\"selected\"`\n\tRow          string `json:\"row\"`\n\tColumn       string `json:\"column\"`\n\tDisplayOrder int    `json:\"display_order\"`\n}\n\n\/\/ Position returns the combined Row and Column of the Phrase\nfunc (p Phrase) Position() string {\n\treturn p.Column + p.Row\n}\n<|endoftext|>"}
{"text":"<commit_before>package check_volume\n\nimport (\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/appscode\/go\/flags\"\n\t\"github.com\/appscode\/searchlight\/pkg\/client\/k8s\"\n\t\"github.com\/appscode\/searchlight\/util\"\n\t\"github.com\/spf13\/cobra\"\n\tkapi \"k8s.io\/kubernetes\/pkg\/api\"\n)\n\nconst (\n\tawsElasticBlockStorePluginName = \"kubernetes.io~aws-ebs\"\n\tazureDataDiskPluginName        = \"kubernetes.io~azure-disk\"\n\tazureFilePluginName            = \"kubernetes.io~azure-file\"\n\tcephfsPluginName               = \"kubernetes.io~cephfs\"\n\tcinderVolumePluginName         = \"kubernetes.io~cinder\"\n\tconfigMapPluginName            = \"kubernetes.io~configmap\"\n\tdownwardAPIPluginName          = \"kubernetes.io~downward-api\"\n\temptyDirPluginName             = \"kubernetes.io~empty-dir\"\n\tfcPluginName                   = \"kubernetes.io~fc\"\n\tflockerPluginName              = \"kubernetes.io~flocker\"\n\tgcePersistentDiskPluginName    = \"kubernetes.io~gce-pd\"\n\tgitRepoPluginName              = \"kubernetes.io~git-repo\"\n\tglusterfsPluginName            = \"kubernetes.io~glusterfs\"\n\thostPathPluginName             = \"kubernetes.io~host-path\"\n\tiscsiPluginName                = \"kubernetes.io~iscsi\"\n\tnfsPluginName                  = \"kubernetes.io~nfs\"\n\tquobytePluginName              = \"kubernetes.io~quobyte\"\n\trbdPluginName                  = \"kubernetes.io~rbd\"\n\tsecretPluginName               = \"kubernetes.io~secret\"\n\tvsphereVolumePluginName        = \"kubernetes.io~vsphere-volume\"\n)\n\nfunc getVolumePluginName(volumeSource *kapi.VolumeSource) string {\n\tif volumeSource.AWSElasticBlockStore != nil {\n\t\treturn awsElasticBlockStorePluginName\n\t} else if volumeSource.AzureDisk != nil {\n\t\treturn azureDataDiskPluginName\n\t} else if volumeSource.AzureFile != nil {\n\t\treturn azureFilePluginName\n\t} else if volumeSource.CephFS != nil {\n\t\treturn cephfsPluginName\n\t} else if volumeSource.Cinder != nil {\n\t\treturn cinderVolumePluginName\n\t} else if volumeSource.ConfigMap != nil {\n\t\treturn configMapPluginName\n\t} else if volumeSource.DownwardAPI != nil {\n\t\treturn downwardAPIPluginName\n\t} else if volumeSource.EmptyDir != nil {\n\t\treturn emptyDirPluginName\n\t} else if volumeSource.FC != nil {\n\t\treturn fcPluginName\n\t} else if volumeSource.Flocker != nil {\n\t\treturn flockerPluginName\n\t} else if volumeSource.GCEPersistentDisk != nil {\n\t\treturn gcePersistentDiskPluginName\n\t} else if volumeSource.GitRepo != nil {\n\t\treturn gitRepoPluginName\n\t} else if volumeSource.Glusterfs != nil {\n\t\treturn glusterfsPluginName\n\t} else if volumeSource.HostPath != nil {\n\t\treturn hostPathPluginName\n\t} else if volumeSource.ISCSI != nil {\n\t\treturn iscsiPluginName\n\t} else if volumeSource.NFS != nil {\n\t\treturn nfsPluginName\n\t} else if volumeSource.Quobyte != nil {\n\t\treturn quobytePluginName\n\t} else if volumeSource.RBD != nil {\n\t\treturn rbdPluginName\n\t} else if volumeSource.Secret != nil {\n\t\treturn secretPluginName\n\t} else if volumeSource.VsphereVolume != nil {\n\t\treturn vsphereVolumePluginName\n\t}\n\treturn \"\"\n}\n\nfunc getPersistentVolumePluginName(volumeSource *kapi.PersistentVolumeSource) string {\n\tif volumeSource.AWSElasticBlockStore != nil {\n\t\treturn awsElasticBlockStorePluginName\n\t} else if volumeSource.AzureDisk != nil {\n\t\treturn azureDataDiskPluginName\n\t} else if volumeSource.AzureFile != nil {\n\t\treturn azureFilePluginName\n\t} else if volumeSource.CephFS != nil {\n\t\treturn cephfsPluginName\n\t} else if volumeSource.Cinder != nil {\n\t\treturn cinderVolumePluginName\n\t} else if volumeSource.FC != nil {\n\t\treturn fcPluginName\n\t} else if volumeSource.Flocker != nil {\n\t\treturn flockerPluginName\n\t} else if volumeSource.GCEPersistentDisk != nil {\n\t\treturn gcePersistentDiskPluginName\n\t} else if volumeSource.Glusterfs != nil {\n\t\treturn glusterfsPluginName\n\t} else if volumeSource.HostPath != nil {\n\t\treturn hostPathPluginName\n\t} else if volumeSource.ISCSI != nil {\n\t\treturn iscsiPluginName\n\t} else if volumeSource.NFS != nil {\n\t\treturn nfsPluginName\n\t} else if volumeSource.Quobyte != nil {\n\t\treturn quobytePluginName\n\t} else if volumeSource.RBD != nil {\n\t\treturn rbdPluginName\n\t} else if volumeSource.VsphereVolume != nil {\n\t\treturn vsphereVolumePluginName\n\t}\n\treturn \"\"\n}\n\nconst (\n\thostFactPort = 56977\n)\n\ntype request struct {\n\thost      string\n\tname      string\n\twarning   float64\n\tcritical  float64\n\tnode_stat bool\n\tsecret    string\n}\n\ntype usageStat struct {\n\tPath              string  `json:\"path\"`\n\tFstype            string  `json:\"fstype\"`\n\tTotal             uint64  `json:\"total\"`\n\tFree              uint64  `json:\"free\"`\n\tUsed              uint64  `json:\"used\"`\n\tUsedPercent       float64 `json:\"usedPercent\"`\n\tInodesTotal       uint64  `json:\"inodesTotal\"`\n\tInodesUsed        uint64  `json:\"inodesUsed\"`\n\tInodesFree        uint64  `json:\"inodesFree\"`\n\tInodesUsedPercent float64 `json:\"inodesUsedPercent\"`\n}\n\ntype authInfo struct {\n\tca        string\n\tkey       string\n\tcrt       string\n\tauthToken string\n\tusername  string\n\tpassword  string\n}\n\nconst (\n\tca        = \"ca.crt\"\n\tkey       = \"hostfacts.key\"\n\tcrt       = \"hostfacts.crt\"\n\tauthToken = \"auth_token\"\n\tusername  = \"username\"\n\tpassword  = \"password\"\n)\n\nfunc getHostfactsSecretData(kubeClient *k8s.KubeClient, secretName string) *authInfo {\n\tif secretName == \"\" {\n\t\treturn nil\n\t}\n\n\tparts := strings.Split(secretName, \".\")\n\tname := parts[0]\n\tnamespace := \"default\"\n\tif len(parts) > 1 {\n\t\tnamespace = parts[1]\n\t}\n\n\tsecret, err := kubeClient.Client.Core().Secrets(namespace).Get(name)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tauthData := &authInfo{\n\t\tca:        string(secret.Data[ca]),\n\t\tkey:       string(secret.Data[key]),\n\t\tcrt:       string(secret.Data[crt]),\n\t\tauthToken: string(secret.Data[authToken]),\n\t\tusername:  string(secret.Data[username]),\n\t\tpassword:  string(secret.Data[password]),\n\t}\n\n\treturn authData\n}\n\nfunc getUsage(authInfo *authInfo, hostIP, path string) (*usageStat, error) {\n\tprotocol := \"http\"\n\tif authInfo != nil {\n\t\tprotocol = \"https\"\n\t}\n\n\turlStr := fmt.Sprintf(\"%v:\/\/%v:%v\/du?p=%v\", protocol, hostIP, hostFactPort, path)\n\treq, err := http.NewRequest(http.MethodGet, urlStr, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmTLSConfig := &tls.Config{}\n\n\tif authInfo != nil {\n\t\tif authInfo.username != \"\" && authInfo.password != \"\" {\n\t\t\treq.SetBasicAuth(authInfo.username, authInfo.password)\n\t\t} else if authInfo.authToken != \"\" {\n\t\t\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", authInfo.authToken))\n\t\t}\n\n\t\tif authInfo.ca != \"\" {\n\t\t\tcerts := x509.NewCertPool()\n\t\t\tcerts.AppendCertsFromPEM([]byte(authInfo.ca))\n\t\t\tmTLSConfig.RootCAs = certs\n\t\t\tif authInfo.crt != \"\" && authInfo.key != \"\" {\n\t\t\t\tcert, err := tls.X509KeyPair([]byte(authInfo.crt), []byte(authInfo.key))\n\t\t\t\tif err == nil {\n\t\t\t\t\tmTLSConfig.Certificates = []tls.Certificate{cert}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tmTLSConfig.InsecureSkipVerify = true\n\t\t}\n\t}\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: mTLSConfig,\n\t}\n\tclient := &http.Client{Transport: tr}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trespData, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tusages := make([]*usageStat, 1)\n\tif err = json.Unmarshal(respData, &usages); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn usages[0], nil\n}\n\nfunc checkResult(field string, warning, critical, result float64) (util.IcingaState, interface{}) {\n\tif result >= critical {\n\t\treturn util.Critical, fmt.Sprintf(\"%v used more than %v%%\", field, critical)\n\t}\n\tif result >= warning {\n\t\treturn util.Warning, fmt.Sprintf(\"%v used more than %v%%\", field, warning)\n\t}\n\treturn util.Ok, \"(Disk & Inodes)\"\n}\n\nfunc checkDiskStat(kubeClient *k8s.KubeClient, req *request, nodeIP, path string) (util.IcingaState, interface{}) {\n\tauthInfo := getHostfactsSecretData(kubeClient, req.secret)\n\n\tusage, err := getUsage(authInfo, nodeIP, path)\n\tif err != nil {\n\t\treturn util.Unknown, err\n\t}\n\n\twarning := req.warning\n\tcritical := req.critical\n\tstate, message := checkResult(\"Disk\", warning, critical, usage.UsedPercent)\n\tif state != util.Ok {\n\t\treturn state, message\n\t}\n\tstate, message = checkResult(\"Inodes\", warning, critical, usage.InodesUsedPercent)\n\treturn state, message\n}\n\nfunc checkNodeDiskStat(req *request) (util.IcingaState, interface{}) {\n\thost := req.host\n\tparts := strings.Split(host, \"@\")\n\tif len(parts) != 2 {\n\t\treturn util.Unknown, \"Invalid icinga host.name\"\n\t}\n\n\tkubeClient, err := k8s.NewClient()\n\tif err != nil {\n\t\treturn util.Unknown, err\n\t}\n\n\tnode_name := parts[0]\n\tnode, err := kubeClient.Client.Core().Nodes().Get(node_name)\n\tif err != nil {\n\t\treturn util.Unknown, err\n\t}\n\n\tif node == nil {\n\t\treturn util.Unknown, \"Node not found\"\n\t}\n\n\thostIP := \"\"\n\tfor _, address := range node.Status.Addresses {\n\t\tif address.Type == kapi.NodeInternalIP {\n\t\t\thostIP = address.Address\n\t\t}\n\t}\n\n\tif hostIP == \"\" {\n\t\treturn util.Unknown, \"Node InternalIP not found\"\n\t}\n\treturn checkDiskStat(kubeClient, req, hostIP, \"\/\")\n}\n\nfunc checkPodVolumeStat(req *request) (util.IcingaState, interface{}) {\n\thost := req.host\n\tname := req.name\n\tparts := strings.Split(host, \"@\")\n\tif len(parts) != 2 {\n\t\treturn util.Unknown, \"Invalid icinga host.name\"\n\t}\n\n\tkubeClient, err := k8s.NewClient()\n\tif err != nil {\n\t\treturn util.Unknown, err\n\t}\n\n\tpod_name := parts[0]\n\tnamespace := parts[1]\n\tpod, err := kubeClient.Client.Core().Pods(namespace).Get(pod_name)\n\tif err != nil {\n\t\treturn util.Unknown, err\n\t}\n\n\tvar volumeSourcePluginName = \"\"\n\tvar volumeSourceName = \"\"\n\tfor _, volume := range pod.Spec.Volumes {\n\t\tif volume.Name == name {\n\t\t\tif volume.PersistentVolumeClaim != nil {\n\t\t\t\tclaim, err := kubeClient.Client.Core().\n\t\t\t\t\tPersistentVolumeClaims(namespace).Get(volume.PersistentVolumeClaim.ClaimName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn util.Unknown, err\n\n\t\t\t\t}\n\t\t\t\tvolume, err := kubeClient.Client.Core().PersistentVolumes().Get(claim.Spec.VolumeName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn util.Unknown, err\n\t\t\t\t}\n\t\t\t\tvolumeSourcePluginName = getPersistentVolumePluginName(&volume.Spec.PersistentVolumeSource)\n\t\t\t\tvolumeSourceName = volume.Name\n\n\t\t\t} else {\n\t\t\t\tvolumeSourcePluginName = getVolumePluginName(&volume.VolumeSource)\n\t\t\t\tvolumeSourceName = volume.Name\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif volumeSourcePluginName == \"\" {\n\t\treturn util.Unknown, errors.New(\"Invalid volume source\")\n\t}\n\n\tpath := fmt.Sprintf(\"\/var\/lib\/kubelet\/pods\/%v\/volumes\/%v\/%v\", pod.UID, volumeSourcePluginName, volumeSourceName)\n\treturn checkDiskStat(kubeClient, req, pod.Status.HostIP, path)\n}\n\nfunc NewCmd() *cobra.Command {\n\tvar req request\n\n\tc := &cobra.Command{\n\t\tUse:     \"check_volume\",\n\t\tShort:   \"Check kubernetes volume\",\n\t\tExample: \"\",\n\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tflags.EnsureRequiredFlags(cmd, \"host\")\n\t\t\tif req.node_stat {\n\t\t\t\tcheckNodeDiskStat(&req)\n\t\t\t} else {\n\t\t\t\tflags.EnsureRequiredFlags(cmd, \"name\")\n\t\t\t\tcheckPodVolumeStat(&req)\n\t\t\t}\n\t\t},\n\t}\n\n\tc.Flags().BoolVar(&req.node_stat, \"node_stat\", false, \"Checking Node disk size\")\n\tc.Flags().StringVarP(&req.secret, \"secret\", \"s\", \"\", `Kubernetes secret name`)\n\tc.Flags().StringVarP(&req.host, \"host\", \"H\", \"\", \"Icinga host name\")\n\tc.Flags().StringVarP(&req.name, \"name\", \"N\", \"\", \"Volume name\")\n\tc.Flags().Float64VarP(&req.warning, \"warning\", \"w\", 75.0, \"Warning level value (usage percentage)\")\n\tc.Flags().Float64VarP(&req.critical, \"critical\", \"c\", 90.0, \"Critical level value (usage percentage)\")\n\treturn c\n}\n<commit_msg>Used \"appscode\/go\/net\/httpclient\" as Client (#23)<commit_after>package check_volume\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/appscode\/go\/flags\"\n\t\"github.com\/appscode\/go\/net\/httpclient\"\n\t\"github.com\/appscode\/searchlight\/pkg\/client\/k8s\"\n\t\"github.com\/appscode\/searchlight\/util\"\n\t\"github.com\/spf13\/cobra\"\n\tkapi \"k8s.io\/kubernetes\/pkg\/api\"\n)\n\nconst (\n\tawsElasticBlockStorePluginName = \"kubernetes.io~aws-ebs\"\n\tazureDataDiskPluginName        = \"kubernetes.io~azure-disk\"\n\tazureFilePluginName            = \"kubernetes.io~azure-file\"\n\tcephfsPluginName               = \"kubernetes.io~cephfs\"\n\tcinderVolumePluginName         = \"kubernetes.io~cinder\"\n\tconfigMapPluginName            = \"kubernetes.io~configmap\"\n\tdownwardAPIPluginName          = \"kubernetes.io~downward-api\"\n\temptyDirPluginName             = \"kubernetes.io~empty-dir\"\n\tfcPluginName                   = \"kubernetes.io~fc\"\n\tflockerPluginName              = \"kubernetes.io~flocker\"\n\tgcePersistentDiskPluginName    = \"kubernetes.io~gce-pd\"\n\tgitRepoPluginName              = \"kubernetes.io~git-repo\"\n\tglusterfsPluginName            = \"kubernetes.io~glusterfs\"\n\thostPathPluginName             = \"kubernetes.io~host-path\"\n\tiscsiPluginName                = \"kubernetes.io~iscsi\"\n\tnfsPluginName                  = \"kubernetes.io~nfs\"\n\tquobytePluginName              = \"kubernetes.io~quobyte\"\n\trbdPluginName                  = \"kubernetes.io~rbd\"\n\tsecretPluginName               = \"kubernetes.io~secret\"\n\tvsphereVolumePluginName        = \"kubernetes.io~vsphere-volume\"\n)\n\nfunc getVolumePluginName(volumeSource *kapi.VolumeSource) string {\n\tif volumeSource.AWSElasticBlockStore != nil {\n\t\treturn awsElasticBlockStorePluginName\n\t} else if volumeSource.AzureDisk != nil {\n\t\treturn azureDataDiskPluginName\n\t} else if volumeSource.AzureFile != nil {\n\t\treturn azureFilePluginName\n\t} else if volumeSource.CephFS != nil {\n\t\treturn cephfsPluginName\n\t} else if volumeSource.Cinder != nil {\n\t\treturn cinderVolumePluginName\n\t} else if volumeSource.ConfigMap != nil {\n\t\treturn configMapPluginName\n\t} else if volumeSource.DownwardAPI != nil {\n\t\treturn downwardAPIPluginName\n\t} else if volumeSource.EmptyDir != nil {\n\t\treturn emptyDirPluginName\n\t} else if volumeSource.FC != nil {\n\t\treturn fcPluginName\n\t} else if volumeSource.Flocker != nil {\n\t\treturn flockerPluginName\n\t} else if volumeSource.GCEPersistentDisk != nil {\n\t\treturn gcePersistentDiskPluginName\n\t} else if volumeSource.GitRepo != nil {\n\t\treturn gitRepoPluginName\n\t} else if volumeSource.Glusterfs != nil {\n\t\treturn glusterfsPluginName\n\t} else if volumeSource.HostPath != nil {\n\t\treturn hostPathPluginName\n\t} else if volumeSource.ISCSI != nil {\n\t\treturn iscsiPluginName\n\t} else if volumeSource.NFS != nil {\n\t\treturn nfsPluginName\n\t} else if volumeSource.Quobyte != nil {\n\t\treturn quobytePluginName\n\t} else if volumeSource.RBD != nil {\n\t\treturn rbdPluginName\n\t} else if volumeSource.Secret != nil {\n\t\treturn secretPluginName\n\t} else if volumeSource.VsphereVolume != nil {\n\t\treturn vsphereVolumePluginName\n\t}\n\treturn \"\"\n}\n\nfunc getPersistentVolumePluginName(volumeSource *kapi.PersistentVolumeSource) string {\n\tif volumeSource.AWSElasticBlockStore != nil {\n\t\treturn awsElasticBlockStorePluginName\n\t} else if volumeSource.AzureDisk != nil {\n\t\treturn azureDataDiskPluginName\n\t} else if volumeSource.AzureFile != nil {\n\t\treturn azureFilePluginName\n\t} else if volumeSource.CephFS != nil {\n\t\treturn cephfsPluginName\n\t} else if volumeSource.Cinder != nil {\n\t\treturn cinderVolumePluginName\n\t} else if volumeSource.FC != nil {\n\t\treturn fcPluginName\n\t} else if volumeSource.Flocker != nil {\n\t\treturn flockerPluginName\n\t} else if volumeSource.GCEPersistentDisk != nil {\n\t\treturn gcePersistentDiskPluginName\n\t} else if volumeSource.Glusterfs != nil {\n\t\treturn glusterfsPluginName\n\t} else if volumeSource.HostPath != nil {\n\t\treturn hostPathPluginName\n\t} else if volumeSource.ISCSI != nil {\n\t\treturn iscsiPluginName\n\t} else if volumeSource.NFS != nil {\n\t\treturn nfsPluginName\n\t} else if volumeSource.Quobyte != nil {\n\t\treturn quobytePluginName\n\t} else if volumeSource.RBD != nil {\n\t\treturn rbdPluginName\n\t} else if volumeSource.VsphereVolume != nil {\n\t\treturn vsphereVolumePluginName\n\t}\n\treturn \"\"\n}\n\nconst (\n\thostFactPort = 56977\n)\n\ntype request struct {\n\thost      string\n\tname      string\n\twarning   float64\n\tcritical  float64\n\tnode_stat bool\n\tsecret    string\n}\n\ntype usageStat struct {\n\tPath              string  `json:\"path\"`\n\tFstype            string  `json:\"fstype\"`\n\tTotal             uint64  `json:\"total\"`\n\tFree              uint64  `json:\"free\"`\n\tUsed              uint64  `json:\"used\"`\n\tUsedPercent       float64 `json:\"usedPercent\"`\n\tInodesTotal       uint64  `json:\"inodesTotal\"`\n\tInodesUsed        uint64  `json:\"inodesUsed\"`\n\tInodesFree        uint64  `json:\"inodesFree\"`\n\tInodesUsedPercent float64 `json:\"inodesUsedPercent\"`\n}\n\ntype authInfo struct {\n\tca        []byte\n\tkey       []byte\n\tcrt       []byte\n\tauthToken string\n\tusername  string\n\tpassword  string\n}\n\nconst (\n\tca        = \"ca.crt\"\n\tkey       = \"hostfacts.key\"\n\tcrt       = \"hostfacts.crt\"\n\tauthToken = \"auth_token\"\n\tusername  = \"username\"\n\tpassword  = \"password\"\n)\n\nfunc getHostfactsSecretData(kubeClient *k8s.KubeClient, secretName string) *authInfo {\n\tif secretName == \"\" {\n\t\treturn nil\n\t}\n\n\tparts := strings.Split(secretName, \".\")\n\tname := parts[0]\n\tnamespace := \"default\"\n\tif len(parts) > 1 {\n\t\tnamespace = parts[1]\n\t}\n\n\tsecret, err := kubeClient.Client.Core().Secrets(namespace).Get(name)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tauthData := &authInfo{\n\t\tca:        secret.Data[ca],\n\t\tkey:       secret.Data[key],\n\t\tcrt:       secret.Data[crt],\n\t\tauthToken: string(secret.Data[authToken]),\n\t\tusername:  string(secret.Data[username]),\n\t\tpassword:  string(secret.Data[password]),\n\t}\n\n\treturn authData\n}\n\nfunc getUsage(authInfo *authInfo, hostIP, path string) (*usageStat, error) {\n\tscheme := \"http\"\n\thttpClient := httpclient.Default()\n\tif authInfo != nil && authInfo.ca != nil {\n\t\tscheme = \"https\"\n\t\thttpClient.WithBasicAuth(authInfo.username, authInfo.password).\n\t\t\tWithBearerToken(authInfo.authToken).\n\t\t        WithTLSConfig(authInfo.ca, authInfo.crt, authInfo.key)\n\t}\n\n\turlStr := fmt.Sprintf(\"%v:\/\/%v:%v\/du?p=%v\", scheme, hostIP, hostFactPort, path)\n\tusages := make([]*usageStat, 1)\n\t_, err := httpClient.Call(http.MethodGet, urlStr, nil, &usages, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn usages[0], nil\n}\n\nfunc checkResult(field string, warning, critical, result float64) (util.IcingaState, interface{}) {\n\tif result >= critical {\n\t\treturn util.Critical, fmt.Sprintf(\"%v used more than %v%%\", field, critical)\n\t}\n\tif result >= warning {\n\t\treturn util.Warning, fmt.Sprintf(\"%v used more than %v%%\", field, warning)\n\t}\n\treturn util.Ok, \"(Disk & Inodes)\"\n}\n\nfunc checkDiskStat(kubeClient *k8s.KubeClient, req *request, nodeIP, path string) (util.IcingaState, interface{}) {\n\tauthInfo := getHostfactsSecretData(kubeClient, req.secret)\n\n\tusage, err := getUsage(authInfo, nodeIP, path)\n\tif err != nil {\n\t\treturn util.Unknown, err\n\t}\n\n\twarning := req.warning\n\tcritical := req.critical\n\tstate, message := checkResult(\"Disk\", warning, critical, usage.UsedPercent)\n\tif state != util.Ok {\n\t\treturn state, message\n\t}\n\tstate, message = checkResult(\"Inodes\", warning, critical, usage.InodesUsedPercent)\n\treturn state, message\n}\n\nfunc checkNodeDiskStat(req *request) (util.IcingaState, interface{}) {\n\thost := req.host\n\tparts := strings.Split(host, \"@\")\n\tif len(parts) != 2 {\n\t\treturn util.Unknown, \"Invalid icinga host.name\"\n\t}\n\n\tkubeClient, err := k8s.NewClient()\n\tif err != nil {\n\t\treturn util.Unknown, err\n\t}\n\n\tnode_name := parts[0]\n\tnode, err := kubeClient.Client.Core().Nodes().Get(node_name)\n\tif err != nil {\n\t\treturn util.Unknown, err\n\t}\n\n\tif node == nil {\n\t\treturn util.Unknown, \"Node not found\"\n\t}\n\n\thostIP := \"\"\n\tfor _, address := range node.Status.Addresses {\n\t\tif address.Type == kapi.NodeInternalIP {\n\t\t\thostIP = address.Address\n\t\t}\n\t}\n\n\tif hostIP == \"\" {\n\t\treturn util.Unknown, \"Node InternalIP not found\"\n\t}\n\treturn checkDiskStat(kubeClient, req, hostIP, \"\/\")\n}\n\nfunc checkPodVolumeStat(req *request) (util.IcingaState, interface{}) {\n\thost := req.host\n\tname := req.name\n\tparts := strings.Split(host, \"@\")\n\tif len(parts) != 2 {\n\t\treturn util.Unknown, \"Invalid icinga host.name\"\n\t}\n\n\tkubeClient, err := k8s.NewClient()\n\tif err != nil {\n\t\treturn util.Unknown, err\n\t}\n\n\tpod_name := parts[0]\n\tnamespace := parts[1]\n\tpod, err := kubeClient.Client.Core().Pods(namespace).Get(pod_name)\n\tif err != nil {\n\t\treturn util.Unknown, err\n\t}\n\n\tvar volumeSourcePluginName = \"\"\n\tvar volumeSourceName = \"\"\n\tfor _, volume := range pod.Spec.Volumes {\n\t\tif volume.Name == name {\n\t\t\tif volume.PersistentVolumeClaim != nil {\n\t\t\t\tclaim, err := kubeClient.Client.Core().\n\t\t\t\t\tPersistentVolumeClaims(namespace).Get(volume.PersistentVolumeClaim.ClaimName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn util.Unknown, err\n\n\t\t\t\t}\n\t\t\t\tvolume, err := kubeClient.Client.Core().PersistentVolumes().Get(claim.Spec.VolumeName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn util.Unknown, err\n\t\t\t\t}\n\t\t\t\tvolumeSourcePluginName = getPersistentVolumePluginName(&volume.Spec.PersistentVolumeSource)\n\t\t\t\tvolumeSourceName = volume.Name\n\n\t\t\t} else {\n\t\t\t\tvolumeSourcePluginName = getVolumePluginName(&volume.VolumeSource)\n\t\t\t\tvolumeSourceName = volume.Name\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif volumeSourcePluginName == \"\" {\n\t\treturn util.Unknown, errors.New(\"Invalid volume source\")\n\t}\n\n\tpath := fmt.Sprintf(\"\/var\/lib\/kubelet\/pods\/%v\/volumes\/%v\/%v\", pod.UID, volumeSourcePluginName, volumeSourceName)\n\treturn checkDiskStat(kubeClient, req, pod.Status.HostIP, path)\n}\n\nfunc NewCmd() *cobra.Command {\n\tvar req request\n\n\tc := &cobra.Command{\n\t\tUse:     \"check_volume\",\n\t\tShort:   \"Check kubernetes volume\",\n\t\tExample: \"\",\n\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tflags.EnsureRequiredFlags(cmd, \"host\")\n\t\t\tif req.node_stat {\n\t\t\t\tcheckNodeDiskStat(&req)\n\t\t\t} else {\n\t\t\t\tflags.EnsureRequiredFlags(cmd, \"name\")\n\t\t\t\tcheckPodVolumeStat(&req)\n\t\t\t}\n\t\t},\n\t}\n\n\tc.Flags().BoolVar(&req.node_stat, \"node_stat\", false, \"Checking Node disk size\")\n\tc.Flags().StringVarP(&req.secret, \"secret\", \"s\", \"\", `Kubernetes secret name`)\n\tc.Flags().StringVarP(&req.host, \"host\", \"H\", \"\", \"Icinga host name\")\n\tc.Flags().StringVarP(&req.name, \"name\", \"N\", \"\", \"Volume name\")\n\tc.Flags().Float64VarP(&req.warning, \"warning\", \"w\", 75.0, \"Warning level value (usage percentage)\")\n\tc.Flags().Float64VarP(&req.critical, \"critical\", \"c\", 90.0, \"Critical level value (usage percentage)\")\n\treturn c\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\r\n\r\n\/*\r\nconference.go -- server-side Go App Engine API;\r\n    uses Google Cloud Endpoints\r\n\r\n*\/\r\n\r\n\r\nimport (\r\n\t\"log\"\r\n\tapplog \"google.golang.org\/appengine\/log\"\r\n\t\"github.com\/GoogleCloudPlatform\/go-endpoints\/endpoints\"\r\n\t\"net\/http\"\r\n\t\"google.golang.org\/appengine\"\r\n)\r\n\r\ntype ConferenceApi struct {\r\n}\r\n\r\nfunc copyProfileToForm(r *http.Request, prof *Profile) (*ProfileForm, error) {\r\n\t\/\/Copy relevant fields from Profile to ProfileForm.\r\n\tpf := &ProfileForm{\r\n\t\t\tDisplayName: prof.DisplayName,\r\n\t\t\tMainEmail: prof.MainEmail,\r\n\t\t\tTeeShirtSize: StringEnumToTeeShirtSize(prof.TeeShirtSize),\r\n\t}\r\n\tappCtx := appengine.NewContext(r)\r\n\tapplog.Debugf(appCtx, \"Did run copyProfileToForm()\")\r\n\treturn pf, nil\r\n}\r\n\r\nfunc getProfileFromUser(r *http.Request) (*Profile, error) {\r\n\t\/\/Return user Profile from datastore, creating new one if non-existent.\r\n\t\/\/TODO\r\n\t\/\/make sure user is authed\r\n\tc := endpoints.NewContext(r)\r\n\tuser, err := endpoints.CurrentUser(c, []string{endpoints.EmailScope},\r\n\t\t[]string{WEB_CLIENT_ID, endpoints.APIExplorerClientID}, []string{WEB_CLIENT_ID, endpoints.APIExplorerClientID})\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tif user == nil {\r\n\t\treturn nil, endpoints.UnauthorizedError\r\n\t}\r\n\tvar profile *Profile\r\n\tif profile == nil {\r\n\t\tprofile = &Profile{\r\n\t\t\tDisplayName: user.String(),\r\n\t\t\tMainEmail: user.Email,\r\n\t\t\tTeeShirtSize: TeeShirtSizeToStringEnum(NOT_SPECIFIED),\r\n\t\t}\r\n\t\t\/\/TODO\r\n\t}\r\n\treturn profile, nil\r\n}\r\n\r\nfunc doProfile(r *http.Request, saveRequest *ProfileMiniForm) (*ProfileForm, error) {\r\n\t\/\/Get user Profile and return to user, possibly updating it first.\r\n\t\/\/get user Profile\r\n\tprof, err := getProfileFromUser(r)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\t\r\n\t\/\/if saveProfile(), process user-modifyable fields\r\n\tif saveRequest != nil {\r\n\t\tprof.TeeShirtSize = TeeShirtSizeToStringEnum(saveRequest.TeeShirtSize)\r\n\t\tprof.DisplayName = saveRequest.DisplayName\r\n\t}\r\n\t\r\n\t\/\/return ProfileForm\r\n\treturn copyProfileToForm(r, prof)\r\n}\r\n\r\nfunc (h *ConferenceApi) GetProfile(r *http.Request) (*ProfileForm, error) {\r\n\t\/\/Return user profile.\r\n\treturn doProfile(r, nil)\r\n}\r\n\r\nfunc (h *ConferenceApi) SaveProfile(r *http.Request, pf *ProfileMiniForm) (*ProfileForm, error) {\r\n\t\/\/Update & return user profile.\r\n\treturn doProfile(r, pf)\r\n}\r\n\r\nfunc init() {\r\n\t\/\/Conference API v0.1\r\n\tconference := &ConferenceApi{}\r\n\t\/\/registers API\r\n\tapi, err := endpoints.RegisterService(conference, \"conference\", \"v1\", \"Conference API\", true)\r\n\tif err != nil {\r\n\t\tlog.Fatalf(\"Register service: %v\", err)\r\n\t}\r\n\t\r\n\tregister := func(orig, name, method, path, desc string) {\r\n\t\tm := api.MethodByName(orig)\r\n\t\tif m == nil {\r\n\t\t\tlog.Fatalf(\"Missing method %s\", orig)\r\n\t\t}\r\n\t\ti := m.Info()\r\n\t\ti.Name, i.HTTPMethod, i.Path, i.Desc = name, method, path, desc\r\n\t\ti.Scopes = []string{endpoints.EmailScope}\r\n\t\ti.ClientIds = []string{WEB_CLIENT_ID, endpoints.APIExplorerClientID}\r\n\t}\r\n\r\n\tregister(\"GetProfile\", \"getProfile\", \"GET\", \"profile\", \"Get profile\")\r\n\tregister(\"SaveProfile\", \"saveProfile\", \"POST\", \"profile\", \"Save profile\")\r\n\tendpoints.HandleHTTP()\r\n}\r\n<commit_msg>changed how user-modified fields processed in lines 64-69 - empty fields allow defaults or previous values to persist in lab 3<commit_after>package main\r\n\r\n\/*\r\nconference.go -- server-side Go App Engine API;\r\n    uses Google Cloud Endpoints\r\n\r\n*\/\r\n\r\n\r\nimport (\r\n\t\"log\"\r\n\tapplog \"google.golang.org\/appengine\/log\"\r\n\t\"github.com\/GoogleCloudPlatform\/go-endpoints\/endpoints\"\r\n\t\"net\/http\"\r\n\t\"google.golang.org\/appengine\"\r\n)\r\n\r\ntype ConferenceApi struct {\r\n}\r\n\r\nfunc copyProfileToForm(r *http.Request, prof *Profile) (*ProfileForm, error) {\r\n\t\/\/Copy relevant fields from Profile to ProfileForm.\r\n\tpf := &ProfileForm{\r\n\t\t\tDisplayName: prof.DisplayName,\r\n\t\t\tMainEmail: prof.MainEmail,\r\n\t\t\tTeeShirtSize: StringEnumToTeeShirtSize(prof.TeeShirtSize),\r\n\t}\r\n\tappCtx := appengine.NewContext(r)\r\n\tapplog.Debugf(appCtx, \"Did run copyProfileToForm()\")\r\n\treturn pf, nil\r\n}\r\n\r\nfunc getProfileFromUser(r *http.Request) (*Profile, error) {\r\n\t\/\/Return user Profile from datastore, creating new one if non-existent.\r\n\t\/\/TODO\r\n\t\/\/make sure user is authed\r\n\tc := endpoints.NewContext(r)\r\n\tuser, err := endpoints.CurrentUser(c, []string{endpoints.EmailScope},\r\n\t\t[]string{WEB_CLIENT_ID, endpoints.APIExplorerClientID}, []string{WEB_CLIENT_ID, endpoints.APIExplorerClientID})\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\tif user == nil {\r\n\t\treturn nil, endpoints.UnauthorizedError\r\n\t}\r\n\tvar profile *Profile\r\n\tif profile == nil {\r\n\t\tprofile = &Profile{\r\n\t\t\tDisplayName: user.String(),\r\n\t\t\tMainEmail: user.Email,\r\n\t\t\tTeeShirtSize: TeeShirtSizeToStringEnum(NOT_SPECIFIED),\r\n\t\t}\r\n\t\t\/\/TODO\r\n\t}\r\n\treturn profile, nil\r\n}\r\n\r\nfunc doProfile(r *http.Request, saveRequest *ProfileMiniForm) (*ProfileForm, error) {\r\n\t\/\/Get user Profile and return to user, possibly updating it first.\r\n\t\/\/get user Profile\r\n\tprof, err := getProfileFromUser(r)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\t\r\n\t\/\/if saveProfile(), process user-modifyable fields\r\n\tif saveRequest != nil {\r\n\t\tif saveRequest.DisplayName != \"\" {\r\n\t\t\tprof.DisplayName = saveRequest.DisplayName\r\n\t\t}\r\n\t\tif TeeShirtSizeToStringEnum(saveRequest.TeeShirtSize) != \"\" {\r\n\t\t\tprof.TeeShirtSize = TeeShirtSizeToStringEnum(saveRequest.TeeShirtSize)\r\n\t\t}\r\n\t}\r\n\t\r\n\t\/\/return ProfileForm\r\n\treturn copyProfileToForm(r, prof)\r\n}\r\n\r\nfunc (h *ConferenceApi) GetProfile(r *http.Request) (*ProfileForm, error) {\r\n\t\/\/Return user profile.\r\n\treturn doProfile(r, nil)\r\n}\r\n\r\nfunc (h *ConferenceApi) SaveProfile(r *http.Request, pf *ProfileMiniForm) (*ProfileForm, error) {\r\n\t\/\/Update & return user profile.\r\n\treturn doProfile(r, pf)\r\n}\r\n\r\nfunc init() {\r\n\t\/\/Conference API v0.1\r\n\tconference := &ConferenceApi{}\r\n\t\/\/registers API\r\n\tapi, err := endpoints.RegisterService(conference, \"conference\", \"v1\", \"Conference API\", true)\r\n\tif err != nil {\r\n\t\tlog.Fatalf(\"Register service: %v\", err)\r\n\t}\r\n\t\r\n\tregister := func(orig, name, method, path, desc string) {\r\n\t\tm := api.MethodByName(orig)\r\n\t\tif m == nil {\r\n\t\t\tlog.Fatalf(\"Missing method %s\", orig)\r\n\t\t}\r\n\t\ti := m.Info()\r\n\t\ti.Name, i.HTTPMethod, i.Path, i.Desc = name, method, path, desc\r\n\t\ti.Scopes = []string{endpoints.EmailScope}\r\n\t\ti.ClientIds = []string{WEB_CLIENT_ID, endpoints.APIExplorerClientID}\r\n\t}\r\n\r\n\tregister(\"GetProfile\", \"getProfile\", \"GET\", \"profile\", \"Get profile\")\r\n\tregister(\"SaveProfile\", \"saveProfile\", \"POST\", \"profile\", \"Save profile\")\r\n\tendpoints.HandleHTTP()\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>package battery\n\nimport (\n\t\"bufio\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc Info() (int, int, bool, error) {\n\tf, err := os.Open(\"\/sys\/class\/power_supply\/BAT0\/uevent\")\n\tif err != nil {\n\t\treturn 0, 0, false, err\n\t}\n\tdefer f.Close()\n\tscanner := bufio.NewScanner(f)\n\n\tvar full, now, powerNow float64\n\tvar present bool\n\tfor scanner.Scan() {\n\t\ttokens := strings.SplitN(scanner.Text(), \"=\", 2)\n\t\tif len(tokens) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tswitch tokens[0] {\n\t\tcase \"POWER_SUPPLY_ENERGY_FULL_DESIGN\":\n\t\t\tfull, _ = strconv.ParseFloat(tokens[1], 64)\n\t\tcase \"POWER_SUPPLY_CHARGE_FULL\":\n\t\t\tfull, _ = strconv.ParseFloat(tokens[1], 64)\n\t\tcase \"POWER_SUPPLY_ENERGY_NOW\":\n\t\t\tnow, _ = strconv.ParseFloat(tokens[1], 64)\n\t\tcase \"POWER_SUPPLY_CHARGE_NOW\":\n\t\t\tnow, _ = strconv.ParseFloat(tokens[1], 64)\n\t\tcase \"POWER_SUPPLY_STATUS\":\n\t\t\tpresent = tokens[1] == \"Charging\"\n\t\tcase \"POWER_SUPPLY_POWER_NOW\":\n\t\t\tpowerNow, _ = strconv.ParseFloat(tokens[1], 64)\n\t\t}\n\t}\n\tvar percent, elapsed int\n\tif full > 0 {\n\t\tpercent = int(now \/ full * 100)\n\t}\n\tif powerNow > 0 {\n\t\telapsed = int(now \/ powerNow * 60)\n\t}\n\treturn percent, elapsed, present, nil\n}\n<commit_msg>Enable to detect batteries rather than BAT0<commit_after>package battery\n\nimport (\n\t\"bufio\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc Info() (percent int, elapsed int, present bool, err error) {\n\tvar uevents []string\n\tuevents, err = filepath.Glob(\"\/sys\/class\/power_supply\/BAT*\/uevent\")\n\tif err != nil {\n\t\treturn\n\t}\n\tif len(uevents) == 0 {\n\t\treturn\n\t}\n\tvar f *os.File\n\tfor _, u := range uevents {\n\t\tf, err = os.Open(u)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\tscanner := bufio.NewScanner(f)\n\n\tvar full, now, powerNow float64\n\tfor scanner.Scan() {\n\t\ttokens := strings.SplitN(scanner.Text(), \"=\", 2)\n\t\tif len(tokens) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tswitch tokens[0] {\n\t\tcase \"POWER_SUPPLY_ENERGY_FULL_DESIGN\":\n\t\t\tfull, _ = strconv.ParseFloat(tokens[1], 64)\n\t\tcase \"POWER_SUPPLY_CHARGE_FULL\":\n\t\t\tfull, _ = strconv.ParseFloat(tokens[1], 64)\n\t\tcase \"POWER_SUPPLY_ENERGY_NOW\":\n\t\t\tnow, _ = strconv.ParseFloat(tokens[1], 64)\n\t\tcase \"POWER_SUPPLY_CHARGE_NOW\":\n\t\t\tnow, _ = strconv.ParseFloat(tokens[1], 64)\n\t\tcase \"POWER_SUPPLY_STATUS\":\n\t\t\tpresent = tokens[1] == \"Charging\"\n\t\tcase \"POWER_SUPPLY_POWER_NOW\":\n\t\t\tpowerNow, _ = strconv.ParseFloat(tokens[1], 64)\n\t\t}\n\t}\n\tif full > 0 {\n\t\tpercent = int(now \/ full * 100)\n\t}\n\tif powerNow > 0 {\n\t\telapsed = int(now \/ powerNow * 60)\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package bbox\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/nsf\/termbox-go\"\n)\n\n\/\/ mapping from keyboard box\n\/\/ 2 x 21 = [volume down]\n\/\/ 2 x 24 = [mute]\n\/\/ 3 x 19 = `\n\/\/ 3 x 20 = 1\n\/\/ 3 x 21 = q\n\/\/ 3 x 22 = KeyTab\n\/\/ 3 x 23 = a\n\/\/ 3 x 24 = z\n\/\/ 4 x 19 = KeyF1\n\/\/ 4 x 20 = 2\n\/\/ 4 x 21 = w\n\/\/ 4 x 23 = S\n\/\/ 4 x 24 = §\n\/\/ 4 x 25 = x\n\/\/ 5 x 19 = KeyF2\n\/\/ 5 x 20 = 3\n\/\/ 5 x 21 = e\n\/\/ 5 x 22 = d\n\/\/ 5 x 23 = c\n\/\/ 5 x 24 = KeyF4\n\/\/ 6 x 19 = 5\n\/\/ 6 x 20 = 4\n\/\/ 6 x 21 = r\n\/\/ 6 x 22 = t\n\/\/ 6 x 23 = f\n\/\/ 6 x 24 = g\n\/\/ 6 x 25 = v\n\/\/ 6 x 26 = b\n\/\/ 7 x 19 = 6\n\/\/ 7 x 20 = 7\n\/\/ 7 x 21 = u\n\/\/ 7 x 22 = y\n\/\/ 7 x 23 = j\n\/\/ 7 x 24 = h\n\/\/ 7 x 25 = m\n\/\/ 7 x 26 = n\n\/\/ 8 x 19 = =\n\/\/ 8 x 20 = 8\n\/\/ 8 x 21 = i\n\/\/ 8 x 22 = ]\n\/\/ 8 x 23 = K\n\/\/ 8 x 24 = KeyF6\n\/\/ 8 x 25 = ,\n\/\/ 9 x 19 = KeyF8\n\/\/ 9 x 20 = 9\n\/\/ 9 x 21 = o\n\/\/ 9 x 23 = l\n\/\/ 9 x 25 = .\n\/\/ 10 x 19 = -\n\/\/ 10 x 20 = 0\n\/\/ 10 x 21 = p\n\/\/ 10 x 22 = [\n\/\/ 10 x 23 = ;\n\/\/ 10 x 24 = '\n\/\/ 10 x 25 = \\\n\/\/ 10 x 26 = \/\n\/\/ 11 x 19 = KeyF9\n\/\/ 11 x 20 = KeyF10\n\/\/ 11 x 22 = KeyBackspace2\n\/\/ 11 x 23 = \\ ***\n\/\/ 11 x 24 = KeyF5\n\/\/ 11 x 25 = KeyEnter\n\/\/ 11 x 26 = KeySpace\n\/\/ 12 x 20 = KeyF12\n\/\/ 12 x 21 = 8 ***\n\/\/ 12 x 22 = 5 ***\n\/\/ 12 x 23 = 2 ***\n\/\/ 12 x 24 = 0 ***\n\/\/ 12 x 25 = \/ ***\n\/\/ 12 x 26 = KeyArrowRight\n\/\/ 13 x 19 = KeyDelete\n\/\/ 13 x 20 = [fn f11]\n\/\/ 13 x 21 = 7 ***\n\/\/ 13 x 22 = 4 ***\n\/\/ 13 x 23 = 1 ***\n\/\/ 13 x 26 = KeyArrowDown\n\/\/ 14 x 19 = KeyPgup\n\/\/ 14 x 20 = KeyPgdn\n\/\/ 14 x 21 = 9 ***\n\/\/ 14 x 22 = 6 ***\n\/\/ 14 x 23 = 3 ***\n\/\/ 14 x 24 = . ***\n\/\/ 14 x 25 = *\n\/\/ 14 x 26 = - ***\n\/\/ 15 x 19 = KeyHome\n\/\/ 15 x 20 = KeyEnd\n\/\/ 15 x 21 = +\n\/\/ 15 x 23 = KeyEnter ***\n\/\/ 15 x 24 = KeyArrowUp\n\/\/ 15 x 25 = [brightness up]\n\/\/ 15 x 26 = KeyArrowLeft\n\/\/ 16 x 21 = [brightness down]\n\/\/ 17 x 24 = [launch itunes?]\n\/\/ 18 x 22 = [volume up]\n\nvar keymaps = map[string][]int{\n\t\"1\": []int{0, 0},\n\t\"2\": []int{0, 1},\n\t\"3\": []int{0, 2},\n\t\"4\": []int{0, 3},\n\t\"5\": []int{0, 4},\n\t\"6\": []int{0, 5},\n\t\"7\": []int{0, 6},\n\t\"8\": []int{0, 7},\n\t\"!\": []int{0, 8},\n\t\"@\": []int{0, 9},\n\t\"#\": []int{0, 10},\n\t\"$\": []int{0, 11},\n\t\"%\": []int{0, 12},\n\t\"^\": []int{0, 13},\n\t\"&\": []int{0, 14},\n\t\"*\": []int{0, 15},\n\n\t\"w\": []int{1, 0},\n\t\"e\": []int{1, 1},\n\t\"r\": []int{1, 2},\n\t\"t\": []int{1, 3},\n\t\"y\": []int{1, 4},\n\t\"u\": []int{1, 5},\n\t\"i\": []int{1, 6},\n\t\"o\": []int{1, 7},\n\t\"W\": []int{1, 8},\n\t\"E\": []int{1, 9},\n\t\"R\": []int{1, 10},\n\t\"T\": []int{1, 11},\n\t\"Y\": []int{1, 12},\n\t\"U\": []int{1, 13},\n\t\"I\": []int{1, 14},\n\t\"O\": []int{1, 15},\n\n\t\"a\": []int{2, 0},\n\t\"s\": []int{2, 1},\n\t\"d\": []int{2, 2},\n\t\"f\": []int{2, 3},\n\t\"g\": []int{2, 4},\n\t\"h\": []int{2, 5},\n\t\"j\": []int{2, 6},\n\t\"k\": []int{2, 7},\n\t\"A\": []int{2, 8},\n\t\"S\": []int{2, 9},\n\t\"D\": []int{2, 10},\n\t\"F\": []int{2, 11},\n\t\"G\": []int{2, 12},\n\t\"H\": []int{2, 13},\n\t\"J\": []int{2, 14},\n\t\"K\": []int{2, 15},\n\n\t\"z\": []int{3, 0},\n\t\"x\": []int{3, 1},\n\t\"c\": []int{3, 2},\n\t\"v\": []int{3, 3},\n\t\"b\": []int{3, 4},\n\t\"n\": []int{3, 5},\n\t\"m\": []int{3, 6},\n\t\",\": []int{3, 7},\n\t\"Z\": []int{3, 8},\n\t\"X\": []int{3, 9},\n\t\"C\": []int{3, 10},\n\t\"V\": []int{3, 11},\n\t\"B\": []int{3, 12},\n\t\"N\": []int{3, 13},\n\t\"M\": []int{3, 14},\n\t\"<\": []int{3, 15},\n}\n\nvar keymaps_rpi = map[string][]int{\n\t\"1\": []int{0, 0},  \/\/ 3 x 20\n\t\"q\": []int{0, 1},  \/\/ 3 x 21\n\t\"a\": []int{0, 2},  \/\/ 3 x 23\n\t\"z\": []int{0, 4},  \/\/ 3 x 24\n\t\"2\": []int{0, 5},  \/\/ 4 x 20\n\t\"w\": []int{0, 6},  \/\/ 4 x 21\n\t\"S\": []int{0, 7},  \/\/ 4 x 23\n\t\"§\": []int{0, 8},  \/\/ 4 x 24\n\t\"x\": []int{0, 9},  \/\/ 4 x 25\n\t\"3\": []int{0, 10}, \/\/ 5 x 20\n\t\"e\": []int{0, 11}, \/\/ 5 x 21\n\t\"d\": []int{0, 12}, \/\/ 5 x 22\n\t\"c\": []int{0, 13}, \/\/ 5 x 23\n\t\"5\": []int{0, 14}, \/\/ 6 x 19\n\t\"4\": []int{0, 15}, \/\/ 6 x 20\n\n\t\"r\": []int{1, 0},  \/\/ 6 x 21\n\t\"t\": []int{1, 1},  \/\/ 6 x 22\n\t\"f\": []int{1, 2},  \/\/ 6 x 23\n\t\"g\": []int{1, 3},  \/\/ 6 x 24\n\t\"v\": []int{1, 4},  \/\/ 6 x 25\n\t\"b\": []int{1, 5},  \/\/ 6 x 26\n\t\"6\": []int{1, 6},  \/\/ 7 x 19\n\t\"7\": []int{1, 7},  \/\/ 7 x 20\n\t\"u\": []int{1, 8},  \/\/ 7 x 21\n\t\"y\": []int{1, 9},  \/\/ 7 x 22\n\t\"j\": []int{1, 10}, \/\/ 7 x 23\n\t\"h\": []int{1, 11}, \/\/ 7 x 24\n\t\"m\": []int{1, 12}, \/\/ 7 x 25\n\t\"n\": []int{1, 13}, \/\/ 7 x 26\n\t\"=\": []int{1, 14}, \/\/ 8 x 19\n\t\"8\": []int{1, 15}, \/\/ 8 x 20\n\n\t\"i\":  []int{2, 0},  \/\/ 8 x 21\n\t\"]\":  []int{2, 1},  \/\/ 8 x 22\n\t\"K\":  []int{2, 2},  \/\/ 8 x 23\n\t\",\":  []int{2, 3},  \/\/ 8 x 25\n\t\"9\":  []int{2, 4},  \/\/ 9 x 20\n\t\"o\":  []int{2, 5},  \/\/ 9 x 21\n\t\"l\":  []int{2, 6},  \/\/ 9 x 23\n\t\".\":  []int{2, 7},  \/\/ 9 x 23\n\t\"-\":  []int{2, 8},  \/\/ 10 x 19\n\t\"0\":  []int{2, 9},  \/\/ 10 x 20\n\t\"p\":  []int{2, 10}, \/\/ 10 x 21\n\t\"[\":  []int{2, 11}, \/\/ 10 x 22\n\t\";\":  []int{2, 12}, \/\/ 10 x 23\n\t\"'\":  []int{2, 13}, \/\/ 10 x 24\n\t\"\\\\\": []int{2, 14}, \/\/ 10 x 25\n\t\"\/\":  []int{2, 15}, \/\/ 10 x 26\n\n\t\/\/ \".\": []int{3, 8}, \/\/ 14 x 24\n\n\t\"*\": []int{3, 9}, \/\/ 14 x 25\n\n\t\/\/ \"-\": []int{3, 10}, \/\/ 14 x 26\n\n\t\"+\": []int{3, 13}, \/\/ 15 x 21\n}\n\nvar keymaps_rpi_keys = map[termbox.Key][]int{\n\ttermbox.KeyTab: []int{0, 3}, \/\/ 3 x 22\n\n\ttermbox.KeyBackspace:  []int{3, 0},  \/\/ 11 x 22\n\ttermbox.KeyEnter:      []int{3, 1},  \/\/ 11 x 25\n\ttermbox.KeySpace:      []int{3, 2},  \/\/ 11 x 26\n\ttermbox.KeyArrowRight: []int{3, 3},  \/\/ 12 x 26\n\ttermbox.KeyDelete:     []int{3, 4},  \/\/ 13 x 19\n\ttermbox.KeyArrowDown:  []int{3, 5},  \/\/ 13 x 26\n\ttermbox.KeyPgup:       []int{3, 6},  \/\/ 14 x 19\n\ttermbox.KeyPgdn:       []int{3, 7},  \/\/ 14 x 20\n\ttermbox.KeyHome:       []int{3, 11}, \/\/ 15 x 19\n\ttermbox.KeyEnd:        []int{3, 12}, \/\/ 15 x 20\n\ttermbox.KeyArrowUp:    []int{3, 14}, \/\/ 15 x 24\n\ttermbox.KeyF2:         []int{3, 15}, \/\/ 15 x 25\n}\n\n\/\/ normal operation:\n\/\/   beats -> emit -> msgs\n\/\/ shtudown operation:\n\/\/   q -> close(emit) -> close(msgs) -> termbox.Close()\ntype Keyboard struct {\n\tbeats Beats\n\temit  chan Beats\n\tmsgs  []chan<- Beats\n}\n\nfunc tbprint(x, y int, fg, bg termbox.Attribute, msg string) {\n\tfor _, c := range msg {\n\t\ttermbox.SetCell(x, y, c, fg, bg)\n\t\tx++\n\t}\n}\n\nfunc InitKeyboard(msgs []chan<- Beats) *Keyboard {\n\t\/\/ termbox.Close() called when Render.Run() exits\n\terr := termbox.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttermbox.SetInputMode(termbox.InputAlt)\n\n\treturn &Keyboard{\n\t\tbeats: Beats{},\n\t\temit:  make(chan Beats),\n\t\tmsgs:  msgs,\n\t}\n}\n\nfunc (kb *Keyboard) Run() {\n\tvar current string\n\tvar curev termbox.Event\n\n\tdefer close(kb.emit)\n\n\tdata := make([]byte, 0, 64)\n\n\t\/\/ starter beat\n\tgo kb.Emitter()\n\tkb.beats[1][0] = true\n\tkb.beats[1][8] = true\n\tkb.Emit()\n\n\tfor {\n\t\tif cap(data)-len(data) < 32 {\n\t\t\tnewdata := make([]byte, len(data), len(data)+32)\n\t\t\tcopy(newdata, data)\n\t\t\tdata = newdata\n\t\t}\n\t\tbeg := len(data)\n\t\td := data[beg : beg+32]\n\t\tswitch ev := termbox.PollRawEvent(d); ev.Type {\n\t\tcase termbox.EventRaw:\n\t\t\tdata = data[:beg+ev.N]\n\t\t\tcurrent = fmt.Sprintf(\"%s\", data)\n\t\t\tif current == \"`\" {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tkey := keymaps[current]\n\t\t\tif key != nil {\n\t\t\t\tkb.beats[key[0]][key[1]] = !kb.beats[key[0]][key[1]]\n\t\t\t\tkb.Emit()\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\t\/\/ TODO: move kb.beats code to here\n\t\t\t\tev := termbox.ParseEvent(data)\n\t\t\t\tif ev.N == 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcurev = ev\n\t\t\t\tcopy(data, data[curev.N:])\n\t\t\t\tdata = data[:len(data)-curev.N]\n\n\t\t\t\ttbprint(0, BEATS+1, termbox.ColorDefault, termbox.ColorDefault,\n\t\t\t\t\tfmt.Sprintf(\"EventKey: k: %5d, c: %c\", ev.Key, ev.Ch))\n\t\t\t\ttermbox.Flush()\n\t\t\t}\n\t\tcase termbox.EventError:\n\t\t\tpanic(ev.Err)\n\t\t}\n\t}\n}\n\nfunc (kb *Keyboard) Emit() {\n\tbeats := kb.beats\n\tkb.emit <- beats\n}\n\nfunc (kb *Keyboard) Emitter() {\n\tfor {\n\t\tselect {\n\t\tcase beats, more := <-kb.emit:\n\t\t\tif more {\n\t\t\t\tfor _, msg := range kb.msgs {\n\t\t\t\t\tmsg <- beats\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor _, msg := range kb.msgs {\n\t\t\t\t\tclose(msg)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>clean up mappings<commit_after>package bbox\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/nsf\/termbox-go\"\n)\n\nvar keymaps = map[string][]int{\n\t\"1\": []int{0, 0},\n\t\"2\": []int{0, 1},\n\t\"3\": []int{0, 2},\n\t\"4\": []int{0, 3},\n\t\"5\": []int{0, 4},\n\t\"6\": []int{0, 5},\n\t\"7\": []int{0, 6},\n\t\"8\": []int{0, 7},\n\t\"!\": []int{0, 8},\n\t\"@\": []int{0, 9},\n\t\"#\": []int{0, 10},\n\t\"$\": []int{0, 11},\n\t\"%\": []int{0, 12},\n\t\"^\": []int{0, 13},\n\t\"&\": []int{0, 14},\n\t\"*\": []int{0, 15},\n\n\t\"w\": []int{1, 0},\n\t\"e\": []int{1, 1},\n\t\"r\": []int{1, 2},\n\t\"t\": []int{1, 3},\n\t\"y\": []int{1, 4},\n\t\"u\": []int{1, 5},\n\t\"i\": []int{1, 6},\n\t\"o\": []int{1, 7},\n\t\"W\": []int{1, 8},\n\t\"E\": []int{1, 9},\n\t\"R\": []int{1, 10},\n\t\"T\": []int{1, 11},\n\t\"Y\": []int{1, 12},\n\t\"U\": []int{1, 13},\n\t\"I\": []int{1, 14},\n\t\"O\": []int{1, 15},\n\n\t\"a\": []int{2, 0},\n\t\"s\": []int{2, 1},\n\t\"d\": []int{2, 2},\n\t\"f\": []int{2, 3},\n\t\"g\": []int{2, 4},\n\t\"h\": []int{2, 5},\n\t\"j\": []int{2, 6},\n\t\"k\": []int{2, 7},\n\t\"A\": []int{2, 8},\n\t\"S\": []int{2, 9},\n\t\"D\": []int{2, 10},\n\t\"F\": []int{2, 11},\n\t\"G\": []int{2, 12},\n\t\"H\": []int{2, 13},\n\t\"J\": []int{2, 14},\n\t\"K\": []int{2, 15},\n\n\t\"z\": []int{3, 0},\n\t\"x\": []int{3, 1},\n\t\"c\": []int{3, 2},\n\t\"v\": []int{3, 3},\n\t\"b\": []int{3, 4},\n\t\"n\": []int{3, 5},\n\t\"m\": []int{3, 6},\n\t\",\": []int{3, 7},\n\t\"Z\": []int{3, 8},\n\t\"X\": []int{3, 9},\n\t\"C\": []int{3, 10},\n\t\"V\": []int{3, 11},\n\t\"B\": []int{3, 12},\n\t\"N\": []int{3, 13},\n\t\"M\": []int{3, 14},\n\t\"<\": []int{3, 15},\n}\n\ntype Key struct {\n\tCh  rune        \/\/ a unicode character\n\tKey termbox.Key \/\/ one of Key* constants, invalid if 'Ch' is not 0\n}\n\n\/\/ mapping from keyboard box\nvar keymaps_rpi = map[Key][]int{\n\t\/\/ 2 x 21 = [volume down]\n\t\/\/ 2 x 24 = [mute]\n\t\/\/ 3 x 19 = ` (quit)\n\n\t{'1', 0}:            []int{0, 0}, \/\/ 3 x 20\n\t{'q', 0}:            []int{0, 1}, \/\/ 3 x 21\n\t{0, termbox.KeyTab}: []int{0, 2}, \/\/ 3 x 22\n\t{'a', 0}:            []int{0, 3}, \/\/ 3 x 23\n\t{'z', 0}:            []int{0, 4}, \/\/ 3 x 24\n\t{0, termbox.KeyF1}:  []int{0, 5}, \/\/ 4 x 19\n\t{'2', 0}:            []int{0, 6}, \/\/ 4 x 20\n\t{'w', 0}:            []int{0, 7}, \/\/ 4 x 21\n\t{'S', 0}:            []int{0, 8}, \/\/ 4 x 23\n\t\/\/ 4 x 24 = §\n\t{'x', 0}:           []int{0, 9},  \/\/ 4 x 25\n\t{0, termbox.KeyF2}: []int{0, 10}, \/\/ 5 x 19\n\t{'3', 0}:           []int{0, 11}, \/\/ 5 x 20\n\t{'e', 0}:           []int{0, 12}, \/\/ 5 x 21\n\t{'d', 0}:           []int{0, 13}, \/\/ 5 x 22\n\t{'c', 0}:           []int{0, 14}, \/\/ 5 x 23\n\t{0, termbox.KeyF4}: []int{0, 15}, \/\/ 5 x 24\n\n\t{'5', 0}: []int{1, 0},  \/\/ 6 x 19\n\t{'4', 0}: []int{1, 1},  \/\/ 6 x 20\n\t{'r', 0}: []int{1, 2},  \/\/ 6 x 21\n\t{'t', 0}: []int{1, 3},  \/\/ 6 x 22\n\t{'f', 0}: []int{1, 4},  \/\/ 6 x 23\n\t{'g', 0}: []int{1, 5},  \/\/ 6 x 24\n\t{'v', 0}: []int{1, 6},  \/\/ 6 x 25\n\t{'b', 0}: []int{1, 7},  \/\/ 6 x 26\n\t{'6', 0}: []int{1, 8},  \/\/ 7 x 19\n\t{'7', 0}: []int{1, 9},  \/\/ 7 x 20\n\t{'u', 0}: []int{1, 10}, \/\/ 7 x 21\n\t{'y', 0}: []int{1, 11}, \/\/ 7 x 22\n\t{'j', 0}: []int{1, 12}, \/\/ 7 x 23\n\t{'h', 0}: []int{1, 13}, \/\/ 7 x 24\n\t{'m', 0}: []int{1, 14}, \/\/ 7 x 25\n\t{'n', 0}: []int{1, 15}, \/\/ 7 x 26\n\n\t{'=', 0}:           []int{2, 0},  \/\/ 8 x 19\n\t{'8', 0}:           []int{2, 1},  \/\/ 8 x 20\n\t{'i', 0}:           []int{2, 2},  \/\/ 8 x 21\n\t{']', 0}:           []int{2, 3},  \/\/ 8 x 22\n\t{'K', 0}:           []int{2, 4},  \/\/ 8 x 23\n\t{0, termbox.KeyF6}: []int{2, 5},  \/\/ 8 x 24\n\t{',', 0}:           []int{2, 6},  \/\/ 8 x 25\n\t{0, termbox.KeyF8}: []int{2, 7},  \/\/ 9 x 19\n\t{'9', 0}:           []int{2, 8},  \/\/ 9 x 20\n\t{'o', 0}:           []int{2, 9},  \/\/ 9 x 21\n\t{'l', 0}:           []int{2, 10}, \/\/ 9 x 23\n\t{'.', 0}:           []int{2, 11}, \/\/ 9 x 25\n\t{'-', 0}:           []int{2, 12}, \/\/ 10 x 19\n\t{'0', 0}:           []int{2, 13}, \/\/ 10 x 20\n\t{'p', 0}:           []int{2, 14}, \/\/ 10 x 21\n\t{'[', 0}:           []int{2, 15}, \/\/ 10 x 22\n\n\t{';', 0}:                   []int{3, 0}, \/\/ 10 x 23\n\t{'\\'', 0}:                  []int{3, 1}, \/\/ 10 x 24\n\t{'\\\\', 0}:                  []int{3, 2}, \/\/ 10 x 25\n\t{'\/', 0}:                   []int{3, 3}, \/\/ 10 x 26\n\t{0, termbox.KeyF9}:         []int{3, 4}, \/\/ 11 x 19\n\t{0, termbox.KeyF10}:        []int{3, 5}, \/\/ 11 x 20\n\t{0, termbox.KeyBackspace2}: []int{3, 6}, \/\/ 11 x 22\n\t\/\/ 11 x 23 = \\ ***\n\t{0, termbox.KeyF5}:    []int{3, 7},  \/\/ 11 x 24\n\t{0, termbox.KeyEnter}: []int{3, 8},  \/\/ 11 x 25\n\t{0, termbox.KeySpace}: []int{3, 9},  \/\/ 11 x 26\n\t{0, termbox.KeyF12}:   []int{3, 10}, \/\/ 12 x 20\n\t\/\/ 12 x 21 = 8 ***\n\t\/\/ 12 x 22 = 5 ***\n\t\/\/ 12 x 23 = 2 ***\n\t\/\/ 12 x 24 = 0 ***\n\t\/\/ 12 x 25 = \/ ***\n\t{0, termbox.KeyArrowRight}: []int{3, 11}, \/\/ 12 x 26\n\t{0, termbox.KeyDelete}:     []int{3, 12}, \/\/ 13 x 19\n\t\/\/ 13 x 20 = [fn f11]\n\t\/\/ 13 x 21 = 7 ***\n\t\/\/ 13 x 22 = 4 ***\n\t\/\/ 13 x 23 = 1 ***\n\t{0, termbox.KeyArrowDown}: []int{3, 13}, \/\/ 13 x 26\n\t{0, termbox.KeyPgup}:      []int{3, 14}, \/\/ 14 x 19\n\t{0, termbox.KeyPgdn}:      []int{3, 15}, \/\/ 14 x 20\n\t\/\/ 14 x 21 = 9 ***\n\t\/\/ 14 x 22 = 6 ***\n\t\/\/ 14 x 23 = 3 ***\n\t\/\/ 14 x 24 = . ***\n\t\/\/ 14 x 25 = *\n\t\/\/ 14 x 26 = - ***\n\t\/\/ 15 x 19 = KeyHome\n\t\/\/ 15 x 20 = KeyEnd\n\t\/\/ 15 x 21 = +\n\t\/\/ 15 x 23 = KeyEnter ***\n\t\/\/ 15 x 24 = KeyArrowUp\n\t\/\/ 15 x 25 = [brightness up]\n\t\/\/ 15 x 26 = KeyArrowLeft\n\t\/\/ 16 x 21 = [brightness down]\n\t\/\/ 17 x 24 = [launch itunes?]\n\t\/\/ 18 x 22 = [volume up]\n}\n\n\/\/ normal operation:\n\/\/   beats -> emit -> msgs\n\/\/ shtudown operation:\n\/\/   q -> close(emit) -> close(msgs) -> termbox.Close()\ntype Keyboard struct {\n\tbeats Beats\n\temit  chan Beats\n\tmsgs  []chan<- Beats\n}\n\nfunc tbprint(x, y int, fg, bg termbox.Attribute, msg string) {\n\tfor _, c := range msg {\n\t\ttermbox.SetCell(x, y, c, fg, bg)\n\t\tx++\n\t}\n}\n\nfunc InitKeyboard(msgs []chan<- Beats) *Keyboard {\n\t\/\/ termbox.Close() called when Render.Run() exits\n\terr := termbox.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttermbox.SetInputMode(termbox.InputAlt)\n\n\treturn &Keyboard{\n\t\tbeats: Beats{},\n\t\temit:  make(chan Beats),\n\t\tmsgs:  msgs,\n\t}\n}\n\nfunc (kb *Keyboard) Run() {\n\tvar current string\n\tvar curev termbox.Event\n\n\tdefer close(kb.emit)\n\n\tdata := make([]byte, 0, 64)\n\n\t\/\/ starter beat\n\tgo kb.Emitter()\n\tkb.beats[1][0] = true\n\tkb.beats[1][8] = true\n\tkb.Emit()\n\n\tfor {\n\t\tif cap(data)-len(data) < 32 {\n\t\t\tnewdata := make([]byte, len(data), len(data)+32)\n\t\t\tcopy(newdata, data)\n\t\t\tdata = newdata\n\t\t}\n\t\tbeg := len(data)\n\t\td := data[beg : beg+32]\n\t\tswitch ev := termbox.PollRawEvent(d); ev.Type {\n\t\tcase termbox.EventRaw:\n\t\t\tdata = data[:beg+ev.N]\n\t\t\tcurrent = fmt.Sprintf(\"%s\", data)\n\t\t\tif current == \"`\" {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tkey := keymaps[current]\n\t\t\tif key != nil {\n\t\t\t\tkb.beats[key[0]][key[1]] = !kb.beats[key[0]][key[1]]\n\t\t\t\tkb.Emit()\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\t\/\/ TODO: move kb.beats code to here\n\t\t\t\tev := termbox.ParseEvent(data)\n\t\t\t\tif ev.N == 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcurev = ev\n\t\t\t\tcopy(data, data[curev.N:])\n\t\t\t\tdata = data[:len(data)-curev.N]\n\n\t\t\t\ttbprint(0, BEATS+1, termbox.ColorDefault, termbox.ColorDefault,\n\t\t\t\t\tfmt.Sprintf(\"EventKey: k: %5d, c: %c\", ev.Key, ev.Ch))\n\t\t\t\ttermbox.Flush()\n\t\t\t}\n\t\tcase termbox.EventError:\n\t\t\tpanic(ev.Err)\n\t\t}\n\t}\n}\n\nfunc (kb *Keyboard) Emit() {\n\tbeats := kb.beats\n\tkb.emit <- beats\n}\n\nfunc (kb *Keyboard) Emitter() {\n\tfor {\n\t\tselect {\n\t\tcase beats, more := <-kb.emit:\n\t\t\tif more {\n\t\t\t\tfor _, msg := range kb.msgs {\n\t\t\t\t\tmsg <- beats\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor _, msg := range kb.msgs {\n\t\t\t\t\tclose(msg)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package bcrypt implements Provos and Mazières's bcrypt adaptive hashing\n\/\/ algorithm. See http:\/\/www.usenix.org\/event\/usenix99\/provos\/provos.pdf\npackage bcrypt\n\n\/\/ The code is a port of Provos and Mazières's C implementation.\nimport (\n\t\"code.google.com\/p\/go.crypto\/blowfish\"\n\t\"crypto\/rand\"\n\t\"crypto\/subtle\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n)\n\nconst (\n\tMinCost     int = 4  \/\/ the minimum allowable cost as passed in to GenerateFromPassword\n\tMaxCost     int = 31 \/\/ the maximum allowable cost as passed in to GenerateFromPassword\n\tDefaultCost int = 10 \/\/ the cost that will actually be set if a cost below MinCost is passed into GenerateFromPassword\n)\n\n\/\/ The error returned from CompareHashAndPassword when a password and hash do\n\/\/ not match.\nvar ErrMismatchedHashAndPassword = errors.New(\"crypto\/bcrypt: hashedPassword is not the hash of the given password\")\n\n\/\/ The error returned from CompareHashAndPassword when a hash is too short to\n\/\/ be a bcrypt hash.\nvar ErrHashTooShort = errors.New(\"crypto\/bcrypt: hashedSecret too short to be a bcrypted password\")\n\n\/\/ The error returned from CompareHashAndPassword when a hash was created with\n\/\/ a bcrypt algorithm newer than this implementation.\ntype HashVersionTooNewError byte\n\nfunc (hv HashVersionTooNewError) Error() string {\n\treturn fmt.Sprintf(\"crypto\/bcrypt: bcrypt algorithm version '%c' requested is newer than current version '%c'\", byte(hv), majorVersion)\n}\n\n\/\/ The error returned from CompareHashAndPassword when a hash starts with something other than '$'\ntype InvalidHashPrefixError byte\n\nfunc (ih InvalidHashPrefixError) Error() string {\n\treturn fmt.Sprintf(\"crypto\/bcrypt: bcrypt hashes must start with '$', but hashedSecret started with '%c'\", byte(ih))\n}\n\ntype InvalidCostError int\n\nfunc (ic InvalidCostError) Error() string {\n\treturn fmt.Sprintf(\"crypto\/bcrypt: cost %d is outside allowed range (%d,%d)\", int(ic), int(MinCost), int(MaxCost))\n}\n\nconst (\n\tmajorVersion       = '2'\n\tminorVersion       = 'a'\n\tmaxSaltSize        = 16\n\tmaxCryptedHashSize = 23\n\tencodedSaltSize    = 22\n\tencodedHashSize    = 31\n\tminHashSize        = 59\n)\n\n\/\/ magicCipherData is an IV for the 64 Blowfish encryption calls in\n\/\/ bcrypt(). It's the string \"OrpheanBeholderScryDoubt\" in big-endian bytes.\nvar magicCipherData = []byte{\n\t0x4f, 0x72, 0x70, 0x68,\n\t0x65, 0x61, 0x6e, 0x42,\n\t0x65, 0x68, 0x6f, 0x6c,\n\t0x64, 0x65, 0x72, 0x53,\n\t0x63, 0x72, 0x79, 0x44,\n\t0x6f, 0x75, 0x62, 0x74,\n}\n\ntype hashed struct {\n\thash  []byte\n\tsalt  []byte\n\tcost  int \/\/ allowed range is MinCost to MaxCost\n\tmajor byte\n\tminor byte\n}\n\n\/\/ GenerateFromPassword returns the bcrypt hash of the password at the given\n\/\/ cost. If the cost given is less than MinCost, the cost will be set to\n\/\/ DefaultCost, instead. Use CompareHashAndPassword, as defined in this package,\n\/\/ to compare the returned hashed password with its cleartext version.\nfunc GenerateFromPassword(password []byte, cost int) ([]byte, error) {\n\tp, err := newFromPassword(password, cost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p.Hash(), nil\n}\n\n\/\/ CompareHashAndPassword compares a bcrypt hashed password with its possible\n\/\/ plaintext equivalent. Returns nil on success, or an error on failure.\nfunc CompareHashAndPassword(hashedPassword, password []byte) error {\n\tp, err := newFromHash(hashedPassword)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\totherHash, err := bcrypt(password, p.cost, p.salt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\totherP := &hashed{otherHash, p.salt, p.cost, p.major, p.minor}\n\tif subtle.ConstantTimeCompare(p.Hash(), otherP.Hash()) == 1 {\n\t\treturn nil\n\t}\n\n\treturn ErrMismatchedHashAndPassword\n}\n\n\/\/ Cost returns the hashing cost used to create the given hashed\n\/\/ password. When, in the future, the hashing cost of a password system needs\n\/\/ to be increased in order to adjust for greater computational power, this\n\/\/ function allows one to establish which passwords need to be updated.\nfunc Cost(hashedPassword []byte) (int, error) {\n\tp, err := newFromHash(hashedPassword)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn p.cost, nil\n}\n\nfunc newFromPassword(password []byte, cost int) (*hashed, error) {\n\tif cost < MinCost {\n\t\tcost = DefaultCost\n\t}\n\tp := new(hashed)\n\tp.major = majorVersion\n\tp.minor = minorVersion\n\n\terr := checkCost(cost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.cost = cost\n\n\tunencodedSalt := make([]byte, maxSaltSize)\n\t_, err = io.ReadFull(rand.Reader, unencodedSalt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp.salt = base64Encode(unencodedSalt)\n\thash, err := bcrypt(password, p.cost, p.salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.hash = hash\n\treturn p, err\n}\n\nfunc newFromHash(hashedSecret []byte) (*hashed, error) {\n\tif len(hashedSecret) < minHashSize {\n\t\treturn nil, ErrHashTooShort\n\t}\n\tp := new(hashed)\n\tn, err := p.decodeVersion(hashedSecret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thashedSecret = hashedSecret[n:]\n\tn, err = p.decodeCost(hashedSecret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thashedSecret = hashedSecret[n:]\n\n\t\/\/ The \"+2\" is here because we'll have to append at most 2 '=' to the salt\n\t\/\/ when base64 decoding it in expensiveBlowfishSetup().\n\tp.salt = make([]byte, encodedSaltSize, encodedSaltSize+2)\n\tcopy(p.salt, hashedSecret[:encodedSaltSize])\n\n\thashedSecret = hashedSecret[encodedSaltSize:]\n\tp.hash = make([]byte, len(hashedSecret))\n\tcopy(p.hash, hashedSecret)\n\n\treturn p, nil\n}\n\nfunc bcrypt(password []byte, cost int, salt []byte) ([]byte, error) {\n\tcipherData := make([]byte, len(magicCipherData))\n\tcopy(cipherData, magicCipherData)\n\n\tc, err := expensiveBlowfishSetup(password, uint32(cost), salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i := 0; i < 24; i += 8 {\n\t\tfor j := 0; j < 64; j++ {\n\t\t\tc.Encrypt(cipherData[i:i+8], cipherData[i:i+8])\n\t\t}\n\t}\n\n\t\/\/ Bug compatibility with C bcrypt implementations. We only encode 23 of\n\t\/\/ the 24 bytes encrypted.\n\thsh := base64Encode(cipherData[:maxCryptedHashSize])\n\treturn hsh, nil\n}\n\nfunc expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cipher, error) {\n\n\tcsalt, err := base64Decode(salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Bug compatibility with C bcrypt implementations. They use the trailing\n\t\/\/ NULL in the key string during expansion.\n\tckey := append(key, 0)\n\n\tc, err := blowfish.NewSaltedCipher(ckey, csalt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trounds := 1 << cost\n\tfor i := 0; i < rounds; i++ {\n\t\tblowfish.ExpandKey(ckey, c)\n\t\tblowfish.ExpandKey(csalt, c)\n\t}\n\n\treturn c, nil\n}\n\nfunc (p *hashed) Hash() []byte {\n\tarr := make([]byte, 60)\n\tarr[0] = '$'\n\tarr[1] = p.major\n\tn := 2\n\tif p.minor != 0 {\n\t\tarr[2] = p.minor\n\t\tn = 3\n\t}\n\tarr[n] = '$'\n\tn += 1\n\tcopy(arr[n:], []byte(fmt.Sprintf(\"%02d\", p.cost)))\n\tn += 2\n\tarr[n] = '$'\n\tn += 1\n\tcopy(arr[n:], p.salt)\n\tn += encodedSaltSize\n\tcopy(arr[n:], p.hash)\n\tn += encodedHashSize\n\treturn arr[:n]\n}\n\nfunc (p *hashed) decodeVersion(sbytes []byte) (int, error) {\n\tif sbytes[0] != '$' {\n\t\treturn -1, InvalidHashPrefixError(sbytes[0])\n\t}\n\tif sbytes[1] > majorVersion {\n\t\treturn -1, HashVersionTooNewError(sbytes[1])\n\t}\n\tp.major = sbytes[1]\n\tn := 3\n\tif sbytes[2] != '$' {\n\t\tp.minor = sbytes[2]\n\t\tn++\n\t}\n\treturn n, nil\n}\n\n\/\/ sbytes should begin where decodeVersion left off.\nfunc (p *hashed) decodeCost(sbytes []byte) (int, error) {\n\tcost, err := strconv.Atoi(string(sbytes[0:2]))\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\terr = checkCost(cost)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tp.cost = cost\n\treturn 3, nil\n}\n\nfunc (p *hashed) String() string {\n\treturn fmt.Sprintf(\"&{hash: %#v, salt: %#v, cost: %d, major: %c, minor: %c}\", string(p.hash), p.salt, p.cost, p.major, p.minor)\n}\n\nfunc checkCost(cost int) error {\n\tif cost < MinCost || cost > MaxCost {\n\t\treturn InvalidCostError(cost)\n\t}\n\treturn nil\n}\n<commit_msg>go.crypto\/bcrypt: fix interger overflow for cost == 31 Fixes issue 4803.<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package bcrypt implements Provos and Mazières's bcrypt adaptive hashing\n\/\/ algorithm. See http:\/\/www.usenix.org\/event\/usenix99\/provos\/provos.pdf\npackage bcrypt\n\n\/\/ The code is a port of Provos and Mazières's C implementation.\nimport (\n\t\"code.google.com\/p\/go.crypto\/blowfish\"\n\t\"crypto\/rand\"\n\t\"crypto\/subtle\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n)\n\nconst (\n\tMinCost     int = 4  \/\/ the minimum allowable cost as passed in to GenerateFromPassword\n\tMaxCost     int = 31 \/\/ the maximum allowable cost as passed in to GenerateFromPassword\n\tDefaultCost int = 10 \/\/ the cost that will actually be set if a cost below MinCost is passed into GenerateFromPassword\n)\n\n\/\/ The error returned from CompareHashAndPassword when a password and hash do\n\/\/ not match.\nvar ErrMismatchedHashAndPassword = errors.New(\"crypto\/bcrypt: hashedPassword is not the hash of the given password\")\n\n\/\/ The error returned from CompareHashAndPassword when a hash is too short to\n\/\/ be a bcrypt hash.\nvar ErrHashTooShort = errors.New(\"crypto\/bcrypt: hashedSecret too short to be a bcrypted password\")\n\n\/\/ The error returned from CompareHashAndPassword when a hash was created with\n\/\/ a bcrypt algorithm newer than this implementation.\ntype HashVersionTooNewError byte\n\nfunc (hv HashVersionTooNewError) Error() string {\n\treturn fmt.Sprintf(\"crypto\/bcrypt: bcrypt algorithm version '%c' requested is newer than current version '%c'\", byte(hv), majorVersion)\n}\n\n\/\/ The error returned from CompareHashAndPassword when a hash starts with something other than '$'\ntype InvalidHashPrefixError byte\n\nfunc (ih InvalidHashPrefixError) Error() string {\n\treturn fmt.Sprintf(\"crypto\/bcrypt: bcrypt hashes must start with '$', but hashedSecret started with '%c'\", byte(ih))\n}\n\ntype InvalidCostError int\n\nfunc (ic InvalidCostError) Error() string {\n\treturn fmt.Sprintf(\"crypto\/bcrypt: cost %d is outside allowed range (%d,%d)\", int(ic), int(MinCost), int(MaxCost))\n}\n\nconst (\n\tmajorVersion       = '2'\n\tminorVersion       = 'a'\n\tmaxSaltSize        = 16\n\tmaxCryptedHashSize = 23\n\tencodedSaltSize    = 22\n\tencodedHashSize    = 31\n\tminHashSize        = 59\n)\n\n\/\/ magicCipherData is an IV for the 64 Blowfish encryption calls in\n\/\/ bcrypt(). It's the string \"OrpheanBeholderScryDoubt\" in big-endian bytes.\nvar magicCipherData = []byte{\n\t0x4f, 0x72, 0x70, 0x68,\n\t0x65, 0x61, 0x6e, 0x42,\n\t0x65, 0x68, 0x6f, 0x6c,\n\t0x64, 0x65, 0x72, 0x53,\n\t0x63, 0x72, 0x79, 0x44,\n\t0x6f, 0x75, 0x62, 0x74,\n}\n\ntype hashed struct {\n\thash  []byte\n\tsalt  []byte\n\tcost  int \/\/ allowed range is MinCost to MaxCost\n\tmajor byte\n\tminor byte\n}\n\n\/\/ GenerateFromPassword returns the bcrypt hash of the password at the given\n\/\/ cost. If the cost given is less than MinCost, the cost will be set to\n\/\/ DefaultCost, instead. Use CompareHashAndPassword, as defined in this package,\n\/\/ to compare the returned hashed password with its cleartext version.\nfunc GenerateFromPassword(password []byte, cost int) ([]byte, error) {\n\tp, err := newFromPassword(password, cost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn p.Hash(), nil\n}\n\n\/\/ CompareHashAndPassword compares a bcrypt hashed password with its possible\n\/\/ plaintext equivalent. Returns nil on success, or an error on failure.\nfunc CompareHashAndPassword(hashedPassword, password []byte) error {\n\tp, err := newFromHash(hashedPassword)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\totherHash, err := bcrypt(password, p.cost, p.salt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\totherP := &hashed{otherHash, p.salt, p.cost, p.major, p.minor}\n\tif subtle.ConstantTimeCompare(p.Hash(), otherP.Hash()) == 1 {\n\t\treturn nil\n\t}\n\n\treturn ErrMismatchedHashAndPassword\n}\n\n\/\/ Cost returns the hashing cost used to create the given hashed\n\/\/ password. When, in the future, the hashing cost of a password system needs\n\/\/ to be increased in order to adjust for greater computational power, this\n\/\/ function allows one to establish which passwords need to be updated.\nfunc Cost(hashedPassword []byte) (int, error) {\n\tp, err := newFromHash(hashedPassword)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn p.cost, nil\n}\n\nfunc newFromPassword(password []byte, cost int) (*hashed, error) {\n\tif cost < MinCost {\n\t\tcost = DefaultCost\n\t}\n\tp := new(hashed)\n\tp.major = majorVersion\n\tp.minor = minorVersion\n\n\terr := checkCost(cost)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.cost = cost\n\n\tunencodedSalt := make([]byte, maxSaltSize)\n\t_, err = io.ReadFull(rand.Reader, unencodedSalt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp.salt = base64Encode(unencodedSalt)\n\thash, err := bcrypt(password, p.cost, p.salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.hash = hash\n\treturn p, err\n}\n\nfunc newFromHash(hashedSecret []byte) (*hashed, error) {\n\tif len(hashedSecret) < minHashSize {\n\t\treturn nil, ErrHashTooShort\n\t}\n\tp := new(hashed)\n\tn, err := p.decodeVersion(hashedSecret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thashedSecret = hashedSecret[n:]\n\tn, err = p.decodeCost(hashedSecret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thashedSecret = hashedSecret[n:]\n\n\t\/\/ The \"+2\" is here because we'll have to append at most 2 '=' to the salt\n\t\/\/ when base64 decoding it in expensiveBlowfishSetup().\n\tp.salt = make([]byte, encodedSaltSize, encodedSaltSize+2)\n\tcopy(p.salt, hashedSecret[:encodedSaltSize])\n\n\thashedSecret = hashedSecret[encodedSaltSize:]\n\tp.hash = make([]byte, len(hashedSecret))\n\tcopy(p.hash, hashedSecret)\n\n\treturn p, nil\n}\n\nfunc bcrypt(password []byte, cost int, salt []byte) ([]byte, error) {\n\tcipherData := make([]byte, len(magicCipherData))\n\tcopy(cipherData, magicCipherData)\n\n\tc, err := expensiveBlowfishSetup(password, uint32(cost), salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i := 0; i < 24; i += 8 {\n\t\tfor j := 0; j < 64; j++ {\n\t\t\tc.Encrypt(cipherData[i:i+8], cipherData[i:i+8])\n\t\t}\n\t}\n\n\t\/\/ Bug compatibility with C bcrypt implementations. We only encode 23 of\n\t\/\/ the 24 bytes encrypted.\n\thsh := base64Encode(cipherData[:maxCryptedHashSize])\n\treturn hsh, nil\n}\n\nfunc expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cipher, error) {\n\n\tcsalt, err := base64Decode(salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Bug compatibility with C bcrypt implementations. They use the trailing\n\t\/\/ NULL in the key string during expansion.\n\tckey := append(key, 0)\n\n\tc, err := blowfish.NewSaltedCipher(ckey, csalt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar i, rounds uint64\n\trounds = 1 << cost\n\tfor i = 0; i < rounds; i++ {\n\t\tblowfish.ExpandKey(ckey, c)\n\t\tblowfish.ExpandKey(csalt, c)\n\t}\n\n\treturn c, nil\n}\n\nfunc (p *hashed) Hash() []byte {\n\tarr := make([]byte, 60)\n\tarr[0] = '$'\n\tarr[1] = p.major\n\tn := 2\n\tif p.minor != 0 {\n\t\tarr[2] = p.minor\n\t\tn = 3\n\t}\n\tarr[n] = '$'\n\tn += 1\n\tcopy(arr[n:], []byte(fmt.Sprintf(\"%02d\", p.cost)))\n\tn += 2\n\tarr[n] = '$'\n\tn += 1\n\tcopy(arr[n:], p.salt)\n\tn += encodedSaltSize\n\tcopy(arr[n:], p.hash)\n\tn += encodedHashSize\n\treturn arr[:n]\n}\n\nfunc (p *hashed) decodeVersion(sbytes []byte) (int, error) {\n\tif sbytes[0] != '$' {\n\t\treturn -1, InvalidHashPrefixError(sbytes[0])\n\t}\n\tif sbytes[1] > majorVersion {\n\t\treturn -1, HashVersionTooNewError(sbytes[1])\n\t}\n\tp.major = sbytes[1]\n\tn := 3\n\tif sbytes[2] != '$' {\n\t\tp.minor = sbytes[2]\n\t\tn++\n\t}\n\treturn n, nil\n}\n\n\/\/ sbytes should begin where decodeVersion left off.\nfunc (p *hashed) decodeCost(sbytes []byte) (int, error) {\n\tcost, err := strconv.Atoi(string(sbytes[0:2]))\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\terr = checkCost(cost)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tp.cost = cost\n\treturn 3, nil\n}\n\nfunc (p *hashed) String() string {\n\treturn fmt.Sprintf(\"&{hash: %#v, salt: %#v, cost: %d, major: %c, minor: %c}\", string(p.hash), p.salt, p.cost, p.major, p.minor)\n}\n\nfunc checkCost(cost int) error {\n\tif cost < MinCost || cost > MaxCost {\n\t\treturn InvalidCostError(cost)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cluster\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/crypto\/scrypt\"\n\n\t\"github.com\/lxc\/lxd\/lxd\/config\"\n\t\"github.com\/lxc\/lxd\/lxd\/db\"\n\t\"github.com\/lxc\/lxd\/shared\/validate\"\n)\n\n\/\/ Config holds cluster-wide configuration values.\ntype Config struct {\n\ttx *db.ClusterTx \/\/ DB transaction the values in this config are bound to.\n\tm  config.Map    \/\/ Low-level map holding the config values.\n}\n\n\/\/ ConfigLoad loads a new Config object with the current cluster configuration\n\/\/ values fetched from the database.\nfunc ConfigLoad(tx *db.ClusterTx) (*Config, error) {\n\t\/\/ Load current raw values from the database, any error is fatal.\n\tvalues, err := tx.Config()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot fetch node config from database: %v\", err)\n\t}\n\n\tm, err := config.SafeLoad(ConfigSchema, values)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load node config: %v\", err)\n\t}\n\n\treturn &Config{tx: tx, m: m}, nil\n}\n\n\/\/ HTTPSAllowedHeaders returns the relevant CORS setting.\nfunc (c *Config) HTTPSAllowedHeaders() string {\n\treturn c.m.GetString(\"core.https_allowed_headers\")\n}\n\n\/\/ HTTPSAllowedMethods returns the relevant CORS setting.\nfunc (c *Config) HTTPSAllowedMethods() string {\n\treturn c.m.GetString(\"core.https_allowed_methods\")\n}\n\n\/\/ HTTPSAllowedOrigin returns the relevant CORS setting.\nfunc (c *Config) HTTPSAllowedOrigin() string {\n\treturn c.m.GetString(\"core.https_allowed_origin\")\n}\n\n\/\/ HTTPSAllowedCredentials returns the relevant CORS setting.\nfunc (c *Config) HTTPSAllowedCredentials() bool {\n\treturn c.m.GetBool(\"core.https_allowed_credentials\")\n}\n\n\/\/ TrustPassword returns the LXD trust password for authenticating clients.\nfunc (c *Config) TrustPassword() string {\n\treturn c.m.GetString(\"core.trust_password\")\n}\n\n\/\/ TrustCACertificates returns whether client certificates are checked\n\/\/ against a CA.\nfunc (c *Config) TrustCACertificates() bool {\n\treturn c.m.GetBool(\"core.trust_ca_certificates\")\n}\n\n\/\/ CandidServer returns all the Candid settings needed to connect to a server.\nfunc (c *Config) CandidServer() (string, string, int64, string) {\n\treturn c.m.GetString(\"candid.api.url\"),\n\t\tc.m.GetString(\"candid.api.key\"),\n\t\tc.m.GetInt64(\"candid.expiry\"),\n\t\tc.m.GetString(\"candid.domains\")\n}\n\n\/\/ RBACServer returns all the Candid settings needed to connect to a server.\nfunc (c *Config) RBACServer() (string, string, int64, string, string, string, string) {\n\treturn c.m.GetString(\"rbac.api.url\"),\n\t\tc.m.GetString(\"rbac.api.key\"),\n\t\tc.m.GetInt64(\"rbac.expiry\"),\n\t\tc.m.GetString(\"rbac.agent.url\"),\n\t\tc.m.GetString(\"rbac.agent.username\"),\n\t\tc.m.GetString(\"rbac.agent.private_key\"),\n\t\tc.m.GetString(\"rbac.agent.public_key\")\n}\n\n\/\/ ProxyHTTPS returns the configured HTTPS proxy, if any.\nfunc (c *Config) ProxyHTTPS() string {\n\treturn c.m.GetString(\"core.proxy_https\")\n}\n\n\/\/ ProxyHTTP returns the configured HTTP proxy, if any.\nfunc (c *Config) ProxyHTTP() string {\n\treturn c.m.GetString(\"core.proxy_http\")\n}\n\n\/\/ ProxyIgnoreHosts returns the configured ignore-hosts proxy setting, if any.\nfunc (c *Config) ProxyIgnoreHosts() string {\n\treturn c.m.GetString(\"core.proxy_ignore_hosts\")\n}\n\n\/\/ HTTPSTrustedProxy returns the configured HTTPS trusted proxy setting, if any.\nfunc (c *Config) HTTPSTrustedProxy() string {\n\treturn c.m.GetString(\"core.https_trusted_proxy\")\n}\n\n\/\/ MAASController the configured MAAS url and key, if any.\nfunc (c *Config) MAASController() (string, string) {\n\turl := c.m.GetString(\"maas.api.url\")\n\tkey := c.m.GetString(\"maas.api.key\")\n\treturn url, key\n}\n\n\/\/ OfflineThreshold returns the configured heartbeat threshold, i.e. the\n\/\/ number of seconds before after which an unresponsive node is considered\n\/\/ offline..\nfunc (c *Config) OfflineThreshold() time.Duration {\n\tn := c.m.GetInt64(\"cluster.offline_threshold\")\n\treturn time.Duration(n) * time.Second\n}\n\n\/\/ ImagesMinimalReplica returns the numbers of nodes for cluster images replication\nfunc (c *Config) ImagesMinimalReplica() int64 {\n\treturn c.m.GetInt64(\"cluster.images_minimal_replica\")\n}\n\n\/\/ MaxVoters returns the maximum number of members in a cluster that will be\n\/\/ assigned the voter role.\nfunc (c *Config) MaxVoters() int64 {\n\treturn c.m.GetInt64(\"cluster.max_voters\")\n}\n\n\/\/ MaxStandBy returns the maximum number of standby members in a cluster that\n\/\/ will be assigned the stand-by role.\nfunc (c *Config) MaxStandBy() int64 {\n\treturn c.m.GetInt64(\"cluster.max_standby\")\n}\n\n\/\/ ShutdownTimeout returns the number of minutes to wait for running operation to complete\n\/\/ before LXD server shut down\nfunc (c *Config) ShutdownTimeout() time.Duration {\n\tn := c.m.GetInt64(\"core.shutdown_timeout\")\n\treturn time.Duration(n) * time.Minute\n}\n\n\/\/ Dump current configuration keys and their values. Keys with values matching\n\/\/ their defaults are omitted.\nfunc (c *Config) Dump() map[string]interface{} {\n\treturn c.m.Dump()\n}\n\n\/\/ Replace the current configuration with the given values.\n\/\/\n\/\/ Return what has actually changed.\nfunc (c *Config) Replace(values map[string]interface{}) (map[string]string, error) {\n\treturn c.update(values)\n}\n\n\/\/ Patch changes only the configuration keys in the given map.\n\/\/\n\/\/ Return what has actually changed.\nfunc (c *Config) Patch(patch map[string]interface{}) (map[string]string, error) {\n\tvalues := c.Dump() \/\/ Use current values as defaults\n\tfor name, value := range patch {\n\t\tvalues[name] = value\n\t}\n\treturn c.update(values)\n}\n\nfunc (c *Config) update(values map[string]interface{}) (map[string]string, error) {\n\tchanged, err := c.m.Change(values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = c.tx.UpdateConfig(changed)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"cannot persist configuration changes: %v\")\n\t}\n\n\treturn changed, nil\n}\n\n\/\/ ConfigGetString is a convenience for loading the cluster configuration and\n\/\/ returning the value of a particular key.\n\/\/\n\/\/ It's a deprecated API meant to be used by call sites that are not\n\/\/ interacting with the database in a transactional way.\nfunc ConfigGetString(cluster *db.Cluster, key string) (string, error) {\n\tconfig, err := configGet(cluster)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn config.m.GetString(key), nil\n}\n\n\/\/ ConfigGetBool is a convenience for loading the cluster configuration and\n\/\/ returning the value of a particular boolean key.\n\/\/\n\/\/ It's a deprecated API meant to be used by call sites that are not\n\/\/ interacting with the database in a transactional way.\nfunc ConfigGetBool(cluster *db.Cluster, key string) (bool, error) {\n\tconfig, err := configGet(cluster)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn config.m.GetBool(key), nil\n}\n\n\/\/ ConfigGetInt64 is a convenience for loading the cluster configuration and\n\/\/ returning the value of a particular key.\n\/\/\n\/\/ It's a deprecated API meant to be used by call sites that are not\n\/\/ interacting with the database in a transactional way.\nfunc ConfigGetInt64(cluster *db.Cluster, key string) (int64, error) {\n\tconfig, err := configGet(cluster)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn config.m.GetInt64(key), nil\n}\n\nfunc configGet(cluster *db.Cluster) (*Config, error) {\n\tvar config *Config\n\terr := cluster.Transaction(func(tx *db.ClusterTx) error {\n\t\tvar err error\n\t\tconfig, err = ConfigLoad(tx)\n\t\treturn err\n\t})\n\treturn config, err\n}\n\n\/\/ ConfigSchema defines available server configuration keys.\nvar ConfigSchema = config.Schema{\n\t\"backups.compression_algorithm\":  {Default: \"gzip\", Validator: validate.IsCompressionAlgorithm},\n\t\"cluster.offline_threshold\":      {Type: config.Int64, Default: offlineThresholdDefault(), Validator: offlineThresholdValidator},\n\t\"cluster.images_minimal_replica\": {Type: config.Int64, Default: \"3\", Validator: imageMinimalReplicaValidator},\n\t\"cluster.max_voters\":             {Type: config.Int64, Default: \"3\", Validator: maxVotersValidator},\n\t\"cluster.max_standby\":            {Type: config.Int64, Default: \"2\", Validator: maxStandByValidator},\n\t\"core.https_allowed_headers\":     {},\n\t\"core.https_allowed_methods\":     {},\n\t\"core.https_allowed_origin\":      {},\n\t\"core.https_allowed_credentials\": {Type: config.Bool},\n\t\"core.https_trusted_proxy\":       {},\n\t\"core.proxy_http\":                {},\n\t\"core.proxy_https\":               {},\n\t\"core.proxy_ignore_hosts\":        {},\n\t\"core.shutdown_timeout\":          {Type: config.Int64, Default: \"5\"},\n\t\"core.trust_password\":            {Hidden: true, Setter: passwordSetter},\n\t\"core.trust_ca_certificates\":     {Type: config.Bool},\n\t\"candid.api.key\":                 {},\n\t\"candid.api.url\":                 {},\n\t\"candid.domains\":                 {},\n\t\"candid.expiry\":                  {Type: config.Int64, Default: \"3600\"},\n\t\"images.auto_update_cached\":      {Type: config.Bool, Default: \"true\"},\n\t\"images.auto_update_interval\":    {Type: config.Int64, Default: \"6\"},\n\t\"images.compression_algorithm\":   {Default: \"gzip\", Validator: validate.IsCompressionAlgorithm},\n\t\"images.default_architecture\":    {Validator: validate.IsArchitecture},\n\t\"images.remote_cache_expiry\":     {Type: config.Int64, Default: \"10\"},\n\t\"maas.api.key\":                   {},\n\t\"maas.api.url\":                   {},\n\t\"rbac.agent.url\":                 {},\n\t\"rbac.agent.username\":            {},\n\t\"rbac.agent.private_key\":         {},\n\t\"rbac.agent.public_key\":          {},\n\t\"rbac.api.expiry\":                {Type: config.Int64, Default: \"3600\"},\n\t\"rbac.api.key\":                   {},\n\t\"rbac.api.url\":                   {},\n\t\"rbac.expiry\":                    {Type: config.Int64, Default: \"3600\"},\n\n\t\/\/ Keys deprecated since the implementation of the storage api.\n\t\"storage.lvm_fstype\":           {Setter: deprecatedStorage, Default: \"ext4\"},\n\t\"storage.lvm_mount_options\":    {Setter: deprecatedStorage, Default: \"discard\"},\n\t\"storage.lvm_thinpool_name\":    {Setter: deprecatedStorage, Default: \"LXDThinPool\"},\n\t\"storage.lvm_vg_name\":          {Setter: deprecatedStorage},\n\t\"storage.lvm_volume_size\":      {Setter: deprecatedStorage, Default: \"10GiB\"},\n\t\"storage.zfs_pool_name\":        {Setter: deprecatedStorage},\n\t\"storage.zfs_remove_snapshots\": {Setter: deprecatedStorage, Type: config.Bool},\n\t\"storage.zfs_use_refquota\":     {Setter: deprecatedStorage, Type: config.Bool},\n\n\t\/\/ OVN networking global keys.\n\t\"network.ovn.integration_bridge\":    {Default: \"br-int\"},\n\t\"network.ovn.northbound_connection\": {Default: \"unix:\/var\/run\/ovn\/ovnnb_db.sock\"},\n}\n\nfunc offlineThresholdDefault() string {\n\treturn strconv.Itoa(db.DefaultOfflineThreshold)\n}\n\nfunc offlineThresholdValidator(value string) error {\n\tminThreshold := 10\n\n\t\/\/ Ensure that the given value is greater than the heartbeat interval,\n\t\/\/ which is the lower bound granularity of the offline check.\n\tthreshold, err := strconv.Atoi(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Offline threshold is not a number\")\n\t}\n\n\tif threshold <= minThreshold {\n\t\treturn fmt.Errorf(\"Value must be greater than '%d'\", minThreshold)\n\t}\n\n\treturn nil\n}\n\nfunc imageMinimalReplicaValidator(value string) error {\n\tcount, err := strconv.Atoi(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Minimal image replica count is not a number\")\n\t}\n\n\tif count < 1 && count != -1 {\n\t\treturn fmt.Errorf(\"Invalid value for image replica count\")\n\t}\n\n\treturn nil\n}\n\nfunc maxVotersValidator(value string) error {\n\tn, err := strconv.Atoi(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Value is not a number\")\n\t}\n\n\tif n < 3 || n%2 != 1 {\n\t\treturn fmt.Errorf(\"Value must be an odd number equal to or higher than 3\")\n\t}\n\n\treturn nil\n}\n\nfunc maxStandByValidator(value string) error {\n\tn, err := strconv.Atoi(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Value is not a number\")\n\t}\n\n\tif n < 0 || n > 5 {\n\t\treturn fmt.Errorf(\"Value must be between 0 and 5\")\n\t}\n\n\treturn nil\n}\n\nfunc passwordSetter(value string) (string, error) {\n\t\/\/ Nothing to do on unset\n\tif value == \"\" {\n\t\treturn value, nil\n\t}\n\n\t\/\/ Hash the password\n\tbuf := make([]byte, 32)\n\t_, err := io.ReadFull(rand.Reader, buf)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thash, err := scrypt.Key([]byte(value), buf, 1<<14, 8, 1, 64)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tbuf = append(buf, hash...)\n\tvalue = hex.EncodeToString(buf)\n\n\treturn value, nil\n}\n\nfunc deprecatedStorage(value string) (string, error) {\n\tif value == \"\" {\n\t\treturn \"\", nil\n\t}\n\treturn \"\", fmt.Errorf(\"deprecated: use storage pool configuration\")\n}\n<commit_msg>lxd\/cluster\/config: Wraps images.default_architecture with validate.Optional due to IsOneOf change in IsArchitecture<commit_after>package cluster\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/crypto\/scrypt\"\n\n\t\"github.com\/lxc\/lxd\/lxd\/config\"\n\t\"github.com\/lxc\/lxd\/lxd\/db\"\n\t\"github.com\/lxc\/lxd\/shared\/validate\"\n)\n\n\/\/ Config holds cluster-wide configuration values.\ntype Config struct {\n\ttx *db.ClusterTx \/\/ DB transaction the values in this config are bound to.\n\tm  config.Map    \/\/ Low-level map holding the config values.\n}\n\n\/\/ ConfigLoad loads a new Config object with the current cluster configuration\n\/\/ values fetched from the database.\nfunc ConfigLoad(tx *db.ClusterTx) (*Config, error) {\n\t\/\/ Load current raw values from the database, any error is fatal.\n\tvalues, err := tx.Config()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot fetch node config from database: %v\", err)\n\t}\n\n\tm, err := config.SafeLoad(ConfigSchema, values)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load node config: %v\", err)\n\t}\n\n\treturn &Config{tx: tx, m: m}, nil\n}\n\n\/\/ HTTPSAllowedHeaders returns the relevant CORS setting.\nfunc (c *Config) HTTPSAllowedHeaders() string {\n\treturn c.m.GetString(\"core.https_allowed_headers\")\n}\n\n\/\/ HTTPSAllowedMethods returns the relevant CORS setting.\nfunc (c *Config) HTTPSAllowedMethods() string {\n\treturn c.m.GetString(\"core.https_allowed_methods\")\n}\n\n\/\/ HTTPSAllowedOrigin returns the relevant CORS setting.\nfunc (c *Config) HTTPSAllowedOrigin() string {\n\treturn c.m.GetString(\"core.https_allowed_origin\")\n}\n\n\/\/ HTTPSAllowedCredentials returns the relevant CORS setting.\nfunc (c *Config) HTTPSAllowedCredentials() bool {\n\treturn c.m.GetBool(\"core.https_allowed_credentials\")\n}\n\n\/\/ TrustPassword returns the LXD trust password for authenticating clients.\nfunc (c *Config) TrustPassword() string {\n\treturn c.m.GetString(\"core.trust_password\")\n}\n\n\/\/ TrustCACertificates returns whether client certificates are checked\n\/\/ against a CA.\nfunc (c *Config) TrustCACertificates() bool {\n\treturn c.m.GetBool(\"core.trust_ca_certificates\")\n}\n\n\/\/ CandidServer returns all the Candid settings needed to connect to a server.\nfunc (c *Config) CandidServer() (string, string, int64, string) {\n\treturn c.m.GetString(\"candid.api.url\"),\n\t\tc.m.GetString(\"candid.api.key\"),\n\t\tc.m.GetInt64(\"candid.expiry\"),\n\t\tc.m.GetString(\"candid.domains\")\n}\n\n\/\/ RBACServer returns all the Candid settings needed to connect to a server.\nfunc (c *Config) RBACServer() (string, string, int64, string, string, string, string) {\n\treturn c.m.GetString(\"rbac.api.url\"),\n\t\tc.m.GetString(\"rbac.api.key\"),\n\t\tc.m.GetInt64(\"rbac.expiry\"),\n\t\tc.m.GetString(\"rbac.agent.url\"),\n\t\tc.m.GetString(\"rbac.agent.username\"),\n\t\tc.m.GetString(\"rbac.agent.private_key\"),\n\t\tc.m.GetString(\"rbac.agent.public_key\")\n}\n\n\/\/ ProxyHTTPS returns the configured HTTPS proxy, if any.\nfunc (c *Config) ProxyHTTPS() string {\n\treturn c.m.GetString(\"core.proxy_https\")\n}\n\n\/\/ ProxyHTTP returns the configured HTTP proxy, if any.\nfunc (c *Config) ProxyHTTP() string {\n\treturn c.m.GetString(\"core.proxy_http\")\n}\n\n\/\/ ProxyIgnoreHosts returns the configured ignore-hosts proxy setting, if any.\nfunc (c *Config) ProxyIgnoreHosts() string {\n\treturn c.m.GetString(\"core.proxy_ignore_hosts\")\n}\n\n\/\/ HTTPSTrustedProxy returns the configured HTTPS trusted proxy setting, if any.\nfunc (c *Config) HTTPSTrustedProxy() string {\n\treturn c.m.GetString(\"core.https_trusted_proxy\")\n}\n\n\/\/ MAASController the configured MAAS url and key, if any.\nfunc (c *Config) MAASController() (string, string) {\n\turl := c.m.GetString(\"maas.api.url\")\n\tkey := c.m.GetString(\"maas.api.key\")\n\treturn url, key\n}\n\n\/\/ OfflineThreshold returns the configured heartbeat threshold, i.e. the\n\/\/ number of seconds before after which an unresponsive node is considered\n\/\/ offline..\nfunc (c *Config) OfflineThreshold() time.Duration {\n\tn := c.m.GetInt64(\"cluster.offline_threshold\")\n\treturn time.Duration(n) * time.Second\n}\n\n\/\/ ImagesMinimalReplica returns the numbers of nodes for cluster images replication\nfunc (c *Config) ImagesMinimalReplica() int64 {\n\treturn c.m.GetInt64(\"cluster.images_minimal_replica\")\n}\n\n\/\/ MaxVoters returns the maximum number of members in a cluster that will be\n\/\/ assigned the voter role.\nfunc (c *Config) MaxVoters() int64 {\n\treturn c.m.GetInt64(\"cluster.max_voters\")\n}\n\n\/\/ MaxStandBy returns the maximum number of standby members in a cluster that\n\/\/ will be assigned the stand-by role.\nfunc (c *Config) MaxStandBy() int64 {\n\treturn c.m.GetInt64(\"cluster.max_standby\")\n}\n\n\/\/ ShutdownTimeout returns the number of minutes to wait for running operation to complete\n\/\/ before LXD server shut down\nfunc (c *Config) ShutdownTimeout() time.Duration {\n\tn := c.m.GetInt64(\"core.shutdown_timeout\")\n\treturn time.Duration(n) * time.Minute\n}\n\n\/\/ Dump current configuration keys and their values. Keys with values matching\n\/\/ their defaults are omitted.\nfunc (c *Config) Dump() map[string]interface{} {\n\treturn c.m.Dump()\n}\n\n\/\/ Replace the current configuration with the given values.\n\/\/\n\/\/ Return what has actually changed.\nfunc (c *Config) Replace(values map[string]interface{}) (map[string]string, error) {\n\treturn c.update(values)\n}\n\n\/\/ Patch changes only the configuration keys in the given map.\n\/\/\n\/\/ Return what has actually changed.\nfunc (c *Config) Patch(patch map[string]interface{}) (map[string]string, error) {\n\tvalues := c.Dump() \/\/ Use current values as defaults\n\tfor name, value := range patch {\n\t\tvalues[name] = value\n\t}\n\treturn c.update(values)\n}\n\nfunc (c *Config) update(values map[string]interface{}) (map[string]string, error) {\n\tchanged, err := c.m.Change(values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = c.tx.UpdateConfig(changed)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"cannot persist configuration changes: %v\")\n\t}\n\n\treturn changed, nil\n}\n\n\/\/ ConfigGetString is a convenience for loading the cluster configuration and\n\/\/ returning the value of a particular key.\n\/\/\n\/\/ It's a deprecated API meant to be used by call sites that are not\n\/\/ interacting with the database in a transactional way.\nfunc ConfigGetString(cluster *db.Cluster, key string) (string, error) {\n\tconfig, err := configGet(cluster)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn config.m.GetString(key), nil\n}\n\n\/\/ ConfigGetBool is a convenience for loading the cluster configuration and\n\/\/ returning the value of a particular boolean key.\n\/\/\n\/\/ It's a deprecated API meant to be used by call sites that are not\n\/\/ interacting with the database in a transactional way.\nfunc ConfigGetBool(cluster *db.Cluster, key string) (bool, error) {\n\tconfig, err := configGet(cluster)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn config.m.GetBool(key), nil\n}\n\n\/\/ ConfigGetInt64 is a convenience for loading the cluster configuration and\n\/\/ returning the value of a particular key.\n\/\/\n\/\/ It's a deprecated API meant to be used by call sites that are not\n\/\/ interacting with the database in a transactional way.\nfunc ConfigGetInt64(cluster *db.Cluster, key string) (int64, error) {\n\tconfig, err := configGet(cluster)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn config.m.GetInt64(key), nil\n}\n\nfunc configGet(cluster *db.Cluster) (*Config, error) {\n\tvar config *Config\n\terr := cluster.Transaction(func(tx *db.ClusterTx) error {\n\t\tvar err error\n\t\tconfig, err = ConfigLoad(tx)\n\t\treturn err\n\t})\n\treturn config, err\n}\n\n\/\/ ConfigSchema defines available server configuration keys.\nvar ConfigSchema = config.Schema{\n\t\"backups.compression_algorithm\":  {Default: \"gzip\", Validator: validate.IsCompressionAlgorithm},\n\t\"cluster.offline_threshold\":      {Type: config.Int64, Default: offlineThresholdDefault(), Validator: offlineThresholdValidator},\n\t\"cluster.images_minimal_replica\": {Type: config.Int64, Default: \"3\", Validator: imageMinimalReplicaValidator},\n\t\"cluster.max_voters\":             {Type: config.Int64, Default: \"3\", Validator: maxVotersValidator},\n\t\"cluster.max_standby\":            {Type: config.Int64, Default: \"2\", Validator: maxStandByValidator},\n\t\"core.https_allowed_headers\":     {},\n\t\"core.https_allowed_methods\":     {},\n\t\"core.https_allowed_origin\":      {},\n\t\"core.https_allowed_credentials\": {Type: config.Bool},\n\t\"core.https_trusted_proxy\":       {},\n\t\"core.proxy_http\":                {},\n\t\"core.proxy_https\":               {},\n\t\"core.proxy_ignore_hosts\":        {},\n\t\"core.shutdown_timeout\":          {Type: config.Int64, Default: \"5\"},\n\t\"core.trust_password\":            {Hidden: true, Setter: passwordSetter},\n\t\"core.trust_ca_certificates\":     {Type: config.Bool},\n\t\"candid.api.key\":                 {},\n\t\"candid.api.url\":                 {},\n\t\"candid.domains\":                 {},\n\t\"candid.expiry\":                  {Type: config.Int64, Default: \"3600\"},\n\t\"images.auto_update_cached\":      {Type: config.Bool, Default: \"true\"},\n\t\"images.auto_update_interval\":    {Type: config.Int64, Default: \"6\"},\n\t\"images.compression_algorithm\":   {Default: \"gzip\", Validator: validate.IsCompressionAlgorithm},\n\t\"images.default_architecture\":    {Validator: validate.Optional(validate.IsArchitecture)},\n\t\"images.remote_cache_expiry\":     {Type: config.Int64, Default: \"10\"},\n\t\"maas.api.key\":                   {},\n\t\"maas.api.url\":                   {},\n\t\"rbac.agent.url\":                 {},\n\t\"rbac.agent.username\":            {},\n\t\"rbac.agent.private_key\":         {},\n\t\"rbac.agent.public_key\":          {},\n\t\"rbac.api.expiry\":                {Type: config.Int64, Default: \"3600\"},\n\t\"rbac.api.key\":                   {},\n\t\"rbac.api.url\":                   {},\n\t\"rbac.expiry\":                    {Type: config.Int64, Default: \"3600\"},\n\n\t\/\/ Keys deprecated since the implementation of the storage api.\n\t\"storage.lvm_fstype\":           {Setter: deprecatedStorage, Default: \"ext4\"},\n\t\"storage.lvm_mount_options\":    {Setter: deprecatedStorage, Default: \"discard\"},\n\t\"storage.lvm_thinpool_name\":    {Setter: deprecatedStorage, Default: \"LXDThinPool\"},\n\t\"storage.lvm_vg_name\":          {Setter: deprecatedStorage},\n\t\"storage.lvm_volume_size\":      {Setter: deprecatedStorage, Default: \"10GiB\"},\n\t\"storage.zfs_pool_name\":        {Setter: deprecatedStorage},\n\t\"storage.zfs_remove_snapshots\": {Setter: deprecatedStorage, Type: config.Bool},\n\t\"storage.zfs_use_refquota\":     {Setter: deprecatedStorage, Type: config.Bool},\n\n\t\/\/ OVN networking global keys.\n\t\"network.ovn.integration_bridge\":    {Default: \"br-int\"},\n\t\"network.ovn.northbound_connection\": {Default: \"unix:\/var\/run\/ovn\/ovnnb_db.sock\"},\n}\n\nfunc offlineThresholdDefault() string {\n\treturn strconv.Itoa(db.DefaultOfflineThreshold)\n}\n\nfunc offlineThresholdValidator(value string) error {\n\tminThreshold := 10\n\n\t\/\/ Ensure that the given value is greater than the heartbeat interval,\n\t\/\/ which is the lower bound granularity of the offline check.\n\tthreshold, err := strconv.Atoi(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Offline threshold is not a number\")\n\t}\n\n\tif threshold <= minThreshold {\n\t\treturn fmt.Errorf(\"Value must be greater than '%d'\", minThreshold)\n\t}\n\n\treturn nil\n}\n\nfunc imageMinimalReplicaValidator(value string) error {\n\tcount, err := strconv.Atoi(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Minimal image replica count is not a number\")\n\t}\n\n\tif count < 1 && count != -1 {\n\t\treturn fmt.Errorf(\"Invalid value for image replica count\")\n\t}\n\n\treturn nil\n}\n\nfunc maxVotersValidator(value string) error {\n\tn, err := strconv.Atoi(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Value is not a number\")\n\t}\n\n\tif n < 3 || n%2 != 1 {\n\t\treturn fmt.Errorf(\"Value must be an odd number equal to or higher than 3\")\n\t}\n\n\treturn nil\n}\n\nfunc maxStandByValidator(value string) error {\n\tn, err := strconv.Atoi(value)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Value is not a number\")\n\t}\n\n\tif n < 0 || n > 5 {\n\t\treturn fmt.Errorf(\"Value must be between 0 and 5\")\n\t}\n\n\treturn nil\n}\n\nfunc passwordSetter(value string) (string, error) {\n\t\/\/ Nothing to do on unset\n\tif value == \"\" {\n\t\treturn value, nil\n\t}\n\n\t\/\/ Hash the password\n\tbuf := make([]byte, 32)\n\t_, err := io.ReadFull(rand.Reader, buf)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thash, err := scrypt.Key([]byte(value), buf, 1<<14, 8, 1, 64)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tbuf = append(buf, hash...)\n\tvalue = hex.EncodeToString(buf)\n\n\treturn value, nil\n}\n\nfunc deprecatedStorage(value string) (string, error) {\n\tif value == \"\" {\n\t\treturn \"\", nil\n\t}\n\treturn \"\", fmt.Errorf(\"deprecated: use storage pool configuration\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package cluster\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\tlog \"gopkg.in\/inconshreveable\/log15.v2\"\n\n\t\"github.com\/lxc\/lxd\/client\"\n\t\"github.com\/lxc\/lxd\/lxd\/db\"\n\t\"github.com\/lxc\/lxd\/lxd\/endpoints\"\n\t\"github.com\/lxc\/lxd\/lxd\/revert\"\n\t\"github.com\/lxc\/lxd\/shared\"\n\t\"github.com\/lxc\/lxd\/shared\/api\"\n\t\"github.com\/lxc\/lxd\/shared\/logger\"\n)\n\n\/\/ eventHubMinHosts is the minimum number of members that must have the event-hub role to trigger switching into\n\/\/ event-hub mode (where cluster members will only connect to event-hub members rather than all members when\n\/\/ operating in the normal full-mesh mode).\nconst eventHubMinHosts = 2\n\n\/\/ EventMode indicates the event distribution mode.\ntype EventMode string\n\n\/\/ EventModeFullMesh is when every cluster member connects to every other cluster member to pull events.\nconst EventModeFullMesh EventMode = \"full-mesh\"\n\n\/\/ EventModeHubServer is when the cluster is operating in event-hub mode and this server is designated as a hub\n\/\/ server, meaning that it will only connect to the other event-hub members and not other members.\nconst EventModeHubServer EventMode = \"hub-server\"\n\n\/\/ EventModeHubClient is when the cluster is operating in event-hub mode and this member is designated as a hub\n\/\/ client, meaning that it is expected to connect to the event-hub members.\nconst EventModeHubClient EventMode = \"hub-client\"\n\nvar listeners = map[string]*lxd.EventListener{}\nvar listenersNotify = map[chan struct{}][]string{}\nvar listenersLock sync.Mutex\nvar listenersUpdateLock sync.Mutex\n\n\/\/ ServerEventMode returns the event distribution mode that this local server is operating in.\nfunc ServerEventMode() EventMode {\n\tlistenersLock.Lock()\n\tdefer listenersLock.Unlock()\n\n\treturn eventMode\n}\n\n\/\/ RoleInSlice returns whether or not the rule is within the roles list.\nfunc RoleInSlice(role db.ClusterRole, roles []db.ClusterRole) bool {\n\tfor _, r := range roles {\n\t\tif r == role {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ EventListenerWait waits for there to be listener connected to the specified address, or one of the event hubs\n\/\/ if operating in event hub mode.\nfunc EventListenerWait(ctx context.Context, address string) error {\n\t\/\/ Check if there is already a listener.\n\tlistenersLock.Lock()\n\tlistener, found := listeners[address]\n\tif found && listener.IsActive() {\n\t\tlistenersLock.Unlock()\n\t\treturn nil\n\t}\n\n\tlistenAddresses := []string{address}\n\n\t\/\/ If not setup a notification for when the desired address or any of the event hubs connect.\n\tconnected := make(chan struct{})\n\tlistenersNotify[connected] = listenAddresses\n\tlistenersLock.Unlock()\n\n\tdefer func() {\n\t\tlistenersLock.Lock()\n\t\tdelete(listenersNotify, connected)\n\t\tlistenersLock.Unlock()\n\t}()\n\n\t\/\/ Wait for the connected channel to be closed (indicating a new listener has been connected), and return.\n\tselect {\n\tcase <-connected:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}\n\n\/\/ EventsUpdateListeners refreshes the cluster event listener connections.\nfunc EventsUpdateListeners(endpoints *endpoints.Endpoints, cluster *db.Cluster, serverCert func() *shared.CertInfo, members map[int64]APIHeartbeatMember, f func(int64, api.Event)) {\n\tlistenersUpdateLock.Lock()\n\tdefer listenersUpdateLock.Unlock()\n\n\t\/\/ If no heartbeat members provided, populate from global database.\n\tif members == nil {\n\t\tvar dbMembers []db.NodeInfo\n\t\tvar offlineThreshold time.Duration\n\n\t\terr := cluster.Transaction(func(tx *db.ClusterTx) error {\n\t\t\tvar err error\n\n\t\t\tdbMembers, err = tx.GetNodes()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tofflineThreshold, err = tx.GetNodeOfflineThreshold()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tlogger.Warn(\"Failed to get current cluster members\", log.Ctx{\"err\": err})\n\t\t\treturn\n\t\t}\n\n\t\tmembers = make(map[int64]APIHeartbeatMember, len(dbMembers))\n\t\tfor _, dbMember := range dbMembers {\n\t\t\tmembers[dbMember.ID] = APIHeartbeatMember{\n\t\t\t\tID:            dbMember.ID,\n\t\t\t\tName:          dbMember.Name,\n\t\t\t\tAddress:       dbMember.Address,\n\t\t\t\tLastHeartbeat: dbMember.Heartbeat,\n\t\t\t\tOnline:        !dbMember.IsOffline(offlineThreshold),\n\t\t\t\tRoles:         dbMember.Roles,\n\t\t\t}\n\t\t}\n\t}\n\n\tnetworkAddress := endpoints.NetworkAddress()\n\n\tkeepListeners := make(map[string]struct{})\n\twg := sync.WaitGroup{}\n\tfor _, member := range members {\n\t\t\/\/ Don't bother trying to connect to ourselves or offline members.\n\t\tif member.Address == networkAddress || !member.Online {\n\t\t\tcontinue\n\t\t}\n\n\t\tlistenersLock.Lock()\n\t\tlistener, ok := listeners[member.Address]\n\n\t\t\/\/ If the member already has a listener associated to it, check that the listener is still active.\n\t\t\/\/ If it is, just move on to next member, but if not then we'll try to connect again.\n\t\tif ok {\n\t\t\tif listener.IsActive() {\n\t\t\t\tkeepListeners[member.Address] = struct{}{} \/\/ Add to current listeners list.\n\t\t\t\tlistenersLock.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ Disconnect and delete listener, but don't delete any listenersNotify entry as there\n\t\t\t\/\/ might be something waiting for a future connection.\n\t\t\tlistener.Disconnect()\n\t\t\tdelete(listeners, member.Address)\n\t\t\tlogger.Info(\"Removed inactive member event listener client\", log.Ctx{\"local\": networkAddress, \"remote\": member.Address})\n\t\t}\n\t\tlistenersLock.Unlock()\n\n\t\tkeepListeners[member.Address] = struct{}{} \/\/ Add to current listeners list.\n\n\t\t\/\/ Connect to remote concurrently and add to active listeners if successful.\n\t\twg.Add(1)\n\t\tgo func(m APIHeartbeatMember) {\n\t\t\tdefer wg.Done()\n\t\t\tlistener, err := eventsConnect(m.Address, endpoints.NetworkCert(), serverCert())\n\t\t\tif err != nil {\n\t\t\t\tlogger.Warn(\"Failed adding member event listener client\", log.Ctx{\"local\": networkAddress, \"remote\": m.Address, \"err\": err})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlistener.AddHandler(nil, func(event api.Event) { f(m.ID, event) })\n\n\t\t\tlistenersLock.Lock()\n\t\t\tlisteners[m.Address] = listener\n\n\t\t\t\/\/ Indicate to any notifiers waiting for this member's address that it is connected.\n\t\t\tfor connected, notifyAddresses := range listenersNotify {\n\t\t\t\tif shared.StringInSlice(m.Address, notifyAddresses) {\n\t\t\t\t\tclose(connected)\n\t\t\t\t\tdelete(listenersNotify, connected)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlogger.Info(\"Added member event listener client\", log.Ctx{\"local\": networkAddress, \"remote\": m.Address})\n\t\t\tlistenersLock.Unlock()\n\t\t}(member)\n\t}\n\n\twg.Wait()\n\n\t\/\/ Disconnect and delete any out of date listeners and their notifiers.\n\tlistenersLock.Lock()\n\tfor address, listener := range listeners {\n\t\tif _, found := keepListeners[address]; !found {\n\t\t\tlistener.Disconnect()\n\t\t\tdelete(listeners, address)\n\t\t\tlogger.Info(\"Removed old member event listener client\", log.Ctx{\"local\": networkAddress, \"remote\": address})\n\t\t}\n\t}\n\tlistenersLock.Unlock()\n}\n\n\/\/ Establish a client connection to get events from the given node.\nfunc eventsConnect(address string, networkCert *shared.CertInfo, serverCert *shared.CertInfo) (*lxd.EventListener, error) {\n\tclient, err := Connect(address, networkCert, serverCert, nil, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trevert := revert.New()\n\trevert.Add(func() {\n\t\tclient.Disconnect()\n\t})\n\n\tlistener, err := client.GetEventsAllProjects()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trevert.Success()\n\treturn listener, nil\n}\n<commit_msg>lxd\/cluster\/events: Updates EventsUpdateListeners to only connect to event-hub servers<commit_after>package cluster\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\tlog \"gopkg.in\/inconshreveable\/log15.v2\"\n\n\t\"github.com\/lxc\/lxd\/client\"\n\t\"github.com\/lxc\/lxd\/lxd\/db\"\n\t\"github.com\/lxc\/lxd\/lxd\/endpoints\"\n\t\"github.com\/lxc\/lxd\/lxd\/revert\"\n\t\"github.com\/lxc\/lxd\/shared\"\n\t\"github.com\/lxc\/lxd\/shared\/api\"\n\t\"github.com\/lxc\/lxd\/shared\/logger\"\n)\n\n\/\/ eventHubMinHosts is the minimum number of members that must have the event-hub role to trigger switching into\n\/\/ event-hub mode (where cluster members will only connect to event-hub members rather than all members when\n\/\/ operating in the normal full-mesh mode).\nconst eventHubMinHosts = 2\n\n\/\/ EventMode indicates the event distribution mode.\ntype EventMode string\n\n\/\/ EventModeFullMesh is when every cluster member connects to every other cluster member to pull events.\nconst EventModeFullMesh EventMode = \"full-mesh\"\n\n\/\/ EventModeHubServer is when the cluster is operating in event-hub mode and this server is designated as a hub\n\/\/ server, meaning that it will only connect to the other event-hub members and not other members.\nconst EventModeHubServer EventMode = \"hub-server\"\n\n\/\/ EventModeHubClient is when the cluster is operating in event-hub mode and this member is designated as a hub\n\/\/ client, meaning that it is expected to connect to the event-hub members.\nconst EventModeHubClient EventMode = \"hub-client\"\n\nvar eventMode EventMode = EventModeFullMesh\nvar eventHubAddresses []string\nvar listeners = map[string]*lxd.EventListener{}\nvar listenersNotify = map[chan struct{}][]string{}\nvar listenersLock sync.Mutex\nvar listenersUpdateLock sync.Mutex\n\n\/\/ ServerEventMode returns the event distribution mode that this local server is operating in.\nfunc ServerEventMode() EventMode {\n\tlistenersLock.Lock()\n\tdefer listenersLock.Unlock()\n\n\treturn eventMode\n}\n\n\/\/ RoleInSlice returns whether or not the rule is within the roles list.\nfunc RoleInSlice(role db.ClusterRole, roles []db.ClusterRole) bool {\n\tfor _, r := range roles {\n\t\tif r == role {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ EventListenerWait waits for there to be listener connected to the specified address, or one of the event hubs\n\/\/ if operating in event hub mode.\nfunc EventListenerWait(ctx context.Context, address string) error {\n\t\/\/ Check if there is already a listener.\n\tlistenersLock.Lock()\n\tlistener, found := listeners[address]\n\tif found && listener.IsActive() {\n\t\tlistenersLock.Unlock()\n\t\treturn nil\n\t}\n\n\tlistenAddresses := []string{address}\n\n\t\/\/ If not setup a notification for when the desired address or any of the event hubs connect.\n\tconnected := make(chan struct{})\n\tlistenersNotify[connected] = listenAddresses\n\tlistenersLock.Unlock()\n\n\tdefer func() {\n\t\tlistenersLock.Lock()\n\t\tdelete(listenersNotify, connected)\n\t\tlistenersLock.Unlock()\n\t}()\n\n\t\/\/ Wait for the connected channel to be closed (indicating a new listener has been connected), and return.\n\tselect {\n\tcase <-connected:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}\n\n\/\/ hubAddresses returns the addresses of members with event-hub role, and the event mode of the server.\n\/\/ The event mode will only be hub-server or hub-client if at least eventHubMinHosts have an event-hub role.\n\/\/ Otherwise the mode will be full-mesh.\nfunc hubAddresses(localAddress string, members map[int64]APIHeartbeatMember) ([]string, EventMode) {\n\tvar hubAddresses []string\n\tvar localHasHubRole bool\n\n\t\/\/ Do a first pass of members to count the members with event-hub role, and whether we are a hub server.\n\tfor _, member := range members {\n\t\tif RoleInSlice(db.ClusterRoleEventHub, member.Roles) {\n\t\t\thubAddresses = append(hubAddresses, member.Address)\n\n\t\t\tif member.Address == localAddress {\n\t\t\t\tlocalHasHubRole = true\n\t\t\t}\n\t\t}\n\t}\n\n\teventMode := EventModeFullMesh\n\tif len(hubAddresses) >= eventHubMinHosts {\n\t\tif localHasHubRole {\n\t\t\teventMode = EventModeHubServer\n\t\t} else {\n\t\t\teventMode = EventModeHubClient\n\t\t}\n\t}\n\n\treturn hubAddresses, eventMode\n}\n\n\/\/ EventsUpdateListeners refreshes the cluster event listener connections.\nfunc EventsUpdateListeners(endpoints *endpoints.Endpoints, cluster *db.Cluster, serverCert func() *shared.CertInfo, members map[int64]APIHeartbeatMember, f func(int64, api.Event)) {\n\tlistenersUpdateLock.Lock()\n\tdefer listenersUpdateLock.Unlock()\n\n\t\/\/ If no heartbeat members provided, populate from global database.\n\tif members == nil {\n\t\tvar dbMembers []db.NodeInfo\n\t\tvar offlineThreshold time.Duration\n\n\t\terr := cluster.Transaction(func(tx *db.ClusterTx) error {\n\t\t\tvar err error\n\n\t\t\tdbMembers, err = tx.GetNodes()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tofflineThreshold, err = tx.GetNodeOfflineThreshold()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tlogger.Warn(\"Failed to get current cluster members\", log.Ctx{\"err\": err})\n\t\t\treturn\n\t\t}\n\n\t\tmembers = make(map[int64]APIHeartbeatMember, len(dbMembers))\n\t\tfor _, dbMember := range dbMembers {\n\t\t\tmembers[dbMember.ID] = APIHeartbeatMember{\n\t\t\t\tID:            dbMember.ID,\n\t\t\t\tName:          dbMember.Name,\n\t\t\t\tAddress:       dbMember.Address,\n\t\t\t\tLastHeartbeat: dbMember.Heartbeat,\n\t\t\t\tOnline:        !dbMember.IsOffline(offlineThreshold),\n\t\t\t\tRoles:         dbMember.Roles,\n\t\t\t}\n\t\t}\n\t}\n\n\tnetworkAddress := endpoints.NetworkAddress()\n\thubAddresses, localEventMode := hubAddresses(networkAddress, members)\n\n\t\/\/ Store event hub addresses in global slice.\n\tlistenersLock.Lock()\n\teventHubAddresses = hubAddresses\n\teventMode = localEventMode\n\tlistenersLock.Unlock()\n\n\tkeepListeners := make(map[string]struct{})\n\twg := sync.WaitGroup{}\n\tfor _, member := range members {\n\t\t\/\/ Don't bother trying to connect to ourselves or offline members.\n\t\tif member.Address == networkAddress || !member.Online {\n\t\t\tcontinue\n\t\t}\n\n\t\tif localEventMode != EventModeFullMesh && !RoleInSlice(db.ClusterRoleEventHub, member.Roles) {\n\t\t\tcontinue \/\/ Skip non-event-hub members if we are operating in event-hub mode.\n\t\t}\n\n\t\tlistenersLock.Lock()\n\t\tlistener, ok := listeners[member.Address]\n\n\t\t\/\/ If the member already has a listener associated to it, check that the listener is still active.\n\t\t\/\/ If it is, just move on to next member, but if not then we'll try to connect again.\n\t\tif ok {\n\t\t\tif listener.IsActive() {\n\t\t\t\tkeepListeners[member.Address] = struct{}{} \/\/ Add to current listeners list.\n\t\t\t\tlistenersLock.Unlock()\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ Disconnect and delete listener, but don't delete any listenersNotify entry as there\n\t\t\t\/\/ might be something waiting for a future connection.\n\t\t\tlistener.Disconnect()\n\t\t\tdelete(listeners, member.Address)\n\t\t\tlogger.Info(\"Removed inactive member event listener client\", log.Ctx{\"local\": networkAddress, \"remote\": member.Address})\n\t\t}\n\t\tlistenersLock.Unlock()\n\n\t\tkeepListeners[member.Address] = struct{}{} \/\/ Add to current listeners list.\n\n\t\t\/\/ Connect to remote concurrently and add to active listeners if successful.\n\t\twg.Add(1)\n\t\tgo func(m APIHeartbeatMember) {\n\t\t\tdefer wg.Done()\n\t\t\tlistener, err := eventsConnect(m.Address, endpoints.NetworkCert(), serverCert())\n\t\t\tif err != nil {\n\t\t\t\tlogger.Warn(\"Failed adding member event listener client\", log.Ctx{\"local\": networkAddress, \"remote\": m.Address, \"err\": err})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlistener.AddHandler(nil, func(event api.Event) { f(m.ID, event) })\n\n\t\t\tlistenersLock.Lock()\n\t\t\tlisteners[m.Address] = listener\n\n\t\t\t\/\/ Indicate to any notifiers waiting for this member's address that it is connected.\n\t\t\tfor connected, notifyAddresses := range listenersNotify {\n\t\t\t\tif shared.StringInSlice(m.Address, notifyAddresses) {\n\t\t\t\t\tclose(connected)\n\t\t\t\t\tdelete(listenersNotify, connected)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlogger.Info(\"Added member event listener client\", log.Ctx{\"local\": networkAddress, \"remote\": m.Address})\n\t\t\tlistenersLock.Unlock()\n\t\t}(member)\n\t}\n\n\twg.Wait()\n\n\t\/\/ Disconnect and delete any out of date listeners and their notifiers.\n\tlistenersLock.Lock()\n\tfor address, listener := range listeners {\n\t\tif _, found := keepListeners[address]; !found {\n\t\t\tlistener.Disconnect()\n\t\t\tdelete(listeners, address)\n\t\t\tlogger.Info(\"Removed old member event listener client\", log.Ctx{\"local\": networkAddress, \"remote\": address})\n\t\t}\n\t}\n\tlistenersLock.Unlock()\n}\n\n\/\/ Establish a client connection to get events from the given node.\nfunc eventsConnect(address string, networkCert *shared.CertInfo, serverCert *shared.CertInfo) (*lxd.EventListener, error) {\n\tclient, err := Connect(address, networkCert, serverCert, nil, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trevert := revert.New()\n\trevert.Add(func() {\n\t\tclient.Disconnect()\n\t})\n\n\tlistener, err := client.GetEventsAllProjects()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trevert.Success()\n\treturn listener, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"database\/sql\"\n\n\t_ \"github.com\/mattn\/go-sqlite3\"\n)\n\ntype Backup struct {\n\tID       int    `json:\"id\"`\n\tName     string `json:\"name\"`\n\tStarted  string `json:\"started\"`\n\tFinished string `json:\"finished\"`\n\tDuration string `json:\"duration\"`\n\tStatus   string `json:\"status\"`\n}\n\ntype BackupCollection struct {\n\tBackups []Backup `json:\"items\"`\n}\n\nfunc GetBackups(db *sql.DB) BackupCollection {\n\tsql := \"SELECT * FROM backups\"\n\trows, err := db.Query(sql)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t\/\/ Cleanup if exit\n\tdefer rows.Close()\n\n\tresult := BackupCollection{}\n\n\tfor rows.Next() {\n\t\tbackup := Backup{}\n\t\terr2 := rows.Scan(&backup.ID, &backup.Name)\n\n\t\tif err2 != nil {\n\t\t\tpanic(err2)\n\t\t}\n\n\t\tresult.Backups = append(result.Backups, backup)\n\t}\n\treturn result\n}\n\nfunc PutBackup(db *sql.DB, name string, starting string, finished string, duration string, status string) (int64, error) {\n\tsql := \"INSERT INTO backups(name, starting, finished, duration, status) VALUES(?,?,?,?,?)\"\n\n\t\/\/ Create prepared sql statement\n\tstmt, err := db.Prepare(sql)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer stmt.Close()\n\n\tresult, err2 := stmt.Exec(name)\n\n\tif err2 != nil {\n\t\tpanic(err)\n\t}\n\n\treturn result.LastInsertId()\n\n}\n<commit_msg>🐛 Fix PutBackup and GetBackup on Backup Model<commit_after>package models\n\nimport (\n\t\"database\/sql\"\n\n\t_ \"github.com\/mattn\/go-sqlite3\"\n)\n\ntype Backup struct {\n\tID       int    `json:\"id\"`\n\tName     string `json:\"name\"`\n\tStarted  string `json:\"started\"`\n\tFinished string `json:\"finished\"`\n\tDuration string `json:\"duration\"`\n\tStatus   string `json:\"status\"`\n}\n\ntype BackupCollection struct {\n\tBackups []Backup `json:\"items\"`\n}\n\nfunc GetBackups(db *sql.DB) BackupCollection {\n\tsql := \"SELECT * FROM backups\"\n\trows, err := db.Query(sql)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t\/\/ Cleanup if exit\n\tdefer rows.Close()\n\n\tresult := BackupCollection{}\n\n\tfor rows.Next() {\n\t\tbackup := Backup{}\n\t\terr2 := rows.Scan(&backup.ID, &backup.Name, &backup.Started, &backup.Finished, &backup.Duration, &backup.Status)\n\n\t\tif err2 != nil {\n\t\t\tpanic(err2)\n\t\t}\n\n\t\tresult.Backups = append(result.Backups, backup)\n\t}\n\treturn result\n}\n\nfunc PutBackup(db *sql.DB, name string, starting string, finished string, duration string, status string) (int64, error) {\n\tsql := \"INSERT INTO backups(name, starting, finished, duration, status) VALUES(?, ?, ?, ?, ?)\"\n\n\t\/\/ Create prepared sql statement\n\tstmt, err := db.Prepare(sql)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer stmt.Close()\n\n\tresult, err2 := stmt.Exec(name, starting, finished, duration, status)\n\n\tif err2 != nil {\n\t\tpanic(err)\n\t}\n\n\treturn result.LastInsertId()\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"fmt\"\n\t\"github.com\/Shopify\/sarama\"\n)\n\nvar (\n\tDefaultMessageList *MessageManager\n\tkafkaTopic      = \"franz\"\n\tkafkaBroker     = \"localhost:9092\"\n)\n\ntype Message struct {\n\tID    int64  \/\/ Unique identifier\n\tTitle string \/\/ Description\n\tDone  bool   \/\/ Is this Message done?\n}\n\n\/\/ NewMessage creates a new message given a title, that can't be empty.\nfunc NewMessage(title string) (*Message, error) {\n\tif title == \"\" {\n\t\treturn nil, fmt.Errorf(\"empty title\")\n\t}\n\treturn &Message{0, title, false}, nil\n}\n\n\/\/ MessageManager manages a list of messages in memory.\ntype MessageManager struct {\n\tmessages  []*Message\n\tlastID int64\n}\n\n\/\/ NewMessageManager returns an empty MessageManager.\nfunc NewMessageManager() *MessageManager {\n\treturn &MessageManager{}\n}\n\n\/\/ Save saves the given Message in the MessageManager.\nfunc (m *MessageManager) Save(message *Message) error {\n\tif message.ID == 0 {\n\t\tm.lastID++\n\t\tmessage.ID = m.lastID\n\t\tm.messages = append(m.messages, cloneMessage(message))\n\t\treturn nil\n\t}\n\n\tfor i, t := range m.messages {\n\t\tif t.ID == message.ID {\n\t\t\tm.messages[i] = cloneMessage(message)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"unknown message\")\n}\n\n\/\/ cloneMessage creates and returns a deep copy of the given Message.\nfunc cloneMessage(t *Message) *Message {\n\tc := *t\n\treturn &c\n}\n\n\/\/ All returns the list of all the Messages in the MessageManager.\nfunc (m *MessageManager) All() []*Message {\n\treturn m.messages\n}\n\n\/\/ Find returns the Message with the given id in the MessageManager and a boolean\n\/\/ indicating if the id was found.\nfunc (m *MessageManager) Find(ID int64) (*Message, bool) {\n\tfor _, t := range m.messages {\n\t\tif t.ID == ID {\n\t\t\treturn t, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (m *MessageManager) Send(message *Message) error {\n\tkafkaMessage := &sarama.ProducerMessage{\n\t\tTopic: kafkaTopic,\n\t\tKey:   nil,\n\t\tValue: sarama.StringEncoder(message.Title),\n\t}\n\n\tkafkaProducer, err := sarama.NewSyncProducer([]string{kafkaBroker}, nil)\n\tif err != nil {\n\t\t\/\/TODO Cosmin\n\t}\n\tdefer func() {\n\t\tif errClose := kafkaProducer.Close(); errClose != nil {\n\t\t\t\/\/TODO Cosmin\n\t\t}\n\t}()\n\n\t_, _, errSend := kafkaProducer.SendMessage(kafkaMessage)\n\treturn errSend\n}\n\nfunc init() {\n\tDefaultMessageList = NewMessageManager()\n}\n<commit_msg>adding error handling at message sending<commit_after>package models\n\nimport (\n\t\"fmt\"\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/astaxie\/beego\"\n)\n\nvar (\n\tDefaultMessageList *MessageManager\n\tkafkaTopic      = \"franz\"\n\tkafkaBroker     = \"localhost:9092\"\n)\n\ntype Message struct {\n\tID    int64  \/\/ Unique identifier\n\tTitle string \/\/ Description\n\tDone  bool   \/\/ Is this Message done?\n}\n\n\/\/ NewMessage creates a new message given a title, that can't be empty.\nfunc NewMessage(title string) (*Message, error) {\n\tif title == \"\" {\n\t\treturn nil, fmt.Errorf(\"empty title\")\n\t}\n\treturn &Message{0, title, false}, nil\n}\n\n\/\/ MessageManager manages a list of messages in memory.\ntype MessageManager struct {\n\tmessages  []*Message\n\tlastID int64\n}\n\n\/\/ NewMessageManager returns an empty MessageManager.\nfunc NewMessageManager() *MessageManager {\n\treturn &MessageManager{}\n}\n\n\/\/ Save saves the given Message in the MessageManager.\nfunc (m *MessageManager) Save(message *Message) error {\n\tif message.ID == 0 {\n\t\tm.lastID++\n\t\tmessage.ID = m.lastID\n\t\tm.messages = append(m.messages, cloneMessage(message))\n\t\treturn nil\n\t}\n\n\tfor i, t := range m.messages {\n\t\tif t.ID == message.ID {\n\t\t\tm.messages[i] = cloneMessage(message)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"unknown message\")\n}\n\n\/\/ cloneMessage creates and returns a deep copy of the given Message.\nfunc cloneMessage(t *Message) *Message {\n\tc := *t\n\treturn &c\n}\n\n\/\/ All returns the list of all the Messages in the MessageManager.\nfunc (m *MessageManager) All() []*Message {\n\treturn m.messages\n}\n\n\/\/ Find returns the Message with the given id in the MessageManager and a boolean\n\/\/ indicating if the id was found.\nfunc (m *MessageManager) Find(ID int64) (*Message, bool) {\n\tfor _, t := range m.messages {\n\t\tif t.ID == ID {\n\t\t\treturn t, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (m *MessageManager) Send(message *Message) error {\n\tkafkaMessage := &sarama.ProducerMessage{\n\t\tTopic: kafkaTopic,\n\t\tKey:   nil,\n\t\tValue: sarama.StringEncoder(message.Title),\n\t}\n\n\tkafkaProducer, err := sarama.NewSyncProducer([]string{kafkaBroker}, nil)\n\tif err != nil {\n\t\tbeego.Error(\"error when creating Kafka SyncProducer\", err)\n\t}\n\tdefer func() {\n\t\tif errClose := kafkaProducer.Close(); errClose != nil {\n\t\t\tbeego.Error(\"error when closing Kafka SyncProducer\", errClose)\n\t\t}\n\t}()\n\n\t_, _, errSend := kafkaProducer.SendMessage(kafkaMessage)\n\treturn errSend\n}\n\nfunc init() {\n\tDefaultMessageList = NewMessageManager()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Unknwon\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"): you may\n\/\/ not use this file except in compliance with the License. You may obtain\n\/\/ a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations\n\/\/ under the License.\n\npackage models\n\nimport (\n\t\"errors\"\n\t\/\/ \"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Unknwon\/com\"\n\n\t\"github.com\/gpmgo\/switch\/modules\/archive\"\n\t\"github.com\/gpmgo\/switch\/modules\/log\"\n\t\"github.com\/gpmgo\/switch\/modules\/qiniu\"\n\t\"github.com\/gpmgo\/switch\/modules\/setting\"\n)\n\nvar (\n\tErrRevisionIsLocal  = errors.New(\"Revision archive is in local\")\n\tErrPackageNotExist  = errors.New(\"Package does not exist\")\n\tErrRevisionNotExist = errors.New(\"Revision does not exist\")\n)\n\ntype Storage int\n\nconst (\n\tLOCAL Storage = iota\n\tQINIU\n)\n\n\/\/ Revision represents a revision of a Go package.\ntype Revision struct {\n\tId       int64\n\tPkgId    int64    `xorm:\"UNIQUE(s)\"`\n\tPkg      *Package `xorm:\"-\"`\n\tRevision string   `xorm:\"UNIQUE(s)\"`\n\tStorage\n\tSize    int64\n\tUpdated time.Time `xorm:\"UPDATED\"`\n}\n\nfunc (r *Revision) GetPackage() (err error) {\n\tif r.Pkg != nil {\n\t\treturn nil\n\t}\n\tr.Pkg, err = GetPakcageById(r.PkgId)\n\treturn err\n}\n\n\/\/ KeyName returns QiNiu key name.\nfunc (r *Revision) KeyName() (string, error) {\n\tif r.Storage == LOCAL {\n\t\treturn \"\", ErrRevisionIsLocal\n\t}\n\tif err := r.GetPackage(); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn r.Pkg.ImportPath + \"-\" + r.Revision + archive.GetExtension(r.Pkg.ImportPath), nil\n}\n\n\/\/ GetRevision returns revision by given pakcage ID and revision.\nfunc GetRevision(pkgId int64, rev string) (*Revision, error) {\n\tr := &Revision{\n\t\tPkgId:    pkgId,\n\t\tRevision: rev,\n\t}\n\thas, err := x.Get(r)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !has {\n\t\treturn nil, ErrRevisionNotExist\n\t}\n\treturn r, nil\n}\n\n\/\/ UpdateRevision updates revision information.\nfunc UpdateRevision(rev *Revision) error {\n\t_, err := x.Id(rev.Id).Update(rev)\n\treturn err\n}\n\n\/\/ DeleteRevisionById delete revision by given ID.\nfunc DeleteRevisionById(revId int64) error {\n\t_, err := x.Id(revId).Delete(new(Revision))\n\treturn err\n}\n\n\/\/ GetLocalRevisions returns all revisions that archives are saved locally.\nfunc GetLocalRevisions() ([]*Revision, error) {\n\trevs := make([]*Revision, 0, 10)\n\terr := x.Where(\"storage=0\").Find(&revs)\n\treturn revs, err\n}\n\n\/\/ GetRevisionsByPkgId returns a list of revisions of given package ID.\nfunc GetRevisionsByPkgId(pkgId int64) ([]*Revision, error) {\n\trevs := make([]*Revision, 0, 10)\n\terr := x.Where(\"pkg_id=?\", pkgId).Find(&revs)\n\treturn revs, err\n}\n\n\/\/ Package represents a Go package.\ntype Package struct {\n\tId             int64\n\tImportPath     string `xorm:\"UNIQUE\"`\n\tDescription    string\n\tHomepage       string\n\tIssues         string\n\tDownloadCount  int64\n\tRecentDownload int64\n\tIsValidated    bool      `xorm:\"DEFAULT 0\"`\n\tCreated        time.Time `xorm:\"CREATED\"`\n}\n\nfunc (pkg *Package) GetRevisions() ([]*Revision, error) {\n\treturn GetRevisionsByPkgId(pkg.Id)\n}\n\n\/\/ NewPackage creates\nfunc NewPackage(importPath string) (*Package, error) {\n\tpkg := &Package{\n\t\tImportPath: importPath,\n\t}\n\tif _, err := x.Insert(pkg); err != nil {\n\t\treturn nil, err\n\t}\n\treturn pkg, nil\n}\n\n\/\/ GetPakcageById returns a package by given ID.\nfunc GetPakcageById(pkgId int64) (*Package, error) {\n\tpkg := &Package{}\n\thas, err := x.Id(pkgId).Get(pkg)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !has {\n\t\treturn nil, ErrPackageNotExist\n\t}\n\treturn pkg, nil\n}\n\n\/\/ GetPakcageByPath returns a package by given import path.\nfunc GetPakcageByPath(importPath string) (*Package, error) {\n\tpkg := &Package{\n\t\tImportPath: importPath,\n\t}\n\thas, err := x.Get(pkg)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !has {\n\t\treturn nil, ErrPackageNotExist\n\t}\n\treturn pkg, nil\n}\n\n\/\/ CheckPkg checks if versioned package is in records, and download it when needed.\nfunc CheckPkg(importPath, rev string) (*Revision, error) {\n\t\/\/ Check package record.\n\tpkg, err := GetPakcageByPath(importPath)\n\tif err != nil {\n\t\tif err != ErrPackageNotExist {\n\t\t\treturn nil, err\n\t\t}\n\t\tblocked, blockErr, err := IsPackageBlocked(importPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t} else if blocked {\n\t\t\treturn nil, blockErr\n\t\t}\n\t}\n\n\tn := archive.NewNode(importPath, rev)\n\n\t\/\/ Get and check revision record.\n\tif err = n.GetRevision(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r *Revision\n\tif pkg != nil {\n\t\tr, err = GetRevision(pkg.Id, n.Revision)\n\t\tif err != nil && err != ErrRevisionNotExist {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ return nil, fmt.Errorf(\"Revision: %s\", n.Revision)\n\n\tif r == nil || (r.Storage == LOCAL && !com.IsFile(n.ArchivePath)) {\n\t\tif err := n.Download(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif pkg == nil {\n\t\tpkg, err = NewPackage(n.ImportPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif r == nil {\n\t\tr = &Revision{\n\t\t\tPkgId:    pkg.Id,\n\t\t\tRevision: n.Revision,\n\t\t}\n\t\t_, err = x.Insert(r)\n\t} else {\n\t\t_, err = x.Id(r.Id).Update(r)\n\t}\n\treturn r, nil\n}\n\n\/\/ IncreasePackageDownloadCount increase package download count by 1.\nfunc IncreasePackageDownloadCount(importPath string) error {\n\tpkg, err := GetPakcageByPath(importPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpkg.DownloadCount++\n\tpkg.RecentDownload++\n\t_, err = x.Id(pkg.Id).Update(pkg)\n\treturn err\n}\n\n\/\/ SearchPackages searchs packages by given keyword.\nfunc SearchPackages(keys string) ([]*Package, error) {\n\tkeys = strings.TrimSpace(keys)\n\tif len(keys) == 0 {\n\t\treturn nil, nil\n\t}\n\tkey := strings.Split(keys, \" \")[0]\n\tif len(key) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tpkgs := make([]*Package, 0, 50)\n\terr := x.Limit(50).Where(\"name like '%\" + keys + \"%'\").Find(&pkgs)\n\treturn pkgs, err\n}\n\nconst _EXPIRE_DURATION = -1 * 24 * 30 * 3 * time.Hour\n\nfunc cleanExpireRevesions() {\n\tif err := x.Where(\"updated<?\", time.Now().Add(_EXPIRE_DURATION)).\n\t\tIterate(new(Revision), func(idx int, bean interface{}) (err error) {\n\t\trev := bean.(*Revision)\n\t\tif err = rev.GetPackage(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err = x.Id(rev.Id).Delete(new(Revision)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\text := archive.GetExtension(rev.Pkg.ImportPath)\n\t\tfpath := path.Join(setting.ArchivePath, rev.Pkg.ImportPath, rev.Revision+ext)\n\n\t\tswitch rev.Storage {\n\t\tcase LOCAL:\n\t\t\tos.Remove(fpath)\n\t\t\tlog.Info(\"Revision deleted: %s\", fpath)\n\t\t\treturn nil\n\t\tcase QINIU:\n\t\t\tkey, err := rev.KeyName()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif setting.ProdMode {\n\t\t\t\tif err = qiniu.DeleteArchive(key); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Info(\"Revision deleted: %s\", key)\n\t\t\treturn nil\n\t\tdefault:\n\t\t\treturn nil\n\t\t}\n\n\t\treturn nil\n\t}); err != nil {\n\t\tlog.Error(4, \"Fail to clean expire revisions: %v\", err)\n\t}\n}\n<commit_msg>models\/package.go: fix log depth<commit_after>\/\/ Copyright 2014 Unknwon\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"): you may\n\/\/ not use this file except in compliance with the License. You may obtain\n\/\/ a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations\n\/\/ under the License.\n\npackage models\n\nimport (\n\t\"errors\"\n\t\/\/ \"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Unknwon\/com\"\n\n\t\"github.com\/gpmgo\/switch\/modules\/archive\"\n\t\"github.com\/gpmgo\/switch\/modules\/log\"\n\t\"github.com\/gpmgo\/switch\/modules\/qiniu\"\n\t\"github.com\/gpmgo\/switch\/modules\/setting\"\n)\n\nvar (\n\tErrRevisionIsLocal  = errors.New(\"Revision archive is in local\")\n\tErrPackageNotExist  = errors.New(\"Package does not exist\")\n\tErrRevisionNotExist = errors.New(\"Revision does not exist\")\n)\n\ntype Storage int\n\nconst (\n\tLOCAL Storage = iota\n\tQINIU\n)\n\n\/\/ Revision represents a revision of a Go package.\ntype Revision struct {\n\tId       int64\n\tPkgId    int64    `xorm:\"UNIQUE(s)\"`\n\tPkg      *Package `xorm:\"-\"`\n\tRevision string   `xorm:\"UNIQUE(s)\"`\n\tStorage\n\tSize    int64\n\tUpdated time.Time `xorm:\"UPDATED\"`\n}\n\nfunc (r *Revision) GetPackage() (err error) {\n\tif r.Pkg != nil {\n\t\treturn nil\n\t}\n\tr.Pkg, err = GetPakcageById(r.PkgId)\n\treturn err\n}\n\n\/\/ KeyName returns QiNiu key name.\nfunc (r *Revision) KeyName() (string, error) {\n\tif r.Storage == LOCAL {\n\t\treturn \"\", ErrRevisionIsLocal\n\t}\n\tif err := r.GetPackage(); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn r.Pkg.ImportPath + \"-\" + r.Revision + archive.GetExtension(r.Pkg.ImportPath), nil\n}\n\n\/\/ GetRevision returns revision by given pakcage ID and revision.\nfunc GetRevision(pkgId int64, rev string) (*Revision, error) {\n\tr := &Revision{\n\t\tPkgId:    pkgId,\n\t\tRevision: rev,\n\t}\n\thas, err := x.Get(r)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !has {\n\t\treturn nil, ErrRevisionNotExist\n\t}\n\treturn r, nil\n}\n\n\/\/ UpdateRevision updates revision information.\nfunc UpdateRevision(rev *Revision) error {\n\t_, err := x.Id(rev.Id).Update(rev)\n\treturn err\n}\n\n\/\/ DeleteRevisionById delete revision by given ID.\nfunc DeleteRevisionById(revId int64) error {\n\t_, err := x.Id(revId).Delete(new(Revision))\n\treturn err\n}\n\n\/\/ GetLocalRevisions returns all revisions that archives are saved locally.\nfunc GetLocalRevisions() ([]*Revision, error) {\n\trevs := make([]*Revision, 0, 10)\n\terr := x.Where(\"storage=0\").Find(&revs)\n\treturn revs, err\n}\n\n\/\/ GetRevisionsByPkgId returns a list of revisions of given package ID.\nfunc GetRevisionsByPkgId(pkgId int64) ([]*Revision, error) {\n\trevs := make([]*Revision, 0, 10)\n\terr := x.Where(\"pkg_id=?\", pkgId).Find(&revs)\n\treturn revs, err\n}\n\n\/\/ Package represents a Go package.\ntype Package struct {\n\tId             int64\n\tImportPath     string `xorm:\"UNIQUE\"`\n\tDescription    string\n\tHomepage       string\n\tIssues         string\n\tDownloadCount  int64\n\tRecentDownload int64\n\tIsValidated    bool      `xorm:\"DEFAULT 0\"`\n\tCreated        time.Time `xorm:\"CREATED\"`\n}\n\nfunc (pkg *Package) GetRevisions() ([]*Revision, error) {\n\treturn GetRevisionsByPkgId(pkg.Id)\n}\n\n\/\/ NewPackage creates\nfunc NewPackage(importPath string) (*Package, error) {\n\tpkg := &Package{\n\t\tImportPath: importPath,\n\t}\n\tif _, err := x.Insert(pkg); err != nil {\n\t\treturn nil, err\n\t}\n\treturn pkg, nil\n}\n\n\/\/ GetPakcageById returns a package by given ID.\nfunc GetPakcageById(pkgId int64) (*Package, error) {\n\tpkg := &Package{}\n\thas, err := x.Id(pkgId).Get(pkg)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !has {\n\t\treturn nil, ErrPackageNotExist\n\t}\n\treturn pkg, nil\n}\n\n\/\/ GetPakcageByPath returns a package by given import path.\nfunc GetPakcageByPath(importPath string) (*Package, error) {\n\tpkg := &Package{\n\t\tImportPath: importPath,\n\t}\n\thas, err := x.Get(pkg)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if !has {\n\t\treturn nil, ErrPackageNotExist\n\t}\n\treturn pkg, nil\n}\n\n\/\/ CheckPkg checks if versioned package is in records, and download it when needed.\nfunc CheckPkg(importPath, rev string) (*Revision, error) {\n\t\/\/ Check package record.\n\tpkg, err := GetPakcageByPath(importPath)\n\tif err != nil {\n\t\tif err != ErrPackageNotExist {\n\t\t\treturn nil, err\n\t\t}\n\t\tblocked, blockErr, err := IsPackageBlocked(importPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t} else if blocked {\n\t\t\treturn nil, blockErr\n\t\t}\n\t}\n\n\tn := archive.NewNode(importPath, rev)\n\n\t\/\/ Get and check revision record.\n\tif err = n.GetRevision(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r *Revision\n\tif pkg != nil {\n\t\tr, err = GetRevision(pkg.Id, n.Revision)\n\t\tif err != nil && err != ErrRevisionNotExist {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ return nil, fmt.Errorf(\"Revision: %s\", n.Revision)\n\n\tif r == nil || (r.Storage == LOCAL && !com.IsFile(n.ArchivePath)) {\n\t\tif err := n.Download(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif pkg == nil {\n\t\tpkg, err = NewPackage(n.ImportPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif r == nil {\n\t\tr = &Revision{\n\t\t\tPkgId:    pkg.Id,\n\t\t\tRevision: n.Revision,\n\t\t}\n\t\t_, err = x.Insert(r)\n\t} else {\n\t\t_, err = x.Id(r.Id).Update(r)\n\t}\n\treturn r, nil\n}\n\n\/\/ IncreasePackageDownloadCount increase package download count by 1.\nfunc IncreasePackageDownloadCount(importPath string) error {\n\tpkg, err := GetPakcageByPath(importPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpkg.DownloadCount++\n\tpkg.RecentDownload++\n\t_, err = x.Id(pkg.Id).Update(pkg)\n\treturn err\n}\n\n\/\/ SearchPackages searchs packages by given keyword.\nfunc SearchPackages(keys string) ([]*Package, error) {\n\tkeys = strings.TrimSpace(keys)\n\tif len(keys) == 0 {\n\t\treturn nil, nil\n\t}\n\tkey := strings.Split(keys, \" \")[0]\n\tif len(key) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tpkgs := make([]*Package, 0, 50)\n\terr := x.Limit(50).Where(\"name like '%\" + keys + \"%'\").Find(&pkgs)\n\treturn pkgs, err\n}\n\nconst _EXPIRE_DURATION = -1 * 24 * 30 * 3 * time.Hour\n\nfunc cleanExpireRevesions() {\n\tif err := x.Where(\"updated<?\", time.Now().Add(_EXPIRE_DURATION)).\n\t\tIterate(new(Revision), func(idx int, bean interface{}) (err error) {\n\t\trev := bean.(*Revision)\n\t\tif err = rev.GetPackage(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err = x.Id(rev.Id).Delete(new(Revision)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\text := archive.GetExtension(rev.Pkg.ImportPath)\n\t\tfpath := path.Join(setting.ArchivePath, rev.Pkg.ImportPath, rev.Revision+ext)\n\n\t\tswitch rev.Storage {\n\t\tcase LOCAL:\n\t\t\tos.Remove(fpath)\n\t\t\tlog.Info(\"Revision deleted: %s\", fpath)\n\t\t\treturn nil\n\t\tcase QINIU:\n\t\t\tkey, err := rev.KeyName()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif setting.ProdMode {\n\t\t\t\tif err = qiniu.DeleteArchive(key); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tlog.Info(\"Revision deleted: %s\", key)\n\t\t\treturn nil\n\t\tdefault:\n\t\t\treturn nil\n\t\t}\n\n\t\treturn nil\n\t}); err != nil {\n\t\tlog.Error(3, \"Fail to clean expire revisions: %v\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nA trivial example of wrapping a C library in Go.\nFor a more complex example and explanation,\nsee ..\/gmp\/gmp.go.\n*\/\n\npackage stdio\n\n\/*\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/stat.h>\n#include <errno.h>\n\nchar* greeting = \"hello, world\";\n*\/\nimport \"C\"\nimport \"unsafe\"\n\ntype File C.FILE\n\nvar Stdout = (*File)(C.stdout)\nvar Stderr = (*File)(C.stderr)\n\n\/\/ Test reference to library symbol.\n\/\/ Stdout and stderr are too special to be a reliable test.\nvar myerr = C.sys_errlist\n\nfunc (f *File) WriteString(s string) {\n\tp := C.CString(s)\n\tC.fputs(p, (*C.FILE)(f))\n\tC.free(unsafe.Pointer(p))\n\tf.Flush()\n}\n\nfunc (f *File) Flush() {\n\tC.fflush((*C.FILE)(f))\n}\n\nvar Greeting = C.GoString(C.greeting)\n<commit_msg>go\/build: fix windows build by commenting out references to stdout and stderr in cgotest<commit_after>\/\/ Copyright 2009 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nA trivial example of wrapping a C library in Go.\nFor a more complex example and explanation,\nsee ..\/gmp\/gmp.go.\n*\/\n\npackage stdio\n\n\/*\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/stat.h>\n#include <errno.h>\n\nchar* greeting = \"hello, world\";\n*\/\nimport \"C\"\nimport \"unsafe\"\n\ntype File C.FILE\n\n\/\/ TODO(brainman): uncomment once stdout and stderr references are working on Windows.\n\/\/var Stdout = (*File)(C.stdout)\n\/\/var Stderr = (*File)(C.stderr)\n\n\/\/ Test reference to library symbol.\n\/\/ Stdout and stderr are too special to be a reliable test.\nvar myerr = C.sys_errlist\n\nfunc (f *File) WriteString(s string) {\n\tp := C.CString(s)\n\tC.fputs(p, (*C.FILE)(f))\n\tC.free(unsafe.Pointer(p))\n\tf.Flush()\n}\n\nfunc (f *File) Flush() {\n\tC.fflush((*C.FILE)(f))\n}\n\nvar Greeting = C.GoString(C.greeting)\n<|endoftext|>"}
{"text":"<commit_before>package mpeg4file\n\ntype mdat struct{\n\tsize uint32\n\tlargeSize uint64\n\tboxtype uint32\n\tdata []byte\n}\n\nfunc NewMdat (s uint32, payload []byte) *mdat{\n\tnewMdat:=new(mdat)\n\tnewMdat.size=s\n\tnewMdat.data = payload\n\treturn newMdat\n}\n\nfunc NewMdatLargeSize (s uint64, payload []byte) *mdat{\n\tnewMdat:=new(mdat)\n\tnewMdat.size=1\n\tnewMdat.largeSize = s\n\tnewMdat.data = payload\n\treturn newMdat\n}\n\nfunc (m *mdat) SetSize (s uint64){\n\tif s>4294967295 {\n\t\tm.size = uint32(s)\n\t}else{\n\t\tm.size = 1\n\t\tm.largeSize = s\n\t}\n}<commit_msg>updated mdat<commit_after>package mpeg4file\n\ntype mdat struct{\n\tsize uint32\n\tlargeSize uint64\n\tboxtype uint32\n\tdata []byte\n}\n\nfunc NewMdat (s uint64, payload []byte) *mdat{\n\tnewMdat:=new(mdat)\n\tnewMdat.SetSize(s)\n\tnewMdat.data = payload\n\treturn newMdat\n}\n\nfunc (m *mdat) SetSize (s uint64){\n\tif s==0{\n\t\tm.size=0\n\t} else {\n\t\tif s>4294967295 {\n\t\t\tm.size = uint32(s)\n\t\t}else{\n\t\t\tm.size = 1\n\t\t\tm.largeSize = s\n\t\t}\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>package gonameparts\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestLooksCorporate(t *testing.T) {\n\tt.Parallel()\n\tn := nameString{FullName: \"Sprockets Inc\"}\n\n\tres := n.looksCorporate()\n\n\tif res != true {\n\t\tt.Errorf(\"Expected true.  Actual %v\", res)\n\t}\n\n}\n\nfunc TestSearchParts(t *testing.T) {\n\tt.Parallel()\n\tn := nameString{FullName: \"Mr. James Polera\"}\n\n\tres := n.searchParts(&salutations)\n\n\tif res != 0 {\n\t\tt.Errorf(\"Expected true.  Actual %v\", res)\n\t}\n\n}\n\nfunc TestClean(t *testing.T) {\n\tt.Parallel()\n\tn := nameString{FullName: \"Mr. James Polera\"}\n\n\tres := n.cleaned()\n\n\tif res[0] != \"Mr\" {\n\t\tt.Errorf(\"Expected 'Mr'.  Actual %v\", res[0])\n\t}\n\n}\n\nfunc TestLocateSalutation(t *testing.T) {\n\tt.Parallel()\n\tn := nameString{FullName: \"Mr. James Polera\"}\n\n\tres := n.find(\"salutation\")\n\n\tif res != 0 {\n\t\tt.Errorf(\"Expected 0.  Actual %v\", res)\n\t}\n}\n\nfunc TestHasComma(t *testing.T) {\n\tt.Parallel()\n\tn := nameString{FullName: \"Polera, James\"}\n\tres := n.hasComma()\n\n\tif res != true {\n\t\tt.Errorf(\"Expected true.  Actual %v\", res)\n\t}\n\n}\n\nfunc TestNormalize(t *testing.T) {\n\tt.Parallel()\n\tn := nameString{FullName: \"Polera, James\"}\n\tres := n.normalize()\n\n\tif res[0] != \"James\" {\n\t\tt.Errorf(\"Expected James.  Actual %v\", res[0])\n\t}\n\n\tif res[1] != \"Polera\" {\n\t\tt.Errorf(\"Expected Polera.  Actual %v\", res[1])\n\t}\n\n}\n\nfunc TestParseAllFields(t *testing.T) {\n\tt.Parallel()\n\tres := Parse(\"Mr. James J. Polera Jr. Esq.\")\n\n\tif res.Salutation != \"Mr.\" {\n\t\tt.Errorf(\"Expected 'Mr.'.  Actual %v\", res.Salutation)\n\t}\n\n\tif res.FirstName != \"James\" {\n\t\tt.Errorf(\"Expected 'James'.  Actual %v\", res.FirstName)\n\t}\n\n\tif res.MiddleName != \"J.\" {\n\t\tt.Errorf(\"Expected 'J.'.  Actual %v\", res.MiddleName)\n\t}\n\n\tif res.LastName != \"Polera\" {\n\t\tt.Errorf(\"Expected 'Polera'.  Actual %v\", res.LastName)\n\t}\n\n\tif res.Generation != \"Jr.\" {\n\t\tt.Errorf(\"Expected 'Jr.'.  Actual %v\", res.Generation)\n\t}\n\n\tif res.Suffix != \"Esq.\" {\n\t\tt.Errorf(\"Expected 'Esq.'.  Actual %v\", res.Suffix)\n\t}\n}\n\nfunc TestParseFirstLast(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"James Polera\")\n\tif res.FirstName != \"James\" {\n\t\tt.Errorf(\"Expected 'James'.  Actual %v\", res.FirstName)\n\t}\n\n\tif res.LastName != \"Polera\" {\n\t\tt.Errorf(\"Expected 'Polera'.  Actual %v\", res.LastName)\n\t}\n}\n\nfunc TestLastNamePrefix(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"Otto von Bismark\")\n\n\tif res.FirstName != \"Otto\" {\n\t\tt.Errorf(\"Expected 'Otto'.  Actual %v\", res.FirstName)\n\t}\n\n\tif res.LastName != \"von Bismark\" {\n\t\tt.Errorf(\"Expected 'von Bismark'.  Actual %v\", res.LastName)\n\t}\n\n}\n\nfunc TestAliases(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"James Polera a\/k\/a Batman\")\n\n\tif res.Aliases[0].FirstName != \"Batman\" {\n\t\tt.Errorf(\"Expected 'Batman'.  Actual: %v\", res.Aliases[0].FirstName)\n\t}\n\n}\n\nfunc TestNickname(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"Philip Francis 'The Scooter' Rizzuto\")\n\n\tif res.Nickname != \"'The Scooter'\" {\n\t\tt.Errorf(\"Expected 'The Scooter'.  Actual: %v\", res.Nickname)\n\t}\n}\n\nfunc TestStripSupplemental(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"Philip Francis 'The Scooter' Rizzuto, deceased\")\n\n\tif res.FirstName != \"Philip\" {\n\t\tt.Errorf(\"Expected 'Philip'.  Actual: %v\", res.FirstName)\n\t}\n\n\tif res.MiddleName != \"Francis\" {\n\t\tt.Errorf(\"Expected 'Francis'.  Actual: %v\", res.MiddleName)\n\t}\n\n\tif res.Nickname != \"'The Scooter'\" {\n\t\tt.Errorf(\"Expected 'The Scooter'.  Actual: %v\", res.Nickname)\n\t}\n\n\tif res.LastName != \"Rizzuto\" {\n\t\tt.Errorf(\"Expected 'Rizzuto'.  Actual: %v\", res.LastName)\n\t}\n}\n\nfunc TestLongPrefixedLastName(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"Saleh ibn Tariq ibn Khalid al-Fulan\")\n\n\tif res.FirstName != \"Saleh\" {\n\t\tt.Errorf(\"Expected 'Saleh'.  Actual: %v\", res.FirstName)\n\t}\n\n\tif res.LastName != \"ibn Tariq ibn Khalid al-Fulan\" {\n\t\tt.Errorf(\"Expected 'ibn Tariq ibn Khalid al-Fulan'.  Actual: %v\", res.LastName)\n\n\t}\n}\n\nfunc TestMisplacedApostrophe(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"John O' Hurley\")\n\n\tif res.FirstName != \"John\" {\n\t\tt.Errorf(\"Expected 'John'.  Actual: %v\", res.FirstName)\n\t}\n\n\tif res.LastName != \"O'Hurley\" {\n\t\tt.Errorf(\"Expected 'O'Hurley'.  Actual: %v\", res.LastName)\n\t}\n\n}\n\nfunc TestMultipleAKA(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"Tony Stark a\/k\/a Ironman a\/k\/a Stark, Anthony a\/k\/a Anthony Edward \\\"Tony\\\" Stark\")\n\n\tif len(res.Aliases) != 3 {\n\t\tt.Errorf(\"Expected 3 aliases.  Actual: %v\", len(res.Aliases))\n\t}\n\n\tif res.FirstName != \"Tony\" {\n\t\tt.Errorf(\"Expected 'Tony'.  Actual: %v\", res.FirstName)\n\t}\n\n\tif res.LastName != \"Stark\" {\n\t\tt.Errorf(\"Expected 'Stark'.  Actual: %v\", res.LastName)\n\t}\n\n}\n\nfunc TestBuildFullName(t *testing.T) {\n\tres := Parse(\"President George Herbert Walker Bush\")\n\n\tif res.FullName != \"President George Herbert Walker Bush\" {\n\n\t\tt.Errorf(\"Expected 'President George Herbert Walker Bush'.  Actual: %v\", res.FullName)\n\t}\n\n}\n\nfunc TestDottedAka(t *testing.T) {\n\tres := Parse(\"James Polera a.k.a James K. Polera\")\n\tif len(res.Aliases) != 1 {\n\t\tt.Errorf(\"Expected 1 alias.  Actual: %v\", len(res.Aliases))\n\t}\n}\n\nfunc TestUnicodeCharsInName(t *testing.T) {\n\tres := Parse(\"König Ludwig\")\n\n\tif res.FirstName != \"König\" {\n\t\tt.Errorf(\"Expected 'König'.  Actual: %v\", res.FirstName)\n\n\t}\n}\n\nfunc ExampleParse() {\n\tres := Parse(\"Thurston Howell III\")\n\tfmt.Println(\"FirstName:\", res.FirstName)\n\tfmt.Println(\"LastName:\", res.LastName)\n\tfmt.Println(\"Generation:\", res.Generation)\n\n\t\/\/ Output:\n\t\/\/ FirstName: Thurston\n\t\/\/ LastName: Howell\n\t\/\/ Generation: III\n\n}\n\nfunc ExampleParse_second() {\n\n\tres := Parse(\"President George Herbert Walker Bush\")\n\tfmt.Println(\"Salutation:\", res.Salutation)\n\tfmt.Println(\"FirstName:\", res.FirstName)\n\tfmt.Println(\"MiddleName:\", res.MiddleName)\n\tfmt.Println(\"LastName:\", res.LastName)\n\n\t\/\/ Output:\n\t\/\/ Salutation: President\n\t\/\/ FirstName: George\n\t\/\/ MiddleName: Herbert Walker\n\t\/\/ LastName: Bush\n\n}\n<commit_msg>Added tabs in name test<commit_after>package gonameparts\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestLooksCorporate(t *testing.T) {\n\tt.Parallel()\n\tn := nameString{FullName: \"Sprockets Inc\"}\n\n\tres := n.looksCorporate()\n\n\tif res != true {\n\t\tt.Errorf(\"Expected true.  Actual %v\", res)\n\t}\n\n}\n\nfunc TestSearchParts(t *testing.T) {\n\tt.Parallel()\n\tn := nameString{FullName: \"Mr. James Polera\"}\n\n\tres := n.searchParts(&salutations)\n\n\tif res != 0 {\n\t\tt.Errorf(\"Expected true.  Actual %v\", res)\n\t}\n\n}\n\nfunc TestClean(t *testing.T) {\n\tt.Parallel()\n\tn := nameString{FullName: \"Mr. James Polera\"}\n\n\tres := n.cleaned()\n\n\tif res[0] != \"Mr\" {\n\t\tt.Errorf(\"Expected 'Mr'.  Actual %v\", res[0])\n\t}\n\n}\n\nfunc TestLocateSalutation(t *testing.T) {\n\tt.Parallel()\n\tn := nameString{FullName: \"Mr. James Polera\"}\n\n\tres := n.find(\"salutation\")\n\n\tif res != 0 {\n\t\tt.Errorf(\"Expected 0.  Actual %v\", res)\n\t}\n}\n\nfunc TestHasComma(t *testing.T) {\n\tt.Parallel()\n\tn := nameString{FullName: \"Polera, James\"}\n\tres := n.hasComma()\n\n\tif res != true {\n\t\tt.Errorf(\"Expected true.  Actual %v\", res)\n\t}\n\n}\n\nfunc TestNormalize(t *testing.T) {\n\tt.Parallel()\n\tn := nameString{FullName: \"Polera, James\"}\n\tres := n.normalize()\n\n\tif res[0] != \"James\" {\n\t\tt.Errorf(\"Expected James.  Actual %v\", res[0])\n\t}\n\n\tif res[1] != \"Polera\" {\n\t\tt.Errorf(\"Expected Polera.  Actual %v\", res[1])\n\t}\n\n}\n\nfunc TestParseAllFields(t *testing.T) {\n\tt.Parallel()\n\tres := Parse(\"Mr. James J. Polera Jr. Esq.\")\n\n\tif res.Salutation != \"Mr.\" {\n\t\tt.Errorf(\"Expected 'Mr.'.  Actual %v\", res.Salutation)\n\t}\n\n\tif res.FirstName != \"James\" {\n\t\tt.Errorf(\"Expected 'James'.  Actual %v\", res.FirstName)\n\t}\n\n\tif res.MiddleName != \"J.\" {\n\t\tt.Errorf(\"Expected 'J.'.  Actual %v\", res.MiddleName)\n\t}\n\n\tif res.LastName != \"Polera\" {\n\t\tt.Errorf(\"Expected 'Polera'.  Actual %v\", res.LastName)\n\t}\n\n\tif res.Generation != \"Jr.\" {\n\t\tt.Errorf(\"Expected 'Jr.'.  Actual %v\", res.Generation)\n\t}\n\n\tif res.Suffix != \"Esq.\" {\n\t\tt.Errorf(\"Expected 'Esq.'.  Actual %v\", res.Suffix)\n\t}\n}\n\nfunc TestParseFirstLast(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"James Polera\")\n\tif res.FirstName != \"James\" {\n\t\tt.Errorf(\"Expected 'James'.  Actual %v\", res.FirstName)\n\t}\n\n\tif res.LastName != \"Polera\" {\n\t\tt.Errorf(\"Expected 'Polera'.  Actual %v\", res.LastName)\n\t}\n}\n\nfunc TestLastNamePrefix(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"Otto von Bismark\")\n\n\tif res.FirstName != \"Otto\" {\n\t\tt.Errorf(\"Expected 'Otto'.  Actual %v\", res.FirstName)\n\t}\n\n\tif res.LastName != \"von Bismark\" {\n\t\tt.Errorf(\"Expected 'von Bismark'.  Actual %v\", res.LastName)\n\t}\n\n}\n\nfunc TestAliases(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"James Polera a\/k\/a Batman\")\n\n\tif res.Aliases[0].FirstName != \"Batman\" {\n\t\tt.Errorf(\"Expected 'Batman'.  Actual: %v\", res.Aliases[0].FirstName)\n\t}\n\n}\n\nfunc TestNickname(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"Philip Francis 'The Scooter' Rizzuto\")\n\n\tif res.Nickname != \"'The Scooter'\" {\n\t\tt.Errorf(\"Expected 'The Scooter'.  Actual: %v\", res.Nickname)\n\t}\n}\n\nfunc TestStripSupplemental(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"Philip Francis 'The Scooter' Rizzuto, deceased\")\n\n\tif res.FirstName != \"Philip\" {\n\t\tt.Errorf(\"Expected 'Philip'.  Actual: %v\", res.FirstName)\n\t}\n\n\tif res.MiddleName != \"Francis\" {\n\t\tt.Errorf(\"Expected 'Francis'.  Actual: %v\", res.MiddleName)\n\t}\n\n\tif res.Nickname != \"'The Scooter'\" {\n\t\tt.Errorf(\"Expected 'The Scooter'.  Actual: %v\", res.Nickname)\n\t}\n\n\tif res.LastName != \"Rizzuto\" {\n\t\tt.Errorf(\"Expected 'Rizzuto'.  Actual: %v\", res.LastName)\n\t}\n}\n\nfunc TestLongPrefixedLastName(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"Saleh ibn Tariq ibn Khalid al-Fulan\")\n\n\tif res.FirstName != \"Saleh\" {\n\t\tt.Errorf(\"Expected 'Saleh'.  Actual: %v\", res.FirstName)\n\t}\n\n\tif res.LastName != \"ibn Tariq ibn Khalid al-Fulan\" {\n\t\tt.Errorf(\"Expected 'ibn Tariq ibn Khalid al-Fulan'.  Actual: %v\", res.LastName)\n\n\t}\n}\n\nfunc TestMisplacedApostrophe(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"John O' Hurley\")\n\n\tif res.FirstName != \"John\" {\n\t\tt.Errorf(\"Expected 'John'.  Actual: %v\", res.FirstName)\n\t}\n\n\tif res.LastName != \"O'Hurley\" {\n\t\tt.Errorf(\"Expected 'O'Hurley'.  Actual: %v\", res.LastName)\n\t}\n\n}\n\nfunc TestMultipleAKA(t *testing.T) {\n\tt.Parallel()\n\n\tres := Parse(\"Tony Stark a\/k\/a Ironman a\/k\/a Stark, Anthony a\/k\/a Anthony Edward \\\"Tony\\\" Stark\")\n\n\tif len(res.Aliases) != 3 {\n\t\tt.Errorf(\"Expected 3 aliases.  Actual: %v\", len(res.Aliases))\n\t}\n\n\tif res.FirstName != \"Tony\" {\n\t\tt.Errorf(\"Expected 'Tony'.  Actual: %v\", res.FirstName)\n\t}\n\n\tif res.LastName != \"Stark\" {\n\t\tt.Errorf(\"Expected 'Stark'.  Actual: %v\", res.LastName)\n\t}\n\n}\n\nfunc TestBuildFullName(t *testing.T) {\n\tres := Parse(\"President George Herbert Walker Bush\")\n\n\tif res.FullName != \"President George Herbert Walker Bush\" {\n\n\t\tt.Errorf(\"Expected 'President George Herbert Walker Bush'.  Actual: %v\", res.FullName)\n\t}\n\n}\n\nfunc TestDottedAka(t *testing.T) {\n\tres := Parse(\"James Polera a.k.a James K. Polera\")\n\tif len(res.Aliases) != 1 {\n\t\tt.Errorf(\"Expected 1 alias.  Actual: %v\", len(res.Aliases))\n\t}\n}\n\nfunc TestUnicodeCharsInName(t *testing.T) {\n\tres := Parse(\"König Ludwig\")\n\n\tif res.FirstName != \"König\" {\n\t\tt.Errorf(\"Expected 'König'.  Actual: %v\", res.FirstName)\n\t}\n}\n\nfunc TestTabsInName(t *testing.T) {\n\tres := Parse(\"Dr. James\\tPolera\\tEsq.\")\n\n\tif res.Salutation != \"Dr.\" {\n\t\tt.Errorf(\"Expected 'Dr.'.  Actual: %v\", res.Salutation)\n\t}\n\n\tif res.FirstName != \"James\" {\n\t\tt.Errorf(\"Expected 'James'.  Actual: %v\", res.FirstName)\n\t}\n\n\tif res.LastName != \"Polera\" {\n\t\tt.Errorf(\"Expected 'Polera'.  Actual: %v\", res.LastName)\n\t}\n\n\tif res.Suffix != \"Esq.\" {\n\t\tt.Errorf(\"Expected 'Esq.'.  Actual: %v\", res.Suffix)\n\t}\n}\n\nfunc ExampleParse() {\n\tres := Parse(\"Thurston Howell III\")\n\tfmt.Println(\"FirstName:\", res.FirstName)\n\tfmt.Println(\"LastName:\", res.LastName)\n\tfmt.Println(\"Generation:\", res.Generation)\n\n\t\/\/ Output:\n\t\/\/ FirstName: Thurston\n\t\/\/ LastName: Howell\n\t\/\/ Generation: III\n\n}\n\nfunc ExampleParse_second() {\n\n\tres := Parse(\"President George Herbert Walker Bush\")\n\tfmt.Println(\"Salutation:\", res.Salutation)\n\tfmt.Println(\"FirstName:\", res.FirstName)\n\tfmt.Println(\"MiddleName:\", res.MiddleName)\n\tfmt.Println(\"LastName:\", res.LastName)\n\n\t\/\/ Output:\n\t\/\/ Salutation: President\n\t\/\/ FirstName: George\n\t\/\/ MiddleName: Herbert Walker\n\t\/\/ LastName: Bush\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build go1.7\n\npackage nethttp\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/http\/httptrace\"\n\t\"net\/url\"\n\n\t\"github.com\/opentracing\/opentracing-go\"\n\t\"github.com\/opentracing\/opentracing-go\/ext\"\n\t\"github.com\/opentracing\/opentracing-go\/log\"\n)\n\ntype contextKey int\n\nconst (\n\tkeyTracer contextKey = iota\n)\n\nconst defaultComponentName = \"net\/http\"\n\n\/\/ Transport wraps a RoundTripper. If a request is being traced with\n\/\/ Tracer, Transport will inject the current span into the headers,\n\/\/ and set HTTP related tags on the span.\ntype Transport struct {\n\t\/\/ The actual RoundTripper to use for the request. A nil\n\t\/\/ RoundTripper defaults to http.DefaultTransport.\n\thttp.RoundTripper\n}\n\ntype clientOptions struct {\n\toperationName            string\n\tcomponentName            string\n\turlTagFunc               func(u *url.URL) string\n\tdisableClientTrace       bool\n\tdisableInjectSpanContext bool\n\tspanObserver             func(span opentracing.Span, r *http.Request)\n}\n\n\/\/ ClientOption contols the behavior of TraceRequest.\ntype ClientOption func(*clientOptions)\n\n\/\/ OperationName returns a ClientOption that sets the operation\n\/\/ name for the client-side span.\nfunc OperationName(operationName string) ClientOption {\n\treturn func(options *clientOptions) {\n\t\toptions.operationName = operationName\n\t}\n}\n\n\/\/ URLTagFunc returns a ClientOption that uses given function f\n\/\/ to set the span's http.url tag. Can be used to change the default\n\/\/ http.url tag, eg to redact sensitive information.\nfunc URLTagFunc(f func(u *url.URL) string) ClientOption {\n\treturn func(options *clientOptions) {\n\t\toptions.urlTagFunc = f\n\t}\n}\n\n\/\/ ComponentName returns a ClientOption that sets the component\n\/\/ name for the client-side span.\nfunc ComponentName(componentName string) ClientOption {\n\treturn func(options *clientOptions) {\n\t\toptions.componentName = componentName\n\t}\n}\n\n\/\/ ClientTrace returns a ClientOption that turns on or off\n\/\/ extra instrumentation via httptrace.WithClientTrace.\nfunc ClientTrace(enabled bool) ClientOption {\n\treturn func(options *clientOptions) {\n\t\toptions.disableClientTrace = !enabled\n\t}\n}\n\n\/\/ InjectSpanContext returns a ClientOption that turns on or off\n\/\/ injection of the Span context in the request HTTP headers.\n\/\/ If this option is not used, the default behaviour is to\n\/\/ inject the span context.\nfunc InjectSpanContext(enabled bool) ClientOption {\n\treturn func(options *clientOptions) {\n\t\toptions.disableInjectSpanContext = !enabled\n\t}\n}\n\n\/\/ ClientSpanObserver returns a ClientOption that observes the span\n\/\/ for the client-side span.\nfunc ClientSpanObserver(f func(span opentracing.Span, r *http.Request)) ClientOption {\n\treturn func(options *clientOptions) {\n\t\toptions.spanObserver = f\n\t}\n}\n\n\/\/ TraceRequest adds a ClientTracer to req, tracing the request and\n\/\/ all requests caused due to redirects. When tracing requests this\n\/\/ way you must also use Transport.\n\/\/\n\/\/ Example:\n\/\/\n\/\/ \tfunc AskGoogle(ctx context.Context) error {\n\/\/ \t\tclient := &http.Client{Transport: &nethttp.Transport{}}\n\/\/ \t\treq, err := http.NewRequest(\"GET\", \"http:\/\/google.com\", nil)\n\/\/ \t\tif err != nil {\n\/\/ \t\t\treturn err\n\/\/ \t\t}\n\/\/ \t\treq = req.WithContext(ctx) \/\/ extend existing trace, if any\n\/\/\n\/\/ \t\treq, ht := nethttp.TraceRequest(tracer, req)\n\/\/ \t\tdefer ht.Finish()\n\/\/\n\/\/ \t\tres, err := client.Do(req)\n\/\/ \t\tif err != nil {\n\/\/ \t\t\treturn err\n\/\/ \t\t}\n\/\/ \t\tres.Body.Close()\n\/\/ \t\treturn nil\n\/\/ \t}\nfunc TraceRequest(tr opentracing.Tracer, req *http.Request, options ...ClientOption) (*http.Request, *Tracer) {\n\topts := &clientOptions{\n\t\turlTagFunc: func(u *url.URL) string {\n\t\t\treturn u.String()\n\t\t},\n\t\tspanObserver: func(_ opentracing.Span, _ *http.Request) {},\n\t}\n\tfor _, opt := range options {\n\t\topt(opts)\n\t}\n\tht := &Tracer{tr: tr, opts: opts}\n\tctx := req.Context()\n\tif !opts.disableClientTrace {\n\t\tctx = httptrace.WithClientTrace(ctx, ht.clientTrace())\n\t}\n\treq = req.WithContext(context.WithValue(ctx, keyTracer, ht))\n\treturn req, ht\n}\n\ntype closeTracker struct {\n\tio.ReadCloser\n\tsp opentracing.Span\n}\n\nfunc (c closeTracker) Close() error {\n\terr := c.ReadCloser.Close()\n\tc.sp.LogFields(log.String(\"event\", \"ClosedBody\"))\n\tc.sp.Finish()\n\treturn err\n}\n\ntype writerCloseTracker struct {\n\tio.ReadWriteCloser\n\tsp opentracing.Span\n}\n\nfunc (c writerCloseTracker) Close() error {\n\terr := c.ReadWriteCloser.Close()\n\tc.sp.LogFields(log.String(\"event\", \"ClosedBody\"))\n\tc.sp.Finish()\n\treturn err\n}\n\n\/\/ TracerFromRequest retrieves the Tracer from the request. If the request does\n\/\/ not have a Tracer it will return nil.\nfunc TracerFromRequest(req *http.Request) *Tracer {\n\ttr, ok := req.Context().Value(keyTracer).(*Tracer)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn tr\n}\n\n\/\/ RoundTrip implements the RoundTripper interface.\nfunc (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {\n\trt := t.RoundTripper\n\tif rt == nil {\n\t\trt = http.DefaultTransport\n\t}\n\ttracer := TracerFromRequest(req)\n\tif tracer == nil {\n\t\treturn rt.RoundTrip(req)\n\t}\n\n\ttracer.start(req)\n\n\text.HTTPMethod.Set(tracer.sp, req.Method)\n\text.HTTPUrl.Set(tracer.sp, tracer.opts.urlTagFunc(req.URL))\n\text.PeerAddress.Set(tracer.sp, req.URL.Host)\n\ttracer.opts.spanObserver(tracer.sp, req)\n\n\tif !tracer.opts.disableInjectSpanContext {\n\t\tcarrier := opentracing.HTTPHeadersCarrier(req.Header)\n\t\ttracer.sp.Tracer().Inject(tracer.sp.Context(), opentracing.HTTPHeaders, carrier)\n\t}\n\n\tresp, err := rt.RoundTrip(req)\n\n\tif err != nil {\n\t\ttracer.sp.Finish()\n\t\treturn resp, err\n\t}\n\text.HTTPStatusCode.Set(tracer.sp, uint16(resp.StatusCode))\n\tif resp.StatusCode >= http.StatusInternalServerError {\n\t\text.Error.Set(tracer.sp, true)\n\t}\n\tif req.Method == \"HEAD\" {\n\t\ttracer.sp.Finish()\n\t} else {\n\t\treadWriteCloser, ok := resp.Body.(io.ReadWriteCloser)\n\t\tif ok {\n\t\t\tresp.Body = writerCloseTracker{readWriteCloser, tracer.sp}\n\t\t} else {\n\t\t\tresp.Body = closeTracker{resp.Body, tracer.sp}\n\t\t}\n\t}\n\treturn resp, nil\n}\n\n\/\/ Tracer holds tracing details for one HTTP request.\ntype Tracer struct {\n\ttr   opentracing.Tracer\n\troot opentracing.Span\n\tsp   opentracing.Span\n\topts *clientOptions\n}\n\nfunc (h *Tracer) start(req *http.Request) opentracing.Span {\n\tif h.root == nil {\n\t\tparent := opentracing.SpanFromContext(req.Context())\n\t\tvar spanctx opentracing.SpanContext\n\t\tif parent != nil {\n\t\t\tspanctx = parent.Context()\n\t\t}\n\t\toperationName := h.opts.operationName\n\t\tif operationName == \"\" {\n\t\t\toperationName = \"HTTP Client\"\n\t\t}\n\t\troot := h.tr.StartSpan(operationName, opentracing.ChildOf(spanctx))\n\t\th.root = root\n\t}\n\n\tctx := h.root.Context()\n\th.sp = h.tr.StartSpan(\"HTTP \"+req.Method, opentracing.ChildOf(ctx), ext.SpanKindRPCClient)\n\n\tcomponentName := h.opts.componentName\n\tif componentName == \"\" {\n\t\tcomponentName = defaultComponentName\n\t}\n\text.Component.Set(h.sp, componentName)\n\n\treturn h.sp\n}\n\n\/\/ Finish finishes the span of the traced request.\nfunc (h *Tracer) Finish() {\n\tif h.root != nil {\n\t\th.root.Finish()\n\t}\n}\n\n\/\/ Span returns the root span of the traced request. This function\n\/\/ should only be called after the request has been executed.\nfunc (h *Tracer) Span() opentracing.Span {\n\treturn h.root\n}\n\nfunc (h *Tracer) clientTrace() *httptrace.ClientTrace {\n\treturn &httptrace.ClientTrace{\n\t\tGetConn:              h.getConn,\n\t\tGotConn:              h.gotConn,\n\t\tPutIdleConn:          h.putIdleConn,\n\t\tGotFirstResponseByte: h.gotFirstResponseByte,\n\t\tGot100Continue:       h.got100Continue,\n\t\tDNSStart:             h.dnsStart,\n\t\tDNSDone:              h.dnsDone,\n\t\tConnectStart:         h.connectStart,\n\t\tConnectDone:          h.connectDone,\n\t\tWroteHeaders:         h.wroteHeaders,\n\t\tWait100Continue:      h.wait100Continue,\n\t\tWroteRequest:         h.wroteRequest,\n\t}\n}\n\nfunc (h *Tracer) getConn(hostPort string) {\n\th.sp.LogFields(log.String(\"event\", \"GetConn\"), log.String(\"hostPort\", hostPort))\n}\n\nfunc (h *Tracer) gotConn(info httptrace.GotConnInfo) {\n\th.sp.SetTag(\"net\/http.reused\", info.Reused)\n\th.sp.SetTag(\"net\/http.was_idle\", info.WasIdle)\n\th.sp.LogFields(log.String(\"event\", \"GotConn\"))\n}\n\nfunc (h *Tracer) putIdleConn(error) {\n\th.sp.LogFields(log.String(\"event\", \"PutIdleConn\"))\n}\n\nfunc (h *Tracer) gotFirstResponseByte() {\n\th.sp.LogFields(log.String(\"event\", \"GotFirstResponseByte\"))\n}\n\nfunc (h *Tracer) got100Continue() {\n\th.sp.LogFields(log.String(\"event\", \"Got100Continue\"))\n}\n\nfunc (h *Tracer) dnsStart(info httptrace.DNSStartInfo) {\n\th.sp.LogFields(\n\t\tlog.String(\"event\", \"DNSStart\"),\n\t\tlog.String(\"host\", info.Host),\n\t)\n}\n\nfunc (h *Tracer) dnsDone(info httptrace.DNSDoneInfo) {\n\tfields := []log.Field{log.String(\"event\", \"DNSDone\")}\n\tfor _, addr := range info.Addrs {\n\t\tfields = append(fields, log.String(\"addr\", addr.String()))\n\t}\n\tif info.Err != nil {\n\t\tfields = append(fields, log.Error(info.Err))\n\t}\n\th.sp.LogFields(fields...)\n}\n\nfunc (h *Tracer) connectStart(network, addr string) {\n\th.sp.LogFields(\n\t\tlog.String(\"event\", \"ConnectStart\"),\n\t\tlog.String(\"network\", network),\n\t\tlog.String(\"addr\", addr),\n\t)\n}\n\nfunc (h *Tracer) connectDone(network, addr string, err error) {\n\tif err != nil {\n\t\th.sp.LogFields(\n\t\t\tlog.String(\"message\", \"ConnectDone\"),\n\t\t\tlog.String(\"network\", network),\n\t\t\tlog.String(\"addr\", addr),\n\t\t\tlog.String(\"event\", \"error\"),\n\t\t\tlog.Error(err),\n\t\t)\n\t} else {\n\t\th.sp.LogFields(\n\t\t\tlog.String(\"event\", \"ConnectDone\"),\n\t\t\tlog.String(\"network\", network),\n\t\t\tlog.String(\"addr\", addr),\n\t\t)\n\t}\n}\n\nfunc (h *Tracer) wroteHeaders() {\n\th.sp.LogFields(log.String(\"event\", \"WroteHeaders\"))\n}\n\nfunc (h *Tracer) wait100Continue() {\n\th.sp.LogFields(log.String(\"event\", \"Wait100Continue\"))\n}\n\nfunc (h *Tracer) wroteRequest(info httptrace.WroteRequestInfo) {\n\tif info.Err != nil {\n\t\th.sp.LogFields(\n\t\t\tlog.String(\"message\", \"WroteRequest\"),\n\t\t\tlog.String(\"event\", \"error\"),\n\t\t\tlog.Error(info.Err),\n\t\t)\n\t\text.Error.Set(h.sp, true)\n\t} else {\n\t\th.sp.LogFields(log.String(\"event\", \"WroteRequest\"))\n\t}\n}\n<commit_msg>Use local variable for span (#63)<commit_after>\/\/go:build go1.7\n\/\/ +build go1.7\n\npackage nethttp\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/http\/httptrace\"\n\t\"net\/url\"\n\n\t\"github.com\/opentracing\/opentracing-go\"\n\t\"github.com\/opentracing\/opentracing-go\/ext\"\n\t\"github.com\/opentracing\/opentracing-go\/log\"\n)\n\ntype contextKey int\n\nconst (\n\tkeyTracer contextKey = iota\n)\n\nconst defaultComponentName = \"net\/http\"\n\n\/\/ Transport wraps a RoundTripper. If a request is being traced with\n\/\/ Tracer, Transport will inject the current span into the headers,\n\/\/ and set HTTP related tags on the span.\ntype Transport struct {\n\t\/\/ The actual RoundTripper to use for the request. A nil\n\t\/\/ RoundTripper defaults to http.DefaultTransport.\n\thttp.RoundTripper\n}\n\ntype clientOptions struct {\n\toperationName            string\n\tcomponentName            string\n\turlTagFunc               func(u *url.URL) string\n\tdisableClientTrace       bool\n\tdisableInjectSpanContext bool\n\tspanObserver             func(span opentracing.Span, r *http.Request)\n}\n\n\/\/ ClientOption contols the behavior of TraceRequest.\ntype ClientOption func(*clientOptions)\n\n\/\/ OperationName returns a ClientOption that sets the operation\n\/\/ name for the client-side span.\nfunc OperationName(operationName string) ClientOption {\n\treturn func(options *clientOptions) {\n\t\toptions.operationName = operationName\n\t}\n}\n\n\/\/ URLTagFunc returns a ClientOption that uses given function f\n\/\/ to set the span's http.url tag. Can be used to change the default\n\/\/ http.url tag, eg to redact sensitive information.\nfunc URLTagFunc(f func(u *url.URL) string) ClientOption {\n\treturn func(options *clientOptions) {\n\t\toptions.urlTagFunc = f\n\t}\n}\n\n\/\/ ComponentName returns a ClientOption that sets the component\n\/\/ name for the client-side span.\nfunc ComponentName(componentName string) ClientOption {\n\treturn func(options *clientOptions) {\n\t\toptions.componentName = componentName\n\t}\n}\n\n\/\/ ClientTrace returns a ClientOption that turns on or off\n\/\/ extra instrumentation via httptrace.WithClientTrace.\nfunc ClientTrace(enabled bool) ClientOption {\n\treturn func(options *clientOptions) {\n\t\toptions.disableClientTrace = !enabled\n\t}\n}\n\n\/\/ InjectSpanContext returns a ClientOption that turns on or off\n\/\/ injection of the Span context in the request HTTP headers.\n\/\/ If this option is not used, the default behaviour is to\n\/\/ inject the span context.\nfunc InjectSpanContext(enabled bool) ClientOption {\n\treturn func(options *clientOptions) {\n\t\toptions.disableInjectSpanContext = !enabled\n\t}\n}\n\n\/\/ ClientSpanObserver returns a ClientOption that observes the span\n\/\/ for the client-side span.\nfunc ClientSpanObserver(f func(span opentracing.Span, r *http.Request)) ClientOption {\n\treturn func(options *clientOptions) {\n\t\toptions.spanObserver = f\n\t}\n}\n\n\/\/ TraceRequest adds a ClientTracer to req, tracing the request and\n\/\/ all requests caused due to redirects. When tracing requests this\n\/\/ way you must also use Transport.\n\/\/\n\/\/ Example:\n\/\/\n\/\/ \tfunc AskGoogle(ctx context.Context) error {\n\/\/ \t\tclient := &http.Client{Transport: &nethttp.Transport{}}\n\/\/ \t\treq, err := http.NewRequest(\"GET\", \"http:\/\/google.com\", nil)\n\/\/ \t\tif err != nil {\n\/\/ \t\t\treturn err\n\/\/ \t\t}\n\/\/ \t\treq = req.WithContext(ctx) \/\/ extend existing trace, if any\n\/\/\n\/\/ \t\treq, ht := nethttp.TraceRequest(tracer, req)\n\/\/ \t\tdefer ht.Finish()\n\/\/\n\/\/ \t\tres, err := client.Do(req)\n\/\/ \t\tif err != nil {\n\/\/ \t\t\treturn err\n\/\/ \t\t}\n\/\/ \t\tres.Body.Close()\n\/\/ \t\treturn nil\n\/\/ \t}\nfunc TraceRequest(tr opentracing.Tracer, req *http.Request, options ...ClientOption) (*http.Request, *Tracer) {\n\topts := &clientOptions{\n\t\turlTagFunc: func(u *url.URL) string {\n\t\t\treturn u.String()\n\t\t},\n\t\tspanObserver: func(_ opentracing.Span, _ *http.Request) {},\n\t}\n\tfor _, opt := range options {\n\t\topt(opts)\n\t}\n\tht := &Tracer{tr: tr, opts: opts}\n\tctx := req.Context()\n\tif !opts.disableClientTrace {\n\t\tctx = httptrace.WithClientTrace(ctx, ht.clientTrace())\n\t}\n\treq = req.WithContext(context.WithValue(ctx, keyTracer, ht))\n\treturn req, ht\n}\n\ntype closeTracker struct {\n\tio.ReadCloser\n\tsp opentracing.Span\n}\n\nfunc (c closeTracker) Close() error {\n\terr := c.ReadCloser.Close()\n\tc.sp.LogFields(log.String(\"event\", \"ClosedBody\"))\n\tc.sp.Finish()\n\treturn err\n}\n\ntype writerCloseTracker struct {\n\tio.ReadWriteCloser\n\tsp opentracing.Span\n}\n\nfunc (c writerCloseTracker) Close() error {\n\terr := c.ReadWriteCloser.Close()\n\tc.sp.LogFields(log.String(\"event\", \"ClosedBody\"))\n\tc.sp.Finish()\n\treturn err\n}\n\n\/\/ TracerFromRequest retrieves the Tracer from the request. If the request does\n\/\/ not have a Tracer it will return nil.\nfunc TracerFromRequest(req *http.Request) *Tracer {\n\ttr, ok := req.Context().Value(keyTracer).(*Tracer)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn tr\n}\n\n\/\/ RoundTrip implements the RoundTripper interface.\nfunc (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {\n\trt := t.RoundTripper\n\tif rt == nil {\n\t\trt = http.DefaultTransport\n\t}\n\ttracer := TracerFromRequest(req)\n\tif tracer == nil {\n\t\treturn rt.RoundTrip(req)\n\t}\n\n\tsp := tracer.start(req)\n\n\text.HTTPMethod.Set(sp, req.Method)\n\text.HTTPUrl.Set(sp, tracer.opts.urlTagFunc(req.URL))\n\text.PeerAddress.Set(sp, req.URL.Host)\n\ttracer.opts.spanObserver(sp, req)\n\n\tif !tracer.opts.disableInjectSpanContext {\n\t\tcarrier := opentracing.HTTPHeadersCarrier(req.Header)\n\t\tsp.Tracer().Inject(sp.Context(), opentracing.HTTPHeaders, carrier)\n\t}\n\n\tresp, err := rt.RoundTrip(req)\n\n\tif err != nil {\n\t\tsp.Finish()\n\t\treturn resp, err\n\t}\n\text.HTTPStatusCode.Set(sp, uint16(resp.StatusCode))\n\tif resp.StatusCode >= http.StatusInternalServerError {\n\t\text.Error.Set(sp, true)\n\t}\n\tif req.Method == \"HEAD\" {\n\t\tsp.Finish()\n\t} else {\n\t\treadWriteCloser, ok := resp.Body.(io.ReadWriteCloser)\n\t\tif ok {\n\t\t\tresp.Body = writerCloseTracker{readWriteCloser, sp}\n\t\t} else {\n\t\t\tresp.Body = closeTracker{resp.Body, sp}\n\t\t}\n\t}\n\treturn resp, nil\n}\n\n\/\/ Tracer holds tracing details for one HTTP request.\ntype Tracer struct {\n\ttr   opentracing.Tracer\n\troot opentracing.Span\n\tsp   opentracing.Span\n\topts *clientOptions\n}\n\nfunc (h *Tracer) start(req *http.Request) opentracing.Span {\n\tif h.root == nil {\n\t\tparent := opentracing.SpanFromContext(req.Context())\n\t\tvar spanctx opentracing.SpanContext\n\t\tif parent != nil {\n\t\t\tspanctx = parent.Context()\n\t\t}\n\t\toperationName := h.opts.operationName\n\t\tif operationName == \"\" {\n\t\t\toperationName = \"HTTP Client\"\n\t\t}\n\t\troot := h.tr.StartSpan(operationName, opentracing.ChildOf(spanctx))\n\t\th.root = root\n\t}\n\n\tctx := h.root.Context()\n\th.sp = h.tr.StartSpan(\"HTTP \"+req.Method, opentracing.ChildOf(ctx), ext.SpanKindRPCClient)\n\n\tcomponentName := h.opts.componentName\n\tif componentName == \"\" {\n\t\tcomponentName = defaultComponentName\n\t}\n\text.Component.Set(h.sp, componentName)\n\n\treturn h.sp\n}\n\n\/\/ Finish finishes the span of the traced request.\nfunc (h *Tracer) Finish() {\n\tif h.root != nil {\n\t\th.root.Finish()\n\t}\n}\n\n\/\/ Span returns the root span of the traced request. This function\n\/\/ should only be called after the request has been executed.\nfunc (h *Tracer) Span() opentracing.Span {\n\treturn h.root\n}\n\nfunc (h *Tracer) clientTrace() *httptrace.ClientTrace {\n\treturn &httptrace.ClientTrace{\n\t\tGetConn:              h.getConn,\n\t\tGotConn:              h.gotConn,\n\t\tPutIdleConn:          h.putIdleConn,\n\t\tGotFirstResponseByte: h.gotFirstResponseByte,\n\t\tGot100Continue:       h.got100Continue,\n\t\tDNSStart:             h.dnsStart,\n\t\tDNSDone:              h.dnsDone,\n\t\tConnectStart:         h.connectStart,\n\t\tConnectDone:          h.connectDone,\n\t\tWroteHeaders:         h.wroteHeaders,\n\t\tWait100Continue:      h.wait100Continue,\n\t\tWroteRequest:         h.wroteRequest,\n\t}\n}\n\nfunc (h *Tracer) getConn(hostPort string) {\n\th.sp.LogFields(log.String(\"event\", \"GetConn\"), log.String(\"hostPort\", hostPort))\n}\n\nfunc (h *Tracer) gotConn(info httptrace.GotConnInfo) {\n\th.sp.SetTag(\"net\/http.reused\", info.Reused)\n\th.sp.SetTag(\"net\/http.was_idle\", info.WasIdle)\n\th.sp.LogFields(log.String(\"event\", \"GotConn\"))\n}\n\nfunc (h *Tracer) putIdleConn(error) {\n\th.sp.LogFields(log.String(\"event\", \"PutIdleConn\"))\n}\n\nfunc (h *Tracer) gotFirstResponseByte() {\n\th.sp.LogFields(log.String(\"event\", \"GotFirstResponseByte\"))\n}\n\nfunc (h *Tracer) got100Continue() {\n\th.sp.LogFields(log.String(\"event\", \"Got100Continue\"))\n}\n\nfunc (h *Tracer) dnsStart(info httptrace.DNSStartInfo) {\n\th.sp.LogFields(\n\t\tlog.String(\"event\", \"DNSStart\"),\n\t\tlog.String(\"host\", info.Host),\n\t)\n}\n\nfunc (h *Tracer) dnsDone(info httptrace.DNSDoneInfo) {\n\tfields := []log.Field{log.String(\"event\", \"DNSDone\")}\n\tfor _, addr := range info.Addrs {\n\t\tfields = append(fields, log.String(\"addr\", addr.String()))\n\t}\n\tif info.Err != nil {\n\t\tfields = append(fields, log.Error(info.Err))\n\t}\n\th.sp.LogFields(fields...)\n}\n\nfunc (h *Tracer) connectStart(network, addr string) {\n\th.sp.LogFields(\n\t\tlog.String(\"event\", \"ConnectStart\"),\n\t\tlog.String(\"network\", network),\n\t\tlog.String(\"addr\", addr),\n\t)\n}\n\nfunc (h *Tracer) connectDone(network, addr string, err error) {\n\tif err != nil {\n\t\th.sp.LogFields(\n\t\t\tlog.String(\"message\", \"ConnectDone\"),\n\t\t\tlog.String(\"network\", network),\n\t\t\tlog.String(\"addr\", addr),\n\t\t\tlog.String(\"event\", \"error\"),\n\t\t\tlog.Error(err),\n\t\t)\n\t} else {\n\t\th.sp.LogFields(\n\t\t\tlog.String(\"event\", \"ConnectDone\"),\n\t\t\tlog.String(\"network\", network),\n\t\t\tlog.String(\"addr\", addr),\n\t\t)\n\t}\n}\n\nfunc (h *Tracer) wroteHeaders() {\n\th.sp.LogFields(log.String(\"event\", \"WroteHeaders\"))\n}\n\nfunc (h *Tracer) wait100Continue() {\n\th.sp.LogFields(log.String(\"event\", \"Wait100Continue\"))\n}\n\nfunc (h *Tracer) wroteRequest(info httptrace.WroteRequestInfo) {\n\tif info.Err != nil {\n\t\th.sp.LogFields(\n\t\t\tlog.String(\"message\", \"WroteRequest\"),\n\t\t\tlog.String(\"event\", \"error\"),\n\t\t\tlog.Error(info.Err),\n\t\t)\n\t\text.Error.Set(h.sp, true)\n\t} else {\n\t\th.sp.LogFields(log.String(\"event\", \"WroteRequest\"))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/buildkite\/buildkite-metrics\/backend\"\n\t\"github.com\/buildkite\/buildkite-metrics\/collector\"\n\t\"github.com\/eawsy\/aws-lambda-go\/service\/lambda\/runtime\"\n\t\"gopkg.in\/buildkite\/go-buildkite.v2\/buildkite\"\n)\n\nfunc handle(evt json.RawMessage, ctx *runtime.Context) (interface{}, error) {\n\torg := os.Getenv(\"BUILDKITE_ORG\")\n\ttoken := os.Getenv(\"BUILDKITE_TOKEN\")\n\tbackendOpt := os.Getenv(\"BUILDKITE_BACKEND\")\n\tqueue := os.Getenv(\"BUILDKITE_QUEUE\")\n\tquiet := os.Getenv(\"BUILDKITE_QUIET\")\n\n\tif quiet == \"1\" || quiet == \"false\" {\n\t\tlog.SetOutput(ioutil.Discard)\n\t}\n\n\tconfig, err := buildkite.NewTokenConfig(token, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := buildkite.NewClient(config.Client())\n\tt := time.Now()\n\n\tcol := collector.New(client, collector.Opts{\n\t\tOrgSlug:    org,\n\t\tHistorical: time.Hour * 24,\n\t})\n\n\tif queue != \"\" {\n\t\tcol.Queue = queue\n\t}\n\n\tvar bk backend.Backend\n\tif backendOpt == \"statsd\" {\n\t\tbk, err = backend.NewStatsDBackend(os.Getenv(\"STATSD_HOST\"), strings.ToLower(os.Getenv(\"STATSD_TAGS\")) == \"true\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tbk = &backend.CloudWatchBackend{}\n\t}\n\n\tres, err := col.Collect()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres.Dump()\n\n\terr = bk.Collect(res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Printf(\"Finished in %s\", time.Now().Sub(t))\n\treturn \"\", nil\n}\n\nfunc init() {\n\truntime.HandleFunc(handle)\n}\n<commit_msg>Add retry for failed bk calls to lambda<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/buildkite\/buildkite-metrics\/backend\"\n\t\"github.com\/buildkite\/buildkite-metrics\/collector\"\n\t\"github.com\/eawsy\/aws-lambda-go\/service\/lambda\/runtime\"\n\t\"gopkg.in\/buildkite\/go-buildkite.v2\/buildkite\"\n)\n\nfunc handle(evt json.RawMessage, ctx *runtime.Context) (interface{}, error) {\n\torg := os.Getenv(\"BUILDKITE_ORG\")\n\ttoken := os.Getenv(\"BUILDKITE_TOKEN\")\n\tbackendOpt := os.Getenv(\"BUILDKITE_BACKEND\")\n\tqueue := os.Getenv(\"BUILDKITE_QUEUE\")\n\tquiet := os.Getenv(\"BUILDKITE_QUIET\")\n\n\tif quiet == \"1\" || quiet == \"false\" {\n\t\tlog.SetOutput(ioutil.Discard)\n\t}\n\n\tconfig, err := buildkite.NewTokenConfig(token, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := buildkite.NewClient(config.Client())\n\tt := time.Now()\n\n\tcol := collector.New(client, collector.Opts{\n\t\tOrgSlug:    org,\n\t\tHistorical: time.Hour * 24,\n\t})\n\n\tif queue != \"\" {\n\t\tcol.Queue = queue\n\t}\n\n\tvar bk backend.Backend\n\tif backendOpt == \"statsd\" {\n\t\tbk, err = backend.NewStatsDBackend(os.Getenv(\"STATSD_HOST\"), strings.ToLower(os.Getenv(\"STATSD_TAGS\")) == \"true\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tbk = &backend.CloudWatchBackend{}\n\t}\n\n\treturn \"\", retry(time.Minute, func() error {\n\t\tres, err := col.Collect()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tres.Dump()\n\n\t\terr = bk.Collect(res)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Printf(\"Finished in %s\", time.Now().Sub(t))\n\t\treturn nil\n\t})\n}\n\nfunc retry(timeout time.Duration, callback func() error) (err error) {\n\tt0 := time.Now()\n\ti := 0\n\tfor {\n\t\ti++\n\n\t\terr = callback()\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\n\t\tdelta := time.Now().Sub(t0)\n\t\tif delta > timeout {\n\t\t\treturn fmt.Errorf(\"after %d attempts (during %s), last error: %s\", i, delta, err)\n\t\t}\n\n\t\ttime.Sleep(time.Second * 2)\n\t\tlog.Println(\"retrying after error:\", err)\n\t}\n}\n\nfunc init() {\n\truntime.HandleFunc(handle)\n}\n<|endoftext|>"}
{"text":"<commit_before>package peco\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\t\"unicode\/utf8\"\n\n\t\"github.com\/mattn\/go-runewidth\"\n\t\"github.com\/nsf\/termbox-go\"\n)\n\ntype Layout interface {\n\tClearStatus(time.Duration)\n\tPrintStatus(string)\n\tDrawScreen([]Match)\n}\n\n\/\/ Utility function\nfunc mergeAttribute(a, b termbox.Attribute) termbox.Attribute {\n\tif a&0x0F == 0 || b&0x0F == 0 {\n\t\treturn a | b\n\t} else {\n\t\treturn ((a - 1) | (b - 1)) + 1\n\t}\n}\n\n\/\/ Utility function\nfunc printScreen(x, y int, fg, bg termbox.Attribute, msg string, fill bool) {\n\tfor len(msg) > 0 {\n\t\tc, w := utf8.DecodeRuneInString(msg)\n\t\tif c == utf8.RuneError {\n\t\t\tc = '?'\n\t\t\tw = 1\n\t\t}\n\t\tmsg = msg[w:]\n\t\ttermbox.SetCell(x, y, c, fg, bg)\n\t\tx += runewidth.RuneWidth(c)\n\t}\n\n\tif !fill {\n\t\treturn\n\t}\n\n\twidth, _ := termbox.Size()\n\tfor ; x < width; x++ {\n\t\ttermbox.SetCell(x, y, ' ', fg, bg)\n\t}\n}\n\n\/\/ UserPrompt draws the prompt line\ntype UserPrompt struct {\n\t*Ctx\n\tprefix string\n\tprefixLen int\n}\n\nfunc NewUserPrompt(ctx *Ctx) *UserPrompt {\n\tprefix := ctx.config.Prompt\n\tif len(prefix) <= 0 { \/\/ default\n\t\tprefix = \"QUERY>\"\n\t}\n\tprefixLen := runewidth.StringWidth(prefix)\n\n\treturn &UserPrompt{\n\t\tCtx: ctx,\n\t\tprefix:    prefix,\n\t\tprefixLen: prefixLen,\n\t}\n}\n\nfunc (u UserPrompt) Draw() {\n\t\/\/ print \"QUERY>\"\n\tprintScreen(0, 0, u.config.Style.BasicFG(), u.config.Style.BasicBG(), u.prefix, false)\n\n\tif u.caretPos <= 0 {\n\t\tu.caretPos = 0 \/\/ sanity\n\t}\n\n\tif u.caretPos > len(u.query) {\n\t\tu.caretPos = len(u.query)\n\t}\n\n\tif u.caretPos == len(u.query) {\n\t\t\/\/ the entire string + the caret after the string\n\t\tfg := u.config.Style.QueryFG()\n\t\tbg := u.config.Style.QueryBG()\n\t\tqs := string(u.query)\n\t\tql := runewidth.StringWidth(qs)\n\t\tprintScreen(u.prefixLen+1, 0, fg, bg, qs, false)\n\t\tprintScreen(u.prefixLen+1+ql, 0, fg|termbox.AttrReverse, bg|termbox.AttrReverse, \" \", false)\n\t\tprintScreen(u.prefixLen+1+ql+1, 0, fg, bg, \"\", true)\n\t} else {\n\t\t\/\/ the caret is in the middle of the string\n\t\tprev := 0\n\t\tfg := u.config.Style.QueryFG()\n\t\tbg := u.config.Style.QueryBG()\n\t\tfor i, r := range u.query {\n\t\t\tif i == u.caretPos {\n\t\t\t\tfg |= termbox.AttrReverse\n\t\t\t\tbg |= termbox.AttrReverse\n\t\t\t}\n\t\t\ttermbox.SetCell(u.prefixLen+1+prev, 0, r, fg, bg)\n\t\t\tprev += runewidth.RuneWidth(r)\n\t\t}\n\t}\n\n\twidth, _ := termbox.Size()\n\n\tpmsg := fmt.Sprintf(\"%s [%d\/%d]\", u.Matcher().String(), u.currentPage.index, u.maxPage)\n\tprintScreen(width-runewidth.StringWidth(pmsg), 0, u.config.Style.BasicFG(), u.config.Style.BasicBG(), pmsg, false)\n}\n\n\/\/ StatusBar draws the status message bar\ntype StatusBar struct {\n\t*Ctx\n\tclearTimer *time.Timer\n}\n\nfunc NewStatusBar(ctx *Ctx) *StatusBar {\n\treturn &StatusBar{\n\t\tctx,\n\t\tnil,\n\t}\n}\n\nfunc (s *StatusBar) stopTimer() {\n\tif t := s.clearTimer; t != nil {\n\t\tt.Stop()\n\t}\n}\n\nfunc (s *StatusBar) ClearStatus(d time.Duration) {\n\ts.stopTimer()\n\ts.clearTimer = time.AfterFunc(d, func() {\n\t\ts.PrintStatus(\"\")\n\t})\n}\n\nfunc (s *StatusBar) PrintStatus(msg string) {\n\ts.stopTimer()\n\n\tw, h := termbox.Size()\n\n\twidth := runewidth.StringWidth(msg)\n\tfor width > w {\n\t\t_, rw := utf8.DecodeRuneInString(msg)\n\t\twidth = width - rw\n\t\tmsg = msg[rw:]\n\t}\n\n\tvar pad []byte\n\tif w > width {\n\t\tpad = make([]byte, w-width)\n\t\tfor i := 0; i < w-width; i++ {\n\t\t\tpad[i] = ' '\n\t\t}\n\t}\n\n\tfgAttr := s.config.Style.BasicFG()\n\tbgAttr := s.config.Style.BasicBG()\n\n\tif w > width {\n\t\tprintScreen(0, h-2, fgAttr, bgAttr, string(pad), false)\n\t}\n\n\tif width > 0 {\n\t\tprintScreen(w-width, h-2, fgAttr|termbox.AttrReverse|termbox.AttrBold, bgAttr|termbox.AttrReverse, msg, false)\n\t}\n\ttermbox.Flush()\n}\n\ntype basicLayout struct {\n\t*Ctx\n\t*StatusBar\n\t*UserPrompt\n}\n\n\/\/ DefaultLayout implements the top-down layout\ntype DefaultLayout struct {\n\t*basicLayout\n}\ntype BottomUpLayout struct {\n\t*basicLayout\n}\n\nfunc NewDefaultLayout(ctx *Ctx) *DefaultLayout {\n\treturn &DefaultLayout{\n\t\t&basicLayout{\n\t\t\tCtx: ctx,\n\t\t\tStatusBar: NewStatusBar(ctx),\n\t\t\tUserPrompt: NewUserPrompt(ctx),\n\t\t},\n\t}\n}\n\nfunc (l *DefaultLayout) DrawScreen(targets []Match) {\n\tfgAttr := l.config.Style.BasicFG()\n\tbgAttr := l.config.Style.BasicBG()\n\n\tif err := termbox.Clear(fgAttr, bgAttr); err != nil {\n\t\treturn\n\t}\n\n\tif l.currentLine > len(targets) && len(targets) > 0 {\n\t\tl.currentLine = len(targets)\n\t}\n\n\t_, height := termbox.Size()\n\tperPage := height - 4\n\nCALCULATE_PAGE:\n\tcurrentPage := l.currentPage\n\tcurrentPage.index = ((l.currentLine - 1) \/ perPage) + 1\n\tif currentPage.index <= 0 {\n\t\tcurrentPage.index = 1\n\t}\n\tcurrentPage.offset = (currentPage.index - 1) * perPage\n\tcurrentPage.perPage = perPage\n\tif len(targets) == 0 {\n\t\tl.maxPage = 1\n\t} else {\n\t\tl.maxPage = ((len(targets) + perPage - 1) \/ perPage)\n\t}\n\n\tif l.maxPage < currentPage.index {\n\t\tif len(targets) == 0 && len(l.query) == 0 {\n\t\t\t\/\/ wait for targets\n\t\t\treturn\n\t\t}\n\t\tl.currentLine = currentPage.offset\n\t\tgoto CALCULATE_PAGE\n\t}\n\n\tl.UserPrompt.Draw()\n\n\tfor n := 1; n <= perPage; n++ {\n\t\tswitch {\n\t\tcase n+currentPage.offset == l.currentLine:\n\t\t\tfgAttr = l.config.Style.SelectedFG()\n\t\t\tbgAttr = l.config.Style.SelectedBG()\n\t\tcase l.selection.Has(n+currentPage.offset) || l.SelectedRange().Has(n+currentPage.offset):\n\t\t\tfgAttr = l.config.Style.SavedSelectionFG()\n\t\t\tbgAttr = l.config.Style.SavedSelectionBG()\n\t\tdefault:\n\t\t\tfgAttr = l.config.Style.BasicFG()\n\t\t\tbgAttr = l.config.Style.BasicBG()\n\t\t}\n\n\t\ttargetIdx := currentPage.offset + n - 1\n\t\tif targetIdx >= len(targets) {\n\t\t\tbreak\n\t\t}\n\n\t\ttarget := targets[targetIdx]\n\t\tline := target.Line()\n\t\tmatches := target.Indices()\n\t\tif matches == nil {\n\t\t\tprintScreen(0, n, fgAttr, bgAttr, line, true)\n\t\t} else {\n\t\t\tprev := 0\n\t\t\tindex := 0\n\t\t\tfor _, m := range matches {\n\t\t\t\tif m[0] > index {\n\t\t\t\t\tc := line[index:m[0]]\n\t\t\t\t\tprintScreen(prev, n, fgAttr, bgAttr, c, false)\n\t\t\t\t\tprev += runewidth.StringWidth(c)\n\t\t\t\t\tindex += len(c)\n\t\t\t\t}\n\t\t\t\tc := line[m[0]:m[1]]\n\t\t\t\tprintScreen(prev, n, l.config.Style.MatchedFG(), mergeAttribute(bgAttr, l.config.Style.MatchedBG()), c, true)\n\t\t\t\tprev += runewidth.StringWidth(c)\n\t\t\t\tindex += len(c)\n\t\t\t}\n\n\t\t\tm := matches[len(matches)-1]\n\t\t\tif m[0] > index {\n\t\t\t\tprintScreen(prev, n, l.config.Style.QueryFG(), mergeAttribute(bgAttr, l.config.Style.QueryBG()), line[m[0]:m[1]], true)\n\t\t\t} else if len(line) > m[1] {\n\t\t\t\tprintScreen(prev, n, fgAttr, bgAttr, line[m[1]:len(line)], true)\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := termbox.Flush(); err != nil {\n\t\treturn\n\t}\n}\n<commit_msg>rip out page calculation<commit_after>package peco\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\t\"unicode\/utf8\"\n\n\t\"github.com\/mattn\/go-runewidth\"\n\t\"github.com\/nsf\/termbox-go\"\n)\n\ntype Layout interface {\n\tClearStatus(time.Duration)\n\tPrintStatus(string)\n\tDrawScreen([]Match)\n}\n\n\/\/ Utility function\nfunc mergeAttribute(a, b termbox.Attribute) termbox.Attribute {\n\tif a&0x0F == 0 || b&0x0F == 0 {\n\t\treturn a | b\n\t} else {\n\t\treturn ((a - 1) | (b - 1)) + 1\n\t}\n}\n\n\/\/ Utility function\nfunc printScreen(x, y int, fg, bg termbox.Attribute, msg string, fill bool) {\n\tfor len(msg) > 0 {\n\t\tc, w := utf8.DecodeRuneInString(msg)\n\t\tif c == utf8.RuneError {\n\t\t\tc = '?'\n\t\t\tw = 1\n\t\t}\n\t\tmsg = msg[w:]\n\t\ttermbox.SetCell(x, y, c, fg, bg)\n\t\tx += runewidth.RuneWidth(c)\n\t}\n\n\tif !fill {\n\t\treturn\n\t}\n\n\twidth, _ := termbox.Size()\n\tfor ; x < width; x++ {\n\t\ttermbox.SetCell(x, y, ' ', fg, bg)\n\t}\n}\n\n\/\/ UserPrompt draws the prompt line\ntype UserPrompt struct {\n\t*Ctx\n\tprefix string\n\tprefixLen int\n}\n\nfunc NewUserPrompt(ctx *Ctx) *UserPrompt {\n\tprefix := ctx.config.Prompt\n\tif len(prefix) <= 0 { \/\/ default\n\t\tprefix = \"QUERY>\"\n\t}\n\tprefixLen := runewidth.StringWidth(prefix)\n\n\treturn &UserPrompt{\n\t\tCtx: ctx,\n\t\tprefix:    prefix,\n\t\tprefixLen: prefixLen,\n\t}\n}\n\nfunc (u UserPrompt) Draw() {\n\t\/\/ print \"QUERY>\"\n\tprintScreen(0, 0, u.config.Style.BasicFG(), u.config.Style.BasicBG(), u.prefix, false)\n\n\tif u.caretPos <= 0 {\n\t\tu.caretPos = 0 \/\/ sanity\n\t}\n\n\tif u.caretPos > len(u.query) {\n\t\tu.caretPos = len(u.query)\n\t}\n\n\tif u.caretPos == len(u.query) {\n\t\t\/\/ the entire string + the caret after the string\n\t\tfg := u.config.Style.QueryFG()\n\t\tbg := u.config.Style.QueryBG()\n\t\tqs := string(u.query)\n\t\tql := runewidth.StringWidth(qs)\n\t\tprintScreen(u.prefixLen+1, 0, fg, bg, qs, false)\n\t\tprintScreen(u.prefixLen+1+ql, 0, fg|termbox.AttrReverse, bg|termbox.AttrReverse, \" \", false)\n\t\tprintScreen(u.prefixLen+1+ql+1, 0, fg, bg, \"\", true)\n\t} else {\n\t\t\/\/ the caret is in the middle of the string\n\t\tprev := 0\n\t\tfg := u.config.Style.QueryFG()\n\t\tbg := u.config.Style.QueryBG()\n\t\tfor i, r := range u.query {\n\t\t\tif i == u.caretPos {\n\t\t\t\tfg |= termbox.AttrReverse\n\t\t\t\tbg |= termbox.AttrReverse\n\t\t\t}\n\t\t\ttermbox.SetCell(u.prefixLen+1+prev, 0, r, fg, bg)\n\t\t\tprev += runewidth.RuneWidth(r)\n\t\t}\n\t}\n\n\twidth, _ := termbox.Size()\n\n\tpmsg := fmt.Sprintf(\"%s [%d\/%d]\", u.Matcher().String(), u.currentPage.index, u.maxPage)\n\tprintScreen(width-runewidth.StringWidth(pmsg), 0, u.config.Style.BasicFG(), u.config.Style.BasicBG(), pmsg, false)\n}\n\n\/\/ StatusBar draws the status message bar\ntype StatusBar struct {\n\t*Ctx\n\tclearTimer *time.Timer\n}\n\nfunc NewStatusBar(ctx *Ctx) *StatusBar {\n\treturn &StatusBar{\n\t\tctx,\n\t\tnil,\n\t}\n}\n\nfunc (s *StatusBar) stopTimer() {\n\tif t := s.clearTimer; t != nil {\n\t\tt.Stop()\n\t}\n}\n\nfunc (s *StatusBar) ClearStatus(d time.Duration) {\n\ts.stopTimer()\n\ts.clearTimer = time.AfterFunc(d, func() {\n\t\ts.PrintStatus(\"\")\n\t})\n}\n\nfunc (s *StatusBar) PrintStatus(msg string) {\n\ts.stopTimer()\n\n\tw, h := termbox.Size()\n\n\twidth := runewidth.StringWidth(msg)\n\tfor width > w {\n\t\t_, rw := utf8.DecodeRuneInString(msg)\n\t\twidth = width - rw\n\t\tmsg = msg[rw:]\n\t}\n\n\tvar pad []byte\n\tif w > width {\n\t\tpad = make([]byte, w-width)\n\t\tfor i := 0; i < w-width; i++ {\n\t\t\tpad[i] = ' '\n\t\t}\n\t}\n\n\tfgAttr := s.config.Style.BasicFG()\n\tbgAttr := s.config.Style.BasicBG()\n\n\tif w > width {\n\t\tprintScreen(0, h-2, fgAttr, bgAttr, string(pad), false)\n\t}\n\n\tif width > 0 {\n\t\tprintScreen(w-width, h-2, fgAttr|termbox.AttrReverse|termbox.AttrBold, bgAttr|termbox.AttrReverse, msg, false)\n\t}\n\ttermbox.Flush()\n}\n\ntype basicLayout struct {\n\t*Ctx\n\t*StatusBar\n\t*UserPrompt\n}\n\n\/\/ DefaultLayout implements the top-down layout\ntype DefaultLayout struct {\n\t*basicLayout\n}\ntype BottomUpLayout struct {\n\t*basicLayout\n}\n\nfunc NewDefaultLayout(ctx *Ctx) *DefaultLayout {\n\treturn &DefaultLayout{\n\t\t&basicLayout{\n\t\t\tCtx: ctx,\n\t\t\tStatusBar: NewStatusBar(ctx),\n\t\t\tUserPrompt: NewUserPrompt(ctx),\n\t\t},\n\t}\n}\n\nfunc (l *DefaultLayout) CalculatePage(targets []Match, perPage int) error {\nCALCULATE_PAGE:\n\tcurrentPage := l.currentPage\n\tcurrentPage.index = ((l.currentLine - 1) \/ perPage) + 1\n\tif currentPage.index <= 0 {\n\t\tcurrentPage.index = 1\n\t}\n\tcurrentPage.offset = (currentPage.index - 1) * perPage\n\tcurrentPage.perPage = perPage\n\tif len(targets) == 0 {\n\t\tl.maxPage = 1\n\t} else {\n\t\tl.maxPage = ((len(targets) + perPage - 1) \/ perPage)\n\t}\n\n\tif l.maxPage < currentPage.index {\n\t\tif len(targets) == 0 && len(l.query) == 0 {\n\t\t\t\/\/ wait for targets\n\t\t\treturn fmt.Errorf(\"no targets or query. nothing to do\")\n\t\t}\n\t\tl.currentLine = currentPage.offset\n\t\tgoto CALCULATE_PAGE\n\t}\n\n\treturn nil\n}\n\nfunc (l *DefaultLayout) DrawScreen(targets []Match) {\n\tfgAttr := l.config.Style.BasicFG()\n\tbgAttr := l.config.Style.BasicBG()\n\n\tif err := termbox.Clear(fgAttr, bgAttr); err != nil {\n\t\treturn\n\t}\n\n\tif l.currentLine > len(targets) && len(targets) > 0 {\n\t\tl.currentLine = len(targets)\n\t}\n\n\t_, height := termbox.Size()\n\tperPage := height - 4\n\n\tif err := l.CalculatePage(targets, perPage); err != nil {\n\t\treturn\n\t}\n\n\tl.UserPrompt.Draw()\n\tcurrentPage := l.currentPage\n\n\tfor n := 1; n <= perPage; n++ {\n\t\tswitch {\n\t\tcase n+currentPage.offset == l.currentLine:\n\t\t\tfgAttr = l.config.Style.SelectedFG()\n\t\t\tbgAttr = l.config.Style.SelectedBG()\n\t\tcase l.selection.Has(n+currentPage.offset) || l.SelectedRange().Has(n+currentPage.offset):\n\t\t\tfgAttr = l.config.Style.SavedSelectionFG()\n\t\t\tbgAttr = l.config.Style.SavedSelectionBG()\n\t\tdefault:\n\t\t\tfgAttr = l.config.Style.BasicFG()\n\t\t\tbgAttr = l.config.Style.BasicBG()\n\t\t}\n\n\t\ttargetIdx := currentPage.offset + n - 1\n\t\tif targetIdx >= len(targets) {\n\t\t\tbreak\n\t\t}\n\n\t\ttarget := targets[targetIdx]\n\t\tline := target.Line()\n\t\tmatches := target.Indices()\n\t\tif matches == nil {\n\t\t\tprintScreen(0, n, fgAttr, bgAttr, line, true)\n\t\t} else {\n\t\t\tprev := 0\n\t\t\tindex := 0\n\t\t\tfor _, m := range matches {\n\t\t\t\tif m[0] > index {\n\t\t\t\t\tc := line[index:m[0]]\n\t\t\t\t\tprintScreen(prev, n, fgAttr, bgAttr, c, false)\n\t\t\t\t\tprev += runewidth.StringWidth(c)\n\t\t\t\t\tindex += len(c)\n\t\t\t\t}\n\t\t\t\tc := line[m[0]:m[1]]\n\t\t\t\tprintScreen(prev, n, l.config.Style.MatchedFG(), mergeAttribute(bgAttr, l.config.Style.MatchedBG()), c, true)\n\t\t\t\tprev += runewidth.StringWidth(c)\n\t\t\t\tindex += len(c)\n\t\t\t}\n\n\t\t\tm := matches[len(matches)-1]\n\t\t\tif m[0] > index {\n\t\t\t\tprintScreen(prev, n, l.config.Style.QueryFG(), mergeAttribute(bgAttr, l.config.Style.QueryBG()), line[m[0]:m[1]], true)\n\t\t\t} else if len(line) > m[1] {\n\t\t\t\tprintScreen(prev, n, fgAttr, bgAttr, line[m[1]:len(line)], true)\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := termbox.Flush(); err != nil {\n\t\treturn\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *\n * Copyright 2014, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\npackage grpc\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\/credentials\"\n\t\"google.golang.org\/grpc\/grpclog\"\n\t\"google.golang.org\/grpc\/transport\"\n)\n\nvar (\n\t\/\/ ErrUnspecTarget indicates that the target address is unspecified.\n\tErrUnspecTarget = errors.New(\"grpc: target is unspecified\")\n\t\/\/ ErrNoTransportSecurity indicates that there is no transport security\n\t\/\/ being set for ClientConn. Users should either set one or explicityly\n\t\/\/ call WithInsecure DialOption to disable security.\n\tErrNoTransportSecurity = errors.New(\"grpc: no transport security set (use grpc.WithInsecure() explicitly or set credentials)\")\n\t\/\/ ErrCredentialsMisuse indicates that users want to transmit security infomation\n\t\/\/ (e.g., oauth2 token) which requires secure connection on an insecure\n\t\/\/ connection.\n\tErrCredentialsMisuse = errors.New(\"grpc: the credentials require transport level security (use grpc.WithTransportAuthenticator() to set)\")\n\t\/\/ ErrClientConnClosing indicates that the operation is illegal because\n\t\/\/ the session is closing.\n\tErrClientConnClosing = errors.New(\"grpc: the client connection is closing\")\n\t\/\/ ErrClientConnTimeout indicates that the connection could not be\n\t\/\/ established or re-established within the specified timeout.\n\tErrClientConnTimeout = errors.New(\"grpc: timed out trying to connect\")\n\t\/\/ minimum time to give a connection to complete\n\tminConnectTimeout = 20 * time.Second\n)\n\n\/\/ dialOptions configure a Dial call. dialOptions are set by the DialOption\n\/\/ values passed to Dial.\ntype dialOptions struct {\n\tcodec    Codec\n\tblock    bool\n\tinsecure bool\n\tcopts    transport.ConnectOptions\n}\n\n\/\/ DialOption configures how we set up the connection.\ntype DialOption func(*dialOptions)\n\n\/\/ WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling.\nfunc WithCodec(c Codec) DialOption {\n\treturn func(o *dialOptions) {\n\t\to.codec = c\n\t}\n}\n\n\/\/ WithBlock returns a DialOption which makes caller of Dial blocks until the underlying\n\/\/ connection is up. Without this, Dial returns immediately and connecting the server\n\/\/ happens in background.\nfunc WithBlock() DialOption {\n\treturn func(o *dialOptions) {\n\t\to.block = true\n\t}\n}\n\nfunc WithInsecure() DialOption {\n\treturn func(o *dialOptions) {\n\t\to.insecure = true\n\t}\n}\n\n\/\/ WithTransportCredentials returns a DialOption which configures a\n\/\/ connection level security credentials (e.g., TLS\/SSL).\nfunc WithTransportCredentials(creds credentials.TransportAuthenticator) DialOption {\n\treturn func(o *dialOptions) {\n\t\to.copts.AuthOptions = append(o.copts.AuthOptions, creds)\n\t}\n}\n\n\/\/ WithPerRPCCredentials returns a DialOption which sets\n\/\/ credentials which will place auth state on each outbound RPC.\nfunc WithPerRPCCredentials(creds credentials.Credentials) DialOption {\n\treturn func(o *dialOptions) {\n\t\to.copts.AuthOptions = append(o.copts.AuthOptions, creds)\n\t}\n}\n\n\/\/ WithTimeout returns a DialOption that configures a timeout for dialing a client connection.\nfunc WithTimeout(d time.Duration) DialOption {\n\treturn func(o *dialOptions) {\n\t\to.copts.Timeout = d\n\t}\n}\n\n\/\/ WithDialer returns a DialOption that specifies a function to use for dialing network addresses.\nfunc WithDialer(f func(addr string, timeout time.Duration) (net.Conn, error)) DialOption {\n\treturn func(o *dialOptions) {\n\t\to.copts.Dialer = f\n\t}\n}\n\n\/\/ WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs.\nfunc WithUserAgent(s string) DialOption {\n\treturn func(o *dialOptions) {\n\t\to.copts.UserAgent = s\n\t}\n}\n\n\/\/ Dial creates a client connection the given target.\nfunc Dial(target string, opts ...DialOption) (*ClientConn, error) {\n\tif target == \"\" {\n\t\treturn nil, ErrUnspecTarget\n\t}\n\tcc := &ClientConn{\n\t\ttarget:       target,\n\t\tshutdownChan: make(chan struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(&cc.dopts)\n\t}\n\tif !cc.dopts.insecure {\n\t\tvar ok bool\n\t\tfor _, c := range cc.dopts.copts.AuthOptions {\n\t\t\tif _, ok := c.(credentials.TransportAuthenticator); !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tok = true\n\t\t}\n\t\tif !ok {\n\t\t\treturn nil, ErrNoTransportSecurity\n\t\t}\n\t} else {\n\t\tfor _, c := range cc.dopts.copts.AuthOptions {\n\t\t\tif c.RequireTransportSecurity() {\n\t\t\t\treturn nil, ErrCredentialsMisuse\n\t\t\t}\n\t\t}\n\t}\n\tcolonPos := strings.LastIndex(target, \":\")\n\tif colonPos == -1 {\n\t\tcolonPos = len(target)\n\t}\n\tcc.authority = target[:colonPos]\n\tif cc.dopts.codec == nil {\n\t\t\/\/ Set the default codec.\n\t\tcc.dopts.codec = protoCodec{}\n\t}\n\tcc.stateCV = sync.NewCond(&cc.mu)\n\tif cc.dopts.block {\n\t\tif err := cc.resetTransport(false); err != nil {\n\t\t\tcc.Close()\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ Start to monitor the error status of transport.\n\t\tgo cc.transportMonitor()\n\t} else {\n\t\t\/\/ Start a goroutine connecting to the server asynchronously.\n\t\tgo func() {\n\t\t\tif err := cc.resetTransport(false); err != nil {\n\t\t\t\tgrpclog.Printf(\"Failed to dial %s: %v; please retry.\", target, err)\n\t\t\t\tcc.Close()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tgo cc.transportMonitor()\n\t\t}()\n\t}\n\treturn cc, nil\n}\n\n\/\/ ConnectivityState indicates the state of a client connection.\ntype ConnectivityState int\n\nconst (\n\t\/\/ Idle indicates the ClientConn is idle.\n\tIdle ConnectivityState = iota\n\t\/\/ Connecting indicates the ClienConn is connecting.\n\tConnecting\n\t\/\/ Ready indicates the ClientConn is ready for work.\n\tReady\n\t\/\/ TransientFailure indicates the ClientConn has seen a failure but expects to recover.\n\tTransientFailure\n\t\/\/ Shutdown indicates the ClientConn has stated shutting down.\n\tShutdown\n)\n\nfunc (s ConnectivityState) String() string {\n\tswitch s {\n\tcase Idle:\n\t\treturn \"IDLE\"\n\tcase Connecting:\n\t\treturn \"CONNECTING\"\n\tcase Ready:\n\t\treturn \"READY\"\n\tcase TransientFailure:\n\t\treturn \"TRANSIENT_FAILURE\"\n\tcase Shutdown:\n\t\treturn \"SHUTDOWN\"\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unknown connectivity state: %d\", s))\n\t}\n}\n\n\/\/ ClientConn represents a client connection to an RPC service.\ntype ClientConn struct {\n\ttarget       string\n\tauthority    string\n\tdopts        dialOptions\n\tshutdownChan chan struct{}\n\n\tmu      sync.Mutex\n\tstate   ConnectivityState\n\tstateCV *sync.Cond\n\t\/\/ ready is closed and becomes nil when a new transport is up or failed\n\t\/\/ due to timeout.\n\tready chan struct{}\n\t\/\/ Every time a new transport is created, this is incremented by 1. Used\n\t\/\/ to avoid trying to recreate a transport while the new one is already\n\t\/\/ under construction.\n\ttransportSeq int\n\ttransport    transport.ClientTransport\n}\n\n\/\/ State returns the connectivity state of the ClientConn\nfunc (cc *ClientConn) State() ConnectivityState {\n\tcc.mu.Lock()\n\tdefer cc.mu.Unlock()\n\treturn cc.state\n}\n\n\/\/ WaitForStateChange blocks until the state changes to something other than the sourceState\n\/\/ or timeout fires. It returns false if timeout fires and true otherwise.\nfunc (cc *ClientConn) WaitForStateChange(timeout time.Duration, sourceState ConnectivityState) bool {\n\tstart := time.Now()\n\tcc.mu.Lock()\n\tdefer cc.mu.Unlock()\n\tif sourceState != cc.state {\n\t\treturn true\n\t}\n\texpired := timeout <= time.Since(start)\n\tif expired {\n\t\treturn false\n\t}\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tselect {\n\t\tcase <-time.After(timeout - time.Since(start)):\n\t\t\tcc.mu.Lock()\n\t\t\texpired = true\n\t\t\tcc.stateCV.Broadcast()\n\t\t\tcc.mu.Unlock()\n\t\tcase <-done:\n\t\t}\n\t}()\n\tdefer close(done)\n\tfor sourceState == cc.state {\n\t\tcc.stateCV.Wait()\n\t\tif expired {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (cc *ClientConn) resetTransport(closeTransport bool) error {\n\tvar retries int\n\tstart := time.Now()\n\tfor {\n\t\tcc.mu.Lock()\n\t\tcc.state = Connecting\n\t\tcc.stateCV.Broadcast()\n\t\tt := cc.transport\n\t\tts := cc.transportSeq\n\t\t\/\/ Avoid wait() picking up a dying transport unnecessarily.\n\t\tcc.transportSeq = 0\n\t\tif cc.state == Shutdown {\n\t\t\tcc.mu.Unlock()\n\t\t\treturn ErrClientConnClosing\n\t\t}\n\t\tcc.mu.Unlock()\n\t\tif closeTransport {\n\t\t\tt.Close()\n\t\t}\n\t\t\/\/ Adjust timeout for the current try.\n\t\tcopts := cc.dopts.copts\n\t\tif copts.Timeout < 0 {\n\t\t\tcc.Close()\n\t\t\treturn ErrClientConnTimeout\n\t\t}\n\t\tif copts.Timeout > 0 {\n\t\t\tcopts.Timeout -= time.Since(start)\n\t\t\tif copts.Timeout <= 0 {\n\t\t\t\tcc.Close()\n\t\t\t\treturn ErrClientConnTimeout\n\t\t\t}\n\t\t}\n\t\tsleepTime := backoff(retries)\n\t\ttimeout := sleepTime\n\t\tif timeout < minConnectTimeout {\n\t\t\ttimeout = minConnectTimeout\n\t\t}\n\t\tif copts.Timeout == 0 || copts.Timeout > timeout {\n\t\t\tcopts.Timeout = timeout\n\t\t}\n\t\tconnectTime := time.Now()\n\t\tnewTransport, err := transport.NewClientTransport(cc.target, &copts)\n\t\tif err != nil {\n\t\t\tcc.mu.Lock()\n\t\t\tcc.state = TransientFailure\n\t\t\tcc.stateCV.Broadcast()\n\t\t\tcc.mu.Unlock()\n\t\t\tsleepTime -= time.Since(connectTime)\n\t\t\tif sleepTime < 0 {\n\t\t\t\tsleepTime = 0\n\t\t\t}\n\t\t\t\/\/ Fail early before falling into sleep.\n\t\t\tif cc.dopts.copts.Timeout > 0 && cc.dopts.copts.Timeout < sleepTime+time.Since(start) {\n\t\t\t\tcc.Close()\n\t\t\t\treturn ErrClientConnTimeout\n\t\t\t}\n\t\t\tcloseTransport = false\n\t\t\ttime.Sleep(sleepTime)\n\t\t\tretries++\n\t\t\tgrpclog.Printf(\"grpc: ClientConn.resetTransport failed to create client transport: %v; Reconnecting to %q\", err, cc.target)\n\t\t\tcontinue\n\t\t}\n\t\tcc.mu.Lock()\n\t\tif cc.state == Shutdown {\n\t\t\t\/\/ cc.Close() has been invoked.\n\t\t\tcc.mu.Unlock()\n\t\t\tnewTransport.Close()\n\t\t\treturn ErrClientConnClosing\n\t\t}\n\t\tcc.state = Ready\n\t\tcc.stateCV.Broadcast()\n\t\tcc.transport = newTransport\n\t\tcc.transportSeq = ts + 1\n\t\tif cc.ready != nil {\n\t\t\tclose(cc.ready)\n\t\t\tcc.ready = nil\n\t\t}\n\t\tcc.mu.Unlock()\n\t\treturn nil\n\t}\n}\n\n\/\/ Run in a goroutine to track the error in transport and create the\n\/\/ new transport if an error happens. It returns when the channel is closing.\nfunc (cc *ClientConn) transportMonitor() {\n\tfor {\n\t\tselect {\n\t\t\/\/ shutdownChan is needed to detect the teardown when\n\t\t\/\/ the ClientConn is idle (i.e., no RPC in flight).\n\t\tcase <-cc.shutdownChan:\n\t\t\treturn\n\t\tcase <-cc.transport.Error():\n\t\t\tcc.mu.Lock()\n\t\t\tcc.state = TransientFailure\n\t\t\tcc.stateCV.Broadcast()\n\t\t\tcc.mu.Unlock()\n\t\t\tif err := cc.resetTransport(true); err != nil {\n\t\t\t\t\/\/ The ClientConn is closing.\n\t\t\t\tgrpclog.Printf(\"grpc: ClientConn.transportMonitor exits due to: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\n\/\/ When wait returns, either the new transport is up or ClientConn is\n\/\/ closing. Used to avoid working on a dying transport. It updates and\n\/\/ returns the transport and its version when there is no error.\nfunc (cc *ClientConn) wait(ctx context.Context, ts int) (transport.ClientTransport, int, error) {\n\tfor {\n\t\tcc.mu.Lock()\n\t\tswitch {\n\t\tcase cc.state == Shutdown:\n\t\t\tcc.mu.Unlock()\n\t\t\treturn nil, 0, ErrClientConnClosing\n\t\tcase ts < cc.transportSeq:\n\t\t\t\/\/ Worked on a dying transport. Try the new one immediately.\n\t\t\tdefer cc.mu.Unlock()\n\t\t\treturn cc.transport, cc.transportSeq, nil\n\t\tdefault:\n\t\t\tready := cc.ready\n\t\t\tif ready == nil {\n\t\t\t\tready = make(chan struct{})\n\t\t\t\tcc.ready = ready\n\t\t\t}\n\t\t\tcc.mu.Unlock()\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn nil, 0, transport.ContextErr(ctx.Err())\n\t\t\t\/\/ Wait until the new transport is ready or failed.\n\t\t\tcase <-ready:\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Close starts to tear down the ClientConn. Returns ErrClientConnClosing if\n\/\/ it has been closed (mostly due to dial time-out).\n\/\/ TODO(zhaoq): Make this synchronous to avoid unbounded memory consumption in\n\/\/ some edge cases (e.g., the caller opens and closes many ClientConn's in a\n\/\/ tight loop.\nfunc (cc *ClientConn) Close() error {\n\tcc.mu.Lock()\n\tdefer cc.mu.Unlock()\n\tif cc.state == Shutdown {\n\t\treturn ErrClientConnClosing\n\t}\n\tcc.state = Shutdown\n\tcc.stateCV.Broadcast()\n\tif cc.ready != nil {\n\t\tclose(cc.ready)\n\t\tcc.ready = nil\n\t}\n\tif cc.transport != nil {\n\t\tcc.transport.Close()\n\t}\n\tif cc.shutdownChan != nil {\n\t\tclose(cc.shutdownChan)\n\t}\n\treturn nil\n}\n<commit_msg>s\/stated\/started\/ in Shutdown doc<commit_after>\/*\n *\n * Copyright 2014, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\npackage grpc\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\/credentials\"\n\t\"google.golang.org\/grpc\/grpclog\"\n\t\"google.golang.org\/grpc\/transport\"\n)\n\nvar (\n\t\/\/ ErrUnspecTarget indicates that the target address is unspecified.\n\tErrUnspecTarget = errors.New(\"grpc: target is unspecified\")\n\t\/\/ ErrNoTransportSecurity indicates that there is no transport security\n\t\/\/ being set for ClientConn. Users should either set one or explicityly\n\t\/\/ call WithInsecure DialOption to disable security.\n\tErrNoTransportSecurity = errors.New(\"grpc: no transport security set (use grpc.WithInsecure() explicitly or set credentials)\")\n\t\/\/ ErrCredentialsMisuse indicates that users want to transmit security infomation\n\t\/\/ (e.g., oauth2 token) which requires secure connection on an insecure\n\t\/\/ connection.\n\tErrCredentialsMisuse = errors.New(\"grpc: the credentials require transport level security (use grpc.WithTransportAuthenticator() to set)\")\n\t\/\/ ErrClientConnClosing indicates that the operation is illegal because\n\t\/\/ the session is closing.\n\tErrClientConnClosing = errors.New(\"grpc: the client connection is closing\")\n\t\/\/ ErrClientConnTimeout indicates that the connection could not be\n\t\/\/ established or re-established within the specified timeout.\n\tErrClientConnTimeout = errors.New(\"grpc: timed out trying to connect\")\n\t\/\/ minimum time to give a connection to complete\n\tminConnectTimeout = 20 * time.Second\n)\n\n\/\/ dialOptions configure a Dial call. dialOptions are set by the DialOption\n\/\/ values passed to Dial.\ntype dialOptions struct {\n\tcodec    Codec\n\tblock    bool\n\tinsecure bool\n\tcopts    transport.ConnectOptions\n}\n\n\/\/ DialOption configures how we set up the connection.\ntype DialOption func(*dialOptions)\n\n\/\/ WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling.\nfunc WithCodec(c Codec) DialOption {\n\treturn func(o *dialOptions) {\n\t\to.codec = c\n\t}\n}\n\n\/\/ WithBlock returns a DialOption which makes caller of Dial blocks until the underlying\n\/\/ connection is up. Without this, Dial returns immediately and connecting the server\n\/\/ happens in background.\nfunc WithBlock() DialOption {\n\treturn func(o *dialOptions) {\n\t\to.block = true\n\t}\n}\n\nfunc WithInsecure() DialOption {\n\treturn func(o *dialOptions) {\n\t\to.insecure = true\n\t}\n}\n\n\/\/ WithTransportCredentials returns a DialOption which configures a\n\/\/ connection level security credentials (e.g., TLS\/SSL).\nfunc WithTransportCredentials(creds credentials.TransportAuthenticator) DialOption {\n\treturn func(o *dialOptions) {\n\t\to.copts.AuthOptions = append(o.copts.AuthOptions, creds)\n\t}\n}\n\n\/\/ WithPerRPCCredentials returns a DialOption which sets\n\/\/ credentials which will place auth state on each outbound RPC.\nfunc WithPerRPCCredentials(creds credentials.Credentials) DialOption {\n\treturn func(o *dialOptions) {\n\t\to.copts.AuthOptions = append(o.copts.AuthOptions, creds)\n\t}\n}\n\n\/\/ WithTimeout returns a DialOption that configures a timeout for dialing a client connection.\nfunc WithTimeout(d time.Duration) DialOption {\n\treturn func(o *dialOptions) {\n\t\to.copts.Timeout = d\n\t}\n}\n\n\/\/ WithDialer returns a DialOption that specifies a function to use for dialing network addresses.\nfunc WithDialer(f func(addr string, timeout time.Duration) (net.Conn, error)) DialOption {\n\treturn func(o *dialOptions) {\n\t\to.copts.Dialer = f\n\t}\n}\n\n\/\/ WithUserAgent returns a DialOption that specifies a user agent string for all the RPCs.\nfunc WithUserAgent(s string) DialOption {\n\treturn func(o *dialOptions) {\n\t\to.copts.UserAgent = s\n\t}\n}\n\n\/\/ Dial creates a client connection the given target.\nfunc Dial(target string, opts ...DialOption) (*ClientConn, error) {\n\tif target == \"\" {\n\t\treturn nil, ErrUnspecTarget\n\t}\n\tcc := &ClientConn{\n\t\ttarget:       target,\n\t\tshutdownChan: make(chan struct{}),\n\t}\n\tfor _, opt := range opts {\n\t\topt(&cc.dopts)\n\t}\n\tif !cc.dopts.insecure {\n\t\tvar ok bool\n\t\tfor _, c := range cc.dopts.copts.AuthOptions {\n\t\t\tif _, ok := c.(credentials.TransportAuthenticator); !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tok = true\n\t\t}\n\t\tif !ok {\n\t\t\treturn nil, ErrNoTransportSecurity\n\t\t}\n\t} else {\n\t\tfor _, c := range cc.dopts.copts.AuthOptions {\n\t\t\tif c.RequireTransportSecurity() {\n\t\t\t\treturn nil, ErrCredentialsMisuse\n\t\t\t}\n\t\t}\n\t}\n\tcolonPos := strings.LastIndex(target, \":\")\n\tif colonPos == -1 {\n\t\tcolonPos = len(target)\n\t}\n\tcc.authority = target[:colonPos]\n\tif cc.dopts.codec == nil {\n\t\t\/\/ Set the default codec.\n\t\tcc.dopts.codec = protoCodec{}\n\t}\n\tcc.stateCV = sync.NewCond(&cc.mu)\n\tif cc.dopts.block {\n\t\tif err := cc.resetTransport(false); err != nil {\n\t\t\tcc.Close()\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ Start to monitor the error status of transport.\n\t\tgo cc.transportMonitor()\n\t} else {\n\t\t\/\/ Start a goroutine connecting to the server asynchronously.\n\t\tgo func() {\n\t\t\tif err := cc.resetTransport(false); err != nil {\n\t\t\t\tgrpclog.Printf(\"Failed to dial %s: %v; please retry.\", target, err)\n\t\t\t\tcc.Close()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tgo cc.transportMonitor()\n\t\t}()\n\t}\n\treturn cc, nil\n}\n\n\/\/ ConnectivityState indicates the state of a client connection.\ntype ConnectivityState int\n\nconst (\n\t\/\/ Idle indicates the ClientConn is idle.\n\tIdle ConnectivityState = iota\n\t\/\/ Connecting indicates the ClienConn is connecting.\n\tConnecting\n\t\/\/ Ready indicates the ClientConn is ready for work.\n\tReady\n\t\/\/ TransientFailure indicates the ClientConn has seen a failure but expects to recover.\n\tTransientFailure\n\t\/\/ Shutdown indicates the ClientConn has started shutting down.\n\tShutdown\n)\n\nfunc (s ConnectivityState) String() string {\n\tswitch s {\n\tcase Idle:\n\t\treturn \"IDLE\"\n\tcase Connecting:\n\t\treturn \"CONNECTING\"\n\tcase Ready:\n\t\treturn \"READY\"\n\tcase TransientFailure:\n\t\treturn \"TRANSIENT_FAILURE\"\n\tcase Shutdown:\n\t\treturn \"SHUTDOWN\"\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unknown connectivity state: %d\", s))\n\t}\n}\n\n\/\/ ClientConn represents a client connection to an RPC service.\ntype ClientConn struct {\n\ttarget       string\n\tauthority    string\n\tdopts        dialOptions\n\tshutdownChan chan struct{}\n\n\tmu      sync.Mutex\n\tstate   ConnectivityState\n\tstateCV *sync.Cond\n\t\/\/ ready is closed and becomes nil when a new transport is up or failed\n\t\/\/ due to timeout.\n\tready chan struct{}\n\t\/\/ Every time a new transport is created, this is incremented by 1. Used\n\t\/\/ to avoid trying to recreate a transport while the new one is already\n\t\/\/ under construction.\n\ttransportSeq int\n\ttransport    transport.ClientTransport\n}\n\n\/\/ State returns the connectivity state of the ClientConn\nfunc (cc *ClientConn) State() ConnectivityState {\n\tcc.mu.Lock()\n\tdefer cc.mu.Unlock()\n\treturn cc.state\n}\n\n\/\/ WaitForStateChange blocks until the state changes to something other than the sourceState\n\/\/ or timeout fires. It returns false if timeout fires and true otherwise.\nfunc (cc *ClientConn) WaitForStateChange(timeout time.Duration, sourceState ConnectivityState) bool {\n\tstart := time.Now()\n\tcc.mu.Lock()\n\tdefer cc.mu.Unlock()\n\tif sourceState != cc.state {\n\t\treturn true\n\t}\n\texpired := timeout <= time.Since(start)\n\tif expired {\n\t\treturn false\n\t}\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tselect {\n\t\tcase <-time.After(timeout - time.Since(start)):\n\t\t\tcc.mu.Lock()\n\t\t\texpired = true\n\t\t\tcc.stateCV.Broadcast()\n\t\t\tcc.mu.Unlock()\n\t\tcase <-done:\n\t\t}\n\t}()\n\tdefer close(done)\n\tfor sourceState == cc.state {\n\t\tcc.stateCV.Wait()\n\t\tif expired {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (cc *ClientConn) resetTransport(closeTransport bool) error {\n\tvar retries int\n\tstart := time.Now()\n\tfor {\n\t\tcc.mu.Lock()\n\t\tcc.state = Connecting\n\t\tcc.stateCV.Broadcast()\n\t\tt := cc.transport\n\t\tts := cc.transportSeq\n\t\t\/\/ Avoid wait() picking up a dying transport unnecessarily.\n\t\tcc.transportSeq = 0\n\t\tif cc.state == Shutdown {\n\t\t\tcc.mu.Unlock()\n\t\t\treturn ErrClientConnClosing\n\t\t}\n\t\tcc.mu.Unlock()\n\t\tif closeTransport {\n\t\t\tt.Close()\n\t\t}\n\t\t\/\/ Adjust timeout for the current try.\n\t\tcopts := cc.dopts.copts\n\t\tif copts.Timeout < 0 {\n\t\t\tcc.Close()\n\t\t\treturn ErrClientConnTimeout\n\t\t}\n\t\tif copts.Timeout > 0 {\n\t\t\tcopts.Timeout -= time.Since(start)\n\t\t\tif copts.Timeout <= 0 {\n\t\t\t\tcc.Close()\n\t\t\t\treturn ErrClientConnTimeout\n\t\t\t}\n\t\t}\n\t\tsleepTime := backoff(retries)\n\t\ttimeout := sleepTime\n\t\tif timeout < minConnectTimeout {\n\t\t\ttimeout = minConnectTimeout\n\t\t}\n\t\tif copts.Timeout == 0 || copts.Timeout > timeout {\n\t\t\tcopts.Timeout = timeout\n\t\t}\n\t\tconnectTime := time.Now()\n\t\tnewTransport, err := transport.NewClientTransport(cc.target, &copts)\n\t\tif err != nil {\n\t\t\tcc.mu.Lock()\n\t\t\tcc.state = TransientFailure\n\t\t\tcc.stateCV.Broadcast()\n\t\t\tcc.mu.Unlock()\n\t\t\tsleepTime -= time.Since(connectTime)\n\t\t\tif sleepTime < 0 {\n\t\t\t\tsleepTime = 0\n\t\t\t}\n\t\t\t\/\/ Fail early before falling into sleep.\n\t\t\tif cc.dopts.copts.Timeout > 0 && cc.dopts.copts.Timeout < sleepTime+time.Since(start) {\n\t\t\t\tcc.Close()\n\t\t\t\treturn ErrClientConnTimeout\n\t\t\t}\n\t\t\tcloseTransport = false\n\t\t\ttime.Sleep(sleepTime)\n\t\t\tretries++\n\t\t\tgrpclog.Printf(\"grpc: ClientConn.resetTransport failed to create client transport: %v; Reconnecting to %q\", err, cc.target)\n\t\t\tcontinue\n\t\t}\n\t\tcc.mu.Lock()\n\t\tif cc.state == Shutdown {\n\t\t\t\/\/ cc.Close() has been invoked.\n\t\t\tcc.mu.Unlock()\n\t\t\tnewTransport.Close()\n\t\t\treturn ErrClientConnClosing\n\t\t}\n\t\tcc.state = Ready\n\t\tcc.stateCV.Broadcast()\n\t\tcc.transport = newTransport\n\t\tcc.transportSeq = ts + 1\n\t\tif cc.ready != nil {\n\t\t\tclose(cc.ready)\n\t\t\tcc.ready = nil\n\t\t}\n\t\tcc.mu.Unlock()\n\t\treturn nil\n\t}\n}\n\n\/\/ Run in a goroutine to track the error in transport and create the\n\/\/ new transport if an error happens. It returns when the channel is closing.\nfunc (cc *ClientConn) transportMonitor() {\n\tfor {\n\t\tselect {\n\t\t\/\/ shutdownChan is needed to detect the teardown when\n\t\t\/\/ the ClientConn is idle (i.e., no RPC in flight).\n\t\tcase <-cc.shutdownChan:\n\t\t\treturn\n\t\tcase <-cc.transport.Error():\n\t\t\tcc.mu.Lock()\n\t\t\tcc.state = TransientFailure\n\t\t\tcc.stateCV.Broadcast()\n\t\t\tcc.mu.Unlock()\n\t\t\tif err := cc.resetTransport(true); err != nil {\n\t\t\t\t\/\/ The ClientConn is closing.\n\t\t\t\tgrpclog.Printf(\"grpc: ClientConn.transportMonitor exits due to: %v\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\n\/\/ When wait returns, either the new transport is up or ClientConn is\n\/\/ closing. Used to avoid working on a dying transport. It updates and\n\/\/ returns the transport and its version when there is no error.\nfunc (cc *ClientConn) wait(ctx context.Context, ts int) (transport.ClientTransport, int, error) {\n\tfor {\n\t\tcc.mu.Lock()\n\t\tswitch {\n\t\tcase cc.state == Shutdown:\n\t\t\tcc.mu.Unlock()\n\t\t\treturn nil, 0, ErrClientConnClosing\n\t\tcase ts < cc.transportSeq:\n\t\t\t\/\/ Worked on a dying transport. Try the new one immediately.\n\t\t\tdefer cc.mu.Unlock()\n\t\t\treturn cc.transport, cc.transportSeq, nil\n\t\tdefault:\n\t\t\tready := cc.ready\n\t\t\tif ready == nil {\n\t\t\t\tready = make(chan struct{})\n\t\t\t\tcc.ready = ready\n\t\t\t}\n\t\t\tcc.mu.Unlock()\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn nil, 0, transport.ContextErr(ctx.Err())\n\t\t\t\/\/ Wait until the new transport is ready or failed.\n\t\t\tcase <-ready:\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Close starts to tear down the ClientConn. Returns ErrClientConnClosing if\n\/\/ it has been closed (mostly due to dial time-out).\n\/\/ TODO(zhaoq): Make this synchronous to avoid unbounded memory consumption in\n\/\/ some edge cases (e.g., the caller opens and closes many ClientConn's in a\n\/\/ tight loop.\nfunc (cc *ClientConn) Close() error {\n\tcc.mu.Lock()\n\tdefer cc.mu.Unlock()\n\tif cc.state == Shutdown {\n\t\treturn ErrClientConnClosing\n\t}\n\tcc.state = Shutdown\n\tcc.stateCV.Broadcast()\n\tif cc.ready != nil {\n\t\tclose(cc.ready)\n\t\tcc.ready = nil\n\t}\n\tif cc.transport != nil {\n\t\tcc.transport.Close()\n\t}\n\tif cc.shutdownChan != nil {\n\t\tclose(cc.shutdownChan)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package clix\n\nimport (\n\t\"time\"\n\n\t\"github.com\/urfave\/cli\/v2\"\n)\n\n\/\/ Flag constants declared for CLI use.\nconst (\n\tFlagPort = \"port\"\n\n\tFlagLogFormat = \"log-format\"\n\tFlagLogLevel  = \"log-level\"\n\tFlagLogTags   = \"log-tags\"\n\n\tFlagStatsDSN    = \"stats-dsn\"\n\tFlagStatsPrefix = \"stats-prefix\"\n\tFlagStatsTags   = \"stats-tags\"\n\n\tFlagProfiler     = \"profiler\"\n\tFlagProfilerPort = \"profiler-port\"\n\n\tFlagKafkaConsumerBrokers      = \"kafka-consumer-brokers\"\n\tFlagKafkaConsumerGroupID      = \"kafka-consumer-group-id\"\n\tFlagKafkaConsumerTopic        = \"kafka-consumer-topic\"\n\tFlagKafkaConsumerKafkaVersion = \"kafka-consumer-kafka-version\"\n\tFlagKafkaProducerBrokers      = \"kafka-producer-brokers\"\n\tFlagKafkaProducerTopic        = \"kafka-producer-topic\"\n\tFlagKafkaProducerKafkaVersion = \"kafka-producer-kafka-version\"\n\n\tFlagCommitBatch    = \"commit-batch\"\n\tFlagCommitInterval = \"commit-interval\"\n\n\tFlagRedisDSN = \"redis-dsn\"\n)\n\ntype defaults struct {\n\tPort      string\n\tLogFormat string\n\tLogLevel  string\n\n\tProfilerPort string\n}\n\n\/\/ Defaults holds the flag default values.\nvar Defaults = defaults{\n\tPort:      \"80\",\n\tLogFormat: \"json\",\n\tLogLevel:  \"info\",\n\n\tProfilerPort: \"8081\",\n}\n\n\/\/ Flags represents a set of CLI flags.\ntype Flags []cli.Flag\n\n\/\/ Merge joins one or more Flags together, making a new set.\nfunc (f Flags) Merge(flags ...Flags) Flags {\n\tvar m Flags\n\tm = append(m, f...)\n\tfor _, flag := range flags {\n\t\tm = append(m, flag...)\n\t}\n\n\treturn m\n}\n\n\/\/ ServerFlags are flags that configure a server.\nvar ServerFlags = Flags{\n\t&cli.StringFlag{\n\t\tName:    FlagPort,\n\t\tValue:   Defaults.Port,\n\t\tUsage:   \"Port for HTTP server to listen on\",\n\t\tEnvVars: []string{\"PORT\"},\n\t},\n}\n\n\/\/ KafkaConsumerFlags are flags that configure a Kafka consumer.\nvar KafkaConsumerFlags = Flags{\n\t&cli.StringSliceFlag{\n\t\tName:     FlagKafkaConsumerBrokers,\n\t\tUsage:    \"Kafka consumer brokers.\",\n\t\tEnvVars:  []string{\"KAFKA_CONSUMER_BROKERS\"},\n\t\tRequired: true,\n\t},\n\t&cli.StringFlag{\n\t\tName:     FlagKafkaConsumerGroupID,\n\t\tUsage:    \"Kafka consumer group id.\",\n\t\tEnvVars:  []string{\"KAFKA_CONSUMER_GROUP_ID\"},\n\t\tRequired: true,\n\t},\n\t&cli.StringFlag{\n\t\tName:     FlagKafkaConsumerTopic,\n\t\tUsage:    \"Kafka topic to consume from.\",\n\t\tEnvVars:  []string{\"KAFKA_CONSUMER_TOPIC\"},\n\t\tRequired: true,\n\t},\n\t&cli.StringFlag{\n\t\tName:     FlagKafkaConsumerKafkaVersion,\n\t\tUsage:    \"Kafka version (e.g. 0.10.2.0 or 2.3.0).\",\n\t\tEnvVars:  []string{\"KAFKA_CONSUMER_KAFKA_VERSION\"},\n\t\tRequired: true,\n\t},\n}\n\n\/\/ KafkaProducerFlags are flags that configure a Kafka producer.\nvar KafkaProducerFlags = Flags{\n\t&cli.StringSliceFlag{\n\t\tName:     FlagKafkaProducerBrokers,\n\t\tUsage:    \"Kafka producer brokers.\",\n\t\tEnvVars:  []string{\"KAFKA_PRODUCER_BROKERS\"},\n\t\tRequired: true,\n\t},\n\t&cli.StringFlag{\n\t\tName:     FlagKafkaProducerTopic,\n\t\tUsage:    \"Kafka topic to produce into.\",\n\t\tEnvVars:  []string{\"KAFKA_PRODUCER_TOPIC\"},\n\t\tRequired: true,\n\t},\n\t&cli.StringFlag{\n\t\tName:     FlagKafkaProducerKafkaVersion,\n\t\tUsage:    \"Kafka version (e.g. 0.10.2.0 or 2.3.0).\",\n\t\tEnvVars:  []string{\"KAFKA_PRODUCER_KAFKA_VERSION\"},\n\t\tRequired: true,\n\t},\n}\n\n\/\/ CommitterFlags are flags that configure message processing batch size and committing interval.\nvar CommitterFlags = Flags{\n\t&cli.IntFlag{\n\t\tName:    FlagCommitBatch,\n\t\tValue:   500,\n\t\tUsage:   \"Commit batch size for message processing.\",\n\t\tEnvVars: []string{\"COMMIT_BATCH\"},\n\t},\n\t&cli.DurationFlag{\n\t\tName:    FlagCommitInterval,\n\t\tValue:   1 * time.Second,\n\t\tUsage:   \"Commit interval for message processing.\",\n\t\tEnvVars: []string{\"COMMIT_INTERVAL\"},\n\t},\n}\n\n\/\/ RedisFlags are flags that configure redis.\nvar RedisFlags = Flags{\n\t&cli.StringFlag{\n\t\tName:     FlagRedisDSN,\n\t\tUsage:    \"The DSN of Redis.\",\n\t\tEnvVars:  []string{\"REDIS_DSN\"},\n\t\tRequired: true,\n\t},\n}\n\n\/\/ CommonFlags are flags that configure logging and stats.\nvar CommonFlags = Flags{\n\t&cli.StringFlag{\n\t\tName:    FlagLogFormat,\n\t\tValue:   Defaults.LogFormat,\n\t\tUsage:   \"Specify the format of logs. Supported formats: 'terminal', 'json'\",\n\t\tEnvVars: []string{\"LOG_FORMAT\"},\n\t},\n\t&cli.StringFlag{\n\t\tName:    FlagLogLevel,\n\t\tValue:   Defaults.LogLevel,\n\t\tUsage:   \"Specify the log level. E.g. 'debug', 'warning'.\",\n\t\tEnvVars: []string{\"LOG_LEVEL\"},\n\t},\n\t&cli.StringSliceFlag{\n\t\tName:    FlagLogTags,\n\t\tUsage:   \"A list of tags appended to every log. Format: key=value.\",\n\t\tEnvVars: []string{\"LOG_TAGS\"},\n\t},\n\t&cli.StringFlag{\n\t\tName:     FlagStatsDSN,\n\t\tUsage:    \"The URL of a stats backend.\",\n\t\tEnvVars:  []string{\"STATS_DSN\"},\n\t\tRequired: true,\n\t},\n\t&cli.StringFlag{\n\t\tName:    FlagStatsPrefix,\n\t\tUsage:   \"The prefix of the measurements names.\",\n\t\tEnvVars: []string{\"STATS_PREFIX\"},\n\t},\n\t&cli.StringSliceFlag{\n\t\tName:    FlagStatsTags,\n\t\tUsage:   \"A list of tags appended to every measurement. Format: key=value.\",\n\t\tEnvVars: []string{\"STATS_TAGS\"},\n\t},\n}\n\n\/\/ ProfilerFlags are flags that configure to the profiler.\nvar ProfilerFlags = Flags{\n\t&cli.BoolFlag{\n\t\tName:    FlagProfiler,\n\t\tUsage:   \"Enable profiler server.\",\n\t\tEnvVars: []string{\"PROFILER\"},\n\t},\n\t&cli.StringFlag{\n\t\tName:    FlagProfilerPort,\n\t\tValue:   Defaults.ProfilerPort,\n\t\tUsage:   \"Port for the profiler to listen on.\",\n\t\tEnvVars: []string{\"PROFILER_PORT\"},\n\t},\n}\n<commit_msg>[FEATURE] Added redis addrs flag for cluster reds. (#156)<commit_after>package clix\n\nimport (\n\t\"time\"\n\n\t\"github.com\/urfave\/cli\/v2\"\n)\n\n\/\/ Flag constants declared for CLI use.\nconst (\n\tFlagPort = \"port\"\n\n\tFlagLogFormat = \"log-format\"\n\tFlagLogLevel  = \"log-level\"\n\tFlagLogTags   = \"log-tags\"\n\n\tFlagStatsDSN    = \"stats-dsn\"\n\tFlagStatsPrefix = \"stats-prefix\"\n\tFlagStatsTags   = \"stats-tags\"\n\n\tFlagProfiler     = \"profiler\"\n\tFlagProfilerPort = \"profiler-port\"\n\n\tFlagKafkaConsumerBrokers      = \"kafka-consumer-brokers\"\n\tFlagKafkaConsumerGroupID      = \"kafka-consumer-group-id\"\n\tFlagKafkaConsumerTopic        = \"kafka-consumer-topic\"\n\tFlagKafkaConsumerKafkaVersion = \"kafka-consumer-kafka-version\"\n\tFlagKafkaProducerBrokers      = \"kafka-producer-brokers\"\n\tFlagKafkaProducerTopic        = \"kafka-producer-topic\"\n\tFlagKafkaProducerKafkaVersion = \"kafka-producer-kafka-version\"\n\n\tFlagCommitBatch    = \"commit-batch\"\n\tFlagCommitInterval = \"commit-interval\"\n\n\tFlagRedisDSN   = \"redis-dsn\"\n\tFlagRedisAddrs = \"redis-addrs\"\n)\n\ntype defaults struct {\n\tPort      string\n\tLogFormat string\n\tLogLevel  string\n\n\tProfilerPort string\n}\n\n\/\/ Defaults holds the flag default values.\nvar Defaults = defaults{\n\tPort:      \"80\",\n\tLogFormat: \"json\",\n\tLogLevel:  \"info\",\n\n\tProfilerPort: \"8081\",\n}\n\n\/\/ Flags represents a set of CLI flags.\ntype Flags []cli.Flag\n\n\/\/ Merge joins one or more Flags together, making a new set.\nfunc (f Flags) Merge(flags ...Flags) Flags {\n\tvar m Flags\n\tm = append(m, f...)\n\tfor _, flag := range flags {\n\t\tm = append(m, flag...)\n\t}\n\n\treturn m\n}\n\n\/\/ ServerFlags are flags that configure a server.\nvar ServerFlags = Flags{\n\t&cli.StringFlag{\n\t\tName:    FlagPort,\n\t\tValue:   Defaults.Port,\n\t\tUsage:   \"Port for HTTP server to listen on\",\n\t\tEnvVars: []string{\"PORT\"},\n\t},\n}\n\n\/\/ KafkaConsumerFlags are flags that configure a Kafka consumer.\nvar KafkaConsumerFlags = Flags{\n\t&cli.StringSliceFlag{\n\t\tName:     FlagKafkaConsumerBrokers,\n\t\tUsage:    \"Kafka consumer brokers.\",\n\t\tEnvVars:  []string{\"KAFKA_CONSUMER_BROKERS\"},\n\t\tRequired: true,\n\t},\n\t&cli.StringFlag{\n\t\tName:     FlagKafkaConsumerGroupID,\n\t\tUsage:    \"Kafka consumer group id.\",\n\t\tEnvVars:  []string{\"KAFKA_CONSUMER_GROUP_ID\"},\n\t\tRequired: true,\n\t},\n\t&cli.StringFlag{\n\t\tName:     FlagKafkaConsumerTopic,\n\t\tUsage:    \"Kafka topic to consume from.\",\n\t\tEnvVars:  []string{\"KAFKA_CONSUMER_TOPIC\"},\n\t\tRequired: true,\n\t},\n\t&cli.StringFlag{\n\t\tName:     FlagKafkaConsumerKafkaVersion,\n\t\tUsage:    \"Kafka version (e.g. 0.10.2.0 or 2.3.0).\",\n\t\tEnvVars:  []string{\"KAFKA_CONSUMER_KAFKA_VERSION\"},\n\t\tRequired: true,\n\t},\n}\n\n\/\/ KafkaProducerFlags are flags that configure a Kafka producer.\nvar KafkaProducerFlags = Flags{\n\t&cli.StringSliceFlag{\n\t\tName:     FlagKafkaProducerBrokers,\n\t\tUsage:    \"Kafka producer brokers.\",\n\t\tEnvVars:  []string{\"KAFKA_PRODUCER_BROKERS\"},\n\t\tRequired: true,\n\t},\n\t&cli.StringFlag{\n\t\tName:     FlagKafkaProducerTopic,\n\t\tUsage:    \"Kafka topic to produce into.\",\n\t\tEnvVars:  []string{\"KAFKA_PRODUCER_TOPIC\"},\n\t\tRequired: true,\n\t},\n\t&cli.StringFlag{\n\t\tName:     FlagKafkaProducerKafkaVersion,\n\t\tUsage:    \"Kafka version (e.g. 0.10.2.0 or 2.3.0).\",\n\t\tEnvVars:  []string{\"KAFKA_PRODUCER_KAFKA_VERSION\"},\n\t\tRequired: true,\n\t},\n}\n\n\/\/ CommitterFlags are flags that configure message processing batch size and committing interval.\nvar CommitterFlags = Flags{\n\t&cli.IntFlag{\n\t\tName:    FlagCommitBatch,\n\t\tValue:   500,\n\t\tUsage:   \"Commit batch size for message processing.\",\n\t\tEnvVars: []string{\"COMMIT_BATCH\"},\n\t},\n\t&cli.DurationFlag{\n\t\tName:    FlagCommitInterval,\n\t\tValue:   1 * time.Second,\n\t\tUsage:   \"Commit interval for message processing.\",\n\t\tEnvVars: []string{\"COMMIT_INTERVAL\"},\n\t},\n}\n\n\/\/ RedisFlags are flags that configure redis.\nvar RedisFlags = Flags{\n\t&cli.StringFlag{\n\t\tName:     FlagRedisDSN,\n\t\tUsage:    \"The DSN of Redis.\",\n\t\tEnvVars:  []string{\"REDIS_DSN\"},\n\t\tRequired: true,\n\t},\n}\n\n\/\/ RedisClusterFlags are flags that configure redis cluster.\nvar RedisClusterFlags = Flags{\n\t&cli.StringSliceFlag{\n\t\tName:     FlagRedisAddrs,\n\t\tUsage:    \"Adresses of Redis cluster.\",\n\t\tEnvVars:  []string{\"REDIS_ADDRS\"},\n\t\tRequired: true,\n\t},\n}\n\n\/\/ CommonFlags are flags that configure logging and stats.\nvar CommonFlags = Flags{\n\t&cli.StringFlag{\n\t\tName:    FlagLogFormat,\n\t\tValue:   Defaults.LogFormat,\n\t\tUsage:   \"Specify the format of logs. Supported formats: 'terminal', 'json'\",\n\t\tEnvVars: []string{\"LOG_FORMAT\"},\n\t},\n\t&cli.StringFlag{\n\t\tName:    FlagLogLevel,\n\t\tValue:   Defaults.LogLevel,\n\t\tUsage:   \"Specify the log level. E.g. 'debug', 'warning'.\",\n\t\tEnvVars: []string{\"LOG_LEVEL\"},\n\t},\n\t&cli.StringSliceFlag{\n\t\tName:    FlagLogTags,\n\t\tUsage:   \"A list of tags appended to every log. Format: key=value.\",\n\t\tEnvVars: []string{\"LOG_TAGS\"},\n\t},\n\t&cli.StringFlag{\n\t\tName:     FlagStatsDSN,\n\t\tUsage:    \"The URL of a stats backend.\",\n\t\tEnvVars:  []string{\"STATS_DSN\"},\n\t\tRequired: true,\n\t},\n\t&cli.StringFlag{\n\t\tName:    FlagStatsPrefix,\n\t\tUsage:   \"The prefix of the measurements names.\",\n\t\tEnvVars: []string{\"STATS_PREFIX\"},\n\t},\n\t&cli.StringSliceFlag{\n\t\tName:    FlagStatsTags,\n\t\tUsage:   \"A list of tags appended to every measurement. Format: key=value.\",\n\t\tEnvVars: []string{\"STATS_TAGS\"},\n\t},\n}\n\n\/\/ ProfilerFlags are flags that configure to the profiler.\nvar ProfilerFlags = Flags{\n\t&cli.BoolFlag{\n\t\tName:    FlagProfiler,\n\t\tUsage:   \"Enable profiler server.\",\n\t\tEnvVars: []string{\"PROFILER\"},\n\t},\n\t&cli.StringFlag{\n\t\tName:    FlagProfilerPort,\n\t\tValue:   Defaults.ProfilerPort,\n\t\tUsage:   \"Port for the profiler to listen on.\",\n\t\tEnvVars: []string{\"PROFILER_PORT\"},\n\t},\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\/\/ Contributor: Julien Vehent jvehent@mozilla.com [:ulfr]\n\npackage client \/* import \"mig.ninja\/mig\/client\" *\/\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n)\n\ntype CommandLocation struct {\n\tEndpoint      string   `json:\"endpoint\"`\n\tCommandID     float64  `json:\"commandid\"`\n\tActionID      float64  `json:\"actionid\"`\n\tFoundAnything bool     `json:\"foundanything\"`\n\tConnectionsTo []string `json:\"connections_to\"`\n\tLatitude      float64  `json:\"latitude\"`\n\tLongitude     float64  `json:\"longitude\"`\n\tCity          string   `json:\"city\"`\n\tCountry       string   `json:\"country\"`\n}\n\nfunc ValueToLocation(v interface{}) (cl CommandLocation, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"ValueToLocation) -> %v\", e)\n\t\t}\n\t}()\n\tbData, err := json.Marshal(v)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = json.Unmarshal(bData, &cl)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}\n\nfunc PrintMap(locs []CommandLocation, title string) (err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"PrintMap() -> %v\", e)\n\t\t}\n\t}()\n\tgmap := makeMapHeader(title)\n\tlocs = singularizeLocations(locs)\n\tdata, err := json.Marshal(locs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgmap += fmt.Sprintf(`        <script type=\"text\/javascript\"> var endpoints = %s <\/script>`, data)\n\tvar details []string\n\tdetails = append(details, \"        <ol>\\n\")\n\tfor _, cl := range locs {\n\t\tdetail := fmt.Sprintf(\"            <li>%s: found=%t<\/li>\", cl.Endpoint, cl.FoundAnything)\n\t\tdetails = append(details, detail)\n\t}\n\tdetails = append(details, \"        <\/ol>\\n\")\n\tgmap += makeMapFooter(title, details)\n\n\t\/\/ write map data to temp file\n\tfd, err := ioutil.TempFile(\"\", \"migmap_\")\n\tdefer fd.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = fd.Write([]byte(gmap))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfi, err := fd.Stat()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfilepath := fmt.Sprintf(\"%s\/%s\", os.TempDir(), fi.Name())\n\tfmt.Fprintf(os.Stderr, \"map written to %s\\n\", filepath)\n\terr = exec.Command(\"firefox\", filepath).Start()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}\n\n\/\/ singularizeLocations prevent multiple point from using the same coordinates, and therefore show as one point on the map\nfunc singularizeLocations(orig_locs []CommandLocation) (locs []CommandLocation) {\n\tlocs = orig_locs\n\tfor i, _ := range locs {\n\t\tfor j := 0; j < i; j++ {\n\t\t\tif locs[i].Latitude == locs[j].Latitude && locs[i].Longitude == locs[j].Longitude {\n\t\t\t\tswitch i % 8 {\n\t\t\t\tcase 0:\n\t\t\t\t\tlocs[i].Latitude += 0.005\n\t\t\t\tcase 1:\n\t\t\t\t\tlocs[i].Longitude += 0.005\n\t\t\t\tcase 2:\n\t\t\t\t\tlocs[i].Latitude -= 0.005\n\t\t\t\tcase 3:\n\t\t\t\t\tlocs[i].Longitude -= 0.005\n\t\t\t\tcase 4:\n\t\t\t\t\tlocs[i].Latitude += 0.005\n\t\t\t\t\tlocs[i].Longitude += 0.005\n\t\t\t\tcase 5:\n\t\t\t\t\tlocs[i].Latitude -= 0.005\n\t\t\t\t\tlocs[i].Longitude -= 0.005\n\t\t\t\tcase 6:\n\t\t\t\t\tlocs[i].Latitude += 0.005\n\t\t\t\t\tlocs[i].Longitude -= 0.005\n\t\t\t\tcase 7:\n\t\t\t\t\tlocs[i].Latitude -= 0.005\n\t\t\t\t\tlocs[i].Longitude += 0.005\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc makeMapHeader(title string) string {\n\treturn fmt.Sprintf(`\n<!DOCTYPE html PUBLIC \"-\/\/W3C\/\/DTD XHTML 1.0 Strict\/\/EN\" \"http:\/\/www.w3.org\/TR\/xhtml1\/DTD\/xhtml1-strict.dtd\">\n<html xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\" xml:lang=\"en\" lang=\"en\">\n    <head>\n        <meta http-equiv=\"Content-Type\" content=\"text\/html;charset=utf-8\" \/>\n        <title>%s<\/title>\n        <script type=\"text\/javascript\" src=\"https:\/\/maps.googleapis.com\/maps\/api\/js?v=3.exp&amp;signed_in=true\"><\/script>\n        <script type=\"text\/javascript\" src=\"https:\/\/raw.githubusercontent.com\/googlemaps\/js-marker-clusterer\/gh-pages\/src\/markerclusterer_compiled.js\"><\/script>\n`, title)\n}\nfunc makeMapFooter(title string, body []string) (footer string) {\n\tfooter = `\n        <script type=\"text\/javascript\">\nvar locs = new Array();\nvar marker = new Array();\nvar connections = new Array();\nvar cluster = new Array();\nvar arrowSymbol = {\n    path: google.maps.SymbolPath.CIRCLE,\n    scale: 2,\n    strokeColor: 'blue'\n};\nfunction initialize() {\n    var center = new google.maps.LatLng(0,0);\n    var mapOptions = {\n        zoom: 2,\n        center: center,\n        mapTypeId: google.maps.MapTypeId.TERRAIN\n    };\n    var map = new google.maps.Map(\n        document.getElementById('map'),\n        mapOptions\n    );\n    endpointscount = endpoints.length;\n    for (var i=0; i<endpointscount; i++) {\n        locs[endpoints[i].endpoint] = new google.maps.LatLng(endpoints[i].latitude, endpoints[i].longitude);\n        marker[endpoints[i].endpoint] = new google.maps.Marker({\n            position: locs[endpoints[i].endpoint],\n            map: map,\n            title: endpoints[i].endpoint\n        });\n        cluster.push(marker[endpoints[i].endpoint]);\n    }\n    for (var i=0; i<endpointscount; i++) {\n        if ( endpoints[i].connections_to == null ) {\n            continue\n        }\n        for (var j=0; j<endpoints[i].connections_to.length; j++) {\n            connections[i+j] = new google.maps.Polyline({\n                path: [locs[endpoints[i].endpoint], locs[endpoints[i].connections_to[j]]],\n                geodesic: true,\n                strokeColor: 'blue',\n                strokeOpacity: 1.0,\n                strokeWeight: 1,\n                icons: [{\n                    icon: arrowSymbol,\n                    offset: '100%'\n                }],\n                map: map\n            });\n        }\n    }\n    animateCircle();\n    var markerCluster = new MarkerClusterer(map, cluster);\n}\n\/\/ Use the DOM setInterval() function to change the offset of the symbol\n\/\/ at fixed intervals.\nfunction animateCircle() {\n    var count = 0;\n    window.setInterval(function() {\n        count = (count + 1) % 200;\n        conncount = connections.length;\n        for (var i=0; i<conncount; i++) {\n            var icons = connections[i].get('icons');\n            icons[0].offset = (count \/ 2) + '%';\n            connections[i].set('icons', icons);\n        }\n    }, 10);\n}\n\ngoogle.maps.event.addDomListener(window, 'load', initialize);\n        <\/script>\n        <style type=\"text\/css\">\n            #map {\n                width:100%;\n                height:600px;\n            }\n        <\/style>\n    <\/head>\n    <body>\n`\n\tfooter += fmt.Sprintf(\"        <p><b>%s<\/b><\/p>\\n\", title)\n\tfooter += `<div id=\"map\"><\/div>`\n\tfor _, p := range body {\n\t\tfooter += p + \"\\n\"\n\t}\n\tfooter += `\n    <\/body>\n<\/html>`\n\treturn\n}\n<commit_msg>[minor] fix map opening on macos<commit_after>\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\/\/ Contributor: Julien Vehent jvehent@mozilla.com [:ulfr]\n\npackage client \/* import \"mig.ninja\/mig\/client\" *\/\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n)\n\ntype CommandLocation struct {\n\tEndpoint      string   `json:\"endpoint\"`\n\tCommandID     float64  `json:\"commandid\"`\n\tActionID      float64  `json:\"actionid\"`\n\tFoundAnything bool     `json:\"foundanything\"`\n\tConnectionsTo []string `json:\"connections_to\"`\n\tLatitude      float64  `json:\"latitude\"`\n\tLongitude     float64  `json:\"longitude\"`\n\tCity          string   `json:\"city\"`\n\tCountry       string   `json:\"country\"`\n}\n\nfunc ValueToLocation(v interface{}) (cl CommandLocation, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"ValueToLocation) -> %v\", e)\n\t\t}\n\t}()\n\tbData, err := json.Marshal(v)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = json.Unmarshal(bData, &cl)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}\n\nfunc PrintMap(locs []CommandLocation, title string) (err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"PrintMap() -> %v\", e)\n\t\t}\n\t}()\n\tgmap := makeMapHeader(title)\n\tlocs = singularizeLocations(locs)\n\tdata, err := json.Marshal(locs)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tgmap += fmt.Sprintf(`        <script type=\"text\/javascript\"> var endpoints = %s <\/script>`, data)\n\tvar details []string\n\tdetails = append(details, \"        <ol>\\n\")\n\tfor _, cl := range locs {\n\t\tdetail := fmt.Sprintf(\"            <li>%s: found=%t<\/li>\", cl.Endpoint, cl.FoundAnything)\n\t\tdetails = append(details, detail)\n\t}\n\tdetails = append(details, \"        <\/ol>\\n\")\n\tgmap += makeMapFooter(title, details)\n\n\t\/\/ write map data to temp file\n\tfd, err := ioutil.TempFile(\"\", \"migmap_\")\n\tdefer fd.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = fd.Write([]byte(gmap))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfi, err := fd.Stat()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfilepath := fmt.Sprintf(\"%s\/%s\", os.TempDir(), fi.Name())\n\tfmt.Fprintf(os.Stderr, \"map written to %s\\n\", filepath)\n\tswitch runtime.GOOS {\n\tcase \"linux\":\n\t\terr = exec.Command(\"firefox\", filepath).Start()\n\tcase \"darwin\":\n\t\terr = exec.Command(\"open\", \"-b\", \"org.mozilla.firefox\", filepath).Start()\n\tdefault:\n\t\treturn\n\t}\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}\n\n\/\/ singularizeLocations prevent multiple point from using the same coordinates, and therefore show as one point on the map\nfunc singularizeLocations(orig_locs []CommandLocation) (locs []CommandLocation) {\n\tlocs = orig_locs\n\tfor i, _ := range locs {\n\t\tfor j := 0; j < i; j++ {\n\t\t\tif locs[i].Latitude == locs[j].Latitude && locs[i].Longitude == locs[j].Longitude {\n\t\t\t\tswitch i % 8 {\n\t\t\t\tcase 0:\n\t\t\t\t\tlocs[i].Latitude += 0.005\n\t\t\t\tcase 1:\n\t\t\t\t\tlocs[i].Longitude += 0.005\n\t\t\t\tcase 2:\n\t\t\t\t\tlocs[i].Latitude -= 0.005\n\t\t\t\tcase 3:\n\t\t\t\t\tlocs[i].Longitude -= 0.005\n\t\t\t\tcase 4:\n\t\t\t\t\tlocs[i].Latitude += 0.005\n\t\t\t\t\tlocs[i].Longitude += 0.005\n\t\t\t\tcase 5:\n\t\t\t\t\tlocs[i].Latitude -= 0.005\n\t\t\t\t\tlocs[i].Longitude -= 0.005\n\t\t\t\tcase 6:\n\t\t\t\t\tlocs[i].Latitude += 0.005\n\t\t\t\t\tlocs[i].Longitude -= 0.005\n\t\t\t\tcase 7:\n\t\t\t\t\tlocs[i].Latitude -= 0.005\n\t\t\t\t\tlocs[i].Longitude += 0.005\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc makeMapHeader(title string) string {\n\treturn fmt.Sprintf(`\n<!DOCTYPE html PUBLIC \"-\/\/W3C\/\/DTD XHTML 1.0 Strict\/\/EN\" \"http:\/\/www.w3.org\/TR\/xhtml1\/DTD\/xhtml1-strict.dtd\">\n<html xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\" xml:lang=\"en\" lang=\"en\">\n    <head>\n        <meta http-equiv=\"Content-Type\" content=\"text\/html;charset=utf-8\" \/>\n        <title>%s<\/title>\n        <script type=\"text\/javascript\" src=\"https:\/\/maps.googleapis.com\/maps\/api\/js?v=3.exp&amp;signed_in=true\"><\/script>\n        <script type=\"text\/javascript\" src=\"https:\/\/raw.githubusercontent.com\/googlemaps\/js-marker-clusterer\/gh-pages\/src\/markerclusterer_compiled.js\"><\/script>\n`, title)\n}\nfunc makeMapFooter(title string, body []string) (footer string) {\n\tfooter = `\n        <script type=\"text\/javascript\">\nvar locs = new Array();\nvar marker = new Array();\nvar connections = new Array();\nvar cluster = new Array();\nvar arrowSymbol = {\n    path: google.maps.SymbolPath.CIRCLE,\n    scale: 2,\n    strokeColor: 'blue'\n};\nfunction initialize() {\n    var center = new google.maps.LatLng(0,0);\n    var mapOptions = {\n        zoom: 2,\n        center: center,\n        mapTypeId: google.maps.MapTypeId.TERRAIN\n    };\n    var map = new google.maps.Map(\n        document.getElementById('map'),\n        mapOptions\n    );\n    endpointscount = endpoints.length;\n    for (var i=0; i<endpointscount; i++) {\n        locs[endpoints[i].endpoint] = new google.maps.LatLng(endpoints[i].latitude, endpoints[i].longitude);\n        marker[endpoints[i].endpoint] = new google.maps.Marker({\n            position: locs[endpoints[i].endpoint],\n            map: map,\n            title: endpoints[i].endpoint\n        });\n        cluster.push(marker[endpoints[i].endpoint]);\n    }\n    for (var i=0; i<endpointscount; i++) {\n        if ( endpoints[i].connections_to == null ) {\n            continue\n        }\n        for (var j=0; j<endpoints[i].connections_to.length; j++) {\n            connections[i+j] = new google.maps.Polyline({\n                path: [locs[endpoints[i].endpoint], locs[endpoints[i].connections_to[j]]],\n                geodesic: true,\n                strokeColor: 'blue',\n                strokeOpacity: 1.0,\n                strokeWeight: 1,\n                icons: [{\n                    icon: arrowSymbol,\n                    offset: '100%'\n                }],\n                map: map\n            });\n        }\n    }\n    animateCircle();\n    var markerCluster = new MarkerClusterer(map, cluster);\n}\n\/\/ Use the DOM setInterval() function to change the offset of the symbol\n\/\/ at fixed intervals.\nfunction animateCircle() {\n    var count = 0;\n    window.setInterval(function() {\n        count = (count + 1) % 200;\n        conncount = connections.length;\n        for (var i=0; i<conncount; i++) {\n            var icons = connections[i].get('icons');\n            icons[0].offset = (count \/ 2) + '%';\n            connections[i].set('icons', icons);\n        }\n    }, 10);\n}\n\ngoogle.maps.event.addDomListener(window, 'load', initialize);\n        <\/script>\n        <style type=\"text\/css\">\n            #map {\n                width:100%;\n                height:600px;\n            }\n        <\/style>\n    <\/head>\n    <body>\n`\n\tfooter += fmt.Sprintf(\"        <p><b>%s<\/b><\/p>\\n\", title)\n\tfooter += `<div id=\"map\"><\/div>`\n\tfor _, p := range body {\n\t\tfooter += p + \"\\n\"\n\t}\n\tfooter += `\n    <\/body>\n<\/html>`\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"github.com\/juju\/errgo\"\n\t\"github.com\/coreos\/fleet\/job\"\n\n\texecPkg \"os\/exec\"\n\t\"fmt\"\n)\n\nconst (\n\tFLEETCTL        = \"fleetctl\"\n\tENDPOINT_OPTION = \"--endpoint\"\n\tENDPOINT_VALUE  = \"http:\/\/172.17.42.1:4001\"\n)\n\ntype ClientCLI struct {\n\tetcdPeer string\n}\n\nfunc NewClientCLI() FleetClient {\n\treturn NewClientCLIWithPeer(ENDPOINT_VALUE)\n}\n\nfunc NewClientCLIWithPeer(etcdPeer string) FleetClient {\n\treturn &ClientCLI{\n\t\tetcdPeer: ENDPOINT_VALUE,\n\t}\n}\n\nfunc (this *ClientCLI) Submit(name, filePath string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"submit\", filePath)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Get(name string) (*job.Job, error) {\n\treturn nil, fmt.Errorf(\"Method not implemented: ClientCLI.Get\")\n}\n\nfunc (this *ClientCLI) Start(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"start\", \"--no-block=true\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Stop(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"stop\", \"--no-block=true\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Destroy(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"destroy\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n<commit_msg>Fixes ignored peers parameter<commit_after>package client\n\nimport (\n\t\"github.com\/juju\/errgo\"\n\t\"github.com\/coreos\/fleet\/job\"\n\n\texecPkg \"os\/exec\"\n\t\"fmt\"\n)\n\nconst (\n\tFLEETCTL        = \"fleetctl\"\n\tENDPOINT_OPTION = \"--endpoint\"\n\tENDPOINT_VALUE  = \"http:\/\/172.17.42.1:4001\"\n)\n\ntype ClientCLI struct {\n\tetcdPeer string\n}\n\nfunc NewClientCLI() FleetClient {\n\treturn NewClientCLIWithPeer(ENDPOINT_VALUE)\n}\n\nfunc NewClientCLIWithPeer(etcdPeer string) FleetClient {\n\treturn &ClientCLI{\n\t\tetcdPeer: etcdPeer,\n\t}\n}\n\nfunc (this *ClientCLI) Submit(name, filePath string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"submit\", filePath)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Get(name string) (*job.Job, error) {\n\treturn nil, fmt.Errorf(\"Method not implemented: ClientCLI.Get\")\n}\n\nfunc (this *ClientCLI) Start(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"start\", \"--no-block=true\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Stop(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"stop\", \"--no-block=true\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n\nfunc (this *ClientCLI) Destroy(name string) error {\n\tcmd := execPkg.Command(FLEETCTL, ENDPOINT_OPTION, this.etcdPeer, \"destroy\", name)\n\t_, err := exec(cmd)\n\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>decode with go<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 The StudyGolang Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/ http:\/\/studygolang.com\n\/\/ Author: polaris\tpolaris@studygolang.com\n\npackage controller\n\nimport (\n\t\"http\/middleware\"\n\t\"logic\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/polaris1119\/echoutils\"\n\t\"github.com\/polaris1119\/goutils\"\n\t\"github.com\/polaris1119\/logger\"\n\n\t. \"http\"\n\t\"model\"\n)\n\n\/\/ 在需要评论（喜欢）且要回调的地方注册评论（喜欢）对象\nfunc init() {\n\t\/\/ 注册评论（喜欢）对象\n\tlogic.RegisterCommentObject(model.TypeArticle, logic.ArticleComment{})\n\tlogic.RegisterLikeObject(model.TypeArticle, logic.ArticleLike{})\n}\n\ntype ArticleController struct{}\n\n\/\/ 注册路由\nfunc (self ArticleController) RegisterRoute(g *echo.Group) {\n\tg.Get(\"\/articles\", self.ReadList)\n\tg.Get(\"\/articles\/crawl\", self.Crawl)\n\n\tg.Get(\"\/articles\/:id\", self.Detail)\n\n\tg.Match([]string{\"GET\", \"POST\"}, \"\/articles\/new\", self.Create, middleware.NeedLogin(), middleware.Sensivite(), middleware.BalanceCheck(), middleware.PublishNotice())\n\tg.Post(\"\/articles\/modify\", self.Modify, middleware.NeedLogin(), middleware.Sensivite())\n}\n\n\/\/ ReadList 网友文章列表页\nfunc (ArticleController) ReadList(ctx echo.Context) error {\n\tlimit := 20\n\n\tlastId := goutils.MustInt(ctx.QueryParam(\"lastid\"))\n\tarticles := logic.DefaultArticle.FindBy(ctx, limit+5, lastId)\n\tif articles == nil {\n\t\tlogger.Errorln(\"article controller: find article error\")\n\t\treturn ctx.Redirect(http.StatusSeeOther, \"\/articles\")\n\t}\n\n\tnum := len(articles)\n\tif num == 0 {\n\t\tif lastId == 0 {\n\t\t\treturn render(ctx, \"articles\/list.html\", map[string]interface{}{\"articles\": articles, \"activeArticles\": \"active\"})\n\t\t}\n\t\treturn ctx.Redirect(http.StatusSeeOther, \"\/articles\")\n\t}\n\n\tvar (\n\t\thasPrev, hasNext bool\n\t\tprevId, nextId   int\n\t)\n\n\tif lastId != 0 {\n\t\tprevId = lastId\n\n\t\tfirstNoTopId := articles[0].Id\n\t\tfor i := 0; i < num; i++ {\n\t\t\tif articles[i].Top != 1 {\n\t\t\t\tfirstNoTopId = articles[i].Id\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t\/\/ 避免因为文章下线，导致判断错误（所以 > 5）\n\t\tif prevId-firstNoTopId > 5 {\n\t\t\thasPrev = false\n\t\t} else {\n\t\t\tprevId += limit\n\t\t\thasPrev = true\n\t\t}\n\t}\n\n\tif num > limit {\n\t\thasNext = true\n\t\tarticles = articles[:limit]\n\t\tnextId = articles[limit-1].Id\n\t} else {\n\t\tnextId = articles[num-1].Id\n\t}\n\n\tpageInfo := map[string]interface{}{\n\t\t\"has_prev\": hasPrev,\n\t\t\"prev_id\":  prevId,\n\t\t\"has_next\": hasNext,\n\t\t\"next_id\":  nextId,\n\t}\n\n\t\/\/ 获取当前用户喜欢对象信息\n\tme, ok := ctx.Get(\"user\").(*model.Me)\n\tvar likeFlags map[int]int\n\tif ok {\n\t\tlikeFlags, _ = logic.DefaultLike.FindUserLikeObjects(ctx, me.Uid, model.TypeArticle, articles[0].Id, nextId)\n\t}\n\n\treturn render(ctx, \"articles\/list.html\", map[string]interface{}{\"articles\": articles, \"activeArticles\": \"active\", \"page\": pageInfo, \"likeflags\": likeFlags})\n}\n\n\/\/ Detail 文章详细页\nfunc (ArticleController) Detail(ctx echo.Context) error {\n\tarticle, prevNext, err := logic.DefaultArticle.FindByIdAndPreNext(ctx, goutils.MustInt(ctx.Param(\"id\")))\n\tif err != nil {\n\t\treturn ctx.Redirect(http.StatusSeeOther, \"\/articles\")\n\t}\n\n\tif article == nil || article.Id == 0 || article.Status == model.ArticleStatusOffline {\n\t\treturn ctx.Redirect(http.StatusSeeOther, \"\/articles\")\n\t}\n\n\tdata := map[string]interface{}{\n\t\t\"activeArticles\": \"active\",\n\t\t\"article\":        article,\n\t\t\"prev\":           prevNext[0],\n\t\t\"next\":           prevNext[1],\n\t}\n\n\tme, ok := ctx.Get(\"user\").(*model.Me)\n\tif ok {\n\t\tdata[\"likeflag\"] = logic.DefaultLike.HadLike(ctx, me.Uid, article.Id, model.TypeArticle)\n\t\tdata[\"hadcollect\"] = logic.DefaultFavorite.HadFavorite(ctx, me.Uid, article.Id, model.TypeArticle)\n\n\t\tlogic.Views.Incr(Request(ctx), model.TypeArticle, article.Id, me.Uid)\n\n\t\tif article.IsSelf && me.Uid != article.User.Uid {\n\t\t\tgo logic.DefaultViewRecord.Record(article.Id, model.TypeArticle, me.Uid)\n\t\t}\n\n\t\tif me.IsRoot || (article.IsSelf && me.Uid == article.User.Uid) {\n\t\t\tdata[\"view_user_num\"] = logic.DefaultViewRecord.FindUserNum(ctx, article.Id, model.TypeArticle)\n\t\t}\n\t} else {\n\t\tlogic.Views.Incr(Request(ctx), model.TypeArticle, article.Id)\n\t}\n\n\t\/\/ 为了阅读数即时看到\n\tarticle.Viewnum++\n\n\treturn render(ctx, \"articles\/detail.html,common\/comment.html\", data)\n}\n\n\/\/ Create 发布新文章\nfunc (ArticleController) Create(ctx echo.Context) error {\n\ttitle := ctx.FormValue(\"title\")\n\tif title == \"\" || ctx.Request().Method() != \"POST\" {\n\t\treturn render(ctx, \"articles\/new.html\", map[string]interface{}{\"activeArticles\": \"active\"})\n\t}\n\n\tif ctx.FormValue(\"content\") == \"\" || ctx.FormValue(\"txt\") == \"\" {\n\t\treturn fail(ctx, 1, \"内容不能为空\")\n\t}\n\n\tme := ctx.Get(\"user\").(*model.Me)\n\terr := logic.DefaultArticle.Publish(echoutils.WrapEchoContext(ctx), me, ctx.FormParams())\n\tif err != nil {\n\t\treturn fail(ctx, 2, \"内部服务错误\")\n\t}\n\n\treturn success(ctx, nil)\n}\n\n\/\/ Modify 修改文章\nfunc (ArticleController) Modify(ctx echo.Context) error {\n\tif ctx.FormValue(\"id\") == \"\" || ctx.FormValue(\"content\") == \"\" {\n\t\treturn fail(ctx, 1, \"内容不能为空\")\n\t}\n\tarticle, err := logic.DefaultArticle.FindById(ctx, ctx.FormValue(\"id\"))\n\tif err != nil {\n\t\treturn fail(ctx, 2, \"文章不存在\")\n\t}\n\n\tme := ctx.Get(\"user\").(*model.Me)\n\tif !logic.CanEdit(me, article) {\n\t\treturn fail(ctx, 3, \"没有修改权限\")\n\t}\n\n\terrMsg, err := logic.DefaultArticle.Modify(echoutils.WrapEchoContext(ctx), me, ctx.FormParams())\n\tif err != nil {\n\t\treturn fail(ctx, 4, errMsg)\n\t}\n\n\treturn success(ctx, nil)\n}\n\nfunc (ArticleController) Crawl(ctx echo.Context) error {\n\tstrUrl := ctx.QueryParam(\"url\")\n\n\tvar (\n\t\terrMsg string\n\t\terr    error\n\t)\n\tstrUrl = strings.TrimSpace(strUrl)\n\t_, err = logic.DefaultArticle.ParseArticle(ctx, strUrl, false)\n\tif err != nil {\n\t\terrMsg = err.Error()\n\t}\n\n\tif errMsg != \"\" {\n\t\treturn fail(ctx, 1, errMsg)\n\t}\n\treturn success(ctx, nil)\n}\n<commit_msg>bugfix<commit_after>\/\/ Copyright 2014 The StudyGolang Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/ http:\/\/studygolang.com\n\/\/ Author: polaris\tpolaris@studygolang.com\n\npackage controller\n\nimport (\n\t\"http\/middleware\"\n\t\"logic\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/polaris1119\/echoutils\"\n\t\"github.com\/polaris1119\/goutils\"\n\t\"github.com\/polaris1119\/logger\"\n\n\t. \"http\"\n\t\"model\"\n)\n\n\/\/ 在需要评论（喜欢）且要回调的地方注册评论（喜欢）对象\nfunc init() {\n\t\/\/ 注册评论（喜欢）对象\n\tlogic.RegisterCommentObject(model.TypeArticle, logic.ArticleComment{})\n\tlogic.RegisterLikeObject(model.TypeArticle, logic.ArticleLike{})\n}\n\ntype ArticleController struct{}\n\n\/\/ 注册路由\nfunc (self ArticleController) RegisterRoute(g *echo.Group) {\n\tg.Get(\"\/articles\", self.ReadList)\n\tg.Get(\"\/articles\/crawl\", self.Crawl)\n\n\tg.Get(\"\/articles\/:id\", self.Detail)\n\n\tg.Match([]string{\"GET\", \"POST\"}, \"\/articles\/new\", self.Create, middleware.NeedLogin(), middleware.Sensivite(), middleware.BalanceCheck(), middleware.PublishNotice())\n\tg.Post(\"\/articles\/modify\", self.Modify, middleware.NeedLogin(), middleware.Sensivite())\n}\n\n\/\/ ReadList 网友文章列表页\nfunc (ArticleController) ReadList(ctx echo.Context) error {\n\tlimit := 20\n\n\tlastId := goutils.MustInt(ctx.QueryParam(\"lastid\"))\n\tarticles := logic.DefaultArticle.FindBy(ctx, limit+5, lastId)\n\tif articles == nil {\n\t\tlogger.Errorln(\"article controller: find article error\")\n\t\treturn ctx.Redirect(http.StatusSeeOther, \"\/articles\")\n\t}\n\n\tnum := len(articles)\n\tif num == 0 {\n\t\tif lastId == 0 {\n\t\t\treturn render(ctx, \"articles\/list.html\", map[string]interface{}{\"articles\": articles, \"activeArticles\": \"active\"})\n\t\t}\n\t\treturn ctx.Redirect(http.StatusSeeOther, \"\/articles\")\n\t}\n\n\tvar (\n\t\thasPrev, hasNext bool\n\t\tprevId, nextId   int\n\t)\n\n\tif lastId != 0 {\n\t\tprevId = lastId\n\n\t\tfirstNoTopId := articles[0].Id\n\t\tfor i := 0; i < num; i++ {\n\t\t\tif articles[i].Top != 1 {\n\t\t\t\tfirstNoTopId = articles[i].Id\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t\/\/ 避免因为文章下线，导致判断错误（所以 > 5）\n\t\tif prevId-firstNoTopId > 5 {\n\t\t\thasPrev = false\n\t\t} else {\n\t\t\tprevId += limit\n\t\t\thasPrev = true\n\t\t}\n\t}\n\n\tif num > limit {\n\t\thasNext = true\n\t\tarticles = articles[:limit]\n\t\tnextId = articles[limit-1].Id\n\t} else {\n\t\tnextId = articles[num-1].Id\n\t}\n\n\tpageInfo := map[string]interface{}{\n\t\t\"has_prev\": hasPrev,\n\t\t\"prev_id\":  prevId,\n\t\t\"has_next\": hasNext,\n\t\t\"next_id\":  nextId,\n\t}\n\n\t\/\/ 获取当前用户喜欢对象信息\n\tme, ok := ctx.Get(\"user\").(*model.Me)\n\tvar likeFlags map[int]int\n\tif ok {\n\t\tlikeFlags, _ = logic.DefaultLike.FindUserLikeObjects(ctx, me.Uid, model.TypeArticle, articles[0].Id, nextId)\n\t}\n\n\treturn render(ctx, \"articles\/list.html\", map[string]interface{}{\"articles\": articles, \"activeArticles\": \"active\", \"page\": pageInfo, \"likeflags\": likeFlags})\n}\n\n\/\/ Detail 文章详细页\nfunc (ArticleController) Detail(ctx echo.Context) error {\n\tarticle, prevNext, err := logic.DefaultArticle.FindByIdAndPreNext(ctx, goutils.MustInt(ctx.Param(\"id\")))\n\tif err != nil {\n\t\treturn ctx.Redirect(http.StatusSeeOther, \"\/articles\")\n\t}\n\n\tif article == nil || article.Id == 0 || article.Status == model.ArticleStatusOffline {\n\t\treturn ctx.Redirect(http.StatusSeeOther, \"\/articles\")\n\t}\n\n\tdata := map[string]interface{}{\n\t\t\"activeArticles\": \"active\",\n\t\t\"article\":        article,\n\t\t\"prev\":           prevNext[0],\n\t\t\"next\":           prevNext[1],\n\t}\n\n\tme, ok := ctx.Get(\"user\").(*model.Me)\n\tif ok {\n\t\tdata[\"likeflag\"] = logic.DefaultLike.HadLike(ctx, me.Uid, article.Id, model.TypeArticle)\n\t\tdata[\"hadcollect\"] = logic.DefaultFavorite.HadFavorite(ctx, me.Uid, article.Id, model.TypeArticle)\n\n\t\tlogic.Views.Incr(Request(ctx), model.TypeArticle, article.Id, me.Uid)\n\n\t\tif !article.IsSelf || me.Uid != article.User.Uid {\n\t\t\tgo logic.DefaultViewRecord.Record(article.Id, model.TypeArticle, me.Uid)\n\t\t}\n\n\t\tif me.IsRoot || (article.IsSelf && me.Uid == article.User.Uid) {\n\t\t\tdata[\"view_user_num\"] = logic.DefaultViewRecord.FindUserNum(ctx, article.Id, model.TypeArticle)\n\t\t}\n\t} else {\n\t\tlogic.Views.Incr(Request(ctx), model.TypeArticle, article.Id)\n\t}\n\n\t\/\/ 为了阅读数即时看到\n\tarticle.Viewnum++\n\n\treturn render(ctx, \"articles\/detail.html,common\/comment.html\", data)\n}\n\n\/\/ Create 发布新文章\nfunc (ArticleController) Create(ctx echo.Context) error {\n\ttitle := ctx.FormValue(\"title\")\n\tif title == \"\" || ctx.Request().Method() != \"POST\" {\n\t\treturn render(ctx, \"articles\/new.html\", map[string]interface{}{\"activeArticles\": \"active\"})\n\t}\n\n\tif ctx.FormValue(\"content\") == \"\" || ctx.FormValue(\"txt\") == \"\" {\n\t\treturn fail(ctx, 1, \"内容不能为空\")\n\t}\n\n\tme := ctx.Get(\"user\").(*model.Me)\n\terr := logic.DefaultArticle.Publish(echoutils.WrapEchoContext(ctx), me, ctx.FormParams())\n\tif err != nil {\n\t\treturn fail(ctx, 2, \"内部服务错误\")\n\t}\n\n\treturn success(ctx, nil)\n}\n\n\/\/ Modify 修改文章\nfunc (ArticleController) Modify(ctx echo.Context) error {\n\tif ctx.FormValue(\"id\") == \"\" || ctx.FormValue(\"content\") == \"\" {\n\t\treturn fail(ctx, 1, \"内容不能为空\")\n\t}\n\tarticle, err := logic.DefaultArticle.FindById(ctx, ctx.FormValue(\"id\"))\n\tif err != nil {\n\t\treturn fail(ctx, 2, \"文章不存在\")\n\t}\n\n\tme := ctx.Get(\"user\").(*model.Me)\n\tif !logic.CanEdit(me, article) {\n\t\treturn fail(ctx, 3, \"没有修改权限\")\n\t}\n\n\terrMsg, err := logic.DefaultArticle.Modify(echoutils.WrapEchoContext(ctx), me, ctx.FormParams())\n\tif err != nil {\n\t\treturn fail(ctx, 4, errMsg)\n\t}\n\n\treturn success(ctx, nil)\n}\n\nfunc (ArticleController) Crawl(ctx echo.Context) error {\n\tstrUrl := ctx.QueryParam(\"url\")\n\n\tvar (\n\t\terrMsg string\n\t\terr    error\n\t)\n\tstrUrl = strings.TrimSpace(strUrl)\n\t_, err = logic.DefaultArticle.ParseArticle(ctx, strUrl, false)\n\tif err != nil {\n\t\terrMsg = err.Error()\n\t}\n\n\tif errMsg != \"\" {\n\t\treturn fail(ctx, 1, errMsg)\n\t}\n\treturn success(ctx, nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"path\/filepath\"\n\n\t\"github.com\/hashicorp\/go-checkpoint\"\n\t\"github.com\/mitchellh\/packer\/command\"\n)\n\nfunc init() {\n\tcheckpointResult = make(chan *checkpoint.CheckResponse, 1)\n}\n\nvar checkpointResult chan *checkpoint.CheckResponse\n\n\/\/ runCheckpoint runs a HashiCorp Checkpoint request. You can read about\n\/\/ Checkpoint here: https:\/\/github.com\/hashicorp\/go-checkpoint.\nfunc runCheckpoint(c *config) {\n\t\/\/ If the user doesn't want checkpoint at all, then return.\n\tif c.DisableCheckpoint {\n\t\tlog.Printf(\"[INFO] Checkpoint disabled. Not running.\")\n\t\tcheckpointResult <- nil\n\t\treturn\n\t}\n\n\tconfigDir, err := ConfigDir()\n\tif err != nil {\n\t\tlog.Printf(\"[ERR] Checkpoint setup error: %s\", err)\n\t\tcheckpointResult <- nil\n\t\treturn\n\t}\n\n\tversion := Version\n\tif VersionPrerelease != \"\" {\n\t\tversion += fmt.Sprintf(\".%s\", VersionPrerelease)\n\t}\n\n\tsignaturePath := filepath.Join(configDir, \"checkpoint_signature\")\n\tif c.DisableCheckpointSignature {\n\t\tlog.Printf(\"[INFO] Checkpoint signature disabled\")\n\t\tsignaturePath = \"\"\n\t}\n\n\tresp, err := checkpoint.Check(&checkpoint.CheckParams{\n\t\tProduct:       \"packer\",\n\t\tVersion:       version,\n\t\tSignatureFile: signaturePath,\n\t\tCacheFile:     filepath.Join(configDir, \"checkpoint_cache\"),\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"[ERR] Checkpoint error: %s\", err)\n\t\tresp = nil\n\t}\n\n\tcheckpointResult <- resp\n}\n\n\/\/ commandVersionCheck implements command.VersionCheckFunc and is used\n\/\/ as the version checker.\nfunc commandVersionCheck() (command.VersionCheckInfo, error) {\n\t\/\/ Wait for the result to come through\n\tinfo := <-checkpointResult\n\tif info == nil {\n\t\tvar zero command.VersionCheckInfo\n\t\treturn zero, nil\n\t}\n\n\t\/\/ Build the alerts that we may have received about our version\n\talerts := make([]string, len(info.Alerts))\n\tfor i, a := range info.Alerts {\n\t\talerts[i] = a.Message\n\t}\n\n\treturn command.VersionCheckInfo{\n\t\tOutdated: info.Outdated,\n\t\tLatest:   info.CurrentVersion,\n\t\tAlerts:   alerts,\n\t}, nil\n}\n<commit_msg>fixing version numbers: RCs should be labeled x.x.x-rcx<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"path\/filepath\"\n\n\t\"github.com\/hashicorp\/go-checkpoint\"\n\t\"github.com\/mitchellh\/packer\/command\"\n)\n\nfunc init() {\n\tcheckpointResult = make(chan *checkpoint.CheckResponse, 1)\n}\n\nvar checkpointResult chan *checkpoint.CheckResponse\n\n\/\/ runCheckpoint runs a HashiCorp Checkpoint request. You can read about\n\/\/ Checkpoint here: https:\/\/github.com\/hashicorp\/go-checkpoint.\nfunc runCheckpoint(c *config) {\n\t\/\/ If the user doesn't want checkpoint at all, then return.\n\tif c.DisableCheckpoint {\n\t\tlog.Printf(\"[INFO] Checkpoint disabled. Not running.\")\n\t\tcheckpointResult <- nil\n\t\treturn\n\t}\n\n\tconfigDir, err := ConfigDir()\n\tif err != nil {\n\t\tlog.Printf(\"[ERR] Checkpoint setup error: %s\", err)\n\t\tcheckpointResult <- nil\n\t\treturn\n\t}\n\n\tversion := Version\n\tif VersionPrerelease != \"\" {\n\t\tversion += fmt.Sprintf(\"-%s\", VersionPrerelease)\n\t}\n\n\tsignaturePath := filepath.Join(configDir, \"checkpoint_signature\")\n\tif c.DisableCheckpointSignature {\n\t\tlog.Printf(\"[INFO] Checkpoint signature disabled\")\n\t\tsignaturePath = \"\"\n\t}\n\n\tresp, err := checkpoint.Check(&checkpoint.CheckParams{\n\t\tProduct:       \"packer\",\n\t\tVersion:       version,\n\t\tSignatureFile: signaturePath,\n\t\tCacheFile:     filepath.Join(configDir, \"checkpoint_cache\"),\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"[ERR] Checkpoint error: %s\", err)\n\t\tresp = nil\n\t}\n\n\tcheckpointResult <- resp\n}\n\n\/\/ commandVersionCheck implements command.VersionCheckFunc and is used\n\/\/ as the version checker.\nfunc commandVersionCheck() (command.VersionCheckInfo, error) {\n\t\/\/ Wait for the result to come through\n\tinfo := <-checkpointResult\n\tif info == nil {\n\t\tvar zero command.VersionCheckInfo\n\t\treturn zero, nil\n\t}\n\n\t\/\/ Build the alerts that we may have received about our version\n\talerts := make([]string, len(info.Alerts))\n\tfor i, a := range info.Alerts {\n\t\talerts[i] = a.Message\n\t}\n\n\treturn command.VersionCheckInfo{\n\t\tOutdated: info.Outdated,\n\t\tLatest:   info.CurrentVersion,\n\t\tAlerts:   alerts,\n\t}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package acl\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestChmod(t *testing.T) {\n\tp, err := ioutil.TempDir(os.TempDir(), \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(p)\n\tif err := Chmod(p, 0); err != nil {\n\t\tt.Fatal(err)\n\t}\n\td, err := os.Open(p)\n\tif err == nil {\n\t\td.Close()\n\t\tt.Fatal(\"owner able to access directory\")\n\t}\n\tif err := Chmod(p, 0400); err != nil {\n\t\tt.Fatal(err)\n\t}\n\td, err = os.Open(p)\n\tif err != nil {\n\t\tt.Fatal(\"owner unable to access directory\")\n\t}\n\td.Close()\n}\n<commit_msg>Updated Chmod() test.<commit_after>package acl\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestChmod(t *testing.T) {\n\tf, err := ioutil.TempDir(os.TempFile(), \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.Remove(f)\n\tif err := Chmod(f.Name(), 0); err != nil {\n\t\tt.Fatal(err)\n\t}\n\td, err := os.Open(f.Name())\n\tif err == nil {\n\t\td.Close()\n\t\tt.Fatal(\"owner able to access directory\")\n\t}\n\tif err := Chmod(f.Name(), 0400); err != nil {\n\t\tt.Fatal(err)\n\t}\n\td, err = os.Open(f.Name())\n\tif err != nil {\n\t\tt.Fatal(\"owner unable to access directory\")\n\t}\n\td.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"time\"\n\n\t\"github.com\/jvikstedt\/alarmy\/api\"\n\t\"github.com\/jvikstedt\/alarmy\/schedule\"\n\t\"github.com\/jvikstedt\/alarmy\/store\"\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ serverCmd represents the server command\nvar serverCmd = &cobra.Command{\n\tUse:   \"server\",\n\tShort: \"A brief description of your command\",\n\tLong: `A longer description that spans multiple lines and likely contains examples\nand usage of using your command. For example:\n\nCobra is a CLI library for Go that empowers applications.\nThis application is a tool to generate the needed files\nto quickly create a Cobra application.`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\/\/ Store \/ Database Setup\n\t\tboltStore, err := store.NewBoltStore(\"alarmy_dev.db\")\n\t\tif err != nil {\n\t\t\tprintAndExitError(err, nil)\n\t\t}\n\t\tdefer boltStore.Close()\n\n\t\t\/\/ Logger setup\n\t\tf, err := os.OpenFile(\"dev.log\", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\t\tif err != nil {\n\t\t\tprintAndExitError(err, nil)\n\t\t}\n\t\tdefer f.Close()\n\t\tlogger := log.New(f, \"\", log.LstdFlags)\n\n\t\t\/\/ Scheduler setup\n\t\tscheduler := schedule.NewCronScheduler(logger)\n\t\tgo scheduler.Start()\n\t\tdefer scheduler.Stop()\n\n\t\t\/\/ Server & http.Handler setup\n\t\tapi := api.NewApi(boltStore.Store(), logger, scheduler)\n\t\thandler, err := api.Handler()\n\t\tif err != nil {\n\t\t\tprintAndExitError(err, logger)\n\t\t}\n\t\ts := http.Server{Addr: \":8080\", Handler: handler}\n\n\t\t\/\/ Signalling\n\t\tstop := make(chan os.Signal, 1)\n\t\tsignal.Notify(stop, os.Interrupt)\n\n\t\tgo func() {\n\t\t\t<-stop\n\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\t\tdefer cancel()\n\n\t\t\t\/\/ Shutdown server gracefully\n\t\t\ts.Shutdown(ctx)\n\t\t}()\n\n\t\t\/\/ Server startup\n\t\tif err := s.ListenAndServe(); err != nil {\n\t\t\tprintAndExitError(err, logger)\n\t\t}\n\t},\n}\n\nfunc printAndExitError(a interface{}, logger *log.Logger) {\n\tif logger != nil {\n\t\tlogger.Println(a)\n\t}\n\tfmt.Println(a)\n\tos.Exit(1)\n}\n\nfunc init() {\n\tRootCmd.AddCommand(serverCmd)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\n\t\/\/ Cobra supports Persistent Flags which will work for this command\n\t\/\/ and all subcommands, e.g.:\n\t\/\/ serverCmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t\/\/ Cobra supports local flags which will only run when this command\n\t\/\/ is called directly, e.g.:\n\t\/\/ serverCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n}\n<commit_msg>Server command better handling of errors and exit<commit_after>package cmd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"time\"\n\n\t\"github.com\/jvikstedt\/alarmy\/api\"\n\t\"github.com\/jvikstedt\/alarmy\/schedule\"\n\t\"github.com\/jvikstedt\/alarmy\/store\"\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ serverCmd represents the server command\nvar serverCmd = &cobra.Command{\n\tUse:   \"server\",\n\tShort: \"A brief description of your command\",\n\tLong: `A longer description that spans multiple lines and likely contains examples\nand usage of using your command. For example:\n\nCobra is a CLI library for Go that empowers applications.\nThis application is a tool to generate the needed files\nto quickly create a Cobra application.`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\terr := setupServer()\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t},\n}\n\nfunc setupServer() error {\n\t\/\/ Store \/ Database Setup\n\tboltStore, err := store.NewBoltStore(\"alarmy_dev.db\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer boltStore.Close()\n\n\t\/\/ Logger setup\n\tf, err := os.OpenFile(\"dev.log\", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tlogger := log.New(f, \"\", log.LstdFlags)\n\n\t\/\/ Scheduler setup\n\tscheduler := schedule.NewCronScheduler(logger)\n\tgo scheduler.Start()\n\tdefer scheduler.Stop()\n\n\t\/\/ Server & http.Handler setup\n\tapi := api.NewApi(boltStore.Store(), logger, scheduler)\n\thandler, err := api.Handler()\n\tif err != nil {\n\t\treturn err\n\t}\n\ts := http.Server{Addr: \":8080\", Handler: handler}\n\n\t\/\/ Signalling\n\tstop := make(chan os.Signal, 1)\n\tsignal.Notify(stop, os.Interrupt)\n\n\tgo func() {\n\t\t<-stop\n\n\t\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\t\tdefer cancel()\n\n\t\t\/\/ Shutdown server gracefully\n\t\ts.Shutdown(ctx)\n\t}()\n\n\t\/\/ Server startup\n\tif err := s.ListenAndServe(); err != nil {\n\t\tif err == http.ErrServerClosed {\n\t\t\tlogger.Println(err)\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc init() {\n\tRootCmd.AddCommand(serverCmd)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\n\t\/\/ Cobra supports Persistent Flags which will work for this command\n\t\/\/ and all subcommands, e.g.:\n\t\/\/ serverCmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t\/\/ Cobra supports local flags which will only run when this command\n\t\/\/ is called directly, e.g.:\n\t\/\/ serverCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\ntype AppendConfig struct {\n\n}\n\nvar _ Mode = &AppendConfig{}\n\nfunc (config *AppendConfig) ExampleConfig() string {\n\tpanic(\"NYI\")\n}\n\nfunc (config *AppendConfig) ReadConfig(fname string) error {\n\tpanic(\"NYI\")\n}\n\nfunc (config *AppendConfig) validate() error {\n\tpanic(\"NYI\")\n}\n\nfunc (config *AppendConfig) Run(\n\tflags []string, gConfig *GlobalConfig, stdin []string,\n) ([]string, error) {\n\tpanic(\"NYI\")\n}<commit_msg>Removed append mode skeleton.<commit_after><|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\t\"time\"\n\n\t\"github.com\/oberd\/ecsy\/ecs\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar prevCount int\nvar poll bool\n\nfunc printServiceStatus(cluster, service string) bool {\n\tserviceObj, err := ecs.FindService(cluster, service)\n\tfailOnError(err, fmt.Sprintf(\"Problem finding service: %s %s\\n\", cluster, service))\n\tfmt.Printf(\"Cluster:\\t\\t%s\\n\", cluster)\n\tfmt.Printf(\"Service:\\t\\t%s\\n\", service)\n\tfmt.Printf(\"Task Definition:\\t%s\\n\", path.Base(*serviceObj.TaskDefinition))\n\tfmt.Println(\"Deployments:\")\n\tfor _, d := range serviceObj.Deployments {\n\t\tfmt.Printf(\"%s %s (%d Desired, %d Pending, %d Running) %v\\n\", path.Base(*d.TaskDefinition), *d.Status, *d.DesiredCount, *d.PendingCount, *d.RunningCount, *d.CreatedAt)\n\t}\n\tcurrCount := len(serviceObj.Deployments)\n\thasChanged := prevCount != 1000 && currCount != prevCount\n\tprevCount = currCount\n\treturn !hasChanged\n}\n\n\/\/ statusCmd represents the status command\nvar statusCmd = &cobra.Command{\n\tUse:   \"status\",\n\tShort: \"View current cluster or service deployment status\",\n\tLong:  \"View current cluster or service deployment status\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tcluster, service := ServiceChooser(args)\n\t\tprevCount = 1000\n\t\tprintServiceStatus(cluster, service)\n\t\tfor poll {\n\t\t\ttime.Sleep(15 * time.Second)\n\t\t\tpoll = printServiceStatus(cluster, service)\n\t\t}\n\t},\n}\n\nfunc init() {\n\tRootCmd.AddCommand(statusCmd)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\n\t\/\/ Cobra supports Persistent Flags which will work for this command\n\t\/\/ and all subcommands, e.g.:\n\t\/\/ statusCmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t\/\/ Cobra supports local flags which will only run when this command\n\t\/\/ is called directly, e.g.:\n\tstatusCmd.Flags().BoolVarP(&poll, \"poll\", \"p\", false, \"Poll at a 15 second interval until a change in deployments occurs\")\n\n}\n<commit_msg>adds instances to status command<commit_after>package cmd\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/oberd\/ecsy\/ecs\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar prevCount int\nvar poll bool\n\nfunc printServiceStatus(cluster, service string) bool {\n\tserviceObj, err := ecs.FindService(cluster, service)\n\tfailOnError(err, fmt.Sprintf(\"Problem finding service: %s %s\\n\", cluster, service))\n\tinstances, err := ecs.GetContainerInstances(cluster, service)\n\tfailOnError(err, \"\")\n\tfmt.Printf(\"Cluster:\\t\\t%s\\n\", cluster)\n\tfmt.Printf(\"Service:\\t\\t%s\\n\", service)\n\tfmt.Printf(\"Task Definition:\\t%s\\n\", path.Base(*serviceObj.TaskDefinition))\n\tfmt.Printf(\"Instances:\\n\\t%s\\n\", strings.Join(instances, \"\\n\\t\"))\n\tfmt.Println(\"Deployments:\")\n\tfor _, d := range serviceObj.Deployments {\n\t\tfmt.Printf(\"%s %s (%d Desired, %d Pending, %d Running) %v\\n\", path.Base(*d.TaskDefinition), *d.Status, *d.DesiredCount, *d.PendingCount, *d.RunningCount, *d.CreatedAt)\n\t}\n\tcurrCount := len(serviceObj.Deployments)\n\thasChanged := prevCount != 1000 && currCount != prevCount\n\tprevCount = currCount\n\treturn !hasChanged\n}\n\n\/\/ statusCmd represents the status command\nvar statusCmd = &cobra.Command{\n\tUse:   \"status\",\n\tShort: \"View current cluster or service deployment status\",\n\tLong:  \"View current cluster or service deployment status\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tcluster, service := ServiceChooser(args)\n\t\tprevCount = 1000\n\t\tprintServiceStatus(cluster, service)\n\t\tfor poll {\n\t\t\ttime.Sleep(15 * time.Second)\n\t\t\tpoll = printServiceStatus(cluster, service)\n\t\t}\n\t},\n}\n\nfunc init() {\n\tRootCmd.AddCommand(statusCmd)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\n\t\/\/ Cobra supports Persistent Flags which will work for this command\n\t\/\/ and all subcommands, e.g.:\n\t\/\/ statusCmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t\/\/ Cobra supports local flags which will only run when this command\n\t\/\/ is called directly, e.g.:\n\tstatusCmd.Flags().BoolVarP(&poll, \"poll\", \"p\", false, \"Poll at a 15 second interval until a change in deployments occurs\")\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/zrepl\/zrepl\/logger\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\/\/ daemonCmd represents the daemon command\nvar daemonCmd = &cobra.Command{\n\tUse:   \"daemon\",\n\tShort: \"start daemon\",\n\tRun:   doDaemon,\n}\n\nfunc init() {\n\tRootCmd.AddCommand(daemonCmd)\n}\n\ntype Job interface {\n\tJobName() string\n\tJobStart(ctxt context.Context)\n}\n\nfunc doDaemon(cmd *cobra.Command, args []string) {\n\n\tconf, err := ParseConfig(rootArgs.configFile)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error parsing config: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlog := logger.NewLogger(conf.Global.logging.Outlets, 1*time.Second)\n\n\tlog.Info(NewZreplVersionInformation().String())\n\tlog.Debug(\"starting daemon\")\n\tctx := context.WithValue(context.Background(), contextKeyLog, log)\n\tctx = context.WithValue(ctx, contextKeyLog, log)\n\n\td := NewDaemon(conf)\n\td.Loop(ctx)\n\n}\n\ntype contextKey string\n\nconst (\n\tcontextKeyLog contextKey = contextKey(\"log\")\n)\n\ntype Daemon struct {\n\tconf *Config\n}\n\nfunc NewDaemon(initialConf *Config) *Daemon {\n\treturn &Daemon{initialConf}\n}\n\nfunc (d *Daemon) Loop(ctx context.Context) {\n\n\tlog := ctx.Value(contextKeyLog).(Logger)\n\n\tctx, cancel := context.WithCancel(ctx)\n\n\tsigChan := make(chan os.Signal, 1)\n\tfinishs := make(chan Job)\n\n\tsignal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)\n\n\tlog.Info(\"starting jobs from config\")\n\ti := 0\n\tfor _, job := range d.conf.Jobs {\n\t\tlogger := log.WithField(logJobField, job.JobName())\n\t\tlogger.Info(\"starting\")\n\t\ti++\n\t\tjobCtx := context.WithValue(ctx, contextKeyLog, logger)\n\t\tgo func(j Job) {\n\t\t\tj.JobStart(jobCtx)\n\t\t\tfinishs <- j\n\t\t}(job)\n\t}\n\n\tfinishCount := 0\nouter:\n\tfor {\n\t\tselect {\n\t\tcase <-finishs:\n\t\t\tfinishCount++\n\t\t\tif finishCount == len(d.conf.Jobs) {\n\t\t\t\tlog.Info(\"all jobs finished\")\n\t\t\t\tbreak outer\n\t\t\t}\n\n\t\tcase sig := <-sigChan:\n\t\t\tlog.WithField(\"signal\", sig).Info(\"received signal\")\n\t\t\tlog.Info(\"cancelling all jobs\")\n\t\t\tcancel()\n\t\t}\n\t}\n\n\tsignal.Stop(sigChan)\n\tcancel() \/\/ make go vet happy\n\n\tlog.Info(\"exiting\")\n\n}\n<commit_msg>daemon: Task abstraction + TaskStatus<commit_after>package cmd\n\nimport (\n\t\"container\/list\"\n\t\"context\"\n\t\"fmt\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/zrepl\/zrepl\/logger\"\n\t\"io\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\/\/ daemonCmd represents the daemon command\nvar daemonCmd = &cobra.Command{\n\tUse:   \"daemon\",\n\tShort: \"start daemon\",\n\tRun:   doDaemon,\n}\n\nfunc init() {\n\tRootCmd.AddCommand(daemonCmd)\n}\n\ntype Job interface {\n\tJobName() string\n\tJobStart(ctxt context.Context)\n}\n\nfunc doDaemon(cmd *cobra.Command, args []string) {\n\n\tconf, err := ParseConfig(rootArgs.configFile)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error parsing config: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlog := logger.NewLogger(conf.Global.logging.Outlets, 1*time.Second)\n\n\tlog.Info(NewZreplVersionInformation().String())\n\tlog.Debug(\"starting daemon\")\n\tctx := context.WithValue(context.Background(), contextKeyLog, log)\n\tctx = context.WithValue(ctx, contextKeyLog, log)\n\n\td := NewDaemon(conf)\n\td.Loop(ctx)\n\n}\n\ntype contextKey string\n\nconst (\n\tcontextKeyLog contextKey = contextKey(\"log\")\n)\n\ntype Daemon struct {\n\tconf *Config\n}\n\nfunc NewDaemon(initialConf *Config) *Daemon {\n\treturn &Daemon{initialConf}\n}\n\nfunc (d *Daemon) Loop(ctx context.Context) {\n\n\tlog := ctx.Value(contextKeyLog).(Logger)\n\n\tctx, cancel := context.WithCancel(ctx)\n\n\tsigChan := make(chan os.Signal, 1)\n\tfinishs := make(chan Job)\n\n\tsignal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)\n\n\tlog.Info(\"starting jobs from config\")\n\ti := 0\n\tfor _, job := range d.conf.Jobs {\n\t\tlogger := log.WithField(logJobField, job.JobName())\n\t\tlogger.Info(\"starting\")\n\t\ti++\n\t\tjobCtx := context.WithValue(ctx, contextKeyLog, logger)\n\t\tgo func(j Job) {\n\t\t\tj.JobStart(jobCtx)\n\t\t\tfinishs <- j\n\t\t}(job)\n\t}\n\n\tfinishCount := 0\nouter:\n\tfor {\n\t\tselect {\n\t\tcase <-finishs:\n\t\t\tfinishCount++\n\t\t\tif finishCount == len(d.conf.Jobs) {\n\t\t\t\tlog.Info(\"all jobs finished\")\n\t\t\t\tbreak outer\n\t\t\t}\n\n\t\tcase sig := <-sigChan:\n\t\t\tlog.WithField(\"signal\", sig).Info(\"received signal\")\n\t\t\tlog.Info(\"cancelling all jobs\")\n\t\t\tcancel()\n\t\t}\n\t}\n\n\tsignal.Stop(sigChan)\n\tcancel() \/\/ make go vet happy\n\n\tlog.Info(\"exiting\")\n\n}\n\n\/\/ Representation of a Task's status\ntype TaskStatus struct {\n\tName string\n\t\/\/ Whether the task is idle.\n\tIdle bool\n\t\/\/ The stack of activities the task is currently executing.\n\t\/\/ The first element is the root activity and equal to Name.\n\tActivityStack []string\n\t\/\/ Number of bytes received by the task since it last left idle state.\n\tProgressRx int64\n\t\/\/ Number of bytes sent by the task since it last left idle state.\n\tProgressTx int64\n\t\/\/ Log entries emitted by the task since it last left idle state.\n\t\/\/ Only contains the log entries emitted through the task's logger\n\t\/\/ (provided by Task.Log()).\n\tLogEntries []logger.Entry\n\t\/\/ The maximum log level of LogEntries.\n\t\/\/ Only valid if len(LogEntries) > 0.\n\tMaxLogLevel logger.Level\n}\n\n\/\/ An instance of Task tracks  a single thread of activity that is part of a Job.\ntype Task struct {\n\t\/\/ Stack of activities the task is currently in\n\t\/\/ Members are instances of taskActivity\n\tactivities *list.List\n\t\/\/ Protects Task members from modification\n\trwl sync.RWMutex\n}\n\n\/\/ Structure that describes the progress a Task has made\ntype taskProgress struct {\n\trx         int64\n\ttx         int64\n\tlastUpdate time.Time\n\tlogEntries []logger.Entry\n\tmtx        sync.RWMutex\n}\n\nfunc newTaskProgress() (p *taskProgress) {\n\treturn &taskProgress{\n\t\tlogEntries: make([]logger.Entry, 0),\n\t}\n}\n\nfunc (p *taskProgress) UpdateIO(drx, dtx int64) {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\tp.rx += drx\n\tp.tx += dtx\n\tp.lastUpdate = time.Now()\n}\n\nfunc (p *taskProgress) UpdateLogEntry(entry logger.Entry) {\n\tp.mtx.Lock()\n\tdefer p.mtx.Unlock()\n\t\/\/ FIXME: ensure maximum size (issue #48)\n\tp.logEntries = append(p.logEntries, entry)\n\tp.lastUpdate = time.Now()\n}\n\nfunc (p *taskProgress) DeepCopy() (out taskProgress) {\n\tp.mtx.RLock()\n\tdefer p.mtx.RUnlock()\n\tout.rx, out.tx = p.rx, p.tx\n\tout.logEntries = make([]logger.Entry, len(p.logEntries))\n\tfor i := range p.logEntries {\n\t\tout.logEntries[i] = p.logEntries[i]\n\t}\n\treturn\n}\n\n\/\/ returns a copy of this taskProgress, the mutex carries no semantic value\nfunc (p *taskProgress) Read() (out taskProgress) {\n\tp.mtx.RLock()\n\tdefer p.mtx.RUnlock()\n\treturn p.DeepCopy()\n}\n\n\/\/ Element of a Task's activity stack\ntype taskActivity struct {\n\tname   string\n\tidle   bool\n\tlogger *logger.Logger\n\t\/\/ The progress of the task that is updated by UpdateIO() and UpdateLogEntry()\n\t\/\/\n\t\/\/ Progress happens on a task-level and is thus global to the task.\n\t\/\/ That's why progress is just a pointer to the current taskProgress:\n\t\/\/ we reset progress when leaving the idle root activity\n\tprogress *taskProgress\n}\n\nfunc NewTask(name string, lg *logger.Logger) *Task {\n\tt := &Task{\n\t\tactivities: list.New(),\n\t}\n\trootLogger := lg.ReplaceField(logTaskField, name).\n\t\tWithOutlet(t, logger.Debug)\n\trootAct := &taskActivity{name, true, rootLogger, newTaskProgress()}\n\tt.activities.PushFront(rootAct)\n\treturn t\n}\n\n\/\/ callers must hold t.rwl\nfunc (t *Task) cur() *taskActivity {\n\treturn t.activities.Front().Value.(*taskActivity)\n}\n\n\/\/ buildActivityStack returns the stack of activity names\n\/\/ t.rwl must be held, but the slice can be returned since strings are immutable\nfunc (t *Task) buildActivityStack() []string {\n\tcomps := make([]string, 0, t.activities.Len())\n\tfor e := t.activities.Back(); e != nil; e = e.Prev() {\n\t\tact := e.Value.(*taskActivity)\n\t\tcomps = append(comps, act.name)\n\t}\n\treturn comps\n}\n\n\/\/ Start a sub-activity.\n\/\/ Must always be matched with a call to t.Finish()\n\/\/ --- consider using defer for this purpose.\nfunc (t *Task) Enter(activity string) {\n\tt.rwl.Lock()\n\tdefer t.rwl.Unlock()\n\n\tprev := t.cur()\n\tif prev.idle {\n\t\t\/\/ reset progress when leaving idle task\n\t\t\/\/ we leave the old progress dangling to have the user not worry about\n\t\tprev.progress = newTaskProgress()\n\t}\n\tact := &taskActivity{activity, false, nil, prev.progress}\n\tt.activities.PushFront(act)\n\tstack := t.buildActivityStack()\n\tactivityField := strings.Join(stack, \".\")\n\tact.logger = prev.logger.ReplaceField(logTaskField, activityField)\n\n}\n\nfunc (t *Task) UpdateProgress(dtx, drx int64) {\n\tt.rwl.RLock()\n\tp := t.cur().progress \/\/ protected by own rwlock\n\tt.rwl.RUnlock()\n\tp.UpdateIO(dtx, drx)\n}\n\n\/\/ Returns a wrapper io.Reader that updates this task's _current_ progress value.\n\/\/ Progress updates after this task resets its progress value are discarded.\nfunc (t *Task) ProgressUpdater(r io.Reader) *IOProgressUpdater {\n\tt.rwl.RLock()\n\tdefer t.rwl.RUnlock()\n\treturn &IOProgressUpdater{r, t.cur().progress}\n}\n\nfunc (t *Task) Status() *TaskStatus {\n\tt.rwl.RLock()\n\tdefer t.rwl.RUnlock()\n\t\/\/ NOTE\n\t\/\/ do not return any state in TaskStatus that is protected by t.rwl\n\n\tcur := t.cur()\n\tstack := t.buildActivityStack()\n\tprog := cur.progress.Read()\n\n\tvar maxLevel logger.Level\n\tfor _, entry := range prog.logEntries {\n\t\tif maxLevel < entry.Level {\n\t\t\tmaxLevel = entry.Level\n\t\t}\n\t}\n\n\ts := &TaskStatus{\n\t\tName:          stack[0],\n\t\tActivityStack: stack,\n\t\tIdle:          cur.idle,\n\t\tProgressRx:    prog.rx,\n\t\tProgressTx:    prog.tx,\n\t\tLogEntries:    prog.logEntries,\n\t\tMaxLogLevel:   maxLevel,\n\t}\n\n\treturn s\n}\n\n\/\/ Finish a sub-activity.\n\/\/ Corresponds to a preceding call to t.Enter()\nfunc (t *Task) Finish() {\n\tt.rwl.Lock()\n\tdefer t.rwl.Unlock()\n\ttop := t.activities.Front()\n\tif top.Next() == nil {\n\t\treturn \/\/ cannot remove root activity\n\t}\n\tt.activities.Remove(top)\n\n}\n\n\/\/ Returns a logger derived from the logger passed to the constructor function.\n\/\/ The logger's task field contains the current activity stack joined by '.'.\nfunc (t *Task) Log() *logger.Logger {\n\tt.rwl.RLock()\n\tdefer t.rwl.RUnlock()\n\treturn t.cur().logger\n}\n\n\/\/ implement logger.Outlet interface\nfunc (t *Task) WriteEntry(ctx context.Context, entry logger.Entry) error {\n\tt.rwl.RLock()\n\tdefer t.rwl.RUnlock()\n\tt.cur().progress.UpdateLogEntry(entry)\n\treturn nil\n}\n\ntype IOProgressUpdater struct {\n\tr io.Reader\n\tp *taskProgress\n}\n\nfunc (u *IOProgressUpdater) Read(p []byte) (n int, err error) {\n\tn, err = u.r.Read(p)\n\tu.p.UpdateIO(int64(n), 0)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nstruct texFmt {\n\tlvl int\n\tps  int\n\t*par\n\toutfig string\n}\n\nconst lspecial = `&_$\\%{}#`\n\nfunc escTex(s string) string {\n\tns := \"\"\n\tnoesc := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase r == 1:\n\t\t\tnoesc = true\n\t\t\tcontinue\n\t\tcase r == 2:\n\t\t\tnoesc = false\n\t\t\tcontinue\n\t\tcase noesc:\n\t\tcase strings.ContainsRune(lspecial, r):\n\t\t\tns += `\\`\n\t\t}\n\t\tns += string(r)\n\t}\n\treturn ns\n}\n\nvar figstart = map[Kind]string{\n\tKpic:  \".PS\",\n\tKgrap: \".G1\",\n\tKeqn:  \".EQ\",\n}\nvar figend = map[Kind]string{\n\tKpic:  \".PE\",\n\tKgrap: \".G2\",\n\tKeqn:  \".EN\",\n}\n\nfunc (f *texFmt) wrText(e *Elem) {\n\tif e == nil {\n\t\treturn\n\t}\n\tswitch e.Kind {\n\tcase Khdr1, Khdr2, Khdr3, Kfoot:\n\tdefault:\n\t\tif e.Nb != \"\" {\n\t\t\tf.printPar(e.Nb, \" \")\n\t\t}\n\t}\n\tswitch e.Kind {\n\tcase Kit, Kbf, Ktt, Kitend, Kbfend, Kttend:\n\t\tf.wrFnt(e)\n\tcase Kfont:\n\t\tf.fntSz(e.Data)\n\tcase Kurl:\n\t\ttoks := strings.SplitN(e.Data, \"|\", 2)\n\t\tif len(toks) == 1 {\n\t\t\tf.printParCmd(`\\verb|` + e.Data + `|`)\n\t\t} else {\n\t\t\tf.printPar(toks[0] + \" \")\n\t\t\tf.printParCmd(`\\verb|` + toks[1] + `|`)\n\t\t}\n\tcase Kbib:\n\t\tnbs := strings.Split(e.Data, \",\")\n\t\tif len(nbs) == 0 {\n\t\t\tnbs = append(nbs, \"XXX\")\n\t\t}\n\t\te.Data = `\\cite{bib` + nbs[0]\n\t\tfor _, nb := range nbs[1:] {\n\t\t\te.Data += \",bib\" + nb\n\t\t}\n\t\te.Data += \"}\"\n\t\tf.printParCmd(e.Data)\n\tcase Kcref:\n\t\tf.printParCmd(`\\ref{lst` + e.Data + `}`)\n\tcase Keref:\n\t\tf.printParCmd(`\\ref{eqn` + e.Data + `}`)\n\tcase Ktref:\n\t\tf.printParCmd(`\\ref{tbl` + e.Data + `}`)\n\tcase Kfref:\n\t\tf.printParCmd(`\\ref{fig` + e.Data + `}`)\n\tcase Ksref:\n\t\tnb := strings.Replace(e.Data, \".\", \"x\", -1)\n\t\tf.printParCmd(`\\ref{sec` + nb + `}`)\n\tcase Kcite:\n\t\te.Data = \"[\" + e.Data + \"]\"\n\t\tf.printPar(e.Data)\n\tdefault:\n\t\tif e.Kind == Knref {\n\t\t\te.Data = footRef(e.Data)\n\t\t}\n\t\tf.printPar(e.Data)\n\t\tfor _, c := range e.Textchild {\n\t\t\tf.wrText(c)\n\t\t}\n\t}\n}\n\nvar ilfnts = map[Kind]string{\n\tKit:    `\\textit{`,\n\tKbf:    `\\textbf{`,\n\tKtt:    `\\texttt{`,\n\tKitend: \"}\",\n\tKbfend: \"}\",\n\tKttend: \"}\",\n}\n\nvar lfnts = map[Kind]string{\n\tKit:    `\\textit{%`,\n\tKbf:    `\\textbf{%`,\n\tKtt:    `\\texttt{%`,\n\tKitend: \"}%\",\n\tKbfend: \"}%\",\n\tKttend: \"}%\",\n}\n\nvar lhdrs = map[Kind]string{\n\tKhdr1: \"section\",\n\tKhdr2: \"subsection\",\n\tKhdr3: \"subsubsection\",\n}\n\nvar llst = map[Kind]string{\n\tKindent:      \"itemize\",\n\tKitemize:     \"itemize\",\n\tKenumeration: \"enumerate\",\n\tKdescription: \"description\",\n}\n\nfunc (f *texFmt) wrFnt(e *Elem) {\n\tif e.Inline {\n\t\tf.printParCmd(ilfnts[e.Kind])\n\t} else {\n\t\tf.printCmd(\"%s\\n\", lfnts[e.Kind])\n\t}\n}\n\nvar lszs = map[int]string{\n\t-5: \"tiny\",\n\t-4: \"tiny\",\n\t-3: \"scriptsize\",\n\t-2: \"footnotesize\",\n\t-1: \"small\",\n\t0:  \"normalsize\",\n\t1:  \"large\",\n\t2:  \"Large\",\n\t3:  \"LARGE\",\n\t4:  \"huge\",\n\t5:  \"Huge\",\n}\n\nfunc (f *texFmt) fntSz(d string) {\n\tif len(d) == 0 {\n\t\treturn\n\t}\n\tn, _ := strconv.Atoi(d)\n\tf.ps += n\n\ts := lszs[f.ps]\n\tif s == \"\" {\n\t\ts = lszs[0]\n\t}\n\tf.printParCmd(`\\` + s + ` `)\n}\n\nfunc (f *texFmt) wrCaption(e *Elem) {\n\tf.printParCmd(`\\caption{`)\n\tif e.Caption != nil {\n\t\tf.wrText(e.Caption)\n\t}\n\tf.printParCmd(`\\label{` + llbl[e.Kind] + e.Nb + `}`)\n\tf.printParCmd(`}`)\n}\n\nvar llbl = map[Kind]string{\n\tKfig:  \"fig\",\n\tKpic:  \"fig\",\n\tKcode: \"lst\",\n\tKfoot: \"foot\",\n\tKeqn:  \"eqn\",\n\tKtbl:  \"tbl\",\n\tKhdr1: \"sec\",\n\tKhdr2: \"sec\",\n\tKhdr3: \"sec\",\n}\n\nfunc (f *texFmt) wrElems(els ...*Elem) {\n\tinabs := false\n\tpref := strings.Repeat(f.tab, f.lvl)\n\tf.lvl++\n\tdefer func() {\n\t\tf.lvl--\n\t}()\n\tfor _, e := range els {\n\t\tf.i0, f.in = pref, pref\n\t\tswitch e.Kind {\n\t\tcase Kit, Kbf, Ktt, Kitend, Kbfend, Kttend:\n\t\t\tf.wrFnt(e)\n\t\tcase Kfont:\n\t\t\tf.fntSz(e.Data)\n\t\tcase Khdr1, Khdr2, Khdr3:\n\t\t\tif inabs {\n\t\t\t\tf.printCmd(`\\end{abstract}` + \"\\n\\n\")\n\t\t\t\tinabs = false\n\t\t\t}\n\t\t\tif strings.ToLower(e.Data) == \"abstract\" {\n\t\t\t\tf.printCmd(`\\begin{abstract}` + \"\\n\")\n\t\t\t\tinabs = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tf.closePar()\n\t\t\tf.printParCmd(\"\\\\\", lhdrs[e.Kind], \"{\")\n\t\t\tf.wrText(e)\n\t\t\tf.printParCmd(\"}\")\n\t\t\tf.closePar()\n\t\t\tf.printCmd(pref + `\\label{` + llbl[e.Kind] +\n\t\t\t\tstrings.Replace(e.Nb, \".\", \"x\", -1) + `}` + \"\\n\")\n\t\tcase Kpar:\n\t\t\tf.printCmd(\"\\n\")\n\t\t\tif inabs {\n\t\t\t\tf.printCmd(`\\end{abstract}` + \"\\n\")\n\t\t\t\tinabs = false\n\t\t\t}\n\t\tcase Kbr:\n\t\t\tf.printParCmd(`\\\\`)\n\t\t\tf.closePar()\n\t\tcase Kindent:\n\t\t\t\/\/ If it contains just a fig, pic, or tbl, then\n\t\t\t\/\/ skip this level and jump to the child\n\t\t\tif len(e.Child) == 1 || len(e.Child) == 2 && e.Child[1].Kind == Kpar {\n\t\t\t\tswitch e.Child[0].Kind {\n\t\t\t\tcase Kfig, Kpic, Keqn, Ktbl, Kgrap, Kcode:\n\t\t\t\t\tf.wrElems(e.Child...)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tfallthrough\n\t\tcase Kitemize, Kenumeration, Kdescription:\n\t\t\tf.closePar()\n\t\t\tf.printCmd(pref + `\\begin{` + llst[e.Kind] + `}` + \"\\n\")\n\t\t\tif e.Kind == Kindent {\n\t\t\t\tf.printCmd(pref + `\\item[]` + \"\\n\")\n\t\t\t}\n\t\t\tf.wrElems(e.Child...)\n\t\t\tf.printCmd(pref + `\\end{` + llst[e.Kind] + `}` + \"\\n\")\n\t\tcase Kname:\n\t\t\tf.closePar()\n\t\t\tf.printParCmd(`\\item[`)\n\t\t\tf.wrText(e)\n\t\t\tf.printParCmd(`]`)\n\t\t\tf.closePar()\n\t\t\tf.wrElems(e.Child...)\n\t\tcase Kitem, Kenum:\n\t\t\tf.closePar()\n\t\t\tf.printCmd(\"\\n\")\n\t\t\tf.printParCmd(`\\item `)\n\t\t\tf.wrText(e)\n\t\tcase Kverb, Ksh:\n\t\t\tf.printCmd(pref + `\\begin{verbatim}` + \"\\n\")\n\t\t\te.Data = indentVerb(e.Data, f.i0, f.tab)\n\t\t\tf.printCmd(\"%s\", e.Data)\n\t\t\tf.printCmd(pref + `\\end{verbatim}` + \"\\n\")\n\t\tcase Kfoot:\n\t\t\tf.printCmd(`\\let\\thefootnote\\relax\\footnote{` + e.Nb + \". \")\n\t\t\tf.wrText(e)\n\t\t\tf.printCmd(`}` + \"\\n\")\n\t\tcase Ktext, Kurl, Kbib, Kcref, Keref, Ktref, Kfref, Knref, Ksref, Kcite:\n\t\t\tf.wrText(e)\n\t\tcase Kfig, Kpic, Kcode, Kgrap, Keqn:\n\t\t\tf.printCmd(pref + `\\begin{figure}` + \"\\n\")\n\t\t\tf.printCmd(pref + `\\centering` + \"\\n\")\n\t\t\tswitch e.Kind {\n\t\t\tcase Kpic, Kgrap:\n\t\t\t\tfn := e.pic(f.outfig)\n\t\t\t\tf.printCmd(\"%s\\n\", pref+f.tab+`\\includegraphics{`+fn+\"}\")\n\t\t\tcase Kfig:\n\t\t\t\te.Data = strings.TrimSpace(e.Data)\n\t\t\t\tfn := e.pdffig()\n\t\t\t\tf.printCmd(\"%s\\n\", pref+f.tab+`\\includegraphics{`+fn+\"}\")\n\t\t\tcase Keqn:\n\t\t\t\tfn := e.pic(f.outfig)\n\t\t\t\tf.printCmd(\"%s\\n\", pref+f.tab+`\\includegraphics{`+fn+\"}\")\n\t\t\tcase Kcode:\n\t\t\t\txpref := pref + f.tab\n\t\t\t\tf.printCmd(xpref + `\\begin{verbatim}` + \"\\n\")\n\t\t\t\tf.printCmd(\"%s\\n\", indentVerb(e.Data, xpref+f.tab, f.tab))\n\t\t\t\tf.printCmd(xpref + `\\end{verbatim}` + \"\\n\")\n\t\t\t}\n\t\t\tf.closePar()\n\t\t\tf.wrCaption(e)\n\t\t\tf.printCmd(pref + `\\end{figure}` + \"\\n\")\n\t\tcase Ktbl:\n\t\t\tf.closePar()\n\t\t\tf.printCmd(pref + `\\begin{table}` + \"\\n\")\n\t\t\tf.printCmd(pref + `\\centering` + \"\\n\")\n\t\t\tf.lvl++\n\t\t\tf.i0, f.in = pref+f.tab, pref+f.tab\n\t\t\tf.wrTbl(e.Tbl)\n\t\t\tf.lvl--\n\t\t\tf.wrCaption(e)\n\t\t\tf.printCmd(pref + `\\end{table}` + \"\\n\")\n\t\t}\n\t}\n\tf.closePar()\n}\n\nfunc (f *texFmt) wrTbl(rows [][]string) {\n\tif len(rows) < 2 || len(rows[0]) < 2 || len(rows[1]) < 2 {\n\t\treturn\n\t}\n\trfmt := rows[0]\n\trows = rows[1:]\n\ttfmt := \"\"\n\trfmt[0] = \"|l\"\n\tfor _, r := range rfmt {\n\t\ttfmt += \"|\" + r\n\t}\n\ttfmt += \"|\"\n\tf.printCmd(f.i0 + `\\begin{tabular}{` + tfmt + `}\\hline` + \"\\n\")\n\trows[0][0] = \"\"\n\tfor i, r := range rows {\n\t\tf.printCmd(f.i0 + f.tab)\n\t\tfor j, c := range r {\n\t\t\tif j > 0 {\n\t\t\t\tf.printCmd(\"\\t&\")\n\t\t\t}\n\t\t\tf.printCmd(\"%s\", escTex(c))\n\t\t}\n\t\tif i < len(rows)-1 {\n\t\t\tf.printCmd(`\\\\ \\hline` + \"\\n\")\n\t\t} else {\n\t\t\tf.printCmd(`\\\\` + \"\\n\")\n\t\t}\n\t}\n\tf.printCmd(f.i0 + f.tab + `\\hline` + \"\\n\")\n\tf.printCmd(f.i0 + `\\end{tabular}` + \"\\n\")\n}\n\nfunc (f *texFmt) wrBib(refs []string) {\n\tif len(refs) == 0 {\n\t\treturn\n\t}\n\tf.printCmd(`\\begin{thebibliography}{50}` + \"\\n\")\n\tf.i0 = f.tab\n\tf.in = f.tab\n\tfor i, r := range refs {\n\t\tk := fmt.Sprintf(\"bib%d\", i+1)\n\t\tf.printCmd(`\\bibitem{` + k + `} `)\n\t\tf.printPar(r)\n\t\tf.closePar()\n\t}\n\tf.printCmd(`\\end{thebibliography}` + \"\\n\")\n}\n\nfunc (f *texFmt) run(t *Text) {\n\tf.printCmd(\"%s\\n\", `% use pdflatex to compile this.`)\n\tf.printCmd(`\\documentclass[a4paper]{article}` + \"\\n\")\n\tf.printCmd(`\\usepackage{graphicx}` + \"\\n\")\n\tf.printCmd(`\\usepackage[utf8x]{inputenc}` + \"\\n\")\n\tels := t.Elems\n\tn := 0\n\tfor len(els) > 0 && els[0].Kind == Ktitle {\n\t\tswitch n {\n\t\tcase 0:\n\t\t\tf.printParCmd(\"\\\\title{\")\n\t\t\tf.wrText(els[0])\n\t\t\tf.printParCmd(\"}\")\n\t\t\tf.closePar()\n\t\tcase 1:\n\t\t\tf.printParCmd(\"\\\\author{\")\n\t\t\tf.wrText(els[0])\n\t\tdefault:\n\t\t\tf.printParCmd(`\\\\`)\n\t\t\tf.closePar()\n\t\t\tf.wrText(els[0])\n\t\t}\n\t\tn++\n\t\tels = els[1:]\n\t}\n\tif n > 0 {\n\t\tf.printParCmd(\"}\\n\")\n\t}\n\tf.printCmd(\"\\n\\\\begin{document}\\n\")\n\tf.printCmd(\"\\n\\\\maketitle{}\\n\")\n\tf.wrElems(els...)\n\tf.wrBib(t.bibrefs)\n\tf.printCmd(\"\\n\\\\end{document}\\n\")\n}\n\n\/\/ (la)tex writer\nfunc wrtex(t *Text, wid int, out io.Writer, outfig string) {\n\tf := &texFmt{\n\t\tpar:    &par{fn: escTex, out: out, wid: wid, tab: \"    \"},\n\t\toutfig: outfig,\n\t}\n\tf.run(t)\n}\n<commit_msg>latex fig label fix<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nstruct texFmt {\n\tlvl int\n\tps  int\n\t*par\n\toutfig string\n}\n\nconst lspecial = `&_$\\%{}#`\n\nfunc escTex(s string) string {\n\tns := \"\"\n\tnoesc := false\n\tfor _, r := range s {\n\t\tswitch {\n\t\tcase r == 1:\n\t\t\tnoesc = true\n\t\t\tcontinue\n\t\tcase r == 2:\n\t\t\tnoesc = false\n\t\t\tcontinue\n\t\tcase noesc:\n\t\tcase strings.ContainsRune(lspecial, r):\n\t\t\tns += `\\`\n\t\t}\n\t\tns += string(r)\n\t}\n\treturn ns\n}\n\nvar figstart = map[Kind]string{\n\tKpic:  \".PS\",\n\tKgrap: \".G1\",\n\tKeqn:  \".EQ\",\n}\nvar figend = map[Kind]string{\n\tKpic:  \".PE\",\n\tKgrap: \".G2\",\n\tKeqn:  \".EN\",\n}\n\nfunc (f *texFmt) wrText(e *Elem) {\n\tif e == nil {\n\t\treturn\n\t}\n\tswitch e.Kind {\n\tcase Khdr1, Khdr2, Khdr3, Kfoot:\n\tdefault:\n\t\tif e.Nb != \"\" {\n\t\t\tf.printPar(e.Nb, \" \")\n\t\t}\n\t}\n\tswitch e.Kind {\n\tcase Kit, Kbf, Ktt, Kitend, Kbfend, Kttend:\n\t\tf.wrFnt(e)\n\tcase Kfont:\n\t\tf.fntSz(e.Data)\n\tcase Kurl:\n\t\ttoks := strings.SplitN(e.Data, \"|\", 2)\n\t\tif len(toks) == 1 {\n\t\t\tf.printParCmd(`\\verb|` + e.Data + `|`)\n\t\t} else {\n\t\t\tf.printPar(toks[0] + \" \")\n\t\t\tf.printParCmd(`\\verb|` + toks[1] + `|`)\n\t\t}\n\tcase Kbib:\n\t\tnbs := strings.Split(e.Data, \",\")\n\t\tif len(nbs) == 0 {\n\t\t\tnbs = append(nbs, \"XXX\")\n\t\t}\n\t\te.Data = `\\cite{bib` + nbs[0]\n\t\tfor _, nb := range nbs[1:] {\n\t\t\te.Data += \",bib\" + nb\n\t\t}\n\t\te.Data += \"}\"\n\t\tf.printParCmd(e.Data)\n\tcase Kcref:\n\t\tf.printParCmd(`\\ref{lst` + e.Data + `}`)\n\tcase Keref:\n\t\tf.printParCmd(`\\ref{eqn` + e.Data + `}`)\n\tcase Ktref:\n\t\tf.printParCmd(`\\ref{tbl` + e.Data + `}`)\n\tcase Kfref:\n\t\tf.printParCmd(`\\ref{fig` + e.Data + `}`)\n\tcase Ksref:\n\t\tnb := strings.Replace(e.Data, \".\", \"x\", -1)\n\t\tf.printParCmd(`\\ref{sec` + nb + `}`)\n\tcase Kcite:\n\t\te.Data = \"[\" + e.Data + \"]\"\n\t\tf.printPar(e.Data)\n\tdefault:\n\t\tif e.Kind == Knref {\n\t\t\te.Data = footRef(e.Data)\n\t\t}\n\t\tf.printPar(e.Data)\n\t\tfor _, c := range e.Textchild {\n\t\t\tf.wrText(c)\n\t\t}\n\t}\n}\n\nvar ilfnts = map[Kind]string{\n\tKit:    `\\textit{`,\n\tKbf:    `\\textbf{`,\n\tKtt:    `\\texttt{`,\n\tKitend: \"}\",\n\tKbfend: \"}\",\n\tKttend: \"}\",\n}\n\nvar lfnts = map[Kind]string{\n\tKit:    `\\textit{%`,\n\tKbf:    `\\textbf{%`,\n\tKtt:    `\\texttt{%`,\n\tKitend: \"}%\",\n\tKbfend: \"}%\",\n\tKttend: \"}%\",\n}\n\nvar lhdrs = map[Kind]string{\n\tKhdr1: \"section\",\n\tKhdr2: \"subsection\",\n\tKhdr3: \"subsubsection\",\n}\n\nvar llst = map[Kind]string{\n\tKindent:      \"itemize\",\n\tKitemize:     \"itemize\",\n\tKenumeration: \"enumerate\",\n\tKdescription: \"description\",\n}\n\nfunc (f *texFmt) wrFnt(e *Elem) {\n\tif e.Inline {\n\t\tf.printParCmd(ilfnts[e.Kind])\n\t} else {\n\t\tf.printCmd(\"%s\\n\", lfnts[e.Kind])\n\t}\n}\n\nvar lszs = map[int]string{\n\t-5: \"tiny\",\n\t-4: \"tiny\",\n\t-3: \"scriptsize\",\n\t-2: \"footnotesize\",\n\t-1: \"small\",\n\t0:  \"normalsize\",\n\t1:  \"large\",\n\t2:  \"Large\",\n\t3:  \"LARGE\",\n\t4:  \"huge\",\n\t5:  \"Huge\",\n}\n\nfunc (f *texFmt) fntSz(d string) {\n\tif len(d) == 0 {\n\t\treturn\n\t}\n\tn, _ := strconv.Atoi(d)\n\tf.ps += n\n\ts := lszs[f.ps]\n\tif s == \"\" {\n\t\ts = lszs[0]\n\t}\n\tf.printParCmd(`\\` + s + ` `)\n}\n\nfunc (f *texFmt) wrCaption(e *Elem) {\n\tf.printParCmd(`\\caption{`)\n\tif e.Caption != nil {\n\t\tf.wrText(e.Caption)\n\t}\n\tf.printParCmd(`\\label{` + llbl[e.Kind] + e.Nb + `}`)\n\tf.printParCmd(`}`)\n}\n\nvar llbl = map[Kind]string{\n\tKfig:  \"fig\",\n\tKpic:  \"fig\",\n\tKgrap:  \"fig\",\n\tKcode: \"lst\",\n\tKfoot: \"foot\",\n\tKeqn:  \"eqn\",\n\tKtbl:  \"tbl\",\n\tKhdr1: \"sec\",\n\tKhdr2: \"sec\",\n\tKhdr3: \"sec\",\n}\n\nfunc (f *texFmt) wrElems(els ...*Elem) {\n\tinabs := false\n\tpref := strings.Repeat(f.tab, f.lvl)\n\tf.lvl++\n\tdefer func() {\n\t\tf.lvl--\n\t}()\n\tfor _, e := range els {\n\t\tf.i0, f.in = pref, pref\n\t\tswitch e.Kind {\n\t\tcase Kit, Kbf, Ktt, Kitend, Kbfend, Kttend:\n\t\t\tf.wrFnt(e)\n\t\tcase Kfont:\n\t\t\tf.fntSz(e.Data)\n\t\tcase Khdr1, Khdr2, Khdr3:\n\t\t\tif inabs {\n\t\t\t\tf.printCmd(`\\end{abstract}` + \"\\n\\n\")\n\t\t\t\tinabs = false\n\t\t\t}\n\t\t\tif strings.ToLower(e.Data) == \"abstract\" {\n\t\t\t\tf.printCmd(`\\begin{abstract}` + \"\\n\")\n\t\t\t\tinabs = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tf.closePar()\n\t\t\tf.printParCmd(\"\\\\\", lhdrs[e.Kind], \"{\")\n\t\t\tf.wrText(e)\n\t\t\tf.printParCmd(\"}\")\n\t\t\tf.closePar()\n\t\t\tf.printCmd(pref + `\\label{` + llbl[e.Kind] +\n\t\t\t\tstrings.Replace(e.Nb, \".\", \"x\", -1) + `}` + \"\\n\")\n\t\tcase Kpar:\n\t\t\tf.printCmd(\"\\n\")\n\t\t\tif inabs {\n\t\t\t\tf.printCmd(`\\end{abstract}` + \"\\n\")\n\t\t\t\tinabs = false\n\t\t\t}\n\t\tcase Kbr:\n\t\t\tf.printParCmd(`\\\\`)\n\t\t\tf.closePar()\n\t\tcase Kindent:\n\t\t\t\/\/ If it contains just a fig, pic, or tbl, then\n\t\t\t\/\/ skip this level and jump to the child\n\t\t\tif len(e.Child) == 1 || len(e.Child) == 2 && e.Child[1].Kind == Kpar {\n\t\t\t\tswitch e.Child[0].Kind {\n\t\t\t\tcase Kfig, Kpic, Keqn, Ktbl, Kgrap, Kcode:\n\t\t\t\t\tf.wrElems(e.Child...)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tfallthrough\n\t\tcase Kitemize, Kenumeration, Kdescription:\n\t\t\tf.closePar()\n\t\t\tf.printCmd(pref + `\\begin{` + llst[e.Kind] + `}` + \"\\n\")\n\t\t\tif e.Kind == Kindent {\n\t\t\t\tf.printCmd(pref + `\\item[]` + \"\\n\")\n\t\t\t}\n\t\t\tf.wrElems(e.Child...)\n\t\t\tf.printCmd(pref + `\\end{` + llst[e.Kind] + `}` + \"\\n\")\n\t\tcase Kname:\n\t\t\tf.closePar()\n\t\t\tf.printParCmd(`\\item[`)\n\t\t\tf.wrText(e)\n\t\t\tf.printParCmd(`]`)\n\t\t\tf.closePar()\n\t\t\tf.wrElems(e.Child...)\n\t\tcase Kitem, Kenum:\n\t\t\tf.closePar()\n\t\t\tf.printCmd(\"\\n\")\n\t\t\tf.printParCmd(`\\item `)\n\t\t\tf.wrText(e)\n\t\tcase Kverb, Ksh:\n\t\t\tf.printCmd(pref + `\\begin{verbatim}` + \"\\n\")\n\t\t\te.Data = indentVerb(e.Data, f.i0, f.tab)\n\t\t\tf.printCmd(\"%s\", e.Data)\n\t\t\tf.printCmd(pref + `\\end{verbatim}` + \"\\n\")\n\t\tcase Kfoot:\n\t\t\tf.printCmd(`\\let\\thefootnote\\relax\\footnote{` + e.Nb + \". \")\n\t\t\tf.wrText(e)\n\t\t\tf.printCmd(`}` + \"\\n\")\n\t\tcase Ktext, Kurl, Kbib, Kcref, Keref, Ktref, Kfref, Knref, Ksref, Kcite:\n\t\t\tf.wrText(e)\n\t\tcase Kfig, Kpic, Kcode, Kgrap, Keqn:\n\t\t\tf.printCmd(pref + `\\begin{figure}` + \"\\n\")\n\t\t\tf.printCmd(pref + `\\centering` + \"\\n\")\n\t\t\tswitch e.Kind {\n\t\t\tcase Kpic, Kgrap:\n\t\t\t\tfn := e.pic(f.outfig)\n\t\t\t\tf.printCmd(\"%s\\n\", pref+f.tab+`\\includegraphics{`+fn+\"}\")\n\t\t\tcase Kfig:\n\t\t\t\te.Data = strings.TrimSpace(e.Data)\n\t\t\t\tfn := e.pdffig()\n\t\t\t\tf.printCmd(\"%s\\n\", pref+f.tab+`\\includegraphics{`+fn+\"}\")\n\t\t\tcase Keqn:\n\t\t\t\tfn := e.pic(f.outfig)\n\t\t\t\tf.printCmd(\"%s\\n\", pref+f.tab+`\\includegraphics{`+fn+\"}\")\n\t\t\tcase Kcode:\n\t\t\t\txpref := pref + f.tab\n\t\t\t\tf.printCmd(xpref + `\\begin{verbatim}` + \"\\n\")\n\t\t\t\tf.printCmd(\"%s\\n\", indentVerb(e.Data, xpref+f.tab, f.tab))\n\t\t\t\tf.printCmd(xpref + `\\end{verbatim}` + \"\\n\")\n\t\t\t}\n\t\t\tf.closePar()\n\t\t\tf.wrCaption(e)\n\t\t\tf.printCmd(pref + `\\end{figure}` + \"\\n\")\n\t\tcase Ktbl:\n\t\t\tf.closePar()\n\t\t\tf.printCmd(pref + `\\begin{table}` + \"\\n\")\n\t\t\tf.printCmd(pref + `\\centering` + \"\\n\")\n\t\t\tf.lvl++\n\t\t\tf.i0, f.in = pref+f.tab, pref+f.tab\n\t\t\tf.wrTbl(e.Tbl)\n\t\t\tf.lvl--\n\t\t\tf.wrCaption(e)\n\t\t\tf.printCmd(pref + `\\end{table}` + \"\\n\")\n\t\t}\n\t}\n\tf.closePar()\n}\n\nfunc (f *texFmt) wrTbl(rows [][]string) {\n\tif len(rows) < 2 || len(rows[0]) < 2 || len(rows[1]) < 2 {\n\t\treturn\n\t}\n\trfmt := rows[0]\n\trows = rows[1:]\n\ttfmt := \"\"\n\trfmt[0] = \"|l\"\n\tfor _, r := range rfmt {\n\t\ttfmt += \"|\" + r\n\t}\n\ttfmt += \"|\"\n\tf.printCmd(f.i0 + `\\begin{tabular}{` + tfmt + `}\\hline` + \"\\n\")\n\trows[0][0] = \"\"\n\tfor i, r := range rows {\n\t\tf.printCmd(f.i0 + f.tab)\n\t\tfor j, c := range r {\n\t\t\tif j > 0 {\n\t\t\t\tf.printCmd(\"\\t&\")\n\t\t\t}\n\t\t\tf.printCmd(\"%s\", escTex(c))\n\t\t}\n\t\tif i < len(rows)-1 {\n\t\t\tf.printCmd(`\\\\ \\hline` + \"\\n\")\n\t\t} else {\n\t\t\tf.printCmd(`\\\\` + \"\\n\")\n\t\t}\n\t}\n\tf.printCmd(f.i0 + f.tab + `\\hline` + \"\\n\")\n\tf.printCmd(f.i0 + `\\end{tabular}` + \"\\n\")\n}\n\nfunc (f *texFmt) wrBib(refs []string) {\n\tif len(refs) == 0 {\n\t\treturn\n\t}\n\tf.printCmd(`\\begin{thebibliography}{50}` + \"\\n\")\n\tf.i0 = f.tab\n\tf.in = f.tab\n\tfor i, r := range refs {\n\t\tk := fmt.Sprintf(\"bib%d\", i+1)\n\t\tf.printCmd(`\\bibitem{` + k + `} `)\n\t\tf.printPar(r)\n\t\tf.closePar()\n\t}\n\tf.printCmd(`\\end{thebibliography}` + \"\\n\")\n}\n\nfunc (f *texFmt) run(t *Text) {\n\tf.printCmd(\"%s\\n\", `% use pdflatex to compile this.`)\n\tf.printCmd(`\\documentclass[a4paper]{article}` + \"\\n\")\n\tf.printCmd(`\\usepackage{graphicx}` + \"\\n\")\n\tf.printCmd(`\\usepackage[utf8x]{inputenc}` + \"\\n\")\n\tels := t.Elems\n\tn := 0\n\tfor len(els) > 0 && els[0].Kind == Ktitle {\n\t\tswitch n {\n\t\tcase 0:\n\t\t\tf.printParCmd(\"\\\\title{\")\n\t\t\tf.wrText(els[0])\n\t\t\tf.printParCmd(\"}\")\n\t\t\tf.closePar()\n\t\tcase 1:\n\t\t\tf.printParCmd(\"\\\\author{\")\n\t\t\tf.wrText(els[0])\n\t\tdefault:\n\t\t\tf.printParCmd(`\\\\`)\n\t\t\tf.closePar()\n\t\t\tf.wrText(els[0])\n\t\t}\n\t\tn++\n\t\tels = els[1:]\n\t}\n\tif n > 0 {\n\t\tf.printParCmd(\"}\\n\")\n\t}\n\tf.printCmd(\"\\n\\\\begin{document}\\n\")\n\tf.printCmd(\"\\n\\\\maketitle{}\\n\")\n\tf.wrElems(els...)\n\tf.wrBib(t.bibrefs)\n\tf.printCmd(\"\\n\\\\end{document}\\n\")\n}\n\n\/\/ (la)tex writer\nfunc wrtex(t *Text, wid int, out io.Writer, outfig string) {\n\tf := &texFmt{\n\t\tpar:    &par{fn: escTex, out: out, wid: wid, tab: \"    \"},\n\t\toutfig: outfig,\n\t}\n\tf.run(t)\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/nextgearcapital\/pepper\/pkg\/device42\"\n\t\"github.com\/nextgearcapital\/pepper\/pkg\/log\"\n\t\"github.com\/nextgearcapital\/pepper\/pkg\/salt\"\n\t\"github.com\/nextgearcapital\/pepper\/template\/vsphere\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tprofile    string\n\troles      string\n\tosTemplate string\n\tipam       bool\n)\n\nfunc init() {\n\tRootCmd.AddCommand(deployCmd)\n\n\tdeployCmd.Flags().StringVarP(&profile, \"profile\", \"p\", \"\", \"Profile to generate and output to \/etc\/salt\/cloud.profiles.d for salt-cloud to use\")\n\tdeployCmd.Flags().StringVarP(&roles, \"roles\", \"r\", \"\", \"List of roles to assign to the host in D42 [eg: dcos,dcos-master]\")\n\tdeployCmd.Flags().StringVarP(&osTemplate, \"template\", \"t\", \"\", \"Which OS template you want to use [eg: Ubuntu, CentOS, someothertemplatename]\")\n\tdeployCmd.Flags().BoolVarP(&ipam, \"no-ipam\", \"\", false, \"Whether or not to use Device42 IPAM [This is only used internally]\")\n\tdeployCmd.Flags().BoolVarP(&log.IsDebugging, \"debug\", \"d\", false, \"Turn debugging on\")\n}\n\nvar deployCmd = &cobra.Command{\n\tUse:   \"deploy\",\n\tShort: \"Deploy VM's via salt-cloud\",\n\tLong: `pepper is a wrapper around salt-cloud that will generate salt-cloud profiles based on information you provide in profile configs.\nProfile configs live in \"\/etc\/pepper\/config.d\/{platform}\/{environment}. Pepper is opinionated and looks at the profile you pass in as it's source\nof truth. For example: If you pass in \"vmware-dev-large\" as the profile, it will look for your profile config in \"\/etc\/pepper\/config.d\/vmware\/large.yaml\".\nThis allows for maximum flexibility due to the fact that everyone has different environments and may have some sort of naming scheme associated with them\nso Pepper makes no assumptions on that. Pepper does however make assumptions on your instance type. [eg: nano, micro, small, medium, etc] Although these\noptions are available to you, you are free to override them as you see fit.\nFor example:\n\nProvision new host web01 (Ubuntu) in the dev environment from the nano profile using vmware as a provider:\n\n$ pepper deploy -p vmware-dev-nano -t Ubuntu web01\n\nOr alternatively:\n\n$ pepper deploy --profile vmware-dev-nano --template Ubuntu web01\n\nProvision new host web02 (CentOS) in the prd environment from the large profile using vmware as a provider:\n\n$ pepper deploy -p vmware-prd-large -t CentOS web02\n\nProvision new host web03 (Ubuntu) in the uat environment from the hyper profile using vmware as a provider:\n\n$ pepper deploy -p vmware-uat-hyper -t Ubuntu web03\n\nAre you getting this yet?\n\n$ pepper deploy -p vmware-prd-mid -t Ubuntu -r dcos,dcos-master dcos01 dcos02 dcos03`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tif profile == \"\" {\n\t\t\tlog.Die(\"You didn't specify a profile.\")\n\t\t} else if osTemplate == \"\" {\n\t\t\tlog.Die(\"You didn't specify an OS template.\")\n\t\t} else if len(args) == 0 {\n\t\t\tlog.Die(\"You didn't specify any hosts.\")\n\t\t}\n\n\t\tsplitProfile := strings.Split(profile, \"-\")\n\n\t\t\/\/ These will be the basis for how the profile gets generated.\n\t\tplatform := splitProfile[0]\n\t\tenvironment := splitProfile[1]\n\t\tinstancetype := splitProfile[2]\n\n\t\t\/\/ Nothing really gained here it just makes the code more readable.\n\t\thosts := args\n\n\t\tvar ipAddress string\n\n\t\tfor _, host := range hosts {\n\t\t\tif ipam != true {\n\t\t\t\tif err := device42.ReadConfig(); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif environment == \"prd\" {\n\t\t\t\t\t\/\/ Get a new IP\n\t\t\t\t\tnewIP, err := device42.GetNextIP(device42.PrdRange)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tipAddress = newIP\n\t\t\t\t\t\/\/ Create the Device\n\t\t\t\t\tif err := device42.CreateDevice(host, \"Production\"); err != nil {\n\t\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Reserve IP\n\t\t\t\t\tif err := device42.ReserveIP(newIP, host); err != nil {\n\t\t\t\t\t\tif err = device42.MakeIPAvailable(newIP); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Update custom fields\n\t\t\t\t\tif err := device42.UpdateCustomFields(host, \"roles\", roles); err != nil {\n\t\t\t\t\t\tif err = device42.MakeIPAvailable(newIP); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t} else if environment == \"dev\" {\n\t\t\t\t\t\/\/ Get a new IP\n\t\t\t\t\tnewIP, err := device42.GetNextIP(device42.DevRange)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tipAddress = newIP\n\t\t\t\t\t\/\/ Create the Device\n\t\t\t\t\tif err := device42.CreateDevice(host, \"Development\"); err != nil {\n\t\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Reserve IP\n\t\t\t\t\tif err := device42.ReserveIP(newIP, host); err != nil {\n\t\t\t\t\t\tif err = device42.MakeIPAvailable(newIP); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Update custom fields\n\t\t\t\t\tif err := device42.UpdateCustomFields(host, \"roles\", roles); err != nil {\n\t\t\t\t\t\tif err = device42.MakeIPAvailable(newIP); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch platform {\n\t\t\tcase \"vmware\":\n\t\t\t\tvar vsphere vsphere.ProfileConfig\n\t\t\t\tif err := vsphere.Prepare(platform, environment, instancetype, osTemplate, ipAddress); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif err := vsphere.Generate(); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif err := salt.Provision(profile, host); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif err := vsphere.Remove(); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlog.Die(\"I don't recognize this platform!\")\n\t\t\t}\n\t\t}\n\t},\n}\n<commit_msg>Forgot to change this a few commits back...<commit_after>package cmd\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/nextgearcapital\/pepper\/pkg\/device42\"\n\t\"github.com\/nextgearcapital\/pepper\/pkg\/log\"\n\t\"github.com\/nextgearcapital\/pepper\/pkg\/salt\"\n\t\"github.com\/nextgearcapital\/pepper\/template\/vsphere\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tprofile    string\n\troles      string\n\tosTemplate string\n\tipam       bool\n)\n\nfunc init() {\n\tRootCmd.AddCommand(deployCmd)\n\n\tdeployCmd.Flags().StringVarP(&profile, \"profile\", \"p\", \"\", \"Profile to generate and output to \/etc\/salt\/cloud.profiles.d for salt-cloud to use\")\n\tdeployCmd.Flags().StringVarP(&roles, \"roles\", \"r\", \"\", \"List of roles to assign to the host in D42 [eg: dcos,dcos-master]\")\n\tdeployCmd.Flags().StringVarP(&osTemplate, \"template\", \"t\", \"\", \"Which OS template you want to use [eg: Ubuntu, CentOS, someothertemplatename]\")\n\tdeployCmd.Flags().BoolVarP(&ipam, \"no-ipam\", \"\", false, \"Whether or not to use Device42 IPAM [This is only used internally]\")\n\tdeployCmd.Flags().BoolVarP(&log.IsDebugging, \"debug\", \"d\", false, \"Turn debugging on\")\n}\n\nvar deployCmd = &cobra.Command{\n\tUse:   \"deploy\",\n\tShort: \"Deploy VM's via salt-cloud\",\n\tLong: `pepper is a wrapper around salt-cloud that will generate salt-cloud profiles based on information you provide in profile configs.\nProfile configs live in \"\/etc\/pepper\/config.d\/{platform}\/{environment}. Pepper is opinionated and looks at the profile you pass in as it's source\nof truth. For example: If you pass in \"vmware-dev-large\" as the profile, it will look for your profile config in \"\/etc\/pepper\/config.d\/vmware\/large.yaml\".\nThis allows for maximum flexibility due to the fact that everyone has different environments and may have some sort of naming scheme associated with them\nso Pepper makes no assumptions on that. Pepper does however make assumptions on your instance type. [eg: nano, micro, small, medium, etc] Although these\noptions are available to you, you are free to override them as you see fit.\nFor example:\n\nProvision new host web01 (Ubuntu) in the dev environment from the nano profile using vmware as a provider:\n\n$ pepper deploy -p vmware-dev-nano -t Ubuntu web01\n\nOr alternatively:\n\n$ pepper deploy --profile vmware-dev-nano --template Ubuntu web01\n\nProvision new host web02 (CentOS) in the prd environment from the large profile using vmware as a provider:\n\n$ pepper deploy -p vmware-prd-large -t CentOS web02\n\nProvision new host web03 (Ubuntu) in the uat environment from the hyper profile using vmware as a provider:\n\n$ pepper deploy -p vmware-uat-hyper -t Ubuntu web03\n\nAre you getting this yet?\n\n$ pepper deploy -p vmware-prd-mid -t Ubuntu -r dcos,dcos-master dcos01 dcos02 dcos03`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tif profile == \"\" {\n\t\t\tlog.Die(\"You didn't specify a profile.\")\n\t\t} else if osTemplate == \"\" {\n\t\t\tlog.Die(\"You didn't specify an OS template.\")\n\t\t} else if len(args) == 0 {\n\t\t\tlog.Die(\"You didn't specify any hosts.\")\n\t\t}\n\n\t\tsplitProfile := strings.Split(profile, \"-\")\n\n\t\t\/\/ These will be the basis for how the profile gets generated.\n\t\tplatform := splitProfile[0]\n\t\tenvironment := splitProfile[1]\n\t\tinstancetype := splitProfile[2]\n\n\t\t\/\/ Nothing really gained here it just makes the code more readable.\n\t\thosts := args\n\n\t\tvar ipAddress string\n\n\t\tfor _, host := range hosts {\n\t\t\tif ipam == true {\n\t\t\t\tif err := device42.ReadConfig(); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif environment == \"prd\" {\n\t\t\t\t\t\/\/ Get a new IP\n\t\t\t\t\tnewIP, err := device42.GetNextIP(device42.PrdRange)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tipAddress = newIP\n\t\t\t\t\t\/\/ Create the Device\n\t\t\t\t\tif err := device42.CreateDevice(host, \"Production\"); err != nil {\n\t\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Reserve IP\n\t\t\t\t\tif err := device42.ReserveIP(newIP, host); err != nil {\n\t\t\t\t\t\tif err = device42.MakeIPAvailable(newIP); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Update custom fields\n\t\t\t\t\tif err := device42.UpdateCustomFields(host, \"roles\", roles); err != nil {\n\t\t\t\t\t\tif err = device42.MakeIPAvailable(newIP); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t} else if environment == \"dev\" {\n\t\t\t\t\t\/\/ Get a new IP\n\t\t\t\t\tnewIP, err := device42.GetNextIP(device42.DevRange)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\tipAddress = newIP\n\t\t\t\t\t\/\/ Create the Device\n\t\t\t\t\tif err := device42.CreateDevice(host, \"Development\"); err != nil {\n\t\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Reserve IP\n\t\t\t\t\tif err := device42.ReserveIP(newIP, host); err != nil {\n\t\t\t\t\t\tif err = device42.MakeIPAvailable(newIP); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Update custom fields\n\t\t\t\t\tif err := device42.UpdateCustomFields(host, \"roles\", roles); err != nil {\n\t\t\t\t\t\tif err = device42.MakeIPAvailable(newIP); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif err = device42.DeleteDevice(host); err != nil {\n\t\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch platform {\n\t\t\tcase \"vmware\":\n\t\t\t\tvar vsphere vsphere.ProfileConfig\n\t\t\t\tif err := vsphere.Prepare(platform, environment, instancetype, osTemplate, ipAddress); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif err := vsphere.Generate(); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif err := salt.Provision(profile, host); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\t\tif err := vsphere.Remove(); err != nil {\n\t\t\t\t\tlog.Die(\"%s\", err)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlog.Die(\"I don't recognize this platform!\")\n\t\t\t}\n\t\t}\n\t},\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright (C) 2015 Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage cmds\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fabric8io\/gofabric8\/util\"\n\t\"github.com\/spf13\/cobra\"\n\tclient \"k8s.io\/kubernetes\/pkg\/client\/unversioned\"\n\tcmdutil \"k8s.io\/kubernetes\/pkg\/kubectl\/cmd\/util\"\n)\n\nconst (\n\tdefaultMemory = \"4096\"\n\tdefaultCPU    = \"1\"\n)\n\n\/\/ NewCmdStart starts a local cloud environment\nfunc NewCmdStart(f *cmdutil.Factory) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"start\",\n\t\tShort: \"Starts a local cloud development environment\",\n\t\tLong:  `Starts a local cloud development environment`,\n\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tflag := cmd.Flags().Lookup(minishift)\n\t\t\tisOpenshift := false\n\t\t\tif flag != nil {\n\t\t\t\tisOpenshift = flag.Value.String() == \"true\"\n\t\t\t}\n\t\t\tif isOpenshift {\n\t\t\t\tkubeBinary = minishift\n\t\t\t}\n\n\t\t\t\/\/ check if already running\n\t\t\t\/\/ TODO: should we vendor the minikube and minishift status packages rather than using exec?\n\t\t\tout, err := exec.Command(kubeBinary, \"status\").Output()\n\t\t\tstatus := strings.TrimSpace(string(out))\n\t\t\tif err == nil && status == \"Running\" {\n\t\t\t\t\/\/ already running so lets\n\t\t\t\tutil.Successf(\"%s already running\\n\", kubeBinary)\n\n\t\t\t} else {\n\t\t\t\targs := []string{\"start\", \"--memory=\" + defaultMemory, \"--cpus=\" + defaultCPU}\n\t\t\t\tif runtime.GOOS == \"darwin\" {\n\t\t\t\t\targs = append(args, \"--vm-driver=xhyve\")\n\t\t\t\t}\n\t\t\t\t\/\/ start the local VM\n\t\t\t\te := exec.Command(kubeBinary, args...)\n\t\t\t\te.Stdout = os.Stdout\n\t\t\t\te.Stderr = os.Stderr\n\t\t\t\terr = e.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.Errorf(\"Unable to start %v\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ now check that fabric8 is running, if not deploy it\n\t\t\tc, err := keepTryingToGetClient(f)\n\t\t\tif err != nil {\n\t\t\t\tutil.Fatalf(\"Unable to connect to %s\", kubeBinary)\n\t\t\t}\n\n\t\t\tif isOpenshift {\n\t\t\t\t\/\/ deploy fabric8\n\t\t\t\te := exec.Command(\"oc\", \"login\", \"--username=admin\", \"--password=admin\")\n\t\t\t\te.Stdout = os.Stdout\n\t\t\t\te.Stderr = os.Stderr\n\t\t\t\terr = e.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.Errorf(\"Unable to login %v\", err)\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t\/\/ deploy fabric8 if its not already running\n\t\t\tns, _, _ := f.DefaultNamespace()\n\t\t\t_, err = c.Services(ns).Get(\"fabric8\")\n\t\t\tif err != nil {\n\t\t\t\targs := []string{\"deploy\", \"y\", \"--app=\"}\n\n\t\t\t\t\/\/ deploy fabric8\n\t\t\t\te := exec.Command(\"gofabric8\", args...)\n\t\t\t\te.Stdout = os.Stdout\n\t\t\t\te.Stderr = os.Stderr\n\t\t\t\terr = e.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.Errorf(\"Unable to start %v\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\topenService(ns, \"fabric8\", c, false)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.PersistentFlags().BoolP(minishift, \"\", false, \"start the openshift flavour of Kubernetes\")\n\treturn cmd\n}\n\nfunc keepTryingToGetClient(f *cmdutil.Factory) (*client.Client, error) {\n\ttimeout := time.After(2 * time.Minute)\n\ttick := time.Tick(1 * time.Second)\n\t\/\/ Keep trying until we're timed out or got a result or got an error\n\tfor {\n\t\tselect {\n\t\t\/\/ Got a timeout! fail with a timeout error\n\t\tcase <-timeout:\n\t\t\treturn nil, errors.New(\"timed out\")\n\t\t\/\/ Got a tick, try and get teh client\n\t\tcase <-tick:\n\t\t\tc, _ := getClient(f)\n\t\t\t\/\/ return if we have a client\n\t\t\tif c != nil {\n\t\t\t\treturn c, nil\n\t\t\t}\n\t\t\tutil.Info(\"Cannot connect to api server, retrying...\")\n\t\t\t\/\/ retry\n\t\t}\n\t}\n}\n\nfunc getClient(f *cmdutil.Factory) (*client.Client, error) {\n\tvar err error\n\tcfg, err := f.ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := client.New(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}\n<commit_msg>allow the default memory and cpu flags to be overridden<commit_after>\/**\n * Copyright (C) 2015 Red Hat, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *         http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\npackage cmds\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fabric8io\/gofabric8\/util\"\n\t\"github.com\/spf13\/cobra\"\n\tclient \"k8s.io\/kubernetes\/pkg\/client\/unversioned\"\n\tcmdutil \"k8s.io\/kubernetes\/pkg\/kubectl\/cmd\/util\"\n)\n\nconst (\n\tmemory  = \"memory\"\n\tcpus    = \"cpus\"\n\tconsole = \"console\"\n)\n\n\/\/ NewCmdStart starts a local cloud environment\nfunc NewCmdStart(f *cmdutil.Factory) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"start\",\n\t\tShort: \"Starts a local cloud development environment\",\n\t\tLong:  `Starts a local cloud development environment`,\n\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\tflag := cmd.Flags().Lookup(minishift)\n\t\t\tisOpenshift := false\n\t\t\tif flag != nil {\n\t\t\t\tisOpenshift = flag.Value.String() == \"true\"\n\t\t\t}\n\t\t\tif isOpenshift {\n\t\t\t\tkubeBinary = minishift\n\t\t\t}\n\n\t\t\t\/\/ check if already running\n\t\t\t\/\/ TODO: should we vendor the minikube and minishift status packages rather than using exec?\n\t\t\tout, err := exec.Command(kubeBinary, \"status\").Output()\n\t\t\tstatus := strings.TrimSpace(string(out))\n\t\t\tif err == nil && status == \"Running\" {\n\t\t\t\t\/\/ already running so lets\n\t\t\t\tutil.Successf(\"%s already running\\n\", kubeBinary)\n\n\t\t\t} else {\n\t\t\t\targs := []string{\"start\"}\n\n\t\t\t\t\/\/ if we're running on OSX default to using xhyve\n\t\t\t\tif runtime.GOOS == \"darwin\" {\n\t\t\t\t\targs = append(args, \"--vm-driver=xhyve\")\n\t\t\t\t}\n\n\t\t\t\t\/\/ set memory flag\n\t\t\t\tmemoryValue := cmd.Flags().Lookup(memory).Value.String()\n\t\t\t\targs = append(args, \"--memory=\"+memoryValue)\n\n\t\t\t\t\/\/ set cpu flag\n\t\t\t\tcpusValue := cmd.Flags().Lookup(cpus).Value.String()\n\t\t\t\targs = append(args, \"--cpus=\"+cpusValue)\n\n\t\t\t\t\/\/ start the local VM\n\t\t\t\te := exec.Command(kubeBinary, args...)\n\t\t\t\te.Stdout = os.Stdout\n\t\t\t\te.Stderr = os.Stderr\n\t\t\t\terr = e.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.Errorf(\"Unable to start %v\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ now check that fabric8 is running, if not deploy it\n\t\t\tc, err := keepTryingToGetClient(f)\n\t\t\tif err != nil {\n\t\t\t\tutil.Fatalf(\"Unable to connect to %s\", kubeBinary)\n\t\t\t}\n\n\t\t\tif isOpenshift {\n\t\t\t\t\/\/ deploy fabric8\n\t\t\t\te := exec.Command(\"oc\", \"login\", \"--username=admin\", \"--password=admin\")\n\t\t\t\te.Stdout = os.Stdout\n\t\t\t\te.Stderr = os.Stderr\n\t\t\t\terr = e.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.Errorf(\"Unable to login %v\", err)\n\t\t\t\t}\n\n\t\t\t}\n\t\t\t\/\/ deploy fabric8 if its not already running\n\t\t\tns, _, _ := f.DefaultNamespace()\n\t\t\t_, err = c.Services(ns).Get(\"fabric8\")\n\t\t\tif err != nil {\n\t\t\t\targs := []string{\"deploy\", \"y\"}\n\n\t\t\t\tflag := cmd.Flags().Lookup(console)\n\t\t\t\tif flag != nil && flag.Value.String() == \"true\" {\n\t\t\t\t\targs = append(args, \"--app=\")\n\t\t\t\t}\n\n\t\t\t\t\/\/ deploy fabric8\n\t\t\t\te := exec.Command(\"gofabric8\", args...)\n\t\t\t\te.Stdout = os.Stdout\n\t\t\t\te.Stderr = os.Stderr\n\t\t\t\terr = e.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.Errorf(\"Unable to start %v\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\topenService(ns, \"fabric8\", c, false)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.PersistentFlags().BoolP(minishift, \"\", false, \"start the openshift flavour of Kubernetes\")\n\tcmd.PersistentFlags().BoolP(console, \"\", false, \"start only the fabric8 console\")\n\tcmd.PersistentFlags().StringP(memory, \"\", \"4096\", \"amount of RAM allocated to the VM\")\n\tcmd.PersistentFlags().StringP(cpus, \"\", \"1\", \"number of CPUs allocated to the VM\")\n\treturn cmd\n}\n\nfunc keepTryingToGetClient(f *cmdutil.Factory) (*client.Client, error) {\n\ttimeout := time.After(2 * time.Minute)\n\ttick := time.Tick(1 * time.Second)\n\t\/\/ Keep trying until we're timed out or got a result or got an error\n\tfor {\n\t\tselect {\n\t\t\/\/ Got a timeout! fail with a timeout error\n\t\tcase <-timeout:\n\t\t\treturn nil, errors.New(\"timed out\")\n\t\t\/\/ Got a tick, try and get teh client\n\t\tcase <-tick:\n\t\t\tc, _ := getClient(f)\n\t\t\t\/\/ return if we have a client\n\t\t\tif c != nil {\n\t\t\t\treturn c, nil\n\t\t\t}\n\t\t\tutil.Info(\"Cannot connect to api server, retrying...\")\n\t\t\t\/\/ retry\n\t\t}\n\t}\n}\n\nfunc getClient(f *cmdutil.Factory) (*client.Client, error) {\n\tvar err error\n\tcfg, err := f.ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := client.New(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2020 Karim Radhouani <medkarimrdi@gmail.com>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\n\t\"github.com\/fullstorydev\/grpcurl\"\n\tgrpc_prometheus \"github.com\/grpc-ecosystem\/go-grpc-prometheus\"\n\t\"github.com\/jhump\/protoreflect\/desc\"\n\t\"github.com\/jhump\/protoreflect\/dynamic\"\n\t\"github.com\/karimra\/gnmic\/outputs\"\n\t\"github.com\/karimra\/gnmic\/utils\"\n\tnokiasros \"github.com\/karimra\/sros-dialout\"\n\t\"github.com\/openconfig\/gnmi\/proto\/gnmi\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\/promhttp\"\n\t\"github.com\/spf13\/cobra\"\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/credentials\"\n\t\"google.golang.org\/grpc\/metadata\"\n\t\"google.golang.org\/grpc\/peer\"\n)\n\n\/\/ listenCmd represents the listen command\nfunc newListenCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"listen\",\n\t\tShort: \"listens for telemetry dialout updates from the node\",\n\t\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\t\tgApp.Config.SetLocalFlagsFromFile(cmd)\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\tdefer cancel()\n\t\t\tserver := new(dialoutTelemetryServer)\n\t\t\tserver.ctx = ctx\n\t\t\tif len(gApp.Config.Address) == 0 {\n\t\t\t\treturn fmt.Errorf(\"no address specified\")\n\t\t\t}\n\t\t\tif len(gApp.Config.Address) > 1 {\n\t\t\t\tfmt.Printf(\"multiple addresses specified, listening only on %s\\n\", gApp.Config.Address[0])\n\t\t\t}\n\t\t\tif len(gApp.Config.ProtoFile) > 0 {\n\t\t\t\tgApp.Logger.Printf(\"loading proto files...\")\n\t\t\t\tdescSource, err := grpcurl.DescriptorSourceFromProtoFiles(gApp.Config.ProtoDir, gApp.Config.ProtoFile...)\n\t\t\t\tif err != nil {\n\t\t\t\t\tgApp.Logger.Printf(\"failed to load proto files: %v\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tserver.rootDesc, err = descSource.FindSymbol(\"Nokia.SROS.root\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tgApp.Logger.Printf(\"could not get symbol 'Nokia.SROS.root': %v\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tgApp.Logger.Printf(\"loaded proto files\")\n\t\t\t}\n\t\t\tserver.Outputs = make(map[string]outputs.Output)\n\t\t\toutCfgs, err := gApp.Config.GetOutputs()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor name, outConf := range outCfgs {\n\t\t\t\tif outType, ok := outConf[\"type\"]; ok {\n\t\t\t\t\tif initializer, ok := outputs.Outputs[outType.(string)]; ok {\n\t\t\t\t\t\tout := initializer()\n\t\t\t\t\t\tgo out.Init(ctx, name, outConf, outputs.WithLogger(gApp.Logger))\n\t\t\t\t\t\tserver.Outputs[name] = out\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tfor _, o := range server.Outputs {\n\t\t\t\t\to.Close()\n\t\t\t\t}\n\t\t\t}()\n\t\t\tserver.listener, err = net.Listen(\"tcp\", gApp.Config.Address[0])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgApp.Logger.Printf(\"waiting for connections on %s\", gApp.Config.Address[0])\n\t\t\tvar opts []grpc.ServerOption\n\t\t\tif gApp.Config.MaxMsgSize > 0 {\n\t\t\t\topts = append(opts, grpc.MaxRecvMsgSize(gApp.Config.MaxMsgSize))\n\t\t\t}\n\t\t\topts = append(opts,\n\t\t\t\tgrpc.MaxConcurrentStreams(gApp.Config.LocalFlags.ListenMaxConcurrentStreams),\n\t\t\t\tgrpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor))\n\n\t\t\tif gApp.Config.TLSKey != \"\" && gApp.Config.TLSCert != \"\" {\n\t\t\t\ttlsConfig, err := utils.NewTLSConfig(\n\t\t\t\t\tgApp.Config.TLSCa,\n\t\t\t\t\tgApp.Config.TLSCert,\n\t\t\t\t\tgApp.Config.TLSKey,\n\t\t\t\t\tgApp.Config.SkipVerify,\n\t\t\t\t\tfalse)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\topts = append(opts, grpc.Creds(credentials.NewTLS(tlsConfig)))\n\t\t\t}\n\n\t\t\tserver.grpcServer = grpc.NewServer(opts...)\n\t\t\tnokiasros.RegisterDialoutTelemetryServer(server.grpcServer, server)\n\n\t\t\tif gApp.Config.LocalFlags.ListenPrometheusAddress != \"\" {\n\t\t\t\tgrpc_prometheus.Register(server.grpcServer)\n\n\t\t\t\thttpServer := &http.Server{\n\t\t\t\t\tHandler: promhttp.Handler(),\n\t\t\t\t\tAddr:    gApp.Config.LocalFlags.ListenPrometheusAddress,\n\t\t\t\t}\n\t\t\t\tgo func() {\n\t\t\t\t\tif err := httpServer.ListenAndServe(); err != nil {\n\t\t\t\t\t\tgApp.Logger.Printf(\"Unable to start prometheus http server.\")\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\tdefer httpServer.Close()\n\t\t\t}\n\n\t\t\tserver.grpcServer.Serve(server.listener)\n\t\t\tdefer server.grpcServer.Stop()\n\t\t\treturn nil\n\t\t},\n\t\tSilenceUsage: true,\n\t}\n\tcmd.Flags().Uint32P(\"max-concurrent-streams\", \"\", 256, \"max concurrent streams gnmic can receive per transport\")\n\tcmd.Flags().StringP(\"prometheus-address\", \"\", \"\", \"prometheus server address\")\n\tgApp.Config.FileConfig.BindPFlag(\"listen-max-concurrent-streams\", cmd.LocalFlags().Lookup(\"max-concurrent-streams\"))\n\tgApp.Config.FileConfig.BindPFlag(\"listen-prometheus-address\", cmd.LocalFlags().Lookup(\"prometheus-address\"))\n\treturn cmd\n}\n\ntype dialoutTelemetryServer struct {\n\tlistener   net.Listener\n\tgrpcServer *grpc.Server\n\trootDesc   desc.Descriptor\n\n\tOutputs map[string]outputs.Output\n\n\tctx context.Context\n}\n\nfunc (s *dialoutTelemetryServer) Publish(stream nokiasros.DialoutTelemetry_PublishServer) error {\n\tpeer, ok := peer.FromContext(stream.Context())\n\tif ok && gApp.Config.Debug {\n\t\tb, err := json.Marshal(peer)\n\t\tif err != nil {\n\t\t\tgApp.Logger.Printf(\"failed to marshal peer data: %v\", err)\n\t\t} else {\n\t\t\tgApp.Logger.Printf(\"received Publish RPC from peer=%s\", string(b))\n\t\t}\n\t}\n\tmd, ok := metadata.FromIncomingContext(stream.Context())\n\tif ok && gApp.Config.Debug {\n\t\tb, err := json.Marshal(md)\n\t\tif err != nil {\n\t\t\tgApp.Logger.Printf(\"failed to marshal context metadata: %v\", err)\n\t\t} else {\n\t\t\tgApp.Logger.Printf(\"received http2_header=%s\", string(b))\n\t\t}\n\t}\n\toutMeta := outputs.Meta{}\n\tmeta := make(map[string]interface{})\n\tif sn, ok := md[\"subscription-name\"]; ok {\n\t\tif len(sn) > 0 {\n\t\t\tmeta[\"subscription-name\"] = sn[0]\n\t\t\toutMeta[\"subscription-name\"] = sn[0]\n\t\t}\n\t} else {\n\t\tgApp.Logger.Println(\"could not find subscription-name in http2 headers\")\n\t}\n\tmeta[\"source\"] = peer.Addr.String()\n\toutMeta[\"source\"] = peer.Addr.String()\n\tif systemName, ok := md[\"system-name\"]; ok {\n\t\tif len(systemName) > 0 {\n\t\t\tmeta[\"system-name\"] = systemName[0]\n\t\t}\n\t} else {\n\t\tgApp.Logger.Println(\"could not find system-name in http2 headers\")\n\t}\n\tfor {\n\t\tsubResp, err := stream.Recv()\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tgApp.Logger.Printf(\"gRPC dialout receive error: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\terr = stream.Send(&nokiasros.PublishResponse{})\n\t\tif err != nil {\n\t\t\tgApp.Logger.Printf(\"error sending publish response to server: %v\", err)\n\t\t}\n\t\tswitch resp := subResp.Response.(type) {\n\t\tcase *gnmi.SubscribeResponse_Update:\n\t\t\tif s.rootDesc != nil {\n\t\t\t\tfor _, update := range resp.Update.Update {\n\t\t\t\t\tswitch update.Val.Value.(type) {\n\t\t\t\t\tcase *gnmi.TypedValue_ProtoBytes:\n\t\t\t\t\t\tm := dynamic.NewMessage(s.rootDesc.GetFile().FindMessage(\"Nokia.SROS.root\"))\n\t\t\t\t\t\terr := m.Unmarshal(update.Val.GetProtoBytes())\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tgApp.Logger.Printf(\"failed to unmarshal m: %v\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tjsondata, err := m.MarshalJSON()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tgApp.Logger.Printf(\"failed to marshal dynamic proto msg: %v\", err)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif gApp.Config.Debug {\n\t\t\t\t\t\t\tgApp.Logger.Printf(\"json format=%s\", string(jsondata))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tupdate.Val.Value = &gnmi.TypedValue_JsonVal{JsonVal: jsondata}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, o := range s.Outputs {\n\t\t\t\tgo o.Write(s.ctx, subResp, outMeta)\n\t\t\t}\n\n\t\tcase *gnmi.SubscribeResponse_SyncResponse:\n\t\t\tgApp.Logger.Printf(\"received sync response=%+v from %s\\n\", resp.SyncResponse, meta[\"source\"])\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>enable event processors when using the listen command<commit_after>\/\/ Copyright © 2020 Karim Radhouani <medkarimrdi@gmail.com>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\n\t\"github.com\/fullstorydev\/grpcurl\"\n\tgrpc_prometheus \"github.com\/grpc-ecosystem\/go-grpc-prometheus\"\n\t\"github.com\/jhump\/protoreflect\/desc\"\n\t\"github.com\/jhump\/protoreflect\/dynamic\"\n\t\"github.com\/karimra\/gnmic\/outputs\"\n\t\"github.com\/karimra\/gnmic\/utils\"\n\tnokiasros \"github.com\/karimra\/sros-dialout\"\n\t\"github.com\/openconfig\/gnmi\/proto\/gnmi\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\/promhttp\"\n\t\"github.com\/spf13\/cobra\"\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/credentials\"\n\t\"google.golang.org\/grpc\/metadata\"\n\t\"google.golang.org\/grpc\/peer\"\n)\n\n\/\/ listenCmd represents the listen command\nfunc newListenCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"listen\",\n\t\tShort: \"listens for telemetry dialout updates from the node\",\n\t\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\t\tgApp.Config.SetLocalFlagsFromFile(cmd)\n\t\t},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\tdefer cancel()\n\t\t\tserver := new(dialoutTelemetryServer)\n\t\t\tserver.ctx = ctx\n\t\t\tif len(gApp.Config.Address) == 0 {\n\t\t\t\treturn fmt.Errorf(\"no address specified\")\n\t\t\t}\n\t\t\tif len(gApp.Config.Address) > 1 {\n\t\t\t\tfmt.Printf(\"multiple addresses specified, listening only on %s\\n\", gApp.Config.Address[0])\n\t\t\t}\n\t\t\tif len(gApp.Config.ProtoFile) > 0 {\n\t\t\t\tgApp.Logger.Printf(\"loading proto files...\")\n\t\t\t\tdescSource, err := grpcurl.DescriptorSourceFromProtoFiles(gApp.Config.ProtoDir, gApp.Config.ProtoFile...)\n\t\t\t\tif err != nil {\n\t\t\t\t\tgApp.Logger.Printf(\"failed to load proto files: %v\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tserver.rootDesc, err = descSource.FindSymbol(\"Nokia.SROS.root\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tgApp.Logger.Printf(\"could not get symbol 'Nokia.SROS.root': %v\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tgApp.Logger.Printf(\"loaded proto files\")\n\t\t\t}\n\t\t\t\/\/ read config\n\t\t\tactCfg, err := gApp.Config.GetActions()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed reading actions config: %v\", err)\n\t\t\t}\n\t\t\tprocCfg, err := gApp.Config.GetEventProcessors()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed reading event processors config: %v\", err)\n\t\t\t}\n\n\t\t\tserver.Outputs = make(map[string]outputs.Output)\n\t\t\toutCfgs, err := gApp.Config.GetOutputs()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor name, outConf := range outCfgs {\n\t\t\t\tif outType, ok := outConf[\"type\"]; ok {\n\t\t\t\t\tif initializer, ok := outputs.Outputs[outType.(string)]; ok {\n\t\t\t\t\t\tout := initializer()\n\t\t\t\t\t\tgo out.Init(ctx, name, outConf,\n\t\t\t\t\t\t\toutputs.WithLogger(gApp.Logger),\n\t\t\t\t\t\t\toutputs.WithEventProcessors(procCfg, gApp.Logger, nil, actCfg),\n\t\t\t\t\t\t\toutputs.WithName(gApp.Config.InstanceName),\n\t\t\t\t\t\t\toutputs.WithClusterName(gApp.Config.ClusterName),\n\t\t\t\t\t\t)\n\t\t\t\t\t\tserver.Outputs[name] = out\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tfor _, o := range server.Outputs {\n\t\t\t\t\to.Close()\n\t\t\t\t}\n\t\t\t}()\n\t\t\tserver.listener, err = net.Listen(\"tcp\", gApp.Config.Address[0])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgApp.Logger.Printf(\"waiting for connections on %s\", gApp.Config.Address[0])\n\t\t\tvar opts []grpc.ServerOption\n\t\t\tif gApp.Config.MaxMsgSize > 0 {\n\t\t\t\topts = append(opts, grpc.MaxRecvMsgSize(gApp.Config.MaxMsgSize))\n\t\t\t}\n\t\t\topts = append(opts,\n\t\t\t\tgrpc.MaxConcurrentStreams(gApp.Config.LocalFlags.ListenMaxConcurrentStreams),\n\t\t\t\tgrpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor))\n\n\t\t\tif gApp.Config.TLSKey != \"\" && gApp.Config.TLSCert != \"\" {\n\t\t\t\ttlsConfig, err := utils.NewTLSConfig(\n\t\t\t\t\tgApp.Config.TLSCa,\n\t\t\t\t\tgApp.Config.TLSCert,\n\t\t\t\t\tgApp.Config.TLSKey,\n\t\t\t\t\tgApp.Config.SkipVerify,\n\t\t\t\t\tfalse)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\topts = append(opts, grpc.Creds(credentials.NewTLS(tlsConfig)))\n\t\t\t}\n\n\t\t\tserver.grpcServer = grpc.NewServer(opts...)\n\t\t\tnokiasros.RegisterDialoutTelemetryServer(server.grpcServer, server)\n\n\t\t\tif gApp.Config.LocalFlags.ListenPrometheusAddress != \"\" {\n\t\t\t\tgrpc_prometheus.Register(server.grpcServer)\n\n\t\t\t\thttpServer := &http.Server{\n\t\t\t\t\tHandler: promhttp.Handler(),\n\t\t\t\t\tAddr:    gApp.Config.LocalFlags.ListenPrometheusAddress,\n\t\t\t\t}\n\t\t\t\tgo func() {\n\t\t\t\t\tif err := httpServer.ListenAndServe(); err != nil {\n\t\t\t\t\t\tgApp.Logger.Printf(\"Unable to start prometheus http server.\")\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t\tdefer httpServer.Close()\n\t\t\t}\n\n\t\t\tserver.grpcServer.Serve(server.listener)\n\t\t\tdefer server.grpcServer.Stop()\n\t\t\treturn nil\n\t\t},\n\t\tSilenceUsage: true,\n\t}\n\tcmd.Flags().Uint32P(\"max-concurrent-streams\", \"\", 256, \"max concurrent streams gnmic can receive per transport\")\n\tcmd.Flags().StringP(\"prometheus-address\", \"\", \"\", \"prometheus server address\")\n\tgApp.Config.FileConfig.BindPFlag(\"listen-max-concurrent-streams\", cmd.LocalFlags().Lookup(\"max-concurrent-streams\"))\n\tgApp.Config.FileConfig.BindPFlag(\"listen-prometheus-address\", cmd.LocalFlags().Lookup(\"prometheus-address\"))\n\treturn cmd\n}\n\ntype dialoutTelemetryServer struct {\n\tlistener   net.Listener\n\tgrpcServer *grpc.Server\n\trootDesc   desc.Descriptor\n\n\tOutputs map[string]outputs.Output\n\n\tctx context.Context\n}\n\nfunc (s *dialoutTelemetryServer) Publish(stream nokiasros.DialoutTelemetry_PublishServer) error {\n\tpeer, ok := peer.FromContext(stream.Context())\n\tif ok && gApp.Config.Debug {\n\t\tb, err := json.Marshal(peer)\n\t\tif err != nil {\n\t\t\tgApp.Logger.Printf(\"failed to marshal peer data: %v\", err)\n\t\t} else {\n\t\t\tgApp.Logger.Printf(\"received Publish RPC from peer=%s\", string(b))\n\t\t}\n\t}\n\tmd, ok := metadata.FromIncomingContext(stream.Context())\n\tif ok && gApp.Config.Debug {\n\t\tb, err := json.Marshal(md)\n\t\tif err != nil {\n\t\t\tgApp.Logger.Printf(\"failed to marshal context metadata: %v\", err)\n\t\t} else {\n\t\t\tgApp.Logger.Printf(\"received http2_header=%s\", string(b))\n\t\t}\n\t}\n\toutMeta := outputs.Meta{}\n\tmeta := make(map[string]interface{})\n\tif sn, ok := md[\"subscription-name\"]; ok {\n\t\tif len(sn) > 0 {\n\t\t\tmeta[\"subscription-name\"] = sn[0]\n\t\t\toutMeta[\"subscription-name\"] = sn[0]\n\t\t}\n\t} else {\n\t\tgApp.Logger.Println(\"could not find subscription-name in http2 headers\")\n\t}\n\tmeta[\"source\"] = peer.Addr.String()\n\toutMeta[\"source\"] = peer.Addr.String()\n\tif systemName, ok := md[\"system-name\"]; ok {\n\t\tif len(systemName) > 0 {\n\t\t\tmeta[\"system-name\"] = systemName[0]\n\t\t}\n\t} else {\n\t\tgApp.Logger.Println(\"could not find system-name in http2 headers\")\n\t}\n\tfor {\n\t\tsubResp, err := stream.Recv()\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tgApp.Logger.Printf(\"gRPC dialout receive error: %v\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\terr = stream.Send(&nokiasros.PublishResponse{})\n\t\tif err != nil {\n\t\t\tgApp.Logger.Printf(\"error sending publish response to server: %v\", err)\n\t\t}\n\t\tswitch resp := subResp.Response.(type) {\n\t\tcase *gnmi.SubscribeResponse_Update:\n\t\t\tif s.rootDesc != nil {\n\t\t\t\tfor _, update := range resp.Update.Update {\n\t\t\t\t\tswitch update.Val.Value.(type) {\n\t\t\t\t\tcase *gnmi.TypedValue_ProtoBytes:\n\t\t\t\t\t\tm := dynamic.NewMessage(s.rootDesc.GetFile().FindMessage(\"Nokia.SROS.root\"))\n\t\t\t\t\t\terr := m.Unmarshal(update.Val.GetProtoBytes())\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tgApp.Logger.Printf(\"failed to unmarshal m: %v\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tjsondata, err := m.MarshalJSON()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tgApp.Logger.Printf(\"failed to marshal dynamic proto msg: %v\", err)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif gApp.Config.Debug {\n\t\t\t\t\t\t\tgApp.Logger.Printf(\"json format=%s\", string(jsondata))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tupdate.Val.Value = &gnmi.TypedValue_JsonVal{JsonVal: jsondata}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, o := range s.Outputs {\n\t\t\t\tgo o.Write(s.ctx, subResp, outMeta)\n\t\t\t}\n\n\t\tcase *gnmi.SubscribeResponse_SyncResponse:\n\t\t\tgApp.Logger.Printf(\"received sync response=%+v from %s\\n\", resp.SyncResponse, meta[\"source\"])\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2017 Philippe Hässig <phil@neckhair.ch>\n\npackage cmd\n\nimport (\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n\n\t\"github.com\/neckhair\/owntracks-eventr\/listener\"\n)\n\nvar config = listener.Configuration{}\n\nvar listenCmd = &cobra.Command{\n\tUse:   \"listen\",\n\tShort: \"Listen for events and write them into a file\",\n\tLong: `Listen for events and write them into a file line by line.\n\nA password for MQTT can be provided in an environment variable named MQTT_PASSWORD.\n\n    MQTT_PASSWORD=secret owntracks-eventr listen -u eventr\n`,\n\n\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\tconfig.Url = viper.GetString(\"url\")\n\t\tconfig.Filename = viper.GetString(\"output\")\n\t\tconfig.Username = viper.GetString(\"username\")\n\t\tconfig.Password = viper.GetString(\"password\")\n\n\t\tfmt.Printf(\"--> Listening for MQTT events\\n\")\n\t\tfmt.Printf(\"Server:  %s\\n\", config.Url)\n\t\tfmt.Printf(\"Output:  %s\\n\", config.Filename)\n\t\tfmt.Printf(\"Logfile: %s\\n\\n\", viper.GetString(\"LogFile\"))\n\t},\n\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tconfig.Password = viper.GetString(\"password\")\n\t\tlistener := listener.NewListener(&config)\n\n\t\tvar err error\n\t\tif listener.TLSConfig, err = tlsConfig(); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t\tif err := listener.Start(); err != nil {\n\t\t\tfmt.Println(\"Could not connect to MQTT server.\")\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tdefer listener.Stop()\n\n\t\tfor {\n\t\t}\n\t},\n}\n\nfunc init() {\n\tRootCmd.AddCommand(listenCmd)\n\n\tlistenCmd.Flags().StringP(\"url\", \"\", \"tls:\/\/localhost:8883\", \"Connection string\")\n\tlistenCmd.Flags().StringP(\"output\", \"o\", \"eventlog.txt\", \"Path to destination file\")\n\tlistenCmd.Flags().StringP(\"username\", \"u\", \"\", \"MQTT Username\")\n\tlistenCmd.Flags().Bool(\"insecure\", false, \"Skip TLS certificate verification\")\n\tlistenCmd.Flags().String(\"ca-cert\", \"\", \"CA certificate file\")\n\n\tviper.BindPFlag(\"url\", listenCmd.Flags().Lookup(\"url\"))\n\tviper.BindPFlag(\"output\", listenCmd.Flags().Lookup(\"output\"))\n\tviper.BindPFlag(\"username\", listenCmd.Flags().Lookup(\"username\"))\n\tviper.BindPFlag(\"insecure\", listenCmd.Flags().Lookup(\"insecure\"))\n\tviper.BindPFlag(\"ca-cert\", listenCmd.Flags().Lookup(\"ca-cert\"))\n\n\tviper.BindEnv(\"password\", \"MQTT_PASSWORD\")\n}\n\nfunc tlsConfig() (*tls.Config, error) {\n\tcertPool, err := x509.SystemCertPool()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif caCert, err := ioutil.ReadFile(viper.GetString(\"ca-cert\")); err != nil {\n\t\treturn nil, errors.New(\"Could not read CA certificate.\")\n\t} else {\n\t\tcertPool.AppendCertsFromPEM(caCert)\n\t}\n\n\tconfig := tls.Config{\n\t\tInsecureSkipVerify: viper.GetBool(\"insecure\"),\n\t\tRootCAs:            certPool}\n\n\treturn &config, nil\n}\n<commit_msg>Fix error when ca cert was not given<commit_after>\/\/ Copyright © 2017 Philippe Hässig <phil@neckhair.ch>\n\npackage cmd\n\nimport (\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n\n\t\"github.com\/neckhair\/owntracks-eventr\/listener\"\n)\n\nvar config = listener.Configuration{}\n\nvar listenCmd = &cobra.Command{\n\tUse:   \"listen\",\n\tShort: \"Listen for events and write them into a file\",\n\tLong: `Listen for events and write them into a file line by line.\n\nA password for MQTT can be provided in an environment variable named MQTT_PASSWORD.\n\n    MQTT_PASSWORD=secret owntracks-eventr listen -u eventr\n`,\n\n\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\tconfig.Url = viper.GetString(\"url\")\n\t\tconfig.Filename = viper.GetString(\"output\")\n\t\tconfig.Username = viper.GetString(\"username\")\n\t\tconfig.Password = viper.GetString(\"password\")\n\n\t\tfmt.Printf(\"--> Listening for MQTT events\\n\")\n\t\tfmt.Printf(\"Server:  %s\\n\", config.Url)\n\t\tfmt.Printf(\"Output:  %s\\n\", config.Filename)\n\t\tfmt.Printf(\"Logfile: %s\\n\\n\", viper.GetString(\"LogFile\"))\n\t},\n\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tconfig.Password = viper.GetString(\"password\")\n\t\tlistener := listener.NewListener(&config)\n\n\t\tvar err error\n\t\tif listener.TLSConfig, err = tlsConfig(); err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t\tif err := listener.Start(); err != nil {\n\t\t\tfmt.Println(\"Could not connect to MQTT server.\")\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tdefer listener.Stop()\n\n\t\tfor {\n\t\t}\n\t},\n}\n\nfunc init() {\n\tRootCmd.AddCommand(listenCmd)\n\n\tlistenCmd.Flags().StringP(\"url\", \"\", \"tls:\/\/localhost:8883\", \"Connection string\")\n\tlistenCmd.Flags().StringP(\"output\", \"o\", \"eventlog.txt\", \"Path to destination file\")\n\tlistenCmd.Flags().StringP(\"username\", \"u\", \"\", \"MQTT Username\")\n\tlistenCmd.Flags().Bool(\"insecure\", false, \"Skip TLS certificate verification\")\n\tlistenCmd.Flags().String(\"ca-cert\", \"\", \"CA certificate file\")\n\n\tviper.BindPFlag(\"url\", listenCmd.Flags().Lookup(\"url\"))\n\tviper.BindPFlag(\"output\", listenCmd.Flags().Lookup(\"output\"))\n\tviper.BindPFlag(\"username\", listenCmd.Flags().Lookup(\"username\"))\n\tviper.BindPFlag(\"insecure\", listenCmd.Flags().Lookup(\"insecure\"))\n\tviper.BindPFlag(\"ca-cert\", listenCmd.Flags().Lookup(\"ca-cert\"))\n\n\tviper.BindEnv(\"password\", \"MQTT_PASSWORD\")\n}\n\nfunc tlsConfig() (*tls.Config, error) {\n\tcertPool, err := x509.SystemCertPool()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif caCertPath := viper.GetString(\"ca-cert\"); caCertPath != \"\" {\n\t\tif caCert, err := ioutil.ReadFile(viper.GetString(\"ca-cert\")); err != nil {\n\t\t\treturn nil, errors.New(\"Could not read CA certificate.\")\n\t\t} else {\n\t\t\tcertPool.AppendCertsFromPEM(caCert)\n\t\t}\n\t}\n\n\tconfig := tls.Config{\n\t\tInsecureSkipVerify: viper.GetBool(\"insecure\"),\n\t\tRootCAs:            certPool}\n\n\treturn &config, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2016 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\npackage cmd\n\nimport (\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/TheThingsNetwork\/ttn\/core\"\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/adapters\/http\"\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/adapters\/http\/broadcast\"\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/adapters\/http\/parser\"\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/adapters\/http\/statuspage\"\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/adapters\/semtech\"\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/components\"\n\t\"github.com\/apex\/log\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ routerCmd represents the router command\nvar routerCmd = &cobra.Command{\n\tUse:   \"router\",\n\tShort: \"The Things Network router\",\n\tLong: `The router accepts connections from gateways and forwards uplink packets to one\nor more brokers. The router is also responsible for monitoring gateways,\ncollecting statistics from gateways and for enforcing TTN's fair use policy when\nthe gateway's duty cycle is (almost) full.`,\n\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\tctx.WithFields(log.Fields{\n\t\t\t\"database\":      viper.GetString(\"router.database\"),\n\t\t\t\"gateways-port\": viper.GetInt(\"router.gateways-port\"),\n\t\t\t\"brokers\":       viper.GetString(\"router.brokers\"),\n\t\t\t\"brokers-port\":  viper.GetInt(\"router.brokers-port\"),\n\t\t}).Info(\"Using Configuration\")\n\t},\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tctx.Info(\"Starting\")\n\n\t\tgtwAdapter, err := semtech.NewAdapter(uint(viper.GetInt(\"router.gateways-port\")), ctx.WithField(\"adapter\", \"gateway-semtech\"))\n\t\tif err != nil {\n\t\t\tctx.WithError(err).Fatal(\"Could not start Gateway Adapter\")\n\t\t}\n\n\t\tpktAdapter, err := http.NewAdapter(uint(viper.GetInt(\"router.brokers-port\")), parser.JSON{}, ctx.WithField(\"adapter\", \"broker-http\"))\n\t\tif err != nil {\n\t\t\tctx.WithError(err).Fatal(\"Could not start Broker Adapter\")\n\t\t}\n\n\t\t_, err = statuspage.NewAdapter(pktAdapter, ctx.WithField(\"adapter\", \"statuspage-http\"))\n\t\tif err != nil {\n\t\t\tctx.WithError(err).Fatal(\"Could not start Broker Adapter\")\n\t\t}\n\n\t\tvar brokers []core.Recipient\n\t\tbrokersStr := strings.Split(viper.GetString(\"router.brokers\"), \",\")\n\t\tfor i := range brokersStr {\n\t\t\tbrokers = append(brokers, core.Recipient{\n\t\t\t\tAddress: strings.Trim(brokersStr[i], \" \"),\n\t\t\t\tId:      i,\n\t\t\t})\n\t\t}\n\n\t\tbrkAdapter, err := broadcast.NewAdapter(pktAdapter, brokers, ctx.WithField(\"adapter\", \"broker-broadcast\"))\n\t\tif err != nil {\n\t\t\tctx.WithError(err).Fatal(\"Could not start Broker Adapter\")\n\t\t}\n\n\t\tdb, err := components.NewRouterStorage(time.Hour * 8)\n\t\tif err != nil {\n\t\t\tctx.WithError(err).Fatal(\"Could not create a local storage\")\n\t\t}\n\n\t\trouter := components.NewRouter(db, ctx)\n\n\t\t\/\/ Bring the service to life\n\n\t\t\/\/ Listen uplink\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tpacket, an, err := gtwAdapter.Next()\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.WithError(err).Warn(\"Could not get next packet from gateway\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tgo func(packet core.Packet, an core.AckNacker) {\n\t\t\t\t\tif err := router.HandleUp(packet, an, brkAdapter); err != nil {\n\t\t\t\t\t\tctx.WithError(err).Warn(\"Could not process packet from gateway\")\n\t\t\t\t\t}\n\t\t\t\t}(packet, an)\n\t\t\t}\n\t\t}()\n\n\t\t\/\/ Listen broker registrations\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\treg, an, err := brkAdapter.NextRegistration()\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.WithError(err).Warn(\"Could not get next registration from broker\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tgo func(reg core.Registration, an core.AckNacker) {\n\t\t\t\t\tif err := router.Register(reg, an); err != nil {\n\t\t\t\t\t\tctx.WithError(err).Warn(\"Could not process registration from broker\")\n\t\t\t\t\t}\n\t\t\t\t}(reg, an)\n\t\t\t}\n\t\t}()\n\n\t\t<-make(chan bool)\n\t},\n}\n\nfunc init() {\n\tRootCmd.AddCommand(routerCmd)\n\n\trouterCmd.Flags().String(\"database\", \"boltdb:\/tmp\/ttn_router.db\", \"Database connection\")\n\trouterCmd.Flags().Int(\"gateways-port\", 1700, \"UDP port for connections from gateways\")\n\trouterCmd.Flags().String(\"brokers\", \"localhost:1690\", \"Comma-separated list of brokers\")\n\trouterCmd.Flags().Int(\"brokers-port\", 1780, \"TCP port for connections from brokers\")\n\n\tviper.BindPFlag(\"router.database\", routerCmd.Flags().Lookup(\"database\"))\n\tviper.BindPFlag(\"router.gateways-port\", routerCmd.Flags().Lookup(\"gateways-port\"))\n\tviper.BindPFlag(\"router.brokers\", routerCmd.Flags().Lookup(\"brokers\"))\n\tviper.BindPFlag(\"router.brokers-port\", routerCmd.Flags().Lookup(\"brokers-port\"))\n}\n<commit_msg>[refactor] Integrate API changes to router command<commit_after>\/\/ Copyright © 2016 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\npackage cmd\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/TheThingsNetwork\/ttn\/core\"\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/adapters\/http\"\n\thttpHandlers \"github.com\/TheThingsNetwork\/ttn\/core\/adapters\/http\/handlers\"\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/adapters\/udp\"\n\tudpHandlers \"github.com\/TheThingsNetwork\/ttn\/core\/adapters\/udp\/handlers\"\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/components\/router\"\n\t\"github.com\/apex\/log\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ routerCmd represents the router command\nvar routerCmd = &cobra.Command{\n\tUse:   \"router\",\n\tShort: \"The Things Network router\",\n\tLong: `The router accepts connections from gateways and forwards uplink packets to one\nor more brokers. The router is also responsible for monitoring gateways,\ncollecting statistics from gateways and for enforcing TTN's fair use policy when\nthe gateway's duty cycle is (almost) full.`,\n\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\tctx.WithFields(log.Fields{\n\t\t\t\"database\":      viper.GetString(\"router.database\"),\n\t\t\t\"gateways-port\": viper.GetInt(\"router.gateways-port\"),\n\t\t\t\"brokers\":       viper.GetString(\"router.brokers\"),\n\t\t\t\"brokers-port\":  viper.GetInt(\"router.brokers-port\"),\n\t\t}).Info(\"Using Configuration\")\n\t},\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tctx.Info(\"Starting\")\n\n\t\tgtwAdapter, err := udp.NewAdapter(uint(viper.GetInt(\"router.gateways-port\")), ctx.WithField(\"adapter\", \"gateway-semtech\"))\n\t\tif err != nil {\n\t\t\tctx.WithError(err).Fatal(\"Could not start Gateway Adapter\")\n\t\t}\n\t\tgtwAdapter.Bind(udpHandlers.Semtech{})\n\n\t\tvar brokers []core.Recipient\n\t\tbrokersStr := strings.Split(viper.GetString(\"router.brokers\"), \",\")\n\t\tfor i := range brokersStr {\n\t\t\turl := fmt.Sprintf(\"%s\/packets\", strings.Trim(brokersStr[i], \" \"))\n\t\t\tbrokers = append(brokers, http.NewHttpRecipient(url, \"POST\"))\n\t\t}\n\n\t\tbrkAdapter, err := http.NewAdapter(uint(viper.GetInt(\"router.brokers-port\")), brokers, ctx.WithField(\"adapter\", \"broker-http\"))\n\t\tif err != nil {\n\t\t\tctx.WithError(err).Fatal(\"Could not start Broker Adapter\")\n\t\t}\n\t\tbrkAdapter.Bind(httpHandlers.StatusPage{})\n\n\t\tdb, err := router.NewStorage(\"router_storage.db\", time.Hour*8) \/\/ TODO use cli flag\n\t\tif err != nil {\n\t\t\tctx.WithError(err).Fatal(\"Could not create a local storage\")\n\t\t}\n\n\t\trouter := router.New(db, ctx)\n\n\t\t\/\/ Bring the service to life\n\n\t\t\/\/ Listen uplink\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tpacket, an, err := gtwAdapter.Next()\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.WithError(err).Warn(\"Could not get next packet from gateway\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tgo func(packet []byte, an core.AckNacker) {\n\t\t\t\t\tif err := router.HandleUp(packet, an, brkAdapter); err != nil {\n\t\t\t\t\t\tctx.WithError(err).Warn(\"Could not process packet from gateway\")\n\t\t\t\t\t}\n\t\t\t\t}(packet, an)\n\t\t\t}\n\t\t}()\n\n\t\t\/\/ Listen broker registrations\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\treg, an, err := brkAdapter.NextRegistration()\n\t\t\t\tif err != nil {\n\t\t\t\t\tctx.WithError(err).Warn(\"Could not get next registration from broker\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tgo func(reg core.Registration, an core.AckNacker) {\n\t\t\t\t\tif err := router.Register(reg, an); err != nil {\n\t\t\t\t\t\tctx.WithError(err).Warn(\"Could not process registration from broker\")\n\t\t\t\t\t}\n\t\t\t\t}(reg, an)\n\t\t\t}\n\t\t}()\n\n\t\t<-make(chan bool)\n\t},\n}\n\nfunc init() {\n\tRootCmd.AddCommand(routerCmd)\n\n\trouterCmd.Flags().String(\"database\", \"boltdb:\/tmp\/ttn_router.db\", \"Database connection\")\n\trouterCmd.Flags().Int(\"gateways-port\", 1700, \"UDP port for connections from gateways\")\n\trouterCmd.Flags().String(\"brokers\", \"localhost:1690\", \"Comma-separated list of brokers\")\n\trouterCmd.Flags().Int(\"brokers-port\", 1780, \"TCP port for connections from brokers\")\n\n\tviper.BindPFlag(\"router.database\", routerCmd.Flags().Lookup(\"database\"))\n\tviper.BindPFlag(\"router.gateways-port\", routerCmd.Flags().Lookup(\"gateways-port\"))\n\tviper.BindPFlag(\"router.brokers\", routerCmd.Flags().Lookup(\"brokers\"))\n\tviper.BindPFlag(\"router.brokers-port\", routerCmd.Flags().Lookup(\"brokers-port\"))\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"net\/http\"\n)\n\ntype stressRequest interface{}\n\ntype finishedStress struct{}\n\ntype workerDone struct{}\n\ntype requestStat struct {\n\tduration int64 \/\/nanoseconds\n}\ntype requestStatSummary struct {\n\tavgDuration int64 \/\/nanoseconds\n\tmaxDuration int64 \/\/nanoseconds\n\tminDuration int64 \/\/nanoseconds\n}\n\n\/\/flags\nvar (\n\tnumTests      int\n\ttimeout       int\n\tconcurrency   int\n\trequestMethod string\n)\n\nfunc init() {\n\tRootCmd.AddCommand(stressCmd)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\n\t\/\/ Cobra supports Persistent Flags which will work for this command\n\t\/\/ and all subcommands, e.g.:\n\t\/\/ stressCmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t\/\/ Cobra supports local flags which will only run when this command\n\t\/\/ is called directly, e.g.:\n\t\/\/ stressCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n\n\tstressCmd.Flags().IntVarP(&numTests, \"num\", \"n\", 100, \"Number of requests to make\")\n\tstressCmd.Flags().IntVarP(&concurrency, \"concurrent\", \"c\", 1, \"Number of multiple requests to make\")\n\tstressCmd.Flags().IntVarP(&timeout, \"timeout\", \"t\", 0, \"Maximum seconds to wait for response. 0 means unlimited\")\n\tstressCmd.Flags().StringVarP(&requestMethod, \"requestMethod\", \"X\", \"GET\", \"Request type. GET, HEAD, POST, PUT, etc.\")\n}\n\n\/\/ stressCmd represents the stress command\nvar stressCmd = &cobra.Command{\n\tUse:   \"stress http[s]:\/\/hostname[:port]\/path\",\n\tShort: \"Run predefined load of requests\",\n\tLong:  `Run predefined load of requests`,\n\tRunE:  runStress,\n}\n\nfunc runStress(cmd *cobra.Command, args []string) error {\n\t\/\/checks\n\tif len(args) != 1 {\n\t\treturn errors.New(\"needs URL\")\n\t}\n\tif numTests <= 0 {\n\t\treturn errors.New(\"number of requests must be one or more\")\n\t}\n\tif concurrency <= 0 {\n\t\treturn errors.New(\"concurrency must be one or more\")\n\t}\n\tif timeout < 0 {\n\t\treturn errors.New(\"timeout must be zero or more\")\n\t}\n\tif concurrency > numTests {\n\t\treturn errors.New(\"concurrency must be higher than number of requests\")\n\t}\n\n\turl := args[0]\n\n\tfmt.Println(\"Stress testing \" + url + \"...\")\n\n\t\/\/setup the queue of requests\n\trequestChan := make(chan stressRequest, numTests+concurrency)\n\tfor i := 0; i < numTests; i++ {\n\t\t\/\/TODO optimize by not creating a new http request each time since it's the same thing\n\t\treq, err := http.NewRequest(requestMethod, url, nil)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"failed to create request: \" + err.Error())\n\t\t}\n\t\trequestChan <- req\n\t}\n\tfor i := 0; i < concurrency; i++ {\n\t\trequestChan <- finishedStress{}\n\t}\n\n\tworkerDoneChan := make(chan workerDone)   \/\/workers use this to indicate they are done\n\trequestStatChan := make(chan requestStat) \/\/workers communicate each requests' info\n\n\t\/\/workers\n\ttotalStartTime := time.Now()\n\tfor i := 0; i < concurrency; i++ {\n\t\tgo func() {\n\t\t\tclient := &http.Client{Timeout: time.Duration(timeout) * time.Second}\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase req := <-requestChan:\n\t\t\t\t\tswitch req.(type) {\n\t\t\t\t\tcase *http.Request:\n\t\t\t\t\t\t\/\/run the acutal request\n\t\t\t\t\t\treqStartTime := time.Now()\n\t\t\t\t\t\t_, err := client.Do(req.(*http.Request))\n\t\t\t\t\t\treqEndTime := time.Now()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(err.Error()) \/\/TODO handle this further up\n\t\t\t\t\t\t}\n\t\t\t\t\t\treqTimeNs := (reqEndTime.UnixNano() - reqStartTime.UnixNano())\n\t\t\t\t\t\tfmt.Printf(\"request took %dms\\n\", reqTimeNs\/1000000)\n\t\t\t\t\t\trequestStatChan <- requestStat{duration: reqTimeNs}\n\t\t\t\t\tcase finishedStress:\n\t\t\t\t\t\tworkerDoneChan <- workerDone{}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tallRequestStats := make([]requestStat, numTests)\n\trequestsCompleteCount := 0\n\tworkersDoneCount := 0\n\t\/\/wait for all workers to finish\n\tfor {\n\t\tselect {\n\t\tcase <-workerDoneChan:\n\t\t\tworkersDoneCount++\n\t\t\tif workersDoneCount == concurrency {\n\t\t\t\t\/\/all workers are done\n\t\t\t\ttotalEndTime := time.Now()\n\n\t\t\t\treqStats := createRequestsStats(allRequestStats)\n\t\t\t\ttotalTimeNs := totalEndTime.UnixNano() - totalStartTime.UnixNano()\n\t\t\t\tfmt.Println(createTextSummary(reqStats, totalTimeNs))\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase requestStat := <-requestStatChan:\n\t\t\tallRequestStats[requestsCompleteCount] = requestStat\n\t\t\trequestsCompleteCount++\n\t\t}\n\t}\n}\n\nfunc createRequestsStats(requestStats []requestStat) requestStatSummary {\n\tif len(requestStats) == 0 {\n\t\treturn requestStatSummary{}\n\t}\n\n\tsummary := requestStatSummary{maxDuration: requestStats[0].duration, minDuration: requestStats[0].duration}\n\tvar totalDurations int64\n\ttotalDurations = 0\n\tfor i := 0; i < len(requestStats); i++ {\n\t\tif requestStats[i].duration > summary.maxDuration {\n\t\t\tsummary.maxDuration = requestStats[i].duration\n\t\t}\n\t\tif requestStats[i].duration < summary.minDuration {\n\t\t\tsummary.minDuration = requestStats[i].duration\n\t\t}\n\t\ttotalDurations += requestStats[i].duration\n\t}\n\tsummary.avgDuration = totalDurations \/ int64(len(requestStats))\n\treturn summary\n}\n\nfunc createTextSummary(reqStatSummary requestStatSummary, totalTimeNs int64) string {\n\tsummary := \"\\n\"\n\tsummary = summary + \"Average:    \" + strconv.Itoa(int(reqStatSummary.avgDuration\/1000000)) + \"ms\\n\"\n\tsummary = summary + \"Max:        \" + strconv.Itoa(int(reqStatSummary.maxDuration\/1000000)) + \"ms\\n\"\n\tsummary = summary + \"Min:        \" + strconv.Itoa(int(reqStatSummary.minDuration\/1000000)) + \"ms\\n\"\n\tsummary = summary + \"Total Time: \" + strconv.Itoa(int(totalTimeNs\/1000000)) + \"ms\"\n\treturn summary\n}\n<commit_msg>Adding verbose levels<commit_after>package cmd\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"net\/http\"\n)\n\ntype stressRequest interface{}\n\ntype finishedStress struct{}\n\ntype workerDone struct{}\n\ntype requestStat struct {\n\tduration int64 \/\/nanoseconds\n}\ntype requestStatSummary struct {\n\tavgDuration int64 \/\/nanoseconds\n\tmaxDuration int64 \/\/nanoseconds\n\tminDuration int64 \/\/nanoseconds\n}\n\n\/\/verbose levels\nconst (\n\tVerboseNone = iota\n\tVerboseLow\n\tVerboseMedium\n\tVerboseHigh\n)\n\n\/\/flags\nvar (\n\tnumTests      int\n\ttimeout       int\n\tconcurrency   int\n\trequestMethod string\n\tverboseLevel  int\n)\n\nfunc init() {\n\tRootCmd.AddCommand(stressCmd)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\n\t\/\/ Cobra supports Persistent Flags which will work for this command\n\t\/\/ and all subcommands, e.g.:\n\t\/\/ stressCmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t\/\/ Cobra supports local flags which will only run when this command\n\t\/\/ is called directly, e.g.:\n\t\/\/ stressCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n\n\tstressCmd.Flags().IntVarP(&numTests, \"num\", \"n\", 100, \"Number of requests to make\")\n\tstressCmd.Flags().IntVarP(&concurrency, \"concurrent\", \"c\", 1, \"Number of multiple requests to make\")\n\tstressCmd.Flags().IntVarP(&timeout, \"timeout\", \"t\", 0, \"Maximum seconds to wait for response. 0 means unlimited\")\n\tstressCmd.Flags().StringVarP(&requestMethod, \"requestMethod\", \"X\", \"GET\", \"Request type. GET, HEAD, POST, PUT, etc.\")\n\tstressCmd.Flags().IntVarP(&verboseLevel, \"verbose\", \"v\", 0, \"Level of verbosity (\"+strconv.Itoa(VerboseNone)+\"-\"+strconv.Itoa(VerboseHigh)+\")\")\n}\n\n\/\/ stressCmd represents the stress command\nvar stressCmd = &cobra.Command{\n\tUse:   \"stress http[s]:\/\/hostname[:port]\/path\",\n\tShort: \"Run predefined load of requests\",\n\tLong:  `Run predefined load of requests`,\n\tRunE:  runStress,\n}\n\nfunc runStress(cmd *cobra.Command, args []string) error {\n\t\/\/checks\n\tif len(args) != 1 {\n\t\treturn errors.New(\"needs URL\")\n\t}\n\tif numTests <= 0 {\n\t\treturn errors.New(\"number of requests must be one or more\")\n\t}\n\tif concurrency <= 0 {\n\t\treturn errors.New(\"concurrency must be one or more\")\n\t}\n\tif timeout < 0 {\n\t\treturn errors.New(\"timeout must be zero or more\")\n\t}\n\tif concurrency > numTests {\n\t\treturn errors.New(\"concurrency must be higher than number of requests\")\n\t}\n\tif verboseLevel < VerboseNone || verboseLevel > VerboseHigh {\n\t\treturn errors.New(\"verbose level must be between \" + strconv.Itoa(VerboseNone) + \" and \" + strconv.Itoa(VerboseHigh))\n\t}\n\n\turl := args[0]\n\n\tfmt.Println(\"Stress testing \" + url + \"...\")\n\n\t\/\/setup the queue of requests\n\trequestChan := make(chan stressRequest, numTests+concurrency)\n\tfor i := 0; i < numTests; i++ {\n\t\t\/\/TODO optimize by not creating a new http request each time since it's the same thing\n\t\treq, err := http.NewRequest(requestMethod, url, nil)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"failed to create request: \" + err.Error())\n\t\t}\n\t\trequestChan <- req\n\t}\n\tfor i := 0; i < concurrency; i++ {\n\t\trequestChan <- finishedStress{}\n\t}\n\n\tworkerDoneChan := make(chan workerDone)   \/\/workers use this to indicate they are done\n\trequestStatChan := make(chan requestStat) \/\/workers communicate each requests' info\n\n\t\/\/workers\n\ttotalStartTime := time.Now()\n\tfor i := 0; i < concurrency; i++ {\n\t\tgo func() {\n\t\t\tclient := &http.Client{Timeout: time.Duration(timeout) * time.Second}\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase req := <-requestChan:\n\t\t\t\t\tswitch req.(type) {\n\t\t\t\t\tcase *http.Request:\n\t\t\t\t\t\t\/\/run the acutal request\n\t\t\t\t\t\treqStartTime := time.Now()\n\t\t\t\t\t\tresponse, err := client.Do(req.(*http.Request))\n\t\t\t\t\t\treqEndTime := time.Now()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Printf(err.Error()) \/\/TODO handle this further up\n\t\t\t\t\t\t}\n\t\t\t\t\t\treqTimeNs := (reqEndTime.UnixNano() - reqStartTime.UnixNano())\n\t\t\t\t\t\tif verboseLevel >= VerboseLow {\n\t\t\t\t\t\t\t\/\/request timing\n\t\t\t\t\t\t\tfmt.Printf(\"request took %dms\\n\\n\", reqTimeNs\/1000000)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif verboseLevel >= VerboseHigh {\n\t\t\t\t\t\t\t\/\/reponse metadata\n\t\t\t\t\t\t\tfmt.Printf(\"Response:\\n%+v\\n\\n\", response)\n\t\t\t\t\t\t}\n\t\t\t\t\t\trequestStatChan <- requestStat{duration: reqTimeNs}\n\t\t\t\t\tcase finishedStress:\n\t\t\t\t\t\tworkerDoneChan <- workerDone{}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tallRequestStats := make([]requestStat, numTests)\n\trequestsCompleteCount := 0\n\tworkersDoneCount := 0\n\t\/\/wait for all workers to finish\n\tfor {\n\t\tselect {\n\t\tcase <-workerDoneChan:\n\t\t\tworkersDoneCount++\n\t\t\tif workersDoneCount == concurrency {\n\t\t\t\t\/\/all workers are done\n\t\t\t\ttotalEndTime := time.Now()\n\n\t\t\t\treqStats := createRequestsStats(allRequestStats)\n\t\t\t\ttotalTimeNs := totalEndTime.UnixNano() - totalStartTime.UnixNano()\n\t\t\t\tfmt.Println(createTextSummary(reqStats, totalTimeNs))\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase requestStat := <-requestStatChan:\n\t\t\tallRequestStats[requestsCompleteCount] = requestStat\n\t\t\trequestsCompleteCount++\n\t\t}\n\t}\n}\n\nfunc createRequestsStats(requestStats []requestStat) requestStatSummary {\n\tif len(requestStats) == 0 {\n\t\treturn requestStatSummary{}\n\t}\n\n\tsummary := requestStatSummary{maxDuration: requestStats[0].duration, minDuration: requestStats[0].duration}\n\tvar totalDurations int64\n\ttotalDurations = 0\n\tfor i := 0; i < len(requestStats); i++ {\n\t\tif requestStats[i].duration > summary.maxDuration {\n\t\t\tsummary.maxDuration = requestStats[i].duration\n\t\t}\n\t\tif requestStats[i].duration < summary.minDuration {\n\t\t\tsummary.minDuration = requestStats[i].duration\n\t\t}\n\t\ttotalDurations += requestStats[i].duration\n\t}\n\tsummary.avgDuration = totalDurations \/ int64(len(requestStats))\n\treturn summary\n}\n\nfunc createTextSummary(reqStatSummary requestStatSummary, totalTimeNs int64) string {\n\tsummary := \"\\n\"\n\tsummary = summary + \"Average:    \" + strconv.Itoa(int(reqStatSummary.avgDuration\/1000000)) + \"ms\\n\"\n\tsummary = summary + \"Max:        \" + strconv.Itoa(int(reqStatSummary.maxDuration\/1000000)) + \"ms\\n\"\n\tsummary = summary + \"Min:        \" + strconv.Itoa(int(reqStatSummary.minDuration\/1000000)) + \"ms\\n\"\n\tsummary = summary + \"Total Time: \" + strconv.Itoa(int(totalTimeNs\/1000000)) + \"ms\"\n\treturn summary\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"net\/http\"\n)\n\ntype stressRequest interface{}\n\ntype finishedStress struct{}\n\ntype workerDone struct{}\n\ntype requestStat struct {\n\tduration int64 \/\/milliseconds\n}\ntype requestStatSummary struct {\n\tavgDuration int64 \/\/milliseconds\n\tmaxDuration int64 \/\/milliseconds\n\tminDuration int64 \/\/milliseconds\n}\n\n\/\/flags\nvar (\n\tnumTests    int\n\ttimeout     int\n\tconcurrency int\n)\n\nfunc init() {\n\tRootCmd.AddCommand(stressCmd)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\n\t\/\/ Cobra supports Persistent Flags which will work for this command\n\t\/\/ and all subcommands, e.g.:\n\t\/\/ stressCmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t\/\/ Cobra supports local flags which will only run when this command\n\t\/\/ is called directly, e.g.:\n\t\/\/ stressCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n\n\tstressCmd.Flags().IntVarP(&numTests, \"num\", \"n\", 100, \"Number of requests to make\")\n\tstressCmd.Flags().IntVarP(&concurrency, \"concurrent\", \"c\", 1, \"Number of multiple requests to make\")\n\tstressCmd.Flags().IntVarP(&timeout, \"timeout\", \"t\", 0, \"Maximum seconds to wait for response. 0 means unlimited\")\n}\n\n\/\/ stressCmd represents the stress command\nvar stressCmd = &cobra.Command{\n\tUse:   \"stress http[s]:\/\/hostname[:port]\/path\",\n\tShort: \"Run predefined load of requests\",\n\tLong:  `Run predefined load of requests`,\n\tRunE:  RunStress,\n}\n\nfunc RunStress(cmd *cobra.Command, args []string) error {\n\t\/\/checks\n\tif len(args) != 1 {\n\t\treturn errors.New(\"needs URL\")\n\t}\n\tif numTests <= 0 {\n\t\treturn errors.New(\"number of requests must be one or more\")\n\t}\n\tif concurrency <= 0 {\n\t\treturn errors.New(\"concurrency must be one or more\")\n\t}\n\tif timeout < 0 {\n\t\treturn errors.New(\"timeout must be zero or more\")\n\t}\n\tif concurrency > numTests {\n\t\treturn errors.New(\"concurrency must be higher than number of requests\")\n\t}\n\n\turl := args[0]\n\n\tfmt.Println(\"Stress testing \" + url + \"...\")\n\n\t\/\/setup the queue of requests\n\trequestChan := make(chan stressRequest, numTests+concurrency)\n\tfor i := 0; i < numTests; i++ {\n\t\t\/\/TODO optimize by not creating a new http request each time since it's the same thing\n\t\treq, err := http.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"failed to create request: \" + err.Error())\n\t\t}\n\t\trequestChan <- req\n\t}\n\tfor i := 0; i < concurrency; i++ {\n\t\trequestChan <- finishedStress{}\n\t}\n\n\tworkerDoneChan := make(chan workerDone)   \/\/workers use this to indicate they are done\n\trequestStatChan := make(chan requestStat) \/\/workers communicate each requests' info\n\n\t\/\/workers\n\tfor i := 0; i < concurrency; i++ {\n\t\tgo func() {\n\t\t\tclient := &http.Client{Timeout: time.Duration(timeout) * time.Second}\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase req := <-requestChan:\n\t\t\t\t\tswitch req.(type) {\n\t\t\t\t\tcase *http.Request:\n\t\t\t\t\t\t\/\/run the acutal request\n\t\t\t\t\t\treqStartTime := time.Now()\n\t\t\t\t\t\t_, err := client.Do(req.(*http.Request))\n\t\t\t\t\t\treqEndTime := time.Now()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Errorf(err.Error()) \/\/TODO handle this further up\n\t\t\t\t\t\t}\n\t\t\t\t\t\treqTimeMs := (reqEndTime.UnixNano() - reqStartTime.UnixNano()) \/ 1000000\n\t\t\t\t\t\tfmt.Printf(\"request took %dms\\n\", reqTimeMs)\n\t\t\t\t\t\trequestStatChan <- requestStat{duration: reqTimeMs}\n\t\t\t\t\tcase finishedStress:\n\t\t\t\t\t\tworkerDoneChan <- workerDone{}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tallRequestStats := make([]requestStat, numTests)\n\trequestsCompleteCount := 0\n\tworkersDoneCount := 0\n\t\/\/wait for all workers to finish\n\tfor {\n\t\tselect {\n\t\tcase <-workerDoneChan:\n\t\t\tworkersDoneCount++\n\t\t\tif workersDoneCount == concurrency {\n\t\t\t\t\/\/all workers are done\n\t\t\t\tfmt.Println(createTextSummary(createStats(allRequestStats)))\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase requestStat := <-requestStatChan:\n\t\t\tallRequestStats[requestsCompleteCount] = requestStat\n\t\t\trequestsCompleteCount++\n\t\t}\n\t}\n}\n\nfunc createStats(requestStats []requestStat) requestStatSummary {\n\tif len(requestStats) == 0 {\n\t\treturn requestStatSummary{}\n\t}\n\n\tsummary := requestStatSummary{maxDuration: requestStats[0].duration, minDuration: requestStats[0].duration}\n\tvar totalDurations int64\n\ttotalDurations = 0\n\tfor i := 0; i < len(requestStats); i++ {\n\t\tif requestStats[i].duration > summary.maxDuration {\n\t\t\tsummary.maxDuration = requestStats[i].duration\n\t\t}\n\t\tif requestStats[i].duration < summary.minDuration {\n\t\t\tsummary.minDuration = requestStats[i].duration\n\t\t}\n\t\ttotalDurations += requestStats[i].duration\n\t}\n\tsummary.avgDuration = totalDurations \/ int64(len(requestStats))\n\treturn summary\n}\n\nfunc createTextSummary(summary requestStatSummary) string {\n\treturn `Average: ` + strconv.Itoa(int(summary.avgDuration)) + \"ms\\n\" +\n\t\t`Max:     ` + strconv.Itoa(int(summary.maxDuration)) + \"ms\\n\" +\n\t\t`Min:     ` + strconv.Itoa(int(summary.minDuration)) + \"ms\"\n}\n<commit_msg>Adding saving total time and handling everything as nanoseconds (choose less granual units when ready to print)<commit_after>package cmd\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"net\/http\"\n)\n\ntype stressRequest interface{}\n\ntype finishedStress struct{}\n\ntype workerDone struct{}\n\ntype requestStat struct {\n\tduration int64 \/\/nanoseconds\n}\ntype requestStatSummary struct {\n\tavgDuration int64 \/\/nanoseconds\n\tmaxDuration int64 \/\/nanoseconds\n\tminDuration int64 \/\/nanoseconds\n}\n\n\/\/flags\nvar (\n\tnumTests    int\n\ttimeout     int\n\tconcurrency int\n)\n\nfunc init() {\n\tRootCmd.AddCommand(stressCmd)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\n\t\/\/ Cobra supports Persistent Flags which will work for this command\n\t\/\/ and all subcommands, e.g.:\n\t\/\/ stressCmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t\/\/ Cobra supports local flags which will only run when this command\n\t\/\/ is called directly, e.g.:\n\t\/\/ stressCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n\n\tstressCmd.Flags().IntVarP(&numTests, \"num\", \"n\", 100, \"Number of requests to make\")\n\tstressCmd.Flags().IntVarP(&concurrency, \"concurrent\", \"c\", 1, \"Number of multiple requests to make\")\n\tstressCmd.Flags().IntVarP(&timeout, \"timeout\", \"t\", 0, \"Maximum seconds to wait for response. 0 means unlimited\")\n}\n\n\/\/ stressCmd represents the stress command\nvar stressCmd = &cobra.Command{\n\tUse:   \"stress http[s]:\/\/hostname[:port]\/path\",\n\tShort: \"Run predefined load of requests\",\n\tLong:  `Run predefined load of requests`,\n\tRunE:  RunStress,\n}\n\nfunc RunStress(cmd *cobra.Command, args []string) error {\n\t\/\/checks\n\tif len(args) != 1 {\n\t\treturn errors.New(\"needs URL\")\n\t}\n\tif numTests <= 0 {\n\t\treturn errors.New(\"number of requests must be one or more\")\n\t}\n\tif concurrency <= 0 {\n\t\treturn errors.New(\"concurrency must be one or more\")\n\t}\n\tif timeout < 0 {\n\t\treturn errors.New(\"timeout must be zero or more\")\n\t}\n\tif concurrency > numTests {\n\t\treturn errors.New(\"concurrency must be higher than number of requests\")\n\t}\n\n\turl := args[0]\n\n\tfmt.Println(\"Stress testing \" + url + \"...\")\n\n\t\/\/setup the queue of requests\n\trequestChan := make(chan stressRequest, numTests+concurrency)\n\tfor i := 0; i < numTests; i++ {\n\t\t\/\/TODO optimize by not creating a new http request each time since it's the same thing\n\t\treq, err := http.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"failed to create request: \" + err.Error())\n\t\t}\n\t\trequestChan <- req\n\t}\n\tfor i := 0; i < concurrency; i++ {\n\t\trequestChan <- finishedStress{}\n\t}\n\n\tworkerDoneChan := make(chan workerDone)   \/\/workers use this to indicate they are done\n\trequestStatChan := make(chan requestStat) \/\/workers communicate each requests' info\n\n\t\/\/workers\n\ttotalStartTime := time.Now()\n\tfor i := 0; i < concurrency; i++ {\n\t\tgo func() {\n\t\t\tclient := &http.Client{Timeout: time.Duration(timeout) * time.Second}\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase req := <-requestChan:\n\t\t\t\t\tswitch req.(type) {\n\t\t\t\t\tcase *http.Request:\n\t\t\t\t\t\t\/\/run the acutal request\n\t\t\t\t\t\treqStartTime := time.Now()\n\t\t\t\t\t\t_, err := client.Do(req.(*http.Request))\n\t\t\t\t\t\treqEndTime := time.Now()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Errorf(err.Error()) \/\/TODO handle this further up\n\t\t\t\t\t\t}\n\t\t\t\t\t\treqTimeNs := (reqEndTime.UnixNano() - reqStartTime.UnixNano())\n\t\t\t\t\t\tfmt.Printf(\"request took %dms\\n\", reqTimeNs\/1000000)\n\t\t\t\t\t\trequestStatChan <- requestStat{duration: reqTimeNs}\n\t\t\t\t\tcase finishedStress:\n\t\t\t\t\t\tworkerDoneChan <- workerDone{}\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tallRequestStats := make([]requestStat, numTests)\n\trequestsCompleteCount := 0\n\tworkersDoneCount := 0\n\t\/\/wait for all workers to finish\n\tfor {\n\t\tselect {\n\t\tcase <-workerDoneChan:\n\t\t\tworkersDoneCount++\n\t\t\tif workersDoneCount == concurrency {\n\t\t\t\t\/\/all workers are done\n\t\t\t\ttotalEndTime := time.Now()\n\n\t\t\t\treqStats := createRequestsStats(allRequestStats)\n\t\t\t\ttotalTimeNs := totalEndTime.UnixNano() - totalStartTime.UnixNano()\n\t\t\t\tfmt.Println(createTextSummary(reqStats, totalTimeNs))\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase requestStat := <-requestStatChan:\n\t\t\tallRequestStats[requestsCompleteCount] = requestStat\n\t\t\trequestsCompleteCount++\n\t\t}\n\t}\n}\n\nfunc createRequestsStats(requestStats []requestStat) requestStatSummary {\n\tif len(requestStats) == 0 {\n\t\treturn requestStatSummary{}\n\t}\n\n\tsummary := requestStatSummary{maxDuration: requestStats[0].duration, minDuration: requestStats[0].duration}\n\tvar totalDurations int64\n\ttotalDurations = 0\n\tfor i := 0; i < len(requestStats); i++ {\n\t\tif requestStats[i].duration > summary.maxDuration {\n\t\t\tsummary.maxDuration = requestStats[i].duration\n\t\t}\n\t\tif requestStats[i].duration < summary.minDuration {\n\t\t\tsummary.minDuration = requestStats[i].duration\n\t\t}\n\t\ttotalDurations += requestStats[i].duration\n\t}\n\tsummary.avgDuration = totalDurations \/ int64(len(requestStats))\n\treturn summary\n}\n\nfunc createTextSummary(reqStatSummary requestStatSummary, totalTimeNs int64) string {\n\tsummary := \"\\n\"\n\tsummary = summary + \"Average:    \" + strconv.Itoa(int(reqStatSummary.avgDuration\/1000000)) + \"ms\\n\"\n\tsummary = summary + \"Max:        \" + strconv.Itoa(int(reqStatSummary.maxDuration\/1000000)) + \"ms\\n\"\n\tsummary = summary + \"Min:        \" + strconv.Itoa(int(reqStatSummary.minDuration\/1000000)) + \"ms\\n\"\n\tsummary = summary + \"Total Time: \" + strconv.Itoa(int(totalTimeNs\/1000000)) + \"ms\"\n\treturn summary\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Improve report package documentation<commit_after><|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/user\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar defaultConfig = `{\n\t\"ping\" : {\n\t\t\"timeout\" : \"2s\",\n\t\t\"interval\": \"1s\",\n\t\t\"count\":\t4\n\t},\t\n\t\"hping\" : {\n\t\t\"timeout\"  : \"2s\",\n\t\t\"method\"   : \"HEAD\",\n\t\t\"data\"\t   : \"mylg\",\n\t\t\"count\"\t   : 5\n\t},\n\t\"web\" : {\n\t\t\"port\"\t   : 8080,\n\t\t\"address\"  : \"127.0.0.1\"\n\t},\n\t\"scan\" : {\n\t\t\"port\"     : \"1-500\"\t\t\n\t}\n}`\n\n\/\/ Config represents configuration\ntype Config struct {\n\tPing  Ping  `json:\"ping\"`\n\tHping HPing `json:\"hping\"`\n\tWeb   Web   `json:\"web\"`\n\tScan  Scan  `json:\"scan\"`\n}\n\n\/\/ Ping represents ping command options\ntype Ping struct {\n\tTimeout  string `json:\"timeout\"`\n\tInterval string `json:\"interval\"`\n\tCount    int    `json:\"count\"`\n}\n\n\/\/ HPing represents ping command options\ntype HPing struct {\n\tTimeout string `json:\"timeout\"`\n\tMethod  string `json:\"method\"`\n\tData    string `json:\"data\"`\n\tCount   int    `json:\"count\"`\n}\n\n\/\/ Web represents web command options\ntype Web struct {\n\tPort    int    `json:port`\n\tAddress string `json:address`\n}\n\n\/\/ Scan represents scan command options\ntype Scan struct {\n\tPort string `json:port`\n}\n\n\/\/ UpdateConfig\nfunc WriteConfig(cfg Config) error {\n\tf, err := cfgFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\th, err := os.Create(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb, err := json.Marshal(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = h.Write(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\th.Close()\n\n\treturn nil\n}\n\n\/\/ UpgradeConfig adds \/ removes new command(s)\/option(s)\nfunc UpgradeConfig() {\n\t\/\/ TODO\n\tvar conf map[string]interface{}\n\tb := make([]byte, 2048)\n\tf, err := cfgFile()\n\tif err != nil {\n\n\t}\n\th, err := os.Open(f)\n\tn, _ := h.Read(b)\n\tb = b[:n]\n\n\tjson.Unmarshal(b, &conf)\n\tif v, ok := conf[\"ping\"].(interface{}); ok {\n\t\tif _, ok = v.(map[string]interface{})[\"timeout\"]; !ok {\n\t\t\t\/\/ there is new option\n\t\t}\n\t} else {\n\t\t\/\/ there is new command\n\t}\n\n}\n\n\/\/ LoadConfig loads configuration\nfunc LoadConfig() Config {\n\tvar cfg Config\n\n\tcfg = ReadConfig()\n\n\treturn cfg\n}\n\n\/\/ InitConfig creates new config file\nfunc InitConfig(f string) ([]byte, error) {\n\th, err := os.Create(f)\n\tif err != nil {\n\t\treturn []byte(\"\"), err\n\t}\n\n\th.Chmod(os.FileMode(int(0600)))\n\th.WriteString(defaultConfig)\n\th.Close()\n\n\treturn []byte(defaultConfig), nil\n}\n\n\/\/ ReadConfig reads configuration from existing\n\/\/ or default configuration\nfunc ReadConfig() Config {\n\tvar (\n\t\tb    = make([]byte, 2048)\n\t\tconf Config\n\t\terr  error\n\t)\n\tf, err := cfgFile()\n\tif err != nil {\n\n\t}\n\n\th, err := os.Open(f)\n\n\tif err != nil {\n\t\tswitch {\n\t\tcase os.IsNotExist(err):\n\t\t\tif b, err = InitConfig(f); err != nil {\n\t\t\t\tprintln(err.Error())\n\t\t\t}\n\t\tcase os.IsPermission(err):\n\t\t\tprintln(\"cannot read configuration file due to insufficient permissions\")\n\t\t\tb = []byte(defaultConfig)\n\t\tdefault:\n\t\t\tprintln(err.Error())\n\t\t\tb = []byte(defaultConfig)\n\t\t}\n\t} else {\n\t\tn, _ := h.Read(b)\n\t\tb = b[:n]\n\t}\n\n\terr = json.Unmarshal(b, &conf)\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\tb = []byte(defaultConfig)\n\t\tjson.Unmarshal(b, &conf)\n\t}\n\n\treturn conf\n}\n\n\/\/ ReadDefaultConfig returns default configuration\nfunc ReadDefaultConfig() (Config, error) {\n\tvar (\n\t\tb    = make([]byte, 2048)\n\t\tconf Config\n\t)\n\tb = []byte(defaultConfig)\n\terr := json.Unmarshal(b, &conf)\n\treturn conf, err\n}\n\n\/\/ cfgFile returns config file\nfunc cfgFile() (string, error) {\n\tuser, err := user.Current()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn user.HomeDir + \"\/.mylg.config\", nil\n}\n\n\/\/ SetConfig handles update option's value\nfunc SetConfig(args string, s *Config) {\n\tvar (\n\t\tv     reflect.Value\n\t\ti     int64\n\t\tfloat float64\n\t\terr   error\n\t)\n\n\targs = strings.ToLower(args)\n\tf := strings.Fields(args)\n\tif len(f) < 1 {\n\t\thelpSet()\n\t\treturn\n\t}\n\n\tv = reflect.ValueOf(s)\n\tv = reflect.Indirect(v)\n\tv = v.FieldByName(strings.Title(f[0]))\n\n\tif v.IsValid() {\n\t\tif i, err = strconv.ParseInt(f[2], 10, 64); err == nil {\n\t\t\t\/\/ integer\n\t\t\terr = SetValue(v.Addr(), strings.Title(f[1]), i)\n\t\t} else if float, err = strconv.ParseFloat(f[2], 64); err == nil {\n\t\t\t\/\/ float\n\t\t\terr = SetValue(v.Addr(), strings.Title(f[1]), float)\n\t\t} else {\n\t\t\t\/\/ string\n\t\t\terr = SetValue(v.Addr(), strings.Title(f[1]), f[2])\n\t\t}\n\t} else {\n\t\terr = fmt.Errorf(\"invalid\")\n\t}\n\n\tif err != nil {\n\t\tprintln(err.Error())\n\t} else {\n\t\tif err = WriteConfig(*s); err != nil {\n\t\t\tprintln(err.Error())\n\t\t}\n\t}\n\n}\n\n\/\/ SetConfig set optioni's value\nfunc SetValue(v reflect.Value, rec string, val interface{}) error {\n\n\tif v.Kind() != reflect.Ptr {\n\t\treturn fmt.Errorf(\"not a pointer value\")\n\t}\n\n\tv = reflect.Indirect(v)\n\tswitch v.Kind() {\n\tcase reflect.Int:\n\t\tif value, ok := val.(int64); ok {\n\t\t\tv.SetInt(value)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"the value should be integer\")\n\t\t}\n\tcase reflect.Float64:\n\t\tif value, ok := val.(float64); ok {\n\t\t\tv.SetFloat(value)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"the value should be float\")\n\t\t}\n\tcase reflect.String:\n\t\tif value, ok := val.(string); ok {\n\t\t\tv.SetString(value)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"the value shouldn't be number\")\n\t\t}\n\tcase reflect.Struct:\n\t\tfor i := 0; i < v.NumField(); i++ {\n\t\t\tif v.Type().Field(i).Name == rec {\n\t\t\t\terr := SetValue(v.Field(i).Addr(), rec, val)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ ShowConfig prints the configuration\nfunc ShowConfig(s *Config) {\n\tvar v reflect.Value\n\n\tv = reflect.ValueOf(s)\n\tv = reflect.Indirect(v)\n\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tcmd := v.Type().Field(i).Name\n\t\tcmd = strings.ToLower(cmd)\n\n\t\tvv := v.Field(i).Addr()\n\t\tvv = reflect.Indirect(vv)\n\n\t\tfor j := 0; j < vv.NumField(); j++ {\n\t\t\tsubCmd := vv.Type().Field(j).Name\n\t\t\tsubCmd = strings.ToLower(subCmd)\n\t\t\tvalue := vv.Field(j)\n\t\t\tfmt.Printf(\"set %-8s %-10s %v\\n\", cmd, subCmd, value)\n\t\t}\n\t}\n}\n\n\/\/ helpSet shows set command\nfunc helpSet() {\n\tprintln(`\n          usage:\n               set command option value\n          example:\n               set ping timeout 2s\t\t  \n\t`)\n\n}\n<commit_msg>upgrade config<commit_after>package cli\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/user\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar defaultConfig = `{\n\t\"ping\" : {\n\t\t\"timeout\" : \"2s\",\n\t\t\"interval\": \"1s\",\n\t\t\"count\":\t4\n\t},\n\t\"hping\" : {\n\t\t\"timeout\"  : \"2s\",\n\t\t\"method\"   : \"HEAD\",\n\t\t\"data\"\t   : \"mylg\",\n\t\t\"count\"\t   : 5\n\t},\n\t\"web\" : {\n\t\t\"port\"\t   : 8080,\n\t\t\"address\"  : \"127.0.0.1\"\n\t},\n\t\"scan\" : {\n\t\t\"port\"     : \"1-500\"\n\t}\n}`\n\n\/\/ Config represents configuration\ntype Config struct {\n\tPing  Ping  `json:\"ping\"`\n\tHping HPing `json:\"hping\"`\n\tWeb   Web   `json:\"web\"`\n\tScan  Scan  `json:\"scan\"`\n}\n\n\/\/ Ping represents ping command options\ntype Ping struct {\n\tTimeout  string `json:\"timeout\"`\n\tInterval string `json:\"interval\"`\n\tCount    int    `json:\"count\"`\n}\n\n\/\/ HPing represents ping command options\ntype HPing struct {\n\tTimeout string `json:\"timeout\"`\n\tMethod  string `json:\"method\"`\n\tData    string `json:\"data\"`\n\tCount   int    `json:\"count\"`\n}\n\n\/\/ Web represents web command options\ntype Web struct {\n\tPort    int    `json:port`\n\tAddress string `json:address`\n}\n\n\/\/ Scan represents scan command options\ntype Scan struct {\n\tPort string `json:port`\n}\n\n\/\/ UpdateConfig\nfunc WriteConfig(cfg Config) error {\n\tf, err := cfgFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\th, err := os.Create(f)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb, err := json.Marshal(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = h.Write(bytes.ToLower(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\th.Close()\n\n\treturn nil\n}\n\n\/\/ GetOptions returns option(s)\/value(s) for specific command\nfunc GetOptions(s interface{}, key string) ([]string, []interface{}) {\n\tvar (\n\t\topts []string\n\t\tvals []interface{}\n\t)\n\tv := reflect.ValueOf(s)\n\tt := v.Type()\n\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tif t.Field(i).Name == key {\n\t\t\tf := v.Field(i)\n\t\t\tft := f.Type()\n\t\t\tfor j := 0; j < f.NumField(); j++ {\n\t\t\t\tvals = append(vals, f.Field(j))\n\t\t\t\topts = append(opts, ft.Field(j).Name)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\treturn opts, vals\n}\n\n\/\/ GetCMDNames returns command line names\nfunc GetCMDNames(s interface{}) []string {\n\tvar fields []string\n\n\tv := reflect.ValueOf(s)\n\tt := v.Type()\n\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tfields = append(fields, t.Field(i).Name)\n\t}\n\treturn fields\n}\n\n\/\/ UpgradeConfig adds \/ removes new command(s)\/option(s)\nfunc UpgradeConfig(cfg *Config) {\n\tvar (\n\t\tconf  map[string]interface{}\n\t\tcConf Config\n\t)\n\tb := make([]byte, 2048)\n\tf, err := cfgFile()\n\tif err != nil {\n\n\t}\n\th, err := os.Open(f)\n\tn, _ := h.Read(b)\n\tb = b[:n]\n\t\/\/ load saved\/old config to conf\n\tjson.Unmarshal(b, &conf)\n\t\/\/ load default config to cConf\n\tjson.Unmarshal([]byte(defaultConfig), &cConf)\n\n\tfor _, cmd := range GetCMDNames(cConf) {\n\t\topts, vals := GetOptions(cConf, cmd)\n\t\tfor i, opt := range opts {\n\t\t\tif v, ok := conf[strings.ToLower(cmd)].(interface{}); ok {\n\t\t\t\tif _, ok = v.(map[string]interface{})[strings.ToLower(opt)]; !ok {\n\t\t\t\t\targs := fmt.Sprintf(\"%s %s %v\", cmd, opt, vals[i])\n\t\t\t\t\tSetConfig(args, cfg)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/TODO:\n\t\t\t\t\/\/ there is new command\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ LoadConfig loads configuration\nfunc LoadConfig() Config {\n\tvar cfg Config\n\n\tcfg = ReadConfig()\n\tUpgradeConfig(&cfg)\n\treturn cfg\n}\n\n\/\/ InitConfig creates new config file\nfunc InitConfig(f string) ([]byte, error) {\n\th, err := os.Create(f)\n\tif err != nil {\n\t\treturn []byte(\"\"), err\n\t}\n\n\th.Chmod(os.FileMode(int(0600)))\n\th.WriteString(defaultConfig)\n\th.Close()\n\n\treturn []byte(defaultConfig), nil\n}\n\n\/\/ ReadConfig reads configuration from existing\n\/\/ or default configuration\nfunc ReadConfig() Config {\n\tvar (\n\t\tb    = make([]byte, 2048)\n\t\tconf Config\n\t\terr  error\n\t)\n\tf, err := cfgFile()\n\tif err != nil {\n\n\t}\n\n\th, err := os.Open(f)\n\n\tif err != nil {\n\t\tswitch {\n\t\tcase os.IsNotExist(err):\n\t\t\tif b, err = InitConfig(f); err != nil {\n\t\t\t\tprintln(err.Error())\n\t\t\t}\n\t\tcase os.IsPermission(err):\n\t\t\tprintln(\"cannot read configuration file due to insufficient permissions\")\n\t\t\tb = []byte(defaultConfig)\n\t\tdefault:\n\t\t\tprintln(err.Error())\n\t\t\tb = []byte(defaultConfig)\n\t\t}\n\t} else {\n\t\tn, _ := h.Read(b)\n\t\tb = b[:n]\n\t}\n\n\terr = json.Unmarshal(b, &conf)\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\tb = []byte(defaultConfig)\n\t\tjson.Unmarshal(b, &conf)\n\t}\n\n\treturn conf\n}\n\n\/\/ ReadDefaultConfig returns default configuration\nfunc ReadDefaultConfig() (Config, error) {\n\tvar (\n\t\tb    = make([]byte, 2048)\n\t\tconf Config\n\t)\n\tb = []byte(defaultConfig)\n\terr := json.Unmarshal(b, &conf)\n\treturn conf, err\n}\n\n\/\/ cfgFile returns config file\nfunc cfgFile() (string, error) {\n\tuser, err := user.Current()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn user.HomeDir + \"\/.mylg.config\", nil\n}\n\n\/\/ SetConfig handles update option's value\nfunc SetConfig(args string, s *Config) {\n\tvar (\n\t\tv     reflect.Value\n\t\ti     int64\n\t\tfloat float64\n\t\terr   error\n\t)\n\n\targs = strings.ToLower(args)\n\tf := strings.Fields(args)\n\tif len(f) < 1 {\n\t\thelpSet()\n\t\treturn\n\t}\n\n\tv = reflect.ValueOf(s)\n\tv = reflect.Indirect(v)\n\tv = v.FieldByName(strings.Title(f[0]))\n\n\tif v.IsValid() {\n\t\tif i, err = strconv.ParseInt(f[2], 10, 64); err == nil {\n\t\t\t\/\/ integer\n\t\t\terr = SetValue(v.Addr(), strings.Title(f[1]), i)\n\t\t} else if float, err = strconv.ParseFloat(f[2], 64); err == nil {\n\t\t\t\/\/ float\n\t\t\terr = SetValue(v.Addr(), strings.Title(f[1]), float)\n\t\t} else {\n\t\t\t\/\/ string\n\t\t\terr = SetValue(v.Addr(), strings.Title(f[1]), f[2])\n\t\t}\n\t} else {\n\t\terr = fmt.Errorf(\"invalid\")\n\t}\n\n\tif err != nil {\n\t\tprintln(err.Error())\n\t} else {\n\t\tif err = WriteConfig(*s); err != nil {\n\t\t\tprintln(err.Error())\n\t\t}\n\t}\n\n}\n\n\/\/ SetConfig set optioni's value\nfunc SetValue(v reflect.Value, rec string, val interface{}) error {\n\n\tif v.Kind() != reflect.Ptr {\n\t\treturn fmt.Errorf(\"not a pointer value\")\n\t}\n\n\tv = reflect.Indirect(v)\n\tswitch v.Kind() {\n\tcase reflect.Int:\n\t\tif value, ok := val.(int64); ok {\n\t\t\tv.SetInt(value)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"the value should be integer\")\n\t\t}\n\tcase reflect.Float64:\n\t\tif value, ok := val.(float64); ok {\n\t\t\tv.SetFloat(value)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"the value should be float\")\n\t\t}\n\tcase reflect.String:\n\t\tif value, ok := val.(string); ok {\n\t\t\tv.SetString(value)\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"the value shouldn't be number\")\n\t\t}\n\tcase reflect.Struct:\n\t\tfor i := 0; i < v.NumField(); i++ {\n\t\t\tif v.Type().Field(i).Name == rec {\n\t\t\t\terr := SetValue(v.Field(i).Addr(), rec, val)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ ShowConfig prints the configuration\nfunc ShowConfig(s *Config) {\n\tvar v reflect.Value\n\n\tv = reflect.ValueOf(s)\n\tv = reflect.Indirect(v)\n\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tcmd := v.Type().Field(i).Name\n\t\tcmd = strings.ToLower(cmd)\n\n\t\tvv := v.Field(i).Addr()\n\t\tvv = reflect.Indirect(vv)\n\n\t\tfor j := 0; j < vv.NumField(); j++ {\n\t\t\tsubCmd := vv.Type().Field(j).Name\n\t\t\tsubCmd = strings.ToLower(subCmd)\n\t\t\tvalue := vv.Field(j)\n\t\t\tfmt.Printf(\"set %-8s %-10s %v\\n\", cmd, subCmd, value)\n\t\t}\n\t}\n}\n\n\/\/ helpSet shows set command\nfunc helpSet() {\n\tprintln(`\n          usage:\n               set command option value\n          example:\n               set ping timeout 2s\n\t`)\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package lint\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/golang\/protobuf\/v2\/reflect\/protoreflect\"\n\tdescriptorpb \"github.com\/golang\/protobuf\/v2\/types\/descriptor\"\n)\n\nvar (\n\t\/\/ ErrPathNotFound is the returned error when a path is not found.\n\tErrPathNotFound = errors.New(\"source: path not found\")\n\t\/\/ ErrSourceInfoNotAvailable is the returned error when creating a source\n\t\/\/ but the source information is not available.\n\tErrSourceInfoNotAvailable = errors.New(\"source: source information is not available\")\n)\n\n\/\/ Comments describes a collection of comments associate with an element,\n\/\/ which contains leading, trailing, and leading-detached comments, in a\n\/\/ source code file.\ntype Comments struct {\n\tLeadingComments         string\n\tTrailingComments        string\n\tLeadingDetachedComments []string\n}\n\nconst sep = \",\"\n\n\/\/ locPath represents a path in the SourceCodeInfo_Location,\n\/\/ and this serves as a map key.\n\/\/ It's a string representation of a slice because slices\n\/\/ cannot be map keys.\n\/\/ Representation: integers separated by commas. No spaces.\n\/\/ Example: [4, 3, 2, 7] --> \"4,3,2,7\"\n\/\/ See descriptor.proto for more explanation of semantics.\ntype locPath string\n\n\/\/ newLocPath return a locPath from a list of index.\nfunc newLocPath(p ...int) locPath {\n\ta := []string{}\n\tfor _, i := range p {\n\t\ta = append(a, strconv.Itoa(i))\n\t}\n\treturn locPath(strings.Join(a, sep))\n}\n\n\/\/ buildLocPathMap creates a map of locPath to *descriptorpb.SourceCodeInfo_Location\n\/\/ from *descriptorpb.SourceCodeInfo.\nfunc buildLocPathMap(sci *descriptorpb.SourceCodeInfo) map[locPath]*descriptorpb.SourceCodeInfo_Location {\n\tm := make(map[locPath]*descriptorpb.SourceCodeInfo_Location)\n\tif sci == nil {\n\t\treturn m\n\t}\n\n\tfor _, loc := range sci.GetLocation() {\n\t\tvar path []int\n\t\tfor _, v := range loc.GetPath() {\n\t\t\tpath = append(path, int(v))\n\t\t}\n\t\tm[newLocPath(path...)] = loc\n\t}\n\treturn m\n}\n\n\/\/ DescriptorSource represents a map of locPath to *descriptorpb.SourceCodeInfo_Location.\ntype DescriptorSource struct {\n\tm map[locPath]*descriptorpb.SourceCodeInfo_Location\n}\n\n\/\/ newDescriptorSource creates a new DescriptorSource from a FileDescriptorProto.\n\/\/ If source code information is not available, returns (nil, ErrSourceInfoNotAvailable).\nfunc newDescriptorSource(f *descriptorpb.FileDescriptorProto) (DescriptorSource, error) {\n\tif f.GetSourceCodeInfo() == nil {\n\t\treturn DescriptorSource{}, ErrSourceInfoNotAvailable\n\t}\n\treturn DescriptorSource{m: buildLocPathMap(f.GetSourceCodeInfo())}, nil\n}\n\n\/\/ findLocationByPath returns a `Location` if found in the map,\n\/\/ and (nil, ErrPathNotFound) if not found.\nfunc (s DescriptorSource) findLocationByPath(path []int) (*Location, error) {\n\tl := s.m[newLocPath(path...)]\n\tif l == nil {\n\t\treturn nil, ErrPathNotFound\n\t}\n\treturn newLocationFromSpan(l.GetSpan())\n}\n\n\/\/ findCommentsByPath returns a `Comments` for the path. If not found, returns\n\/\/ (nil, ErrCommentsNotFound).\nfunc (s DescriptorSource) findCommentsByPath(path []int) (Comments, error) {\n\tl := s.m[newLocPath(path...)]\n\tif l == nil {\n\t\treturn Comments{}, ErrPathNotFound\n\t}\n\treturn Comments{\n\t\tLeadingComments:         l.GetLeadingComments(),\n\t\tTrailingComments:        l.GetTrailingComments(),\n\t\tLeadingDetachedComments: l.GetLeadingDetachedComments(),\n\t}, nil\n}\n\nfunc newLocationFromSpan(span []int32) (*Location, error) {\n\tif len(span) == 4 {\n\t\tstart := NewPosition(int(span[0]), int(span[1]))\n\t\tend := NewPosition(int(span[2]), int(span[3]))\n\t\treturn NewLocation(start, end), nil\n\t}\n\n\tif len(span) == 3 {\n\t\tstart := NewPosition(int(span[0]), int(span[1]))\n\t\tend := NewPosition(int(span[0]), int(span[2]))\n\t\treturn NewLocation(start, end), nil\n\t}\n\n\treturn nil, fmt.Errorf(\"source: %v is not a valid span to create a Location\", span)\n}\n\n\/\/ SyntaxLocation returns the location of the syntax definition.\nfunc (s DescriptorSource) SyntaxLocation() (*Location, error) {\n\treturn s.findLocationByPath([]int{syntaxTag})\n}\n\n\/\/ SyntaxComments returns the comments of the syntax definition.\nfunc (s DescriptorSource) SyntaxComments() (Comments, error) {\n\treturn s.findCommentsByPath([]int{syntaxTag})\n}\n\n\/\/ DescriptorLocation returns a `Location` for the given descriptor.\n\/\/ If not found, returns (nil, ErrPathNotFound).\nfunc (s DescriptorSource) DescriptorLocation(d protoreflect.Descriptor) (*Location, error) {\n\treturn s.findLocationByPath(getPath(d))\n}\n\nfunc getPath(d protoreflect.Descriptor) []int {\n\tpath := []int{}\n\tfor p := d; !isFileDescriptor(p); p, _ = p.Parent() {\n\t\tpath = append(path, p.Index(), getDescriptorTag(p))\n\t}\n\treverseInts(path)\n\treturn path\n}\n\nconst syntaxTag = 12\n\nvar enumTagInFile = 5\nvar enumTagInMessage = 4\nvar enumValueTag = 2\nvar fieldTag = 2\nvar extensionTagInFile = 7\nvar extensionTagInMessage = 6\nvar messageTagInFile = 4\nvar nestedMessageTag = 3\nvar oneofTag = 8\nvar serviceTag = 6\nvar methodTag = 2\n\nfunc getDescriptorTag(d protoreflect.Descriptor) int {\n\tswitch d.(type) {\n\tcase protoreflect.EnumDescriptor:\n\t\tif isTopLevelDescriptor(d) {\n\t\t\treturn enumTagInFile\n\t\t}\n\t\treturn enumTagInMessage\n\tcase protoreflect.EnumValueDescriptor:\n\t\treturn enumValueTag\n\tcase protoreflect.FieldDescriptor:\n\t\tif isFieldExtension(d) {\n\t\t\tif isTopLevelDescriptor(d) {\n\t\t\t\treturn extensionTagInFile\n\t\t\t}\n\t\t\treturn extensionTagInMessage\n\t\t}\n\t\treturn fieldTag\n\tcase protoreflect.MessageDescriptor:\n\t\tif isTopLevelDescriptor(d) {\n\t\t\treturn messageTagInFile\n\t\t}\n\t\treturn nestedMessageTag\n\tcase protoreflect.MethodDescriptor:\n\t\treturn methodTag\n\tcase protoreflect.OneofDescriptor:\n\t\treturn oneofTag\n\tcase protoreflect.ServiceDescriptor:\n\t\treturn serviceTag\n\tdefault:\n\t\treturn 0\n\t}\n}\n\nfunc isFieldExtension(d protoreflect.Descriptor) bool {\n\tf, ok := d.(protoreflect.FieldDescriptor)\n\treturn ok && f.ExtendedType() != nil\n}\n\nfunc isFileDescriptor(d protoreflect.Descriptor) bool {\n\t_, ok := d.(protoreflect.FileDescriptor)\n\treturn ok\n}\n\nfunc isTopLevelDescriptor(d protoreflect.Descriptor) bool {\n\tp, _ := d.Parent()\n\t_, ok := p.(protoreflect.FileDescriptor)\n\treturn ok\n}\n\n\/\/ DescriptorComments returns a `Comments` for the given descriptor.\n\/\/ If not found, returns (nil, ErrCommentsNotFound).\nfunc (s DescriptorSource) DescriptorComments(d protoreflect.Descriptor) (Comments, error) {\n\treturn s.findCommentsByPath(getPath(d))\n}\n\nfunc reverseInts(a []int) {\n\tfor left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 {\n\t\ta[left], a[right] = a[right], a[left]\n\t}\n}\n\n\/\/ IsRuleDisabled check if a rule is disabled for a descriptor\n\/\/ in the comments.\nfunc (s DescriptorSource) IsRuleDisabled(name RuleName, d protoreflect.Descriptor) bool {\n\tcomments, err := s.DescriptorComments(d)\n\tif err != nil {\n\t\treturn true\n\t}\n\n\tcommentsToCheck := []string{\n\t\tcomments.LeadingComments,\n\t\tcomments.TrailingComments,\n\t}\n\tcommentsToCheck = append(commentsToCheck, s.fileComments().LeadingDetachedComments...)\n\n\treturn stringsContains(commentsToCheck, ruleDisablingComment(name))\n}\n\nfunc stringsContains(comments []string, s string) bool {\n\tfor _, c := range comments {\n\t\tif strings.Contains(c, s) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc ruleDisablingComment(name RuleName) string {\n\treturn fmt.Sprintf(\"(-- api-linter: %v =disabled --)\", name)\n}\n\nfunc (s DescriptorSource) fileComments() Comments {\n\tcomments, _ := s.SyntaxComments()\n\treturn comments\n}\n<commit_msg>Fixed format string<commit_after>package lint\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/golang\/protobuf\/v2\/reflect\/protoreflect\"\n\tdescriptorpb \"github.com\/golang\/protobuf\/v2\/types\/descriptor\"\n)\n\nvar (\n\t\/\/ ErrPathNotFound is the returned error when a path is not found.\n\tErrPathNotFound = errors.New(\"source: path not found\")\n\t\/\/ ErrSourceInfoNotAvailable is the returned error when creating a source\n\t\/\/ but the source information is not available.\n\tErrSourceInfoNotAvailable = errors.New(\"source: source information is not available\")\n)\n\n\/\/ Comments describes a collection of comments associate with an element,\n\/\/ which contains leading, trailing, and leading-detached comments, in a\n\/\/ source code file.\ntype Comments struct {\n\tLeadingComments         string\n\tTrailingComments        string\n\tLeadingDetachedComments []string\n}\n\nconst sep = \",\"\n\n\/\/ locPath represents a path in the SourceCodeInfo_Location,\n\/\/ and this serves as a map key.\n\/\/ It's a string representation of a slice because slices\n\/\/ cannot be map keys.\n\/\/ Representation: integers separated by commas. No spaces.\n\/\/ Example: [4, 3, 2, 7] --> \"4,3,2,7\"\n\/\/ See descriptor.proto for more explanation of semantics.\ntype locPath string\n\n\/\/ newLocPath return a locPath from a list of index.\nfunc newLocPath(p ...int) locPath {\n\ta := []string{}\n\tfor _, i := range p {\n\t\ta = append(a, strconv.Itoa(i))\n\t}\n\treturn locPath(strings.Join(a, sep))\n}\n\n\/\/ buildLocPathMap creates a map of locPath to *descriptorpb.SourceCodeInfo_Location\n\/\/ from *descriptorpb.SourceCodeInfo.\nfunc buildLocPathMap(sci *descriptorpb.SourceCodeInfo) map[locPath]*descriptorpb.SourceCodeInfo_Location {\n\tm := make(map[locPath]*descriptorpb.SourceCodeInfo_Location)\n\tif sci == nil {\n\t\treturn m\n\t}\n\n\tfor _, loc := range sci.GetLocation() {\n\t\tvar path []int\n\t\tfor _, v := range loc.GetPath() {\n\t\t\tpath = append(path, int(v))\n\t\t}\n\t\tm[newLocPath(path...)] = loc\n\t}\n\treturn m\n}\n\n\/\/ DescriptorSource represents a map of locPath to *descriptorpb.SourceCodeInfo_Location.\ntype DescriptorSource struct {\n\tm map[locPath]*descriptorpb.SourceCodeInfo_Location\n}\n\n\/\/ newDescriptorSource creates a new DescriptorSource from a FileDescriptorProto.\n\/\/ If source code information is not available, returns (nil, ErrSourceInfoNotAvailable).\nfunc newDescriptorSource(f *descriptorpb.FileDescriptorProto) (DescriptorSource, error) {\n\tif f.GetSourceCodeInfo() == nil {\n\t\treturn DescriptorSource{}, ErrSourceInfoNotAvailable\n\t}\n\treturn DescriptorSource{m: buildLocPathMap(f.GetSourceCodeInfo())}, nil\n}\n\n\/\/ findLocationByPath returns a `Location` if found in the map,\n\/\/ and (nil, ErrPathNotFound) if not found.\nfunc (s DescriptorSource) findLocationByPath(path []int) (*Location, error) {\n\tl := s.m[newLocPath(path...)]\n\tif l == nil {\n\t\treturn nil, ErrPathNotFound\n\t}\n\treturn newLocationFromSpan(l.GetSpan())\n}\n\n\/\/ findCommentsByPath returns a `Comments` for the path. If not found, returns\n\/\/ (nil, ErrCommentsNotFound).\nfunc (s DescriptorSource) findCommentsByPath(path []int) (Comments, error) {\n\tl := s.m[newLocPath(path...)]\n\tif l == nil {\n\t\treturn Comments{}, ErrPathNotFound\n\t}\n\treturn Comments{\n\t\tLeadingComments:         l.GetLeadingComments(),\n\t\tTrailingComments:        l.GetTrailingComments(),\n\t\tLeadingDetachedComments: l.GetLeadingDetachedComments(),\n\t}, nil\n}\n\nfunc newLocationFromSpan(span []int32) (*Location, error) {\n\tif len(span) == 4 {\n\t\tstart := NewPosition(int(span[0]), int(span[1]))\n\t\tend := NewPosition(int(span[2]), int(span[3]))\n\t\treturn NewLocation(start, end), nil\n\t}\n\n\tif len(span) == 3 {\n\t\tstart := NewPosition(int(span[0]), int(span[1]))\n\t\tend := NewPosition(int(span[0]), int(span[2]))\n\t\treturn NewLocation(start, end), nil\n\t}\n\n\treturn nil, fmt.Errorf(\"source: %v is not a valid span to create a Location\", span)\n}\n\n\/\/ SyntaxLocation returns the location of the syntax definition.\nfunc (s DescriptorSource) SyntaxLocation() (*Location, error) {\n\treturn s.findLocationByPath([]int{syntaxTag})\n}\n\n\/\/ SyntaxComments returns the comments of the syntax definition.\nfunc (s DescriptorSource) SyntaxComments() (Comments, error) {\n\treturn s.findCommentsByPath([]int{syntaxTag})\n}\n\n\/\/ DescriptorLocation returns a `Location` for the given descriptor.\n\/\/ If not found, returns (nil, ErrPathNotFound).\nfunc (s DescriptorSource) DescriptorLocation(d protoreflect.Descriptor) (*Location, error) {\n\treturn s.findLocationByPath(getPath(d))\n}\n\nfunc getPath(d protoreflect.Descriptor) []int {\n\tpath := []int{}\n\tfor p := d; !isFileDescriptor(p); p, _ = p.Parent() {\n\t\tpath = append(path, p.Index(), getDescriptorTag(p))\n\t}\n\treverseInts(path)\n\treturn path\n}\n\nconst syntaxTag = 12\n\nvar enumTagInFile = 5\nvar enumTagInMessage = 4\nvar enumValueTag = 2\nvar fieldTag = 2\nvar extensionTagInFile = 7\nvar extensionTagInMessage = 6\nvar messageTagInFile = 4\nvar nestedMessageTag = 3\nvar oneofTag = 8\nvar serviceTag = 6\nvar methodTag = 2\n\nfunc getDescriptorTag(d protoreflect.Descriptor) int {\n\tswitch d.(type) {\n\tcase protoreflect.EnumDescriptor:\n\t\tif isTopLevelDescriptor(d) {\n\t\t\treturn enumTagInFile\n\t\t}\n\t\treturn enumTagInMessage\n\tcase protoreflect.EnumValueDescriptor:\n\t\treturn enumValueTag\n\tcase protoreflect.FieldDescriptor:\n\t\tif isFieldExtension(d) {\n\t\t\tif isTopLevelDescriptor(d) {\n\t\t\t\treturn extensionTagInFile\n\t\t\t}\n\t\t\treturn extensionTagInMessage\n\t\t}\n\t\treturn fieldTag\n\tcase protoreflect.MessageDescriptor:\n\t\tif isTopLevelDescriptor(d) {\n\t\t\treturn messageTagInFile\n\t\t}\n\t\treturn nestedMessageTag\n\tcase protoreflect.MethodDescriptor:\n\t\treturn methodTag\n\tcase protoreflect.OneofDescriptor:\n\t\treturn oneofTag\n\tcase protoreflect.ServiceDescriptor:\n\t\treturn serviceTag\n\tdefault:\n\t\treturn 0\n\t}\n}\n\nfunc isFieldExtension(d protoreflect.Descriptor) bool {\n\tf, ok := d.(protoreflect.FieldDescriptor)\n\treturn ok && f.ExtendedType() != nil\n}\n\nfunc isFileDescriptor(d protoreflect.Descriptor) bool {\n\t_, ok := d.(protoreflect.FileDescriptor)\n\treturn ok\n}\n\nfunc isTopLevelDescriptor(d protoreflect.Descriptor) bool {\n\tp, _ := d.Parent()\n\t_, ok := p.(protoreflect.FileDescriptor)\n\treturn ok\n}\n\n\/\/ DescriptorComments returns a `Comments` for the given descriptor.\n\/\/ If not found, returns (nil, ErrCommentsNotFound).\nfunc (s DescriptorSource) DescriptorComments(d protoreflect.Descriptor) (Comments, error) {\n\treturn s.findCommentsByPath(getPath(d))\n}\n\nfunc reverseInts(a []int) {\n\tfor left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 {\n\t\ta[left], a[right] = a[right], a[left]\n\t}\n}\n\n\/\/ IsRuleDisabled check if a rule is disabled for a descriptor\n\/\/ in the comments.\nfunc (s DescriptorSource) IsRuleDisabled(name RuleName, d protoreflect.Descriptor) bool {\n\tcomments, err := s.DescriptorComments(d)\n\tif err != nil {\n\t\treturn true\n\t}\n\n\tcommentsToCheck := []string{\n\t\tcomments.LeadingComments,\n\t\tcomments.TrailingComments,\n\t}\n\tcommentsToCheck = append(commentsToCheck, s.fileComments().LeadingDetachedComments...)\n\n\treturn stringsContains(commentsToCheck, ruleDisablingComment(name))\n}\n\nfunc stringsContains(comments []string, s string) bool {\n\tfor _, c := range comments {\n\t\tif strings.Contains(c, s) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc ruleDisablingComment(name RuleName) string {\n\treturn fmt.Sprintf(\"(-- api-linter: %s=disabled --)\", name)\n}\n\nfunc (s DescriptorSource) fileComments() Comments {\n\tcomments, _ := s.SyntaxComments()\n\treturn comments\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 Alexander Orlov <alexander.orlov@loxal.net>. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage test\n\nimport (\n    \"flag\" \/\/ replace by a post release.58.1 version and check whether flag.Init() exists\n           \/\/   then test whether flag.Init(\"name\", 0) works\n\t\"fmt\"\n\t\"http\"\n\t\"math\"\n)\n\nfunc test1(w http.ResponseWriter) (func(int) int) {\n    fmt.Fprintf(w, \"Hello From MON\\n<br>\")\n    fmt.Fprintf(w, \"POST-TEXTYPE-MON\")\n    var x int\n    return func(delta int) int {\n        x += delta\n        return x\n    }\n}\n\nfunc TestFlag(w http.ResponseWriter){\n\/\/    var test flag.FlagSet\nvar myFlag string\n\/\/flagSetPointer.StringVar(&myFlag, \"g\", \"value of String\", \"usage of string\")\n\/\/var myFlag *string = flag.String(\"g\", \"value of String\", \"usage of string\")\n\/\/flag.StringVar(&myFlag, \"nameOFString\", \"value of String\", \"usage of string\")\n\/\/flag.Parse()\nflagSetPointer := flag.NewFlagSet(\"\", flag.ContinueOnError)\n\/\/var myFlag *string = flagSetPointer.String(\"f\", \"v\", \"u\")\n\/\/var myFlag = flagSetPointer.String(\"f\", \"\", \"u\")\nflagSetPointer.StringVar(&myFlag, \"f\", \"v\", \"u\")\n\/\/args:= []string{\"g\", \"-g\", \"-g=g\", \"-g g\", \"-g u\", *myFlag}\nargs:= []string{\"-f\", \"FEST\"}\n\/\/flagSetPointer.Usage = func() {}\n\/\/otherArgs := flagSetPointer.Args()\n\n\n  if err := flagSetPointer.Parse(args); err != nil {\n            fmt.Fprintf(w, \" error <br> %v\", err)\n\/\/            return\n    }\nfmt.Fprint(w, \" test \")\n\n\/\/    fmt.Fprintf(w, \"Arg: %v \", flagSetPointer.NArg());\n\/\/    fmt.Fprintf(w, \"Arg: %q \", flagSetPointer.Arg(0));\n\/\/    fmt.Fprintf(w, \"Arg: %q \", flagSetPointer.Arg(1));\n    fmt.Fprintf(w, \"Arg: %q \", myFlag);\n\/\/    fmt.Fprintf(w, \"Arg: %q \", flagSetPointer.Arg(3));\n\/\/    fmt.Fprintf(w, \"Arg: %q \", flagSetPointer.Arg(4));\n\/\/    fmt.Fprintf(w, \"Arg: %q \", flagSetPointer.Arg(5));\n\/\/    fmt.Fprintf(w, \"Arg: %q \", flagSetPointer.Arg(6));\n\/\/    fmt.Fprintf(w, \"Other: %v \", otherArgs);\n}\n\ntype Point struct { x, y float64 }\n\/\/ A method on *Point\nfunc (p *Point) Abs() float64 {\n    return math.Sqrt(p.x*p.x + p.y*p.y)\n}\n\n\n\n\n<commit_msg>improved flag pkg example<commit_after>\/\/ Copyright 2011 Alexander Orlov <alexander.orlov@loxal.net>. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage test\n\nimport (\n    \"flag\" \/\/ replace by a post release.58.1 version and check whether flag.Init() exists\n           \/\/   then test whether flag.Init(\"name\", 0) works\n\t\"fmt\"\n\t\"http\"\n\t\"math\"\n)\n\nfunc test1(w http.ResponseWriter) (func(int) int) {\n    fmt.Fprintf(w, \"Hello From MON\\n<br>\")\n    fmt.Fprintf(w, \"POST-TEXTYPE-MON\")\n    var x int\n    return func(delta int) int {\n        x += delta\n        return x\n    }\n}\n\nfunc TestFlag(w http.ResponseWriter){\n\/\/    var test flag.FlagSet\nvar myFlag string\nvar myFlag1 *string\nvar myFlag2 string\n\/\/flagSetPointer.StringVar(&myFlag, \"g\", \"value of String\", \"usage of string\")\n\/\/var myFlag *string = flag.String(\"g\", \"value of String\", \"usage of string\")\n\/\/flag.StringVar(&myFlag, \"nameOFString\", \"value of String\", \"usage of string\")\n\/\/flag.Parse()\nflagSetPointer := flag.NewFlagSet(\"google\", flag.ContinueOnError)\n\/\/var myFlag *string = flagSetPointer.String(\"f\", \"v\", \"u\")\n\/\/var myFlag = flagSetPointer.String(\"f\", \"\", \"u\")\nflagSetPointer.StringVar(&myFlag, \"flag\", \"v\", \"usage\")\nmyFlag1 = flagSetPointer.String(\"flag1\", \"v\", \"u\")\nflagSetPointer.StringVar(&myFlag2, \"mon\", \"DEFAULT VALUE\", \"u\")\n\/\/args:= []string{\"g\", \"-g\", \"-g=g\", \"-g g\", \"-g u\", *myFlag}\nargs:= []string{\"-flag\", \"value\", \"-flag1\", \"flag1 Value\", \"-f\", \"vom\"}\nflagSetPointer.Usage = func() {\n    fmt.Fprintln(w, \"[MY USAGE]\")\n}\n\/\/otherArgs := flagSetPointer.Args()\n f:=flagSetPointer.Lookup(\"flag\")\n fmt.Fprintln(w, f.Usage)\n\n  flagSetPointer.PrintDefaults()\n  if err := flagSetPointer.Parse(args); err != nil {\n            fmt.Fprintf(w, \" [MY ERROR] <br\/> %v\", err)\n\/\/            fmt.Fprintf(w, \" error <br> %v\", &myFlag2.Usage)\n\/\/            return\n    }\nfmt.Fprint(w, \" BAL \")\n\n\/\/    fmt.Fprintf(w, \"Arg: %v \", flagSetPointer.NArg());\n\/\/    fmt.Fprintf(w, \"Arg: %q \", flagSetPointer.Arg(0));\n\/\/    fmt.Fprintf(w, \"Arg: %q \", flagSetPointer.Arg(1));\n    fmt.Fprintf(w, \"Arg: %q \", myFlag);\n    fmt.Fprintf(w, \"Arg: %q \", *myFlag1);\n    fmt.Fprintf(w, \"Arg: %q \", myFlag2);\n\/\/    fmt.Fprintf(w, \"Arg: %q \", flagSetPointer.Arg(3));\n\/\/    fmt.Fprintf(w, \"Arg: %q \", flagSetPointer.Arg(4));\n\/\/    fmt.Fprintf(w, \"Arg: %q \", flagSetPointer.Arg(5));\n\/\/    fmt.Fprintf(w, \"Arg: %q \", flagSetPointer.Arg(6));\n\/\/    fmt.Fprintf(w, \"Other: %v \", otherArgs);\n}\n\ntype Point struct { x, y float64 }\n\/\/ A method on *Point\nfunc (p *Point) Abs() float64 {\n    return math.Sqrt(p.x*p.x + p.y*p.y)\n}\n\n\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The Netstack Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage header\n\nimport (\n\t\"encoding\/binary\"\n\n\t\"github.com\/google\/netstack\/tcpip\"\n)\n\nconst (\n\tversIHL  = 0\n\ttos      = 1\n\ttotalLen = 2\n\tid       = 4\n\tflagsFO  = 6\n\tttl      = 8\n\tprotocol = 9\n\tchecksum = 10\n\tsrcAddr  = 12\n\tdstAddr  = 16\n)\n\n\/\/ IPv4Fields contains the fields of an IPv4 packet. It is used to describe the\n\/\/ fields of a packet that needs to be encoded.\ntype IPv4Fields struct {\n\t\/\/ IHL is the \"internet header length\" field of an IPv4 packet.\n\tIHL uint8\n\n\t\/\/ TOS is the \"type of service\" field of an IPv4 packet.\n\tTOS uint8\n\n\t\/\/ TotalLength is the \"total length\" field of an IPv4 packet.\n\tTotalLength uint16\n\n\t\/\/ ID is the \"identification\" field of an IPv4 packet.\n\tID uint16\n\n\t\/\/ Flags is the \"flags\" field of an IPv4 packet.\n\tFlags uint8\n\n\t\/\/ FragmentOffset is the \"fragment offset\" field of an IPv4 packet.\n\tFragmentOffset uint16\n\n\t\/\/ TTL is the \"time to live\" field of an IPv4 packet.\n\tTTL uint8\n\n\t\/\/ Protocol is the \"protocol\" field of an IPv4 packet.\n\tProtocol uint8\n\n\t\/\/ Checksum is the \"checksum\" field of an IPv4 packet.\n\tChecksum uint16\n\n\t\/\/ SrcAddr is the \"source ip address\" of an IPv4 packet.\n\tSrcAddr tcpip.Address\n\n\t\/\/ DstAddr is the \"destination ip address\" of an IPv4 packet.\n\tDstAddr tcpip.Address\n}\n\n\/\/ IPv4 represents an ipv4 header stored in a byte array.\n\/\/ Most of the methods of IPv4 access to the underlying slice without\n\/\/ checking the boundaries and could panic because of 'index out of range'.\n\/\/ Always call IsValid() to validate an instance of IPv4 before using other methods.\ntype IPv4 []byte\n\nconst (\n\t\/\/ IPv4MinimumSize is the minimum size of a valid IPv4 packet.\n\tIPv4MinimumSize = 20\n\n\t\/\/ IPv4MaximumHeaderSize is the maximum size of an IPv4 header. Given\n\t\/\/ that there are only 4 bits to represents the header length in 32-bit\n\t\/\/ units, the header cannot exceed 15*4 = 60 bytes.\n\tIPv4MaximumHeaderSize = 60\n\n\t\/\/ IPv4AddressSize is the size, in bytes, of an IPv4 address.\n\tIPv4AddressSize = 4\n\n\t\/\/ IPv4ProtocolNumber is IPv4's network protocol number.\n\tIPv4ProtocolNumber tcpip.NetworkProtocolNumber = 0x0800\n\n\t\/\/ IPv4Version is the version of the ipv4 procotol.\n\tIPv4Version = 4\n)\n\n\/\/ Flags that may be set in an IPv4 packet.\nconst (\n\tIPv4FlagMoreFragments = 1 << iota\n\tIPv4FlagDontFragment\n)\n\n\/\/ IPVersion returns the version of IP used in the given packet. It returns -1\n\/\/ if the packet is not large enough to contain the version field.\nfunc IPVersion(b []byte) int {\n\t\/\/ Length must be at least offset+length of version field.\n\tif len(b) < versIHL+1 {\n\t\treturn -1\n\t}\n\treturn int(b[versIHL] >> 4)\n}\n\n\/\/ HeaderLength returns the value of the \"header length\" field of the ipv4\n\/\/ header.\nfunc (b IPv4) HeaderLength() uint8 {\n\treturn (b[versIHL] & 0xf) * 4\n}\n\n\/\/ ID returns the value of the identifier field of the ipv4 header.\nfunc (b IPv4) ID() uint16 {\n\treturn binary.BigEndian.Uint16(b[id:])\n}\n\n\/\/ Protocol returns the value of the protocol field of the ipv4 header.\nfunc (b IPv4) Protocol() uint8 {\n\treturn b[protocol]\n}\n\n\/\/ Flags returns the \"flags\" field of the ipv4 header.\nfunc (b IPv4) Flags() uint8 {\n\treturn uint8(binary.BigEndian.Uint16(b[flagsFO:]) >> 13)\n}\n\n\/\/ TTL returns the \"TTL\" field of the ipv4 header.\nfunc (b IPv4) TTL() uint8 {\n\treturn b[ttl]\n}\n\n\/\/ FragmentOffset returns the \"fragment offset\" field of the ipv4 header.\nfunc (b IPv4) FragmentOffset() uint16 {\n\treturn binary.BigEndian.Uint16(b[flagsFO:]) << 3\n}\n\n\/\/ TotalLength returns the \"total length\" field of the ipv4 header.\nfunc (b IPv4) TotalLength() uint16 {\n\treturn binary.BigEndian.Uint16(b[totalLen:])\n}\n\n\/\/ Checksum returns the checksum field of the ipv4 header.\nfunc (b IPv4) Checksum() uint16 {\n\treturn binary.BigEndian.Uint16(b[checksum:])\n}\n\n\/\/ SourceAddress returns the \"source address\" field of the ipv4 header.\nfunc (b IPv4) SourceAddress() tcpip.Address {\n\treturn tcpip.Address(b[srcAddr : srcAddr+IPv4AddressSize])\n}\n\n\/\/ DestinationAddress returns the \"destination address\" field of the ipv4\n\/\/ header.\nfunc (b IPv4) DestinationAddress() tcpip.Address {\n\treturn tcpip.Address(b[dstAddr : dstAddr+IPv4AddressSize])\n}\n\n\/\/ TransportProtocol implements Network.TransportProtocol.\nfunc (b IPv4) TransportProtocol() tcpip.TransportProtocolNumber {\n\treturn tcpip.TransportProtocolNumber(b.Protocol())\n}\n\n\/\/ Payload implements Network.Payload.\nfunc (b IPv4) Payload() []byte {\n\treturn b[b.HeaderLength():][:b.PayloadLength()]\n}\n\n\/\/ PayloadLength returns the length of the payload portion of the ipv4 packet.\nfunc (b IPv4) PayloadLength() uint16 {\n\treturn b.TotalLength() - uint16(b.HeaderLength())\n}\n\n\/\/ TOS returns the \"type of service\" field of the ipv4 header.\nfunc (b IPv4) TOS() (uint8, uint32) {\n\treturn b[tos], 0\n}\n\n\/\/ SetTOS sets the \"type of service\" field of the ipv4 header.\nfunc (b IPv4) SetTOS(v uint8, _ uint32) {\n\tb[tos] = v\n}\n\n\/\/ SetTotalLength sets the \"total length\" field of the ipv4 header.\nfunc (b IPv4) SetTotalLength(totalLength uint16) {\n\tbinary.BigEndian.PutUint16(b[totalLen:], totalLength)\n}\n\n\/\/ SetChecksum sets the checksum field of the ipv4 header.\nfunc (b IPv4) SetChecksum(v uint16) {\n\tbinary.BigEndian.PutUint16(b[checksum:], v)\n}\n\n\/\/ SetFlagsFragmentOffset sets the \"flags\" and \"fragment offset\" fields of the\n\/\/ ipv4 header.\nfunc (b IPv4) SetFlagsFragmentOffset(flags uint8, offset uint16) {\n\tv := (uint16(flags) << 13) | (offset >> 3)\n\tbinary.BigEndian.PutUint16(b[flagsFO:], v)\n}\n\n\/\/ SetSourceAddress sets the \"source address\" field of the ipv4 header.\nfunc (b IPv4) SetSourceAddress(addr tcpip.Address) {\n\tcopy(b[srcAddr:srcAddr+IPv4AddressSize], addr)\n}\n\n\/\/ SetDestinationAddress sets the \"destination address\" field of the ipv4\n\/\/ header.\nfunc (b IPv4) SetDestinationAddress(addr tcpip.Address) {\n\tcopy(b[dstAddr:dstAddr+IPv4AddressSize], addr)\n}\n\n\/\/ CalculateChecksum calculates the checksum of the ipv4 header.\nfunc (b IPv4) CalculateChecksum() uint16 {\n\treturn Checksum(b[:b.HeaderLength()], 0)\n}\n\n\/\/ Encode encodes all the fields of the ipv4 header.\nfunc (b IPv4) Encode(i *IPv4Fields) {\n\tb[versIHL] = (4 << 4) | ((i.IHL \/ 4) & 0xf)\n\tb[tos] = i.TOS\n\tb.SetTotalLength(i.TotalLength)\n\tbinary.BigEndian.PutUint16(b[id:], i.ID)\n\tb.SetFlagsFragmentOffset(i.Flags, i.FragmentOffset)\n\tb[ttl] = i.TTL\n\tb[protocol] = i.Protocol\n\tb.SetChecksum(i.Checksum)\n\tcopy(b[srcAddr:srcAddr+IPv4AddressSize], i.SrcAddr)\n\tcopy(b[dstAddr:dstAddr+IPv4AddressSize], i.DstAddr)\n}\n\n\/\/ EncodePartial updates the total length and checksum fields of ipv4 header,\n\/\/ taking in the partial checksum, which is the checksum of the header without\n\/\/ the total length and checksum fields. It is useful in cases when similar\n\/\/ packets are produced.\nfunc (b IPv4) EncodePartial(partialChecksum, totalLength uint16) {\n\tb.SetTotalLength(totalLength)\n\tchecksum := Checksum(b[totalLen:totalLen+2], partialChecksum)\n\tb.SetChecksum(^checksum)\n}\n\n\/\/ IsValid performs basic validation on the packet.\nfunc (b IPv4) IsValid(pktSize int) bool {\n\tif len(b) < IPv4MinimumSize {\n\t\treturn false\n\t}\n\n\thlen := int(b.HeaderLength())\n\ttlen := int(b.TotalLength())\n\tif hlen > tlen || tlen > pktSize {\n\t\treturn false\n\t}\n\n\treturn true\n}\n<commit_msg>Fix misspellings<commit_after>\/\/ Copyright 2016 The Netstack Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage header\n\nimport (\n\t\"encoding\/binary\"\n\n\t\"github.com\/google\/netstack\/tcpip\"\n)\n\nconst (\n\tversIHL  = 0\n\ttos      = 1\n\ttotalLen = 2\n\tid       = 4\n\tflagsFO  = 6\n\tttl      = 8\n\tprotocol = 9\n\tchecksum = 10\n\tsrcAddr  = 12\n\tdstAddr  = 16\n)\n\n\/\/ IPv4Fields contains the fields of an IPv4 packet. It is used to describe the\n\/\/ fields of a packet that needs to be encoded.\ntype IPv4Fields struct {\n\t\/\/ IHL is the \"internet header length\" field of an IPv4 packet.\n\tIHL uint8\n\n\t\/\/ TOS is the \"type of service\" field of an IPv4 packet.\n\tTOS uint8\n\n\t\/\/ TotalLength is the \"total length\" field of an IPv4 packet.\n\tTotalLength uint16\n\n\t\/\/ ID is the \"identification\" field of an IPv4 packet.\n\tID uint16\n\n\t\/\/ Flags is the \"flags\" field of an IPv4 packet.\n\tFlags uint8\n\n\t\/\/ FragmentOffset is the \"fragment offset\" field of an IPv4 packet.\n\tFragmentOffset uint16\n\n\t\/\/ TTL is the \"time to live\" field of an IPv4 packet.\n\tTTL uint8\n\n\t\/\/ Protocol is the \"protocol\" field of an IPv4 packet.\n\tProtocol uint8\n\n\t\/\/ Checksum is the \"checksum\" field of an IPv4 packet.\n\tChecksum uint16\n\n\t\/\/ SrcAddr is the \"source ip address\" of an IPv4 packet.\n\tSrcAddr tcpip.Address\n\n\t\/\/ DstAddr is the \"destination ip address\" of an IPv4 packet.\n\tDstAddr tcpip.Address\n}\n\n\/\/ IPv4 represents an ipv4 header stored in a byte array.\n\/\/ Most of the methods of IPv4 access to the underlying slice without\n\/\/ checking the boundaries and could panic because of 'index out of range'.\n\/\/ Always call IsValid() to validate an instance of IPv4 before using other methods.\ntype IPv4 []byte\n\nconst (\n\t\/\/ IPv4MinimumSize is the minimum size of a valid IPv4 packet.\n\tIPv4MinimumSize = 20\n\n\t\/\/ IPv4MaximumHeaderSize is the maximum size of an IPv4 header. Given\n\t\/\/ that there are only 4 bits to represents the header length in 32-bit\n\t\/\/ units, the header cannot exceed 15*4 = 60 bytes.\n\tIPv4MaximumHeaderSize = 60\n\n\t\/\/ IPv4AddressSize is the size, in bytes, of an IPv4 address.\n\tIPv4AddressSize = 4\n\n\t\/\/ IPv4ProtocolNumber is IPv4's network protocol number.\n\tIPv4ProtocolNumber tcpip.NetworkProtocolNumber = 0x0800\n\n\t\/\/ IPv4Version is the version of the ipv4 protocol.\n\tIPv4Version = 4\n)\n\n\/\/ Flags that may be set in an IPv4 packet.\nconst (\n\tIPv4FlagMoreFragments = 1 << iota\n\tIPv4FlagDontFragment\n)\n\n\/\/ IPVersion returns the version of IP used in the given packet. It returns -1\n\/\/ if the packet is not large enough to contain the version field.\nfunc IPVersion(b []byte) int {\n\t\/\/ Length must be at least offset+length of version field.\n\tif len(b) < versIHL+1 {\n\t\treturn -1\n\t}\n\treturn int(b[versIHL] >> 4)\n}\n\n\/\/ HeaderLength returns the value of the \"header length\" field of the ipv4\n\/\/ header.\nfunc (b IPv4) HeaderLength() uint8 {\n\treturn (b[versIHL] & 0xf) * 4\n}\n\n\/\/ ID returns the value of the identifier field of the ipv4 header.\nfunc (b IPv4) ID() uint16 {\n\treturn binary.BigEndian.Uint16(b[id:])\n}\n\n\/\/ Protocol returns the value of the protocol field of the ipv4 header.\nfunc (b IPv4) Protocol() uint8 {\n\treturn b[protocol]\n}\n\n\/\/ Flags returns the \"flags\" field of the ipv4 header.\nfunc (b IPv4) Flags() uint8 {\n\treturn uint8(binary.BigEndian.Uint16(b[flagsFO:]) >> 13)\n}\n\n\/\/ TTL returns the \"TTL\" field of the ipv4 header.\nfunc (b IPv4) TTL() uint8 {\n\treturn b[ttl]\n}\n\n\/\/ FragmentOffset returns the \"fragment offset\" field of the ipv4 header.\nfunc (b IPv4) FragmentOffset() uint16 {\n\treturn binary.BigEndian.Uint16(b[flagsFO:]) << 3\n}\n\n\/\/ TotalLength returns the \"total length\" field of the ipv4 header.\nfunc (b IPv4) TotalLength() uint16 {\n\treturn binary.BigEndian.Uint16(b[totalLen:])\n}\n\n\/\/ Checksum returns the checksum field of the ipv4 header.\nfunc (b IPv4) Checksum() uint16 {\n\treturn binary.BigEndian.Uint16(b[checksum:])\n}\n\n\/\/ SourceAddress returns the \"source address\" field of the ipv4 header.\nfunc (b IPv4) SourceAddress() tcpip.Address {\n\treturn tcpip.Address(b[srcAddr : srcAddr+IPv4AddressSize])\n}\n\n\/\/ DestinationAddress returns the \"destination address\" field of the ipv4\n\/\/ header.\nfunc (b IPv4) DestinationAddress() tcpip.Address {\n\treturn tcpip.Address(b[dstAddr : dstAddr+IPv4AddressSize])\n}\n\n\/\/ TransportProtocol implements Network.TransportProtocol.\nfunc (b IPv4) TransportProtocol() tcpip.TransportProtocolNumber {\n\treturn tcpip.TransportProtocolNumber(b.Protocol())\n}\n\n\/\/ Payload implements Network.Payload.\nfunc (b IPv4) Payload() []byte {\n\treturn b[b.HeaderLength():][:b.PayloadLength()]\n}\n\n\/\/ PayloadLength returns the length of the payload portion of the ipv4 packet.\nfunc (b IPv4) PayloadLength() uint16 {\n\treturn b.TotalLength() - uint16(b.HeaderLength())\n}\n\n\/\/ TOS returns the \"type of service\" field of the ipv4 header.\nfunc (b IPv4) TOS() (uint8, uint32) {\n\treturn b[tos], 0\n}\n\n\/\/ SetTOS sets the \"type of service\" field of the ipv4 header.\nfunc (b IPv4) SetTOS(v uint8, _ uint32) {\n\tb[tos] = v\n}\n\n\/\/ SetTotalLength sets the \"total length\" field of the ipv4 header.\nfunc (b IPv4) SetTotalLength(totalLength uint16) {\n\tbinary.BigEndian.PutUint16(b[totalLen:], totalLength)\n}\n\n\/\/ SetChecksum sets the checksum field of the ipv4 header.\nfunc (b IPv4) SetChecksum(v uint16) {\n\tbinary.BigEndian.PutUint16(b[checksum:], v)\n}\n\n\/\/ SetFlagsFragmentOffset sets the \"flags\" and \"fragment offset\" fields of the\n\/\/ ipv4 header.\nfunc (b IPv4) SetFlagsFragmentOffset(flags uint8, offset uint16) {\n\tv := (uint16(flags) << 13) | (offset >> 3)\n\tbinary.BigEndian.PutUint16(b[flagsFO:], v)\n}\n\n\/\/ SetSourceAddress sets the \"source address\" field of the ipv4 header.\nfunc (b IPv4) SetSourceAddress(addr tcpip.Address) {\n\tcopy(b[srcAddr:srcAddr+IPv4AddressSize], addr)\n}\n\n\/\/ SetDestinationAddress sets the \"destination address\" field of the ipv4\n\/\/ header.\nfunc (b IPv4) SetDestinationAddress(addr tcpip.Address) {\n\tcopy(b[dstAddr:dstAddr+IPv4AddressSize], addr)\n}\n\n\/\/ CalculateChecksum calculates the checksum of the ipv4 header.\nfunc (b IPv4) CalculateChecksum() uint16 {\n\treturn Checksum(b[:b.HeaderLength()], 0)\n}\n\n\/\/ Encode encodes all the fields of the ipv4 header.\nfunc (b IPv4) Encode(i *IPv4Fields) {\n\tb[versIHL] = (4 << 4) | ((i.IHL \/ 4) & 0xf)\n\tb[tos] = i.TOS\n\tb.SetTotalLength(i.TotalLength)\n\tbinary.BigEndian.PutUint16(b[id:], i.ID)\n\tb.SetFlagsFragmentOffset(i.Flags, i.FragmentOffset)\n\tb[ttl] = i.TTL\n\tb[protocol] = i.Protocol\n\tb.SetChecksum(i.Checksum)\n\tcopy(b[srcAddr:srcAddr+IPv4AddressSize], i.SrcAddr)\n\tcopy(b[dstAddr:dstAddr+IPv4AddressSize], i.DstAddr)\n}\n\n\/\/ EncodePartial updates the total length and checksum fields of ipv4 header,\n\/\/ taking in the partial checksum, which is the checksum of the header without\n\/\/ the total length and checksum fields. It is useful in cases when similar\n\/\/ packets are produced.\nfunc (b IPv4) EncodePartial(partialChecksum, totalLength uint16) {\n\tb.SetTotalLength(totalLength)\n\tchecksum := Checksum(b[totalLen:totalLen+2], partialChecksum)\n\tb.SetChecksum(^checksum)\n}\n\n\/\/ IsValid performs basic validation on the packet.\nfunc (b IPv4) IsValid(pktSize int) bool {\n\tif len(b) < IPv4MinimumSize {\n\t\treturn false\n\t}\n\n\thlen := int(b.HeaderLength())\n\ttlen := int(b.TotalLength())\n\tif hlen > tlen || tlen > pktSize {\n\t\treturn false\n\t}\n\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012-2013 Tamás Gulácsi\n\/\/ See LICENSE.txt\n\/\/ Translated from cx_Oracle ((c) Anthony Tuininga) by Tamás Gulácsi\npackage goracle\n\n\/*\n#cgo CFLAGS: -I\/usr\/include\/oracle\/11.2\/client64\n#cgo LDFLAGS: -lclntsh -L\/usr\/lib\/oracle\/11.2\/client64\/lib\n\n#include <stdlib.h>\n#include <oci.h>\n*\/\nimport \"C\"\n\nimport (\n\t\/\/ \"unsafe\"\n\t\"errors\"\n\t\"fmt\"\n)\n\n\/\/ Initialize the variable.\nfunc stringVar_Initialize(v *Variable, cur *Cursor) error {\n\tv.actualLength = make([]C.ub2, v.allocatedElements)\n\treturn nil\n}\n\n\/\/ Set the value of the variable.\nfunc stringVar_SetValue(v *Variable, pos uint, value interface{}) error {\n\tvar (\n\t\ttext   string\n\t\tbuf    []byte\n\t\tok     bool\n\t\tlength int\n\t)\n\tif text, ok = value.(string); !ok {\n\t\tif buf, ok = value.([]byte); !ok {\n\t\t\treturn fmt.Errorf(\"string or []byte required, got %T\", value)\n\t\t} else {\n\t\t\tif v.typ.isCharData {\n\t\t\t\ttext = string(buf)\n\t\t\t\tlength = len(text)\n\t\t\t} else {\n\t\t\t\tlength = len(buf)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif v.typ.isCharData {\n\t\t\tlength = len(text)\n\t\t} else {\n\t\t\tlength = len(buf)\n\t\t}\n\t\tbuf = []byte(text)\n\t}\n\tif v.typ.isCharData && length > MAX_STRING_CHARS {\n\t\treturn errors.New(\"string data too large\")\n\t} else if !v.typ.isCharData && length > MAX_BINARY_BYTES {\n\t\treturn errors.New(\"binary data too large\")\n\t}\n\n\t\/\/ ensure that the buffer is large enough\n\tif length > int(v.bufferSize) {\n\t\tif err := v.resize(uint(length)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ keep a copy of the string\n\tv.actualLength[pos] = C.ub2(length)\n\tif length > 0 {\n\t\tcopy(v.dataBytes[int(v.bufferSize*pos):], buf)\n\t}\n\n\treturn nil\n}\n\n\/\/ Returns the value stored at the given array position.\nfunc stringVar_GetValue(v *Variable, pos uint) (interface{}, error) {\n\tbuf := v.dataBytes[int(v.bufferSize*pos) : int(v.bufferSize*pos)+int(v.actualLength[pos])]\n\tif v.typ == BinaryVarType {\n\t\treturn buf, nil\n\t}\n\treturn v.environment.FromEncodedString(buf), nil\n\t\/*\n\t\t#if PY_MAJOR_VERSION < 3\n\t\t    if (var->type == &vt_FixedNationalChar\n\t\t            || var->type == &vt_NationalCharString)\n\t\t        return PyUnicode_Decode(data, var->actualLength[pos],\n\t\t                var->environment->nencoding, NULL);\n\t\t#endif\n\t*\/\n}\n\n\/*\n#if PY_MAJOR_VERSION < 3\n\/\/-----------------------------------------------------------------------------\n\/\/ StringVar_PostDefine()\n\/\/   Set the character set information when values are fetched from this\n\/\/ variable.\n\/\/-----------------------------------------------------------------------------\nstatic int StringVar_PostDefine(\n    udt_StringVar *var)                 \/\/ variable to initialize\n{\n    sword status;\n\n    status = OCIAttrSet(var->defineHandle, OCI_HTYPE_DEFINE,\n            &var->type->charsetForm, 0, OCI_ATTR_CHARSET_FORM,\n            var->environment->errorHandle);\n    if (Environment_CheckForError(var->environment, status,\n            \"StringVar_PostDefine(): setting charset form\") < 0)\n        return -1;\n\n    return 0;\n}\n#endif\n*\/\n\n\/\/ Returns the buffer size to use for the variable.\nfunc stringVar_GetBufferSize(v *Variable) uint {\n\tif v.typ.isCharData {\n\t\treturn v.size * v.environment.maxBytesPerCharacter\n\t}\n\treturn uint(v.size)\n}\n\nvar (\n\tStringVarType, FixedCharVarType *VariableType\n\tBinaryVarType, RowidVarType     *VariableType\n)\n\nfunc init() {\n\tStringVarType = &VariableType{\n\t\tName:             \"String\",\n\t\tisVariableLength: true,\n\t\tinitialize:       stringVar_Initialize,\n\t\tsetValue:         stringVar_SetValue,\n\t\tgetValue:         stringVar_GetValue,\n\t\tgetBufferSize:    stringVar_GetBufferSize,\n\t\toracleType:       C.SQLT_CHR,       \/\/ Oracle type\n\t\tcharsetForm:      C.SQLCS_IMPLICIT, \/\/ charset form\n\t\tsize:             MAX_STRING_CHARS, \/\/ element length (default)\n\t\tisCharData:       true,             \/\/ is character data\n\t\tcanBeCopied:      true,             \/\/ can be copied\n\t\tcanBeInArray:     true,             \/\/ can be in array\n\t}\n\n\tFixedCharVarType = &VariableType{\n\t\tName:             \"FixedChar\",\n\t\tinitialize:       stringVar_Initialize,\n\t\tsetValue:         stringVar_SetValue,\n\t\tgetValue:         stringVar_GetValue,\n\t\tgetBufferSize:    stringVar_GetBufferSize,\n\t\toracleType:       C.SQLT_AFC,       \/\/ Oracle type\n\t\tcharsetForm:      C.SQLCS_IMPLICIT, \/\/ charset form\n\t\tsize:             2000,             \/\/ element length (default)\n\t\tisCharData:       true,             \/\/ is character data\n\t\tisVariableLength: true,             \/\/ is variable length\n\t\tcanBeCopied:      true,             \/\/ can be copied\n\t\tcanBeInArray:     true,             \/\/ can be in array\n\t}\n\n\tRowidVarType = &VariableType{\n\t\tName:             \"Rowid\",\n\t\tinitialize:       stringVar_Initialize,\n\t\tsetValue:         stringVar_SetValue,\n\t\tgetValue:         stringVar_GetValue,\n\t\tgetBufferSize:    stringVar_GetBufferSize,\n\t\toracleType:       C.SQLT_CHR,       \/\/ Oracle type\n\t\tcharsetForm:      C.SQLCS_IMPLICIT, \/\/ charset form\n\t\tsize:             18,               \/\/ element length (default)\n\t\tisCharData:       true,             \/\/ is character data\n\t\tisVariableLength: false,            \/\/ is variable length\n\t\tcanBeCopied:      true,             \/\/ can be copied\n\t\tcanBeInArray:     true,             \/\/ can be in array\n\t}\n\n\tBinaryVarType = &VariableType{\n\t\tName:             \"Binary\",\n\t\tinitialize:       stringVar_Initialize,\n\t\tsetValue:         stringVar_SetValue,\n\t\tgetValue:         stringVar_GetValue,\n\t\toracleType:       C.SQLT_BIN,       \/\/ Oracle type\n\t\tcharsetForm:      C.SQLCS_IMPLICIT, \/\/ charset form\n\t\tsize:             MAX_BINARY_BYTES, \/\/ element length (default)\n\t\tisCharData:       false,            \/\/ is character data\n\t\tisVariableLength: true,             \/\/ is variable length\n\t\tcanBeCopied:      true,             \/\/ can be copied\n\t\tcanBeInArray:     true,             \/\/ can be in array\n\t}\n}\n<commit_msg>stringvar still contained license<commit_after>package goracle\n\n\/*\n#cgo CFLAGS: -I\/usr\/include\/oracle\/11.2\/client64\n#cgo LDFLAGS: -lclntsh -L\/usr\/lib\/oracle\/11.2\/client64\/lib\n\n#include <stdlib.h>\n#include <oci.h>\n*\/\nimport \"C\"\n\nimport (\n\t\/\/ \"unsafe\"\n\t\"errors\"\n\t\"fmt\"\n)\n\n\/\/ Initialize the variable.\nfunc stringVar_Initialize(v *Variable, cur *Cursor) error {\n\tv.actualLength = make([]C.ub2, v.allocatedElements)\n\treturn nil\n}\n\n\/\/ Set the value of the variable.\nfunc stringVar_SetValue(v *Variable, pos uint, value interface{}) error {\n\tvar (\n\t\ttext   string\n\t\tbuf    []byte\n\t\tok     bool\n\t\tlength int\n\t)\n\tif text, ok = value.(string); !ok {\n\t\tif buf, ok = value.([]byte); !ok {\n\t\t\treturn fmt.Errorf(\"string or []byte required, got %T\", value)\n\t\t} else {\n\t\t\tif v.typ.isCharData {\n\t\t\t\ttext = string(buf)\n\t\t\t\tlength = len(text)\n\t\t\t} else {\n\t\t\t\tlength = len(buf)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif v.typ.isCharData {\n\t\t\tlength = len(text)\n\t\t} else {\n\t\t\tlength = len(buf)\n\t\t}\n\t\tbuf = []byte(text)\n\t}\n\tif v.typ.isCharData && length > MAX_STRING_CHARS {\n\t\treturn errors.New(\"string data too large\")\n\t} else if !v.typ.isCharData && length > MAX_BINARY_BYTES {\n\t\treturn errors.New(\"binary data too large\")\n\t}\n\n\t\/\/ ensure that the buffer is large enough\n\tif length > int(v.bufferSize) {\n\t\tif err := v.resize(uint(length)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ keep a copy of the string\n\tv.actualLength[pos] = C.ub2(length)\n\tif length > 0 {\n\t\tcopy(v.dataBytes[int(v.bufferSize*pos):], buf)\n\t}\n\n\treturn nil\n}\n\n\/\/ Returns the value stored at the given array position.\nfunc stringVar_GetValue(v *Variable, pos uint) (interface{}, error) {\n\tbuf := v.dataBytes[int(v.bufferSize*pos) : int(v.bufferSize*pos)+int(v.actualLength[pos])]\n\tif v.typ == BinaryVarType {\n\t\treturn buf, nil\n\t}\n\treturn v.environment.FromEncodedString(buf), nil\n\t\/*\n\t\t#if PY_MAJOR_VERSION < 3\n\t\t    if (var->type == &vt_FixedNationalChar\n\t\t            || var->type == &vt_NationalCharString)\n\t\t        return PyUnicode_Decode(data, var->actualLength[pos],\n\t\t                var->environment->nencoding, NULL);\n\t\t#endif\n\t*\/\n}\n\n\/*\n#if PY_MAJOR_VERSION < 3\n\/\/-----------------------------------------------------------------------------\n\/\/ StringVar_PostDefine()\n\/\/   Set the character set information when values are fetched from this\n\/\/ variable.\n\/\/-----------------------------------------------------------------------------\nstatic int StringVar_PostDefine(\n    udt_StringVar *var)                 \/\/ variable to initialize\n{\n    sword status;\n\n    status = OCIAttrSet(var->defineHandle, OCI_HTYPE_DEFINE,\n            &var->type->charsetForm, 0, OCI_ATTR_CHARSET_FORM,\n            var->environment->errorHandle);\n    if (Environment_CheckForError(var->environment, status,\n            \"StringVar_PostDefine(): setting charset form\") < 0)\n        return -1;\n\n    return 0;\n}\n#endif\n*\/\n\n\/\/ Returns the buffer size to use for the variable.\nfunc stringVar_GetBufferSize(v *Variable) uint {\n\tif v.typ.isCharData {\n\t\treturn v.size * v.environment.maxBytesPerCharacter\n\t}\n\treturn uint(v.size)\n}\n\nvar (\n\tStringVarType, FixedCharVarType *VariableType\n\tBinaryVarType, RowidVarType     *VariableType\n)\n\nfunc init() {\n\tStringVarType = &VariableType{\n\t\tName:             \"String\",\n\t\tisVariableLength: true,\n\t\tinitialize:       stringVar_Initialize,\n\t\tsetValue:         stringVar_SetValue,\n\t\tgetValue:         stringVar_GetValue,\n\t\tgetBufferSize:    stringVar_GetBufferSize,\n\t\toracleType:       C.SQLT_CHR,       \/\/ Oracle type\n\t\tcharsetForm:      C.SQLCS_IMPLICIT, \/\/ charset form\n\t\tsize:             MAX_STRING_CHARS, \/\/ element length (default)\n\t\tisCharData:       true,             \/\/ is character data\n\t\tcanBeCopied:      true,             \/\/ can be copied\n\t\tcanBeInArray:     true,             \/\/ can be in array\n\t}\n\n\tFixedCharVarType = &VariableType{\n\t\tName:             \"FixedChar\",\n\t\tinitialize:       stringVar_Initialize,\n\t\tsetValue:         stringVar_SetValue,\n\t\tgetValue:         stringVar_GetValue,\n\t\tgetBufferSize:    stringVar_GetBufferSize,\n\t\toracleType:       C.SQLT_AFC,       \/\/ Oracle type\n\t\tcharsetForm:      C.SQLCS_IMPLICIT, \/\/ charset form\n\t\tsize:             2000,             \/\/ element length (default)\n\t\tisCharData:       true,             \/\/ is character data\n\t\tisVariableLength: true,             \/\/ is variable length\n\t\tcanBeCopied:      true,             \/\/ can be copied\n\t\tcanBeInArray:     true,             \/\/ can be in array\n\t}\n\n\tRowidVarType = &VariableType{\n\t\tName:             \"Rowid\",\n\t\tinitialize:       stringVar_Initialize,\n\t\tsetValue:         stringVar_SetValue,\n\t\tgetValue:         stringVar_GetValue,\n\t\tgetBufferSize:    stringVar_GetBufferSize,\n\t\toracleType:       C.SQLT_CHR,       \/\/ Oracle type\n\t\tcharsetForm:      C.SQLCS_IMPLICIT, \/\/ charset form\n\t\tsize:             18,               \/\/ element length (default)\n\t\tisCharData:       true,             \/\/ is character data\n\t\tisVariableLength: false,            \/\/ is variable length\n\t\tcanBeCopied:      true,             \/\/ can be copied\n\t\tcanBeInArray:     true,             \/\/ can be in array\n\t}\n\n\tBinaryVarType = &VariableType{\n\t\tName:             \"Binary\",\n\t\tinitialize:       stringVar_Initialize,\n\t\tsetValue:         stringVar_SetValue,\n\t\tgetValue:         stringVar_GetValue,\n\t\toracleType:       C.SQLT_BIN,       \/\/ Oracle type\n\t\tcharsetForm:      C.SQLCS_IMPLICIT, \/\/ charset form\n\t\tsize:             MAX_BINARY_BYTES, \/\/ element length (default)\n\t\tisCharData:       false,            \/\/ is character data\n\t\tisVariableLength: true,             \/\/ is variable length\n\t\tcanBeCopied:      true,             \/\/ can be copied\n\t\tcanBeInArray:     true,             \/\/ can be in array\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package web\n\nimport \"gopkg.in\/webnice\/debug.v1\"\nimport \"gopkg.in\/webnice\/log.v2\"\nimport (\n\t\"crypto\/tls\"\n\t\"net\"\n\t\"os\"\n)\n\n\/\/ Wait while web server is running\nfunc (wsv *web) Wait() Interface { wsv.doCloseDone.Wait(); return wsv }\n\n\/\/ ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections\nfunc (wsv *web) ListenAndServe(addr string) Interface {\n\tvar conf *Configuration\n\n\tif conf, wsv.err = parseAddress(addr); wsv.err != nil {\n\t\treturn wsv\n\t}\n\n\treturn wsv.ListenAndServeWithConfig(conf)\n}\n\n\/\/ ListenAndServeTLS listens on the TCP network address address with TLS and then calls Serve with handler\n\/\/ to handle requests on incoming connections\nfunc (wsv *web) ListenAndServeTLS(addr string, certFile string, keyFile string, tlsConfig *tls.Config) Interface {\n\tvar conf *Configuration\n\n\tif conf, wsv.err = parseAddress(addr); wsv.err != nil {\n\t\treturn wsv\n\t}\n\tconf.TLSPublicKeyPEM, conf.TLSPrivateKeyPEM = certFile, keyFile\n\n\treturn wsv.ListenAndServeTLSWithConfig(conf, tlsConfig)\n}\n\n\/\/ ListenAndServeWithConfig Fully configurable web server listens and then calls Serve on incoming connections\nfunc (wsv *web) ListenAndServeWithConfig(conf *Configuration) Interface {\n\tif conf == nil {\n\t\twsv.err = ErrNoConfiguration()\n\t\treturn wsv\n\t}\n\twsv.conf = conf\n\n\treturn wsv.Listen(nil)\n}\n\n\/\/ ListenAndServeTLSWithConfig Fully configurable web server listens and then calls Serve on incoming connections\nfunc (wsv *web) ListenAndServeTLSWithConfig(conf *Configuration, tlsConfig *tls.Config) Interface {\n\tif conf == nil {\n\t\twsv.err = ErrNoConfiguration()\n\t\treturn wsv\n\t}\n\twsv.conf = conf\n\tif tlsConfig == nil {\n\t\tif tlsConfig, wsv.err = wsv.tlsConfigDefault(conf.TLSPublicKeyPEM, conf.TLSPrivateKeyPEM); wsv.err != nil {\n\t\t\treturn wsv\n\t\t}\n\t}\n\n\treturn wsv.Listen(tlsConfig)\n}\n\n\/\/ NewListener Make new listener from web server configuration\nfunc (wsv *web) NewListener(conf *Configuration) (ret net.Listener, err error) {\n\tvar (\n\t\tlstWithNames map[string][]net.Listener\n\t\tlisteners    []net.Listener\n\t\tok           bool\n\t)\n\n\tdefaultConfiguration(conf)\n\tswitch conf.Mode {\n\tcase netSystemd:\n\t\tif conf.Socket != \"\" {\n\t\t\t\/\/ Имена сокетов указаны\n\t\t\tif lstWithNames, err = wsv.ListenersSystemdWithNames(false); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Debug(debug.DumperString(lstWithNames, listeners, os.Environ(), conf.Socket, conf))\n\n\t\t\t\/\/ Выбор сокета по имени\n\t\t\tif listeners, ok = lstWithNames[conf.Socket]; !ok {\n\t\t\t\terr = ErrListenSystemdNotFound()\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Имена сокетов не указаны\n\t\t\tif listeners, err = wsv.ListenersSystemdWithoutNames(false); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif len(listeners) == 0 {\n\t\t\terr = ErrListenSystemdUnexpectedNumber()\n\t\t\treturn\n\t\t}\n\t\tret = listeners[0]\n\tcase netUnix, netUnixPacket:\n\t\t_ = os.Remove(conf.Socket)\n\t\tret, err = net.Listen(conf.Mode, conf.Socket)\n\t\t_ = os.Chmod(conf.Socket, os.FileMode(0666))\n\tdefault:\n\t\tret, err = net.Listen(conf.Mode, conf.HostPort)\n\t}\n\n\treturn\n}\n\n\/\/ NewListenerTLS Make new listener with TLS from web server configuration\nfunc (wsv *web) NewListenerTLS(conf *Configuration, tlsConfig *tls.Config) (ret net.Listener, err error) {\n\tvar l net.Listener\n\n\tif l, err = wsv.NewListener(conf); err != nil {\n\t\treturn\n\t}\n\tif tlsConfig == nil {\n\t\tif tlsConfig, err = wsv.tlsConfigDefault(conf.TLSPublicKeyPEM, conf.TLSPrivateKeyPEM); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tret = tls.NewListener(l, tlsConfig)\n\n\treturn\n}\n\n\/\/ Конфигурация TLS по умолчанию\nfunc (wsv *web) tlsConfigDefault(tlsPublicFile string, tlsPrivateFile string) (ret *tls.Config, err error) {\n\tret = &tls.Config{\n\t\tMinVersion:               tls.VersionTLS12,\n\t\tCurvePreferences:         []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},\n\t\tPreferServerCipherSuites: true,\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_RSA_WITH_AES_256_CBC_SHA,\n\t\t},\n\t\tCertificates: make([]tls.Certificate, 1),\n\t}\n\tif ret.Certificates[0], err = tls.LoadX509KeyPair(tlsPublicFile, tlsPrivateFile); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ Listen Begin listen port and web server serve\nfunc (wsv *web) Listen(tlsConfig *tls.Config) Interface {\n\tvar ltn net.Listener\n\n\tif wsv.isRun.Load().(bool) {\n\t\twsv.err = ErrAlreadyRunning()\n\t\treturn wsv\n\t}\n\tswitch tlsConfig == nil {\n\tcase true:\n\t\tltn, wsv.err = wsv.NewListener(wsv.conf)\n\tcase false:\n\t\tltn, wsv.err = wsv.NewListenerTLS(wsv.conf, tlsConfig)\n\t}\n\tif wsv.err != nil {\n\t\treturn wsv\n\t}\n\n\treturn wsv.ServeTLS(ltn, tlsConfig)\n}\n\n\/\/ Serve accepts incoming connections on the listener, creating a new web server goroutine\nfunc (wsv *web) Serve(ltn net.Listener) Interface { return wsv.ServeTLS(ltn, nil) }\n\n\/\/ ServeTLS accepts incoming connections on the listener with TLS configuration, creating a new web server goroutine\nfunc (wsv *web) ServeTLS(ltn net.Listener, tlsConfig *tls.Config) Interface {\n\tvar conf *Configuration\n\n\t\/\/ TODO: Реализовать поддержку PROXY Protocol через \"gopkg.in\/webnice\/web.v1\/proxyp\", conf.ProxyProtocol\n\n\tif wsv.conf == nil {\n\t\tconf, _ = parseAddress(ltn.Addr().String())\n\t\tdefaultConfiguration(conf)\n\t\twsv.conf = conf\n\t}\n\twsv.listener = ltn\n\twsv.isRun.Store(true)\n\twsv.doCloseDone.Add(1)\n\tgo wsv.run(tlsConfig)\n\n\treturn wsv\n}\n\n\/\/ Goroutine of the web server\nfunc (wsv *web) run(tlsConfig *tls.Config) {\n\tdefer wsv.doCloseDone.Done()\n\tdefer wsv.isRun.Store(false)\n\tdefer func() {\n\t\tif wsv.conf.Socket == \"\" {\n\t\t\treturn\n\t\t}\n\t\tswitch wsv.conf.Mode {\n\t\tcase netSystemd:\n\t\t\treturn\n\t\tcase netUnix, netUnixPacket:\n\t\t\t_ = os.Remove(wsv.conf.Socket)\n\t\t}\n\t}()\n\n\t\/\/ Configure net\/http web server\n\tif wsv.server = wsv.loadConfiguration(tlsConfig); wsv.err != nil {\n\t\treturn\n\t}\n\t\/\/ Configure keepalive of web server\n\tif wsv.conf.KeepAliveDisable {\n\t\twsv.server.SetKeepAlivesEnabled(false)\n\t}\n\t\/\/ Begin serve\n\tif wsv.conf.TLSPrivateKeyPEM == \"\" || wsv.conf.TLSPublicKeyPEM == \"\" {\n\t\twsv.err = wsv.server.Serve(wsv.listener)\n\t\treturn\n\t}\n\twsv.err = wsv.server.ServeTLS(wsv.listener, wsv.conf.TLSPublicKeyPEM, wsv.conf.TLSPrivateKeyPEM)\n}\n<commit_msg>Debug removed<commit_after>package web\n\n\/\/import \"gopkg.in\/webnice\/debug.v1\"\n\/\/import \"gopkg.in\/webnice\/log.v2\"\nimport (\n\t\"crypto\/tls\"\n\t\"net\"\n\t\"os\"\n\t\"path\"\n)\n\n\/\/ Wait while web server is running\nfunc (wsv *web) Wait() Interface { wsv.doCloseDone.Wait(); return wsv }\n\n\/\/ ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections\nfunc (wsv *web) ListenAndServe(addr string) Interface {\n\tvar conf *Configuration\n\n\tif conf, wsv.err = parseAddress(addr); wsv.err != nil {\n\t\treturn wsv\n\t}\n\n\treturn wsv.ListenAndServeWithConfig(conf)\n}\n\n\/\/ ListenAndServeTLS listens on the TCP network address address with TLS and then calls Serve with handler\n\/\/ to handle requests on incoming connections\nfunc (wsv *web) ListenAndServeTLS(addr string, certFile string, keyFile string, tlsConfig *tls.Config) Interface {\n\tvar conf *Configuration\n\n\tif conf, wsv.err = parseAddress(addr); wsv.err != nil {\n\t\treturn wsv\n\t}\n\tconf.TLSPublicKeyPEM, conf.TLSPrivateKeyPEM = certFile, keyFile\n\n\treturn wsv.ListenAndServeTLSWithConfig(conf, tlsConfig)\n}\n\n\/\/ ListenAndServeWithConfig Fully configurable web server listens and then calls Serve on incoming connections\nfunc (wsv *web) ListenAndServeWithConfig(conf *Configuration) Interface {\n\tif conf == nil {\n\t\twsv.err = ErrNoConfiguration()\n\t\treturn wsv\n\t}\n\twsv.conf = conf\n\n\treturn wsv.Listen(nil)\n}\n\n\/\/ ListenAndServeTLSWithConfig Fully configurable web server listens and then calls Serve on incoming connections\nfunc (wsv *web) ListenAndServeTLSWithConfig(conf *Configuration, tlsConfig *tls.Config) Interface {\n\tif conf == nil {\n\t\twsv.err = ErrNoConfiguration()\n\t\treturn wsv\n\t}\n\twsv.conf = conf\n\tif tlsConfig == nil {\n\t\tif tlsConfig, wsv.err = wsv.tlsConfigDefault(conf.TLSPublicKeyPEM, conf.TLSPrivateKeyPEM); wsv.err != nil {\n\t\t\treturn wsv\n\t\t}\n\t}\n\n\treturn wsv.Listen(tlsConfig)\n}\n\n\/\/ NewListener Make new listener from web server configuration\nfunc (wsv *web) NewListener(conf *Configuration) (ret net.Listener, err error) {\n\tvar (\n\t\tlstWithNames map[string][]net.Listener\n\t\tlisteners    []net.Listener\n\t\tok           bool\n\t)\n\n\tdefaultConfiguration(conf)\n\tswitch conf.Mode {\n\tcase netSystemd:\n\t\tif conf.Socket != \"\" {\n\t\t\t\/\/ Имена сокетов указаны\n\t\t\tif lstWithNames, err = wsv.ListenersSystemdWithNames(false); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ Выбор сокета по имени\n\t\t\tif listeners, ok = lstWithNames[path.Base(conf.Socket)]; !ok {\n\t\t\t\terr = ErrListenSystemdNotFound()\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Имена сокетов не указаны\n\t\t\tif listeners, err = wsv.ListenersSystemdWithoutNames(false); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif len(listeners) == 0 {\n\t\t\terr = ErrListenSystemdUnexpectedNumber()\n\t\t\treturn\n\t\t}\n\t\tret = listeners[0]\n\tcase netUnix, netUnixPacket:\n\t\t_ = os.Remove(conf.Socket)\n\t\tret, err = net.Listen(conf.Mode, conf.Socket)\n\t\t_ = os.Chmod(conf.Socket, os.FileMode(0666))\n\tdefault:\n\t\tret, err = net.Listen(conf.Mode, conf.HostPort)\n\t}\n\n\treturn\n}\n\n\/\/ NewListenerTLS Make new listener with TLS from web server configuration\nfunc (wsv *web) NewListenerTLS(conf *Configuration, tlsConfig *tls.Config) (ret net.Listener, err error) {\n\tvar l net.Listener\n\n\tif l, err = wsv.NewListener(conf); err != nil {\n\t\treturn\n\t}\n\tif tlsConfig == nil {\n\t\tif tlsConfig, err = wsv.tlsConfigDefault(conf.TLSPublicKeyPEM, conf.TLSPrivateKeyPEM); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tret = tls.NewListener(l, tlsConfig)\n\n\treturn\n}\n\n\/\/ Конфигурация TLS по умолчанию\nfunc (wsv *web) tlsConfigDefault(tlsPublicFile string, tlsPrivateFile string) (ret *tls.Config, err error) {\n\tret = &tls.Config{\n\t\tMinVersion:               tls.VersionTLS12,\n\t\tCurvePreferences:         []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},\n\t\tPreferServerCipherSuites: true,\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n\t\t\ttls.TLS_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_RSA_WITH_AES_256_CBC_SHA,\n\t\t},\n\t\tCertificates: make([]tls.Certificate, 1),\n\t}\n\tif ret.Certificates[0], err = tls.LoadX509KeyPair(tlsPublicFile, tlsPrivateFile); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ Listen Begin listen port and web server serve\nfunc (wsv *web) Listen(tlsConfig *tls.Config) Interface {\n\tvar ltn net.Listener\n\n\tif wsv.isRun.Load().(bool) {\n\t\twsv.err = ErrAlreadyRunning()\n\t\treturn wsv\n\t}\n\tswitch tlsConfig == nil {\n\tcase true:\n\t\tltn, wsv.err = wsv.NewListener(wsv.conf)\n\tcase false:\n\t\tltn, wsv.err = wsv.NewListenerTLS(wsv.conf, tlsConfig)\n\t}\n\tif wsv.err != nil {\n\t\treturn wsv\n\t}\n\n\treturn wsv.ServeTLS(ltn, tlsConfig)\n}\n\n\/\/ Serve accepts incoming connections on the listener, creating a new web server goroutine\nfunc (wsv *web) Serve(ltn net.Listener) Interface { return wsv.ServeTLS(ltn, nil) }\n\n\/\/ ServeTLS accepts incoming connections on the listener with TLS configuration, creating a new web server goroutine\nfunc (wsv *web) ServeTLS(ltn net.Listener, tlsConfig *tls.Config) Interface {\n\tvar conf *Configuration\n\n\t\/\/ TODO: Реализовать поддержку PROXY Protocol через \"gopkg.in\/webnice\/web.v1\/proxyp\", conf.ProxyProtocol\n\n\tif wsv.conf == nil {\n\t\tconf, _ = parseAddress(ltn.Addr().String())\n\t\tdefaultConfiguration(conf)\n\t\twsv.conf = conf\n\t}\n\twsv.listener = ltn\n\twsv.isRun.Store(true)\n\twsv.doCloseDone.Add(1)\n\tgo wsv.run(tlsConfig)\n\n\treturn wsv\n}\n\n\/\/ Goroutine of the web server\nfunc (wsv *web) run(tlsConfig *tls.Config) {\n\tdefer wsv.doCloseDone.Done()\n\tdefer wsv.isRun.Store(false)\n\tdefer func() {\n\t\tif wsv.conf.Socket == \"\" {\n\t\t\treturn\n\t\t}\n\t\tswitch wsv.conf.Mode {\n\t\tcase netSystemd:\n\t\t\treturn\n\t\tcase netUnix, netUnixPacket:\n\t\t\t_ = os.Remove(wsv.conf.Socket)\n\t\t}\n\t}()\n\n\t\/\/ Configure net\/http web server\n\tif wsv.server = wsv.loadConfiguration(tlsConfig); wsv.err != nil {\n\t\treturn\n\t}\n\t\/\/ Configure keepalive of web server\n\tif wsv.conf.KeepAliveDisable {\n\t\twsv.server.SetKeepAlivesEnabled(false)\n\t}\n\t\/\/ Begin serve\n\tif wsv.conf.TLSPrivateKeyPEM == \"\" || wsv.conf.TLSPublicKeyPEM == \"\" {\n\t\twsv.err = wsv.server.Serve(wsv.listener)\n\t\treturn\n\t}\n\twsv.err = wsv.server.ServeTLS(wsv.listener, wsv.conf.TLSPublicKeyPEM, wsv.conf.TLSPrivateKeyPEM)\n}\n<|endoftext|>"}
{"text":"<commit_before>package tlsdefaults\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/getlantern\/keyman\"\n)\n\nvar (\n\ttenYearsFromToday = time.Now().AddDate(10, 0, 0)\n)\n\n\/\/ Listen opens a TLS listener at the given address using the private key and\n\/\/ certificate PEM files at the given paths. If no files exists, it creates a\n\/\/ new key and self-signed certificate at those locations.\nfunc Listen(addr, pkfile, certfile string) (net.Listener, error) {\n\tl, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to listen for connections at %s: %s\\n\", addr, err)\n\t}\n\n\treturn NewListenerAddr(l, addr, pkfile, certfile)\n}\n\n\/\/ NewListener creates a TLS listener based on the given listener using the\n\/\/ private key and certificate PEM files at the given paths. If no files exists,\n\/\/ it creates a new key and self-signed certificate at those locations.\nfunc NewListener(l net.Listener, pkfile, certfile string) (net.Listener, error) {\n\treturn NewListenerAddr(l, l.Addr().String(), pkfile, certfile)\n}\n\n\/\/ NewListenerAddr is like NewListener but uses the specified addr to generate\n\/\/ the cert.\nfunc NewListenerAddr(l net.Listener, addr string, pkfile, certfile string) (net.Listener, error) {\n\thost, _, err := net.SplitHostPort(addr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to split host and port for %v: %v\\n\", addr, err)\n\t}\n\n\tmypkfile := pkfile\n\tif mypkfile == \"\" {\n\t\tmypkfile = \"key.pem\"\n\t}\n\tmycertfile := certfile\n\tif mycertfile == \"\" {\n\t\tmycertfile = \"cert.pem\"\n\t}\n\tctx := CertContext{\n\t\tPKFile:         mypkfile,\n\t\tServerCertFile: mycertfile,\n\t}\n\t_, err1 := os.Stat(ctx.ServerCertFile)\n\t_, err2 := os.Stat(ctx.PKFile)\n\tif os.IsNotExist(err1) || os.IsNotExist(err2) {\n\t\tfmt.Println(\"At least one of the Key\/Cert files is not found -> Generating new key pair\")\n\t\terr = ctx.initServerCert(host)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to init server cert: %s\\n\", err)\n\t\t}\n\t} \/* else if *debug {\n\t    fmt.Println(\"Using provided Key\/Cert files\")\n\t}*\/\n\n\ttlsConfig := Server()\n\tcert, err := tls.LoadX509KeyPair(ctx.ServerCertFile, ctx.PKFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to load certificate and key from %s and %s: %s\\n\", ctx.ServerCertFile, ctx.PKFile, err)\n\t}\n\ttlsConfig.Certificates = []tls.Certificate{cert}\n\n\treturn tls.NewListener(l, tlsConfig), nil\n}\n\n\/\/ CertContext encapsulates the certificates used by a Server\ntype CertContext struct {\n\tPKFile         string\n\tServerCertFile string\n\tPK             *keyman.PrivateKey\n\tServerCert     *keyman.Certificate\n}\n\n\/\/ InitServerCert initializes a PK + cert for use by a server proxy, signed by\n\/\/ the CA certificate.  We always generate a new certificate just in case.\nfunc (ctx *CertContext) initServerCert(host string) (err error) {\n\tif ctx.PK, err = keyman.LoadPKFromFile(ctx.PKFile); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tfmt.Printf(\"Creating new PK at: %s\\n\", ctx.PKFile)\n\t\t\tif ctx.PK, err = keyman.GeneratePK(2048); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err = ctx.PK.WriteToFile(ctx.PKFile); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Unable to save private key: %s\\n\", err)\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"Unable to read private key, even though it exists: %s\\n\", err)\n\t\t}\n\t}\n\n\tfmt.Printf(\"Creating new server cert at: %s\\n\", ctx.ServerCertFile)\n\tctx.ServerCert, err = ctx.PK.TLSCertificateFor(\"Lantern\", host, tenYearsFromToday, true, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = ctx.ServerCert.WriteToFile(ctx.ServerCertFile)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn nil\n}\n<commit_msg>Exposed BuildListenerConfig function<commit_after>package tlsdefaults\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/getlantern\/keyman\"\n)\n\nvar (\n\ttenYearsFromToday = time.Now().AddDate(10, 0, 0)\n)\n\n\/\/ Listen opens a TLS listener at the given address using the private key and\n\/\/ certificate PEM files at the given paths. If no files exists, it creates a\n\/\/ new key and self-signed certificate at those locations.\nfunc Listen(addr, pkfile, certfile string) (net.Listener, error) {\n\tl, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to listen for connections at %s: %s\\n\", addr, err)\n\t}\n\n\treturn NewListenerAddr(l, addr, pkfile, certfile)\n}\n\n\/\/ NewListener creates a TLS listener based on the given listener using the\n\/\/ private key and certificate PEM files at the given paths. If no files exists,\n\/\/ it creates a new key and self-signed certificate at those locations.\nfunc NewListener(l net.Listener, pkfile, certfile string) (net.Listener, error) {\n\treturn NewListenerAddr(l, l.Addr().String(), pkfile, certfile)\n}\n\n\/\/ NewListenerAddr is like NewListener but uses the specified addr to generate\n\/\/ the cert.\nfunc NewListenerAddr(l net.Listener, addr string, pkfile, certfile string) (net.Listener, error) {\n\tcfg, err := BuildListenerConfig(addr, pkfile, certfile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn tls.NewListener(l, cfg), nil\n}\n\n\/\/ BuildListenerConfig builds a tls.Config for a listener at the given addr\nfunc BuildListenerConfig(addr string, pkfile string, certfile string) (*tls.Config, error) {\n\thost, _, err := net.SplitHostPort(addr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to split host and port for %v: %v\\n\", addr, err)\n\t}\n\n\tmypkfile := pkfile\n\tif mypkfile == \"\" {\n\t\tmypkfile = \"key.pem\"\n\t}\n\tmycertfile := certfile\n\tif mycertfile == \"\" {\n\t\tmycertfile = \"cert.pem\"\n\t}\n\tctx := CertContext{\n\t\tPKFile:         mypkfile,\n\t\tServerCertFile: mycertfile,\n\t}\n\t_, err1 := os.Stat(ctx.ServerCertFile)\n\t_, err2 := os.Stat(ctx.PKFile)\n\tif os.IsNotExist(err1) || os.IsNotExist(err2) {\n\t\tfmt.Println(\"At least one of the Key\/Cert files is not found -> Generating new key pair\")\n\t\terr = ctx.initServerCert(host)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to init server cert: %s\\n\", err)\n\t\t}\n\t} \/* else if *debug {\n\t    fmt.Println(\"Using provided Key\/Cert files\")\n\t}*\/\n\n\ttlsConfig := Server()\n\tcert, err := tls.LoadX509KeyPair(ctx.ServerCertFile, ctx.PKFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to load certificate and key from %s and %s: %s\\n\", ctx.ServerCertFile, ctx.PKFile, err)\n\t}\n\ttlsConfig.Certificates = []tls.Certificate{cert}\n\n\treturn tlsConfig, nil\n}\n\n\/\/ CertContext encapsulates the certificates used by a Server\ntype CertContext struct {\n\tPKFile         string\n\tServerCertFile string\n\tPK             *keyman.PrivateKey\n\tServerCert     *keyman.Certificate\n}\n\n\/\/ InitServerCert initializes a PK + cert for use by a server proxy, signed by\n\/\/ the CA certificate.  We always generate a new certificate just in case.\nfunc (ctx *CertContext) initServerCert(host string) (err error) {\n\tif ctx.PK, err = keyman.LoadPKFromFile(ctx.PKFile); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tfmt.Printf(\"Creating new PK at: %s\\n\", ctx.PKFile)\n\t\t\tif ctx.PK, err = keyman.GeneratePK(2048); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err = ctx.PK.WriteToFile(ctx.PKFile); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Unable to save private key: %s\\n\", err)\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"Unable to read private key, even though it exists: %s\\n\", err)\n\t\t}\n\t}\n\n\tfmt.Printf(\"Creating new server cert at: %s\\n\", ctx.ServerCertFile)\n\tctx.ServerCert, err = ctx.PK.TLSCertificateFor(\"Lantern\", host, tenYearsFromToday, true, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = ctx.ServerCert.WriteToFile(ctx.ServerCertFile)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package ics\n\nimport (\n\t\"encoding\/base64\"\n\t\"errors\"\n)\n\nconst (\n\tcalscalec        = \"CALSCALE\"\n\tmethodc          = \"METHOD\"\n\tprodidc          = \"PRODID\"\n\tversionc         = \"VERSION\"\n\tattachc          = \"ATTACH\"\n\tcategoriesc      = \"CATEGORIES\"\n\tclassc           = \"CLASS\"\n\tcommentc         = \"COMMENT\"\n\tdescriptionc     = \"DESCRIPTION\"\n\tgeoc             = \"GEO\"\n\tlocationc        = \"LOCATION\"\n\tpercentcompletec = \"PERCENT-COMPLETE\"\n\tpriorityc        = \"PRIORITY\"\n\tresourcesc       = \"RESOURCES\"\n\tstatusc          = \"STATUS\"\n\tsummaryc         = \"SUMMARY\"\n\tcompletedc       = \"COMPLETED\"\n\tdtendc           = \"DTEND\"\n\tduec             = \"DUE\"\n\tdtstartc         = \"DTSTART\"\n\tdurationc        = \"DURATION\"\n\tfreebusyc        = \"FREEBUSY\"\n\ttranspc          = \"TRANSP\"\n\ttzidc            = \"TZID\"\n\ttznamec          = \"TZNAME\"\n\ttzoffsetfromc    = \"TZOFFSETFROM\"\n\ttzoffsettoc      = \"TZOFFSETTO\"\n\ttzurlc           = \"TZURL\"\n\tattendeec        = \"ATTENDEE\"\n\tcontactc         = \"CONTACT\"\n\torganizerc       = \"ORGANIZER\"\n\trecuridc         = \"RECURRENCE-ID\"\n\trelatedc         = \"RELATED-TO\"\n\turlc             = \"URL\"\n\tuidc             = \"UID\"\n\texdatec          = \"EXDATE\"\n\trdatec           = \"RDATE\"\n\trrulec           = \"RRULE\"\n\tactionc          = \"ACTION\"\n\trepeatc          = \"REPEAT\"\n\ttriggerc         = \"TRIGGER\"\n\tcreatedc         = \"CREATED\"\n\tdtstampc         = \"DTSTAMP\"\n\tlastmodc         = \"LAST-MODIFIED\"\n\tseqc             = \"SEQUENCE\"\n)\n\ntype component interface{}\n\ntype attach struct {\n\tURI  bool\n\tMime string\n\tData []byte\n}\n\nfunc (p *parser) readAttachComponent() (component, error) {\n\tas, err := p.readAttributes(fmttypeparam, encodingparam, valuetypeparam)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvalue, err := p.readValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turi := true\n\tenc, encOK := as[encodingparam]\n\tval, valOK := as[valuetypeparam]\n\tvar data []byte\n\tif encOK && valOK {\n\t\turi = false\n\t\tif enc.(encoding) != encodingBase64 || val.(value) != valueBinary {\n\t\t\treturn nil, ErrUnsupportedValue\n\t\t}\n\t\tdata, err = base64.StdEncoding.DecodeString(value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t} else if encOK == valOK {\n\t\tdata = []byte(unescape(value))\n\t} else {\n\t\treturn nil, ErrInvalidAttributeCombination\n\t}\n\treturn attach{\n\t\turi,\n\t\tas[fmttypeparam],\n\t\tdata,\n\t}, nil\n}\n\ntype categories struct {\n\tLanguage   string\n\tCategories []string\n}\n\nfunc (p *parser) readCategoriesComponent() (component, error) {\n\tas, err := p.readAttributes(languageparam)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tv, err := p.readValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlanguage := \"\"\n\tif l, ok := as[languageparam]; ok {\n\t\tlanguage = l.String()\n\t}\n\treturn categories{\n\t\tlanguage,\n\t\ttextSplit(v),\n\t}, nil\n}\n\nconst (\n\tclassPublic = iota\n\tclassPrivate\n\tclassConfidential\n)\n\ntype class struct {\n\tValue int\n}\n\nfunc (p *parser) readClassComponent() (component, error) {\n\tv, err := p.readValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar cv int\n\tswitch v {\n\tcase \"PUBLIC\":\n\t\tcv = classPublic\n\tcase \"PRIVATE\":\n\t\tcv = classPrivate\n\tcase \"CONFIDENTIAL\":\n\t\tcv = classConfidential\n\tdefault:\n\t\tcv = classPrivate\n\t}\n\treturn class{cv}, nil\n}\n\ntype comment struct {\n\tAltrep, Language string\n}\n\nfunc (p *parser) readCommentComponent() (component, error) {\n\n}\n\ntype unknown struct {\n\tName   string\n\tParams []token\n\tValue  string\n}\n\nfunc (p *parser) readUnknownComponent(name string) (component, error) {\n\tvs, err := p.readAttributes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tv, err := p.readValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn unknown{\n\t\tname,\n\t\tvs,\n\t\tv,\n\t}, err\n}\n\n\/\/ Errors\n\nvar (\n\tErrUnsupportedValue            = errors.New(\"attribute contained unsupported value\")\n\tErrInvalidAttributeCombination = errors.New(\"invalid combination of attributes\")\n)\n<commit_msg>added more component parsing<commit_after>package ics\n\nimport (\n\t\"encoding\/base64\"\n\t\"errors\"\n)\n\nconst (\n\tcalscalec        = \"CALSCALE\"\n\tmethodc          = \"METHOD\"\n\tprodidc          = \"PRODID\"\n\tversionc         = \"VERSION\"\n\tattachc          = \"ATTACH\"\n\tcategoriesc      = \"CATEGORIES\"\n\tclassc           = \"CLASS\"\n\tcommentc         = \"COMMENT\"\n\tdescriptionc     = \"DESCRIPTION\"\n\tgeoc             = \"GEO\"\n\tlocationc        = \"LOCATION\"\n\tpercentcompletec = \"PERCENT-COMPLETE\"\n\tpriorityc        = \"PRIORITY\"\n\tresourcesc       = \"RESOURCES\"\n\tstatusc          = \"STATUS\"\n\tsummaryc         = \"SUMMARY\"\n\tcompletedc       = \"COMPLETED\"\n\tdtendc           = \"DTEND\"\n\tduec             = \"DUE\"\n\tdtstartc         = \"DTSTART\"\n\tdurationc        = \"DURATION\"\n\tfreebusyc        = \"FREEBUSY\"\n\ttranspc          = \"TRANSP\"\n\ttzidc            = \"TZID\"\n\ttznamec          = \"TZNAME\"\n\ttzoffsetfromc    = \"TZOFFSETFROM\"\n\ttzoffsettoc      = \"TZOFFSETTO\"\n\ttzurlc           = \"TZURL\"\n\tattendeec        = \"ATTENDEE\"\n\tcontactc         = \"CONTACT\"\n\torganizerc       = \"ORGANIZER\"\n\trecuridc         = \"RECURRENCE-ID\"\n\trelatedc         = \"RELATED-TO\"\n\turlc             = \"URL\"\n\tuidc             = \"UID\"\n\texdatec          = \"EXDATE\"\n\trdatec           = \"RDATE\"\n\trrulec           = \"RRULE\"\n\tactionc          = \"ACTION\"\n\trepeatc          = \"REPEAT\"\n\ttriggerc         = \"TRIGGER\"\n\tcreatedc         = \"CREATED\"\n\tdtstampc         = \"DTSTAMP\"\n\tlastmodc         = \"LAST-MODIFIED\"\n\tseqc             = \"SEQUENCE\"\n)\n\ntype component interface{}\n\ntype calscale string\n\nfunc (p *parser) readCalScaleComponent() (component, error) {\n\tv, err := p.readValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn calscale(unescape(v)), nil\n}\n\ntype method string\n\nfunc (p *parser) readMethodComponent() (component, error) {\n\tv, err := p.readValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn method(unescape(v)), nil\n}\n\ntype productID string\n\nfunc (p *parser) readProductIDComponent() (component, error) {\n\tv, err := p.readValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn productID(unescape(v)), nil\n}\n\ntype version struct {\n\tMin, Max string\n}\n\nfunc (p *parser) readVersionComponent() (component, error) {\n\tv, err := p.readValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tparts := textSplit(v, ';')\n\tif len(parts) > 2 {\n\t\treturn nil, ErrUnsupportedValue\n\t} else if len(parts) == 2 {\n\t\treturn version{parts[0], parts[1]}, nil\n\t} else {\n\t\treturn version{parts[0], parts[0]}, nil\n\t}\n}\n\ntype attach struct {\n\tURI  bool\n\tMime string\n\tData []byte\n}\n\nfunc (p *parser) readAttachComponent() (component, error) {\n\tas, err := p.readAttributes(fmttypeparam, encodingparam, valuetypeparam)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvalue, err := p.readValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turi := true\n\tenc, encOK := as[encodingparam]\n\tval, valOK := as[valuetypeparam]\n\tvar data []byte\n\tif encOK && valOK {\n\t\turi = false\n\t\tif enc.(encoding) != encodingBase64 || val.(value) != valueBinary {\n\t\t\treturn nil, ErrUnsupportedValue\n\t\t}\n\t\tdata, err = base64.StdEncoding.DecodeString(value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t} else if encOK == valOK {\n\t\tdata = []byte(unescape(value))\n\t} else {\n\t\treturn nil, ErrInvalidAttributeCombination\n\t}\n\treturn attach{\n\t\turi,\n\t\tas[fmttypeparam],\n\t\tdata,\n\t}, nil\n}\n\ntype categories struct {\n\tLanguage   string\n\tCategories []string\n}\n\nfunc (p *parser) readCategoriesComponent() (component, error) {\n\tas, err := p.readAttributes(languageparam)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tv, err := p.readValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlanguage := \"\"\n\tif l, ok := as[languageparam]; ok {\n\t\tlanguage = l.String()\n\t}\n\treturn categories{\n\t\tlanguage,\n\t\ttextSplit(v, ','),\n\t}, nil\n}\n\nconst (\n\tclassPublic = iota\n\tclassPrivate\n\tclassConfidential\n)\n\ntype class struct {\n\tValue int\n}\n\nfunc (p *parser) readClassComponent() (component, error) {\n\tv, err := p.readValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar cv int\n\tswitch v {\n\tcase \"PUBLIC\":\n\t\tcv = classPublic\n\tcase \"PRIVATE\":\n\t\tcv = classPrivate\n\tcase \"CONFIDENTIAL\":\n\t\tcv = classConfidential\n\tdefault:\n\t\tcv = classPrivate\n\t}\n\treturn class{cv}, nil\n}\n\ntype comment struct {\n\tAltrep, Language string\n}\n\nfunc (p *parser) readCommentComponent() (component, error) {\n\n}\n\ntype unknown struct {\n\tName   string\n\tParams []token\n\tValue  string\n}\n\nfunc (p *parser) readUnknownComponent(name string) (component, error) {\n\tvs, err := p.readAttributes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tv, err := p.readValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn unknown{\n\t\tname,\n\t\tvs,\n\t\tv,\n\t}, err\n}\n\n\/\/ Errors\n\nvar (\n\tErrUnsupportedValue            = errors.New(\"attribute contained unsupported value\")\n\tErrInvalidAttributeCombination = errors.New(\"invalid combination of attributes\")\n)\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\npackage grpcgen_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\"\n\t\"net\"\n\t\"runtime\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"google.golang.org\/grpc\"\n\n\t\/\/  To install the xds resolvers and balancers.\n\t_ \"google.golang.org\/grpc\/xds\"\n\n\tnetworking \"istio.io\/api\/networking\/v1alpha3\"\n\t\"istio.io\/istio\/pilot\/pkg\/xds\"\n\t\"istio.io\/istio\/pkg\/config\"\n\t\"istio.io\/istio\/pkg\/config\/protocol\"\n\t\"istio.io\/istio\/pkg\/config\/schema\/collections\"\n\t\"istio.io\/istio\/pkg\/test\/echo\/client\"\n\t\"istio.io\/istio\/pkg\/test\/echo\/common\"\n\t\"istio.io\/istio\/pkg\/test\/echo\/proto\"\n\t\"istio.io\/istio\/pkg\/test\/echo\/server\/endpoint\"\n\t\"istio.io\/istio\/pkg\/test\/util\/retry\"\n)\n\nconst grpcEchoPort = 14058\n\ntype echoCfg struct {\n\tversion   string\n\tnamespace string\n\ttls       bool\n}\n\ntype configGenTest struct {\n\t*testing.T\n\tendpoints []endpoint.Instance\n\tds        *xds.FakeDiscoveryServer\n}\n\n\/\/ newConfigGenTest creates a FakeDiscoveryServer that listens for gRPC on grpcXdsAddr\n\/\/ For each of the given servers, we serve echo (only supporting Echo, no ForwardEcho) and\n\/\/ create a corresponding WorkloadEntry. The WorkloadEntry will have the given format:\n\/\/\n\/\/    meta:\n\/\/      name: echo-{generated portnum}-{server.version}\n\/\/      namespace: {server.namespace or \"default\"}\n\/\/      labels: {\"app\": \"grpc\", \"version\": \"{server.version}\"}\n\/\/    spec:\n\/\/      address: {grpcEchoHost}\n\/\/      ports:\n\/\/        grpc: {generated portnum}\nfunc newConfigGenTest(t *testing.T, discoveryOpts xds.FakeOptions, servers ...echoCfg) *configGenTest {\n\tif runtime.GOOS == \"darwin\" && len(servers) > 1 {\n\t\t\/\/ TODO always skip if this breaks anywhere else\n\t\tt.Skip(\"cannot use 127.0.0.2-255 on OSX without manual setup\")\n\t}\n\n\tcgt := &configGenTest{T: t}\n\twg := sync.WaitGroup{}\n\tfor i, s := range servers {\n\t\thost := fmt.Sprintf(\"127.0.0.%d\", i+1)\n\t\tdiscoveryOpts.Configs = append(discoveryOpts.Configs, makeWE(s, host, grpcEchoPort))\n\t}\n\tdiscoveryOpts.ListenerBuilder = func() (net.Listener, error) {\n\t\treturn net.Listen(\"tcp\", grpcXdsAddr)\n\t}\n\t\/\/ Start XDS server\n\tcgt.ds = xds.NewFakeDiscoveryServer(t, discoveryOpts)\n\tfor i, s := range servers {\n\t\tif s.namespace == \"\" {\n\t\t\ts.namespace = \"default\"\n\t\t}\n\t\t\/\/ TODO this breaks without extra ifonfig aliases on OSX, and probably elsewhere\n\t\thost := fmt.Sprintf(\"127.0.0.%d\", i+1)\n\t\tnodeID := fmt.Sprintf(\"sidecar~%s~echo-%s.%s~cluster.local\", host, s.version, s.namespace)\n\t\tbootstrapBytes, err := bootstrapForTest(nodeID, s.namespace)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tep, err := endpoint.New(endpoint.Config{\n\t\t\tPort: &common.Port{\n\t\t\t\tName:             \"grpc\",\n\t\t\t\tPort:             grpcEchoPort,\n\t\t\t\tProtocol:         protocol.GRPC,\n\t\t\t\tXDSServer:        true,\n\t\t\t\tXDSReadinessTLS:  s.tls,\n\t\t\t\tXDSTestBootstrap: bootstrapBytes,\n\t\t\t},\n\t\t\tListenerIP: host,\n\t\t\tVersion:    s.version,\n\t\t})\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\twg.Add(1)\n\t\tif err := ep.Start(func() {\n\t\t\twg.Done()\n\t\t}); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tcgt.endpoints = append(cgt.endpoints, ep)\n\t\tt.Cleanup(func() {\n\t\t\tif err := ep.Close(); err != nil {\n\t\t\t\tt.Errorf(\"failed to close endpoint %s: %v\", host, err)\n\t\t\t}\n\t\t})\n\t}\n\t\/\/ we know onReady will get called because there are internal timeouts for this\n\twg.Wait()\n\treturn cgt\n}\n\nfunc makeWE(s echoCfg, host string, port int) config.Config {\n\tns := \"default\"\n\tif s.namespace != \"\" {\n\t\tns = s.namespace\n\t}\n\treturn config.Config{\n\t\tMeta: config.Meta{\n\t\t\tName:             fmt.Sprintf(\"echo-%d-%s\", port, s.version),\n\t\t\tNamespace:        ns,\n\t\t\tGroupVersionKind: collections.IstioNetworkingV1Alpha3Workloadentries.Resource().GroupVersionKind(),\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\":     \"echo\",\n\t\t\t\t\"version\": s.version,\n\t\t\t},\n\t\t},\n\t\tSpec: &networking.WorkloadEntry{\n\t\t\tAddress: host,\n\t\t\tPorts:   map[string]uint32{\"grpc\": uint32(port)},\n\t\t},\n\t}\n}\n\nfunc (t *configGenTest) dialEcho(addr string) *client.Instance {\n\tresolver := resolverForTest(t, \"default\")\n\tout, err := client.New(addr, nil, grpc.WithResolvers(resolver))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn out\n}\n\nfunc TestTrafficShifting(t *testing.T) {\n\ttt := newConfigGenTest(t, xds.FakeOptions{\n\t\tKubernetesObjectString: `\napiVersion: v1\nkind: Service\nmetadata:\n  labels:\n    app: echo-app\n  name: echo-app\n  namespace: default\nspec:\n  clusterIP: 1.2.3.4\n  selector:\n    app: echo\n  ports:\n  - name: grpc\n    targetPort: grpc\n    port: 7070\n`,\n\t\tConfigString: `\napiVersion: networking.istio.io\/v1alpha3\nkind: DestinationRule\nmetadata:\n  name: echo-dr\n  namespace: default\nspec:\n  host: echo-app.default.svc.cluster.local\n  subsets:\n    - name: v1\n      labels:\n        version: v1\n    - name: v2\n      labels:\n        version: v2\n---\napiVersion: networking.istio.io\/v1alpha3\nkind: VirtualService\nmetadata:\n  name: echo-vs\n  namespace: default\nspec:\n  hosts:\n  - echo-app.default.svc.cluster.local\n  http:\n  - route:\n    - destination:\n        host: echo-app.default.svc.cluster.local\n        subset: v1\n      weight: 20\n    - destination:\n        host: echo-app.default.svc.cluster.local\n        subset: v2\n      weight: 80\n\n`,\n\t}, echoCfg{version: \"v1\"}, echoCfg{version: \"v2\"})\n\n\tretry.UntilSuccessOrFail(tt.T, func() error {\n\t\tcw := tt.dialEcho(\"xds:\/\/\/echo-app.default.svc.cluster.local:7070\")\n\t\tdistribution := map[string]int{}\n\t\tfor i := 0; i < 100; i++ {\n\t\t\tres, err := cw.Echo(context.Background(), &proto.EchoRequest{Message: \"needle\"})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdistribution[res.Version]++\n\t\t}\n\n\t\tif err := expectAlmost(distribution[\"v1\"], 20); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := expectAlmost(distribution[\"v2\"], 80); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}, retry.Timeout(5*time.Second), retry.Delay(0))\n}\n\nfunc TestMtls(t *testing.T) {\n\ttt := newConfigGenTest(t, xds.FakeOptions{\n\t\tKubernetesObjectString: `\napiVersion: v1\nkind: Service\nmetadata:\n  labels:\n    app: echo-app\n  name: echo-app\n  namespace: default\nspec:\n  clusterIP: 1.2.3.4\n  selector:\n    app: echo\n  ports:\n  - name: grpc\n    targetPort: grpc\n    port: 7070\n`,\n\t\tConfigString: `\napiVersion: networking.istio.io\/v1alpha3\nkind: DestinationRule\nmetadata:\n  name: echo-dr\n  namespace: default\nspec:\n  host: echo-app.default.svc.cluster.local\n  trafficPolicy:\n    tls:\n      mode: ISTIO_MUTUAL\n---\napiVersion: security.istio.io\/v1beta1\nkind: PeerAuthentication\nmetadata:\n  name: default\n  namespace: default\nspec:\n  mtls:\n    mode: STRICT\n`,\n\t}, echoCfg{version: \"v1\", tls: true})\n\n\t\/\/ ensure we can make 10 consecutive successful requests\n\tretry.UntilSuccessOrFail(tt.T, func() error {\n\t\tcw := tt.dialEcho(\"xds:\/\/\/echo-app.default.svc.cluster.local:7070\")\n\t\tfor i := 0; i < 10; i++ {\n\t\t\t_, err := cw.Echo(context.Background(), &proto.EchoRequest{Message: \"needle\"})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}, retry.Timeout(5*time.Second), retry.Delay(0))\n}\n\nfunc TestFault(t *testing.T) {\n\ttt := newConfigGenTest(t, xds.FakeOptions{\n\t\tKubernetesObjectString: `\napiVersion: v1\nkind: Service\nmetadata:\n  labels:\n    app: echo-app\n  name: echo-app\n  namespace: default\nspec:\n  clusterIP: 1.2.3.4\n  selector:\n    app: echo\n  ports:\n  - name: grpc\n    targetPort: grpc\n    port: 7070\n`,\n\t\tConfigString: `\napiVersion: networking.istio.io\/v1alpha3\nkind: VirtualService\nmetadata:\n  name: echo-delay\nspec:\n  hosts:\n  - echo-app.default.svc.cluster.local\n  http:\n  - fault:\n      delay:\n        percent: 100\n        fixedDelay: 100ms\n    route:\n    - destination:\n        host: echo-app.default.svc.cluster.local\n`,\n\t}, echoCfg{version: \"v1\"})\n\tc := tt.dialEcho(\"xds:\/\/\/echo-app.default.svc.cluster.local:7070\")\n\n\t\/\/ without a delay it usually takes ~500us\n\tst := time.Now()\n\t_, err := c.Echo(context.Background(), &proto.EchoRequest{})\n\tduration := time.Since(st)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif duration < time.Millisecond*100 {\n\t\tt.Fatalf(\"expected to take over 1s but took %v\", duration)\n\t}\n\n\t\/\/ TODO test timeouts, aborts\n}\n\nfunc expectAlmost(got, want int) error {\n\tif math.Abs(float64(want-got)) > 10 {\n\t\treturn fmt.Errorf(\"expected within %d of %d but got %d\", 10, want, got)\n\t}\n\treturn nil\n}\n<commit_msg>fix grpcgen tests (#36862)<commit_after>\/\/ Copyright Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\npackage grpcgen_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\"\n\t\"net\"\n\t\"runtime\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"google.golang.org\/grpc\"\n\n\t\/\/  To install the xds resolvers and balancers.\n\t_ \"google.golang.org\/grpc\/xds\"\n\n\tnetworking \"istio.io\/api\/networking\/v1alpha3\"\n\t\"istio.io\/istio\/pilot\/pkg\/xds\"\n\t\"istio.io\/istio\/pkg\/config\"\n\t\"istio.io\/istio\/pkg\/config\/protocol\"\n\t\"istio.io\/istio\/pkg\/config\/schema\/collections\"\n\t\"istio.io\/istio\/pkg\/test\/echo\/client\"\n\t\"istio.io\/istio\/pkg\/test\/echo\/common\"\n\t\"istio.io\/istio\/pkg\/test\/echo\/proto\"\n\t\"istio.io\/istio\/pkg\/test\/echo\/server\/endpoint\"\n\t\"istio.io\/istio\/pkg\/test\/util\/retry\"\n)\n\nconst grpcEchoPort = 14058\n\ntype echoCfg struct {\n\tversion   string\n\tnamespace string\n\ttls       bool\n}\n\ntype configGenTest struct {\n\t*testing.T\n\tendpoints []endpoint.Instance\n\tds        *xds.FakeDiscoveryServer\n}\n\n\/\/ newConfigGenTest creates a FakeDiscoveryServer that listens for gRPC on grpcXdsAddr\n\/\/ For each of the given servers, we serve echo (only supporting Echo, no ForwardEcho) and\n\/\/ create a corresponding WorkloadEntry. The WorkloadEntry will have the given format:\n\/\/\n\/\/    meta:\n\/\/      name: echo-{generated portnum}-{server.version}\n\/\/      namespace: {server.namespace or \"default\"}\n\/\/      labels: {\"app\": \"grpc\", \"version\": \"{server.version}\"}\n\/\/    spec:\n\/\/      address: {grpcEchoHost}\n\/\/      ports:\n\/\/        grpc: {generated portnum}\nfunc newConfigGenTest(t *testing.T, discoveryOpts xds.FakeOptions, servers ...echoCfg) *configGenTest {\n\tif runtime.GOOS == \"darwin\" && len(servers) > 1 {\n\t\t\/\/ TODO always skip if this breaks anywhere else\n\t\tt.Skip(\"cannot use 127.0.0.2-255 on OSX without manual setup\")\n\t}\n\n\tcgt := &configGenTest{T: t}\n\twg := sync.WaitGroup{}\n\tfor i, s := range servers {\n\t\thost := fmt.Sprintf(\"127.0.0.%d\", i+1)\n\t\tdiscoveryOpts.Configs = append(discoveryOpts.Configs, makeWE(s, host, grpcEchoPort))\n\t}\n\tdiscoveryOpts.ListenerBuilder = func() (net.Listener, error) {\n\t\treturn net.Listen(\"tcp\", grpcXdsAddr)\n\t}\n\t\/\/ Start XDS server\n\tcgt.ds = xds.NewFakeDiscoveryServer(t, discoveryOpts)\n\tfor i, s := range servers {\n\t\tif s.namespace == \"\" {\n\t\t\ts.namespace = \"default\"\n\t\t}\n\t\t\/\/ TODO this breaks without extra ifonfig aliases on OSX, and probably elsewhere\n\t\thost := fmt.Sprintf(\"127.0.0.%d\", i+1)\n\t\tnodeID := fmt.Sprintf(\"sidecar~%s~echo-%s.%s~cluster.local\", host, s.version, s.namespace)\n\t\tbootstrapBytes, err := bootstrapForTest(nodeID, s.namespace)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tep, err := endpoint.New(endpoint.Config{\n\t\t\tPort: &common.Port{\n\t\t\t\tName:             \"grpc\",\n\t\t\t\tPort:             grpcEchoPort,\n\t\t\t\tProtocol:         protocol.GRPC,\n\t\t\t\tXDSServer:        true,\n\t\t\t\tXDSReadinessTLS:  s.tls,\n\t\t\t\tXDSTestBootstrap: bootstrapBytes,\n\t\t\t},\n\t\t\tListenerIP: host,\n\t\t\tVersion:    s.version,\n\t\t})\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\twg.Add(1)\n\t\tif err := ep.Start(func() {\n\t\t\twg.Done()\n\t\t}); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tcgt.endpoints = append(cgt.endpoints, ep)\n\t\tt.Cleanup(func() {\n\t\t\tif err := ep.Close(); err != nil {\n\t\t\t\tt.Errorf(\"failed to close endpoint %s: %v\", host, err)\n\t\t\t}\n\t\t})\n\t}\n\t\/\/ we know onReady will get called because there are internal timeouts for this\n\twg.Wait()\n\treturn cgt\n}\n\nfunc makeWE(s echoCfg, host string, port int) config.Config {\n\tns := \"default\"\n\tif s.namespace != \"\" {\n\t\tns = s.namespace\n\t}\n\treturn config.Config{\n\t\tMeta: config.Meta{\n\t\t\tName:             fmt.Sprintf(\"echo-%d-%s\", port, s.version),\n\t\t\tNamespace:        ns,\n\t\t\tGroupVersionKind: collections.IstioNetworkingV1Alpha3Workloadentries.Resource().GroupVersionKind(),\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\":     \"echo\",\n\t\t\t\t\"version\": s.version,\n\t\t\t},\n\t\t},\n\t\tSpec: &networking.WorkloadEntry{\n\t\t\tAddress: host,\n\t\t\tPorts:   map[string]uint32{\"grpc\": uint32(port)},\n\t\t},\n\t}\n}\n\nfunc (t *configGenTest) dialEcho(addr string) *client.Instance {\n\tresolver := resolverForTest(t, \"default\")\n\tout, err := client.New(addr, nil, grpc.WithResolvers(resolver))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn out\n}\n\nfunc TestTrafficShifting(t *testing.T) {\n\ttt := newConfigGenTest(t, xds.FakeOptions{\n\t\tKubernetesObjectString: `\napiVersion: v1\nkind: Service\nmetadata:\n  labels:\n    app: echo-app\n  name: echo-app\n  namespace: default\nspec:\n  clusterIP: 1.2.3.4\n  selector:\n    app: echo\n  ports:\n  - name: grpc\n    targetPort: grpc\n    port: 7070\n`,\n\t\tConfigString: `\napiVersion: networking.istio.io\/v1alpha3\nkind: DestinationRule\nmetadata:\n  name: echo-dr\n  namespace: default\nspec:\n  host: echo-app.default.svc.cluster.local\n  subsets:\n    - name: v1\n      labels:\n        version: v1\n    - name: v2\n      labels:\n        version: v2\n---\napiVersion: networking.istio.io\/v1alpha3\nkind: VirtualService\nmetadata:\n  name: echo-vs\n  namespace: default\nspec:\n  hosts:\n  - echo-app.default.svc.cluster.local\n  http:\n  - route:\n    - destination:\n        host: echo-app.default.svc.cluster.local\n        subset: v1\n      weight: 20\n    - destination:\n        host: echo-app.default.svc.cluster.local\n        subset: v2\n      weight: 80\n\n`,\n\t}, echoCfg{version: \"v1\"}, echoCfg{version: \"v2\"})\n\n\tretry.UntilSuccessOrFail(tt.T, func() error {\n\t\tcw := tt.dialEcho(\"xds:\/\/\/echo-app.default.svc.cluster.local:7070\")\n\t\tdistribution := map[string]int{}\n\t\tfor i := 0; i < 100; i++ {\n\t\t\tres, err := cw.Echo(context.Background(), &proto.EchoRequest{Message: \"needle\"})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdistribution[res.Version]++\n\t\t}\n\n\t\tif err := expectAlmost(distribution[\"v1\"], 20); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := expectAlmost(distribution[\"v2\"], 80); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}, retry.Timeout(5*time.Second), retry.Delay(0))\n}\n\nfunc TestMtls(t *testing.T) {\n\ttt := newConfigGenTest(t, xds.FakeOptions{\n\t\tKubernetesObjectString: `\napiVersion: v1\nkind: Service\nmetadata:\n  labels:\n    app: echo-app\n  name: echo-app\n  namespace: default\nspec:\n  clusterIP: 1.2.3.4\n  selector:\n    app: echo\n  ports:\n  - name: grpc\n    targetPort: grpc\n    port: 7070\n`,\n\t\tConfigString: `\napiVersion: networking.istio.io\/v1alpha3\nkind: DestinationRule\nmetadata:\n  name: echo-dr\n  namespace: default\nspec:\n  host: echo-app.default.svc.cluster.local\n  trafficPolicy:\n    tls:\n      mode: ISTIO_MUTUAL\n---\napiVersion: security.istio.io\/v1beta1\nkind: PeerAuthentication\nmetadata:\n  name: default\n  namespace: default\nspec:\n  mtls:\n    mode: STRICT\n`,\n\t}, echoCfg{version: \"v1\", tls: true})\n\n\t\/\/ ensure we can make 10 consecutive successful requests\n\tretry.UntilSuccessOrFail(tt.T, func() error {\n\t\tcw := tt.dialEcho(\"xds:\/\/\/echo-app.default.svc.cluster.local:7070\")\n\t\tfor i := 0; i < 10; i++ {\n\t\t\t_, err := cw.Echo(context.Background(), &proto.EchoRequest{Message: \"needle\"})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}, retry.Timeout(5*time.Second), retry.Delay(0))\n}\n\nfunc TestFault(t *testing.T) {\n\ttt := newConfigGenTest(t, xds.FakeOptions{\n\t\tKubernetesObjectString: `\napiVersion: v1\nkind: Service\nmetadata:\n  labels:\n    app: echo-app\n  name: echo-app\n  namespace: default\nspec:\n  clusterIP: 1.2.3.4\n  selector:\n    app: echo\n  ports:\n  - name: grpc\n    targetPort: grpc\n    port: 7071\n`,\n\t\tConfigString: `\napiVersion: networking.istio.io\/v1alpha3\nkind: VirtualService\nmetadata:\n  name: echo-delay\nspec:\n  hosts:\n  - echo-app.default.svc.cluster.local\n  http:\n  - fault:\n      delay:\n        percent: 100\n        fixedDelay: 100ms\n    route:\n    - destination:\n        host: echo-app.default.svc.cluster.local\n`,\n\t}, echoCfg{version: \"v1\"})\n\tc := tt.dialEcho(\"xds:\/\/\/echo-app.default.svc.cluster.local:7071\")\n\n\t\/\/ without a delay it usually takes ~500us\n\tst := time.Now()\n\t_, err := c.Echo(context.Background(), &proto.EchoRequest{})\n\tduration := time.Since(st)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif duration < time.Millisecond*100 {\n\t\tt.Fatalf(\"expected to take over 1s but took %v\", duration)\n\t}\n\n\t\/\/ TODO test timeouts, aborts\n}\n\nfunc expectAlmost(got, want int) error {\n\tif math.Abs(float64(want-got)) > 10 {\n\t\treturn fmt.Errorf(\"expected within %d of %d but got %d\", 10, want, got)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2011 Google Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ Package cloudstorage registers the \"googlecloudstorage\" blob storage type, storing blobs\n\/\/ on Google Cloud Storage (not Google Drive).\n\/\/ See https:\/\/cloud.google.com\/products\/cloud-storage\npackage cloudstorage\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha1\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"time\"\n\n\t\"camlistore.org\/pkg\/blob\"\n\t\"camlistore.org\/pkg\/blobserver\"\n\t\"camlistore.org\/pkg\/constants\"\n\t\"camlistore.org\/pkg\/context\"\n\t\"camlistore.org\/pkg\/googlestorage\"\n\t\"camlistore.org\/pkg\/jsonconfig\"\n\t\"camlistore.org\/pkg\/syncutil\"\n)\n\ntype Storage struct {\n\tbucket string \/\/ the gs bucket containing blobs\n\tclient *googlestorage.Client\n\n\t\/\/ For blobserver.Generationer:\n\tgenTime   time.Time\n\tgenRandom string\n}\n\nvar (\n\t_ blobserver.MaxEnumerateConfig = (*Storage)(nil)\n\t_ blobserver.Generationer       = (*Storage)(nil)\n)\n\nfunc (gs *Storage) MaxEnumerate() int { return 1000 }\n\nfunc (gs *Storage) StorageGeneration() (time.Time, string, error) {\n\treturn gs.genTime, gs.genRandom, nil\n}\nfunc (gs *Storage) ResetStorageGeneration() error { return errors.New(\"not supported\") }\n\nfunc newFromConfig(_ blobserver.Loader, config jsonconfig.Obj) (blobserver.Storage, error) {\n\tvar (\n\t\tauth   = config.RequiredObject(\"auth\")\n\t\tbucket = config.RequiredString(\"bucket\")\n\n\t\tclientID     = auth.RequiredString(\"client_id\") \/\/ or \"auto\" for service accounts\n\t\tclientSecret = auth.OptionalString(\"client_secret\", \"\")\n\t\trefreshToken = auth.OptionalString(\"refresh_token\", \"\")\n\t)\n\n\tif err := config.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := auth.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgs := &Storage{bucket: bucket}\n\tif clientID == \"auto\" {\n\t\tvar err error\n\t\tgs.client, err = googlestorage.NewServiceClient()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tif clientSecret == \"\" {\n\t\t\treturn nil, errors.New(\"missing required parameter 'client_secret'\")\n\t\t}\n\t\tif refreshToken == \"\" {\n\t\t\treturn nil, errors.New(\"missing required parameter 'refresh_token'\")\n\t\t}\n\t\tgs.client = googlestorage.NewClient(googlestorage.MakeOauthTransport(\n\t\t\tclientID, clientSecret, refreshToken))\n\t}\n\n\tbi, err := gs.client.BucketInfo(bucket)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error statting bucket %q: %v\", bucket, err)\n\t}\n\thash := sha1.New()\n\tfmt.Fprintf(hash, \"%v%v\", bi.TimeCreated, bi.Metageneration)\n\tgs.genRandom = fmt.Sprintf(\"%x\", hash.Sum(nil))\n\tgs.genTime, _ = time.Parse(time.RFC3339, bi.TimeCreated)\n\n\treturn gs, nil\n}\n\nfunc (gs *Storage) EnumerateBlobs(ctx *context.Context, dest chan<- blob.SizedRef, after string, limit int) error {\n\tdefer close(dest)\n\tobjs, err := gs.client.EnumerateObjects(gs.bucket, after, limit)\n\tif err != nil {\n\t\tlog.Printf(\"gstorage EnumerateObjects: %v\", err)\n\t\treturn err\n\t}\n\tfor _, obj := range objs {\n\t\tbr, ok := blob.Parse(obj.Key)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Non-Camlistore object named %q found in bucket\", obj.Key)\n\t\t}\n\t\tselect {\n\t\tcase dest <- blob.SizedRef{Ref: br, Size: uint32(obj.Size)}:\n\t\tcase <-ctx.Done():\n\t\t\treturn context.ErrCanceled\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (gs *Storage) ReceiveBlob(br blob.Ref, source io.Reader) (blob.SizedRef, error) {\n\tbuf := &bytes.Buffer{}\n\tsize, err := io.Copy(buf, source)\n\tif err != nil {\n\t\treturn blob.SizedRef{}, err\n\t}\n\n\tfor tries, shouldRetry := 0, true; tries < 2 && shouldRetry; tries++ {\n\t\tshouldRetry, err = gs.client.PutObject(\n\t\t\t&googlestorage.Object{Bucket: gs.bucket, Key: br.String()},\n\t\t\tioutil.NopCloser(bytes.NewReader(buf.Bytes())))\n\t}\n\tif err != nil {\n\t\treturn blob.SizedRef{}, err\n\t}\n\n\treturn blob.SizedRef{Ref: br, Size: uint32(size)}, nil\n}\n\nfunc (gs *Storage) StatBlobs(dest chan<- blob.SizedRef, blobs []blob.Ref) error {\n\tvar grp syncutil.Group\n\tgate := syncutil.NewGate(20) \/\/ arbitrary cap\n\tfor i := range blobs {\n\t\tbr := blobs[i]\n\t\tgate.Start()\n\t\tgrp.Go(func() error {\n\t\t\tdefer gate.Done()\n\t\t\tsize, exists, err := gs.client.StatObject(\n\t\t\t\t&googlestorage.Object{Bucket: gs.bucket, Key: br.String()})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif size > constants.MaxBlobSize {\n\t\t\t\treturn fmt.Errorf(\"blob %s stat size too large (%d)\", br, size)\n\t\t\t}\n\t\t\tdest <- blob.SizedRef{Ref: br, Size: uint32(size)}\n\t\t\treturn nil\n\t\t})\n\t}\n\treturn grp.Err()\n}\n\nfunc (gs *Storage) Fetch(blob blob.Ref) (file io.ReadCloser, size uint32, err error) {\n\tfile, sz, err := gs.client.GetObject(&googlestorage.Object{Bucket: gs.bucket, Key: blob.String()})\n\tif err != nil && sz > constants.MaxBlobSize {\n\t\terr = errors.New(\"object too big\")\n\t}\n\treturn file, uint32(sz), err\n\n}\n\nfunc (gs *Storage) RemoveBlobs(blobs []blob.Ref) error {\n\tvar reterr error\n\t\/\/ TODO: do a batch API call, or at least keep N of these in flight at a time. No need to do them all serially.\n\tfor _, br := range blobs {\n\t\terr := gs.client.DeleteObject(&googlestorage.Object{Bucket: gs.bucket, Key: br.String()})\n\t\tif err != nil {\n\t\t\treterr = err\n\t\t}\n\t}\n\treturn reterr\n}\n\nfunc init() {\n\tblobserver.RegisterStorageConstructor(\"googlecloudstorage\", blobserver.StorageConstructor(newFromConfig))\n}\n<commit_msg>Google cloud storage: delete objects in a batch<commit_after>\/*\nCopyright 2011 Google Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ Package cloudstorage registers the \"googlecloudstorage\" blob storage type, storing blobs\n\/\/ on Google Cloud Storage (not Google Drive).\n\/\/ See https:\/\/cloud.google.com\/products\/cloud-storage\npackage cloudstorage\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha1\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"time\"\n\n\t\"camlistore.org\/pkg\/blob\"\n\t\"camlistore.org\/pkg\/blobserver\"\n\t\"camlistore.org\/pkg\/constants\"\n\t\"camlistore.org\/pkg\/context\"\n\t\"camlistore.org\/pkg\/googlestorage\"\n\t\"camlistore.org\/pkg\/jsonconfig\"\n\t\"camlistore.org\/pkg\/syncutil\"\n)\n\ntype Storage struct {\n\tbucket string \/\/ the gs bucket containing blobs\n\tclient *googlestorage.Client\n\n\t\/\/ For blobserver.Generationer:\n\tgenTime   time.Time\n\tgenRandom string\n}\n\nvar (\n\t_ blobserver.MaxEnumerateConfig = (*Storage)(nil)\n\t_ blobserver.Generationer       = (*Storage)(nil)\n)\n\nfunc (gs *Storage) MaxEnumerate() int { return 1000 }\n\nfunc (gs *Storage) StorageGeneration() (time.Time, string, error) {\n\treturn gs.genTime, gs.genRandom, nil\n}\nfunc (gs *Storage) ResetStorageGeneration() error { return errors.New(\"not supported\") }\n\nfunc newFromConfig(_ blobserver.Loader, config jsonconfig.Obj) (blobserver.Storage, error) {\n\tvar (\n\t\tauth   = config.RequiredObject(\"auth\")\n\t\tbucket = config.RequiredString(\"bucket\")\n\n\t\tclientID     = auth.RequiredString(\"client_id\") \/\/ or \"auto\" for service accounts\n\t\tclientSecret = auth.OptionalString(\"client_secret\", \"\")\n\t\trefreshToken = auth.OptionalString(\"refresh_token\", \"\")\n\t)\n\n\tif err := config.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := auth.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tgs := &Storage{bucket: bucket}\n\tif clientID == \"auto\" {\n\t\tvar err error\n\t\tgs.client, err = googlestorage.NewServiceClient()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tif clientSecret == \"\" {\n\t\t\treturn nil, errors.New(\"missing required parameter 'client_secret'\")\n\t\t}\n\t\tif refreshToken == \"\" {\n\t\t\treturn nil, errors.New(\"missing required parameter 'refresh_token'\")\n\t\t}\n\t\tgs.client = googlestorage.NewClient(googlestorage.MakeOauthTransport(\n\t\t\tclientID, clientSecret, refreshToken))\n\t}\n\n\tbi, err := gs.client.BucketInfo(bucket)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error statting bucket %q: %v\", bucket, err)\n\t}\n\thash := sha1.New()\n\tfmt.Fprintf(hash, \"%v%v\", bi.TimeCreated, bi.Metageneration)\n\tgs.genRandom = fmt.Sprintf(\"%x\", hash.Sum(nil))\n\tgs.genTime, _ = time.Parse(time.RFC3339, bi.TimeCreated)\n\n\treturn gs, nil\n}\n\nfunc (gs *Storage) EnumerateBlobs(ctx *context.Context, dest chan<- blob.SizedRef, after string, limit int) error {\n\tdefer close(dest)\n\tobjs, err := gs.client.EnumerateObjects(gs.bucket, after, limit)\n\tif err != nil {\n\t\tlog.Printf(\"gstorage EnumerateObjects: %v\", err)\n\t\treturn err\n\t}\n\tfor _, obj := range objs {\n\t\tbr, ok := blob.Parse(obj.Key)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Non-Camlistore object named %q found in bucket\", obj.Key)\n\t\t}\n\t\tselect {\n\t\tcase dest <- blob.SizedRef{Ref: br, Size: uint32(obj.Size)}:\n\t\tcase <-ctx.Done():\n\t\t\treturn context.ErrCanceled\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (gs *Storage) ReceiveBlob(br blob.Ref, source io.Reader) (blob.SizedRef, error) {\n\tbuf := &bytes.Buffer{}\n\tsize, err := io.Copy(buf, source)\n\tif err != nil {\n\t\treturn blob.SizedRef{}, err\n\t}\n\n\tfor tries, shouldRetry := 0, true; tries < 2 && shouldRetry; tries++ {\n\t\tshouldRetry, err = gs.client.PutObject(\n\t\t\t&googlestorage.Object{Bucket: gs.bucket, Key: br.String()},\n\t\t\tioutil.NopCloser(bytes.NewReader(buf.Bytes())))\n\t}\n\tif err != nil {\n\t\treturn blob.SizedRef{}, err\n\t}\n\n\treturn blob.SizedRef{Ref: br, Size: uint32(size)}, nil\n}\n\nfunc (gs *Storage) StatBlobs(dest chan<- blob.SizedRef, blobs []blob.Ref) error {\n\tvar grp syncutil.Group\n\tgate := syncutil.NewGate(20) \/\/ arbitrary cap\n\tfor i := range blobs {\n\t\tbr := blobs[i]\n\t\tgate.Start()\n\t\tgrp.Go(func() error {\n\t\t\tdefer gate.Done()\n\t\t\tsize, exists, err := gs.client.StatObject(\n\t\t\t\t&googlestorage.Object{Bucket: gs.bucket, Key: br.String()})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !exists {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif size > constants.MaxBlobSize {\n\t\t\t\treturn fmt.Errorf(\"blob %s stat size too large (%d)\", br, size)\n\t\t\t}\n\t\t\tdest <- blob.SizedRef{Ref: br, Size: uint32(size)}\n\t\t\treturn nil\n\t\t})\n\t}\n\treturn grp.Err()\n}\n\nfunc (gs *Storage) Fetch(blob blob.Ref) (file io.ReadCloser, size uint32, err error) {\n\tfile, sz, err := gs.client.GetObject(&googlestorage.Object{Bucket: gs.bucket, Key: blob.String()})\n\tif err != nil && sz > constants.MaxBlobSize {\n\t\terr = errors.New(\"object too big\")\n\t}\n\treturn file, uint32(sz), err\n\n}\n\nfunc (gs *Storage) RemoveBlobs(blobs []blob.Ref) error {\n\tgate := syncutil.NewGate(50) \/\/ arbitrary\n\tvar grp syncutil.Group\n\tfor i := range blobs {\n\t\tgate.Start()\n\t\tbr := blobs[i]\n\t\tgrp.Go(func() error {\n\t\t\tdefer gate.Done()\n\t\t\treturn gs.client.DeleteObject(&googlestorage.Object{Bucket: gs.bucket, Key: br.String()})\n\t\t})\n\t}\n\treturn grp.Err()\n}\n\nfunc init() {\n\tblobserver.RegisterStorageConstructor(\"googlecloudstorage\", blobserver.StorageConstructor(newFromConfig))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2014 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage credentials\n\nimport (\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/request\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ecr\"\n\t\"github.com\/golang\/glog\"\n\t\"k8s.io\/kubernetes\/pkg\/credentialprovider\"\n)\n\n\/\/ AWSRegions is the complete list of regions known to the AWS cloudprovider\n\/\/ and credentialprovider.\nvar AWSRegions = [...]string{\n\t\"us-east-1\",\n\t\"us-west-1\",\n\t\"us-west-2\",\n\t\"eu-west-1\",\n\t\"eu-central-1\",\n\t\"ap-southeast-1\",\n\t\"ap-southeast-2\",\n\t\"ap-northeast-1\",\n\t\"ap-northeast-2\",\n\t\"cn-north-1\",\n\t\"us-gov-west-1\",\n\t\"sa-east-1\",\n}\n\nconst registryURLTemplate = \"*.dkr.ecr.%s.amazonaws.com\"\n\n\/\/ awsHandlerLogger is a handler that logs all AWS SDK requests\n\/\/ Copied from cloudprovider\/aws\/log_handler.go\nfunc awsHandlerLogger(req *request.Request) {\n\tservice := req.ClientInfo.ServiceName\n\tregion := req.Config.Region\n\n\tname := \"?\"\n\tif req.Operation != nil {\n\t\tname = req.Operation.Name\n\t}\n\n\tglog.V(3).Infof(\"AWS request: %s:%s in %s\", service, name, *region)\n}\n\n\/\/ An interface for testing purposes.\ntype tokenGetter interface {\n\tGetAuthorizationToken(input *ecr.GetAuthorizationTokenInput) (*ecr.GetAuthorizationTokenOutput, error)\n}\n\n\/\/ The canonical implementation\ntype ecrTokenGetter struct {\n\tsvc *ecr.ECR\n}\n\nfunc (p *ecrTokenGetter) GetAuthorizationToken(input *ecr.GetAuthorizationTokenInput) (*ecr.GetAuthorizationTokenOutput, error) {\n\treturn p.svc.GetAuthorizationToken(input)\n}\n\n\/\/ lazyEcrProvider is a DockerConfigProvider that creates on demand an\n\/\/ ecrProvider for a given region and then proxies requests to it.\ntype lazyEcrProvider struct {\n\tregion         string\n\tregionURL      string\n\tactualProvider *credentialprovider.CachingDockerConfigProvider\n}\n\nvar _ credentialprovider.DockerConfigProvider = &lazyEcrProvider{}\n\n\/\/ ecrProvider is a DockerConfigProvider that gets and refreshes 12-hour tokens\n\/\/ from AWS to access ECR.\ntype ecrProvider struct {\n\tregion    string\n\tregionURL string\n\tgetter    tokenGetter\n}\n\nvar _ credentialprovider.DockerConfigProvider = &ecrProvider{}\n\n\/\/ Init creates a lazy provider for each AWS region, in order to support\n\/\/ cross-region ECR access. They have to be lazy because it's unlikely, but not\n\/\/ impossible, that we'll use more than one.\n\/\/ Not using the package init() function: this module should be initialized only\n\/\/ if using the AWS cloud provider. This way, we avoid timeouts waiting for a\n\/\/ non-existent provider.\nfunc Init() {\n\tfor _, region := range AWSRegions {\n\t\tcredentialprovider.RegisterCredentialProvider(\"aws-ecr-\"+region,\n\t\t\t&lazyEcrProvider{\n\t\t\t\tregion:    region,\n\t\t\t\tregionURL: fmt.Sprintf(registryURLTemplate, region),\n\t\t\t})\n\t}\n\n}\n\n\/\/ Enabled implements DockerConfigProvider.Enabled for the lazy provider.\n\/\/ Since we perform no checks\/work of our own and actualProvider is only created\n\/\/ later at image pulling time (if ever), always return true.\nfunc (p *lazyEcrProvider) Enabled() bool {\n\treturn true\n}\n\n\/\/ LazyProvide implements DockerConfigProvider.LazyProvide. It will be called\n\/\/ by the client when attempting to pull an image and it will create the actual\n\/\/ provider only when we actually need it the first time.\nfunc (p *lazyEcrProvider) LazyProvide() *credentialprovider.DockerConfigEntry {\n\tif p.actualProvider == nil {\n\t\tglog.V(2).Infof(\"Creating ecrProvider for %s\", p.region)\n\t\tp.actualProvider = &credentialprovider.CachingDockerConfigProvider{\n\t\t\tProvider: newEcrProvider(p.region, nil),\n\t\t\t\/\/ Refresh credentials a little earlier than expiration time\n\t\t\tLifetime: 11*time.Hour + 55*time.Minute,\n\t\t}\n\t\tif !p.actualProvider.Enabled() {\n\t\t\treturn nil\n\t\t}\n\t}\n\tentry := p.actualProvider.Provide()[p.regionURL]\n\treturn &entry\n}\n\n\/\/ Provide implements DockerConfigProvider.Provide, creating dummy credentials.\n\/\/ Client code will call Provider.LazyProvide() at image pulling time.\nfunc (p *lazyEcrProvider) Provide() credentialprovider.DockerConfig {\n\tentry := credentialprovider.DockerConfigEntry{\n\t\tProvider: p,\n\t}\n\tcfg := credentialprovider.DockerConfig{}\n\tcfg[p.regionURL] = entry\n\treturn cfg\n}\n\nfunc newEcrProvider(region string, getter tokenGetter) *ecrProvider {\n\treturn &ecrProvider{\n\t\tregion:    region,\n\t\tregionURL: fmt.Sprintf(registryURLTemplate, region),\n\t\tgetter:    getter,\n\t}\n}\n\n\/\/ Enabled implements DockerConfigProvider.Enabled for the AWS token-based implementation.\n\/\/ For now, it gets activated only if AWS was chosen as the cloud provider.\n\/\/ TODO: figure how to enable it manually for deployments that are not on AWS but still\n\/\/ use ECR somehow?\nfunc (p *ecrProvider) Enabled() bool {\n\tif p.region == \"\" {\n\t\tglog.Errorf(\"Called ecrProvider.Enabled() with no region set\")\n\t\treturn false\n\t}\n\n\tgetter := &ecrTokenGetter{svc: ecr.New(session.New(&aws.Config{\n\t\tCredentials: nil,\n\t\tRegion:      &p.region,\n\t}))}\n\tgetter.svc.Handlers.Sign.PushFrontNamed(request.NamedHandler{\n\t\tName: \"k8s\/logger\",\n\t\tFn:   awsHandlerLogger,\n\t})\n\tp.getter = getter\n\n\treturn true\n}\n\n\/\/ LazyProvide implements DockerConfigProvider.LazyProvide. Should never be called.\nfunc (p *ecrProvider) LazyProvide() *credentialprovider.DockerConfigEntry {\n\treturn nil\n}\n\n\/\/ Provide implements DockerConfigProvider.Provide, refreshing ECR tokens on demand\nfunc (p *ecrProvider) Provide() credentialprovider.DockerConfig {\n\tcfg := credentialprovider.DockerConfig{}\n\n\t\/\/ TODO: fill in RegistryIds?\n\tparams := &ecr.GetAuthorizationTokenInput{}\n\toutput, err := p.getter.GetAuthorizationToken(params)\n\tif err != nil {\n\t\tglog.Errorf(\"while requesting ECR authorization token %v\", err)\n\t\treturn cfg\n\t}\n\tif output == nil {\n\t\tglog.Errorf(\"Got back no ECR token\")\n\t\treturn cfg\n\t}\n\n\tfor _, data := range output.AuthorizationData {\n\t\tif data.ProxyEndpoint != nil &&\n\t\t\tdata.AuthorizationToken != nil {\n\t\t\tdecodedToken, err := base64.StdEncoding.DecodeString(aws.StringValue(data.AuthorizationToken))\n\t\t\tif err != nil {\n\t\t\t\tglog.Errorf(\"while decoding token for endpoint %v %v\", data.ProxyEndpoint, err)\n\t\t\t\treturn cfg\n\t\t\t}\n\t\t\tparts := strings.SplitN(string(decodedToken), \":\", 2)\n\t\t\tuser := parts[0]\n\t\t\tpassword := parts[1]\n\t\t\tentry := credentialprovider.DockerConfigEntry{\n\t\t\t\tUsername: user,\n\t\t\t\tPassword: password,\n\t\t\t\t\/\/ ECR doesn't care and Docker is about to obsolete it\n\t\t\t\tEmail: \"not@val.id\",\n\t\t\t}\n\n\t\t\tglog.V(3).Infof(\"Adding credentials for user %s in %s\", user, p.region)\n\t\t\t\/\/ Add our config entry for this region's registry URLs\n\t\t\tcfg[p.regionURL] = entry\n\n\t\t}\n\t}\n\treturn cfg\n}\n<commit_msg>AWS: Add ap-south-1 to list of known AWS regions<commit_after>\/*\nCopyright 2014 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage credentials\n\nimport (\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/request\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ecr\"\n\t\"github.com\/golang\/glog\"\n\t\"k8s.io\/kubernetes\/pkg\/credentialprovider\"\n)\n\n\/\/ AWSRegions is the complete list of regions known to the AWS cloudprovider\n\/\/ and credentialprovider.\nvar AWSRegions = [...]string{\n\t\"us-east-1\",\n\t\"us-west-1\",\n\t\"us-west-2\",\n\t\"eu-west-1\",\n\t\"eu-central-1\",\n\t\"ap-south-1\",\n\t\"ap-southeast-1\",\n\t\"ap-southeast-2\",\n\t\"ap-northeast-1\",\n\t\"ap-northeast-2\",\n\t\"cn-north-1\",\n\t\"us-gov-west-1\",\n\t\"sa-east-1\",\n}\n\nconst registryURLTemplate = \"*.dkr.ecr.%s.amazonaws.com\"\n\n\/\/ awsHandlerLogger is a handler that logs all AWS SDK requests\n\/\/ Copied from cloudprovider\/aws\/log_handler.go\nfunc awsHandlerLogger(req *request.Request) {\n\tservice := req.ClientInfo.ServiceName\n\tregion := req.Config.Region\n\n\tname := \"?\"\n\tif req.Operation != nil {\n\t\tname = req.Operation.Name\n\t}\n\n\tglog.V(3).Infof(\"AWS request: %s:%s in %s\", service, name, *region)\n}\n\n\/\/ An interface for testing purposes.\ntype tokenGetter interface {\n\tGetAuthorizationToken(input *ecr.GetAuthorizationTokenInput) (*ecr.GetAuthorizationTokenOutput, error)\n}\n\n\/\/ The canonical implementation\ntype ecrTokenGetter struct {\n\tsvc *ecr.ECR\n}\n\nfunc (p *ecrTokenGetter) GetAuthorizationToken(input *ecr.GetAuthorizationTokenInput) (*ecr.GetAuthorizationTokenOutput, error) {\n\treturn p.svc.GetAuthorizationToken(input)\n}\n\n\/\/ lazyEcrProvider is a DockerConfigProvider that creates on demand an\n\/\/ ecrProvider for a given region and then proxies requests to it.\ntype lazyEcrProvider struct {\n\tregion         string\n\tregionURL      string\n\tactualProvider *credentialprovider.CachingDockerConfigProvider\n}\n\nvar _ credentialprovider.DockerConfigProvider = &lazyEcrProvider{}\n\n\/\/ ecrProvider is a DockerConfigProvider that gets and refreshes 12-hour tokens\n\/\/ from AWS to access ECR.\ntype ecrProvider struct {\n\tregion    string\n\tregionURL string\n\tgetter    tokenGetter\n}\n\nvar _ credentialprovider.DockerConfigProvider = &ecrProvider{}\n\n\/\/ Init creates a lazy provider for each AWS region, in order to support\n\/\/ cross-region ECR access. They have to be lazy because it's unlikely, but not\n\/\/ impossible, that we'll use more than one.\n\/\/ Not using the package init() function: this module should be initialized only\n\/\/ if using the AWS cloud provider. This way, we avoid timeouts waiting for a\n\/\/ non-existent provider.\nfunc Init() {\n\tfor _, region := range AWSRegions {\n\t\tcredentialprovider.RegisterCredentialProvider(\"aws-ecr-\"+region,\n\t\t\t&lazyEcrProvider{\n\t\t\t\tregion:    region,\n\t\t\t\tregionURL: fmt.Sprintf(registryURLTemplate, region),\n\t\t\t})\n\t}\n\n}\n\n\/\/ Enabled implements DockerConfigProvider.Enabled for the lazy provider.\n\/\/ Since we perform no checks\/work of our own and actualProvider is only created\n\/\/ later at image pulling time (if ever), always return true.\nfunc (p *lazyEcrProvider) Enabled() bool {\n\treturn true\n}\n\n\/\/ LazyProvide implements DockerConfigProvider.LazyProvide. It will be called\n\/\/ by the client when attempting to pull an image and it will create the actual\n\/\/ provider only when we actually need it the first time.\nfunc (p *lazyEcrProvider) LazyProvide() *credentialprovider.DockerConfigEntry {\n\tif p.actualProvider == nil {\n\t\tglog.V(2).Infof(\"Creating ecrProvider for %s\", p.region)\n\t\tp.actualProvider = &credentialprovider.CachingDockerConfigProvider{\n\t\t\tProvider: newEcrProvider(p.region, nil),\n\t\t\t\/\/ Refresh credentials a little earlier than expiration time\n\t\t\tLifetime: 11*time.Hour + 55*time.Minute,\n\t\t}\n\t\tif !p.actualProvider.Enabled() {\n\t\t\treturn nil\n\t\t}\n\t}\n\tentry := p.actualProvider.Provide()[p.regionURL]\n\treturn &entry\n}\n\n\/\/ Provide implements DockerConfigProvider.Provide, creating dummy credentials.\n\/\/ Client code will call Provider.LazyProvide() at image pulling time.\nfunc (p *lazyEcrProvider) Provide() credentialprovider.DockerConfig {\n\tentry := credentialprovider.DockerConfigEntry{\n\t\tProvider: p,\n\t}\n\tcfg := credentialprovider.DockerConfig{}\n\tcfg[p.regionURL] = entry\n\treturn cfg\n}\n\nfunc newEcrProvider(region string, getter tokenGetter) *ecrProvider {\n\treturn &ecrProvider{\n\t\tregion:    region,\n\t\tregionURL: fmt.Sprintf(registryURLTemplate, region),\n\t\tgetter:    getter,\n\t}\n}\n\n\/\/ Enabled implements DockerConfigProvider.Enabled for the AWS token-based implementation.\n\/\/ For now, it gets activated only if AWS was chosen as the cloud provider.\n\/\/ TODO: figure how to enable it manually for deployments that are not on AWS but still\n\/\/ use ECR somehow?\nfunc (p *ecrProvider) Enabled() bool {\n\tif p.region == \"\" {\n\t\tglog.Errorf(\"Called ecrProvider.Enabled() with no region set\")\n\t\treturn false\n\t}\n\n\tgetter := &ecrTokenGetter{svc: ecr.New(session.New(&aws.Config{\n\t\tCredentials: nil,\n\t\tRegion:      &p.region,\n\t}))}\n\tgetter.svc.Handlers.Sign.PushFrontNamed(request.NamedHandler{\n\t\tName: \"k8s\/logger\",\n\t\tFn:   awsHandlerLogger,\n\t})\n\tp.getter = getter\n\n\treturn true\n}\n\n\/\/ LazyProvide implements DockerConfigProvider.LazyProvide. Should never be called.\nfunc (p *ecrProvider) LazyProvide() *credentialprovider.DockerConfigEntry {\n\treturn nil\n}\n\n\/\/ Provide implements DockerConfigProvider.Provide, refreshing ECR tokens on demand\nfunc (p *ecrProvider) Provide() credentialprovider.DockerConfig {\n\tcfg := credentialprovider.DockerConfig{}\n\n\t\/\/ TODO: fill in RegistryIds?\n\tparams := &ecr.GetAuthorizationTokenInput{}\n\toutput, err := p.getter.GetAuthorizationToken(params)\n\tif err != nil {\n\t\tglog.Errorf(\"while requesting ECR authorization token %v\", err)\n\t\treturn cfg\n\t}\n\tif output == nil {\n\t\tglog.Errorf(\"Got back no ECR token\")\n\t\treturn cfg\n\t}\n\n\tfor _, data := range output.AuthorizationData {\n\t\tif data.ProxyEndpoint != nil &&\n\t\t\tdata.AuthorizationToken != nil {\n\t\t\tdecodedToken, err := base64.StdEncoding.DecodeString(aws.StringValue(data.AuthorizationToken))\n\t\t\tif err != nil {\n\t\t\t\tglog.Errorf(\"while decoding token for endpoint %v %v\", data.ProxyEndpoint, err)\n\t\t\t\treturn cfg\n\t\t\t}\n\t\t\tparts := strings.SplitN(string(decodedToken), \":\", 2)\n\t\t\tuser := parts[0]\n\t\t\tpassword := parts[1]\n\t\t\tentry := credentialprovider.DockerConfigEntry{\n\t\t\t\tUsername: user,\n\t\t\t\tPassword: password,\n\t\t\t\t\/\/ ECR doesn't care and Docker is about to obsolete it\n\t\t\t\tEmail: \"not@val.id\",\n\t\t\t}\n\n\t\t\tglog.V(3).Infof(\"Adding credentials for user %s in %s\", user, p.region)\n\t\t\t\/\/ Add our config entry for this region's registry URLs\n\t\t\tcfg[p.regionURL] = entry\n\n\t\t}\n\t}\n\treturn cfg\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage devicemanager\n\nimport (\n\t\"path\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/require\"\n\n\tpluginapi \"k8s.io\/kubelet\/pkg\/apis\/deviceplugin\/v1beta1\"\n)\n\nvar (\n\tesocketName = \"mock.sock\"\n)\n\nfunc TestNewEndpoint(t *testing.T) {\n\tsocket := path.Join(\"\/tmp\", esocketName)\n\n\tdevs := []*pluginapi.Device{\n\t\t{ID: \"ADeviceId\", Health: pluginapi.Healthy},\n\t}\n\n\tp, e := esetup(t, devs, socket, \"mock\", func(n string, d []pluginapi.Device) {})\n\tdefer ecleanup(t, p, e)\n}\n\nfunc TestRun(t *testing.T) {\n\tsocket := path.Join(\"\/tmp\", esocketName)\n\n\tdevs := []*pluginapi.Device{\n\t\t{ID: \"ADeviceId\", Health: pluginapi.Healthy},\n\t\t{ID: \"AnotherDeviceId\", Health: pluginapi.Healthy},\n\t\t{ID: \"AThirdDeviceId\", Health: pluginapi.Unhealthy},\n\t}\n\n\tupdated := []*pluginapi.Device{\n\t\t{ID: \"ADeviceId\", Health: pluginapi.Unhealthy},\n\t\t{ID: \"AThirdDeviceId\", Health: pluginapi.Healthy},\n\t\t{ID: \"AFourthDeviceId\", Health: pluginapi.Healthy},\n\t}\n\n\tcallbackCount := 0\n\tcallbackChan := make(chan int)\n\tcallback := func(n string, devices []pluginapi.Device) {\n\t\t\/\/ Should be called twice:\n\t\t\/\/ one for plugin registration, one for plugin update.\n\t\tif callbackCount > 2 {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\t\/\/ Check plugin registration\n\t\tif callbackCount == 0 {\n\t\t\trequire.Len(t, devices, 3)\n\t\t\trequire.Equal(t, devices[0].ID, devs[0].ID)\n\t\t\trequire.Equal(t, devices[1].ID, devs[1].ID)\n\t\t\trequire.Equal(t, devices[2].ID, devs[2].ID)\n\t\t\trequire.Equal(t, devices[0].Health, devs[0].Health)\n\t\t\trequire.Equal(t, devices[1].Health, devs[1].Health)\n\t\t\trequire.Equal(t, devices[2].Health, devs[2].Health)\n\t\t}\n\n\t\t\/\/ Check plugin update\n\t\tif callbackCount == 1 {\n\t\t\trequire.Len(t, devices, 3)\n\t\t\trequire.Equal(t, devices[0].ID, updated[0].ID)\n\t\t\trequire.Equal(t, devices[1].ID, updated[1].ID)\n\t\t\trequire.Equal(t, devices[2].ID, updated[2].ID)\n\t\t\trequire.Equal(t, devices[0].Health, updated[0].Health)\n\t\t\trequire.Equal(t, devices[1].Health, updated[1].Health)\n\t\t\trequire.Equal(t, devices[2].Health, updated[2].Health)\n\t\t}\n\n\t\tcallbackCount++\n\t\tcallbackChan <- callbackCount\n\t}\n\n\tp, e := esetup(t, devs, socket, \"mock\", callback)\n\tdefer ecleanup(t, p, e)\n\n\tgo e.run()\n\t\/\/ Wait for the first callback to be issued.\n\t<-callbackChan\n\n\tp.Update(updated)\n\n\t\/\/ Wait for the second callback to be issued.\n\t<-callbackChan\n\n\trequire.Equal(t, callbackCount, 2)\n}\n\nfunc TestAllocate(t *testing.T) {\n\tsocket := path.Join(\"\/tmp\", esocketName)\n\tdevs := []*pluginapi.Device{\n\t\t{ID: \"ADeviceId\", Health: pluginapi.Healthy},\n\t}\n\tcallbackCount := 0\n\tcallbackChan := make(chan int)\n\tp, e := esetup(t, devs, socket, \"mock\", func(n string, d []pluginapi.Device) {\n\t\tcallbackCount++\n\t\tcallbackChan <- callbackCount\n\t})\n\tdefer ecleanup(t, p, e)\n\n\tresp := new(pluginapi.AllocateResponse)\n\tcontResp := new(pluginapi.ContainerAllocateResponse)\n\tcontResp.Devices = append(contResp.Devices, &pluginapi.DeviceSpec{\n\t\tContainerPath: \"\/dev\/aaa\",\n\t\tHostPath:      \"\/dev\/aaa\",\n\t\tPermissions:   \"mrw\",\n\t})\n\n\tcontResp.Devices = append(contResp.Devices, &pluginapi.DeviceSpec{\n\t\tContainerPath: \"\/dev\/bbb\",\n\t\tHostPath:      \"\/dev\/bbb\",\n\t\tPermissions:   \"mrw\",\n\t})\n\n\tcontResp.Mounts = append(contResp.Mounts, &pluginapi.Mount{\n\t\tContainerPath: \"\/container_dir1\/file1\",\n\t\tHostPath:      \"host_dir1\/file1\",\n\t\tReadOnly:      true,\n\t})\n\n\tresp.ContainerResponses = append(resp.ContainerResponses, contResp)\n\n\tp.SetAllocFunc(func(r *pluginapi.AllocateRequest, devs map[string]pluginapi.Device) (*pluginapi.AllocateResponse, error) {\n\t\treturn resp, nil\n\t})\n\n\tgo e.run()\n\t\/\/ Wait for the callback to be issued.\n\tselect {\n\tcase <-callbackChan:\n\t\tbreak\n\tcase <-time.After(time.Second):\n\t\tt.FailNow()\n\t}\n\n\trespOut, err := e.allocate([]string{\"ADeviceId\"})\n\trequire.NoError(t, err)\n\trequire.Equal(t, resp, respOut)\n}\n\nfunc TestGetPreferredAllocation(t *testing.T) {\n\tsocket := path.Join(\"\/tmp\", esocketName)\n\tcallbackCount := 0\n\tcallbackChan := make(chan int)\n\tp, e := esetup(t, []*pluginapi.Device{}, socket, \"mock\", func(n string, d []pluginapi.Device) {\n\t\tcallbackCount++\n\t\tcallbackChan <- callbackCount\n\t})\n\tdefer ecleanup(t, p, e)\n\n\tresp := &pluginapi.PreferredAllocationResponse{\n\t\tContainerResponses: []*pluginapi.ContainerPreferredAllocationResponse{\n\t\t\t{DeviceIDs: []string{\"device0\", \"device1\", \"device2\"}},\n\t\t},\n\t}\n\n\tp.SetGetPreferredAllocFunc(func(r *pluginapi.PreferredAllocationRequest, devs map[string]pluginapi.Device) (*pluginapi.PreferredAllocationResponse, error) {\n\t\treturn resp, nil\n\t})\n\n\tgo e.run()\n\t\/\/ Wait for the callback to be issued.\n\tselect {\n\tcase <-callbackChan:\n\t\tbreak\n\tcase <-time.After(time.Second):\n\t\tt.FailNow()\n\t}\n\n\trespOut, err := e.getPreferredAllocation([]string{}, []string{}, -1)\n\trequire.NoError(t, err)\n\trequire.Equal(t, resp, respOut)\n}\n\nfunc esetup(t *testing.T, devs []*pluginapi.Device, socket, resourceName string, callback monitorCallback) (*Stub, *endpointImpl) {\n\tp := NewDevicePluginStub(devs, socket, resourceName, false, false)\n\n\terr := p.Start()\n\trequire.NoError(t, err)\n\n\te, err := newEndpointImpl(socket, resourceName, callback)\n\trequire.NoError(t, err)\n\n\treturn p, e\n}\n\nfunc ecleanup(t *testing.T, p *Stub, e *endpointImpl) {\n\tp.Stop()\n\te.stop()\n}\n<commit_msg>Use unique socket name per cm test<commit_after>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage devicemanager\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/require\"\n\n\tpluginapi \"k8s.io\/kubelet\/pkg\/apis\/deviceplugin\/v1beta1\"\n)\n\nfunc esocketName() string {\n\treturn fmt.Sprintf(\"mock%d.sock\", time.Now().UnixNano())\n}\n\nfunc TestNewEndpoint(t *testing.T) {\n\tsocket := path.Join(\"\/tmp\", esocketName())\n\n\tdevs := []*pluginapi.Device{\n\t\t{ID: \"ADeviceId\", Health: pluginapi.Healthy},\n\t}\n\n\tp, e := esetup(t, devs, socket, \"mock\", func(n string, d []pluginapi.Device) {})\n\tdefer ecleanup(t, p, e)\n}\n\nfunc TestRun(t *testing.T) {\n\tsocket := path.Join(\"\/tmp\", esocketName())\n\n\tdevs := []*pluginapi.Device{\n\t\t{ID: \"ADeviceId\", Health: pluginapi.Healthy},\n\t\t{ID: \"AnotherDeviceId\", Health: pluginapi.Healthy},\n\t\t{ID: \"AThirdDeviceId\", Health: pluginapi.Unhealthy},\n\t}\n\n\tupdated := []*pluginapi.Device{\n\t\t{ID: \"ADeviceId\", Health: pluginapi.Unhealthy},\n\t\t{ID: \"AThirdDeviceId\", Health: pluginapi.Healthy},\n\t\t{ID: \"AFourthDeviceId\", Health: pluginapi.Healthy},\n\t}\n\n\tcallbackCount := 0\n\tcallbackChan := make(chan int)\n\tcallback := func(n string, devices []pluginapi.Device) {\n\t\t\/\/ Should be called twice:\n\t\t\/\/ one for plugin registration, one for plugin update.\n\t\tif callbackCount > 2 {\n\t\t\tt.FailNow()\n\t\t}\n\n\t\t\/\/ Check plugin registration\n\t\tif callbackCount == 0 {\n\t\t\trequire.Len(t, devices, 3)\n\t\t\trequire.Equal(t, devices[0].ID, devs[0].ID)\n\t\t\trequire.Equal(t, devices[1].ID, devs[1].ID)\n\t\t\trequire.Equal(t, devices[2].ID, devs[2].ID)\n\t\t\trequire.Equal(t, devices[0].Health, devs[0].Health)\n\t\t\trequire.Equal(t, devices[1].Health, devs[1].Health)\n\t\t\trequire.Equal(t, devices[2].Health, devs[2].Health)\n\t\t}\n\n\t\t\/\/ Check plugin update\n\t\tif callbackCount == 1 {\n\t\t\trequire.Len(t, devices, 3)\n\t\t\trequire.Equal(t, devices[0].ID, updated[0].ID)\n\t\t\trequire.Equal(t, devices[1].ID, updated[1].ID)\n\t\t\trequire.Equal(t, devices[2].ID, updated[2].ID)\n\t\t\trequire.Equal(t, devices[0].Health, updated[0].Health)\n\t\t\trequire.Equal(t, devices[1].Health, updated[1].Health)\n\t\t\trequire.Equal(t, devices[2].Health, updated[2].Health)\n\t\t}\n\n\t\tcallbackCount++\n\t\tcallbackChan <- callbackCount\n\t}\n\n\tp, e := esetup(t, devs, socket, \"mock\", callback)\n\tdefer ecleanup(t, p, e)\n\n\tgo e.run()\n\t\/\/ Wait for the first callback to be issued.\n\t<-callbackChan\n\n\tp.Update(updated)\n\n\t\/\/ Wait for the second callback to be issued.\n\t<-callbackChan\n\n\trequire.Equal(t, callbackCount, 2)\n}\n\nfunc TestAllocate(t *testing.T) {\n\tsocket := path.Join(\"\/tmp\", esocketName())\n\tdevs := []*pluginapi.Device{\n\t\t{ID: \"ADeviceId\", Health: pluginapi.Healthy},\n\t}\n\tcallbackCount := 0\n\tcallbackChan := make(chan int)\n\tp, e := esetup(t, devs, socket, \"mock\", func(n string, d []pluginapi.Device) {\n\t\tcallbackCount++\n\t\tcallbackChan <- callbackCount\n\t})\n\tdefer ecleanup(t, p, e)\n\n\tresp := new(pluginapi.AllocateResponse)\n\tcontResp := new(pluginapi.ContainerAllocateResponse)\n\tcontResp.Devices = append(contResp.Devices, &pluginapi.DeviceSpec{\n\t\tContainerPath: \"\/dev\/aaa\",\n\t\tHostPath:      \"\/dev\/aaa\",\n\t\tPermissions:   \"mrw\",\n\t})\n\n\tcontResp.Devices = append(contResp.Devices, &pluginapi.DeviceSpec{\n\t\tContainerPath: \"\/dev\/bbb\",\n\t\tHostPath:      \"\/dev\/bbb\",\n\t\tPermissions:   \"mrw\",\n\t})\n\n\tcontResp.Mounts = append(contResp.Mounts, &pluginapi.Mount{\n\t\tContainerPath: \"\/container_dir1\/file1\",\n\t\tHostPath:      \"host_dir1\/file1\",\n\t\tReadOnly:      true,\n\t})\n\n\tresp.ContainerResponses = append(resp.ContainerResponses, contResp)\n\n\tp.SetAllocFunc(func(r *pluginapi.AllocateRequest, devs map[string]pluginapi.Device) (*pluginapi.AllocateResponse, error) {\n\t\treturn resp, nil\n\t})\n\n\tgo e.run()\n\t\/\/ Wait for the callback to be issued.\n\tselect {\n\tcase <-callbackChan:\n\t\tbreak\n\tcase <-time.After(time.Second):\n\t\tt.FailNow()\n\t}\n\n\trespOut, err := e.allocate([]string{\"ADeviceId\"})\n\trequire.NoError(t, err)\n\trequire.Equal(t, resp, respOut)\n}\n\nfunc TestGetPreferredAllocation(t *testing.T) {\n\tsocket := path.Join(\"\/tmp\", esocketName())\n\tcallbackCount := 0\n\tcallbackChan := make(chan int)\n\tp, e := esetup(t, []*pluginapi.Device{}, socket, \"mock\", func(n string, d []pluginapi.Device) {\n\t\tcallbackCount++\n\t\tcallbackChan <- callbackCount\n\t})\n\tdefer ecleanup(t, p, e)\n\n\tresp := &pluginapi.PreferredAllocationResponse{\n\t\tContainerResponses: []*pluginapi.ContainerPreferredAllocationResponse{\n\t\t\t{DeviceIDs: []string{\"device0\", \"device1\", \"device2\"}},\n\t\t},\n\t}\n\n\tp.SetGetPreferredAllocFunc(func(r *pluginapi.PreferredAllocationRequest, devs map[string]pluginapi.Device) (*pluginapi.PreferredAllocationResponse, error) {\n\t\treturn resp, nil\n\t})\n\n\tgo e.run()\n\t\/\/ Wait for the callback to be issued.\n\tselect {\n\tcase <-callbackChan:\n\t\tbreak\n\tcase <-time.After(time.Second):\n\t\tt.FailNow()\n\t}\n\n\trespOut, err := e.getPreferredAllocation([]string{}, []string{}, -1)\n\trequire.NoError(t, err)\n\trequire.Equal(t, resp, respOut)\n}\n\nfunc esetup(t *testing.T, devs []*pluginapi.Device, socket, resourceName string, callback monitorCallback) (*Stub, *endpointImpl) {\n\tp := NewDevicePluginStub(devs, socket, resourceName, false, false)\n\n\terr := p.Start()\n\trequire.NoError(t, err)\n\n\te, err := newEndpointImpl(socket, resourceName, callback)\n\trequire.NoError(t, err)\n\n\treturn p, e\n}\n\nfunc ecleanup(t *testing.T, p *Stub, e *endpointImpl) {\n\tp.Stop()\n\te.stop()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage customresourcedefinition\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\"\n\tapierrors \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\tgenericapirequest \"k8s.io\/apiserver\/pkg\/endpoints\/request\"\n\t\"k8s.io\/apiserver\/pkg\/registry\/generic\"\n\tgenericregistry \"k8s.io\/apiserver\/pkg\/registry\/generic\/registry\"\n\t\"k8s.io\/apiserver\/pkg\/registry\/rest\"\n\t\"k8s.io\/apiserver\/pkg\/storage\"\n\tstorageerr \"k8s.io\/apiserver\/pkg\/storage\/errors\"\n)\n\n\/\/ rest implements a RESTStorage for API services against etcd\ntype REST struct {\n\t*genericregistry.Store\n}\n\n\/\/ NewREST returns a RESTStorage object that will work against API services.\nfunc NewREST(scheme *runtime.Scheme, optsGetter generic.RESTOptionsGetter) *REST {\n\tstrategy := NewStrategy(scheme)\n\n\tstore := &genericregistry.Store{\n\t\tNewFunc:                  func() runtime.Object { return &apiextensions.CustomResourceDefinition{} },\n\t\tNewListFunc:              func() runtime.Object { return &apiextensions.CustomResourceDefinitionList{} },\n\t\tPredicateFunc:            MatchCustomResourceDefinition,\n\t\tDefaultQualifiedResource: apiextensions.Resource(\"customresourcedefinitions\"),\n\n\t\tCreateStrategy: strategy,\n\t\tUpdateStrategy: strategy,\n\t\tDeleteStrategy: strategy,\n\t}\n\toptions := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\tpanic(err) \/\/ TODO: Propagate error up\n\t}\n\treturn &REST{store}\n}\n\n\/\/ Implement ShortNamesProvider\nvar _ rest.ShortNamesProvider = &REST{}\n\n\/\/ ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"crd\"}\n}\n\n\/\/ Delete adds the CRD finalizer to the list\nfunc (r *REST) Delete(ctx genericapirequest.Context, name string, options *metav1.DeleteOptions) (runtime.Object, bool, error) {\n\tobj, err := r.Get(ctx, name, &metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tcrd := obj.(*apiextensions.CustomResourceDefinition)\n\n\t\/\/ Ensure we have a UID precondition\n\tif options == nil {\n\t\toptions = metav1.NewDeleteOptions(0)\n\t}\n\tif options.Preconditions == nil {\n\t\toptions.Preconditions = &metav1.Preconditions{}\n\t}\n\tif options.Preconditions.UID == nil {\n\t\toptions.Preconditions.UID = &crd.UID\n\t} else if *options.Preconditions.UID != crd.UID {\n\t\terr = apierrors.NewConflict(\n\t\t\tapiextensions.Resource(\"customresourcedefinitions\"),\n\t\t\tname,\n\t\t\tfmt.Errorf(\"Precondition failed: UID in precondition: %v, UID in object meta: %v\", *options.Preconditions.UID, crd.UID),\n\t\t)\n\t\treturn nil, false, err\n\t}\n\n\t\/\/ upon first request to delete, add our finalizer and then delegate\n\tif crd.DeletionTimestamp.IsZero() {\n\t\tkey, err := r.Store.KeyFunc(ctx, name)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\n\t\tpreconditions := storage.Preconditions{UID: options.Preconditions.UID}\n\n\t\tout := r.Store.NewFunc()\n\t\terr = r.Store.Storage.GuaranteedUpdate(\n\t\t\tctx, key, out, false, &preconditions,\n\t\t\tstorage.SimpleUpdate(func(existing runtime.Object) (runtime.Object, error) {\n\t\t\t\texistingCRD, ok := existing.(*apiextensions.CustomResourceDefinition)\n\t\t\t\tif !ok {\n\t\t\t\t\t\/\/ wrong type\n\t\t\t\t\treturn nil, fmt.Errorf(\"expected *apiextensions.CustomResourceDefinition, got %v\", existing)\n\t\t\t\t}\n\n\t\t\t\t\/\/ Set the deletion timestamp if needed\n\t\t\t\tif existingCRD.DeletionTimestamp.IsZero() {\n\t\t\t\t\tnow := metav1.Now()\n\t\t\t\t\texistingCRD.DeletionTimestamp = &now\n\t\t\t\t}\n\n\t\t\t\tif !apiextensions.CRDHasFinalizer(existingCRD, apiextensions.CustomResourceCleanupFinalizer) {\n\t\t\t\t\texistingCRD.Finalizers = append(existingCRD.Finalizers, apiextensions.CustomResourceCleanupFinalizer)\n\t\t\t\t}\n\t\t\t\t\/\/ update the status condition too\n\t\t\t\tapiextensions.SetCRDCondition(existingCRD, apiextensions.CustomResourceDefinitionCondition{\n\t\t\t\t\tType:    apiextensions.Terminating,\n\t\t\t\t\tStatus:  apiextensions.ConditionTrue,\n\t\t\t\t\tReason:  \"InstanceDeletionPending\",\n\t\t\t\t\tMessage: \"CustomResourceDefinition marked for deletion; CustomResource deletion will begin soon\",\n\t\t\t\t})\n\t\t\t\treturn existingCRD, nil\n\t\t\t}),\n\t\t)\n\n\t\tif err != nil {\n\t\t\terr = storageerr.InterpretGetError(err, apiextensions.Resource(\"customresourcedefinitions\"), name)\n\t\t\terr = storageerr.InterpretUpdateError(err, apiextensions.Resource(\"customresourcedefinitions\"), name)\n\t\t\tif _, ok := err.(*apierrors.StatusError); !ok {\n\t\t\t\terr = apierrors.NewInternalError(err)\n\t\t\t}\n\t\t\treturn nil, false, err\n\t\t}\n\n\t\treturn out, false, nil\n\t}\n\n\treturn r.Store.Delete(ctx, name, options)\n}\n\n\/\/ NewStatusREST makes a RESTStorage for status that has more limited options.\n\/\/ It is based on the original REST so that we can share the same underlying store\nfunc NewStatusREST(scheme *runtime.Scheme, rest *REST) *StatusREST {\n\tstatusStore := *rest.Store\n\tstatusStore.CreateStrategy = nil\n\tstatusStore.DeleteStrategy = nil\n\tstatusStore.UpdateStrategy = NewStatusStrategy(scheme)\n\treturn &StatusREST{store: &statusStore}\n}\n\ntype StatusREST struct {\n\tstore *genericregistry.Store\n}\n\nvar _ = rest.Updater(&StatusREST{})\n\nfunc (r *StatusREST) New() runtime.Object {\n\treturn &apiextensions.CustomResourceDefinition{}\n}\n\n\/\/ Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx genericapirequest.Context, name string, objInfo rest.UpdatedObjectInfo) (runtime.Object, bool, error) {\n\treturn r.store.Update(ctx, name, objInfo)\n}\n<commit_msg>admission: wire create+update validation func into kube registries<commit_after>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage customresourcedefinition\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\"\n\tapierrors \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\tgenericapirequest \"k8s.io\/apiserver\/pkg\/endpoints\/request\"\n\t\"k8s.io\/apiserver\/pkg\/registry\/generic\"\n\tgenericregistry \"k8s.io\/apiserver\/pkg\/registry\/generic\/registry\"\n\t\"k8s.io\/apiserver\/pkg\/registry\/rest\"\n\t\"k8s.io\/apiserver\/pkg\/storage\"\n\tstorageerr \"k8s.io\/apiserver\/pkg\/storage\/errors\"\n)\n\n\/\/ rest implements a RESTStorage for API services against etcd\ntype REST struct {\n\t*genericregistry.Store\n}\n\n\/\/ NewREST returns a RESTStorage object that will work against API services.\nfunc NewREST(scheme *runtime.Scheme, optsGetter generic.RESTOptionsGetter) *REST {\n\tstrategy := NewStrategy(scheme)\n\n\tstore := &genericregistry.Store{\n\t\tNewFunc:                  func() runtime.Object { return &apiextensions.CustomResourceDefinition{} },\n\t\tNewListFunc:              func() runtime.Object { return &apiextensions.CustomResourceDefinitionList{} },\n\t\tPredicateFunc:            MatchCustomResourceDefinition,\n\t\tDefaultQualifiedResource: apiextensions.Resource(\"customresourcedefinitions\"),\n\n\t\tCreateStrategy: strategy,\n\t\tUpdateStrategy: strategy,\n\t\tDeleteStrategy: strategy,\n\t}\n\toptions := &generic.StoreOptions{RESTOptions: optsGetter, AttrFunc: GetAttrs}\n\tif err := store.CompleteWithOptions(options); err != nil {\n\t\tpanic(err) \/\/ TODO: Propagate error up\n\t}\n\treturn &REST{store}\n}\n\n\/\/ Implement ShortNamesProvider\nvar _ rest.ShortNamesProvider = &REST{}\n\n\/\/ ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource.\nfunc (r *REST) ShortNames() []string {\n\treturn []string{\"crd\"}\n}\n\n\/\/ Delete adds the CRD finalizer to the list\nfunc (r *REST) Delete(ctx genericapirequest.Context, name string, options *metav1.DeleteOptions) (runtime.Object, bool, error) {\n\tobj, err := r.Get(ctx, name, &metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tcrd := obj.(*apiextensions.CustomResourceDefinition)\n\n\t\/\/ Ensure we have a UID precondition\n\tif options == nil {\n\t\toptions = metav1.NewDeleteOptions(0)\n\t}\n\tif options.Preconditions == nil {\n\t\toptions.Preconditions = &metav1.Preconditions{}\n\t}\n\tif options.Preconditions.UID == nil {\n\t\toptions.Preconditions.UID = &crd.UID\n\t} else if *options.Preconditions.UID != crd.UID {\n\t\terr = apierrors.NewConflict(\n\t\t\tapiextensions.Resource(\"customresourcedefinitions\"),\n\t\t\tname,\n\t\t\tfmt.Errorf(\"Precondition failed: UID in precondition: %v, UID in object meta: %v\", *options.Preconditions.UID, crd.UID),\n\t\t)\n\t\treturn nil, false, err\n\t}\n\n\t\/\/ upon first request to delete, add our finalizer and then delegate\n\tif crd.DeletionTimestamp.IsZero() {\n\t\tkey, err := r.Store.KeyFunc(ctx, name)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\n\t\tpreconditions := storage.Preconditions{UID: options.Preconditions.UID}\n\n\t\tout := r.Store.NewFunc()\n\t\terr = r.Store.Storage.GuaranteedUpdate(\n\t\t\tctx, key, out, false, &preconditions,\n\t\t\tstorage.SimpleUpdate(func(existing runtime.Object) (runtime.Object, error) {\n\t\t\t\texistingCRD, ok := existing.(*apiextensions.CustomResourceDefinition)\n\t\t\t\tif !ok {\n\t\t\t\t\t\/\/ wrong type\n\t\t\t\t\treturn nil, fmt.Errorf(\"expected *apiextensions.CustomResourceDefinition, got %v\", existing)\n\t\t\t\t}\n\n\t\t\t\t\/\/ Set the deletion timestamp if needed\n\t\t\t\tif existingCRD.DeletionTimestamp.IsZero() {\n\t\t\t\t\tnow := metav1.Now()\n\t\t\t\t\texistingCRD.DeletionTimestamp = &now\n\t\t\t\t}\n\n\t\t\t\tif !apiextensions.CRDHasFinalizer(existingCRD, apiextensions.CustomResourceCleanupFinalizer) {\n\t\t\t\t\texistingCRD.Finalizers = append(existingCRD.Finalizers, apiextensions.CustomResourceCleanupFinalizer)\n\t\t\t\t}\n\t\t\t\t\/\/ update the status condition too\n\t\t\t\tapiextensions.SetCRDCondition(existingCRD, apiextensions.CustomResourceDefinitionCondition{\n\t\t\t\t\tType:    apiextensions.Terminating,\n\t\t\t\t\tStatus:  apiextensions.ConditionTrue,\n\t\t\t\t\tReason:  \"InstanceDeletionPending\",\n\t\t\t\t\tMessage: \"CustomResourceDefinition marked for deletion; CustomResource deletion will begin soon\",\n\t\t\t\t})\n\t\t\t\treturn existingCRD, nil\n\t\t\t}),\n\t\t)\n\n\t\tif err != nil {\n\t\t\terr = storageerr.InterpretGetError(err, apiextensions.Resource(\"customresourcedefinitions\"), name)\n\t\t\terr = storageerr.InterpretUpdateError(err, apiextensions.Resource(\"customresourcedefinitions\"), name)\n\t\t\tif _, ok := err.(*apierrors.StatusError); !ok {\n\t\t\t\terr = apierrors.NewInternalError(err)\n\t\t\t}\n\t\t\treturn nil, false, err\n\t\t}\n\n\t\treturn out, false, nil\n\t}\n\n\treturn r.Store.Delete(ctx, name, options)\n}\n\n\/\/ NewStatusREST makes a RESTStorage for status that has more limited options.\n\/\/ It is based on the original REST so that we can share the same underlying store\nfunc NewStatusREST(scheme *runtime.Scheme, rest *REST) *StatusREST {\n\tstatusStore := *rest.Store\n\tstatusStore.CreateStrategy = nil\n\tstatusStore.DeleteStrategy = nil\n\tstatusStore.UpdateStrategy = NewStatusStrategy(scheme)\n\treturn &StatusREST{store: &statusStore}\n}\n\ntype StatusREST struct {\n\tstore *genericregistry.Store\n}\n\nvar _ = rest.Updater(&StatusREST{})\n\nfunc (r *StatusREST) New() runtime.Object {\n\treturn &apiextensions.CustomResourceDefinition{}\n}\n\n\/\/ Update alters the status subset of an object.\nfunc (r *StatusREST) Update(ctx genericapirequest.Context, name string, objInfo rest.UpdatedObjectInfo, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc) (runtime.Object, bool, error) {\n\treturn r.store.Update(ctx, name, objInfo, createValidation, updateValidation)\n}\n<|endoftext|>"}
{"text":"<commit_before>package marshal\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t. \"github.com\/xitongsys\/parquet-go\/schema\"\n)\n\ntype Student struct {\n\tName    string               `parquet:\"name=name, type=UTF8\"`\n\tAge     int32                `parquet:\"name=age, type=INT32\"`\n\tWeight  *int32               `parquet:\"name=weight, type=INT32\"`\n\tClasses *map[string][]*Class `parquet:\"name=classes, keytype=UTF8\"`\n}\n\ntype Class struct {\n\tName     string   `parquet:\"name=name, type=UTF8\"`\n\tID       *int64   `parquet:\"name=id, type=INT64\"`\n\tRequired []string `parquet:\"name=required, type=UTF8\"`\n}\n\nfunc (c Class) String() string {\n\tid := \"nil\"\n\tif c.ID != nil {\n\t\tid = fmt.Sprintf(\"%d\", *c.ID)\n\t}\n\tres := fmt.Sprintf(\"{Name:%s, ID:%v, Required:%s}\", c.Name, id, fmt.Sprint(c.Required))\n\treturn res\n}\n\nfunc (s Student) String() string {\n\tweight := \"nil\"\n\tif s.Weight != nil {\n\t\tweight = fmt.Sprintf(\"%d\", *s.Weight)\n\t}\n\n\tcs := \"{\"\n\tfor key, classes := range *s.Classes {\n\t\ts := string(key) + \":[\"\n\t\tfor _, class := range classes {\n\t\t\ts += (*class).String() + \",\"\n\t\t}\n\t\ts += \"]\"\n\t\tcs += s\n\t}\n\tcs += \"}\"\n\tres := fmt.Sprintf(\"{Name:%s, Age:%d, Weight:%s, Classes:%s}\", s.Name, s.Age, weight, cs)\n\treturn res\n}\n\nfunc TestMarshalUnmarshal(t *testing.T) {\n\tschemaHandler, _ := NewSchemaHandlerFromStruct(new(Student))\n\tfmt.Println(\"SchemaHandler Finished\")\n\n\tmath01ID := int64(1)\n\tmath01 := Class{\n\t\tName:     \"Math1\",\n\t\tID:       &math01ID,\n\t\tRequired: make([]string, 0),\n\t}\n\n\tmath02ID := int64(2)\n\tmath02 := Class{\n\t\tName:     \"Math2\",\n\t\tID:       &math02ID,\n\t\tRequired: make([]string, 0),\n\t}\n\tmath02.Required = append(math02.Required, \"Math01\")\n\n\tphysics := Class{\n\t\tName:     \"Physics\",\n\t\tID:       nil,\n\t\tRequired: make([]string, 0),\n\t}\n\tphysics.Required = append(physics.Required, \"Math01\", \"Math02\")\n\n\tweight01 := int32(60)\n\tstu01Class := make(map[string][]*Class)\n\tstu01Class[\"Science\"] = make([]*Class, 0)\n\tstu01Class[\"Science\"] = append(stu01Class[\"Science\"], &math01, &math02)\n\tstu01 := Student{\n\t\tName:    \"zxt\",\n\t\tAge:     18,\n\t\tWeight:  &weight01,\n\t\tClasses: &stu01Class,\n\t}\n\n\tstu02Class := make(map[string][]*Class)\n\tstu02Class[\"Science\"] = make([]*Class, 0)\n\tstu02Class[\"Science\"] = append(stu02Class[\"Science\"], &physics)\n\tstu02 := Student{\n\t\tName:    \"tong\",\n\t\tAge:     29,\n\t\tWeight:  nil,\n\t\tClasses: &stu02Class,\n\t}\n\n\tstus := make([]interface{}, 0)\n\tstus = append(stus, stu01, stu02)\n\n\tsrc, _ := Marshal(stus, 0, len(stus), schemaHandler)\n\tfmt.Println(\"Marshal Finished\")\n\n\tfor name, table := range *src {\n\t\tfmt.Println(name)\n\t\tfmt.Println(\"Val: \", table.Values)\n\t\tfmt.Println(\"RL: \", table.RepetitionLevels)\n\t\tfmt.Println(\"DL: \", table.DefinitionLevels)\n\t}\n\n\tdst := make([]Student, 0)\n\tUnmarshal(src, 0, len(stus), &dst, schemaHandler)\n\n\ts0 := fmt.Sprint(stus)\n\ts1 := fmt.Sprint(dst)\n\tif s0 != s1 {\n\t\tt.Errorf(\"Fail expect %s, get %s\", s0, s1)\n\t}\n\n}\n<commit_msg>update ut<commit_after>package marshal\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t. \"github.com\/xitongsys\/parquet-go\/schema\"\n)\n\ntype Student struct {\n\tName    string               `parquet:\"name=name, type=UTF8\"`\n\tAge     int32                `parquet:\"name=age, type=INT32\"`\n\tWeight  *int32               `parquet:\"name=weight, type=INT32\"`\n\tClasses *map[string][]*Class `parquet:\"name=classes, keytype=UTF8\"`\n}\n\ntype Class struct {\n\tName     string   `parquet:\"name=name, type=UTF8\"`\n\tID       *int64   `parquet:\"name=id, type=INT64\"`\n\tRequired []string `parquet:\"name=required, type=UTF8\"`\n}\n\nfunc (c Class) String() string {\n\tid := \"nil\"\n\tif c.ID != nil {\n\t\tid = fmt.Sprintf(\"%d\", *c.ID)\n\t}\n\tres := fmt.Sprintf(\"{Name:%s, ID:%v, Required:%s}\", c.Name, id, fmt.Sprint(c.Required))\n\treturn res\n}\n\nfunc (s Student) String() string {\n\tweight := \"nil\"\n\tif s.Weight != nil {\n\t\tweight = fmt.Sprintf(\"%d\", *s.Weight)\n\t}\n\n\tcs := \"{\"\n\tfor key, classes := range *s.Classes {\n\t\ts := string(key) + \":[\"\n\t\tfor _, class := range classes {\n\t\t\ts += (*class).String() + \",\"\n\t\t}\n\t\ts += \"]\"\n\t\tcs += s\n\t}\n\tcs += \"}\"\n\tres := fmt.Sprintf(\"{Name:%s, Age:%d, Weight:%s, Classes:%s}\", s.Name, s.Age, weight, cs)\n\treturn res\n}\n\nfunc TestMarshalUnmarshal(t *testing.T) {\n\tschemaHandler, _ := NewSchemaHandlerFromStruct(new(Student))\n\tfmt.Println(\"SchemaHandler Finished\")\n\n\tmath01ID := int64(1)\n\tmath01 := Class{\n\t\tName:     \"Math1\",\n\t\tID:       &math01ID,\n\t\tRequired: make([]string, 0),\n\t}\n\n\tmath02ID := int64(2)\n\tmath02 := Class{\n\t\tName:     \"Math2\",\n\t\tID:       &math02ID,\n\t\tRequired: make([]string, 0),\n\t}\n\tmath02.Required = append(math02.Required, \"Math01\")\n\n\tphysics := Class{\n\t\tName:     \"Physics\",\n\t\tID:       nil,\n\t\tRequired: make([]string, 0),\n\t}\n\tphysics.Required = append(physics.Required, \"Math01\", \"Math02\")\n\n\tweight01 := int32(60)\n\tstu01Class := make(map[string][]*Class)\n\tstu01Class[\"Science\"] = make([]*Class, 0)\n\tstu01Class[\"Science\"] = append(stu01Class[\"Science\"], &math01, &math02)\n\tstu01 := Student{\n\t\tName:    \"zxt\",\n\t\tAge:     18,\n\t\tWeight:  &weight01,\n\t\tClasses: &stu01Class,\n\t}\n\n\tstu02Class := make(map[string][]*Class)\n\tstu02Class[\"Science\"] = make([]*Class, 0)\n\tstu02Class[\"Science\"] = append(stu02Class[\"Science\"], &physics)\n\tstu02 := Student{\n\t\tName:    \"tong\",\n\t\tAge:     29,\n\t\tWeight:  nil,\n\t\tClasses: &stu02Class,\n\t}\n\n\tstus := make([]interface{}, 0)\n\tstus = append(stus, stu01, stu02)\n\n\tsrc, _ := Marshal(stus, 0, len(stus), schemaHandler)\n\tfmt.Println(\"Marshal Finished\")\n\n\tfor name, table := range *src {\n\t\tfmt.Println(name)\n\t\tfmt.Println(\"Val: \", table.Values)\n\t\tfmt.Println(\"RL: \", table.RepetitionLevels)\n\t\tfmt.Println(\"DL: \", table.DefinitionLevels)\n\t}\n\n\tdst := make([]Student, 0)\n\tUnmarshal(src, 0, len(stus), &dst, schemaHandler, \"\")\n\n\ts0 := fmt.Sprint(stus)\n\ts1 := fmt.Sprint(dst)\n\tif s0 != s1 {\n\t\tt.Errorf(\"Fail expect %s, get %s\", s0, s1)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package logger provides a logging framework similar to those of python\n\/\/ and haskell.\npackage logger\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"text\/template\"\n\t\"time\"\n)\n\nconst (\n\tname = \"logger\"\n)\n\n\/\/ Format represents the format which will be used to print the message\n\/\/ for an logger.\ntype Format string\n\n\/\/ Logger represent different lognames and priorities. They can have\n\/\/ parents and child loggers which will inherit the priority of the\n\/\/ parent if it has none. The hirachy of loggers is represented through\n\/\/ sepperation with dots ('.'). The root logger has the name '.'.\ntype Logger string\n\n\/\/ Priority defines how important a log message is. Loggers will output\n\/\/ messages which are above their priority level.\ntype Priority int\n\n\/\/ Different priority levels ordered by their severity.\nconst (\n\tDebug Priority = iota\n\tInfo\n\tNotice\n\tWarning\n\tError\n\tCritical\n\tAlert\n\tEmergency\n\tDisable\n)\n\n\/\/ DefaultPriority of the root logger.\nconst (\n\tDefaultPriority Priority = Notice\n)\n\nvar (\n\tformat     = \"[{{.Time}} {{.Priority}} {{.Logger}}] - {{.Message}}.\\n\"\n\ttimeformat = time.RFC3339\n\n\tpriorities     map[Priority]string\n\tlist           loggers\n\tformattemplate template.Template\n)\n\nfunc init() {\n\tlist = newLoggers()\n\n\tpriorities = make(map[Priority]string)\n\tpriorities[Debug] = \"Debug\"\n\tpriorities[Info] = \"Info\"\n\tpriorities[Notice] = \"Notice\"\n\tpriorities[Warning] = \"Warning\"\n\tpriorities[Error] = \"Error\"\n\tpriorities[Critical] = \"Critical\"\n\tpriorities[Alert] = \"Alert\"\n\tpriorities[Emergency] = \"Emergency\"\n\tpriorities[Disable] = \"Disabled\"\n}\n\n\/\/ New will return a logger with the given name.\nfunc New(na string) (log Logger) {\n\treturn Logger(na)\n}\n\n\/\/ GetLevel returns the priority level of the given logger.\nfunc GetLevel(lo Logger) (pri Priority) {\n\treturn list.GetLevel(lo)\n}\n\n\/\/ SetLevel sets the priority level for the given logger.\nfunc SetLevel(lo Logger, pr Priority) (err error) {\n\terr = list.SetLevel(lo, pr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ SetFormat changes the message format for the given logger. Avaivable\n\/\/ fields are:\n\/\/\n\/\/ Time: The time when the message is printed.\n\/\/\n\/\/ Logger: The name of the logger.\n\/\/\n\/\/ Priority: The priority of the logger.\n\/\/\n\/\/ Message: The output message.\n\/\/\n\/\/ The default Format is:\n\/\/\n\/\/ \"[{{.Time}} {{.Logger}} {{.Priority}}] - {{.Message}}.\\n\"\nfunc SetFormat(lo Logger, fo Format) error {\n\treturn list.SetFormat(lo, fo)\n}\n\n\/\/ SetTimeFormat sets the TimeFormat which will be used in the message\n\/\/ format for the specified logger\n\/\/\n\/\/ The default format is: RFC3339\nfunc SetTimeFormat(lo Logger, fo string) error {\n\treturn list.SetTimeFormat(lo, fo)\n}\n\n\/\/ SetNoColor sets the nocolor flag for the given logger. If true no\n\/\/ colors will be printed for the logger.\nfunc SetNoColor(lo Logger, nc bool) {\n\tlist.SetNoColor(lo, nc)\n}\n\n\/\/ SetOutput sets the output parameter of the logger to the given\n\/\/ io.Writer. The default is os.Stderr.\nfunc SetOutput(lo Logger, ou io.Writer) error {\n\treturn list.SetOutput(lo, ou)\n}\n\n\/\/ ParsePriority tries to parse the priority by the given string.\nfunc ParsePriority(pr string) (Priority, error) {\n\tfor k, v := range priorities {\n\t\tif v == pr {\n\t\t\treturn k, nil\n\t\t}\n\t}\n\n\te := errors.New(\"can not parse priority: do not recognize \" + pr)\n\treturn DefaultPriority, e\n}\n\n\/\/ NamePriority returns the string value of the given priority.\nfunc NamePriority(pr Priority) (pri string, err error) {\n\terr = checkPriority(pr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpri = priorities[pr]\n\n\treturn\n}\n\nfunc logMessage(lo Logger, pr Priority, me ...interface{}) {\n\tl := list.GetLogger(lo)\n\n\tif l.Priority > pr {\n\t\treturn\n\t}\n\n\tprintMessage(l, pr, me...)\n}\n\n\/\/ Log logs a message with the given priority.\nfunc (lo Logger) Log(pr Priority, me ...interface{}) {\n\tlogMessage(lo, pr, me)\n}\n\n\/\/ Debug logs a message with the Debug priority.\nfunc (lo Logger) Debug(me ...interface{}) {\n\tlogMessage(lo, Debug, me...)\n}\n\n\/\/ Info logs a message with the Debug priority.\nfunc (lo Logger) Info(me ...interface{}) {\n\tlogMessage(lo, Info, me...)\n}\n\n\/\/ Notice logs a message with the Debug priority.\nfunc (lo Logger) Notice(me ...interface{}) {\n\tlogMessage(lo, Notice, me...)\n}\n\n\/\/ Warning logs a message with the Debug priority.\nfunc (lo Logger) Warning(me ...interface{}) {\n\tlogMessage(lo, Warning, me...)\n}\n\n\/\/ Error logs a message with the Debug priority.\nfunc (lo Logger) Error(me ...interface{}) {\n\tlogMessage(lo, Error, me...)\n}\n\n\/\/ Critical logs a message with the Debug priority.\nfunc (lo Logger) Critical(me ...interface{}) {\n\tlogMessage(lo, Critical, me...)\n}\n\n\/\/ Alert logs a message with the Debug priority.\nfunc (lo Logger) Alert(me ...interface{}) {\n\tlogMessage(lo, Alert, me...)\n}\n\n\/\/ Emergency logs a message with the Debug priority.\nfunc (lo Logger) Emergency(me ...interface{}) {\n\tlogMessage(lo, Emergency, me...)\n}\n\n\/\/ GetLevel returns the priority level of the logger.\nfunc (lo Logger) GetLevel() Priority {\n\treturn GetLevel(lo)\n}\n\n\/\/ SetLevel sets the priority level for the Logger.\nfunc (lo Logger) SetLevel(pr Priority) (err error) {\n\terr = SetLevel(lo, pr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ SetFormat changes the message format for the Logger. Avaivable fields\n\/\/ are:\n\/\/\n\/\/ Time: The time when the message is printed.\n\/\/\n\/\/ Logger: The name of the logger.\n\/\/\n\/\/ Priority: The priority of the logger.\n\/\/\n\/\/ Message: The output message.\n\/\/\n\/\/ The default Format is:\n\/\/\n\/\/ \"[{{.Time}} {{.Logger}} {{.Priority}}] - {{.Message}}.\\n\"\nfunc (lo Logger) SetFormat(fo Format) {\n\tSetFormat(lo, fo)\n}\n\n\/\/ SetTimeFormat sets the TimeFormat which will be used in the message\n\/\/ format for the Logger\n\/\/\n\/\/ The default format is: RFC3339\nfunc (lo Logger) SetTimeFormat(fo string) error {\n\treturn SetTimeFormat(lo, fo)\n}\n\n\/\/ SetNoColor sets the nocolor flag for the given logger. If true no\n\/\/ colors will be printed for the logger.\nfunc (lo Logger) SetNoColor(nc bool) {\n\tSetNoColor(lo, nc)\n}\n\n\/\/ SetOutput sets the output parameter of the logger to the given\n\/\/ io.Writer. The default is os.Stderr.\nfunc (lo Logger) SetOutput(ou io.Writer) {\n\tSetOutput(lo, ou)\n}\n<commit_msg>Added ImportLoggers which sets the loglevels for the given map.<commit_after>\/\/ Package logger provides a logging framework similar to those of python\n\/\/ and haskell.\npackage logger\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"text\/template\"\n\t\"time\"\n)\n\nconst (\n\tname = \"logger\"\n)\n\n\/\/ Format represents the format which will be used to print the message\n\/\/ for an logger.\ntype Format string\n\n\/\/ Logger represent different lognames and priorities. They can have\n\/\/ parents and child loggers which will inherit the priority of the\n\/\/ parent if it has none. The hirachy of loggers is represented through\n\/\/ sepperation with dots ('.'). The root logger has the name '.'.\ntype Logger string\n\n\/\/ Priority defines how important a log message is. Loggers will output\n\/\/ messages which are above their priority level.\ntype Priority int\n\n\/\/ Different priority levels ordered by their severity.\nconst (\n\tDebug Priority = iota\n\tInfo\n\tNotice\n\tWarning\n\tError\n\tCritical\n\tAlert\n\tEmergency\n\tDisable\n)\n\n\/\/ DefaultPriority of the root logger.\nconst (\n\tDefaultPriority Priority = Notice\n)\n\nvar (\n\tformat     = \"[{{.Time}} {{.Priority}} {{.Logger}}] - {{.Message}}.\\n\"\n\ttimeformat = time.RFC3339\n\n\tpriorities     map[Priority]string\n\tlist           loggers\n\tformattemplate template.Template\n)\n\nfunc init() {\n\tlist = newLoggers()\n\n\tpriorities = make(map[Priority]string)\n\tpriorities[Debug] = \"Debug\"\n\tpriorities[Info] = \"Info\"\n\tpriorities[Notice] = \"Notice\"\n\tpriorities[Warning] = \"Warning\"\n\tpriorities[Error] = \"Error\"\n\tpriorities[Critical] = \"Critical\"\n\tpriorities[Alert] = \"Alert\"\n\tpriorities[Emergency] = \"Emergency\"\n\tpriorities[Disable] = \"Disabled\"\n}\n\n\/\/ ImportLoggers sets the LogLevel for the given Loggers.\nfunc ImportLoggers(lo map[Logger]string) (err error) {\n\tif lo == nil {\n\t\terr = errors.New(\"the loglevel map is nil\")\n\t\treturn\n\t}\n\n\tfor k, v := range lo {\n\t\tp, e := ParsePriority(v)\n\t\tif e != nil {\n\t\t\terr = errors.New(\"can not parse priority: \" + e.Error())\n\t\t\treturn\n\t\t}\n\n\t\tSetLevel(k, p)\n\t}\n\n\treturn\n}\n\n\/\/ New will return a logger with the given name.\nfunc New(na string) (log Logger) {\n\treturn Logger(na)\n}\n\n\/\/ GetLevel returns the priority level of the given logger.\nfunc GetLevel(lo Logger) (pri Priority) {\n\treturn list.GetLevel(lo)\n}\n\n\/\/ SetLevel sets the priority level for the given logger.\nfunc SetLevel(lo Logger, pr Priority) (err error) {\n\terr = list.SetLevel(lo, pr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ SetFormat changes the message format for the given logger. Avaivable\n\/\/ fields are:\n\/\/\n\/\/ Time: The time when the message is printed.\n\/\/\n\/\/ Logger: The name of the logger.\n\/\/\n\/\/ Priority: The priority of the logger.\n\/\/\n\/\/ Message: The output message.\n\/\/\n\/\/ The default Format is:\n\/\/\n\/\/ \"[{{.Time}} {{.Logger}} {{.Priority}}] - {{.Message}}.\\n\"\nfunc SetFormat(lo Logger, fo Format) error {\n\treturn list.SetFormat(lo, fo)\n}\n\n\/\/ SetTimeFormat sets the TimeFormat which will be used in the message\n\/\/ format for the specified logger\n\/\/\n\/\/ The default format is: RFC3339\nfunc SetTimeFormat(lo Logger, fo string) error {\n\treturn list.SetTimeFormat(lo, fo)\n}\n\n\/\/ SetNoColor sets the nocolor flag for the given logger. If true no\n\/\/ colors will be printed for the logger.\nfunc SetNoColor(lo Logger, nc bool) {\n\tlist.SetNoColor(lo, nc)\n}\n\n\/\/ SetOutput sets the output parameter of the logger to the given\n\/\/ io.Writer. The default is os.Stderr.\nfunc SetOutput(lo Logger, ou io.Writer) error {\n\treturn list.SetOutput(lo, ou)\n}\n\n\/\/ ParsePriority tries to parse the priority by the given string.\nfunc ParsePriority(pr string) (Priority, error) {\n\tfor k, v := range priorities {\n\t\tif v == pr {\n\t\t\treturn k, nil\n\t\t}\n\t}\n\n\te := errors.New(\"can not parse priority: do not recognize \" + pr)\n\treturn DefaultPriority, e\n}\n\n\/\/ NamePriority returns the string value of the given priority.\nfunc NamePriority(pr Priority) (pri string, err error) {\n\terr = checkPriority(pr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpri = priorities[pr]\n\n\treturn\n}\n\nfunc logMessage(lo Logger, pr Priority, me ...interface{}) {\n\tl := list.GetLogger(lo)\n\n\tif l.Priority > pr {\n\t\treturn\n\t}\n\n\tprintMessage(l, pr, me...)\n}\n\n\/\/ Log logs a message with the given priority.\nfunc (lo Logger) Log(pr Priority, me ...interface{}) {\n\tlogMessage(lo, pr, me)\n}\n\n\/\/ Debug logs a message with the Debug priority.\nfunc (lo Logger) Debug(me ...interface{}) {\n\tlogMessage(lo, Debug, me...)\n}\n\n\/\/ Info logs a message with the Debug priority.\nfunc (lo Logger) Info(me ...interface{}) {\n\tlogMessage(lo, Info, me...)\n}\n\n\/\/ Notice logs a message with the Debug priority.\nfunc (lo Logger) Notice(me ...interface{}) {\n\tlogMessage(lo, Notice, me...)\n}\n\n\/\/ Warning logs a message with the Debug priority.\nfunc (lo Logger) Warning(me ...interface{}) {\n\tlogMessage(lo, Warning, me...)\n}\n\n\/\/ Error logs a message with the Debug priority.\nfunc (lo Logger) Error(me ...interface{}) {\n\tlogMessage(lo, Error, me...)\n}\n\n\/\/ Critical logs a message with the Debug priority.\nfunc (lo Logger) Critical(me ...interface{}) {\n\tlogMessage(lo, Critical, me...)\n}\n\n\/\/ Alert logs a message with the Debug priority.\nfunc (lo Logger) Alert(me ...interface{}) {\n\tlogMessage(lo, Alert, me...)\n}\n\n\/\/ Emergency logs a message with the Debug priority.\nfunc (lo Logger) Emergency(me ...interface{}) {\n\tlogMessage(lo, Emergency, me...)\n}\n\n\/\/ GetLevel returns the priority level of the logger.\nfunc (lo Logger) GetLevel() Priority {\n\treturn GetLevel(lo)\n}\n\n\/\/ SetLevel sets the priority level for the Logger.\nfunc (lo Logger) SetLevel(pr Priority) (err error) {\n\terr = SetLevel(lo, pr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ SetFormat changes the message format for the Logger. Avaivable fields\n\/\/ are:\n\/\/\n\/\/ Time: The time when the message is printed.\n\/\/\n\/\/ Logger: The name of the logger.\n\/\/\n\/\/ Priority: The priority of the logger.\n\/\/\n\/\/ Message: The output message.\n\/\/\n\/\/ The default Format is:\n\/\/\n\/\/ \"[{{.Time}} {{.Logger}} {{.Priority}}] - {{.Message}}.\\n\"\nfunc (lo Logger) SetFormat(fo Format) {\n\tSetFormat(lo, fo)\n}\n\n\/\/ SetTimeFormat sets the TimeFormat which will be used in the message\n\/\/ format for the Logger\n\/\/\n\/\/ The default format is: RFC3339\nfunc (lo Logger) SetTimeFormat(fo string) error {\n\treturn SetTimeFormat(lo, fo)\n}\n\n\/\/ SetNoColor sets the nocolor flag for the given logger. If true no\n\/\/ colors will be printed for the logger.\nfunc (lo Logger) SetNoColor(nc bool) {\n\tSetNoColor(lo, nc)\n}\n\n\/\/ SetOutput sets the output parameter of the logger to the given\n\/\/ io.Writer. The default is os.Stderr.\nfunc (lo Logger) SetOutput(ou io.Writer) {\n\tSetOutput(lo, ou)\n}\n<|endoftext|>"}
{"text":"<commit_before>package hands\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n)\n\n\/\/ Logger provides a very simple logger in l2met format.\nfunc Logger(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\twr := newWrapper(w)\n\t\tnext.ServeHTTP(wr, r)\n\n\t\tstr := fmt.Sprintf(\"method=%s path=%+v host=%+v code=%d bytes=%d\",\n\t\t\tr.Method,\n\t\t\tr.URL.Path,\n\t\t\tr.Host,\n\t\t\twr.status,\n\t\t\twr.bytes,\n\t\t)\n\t\tif reqID := wr.Header().Get(HeaderRequestID); reqID != \"\" {\n\t\t\tstr = fmt.Sprintf(\"%s request_id=%s\",\n\t\t\t\tstr,\n\t\t\t\treqID,\n\t\t\t)\n\t\t}\n\t\tlog.Print(str)\n\t}\n\treturn http.HandlerFunc(fn)\n}\n\n\/\/ wrapper allows further introspection of generated responses.\ntype wrapper struct {\n\thttp.ResponseWriter\n\twroteHeader bool\n\tstatus      int\n\tbytes       int\n}\n\nfunc newWrapper(w http.ResponseWriter) *wrapper {\n\treturn &wrapper{ResponseWriter: w}\n}\n\nfunc (wr *wrapper) WriteHeader(code int) {\n\tif !wr.wroteHeader {\n\t\twr.ResponseWriter.WriteHeader(code)\n\t\twr.wroteHeader = true\n\t\twr.status = code\n\t}\n}\n\nfunc (wr *wrapper) Write(data []byte) (int, error) {\n\twr.WriteHeader(http.StatusOK)\n\tn, err := wr.ResponseWriter.Write(data)\n\twr.bytes += n\n\treturn n, err\n}\n\n\/\/ Flush implements http.Flusher.\nfunc (wr *wrapper) Flush() {\n\tif f, ok := wr.ResponseWriter.(http.Flusher); ok {\n\t\tf.Flush()\n\t}\n}\n\n\/\/ CloseNotify implements http.CloseNotifier.\nfunc (wr *wrapper) CloseNotify() <-chan bool {\n\tif cn, ok := wr.ResponseWriter.(http.CloseNotifier); ok {\n\t\treturn cn.CloseNotify()\n\t}\n\treturn nil\n}\n\n\/\/ Hijack implements http.Hijacker.\nfunc (wr *wrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {\n\tif hj, ok := wr.ResponseWriter.(http.Hijacker); ok {\n\t\treturn hj.Hijack()\n\t}\n\treturn nil, nil, nil\n}\n<commit_msg>logging doesn't belong here<commit_after><|endoftext|>"}
{"text":"<commit_before>package mdqi\n\nimport (\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\nvar logger = func() *log.Logger {\n\treturn log.New(os.Stderr, \"\", log.Ldate|log.Ltime|log.Lshortfile)\n}()\n\nvar debug = func() *log.Logger {\n\tvar out io.Writer\n\n\tif os.Getenv(\"DEBUG\") != \"\" {\n\t\tout = os.Stderr\n\t} else {\n\t\tout = ioutil.Discard\n\t}\n\n\tl := log.New(out, \"[debug] \", log.Ldate|log.Ltime|log.Lshortfile)\n\n\treturn l\n}()\n<commit_msg>source code filename is not required for log.<commit_after>package mdqi\n\nimport (\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\nvar logger = func() *log.Logger {\n\treturn log.New(os.Stderr, \"\", log.Ldate|log.Ltime)\n}()\n\nvar debug = func() *log.Logger {\n\tvar out io.Writer\n\n\tif os.Getenv(\"DEBUG\") != \"\" {\n\t\tout = os.Stderr\n\t} else {\n\t\tout = ioutil.Discard\n\t}\n\n\tl := log.New(out, \"[debug] \", log.Ldate|log.Ltime|log.Lshortfile)\n\n\treturn l\n}()\n<|endoftext|>"}
{"text":"<commit_before>package clog\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"sync\/atomic\"\n\n\t\"github.com\/fatih\/color\"\n)\n\n\/\/ Logger is an interface for a logger with a specific name and level.\ntype Logger interface {\n\t\/\/ Name returns the name can used to identify the logger.\n\tName() string\n\t\/\/ Level returns the minimum logging level of the logger.\n\tLevel() Level\n\t\/\/ Write processes a Messager entry.\n\tWrite(Messager) error\n}\n\nvar _ Logger = (*noopLogger)(nil)\n\ntype noopLogger struct {\n\tname  string\n\tlevel Level\n}\n\nfunc (l *noopLogger) Name() string           { return l.name }\nfunc (l *noopLogger) Level() Level           { return l.level }\nfunc (l *noopLogger) Write(_ Messager) error { return nil }\n\nfunc noopIniter(name string, _ ...interface{}) Initer {\n\treturn func(string, ...interface{}) (Logger, error) {\n\t\treturn &noopLogger{name: name}, nil\n\t}\n}\n\ntype cancelableLogger struct {\n\tcancel  context.CancelFunc\n\tmsgChan chan Messager\n\tdone    chan struct{}\n\tLogger\n}\n\nvar errLogger = log.New(color.Output, \"\", log.Ldate|log.Ltime)\nvar errSprintf = color.New(color.FgRed).Sprintf\n\nfunc (l *cancelableLogger) error(err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\n\terrLogger.Print(errSprintf(\"[clog] [%s]: %v\", l.Name(), err))\n}\n\nconst (\n\tstateStopping int64 = 0\n\tstateRunning  int64 = 1\n)\n\ntype manager struct {\n\tstate   int64\n\tctx     context.Context\n\tcancel  context.CancelFunc\n\tloggers []*cancelableLogger\n}\n\nfunc (m *manager) len() int {\n\treturn len(m.loggers)\n}\n\nfunc (m *manager) write(level Level, skip int, format string, v ...interface{}) {\n\tvar msg *message\n\tfor i := range mgr.loggers {\n\t\tif mgr.loggers[i].Level() > level {\n\t\t\tcontinue\n\t\t}\n\n\t\tif msg == nil {\n\t\t\tmsg = newMessage(level, skip, format, v...)\n\t\t}\n\n\t\tmgr.loggers[i].msgChan <- msg\n\t}\n\n\tif msg == nil {\n\t\terrLogger.Print(errSprintf(\"[clog] no logger is available\"))\n\t}\n}\n\nfunc (m *manager) stop() {\n\t\/\/ Make sure cancellation is only propagated once to prevent deadlock of WaitForStop.\n\tif !atomic.CompareAndSwapInt64(&m.state, stateRunning, stateStopping) {\n\t\treturn\n\t}\n\n\tm.cancel()\n\tfor _, l := range m.loggers {\n\t\t<-l.done\n\t}\n}\n\nvar mgr *manager\n\nfunc init() {\n\tctx, cancel := context.WithCancel(context.Background())\n\tmgr = &manager{\n\t\tstate:  stateRunning,\n\t\tctx:    ctx,\n\t\tcancel: cancel,\n\t}\n}\n\n\/\/ Initer takes a name and arbitrary number of parameters needed for initalization\n\/\/ and returns an initalized logger.\ntype Initer func(string, ...interface{}) (Logger, error)\n\n\/\/ New initializes and appends a new logger to the managed list.\n\/\/ Calling this function multiple times will overwrite previous initialized\n\/\/ logger with the same name.\n\/\/\n\/\/ Any integer type (i.e. int, int32, int64) will be used as buffer size.\n\/\/ Otherwise, the value will be passed to the initer.\n\/\/\n\/\/ This function is not concurrent safe.\nfunc New(name string, initer Initer, opts ...interface{}) error {\n\tbufferSize := 0\n\n\tvs := opts[:0]\n\tfor i := range opts {\n\t\tswitch opt := opts[i].(type) {\n\t\tcase int:\n\t\t\tbufferSize = opt\n\t\tcase int32:\n\t\t\tbufferSize = int(opt)\n\t\tcase int64:\n\t\t\tbufferSize = int(opt)\n\t\tdefault:\n\t\t\tvs = append(vs, opt)\n\t\t}\n\t}\n\n\tl, err := initer(name, vs...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"initialize logger: %v\", err)\n\t}\n\n\tif bufferSize < 0 {\n\t\tbufferSize = 0\n\t}\n\n\tctx, cancel := context.WithCancel(mgr.ctx)\n\tcl := &cancelableLogger{\n\t\tcancel:  cancel,\n\t\tmsgChan: make(chan Messager, bufferSize),\n\t\tdone:    make(chan struct{}),\n\t\tLogger:  l,\n\t}\n\n\t\/\/ Check and replace previous logger\n\tfound := false\n\tfor i, l := range mgr.loggers {\n\t\tif l.Name() == name {\n\t\t\tfound = true\n\n\t\t\t\/\/ Release previous logger\n\t\t\tl.cancel()\n\t\t\t<-l.done\n\n\t\t\tmgr.loggers[i] = cl\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\tmgr.loggers = append(mgr.loggers, cl)\n\t}\n\n\tgo func() {\n\tloop:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase m := <-cl.msgChan:\n\t\t\t\tcl.error(cl.Write(m))\n\t\t\tcase <-ctx.Done():\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Drain the msgChan at best effort\n\t\tfor {\n\t\t\tif len(cl.msgChan) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcl.error(cl.Write(<-cl.msgChan))\n\t\t}\n\n\t\t\/\/ Notify the cleanup is done\n\t\tcl.done <- struct{}{}\n\t}()\n\treturn nil\n}\n\n\/\/ Remove removes a logger with given name from the managed list.\n\/\/\n\/\/ This function is not concurrent safe.\nfunc Remove(name string) {\n\tloggers := mgr.loggers[:0]\n\tfor _, l := range mgr.loggers {\n\t\tif l.Name() == name {\n\t\t\tgo func(l *cancelableLogger) {\n\t\t\t\tl.cancel()\n\t\t\t\t<-l.done\n\t\t\t}(l)\n\t\t\tcontinue\n\t\t}\n\t\tloggers = append(loggers, l)\n\t}\n\tmgr.loggers = loggers\n}\n<commit_msg>logger: fix false-positive of no longer available error<commit_after>package clog\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"sync\/atomic\"\n\n\t\"github.com\/fatih\/color\"\n)\n\n\/\/ Logger is an interface for a logger with a specific name and level.\ntype Logger interface {\n\t\/\/ Name returns the name can used to identify the logger.\n\tName() string\n\t\/\/ Level returns the minimum logging level of the logger.\n\tLevel() Level\n\t\/\/ Write processes a Messager entry.\n\tWrite(Messager) error\n}\n\nvar _ Logger = (*noopLogger)(nil)\n\ntype noopLogger struct {\n\tname  string\n\tlevel Level\n}\n\nfunc (l *noopLogger) Name() string           { return l.name }\nfunc (l *noopLogger) Level() Level           { return l.level }\nfunc (l *noopLogger) Write(_ Messager) error { return nil }\n\nfunc noopIniter(name string, _ ...interface{}) Initer {\n\treturn func(string, ...interface{}) (Logger, error) {\n\t\treturn &noopLogger{name: name}, nil\n\t}\n}\n\ntype cancelableLogger struct {\n\tcancel  context.CancelFunc\n\tmsgChan chan Messager\n\tdone    chan struct{}\n\tLogger\n}\n\nvar errLogger = log.New(color.Output, \"\", log.Ldate|log.Ltime)\nvar errSprintf = color.New(color.FgRed).Sprintf\n\nfunc (l *cancelableLogger) error(err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\n\terrLogger.Print(errSprintf(\"[clog] [%s]: %v\", l.Name(), err))\n}\n\nconst (\n\tstateStopping int64 = 0\n\tstateRunning  int64 = 1\n)\n\ntype manager struct {\n\tstate   int64\n\tctx     context.Context\n\tcancel  context.CancelFunc\n\tloggers []*cancelableLogger\n}\n\nfunc (m *manager) len() int {\n\treturn len(m.loggers)\n}\n\nfunc (m *manager) write(level Level, skip int, format string, v ...interface{}) {\n\tif mgr.len() == 0 {\n\t\terrLogger.Print(errSprintf(\"[clog] no logger is available\"))\n\t\treturn\n\t}\n\n\tvar msg *message\n\tfor i := range mgr.loggers {\n\t\tif mgr.loggers[i].Level() > level {\n\t\t\tcontinue\n\t\t}\n\n\t\tif msg == nil {\n\t\t\tmsg = newMessage(level, skip, format, v...)\n\t\t}\n\n\t\tmgr.loggers[i].msgChan <- msg\n\t}\n}\n\nfunc (m *manager) stop() {\n\t\/\/ Make sure cancellation is only propagated once to prevent deadlock of WaitForStop.\n\tif !atomic.CompareAndSwapInt64(&m.state, stateRunning, stateStopping) {\n\t\treturn\n\t}\n\n\tm.cancel()\n\tfor _, l := range m.loggers {\n\t\t<-l.done\n\t}\n}\n\nvar mgr *manager\n\nfunc init() {\n\tctx, cancel := context.WithCancel(context.Background())\n\tmgr = &manager{\n\t\tstate:  stateRunning,\n\t\tctx:    ctx,\n\t\tcancel: cancel,\n\t}\n}\n\n\/\/ Initer takes a name and arbitrary number of parameters needed for initalization\n\/\/ and returns an initalized logger.\ntype Initer func(string, ...interface{}) (Logger, error)\n\n\/\/ New initializes and appends a new logger to the managed list.\n\/\/ Calling this function multiple times will overwrite previous initialized\n\/\/ logger with the same name.\n\/\/\n\/\/ Any integer type (i.e. int, int32, int64) will be used as buffer size.\n\/\/ Otherwise, the value will be passed to the initer.\n\/\/\n\/\/ This function is not concurrent safe.\nfunc New(name string, initer Initer, opts ...interface{}) error {\n\tbufferSize := 0\n\n\tvs := opts[:0]\n\tfor i := range opts {\n\t\tswitch opt := opts[i].(type) {\n\t\tcase int:\n\t\t\tbufferSize = opt\n\t\tcase int32:\n\t\t\tbufferSize = int(opt)\n\t\tcase int64:\n\t\t\tbufferSize = int(opt)\n\t\tdefault:\n\t\t\tvs = append(vs, opt)\n\t\t}\n\t}\n\n\tl, err := initer(name, vs...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"initialize logger: %v\", err)\n\t}\n\n\tif bufferSize < 0 {\n\t\tbufferSize = 0\n\t}\n\n\tctx, cancel := context.WithCancel(mgr.ctx)\n\tcl := &cancelableLogger{\n\t\tcancel:  cancel,\n\t\tmsgChan: make(chan Messager, bufferSize),\n\t\tdone:    make(chan struct{}),\n\t\tLogger:  l,\n\t}\n\n\t\/\/ Check and replace previous logger\n\tfound := false\n\tfor i, l := range mgr.loggers {\n\t\tif l.Name() == name {\n\t\t\tfound = true\n\n\t\t\t\/\/ Release previous logger\n\t\t\tl.cancel()\n\t\t\t<-l.done\n\n\t\t\tmgr.loggers[i] = cl\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\tmgr.loggers = append(mgr.loggers, cl)\n\t}\n\n\tgo func() {\n\tloop:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase m := <-cl.msgChan:\n\t\t\t\tcl.error(cl.Write(m))\n\t\t\tcase <-ctx.Done():\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Drain the msgChan at best effort\n\t\tfor {\n\t\t\tif len(cl.msgChan) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcl.error(cl.Write(<-cl.msgChan))\n\t\t}\n\n\t\t\/\/ Notify the cleanup is done\n\t\tcl.done <- struct{}{}\n\t}()\n\treturn nil\n}\n\n\/\/ Remove removes a logger with given name from the managed list.\n\/\/\n\/\/ This function is not concurrent safe.\nfunc Remove(name string) {\n\tloggers := mgr.loggers[:0]\n\tfor _, l := range mgr.loggers {\n\t\tif l.Name() == name {\n\t\t\tgo func(l *cancelableLogger) {\n\t\t\t\tl.cancel()\n\t\t\t\t<-l.done\n\t\t\t}(l)\n\t\t\tcontinue\n\t\t}\n\t\tloggers = append(loggers, l)\n\t}\n\tmgr.loggers = loggers\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014-2017 Bitmark Inc.\n\/\/ Use of this source code is governed by an ISC\n\/\/ license that can be found in the LICENSE file.\n\npackage logger\n\nimport (\n\t\"fmt\"\n\t\"github.com\/cihub\/seelog\"\n\t\"strings\"\n\t\"sync\"\n)\n\n\/\/ The log messages will be \"<tag><tagSuffix><message>\"\nconst tagSuffix = \": \"\n\n\/\/ the tagname reserved to set the default level for unknown tags\nconst DefaultTag = \"DEFAULT\"\n\n\/\/ the initial level for unknown tags\nconst DefaultLevel = \"error\"\n\n\/\/ Holds a set of default values for future NewChannel calls\nvar levelMap = map[string]string{DefaultTag: DefaultLevel}\n\n\/\/ simple ordering to allow <= to decide if log will be output\nconst (\n\t_ = iota\n\ttraceValue\n\tdebugValue\n\tinfoValue\n\twarnValue\n\terrorValue\n\tcriticalValue\n\toffValue\n)\n\n\/\/ This needs to correspond to seelog levels\nvar validLevels = map[string]int{\n\t\"trace\":    traceValue,\n\t\"debug\":    debugValue,\n\t\"info\":     infoValue,\n\t\"warn\":     warnValue,\n\t\"error\":    errorValue,\n\t\"critical\": criticalValue,\n\t\"off\":      offValue,\n}\n\n\/\/ The logging structure\n\/\/ nice short name so use like:\n\/\/\n\/\/   var log *logger.L\n\/\/   log := logger.New(\"sometag\")\ntype L struct {\n\tsync.Mutex\n\ttag          string\n\tformatPrefix string\n\ttextPrefix   string\n\tlevel        string\n\tlevelNumber  int\n\tlog          seelog.LoggerInterface\n}\n\n\/\/ Pre-load default levels before creating any new logging channels\n\/\/ invalid levels are simply skipped and repeated calls will\n\/\/ accumulate new tag values and overwrite old tag values.\n\/\/\n\/\/ This will not update currently open channels, it is only for new\n\/\/ channels, it is intended to be called once after command-line\n\/\/ arguments and any configuration files have been processed to\n\/\/ establish logging defaults.\n\/\/\n\/\/ the name \"*\" is reserved to set a level for any tags that do not\n\/\/ have table entries.\nfunc LoadLevels(levels map[string]string) {\n\tfor tag, level := range levels {\n\t\t\/\/ make sure that levelMap only contains correct data\n\t\t\/\/ by ignoring invalid levels\n\t\tif _, ok := validLevels[level]; ok {\n\t\t\tlevelMap[tag] = level\n\t\t}\n\t}\n}\n\n\/\/ Setup seelog to used a rotated log file and output all logs\n\/\/ level control is now controlled by this module\nfunc Initialise(file string, size int, number int) error {\n\tconfig := fmt.Sprintf(`\n          <seelog type=\"adaptive\"\n                  mininterval=\"2000000\"\n                  maxinterval=\"100000000\"\n                  critmsgcount=\"500\"\n                  minlevel=\"trace\">\n              <outputs formatid=\"all\">\n                  <rollingfile type=\"size\" filename=\"%s\" maxsize=\"%d\" maxrolls=\"%d\" \/>\n              <\/outputs>\n              <formats>\n                  <format id=\"all\" format=\"%%Date %%Time [%%LEVEL] %%Msg%%n\" \/>\n              <\/formats>\n          <\/seelog>`, file, size, number)\n\n\tlogger, err := seelog.LoggerFromConfigAsString(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = seelog.ReplaceLogger(logger)\n\tif nil == err {\n\t\tseelog.Current.Warn(\"LOGGER: ===== Logging system started =====\")\n\t}\n\treturn err\n}\n\n\/\/ flush all channels\nfunc Finalise() {\n\tseelog.Current.Warn(\"LOGGER: ===== Logging system stopped =====\")\n\tseelog.Flush()\n}\n\n\/\/ flush all channels\nfunc Flush() {\n\tseelog.Flush()\n}\n\n\/\/ Open a new logging channel with a specified tag\nfunc New(tag string) *L {\n\n\t\/\/ map % -> %% to be printf safe\n\ts := strings.Split(tag, \"%\")\n\tj := strings.Join(s, \"%%\")\n\n\t\/\/ determine the initial level\n\tlevel, ok := levelMap[tag]\n\tif !ok {\n\t\tlevel, ok = levelMap[DefaultTag]\n\t}\n\tif !ok {\n\t\tlevel = \"error\"\n\t}\n\n\t\/\/ create a logger channel\n\treturn &L{\n\t\ttag:          tag, \/\/ for referencing default level\n\t\tformatPrefix: j + tagSuffix,\n\t\ttextPrefix:   tag + tagSuffix,\n\t\tlevel:        level,\n\t\tlevelNumber:  validLevels[level], \/\/ level is validated so get a non-zero value\n\t\tlog:          seelog.Current,\n\t}\n}\n\n\/\/ Change the log level for a given channel returns the current level\n\/\/\n\/\/ Use the value of DefaultTag to return to current default value.\n\/\/ Use the value \"\" to just return the current setting\nfunc (l *L) ChangeLevel(level string) string {\n\t\/\/ preserve current\n\tcurrent := l.level\n\n\t\/\/ to return to default level which may have been modified\n\t\/\/ by subsequent LoadLevels calls.\n\tif DefaultTag == level {\n\t\t\/\/ get currrent default level for this tag\n\t\tvar ok bool\n\t\tlevel, ok = levelMap[l.tag]\n\t\tif !ok {\n\t\t\tlevel, ok = levelMap[DefaultTag]\n\t\t}\n\t\tif !ok {\n\t\t\tlevel = DefaultLevel\n\t\t}\n\t} else if \"\" == level {\n\t\treturn current\n\t}\n\n\t\/\/ set level and corresponding number\n\tif n, ok := validLevels[level]; ok {\n\t\tl.Lock()\n\t\tdefer l.Unlock()\n\t\tl.level = level\n\t\tl.levelNumber = n\n\t}\n\treturn current\n}\n\n\/\/ flush messages\nfunc (l *L) Flush() {\n\tFlush()\n}\n<commit_msg>fix a comment<commit_after>\/\/ Copyright (c) 2014-2017 Bitmark Inc.\n\/\/ Use of this source code is governed by an ISC\n\/\/ license that can be found in the LICENSE file.\n\npackage logger\n\nimport (\n\t\"fmt\"\n\t\"github.com\/cihub\/seelog\"\n\t\"strings\"\n\t\"sync\"\n)\n\n\/\/ The log messages will be \"<tag><tagSuffix><message>\"\nconst tagSuffix = \": \"\n\n\/\/ the tagname reserved to set the default level for unknown tags\nconst DefaultTag = \"DEFAULT\"\n\n\/\/ the initial level for unknown tags\nconst DefaultLevel = \"error\"\n\n\/\/ Holds a set of default values for future NewChannel calls\nvar levelMap = map[string]string{DefaultTag: DefaultLevel}\n\n\/\/ simple ordering to allow <= to decide if log will be output\nconst (\n\t_ = iota\n\ttraceValue\n\tdebugValue\n\tinfoValue\n\twarnValue\n\terrorValue\n\tcriticalValue\n\toffValue\n)\n\n\/\/ This needs to correspond to seelog levels\nvar validLevels = map[string]int{\n\t\"trace\":    traceValue,\n\t\"debug\":    debugValue,\n\t\"info\":     infoValue,\n\t\"warn\":     warnValue,\n\t\"error\":    errorValue,\n\t\"critical\": criticalValue,\n\t\"off\":      offValue,\n}\n\n\/\/ The logging structure\n\/\/ nice short name so use like:\n\/\/\n\/\/   var log *logger.L\n\/\/   log := logger.New(\"sometag\")\ntype L struct {\n\tsync.Mutex\n\ttag          string\n\tformatPrefix string\n\ttextPrefix   string\n\tlevel        string\n\tlevelNumber  int\n\tlog          seelog.LoggerInterface\n}\n\n\/\/ Pre-load default levels before creating any new logging channels\n\/\/ invalid levels are simply skipped and repeated calls will\n\/\/ accumulate new tag values and overwrite old tag values.\n\/\/\n\/\/ This will not update currently open channels, it is only for new\n\/\/ channels, it is intended to be called once after command-line\n\/\/ arguments and any configuration files have been processed to\n\/\/ establish logging defaults.\n\/\/\n\/\/ the name from \"DefaultTag\" is reserved to set a level for any tags that do not\n\/\/ have table entries.\nfunc LoadLevels(levels map[string]string) {\n\tfor tag, level := range levels {\n\t\t\/\/ make sure that levelMap only contains correct data\n\t\t\/\/ by ignoring invalid levels\n\t\tif _, ok := validLevels[level]; ok {\n\t\t\tlevelMap[tag] = level\n\t\t}\n\t}\n}\n\n\/\/ Setup seelog to used a rotated log file and output all logs\n\/\/ level control is now controlled by this module\nfunc Initialise(file string, size int, number int) error {\n\tconfig := fmt.Sprintf(`\n          <seelog type=\"adaptive\"\n                  mininterval=\"2000000\"\n                  maxinterval=\"100000000\"\n                  critmsgcount=\"500\"\n                  minlevel=\"trace\">\n              <outputs formatid=\"all\">\n                  <rollingfile type=\"size\" filename=\"%s\" maxsize=\"%d\" maxrolls=\"%d\" \/>\n              <\/outputs>\n              <formats>\n                  <format id=\"all\" format=\"%%Date %%Time [%%LEVEL] %%Msg%%n\" \/>\n              <\/formats>\n          <\/seelog>`, file, size, number)\n\n\tlogger, err := seelog.LoggerFromConfigAsString(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = seelog.ReplaceLogger(logger)\n\tif nil == err {\n\t\tseelog.Current.Warn(\"LOGGER: ===== Logging system started =====\")\n\t}\n\treturn err\n}\n\n\/\/ flush all channels\nfunc Finalise() {\n\tseelog.Current.Warn(\"LOGGER: ===== Logging system stopped =====\")\n\tseelog.Flush()\n}\n\n\/\/ flush all channels\nfunc Flush() {\n\tseelog.Flush()\n}\n\n\/\/ Open a new logging channel with a specified tag\nfunc New(tag string) *L {\n\n\t\/\/ map % -> %% to be printf safe\n\ts := strings.Split(tag, \"%\")\n\tj := strings.Join(s, \"%%\")\n\n\t\/\/ determine the initial level\n\tlevel, ok := levelMap[tag]\n\tif !ok {\n\t\tlevel, ok = levelMap[DefaultTag]\n\t}\n\tif !ok {\n\t\tlevel = \"error\"\n\t}\n\n\t\/\/ create a logger channel\n\treturn &L{\n\t\ttag:          tag, \/\/ for referencing default level\n\t\tformatPrefix: j + tagSuffix,\n\t\ttextPrefix:   tag + tagSuffix,\n\t\tlevel:        level,\n\t\tlevelNumber:  validLevels[level], \/\/ level is validated so get a non-zero value\n\t\tlog:          seelog.Current,\n\t}\n}\n\n\/\/ Change the log level for a given channel returns the current level\n\/\/\n\/\/ Use the value of DefaultTag to return to current default value.\n\/\/ Use the value \"\" to just return the current setting\nfunc (l *L) ChangeLevel(level string) string {\n\t\/\/ preserve current\n\tcurrent := l.level\n\n\t\/\/ to return to default level which may have been modified\n\t\/\/ by subsequent LoadLevels calls.\n\tif DefaultTag == level {\n\t\t\/\/ get currrent default level for this tag\n\t\tvar ok bool\n\t\tlevel, ok = levelMap[l.tag]\n\t\tif !ok {\n\t\t\tlevel, ok = levelMap[DefaultTag]\n\t\t}\n\t\tif !ok {\n\t\t\tlevel = DefaultLevel\n\t\t}\n\t} else if \"\" == level {\n\t\treturn current\n\t}\n\n\t\/\/ set level and corresponding number\n\tif n, ok := validLevels[level]; ok {\n\t\tl.Lock()\n\t\tdefer l.Unlock()\n\t\tl.level = level\n\t\tl.levelNumber = n\n\t}\n\treturn current\n}\n\n\/\/ flush messages\nfunc (l *L) Flush() {\n\tFlush()\n}\n<|endoftext|>"}
{"text":"<commit_before>package console\n\nimport (\n\t\"fmt\"\n\t\"github.com\/mgutz\/ansi\"\n\t\"path\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/Logger options\ntype Options struct {\n\tColors            ColorsOptions\n\tContextMediumSize int\n\tSpaceSize         int\n\tDefaultTags       []string\n}\n\ntype Show struct {\n\tTags     bool\n\tLocation bool\n\tTime     bool\n}\n\n\/\/A log location\ntype Location struct {\n\tFilename string\n\tLine     int\n}\n\n\/\/Logger struct stores log params\n\/\/up to the print\ntype Logger struct {\n\tLevel          string\n\tTags           []string\n\tTimestamp      int64\n\tContextMessage string\n\tMessage        string\n\tHooks          internalHooks\n\tShow\n\tLocation\n\tOptions\n}\n\n\/\/Reset the logger after print\nfunc (logger *Logger) reset() {\n\n\tlogger.Tags = []string{}\n\tlogger.Show = Show{}\n\n}\n\n\/\/Build the context string\n\/\/ie. tags, time, location\nfunc (logger *Logger) buildContext() {\n\n\tvar context string\n\n\t\/\/Build location\n\t_, logger.Location.Filename, logger.Location.Line, _ = runtime.Caller(3)\n\tlogger.Location.Filename = path.Base(logger.Location.Filename)\n\n\t\/\/Build time\n\tlogger.Timestamp = time.Now().Unix()\n\n\t\/\/Build context message\n\n\tif logger.Show.Tags {\n\t\tfor _, tag := range logger.Tags {\n\t\t\tcontext += \"[\" + tag + \"]\"\n\t\t}\n\t}\n\n\tif logger.Show.Location {\n\t\tcontext += \" [\" + logger.Location.Filename + \":\" + strconv.Itoa(logger.Location.Line) + \"] \"\n\t}\n\n\tif logger.Show.Time {\n\t\tcontext += time.Now().Format(time.RFC3339) + \" \"\n\t}\n\n\tlogger.ContextMessage = context\n}\n\n\/\/Print the log in console\n\/\/And fire hooks\nfunc (logger *Logger) PrintLog(color string, msg string, args ...interface{}) {\n\n\tif len(args) > 0 {\n\t\tlogger.Message = fmt.Sprintf(msg, args...)\n\t} else {\n\t\tlogger.Message = msg\n\t}\n\n\t\/\/Build context string\n\tlogger.buildContext()\n\n\t\/\/Fire hook\n\tlogger.Hooks.Fire(*logger)\n\n\t\/\/Print message to console\n\tfmt.Println(ansi.Color(\n\t\tlogger.ContextMessage+logger.Message,\n\t\tcolor,\n\t))\n\n\tlogger.reset()\n}\n\n\/\/Add tags to the log\nfunc (logger *Logger) Tag(args ...string) *Logger {\n\n\tlogger.Show.Tags = true\n\tlogger.Tags = append(logger.Tags, args...)\n\n\treturn logger\n}\n\n\/\/Add file and line information to the log\nfunc (logger *Logger) File() *Logger {\n\n\tlogger.Show.Location = true\n\n\treturn logger\n}\n\n\/\/Add time information to the log\nfunc (logger *Logger) Time() *Logger {\n\tlogger.Show.Time = true\n\n\treturn logger\n}\n\n\/\/Log functions\n\n\/\/Log level\n\/\/\tconsole.Log(\"Hello World\")\nfunc (logger *Logger) Log(msg string, args ...interface{}) {\n\tlogger.Level = \"log\"\n\tcolor := logger.Options.Colors[\"Log\"]\n\tlogger.PrintLog(color, msg, args...)\n}\n\n\/\/Info level\n\/\/\tconsole.Info(\"Hello World\")\nfunc (logger *Logger) Info(msg string, args ...interface{}) {\n\tlogger.Level = \"info\"\n\tcolor := logger.Options.Colors[\"Info\"]\n\tlogger.PrintLog(color, msg, args...)\n}\n\n\/\/Error level\n\/\/\tconsole.Error(\"Hello World\")\nfunc (logger *Logger) Error(msg string, args ...interface{}) {\n\tlogger.Level = \"error\"\n\tcolor := logger.Options.Colors[\"Error\"]\n\tlogger.PrintLog(color, msg, args...)\n}\n\n\/\/Warn level\n\/\/\tconsole.Warn(\"Hello World\")\nfunc (logger *Logger) Warning(msg string, args ...interface{}) {\n\tlogger.Level = \"warning\"\n\tcolor := logger.Options.Colors[\"Warning\"]\n\tlogger.PrintLog(color, msg, args...)\n}\n<commit_msg>Make PrintLog private<commit_after>package console\n\nimport (\n\t\"fmt\"\n\t\"github.com\/mgutz\/ansi\"\n\t\"path\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/Logger options\ntype Options struct {\n\tColors            ColorsOptions\n\tContextMediumSize int\n\tSpaceSize         int\n\tDefaultTags       []string\n}\n\ntype Show struct {\n\tTags     bool\n\tLocation bool\n\tTime     bool\n}\n\n\/\/A log location\ntype Location struct {\n\tFilename string\n\tLine     int\n}\n\n\/\/Logger struct stores log params\n\/\/up to the print\ntype Logger struct {\n\tLevel          string\n\tTags           []string\n\tTimestamp      int64\n\tContextMessage string\n\tMessage        string\n\tHooks          internalHooks\n\tShow\n\tLocation\n\tOptions\n}\n\n\/\/Reset the logger after print\nfunc (logger *Logger) reset() {\n\n\tlogger.Tags = []string{}\n\tlogger.Show = Show{}\n\n}\n\n\/\/Build the context string\n\/\/ie. tags, time, location\nfunc (logger *Logger) buildContext() {\n\n\tvar context string\n\n\t\/\/Build location\n\t_, logger.Location.Filename, logger.Location.Line, _ = runtime.Caller(3)\n\tlogger.Location.Filename = path.Base(logger.Location.Filename)\n\n\t\/\/Build time\n\tlogger.Timestamp = time.Now().Unix()\n\n\t\/\/Build context message\n\n\tif logger.Show.Tags {\n\t\tfor _, tag := range logger.Tags {\n\t\t\tcontext += \"[\" + tag + \"]\"\n\t\t}\n\t}\n\n\tif logger.Show.Location {\n\t\tcontext += \" [\" + logger.Location.Filename + \":\" + strconv.Itoa(logger.Location.Line) + \"] \"\n\t}\n\n\tif logger.Show.Time {\n\t\tcontext += time.Now().Format(time.RFC3339) + \" \"\n\t}\n\n\tlogger.ContextMessage = context\n}\n\n\/\/Print the log in console\n\/\/And fire hooks\nfunc (logger *Logger) printLog(color string, msg string, args ...interface{}) {\n\n\tif len(args) > 0 {\n\t\tlogger.Message = fmt.Sprintf(msg, args...)\n\t} else {\n\t\tlogger.Message = msg\n\t}\n\n\t\/\/Build context string\n\tlogger.buildContext()\n\n\t\/\/Fire hook\n\tlogger.Hooks.Fire(*logger)\n\n\t\/\/Print message to console\n\tfmt.Println(ansi.Color(\n\t\tlogger.ContextMessage+logger.Message,\n\t\tcolor,\n\t))\n\n\tlogger.reset()\n}\n\n\/\/Add tags to the log\nfunc (logger *Logger) Tag(args ...string) *Logger {\n\n\tlogger.Show.Tags = true\n\tlogger.Tags = append(logger.Tags, args...)\n\n\treturn logger\n}\n\n\/\/Add file and line information to the log\nfunc (logger *Logger) File() *Logger {\n\n\tlogger.Show.Location = true\n\n\treturn logger\n}\n\n\/\/Add time information to the log\nfunc (logger *Logger) Time() *Logger {\n\tlogger.Show.Time = true\n\n\treturn logger\n}\n\n\/\/Log functions\n\n\/\/Log level\n\/\/\tconsole.Log(\"Hello World\")\nfunc (logger *Logger) Log(msg string, args ...interface{}) {\n\tlogger.Level = \"log\"\n\tcolor := logger.Options.Colors[\"Log\"]\n\tlogger.printLog(color, msg, args...)\n}\n\n\/\/Info level\n\/\/\tconsole.Info(\"Hello World\")\nfunc (logger *Logger) Info(msg string, args ...interface{}) {\n\tlogger.Level = \"info\"\n\tcolor := logger.Options.Colors[\"Info\"]\n\tlogger.printLog(color, msg, args...)\n}\n\n\/\/Error level\n\/\/\tconsole.Error(\"Hello World\")\nfunc (logger *Logger) Error(msg string, args ...interface{}) {\n\tlogger.Level = \"error\"\n\tcolor := logger.Options.Colors[\"Error\"]\n\tlogger.printLog(color, msg, args...)\n}\n\n\/\/Warn level\n\/\/\tconsole.Warn(\"Hello World\")\nfunc (logger *Logger) Warning(msg string, args ...interface{}) {\n\tlogger.Level = \"warning\"\n\tcolor := logger.Options.Colors[\"Warning\"]\n\tlogger.printLog(color, msg, args...)\n}\n<|endoftext|>"}
{"text":"<commit_before>package logger\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"sync\/atomic\"\n)\n\n\/\/ Level describes the chosen log level\ntype Level int\n\n\/\/ LevelLogger represents levelled logger.\ntype LevelLogger struct {\n\tenabled int32\n\tlevel   Level\n\tprefix  string\n\tlogger  *log.Logger\n}\n\n\/\/ Enabled exists to prevent calling underlying logger methods when not needed.\n\/\/ This can also called from library users before calling LevelLogger methods\n\/\/ to reduce allocations.\nfunc (n *LevelLogger) Enabled() bool {\n\treturn atomic.LoadInt32(&n.enabled) != 0\n}\n\nvar callDepth = 2\n\n\/\/ Print calls underlying Logger Print func.\nfunc (n *LevelLogger) Print(v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\tn.logger.Output(callDepth, fmt.Sprint(v...))\n}\n\n\/\/ Printf calls underlying Logger Printf func.\nfunc (n *LevelLogger) Printf(format string, v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\tn.logger.Output(callDepth, fmt.Sprintf(format, v...))\n}\n\n\/\/ Println calls underlying Logger Println func.\nfunc (n *LevelLogger) Println(v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\tn.logger.Output(callDepth, fmt.Sprintln(v...))\n}\n\n\/\/ Fatal calls underlying Logger Fatal func.\nfunc (n *LevelLogger) Fatal(v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\tn.logger.Output(callDepth, fmt.Sprint(v...))\n\tos.Exit(1)\n}\n\n\/\/ Fatalf calls underlying Logger Fatalf func.\nfunc (n *LevelLogger) Fatalf(format string, v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\tn.logger.Output(callDepth, fmt.Sprintf(format, v...))\n\tos.Exit(1)\n}\n\n\/\/ Fatalln calls underlying Logger Fatalln func.\nfunc (n *LevelLogger) Fatalln(v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\tn.logger.Output(callDepth, fmt.Sprintln(v...))\n\tos.Exit(1)\n}\n\n\/\/ Panic calls underlying Logger Panic func.\nfunc (n *LevelLogger) Panic(v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\ts := fmt.Sprint(v...)\n\tn.logger.Output(callDepth, s)\n\tpanic(s)\n}\n\n\/\/ Panicf calls underlying Logger Panicf func.\nfunc (n *LevelLogger) Panicf(format string, v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\ts := fmt.Sprintf(format, v...)\n\tn.logger.Output(callDepth, s)\n\tpanic(s)\n}\n\n\/\/ Panicln calls underlying Logger Panicln func.\nfunc (n *LevelLogger) Panicln(v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\ts := fmt.Sprintln(v...)\n\tn.logger.Output(callDepth, s)\n\tpanic(s)\n}\n\nconst (\n\tLevelTrace Level = iota\n\tLevelDebug\n\tLevelInfo\n\tLevelWarn\n\tLevelError\n\tLevelCritical\n\tLevelFatal\n\tLevelNone\n\n\tDefaultLogThreshold    = LevelInfo\n\tDefaultStdoutThreshold = LevelInfo\n)\n\nvar (\n\tlogger *log.Logger\n\n\tLogHandle  io.Writer = ioutil.Discard\n\tOutHandle  io.Writer = os.Stdout\n\tBothHandle io.Writer = io.MultiWriter(LogHandle, OutHandle)\n\n\tFlag int = log.Ldate | log.Ltime\n\n\tTRACE    *LevelLogger = &LevelLogger{level: LevelTrace, logger: logger, prefix: \"[T]: \"}\n\tDEBUG    *LevelLogger = &LevelLogger{level: LevelDebug, logger: logger, prefix: \"[D]: \"}\n\tINFO     *LevelLogger = &LevelLogger{level: LevelInfo, logger: logger, prefix: \"[I]: \"}\n\tWARN     *LevelLogger = &LevelLogger{level: LevelWarn, logger: logger, prefix: \"[W]: \"}\n\tERROR    *LevelLogger = &LevelLogger{level: LevelError, logger: logger, prefix: \"[E]: \"}\n\tCRITICAL *LevelLogger = &LevelLogger{level: LevelCritical, logger: logger, prefix: \"[C]: \"}\n\tFATAL    *LevelLogger = &LevelLogger{level: LevelFatal, logger: logger, prefix: \"[F]: \"}\n\n\tloggers []*LevelLogger = []*LevelLogger{TRACE, DEBUG, INFO, WARN, ERROR, CRITICAL, FATAL}\n\n\tlogThreshold    Level = DefaultLogThreshold\n\toutputThreshold Level = DefaultStdoutThreshold\n)\n\nvar LevelMatches = map[string]Level{\n\t\"TRACE\":    LevelTrace,\n\t\"DEBUG\":    LevelDebug,\n\t\"INFO\":     LevelInfo,\n\t\"WARN\":     LevelWarn,\n\t\"ERROR\":    LevelError,\n\t\"CRITICAL\": LevelCritical,\n\t\"FATAL\":    LevelFatal,\n\t\"NONE\":     LevelNone,\n}\n\nfunc init() {\n\tinitialize()\n}\n\n\/\/ initialize initializes loggers.\nfunc initialize() {\n\tBothHandle = io.MultiWriter(LogHandle, OutHandle)\n\tfor _, l := range loggers {\n\n\t\tvar handler io.Writer\n\t\tvar enabled int32\n\n\t\tif l.level < outputThreshold && l.level < logThreshold {\n\t\t\tenabled = 0\n\t\t\thandler = ioutil.Discard\n\t\t} else if l.level >= outputThreshold && l.level >= logThreshold {\n\t\t\tenabled = 1\n\t\t\thandler = BothHandle\n\t\t} else if l.level >= outputThreshold && l.level < logThreshold {\n\t\t\tenabled = 1\n\t\t\thandler = OutHandle\n\t\t} else {\n\t\t\tenabled = 1\n\t\t\thandler = LogHandle\n\t\t}\n\n\t\tatomic.StoreInt32(&l.enabled, 0)\n\t\tl.logger = log.New(handler, l.prefix, Flag)\n\t\tatomic.StoreInt32(&l.enabled, enabled)\n\t}\n}\n\n\/\/ Ensures that the level provided is within the bounds of available levels.\nfunc levelCheck(level Level) Level {\n\tswitch {\n\tcase level <= LevelTrace:\n\t\treturn LevelTrace\n\tcase level >= LevelFatal:\n\t\treturn LevelFatal\n\tdefault:\n\t\treturn level\n\t}\n}\n\n\/\/ SetLogThreshold establishes a threshold where anything matching or above will be logged.\nfunc SetLogThreshold(level Level) {\n\tthresholdChanged := level != logThreshold\n\tif thresholdChanged {\n\t\tlogThreshold = levelCheck(level)\n\t\tinitialize()\n\t}\n}\n\n\/\/ SetStdoutThreshold establishes a threshold where anything matching or above will be output.\nfunc SetStdoutThreshold(level Level) {\n\tthresholdChanged := level != outputThreshold\n\tif thresholdChanged {\n\t\toutputThreshold = levelCheck(level)\n\t\tinitialize()\n\t}\n}\n\n\/\/ SetLogFile sets the LogHandle to a io.writer created for the file behind the given file path.\n\/\/ Will append to this file.\nfunc SetLogFile(path string) error {\n\tfile, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tLogHandle = file\n\tinitialize()\n\treturn nil\n}\n\n\/\/ SetLogFlag sets global log flag used in package.\nfunc SetLogFlag(flag int) {\n\tflagChanged := flag != Flag\n\tFlag = flag\n\tif flagChanged {\n\t\tinitialize()\n\t}\n}\n<commit_msg>make LevelLogger implement io.Writer<commit_after>package logger\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"sync\/atomic\"\n)\n\n\/\/ Level describes the chosen log level\ntype Level int\n\n\/\/ LevelLogger represents levelled logger.\ntype LevelLogger struct {\n\tenabled int32\n\tlevel   Level\n\tprefix  string\n\tlogger  *log.Logger\n}\n\n\/\/ Enabled exists to prevent calling underlying logger methods when not needed.\n\/\/ This can also called from library users before calling LevelLogger methods\n\/\/ to reduce allocations.\nfunc (n *LevelLogger) Enabled() bool {\n\treturn atomic.LoadInt32(&n.enabled) != 0\n}\n\nvar callDepth = 2\n\n\/\/ Write allows LevelLogger to implement io.Writer interface so we can use it\n\/\/ as output for other loggers.\nfunc (n *LevelLogger) Write(p []byte) (int, error) {\n\tif !n.Enabled() {\n\t\treturn len(p), nil\n\t}\n\tn.Printf(\"%s\", p)\n\treturn len(p), nil\n}\n\n\/\/ Print calls underlying Logger Print func.\nfunc (n *LevelLogger) Print(v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\tn.logger.Output(callDepth, fmt.Sprint(v...))\n}\n\n\/\/ Printf calls underlying Logger Printf func.\nfunc (n *LevelLogger) Printf(format string, v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\tn.logger.Output(callDepth, fmt.Sprintf(format, v...))\n}\n\n\/\/ Println calls underlying Logger Println func.\nfunc (n *LevelLogger) Println(v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\tn.logger.Output(callDepth, fmt.Sprintln(v...))\n}\n\n\/\/ Fatal calls underlying Logger Fatal func.\nfunc (n *LevelLogger) Fatal(v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\tn.logger.Output(callDepth, fmt.Sprint(v...))\n\tos.Exit(1)\n}\n\n\/\/ Fatalf calls underlying Logger Fatalf func.\nfunc (n *LevelLogger) Fatalf(format string, v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\tn.logger.Output(callDepth, fmt.Sprintf(format, v...))\n\tos.Exit(1)\n}\n\n\/\/ Fatalln calls underlying Logger Fatalln func.\nfunc (n *LevelLogger) Fatalln(v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\tn.logger.Output(callDepth, fmt.Sprintln(v...))\n\tos.Exit(1)\n}\n\n\/\/ Panic calls underlying Logger Panic func.\nfunc (n *LevelLogger) Panic(v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\ts := fmt.Sprint(v...)\n\tn.logger.Output(callDepth, s)\n\tpanic(s)\n}\n\n\/\/ Panicf calls underlying Logger Panicf func.\nfunc (n *LevelLogger) Panicf(format string, v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\ts := fmt.Sprintf(format, v...)\n\tn.logger.Output(callDepth, s)\n\tpanic(s)\n}\n\n\/\/ Panicln calls underlying Logger Panicln func.\nfunc (n *LevelLogger) Panicln(v ...interface{}) {\n\tif !n.Enabled() {\n\t\treturn\n\t}\n\ts := fmt.Sprintln(v...)\n\tn.logger.Output(callDepth, s)\n\tpanic(s)\n}\n\nconst (\n\tLevelTrace Level = iota\n\tLevelDebug\n\tLevelInfo\n\tLevelWarn\n\tLevelError\n\tLevelCritical\n\tLevelFatal\n\tLevelNone\n\n\tDefaultLogThreshold    = LevelInfo\n\tDefaultStdoutThreshold = LevelInfo\n)\n\nvar (\n\tlogger *log.Logger\n\n\tLogHandle  io.Writer = ioutil.Discard\n\tOutHandle  io.Writer = os.Stdout\n\tBothHandle io.Writer = io.MultiWriter(LogHandle, OutHandle)\n\n\tFlag int = log.Ldate | log.Ltime\n\n\tTRACE    *LevelLogger = &LevelLogger{level: LevelTrace, logger: logger, prefix: \"[T]: \"}\n\tDEBUG    *LevelLogger = &LevelLogger{level: LevelDebug, logger: logger, prefix: \"[D]: \"}\n\tINFO     *LevelLogger = &LevelLogger{level: LevelInfo, logger: logger, prefix: \"[I]: \"}\n\tWARN     *LevelLogger = &LevelLogger{level: LevelWarn, logger: logger, prefix: \"[W]: \"}\n\tERROR    *LevelLogger = &LevelLogger{level: LevelError, logger: logger, prefix: \"[E]: \"}\n\tCRITICAL *LevelLogger = &LevelLogger{level: LevelCritical, logger: logger, prefix: \"[C]: \"}\n\tFATAL    *LevelLogger = &LevelLogger{level: LevelFatal, logger: logger, prefix: \"[F]: \"}\n\n\tloggers []*LevelLogger = []*LevelLogger{TRACE, DEBUG, INFO, WARN, ERROR, CRITICAL, FATAL}\n\n\tlogThreshold    Level = DefaultLogThreshold\n\toutputThreshold Level = DefaultStdoutThreshold\n)\n\nvar LevelMatches = map[string]Level{\n\t\"TRACE\":    LevelTrace,\n\t\"DEBUG\":    LevelDebug,\n\t\"INFO\":     LevelInfo,\n\t\"WARN\":     LevelWarn,\n\t\"ERROR\":    LevelError,\n\t\"CRITICAL\": LevelCritical,\n\t\"FATAL\":    LevelFatal,\n\t\"NONE\":     LevelNone,\n}\n\nfunc init() {\n\tinitialize()\n}\n\n\/\/ initialize initializes loggers.\nfunc initialize() {\n\tBothHandle = io.MultiWriter(LogHandle, OutHandle)\n\tfor _, l := range loggers {\n\n\t\tvar handler io.Writer\n\t\tvar enabled int32\n\n\t\tif l.level < outputThreshold && l.level < logThreshold {\n\t\t\tenabled = 0\n\t\t\thandler = ioutil.Discard\n\t\t} else if l.level >= outputThreshold && l.level >= logThreshold {\n\t\t\tenabled = 1\n\t\t\thandler = BothHandle\n\t\t} else if l.level >= outputThreshold && l.level < logThreshold {\n\t\t\tenabled = 1\n\t\t\thandler = OutHandle\n\t\t} else {\n\t\t\tenabled = 1\n\t\t\thandler = LogHandle\n\t\t}\n\n\t\tatomic.StoreInt32(&l.enabled, 0)\n\t\tl.logger = log.New(handler, l.prefix, Flag)\n\t\tatomic.StoreInt32(&l.enabled, enabled)\n\t}\n}\n\n\/\/ Ensures that the level provided is within the bounds of available levels.\nfunc levelCheck(level Level) Level {\n\tswitch {\n\tcase level <= LevelTrace:\n\t\treturn LevelTrace\n\tcase level >= LevelFatal:\n\t\treturn LevelFatal\n\tdefault:\n\t\treturn level\n\t}\n}\n\n\/\/ SetLogThreshold establishes a threshold where anything matching or above will be logged.\nfunc SetLogThreshold(level Level) {\n\tthresholdChanged := level != logThreshold\n\tif thresholdChanged {\n\t\tlogThreshold = levelCheck(level)\n\t\tinitialize()\n\t}\n}\n\n\/\/ SetStdoutThreshold establishes a threshold where anything matching or above will be output.\nfunc SetStdoutThreshold(level Level) {\n\tthresholdChanged := level != outputThreshold\n\tif thresholdChanged {\n\t\toutputThreshold = levelCheck(level)\n\t\tinitialize()\n\t}\n}\n\n\/\/ SetLogFile sets the LogHandle to a io.writer created for the file behind the given file path.\n\/\/ Will append to this file.\nfunc SetLogFile(path string) error {\n\tfile, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tLogHandle = file\n\tinitialize()\n\treturn nil\n}\n\n\/\/ SetLogFlag sets global log flag used in package.\nfunc SetLogFlag(flag int) {\n\tflagChanged := flag != Flag\n\tFlag = flag\n\tif flagChanged {\n\t\tinitialize()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 The go-logger Authors. All rights reserved.\n\/\/ This code is MIT licensed. See the LICENSE file for more info.\n\n\/\/ Package logger is a better logging system for Go than the generic log\n\/\/ package in the Go Standard Library. The logger packages provides colored\n\/\/ output, logging levels, custom log formatting, and simultaneous logging\n\/\/ output stream to stdout, stderr, and os.File.\npackage logger\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"runtime\"\n\t\"sync\"\n\t\"text\/template\"\n\t\"time\"\n)\n\n\/\/ Used for string output of the logging object\nvar levels = [5]string{\n\t\"DEBUG\",\n\t\"INFO\",\n\t\"WARNING\",\n\t\"ERROR\",\n\t\"CRITICAL\",\n}\n\ntype level int\n\n\/\/ Returns the string representation of the level\nfunc (l level) String() string { return levels[l] }\n\n\/\/ The DEBUG level is the lowest possible output level. This is meant for\n\/\/ development use. The default output level is WARNING.\nconst (\n\t\/\/ DEBUG level messages should be used for development logging instead\n\t\/\/ of Printf calls. When used in this manner, instead of sprinkling\n\t\/\/ Printf calls everywhere and then having to remove them once the bug\n\t\/\/ is fixed, the developer can simply change to a higher logging level\n\t\/\/ and the debug messages will not be sent to the output stream.\n\tDEBUG level = iota\n\t\/\/ Info level messages should be used to convey more informative output\n\t\/\/ than debug that could be used by a user.\n\tINFO\n\t\/\/ Warning messages should be used to notify the user that something\n\t\/\/ worked, but the expected value was not the result.\n\tWARNING\n\t\/\/ Error messages should be used when something just did not work at\n\t\/\/ all.\n\tERROR\n\t\/\/ Critical messages are used when something is completely broken and\n\t\/\/ unrecoverable. Critical messages are usually followed by os.Exit().\n\tCRITICAL\n)\n\n\/\/ These flags define which text to prefix to each log entry generated by the Logger.\nconst (\n\t\/\/ Bits or'ed together to control what's printed.\n\tLdate = 1 << iota\n\t\/\/ full file name and line number: \/a\/b\/c\/d.go:23\n\tLlongfile\n\t\/\/ base file name and line number: d.go:23. overrides Llongfile\n\tLshortfile\n\t\/\/ Use ansi escape sequences\n\tLansi\n\t\/\/ initial values for the standard logger\n\tLstdFlags = Ldate | Lansi\n)\n\nvar (\n\tdefPrefix      = \">>>\"\n\tdefColorPrefix = AnsiEscape(BOLD, GREEN, \">>>\", OFF)\n\t\/\/ std is the default logger object\n\tlog = New(os.Stderr, WARNING)\n)\n\n\/\/ A Logger represents an active logging object that generates lines of output\n\/\/ to an io.Writer. Each logging operation makes a single call to the Writer's\n\/\/ Write method. A Logger can be used simultaneously from multiple goroutines;\n\/\/ it guarantees to serialize access to the Writer.\ntype Logger struct {\n\tmu         sync.Mutex         \/\/ Ensures atomic writes\n\tbuf        []byte             \/\/ For marshaling output to write\n\tColors     bool               \/\/ Enable\/Disable colored output\n\tDateFormat string             \/\/ time.RubyDate is the default format\n\tFlags      int                \/\/ Properties of the output\n\tLevel      level              \/\/ The default level is warning\n\tTemplate   *template.Template \/\/ The format order of the output\n\tPrefix     string             \/\/ Inserted into every logging output\n\tStream     io.Writer          \/\/ Destination for output\n}\n\n\/\/ formatOutput is used by Output() to apply the desired output format using\n\/\/ the logTemplate. Using this template, an output string is built containing\n\/\/ the desired structure such as prefix, date, and file + line number.\nfunc (l *Logger) formatOutput(buf *[]byte, t time.Time, file string,\n\tline int, text string) {\n\tl.buf = append(l.buf, t.Format(l.dateFormat)...)\n\tif len(text) > 0 && text[len(text)-1] != '\\n' {\n\t\tl.buf = append(l.buf, '\\n')\n\t}\n}\n\n\/\/ Output is used by all of the logging functions to send output to the output\n\/\/ stream.\n\/\/\n\/\/ calldepth is the number of stack frames to skip when getting the file\n\/\/ name of original calling function for file name output.\n\/\/\n\/\/ text is the string to append to the assembled log format output.\n\/\/\n\/\/ stream will be used as the output stream the text will be written to. If\n\/\/ stream is nil, the stream value contained in the logger object is used.\nfunc (l *Logger) Fprint(calldepth int,\n\ttext string, stream io.Writer) (n int, err error) {\n\tnow := time.Now()\n\tvar file string\n\tvar line int\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tif l.Flags&(Lshortfile|Llongfile) != 0 {\n\t\t\/\/ release lock while getting caller info - it's expensive.\n\t\tl.mu.Unlock()\n\t\tvar ok bool\n\t\t_, file, line, ok = runtime.Caller(calldepth)\n\t\tif !ok {\n\t\t\tfile = \"???\"\n\t\t\tline = 0\n\t\t}\n\t\tl.mu.Lock()\n\t}\n\tl.buf = l.buf[:0]\n\tl.formatOutput(&l.buf, now, file, line, text)\n\tif stream == nil {\n\t\tn, err = l.Stream.Write(l.buf)\n\t} else {\n\t\tn, err = stream.Write(l.buf)\n\t}\n\treturn int(n), err\n}\n\n\/\/ Print sends output to the standard logger output stream regardless of\n\/\/ logging level including the logger format properties and flags. Spaces are\n\/\/ added between operands when neither is a string. It returns the number of\n\/\/ bytes written and any write error encountered.\nfunc (l *Logger) Print(v ...interface{}) (n int, err error) {\n\treturn l.Fprint(2, fmt.Sprint(v...), os.Stdout)\n}\n\n\/\/ Println formats using the default formats for its operands and writes to\n\/\/ standard output. Spaces are always added between operands and a newline is\n\/\/ appended. It returns the number of bytes written and any write error\n\/\/ encountered.\nfunc (l *Logger) Println(v ...interface{}) (n int, err error) {\n\treturn l.Fprint(2, fmt.Sprintln(v...), os.Stdout)\n}\n\n\/\/ Printf formats according to a format specifier and writes to standard\n\/\/ output. It returns the number of bytes written and any write error\n\/\/ encountered.\nfunc (l *Logger) Printf(format string, v ...interface{}) (n int, err error) {\n\treturn l.Fprint(2, fmt.Sprintf(format, v...), os.Stdout)\n}\n\n\/\/ New creates a new logger object and returns it.\nfunc New(stream io.Writer, level level) (obj *Logger) {\n\ttmpl := template.Must(template.New(\"std\").Funcs(funcMap).Parse(logFmt))\n\tobj = &Logger{Stream: stream, Colors: true, DateFormat: time.RubyDate,\n\t\tFlags: LstdFlags, Level: level, Template: tmpl,\n\t\tPrefix: defColorPrefix}\n\treturn\n}\n<commit_msg>Remove formatOutput()<commit_after>\/\/ Copyright 2013 The go-logger Authors. All rights reserved.\n\/\/ This code is MIT licensed. See the LICENSE file for more info.\n\n\/\/ Package logger is a better logging system for Go than the generic log\n\/\/ package in the Go Standard Library. The logger packages provides colored\n\/\/ output, logging levels, custom log formatting, and simultaneous logging\n\/\/ output stream to stdout, stderr, and os.File.\npackage logger\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"runtime\"\n\t\"sync\"\n\t\"text\/template\"\n\t\"time\"\n)\n\n\/\/ Used for string output of the logging object\nvar levels = [5]string{\n\t\"DEBUG\",\n\t\"INFO\",\n\t\"WARNING\",\n\t\"ERROR\",\n\t\"CRITICAL\",\n}\n\ntype level int\n\n\/\/ Returns the string representation of the level\nfunc (l level) String() string { return levels[l] }\n\n\/\/ The DEBUG level is the lowest possible output level. This is meant for\n\/\/ development use. The default output level is WARNING.\nconst (\n\t\/\/ DEBUG level messages should be used for development logging instead\n\t\/\/ of Printf calls. When used in this manner, instead of sprinkling\n\t\/\/ Printf calls everywhere and then having to remove them once the bug\n\t\/\/ is fixed, the developer can simply change to a higher logging level\n\t\/\/ and the debug messages will not be sent to the output stream.\n\tDEBUG level = iota\n\t\/\/ Info level messages should be used to convey more informative output\n\t\/\/ than debug that could be used by a user.\n\tINFO\n\t\/\/ Warning messages should be used to notify the user that something\n\t\/\/ worked, but the expected value was not the result.\n\tWARNING\n\t\/\/ Error messages should be used when something just did not work at\n\t\/\/ all.\n\tERROR\n\t\/\/ Critical messages are used when something is completely broken and\n\t\/\/ unrecoverable. Critical messages are usually followed by os.Exit().\n\tCRITICAL\n)\n\n\/\/ These flags define which text to prefix to each log entry generated by the Logger.\nconst (\n\t\/\/ Bits or'ed together to control what's printed.\n\tLdate = 1 << iota\n\t\/\/ full file name and line number: \/a\/b\/c\/d.go:23\n\tLlongfile\n\t\/\/ base file name and line number: d.go:23. overrides Llongfile\n\tLshortfile\n\t\/\/ Use ansi escape sequences\n\tLansi\n\t\/\/ initial values for the standard logger\n\tLstdFlags = Ldate | Lansi\n)\n\nvar (\n\tdefPrefix      = \">>>\"\n\tdefColorPrefix = AnsiEscape(BOLD, GREEN, \">>>\", OFF)\n\t\/\/ std is the default logger object\n\tlog = New(os.Stderr, WARNING)\n)\n\n\/\/ A Logger represents an active logging object that generates lines of output\n\/\/ to an io.Writer. Each logging operation makes a single call to the Writer's\n\/\/ Write method. A Logger can be used simultaneously from multiple goroutines;\n\/\/ it guarantees to serialize access to the Writer.\ntype Logger struct {\n\tmu         sync.Mutex         \/\/ Ensures atomic writes\n\tbuf        []byte             \/\/ For marshaling output to write\n\tColors     bool               \/\/ Enable\/Disable colored output\n\tDateFormat string             \/\/ time.RubyDate is the default format\n\tFlags      int                \/\/ Properties of the output\n\tLevel      level              \/\/ The default level is warning\n\tTemplate   *template.Template \/\/ The format order of the output\n\tPrefix     string             \/\/ Inserted into every logging output\n\tStream     io.Writer          \/\/ Destination for output\n}\n\n\/\/ Output is used by all of the logging functions to send output to the output\n\/\/ stream.\n\/\/\n\/\/ calldepth is the number of stack frames to skip when getting the file\n\/\/ name of original calling function for file name output.\n\/\/\n\/\/ text is the string to append to the assembled log format output.\n\/\/\n\/\/ stream will be used as the output stream the text will be written to. If\n\/\/ stream is nil, the stream value contained in the logger object is used.\nfunc (l *Logger) Fprint(calldepth int,\n\ttext string, stream io.Writer) (n int, err error) {\n\tnow := time.Now()\n\tvar file string\n\tvar line int\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tif l.Flags&(Lshortfile|Llongfile) != 0 {\n\t\t\/\/ release lock while getting caller info - it's expensive.\n\t\tl.mu.Unlock()\n\t\tvar ok bool\n\t\t_, file, line, ok = runtime.Caller(calldepth)\n\t\tif !ok {\n\t\t\tfile = \"???\"\n\t\t\tline = 0\n\t\t}\n\t\tl.mu.Lock()\n\t}\n\tl.buf = l.buf[:0]\n\tif stream == nil {\n\t\tn, err = l.Stream.Write(l.buf)\n\t} else {\n\t\tn, err = stream.Write(l.buf)\n\t}\n\treturn int(n), err\n}\n\n\/\/ Print sends output to the standard logger output stream regardless of\n\/\/ logging level including the logger format properties and flags. Spaces are\n\/\/ added between operands when neither is a string. It returns the number of\n\/\/ bytes written and any write error encountered.\nfunc (l *Logger) Print(v ...interface{}) (n int, err error) {\n\treturn l.Fprint(2, fmt.Sprint(v...), os.Stdout)\n}\n\n\/\/ Println formats using the default formats for its operands and writes to\n\/\/ standard output. Spaces are always added between operands and a newline is\n\/\/ appended. It returns the number of bytes written and any write error\n\/\/ encountered.\nfunc (l *Logger) Println(v ...interface{}) (n int, err error) {\n\treturn l.Fprint(2, fmt.Sprintln(v...), os.Stdout)\n}\n\n\/\/ Printf formats according to a format specifier and writes to standard\n\/\/ output. It returns the number of bytes written and any write error\n\/\/ encountered.\nfunc (l *Logger) Printf(format string, v ...interface{}) (n int, err error) {\n\treturn l.Fprint(2, fmt.Sprintf(format, v...), os.Stdout)\n}\n\n\/\/ New creates a new logger object and returns it.\nfunc New(stream io.Writer, level level) (obj *Logger) {\n\ttmpl := template.Must(template.New(\"std\").Funcs(funcMap).Parse(logFmt))\n\tobj = &Logger{Stream: stream, Colors: true, DateFormat: time.RubyDate,\n\t\tFlags: LstdFlags, Level: level, Template: tmpl,\n\t\tPrefix: defColorPrefix}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/xml\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"net\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/prometheus\/common\/log\"\n)\n\nconst (\n\tnamespace = \"bind\"\n)\n\nvar (\n\tup = prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, \"\", \"up\"),\n\t\t\"Was the Bind instance query successful?\",\n\t\tnil, nil,\n\t)\n\tincomingQueries = prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, \"\", \"incoming_queries_total\"),\n\t\t\"Number of incomming DNS queries.\",\n\t\t[]string{\"name\"}, nil,\n\t)\n\tincomingRequests = prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, \"\", \"incoming_requests_total\"),\n\t\t\"Number of incomming DNS queries.\",\n\t\t[]string{\"name\"}, nil,\n\t)\n\tresolverQueries = prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, \"\", \"resolver_queries_total\"),\n\t\t\"Number of outgoing DNS queries.\",\n\t\t[]string{\"view\", \"name\"}, nil,\n\t)\n\tresolverQueryDuration = prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, \"\", \"resolver_query_duration_seconds\"),\n\t\t\"Resolver query round-trip time in seconds.\",\n\t\t[]string{\"view\"}, nil,\n\t)\n)\n\n\/\/ Exporter collects Binds stats from the given server and exports\n\/\/ them using the prometheus metrics package.\ntype Exporter struct {\n\tURI    string\n\tclient *http.Client\n}\n\n\/\/ NewExporter returns an initialized Exporter.\nfunc NewExporter(uri string, timeout time.Duration) *Exporter {\n\treturn &Exporter{\n\t\tURI: uri,\n\t\tclient: &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDial: func(netw, addr string) (net.Conn, error) {\n\t\t\t\t\tc, err := net.DialTimeout(netw, addr, timeout)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tif err := c.SetDeadline(time.Now().Add(timeout)); err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\treturn c, nil\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\n\/\/ Describe describes all the metrics ever exported by the bind\n\/\/ exporter. It implements prometheus.Collector.\nfunc (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tch <- up\n\tch <- incomingQueries\n\tch <- incomingRequests\n\tch <- resolverQueries\n\tch <- resolverQueryDuration\n}\n\n\/\/ Collect fetches the stats from configured bind location and\n\/\/ delivers them as Prometheus metrics. It implements prometheus.Collector.\nfunc (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tvar status float64\n\tdefer func() {\n\t\tch <- prometheus.MustNewConstMetric(up, prometheus.GaugeValue, status)\n\t}()\n\n\tresp, err := e.client.Get(e.URI)\n\tif err != nil {\n\t\tlog.Error(\"Error while querying Bind: \", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Error(\"Failed to read XML response body: \", err)\n\t\treturn\n\t}\n\n\tstatus = 1\n\n\troot := Isc{}\n\tif err := xml.Unmarshal([]byte(body), &root); err != nil {\n\t\tlog.Error(\"Failed to unmarshal XML response: \", err)\n\t\treturn\n\t}\n\n\tserverNode := root.Bind.Statistics.Server\n\tfor _, s := range serverNode.QueriesIn.Rdtype {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tincomingQueries, prometheus.CounterValue, float64(s.Counter), s.Name,\n\t\t)\n\t}\n\tfor _, s := range serverNode.Requests.Opcode {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tincomingRequests, prometheus.CounterValue, float64(s.Counter), s.Name,\n\t\t)\n\t}\n\n\tfor _, v := range root.Bind.Statistics.Views {\n\t\tfor _, s := range v.Rdtype {\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tresolverQueries, prometheus.CounterValue, float64(s.Counter), v.Name, s.Name,\n\t\t\t)\n\t\t}\n\n\t\tif buckets, count, err := histogram(v.Resstat); err == nil {\n\t\t\tch <- prometheus.MustNewConstHistogram(\n\t\t\t\tresolverQueryDuration, count, math.NaN(), buckets, v.Name,\n\t\t\t)\n\t\t} else {\n\t\t\tlog.Warn(\"Error parsing RTT:\", err)\n\t\t}\n\t}\n}\n\nfunc histogram(stats []Stat) (map[float64]uint64, uint64, error) {\n\tbuckets := map[float64]uint64{}\n\tvar count uint64\n\n\tfor _, s := range stats {\n\t\tif strings.HasPrefix(s.Name, qryRTT) {\n\t\t\tb := math.Inf(0)\n\t\t\tif !strings.HasSuffix(s.Name, \"+\") {\n\t\t\t\tvar err error\n\t\t\t\trrt := strings.TrimPrefix(s.Name, qryRTT)\n\t\t\t\tb, err = strconv.ParseFloat(rrt, 32)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn buckets, 0, fmt.Errorf(\"could not parse RTT: %s\", rrt)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbuckets[b\/1000] = count + uint64(s.Counter)\n\t\t\tcount += uint64(s.Counter)\n\t\t}\n\t}\n\treturn buckets, count, nil\n}\n\nfunc main() {\n\tvar (\n\t\tlistenAddress = flag.String(\"web.listen-address\", \":9109\", \"Address to listen on for web interface and telemetry.\")\n\t\tmetricsPath   = flag.String(\"web.telemetry-path\", \"\/metrics\", \"Path under which to expose metrics.\")\n\t\tbindURI       = flag.String(\"bind.statsuri\", \"http:\/\/localhost:8053\/\", \"HTTP XML API address of an Bind server.\")\n\t\tbindTimeout   = flag.Duration(\"bind.timeout\", 10*time.Second, \"Timeout for trying to get stats from Bind.\")\n\t\tbindPidFile   = flag.String(\"bind.pid-file\", \"\", \"Path to Bind's pid file to export process information.\")\n\t)\n\tflag.Parse()\n\n\tprometheus.MustRegister(NewExporter(*bindURI, *bindTimeout))\n\tif *bindPidFile != \"\" {\n\t\tprocExporter := prometheus.NewProcessCollectorPIDFn(\n\t\t\tfunc() (int, error) {\n\t\t\t\tcontent, err := ioutil.ReadFile(*bindPidFile)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"Can't read pid file: %s\", err)\n\t\t\t\t}\n\t\t\t\tvalue, err := strconv.Atoi(strings.TrimSpace(string(content)))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"Can't parse pid file: %s\", err)\n\t\t\t\t}\n\t\t\t\treturn value, nil\n\t\t\t}, namespace)\n\t\tprometheus.MustRegister(procExporter)\n\t}\n\n\tlog.Info(\"Starting Server: \", *listenAddress)\n\thttp.Handle(*metricsPath, prometheus.Handler())\n\thttp.HandleFunc(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(`<html>\n             <head><title>Bind Exporter<\/title><\/head>\n             <body>\n             <h1>Bind Exporter<\/h1>\n             <p><a href='` + *metricsPath + `'>Metrics<\/a><\/p>\n             <\/body>\n             <\/html>`))\n\t})\n\tlog.Fatal(http.ListenAndServe(*listenAddress, nil))\n}\n<commit_msg>Add majority of resolver statistics<commit_after>package main\n\nimport (\n\t\"encoding\/xml\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"net\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/prometheus\/common\/log\"\n)\n\nconst (\n\tnamespace = \"bind\"\n\tresolver  = \"resolver\"\n)\n\nvar (\n\tup = prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, \"\", \"up\"),\n\t\t\"Was the Bind instance query successful?\",\n\t\tnil, nil,\n\t)\n\tincomingQueries = prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, \"\", \"incoming_queries_total\"),\n\t\t\"Number of incomming DNS queries.\",\n\t\t[]string{\"name\"}, nil,\n\t)\n\tincomingRequests = prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, \"\", \"incoming_requests_total\"),\n\t\t\"Number of incomming DNS queries.\",\n\t\t[]string{\"name\"}, nil,\n\t)\n\tresolverQueries = prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, resolver, \"queries_total\"),\n\t\t\"Number of outgoing DNS queries.\",\n\t\t[]string{\"view\", \"name\"}, nil,\n\t)\n\tresolverQueryDuration = prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, resolver, \"query_duration_seconds\"),\n\t\t\"Resolver query round-trip time in seconds.\",\n\t\t[]string{\"view\"}, nil,\n\t)\n\tresolverQueryErrors = prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, resolver, \"query_errors_total\"),\n\t\t\"Number of resolver queries failed.\",\n\t\t[]string{\"view\", \"error\"}, nil,\n\t)\n\tresolverResponseErrors = prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, resolver, \"response_errors_total\"),\n\t\t\"Number of resolver reponse errors received.\",\n\t\t[]string{\"view\", \"error\"}, nil,\n\t)\n\tresolverDNSSECSucess = prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, resolver, \"dnssec_validation_success_total\"),\n\t\t\"Number of DNSSEC validation attempts succeeded.\",\n\t\t[]string{\"view\", \"result\"}, nil,\n\t)\n\tresolverMetricStats = map[string]*prometheus.Desc{\n\t\t\"Lame\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, resolver, \"response_lame_total\"),\n\t\t\t\"Number of lame delegation responses received.\",\n\t\t\t[]string{\"view\"}, nil,\n\t\t),\n\t\t\"EDNS0Fail\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, resolver, \"query_edns0_errors_total\"),\n\t\t\t\"Number of EDNS(0) query errors.\",\n\t\t\t[]string{\"view\"}, nil,\n\t\t),\n\t\t\"Mismatch\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, resolver, \"response_mismatch_total\"),\n\t\t\t\"Number of mismatch responses received.\",\n\t\t\t[]string{\"view\"}, nil,\n\t\t),\n\t\t\"Retry\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, resolver, \"query_retries_total\"),\n\t\t\t\"Number of resolver query retries.\",\n\t\t\t[]string{\"view\"}, nil,\n\t\t),\n\t\t\"Truncated\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, resolver, \"response_truncated_total\"),\n\t\t\t\"Number of truncated responses received.\",\n\t\t\t[]string{\"view\"}, nil,\n\t\t),\n\t\t\"ValFail\": prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, resolver, \"dnssec_validation_errors_total\"),\n\t\t\t\"Number of DNSSEC validation attempt errors.\",\n\t\t\t[]string{\"view\"}, nil,\n\t\t),\n\t}\n\tresolverLabelStats = map[string]*prometheus.Desc{\n\t\t\"QueryAbort\":    resolverQueryErrors,\n\t\t\"QuerySockFail\": resolverQueryErrors,\n\t\t\"QueryTimeout\":  resolverQueryErrors,\n\t\t\"NXDOMAIN\":      resolverResponseErrors,\n\t\t\"SERVFAIL\":      resolverResponseErrors,\n\t\t\"FORMERR\":       resolverResponseErrors,\n\t\t\"OtherError\":    resolverResponseErrors,\n\t\t\"ValOk\":         resolverDNSSECSucess,\n\t\t\"ValNegOk\":      resolverDNSSECSucess,\n\t}\n)\n\n\/\/ Exporter collects Binds stats from the given server and exports\n\/\/ them using the prometheus metrics package.\ntype Exporter struct {\n\tURI    string\n\tclient *http.Client\n}\n\n\/\/ NewExporter returns an initialized Exporter.\nfunc NewExporter(uri string, timeout time.Duration) *Exporter {\n\treturn &Exporter{\n\t\tURI: uri,\n\t\tclient: &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDial: func(netw, addr string) (net.Conn, error) {\n\t\t\t\t\tc, err := net.DialTimeout(netw, addr, timeout)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tif err := c.SetDeadline(time.Now().Add(timeout)); err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\treturn c, nil\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\n\/\/ Describe describes all the metrics ever exported by the bind\n\/\/ exporter. It implements prometheus.Collector.\nfunc (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n\tch <- up\n\tch <- incomingQueries\n\tch <- incomingRequests\n\tch <- resolverDNSSECSucess\n\tch <- resolverQueries\n\tch <- resolverQueryDuration\n\tch <- resolverQueryErrors\n\tch <- resolverResponseErrors\n\tfor _, desc := range resolverMetricStats {\n\t\tch <- desc\n\t}\n}\n\n\/\/ Collect fetches the stats from configured bind location and\n\/\/ delivers them as Prometheus metrics. It implements prometheus.Collector.\nfunc (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\tvar status float64\n\tdefer func() {\n\t\tch <- prometheus.MustNewConstMetric(up, prometheus.GaugeValue, status)\n\t}()\n\n\tresp, err := e.client.Get(e.URI)\n\tif err != nil {\n\t\tlog.Error(\"Error while querying Bind: \", err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Error(\"Failed to read XML response body: \", err)\n\t\treturn\n\t}\n\n\tstatus = 1\n\n\troot := Isc{}\n\tif err := xml.Unmarshal([]byte(body), &root); err != nil {\n\t\tlog.Error(\"Failed to unmarshal XML response: \", err)\n\t\treturn\n\t}\n\n\tserverNode := root.Bind.Statistics.Server\n\tfor _, s := range serverNode.QueriesIn.Rdtype {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tincomingQueries, prometheus.CounterValue, float64(s.Counter), s.Name,\n\t\t)\n\t}\n\tfor _, s := range serverNode.Requests.Opcode {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tincomingRequests, prometheus.CounterValue, float64(s.Counter), s.Name,\n\t\t)\n\t}\n\n\tfor _, v := range root.Bind.Statistics.Views {\n\t\tfor _, s := range v.Rdtype {\n\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\tresolverQueries, prometheus.CounterValue, float64(s.Counter), v.Name, s.Name,\n\t\t\t)\n\t\t}\n\n\t\tfor _, s := range v.Resstat {\n\t\t\tif desc, ok := resolverMetricStats[s.Name]; ok {\n\t\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\t\tdesc, prometheus.CounterValue, float64(s.Counter), v.Name,\n\t\t\t\t)\n\t\t\t}\n\t\t\tif desc, ok := resolverLabelStats[s.Name]; ok {\n\t\t\t\tch <- prometheus.MustNewConstMetric(\n\t\t\t\t\tdesc, prometheus.CounterValue, float64(s.Counter), v.Name, s.Name,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tif buckets, count, err := histogram(v.Resstat); err == nil {\n\t\t\tch <- prometheus.MustNewConstHistogram(\n\t\t\t\tresolverQueryDuration, count, math.NaN(), buckets, v.Name,\n\t\t\t)\n\t\t} else {\n\t\t\tlog.Warn(\"Error parsing RTT:\", err)\n\t\t}\n\t}\n}\n\nfunc histogram(stats []Stat) (map[float64]uint64, uint64, error) {\n\tbuckets := map[float64]uint64{}\n\tvar count uint64\n\n\tfor _, s := range stats {\n\t\tif strings.HasPrefix(s.Name, qryRTT) {\n\t\t\tb := math.Inf(0)\n\t\t\tif !strings.HasSuffix(s.Name, \"+\") {\n\t\t\t\tvar err error\n\t\t\t\trrt := strings.TrimPrefix(s.Name, qryRTT)\n\t\t\t\tb, err = strconv.ParseFloat(rrt, 32)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn buckets, 0, fmt.Errorf(\"could not parse RTT: %s\", rrt)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbuckets[b\/1000] = count + uint64(s.Counter)\n\t\t\tcount += uint64(s.Counter)\n\t\t}\n\t}\n\treturn buckets, count, nil\n}\n\nfunc main() {\n\tvar (\n\t\tlistenAddress = flag.String(\"web.listen-address\", \":9109\", \"Address to listen on for web interface and telemetry.\")\n\t\tmetricsPath   = flag.String(\"web.telemetry-path\", \"\/metrics\", \"Path under which to expose metrics.\")\n\t\tbindURI       = flag.String(\"bind.statsuri\", \"http:\/\/localhost:8053\/\", \"HTTP XML API address of an Bind server.\")\n\t\tbindTimeout   = flag.Duration(\"bind.timeout\", 10*time.Second, \"Timeout for trying to get stats from Bind.\")\n\t\tbindPidFile   = flag.String(\"bind.pid-file\", \"\", \"Path to Bind's pid file to export process information.\")\n\t)\n\tflag.Parse()\n\n\tprometheus.MustRegister(NewExporter(*bindURI, *bindTimeout))\n\tif *bindPidFile != \"\" {\n\t\tprocExporter := prometheus.NewProcessCollectorPIDFn(\n\t\t\tfunc() (int, error) {\n\t\t\t\tcontent, err := ioutil.ReadFile(*bindPidFile)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"Can't read pid file: %s\", err)\n\t\t\t\t}\n\t\t\t\tvalue, err := strconv.Atoi(strings.TrimSpace(string(content)))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"Can't parse pid file: %s\", err)\n\t\t\t\t}\n\t\t\t\treturn value, nil\n\t\t\t}, namespace)\n\t\tprometheus.MustRegister(procExporter)\n\t}\n\n\tlog.Info(\"Starting Server: \", *listenAddress)\n\thttp.Handle(*metricsPath, prometheus.Handler())\n\thttp.HandleFunc(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(`<html>\n             <head><title>Bind Exporter<\/title><\/head>\n             <body>\n             <h1>Bind Exporter<\/h1>\n             <p><a href='` + *metricsPath + `'>Metrics<\/a><\/p>\n             <\/body>\n             <\/html>`))\n\t})\n\tlog.Fatal(http.ListenAndServe(*listenAddress, nil))\n}\n<|endoftext|>"}
{"text":"<commit_before>package bitmap\n\nimport (\n\t\"github.com\/RoaringBitmap\/roaring\"\n\n\t\"github.com\/anacrolix\/missinggo\"\n)\n\n\/\/ Bitmaps store the existence of values in [0,math.MaxUint32] more\n\/\/ efficiently than []bool. The empty value starts with no bits set.\ntype Bitmap struct {\n\trb *roaring.Bitmap\n}\n\nfunc (me *Bitmap) Len() int {\n\tif me.rb == nil {\n\t\treturn 0\n\t}\n\treturn int(me.rb.GetCardinality())\n}\n\nfunc (me Bitmap) ToSortedSlice() (ret []int) {\n\tif me.rb == nil {\n\t\treturn\n\t}\n\tmissinggo.CastSlice(&ret, me.rb.ToArray())\n\treturn\n}\n\nfunc (me *Bitmap) lazyRB() *roaring.Bitmap {\n\tif me.rb == nil {\n\t\tme.rb = roaring.NewBitmap()\n\t}\n\treturn me.rb\n}\n\nfunc (me *Bitmap) Iter(f func(interface{}) bool) {\n\tme.IterTyped(func(i int) bool {\n\t\treturn f(i)\n\t})\n}\n\nfunc (me Bitmap) IterTyped(f func(int) bool) bool {\n\tif me.rb == nil {\n\t\treturn true\n\t}\n\tit := me.rb.Iterator()\n\tfor it.HasNext() {\n\t\tif !f(int(it.Next())) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (me *Bitmap) Add(is ...int) {\n\trb := me.lazyRB()\n\tfor _, i := range is {\n\t\trb.AddInt(i)\n\t}\n}\n\nfunc (me *Bitmap) AddRange(begin, end int) {\n\tif begin >= end {\n\t\treturn\n\t}\n\tme.lazyRB().AddRange(uint32(begin), uint32(end))\n}\n\nfunc (me *Bitmap) Remove(i int) {\n\tif me.rb == nil {\n\t\treturn\n\t}\n\tme.rb.Remove(uint32(i))\n}\n\nfunc (me *Bitmap) Union(other *Bitmap) {\n\tme.lazyRB().Or(other.lazyRB())\n}\n\nfunc (me *Bitmap) Contains(i int) bool {\n\tif me.rb == nil {\n\t\treturn false\n\t}\n\treturn me.rb.Contains(uint32(i))\n}\n\ntype Iter struct {\n\tii roaring.IntIterable\n}\n\nfunc (me *Iter) Next() bool {\n\tif me == nil {\n\t\treturn false\n\t}\n\treturn me.ii.HasNext()\n}\n\nfunc (me *Iter) Value() interface{} {\n\treturn me.ValueInt()\n}\n\nfunc (me *Iter) ValueInt() int {\n\treturn int(me.ii.Next())\n}\n\nfunc (me *Iter) Stop() {}\n\nfunc Sub(left, right *Bitmap) *Bitmap {\n\treturn &Bitmap{\n\t\trb: roaring.AndNot(left.lazyRB(), right.lazyRB()),\n\t}\n}\n\nfunc (me *Bitmap) Sub(other *Bitmap) {\n\tif other.rb == nil {\n\t\treturn\n\t}\n\tif me.rb == nil {\n\t\treturn\n\t}\n\tme.rb.AndNot(other.rb)\n}\n\nfunc (me *Bitmap) Clear() {\n\tif me.rb == nil {\n\t\treturn\n\t}\n\tme.rb.Clear()\n}\n\nfunc (me Bitmap) Copy() (ret Bitmap) {\n\tret = me\n\tif ret.rb != nil {\n\t\tret.rb = ret.rb.Clone()\n\t}\n\treturn\n}\n\nfunc (me *Bitmap) FlipRange(begin, end int) {\n\tme.lazyRB().FlipInt(begin, end)\n}\n<commit_msg>bitmap.Bitmap: Get and Set<commit_after>package bitmap\n\nimport (\n\t\"github.com\/RoaringBitmap\/roaring\"\n\n\t\"github.com\/anacrolix\/missinggo\"\n)\n\n\/\/ Bitmaps store the existence of values in [0,math.MaxUint32] more\n\/\/ efficiently than []bool. The empty value starts with no bits set.\ntype Bitmap struct {\n\trb *roaring.Bitmap\n}\n\nfunc (me *Bitmap) Len() int {\n\tif me.rb == nil {\n\t\treturn 0\n\t}\n\treturn int(me.rb.GetCardinality())\n}\n\nfunc (me Bitmap) ToSortedSlice() (ret []int) {\n\tif me.rb == nil {\n\t\treturn\n\t}\n\tmissinggo.CastSlice(&ret, me.rb.ToArray())\n\treturn\n}\n\nfunc (me *Bitmap) lazyRB() *roaring.Bitmap {\n\tif me.rb == nil {\n\t\tme.rb = roaring.NewBitmap()\n\t}\n\treturn me.rb\n}\n\nfunc (me *Bitmap) Iter(f func(interface{}) bool) {\n\tme.IterTyped(func(i int) bool {\n\t\treturn f(i)\n\t})\n}\n\nfunc (me Bitmap) IterTyped(f func(int) bool) bool {\n\tif me.rb == nil {\n\t\treturn true\n\t}\n\tit := me.rb.Iterator()\n\tfor it.HasNext() {\n\t\tif !f(int(it.Next())) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (me *Bitmap) Add(is ...int) {\n\trb := me.lazyRB()\n\tfor _, i := range is {\n\t\trb.AddInt(i)\n\t}\n}\n\nfunc (me *Bitmap) AddRange(begin, end int) {\n\tif begin >= end {\n\t\treturn\n\t}\n\tme.lazyRB().AddRange(uint32(begin), uint32(end))\n}\n\nfunc (me *Bitmap) Remove(i int) {\n\tif me.rb == nil {\n\t\treturn\n\t}\n\tme.rb.Remove(uint32(i))\n}\n\nfunc (me *Bitmap) Union(other *Bitmap) {\n\tme.lazyRB().Or(other.lazyRB())\n}\n\nfunc (me *Bitmap) Contains(i int) bool {\n\tif me.rb == nil {\n\t\treturn false\n\t}\n\treturn me.rb.Contains(uint32(i))\n}\n\ntype Iter struct {\n\tii roaring.IntIterable\n}\n\nfunc (me *Iter) Next() bool {\n\tif me == nil {\n\t\treturn false\n\t}\n\treturn me.ii.HasNext()\n}\n\nfunc (me *Iter) Value() interface{} {\n\treturn me.ValueInt()\n}\n\nfunc (me *Iter) ValueInt() int {\n\treturn int(me.ii.Next())\n}\n\nfunc (me *Iter) Stop() {}\n\nfunc Sub(left, right *Bitmap) *Bitmap {\n\treturn &Bitmap{\n\t\trb: roaring.AndNot(left.lazyRB(), right.lazyRB()),\n\t}\n}\n\nfunc (me *Bitmap) Sub(other *Bitmap) {\n\tif other.rb == nil {\n\t\treturn\n\t}\n\tif me.rb == nil {\n\t\treturn\n\t}\n\tme.rb.AndNot(other.rb)\n}\n\nfunc (me *Bitmap) Clear() {\n\tif me.rb == nil {\n\t\treturn\n\t}\n\tme.rb.Clear()\n}\n\nfunc (me Bitmap) Copy() (ret Bitmap) {\n\tret = me\n\tif ret.rb != nil {\n\t\tret.rb = ret.rb.Clone()\n\t}\n\treturn\n}\n\nfunc (me *Bitmap) FlipRange(begin, end int) {\n\tme.lazyRB().FlipInt(begin, end)\n}\n\nfunc (me *Bitmap) Get(bit int) bool {\n\treturn me.rb != nil && me.rb.ContainsInt(bit)\n}\n\nfunc (me *Bitmap) Set(bit int, value bool) {\n\tif value {\n\t\tme.lazyRB().AddInt(bit)\n\t} else {\n\t\tif me.rb != nil {\n\t\t\tme.rb.Remove(uint32(bit))\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package repo_manager\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/skia-dev\/glog\"\n\n\t\"go.skia.org\/infra\/go\/autoroll\"\n\t\"go.skia.org\/infra\/go\/exec\"\n\t\"go.skia.org\/infra\/go\/gitinfo\"\n\t\"go.skia.org\/infra\/go\/util\"\n)\n\nconst (\n\tDEPS_ROLL_BRANCH = \"roll_branch\"\n\n\tGCLIENT  = \"gclient\"\n\tROLL_DEP = \"roll-dep\"\n\n\tREPO_CHROMIUM = \"https:\/\/chromium.googlesource.com\/chromium\/src.git\"\n\n\tTMPL_CQ_INCLUDE_TRYBOTS = \"CQ_INCLUDE_TRYBOTS=%s\"\n)\n\nvar (\n\tISSUE_CREATED_REGEX = regexp.MustCompile(fmt.Sprintf(\"Issue created. URL: %s\/(\\\\d+)\", autoroll.RIETVELD_URL))\n\n\t\/\/ Use this function to instantiate a RepoManager. This is able to be\n\t\/\/ overridden for testing.\n\tNewRepoManager func(string, string, time.Duration, string) (RepoManager, error) = NewDefaultRepoManager\n\n\tDEPOT_TOOLS_AUTH_USER_REGEX = regexp.MustCompile(fmt.Sprintf(\"Logged in to %s as ([\\\\w-]+).\", autoroll.RIETVELD_URL))\n)\n\n\/\/ RepoManager is used by AutoRoller for managing checkouts.\ntype RepoManager interface {\n\tForceUpdate() error\n\tFullChildHash(string) (string, error)\n\tLastRollRev() string\n\tRolledPast(string) bool\n\tChildHead() string\n\tCreateNewRoll([]string, string, bool) (int64, error)\n\tUser() string\n}\n\n\/\/ repoManager is a struct used by AutoRoller for managing checkouts.\ntype repoManager struct {\n\tchromiumDir       string\n\tchromiumParentDir string\n\tdepot_tools       string\n\tgclient           string\n\tinfoMtx           sync.RWMutex\n\tlastRollRev       string\n\trepoMtx           sync.RWMutex\n\trollDep           string\n\tchildDir          string\n\tchildHead         string\n\tchildPath         string\n\tchildRepo         *gitinfo.GitInfo\n\tuser              string\n}\n\n\/\/ getEnv returns the environment used for most commands.\nfunc getEnv(depotTools string) []string {\n\treturn []string{\n\t\tfmt.Sprintf(\"PATH=%s:%s\", depotTools, os.Getenv(\"PATH\")),\n\t\tfmt.Sprintf(\"HOME=%s\", os.Getenv(\"HOME\")),\n\t}\n}\n\n\/\/ getDepotToolsUser returns the authorized depot tools user.\nfunc getDepotToolsUser(depotTools string) (string, error) {\n\toutput, err := exec.RunCommand(&exec.Command{\n\t\tEnv:  getEnv(depotTools),\n\t\tName: path.Join(depotTools, \"depot-tools-auth\"),\n\t\tArgs: []string{\"info\", autoroll.RIETVELD_URL},\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tm := DEPOT_TOOLS_AUTH_USER_REGEX.FindStringSubmatch(output)\n\tif len(m) != 2 {\n\t\treturn \"\", fmt.Errorf(\"Unable to parse the output of depot-tools-auth.\")\n\t}\n\treturn m[1], nil\n}\n\n\/\/ NewDefaultRepoManager returns a RepoManager instance which operates in the given\n\/\/ working directory and updates at the given frequency.\nfunc NewDefaultRepoManager(workdir, childPath string, frequency time.Duration, depot_tools string) (RepoManager, error) {\n\tgclient := GCLIENT\n\trollDep := ROLL_DEP\n\tif depot_tools != \"\" {\n\t\tgclient = path.Join(depot_tools, gclient)\n\t\trollDep = path.Join(depot_tools, rollDep)\n\t}\n\n\tchromiumParentDir := path.Join(workdir, \"chromium\")\n\tchromiumDir := path.Join(chromiumParentDir, \"src\")\n\n\tuser, err := getDepotToolsUser(depot_tools)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to determine depot tools user: %s\", err)\n\t}\n\n\tr := &repoManager{\n\t\tchromiumDir:       chromiumDir,\n\t\tchromiumParentDir: chromiumParentDir,\n\t\tdepot_tools:       depot_tools,\n\t\tgclient:           gclient,\n\t\trollDep:           rollDep,\n\t\tchildDir:          path.Join(chromiumParentDir, childPath),\n\t\tchildPath:         childPath,\n\t\tchildRepo:         nil, \/\/ This will be filled in on the first update.\n\t\tuser:              user,\n\t}\n\tif err := r.update(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo func() {\n\t\tfor _ = range time.Tick(frequency) {\n\t\t\tutil.LogErr(r.update())\n\t\t}\n\t}()\n\treturn r, nil\n}\n\n\/\/ update syncs code in the relevant repositories.\nfunc (r *repoManager) update() error {\n\t\/\/ Sync the projects.\n\tr.repoMtx.Lock()\n\tdefer r.repoMtx.Unlock()\n\n\t\/\/ Create the chromium parent directory if needed.\n\tif _, err := os.Stat(r.chromiumParentDir); err != nil {\n\t\tif err := os.MkdirAll(r.chromiumParentDir, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif _, err := os.Stat(path.Join(r.chromiumDir, \".git\")); err == nil {\n\t\tif err := r.cleanChromium(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Update the repo.\n\t\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"fetch\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"reset\", \"--hard\", \"origin\/master\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif _, err := exec.RunCommand(&exec.Command{\n\t\tDir:  r.chromiumParentDir,\n\t\tEnv:  getEnv(r.depot_tools),\n\t\tName: r.gclient,\n\t\tArgs: []string{\"config\", REPO_CHROMIUM},\n\t}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := exec.RunCommand(&exec.Command{\n\t\tDir:  r.chromiumParentDir,\n\t\tEnv:  getEnv(r.depot_tools),\n\t\tName: r.gclient,\n\t\tArgs: []string{\"sync\", \"--nohooks\"},\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Create the child GitInfo if needed.\n\tif r.childRepo == nil {\n\t\tchildRepo, err := gitinfo.NewGitInfo(r.childDir, false, true)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tr.childRepo = childRepo\n\t}\n\n\t\/\/ Get the last roll revision.\n\tlastRollRev, err := r.getLastRollRev()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Record child HEAD\n\tchildHead, err := r.childRepo.FullHash(\"origin\/master\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.infoMtx.Lock()\n\tdefer r.infoMtx.Unlock()\n\tr.lastRollRev = lastRollRev\n\tr.childHead = childHead\n\treturn nil\n}\n\n\/\/ ForceUpdate forces the repoManager to update.\nfunc (r *repoManager) ForceUpdate() error {\n\treturn r.update()\n}\n\n\/\/ getLastRollRev returns the commit hash of the last-completed DEPS roll.\nfunc (r *repoManager) getLastRollRev() (string, error) {\n\toutput, err := exec.RunCwd(r.chromiumDir, r.gclient, \"revinfo\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsplit := strings.Split(output, \"\\n\")\n\tfor _, s := range split {\n\t\tif strings.HasPrefix(s, r.childPath) {\n\t\t\tsubs := strings.Split(s, \"@\")\n\t\t\tif len(subs) != 2 {\n\t\t\t\treturn \"\", fmt.Errorf(\"Failed to parse output of `gclient revinfo`\")\n\t\t\t}\n\t\t\treturn subs[1], nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"Failed to parse output of `gclient revinfo`\")\n}\n\n\/\/ FullChildHash returns the full hash of the given short hash or ref in the\n\/\/ child repo.\nfunc (r *repoManager) FullChildHash(shortHash string) (string, error) {\n\tr.repoMtx.RLock()\n\tdefer r.repoMtx.RUnlock()\n\treturn r.childRepo.FullHash(shortHash)\n}\n\n\/\/ LastRollRev returns the last-rolled child commit.\nfunc (r *repoManager) LastRollRev() string {\n\tr.infoMtx.RLock()\n\tdefer r.infoMtx.RUnlock()\n\treturn r.lastRollRev\n}\n\n\/\/ RolledPast determines whether DEPS has rolled past the given commit.\nfunc (r *repoManager) RolledPast(hash string) bool {\n\tr.repoMtx.RLock()\n\tdefer r.repoMtx.RUnlock()\n\tif _, err := exec.RunCwd(r.childDir, \"git\", \"merge-base\", \"--is-ancestor\", hash, r.lastRollRev); err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ ChildHead returns the current child origin\/master branch head.\nfunc (r *repoManager) ChildHead() string {\n\tr.infoMtx.RLock()\n\tdefer r.infoMtx.RUnlock()\n\treturn r.childHead\n}\n\n\/\/ cleanChromium forces the Chromium checkout into a clean state.\nfunc (r *repoManager) cleanChromium() error {\n\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"clean\", \"-d\", \"-f\", \"-f\"); err != nil {\n\t\treturn err\n\t}\n\t_, _ = exec.RunCwd(r.chromiumDir, \"git\", \"rebase\", \"--abort\")\n\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"checkout\", \"origin\/master\", \"-f\"); err != nil {\n\t\treturn err\n\t}\n\t_, _ = exec.RunCwd(r.chromiumDir, \"git\", \"branch\", \"-D\", DEPS_ROLL_BRANCH)\n\tif _, err := exec.RunCommand(&exec.Command{\n\t\tDir:  r.chromiumDir,\n\t\tEnv:  getEnv(r.depot_tools),\n\t\tName: r.gclient,\n\t\tArgs: []string{\"revert\", \"--nohooks\"},\n\t}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ CreateNewRoll creates and uploads a new DEPS roll to the given commit.\n\/\/ Returns the issue number of the uploaded roll.\nfunc (r *repoManager) CreateNewRoll(emails []string, cqExtraTrybots string, dryRun bool) (int64, error) {\n\tr.repoMtx.Lock()\n\tdefer r.repoMtx.Unlock()\n\n\t\/\/ Clean the checkout, get onto a fresh branch.\n\tif err := r.cleanChromium(); err != nil {\n\t\treturn 0, err\n\t}\n\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"checkout\", \"-b\", DEPS_ROLL_BRANCH, \"-t\", \"origin\/master\", \"-f\"); err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ Defer some more cleanup.\n\tdefer func() {\n\t\tutil.LogErr(r.cleanChromium())\n\t}()\n\n\t\/\/ Create the roll CL.\n\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"config\", \"user.name\", autoroll.ROLL_AUTHOR); err != nil {\n\t\treturn 0, err\n\t}\n\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"config\", \"user.email\", autoroll.ROLL_AUTHOR); err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ Find Chromium bugs.\n\tbugs := []string{}\n\tcr := r.childRepo\n\tcommits, err := cr.RevList(fmt.Sprintf(\"%s..%s\", r.lastRollRev, r.childHead))\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"Failed to list revisions: %s\", err)\n\t}\n\tfor _, c := range commits {\n\t\td, err := cr.Details(c, false)\n\t\tif err != nil {\n\t\t\treturn 0, fmt.Errorf(\"Failed to obtain commit details: %s\", err)\n\t\t}\n\t\tb := util.BugsFromCommitMsg(d.Body)\n\t\tfor _, bug := range b[util.PROJECT_CHROMIUM] {\n\t\t\tbugs = append(bugs, bug)\n\t\t}\n\t}\n\n\targs := []string{r.childPath, r.childHead}\n\tif len(bugs) > 0 {\n\t\targs = append(args, \"--bug\", strings.Join(bugs, \",\"))\n\t}\n\tglog.Infof(\"Running command: roll-dep %s\", strings.Join(args, \" \"))\n\tif _, err := exec.RunCommand(&exec.Command{\n\t\tDir:  r.chromiumDir,\n\t\tEnv:  getEnv(r.depot_tools),\n\t\tName: r.rollDep,\n\t\tArgs: args,\n\t}); err != nil {\n\t\treturn 0, err\n\t}\n\t\/\/ Build the commit message, starting with the message provided by roll-dep.\n\tcommitMsg, err := exec.RunCwd(r.chromiumDir, \"git\", \"log\", \"-n1\", \"--format=%B\", \"HEAD\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif cqExtraTrybots != \"\" {\n\t\tcommitMsg += \"\\n\" + fmt.Sprintf(TMPL_CQ_INCLUDE_TRYBOTS, cqExtraTrybots)\n\t}\n\tuploadCmd := &exec.Command{\n\t\tDir:  r.chromiumDir,\n\t\tEnv:  getEnv(r.depot_tools),\n\t\tName: \"git\",\n\t\tArgs: []string{\"cl\", \"upload\", \"--bypass-hooks\", \"-f\"},\n\t}\n\tif dryRun {\n\t\tuploadCmd.Args = append(uploadCmd.Args, \"--cq-dry-run\")\n\t} else {\n\t\tuploadCmd.Args = append(uploadCmd.Args, \"--use-commit-queue\")\n\t}\n\ttbr := \"\\nTBR=\"\n\tif emails != nil && len(emails) > 0 {\n\t\temailStr := strings.Join(emails, \",\")\n\t\ttbr += emailStr\n\t\tuploadCmd.Args = append(uploadCmd.Args, \"--send-mail\", \"--cc\", emailStr)\n\t}\n\tcommitMsg += tbr\n\tuploadCmd.Args = append(uploadCmd.Args, \"-m\", commitMsg)\n\n\t\/\/ Upload the CL.\n\tuploadOutput, err := exec.RunCommand(uploadCmd)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tissues := ISSUE_CREATED_REGEX.FindStringSubmatch(uploadOutput)\n\tif len(issues) != 2 {\n\t\treturn 0, fmt.Errorf(\"Failed to find newly-uploaded issue number!\")\n\t}\n\treturn strconv.ParseInt(issues[1], 10, 64)\n}\n\nfunc (r *repoManager) User() string {\n\treturn r.user\n}\n<commit_msg>Fix autoroll issue number parsing<commit_after>package repo_manager\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/skia-dev\/glog\"\n\n\t\"go.skia.org\/infra\/go\/autoroll\"\n\t\"go.skia.org\/infra\/go\/exec\"\n\t\"go.skia.org\/infra\/go\/gitinfo\"\n\t\"go.skia.org\/infra\/go\/util\"\n)\n\nconst (\n\tDEPS_ROLL_BRANCH = \"roll_branch\"\n\n\tGCLIENT  = \"gclient\"\n\tROLL_DEP = \"roll-dep\"\n\n\tREPO_CHROMIUM = \"https:\/\/chromium.googlesource.com\/chromium\/src.git\"\n\n\tTMPL_CQ_INCLUDE_TRYBOTS = \"CQ_INCLUDE_TRYBOTS=%s\"\n)\n\nvar (\n\t\/\/ Use this function to instantiate a RepoManager. This is able to be\n\t\/\/ overridden for testing.\n\tNewRepoManager func(string, string, time.Duration, string) (RepoManager, error) = NewDefaultRepoManager\n\n\tDEPOT_TOOLS_AUTH_USER_REGEX = regexp.MustCompile(fmt.Sprintf(\"Logged in to %s as ([\\\\w-]+).\", autoroll.RIETVELD_URL))\n)\n\n\/\/ issueJson is the structure of \"git cl issue --json\"\ntype issueJson struct {\n\tIssue    int64  `json:\"issue\"`\n\tIssueUrl string `json:\"issue_url\"`\n}\n\n\/\/ RepoManager is used by AutoRoller for managing checkouts.\ntype RepoManager interface {\n\tForceUpdate() error\n\tFullChildHash(string) (string, error)\n\tLastRollRev() string\n\tRolledPast(string) bool\n\tChildHead() string\n\tCreateNewRoll([]string, string, bool) (int64, error)\n\tUser() string\n}\n\n\/\/ repoManager is a struct used by AutoRoller for managing checkouts.\ntype repoManager struct {\n\tchromiumDir       string\n\tchromiumParentDir string\n\tdepot_tools       string\n\tgclient           string\n\tinfoMtx           sync.RWMutex\n\tlastRollRev       string\n\trepoMtx           sync.RWMutex\n\trollDep           string\n\tchildDir          string\n\tchildHead         string\n\tchildPath         string\n\tchildRepo         *gitinfo.GitInfo\n\tuser              string\n}\n\n\/\/ getEnv returns the environment used for most commands.\nfunc getEnv(depotTools string) []string {\n\treturn []string{\n\t\tfmt.Sprintf(\"PATH=%s:%s\", depotTools, os.Getenv(\"PATH\")),\n\t\tfmt.Sprintf(\"HOME=%s\", os.Getenv(\"HOME\")),\n\t}\n}\n\n\/\/ getDepotToolsUser returns the authorized depot tools user.\nfunc getDepotToolsUser(depotTools string) (string, error) {\n\toutput, err := exec.RunCommand(&exec.Command{\n\t\tEnv:  getEnv(depotTools),\n\t\tName: path.Join(depotTools, \"depot-tools-auth\"),\n\t\tArgs: []string{\"info\", autoroll.RIETVELD_URL},\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tm := DEPOT_TOOLS_AUTH_USER_REGEX.FindStringSubmatch(output)\n\tif len(m) != 2 {\n\t\treturn \"\", fmt.Errorf(\"Unable to parse the output of depot-tools-auth.\")\n\t}\n\treturn m[1], nil\n}\n\n\/\/ NewDefaultRepoManager returns a RepoManager instance which operates in the given\n\/\/ working directory and updates at the given frequency.\nfunc NewDefaultRepoManager(workdir, childPath string, frequency time.Duration, depot_tools string) (RepoManager, error) {\n\tgclient := GCLIENT\n\trollDep := ROLL_DEP\n\tif depot_tools != \"\" {\n\t\tgclient = path.Join(depot_tools, gclient)\n\t\trollDep = path.Join(depot_tools, rollDep)\n\t}\n\n\tchromiumParentDir := path.Join(workdir, \"chromium\")\n\tchromiumDir := path.Join(chromiumParentDir, \"src\")\n\n\tuser, err := getDepotToolsUser(depot_tools)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to determine depot tools user: %s\", err)\n\t}\n\n\tr := &repoManager{\n\t\tchromiumDir:       chromiumDir,\n\t\tchromiumParentDir: chromiumParentDir,\n\t\tdepot_tools:       depot_tools,\n\t\tgclient:           gclient,\n\t\trollDep:           rollDep,\n\t\tchildDir:          path.Join(chromiumParentDir, childPath),\n\t\tchildPath:         childPath,\n\t\tchildRepo:         nil, \/\/ This will be filled in on the first update.\n\t\tuser:              user,\n\t}\n\tif err := r.update(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo func() {\n\t\tfor _ = range time.Tick(frequency) {\n\t\t\tutil.LogErr(r.update())\n\t\t}\n\t}()\n\treturn r, nil\n}\n\n\/\/ update syncs code in the relevant repositories.\nfunc (r *repoManager) update() error {\n\t\/\/ Sync the projects.\n\tr.repoMtx.Lock()\n\tdefer r.repoMtx.Unlock()\n\n\t\/\/ Create the chromium parent directory if needed.\n\tif _, err := os.Stat(r.chromiumParentDir); err != nil {\n\t\tif err := os.MkdirAll(r.chromiumParentDir, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif _, err := os.Stat(path.Join(r.chromiumDir, \".git\")); err == nil {\n\t\tif err := r.cleanChromium(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Update the repo.\n\t\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"fetch\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"reset\", \"--hard\", \"origin\/master\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif _, err := exec.RunCommand(&exec.Command{\n\t\tDir:  r.chromiumParentDir,\n\t\tEnv:  getEnv(r.depot_tools),\n\t\tName: r.gclient,\n\t\tArgs: []string{\"config\", REPO_CHROMIUM},\n\t}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := exec.RunCommand(&exec.Command{\n\t\tDir:  r.chromiumParentDir,\n\t\tEnv:  getEnv(r.depot_tools),\n\t\tName: r.gclient,\n\t\tArgs: []string{\"sync\", \"--nohooks\"},\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Create the child GitInfo if needed.\n\tif r.childRepo == nil {\n\t\tchildRepo, err := gitinfo.NewGitInfo(r.childDir, false, true)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tr.childRepo = childRepo\n\t}\n\n\t\/\/ Get the last roll revision.\n\tlastRollRev, err := r.getLastRollRev()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Record child HEAD\n\tchildHead, err := r.childRepo.FullHash(\"origin\/master\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.infoMtx.Lock()\n\tdefer r.infoMtx.Unlock()\n\tr.lastRollRev = lastRollRev\n\tr.childHead = childHead\n\treturn nil\n}\n\n\/\/ ForceUpdate forces the repoManager to update.\nfunc (r *repoManager) ForceUpdate() error {\n\treturn r.update()\n}\n\n\/\/ getLastRollRev returns the commit hash of the last-completed DEPS roll.\nfunc (r *repoManager) getLastRollRev() (string, error) {\n\toutput, err := exec.RunCwd(r.chromiumDir, r.gclient, \"revinfo\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tsplit := strings.Split(output, \"\\n\")\n\tfor _, s := range split {\n\t\tif strings.HasPrefix(s, r.childPath) {\n\t\t\tsubs := strings.Split(s, \"@\")\n\t\t\tif len(subs) != 2 {\n\t\t\t\treturn \"\", fmt.Errorf(\"Failed to parse output of `gclient revinfo`\")\n\t\t\t}\n\t\t\treturn subs[1], nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"Failed to parse output of `gclient revinfo`\")\n}\n\n\/\/ FullChildHash returns the full hash of the given short hash or ref in the\n\/\/ child repo.\nfunc (r *repoManager) FullChildHash(shortHash string) (string, error) {\n\tr.repoMtx.RLock()\n\tdefer r.repoMtx.RUnlock()\n\treturn r.childRepo.FullHash(shortHash)\n}\n\n\/\/ LastRollRev returns the last-rolled child commit.\nfunc (r *repoManager) LastRollRev() string {\n\tr.infoMtx.RLock()\n\tdefer r.infoMtx.RUnlock()\n\treturn r.lastRollRev\n}\n\n\/\/ RolledPast determines whether DEPS has rolled past the given commit.\nfunc (r *repoManager) RolledPast(hash string) bool {\n\tr.repoMtx.RLock()\n\tdefer r.repoMtx.RUnlock()\n\tif _, err := exec.RunCwd(r.childDir, \"git\", \"merge-base\", \"--is-ancestor\", hash, r.lastRollRev); err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ ChildHead returns the current child origin\/master branch head.\nfunc (r *repoManager) ChildHead() string {\n\tr.infoMtx.RLock()\n\tdefer r.infoMtx.RUnlock()\n\treturn r.childHead\n}\n\n\/\/ cleanChromium forces the Chromium checkout into a clean state.\nfunc (r *repoManager) cleanChromium() error {\n\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"clean\", \"-d\", \"-f\", \"-f\"); err != nil {\n\t\treturn err\n\t}\n\t_, _ = exec.RunCwd(r.chromiumDir, \"git\", \"rebase\", \"--abort\")\n\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"checkout\", \"origin\/master\", \"-f\"); err != nil {\n\t\treturn err\n\t}\n\t_, _ = exec.RunCwd(r.chromiumDir, \"git\", \"branch\", \"-D\", DEPS_ROLL_BRANCH)\n\tif _, err := exec.RunCommand(&exec.Command{\n\t\tDir:  r.chromiumDir,\n\t\tEnv:  getEnv(r.depot_tools),\n\t\tName: r.gclient,\n\t\tArgs: []string{\"revert\", \"--nohooks\"},\n\t}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ CreateNewRoll creates and uploads a new DEPS roll to the given commit.\n\/\/ Returns the issue number of the uploaded roll.\nfunc (r *repoManager) CreateNewRoll(emails []string, cqExtraTrybots string, dryRun bool) (int64, error) {\n\tr.repoMtx.Lock()\n\tdefer r.repoMtx.Unlock()\n\n\t\/\/ Clean the checkout, get onto a fresh branch.\n\tif err := r.cleanChromium(); err != nil {\n\t\treturn 0, err\n\t}\n\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"checkout\", \"-b\", DEPS_ROLL_BRANCH, \"-t\", \"origin\/master\", \"-f\"); err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ Defer some more cleanup.\n\tdefer func() {\n\t\tutil.LogErr(r.cleanChromium())\n\t}()\n\n\t\/\/ Create the roll CL.\n\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"config\", \"user.name\", autoroll.ROLL_AUTHOR); err != nil {\n\t\treturn 0, err\n\t}\n\tif _, err := exec.RunCwd(r.chromiumDir, \"git\", \"config\", \"user.email\", autoroll.ROLL_AUTHOR); err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ Find Chromium bugs.\n\tbugs := []string{}\n\tcr := r.childRepo\n\tcommits, err := cr.RevList(fmt.Sprintf(\"%s..%s\", r.lastRollRev, r.childHead))\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"Failed to list revisions: %s\", err)\n\t}\n\tfor _, c := range commits {\n\t\td, err := cr.Details(c, false)\n\t\tif err != nil {\n\t\t\treturn 0, fmt.Errorf(\"Failed to obtain commit details: %s\", err)\n\t\t}\n\t\tb := util.BugsFromCommitMsg(d.Body)\n\t\tfor _, bug := range b[util.PROJECT_CHROMIUM] {\n\t\t\tbugs = append(bugs, bug)\n\t\t}\n\t}\n\n\targs := []string{r.childPath, r.childHead}\n\tif len(bugs) > 0 {\n\t\targs = append(args, \"--bug\", strings.Join(bugs, \",\"))\n\t}\n\tglog.Infof(\"Running command: roll-dep %s\", strings.Join(args, \" \"))\n\tif _, err := exec.RunCommand(&exec.Command{\n\t\tDir:  r.chromiumDir,\n\t\tEnv:  getEnv(r.depot_tools),\n\t\tName: r.rollDep,\n\t\tArgs: args,\n\t}); err != nil {\n\t\treturn 0, err\n\t}\n\t\/\/ Build the commit message, starting with the message provided by roll-dep.\n\tcommitMsg, err := exec.RunCwd(r.chromiumDir, \"git\", \"log\", \"-n1\", \"--format=%B\", \"HEAD\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif cqExtraTrybots != \"\" {\n\t\tcommitMsg += \"\\n\" + fmt.Sprintf(TMPL_CQ_INCLUDE_TRYBOTS, cqExtraTrybots)\n\t}\n\tuploadCmd := &exec.Command{\n\t\tDir:  r.chromiumDir,\n\t\tEnv:  getEnv(r.depot_tools),\n\t\tName: \"git\",\n\t\tArgs: []string{\"cl\", \"upload\", \"--bypass-hooks\", \"-f\"},\n\t}\n\tif dryRun {\n\t\tuploadCmd.Args = append(uploadCmd.Args, \"--cq-dry-run\")\n\t} else {\n\t\tuploadCmd.Args = append(uploadCmd.Args, \"--use-commit-queue\")\n\t}\n\ttbr := \"\\nTBR=\"\n\tif emails != nil && len(emails) > 0 {\n\t\temailStr := strings.Join(emails, \",\")\n\t\ttbr += emailStr\n\t\tuploadCmd.Args = append(uploadCmd.Args, \"--send-mail\", \"--cc\", emailStr)\n\t}\n\tcommitMsg += tbr\n\tuploadCmd.Args = append(uploadCmd.Args, \"-m\", commitMsg)\n\n\t\/\/ Upload the CL.\n\tif _, err := exec.RunCommand(uploadCmd); err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ Obtain the issue number.\n\ttmp, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer util.RemoveAll(tmp)\n\tjsonFile := path.Join(tmp, \"issue.json\")\n\tif _, err := exec.RunCommand(&exec.Command{\n\t\tDir:  r.chromiumDir,\n\t\tEnv:  getEnv(r.depot_tools),\n\t\tName: \"git\",\n\t\tArgs: []string{\"cl\", \"issue\", fmt.Sprintf(\"--json=%s\", jsonFile)},\n\t}); err != nil {\n\t\treturn 0, err\n\t}\n\tf, err := os.Open(jsonFile)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tvar issue issueJson\n\tif err := json.NewDecoder(f).Decode(&issue); err != nil {\n\t\treturn 0, err\n\t}\n\treturn issue.Issue, nil\n}\n\nfunc (r *repoManager) User() string {\n\treturn r.user\n}\n<|endoftext|>"}
{"text":"<commit_before>package broker\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/lager\"\n\t\"github.com\/cloudfoundry-community\/go-cfclient\"\n\t\"github.com\/pivotal-cf\/brokerapi\"\n\n\t\"github.com\/cloudfoundry-community\/s3-broker\/awsiam\"\n\t\"github.com\/cloudfoundry-community\/s3-broker\/awss3\"\n)\n\nconst instanceIDLogKey = \"instance-id\"\nconst bindingIDLogKey = \"binding-id\"\nconst detailsLogKey = \"details\"\nconst acceptsIncompleteLogKey = \"acceptsIncomplete\"\n\nvar (\n\tErrNoClientConfigured = errors.New(\"This broker is not configured to support binding to additional instances. Contact your Cloud Foundry operator for details.\")\n)\n\ntype S3Broker struct {\n\tiamPath                      string\n\tuserPrefix                   string\n\tpolicyPrefix                 string\n\tbucketPrefix                 string\n\tawsPartition                 string\n\tallowUserProvisionParameters bool\n\tallowUserUpdateParameters    bool\n\tallowUserBindParameters      bool\n\tcatalog                      Catalog\n\tbucket                       awss3.Bucket\n\tuser                         awsiam.User\n\tcfClient                     *cfclient.Client\n\tlogger                       lager.Logger\n}\n\ntype CatalogExternal struct {\n\tServices []brokerapi.Service `json:\"services\"`\n}\n\ntype Credentials struct {\n\tAccessKeyID       string   `json:\"access_key_id\"`\n\tSecretAccessKey   string   `json:\"secret_access_key\"`\n\tRegion            string   `json:\"region\"`\n\tBucket            string   `json:\"bucket\"`\n\tAdditionalBuckets []string `json:\"additional_buckets\"`\n}\n\nfunc New(\n\tconfig Config,\n\tbucket awss3.Bucket,\n\tuser awsiam.User,\n\tcfClient *cfclient.Client,\n\tlogger lager.Logger,\n) *S3Broker {\n\treturn &S3Broker{\n\t\tiamPath:                      config.IamPath,\n\t\tuserPrefix:                   config.UserPrefix,\n\t\tpolicyPrefix:                 config.PolicyPrefix,\n\t\tbucketPrefix:                 config.BucketPrefix,\n\t\tawsPartition:                 config.AwsPartition,\n\t\tallowUserProvisionParameters: config.AllowUserProvisionParameters,\n\t\tallowUserUpdateParameters:    config.AllowUserUpdateParameters,\n\t\tcatalog:                      config.Catalog,\n\t\tbucket:                       bucket,\n\t\tuser:                         user,\n\t\tcfClient:                     cfClient,\n\t\tlogger:                       logger.Session(\"broker\"),\n\t}\n}\n\nfunc (b *S3Broker) Services(context context.Context) []brokerapi.Service {\n\tbrokerCatalog, err := json.Marshal(b.catalog)\n\tif err != nil {\n\t\tb.logger.Error(\"marshal-error\", err)\n\t\treturn []brokerapi.Service{}\n\t}\n\n\tapiCatalog := CatalogExternal{}\n\tif err = json.Unmarshal(brokerCatalog, &apiCatalog); err != nil {\n\t\tb.logger.Error(\"unmarshal-error\", err)\n\t\treturn []brokerapi.Service{}\n\t}\n\n\treturn apiCatalog.Services\n}\n\nfunc (b *S3Broker) Provision(\n\tcontext context.Context,\n\tinstanceID string,\n\tdetails brokerapi.ProvisionDetails,\n\tasyncAllowed bool,\n) (brokerapi.ProvisionedServiceSpec, error) {\n\tb.logger.Debug(\"provision\", lager.Data{\n\t\tinstanceIDLogKey:        instanceID,\n\t\tdetailsLogKey:           details,\n\t\tacceptsIncompleteLogKey: asyncAllowed,\n\t})\n\n\tprovisionParameters := ProvisionParameters{}\n\tif b.allowUserProvisionParameters && len(details.RawParameters) > 0 {\n\t\tif err := json.Unmarshal(details.RawParameters, &provisionParameters); err != nil {\n\t\t\treturn brokerapi.ProvisionedServiceSpec{}, err\n\t\t}\n\t}\n\n\tservicePlan, ok := b.catalog.FindServicePlan(details.PlanID)\n\tif !ok {\n\t\treturn brokerapi.ProvisionedServiceSpec{}, fmt.Errorf(\"Service Plan '%s' not found\", details.PlanID)\n\t}\n\n\tvar err error\n\tinstance := b.createBucket(instanceID, servicePlan, provisionParameters, details)\n\tif _, err = b.bucket.Create(b.bucketName(instanceID), *instance); err != nil {\n\t\treturn brokerapi.ProvisionedServiceSpec{}, err\n\t}\n\n\treturn brokerapi.ProvisionedServiceSpec{IsAsync: false}, nil\n}\n\nfunc (b *S3Broker) Update(\n\tcontext context.Context,\n\tinstanceID string,\n\tdetails brokerapi.UpdateDetails,\n\tasyncAllowed bool,\n) (brokerapi.UpdateServiceSpec, error) {\n\tb.logger.Debug(\"update\", lager.Data{\n\t\tinstanceIDLogKey:        instanceID,\n\t\tdetailsLogKey:           details,\n\t\tacceptsIncompleteLogKey: asyncAllowed,\n\t})\n\n\tupdateParameters := UpdateParameters{}\n\tif b.allowUserUpdateParameters && len(details.RawParameters) > 0 {\n\t\tif err := json.Unmarshal(details.RawParameters, &updateParameters); err != nil {\n\t\t\treturn brokerapi.UpdateServiceSpec{}, err\n\t\t}\n\t}\n\n\tservicePlan, ok := b.catalog.FindServicePlan(details.PlanID)\n\tif !ok {\n\t\treturn brokerapi.UpdateServiceSpec{}, fmt.Errorf(\"Service Plan '%s' not found\", details.PlanID)\n\t}\n\n\tinstance := b.modifyBucket(instanceID, servicePlan, updateParameters, details)\n\tif err := b.bucket.Modify(b.bucketName(instanceID), *instance); err != nil {\n\t\tif err == awss3.ErrBucketDoesNotExist {\n\t\t\treturn brokerapi.UpdateServiceSpec{}, brokerapi.ErrInstanceDoesNotExist\n\t\t}\n\t\treturn brokerapi.UpdateServiceSpec{}, err\n\t}\n\n\treturn brokerapi.UpdateServiceSpec{IsAsync: false}, nil\n}\n\nfunc (b *S3Broker) Deprovision(\n\tcontext context.Context,\n\tinstanceID string,\n\tdetails brokerapi.DeprovisionDetails,\n\tasyncAllowed bool,\n) (brokerapi.DeprovisionServiceSpec, error) {\n\tb.logger.Debug(\"deprovision\", lager.Data{\n\t\tinstanceIDLogKey:        instanceID,\n\t\tdetailsLogKey:           details,\n\t\tacceptsIncompleteLogKey: asyncAllowed,\n\t})\n\n\tif err := b.bucket.Delete(b.bucketName(instanceID)); err != nil {\n\t\tif err == awss3.ErrBucketDoesNotExist {\n\t\t\treturn brokerapi.DeprovisionServiceSpec{}, brokerapi.ErrInstanceDoesNotExist\n\t\t}\n\t\treturn brokerapi.DeprovisionServiceSpec{}, err\n\t}\n\n\treturn brokerapi.DeprovisionServiceSpec{IsAsync: false}, nil\n}\n\nfunc (b *S3Broker) getBucketNames(instanceNames []string, instanceGUID, serviceGUID string) ([]string, error) {\n\tvar bucketNames []string\n\n\tinstance, err := b.cfClient.ServiceInstanceByGuid(instanceGUID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tquery := url.Values{}\n\tquery.Set(\"space_guid\", instance.SpaceGuid)\n\tquery.Set(\"plan_guid\", serviceGUID)\n\tinstances, err := b.cfClient.ListServiceInstancesByQuery(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinstanceGUIDs := make(map[string]string, len(instanceNames))\n\tfor _, instance := range instances {\n\t\tinstanceGUIDs[instance.Name] = instance.Guid\n\t}\n\n\tfor _, instanceName := range instanceNames {\n\t\tinstanceGUID, ok := instanceGUIDs[instanceName]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Service instance %s not found\", instanceName)\n\t\t}\n\t\tbucketNames = append(bucketNames, b.bucketName(instanceGUID))\n\t}\n\n\treturn bucketNames, nil\n}\n\nfunc (b *S3Broker) Bind(\n\tcontext context.Context,\n\tinstanceID, bindingID string,\n\tdetails brokerapi.BindDetails,\n) (brokerapi.Binding, error) {\n\tb.logger.Debug(\"bind\", lager.Data{\n\t\tinstanceIDLogKey: instanceID,\n\t\tbindingIDLogKey:  bindingID,\n\t\tdetailsLogKey:    details,\n\t})\n\n\tbinding := brokerapi.Binding{}\n\n\tvar accessKeyID, secretAccessKey string\n\tvar policyARN string\n\tvar err error\n\n\tservicePlan, ok := b.catalog.FindServicePlan(details.PlanID)\n\tif !ok {\n\t\treturn binding, fmt.Errorf(\"Service Plan '%s' not found\", details.PlanID)\n\t}\n\n\tbindParameters := BindParameters{}\n\tif len(details.RawParameters) > 0 {\n\t\tif err := json.Unmarshal(details.RawParameters, &bindParameters); err != nil {\n\t\t\treturn binding, err\n\t\t}\n\t}\n\n\tbucketNames := []string{b.bucketName(instanceID)}\n\tif len(bindParameters.AdditionalInstances) > 0 {\n\t\tif b.cfClient == nil {\n\t\t\treturn binding, ErrNoClientConfigured\n\t\t}\n\t\tadditionalNames, err := b.getBucketNames(bindParameters.AdditionalInstances, instanceID, details.ServiceID)\n\t\tif err != nil {\n\t\t\treturn binding, err\n\t\t}\n\t\tbucketNames = append(bucketNames, additionalNames...)\n\t}\n\n\tcredentials := Credentials{AdditionalBuckets: []string{}}\n\tbucketARNs := make([]string, len(bucketNames))\n\tdetailc, errc := make(chan awss3.BucketDetails), make(chan error)\n\tfor _, bucketName := range bucketNames {\n\t\tgo func(bucketName string) {\n\t\t\tbucketDetails, err := b.bucket.Describe(bucketName, b.awsPartition)\n\t\t\tif err != nil {\n\t\t\t\tif err == awss3.ErrBucketDoesNotExist {\n\t\t\t\t\terrc <- brokerapi.ErrInstanceDoesNotExist\n\t\t\t\t}\n\t\t\t\terrc <- err\n\t\t\t} else {\n\t\t\t\tdetailc <- bucketDetails\n\t\t\t}\n\t\t}(bucketName)\n\t}\n\tfor idx, _ := range bucketNames {\n\t\tselect {\n\t\tcase bucketDetails := <-detailc:\n\t\t\tbucketARNs[idx] = bucketDetails.ARN\n\t\t\tif bucketDetails.BucketName == b.bucketName(instanceID) {\n\t\t\t\tcredentials.Bucket = bucketDetails.BucketName\n\t\t\t\tcredentials.Region = bucketDetails.Region\n\t\t\t} else {\n\t\t\t\tcredentials.AdditionalBuckets = append(credentials.AdditionalBuckets, bucketDetails.BucketName)\n\t\t\t}\n\t\tcase err := <-errc:\n\t\t\treturn binding, err\n\t\t}\n\t}\n\n\tif _, err = b.user.Create(b.userName(bindingID), b.iamPath); err != nil {\n\t\treturn binding, err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif policyARN != \"\" {\n\t\t\t\tb.user.DeletePolicy(policyARN)\n\t\t\t}\n\t\t\tif accessKeyID != \"\" {\n\t\t\t\tb.user.DeleteAccessKey(b.userName(bindingID), accessKeyID)\n\t\t\t}\n\t\t\tb.user.Delete(b.userName(bindingID))\n\t\t}\n\t}()\n\n\taccessKeyID, secretAccessKey, err = b.user.CreateAccessKey(b.userName(bindingID))\n\tif err != nil {\n\t\treturn binding, err\n\t}\n\n\tpolicyARN, err = b.user.CreatePolicy(b.policyName(bindingID), b.iamPath, string(servicePlan.S3Properties.IamPolicy), bucketARNs)\n\tif err != nil {\n\t\treturn binding, err\n\t}\n\n\tif err = b.user.AttachUserPolicy(b.userName(bindingID), policyARN); err != nil {\n\t\treturn binding, err\n\t}\n\n\tcredentials.AccessKeyID = accessKeyID\n\tcredentials.SecretAccessKey = secretAccessKey\n\tbinding.Credentials = credentials\n\n\treturn binding, nil\n}\n\nfunc (b *S3Broker) Unbind(\n\tcontext context.Context,\n\tinstanceID, bindingID string,\n\tdetails brokerapi.UnbindDetails,\n) error {\n\tb.logger.Debug(\"unbind\", lager.Data{\n\t\tinstanceIDLogKey: instanceID,\n\t\tbindingIDLogKey:  bindingID,\n\t\tdetailsLogKey:    details,\n\t})\n\n\taccessKeys, err := b.user.ListAccessKeys(b.userName(bindingID))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, accessKey := range accessKeys {\n\t\tif err := b.user.DeleteAccessKey(b.userName(bindingID), accessKey); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tuserPolicies, err := b.user.ListAttachedUserPolicies(b.userName(bindingID), b.iamPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, userPolicy := range userPolicies {\n\t\tif err := b.user.DetachUserPolicy(b.userName(bindingID), userPolicy); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := b.user.DeletePolicy(userPolicy); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := b.user.Delete(b.userName(bindingID)); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (b *S3Broker) LastOperation(\n\tcontext context.Context,\n\tinstanceID, operationData string,\n) (brokerapi.LastOperation, error) {\n\tb.logger.Debug(\"last-operation\", lager.Data{\n\t\tinstanceIDLogKey: instanceID,\n\t})\n\n\treturn brokerapi.LastOperation{}, errors.New(\"This broker does not support LastOperation\")\n}\n\nfunc (b *S3Broker) bucketName(instanceID string) string {\n\treturn fmt.Sprintf(\"%s-%s\", b.bucketPrefix, instanceID)\n}\n\nfunc (b *S3Broker) userName(bindingID string) string {\n\treturn fmt.Sprintf(\"%s-%s\", b.userPrefix, bindingID)\n}\n\nfunc (b *S3Broker) policyName(bindingID string) string {\n\treturn fmt.Sprintf(\"%s-%s\", b.policyPrefix, bindingID)\n}\n\nfunc (b *S3Broker) createBucket(instanceID string, servicePlan ServicePlan, provisionParameters ProvisionParameters, details brokerapi.ProvisionDetails) *awss3.BucketDetails {\n\tbucketDetails := b.bucketFromPlan(servicePlan)\n\tbucketDetails.Tags = b.bucketTags(\"Created\", details.ServiceID, details.PlanID, details.OrganizationGUID, details.SpaceGUID)\n\tbucketDetails.Policy = string(servicePlan.S3Properties.BucketPolicy)\n\tbucketDetails.AwsPartition = b.awsPartition\n\treturn bucketDetails\n}\n\nfunc (b *S3Broker) modifyBucket(instanceID string, servicePlan ServicePlan, updateParameters UpdateParameters, details brokerapi.UpdateDetails) *awss3.BucketDetails {\n\tbucketDetails := b.bucketFromPlan(servicePlan)\n\tbucketDetails.Tags = b.bucketTags(\"Updated\", details.ServiceID, details.PlanID, \"\", \"\")\n\treturn bucketDetails\n}\n\nfunc (b *S3Broker) bucketFromPlan(servicePlan ServicePlan) *awss3.BucketDetails {\n\tbucketDetails := &awss3.BucketDetails{}\n\treturn bucketDetails\n}\n\nfunc (b *S3Broker) bucketTags(action, serviceID, planID, organizationID, spaceID string) map[string]string {\n\ttags := make(map[string]string)\n\n\ttags[\"Owner\"] = \"Cloud Foundry\"\n\n\ttags[action+\" by\"] = \"AWS S3 Service Broker\"\n\n\ttags[action+\" at\"] = time.Now().Format(time.RFC822Z)\n\n\tif serviceID != \"\" {\n\t\ttags[\"Service ID\"] = serviceID\n\t}\n\n\tif planID != \"\" {\n\t\ttags[\"Plan ID\"] = planID\n\t}\n\n\tif organizationID != \"\" {\n\t\ttags[\"Organization ID\"] = organizationID\n\t}\n\n\tif spaceID != \"\" {\n\t\ttags[\"Space ID\"] = spaceID\n\t}\n\treturn tags\n}\n<commit_msg>Include a URI with the S3 bucket credentials<commit_after>package broker\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/lager\"\n\t\"github.com\/cloudfoundry-community\/go-cfclient\"\n\t\"github.com\/pivotal-cf\/brokerapi\"\n\n\t\"github.com\/cloudfoundry-community\/s3-broker\/awsiam\"\n\t\"github.com\/cloudfoundry-community\/s3-broker\/awss3\"\n)\n\nconst instanceIDLogKey = \"instance-id\"\nconst bindingIDLogKey = \"binding-id\"\nconst detailsLogKey = \"details\"\nconst acceptsIncompleteLogKey = \"acceptsIncomplete\"\n\nvar (\n\tErrNoClientConfigured = errors.New(\"This broker is not configured to support binding to additional instances. Contact your Cloud Foundry operator for details.\")\n)\n\ntype S3Broker struct {\n\tiamPath                      string\n\tuserPrefix                   string\n\tpolicyPrefix                 string\n\tbucketPrefix                 string\n\tawsPartition                 string\n\tallowUserProvisionParameters bool\n\tallowUserUpdateParameters    bool\n\tallowUserBindParameters      bool\n\tcatalog                      Catalog\n\tbucket                       awss3.Bucket\n\tuser                         awsiam.User\n\tcfClient                     *cfclient.Client\n\tlogger                       lager.Logger\n}\n\ntype CatalogExternal struct {\n\tServices []brokerapi.Service `json:\"services\"`\n}\n\ntype Credentials struct {\n\tURI               string   `json:\"URI\"`\n\tAccessKeyID       string   `json:\"access_key_id\"`\n\tSecretAccessKey   string   `json:\"secret_access_key\"`\n\tRegion            string   `json:\"region\"`\n\tBucket            string   `json:\"bucket\"`\n\tAdditionalBuckets []string `json:\"additional_buckets\"`\n}\n\nfunc New(\n\tconfig Config,\n\tbucket awss3.Bucket,\n\tuser awsiam.User,\n\tcfClient *cfclient.Client,\n\tlogger lager.Logger,\n) *S3Broker {\n\treturn &S3Broker{\n\t\tiamPath:                      config.IamPath,\n\t\tuserPrefix:                   config.UserPrefix,\n\t\tpolicyPrefix:                 config.PolicyPrefix,\n\t\tbucketPrefix:                 config.BucketPrefix,\n\t\tawsPartition:                 config.AwsPartition,\n\t\tallowUserProvisionParameters: config.AllowUserProvisionParameters,\n\t\tallowUserUpdateParameters:    config.AllowUserUpdateParameters,\n\t\tcatalog:                      config.Catalog,\n\t\tbucket:                       bucket,\n\t\tuser:                         user,\n\t\tcfClient:                     cfClient,\n\t\tlogger:                       logger.Session(\"broker\"),\n\t}\n}\n\nfunc (b *S3Broker) Services(context context.Context) []brokerapi.Service {\n\tbrokerCatalog, err := json.Marshal(b.catalog)\n\tif err != nil {\n\t\tb.logger.Error(\"marshal-error\", err)\n\t\treturn []brokerapi.Service{}\n\t}\n\n\tapiCatalog := CatalogExternal{}\n\tif err = json.Unmarshal(brokerCatalog, &apiCatalog); err != nil {\n\t\tb.logger.Error(\"unmarshal-error\", err)\n\t\treturn []brokerapi.Service{}\n\t}\n\n\treturn apiCatalog.Services\n}\n\nfunc (b *S3Broker) Provision(\n\tcontext context.Context,\n\tinstanceID string,\n\tdetails brokerapi.ProvisionDetails,\n\tasyncAllowed bool,\n) (brokerapi.ProvisionedServiceSpec, error) {\n\tb.logger.Debug(\"provision\", lager.Data{\n\t\tinstanceIDLogKey:        instanceID,\n\t\tdetailsLogKey:           details,\n\t\tacceptsIncompleteLogKey: asyncAllowed,\n\t})\n\n\tprovisionParameters := ProvisionParameters{}\n\tif b.allowUserProvisionParameters && len(details.RawParameters) > 0 {\n\t\tif err := json.Unmarshal(details.RawParameters, &provisionParameters); err != nil {\n\t\t\treturn brokerapi.ProvisionedServiceSpec{}, err\n\t\t}\n\t}\n\n\tservicePlan, ok := b.catalog.FindServicePlan(details.PlanID)\n\tif !ok {\n\t\treturn brokerapi.ProvisionedServiceSpec{}, fmt.Errorf(\"Service Plan '%s' not found\", details.PlanID)\n\t}\n\n\tvar err error\n\tinstance := b.createBucket(instanceID, servicePlan, provisionParameters, details)\n\tif _, err = b.bucket.Create(b.bucketName(instanceID), *instance); err != nil {\n\t\treturn brokerapi.ProvisionedServiceSpec{}, err\n\t}\n\n\treturn brokerapi.ProvisionedServiceSpec{IsAsync: false}, nil\n}\n\nfunc (b *S3Broker) Update(\n\tcontext context.Context,\n\tinstanceID string,\n\tdetails brokerapi.UpdateDetails,\n\tasyncAllowed bool,\n) (brokerapi.UpdateServiceSpec, error) {\n\tb.logger.Debug(\"update\", lager.Data{\n\t\tinstanceIDLogKey:        instanceID,\n\t\tdetailsLogKey:           details,\n\t\tacceptsIncompleteLogKey: asyncAllowed,\n\t})\n\n\tupdateParameters := UpdateParameters{}\n\tif b.allowUserUpdateParameters && len(details.RawParameters) > 0 {\n\t\tif err := json.Unmarshal(details.RawParameters, &updateParameters); err != nil {\n\t\t\treturn brokerapi.UpdateServiceSpec{}, err\n\t\t}\n\t}\n\n\tservicePlan, ok := b.catalog.FindServicePlan(details.PlanID)\n\tif !ok {\n\t\treturn brokerapi.UpdateServiceSpec{}, fmt.Errorf(\"Service Plan '%s' not found\", details.PlanID)\n\t}\n\n\tinstance := b.modifyBucket(instanceID, servicePlan, updateParameters, details)\n\tif err := b.bucket.Modify(b.bucketName(instanceID), *instance); err != nil {\n\t\tif err == awss3.ErrBucketDoesNotExist {\n\t\t\treturn brokerapi.UpdateServiceSpec{}, brokerapi.ErrInstanceDoesNotExist\n\t\t}\n\t\treturn brokerapi.UpdateServiceSpec{}, err\n\t}\n\n\treturn brokerapi.UpdateServiceSpec{IsAsync: false}, nil\n}\n\nfunc (b *S3Broker) Deprovision(\n\tcontext context.Context,\n\tinstanceID string,\n\tdetails brokerapi.DeprovisionDetails,\n\tasyncAllowed bool,\n) (brokerapi.DeprovisionServiceSpec, error) {\n\tb.logger.Debug(\"deprovision\", lager.Data{\n\t\tinstanceIDLogKey:        instanceID,\n\t\tdetailsLogKey:           details,\n\t\tacceptsIncompleteLogKey: asyncAllowed,\n\t})\n\n\tif err := b.bucket.Delete(b.bucketName(instanceID)); err != nil {\n\t\tif err == awss3.ErrBucketDoesNotExist {\n\t\t\treturn brokerapi.DeprovisionServiceSpec{}, brokerapi.ErrInstanceDoesNotExist\n\t\t}\n\t\treturn brokerapi.DeprovisionServiceSpec{}, err\n\t}\n\n\treturn brokerapi.DeprovisionServiceSpec{IsAsync: false}, nil\n}\n\nfunc (b *S3Broker) getBucketURI(credentials Credentials) string { \n\tvar endpoint string\n\tif credentials.Region == \"us-east-1\" {\n\t\tendpoint = \"s3.amazonaws.com\"\n\t} else {\n\t\tendpoint = \"s3-\" + credentials.Region + \".amazonaws.com\"\n\t}\n\treturn fmt.Sprintf(\"s3:\/\/%s:%s@%s\/%s\", credentials.AccessKeyID, credentials.SecretAccessKey, endpoint, credentials.Bucket)\n}\n\n\nfunc (b *S3Broker) getBucketNames(instanceNames []string, instanceGUID, serviceGUID string) ([]string, error) {\n\tvar bucketNames []string\n\n\tinstance, err := b.cfClient.ServiceInstanceByGuid(instanceGUID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tquery := url.Values{}\n\tquery.Set(\"space_guid\", instance.SpaceGuid)\n\tquery.Set(\"plan_guid\", serviceGUID)\n\tinstances, err := b.cfClient.ListServiceInstancesByQuery(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinstanceGUIDs := make(map[string]string, len(instanceNames))\n\tfor _, instance := range instances {\n\t\tinstanceGUIDs[instance.Name] = instance.Guid\n\t}\n\n\tfor _, instanceName := range instanceNames {\n\t\tinstanceGUID, ok := instanceGUIDs[instanceName]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Service instance %s not found\", instanceName)\n\t\t}\n\t\tbucketNames = append(bucketNames, b.bucketName(instanceGUID))\n\t}\n\n\treturn bucketNames, nil\n}\n\nfunc (b *S3Broker) Bind(\n\tcontext context.Context,\n\tinstanceID, bindingID string,\n\tdetails brokerapi.BindDetails,\n) (brokerapi.Binding, error) {\n\tb.logger.Debug(\"bind\", lager.Data{\n\t\tinstanceIDLogKey: instanceID,\n\t\tbindingIDLogKey:  bindingID,\n\t\tdetailsLogKey:    details,\n\t})\n\n\tbinding := brokerapi.Binding{}\n\n\tvar accessKeyID, secretAccessKey string\n\tvar policyARN string\n\tvar err error\n\n\tservicePlan, ok := b.catalog.FindServicePlan(details.PlanID)\n\tif !ok {\n\t\treturn binding, fmt.Errorf(\"Service Plan '%s' not found\", details.PlanID)\n\t}\n\n\tbindParameters := BindParameters{}\n\tif len(details.RawParameters) > 0 {\n\t\tif err := json.Unmarshal(details.RawParameters, &bindParameters); err != nil {\n\t\t\treturn binding, err\n\t\t}\n\t}\n\n\tbucketNames := []string{b.bucketName(instanceID)}\n\tif len(bindParameters.AdditionalInstances) > 0 {\n\t\tif b.cfClient == nil {\n\t\t\treturn binding, ErrNoClientConfigured\n\t\t}\n\t\tadditionalNames, err := b.getBucketNames(bindParameters.AdditionalInstances, instanceID, details.ServiceID)\n\t\tif err != nil {\n\t\t\treturn binding, err\n\t\t}\n\t\tbucketNames = append(bucketNames, additionalNames...)\n\t}\n\n\tcredentials := Credentials{AdditionalBuckets: []string{}}\n\tbucketARNs := make([]string, len(bucketNames))\n\tdetailc, errc := make(chan awss3.BucketDetails), make(chan error)\n\tfor _, bucketName := range bucketNames {\n\t\tgo func(bucketName string) {\n\t\t\tbucketDetails, err := b.bucket.Describe(bucketName, b.awsPartition)\n\t\t\tif err != nil {\n\t\t\t\tif err == awss3.ErrBucketDoesNotExist {\n\t\t\t\t\terrc <- brokerapi.ErrInstanceDoesNotExist\n\t\t\t\t}\n\t\t\t\terrc <- err\n\t\t\t} else {\n\t\t\t\tdetailc <- bucketDetails\n\t\t\t}\n\t\t}(bucketName)\n\t}\n\tfor idx, _ := range bucketNames {\n\t\tselect {\n\t\tcase bucketDetails := <-detailc:\n\t\t\tbucketARNs[idx] = bucketDetails.ARN\n\t\t\tif bucketDetails.BucketName == b.bucketName(instanceID) {\n\t\t\t\tcredentials.Bucket = bucketDetails.BucketName\n\t\t\t\tcredentials.Region = bucketDetails.Region\n\t\t\t} else {\n\t\t\t\tcredentials.AdditionalBuckets = append(credentials.AdditionalBuckets, bucketDetails.BucketName)\n\t\t\t}\n\t\tcase err := <-errc:\n\t\t\treturn binding, err\n\t\t}\n\t}\n\n\tif _, err = b.user.Create(b.userName(bindingID), b.iamPath); err != nil {\n\t\treturn binding, err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tif policyARN != \"\" {\n\t\t\t\tb.user.DeletePolicy(policyARN)\n\t\t\t}\n\t\t\tif accessKeyID != \"\" {\n\t\t\t\tb.user.DeleteAccessKey(b.userName(bindingID), accessKeyID)\n\t\t\t}\n\t\t\tb.user.Delete(b.userName(bindingID))\n\t\t}\n\t}()\n\n\taccessKeyID, secretAccessKey, err = b.user.CreateAccessKey(b.userName(bindingID))\n\tif err != nil {\n\t\treturn binding, err\n\t}\n\n\tpolicyARN, err = b.user.CreatePolicy(b.policyName(bindingID), b.iamPath, string(servicePlan.S3Properties.IamPolicy), bucketARNs)\n\tif err != nil {\n\t\treturn binding, err\n\t}\n\n\tif err = b.user.AttachUserPolicy(b.userName(bindingID), policyARN); err != nil {\n\t\treturn binding, err\n\t}\n\n\tcredentials.URI = b.getBucketURI(credentials)\n\tcredentials.AccessKeyID = accessKeyID\n\tcredentials.SecretAccessKey = secretAccessKey\n\tbinding.Credentials = credentials\n\n\treturn binding, nil\n}\n\nfunc (b *S3Broker) Unbind(\n\tcontext context.Context,\n\tinstanceID, bindingID string,\n\tdetails brokerapi.UnbindDetails,\n) error {\n\tb.logger.Debug(\"unbind\", lager.Data{\n\t\tinstanceIDLogKey: instanceID,\n\t\tbindingIDLogKey:  bindingID,\n\t\tdetailsLogKey:    details,\n\t})\n\n\taccessKeys, err := b.user.ListAccessKeys(b.userName(bindingID))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, accessKey := range accessKeys {\n\t\tif err := b.user.DeleteAccessKey(b.userName(bindingID), accessKey); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tuserPolicies, err := b.user.ListAttachedUserPolicies(b.userName(bindingID), b.iamPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, userPolicy := range userPolicies {\n\t\tif err := b.user.DetachUserPolicy(b.userName(bindingID), userPolicy); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := b.user.DeletePolicy(userPolicy); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := b.user.Delete(b.userName(bindingID)); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (b *S3Broker) LastOperation(\n\tcontext context.Context,\n\tinstanceID, operationData string,\n) (brokerapi.LastOperation, error) {\n\tb.logger.Debug(\"last-operation\", lager.Data{\n\t\tinstanceIDLogKey: instanceID,\n\t})\n\n\treturn brokerapi.LastOperation{}, errors.New(\"This broker does not support LastOperation\")\n}\n\nfunc (b *S3Broker) bucketName(instanceID string) string {\n\treturn fmt.Sprintf(\"%s-%s\", b.bucketPrefix, instanceID)\n}\n\nfunc (b *S3Broker) userName(bindingID string) string {\n\treturn fmt.Sprintf(\"%s-%s\", b.userPrefix, bindingID)\n}\n\nfunc (b *S3Broker) policyName(bindingID string) string {\n\treturn fmt.Sprintf(\"%s-%s\", b.policyPrefix, bindingID)\n}\n\nfunc (b *S3Broker) createBucket(instanceID string, servicePlan ServicePlan, provisionParameters ProvisionParameters, details brokerapi.ProvisionDetails) *awss3.BucketDetails {\n\tbucketDetails := b.bucketFromPlan(servicePlan)\n\tbucketDetails.Tags = b.bucketTags(\"Created\", details.ServiceID, details.PlanID, details.OrganizationGUID, details.SpaceGUID)\n\tbucketDetails.Policy = string(servicePlan.S3Properties.BucketPolicy)\n\tbucketDetails.AwsPartition = b.awsPartition\n\treturn bucketDetails\n}\n\nfunc (b *S3Broker) modifyBucket(instanceID string, servicePlan ServicePlan, updateParameters UpdateParameters, details brokerapi.UpdateDetails) *awss3.BucketDetails {\n\tbucketDetails := b.bucketFromPlan(servicePlan)\n\tbucketDetails.Tags = b.bucketTags(\"Updated\", details.ServiceID, details.PlanID, \"\", \"\")\n\treturn bucketDetails\n}\n\nfunc (b *S3Broker) bucketFromPlan(servicePlan ServicePlan) *awss3.BucketDetails {\n\tbucketDetails := &awss3.BucketDetails{}\n\treturn bucketDetails\n}\n\nfunc (b *S3Broker) bucketTags(action, serviceID, planID, organizationID, spaceID string) map[string]string {\n\ttags := make(map[string]string)\n\n\ttags[\"Owner\"] = \"Cloud Foundry\"\n\n\ttags[action+\" by\"] = \"AWS S3 Service Broker\"\n\n\ttags[action+\" at\"] = time.Now().Format(time.RFC822Z)\n\n\tif serviceID != \"\" {\n\t\ttags[\"Service ID\"] = serviceID\n\t}\n\n\tif planID != \"\" {\n\t\ttags[\"Plan ID\"] = planID\n\t}\n\n\tif organizationID != \"\" {\n\t\ttags[\"Organization ID\"] = organizationID\n\t}\n\n\tif spaceID != \"\" {\n\t\ttags[\"Space ID\"] = spaceID\n\t}\n\treturn tags\n}\n<|endoftext|>"}
{"text":"<commit_before>package browser\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/moovweb\/gokogiri\"\n\t\"github.com\/moovweb\/gokogiri\/xml\"\n)\n\ntype Form struct {\n\tAction string\n\tMethod string\n\n\tInputs []*Input\n}\n\nfunc (f *Form) FillIn(name string, value string) error {\n\tfor _, i := range f.Inputs {\n\t\tif i.Name == name {\n\t\t\ti.Value = value\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"no input with Name %q found\", name)\n}\n\ntype Input struct {\n\tType    string\n\tName    string\n\tValue   string\n\tChecked bool\n}\n\nfunc loadForms(baseUrl string, b []byte) ([]*Form, error) {\n\tu, e := url.Parse(baseUrl)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tdoc, e := gokogiri.ParseHtml(b)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tformTags, e := doc.Search(\"\/\/form\")\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tout := []*Form{}\n\tfor _, node := range formTags {\n\t\taction := node.Attr(\"action\")\n\t\tif !strings.HasPrefix(action, \"http\") {\n\t\t\tbase := u.Scheme + \":\/\/\" + u.Host\n\t\t\tif strings.HasPrefix(action, \"\/\") {\n\t\t\t\taction = base + action\n\t\t\t} else {\n\t\t\t\taction = base + u.Path + action\n\t\t\t}\n\t\t}\n\t\tf := &Form{Method: node.Attr(\"method\"), Action: action}\n\t\tf.Inputs, e = loadInputs(node)\n\t\tif e != nil {\n\t\t\treturn nil, e\n\t\t}\n\t\tout = append(out, f)\n\t}\n\treturn out, nil\n}\n\nfunc loadInputs(doc xml.Node) ([]*Input, error) {\n\tnodes, e := doc.Search(\".\/\/input\")\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tout := []*Input{}\n\tfor _, n := range nodes {\n\t\ti := &Input{\n\t\t\tType:    n.Attr(\"type\"),\n\t\t\tName:    n.Attr(\"name\"),\n\t\t\tValue:   n.Attr(\"value\"),\n\t\t\tChecked: n.Attr(\"checked\") == \"checked\",\n\t\t}\n\t\tout = append(out, i)\n\t}\n\treturn out, nil\n\n}\n<commit_msg>fix missing slashes in actions<commit_after>package browser\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/moovweb\/gokogiri\"\n\t\"github.com\/moovweb\/gokogiri\/xml\"\n)\n\ntype Form struct {\n\tAction string\n\tMethod string\n\n\tInputs []*Input\n}\n\nfunc (f *Form) FillIn(name string, value string) error {\n\tfor _, i := range f.Inputs {\n\t\tif i.Name == name {\n\t\t\ti.Value = value\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"no input with Name %q found\", name)\n}\n\ntype Input struct {\n\tType    string\n\tName    string\n\tValue   string\n\tChecked bool\n}\n\nfunc loadForms(baseUrl string, b []byte) ([]*Form, error) {\n\tu, e := url.Parse(baseUrl)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tdoc, e := gokogiri.ParseHtml(b)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tformTags, e := doc.Search(\"\/\/form\")\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tout := []*Form{}\n\tfor _, node := range formTags {\n\t\taction := node.Attr(\"action\")\n\t\tif !strings.HasPrefix(action, \"http\") {\n\t\t\tbase := u.Scheme + \":\/\/\" + u.Host\n\t\t\tif strings.HasPrefix(action, \"\/\") {\n\t\t\t\taction = base + action\n\t\t\t} else {\n\t\t\t\taction = base + u.Path + \"\/\" + strings.TrimPrefix(action, \"\/\")\n\t\t\t}\n\t\t}\n\t\tf := &Form{Method: node.Attr(\"method\"), Action: action}\n\t\tf.Inputs, e = loadInputs(node)\n\t\tif e != nil {\n\t\t\treturn nil, e\n\t\t}\n\t\tout = append(out, f)\n\t}\n\treturn out, nil\n}\n\nfunc loadInputs(doc xml.Node) ([]*Input, error) {\n\tnodes, e := doc.Search(\".\/\/input\")\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\tout := []*Input{}\n\tfor _, n := range nodes {\n\t\ti := &Input{\n\t\t\tType:    n.Attr(\"type\"),\n\t\t\tName:    n.Attr(\"name\"),\n\t\t\tValue:   n.Attr(\"value\"),\n\t\t\tChecked: n.Attr(\"checked\") == \"checked\",\n\t\t}\n\t\tout = append(out, i)\n\t}\n\treturn out, nil\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package eveConsumer\n\nimport (\n\t\"fmt\"\n\t\"log\"\n)\n\nfunc (c *EveConsumer) contactSync() {\n\trows, err := c.db.Query(\n\t\t`SELECT source, group_concat(destination)\n\t\t\tFROM contactSyncs GROUP BY source\n\t\t    HAVING max(nextSync) < UTC_TIMESTAMP()`)\n\ttx, err := c.db.Beginx()\n\tif err != nil {\n\t\tlog.Printf(\"EVEConsumer: Failed starting transaction: %v\", err)\n\t\treturn\n\t}\n\n\tfor rows.Next() {\n\t\tvar (\n\t\t\tsource int\n\t\t\tdest   string\n\t\t)\n\n\t\terr = rows.Scan(&source, &dest)\n\t\t\/\/destinations := strings.Split(dest, \",\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"EVEConsumer: Failed Scanning Rows: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tchar, err := c.eve.GetCharacterInfo(source)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"EVEConsumer: Failed getting character info %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%+v %+v\\n\", source, char)\n\n\t}\n\terr = tx.Commit()\n}\n<commit_msg>update<commit_after>package eveConsumer\n\nimport \"log\"\n\nfunc (c *EveConsumer) contactSync() {\n\trows, err := c.db.Query(\n\t\t`SELECT source, group_concat(destination)\n\t\t\tFROM contactSyncs GROUP BY source\n\t\t    HAVING max(nextSync) < UTC_TIMESTAMP()`)\n\ttx, err := c.db.Beginx()\n\tif err != nil {\n\t\tlog.Printf(\"EVEConsumer: Failed starting transaction: %v\", err)\n\t\treturn\n\t}\n\n\tfor rows.Next() {\n\t\tvar (\n\t\t\tsource int\n\t\t\tdest   string\n\t\t)\n\n\t\terr = rows.Scan(&source, &dest)\n\t\t\/\/destinations := strings.Split(dest, \",\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"EVEConsumer: Failed Scanning Rows: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tchar, err := c.eve.GetCharacterInfo(source)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"EVEConsumer: Failed getting character info %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif char.AllianceID > 0 {\n\n\t\t}\n\n\t}\n\terr = tx.Commit()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2015 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\npackage components\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/thethingsnetwork\/core\/utils\/pointer\"\n\t. \"github.com\/thethingsnetwork\/core\/utils\/testing\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/ The broker can handle an uplink packet\nfunc TestMarshaljson(t *testing.T) {\n\ttests := []struct {\n\t\tMetadata  Metadata\n\t\tWantError error\n\t\tWantJSON  string\n\t}{\n\t\t{ \/\/ Basic attributes, uint, string and float64\n\t\t\tMetadata{Chan: pointer.Uint(2), Codr: pointer.String(\"4\/6\"), Freq: pointer.Float64(864.125)},\n\t\t\tnil,\n\t\t\t`{\"chan\":2,\"codr\":\"4\/6\",\"freq\":864.125}`,\n\t\t},\n\n\t\t{ \/\/ Basic attributes #2, int and bool\n\t\t\tMetadata{Imme: pointer.Bool(true), Rssi: pointer.Int(-54)},\n\t\t\tnil,\n\t\t\t`{\"imme\":true,\"rssi\":-54}`,\n\t\t},\n\n\t\t{ \/\/ Datr attr, FSK type\n\t\t\tMetadata{Datr: pointer.String(\"50000\"), Modu: pointer.String(\"FSK\")},\n\t\t\tnil,\n\t\t\t`{\"modu\":\"FSK\",\"datr\":50000}`,\n\t\t},\n\n\t\t{ \/\/ Datr attr, lora modulation\n\t\t\tMetadata{Datr: pointer.String(\"SF7BW125\"), Modu: pointer.String(\"LORA\")},\n\t\t\tnil,\n\t\t\t`{\"modu\":\"LORA\",\"datr\":\"SF7BW125\"}`,\n\t\t},\n\n\t\t{ \/\/ Time attr\n\t\t\tMetadata{Time: pointer.Time(time.Date(2016, 1, 6, 15, 11, 12, 142, time.UTC))},\n\t\t\tnil,\n\t\t\t`{\"time\":\"2016-01-06T15:11:12.000000142Z\"}`,\n\t\t},\n\n\t\t{ \/\/ Mixed\n\t\t\tMetadata{\n\t\t\t\tTime: pointer.Time(time.Date(2016, 1, 6, 15, 11, 12, 142, time.UTC)),\n\t\t\t\tModu: pointer.String(\"FSK\"),\n\t\t\t\tDatr: pointer.String(\"50000\"),\n\t\t\t\tSize: pointer.Uint(14),\n\t\t\t\tLsnr: pointer.Float64(5.7),\n\t\t\t},\n\t\t\tnil,\n\t\t\t`{\"lsnr\":5.7,\"modu\":\"FSK\",\"size\":14,\"datr\":50000,\"time\":\"2016-01-06T15:11:12.000000142Z\"}`,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tDesc(t, \"Marshal medatadata: %v\", pointer.DumpPStruct(test.Metadata, false))\n\t\traw, err := json.Marshal(test.Metadata)\n\n\t\tif err != test.WantError {\n\t\t\tKo(t, \"Expected error to be %v but got %v\", test.WantError, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tstr := string(raw)\n\t\tif str != test.WantJSON {\n\t\t\tKo(t, \"Marshaled data don't match expectation.\\nWant: %s\\nGot:  %s\", test.WantJSON, str)\n\t\t\tcontinue\n\t\t}\n\t\tOk(t)\n\t}\n}\n<commit_msg>[broker] Write test for metadata.UnmarshalJSON()<commit_after>\/\/ Copyright © 2015 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\npackage components\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/thethingsnetwork\/core\/utils\/pointer\"\n\t. \"github.com\/thethingsnetwork\/core\/utils\/testing\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar commonTests = []struct {\n\tMetadata  Metadata\n\tWantError error\n\tJSON      string\n}{\n\t{ \/\/ Basic attributes, uint, string and float64\n\t\tMetadata{Chan: pointer.Uint(2), Codr: pointer.String(\"4\/6\"), Freq: pointer.Float64(864.125)},\n\t\tnil,\n\t\t`{\"chan\":2,\"codr\":\"4\/6\",\"freq\":864.125}`,\n\t},\n\n\t{ \/\/ Basic attributes #2, int and bool\n\t\tMetadata{Imme: pointer.Bool(true), Rssi: pointer.Int(-54)},\n\t\tnil,\n\t\t`{\"imme\":true,\"rssi\":-54}`,\n\t},\n\n\t{ \/\/ Datr attr, FSK type\n\t\tMetadata{Datr: pointer.String(\"50000\"), Modu: pointer.String(\"FSK\")},\n\t\tnil,\n\t\t`{\"modu\":\"FSK\",\"datr\":50000}`,\n\t},\n\n\t{ \/\/ Datr attr, lora modulation\n\t\tMetadata{Datr: pointer.String(\"SF7BW125\"), Modu: pointer.String(\"LORA\")},\n\t\tnil,\n\t\t`{\"modu\":\"LORA\",\"datr\":\"SF7BW125\"}`,\n\t},\n\n\t{ \/\/ Time attr\n\t\tMetadata{Time: pointer.Time(time.Date(2016, 1, 6, 15, 11, 12, 142, time.UTC))},\n\t\tnil,\n\t\t`{\"time\":\"2016-01-06T15:11:12.000000142Z\"}`,\n\t},\n\n\t{ \/\/ Mixed\n\t\tMetadata{\n\t\t\tTime: pointer.Time(time.Date(2016, 1, 6, 15, 11, 12, 142, time.UTC)),\n\t\t\tModu: pointer.String(\"FSK\"),\n\t\t\tDatr: pointer.String(\"50000\"),\n\t\t\tSize: pointer.Uint(14),\n\t\t\tLsnr: pointer.Float64(5.7),\n\t\t},\n\t\tnil,\n\t\t`{\"lsnr\":5.7,\"modu\":\"FSK\",\"size\":14,\"datr\":50000,\"time\":\"2016-01-06T15:11:12.000000142Z\"}`,\n\t},\n}\n\nvar unmarshalTests = []struct {\n\tMetadata  Metadata\n\tWantError error\n\tJSON      string\n}{\n\t{ \/\/ Local time\n\t\tMetadata{Time: pointer.Time(time.Date(2016, 1, 6, 15, 11, 12, 0, time.UTC))},\n\t\tnil,\n\t\t`{\"time\":\"2016-01-06 15:11:12 GMT\"}`,\n\t},\n\n\t{ \/\/ RFC3339 time\n\t\tMetadata{Time: pointer.Time(time.Date(2016, 1, 6, 15, 11, 12, 142000000, time.UTC))},\n\t\tnil,\n\t\t`{\"time\":\"2016-01-06T15:11:12.142000Z\"}`,\n\t},\n}\n\n\/\/ The broker can handle an uplink packet\nfunc TestMarshaljson(t *testing.T) {\n\tfor _, test := range commonTests {\n\t\tDesc(t, \"Marshal medatadata: %v\", pointer.DumpPStruct(test.Metadata, false))\n\t\traw, err := json.Marshal(test.Metadata)\n\t\tcheckErrors(t, test.WantError, err)\n\t\tcheckJSON(t, test.JSON, raw)\n\t}\n}\n\nfunc TestUnmarshalJSON(t *testing.T) {\n\tfor _, test := range append(commonTests, unmarshalTests...) {\n\t\tDesc(t, \"Unmarshal json: %s\", test.JSON)\n\t\tmetadata := Metadata{}\n\t\terr := json.Unmarshal([]byte(test.JSON), &metadata)\n\t\tcheckErrors(t, test.WantError, err)\n\t\tcheckMetadata(t, test.Metadata, metadata)\n\t}\n}\n\n\/\/ ----- Check utilities\n\n\/\/ Check that errors match\nfunc checkErrors(t *testing.T, want error, got error) {\n\tif got == want {\n\t\tOk(t)\n\t\treturn\n\t}\n\tKo(t, \"Expected error to be %v but got %v\", want, got)\n}\n\n\/\/ Check that obtained json matches expected one\nfunc checkJSON(t *testing.T, want string, got []byte) {\n\tstr := string(got)\n\tif str == want {\n\t\tOk(t)\n\t\treturn\n\t}\n\tKo(t, \"Marshaled data don't match expectations.\\nWant: %s\\nGot:  %s\", want, str)\n\treturn\n}\n\n\/\/ Check that obtained metadata matches expected one\nfunc checkMetadata(t *testing.T, want Metadata, got Metadata) {\n\tif reflect.DeepEqual(want, got) {\n\t\tOk(t)\n\t\treturn\n\t}\n\tKo(t, \"Unmarshaled json don't match expectations. \\nWant: %s\\nGot:  %s\", pointer.DumpPStruct(want, false), pointer.DumpPStruct(got, false))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 Gonéri Le Bouder. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport \"notmuch\"\nimport \"log\"\nimport \"encoding\/json\"\nimport \"os\"\nimport \"io\"\nimport \"fmt\"\nimport \"regexp\"\nimport \"net\/mail\"\nimport \"path\"\n\ntype Filter struct {\n\tField   string\n\tPattern string\n\tRe      *regexp.Regexp\n\tTags    string\n}\n\ntype Result struct {\n\tMessageID string\n\tTags      string\n\tDie       bool\n}\n\n\nconst NCPU = 4 \/\/ number of CPU cores \n\nfunc getMaildirLoc() (string) {\n    \/\/ honor NOTMUCH_CONFIG\n    home := os.Getenv(\"NOTMUCH_CONFIG\")\n    if home == \"\" {\n        home = os.Getenv(\"HOME\")\n    }\n\n    return path.Join(home, \"Maildir\")\n}\n\nfunc saveResult(resultOut chan Result, quit chan bool) {\n\n\t\/\/\tvar query *notmuch.Query\n\tvar nmdb *notmuch.Database\n\tvar msgIDRegexp = regexp.MustCompile(\"^<(.*)>$\")\n\tvar tagRegexp = regexp.MustCompile(\"([\\\\+-])(\\\\S+)\")\n\n\t\/\/ open the database\n\tif db, status := notmuch.OpenDatabase(getMaildirLoc(),\n\t\t1); status == notmuch.STATUS_SUCCESS {\n\t\tnmdb = db\n\t} else {\n\t\tlog.Fatalf(\"Failed to open the database: %v\\n\", status)\n\t}\n\tdefer nmdb.Close()\n\n\tfor {\n\t\tresult := <-resultOut\n\n\t\tif result.Die {\n\t\t\tnmdb.Close()\n\t\t\tquit <- true\n                        fmt.Print(\"\")\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Message-ID without the <>\n\t\tmsgID := msgIDRegexp.FindStringSubmatch(result.MessageID)[1]\n\t\tfilter := \"id:\"\n\t\tfilter += msgID\n\t\tquery := nmdb.CreateQuery(filter)\n\t\tmsgs := query.SearchMessages()\n\t\tmsg := msgs.Get()\n\n\t\tmsg.Freeze()\n\t\tfor _, v := range tagRegexp.FindAllStringSubmatch(result.Tags, -1) {\n\t\t\tif v[1] == \"+\" {\n\t\t\t\tmsg.AddTag(v[2])\n\t\t\t} else if v[1] == \"-\" {\n\t\t\t\tmsg.RemoveTag(v[2])\n\t\t\t}\n\t\t}\n\t\tmsg.Thaw()\n\n\t}\n}\n\nfunc studyMsg(filter []Filter, filenameIn chan string, resultOut chan Result, quit chan bool) {\n\tfor {\n\t\tfilename := <-filenameIn\n\n\t\tif filename == \"\" {\n\t\t\tquit <- true\n\t\t\treturn\n\t\t}\n\t\t\/\/ We can use Notmuch for this directly because Xappian will\n\t\t\/\/ fails as soon as we have 2 concurrent goroutine\n\t\tfile, err := os.Open(filename) \/\/ For read access.\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tvar msg *mail.Message\n\t\tmsg, err = mail.ReadMessage(file)\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tvar result Result\n\t\tresult.MessageID = msg.Header.Get(\"Message-Id\")\n\t\tfor _, f := range filter {\n\t\t\tif f.Re.MatchString(msg.Header.Get(f.Field)) {\n\t\t\t\tresult.Tags += \" \"\n\t\t\t\tresult.Tags += f.Tags\n\t\t\t}\n\n\t\t}\n\t\tfile.Close()\n\n\t\tresultOut <- result\n\t}\n}\n\nfunc loadFilter() (filter []Filter) {\n\n\tfile, err := os.Open(fmt.Sprintf(\"\/%s\/notmuch-filter.json\",getMaildirLoc())) \/\/ For read access.\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tdec := json.NewDecoder(file)\n\tfor {\n\t\tvar f Filter\n\t\tif err := dec.Decode(&f); err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tvar err error = nil\n\t\tif f.Re, err = regexp.Compile(f.Pattern); err != nil {\n\t\t\tlog.Printf(\"error: %v\\n\", err)\n\t\t}\n\n\t\tfilter = append(filter, f)\n\t}\n\n\treturn filter\n}\n\nfunc studyMsgs(resultOut chan Result, quit chan bool, filenames []string) {\n\n\tfilter := loadFilter()\n\n\tfilenameIn := make(chan string)\n\tfor i := 0; i < NCPU+1; i++ {\n\t\tgo studyMsg(filter, filenameIn, resultOut, quit)\n\t}\n\tfor _, filename := range filenames {\n\t\tfilenameIn <- filename\n\t}\n\n\tfor i := 0; i < NCPU+1; i++ {\n\t\tfilenameIn <- \"\"\n\t}\n\n}\n\nfunc main() {\n\tvar query *notmuch.Query\n\tvar nmdb *notmuch.Database\n\n\tif db, status := notmuch.OpenDatabase(getMaildirLoc(),\n\t\tnotmuch.DATABASE_MODE_READ_ONLY); status == notmuch.STATUS_SUCCESS {\n\t\tnmdb = db\n\t} else {\n\t\tlog.Fatalf(\"Failed to open the database: %v\\n\", status)\n\t}\n\n\tquery = nmdb.CreateQuery(\"tag:inbox\")\n\tif query.CountMessages() == 0 {\n\t\tfmt.Printf(\"Nothing to do\\n\")\n\t\tos.Exit(0)\n\t}\n\n\tprintln(\">\", query.CountMessages(), \"<\")\n\tmsgs := query.SearchMessages()\n\n\tvar filenames []string\n\tfor ; msgs.Valid(); msgs.MoveToNext() {\n\t\tmsg := msgs.Get()\n\t\tfilenames = append(filenames, msg.GetFileName())\n\t}\n\tquery.Destroy()\n\tnmdb.Close()\n\n\tquit := make(chan bool)\n\tresultOut := make(chan Result)\n\tgo saveResult(resultOut, quit)\n\n\tstudyMsgs(resultOut, quit, filenames)\n\n\tvar lastResult Result\n\tlastResult.Die = true\n\n\tresultOut <- lastResult\n\n\tfor i := 0; i < NCPU+2; i++ {\n\t\t<-quit\n\t}\n\n\tfmt.Printf(\"done\\n\")\n\n}\n<commit_msg>expect newly imported mail to have the \"new\" tag<commit_after>\/\/ Copyright 2012 Gonéri Le Bouder. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport \"notmuch\"\nimport \"log\"\nimport \"encoding\/json\"\nimport \"os\"\nimport \"io\"\nimport \"fmt\"\nimport \"regexp\"\nimport \"net\/mail\"\nimport \"path\"\n\ntype Filter struct {\n\tField   string\n\tPattern string\n\tRe      *regexp.Regexp\n\tTags    string\n}\n\ntype Result struct {\n\tMessageID string\n\tTags      string\n\tDie       bool\n}\n\n\nconst NCPU = 4 \/\/ number of CPU cores \n\nfunc getMaildirLoc() (string) {\n    \/\/ honor NOTMUCH_CONFIG\n    home := os.Getenv(\"NOTMUCH_CONFIG\")\n    if home == \"\" {\n        home = os.Getenv(\"HOME\")\n    }\n\n    return path.Join(home, \"Maildir\")\n}\n\nfunc saveResult(resultOut chan Result, quit chan bool) {\n\n\t\/\/\tvar query *notmuch.Query\n\tvar nmdb *notmuch.Database\n\tvar msgIDRegexp = regexp.MustCompile(\"^<(.*)>$\")\n\tvar tagRegexp = regexp.MustCompile(\"([\\\\+-])(\\\\S+)\")\n\n\t\/\/ open the database\n\tif db, status := notmuch.OpenDatabase(getMaildirLoc(),\n\t\t1); status == notmuch.STATUS_SUCCESS {\n\t\tnmdb = db\n\t} else {\n\t\tlog.Fatalf(\"Failed to open the database: %v\\n\", status)\n\t}\n\tdefer nmdb.Close()\n\n\tfor {\n\t\tresult := <-resultOut\n\n\t\tif result.Die {\n\t\t\tnmdb.Close()\n\t\t\tquit <- true\n                        fmt.Print(\"\")\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Message-ID without the <>\n\t\tmsgID := msgIDRegexp.FindStringSubmatch(result.MessageID)[1]\n\t\tfilter := \"id:\"\n\t\tfilter += msgID\n\t\tquery := nmdb.CreateQuery(filter)\n\t\tmsgs := query.SearchMessages()\n\t\tmsg := msgs.Get()\n\n\t\tmsg.Freeze()\n\t\tfor _, v := range tagRegexp.FindAllStringSubmatch(result.Tags, -1) {\n\t\t\tif v[1] == \"+\" {\n\t\t\t\tmsg.AddTag(v[2])\n\t\t\t} else if v[1] == \"-\" {\n\t\t\t\tmsg.RemoveTag(v[2])\n\t\t\t}\n\t\t}\n\t\tmsg.Thaw()\n\n\t}\n}\n\nfunc studyMsg(filter []Filter, filenameIn chan string, resultOut chan Result, quit chan bool) {\n\tfor {\n\t\tfilename := <-filenameIn\n\n\t\tif filename == \"\" {\n\t\t\tquit <- true\n\t\t\treturn\n\t\t}\n\t\t\/\/ We can use Notmuch for this directly because Xappian will\n\t\t\/\/ fails as soon as we have 2 concurrent goroutine\n\t\tfile, err := os.Open(filename) \/\/ For read access.\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tvar msg *mail.Message\n\t\tmsg, err = mail.ReadMessage(file)\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tvar result Result\n\t\tresult.MessageID = msg.Header.Get(\"Message-Id\")\n\t\tfor _, f := range filter {\n\t\t\tif f.Re.MatchString(msg.Header.Get(f.Field)) {\n\t\t\t\tresult.Tags += \" \"\n\t\t\t\tresult.Tags += f.Tags\n\t\t\t}\n\n\t\t}\n\t\tfile.Close()\n\n\t\tresultOut <- result\n\t}\n}\n\nfunc loadFilter() (filter []Filter) {\n\n\tfile, err := os.Open(fmt.Sprintf(\"\/%s\/notmuch-filter.json\",getMaildirLoc())) \/\/ For read access.\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer file.Close()\n\n\tdec := json.NewDecoder(file)\n\tfor {\n\t\tvar f Filter\n\t\tif err := dec.Decode(&f); err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tvar err error = nil\n\t\tif f.Re, err = regexp.Compile(f.Pattern); err != nil {\n\t\t\tlog.Printf(\"error: %v\\n\", err)\n\t\t}\n\n\t\tfilter = append(filter, f)\n\t}\n\n\treturn filter\n}\n\nfunc studyMsgs(resultOut chan Result, quit chan bool, filenames []string) {\n\n\tfilter := loadFilter()\n\n\tfilenameIn := make(chan string)\n\tfor i := 0; i < NCPU+1; i++ {\n\t\tgo studyMsg(filter, filenameIn, resultOut, quit)\n\t}\n\tfor _, filename := range filenames {\n\t\tfilenameIn <- filename\n\t}\n\n\tfor i := 0; i < NCPU+1; i++ {\n\t\tfilenameIn <- \"\"\n\t}\n\n}\n\nfunc main() {\n\tvar query *notmuch.Query\n\tvar nmdb *notmuch.Database\n\n\tif db, status := notmuch.OpenDatabase(getMaildirLoc(),\n\t\tnotmuch.DATABASE_MODE_READ_ONLY); status == notmuch.STATUS_SUCCESS {\n\t\tnmdb = db\n\t} else {\n\t\tlog.Fatalf(\"Failed to open the database: %v\\n\", status)\n\t}\n\n\tquery = nmdb.CreateQuery(\"tag:new\")\n\tif query.CountMessages() == 0 {\n\t\tfmt.Printf(\"Nothing to do\\n\")\n\t\tos.Exit(0)\n\t}\n\n\tprintln(\">\", query.CountMessages(), \"<\")\n\tmsgs := query.SearchMessages()\n\n\tvar filenames []string\n\tfor ; msgs.Valid(); msgs.MoveToNext() {\n\t\tmsg := msgs.Get()\n\t\tfilenames = append(filenames, msg.GetFileName())\n\t}\n\tquery.Destroy()\n\tnmdb.Close()\n\n\tquit := make(chan bool)\n\tresultOut := make(chan Result)\n\tgo saveResult(resultOut, quit)\n\n\tstudyMsgs(resultOut, quit, filenames)\n\n\tvar lastResult Result\n\tlastResult.Die = true\n\n\tresultOut <- lastResult\n\n\tfor i := 0; i < NCPU+2; i++ {\n\t\t<-quit\n\t}\n\n\tfmt.Printf(\"done\\n\")\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package clouddriveclient\n\nimport (\n\t\"compress\/gzip\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/koofr\/go-httpclient\"\n\t\"github.com\/koofr\/go-ioutils\"\n)\n\nconst DefaultMaxRetries = 5\n\ntype CloudDrive struct {\n\tContentClient  *httpclient.HTTPClient\n\tMetadataClient *httpclient.HTTPClient\n\tAuth           *CloudDriveAuth\n\tMaxRetries     int\n}\n\nfunc NewCloudDrive(auth *CloudDriveAuth) (d *CloudDrive, err error) {\n\td = &CloudDrive{\n\t\tAuth:       auth,\n\t\tMaxRetries: DefaultMaxRetries,\n\t}\n\n\tendpointUrl, _ := url.Parse(\"https:\/\/drive.amazonaws.com\/drive\/v1\")\n\n\tendpointClient := httpclient.New()\n\tendpointClient.BaseURL = endpointUrl\n\n\tendpoint := &Endpoint{}\n\n\tendpointReq := &httpclient.RequestData{\n\t\tMethod:         \"GET\",\n\t\tPath:           \"\/account\/endpoint\",\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &endpoint,\n\t}\n\n\t_, err = d.Request(endpointClient, endpointReq)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !endpoint.CustomerExists {\n\t\treturn nil, fmt.Errorf(\"CloudDrive customer does not exist.\")\n\t}\n\n\tcontentUrl, _ := url.Parse(endpoint.ContentUrl)\n\tmetadataUrl, _ := url.Parse(endpoint.MetadataUrl)\n\n\td.ContentClient = httpclient.New()\n\td.ContentClient.BaseURL = contentUrl\n\n\td.MetadataClient = httpclient.New()\n\td.MetadataClient.BaseURL = metadataUrl\n\n\treturn d, nil\n}\n\nfunc (d *CloudDrive) Request(client *httpclient.HTTPClient, request *httpclient.RequestData) (response *http.Response, err error) {\n\tretries := d.MaxRetries\n\n\tcanRetry := request.CanCopy()\n\n\tif !canRetry {\n\t\tretries = 1\n\t}\n\n\tfor retry := 0; retry < retries; retry++ {\n\t\tvar currentRequest *httpclient.RequestData\n\n\t\tif canRetry {\n\t\t\t_, currentRequest = request.Copy()\n\t\t} else {\n\t\t\tcurrentRequest = request\n\t\t}\n\n\t\ttoken, err := d.Auth.ValidToken()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif currentRequest.Headers == nil {\n\t\t\tcurrentRequest.Headers = http.Header{}\n\t\t}\n\n\t\tcurrentRequest.Headers.Set(\"Authorization\", \"Bearer \"+token)\n\n\t\tresponse, err = client.Request(currentRequest)\n\n\t\tdoRetry := false\n\n\t\tif err != nil {\n\t\t\tif httpErr, ok := err.(httpclient.InvalidStatusError); ok {\n\t\t\t\tdoRetry = httpErr.Got == 429\n\t\t\t}\n\t\t} else if response.StatusCode == 429 {\n\t\t\tdoRetry = true\n\t\t}\n\n\t\tif doRetry {\n\t\t\tseconds := rand.Intn(int(math.Pow(2, float64(retry))))\n\n\t\t\ttime.Sleep(time.Duration(seconds) * time.Second)\n\n\t\t\tcontinue\n\t\t}\n\n\t\treturn response, err\n\t}\n\n\treturn nil, err\n}\n\nfunc (d *CloudDrive) LookupRoot() (root *Node, err error) {\n\tparams := make(url.Values)\n\tparams.Set(\"filters\", \"isRoot:true\")\n\n\tnodes := &Nodes{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"GET\",\n\t\tPath:           \"\/nodes\",\n\t\tParams:         params,\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &nodes,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(nodes.Nodes) == 0 {\n\t\treturn nil, fmt.Errorf(\"Root not found.\")\n\t}\n\n\troot = nodes.Nodes[0]\n\n\treturn root, nil\n}\n\nfunc (d *CloudDrive) LookupNode(parentId string, name string) (node *Node, ok bool, err error) {\n\tnameEscaped := strings.Replace(name, \"\\\"\", \"\\\\\\\\\", -1)\n\n\tparams := make(url.Values)\n\tparams.Set(\"filters\", \"parents:\"+parentId+\" AND name:\\\"\"+nameEscaped+\"\\\"\")\n\n\tnodes := &Nodes{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"GET\",\n\t\tPath:           \"\/nodes\",\n\t\tParams:         params,\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &nodes,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tif len(nodes.Nodes) == 0 {\n\t\treturn nil, false, nil\n\t}\n\n\treturn nodes.Nodes[0], true, nil\n}\n\nfunc (d *CloudDrive) NodeChildren(parentId string) (nodes []*Node, err error) {\n\tnextToken := \"\"\n\n\tnodes = []*Node{}\n\n\tfor {\n\t\tparams := make(url.Values)\n\t\tparams.Set(\"filters\", \"parents:\"+parentId)\n\t\tif nextToken != \"\" {\n\t\t\tparams.Set(\"startToken\", nextToken)\n\t\t}\n\n\t\tns := &Nodes{}\n\n\t\treq := &httpclient.RequestData{\n\t\t\tMethod:         \"GET\",\n\t\t\tPath:           \"\/nodes\",\n\t\t\tParams:         params,\n\t\t\tExpectedStatus: []int{http.StatusOK},\n\t\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\t\tRespValue:      &ns,\n\t\t}\n\n\t\t_, err = d.Request(d.MetadataClient, req)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(ns.Nodes) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tnodes = append(nodes, ns.Nodes...)\n\n\t\tif ns.NextToken == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tnextToken = ns.NextToken\n\t}\n\n\treturn nodes, nil\n}\n\nfunc (d *CloudDrive) Changes(checkpoint string) (changes *Changes, err error) {\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"POST\",\n\t\tPath:           \"\/changes\",\n\t\tExpectedStatus: []int{http.StatusOK},\n\t}\n\n\tif checkpoint != \"\" {\n\t\treq.ReqEncoding = httpclient.EncodingJSON\n\n\t\treq.ReqValue = struct {\n\t\t\tCheckpoint string `json:\"checkpoint\"`\n\t\t}{\n\t\t\tCheckpoint: checkpoint,\n\t\t}\n\t}\n\n\tres, err := d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r io.ReadCloser = res.Body\n\n\tif res.Header.Get(\"Content-Encoding\") == \"gzip\" {\n\t\tr, err = gzip.NewReader(r)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdecoder := json.NewDecoder(r)\n\n\tchanges = &Changes{}\n\n\terr = decoder.Decode(changes)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres.Body.Close()\n\n\treturn changes, nil\n}\n\nfunc (d *CloudDrive) CreateFolder(parentId string, name string) (node *Node, err error) {\n\tcreate := &NodeCreate{\n\t\tName:    name,\n\t\tKind:    NodeKindFolder,\n\t\tParents: []string{parentId},\n\t}\n\n\tnode = &Node{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"POST\",\n\t\tPath:           \"\/nodes\",\n\t\tExpectedStatus: []int{http.StatusCreated},\n\t\tReqEncoding:    httpclient.EncodingJSON,\n\t\tReqValue:       create,\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &node,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn node, nil\n}\n\nfunc (d *CloudDrive) DeleteNode(nodeId string) (node *Node, err error) {\n\tnode = &Node{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"PUT\",\n\t\tPath:           \"\/trash\/\" + nodeId,\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &node,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn node, nil\n}\n\nfunc (d *CloudDrive) RenameNode(nodeId string, newName string) (node *Node, err error) {\n\trename := &NodeRename{\n\t\tName: newName,\n\t}\n\n\tnode = &Node{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"PATCH\",\n\t\tPath:           \"\/nodes\/\" + nodeId,\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tReqEncoding:    httpclient.EncodingJSON,\n\t\tReqValue:       rename,\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &node,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn node, nil\n}\n\nfunc (d *CloudDrive) MoveNode(nodeId string, fromParentId string, toParentId string) (node *Node, err error) {\n\tmove := &NodeMove{\n\t\tFromParent: fromParentId,\n\t\tChildId:    nodeId,\n\t}\n\n\tnode = &Node{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"POST\",\n\t\tPath:           \"\/nodes\/\" + toParentId + \"\/children\",\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tReqEncoding:    httpclient.EncodingJSON,\n\t\tReqValue:       move,\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &node,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn node, nil\n}\n\nfunc (d *CloudDrive) DownloadNode(nodeId string, span *ioutils.FileSpan) (reader io.ReadCloser, size int64, err error) {\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"GET\",\n\t\tPath:           \"\/nodes\/\" + nodeId + \"\/content\",\n\t\tExpectedStatus: []int{http.StatusOK, http.StatusPartialContent},\n\t}\n\n\tif span != nil {\n\t\treq.Headers = make(http.Header)\n\t\treq.Headers.Set(\"Range\", fmt.Sprintf(\"bytes=%d-%d\", span.Start, span.End))\n\t}\n\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tres, err := d.Request(d.ContentClient, req)\n\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn res.Body, res.ContentLength, nil\n}\n\nfunc (d *CloudDrive) UploadNode(parentId string, name string, reader io.Reader) (node *Node, err error) {\n\tcreate := &NodeCreate{\n\t\tName:    name,\n\t\tKind:    NodeKindFile,\n\t\tParents: []string{parentId},\n\t}\n\n\tcreateJson, err := json.Marshal(create)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams := make(url.Values)\n\tparams.Set(\"suppress\", \"deduplication\")\n\n\tnode = &Node{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"POST\",\n\t\tPath:           \"\/nodes\",\n\t\tParams:         params,\n\t\tExpectedStatus: []int{http.StatusCreated},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &node,\n\t}\n\n\textra := map[string]string{\n\t\t\"metadata\": string(createJson),\n\t}\n\n\terr = req.UploadFileExtra(\"file\", \"file\", reader, extra)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = d.Request(d.ContentClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn node, nil\n}\n\nfunc (d *CloudDrive) OverwriteNode(nodeId string, reader io.Reader) (node *Node, err error) {\n\tnode = &Node{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"PUT\",\n\t\tPath:           \"\/nodes\/\" + nodeId + \"\/content\",\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &node,\n\t}\n\n\terr = req.UploadFile(\"file\", \"file\", reader)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = d.Request(d.ContentClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn node, nil\n}\n\nfunc (d *CloudDrive) Quota() (quota *Quota, err error) {\n\tquota = &Quota{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"GET\",\n\t\tPath:           \"\/account\/quota\",\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &quota,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn quota, nil\n}\n<commit_msg>Too many retries error<commit_after>package clouddriveclient\n\nimport (\n\t\"compress\/gzip\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/koofr\/go-httpclient\"\n\t\"github.com\/koofr\/go-ioutils\"\n)\n\nconst DefaultMaxRetries = 5\n\ntype CloudDrive struct {\n\tContentClient  *httpclient.HTTPClient\n\tMetadataClient *httpclient.HTTPClient\n\tAuth           *CloudDriveAuth\n\tMaxRetries     int\n}\n\nfunc NewCloudDrive(auth *CloudDriveAuth) (d *CloudDrive, err error) {\n\td = &CloudDrive{\n\t\tAuth:       auth,\n\t\tMaxRetries: DefaultMaxRetries,\n\t}\n\n\tendpointUrl, _ := url.Parse(\"https:\/\/drive.amazonaws.com\/drive\/v1\")\n\n\tendpointClient := httpclient.New()\n\tendpointClient.BaseURL = endpointUrl\n\n\tendpoint := &Endpoint{}\n\n\tendpointReq := &httpclient.RequestData{\n\t\tMethod:         \"GET\",\n\t\tPath:           \"\/account\/endpoint\",\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &endpoint,\n\t}\n\n\t_, err = d.Request(endpointClient, endpointReq)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !endpoint.CustomerExists {\n\t\treturn nil, fmt.Errorf(\"CloudDrive customer does not exist.\")\n\t}\n\n\tcontentUrl, _ := url.Parse(endpoint.ContentUrl)\n\tmetadataUrl, _ := url.Parse(endpoint.MetadataUrl)\n\n\td.ContentClient = httpclient.New()\n\td.ContentClient.BaseURL = contentUrl\n\n\td.MetadataClient = httpclient.New()\n\td.MetadataClient.BaseURL = metadataUrl\n\n\treturn d, nil\n}\n\nfunc (d *CloudDrive) Request(client *httpclient.HTTPClient, request *httpclient.RequestData) (response *http.Response, err error) {\n\tretries := d.MaxRetries\n\n\tcanRetry := request.CanCopy()\n\n\tif !canRetry {\n\t\tretries = 1\n\t}\n\n\tfor retry := 0; retry < retries; retry++ {\n\t\tvar currentRequest *httpclient.RequestData\n\n\t\tif canRetry {\n\t\t\t_, currentRequest = request.Copy()\n\t\t} else {\n\t\t\tcurrentRequest = request\n\t\t}\n\n\t\ttoken, err := d.Auth.ValidToken()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif currentRequest.Headers == nil {\n\t\t\tcurrentRequest.Headers = http.Header{}\n\t\t}\n\n\t\tcurrentRequest.Headers.Set(\"Authorization\", \"Bearer \"+token)\n\n\t\tresponse, err = client.Request(currentRequest)\n\n\t\tdoRetry := false\n\n\t\tif err != nil {\n\t\t\tif httpErr, ok := err.(httpclient.InvalidStatusError); ok {\n\t\t\t\tdoRetry = httpErr.Got == 429\n\t\t\t}\n\t\t} else if response.StatusCode == 429 {\n\t\t\tdoRetry = true\n\t\t}\n\n\t\tif doRetry {\n\t\t\tseconds := rand.Intn(int(math.Pow(2, float64(retry))))\n\n\t\t\ttime.Sleep(time.Duration(seconds) * time.Second)\n\n\t\t\tcontinue\n\t\t}\n\n\t\treturn response, err\n\t}\n\n\treturn nil, fmt.Errorf(\"Too many retries\")\n}\n\nfunc (d *CloudDrive) LookupRoot() (root *Node, err error) {\n\tparams := make(url.Values)\n\tparams.Set(\"filters\", \"isRoot:true\")\n\n\tnodes := &Nodes{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"GET\",\n\t\tPath:           \"\/nodes\",\n\t\tParams:         params,\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &nodes,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(nodes.Nodes) == 0 {\n\t\treturn nil, fmt.Errorf(\"Root not found.\")\n\t}\n\n\troot = nodes.Nodes[0]\n\n\treturn root, nil\n}\n\nfunc (d *CloudDrive) LookupNode(parentId string, name string) (node *Node, ok bool, err error) {\n\tnameEscaped := strings.Replace(name, \"\\\"\", \"\\\\\\\\\", -1)\n\n\tparams := make(url.Values)\n\tparams.Set(\"filters\", \"parents:\"+parentId+\" AND name:\\\"\"+nameEscaped+\"\\\"\")\n\n\tnodes := &Nodes{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"GET\",\n\t\tPath:           \"\/nodes\",\n\t\tParams:         params,\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &nodes,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tif len(nodes.Nodes) == 0 {\n\t\treturn nil, false, nil\n\t}\n\n\treturn nodes.Nodes[0], true, nil\n}\n\nfunc (d *CloudDrive) NodeChildren(parentId string) (nodes []*Node, err error) {\n\tnextToken := \"\"\n\n\tnodes = []*Node{}\n\n\tfor {\n\t\tparams := make(url.Values)\n\t\tparams.Set(\"filters\", \"parents:\"+parentId)\n\t\tif nextToken != \"\" {\n\t\t\tparams.Set(\"startToken\", nextToken)\n\t\t}\n\n\t\tns := &Nodes{}\n\n\t\treq := &httpclient.RequestData{\n\t\t\tMethod:         \"GET\",\n\t\t\tPath:           \"\/nodes\",\n\t\t\tParams:         params,\n\t\t\tExpectedStatus: []int{http.StatusOK},\n\t\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\t\tRespValue:      &ns,\n\t\t}\n\n\t\t_, err = d.Request(d.MetadataClient, req)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif len(ns.Nodes) == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tnodes = append(nodes, ns.Nodes...)\n\n\t\tif ns.NextToken == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tnextToken = ns.NextToken\n\t}\n\n\treturn nodes, nil\n}\n\nfunc (d *CloudDrive) Changes(checkpoint string) (changes *Changes, err error) {\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"POST\",\n\t\tPath:           \"\/changes\",\n\t\tExpectedStatus: []int{http.StatusOK},\n\t}\n\n\tif checkpoint != \"\" {\n\t\treq.ReqEncoding = httpclient.EncodingJSON\n\n\t\treq.ReqValue = struct {\n\t\t\tCheckpoint string `json:\"checkpoint\"`\n\t\t}{\n\t\t\tCheckpoint: checkpoint,\n\t\t}\n\t}\n\n\tres, err := d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r io.ReadCloser = res.Body\n\n\tif res.Header.Get(\"Content-Encoding\") == \"gzip\" {\n\t\tr, err = gzip.NewReader(r)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdecoder := json.NewDecoder(r)\n\n\tchanges = &Changes{}\n\n\terr = decoder.Decode(changes)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres.Body.Close()\n\n\treturn changes, nil\n}\n\nfunc (d *CloudDrive) CreateFolder(parentId string, name string) (node *Node, err error) {\n\tcreate := &NodeCreate{\n\t\tName:    name,\n\t\tKind:    NodeKindFolder,\n\t\tParents: []string{parentId},\n\t}\n\n\tnode = &Node{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"POST\",\n\t\tPath:           \"\/nodes\",\n\t\tExpectedStatus: []int{http.StatusCreated},\n\t\tReqEncoding:    httpclient.EncodingJSON,\n\t\tReqValue:       create,\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &node,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn node, nil\n}\n\nfunc (d *CloudDrive) DeleteNode(nodeId string) (node *Node, err error) {\n\tnode = &Node{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"PUT\",\n\t\tPath:           \"\/trash\/\" + nodeId,\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &node,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn node, nil\n}\n\nfunc (d *CloudDrive) RenameNode(nodeId string, newName string) (node *Node, err error) {\n\trename := &NodeRename{\n\t\tName: newName,\n\t}\n\n\tnode = &Node{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"PATCH\",\n\t\tPath:           \"\/nodes\/\" + nodeId,\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tReqEncoding:    httpclient.EncodingJSON,\n\t\tReqValue:       rename,\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &node,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn node, nil\n}\n\nfunc (d *CloudDrive) MoveNode(nodeId string, fromParentId string, toParentId string) (node *Node, err error) {\n\tmove := &NodeMove{\n\t\tFromParent: fromParentId,\n\t\tChildId:    nodeId,\n\t}\n\n\tnode = &Node{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"POST\",\n\t\tPath:           \"\/nodes\/\" + toParentId + \"\/children\",\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tReqEncoding:    httpclient.EncodingJSON,\n\t\tReqValue:       move,\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &node,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn node, nil\n}\n\nfunc (d *CloudDrive) DownloadNode(nodeId string, span *ioutils.FileSpan) (reader io.ReadCloser, size int64, err error) {\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"GET\",\n\t\tPath:           \"\/nodes\/\" + nodeId + \"\/content\",\n\t\tExpectedStatus: []int{http.StatusOK, http.StatusPartialContent},\n\t}\n\n\tif span != nil {\n\t\treq.Headers = make(http.Header)\n\t\treq.Headers.Set(\"Range\", fmt.Sprintf(\"bytes=%d-%d\", span.Start, span.End))\n\t}\n\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\tres, err := d.Request(d.ContentClient, req)\n\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\treturn res.Body, res.ContentLength, nil\n}\n\nfunc (d *CloudDrive) UploadNode(parentId string, name string, reader io.Reader) (node *Node, err error) {\n\tcreate := &NodeCreate{\n\t\tName:    name,\n\t\tKind:    NodeKindFile,\n\t\tParents: []string{parentId},\n\t}\n\n\tcreateJson, err := json.Marshal(create)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams := make(url.Values)\n\tparams.Set(\"suppress\", \"deduplication\")\n\n\tnode = &Node{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"POST\",\n\t\tPath:           \"\/nodes\",\n\t\tParams:         params,\n\t\tExpectedStatus: []int{http.StatusCreated},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &node,\n\t}\n\n\textra := map[string]string{\n\t\t\"metadata\": string(createJson),\n\t}\n\n\terr = req.UploadFileExtra(\"file\", \"file\", reader, extra)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = d.Request(d.ContentClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn node, nil\n}\n\nfunc (d *CloudDrive) OverwriteNode(nodeId string, reader io.Reader) (node *Node, err error) {\n\tnode = &Node{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"PUT\",\n\t\tPath:           \"\/nodes\/\" + nodeId + \"\/content\",\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &node,\n\t}\n\n\terr = req.UploadFile(\"file\", \"file\", reader)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = d.Request(d.ContentClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn node, nil\n}\n\nfunc (d *CloudDrive) Quota() (quota *Quota, err error) {\n\tquota = &Quota{}\n\n\treq := &httpclient.RequestData{\n\t\tMethod:         \"GET\",\n\t\tPath:           \"\/account\/quota\",\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &quota,\n\t}\n\n\t_, err = d.Request(d.MetadataClient, req)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn quota, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package presilo\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/*\n  Generates valid CSharp code for a given schema.\n\n\tC# code contains DataContractJsonSerializer annotations,\n\twhich are required for proper serialization\/deserialization of fields.\n\tUnfortunately this isn't available before .NET 4.5, so any generated code\n\twill need to be compiled with .NET 4.5+\n*\/\nfunc GenerateCSharp(schema *ObjectSchema, module string, tabstyle string) string {\n\n\tvar buffer *BufferedFormatString\n\n\tbuffer = NewBufferedFormatString(tabstyle)\n\n\tgenerateCSharpImports(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpNamespace(schema, buffer, module)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpTypeDeclaration(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpConstructor(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpFunctions(schema, buffer)\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\n\treturn buffer.String()\n}\n\nfunc ValidateCSharpModule(module string) bool {\n\n\tpattern := \"^[a-zA-Z_]+[0-9a-zA-Z_]*(\\\\.[a-zA-Z_]+[0-9a-zA-Z_]*)*$\"\n\tmatched, err := regexp.MatchString(pattern, module)\n\treturn err == nil && matched\n}\n\nfunc generateCSharpImports(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tbuffer.Print(\"using System;\")\n\tbuffer.Print(\"\\n using System.Runtime.Serialization;\")\n\n\t\/\/ import regex if we need it\n\tif containsRegexpMatch(schema) {\n\t\tbuffer.Print(\"\\nusing System.Text.RegularExpressions;\")\n\t}\n\n\tbuffer.Print(\"\\n\")\n}\n\nfunc generateCSharpNamespace(schema *ObjectSchema, buffer *BufferedFormatString, module string) {\n\n\tbuffer.Printf(\"namespace %s\\n{\", module)\n\tbuffer.AddIndentation(1)\n}\n\nfunc generateCSharpTypeDeclaration(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar propertyName string\n\n\tbuffer.Print(\"[DataContract]\")\n\tbuffer.Printf(\"\\npublic class %s\\n{\", ToCamelCase(schema.Title))\n\tbuffer.AddIndentation(1)\n\n\tfor _, propertyName = range schema.GetOrderedPropertyNames() {\n\n\t\tsubschema = schema.Properties[propertyName]\n\n\t\tbuffer.Print(\"\\n[DataMember]\")\n\t\tbuffer.Printf(\"\\nprotected %s %s;\", GenerateCSharpTypeForSchema(subschema), ToJavaCase(propertyName))\n\t}\n}\n\nfunc generateCSharpConstructor(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar declarations, setters []string\n\tvar propertyName string\n\tvar toWrite string\n\n\tbuffer.Printf(\"\\npublic %s(\", ToCamelCase(schema.Title))\n\n\tfor _, propertyName = range schema.RequiredProperties {\n\n\t\tsubschema = schema.Properties[propertyName]\n\t\tpropertyName = ToJavaCase(propertyName)\n\n\t\ttoWrite = fmt.Sprintf(\"%s %s\", GenerateCSharpTypeForSchema(subschema), propertyName)\n\t\tdeclarations = append(declarations, toWrite)\n\n\t\ttoWrite = fmt.Sprintf(\"\\nset%s(%s);\", ToCamelCase(propertyName), propertyName)\n\t\tsetters = append(setters, toWrite)\n\t}\n\n\tbuffer.Print(strings.Join(declarations, \",\"))\n\tbuffer.Print(\")\\n{\")\n\tbuffer.AddIndentation(1)\n\n\tfor _, setter := range setters {\n\t\tbuffer.Print(setter)\n\t}\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\nfunc generateCSharpFunctions(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar propertyName, properName, camelName, typeName string\n\n\tfor _, propertyName = range schema.GetOrderedPropertyNames() {\n\n\t\tsubschema = schema.Properties[propertyName]\n\n\t\tproperName = ToJavaCase(propertyName)\n\t\tcamelName = ToStrictCamelCase(propertyName)\n\t\ttypeName = GenerateCSharpTypeForSchema(subschema)\n\n\t\t\/\/ getter\n\t\tbuffer.Printf(\"\\npublic %s get%s()\\n{\", typeName, camelName)\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nreturn this.%s;\", properName)\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\")\n\n\t\t\/\/ setter\n\t\tbuffer.Printf(\"\\npublic void set%s(%s value)\\n{\", camelName, typeName)\n\t\tbuffer.AddIndentation(1)\n\n\t\tswitch subschema.GetSchemaType() {\n\t\tcase SCHEMATYPE_STRING:\n\t\t\tgenerateCSharpStringSetter(subschema.(*StringSchema), buffer)\n\t\tcase SCHEMATYPE_INTEGER:\n\t\t\tfallthrough\n\t\tcase SCHEMATYPE_NUMBER:\n\t\t\tgenerateCSharpNumericSetter(subschema.(NumericSchemaType), buffer)\n\t\tcase SCHEMATYPE_OBJECT:\n\t\t\tgenerateCSharpObjectSetter(subschema.(*ObjectSchema), buffer)\n\t\tcase SCHEMATYPE_ARRAY:\n\t\t\tgenerateCSharpArraySetter(subschema.(*ArraySchema), buffer)\n\t\t}\n\n\t\tbuffer.Printf(\"\\n%s = value;\", properName)\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\\n\")\n\t}\n}\n\nfunc generateCSharpStringSetter(schema *StringSchema, buffer *BufferedFormatString) {\n\n\tif !schema.Nullable {\n\t\tgenerateCSharpNullCheck(buffer)\n\t}\n\n\tif schema.MinLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MinLength, \"value.Length\", \"was shorter than allowable minimum\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MaxLength, \"value.Length\", \"was longer than allowable maximum\", \"%d\", false, \">\", \"\", buffer)\n\t}\n\n\tif schema.MinByteLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MinByteLength, \"value.Length * sizeof(Char)\", \"had fewer bytes than allowable minimum\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxByteLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MaxByteLength, \"value.Length * sizeof(Char)\", \"had more bytes than allowable minimum\", \"%d\", false, \">\", \"\", buffer)\n\t}\n\n\tif schema.Pattern != nil {\n\n\t\tbuffer.Printf(\"\\nRegex regex = new Regex(\\\"%s\\\");\", sanitizeQuotedString(*schema.Pattern))\n\t\tbuffer.Printf(\"\\nif(!regex.IsMatch(value))\\n{\")\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nthrow new Exception(\\\"Value '\\\"+value+\\\"' did not match pattern '%s'\\\");\", *schema.Pattern)\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\")\n\t}\n}\n\nfunc generateCSharpNumericSetter(schema NumericSchemaType, buffer *BufferedFormatString) {\n\n\tif schema.HasMinimum() {\n\t\tgenerateCSharpRangeCheck(schema.GetMinimum(), \"value\", \"is under the allowable minimum\", schema.GetConstraintFormat(), schema.IsExclusiveMinimum(), \"<=\", \"<\", buffer)\n\t}\n\n\tif schema.HasMaximum() {\n\t\tgenerateCSharpRangeCheck(schema.GetMaximum(), \"value\", \"is over the allowable maximum\", schema.GetConstraintFormat(), schema.IsExclusiveMaximum(), \">=\", \">\", buffer)\n\t}\n\n\tif schema.HasEnum() {\n\t\tgenerateCSharpEnumCheck(schema, buffer, schema.GetEnum(), \"\", \"\")\n\t}\n\n\tif schema.HasMultiple() {\n\n\t\tbuffer.Printf(\"\\nif(value %% %f != 0)\\n{\", schema.GetMultiple())\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nthrow new Exception(\\\"Property '\\\"+value+\\\"' was not a multiple of %s\\\");\", schema.GetMultiple())\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\\n\")\n\t}\n}\n\nfunc generateCSharpObjectSetter(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tif !schema.Nullable {\n\t\tgenerateCSharpNullCheck(buffer)\n\t}\n}\n\nfunc generateCSharpArraySetter(schema *ArraySchema, buffer *BufferedFormatString) {\n\n\tif !schema.Nullable {\n\t\tgenerateCSharpNullCheck(buffer)\n\t}\n\n\tif schema.MinItems != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MinItems, \"value.Length\", \"does not have enough items\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxItems != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MaxItems, \"value.Length\", \"does not have enough items\", \"%d\", false, \">\", \"\", buffer)\n\t}\n}\n\nfunc generateCSharpNullCheck(buffer *BufferedFormatString) {\n\n\tbuffer.Printf(\"\\nif(value == null)\\n{\")\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Print(\"\\nthrow new NullReferenceException(\\\"Cannot set property to null value\\\");\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\nfunc generateCSharpRangeCheck(value interface{}, reference, message, format string, exclusive bool, comparator, exclusiveComparator string, buffer *BufferedFormatString) {\n\n\tvar compareString string\n\n\tif exclusive {\n\t\tcompareString = exclusiveComparator\n\t} else {\n\t\tcompareString = comparator\n\t}\n\n\tbuffer.Printf(\"\\nif(%s %s \"+format+\")\\n{\", reference, compareString, value)\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Printf(\"\\nthrow new Exception(\\\"Property '\\\"+value+\\\"' %s.\\\");\", message)\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\n\/*\n\tGenerates code which throws an error if the given [parameter]'s value is not contained in the given [validValues].\n*\/\nfunc generateCSharpEnumCheck(schema TypeSchema, buffer *BufferedFormatString, enumValues []interface{}, prefix string, postfix string) {\n\n\tvar typeName string\n\tvar length int\n\n\tlength = len(enumValues)\n\n\tif length <= 0 {\n\t\treturn\n\t}\n\n\t\/\/ write array of valid values\n\ttypeName = GenerateCSharpTypeForSchema(schema)\n\tbuffer.Printf(\"%s[] validValues = new %s[]{%s%v%s\", typeName, typeName, prefix, enumValues[0], postfix)\n\n\tfor _, enumValue := range enumValues[1:length] {\n\t\tbuffer.Printf(\",%s%v%s\", prefix, enumValue, postfix)\n\t}\n\n\tbuffer.Print(\"};\\n\")\n\n\t\/\/ compare\n\tbuffer.Print(\"\\nbool isValid = false;\")\n\tbuffer.Print(\"\\nfor(int i = 0; i < validValues.Length; i++)\\n{\")\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Print(\"\\nif(validValues[i] == value)\\n{\")\n\tbuffer.AddIndentation(1)\n\tbuffer.Print(\"\\nisValid = true;\\nbreak;\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\n\tbuffer.Print(\"\\nif(!isValid)\\n{\")\n\tbuffer.AddIndentation(1)\n\tbuffer.Print(\"\\nthrow new Exception(\\\"Given value '\\\"+value+\\\"' was not found in list of acceptable values\\\");\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\nfunc GenerateCSharpTypeForSchema(subschema TypeSchema) string {\n\n\tswitch subschema.GetSchemaType() {\n\tcase SCHEMATYPE_NUMBER:\n\t\treturn \"double\"\n\tcase SCHEMATYPE_INTEGER:\n\t\treturn \"int\"\n\tcase SCHEMATYPE_ARRAY:\n\t\treturn ToCamelCase(subschema.(*ArraySchema).Items.GetTitle()) + \"[]\"\n\tcase SCHEMATYPE_OBJECT:\n\t\treturn ToCamelCase(subschema.GetTitle())\n\tcase SCHEMATYPE_STRING:\n\t\treturn \"string\"\n\tcase SCHEMATYPE_BOOLEAN:\n\t\treturn \"bool\"\n\t}\n\n\treturn \"Object\"\n}\n<commit_msg>Added datacontract original member name, and fixed a casing bug, in cs codgegen<commit_after>package presilo\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/*\n  Generates valid CSharp code for a given schema.\n\n\tC# code contains DataContractJsonSerializer annotations,\n\twhich are required for proper serialization\/deserialization of fields.\n\tUnfortunately this isn't available before .NET 4.5, so any generated code\n\twill need to be compiled with .NET 4.5+\n*\/\nfunc GenerateCSharp(schema *ObjectSchema, module string, tabstyle string) string {\n\n\tvar buffer *BufferedFormatString\n\n\tbuffer = NewBufferedFormatString(tabstyle)\n\n\tgenerateCSharpImports(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpNamespace(schema, buffer, module)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpTypeDeclaration(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpConstructor(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpFunctions(schema, buffer)\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\n\treturn buffer.String()\n}\n\nfunc ValidateCSharpModule(module string) bool {\n\n\tpattern := \"^[a-zA-Z_]+[0-9a-zA-Z_]*(\\\\.[a-zA-Z_]+[0-9a-zA-Z_]*)*$\"\n\tmatched, err := regexp.MatchString(pattern, module)\n\treturn err == nil && matched\n}\n\nfunc generateCSharpImports(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tbuffer.Print(\"using System;\")\n\tbuffer.Print(\"\\n using System.Runtime.Serialization;\")\n\n\t\/\/ import regex if we need it\n\tif containsRegexpMatch(schema) {\n\t\tbuffer.Print(\"\\nusing System.Text.RegularExpressions;\")\n\t}\n\n\tbuffer.Print(\"\\n\")\n}\n\nfunc generateCSharpNamespace(schema *ObjectSchema, buffer *BufferedFormatString, module string) {\n\n\tbuffer.Printf(\"namespace %s\\n{\", module)\n\tbuffer.AddIndentation(1)\n}\n\nfunc generateCSharpTypeDeclaration(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar propertyName string\n\n\tbuffer.Print(\"[DataContract]\")\n\tbuffer.Printf(\"\\npublic class %s\\n{\", ToCamelCase(schema.Title))\n\tbuffer.AddIndentation(1)\n\n\tfor _, propertyName = range schema.GetOrderedPropertyNames() {\n\n\t\tsubschema = schema.Properties[propertyName]\n\n\t\tbuffer.Printf(\"\\n[DataMember(Name = \\\"%s\\\")]\", propertyName)\n\t\tbuffer.Printf(\"\\nprotected %s %s;\", GenerateCSharpTypeForSchema(subschema), ToJavaCase(propertyName))\n\t}\n}\n\nfunc generateCSharpConstructor(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar declarations, setters []string\n\tvar propertyName string\n\tvar toWrite string\n\n\tbuffer.Printf(\"\\npublic %s(\", ToCamelCase(schema.Title))\n\n\tfor _, propertyName = range schema.RequiredProperties {\n\n\t\tsubschema = schema.Properties[propertyName]\n\t\tpropertyName = ToJavaCase(propertyName)\n\n\t\ttoWrite = fmt.Sprintf(\"%s %s\", GenerateCSharpTypeForSchema(subschema), propertyName)\n\t\tdeclarations = append(declarations, toWrite)\n\n\t\ttoWrite = fmt.Sprintf(\"\\nset%s(%s);\", ToStrictCamelCase(propertyName), propertyName)\n\t\tsetters = append(setters, toWrite)\n\t}\n\n\tbuffer.Print(strings.Join(declarations, \",\"))\n\tbuffer.Print(\")\\n{\")\n\tbuffer.AddIndentation(1)\n\n\tfor _, setter := range setters {\n\t\tbuffer.Print(setter)\n\t}\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\nfunc generateCSharpFunctions(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar propertyName, properName, camelName, typeName string\n\n\tfor _, propertyName = range schema.GetOrderedPropertyNames() {\n\n\t\tsubschema = schema.Properties[propertyName]\n\n\t\tproperName = ToJavaCase(propertyName)\n\t\tcamelName = ToStrictCamelCase(propertyName)\n\t\ttypeName = GenerateCSharpTypeForSchema(subschema)\n\n\t\t\/\/ getter\n\t\tbuffer.Printf(\"\\npublic %s get%s()\\n{\", typeName, camelName)\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nreturn this.%s;\", properName)\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\")\n\n\t\t\/\/ setter\n\t\tbuffer.Printf(\"\\npublic void set%s(%s value)\\n{\", camelName, typeName)\n\t\tbuffer.AddIndentation(1)\n\n\t\tswitch subschema.GetSchemaType() {\n\t\tcase SCHEMATYPE_STRING:\n\t\t\tgenerateCSharpStringSetter(subschema.(*StringSchema), buffer)\n\t\tcase SCHEMATYPE_INTEGER:\n\t\t\tfallthrough\n\t\tcase SCHEMATYPE_NUMBER:\n\t\t\tgenerateCSharpNumericSetter(subschema.(NumericSchemaType), buffer)\n\t\tcase SCHEMATYPE_OBJECT:\n\t\t\tgenerateCSharpObjectSetter(subschema.(*ObjectSchema), buffer)\n\t\tcase SCHEMATYPE_ARRAY:\n\t\t\tgenerateCSharpArraySetter(subschema.(*ArraySchema), buffer)\n\t\t}\n\n\t\tbuffer.Printf(\"\\n%s = value;\", properName)\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\\n\")\n\t}\n}\n\nfunc generateCSharpStringSetter(schema *StringSchema, buffer *BufferedFormatString) {\n\n\tif !schema.Nullable {\n\t\tgenerateCSharpNullCheck(buffer)\n\t}\n\n\tif schema.MinLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MinLength, \"value.Length\", \"was shorter than allowable minimum\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MaxLength, \"value.Length\", \"was longer than allowable maximum\", \"%d\", false, \">\", \"\", buffer)\n\t}\n\n\tif schema.MinByteLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MinByteLength, \"value.Length * sizeof(Char)\", \"had fewer bytes than allowable minimum\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxByteLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MaxByteLength, \"value.Length * sizeof(Char)\", \"had more bytes than allowable minimum\", \"%d\", false, \">\", \"\", buffer)\n\t}\n\n\tif schema.Pattern != nil {\n\n\t\tbuffer.Printf(\"\\nRegex regex = new Regex(\\\"%s\\\");\", sanitizeQuotedString(*schema.Pattern))\n\t\tbuffer.Printf(\"\\nif(!regex.IsMatch(value))\\n{\")\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nthrow new Exception(\\\"Value '\\\"+value+\\\"' did not match pattern '%s'\\\");\", *schema.Pattern)\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\")\n\t}\n}\n\nfunc generateCSharpNumericSetter(schema NumericSchemaType, buffer *BufferedFormatString) {\n\n\tif schema.HasMinimum() {\n\t\tgenerateCSharpRangeCheck(schema.GetMinimum(), \"value\", \"is under the allowable minimum\", schema.GetConstraintFormat(), schema.IsExclusiveMinimum(), \"<=\", \"<\", buffer)\n\t}\n\n\tif schema.HasMaximum() {\n\t\tgenerateCSharpRangeCheck(schema.GetMaximum(), \"value\", \"is over the allowable maximum\", schema.GetConstraintFormat(), schema.IsExclusiveMaximum(), \">=\", \">\", buffer)\n\t}\n\n\tif schema.HasEnum() {\n\t\tgenerateCSharpEnumCheck(schema, buffer, schema.GetEnum(), \"\", \"\")\n\t}\n\n\tif schema.HasMultiple() {\n\n\t\tbuffer.Printf(\"\\nif(value %% %f != 0)\\n{\", schema.GetMultiple())\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nthrow new Exception(\\\"Property '\\\"+value+\\\"' was not a multiple of %s\\\");\", schema.GetMultiple())\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\\n\")\n\t}\n}\n\nfunc generateCSharpObjectSetter(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tif !schema.Nullable {\n\t\tgenerateCSharpNullCheck(buffer)\n\t}\n}\n\nfunc generateCSharpArraySetter(schema *ArraySchema, buffer *BufferedFormatString) {\n\n\tif !schema.Nullable {\n\t\tgenerateCSharpNullCheck(buffer)\n\t}\n\n\tif schema.MinItems != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MinItems, \"value.Length\", \"does not have enough items\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxItems != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MaxItems, \"value.Length\", \"does not have enough items\", \"%d\", false, \">\", \"\", buffer)\n\t}\n}\n\nfunc generateCSharpNullCheck(buffer *BufferedFormatString) {\n\n\tbuffer.Printf(\"\\nif(value == null)\\n{\")\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Print(\"\\nthrow new NullReferenceException(\\\"Cannot set property to null value\\\");\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\nfunc generateCSharpRangeCheck(value interface{}, reference, message, format string, exclusive bool, comparator, exclusiveComparator string, buffer *BufferedFormatString) {\n\n\tvar compareString string\n\n\tif exclusive {\n\t\tcompareString = exclusiveComparator\n\t} else {\n\t\tcompareString = comparator\n\t}\n\n\tbuffer.Printf(\"\\nif(%s %s \"+format+\")\\n{\", reference, compareString, value)\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Printf(\"\\nthrow new Exception(\\\"Property '\\\"+value+\\\"' %s.\\\");\", message)\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\n\/*\n\tGenerates code which throws an error if the given [parameter]'s value is not contained in the given [validValues].\n*\/\nfunc generateCSharpEnumCheck(schema TypeSchema, buffer *BufferedFormatString, enumValues []interface{}, prefix string, postfix string) {\n\n\tvar typeName string\n\tvar length int\n\n\tlength = len(enumValues)\n\n\tif length <= 0 {\n\t\treturn\n\t}\n\n\t\/\/ write array of valid values\n\ttypeName = GenerateCSharpTypeForSchema(schema)\n\tbuffer.Printf(\"%s[] validValues = new %s[]{%s%v%s\", typeName, typeName, prefix, enumValues[0], postfix)\n\n\tfor _, enumValue := range enumValues[1:length] {\n\t\tbuffer.Printf(\",%s%v%s\", prefix, enumValue, postfix)\n\t}\n\n\tbuffer.Print(\"};\\n\")\n\n\t\/\/ compare\n\tbuffer.Print(\"\\nbool isValid = false;\")\n\tbuffer.Print(\"\\nfor(int i = 0; i < validValues.Length; i++)\\n{\")\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Print(\"\\nif(validValues[i] == value)\\n{\")\n\tbuffer.AddIndentation(1)\n\tbuffer.Print(\"\\nisValid = true;\\nbreak;\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\n\tbuffer.Print(\"\\nif(!isValid)\\n{\")\n\tbuffer.AddIndentation(1)\n\tbuffer.Print(\"\\nthrow new Exception(\\\"Given value '\\\"+value+\\\"' was not found in list of acceptable values\\\");\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\nfunc GenerateCSharpTypeForSchema(subschema TypeSchema) string {\n\n\tswitch subschema.GetSchemaType() {\n\tcase SCHEMATYPE_NUMBER:\n\t\treturn \"double\"\n\tcase SCHEMATYPE_INTEGER:\n\t\treturn \"int\"\n\tcase SCHEMATYPE_ARRAY:\n\t\treturn ToCamelCase(subschema.(*ArraySchema).Items.GetTitle()) + \"[]\"\n\tcase SCHEMATYPE_OBJECT:\n\t\treturn ToCamelCase(subschema.GetTitle())\n\tcase SCHEMATYPE_STRING:\n\t\treturn \"string\"\n\tcase SCHEMATYPE_BOOLEAN:\n\t\treturn \"bool\"\n\t}\n\n\treturn \"Object\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/skatteetaten\/ao\/pkg\/client\"\n\t\"github.com\/skatteetaten\/ao\/pkg\/config\"\n\t\"github.com\/skatteetaten\/ao\/pkg\/fuzzy\"\n\t\"github.com\/skatteetaten\/ao\/pkg\/prompt\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tflagAffiliation string\n\tflagOverrides   []string\n\tflagNoPrompt    bool\n\tflagVersion     string\n\tflagCluster     string\n)\n\nconst deployLong = `Deploys applications from the current AuroraConfig.\nFor use in CI environments use --no-prompt to disable interactivity.\n`\n\nconst exampleDeploy = `  Given the following AuroraConfig:\n    - about.json\n    - foobar.json\n    - bar.json\n    - foo\/about.json\n    - foo\/bar.json\n    - foo\/foobar.json\n\n  # Fuzzy matching: deploy foo\/bar and foo\/foobar\n  ao deploy fo\/ba\n\n  # Exact matching: deploy foo\/bar\n  ao deploy foo\/bar\n\n  # Deploy an application with override for application file\n  ao deploy foo\/bar -o 'foo\/bar.json:{\"pause\": true}'\n`\n\nvar deployCmd = &cobra.Command{\n\tAliases:     []string{\"setup\", \"apply\"},\n\tUse:         \"deploy <applicationId>\",\n\tShort:       \"Deploy one or more ApplicationId (environment\/application) to one or more clusters\",\n\tLong:        deployLong,\n\tExample:     exampleDeploy,\n\tAnnotations: map[string]string{\"type\": \"actions\"},\n\tRunE:        deploy,\n}\n\nfunc init() {\n\tRootCmd.AddCommand(deployCmd)\n\n\tdeployCmd.Flags().StringVarP(&flagAffiliation, \"auroraconfig\", \"a\", \"\", \"Overrides the logged in AuroraConfig\")\n\tdeployCmd.Flags().StringVarP(&flagCluster, \"cluster\", \"c\", \"\", \"Limit deploy to given cluster name\")\n\tdeployCmd.Flags().BoolVarP(&flagNoPrompt, \"no-prompt\", \"\", false, \"Suppress prompts\")\n\tdeployCmd.Flags().StringArrayVarP(&flagOverrides, \"overrides\", \"o\", []string{}, \"Override in the form '[env\/]file:{<json override>}'\")\n\tdeployCmd.Flags().StringVarP(&flagVersion, \"version\", \"v\", \"\", \"Set the given version in AuroraConfig before deploy\")\n\n\tdeployCmd.Flags().BoolVarP(&flagNoPrompt, \"force\", \"f\", false, \"Suppress prompts\")\n\tdeployCmd.Flags().MarkHidden(\"force\")\n\tdeployCmd.Flags().StringVarP(&flagAffiliation, \"affiliation\", \"\", \"\", \"Overrides the logged in affiliation\")\n\tdeployCmd.Flags().MarkHidden(\"affiliation\")\n}\n\nfunc deploy(cmd *cobra.Command, args []string) error {\n\n\tif len(args) > 2 || len(args) < 1 {\n\t\treturn cmd.Usage()\n\t}\n\n\tsearch := args[0]\n\tif len(args) == 2 {\n\t\tsearch = fmt.Sprintf(\"%s\/%s\", args[0], args[1])\n\t}\n\n\toverrides, err := parseOverride(flagOverrides)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif flagAffiliation == \"\" {\n\t\tflagAffiliation = AO.Affiliation\n\t}\n\n\tapi := DefaultApiClient\n\tapi.Affiliation = flagAffiliation\n\n\tif flagCluster != \"\" && !AO.Localhost {\n\t\tc := AO.Clusters[flagCluster]\n\t\tif c == nil {\n\t\t\treturn errors.New(\"No such cluster \" + flagCluster)\n\t\t}\n\t\tif !c.Reachable {\n\t\t\treturn errors.Errorf(\"%s cluster is not reachable\", flagCluster)\n\t\t}\n\n\t\tapi.Host = c.BooberUrl\n\t\tapi.Token = c.Token\n\t\tif pFlagToken != \"\" {\n\t\t\tapi.Token = pFlagToken\n\t\t}\n\t}\n\n\tfiles, err := api.GetFileNames()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpossibleDeploys := files.GetApplicationIds()\n\tapplications := fuzzy.SearchForApplications(search, possibleDeploys)\n\n\tif len(applications) == 0 {\n\t\treturn errors.New(\"No applications to deploy\")\n\t}\n\n\tif flagVersion != \"\" {\n\t\tif len(applications) > 1 {\n\t\t\treturn errors.New(\"Deploy with version does only support one application\")\n\t\t}\n\t\tfileName, err := files.Find(applications[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = Set(cmd, []string{fileName, \"\/version\", flagVersion})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tdeploySpecs, err := api.GetAuroraDeploySpec(applications, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar filteredDeploymentSpecs []client.AuroraDeploySpec\n\tif flagCluster != \"\" {\n\t\tfor _, spec := range deploySpecs {\n\t\t\tif spec.Value(\"\/cluster\").(string) == flagCluster {\n\t\t\t\tfilteredDeploymentSpecs = append(filteredDeploymentSpecs, spec)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfilteredDeploymentSpecs = deploySpecs\n\t}\n\theader, rows := GetDeploySpecTable(filteredDeploymentSpecs)\n\tDefaultTablePrinter(header, rows, cmd.OutOrStdout())\n\n\tvar filteredApplications []string\n\tfor _, spec := range filteredDeploymentSpecs {\n\t\tappID := spec.Value(\"applicationId\").(string)\n\t\tfilteredApplications = append(filteredApplications, appID)\n\t}\n\n\tshouldDeploy := true\n\tif !flagNoPrompt {\n\t\tdefaultAnswer := len(filteredApplications) == 1\n\t\tmessage := fmt.Sprintf(\"Do you want to deploy %d application(s)?\", len(filteredApplications))\n\t\tshouldDeploy = prompt.Confirm(message, defaultAnswer)\n\t}\n\n\tif !shouldDeploy {\n\t\treturn errors.New(\"No applications to deploy\")\n\t}\n\n\tpayload := client.NewDeployPayload(filteredApplications, overrides)\n\n\tvar result []*client.DeployResults\n\tif AO.Localhost || flagCluster != \"\" {\n\t\tres, err := api.Deploy(payload)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresult = append(result, res)\n\t} else {\n\t\tresult, err = deployToReachableClusters(flagAffiliation, pFlagToken, AO.Clusters, payload)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar results []client.DeployResult\n\tfor _, r := range result {\n\t\tresults = append(results, r.Results...)\n\t}\n\n\tif len(results) == 0 {\n\t\treturn errors.New(\"No deploys were made\")\n\t}\n\n\tsort.Slice(results, func(i, j int) bool {\n\t\treturn strings.Compare(results[i].ADS.Name, results[j].ADS.Name) < 1\n\t})\n\n\theader, rows = getDeployResultTable(results)\n\tif len(rows) == 0 {\n\t\treturn nil\n\t}\n\n\tDefaultTablePrinter(header, rows, cmd.OutOrStdout())\n\tfor _, deploy := range results {\n\t\tif !deploy.Success {\n\t\t\treturn errors.New(\"One or more deploys failed\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc deployToReachableClusters(affiliation, token string, clusters map[string]*config.Cluster, payload *client.DeployPayload) ([]*client.DeployResults, error) {\n\n\treachableClusters := 0\n\tdeployResult := make(chan *client.DeployResults)\n\tdeployErrors := make(chan error)\n\tfor _, c := range clusters {\n\t\tif !c.Reachable {\n\t\t\tcontinue\n\t\t}\n\t\treachableClusters++\n\n\t\tclusterToken := c.Token\n\t\tif token != \"\" {\n\t\t\tclusterToken = token\n\t\t}\n\n\t\tcli := &client.ApiClient{\n\t\t\tAffiliation: affiliation,\n\t\t\tHost:        c.BooberUrl,\n\t\t\tToken:       clusterToken,\n\t\t\tRefName:     DefaultApiClient.RefName,\n\t\t}\n\n\t\tgo func() {\n\t\t\tresult, err := cli.Deploy(payload)\n\t\t\tif err != nil {\n\t\t\t\tdeployErrors <- err\n\t\t\t} else {\n\t\t\t\tdeployResult <- result\n\t\t\t}\n\t\t}()\n\t}\n\n\tvar allResults []*client.DeployResults\n\tfor i := 0; i < reachableClusters; i++ {\n\t\tselect {\n\t\tcase err := <-deployErrors:\n\t\t\treturn nil, err\n\t\tcase result := <-deployResult:\n\t\t\tallResults = append(allResults, result)\n\t\t}\n\t}\n\n\treturn allResults, nil\n}\n\nfunc parseOverride(override []string) (map[string]string, error) {\n\treturnMap := make(map[string]string)\n\tfor i := 0; i < len(override); i++ {\n\t\tindexByte := strings.IndexByte(override[i], ':')\n\t\tfilename := override[i][:indexByte]\n\t\tjsonOverride := override[i][indexByte+1:]\n\n\t\tif !json.Valid([]byte(jsonOverride)) {\n\t\t\tmsg := fmt.Sprintf(\"%s is not a valid json\", jsonOverride)\n\t\t\treturn nil, errors.New(msg)\n\t\t}\n\n\t\treturnMap[filename] = jsonOverride\n\t}\n\treturn returnMap, nil\n}\n\nfunc getDeployResultTable(deploys []client.DeployResult) (string, []string) {\n\tvar rows []string\n\tfor _, item := range deploys {\n\t\tif item.Ignored {\n\t\t\tcontinue\n\t\t}\n\t\tads := item.ADS\n\t\tpattern := \"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\"\n\t\tstatus := \"\\x1b[32mDeployed\\x1b[0m\"\n\t\tif !item.Success {\n\t\t\tstatus = \"\\x1b[31mFailed\\x1b[0m\"\n\t\t}\n\t\tresult := fmt.Sprintf(pattern, status, ads.Cluster, ads.Environment.Namespace, ads.Name, ads.Deploy.Version, item.DeployId, item.Reason)\n\t\trows = append(rows, result)\n\t}\n\n\theader := \"\\x1b[00mSTATUS\\x1b[0m\\tCLUSTER\\tENVIRONMENT\\tAPPLICATION\\tVERSION\\tDEPLOY_ID\\tMESSAGE\"\n\treturn header, rows\n}\n<commit_msg>added exclude flag to deploy cmd<commit_after>package cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/skatteetaten\/ao\/pkg\/client\"\n\t\"github.com\/skatteetaten\/ao\/pkg\/config\"\n\t\"github.com\/skatteetaten\/ao\/pkg\/fuzzy\"\n\t\"github.com\/skatteetaten\/ao\/pkg\/prompt\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tflagAffiliation string\n\tflagOverrides   []string\n\tflagNoPrompt    bool\n\tflagVersion     string\n\tflagCluster     string\n\tflagExcludes    []string\n)\n\nconst deployLong = `Deploys applications from the current AuroraConfig.\nFor use in CI environments use --no-prompt to disable interactivity.\n`\n\nconst exampleDeploy = `  Given the following AuroraConfig:\n    - about.json\n    - foobar.json\n    - bar.json\n    - foo\/about.json\n    - foo\/bar.json\n\t\t- foo\/foobar.json\n\t\t- ref\/about.json\n    - ref\/bar.json\n\n  # Fuzzy matching: deploy foo\/bar and foo\/foobar\n  ao deploy fo\/ba\n\n  # Exact matching: deploy foo\/bar\n  ao deploy foo\/bar\n\n  # Deploy an application with override for application file\n\tao deploy foo\/bar -o 'foo\/bar.json:{\"pause\": true}'\n\t\n\t# Exclude application (regexp)\n\tao deploy foo -e .*\/bar\n\n\t# Exclude environment (regexp)\n\tao deploy bar -e ref\/.*\n`\n\nvar deployCmd = &cobra.Command{\n\tAliases:     []string{\"setup\", \"apply\"},\n\tUse:         \"deploy <applicationId>\",\n\tShort:       \"Deploy one or more ApplicationId (environment\/application) to one or more clusters\",\n\tLong:        deployLong,\n\tExample:     exampleDeploy,\n\tAnnotations: map[string]string{\"type\": \"actions\"},\n\tRunE:        deploy,\n}\n\nfunc init() {\n\tRootCmd.AddCommand(deployCmd)\n\n\tdeployCmd.Flags().StringVarP(&flagAffiliation, \"auroraconfig\", \"a\", \"\", \"Overrides the logged in AuroraConfig\")\n\tdeployCmd.Flags().StringVarP(&flagCluster, \"cluster\", \"c\", \"\", \"Limit deploy to given cluster name\")\n\tdeployCmd.Flags().BoolVarP(&flagNoPrompt, \"no-prompt\", \"\", false, \"Suppress prompts\")\n\tdeployCmd.Flags().StringArrayVarP(&flagOverrides, \"overrides\", \"o\", []string{}, \"Override in the form '[env\/]file:{<json override>}'\")\n\tdeployCmd.Flags().StringArrayVarP(&flagExcludes, \"exclude\", \"e\", []string{}, \"Select applications or environments to exclude from deploy\")\n\tdeployCmd.Flags().StringVarP(&flagVersion, \"version\", \"v\", \"\", \"Set the given version in AuroraConfig before deploy\")\n\n\tdeployCmd.Flags().BoolVarP(&flagNoPrompt, \"force\", \"f\", false, \"Suppress prompts\")\n\tdeployCmd.Flags().MarkHidden(\"force\")\n\tdeployCmd.Flags().StringVarP(&flagAffiliation, \"affiliation\", \"\", \"\", \"Overrides the logged in affiliation\")\n\tdeployCmd.Flags().MarkHidden(\"affiliation\")\n}\n\nfunc deploy(cmd *cobra.Command, args []string) error {\n\n\tif len(args) > 2 || len(args) < 1 {\n\t\treturn cmd.Usage()\n\t}\n\n\tsearch := args[0]\n\tif len(args) == 2 {\n\t\tsearch = fmt.Sprintf(\"%s\/%s\", args[0], args[1])\n\t}\n\n\toverrides, err := parseOverride(flagOverrides)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif flagAffiliation == \"\" {\n\t\tflagAffiliation = AO.Affiliation\n\t}\n\n\tapi := DefaultApiClient\n\tapi.Affiliation = flagAffiliation\n\n\tif flagCluster != \"\" && !AO.Localhost {\n\t\tc := AO.Clusters[flagCluster]\n\t\tif c == nil {\n\t\t\treturn errors.New(\"No such cluster \" + flagCluster)\n\t\t}\n\t\tif !c.Reachable {\n\t\t\treturn errors.Errorf(\"%s cluster is not reachable\", flagCluster)\n\t\t}\n\n\t\tapi.Host = c.BooberUrl\n\t\tapi.Token = c.Token\n\t\tif pFlagToken != \"\" {\n\t\t\tapi.Token = pFlagToken\n\t\t}\n\t}\n\n\tfiles, err := api.GetFileNames()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpossibleDeploys := files.GetApplicationIds()\n\tapplications := fuzzy.SearchForApplications(search, possibleDeploys)\n\n\tapplications, err = filterExcludes(flagExcludes, applications)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(applications) == 0 {\n\t\treturn errors.New(\"No applications to deploy\")\n\t}\n\n\tif flagVersion != \"\" {\n\t\tif len(applications) > 1 {\n\t\t\treturn errors.New(\"Deploy with version does only support one application\")\n\t\t}\n\t\tfileName, err := files.Find(applications[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = Set(cmd, []string{fileName, \"\/version\", flagVersion})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tdeploySpecs, err := api.GetAuroraDeploySpec(applications, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar filteredDeploymentSpecs []client.AuroraDeploySpec\n\tif flagCluster != \"\" {\n\t\tfor _, spec := range deploySpecs {\n\t\t\tif spec.Value(\"\/cluster\").(string) == flagCluster {\n\t\t\t\tfilteredDeploymentSpecs = append(filteredDeploymentSpecs, spec)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfilteredDeploymentSpecs = deploySpecs\n\t}\n\theader, rows := GetDeploySpecTable(filteredDeploymentSpecs)\n\tDefaultTablePrinter(header, rows, cmd.OutOrStdout())\n\n\tvar filteredApplications []string\n\tfor _, spec := range filteredDeploymentSpecs {\n\t\tappID := spec.Value(\"applicationId\").(string)\n\t\tfilteredApplications = append(filteredApplications, appID)\n\t}\n\n\tshouldDeploy := true\n\tif !flagNoPrompt {\n\t\tdefaultAnswer := len(filteredApplications) == 1\n\t\tmessage := fmt.Sprintf(\"Do you want to deploy %d application(s)?\", len(filteredApplications))\n\t\tshouldDeploy = prompt.Confirm(message, defaultAnswer)\n\t}\n\n\tif !shouldDeploy {\n\t\treturn errors.New(\"No applications to deploy\")\n\t}\n\n\tpayload := client.NewDeployPayload(filteredApplications, overrides)\n\n\tvar result []*client.DeployResults\n\tif AO.Localhost || flagCluster != \"\" {\n\t\tres, err := api.Deploy(payload)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresult = append(result, res)\n\t} else {\n\t\tresult, err = deployToReachableClusters(flagAffiliation, pFlagToken, AO.Clusters, payload)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar results []client.DeployResult\n\tfor _, r := range result {\n\t\tresults = append(results, r.Results...)\n\t}\n\n\tif len(results) == 0 {\n\t\treturn errors.New(\"No deploys were made\")\n\t}\n\n\tsort.Slice(results, func(i, j int) bool {\n\t\treturn strings.Compare(results[i].ADS.Name, results[j].ADS.Name) < 1\n\t})\n\n\theader, rows = getDeployResultTable(results)\n\tif len(rows) == 0 {\n\t\treturn nil\n\t}\n\n\tDefaultTablePrinter(header, rows, cmd.OutOrStdout())\n\tfor _, deploy := range results {\n\t\tif !deploy.Success {\n\t\t\treturn errors.New(\"One or more deploys failed\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc filterExcludes(expressions, applications []string) ([]string, error) {\n\n\tapps := make([]string, len(applications))\n\tcopy(apps, applications)\n\tfor _, expr := range expressions {\n\t\tr, err := regexp.Compile(expr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttmp := apps[:0]\n\t\tfor _, app := range apps {\n\t\t\tmatch := r.MatchString(app)\n\t\t\tif !match {\n\t\t\t\ttmp = append(tmp, app)\n\t\t\t}\n\t\t}\n\t\tapps = tmp\n\t}\n\n\treturn apps, nil\n}\n\nfunc deployToReachableClusters(affiliation, token string, clusters map[string]*config.Cluster, payload *client.DeployPayload) ([]*client.DeployResults, error) {\n\n\treachableClusters := 0\n\tdeployResult := make(chan *client.DeployResults)\n\tdeployErrors := make(chan error)\n\tfor _, c := range clusters {\n\t\tif !c.Reachable {\n\t\t\tcontinue\n\t\t}\n\t\treachableClusters++\n\n\t\tclusterToken := c.Token\n\t\tif token != \"\" {\n\t\t\tclusterToken = token\n\t\t}\n\n\t\tcli := &client.ApiClient{\n\t\t\tAffiliation: affiliation,\n\t\t\tHost:        c.BooberUrl,\n\t\t\tToken:       clusterToken,\n\t\t\tRefName:     DefaultApiClient.RefName,\n\t\t}\n\n\t\tgo func() {\n\t\t\tresult, err := cli.Deploy(payload)\n\t\t\tif err != nil {\n\t\t\t\tdeployErrors <- err\n\t\t\t} else {\n\t\t\t\tdeployResult <- result\n\t\t\t}\n\t\t}()\n\t}\n\n\tvar allResults []*client.DeployResults\n\tfor i := 0; i < reachableClusters; i++ {\n\t\tselect {\n\t\tcase err := <-deployErrors:\n\t\t\treturn nil, err\n\t\tcase result := <-deployResult:\n\t\t\tallResults = append(allResults, result)\n\t\t}\n\t}\n\n\treturn allResults, nil\n}\n\nfunc parseOverride(override []string) (map[string]string, error) {\n\treturnMap := make(map[string]string)\n\tfor i := 0; i < len(override); i++ {\n\t\tindexByte := strings.IndexByte(override[i], ':')\n\t\tfilename := override[i][:indexByte]\n\t\tjsonOverride := override[i][indexByte+1:]\n\n\t\tif !json.Valid([]byte(jsonOverride)) {\n\t\t\tmsg := fmt.Sprintf(\"%s is not a valid json\", jsonOverride)\n\t\t\treturn nil, errors.New(msg)\n\t\t}\n\n\t\treturnMap[filename] = jsonOverride\n\t}\n\treturn returnMap, nil\n}\n\nfunc getDeployResultTable(deploys []client.DeployResult) (string, []string) {\n\tvar rows []string\n\tfor _, item := range deploys {\n\t\tif item.Ignored {\n\t\t\tcontinue\n\t\t}\n\t\tads := item.ADS\n\t\tpattern := \"%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\"\n\t\tstatus := \"\\x1b[32mDeployed\\x1b[0m\"\n\t\tif !item.Success {\n\t\t\tstatus = \"\\x1b[31mFailed\\x1b[0m\"\n\t\t}\n\t\tresult := fmt.Sprintf(pattern, status, ads.Cluster, ads.Environment.Namespace, ads.Name, ads.Deploy.Version, item.DeployId, item.Reason)\n\t\trows = append(rows, result)\n\t}\n\n\theader := \"\\x1b[00mSTATUS\\x1b[0m\\tCLUSTER\\tENVIRONMENT\\tAPPLICATION\\tVERSION\\tDEPLOY_ID\\tMESSAGE\"\n\treturn header, rows\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build !bootstrap\n\npackage core\n\nimport (\n\t\"github.com\/jessevdk\/go-flags\"\n\n\t\"strings\"\n)\n\n\/\/ AttachAliasFlags attaches the alias flags to the given flag parser.\n\/\/ It returns true if any modifications were made.\nfunc (config *Configuration) AttachAliasFlags(parser *flags.Parser) bool {\n\tfor name, alias := range config.AllAliases() {\n\t\tcmd := parser.Command\n\t\tfor i, namePart := range strings.Fields(name) {\n\t\t\tcmd = addSubcommand(cmd, namePart, alias.Desc, alias.PositionalLabels && len(alias.Subcommand) == 0 && i > 0)\n\t\t\tfor _, subcommand := range alias.Subcommand {\n\t\t\t\taddSubcommands(cmd, strings.Fields(subcommand), alias.PositionalLabels)\n\t\t\t}\n\t\t\tfor _, flag := range alias.Flag {\n\t\t\t\t\/\/ This is unavailable during bootstrap due to being a local modification.\n\t\t\t\tcmd.AddOption(getOption(flag))\n\t\t\t}\n\t\t}\n\t}\n\treturn len(config.Aliases) > 0 || len(config.Alias) > 0\n}\n\n\/\/ addSubcommands attaches a series of subcommands to the given command.\nfunc addSubcommands(cmd *flags.Command, subcommands []string, positionalLabels bool) {\n\tif len(subcommands) > 0 && cmd != nil {\n\t\taddSubcommands(addSubcommand(cmd, subcommands[0], \"\", positionalLabels), subcommands[1:], positionalLabels)\n\t}\n}\n\n\/\/ addSubcommand adds a single subcommand to the given command.\n\/\/ If one by that name already exists, it is returned.\nfunc addSubcommand(cmd *flags.Command, subcommand, desc string, positionalLabels bool) *flags.Command {\n\tif existing := cmd.Find(subcommand); existing != nil {\n\t\treturn existing\n\t}\n\tvar data interface{} = &struct{}{}\n\tif positionalLabels {\n\t\tdata = &struct {\n\t\t\tArgs struct {\n\t\t\t\tTarget []BuildLabel `positional-arg-name:\"target\" description:\"Build targets\"`\n\t\t\t} `positional-args:\"true\"`\n\t\t}{}\n\t}\n\tnewCmd, _ := cmd.AddCommand(subcommand, desc, desc, data)\n\treturn newCmd\n}\n\n\/\/ getOption creates a new flags.Option.\n\/\/ This is a fiddle since it doesn't really expose a direct way of doing this programmatically.\nfunc getOption(name string) *flags.Option {\n\tdata := struct {\n\t\tOpt string `long:\"option\"`\n\t}{}\n\tp := flags.NewParser(&data, 0)\n\topt := p.FindOptionByLongName(\"option\")\n\topt.LongName = strings.TrimLeft(name, \"-\")\n\tif len(name) == 2 && name[0] == '-' {\n\t\topt.ShortName = rune(name[1])\n\t}\n\treturn opt\n}\n<commit_msg>fix flags logic<commit_after>\/\/ +build !bootstrap\n\npackage core\n\nimport (\n\t\"github.com\/jessevdk\/go-flags\"\n\n\t\"strings\"\n)\n\n\/\/ AttachAliasFlags attaches the alias flags to the given flag parser.\n\/\/ It returns true if any modifications were made.\nfunc (config *Configuration) AttachAliasFlags(parser *flags.Parser) bool {\n\tfor name, alias := range config.AllAliases() {\n\t\tcmd := parser.Command\n\t\tfields := strings.Fields(name)\n\t\tfor i, namePart := range fields {\n\t\t\tcmd = addSubcommand(cmd, namePart, alias.Desc, alias.PositionalLabels && len(alias.Subcommand) == 0 && i == len(fields)-1)\n\t\t\tfor _, subcommand := range alias.Subcommand {\n\t\t\t\taddSubcommands(cmd, strings.Fields(subcommand), alias.PositionalLabels)\n\t\t\t}\n\t\t\tfor _, flag := range alias.Flag {\n\t\t\t\t\/\/ This is unavailable during bootstrap due to being a local modification.\n\t\t\t\tcmd.AddOption(getOption(flag))\n\t\t\t}\n\t\t}\n\t}\n\treturn len(config.Aliases) > 0 || len(config.Alias) > 0\n}\n\n\/\/ addSubcommands attaches a series of subcommands to the given command.\nfunc addSubcommands(cmd *flags.Command, subcommands []string, positionalLabels bool) {\n\tif len(subcommands) > 0 && cmd != nil {\n\t\taddSubcommands(addSubcommand(cmd, subcommands[0], \"\", positionalLabels), subcommands[1:], positionalLabels)\n\t}\n}\n\n\/\/ addSubcommand adds a single subcommand to the given command.\n\/\/ If one by that name already exists, it is returned.\nfunc addSubcommand(cmd *flags.Command, subcommand, desc string, positionalLabels bool) *flags.Command {\n\tif existing := cmd.Find(subcommand); existing != nil {\n\t\treturn existing\n\t}\n\tvar data interface{} = &struct{}{}\n\tif positionalLabels {\n\t\tdata = &struct {\n\t\t\tArgs struct {\n\t\t\t\tTarget []BuildLabel `positional-arg-name:\"target\" description:\"Build targets\"`\n\t\t\t} `positional-args:\"true\"`\n\t\t}{}\n\t}\n\tnewCmd, _ := cmd.AddCommand(subcommand, desc, desc, data)\n\treturn newCmd\n}\n\n\/\/ getOption creates a new flags.Option.\n\/\/ This is a fiddle since it doesn't really expose a direct way of doing this programmatically.\nfunc getOption(name string) *flags.Option {\n\tdata := struct {\n\t\tOpt string `long:\"option\"`\n\t}{}\n\tp := flags.NewParser(&data, 0)\n\topt := p.FindOptionByLongName(\"option\")\n\topt.LongName = strings.TrimLeft(name, \"-\")\n\tif len(name) == 2 && name[0] == '-' {\n\t\topt.ShortName = rune(name[1])\n\t}\n\treturn opt\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\n\/\/ Error codes\nconst (\n\t_ = iota\n\t\/\/ KubeauditInternalError is an internal error which cannot be fixed by the user.\n\tKubeauditInternalError\n\t\/\/ ErrorAllowPrivilegeEscalationNIL occurs when AllowPrivilegeEscalation is not\n\t\/\/ set which allows privilege escalation.\n\tErrorAllowPrivilegeEscalationNIL\n\t\/\/ ErrorAllowPrivilegeEscalationTrue occurs when AllowPrivilegeEscalation is set to true\n\tErrorAllowPrivilegeEscalationTrue\n\t\/\/ ErrorAllowPrivilegeEscalationTrueAllowed occurs when AllowPrivilegeEscalation is\n\t\/\/ allowed to be set to true.\n\tErrorAllowPrivilegeEscalationTrueAllowed\n\t\/\/ ErrorAutomountServiceAccountTokenNILAndNoName occurs when automountServiceAccountToken\n\t\/\/ is not set and serviceAccountName is blank.\n\tErrorAutomountServiceAccountTokenNILAndNoName\n\t\/\/ ErrorAutomountServiceAccountTokenTrueAllowed occurs when automountServiceAccountToken\n\t\/\/ is allowed to be set to true.\n\tErrorAutomountServiceAccountTokenTrueAllowed\n\t\/\/ ErrorAutomountServiceAccountTokenTrueAndNoName occurs when automountServiceAccountToken\n\t\/\/ is set as true and serviceAccountName is blank.\n\tErrorAutomountServiceAccountTokenTrueAndNoName\n\t\/\/ ErrorCapabilityAdded occurs when a capability is added that is not allowed\n\tErrorCapabilityAdded\n\t\/\/ ErrorCapabilityAllowed occurs when a capability is allowed that is part of the\n\t\/\/ toBeDropped list.\n\tErrorCapabilityAllowed\n\t\/\/ ErrorCapabilityNotDropped occurs when a capability should be dropped but it isn't\n\tErrorCapabilityNotDropped\n\t\/\/ ErrorImageTagIncorrect occurs when an incorrect image tag is provided.\n\tErrorImageTagIncorrect\n\t\/\/ ErrorImageTagMissing occurs when there is no image tag provided.\n\tErrorImageTagMissing\n\t\/\/ ErrorMisconfiguredKubeauditAllow occurs when the option to allow a setting is set to\n\t\/\/ true but the option itself is set to false or nil.\n\tErrorMisconfiguredKubeauditAllow\n\t\/\/ ErrorPrivilegedNIL occurs when Privileged is not set.\n\tErrorPrivilegedNIL\n\t\/\/ ErrorPrivilegedTrue occurs when Privileged is set to true.\n\tErrorPrivilegedTrue\n\t\/\/ ErrorPrivilegedTrueAllowed occurs when Privileged is allowed to be set to true.\n\tErrorPrivilegedTrueAllowed\n\t\/\/ ErrorReadOnlyRootFilesystemFalse occurs when ReadOnlyRootFilesystem is set to false.\n\tErrorReadOnlyRootFilesystemFalse\n\t\/\/ ErrorReadOnlyRootFilesystemFalseAllowed occurs when ReadOnlyRootFilesystem is allowed\n\t\/\/ to be set to false.\n\tErrorReadOnlyRootFilesystemFalseAllowed\n\t\/\/ ErrorReadOnlyRootFilesystemNIL occurs when ReadOnlyRootFilesystem is set to nil.\n\tErrorReadOnlyRootFilesystemNIL\n\t\/\/ ErrorResourcesLimitsCPUExceeded occurs when the CPU limit is exceeded.\n\tErrorResourcesLimitsCPUExceeded\n\t\/\/ ErrorResourcesLimitsCPUNIL occurs when the CPU limit is not set.\n\tErrorResourcesLimitsCPUNIL\n\t\/\/ ErrorResourcesLimitsMemoryExceeded occurs when the memory limit is exceeded.\n\tErrorResourcesLimitsMemoryExceeded\n\t\/\/ ErrorResourcesLimitsMemoryNIL occurs when the memory limit is not set.\n\tErrorResourcesLimitsMemoryNIL\n\t\/\/ ErrorResourcesLimitsNIL occurs when the resource limit is set to nil.\n\tErrorResourcesLimitsNIL\n\t\/\/ ErrorRunAsNonRootFalse occurs when RunAsNonRoot is set to false.\n\tErrorRunAsNonRootFalse\n\t\/\/ ErrorRunAsNonRootFalseAllowed occurs when RunAsNonRoot is allowed to be set to false.\n\tErrorRunAsNonRootFalseAllowed\n\t\/\/ ErrorRunAsNonRootNIL occurs when RunAsNonRoot is not set.\n\tErrorRunAsNonRootNIL\n\t\/\/ ErrorServiceAccountTokenDeprecated occurs when serviceAccount is used. ServiceAccount\n\t\/\/ is a deprecated alias for ServiceAccountName.\n\tErrorServiceAccountTokenDeprecated\n\tErrorServiceAccountTokenNoName\n\t\/\/ InfoImageCorrect occurs when an image tag is correct.\n\tInfoImageCorrect\n\tPlaceHolder\n)\n<commit_msg>Remove unused constants<commit_after>package cmd\n\n\/\/ Error codes\nconst (\n\t_ = iota\n\t\/\/ KubeauditInternalError is an internal error which cannot be fixed by the user.\n\tKubeauditInternalError\n\t\/\/ ErrorAllowPrivilegeEscalationNIL occurs when AllowPrivilegeEscalation is not\n\t\/\/ set which allows privilege escalation.\n\tErrorAllowPrivilegeEscalationNIL\n\t\/\/ ErrorAllowPrivilegeEscalationTrue occurs when AllowPrivilegeEscalation is set to true\n\tErrorAllowPrivilegeEscalationTrue\n\t\/\/ ErrorAllowPrivilegeEscalationTrueAllowed occurs when AllowPrivilegeEscalation is\n\t\/\/ allowed to be set to true.\n\tErrorAllowPrivilegeEscalationTrueAllowed\n\t\/\/ ErrorAutomountServiceAccountTokenNILAndNoName occurs when automountServiceAccountToken\n\t\/\/ is not set and serviceAccountName is blank.\n\tErrorAutomountServiceAccountTokenNILAndNoName\n\t\/\/ ErrorAutomountServiceAccountTokenTrueAllowed occurs when automountServiceAccountToken\n\t\/\/ is allowed to be set to true.\n\tErrorAutomountServiceAccountTokenTrueAllowed\n\t\/\/ ErrorAutomountServiceAccountTokenTrueAndNoName occurs when automountServiceAccountToken\n\t\/\/ is set as true and serviceAccountName is blank.\n\tErrorAutomountServiceAccountTokenTrueAndNoName\n\t\/\/ ErrorCapabilityAdded occurs when a capability is added that is not allowed\n\tErrorCapabilityAdded\n\t\/\/ ErrorCapabilityAllowed occurs when a capability is allowed that is part of the\n\t\/\/ toBeDropped list.\n\tErrorCapabilityAllowed\n\t\/\/ ErrorCapabilityNotDropped occurs when a capability should be dropped but it isn't\n\tErrorCapabilityNotDropped\n\t\/\/ ErrorImageTagIncorrect occurs when an incorrect image tag is provided.\n\tErrorImageTagIncorrect\n\t\/\/ ErrorImageTagMissing occurs when there is no image tag provided.\n\tErrorImageTagMissing\n\t\/\/ ErrorMisconfiguredKubeauditAllow occurs when the option to allow a setting is set to\n\t\/\/ true but the option itself is set to false or nil.\n\tErrorMisconfiguredKubeauditAllow\n\t\/\/ ErrorPrivilegedNIL occurs when Privileged is not set.\n\tErrorPrivilegedNIL\n\t\/\/ ErrorPrivilegedTrue occurs when Privileged is set to true.\n\tErrorPrivilegedTrue\n\t\/\/ ErrorPrivilegedTrueAllowed occurs when Privileged is allowed to be set to true.\n\tErrorPrivilegedTrueAllowed\n\t\/\/ ErrorReadOnlyRootFilesystemFalse occurs when ReadOnlyRootFilesystem is set to false.\n\tErrorReadOnlyRootFilesystemFalse\n\t\/\/ ErrorReadOnlyRootFilesystemFalseAllowed occurs when ReadOnlyRootFilesystem is allowed\n\t\/\/ to be set to false.\n\tErrorReadOnlyRootFilesystemFalseAllowed\n\t\/\/ ErrorReadOnlyRootFilesystemNIL occurs when ReadOnlyRootFilesystem is set to nil.\n\tErrorReadOnlyRootFilesystemNIL\n\t\/\/ ErrorResourcesLimitsCPUExceeded occurs when the CPU limit is exceeded.\n\tErrorResourcesLimitsCPUExceeded\n\t\/\/ ErrorResourcesLimitsCPUNIL occurs when the CPU limit is not set.\n\tErrorResourcesLimitsCPUNIL\n\t\/\/ ErrorResourcesLimitsMemoryExceeded occurs when the memory limit is exceeded.\n\tErrorResourcesLimitsMemoryExceeded\n\t\/\/ ErrorResourcesLimitsMemoryNIL occurs when the memory limit is not set.\n\tErrorResourcesLimitsMemoryNIL\n\t\/\/ ErrorResourcesLimitsNIL occurs when the resource limit is set to nil.\n\tErrorResourcesLimitsNIL\n\t\/\/ ErrorRunAsNonRootFalse occurs when RunAsNonRoot is set to false.\n\tErrorRunAsNonRootFalse\n\t\/\/ ErrorRunAsNonRootFalseAllowed occurs when RunAsNonRoot is allowed to be set to false.\n\tErrorRunAsNonRootFalseAllowed\n\t\/\/ ErrorRunAsNonRootNIL occurs when RunAsNonRoot is not set.\n\tErrorRunAsNonRootNIL\n\t\/\/ ErrorServiceAccountTokenDeprecated occurs when serviceAccount is used. ServiceAccount\n\t\/\/ is a deprecated alias for ServiceAccountName.\n\tErrorServiceAccountTokenDeprecated\n\t\/\/ InfoImageCorrect occurs when an image tag is correct.\n\tInfoImageCorrect\n)\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements.  See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership.  The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License.  You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied.  See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\npackage cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\n\t\"github.com\/apache\/cloudstack-cloudmonkey\/config\"\n\t\"github.com\/olekukonko\/tablewriter\"\n)\n\nfunc jsonify(value interface{}) string {\n\tif value == nil {\n\t\treturn \"\"\n\t}\n\tif reflect.TypeOf(value).Kind() == reflect.Map || reflect.TypeOf(value).Kind() == reflect.Slice {\n\t\tjsonStr, err := json.MarshalIndent(value, \"\", \"\")\n\t\tif err == nil {\n\t\t\tvalue = string(jsonStr)\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%v\", value)\n}\n\nfunc printJSON(response map[string]interface{}) {\n\tenc := json.NewEncoder(os.Stdout)\n\tenc.SetEscapeHTML(false)\n\tenc.SetIndent(\"\", \"  \")\n\tenc.Encode(response)\n}\n\nfunc printText(response map[string]interface{}) {\n\tfor k, v := range response {\n\t\tvalueType := reflect.TypeOf(v)\n\t\tif valueType.Kind() == reflect.Slice {\n\t\t\tfmt.Printf(\"%v:\\n\", k)\n\t\t\tfor idx, item := range v.([]interface{}) {\n\t\t\t\tif idx > 0 {\n\t\t\t\t\tfmt.Println(\"================================================================================\")\n\t\t\t\t}\n\t\t\t\trow, isMap := item.(map[string]interface{})\n\t\t\t\tif isMap {\n\t\t\t\t\tfor field, value := range row {\n\t\t\t\t\t\tfmt.Printf(\"%s = %v\\n\", field, jsonify(value))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\"%v\\n\", item)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Printf(\"%v = %v\\n\", k, jsonify(v))\n\t\t}\n\t}\n}\n\nfunc printTable(response map[string]interface{}, filter []string) {\n\ttable := tablewriter.NewWriter(os.Stdout)\n\tfor k, v := range response {\n\t\tvalueType := reflect.TypeOf(v)\n\t\tif valueType.Kind() == reflect.Slice {\n\t\t\titems, ok := v.([]interface{})\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Printf(\"%v:\\n\", k)\n\t\t\tvar header []string\n\t\t\tfor _, item := range items {\n\t\t\t\trow, ok := item.(map[string]interface{})\n\t\t\t\tif !ok || len(row) < 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif len(header) == 0 {\n\t\t\t\t\tif len(filter) > 0 {\n\t\t\t\t\t\theader = filter\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor field := range row {\n\t\t\t\t\t\t\theader = append(header, field)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsort.Strings(header)\n\t\t\t\t\t}\n\t\t\t\t\ttable.SetHeader(header)\n\t\t\t\t}\n\t\t\t\tvar rowArray []string\n\t\t\t\tfor _, field := range header {\n\t\t\t\t\trowArray = append(rowArray, jsonify(row[field]))\n\t\t\t\t}\n\t\t\t\ttable.Append(rowArray)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Printf(\"%v = %v\\n\", k, v)\n\t\t}\n\t}\n\ttable.Render()\n}\n\nfunc printColumn(response map[string]interface{}, filter []string) {\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', tabwriter.DiscardEmptyColumns)\n\tfor _, v := range response {\n\t\tvalueType := reflect.TypeOf(v)\n\t\tif valueType.Kind() == reflect.Slice || valueType.Kind() == reflect.Map {\n\t\t\titems, ok := v.([]interface{})\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar header []string\n\t\t\tfor idx, item := range items {\n\t\t\t\trow, ok := item.(map[string]interface{})\n\t\t\t\tif !ok || len(row) < 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif idx == 0 {\n\t\t\t\t\tif len(filter) > 0 {\n\t\t\t\t\t\theader = filter\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor rk := range row {\n\t\t\t\t\t\t\theader = append(header, strings.ToUpper(rk))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsort.Strings(header)\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Fprintln(w, strings.Join(header, \"\\t\"))\n\t\t\t\t}\n\t\t\t\tvar values []string\n\t\t\t\tfor _, key := range header {\n\t\t\t\t\tvalues = append(values, jsonify(row[strings.ToLower(key)]))\n\t\t\t\t}\n\t\t\t\tfmt.Fprintln(w, strings.Join(values, \"\\t\"))\n\t\t\t}\n\t\t}\n\t}\n\tw.Flush()\n}\n\nfunc printCsv(response map[string]interface{}, filter []string) {\n\tfor _, v := range response {\n\t\tvalueType := reflect.TypeOf(v)\n\t\tif valueType.Kind() == reflect.Slice || valueType.Kind() == reflect.Map {\n\t\t\titems, ok := v.([]interface{})\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar header []string\n\t\t\tfor idx, item := range items {\n\t\t\t\trow, ok := item.(map[string]interface{})\n\t\t\t\tif !ok || len(row) < 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif idx == 0 {\n\t\t\t\t\tif len(filter) > 0 {\n\t\t\t\t\t\theader = filter\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor rk := range row {\n\t\t\t\t\t\t\theader = append(header, rk)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsort.Strings(header)\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Println(strings.Join(header, \",\"))\n\t\t\t\t}\n\t\t\t\tvar values []string\n\t\t\t\tfor _, key := range header {\n\t\t\t\t\tvalues = append(values, jsonify(row[key]))\n\t\t\t\t}\n\t\t\t\tfmt.Println(strings.Join(values, \",\"))\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc filterResponse(response map[string]interface{}, filter []string, outputType string) map[string]interface{} {\n\tif filter == nil || len(filter) == 0 {\n\t\treturn response\n\t}\n\tfilteredResponse := make(map[string]interface{})\n\tfor k, v := range response {\n\t\tvalueType := reflect.TypeOf(v)\n\t\tif valueType.Kind() == reflect.Slice || valueType.Kind() == reflect.Map {\n\t\t\titems, ok := v.([]interface{})\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar filteredRows []interface{}\n\t\t\tfor _, item := range items {\n\t\t\t\trow, ok := item.(map[string]interface{})\n\t\t\t\tif !ok || len(row) < 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilteredRow := make(map[string]interface{})\n\t\t\t\tfor _, filterKey := range filter {\n\t\t\t\t\tfor field := range row {\n\t\t\t\t\t\tif filterKey == field {\n\t\t\t\t\t\t\tfilteredRow[field] = row[field]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif outputType == config.COLUMN || outputType == config.CSV || outputType == config.TABLE {\n\t\t\t\t\t\tif _, ok := filteredRow[filterKey]; !ok {\n\t\t\t\t\t\t\tfilteredRow[filterKey] = \"\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfilteredRows = append(filteredRows, filteredRow)\n\t\t\t}\n\t\t\tfilteredResponse[k] = filteredRows\n\t\t} else {\n\t\t\tfilteredResponse[k] = v\n\t\t\tcontinue\n\t\t}\n\n\t}\n\treturn filteredResponse\n}\n\nfunc printResult(outputType string, response map[string]interface{}, filter []string) {\n\tresponse = filterResponse(response, filter, outputType)\n\tswitch outputType {\n\tcase config.JSON:\n\t\tprintJSON(response)\n\tcase config.TEXT:\n\t\tprintText(response)\n\tcase config.COLUMN:\n\t\tprintColumn(response, filter)\n\tcase config.CSV:\n\t\tprintCsv(response, filter)\n\tcase config.TABLE:\n\t\tprintTable(response, filter)\n\tdefault:\n\t\tfmt.Println(\"Invalid output type configured, please fix that!\")\n\t}\n}\n<commit_msg>Avoids adding newline to list\/map output data for output format other than 'text' (#87)<commit_after>\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements.  See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership.  The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License.  You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied.  See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\npackage cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\n\t\"github.com\/apache\/cloudstack-cloudmonkey\/config\"\n\t\"github.com\/olekukonko\/tablewriter\"\n)\n\nfunc jsonify(value interface{}, format string) string {\n\tif value == nil {\n\t\treturn \"\"\n\t}\n\tif reflect.TypeOf(value).Kind() == reflect.Map || reflect.TypeOf(value).Kind() == reflect.Slice {\n\t\tvar jsonStr []byte\n\t\tvar err error\n\t\tif (format == \"text\") {\n\t\t\tjsonStr, err = json.MarshalIndent(value, \"\", \"\")\n\t\t} else {\n\t\t\tjsonStr, err = json.Marshal(value)\n\t\t}\n\t\tif err == nil {\n\t\t\tvalue = string(jsonStr)\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%v\", value)\n}\n\nfunc printJSON(response map[string]interface{}) {\n\tenc := json.NewEncoder(os.Stdout)\n\tenc.SetEscapeHTML(false)\n\tenc.SetIndent(\"\", \"  \")\n\tenc.Encode(response)\n}\n\nfunc printText(response map[string]interface{}) {\n\tformat := \"text\"\n\tfor k, v := range response {\n\t\tvalueType := reflect.TypeOf(v)\n\t\tif valueType.Kind() == reflect.Slice {\n\t\t\tfmt.Printf(\"%v:\\n\", k)\n\t\t\tfor idx, item := range v.([]interface{}) {\n\t\t\t\tif idx > 0 {\n\t\t\t\t\tfmt.Println(\"================================================================================\")\n\t\t\t\t}\n\t\t\t\trow, isMap := item.(map[string]interface{})\n\t\t\t\tif isMap {\n\t\t\t\t\tfor field, value := range row {\n\t\t\t\t\t\tfmt.Printf(\"%s = %v\\n\", field, jsonify(value, format))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\"%v\\n\", item)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Printf(\"%v = %v\\n\", k, jsonify(v, format))\n\t\t}\n\t}\n}\n\nfunc printTable(response map[string]interface{}, filter []string) {\n\tformat := \"table\"\n\ttable := tablewriter.NewWriter(os.Stdout)\n\tfor k, v := range response {\n\t\tvalueType := reflect.TypeOf(v)\n\t\tif valueType.Kind() == reflect.Slice {\n\t\t\titems, ok := v.([]interface{})\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Printf(\"%v:\\n\", k)\n\t\t\tvar header []string\n\t\t\tfor _, item := range items {\n\t\t\t\trow, ok := item.(map[string]interface{})\n\t\t\t\tif !ok || len(row) < 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif len(header) == 0 {\n\t\t\t\t\tif len(filter) > 0 {\n\t\t\t\t\t\theader = filter\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor field := range row {\n\t\t\t\t\t\t\theader = append(header, field)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsort.Strings(header)\n\t\t\t\t\t}\n\t\t\t\t\ttable.SetHeader(header)\n\t\t\t\t}\n\t\t\t\tvar rowArray []string\n\t\t\t\tfor _, field := range header {\n\t\t\t\t\trowArray = append(rowArray, jsonify(row[field], format))\n\t\t\t\t}\n\t\t\t\ttable.Append(rowArray)\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Printf(\"%v = %v\\n\", k, v)\n\t\t}\n\t}\n\ttable.Render()\n}\n\nfunc printColumn(response map[string]interface{}, filter []string) {\n\tformat := \"column\"\n\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', tabwriter.DiscardEmptyColumns)\n\tfor _, v := range response {\n\t\tvalueType := reflect.TypeOf(v)\n\t\tif valueType.Kind() == reflect.Slice || valueType.Kind() == reflect.Map {\n\t\t\titems, ok := v.([]interface{})\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar header []string\n\t\t\tfor idx, item := range items {\n\t\t\t\trow, ok := item.(map[string]interface{})\n\t\t\t\tif !ok || len(row) < 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif idx == 0 {\n\t\t\t\t\tif len(filter) > 0 {\n\t\t\t\t\t\theader = filter\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor rk := range row {\n\t\t\t\t\t\t\theader = append(header, strings.ToUpper(rk))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsort.Strings(header)\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Fprintln(w, strings.Join(header, \"\\t\"))\n\t\t\t\t}\n\t\t\t\tvar values []string\n\t\t\t\tfor _, key := range header {\n\t\t\t\t\tvalues = append(values, jsonify(row[strings.ToLower(key)], format))\n\t\t\t\t}\n\t\t\t\tfmt.Fprintln(w, strings.Join(values, \"\\t\"))\n\t\t\t}\n\t\t}\n\t}\n\tw.Flush()\n}\n\nfunc printCsv(response map[string]interface{}, filter []string) {\n\tformat := \"csv\"\n\tfor _, v := range response {\n\t\tvalueType := reflect.TypeOf(v)\n\t\tif valueType.Kind() == reflect.Slice || valueType.Kind() == reflect.Map {\n\t\t\titems, ok := v.([]interface{})\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar header []string\n\t\t\tfor idx, item := range items {\n\t\t\t\trow, ok := item.(map[string]interface{})\n\t\t\t\tif !ok || len(row) < 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif idx == 0 {\n\t\t\t\t\tif len(filter) > 0 {\n\t\t\t\t\t\theader = filter\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor rk := range row {\n\t\t\t\t\t\t\theader = append(header, rk)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsort.Strings(header)\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Println(strings.Join(header, \",\"))\n\t\t\t\t}\n\t\t\t\tvar values []string\n\t\t\t\tfor _, key := range header {\n\t\t\t\t\tvalues = append(values, jsonify(row[key], format))\n\t\t\t\t}\n\t\t\t\tfmt.Println(strings.Join(values, \",\"))\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc filterResponse(response map[string]interface{}, filter []string, outputType string) map[string]interface{} {\n\tif filter == nil || len(filter) == 0 {\n\t\treturn response\n\t}\n\tfilteredResponse := make(map[string]interface{})\n\tfor k, v := range response {\n\t\tvalueType := reflect.TypeOf(v)\n\t\tif valueType.Kind() == reflect.Slice || valueType.Kind() == reflect.Map {\n\t\t\titems, ok := v.([]interface{})\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar filteredRows []interface{}\n\t\t\tfor _, item := range items {\n\t\t\t\trow, ok := item.(map[string]interface{})\n\t\t\t\tif !ok || len(row) < 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfilteredRow := make(map[string]interface{})\n\t\t\t\tfor _, filterKey := range filter {\n\t\t\t\t\tfor field := range row {\n\t\t\t\t\t\tif filterKey == field {\n\t\t\t\t\t\t\tfilteredRow[field] = row[field]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif outputType == config.COLUMN || outputType == config.CSV || outputType == config.TABLE {\n\t\t\t\t\t\tif _, ok := filteredRow[filterKey]; !ok {\n\t\t\t\t\t\t\tfilteredRow[filterKey] = \"\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfilteredRows = append(filteredRows, filteredRow)\n\t\t\t}\n\t\t\tfilteredResponse[k] = filteredRows\n\t\t} else {\n\t\t\tfilteredResponse[k] = v\n\t\t\tcontinue\n\t\t}\n\n\t}\n\treturn filteredResponse\n}\n\nfunc printResult(outputType string, response map[string]interface{}, filter []string) {\n\tresponse = filterResponse(response, filter, outputType)\n\tswitch outputType {\n\tcase config.JSON:\n\t\tprintJSON(response)\n\tcase config.TEXT:\n\t\tprintText(response)\n\tcase config.COLUMN:\n\t\tprintColumn(response, filter)\n\tcase config.CSV:\n\t\tprintCsv(response, filter)\n\tcase config.TABLE:\n\t\tprintTable(response, filter)\n\tdefault:\n\t\tfmt.Println(\"Invalid output type configured, please fix that!\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/zquestz\/s\/providers\"\n\t\"github.com\/zquestz\/s\/server\"\n)\n\nconst (\n\tappName         = \"s\"\n\tversion         = \"0.4.0\"\n\tdefaultPort     = 8080\n\tdefaultProvider = \"google\"\n)\n\n\/\/ Stores configuration data.\nvar config Config\n\n\/\/ SearchCmd is the main command for Cobra.\nvar SearchCmd = &cobra.Command{\n\tUse:   \"s <query>\",\n\tShort: \"Web search from the terminal\",\n\tLong:  `Web search from the terminal.`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\terr := performCommand(cmd, args)\n\t\tif err != nil {\n\t\t\tbail(err)\n\t\t}\n\t},\n}\n\nfunc init() {\n\terr := config.Load()\n\tif err != nil {\n\t\tbail(err)\n\t}\n\n\tprepareFlags()\n}\n\nfunc bail(err error) {\n\tfmt.Fprintf(os.Stderr, \"[Error] %s\\n\", err)\n\tos.Exit(1)\n}\n\nfunc prepareFlags() {\n\tif config.Provider == \"\" {\n\t\tconfig.Provider = defaultProvider\n\t}\n\n\tif config.Port == 0 {\n\t\tconfig.Port = defaultPort\n\t}\n\n\tSearchCmd.PersistentFlags().BoolVarP(\n\t\t&config.DisplayVersion, \"version\", \"\", false, \"display version\")\n\tSearchCmd.PersistentFlags().BoolVarP(\n\t\t&config.Verbose, \"verbose\", \"v\", config.Verbose, \"display URL when opening\")\n\tSearchCmd.PersistentFlags().StringVarP(\n\t\t&config.Provider, \"provider\", \"p\", config.Provider, \"search provider\")\n\tSearchCmd.PersistentFlags().BoolVarP(\n\t\t&config.ListProviders, \"list-providers\", \"l\", false, \"list supported providers\")\n\tSearchCmd.PersistentFlags().StringVarP(\n\t\t&config.Binary, \"binary\", \"b\", config.Binary, \"binary to launch search URI\")\n\tSearchCmd.PersistentFlags().BoolVarP(\n\t\t&config.ServerMode, \"server\", \"s\", false, \"launch web server\")\n\tSearchCmd.PersistentFlags().IntVarP(\n\t\t&config.Port, \"port\", \"\", config.Port, \"server port\")\n\tSearchCmd.PersistentFlags().StringVarP(\n\t\t&config.Cert, \"cert\", \"c\", config.Cert, \"path to cert.pem for TLS\")\n\tSearchCmd.PersistentFlags().StringVarP(\n\t\t&config.Key, \"key\", \"k\", config.Key, \"path to key.pem for TLS\")\n}\n\n\/\/ Where all the work happens.\nfunc performCommand(cmd *cobra.Command, args []string) error {\n\tif config.DisplayVersion {\n\t\tfmt.Printf(\"%s %s\\n\", appName, version)\n\t\treturn nil\n\t}\n\n\tproviders.SetBlacklist(config.Blacklist)\n\tproviders.SetWhitelist(config.Whitelist)\n\n\tif config.ListProviders {\n\t\tfmt.Printf(providers.DisplayProviders())\n\t\treturn nil\n\t}\n\n\tif config.ServerMode {\n\t\terr := server.Run(config.Port, config.Cert, config.Key, config.Provider)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tquery := strings.Join(args, \" \")\n\n\tst, err := os.Stdin.Stat()\n\tif err != nil {\n\t\t\/\/ os.Stdin.Stat() can be unavailable on Windows.\n\t\tif runtime.GOOS != \"windows\" {\n\t\t\treturn fmt.Errorf(\"Failed to stat Stdin: %s\", err)\n\t\t}\n\t} else {\n\t\tif st.Mode()&os.ModeNamedPipe != 0 {\n\t\t\tbytes, err := ioutil.ReadAll(os.Stdin)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed to read from Stdin: %s\", err)\n\t\t\t}\n\n\t\t\tquery = strings.TrimSpace(fmt.Sprintf(\"%s %s\", query, bytes))\n\t\t}\n\t}\n\n\tif query != \"\" {\n\t\terr := providers.Search(config.Binary, config.Provider, query, config.Verbose)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t\/\/ Don't return an error, help screen is more appropriate.\n\t\tcmd.Help()\n\t}\n\n\treturn nil\n}\n<commit_msg>Print nicer error if configuration file has errors<commit_after>package cmd\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/zquestz\/s\/providers\"\n\t\"github.com\/zquestz\/s\/server\"\n)\n\nconst (\n\tappName         = \"s\"\n\tversion         = \"0.4.0\"\n\tdefaultPort     = 8080\n\tdefaultProvider = \"google\"\n)\n\n\/\/ Stores configuration data.\nvar config Config\n\n\/\/ SearchCmd is the main command for Cobra.\nvar SearchCmd = &cobra.Command{\n\tUse:   \"s <query>\",\n\tShort: \"Web search from the terminal\",\n\tLong:  `Web search from the terminal.`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\terr := performCommand(cmd, args)\n\t\tif err != nil {\n\t\t\tbail(err)\n\t\t}\n\t},\n}\n\nfunc init() {\n\terr := config.Load()\n\tif err != nil {\n\t\tbail(fmt.Errorf(\"Failed to load configuration: %s\", err))\n\t}\n\n\tprepareFlags()\n}\n\nfunc bail(err error) {\n\tfmt.Fprintf(os.Stderr, \"[Error] %s\\n\", err)\n\tos.Exit(1)\n}\n\nfunc prepareFlags() {\n\tif config.Provider == \"\" {\n\t\tconfig.Provider = defaultProvider\n\t}\n\n\tif config.Port == 0 {\n\t\tconfig.Port = defaultPort\n\t}\n\n\tSearchCmd.PersistentFlags().BoolVarP(\n\t\t&config.DisplayVersion, \"version\", \"\", false, \"display version\")\n\tSearchCmd.PersistentFlags().BoolVarP(\n\t\t&config.Verbose, \"verbose\", \"v\", config.Verbose, \"display URL when opening\")\n\tSearchCmd.PersistentFlags().StringVarP(\n\t\t&config.Provider, \"provider\", \"p\", config.Provider, \"search provider\")\n\tSearchCmd.PersistentFlags().BoolVarP(\n\t\t&config.ListProviders, \"list-providers\", \"l\", false, \"list supported providers\")\n\tSearchCmd.PersistentFlags().StringVarP(\n\t\t&config.Binary, \"binary\", \"b\", config.Binary, \"binary to launch search URI\")\n\tSearchCmd.PersistentFlags().BoolVarP(\n\t\t&config.ServerMode, \"server\", \"s\", false, \"launch web server\")\n\tSearchCmd.PersistentFlags().IntVarP(\n\t\t&config.Port, \"port\", \"\", config.Port, \"server port\")\n\tSearchCmd.PersistentFlags().StringVarP(\n\t\t&config.Cert, \"cert\", \"c\", config.Cert, \"path to cert.pem for TLS\")\n\tSearchCmd.PersistentFlags().StringVarP(\n\t\t&config.Key, \"key\", \"k\", config.Key, \"path to key.pem for TLS\")\n}\n\n\/\/ Where all the work happens.\nfunc performCommand(cmd *cobra.Command, args []string) error {\n\tif config.DisplayVersion {\n\t\tfmt.Printf(\"%s %s\\n\", appName, version)\n\t\treturn nil\n\t}\n\n\tproviders.SetBlacklist(config.Blacklist)\n\tproviders.SetWhitelist(config.Whitelist)\n\n\tif config.ListProviders {\n\t\tfmt.Printf(providers.DisplayProviders())\n\t\treturn nil\n\t}\n\n\tif config.ServerMode {\n\t\terr := server.Run(config.Port, config.Cert, config.Key, config.Provider)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tquery := strings.Join(args, \" \")\n\n\tst, err := os.Stdin.Stat()\n\tif err != nil {\n\t\t\/\/ os.Stdin.Stat() can be unavailable on Windows.\n\t\tif runtime.GOOS != \"windows\" {\n\t\t\treturn fmt.Errorf(\"Failed to stat Stdin: %s\", err)\n\t\t}\n\t} else {\n\t\tif st.Mode()&os.ModeNamedPipe != 0 {\n\t\t\tbytes, err := ioutil.ReadAll(os.Stdin)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed to read from Stdin: %s\", err)\n\t\t\t}\n\n\t\t\tquery = strings.TrimSpace(fmt.Sprintf(\"%s %s\", query, bytes))\n\t\t}\n\t}\n\n\tif query != \"\" {\n\t\terr := providers.Search(config.Binary, config.Provider, query, config.Verbose)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t\/\/ Don't return an error, help screen is more appropriate.\n\t\tcmd.Help()\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2017 Douglas Chimento <dchimento@gmail.com>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/Sirupsen\/logrus\/hooks\/syslog\"\n\t\"github.com\/gocraft\/health\"\n\t\"github.com\/gocraft\/web\"\n\t\"github.com\/spf13\/cobra\"\n\t\"io\/ioutil\"\n\t\"log\/syslog\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst eventURL = \"\/api\/v1\/event\"\nconst streamURL = \"\/api\/v1\/event\/stream\"\n\n\/\/Context for http requests\ntype Context struct {\n\teventTransporter\n}\n\nfunc handlers() *web.Router {\n\trouter := web.New(Context{}).\n\t\tMiddleware(loggerMiddleware)\n\tif config.Debug {\n\t\trouter.Middleware(web.ShowErrorsMiddleware)\n\t}\n\trouter.Middleware((*Context).initContext).\n\t\tNotFound(notFound).\n\t\tPost(eventURL, (*Context).handleEvent).\n\t\tGet(eventURL, (*Context).listEvents).\n\t\tGet(streamURL, (*Context).streamEvents)\n\treturn router\n}\n\nfunc notFound(rw web.ResponseWriter, r *web.Request) {\n\trw.WriteHeader(http.StatusNotFound)\n\tlog.Infof(\"%s not found\", r.URL.Path)\n}\n\nvar serverCmd = &cobra.Command{\n\tUse:   \"server\",\n\tShort: \"\",\n\tLong:  \"\",\n\tRun:   run,\n}\n\nfunc run(cmd *cobra.Command, args []string) {\n\tvar err error\n\tif config.Debug {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\tif config.Threads > 0 {\n\t\truntime.GOMAXPROCS(config.Threads)\n\t}\n\tdefaultEventClient = &eventClient{\n\t\tdb:        loadDSN(config.Dsn),\n\t\tgeoClient: geoClient,\n\t}\n\tlog.Debugf(\"Running %s with %s\", cmd.Name(), args)\n\tsrv := &http.Server{\n\t\tHandler:      handlers(),\n\t\tAddr:         config.BindAddr,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tReadTimeout:  10 * time.Second,\n\t}\n\tif config.Syslog != \"\" {\n\t\tif syslogHook, err = logrus_syslog.NewSyslogHook(\"tcp\", config.Syslog, syslog.LOG_LOCAL0, \"passwd-pot\"); err != nil {\n\t\t\tlog.Error(\"Unable to connect to local syslog daemon\")\n\t\t} else {\n\t\t\tlog.AddHook(syslogHook)\n\t\t}\n\t}\n\tdefaultDbEventLogger.Debug = config.Debug\n\thealthMonitor(cmd.Name())\n\tlog.Infof(\"Listing on %s\", config.BindAddr)\n\n\t\/\/websocket requests\n\tgo hub.run()\n\n\terr = srv.ListenAndServe()\n\tif err != nil {\n\t\tlog.Errorf(\"Caught error %s\", err)\n\t\tos.Exit(-1)\n\t}\n}\n\nfunc (c *Context) initContext(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {\n\tc.eventTransporter = defaultEventClient\n\tnext(rw, req)\n}\n\nfunc (c *Context) handleEvent(w web.ResponseWriter, r *web.Request) {\n\tjob := stream.NewJob(fmt.Sprintf(\"%s\", eventURL))\n\tvar event Event\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Error(err)\n\t\tjob.EventErr(\"handle_event_invalid_body\", err)\n\t\tjob.Complete(health.ValidationError)\n\t\treturn\n\t}\n\tif err = json.Unmarshal(b, &event); err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tlog.Errorf(\"Error reading %s\", err)\n\t\tjob.EventErr(\"handle_event_invalid_json\", err)\n\t\tjob.Complete(health.ValidationError)\n\t\treturn\n\t}\n\n\tif event.OriginAddr == \"\" {\n\t\tif r.Header.Get(\"X-Forwarded-For\") != \"\" {\n\t\t\tlog.Debug(\"Using RemoteAddr from  X-Forwarded-For\")\n\t\t\tevent.OriginAddr = r.Header.Get(\"X-Forwarded-For\")\n\t\t} else {\n\t\t\t\/\/IP:Port\n\t\t\tlog.Debugf(\"Using RemoteAddr as OriginAddr %s\", r.RemoteAddr)\n\t\t\tevent.OriginAddr = strings.Split(r.RemoteAddr, \":\")[0]\n\t\t}\n\n\t}\n\n\terr = c.eventTransporter.recordEvent(&event)\n\tgo c.eventTransporter.resolveGeoEvent(&event)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Errorf(\"Error writing %+v %s\", &event, err)\n\t\tjob.EventErr(\"handle_event_event_error\", err)\n\t\tjob.Complete(health.Error)\n\t\treturn\n\t}\n\tjob.Complete(health.Success)\n\tj, _ := json.Marshal(event)\n\tw.WriteHeader(http.StatusAccepted)\n\tw.Header().Add(\"Content-type\", \"application\/json\")\n\tw.Write(j)\n}\n\nfunc (c *Context) listEvents(w web.ResponseWriter, r *web.Request) {\n\tgeoEvents := c.eventTransporter.list()\n\tj, _ := json.Marshal(geoEvents)\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Add(\"Content-type\", \"application\/json\")\n\tw.Write(j)\n}\n\nfunc init() {\n\tRootCmd.AddCommand(serverCmd)\n\tserverCmd.PersistentFlags().StringVar(&config.Dsn, \"dsn\", \"postgres:\/\/postgres:@172.17.0.1\/?sslmode=disable\", \"DSN database url\")\n\tserverCmd.PersistentFlags().StringVar(&config.BindAddr, \"bind\", \"localhost:8080\", \"bind to this address:port\")\n\tserverCmd.PersistentFlags().StringVar(&config.Syslog, \"syslog\", \"\", \"use syslog server\")\n\tserverCmd.PersistentFlags().StringVar(&config.Health, \"health\", \"\", \"create health server\")\n\tserverCmd.PersistentFlags().StringVar(&config.Statsd, \"statsd\", \"\", \"push stats to statsd (localhost:8125\")\n\tserverCmd.PersistentFlags().IntVar(&config.Threads, \"threads\", 0, \"number of thread workers to use\")\n}\n<commit_msg>Allow Cors *<commit_after>\/\/ Copyright © 2017 Douglas Chimento <dchimento@gmail.com>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/Sirupsen\/logrus\/hooks\/syslog\"\n\t\"github.com\/gocraft\/health\"\n\t\"github.com\/gocraft\/web\"\n\t\"github.com\/spf13\/cobra\"\n\t\"io\/ioutil\"\n\t\"log\/syslog\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst eventURL = \"\/api\/v1\/event\"\nconst streamURL = \"\/api\/v1\/event\/stream\"\n\n\/\/Context for http requests\ntype Context struct {\n\teventTransporter\n}\n\nfunc handlers() *web.Router {\n\trouter := web.New(Context{}).\n\t\tMiddleware(loggerMiddleware).\n\t\tMiddleware(allowCors)\n\n\tif config.Debug {\n\t\trouter.Middleware(web.ShowErrorsMiddleware)\n\t}\n\trouter.Middleware((*Context).initContext).\n\t\tNotFound(notFound).\n\t\tPost(eventURL, (*Context).handleEvent).\n\t\tGet(eventURL, (*Context).listEvents).\n\t\tGet(streamURL, (*Context).streamEvents)\n\treturn router\n}\n\nfunc allowCors(w web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tnext(w, r)\n}\nfunc notFound(rw web.ResponseWriter, r *web.Request) {\n\trw.WriteHeader(http.StatusNotFound)\n\tlog.Infof(\"%s not found\", r.URL.Path)\n}\n\nvar serverCmd = &cobra.Command{\n\tUse:   \"server\",\n\tShort: \"\",\n\tLong:  \"\",\n\tRun:   run,\n}\n\nfunc run(cmd *cobra.Command, args []string) {\n\tvar err error\n\tif config.Debug {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\tif config.Threads > 0 {\n\t\truntime.GOMAXPROCS(config.Threads)\n\t}\n\tdefaultEventClient = &eventClient{\n\t\tdb:        loadDSN(config.Dsn),\n\t\tgeoClient: geoClient,\n\t}\n\tlog.Debugf(\"Running %s with %s\", cmd.Name(), args)\n\tsrv := &http.Server{\n\t\tHandler:      handlers(),\n\t\tAddr:         config.BindAddr,\n\t\tWriteTimeout: 10 * time.Second,\n\t\tReadTimeout:  10 * time.Second,\n\t}\n\tif config.Syslog != \"\" {\n\t\tif syslogHook, err = logrus_syslog.NewSyslogHook(\"tcp\", config.Syslog, syslog.LOG_LOCAL0, \"passwd-pot\"); err != nil {\n\t\t\tlog.Error(\"Unable to connect to local syslog daemon\")\n\t\t} else {\n\t\t\tlog.AddHook(syslogHook)\n\t\t}\n\t}\n\tdefaultDbEventLogger.Debug = config.Debug\n\thealthMonitor(cmd.Name())\n\tlog.Infof(\"Listing on %s\", config.BindAddr)\n\n\t\/\/websocket requests\n\tgo hub.run()\n\n\terr = srv.ListenAndServe()\n\tif err != nil {\n\t\tlog.Errorf(\"Caught error %s\", err)\n\t\tos.Exit(-1)\n\t}\n}\n\nfunc (c *Context) initContext(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {\n\tc.eventTransporter = defaultEventClient\n\tnext(rw, req)\n}\n\nfunc (c *Context) handleEvent(w web.ResponseWriter, r *web.Request) {\n\tjob := stream.NewJob(fmt.Sprintf(\"%s\", eventURL))\n\tvar event Event\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Error(err)\n\t\tjob.EventErr(\"handle_event_invalid_body\", err)\n\t\tjob.Complete(health.ValidationError)\n\t\treturn\n\t}\n\tif err = json.Unmarshal(b, &event); err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tlog.Errorf(\"Error reading %s\", err)\n\t\tjob.EventErr(\"handle_event_invalid_json\", err)\n\t\tjob.Complete(health.ValidationError)\n\t\treturn\n\t}\n\n\tif event.OriginAddr == \"\" {\n\t\tif r.Header.Get(\"X-Forwarded-For\") != \"\" {\n\t\t\tlog.Debug(\"Using RemoteAddr from  X-Forwarded-For\")\n\t\t\tevent.OriginAddr = r.Header.Get(\"X-Forwarded-For\")\n\t\t} else {\n\t\t\t\/\/IP:Port\n\t\t\tlog.Debugf(\"Using RemoteAddr as OriginAddr %s\", r.RemoteAddr)\n\t\t\tevent.OriginAddr = strings.Split(r.RemoteAddr, \":\")[0]\n\t\t}\n\n\t}\n\n\terr = c.eventTransporter.recordEvent(&event)\n\tgo c.eventTransporter.resolveGeoEvent(&event)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Errorf(\"Error writing %+v %s\", &event, err)\n\t\tjob.EventErr(\"handle_event_event_error\", err)\n\t\tjob.Complete(health.Error)\n\t\treturn\n\t}\n\tjob.Complete(health.Success)\n\tj, _ := json.Marshal(event)\n\tw.WriteHeader(http.StatusAccepted)\n\tw.Header().Add(\"Content-type\", \"application\/json\")\n\tw.Write(j)\n}\n\nfunc (c *Context) listEvents(w web.ResponseWriter, r *web.Request) {\n\tgeoEvents := c.eventTransporter.list()\n\tj, _ := json.Marshal(geoEvents)\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Add(\"Content-type\", \"application\/json\")\n\tw.Write(j)\n}\n\nfunc init() {\n\tRootCmd.AddCommand(serverCmd)\n\tserverCmd.PersistentFlags().StringVar(&config.Dsn, \"dsn\", \"postgres:\/\/postgres:@172.17.0.1\/?sslmode=disable\", \"DSN database url\")\n\tserverCmd.PersistentFlags().StringVar(&config.BindAddr, \"bind\", \"localhost:8080\", \"bind to this address:port\")\n\tserverCmd.PersistentFlags().StringVar(&config.Syslog, \"syslog\", \"\", \"use syslog server\")\n\tserverCmd.PersistentFlags().StringVar(&config.Health, \"health\", \"\", \"create health server\")\n\tserverCmd.PersistentFlags().StringVar(&config.Statsd, \"statsd\", \"\", \"push stats to statsd (localhost:8125\")\n\tserverCmd.PersistentFlags().IntVar(&config.Threads, \"threads\", 0, \"number of thread workers to use\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2015 The Kythe Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ Binary gotool extracts Kythe compilation information for Go packages named\n\/\/ by import path on the command line.  The output compilations are written\n\/\/ into an index pack directory.\npackage main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"kythe.io\/kythe\/go\/extractors\/golang\"\n\t\"kythe.io\/kythe\/go\/platform\/analysis\"\n\t\"kythe.io\/kythe\/go\/platform\/kzip\"\n\t\"kythe.io\/kythe\/go\/platform\/vfs\"\n\t\"kythe.io\/kythe\/go\/util\/flagutil\"\n\t\"kythe.io\/kythe\/go\/util\/vnameutil\"\n\n\tapb \"kythe.io\/kythe\/proto\/analysis_go_proto\"\n)\n\nvar (\n\tbc = build.Default \/\/ A shallow copy of the default build settings\n\n\tcorpus     = flag.String(\"corpus\", \"\", \"Default corpus name to use\")\n\trulesFile  = flag.String(\"rules\", \"\", \"Path to vnames.json file that maps file paths to output corpus, root, and path.\")\n\toutputPath = flag.String(\"output\", \"\", \"KZip output path\")\n\textraFiles = flag.String(\"extra_files\", \"\", \"Additional files to include in each compilation (CSV)\")\n\tbyDir      = flag.Bool(\"bydir\", false, \"Import by directory rather than import path\")\n\tkeepGoing  = flag.Bool(\"continue\", false, \"Continue past errors\")\n\tverbose    = flag.Bool(\"v\", false, \"Enable verbose logging\")\n\n\tcanonicalizePackageCorpus = flag.Bool(\"canonicalize_package_corpus\", false, \"Whether to use a package's canonical repository root URL as their corpus\")\n\n\tbuildTags flagutil.StringList\n)\n\nfunc init() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, `Usage: %s [options] <import-path>...\nExtract Kythe compilation records from Go import paths specified on the command line.\nOutput is written to a .kzip file specified by --output.\n\nOptions:\n`, filepath.Base(os.Args[0]))\n\t\tflag.PrintDefaults()\n\t}\n\n\t\/\/ Attach flags to the various parts of the go\/build context we are using.\n\t\/\/ These will override the system defaults from the environment.\n\tflag.StringVar(&bc.GOARCH, \"goarch\", bc.GOARCH, \"Go system architecture tag\")\n\tflag.StringVar(&bc.GOOS, \"goos\", bc.GOOS, \"Go operating system tag\")\n\tflag.StringVar(&bc.GOPATH, \"gopath\", bc.GOPATH, \"Go library path\")\n\tflag.StringVar(&bc.GOROOT, \"goroot\", bc.GOROOT, \"Go system root\")\n\tflag.BoolVar(&bc.CgoEnabled, \"gocgo\", bc.CgoEnabled, \"Whether to allow cgo\")\n\tflag.StringVar(&bc.Compiler, \"gocompiler\", bc.Compiler, \"Which Go compiler to use\")\n\tflag.Var(&buildTags, \"buildtags\", \"Comma-separated list of Go +build tags to enable during extraction.\")\n\n\t\/\/ TODO(fromberger): Attach flags to the build and release tags (maybe).\n}\n\nfunc maybeFatal(msg string, args ...interface{}) {\n\tlog.Printf(msg, args...)\n\tif !*keepGoing {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc maybeLog(msg string, args ...interface{}) {\n\tif *verbose {\n\t\tlog.Printf(msg, args...)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tbc.BuildTags = buildTags\n\n\tif *outputPath == \"\" {\n\t\tlog.Fatal(\"You must provide a non-empty --output path\")\n\t}\n\n\t\/\/ Rules for rewriting package and file VNames.\n\tvar rules vnameutil.Rules\n\tif *rulesFile != \"\" {\n\t\tvar err error\n\t\trules, err = vnameutil.LoadRules(*rulesFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"loading rules file: %v\", err)\n\t\t}\n\t}\n\n\tctx := context.Background()\n\text := &golang.Extractor{\n\t\tBuildContext: bc,\n\n\t\tPackageVNameOptions: golang.PackageVNameOptions{\n\t\t\tDefaultCorpus:             *corpus,\n\t\t\tRules:                     rules,\n\t\t\tCanonicalizePackageCorpus: *canonicalizePackageCorpus,\n\t\t},\n\t}\n\tif *extraFiles != \"\" {\n\t\text.ExtraFiles = strings.Split(*extraFiles, \",\")\n\t\tfor i, path := range ext.ExtraFiles {\n\t\t\tvar err error\n\t\t\text.ExtraFiles[i], err = filepath.Abs(path)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Error finding absolute path of %s: %v\", path, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tlocate := ext.Locate\n\tif *byDir {\n\t\tlocate = func(path string) ([]*golang.Package, error) {\n\t\t\tpkg, err := ext.ImportDir(path)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn []*golang.Package{pkg}, nil\n\t\t}\n\t}\n\tfor _, path := range flag.Args() {\n\t\tpkgs, err := locate(path)\n\t\tif err != nil {\n\t\t\tmaybeFatal(\"Error locating %q: %v\", path, err)\n\t\t}\n\t\tfor _, pkg := range pkgs {\n\t\t\tmaybeLog(\"Found %q in %s\", pkg.Path, pkg.BuildPackage.Dir)\n\t\t}\n\t}\n\n\tif err := ext.Extract(); err != nil {\n\t\tmaybeFatal(\"Error in extraction: %v\", err)\n\t}\n\n\tmaybeLog(\"Writing %d package(s) to %q\", len(ext.Packages), *outputPath)\n\tw, err := kzipWriter(ctx, *outputPath)\n\tif err != nil {\n\t\tmaybeFatal(\"Error creating kzip writer: %v\", err)\n\t}\n\tfor _, pkg := range ext.Packages {\n\t\tmaybeLog(\"Package %q:\\n\\t\/\/ %s\", pkg.Path, pkg.BuildPackage.Doc)\n\t\tif err := pkg.EachUnit(ctx, func(cu *apb.CompilationUnit, fetcher analysis.Fetcher) error {\n\t\t\tif _, err := w.AddUnit(cu, nil); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, ri := range cu.RequiredInput {\n\t\t\t\tfd, err := fetcher.Fetch(ri.Info.Path, ri.Info.Digest)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif _, err := w.AddFile(bytes.NewReader(fd)); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}); err != nil {\n\t\t\tmaybeFatal(\"Error writing %q: %v\", pkg.Path, err)\n\t\t}\n\t}\n\tif err := w.Close(); err != nil {\n\t\tmaybeFatal(\"Error closing output: %v\", err)\n\t}\n}\n\nfunc kzipWriter(ctx context.Context, path string) (*kzip.Writer, error) {\n\tif err := vfs.MkdirAll(ctx, filepath.Dir(path), 0755); err != nil {\n\t\tlog.Fatalf(\"Unable to create output directory: %v\", err)\n\t}\n\tf, err := vfs.Create(ctx, path)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to create output file: %v\", err)\n\t}\n\treturn kzip.NewWriteCloser(f)\n}\n<commit_msg>chore: Fixup binary comment (#4367)<commit_after>\/*\n * Copyright 2015 The Kythe Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ Binary gotool extracts Kythe compilation information for Go packages named\n\/\/ by import path on the command line.  The output compilations are written\n\/\/ into a kzip.\npackage main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"kythe.io\/kythe\/go\/extractors\/golang\"\n\t\"kythe.io\/kythe\/go\/platform\/analysis\"\n\t\"kythe.io\/kythe\/go\/platform\/kzip\"\n\t\"kythe.io\/kythe\/go\/platform\/vfs\"\n\t\"kythe.io\/kythe\/go\/util\/flagutil\"\n\t\"kythe.io\/kythe\/go\/util\/vnameutil\"\n\n\tapb \"kythe.io\/kythe\/proto\/analysis_go_proto\"\n)\n\nvar (\n\tbc = build.Default \/\/ A shallow copy of the default build settings\n\n\tcorpus     = flag.String(\"corpus\", \"\", \"Default corpus name to use\")\n\trulesFile  = flag.String(\"rules\", \"\", \"Path to vnames.json file that maps file paths to output corpus, root, and path.\")\n\toutputPath = flag.String(\"output\", \"\", \"KZip output path\")\n\textraFiles = flag.String(\"extra_files\", \"\", \"Additional files to include in each compilation (CSV)\")\n\tbyDir      = flag.Bool(\"bydir\", false, \"Import by directory rather than import path\")\n\tkeepGoing  = flag.Bool(\"continue\", false, \"Continue past errors\")\n\tverbose    = flag.Bool(\"v\", false, \"Enable verbose logging\")\n\n\tcanonicalizePackageCorpus = flag.Bool(\"canonicalize_package_corpus\", false, \"Whether to use a package's canonical repository root URL as their corpus\")\n\n\tbuildTags flagutil.StringList\n)\n\nfunc init() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, `Usage: %s [options] <import-path>...\nExtract Kythe compilation records from Go import paths specified on the command line.\nOutput is written to a .kzip file specified by --output.\n\nOptions:\n`, filepath.Base(os.Args[0]))\n\t\tflag.PrintDefaults()\n\t}\n\n\t\/\/ Attach flags to the various parts of the go\/build context we are using.\n\t\/\/ These will override the system defaults from the environment.\n\tflag.StringVar(&bc.GOARCH, \"goarch\", bc.GOARCH, \"Go system architecture tag\")\n\tflag.StringVar(&bc.GOOS, \"goos\", bc.GOOS, \"Go operating system tag\")\n\tflag.StringVar(&bc.GOPATH, \"gopath\", bc.GOPATH, \"Go library path\")\n\tflag.StringVar(&bc.GOROOT, \"goroot\", bc.GOROOT, \"Go system root\")\n\tflag.BoolVar(&bc.CgoEnabled, \"gocgo\", bc.CgoEnabled, \"Whether to allow cgo\")\n\tflag.StringVar(&bc.Compiler, \"gocompiler\", bc.Compiler, \"Which Go compiler to use\")\n\tflag.Var(&buildTags, \"buildtags\", \"Comma-separated list of Go +build tags to enable during extraction.\")\n\n\t\/\/ TODO(fromberger): Attach flags to the build and release tags (maybe).\n}\n\nfunc maybeFatal(msg string, args ...interface{}) {\n\tlog.Printf(msg, args...)\n\tif !*keepGoing {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc maybeLog(msg string, args ...interface{}) {\n\tif *verbose {\n\t\tlog.Printf(msg, args...)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tbc.BuildTags = buildTags\n\n\tif *outputPath == \"\" {\n\t\tlog.Fatal(\"You must provide a non-empty --output path\")\n\t}\n\n\t\/\/ Rules for rewriting package and file VNames.\n\tvar rules vnameutil.Rules\n\tif *rulesFile != \"\" {\n\t\tvar err error\n\t\trules, err = vnameutil.LoadRules(*rulesFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"loading rules file: %v\", err)\n\t\t}\n\t}\n\n\tctx := context.Background()\n\text := &golang.Extractor{\n\t\tBuildContext: bc,\n\n\t\tPackageVNameOptions: golang.PackageVNameOptions{\n\t\t\tDefaultCorpus:             *corpus,\n\t\t\tRules:                     rules,\n\t\t\tCanonicalizePackageCorpus: *canonicalizePackageCorpus,\n\t\t},\n\t}\n\tif *extraFiles != \"\" {\n\t\text.ExtraFiles = strings.Split(*extraFiles, \",\")\n\t\tfor i, path := range ext.ExtraFiles {\n\t\t\tvar err error\n\t\t\text.ExtraFiles[i], err = filepath.Abs(path)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Error finding absolute path of %s: %v\", path, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tlocate := ext.Locate\n\tif *byDir {\n\t\tlocate = func(path string) ([]*golang.Package, error) {\n\t\t\tpkg, err := ext.ImportDir(path)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn []*golang.Package{pkg}, nil\n\t\t}\n\t}\n\tfor _, path := range flag.Args() {\n\t\tpkgs, err := locate(path)\n\t\tif err != nil {\n\t\t\tmaybeFatal(\"Error locating %q: %v\", path, err)\n\t\t}\n\t\tfor _, pkg := range pkgs {\n\t\t\tmaybeLog(\"Found %q in %s\", pkg.Path, pkg.BuildPackage.Dir)\n\t\t}\n\t}\n\n\tif err := ext.Extract(); err != nil {\n\t\tmaybeFatal(\"Error in extraction: %v\", err)\n\t}\n\n\tmaybeLog(\"Writing %d package(s) to %q\", len(ext.Packages), *outputPath)\n\tw, err := kzipWriter(ctx, *outputPath)\n\tif err != nil {\n\t\tmaybeFatal(\"Error creating kzip writer: %v\", err)\n\t}\n\tfor _, pkg := range ext.Packages {\n\t\tmaybeLog(\"Package %q:\\n\\t\/\/ %s\", pkg.Path, pkg.BuildPackage.Doc)\n\t\tif err := pkg.EachUnit(ctx, func(cu *apb.CompilationUnit, fetcher analysis.Fetcher) error {\n\t\t\tif _, err := w.AddUnit(cu, nil); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, ri := range cu.RequiredInput {\n\t\t\t\tfd, err := fetcher.Fetch(ri.Info.Path, ri.Info.Digest)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif _, err := w.AddFile(bytes.NewReader(fd)); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}); err != nil {\n\t\t\tmaybeFatal(\"Error writing %q: %v\", pkg.Path, err)\n\t\t}\n\t}\n\tif err := w.Close(); err != nil {\n\t\tmaybeFatal(\"Error closing output: %v\", err)\n\t}\n}\n\nfunc kzipWriter(ctx context.Context, path string) (*kzip.Writer, error) {\n\tif err := vfs.MkdirAll(ctx, filepath.Dir(path), 0755); err != nil {\n\t\tlog.Fatalf(\"Unable to create output directory: %v\", err)\n\t}\n\tf, err := vfs.Create(ctx, path)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to create output file: %v\", err)\n\t}\n\treturn kzip.NewWriteCloser(f)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012-2017 the u-root Authors. All rights reserved\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Ed is a simple line-oriented editor\n\/\/\n\/\/ Synopsis:\n\/\/     dd\n\/\/\n\/\/ Description:\n\/\/\n\/\/ Options:\npackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n)\n\ntype editorArg func(Editor) error\n\nvar (\n\td                  = flag.Bool(\"d\", false, \"debug\")\n\tdebug              = func(s string, i ...interface{}) {}\n\tfail               = log.Printf\n\tf           Editor = &file{}\n\tnum                = regexp.MustCompile(\"^[0-9][0-9]*\")\n\tstartsearch        = regexp.MustCompile(\"^\/[^\/]\/\")\n\tendsearch          = regexp.MustCompile(\"^,\/[^\/]\/\")\n\teditors            = map[string]func(...editorArg) (Editor, error){\n\t\t\"text\": NewTextEditor,\n\t\t\"bin\":  NewBinEditor,\n\t}\n\tfileType = flag.String(\"t\", \"text\", \"type of file\")\n)\n\nfunc readerio(r io.Reader) editorArg {\n\treturn func(f Editor) error {\n\t\t_, err := f.Read(r, 0, 0)\n\t\treturn err\n\t}\n}\n\nfunc readFile(n string) editorArg {\n\treturn func(f Editor) error {\n\t\tr, err := os.Open(n)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := f.Read(r, 0, 0); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc main() {\n\tvar (\n\t\targs []editorArg\n\t\terr  error\n\t)\n\n\tflag.Parse()\n\n\tif *d {\n\t\tdebug = log.Printf\n\t}\n\n\te, ok := editors[*fileType]\n\tif !ok {\n\t\tflag.Usage()\n\t}\n\n\tif len(flag.Args()) == 1 {\n\t\targs = append(args, readFile(flag.Args()[0]))\n\t}\n\n\ted, err := e(args...)\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n\n\t\/\/ Now just eat the lines, and turn them into commands.\n\t\/\/ The format is a regular language.\n\t\/\/ [start][,end]command[rest of line]\n\ts := bufio.NewScanner(os.Stdin)\n\n\tfor s.Scan() {\n\t\tif err := DoCommand(ed, s.Text()); err != nil {\n\t\t\tlog.Printf(err.Error())\n\t\t}\n\t}\n}\n<commit_msg>Correct description and synopsis for ed<commit_after>\/\/ Copyright 2012-2017 the u-root Authors. All rights reserved\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ ED(1)               Unix Programmer's Manual                ED(1)\n\/\/ \n\/\/ NAME\n\/\/   ed - text editor\n\/\/\n\/\/ SYNOPSIS\n\/\/   ed [ - ] [ -d ] [ name ]\n\/\/\n\/\/ DESCRIPTION\n\/\/   Ed is the standard text editor.\n\/\/\n\/\/ OPTIONS\npackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n)\n\ntype editorArg func(Editor) error\n\nvar (\n\td                  = flag.Bool(\"d\", false, \"debug\")\n\tdebug              = func(s string, i ...interface{}) {}\n\tfail               = log.Printf\n\tf           Editor = &file{}\n\tnum                = regexp.MustCompile(\"^[0-9][0-9]*\")\n\tstartsearch        = regexp.MustCompile(\"^\/[^\/]\/\")\n\tendsearch          = regexp.MustCompile(\"^,\/[^\/]\/\")\n\teditors            = map[string]func(...editorArg) (Editor, error){\n\t\t\"text\": NewTextEditor,\n\t\t\"bin\":  NewBinEditor,\n\t}\n\tfileType = flag.String(\"t\", \"text\", \"type of file\")\n)\n\nfunc readerio(r io.Reader) editorArg {\n\treturn func(f Editor) error {\n\t\t_, err := f.Read(r, 0, 0)\n\t\treturn err\n\t}\n}\n\nfunc readFile(n string) editorArg {\n\treturn func(f Editor) error {\n\t\tr, err := os.Open(n)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := f.Read(r, 0, 0); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc main() {\n\tvar (\n\t\targs []editorArg\n\t\terr  error\n\t)\n\n\tflag.Parse()\n\n\tif *d {\n\t\tdebug = log.Printf\n\t}\n\n\te, ok := editors[*fileType]\n\tif !ok {\n\t\tflag.Usage()\n\t}\n\n\tif len(flag.Args()) == 1 {\n\t\targs = append(args, readFile(flag.Args()[0]))\n\t}\n\n\ted, err := e(args...)\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n\n\t\/\/ Now just eat the lines, and turn them into commands.\n\t\/\/ The format is a regular language.\n\t\/\/ [start][,end]command[rest of line]\n\ts := bufio.NewScanner(os.Stdin)\n\n\tfor s.Scan() {\n\t\tif err := DoCommand(ed, s.Text()); err != nil {\n\t\t\tlog.Printf(err.Error())\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\n\t\"github.com\/kylelemons\/go-rpcgen\/examples\/echo\/echoservice\"\n)\n\nvar server = flag.String(\"server\", \"localhost:9999\", \"RPC server address\")\n\nfunc TestEcho(t *testing.T) {\n\ttests := []string{\n\t\t\"this is a test\",\n\t\t\"woo, more tests\\n\",\n\t\t\"\",\n\t}\n\n\tgo main()\n\n\techo, err := echoservice.DialEchoService(*server)\n\tif err != nil {\n\t\tt.Fatalf(\"dial: %s\", err)\n\t}\n\n\tfor _, test := range tests {\n\t\tin := &echoservice.Payload{Message:&test}\n\t\tout := &echoservice.Payload{}\n\t\tif err := echo.Echo(in, out); err != nil {\n\t\t\tt.Fatalf(\"echo: %s\", err)\n\t\t}\n\t\tif out.Message == nil {\n\t\t\tt.Fatalf(\"echo: no message returned\")\n\t\t}\n\t\tif got, want := *out.Message, test; got != want {\n\t\t\tt.Errorf(\"echo(%q) = %q, want %q\", test, got, want)\n\t\t}\n\t}\n}\n<commit_msg>Added flag.Parse just in case<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\n\t\"github.com\/kylelemons\/go-rpcgen\/examples\/echo\/echoservice\"\n)\n\nvar server = flag.String(\"server\", \"localhost:9999\", \"RPC server address\")\n\nfunc TestEcho(t *testing.T) {\n\tflag.Parse()\n\n\ttests := []string{\n\t\t\"this is a test\",\n\t\t\"woo, more tests\\n\",\n\t\t\"\",\n\t}\n\n\tgo main()\n\n\techo, err := echoservice.DialEchoService(*server)\n\tif err != nil {\n\t\tt.Fatalf(\"dial: %s\", err)\n\t}\n\n\tfor _, test := range tests {\n\t\tin := &echoservice.Payload{Message:&test}\n\t\tout := &echoservice.Payload{}\n\t\tif err := echo.Echo(in, out); err != nil {\n\t\t\tt.Fatalf(\"echo: %s\", err)\n\t\t}\n\t\tif out.Message == nil {\n\t\t\tt.Fatalf(\"echo: no message returned\")\n\t\t}\n\t\tif got, want := *out.Message, test; got != want {\n\t\t\tt.Errorf(\"echo(%q) = %q, want %q\", test, got, want)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package oauth2Utils\n\nimport (\n\t\"encoding\/base64\"\n\t\"github.com\/RangelReale\/osin\"\n\t\"github.com\/astaxie\/beego\/context\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t. \"github.com\/francoishill\/goangi2\/utils\/cookieUtils\"\n)\n\nconst (\n\tcOSIN_ACCESS_OUTPUT_ACCESS_TOKEN_MAP_KEY         = \"access_token\"\n\tcSCOPE_ALL_SCCOPES_FOR_WEB_PASWORD_AUTHENTICATED = \"all_web_pwd\"\n)\n\ntype StringPredicate func(string) bool\n\nvar OsinServerObject *osin.Server\n\ntype IExpectedUser interface {\n\tGetRands() string\n\tGetPassword() string\n\tGetId() int64\n\tIAmAUser()\n}\n\ntype iAuthUserProvider interface {\n\tDoVerifyUser(userName, password string) (bool, IExpectedUser) \/\/This can handle both login\/register\n}\n\nfunc checkError(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc InjectCodeIntoFormIfWasPassedViaAuthorizationHeader(request *http.Request) {\n\tauthorizationHeader := request.Header.Get(\"Authorization\")\n\taccessTokenFromAuthHeader := \"\"\n\tif strings.HasPrefix(authorizationHeader, \"Bearer \") {\n\t\t\/\/This means if the \"code\" was set in the get\/set form it will be overwritten if we use the Authorization header\n\t\taccessTokenFromAuthHeader = authorizationHeader[7:]\n\t\trequest.ParseForm()\n\t\trequest.Form.Set(\"code\", accessTokenFromAuthHeader)\n\t}\n}\n\nfunc OverwriteOsinResponseErrorWithOwn(osinResponse *osin.Response) {\n\terrKey, ok := osinResponse.Output[\"error\"].(string)\n\tif ok {\n\t\tif errKey == osin.E_INVALID_REQUEST {\n\t\t\tosinResponse.SetError(errKey, errorMapKeys[errKey])\n\t\t}\n\t}\n}\n\nfunc OverwriteOsinResponseErrorWithOwn_SpecifyErrorKey(osinResponse *osin.Response, errorKey string) {\n\tosinResponse.SetError(errorKey, errorMapKeys[errorKey])\n}\n\nfunc GetAuthorizedContextFromAccessToken(osinResponse *osin.Response, ctx *context.Context) *AuthorizedContext {\n\tInjectCodeIntoFormIfWasPassedViaAuthorizationHeader(ctx.Request)\n\n\tvar usr IExpectedUser\n\tvar castedToUserType bool\n\n\tir := OsinServerObject.HandleInfoRequest(osinResponse, ctx.Request)\n\tif ir == nil {\n\t\tpanic(createOsinAuthorizeError(E_INVALID_AUTH_DATA, errorMapKeys[E_INVALID_AUTH_DATA]))\n\t}\n\n\tif ir.AccessData.UserData == nil {\n\t\tpanic(createOsinAuthorizeError(E_ACCESS_DATA_MISSING_USER, errorMapKeys[E_ACCESS_DATA_MISSING_USER]+\"(1)\"))\n\t}\n\tif strings.Trim(ir.AccessData.AccessToken, \" \") == \"\" {\n\t\tpanic(createOsinAuthorizeError(E_ACCESS_DATA_MISSING_USER, errorMapKeys[E_ACCESS_DATA_MISSING_USER]+\"(2)\"))\n\t}\n\tusr, castedToUserType = ir.AccessData.UserData.(IExpectedUser)\n\tif !castedToUserType {\n\t\tpanic(createOsinAuthorizeError(E_ACCESS_DATA_MISSING_USER, errorMapKeys[E_ACCESS_DATA_MISSING_USER]+\"(3)\"))\n\t}\n\n\treturn CreateAuthorizedContext(usr, ir.AccessData.Scope, ir.AccessData.AccessToken)\n}\n\nfunc CheckRequiredScopeSatisfied(responseWriter http.ResponseWriter, authorizedScope string, functionToCheckRequiredScope StringPredicate) {\n\tif authorizedScope == cSCOPE_ALL_SCCOPES_FOR_WEB_PASWORD_AUTHENTICATED {\n\t\treturn\n\t}\n\n\tif !functionToCheckRequiredScope(authorizedScope) {\n\t\tpanic(createOsinAuthorizeError(E_INSUFFICIENT_SCOPE, errorMapKeys[E_INSUFFICIENT_SCOPE]))\n\t}\n}\n\nfunc ServeAccessTokenWithRouter(ctx *context.Context) {\n\tw := ctx.ResponseWriter\n\tr := ctx.Request\n\n\tInjectCodeIntoFormIfWasPassedViaAuthorizationHeader(r)\n\n\tresp := OsinServerObject.NewResponse()\n\tdefer resp.Close()\n\n\tif ir := OsinServerObject.HandleInfoRequest(resp, r); ir != nil {\n\t\tOsinServerObject.FinishInfoRequest(resp, r, ir)\n\t}\n\n\tif resp.IsError {\n\t\tOverwriteOsinResponseErrorWithOwn(resp)\n\t}\n\tosin.OutputJSON(resp, w, r)\n}\n\nfunc setExpirationForAccessRequest(accessRequest *osin.AccessRequest) {\n\taccessRequest.Expiration = 60 * 60 * 24 * 365 * 10 \/\/Ten years\n\t\/\/accessRequest.Expiration = 60 * 60 * 24 * 365 * 1 \/\/One year\n\t\/\/ accessRequest.Expiration = 60 * 60 * 24 \/\/One day\n\t\/\/beego.Warning(\"Currently hardcoded the access token expiration to one year, is this correct?\")\n}\n\nfunc ExtractAccessTokenFromSuccessfulResponseData(responseData osin.ResponseData) (string, bool) {\n\tif token, ok := responseData[cOSIN_ACCESS_OUTPUT_ACCESS_TOKEN_MAP_KEY]; ok {\n\t\tif stringToken, ok := token.(string); ok {\n\t\t\treturn stringToken, true\n\t\t}\n\t}\n\n\treturn \"\", false\n}\n\ntype outputHandlerFunc func(ctx *context.Context) bool\n\nfunc replaceHeadersInlineForWebClient(ctx *context.Context, cookieSecurityContext *CookieSecurityContext) {\n\tctx.Request.Form.Del(\"client\")\n\n\tbasicAuthorizationToken := base64.StdEncoding.EncodeToString([]byte(cookieSecurityContext.WebOauth2ClientId + \":\" + cookieSecurityContext.WebOauth2ClientSecret))\n\tctx.Request.Header.Set(\"Authorization\", \"Basic \"+basicAuthorizationToken)\n\n\tctx.Request.Form.Set(\"grant_type\", \"password\")\n\tctx.Request.Form.Set(\"scope\", cSCOPE_ALL_SCCOPES_FOR_WEB_PASWORD_AUTHENTICATED)\n}\n\nfunc AuthorizeAndServeNewAccessTokenWithRouter(ctx *context.Context, cookieSecurityContext *CookieSecurityContext, authUserProvider iAuthUserProvider, setCookies bool, successfulOutputHandler outputHandlerFunc) {\n\tresp := OsinServerObject.NewResponse()\n\tdefer resp.Close()\n\n\tr := ctx.Request\n\tw := ctx.ResponseWriter\n\n\tisWebClient := ctx.Request.Form.Get(\"client\") == \"web\"\n\n\tif isWebClient {\n\t\treplaceHeadersInlineForWebClient(ctx, cookieSecurityContext)\n\t}\n\n\tvar userId int64\n\n\tar := OsinServerObject.HandleAccessRequest(resp, r)\n\tif ar != nil {\n\t\tswitch ar.Type {\n\t\t\/*case osin.AUTHORIZATION_CODE:\n\t\tar.Authorized = true*\/\n\t\tcase osin.REFRESH_TOKEN:\n\t\t\tar.Authorized = true\n\t\t\tsetExpirationForAccessRequest(ar)\n\t\tcase osin.PASSWORD:\n\t\t\tvar tmpUser IExpectedUser\n\t\t\tar.Authorized, tmpUser = authUserProvider.DoVerifyUser(ar.Username, ar.Password)\n\t\t\tif !ar.Authorized {\n\t\t\t\tOverwriteOsinResponseErrorWithOwn_SpecifyErrorKey(resp, E_EMAIL_DOES_NOT_EXIST_OR_PASSWORD_INCORRECT)\n\t\t\t} else {\n\t\t\t\tar.UserData = tmpUser\n\t\t\t\tuserId = tmpUser.GetId()\n\t\t\t}\n\t\t\tsetExpirationForAccessRequest(ar)\n\n\t\t\t\/*case osin.CLIENT_CREDENTIALS:\n\t\t\tar.Authorized = true*\/\n\t\t}\n\t\tOsinServerObject.FinishAccessRequest(resp, r, ar)\n\t}\n\n\tif resp.IsError {\n\t\tif resp.InternalError != nil {\n\t\t\tOverwriteOsinResponseErrorWithOwn(resp)\n\t\t}\n\n\t\tresp.ErrorStatusCode = 401\n\t\tresp.StatusCode = 401\n\t} else {\n\t\tresp.Output[\"user_id\"] = userId\n\t\tresp.Output[\"success\"] = true\n\t}\n\n\tif setCookies && !resp.IsError {\n\t\tif accessToken, ok := ExtractAccessTokenFromSuccessfulResponseData(resp.Output); ok {\n\t\t\tif ar != nil && ar.UserData != nil {\n\t\t\t\tif usr, ok := ar.UserData.(IExpectedUser); ok {\n\t\t\t\t\tSetUserCookies(ctx, usr.GetId())\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tSetEncryptedAccessTokenInCookie(ctx, accessToken)\n\t\t}\n\t}\n\n\tif successfulOutputHandler != nil {\n\t\tif handledOutput := successfulOutputHandler(ctx); handledOutput {\n\t\t\treturn\n\t\t}\n\t}\n\n\terr := osin.OutputJSON(resp, w, r)\n\tcheckError(err)\n}\n\nfunc InitOsinServerObject() {\n\tsconfig := osin.NewServerConfig()\n\n\tsconfig.AllowGetAccessRequest = false\n\tsconfig.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{osin.CODE, osin.TOKEN}\n\tsconfig.AllowedAccessTypes = osin.AllowedAccessType{\n\t\t\/\/ osin.AUTHORIZATION_CODE,\n\t\tosin.REFRESH_TOKEN,\n\t\tosin.PASSWORD,\n\t\t\/\/ osin.CLIENT_CREDENTIALS,\n\t}\n\tOsinServerObject = osin.NewServer(sconfig, NewOAuth2Storage())\n}\n<commit_msg>Added default osin `sconfig.ErrorStatusCode = 401`.<commit_after>package oauth2Utils\n\nimport (\n\t\"encoding\/base64\"\n\t\"github.com\/RangelReale\/osin\"\n\t\"github.com\/astaxie\/beego\/context\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t. \"github.com\/francoishill\/goangi2\/utils\/cookieUtils\"\n)\n\nconst (\n\tcOSIN_ACCESS_OUTPUT_ACCESS_TOKEN_MAP_KEY         = \"access_token\"\n\tcSCOPE_ALL_SCCOPES_FOR_WEB_PASWORD_AUTHENTICATED = \"all_web_pwd\"\n)\n\ntype StringPredicate func(string) bool\n\nvar OsinServerObject *osin.Server\n\ntype IExpectedUser interface {\n\tGetRands() string\n\tGetPassword() string\n\tGetId() int64\n\tIAmAUser()\n}\n\ntype iAuthUserProvider interface {\n\tDoVerifyUser(userName, password string) (bool, IExpectedUser) \/\/This can handle both login\/register\n}\n\nfunc checkError(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc InjectCodeIntoFormIfWasPassedViaAuthorizationHeader(request *http.Request) {\n\tauthorizationHeader := request.Header.Get(\"Authorization\")\n\taccessTokenFromAuthHeader := \"\"\n\tif strings.HasPrefix(authorizationHeader, \"Bearer \") {\n\t\t\/\/This means if the \"code\" was set in the get\/set form it will be overwritten if we use the Authorization header\n\t\taccessTokenFromAuthHeader = authorizationHeader[7:]\n\t\trequest.ParseForm()\n\t\trequest.Form.Set(\"code\", accessTokenFromAuthHeader)\n\t}\n}\n\nfunc OverwriteOsinResponseErrorWithOwn(osinResponse *osin.Response) {\n\terrKey, ok := osinResponse.Output[\"error\"].(string)\n\tif ok {\n\t\tif errKey == osin.E_INVALID_REQUEST {\n\t\t\tosinResponse.SetError(errKey, errorMapKeys[errKey])\n\t\t}\n\t}\n}\n\nfunc OverwriteOsinResponseErrorWithOwn_SpecifyErrorKey(osinResponse *osin.Response, errorKey string) {\n\tosinResponse.SetError(errorKey, errorMapKeys[errorKey])\n}\n\nfunc GetAuthorizedContextFromAccessToken(osinResponse *osin.Response, ctx *context.Context) *AuthorizedContext {\n\tInjectCodeIntoFormIfWasPassedViaAuthorizationHeader(ctx.Request)\n\n\tvar usr IExpectedUser\n\tvar castedToUserType bool\n\n\tir := OsinServerObject.HandleInfoRequest(osinResponse, ctx.Request)\n\tif ir == nil {\n\t\tpanic(createOsinAuthorizeError(E_INVALID_AUTH_DATA, errorMapKeys[E_INVALID_AUTH_DATA]))\n\t}\n\n\tif ir.AccessData.UserData == nil {\n\t\tpanic(createOsinAuthorizeError(E_ACCESS_DATA_MISSING_USER, errorMapKeys[E_ACCESS_DATA_MISSING_USER]+\"(1)\"))\n\t}\n\tif strings.Trim(ir.AccessData.AccessToken, \" \") == \"\" {\n\t\tpanic(createOsinAuthorizeError(E_ACCESS_DATA_MISSING_USER, errorMapKeys[E_ACCESS_DATA_MISSING_USER]+\"(2)\"))\n\t}\n\tusr, castedToUserType = ir.AccessData.UserData.(IExpectedUser)\n\tif !castedToUserType {\n\t\tpanic(createOsinAuthorizeError(E_ACCESS_DATA_MISSING_USER, errorMapKeys[E_ACCESS_DATA_MISSING_USER]+\"(3)\"))\n\t}\n\n\treturn CreateAuthorizedContext(usr, ir.AccessData.Scope, ir.AccessData.AccessToken)\n}\n\nfunc CheckRequiredScopeSatisfied(responseWriter http.ResponseWriter, authorizedScope string, functionToCheckRequiredScope StringPredicate) {\n\tif authorizedScope == cSCOPE_ALL_SCCOPES_FOR_WEB_PASWORD_AUTHENTICATED {\n\t\treturn\n\t}\n\n\tif !functionToCheckRequiredScope(authorizedScope) {\n\t\tpanic(createOsinAuthorizeError(E_INSUFFICIENT_SCOPE, errorMapKeys[E_INSUFFICIENT_SCOPE]))\n\t}\n}\n\nfunc ServeAccessTokenWithRouter(ctx *context.Context) {\n\tw := ctx.ResponseWriter\n\tr := ctx.Request\n\n\tInjectCodeIntoFormIfWasPassedViaAuthorizationHeader(r)\n\n\tresp := OsinServerObject.NewResponse()\n\tdefer resp.Close()\n\n\tif ir := OsinServerObject.HandleInfoRequest(resp, r); ir != nil {\n\t\tOsinServerObject.FinishInfoRequest(resp, r, ir)\n\t}\n\n\tif resp.IsError {\n\t\tOverwriteOsinResponseErrorWithOwn(resp)\n\t}\n\tosin.OutputJSON(resp, w, r)\n}\n\nfunc setExpirationForAccessRequest(accessRequest *osin.AccessRequest) {\n\taccessRequest.Expiration = 60 * 60 * 24 * 365 * 10 \/\/Ten years\n\t\/\/accessRequest.Expiration = 60 * 60 * 24 * 365 * 1 \/\/One year\n\t\/\/ accessRequest.Expiration = 60 * 60 * 24 \/\/One day\n\t\/\/beego.Warning(\"Currently hardcoded the access token expiration to one year, is this correct?\")\n}\n\nfunc ExtractAccessTokenFromSuccessfulResponseData(responseData osin.ResponseData) (string, bool) {\n\tif token, ok := responseData[cOSIN_ACCESS_OUTPUT_ACCESS_TOKEN_MAP_KEY]; ok {\n\t\tif stringToken, ok := token.(string); ok {\n\t\t\treturn stringToken, true\n\t\t}\n\t}\n\n\treturn \"\", false\n}\n\ntype outputHandlerFunc func(ctx *context.Context) bool\n\nfunc replaceHeadersInlineForWebClient(ctx *context.Context, cookieSecurityContext *CookieSecurityContext) {\n\tctx.Request.Form.Del(\"client\")\n\n\tbasicAuthorizationToken := base64.StdEncoding.EncodeToString([]byte(cookieSecurityContext.WebOauth2ClientId + \":\" + cookieSecurityContext.WebOauth2ClientSecret))\n\tctx.Request.Header.Set(\"Authorization\", \"Basic \"+basicAuthorizationToken)\n\n\tctx.Request.Form.Set(\"grant_type\", \"password\")\n\tctx.Request.Form.Set(\"scope\", cSCOPE_ALL_SCCOPES_FOR_WEB_PASWORD_AUTHENTICATED)\n}\n\nfunc AuthorizeAndServeNewAccessTokenWithRouter(ctx *context.Context, cookieSecurityContext *CookieSecurityContext, authUserProvider iAuthUserProvider, setCookies bool, successfulOutputHandler outputHandlerFunc) {\n\tresp := OsinServerObject.NewResponse()\n\tdefer resp.Close()\n\n\tr := ctx.Request\n\tw := ctx.ResponseWriter\n\n\tisWebClient := ctx.Request.Form.Get(\"client\") == \"web\"\n\n\tif isWebClient {\n\t\treplaceHeadersInlineForWebClient(ctx, cookieSecurityContext)\n\t}\n\n\tvar userId int64\n\n\tar := OsinServerObject.HandleAccessRequest(resp, r)\n\tif ar != nil {\n\t\tswitch ar.Type {\n\t\t\/*case osin.AUTHORIZATION_CODE:\n\t\tar.Authorized = true*\/\n\t\tcase osin.REFRESH_TOKEN:\n\t\t\tar.Authorized = true\n\t\t\tsetExpirationForAccessRequest(ar)\n\t\tcase osin.PASSWORD:\n\t\t\tvar tmpUser IExpectedUser\n\t\t\tar.Authorized, tmpUser = authUserProvider.DoVerifyUser(ar.Username, ar.Password)\n\t\t\tif !ar.Authorized {\n\t\t\t\tOverwriteOsinResponseErrorWithOwn_SpecifyErrorKey(resp, E_EMAIL_DOES_NOT_EXIST_OR_PASSWORD_INCORRECT)\n\t\t\t} else {\n\t\t\t\tar.UserData = tmpUser\n\t\t\t\tuserId = tmpUser.GetId()\n\t\t\t}\n\t\t\tsetExpirationForAccessRequest(ar)\n\n\t\t\t\/*case osin.CLIENT_CREDENTIALS:\n\t\t\tar.Authorized = true*\/\n\t\t}\n\t\tOsinServerObject.FinishAccessRequest(resp, r, ar)\n\t}\n\n\tif resp.IsError {\n\t\tif resp.InternalError != nil {\n\t\t\tOverwriteOsinResponseErrorWithOwn(resp)\n\t\t}\n\n\t\tresp.ErrorStatusCode = 401\n\t\tresp.StatusCode = 401\n\t} else {\n\t\tresp.Output[\"user_id\"] = userId\n\t\tresp.Output[\"success\"] = true\n\t}\n\n\tif setCookies && !resp.IsError {\n\t\tif accessToken, ok := ExtractAccessTokenFromSuccessfulResponseData(resp.Output); ok {\n\t\t\tif ar != nil && ar.UserData != nil {\n\t\t\t\tif usr, ok := ar.UserData.(IExpectedUser); ok {\n\t\t\t\t\tSetUserCookies(ctx, usr.GetId())\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tSetEncryptedAccessTokenInCookie(ctx, accessToken)\n\t\t}\n\t}\n\n\tif successfulOutputHandler != nil {\n\t\tif handledOutput := successfulOutputHandler(ctx); handledOutput {\n\t\t\treturn\n\t\t}\n\t}\n\n\terr := osin.OutputJSON(resp, w, r)\n\tcheckError(err)\n}\n\nfunc InitOsinServerObject() {\n\tsconfig := osin.NewServerConfig()\n\n\tsconfig.AllowGetAccessRequest = false\n\tsconfig.AllowedAuthorizeTypes = osin.AllowedAuthorizeType{osin.CODE, osin.TOKEN}\n\tsconfig.AllowedAccessTypes = osin.AllowedAccessType{\n\t\t\/\/ osin.AUTHORIZATION_CODE,\n\t\tosin.REFRESH_TOKEN,\n\t\tosin.PASSWORD,\n\t\t\/\/ osin.CLIENT_CREDENTIALS,\n\t}\n\tsconfig.ErrorStatusCode = 401\n\tOsinServerObject = osin.NewServer(sconfig, NewOAuth2Storage())\n}\n<|endoftext|>"}
{"text":"<commit_before>package bongo\n\nimport (\n\t\"errors\"\n\t\/\/ \"fmt\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\t\"time\"\n\t\/\/ \"math\"\n\t\"strings\"\n)\n\ntype BeforeSaveHook interface {\n\tBeforeSave(*Collection) error\n}\n\ntype AfterSaveHook interface {\n\tAfterSave(*Collection) error\n}\n\ntype BeforeDeleteHook interface {\n\tBeforeDelete(*Collection) error\n}\n\ntype AfterDeleteHook interface {\n\tAfterDelete(*Collection) error\n}\n\ntype AfterFindHook interface {\n\tAfterFind(*Collection) error\n}\n\ntype ValidateHook interface {\n\tValidate(*Collection) []error\n}\n\ntype ValidationError struct {\n\tErrors []error\n}\n\ntype TimeTracker interface {\n\tSetCreated(time.Time)\n\tSetModified(time.Time)\n}\n\ntype Document interface {\n\tGetId() bson.ObjectId\n\tSetId(bson.ObjectId)\n}\n\ntype CascadingDocument interface {\n\tGetCascade(*Collection) []*CascadeConfig\n}\n\nfunc (v *ValidationError) Error() string {\n\terrs := make([]string, len(v.Errors))\n\n\tfor i, e := range v.Errors {\n\t\terrs[i] = e.Error()\n\t}\n\treturn \"Validation failed. (\" + strings.Join(errs, \", \") + \")\"\n}\n\ntype Collection struct {\n\tName       string\n\tDatabase   string\n\tContext    *Context\n\tConnection *Connection\n}\n\ntype NewTracker interface {\n\tSetIsNew(bool)\n\tIsNew() bool\n}\n\ntype DocumentNotFoundError struct{}\n\nfunc (d DocumentNotFoundError) Error() string {\n\treturn \"Document not found\"\n}\n\n\/\/ Collection ...\nfunc (c *Collection) Collection() *mgo.Collection {\n\treturn c.Connection.Session.DB(c.Database).C(c.Name)\n}\n\n\/\/ CollectionOnSession ...\nfunc (c *Collection) collectionOnSession(sess *mgo.Session) *mgo.Collection {\n\treturn sess.DB(c.Database).C(c.Name)\n}\n\nfunc (c *Collection) PreSave(doc Document) error {\n\t\/\/ Validate?\n\tif validator, ok := doc.(ValidateHook); ok {\n\t\terrs := validator.Validate(c)\n\n\t\tif len(errs) > 0 {\n\t\t\treturn &ValidationError{errs}\n\t\t}\n\t}\n\n\tif hook, ok := doc.(BeforeSaveHook); ok {\n\t\terr := hook.BeforeSave(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *Collection) Save(doc Document) error {\n\tvar err error\n\tsess := c.Connection.Session.Clone()\n\tdefer sess.Close()\n\n\t\/\/ Per mgo's recommendation, create a clone of the session so there is no blocking\n\tcol := c.collectionOnSession(sess)\n\n\terr = c.PreSave(doc)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ If the model implements the NewTracker interface, we'll use that to determine newness. Otherwise always assume it's new\n\n\tisNew := true\n\tif newt, ok := doc.(NewTracker); ok {\n\t\tisNew = newt.IsNew()\n\t}\n\n\t\/\/ Add created\/modified time. Also set on the model itself if it has those fields.\n\tnow := time.Now()\n\n\tif tt, ok := doc.(TimeTracker); ok {\n\t\tif isNew {\n\t\t\ttt.SetCreated(now)\n\t\t}\n\t\ttt.SetModified(now)\n\t}\n\n\tgo CascadeSave(c, doc)\n\n\tid := doc.GetId()\n\n\tif !isNew && !id.Valid() {\n\t\treturn errors.New(\"New tracker says this document isn't new but there is no valid Id field\")\n\t}\n\n\tif isNew && !id.Valid() {\n\t\t\/\/ Generate an Id\n\t\tid = bson.NewObjectId()\n\t\tdoc.SetId(id)\n\t}\n\n\t_, err = col.UpsertId(id, doc)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif hook, ok := doc.(AfterSaveHook); ok {\n\t\terr = hook.AfterSave(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ We saved it, no longer new\n\tif newt, ok := doc.(NewTracker); ok {\n\t\tnewt.SetIsNew(false)\n\t}\n\n\treturn nil\n}\n\nfunc (c *Collection) FindById(id bson.ObjectId, doc interface{}) error {\n\n\terr := c.Collection().FindId(id).One(doc)\n\n\t\/\/ Handle errors coming from mgo - we want to convert it to a DocumentNotFoundError so people can figure out\n\t\/\/ what the error type is without looking at the text\n\tif err != nil {\n\t\tif err.Error() == \"not found\" {\n\t\t\treturn &DocumentNotFoundError{}\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif hook, ok := doc.(AfterFindHook); ok {\n\t\terr = hook.AfterFind(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ We retrieved it, so set new to false\n\tif newt, ok := doc.(NewTracker); ok {\n\t\tnewt.SetIsNew(false)\n\t}\n\treturn nil\n}\n\n\/\/ This doesn't actually do any DB interaction, it just creates the result set so we can\n\/\/ start looping through on the iterator\nfunc (c *Collection) Find(query interface{}) *ResultSet {\n\tcol := c.Collection()\n\n\t\/\/ Count for testing\n\tq := col.Find(query)\n\n\tresultset := new(ResultSet)\n\n\tresultset.Query = q\n\tresultset.Params = query\n\tresultset.Collection = c\n\n\treturn resultset\n}\n\nfunc (c *Collection) FindOne(query interface{}, doc interface{}) error {\n\n\t\/\/ Now run a find\n\tresults := c.Find(query)\n\tresults.Query.Limit(1)\n\n\thasNext := results.Next(doc)\n\n\tif !hasNext {\n\t\t\/\/ There could have been an error fetching the next one, which would set the Error property on the resultset\n\t\tif results.Error != nil {\n\t\t\treturn results.Error\n\t\t} else {\n\t\t\treturn &DocumentNotFoundError{}\n\t\t}\n\n\t}\n\n\tif newt, ok := doc.(NewTracker); ok {\n\t\tnewt.SetIsNew(false)\n\t}\n\n\treturn nil\n}\n\nfunc (c *Collection) DeleteDocument(doc Document) error {\n\tvar err error\n\t\/\/ Create a new session per mgo's suggestion to avoid blocking\n\tsess := c.Connection.Session.Clone()\n\tdefer sess.Close()\n\tcol := c.collectionOnSession(sess)\n\n\tif hook, ok := doc.(BeforeDeleteHook); ok {\n\t\terr := hook.BeforeDelete(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = col.Remove(bson.M{\"_id\": doc.GetId()})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo CascadeDelete(c, doc)\n\n\tif hook, ok := doc.(AfterDeleteHook); ok {\n\t\terr = hook.AfterDelete(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n\n}\n\n\/\/ Convenience method which just delegates to mgo. Note that hooks are NOT run\nfunc (c *Collection) Delete(query bson.M) (*mgo.ChangeInfo, error) {\n\tsess := c.Connection.Session.Clone()\n\tdefer sess.Close()\n\tcol := c.collectionOnSession(sess)\n\treturn col.RemoveAll(query)\n}\n\n\/\/ Convenience method which just delegates to mgo. Note that hooks are NOT run\nfunc (c *Collection) DeleteOne(query bson.M) error {\n\tsess := c.Connection.Session.Clone()\n\tdefer sess.Close()\n\tcol := c.collectionOnSession(sess)\n\treturn col.Remove(query)\n}\n<commit_msg>Replaced error with the error from the `mgo` package<commit_after>package bongo\n\nimport (\n\t\"errors\"\n\t\/\/ \"fmt\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\t\"time\"\n\t\/\/ \"math\"\n\t\"strings\"\n)\n\ntype BeforeSaveHook interface {\n\tBeforeSave(*Collection) error\n}\n\ntype AfterSaveHook interface {\n\tAfterSave(*Collection) error\n}\n\ntype BeforeDeleteHook interface {\n\tBeforeDelete(*Collection) error\n}\n\ntype AfterDeleteHook interface {\n\tAfterDelete(*Collection) error\n}\n\ntype AfterFindHook interface {\n\tAfterFind(*Collection) error\n}\n\ntype ValidateHook interface {\n\tValidate(*Collection) []error\n}\n\ntype ValidationError struct {\n\tErrors []error\n}\n\ntype TimeTracker interface {\n\tSetCreated(time.Time)\n\tSetModified(time.Time)\n}\n\ntype Document interface {\n\tGetId() bson.ObjectId\n\tSetId(bson.ObjectId)\n}\n\ntype CascadingDocument interface {\n\tGetCascade(*Collection) []*CascadeConfig\n}\n\nfunc (v *ValidationError) Error() string {\n\terrs := make([]string, len(v.Errors))\n\n\tfor i, e := range v.Errors {\n\t\terrs[i] = e.Error()\n\t}\n\treturn \"Validation failed. (\" + strings.Join(errs, \", \") + \")\"\n}\n\ntype Collection struct {\n\tName       string\n\tDatabase   string\n\tContext    *Context\n\tConnection *Connection\n}\n\ntype NewTracker interface {\n\tSetIsNew(bool)\n\tIsNew() bool\n}\n\ntype DocumentNotFoundError struct{}\n\nfunc (d DocumentNotFoundError) Error() string {\n\treturn \"Document not found\"\n}\n\n\/\/ Collection ...\nfunc (c *Collection) Collection() *mgo.Collection {\n\treturn c.Connection.Session.DB(c.Database).C(c.Name)\n}\n\n\/\/ CollectionOnSession ...\nfunc (c *Collection) collectionOnSession(sess *mgo.Session) *mgo.Collection {\n\treturn sess.DB(c.Database).C(c.Name)\n}\n\nfunc (c *Collection) PreSave(doc Document) error {\n\t\/\/ Validate?\n\tif validator, ok := doc.(ValidateHook); ok {\n\t\terrs := validator.Validate(c)\n\n\t\tif len(errs) > 0 {\n\t\t\treturn &ValidationError{errs}\n\t\t}\n\t}\n\n\tif hook, ok := doc.(BeforeSaveHook); ok {\n\t\terr := hook.BeforeSave(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *Collection) Save(doc Document) error {\n\tvar err error\n\tsess := c.Connection.Session.Clone()\n\tdefer sess.Close()\n\n\t\/\/ Per mgo's recommendation, create a clone of the session so there is no blocking\n\tcol := c.collectionOnSession(sess)\n\n\terr = c.PreSave(doc)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ If the model implements the NewTracker interface, we'll use that to determine newness. Otherwise always assume it's new\n\n\tisNew := true\n\tif newt, ok := doc.(NewTracker); ok {\n\t\tisNew = newt.IsNew()\n\t}\n\n\t\/\/ Add created\/modified time. Also set on the model itself if it has those fields.\n\tnow := time.Now()\n\n\tif tt, ok := doc.(TimeTracker); ok {\n\t\tif isNew {\n\t\t\ttt.SetCreated(now)\n\t\t}\n\t\ttt.SetModified(now)\n\t}\n\n\tgo CascadeSave(c, doc)\n\n\tid := doc.GetId()\n\n\tif !isNew && !id.Valid() {\n\t\treturn errors.New(\"New tracker says this document isn't new but there is no valid Id field\")\n\t}\n\n\tif isNew && !id.Valid() {\n\t\t\/\/ Generate an Id\n\t\tid = bson.NewObjectId()\n\t\tdoc.SetId(id)\n\t}\n\n\t_, err = col.UpsertId(id, doc)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif hook, ok := doc.(AfterSaveHook); ok {\n\t\terr = hook.AfterSave(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ We saved it, no longer new\n\tif newt, ok := doc.(NewTracker); ok {\n\t\tnewt.SetIsNew(false)\n\t}\n\n\treturn nil\n}\n\nfunc (c *Collection) FindById(id bson.ObjectId, doc interface{}) error {\n\n\terr := c.Collection().FindId(id).One(doc)\n\n\t\/\/ Handle errors coming from mgo - we want to convert it to a DocumentNotFoundError so people can figure out\n\t\/\/ what the error type is without looking at the text\n\tif err != nil {\n\t\tif err == mgo.ErrNotFound {\n\t\t\treturn &DocumentNotFoundError{}\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif hook, ok := doc.(AfterFindHook); ok {\n\t\terr = hook.AfterFind(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ We retrieved it, so set new to false\n\tif newt, ok := doc.(NewTracker); ok {\n\t\tnewt.SetIsNew(false)\n\t}\n\treturn nil\n}\n\n\/\/ This doesn't actually do any DB interaction, it just creates the result set so we can\n\/\/ start looping through on the iterator\nfunc (c *Collection) Find(query interface{}) *ResultSet {\n\tcol := c.Collection()\n\n\t\/\/ Count for testing\n\tq := col.Find(query)\n\n\tresultset := new(ResultSet)\n\n\tresultset.Query = q\n\tresultset.Params = query\n\tresultset.Collection = c\n\n\treturn resultset\n}\n\nfunc (c *Collection) FindOne(query interface{}, doc interface{}) error {\n\n\t\/\/ Now run a find\n\tresults := c.Find(query)\n\tresults.Query.Limit(1)\n\n\thasNext := results.Next(doc)\n\n\tif !hasNext {\n\t\t\/\/ There could have been an error fetching the next one, which would set the Error property on the resultset\n\t\tif results.Error != nil {\n\t\t\treturn results.Error\n\t\t} else {\n\t\t\treturn &DocumentNotFoundError{}\n\t\t}\n\n\t}\n\n\tif newt, ok := doc.(NewTracker); ok {\n\t\tnewt.SetIsNew(false)\n\t}\n\n\treturn nil\n}\n\nfunc (c *Collection) DeleteDocument(doc Document) error {\n\tvar err error\n\t\/\/ Create a new session per mgo's suggestion to avoid blocking\n\tsess := c.Connection.Session.Clone()\n\tdefer sess.Close()\n\tcol := c.collectionOnSession(sess)\n\n\tif hook, ok := doc.(BeforeDeleteHook); ok {\n\t\terr := hook.BeforeDelete(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = col.Remove(bson.M{\"_id\": doc.GetId()})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo CascadeDelete(c, doc)\n\n\tif hook, ok := doc.(AfterDeleteHook); ok {\n\t\terr = hook.AfterDelete(c)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n\n}\n\n\/\/ Convenience method which just delegates to mgo. Note that hooks are NOT run\nfunc (c *Collection) Delete(query bson.M) (*mgo.ChangeInfo, error) {\n\tsess := c.Connection.Session.Clone()\n\tdefer sess.Close()\n\tcol := c.collectionOnSession(sess)\n\treturn col.RemoveAll(query)\n}\n\n\/\/ Convenience method which just delegates to mgo. Note that hooks are NOT run\nfunc (c *Collection) DeleteOne(query bson.M) error {\n\tsess := c.Connection.Session.Clone()\n\tdefer sess.Close()\n\tcol := c.collectionOnSession(sess)\n\treturn col.Remove(query)\n}\n<|endoftext|>"}
{"text":"<commit_before>package ibclient\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n)\n\ntype ObjectManager struct {\n\tconnector *Connector\n\tcmpType   string\n\ttenantID  string\n}\n\nfunc NewObjectManager(connector *Connector, cmpType string, tenantID string) *ObjectManager {\n\tobjMgr := new(ObjectManager)\n\n\tobjMgr.connector = connector\n\tobjMgr.cmpType = cmpType\n\tobjMgr.tenantID = tenantID\n\n\treturn objMgr\n}\n\nfunc (objMgr *ObjectManager) getBasicEA(cloudApiOwned Bool) EA {\n\tea := make(EA)\n\tea[\"Cloud API Owned\"] = cloudApiOwned\n\tea[\"CMP Type\"] = objMgr.cmpType\n\tea[\"Tenant ID\"] = objMgr.tenantID\n\treturn ea\n}\n\nfunc (objMgr *ObjectManager) CreateNetworkView(name string) (*NetworkView, error) {\n\tnetworkView := NewNetworkView(NetworkView{\n\t\tName: name,\n\t\tEa:   objMgr.getBasicEA(false)})\n\n\tref, err := objMgr.connector.CreateObject(networkView)\n\tnetworkView.Ref = ref\n\n\treturn networkView, err\n}\n\nfunc (objMgr *ObjectManager) CreateDefaultNetviews(globalNetview string, localNetview string) (globalNetviewRef string, localNetviewRef string, err error) {\n\tglobalNetviewRef = \"\"\n\tlocalNetviewRef = \"\"\n\n\tvar globalNetviewObj *NetworkView\n\tif globalNetviewObj, err = objMgr.GetNetworkView(globalNetview); err != nil {\n\t\treturn\n\t}\n\tif globalNetviewObj == nil {\n\t\tif globalNetviewObj, err = objMgr.CreateNetworkView(globalNetview); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tglobalNetviewRef = globalNetviewObj.Ref\n\n\tvar localNetviewObj *NetworkView\n\tif localNetviewObj, err = objMgr.GetNetworkView(localNetview); err != nil {\n\t\treturn\n\t}\n\tif localNetviewObj == nil {\n\t\tif localNetviewObj, err = objMgr.CreateNetworkView(localNetview); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tlocalNetviewRef = localNetviewObj.Ref\n\n\treturn\n}\n\nfunc (objMgr *ObjectManager) CreateNetwork(netview string, cidr string, name string) (*Network, error) {\n\tnetwork := NewNetwork(Network{\n\t\tNetviewName: netview,\n\t\tCidr:        cidr,\n\t\tEa:          objMgr.getBasicEA(true)})\n\n\tif name != \"\" {\n\t\tnetwork.Ea[\"Network Name\"] = name\n\t}\n\tref, err := objMgr.connector.CreateObject(network)\n\tnetwork.Ref = ref\n\n\treturn network, err\n}\n\nfunc (objMgr *ObjectManager) CreateNetworkContainer(netview string, cidr string) (*NetworkContainer, error) {\n\tcontainer := NewNetworkContainer(NetworkContainer{\n\t\tNetviewName: netview,\n\t\tCidr:        cidr,\n\t\tEa:          objMgr.getBasicEA(true)})\n\n\tref, err := objMgr.connector.CreateObject(container)\n\tcontainer.Ref = ref\n\n\treturn container, err\n}\n\nfunc (objMgr *ObjectManager) GetNetworkView(name string) (*NetworkView, error) {\n\tvar res []NetworkView\n\n\tnetview := NewNetworkView(NetworkView{Name: name})\n\n\terr := objMgr.connector.GetObject(netview, \"\", &res)\n\n\tif err != nil || res == nil || len(res) == 0 {\n\t\treturn nil, err\n\t}\n\n\treturn &res[0], nil\n}\n\nfunc BuildNetworkViewFromRef(ref string) *NetworkView {\n\t\/\/ networkview\/ZG5zLm5ldHdvcmtfdmlldyQyMw:global_view\/false\n\tr := regexp.MustCompile(`networkview\/\\w+:([^\/]+)\/\\w+`)\n\tm := r.FindStringSubmatch(ref)\n\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\treturn &NetworkView{\n\t\tRef:  ref,\n\t\tName: m[1],\n\t}\n}\n\nfunc BuildNetworkFromRef(ref string) *Network {\n\t\/\/ network\/ZG5zLm5ldHdvcmskODkuMC4wLjAvMjQvMjU:89.0.0.0\/24\/global_view\n\tr := regexp.MustCompile(`network\/\\w+:(\\d+\\.\\d+\\.\\d+\\.\\d+\/\\d+)\/(.+)`)\n\tm := r.FindStringSubmatch(ref)\n\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\treturn &Network{\n\t\tRef:         ref,\n\t\tNetviewName: m[2],\n\t\tCidr:        m[1],\n\t}\n}\n\nfunc (objMgr *ObjectManager) GetNetwork(netview string, cidr string, ea EA) (*Network, error) {\n\tvar res []Network\n\n\tnetwork := NewNetwork(Network{\n\t\tNetviewName: netview})\n\n\tif cidr != \"\" {\n\t\tnetwork.Cidr = cidr\n\t}\n\n\tif ea != nil && len(ea) > 0 {\n\t\tnetwork.eaSearch = ea\n\t}\n\n\terr := objMgr.connector.GetObject(network, \"\", &res)\n\n\tif err != nil || res == nil || len(res) == 0 {\n\t\treturn nil, err\n\t}\n\n\treturn &res[0], nil\n}\n\nfunc (objMgr *ObjectManager) GetNetworkContainer(netview string, cidr string) (*NetworkContainer, error) {\n\tvar res []NetworkContainer\n\n\tnwcontainer := NewNetworkContainer(NetworkContainer{\n\t\tNetviewName: netview,\n\t\tCidr:        cidr})\n\n\terr := objMgr.connector.GetObject(nwcontainer, \"\", &res)\n\n\tif err != nil || res == nil || len(res) == 0 {\n\t\treturn nil, err\n\t}\n\n\treturn &res[0], nil\n}\n\nfunc GetIPAddressFromRef(ref string) string {\n\t\/\/ fixedaddress\/ZG5zLmJpbmRfY25h:12.0.10.1\/external\n\tr := regexp.MustCompile(`fixedaddress\/\\w+:(\\d+\\.\\d+\\.\\d+\\.\\d+)\/.+`)\n\tm := r.FindStringSubmatch(ref)\n\n\tif m != nil {\n\t\treturn m[1]\n\t}\n\treturn \"\"\n}\n\nfunc (objMgr *ObjectManager) AllocateIP(netview string, cidr string, ipAddr string, macAddress string, vmID string) (*FixedAddress, error) {\n\tif len(macAddress) == 0 {\n\t\tmacAddress = MACADDR_ZERO\n\t}\n\n\tea := objMgr.getBasicEA(true)\n\tea[\"VM ID\"] = \"N\/A\"\n\tif vmID != \"\" {\n\t\tea[\"VM ID\"] = vmID\n\t}\n\n\tfixedAddr := NewFixedAddress(FixedAddress{\n\t\tNetviewName: netview,\n\t\tCidr:        cidr,\n\t\tMac:         macAddress,\n\t\tEa:          ea})\n\n\tif ipAddr == \"\" {\n\t\tfixedAddr.IPAddress = fmt.Sprintf(\"func:nextavailableip:%s,%s\", cidr, netview)\n\t} else {\n\t\tfixedAddr.IPAddress = ipAddr\n\t}\n\n\tref, err := objMgr.connector.CreateObject(fixedAddr)\n\tfixedAddr.Ref = ref\n\tfixedAddr.IPAddress = GetIPAddressFromRef(ref)\n\n\treturn fixedAddr, err\n}\n\nfunc (objMgr *ObjectManager) AllocateNetwork(netview string, cidr string, prefixLen uint, name string) (network *Network, err error) {\n\tnetwork = nil\n\n\tnetworkReq := NewNetwork(Network{\n\t\tNetviewName: netview,\n\t\tCidr:        fmt.Sprintf(\"func:nextavailablenetwork:%s,%s,%d\", cidr, netview, prefixLen),\n\t\tEa:          objMgr.getBasicEA(true)})\n\tif name != \"\" {\n\t\tnetworkReq.Ea[\"Network Name\"] = name\n\t}\n\n\tref, err := objMgr.connector.CreateObject(networkReq)\n\tif err == nil && len(ref) > 0 {\n\t\tnetwork = BuildNetworkFromRef(ref)\n\t}\n\n\treturn\n}\n\nfunc (objMgr *ObjectManager) GetFixedAddress(netview string, ipAddr string, macAddr string) (*FixedAddress, error) {\n\tvar res []FixedAddress\n\n\tfixedAddr := NewFixedAddress(FixedAddress{\n\t\tNetviewName: netview})\n\n\tif ipAddr != \"\" {\n\t\tfixedAddr.IPAddress = ipAddr\n\t}\n\n\tif macAddr != \"\" {\n\t\tfixedAddr.Mac = macAddr\n\t}\n\n\terr := objMgr.connector.GetObject(fixedAddr, \"\", &res)\n\n\tif err != nil || res == nil || len(res) == 0 {\n\t\treturn nil, err\n\t}\n\n\treturn &res[0], nil\n}\n\nfunc (objMgr *ObjectManager) ReleaseIP(netview string, ipAddr string, macAddr string) (string, error) {\n\tfmt.Printf(\"ReleaseIP called: '%s', '%s', '%s'\\n\", netview, ipAddr, macAddr)\n\tfixAddress, _ := objMgr.GetFixedAddress(netview, ipAddr, macAddr)\n\tfmt.Printf(\"GetFixedAddress() returns: '%s'\\n\", fixAddress)\n\n\treturn objMgr.connector.DeleteObject(fixAddress.Ref)\n}\n\nfunc (objMgr *ObjectManager) DeleteLocalNetwork(ref string, localNetview string) (string, error) {\n\tnetwork := BuildNetworkFromRef(ref)\n\tif network != nil && network.NetviewName == localNetview {\n\t\treturn objMgr.connector.DeleteObject(ref)\n\t}\n\n\treturn \"\", nil\n}\n\nfunc (objMgr *ObjectManager) GetEADefinition(name string) (*EADefinition, error) {\n\tvar res []EADefinition\n\n\teadef := NewEADefinition(EADefinition{Name: name})\n\n\terr := objMgr.connector.GetObject(eadef, \"\", &res)\n\n\tif err != nil || res == nil || len(res) == 0 {\n\t\treturn nil, err\n\t}\n\n\treturn &res[0], nil\n}\n\nfunc (objMgr *ObjectManager) CreateEADefinition(eadef EADefinition) (*EADefinition, error) {\n\tnewEadef := NewEADefinition(eadef)\n\n\tref, err := objMgr.connector.CreateObject(newEadef)\n\tnewEadef.Ref = ref\n\n\treturn newEadef, err\n}\n<commit_msg>Rename DeleteLocalNetwork() method<commit_after>package ibclient\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n)\n\ntype ObjectManager struct {\n\tconnector *Connector\n\tcmpType   string\n\ttenantID  string\n}\n\nfunc NewObjectManager(connector *Connector, cmpType string, tenantID string) *ObjectManager {\n\tobjMgr := new(ObjectManager)\n\n\tobjMgr.connector = connector\n\tobjMgr.cmpType = cmpType\n\tobjMgr.tenantID = tenantID\n\n\treturn objMgr\n}\n\nfunc (objMgr *ObjectManager) getBasicEA(cloudApiOwned Bool) EA {\n\tea := make(EA)\n\tea[\"Cloud API Owned\"] = cloudApiOwned\n\tea[\"CMP Type\"] = objMgr.cmpType\n\tea[\"Tenant ID\"] = objMgr.tenantID\n\treturn ea\n}\n\nfunc (objMgr *ObjectManager) CreateNetworkView(name string) (*NetworkView, error) {\n\tnetworkView := NewNetworkView(NetworkView{\n\t\tName: name,\n\t\tEa:   objMgr.getBasicEA(false)})\n\n\tref, err := objMgr.connector.CreateObject(networkView)\n\tnetworkView.Ref = ref\n\n\treturn networkView, err\n}\n\nfunc (objMgr *ObjectManager) CreateDefaultNetviews(globalNetview string, localNetview string) (globalNetviewRef string, localNetviewRef string, err error) {\n\tglobalNetviewRef = \"\"\n\tlocalNetviewRef = \"\"\n\n\tvar globalNetviewObj *NetworkView\n\tif globalNetviewObj, err = objMgr.GetNetworkView(globalNetview); err != nil {\n\t\treturn\n\t}\n\tif globalNetviewObj == nil {\n\t\tif globalNetviewObj, err = objMgr.CreateNetworkView(globalNetview); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tglobalNetviewRef = globalNetviewObj.Ref\n\n\tvar localNetviewObj *NetworkView\n\tif localNetviewObj, err = objMgr.GetNetworkView(localNetview); err != nil {\n\t\treturn\n\t}\n\tif localNetviewObj == nil {\n\t\tif localNetviewObj, err = objMgr.CreateNetworkView(localNetview); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tlocalNetviewRef = localNetviewObj.Ref\n\n\treturn\n}\n\nfunc (objMgr *ObjectManager) CreateNetwork(netview string, cidr string, name string) (*Network, error) {\n\tnetwork := NewNetwork(Network{\n\t\tNetviewName: netview,\n\t\tCidr:        cidr,\n\t\tEa:          objMgr.getBasicEA(true)})\n\n\tif name != \"\" {\n\t\tnetwork.Ea[\"Network Name\"] = name\n\t}\n\tref, err := objMgr.connector.CreateObject(network)\n\tnetwork.Ref = ref\n\n\treturn network, err\n}\n\nfunc (objMgr *ObjectManager) CreateNetworkContainer(netview string, cidr string) (*NetworkContainer, error) {\n\tcontainer := NewNetworkContainer(NetworkContainer{\n\t\tNetviewName: netview,\n\t\tCidr:        cidr,\n\t\tEa:          objMgr.getBasicEA(true)})\n\n\tref, err := objMgr.connector.CreateObject(container)\n\tcontainer.Ref = ref\n\n\treturn container, err\n}\n\nfunc (objMgr *ObjectManager) GetNetworkView(name string) (*NetworkView, error) {\n\tvar res []NetworkView\n\n\tnetview := NewNetworkView(NetworkView{Name: name})\n\n\terr := objMgr.connector.GetObject(netview, \"\", &res)\n\n\tif err != nil || res == nil || len(res) == 0 {\n\t\treturn nil, err\n\t}\n\n\treturn &res[0], nil\n}\n\nfunc BuildNetworkViewFromRef(ref string) *NetworkView {\n\t\/\/ networkview\/ZG5zLm5ldHdvcmtfdmlldyQyMw:global_view\/false\n\tr := regexp.MustCompile(`networkview\/\\w+:([^\/]+)\/\\w+`)\n\tm := r.FindStringSubmatch(ref)\n\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\treturn &NetworkView{\n\t\tRef:  ref,\n\t\tName: m[1],\n\t}\n}\n\nfunc BuildNetworkFromRef(ref string) *Network {\n\t\/\/ network\/ZG5zLm5ldHdvcmskODkuMC4wLjAvMjQvMjU:89.0.0.0\/24\/global_view\n\tr := regexp.MustCompile(`network\/\\w+:(\\d+\\.\\d+\\.\\d+\\.\\d+\/\\d+)\/(.+)`)\n\tm := r.FindStringSubmatch(ref)\n\n\tif m == nil {\n\t\treturn nil\n\t}\n\n\treturn &Network{\n\t\tRef:         ref,\n\t\tNetviewName: m[2],\n\t\tCidr:        m[1],\n\t}\n}\n\nfunc (objMgr *ObjectManager) GetNetwork(netview string, cidr string, ea EA) (*Network, error) {\n\tvar res []Network\n\n\tnetwork := NewNetwork(Network{\n\t\tNetviewName: netview})\n\n\tif cidr != \"\" {\n\t\tnetwork.Cidr = cidr\n\t}\n\n\tif ea != nil && len(ea) > 0 {\n\t\tnetwork.eaSearch = ea\n\t}\n\n\terr := objMgr.connector.GetObject(network, \"\", &res)\n\n\tif err != nil || res == nil || len(res) == 0 {\n\t\treturn nil, err\n\t}\n\n\treturn &res[0], nil\n}\n\nfunc (objMgr *ObjectManager) GetNetworkContainer(netview string, cidr string) (*NetworkContainer, error) {\n\tvar res []NetworkContainer\n\n\tnwcontainer := NewNetworkContainer(NetworkContainer{\n\t\tNetviewName: netview,\n\t\tCidr:        cidr})\n\n\terr := objMgr.connector.GetObject(nwcontainer, \"\", &res)\n\n\tif err != nil || res == nil || len(res) == 0 {\n\t\treturn nil, err\n\t}\n\n\treturn &res[0], nil\n}\n\nfunc GetIPAddressFromRef(ref string) string {\n\t\/\/ fixedaddress\/ZG5zLmJpbmRfY25h:12.0.10.1\/external\n\tr := regexp.MustCompile(`fixedaddress\/\\w+:(\\d+\\.\\d+\\.\\d+\\.\\d+)\/.+`)\n\tm := r.FindStringSubmatch(ref)\n\n\tif m != nil {\n\t\treturn m[1]\n\t}\n\treturn \"\"\n}\n\nfunc (objMgr *ObjectManager) AllocateIP(netview string, cidr string, ipAddr string, macAddress string, vmID string) (*FixedAddress, error) {\n\tif len(macAddress) == 0 {\n\t\tmacAddress = MACADDR_ZERO\n\t}\n\n\tea := objMgr.getBasicEA(true)\n\tea[\"VM ID\"] = \"N\/A\"\n\tif vmID != \"\" {\n\t\tea[\"VM ID\"] = vmID\n\t}\n\n\tfixedAddr := NewFixedAddress(FixedAddress{\n\t\tNetviewName: netview,\n\t\tCidr:        cidr,\n\t\tMac:         macAddress,\n\t\tEa:          ea})\n\n\tif ipAddr == \"\" {\n\t\tfixedAddr.IPAddress = fmt.Sprintf(\"func:nextavailableip:%s,%s\", cidr, netview)\n\t} else {\n\t\tfixedAddr.IPAddress = ipAddr\n\t}\n\n\tref, err := objMgr.connector.CreateObject(fixedAddr)\n\tfixedAddr.Ref = ref\n\tfixedAddr.IPAddress = GetIPAddressFromRef(ref)\n\n\treturn fixedAddr, err\n}\n\nfunc (objMgr *ObjectManager) AllocateNetwork(netview string, cidr string, prefixLen uint, name string) (network *Network, err error) {\n\tnetwork = nil\n\n\tnetworkReq := NewNetwork(Network{\n\t\tNetviewName: netview,\n\t\tCidr:        fmt.Sprintf(\"func:nextavailablenetwork:%s,%s,%d\", cidr, netview, prefixLen),\n\t\tEa:          objMgr.getBasicEA(true)})\n\tif name != \"\" {\n\t\tnetworkReq.Ea[\"Network Name\"] = name\n\t}\n\n\tref, err := objMgr.connector.CreateObject(networkReq)\n\tif err == nil && len(ref) > 0 {\n\t\tnetwork = BuildNetworkFromRef(ref)\n\t}\n\n\treturn\n}\n\nfunc (objMgr *ObjectManager) GetFixedAddress(netview string, ipAddr string, macAddr string) (*FixedAddress, error) {\n\tvar res []FixedAddress\n\n\tfixedAddr := NewFixedAddress(FixedAddress{\n\t\tNetviewName: netview})\n\n\tif ipAddr != \"\" {\n\t\tfixedAddr.IPAddress = ipAddr\n\t}\n\n\tif macAddr != \"\" {\n\t\tfixedAddr.Mac = macAddr\n\t}\n\n\terr := objMgr.connector.GetObject(fixedAddr, \"\", &res)\n\n\tif err != nil || res == nil || len(res) == 0 {\n\t\treturn nil, err\n\t}\n\n\treturn &res[0], nil\n}\n\nfunc (objMgr *ObjectManager) ReleaseIP(netview string, ipAddr string, macAddr string) (string, error) {\n\tfmt.Printf(\"ReleaseIP called: '%s', '%s', '%s'\\n\", netview, ipAddr, macAddr)\n\tfixAddress, _ := objMgr.GetFixedAddress(netview, ipAddr, macAddr)\n\tfmt.Printf(\"GetFixedAddress() returns: '%s'\\n\", fixAddress)\n\n\treturn objMgr.connector.DeleteObject(fixAddress.Ref)\n}\n\nfunc (objMgr *ObjectManager) DeleteNetwork(ref string, netview string) (string, error) {\n\tnetwork := BuildNetworkFromRef(ref)\n\tif network != nil && network.NetviewName == netview {\n\t\treturn objMgr.connector.DeleteObject(ref)\n\t}\n\n\treturn \"\", nil\n}\n\nfunc (objMgr *ObjectManager) GetEADefinition(name string) (*EADefinition, error) {\n\tvar res []EADefinition\n\n\teadef := NewEADefinition(EADefinition{Name: name})\n\n\terr := objMgr.connector.GetObject(eadef, \"\", &res)\n\n\tif err != nil || res == nil || len(res) == 0 {\n\t\treturn nil, err\n\t}\n\n\treturn &res[0], nil\n}\n\nfunc (objMgr *ObjectManager) CreateEADefinition(eadef EADefinition) (*EADefinition, error) {\n\tnewEadef := NewEADefinition(eadef)\n\n\tref, err := objMgr.connector.CreateObject(newEadef)\n\tnewEadef.Ref = ref\n\n\treturn newEadef, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package common\n\nimport (\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"log\"\n\t\"path\"\n\t\"io\/ioutil\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/lambda\"\n\t\"encoding\/json\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/pkg\/errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"os\"\n)\n\nfunc SshCommand(sess *session.Session, lambdaFunc, funcIdentity, kmsKeyId, instanceArn, username string, encodedVouchers, args []string) []string {\n\tkp, _ := MyKeyPair()\n\n\tident, err := CallerIdentityUser(sess)\n\tif err != nil {\n\t\tlog.Panicf(\"error getting aws user identity: %+v\\n\", err)\n\t}\n\n\tvouchers := []VoucherToken{}\n\tfor _, encVoucher := range(encodedVouchers) {\n\t\tvoucher, err := DecodeVoucherToken(encVoucher)\n\t\tif err != nil {\n\t\t\tlog.Panicf(\"couldn't decode voucher: %+v\\n\", err)\n\t\t}\n\t\tvouchers = append(vouchers, *voucher)\n\t}\n\n\ttoken := CreateToken(sess, TokenParams{\n\t\tFromId: ident.UserId,\n\t\tFromAccount: ident.AccountId,\n\t\tFromName: ident.Username,\n\t\tTo: funcIdentity,\n\t\tType: ident.Type,\n\t\tRemoteInstanceArn: instanceArn,\n\t\tVouchers: vouchers,\n\t\tSshUsername: username,\n\t}, kmsKeyId)\n\n\treq := UserCertReqJson{\n\t\tEventType: \"UserCertReq\",\n\t\tToken: token,\n\t\tPublicKey: string(kp.PublicKey),\n\t}\n\n\tsigned := UserCertRespJson{}\n\terr = RequestSignedPayload(sess, lambdaFunc, req, &signed)\n\tif err != nil {\n\t\tlog.Panicf(\"err: %s\", err.Error())\n\t}\n\n\tcertPath := path.Join(AppDir(), \"id_rsa-cert.pub\")\n\tioutil.WriteFile(certPath, []byte(signed.SignedPublicKey), 0644)\n\n\tlkpArgs := []string{\n\t\t\"ssh\",\n\t\t\"-o\",\n\t\t\"IdentityFile=~\/.lkp\/id_rsa\",\n\t}\n\n\tif len(signed.Jumpboxes) > 0 {\n\t\tif len(signed.Jumpboxes) > 1 {\n\t\t\tfmt.Fprintln(os.Stderr, \"Lastkeypair doesn't yet support multiple jumpboxes\")\n\t\t}\n\n\t\tjbox := signed.Jumpboxes[0]\n\t\tsprintf := fmt.Sprintf(\"ProxyCommand='ssh -W %%h:%%p %s@%s'\", jbox.User, jbox.Address)\n\t\tproxyCommand := sprintf\n\t\tlkpArgs = append(lkpArgs, \"-o\", proxyCommand)\n\t}\n\n\targs = append(lkpArgs, args...)\n\treturn args\n}\n\nfunc lambdaClientForKeyId(sess *session.Session, lambdaArn string) *lambda.Lambda {\n\tif strings.HasPrefix(lambdaArn, \"arn:aws:lambda\") {\n\t\tparts := strings.Split(lambdaArn, \":\")\n\t\tregion := parts[3]\n\t\tsess = sess.Copy(aws.NewConfig().WithRegion(region))\n\t}\n\n\treturn lambda.New(sess)\n}\n\nfunc RequestSignedPayload(sess *session.Session, lambdaArn string, req interface{}, resp interface{}) error {\n\tca := lambdaClientForKeyId(sess, lambdaArn)\n\n\treqPayload, err := json.Marshal(&req)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"marshalling lambda req payload\")\n\t}\n\n\tinput := lambda.InvokeInput{\n\t\tFunctionName: aws.String(lambdaArn),\n\t\tPayload: reqPayload,\n\t}\n\n\tlambdaResp, err := ca.Invoke(&input)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"invoking CA lambda\")\n\t}\n\n\terr = json.Unmarshal(lambdaResp.Payload, resp)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unmarshalling lambda resp payload\")\n\t}\n\n\treturn nil\n}\n<commit_msg>Client-side support for chained jumpboxes (closes #23)<commit_after>package common\n\nimport (\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"log\"\n\t\"path\"\n\t\"io\/ioutil\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/lambda\"\n\t\"encoding\/json\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/pkg\/errors\"\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc SshCommand(sess *session.Session, lambdaFunc, funcIdentity, kmsKeyId, instanceArn, username string, encodedVouchers, args []string) []string {\n\tkp, _ := MyKeyPair()\n\n\tident, err := CallerIdentityUser(sess)\n\tif err != nil {\n\t\tlog.Panicf(\"error getting aws user identity: %+v\\n\", err)\n\t}\n\n\tvouchers := []VoucherToken{}\n\tfor _, encVoucher := range(encodedVouchers) {\n\t\tvoucher, err := DecodeVoucherToken(encVoucher)\n\t\tif err != nil {\n\t\t\tlog.Panicf(\"couldn't decode voucher: %+v\\n\", err)\n\t\t}\n\t\tvouchers = append(vouchers, *voucher)\n\t}\n\n\ttoken := CreateToken(sess, TokenParams{\n\t\tFromId: ident.UserId,\n\t\tFromAccount: ident.AccountId,\n\t\tFromName: ident.Username,\n\t\tTo: funcIdentity,\n\t\tType: ident.Type,\n\t\tRemoteInstanceArn: instanceArn,\n\t\tVouchers: vouchers,\n\t\tSshUsername: username,\n\t}, kmsKeyId)\n\n\treq := UserCertReqJson{\n\t\tEventType: \"UserCertReq\",\n\t\tToken: token,\n\t\tPublicKey: string(kp.PublicKey),\n\t}\n\n\tsigned := UserCertRespJson{}\n\terr = RequestSignedPayload(sess, lambdaFunc, req, &signed)\n\tif err != nil {\n\t\tlog.Panicf(\"err: %s\", err.Error())\n\t}\n\n\tcertPath := path.Join(AppDir(), \"id_rsa-cert.pub\")\n\tioutil.WriteFile(certPath, []byte(signed.SignedPublicKey), 0644)\n\n\tlkpArgs := []string{\n\t\t\"ssh\",\n\t\t\"-o\",\n\t\t\"IdentityFile=~\/.lkp\/id_rsa\",\n\t}\n\n\tif len(signed.Jumpboxes) > 0 {\n\t\tjumps := []string{}\n\t\tfor _, jbox := range signed.Jumpboxes {\n\t\t\tjumps = append(jumps, fmt.Sprintf(\"%s@%s\", jbox.User, jbox.Address))\n\t\t}\n\t\tjoinedJumps := strings.Join(jumps, \",\")\n\t\tlkpArgs = append(lkpArgs, \"-J\", joinedJumps)\n\t}\n\n\targs = append(lkpArgs, args...)\n\treturn args\n}\n\nfunc lambdaClientForKeyId(sess *session.Session, lambdaArn string) *lambda.Lambda {\n\tif strings.HasPrefix(lambdaArn, \"arn:aws:lambda\") {\n\t\tparts := strings.Split(lambdaArn, \":\")\n\t\tregion := parts[3]\n\t\tsess = sess.Copy(aws.NewConfig().WithRegion(region))\n\t}\n\n\treturn lambda.New(sess)\n}\n\nfunc RequestSignedPayload(sess *session.Session, lambdaArn string, req interface{}, resp interface{}) error {\n\tca := lambdaClientForKeyId(sess, lambdaArn)\n\n\treqPayload, err := json.Marshal(&req)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"marshalling lambda req payload\")\n\t}\n\n\tinput := lambda.InvokeInput{\n\t\tFunctionName: aws.String(lambdaArn),\n\t\tPayload: reqPayload,\n\t}\n\n\tlambdaResp, err := ca.Invoke(&input)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"invoking CA lambda\")\n\t}\n\n\terr = json.Unmarshal(lambdaResp.Payload, resp)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"unmarshalling lambda resp payload\")\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package datastore\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"cloud.google.com\/go\/datastore\"\n\t\"github.com\/rs\/rest-layer\/resource\"\n\t\"github.com\/rs\/rest-layer\/schema\"\n)\n\n\/\/ getSort transform a resource.Lookup into a Datastore sort list.\n\/\/ If the sort list is empty, fallback to _id.\nfunc getSort(query *datastore.Query, s []string) *datastore.Query {\n\n\tfor _, sort := range s {\n\t\tquery = query.Order(sort)\n\t}\n\treturn query\n}\n\n\/\/ getField translates id to _id to avoid duplication\nfunc getField(f string) string {\n\tif f == \"id\" {\n\t\treturn \"_id\"\n\t}\n\treturn f\n}\n\n\/\/ getQuery transform a resource.Lookup into a Google Datastore query\nfunc getQuery(e string, ns string, l *resource.Lookup) (*datastore.Query, error) {\n\tquery, err := translateQuery(datastore.NewQuery(e), l.Filter())\n\t\/\/ if lookup specifies sorting add this to our query\n\tif len(l.Sort()) > 0 {\n\t\tquery = getSort(query, l.Sort())\n\t}\n\t\/\/ Set namespace for this query\n\tquery = query.Namespace(ns)\n\treturn query, err\n}\n\nfunc translateQuery(dsQuery *datastore.Query, q schema.Query) (*datastore.Query, error) {\n\tvar err error\n\t\/\/ process each schema.Expression into a datastore filter\n\tfor _, exp := range q {\n\t\tswitch t := exp.(type) {\n\t\tcase schema.Equal:\n\t\t\t\/\/ If our Query contains a slice, add each as an additional filter\n\t\t\tif reflect.TypeOf(t.Value).Kind() == reflect.Slice {\n\t\t\t\tfor _, v := range t.Value.([]interface{}) {\n\t\t\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s =\", getField(t.Field)), v)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s =\", getField(t.Field)), t.Value)\n\t\t\t}\n\t\tcase schema.NotEqual:\n\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s !=\", getField(t.Field)), t.Value)\n\t\tcase schema.GreaterThan:\n\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s >\", getField(t.Field)), t.Value)\n\t\tcase schema.GreaterOrEqual:\n\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s >=\", getField(t.Field)), t.Value)\n\t\tcase schema.LowerThan:\n\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s <\", getField(t.Field)), t.Value)\n\t\tcase schema.LowerOrEqual:\n\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s <=\", getField(t.Field)), t.Value)\n\t\tcase schema.And:\n\t\t\tfor _, subExp := range t {\n\t\t\t\tdsQuery, err = translateQuery(dsQuery, schema.Query{subExp})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\t\/\/ return resource.ErrNotImplemented for:\n\t\t\t\/\/ schema.Or, schema.In, schema,NotIn\n\t\t\treturn nil, resource.ErrNotImplemented\n\t\t}\n\t}\n\treturn dsQuery, nil\n}\n<commit_msg>Migrate to the new query package. (#4)<commit_after>package datastore\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"cloud.google.com\/go\/datastore\"\n\t\"github.com\/rs\/rest-layer\/resource\"\n\t\"github.com\/rs\/rest-layer\/schema\/query\"\n)\n\n\/\/ getSort transform a resource.Lookup into a Datastore sort list.\n\/\/ If the sort list is empty, fallback to _id.\nfunc getSort(query *datastore.Query, s []string) *datastore.Query {\n\n\tfor _, sort := range s {\n\t\tquery = query.Order(sort)\n\t}\n\treturn query\n}\n\n\/\/ getField translates id to _id to avoid duplication\nfunc getField(f string) string {\n\tif f == \"id\" {\n\t\treturn \"_id\"\n\t}\n\treturn f\n}\n\n\/\/ getQuery transform a resource.Lookup into a Google Datastore query\nfunc getQuery(e string, ns string, l *resource.Lookup) (*datastore.Query, error) {\n\tquery, err := translateQuery(datastore.NewQuery(e), l.Filter())\n\t\/\/ if lookup specifies sorting add this to our query\n\tif len(l.Sort()) > 0 {\n\t\tquery = getSort(query, l.Sort())\n\t}\n\t\/\/ Set namespace for this query\n\tquery = query.Namespace(ns)\n\treturn query, err\n}\n\nfunc translateQuery(dsQuery *datastore.Query, q query.Query) (*datastore.Query, error) {\n\tvar err error\n\t\/\/ process each schema.Expression into a datastore filter\n\tfor _, exp := range q {\n\t\tswitch t := exp.(type) {\n\t\tcase query.Equal:\n\t\t\t\/\/ If our Query contains a slice, add each as an additional filter\n\t\t\tif reflect.TypeOf(t.Value).Kind() == reflect.Slice {\n\t\t\t\tfor _, v := range t.Value.([]interface{}) {\n\t\t\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s =\", getField(t.Field)), v)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s =\", getField(t.Field)), t.Value)\n\t\t\t}\n\t\tcase query.NotEqual:\n\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s !=\", getField(t.Field)), t.Value)\n\t\tcase query.GreaterThan:\n\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s >\", getField(t.Field)), t.Value)\n\t\tcase query.GreaterOrEqual:\n\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s >=\", getField(t.Field)), t.Value)\n\t\tcase query.LowerThan:\n\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s <\", getField(t.Field)), t.Value)\n\t\tcase query.LowerOrEqual:\n\t\t\tdsQuery = dsQuery.Filter(fmt.Sprintf(\"%s <=\", getField(t.Field)), t.Value)\n\t\tcase query.And:\n\t\t\tfor _, subExp := range t {\n\t\t\t\tdsQuery, err = translateQuery(dsQuery, query.Query{subExp})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\t\/\/ return resource.ErrNotImplemented for:\n\t\t\t\/\/ schema.Or, schema.In, schema,NotIn\n\t\t\treturn nil, resource.ErrNotImplemented\n\t\t}\n\t}\n\treturn dsQuery, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/graphql-go\/graphql\"\n\t\"github.com\/graphql-go\/graphql\/examples\/todo\/schema\"\n)\n\ntype postData struct {\n\tQuery     string                 `json:\"query\"`\n\tOperation string                 `json:\"operation\"`\n\tVariables map[string]interface{} `json:\"variables\"`\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/graphql\", func(w http.ResponseWriter, req *http.Request) {\n\t\tvar p postData\n\t\tif err := json.NewDecoder(req.Body).Decode(&p); err != nil {\n\t\t\tw.WriteHeader(400)\n\t\t\treturn\n\t\t}\n\t\tresult := graphql.Do(graphql.Params{\n\t\t\tContext:        req.Context(),\n\t\t\tSchema:         schema.TodoSchema,\n\t\t\tRequestString:  p.Query,\n\t\t\tVariableValues: p.Variables,\n\t\t\tOperationName:  p.Operation,\n\t\t})\n\t\tif err := json.NewEncoder(w).Encode(result); err != nil {\n\t\t\tfmt.Printf(\"could not write result to response: %s\", err)\n\t\t}\n\t})\n\n\tfmt.Println(\"Now server is running on port 8080\\n\")\n\n\tfmt.Println(`Get single todo:\ncurl \\\n-X POST \\\n-H \"Content-Type: application\/json\" \\\n--data '{ \"query\": \"{ todo(id:\\\"b\\\") { id text done } }\" }' \\\nhttp:\/\/localhost:8080\/graphql\n`)\n\n\tfmt.Println(`Create new todo:\ncurl \\\n-X POST \\\n-H \"Content-Type: application\/json\" \\\n--data '{ \"query\": \"mutation { createTodo(text:\\\"My New todo\\\") { id text done } }\" }' \\\nhttp:\/\/localhost:8080\/graphql\n`)\n\n\tfmt.Println(`Update todo:\ncurl \\\n-X POST \\\n-H \"Content-Type: application\/json\" \\\n--data '{ \"query\": \"mutation { updateTodo(id:\\\"a\\\", done: true) { id text done } }\" }' \\\nhttp:\/\/localhost:8080\/graphql\n`)\n\n\tfmt.Println(`Load todo list:\ncurl \\\n-X POST \\\n-H \"Content-Type: application\/json\" \\\n--data '{ \"query\": \"{ todoList { id text done } }\" }' \\\nhttp:\/\/localhost:8080\/graphql`)\n\n\thttp.ListenAndServe(\":8080\", nil)\n}\n<commit_msg>examples\/http-post: fixes 'newline redundant' validation<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/graphql-go\/graphql\"\n\t\"github.com\/graphql-go\/graphql\/examples\/todo\/schema\"\n)\n\ntype postData struct {\n\tQuery     string                 `json:\"query\"`\n\tOperation string                 `json:\"operation\"`\n\tVariables map[string]interface{} `json:\"variables\"`\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/graphql\", func(w http.ResponseWriter, req *http.Request) {\n\t\tvar p postData\n\t\tif err := json.NewDecoder(req.Body).Decode(&p); err != nil {\n\t\t\tw.WriteHeader(400)\n\t\t\treturn\n\t\t}\n\t\tresult := graphql.Do(graphql.Params{\n\t\t\tContext:        req.Context(),\n\t\t\tSchema:         schema.TodoSchema,\n\t\t\tRequestString:  p.Query,\n\t\t\tVariableValues: p.Variables,\n\t\t\tOperationName:  p.Operation,\n\t\t})\n\t\tif err := json.NewEncoder(w).Encode(result); err != nil {\n\t\t\tfmt.Printf(\"could not write result to response: %s\", err)\n\t\t}\n\t})\n\n\tfmt.Println(\"Now server is running on port 8080\")\n\n\tfmt.Println(\"\")\n\n\tfmt.Println(`Get single todo:\ncurl \\\n-X POST \\\n-H \"Content-Type: application\/json\" \\\n--data '{ \"query\": \"{ todo(id:\\\"b\\\") { id text done } }\" }' \\\nhttp:\/\/localhost:8080\/graphql`)\n\n\tfmt.Println(\"\")\n\n\tfmt.Println(`Create new todo:\ncurl \\\n-X POST \\\n-H \"Content-Type: application\/json\" \\\n--data '{ \"query\": \"mutation { createTodo(text:\\\"My New todo\\\") { id text done } }\" }' \\\nhttp:\/\/localhost:8080\/graphql`)\n\n\tfmt.Println(\"\")\n\n\tfmt.Println(`Update todo:\ncurl \\\n-X POST \\\n-H \"Content-Type: application\/json\" \\\n--data '{ \"query\": \"mutation { updateTodo(id:\\\"a\\\", done: true) { id text done } }\" }' \\\nhttp:\/\/localhost:8080\/graphql`)\n\n\tfmt.Println(\"\")\n\n\tfmt.Println(`Load todo list:\ncurl \\\n-X POST \\\n-H \"Content-Type: application\/json\" \\\n--data '{ \"query\": \"{ todoList { id text done } }\" }' \\\nhttp:\/\/localhost:8080\/graphql`)\n\n\thttp.ListenAndServe(\":8080\", nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package presilo\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/*\n  Generates valid CSharp code for a given schema.\n\n\tC# code contains DataContractJsonSerializer annotations,\n\twhich are required for proper serialization\/deserialization of fields.\n\tUnfortunately this isn't available before .NET 4.5, so any generated code\n\twill need to be compiled with .NET 4.5+\n*\/\nfunc GenerateCSharp(schema *ObjectSchema, module string, tabstyle string) string {\n\n\tvar buffer *BufferedFormatString\n\n\tbuffer = NewBufferedFormatString(tabstyle)\n\n\tgenerateCSharpImports(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpNamespace(schema, buffer, module)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpTypeDeclaration(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpConstructor(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpFunctions(schema, buffer)\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\n\treturn buffer.String()\n}\n\nfunc ValidateCSharpModule(module string) bool {\n\n\tpattern := \"^[a-zA-Z_]+[0-9a-zA-Z_]*(\\\\.[a-zA-Z_]+[0-9a-zA-Z_]*)*$\"\n\tmatched, err := regexp.MatchString(pattern, module)\n\treturn err == nil && matched\n}\n\nfunc generateCSharpImports(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tbuffer.Print(\"using System;\")\n\tbuffer.Print(\"\\n using System.Runtime.Serialization;\")\n\n\t\/\/ import regex if we need it\n\tif containsRegexpMatch(schema) {\n\t\tbuffer.Print(\"\\nusing System.Text.RegularExpressions;\")\n\t}\n\n\tbuffer.Print(\"\\n\")\n}\n\nfunc generateCSharpNamespace(schema *ObjectSchema, buffer *BufferedFormatString, module string) {\n\n\tbuffer.Printf(\"namespace %s\\n{\", module)\n\tbuffer.AddIndentation(1)\n}\n\nfunc generateCSharpTypeDeclaration(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar propertyName string\n\n\tbuffer.Print(\"[DataContract]\")\n\tbuffer.Printf(\"\\npublic class %s\\n{\", ToCamelCase(schema.Title))\n\tbuffer.AddIndentation(1)\n\n\tfor _, propertyName = range schema.GetOrderedPropertyNames() {\n\n\t\tsubschema = schema.Properties[propertyName]\n\n\t\tbuffer.Printf(\"\\n[DataMember(Name = \\\"%s\\\")]\", propertyName)\n\t\tbuffer.Printf(\"\\nprotected %s %s;\", GenerateCSharpTypeForSchema(subschema), ToJavaCase(propertyName))\n\t}\n}\n\nfunc generateCSharpConstructor(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar declarations, setters []string\n\tvar propertyName string\n\tvar toWrite string\n\n\tbuffer.Printf(\"\\npublic %s(\", ToCamelCase(schema.Title))\n\n\tfor _, propertyName = range schema.RequiredProperties {\n\n\t\tsubschema = schema.Properties[propertyName]\n\t\tpropertyName = ToJavaCase(propertyName)\n\n\t\ttoWrite = fmt.Sprintf(\"%s %s\", GenerateCSharpTypeForSchema(subschema), propertyName)\n\t\tdeclarations = append(declarations, toWrite)\n\n\t\ttoWrite = fmt.Sprintf(\"\\nset%s(%s);\", ToStrictCamelCase(propertyName), propertyName)\n\t\tsetters = append(setters, toWrite)\n\t}\n\n\tbuffer.Print(strings.Join(declarations, \",\"))\n\tbuffer.Print(\")\\n{\")\n\tbuffer.AddIndentation(1)\n\n\tfor _, setter := range setters {\n\t\tbuffer.Print(setter)\n\t}\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\nfunc generateCSharpFunctions(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar propertyName, properName, camelName, typeName string\n\n\tfor _, propertyName = range schema.GetOrderedPropertyNames() {\n\n\t\tsubschema = schema.Properties[propertyName]\n\n\t\tproperName = ToJavaCase(propertyName)\n\t\tcamelName = ToStrictCamelCase(propertyName)\n\t\ttypeName = GenerateCSharpTypeForSchema(subschema)\n\n\t\t\/\/ getter\n\t\tbuffer.Printf(\"\\npublic %s get%s()\\n{\", typeName, camelName)\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nreturn this.%s;\", properName)\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\")\n\n\t\t\/\/ setter\n\t\tbuffer.Printf(\"\\npublic void set%s(%s value)\\n{\", camelName, typeName)\n\t\tbuffer.AddIndentation(1)\n\n\t\tswitch subschema.GetSchemaType() {\n\t\tcase SCHEMATYPE_STRING:\n\t\t\tgenerateCSharpStringSetter(subschema.(*StringSchema), buffer)\n\t\tcase SCHEMATYPE_INTEGER:\n\t\t\tfallthrough\n\t\tcase SCHEMATYPE_NUMBER:\n\t\t\tgenerateCSharpNumericSetter(subschema.(NumericSchemaType), buffer)\n\t\tcase SCHEMATYPE_OBJECT:\n\t\t\tgenerateCSharpObjectSetter(subschema.(*ObjectSchema), buffer)\n\t\tcase SCHEMATYPE_ARRAY:\n\t\t\tgenerateCSharpArraySetter(subschema.(*ArraySchema), buffer)\n\t\t}\n\n\t\tbuffer.Printf(\"\\n%s = value;\", properName)\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\\n\")\n\t}\n}\n\nfunc generateCSharpStringSetter(schema *StringSchema, buffer *BufferedFormatString) {\n\n\tif !schema.Nullable {\n\t\tgenerateCSharpNullCheck(buffer)\n\t}\n\n\tif schema.MinLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MinLength, \"value.Length\", \"was shorter than allowable minimum\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MaxLength, \"value.Length\", \"was longer than allowable maximum\", \"%d\", false, \">\", \"\", buffer)\n\t}\n\n\tif schema.MinByteLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MinByteLength, \"value.Length * sizeof(Char)\", \"had fewer bytes than allowable minimum\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxByteLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MaxByteLength, \"value.Length * sizeof(Char)\", \"had more bytes than allowable minimum\", \"%d\", false, \">\", \"\", buffer)\n\t}\n\n\tif schema.Pattern != nil {\n\n\t\tbuffer.Printf(\"\\nRegex regex = new Regex(\\\"%s\\\");\", sanitizeQuotedString(*schema.Pattern))\n\t\tbuffer.Printf(\"\\nif(!regex.IsMatch(value))\\n{\")\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nthrow new Exception(\\\"Value '\\\"+value+\\\"' did not match pattern '%s'\\\");\", *schema.Pattern)\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\")\n\t}\n}\n\nfunc generateCSharpNumericSetter(schema NumericSchemaType, buffer *BufferedFormatString) {\n\n\tif schema.HasMinimum() {\n\t\tgenerateCSharpRangeCheck(schema.GetMinimum(), \"value\", \"is under the allowable minimum\", schema.GetConstraintFormat(), schema.IsExclusiveMinimum(), \"<=\", \"<\", buffer)\n\t}\n\n\tif schema.HasMaximum() {\n\t\tgenerateCSharpRangeCheck(schema.GetMaximum(), \"value\", \"is over the allowable maximum\", schema.GetConstraintFormat(), schema.IsExclusiveMaximum(), \">=\", \">\", buffer)\n\t}\n\n\tif schema.HasEnum() {\n\t\tgenerateCSharpEnumCheck(schema, buffer, schema.GetEnum(), \"\", \"\")\n\t}\n\n\tif schema.HasMultiple() {\n\n\t\tbuffer.Printf(\"\\nif(value %% %f != 0)\\n{\", schema.GetMultiple())\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nthrow new Exception(\\\"Property '\\\"+value+\\\"' was not a multiple of %s\\\");\", schema.GetMultiple())\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\\n\")\n\t}\n}\n\nfunc generateCSharpObjectSetter(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tif !schema.Nullable {\n\t\tgenerateCSharpNullCheck(buffer)\n\t}\n}\n\nfunc generateCSharpArraySetter(schema *ArraySchema, buffer *BufferedFormatString) {\n\n\tif !schema.Nullable {\n\t\tgenerateCSharpNullCheck(buffer)\n\t}\n\n\tif schema.MinItems != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MinItems, \"value.Length\", \"does not have enough items\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxItems != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MaxItems, \"value.Length\", \"does not have enough items\", \"%d\", false, \">\", \"\", buffer)\n\t}\n}\n\nfunc generateCSharpNullCheck(buffer *BufferedFormatString) {\n\n\tbuffer.Printf(\"\\nif(value == null)\\n{\")\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Print(\"\\nthrow new NullReferenceException(\\\"Cannot set property to null value\\\");\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\nfunc generateCSharpRangeCheck(value interface{}, reference, message, format string, exclusive bool, comparator, exclusiveComparator string, buffer *BufferedFormatString) {\n\n\tvar compareString string\n\n\tif exclusive {\n\t\tcompareString = exclusiveComparator\n\t} else {\n\t\tcompareString = comparator\n\t}\n\n\tbuffer.Printf(\"\\nif(%s %s \"+format+\")\\n{\", reference, compareString, value)\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Printf(\"\\nthrow new Exception(\\\"Property '\\\"+value+\\\"' %s.\\\");\", message)\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\n\/*\n\tGenerates code which throws an error if the given [parameter]'s value is not contained in the given [validValues].\n*\/\nfunc generateCSharpEnumCheck(schema TypeSchema, buffer *BufferedFormatString, enumValues []interface{}, prefix string, postfix string) {\n\n\tvar typeName string\n\tvar length int\n\n\tlength = len(enumValues)\n\n\tif length <= 0 {\n\t\treturn\n\t}\n\n\t\/\/ write array of valid values\n\ttypeName = GenerateCSharpTypeForSchema(schema)\n\tbuffer.Printf(\"%s[] validValues = new %s[]{%s%v%s\", typeName, typeName, prefix, enumValues[0], postfix)\n\n\tfor _, enumValue := range enumValues[1:length] {\n\t\tbuffer.Printf(\",%s%v%s\", prefix, enumValue, postfix)\n\t}\n\n\tbuffer.Print(\"};\\n\")\n\n\t\/\/ compare\n\tbuffer.Print(\"\\nbool isValid = false;\")\n\tbuffer.Print(\"\\nfor(int i = 0; i < validValues.Length; i++)\\n{\")\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Print(\"\\nif(validValues[i] == value)\\n{\")\n\tbuffer.AddIndentation(1)\n\tbuffer.Print(\"\\nisValid = true;\\nbreak;\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\n\tbuffer.Print(\"\\nif(!isValid)\\n{\")\n\tbuffer.AddIndentation(1)\n\tbuffer.Print(\"\\nthrow new Exception(\\\"Given value '\\\"+value+\\\"' was not found in list of acceptable values\\\");\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\nfunc GenerateCSharpTypeForSchema(subschema TypeSchema) string {\n\n\tswitch subschema.GetSchemaType() {\n\tcase SCHEMATYPE_NUMBER:\n\t\treturn \"double\"\n\tcase SCHEMATYPE_INTEGER:\n\t\treturn \"int\"\n\tcase SCHEMATYPE_ARRAY:\n\t\treturn ToCamelCase(subschema.(*ArraySchema).Items.GetTitle()) + \"[]\"\n\tcase SCHEMATYPE_OBJECT:\n\t\treturn ToCamelCase(subschema.GetTitle())\n\tcase SCHEMATYPE_STRING:\n\t\treturn \"string\"\n\tcase SCHEMATYPE_BOOLEAN:\n\t\treturn \"bool\"\n\t}\n\n\treturn \"Object\"\n}\n<commit_msg>Fixed bug with cs codegen where member names of 'value' would not be written in setter<commit_after>package presilo\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/*\n  Generates valid CSharp code for a given schema.\n\n\tC# code contains DataContractJsonSerializer annotations,\n\twhich are required for proper serialization\/deserialization of fields.\n\tUnfortunately this isn't available before .NET 4.5, so any generated code\n\twill need to be compiled with .NET 4.5+\n*\/\nfunc GenerateCSharp(schema *ObjectSchema, module string, tabstyle string) string {\n\n\tvar buffer *BufferedFormatString\n\n\tbuffer = NewBufferedFormatString(tabstyle)\n\n\tgenerateCSharpImports(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpNamespace(schema, buffer, module)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpTypeDeclaration(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpConstructor(schema, buffer)\n\tbuffer.Print(\"\\n\")\n\tgenerateCSharpFunctions(schema, buffer)\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\n\treturn buffer.String()\n}\n\nfunc ValidateCSharpModule(module string) bool {\n\n\tpattern := \"^[a-zA-Z_]+[0-9a-zA-Z_]*(\\\\.[a-zA-Z_]+[0-9a-zA-Z_]*)*$\"\n\tmatched, err := regexp.MatchString(pattern, module)\n\treturn err == nil && matched\n}\n\nfunc generateCSharpImports(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tbuffer.Print(\"using System;\")\n\tbuffer.Print(\"\\n using System.Runtime.Serialization;\")\n\n\t\/\/ import regex if we need it\n\tif containsRegexpMatch(schema) {\n\t\tbuffer.Print(\"\\nusing System.Text.RegularExpressions;\")\n\t}\n\n\tbuffer.Print(\"\\n\")\n}\n\nfunc generateCSharpNamespace(schema *ObjectSchema, buffer *BufferedFormatString, module string) {\n\n\tbuffer.Printf(\"namespace %s\\n{\", module)\n\tbuffer.AddIndentation(1)\n}\n\nfunc generateCSharpTypeDeclaration(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar propertyName string\n\n\tbuffer.Print(\"[DataContract]\")\n\tbuffer.Printf(\"\\npublic class %s\\n{\", ToCamelCase(schema.Title))\n\tbuffer.AddIndentation(1)\n\n\tfor _, propertyName = range schema.GetOrderedPropertyNames() {\n\n\t\tsubschema = schema.Properties[propertyName]\n\n\t\tbuffer.Printf(\"\\n[DataMember(Name = \\\"%s\\\")]\", propertyName)\n\t\tbuffer.Printf(\"\\nprotected %s %s;\", GenerateCSharpTypeForSchema(subschema), ToJavaCase(propertyName))\n\t}\n}\n\nfunc generateCSharpConstructor(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar declarations, setters []string\n\tvar propertyName string\n\tvar toWrite string\n\n\tbuffer.Printf(\"\\npublic %s(\", ToCamelCase(schema.Title))\n\n\tfor _, propertyName = range schema.RequiredProperties {\n\n\t\tsubschema = schema.Properties[propertyName]\n\t\tpropertyName = ToJavaCase(propertyName)\n\n\t\ttoWrite = fmt.Sprintf(\"%s %s\", GenerateCSharpTypeForSchema(subschema), propertyName)\n\t\tdeclarations = append(declarations, toWrite)\n\n\t\ttoWrite = fmt.Sprintf(\"\\nset%s(%s);\", ToStrictCamelCase(propertyName), propertyName)\n\t\tsetters = append(setters, toWrite)\n\t}\n\n\tbuffer.Print(strings.Join(declarations, \",\"))\n\tbuffer.Print(\")\\n{\")\n\tbuffer.AddIndentation(1)\n\n\tfor _, setter := range setters {\n\t\tbuffer.Print(setter)\n\t}\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\nfunc generateCSharpFunctions(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tvar subschema TypeSchema\n\tvar propertyName, properName, camelName, typeName string\n\n\tfor _, propertyName = range schema.GetOrderedPropertyNames() {\n\n\t\tsubschema = schema.Properties[propertyName]\n\n\t\tproperName = ToJavaCase(propertyName)\n\t\tcamelName = ToStrictCamelCase(propertyName)\n\t\ttypeName = GenerateCSharpTypeForSchema(subschema)\n\n\t\t\/\/ getter\n\t\tbuffer.Printf(\"\\npublic %s get%s()\\n{\", typeName, camelName)\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nreturn this.%s;\", properName)\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\")\n\n\t\t\/\/ setter\n\t\tbuffer.Printf(\"\\npublic void set%s(%s value)\\n{\", camelName, typeName)\n\t\tbuffer.AddIndentation(1)\n\n\t\tswitch subschema.GetSchemaType() {\n\t\tcase SCHEMATYPE_STRING:\n\t\t\tgenerateCSharpStringSetter(subschema.(*StringSchema), buffer)\n\t\tcase SCHEMATYPE_INTEGER:\n\t\t\tfallthrough\n\t\tcase SCHEMATYPE_NUMBER:\n\t\t\tgenerateCSharpNumericSetter(subschema.(NumericSchemaType), buffer)\n\t\tcase SCHEMATYPE_OBJECT:\n\t\t\tgenerateCSharpObjectSetter(subschema.(*ObjectSchema), buffer)\n\t\tcase SCHEMATYPE_ARRAY:\n\t\t\tgenerateCSharpArraySetter(subschema.(*ArraySchema), buffer)\n\t\t}\n\n\t\tbuffer.Printf(\"\\nthis.%s = value;\", properName)\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\\n\")\n\t}\n}\n\nfunc generateCSharpStringSetter(schema *StringSchema, buffer *BufferedFormatString) {\n\n\tif !schema.Nullable {\n\t\tgenerateCSharpNullCheck(buffer)\n\t}\n\n\tif schema.MinLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MinLength, \"value.Length\", \"was shorter than allowable minimum\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MaxLength, \"value.Length\", \"was longer than allowable maximum\", \"%d\", false, \">\", \"\", buffer)\n\t}\n\n\tif schema.MinByteLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MinByteLength, \"value.Length * sizeof(Char)\", \"had fewer bytes than allowable minimum\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxByteLength != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MaxByteLength, \"value.Length * sizeof(Char)\", \"had more bytes than allowable minimum\", \"%d\", false, \">\", \"\", buffer)\n\t}\n\n\tif schema.Pattern != nil {\n\n\t\tbuffer.Printf(\"\\nRegex regex = new Regex(\\\"%s\\\");\", sanitizeQuotedString(*schema.Pattern))\n\t\tbuffer.Printf(\"\\nif(!regex.IsMatch(value))\\n{\")\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nthrow new Exception(\\\"Value '\\\"+value+\\\"' did not match pattern '%s'\\\");\", *schema.Pattern)\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\")\n\t}\n}\n\nfunc generateCSharpNumericSetter(schema NumericSchemaType, buffer *BufferedFormatString) {\n\n\tif schema.HasMinimum() {\n\t\tgenerateCSharpRangeCheck(schema.GetMinimum(), \"value\", \"is under the allowable minimum\", schema.GetConstraintFormat(), schema.IsExclusiveMinimum(), \"<=\", \"<\", buffer)\n\t}\n\n\tif schema.HasMaximum() {\n\t\tgenerateCSharpRangeCheck(schema.GetMaximum(), \"value\", \"is over the allowable maximum\", schema.GetConstraintFormat(), schema.IsExclusiveMaximum(), \">=\", \">\", buffer)\n\t}\n\n\tif schema.HasEnum() {\n\t\tgenerateCSharpEnumCheck(schema, buffer, schema.GetEnum(), \"\", \"\")\n\t}\n\n\tif schema.HasMultiple() {\n\n\t\tbuffer.Printf(\"\\nif(value %% %f != 0)\\n{\", schema.GetMultiple())\n\t\tbuffer.AddIndentation(1)\n\n\t\tbuffer.Printf(\"\\nthrow new Exception(\\\"Property '\\\"+value+\\\"' was not a multiple of %s\\\");\", schema.GetMultiple())\n\n\t\tbuffer.AddIndentation(-1)\n\t\tbuffer.Print(\"\\n}\\n\")\n\t}\n}\n\nfunc generateCSharpObjectSetter(schema *ObjectSchema, buffer *BufferedFormatString) {\n\n\tif !schema.Nullable {\n\t\tgenerateCSharpNullCheck(buffer)\n\t}\n}\n\nfunc generateCSharpArraySetter(schema *ArraySchema, buffer *BufferedFormatString) {\n\n\tif !schema.Nullable {\n\t\tgenerateCSharpNullCheck(buffer)\n\t}\n\n\tif schema.MinItems != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MinItems, \"value.Length\", \"does not have enough items\", \"%d\", false, \"<\", \"\", buffer)\n\t}\n\n\tif schema.MaxItems != nil {\n\t\tgenerateCSharpRangeCheck(*schema.MaxItems, \"value.Length\", \"does not have enough items\", \"%d\", false, \">\", \"\", buffer)\n\t}\n}\n\nfunc generateCSharpNullCheck(buffer *BufferedFormatString) {\n\n\tbuffer.Printf(\"\\nif(value == null)\\n{\")\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Print(\"\\nthrow new NullReferenceException(\\\"Cannot set property to null value\\\");\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\nfunc generateCSharpRangeCheck(value interface{}, reference, message, format string, exclusive bool, comparator, exclusiveComparator string, buffer *BufferedFormatString) {\n\n\tvar compareString string\n\n\tif exclusive {\n\t\tcompareString = exclusiveComparator\n\t} else {\n\t\tcompareString = comparator\n\t}\n\n\tbuffer.Printf(\"\\nif(%s %s \"+format+\")\\n{\", reference, compareString, value)\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Printf(\"\\nthrow new Exception(\\\"Property '\\\"+value+\\\"' %s.\\\");\", message)\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\n\/*\n\tGenerates code which throws an error if the given [parameter]'s value is not contained in the given [validValues].\n*\/\nfunc generateCSharpEnumCheck(schema TypeSchema, buffer *BufferedFormatString, enumValues []interface{}, prefix string, postfix string) {\n\n\tvar typeName string\n\tvar length int\n\n\tlength = len(enumValues)\n\n\tif length <= 0 {\n\t\treturn\n\t}\n\n\t\/\/ write array of valid values\n\ttypeName = GenerateCSharpTypeForSchema(schema)\n\tbuffer.Printf(\"%s[] validValues = new %s[]{%s%v%s\", typeName, typeName, prefix, enumValues[0], postfix)\n\n\tfor _, enumValue := range enumValues[1:length] {\n\t\tbuffer.Printf(\",%s%v%s\", prefix, enumValue, postfix)\n\t}\n\n\tbuffer.Print(\"};\\n\")\n\n\t\/\/ compare\n\tbuffer.Print(\"\\nbool isValid = false;\")\n\tbuffer.Print(\"\\nfor(int i = 0; i < validValues.Length; i++)\\n{\")\n\tbuffer.AddIndentation(1)\n\n\tbuffer.Print(\"\\nif(validValues[i] == value)\\n{\")\n\tbuffer.AddIndentation(1)\n\tbuffer.Print(\"\\nisValid = true;\\nbreak;\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\")\n\n\tbuffer.Print(\"\\nif(!isValid)\\n{\")\n\tbuffer.AddIndentation(1)\n\tbuffer.Print(\"\\nthrow new Exception(\\\"Given value '\\\"+value+\\\"' was not found in list of acceptable values\\\");\")\n\n\tbuffer.AddIndentation(-1)\n\tbuffer.Print(\"\\n}\\n\")\n}\n\nfunc GenerateCSharpTypeForSchema(subschema TypeSchema) string {\n\n\tswitch subschema.GetSchemaType() {\n\tcase SCHEMATYPE_NUMBER:\n\t\treturn \"double\"\n\tcase SCHEMATYPE_INTEGER:\n\t\treturn \"int\"\n\tcase SCHEMATYPE_ARRAY:\n\t\treturn ToCamelCase(subschema.(*ArraySchema).Items.GetTitle()) + \"[]\"\n\tcase SCHEMATYPE_OBJECT:\n\t\treturn ToCamelCase(subschema.GetTitle())\n\tcase SCHEMATYPE_STRING:\n\t\treturn \"string\"\n\tcase SCHEMATYPE_BOOLEAN:\n\t\treturn \"bool\"\n\t}\n\n\treturn \"Object\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package locking\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strconv\"\n\n\t\"github.com\/git-lfs\/git-lfs\/git\"\n\t\"github.com\/git-lfs\/git-lfs\/lfsapi\"\n\t\"github.com\/git-lfs\/git-lfs\/lfshttp\"\n)\n\ntype lockClient struct {\n\t*lfsapi.Client\n}\n\ntype lockRef struct {\n\tName string `json:\"name,omitempty\"`\n}\n\n\/\/ LockRequest encapsulates the payload sent across the API when a client would\n\/\/ like to obtain a lock against a particular path on a given remote.\ntype lockRequest struct {\n\t\/\/ Path is the path that the client would like to obtain a lock against.\n\tPath string   `json:\"path\"`\n\tRef  *lockRef `json:\"ref,omitempty\"`\n}\n\n\/\/ LockResponse encapsulates the information sent over the API in response to\n\/\/ a `LockRequest`.\ntype lockResponse struct {\n\t\/\/ Lock is the Lock that was optionally created in response to the\n\t\/\/ payload that was sent (see above). If the lock already exists, then\n\t\/\/ the existing lock is sent in this field instead, and the author of\n\t\/\/ that lock remains the same, meaning that the client failed to obtain\n\t\/\/ that lock. An HTTP status of \"409 - Conflict\" is used here.\n\t\/\/\n\t\/\/ If the lock was unable to be created, this field will hold the\n\t\/\/ zero-value of Lock and the Err field will provide a more detailed set\n\t\/\/ of information.\n\t\/\/\n\t\/\/ If an error was experienced in creating this lock, then the\n\t\/\/ zero-value of Lock should be sent here instead.\n\tLock *Lock `json:\"lock\"`\n\n\t\/\/ Message is the optional error that was encountered while trying to create\n\t\/\/ the above lock.\n\tMessage          string `json:\"message,omitempty\"`\n\tDocumentationURL string `json:\"documentation_url,omitempty\"`\n\tRequestID        string `json:\"request_id,omitempty\"`\n}\n\nfunc (c *lockClient) Lock(remote string, lockReq *lockRequest) (*lockResponse, *http.Response, error) {\n\te := c.Endpoints.Endpoint(\"upload\", remote)\n\treq, err := c.NewRequest(\"POST\", e, \"locks\", lockReq)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq = c.Client.LogRequest(req, \"lfs.locks.lock\")\n\tres, err := c.DoAPIRequestWithAuth(remote, req)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\n\tlockRes := &lockResponse{}\n\treturn lockRes, res, lfshttp.DecodeJSON(res, lockRes)\n}\n\n\/\/ UnlockRequest encapsulates the data sent in an API request to remove a lock.\ntype unlockRequest struct {\n\t\/\/ Force determines whether or not the lock should be \"forcibly\"\n\t\/\/ unlocked; that is to say whether or not a given individual should be\n\t\/\/ able to break a different individual's lock.\n\tForce bool     `json:\"force\"`\n\tRef   *lockRef `json:\"ref,omitempty\"`\n}\n\n\/\/ UnlockResponse is the result sent back from the API when asked to remove a\n\/\/ lock.\ntype unlockResponse struct {\n\t\/\/ Lock is the lock corresponding to the asked-about lock in the\n\t\/\/ `UnlockPayload` (see above). If no matching lock was found, this\n\t\/\/ field will take the zero-value of Lock, and Err will be non-nil.\n\tLock *Lock `json:\"lock\"`\n\n\t\/\/ Message is an optional field which holds any error that was experienced\n\t\/\/ while removing the lock.\n\tMessage          string `json:\"message,omitempty\"`\n\tDocumentationURL string `json:\"documentation_url,omitempty\"`\n\tRequestID        string `json:\"request_id,omitempty\"`\n}\n\nfunc (c *lockClient) Unlock(ref *git.Ref, remote, id string, force bool) (*unlockResponse, *http.Response, error) {\n\te := c.Endpoints.Endpoint(\"upload\", remote)\n\tsuffix := fmt.Sprintf(\"locks\/%s\/unlock\", id)\n\treq, err := c.NewRequest(\"POST\", e, suffix, &unlockRequest{\n\t\tForce: force,\n\t\tRef:   &lockRef{Name: ref.Refspec()},\n\t})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq = c.Client.LogRequest(req, \"lfs.locks.unlock\")\n\tres, err := c.DoAPIRequestWithAuth(remote, req)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\n\tunlockRes := &unlockResponse{}\n\terr = lfshttp.DecodeJSON(res, unlockRes)\n\treturn unlockRes, res, err\n}\n\n\/\/ Filter represents a single qualifier to apply against a set of locks.\ntype lockFilter struct {\n\t\/\/ Property is the property to search against.\n\t\/\/ Value is the value that the property must take.\n\tProperty, Value string\n}\n\n\/\/ LockSearchRequest encapsulates the request sent to the server when the client\n\/\/ would like a list of locks that match the given criteria.\ntype lockSearchRequest struct {\n\t\/\/ Filters is the set of filters to query against. If the client wishes\n\t\/\/ to obtain a list of all locks, an empty array should be passed here.\n\tFilters []lockFilter\n\t\/\/ Cursor is an optional field used to tell the server which lock was\n\t\/\/ seen last, if scanning through multiple pages of results.\n\t\/\/\n\t\/\/ Servers must return a list of locks sorted in reverse chronological\n\t\/\/ order, so the Cursor provides a consistent method of viewing all\n\t\/\/ locks, even if more were created between two requests.\n\tCursor string\n\t\/\/ Limit is the maximum number of locks to return in a single page.\n\tLimit int\n\n\tRefspec string\n}\n\nfunc (r *lockSearchRequest) QueryValues() map[string]string {\n\tq := make(map[string]string)\n\tfor _, filter := range r.Filters {\n\t\tq[filter.Property] = filter.Value\n\t}\n\n\tif len(r.Cursor) > 0 {\n\t\tq[\"cursor\"] = r.Cursor\n\t}\n\n\tif r.Limit > 0 {\n\t\tq[\"limit\"] = strconv.Itoa(r.Limit)\n\t}\n\n\tif len(r.Refspec) > 0 {\n\t\tq[\"refspec\"] = r.Refspec\n\t}\n\n\treturn q\n}\n\n\/\/ LockList encapsulates a set of Locks.\ntype lockList struct {\n\t\/\/ Locks is the set of locks returned back, typically matching the query\n\t\/\/ parameters sent in the LockListRequest call. If no locks were matched\n\t\/\/ from a given query, then `Locks` will be represented as an empty\n\t\/\/ array.\n\tLocks []Lock `json:\"locks\"`\n\t\/\/ NextCursor returns the Id of the Lock the client should update its\n\t\/\/ cursor to, if there are multiple pages of results for a particular\n\t\/\/ `LockListRequest`.\n\tNextCursor string `json:\"next_cursor,omitempty\"`\n\t\/\/ Message populates any error that was encountered during the search. If no\n\t\/\/ error was encountered and the operation was successful, then a value\n\t\/\/ of nil will be passed here.\n\tMessage          string `json:\"message,omitempty\"`\n\tDocumentationURL string `json:\"documentation_url,omitempty\"`\n\tRequestID        string `json:\"request_id,omitempty\"`\n}\n\nfunc (c *lockClient) Search(remote string, searchReq *lockSearchRequest) (*lockList, *http.Response, error) {\n\te := c.Endpoints.Endpoint(\"download\", remote)\n\treq, err := c.NewRequest(\"GET\", e, \"locks\", nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tq := req.URL.Query()\n\tfor key, value := range searchReq.QueryValues() {\n\t\tq.Add(key, value)\n\t}\n\treq.URL.RawQuery = q.Encode()\n\n\treq = c.Client.LogRequest(req, \"lfs.locks.search\")\n\tres, err := c.DoAPIRequestWithAuth(remote, req)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\n\tlocks := &lockList{}\n\tif res.StatusCode == http.StatusOK {\n\t\terr = lfshttp.DecodeJSON(res, locks)\n\t}\n\n\treturn locks, res, err\n}\n\n\/\/ lockVerifiableRequest encapsulates the request sent to the server when the\n\/\/ client would like a list of locks to verify a Git push.\ntype lockVerifiableRequest struct {\n\tRef *lockRef `json:\"ref,omitempty\"`\n\n\t\/\/ Cursor is an optional field used to tell the server which lock was\n\t\/\/ seen last, if scanning through multiple pages of results.\n\t\/\/\n\t\/\/ Servers must return a list of locks sorted in reverse chronological\n\t\/\/ order, so the Cursor provides a consistent method of viewing all\n\t\/\/ locks, even if more were created between two requests.\n\tCursor string `json:\"cursor,omitempty\"`\n\t\/\/ Limit is the maximum number of locks to return in a single page.\n\tLimit int `json:\"limit,omitempty\"`\n}\n\n\/\/ lockVerifiableList encapsulates a set of Locks to verify a Git push.\ntype lockVerifiableList struct {\n\t\/\/ Ours is the set of locks returned back matching filenames that the user\n\t\/\/ is allowed to edit.\n\tOurs []Lock `json:\"ours\"`\n\n\t\/\/ Their is the set of locks returned back matching filenames that the user\n\t\/\/ is NOT allowed to edit. Any edits matching these files should reject\n\t\/\/ the Git push.\n\tTheirs []Lock `json:\"theirs\"`\n\n\t\/\/ NextCursor returns the Id of the Lock the client should update its\n\t\/\/ cursor to, if there are multiple pages of results for a particular\n\t\/\/ `LockListRequest`.\n\tNextCursor string `json:\"next_cursor,omitempty\"`\n\t\/\/ Message populates any error that was encountered during the search. If no\n\t\/\/ error was encountered and the operation was successful, then a value\n\t\/\/ of nil will be passed here.\n\tMessage          string `json:\"message,omitempty\"`\n\tDocumentationURL string `json:\"documentation_url,omitempty\"`\n\tRequestID        string `json:\"request_id,omitempty\"`\n}\n\nfunc (c *lockClient) SearchVerifiable(remote string, vreq *lockVerifiableRequest) (*lockVerifiableList, *http.Response, error) {\n\te := c.Endpoints.Endpoint(\"upload\", remote)\n\treq, err := c.NewRequest(\"POST\", e, \"locks\/verify\", vreq)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq = c.Client.LogRequest(req, \"lfs.locks.verify\")\n\tres, err := c.DoAPIRequestWithAuth(remote, req)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\n\tlocks := &lockVerifiableList{}\n\tif res.StatusCode == http.StatusOK {\n\t\terr = lfshttp.DecodeJSON(res, locks)\n\t}\n\n\treturn locks, res, err\n}\n\n\/\/ User represents the owner of a lock.\ntype User struct {\n\t\/\/ Name is the name of the individual who would like to obtain the\n\t\/\/ lock, for instance: \"Rick Sanchez\".\n\tName string `json:\"name\"`\n}\n\nfunc NewUser(name string) *User {\n\treturn &User{Name: name}\n}\n\n\/\/ String implements the fmt.Stringer interface.\nfunc (u *User) String() string {\n\treturn u.Name\n}\n<commit_msg>locking: avoid nil pointer dereference with invalid response<commit_after>package locking\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strconv\"\n\n\t\"github.com\/git-lfs\/git-lfs\/git\"\n\t\"github.com\/git-lfs\/git-lfs\/lfsapi\"\n\t\"github.com\/git-lfs\/git-lfs\/lfshttp\"\n)\n\ntype lockClient struct {\n\t*lfsapi.Client\n}\n\ntype lockRef struct {\n\tName string `json:\"name,omitempty\"`\n}\n\n\/\/ LockRequest encapsulates the payload sent across the API when a client would\n\/\/ like to obtain a lock against a particular path on a given remote.\ntype lockRequest struct {\n\t\/\/ Path is the path that the client would like to obtain a lock against.\n\tPath string   `json:\"path\"`\n\tRef  *lockRef `json:\"ref,omitempty\"`\n}\n\n\/\/ LockResponse encapsulates the information sent over the API in response to\n\/\/ a `LockRequest`.\ntype lockResponse struct {\n\t\/\/ Lock is the Lock that was optionally created in response to the\n\t\/\/ payload that was sent (see above). If the lock already exists, then\n\t\/\/ the existing lock is sent in this field instead, and the author of\n\t\/\/ that lock remains the same, meaning that the client failed to obtain\n\t\/\/ that lock. An HTTP status of \"409 - Conflict\" is used here.\n\t\/\/\n\t\/\/ If the lock was unable to be created, this field will hold the\n\t\/\/ zero-value of Lock and the Err field will provide a more detailed set\n\t\/\/ of information.\n\t\/\/\n\t\/\/ If an error was experienced in creating this lock, then the\n\t\/\/ zero-value of Lock should be sent here instead.\n\tLock *Lock `json:\"lock\"`\n\n\t\/\/ Message is the optional error that was encountered while trying to create\n\t\/\/ the above lock.\n\tMessage          string `json:\"message,omitempty\"`\n\tDocumentationURL string `json:\"documentation_url,omitempty\"`\n\tRequestID        string `json:\"request_id,omitempty\"`\n}\n\nfunc (c *lockClient) Lock(remote string, lockReq *lockRequest) (*lockResponse, *http.Response, error) {\n\te := c.Endpoints.Endpoint(\"upload\", remote)\n\treq, err := c.NewRequest(\"POST\", e, \"locks\", lockReq)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq = c.Client.LogRequest(req, \"lfs.locks.lock\")\n\tres, err := c.DoAPIRequestWithAuth(remote, req)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\n\tlockRes := &lockResponse{}\n\terr = lfshttp.DecodeJSON(res, lockRes)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\tif lockRes.Lock == nil && len(lockRes.Message) == 0 {\n\t\treturn nil, res, fmt.Errorf(\"invalid server response\")\n\t}\n\treturn lockRes, res, nil\n}\n\n\/\/ UnlockRequest encapsulates the data sent in an API request to remove a lock.\ntype unlockRequest struct {\n\t\/\/ Force determines whether or not the lock should be \"forcibly\"\n\t\/\/ unlocked; that is to say whether or not a given individual should be\n\t\/\/ able to break a different individual's lock.\n\tForce bool     `json:\"force\"`\n\tRef   *lockRef `json:\"ref,omitempty\"`\n}\n\n\/\/ UnlockResponse is the result sent back from the API when asked to remove a\n\/\/ lock.\ntype unlockResponse struct {\n\t\/\/ Lock is the lock corresponding to the asked-about lock in the\n\t\/\/ `UnlockPayload` (see above). If no matching lock was found, this\n\t\/\/ field will take the zero-value of Lock, and Err will be non-nil.\n\tLock *Lock `json:\"lock\"`\n\n\t\/\/ Message is an optional field which holds any error that was experienced\n\t\/\/ while removing the lock.\n\tMessage          string `json:\"message,omitempty\"`\n\tDocumentationURL string `json:\"documentation_url,omitempty\"`\n\tRequestID        string `json:\"request_id,omitempty\"`\n}\n\nfunc (c *lockClient) Unlock(ref *git.Ref, remote, id string, force bool) (*unlockResponse, *http.Response, error) {\n\te := c.Endpoints.Endpoint(\"upload\", remote)\n\tsuffix := fmt.Sprintf(\"locks\/%s\/unlock\", id)\n\treq, err := c.NewRequest(\"POST\", e, suffix, &unlockRequest{\n\t\tForce: force,\n\t\tRef:   &lockRef{Name: ref.Refspec()},\n\t})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq = c.Client.LogRequest(req, \"lfs.locks.unlock\")\n\tres, err := c.DoAPIRequestWithAuth(remote, req)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\n\tunlockRes := &unlockResponse{}\n\terr = lfshttp.DecodeJSON(res, unlockRes)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\tif unlockRes.Lock == nil && len(unlockRes.Message) == 0 {\n\t\treturn nil, res, fmt.Errorf(\"invalid server response\")\n\t}\n\treturn unlockRes, res, nil\n}\n\n\/\/ Filter represents a single qualifier to apply against a set of locks.\ntype lockFilter struct {\n\t\/\/ Property is the property to search against.\n\t\/\/ Value is the value that the property must take.\n\tProperty, Value string\n}\n\n\/\/ LockSearchRequest encapsulates the request sent to the server when the client\n\/\/ would like a list of locks that match the given criteria.\ntype lockSearchRequest struct {\n\t\/\/ Filters is the set of filters to query against. If the client wishes\n\t\/\/ to obtain a list of all locks, an empty array should be passed here.\n\tFilters []lockFilter\n\t\/\/ Cursor is an optional field used to tell the server which lock was\n\t\/\/ seen last, if scanning through multiple pages of results.\n\t\/\/\n\t\/\/ Servers must return a list of locks sorted in reverse chronological\n\t\/\/ order, so the Cursor provides a consistent method of viewing all\n\t\/\/ locks, even if more were created between two requests.\n\tCursor string\n\t\/\/ Limit is the maximum number of locks to return in a single page.\n\tLimit int\n\n\tRefspec string\n}\n\nfunc (r *lockSearchRequest) QueryValues() map[string]string {\n\tq := make(map[string]string)\n\tfor _, filter := range r.Filters {\n\t\tq[filter.Property] = filter.Value\n\t}\n\n\tif len(r.Cursor) > 0 {\n\t\tq[\"cursor\"] = r.Cursor\n\t}\n\n\tif r.Limit > 0 {\n\t\tq[\"limit\"] = strconv.Itoa(r.Limit)\n\t}\n\n\tif len(r.Refspec) > 0 {\n\t\tq[\"refspec\"] = r.Refspec\n\t}\n\n\treturn q\n}\n\n\/\/ LockList encapsulates a set of Locks.\ntype lockList struct {\n\t\/\/ Locks is the set of locks returned back, typically matching the query\n\t\/\/ parameters sent in the LockListRequest call. If no locks were matched\n\t\/\/ from a given query, then `Locks` will be represented as an empty\n\t\/\/ array.\n\tLocks []Lock `json:\"locks\"`\n\t\/\/ NextCursor returns the Id of the Lock the client should update its\n\t\/\/ cursor to, if there are multiple pages of results for a particular\n\t\/\/ `LockListRequest`.\n\tNextCursor string `json:\"next_cursor,omitempty\"`\n\t\/\/ Message populates any error that was encountered during the search. If no\n\t\/\/ error was encountered and the operation was successful, then a value\n\t\/\/ of nil will be passed here.\n\tMessage          string `json:\"message,omitempty\"`\n\tDocumentationURL string `json:\"documentation_url,omitempty\"`\n\tRequestID        string `json:\"request_id,omitempty\"`\n}\n\nfunc (c *lockClient) Search(remote string, searchReq *lockSearchRequest) (*lockList, *http.Response, error) {\n\te := c.Endpoints.Endpoint(\"download\", remote)\n\treq, err := c.NewRequest(\"GET\", e, \"locks\", nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tq := req.URL.Query()\n\tfor key, value := range searchReq.QueryValues() {\n\t\tq.Add(key, value)\n\t}\n\treq.URL.RawQuery = q.Encode()\n\n\treq = c.Client.LogRequest(req, \"lfs.locks.search\")\n\tres, err := c.DoAPIRequestWithAuth(remote, req)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\n\tlocks := &lockList{}\n\tif res.StatusCode == http.StatusOK {\n\t\terr = lfshttp.DecodeJSON(res, locks)\n\t}\n\n\treturn locks, res, err\n}\n\n\/\/ lockVerifiableRequest encapsulates the request sent to the server when the\n\/\/ client would like a list of locks to verify a Git push.\ntype lockVerifiableRequest struct {\n\tRef *lockRef `json:\"ref,omitempty\"`\n\n\t\/\/ Cursor is an optional field used to tell the server which lock was\n\t\/\/ seen last, if scanning through multiple pages of results.\n\t\/\/\n\t\/\/ Servers must return a list of locks sorted in reverse chronological\n\t\/\/ order, so the Cursor provides a consistent method of viewing all\n\t\/\/ locks, even if more were created between two requests.\n\tCursor string `json:\"cursor,omitempty\"`\n\t\/\/ Limit is the maximum number of locks to return in a single page.\n\tLimit int `json:\"limit,omitempty\"`\n}\n\n\/\/ lockVerifiableList encapsulates a set of Locks to verify a Git push.\ntype lockVerifiableList struct {\n\t\/\/ Ours is the set of locks returned back matching filenames that the user\n\t\/\/ is allowed to edit.\n\tOurs []Lock `json:\"ours\"`\n\n\t\/\/ Their is the set of locks returned back matching filenames that the user\n\t\/\/ is NOT allowed to edit. Any edits matching these files should reject\n\t\/\/ the Git push.\n\tTheirs []Lock `json:\"theirs\"`\n\n\t\/\/ NextCursor returns the Id of the Lock the client should update its\n\t\/\/ cursor to, if there are multiple pages of results for a particular\n\t\/\/ `LockListRequest`.\n\tNextCursor string `json:\"next_cursor,omitempty\"`\n\t\/\/ Message populates any error that was encountered during the search. If no\n\t\/\/ error was encountered and the operation was successful, then a value\n\t\/\/ of nil will be passed here.\n\tMessage          string `json:\"message,omitempty\"`\n\tDocumentationURL string `json:\"documentation_url,omitempty\"`\n\tRequestID        string `json:\"request_id,omitempty\"`\n}\n\nfunc (c *lockClient) SearchVerifiable(remote string, vreq *lockVerifiableRequest) (*lockVerifiableList, *http.Response, error) {\n\te := c.Endpoints.Endpoint(\"upload\", remote)\n\treq, err := c.NewRequest(\"POST\", e, \"locks\/verify\", vreq)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq = c.Client.LogRequest(req, \"lfs.locks.verify\")\n\tres, err := c.DoAPIRequestWithAuth(remote, req)\n\tif err != nil {\n\t\treturn nil, res, err\n\t}\n\n\tlocks := &lockVerifiableList{}\n\tif res.StatusCode == http.StatusOK {\n\t\terr = lfshttp.DecodeJSON(res, locks)\n\t}\n\n\treturn locks, res, err\n}\n\n\/\/ User represents the owner of a lock.\ntype User struct {\n\t\/\/ Name is the name of the individual who would like to obtain the\n\t\/\/ lock, for instance: \"Rick Sanchez\".\n\tName string `json:\"name\"`\n}\n\nfunc NewUser(name string) *User {\n\treturn &User{Name: name}\n}\n\n\/\/ String implements the fmt.Stringer interface.\nfunc (u *User) String() string {\n\treturn u.Name\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/awslabs\/aws-sdk-go\/aws\"\n\t\"github.com\/awslabs\/aws-sdk-go\/service\/autoscaling\"\n\thashiASG \"github.com\/hashicorp\/aws-sdk-go\/gen\/autoscaling\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nfunc TestAccAWSAutoScalingGroup_basic(t *testing.T) {\n\tvar group autoscaling.AutoScalingGroup\n\tvar lc hashiASG.LaunchConfiguration\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSAutoScalingGroupConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupExists(\"aws_autoscaling_group.bar\", &group),\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupAttributes(&group),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"availability_zones.2487133097\", \"us-west-2a\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"name\", \"foobar3-terraform-test\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"max_size\", \"5\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"min_size\", \"2\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"health_check_grace_period\", \"300\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"health_check_type\", \"ELB\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"desired_capacity\", \"4\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"force_delete\", \"true\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"termination_policies.912102603\", \"OldestInstance\"),\n\t\t\t\t),\n\t\t\t},\n\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSAutoScalingGroupConfigUpdate,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupExists(\"aws_autoscaling_group.bar\", &group),\n\t\t\t\t\ttestAccCheckAWSLaunchConfigurationExists(\"aws_launch_configuration.new\", &lc),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"desired_capacity\", \"5\"),\n\t\t\t\t\ttestLaunchConfigurationName(\"aws_autoscaling_group.bar\", &lc),\n\t\t\t\t\ttestAccCheckAutoscalingTags(&group.Tags, \"Bar\", map[string]interface{}{\n\t\t\t\t\t\t\"value\":               \"bar-foo\",\n\t\t\t\t\t\t\"propagate_at_launch\": true,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSAutoScalingGroup_tags(t *testing.T) {\n\tvar group autoscaling.AutoScalingGroup\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSAutoScalingGroupConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupExists(\"aws_autoscaling_group.bar\", &group),\n\t\t\t\t\ttestAccCheckAutoscalingTags(&group.Tags, \"Foo\", map[string]interface{}{\n\t\t\t\t\t\t\"value\":               \"foo-bar\",\n\t\t\t\t\t\t\"propagate_at_launch\": true,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t},\n\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSAutoScalingGroupConfigUpdate,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupExists(\"aws_autoscaling_group.bar\", &group),\n\t\t\t\t\ttestAccCheckAutoscalingTagNotExists(&group.Tags, \"Foo\"),\n\t\t\t\t\ttestAccCheckAutoscalingTags(&group.Tags, \"Bar\", map[string]interface{}{\n\t\t\t\t\t\t\"value\":               \"bar-foo\",\n\t\t\t\t\t\t\"propagate_at_launch\": true,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSAutoScalingGroup_WithLoadBalancer(t *testing.T) {\n\tvar group autoscaling.AutoScalingGroup\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSAutoScalingGroupConfigWithLoadBalancer,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupExists(\"aws_autoscaling_group.bar\", &group),\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupAttributesLoadBalancer(&group),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\nfunc testAccCheckAWSAutoScalingGroupDestroy(s *terraform.State) error {\n\tconn := testAccProvider.Meta().(*AWSClient).asgconn\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_autoscaling_group\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Try to find the Group\n\t\tdescribeGroups, err := conn.DescribeAutoScalingGroups(\n\t\t\t&autoscaling.DescribeAutoScalingGroupsInput{\n\t\t\t\tAutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)},\n\t\t\t})\n\n\t\tif err == nil {\n\t\t\tif len(describeGroups.AutoScalingGroups) != 0 &&\n\t\t\t\t*describeGroups.AutoScalingGroups[0].AutoScalingGroupName == rs.Primary.ID {\n\t\t\t\treturn fmt.Errorf(\"AutoScaling Group still exists\")\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Verify the error\n\t\tec2err, ok := err.(aws.APIError)\n\t\tif !ok {\n\t\t\treturn err\n\t\t}\n\t\tif ec2err.Code != \"InvalidGroup.NotFound\" {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc testAccCheckAWSAutoScalingGroupAttributes(group *autoscaling.AutoScalingGroup) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tif *group.AvailabilityZones[0] != \"us-west-2a\" {\n\t\t\treturn fmt.Errorf(\"Bad availability_zones: %s\", group.AvailabilityZones[0])\n\t\t}\n\n\t\tif *group.AutoScalingGroupName != \"foobar3-terraform-test\" {\n\t\t\treturn fmt.Errorf(\"Bad name: %s\", *group.AutoScalingGroupName)\n\t\t}\n\n\t\tif *group.MaxSize != 5 {\n\t\t\treturn fmt.Errorf(\"Bad max_size: %d\", *group.MaxSize)\n\t\t}\n\n\t\tif *group.MinSize != 2 {\n\t\t\treturn fmt.Errorf(\"Bad max_size: %d\", *group.MinSize)\n\t\t}\n\n\t\tif *group.HealthCheckType != \"ELB\" {\n\t\t\treturn fmt.Errorf(\"Bad health_check_type,\\nexpected: %s\\ngot: %s\", \"ELB\", *group.HealthCheckType)\n\t\t}\n\n\t\tif *group.HealthCheckGracePeriod != 300 {\n\t\t\treturn fmt.Errorf(\"Bad health_check_grace_period: %d\", *group.HealthCheckGracePeriod)\n\t\t}\n\n\t\tif *group.DesiredCapacity != 4 {\n\t\t\treturn fmt.Errorf(\"Bad desired_capacity: %d\", *group.DesiredCapacity)\n\t\t}\n\n\t\tif *group.LaunchConfigurationName == \"\" {\n\t\t\treturn fmt.Errorf(\"Bad launch configuration name: %s\", *group.LaunchConfigurationName)\n\t\t}\n\n\t\tt := &autoscaling.TagDescription{\n\t\t\tKey:               aws.String(\"Foo\"),\n\t\t\tValue:             aws.String(\"foo-bar\"),\n\t\t\tPropagateAtLaunch: aws.Boolean(true),\n\t\t\tResourceType:      aws.String(\"auto-scaling-group\"),\n\t\t\tResourceID:        group.AutoScalingGroupName,\n\t\t}\n\n\t\tif !reflect.DeepEqual(group.Tags[0], t) {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"Got:\\n\\n%#v\\n\\nExpected:\\n\\n%#v\\n\",\n\t\t\t\tgroup.Tags[0],\n\t\t\t\tt)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckAWSAutoScalingGroupAttributesLoadBalancer(group *autoscaling.AutoScalingGroup) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tif *group.LoadBalancerNames[0] != \"foobar-terraform-test\" {\n\t\t\treturn fmt.Errorf(\"Bad load_balancers: %s\", group.LoadBalancerNames[0])\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckAWSAutoScalingGroupExists(n string, group *autoscaling.AutoScalingGroup) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No AutoScaling Group ID is set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).asgconn\n\n\t\tdescribeGroups, err := conn.DescribeAutoScalingGroups(\n\t\t\t&autoscaling.DescribeAutoScalingGroupsInput{\n\t\t\t\tAutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)},\n\t\t\t})\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(describeGroups.AutoScalingGroups) != 1 ||\n\t\t\t*describeGroups.AutoScalingGroups[0].AutoScalingGroupName != rs.Primary.ID {\n\t\t\treturn fmt.Errorf(\"AutoScaling Group not found\")\n\t\t}\n\n\t\t*group = *describeGroups.AutoScalingGroups[0]\n\n\t\treturn nil\n\t}\n}\n\nfunc testLaunchConfigurationName(n string, lc *hashiASG.LaunchConfiguration) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif *lc.LaunchConfigurationName != rs.Primary.Attributes[\"launch_configuration\"] {\n\t\t\treturn fmt.Errorf(\"Launch configuration names do not match\")\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nconst testAccAWSAutoScalingGroupConfig = `\nresource \"aws_launch_configuration\" \"foobar\" {\n  name = \"foobarautoscaling-terraform-test\"\n  image_id = \"ami-21f78e11\"\n  instance_type = \"t1.micro\"\n}\n\nresource \"aws_autoscaling_group\" \"bar\" {\n  availability_zones = [\"us-west-2a\"]\n  name = \"foobar3-terraform-test\"\n  max_size = 5\n  min_size = 2\n  health_check_grace_period = 300\n  health_check_type = \"ELB\"\n  desired_capacity = 4\n  force_delete = true\n  termination_policies = [\"OldestInstance\"]\n\n  launch_configuration = \"${aws_launch_configuration.foobar.name}\"\n\n  tag {\n    key = \"Foo\"\n    value = \"foo-bar\"\n    propagate_at_launch = true\n  }\n}\n`\n\nconst testAccAWSAutoScalingGroupConfigUpdate = `\nresource \"aws_launch_configuration\" \"foobar\" {\n  name = \"foobarautoscaling-terraform-test\"\n  image_id = \"ami-21f78e11\"\n  instance_type = \"t1.micro\"\n}\n\nresource \"aws_launch_configuration\" \"new\" {\n  name = \"foobarautoscaling-terraform-test-new\"\n  image_id = \"ami-21f78e11\"\n  instance_type = \"t1.micro\"\n}\n\nresource \"aws_autoscaling_group\" \"bar\" {\n  availability_zones = [\"us-west-2a\"]\n  name = \"foobar3-terraform-test\"\n  max_size = 5\n  min_size = 2\n  health_check_grace_period = 300\n  health_check_type = \"ELB\"\n  desired_capacity = 5\n  force_delete = true\n\n  launch_configuration = \"${aws_launch_configuration.new.name}\"\n\n  tag {\n    key = \"Bar\"\n    value = \"bar-foo\"\n    propagate_at_launch = true\n  }\n}\n`\n\nconst testAccAWSAutoScalingGroupConfigWithLoadBalancer = `\nresource \"aws_elb\" \"bar\" {\n  name = \"foobar-terraform-test\"\n  availability_zones = [\"us-west-2a\"]\n\n  listener {\n    instance_port = 8000\n    instance_protocol = \"http\"\n    lb_port = 80\n    lb_protocol = \"http\"\n  }\n}\n\nresource \"aws_launch_configuration\" \"foobar\" {\n  name = \"foobarautoscaling-terraform-test\"\n  image_id = \"ami-21f78e11\"\n  instance_type = \"t1.micro\"\n}\n\nresource \"aws_autoscaling_group\" \"bar\" {\n  availability_zones = [\"us-west-2a\"]\n  name = \"foobar3-terraform-test\"\n  max_size = 5\n  min_size = 2\n  health_check_grace_period = 300\n  health_check_type = \"ELB\"\n  desired_capacity = 4\n  force_delete = true\n\n  launch_configuration = \"${aws_launch_configuration.foobar.name}\"\n  load_balancers = [\"${aws_elb.bar.name}\"]\n}\n`\n<commit_msg>go vet updates<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/awslabs\/aws-sdk-go\/aws\"\n\t\"github.com\/awslabs\/aws-sdk-go\/service\/autoscaling\"\n\thashiASG \"github.com\/hashicorp\/aws-sdk-go\/gen\/autoscaling\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nfunc TestAccAWSAutoScalingGroup_basic(t *testing.T) {\n\tvar group autoscaling.AutoScalingGroup\n\tvar lc hashiASG.LaunchConfiguration\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSAutoScalingGroupConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupExists(\"aws_autoscaling_group.bar\", &group),\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupAttributes(&group),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"availability_zones.2487133097\", \"us-west-2a\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"name\", \"foobar3-terraform-test\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"max_size\", \"5\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"min_size\", \"2\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"health_check_grace_period\", \"300\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"health_check_type\", \"ELB\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"desired_capacity\", \"4\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"force_delete\", \"true\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"termination_policies.912102603\", \"OldestInstance\"),\n\t\t\t\t),\n\t\t\t},\n\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSAutoScalingGroupConfigUpdate,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupExists(\"aws_autoscaling_group.bar\", &group),\n\t\t\t\t\ttestAccCheckAWSLaunchConfigurationExists(\"aws_launch_configuration.new\", &lc),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_autoscaling_group.bar\", \"desired_capacity\", \"5\"),\n\t\t\t\t\ttestLaunchConfigurationName(\"aws_autoscaling_group.bar\", &lc),\n\t\t\t\t\ttestAccCheckAutoscalingTags(&group.Tags, \"Bar\", map[string]interface{}{\n\t\t\t\t\t\t\"value\":               \"bar-foo\",\n\t\t\t\t\t\t\"propagate_at_launch\": true,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSAutoScalingGroup_tags(t *testing.T) {\n\tvar group autoscaling.AutoScalingGroup\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSAutoScalingGroupConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupExists(\"aws_autoscaling_group.bar\", &group),\n\t\t\t\t\ttestAccCheckAutoscalingTags(&group.Tags, \"Foo\", map[string]interface{}{\n\t\t\t\t\t\t\"value\":               \"foo-bar\",\n\t\t\t\t\t\t\"propagate_at_launch\": true,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t},\n\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSAutoScalingGroupConfigUpdate,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupExists(\"aws_autoscaling_group.bar\", &group),\n\t\t\t\t\ttestAccCheckAutoscalingTagNotExists(&group.Tags, \"Foo\"),\n\t\t\t\t\ttestAccCheckAutoscalingTags(&group.Tags, \"Bar\", map[string]interface{}{\n\t\t\t\t\t\t\"value\":               \"bar-foo\",\n\t\t\t\t\t\t\"propagate_at_launch\": true,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSAutoScalingGroup_WithLoadBalancer(t *testing.T) {\n\tvar group autoscaling.AutoScalingGroup\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSAutoScalingGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSAutoScalingGroupConfigWithLoadBalancer,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupExists(\"aws_autoscaling_group.bar\", &group),\n\t\t\t\t\ttestAccCheckAWSAutoScalingGroupAttributesLoadBalancer(&group),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\nfunc testAccCheckAWSAutoScalingGroupDestroy(s *terraform.State) error {\n\tconn := testAccProvider.Meta().(*AWSClient).asgconn\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_autoscaling_group\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Try to find the Group\n\t\tdescribeGroups, err := conn.DescribeAutoScalingGroups(\n\t\t\t&autoscaling.DescribeAutoScalingGroupsInput{\n\t\t\t\tAutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)},\n\t\t\t})\n\n\t\tif err == nil {\n\t\t\tif len(describeGroups.AutoScalingGroups) != 0 &&\n\t\t\t\t*describeGroups.AutoScalingGroups[0].AutoScalingGroupName == rs.Primary.ID {\n\t\t\t\treturn fmt.Errorf(\"AutoScaling Group still exists\")\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Verify the error\n\t\tec2err, ok := err.(aws.APIError)\n\t\tif !ok {\n\t\t\treturn err\n\t\t}\n\t\tif ec2err.Code != \"InvalidGroup.NotFound\" {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc testAccCheckAWSAutoScalingGroupAttributes(group *autoscaling.AutoScalingGroup) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tif *group.AvailabilityZones[0] != \"us-west-2a\" {\n\t\t\treturn fmt.Errorf(\"Bad availability_zones: %#v\", group.AvailabilityZones[0])\n\t\t}\n\n\t\tif *group.AutoScalingGroupName != \"foobar3-terraform-test\" {\n\t\t\treturn fmt.Errorf(\"Bad name: %s\", *group.AutoScalingGroupName)\n\t\t}\n\n\t\tif *group.MaxSize != 5 {\n\t\t\treturn fmt.Errorf(\"Bad max_size: %d\", *group.MaxSize)\n\t\t}\n\n\t\tif *group.MinSize != 2 {\n\t\t\treturn fmt.Errorf(\"Bad max_size: %d\", *group.MinSize)\n\t\t}\n\n\t\tif *group.HealthCheckType != \"ELB\" {\n\t\t\treturn fmt.Errorf(\"Bad health_check_type,\\nexpected: %s\\ngot: %s\", \"ELB\", *group.HealthCheckType)\n\t\t}\n\n\t\tif *group.HealthCheckGracePeriod != 300 {\n\t\t\treturn fmt.Errorf(\"Bad health_check_grace_period: %d\", *group.HealthCheckGracePeriod)\n\t\t}\n\n\t\tif *group.DesiredCapacity != 4 {\n\t\t\treturn fmt.Errorf(\"Bad desired_capacity: %d\", *group.DesiredCapacity)\n\t\t}\n\n\t\tif *group.LaunchConfigurationName == \"\" {\n\t\t\treturn fmt.Errorf(\"Bad launch configuration name: %s\", *group.LaunchConfigurationName)\n\t\t}\n\n\t\tt := &autoscaling.TagDescription{\n\t\t\tKey:               aws.String(\"Foo\"),\n\t\t\tValue:             aws.String(\"foo-bar\"),\n\t\t\tPropagateAtLaunch: aws.Boolean(true),\n\t\t\tResourceType:      aws.String(\"auto-scaling-group\"),\n\t\t\tResourceID:        group.AutoScalingGroupName,\n\t\t}\n\n\t\tif !reflect.DeepEqual(group.Tags[0], t) {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"Got:\\n\\n%#v\\n\\nExpected:\\n\\n%#v\\n\",\n\t\t\t\tgroup.Tags[0],\n\t\t\t\tt)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckAWSAutoScalingGroupAttributesLoadBalancer(group *autoscaling.AutoScalingGroup) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tif *group.LoadBalancerNames[0] != \"foobar-terraform-test\" {\n\t\t\treturn fmt.Errorf(\"Bad load_balancers: %#v\", group.LoadBalancerNames[0])\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckAWSAutoScalingGroupExists(n string, group *autoscaling.AutoScalingGroup) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No AutoScaling Group ID is set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).asgconn\n\n\t\tdescribeGroups, err := conn.DescribeAutoScalingGroups(\n\t\t\t&autoscaling.DescribeAutoScalingGroupsInput{\n\t\t\t\tAutoScalingGroupNames: []*string{aws.String(rs.Primary.ID)},\n\t\t\t})\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(describeGroups.AutoScalingGroups) != 1 ||\n\t\t\t*describeGroups.AutoScalingGroups[0].AutoScalingGroupName != rs.Primary.ID {\n\t\t\treturn fmt.Errorf(\"AutoScaling Group not found\")\n\t\t}\n\n\t\t*group = *describeGroups.AutoScalingGroups[0]\n\n\t\treturn nil\n\t}\n}\n\nfunc testLaunchConfigurationName(n string, lc *hashiASG.LaunchConfiguration) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif *lc.LaunchConfigurationName != rs.Primary.Attributes[\"launch_configuration\"] {\n\t\t\treturn fmt.Errorf(\"Launch configuration names do not match\")\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nconst testAccAWSAutoScalingGroupConfig = `\nresource \"aws_launch_configuration\" \"foobar\" {\n  name = \"foobarautoscaling-terraform-test\"\n  image_id = \"ami-21f78e11\"\n  instance_type = \"t1.micro\"\n}\n\nresource \"aws_autoscaling_group\" \"bar\" {\n  availability_zones = [\"us-west-2a\"]\n  name = \"foobar3-terraform-test\"\n  max_size = 5\n  min_size = 2\n  health_check_grace_period = 300\n  health_check_type = \"ELB\"\n  desired_capacity = 4\n  force_delete = true\n  termination_policies = [\"OldestInstance\"]\n\n  launch_configuration = \"${aws_launch_configuration.foobar.name}\"\n\n  tag {\n    key = \"Foo\"\n    value = \"foo-bar\"\n    propagate_at_launch = true\n  }\n}\n`\n\nconst testAccAWSAutoScalingGroupConfigUpdate = `\nresource \"aws_launch_configuration\" \"foobar\" {\n  name = \"foobarautoscaling-terraform-test\"\n  image_id = \"ami-21f78e11\"\n  instance_type = \"t1.micro\"\n}\n\nresource \"aws_launch_configuration\" \"new\" {\n  name = \"foobarautoscaling-terraform-test-new\"\n  image_id = \"ami-21f78e11\"\n  instance_type = \"t1.micro\"\n}\n\nresource \"aws_autoscaling_group\" \"bar\" {\n  availability_zones = [\"us-west-2a\"]\n  name = \"foobar3-terraform-test\"\n  max_size = 5\n  min_size = 2\n  health_check_grace_period = 300\n  health_check_type = \"ELB\"\n  desired_capacity = 5\n  force_delete = true\n\n  launch_configuration = \"${aws_launch_configuration.new.name}\"\n\n  tag {\n    key = \"Bar\"\n    value = \"bar-foo\"\n    propagate_at_launch = true\n  }\n}\n`\n\nconst testAccAWSAutoScalingGroupConfigWithLoadBalancer = `\nresource \"aws_elb\" \"bar\" {\n  name = \"foobar-terraform-test\"\n  availability_zones = [\"us-west-2a\"]\n\n  listener {\n    instance_port = 8000\n    instance_protocol = \"http\"\n    lb_port = 80\n    lb_protocol = \"http\"\n  }\n}\n\nresource \"aws_launch_configuration\" \"foobar\" {\n  name = \"foobarautoscaling-terraform-test\"\n  image_id = \"ami-21f78e11\"\n  instance_type = \"t1.micro\"\n}\n\nresource \"aws_autoscaling_group\" \"bar\" {\n  availability_zones = [\"us-west-2a\"]\n  name = \"foobar3-terraform-test\"\n  max_size = 5\n  min_size = 2\n  health_check_grace_period = 300\n  health_check_type = \"ELB\"\n  desired_capacity = 4\n  force_delete = true\n\n  launch_configuration = \"${aws_launch_configuration.foobar.name}\"\n  load_balancers = [\"${aws_elb.bar.name}\"]\n}\n`\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"strings\"\n\n\t\"github.com\/hyperledger\/fabric\/core\/chaincode\/shim\"\n\t\"github.com\/hyperledger\/fabric\/core\/util\"\n)\n\nvar serviceCharge = 5\n\nvar logger = shim.NewLogger(\"ftLogger\")\n\n\/\/ SimpleChaincode example simple Chaincode implementation\ntype SimpleChaincode struct {\n}\n\n\/\/ Init initializes the chaincode\nfunc (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tvar err error\n\tif len(args) > 0 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 0\")\n\t}\n\n\t\/\/ Write the state to the ledger\n\terr = stub.PutState(\"IBI-CC[init]: \"+time.Now().String(), []byte(\"starting ABI chaincode\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n\n\/\/ Invoke queries another chaincode and updates its own state\nfunc (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tvar jsonResp, customer, name, amount, state string\n\tvar response []byte\n\tvar err error\n\n\tfmt.Println(\"Args: \", args)\n\n\tif len(args) != 3 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 3\")\n\t}\n\n\tchaincodeURL := args[0] \/\/https:\/\/github.com\/sauravhaloi\/chaincode\/issuer\n\toperation := args[1]\n\tcustomer = args[2]\n\n\tswitch operation {\n\tcase \"GetAccountBalance\":\n\t\tf := \"GetAccountBalance\"\n\t\tqueryArgs := util.ToChaincodeArgs(f, customer)\n\t\tresponse, err = stub.QueryChaincode(chaincodeURL, queryArgs)\n\t\tif err != nil {\n\t\t\terrStr := fmt.Sprintf(\"Failed to query chaincode. Got error: %s\", err.Error())\n\t\t\tjsonResp = \"{\\\"Error\\\":\\\"\" + errStr + \"\\\"}\"\n\t\t\treturn nil, errors.New(jsonResp)\n\t\t}\n\n\tcase \"WithdrawFund\":\n\t\tf := \"Withdraw\"\n\t\tname = strings.Split(customer, \",\")[0]\n\t\tamount = strings.Split(customer, \",\")[1]\n\t\tqueryArgs := util.ToChaincodeArgs(f, name, amount)\n\n\t\tfmt.Println(\"Query Args: \", queryArgs)\n\n\t\tresponse, err = stub.InvokeChaincode(chaincodeURL, queryArgs)\n\t\tif err != nil {\n\t\t\terrStr := fmt.Sprintf(\"Failed to invoke chaincode. Got error: %s\", err.Error())\n\t\t\tjsonResp = \"{\\\"Error\\\":\\\"\" + errStr + \"\\\"}\"\n\t\t\treturn nil, errors.New(jsonResp)\n\t\t}\n\n\t\t\/\/ transaction was successful, charge Issuer\n\t\tsettlement, err := strconv.Atoi(amount)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsettlement = settlement + serviceCharge\n\n\t\tstate = fmt.Sprintf(\"IBI owes ABI \" + strconv.Itoa(settlement))\n\n\t\t\/\/ Write amount which IBI owes to ABI back to the ledger\n\t\terr = stub.PutState(\"IBI->ABI\", []byte(state))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfmt.Printf(\"Invoke chaincode successful. IBI Owes ABI %d\\n\", settlement)\n\t\treturn []byte(state), nil\n\n\tdefault:\n\t\tjsonResp = \"{\\\"Error\\\":\\\"Invalid operaton requested: \" + operation + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tjsonResp = \"{\\\"Response\\\":\\\"\" + string(response) + \"\\\"}\"\n\tfmt.Printf(\"Operation: %s | Response: %s\", operation, jsonResp)\n\n\treturn []byte(jsonResp), nil\n}\n\n\/\/ Query callback representing the query of a chaincode\nfunc (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tif function != \"Query\" {\n\t\treturn nil, errors.New(\"Invalid query function name. Expecting \\\"Query\\\"\")\n\t}\n\tvar jsonResp string\n\tvar err error\n\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\ttransactionName := args[0]\n\n\tvalAsbytes, err := stub.GetState(transactionName)\n\tif err != nil {\n\t\tjsonResp = \"{\\\"Error\\\":\\\"Failed to get state for \" + transactionName + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tfmt.Printf(\"Query chaincode successful. Got IBI->ABI %s\\n\", string(valAsbytes))\n\tjsonResp = \"{\\\"IBI Owes ABI\\\":\\\"\" + string(valAsbytes) + \"\\\"}\"\n\tfmt.Printf(\"Query Response:%s\\n\", jsonResp)\n\treturn []byte(valAsbytes), nil\n\n}\n\nfunc main() {\n\tvar err error\n\tlld, _ := shim.LogLevel(\"DEBUG\")\n\tfmt.Println(lld)\n\n\tlogger.SetLevel(lld)\n\tfmt.Println(logger.IsEnabledFor(lld))\n\n\terr = shim.Start(new(SimpleChaincode))\n\tif err != nil {\n\t\tfmt.Println(\"Could not start SimpleChaincode\")\n\t} else {\n\t\tfmt.Println(\"SimpleChaincode successfully started\")\n\t}\n}\n<commit_msg>logging and bug fixing<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"strings\"\n\n\t\"github.com\/hyperledger\/fabric\/core\/chaincode\/shim\"\n\t\"github.com\/hyperledger\/fabric\/core\/util\"\n)\n\nvar serviceCharge = 5\n\nvar logger = shim.NewLogger(\"ftLogger\")\n\n\/\/ SimpleChaincode example simple Chaincode implementation\ntype SimpleChaincode struct {\n}\n\n\/\/ Init initializes the chaincode\nfunc (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tvar err error\n\tif len(args) > 0 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 0\")\n\t}\n\n\t\/\/ Write the state to the ledger\n\terr = stub.PutState(\"IBI-CC[init]: \"+time.Now().String(), []byte(\"starting ABI chaincode\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n\n\/\/ Invoke queries another chaincode and updates its own state\nfunc (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tvar jsonResp, customer, name, amount, state string\n\tvar response []byte\n\tvar err error\n\n\tfmt.Println(\"Args: \", args)\n\n\tif len(args) != 3 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 3\")\n\t}\n\n\tchaincodeURL := args[0] \/\/https:\/\/github.com\/sauravhaloi\/chaincode\/issuer\n\toperation := args[1]\n\tcustomer = args[2]\n\n\tswitch operation {\n\tcase \"GetAccountBalance\":\n\t\tf := \"GetAccountBalance\"\n\t\tqueryArgs := util.ToChaincodeArgs(f, customer)\n\t\tresponse, err = stub.QueryChaincode(chaincodeURL, queryArgs)\n\t\tif err != nil {\n\t\t\terrStr := fmt.Sprintf(\"Failed to query chaincode. Got error: %s\", err.Error())\n\t\t\tjsonResp = \"{\\\"Error\\\":\\\"\" + errStr + \"\\\"}\"\n\t\t\treturn nil, errors.New(jsonResp)\n\t\t}\n\n\tcase \"WithdrawFund\":\n\t\tf := \"Withdraw\"\n\t\tname = strings.Split(customer, \",\")[0]\n\t\tamount = strings.Split(customer, \",\")[1]\n\t\tqueryArgs := util.ToChaincodeArgs(f, name, amount)\n\n\t\tfmt.Println(\"Query Args: \", queryArgs)\n\n\t\tresponse, err = stub.InvokeChaincode(chaincodeURL, queryArgs)\n\t\tif err != nil {\n\t\t\terrStr := fmt.Sprintf(\"Failed to invoke chaincode. Got error: %s\", err.Error())\n\t\t\tjsonResp = \"{\\\"Error\\\":\\\"\" + errStr + \"\\\"}\"\n\t\t\treturn nil, errors.New(jsonResp)\n\t\t}\n\n\t\tjsonResp = \"{\\\"Response of WithdrawFund\\\":\\\"\" + string(response) + \"\\\"}\"\n\t\tfmt.Printf(\"Operation: %s | Response: %s\", operation, jsonResp)\n\n\t\t\/\/ transaction was successful, charge Issuer\n\t\tsettlement, err := strconv.Atoi(amount)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsettlement = settlement + serviceCharge\n\n\t\texisting, err := stub.GetState(\"IBI->ABI\")\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Failed to get state\" + err.Error())\n\t\t}\n\n\t\texistingSettlement := strings.Split(string(existing), \" \")[3]\n\n\t\tpastSettlement, err := strconv.Atoi(existingSettlement)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstate = fmt.Sprintf(\"IBI owes ABI \" + strconv.Itoa(settlement+pastSettlement))\n\n\t\t\/\/ Write amount which IBI owes to ABI back to the ledger\n\t\terr = stub.PutState(\"IBI->ABI\", []byte(state))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfmt.Printf(\"Invoke chaincode successful. IBI Owes ABI %d\\n\", settlement)\n\t\treturn []byte(state), nil\n\n\tdefault:\n\t\tjsonResp = \"{\\\"Error\\\":\\\"Invalid operaton requested: \" + operation + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tjsonResp = \"{\\\"Response\\\":\\\"\" + string(response) + \"\\\"}\"\n\tfmt.Printf(\"Operation: %s | Response: %s\", operation, jsonResp)\n\n\treturn []byte(jsonResp), nil\n}\n\n\/\/ Query callback representing the query of a chaincode\nfunc (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tif function != \"Query\" {\n\t\treturn nil, errors.New(\"Invalid query function name. Expecting \\\"Query\\\"\")\n\t}\n\tvar jsonResp string\n\tvar err error\n\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\ttransactionName := args[0]\n\n\tvalAsbytes, err := stub.GetState(transactionName)\n\tif err != nil {\n\t\tjsonResp = \"{\\\"Error\\\":\\\"Failed to get state for \" + transactionName + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tfmt.Printf(\"Query chaincode successful. Got IBI->ABI %s\\n\", string(valAsbytes))\n\tjsonResp = \"{\\\"IBI Owes ABI\\\":\\\"\" + string(valAsbytes) + \"\\\"}\"\n\tfmt.Printf(\"Query Response:%s\\n\", jsonResp)\n\treturn []byte(valAsbytes), nil\n\n}\n\nfunc main() {\n\tvar err error\n\tlld, _ := shim.LogLevel(\"DEBUG\")\n\tfmt.Println(lld)\n\n\tlogger.SetLevel(lld)\n\tfmt.Println(logger.IsEnabledFor(lld))\n\n\terr = shim.Start(new(SimpleChaincode))\n\tif err != nil {\n\t\tfmt.Println(\"Could not start SimpleChaincode\")\n\t} else {\n\t\tfmt.Println(\"SimpleChaincode successfully started\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 The go-logger Authors. All rights reserved.\n\/\/ This code is MIT licensed. See the LICENSE file for more info.\n\npackage log\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n\t\"runtime\"\n\t\"time\"\n)\n\nfunc TestStream(t *testing.T) {\n\tvar buf bytes.Buffer\n\tlogr := New(LEVEL_CRITICAL, os.Stdout, &buf)\n\tlogr.Streams[1] = &buf\n\tif out := logr.Streams[1]; out != &buf {\n\t\tt.Errorf(\"Stream = %p, want %p\", out, &buf)\n\t}\n}\n\nfunc TestMultiStreams(t *testing.T) {\n\trand.Seed(time.Now().UnixNano())\n\tfPath := filepath.Join(os.TempDir(), fmt.Sprint(\"go_test_\",\n\t\trand.Int()))\n\tfile, err := os.Create(fPath)\n\tif err != nil {\n\t\tt.Error(\"Create(%q) = %v; want: nil\", fPath, err)\n\t}\n\tdefer file.Close()\n\tvar buf bytes.Buffer\n\teLen := 55\n\tlogr := New(LEVEL_DEBUG, file, &buf)\n\tlogr.Debugln(\"Testing debug output!\")\n\tb := make([]byte, eLen)\n\tn, err := file.ReadAt(b, 0)\n\tif n != eLen || err != nil {\n\t\tt.Errorf(\"Read(%d) = %d, %v; want: %d, nil\", eLen, n, err,\n\t\t\teLen)\n\t}\n\tif buf.Len() != eLen {\n\t\tt.Errorf(\"buf.Len() = %d; want: %d\", buf.Len(), eLen)\n\t}\n}\n\nfunc TestLongFileFlag(t *testing.T) {\n\tvar buf bytes.Buffer\n\n\tSetStreams(&buf)\n\tSetLevel(LEVEL_DEBUG)\n\tSetFlags(LnoPrefix | LlongFileName)\n\n\tDebugln(\"Test long file flag\")\n\n\t_, file, _, _ := runtime.Caller(0)\n\n\texpect := fmt.Sprintf(\"[DEBUG] %s: Test long file flag\\n\", file)\n\n\tif buf.String() != expect {\n\t\tt.Errorf(\"\\nExpect:\\n\\t%s\\nGot:\\n\\t%s\\n\", expect, buf.String())\n\t}\n}\n\nfunc TestShortFileFlag(t *testing.T) {\n\tvar buf bytes.Buffer\n\n\tSetStreams(&buf)\n\tSetLevel(LEVEL_DEBUG)\n\tSetFlags(LnoPrefix | LshortFileName)\n\n\tDebugln(\"Test short file flag\")\n\n\t_, file, _, _ := runtime.Caller(0)\n\n\tshort := file\n\tfor i := len(file) - 1; i > 0; i-- {\n\t\tif file[i] == '\/' {\n\t\t\tshort = file[i+1:]\n\t\t\tbreak\n\t\t}\n\t}\n\tfile = short\n\n\texpect := fmt.Sprintf(\"[DEBUG] %s: Test short file flag\\n\", file)\n\n\tif buf.String() != expect {\n\t\tt.Errorf(\"\\nExpect:\\n\\t%s\\nGot:\\n\\t%s\\n\", expect, buf.String())\n\t}\n}\n\nvar (\n\tboldPrefix  = AnsiEscape(ANSI_BOLD, \"TEST>\", ANSI_OFF)\n\tcolorPrefix = AnsiEscape(ANSI_BOLD, ANSI_RED, \"TEST>\", ANSI_OFF)\n\tdate        = \"Mon 20060102 15:04:05\"\n)\n\nvar outputTests = []struct {\n\ttemplate   string\n\tprefix     string\n\tlevel      level\n\tdateFormat string\n\tflags      int\n\ttext       string\n\twant       string\n\twantErr    bool\n}{\n\n\t\/\/ The %s format specifier is the placeholder for the date.\n\t{logFmt, boldPrefix, LEVEL_ALL, date, LstdFlags, \"test number 1\",\n\t\t\"%s \\x1b[1mTEST>\\x1b[0m test number 1\", false},\n\n\t{logFmt, colorPrefix, LEVEL_ALL, date, LstdFlags, \"test number 2\",\n\t\t\"%s \\x1b[1m\\x1b[31mTEST>\\x1b[0m test number 2\", false},\n\n\t\/\/ Test output with coloring turned off\n\t{logFmt, AnsiEscape(ANSI_BOLD, \"::\", ANSI_OFF), LEVEL_ALL, date, Ldate,\n\t\t\"test number 3\", \"%s :: test number 3\", false},\n\n\t{logFmt, defaultPrefixColor, LEVEL_DEBUG, time.RubyDate, LstdFlags,\n\t\t\"test number 4\",\n\t\t\"%s \\x1b[1m\\x1b[32m::\\x1b[0m \\x1b[1m\\x1b[37m[DEBUG]\\x1b[0m test number 4\",\n\t\tfalse},\n\n\t{logFmt, defaultPrefixColor, LEVEL_INFO, time.RubyDate, LstdFlags,\n\t\t\"test number 5\",\n\t\t\"%s \\x1b[1m\\x1b[32m::\\x1b[0m \\x1b[1m\\x1b[32m[INFO]\\x1b[0m test number 5\",\n\t\tfalse},\n\n\t{logFmt, defaultPrefixColor, LEVEL_WARNING, time.RubyDate, LstdFlags,\n\t\t\"test number 6\",\n\t\t\"%s \\x1b[1m\\x1b[32m::\\x1b[0m \\x1b[1m\\x1b[33m[WARNING]\\x1b[0m test number 6\",\n\t\tfalse},\n\n\t{logFmt, defaultPrefixColor, LEVEL_ERROR, time.RubyDate, LstdFlags,\n\t\t\"test number 7\",\n\t\t\"%s \\x1b[1m\\x1b[32m::\\x1b[0m \\x1b[1m\\x1b[35m[ERROR]\\x1b[0m test number 7\",\n\t\tfalse},\n\n\t{logFmt, defaultPrefixColor, LEVEL_CRITICAL, time.RubyDate, LstdFlags,\n\t\t\"test number 8\",\n\t\t\"%s \\x1b[1m\\x1b[32m::\\x1b[0m \\x1b[1m\\x1b[31m[CRITICAL]\\x1b[0m test number 8\",\n\t\tfalse},\n\n\t\/\/ Test date format\n\t{logFmt, defaultPrefixColor, LEVEL_ALL, \"Mon 20060102 15:04:05\",\n\t\tLdate, \"test number 9\",\n\t\t\"%s :: test number 9\", false},\n}\n\nfunc TestOutput(t *testing.T) {\n\tfor i, k := range outputTests {\n\t\tvar buf bytes.Buffer\n\t\tlogr := New(LEVEL_DEBUG, &buf)\n\t\tlogr.Prefix = k.prefix\n\t\tlogr.DateFormat = k.dateFormat\n\t\tlogr.Flags = k.flags\n\t\tlogr.Level = k.level\n\t\td := time.Now().Format(logr.DateFormat)\n\t\tn, err := logr.Fprint(k.level, 1, k.text, &buf)\n\t\tif n != buf.Len() {\n\t\t\tt.Error(\"Error: \", io.ErrShortWrite)\n\t\t}\n\t\twant := fmt.Sprintf(k.want, d)\n\t\tif buf.String() != want || err != nil && !k.wantErr {\n\t\t\tt.Errorf(\"Print test %d failed, \\ngot:  %q\\nwant: \"+\n\t\t\t\t\"%q\", i+1, buf.String(), want)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\nfunc TestLevel(t *testing.T) {\n\tvar buf bytes.Buffer\n\tlogr := New(LEVEL_CRITICAL, &buf)\n\tlogr.Debug(\"This level should produce no output\")\n\tif buf.Len() != 0 {\n\t\tt.Errorf(\"Debug() produced output at LEVEL_CRITICAL logging level\")\n\t}\n\tlogr.Level = LEVEL_DEBUG\n\tlogr.Debug(\"This level should produce output\")\n\tif buf.Len() == 0 {\n\t\tt.Errorf(\"Debug() did not produce output at the LEVEL_DEBUG logging level\")\n\t}\n\tbuf.Reset()\n\tlogr.Level = LEVEL_CRITICAL\n\tlogr.Println(\"This level should produce output\")\n\tif buf.Len() == 0 {\n\t\tt.Errorf(\"Debug() did not produce output at the ALL logging level\")\n\t}\n\tbuf.Reset()\n\tlogr.Level = LEVEL_ALL\n\tlogr.Debug(\"This level should produce output\")\n\tif buf.Len() == 0 {\n\t\tt.Errorf(\"Debug() did not produce output at the ALL logging level\")\n\t}\n}\n\nfunc TestPrefixNewline(t *testing.T) {\n\tvar buf bytes.Buffer\n\n\tc, err := buf.ReadString('\\n')\n\n\t\/\/ If text sent with the logging functions is prepended with newlines,\n\t\/\/ these newlines must be prepended to the output and stripped from the\n\t\/\/ text. First we will make sure the two nl's are at the beginning of\n\t\/\/ the output.\n\tif c[0] != '\\n' {\n\t\tt.Errorf(`First byte should be \"\\n\", found \"%s\"`, string(c[0]))\n\t}\n\n\tSetStreams(&buf)\n\tSetLevel(LEVEL_DEBUG)\n\tSetFlags(LnoPrefix)\n\n\tc, err = buf.ReadString('\\n')\n\tif err != nil {\n\t\tt.Error(\"ReadString unexpected EOF\")\n\t}\n\n\t\/\/ Since nl should be stripped from the text and prepended to the\n\t\/\/ output, we must make sure the nl is still not in the middle where it\n\t\/\/ would be if it had not been stripped.\n\tnlPos := strings.Index(buf.String(), \"] \") + 1\n\tif buf.Bytes()[nlPos+1] == '\\n' {\n\t\tt.Errorf(`\"\\n\" found at position %d.`, nlPos+1)\n\t}\n}\n\nfunc TestFlagsDate(t *testing.T) {\n\tvar buf bytes.Buffer\n\n\tSetStreams(&buf)\n\tSetLevel(LEVEL_DEBUG)\n\tSetFlags(LnoPrefix)\n\n\tDebugln(\"This output should not have a date.\")\n\n\texpect := \"[DEBUG] This output should not have a date.\\n\"\n\tif buf.String() != expect {\n\t\tt.Errorf(\"\\nExpect:\\n\\t%s\\nGot:\\n\\t%s\\n\", expect, buf.String())\n\t}\n}\n\nfunc TestFlagsFunctionName(t *testing.T) {\n\tvar buf bytes.Buffer\n\n\tSetStreams(&buf)\n\tSetLevel(LEVEL_DEBUG)\n\tSetFlags(LnoPrefix | LfunctionName)\n\n\tDebugln(\"This output should have a function name.\")\n\texpect := \"[DEBUG] TestFlagsFunction: This output should have a function name.\\n\"\n\tif buf.String() != expect {\n\t\tt.Errorf(\"\\nExpect:\\n\\t%s\\nGot:\\n\\t%s\\n\", expect, buf.String())\n\t}\n}\n<commit_msg>logger_test.go: Change %s to %q in expect output<commit_after>\/\/ Copyright 2013 The go-logger Authors. All rights reserved.\n\/\/ This code is MIT licensed. See the LICENSE file for more info.\n\npackage log\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n\t\"runtime\"\n\t\"time\"\n)\n\nfunc TestStream(t *testing.T) {\n\tvar buf bytes.Buffer\n\tlogr := New(LEVEL_CRITICAL, os.Stdout, &buf)\n\tlogr.Streams[1] = &buf\n\tif out := logr.Streams[1]; out != &buf {\n\t\tt.Errorf(\"Stream = %p, want %p\", out, &buf)\n\t}\n}\n\nfunc TestMultiStreams(t *testing.T) {\n\trand.Seed(time.Now().UnixNano())\n\tfPath := filepath.Join(os.TempDir(), fmt.Sprint(\"go_test_\",\n\t\trand.Int()))\n\tfile, err := os.Create(fPath)\n\tif err != nil {\n\t\tt.Error(\"Create(%q) = %v; want: nil\", fPath, err)\n\t}\n\tdefer file.Close()\n\tvar buf bytes.Buffer\n\teLen := 55\n\tlogr := New(LEVEL_DEBUG, file, &buf)\n\tlogr.Debugln(\"Testing debug output!\")\n\tb := make([]byte, eLen)\n\tn, err := file.ReadAt(b, 0)\n\tif n != eLen || err != nil {\n\t\tt.Errorf(\"Read(%d) = %d, %v; want: %d, nil\", eLen, n, err,\n\t\t\teLen)\n\t}\n\tif buf.Len() != eLen {\n\t\tt.Errorf(\"buf.Len() = %d; want: %d\", buf.Len(), eLen)\n\t}\n}\n\nfunc TestLongFileFlag(t *testing.T) {\n\tvar buf bytes.Buffer\n\n\tSetStreams(&buf)\n\tSetLevel(LEVEL_DEBUG)\n\tSetFlags(LnoPrefix | LlongFileName)\n\n\tDebugln(\"Test long file flag\")\n\n\t_, file, _, _ := runtime.Caller(0)\n\n\texpect := fmt.Sprintf(\"[DEBUG] %s: Test long file flag\\n\", file)\n\n\tif buf.String() != expect {\n\t\tt.Errorf(\"\\nExpect:\\n\\t%q\\nGot:\\n\\t%q\\n\", expect, buf.String())\n\t}\n}\n\nfunc TestShortFileFlag(t *testing.T) {\n\tvar buf bytes.Buffer\n\n\tSetStreams(&buf)\n\tSetLevel(LEVEL_DEBUG)\n\tSetFlags(LnoPrefix | LshortFileName)\n\n\tDebugln(\"Test short file flag\")\n\n\t_, file, _, _ := runtime.Caller(0)\n\n\tshort := file\n\tfor i := len(file) - 1; i > 0; i-- {\n\t\tif file[i] == '\/' {\n\t\t\tshort = file[i+1:]\n\t\t\tbreak\n\t\t}\n\t}\n\tfile = short\n\n\texpect := fmt.Sprintf(\"[DEBUG] %s: Test short file flag\\n\", file)\n\n\tif buf.String() != expect {\n\t\tt.Errorf(\"\\nExpect:\\n\\t%q\\nGot:\\n\\t%q\\n\", expect, buf.String())\n\t}\n}\n\nvar (\n\tboldPrefix  = AnsiEscape(ANSI_BOLD, \"TEST>\", ANSI_OFF)\n\tcolorPrefix = AnsiEscape(ANSI_BOLD, ANSI_RED, \"TEST>\", ANSI_OFF)\n\tdate        = \"Mon 20060102 15:04:05\"\n)\n\nvar outputTests = []struct {\n\ttemplate   string\n\tprefix     string\n\tlevel      level\n\tdateFormat string\n\tflags      int\n\ttext       string\n\twant       string\n\twantErr    bool\n}{\n\n\t\/\/ The %s format specifier is the placeholder for the date.\n\t{logFmt, boldPrefix, LEVEL_ALL, date, LstdFlags, \"test number 1\",\n\t\t\"%s \\x1b[1mTEST>\\x1b[0m test number 1\", false},\n\n\t{logFmt, colorPrefix, LEVEL_ALL, date, LstdFlags, \"test number 2\",\n\t\t\"%s \\x1b[1m\\x1b[31mTEST>\\x1b[0m test number 2\", false},\n\n\t\/\/ Test output with coloring turned off\n\t{logFmt, AnsiEscape(ANSI_BOLD, \"::\", ANSI_OFF), LEVEL_ALL, date, Ldate,\n\t\t\"test number 3\", \"%s :: test number 3\", false},\n\n\t{logFmt, defaultPrefixColor, LEVEL_DEBUG, time.RubyDate, LstdFlags,\n\t\t\"test number 4\",\n\t\t\"%s \\x1b[1m\\x1b[32m::\\x1b[0m \\x1b[1m\\x1b[37m[DEBUG]\\x1b[0m test number 4\",\n\t\tfalse},\n\n\t{logFmt, defaultPrefixColor, LEVEL_INFO, time.RubyDate, LstdFlags,\n\t\t\"test number 5\",\n\t\t\"%s \\x1b[1m\\x1b[32m::\\x1b[0m \\x1b[1m\\x1b[32m[INFO]\\x1b[0m test number 5\",\n\t\tfalse},\n\n\t{logFmt, defaultPrefixColor, LEVEL_WARNING, time.RubyDate, LstdFlags,\n\t\t\"test number 6\",\n\t\t\"%s \\x1b[1m\\x1b[32m::\\x1b[0m \\x1b[1m\\x1b[33m[WARNING]\\x1b[0m test number 6\",\n\t\tfalse},\n\n\t{logFmt, defaultPrefixColor, LEVEL_ERROR, time.RubyDate, LstdFlags,\n\t\t\"test number 7\",\n\t\t\"%s \\x1b[1m\\x1b[32m::\\x1b[0m \\x1b[1m\\x1b[35m[ERROR]\\x1b[0m test number 7\",\n\t\tfalse},\n\n\t{logFmt, defaultPrefixColor, LEVEL_CRITICAL, time.RubyDate, LstdFlags,\n\t\t\"test number 8\",\n\t\t\"%s \\x1b[1m\\x1b[32m::\\x1b[0m \\x1b[1m\\x1b[31m[CRITICAL]\\x1b[0m test number 8\",\n\t\tfalse},\n\n\t\/\/ Test date format\n\t{logFmt, defaultPrefixColor, LEVEL_ALL, \"Mon 20060102 15:04:05\",\n\t\tLdate, \"test number 9\",\n\t\t\"%s :: test number 9\", false},\n}\n\nfunc TestOutput(t *testing.T) {\n\tfor i, k := range outputTests {\n\t\tvar buf bytes.Buffer\n\t\tlogr := New(LEVEL_DEBUG, &buf)\n\t\tlogr.Prefix = k.prefix\n\t\tlogr.DateFormat = k.dateFormat\n\t\tlogr.Flags = k.flags\n\t\tlogr.Level = k.level\n\t\td := time.Now().Format(logr.DateFormat)\n\t\tn, err := logr.Fprint(k.level, 1, k.text, &buf)\n\t\tif n != buf.Len() {\n\t\t\tt.Error(\"Error: \", io.ErrShortWrite)\n\t\t}\n\t\twant := fmt.Sprintf(k.want, d)\n\t\tif buf.String() != want || err != nil && !k.wantErr {\n\t\t\tt.Errorf(\"Print test %d failed, \\ngot:  %q\\nwant: \"+\n\t\t\t\t\"%q\", i+1, buf.String(), want)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\nfunc TestLevel(t *testing.T) {\n\tvar buf bytes.Buffer\n\tlogr := New(LEVEL_CRITICAL, &buf)\n\tlogr.Debug(\"This level should produce no output\")\n\tif buf.Len() != 0 {\n\t\tt.Errorf(\"Debug() produced output at LEVEL_CRITICAL logging level\")\n\t}\n\tlogr.Level = LEVEL_DEBUG\n\tlogr.Debug(\"This level should produce output\")\n\tif buf.Len() == 0 {\n\t\tt.Errorf(\"Debug() did not produce output at the LEVEL_DEBUG logging level\")\n\t}\n\tbuf.Reset()\n\tlogr.Level = LEVEL_CRITICAL\n\tlogr.Println(\"This level should produce output\")\n\tif buf.Len() == 0 {\n\t\tt.Errorf(\"Debug() did not produce output at the ALL logging level\")\n\t}\n\tbuf.Reset()\n\tlogr.Level = LEVEL_ALL\n\tlogr.Debug(\"This level should produce output\")\n\tif buf.Len() == 0 {\n\t\tt.Errorf(\"Debug() did not produce output at the ALL logging level\")\n\t}\n}\n\nfunc TestPrefixNewline(t *testing.T) {\n\tvar buf bytes.Buffer\n\n\tc, err := buf.ReadString('\\n')\n\n\t\/\/ If text sent with the logging functions is prepended with newlines,\n\t\/\/ these newlines must be prepended to the output and stripped from the\n\t\/\/ text. First we will make sure the two nl's are at the beginning of\n\t\/\/ the output.\n\tif c[0] != '\\n' {\n\t\tt.Errorf(`First byte should be \"\\n\", found \"%s\"`, string(c[0]))\n\t}\n\n\tSetStreams(&buf)\n\tSetLevel(LEVEL_DEBUG)\n\tSetFlags(LnoPrefix)\n\n\tc, err = buf.ReadString('\\n')\n\tif err != nil {\n\t\tt.Error(\"ReadString unexpected EOF\")\n\t}\n\n\t\/\/ Since nl should be stripped from the text and prepended to the\n\t\/\/ output, we must make sure the nl is still not in the middle where it\n\t\/\/ would be if it had not been stripped.\n\tnlPos := strings.Index(buf.String(), \"] \") + 1\n\tif buf.Bytes()[nlPos+1] == '\\n' {\n\t\tt.Errorf(`\"\\n\" found at position %d.`, nlPos+1)\n\t}\n}\n\nfunc TestFlagsDate(t *testing.T) {\n\tvar buf bytes.Buffer\n\n\tSetStreams(&buf)\n\tSetLevel(LEVEL_DEBUG)\n\tSetFlags(LnoPrefix)\n\n\tDebugln(\"This output should not have a date.\")\n\n\texpect := \"[DEBUG] This output should not have a date.\\n\"\n\tif buf.String() != expect {\n\t\tt.Errorf(\"\\nExpect:\\n\\t%q\\nGot:\\n\\t%q\\n\", expect, buf.String())\n\t}\n}\n\nfunc TestFlagsFunctionName(t *testing.T) {\n\tvar buf bytes.Buffer\n\n\tSetStreams(&buf)\n\tSetLevel(LEVEL_DEBUG)\n\tSetFlags(LnoPrefix | LfunctionName)\n\n\tDebugln(\"This output should have a function name.\")\n\texpect := \"[DEBUG] TestFlagsFunction: This output should have a function name.\\n\"\n\tif buf.String() != expect {\n\t\tt.Errorf(\"\\nExpect:\\n\\t%q\\nGot:\\n\\t%q\\n\", expect, buf.String())\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 The casbin Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage xormadapter\n\nimport (\n\t\"log\"\n\t\"testing\"\n\n\t\"github.com\/casbin\/casbin\"\n\t\"github.com\/casbin\/casbin\/util\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nfunc testGetPolicy(t *testing.T, e *casbin.Enforcer, res [][]string) {\n\tmyRes := e.GetPolicy()\n\tlog.Print(\"Policy: \", myRes)\n\n\tif !util.Array2DEquals(res, myRes) {\n\t\tt.Error(\"Policy: \", myRes, \", supposed to be \", res)\n\t}\n}\n\nfunc TestMySQLAdapter(t *testing.T) {\n\t\/\/ Because the MySQL DB is empty at first,\n\t\/\/ so we need to load the policy from the file adapter (.CSV) first.\n\te := casbin.NewEnforcer(\"examples\/rbac_model.conf\", \"examples\/rbac_policy.csv\")\n\n\ta := NewAdapter(\"mysql\", \"root:@tcp(127.0.0.1:3306)\/\")\n\t\/\/ This is a trick to save the current policy to the MySQL DB.\n\t\/\/ We can't call e.SavePolicy() because the adapter in the enforcer is still the file adapter.\n\t\/\/ The current policy means the policy in the Casbin enforcer (aka in memory).\n\terr := a.SavePolicy(e.GetModel())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Clear the current policy.\n\te.ClearPolicy()\n\ttestGetPolicy(t, e, [][]string{})\n\n\t\/\/ Load the policy from MySQL DB.\n\terr = a.LoadPolicy(e.GetModel())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttestGetPolicy(t, e, [][]string{{\"alice\", \"data1\", \"read\"}, {\"bob\", \"data2\", \"write\"}, {\"data2_admin\", \"data2\", \"read\"}, {\"data2_admin\", \"data2\", \"write\"}})\n\n\t\/\/ Note: you don't need to look at the above code\n\t\/\/ if you already have a working MySQL DB with policy inside.\n\n\t\/\/ Now the MySQL DB has policy, so we can provide a normal use case.\n\t\/\/ Create an adapter and an enforcer.\n\t\/\/ NewEnforcer() will load the policy automatically.\n\ta = NewAdapter(\"mysql\", \"root:@tcp(127.0.0.1:3306)\/\")\n\te = casbin.NewEnforcer(\"examples\/rbac_model.conf\", a)\n\ttestGetPolicy(t, e, [][]string{{\"alice\", \"data1\", \"read\"}, {\"bob\", \"data2\", \"write\"}, {\"data2_admin\", \"data2\", \"read\"}, {\"data2_admin\", \"data2\", \"write\"}})\n}\n\nfunc TestPostgresAdapter(t *testing.T) {\n\t\/\/ Because the Postgres DB is empty at first,\n\t\/\/ so we need to load the policy from the file adapter (.CSV) first.\n\te := casbin.NewEnforcer(\"examples\/rbac_model.conf\", \"examples\/rbac_policy.csv\")\n\n\ta := NewAdapter(\"postgres\", \"user=postgres host=127.0.0.1 port=5432 sslmode=disable\")\n\t\/\/ This is a trick to save the current policy to the Postgres DB.\n\t\/\/ We can't call e.SavePolicy() because the adapter in the enforcer is still the file adapter.\n\t\/\/ The current policy means the policy in the Casbin enforcer (aka in memory).\n\terr := a.SavePolicy(e.GetModel())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Clear the current policy.\n\te.ClearPolicy()\n\ttestGetPolicy(t, e, [][]string{})\n\n\t\/\/ Load the policy from Postgres DB.\n\terr = a.LoadPolicy(e.GetModel())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttestGetPolicy(t, e, [][]string{{\"alice\", \"data1\", \"read\"}, {\"bob\", \"data2\", \"write\"}, {\"data2_admin\", \"data2\", \"read\"}, {\"data2_admin\", \"data2\", \"write\"}})\n\n\t\/\/ Note: you don't need to look at the above code\n\t\/\/ if you already have a working Postgres DB with policy inside.\n\n\t\/\/ Now the Postgres DB has policy, so we can provide a normal use case.\n\t\/\/ Create an adapter and an enforcer.\n\t\/\/ NewEnforcer() will load the policy automatically.\n\ta = NewAdapter(\"postgres\", \"user=postgres host=127.0.0.1 port=5432 sslmode=disable\")\n\te = casbin.NewEnforcer(\"examples\/rbac_model.conf\", a)\n\ttestGetPolicy(t, e, [][]string{{\"alice\", \"data1\", \"read\"}, {\"bob\", \"data2\", \"write\"}, {\"data2_admin\", \"data2\", \"read\"}, {\"data2_admin\", \"data2\", \"write\"}})\n}\n\nfunc TestAutoSave(t *testing.T) {\n\t\/\/ Because the MySQL DB is empty at first,\n\t\/\/ so we need to load the policy from the file adapter (.CSV) first.\n\te := casbin.NewEnforcer(\"examples\/rbac_model.conf\", \"examples\/rbac_policy.csv\")\n\n\ta := NewAdapter(\"mysql\", \"root:@tcp(127.0.0.1:3306)\/\")\n\t\/\/ This is a trick to save the current policy to the MySQL DB.\n\t\/\/ We can't call e.SavePolicy() because the adapter in the enforcer is still the file adapter.\n\t\/\/ The current policy means the policy in the Casbin enforcer (aka in memory).\n\terr := a.SavePolicy(e.GetModel())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Clear the current policy.\n\te.ClearPolicy()\n\ttestGetPolicy(t, e, [][]string{})\n\n\t\/\/ Load the policy from MySQL DB.\n\terr = a.LoadPolicy(e.GetModel())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttestGetPolicy(t, e, [][]string{{\"alice\", \"data1\", \"read\"}, {\"bob\", \"data2\", \"write\"}, {\"data2_admin\", \"data2\", \"read\"}, {\"data2_admin\", \"data2\", \"write\"}})\n\n\t\/\/ Note: you don't need to look at the above code\n\t\/\/ if you already have a working MySQL DB with policy inside.\n\n\t\/\/ Now the MySQL DB has policy, so we can provide a normal use case.\n\t\/\/ Create an adapter and an enforcer.\n\t\/\/ NewEnforcer() will load the policy automatically.\n\ta = NewAdapter(\"mysql\", \"root:@tcp(127.0.0.1:3306)\/\")\n\te = casbin.NewEnforcer(\"examples\/rbac_model.conf\", a)\n\n\t\/\/ AutoSave is enabled by default.\n\t\/\/ Now we disable it.\n\te.EnableAutoSave(false)\n\n\t\/\/ Because AutoSave is disabled, the policy change only affects the policy in Casbin enforcer,\n\t\/\/ it doesn't affect the policy in the storage.\n\te.AddPolicy(\"alice\", \"data1\", \"write\")\n\t\/\/ Reload the policy from the storage to see the effect.\n\te.LoadPolicy()\n\t\/\/ This is still the original policy.\n\ttestGetPolicy(t, e, [][]string{{\"alice\", \"data1\", \"read\"}, {\"bob\", \"data2\", \"write\"}, {\"data2_admin\", \"data2\", \"read\"}, {\"data2_admin\", \"data2\", \"write\"}})\n\n\t\/\/ Now we enable the AutoSave.\n\te.EnableAutoSave(true)\n\n\t\/\/ Because AutoSave is enabled, the policy change not only affects the policy in Casbin enforcer,\n\t\/\/ but also affects the policy in the storage.\n\te.AddPolicy(\"alice\", \"data1\", \"write\")\n\t\/\/ Reload the policy from the storage to see the effect.\n\te.LoadPolicy()\n\t\/\/ The policy has a new rule: \"alice\", \"data1\", \"write\"\n\ttestGetPolicy(t, e, [][]string{{\"alice\", \"data1\", \"read\"}, {\"bob\", \"data2\", \"write\"}, {\"data2_admin\", \"data2\", \"read\"}, {\"data2_admin\", \"data2\", \"write\"}, {\"alice\", \"data1\", \"write\"}})\n}\n<commit_msg>Refactor out initMySQLPolicy() and initPostgresPolicy().<commit_after>\/\/ Copyright 2017 The casbin Authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage xormadapter\n\nimport (\n\t\"log\"\n\t\"testing\"\n\n\t\"github.com\/casbin\/casbin\"\n\t\"github.com\/casbin\/casbin\/util\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nfunc testGetPolicy(t *testing.T, e *casbin.Enforcer, res [][]string) {\n\tmyRes := e.GetPolicy()\n\tlog.Print(\"Policy: \", myRes)\n\n\tif !util.Array2DEquals(res, myRes) {\n\t\tt.Error(\"Policy: \", myRes, \", supposed to be \", res)\n\t}\n}\n\nfunc initMySQLPolicy(t *testing.T) {\n\t\/\/ Because the MySQL DB is empty at first,\n\t\/\/ so we need to load the policy from the file adapter (.CSV) first.\n\te := casbin.NewEnforcer(\"examples\/rbac_model.conf\", \"examples\/rbac_policy.csv\")\n\n\ta := NewAdapter(\"mysql\", \"root:@tcp(127.0.0.1:3306)\/\")\n\t\/\/ This is a trick to save the current policy to the MySQL DB.\n\t\/\/ We can't call e.SavePolicy() because the adapter in the enforcer is still the file adapter.\n\t\/\/ The current policy means the policy in the Casbin enforcer (aka in memory).\n\terr := a.SavePolicy(e.GetModel())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Clear the current policy.\n\te.ClearPolicy()\n\ttestGetPolicy(t, e, [][]string{})\n\n\t\/\/ Load the policy from MySQL DB.\n\terr = a.LoadPolicy(e.GetModel())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttestGetPolicy(t, e, [][]string{{\"alice\", \"data1\", \"read\"}, {\"bob\", \"data2\", \"write\"}, {\"data2_admin\", \"data2\", \"read\"}, {\"data2_admin\", \"data2\", \"write\"}})\n}\n\nfunc initPostgresPolicy(t *testing.T) {\n\t\/\/ Because the Postgres DB is empty at first,\n\t\/\/ so we need to load the policy from the file adapter (.CSV) first.\n\te := casbin.NewEnforcer(\"examples\/rbac_model.conf\", \"examples\/rbac_policy.csv\")\n\n\ta := NewAdapter(\"postgres\", \"user=postgres host=127.0.0.1 port=5432 sslmode=disable\")\n\t\/\/ This is a trick to save the current policy to the Postgres DB.\n\t\/\/ We can't call e.SavePolicy() because the adapter in the enforcer is still the file adapter.\n\t\/\/ The current policy means the policy in the Casbin enforcer (aka in memory).\n\terr := a.SavePolicy(e.GetModel())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Clear the current policy.\n\te.ClearPolicy()\n\ttestGetPolicy(t, e, [][]string{})\n\n\t\/\/ Load the policy from Postgres DB.\n\terr = a.LoadPolicy(e.GetModel())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttestGetPolicy(t, e, [][]string{{\"alice\", \"data1\", \"read\"}, {\"bob\", \"data2\", \"write\"}, {\"data2_admin\", \"data2\", \"read\"}, {\"data2_admin\", \"data2\", \"write\"}})\n}\n\nfunc TestMySQLAdapter(t *testing.T) {\n\t\/\/ Initialize some policy in DB.\n\tinitMySQLPolicy(t)\n\t\/\/ Note: you don't need to look at the above code\n\t\/\/ if you already have a working MySQL DB with policy inside.\n\n\t\/\/ Now the MySQL DB has policy, so we can provide a normal use case.\n\t\/\/ Create an adapter and an enforcer.\n\t\/\/ NewEnforcer() will load the policy automatically.\n\ta := NewAdapter(\"mysql\", \"root:@tcp(127.0.0.1:3306)\/\")\n\te := casbin.NewEnforcer(\"examples\/rbac_model.conf\", a)\n\ttestGetPolicy(t, e, [][]string{{\"alice\", \"data1\", \"read\"}, {\"bob\", \"data2\", \"write\"}, {\"data2_admin\", \"data2\", \"read\"}, {\"data2_admin\", \"data2\", \"write\"}})\n}\n\nfunc TestPostgresAdapter(t *testing.T) {\n\t\/\/ Initialize some policy in DB.\n\tinitPostgresPolicy(t)\n\t\/\/ Note: you don't need to look at the above code\n\t\/\/ if you already have a working Postgres DB with policy inside.\n\n\t\/\/ Now the Postgres DB has policy, so we can provide a normal use case.\n\t\/\/ Create an adapter and an enforcer.\n\t\/\/ NewEnforcer() will load the policy automatically.\n\ta := NewAdapter(\"postgres\", \"user=postgres host=127.0.0.1 port=5432 sslmode=disable\")\n\te := casbin.NewEnforcer(\"examples\/rbac_model.conf\", a)\n\ttestGetPolicy(t, e, [][]string{{\"alice\", \"data1\", \"read\"}, {\"bob\", \"data2\", \"write\"}, {\"data2_admin\", \"data2\", \"read\"}, {\"data2_admin\", \"data2\", \"write\"}})\n}\n\nfunc TestAutoSave(t *testing.T) {\n\t\/\/ Initialize some policy in DB.\n\tinitMySQLPolicy(t)\n\t\/\/ Note: you don't need to look at the above code\n\t\/\/ if you already have a working MySQL DB with policy inside.\n\n\t\/\/ Now the MySQL DB has policy, so we can provide a normal use case.\n\t\/\/ Create an adapter and an enforcer.\n\t\/\/ NewEnforcer() will load the policy automatically.\n\ta := NewAdapter(\"mysql\", \"root:@tcp(127.0.0.1:3306)\/\")\n\te := casbin.NewEnforcer(\"examples\/rbac_model.conf\", a)\n\n\t\/\/ AutoSave is enabled by default.\n\t\/\/ Now we disable it.\n\te.EnableAutoSave(false)\n\n\t\/\/ Because AutoSave is disabled, the policy change only affects the policy in Casbin enforcer,\n\t\/\/ it doesn't affect the policy in the storage.\n\te.AddPolicy(\"alice\", \"data1\", \"write\")\n\t\/\/ Reload the policy from the storage to see the effect.\n\te.LoadPolicy()\n\t\/\/ This is still the original policy.\n\ttestGetPolicy(t, e, [][]string{{\"alice\", \"data1\", \"read\"}, {\"bob\", \"data2\", \"write\"}, {\"data2_admin\", \"data2\", \"read\"}, {\"data2_admin\", \"data2\", \"write\"}})\n\n\t\/\/ Now we enable the AutoSave.\n\te.EnableAutoSave(true)\n\n\t\/\/ Because AutoSave is enabled, the policy change not only affects the policy in Casbin enforcer,\n\t\/\/ but also affects the policy in the storage.\n\te.AddPolicy(\"alice\", \"data1\", \"write\")\n\t\/\/ Reload the policy from the storage to see the effect.\n\te.LoadPolicy()\n\t\/\/ The policy has a new rule: \"alice\", \"data1\", \"write\"\n\ttestGetPolicy(t, e, [][]string{{\"alice\", \"data1\", \"read\"}, {\"bob\", \"data2\", \"write\"}, {\"data2_admin\", \"data2\", \"read\"}, {\"data2_admin\", \"data2\", \"write\"}, {\"alice\", \"data1\", \"write\"}})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\n\tPackage builtin provides documentation for Go's predeclared identifiers.\n\tThe items documented here are not actually in package builtin\n\tbut their descriptions here allow godoc to present documentation\n\tfor the language's special identifiers.\n*\/\npackage builtin\n\n\/\/ bool is the set of boolean values, true and false.\ntype bool bool\n\n\/\/ true and false are the two untyped boolean values.\nconst (\n\ttrue  = 0 == 0 \/\/ Untyped bool.\n\tfalse = 0 != 0 \/\/ Untyped bool.\n)\n\n\/\/ uint8 is the set of all unsigned 8-bit integers.\n\/\/ Range: 0 through 255.\ntype uint8 uint8\n\n\/\/ uint16 is the set of all unsigned 16-bit integers.\n\/\/ Range: 0 through 65535.\ntype uint16 uint16\n\n\/\/ uint32 is the set of all unsigned 32-bit integers.\n\/\/ Range: 0 through 4294967295.\ntype uint32 uint32\n\n\/\/ uint64 is the set of all unsigned 64-bit integers.\n\/\/ Range: 0 through 18446744073709551615.\ntype uint64 uint64\n\n\/\/ int8 is the set of all signed 8-bit integers.\n\/\/ Range: -128 through 127.\ntype int8 int8\n\n\/\/ int16 is the set of all signed 16-bit integers.\n\/\/ Range: -32768 through 32767.\ntype int16 int16\n\n\/\/ int32 is the set of all signed 32-bit integers.\n\/\/ Range: -2147483648 through 2147483647.\ntype int32 int32\n\n\/\/ int64 is the set of all signed 64-bit integers.\n\/\/ Range: -9223372036854775808 through 9223372036854775807.\ntype int64 int64\n\n\/\/ float32 is the set of all IEEE-754 32-bit floating-point numbers.\ntype float32 float32\n\n\/\/ float64 is the set of all IEEE-754 64-bit floating-point numbers.\ntype float64 float64\n\n\/\/ complex64 is the set of all complex numbers with float32 real and\n\/\/ imaginary parts.\ntype complex64 complex64\n\n\/\/ complex128 is the set of all complex numbers with float64 real and\n\/\/ imaginary parts.\ntype complex128 complex128\n\n\/\/ string is the set of all strings of 8-bit bytes, conventionally but not\n\/\/ necessarily representing UTF-8-encoded text. A string may be empty, but\n\/\/ not nil. Values of string type are immutable.\ntype string string\n\n\/\/ int is a signed integer type that is at least 32 bits in size. It is a\n\/\/ distinct type, however, and not an alias for, say, int32.\ntype int int\n\n\/\/ uint is an unsigned integer type that is at least 32 bits in size. It is a\n\/\/ distinct type, however, and not an alias for, say, uint32.\ntype uint uint\n\n\/\/ uintptr is an integer type that is large enough to hold the bit pattern of\n\/\/ any pointer.\ntype uintptr uintptr\n\n\/\/ byte is an alias for uint8 and is equivalent to uint8 in all ways. It is\n\/\/ used, by convention, to distinguish byte values from 8-bit unsigned\n\/\/ integer values.\ntype byte byte\n\n\/\/ rune is an alias for int32 and is equivalent to int32 in all ways. It is\n\/\/ used, by convention, to distinguish character values from integer values.\ntype rune rune\n\n\/\/ iota is a predeclared identifier representing the untyped integer ordinal\n\/\/ number of the current const specification in a (usually parenthesized)\n\/\/ const declaration. It is zero-indexed.\nconst iota = 0 \/\/ Untyped int.\n\n\/\/ nil is a predeclared identifier representing the zero value for a\n\/\/ pointer, channel, func, interface, map, or slice type.\nvar nil Type \/\/ Type must be a pointer, channel, func, interface, map, or slice type\n\n\/\/ Type is here for the purposes of documentation only. It is a stand-in\n\/\/ for any Go type, but represents the same type for any given function\n\/\/ invocation.\ntype Type int\n\n\/\/ Type1 is here for the purposes of documentation only. It is a stand-in\n\/\/ for any Go type, but represents the same type for any given function\n\/\/ invocation.\ntype Type1 int\n\n\/\/ IntegerType is here for the purposes of documentation only. It is a stand-in\n\/\/ for any integer type: int, uint, int8 etc.\ntype IntegerType int\n\n\/\/ FloatType is here for the purposes of documentation only. It is a stand-in\n\/\/ for either float type: float32 or float64.\ntype FloatType float32\n\n\/\/ ComplexType is here for the purposes of documentation only. It is a\n\/\/ stand-in for either complex type: complex64 or complex128.\ntype ComplexType complex64\n\n\/\/ The append built-in function appends elements to the end of a slice. If\n\/\/ it has sufficient capacity, the destination is resliced to accommodate the\n\/\/ new elements. If it does not, a new underlying array will be allocated.\n\/\/ Append returns the updated slice. It is therefore necessary to store the\n\/\/ result of append, often in the variable holding the slice itself:\n\/\/\tslice = append(slice, elem1, elem2)\n\/\/\tslice = append(slice, anotherSlice...)\n\/\/ As a special case, it is legal to append a string to a byte slice, like this:\n\/\/\tslice = append([]byte(\"hello \"), \"world\"...)\nfunc append(slice []Type, elems ...Type) []Type\n\n\/\/ The copy built-in function copies elements from a source slice into a\n\/\/ destination slice. (As a special case, it also will copy bytes from a\n\/\/ string to a slice of bytes.) The source and destination may overlap. Copy\n\/\/ returns the number of elements copied, which will be the minimum of\n\/\/ len(src) and len(dst).\nfunc copy(dst, src []Type) int\n\n\/\/ The delete built-in function deletes the element with the specified key\n\/\/ (m[key]) from the map. If m is nil or there is no such element, delete\n\/\/ is a no-op.\nfunc delete(m map[Type]Type1, key Type)\n\n\/\/ The len built-in function returns the length of v, according to its type:\n\/\/\tArray: the number of elements in v.\n\/\/\tPointer to array: the number of elements in *v (even if v is nil).\n\/\/\tSlice, or map: the number of elements in v; if v is nil, len(v) is zero.\n\/\/\tString: the number of bytes in v.\n\/\/\tChannel: the number of elements queued (unread) in the channel buffer;\n\/\/\tif v is nil, len(v) is zero.\nfunc len(v Type) int\n\n\/\/ The cap built-in function returns the capacity of v, according to its type:\n\/\/\tArray: the number of elements in v (same as len(v)).\n\/\/\tPointer to array: the number of elements in *v (same as len(v)).\n\/\/\tSlice: the maximum length the slice can reach when resliced;\n\/\/\tif v is nil, cap(v) is zero.\n\/\/\tChannel: the channel buffer capacity, in units of elements;\n\/\/\tif v is nil, cap(v) is zero.\nfunc cap(v Type) int\n\n\/\/ The make built-in function allocates and initializes an object of type\n\/\/ slice, map, or chan (only). Like new, the first argument is a type, not a\n\/\/ value. Unlike new, make's return type is the same as the type of its\n\/\/ argument, not a pointer to it. The specification of the result depends on\n\/\/ the type:\n\/\/\tSlice: The size specifies the length. The capacity of the slice is\n\/\/\tequal to its length. A second integer argument may be provided to\n\/\/\tspecify a different capacity; it must be no smaller than the\n\/\/\tlength, so make([]int, 0, 10) allocates a slice of length 0 and\n\/\/\tcapacity 10.\n\/\/\tMap: An empty map is allocated with enough space to hold the\n\/\/\tspecified number of elements. The size may be omitted, in which case\n\/\/\ta small starting size is allocated.\n\/\/\tChannel: The channel's buffer is initialized with the specified\n\/\/\tbuffer capacity. If zero, or the size is omitted, the channel is\n\/\/\tunbuffered.\nfunc make(Type, size IntegerType) Type\n\n\/\/ The new built-in function allocates memory. The first argument is a type,\n\/\/ not a value, and the value returned is a pointer to a newly\n\/\/ allocated zero value of that type.\nfunc new(Type) *Type\n\n\/\/ The complex built-in function constructs a complex value from two\n\/\/ floating-point values. The real and imaginary parts must be of the same\n\/\/ size, either float32 or float64 (or assignable to them), and the return\n\/\/ value will be the corresponding complex type (complex64 for float32,\n\/\/ complex128 for float64).\nfunc complex(r, i FloatType) ComplexType\n\n\/\/ The real built-in function returns the real part of the complex number c.\n\/\/ The return value will be floating point type corresponding to the type of c.\nfunc real(c ComplexType) FloatType\n\n\/\/ The imag built-in function returns the imaginary part of the complex\n\/\/ number c. The return value will be floating point type corresponding to\n\/\/ the type of c.\nfunc imag(c ComplexType) FloatType\n\n\/\/ The close built-in function closes a channel, which must be either\n\/\/ bidirectional or send-only. It should be executed only by the sender,\n\/\/ never the receiver, and has the effect of shutting down the channel after\n\/\/ the last sent value is received. After the last value has been received\n\/\/ from a closed channel c, any receive from c will succeed without\n\/\/ blocking, returning the zero value for the channel element. The form\n\/\/\tx, ok := <-c\n\/\/ will also set ok to false for a closed channel.\nfunc close(c chan<- Type)\n\n\/\/ The panic built-in function stops normal execution of the current\n\/\/ goroutine. When a function F calls panic, normal execution of F stops\n\/\/ immediately. Any functions whose execution was deferred by F are run in\n\/\/ the usual way, and then F returns to its caller. To the caller G, the\n\/\/ invocation of F then behaves like a call to panic, terminating G's\n\/\/ execution and running any deferred functions. This continues until all\n\/\/ functions in the executing goroutine have stopped, in reverse order. At\n\/\/ that point, the program is terminated and the error condition is reported,\n\/\/ including the value of the argument to panic. This termination sequence\n\/\/ is called panicking and can be controlled by the built-in function\n\/\/ recover.\nfunc panic(v interface{})\n\n\/\/ The recover built-in function allows a program to manage behavior of a\n\/\/ panicking goroutine. Executing a call to recover inside a deferred\n\/\/ function (but not any function called by it) stops the panicking sequence\n\/\/ by restoring normal execution and retrieves the error value passed to the\n\/\/ call of panic. If recover is called outside the deferred function it will\n\/\/ not stop a panicking sequence. In this case, or when the goroutine is not\n\/\/ panicking, or if the argument supplied to panic was nil, recover returns\n\/\/ nil. Thus the return value from recover reports whether the goroutine is\n\/\/ panicking.\nfunc recover() interface{}\n\n\/\/ The print built-in function formats its arguments in an\n\/\/ implementation-specific way and writes the result to standard error.\n\/\/ Print is useful for bootstrapping and debugging; it is not guaranteed\n\/\/ to stay in the language.\nfunc print(args ...Type)\n\n\/\/ The println built-in function formats its arguments in an\n\/\/ implementation-specific way and writes the result to standard error.\n\/\/ Spaces are always added between arguments and a newline is appended.\n\/\/ Println is useful for bootstrapping and debugging; it is not guaranteed\n\/\/ to stay in the language.\nfunc println(args ...Type)\n\n\/\/ The error built-in interface type is the conventional interface for\n\/\/ representing an error condition, with the nil value representing no error.\ntype error interface {\n\tError() string\n}\n<commit_msg>builtin: fix signature of the builtin function make<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\n\tPackage builtin provides documentation for Go's predeclared identifiers.\n\tThe items documented here are not actually in package builtin\n\tbut their descriptions here allow godoc to present documentation\n\tfor the language's special identifiers.\n*\/\npackage builtin\n\n\/\/ bool is the set of boolean values, true and false.\ntype bool bool\n\n\/\/ true and false are the two untyped boolean values.\nconst (\n\ttrue  = 0 == 0 \/\/ Untyped bool.\n\tfalse = 0 != 0 \/\/ Untyped bool.\n)\n\n\/\/ uint8 is the set of all unsigned 8-bit integers.\n\/\/ Range: 0 through 255.\ntype uint8 uint8\n\n\/\/ uint16 is the set of all unsigned 16-bit integers.\n\/\/ Range: 0 through 65535.\ntype uint16 uint16\n\n\/\/ uint32 is the set of all unsigned 32-bit integers.\n\/\/ Range: 0 through 4294967295.\ntype uint32 uint32\n\n\/\/ uint64 is the set of all unsigned 64-bit integers.\n\/\/ Range: 0 through 18446744073709551615.\ntype uint64 uint64\n\n\/\/ int8 is the set of all signed 8-bit integers.\n\/\/ Range: -128 through 127.\ntype int8 int8\n\n\/\/ int16 is the set of all signed 16-bit integers.\n\/\/ Range: -32768 through 32767.\ntype int16 int16\n\n\/\/ int32 is the set of all signed 32-bit integers.\n\/\/ Range: -2147483648 through 2147483647.\ntype int32 int32\n\n\/\/ int64 is the set of all signed 64-bit integers.\n\/\/ Range: -9223372036854775808 through 9223372036854775807.\ntype int64 int64\n\n\/\/ float32 is the set of all IEEE-754 32-bit floating-point numbers.\ntype float32 float32\n\n\/\/ float64 is the set of all IEEE-754 64-bit floating-point numbers.\ntype float64 float64\n\n\/\/ complex64 is the set of all complex numbers with float32 real and\n\/\/ imaginary parts.\ntype complex64 complex64\n\n\/\/ complex128 is the set of all complex numbers with float64 real and\n\/\/ imaginary parts.\ntype complex128 complex128\n\n\/\/ string is the set of all strings of 8-bit bytes, conventionally but not\n\/\/ necessarily representing UTF-8-encoded text. A string may be empty, but\n\/\/ not nil. Values of string type are immutable.\ntype string string\n\n\/\/ int is a signed integer type that is at least 32 bits in size. It is a\n\/\/ distinct type, however, and not an alias for, say, int32.\ntype int int\n\n\/\/ uint is an unsigned integer type that is at least 32 bits in size. It is a\n\/\/ distinct type, however, and not an alias for, say, uint32.\ntype uint uint\n\n\/\/ uintptr is an integer type that is large enough to hold the bit pattern of\n\/\/ any pointer.\ntype uintptr uintptr\n\n\/\/ byte is an alias for uint8 and is equivalent to uint8 in all ways. It is\n\/\/ used, by convention, to distinguish byte values from 8-bit unsigned\n\/\/ integer values.\ntype byte byte\n\n\/\/ rune is an alias for int32 and is equivalent to int32 in all ways. It is\n\/\/ used, by convention, to distinguish character values from integer values.\ntype rune rune\n\n\/\/ iota is a predeclared identifier representing the untyped integer ordinal\n\/\/ number of the current const specification in a (usually parenthesized)\n\/\/ const declaration. It is zero-indexed.\nconst iota = 0 \/\/ Untyped int.\n\n\/\/ nil is a predeclared identifier representing the zero value for a\n\/\/ pointer, channel, func, interface, map, or slice type.\nvar nil Type \/\/ Type must be a pointer, channel, func, interface, map, or slice type\n\n\/\/ Type is here for the purposes of documentation only. It is a stand-in\n\/\/ for any Go type, but represents the same type for any given function\n\/\/ invocation.\ntype Type int\n\n\/\/ Type1 is here for the purposes of documentation only. It is a stand-in\n\/\/ for any Go type, but represents the same type for any given function\n\/\/ invocation.\ntype Type1 int\n\n\/\/ IntegerType is here for the purposes of documentation only. It is a stand-in\n\/\/ for any integer type: int, uint, int8 etc.\ntype IntegerType int\n\n\/\/ FloatType is here for the purposes of documentation only. It is a stand-in\n\/\/ for either float type: float32 or float64.\ntype FloatType float32\n\n\/\/ ComplexType is here for the purposes of documentation only. It is a\n\/\/ stand-in for either complex type: complex64 or complex128.\ntype ComplexType complex64\n\n\/\/ The append built-in function appends elements to the end of a slice. If\n\/\/ it has sufficient capacity, the destination is resliced to accommodate the\n\/\/ new elements. If it does not, a new underlying array will be allocated.\n\/\/ Append returns the updated slice. It is therefore necessary to store the\n\/\/ result of append, often in the variable holding the slice itself:\n\/\/\tslice = append(slice, elem1, elem2)\n\/\/\tslice = append(slice, anotherSlice...)\n\/\/ As a special case, it is legal to append a string to a byte slice, like this:\n\/\/\tslice = append([]byte(\"hello \"), \"world\"...)\nfunc append(slice []Type, elems ...Type) []Type\n\n\/\/ The copy built-in function copies elements from a source slice into a\n\/\/ destination slice. (As a special case, it also will copy bytes from a\n\/\/ string to a slice of bytes.) The source and destination may overlap. Copy\n\/\/ returns the number of elements copied, which will be the minimum of\n\/\/ len(src) and len(dst).\nfunc copy(dst, src []Type) int\n\n\/\/ The delete built-in function deletes the element with the specified key\n\/\/ (m[key]) from the map. If m is nil or there is no such element, delete\n\/\/ is a no-op.\nfunc delete(m map[Type]Type1, key Type)\n\n\/\/ The len built-in function returns the length of v, according to its type:\n\/\/\tArray: the number of elements in v.\n\/\/\tPointer to array: the number of elements in *v (even if v is nil).\n\/\/\tSlice, or map: the number of elements in v; if v is nil, len(v) is zero.\n\/\/\tString: the number of bytes in v.\n\/\/\tChannel: the number of elements queued (unread) in the channel buffer;\n\/\/\tif v is nil, len(v) is zero.\nfunc len(v Type) int\n\n\/\/ The cap built-in function returns the capacity of v, according to its type:\n\/\/\tArray: the number of elements in v (same as len(v)).\n\/\/\tPointer to array: the number of elements in *v (same as len(v)).\n\/\/\tSlice: the maximum length the slice can reach when resliced;\n\/\/\tif v is nil, cap(v) is zero.\n\/\/\tChannel: the channel buffer capacity, in units of elements;\n\/\/\tif v is nil, cap(v) is zero.\nfunc cap(v Type) int\n\n\/\/ The make built-in function allocates and initializes an object of type\n\/\/ slice, map, or chan (only). Like new, the first argument is a type, not a\n\/\/ value. Unlike new, make's return type is the same as the type of its\n\/\/ argument, not a pointer to it. The specification of the result depends on\n\/\/ the type:\n\/\/\tSlice: The size specifies the length. The capacity of the slice is\n\/\/\tequal to its length. A second integer argument may be provided to\n\/\/\tspecify a different capacity; it must be no smaller than the\n\/\/\tlength, so make([]int, 0, 10) allocates a slice of length 0 and\n\/\/\tcapacity 10.\n\/\/\tMap: An empty map is allocated with enough space to hold the\n\/\/\tspecified number of elements. The size may be omitted, in which case\n\/\/\ta small starting size is allocated.\n\/\/\tChannel: The channel's buffer is initialized with the specified\n\/\/\tbuffer capacity. If zero, or the size is omitted, the channel is\n\/\/\tunbuffered.\nfunc make(t Type, size ...IntegerType) Type\n\n\/\/ The new built-in function allocates memory. The first argument is a type,\n\/\/ not a value, and the value returned is a pointer to a newly\n\/\/ allocated zero value of that type.\nfunc new(Type) *Type\n\n\/\/ The complex built-in function constructs a complex value from two\n\/\/ floating-point values. The real and imaginary parts must be of the same\n\/\/ size, either float32 or float64 (or assignable to them), and the return\n\/\/ value will be the corresponding complex type (complex64 for float32,\n\/\/ complex128 for float64).\nfunc complex(r, i FloatType) ComplexType\n\n\/\/ The real built-in function returns the real part of the complex number c.\n\/\/ The return value will be floating point type corresponding to the type of c.\nfunc real(c ComplexType) FloatType\n\n\/\/ The imag built-in function returns the imaginary part of the complex\n\/\/ number c. The return value will be floating point type corresponding to\n\/\/ the type of c.\nfunc imag(c ComplexType) FloatType\n\n\/\/ The close built-in function closes a channel, which must be either\n\/\/ bidirectional or send-only. It should be executed only by the sender,\n\/\/ never the receiver, and has the effect of shutting down the channel after\n\/\/ the last sent value is received. After the last value has been received\n\/\/ from a closed channel c, any receive from c will succeed without\n\/\/ blocking, returning the zero value for the channel element. The form\n\/\/\tx, ok := <-c\n\/\/ will also set ok to false for a closed channel.\nfunc close(c chan<- Type)\n\n\/\/ The panic built-in function stops normal execution of the current\n\/\/ goroutine. When a function F calls panic, normal execution of F stops\n\/\/ immediately. Any functions whose execution was deferred by F are run in\n\/\/ the usual way, and then F returns to its caller. To the caller G, the\n\/\/ invocation of F then behaves like a call to panic, terminating G's\n\/\/ execution and running any deferred functions. This continues until all\n\/\/ functions in the executing goroutine have stopped, in reverse order. At\n\/\/ that point, the program is terminated and the error condition is reported,\n\/\/ including the value of the argument to panic. This termination sequence\n\/\/ is called panicking and can be controlled by the built-in function\n\/\/ recover.\nfunc panic(v interface{})\n\n\/\/ The recover built-in function allows a program to manage behavior of a\n\/\/ panicking goroutine. Executing a call to recover inside a deferred\n\/\/ function (but not any function called by it) stops the panicking sequence\n\/\/ by restoring normal execution and retrieves the error value passed to the\n\/\/ call of panic. If recover is called outside the deferred function it will\n\/\/ not stop a panicking sequence. In this case, or when the goroutine is not\n\/\/ panicking, or if the argument supplied to panic was nil, recover returns\n\/\/ nil. Thus the return value from recover reports whether the goroutine is\n\/\/ panicking.\nfunc recover() interface{}\n\n\/\/ The print built-in function formats its arguments in an\n\/\/ implementation-specific way and writes the result to standard error.\n\/\/ Print is useful for bootstrapping and debugging; it is not guaranteed\n\/\/ to stay in the language.\nfunc print(args ...Type)\n\n\/\/ The println built-in function formats its arguments in an\n\/\/ implementation-specific way and writes the result to standard error.\n\/\/ Spaces are always added between arguments and a newline is appended.\n\/\/ Println is useful for bootstrapping and debugging; it is not guaranteed\n\/\/ to stay in the language.\nfunc println(args ...Type)\n\n\/\/ The error built-in interface type is the conventional interface for\n\/\/ representing an error condition, with the nil value representing no error.\ntype error interface {\n\tError() string\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Ulrich Kunitz. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ The package u32 provides basic function for the uint32 type.\npackage lzma\n\n\/* Naming conventions follows the CodeReviewComments in the Go Wiki. *\/\n\n\/\/ ntzConst is used by the functions NTZ and NLZ.\nconst ntzConst = 0x04d7651f\n\n\/\/ Helper table for de Bruijn algorithm by Danny Dubé. See Henry S.\n\/\/ Warren, Jr. \"Hacker's Delight\" section 5-1 figure 5-26.\nvar ntzTable = [32]int8{\n\t0, 1, 2, 24, 3, 19, 6, 25,\n\t22, 4, 20, 10, 16, 7, 12, 26,\n\t31, 23, 18, 5, 21, 9, 15, 11,\n\t30, 17, 8, 14, 29, 13, 28, 27}\n\n\/\/ ntz32 computes the number of trailing zeros for an unsigned 32-bit integer.\nfunc ntz32(x uint32) int {\n\tif x == 0 {\n\t\treturn 32\n\t}\n\tx = (x & -x) * ntzConst\n\treturn int(ntzTable[x>>27])\n}\n\n\/\/ nlz32 computes the number of leading zeros for an unsigned 32-bit integer.\nfunc nlz32(x uint32) int {\n\t\/\/ Smear left most bit to the right\n\tx |= x >> 1\n\tx |= x >> 2\n\tx |= x >> 4\n\tx |= x >> 8\n\tx |= x >> 16\n\t\/\/ Use ntz mechanism to calculate nlz.\n\tx++\n\tif x == 0 {\n\t\treturn 0\n\t}\n\tx *= ntzConst\n\treturn 32 - int(ntzTable[x>>27])\n}\n<commit_msg>lzma: fixed comments and formatting in bitops.go<commit_after>\/\/ Copyright 2015 Ulrich Kunitz. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage lzma\n\n\/* Naming conventions follows the CodeReviewComments in the Go Wiki. *\/\n\n\/\/ ntz32Const is used by the functions NTZ and NLZ.\nconst ntz32Const = 0x04d7651f\n\n\/\/ ntz32Table is a helper table for de Bruijn algorithm by Danny Dubé.\n\/\/ See Henry S. Warren, Jr. \"Hacker's Delight\" section 5-1 figure 5-26.\nvar ntz32Table = [32]int8{\n\t0, 1, 2, 24, 3, 19, 6, 25,\n\t22, 4, 20, 10, 16, 7, 12, 26,\n\t31, 23, 18, 5, 21, 9, 15, 11,\n\t30, 17, 8, 14, 29, 13, 28, 27,\n}\n\n\/\/ ntz32 computes the number of trailing zeros for an unsigned 32-bit integer.\nfunc ntz32(x uint32) int {\n\tif x == 0 {\n\t\treturn 32\n\t}\n\tx = (x & -x) * ntz32Const\n\treturn int(ntz32Table[x>>27])\n}\n\n\/\/ nlz32 computes the number of leading zeros for an unsigned 32-bit integer.\nfunc nlz32(x uint32) int {\n\t\/\/ Smear left most bit to the right\n\tx |= x >> 1\n\tx |= x >> 2\n\tx |= x >> 4\n\tx |= x >> 8\n\tx |= x >> 16\n\t\/\/ Use ntz mechanism to calculate nlz.\n\tx++\n\tif x == 0 {\n\t\treturn 0\n\t}\n\tx *= ntz32Const\n\treturn 32 - int(ntz32Table[x>>27])\n}\n<|endoftext|>"}
{"text":"<commit_before>package lzma\n\nimport \"io\"\n\nvar (\n\terrOffset       = newError(\"offset outside buffer range\")\n\terrAgain        = newError(\"buffer exceeded; repeat\")\n\terrNegLen       = newError(\"length is negative\")\n\terrNrOverflow   = newError(\"number overflow\")\n\terrCapacity     = newError(\"capacity must be larger than zero\")\n\terrClosedBuffer = newError(\"buffer is closed for writing\")\n)\n\ntype buffer struct {\n\tdata       []byte\n\tstart      int64\n\tcursor     int64\n\tend        int64\n\twriteLimit int\n\tclosed     bool\n}\n\nfunc (b *buffer) Cap() int {\n\treturn len(b.data)\n}\n\nfunc (b *buffer) Len() int {\n\treturn int(b.end - b.start)\n}\n\nfunc (b *buffer) Readable() int {\n\treturn int(b.end - b.cursor)\n}\n\nfunc (b *buffer) Writable() int {\n\treturn int(b.cursor + int64(b.writeLimit) - b.end)\n}\n\nfunc (b *buffer) setEnd(x int64) {\n\tif x < 0 {\n\t\tpanic(\"b.end overflow?\")\n\t}\n\tb.end = x\n\tb.start = x - int64(len(b.data))\n\tif b.start < 0 {\n\t\tb.start = 0\n\t}\n}\n\nfunc (b *buffer) index(off int64) int {\n\tif off < 0 {\n\t\tpanic(\"negative offsets are not supported\")\n\t}\n\treturn int(off % int64(len(b.data)))\n}\n\nfunc initBuffer(b *buffer, capacity int) error {\n\tif capacity <= 0 {\n\t\treturn errCapacity\n\t}\n\t*b = buffer{data: make([]byte, capacity), writeLimit: capacity}\n\treturn nil\n}\n\nfunc newBuffer(capacity int) (b *buffer, err error) {\n\tb = new(buffer)\n\terr = initBuffer(b, capacity)\n\treturn\n}\n\nfunc (b *buffer) verifyOffset(off int64) error {\n\tif !(b.start <= off && off <= b.end) {\n\t\treturn errOffset\n\t}\n\treturn nil\n}\n\nfunc (b *buffer) readOff(p []byte, off int64) {\n\tfor len(p) > 0 {\n\t\ts := b.index(off)\n\t\tm := copy(p, b.data[s:])\n\t\toff += int64(m)\n\t\tp = p[m:]\n\t}\n}\n\nfunc (b *buffer) ReadAt(p []byte, off int64) (n int, err error) {\n\tif off < b.start {\n\t\treturn 0, errOffset\n\t}\n\tk := b.end - off\n\tn = len(p)\n\tif k < int64(n) {\n\t\tif k < 0 {\n\t\t\treturn 0, errOffset\n\t\t}\n\t\tif b.closed {\n\t\t\terr = io.EOF\n\t\t} else {\n\t\t\terr = errAgain\n\t\t}\n\t\tn = int(k)\n\t}\n\tb.readOff(p[:n], off)\n\treturn\n}\n\nfunc (b *buffer) Read(p []byte) (n int, err error) {\n\tk := b.end - b.cursor\n\tn = len(p)\n\tif k < int64(n) {\n\t\tif k < 0 {\n\t\t\tpanic(\"wrong b.cursor\")\n\t\t}\n\t\tif k == 0 && b.closed {\n\t\t\treturn 0, io.EOF\n\t\t}\n\t\tn = int(k)\n\t}\n\tb.readOff(p[:n], b.cursor)\n\tb.cursor += int64(n)\n\treturn\n}\n\nfunc (b *buffer) Discard(n int) (discarded int, err error) {\n\tif n < 0 {\n\t\treturn 0, errNegLen\n\t}\n\tk := b.end - b.cursor\n\tif k < int64(n) {\n\t\tif k < 0 {\n\t\t\tpanic(\"wrong b.cursor\")\n\t\t}\n\t\tif b.closed {\n\t\t\terr = io.EOF\n\t\t} else {\n\t\t\terr = errAgain\n\t\t}\n\t\tn = int(k)\n\t}\n\tdiscarded = n\n\tb.cursor += int64(n)\n\treturn\n}\n\nfunc (b *buffer) copyNOff(w io.Writer, n int, off int64) (copied int, err error) {\n\tstart, end := off, off+int64(n)\n\te := b.index(end)\n\tfor off < end {\n\t\ts := b.index(off)\n\t\tvar q []byte\n\t\tif s < e {\n\t\t\tq = b.data[s:e]\n\t\t} else {\n\t\t\tq = b.data[s:]\n\t\t}\n\t\tvar m int\n\t\tm, err = w.Write(q)\n\t\toff += int64(m)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn int(off - start), err\n}\n\nfunc (b *buffer) CopyAt(w io.Writer, n int, off int64) (copied int, err error) {\n\tif n < 0 {\n\t\treturn 0, errNegLen\n\t}\n\tif off < b.start {\n\t\treturn 0, errOffset\n\t}\n\tk := b.end - off\n\tif k < int64(n) {\n\t\tif k < 0 {\n\t\t\treturn 0, errOffset\n\t\t}\n\t\tif b.closed {\n\t\t\terr = io.EOF\n\t\t} else {\n\t\t\terr = errAgain\n\t\t}\n\t\tn = int(k)\n\t}\n\tvar cerr error\n\tcopied, cerr = b.copyNOff(w, n, off)\n\tif cerr != nil {\n\t\terr = cerr\n\t}\n\treturn\n}\n\nfunc (b *buffer) Copy(w io.Writer, n int) (copied int, err error) {\n\tif n < 0 {\n\t\treturn 0, errNegLen\n\t}\n\tk := b.end - b.cursor\n\tif k < int64(n) {\n\t\tif k < 0 {\n\t\t\tpanic(\"wrong b.cursor\")\n\t\t}\n\t\tif k == 0 && b.closed {\n\t\t\treturn 0, io.EOF\n\t\t}\n\t\tn = int(k)\n\t}\n\tcopied, err = b.copyNOff(w, n, b.cursor)\n\tb.cursor += int64(copied)\n\treturn\n}\n\nfunc (b *buffer) ReadByteAt(off int64) (c byte, err error) {\n\tif !(b.start <= off && off <= b.end) {\n\t\treturn 0, errOffset\n\t}\n\tif off == b.end {\n\t\tif b.closed {\n\t\t\treturn 0, io.EOF\n\t\t}\n\t\treturn 0, errAgain\n\t}\n\ti := b.index(off)\n\treturn b.data[i], nil\n}\n\nfunc (b *buffer) ReadByte() (c byte, err error) {\n\tif b.cursor == b.end {\n\t\tif b.closed {\n\t\t\treturn 0, io.EOF\n\t\t}\n\t\treturn 0, errAgain\n\t}\n\ti := b.index(b.cursor)\n\tb.cursor++\n\treturn b.data[i], nil\n}\n\nfunc (b *buffer) writeSlice(p []byte) {\n\toff := b.end\n\tfor len(p) > 0 {\n\t\ti := b.index(off)\n\t\tm := copy(b.data[i:], p)\n\t\toff += int64(m)\n\t\tif off < 0 {\n\t\t\tpanic(\"overflow b.end\")\n\t\t}\n\t\tp = p[m:]\n\t}\n\tb.setEnd(off)\n}\n\nfunc (b *buffer) Write(p []byte) (n int, err error) {\n\tif b.closed {\n\t\treturn 0, errClosedBuffer\n\t}\n\tn = b.Writable()\n\tif n < len(p) {\n\t\terr = errAgain\n\t\tp = p[:n]\n\t}\n\tb.writeSlice(p)\n\treturn\n}\n\nfunc (b *buffer) WriteByte(c byte) error {\n\tif b.closed {\n\t\treturn errClosedBuffer\n\t}\n\tif b.Writable() < 1 {\n\t\treturn errAgain\n\t}\n\ti := b.index(b.end)\n\tb.data[i] = c\n\tb.setEnd(b.end + 1)\n\treturn nil\n}\n\nfunc (b *buffer) WriteRepOff(n int, off int64) (written int, err error) {\n\tif n < 0 {\n\t\treturn 0, errNegLen\n\t}\n\tif b.closed {\n\t\treturn 0, errClosedBuffer\n\t}\n\tif !(b.start <= off && off < b.end) {\n\t\treturn 0, errOffset\n\t}\n\tif b.Writable() < n {\n\t\treturn 0, errAgain\n\t}\n\tend := off + int64(n)\n\te := b.index(end)\n\tfor off < end {\n\t\ts := b.index(off)\n\t\tvar t int\n\t\tif end > b.end {\n\t\t\tt = b.index(b.end)\n\t\t} else {\n\t\t\tt = e\n\t\t}\n\t\tvar q []byte\n\t\tif s < t {\n\t\t\tq = b.data[s:t]\n\t\t} else {\n\t\t\tq = b.data[s:]\n\t\t}\n\t\tb.writeSlice(q)\n\t\toff += int64(len(q))\n\t}\n\treturn n, nil\n}\n\nfunc (b *buffer) Close() error {\n\tb.closed = true\n\treturn nil\n}\n\nfunc (b *buffer) EqualBytes(off1, off2 int64, max int) int {\n\tif off1 < b.start || off2 < b.start {\n\t\treturn 0\n\t}\n\tn := b.end - off1\n\tif n < int64(max) {\n\t\tif n < 1 {\n\t\t\treturn 0\n\t\t}\n\t\tmax = int(n)\n\t}\n\tn = b.end - off2\n\tif n < int64(max) {\n\t\tif n < 1 {\n\t\t\treturn 0\n\t\t}\n\t\tmax = int(n)\n\t}\n\tfor k := 0; k < max; k++ {\n\t\ti, j := b.index(off1+int64(k)), b.index(off2+int64(k))\n\t\tif b.data[i] != b.data[j] {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn max\n}\n<commit_msg>lzma: added documentation to the buffer code<commit_after>package lzma\n\nimport \"io\"\n\n\/\/ buffer implements a ring buffer with features to support an LZMA reader and\n\/\/ writer dictionary.\n\/\/\n\/\/ The ring buffer supports writing at the end offset and writing at the cursor\n\/\/ offset. The field start stores the start offset of the buffer, but could be\n\/\/ computed by b.end - b.Cap().\n\/\/\n\/\/ The reader dictionary will have the head at the end offset the writer\n\/\/ dictionary will have the head at the cursor offset.\ntype buffer struct {\n\t\/\/ plain constant length field to store the data\n\tdata []byte\n\t\/\/ start offset of the buffer; b.end - len(b.data)\n\tstart int64\n\t\/\/ offset for reading\n\tcursor int64\n\t\/\/ end offset of the current buffer window; use setEnd method for\n\t\/\/ updates\n\tend int64\n\t\/\/ writeLimit gives the maximum distance between end and cursor\n\twriteLimit int\n\t\/\/ marks the buffer as closed for writing\n\tclosed bool\n}\n\n\/\/ errors generated by the ring buffer functions\nvar (\n\terrOffset       = newError(\"offset outside buffer range\")\n\terrAgain        = newError(\"buffer exceeded; repeat\")\n\terrNegLen       = newError(\"length is negative\")\n\terrNrOverflow   = newError(\"number overflow\")\n\terrCapacity     = newError(\"capacity must be larger than zero\")\n\terrClosedBuffer = newError(\"buffer is closed for writing\")\n)\n\n\/\/ Cap returns the capacity of the ring buffer.\nfunc (b *buffer) Cap() int {\n\treturn len(b.data)\n}\n\n\/\/ Len returns the data amount currently stored in the buffer. It will grow\n\/\/ from zero to the capacity of the buffer.\nfunc (b *buffer) Len() int {\n\treturn int(b.end - b.start)\n}\n\n\/\/ Readable returns the number of bytes that are currently available for\n\/\/ reading.\nfunc (b *buffer) Readable() int {\n\treturn int(b.end - b.cursor)\n}\n\n\/\/ Writable returns the number of byte that are curently available for writing.\nfunc (b *buffer) Writable() int {\n\treturn int(b.cursor + int64(b.writeLimit) - b.end)\n}\n\n\/\/ setEnd updates the start and end fields. Use it always to update the end\n\/\/ field.\nfunc (b *buffer) setEnd(x int64) {\n\tif x < 0 {\n\t\tpanic(\"b.end overflow?\")\n\t}\n\tb.end = x\n\tb.start = x - int64(len(b.data))\n\tif b.start < 0 {\n\t\tb.start = 0\n\t}\n}\n\n\/\/ index computes the index into the data slice for a particular offset.\nfunc (b *buffer) index(off int64) int {\n\tif off < 0 {\n\t\tpanic(\"negative offsets are not supported\")\n\t}\n\treturn int(off % int64(len(b.data)))\n}\n\n\/\/ initBuffer initializes an already allocated buffer.\nfunc initBuffer(b *buffer, capacity int) error {\n\tif capacity <= 0 {\n\t\treturn errCapacity\n\t}\n\t*b = buffer{data: make([]byte, capacity), writeLimit: capacity}\n\treturn nil\n}\n\n\/\/ newBuffer creates a new buffer instance.\nfunc newBuffer(capacity int) (b *buffer, err error) {\n\tb = new(buffer)\n\terr = initBuffer(b, capacity)\n\treturn\n}\n\n\/\/ readOff is a helper method for the ReadAt and Read methods.\nfunc (b *buffer) readOff(p []byte, off int64) {\n\tfor len(p) > 0 {\n\t\ts := b.index(off)\n\t\tm := copy(p, b.data[s:])\n\t\toff += int64(m)\n\t\tp = p[m:]\n\t}\n}\n\n\/\/ ReadAt reads data into p at the specified offset. The offset must be inside\n\/\/ the buffer. It the slice cannot be completely filed errAgain is reported\n\/\/ unless the buffer is not closed. In that case the function returns io.EOF.\nfunc (b *buffer) ReadAt(p []byte, off int64) (n int, err error) {\n\tif off < b.start {\n\t\treturn 0, errOffset\n\t}\n\tk := b.end - off\n\tn = len(p)\n\tif k < int64(n) {\n\t\tif k < 0 {\n\t\t\treturn 0, errOffset\n\t\t}\n\t\tif b.closed {\n\t\t\terr = io.EOF\n\t\t} else {\n\t\t\terr = errAgain\n\t\t}\n\t\tn = int(k)\n\t}\n\tb.readOff(p[:n], off)\n\treturn\n}\n\n\/\/ Read tries to read data into the buffer. No error is returned if n < len(p).\nfunc (b *buffer) Read(p []byte) (n int, err error) {\n\tk := b.end - b.cursor\n\tn = len(p)\n\tif k < int64(n) {\n\t\tif k < 0 {\n\t\t\tpanic(\"wrong b.cursor\")\n\t\t}\n\t\tif k == 0 && b.closed {\n\t\t\treturn 0, io.EOF\n\t\t}\n\t\tn = int(k)\n\t}\n\tb.readOff(p[:n], b.cursor)\n\tb.cursor += int64(n)\n\treturn\n}\n\n\/\/ Discard skips n bytes of reading bytes. If less than n bytes are skipped\n\/\/ errAgain or io.EOF if closed is returned.\nfunc (b *buffer) Discard(n int) (discarded int, err error) {\n\tif n < 0 {\n\t\treturn 0, errNegLen\n\t}\n\tk := b.end - b.cursor\n\tif k < int64(n) {\n\t\tif k < 0 {\n\t\t\tpanic(\"wrong b.cursor\")\n\t\t}\n\t\tif b.closed {\n\t\t\terr = io.EOF\n\t\t} else {\n\t\t\terr = errAgain\n\t\t}\n\t\tn = int(k)\n\t}\n\tdiscarded = n\n\tb.cursor += int64(n)\n\treturn\n}\n\n\/\/ copyNOff is a helper method for CopyAt and Copy.\nfunc (b *buffer) copyNOff(w io.Writer, n int, off int64) (copied int, err error) {\n\tstart, end := off, off+int64(n)\n\te := b.index(end)\n\tfor off < end {\n\t\ts := b.index(off)\n\t\tvar q []byte\n\t\tif s < e {\n\t\t\tq = b.data[s:e]\n\t\t} else {\n\t\t\tq = b.data[s:]\n\t\t}\n\t\tvar m int\n\t\tm, err = w.Write(q)\n\t\toff += int64(m)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn int(off - start), err\n}\n\n\/\/ CopyAt behaves like ReadAt but writes the data into the writer.\nfunc (b *buffer) CopyAt(w io.Writer, n int, off int64) (copied int, err error) {\n\tif n < 0 {\n\t\treturn 0, errNegLen\n\t}\n\tif off < b.start {\n\t\treturn 0, errOffset\n\t}\n\tk := b.end - off\n\tif k < int64(n) {\n\t\tif k < 0 {\n\t\t\treturn 0, errOffset\n\t\t}\n\t\tif b.closed {\n\t\t\terr = io.EOF\n\t\t} else {\n\t\t\terr = errAgain\n\t\t}\n\t\tn = int(k)\n\t}\n\tvar cerr error\n\tcopied, cerr = b.copyNOff(w, n, off)\n\tif cerr != nil {\n\t\terr = cerr\n\t}\n\treturn\n}\n\n\/\/ Copy behaves like read but the data is written into the writer.\nfunc (b *buffer) Copy(w io.Writer, n int) (copied int, err error) {\n\tif n < 0 {\n\t\treturn 0, errNegLen\n\t}\n\tk := b.end - b.cursor\n\tif k < int64(n) {\n\t\tif k < 0 {\n\t\t\tpanic(\"wrong b.cursor\")\n\t\t}\n\t\tif k == 0 && b.closed {\n\t\t\treturn 0, io.EOF\n\t\t}\n\t\tn = int(k)\n\t}\n\tcopied, err = b.copyNOff(w, n, b.cursor)\n\tb.cursor += int64(copied)\n\treturn\n}\n\n\/\/ ReadByteAt reads a single byte at the given offset.\nfunc (b *buffer) ReadByteAt(off int64) (c byte, err error) {\n\tif !(b.start <= off && off <= b.end) {\n\t\treturn 0, errOffset\n\t}\n\tif off == b.end {\n\t\tif b.closed {\n\t\t\treturn 0, io.EOF\n\t\t}\n\t\treturn 0, errAgain\n\t}\n\ti := b.index(off)\n\treturn b.data[i], nil\n}\n\n\/\/ ReadByte reads a single byte.\nfunc (b *buffer) ReadByte() (c byte, err error) {\n\tif b.cursor == b.end {\n\t\tif b.closed {\n\t\t\treturn 0, io.EOF\n\t\t}\n\t\treturn 0, errAgain\n\t}\n\ti := b.index(b.cursor)\n\tb.cursor++\n\treturn b.data[i], nil\n}\n\n\/\/ writeSlice writes the slice p unconditionally into the buffer.\nfunc (b *buffer) writeSlice(p []byte) {\n\toff := b.end\n\tfor len(p) > 0 {\n\t\ti := b.index(off)\n\t\tm := copy(b.data[i:], p)\n\t\toff += int64(m)\n\t\tif off < 0 {\n\t\t\tpanic(\"overflow b.end\")\n\t\t}\n\t\tp = p[m:]\n\t}\n\tb.setEnd(off)\n}\n\n\/\/ Writes data into the buffer. If n < len(p) errAgain is returned. If the\n\/\/ buffer is closed errClosedBuffer is returned.\nfunc (b *buffer) Write(p []byte) (n int, err error) {\n\tif b.closed {\n\t\treturn 0, errClosedBuffer\n\t}\n\tn = b.Writable()\n\tif n < len(p) {\n\t\terr = errAgain\n\t\tp = p[:n]\n\t}\n\tb.writeSlice(p)\n\treturn\n}\n\n\/\/ Writes a single byte into the buffer.\nfunc (b *buffer) WriteByte(c byte) error {\n\tif b.closed {\n\t\treturn errClosedBuffer\n\t}\n\tif b.Writable() < 1 {\n\t\treturn errAgain\n\t}\n\ti := b.index(b.end)\n\tb.data[i] = c\n\tb.setEnd(b.end + 1)\n\treturn nil\n}\n\n\/\/ WriteRepOff writes a match at the given offset into the buffer.\nfunc (b *buffer) WriteRepOff(n int, off int64) (written int, err error) {\n\tif n < 0 {\n\t\treturn 0, errNegLen\n\t}\n\tif b.closed {\n\t\treturn 0, errClosedBuffer\n\t}\n\tif !(b.start <= off && off < b.end) {\n\t\treturn 0, errOffset\n\t}\n\tif b.Writable() < n {\n\t\treturn 0, errAgain\n\t}\n\tend := off + int64(n)\n\te := b.index(end)\n\tfor off < end {\n\t\ts := b.index(off)\n\t\tvar t int\n\t\tif end > b.end {\n\t\t\tt = b.index(b.end)\n\t\t} else {\n\t\t\tt = e\n\t\t}\n\t\tvar q []byte\n\t\tif s < t {\n\t\t\tq = b.data[s:t]\n\t\t} else {\n\t\t\tq = b.data[s:]\n\t\t}\n\t\tb.writeSlice(q)\n\t\toff += int64(len(q))\n\t}\n\treturn n, nil\n}\n\n\/\/ Close closes the buffer.\nfunc (b *buffer) Close() error {\n\tb.closed = true\n\treturn nil\n}\n\n\/\/ EqualBytes count the equal bytes at off1 and off2 until max is reached.\nfunc (b *buffer) EqualBytes(off1, off2 int64, max int) int {\n\tif off1 < b.start || off2 < b.start {\n\t\treturn 0\n\t}\n\tif max < 0 {\n\t\treturn 0\n\t}\n\tn := b.end - off1\n\tif n < int64(max) {\n\t\tif n < 1 {\n\t\t\treturn 0\n\t\t}\n\t\tmax = int(n)\n\t}\n\tn = b.end - off2\n\tif n < int64(max) {\n\t\tif n < 1 {\n\t\t\treturn 0\n\t\t}\n\t\tmax = int(n)\n\t}\n\tfor k := 0; k < max; k++ {\n\t\ti, j := b.index(off1+int64(k)), b.index(off2+int64(k))\n\t\tif b.data[i] != b.data[j] {\n\t\t\treturn k\n\t\t}\n\t}\n\treturn max\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/mail\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/mhale\/smtpd\"\n\t\"github.com\/nlopes\/slack\"\n\t\"github.com\/veqryn\/go-email\/email\"\n)\n\nvar (\n\tport         = os.Getenv(\"PORT\")\n\tslackToken   = os.Getenv(\"SLACK_TOKEN\")\n\tslackChannel = os.Getenv(\"SLACK_CHANNEL\")\n\tdomainList   = os.Getenv(\"DOMAIN_LIST\")\n\tfiletype     string\n)\n\nfunc mailHandler(origin net.Addr, from string, to []string, data []byte) {\n\tmsg, _ := email.ParseMessage(bytes.NewReader(data))\n\tsubject := msg.Header.Get(\"Subject\")\n\tsender := msg.Header.Get(\"From\")\n\trecipient := msg.Header.Get(\"To\")\n\n\t\/\/ If we have been given a list of recipient domains, filter on these\n\tif len(domainList) > 0 {\n\t\tdomains := strings.Split(domainList, \",\")\n\t\trcpt, _ := mail.ParseAddress(recipient)\n\t\trecipientDomain := strings.Split(rcpt.Address, \"@\")[1]\n\t\tok := false\n\t\tfor i := 0; i < len(domains); i++ {\n\t\t\tif recipientDomain == domains[i] {\n\t\t\t\tok = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t}\n\tapi := slack.New(slackToken)\n\tfor _, part := range msg.MessagesContentTypePrefix(\"text\/plain\") {\n\t\tuploadparams := slack.FileUploadParameters{\n\t\t\tChannels:       []string{slackChannel},\n\t\t\tTitle:          fmt.Sprintf(\"Subject: %s\", subject),\n\t\t\tFiletype:       \"text\",\n\t\t\tContent:        string(part.Body),\n\t\t\tInitialComment: fmt.Sprintf(\"To: %s\\nFrom: %s\", recipient, sender),\n\t\t}\n\t\tfile, err := api.UploadFile(uploadparams)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t\treturn\n\t\t}\n\t\tlog.Printf(\"Message successfully sent to channel %s as text file %s\", slackChannel, file.Name)\n\t}\n\tfor _, part := range msg.MessagesContentTypePrefix(\"text\/html\") {\n\t\tuploadparams := slack.FileUploadParameters{\n\t\t\tChannels:       []string{slackChannel},\n\t\t\tTitle:          fmt.Sprintf(\"Subject: %s\", subject),\n\t\t\tFiletype:       \"html\",\n\t\t\tContent:        string(part.Body),\n\t\t\tInitialComment: fmt.Sprintf(\"To: %s\\nFrom: %s\", recipient, sender),\n\t\t}\n\t\tfile, err := api.UploadFile(uploadparams)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t\treturn\n\t\t}\n\t\tlog.Printf(\"Message successfully sent to channel %s as HTML file %s\", slackChannel, file.Name)\n\t}\n}\n\nfunc main() {\n\tif port == \"\" {\n\t\tport = \"2525\"\n\t\tlog.Printf(\"No PORT found, defaulting to %s\", port)\n\t}\n\tif slackToken == \"\" {\n\t\tlog.Fatal(\"No SLACK_TOKEN found\")\n\t\treturn\n\t}\n\tif slackChannel == \"\" {\n\t\tlog.Fatal(\"No SLACK_CHANNEL found\")\n\t\treturn\n\t}\n\tlog.Printf(\"Listening for mail on port %s\", port)\n\tsmtpd.ListenAndServe(fmt.Sprintf(\"0.0.0.0:%s\", port), mailHandler, \"Sendmail 8.11.3\", \"\")\n}\n<commit_msg>add better error handling<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/mail\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/mhale\/smtpd\"\n\t\"github.com\/nlopes\/slack\"\n\t\"github.com\/veqryn\/go-email\/email\"\n)\n\nvar (\n\tport         = os.Getenv(\"PORT\")\n\tslackToken   = os.Getenv(\"SLACK_TOKEN\")\n\tslackChannel = os.Getenv(\"SLACK_CHANNEL\")\n\tdomainList   = os.Getenv(\"DOMAIN_LIST\")\n\tfiletype     string\n)\n\nfunc mailHandler(origin net.Addr, from string, to []string, data []byte) {\n\tmsg, err := email.ParseMessage(bytes.NewReader(data))\n\tif err != nil {\n\t\tlog.Printf(\"error parsing message: %s\", err)\n\t\treturn\n\t}\n\tsubject := msg.Header.Get(\"Subject\")\n\tsender := msg.Header.Get(\"From\")\n\trecipient := msg.Header.Get(\"To\")\n\n\t\/\/ If we have been given a list of recipient domains, filter on these\n\tif len(domainList) > 0 {\n\t\tdomains := strings.Split(domainList, \",\")\n\t\trcpt, err := mail.ParseAddress(recipient)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error parsing recipient email '%s' : %s\", recipient, err)\n\t\t\treturn\n\t\t}\n\t\trecipientDomain := strings.Split(rcpt.Address, \"@\")[1]\n\t\tok := false\n\t\tfor i := 0; i < len(domains); i++ {\n\t\t\tif recipientDomain == domains[i] {\n\t\t\t\tok = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !ok {\n\t\t\tlog.Printf(\"skipping, as recipient domain '%s' is not in whitelist\", recipientDomain)\n\t\t\treturn\n\t\t}\n\t}\n\tapi := slack.New(slackToken)\n\tfor _, part := range msg.MessagesContentTypePrefix(\"text\/plain\") {\n\t\tuploadparams := slack.FileUploadParameters{\n\t\t\tChannels:       []string{slackChannel},\n\t\t\tTitle:          fmt.Sprintf(\"Subject: %s\", subject),\n\t\t\tFiletype:       \"text\",\n\t\t\tContent:        string(part.Body),\n\t\t\tInitialComment: fmt.Sprintf(\"To: %s\\nFrom: %s\", recipient, sender),\n\t\t}\n\t\tfile, err := api.UploadFile(uploadparams)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"failed to upload plaintext file: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tlog.Printf(\"Message successfully sent to channel %s as text file %s\", slackChannel, file.Name)\n\t}\n\tfor _, part := range msg.MessagesContentTypePrefix(\"text\/html\") {\n\t\tuploadparams := slack.FileUploadParameters{\n\t\t\tChannels:       []string{slackChannel},\n\t\t\tTitle:          fmt.Sprintf(\"Subject: %s\", subject),\n\t\t\tFiletype:       \"html\",\n\t\t\tContent:        string(part.Body),\n\t\t\tInitialComment: fmt.Sprintf(\"To: %s\\nFrom: %s\", recipient, sender),\n\t\t}\n\t\tfile, err := api.UploadFile(uploadparams)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"failed to upload html file: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tlog.Printf(\"Message successfully sent to channel %s as HTML file %s\", slackChannel, file.Name)\n\t}\n}\n\nfunc main() {\n\tif port == \"\" {\n\t\tport = \"2525\"\n\t\tlog.Printf(\"No PORT found, defaulting to %s\", port)\n\t}\n\tif slackToken == \"\" {\n\t\tlog.Fatal(\"No SLACK_TOKEN found\")\n\t}\n\tif slackChannel == \"\" {\n\t\tlog.Fatal(\"No SLACK_CHANNEL found\")\n\t}\n\tlog.Printf(\"Listening for mail on port %s\", port)\n\tsmtpd.ListenAndServe(fmt.Sprintf(\"0.0.0.0:%s\", port), mailHandler, \"Sendmail 8.11.3\", \"\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package admin\n\nimport (\n\t\"github.com\/qor\/qor\"\n\t\"github.com\/qor\/qor\/resource\"\n\t\"github.com\/qor\/qor\/rules\"\n\n\t\"reflect\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype resourcer interface {\n\tAllAttrs() []*resource.Meta\n}\n\nfunc ConvertMapToMetaValues(values map[string]interface{}, res resourcer) (metaValues *resource.MetaValues) {\n\tmetas := make(map[string]resource.Metaor)\n\tif res != nil {\n\t\tfor _, attr := range res.AllAttrs() {\n\t\t\tmetas[attr.Name] = attr\n\t\t}\n\t}\n\n\tmetaValues = new(resource.MetaValues)\n\tfor key, value := range values {\n\t\tmeta := metas[key]\n\t\tif str, ok := value.(string); ok {\n\t\t\tmetaValue := &resource.MetaValue{Name: key, Value: str, Meta: meta}\n\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t} else {\n\t\t\tvar res resourcer\n\t\t\tif meta != nil && meta.GetMeta() != nil && meta.GetMeta().Resource != nil {\n\t\t\t\tres, _ = meta.GetMeta().Resource.(resourcer)\n\t\t\t}\n\n\t\t\tif vs, ok := value.(map[string]interface{}); ok {\n\t\t\t\tchildren := ConvertMapToMetaValues(vs, res)\n\t\t\t\tmetaValue := &resource.MetaValue{Name: key, Meta: meta, MetaValues: children}\n\t\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t\t} else if vs, ok := value.([]interface{}); ok {\n\t\t\t\tfor _, v := range vs {\n\t\t\t\t\tif mv, ok := v.(map[string]interface{}); ok {\n\t\t\t\t\t\tchildren := ConvertMapToMetaValues(mv, res)\n\t\t\t\t\t\tmetaValue := &resource.MetaValue{Name: key, Meta: meta, MetaValues: children}\n\t\t\t\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t\t\t\t} else if meta != nil {\n\t\t\t\t\t\tmetaValue := &resource.MetaValue{Name: key, Value: vs, Meta: meta}\n\t\t\t\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tswitch reflect.ValueOf(value).Kind() {\n\t\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:\n\t\t\t\t\tmetaValue := &resource.MetaValue{Name: key, Value: str, Meta: meta}\n\t\t\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(\"doesn't support this type\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc ConvertFormToMetaValues(context *qor.Context, prefix string, res *Resource) (metaValues *resource.MetaValues) {\n\trequest := context.Request\n\tconvertedMap := make(map[string]bool)\n\tmetas := make(map[string]resource.Metaor)\n\tif res != nil {\n\t\tfor _, attr := range res.AllAttrs() {\n\t\t\tmetas[attr.Name] = attr\n\t\t}\n\t}\n\n\tmetaValues = new(resource.MetaValues)\n\tfor key := range request.Form {\n\t\tif strings.HasPrefix(key, prefix) {\n\t\t\tkey = strings.TrimPrefix(key, prefix)\n\t\t\tisCurrent := regexp.MustCompile(\"^[^.]+$\")\n\t\t\tisNext := regexp.MustCompile(`^(([^.\\[\\]]+)(\\[\\d+\\])?)(?:\\.([^.]+)+)$`)\n\n\t\t\tif matches := isCurrent.FindStringSubmatch(key); len(matches) > 0 {\n\t\t\t\tmeta := metas[matches[0]]\n\t\t\t\tmetaValue := &resource.MetaValue{Name: matches[0], Value: request.Form[prefix+key], Meta: meta}\n\t\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t\t} else if matches := isNext.FindStringSubmatch(key); len(matches) > 0 {\n\t\t\t\tif _, ok := convertedMap[matches[1]]; !ok {\n\t\t\t\t\tconvertedMap[matches[1]] = true\n\t\t\t\t\tmeta := metas[matches[2]]\n\t\t\t\t\tvar res *Resource\n\t\t\t\t\tif meta != nil && meta.GetMeta() != nil {\n\t\t\t\t\t\tres = meta.GetMeta().Resource.(*Resource)\n\t\t\t\t\t}\n\t\t\t\t\tchildren := ConvertFormToMetaValues(context, prefix+matches[1]+\".\", res)\n\t\t\t\t\tmetaValue := &resource.MetaValue{Name: matches[2], Meta: meta, MetaValues: children}\n\t\t\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif request.MultipartForm != nil {\n\t\t\/\/ for key, header := range request.MultipartForm.File {\n\t\t\/\/ xxxxx\n\t\t\/\/ }\n\t}\n\treturn\n}\n\nfunc ConvertObjectToMap(context *qor.Context, object interface{}, res *Resource) interface{} {\n\treflectValue := reflect.Indirect(reflect.ValueOf(object))\n\tswitch reflectValue.Kind() {\n\tcase reflect.Slice:\n\t\tlen := reflectValue.Len()\n\t\tvalues := []interface{}{}\n\t\tfor i := 0; i < len; i++ {\n\t\t\tvalues = append(values, ConvertObjectToMap(context, reflectValue.Index(i).Interface(), res))\n\t\t}\n\t\treturn values\n\tcase reflect.Struct:\n\t\tvalues := map[string]interface{}{}\n\t\tmetas := res.ShowMetas()\n\t\tfor _, meta := range metas {\n\t\t\tif meta.HasPermission(rules.Read, context) {\n\t\t\t\tvalue := meta.Value(object, context)\n\t\t\t\tif res, ok := meta.Resource.(*Resource); ok {\n\t\t\t\t\tvalue = ConvertObjectToMap(context, value, res)\n\t\t\t\t}\n\t\t\t\tvalues[meta.Name] = value\n\t\t\t}\n\t\t}\n\t\treturn values\n\tdefault:\n\t\tpanic(\"can't convert object to map\")\n\t}\n}\n<commit_msg>Fix ConvertMapToMetaValues for some data type<commit_after>package admin\n\nimport (\n\t\"github.com\/qor\/qor\"\n\t\"github.com\/qor\/qor\/resource\"\n\t\"github.com\/qor\/qor\/rules\"\n\n\t\"reflect\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype resourcer interface {\n\tAllAttrs() []*resource.Meta\n}\n\nfunc ConvertMapToMetaValues(values map[string]interface{}, res resourcer) (metaValues *resource.MetaValues) {\n\tmetas := make(map[string]resource.Metaor)\n\tif res != nil {\n\t\tfor _, attr := range res.AllAttrs() {\n\t\t\tmetas[attr.Name] = attr\n\t\t}\n\t}\n\n\tmetaValues = new(resource.MetaValues)\n\tfor key, value := range values {\n\t\tmeta := metas[key]\n\t\tif str, ok := value.(string); ok {\n\t\t\tmetaValue := &resource.MetaValue{Name: key, Value: str, Meta: meta}\n\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t} else {\n\t\t\tvar res resourcer\n\t\t\tif meta != nil && meta.GetMeta() != nil && meta.GetMeta().Resource != nil {\n\t\t\t\tres, _ = meta.GetMeta().Resource.(resourcer)\n\t\t\t}\n\n\t\t\tif vs, ok := value.(map[string]interface{}); ok {\n\t\t\t\tchildren := ConvertMapToMetaValues(vs, res)\n\t\t\t\tmetaValue := &resource.MetaValue{Name: key, Meta: meta, MetaValues: children}\n\t\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t\t} else if vs, ok := value.([]interface{}); ok {\n\t\t\t\tfor _, v := range vs {\n\t\t\t\t\tif mv, ok := v.(map[string]interface{}); ok {\n\t\t\t\t\t\tchildren := ConvertMapToMetaValues(mv, res)\n\t\t\t\t\t\tmetaValue := &resource.MetaValue{Name: key, Meta: meta, MetaValues: children}\n\t\t\t\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t\t\t\t} else if meta != nil {\n\t\t\t\t\t\tmetaValue := &resource.MetaValue{Name: key, Value: vs, Meta: meta}\n\t\t\t\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tswitch reflect.ValueOf(value).Kind() {\n\t\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:\n\t\t\t\t\tmetaValue := &resource.MetaValue{Name: key, Value: value, Meta: meta}\n\t\t\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(\"doesn't support this type\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc ConvertFormToMetaValues(context *qor.Context, prefix string, res *Resource) (metaValues *resource.MetaValues) {\n\trequest := context.Request\n\tconvertedMap := make(map[string]bool)\n\tmetas := make(map[string]resource.Metaor)\n\tif res != nil {\n\t\tfor _, attr := range res.AllAttrs() {\n\t\t\tmetas[attr.Name] = attr\n\t\t}\n\t}\n\n\tmetaValues = new(resource.MetaValues)\n\tfor key := range request.Form {\n\t\tif strings.HasPrefix(key, prefix) {\n\t\t\tkey = strings.TrimPrefix(key, prefix)\n\t\t\tisCurrent := regexp.MustCompile(\"^[^.]+$\")\n\t\t\tisNext := regexp.MustCompile(`^(([^.\\[\\]]+)(\\[\\d+\\])?)(?:\\.([^.]+)+)$`)\n\n\t\t\tif matches := isCurrent.FindStringSubmatch(key); len(matches) > 0 {\n\t\t\t\tmeta := metas[matches[0]]\n\t\t\t\tmetaValue := &resource.MetaValue{Name: matches[0], Value: request.Form[prefix+key], Meta: meta}\n\t\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t\t} else if matches := isNext.FindStringSubmatch(key); len(matches) > 0 {\n\t\t\t\tif _, ok := convertedMap[matches[1]]; !ok {\n\t\t\t\t\tconvertedMap[matches[1]] = true\n\t\t\t\t\tmeta := metas[matches[2]]\n\t\t\t\t\tvar res *Resource\n\t\t\t\t\tif meta != nil && meta.GetMeta() != nil {\n\t\t\t\t\t\tres = meta.GetMeta().Resource.(*Resource)\n\t\t\t\t\t}\n\t\t\t\t\tchildren := ConvertFormToMetaValues(context, prefix+matches[1]+\".\", res)\n\t\t\t\t\tmetaValue := &resource.MetaValue{Name: matches[2], Meta: meta, MetaValues: children}\n\t\t\t\t\tmetaValues.Values = append(metaValues.Values, metaValue)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif request.MultipartForm != nil {\n\t\t\/\/ for key, header := range request.MultipartForm.File {\n\t\t\/\/ xxxxx\n\t\t\/\/ }\n\t}\n\treturn\n}\n\nfunc ConvertObjectToMap(context *qor.Context, object interface{}, res *Resource) interface{} {\n\treflectValue := reflect.Indirect(reflect.ValueOf(object))\n\tswitch reflectValue.Kind() {\n\tcase reflect.Slice:\n\t\tlen := reflectValue.Len()\n\t\tvalues := []interface{}{}\n\t\tfor i := 0; i < len; i++ {\n\t\t\tvalues = append(values, ConvertObjectToMap(context, reflectValue.Index(i).Interface(), res))\n\t\t}\n\t\treturn values\n\tcase reflect.Struct:\n\t\tvalues := map[string]interface{}{}\n\t\tmetas := res.ShowMetas()\n\t\tfor _, meta := range metas {\n\t\t\tif meta.HasPermission(rules.Read, context) {\n\t\t\t\tvalue := meta.Value(object, context)\n\t\t\t\tif res, ok := meta.Resource.(*Resource); ok {\n\t\t\t\t\tvalue = ConvertObjectToMap(context, value, res)\n\t\t\t\t}\n\t\t\t\tvalues[meta.Name] = value\n\t\t\t}\n\t\t}\n\t\treturn values\n\tdefault:\n\t\tpanic(\"can't convert object to map\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"..\/interpreter\"\n\t\"..\/lua\"\n)\n\nfunc optionParse(L *lua.Lua) bool {\n\toptionK := flag.String(\"k\", \"\", \"like `cmd \/k`\")\n\toptionC := flag.String(\"c\", \"\", \"like `cmd \/c`\")\n\toptionF := flag.String(\"f\", \"\", \"run lua script\")\n\toptionE := flag.String(\"e\", \"\", \"run inline-lua-code\")\n\n\tflag.Parse()\n\n\tresult := true\n\n\tif *optionK != \"\" {\n\t\tinterpreter.New().Interpret(*optionK)\n\t}\n\tif *optionC != \"\" {\n\t\tinterpreter.New().Interpret(*optionC)\n\t\tresult = false\n\t}\n\tif *optionF != \"\" {\n\t\tL.NewTable()\n\t\tL.PushString(*optionF)\n\t\tL.RawSetI(-2, 0)\n\t\tfor i, arg1 := range flag.Args() {\n\t\t\tL.PushString(arg1)\n\t\t\tL.RawSetI(-2, lua.Integer(i))\n\t\t}\n\t\tL.SetGlobal(\"arg\")\n\t\terr := L.Source(*optionF)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t}\n\t\tresult = false\n\t}\n\tif *optionE != \"\" {\n\t\terr := L.LoadString(*optionE)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t} else {\n\t\t\tL.Call(0, 0)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t}\n\t\t}\n\t\tresult = false\n\t}\n\treturn result\n}\n<commit_msg>On -f SCRIPTFILE, lua's arg[] was shifted.<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"..\/interpreter\"\n\t\"..\/lua\"\n)\n\nfunc optionParse(L *lua.Lua) bool {\n\toptionK := flag.String(\"k\", \"\", \"like `cmd \/k`\")\n\toptionC := flag.String(\"c\", \"\", \"like `cmd \/c`\")\n\toptionF := flag.String(\"f\", \"\", \"run lua script\")\n\toptionE := flag.String(\"e\", \"\", \"run inline-lua-code\")\n\n\tflag.Parse()\n\n\tresult := true\n\n\tif *optionK != \"\" {\n\t\tinterpreter.New().Interpret(*optionK)\n\t}\n\tif *optionC != \"\" {\n\t\tinterpreter.New().Interpret(*optionC)\n\t\tresult = false\n\t}\n\tif *optionF != \"\" {\n\t\tL.NewTable()\n\t\tL.PushString(*optionF)\n\t\tL.RawSetI(-2, 0)\n\t\tfor i, arg1 := range flag.Args() {\n\t\t\tL.PushString(arg1)\n\t\t\tL.RawSetI(-2, lua.Integer(i+1))\n\t\t}\n\t\tL.SetGlobal(\"arg\")\n\t\terr := L.Source(*optionF)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t}\n\t\tresult = false\n\t}\n\tif *optionE != \"\" {\n\t\terr := L.LoadString(*optionE)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t} else {\n\t\t\tL.Call(0, 0)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t}\n\t\t}\n\t\tresult = false\n\t}\n\treturn result\n}\n<|endoftext|>"}
{"text":"<commit_before>package network\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/quilt\/quilt\/db\"\n\t\"github.com\/quilt\/quilt\/join\"\n\t\"github.com\/quilt\/quilt\/minion\/ovsdb\"\n\t\"github.com\/quilt\/quilt\/stitch\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\ntype aclKey struct {\n\tdrop  bool\n\tmatch string\n}\n\nfunc directedACLs(acl ovsdb.ACL) (res []ovsdb.ACL) {\n\tfor _, dir := range []string{\"from-lport\", \"to-lport\"} {\n\t\tres = append(res, ovsdb.ACL{\n\t\t\tCore: ovsdb.ACLCore{\n\t\t\t\tDirection: dir,\n\t\t\t\tAction:    acl.Core.Action,\n\t\t\t\tMatch:     acl.Core.Match,\n\t\t\t\tPriority:  acl.Core.Priority,\n\t\t\t},\n\t\t})\n\t}\n\treturn res\n}\n\nfunc updateACLs(ovsdbClient ovsdb.Client, connections []db.Connection,\n\thostnameToIP map[string]string) {\n\tovsdbACLs, err := ovsdbClient.ListACLs()\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Failed to list ACLs\")\n\t\treturn\n\t}\n\n\texpACLs := directedACLs(ovsdb.ACL{\n\t\tCore: ovsdb.ACLCore{\n\t\t\tAction:   \"drop\",\n\t\t\tMatch:    \"ip\",\n\t\t\tPriority: 0,\n\t\t},\n\t})\n\n\tfor _, conn := range connections {\n\t\tif conn.From == stitch.PublicInternetLabel ||\n\t\t\tconn.To == stitch.PublicInternetLabel {\n\t\t\tcontinue\n\t\t}\n\n\t\tsrc := hostnameToIP[conn.From]\n\t\tdst := hostnameToIP[conn.To]\n\t\tif src == \"\" || dst == \"\" {\n\t\t\tlog.WithField(\"connection\", conn).Warn(\"Unknown hostname \" +\n\t\t\t\t\"in ACL. Ignoring\")\n\t\t\tcontinue\n\t\t}\n\n\t\tmatchStr := getMatchString(src, dst, conn.MinPort, conn.MaxPort)\n\t\texpACLs = append(expACLs, directedACLs(\n\t\t\tovsdb.ACL{\n\t\t\t\tCore: ovsdb.ACLCore{\n\t\t\t\t\tAction:   \"allow\",\n\t\t\t\t\tMatch:    matchStr,\n\t\t\t\t\tPriority: 1,\n\t\t\t\t},\n\t\t\t})...)\n\t}\n\n\tovsdbKey := func(ovsdbIntf interface{}) interface{} {\n\t\treturn ovsdbIntf.(ovsdb.ACL).Core\n\t}\n\t_, toCreate, toDelete := join.HashJoin(ovsdbACLSlice(expACLs),\n\t\tovsdbACLSlice(ovsdbACLs), ovsdbKey, ovsdbKey)\n\n\tfor _, acl := range toDelete {\n\t\tif err := ovsdbClient.DeleteACL(lSwitch, acl.(ovsdb.ACL)); err != nil {\n\t\t\tlog.WithError(err).Warn(\"Error deleting ACL\")\n\t\t}\n\t}\n\n\tfor _, intf := range toCreate {\n\t\tacl := intf.(ovsdb.ACL).Core\n\t\tif err := ovsdbClient.CreateACL(lSwitch, acl.Direction,\n\t\t\tacl.Priority, acl.Match, acl.Action); err != nil {\n\t\t\tlog.WithError(err).Warn(\"Error adding ACL\")\n\t\t}\n\t}\n}\n\nfunc getMatchString(srcIP, dstIP string, minPort, maxPort int) string {\n\treturn or(\n\t\tand(\n\t\t\tand(from(srcIP), to(dstIP)),\n\t\t\tportConstraint(minPort, maxPort, \"dst\")),\n\t\tand(\n\t\t\tand(from(dstIP), to(srcIP)),\n\t\t\tportConstraint(minPort, maxPort, \"src\")))\n}\n\nfunc portConstraint(minPort, maxPort int, direction string) string {\n\treturn fmt.Sprintf(\"(icmp || %[1]d <= udp.%[2]s <= %[3]d || \"+\n\t\t\"%[1]d <= tcp.%[2]s <= %[3]d)\", minPort, direction, maxPort)\n}\n\nfunc from(ip string) string {\n\treturn fmt.Sprintf(\"ip4.src == %s\", ip)\n}\n\nfunc to(ip string) string {\n\treturn fmt.Sprintf(\"ip4.dst == %s\", ip)\n}\n\nfunc or(predicates ...string) string {\n\treturn \"(\" + strings.Join(predicates, \" || \") + \")\"\n}\n\nfunc and(predicates ...string) string {\n\treturn \"(\" + strings.Join(predicates, \" && \") + \")\"\n}\n\n\/\/ ovsdbACLSlice is a wrapper around []ovsdb.ACL to allow us to perform a join\ntype ovsdbACLSlice []ovsdb.ACL\n\n\/\/ Len returns the length of the slice\nfunc (slc ovsdbACLSlice) Len() int {\n\treturn len(slc)\n}\n\n\/\/ Get returns the element at index i of the slice\nfunc (slc ovsdbACLSlice) Get(i int) interface{} {\n\treturn slc[i]\n}\n<commit_msg>network: Log unknown hostname error at Debug<commit_after>package network\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/quilt\/quilt\/db\"\n\t\"github.com\/quilt\/quilt\/join\"\n\t\"github.com\/quilt\/quilt\/minion\/ovsdb\"\n\t\"github.com\/quilt\/quilt\/stitch\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\ntype aclKey struct {\n\tdrop  bool\n\tmatch string\n}\n\nfunc directedACLs(acl ovsdb.ACL) (res []ovsdb.ACL) {\n\tfor _, dir := range []string{\"from-lport\", \"to-lport\"} {\n\t\tres = append(res, ovsdb.ACL{\n\t\t\tCore: ovsdb.ACLCore{\n\t\t\t\tDirection: dir,\n\t\t\t\tAction:    acl.Core.Action,\n\t\t\t\tMatch:     acl.Core.Match,\n\t\t\t\tPriority:  acl.Core.Priority,\n\t\t\t},\n\t\t})\n\t}\n\treturn res\n}\n\nfunc updateACLs(ovsdbClient ovsdb.Client, connections []db.Connection,\n\thostnameToIP map[string]string) {\n\tovsdbACLs, err := ovsdbClient.ListACLs()\n\tif err != nil {\n\t\tlog.WithError(err).Error(\"Failed to list ACLs\")\n\t\treturn\n\t}\n\n\texpACLs := directedACLs(ovsdb.ACL{\n\t\tCore: ovsdb.ACLCore{\n\t\t\tAction:   \"drop\",\n\t\t\tMatch:    \"ip\",\n\t\t\tPriority: 0,\n\t\t},\n\t})\n\n\tfor _, conn := range connections {\n\t\tif conn.From == stitch.PublicInternetLabel ||\n\t\t\tconn.To == stitch.PublicInternetLabel {\n\t\t\tcontinue\n\t\t}\n\n\t\tsrc := hostnameToIP[conn.From]\n\t\tdst := hostnameToIP[conn.To]\n\t\tif src == \"\" || dst == \"\" {\n\t\t\tlog.WithField(\"connection\", conn).Debug(\"Unknown hostname \" +\n\t\t\t\t\"in ACL. Ignoring\")\n\t\t\tcontinue\n\t\t}\n\n\t\tmatchStr := getMatchString(src, dst, conn.MinPort, conn.MaxPort)\n\t\texpACLs = append(expACLs, directedACLs(\n\t\t\tovsdb.ACL{\n\t\t\t\tCore: ovsdb.ACLCore{\n\t\t\t\t\tAction:   \"allow\",\n\t\t\t\t\tMatch:    matchStr,\n\t\t\t\t\tPriority: 1,\n\t\t\t\t},\n\t\t\t})...)\n\t}\n\n\tovsdbKey := func(ovsdbIntf interface{}) interface{} {\n\t\treturn ovsdbIntf.(ovsdb.ACL).Core\n\t}\n\t_, toCreate, toDelete := join.HashJoin(ovsdbACLSlice(expACLs),\n\t\tovsdbACLSlice(ovsdbACLs), ovsdbKey, ovsdbKey)\n\n\tfor _, acl := range toDelete {\n\t\tif err := ovsdbClient.DeleteACL(lSwitch, acl.(ovsdb.ACL)); err != nil {\n\t\t\tlog.WithError(err).Warn(\"Error deleting ACL\")\n\t\t}\n\t}\n\n\tfor _, intf := range toCreate {\n\t\tacl := intf.(ovsdb.ACL).Core\n\t\tif err := ovsdbClient.CreateACL(lSwitch, acl.Direction,\n\t\t\tacl.Priority, acl.Match, acl.Action); err != nil {\n\t\t\tlog.WithError(err).Warn(\"Error adding ACL\")\n\t\t}\n\t}\n}\n\nfunc getMatchString(srcIP, dstIP string, minPort, maxPort int) string {\n\treturn or(\n\t\tand(\n\t\t\tand(from(srcIP), to(dstIP)),\n\t\t\tportConstraint(minPort, maxPort, \"dst\")),\n\t\tand(\n\t\t\tand(from(dstIP), to(srcIP)),\n\t\t\tportConstraint(minPort, maxPort, \"src\")))\n}\n\nfunc portConstraint(minPort, maxPort int, direction string) string {\n\treturn fmt.Sprintf(\"(icmp || %[1]d <= udp.%[2]s <= %[3]d || \"+\n\t\t\"%[1]d <= tcp.%[2]s <= %[3]d)\", minPort, direction, maxPort)\n}\n\nfunc from(ip string) string {\n\treturn fmt.Sprintf(\"ip4.src == %s\", ip)\n}\n\nfunc to(ip string) string {\n\treturn fmt.Sprintf(\"ip4.dst == %s\", ip)\n}\n\nfunc or(predicates ...string) string {\n\treturn \"(\" + strings.Join(predicates, \" || \") + \")\"\n}\n\nfunc and(predicates ...string) string {\n\treturn \"(\" + strings.Join(predicates, \" && \") + \")\"\n}\n\n\/\/ ovsdbACLSlice is a wrapper around []ovsdb.ACL to allow us to perform a join\ntype ovsdbACLSlice []ovsdb.ACL\n\n\/\/ Len returns the length of the slice\nfunc (slc ovsdbACLSlice) Len() int {\n\treturn len(slc)\n}\n\n\/\/ Get returns the element at index i of the slice\nfunc (slc ovsdbACLSlice) Get(i int) interface{} {\n\treturn slc[i]\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Fixed the multi-line tags and locations meta data pattern (again). The previous version did not stop and recognized locations as tags if the locations preceed the tags.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>fixed unit tests<commit_after><|endoftext|>"}
{"text":"<commit_before>package isumm\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"sort\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\tnow       = time.Now()\n\tnextMonth = now.Add(32 * 24 * time.Hour)\n\tincMin    = now.Add(10 * time.Minute)\n\topType    = \"1\"\n\tvalue     = \"12\"\n\tdate      = \"2006-01-02\"\n)\n\nfunc TestSort(t *testing.T) {\n\to := Operations{NewOperation(Balance, 1, now), NewOperation(Balance, 1, incMin)}\n\tsort.Sort(o)\n\tif o[0].Date().Before(o[1].Date()) {\n\t\tt.Errorf(\"want %s before than %s\", o[0], o[1])\n\t}\n}\n\nfunc TestNewOperationFromString(t *testing.T) {\n\tvalidOp, _ := NewOperationFromString(opType, value, date)\n\ttestCases := []struct {\n\t\tdesc, t, v, d string\n\t\twant          *Operation\n\t}{\n\t\t\/\/ Invalid cases.\n\t\t{desc: \"invalid value - empty\", t: opType, v: \"\", d: date},\n\t\t{desc: \"invalid value - chars\", t: opType, v: \"acb\", d: date},\n\t\t{desc: \"invalid op - empty string\", t: \"\", v: value, d: date},\n\t\t{desc: \"invalid op - type does not exist\", t: \"94879138ddffg\", v: value, d: date},\n\t\t{desc: \"invalid date\", t: opType, v: value, d: \"31\/31\/31\"},\n\t\t\/\/ Valid cases.\n\t\t{desc: \"valid - contain spaces\", t: opType, v: fmt.Sprintf(\" %s \", value), d: date, want: &validOp},\n\t\t{desc: \"valid - perfect\", t: opType, v: value, d: date, want: &validOp},\n\t}\n\tfor _, test := range testCases {\n\t\tgot, err := NewOperationFromString(test.t, test.v, test.d)\n\t\tswitch {\n\t\tcase test.want == nil:\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"got:nil expected:err. Test:(%+v)\", test)\n\t\t\t}\n\t\tdefault:\n\t\t\tif !reflect.DeepEqual(test.want, &got) {\n\t\t\t\tt.Errorf(\"got:(%+v) want:(%+v). Test:(%+v)\", got, test.want, test)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestSummarize(t *testing.T) {\n\tdata := []struct {\n\t\tops  Operations\n\t\tsumm Summaries\n\t}{\n\t\t{ \/\/ Simple case: One entry containing only balance.\n\t\t\tops:  Operations{NewOperation(Balance, 1.2, now)},\n\t\t\tsumm: Summaries{{Date: monthYear(now), Balance: 1.2, Change: 0}},\n\t\t},\n\t\t{ \/\/ Empty case.\n\t\t\tops:  Operations{},\n\t\t\tsumm: Summaries{},\n\t\t},\n\t\t{\n\t\t\tops: Operations{\n\t\t\t\tNewOperation(Balance, 1.2, incMin),\n\t\t\t\tNewOperation(Deposit, 1.0, now),\n\t\t\t\tNewOperation(Balance, 2.2, nextMonth),\n\t\t\t},\n\t\t\tsumm: Summaries{\n\t\t\t\t{Date: monthYear(nextMonth), Balance: 2.2, Change: 0},\n\t\t\t\t{Date: monthYear(now), Balance: 1.2, Change: 1.0},\n\t\t\t},\n\t\t},\n\t\t{ \/\/ Middle of the month, no balance.\n\t\t\tops:  Operations{NewOperation(Deposit, 1.0, now)},\n\t\t\tsumm: Summaries{{Date: monthYear(now), Balance: 0, Change: 1.0}},\n\t\t},\n\t\t{ \/\/ Two balances --> Use the most recent.\n\t\t\tops: Operations{\n\t\t\t\tNewOperation(Balance, 1.2, incMin),\n\t\t\t\tNewOperation(Balance, 2.2, now),\n\t\t\t},\n\t\t\tsumm: Summaries{{Date: monthYear(now), Balance: 1.2, Change: 0}},\n\t\t},\n\t}\n\tfor _, d := range data {\n\t\tgot := d.ops.Summarize()\n\t\tif (len(got) != 0 && len(d.summ) != 0) && !reflect.DeepEqual(got, d.summ) {\n\t\t\tt.Errorf(\"got:%+v want:%+v\", got, d.summ)\n\t\t}\n\t}\n}\n<commit_msg>Fixing tests.<commit_after>package isumm\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"sort\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\tnow       = time.Now()\n\tnextMonth = now.Add(32 * 24 * time.Hour)\n\tincMin    = now.Add(10 * time.Minute)\n\topType    = \"1\"\n\tvalue     = \"12\"\n\tdate      = \"2006-01-02\"\n)\n\nfunc TestSort(t *testing.T) {\n\to := Operations{NewOperation(Balance, 1, now), NewOperation(Balance, 1, incMin)}\n\tsort.Sort(o)\n\tif o[0].Date().Before(o[1].Date()) {\n\t\tt.Errorf(\"want %s before than %s\", o[0], o[1])\n\t}\n}\n\nfunc TestNewOperationFromString(t *testing.T) {\n\tvalidOp, _ := NewOperationFromString(opType, value, date)\n\ttestCases := []struct {\n\t\tdesc, t, v, d string\n\t\twant          *Operation\n\t}{\n\t\t\/\/ Invalid cases.\n\t\t{desc: \"invalid value - empty\", t: opType, v: \"\", d: date},\n\t\t{desc: \"invalid value - chars\", t: opType, v: \"acb\", d: date},\n\t\t{desc: \"invalid op - empty string\", t: \"\", v: value, d: date},\n\t\t{desc: \"invalid op - type does not exist\", t: \"94879138ddffg\", v: value, d: date},\n\t\t{desc: \"invalid date\", t: opType, v: value, d: \"31\/31\/31\"},\n\t\t\/\/ Valid cases.\n\t\t{desc: \"valid - contain spaces\", t: opType, v: fmt.Sprintf(\" %s \", value), d: date, want: &validOp},\n\t\t{desc: \"valid - perfect\", t: opType, v: value, d: date, want: &validOp},\n\t}\n\tfor _, test := range testCases {\n\t\tgot, err := NewOperationFromString(test.t, test.v, test.d)\n\t\tswitch {\n\t\tcase test.want == nil:\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"got:nil expected:err. Test:(%+v)\", test)\n\t\t\t}\n\t\tdefault:\n\t\t\tif !reflect.DeepEqual(test.want, &got) {\n\t\t\t\tt.Errorf(\"got:(%+v) want:(%+v). Test:(%+v)\", got, test.want, test)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestSummarize(t *testing.T) {\n\tdata := []struct {\n\t\tops  Operations\n\t\tsumm Summaries\n\t}{\n\t\t{ \/\/ Simple case: One entry containing only balance.\n\t\t\tops:  Operations{NewOperation(Balance, 1.2, now)},\n\t\t\tsumm: Summaries{\n\t\t\t\t{\n\t\t\t\t\tDate: monthYear(now),\n\t\t\t\t\tBalance: 1.2,\n\t\t\t\t\tChange: 0,\n\t\t\t\t\tSummaryOps: []SummaryOp{\n\t\t\t\t\t\t{Index: 0, Operation: NewOperation(Balance, 1.2, now)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{ \/\/ Empty case.\n\t\t\tops:  Operations{},\n\t\t\tsumm: Summaries{},\n\t\t},\n\t\t{\n\t\t\tops: Operations{\n\t\t\t\tNewOperation(Balance, 1.2, incMin),\n\t\t\t\tNewOperation(Deposit, 1.0, now),\n\t\t\t\tNewOperation(Balance, 2.2, nextMonth),\n\t\t\t},\n\t\t\tsumm: Summaries{\n\t\t\t\t{\n\t\t\t\t\tDate: monthYear(nextMonth),\n\t\t\t\t\tBalance: 2.2,\n\t\t\t\t\tChange: 0,\n\t\t\t\t\tSummaryOps: []SummaryOp{\n\t\t\t\t\t\t{Index: 0, Operation: NewOperation(Balance, 2.2, nextMonth)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tDate: monthYear(now),\n\t\t\t\t\tBalance: 1.2,\n\t\t\t\t\tChange: 1.0,\n\t\t\t\t\tSummaryOps: []SummaryOp{\n\t\t\t\t\t\t{Index: 1, Operation: NewOperation(Balance, 1.2, incMin)},\n\t\t\t\t\t\t{Index: 2, Operation: NewOperation(Deposit, 1.0, now)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{ \/\/ Middle of the month, no balance.\n\t\t\tops:  Operations{NewOperation(Deposit, 1.0, now)},\n\t\t\tsumm: Summaries{\n\t\t\t\t{\n\t\t\t\t\tDate: monthYear(now),\n\t\t\t\t\tBalance: 0,\n\t\t\t\t\tChange: 1.0,\n\t\t\t\t\tSummaryOps: []SummaryOp{\n\t\t\t\t\t\t{Index: 0, Operation: NewOperation(Deposit, 1.0, now)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{ \/\/ Two balances --> Use the most recent.\n\t\t\tops: Operations{\n\t\t\t\tNewOperation(Balance, 1.2, incMin),\n\t\t\t\tNewOperation(Balance, 2.2, now),\n\t\t\t},\n\t\t\tsumm: Summaries{\n\t\t\t\t{\n\t\t\t\t\tDate: monthYear(now),\n\t\t\t\t\tBalance: 1.2,\n\t\t\t\t\tChange: 0,\n\t\t\t\t\tSummaryOps: []SummaryOp{\n\t\t\t\t\t\t{Index: 0, Operation: NewOperation(Balance, 1.2, incMin)},\n\t\t\t\t\t\t{Index: 1, Operation: NewOperation(Balance, 2.2, now)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, d := range data {\n\t\tgot := d.ops.Summarize()\n\t\tif (len(got) != 0 && len(d.summ) != 0) && !reflect.DeepEqual(got, d.summ) {\n\t\t\tt.Errorf(\"got:%+v want:%+v\", got, d.summ)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>protocol\/bc: make this benchmark test a little more focused<commit_after><|endoftext|>"}
{"text":"<commit_before>package sync\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\tdm \"github.com\/svdberg\/syncmysport-runkeeper\/datamodel\"\n\trk \"github.com\/svdberg\/syncmysport-runkeeper\/runkeeper\"\n\tstv \"github.com\/svdberg\/syncmysport-runkeeper\/strava\"\n)\n\ntype Syncer interface {\n\tSync() (int, int, error)\n}\n\n\/*\n * Returns the set of activities that are in RunKeeper, but not in Strava.\n * So if the set of Runkeeper activites is A, and the set of Strava activities is B,\n * this function calculates B\\A.\n *\/\nfunc CalculateRKDifference(rkActivities dm.ActivitySet, stvActivities dm.ActivitySet) *dm.ActivitySet {\n\treturn rkActivities.ApproxSubtract(stvActivities)\n}\n\ntype SyncTask struct {\n\tStravaToken       string `json:\"stv_token\"`\n\tRunkeeperToken    string `json:\"rk_token\"`\n\tLastSeenTimestamp int    `json:\"last_seen_ts\"`\n\tUid               int64  `json:\"id\"`\n\tEnvironment       string `json:\"environment\"`\n}\n\nfunc CreateSyncTask(rkToken string, stvToken string, lastSeenTS int, environment string) *SyncTask {\n\treturn &SyncTask{stvToken, rkToken, lastSeenTS, -1, environment}\n}\n\n\/*\n * return the Total difference and the number of Activites created\n *\/\nfunc (st SyncTask) Sync(stvClient stv.StravaClientInt, rkClient rk.RunkeeperCientInt) (int, int, error) {\n\t\/\/get activities from strava\n\t\/\/normalize time to the start of the day, because Runkeeper only supports days as offset, not timestamps\n\ttsOfStartOfDay := calculateTsAtStartOfDay(st.LastSeenTimestamp)\n\tactivities, err := stvClient.GetSTVActivitiesSince(tsOfStartOfDay)\n\tif err != nil {\n\t\tlog.Print(\"Error retrieving Strava activitites since %s, aborting this run\", st.LastSeenTimestamp)\n\t\treturn 0, 0, err\n\t}\n\tstvDetailedActivities := dm.NewActivitySet()\n\tfor _, actSummary := range activities {\n\t\t\/\/get Detailed Actv\n\t\tdetailedAct, _ := stvClient.GetSTVDetailedActivity(actSummary.Id)\n\t\t\/\/get associated Streams\n\t\ttimeStream, err := stvClient.GetSTVActivityStream(actSummary.Id, \"Time\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error while retrieving time series from Strava: %s\", err)\n\t\t}\n\t\tlocStream, _ := stvClient.GetSTVActivityStream(actSummary.Id, \"GPS\")\n\t\thrStream, _ := stvClient.GetSTVActivityStream(actSummary.Id, \"Heartrate\")\n\n\t\tstvDetailedActivities.Add(*stv.ConvertToActivity(detailedAct, timeStream, locStream, hrStream))\n\t}\n\tlog.Printf(\"Got %d items from Strava\", stvDetailedActivities.NumElements())\n\tfor i := 0; i < stvDetailedActivities.NumElements(); i++ {\n\t\tlog.Printf(\"Strava Activity: %s\", stvDetailedActivities.Get(i))\n\t}\n\n\t\/\/get activities from runkeeper\n\trkActivitiesOverview, err := rkClient.GetRKActivitiesSince(st.LastSeenTimestamp)\n\trkDetailActivities := rkClient.EnrichRKActivities(rkActivitiesOverview)\n\t\/\/log.Printf(\"rk detail activities: %s\", rkDetailActivities)\n\n\trkActivities := dm.NewActivitySet()\n\tfor _, item := range rkDetailActivities {\n\t\trkActivities.Add(*rk.ConvertToActivity(&item))\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Got %d items from RunKeeper\", rkActivities.NumElements())\n\tfor i := 0; i < rkActivities.NumElements(); i++ {\n\t\tlog.Printf(\"Runkeeper Activity: %s\", rkActivities.Get(i))\n\t}\n\n\t\/\/caclulate difference\n\titemsToSyncToRk := stvDetailedActivities.ApproxSubtract(rkActivities)\n\tlog.Printf(\"Difference between Runkeeper and Strava is %d items\", itemsToSyncToRk.NumElements())\n\n\t\/\/write to runkeeper\n\ttotalItemsCreated := 0\n\tfor i := 0; i < itemsToSyncToRk.NumElements(); i++ {\n\t\tlog.Printf(\"Now storing item %s to RunKeeper\", itemsToSyncToRk.Get(i))\n\t\tvar (\n\t\t\turi string\n\t\t\terr error\n\t\t)\n\t\tif st.Environment == \"Prod\" {\n\t\t\turi, err = rkClient.PostActivity(rk.ConvertToRkActivity(itemsToSyncToRk.Get(i)))\n\t\t} else {\n\t\t\tlog.Print(\"Assuming DEBUG\/TEST mode, not actually writing to Runkeeper\")\n\t\t\terr = nil\n\t\t\turi = \"fake_uri\"\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Something failed during the write to Runkeeper: %s\", err)\n\t\t}\n\t\tif uri != \"\" {\n\t\t\tlog.Printf(\"URI of activity: %s\", uri)\n\t\t\ttotalItemsCreated++\n\t\t}\n\t}\n\treturn itemsToSyncToRk.NumElements(), totalItemsCreated, nil\n}\n\nfunc calculateTsAtStartOfDay(timestamp int) int {\n\ttimeAtTimestamp := time.Unix(int64(timestamp), 0).UTC()\n\tyear, month, day := timeAtTimestamp.Date()\n\t\/\/\tMon Jan 2 15:04:05 -0700 MST 2006\n\tts, err := time.Parse(\"2006-1-2 15:04:05 MST\", fmt.Sprintf(\"%d-%d-%d 00:00:00 UTC\", year, month, day))\n\tif err != nil {\n\t\tlog.Printf(\"Error parsing time from y\/m\/d to ts of current day: %s\", err)\n\t}\n\tts = ts.Add(time.Duration(1) * time.Minute)\n\treturn int(ts.Unix())\n}\n<commit_msg>Some further fixes to the error handling in the jobs<commit_after>package sync\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\tdm \"github.com\/svdberg\/syncmysport-runkeeper\/datamodel\"\n\trk \"github.com\/svdberg\/syncmysport-runkeeper\/runkeeper\"\n\tstv \"github.com\/svdberg\/syncmysport-runkeeper\/strava\"\n)\n\ntype Syncer interface {\n\tSync() (int, int, error)\n}\n\n\/*\n * Returns the set of activities that are in RunKeeper, but not in Strava.\n * So if the set of Runkeeper activites is A, and the set of Strava activities is B,\n * this function calculates B\\A.\n *\/\nfunc CalculateRKDifference(rkActivities dm.ActivitySet, stvActivities dm.ActivitySet) *dm.ActivitySet {\n\treturn rkActivities.ApproxSubtract(stvActivities)\n}\n\ntype SyncTask struct {\n\tStravaToken       string `json:\"stv_token\"`\n\tRunkeeperToken    string `json:\"rk_token\"`\n\tLastSeenTimestamp int    `json:\"last_seen_ts\"`\n\tUid               int64  `json:\"id\"`\n\tEnvironment       string `json:\"environment\"`\n}\n\nfunc CreateSyncTask(rkToken string, stvToken string, lastSeenTS int, environment string) *SyncTask {\n\treturn &SyncTask{stvToken, rkToken, lastSeenTS, -1, environment}\n}\n\n\/*\n * return the Total difference and the number of Activites created\n *\/\nfunc (st SyncTask) Sync(stvClient stv.StravaClientInt, rkClient rk.RunkeeperCientInt) (int, int, error) {\n\t\/\/get activities from strava\n\t\/\/normalize time to the start of the day, because Runkeeper only supports days as offset, not timestamps\n\ttsOfStartOfDay := calculateTsAtStartOfDay(st.LastSeenTimestamp)\n\tactivities, err := stvClient.GetSTVActivitiesSince(tsOfStartOfDay)\n\tif err != nil {\n\t\tlog.Print(\"Error retrieving Strava activitites since %s, aborting this run\", st.LastSeenTimestamp)\n\t\treturn 0, 0, err\n\t}\n\tstvDetailedActivities := dm.NewActivitySet()\n\tfor _, actSummary := range activities {\n\t\t\/\/get Detailed Actv\n\t\tdetailedAct, _ := stvClient.GetSTVDetailedActivity(actSummary.Id)\n\t\t\/\/get associated Streams\n\t\ttimeStream, err := stvClient.GetSTVActivityStream(actSummary.Id, \"Time\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error while retrieving time series from Strava: %s\", err)\n\t\t\treturn 0, 0, err\n\t\t}\n\t\tlocStream, _ := stvClient.GetSTVActivityStream(actSummary.Id, \"GPS\")\n\t\thrStream, _ := stvClient.GetSTVActivityStream(actSummary.Id, \"Heartrate\")\n\n\t\tstvDetailedActivities.Add(*stv.ConvertToActivity(detailedAct, timeStream, locStream, hrStream))\n\t}\n\tlog.Printf(\"Got %d items from Strava\", stvDetailedActivities.NumElements())\n\tfor i := 0; i < stvDetailedActivities.NumElements(); i++ {\n\t\tlog.Printf(\"Strava Activity: %s\", stvDetailedActivities.Get(i))\n\t}\n\n\t\/\/get activities from runkeeper\n\trkActivitiesOverview, err := rkClient.GetRKActivitiesSince(st.LastSeenTimestamp)\n\trkDetailActivities := rkClient.EnrichRKActivities(rkActivitiesOverview)\n\t\/\/log.Printf(\"rk detail activities: %s\", rkDetailActivities)\n\n\trkActivities := dm.NewActivitySet()\n\tfor _, item := range rkDetailActivities {\n\t\trkActivities.Add(*rk.ConvertToActivity(&item))\n\t}\n\tif err != nil {\n\t\tlog.Printf(\"%s\", err)\n\t}\n\tlog.Printf(\"Got %d items from RunKeeper\", rkActivities.NumElements())\n\tfor i := 0; i < rkActivities.NumElements(); i++ {\n\t\tlog.Printf(\"Runkeeper Activity: %s\", rkActivities.Get(i))\n\t}\n\n\t\/\/caclulate difference\n\titemsToSyncToRk := stvDetailedActivities.ApproxSubtract(rkActivities)\n\tlog.Printf(\"Difference between Runkeeper and Strava is %d items\", itemsToSyncToRk.NumElements())\n\n\t\/\/write to runkeeper\n\ttotalItemsCreated := 0\n\tfor i := 0; i < itemsToSyncToRk.NumElements(); i++ {\n\t\tlog.Printf(\"Now storing item %s to RunKeeper\", itemsToSyncToRk.Get(i))\n\t\tvar (\n\t\t\turi string\n\t\t\terr error\n\t\t)\n\t\tif st.Environment == \"Prod\" {\n\t\t\turi, err = rkClient.PostActivity(rk.ConvertToRkActivity(itemsToSyncToRk.Get(i)))\n\t\t} else {\n\t\t\tlog.Print(\"Assuming DEBUG\/TEST mode, not actually writing to Runkeeper\")\n\t\t\terr = nil\n\t\t\turi = \"fake_uri\"\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Something failed during the write to Runkeeper: %s\", err)\n\t\t\treturn itemsToSyncToRk.NumElements(), totalItemsCreated, err\n\t\t}\n\t\tif uri != \"\" {\n\t\t\tlog.Printf(\"URI of activity: %s\", uri)\n\t\t\ttotalItemsCreated++\n\t\t}\n\t}\n\treturn itemsToSyncToRk.NumElements(), totalItemsCreated, nil\n}\n\nfunc calculateTsAtStartOfDay(timestamp int) int {\n\ttimeAtTimestamp := time.Unix(int64(timestamp), 0).UTC()\n\tyear, month, day := timeAtTimestamp.Date()\n\t\/\/\tMon Jan 2 15:04:05 -0700 MST 2006\n\tts, err := time.Parse(\"2006-1-2 15:04:05 MST\", fmt.Sprintf(\"%d-%d-%d 00:00:00 UTC\", year, month, day))\n\tif err != nil {\n\t\tlog.Printf(\"Error parsing time from y\/m\/d to ts of current day: %s\", err)\n\t}\n\tts = ts.Add(time.Duration(1) * time.Minute)\n\treturn int(ts.Unix())\n}\n<|endoftext|>"}
{"text":"<commit_before>package termite\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n)\n\n\/\/ A in-memory cache of attributes.\n\/\/\n\/\/ Invariants: for all entries, we have their parent directories too\ntype AttributeCache struct {\n\tmutex      sync.RWMutex\n\tattributes map[string]*FileAttr\n\tcond       *sync.Cond\n\tbusy       map[string]bool\n\tgetter     func(name string) *FileAttr\n\tstatter    func(name string) *os.FileInfo\n}\n\nfunc NewAttributeCache(getter func(n string) *FileAttr,\n\tstatter func(n string) *os.FileInfo) *AttributeCache {\n\tme := &AttributeCache{\n\t\tattributes: make(map[string]*FileAttr),\n\t\tbusy:       map[string]bool{},\n\t}\n\tme.cond = sync.NewCond(&me.mutex)\n\tme.getter = getter\n\tme.statter = statter\n\treturn me\n}\n\nvar paranoia = false\n\nfunc (me *AttributeCache) Verify() {\n\tif !paranoia {\n\t\treturn\n\t}\n\tme.mutex.RLock()\n\tdefer me.mutex.RUnlock()\n\tme.verify()\n}\n\nfunc (me *AttributeCache) verify() {\n\tif !paranoia {\n\t\treturn\n\t}\n\tfor k, v := range me.attributes {\n\t\tif k != \"\" && filepath.Clean(k) != k {\n\t\t\tlog.Panicf(\"Unclean path %q\", k)\n\t\t}\n\t\tif v.Path != k {\n\t\t\tlog.Panicf(\"attributes mismatch %q %#v\", k, v)\n\t\t}\n\t\tif _, ok := me.busy[k]; ok {\n\t\t\tlog.Panicf(\"busy and attributes entry for %q\", k)\n\t\t}\n\t\tif v.Deletion() {\n\t\t\tlog.Panicf(\"Attribute cache may not contain deletions %q\", k)\n\t\t}\n\t\tif v.IsDirectory() && v.NameModeMap == nil {\n\t\t\tlog.Panicf(\"dir has no NameModeMap %q\", k)\n\t\t}\n\t\tfor childName, mode := range v.NameModeMap {\n\t\t\tif strings.Contains(childName, \"\\000\") || strings.Contains(childName, \"\/\") || len(childName) == 0 {\n\t\t\t\tlog.Panicf(\"%q has illegal child name %q: %o\", k, childName, mode)  \n\t\t\t}\n\t\t\tif mode == 0 {\n\t\t\t\tlog.Panicf(\"child has 0 mode: %q.%q\", k, childName)\n\t\t\t}\n\t\t}\n\t\tdir, base := SplitPath(k)\n\t\tif base != k {\n\t\t\tparent := me.attributes[dir]\n\t\t\tif v.Deletion() && parent != nil && parent.NameModeMap[base] != 0 {\n\t\t\t\tlog.Panicf(\"Parent %q has entry for deleted %q\", dir, base)\n\t\t\t}\n\t\t\tif !v.Deletion() && parent == nil {\n\t\t\t\tlog.Panicf(\"Missing parent for %q\", k)\n\t\t\t}\n\t\t\tif !v.Deletion() && parent.NameModeMap[base] == 0 {\n\t\t\t\tlog.Panicf(\"Parent %q has no entry for %q\", dir, base)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (me *AttributeCache) Have(name string) bool {\n\tme.mutex.RLock()\n\tdefer me.mutex.RUnlock()\n\t_, ok := me.attributes[name]\n\treturn ok\n}\n\nfunc (me *AttributeCache) Get(name string) (rep *FileAttr) {\n\treturn me.get(name, false)\n}\n\nfunc (me *AttributeCache) GetDir(name string) (rep *FileAttr) {\n\treturn me.get(name, true)\n}\n\nfunc (me *AttributeCache) localGet(name string, withdir bool) (rep *FileAttr) {\n\tme.mutex.RLock()\n\tdefer me.mutex.RUnlock()\n\n\trep, ok := me.attributes[name]\n\tif ok {\n\t\treturn rep.Copy(withdir)\n\t}\n\n\tif name != \"\" {\n\t\tdir, base := SplitPath(name)\n\t\tdirAttr := me.attributes[dir]\n\t\tif dirAttr != nil && dirAttr.NameModeMap != nil && dirAttr.NameModeMap[base] == 0 {\n\t\t\treturn &FileAttr{Path: name}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (me *AttributeCache) get(name string, withdir bool) (rep *FileAttr) {\n\trep = me.localGet(name, withdir)\n\tif rep != nil {\n\t\treturn rep\n\t}\n\n\tif name != \"\" {\n\t\tdir, base := SplitPath(name)\n\t\tdirAttr := me.get(dir, true)\n\t\tif dirAttr.NameModeMap != nil && dirAttr.NameModeMap[base] == 0 {\n\t\t\treturn &FileAttr{Path: name}\n\t\t}\n\t}\n\n\tdefer me.Verify()\n\tme.mutex.Lock()\n\tdefer me.mutex.Unlock()\n\tfor me.busy[name] && me.attributes[name] == nil {\n\t\tme.cond.Wait()\n\t}\n\trep, ok := me.attributes[name]\n\tif ok {\n\t\treturn rep\n\t}\n\tme.busy[name] = true\n\tme.mutex.Unlock()\n\n\trep = me.getter(name)\n\n\tme.mutex.Lock()\n\tif rep == nil {\n\t\t\/\/ This is an error, but what can we do?\n\t\treturn &FileAttr{Path: name}\n\t}\n\trep.Path = name\n\n\tif !rep.Deletion() {\n\t\tme.attributes[name] = rep\n\t}\n\tme.cond.Broadcast()\n\tme.busy[name] = false, false\n\treturn rep.Copy(withdir)\n}\n\nfunc (me *AttributeCache) Update(files []*FileAttr) {\n\tme.mutex.Lock()\n\tdefer me.mutex.Unlock()\n\tme.update(files)\n}\n\nfunc (me *AttributeCache) update(files []*FileAttr) {\n\tdefer me.verify()\n\tattributes := me.attributes\n\tfor _, inF := range files {\n\t\tr := *inF\n\t\tif len(r.Path) > 0 && r.Path[0] == '\/' {\n\t\t\tpanic(\"Leading slash.\")\n\t\t}\n\n\t\tdir, basename := SplitPath(r.Path)\n\t\tif basename != \"\" {\n\t\t\tdirAttr := attributes[dir]\n\t\t\tif dirAttr == nil {\n\t\t\t\tlog.Println(\"Discarding update: \", r)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif dirAttr.NameModeMap == nil {\n\t\t\t\tlog.Panicf(\"parent dir has no NameModeMap: %q\", dir)\n\t\t\t}\n\t\t\tif r.Deletion() {\n\t\t\t\tdirAttr.NameModeMap[basename] = 0, false\n\t\t\t} else {\n\t\t\t\tdirAttr.NameModeMap[basename] = FileMode(r.Mode &^ 07777)\n\t\t\t}\n\t\t}\n\t\t\n\t\tif r.Deletion() {\n\t\t\tattributes[r.Path] = nil, false\n\t\t\tcontinue\n\t\t}\n\n\t\told := attributes[r.Path]\n\t\tif old == nil {\n\t\t\told = &r\n\t\t\tattributes[r.Path] = old\n\t\t}\n\t\told.Merge(r)\n\t}\n}\n\nfunc (me *AttributeCache) Refresh(prefix string) FileSet {\n\tme.mutex.Lock()\n\tdefer me.mutex.Unlock()\n\n\tif prefix != \"\" && prefix[0] == '\/' {\n\t\tpanic(\"leading \/\")\n\t}\n\n\tupdated := []*FileAttr{}\n\tfor key, attr := range me.attributes {\n\t\t\/\/ TODO -should just do everything?\n\t\tif !strings.HasPrefix(key, prefix) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfi := me.statter(key)\n\t\tif fi == nil && !attr.Deletion() {\n\t\t\tdel := FileAttr{\n\t\t\t\tPath: key,\n\t\t\t}\n\t\t\tupdated = append(updated, &del)\n\t\t}\n\t\t\/\/ TODO - does this handle symlinks corrrectly?\n\t\tif fi != nil && attr.FileInfo != nil && EncodeFileInfo(*attr.FileInfo) != EncodeFileInfo(*fi) {\n\t\t\tnewEnt := me.getter(key)\n\t\t\tnewEnt.Path = key\n\t\t\tupdated = append(updated, newEnt)\n\t\t}\n\t}\n\tfs := FileSet{updated}\n\tfs.Sort()\n\n\tme.update(fs.Files)\n\treturn fs\n}\n\nfunc (me *AttributeCache) Copy() FileSet {\n\tme.mutex.RLock()\n\tdefer me.mutex.RUnlock()\n\n\tdump := []*FileAttr{}\n\tfor _, attr := range me.attributes {\n\t\tdump = append(dump, attr.Copy(true))\n\t}\n\n\tfs := FileSet{dump}\n\tfs.Sort()\n\treturn fs\n}\n<commit_msg>AttributeCache: nits:<commit_after>package termite\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n)\n\n\/\/ A in-memory cache of attributes.\n\/\/\n\/\/ Invariants: for all entries, we have their parent directories too\ntype AttributeCache struct {\n\tmutex      sync.RWMutex\n\tattributes map[string]*FileAttr\n\tcond       *sync.Cond\n\tbusy       map[string]bool\n\tgetter     func(name string) *FileAttr\n\tstatter    func(name string) *os.FileInfo\n}\n\nfunc NewAttributeCache(getter func(n string) *FileAttr,\n\tstatter func(n string) *os.FileInfo) *AttributeCache {\n\tme := &AttributeCache{\n\t\tattributes: make(map[string]*FileAttr),\n\t\tbusy:       map[string]bool{},\n\t}\n\tme.cond = sync.NewCond(&me.mutex)\n\tme.getter = getter\n\tme.statter = statter\n\n\treturn me\n}\n\nvar paranoia = false\n\nfunc (me *AttributeCache) Verify() {\n\tif !paranoia {\n\t\treturn\n\t}\n\tme.mutex.RLock()\n\tdefer me.mutex.RUnlock()\n\tme.verify()\n}\n\nfunc (me *AttributeCache) verify() {\n\tif !paranoia {\n\t\treturn\n\t}\n\tfor k, v := range me.attributes {\n\t\tif k != \"\" && filepath.Clean(k) != k {\n\t\t\tlog.Panicf(\"Unclean path %q\", k)\n\t\t}\n\t\tif v.Path != k {\n\t\t\tlog.Panicf(\"attributes mismatch %q %#v\", k, v)\n\t\t}\n\t\tif _, ok := me.busy[k]; ok {\n\t\t\tlog.Panicf(\"busy and attributes entry for %q\", k)\n\t\t}\n\t\tif v.Deletion() {\n\t\t\tlog.Panicf(\"Attribute cache may not contain deletions %q\", k)\n\t\t}\n\t\tif v.IsDirectory() && v.NameModeMap == nil {\n\t\t\tlog.Panicf(\"dir has no NameModeMap %q\", k)\n\t\t}\n\t\tfor childName, mode := range v.NameModeMap {\n\t\t\tif strings.Contains(childName, \"\\000\") || strings.Contains(childName, \"\/\") || len(childName) == 0 {\n\t\t\t\tlog.Panicf(\"%q has illegal child name %q: %o\", k, childName, mode)  \n\t\t\t}\n\t\t\tif mode == 0 {\n\t\t\t\tlog.Panicf(\"child has 0 mode: %q.%q\", k, childName)\n\t\t\t}\n\t\t}\n\t\tdir, base := SplitPath(k)\n\t\tif base != k {\n\t\t\tparent := me.attributes[dir]\n\t\t\tif v.Deletion() && parent != nil && parent.NameModeMap[base] != 0 {\n\t\t\t\tlog.Panicf(\"Parent %q has entry for deleted %q\", dir, base)\n\t\t\t}\n\t\t\tif !v.Deletion() && parent == nil {\n\t\t\t\tlog.Panicf(\"Missing parent for %q\", k)\n\t\t\t}\n\t\t\tif !v.Deletion() && parent.NameModeMap[base] == 0 {\n\t\t\t\tlog.Panicf(\"Parent %q has no entry for %q\", dir, base)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (me *AttributeCache) Have(name string) bool {\n\tme.mutex.RLock()\n\tdefer me.mutex.RUnlock()\n\t_, ok := me.attributes[name]\n\treturn ok\n}\n\nfunc (me *AttributeCache) Get(name string) (rep *FileAttr) {\n\treturn me.get(name, false)\n}\n\nfunc (me *AttributeCache) GetDir(name string) (rep *FileAttr) {\n\treturn me.get(name, true)\n}\n\nfunc (me *AttributeCache) localGet(name string, withdir bool) (rep *FileAttr) {\n\tme.mutex.RLock()\n\tdefer me.mutex.RUnlock()\n\n\trep, ok := me.attributes[name]\n\tif ok {\n\t\treturn rep.Copy(withdir)\n\t}\n\n\tif name != \"\" {\n\t\tdir, base := SplitPath(name)\n\t\tdirAttr := me.attributes[dir]\n\t\tif dirAttr != nil && dirAttr.NameModeMap != nil && dirAttr.NameModeMap[base] == 0 {\n\t\t\treturn &FileAttr{Path: name}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (me *AttributeCache) get(name string, withdir bool) (rep *FileAttr) {\n\trep = me.localGet(name, withdir)\n\t\n\tif rep != nil {\n\t\treturn rep\n\t}\n\n\tdefer me.Verify()\n\tme.mutex.Lock()\n\tdefer me.mutex.Unlock()\n\treturn me.unsafeGet(name, withdir)\n}\n\t\nfunc (me *AttributeCache) unsafeGet(name string, withdir bool) (rep *FileAttr) {\n\tif name != \"\" {\n\t\tdir, base := SplitPath(name)\n\t\tdirAttr := me.unsafeGet(dir, true)\n\t\tif dirAttr.NameModeMap != nil && dirAttr.NameModeMap[base] == 0 {\n\t\t\treturn &FileAttr{Path: name}\n\t\t}\n\t}\n\n\tfor me.busy[name] && me.attributes[name] == nil {\n\t\tme.cond.Wait()\n\t}\n\trep, ok := me.attributes[name]\n\tif ok {\n\t\treturn rep\n\t}\n\tme.busy[name] = true\n\tme.mutex.Unlock()\n\n\trep = me.getter(name)\n\n\tme.mutex.Lock()\n\tif rep == nil {\n\t\t\/\/ This is an error, but what can we do?\n\t\treturn &FileAttr{Path: name}\n\t}\n\trep.Path = name\n\n\tif !rep.Deletion() {\n\t\tme.attributes[name] = rep\n\t}\n\tme.cond.Broadcast()\n\tme.busy[name] = false, false\n\treturn rep.Copy(withdir)\n}\n\nfunc (me *AttributeCache) Update(files []*FileAttr) {\n\tme.mutex.Lock()\n\tdefer me.mutex.Unlock()\n\tme.update(files)\n}\n\nfunc (me *AttributeCache) update(files []*FileAttr) {\n\tdefer me.verify()\n\tattributes := me.attributes\n\tfor _, inF := range files {\n\t\tr := *inF\n\t\tif len(r.Path) > 0 && r.Path[0] == '\/' {\n\t\t\tpanic(\"Leading slash.\")\n\t\t}\n\n\t\tdir, basename := SplitPath(r.Path)\n\t\tif basename != \"\" {\n\t\t\tdirAttr := attributes[dir]\n\t\t\tif dirAttr == nil {\n\t\t\t\tlog.Println(\"Discarding update: \", r)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif dirAttr.NameModeMap == nil {\n\t\t\t\tlog.Panicf(\"parent dir has no NameModeMap: %q\", dir)\n\t\t\t}\n\t\t\tif r.Deletion() {\n\t\t\t\tdirAttr.NameModeMap[basename] = 0, false\n\t\t\t} else {\n\t\t\t\tdirAttr.NameModeMap[basename] = FileMode(r.Mode &^ 07777)\n\t\t\t}\n\t\t}\n\t\t\n\t\tif r.Deletion() {\n\t\t\tattributes[r.Path] = nil, false\n\t\t\tcontinue\n\t\t}\n\n\t\told := attributes[r.Path]\n\t\tif old == nil {\n\t\t\told = &r\n\t\t\tattributes[r.Path] = old\n\t\t}\n\t\told.Merge(r)\n\t\tme.busy[r.Path] = false, false\n\t}\n\tme.cond.Broadcast()\n}\n\nfunc (me *AttributeCache) Refresh(prefix string) FileSet {\n\tme.mutex.Lock()\n\tdefer me.mutex.Unlock()\n\n\tif prefix != \"\" && prefix[0] == '\/' {\n\t\tpanic(\"leading \/\")\n\t}\n\n\tupdated := []*FileAttr{}\n\tfor key, attr := range me.attributes {\n\t\t\/\/ TODO -should just do everything?\n\t\tif !strings.HasPrefix(key, prefix) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfi := me.statter(key)\n\t\tif fi == nil && !attr.Deletion() {\n\t\t\tdel := FileAttr{\n\t\t\t\tPath: key,\n\t\t\t}\n\t\t\tupdated = append(updated, &del)\n\t\t}\n\t\t\/\/ TODO - does this handle symlinks corrrectly?\n\t\tif fi != nil && attr.FileInfo != nil && EncodeFileInfo(*attr.FileInfo) != EncodeFileInfo(*fi) {\n\t\t\tnewEnt := me.getter(key)\n\t\t\tnewEnt.Path = key\n\t\t\tupdated = append(updated, newEnt)\n\t\t}\n\t}\n\tfs := FileSet{updated}\n\tfs.Sort()\n\n\tme.update(fs.Files)\n\treturn fs\n}\n\nfunc (me *AttributeCache) Copy() FileSet {\n\tme.mutex.RLock()\n\tdefer me.mutex.RUnlock()\n\n\tdump := []*FileAttr{}\n\tfor _, attr := range me.attributes {\n\t\tdump = append(dump, attr.Copy(true))\n\t}\n\n\tfs := FileSet{dump}\n\tfs.Sort()\n\treturn fs\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/x509\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/ogier\/pflag\"\n\t\"github.com\/papertrail\/remote_syslog2\/papertrail\"\n\t\"github.com\/papertrail\/remote_syslog2\/syslog\"\n\t\"github.com\/papertrail\/remote_syslog2\/utils\"\n\t\"launchpad.net\/goyaml\"\n)\n\nconst (\n\tMinimumRefreshInterval = (time.Duration(10) * time.Second)\n\tDefaultConfigFile      = \"\/etc\/log_files.yml\"\n)\n\ntype LogFile struct {\n\tPath string\n\tTag  string\n}\n\ntype ConfigFile struct {\n\tFiles       []LogFile\n\tDestination struct {\n\t\tHost     string `yaml:\"host\"`\n\t\tPort     int    `yaml:\"port\"`\n\t\tProtocol string `yaml:\"protocol\"`\n\t}\n\tHostname string `yaml:\"hostname\"`\n\t\/\/SetYAML is only called on pointers\n\tRefreshInterval *RefreshInterval `yaml:\"new_file_check_interval\"`\n\tExcludeFiles    *RegexCollection `yaml:\"exclude_files\"`\n\tExcludePatterns *RegexCollection `yaml:\"exclude_patterns\"`\n}\n\ntype ConfigManager struct {\n\tConfig    ConfigFile\n\tFlagFiles []LogFile\n\tFlags     struct {\n\t\tHostname        string\n\t\tDestHost        string\n\t\tDestPort        int\n\t\tConfigFile      string\n\t\tLogLevels       string\n\t\tDebugLogFile    string\n\t\tPidFile         string\n\t\tRefreshInterval RefreshInterval\n\t\tUseTCP          bool\n\t\tUseTLS          bool\n\t\tNoDaemonize     bool\n\t\tSeverity        string\n\t\tFacility        string\n\t\tPoll            bool\n\t}\n}\n\ntype RefreshInterval struct {\n\tDuration time.Duration\n}\n\nfunc (r *RefreshInterval) String() string {\n\treturn fmt.Sprint(*r)\n}\n\nfunc (r *RefreshInterval) Set(value string) error {\n\td, err := time.ParseDuration(value)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif d < MinimumRefreshInterval {\n\t\treturn fmt.Errorf(\"refresh interval must be greater than %s\", MinimumRefreshInterval)\n\t}\n\tr.Duration = d\n\treturn nil\n}\n\nfunc (r *RefreshInterval) SetYAML(tag string, value interface{}) bool {\n\terr := r.Set(value.(string))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\ntype RegexCollection []*regexp.Regexp\n\nfunc (r *RegexCollection) Set(value string) error {\n\texp, err := regexp.Compile(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*r = append(*r, exp)\n\treturn nil\n}\n\nfunc (r *RegexCollection) String() string {\n\treturn fmt.Sprint(*r)\n}\n\nfunc (r *RegexCollection) SetYAML(tag string, value interface{}) bool {\n\titems, ok := value.([]interface{})\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tfor _, item := range items {\n\t\ts, ok := item.(string)\n\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\n\t\terr := r.Set(s)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Failed to compile regex expression \\\"%s\\\"\", s))\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc NewConfigManager() ConfigManager {\n\tcm := ConfigManager{}\n\terr := cm.Initialize()\n\n\tif err != nil {\n\t\tlog.Criticalf(\"Failed to configure the application: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn cm\n}\n\nfunc (cm *ConfigManager) Initialize() error {\n\tcm.Config.ExcludeFiles = &RegexCollection{}\n\tcm.Config.ExcludePatterns = &RegexCollection{}\n\tcm.parseFlags()\n\n\terr := cm.readConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (cm *ConfigManager) parseFlags() {\n\tpflag.StringVarP(&cm.Flags.ConfigFile, \"configfile\", \"c\", DefaultConfigFile, \"Path to config\")\n\tpflag.StringVarP(&cm.Flags.DestHost, \"dest-host\", \"d\", \"\", \"Destination syslog hostname or IP\")\n\tpflag.IntVarP(&cm.Flags.DestPort, \"dest-port\", \"p\", 0, \"Destination syslog port\")\n\tif utils.CanDaemonize {\n\t\tpflag.BoolVarP(&cm.Flags.NoDaemonize, \"no-detach\", \"D\", false, \"Don't daemonize and detach from the terminal\")\n\t} else {\n\t\tcm.Flags.NoDaemonize = true\n\t}\n\tpflag.StringVarP(&cm.Flags.Facility, \"facility\", \"f\", \"user\", \"Facility\")\n\tpflag.StringVar(&cm.Flags.Hostname, \"hostname\", \"\", \"Local hostname to send from\")\n\tpflag.StringVar(&cm.Flags.PidFile, \"pid-file\", \"\", \"Location of the PID file\")\n\t\/\/ --parse-syslog\n\tpflag.StringVarP(&cm.Flags.Severity, \"severity\", \"s\", \"notice\", \"Severity\")\n\t\/\/ --strip-color\n\tpflag.BoolVar(&cm.Flags.UseTCP, \"tcp\", false, \"Connect via TCP (no TLS)\")\n\tpflag.BoolVar(&cm.Flags.UseTLS, \"tls\", false, \"Connect via TCP with TLS\")\n\tpflag.BoolVar(&cm.Flags.Poll, \"poll\", false, \"Detect changes by polling instead of inotify\")\n\tpflag.Var(&cm.Flags.RefreshInterval, \"new-file-check-interval\", \"How often to check for new files\")\n\t_ = pflag.Bool(\"no-eventmachine-tail\", false, \"No action, provided for backwards compatibility\")\n\t_ = pflag.Bool(\"eventmachine-tail\", false, \"No action, provided for backwards compatibility\")\n\tpflag.StringVar(&cm.Flags.DebugLogFile, \"debug-log-cfg\", \"\", \"the debug log file\")\n\tpflag.StringVar(&cm.Flags.LogLevels, \"log\", \"<root>=INFO\", \"\\\"logging configuration <root>=INFO;first=TRACE\\\"\")\n\tpflag.Parse()\n\tfor _, arg := range pflag.Args() {\n\t\tlog := strings.Split(arg, \":\")\n\t\tif len(log) == 2 {\n\t\t\tcm.FlagFiles = append(cm.FlagFiles, LogFile{Tag: log[0], Path: log[1]})\n\t\t} else {\n\t\t\tcm.FlagFiles = append(cm.FlagFiles, LogFile{Tag: \"\", Path: log[0]})\n\t\t}\n\t}\n}\n\nfunc (cm *ConfigManager) readConfig() error {\n\tlog.Infof(\"Reading configuration file %s\", cm.Flags.ConfigFile)\n\terr := cm.loadConfigFile()\n\tif err != nil {\n\t\tlog.Errorf(\"%s\", err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (cm *ConfigManager) loadConfigFile() error {\n\tfile, err := ioutil.ReadFile(cm.Flags.ConfigFile)\n\t\/\/ don't error if the default config file isn't found\n\tif os.IsNotExist(err) && cm.Flags.ConfigFile == DefaultConfigFile {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not read the config file: %s\", err)\n\t}\n\n\terr = goyaml.Unmarshal(file, &cm.Config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not parse the config file: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc (cm *ConfigManager) Daemonize() bool {\n\treturn !cm.Flags.NoDaemonize\n}\n\nfunc (cm *ConfigManager) Hostname() string {\n\tswitch {\n\tcase cm.Flags.Hostname != \"\":\n\t\treturn cm.Flags.Hostname\n\tcase cm.Config.Hostname != \"\":\n\t\treturn cm.Config.Hostname\n\tdefault:\n\t\thostname, _ := os.Hostname()\n\t\treturn hostname\n\t}\n}\n\nfunc (cm *ConfigManager) RootCAs() *x509.CertPool {\n\tif cm.DestProtocol() == \"tls\" && cm.DestHost() == \"logs.papertrailapp.com\" {\n\t\treturn papertrail.RootCA()\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc (cm *ConfigManager) DestHost() string {\n\tswitch {\n\tcase cm.Flags.DestHost != \"\":\n\t\treturn cm.Flags.DestHost\n\tcase cm.Config.Destination.Host == \"\":\n\t\tlog.Criticalf(\"No destination hostname specified\")\n\t\tos.Exit(1)\n\t}\n\treturn cm.Config.Destination.Host\n}\n\nfunc (cm ConfigManager) DestPort() int {\n\tswitch {\n\tcase cm.Flags.DestPort != 0:\n\t\treturn cm.Flags.DestPort\n\tcase cm.Config.Destination.Port != 0:\n\t\treturn cm.Config.Destination.Port\n\tdefault:\n\t\treturn 514\n\t}\n}\n\nfunc (cm *ConfigManager) DestProtocol() string {\n\tswitch {\n\tcase cm.Flags.UseTLS:\n\t\treturn \"tls\"\n\tcase cm.Flags.UseTCP:\n\t\treturn \"tcp\"\n\tcase cm.Config.Destination.Protocol != \"\":\n\t\treturn cm.Config.Destination.Protocol\n\tdefault:\n\t\treturn \"udp\"\n\t}\n}\n\nfunc (cm *ConfigManager) Severity() syslog.Priority {\n\ts, err := syslog.Severity(cm.Flags.Severity)\n\tif err != nil {\n\t\tlog.Criticalf(\"%s is not a designated facility\", cm.Flags.Severity)\n\t\tos.Exit(1)\n\t}\n\treturn s\n}\n\nfunc (cm *ConfigManager) Facility() syslog.Priority {\n\tf, err := syslog.Facility(cm.Flags.Facility)\n\tif err != nil {\n\t\tlog.Criticalf(\"%s is not a designated facility\", cm.Flags.Facility)\n\t\tos.Exit(1)\n\t}\n\treturn f\n}\n\nfunc (cm *ConfigManager) Poll() bool {\n\treturn cm.Flags.Poll\n}\n\nfunc (cm *ConfigManager) Files() []LogFile {\n\treturn append(cm.FlagFiles, cm.Config.Files...)\n}\n\nfunc (cm *ConfigManager) DebugLogFile() string {\n\tswitch {\n\tcase cm.Flags.DebugLogFile != \"\":\n\t\treturn cm.Flags.DebugLogFile\n\tdefault:\n\t\treturn \"\/dev\/null\"\n\t}\n}\n\nfunc (cm *ConfigManager) defaultPidFile() string {\n\tpidFiles := []string{\n\t\t\"\/var\/run\/remote_syslog.pid\",\n\t\tos.Getenv(\"HOME\") + \"\/run\/remote_syslog.pid\",\n\t\tos.Getenv(\"HOME\") + \"\/tmp\/remote_syslog.pid\",\n\t\tos.Getenv(\"HOME\") + \"\/remote_syslog.pid\",\n\t\tos.TempDir() + \"\/remote_syslog.pid\",\n\t\tos.Getenv(\"TMPDIR\") + \"\/remote_syslog.pid\",\n\t}\n\tfor _, f := range pidFiles {\n\t\tdir := filepath.Dir(f)\n\t\tdirStat, err := os.Stat(dir)\n\t\tif err != nil || dirStat == nil || !dirStat.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\tfd, err := os.OpenFile(f, os.O_WRONLY|os.O_CREATE, 0644)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfd.Close()\n\t\treturn f\n\t}\n\treturn \"\/tmp\/remote_syslog.pid\"\n}\n\nfunc (cm *ConfigManager) PidFile() string {\n\tswitch {\n\tcase cm.Flags.PidFile != \"\":\n\t\treturn cm.Flags.PidFile\n\tdefault:\n\t\treturn cm.defaultPidFile()\n\t}\n}\n\nfunc (cm *ConfigManager) LogLevels() string {\n\treturn cm.Flags.LogLevels\n}\n\nfunc (cm *ConfigManager) RefreshInterval() RefreshInterval {\n\tswitch {\n\tcase cm.Config.RefreshInterval != nil && cm.Flags.RefreshInterval.Duration != 0:\n\t\treturn cm.Flags.RefreshInterval\n\tcase cm.Config.RefreshInterval != nil:\n\t\treturn *cm.Config.RefreshInterval\n\tcase cm.Flags.RefreshInterval.Duration != 0:\n\t\treturn cm.Flags.RefreshInterval\n\t}\n\treturn RefreshInterval{Duration: MinimumRefreshInterval}\n}\n\nfunc (cm *ConfigManager) ExcludeFiles() []*regexp.Regexp {\n\treturn *cm.Config.ExcludeFiles\n}\n\nfunc (cm *ConfigManager) ExcludePatterns() []*regexp.Regexp {\n\treturn *cm.Config.ExcludePatterns\n}\n<commit_msg>Don't break the existing config file format.<commit_after>package main\n\nimport (\n\t\"crypto\/x509\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/ogier\/pflag\"\n\t\"github.com\/papertrail\/remote_syslog2\/papertrail\"\n\t\"github.com\/papertrail\/remote_syslog2\/syslog\"\n\t\"github.com\/papertrail\/remote_syslog2\/utils\"\n\t\"launchpad.net\/goyaml\"\n)\n\nconst (\n\tMinimumRefreshInterval = (time.Duration(10) * time.Second)\n\tDefaultConfigFile      = \"\/etc\/log_files.yml\"\n)\n\ntype LogFile struct {\n\tPath string\n\tTag  string\n}\n\ntype ConfigFile struct {\n\tFiles       []string\n\tDestination struct {\n\t\tHost     string `yaml:\"host\"`\n\t\tPort     int    `yaml:\"port\"`\n\t\tProtocol string `yaml:\"protocol\"`\n\t}\n\tHostname string `yaml:\"hostname\"`\n\t\/\/SetYAML is only called on pointers\n\tRefreshInterval *RefreshInterval `yaml:\"new_file_check_interval\"`\n\tExcludeFiles    *RegexCollection `yaml:\"exclude_files\"`\n\tExcludePatterns *RegexCollection `yaml:\"exclude_patterns\"`\n}\n\ntype ConfigManager struct {\n\tConfig    ConfigFile\n\tFlagFiles []LogFile\n\tFlags     struct {\n\t\tHostname        string\n\t\tDestHost        string\n\t\tDestPort        int\n\t\tConfigFile      string\n\t\tLogLevels       string\n\t\tDebugLogFile    string\n\t\tPidFile         string\n\t\tRefreshInterval RefreshInterval\n\t\tUseTCP          bool\n\t\tUseTLS          bool\n\t\tNoDaemonize     bool\n\t\tSeverity        string\n\t\tFacility        string\n\t\tPoll            bool\n\t}\n}\n\ntype RefreshInterval struct {\n\tDuration time.Duration\n}\n\nfunc (r *RefreshInterval) String() string {\n\treturn fmt.Sprint(*r)\n}\n\nfunc (r *RefreshInterval) Set(value string) error {\n\td, err := time.ParseDuration(value)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif d < MinimumRefreshInterval {\n\t\treturn fmt.Errorf(\"refresh interval must be greater than %s\", MinimumRefreshInterval)\n\t}\n\tr.Duration = d\n\treturn nil\n}\n\nfunc (r *RefreshInterval) SetYAML(tag string, value interface{}) bool {\n\terr := r.Set(value.(string))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\ntype RegexCollection []*regexp.Regexp\n\nfunc (r *RegexCollection) Set(value string) error {\n\texp, err := regexp.Compile(value)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*r = append(*r, exp)\n\treturn nil\n}\n\nfunc (r *RegexCollection) String() string {\n\treturn fmt.Sprint(*r)\n}\n\nfunc (r *RegexCollection) SetYAML(tag string, value interface{}) bool {\n\titems, ok := value.([]interface{})\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\tfor _, item := range items {\n\t\ts, ok := item.(string)\n\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\n\t\terr := r.Set(s)\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Failed to compile regex expression \\\"%s\\\"\", s))\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc NewConfigManager() ConfigManager {\n\tcm := ConfigManager{}\n\terr := cm.Initialize()\n\n\tif err != nil {\n\t\tlog.Criticalf(\"Failed to configure the application: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn cm\n}\n\nfunc (cm *ConfigManager) Initialize() error {\n\tcm.Config.ExcludeFiles = &RegexCollection{}\n\tcm.Config.ExcludePatterns = &RegexCollection{}\n\tcm.parseFlags()\n\n\terr := cm.readConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (cm *ConfigManager) parseFlags() {\n\tpflag.StringVarP(&cm.Flags.ConfigFile, \"configfile\", \"c\", DefaultConfigFile, \"Path to config\")\n\tpflag.StringVarP(&cm.Flags.DestHost, \"dest-host\", \"d\", \"\", \"Destination syslog hostname or IP\")\n\tpflag.IntVarP(&cm.Flags.DestPort, \"dest-port\", \"p\", 0, \"Destination syslog port\")\n\tif utils.CanDaemonize {\n\t\tpflag.BoolVarP(&cm.Flags.NoDaemonize, \"no-detach\", \"D\", false, \"Don't daemonize and detach from the terminal\")\n\t} else {\n\t\tcm.Flags.NoDaemonize = true\n\t}\n\tpflag.StringVarP(&cm.Flags.Facility, \"facility\", \"f\", \"user\", \"Facility\")\n\tpflag.StringVar(&cm.Flags.Hostname, \"hostname\", \"\", \"Local hostname to send from\")\n\tpflag.StringVar(&cm.Flags.PidFile, \"pid-file\", \"\", \"Location of the PID file\")\n\t\/\/ --parse-syslog\n\tpflag.StringVarP(&cm.Flags.Severity, \"severity\", \"s\", \"notice\", \"Severity\")\n\t\/\/ --strip-color\n\tpflag.BoolVar(&cm.Flags.UseTCP, \"tcp\", false, \"Connect via TCP (no TLS)\")\n\tpflag.BoolVar(&cm.Flags.UseTLS, \"tls\", false, \"Connect via TCP with TLS\")\n\tpflag.BoolVar(&cm.Flags.Poll, \"poll\", false, \"Detect changes by polling instead of inotify\")\n\tpflag.Var(&cm.Flags.RefreshInterval, \"new-file-check-interval\", \"How often to check for new files\")\n\t_ = pflag.Bool(\"no-eventmachine-tail\", false, \"No action, provided for backwards compatibility\")\n\t_ = pflag.Bool(\"eventmachine-tail\", false, \"No action, provided for backwards compatibility\")\n\tpflag.StringVar(&cm.Flags.DebugLogFile, \"debug-log-cfg\", \"\", \"the debug log file\")\n\tpflag.StringVar(&cm.Flags.LogLevels, \"log\", \"<root>=INFO\", \"\\\"logging configuration <root>=INFO;first=TRACE\\\"\")\n\tpflag.Parse()\n\tfor _, arg := range pflag.Args() {\n\t\tlog := strings.Split(arg, \":\")\n\t\tif len(log) == 2 {\n\t\t\tcm.FlagFiles = append(cm.FlagFiles, LogFile{Tag: log[0], Path: log[1]})\n\t\t} else {\n\t\t\tcm.FlagFiles = append(cm.FlagFiles, LogFile{Tag: \"\", Path: log[0]})\n\t\t}\n\t}\n}\n\nfunc (cm *ConfigManager) readConfig() error {\n\tlog.Infof(\"Reading configuration file %s\", cm.Flags.ConfigFile)\n\terr := cm.loadConfigFile()\n\tif err != nil {\n\t\tlog.Errorf(\"%s\", err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (cm *ConfigManager) loadConfigFile() error {\n\tfile, err := ioutil.ReadFile(cm.Flags.ConfigFile)\n\t\/\/ don't error if the default config file isn't found\n\tif os.IsNotExist(err) && cm.Flags.ConfigFile == DefaultConfigFile {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not read the config file: %s\", err)\n\t}\n\n\terr = goyaml.Unmarshal(file, &cm.Config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not parse the config file: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc (cm *ConfigManager) Daemonize() bool {\n\treturn !cm.Flags.NoDaemonize\n}\n\nfunc (cm *ConfigManager) Hostname() string {\n\tswitch {\n\tcase cm.Flags.Hostname != \"\":\n\t\treturn cm.Flags.Hostname\n\tcase cm.Config.Hostname != \"\":\n\t\treturn cm.Config.Hostname\n\tdefault:\n\t\thostname, _ := os.Hostname()\n\t\treturn hostname\n\t}\n}\n\nfunc (cm *ConfigManager) RootCAs() *x509.CertPool {\n\tif cm.DestProtocol() == \"tls\" && cm.DestHost() == \"logs.papertrailapp.com\" {\n\t\treturn papertrail.RootCA()\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc (cm *ConfigManager) DestHost() string {\n\tswitch {\n\tcase cm.Flags.DestHost != \"\":\n\t\treturn cm.Flags.DestHost\n\tcase cm.Config.Destination.Host == \"\":\n\t\tlog.Criticalf(\"No destination hostname specified\")\n\t\tos.Exit(1)\n\t}\n\treturn cm.Config.Destination.Host\n}\n\nfunc (cm ConfigManager) DestPort() int {\n\tswitch {\n\tcase cm.Flags.DestPort != 0:\n\t\treturn cm.Flags.DestPort\n\tcase cm.Config.Destination.Port != 0:\n\t\treturn cm.Config.Destination.Port\n\tdefault:\n\t\treturn 514\n\t}\n}\n\nfunc (cm *ConfigManager) DestProtocol() string {\n\tswitch {\n\tcase cm.Flags.UseTLS:\n\t\treturn \"tls\"\n\tcase cm.Flags.UseTCP:\n\t\treturn \"tcp\"\n\tcase cm.Config.Destination.Protocol != \"\":\n\t\treturn cm.Config.Destination.Protocol\n\tdefault:\n\t\treturn \"udp\"\n\t}\n}\n\nfunc (cm *ConfigManager) Severity() syslog.Priority {\n\ts, err := syslog.Severity(cm.Flags.Severity)\n\tif err != nil {\n\t\tlog.Criticalf(\"%s is not a designated facility\", cm.Flags.Severity)\n\t\tos.Exit(1)\n\t}\n\treturn s\n}\n\nfunc (cm *ConfigManager) Facility() syslog.Priority {\n\tf, err := syslog.Facility(cm.Flags.Facility)\n\tif err != nil {\n\t\tlog.Criticalf(\"%s is not a designated facility\", cm.Flags.Facility)\n\t\tos.Exit(1)\n\t}\n\treturn f\n}\n\nfunc (cm *ConfigManager) Poll() bool {\n\treturn cm.Flags.Poll\n}\n\nfunc (cm *ConfigManager) Files() []LogFile {\n\tlogFiles := cm.FlagFiles\n\tfor _, file := range cm.Config.Files {\n\t\tlog := strings.Split(file, \":\")\n\t\tif len(log) == 2 {\n\t\t\tlogFiles = append(logFiles, LogFile{Tag: log[0], Path: log[1]})\n\t\t} else {\n\t\t\tlogFiles = append(logFiles, LogFile{Tag: \"\", Path: log[0]})\n\t\t}\n\t}\n\treturn logFiles\n}\n\nfunc (cm *ConfigManager) DebugLogFile() string {\n\tswitch {\n\tcase cm.Flags.DebugLogFile != \"\":\n\t\treturn cm.Flags.DebugLogFile\n\tdefault:\n\t\treturn \"\/dev\/null\"\n\t}\n}\n\nfunc (cm *ConfigManager) defaultPidFile() string {\n\tpidFiles := []string{\n\t\t\"\/var\/run\/remote_syslog.pid\",\n\t\tos.Getenv(\"HOME\") + \"\/run\/remote_syslog.pid\",\n\t\tos.Getenv(\"HOME\") + \"\/tmp\/remote_syslog.pid\",\n\t\tos.Getenv(\"HOME\") + \"\/remote_syslog.pid\",\n\t\tos.TempDir() + \"\/remote_syslog.pid\",\n\t\tos.Getenv(\"TMPDIR\") + \"\/remote_syslog.pid\",\n\t}\n\tfor _, f := range pidFiles {\n\t\tdir := filepath.Dir(f)\n\t\tdirStat, err := os.Stat(dir)\n\t\tif err != nil || dirStat == nil || !dirStat.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\tfd, err := os.OpenFile(f, os.O_WRONLY|os.O_CREATE, 0644)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfd.Close()\n\t\treturn f\n\t}\n\treturn \"\/tmp\/remote_syslog.pid\"\n}\n\nfunc (cm *ConfigManager) PidFile() string {\n\tswitch {\n\tcase cm.Flags.PidFile != \"\":\n\t\treturn cm.Flags.PidFile\n\tdefault:\n\t\treturn cm.defaultPidFile()\n\t}\n}\n\nfunc (cm *ConfigManager) LogLevels() string {\n\treturn cm.Flags.LogLevels\n}\n\nfunc (cm *ConfigManager) RefreshInterval() RefreshInterval {\n\tswitch {\n\tcase cm.Config.RefreshInterval != nil && cm.Flags.RefreshInterval.Duration != 0:\n\t\treturn cm.Flags.RefreshInterval\n\tcase cm.Config.RefreshInterval != nil:\n\t\treturn *cm.Config.RefreshInterval\n\tcase cm.Flags.RefreshInterval.Duration != 0:\n\t\treturn cm.Flags.RefreshInterval\n\t}\n\treturn RefreshInterval{Duration: MinimumRefreshInterval}\n}\n\nfunc (cm *ConfigManager) ExcludeFiles() []*regexp.Regexp {\n\treturn *cm.Config.ExcludeFiles\n}\n\nfunc (cm *ConfigManager) ExcludePatterns() []*regexp.Regexp {\n\treturn *cm.Config.ExcludePatterns\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build proto\n\n\/\/ RPC-based remote cache. Similar to HTTP but likely higher performance.\npackage cache\n\nimport (\n\t\"bytes\"\n\t\"core\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/credentials\"\n\t\"google.golang.org\/grpc\/grpclog\"\n\thealthpb \"google.golang.org\/grpc\/health\/grpc_health_v1\"\n\n\tpb \"cache\/proto\/rpc_cache\"\n)\n\nconst maxErrors = 5\n\ntype rpcCache struct {\n\tconnection *grpc.ClientConn\n\tclient     pb.RpcCacheClient\n\tWriteable  bool\n\tConnected  bool\n\tConnecting bool\n\tOSName     string\n\tnumErrors  int32\n\ttimeout    time.Duration\n\tstartTime  time.Time\n}\n\nfunc (cache *rpcCache) Store(target *core.BuildTarget, key []byte) {\n\tif cache.isConnected() && cache.Writeable {\n\t\tlog.Debug(\"Storing %s in RPC cache...\", target.Label)\n\t\tartifacts := []*pb.Artifact{}\n\t\tfor out := range cacheArtifacts(target) {\n\t\t\tartifacts2, err := cache.loadArtifacts(target, out)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warning(\"RPC cache failed to load artifact %s: %s\", out, err)\n\t\t\t\tcache.error()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tartifacts = append(artifacts, artifacts2...)\n\t\t}\n\t\tcache.sendArtifacts(target, key, artifacts)\n\t}\n}\n\nfunc (cache *rpcCache) StoreExtra(target *core.BuildTarget, key []byte, file string) {\n\tif cache.isConnected() && cache.Writeable {\n\t\tlog.Debug(\"Storing %s : %s in RPC cache...\", target.Label, file)\n\t\tartifacts, err := cache.loadArtifacts(target, file)\n\t\tif err != nil {\n\t\t\tlog.Warning(\"RPC cache failed to load artifact %s: %s\", file, err)\n\t\t\tcache.error()\n\t\t\treturn\n\t\t}\n\t\tcache.sendArtifacts(target, key, artifacts)\n\t}\n}\n\nfunc (cache *rpcCache) loadArtifacts(target *core.BuildTarget, file string) ([]*pb.Artifact, error) {\n\tartifacts := []*pb.Artifact{}\n\toutDir := target.OutDir()\n\troot := path.Join(outDir, file)\n\terr := filepath.Walk(root, func(name string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if !info.IsDir() {\n\t\t\tcontent, err := ioutil.ReadFile(name)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tartifacts = append(artifacts, &pb.Artifact{\n\t\t\t\tPackage: target.Label.PackageName,\n\t\t\t\tTarget:  target.Label.Name,\n\t\t\t\tFile:    name[len(outDir)+1:],\n\t\t\t\tBody:    content,\n\t\t\t})\n\t\t}\n\t\treturn nil\n\t})\n\treturn artifacts, err\n}\n\nfunc (cache *rpcCache) sendArtifacts(target *core.BuildTarget, key []byte, artifacts []*pb.Artifact) {\n\treq := pb.StoreRequest{Artifacts: artifacts, Hash: key, Os: runtime.GOOS, Arch: runtime.GOARCH}\n\tctx, cancel := context.WithTimeout(context.Background(), cache.timeout)\n\tdefer cancel()\n\tresp, err := cache.client.Store(ctx, &req)\n\tif err != nil {\n\t\tlog.Warning(\"Error communicating with RPC cache server: %s\", err)\n\t\tcache.error()\n\t} else if !resp.Success {\n\t\tlog.Warning(\"Failed to store artifacts in RPC cache for %s\", target.Label)\n\t}\n}\n\nfunc (cache *rpcCache) Retrieve(target *core.BuildTarget, key []byte) bool {\n\tif !cache.isConnected() {\n\t\treturn false\n\t}\n\treq := pb.RetrieveRequest{Hash: key, Os: runtime.GOOS, Arch: runtime.GOARCH}\n\tfor out := range cacheArtifacts(target) {\n\t\tartifact := pb.Artifact{Package: target.Label.PackageName, Target: target.Label.Name, File: out}\n\t\treq.Artifacts = append(req.Artifacts, &artifact)\n\t}\n\t\/\/ We can't tell from here if retrieval has been successful for a target with no outputs.\n\t\/\/ This is kind of weird but not actually disallowed, and we already have a test case for it,\n\t\/\/ so might as well try to get it right here.\n\tif len(req.Artifacts) == 0 {\n\t\treturn false\n\t}\n\treturn cache.retrieveArtifacts(target, &req, true)\n}\n\nfunc (cache *rpcCache) RetrieveExtra(target *core.BuildTarget, key []byte, file string) bool {\n\tif !cache.isConnected() {\n\t\treturn false\n\t}\n\tartifact := pb.Artifact{Package: target.Label.PackageName, Target: target.Label.Name, File: file}\n\tartifacts := []*pb.Artifact{&artifact}\n\treq := pb.RetrieveRequest{Hash: key, Os: runtime.GOOS, Arch: runtime.GOARCH, Artifacts: artifacts}\n\treturn cache.retrieveArtifacts(target, &req, false)\n}\n\nfunc (cache *rpcCache) retrieveArtifacts(target *core.BuildTarget, req *pb.RetrieveRequest, remove bool) bool {\n\tctx, cancel := context.WithTimeout(context.Background(), cache.timeout)\n\tdefer cancel()\n\tresponse, err := cache.client.Retrieve(ctx, req)\n\tif err != nil {\n\t\tlog.Warning(\"Failed to retrieve artifacts for %s\", target.Label)\n\t\tcache.error()\n\t\treturn false\n\t} else if !response.Success {\n\t\t\/\/ Quiet, this is almost certainly just a 'not found'\n\t\tlog.Debug(\"Couldn't retrieve artifacts for %s [key %s] from RPC cache\", target.Label, base64.RawURLEncoding.EncodeToString(req.Hash))\n\t\treturn false\n\t}\n\t\/\/ Remove any existing outputs first; this is important for cases where the output is a\n\t\/\/ directory, because we get back individual artifacts, and we need to make sure that\n\t\/\/ only the retrieved artifacts are present in the output.\n\tif remove {\n\t\tfor _, out := range target.Outputs() {\n\t\t\tout := path.Join(target.OutDir(), out)\n\t\t\tif err := os.RemoveAll(out); err != nil {\n\t\t\t\tlog.Error(\"Failed to remove artifact %s: %s\", out, err)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\tfor _, artifact := range response.Artifacts {\n\t\tif !cache.writeFile(target, artifact.File, artifact.Body) {\n\t\t\treturn false\n\t\t}\n\t}\n\t\/\/ Sanity check: if we don't get anything back, assume it probably wasn't really a success.\n\treturn len(response.Artifacts) > 0\n}\n\nfunc (cache *rpcCache) writeFile(target *core.BuildTarget, file string, body []byte) bool {\n\tout := path.Join(target.OutDir(), file)\n\tif err := os.MkdirAll(path.Dir(out), core.DirPermissions); err != nil {\n\t\tlog.Warning(\"Failed to create directory for artifacts: %s\", err)\n\t\treturn false\n\t}\n\tif err := core.WriteFile(bytes.NewReader(body), out, fileMode(target)); err != nil {\n\t\tlog.Warning(\"RPC cache failed to write file %s\", err)\n\t\treturn false\n\t}\n\tlog.Debug(\"Retrieved %s - %s from RPC cache\", target.Label, file)\n\treturn true\n}\n\nfunc (cache *rpcCache) Clean(target *core.BuildTarget) {\n\tif cache.isConnected() && cache.Writeable {\n\t\treq := pb.DeleteRequest{Os: runtime.GOOS, Arch: runtime.GOARCH}\n\t\tartifact := pb.Artifact{Package: target.Label.PackageName, Target: target.Label.Name}\n\t\treq.Artifacts = []*pb.Artifact{&artifact}\n\t\tresponse, err := cache.client.Delete(context.Background(), &req)\n\t\tif err != nil || !response.Success {\n\t\t\tlog.Errorf(\"Failed to remove %s from RPC cache\", target.Label)\n\t\t}\n\t}\n}\n\nfunc (cache *rpcCache) connect(config *core.Configuration) {\n\t\/\/ Change grpc to log using our implementation\n\tgrpclog.SetLogger(&grpcLogMabob{})\n\tlog.Info(\"Connecting to RPC cache at %s\", config.Cache.RpcUrl)\n\topts := []grpc.DialOption{grpc.WithTimeout(cache.timeout)}\n\tif config.Cache.RpcPublicKey != \"\" || config.Cache.RpcCACert != \"\" || config.Cache.RpcSecure {\n\t\tauth, err := loadAuth(config.Cache.RpcCACert, config.Cache.RpcPublicKey, config.Cache.RpcPrivateKey)\n\t\tif err != nil {\n\t\t\tlog.Warning(\"Failed to load RPC cache auth keys: %s\", err)\n\t\t\treturn\n\t\t}\n\t\topts = append(opts, auth)\n\t} else {\n\t\topts = append(opts, grpc.WithInsecure())\n\t}\n\tconnection, err := grpc.Dial(config.Cache.RpcUrl, opts...)\n\tif err != nil {\n\t\tcache.Connecting = false\n\t\tlog.Warning(\"Failed to connect to RPC cache: %s\", err)\n\t\treturn\n\t}\n\t\/\/ Note that we have to actually send it a message here to validate the connection;\n\t\/\/ Dial() only seems to return errors for superficial failures like syntactically invalid addresses,\n\t\/\/ it will return essentially immediately even if the server doesn't exist.\n\thealthclient := healthpb.NewHealthClient(connection)\n\tctx, cancel := context.WithTimeout(context.Background(), cache.timeout)\n\tdefer cancel()\n\tresp, err := healthclient.Check(ctx, &healthpb.HealthCheckRequest{Service: \"plz-rpc-cache\"})\n\tif err != nil {\n\t\tcache.Connecting = false\n\t\tlog.Warning(\"Failed to contact RPC cache: %s\", err)\n\t} else if resp.Status != healthpb.HealthCheckResponse_SERVING {\n\t\tcache.Connecting = false\n\t\tlog.Warning(\"RPC cache says it is not serving (%d)\", resp.Status)\n\t} else {\n\t\tcache.connection = connection\n\t\tcache.client = pb.NewRpcCacheClient(connection)\n\t\tcache.Connected = true\n\t\tcache.Connecting = false\n\t\tlog.Info(\"RPC cache connected after %0.2fs\", time.Since(cache.startTime).Seconds())\n\t}\n}\n\n\/\/ isConnected checks if the cache is connected. If it's still trying to connect it allows a\n\/\/ very brief wait to give it a chance to come online.\nfunc (cache *rpcCache) isConnected() bool {\n\tif cache.Connected {\n\t\treturn true\n\t} else if !cache.Connecting {\n\t\treturn false\n\t}\n\tticker := time.NewTicker(10 * time.Millisecond)\n\tfor i := 0; i < 5 && cache.Connecting; i++ {\n\t\t<-ticker.C\n\t}\n\tticker.Stop()\n\treturn cache.Connected\n}\n\n\/\/ error increments the error counter on the cache, and disables it if it gets too high.\n\/\/ Note that after this it won't reconnect; we could try that but it probably isn't worth it\n\/\/ (it's unlikely to restart in time if it's got a nontrivial set of artifacts to scan) and\n\/\/ the user has probably been pestered by enough messages already.\nfunc (cache *rpcCache) error() {\n\tif atomic.AddInt32(&cache.numErrors, 1) >= maxErrors && cache.Connected {\n\t\tlog.Warning(\"Disabling RPC cache, looks like the connection has been lost\")\n\t\tcache.Connected = false\n\t}\n}\n\nfunc newRpcCache(config *core.Configuration) (*rpcCache, error) {\n\tcache := &rpcCache{\n\t\tWriteable:  config.Cache.RpcWriteable,\n\t\tConnecting: true,\n\t\ttimeout:    time.Duration(config.Cache.RpcTimeout) * time.Second,\n\t\tstartTime:  time.Now(),\n\t}\n\tgo cache.connect(config)\n\treturn cache, nil\n}\n\n\/\/ grpcLogMabob is an implementation of grpc's logging interface using our backend.\ntype grpcLogMabob struct{}\n\nfunc (g *grpcLogMabob) Fatal(args ...interface{})                 { log.Fatal(args...) }\nfunc (g *grpcLogMabob) Fatalf(format string, args ...interface{}) { log.Fatalf(format, args...) }\nfunc (g *grpcLogMabob) Fatalln(args ...interface{})               { log.Fatal(args...) }\nfunc (g *grpcLogMabob) Print(args ...interface{})                 { log.Warning(\"%s\", args) }\nfunc (g *grpcLogMabob) Printf(format string, args ...interface{}) { log.Warning(format, args...) }\nfunc (g *grpcLogMabob) Println(args ...interface{})               { log.Warning(\"%s\", args) }\n\n\/\/ loadAuth loads authentication credentials from a given pair of public \/ private key files.\nfunc loadAuth(caCert, publicKey, privateKey string) (grpc.DialOption, error) {\n\tconfig := tls.Config{}\n\tif publicKey != \"\" {\n\t\tlog.Debug(\"Loading client certificate from %s, key %s\", publicKey, privateKey)\n\t\tcert, err := tls.LoadX509KeyPair(publicKey, privateKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.Certificates = []tls.Certificate{cert}\n\t}\n\tif caCert != \"\" {\n\t\tlog.Debug(\"Reading CA cert file from %s\", caCert)\n\t\tcert, err := ioutil.ReadFile(caCert)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.RootCAs = x509.NewCertPool()\n\t\tif !config.RootCAs.AppendCertsFromPEM(cert) {\n\t\t\treturn nil, fmt.Errorf(\"Failed to add any PEM certificates from %s\", caCert)\n\t\t}\n\t}\n\treturn grpc.WithTransportCredentials(credentials.NewTLS(&config)), nil\n}\n<commit_msg>Remove unnecessary multiplication<commit_after>\/\/ +build proto\n\n\/\/ RPC-based remote cache. Similar to HTTP but likely higher performance.\npackage cache\n\nimport (\n\t\"bytes\"\n\t\"core\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/credentials\"\n\t\"google.golang.org\/grpc\/grpclog\"\n\thealthpb \"google.golang.org\/grpc\/health\/grpc_health_v1\"\n\n\tpb \"cache\/proto\/rpc_cache\"\n)\n\nconst maxErrors = 5\n\ntype rpcCache struct {\n\tconnection *grpc.ClientConn\n\tclient     pb.RpcCacheClient\n\tWriteable  bool\n\tConnected  bool\n\tConnecting bool\n\tOSName     string\n\tnumErrors  int32\n\ttimeout    time.Duration\n\tstartTime  time.Time\n}\n\nfunc (cache *rpcCache) Store(target *core.BuildTarget, key []byte) {\n\tif cache.isConnected() && cache.Writeable {\n\t\tlog.Debug(\"Storing %s in RPC cache...\", target.Label)\n\t\tartifacts := []*pb.Artifact{}\n\t\tfor out := range cacheArtifacts(target) {\n\t\t\tartifacts2, err := cache.loadArtifacts(target, out)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warning(\"RPC cache failed to load artifact %s: %s\", out, err)\n\t\t\t\tcache.error()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tartifacts = append(artifacts, artifacts2...)\n\t\t}\n\t\tcache.sendArtifacts(target, key, artifacts)\n\t}\n}\n\nfunc (cache *rpcCache) StoreExtra(target *core.BuildTarget, key []byte, file string) {\n\tif cache.isConnected() && cache.Writeable {\n\t\tlog.Debug(\"Storing %s : %s in RPC cache...\", target.Label, file)\n\t\tartifacts, err := cache.loadArtifacts(target, file)\n\t\tif err != nil {\n\t\t\tlog.Warning(\"RPC cache failed to load artifact %s: %s\", file, err)\n\t\t\tcache.error()\n\t\t\treturn\n\t\t}\n\t\tcache.sendArtifacts(target, key, artifacts)\n\t}\n}\n\nfunc (cache *rpcCache) loadArtifacts(target *core.BuildTarget, file string) ([]*pb.Artifact, error) {\n\tartifacts := []*pb.Artifact{}\n\toutDir := target.OutDir()\n\troot := path.Join(outDir, file)\n\terr := filepath.Walk(root, func(name string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if !info.IsDir() {\n\t\t\tcontent, err := ioutil.ReadFile(name)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tartifacts = append(artifacts, &pb.Artifact{\n\t\t\t\tPackage: target.Label.PackageName,\n\t\t\t\tTarget:  target.Label.Name,\n\t\t\t\tFile:    name[len(outDir)+1:],\n\t\t\t\tBody:    content,\n\t\t\t})\n\t\t}\n\t\treturn nil\n\t})\n\treturn artifacts, err\n}\n\nfunc (cache *rpcCache) sendArtifacts(target *core.BuildTarget, key []byte, artifacts []*pb.Artifact) {\n\treq := pb.StoreRequest{Artifacts: artifacts, Hash: key, Os: runtime.GOOS, Arch: runtime.GOARCH}\n\tctx, cancel := context.WithTimeout(context.Background(), cache.timeout)\n\tdefer cancel()\n\tresp, err := cache.client.Store(ctx, &req)\n\tif err != nil {\n\t\tlog.Warning(\"Error communicating with RPC cache server: %s\", err)\n\t\tcache.error()\n\t} else if !resp.Success {\n\t\tlog.Warning(\"Failed to store artifacts in RPC cache for %s\", target.Label)\n\t}\n}\n\nfunc (cache *rpcCache) Retrieve(target *core.BuildTarget, key []byte) bool {\n\tif !cache.isConnected() {\n\t\treturn false\n\t}\n\treq := pb.RetrieveRequest{Hash: key, Os: runtime.GOOS, Arch: runtime.GOARCH}\n\tfor out := range cacheArtifacts(target) {\n\t\tartifact := pb.Artifact{Package: target.Label.PackageName, Target: target.Label.Name, File: out}\n\t\treq.Artifacts = append(req.Artifacts, &artifact)\n\t}\n\t\/\/ We can't tell from here if retrieval has been successful for a target with no outputs.\n\t\/\/ This is kind of weird but not actually disallowed, and we already have a test case for it,\n\t\/\/ so might as well try to get it right here.\n\tif len(req.Artifacts) == 0 {\n\t\treturn false\n\t}\n\treturn cache.retrieveArtifacts(target, &req, true)\n}\n\nfunc (cache *rpcCache) RetrieveExtra(target *core.BuildTarget, key []byte, file string) bool {\n\tif !cache.isConnected() {\n\t\treturn false\n\t}\n\tartifact := pb.Artifact{Package: target.Label.PackageName, Target: target.Label.Name, File: file}\n\tartifacts := []*pb.Artifact{&artifact}\n\treq := pb.RetrieveRequest{Hash: key, Os: runtime.GOOS, Arch: runtime.GOARCH, Artifacts: artifacts}\n\treturn cache.retrieveArtifacts(target, &req, false)\n}\n\nfunc (cache *rpcCache) retrieveArtifacts(target *core.BuildTarget, req *pb.RetrieveRequest, remove bool) bool {\n\tctx, cancel := context.WithTimeout(context.Background(), cache.timeout)\n\tdefer cancel()\n\tresponse, err := cache.client.Retrieve(ctx, req)\n\tif err != nil {\n\t\tlog.Warning(\"Failed to retrieve artifacts for %s\", target.Label)\n\t\tcache.error()\n\t\treturn false\n\t} else if !response.Success {\n\t\t\/\/ Quiet, this is almost certainly just a 'not found'\n\t\tlog.Debug(\"Couldn't retrieve artifacts for %s [key %s] from RPC cache\", target.Label, base64.RawURLEncoding.EncodeToString(req.Hash))\n\t\treturn false\n\t}\n\t\/\/ Remove any existing outputs first; this is important for cases where the output is a\n\t\/\/ directory, because we get back individual artifacts, and we need to make sure that\n\t\/\/ only the retrieved artifacts are present in the output.\n\tif remove {\n\t\tfor _, out := range target.Outputs() {\n\t\t\tout := path.Join(target.OutDir(), out)\n\t\t\tif err := os.RemoveAll(out); err != nil {\n\t\t\t\tlog.Error(\"Failed to remove artifact %s: %s\", out, err)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\tfor _, artifact := range response.Artifacts {\n\t\tif !cache.writeFile(target, artifact.File, artifact.Body) {\n\t\t\treturn false\n\t\t}\n\t}\n\t\/\/ Sanity check: if we don't get anything back, assume it probably wasn't really a success.\n\treturn len(response.Artifacts) > 0\n}\n\nfunc (cache *rpcCache) writeFile(target *core.BuildTarget, file string, body []byte) bool {\n\tout := path.Join(target.OutDir(), file)\n\tif err := os.MkdirAll(path.Dir(out), core.DirPermissions); err != nil {\n\t\tlog.Warning(\"Failed to create directory for artifacts: %s\", err)\n\t\treturn false\n\t}\n\tif err := core.WriteFile(bytes.NewReader(body), out, fileMode(target)); err != nil {\n\t\tlog.Warning(\"RPC cache failed to write file %s\", err)\n\t\treturn false\n\t}\n\tlog.Debug(\"Retrieved %s - %s from RPC cache\", target.Label, file)\n\treturn true\n}\n\nfunc (cache *rpcCache) Clean(target *core.BuildTarget) {\n\tif cache.isConnected() && cache.Writeable {\n\t\treq := pb.DeleteRequest{Os: runtime.GOOS, Arch: runtime.GOARCH}\n\t\tartifact := pb.Artifact{Package: target.Label.PackageName, Target: target.Label.Name}\n\t\treq.Artifacts = []*pb.Artifact{&artifact}\n\t\tresponse, err := cache.client.Delete(context.Background(), &req)\n\t\tif err != nil || !response.Success {\n\t\t\tlog.Errorf(\"Failed to remove %s from RPC cache\", target.Label)\n\t\t}\n\t}\n}\n\nfunc (cache *rpcCache) connect(config *core.Configuration) {\n\t\/\/ Change grpc to log using our implementation\n\tgrpclog.SetLogger(&grpcLogMabob{})\n\tlog.Info(\"Connecting to RPC cache at %s\", config.Cache.RpcUrl)\n\topts := []grpc.DialOption{grpc.WithTimeout(cache.timeout)}\n\tif config.Cache.RpcPublicKey != \"\" || config.Cache.RpcCACert != \"\" || config.Cache.RpcSecure {\n\t\tauth, err := loadAuth(config.Cache.RpcCACert, config.Cache.RpcPublicKey, config.Cache.RpcPrivateKey)\n\t\tif err != nil {\n\t\t\tlog.Warning(\"Failed to load RPC cache auth keys: %s\", err)\n\t\t\treturn\n\t\t}\n\t\topts = append(opts, auth)\n\t} else {\n\t\topts = append(opts, grpc.WithInsecure())\n\t}\n\tconnection, err := grpc.Dial(config.Cache.RpcUrl, opts...)\n\tif err != nil {\n\t\tcache.Connecting = false\n\t\tlog.Warning(\"Failed to connect to RPC cache: %s\", err)\n\t\treturn\n\t}\n\t\/\/ Note that we have to actually send it a message here to validate the connection;\n\t\/\/ Dial() only seems to return errors for superficial failures like syntactically invalid addresses,\n\t\/\/ it will return essentially immediately even if the server doesn't exist.\n\thealthclient := healthpb.NewHealthClient(connection)\n\tctx, cancel := context.WithTimeout(context.Background(), cache.timeout)\n\tdefer cancel()\n\tresp, err := healthclient.Check(ctx, &healthpb.HealthCheckRequest{Service: \"plz-rpc-cache\"})\n\tif err != nil {\n\t\tcache.Connecting = false\n\t\tlog.Warning(\"Failed to contact RPC cache: %s\", err)\n\t} else if resp.Status != healthpb.HealthCheckResponse_SERVING {\n\t\tcache.Connecting = false\n\t\tlog.Warning(\"RPC cache says it is not serving (%d)\", resp.Status)\n\t} else {\n\t\tcache.connection = connection\n\t\tcache.client = pb.NewRpcCacheClient(connection)\n\t\tcache.Connected = true\n\t\tcache.Connecting = false\n\t\tlog.Info(\"RPC cache connected after %0.2fs\", time.Since(cache.startTime).Seconds())\n\t}\n}\n\n\/\/ isConnected checks if the cache is connected. If it's still trying to connect it allows a\n\/\/ very brief wait to give it a chance to come online.\nfunc (cache *rpcCache) isConnected() bool {\n\tif cache.Connected {\n\t\treturn true\n\t} else if !cache.Connecting {\n\t\treturn false\n\t}\n\tticker := time.NewTicker(10 * time.Millisecond)\n\tfor i := 0; i < 5 && cache.Connecting; i++ {\n\t\t<-ticker.C\n\t}\n\tticker.Stop()\n\treturn cache.Connected\n}\n\n\/\/ error increments the error counter on the cache, and disables it if it gets too high.\n\/\/ Note that after this it won't reconnect; we could try that but it probably isn't worth it\n\/\/ (it's unlikely to restart in time if it's got a nontrivial set of artifacts to scan) and\n\/\/ the user has probably been pestered by enough messages already.\nfunc (cache *rpcCache) error() {\n\tif atomic.AddInt32(&cache.numErrors, 1) >= maxErrors && cache.Connected {\n\t\tlog.Warning(\"Disabling RPC cache, looks like the connection has been lost\")\n\t\tcache.Connected = false\n\t}\n}\n\nfunc newRpcCache(config *core.Configuration) (*rpcCache, error) {\n\tcache := &rpcCache{\n\t\tWriteable:  config.Cache.RpcWriteable,\n\t\tConnecting: true,\n\t\ttimeout:    time.Duration(config.Cache.RpcTimeout),\n\t\tstartTime:  time.Now(),\n\t}\n\tgo cache.connect(config)\n\treturn cache, nil\n}\n\n\/\/ grpcLogMabob is an implementation of grpc's logging interface using our backend.\ntype grpcLogMabob struct{}\n\nfunc (g *grpcLogMabob) Fatal(args ...interface{})                 { log.Fatal(args...) }\nfunc (g *grpcLogMabob) Fatalf(format string, args ...interface{}) { log.Fatalf(format, args...) }\nfunc (g *grpcLogMabob) Fatalln(args ...interface{})               { log.Fatal(args...) }\nfunc (g *grpcLogMabob) Print(args ...interface{})                 { log.Warning(\"%s\", args) }\nfunc (g *grpcLogMabob) Printf(format string, args ...interface{}) { log.Warning(format, args...) }\nfunc (g *grpcLogMabob) Println(args ...interface{})               { log.Warning(\"%s\", args) }\n\n\/\/ loadAuth loads authentication credentials from a given pair of public \/ private key files.\nfunc loadAuth(caCert, publicKey, privateKey string) (grpc.DialOption, error) {\n\tconfig := tls.Config{}\n\tif publicKey != \"\" {\n\t\tlog.Debug(\"Loading client certificate from %s, key %s\", publicKey, privateKey)\n\t\tcert, err := tls.LoadX509KeyPair(publicKey, privateKey)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.Certificates = []tls.Certificate{cert}\n\t}\n\tif caCert != \"\" {\n\t\tlog.Debug(\"Reading CA cert file from %s\", caCert)\n\t\tcert, err := ioutil.ReadFile(caCert)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tconfig.RootCAs = x509.NewCertPool()\n\t\tif !config.RootCAs.AppendCertsFromPEM(cert) {\n\t\t\treturn nil, fmt.Errorf(\"Failed to add any PEM certificates from %s\", caCert)\n\t\t}\n\t}\n\treturn grpc.WithTransportCredentials(credentials.NewTLS(&config)), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package shell\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/operation\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/filer_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/master_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/volume_server_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/needle_map\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/types\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/util\"\n)\n\nfunc init() {\n\tCommands = append(Commands, &commandVolumeFsck{})\n}\n\ntype commandVolumeFsck struct {\n\tenv *CommandEnv\n}\n\nfunc (c *commandVolumeFsck) Name() string {\n\treturn \"volume.fsck\"\n}\n\nfunc (c *commandVolumeFsck) Help() string {\n\treturn `check all volumes to find entries not used by the filer\n\n\tImportant assumption!!!\n\t\tthe system is all used by one filer.\n\n\tThis command works this way:\n\t1. collect all file ids from all volumes, as set A\n\t2. collect all file ids from the filer, as set B\n\t3. find out the set A subtract B\n\n`\n}\n\nfunc (c *commandVolumeFsck) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {\n\n\tc.env = commandEnv\n\n\t\/\/ collect all volume id locations\n\tvolumeIdToServer, err := c.collectVolumeIds()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to collect all volume locations: %v\", err)\n\t}\n\n\t\/\/ create a temp folder\n\ttempFolder, err := ioutil.TempDir(\"\", \"sw_fsck\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create temp folder: %v\", err)\n\t}\n\tfmt.Fprintf(writer, \"working directory: %s\\n\", tempFolder)\n\n\t\/\/ collect each volume file ids\n\tfor volumeId, vinfo := range volumeIdToServer {\n\t\terr = c.collectOneVolumeFileIds(tempFolder, volumeId, vinfo)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to collect file ids from volume %d on %s: %v\", volumeId, vinfo.server, err)\n\t\t}\n\t}\n\n\t\/\/ collect all filer file ids\n\tif err = c.collectFilerFileIds(tempFolder, volumeIdToServer); err != nil {\n\t\treturn fmt.Errorf(\"failed to collect file ids from filer: %v\", err)\n\t}\n\n\t\/\/ volume file ids substract filer file ids\n\tvar totalOrphanChunkCount, totalOrphanDataSize uint64\n\tfor volumeId, server := range volumeIdToServer {\n\t\torphanChunkCount, orphanDataSize, checkErr := c.oneVolumeFileIdsSubtractFilerFileIds(tempFolder, volumeId)\n\t\tif checkErr != nil {\n\t\t\treturn fmt.Errorf(\"failed to collect file ids from volume %d on %s: %v\", volumeId, server, checkErr)\n\t\t}\n\t\ttotalOrphanChunkCount += orphanChunkCount\n\t\ttotalOrphanDataSize += orphanDataSize\n\t}\n\n\tif totalOrphanChunkCount > 0 {\n\t\tfmt.Fprintf(writer, \"total %d orphan chunks, %d bytes\\n\", totalOrphanChunkCount, totalOrphanDataSize)\n\t} else {\n\t\tfmt.Fprintf(writer, \"no orphan data\\n\")\n\t}\n\n\tos.RemoveAll(tempFolder)\n\n\treturn nil\n}\n\nfunc (c *commandVolumeFsck) collectOneVolumeFileIds(tempFolder string, volumeId uint32, vinfo VInfo) error {\n\n\treturn operation.WithVolumeServerClient(vinfo.server, c.env.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {\n\n\t\tcopyFileClient, err := volumeServerClient.CopyFile(context.Background(), &volume_server_pb.CopyFileRequest{\n\t\t\tVolumeId:                 volumeId,\n\t\t\tExt:                      \".idx\",\n\t\t\tCompactionRevision:       math.MaxUint32,\n\t\t\tStopOffset:               math.MaxInt64,\n\t\t\tCollection:               vinfo.collection,\n\t\t\tIsEcVolume:               vinfo.isEcVolume,\n\t\t\tIgnoreSourceFileNotFound: false,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to start copying volume %d.idx: %v\", volumeId, err)\n\t\t}\n\n\t\terr = writeToFile(copyFileClient, getVolumeFileIdFile(tempFolder, volumeId))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to copy %s.idx from %s: %v\", volumeId, vinfo.server, err)\n\t\t}\n\n\t\treturn nil\n\n\t})\n\n}\n\nfunc (c *commandVolumeFsck) collectFilerFileIds(tempFolder string, volumeIdToServer map[uint32]VInfo) error {\n\n\tfiles := make(map[uint32]*os.File)\n\tfor vid := range volumeIdToServer {\n\t\tdst, openErr := os.OpenFile(getFilerFileIdFile(tempFolder, vid), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\t\tif openErr != nil {\n\t\t\treturn fmt.Errorf(\"failed to create file %s: %v\", getFilerFileIdFile(tempFolder, vid), openErr)\n\t\t}\n\t\tfiles[vid] = dst\n\t}\n\tdefer func() {\n\t\tfor _, f := range files {\n\t\t\tf.Close()\n\t\t}\n\t}()\n\n\ttype Item struct {\n\t\tvid     uint32\n\t\tfileKey uint64\n\t}\n\treturn doTraverseBfsAndSaving(c.env, nil, \"\/\", false, func(outputChan chan interface{}) {\n\t\tbuffer := make([]byte, 8)\n\t\tfor item := range outputChan {\n\t\t\ti := item.(*Item)\n\t\t\tutil.Uint64toBytes(buffer, i.fileKey)\n\t\t\tfiles[i.vid].Write(buffer)\n\t\t}\n\t}, func(entry *filer_pb.FullEntry, outputChan chan interface{}) (err error) {\n\t\tfor _, chunk := range entry.Entry.Chunks {\n\t\t\toutputChan <- &Item{\n\t\t\t\tvid:     chunk.Fid.VolumeId,\n\t\t\t\tfileKey: chunk.Fid.FileKey,\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc (c *commandVolumeFsck) oneVolumeFileIdsSubtractFilerFileIds(tempFolder string, volumeId uint32) (orphanChunkCount, orphanDataSize uint64, err error) {\n\n\tdb := needle_map.NewMemDb()\n\tdefer db.Close()\n\n\tif err = db.LoadFromIdx(getVolumeFileIdFile(tempFolder, volumeId)); err != nil {\n\t\treturn\n\t}\n\n\tfilerFileIdsData, err := ioutil.ReadFile(getFilerFileIdFile(tempFolder, volumeId))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdataLen := len(filerFileIdsData)\n\tif dataLen%8 != 0 {\n\t\treturn 0, 0, fmt.Errorf(\"filer data is corrupted\")\n\t}\n\n\tfor i := 0; i < len(filerFileIdsData); i += 8 {\n\t\tfileKey := util.BytesToUint64(filerFileIdsData[i : i+8])\n\t\tdb.Delete(types.NeedleId(fileKey))\n\t}\n\n\tdb.AscendingVisit(func(n needle_map.NeedleValue) error {\n\t\tfmt.Printf(\"%d,%x\\n\", volumeId, n.Key)\n\t\torphanChunkCount++\n\t\torphanDataSize += uint64(n.Size)\n\t\treturn nil\n\t})\n\n\treturn\n\n}\n\ntype VInfo struct {\n\tserver     string\n\tcollection string\n\tisEcVolume bool\n}\n\nfunc (c *commandVolumeFsck) collectVolumeIds() (volumeIdToServer map[uint32]VInfo, err error) {\n\n\tvolumeIdToServer = make(map[uint32]VInfo)\n\tvar resp *master_pb.VolumeListResponse\n\terr = c.env.MasterClient.WithClient(func(client master_pb.SeaweedClient) error {\n\t\tresp, err = client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\n\teachDataNode(resp.TopologyInfo, func(dc string, rack RackId, t *master_pb.DataNodeInfo) {\n\t\tfor _, vi := range t.VolumeInfos {\n\t\t\tvolumeIdToServer[vi.Id] = VInfo{\n\t\t\t\tserver:     t.Id,\n\t\t\t\tcollection: vi.Collection,\n\t\t\t\tisEcVolume: false,\n\t\t\t}\n\t\t}\n\t\tfor _, ecShardInfo := range t.EcShardInfos {\n\t\t\tvolumeIdToServer[ecShardInfo.Id] = VInfo{\n\t\t\t\tserver:     t.Id,\n\t\t\t\tcollection: ecShardInfo.Collection,\n\t\t\t\tisEcVolume: true,\n\t\t\t}\n\t\t}\n\t})\n\n\treturn\n}\n\nfunc getVolumeFileIdFile(tempFolder string, vid uint32) string {\n\treturn filepath.Join(tempFolder, fmt.Sprintf(\"%d.idx\", vid))\n}\n\nfunc getFilerFileIdFile(tempFolder string, vid uint32) string {\n\treturn filepath.Join(tempFolder, fmt.Sprintf(\"%d.fid\", vid))\n}\n\nfunc writeToFile(client volume_server_pb.VolumeServer_CopyFileClient, fileName string) error {\n\tflags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC\n\tdst, err := os.OpenFile(fileName, flags, 0644)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer dst.Close()\n\n\tfor {\n\t\tresp, receiveErr := client.Recv()\n\t\tif receiveErr == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif receiveErr != nil {\n\t\t\treturn fmt.Errorf(\"receiving %s: %v\", fileName, receiveErr)\n\t\t}\n\t\tdst.Write(resp.FileContent)\n\t}\n\treturn nil\n}\n<commit_msg>better output format<commit_after>package shell\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/operation\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/filer_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/master_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/volume_server_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/needle_map\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/types\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/util\"\n)\n\nfunc init() {\n\tCommands = append(Commands, &commandVolumeFsck{})\n}\n\ntype commandVolumeFsck struct {\n\tenv *CommandEnv\n}\n\nfunc (c *commandVolumeFsck) Name() string {\n\treturn \"volume.fsck\"\n}\n\nfunc (c *commandVolumeFsck) Help() string {\n\treturn `check all volumes to find entries not used by the filer\n\n\tImportant assumption!!!\n\t\tthe system is all used by one filer.\n\n\tThis command works this way:\n\t1. collect all file ids from all volumes, as set A\n\t2. collect all file ids from the filer, as set B\n\t3. find out the set A subtract B\n\n`\n}\n\nfunc (c *commandVolumeFsck) Do(args []string, commandEnv *CommandEnv, writer io.Writer) (err error) {\n\n\tc.env = commandEnv\n\n\t\/\/ collect all volume id locations\n\tvolumeIdToServer, err := c.collectVolumeIds()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to collect all volume locations: %v\", err)\n\t}\n\n\t\/\/ create a temp folder\n\ttempFolder, err := ioutil.TempDir(\"\", \"sw_fsck\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create temp folder: %v\", err)\n\t}\n\t\/\/ fmt.Fprintf(writer, \"working directory: %s\\n\", tempFolder)\n\n\t\/\/ collect each volume file ids\n\tfor volumeId, vinfo := range volumeIdToServer {\n\t\terr = c.collectOneVolumeFileIds(tempFolder, volumeId, vinfo)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to collect file ids from volume %d on %s: %v\", volumeId, vinfo.server, err)\n\t\t}\n\t}\n\n\t\/\/ collect all filer file ids\n\tif err = c.collectFilerFileIds(tempFolder, volumeIdToServer); err != nil {\n\t\treturn fmt.Errorf(\"failed to collect file ids from filer: %v\", err)\n\t}\n\n\t\/\/ volume file ids substract filer file ids\n\tvar totalOrphanChunkCount, totalOrphanDataSize uint64\n\tfor volumeId, server := range volumeIdToServer {\n\t\torphanChunkCount, orphanDataSize, checkErr := c.oneVolumeFileIdsSubtractFilerFileIds(tempFolder, volumeId, writer)\n\t\tif checkErr != nil {\n\t\t\treturn fmt.Errorf(\"failed to collect file ids from volume %d on %s: %v\", volumeId, server, checkErr)\n\t\t}\n\t\ttotalOrphanChunkCount += orphanChunkCount\n\t\ttotalOrphanDataSize += orphanDataSize\n\t}\n\n\tif totalOrphanChunkCount > 0 {\n\t\tfmt.Fprintf(writer, \"\\ntotal\\t%d orphan entries\\t%d bytes not used by filer http:\/\/%s:%d\/\\n\",\n\t\t\ttotalOrphanChunkCount, totalOrphanDataSize, c.env.option.FilerHost, c.env.option.FilerPort)\n\t\tfmt.Fprintf(writer, \"This could be normal if multiple filers or no filers are used.\\n\")\n\t} else {\n\t\tfmt.Fprintf(writer, \"no orphan data\\n\")\n\t}\n\n\tos.RemoveAll(tempFolder)\n\n\treturn nil\n}\n\nfunc (c *commandVolumeFsck) collectOneVolumeFileIds(tempFolder string, volumeId uint32, vinfo VInfo) error {\n\n\treturn operation.WithVolumeServerClient(vinfo.server, c.env.option.GrpcDialOption, func(volumeServerClient volume_server_pb.VolumeServerClient) error {\n\n\t\tcopyFileClient, err := volumeServerClient.CopyFile(context.Background(), &volume_server_pb.CopyFileRequest{\n\t\t\tVolumeId:                 volumeId,\n\t\t\tExt:                      \".idx\",\n\t\t\tCompactionRevision:       math.MaxUint32,\n\t\t\tStopOffset:               math.MaxInt64,\n\t\t\tCollection:               vinfo.collection,\n\t\t\tIsEcVolume:               vinfo.isEcVolume,\n\t\t\tIgnoreSourceFileNotFound: false,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to start copying volume %d.idx: %v\", volumeId, err)\n\t\t}\n\n\t\terr = writeToFile(copyFileClient, getVolumeFileIdFile(tempFolder, volumeId))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to copy %s.idx from %s: %v\", volumeId, vinfo.server, err)\n\t\t}\n\n\t\treturn nil\n\n\t})\n\n}\n\nfunc (c *commandVolumeFsck) collectFilerFileIds(tempFolder string, volumeIdToServer map[uint32]VInfo) error {\n\n\tfiles := make(map[uint32]*os.File)\n\tfor vid := range volumeIdToServer {\n\t\tdst, openErr := os.OpenFile(getFilerFileIdFile(tempFolder, vid), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\t\tif openErr != nil {\n\t\t\treturn fmt.Errorf(\"failed to create file %s: %v\", getFilerFileIdFile(tempFolder, vid), openErr)\n\t\t}\n\t\tfiles[vid] = dst\n\t}\n\tdefer func() {\n\t\tfor _, f := range files {\n\t\t\tf.Close()\n\t\t}\n\t}()\n\n\ttype Item struct {\n\t\tvid     uint32\n\t\tfileKey uint64\n\t}\n\treturn doTraverseBfsAndSaving(c.env, nil, \"\/\", false, func(outputChan chan interface{}) {\n\t\tbuffer := make([]byte, 8)\n\t\tfor item := range outputChan {\n\t\t\ti := item.(*Item)\n\t\t\tutil.Uint64toBytes(buffer, i.fileKey)\n\t\t\tfiles[i.vid].Write(buffer)\n\t\t}\n\t}, func(entry *filer_pb.FullEntry, outputChan chan interface{}) (err error) {\n\t\tfor _, chunk := range entry.Entry.Chunks {\n\t\t\toutputChan <- &Item{\n\t\t\t\tvid:     chunk.Fid.VolumeId,\n\t\t\t\tfileKey: chunk.Fid.FileKey,\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc (c *commandVolumeFsck) oneVolumeFileIdsSubtractFilerFileIds(tempFolder string, volumeId uint32, writer io.Writer) (orphanChunkCount, orphanDataSize uint64, err error) {\n\n\tdb := needle_map.NewMemDb()\n\tdefer db.Close()\n\n\tif err = db.LoadFromIdx(getVolumeFileIdFile(tempFolder, volumeId)); err != nil {\n\t\treturn\n\t}\n\n\tfilerFileIdsData, err := ioutil.ReadFile(getFilerFileIdFile(tempFolder, volumeId))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdataLen := len(filerFileIdsData)\n\tif dataLen%8 != 0 {\n\t\treturn 0, 0, fmt.Errorf(\"filer data is corrupted\")\n\t}\n\n\tfor i := 0; i < len(filerFileIdsData); i += 8 {\n\t\tfileKey := util.BytesToUint64(filerFileIdsData[i : i+8])\n\t\tdb.Delete(types.NeedleId(fileKey))\n\t}\n\n\tdb.AscendingVisit(func(n needle_map.NeedleValue) error {\n\t\t\/\/ fmt.Printf(\"%d,%x\\n\", volumeId, n.Key)\n\t\torphanChunkCount++\n\t\torphanDataSize += uint64(n.Size)\n\t\treturn nil\n\t})\n\n\tif orphanChunkCount > 0 {\n\t\tfmt.Fprintf(writer, \"volume %d\\t%d orphan entries\\t%d bytes\\n\", volumeId, orphanChunkCount, orphanDataSize)\n\t}\n\n\treturn\n\n}\n\ntype VInfo struct {\n\tserver     string\n\tcollection string\n\tisEcVolume bool\n}\n\nfunc (c *commandVolumeFsck) collectVolumeIds() (volumeIdToServer map[uint32]VInfo, err error) {\n\n\tvolumeIdToServer = make(map[uint32]VInfo)\n\tvar resp *master_pb.VolumeListResponse\n\terr = c.env.MasterClient.WithClient(func(client master_pb.SeaweedClient) error {\n\t\tresp, err = client.VolumeList(context.Background(), &master_pb.VolumeListRequest{})\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\n\teachDataNode(resp.TopologyInfo, func(dc string, rack RackId, t *master_pb.DataNodeInfo) {\n\t\tfor _, vi := range t.VolumeInfos {\n\t\t\tvolumeIdToServer[vi.Id] = VInfo{\n\t\t\t\tserver:     t.Id,\n\t\t\t\tcollection: vi.Collection,\n\t\t\t\tisEcVolume: false,\n\t\t\t}\n\t\t}\n\t\tfor _, ecShardInfo := range t.EcShardInfos {\n\t\t\tvolumeIdToServer[ecShardInfo.Id] = VInfo{\n\t\t\t\tserver:     t.Id,\n\t\t\t\tcollection: ecShardInfo.Collection,\n\t\t\t\tisEcVolume: true,\n\t\t\t}\n\t\t}\n\t})\n\n\treturn\n}\n\nfunc getVolumeFileIdFile(tempFolder string, vid uint32) string {\n\treturn filepath.Join(tempFolder, fmt.Sprintf(\"%d.idx\", vid))\n}\n\nfunc getFilerFileIdFile(tempFolder string, vid uint32) string {\n\treturn filepath.Join(tempFolder, fmt.Sprintf(\"%d.fid\", vid))\n}\n\nfunc writeToFile(client volume_server_pb.VolumeServer_CopyFileClient, fileName string) error {\n\tflags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC\n\tdst, err := os.OpenFile(fileName, flags, 0644)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer dst.Close()\n\n\tfor {\n\t\tresp, receiveErr := client.Recv()\n\t\tif receiveErr == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif receiveErr != nil {\n\t\t\treturn fmt.Errorf(\"receiving %s: %v\", fileName, receiveErr)\n\t\t}\n\t\tdst.Write(resp.FileContent)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package resp\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n)\n\n\/\/ RedisConnection is the protocol reading and writing layer\ntype RedisConnection struct {\n\tConn   net.Conn\n\treader *bufio.Reader\n}\n\nfunc NewRedisConnection(conn net.Conn) *RedisConnection {\n\treturn &RedisConnection{\n\t\tConn:   conn,\n\t\treader: bufio.NewReader(conn),\n\t}\n}\n\nfunc (rconn *RedisConnection) Close() error {\n\treturn rconn.Conn.Close()\n}\n\nfunc (rconn *RedisConnection) Handle(handler RedisHandler) {\n\tif err := rconn.handle(handler); err != nil {\n\t\tfmt.Printf(\"redis handler error from %v: %v\\n\", rconn.Conn.RemoteAddr(), err)\n\t}\n\tif err := rconn.Close(); err != nil {\n\t\tfmt.Printf(\"error closing connection from %v: %v\\n\", rconn.Conn.RemoteAddr(), err)\n\t}\n}\n\nfunc (rconn *RedisConnection) handle(handler RedisHandler) error {\n\tif err := handler.HandleStart(rconn); err != nil {\n\t\treturn err\n\t}\n\n\tfor {\n\t\terr := rconn.Consume(handler)\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\trconn.WriteError(err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn handler.HandleEnd(rconn)\n}\n\nfunc (rconn *RedisConnection) Consume(handler RedisHandler) error {\n\tc, err := rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch c {\n\tcase '-':\n\t\treturn rconn.consumeError(handler)\n\n\tcase ':':\n\t\treturn rconn.consumeInteger(handler)\n\n\tcase '+':\n\t\treturn rconn.consumeShortString(handler)\n\n\tcase '$':\n\t\treturn rconn.consumeBulkString(handler)\n\n\tcase '*':\n\t\treturn rconn.consumeArray(handler)\n\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown RESP type %#v\", string(c))\n\t}\n\n\treturn nil\n}\n\nfunc (rconn *RedisConnection) consumeError(handler RedisHandler) error {\n\tbuf, err := rconn.scanLine()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn handler.HandleError(rconn, buf)\n}\n\nfunc (rconn *RedisConnection) consumeInteger(handler RedisHandler) error {\n\tn, err := rconn.readInteger()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn handler.HandleInteger(rconn, n)\n}\n\nfunc (rconn *RedisConnection) consumeShortString(handler RedisHandler) error {\n\tbuf, err := rconn.scanLine()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn handler.HandleString(rconn, buf)\n}\n\nfunc (rconn *RedisConnection) consumeBulkString(handler RedisHandler) error {\n\tn, err := rconn.readInteger()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif n < 0 {\n\t\treturn handler.HandleNull(rconn)\n\t}\n\n\tstrReader := io.LimitReader(rconn.reader, int64(n))\n\tif err := handler.HandleBulkString(rconn, n, strReader); err != nil {\n\t\treturn err\n\t}\n\n\tc, err := rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif c != '\\r' {\n\t\treturn fmt.Errorf(\"missing CR\")\n\t}\n\n\tc, err = rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif c != '\\n' {\n\t\treturn fmt.Errorf(\"missing LF after CR\")\n\t}\n\n\treturn nil\n}\n\nfunc (rconn *RedisConnection) consumeArray(handler RedisHandler) error {\n\tn, err := rconn.readInteger()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif n < 0 {\n\t\treturn handler.HandleNull(rconn)\n\t}\n\n\treturn handler.HandleArray(rconn, n)\n}\n\nfunc (rconn *RedisConnection) readUInteger() (uint, error) {\n\tn, err := rconn.scanNumbers(0)\n\tif err != nil {\n\t\treturn n, err\n\t}\n\n\tc, err := rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn n, err\n\t}\n\tif c != '\\n' {\n\t\treturn n, fmt.Errorf(\"missing LF after CR\")\n\t}\n\n\treturn n, nil\n}\n\nfunc (rconn *RedisConnection) readInteger() (int, error) {\n\tn := 0\n\n\tc, err := rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn n, err\n\t}\n\n\tif c == '-' {\n\t\tnu, err := rconn.scanNumbers(0)\n\t\tn = -int(nu)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t} else if c != '\\r' {\n\t\t\/\/ if c > '9' {\n\t\t\/\/ \treturn n, fmt.Errorf(\"unexpected byte %v while scanning integer, expected [0-9]\", c)\n\t\t\/\/ }\n\t\tnu, err := rconn.scanNumbers(uint(c - '0'))\n\t\tn = int(nu)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t}\n\n\tc, err = rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn n, err\n\t}\n\tif c != '\\n' {\n\t\treturn n, fmt.Errorf(\"missing LF after CR\")\n\t}\n\n\treturn n, nil\n}\n\nfunc (rconn *RedisConnection) scanNumbers(n uint) (uint, error) {\n\tfor {\n\t\tc, err := rconn.reader.ReadByte()\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t\tif c == '\\r' {\n\t\t\tbreak\n\t\t}\n\t\t\/\/ if c > '9' {\n\t\t\/\/ \treturn n, fmt.Errorf(\"unexpected byte %v while scanning integer, expected [0-9]\", c)\n\t\t\/\/ }\n\n\t\tn = 10*n + uint(c-'0')\n\t}\n\n\treturn n, nil\n}\n\nfunc (rconn *RedisConnection) scanLine() ([]byte, error) {\n\tbuf, err := rconn.reader.ReadBytes('\\r')\n\tif err != nil {\n\t\treturn buf, err\n\t}\n\n\tc, err := rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn buf, err\n\t}\n\tif c != '\\n' {\n\t\treturn buf, fmt.Errorf(\"missing LF after CR\")\n\t}\n\n\treturn buf, nil\n}\n\nfunc (rconn *RedisConnection) WriteArrayHeader(num int) error {\n\treturn rconn.writef(\"*%v\\r\\n\", num)\n}\n\nfunc (rconn *RedisConnection) WriteInteger(num int) error {\n\treturn rconn.writef(\":%v\\r\\n\", num)\n}\n\nfunc (rconn *RedisConnection) WriteNull() error {\n\treturn rconn.write([]byte(\"$-1\\r\\n\"))\n}\n\nfunc (rconn *RedisConnection) WriteNullArray() error {\n\treturn rconn.write([]byte(\"*-1\\r\\n\"))\n}\n\nfunc (rconn *RedisConnection) WriteBulkBytes(buf []byte) error {\n\tn := len(buf)\n\tif n == 0 {\n\t\treturn rconn.write([]byte(\"$0\\r\\n\\r\\n\"))\n\t}\n\n\tif err := rconn.writef(\"$%v\\r\\n\", n); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := rconn.Conn.Write(buf); err != nil {\n\t\treturn err\n\t}\n\n\treturn rconn.write([]byte(\"\\r\\n\"))\n}\n\nfunc (rconn *RedisConnection) WriteBulkStringHeader(n int) error {\n\treturn rconn.writef(\"$%v\\r\\n\", n)\n}\n\nfunc (rconn *RedisConnection) WriteBulkStringFooter() error {\n\treturn rconn.write([]byte(\"\\r\\n\"))\n}\n\nfunc (rconn *RedisConnection) WriteBulkString(str string) error {\n\tn := len(str)\n\tif n == 0 {\n\t\treturn rconn.write([]byte(\"$0\\r\\n\\r\\n\"))\n\t}\n\treturn rconn.writef(\"$%v\\r\\n%v\\r\\n\", n, str)\n}\n\nfunc (rconn *RedisConnection) WriteSimpleString(str string) error {\n\treturn rconn.writef(\"+%v\\r\\n\", str)\n}\n\nfunc (rconn *RedisConnection) WriteSimpleBytes(b []byte) error {\n\treturn rconn.writef(\"+%s\\r\\n\", b)\n}\n\nfunc (rconn *RedisConnection) WriteError(err error) error {\n\treturn rconn.writef(\"-ERR %v\\r\\n\", err)\n}\n\nfunc (rconn *RedisConnection) WriteErrorBytes(b []byte) error {\n\tif _, err := rconn.Conn.Write([]byte(\"-\")); err != nil {\n\t\treturn err\n\t}\n\tif _, err := rconn.Conn.Write(b); err != nil {\n\t\treturn err\n\t}\n\tif _, err := rconn.Conn.Write([]byte(\"\\r\\n\")); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (rconn *RedisConnection) WriteErrorString(errType string, str string) error {\n\treturn rconn.writef(\"-%v %v\\r\\n\", errType, str)\n}\n\nfunc (rconn *RedisConnection) writef(format string, a ...interface{}) error {\n\t_, err := fmt.Fprintf(rconn.Conn, format, a...)\n\treturn err\n}\n\nfunc (rconn *RedisConnection) write(buf []byte) error {\n\tif _, err := rconn.Conn.Write(buf); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>RedisConnection: docs<commit_after>package resp\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n)\n\n\/\/ RedisConnection is the protocol reading and writing layer\ntype RedisConnection struct {\n\tConn   net.Conn\n\treader *bufio.Reader\n}\n\n\/\/ NewRedisConnection creates a redis connection around an existing net.Conn.\nfunc NewRedisConnection(conn net.Conn) *RedisConnection {\n\treturn &RedisConnection{\n\t\tConn:   conn,\n\t\treader: bufio.NewReader(conn),\n\t}\n}\n\n\/\/ Close closes the underlying connection.\nfunc (rconn *RedisConnection) Close() error {\n\treturn rconn.Conn.Close()\n}\n\n\/\/ Handle runs the passed handler until the connection ends or errors.\nfunc (rconn *RedisConnection) Handle(handler RedisHandler) {\n\tif err := rconn.handle(handler); err != nil {\n\t\tfmt.Printf(\"redis handler error from %v: %v\\n\", rconn.Conn.RemoteAddr(), err)\n\t}\n\tif err := rconn.Close(); err != nil {\n\t\tfmt.Printf(\"error closing connection from %v: %v\\n\", rconn.Conn.RemoteAddr(), err)\n\t}\n}\n\nfunc (rconn *RedisConnection) handle(handler RedisHandler) error {\n\tif err := handler.HandleStart(rconn); err != nil {\n\t\treturn err\n\t}\n\n\tfor {\n\t\terr := rconn.Consume(handler)\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\trconn.WriteError(err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn handler.HandleEnd(rconn)\n}\n\n\/\/ Consume reads one element from the connection and passes it to the given handler.\nfunc (rconn *RedisConnection) Consume(handler RedisHandler) error {\n\tc, err := rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch c {\n\tcase '-':\n\t\treturn rconn.consumeError(handler)\n\n\tcase ':':\n\t\treturn rconn.consumeInteger(handler)\n\n\tcase '+':\n\t\treturn rconn.consumeShortString(handler)\n\n\tcase '$':\n\t\treturn rconn.consumeBulkString(handler)\n\n\tcase '*':\n\t\treturn rconn.consumeArray(handler)\n\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown RESP type %#v\", string(c))\n\t}\n\n\treturn nil\n}\n\nfunc (rconn *RedisConnection) consumeError(handler RedisHandler) error {\n\tbuf, err := rconn.scanLine()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn handler.HandleError(rconn, buf)\n}\n\nfunc (rconn *RedisConnection) consumeInteger(handler RedisHandler) error {\n\tn, err := rconn.readInteger()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn handler.HandleInteger(rconn, n)\n}\n\nfunc (rconn *RedisConnection) consumeShortString(handler RedisHandler) error {\n\tbuf, err := rconn.scanLine()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn handler.HandleString(rconn, buf)\n}\n\nfunc (rconn *RedisConnection) consumeBulkString(handler RedisHandler) error {\n\tn, err := rconn.readInteger()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif n < 0 {\n\t\treturn handler.HandleNull(rconn)\n\t}\n\n\tstrReader := io.LimitReader(rconn.reader, int64(n))\n\tif err := handler.HandleBulkString(rconn, n, strReader); err != nil {\n\t\treturn err\n\t}\n\n\tc, err := rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif c != '\\r' {\n\t\treturn fmt.Errorf(\"missing CR\")\n\t}\n\n\tc, err = rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif c != '\\n' {\n\t\treturn fmt.Errorf(\"missing LF after CR\")\n\t}\n\n\treturn nil\n}\n\nfunc (rconn *RedisConnection) consumeArray(handler RedisHandler) error {\n\tn, err := rconn.readInteger()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif n < 0 {\n\t\treturn handler.HandleNull(rconn)\n\t}\n\n\treturn handler.HandleArray(rconn, n)\n}\n\nfunc (rconn *RedisConnection) readUInteger() (uint, error) {\n\tn, err := rconn.scanNumbers(0)\n\tif err != nil {\n\t\treturn n, err\n\t}\n\n\tc, err := rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn n, err\n\t}\n\tif c != '\\n' {\n\t\treturn n, fmt.Errorf(\"missing LF after CR\")\n\t}\n\n\treturn n, nil\n}\n\nfunc (rconn *RedisConnection) readInteger() (int, error) {\n\tn := 0\n\n\tc, err := rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn n, err\n\t}\n\n\tif c == '-' {\n\t\tnu, err := rconn.scanNumbers(0)\n\t\tn = -int(nu)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t} else if c != '\\r' {\n\t\t\/\/ if c > '9' {\n\t\t\/\/ \treturn n, fmt.Errorf(\"unexpected byte %v while scanning integer, expected [0-9]\", c)\n\t\t\/\/ }\n\t\tnu, err := rconn.scanNumbers(uint(c - '0'))\n\t\tn = int(nu)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t}\n\n\tc, err = rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn n, err\n\t}\n\tif c != '\\n' {\n\t\treturn n, fmt.Errorf(\"missing LF after CR\")\n\t}\n\n\treturn n, nil\n}\n\nfunc (rconn *RedisConnection) scanNumbers(n uint) (uint, error) {\n\tfor {\n\t\tc, err := rconn.reader.ReadByte()\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t\tif c == '\\r' {\n\t\t\tbreak\n\t\t}\n\t\t\/\/ if c > '9' {\n\t\t\/\/ \treturn n, fmt.Errorf(\"unexpected byte %v while scanning integer, expected [0-9]\", c)\n\t\t\/\/ }\n\n\t\tn = 10*n + uint(c-'0')\n\t}\n\n\treturn n, nil\n}\n\nfunc (rconn *RedisConnection) scanLine() ([]byte, error) {\n\tbuf, err := rconn.reader.ReadBytes('\\r')\n\tif err != nil {\n\t\treturn buf, err\n\t}\n\n\tc, err := rconn.reader.ReadByte()\n\tif err != nil {\n\t\treturn buf, err\n\t}\n\tif c != '\\n' {\n\t\treturn buf, fmt.Errorf(\"missing LF after CR\")\n\t}\n\n\treturn buf, nil\n}\n\n\/\/ WriteArrayHeader writes a \"*N\\r\\n\" array header.\nfunc (rconn *RedisConnection) WriteArrayHeader(num int) error {\n\treturn rconn.writef(\"*%v\\r\\n\", num)\n}\n\n\/\/ WriteInteger writes a \":N\\r\\n\" integer literal\nfunc (rconn *RedisConnection) WriteInteger(num int) error {\n\treturn rconn.writef(\":%v\\r\\n\", num)\n}\n\n\/\/ WriteNull writes a \"$-1\\r\\n\" null string\nfunc (rconn *RedisConnection) WriteNull() error {\n\treturn rconn.write([]byte(\"$-1\\r\\n\"))\n}\n\n\/\/ WriteNullArray writes a \"*-1\\r\\n\" null array\nfunc (rconn *RedisConnection) WriteNullArray() error {\n\treturn rconn.write([]byte(\"*-1\\r\\n\"))\n}\n\n\/\/ WriteBulkBytes writes \"$N\\r\\n...\\r\\n\" bulk string from a byte slice.\nfunc (rconn *RedisConnection) WriteBulkBytes(buf []byte) error {\n\tn := len(buf)\n\tif n == 0 {\n\t\treturn rconn.write([]byte(\"$0\\r\\n\\r\\n\"))\n\t}\n\n\tif err := rconn.writef(\"$%v\\r\\n\", n); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := rconn.Conn.Write(buf); err != nil {\n\t\treturn err\n\t}\n\n\treturn rconn.write([]byte(\"\\r\\n\"))\n}\n\n\/\/ WriteBulkStringHeader writes a \"$N\\r\\n\" bulk string header.\nfunc (rconn *RedisConnection) WriteBulkStringHeader(n int) error {\n\treturn rconn.writef(\"$%v\\r\\n\", n)\n}\n\n\/\/ WriteBulkStringFooter writes a \"\\r\\n\" bulk string footer.\nfunc (rconn *RedisConnection) WriteBulkStringFooter() error {\n\treturn rconn.write([]byte(\"\\r\\n\"))\n}\n\n\/\/ WriteBulkString writes a \"$N\\r\\n...\\r\\n\" bulk string.\nfunc (rconn *RedisConnection) WriteBulkString(str string) error {\n\tn := len(str)\n\tif n == 0 {\n\t\treturn rconn.write([]byte(\"$0\\r\\n\\r\\n\"))\n\t}\n\treturn rconn.writef(\"$%v\\r\\n%v\\r\\n\", n, str)\n}\n\n\/\/ WriteSimpleString writes a \"+...\\r\\n\" simple string.\nfunc (rconn *RedisConnection) WriteSimpleString(str string) error {\n\treturn rconn.writef(\"+%v\\r\\n\", str)\n}\n\n\/\/ WriteSimpleBytes writes a \"+...\\r\\n\" simple string froma byte slice.\nfunc (rconn *RedisConnection) WriteSimpleBytes(b []byte) error {\n\treturn rconn.writef(\"+%s\\r\\n\", b)\n}\n\n\/\/ WriteError writes a \"-ERR...\\r\\n\" error.\nfunc (rconn *RedisConnection) WriteError(err error) error {\n\treturn rconn.writef(\"-ERR %v\\r\\n\", err)\n}\n\n\/\/ WriteErrorBytes writes a \"-...\\r\\n\" error from a byte slice.\nfunc (rconn *RedisConnection) WriteErrorBytes(b []byte) error {\n\tif _, err := rconn.Conn.Write([]byte(\"-\")); err != nil {\n\t\treturn err\n\t}\n\tif _, err := rconn.Conn.Write(b); err != nil {\n\t\treturn err\n\t}\n\tif _, err := rconn.Conn.Write([]byte(\"\\r\\n\")); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ WriteErrorString writes a \"-TYPE ...\\r\\n\" error from a string type and body.\nfunc (rconn *RedisConnection) WriteErrorString(errType, str string) error {\n\treturn rconn.writef(\"-%v %v\\r\\n\", errType, str)\n}\n\nfunc (rconn *RedisConnection) writef(format string, a ...interface{}) error {\n\t_, err := fmt.Fprintf(rconn.Conn, format, a...)\n\treturn err\n}\n\nfunc (rconn *RedisConnection) write(buf []byte) error {\n\tif _, err := rconn.Conn.Write(buf); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ consistentHash project consistentHash.go\npackage consistentHash\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/spaolacci\/murmur3\"\n\t\"sort\"\n\t\"strconv\"\n\t\"sync\"\n)\n\nvar (\n\tnoMembersError                   = errors.New(\"no members added\")\n\tnotEnoughMembersError            = errors.New(\"not enough members\")\n\tnotAvailableOnceMembersAddedEror = errors.New(\"not available once members are added\")\n\tinvalidVnodeCountError           = errors.New(\"vnodeCount must be > 0\")\n)\n\nconst (\n\t\/\/ DefaultVnodeCount is a tradeoff of memory and ~ log(N) speed versus how well the hash spreads\n\tDefaultVnodeCount = 200\n)\n\ntype vnode struct {\n\ttoken   uint64\n\taddress string\n}\n\ntype vnodes []vnode\n\ntype consistentHash struct {\n\tvnodes     vnodes\n\tnodes      map[string]bool\n\tvnodeCount int\n\tmutex      sync.Mutex\n}\n\n\/\/ NewConsistentHash creates a new consistentHash pointer and initializes all the necessary fields\nfunc New() *consistentHash {\n\tch := new(consistentHash)\n\tch.nodes = make(map[string]bool)\n\tch.vnodes = make(vnodes, 0)\n\tch.vnodeCount = DefaultVnodeCount\n\treturn ch\n}\n\n\/\/ dumpVnodes prints the vnode slice to stdout, only useful for debugging\nfunc (ch *consistentHash) dumpVnodes() {\n\tfor _, vn := range ch.vnodes {\n\t\tfmt.Printf(\"%v\\n\", vn)\n\t}\n}\n\n\/\/ addressToKey converts an address and an integer to a []byte that we are sure won't be duplicated with a later valid IP\n\/\/ or hostname\nfunc addressToKey(address string, increment int) []byte {\n\treturn []byte(strconv.Itoa(increment) + \"=\" + address)\n}\n\n\/\/ SetVnodeCount sets the number of vnodes that will be added for every server\n\/\/ This must be called before any Add() calls\nfunc (ch *consistentHash) SetVnodeCount(count int) error {\n\tif len(ch.nodes) > 0 {\n\t\treturn notAvailableOnceMembersAddedEror\n\t}\n\tif count < 1 {\n\t\treturn invalidVnodeCountError\n\t}\n\tch.vnodeCount = count\n\treturn nil\n}\n\n\/\/ Add adds a server to the consistentHash\nfunc (ch *consistentHash) Add(address string) {\n\tch.mutex.Lock()\n\tdefer ch.mutex.Unlock()\n\t\/\/ if the address has already been added, there is no work to do\n\tif _, found := ch.nodes[address]; found {\n\t\treturn\n\t}\n\tch.nodes[address] = true\n\tfor i := 0; i < ch.vnodeCount; i++ {\n\t\ttoken := murmur3.Sum64(addressToKey(address, i))\n\t\tnewVnode := vnode{token, address}\n\t\tch.insertVnode(newVnode)\n\t}\n}\n\n\/\/ Remove removes a server from the consistentHash\nfunc (ch *consistentHash) Remove(address string) {\n\tch.mutex.Lock()\n\tdefer ch.mutex.Unlock()\n\tif _, found := ch.nodes[address]; !found {\n\t\treturn\n\t}\n\tfor i := 0; i < ch.vnodeCount; i++ {\n\t\ttoken := murmur3.Sum64(addressToKey(address, i))\n\t\tch.removeVnode(token)\n\t}\n\tdelete(ch.nodes, address)\n}\n\nfunc (v *vnode) String() string {\n\treturn fmt.Sprintf(\"token=%d address=%s\", v.token, v.address)\n}\n\n\/\/ Get finds the closest member for a given key\nfunc (ch *consistentHash) Get(key []byte) (string, error) {\n\tch.mutex.Lock()\n\tdefer ch.mutex.Unlock()\n\tif len(ch.vnodes) == 0 {\n\t\treturn \"\", noMembersError\n\t}\n\ttoken := murmur3.Sum64(key)\n\treturn ch.vnodes[ch.closest(token)].address, nil\n}\n\n\/\/ Get2 finds the closest 2 members for a given key and is just a helper function\n\/\/ calling into GetN\nfunc (ch *consistentHash) Get2(key []byte) (string, string, error) {\n\t\/\/ don't use the mutex since GetN will use it\n\tservers, err := ch.GetN(key, 2)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\treturn servers[0], servers[1], nil\n\n}\n\n\/\/ GetN finds the closest N members for a given key\nfunc (ch *consistentHash) GetN(key []byte, count int) ([]string, error) {\n\tch.mutex.Lock()\n\tdefer ch.mutex.Unlock()\n\tif len(ch.nodes) < count {\n\t\treturn nil, notEnoughMembersError\n\t}\n\ttoken := murmur3.Sum64(key)\n\taddressMap := make(map[string]bool)\n\taddresses := make([]string, count)\n\tindex := ch.closest(token)\n\tfound := 0\n\tfor found < count {\n\t\tif exists := addressMap[ch.vnodes[index].address]; !exists {\n\t\t\taddressMap[ch.vnodes[index].address] = true\n\t\t\taddresses[found] = ch.vnodes[index].address\n\t\t\tfound++\n\t\t}\n\t\tindex++\n\t\tif index == len(ch.vnodes) {\n\t\t\tindex = 0\n\t\t}\n\t}\n\treturn addresses, nil\n\n}\n\n\/\/ removeVnode removes a vnode from the ring\nfunc (ch *consistentHash) removeVnode(token uint64) {\n\tindex := ch.index(token)\n\tif index == len(ch.vnodes) {\n\t\tch.vnodes = ch.vnodes[:index-1]\n\t\treturn\n\t}\n\tch.vnodes = append(ch.vnodes[:index], ch.vnodes[index+1:]...)\n}\n\n\/\/ insertVnode adds a vnode into the appropriate location of the ring\nfunc (ch *consistentHash) insertVnode(vn vnode) {\n\tindex := ch.index(vn.token)\n\tch.vnodes = append(ch.vnodes[:index], append(vnodes{vn}, ch.vnodes[index:]...)...)\n}\n\n\/\/ index returns the position where we should insert a new vnode\n\/\/ differs from closest in that if the new token is bigger than the current highest token\n\/\/ the index returned should be the end\nfunc (ch *consistentHash) index(token uint64) int {\n\tindex := sort.Search(len(ch.vnodes), func(i int) bool {\n\t\treturn ch.vnodes[i].token >= token\n\t})\n\treturn index\n}\n\n\/\/ closest returns the index of the vnode greater than or equal to the token\nfunc (ch *consistentHash) closest(token uint64) int {\n\tindex := sort.Search(len(ch.vnodes), func(i int) bool {\n\t\treturn ch.vnodes[i].token >= token\n\t})\n\tif index == len(ch.vnodes) {\n\t\tindex = 0\n\t}\n\treturn index\n}\n<commit_msg>export struct<commit_after>\/\/ consistentHash project consistentHash.go\npackage consistentHash\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/spaolacci\/murmur3\"\n\t\"sort\"\n\t\"strconv\"\n\t\"sync\"\n)\n\nvar (\n\tnoMembersError                   = errors.New(\"no members added\")\n\tnotEnoughMembersError            = errors.New(\"not enough members\")\n\tnotAvailableOnceMembersAddedEror = errors.New(\"not available once members are added\")\n\tinvalidVnodeCountError           = errors.New(\"vnodeCount must be > 0\")\n)\n\nconst (\n\t\/\/ DefaultVnodeCount is a tradeoff of memory and ~ log(N) speed versus how well the hash spreads\n\tDefaultVnodeCount = 200\n)\n\ntype vnode struct {\n\ttoken   uint64\n\taddress string\n}\n\ntype vnodes []vnode\n\ntype ConsistentHash struct {\n\tvnodes     vnodes\n\tnodes      map[string]bool\n\tvnodeCount int\n\tmutex      sync.Mutex\n}\n\n\/\/ NewConsistentHash creates a new consistentHash pointer and initializes all the necessary fields\nfunc New() *ConsistentHash {\n\tch := new(ConsistentHash)\n\tch.nodes = make(map[string]bool)\n\tch.vnodes = make(vnodes, 0)\n\tch.vnodeCount = DefaultVnodeCount\n\treturn ch\n}\n\n\/\/ dumpVnodes prints the vnode slice to stdout, only useful for debugging\nfunc (ch *ConsistentHash) dumpVnodes() {\n\tfor _, vn := range ch.vnodes {\n\t\tfmt.Printf(\"%v\\n\", vn)\n\t}\n}\n\n\/\/ addressToKey converts an address and an integer to a []byte that we are sure won't be duplicated with a later valid IP\n\/\/ or hostname\nfunc addressToKey(address string, increment int) []byte {\n\treturn []byte(strconv.Itoa(increment) + \"=\" + address)\n}\n\n\/\/ SetVnodeCount sets the number of vnodes that will be added for every server\n\/\/ This must be called before any Add() calls\nfunc (ch *ConsistentHash) SetVnodeCount(count int) error {\n\tif len(ch.nodes) > 0 {\n\t\treturn notAvailableOnceMembersAddedEror\n\t}\n\tif count < 1 {\n\t\treturn invalidVnodeCountError\n\t}\n\tch.vnodeCount = count\n\treturn nil\n}\n\n\/\/ Add adds a server to the consistentHash\nfunc (ch *ConsistentHash) Add(address string) {\n\tch.mutex.Lock()\n\tdefer ch.mutex.Unlock()\n\t\/\/ if the address has already been added, there is no work to do\n\tif _, found := ch.nodes[address]; found {\n\t\treturn\n\t}\n\tch.nodes[address] = true\n\tfor i := 0; i < ch.vnodeCount; i++ {\n\t\ttoken := murmur3.Sum64(addressToKey(address, i))\n\t\tnewVnode := vnode{token, address}\n\t\tch.insertVnode(newVnode)\n\t}\n}\n\n\/\/ Remove removes a server from the consistentHash\nfunc (ch *ConsistentHash) Remove(address string) {\n\tch.mutex.Lock()\n\tdefer ch.mutex.Unlock()\n\tif _, found := ch.nodes[address]; !found {\n\t\treturn\n\t}\n\tfor i := 0; i < ch.vnodeCount; i++ {\n\t\ttoken := murmur3.Sum64(addressToKey(address, i))\n\t\tch.removeVnode(token)\n\t}\n\tdelete(ch.nodes, address)\n}\n\nfunc (v *vnode) String() string {\n\treturn fmt.Sprintf(\"token=%d address=%s\", v.token, v.address)\n}\n\n\/\/ Get finds the closest member for a given key\nfunc (ch *ConsistentHash) Get(key []byte) (string, error) {\n\tch.mutex.Lock()\n\tdefer ch.mutex.Unlock()\n\tif len(ch.vnodes) == 0 {\n\t\treturn \"\", noMembersError\n\t}\n\ttoken := murmur3.Sum64(key)\n\treturn ch.vnodes[ch.closest(token)].address, nil\n}\n\n\/\/ Get2 finds the closest 2 members for a given key and is just a helper function\n\/\/ calling into GetN\nfunc (ch *ConsistentHash) Get2(key []byte) (string, string, error) {\n\t\/\/ don't use the mutex since GetN will use it\n\tservers, err := ch.GetN(key, 2)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\treturn servers[0], servers[1], nil\n\n}\n\n\/\/ GetN finds the closest N members for a given key\nfunc (ch *ConsistentHash) GetN(key []byte, count int) ([]string, error) {\n\tch.mutex.Lock()\n\tdefer ch.mutex.Unlock()\n\tif len(ch.nodes) < count {\n\t\treturn nil, notEnoughMembersError\n\t}\n\ttoken := murmur3.Sum64(key)\n\taddressMap := make(map[string]bool)\n\taddresses := make([]string, count)\n\tindex := ch.closest(token)\n\tfound := 0\n\tfor found < count {\n\t\tif exists := addressMap[ch.vnodes[index].address]; !exists {\n\t\t\taddressMap[ch.vnodes[index].address] = true\n\t\t\taddresses[found] = ch.vnodes[index].address\n\t\t\tfound++\n\t\t}\n\t\tindex++\n\t\tif index == len(ch.vnodes) {\n\t\t\tindex = 0\n\t\t}\n\t}\n\treturn addresses, nil\n\n}\n\n\/\/ removeVnode removes a vnode from the ring\nfunc (ch *ConsistentHash) removeVnode(token uint64) {\n\tindex := ch.index(token)\n\tif index == len(ch.vnodes) {\n\t\tch.vnodes = ch.vnodes[:index-1]\n\t\treturn\n\t}\n\tch.vnodes = append(ch.vnodes[:index], ch.vnodes[index+1:]...)\n}\n\n\/\/ insertVnode adds a vnode into the appropriate location of the ring\nfunc (ch *ConsistentHash) insertVnode(vn vnode) {\n\tindex := ch.index(vn.token)\n\tch.vnodes = append(ch.vnodes[:index], append(vnodes{vn}, ch.vnodes[index:]...)...)\n}\n\n\/\/ index returns the position where we should insert a new vnode\n\/\/ differs from closest in that if the new token is bigger than the current highest token\n\/\/ the index returned should be the end\nfunc (ch *ConsistentHash) index(token uint64) int {\n\tindex := sort.Search(len(ch.vnodes), func(i int) bool {\n\t\treturn ch.vnodes[i].token >= token\n\t})\n\treturn index\n}\n\n\/\/ closest returns the index of the vnode greater than or equal to the token\nfunc (ch *ConsistentHash) closest(token uint64) int {\n\tindex := sort.Search(len(ch.vnodes), func(i int) bool {\n\t\treturn ch.vnodes[i].token >= token\n\t})\n\tif index == len(ch.vnodes) {\n\t\tindex = 0\n\t}\n\treturn index\n}\n<|endoftext|>"}
{"text":"<commit_before>package dingo\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\n\t\"github.com\/mission-liao\/dingo\/broker\"\n\t\"github.com\/mission-liao\/dingo\/common\"\n\t\"github.com\/mission-liao\/dingo\/transport\"\n)\n\n\/\/\n\/\/ mapper container\n\/\/\n\ntype _mappers struct {\n\tworkers *_workers\n\tmappers *common.Routines\n\ttoLock  sync.Mutex\n\tto      atomic.Value\n}\n\n\/\/ allocating more mappers\n\/\/\n\/\/ parameters:\n\/\/ - tasks: input channel for transport.Task\n\/\/ - receipts: output channel for broker.Receipt\nfunc (me *_mappers) more(tasks <-chan *transport.Task, receipts chan<- *broker.Receipt) {\n\tgo me._mapper_routine_(me.mappers.New(), me.mappers.Wait(), me.mappers.Events(), tasks, receipts)\n}\n\n\/\/ dispatching a 'transport.Task'\n\/\/\n\/\/ parameters:\n\/\/ - t: the task\n\/\/ returns:\n\/\/ - err: any error\nfunc (me *_mappers) dispatch(t *transport.Task) (err error) {\n\tall := me.to.Load().(map[string]chan *transport.Task)\n\tif out, ok := all[t.Name()]; ok {\n\t\tout <- t\n\t} else {\n\t\terr = errWorkerNotFound\n\t}\n\treturn\n}\n\n\/\/\n\/\/ proxy of _workers\n\/\/\n\nfunc (me *_mappers) allocateWorkers(name string, count, share int) ([]<-chan *transport.Report, int, error) {\n\tme.toLock.Lock()\n\tdefer me.toLock.Unlock()\n\n\tall := me.to.Load().(map[string]chan *transport.Task)\n\tif _, ok := all[name]; ok {\n\t\treturn nil, count, errors.New(fmt.Sprintf(\"already registered: %v\", name))\n\t}\n\tt := make(chan *transport.Task, 10)\n\tr, n, err := me.workers.allocate(name, t, nil, count, share)\n\tif err != nil {\n\t\treturn r, n, err\n\t}\n\n\talln := make(map[string]chan *transport.Task)\n\tfor k := range all {\n\t\talln[k] = all[k]\n\t}\n\talln[name] = t\n\tme.to.Store(alln)\n\treturn r, n, err\n}\n\n\/\/\n\/\/ common.Object interface\n\/\/\n\nfunc (me *_mappers) Events() (ret []<-chan *common.Event, err error) {\n\tret, err = me.workers.Events()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tret = append(ret, me.mappers.Events())\n\treturn\n}\n\nfunc (m *_mappers) Close() (err error) {\n\tm.mappers.Close()\n\terr = m.workers.Close()\n\n\tm.toLock.Lock()\n\tdefer m.toLock.Unlock()\n\n\tall := m.to.Load().(map[string]chan *transport.Task)\n\tfor _, v := range all {\n\t\tclose(v)\n\t}\n\tm.to.Store(make(map[string]chan *transport.Task))\n\n\treturn\n}\n\n\/\/ factory function\n\/\/ parameters:\n\/\/ - tasks: input channel\n\/\/ returns:\n\/\/ ...\nfunc newMappers(trans *transport.Mgr) (m *_mappers, err error) {\n\tw, err := newWorkers(trans)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tm = &_mappers{\n\t\tworkers: w,\n\t\tmappers: common.NewRoutines(),\n\t}\n\n\tm.to.Store(make(map[string]chan *transport.Task))\n\treturn\n}\n\n\/\/\n\/\/ mapper routine\n\/\/\n\nfunc (m *_mappers) _mapper_routine_(\n\tquit <-chan int,\n\twait *sync.WaitGroup,\n\tevents chan<- *common.Event,\n\ttasks <-chan *transport.Task,\n\treceipts chan<- *broker.Receipt,\n) {\n\tdefer wait.Done()\n\tfor {\n\t\tselect {\n\t\tcase t, ok := <-tasks:\n\t\t\tif !ok {\n\t\t\t\tgoto cleanup\n\t\t\t}\n\n\t\t\t\/\/ find registered worker\n\t\t\terr := m.dispatch(t)\n\n\t\t\t\/\/ compose a receipt\n\t\t\tvar rpt broker.Receipt\n\t\t\tif err != nil {\n\t\t\t\t\/\/ send an error event\n\t\t\t\tevents <- common.NewEventFromError(common.InstT.MAPPER, err)\n\n\t\t\t\tif err == errWorkerNotFound {\n\t\t\t\t\trpt = broker.Receipt{\n\t\t\t\t\t\tStatus: broker.Status.WORKER_NOT_FOUND,\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\trpt = broker.Receipt{\n\t\t\t\t\t\tStatus:  broker.Status.NOK,\n\t\t\t\t\t\tPayload: err,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trpt = broker.Receipt{\n\t\t\t\t\tStatus: broker.Status.OK,\n\t\t\t\t}\n\t\t\t}\n\t\t\treceipts <- &rpt\n\n\t\tcase <-quit:\n\t\t\t\/\/ clean up code below\n\t\t\tgoto cleanup\n\t\t}\n\t}\ncleanup:\n\t\/\/ TODO: cleanup\n\tclose(receipts)\n\treturn\n}\n<commit_msg>clean TODOs<commit_after>package dingo\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\n\t\"github.com\/mission-liao\/dingo\/broker\"\n\t\"github.com\/mission-liao\/dingo\/common\"\n\t\"github.com\/mission-liao\/dingo\/transport\"\n)\n\n\/\/\n\/\/ mapper container\n\/\/\n\ntype _mappers struct {\n\tworkers *_workers\n\tmappers *common.Routines\n\ttoLock  sync.Mutex\n\tto      atomic.Value\n}\n\n\/\/ allocating more mappers\n\/\/\n\/\/ parameters:\n\/\/ - tasks: input channel for transport.Task\n\/\/ - receipts: output channel for broker.Receipt\nfunc (me *_mappers) more(tasks <-chan *transport.Task, receipts chan<- *broker.Receipt) {\n\tgo me._mapper_routine_(me.mappers.New(), me.mappers.Wait(), me.mappers.Events(), tasks, receipts)\n}\n\n\/\/ dispatching a 'transport.Task'\n\/\/\n\/\/ parameters:\n\/\/ - t: the task\n\/\/ returns:\n\/\/ - err: any error\nfunc (me *_mappers) dispatch(t *transport.Task) (err error) {\n\tall := me.to.Load().(map[string]chan *transport.Task)\n\tif out, ok := all[t.Name()]; ok {\n\t\tout <- t\n\t} else {\n\t\terr = errWorkerNotFound\n\t}\n\treturn\n}\n\n\/\/\n\/\/ proxy of _workers\n\/\/\n\nfunc (me *_mappers) allocateWorkers(name string, count, share int) ([]<-chan *transport.Report, int, error) {\n\tme.toLock.Lock()\n\tdefer me.toLock.Unlock()\n\n\tall := me.to.Load().(map[string]chan *transport.Task)\n\tif _, ok := all[name]; ok {\n\t\treturn nil, count, errors.New(fmt.Sprintf(\"already registered: %v\", name))\n\t}\n\tt := make(chan *transport.Task, 10)\n\tr, n, err := me.workers.allocate(name, t, nil, count, share)\n\tif err != nil {\n\t\treturn r, n, err\n\t}\n\n\talln := make(map[string]chan *transport.Task)\n\tfor k := range all {\n\t\talln[k] = all[k]\n\t}\n\talln[name] = t\n\tme.to.Store(alln)\n\treturn r, n, err\n}\n\n\/\/\n\/\/ common.Object interface\n\/\/\n\nfunc (me *_mappers) Events() (ret []<-chan *common.Event, err error) {\n\tret, err = me.workers.Events()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tret = append(ret, me.mappers.Events())\n\treturn\n}\n\nfunc (m *_mappers) Close() (err error) {\n\tm.mappers.Close()\n\terr = m.workers.Close()\n\n\tm.toLock.Lock()\n\tdefer m.toLock.Unlock()\n\n\tall := m.to.Load().(map[string]chan *transport.Task)\n\tfor _, v := range all {\n\t\tclose(v)\n\t}\n\tm.to.Store(make(map[string]chan *transport.Task))\n\n\treturn\n}\n\n\/\/ factory function\n\/\/ parameters:\n\/\/ - tasks: input channel\n\/\/ returns:\n\/\/ ...\nfunc newMappers(trans *transport.Mgr) (m *_mappers, err error) {\n\tw, err := newWorkers(trans)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tm = &_mappers{\n\t\tworkers: w,\n\t\tmappers: common.NewRoutines(),\n\t}\n\n\tm.to.Store(make(map[string]chan *transport.Task))\n\treturn\n}\n\n\/\/\n\/\/ mapper routine\n\/\/\n\nfunc (m *_mappers) _mapper_routine_(\n\tquit <-chan int,\n\twait *sync.WaitGroup,\n\tevents chan<- *common.Event,\n\ttasks <-chan *transport.Task,\n\treceipts chan<- *broker.Receipt,\n) {\n\tdefer wait.Done()\n\tdefer close(receipts)\n\n\treceive := func(t *transport.Task) {\n\t\t\/\/ find registered worker\n\t\terr := m.dispatch(t)\n\n\t\t\/\/ compose a receipt\n\t\tvar rpt broker.Receipt\n\t\tif err != nil {\n\t\t\t\/\/ send an error event\n\t\t\tevents <- common.NewEventFromError(common.InstT.MAPPER, err)\n\n\t\t\tif err == errWorkerNotFound {\n\t\t\t\trpt = broker.Receipt{\n\t\t\t\t\tStatus: broker.Status.WORKER_NOT_FOUND,\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trpt = broker.Receipt{\n\t\t\t\t\tStatus:  broker.Status.NOK,\n\t\t\t\t\tPayload: err,\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\trpt = broker.Receipt{\n\t\t\t\tStatus: broker.Status.OK,\n\t\t\t}\n\t\t}\n\t\treceipts <- &rpt\n\t}\n\nfinished:\n\tfor {\n\t\tselect {\n\t\tcase t, ok := <-tasks:\n\t\t\tif !ok {\n\t\t\t\tbreak finished\n\t\t\t}\n\t\t\treceive(t)\n\n\t\tcase <-quit:\n\t\t\t\/\/ clean up code below\n\t\t\tbreak finished\n\t\t}\n\t}\n\ndone:\n\t\/\/ consuming remaining tasks in channel.\n\tfor {\n\t\tselect {\n\t\tcase t, ok := <-tasks:\n\t\t\tif !ok {\n\t\t\t\tbreak done\n\t\t\t}\n\t\t\treceive(t)\n\t\tdefault:\n\t\t\tbreak done\n\t\t}\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package qb\n\nimport (\n\t\"fmt\"\n\t\"github.com\/fatih\/structs\"\n\t\"github.com\/serenize\/snaker\"\n\t\"strings\"\n)\n\nconst tagPrefix = \"qb\"\n\n\/\/ NewMapper instantiates a new mapper object and returns it as a mapper pointer\nfunc NewMapper(driver string) *Mapper {\n\treturn &Mapper{\n\t\tdriver: driver,\n\t}\n}\n\n\/\/ Mapper is the generic struct for struct to table mapping\ntype Mapper struct {\n\tdriver string\n}\n\nfunc (m *Mapper) extractValue(value string) string {\n\n\thasParams := strings.Contains(value, \"(\") && strings.Contains(value, \")\")\n\n\tif hasParams {\n\t\tstartIndex := strings.Index(value, \"(\")\n\t\tendIndex := strings.Index(value, \")\")\n\t\treturn value[startIndex+1 : endIndex]\n\t}\n\n\treturn \"\"\n}\n\n\/\/ ConvertType returns the type mapping of column.\n\/\/ If tagType is, then colType would automatically be resolved.\n\/\/ If tagType is not \"\", then automatic type resolving would be overridden by tagType\nfunc (m *Mapper) ConvertType(colType string, tagType string) *Type {\n\n\t\/\/ convert tagType\n\tif tagType != \"\" {\n\t\ttagType = strings.ToUpper(tagType)\n\t\treturn &Type{func() string { return tagType }}\n\t}\n\n\t\/\/ convert default type\n\tswitch colType {\n\tcase \"string\":\n\t\treturn VarChar()\n\tcase \"int\":\n\t\treturn Int()\n\tcase \"int64\":\n\t\treturn BigInt()\n\tcase \"float32\":\n\t\treturn Float()\n\tcase \"float64\":\n\t\treturn Float()\n\tcase \"bool\":\n\t\treturn Boolean()\n\tcase \"uuid.UUID\":\n\t\tif m.driver == \"postgres\" {\n\t\t\treturn UUID()\n\t\t}\n\t\treturn VarChar(36)\n\tcase \"time.Time\":\n\t\treturn Timestamp()\n\tcase \"*time.Time\":\n\t\treturn Timestamp()\n\tdefault:\n\t\treturn VarChar()\n\t}\n}\n\n\/\/ Convert parses struct and converts it to a new table\nfunc (m *Mapper) Convert(model interface{}) (*Table, error) {\n\n\tmodelName := snaker.CamelToSnake(structs.Name(model))\n\n\ttable := &Table{\n\t\tname:        modelName,\n\t\tcolumns:     []Column{},\n\t\tconstraints: []Constraint{},\n\t\tbuilder:     NewBuilder(),\n\t}\n\n\tfmt.Printf(\"model name: %s\\n\\n\", modelName)\n\n\tvar col Column\n\tvar rawTag string\n\n\tfor _, f := range structs.Fields(model) {\n\n\t\tcolName := snaker.CamelToSnake(f.Name())\n\t\tcolType := fmt.Sprintf(\"%T\", f.Value())\n\n\t\trawTag = f.Tag(tagPrefix)\n\n\t\tconstraints := []Constraint{}\n\t\tfmt.Printf(\"field name: %s\\n\", colName)\n\t\tfmt.Printf(\"field raw tag: %s\\n\", rawTag)\n\t\tfmt.Printf(\"field type name: %T\\n\", f.Value())\n\t\tfmt.Printf(\"field constraints: %v\\n\", constraints)\n\n\t\t\/\/ clean trailing spaces of tag\n\t\trawTag = strings.Replace(f.Tag(tagPrefix), \" \", \"\", 1)\n\n\t\t\/\/ parse tag\n\t\ttag, err := ParseTag(rawTag)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ convert tag into constraints\n\t\tvar constraint Constraint\n\t\tfor _, v := range tag.Constraints {\n\t\t\tif v == \"null\" {\n\t\t\t\tconstraint = Null()\n\t\t\t} else if v == \"notnull\" {\n\t\t\t\tconstraint = NotNull()\n\t\t\t} else if v == \"unique\" {\n\t\t\t\tconstraint = Constraint{\n\t\t\t\t\tName: \"UNIQUE\",\n\t\t\t\t}\n\t\t\t} else if v == \"index\" {\n\t\t\t\tconstraint = Constraint{\n\t\t\t\t\tName: \"INDEX\",\n\t\t\t\t}\n\t\t\t} else if strings.Contains(v, \"default\") {\n\t\t\t\tconstraint = Default(m.extractValue(v))\n\t\t\t} else if strings.Contains(v, \"primary_key\") {\n\t\t\t\ttable.AddPrimary(colName)\n\t\t\t\tcontinue\n\t\t\t} else if strings.Contains(v, \"ref\") && strings.Contains(v, \"(\") && strings.Contains(v, \")\") {\n\t\t\t\ttc := strings.Split(m.extractValue(v), \".\")\n\t\t\t\ttable.AddRef(colName, tc[0], tc[1])\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"Invalid constraint: %s\", v)\n\t\t\t}\n\t\t\tconstraints = append(constraints, constraint)\n\t\t}\n\n\t\tfmt.Printf(\"field tag.Type: %s\\n\", tag.Type)\n\t\tfmt.Printf(\"field tag.Constraints: %v\\n\", tag.Constraints)\n\n\t\tcol = Column{\n\t\t\tName:        colName,\n\t\t\tConstraints: constraints,\n\t\t\tType:        m.ConvertType(colType, tag.Type),\n\t\t}\n\n\t\ttable.AddColumn(col)\n\n\t\tfmt.Println()\n\t}\n\n\treturn table, nil\n}\n<commit_msg>remove index tag temporarily, remove uuid type check because go standard lib doesn't have uuid library<commit_after>package qb\n\nimport (\n\t\"fmt\"\n\t\"github.com\/fatih\/structs\"\n\t\"github.com\/serenize\/snaker\"\n\t\"strings\"\n)\n\nconst tagPrefix = \"qb\"\n\n\/\/ NewMapper instantiates a new mapper object and returns it as a mapper pointer\nfunc NewMapper(driver string) *Mapper {\n\treturn &Mapper{\n\t\tdriver: driver,\n\t}\n}\n\n\/\/ Mapper is the generic struct for struct to table mapping\ntype Mapper struct {\n\tdriver string\n}\n\nfunc (m *Mapper) extractValue(value string) string {\n\n\thasParams := strings.Contains(value, \"(\") && strings.Contains(value, \")\")\n\n\tif hasParams {\n\t\tstartIndex := strings.Index(value, \"(\")\n\t\tendIndex := strings.Index(value, \")\")\n\t\treturn value[startIndex+1 : endIndex]\n\t}\n\n\treturn \"\"\n}\n\n\/\/ ConvertType returns the type mapping of column.\n\/\/ If tagType is, then colType would automatically be resolved.\n\/\/ If tagType is not \"\", then automatic type resolving would be overridden by tagType\nfunc (m *Mapper) ConvertType(colType string, tagType string) *Type {\n\n\t\/\/ convert tagType\n\tif tagType != \"\" {\n\t\ttagType = strings.ToUpper(tagType)\n\t\treturn &Type{func() string { return tagType }}\n\t}\n\n\t\/\/ convert default type\n\tswitch colType {\n\tcase \"string\":\n\t\treturn VarChar()\n\tcase \"int\":\n\t\treturn Int()\n\tcase \"int64\":\n\t\treturn BigInt()\n\tcase \"float32\":\n\t\treturn Float()\n\tcase \"float64\":\n\t\treturn Float()\n\tcase \"bool\":\n\t\treturn Boolean()\n\tcase \"time.Time\":\n\t\treturn Timestamp()\n\tcase \"*time.Time\":\n\t\treturn Timestamp()\n\tdefault:\n\t\treturn VarChar()\n\t}\n}\n\n\/\/ Convert parses struct and converts it to a new table\nfunc (m *Mapper) Convert(model interface{}) (*Table, error) {\n\n\tmodelName := snaker.CamelToSnake(structs.Name(model))\n\n\ttable := &Table{\n\t\tname:        modelName,\n\t\tcolumns:     []Column{},\n\t\tconstraints: []Constraint{},\n\t\tbuilder:     NewBuilder(),\n\t}\n\n\tfmt.Printf(\"model name: %s\\n\\n\", modelName)\n\n\tvar col Column\n\tvar rawTag string\n\n\tfor _, f := range structs.Fields(model) {\n\n\t\tcolName := snaker.CamelToSnake(f.Name())\n\t\tcolType := fmt.Sprintf(\"%T\", f.Value())\n\n\t\trawTag = f.Tag(tagPrefix)\n\n\t\tconstraints := []Constraint{}\n\t\tfmt.Printf(\"field name: %s\\n\", colName)\n\t\tfmt.Printf(\"field raw tag: %s\\n\", rawTag)\n\t\tfmt.Printf(\"field type name: %T\\n\", f.Value())\n\t\tfmt.Printf(\"field constraints: %v\\n\", constraints)\n\n\t\t\/\/ clean trailing spaces of tag\n\t\trawTag = strings.Replace(f.Tag(tagPrefix), \" \", \"\", 1)\n\n\t\t\/\/ parse tag\n\t\ttag, err := ParseTag(rawTag)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ convert tag into constraints\n\t\tvar constraint Constraint\n\t\tfor _, v := range tag.Constraints {\n\t\t\tif v == \"null\" {\n\t\t\t\tconstraint = Null()\n\t\t\t} else if v == \"notnull\" {\n\t\t\t\tconstraint = NotNull()\n\t\t\t} else if v == \"unique\" {\n\t\t\t\tconstraint = Constraint{\n\t\t\t\t\tName: \"UNIQUE\",\n\t\t\t\t}\n\t\t\t} else if strings.Contains(v, \"default\") {\n\t\t\t\tconstraint = Default(m.extractValue(v))\n\t\t\t} else if strings.Contains(v, \"primary_key\") {\n\t\t\t\ttable.AddPrimary(colName)\n\t\t\t\tcontinue\n\t\t\t} else if strings.Contains(v, \"ref\") && strings.Contains(v, \"(\") && strings.Contains(v, \")\") {\n\t\t\t\ttc := strings.Split(m.extractValue(v), \".\")\n\t\t\t\ttable.AddRef(colName, tc[0], tc[1])\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"Invalid constraint: %s\", v)\n\t\t\t}\n\t\t\tconstraints = append(constraints, constraint)\n\t\t}\n\n\t\tfmt.Printf(\"field tag.Type: %s\\n\", tag.Type)\n\t\tfmt.Printf(\"field tag.Constraints: %v\\n\", tag.Constraints)\n\n\t\tcol = Column{\n\t\t\tName:        colName,\n\t\t\tConstraints: constraints,\n\t\t\tType:        m.ConvertType(colType, tag.Type),\n\t\t}\n\n\t\ttable.AddColumn(col)\n\n\t\tfmt.Println()\n\t}\n\n\treturn table, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n)\n\nfunc TestGetHosts(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.URL.Path != \"\/hosts\" {\n\t\t\tt.Errorf(\"expected HTTP request to \/hosts, got %s\", r.URL.Path)\n\t\t}\n\n\t\tfmt.Fprintln(w, `[\n      {\n        \"id\": \"14dff6d8-3b9a-41be-9ffd-d0d054a17492\",\n        \"url\": \"http:\/\/dummy\/hosts\/default_bfirsh\",\n        \"name\": \"default_bfirsh\"\n      }\n    ]`)\n\t}))\n\tdefer ts.Close()\n\n\tclient := HTTPClient{ts.URL, \"dummy_token\"}\n\n\thosts, err := client.GetHosts()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif len(hosts) != 1 {\n\t\tt.Errorf(\"expected 1 element, got %d (hosts: %v)\", len(hosts), hosts)\n\t}\n\tif hosts[0].Name != \"default_bfirsh\" {\n\t\tt.Errorf(\"expected default_bfirsh, got %s (hosts: %v)\", hosts[0].Name, hosts)\n\t}\n}\n\nfunc TestCreateHost(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.URL.Path != \"\/hosts\" {\n\t\t\tt.Errorf(\"expected HTTP request to \/hosts, got %s\", r.URL.Path)\n\t\t}\n\n\t\tif r.Header.Get(\"Content-Type\") != \"application\/json\" {\n\t\t\tt.Errorf(\"expected application\/json, got %s\", r.Header.Get(\"Content-Type\"))\n\t\t}\n\n\t\tbody, _ := ioutil.ReadAll(r.Body)\n\t\tvar data map[string]string\n\t\tjson.Unmarshal(body, &data)\n\n\t\tif data[\"name\"] != \"newhost\" {\n\t\t\tt.Errorf(\"expected 'newhost', got '%s'\", data[\"name\"])\n\t\t}\n\n\t\tw.WriteHeader(201)\n\t\tfmt.Fprintln(w, `{\n      \"id\": \"14dff6d8-3b9a-41be-9ffd-d0d054a17492\",\n      \"url\": \"http:\/\/dummy\/hosts\/newhost\",\n      \"name\": \"newhost\"\n    }`)\n\t}))\n\n\tclient := HTTPClient{ts.URL, \"dummy_token\"}\n\n\thost, err := client.CreateHost(\"newhost\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif host.Name != \"newhost\" {\n\t\tt.Errorf(\"expected 'newhost', got '%s' (host: %v)\", host.Name, host)\n\t}\n}\n\nfunc TestDeleteHost(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != \"DELETE\" || r.URL.Path != \"\/hosts\/myhost\" {\n\t\t\tt.Errorf(\"expected DELETE request to \/hosts\/myhost, got %s request to %s\", r.Method, r.URL.Path)\n\t\t}\n\n\t\tfmt.Fprintln(w, \"\")\n\t}))\n\n\tclient := HTTPClient{ts.URL, \"dummy_token\"}\n\n\terr := client.DeleteHost(\"myhost\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestDeleteHostError(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(500)\n\t\tfmt.Fprintln(w, \"I broke :(\")\n\t}))\n\n\tclient := HTTPClient{ts.URL, \"dummy_token\"}\n\n\terr := client.DeleteHost(\"myhost\")\n\tif err == nil {\n\t\tt.Error(\"expected DeleteHost() to return an error\")\n\t}\n}\n<commit_msg>Fix API test<commit_after>package api\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n)\n\nfunc TestGetHosts(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.URL.Path != \"\/hosts\" {\n\t\t\tt.Errorf(\"expected HTTP request to \/hosts, got %s\", r.URL.Path)\n\t\t}\n\n\t\tfmt.Fprintln(w, `[\n      {\n        \"id\": \"14dff6d8-3b9a-41be-9ffd-d0d054a17492\",\n        \"url\": \"http:\/\/dummy\/hosts\/default_bfirsh\",\n        \"name\": \"default_bfirsh\"\n      }\n    ]`)\n\t}))\n\tdefer ts.Close()\n\n\tclient := HTTPClient{ts.URL, \"dummy_token\"}\n\n\thosts, err := client.GetHosts()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif len(hosts) != 1 {\n\t\tt.Errorf(\"expected 1 element, got %d (hosts: %v)\", len(hosts), hosts)\n\t}\n\tif hosts[0].Name != \"default_bfirsh\" {\n\t\tt.Errorf(\"expected default_bfirsh, got %s (hosts: %v)\", hosts[0].Name, hosts)\n\t}\n}\n\nfunc TestCreateHost(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.URL.Path != \"\/hosts\" {\n\t\t\tt.Errorf(\"expected HTTP request to \/hosts, got %s\", r.URL.Path)\n\t\t}\n\n\t\tif r.Header.Get(\"Content-Type\") != \"application\/json\" {\n\t\t\tt.Errorf(\"expected application\/json, got %s\", r.Header.Get(\"Content-Type\"))\n\t\t}\n\n\t\tbody, _ := ioutil.ReadAll(r.Body)\n\t\tvar data map[string]interface{}\n\t\tjson.Unmarshal(body, &data)\n\n\t\tif data[\"name\"] != \"newhost\" {\n\t\t\tt.Errorf(\"expected 'newhost', got '%s'\", data[\"name\"])\n\t\t}\n\n\t\tif int(data[\"size\"].(float64)) != 512 {\n\t\t\tt.Errorf(\"expected 512, got %#v\", data[\"size\"])\n\t\t}\n\n\t\tw.WriteHeader(201)\n\t\tfmt.Fprintln(w, `{\n      \"id\": \"14dff6d8-3b9a-41be-9ffd-d0d054a17492\",\n      \"url\": \"http:\/\/dummy\/hosts\/newhost\",\n      \"name\": \"newhost\"\n    }`)\n\t}))\n\n\tclient := HTTPClient{ts.URL, \"dummy_token\"}\n\n\thost, err := client.CreateHost(\"newhost\", 512)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif host.Name != \"newhost\" {\n\t\tt.Errorf(\"expected 'newhost', got '%s' (host: %v)\", host.Name, host)\n\t}\n}\n\nfunc TestDeleteHost(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method != \"DELETE\" || r.URL.Path != \"\/hosts\/myhost\" {\n\t\t\tt.Errorf(\"expected DELETE request to \/hosts\/myhost, got %s request to %s\", r.Method, r.URL.Path)\n\t\t}\n\n\t\tfmt.Fprintln(w, \"\")\n\t}))\n\n\tclient := HTTPClient{ts.URL, \"dummy_token\"}\n\n\terr := client.DeleteHost(\"myhost\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestDeleteHostError(t *testing.T) {\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(500)\n\t\tfmt.Fprintln(w, \"I broke :(\")\n\t}))\n\n\tclient := HTTPClient{ts.URL, \"dummy_token\"}\n\n\terr := client.DeleteHost(\"myhost\")\n\tif err == nil {\n\t\tt.Error(\"expected DeleteHost() to return an error\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package matrix provides functions for simple linear algebra\npackage matrix\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ Describes error during calculations\ntype MatrixError struct {\n\tErrorString string\n}\n\nfunc (err *MatrixError) Error() string { return err.ErrorString }\n\nvar (\n\tErrIncompatibleSizes = &MatrixError{\"Incompatible sizes of matricies\"}\n\tErrOutOfBounds       = &MatrixError{\"The element you are trying to access is out of bounds.\"}\n)\n\n\/\/ A function that will apply an abitary transformation to an element in the matrix\ntype ApplyFunc func(index int, value float64) float64\n\ntype Matrix struct {\n\trows, cols int\n\tvalues     []float64\n}\n\n\/\/ Creates a new Matrix and initializes all values to 0\nfunc Zeros(rows, cols int) *Matrix {\n\tA := new(Matrix)\n\n\tA.rows = rows\n\tA.cols = cols\n\tA.values = make([]float64, rows*cols)\n\n\treturn A\n}\n\n\/\/ Creates a new Matrix and initializes all values to 1\nfunc Ones(rows, cols int) *Matrix {\n\tA := Zeros(rows, cols)\n\tA.AddNum(1)\n\n\treturn A\n}\n\n\/\/ Creates a new identity matrix\nfunc Eye(size int) *Matrix {\n\tA := Zeros(size, size)\n\n\tfor i := 1; i <= size; i++ {\n\t\tA.Set(i, i, 1)\n\t}\n\n\treturn A\n}\n\n\/\/ Constructs a new matrix with random values in range [0;1)\nfunc Rand(rows, cols int) *Matrix {\n\tA := Zeros(rows, cols)\n\n\tfor i := range A.values {\n\t\tA.values[i] = rand.Float64()\n\t}\n\n\treturn A\n}\n\n\/\/ Constructs a new Matrix from a Matlab style representation\nfunc FromMatlab(str string) *Matrix {\n\trows := strings.Split(str, \";\")\n\n\tfor i, row := range rows {\n\t\trows[i] = strings.Replace(row, \",\", \" \", -1)\n\t}\n\n\tnRows := len(rows)\n\tnColumns := len(strings.Fields(rows[0]))\n\n\tA := Zeros(nRows, nColumns)\n\n\tfor i, row := range rows {\n\t\trow = strings.Trim(row, \"[] \")\n\t\tstrNums := strings.Fields(row)\n\n\t\tfor j, num := range strNums {\n\t\t\tn, _ := strconv.ParseFloat(num, 64)\n\t\t\tA.Set(i+1, j+1, n)\n\t\t}\n\t}\n\n\treturn A\n}\n\n\/\/ Return a Matlab representation of the matrix\nfunc (A *Matrix) ToMatlab() string {\n\tbuffer := new(bytes.Buffer)\n\tbuffer.WriteString(\"[\")\n\n\tfor i, v := range A.values {\n\t\tbuffer.WriteString(fmt.Sprintf(\"%f \", v))\n\n\t\tif (i+1)%A.cols == 0 {\n\t\t\tbuffer.WriteString(\"; \")\n\t\t}\n\t}\n\n\tbuffer.WriteString(\"]\")\n\n\treturn buffer.String()\n}\n\n\/\/ Gives the dimensions of the matrix\nfunc (A *Matrix) Dim() (int, int) {\n\treturn A.rows, A.cols\n}\n\n\/\/ Return the number of rows in the matrix\nfunc (A *Matrix) Rows() int {\n\treturn A.rows\n}\n\n\/\/ Return the number of columns in the matrix\nfunc (A *Matrix) Columns() int {\n\treturn A.cols\n}\n\n\/\/ Returns an array of all the values\nfunc (A *Matrix) Values() []float64 {\n\ttmp := make([]float64, len(A.values))\n\tcopy(tmp, A.values)\n\treturn tmp\n}\n\n\/\/ Returns an exact copy of the matrix\nfunc (A *Matrix) Copy() *Matrix {\n\tB := Zeros(A.rows, A.cols)\n\tcopy(B.values, A.values)\n\n\treturn B\n}\n\nfunc (A *Matrix) Apply(f ApplyFunc) *Matrix {\n\tfor i, v := range A.values {\n\t\tA.values[i] = f(i, v)\n\t}\n\n\treturn A\n}\n\n\/\/ Returns a string representation of the matrix\nfunc (A *Matrix) String() string {\n\tbuffer := new(bytes.Buffer)\n\n\tfor i, elem := range A.values {\n\t\tbuffer.WriteString(fmt.Sprintf(\"%.3f \", elem))\n\n\t\tif (i+1)%A.cols == 0 {\n\t\t\tbuffer.WriteString(\"\\n\")\n\t\t}\n\t}\n\n\treturn buffer.String()\n}\n\n\/\/ Retrieve value at [row, col]\nfunc (A *Matrix) Get(row, col int) (float64, error) {\n\n\tif A.isOutOfBounds(row, col) {\n\t\treturn 0, ErrOutOfBounds\n\t}\n\n\treturn A.values[(row-1)*A.cols+col-1], nil\n}\n\n\/\/ Set the element at [row, col] to val\nfunc (A *Matrix) Set(row, col int, val float64) error {\n\n\tif A.isOutOfBounds(row, col) {\n\t\treturn ErrOutOfBounds\n\t}\n\n\tA.values[(row-1)*A.cols+col-1] = val\n\n\treturn nil\n}\n\nfunc (A *Matrix) Sigmoid() *Matrix {\n\tfor i, v := range A.values {\n\t\tA.values[i] = sigmoid(v)\n\t}\n\n\treturn A\n}\n\n\/\/ Transpose the matrix (in-place, costly)\nfunc (A *Matrix) Transpose() *Matrix {\n\tB := Zeros(A.cols, A.rows)\n\n\tfor i := 1; i <= A.rows; i++ {\n\t\tfor j := 1; j <= A.cols; j++ {\n\t\t\tv, _ := A.Get(i, j)\n\t\t\tB.Set(j, i, v)\n\t\t}\n\t}\n\n\tA.rows, A.cols = A.cols, A.rows\n\tcopy(A.values, B.values)\n\treturn A\n}\n\n\/\/ Add B to the matrix A (in-place)\nfunc (A *Matrix) Add(B *Matrix) (*Matrix, error) {\n\tif !sameSize(A, B) {\n\t\treturn nil, ErrIncompatibleSizes\n\t}\n\n\tfor i, val := range B.values {\n\t\tA.values[i] += val\n\t}\n\n\treturn A, nil\n}\n\n\/\/ Subtract B from the matrix A (in-place)\nfunc (A *Matrix) Sub(B *Matrix) (*Matrix, error) {\n\tif !sameSize(A, B) {\n\t\treturn nil, ErrIncompatibleSizes\n\t}\n\n\tfor i, val := range B.values {\n\t\tA.values[i] -= val\n\t}\n\n\treturn A, nil\n}\n\n\/\/ Multiply 2 matricies with each other returning a new matrix\nfunc (A *Matrix) Mul(B *Matrix) (*Matrix, error) {\n\tif !columnIsRow(A, B) {\n\t\treturn nil, ErrIncompatibleSizes\n\t}\n\n\tC := Zeros(A.rows, B.cols)\n\n\tfor i := 0; i < C.rows; i++ {\n\t\tfor j := 0; j < C.cols; j++ {\n\t\t\tsum := float64(0)\n\n\t\t\tfor k := 0; k < A.cols; k++ {\n\t\t\t\tsum += A.values[i*A.cols+k] * B.values[k*B.cols+j]\n\t\t\t}\n\n\t\t\tC.values[i*C.rows+j] = sum\n\t\t}\n\t}\n\n\treturn C, nil\n}\n\n\/\/ Standard scalar product of 2 matricies\nfunc (A *Matrix) Dot(B *Matrix) (*Matrix, error) {\n\tif !sameSize(A, B) {\n\t\treturn nil, ErrIncompatibleSizes\n\t}\n\n\tfor i, v := range B.values {\n\t\tA.values[i] *= v\n\t}\n\treturn A, nil\n}\n\n\/\/ Scale the matrix in-place by the factor f\nfunc (A *Matrix) Scale(f float64) *Matrix {\n\tfor i := range A.values {\n\t\tA.values[i] *= f\n\t}\n\n\treturn A\n}\n\n\/\/ Take every element of the matrix to the power of n (in-place)\nfunc (A *Matrix) Power(n float64) *Matrix {\n\tfor i, elem := range A.values {\n\t\tA.values[i] = math.Pow(elem, n)\n\t}\n\n\treturn A\n}\n\n\/\/ Add n to all elements in the matrix (in-place)\nfunc (A *Matrix) AddNum(n float64) *Matrix {\n\tfor i := range A.values {\n\t\tA.values[i] += n\n\t}\n\n\treturn A\n}\n\nfunc (A *Matrix) isOutOfBounds(row, col int) bool {\n\tindex := (row-1)*A.cols + col - 1\n\n\tif index >= len(A.values) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc sameSize(A, B *Matrix) bool {\n\treturn A.rows == B.rows && A.cols == B.cols\n}\n\nfunc columnIsRow(A, B *Matrix) bool {\n\treturn A.cols == B.rows\n}\n\n\/\/ Sigmoid function\nfunc sigmoid(z float64) float64 {\n\treturn 1.0 \/ (1.0 + math.Pow(math.E, -1.0*z))\n}\n<commit_msg>removed sigmoid functionality<commit_after>\/\/ Package matrix provides functions for simple linear algebra\npackage matrix\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ Describes error during calculations\ntype MatrixError struct {\n\tErrorString string\n}\n\nfunc (err *MatrixError) Error() string { return err.ErrorString }\n\nvar (\n\tErrIncompatibleSizes = &MatrixError{\"Incompatible sizes of matricies\"}\n\tErrOutOfBounds       = &MatrixError{\"The element you are trying to access is out of bounds.\"}\n)\n\n\/\/ A function that will apply an abitary transformation to an element in the matrix\ntype ApplyFunc func(index int, value float64) float64\n\ntype Matrix struct {\n\trows, cols int\n\tvalues     []float64\n}\n\n\/\/ Creates a new Matrix and initializes all values to 0\nfunc Zeros(rows, cols int) *Matrix {\n\tA := new(Matrix)\n\n\tA.rows = rows\n\tA.cols = cols\n\tA.values = make([]float64, rows*cols)\n\n\treturn A\n}\n\n\/\/ Creates a new Matrix and initializes all values to 1\nfunc Ones(rows, cols int) *Matrix {\n\tA := Zeros(rows, cols)\n\tA.AddNum(1)\n\n\treturn A\n}\n\n\/\/ Creates a new identity matrix\nfunc Eye(size int) *Matrix {\n\tA := Zeros(size, size)\n\n\tfor i := 1; i <= size; i++ {\n\t\tA.Set(i, i, 1)\n\t}\n\n\treturn A\n}\n\n\/\/ Constructs a new matrix with random values in range [0;1)\nfunc Rand(rows, cols int) *Matrix {\n\tA := Zeros(rows, cols)\n\n\tfor i := range A.values {\n\t\tA.values[i] = rand.Float64()\n\t}\n\n\treturn A\n}\n\n\/\/ Constructs a new Matrix from a Matlab style representation\nfunc FromMatlab(str string) *Matrix {\n\trows := strings.Split(str, \";\")\n\n\tfor i, row := range rows {\n\t\trows[i] = strings.Replace(row, \",\", \" \", -1)\n\t}\n\n\tnRows := len(rows)\n\tnColumns := len(strings.Fields(rows[0]))\n\n\tA := Zeros(nRows, nColumns)\n\n\tfor i, row := range rows {\n\t\trow = strings.Trim(row, \"[] \")\n\t\tstrNums := strings.Fields(row)\n\n\t\tfor j, num := range strNums {\n\t\t\tn, _ := strconv.ParseFloat(num, 64)\n\t\t\tA.Set(i+1, j+1, n)\n\t\t}\n\t}\n\n\treturn A\n}\n\n\/\/ Return a Matlab representation of the matrix\nfunc (A *Matrix) ToMatlab() string {\n\tbuffer := new(bytes.Buffer)\n\tbuffer.WriteString(\"[\")\n\n\tfor i, v := range A.values {\n\t\tbuffer.WriteString(fmt.Sprintf(\"%f \", v))\n\n\t\tif (i+1)%A.cols == 0 {\n\t\t\tbuffer.WriteString(\"; \")\n\t\t}\n\t}\n\n\tbuffer.WriteString(\"]\")\n\n\treturn buffer.String()\n}\n\n\/\/ Gives the dimensions of the matrix\nfunc (A *Matrix) Dim() (int, int) {\n\treturn A.rows, A.cols\n}\n\n\/\/ Return the number of rows in the matrix\nfunc (A *Matrix) Rows() int {\n\treturn A.rows\n}\n\n\/\/ Return the number of columns in the matrix\nfunc (A *Matrix) Columns() int {\n\treturn A.cols\n}\n\n\/\/ Returns an array of all the values\nfunc (A *Matrix) Values() []float64 {\n\ttmp := make([]float64, len(A.values))\n\tcopy(tmp, A.values)\n\treturn tmp\n}\n\n\/\/ Returns an exact copy of the matrix\nfunc (A *Matrix) Copy() *Matrix {\n\tB := Zeros(A.rows, A.cols)\n\tcopy(B.values, A.values)\n\n\treturn B\n}\n\nfunc (A *Matrix) Apply(f ApplyFunc) *Matrix {\n\tfor i, v := range A.values {\n\t\tA.values[i] = f(i, v)\n\t}\n\n\treturn A\n}\n\n\/\/ Returns a string representation of the matrix\nfunc (A *Matrix) String() string {\n\tbuffer := new(bytes.Buffer)\n\n\tfor i, elem := range A.values {\n\t\tbuffer.WriteString(fmt.Sprintf(\"%.3f \", elem))\n\n\t\tif (i+1)%A.cols == 0 {\n\t\t\tbuffer.WriteString(\"\\n\")\n\t\t}\n\t}\n\n\treturn buffer.String()\n}\n\n\/\/ Retrieve value at [row, col]\nfunc (A *Matrix) Get(row, col int) (float64, error) {\n\n\tif A.isOutOfBounds(row, col) {\n\t\treturn 0, ErrOutOfBounds\n\t}\n\n\treturn A.values[(row-1)*A.cols+col-1], nil\n}\n\n\/\/ Set the element at [row, col] to val\nfunc (A *Matrix) Set(row, col int, val float64) error {\n\n\tif A.isOutOfBounds(row, col) {\n\t\treturn ErrOutOfBounds\n\t}\n\n\tA.values[(row-1)*A.cols+col-1] = val\n\n\treturn nil\n}\n\n\/\/ Transpose the matrix (in-place, costly)\nfunc (A *Matrix) Transpose() *Matrix {\n\tB := Zeros(A.cols, A.rows)\n\n\tfor i := 1; i <= A.rows; i++ {\n\t\tfor j := 1; j <= A.cols; j++ {\n\t\t\tv, _ := A.Get(i, j)\n\t\t\tB.Set(j, i, v)\n\t\t}\n\t}\n\n\tA.rows, A.cols = A.cols, A.rows\n\tcopy(A.values, B.values)\n\treturn A\n}\n\n\/\/ Add B to the matrix A (in-place)\nfunc (A *Matrix) Add(B *Matrix) (*Matrix, error) {\n\tif !sameSize(A, B) {\n\t\treturn nil, ErrIncompatibleSizes\n\t}\n\n\tfor i, val := range B.values {\n\t\tA.values[i] += val\n\t}\n\n\treturn A, nil\n}\n\n\/\/ Subtract B from the matrix A (in-place)\nfunc (A *Matrix) Sub(B *Matrix) (*Matrix, error) {\n\tif !sameSize(A, B) {\n\t\treturn nil, ErrIncompatibleSizes\n\t}\n\n\tfor i, val := range B.values {\n\t\tA.values[i] -= val\n\t}\n\n\treturn A, nil\n}\n\n\/\/ Multiply 2 matricies with each other returning a new matrix\nfunc (A *Matrix) Mul(B *Matrix) (*Matrix, error) {\n\tif !columnIsRow(A, B) {\n\t\treturn nil, ErrIncompatibleSizes\n\t}\n\n\tC := Zeros(A.rows, B.cols)\n\n\tfor i := 0; i < C.rows; i++ {\n\t\tfor j := 0; j < C.cols; j++ {\n\t\t\tsum := float64(0)\n\n\t\t\tfor k := 0; k < A.cols; k++ {\n\t\t\t\tsum += A.values[i*A.cols+k] * B.values[k*B.cols+j]\n\t\t\t}\n\n\t\t\tC.values[i*C.rows+j] = sum\n\t\t}\n\t}\n\n\treturn C, nil\n}\n\n\/\/ Standard scalar product of 2 matricies\nfunc (A *Matrix) Dot(B *Matrix) (*Matrix, error) {\n\tif !sameSize(A, B) {\n\t\treturn nil, ErrIncompatibleSizes\n\t}\n\n\tfor i, v := range B.values {\n\t\tA.values[i] *= v\n\t}\n\treturn A, nil\n}\n\n\/\/ Scale the matrix in-place by the factor f\nfunc (A *Matrix) Scale(f float64) *Matrix {\n\tfor i := range A.values {\n\t\tA.values[i] *= f\n\t}\n\n\treturn A\n}\n\n\/\/ Take every element of the matrix to the power of n (in-place)\nfunc (A *Matrix) Power(n float64) *Matrix {\n\tfor i, elem := range A.values {\n\t\tA.values[i] = math.Pow(elem, n)\n\t}\n\n\treturn A\n}\n\n\/\/ Add n to all elements in the matrix (in-place)\nfunc (A *Matrix) AddNum(n float64) *Matrix {\n\tfor i := range A.values {\n\t\tA.values[i] += n\n\t}\n\n\treturn A\n}\n\nfunc (A *Matrix) isOutOfBounds(row, col int) bool {\n\tindex := (row-1)*A.cols + col - 1\n\n\tif index >= len(A.values) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc sameSize(A, B *Matrix) bool {\n\treturn A.rows == B.rows && A.cols == B.cols\n}\n\nfunc columnIsRow(A, B *Matrix) bool {\n\treturn A.cols == B.rows\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The Knative Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage resources\n\nimport (\n\t\"context\"\n\t\"crypto\/rand\"\n\t\"crypto\/rsa\"\n\t\"crypto\/x509\"\n\t\"crypto\/x509\/pkix\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"math\/big\"\n\t\"time\"\n\n\t\"go.uber.org\/zap\"\n\n\t\"knative.dev\/pkg\/logging\"\n)\n\nconst (\n\torganization = \"knative.dev\"\n)\n\n\/\/ Create the common parts of the cert. These don't change between\n\/\/ the root\/CA cert and the server cert.\nfunc createCertTemplate(name, namespace string, notAfter time.Time) (*x509.Certificate, error) {\n\tserialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)\n\tserialNumber, err := rand.Int(rand.Reader, serialNumberLimit)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to generate serial number: \" + err.Error())\n\t}\n\n\tserviceName := name + \".\" + namespace\n\tcommonName := serviceName + \".svc\"\n\tserviceNames := []string{\n\t\tname,\n\t\tserviceName,\n\t\tcommonName,\n\t\tserviceName + \".svc.cluster.local\",\n\t}\n\n\ttmpl := x509.Certificate{\n\t\tSerialNumber: serialNumber,\n\t\tSubject: pkix.Name{\n\t\t\tOrganization: []string{organization},\n\t\t\tCommonName:   commonName,\n\t\t},\n\t\tSignatureAlgorithm:    x509.SHA256WithRSA,\n\t\tNotBefore:             time.Now(),\n\t\tNotAfter:              notAfter,\n\t\tBasicConstraintsValid: true,\n\t\tDNSNames:              serviceNames,\n\t}\n\treturn &tmpl, nil\n}\n\n\/\/ Create cert template suitable for CA and hence signing\nfunc createCACertTemplate(name, namespace string, notAfter time.Time) (*x509.Certificate, error) {\n\trootCert, err := createCertTemplate(name, namespace, notAfter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Make it into a CA cert and change it so we can use it to sign certs\n\trootCert.IsCA = true\n\trootCert.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature\n\trootCert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}\n\treturn rootCert, nil\n}\n\n\/\/ Create cert template that we can use on the server for TLS\nfunc createServerCertTemplate(name, namespace string, notAfter time.Time) (*x509.Certificate, error) {\n\tserverCert, err := createCertTemplate(name, namespace, notAfter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserverCert.KeyUsage = x509.KeyUsageDigitalSignature\n\tserverCert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}\n\treturn serverCert, err\n}\n\n\/\/ Actually sign the cert and return things in a form that we can use later on\nfunc createCert(template, parent *x509.Certificate, pub, parentPriv interface{}) (\n\tcert *x509.Certificate, certPEM []byte, err error) {\n\n\tcertDER, err := x509.CreateCertificate(rand.Reader, template, parent, pub, parentPriv)\n\tif err != nil {\n\t\treturn\n\t}\n\tcert, err = x509.ParseCertificate(certDER)\n\tif err != nil {\n\t\treturn\n\t}\n\tb := pem.Block{Type: \"CERTIFICATE\", Bytes: certDER}\n\tcertPEM = pem.EncodeToMemory(&b)\n\treturn\n}\n\nfunc createCA(ctx context.Context, name, namespace string, notAfter time.Time) (*rsa.PrivateKey, *x509.Certificate, []byte, error) {\n\tlogger := logging.FromContext(ctx)\n\trootKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\tlogger.Errorw(\"error generating random key\", zap.Error(err))\n\t\treturn nil, nil, nil, err\n\t}\n\n\trootCertTmpl, err := createCACertTemplate(name, namespace, notAfter)\n\tif err != nil {\n\t\tlogger.Errorw(\"error generating CA cert\", zap.Error(err))\n\t\treturn nil, nil, nil, err\n\t}\n\n\trootCert, rootCertPEM, err := createCert(rootCertTmpl, rootCertTmpl, &rootKey.PublicKey, rootKey)\n\tif err != nil {\n\t\tlogger.Errorw(\"error signing the CA cert\", zap.Error(err))\n\t\treturn nil, nil, nil, err\n\t}\n\treturn rootKey, rootCert, rootCertPEM, nil\n}\n\n\/\/ CreateCerts creates and returns a CA certificate and certificate and\n\/\/ key for the server. serverKey and serverCert are used by the server\n\/\/ to establish trust for clients, CA certificate is used by the\n\/\/ client to verify the server authentication chain. notAfter specifies\n\/\/ the expiration date.\nfunc CreateCerts(ctx context.Context, name, namespace string, notAfter time.Time) (serverKey, serverCert, caCert []byte, err error) {\n\tlogger := logging.FromContext(ctx)\n\t\/\/ First create a CA certificate and private key\n\tcaKey, caCertificate, caCertificatePEM, err := createCA(ctx, name, namespace, notAfter)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t\/\/ Then create the private key for the serving cert\n\tservKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\tlogger.Errorw(\"error generating random key\", zap.Error(err))\n\t\treturn nil, nil, nil, err\n\t}\n\tservCertTemplate, err := createServerCertTemplate(name, namespace, notAfter)\n\tif err != nil {\n\t\tlogger.Errorw(\"failed to create the server certificate template\", zap.Error(err))\n\t\treturn nil, nil, nil, err\n\t}\n\n\t\/\/ create a certificate which wraps the server's public key, sign it with the CA private key\n\t_, servCertPEM, err := createCert(servCertTemplate, caCertificate, &servKey.PublicKey, caKey)\n\tif err != nil {\n\t\tlogger.Errorw(\"error signing server certificate template\", zap.Error(err))\n\t\treturn nil, nil, nil, err\n\t}\n\tservKeyPEM := pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\", Bytes: x509.MarshalPKCS1PrivateKey(servKey),\n\t})\n\treturn servKeyPEM, servCertPEM, caCertificatePEM, nil\n}\n<commit_msg>feat: get cluster domain use utility (#1795)<commit_after>\/*\nCopyright 2019 The Knative Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage resources\n\nimport (\n\t\"context\"\n\t\"crypto\/rand\"\n\t\"crypto\/rsa\"\n\t\"crypto\/x509\"\n\t\"crypto\/x509\/pkix\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"math\/big\"\n\t\"time\"\n\n\t\"go.uber.org\/zap\"\n\n\t\"knative.dev\/pkg\/logging\"\n\t\"knative.dev\/pkg\/network\"\n)\n\nconst (\n\torganization = \"knative.dev\"\n)\n\n\/\/ Create the common parts of the cert. These don't change between\n\/\/ the root\/CA cert and the server cert.\nfunc createCertTemplate(name, namespace string, notAfter time.Time) (*x509.Certificate, error) {\n\tserialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)\n\tserialNumber, err := rand.Int(rand.Reader, serialNumberLimit)\n\tif err != nil {\n\t\treturn nil, errors.New(\"failed to generate serial number: \" + err.Error())\n\t}\n\n\tserviceName := name + \".\" + namespace\n\tcommonName := serviceName + \".svc\"\n\tserviceHostname := network.GetServiceHostname(name, namespace)\n\tserviceNames := []string{\n\t\tname,\n\t\tserviceName,\n\t\tcommonName,\n\t\tserviceHostname,\n\t}\n\n\ttmpl := x509.Certificate{\n\t\tSerialNumber: serialNumber,\n\t\tSubject: pkix.Name{\n\t\t\tOrganization: []string{organization},\n\t\t\tCommonName:   commonName,\n\t\t},\n\t\tSignatureAlgorithm:    x509.SHA256WithRSA,\n\t\tNotBefore:             time.Now(),\n\t\tNotAfter:              notAfter,\n\t\tBasicConstraintsValid: true,\n\t\tDNSNames:              serviceNames,\n\t}\n\treturn &tmpl, nil\n}\n\n\/\/ Create cert template suitable for CA and hence signing\nfunc createCACertTemplate(name, namespace string, notAfter time.Time) (*x509.Certificate, error) {\n\trootCert, err := createCertTemplate(name, namespace, notAfter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Make it into a CA cert and change it so we can use it to sign certs\n\trootCert.IsCA = true\n\trootCert.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature\n\trootCert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}\n\treturn rootCert, nil\n}\n\n\/\/ Create cert template that we can use on the server for TLS\nfunc createServerCertTemplate(name, namespace string, notAfter time.Time) (*x509.Certificate, error) {\n\tserverCert, err := createCertTemplate(name, namespace, notAfter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserverCert.KeyUsage = x509.KeyUsageDigitalSignature\n\tserverCert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}\n\treturn serverCert, err\n}\n\n\/\/ Actually sign the cert and return things in a form that we can use later on\nfunc createCert(template, parent *x509.Certificate, pub, parentPriv interface{}) (\n\tcert *x509.Certificate, certPEM []byte, err error) {\n\n\tcertDER, err := x509.CreateCertificate(rand.Reader, template, parent, pub, parentPriv)\n\tif err != nil {\n\t\treturn\n\t}\n\tcert, err = x509.ParseCertificate(certDER)\n\tif err != nil {\n\t\treturn\n\t}\n\tb := pem.Block{Type: \"CERTIFICATE\", Bytes: certDER}\n\tcertPEM = pem.EncodeToMemory(&b)\n\treturn\n}\n\nfunc createCA(ctx context.Context, name, namespace string, notAfter time.Time) (*rsa.PrivateKey, *x509.Certificate, []byte, error) {\n\tlogger := logging.FromContext(ctx)\n\trootKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\tlogger.Errorw(\"error generating random key\", zap.Error(err))\n\t\treturn nil, nil, nil, err\n\t}\n\n\trootCertTmpl, err := createCACertTemplate(name, namespace, notAfter)\n\tif err != nil {\n\t\tlogger.Errorw(\"error generating CA cert\", zap.Error(err))\n\t\treturn nil, nil, nil, err\n\t}\n\n\trootCert, rootCertPEM, err := createCert(rootCertTmpl, rootCertTmpl, &rootKey.PublicKey, rootKey)\n\tif err != nil {\n\t\tlogger.Errorw(\"error signing the CA cert\", zap.Error(err))\n\t\treturn nil, nil, nil, err\n\t}\n\treturn rootKey, rootCert, rootCertPEM, nil\n}\n\n\/\/ CreateCerts creates and returns a CA certificate and certificate and\n\/\/ key for the server. serverKey and serverCert are used by the server\n\/\/ to establish trust for clients, CA certificate is used by the\n\/\/ client to verify the server authentication chain. notAfter specifies\n\/\/ the expiration date.\nfunc CreateCerts(ctx context.Context, name, namespace string, notAfter time.Time) (serverKey, serverCert, caCert []byte, err error) {\n\tlogger := logging.FromContext(ctx)\n\t\/\/ First create a CA certificate and private key\n\tcaKey, caCertificate, caCertificatePEM, err := createCA(ctx, name, namespace, notAfter)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\t\/\/ Then create the private key for the serving cert\n\tservKey, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\tlogger.Errorw(\"error generating random key\", zap.Error(err))\n\t\treturn nil, nil, nil, err\n\t}\n\tservCertTemplate, err := createServerCertTemplate(name, namespace, notAfter)\n\tif err != nil {\n\t\tlogger.Errorw(\"failed to create the server certificate template\", zap.Error(err))\n\t\treturn nil, nil, nil, err\n\t}\n\n\t\/\/ create a certificate which wraps the server's public key, sign it with the CA private key\n\t_, servCertPEM, err := createCert(servCertTemplate, caCertificate, &servKey.PublicKey, caKey)\n\tif err != nil {\n\t\tlogger.Errorw(\"error signing server certificate template\", zap.Error(err))\n\t\treturn nil, nil, nil, err\n\t}\n\tservKeyPEM := pem.EncodeToMemory(&pem.Block{\n\t\tType: \"RSA PRIVATE KEY\", Bytes: x509.MarshalPKCS1PrivateKey(servKey),\n\t})\n\treturn servKeyPEM, servCertPEM, caCertificatePEM, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\ntype ErrorResponse struct {\n\tError string `json:\"error\"`\n}\n\ntype VolumeResponse struct {\n\tUUID string\n\tBase string\n\tSize int64\n}\n\ntype SnapshotResponse struct {\n\tUUID       string\n\tVolumeUUID string\n}\n\ntype BlockStoreResponse struct {\n\tUUID      string\n\tKind      string\n\tBlockSize int64\n}\n\nfunc ResponseError(format string, a ...interface{}) {\n\tresponse := ErrorResponse{Error: fmt.Sprintf(format, a...)}\n\tj, err := json.MarshalIndent(&response, \"\", \"\\t\")\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to generate response for error:\", err))\n\t}\n\tfmt.Println(string(j[:]))\n}\n\nfunc ResponseLogAndError(format string, a ...interface{}) {\n\tlog.Errorf(format, a...)\n\tResponseError(format, a...)\n}\n\nfunc ResponseOutput(v interface{}) {\n\tj, err := json.MarshalIndent(v, \"\", \"\\t\")\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to generate response for error:\", err))\n\t}\n\tfmt.Println(string(j[:]))\n}\n<commit_msg>Remove unnecessary json tag<commit_after>package api\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\ntype ErrorResponse struct {\n\tError string\n}\n\ntype VolumeResponse struct {\n\tUUID string\n\tBase string\n\tSize int64\n}\n\ntype SnapshotResponse struct {\n\tUUID       string\n\tVolumeUUID string\n}\n\ntype BlockStoreResponse struct {\n\tUUID      string\n\tKind      string\n\tBlockSize int64\n}\n\nfunc ResponseError(format string, a ...interface{}) {\n\tresponse := ErrorResponse{Error: fmt.Sprintf(format, a...)}\n\tj, err := json.MarshalIndent(&response, \"\", \"\\t\")\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to generate response for error:\", err))\n\t}\n\tfmt.Println(string(j[:]))\n}\n\nfunc ResponseLogAndError(format string, a ...interface{}) {\n\tlog.Errorf(format, a...)\n\tResponseError(format, a...)\n}\n\nfunc ResponseOutput(v interface{}) {\n\tj, err := json.MarshalIndent(v, \"\", \"\\t\")\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to generate response for error:\", err))\n\t}\n\tfmt.Println(string(j[:]))\n}\n<|endoftext|>"}
{"text":"<commit_before>package apis\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"strings\"\n\n\t\"github.com\/ghchinoy\/atmotool\/cm\"\n\t\"github.com\/ghchinoy\/atmotool\/control\"\n)\n\nconst (\n\t\/\/ APIGetInfo is the endpoint to get info about an API\n\tAPIGetInfo = \"\/api\/apis\/%s\"\n\t\/\/ APIGetInfoIncludeDefault is the endpoint to get info about an API and its default version\n\tAPIGetInfoIncludeDefault = \"\/api\/apis\/%s?includeDefaultVersion=true\"\n\t\/\/ APIGetInfoIncludeDefaultAndSettings retrieves info about the API, its default version, and settings\n\tAPIGetInfoIncludeDefaultAndSettings = \"\/api\/apis\/%s?IncludeDefaultVersion=true&IncludeSettings=true\"\n\t\/\/ APIGetVersionInfo is the endpoint pattern for getting information about a version, defaulting endpoint enclusion\n\tAPIGetVersionInfo = \"\/api\/apis\/versions\/%s?IncludeEndpoints=true\"\n\t\/\/ APIVersionImplementations is the endpoint for getting implementation info\n\tAPIVersionImplementations = \"\/api\/apis\/versions\/implementations\"\n\t\/\/ APISettings is the endpoint to retrieve only the API's settings, ref. http:\/\/docs.akana.com\/cm\/api\/apis\/m_apis_getAPISettings.htm\n\tAPISettings = \"\/api\/apis\/%s\/settings\"\n)\n\n\/\/ ShowDetailsforAPIID outputs API details\nfunc ShowDetailsforAPIID(apiID string, useVersion bool, config control.Configuration, debug bool) error {\n\tclient, _, err := control.LoginToCM(config, debug)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t\treturn err\n\t}\n\n\tvar pattern string\n\tif useVersion {\n\t\tpattern = APIGetVersionInfo\n\t} else {\n\t\tpattern = APIGetInfoIncludeDefault\n\t}\n\n\turl := config.URL + fmt.Sprintf(pattern, apiID)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Add(\"Accept\", \"application\/json\")\n\tif debug {\n\t\tlog.Println(\"Calling\", url)\n\t\tcontrol.DebugRequestHeader(req)\n\t}\n\tresp, err := client.Do(req)\n\tdefer resp.Body.Close()\n\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif debug {\n\t\tcontrol.DebugResponseHeader(resp)\n\t}\n\tvar apiInfo cm.ApisResponse\n\terr = json.Unmarshal(bodyBytes, &apiInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode == 500 {\n\t\tvar message string\n\t\tif strings.Contains(apiInfo.FaultMessage, \"[apiversion]\") {\n\t\t\tmessage = \"Please provide an API ID. An API ID was expected; instead, an API Version ID was provided.\\nPlease use the --ver flag.\"\n\t\t}\n\t\tif strings.Contains(apiInfo.FaultMessage, \"[api]\") {\n\t\t\tmessage = \"Please provide an API Version ID. An API Version ID was expected; instead, an API ID was provided.\\nPlease remove the --ver flag.\"\n\t\t}\n\t\tif debug {\n\t\t\tfmt.Printf(\"%s : %s\\n\", resp.Status, apiInfo.FaultMessage)\n\t\t}\n\t\treturn errors.New(message)\n\t}\n\tif useVersion {\n\t\tvar api cm.APIVersion\n\t\terr = json.Unmarshal(bodyBytes, &api)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toutputAPIVersion(api)\n\t} else {\n\t\tvar api cm.APIDetails\n\t\terr = json.Unmarshal(bodyBytes, &api)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toutputAPI(api)\n\t}\n\t\/\/fmt.Printf(\"%s: %s\\n\", resp.Status, bodyBytes)\n\treturn nil\n}\n\nfunc outputAPIVersion(api cm.APIVersion) {\n\n\tfmt.Printf(\"API: %s (%s)\\n\", api.Description, api.APIID)\n\tfmt.Printf(\"Version: %s (%s)\\n\", api.Name, api.APIVersionID)\n\tfor _, v := range api.Endpoints.Endpoint {\n\t\tvar visibility string\n\t\tfor _, t := range v.ConnectionProperties {\n\t\t\tif t.Name == \"visibility\" {\n\t\t\t\tvisibility = t.Value\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"%s (%s): %s\\n\", v.ImplementationCode, visibility, v.URI)\n\t}\n}\n\nfunc outputAPI(api cm.APIDetails) {\n\n\tfmt.Printf(\"API: %s (%s)\", api.Description, api.APIID)\n\tfmt.Printf(\"Latest version ID: %s\", api.LatestVersionID)\n}\n<commit_msg>output \\n's<commit_after>package apis\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"strings\"\n\n\t\"github.com\/ghchinoy\/atmotool\/cm\"\n\t\"github.com\/ghchinoy\/atmotool\/control\"\n)\n\nconst (\n\t\/\/ APIGetInfo is the endpoint to get info about an API\n\tAPIGetInfo = \"\/api\/apis\/%s\"\n\t\/\/ APIGetInfoIncludeDefault is the endpoint to get info about an API and its default version\n\tAPIGetInfoIncludeDefault = \"\/api\/apis\/%s?includeDefaultVersion=true\"\n\t\/\/ APIGetInfoIncludeDefaultAndSettings retrieves info about the API, its default version, and settings\n\tAPIGetInfoIncludeDefaultAndSettings = \"\/api\/apis\/%s?IncludeDefaultVersion=true&IncludeSettings=true\"\n\t\/\/ APIGetVersionInfo is the endpoint pattern for getting information about a version, defaulting endpoint enclusion\n\tAPIGetVersionInfo = \"\/api\/apis\/versions\/%s?IncludeEndpoints=true\"\n\t\/\/ APIVersionImplementations is the endpoint for getting implementation info\n\tAPIVersionImplementations = \"\/api\/apis\/versions\/implementations\"\n\t\/\/ APISettings is the endpoint to retrieve only the API's settings, ref. http:\/\/docs.akana.com\/cm\/api\/apis\/m_apis_getAPISettings.htm\n\tAPISettings = \"\/api\/apis\/%s\/settings\"\n)\n\n\/\/ ShowDetailsforAPIID outputs API details\nfunc ShowDetailsforAPIID(apiID string, useVersion bool, config control.Configuration, debug bool) error {\n\tclient, _, err := control.LoginToCM(config, debug)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t\treturn err\n\t}\n\n\tvar pattern string\n\tif useVersion {\n\t\tpattern = APIGetVersionInfo\n\t} else {\n\t\tpattern = APIGetInfoIncludeDefault\n\t}\n\n\turl := config.URL + fmt.Sprintf(pattern, apiID)\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Add(\"Accept\", \"application\/json\")\n\tif debug {\n\t\tlog.Println(\"Calling\", url)\n\t\tcontrol.DebugRequestHeader(req)\n\t}\n\tresp, err := client.Do(req)\n\tdefer resp.Body.Close()\n\tbodyBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif debug {\n\t\tcontrol.DebugResponseHeader(resp)\n\t}\n\tvar apiInfo cm.ApisResponse\n\terr = json.Unmarshal(bodyBytes, &apiInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode == 500 {\n\t\tvar message string\n\t\tif strings.Contains(apiInfo.FaultMessage, \"[apiversion]\") {\n\t\t\tmessage = \"Please provide an API ID. An API ID was expected; instead, an API Version ID was provided.\\nPlease use the --ver flag.\"\n\t\t}\n\t\tif strings.Contains(apiInfo.FaultMessage, \"[api]\") {\n\t\t\tmessage = \"Please provide an API Version ID. An API Version ID was expected; instead, an API ID was provided.\\nPlease remove the --ver flag.\"\n\t\t}\n\t\tif debug {\n\t\t\tfmt.Printf(\"%s : %s\\n\", resp.Status, apiInfo.FaultMessage)\n\t\t}\n\t\treturn errors.New(message)\n\t}\n\tif useVersion {\n\t\tvar api cm.APIVersion\n\t\terr = json.Unmarshal(bodyBytes, &api)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toutputAPIVersion(api)\n\t} else {\n\t\tvar api cm.APIDetails\n\t\terr = json.Unmarshal(bodyBytes, &api)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toutputAPI(api)\n\t}\n\t\/\/fmt.Printf(\"%s: %s\\n\", resp.Status, bodyBytes)\n\treturn nil\n}\n\nfunc outputAPIVersion(api cm.APIVersion) {\n\n\tfmt.Printf(\"API: %s (%s)\\n\", api.Description, api.APIID)\n\tfmt.Printf(\"Version: %s (%s)\\n\", api.Name, api.APIVersionID)\n\tfor _, v := range api.Endpoints.Endpoint {\n\t\tvar visibility string\n\t\tfor _, t := range v.ConnectionProperties {\n\t\t\tif t.Name == \"visibility\" {\n\t\t\t\tvisibility = t.Value\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"%s (%s): %s\\n\", v.ImplementationCode, visibility, v.URI)\n\t}\n}\n\nfunc outputAPI(api cm.APIDetails) {\n\n\tfmt.Printf(\"API: %s (%s)\\n\", api.Description, api.APIID)\n\tfmt.Printf(\"Latest version ID: %s\\n\", api.LatestVersionID)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013-2017 The btcsuite developers\n\/\/ Copyright (c) 2015-2016 The Decred developers\n\/\/ Heavily inspired by https:\/\/github.com\/btcsuite\/btcd\/blob\/master\/version.go\n\/\/ Copyright (C) 2015-2017 The Lightning Network Developers\n\npackage build\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\/\/ Commit stores the current commit hash of this build, this should be set using\n\/\/ the -ldflags during compilation.\nvar Commit string\n\n\/\/ semanticAlphabet\nconst semanticAlphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\"\n\n\/\/ These constants define the application version and follow the semantic\n\/\/ versioning 2.0.0 spec (http:\/\/semver.org\/).\nconst (\n\tappMajor uint = 0\n\tappMinor uint = 6\n\tappPatch uint = 1\n\n\t\/\/ appPreRelease MUST only contain characters from semanticAlphabet\n\t\/\/ per the semantic versioning spec.\n\tappPreRelease = \"beta\"\n)\n\n\/\/ Version returns the application version as a properly formed string per the\n\/\/ semantic versioning 2.0.0 spec (http:\/\/semver.org\/).\nfunc Version() string {\n\t\/\/ Start with the major, minor, and patch versions.\n\tversion := fmt.Sprintf(\"%d.%d.%d\", appMajor, appMinor, appPatch)\n\n\t\/\/ Append pre-release version if there is one.  The hyphen called for\n\t\/\/ by the semantic versioning spec is automatically appended and should\n\t\/\/ not be contained in the pre-release string.  The pre-release version\n\t\/\/ is not appended if it contains invalid characters.\n\tpreRelease := normalizeVerString(appPreRelease)\n\tif preRelease != \"\" {\n\t\tversion = fmt.Sprintf(\"%s-%s\", version, preRelease)\n\t}\n\n\t\/\/ Append commit hash of current build to version.\n\tversion = fmt.Sprintf(\"%s commit=%s\", version, Commit)\n\n\treturn version\n}\n\n\/\/ normalizeVerString returns the passed string stripped of all characters which\n\/\/ are not valid according to the semantic versioning guidelines for pre-release\n\/\/ version and build metadata strings.  In particular they MUST only contain\n\/\/ characters in semanticAlphabet.\nfunc normalizeVerString(str string) string {\n\tvar result bytes.Buffer\n\tfor _, r := range str {\n\t\tif strings.ContainsRune(semanticAlphabet, r) {\n\t\t\tresult.WriteRune(r)\n\t\t}\n\t}\n\treturn result.String()\n}\n<commit_msg>lnd: bump version to 0.7<commit_after>\/\/ Copyright (c) 2013-2017 The btcsuite developers\n\/\/ Copyright (c) 2015-2016 The Decred developers\n\/\/ Heavily inspired by https:\/\/github.com\/btcsuite\/btcd\/blob\/master\/version.go\n\/\/ Copyright (C) 2015-2017 The Lightning Network Developers\n\npackage build\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\/\/ Commit stores the current commit hash of this build, this should be set using\n\/\/ the -ldflags during compilation.\nvar Commit string\n\n\/\/ semanticAlphabet\nconst semanticAlphabet = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-\"\n\n\/\/ These constants define the application version and follow the semantic\n\/\/ versioning 2.0.0 spec (http:\/\/semver.org\/).\nconst (\n\tappMajor uint = 0\n\tappMinor uint = 7\n\tappPatch uint = 0\n\n\t\/\/ appPreRelease MUST only contain characters from semanticAlphabet\n\t\/\/ per the semantic versioning spec.\n\tappPreRelease = \"beta\"\n)\n\n\/\/ Version returns the application version as a properly formed string per the\n\/\/ semantic versioning 2.0.0 spec (http:\/\/semver.org\/).\nfunc Version() string {\n\t\/\/ Start with the major, minor, and patch versions.\n\tversion := fmt.Sprintf(\"%d.%d.%d\", appMajor, appMinor, appPatch)\n\n\t\/\/ Append pre-release version if there is one.  The hyphen called for\n\t\/\/ by the semantic versioning spec is automatically appended and should\n\t\/\/ not be contained in the pre-release string.  The pre-release version\n\t\/\/ is not appended if it contains invalid characters.\n\tpreRelease := normalizeVerString(appPreRelease)\n\tif preRelease != \"\" {\n\t\tversion = fmt.Sprintf(\"%s-%s\", version, preRelease)\n\t}\n\n\t\/\/ Append commit hash of current build to version.\n\tversion = fmt.Sprintf(\"%s commit=%s\", version, Commit)\n\n\treturn version\n}\n\n\/\/ normalizeVerString returns the passed string stripped of all characters which\n\/\/ are not valid according to the semantic versioning guidelines for pre-release\n\/\/ version and build metadata strings.  In particular they MUST only contain\n\/\/ characters in semanticAlphabet.\nfunc normalizeVerString(str string) string {\n\tvar result bytes.Buffer\n\tfor _, r := range str {\n\t\tif strings.ContainsRune(semanticAlphabet, r) {\n\t\t\tresult.WriteRune(r)\n\t\t}\n\t}\n\treturn result.String()\n}\n<|endoftext|>"}
{"text":"<commit_before>package hmm\n\nimport (\n\t\"code.google.com\/p\/biogo.matrix\"\n\t\"github.com\/akualab\/gjoa\/model\"\n\t\"github.com\/akualab\/gjoa\/model\/gaussian\"\n\t\/\/\"math\"\n\t\"testing\"\n)\n\n\/\/ Tests\n\n\/*\n   DISCUSSION:\n   If you look at the sample data and model params. I manufactured the\n   data as if it was emitted with the following sequence:\n\n   t:  0   1   2   3   4   5   6   7   8   9   10  11\n   q:  s0  s0  s0  s0  s0  s0  s1  s1  s1  s1  s0  s0\n   o:  0.1 0.3 1.1 1.2 0.7 0.7 5.5 7.8 10  5.2 1.1 1.3 <=\n   data I created given the Gaussians [1,1] and [4,4]\n\n   I got the following gamma:\n\n   γ0: -0.03 -0.03 -0.05 -0.05 -0.04 -0.11 -9.02 -21 -36 -7.8 -0.15 -0.11\n   γ1: -3.35 -3.41 -3.01 -2.92 -3.13 -2.24 -0.00 -0  -0  -0   -1.91 -2.21\n\n   As you can see choosing the gamma with highest prob for each state give\n   us the hidden sequence of states.\n\n   gamma gives you the most likely state at time t. In this case the result is what we expect.\n\n   Viterbi gives you the P(q | O,  model), that is, it maximizes of over the whole sequence.\n*\/\n\n\/\/ Test ColumnAt() function.\nfunc TestColumnAt(t *testing.T) {\n\n\tmat, e := matrix.NewDense([][]float64{\n\t\t{10, 11, 12, 13}, {20, 21, 22, 23}, {30, 31, 32, 33}})\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\tcol := ColumnAt(mat, 1)\n\n\tt.Logf(\"col: \\n%+v\", col)\n\n\tfor i, expected := range []float64{11.0, 21.0, 31.0} {\n\t\tv := col.At(i, 0)\n\t\tif !model.Comparef64(expected, v) {\n\t\t\tt.Errorf(\"Wrong value. Expected: [%f], Got: [%f]\", expected, v)\n\t\t}\n\t}\n}\n\nfunc MakeNewDenseMatrix(t *testing.T, m [][]float64) *matrix.Dense {\n\tmm, emm := matrix.NewDense(m)\n\tif emm != nil {\n\t\tt.Fatal(emm)\n\t}\n\treturn mm\n}\n\nfunc MakeHMM(t *testing.T) *HMM {\n\n\t\/\/ Gaussian 1.\n\tmean1 := MakeNewDenseMatrix(t, [][]float64{{1}})\n\tvar1 := MakeNewDenseMatrix(t, [][]float64{{1}})\n\tg1, eg1 := gaussian.NewGaussian(1, mean1, var1, true, true, \"g1\")\n\tif eg1 != nil {\n\t\tt.Fatal(eg1)\n\t}\n\t\/\/ Gaussian 2.\n\tmean2 := MakeNewDenseMatrix(t, [][]float64{{4}})\n\tvar2 := MakeNewDenseMatrix(t, [][]float64{{4}})\n\tvar2, ev2 := matrix.NewDense([][]float64{{4}})\n\tif ev2 != nil {\n\t\tt.Fatal(ev2)\n\t}\n\tg2, eg2 := gaussian.NewGaussian(1, mean2, var2, true, true, \"g2\")\n\tif eg2 != nil {\n\t\tt.Fatal(eg2)\n\t}\n\n\tinitialStateProbs := MakeNewDenseMatrix(t, [][]float64{{0.8}, {0.2}})\n\n\ttransProbs := MakeNewDenseMatrix(t, [][]float64{{0.9, 0.1}, {0.3, 0.7}})\n\n\t\/\/ These are the models.\n\tmodels := []*gaussian.Gaussian{g1, g2}\n\n\t\/\/ To pass the to an HMM we need to convert []*gaussian.Gaussian[]\n\t\/\/ to []model.Modeler\n\t\/\/ see http:\/\/golang.org\/doc\/faq#convert_slice_of_interface\n\tm := make([]model.Modeler, len(models))\n\tfor i, v := range models {\n\t\tm[i] = v\n\t}\n\thmm, e := NewHMM(transProbs, initialStateProbs, m)\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\treturn hmm\n}\n\nvar (\n\tobs0 = [][]float64{\n\t\t{0.1, 0.3, 1.1, 1.2, 0.7, 0.7, 5.5, 7.8, 10.0, 5.2, 1.1, 1.3}}\n\talpha0 = []float64{\n\t\t-1.54708208451888,\n\t\t-2.80709238811418,\n\t\t-3.83134003758912,\n\t\t-4.86850442594034,\n\t\t-5.92973730403429,\n\t\t-6.99328952650412,\n\t\t-18.1370692144982,\n\t\t-36.3195887463382,\n\t\t-57.4758051059185,\n\t\t-32.2645657649804,\n\t\t-25.5978716740632,\n\t\t-26.5391830081456}\n\talpha1 = []float64{\n\t\t-5.12277362619872,\n\t\t-6.99404330419337,\n\t\t-7.67194890763762,\n\t\t-8.58593275227677,\n\t\t-9.98735773434079,\n\t\t-11.0914094981902,\n\t\t-11.0792560557189,\n\t\t-14.8528937698143,\n\t\t-21.3216544274498,\n\t\t-23.4704150851531,\n\t\t-26.4904040834703,\n\t\t-29.0712307616184}\n\tbeta0 = []float64{\n\t\t-24.9258011954291,\n\t\t-23.661415171904,\n\t\t-22.6397641116887,\n\t\t-21.6045197079498,\n\t\t-20.549461075003,\n\t\t-19.579339900188,\n\t\t-17.3294657178329,\n\t\t-13.5557050615525,\n\t\t-7.07931720879328,\n\t\t-2.06607429111337,\n\t\t-1.04620524392834,\n\t\t0}\n\tbeta1 = []float64{\n\t\t-25.9309053603105,\n\t\t-24.6182012641994,\n\t\t-23.5726285099546,\n\t\t-22.4540945910146,\n\t\t-20.5873818254665,\n\t\t-17.6335597285231,\n\t\t-15.3835555701327,\n\t\t-11.6097949124971,\n\t\t-5.14103425479379,\n\t\t-2.99265648819389,\n\t\t-1.76872378444132,\n\t\t0}\n)\n\nfunc CompareSliceFloat(t *testing.T, expected []float64, actual *matrix.Dense, row int, message string) {\n\tfor i, _ := range expected {\n\t\tif !model.Comparef64(expected[i], actual.At(row, i)) {\n\t\t\tt.Errorf(\"[%s]. Expected: [%f], Got: [%f]\",\n\t\t\t\tmessage, expected[i], actual.At(i, 0))\n\t\t}\n\t}\n}\n\nfunc TestEvaluationAlpha(t *testing.T) {\n\n\thmm := MakeHMM(t)\n\tobs, eobs := matrix.NewDense(obs0)\n\tif eobs != nil {\n\t\tt.Fatal(eobs)\n\t}\n\talpha, logProb, err_alpha := hmm.alpha(obs)\n\tif err_alpha != nil {\n\t\tt.Fatal(err_alpha)\n\t}\n\tt.Logf(\"logProb:\\n%+v\\n\", logProb)\n\tmessage := \"Error in alpha\"\n\tCompareSliceFloat(t, alpha0, alpha, 0, message)\n\tCompareSliceFloat(t, alpha1, alpha, 1, message)\n}\n\nfunc TestEvaluationBeta(t *testing.T) {\n\n\thmm := MakeHMM(t)\n\tobs := MakeNewDenseMatrix(t, obs0)\n\tbeta, err_beta := hmm.beta(obs)\n\tif err_beta != nil {\n\t\tt.Fatal(err_beta)\n\t}\n\tmessage := \"Error in beta\"\n\tCompareSliceFloat(t, beta0, beta, 0, message)\n\tCompareSliceFloat(t, beta1, beta, 1, message)\n}\n\nfunc TestEvaluationGamma(t *testing.T) {\n\n\thmm := MakeHMM(t)\n\tobs := MakeNewDenseMatrix(t, obs0)\n\talpha, _, err_alpha := hmm.alpha(obs)\n\tif err_alpha != nil {\n\t\tt.Fatal(err_alpha)\n\t}\n\tbeta, err_beta := hmm.beta(obs)\n\tif err_beta != nil {\n\t\tt.Fatal(err_beta)\n\t}\n\tgamma, err_gamma := hmm.gamma(alpha, beta)\n\tif err_gamma != nil {\n\t\tt.Fatal(err_gamma)\n\t}\n\tt.Logf(\"gamma:\\n%+v\\n\", gamma)\n}\n\n\/*\nfunc TestEvaluationXi(t *testing.T) {\n\tobs := MakeNewDenseMatrix(t, obs0)\n\txi, err_xi := hmm.xi(obs, alpha, beta)\n\tif err_xi != nil {\n\t\tt.Fatal(err_xi)\n\t}\n\tt.Logf(\"xi:\\n%+v\\n\", xi)\n}*\/\n<commit_msg>Tested Gamma.<commit_after>package hmm\n\nimport (\n\t\"code.google.com\/p\/biogo.matrix\"\n\t\"github.com\/akualab\/gjoa\/model\"\n\t\"github.com\/akualab\/gjoa\/model\/gaussian\"\n\t\/\/\"math\"\n\t\"testing\"\n)\n\n\/\/ Tests\n\n\/*\n   DISCUSSION:\n   If you look at the sample data and model params. I manufactured the\n   data as if it was emitted with the following sequence:\n\n   t:  0   1   2   3   4   5   6   7   8   9   10  11\n   q:  s0  s0  s0  s0  s0  s0  s1  s1  s1  s1  s0  s0\n   o:  0.1 0.3 1.1 1.2 0.7 0.7 5.5 7.8 10  5.2 1.1 1.3 <=\n   data I created given the Gaussians [1,1] and [4,4]\n\n   I got the following gamma:\n\n   γ0: -0.03 -0.03 -0.05 -0.05 -0.04 -0.11 -9.02 -21 -36 -7.8 -0.15 -0.11\n   γ1: -3.35 -3.41 -3.01 -2.92 -3.13 -2.24 -0.00 -0  -0  -0   -1.91 -2.21\n\n   As you can see choosing the gamma with highest prob for each state give\n   us the hidden sequence of states.\n\n   gamma gives you the most likely state at time t. In this case the result is what we expect.\n\n   Viterbi gives you the P(q | O,  model), that is, it maximizes of over the whole sequence.\n*\/\n\n\/\/ Test ColumnAt() function.\nfunc TestColumnAt(t *testing.T) {\n\n\tmat, e := matrix.NewDense([][]float64{\n\t\t{10, 11, 12, 13}, {20, 21, 22, 23}, {30, 31, 32, 33}})\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\n\tcol := ColumnAt(mat, 1)\n\n\tt.Logf(\"col: \\n%+v\", col)\n\n\tfor i, expected := range []float64{11.0, 21.0, 31.0} {\n\t\tv := col.At(i, 0)\n\t\tif !model.Comparef64(expected, v) {\n\t\t\tt.Errorf(\"Wrong value. Expected: [%f], Got: [%f]\", expected, v)\n\t\t}\n\t}\n}\n\nfunc MakeNewDenseMatrix(t *testing.T, m [][]float64) *matrix.Dense {\n\tmm, emm := matrix.NewDense(m)\n\tif emm != nil {\n\t\tt.Fatal(emm)\n\t}\n\treturn mm\n}\n\nfunc MakeHMM(t *testing.T) *HMM {\n\n\t\/\/ Gaussian 1.\n\tmean1 := MakeNewDenseMatrix(t, [][]float64{{1}})\n\tvar1 := MakeNewDenseMatrix(t, [][]float64{{1}})\n\tg1, eg1 := gaussian.NewGaussian(1, mean1, var1, true, true, \"g1\")\n\tif eg1 != nil {\n\t\tt.Fatal(eg1)\n\t}\n\t\/\/ Gaussian 2.\n\tmean2 := MakeNewDenseMatrix(t, [][]float64{{4}})\n\tvar2 := MakeNewDenseMatrix(t, [][]float64{{4}})\n\tvar2, ev2 := matrix.NewDense([][]float64{{4}})\n\tif ev2 != nil {\n\t\tt.Fatal(ev2)\n\t}\n\tg2, eg2 := gaussian.NewGaussian(1, mean2, var2, true, true, \"g2\")\n\tif eg2 != nil {\n\t\tt.Fatal(eg2)\n\t}\n\n\tinitialStateProbs := MakeNewDenseMatrix(t, [][]float64{{0.8}, {0.2}})\n\n\ttransProbs := MakeNewDenseMatrix(t, [][]float64{{0.9, 0.1}, {0.3, 0.7}})\n\n\t\/\/ These are the models.\n\tmodels := []*gaussian.Gaussian{g1, g2}\n\n\t\/\/ To pass the to an HMM we need to convert []*gaussian.Gaussian[]\n\t\/\/ to []model.Modeler\n\t\/\/ see http:\/\/golang.org\/doc\/faq#convert_slice_of_interface\n\tm := make([]model.Modeler, len(models))\n\tfor i, v := range models {\n\t\tm[i] = v\n\t}\n\thmm, e := NewHMM(transProbs, initialStateProbs, m)\n\tif e != nil {\n\t\tt.Fatal(e)\n\t}\n\treturn hmm\n}\n\nvar (\n\tobs0 = [][]float64{\n\t\t{0.1, 0.3, 1.1, 1.2, 0.7, 0.7, 5.5, 7.8, 10.0, 5.2, 1.1, 1.3}}\n\talpha0 = []float64{\n\t\t-1.54708208451888,\n\t\t-2.80709238811418,\n\t\t-3.83134003758912,\n\t\t-4.86850442594034,\n\t\t-5.92973730403429,\n\t\t-6.99328952650412,\n\t\t-18.1370692144982,\n\t\t-36.3195887463382,\n\t\t-57.4758051059185,\n\t\t-32.2645657649804,\n\t\t-25.5978716740632,\n\t\t-26.5391830081456}\n\talpha1 = []float64{\n\t\t-5.12277362619872,\n\t\t-6.99404330419337,\n\t\t-7.67194890763762,\n\t\t-8.58593275227677,\n\t\t-9.98735773434079,\n\t\t-11.0914094981902,\n\t\t-11.0792560557189,\n\t\t-14.8528937698143,\n\t\t-21.3216544274498,\n\t\t-23.4704150851531,\n\t\t-26.4904040834703,\n\t\t-29.0712307616184}\n\tbeta0 = []float64{\n\t\t-24.9258011954291,\n\t\t-23.661415171904,\n\t\t-22.6397641116887,\n\t\t-21.6045197079498,\n\t\t-20.549461075003,\n\t\t-19.579339900188,\n\t\t-17.3294657178329,\n\t\t-13.5557050615525,\n\t\t-7.07931720879328,\n\t\t-2.06607429111337,\n\t\t-1.04620524392834,\n\t\t0}\n\tbeta1 = []float64{\n\t\t-25.9309053603105,\n\t\t-24.6182012641994,\n\t\t-23.5726285099546,\n\t\t-22.4540945910146,\n\t\t-20.5873818254665,\n\t\t-17.6335597285231,\n\t\t-15.3835555701327,\n\t\t-11.6097949124971,\n\t\t-5.14103425479379,\n\t\t-2.99265648819389,\n\t\t-1.76872378444132,\n\t\t0}\n\tgamma0 = []float64{\n\t\t-0.0101945977044363,\n\t\t-0.00581887777458709,\n\t\t-0.00841546703429051,\n\t\t-0.0103354516465726,\n\t\t-0.0165096967936958,\n\t\t-0.10994074444856,\n\t\t-9.00384625008746,\n\t\t-23.4126051256471,\n\t\t-38.0924336324682,\n\t\t-7.86795137385019,\n\t\t-0.181388235747997,\n\t\t-0.076494325902054}\n\tgamma1 = []float64{\n\t\t-4.59099030426571,\n\t\t-5.14955588614921,\n\t\t-4.78188873534866,\n\t\t-4.5773386610478,\n\t\t-4.11205087756371,\n\t\t-2.2622805444697,\n\t\t-0.000122943608043396,\n\t\t-6.79257761172257e-11,\n\t\t0,\n\t\t-0.000382891103450269,\n\t\t-1.79643918566812,\n\t\t-2.60854207937483}\n)\n\nfunc CompareSliceFloat(t *testing.T, expected []float64, actual *matrix.Dense, row int, message string) {\n\tfor i, _ := range expected {\n\t\tif !model.Comparef64(expected[i], actual.At(row, i)) {\n\t\t\tt.Errorf(\"[%s]. Expected: [%f], Got: [%f]\",\n\t\t\t\tmessage, expected[i], actual.At(i, 0))\n\t\t}\n\t}\n}\n\nfunc CompareFloats(t *testing.T, expected float64, actual float64, message string) {\n\tif !model.Comparef64(expected, actual) {\n\t\tt.Errorf(\"[%s]. Expected: [%f], Got: [%f]\",\n\t\t\tmessage, expected, actual)\n\t}\n}\n\nfunc TestEvaluationAlpha(t *testing.T) {\n\n\thmm := MakeHMM(t)\n\tobs := MakeNewDenseMatrix(t, obs0)\n\talpha, logProb, err_alpha := hmm.alpha(obs)\n\tif err_alpha != nil {\n\t\tt.Fatal(err_alpha)\n\t}\n\texpectedLogProb := -26.4626886822436\n\tCompareFloats(t, expectedLogProb, logProb, \"Error in logProb\")\n\tmessage := \"Error in alpha\"\n\tCompareSliceFloat(t, alpha0, alpha, 0, message)\n\tCompareSliceFloat(t, alpha1, alpha, 1, message)\n}\n\nfunc TestEvaluationBeta(t *testing.T) {\n\n\thmm := MakeHMM(t)\n\tobs := MakeNewDenseMatrix(t, obs0)\n\tbeta, err_beta := hmm.beta(obs)\n\tif err_beta != nil {\n\t\tt.Fatal(err_beta)\n\t}\n\tmessage := \"Error in beta\"\n\tCompareSliceFloat(t, beta0, beta, 0, message)\n\tCompareSliceFloat(t, beta1, beta, 1, message)\n}\n\nfunc TestEvaluationGamma(t *testing.T) {\n\n\thmm := MakeHMM(t)\n\tobs := MakeNewDenseMatrix(t, obs0)\n\talpha, _, err_alpha := hmm.alpha(obs)\n\tif err_alpha != nil {\n\t\tt.Fatal(err_alpha)\n\t}\n\tbeta, err_beta := hmm.beta(obs)\n\tif err_beta != nil {\n\t\tt.Fatal(err_beta)\n\t}\n\tgamma, err_gamma := hmm.gamma(alpha, beta)\n\tif err_gamma != nil {\n\t\tt.Fatal(err_gamma)\n\t}\n\tmessage := \"Error in gamma\"\n\tCompareSliceFloat(t, gamma0, gamma, 0, message)\n\tCompareSliceFloat(t, gamma1, gamma, 1, message)\n}\n\n\/*\nfunc TestEvaluationXi(t *testing.T) {\n\tobs := MakeNewDenseMatrix(t, obs0)\n\txi, err_xi := hmm.xi(obs, alpha, beta)\n\tif err_xi != nil {\n\t\tt.Fatal(err_xi)\n\t}\n\tt.Logf(\"xi:\\n%+v\\n\", xi)\n}*\/\n<|endoftext|>"}
{"text":"<commit_before>package uploads\n\nimport (\n\t\"github.com\/materials-commons\/mcstore\/pkg\/app\"\n\tdmocks \"github.com\/materials-commons\/mcstore\/pkg\/db\/dai\/mocks\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/db\/schema\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"FinishRequest\", func() {\n\tvar (\n\t\tfiles *dmocks.Files\n\t\tdirs  *dmocks.Dirs\n\t\tf     *finisher\n\t)\n\n\tBeforeEach(func() {\n\t\tfiles = dmocks.NewMFiles()\n\t\tdirs = dmocks.NewMDirs()\n\t\tf = &finisher{\n\t\t\tfiles: files,\n\t\t\tdirs:  dirs,\n\t\t}\n\t})\n\n\tDescribe(\"parentID method tests\", func() {\n\t\tIt(\"Should return a parent when there is one\", func() {\n\t\t\tparentFile := &schema.File{\n\t\t\t\tID: \"parent\",\n\t\t\t}\n\t\t\tfiles.On(\"ByPath\", \"file.name\", \"dir\").Return(parentFile, nil)\n\t\t\tparentID, err := f.parentID(\"file.name\", \"dir\")\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(parentID).To(Equal(\"parent\"))\n\t\t})\n\n\t\tIt(\"Should not return a parent when there isn't one\", func() {\n\t\t\tvar nilFile *schema.File = nil\n\t\t\tfiles.On(\"ByPath\", \"file.name\", \"dir\").Return(nilFile, app.ErrNotFound)\n\t\t\tparentID, err := f.parentID(\"file.name\", \"dir\")\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(parentID).To(Equal(\"\"))\n\t\t})\n\n\t\tIt(\"Should return an error when ByPath returns an error other than app.ErrNotFound\", func() {\n\t\t\tvar nilFile *schema.File = nil\n\t\t\tfiles.On(\"ByPath\", \"file.name\", \"dir\").Return(nilFile, app.ErrInvalid)\n\t\t\tparentID, err := f.parentID(\"file.name\", \"dir\")\n\t\t\tExpect(err).To(Equal(app.ErrInvalid))\n\t\t\tExpect(parentID).To(Equal(\"\"))\n\t\t})\n\t})\n\n\tDescribe(\"fileInDir method tests\", func() {\n\t\tIt(\"Should return false if the file isn't in the directory\", func() {\n\t\t\tvar noFiles []schema.File\n\t\t\tdirs.On(\"Files\", \"dir\").Return(noFiles, app.ErrNotFound)\n\t\t\tExpect(f.fileInDir(\"checksum\", \"file.name\", \"dir\")).To(BeFalse())\n\t\t})\n\n\t\tIt(\"Should return false if there is a matching file with a different checksum\", func() {\n\t\t\tmatchingFile := schema.File{\n\t\t\t\tName:     \"file.name\",\n\t\t\t\tChecksum: \"wrongchecksum\",\n\t\t\t}\n\t\t\tvar matching []schema.File = []schema.File{matchingFile}\n\t\t\tdirs.On(\"Files\", \"dir\").Return(matching, nil)\n\t\t\tExpect(f.fileInDir(\"abc123\", \"file.name\", \"dir\")).To(BeFalse())\n\t\t})\n\n\t\tIt(\"Should return true if the file with exact checksum is in the directory\", func() {\n\t\t\tmatchingFile := schema.File{\n\t\t\t\tName:     \"file.name\",\n\t\t\t\tChecksum: \"abc123\",\n\t\t\t}\n\t\t\tvar matching []schema.File = []schema.File{matchingFile}\n\t\t\tdirs.On(\"Files\", \"dir\").Return(matching, nil)\n\t\t\tExpect(f.fileInDir(\"abc123\", \"file.name\", \"dir\")).To(BeTrue())\n\t\t})\n\t})\n\n\tDescribe(\"finish method tests\", func() {\n\t})\n})\n<commit_msg>Add more mock services.<commit_after>package uploads\n\nimport (\n\t\"github.com\/materials-commons\/gohandy\/file\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/app\"\n\tdmocks \"github.com\/materials-commons\/mcstore\/pkg\/db\/dai\/mocks\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/db\/schema\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"FinishRequest\", func() {\n\tvar (\n\t\tfiles  *dmocks.Files\n\t\tdirs   *dmocks.Dirs\n\t\tfiles2 *dmocks.Files2\n\t\tf      *finisher\n\t)\n\n\tBeforeEach(func() {\n\t\tfiles = dmocks.NewMFiles()\n\t\tdirs = dmocks.NewMDirs()\n\t\tfiles2 = dmocks.NewMFiles2()\n\t\tf = &finisher{\n\t\t\tfiles: files,\n\t\t\tdirs:  dirs,\n\t\t\tfops:  file.MockOps,\n\t\t}\n\t})\n\n\tDescribe(\"parentID method tests\", func() {\n\t\tIt(\"Should return a parent when there is one\", func() {\n\t\t\tparentFile := &schema.File{\n\t\t\t\tID: \"parent\",\n\t\t\t}\n\t\t\tfiles.On(\"ByPath\", \"file.name\", \"dir\").Return(parentFile, nil)\n\t\t\tparentID, err := f.parentID(\"file.name\", \"dir\")\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(parentID).To(Equal(\"parent\"))\n\t\t})\n\n\t\tIt(\"Should not return a parent when there isn't one\", func() {\n\t\t\tvar nilFile *schema.File = nil\n\t\t\tfiles.On(\"ByPath\", \"file.name\", \"dir\").Return(nilFile, app.ErrNotFound)\n\t\t\tparentID, err := f.parentID(\"file.name\", \"dir\")\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(parentID).To(Equal(\"\"))\n\t\t})\n\n\t\tIt(\"Should return an error when ByPath returns an error other than app.ErrNotFound\", func() {\n\t\t\tvar nilFile *schema.File = nil\n\t\t\tfiles.On(\"ByPath\", \"file.name\", \"dir\").Return(nilFile, app.ErrInvalid)\n\t\t\tparentID, err := f.parentID(\"file.name\", \"dir\")\n\t\t\tExpect(err).To(Equal(app.ErrInvalid))\n\t\t\tExpect(parentID).To(Equal(\"\"))\n\t\t})\n\t})\n\n\tDescribe(\"fileInDir method tests\", func() {\n\t\tIt(\"Should return false if the file isn't in the directory\", func() {\n\t\t\tvar noFiles []schema.File\n\t\t\tdirs.On(\"Files\", \"dir\").Return(noFiles, app.ErrNotFound)\n\t\t\tExpect(f.fileInDir(\"checksum\", \"file.name\", \"dir\")).To(BeFalse())\n\t\t})\n\n\t\tIt(\"Should return false if there is a matching file with a different checksum\", func() {\n\t\t\tmatchingFile := schema.File{\n\t\t\t\tName:     \"file.name\",\n\t\t\t\tChecksum: \"wrongchecksum\",\n\t\t\t}\n\t\t\tvar matching []schema.File = []schema.File{matchingFile}\n\t\t\tdirs.On(\"Files\", \"dir\").Return(matching, nil)\n\t\t\tExpect(f.fileInDir(\"abc123\", \"file.name\", \"dir\")).To(BeFalse())\n\t\t})\n\n\t\tIt(\"Should return true if the file with exact checksum is in the directory\", func() {\n\t\t\tmatchingFile := schema.File{\n\t\t\t\tName:     \"file.name\",\n\t\t\t\tChecksum: \"abc123\",\n\t\t\t}\n\t\t\tvar matching []schema.File = []schema.File{matchingFile}\n\t\t\tdirs.On(\"Files\", \"dir\").Return(matching, nil)\n\t\t\tExpect(f.fileInDir(\"abc123\", \"file.name\", \"dir\")).To(BeTrue())\n\t\t})\n\t})\n\n\tDescribe(\"finish method tests\", func() {\n\n\t\tIt(\"Should fail if the size is wrong.\", func() {\n\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package upload\n\nimport (\n\t\"github.com\/emicklei\/go-restful\"\n\t\"github.com\/inconshreveable\/log15\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/app\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/app\/flow\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/db\/schema\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/ws\/rest\"\n\t\"github.com\/materials-commons\/mcstore\/server\/mcstored\/service\/uploads\"\n)\n\n\/\/ An uploadResource handles all upload requests.\ntype uploadResource struct {\n\tuploader      *uploader\n\tlog           log15.Logger\n\tfactory       AssemblerFactory\n\tcreateService uploads.CreateService\n}\n\n\/\/ NewResources creates a new upload resource\nfunc NewResource(uploader *uploader, factory AssemblerFactory) rest.Service {\n\treturn &uploadResource{\n\t\tuploader:      uploader,\n\t\tlog:           app.NewLog(\"resource\", \"upload\"),\n\t\tfactory:       factory,\n\t\tcreateService: uploads.NewCreateService(),\n\t}\n}\n\n\/\/ WebService creates an instance of the upload web service.\nfunc (r *uploadResource) WebService() *restful.WebService {\n\tws := new(restful.WebService)\n\n\tws.Path(\"\/upload\").Produces(restful.MIME_JSON)\n\tws.Route(ws.POST(\"\").To(rest.RouteHandler(r.createUploadRequest)).\n\t\tDoc(\"Creates a new upload request\").\n\t\tReads(uploadCreateRequest{}).\n\t\tWrites(uploadCreateResponse{}))\n\tws.Route(ws.POST(\"\/chunk\").To(rest.RouteHandler1(r.uploadFileChunk)).\n\t\tConsumes(\"multipart\/form-data\").\n\t\tDoc(\"Upload a file chunk\"))\n\n\treturn ws\n}\n\n\/\/ uploadFileChunk uploads a new file chunk.\nfunc (r *uploadResource) uploadFileChunk(request *restful.Request, response *restful.Response, user schema.User) error {\n\tflowRequest, err := form2FlowRequest(request)\n\tif err != nil {\n\t\tr.log.Error(app.Logf(\"Error converting form to flow.Request: %s\", err))\n\t\treturn err\n\t}\n\n\tif err := r.uploader.processRequest(flowRequest); err != nil {\n\t\treturn err\n\t}\n\n\tif r.uploader.allBlocksUploaded(flowRequest) {\n\t\tgo r.assembler(flowRequest)\n\t}\n\n\treturn nil\n}\n\n\/\/ assembler builds a new Assembler to assemble the pieces of the file.\nfunc (r *uploadResource) assembler(request *flow.Request) {\n\tif assembler := r.factory.Assembler(request); assembler != nil {\n\t\tassembler.Assemble()\n\t}\n}\n<commit_msg>Change service to also consume JSON. Make the createService a parameter rather than creating it.<commit_after>package upload\n\nimport (\n\t\"github.com\/emicklei\/go-restful\"\n\t\"github.com\/inconshreveable\/log15\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/app\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/app\/flow\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/db\/schema\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/ws\/rest\"\n\t\"github.com\/materials-commons\/mcstore\/server\/mcstored\/service\/uploads\"\n)\n\n\/\/ An uploadResource handles all upload requests.\ntype uploadResource struct {\n\tuploader      *uploader\n\tlog           log15.Logger\n\tfactory       AssemblerFactory\n\tcreateService uploads.CreateService\n}\n\n\/\/ NewResources creates a new upload resource\nfunc NewResource(uploader *uploader, factory AssemblerFactory, createService uploads.CreateService) rest.Service {\n\treturn &uploadResource{\n\t\tuploader:      uploader,\n\t\tlog:           app.NewLog(\"resource\", \"upload\"),\n\t\tfactory:       factory,\n\t\tcreateService: createService,\n\t}\n}\n\n\/\/ WebService creates an instance of the upload web service.\nfunc (r *uploadResource) WebService() *restful.WebService {\n\tws := new(restful.WebService)\n\n\tws.Path(\"\/upload\").Produces(restful.MIME_JSON).Consumes(restful.MIME_JSON)\n\tws.Route(ws.POST(\"\").To(rest.RouteHandler(r.createUploadRequest)).\n\t\tDoc(\"Creates a new upload request\").\n\t\tReads(uploadCreateRequest{}).\n\t\tWrites(uploadCreateResponse{}))\n\tws.Route(ws.POST(\"\/chunk\").To(rest.RouteHandler1(r.uploadFileChunk)).\n\t\tConsumes(\"multipart\/form-data\").\n\t\tDoc(\"Upload a file chunk\"))\n\n\treturn ws\n}\n\n\/\/ uploadFileChunk uploads a new file chunk.\nfunc (r *uploadResource) uploadFileChunk(request *restful.Request, response *restful.Response, user schema.User) error {\n\tflowRequest, err := form2FlowRequest(request)\n\tif err != nil {\n\t\tr.log.Error(app.Logf(\"Error converting form to flow.Request: %s\", err))\n\t\treturn err\n\t}\n\n\tif err := r.uploader.processRequest(flowRequest); err != nil {\n\t\treturn err\n\t}\n\n\tif r.uploader.allBlocksUploaded(flowRequest) {\n\t\tgo r.assembler(flowRequest)\n\t}\n\n\treturn nil\n}\n\n\/\/ assembler builds a new Assembler to assemble the pieces of the file.\nfunc (r *uploadResource) assembler(request *flow.Request) {\n\tif assembler := r.factory.Assembler(request); assembler != nil {\n\t\tassembler.Assemble()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package tai64\n\nimport (\n\t\"fmt\"\n\t\"syscall\"\n\t\"time\"\n)\n\ntype Tai struct {\n\tx uint64\n}\n\ntype Taia struct {\n\tsec  Tai\n\tnano uint64\n\tatto uint64\n}\n\nconst TAICONST = 4611686018427387914\nconst Tai_Count = 8\nconst Taia_Count = 16\n\nfunc Tai_now() Tai {\n\tvar result Tai\n\tresult.x = TAICONST + uint64(time.Now().Unix())\n\treturn result\n}\n\nfunc Taia_now() Taia {\n\tvar result Taia\n\tnow := new(syscall.Timeval)\n\terr := syscall.Gettimeofday(now)\n\tif err == nil {\n\t\tvar t Tai\n\t\tt.x = TAICONST + uint64(now.Sec)\n\t\tresult.sec = t\n\t\tresult.nano = uint64(1000*uint64(now.Usec) + 500)\n\t\tresult.atto = 0\n\t} else {\n\t\tfmt.Println(err)\n\t}\n\treturn result\n}\n\nfunc Tai_pack(t Tai) []byte {\n\tresult := make([]byte, Tai_Count)\n\tx := t.x\n\tresult[7] = byte(x & 255)\n\tx >>= 8\n\tresult[6] = byte(x & 255)\n\tx >>= 8\n\tresult[5] = byte(x & 255)\n\tx >>= 8\n\tresult[4] = byte(x & 255)\n\tx >>= 8\n\tresult[3] = byte(x & 255)\n\tx >>= 8\n\tresult[2] = byte(x & 255)\n\tx >>= 8\n\tresult[1] = byte(x & 255)\n\tx >>= 8\n\tresult[0] = byte(x)\n\treturn result\n\n}\n\nfunc Tai_unpack(s []byte) Tai {\n\tvar result Tai\n\tvar x uint64\n\tx = uint64(s[0])\n\tx <<= 8\n\tx += uint64(s[1])\n\tx <<= 8\n\tx += uint64(s[2])\n\tx <<= 8\n\tx += uint64(s[3])\n\tx <<= 8\n\tx += uint64(s[4])\n\tx <<= 8\n\tx += uint64(s[5])\n\tx <<= 8\n\tx += uint64(s[6])\n\tx <<= 8\n\tx += uint64(s[7])\n\tresult.x = x\n\treturn result\n}\n\nfunc Taia_pack(t Taia) []byte {\n\tresult := make([]byte, Taia_Count)\n\tzz := make([]byte, Tai_Count)\n\tzz = Tai_pack(t.sec)\n\tfor i := 0; i < Tai_Count; i++ {\n\t\tresult[i+Tai_Count] = zz[i]\n\t}\n\tx := t.atto\n\tresult[7] = byte(x & 255)\n\tx >>= 8\n\tresult[6] = byte(x & 255)\n\tx >>= 8\n\tresult[5] = byte(x & 255)\n\tx >>= 8\n\tresult[4] = byte(x)\n\n\tx = t.nano\n\tresult[3] = byte(x & 255)\n\tx >>= 8\n\tresult[2] = byte(x & 255)\n\tx >>= 8\n\tresult[1] = byte(x & 255)\n\tx >>= 8\n\tresult[0] = byte(x)\n\n\treturn result\n}\n\nfunc Taia_unpack(s []byte) Taia {\n\tvar result Taia\n\tvar zz Tai\n\tzz = Tai_unpack(s[8:])\n\tresult.sec = zz\n\tx := uint64(s[4])\n\tx <<= 8\n\tx += uint64(s[5])\n\tx <<= 8\n\tx += uint64(s[6])\n\tx <<= 8\n\tx += uint64(s[7])\n\tresult.atto = x\n\tx = uint64(s[0])\n\tx <<= 8\n\tx += uint64(s[1])\n\tx <<= 8\n\tx += uint64(s[2])\n\tx <<= 8\n\tx += uint64(s[3])\n\tresult.nano = x\n\treturn result\n\n}\n<commit_msg>gtclock: partially obeyed golint<commit_after>package tai64\n\nimport (\n\t\"fmt\"\n\t\"syscall\"\n\t\"time\"\n)\n\ntype Tai struct {\n\tx uint64\n}\n\ntype Taia struct {\n\tsec  Tai\n\tnano uint64\n\tatto uint64\n}\n\nconst TAICONST = 4611686018427387914\nconst TaiCount = 8\nconst TaiaCount = 16\n\nfunc TaiNow() Tai {\n\tvar result Tai\n\tresult.x = TAICONST + uint64(time.Now().Unix())\n\treturn result\n}\n\nfunc TaiaNow() Taia {\n\tvar result Taia\n\tnow := new(syscall.Timeval)\n\terr := syscall.Gettimeofday(now)\n\tif err == nil {\n\t\tvar t Tai\n\t\tt.x = TAICONST + uint64(now.Sec)\n\t\tresult.sec = t\n\t\tresult.nano = uint64(1000*uint64(now.Usec) + 500)\n\t\tresult.atto = 0\n\t} else {\n\t\tfmt.Println(err)\n\t}\n\treturn result\n}\n\nfunc TaiPack(t Tai) []byte {\n\tresult := make([]byte, TaiCount)\n\tx := t.x\n\tresult[7] = byte(x & 255)\n\tx >>= 8\n\tresult[6] = byte(x & 255)\n\tx >>= 8\n\tresult[5] = byte(x & 255)\n\tx >>= 8\n\tresult[4] = byte(x & 255)\n\tx >>= 8\n\tresult[3] = byte(x & 255)\n\tx >>= 8\n\tresult[2] = byte(x & 255)\n\tx >>= 8\n\tresult[1] = byte(x & 255)\n\tx >>= 8\n\tresult[0] = byte(x)\n\treturn result\n\n}\n\nfunc TaiUnpack(s []byte) Tai {\n\tvar result Tai\n\tvar x uint64\n\tx = uint64(s[0])\n\tx <<= 8\n\tx += uint64(s[1])\n\tx <<= 8\n\tx += uint64(s[2])\n\tx <<= 8\n\tx += uint64(s[3])\n\tx <<= 8\n\tx += uint64(s[4])\n\tx <<= 8\n\tx += uint64(s[5])\n\tx <<= 8\n\tx += uint64(s[6])\n\tx <<= 8\n\tx += uint64(s[7])\n\tresult.x = x\n\treturn result\n}\n\nfunc TaiaPack(t Taia) []byte {\n\tresult := make([]byte, TaiaCount)\n\tzz := make([]byte, TaiCount)\n\tzz = TaiPack(t.sec)\n\tfor i := 0; i < TaiCount; i++ {\n\t\tresult[i+TaiCount] = zz[i]\n\t}\n\tx := t.atto\n\tresult[7] = byte(x & 255)\n\tx >>= 8\n\tresult[6] = byte(x & 255)\n\tx >>= 8\n\tresult[5] = byte(x & 255)\n\tx >>= 8\n\tresult[4] = byte(x)\n\n\tx = t.nano\n\tresult[3] = byte(x & 255)\n\tx >>= 8\n\tresult[2] = byte(x & 255)\n\tx >>= 8\n\tresult[1] = byte(x & 255)\n\tx >>= 8\n\tresult[0] = byte(x)\n\n\treturn result\n}\n\nfunc TaiaUnpack(s []byte) Taia {\n\tvar result Taia\n\tvar zz Tai\n\tzz = TaiUnpack(s[8:])\n\tresult.sec = zz\n\tx := uint64(s[4])\n\tx <<= 8\n\tx += uint64(s[5])\n\tx <<= 8\n\tx += uint64(s[6])\n\tx <<= 8\n\tx += uint64(s[7])\n\tresult.atto = x\n\tx = uint64(s[0])\n\tx <<= 8\n\tx += uint64(s[1])\n\tx <<= 8\n\tx += uint64(s[2])\n\tx <<= 8\n\tx += uint64(s[3])\n\tresult.nano = x\n\treturn result\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ runoutput\n\n\/\/ Copyright 2011 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Generate test of channel operations and simple selects.\n\/\/ The output of this program is compiled and run to do the\n\/\/ actual test.\n\n\/\/ Each test does only one real send or receive at a time, but phrased\n\/\/ in various ways that the compiler may or may not rewrite\n\/\/ into simpler expressions.\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"text\/template\"\n)\n\nfunc main() {\n\tout := bufio.NewWriter(os.Stdout)\n\tfmt.Fprintln(out, header)\n\ta := new(arg)\n\n\t\/\/ Generate each kind of test as a separate function to avoid\n\t\/\/ hitting the 6g optimizer with one enormous function.\n\t\/\/ If we name all the functions init we don't have to\n\t\/\/ maintain a list of which ones to run.\n\tdo := func(t *template.Template) {\n\t\tfmt.Fprintln(out, `func init() {`)\n\t\tfor ; next(); a.reset() {\n\t\t\trun(t, a, out)\n\t\t}\n\t\tfmt.Fprintln(out, `}`)\n\t}\n\n\tdo(recv)\n\tdo(send)\n\tdo(recvOrder)\n\tdo(sendOrder)\n\tdo(nonblock)\n\n\tfmt.Fprintln(out, \"\/\/\", a.nreset, \"cases\")\n\tout.Flush()\n}\n\nfunc run(t *template.Template, a interface{}, out io.Writer) {\n\tif err := t.Execute(out, a); err != nil {\n\t\tpanic(err)\n\t}\n}\n\ntype arg struct {\n\tdef    bool\n\tnreset int\n}\n\nfunc (a *arg) Maybe() bool {\n\treturn maybe()\n}\n\nfunc (a *arg) MaybeDefault() bool {\n\tif a.def {\n\t\treturn false\n\t}\n\ta.def = maybe()\n\treturn a.def\n}\n\nfunc (a *arg) MustDefault() bool {\n\treturn !a.def\n}\n\nfunc (a *arg) reset() {\n\ta.def = false\n\ta.nreset++\n}\n\nconst header = `\/\/ GENERATED BY select5.go; DO NOT EDIT\n\npackage main\n\n\/\/ channel is buffered so test is single-goroutine.\n\/\/ we are not interested in the concurrency aspects\n\/\/ of select, just testing that the right calls happen.\nvar c = make(chan int, 1)\nvar nilch chan int\nvar n = 1\nvar x int\nvar i interface{}\nvar dummy = make(chan int)\nvar m = make(map[int]int)\nvar order = 0\n\nfunc f(p *int) *int {\n\treturn p\n}\n\n\/\/ check order of operations by ensuring that\n\/\/ successive calls to checkorder have increasing o values.\nfunc checkorder(o int) {\n\tif o <= order {\n\t\tprintln(\"invalid order\", o, \"after\", order)\n\t\tpanic(\"order\")\n\t}\n\torder = o\n}\n\nfunc fc(c chan int, o int) chan int {\n\tcheckorder(o)\n\treturn c\n}\n\nfunc fp(p *int, o int) *int {\n\tcheckorder(o)\n\treturn p\n}\n\nfunc fn(n, o int) int {\n\tcheckorder(o)\n\treturn n\n}\n\nfunc die(x int) {\n\tprintln(\"have\", x, \"want\", n)\n\tpanic(\"chan\")\n}\n\nfunc main() {\n\t\/\/ everything happens in init funcs\n}\n`\n\nfunc parse(name, s string) *template.Template {\n\tt, err := template.New(name).Parse(s)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"%q: %s\", name, err))\n\t}\n\treturn t\n}\n\nvar recv = parse(\"recv\", `\n\t{{\/*  Send n, receive it one way or another into x, check that they match. *\/}}\n\tc <- n\n\t{{if .Maybe}}\n\tx = <-c\n\t{{else}}\n\tselect {\n\t{{\/*  Blocking or non-blocking, before the receive. *\/}}\n\t{{\/*  The compiler implements two-case select where one is default with custom code, *\/}}\n\t{{\/*  so test the default branch both before and after the send. *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Receive from c.  Different cases are direct, indirect, :=, interface, and map assignment. *\/}}\n\t{{if .Maybe}}\n\tcase x = <-c:\n\t{{else}}{{if .Maybe}}\n\tcase *f(&x) = <-c:\n\t{{else}}{{if .Maybe}}\n\tcase y := <-c:\n\t\tx = y\n\t{{else}}{{if .Maybe}}\n\tcase i = <-c:\n\t\tx = i.(int)\n\t{{else}}\n\tcase m[13] = <-c:\n\t\tx = m[13]\n\t{{end}}{{end}}{{end}}{{end}}\n\t{{\/*  Blocking or non-blocking again, after the receive. *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Dummy send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase dummy <- 1:\n\t\tpanic(\"dummy send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-dummy:\n\t\tpanic(\"dummy receive\")\n\t{{end}}\n\t{{\/*  Nil channel send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase nilch <- 1:\n\t\tpanic(\"nilch send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-nilch:\n\t\tpanic(\"nilch recv\")\n\t{{end}}\n\t}\n\t{{end}}\n\tif x != n {\n\t\tdie(x)\n\t}\n\tn++\n`)\n\nvar recvOrder = parse(\"recvOrder\", `\n\t{{\/*  Send n, receive it one way or another into x, check that they match. *\/}}\n\t{{\/*  Check order of operations along the way by calling functions that check *\/}}\n\t{{\/*  that the argument sequence is strictly increasing. *\/}}\n\torder = 0\n\tc <- n\n\t{{if .Maybe}}\n\t{{\/*  Outside of select, left-to-right rule applies. *\/}}\n\t{{\/*  (Inside select, assignment waits until case is chosen, *\/}}\n\t{{\/*  so right hand side happens before anything on left hand side. *\/}}\n\t*fp(&x, 1) = <-fc(c, 2)\n\t{{else}}{{if .Maybe}}\n\tm[fn(13, 1)] = <-fc(c, 2)\n\tx = m[13]\n\t{{else}}\n\tselect {\n\t{{\/*  Blocking or non-blocking, before the receive. *\/}}\n\t{{\/*  The compiler implements two-case select where one is default with custom code, *\/}}\n\t{{\/*  so test the default branch both before and after the send. *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Receive from c.  Different cases are direct, indirect, :=, interface, and map assignment. *\/}}\n\t{{if .Maybe}}\n\tcase *fp(&x, 100) = <-fc(c, 1):\n\t{{else}}{{if .Maybe}}\n\tcase y := <-fc(c, 1):\n\t\tx = y\n\t{{else}}{{if .Maybe}}\n\tcase i = <-fc(c, 1):\n\t\tx = i.(int)\n\t{{else}}\n\tcase m[fn(13, 100)] = <-fc(c, 1):\n\t\tx = m[13]\n\t{{end}}{{end}}{{end}}\n\t{{\/*  Blocking or non-blocking again, after the receive. *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Dummy send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase fc(dummy, 2) <- fn(1, 3):\n\t\tpanic(\"dummy send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-fc(dummy, 4):\n\t\tpanic(\"dummy receive\")\n\t{{end}}\n\t{{\/*  Nil channel send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase fc(nilch, 5) <- fn(1, 6):\n\t\tpanic(\"nilch send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-fc(nilch, 7):\n\t\tpanic(\"nilch recv\")\n\t{{end}}\n\t}\n\t{{end}}{{end}}\n\tif x != n {\n\t\tdie(x)\n\t}\n\tn++\n`)\n\nvar send = parse(\"send\", `\n\t{{\/*  Send n one way or another, receive it into x, check that they match. *\/}}\n\t{{if .Maybe}}\n\tc <- n\n\t{{else}}\n\tselect {\n\t{{\/*  Blocking or non-blocking, before the receive (same reason as in recv). *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Send c <- n.  No real special cases here, because no values come back *\/}}\n\t{{\/*  from the send operation. *\/}}\n\tcase c <- n:\n\t{{\/*  Blocking or non-blocking. *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Dummy send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase dummy <- 1:\n\t\tpanic(\"dummy send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-dummy:\n\t\tpanic(\"dummy receive\")\n\t{{end}}\n\t{{\/*  Nil channel send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase nilch <- 1:\n\t\tpanic(\"nilch send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-nilch:\n\t\tpanic(\"nilch recv\")\n\t{{end}}\n\t}\n\t{{end}}\n\tx = <-c\n\tif x != n {\n\t\tdie(x)\n\t}\n\tn++\n`)\n\nvar sendOrder = parse(\"sendOrder\", `\n\t{{\/*  Send n one way or another, receive it into x, check that they match. *\/}}\n\t{{\/*  Check order of operations along the way by calling functions that check *\/}}\n\t{{\/*  that the argument sequence is strictly increasing. *\/}}\n\torder = 0\n\t{{if .Maybe}}\n\tfc(c, 1) <- fn(n, 2)\n\t{{else}}\n\tselect {\n\t{{\/*  Blocking or non-blocking, before the receive (same reason as in recv). *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Send c <- n.  No real special cases here, because no values come back *\/}}\n\t{{\/*  from the send operation. *\/}}\n\tcase fc(c, 1) <- fn(n, 2):\n\t{{\/*  Blocking or non-blocking. *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Dummy send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase fc(dummy, 3) <- fn(1, 4):\n\t\tpanic(\"dummy send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-fc(dummy, 5):\n\t\tpanic(\"dummy receive\")\n\t{{end}}\n\t{{\/*  Nil channel send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase fc(nilch, 6) <- fn(1, 7):\n\t\tpanic(\"nilch send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-fc(nilch, 8):\n\t\tpanic(\"nilch recv\")\n\t{{end}}\n\t}\n\t{{end}}\n\tx = <-c\n\tif x != n {\n\t\tdie(x)\n\t}\n\tn++\n`)\n\nvar nonblock = parse(\"nonblock\", `\n\tx = n\n\t{{\/*  Test various combinations of non-blocking operations. *\/}}\n\t{{\/*  Receive assignments must not edit or even attempt to compute the address of the lhs. *\/}}\n\tselect {\n\t{{if .MaybeDefault}}\n\tdefault:\n\t{{end}}\n\t{{if .Maybe}}\n\tcase dummy <- 1:\n\t\tpanic(\"dummy <- 1\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase nilch <- 1:\n\t\tpanic(\"nilch <- 1\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-dummy:\n\t\tpanic(\"<-dummy\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase x = <-dummy:\n\t\tpanic(\"<-dummy x\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase **(**int)(nil) = <-dummy:\n\t\tpanic(\"<-dummy (and didn't crash saving result!)\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-nilch:\n\t\tpanic(\"<-nilch\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase x = <-nilch:\n\t\tpanic(\"<-nilch x\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase **(**int)(nil) = <-nilch:\n\t\tpanic(\"<-nilch (and didn't crash saving result!)\")\n\t{{end}}\n\t{{if .MustDefault}}\n\tdefault:\n\t{{end}}\n\t}\n\tif x != n {\n\t\tdie(x)\n\t}\n\tn++\n`)\n\n\/\/ Code for enumerating all possible paths through\n\/\/ some logic.  The logic should call choose(n) when\n\/\/ it wants to choose between n possibilities.\n\/\/ On successive runs through the logic, choose(n)\n\/\/ will return 0, 1, ..., n-1.  The helper maybe() is\n\/\/ similar but returns true and then false.\n\/\/\n\/\/ Given a function gen that generates an output\n\/\/ using choose and maybe, code can generate all\n\/\/ possible outputs using\n\/\/\n\/\/\tfor next() {\n\/\/\t\tgen()\n\/\/\t}\n\ntype choice struct {\n\ti, n int\n}\n\nvar choices []choice\nvar cp int = -1\n\nfunc maybe() bool {\n\treturn choose(2) == 0\n}\n\nfunc choose(n int) int {\n\tif cp >= len(choices) {\n\t\t\/\/ never asked this before: start with 0.\n\t\tchoices = append(choices, choice{0, n})\n\t\tcp = len(choices)\n\t\treturn 0\n\t}\n\t\/\/ otherwise give recorded answer\n\tif n != choices[cp].n {\n\t\tpanic(\"inconsistent choices\")\n\t}\n\ti := choices[cp].i\n\tcp++\n\treturn i\n}\n\nfunc next() bool {\n\tif cp < 0 {\n\t\t\/\/ start a new round\n\t\tcp = 0\n\t\treturn true\n\t}\n\n\t\/\/ increment last choice sequence\n\tcp = len(choices) - 1\n\tfor cp >= 0 && choices[cp].i == choices[cp].n-1 {\n\t\tcp--\n\t}\n\tif cp < 0 {\n\t\tchoices = choices[:0]\n\t\treturn false\n\t}\n\tchoices[cp].i++\n\tchoices = choices[:cp+1]\n\tcp = 0\n\treturn true\n}\n<commit_msg>test: speed up chan\/select5<commit_after>\/\/ runoutput\n\n\/\/ Copyright 2011 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Generate test of channel operations and simple selects.\n\/\/ The output of this program is compiled and run to do the\n\/\/ actual test.\n\n\/\/ Each test does only one real send or receive at a time, but phrased\n\/\/ in various ways that the compiler may or may not rewrite\n\/\/ into simpler expressions.\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"text\/template\"\n)\n\nfunc main() {\n\tout := bufio.NewWriter(os.Stdout)\n\tfmt.Fprintln(out, header)\n\ta := new(arg)\n\n\t\/\/ Generate each test as a separate function to avoid\n\t\/\/ hitting the 6g optimizer with one enormous function.\n\t\/\/ If we name all the functions init we don't have to\n\t\/\/ maintain a list of which ones to run.\n\tdo := func(t *template.Template) {\n\t\tfor ; next(); a.reset() {\n\t\t\tfmt.Fprintln(out, `func init() {`)\n\t\t\trun(t, a, out)\n\t\t\tfmt.Fprintln(out, `}`)\n\t\t}\n\t}\n\n\tdo(recv)\n\tdo(send)\n\tdo(recvOrder)\n\tdo(sendOrder)\n\tdo(nonblock)\n\n\tfmt.Fprintln(out, \"\/\/\", a.nreset, \"cases\")\n\tout.Flush()\n}\n\nfunc run(t *template.Template, a interface{}, out io.Writer) {\n\tif err := t.Execute(out, a); err != nil {\n\t\tpanic(err)\n\t}\n}\n\ntype arg struct {\n\tdef    bool\n\tnreset int\n}\n\nfunc (a *arg) Maybe() bool {\n\treturn maybe()\n}\n\nfunc (a *arg) MaybeDefault() bool {\n\tif a.def {\n\t\treturn false\n\t}\n\ta.def = maybe()\n\treturn a.def\n}\n\nfunc (a *arg) MustDefault() bool {\n\treturn !a.def\n}\n\nfunc (a *arg) reset() {\n\ta.def = false\n\ta.nreset++\n}\n\nconst header = `\/\/ GENERATED BY select5.go; DO NOT EDIT\n\npackage main\n\n\/\/ channel is buffered so test is single-goroutine.\n\/\/ we are not interested in the concurrency aspects\n\/\/ of select, just testing that the right calls happen.\nvar c = make(chan int, 1)\nvar nilch chan int\nvar n = 1\nvar x int\nvar i interface{}\nvar dummy = make(chan int)\nvar m = make(map[int]int)\nvar order = 0\n\nfunc f(p *int) *int {\n\treturn p\n}\n\n\/\/ check order of operations by ensuring that\n\/\/ successive calls to checkorder have increasing o values.\nfunc checkorder(o int) {\n\tif o <= order {\n\t\tprintln(\"invalid order\", o, \"after\", order)\n\t\tpanic(\"order\")\n\t}\n\torder = o\n}\n\nfunc fc(c chan int, o int) chan int {\n\tcheckorder(o)\n\treturn c\n}\n\nfunc fp(p *int, o int) *int {\n\tcheckorder(o)\n\treturn p\n}\n\nfunc fn(n, o int) int {\n\tcheckorder(o)\n\treturn n\n}\n\nfunc die(x int) {\n\tprintln(\"have\", x, \"want\", n)\n\tpanic(\"chan\")\n}\n\nfunc main() {\n\t\/\/ everything happens in init funcs\n}\n`\n\nfunc parse(name, s string) *template.Template {\n\tt, err := template.New(name).Parse(s)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"%q: %s\", name, err))\n\t}\n\treturn t\n}\n\nvar recv = parse(\"recv\", `\n\t{{\/*  Send n, receive it one way or another into x, check that they match. *\/}}\n\tc <- n\n\t{{if .Maybe}}\n\tx = <-c\n\t{{else}}\n\tselect {\n\t{{\/*  Blocking or non-blocking, before the receive. *\/}}\n\t{{\/*  The compiler implements two-case select where one is default with custom code, *\/}}\n\t{{\/*  so test the default branch both before and after the send. *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Receive from c.  Different cases are direct, indirect, :=, interface, and map assignment. *\/}}\n\t{{if .Maybe}}\n\tcase x = <-c:\n\t{{else}}{{if .Maybe}}\n\tcase *f(&x) = <-c:\n\t{{else}}{{if .Maybe}}\n\tcase y := <-c:\n\t\tx = y\n\t{{else}}{{if .Maybe}}\n\tcase i = <-c:\n\t\tx = i.(int)\n\t{{else}}\n\tcase m[13] = <-c:\n\t\tx = m[13]\n\t{{end}}{{end}}{{end}}{{end}}\n\t{{\/*  Blocking or non-blocking again, after the receive. *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Dummy send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase dummy <- 1:\n\t\tpanic(\"dummy send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-dummy:\n\t\tpanic(\"dummy receive\")\n\t{{end}}\n\t{{\/*  Nil channel send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase nilch <- 1:\n\t\tpanic(\"nilch send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-nilch:\n\t\tpanic(\"nilch recv\")\n\t{{end}}\n\t}\n\t{{end}}\n\tif x != n {\n\t\tdie(x)\n\t}\n\tn++\n`)\n\nvar recvOrder = parse(\"recvOrder\", `\n\t{{\/*  Send n, receive it one way or another into x, check that they match. *\/}}\n\t{{\/*  Check order of operations along the way by calling functions that check *\/}}\n\t{{\/*  that the argument sequence is strictly increasing. *\/}}\n\torder = 0\n\tc <- n\n\t{{if .Maybe}}\n\t{{\/*  Outside of select, left-to-right rule applies. *\/}}\n\t{{\/*  (Inside select, assignment waits until case is chosen, *\/}}\n\t{{\/*  so right hand side happens before anything on left hand side. *\/}}\n\t*fp(&x, 1) = <-fc(c, 2)\n\t{{else}}{{if .Maybe}}\n\tm[fn(13, 1)] = <-fc(c, 2)\n\tx = m[13]\n\t{{else}}\n\tselect {\n\t{{\/*  Blocking or non-blocking, before the receive. *\/}}\n\t{{\/*  The compiler implements two-case select where one is default with custom code, *\/}}\n\t{{\/*  so test the default branch both before and after the send. *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Receive from c.  Different cases are direct, indirect, :=, interface, and map assignment. *\/}}\n\t{{if .Maybe}}\n\tcase *fp(&x, 100) = <-fc(c, 1):\n\t{{else}}{{if .Maybe}}\n\tcase y := <-fc(c, 1):\n\t\tx = y\n\t{{else}}{{if .Maybe}}\n\tcase i = <-fc(c, 1):\n\t\tx = i.(int)\n\t{{else}}\n\tcase m[fn(13, 100)] = <-fc(c, 1):\n\t\tx = m[13]\n\t{{end}}{{end}}{{end}}\n\t{{\/*  Blocking or non-blocking again, after the receive. *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Dummy send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase fc(dummy, 2) <- fn(1, 3):\n\t\tpanic(\"dummy send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-fc(dummy, 4):\n\t\tpanic(\"dummy receive\")\n\t{{end}}\n\t{{\/*  Nil channel send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase fc(nilch, 5) <- fn(1, 6):\n\t\tpanic(\"nilch send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-fc(nilch, 7):\n\t\tpanic(\"nilch recv\")\n\t{{end}}\n\t}\n\t{{end}}{{end}}\n\tif x != n {\n\t\tdie(x)\n\t}\n\tn++\n`)\n\nvar send = parse(\"send\", `\n\t{{\/*  Send n one way or another, receive it into x, check that they match. *\/}}\n\t{{if .Maybe}}\n\tc <- n\n\t{{else}}\n\tselect {\n\t{{\/*  Blocking or non-blocking, before the receive (same reason as in recv). *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Send c <- n.  No real special cases here, because no values come back *\/}}\n\t{{\/*  from the send operation. *\/}}\n\tcase c <- n:\n\t{{\/*  Blocking or non-blocking. *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Dummy send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase dummy <- 1:\n\t\tpanic(\"dummy send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-dummy:\n\t\tpanic(\"dummy receive\")\n\t{{end}}\n\t{{\/*  Nil channel send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase nilch <- 1:\n\t\tpanic(\"nilch send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-nilch:\n\t\tpanic(\"nilch recv\")\n\t{{end}}\n\t}\n\t{{end}}\n\tx = <-c\n\tif x != n {\n\t\tdie(x)\n\t}\n\tn++\n`)\n\nvar sendOrder = parse(\"sendOrder\", `\n\t{{\/*  Send n one way or another, receive it into x, check that they match. *\/}}\n\t{{\/*  Check order of operations along the way by calling functions that check *\/}}\n\t{{\/*  that the argument sequence is strictly increasing. *\/}}\n\torder = 0\n\t{{if .Maybe}}\n\tfc(c, 1) <- fn(n, 2)\n\t{{else}}\n\tselect {\n\t{{\/*  Blocking or non-blocking, before the receive (same reason as in recv). *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Send c <- n.  No real special cases here, because no values come back *\/}}\n\t{{\/*  from the send operation. *\/}}\n\tcase fc(c, 1) <- fn(n, 2):\n\t{{\/*  Blocking or non-blocking. *\/}}\n\t{{if .MaybeDefault}}\n\tdefault:\n\t\tpanic(\"nonblock\")\n\t{{end}}\n\t{{\/*  Dummy send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase fc(dummy, 3) <- fn(1, 4):\n\t\tpanic(\"dummy send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-fc(dummy, 5):\n\t\tpanic(\"dummy receive\")\n\t{{end}}\n\t{{\/*  Nil channel send, receive to keep compiler from optimizing select. *\/}}\n\t{{if .Maybe}}\n\tcase fc(nilch, 6) <- fn(1, 7):\n\t\tpanic(\"nilch send\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-fc(nilch, 8):\n\t\tpanic(\"nilch recv\")\n\t{{end}}\n\t}\n\t{{end}}\n\tx = <-c\n\tif x != n {\n\t\tdie(x)\n\t}\n\tn++\n`)\n\nvar nonblock = parse(\"nonblock\", `\n\tx = n\n\t{{\/*  Test various combinations of non-blocking operations. *\/}}\n\t{{\/*  Receive assignments must not edit or even attempt to compute the address of the lhs. *\/}}\n\tselect {\n\t{{if .MaybeDefault}}\n\tdefault:\n\t{{end}}\n\t{{if .Maybe}}\n\tcase dummy <- 1:\n\t\tpanic(\"dummy <- 1\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase nilch <- 1:\n\t\tpanic(\"nilch <- 1\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-dummy:\n\t\tpanic(\"<-dummy\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase x = <-dummy:\n\t\tpanic(\"<-dummy x\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase **(**int)(nil) = <-dummy:\n\t\tpanic(\"<-dummy (and didn't crash saving result!)\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase <-nilch:\n\t\tpanic(\"<-nilch\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase x = <-nilch:\n\t\tpanic(\"<-nilch x\")\n\t{{end}}\n\t{{if .Maybe}}\n\tcase **(**int)(nil) = <-nilch:\n\t\tpanic(\"<-nilch (and didn't crash saving result!)\")\n\t{{end}}\n\t{{if .MustDefault}}\n\tdefault:\n\t{{end}}\n\t}\n\tif x != n {\n\t\tdie(x)\n\t}\n\tn++\n`)\n\n\/\/ Code for enumerating all possible paths through\n\/\/ some logic.  The logic should call choose(n) when\n\/\/ it wants to choose between n possibilities.\n\/\/ On successive runs through the logic, choose(n)\n\/\/ will return 0, 1, ..., n-1.  The helper maybe() is\n\/\/ similar but returns true and then false.\n\/\/\n\/\/ Given a function gen that generates an output\n\/\/ using choose and maybe, code can generate all\n\/\/ possible outputs using\n\/\/\n\/\/\tfor next() {\n\/\/\t\tgen()\n\/\/\t}\n\ntype choice struct {\n\ti, n int\n}\n\nvar choices []choice\nvar cp int = -1\n\nfunc maybe() bool {\n\treturn choose(2) == 0\n}\n\nfunc choose(n int) int {\n\tif cp >= len(choices) {\n\t\t\/\/ never asked this before: start with 0.\n\t\tchoices = append(choices, choice{0, n})\n\t\tcp = len(choices)\n\t\treturn 0\n\t}\n\t\/\/ otherwise give recorded answer\n\tif n != choices[cp].n {\n\t\tpanic(\"inconsistent choices\")\n\t}\n\ti := choices[cp].i\n\tcp++\n\treturn i\n}\n\nfunc next() bool {\n\tif cp < 0 {\n\t\t\/\/ start a new round\n\t\tcp = 0\n\t\treturn true\n\t}\n\n\t\/\/ increment last choice sequence\n\tcp = len(choices) - 1\n\tfor cp >= 0 && choices[cp].i == choices[cp].n-1 {\n\t\tcp--\n\t}\n\tif cp < 0 {\n\t\tchoices = choices[:0]\n\t\treturn false\n\t}\n\tchoices[cp].i++\n\tchoices = choices[:cp+1]\n\tcp = 0\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>package metadata\n\ntype MetaData struct {\n\tVersion          string       `json:\"metadata_version\"`\n\tTitle            LanguageList `json:\"title\"`\n\tDescription      LanguageList `json:\"description\"`\n\tYear             int          `json:\"production_year,omitempty\"`\n\tReleaseYear      int          `json:\"release_year,omitempty\"`\n\tType             string       `json:\"type\"`\n\tSeries           Series       `json:\"series,omitempty\"`\n\tGenres           []string     `json:\"genres\"`\n\tCredits          []Credit     `json:\"credits\"`\n\tRegional         bool         `json:\"regional_content\"`\n\tRating           string       `json:\"parental_rating\"`\n\tRatio            string       `json:\"aspect_ratio,omitempty\"`\n\tDuration         string       `json:\"expected_duration,omitempty\"`\n\tCountries        []string     `json:\"country_of_origin\"`\n\tReleaseDate      string       `json:\"first_release_date,omitempty\"`\n\tOriginalLanguage string       `json:\"original_language,omitempty\"`\n\tStudio           string       `json:\"studio,omitempty\"`\n\tImdbUrl          string       `json:\"imdb_url,omitempty\"`\n\tRatings          []Rating     `json:\"ratings,omitempty\"`\n\tMetadataScore    string       `json:\"metadata_score,omitempty\"`\n\tAwards           string       `json:\"awards_and_recognitions,omitempty\"`\n}\n\ntype Series struct {\n\tEpisode      int    `json:\"episode_number,omitempty\"`\n\tSeason       int    `json:\"season,omitempty\"`\n\tExternalId   string `json:\"external_id,omitempty\"`\n\tInternalId   string `json:\"internal_id,omitempty\"`\n\tEpisodeCount int    `json:\"episodes_in_season,omitempty\"`\n}\n\ntype Credit struct {\n\tName      string `json:\"name\"`\n\tFunction  string `json:\"role\"`\n\tCharacter string `json:\"character,omitempty\"`\n}\n\ntype Language map[string]string\ntype LanguageList map[string]Language\n\ntype ImageData struct {\n\tType        string `json:\"type\"`\n\tOrientation string `json:\"orientation\"`\n\tLanguage    string `json:\"language,omitempty\"`\n\tFile        string `json:\"org_file\"`\n}\n\ntype AkkaXMLAsset struct {\n\tContentId string `json:\"content_id,omitempty\"`\n\tMetaData\n\tImages []ImageData   `json:\"images,omitempty\"`\n\tRights []VideoRights `json:\"rights,omitempty\"`\n\tMultiformData\n}\n\n\/\/ NOTE : This is probably not an all inclusive list of rights but reflects what we have samples for\ntype VideoRights struct {\n\tValidFrom string   `json:\"valid_from\"`\n\tValidTo   string   `json:\"valid_to\"`\n\tUnlimited bool     `json:\"unlimited\"`\n\tDevices   []string `json:\"devices\"`\n}\n\ntype Rating struct {\n\tCountry string `json:\"country,omitempty\"`\n\tContent string `json:\"content\"`\n\tSystem  string `json:\"system,omitempty\"`\n}\n\ntype MultiformData struct {\n\tOtherInformation LanguageList `json:\"other_information,omitempty\"`\n\tTags             []string     `json:\"tags,omitempty\"`\n}\n<commit_msg>update other information type (#137)<commit_after>package metadata\n\ntype MetaData struct {\n\tVersion          string       `json:\"metadata_version\"`\n\tTitle            LanguageList `json:\"title\"`\n\tDescription      LanguageList `json:\"description\"`\n\tYear             int          `json:\"production_year,omitempty\"`\n\tReleaseYear      int          `json:\"release_year,omitempty\"`\n\tType             string       `json:\"type\"`\n\tSeries           Series       `json:\"series,omitempty\"`\n\tGenres           []string     `json:\"genres\"`\n\tCredits          []Credit     `json:\"credits\"`\n\tRegional         bool         `json:\"regional_content\"`\n\tRating           string       `json:\"parental_rating\"`\n\tRatio            string       `json:\"aspect_ratio,omitempty\"`\n\tDuration         string       `json:\"expected_duration,omitempty\"`\n\tCountries        []string     `json:\"country_of_origin\"`\n\tReleaseDate      string       `json:\"first_release_date,omitempty\"`\n\tOriginalLanguage string       `json:\"original_language,omitempty\"`\n\tStudio           string       `json:\"studio,omitempty\"`\n\tImdbUrl          string       `json:\"imdb_url,omitempty\"`\n\tRatings          []Rating     `json:\"ratings,omitempty\"`\n\tMetadataScore    string       `json:\"metadata_score,omitempty\"`\n\tAwards           string       `json:\"awards_and_recognitions,omitempty\"`\n}\n\ntype Series struct {\n\tEpisode      int    `json:\"episode_number,omitempty\"`\n\tSeason       int    `json:\"season,omitempty\"`\n\tExternalId   string `json:\"external_id,omitempty\"`\n\tInternalId   string `json:\"internal_id,omitempty\"`\n\tEpisodeCount int    `json:\"episodes_in_season,omitempty\"`\n}\n\ntype Credit struct {\n\tName      string `json:\"name\"`\n\tFunction  string `json:\"role\"`\n\tCharacter string `json:\"character,omitempty\"`\n}\n\ntype Language map[string]string\ntype LanguageList map[string]Language\n\ntype ImageData struct {\n\tType        string `json:\"type\"`\n\tOrientation string `json:\"orientation\"`\n\tLanguage    string `json:\"language,omitempty\"`\n\tFile        string `json:\"org_file\"`\n}\n\ntype AkkaXMLAsset struct {\n\tContentId string `json:\"content_id,omitempty\"`\n\tMetaData\n\tImages []ImageData   `json:\"images,omitempty\"`\n\tRights []VideoRights `json:\"rights,omitempty\"`\n\tMultiformData\n}\n\n\/\/ NOTE : This is probably not an all inclusive list of rights but reflects what we have samples for\ntype VideoRights struct {\n\tValidFrom string   `json:\"valid_from\"`\n\tValidTo   string   `json:\"valid_to\"`\n\tUnlimited bool     `json:\"unlimited\"`\n\tDevices   []string `json:\"devices\"`\n}\n\ntype Rating struct {\n\tCountry string `json:\"country,omitempty\"`\n\tContent string `json:\"content\"`\n}\n\ntype MultiformData struct {\n\tOtherInformation map[string]interface{} `json:\"other_information,omitempty\"`\n\tTags             []string               `json:\"tags,omitempty\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2017 Marcus McCudy <marcus.mccurdy@gmail.com>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage metrics\n\nimport (\n\t\"math\"\n\t\"log\"\n\t\"strconv\"\n)\n\ntype ConfusionMatrix struct {\n\tTP    int64\n\tFP    int64\n\tTN    int64\n\tFN    int64\n\tTotal int64\n}\n\nfunc (cm *ConfusionMatrix) Update(yText, yHatText string) {\n\ty, err := strconv.ParseInt(yText, 10, 8)\n\tif err != nil {\n\t\tlog.Fatal(\"Error parsing int\", err)\n\t}\n\tyHat, err := strconv.ParseInt(yHatText, 10, 8)\n\tif err != nil {\n\t\tlog.Fatal(\"Error parsing int\", err)\n\t}\n\tif y == -1 {\n\t\ty = 0\n\t}\n\tif yHat == -1 {\n\t\tyHat = 0\n\t}\n\tswitch y {\n\tcase 0:\n\t\tswitch yHat {\n\t\tcase 0:\n\t\t\tcm.TN += 1\n\t\tcase 1:\n\t\t\tcm.FP += 1\n\t\t}\n\tcase 1:\n\t\tswitch yHat {\n\t\tcase 0:\n\t\t\tcm.FN += 1\n\t\tcase 1:\n\t\t\tcm.TP += 1\n\t\t}\n\n\t}\n\tcm.Total++\n}\n\nfunc (cm *ConfusionMatrix) FScore(beta float64) float64 {\n\tp := cm.Precision()\n\tr := cm.Recall()\n\tbetaSquared := beta * beta\n\tf1 := (1 + betaSquared) * (p * r \/ ((betaSquared * p) + r))\n\treturn f1\n}\n\nfunc (cm *ConfusionMatrix) Precision() float64 {\n\treturn float64(cm.TP) \/ float64(cm.TP + cm.FP)\n}\n\nfunc (cm *ConfusionMatrix) Recall() float64 {\n\treturn float64(cm.TP) \/ float64(cm.TP + cm.FN)\n}\nfunc (cm *ConfusionMatrix) MCC() float64 {\n\tdenom := float64((cm.TP + cm.FP)) * float64((cm.TP + cm.FN)) * float64((cm.TN + cm.FP)) * float64((cm.TN + cm.FN))\n\tif denom == 0.0 {\n\t\treturn 0.0\n\t}\n\tnumerator := (float64((cm.TP * cm.TN)) - float64((cm.FP * cm.FN)))\n\tmcc :=  numerator \/ math.Sqrt(denom)\n\treturn mcc\n}\n<commit_msg>Fixed braces formatting according to IntelliJ style warnings.<commit_after>\/\/ Copyright © 2017 Marcus McCudy <marcus.mccurdy@gmail.com>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage metrics\n\nimport (\n\t\"log\"\n\t\"math\"\n\t\"strconv\"\n)\n\ntype ConfusionMatrix struct {\n\tTP    int64\n\tFP    int64\n\tTN    int64\n\tFN    int64\n\tTotal int64\n}\n\nfunc (cm *ConfusionMatrix) Update(yText, yHatText string) {\n\ty, err := strconv.ParseInt(yText, 10, 8)\n\tif err != nil {\n\t\tlog.Fatal(\"Error parsing int\", err)\n\t}\n\tyHat, err := strconv.ParseInt(yHatText, 10, 8)\n\tif err != nil {\n\t\tlog.Fatal(\"Error parsing int\", err)\n\t}\n\tif y == -1 {\n\t\ty = 0\n\t}\n\tif yHat == -1 {\n\t\tyHat = 0\n\t}\n\tswitch y {\n\tcase 0:\n\t\tswitch yHat {\n\t\tcase 0:\n\t\t\tcm.TN += 1\n\t\tcase 1:\n\t\t\tcm.FP += 1\n\t\t}\n\tcase 1:\n\t\tswitch yHat {\n\t\tcase 0:\n\t\t\tcm.FN += 1\n\t\tcase 1:\n\t\t\tcm.TP += 1\n\t\t}\n\n\t}\n\tcm.Total++\n}\n\nfunc (cm *ConfusionMatrix) FScore(beta float64) float64 {\n\tp := cm.Precision()\n\tr := cm.Recall()\n\tbetaSquared := beta * beta\n\tf1 := (1 + betaSquared) * (p * r \/ ((betaSquared * p) + r))\n\treturn f1\n}\n\nfunc (cm *ConfusionMatrix) Precision() float64 {\n\treturn float64(cm.TP) \/ float64(cm.TP+cm.FP)\n}\n\nfunc (cm *ConfusionMatrix) Recall() float64 {\n\treturn float64(cm.TP) \/ float64(cm.TP+cm.FN)\n}\nfunc (cm *ConfusionMatrix) MCC() float64 {\n\tdenom := float64(cm.TP + cm.FP) * float64(cm.TP + cm.FN) * float64(cm.TN + cm.FP) * float64(cm.TN + cm.FN)\n\tif denom == 0.0 {\n\t\treturn 0.0\n\t}\n\tnumerator := float64(cm.TP * cm.TN) - float64(cm.FP * cm.FN)\n\tmcc := numerator \/ math.Sqrt(denom)\n\treturn mcc\n}\n<|endoftext|>"}
{"text":"<commit_before>package topology\n\nimport ()\n\ntype DataCenterId uint32\ntype DataCenter struct {\n\tId      DataCenterId\n\tracks   map[RackId]*Rack\n\tipRange IpRange\n}\n<commit_msg>change data center id from integer to string<commit_after>package topology\n\nimport ()\n\ntype DataCenterId string\ntype DataCenter struct {\n\tId      DataCenterId\n\tracks   map[RackId]*Rack\n\tipRange IpRange\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/HewlettPackard\/oneview-golang\/ov\"\n\t\"os\"\n)\n\nfunc main() {\n\n\tvar (\n\t\tClientOV       *ov.OVClient\n\t\tname_to_create = \"Cluster-1\"\n\t\tmanaged_domain = \"TestDomain\" \/\/Variable to update the managedDomain\n\t)\n\n\tovc := ClientOV.NewOVClient(\n\t\tos.Getenv(\"ONEVIEW_OV_USER\"),\n\t\tos.Getenv(\"ONEVIEW_OV_PASSWORD\"),\n\t\tos.Getenv(\"ONEVIEW_OV_DOMAIN\"),\n\t\tos.Getenv(\"ONEVIEW_OV_ENDPOINT\"),\n\t\tfalse,\n\t\t1000,\n\t\t\"*\")\n\n\t\/\/ Create storage system\n\tstorageSystem := ov.StorageSystem{Hostname: \"<hostname>\", Username: \"<username>\", Password: \"<password>\", Family: \"<family>\", Description: \"<description>\"}\n\n\terr := ovc.CreateStorageSystem(storageSystem)\n\tif err != nil {\n\t\tfmt.Println(\"Could not create the system\", err)\n\t}\n\n\t\/\/The below example is to update a storeServ system.\n\t\/\/Please refer the API reference for fields to update a storeVirtual system.\n\n\t\/\/ Get the storage system to be updated\n\tupdate_system, _ := ovc.GetStorageSystemByName(name_to_create)\n\n\t\/\/ Update the given storage system\n\t\/\/Managed domain is mandatory attribute for update\n\tDeviceSpecificAttributesForUpdate := update_system.StorageSystemDeviceSpecificAttributes\n\tDeviceSpecificAttributesForUpdate.ManagedDomain = managed_domain\n\n\tupdated_storage_system := ov.StorageSystem{\n\t\tName: name_to_create,\n\t\tStorageSystemDeviceSpecificAttributes: DeviceSpecificAttributesForUpdate,\n\t\tURI:         update_system.URI,\n\t\tETAG:        update_system.ETAG,\n\t\tDescription: \"Updated the storage system\",\n\t\tCredentials: update_system.Credentials,\n\t\tHostname:    update_system.Hostname,\n\t\tPorts:       update_system.Ports,\n\t}\n\n\terr = ovc.UpdateStorageSystem(updated_storage_system)\n\tif err != nil {\n\t\tfmt.Println(\"Could not update the system\", err)\n\t}\n\n\t\/\/ Get All the systems present\n\tfmt.Println(\"\\nGetting all the storage systems present in the appliance: \\n\")\n\tsort := \"name:desc\"\n\tsystem_list, err := ovc.GetStorageSystems(\"\", sort)\n\tif err != nil {\n\t\tfmt.Println(\"Error Getting the storage systems \", err)\n\t} else {\n\t\tfor i := 0; i < len(system_list.Members); i++ {\n\t\t\tfmt.Println(system_list.Members[i].Name)\n\t\t}\n\t}\n\n\t\/\/ Get reachable ports\n\tfmt.Println(\"\\n Getting rechable ports of:\", name_to_create)\n\treachable_ports, _ := ovc.GetReachablePorts(update_system.URI)\n\tfmt.Println(reachable_ports.Members)\n\n\t\/\/ Get volume sets\n\tfmt.Println(\"\\n Getting volume sets of:\", name_to_create)\n\tvolume_sets, _ := ovc.GetVolumeSets(update_system.URI)\n\tfmt.Println(volume_sets.Members)\n\n\t\/\/ Delete the created system\n\tfmt.Println(\"\\nDeleting the system with name : \", name_to_create)\n\terr = ovc.DeleteStorageSystem(name_to_create)\n\tif err != nil {\n\t\tfmt.Println(\"Delete Unsuccessful\", err)\n\t}\n}\n<commit_msg>Update storage_system.go<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/HewlettPackard\/oneview-golang\/ov\"\n\t\"os\"\n)\n\nfunc main() {\n\n\tvar (\n\t\tClientOV       *ov.OVClient\n\t\tname_to_create = \"Cluster-1\"\n\t\tmanaged_domain = \"TestDomain\" \/\/Variable to update the managedDomain\n\t)\n\n\tovc := ClientOV.NewOVClient(\n\t\tos.Getenv(\"ONEVIEW_OV_USER\"),\n\t\tos.Getenv(\"ONEVIEW_OV_PASSWORD\"),\n\t\tos.Getenv(\"ONEVIEW_OV_DOMAIN\"),\n\t\tos.Getenv(\"ONEVIEW_OV_ENDPOINT\"),\n\t\tfalse,\n\t\t1000,\n\t\t\"*\")\n\n\t\/\/ Create storage system\n\tstorageSystem := ov.StorageSystem{Hostname: \"<hostname>\", Username: \"<username>\", Password: \"<password>\", Family: \"<family>\", Description: \"<description>\"}\n\n\terr := ovc.CreateStorageSystem(storageSystem)\n\tif err != nil {\n\t\tfmt.Println(\"Could not create the system\", err)\n\t}\n\n\t\/\/The below example is to update a storeServ system.\n\t\/\/Please refer the API reference for fields to update a storeVirtual system.\n\n\t\/\/ Get the storage system to be updated\n\tupdate_system, _ := ovc.GetStorageSystemByName(name_to_create)\n\n\t\/\/ Update the given storage system\n\t\/\/Managed domain is mandatory attribute for update\n\tDeviceSpecificAttributesForUpdate := update_system.StorageSystemDeviceSpecificAttributes\n\tDeviceSpecificAttributesForUpdate.ManagedDomain = managed_domain\n\n\tupdated_storage_system := ov.StorageSystem{\n\t\tName:                                  name_to_create,\n\t\tStorageSystemDeviceSpecificAttributes: DeviceSpecificAttributesForUpdate,\n\t\tURI:                                   update_system.URI,\n\t\tETAG:                                  update_system.ETAG,\n\t\tDescription:                           \"Updated the storage system\",\n\t\tCredentials:                           update_system.Credentials,\n\t\tHostname:                              update_system.Hostname,\n\t\tPorts:                                 update_system.Ports,\n\t}\n\n\terr = ovc.UpdateStorageSystem(updated_storage_system)\n\tif err != nil {\n\t\tfmt.Println(\"Could not update the system\", err)\n\t}\n\n\t\/\/ Get All the systems present\n\tfmt.Println(\"\\nGetting all the storage systems present in the appliance: \\n\")\n\tsort := \"name:desc\"\n\tsystem_list, err := ovc.GetStorageSystems(\"\", sort)\n\tif err != nil {\n\t\tfmt.Println(\"Error Getting the storage systems \", err)\n\t} else {\n\t\tfor i := 0; i < len(system_list.Members); i++ {\n\t\t\tfmt.Println(system_list.Members[i].Name)\n\t\t}\n\t}\n\n\t\/\/ Get reachable ports\n\tfmt.Println(\"\\n Getting rechable ports of:\", name_to_create)\n\treachable_ports, _ := ovc.GetReachablePorts(update_system.URI)\n\tfmt.Println(reachable_ports.Members)\n\n\t\/\/ Get volume sets\n\tfmt.Println(\"\\n Getting volume sets of:\", name_to_create)\n\tvolume_sets, _ := ovc.GetVolumeSets(update_system.URI)\n\tfmt.Println(volume_sets.Members)\n\n\t\/\/ Delete the created system\n\tfmt.Println(\"\\nDeleting the system with name : \", name_to_create)\n\terr = ovc.DeleteStorageSystem(name_to_create)\n\tif err != nil {\n\t\tfmt.Println(\"Delete Unsuccessful\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 The go-gl Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ This program demonstrates the use of a MeshBuffer.\npackage main\n\nimport (\n\t\"github.com\/go-gl\/gl\"\n\t\"github.com\/go-gl\/glfw\"\n\t\"github.com\/go-gl\/glh\"\n\t\"github.com\/go-gl\/glu\"\n\t\"log\"\n)\n\nfunc main() {\n\terr := initGL()\n\tif err != nil {\n\t\tlog.Printf(\"InitGL: %v\", err)\n\t\treturn\n\t}\n\n\tprogram := createSampleProgram()\n\n\tdefer glfw.Terminate()\n\n\tmb := createBuffer()\n\tdefer mb.Release()\n\n\t\/\/ Perform the rendering.\n\tvar angle float32\n\tfor glfw.WindowParam(glfw.Opened) > 0 {\n\t\tgl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)\n\t\tgl.LoadIdentity()\n\t\t\/\/gl.translatef(0, 0, -6)\n\t\t\/\/gl.Rotatef(angle, 0, 1, 0)\n\t\tprogram.Use()\n\n\t\t\/\/ Render a solid cube at half the scale.\n\t\t\/\/gl.Scalef(0.2, 0.2, 0.2)\n\t\tgl.Enable(gl.COLOR_MATERIAL)\n\t\tgl.Enable(gl.POLYGON_OFFSET_FILL)\n\t\tgl.PolygonMode(gl.FRONT_AND_BACK, gl.FILL)\n\t\tmb.Render(gl.TRIANGLES)\n\t\t\/*\n\n\t\t\/\/ Render wireframe cubes, with incremental size.\n\t\tgl.Disable(gl.COLOR_MATERIAL)\n\t\tgl.Disable(gl.POLYGON_OFFSET_FILL)\n\t\tgl.PolygonMode(gl.FRONT_AND_BACK, gl.LINE)\n\n\t\tfor i := 0; i < 50; i++ {\n\t\t\tscale := 0.004*float32(i) + 1.0\n\t\t\tgl.Scalef(scale, scale, scale)\n\t\t\tmb.Render(gl.QUADS)\n\t\t}\n\t\t*\/\n\n\t\tangle += 0.5\n\t\tglfw.SwapBuffers()\n\t}\n}\n\nfunc createBuffer() *glh.MeshBuffer {\n\t\/\/ We create as few vertices as possible.\n\t\/\/ Manually building a cube would require 24 vertices. Many of which\n\t\/\/ are duplicates. All we have to define here, is the 8 unique ones\n\t\/\/ necessary to construct each face of the cube.\n\tpos := []float32{\n\t\t0, 1, 0,\n\t\t1, 0, 0,\n\t\t-1, 0, 0,\n\t}\n\n\t\/\/ Each vertex comes with its own colour.\n\tclr := []float32{\n\t\t1, 1, 1, 0,\n\t\t1, 1, 1, 0,\n\t\t1, 1, 1, 0,\n\t}\n\n\t\/\/ These are the indices into the position and color lists.\n\t\/\/ They tell the GPU which position\/color pair to use in order to construct\n\t\/\/ the whole cube. As can be seen, all elements are repeated multiple\n\t\/\/ times to create the correct layout. For large meshes with many duplicate\n\t\/\/ vertices, this can save a sizable amount of storage space.\n\tidx := []byte{\n\t\t0, 1, 2,\n\t}\n\n\t\/\/ Create a mesh buffer with the given attributes.\n\tmb := glh.NewMeshBuffer(\n\t\tglh.RenderArrays,\n\n\t\t\/\/ Indices.\n\t\tglh.NewIndexAttr(1, gl.UNSIGNED_BYTE, gl.STATIC_DRAW),\n\n\t\t\/\/ Vertex positions have 3 components (x, y, z).\n\t\tglh.NewPositionAttr(3, gl.FLOAT, gl.STATIC_DRAW),\n\n\t\t\/\/ Colors have 4 components (r, g, b, a).\n\t\tglh.NewColorAttr(4, gl.FLOAT, gl.STATIC_DRAW),\n\t)\n\n\t\/\/ Add the mesh to the buffer.\n\tmb.Add(idx, pos, clr)\n\treturn mb\n}\n\n\/\/ initGL initializes GLFW and OpenGL.\nfunc initGL() error {\n\terr := glfw.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglfw.OpenWindowHint(glfw.FsaaSamples, 4)\n\n\terr = glfw.OpenWindow(512, 512, 8, 8, 8, 8, 32, 0, glfw.Windowed)\n\tif err != nil {\n\t\tglfw.Terminate()\n\t\treturn err\n\t}\n\n\tglfw.SetWindowTitle(\"Meshbuffer 3D example\")\n\tglfw.SetSwapInterval(1)\n\tglfw.SetWindowSizeCallback(onResize)\n\tglfw.SetKeyCallback(onKey)\n\n\tgl.Init()\n\tif err = glh.CheckGLError(); err != nil {\n\t\treturn err\n\t}\n\n\tgl.Enable(gl.DEPTH_TEST)\n\tgl.Enable(gl.MULTISAMPLE)\n\tgl.Disable(gl.LIGHTING)\n\n\tgl.ClearColor(0.2, 0.2, 0.23, 1.0)\n\tgl.ShadeModel(gl.SMOOTH)\n\tgl.LineWidth(2)\n\tgl.ClearDepth(1)\n\tgl.DepthFunc(gl.LEQUAL)\n\tgl.Hint(gl.PERSPECTIVE_CORRECTION_HINT, gl.NICEST)\n\tgl.ColorMaterial(gl.FRONT_AND_BACK, gl.AMBIENT_AND_DIFFUSE)\n\treturn nil\n}\n\n\/\/ onKey handles key events.\nfunc onKey(key, state int) {\n\tif key == glfw.KeyEsc {\n\t\tglfw.CloseWindow()\n\t}\n}\n\n\/\/ onResize handles window resize events.\nfunc onResize(w, h int) {\n\tif w < 1 {\n\t\tw = 1\n\t}\n\n\tif h < 1 {\n\t\th = 1\n\t}\n\n\tgl.Viewport(0, 0, w, h)\n\tgl.MatrixMode(gl.PROJECTION)\n\tgl.LoadIdentity()\n\tglu.Perspective(45.0, float64(w)\/float64(h), 0.1, 200.0)\n\tgl.MatrixMode(gl.MODELVIEW)\n\tgl.LoadIdentity()\n}\n\n\/\/ Create a vertex\/fragment shader program\nfunc createSampleProgram() gl.Program {\n\tvs := `\n#version 120\n\/\/ Input vertex data, different for all executions of this shader.\n\/\/ attribute vec3 vertexPosition_modelspace;\nvoid main(){\n\n\tgl_Position = gl_Vertex;\n}\n\t`\n\tfs := `\n#version 120\n\nvoid main()\n{\n\n\t\/\/ Output color = red \n\tgl_FragColor = vec4(1,0,0,1);\n\n}\n\t`\n\tvshader := gl.CreateShader(gl.VERTEX_SHADER)\n\tvshader.Source(vs)\n\tvshader.Compile()\n\tif vshader.Get(gl.COMPILE_STATUS) != gl.TRUE {\n\t\tpanic(\"Unable to compile vertex shader. \" + vshader.GetInfoLog())\n\t}\n\n\tfshader := gl.CreateShader(gl.FRAGMENT_SHADER)\n\tfshader.Source(fs)\n\tfshader.Compile()\n\tif fshader.Get(gl.COMPILE_STATUS) != gl.TRUE {\n\t\tpanic(\"Unable to compile fragment shader. \" + fshader.GetInfoLog())\n\t}\n\n\tprogram := gl.CreateProgram()\n\tprogram.AttachShader(vshader)\n\tprogram.AttachShader(fshader)\n\tprogram.Link()\n\n\tif program.Get(gl.LINK_STATUS) != gl.TRUE {\n\t\tpanic(\"Unable to link program. \" + fshader.GetInfoLog())\n\t}\n\n\tprogram.Use()\n\treturn program\n\n}\n<commit_msg>User VBO instead of VAO<commit_after>\/\/ Copyright 2012 The go-gl Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ This program demonstrates the use of a MeshBuffer.\npackage main\n\nimport (\n\t\"github.com\/go-gl\/gl\"\n\t\"github.com\/go-gl\/glfw\"\n\t\"github.com\/go-gl\/glh\"\n\t\"github.com\/go-gl\/glu\"\n\t\"log\"\n)\n\nfunc main() {\n\terr := initGL()\n\tif err != nil {\n\t\tlog.Printf(\"InitGL: %v\", err)\n\t\treturn\n\t}\n\n\tprogram := createSampleProgram()\n\n\tdefer glfw.Terminate()\n\n\tmb := createBuffer()\n\tdefer mb.Release()\n\n\t\/\/ Perform the rendering.\n\tvar angle float32\n\tfor glfw.WindowParam(glfw.Opened) > 0 {\n\t\tgl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)\n\t\tgl.LoadIdentity()\n\t\t\/\/gl.translatef(0, 0, -6)\n\t\t\/\/gl.Rotatef(angle, 0, 1, 0)\n\t\tprogram.Use()\n\n\t\t\/\/ Render a solid cube at half the scale.\n\t\t\/\/gl.Scalef(0.2, 0.2, 0.2)\n\t\tgl.Enable(gl.COLOR_MATERIAL)\n\t\tgl.Enable(gl.POLYGON_OFFSET_FILL)\n\t\tgl.PolygonMode(gl.FRONT_AND_BACK, gl.FILL)\n\t\tmb.Render(gl.TRIANGLES)\n\t\t\/*\n\n\t\t\/\/ Render wireframe cubes, with incremental size.\n\t\tgl.Disable(gl.COLOR_MATERIAL)\n\t\tgl.Disable(gl.POLYGON_OFFSET_FILL)\n\t\tgl.PolygonMode(gl.FRONT_AND_BACK, gl.LINE)\n\n\t\tfor i := 0; i < 50; i++ {\n\t\t\tscale := 0.004*float32(i) + 1.0\n\t\t\tgl.Scalef(scale, scale, scale)\n\t\t\tmb.Render(gl.QUADS)\n\t\t}\n\t\t*\/\n\n\t\tangle += 0.5\n\t\tglfw.SwapBuffers()\n\t}\n}\n\nfunc createBuffer() *glh.MeshBuffer {\n\t\/\/ We create as few vertices as possible.\n\t\/\/ Manually building a cube would require 24 vertices. Many of which\n\t\/\/ are duplicates. All we have to define here, is the 8 unique ones\n\t\/\/ necessary to construct each face of the cube.\n\tpos := []float32{\n\t\t0, 1, 0,\n\t\t1, 0, 0,\n\t\t-1, 0, 0,\n\t}\n\n\t\/\/ Each vertex comes with its own colour.\n\tclr := []float32{\n\t\t1, 1, 1, 0,\n\t\t1, 1, 1, 0,\n\t\t1, 1, 1, 0,\n\t}\n\n\t\/\/ These are the indices into the position and color lists.\n\t\/\/ They tell the GPU which position\/color pair to use in order to construct\n\t\/\/ the whole cube. As can be seen, all elements are repeated multiple\n\t\/\/ times to create the correct layout. For large meshes with many duplicate\n\t\/\/ vertices, this can save a sizable amount of storage space.\n\tidx := []byte{\n\t\t0, 1, 2,\n\t}\n\n\t\/\/ Create a mesh buffer with the given attributes.\n\tmb := glh.NewMeshBuffer(\n\t\tglh.RenderBuffered,\n\n\t\t\/\/ Indices.\n\t\tglh.NewIndexAttr(1, gl.UNSIGNED_BYTE, gl.STATIC_DRAW),\n\n\t\t\/\/ Vertex positions have 3 components (x, y, z).\n\t\tglh.NewPositionAttr(3, gl.FLOAT, gl.STATIC_DRAW),\n\n\t\t\/\/ Colors have 4 components (r, g, b, a).\n\t\tglh.NewColorAttr(4, gl.FLOAT, gl.STATIC_DRAW),\n\t)\n\n\t\/\/ Add the mesh to the buffer.\n\tmb.Add(idx, pos, clr)\n\treturn mb\n}\n\n\/\/ initGL initializes GLFW and OpenGL.\nfunc initGL() error {\n\terr := glfw.Init()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tglfw.OpenWindowHint(glfw.FsaaSamples, 4)\n\n\terr = glfw.OpenWindow(512, 512, 8, 8, 8, 8, 32, 0, glfw.Windowed)\n\tif err != nil {\n\t\tglfw.Terminate()\n\t\treturn err\n\t}\n\n\tglfw.SetWindowTitle(\"Meshbuffer 3D example\")\n\tglfw.SetSwapInterval(1)\n\tglfw.SetWindowSizeCallback(onResize)\n\tglfw.SetKeyCallback(onKey)\n\n\tgl.Init()\n\tif err = glh.CheckGLError(); err != nil {\n\t\treturn err\n\t}\n\n\tgl.Enable(gl.DEPTH_TEST)\n\tgl.Enable(gl.MULTISAMPLE)\n\tgl.Disable(gl.LIGHTING)\n\n\tgl.ClearColor(0.2, 0.2, 0.23, 1.0)\n\tgl.ShadeModel(gl.SMOOTH)\n\tgl.LineWidth(2)\n\tgl.ClearDepth(1)\n\tgl.DepthFunc(gl.LEQUAL)\n\tgl.Hint(gl.PERSPECTIVE_CORRECTION_HINT, gl.NICEST)\n\tgl.ColorMaterial(gl.FRONT_AND_BACK, gl.AMBIENT_AND_DIFFUSE)\n\treturn nil\n}\n\n\/\/ onKey handles key events.\nfunc onKey(key, state int) {\n\tif key == glfw.KeyEsc {\n\t\tglfw.CloseWindow()\n\t}\n}\n\n\/\/ onResize handles window resize events.\nfunc onResize(w, h int) {\n\tif w < 1 {\n\t\tw = 1\n\t}\n\n\tif h < 1 {\n\t\th = 1\n\t}\n\n\tgl.Viewport(0, 0, w, h)\n\tgl.MatrixMode(gl.PROJECTION)\n\tgl.LoadIdentity()\n\tglu.Perspective(45.0, float64(w)\/float64(h), 0.1, 200.0)\n\tgl.MatrixMode(gl.MODELVIEW)\n\tgl.LoadIdentity()\n}\n\n\/\/ Create a vertex\/fragment shader program\nfunc createSampleProgram() gl.Program {\n\tvs := `\n#version 120\n\/\/ Input vertex data, different for all executions of this shader.\n\/\/ attribute vec3 vertexPosition_modelspace;\nvoid main(){\n\n\tgl_Position = gl_Vertex;\n}\n\t`\n\tfs := `\n#version 120\n\nvoid main()\n{\n\n\t\/\/ Output color = red \n\tgl_FragColor = vec4(1,0,0,1);\n\n}\n\t`\n\tvshader := gl.CreateShader(gl.VERTEX_SHADER)\n\tvshader.Source(vs)\n\tvshader.Compile()\n\tif vshader.Get(gl.COMPILE_STATUS) != gl.TRUE {\n\t\tpanic(\"Unable to compile vertex shader. \" + vshader.GetInfoLog())\n\t}\n\n\tfshader := gl.CreateShader(gl.FRAGMENT_SHADER)\n\tfshader.Source(fs)\n\tfshader.Compile()\n\tif fshader.Get(gl.COMPILE_STATUS) != gl.TRUE {\n\t\tpanic(\"Unable to compile fragment shader. \" + fshader.GetInfoLog())\n\t}\n\n\tprogram := gl.CreateProgram()\n\tprogram.AttachShader(vshader)\n\tprogram.AttachShader(fshader)\n\tprogram.Link()\n\n\tif program.Get(gl.LINK_STATUS) != gl.TRUE {\n\t\tpanic(\"Unable to link program. \" + fshader.GetInfoLog())\n\t}\n\n\tprogram.Use()\n\treturn program\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"strconv\"\n\n\t\"github.com\/pachyderm\/pachyderm\/src\/pkg\/deploy\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/pkg\/deploy\/server\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/pkg\/provider\"\n\t\"github.com\/spf13\/cobra\"\n\t\"go.pedge.io\/env\"\n\t\"go.pedge.io\/pkg\/cobra\"\n\t\"go.pedge.io\/protolog\/logrus\"\n\t\"golang.org\/x\/net\/context\"\n\tclient \"k8s.io\/kubernetes\/pkg\/client\/unversioned\"\n)\n\nvar (\n\tdefaultEnv = map[string]string{\n\t\t\"KUBERNETES_ADDRESS\":  \"http:\/\/localhost:8080\",\n\t\t\"KUBERNETES_USERNAME\": \"admin\",\n\t}\n)\n\ntype appEnv struct {\n\tKubernetesAddress  string `env:\"KUBERNETES_ADDRESS\"`\n\tKubernetesUsername string `env:\"KUBERNETES_USERNAME\"`\n\tKubernetesPassword string `env:\"KUBERNETES_PASSWORD\"`\n\tGCEProject         string `env:\"GCE_PROJECT\"`\n\tGCEZone            string `env:\"GCE_ZONE\"`\n}\n\nfunc main() {\n\tenv.Main(do, &appEnv{}, defaultEnv)\n}\n\nfunc do(appEnvObj interface{}) error {\n\tappEnv := appEnvObj.(*appEnv)\n\tlogrus.Register()\n\tconfig := &client.Config{\n\t\tHost:     appEnv.KubernetesAddress,\n\t\tInsecure: true,\n\t\tUsername: appEnv.KubernetesUsername,\n\t\tPassword: appEnv.KubernetesPassword,\n\t}\n\tclient, err := client.New(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tprovider, err := provider.NewGoogleProvider(context.TODO(), appEnv.GCEProject, appEnv.GCEZone)\n\tif err != nil {\n\t\treturn err\n\t}\n\tapiServer := server.NewAPIServer(client, provider)\n\n\tcreateCluster := &cobra.Command{\n\t\tUse:   \"create-cluster cluster-name nodes shards replicas\",\n\t\tShort: \"Create a new pachyderm cluster.\",\n\t\tLong:  \"Create a new pachyderm cluster.\",\n\t\tRun: pkgcobra.RunFixedArgs(4, func(args []string) error {\n\t\t\tnodes, err := strconv.ParseUint(args[1], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tshards, err := strconv.ParseUint(args[2], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treplicas, err := strconv.ParseUint(args[3], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = apiServer.CreateCluster(\n\t\t\t\tcontext.Background(),\n\t\t\t\t&deploy.CreateClusterRequest{\n\t\t\t\t\tCluster: &deploy.Cluster{\n\t\t\t\t\t\tName: args[0],\n\t\t\t\t\t},\n\t\t\t\t\tNodes:    nodes,\n\t\t\t\t\tShards:   shards,\n\t\t\t\t\tReplicas: replicas,\n\t\t\t\t})\n\t\t\treturn err\n\t\t}),\n\t}\n\n\tdeleteCluster := &cobra.Command{\n\t\tUse:   \"delete-cluster cluster-name\",\n\t\tShort: \"Delete a cluster.\",\n\t\tLong:  \"Delete a cluster.\",\n\t\tRun: pkgcobra.RunFixedArgs(1, func(args []string) error {\n\t\t\t_, err = apiServer.DeleteCluster(\n\t\t\t\tcontext.Background(),\n\t\t\t\t&deploy.DeleteClusterRequest{\n\t\t\t\t\tCluster: &deploy.Cluster{\n\t\t\t\t\t\tName: args[0],\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\treturn err\n\t\t}),\n\t}\n\n\trootCmd := &cobra.Command{\n\t\tUse: \"deploy\",\n\t\tLong: `Deploy Pachyderm clusters.\n\nThe environment variable KUBERNETES_ADDRESS controls the Kubernetes endpoint the CLI connects to, the default is https:\/\/localhost:8080.`,\n\t}\n\trootCmd.AddCommand(createCluster)\n\trootCmd.AddCommand(deleteCluster)\n\treturn rootCmd.Execute()\n}\n<commit_msg>Adds validation of env.<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com\/pachyderm\/pachyderm\/src\/pkg\/deploy\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/pkg\/deploy\/server\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/pkg\/provider\"\n\t\"github.com\/spf13\/cobra\"\n\t\"go.pedge.io\/env\"\n\t\"go.pedge.io\/pkg\/cobra\"\n\t\"go.pedge.io\/protolog\/logrus\"\n\t\"golang.org\/x\/net\/context\"\n\tclient \"k8s.io\/kubernetes\/pkg\/client\/unversioned\"\n)\n\nvar (\n\tdefaultEnv = map[string]string{\n\t\t\"KUBERNETES_ADDRESS\":  \"http:\/\/localhost:8080\",\n\t\t\"KUBERNETES_USERNAME\": \"admin\",\n\t}\n)\n\ntype appEnv struct {\n\tKubernetesAddress  string `env:\"KUBERNETES_ADDRESS\"`\n\tKubernetesUsername string `env:\"KUBERNETES_USERNAME\"`\n\tKubernetesPassword string `env:\"KUBERNETES_PASSWORD\"`\n\tGCEProject         string `env:\"GCE_PROJECT\"`\n\tGCEZone            string `env:\"GCE_ZONE\"`\n}\n\nfunc main() {\n\tenv.Main(do, &appEnv{}, defaultEnv)\n}\n\nfunc validateEnv(appEnv *appEnv) error {\n\tif appEnv.GCEProject == \"\" {\n\t\treturn fmt.Errorf(\"envvar GCE_PROJECT must be set.\")\n\t}\n\tif appEnv.GCEZone == \"\" {\n\t\treturn fmt.Errorf(\"envvar GCE_ZONE must be set.\")\n\t}\n\treturn nil\n}\n\nfunc do(appEnvObj interface{}) error {\n\tappEnv := appEnvObj.(*appEnv)\n\tif err := validateEnv(appEnv); err != nil {\n\t\treturn err\n\t}\n\tlogrus.Register()\n\tconfig := &client.Config{\n\t\tHost:     appEnv.KubernetesAddress,\n\t\tInsecure: true,\n\t\tUsername: appEnv.KubernetesUsername,\n\t\tPassword: appEnv.KubernetesPassword,\n\t}\n\tclient, err := client.New(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tprovider, err := provider.NewGoogleProvider(context.TODO(), appEnv.GCEProject, appEnv.GCEZone)\n\tif err != nil {\n\t\treturn err\n\t}\n\tapiServer := server.NewAPIServer(client, provider)\n\n\tcreateCluster := &cobra.Command{\n\t\tUse:   \"create-cluster cluster-name nodes shards replicas\",\n\t\tShort: \"Create a new pachyderm cluster.\",\n\t\tLong:  \"Create a new pachyderm cluster.\",\n\t\tRun: pkgcobra.RunFixedArgs(4, func(args []string) error {\n\t\t\tnodes, err := strconv.ParseUint(args[1], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tshards, err := strconv.ParseUint(args[2], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treplicas, err := strconv.ParseUint(args[3], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = apiServer.CreateCluster(\n\t\t\t\tcontext.Background(),\n\t\t\t\t&deploy.CreateClusterRequest{\n\t\t\t\t\tCluster: &deploy.Cluster{\n\t\t\t\t\t\tName: args[0],\n\t\t\t\t\t},\n\t\t\t\t\tNodes:    nodes,\n\t\t\t\t\tShards:   shards,\n\t\t\t\t\tReplicas: replicas,\n\t\t\t\t})\n\t\t\treturn err\n\t\t}),\n\t}\n\n\tdeleteCluster := &cobra.Command{\n\t\tUse:   \"delete-cluster cluster-name\",\n\t\tShort: \"Delete a cluster.\",\n\t\tLong:  \"Delete a cluster.\",\n\t\tRun: pkgcobra.RunFixedArgs(1, func(args []string) error {\n\t\t\t_, err = apiServer.DeleteCluster(\n\t\t\t\tcontext.Background(),\n\t\t\t\t&deploy.DeleteClusterRequest{\n\t\t\t\t\tCluster: &deploy.Cluster{\n\t\t\t\t\t\tName: args[0],\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\treturn err\n\t\t}),\n\t}\n\n\trootCmd := &cobra.Command{\n\t\tUse: \"deploy\",\n\t\tLong: `Deploy Pachyderm clusters.\n\nThe environment variable KUBERNETES_ADDRESS controls the Kubernetes endpoint the CLI connects to, the default is https:\/\/localhost:8080.`,\n\t}\n\trootCmd.AddCommand(createCluster)\n\trootCmd.AddCommand(deleteCluster)\n\treturn rootCmd.Execute()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"archive\/tar\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/docker\/engine-api\/types\"\n\t\"github.com\/opencontainers\/runtime-spec\/specs-go\"\n\t\"gopkg.in\/yaml.v2\"\n)\n\n\/\/ Moby is the type of a Moby config file\ntype Moby struct {\n\tKernel struct {\n\t\tImage   string\n\t\tCmdline string\n\t}\n\tInit   string\n\tSystem []MobyImage\n\tDaemon []MobyImage\n\tFiles  []struct {\n\t\tPath     string\n\t\tContents string\n\t}\n\tOutputs []struct {\n\t\tFormat  string\n\t\tProject string\n\t\tBucket  string\n\t\tFamily  string\n\t\tKeys    string\n\t\tPublic  bool\n\t\tReplace bool\n\t}\n}\n\n\/\/ MobyImage is the type of an image config\ntype MobyImage struct {\n\tName             string\n\tImage            string\n\tCapabilities     []string\n\tMounts           []specs.Mount\n\tBinds            []string\n\tTmpfs            []string\n\tCommand          []string\n\tEnv              []string\n\tCwd              string\n\tNet              string\n\tPid              string\n\tIpc              string\n\tUts              string\n\tReadonly         bool\n\tUID              uint32   `yaml:\"uid\"`\n\tGID              uint32   `yaml:\"gid\"`\n\tAdditionalGids   []uint32 `yaml:\"additionalGids\"`\n\tNoNewPrivileges  bool     `yaml:\"noNewPrivileges\"`\n\tHostname         string\n\tOomScoreAdj      int  `yaml:\"oomScoreAdj\"`\n\tDisableOOMKiller bool `yaml:\"disableOOMKiller\"`\n}\n\n\/\/ NewConfig parses a config file\nfunc NewConfig(config []byte) (*Moby, error) {\n\tm := Moby{}\n\n\terr := yaml.Unmarshal(config, &m)\n\tif err != nil {\n\t\treturn &m, err\n\t}\n\n\treturn &m, nil\n}\n\n\/\/ ConfigToOCI converts a config specification to an OCI config file\nfunc ConfigToOCI(image *MobyImage) ([]byte, error) {\n\n\t\/\/ TODO pass through same docker client to all functions\n\tcli, err := dockerClient()\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tinspect, err := dockerInspectImage(cli, image.Image)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\treturn ConfigInspectToOCI(image, inspect)\n}\n\nfunc defaultMountpoint(tp string) string {\n\tswitch tp {\n\tcase \"proc\":\n\t\treturn \"\/proc\"\n\tcase \"devpts\":\n\t\treturn \"\/dev\/pts\"\n\tcase \"sysfs\":\n\t\treturn \"\/sys\"\n\tcase \"cgroup\":\n\t\treturn \"\/sys\/fs\/cgroup\"\n\tcase \"mqueue\":\n\t\treturn \"\/dev\/mqueue\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\n\/\/ Sort mounts by number of path components so \/dev\/pts is listed after \/dev\ntype mlist []specs.Mount\n\nfunc (m mlist) Len() int {\n\treturn len(m)\n}\nfunc (m mlist) Less(i, j int) bool {\n\treturn m.parts(i) < m.parts(j)\n}\nfunc (m mlist) Swap(i, j int) {\n\tm[i], m[j] = m[j], m[i]\n}\nfunc (m mlist) parts(i int) int {\n\treturn strings.Count(filepath.Clean(m[i].Destination), string(os.PathSeparator))\n}\n\n\/\/ ConfigInspectToOCI converts a config and the output of image inspect to an OCI config file\nfunc ConfigInspectToOCI(image *MobyImage, inspect types.ImageInspect) ([]byte, error) {\n\toci := specs.Spec{}\n\n\tconfig := inspect.Config\n\tif config == nil {\n\t\treturn []byte{}, errors.New(\"empty image config\")\n\t}\n\n\targs := append(config.Entrypoint, config.Cmd...)\n\tif len(image.Command) != 0 {\n\t\targs = image.Command\n\t}\n\tenv := config.Env\n\tif len(image.Env) != 0 {\n\t\tenv = image.Env\n\t}\n\tcwd := config.WorkingDir\n\tif image.Cwd != \"\" {\n\t\tcwd = image.Cwd\n\t}\n\tif cwd == \"\" {\n\t\tcwd = \"\/\"\n\t}\n\t\/\/ default options match what Docker does\n\tprocOptions := []string{\"nosuid\", \"nodev\", \"noexec\", \"relatime\"}\n\tdevOptions := []string{\"nosuid\", \"strictatime\", \"mode=755\", \"size=65536k\"}\n\tif image.Readonly {\n\t\tdevOptions = append(devOptions, \"ro\")\n\t}\n\tptsOptions := []string{\"nosuid\", \"noexec\", \"newinstance\", \"ptmxmode=0666\", \"mode=0620\"}\n\tsysOptions := []string{\"nosuid\", \"noexec\", \"nodev\"}\n\tif image.Readonly {\n\t\tsysOptions = append(sysOptions, \"ro\")\n\t}\n\tcgroupOptions := []string{\"nosuid\", \"noexec\", \"nodev\", \"relatime\", \"ro\"}\n\t\/\/ note omits \"standard\" \/dev\/shm and \/dev\/mqueue\n\tmounts := map[string]specs.Mount{\n\t\t\"\/proc\":          {Destination: \"\/proc\", Type: \"proc\", Source: \"proc\", Options: procOptions},\n\t\t\"\/dev\":           {Destination: \"\/dev\", Type: \"tmpfs\", Source: \"tmpfs\", Options: devOptions},\n\t\t\"\/dev\/pts\":       {Destination: \"\/dev\/pts\", Type: \"devpts\", Source: \"devpts\", Options: ptsOptions},\n\t\t\"\/sys\":           {Destination: \"\/sys\", Type: \"sysfs\", Source: \"sysfs\", Options: sysOptions},\n\t\t\"\/sys\/fs\/cgroup\": {Destination: \"\/sys\/fs\/cgroup\", Type: \"cgroup\", Source: \"cgroup\", Options: cgroupOptions},\n\t}\n\tfor _, t := range image.Tmpfs {\n\t\tparts := strings.Split(t, \":\")\n\t\tif len(parts) > 2 {\n\t\t\treturn []byte{}, fmt.Errorf(\"Cannot parse tmpfs, too many ':': %s\", t)\n\t\t}\n\t\tdest := parts[0]\n\t\topts := []string{}\n\t\tif len(parts) == 2 {\n\t\t\topts = strings.Split(parts[2], \",\")\n\t\t}\n\t\tmounts[dest] = specs.Mount{Destination: dest, Type: \"tmpfs\", Source: \"tmpfs\", Options: opts}\n\t}\n\tfor _, b := range image.Binds {\n\t\tparts := strings.Split(b, \":\")\n\t\tif len(parts) < 2 {\n\t\t\treturn []byte{}, fmt.Errorf(\"Cannot parse bind, missing ':': %s\", b)\n\t\t}\n\t\tif len(parts) > 3 {\n\t\t\treturn []byte{}, fmt.Errorf(\"Cannot parse bind, too many ':': %s\", b)\n\t\t}\n\t\tsrc := parts[0]\n\t\tdest := parts[1]\n\t\topts := []string{\"rw\", \"rbind\", \"rprivate\"}\n\t\tif len(parts) == 3 {\n\t\t\topts = strings.Split(parts[2], \",\")\n\t\t}\n\t\tmounts[dest] = specs.Mount{Destination: dest, Type: \"bind\", Source: src, Options: opts}\n\t}\n\tfor _, m := range image.Mounts {\n\t\ttp := m.Type\n\t\tsrc := m.Source\n\t\tdest := m.Destination\n\t\topts := m.Options\n\t\tif tp == \"\" {\n\t\t\tswitch src {\n\t\t\tcase \"mqueue\", \"devpts\", \"proc\", \"sysfs\", \"cgroup\":\n\t\t\t\ttp = src\n\t\t\t}\n\t\t}\n\t\tif tp == \"\" && dest == \"\/dev\" {\n\t\t\ttp = \"tmpfs\"\n\t\t}\n\t\tif tp == \"\" {\n\t\t\treturn []byte{}, fmt.Errorf(\"Mount for destination %s is missing type\", dest)\n\t\t}\n\t\tif src == \"\" {\n\t\t\t\/\/ usually sane, eg proc, tmpfs etc\n\t\t\tsrc = tp\n\t\t}\n\t\tif dest == \"\" {\n\t\t\tdest = defaultMountpoint(tp)\n\t\t}\n\t\tif dest == \"\" {\n\t\t\treturn []byte{}, fmt.Errorf(\"Mount type %s is missing destination\", tp)\n\t\t}\n\t\tmounts[dest] = specs.Mount{Destination: dest, Type: tp, Source: src, Options: opts}\n\t}\n\tmountList := mlist{}\n\tfor _, m := range mounts {\n\t\tmountList = append(mountList, m)\n\t}\n\tsort.Sort(mountList)\n\tnamespaces := []specs.LinuxNamespace{}\n\tif image.Net != \"\" && image.Net != \"host\" {\n\t\treturn []byte{}, fmt.Errorf(\"invalid net namespace: %s\", image.Net)\n\t}\n\tif image.Net == \"\" {\n\t\tnamespaces = append(namespaces, specs.LinuxNamespace{Type: specs.NetworkNamespace})\n\t}\n\tif image.Pid != \"\" && image.Pid != \"host\" {\n\t\treturn []byte{}, fmt.Errorf(\"invalid pid namespace: %s\", image.Pid)\n\t}\n\tif image.Pid == \"\" {\n\t\tnamespaces = append(namespaces, specs.LinuxNamespace{Type: specs.PIDNamespace})\n\t}\n\tif image.Ipc != \"\" && image.Ipc != \"host\" {\n\t\treturn []byte{}, fmt.Errorf(\"invalid ipc namespace: %s\", image.Ipc)\n\t}\n\tif image.Ipc == \"\" {\n\t\tnamespaces = append(namespaces, specs.LinuxNamespace{Type: specs.IPCNamespace})\n\t}\n\tif image.Uts != \"\" && image.Uts != \"host\" {\n\t\treturn []byte{}, fmt.Errorf(\"invalid uts namespace: %s\", image.Uts)\n\t}\n\tif image.Uts == \"\" {\n\t\tnamespaces = append(namespaces, specs.LinuxNamespace{Type: specs.UTSNamespace})\n\t}\n\t\/\/ TODO user, cgroup namespaces, maybe mount=host if useful\n\tnamespaces = append(namespaces, specs.LinuxNamespace{Type: specs.MountNamespace})\n\tcaps := image.Capabilities\n\tif len(caps) == 1 && strings.ToLower(caps[0]) == \"all\" {\n\t\tcaps = []string{\n\t\t\t\"CAP_AUDIT_CONTROL\",\n\t\t\t\"CAP_AUDIT_READ\",\n\t\t\t\"CAP_AUDIT_WRITE\",\n\t\t\t\"CAP_BLOCK_SUSPEND\",\n\t\t\t\"CAP_CHOWN\",\n\t\t\t\"CAP_DAC_OVERRIDE\",\n\t\t\t\"CAP_DAC_READ_SEARCH\",\n\t\t\t\"CAP_FOWNER\",\n\t\t\t\"CAP_FSETID\",\n\t\t\t\"CAP_IPC_LOCK\",\n\t\t\t\"CAP_IPC_OWNER\",\n\t\t\t\"CAP_KILL\",\n\t\t\t\"CAP_LEASE\",\n\t\t\t\"CAP_LINUX_IMMUTABLE\",\n\t\t\t\"CAP_MAC_ADMIN\",\n\t\t\t\"CAP_MAC_OVERRIDE\",\n\t\t\t\"CAP_MKNOD\",\n\t\t\t\"CAP_NET_ADMIN\",\n\t\t\t\"CAP_NET_BIND_SERVICE\",\n\t\t\t\"CAP_NET_BROADCAST\",\n\t\t\t\"CAP_NET_RAW\",\n\t\t\t\"CAP_SETFCAP\",\n\t\t\t\"CAP_SETGID\",\n\t\t\t\"CAP_SETPCAP\",\n\t\t\t\"CAP_SETUID\",\n\t\t\t\"CAP_SYSLOG\",\n\t\t\t\"CAP_SYS_ADMIN\",\n\t\t\t\"CAP_SYS_BOOT\",\n\t\t\t\"CAP_SYS_CHROOT\",\n\t\t\t\"CAP_SYS_MODULE\",\n\t\t\t\"CAP_SYS_NICE\",\n\t\t\t\"CAP_SYS_PACCT\",\n\t\t\t\"CAP_SYS_PTRACE\",\n\t\t\t\"CAP_SYS_RAWIO\",\n\t\t\t\"CAP_SYS_RESOURCE\",\n\t\t\t\"CAP_SYS_TIME\",\n\t\t\t\"CAP_SYS_TTY_CONFIG\",\n\t\t\t\"CAP_WAKE_ALARM\",\n\t\t}\n\t}\n\n\toci.Version = specs.Version\n\n\toci.Platform = specs.Platform{\n\t\tOS:   inspect.Os,\n\t\tArch: inspect.Architecture,\n\t}\n\n\toci.Process = specs.Process{\n\t\tTerminal: false,\n\t\t\/\/ConsoleSize\n\t\tUser: specs.User{\n\t\t\tUID:            image.UID,\n\t\t\tGID:            image.GID,\n\t\t\tAdditionalGids: image.AdditionalGids,\n\t\t\t\/\/ Username (Windows)\n\t\t},\n\t\tArgs: args,\n\t\tEnv:  env,\n\t\tCwd:  cwd,\n\t\tCapabilities: &specs.LinuxCapabilities{\n\t\t\tBounding:    caps,\n\t\t\tEffective:   caps,\n\t\t\tInheritable: caps,\n\t\t\tPermitted:   caps,\n\t\t\tAmbient:     []string{},\n\t\t},\n\t\tRlimits:         []specs.LinuxRlimit{},\n\t\tNoNewPrivileges: image.NoNewPrivileges,\n\t\t\/\/ ApparmorProfile\n\t\t\/\/ SelinuxLabel\n\t}\n\n\toci.Root = specs.Root{\n\t\tPath:     \"rootfs\",\n\t\tReadonly: image.Readonly,\n\t}\n\n\toci.Hostname = image.Hostname\n\toci.Mounts = mountList\n\n\toci.Linux = &specs.Linux{\n\t\t\/\/ UIDMappings\n\t\t\/\/ GIDMappings\n\t\t\/\/ Sysctl\n\t\tResources: &specs.LinuxResources{\n\t\t\t\/\/ Devices\n\t\t\tDisableOOMKiller: &image.DisableOOMKiller,\n\t\t\t\/\/ Memory\n\t\t\t\/\/ CPU\n\t\t\t\/\/ Pids\n\t\t\t\/\/ BlockIO\n\t\t\t\/\/ HugepageLimits\n\t\t\t\/\/ Network\n\t\t},\n\t\t\/\/ CgroupsPath\n\t\tNamespaces: namespaces,\n\t\t\/\/ Devices\n\t\t\/\/ Seccomp\n\t\t\/\/ RootfsPropagation\n\t\t\/\/ MaskedPaths\n\t\t\/\/ ReadonlyPaths\n\t\t\/\/ MountLabel\n\t\t\/\/ IntelRdt\n\t}\n\n\treturn json.MarshalIndent(oci, \"\", \"    \")\n}\n\nfunc filesystem(m *Moby) (*bytes.Buffer, error) {\n\tbuf := new(bytes.Buffer)\n\ttw := tar.NewWriter(buf)\n\tdefer tw.Close()\n\n\tlog.Infof(\"Add files:\")\n\tfor _, f := range m.Files {\n\t\tlog.Infof(\"  %s\", f.Path)\n\t\tif f.Path == \"\" {\n\t\t\treturn buf, errors.New(\"Did not specify path for file\")\n\t\t}\n\t\tif f.Contents == \"\" {\n\t\t\treturn buf, errors.New(\"Contents of file not specified\")\n\t\t}\n\t\t\/\/ we need all the leading directories\n\t\tparts := strings.Split(path.Dir(f.Path), \"\/\")\n\t\troot := \"\"\n\t\tfor _, p := range parts {\n\t\t\tif p == \".\" || p == \"\/\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif root == \"\" {\n\t\t\t\troot = p\n\t\t\t} else {\n\t\t\t\troot = root + \"\/\" + p\n\t\t\t}\n\t\t\thdr := &tar.Header{\n\t\t\t\tName:     root,\n\t\t\t\tTypeflag: tar.TypeDir,\n\t\t\t\tMode:     0700,\n\t\t\t}\n\t\t\terr := tw.WriteHeader(hdr)\n\t\t\tif err != nil {\n\t\t\t\treturn buf, err\n\t\t\t}\n\t\t}\n\t\thdr := &tar.Header{\n\t\t\tName: f.Path,\n\t\t\tMode: 0600,\n\t\t\tSize: int64(len(f.Contents)),\n\t\t}\n\t\terr := tw.WriteHeader(hdr)\n\t\tif err != nil {\n\t\t\treturn buf, err\n\t\t}\n\t\t_, err = tw.Write([]byte(f.Contents))\n\t\tif err != nil {\n\t\t\treturn buf, err\n\t\t}\n\t}\n\treturn buf, nil\n}\n<commit_msg>Support creating of directories in files section<commit_after>package main\n\nimport (\n\t\"archive\/tar\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/docker\/engine-api\/types\"\n\t\"github.com\/opencontainers\/runtime-spec\/specs-go\"\n\t\"gopkg.in\/yaml.v2\"\n)\n\n\/\/ Moby is the type of a Moby config file\ntype Moby struct {\n\tKernel struct {\n\t\tImage   string\n\t\tCmdline string\n\t}\n\tInit   string\n\tSystem []MobyImage\n\tDaemon []MobyImage\n\tFiles  []struct {\n\t\tPath      string\n\t\tDirectory bool\n\t\tContents  string\n\t}\n\tOutputs []struct {\n\t\tFormat  string\n\t\tProject string\n\t\tBucket  string\n\t\tFamily  string\n\t\tKeys    string\n\t\tPublic  bool\n\t\tReplace bool\n\t}\n}\n\n\/\/ MobyImage is the type of an image config\ntype MobyImage struct {\n\tName             string\n\tImage            string\n\tCapabilities     []string\n\tMounts           []specs.Mount\n\tBinds            []string\n\tTmpfs            []string\n\tCommand          []string\n\tEnv              []string\n\tCwd              string\n\tNet              string\n\tPid              string\n\tIpc              string\n\tUts              string\n\tReadonly         bool\n\tUID              uint32   `yaml:\"uid\"`\n\tGID              uint32   `yaml:\"gid\"`\n\tAdditionalGids   []uint32 `yaml:\"additionalGids\"`\n\tNoNewPrivileges  bool     `yaml:\"noNewPrivileges\"`\n\tHostname         string\n\tOomScoreAdj      int  `yaml:\"oomScoreAdj\"`\n\tDisableOOMKiller bool `yaml:\"disableOOMKiller\"`\n}\n\n\/\/ NewConfig parses a config file\nfunc NewConfig(config []byte) (*Moby, error) {\n\tm := Moby{}\n\n\terr := yaml.Unmarshal(config, &m)\n\tif err != nil {\n\t\treturn &m, err\n\t}\n\n\treturn &m, nil\n}\n\n\/\/ ConfigToOCI converts a config specification to an OCI config file\nfunc ConfigToOCI(image *MobyImage) ([]byte, error) {\n\n\t\/\/ TODO pass through same docker client to all functions\n\tcli, err := dockerClient()\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tinspect, err := dockerInspectImage(cli, image.Image)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\treturn ConfigInspectToOCI(image, inspect)\n}\n\nfunc defaultMountpoint(tp string) string {\n\tswitch tp {\n\tcase \"proc\":\n\t\treturn \"\/proc\"\n\tcase \"devpts\":\n\t\treturn \"\/dev\/pts\"\n\tcase \"sysfs\":\n\t\treturn \"\/sys\"\n\tcase \"cgroup\":\n\t\treturn \"\/sys\/fs\/cgroup\"\n\tcase \"mqueue\":\n\t\treturn \"\/dev\/mqueue\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\n\/\/ Sort mounts by number of path components so \/dev\/pts is listed after \/dev\ntype mlist []specs.Mount\n\nfunc (m mlist) Len() int {\n\treturn len(m)\n}\nfunc (m mlist) Less(i, j int) bool {\n\treturn m.parts(i) < m.parts(j)\n}\nfunc (m mlist) Swap(i, j int) {\n\tm[i], m[j] = m[j], m[i]\n}\nfunc (m mlist) parts(i int) int {\n\treturn strings.Count(filepath.Clean(m[i].Destination), string(os.PathSeparator))\n}\n\n\/\/ ConfigInspectToOCI converts a config and the output of image inspect to an OCI config file\nfunc ConfigInspectToOCI(image *MobyImage, inspect types.ImageInspect) ([]byte, error) {\n\toci := specs.Spec{}\n\n\tconfig := inspect.Config\n\tif config == nil {\n\t\treturn []byte{}, errors.New(\"empty image config\")\n\t}\n\n\targs := append(config.Entrypoint, config.Cmd...)\n\tif len(image.Command) != 0 {\n\t\targs = image.Command\n\t}\n\tenv := config.Env\n\tif len(image.Env) != 0 {\n\t\tenv = image.Env\n\t}\n\tcwd := config.WorkingDir\n\tif image.Cwd != \"\" {\n\t\tcwd = image.Cwd\n\t}\n\tif cwd == \"\" {\n\t\tcwd = \"\/\"\n\t}\n\t\/\/ default options match what Docker does\n\tprocOptions := []string{\"nosuid\", \"nodev\", \"noexec\", \"relatime\"}\n\tdevOptions := []string{\"nosuid\", \"strictatime\", \"mode=755\", \"size=65536k\"}\n\tif image.Readonly {\n\t\tdevOptions = append(devOptions, \"ro\")\n\t}\n\tptsOptions := []string{\"nosuid\", \"noexec\", \"newinstance\", \"ptmxmode=0666\", \"mode=0620\"}\n\tsysOptions := []string{\"nosuid\", \"noexec\", \"nodev\"}\n\tif image.Readonly {\n\t\tsysOptions = append(sysOptions, \"ro\")\n\t}\n\tcgroupOptions := []string{\"nosuid\", \"noexec\", \"nodev\", \"relatime\", \"ro\"}\n\t\/\/ note omits \"standard\" \/dev\/shm and \/dev\/mqueue\n\tmounts := map[string]specs.Mount{\n\t\t\"\/proc\":          {Destination: \"\/proc\", Type: \"proc\", Source: \"proc\", Options: procOptions},\n\t\t\"\/dev\":           {Destination: \"\/dev\", Type: \"tmpfs\", Source: \"tmpfs\", Options: devOptions},\n\t\t\"\/dev\/pts\":       {Destination: \"\/dev\/pts\", Type: \"devpts\", Source: \"devpts\", Options: ptsOptions},\n\t\t\"\/sys\":           {Destination: \"\/sys\", Type: \"sysfs\", Source: \"sysfs\", Options: sysOptions},\n\t\t\"\/sys\/fs\/cgroup\": {Destination: \"\/sys\/fs\/cgroup\", Type: \"cgroup\", Source: \"cgroup\", Options: cgroupOptions},\n\t}\n\tfor _, t := range image.Tmpfs {\n\t\tparts := strings.Split(t, \":\")\n\t\tif len(parts) > 2 {\n\t\t\treturn []byte{}, fmt.Errorf(\"Cannot parse tmpfs, too many ':': %s\", t)\n\t\t}\n\t\tdest := parts[0]\n\t\topts := []string{}\n\t\tif len(parts) == 2 {\n\t\t\topts = strings.Split(parts[2], \",\")\n\t\t}\n\t\tmounts[dest] = specs.Mount{Destination: dest, Type: \"tmpfs\", Source: \"tmpfs\", Options: opts}\n\t}\n\tfor _, b := range image.Binds {\n\t\tparts := strings.Split(b, \":\")\n\t\tif len(parts) < 2 {\n\t\t\treturn []byte{}, fmt.Errorf(\"Cannot parse bind, missing ':': %s\", b)\n\t\t}\n\t\tif len(parts) > 3 {\n\t\t\treturn []byte{}, fmt.Errorf(\"Cannot parse bind, too many ':': %s\", b)\n\t\t}\n\t\tsrc := parts[0]\n\t\tdest := parts[1]\n\t\topts := []string{\"rw\", \"rbind\", \"rprivate\"}\n\t\tif len(parts) == 3 {\n\t\t\topts = strings.Split(parts[2], \",\")\n\t\t}\n\t\tmounts[dest] = specs.Mount{Destination: dest, Type: \"bind\", Source: src, Options: opts}\n\t}\n\tfor _, m := range image.Mounts {\n\t\ttp := m.Type\n\t\tsrc := m.Source\n\t\tdest := m.Destination\n\t\topts := m.Options\n\t\tif tp == \"\" {\n\t\t\tswitch src {\n\t\t\tcase \"mqueue\", \"devpts\", \"proc\", \"sysfs\", \"cgroup\":\n\t\t\t\ttp = src\n\t\t\t}\n\t\t}\n\t\tif tp == \"\" && dest == \"\/dev\" {\n\t\t\ttp = \"tmpfs\"\n\t\t}\n\t\tif tp == \"\" {\n\t\t\treturn []byte{}, fmt.Errorf(\"Mount for destination %s is missing type\", dest)\n\t\t}\n\t\tif src == \"\" {\n\t\t\t\/\/ usually sane, eg proc, tmpfs etc\n\t\t\tsrc = tp\n\t\t}\n\t\tif dest == \"\" {\n\t\t\tdest = defaultMountpoint(tp)\n\t\t}\n\t\tif dest == \"\" {\n\t\t\treturn []byte{}, fmt.Errorf(\"Mount type %s is missing destination\", tp)\n\t\t}\n\t\tmounts[dest] = specs.Mount{Destination: dest, Type: tp, Source: src, Options: opts}\n\t}\n\tmountList := mlist{}\n\tfor _, m := range mounts {\n\t\tmountList = append(mountList, m)\n\t}\n\tsort.Sort(mountList)\n\tnamespaces := []specs.LinuxNamespace{}\n\tif image.Net != \"\" && image.Net != \"host\" {\n\t\treturn []byte{}, fmt.Errorf(\"invalid net namespace: %s\", image.Net)\n\t}\n\tif image.Net == \"\" {\n\t\tnamespaces = append(namespaces, specs.LinuxNamespace{Type: specs.NetworkNamespace})\n\t}\n\tif image.Pid != \"\" && image.Pid != \"host\" {\n\t\treturn []byte{}, fmt.Errorf(\"invalid pid namespace: %s\", image.Pid)\n\t}\n\tif image.Pid == \"\" {\n\t\tnamespaces = append(namespaces, specs.LinuxNamespace{Type: specs.PIDNamespace})\n\t}\n\tif image.Ipc != \"\" && image.Ipc != \"host\" {\n\t\treturn []byte{}, fmt.Errorf(\"invalid ipc namespace: %s\", image.Ipc)\n\t}\n\tif image.Ipc == \"\" {\n\t\tnamespaces = append(namespaces, specs.LinuxNamespace{Type: specs.IPCNamespace})\n\t}\n\tif image.Uts != \"\" && image.Uts != \"host\" {\n\t\treturn []byte{}, fmt.Errorf(\"invalid uts namespace: %s\", image.Uts)\n\t}\n\tif image.Uts == \"\" {\n\t\tnamespaces = append(namespaces, specs.LinuxNamespace{Type: specs.UTSNamespace})\n\t}\n\t\/\/ TODO user, cgroup namespaces, maybe mount=host if useful\n\tnamespaces = append(namespaces, specs.LinuxNamespace{Type: specs.MountNamespace})\n\tcaps := image.Capabilities\n\tif len(caps) == 1 && strings.ToLower(caps[0]) == \"all\" {\n\t\tcaps = []string{\n\t\t\t\"CAP_AUDIT_CONTROL\",\n\t\t\t\"CAP_AUDIT_READ\",\n\t\t\t\"CAP_AUDIT_WRITE\",\n\t\t\t\"CAP_BLOCK_SUSPEND\",\n\t\t\t\"CAP_CHOWN\",\n\t\t\t\"CAP_DAC_OVERRIDE\",\n\t\t\t\"CAP_DAC_READ_SEARCH\",\n\t\t\t\"CAP_FOWNER\",\n\t\t\t\"CAP_FSETID\",\n\t\t\t\"CAP_IPC_LOCK\",\n\t\t\t\"CAP_IPC_OWNER\",\n\t\t\t\"CAP_KILL\",\n\t\t\t\"CAP_LEASE\",\n\t\t\t\"CAP_LINUX_IMMUTABLE\",\n\t\t\t\"CAP_MAC_ADMIN\",\n\t\t\t\"CAP_MAC_OVERRIDE\",\n\t\t\t\"CAP_MKNOD\",\n\t\t\t\"CAP_NET_ADMIN\",\n\t\t\t\"CAP_NET_BIND_SERVICE\",\n\t\t\t\"CAP_NET_BROADCAST\",\n\t\t\t\"CAP_NET_RAW\",\n\t\t\t\"CAP_SETFCAP\",\n\t\t\t\"CAP_SETGID\",\n\t\t\t\"CAP_SETPCAP\",\n\t\t\t\"CAP_SETUID\",\n\t\t\t\"CAP_SYSLOG\",\n\t\t\t\"CAP_SYS_ADMIN\",\n\t\t\t\"CAP_SYS_BOOT\",\n\t\t\t\"CAP_SYS_CHROOT\",\n\t\t\t\"CAP_SYS_MODULE\",\n\t\t\t\"CAP_SYS_NICE\",\n\t\t\t\"CAP_SYS_PACCT\",\n\t\t\t\"CAP_SYS_PTRACE\",\n\t\t\t\"CAP_SYS_RAWIO\",\n\t\t\t\"CAP_SYS_RESOURCE\",\n\t\t\t\"CAP_SYS_TIME\",\n\t\t\t\"CAP_SYS_TTY_CONFIG\",\n\t\t\t\"CAP_WAKE_ALARM\",\n\t\t}\n\t}\n\n\toci.Version = specs.Version\n\n\toci.Platform = specs.Platform{\n\t\tOS:   inspect.Os,\n\t\tArch: inspect.Architecture,\n\t}\n\n\toci.Process = specs.Process{\n\t\tTerminal: false,\n\t\t\/\/ConsoleSize\n\t\tUser: specs.User{\n\t\t\tUID:            image.UID,\n\t\t\tGID:            image.GID,\n\t\t\tAdditionalGids: image.AdditionalGids,\n\t\t\t\/\/ Username (Windows)\n\t\t},\n\t\tArgs: args,\n\t\tEnv:  env,\n\t\tCwd:  cwd,\n\t\tCapabilities: &specs.LinuxCapabilities{\n\t\t\tBounding:    caps,\n\t\t\tEffective:   caps,\n\t\t\tInheritable: caps,\n\t\t\tPermitted:   caps,\n\t\t\tAmbient:     []string{},\n\t\t},\n\t\tRlimits:         []specs.LinuxRlimit{},\n\t\tNoNewPrivileges: image.NoNewPrivileges,\n\t\t\/\/ ApparmorProfile\n\t\t\/\/ SelinuxLabel\n\t}\n\n\toci.Root = specs.Root{\n\t\tPath:     \"rootfs\",\n\t\tReadonly: image.Readonly,\n\t}\n\n\toci.Hostname = image.Hostname\n\toci.Mounts = mountList\n\n\toci.Linux = &specs.Linux{\n\t\t\/\/ UIDMappings\n\t\t\/\/ GIDMappings\n\t\t\/\/ Sysctl\n\t\tResources: &specs.LinuxResources{\n\t\t\t\/\/ Devices\n\t\t\tDisableOOMKiller: &image.DisableOOMKiller,\n\t\t\t\/\/ Memory\n\t\t\t\/\/ CPU\n\t\t\t\/\/ Pids\n\t\t\t\/\/ BlockIO\n\t\t\t\/\/ HugepageLimits\n\t\t\t\/\/ Network\n\t\t},\n\t\t\/\/ CgroupsPath\n\t\tNamespaces: namespaces,\n\t\t\/\/ Devices\n\t\t\/\/ Seccomp\n\t\t\/\/ RootfsPropagation\n\t\t\/\/ MaskedPaths\n\t\t\/\/ ReadonlyPaths\n\t\t\/\/ MountLabel\n\t\t\/\/ IntelRdt\n\t}\n\n\treturn json.MarshalIndent(oci, \"\", \"    \")\n}\n\nfunc filesystem(m *Moby) (*bytes.Buffer, error) {\n\tbuf := new(bytes.Buffer)\n\ttw := tar.NewWriter(buf)\n\tdefer tw.Close()\n\n\tlog.Infof(\"Add files:\")\n\tfor _, f := range m.Files {\n\t\tlog.Infof(\"  %s\", f.Path)\n\t\tif f.Path == \"\" {\n\t\t\treturn buf, errors.New(\"Did not specify path for file\")\n\t\t}\n\t\tif !f.Directory && f.Contents == \"\" {\n\t\t\treturn buf, errors.New(\"Contents of file not specified\")\n\t\t}\n\t\t\/\/ we need all the leading directories\n\t\tparts := strings.Split(path.Dir(f.Path), \"\/\")\n\t\troot := \"\"\n\t\tfor _, p := range parts {\n\t\t\tif p == \".\" || p == \"\/\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif root == \"\" {\n\t\t\t\troot = p\n\t\t\t} else {\n\t\t\t\troot = root + \"\/\" + p\n\t\t\t}\n\t\t\thdr := &tar.Header{\n\t\t\t\tName:     root,\n\t\t\t\tTypeflag: tar.TypeDir,\n\t\t\t\tMode:     0700,\n\t\t\t}\n\t\t\terr := tw.WriteHeader(hdr)\n\t\t\tif err != nil {\n\t\t\t\treturn buf, err\n\t\t\t}\n\t\t}\n\n\t\tif f.Directory {\n\t\t\tif f.Contents != \"\" {\n\t\t\t\treturn buf, errors.New(\"Directory with contents not allowed\")\n\t\t\t}\n\t\t\thdr := &tar.Header{\n\t\t\t\tName:     f.Path,\n\t\t\t\tTypeflag: tar.TypeDir,\n\t\t\t\tMode:     0700,\n\t\t\t}\n\t\t\terr := tw.WriteHeader(hdr)\n\t\t\tif err != nil {\n\t\t\t\treturn buf, err\n\t\t\t}\n\t\t} else {\n\t\t\thdr := &tar.Header{\n\t\t\t\tName: f.Path,\n\t\t\t\tMode: 0600,\n\t\t\t\tSize: int64(len(f.Contents)),\n\t\t\t}\n\t\t\terr := tw.WriteHeader(hdr)\n\t\t\tif err != nil {\n\t\t\t\treturn buf, err\n\t\t\t}\n\t\t\t_, err = tw.Write([]byte(f.Contents))\n\t\t\tif err != nil {\n\t\t\t\treturn buf, err\n\t\t\t}\n\t\t}\n\t}\n\treturn buf, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package transfer\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"hash\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"github.com\/github\/git-lfs\/errutil\"\n\t\"github.com\/github\/git-lfs\/httputil\"\n\t\"github.com\/github\/git-lfs\/localstorage\"\n\t\"github.com\/github\/git-lfs\/tools\"\n\t\"github.com\/rubyist\/tracerx\"\n)\n\n\/\/ Adapter for basic HTTP downloads, includes resuming via HTTP Range\ntype basicDownloadAdapter struct {\n\t*adapterBase\n}\n\nfunc (a *basicDownloadAdapter) ClearTempStorage() error {\n\treturn os.RemoveAll(a.tempDir())\n}\n\nfunc (a *basicDownloadAdapter) tempDir() string {\n\t\/\/ Must be dedicated to this adapter as deleted by ClearTempStorage\n\t\/\/ Also make local to this repo not global, and separate to localstorage temp,\n\t\/\/ which gets cleared at the end of every invocation\n\td := filepath.Join(localstorage.Objects().RootDir, \"incomplete\")\n\tif err := os.MkdirAll(d, 0755); err != nil {\n\t\treturn os.TempDir()\n\t}\n\treturn d\n}\n\nfunc (a *basicDownloadAdapter) DoTransfer(t *Transfer, cb TransferProgressCallback, authOkFunc func()) error {\n\n\tf, fromByte, hashSoFar, err := a.checkResumeDownload(t)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn a.download(t, cb, authOkFunc, f, fromByte, hashSoFar)\n}\n\n\/\/ Checks to see if a download can be resumed, and if so returns a non-nil locked file, byte start and hash\nfunc (a *basicDownloadAdapter) checkResumeDownload(t *Transfer) (outFile *os.File, fromByte int64, hashSoFar hash.Hash, e error) {\n\t\/\/ lock the file by opening it for read\/write, rather than checking Stat() etc\n\t\/\/ which could be subject to race conditions by other processes\n\tf, err := os.OpenFile(a.downloadFilename(t), os.O_RDWR, 0644)\n\n\tif err != nil {\n\t\t\/\/ Create a new file instead, must not already exist or error (permissions \/ race condition)\n\t\tnewfile, err := os.OpenFile(a.downloadFilename(t), os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0644)\n\t\treturn newfile, 0, nil, err\n\t}\n\n\t\/\/ Successfully opened an existing file at this point\n\t\/\/ Read any existing data into hash then return file handle at end\n\thash := tools.NewLfsContentHash()\n\tn, err := io.Copy(hash, f)\n\tif err != nil {\n\t\tf.Close()\n\t\treturn nil, 0, nil, err\n\t}\n\ttracerx.Printf(\"xfer: Attempting to resume download of %q from byte %d\", t.Object.Oid, n)\n\treturn f, n, hash, nil\n\n}\n\n\/\/ Create or open a download file for resuming\nfunc (a *basicDownloadAdapter) downloadFilename(t *Transfer) string {\n\t\/\/ Not a temp file since we will be resuming it\n\treturn filepath.Join(a.tempDir(), t.Object.Oid+\".tmp\")\n}\n\n\/\/ download starts or resumes and download. Always closes dlFile if non-nil\nfunc (a *basicDownloadAdapter) download(t *Transfer, cb TransferProgressCallback, authOkFunc func(), dlFile *os.File, fromByte int64, hash hash.Hash) error {\n\n\tif dlFile != nil {\n\t\t\/\/ ensure we always close dlFile. Note that this does not conflict with the\n\t\t\/\/ early close below, as close is idempotent.\n\t\tdefer dlFile.Close()\n\t}\n\n\trel, ok := t.Object.Rel(\"download\")\n\tif !ok {\n\t\treturn errors.New(\"Object not found on the server.\")\n\t}\n\n\treq, err := httputil.NewHttpRequest(\"GET\", rel.Href, rel.Header)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif fromByte > 0 {\n\t\tif dlFile == nil || hash == nil {\n\t\t\treturn fmt.Errorf(\"Cannot restart %v from %d without a file & hash\", t.Object.Oid, fromByte)\n\t\t}\n\t\t\/\/ We could just use a start byte, but since we know the length be specific\n\t\treq.Header.Set(\"Range\", fmt.Sprintf(\"bytes=%d-%d\", fromByte, t.Object.Size))\n\t}\n\n\tres, err := httputil.DoHttpRequest(req, true)\n\tif err != nil {\n\t\t\/\/ Special-case status code 416 () - fall back\n\t\tif fromByte > 0 && dlFile != nil && res.StatusCode == 416 {\n\t\t\ttracerx.Printf(\"xfer: server rejected resume download request for %q from byte %d; re-downloading from start\", t.Object.Oid, fromByte)\n\t\t\tdlFile.Close()\n\t\t\tos.Remove(dlFile.Name())\n\t\t\treturn a.download(t, cb, authOkFunc, nil, 0, nil)\n\t\t}\n\t\treturn errutil.NewRetriableError(err)\n\t}\n\thttputil.LogTransfer(\"lfs.data.download\", res)\n\tdefer res.Body.Close()\n\n\t\/\/ Range request must return 206 & content range to confirm\n\tif fromByte > 0 {\n\t\trangeRequestOk := false\n\t\tvar failReason string\n\t\t\/\/ check 206 and Content-Range, fall back if either not as expected\n\t\tif res.StatusCode == 206 {\n\t\t\t\/\/ Probably a successful range request, check Content-Range\n\t\t\tif rangeHdr := res.Header.Get(\"Content-Range\"); rangeHdr != \"\" {\n\t\t\t\tregex := regexp.MustCompile(`bytes (\\d+)\\-.*`)\n\t\t\t\tmatch := regex.FindStringSubmatch(rangeHdr)\n\t\t\t\tif match != nil && len(match) > 1 {\n\t\t\t\t\tcontentStart, _ := strconv.ParseInt(match[1], 10, 64)\n\t\t\t\t\tif contentStart == fromByte {\n\t\t\t\t\t\trangeRequestOk = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfailReason = fmt.Sprintf(\"Content-Range start byte incorrect: %s expected %d\", match[1], fromByte)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfailReason = fmt.Sprintf(\"badly formatted Content-Range header: %q\", rangeHdr)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfailReason = \"missing Content-Range header in response\"\n\t\t\t}\n\t\t} else {\n\t\t\tfailReason = fmt.Sprintf(\"expected status code 206, received %d\", res.StatusCode)\n\t\t}\n\t\tif rangeRequestOk {\n\t\t\ttracerx.Printf(\"xfer: server accepted resume download request: %q from byte %d\", t.Object.Oid, fromByte)\n\t\t\t\/\/ Advance progress callback; must split into max int sizes though\n\t\t\tconst maxInt = int(^uint(0) >> 1)\n\t\t\tfor read := int64(0); read < fromByte; {\n\t\t\t\tremainder := fromByte - read\n\t\t\t\tif remainder > int64(maxInt) {\n\t\t\t\t\tread += int64(maxInt)\n\t\t\t\t\tcb(t.Name, t.Object.Size, read, maxInt)\n\t\t\t\t} else {\n\t\t\t\t\tread += remainder\n\t\t\t\t\tcb(t.Name, t.Object.Size, read, int(remainder))\n\t\t\t\t}\n\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Abort resume, perform regular download\n\t\t\ttracerx.Printf(\"xfer: failed to resume download for %q from byte %d: %s. Re-downloading from start\", t.Object.Oid, fromByte, failReason)\n\t\t\tdlFile.Close()\n\t\t\tos.Remove(dlFile.Name())\n\t\t\tif res.StatusCode == 200 {\n\t\t\t\t\/\/ If status code was 200 then server just ignored Range header and\n\t\t\t\t\/\/ sent everything. Don't re-request, use this one from byte 0\n\t\t\t\tdlFile = nil\n\t\t\t\tfromByte = 0\n\t\t\t\thash = nil\n\t\t\t} else {\n\t\t\t\t\/\/ re-request needed\n\t\t\t\treturn a.download(t, cb, authOkFunc, nil, 0, nil)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Signal auth OK on success response, before starting download to free up\n\t\/\/ other workers immediately\n\tif authOkFunc != nil {\n\t\tauthOkFunc()\n\t}\n\n\tvar hasher *tools.HashingReader\n\tif fromByte > 0 && hash != nil {\n\t\t\/\/ pre-load hashing reader with previous content\n\t\thasher = tools.NewHashingReaderPreloadHash(res.Body, hash)\n\t} else {\n\t\thasher = tools.NewHashingReader(res.Body)\n\t}\n\n\tif dlFile == nil {\n\t\t\/\/ New file start\n\t\tdlFile, err = os.OpenFile(a.downloadFilename(t), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer dlFile.Close()\n\t}\n\tdlfilename := dlFile.Name()\n\t\/\/ Wrap callback to give name context\n\tccb := func(totalSize int64, readSoFar int64, readSinceLast int) error {\n\t\tif cb != nil {\n\t\t\treturn cb(t.Name, totalSize, readSoFar+fromByte, readSinceLast)\n\t\t}\n\t\treturn nil\n\t}\n\twritten, err := tools.CopyWithCallback(dlFile, hasher, res.ContentLength, ccb)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot write data to tempfile %q: %v\", dlfilename, err)\n\t}\n\tif err := dlFile.Close(); err != nil {\n\t\treturn fmt.Errorf(\"can't close tempfile %q: %v\", dlfilename, err)\n\t}\n\n\tif actual := hasher.Hash(); actual != t.Object.Oid {\n\t\treturn fmt.Errorf(\"Expected OID %s, got %s after %d bytes written\", t.Object.Oid, actual, written)\n\t}\n\n\treturn tools.RenameFileCopyPermissions(dlfilename, t.Path)\n\n}\n\nfunc init() {\n\tnewfunc := func(name string, dir Direction) TransferAdapter {\n\t\tswitch dir {\n\t\tcase Download:\n\t\t\tbd := &basicDownloadAdapter{newAdapterBase(name, dir, nil)}\n\t\t\t\/\/ self implements impl\n\t\t\tbd.transferImpl = bd\n\t\t\treturn bd\n\t\tcase Upload:\n\t\t\tpanic(\"Should never ask this func to upload\")\n\t\t}\n\t\treturn nil\n\t}\n\tRegisterNewTransferAdapterFunc(BasicAdapterName, Download, newfunc)\n}\n<commit_msg>Check callback is present before skipping it forward when resuming<commit_after>package transfer\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"hash\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"github.com\/github\/git-lfs\/errutil\"\n\t\"github.com\/github\/git-lfs\/httputil\"\n\t\"github.com\/github\/git-lfs\/localstorage\"\n\t\"github.com\/github\/git-lfs\/tools\"\n\t\"github.com\/rubyist\/tracerx\"\n)\n\n\/\/ Adapter for basic HTTP downloads, includes resuming via HTTP Range\ntype basicDownloadAdapter struct {\n\t*adapterBase\n}\n\nfunc (a *basicDownloadAdapter) ClearTempStorage() error {\n\treturn os.RemoveAll(a.tempDir())\n}\n\nfunc (a *basicDownloadAdapter) tempDir() string {\n\t\/\/ Must be dedicated to this adapter as deleted by ClearTempStorage\n\t\/\/ Also make local to this repo not global, and separate to localstorage temp,\n\t\/\/ which gets cleared at the end of every invocation\n\td := filepath.Join(localstorage.Objects().RootDir, \"incomplete\")\n\tif err := os.MkdirAll(d, 0755); err != nil {\n\t\treturn os.TempDir()\n\t}\n\treturn d\n}\n\nfunc (a *basicDownloadAdapter) DoTransfer(t *Transfer, cb TransferProgressCallback, authOkFunc func()) error {\n\n\tf, fromByte, hashSoFar, err := a.checkResumeDownload(t)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn a.download(t, cb, authOkFunc, f, fromByte, hashSoFar)\n}\n\n\/\/ Checks to see if a download can be resumed, and if so returns a non-nil locked file, byte start and hash\nfunc (a *basicDownloadAdapter) checkResumeDownload(t *Transfer) (outFile *os.File, fromByte int64, hashSoFar hash.Hash, e error) {\n\t\/\/ lock the file by opening it for read\/write, rather than checking Stat() etc\n\t\/\/ which could be subject to race conditions by other processes\n\tf, err := os.OpenFile(a.downloadFilename(t), os.O_RDWR, 0644)\n\n\tif err != nil {\n\t\t\/\/ Create a new file instead, must not already exist or error (permissions \/ race condition)\n\t\tnewfile, err := os.OpenFile(a.downloadFilename(t), os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0644)\n\t\treturn newfile, 0, nil, err\n\t}\n\n\t\/\/ Successfully opened an existing file at this point\n\t\/\/ Read any existing data into hash then return file handle at end\n\thash := tools.NewLfsContentHash()\n\tn, err := io.Copy(hash, f)\n\tif err != nil {\n\t\tf.Close()\n\t\treturn nil, 0, nil, err\n\t}\n\ttracerx.Printf(\"xfer: Attempting to resume download of %q from byte %d\", t.Object.Oid, n)\n\treturn f, n, hash, nil\n\n}\n\n\/\/ Create or open a download file for resuming\nfunc (a *basicDownloadAdapter) downloadFilename(t *Transfer) string {\n\t\/\/ Not a temp file since we will be resuming it\n\treturn filepath.Join(a.tempDir(), t.Object.Oid+\".tmp\")\n}\n\n\/\/ download starts or resumes and download. Always closes dlFile if non-nil\nfunc (a *basicDownloadAdapter) download(t *Transfer, cb TransferProgressCallback, authOkFunc func(), dlFile *os.File, fromByte int64, hash hash.Hash) error {\n\n\tif dlFile != nil {\n\t\t\/\/ ensure we always close dlFile. Note that this does not conflict with the\n\t\t\/\/ early close below, as close is idempotent.\n\t\tdefer dlFile.Close()\n\t}\n\n\trel, ok := t.Object.Rel(\"download\")\n\tif !ok {\n\t\treturn errors.New(\"Object not found on the server.\")\n\t}\n\n\treq, err := httputil.NewHttpRequest(\"GET\", rel.Href, rel.Header)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif fromByte > 0 {\n\t\tif dlFile == nil || hash == nil {\n\t\t\treturn fmt.Errorf(\"Cannot restart %v from %d without a file & hash\", t.Object.Oid, fromByte)\n\t\t}\n\t\t\/\/ We could just use a start byte, but since we know the length be specific\n\t\treq.Header.Set(\"Range\", fmt.Sprintf(\"bytes=%d-%d\", fromByte, t.Object.Size))\n\t}\n\n\tres, err := httputil.DoHttpRequest(req, true)\n\tif err != nil {\n\t\t\/\/ Special-case status code 416 () - fall back\n\t\tif fromByte > 0 && dlFile != nil && res.StatusCode == 416 {\n\t\t\ttracerx.Printf(\"xfer: server rejected resume download request for %q from byte %d; re-downloading from start\", t.Object.Oid, fromByte)\n\t\t\tdlFile.Close()\n\t\t\tos.Remove(dlFile.Name())\n\t\t\treturn a.download(t, cb, authOkFunc, nil, 0, nil)\n\t\t}\n\t\treturn errutil.NewRetriableError(err)\n\t}\n\thttputil.LogTransfer(\"lfs.data.download\", res)\n\tdefer res.Body.Close()\n\n\t\/\/ Range request must return 206 & content range to confirm\n\tif fromByte > 0 {\n\t\trangeRequestOk := false\n\t\tvar failReason string\n\t\t\/\/ check 206 and Content-Range, fall back if either not as expected\n\t\tif res.StatusCode == 206 {\n\t\t\t\/\/ Probably a successful range request, check Content-Range\n\t\t\tif rangeHdr := res.Header.Get(\"Content-Range\"); rangeHdr != \"\" {\n\t\t\t\tregex := regexp.MustCompile(`bytes (\\d+)\\-.*`)\n\t\t\t\tmatch := regex.FindStringSubmatch(rangeHdr)\n\t\t\t\tif match != nil && len(match) > 1 {\n\t\t\t\t\tcontentStart, _ := strconv.ParseInt(match[1], 10, 64)\n\t\t\t\t\tif contentStart == fromByte {\n\t\t\t\t\t\trangeRequestOk = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfailReason = fmt.Sprintf(\"Content-Range start byte incorrect: %s expected %d\", match[1], fromByte)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfailReason = fmt.Sprintf(\"badly formatted Content-Range header: %q\", rangeHdr)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfailReason = \"missing Content-Range header in response\"\n\t\t\t}\n\t\t} else {\n\t\t\tfailReason = fmt.Sprintf(\"expected status code 206, received %d\", res.StatusCode)\n\t\t}\n\t\tif rangeRequestOk {\n\t\t\ttracerx.Printf(\"xfer: server accepted resume download request: %q from byte %d\", t.Object.Oid, fromByte)\n\t\t\t\/\/ Advance progress callback; must split into max int sizes though\n\t\t\tif cb != nil {\n\t\t\t\tconst maxInt = int(^uint(0) >> 1)\n\t\t\t\tfor read := int64(0); read < fromByte; {\n\t\t\t\t\tremainder := fromByte - read\n\t\t\t\t\tif remainder > int64(maxInt) {\n\t\t\t\t\t\tread += int64(maxInt)\n\t\t\t\t\t\tcb(t.Name, t.Object.Size, read, maxInt)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tread += remainder\n\t\t\t\t\t\tcb(t.Name, t.Object.Size, read, int(remainder))\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Abort resume, perform regular download\n\t\t\ttracerx.Printf(\"xfer: failed to resume download for %q from byte %d: %s. Re-downloading from start\", t.Object.Oid, fromByte, failReason)\n\t\t\tdlFile.Close()\n\t\t\tos.Remove(dlFile.Name())\n\t\t\tif res.StatusCode == 200 {\n\t\t\t\t\/\/ If status code was 200 then server just ignored Range header and\n\t\t\t\t\/\/ sent everything. Don't re-request, use this one from byte 0\n\t\t\t\tdlFile = nil\n\t\t\t\tfromByte = 0\n\t\t\t\thash = nil\n\t\t\t} else {\n\t\t\t\t\/\/ re-request needed\n\t\t\t\treturn a.download(t, cb, authOkFunc, nil, 0, nil)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Signal auth OK on success response, before starting download to free up\n\t\/\/ other workers immediately\n\tif authOkFunc != nil {\n\t\tauthOkFunc()\n\t}\n\n\tvar hasher *tools.HashingReader\n\tif fromByte > 0 && hash != nil {\n\t\t\/\/ pre-load hashing reader with previous content\n\t\thasher = tools.NewHashingReaderPreloadHash(res.Body, hash)\n\t} else {\n\t\thasher = tools.NewHashingReader(res.Body)\n\t}\n\n\tif dlFile == nil {\n\t\t\/\/ New file start\n\t\tdlFile, err = os.OpenFile(a.downloadFilename(t), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer dlFile.Close()\n\t}\n\tdlfilename := dlFile.Name()\n\t\/\/ Wrap callback to give name context\n\tccb := func(totalSize int64, readSoFar int64, readSinceLast int) error {\n\t\tif cb != nil {\n\t\t\treturn cb(t.Name, totalSize, readSoFar+fromByte, readSinceLast)\n\t\t}\n\t\treturn nil\n\t}\n\twritten, err := tools.CopyWithCallback(dlFile, hasher, res.ContentLength, ccb)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot write data to tempfile %q: %v\", dlfilename, err)\n\t}\n\tif err := dlFile.Close(); err != nil {\n\t\treturn fmt.Errorf(\"can't close tempfile %q: %v\", dlfilename, err)\n\t}\n\n\tif actual := hasher.Hash(); actual != t.Object.Oid {\n\t\treturn fmt.Errorf(\"Expected OID %s, got %s after %d bytes written\", t.Object.Oid, actual, written)\n\t}\n\n\treturn tools.RenameFileCopyPermissions(dlfilename, t.Path)\n\n}\n\nfunc init() {\n\tnewfunc := func(name string, dir Direction) TransferAdapter {\n\t\tswitch dir {\n\t\tcase Download:\n\t\t\tbd := &basicDownloadAdapter{newAdapterBase(name, dir, nil)}\n\t\t\t\/\/ self implements impl\n\t\t\tbd.transferImpl = bd\n\t\t\treturn bd\n\t\tcase Upload:\n\t\t\tpanic(\"Should never ask this func to upload\")\n\t\t}\n\t\treturn nil\n\t}\n\tRegisterNewTransferAdapterFunc(BasicAdapterName, Download, newfunc)\n}\n<|endoftext|>"}
{"text":"<commit_before>package doozer\n\nimport (\n\t\"doozer\/client\"\n\t\"exec\"\n\t\"github.com\/bmizerany\/assert\"\n\t\"net\"\n\t\"runtime\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/ Upper bound on number of leaked goroutines.\n\/\/ Our goal is to reduce this to zero.\nconst leaked = 23\n\nfunc mustListen() net.Listener {\n\tl, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn l\n}\n\nfunc mustListenPacket(addr string) net.PacketConn {\n\tc, err := net.ListenPacket(\"udp\", addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn c\n}\n\nfunc TestDoozerSimple(t *testing.T) {\n\tl := mustListen()\n\tdefer l.Close()\n\tu := mustListenPacket(l.Addr().String())\n\tdefer u.Close()\n\n\tgo Main(\"a\", \"\", u, l, nil)\n\n\tcl, err := client.Dial(l.Addr().String())\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, nil, cl.Noop())\n}\n\nfunc TestDoozerWatchSimple(t *testing.T) {\n\tl := mustListen()\n\tdefer l.Close()\n\tu := mustListenPacket(l.Addr().String())\n\tdefer u.Close()\n\n\tgo Main(\"a\", \"\", u, l, nil)\n\n\tcl, err := client.Dial(l.Addr().String())\n\tassert.Equal(t, nil, err)\n\n\tch, err := cl.Watch(\"\/test\/**\")\n\tassert.Equal(t, nil, err, err)\n\tdefer close(ch)\n\n\tcl.Set(\"\/test\/foo\", \"bar\", \"\")\n\tev := <-ch\n\tassert.Equal(t, \"\/test\/foo\", ev.Path)\n\tassert.Equal(t, \"bar\", ev.Body)\n\tassert.NotEqual(t, \"\", ev.Cas)\n\n\tcl.Set(\"\/test\/fun\", \"house\", \"\")\n\tev = <-ch\n\tassert.Equal(t, \"\/test\/fun\", ev.Path)\n\tassert.Equal(t, \"house\", ev.Body)\n\tassert.NotEqual(t, \"\", ev.Cas)\n}\n\nfunc mustRunDoozer(listen, web, attach string) *exec.Cmd {\n\texe, err := exec.LookPath(\"doozerd\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\targs := []string{\n\t\t\"doozerd\",\n\t\t\"-l=127.0.0.1:\"+listen,\n\t\t\"-w=127.0.0.1:\"+web,\n\t}\n\n\tif attach != \"\" {\n\t\targs = append(args, \"-a\", \"127.0.0.1:\"+attach)\n\t}\n\n\tcmd, err := exec.Run(\n\t\texe,\n\t\targs,\n\t\tnil,\n\t\t\".\",\n\t\texec.PassThrough,\n\t\texec.PassThrough,\n\t\texec.PassThrough,\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn cmd\n}\n\nfunc TestDoozerNodeFailure(t *testing.T) {\n\td1 := mustRunDoozer(\"8046\", \"8080\", \"\")\n\tdefer syscall.Kill(d1.Pid, 9)\n\n\ttime.Sleep(1e9)\n\n\td2 := mustRunDoozer(\"8047\", \"8081\", \"8046\")\n\tdefer syscall.Kill(d2.Pid, 9)\n\td3 := mustRunDoozer(\"8048\", \"8082\", \"8046\")\n\tdefer syscall.Kill(d3.Pid, 9)\n\n\tcl, err := client.Dial(\"127.0.0.1:8046\")\n\tassert.Equal(t, nil, err)\n\n\tch, err := cl.Watch(\"\/doozer\/slot\/*\")\n\tassert.Equal(t, nil, err)\n\n\tcl.Set(\"\/doozer\/slot\/2\", \"\", \"\")\n\t<-ch; <-ch\n\tcl.Set(\"\/doozer\/slot\/3\", \"\", \"\")\n\t<-ch; <-ch\n\n\t\/\/ Give doozer time to get through initial Nops\n\ttime.Sleep(1e9*5)\n\n\t\/\/ Kill an attached doozer\n\tsyscall.Kill(d2.Pid, 9)\n\n\n\t\/\/ We should get something here\n\tev := <-ch\n\tassert.NotEqual(t, nil, ev)\n\n\tfor i := 0; i < 1000; i++ {\n\t\tcl.Noop()\n\t}\n}\n\nfunc TestDoozerGoroutines(t *testing.T) {\n\tgs := runtime.Goroutines()\n\n\tfunc() {\n\t\tl := mustListen()\n\t\tdefer l.Close()\n\t\tu := mustListenPacket(l.Addr().String())\n\t\tdefer u.Close()\n\n\t\tgo Main(\"a\", \"\", u, l, nil)\n\n\t\tcl, err := client.Dial(l.Addr().String())\n\t\tassert.Equal(t, nil, err)\n\t\tcl.Noop()\n\t}()\n\n\tassert.T(t, gs+leaked >= runtime.Goroutines(), gs+leaked)\n}\n<commit_msg>fail test: sleep 1m<commit_after>package doozer\n\nimport (\n\t\"doozer\/client\"\n\t\"exec\"\n\t\"github.com\/bmizerany\/assert\"\n\t\"net\"\n\t\"runtime\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/ Upper bound on number of leaked goroutines.\n\/\/ Our goal is to reduce this to zero.\nconst leaked = 23\n\nfunc mustListen() net.Listener {\n\tl, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn l\n}\n\nfunc mustListenPacket(addr string) net.PacketConn {\n\tc, err := net.ListenPacket(\"udp\", addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn c\n}\n\nfunc TestDoozerSimple(t *testing.T) {\n\tl := mustListen()\n\tdefer l.Close()\n\tu := mustListenPacket(l.Addr().String())\n\tdefer u.Close()\n\n\tgo Main(\"a\", \"\", u, l, nil)\n\n\tcl, err := client.Dial(l.Addr().String())\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, nil, cl.Noop())\n}\n\nfunc TestDoozerWatchSimple(t *testing.T) {\n\tl := mustListen()\n\tdefer l.Close()\n\tu := mustListenPacket(l.Addr().String())\n\tdefer u.Close()\n\n\tgo Main(\"a\", \"\", u, l, nil)\n\n\tcl, err := client.Dial(l.Addr().String())\n\tassert.Equal(t, nil, err)\n\n\tch, err := cl.Watch(\"\/test\/**\")\n\tassert.Equal(t, nil, err, err)\n\tdefer close(ch)\n\n\tcl.Set(\"\/test\/foo\", \"bar\", \"\")\n\tev := <-ch\n\tassert.Equal(t, \"\/test\/foo\", ev.Path)\n\tassert.Equal(t, \"bar\", ev.Body)\n\tassert.NotEqual(t, \"\", ev.Cas)\n\n\tcl.Set(\"\/test\/fun\", \"house\", \"\")\n\tev = <-ch\n\tassert.Equal(t, \"\/test\/fun\", ev.Path)\n\tassert.Equal(t, \"house\", ev.Body)\n\tassert.NotEqual(t, \"\", ev.Cas)\n}\n\nfunc mustRunDoozer(listen, web, attach string) *exec.Cmd {\n\texe, err := exec.LookPath(\"doozerd\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\targs := []string{\n\t\t\"doozerd\",\n\t\t\"-l=127.0.0.1:\"+listen,\n\t\t\"-w=127.0.0.1:\"+web,\n\t}\n\n\tif attach != \"\" {\n\t\targs = append(args, \"-a\", \"127.0.0.1:\"+attach)\n\t}\n\n\tcmd, err := exec.Run(\n\t\texe,\n\t\targs,\n\t\tnil,\n\t\t\".\",\n\t\texec.PassThrough,\n\t\texec.PassThrough,\n\t\texec.PassThrough,\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn cmd\n}\n\nfunc TestDoozerNodeFailure(t *testing.T) {\n\td1 := mustRunDoozer(\"8046\", \"8080\", \"\")\n\tdefer syscall.Kill(d1.Pid, 9)\n\n\ttime.Sleep(1e9)\n\n\td2 := mustRunDoozer(\"8047\", \"8081\", \"8046\")\n\tdefer syscall.Kill(d2.Pid, 9)\n\td3 := mustRunDoozer(\"8048\", \"8082\", \"8046\")\n\tdefer syscall.Kill(d3.Pid, 9)\n\n\tcl, err := client.Dial(\"127.0.0.1:8046\")\n\tassert.Equal(t, nil, err)\n\n\tch, err := cl.Watch(\"\/doozer\/slot\/*\")\n\tassert.Equal(t, nil, err)\n\n\tcl.Set(\"\/doozer\/slot\/2\", \"\", \"\")\n\t<-ch; <-ch\n\tcl.Set(\"\/doozer\/slot\/3\", \"\", \"\")\n\t<-ch; <-ch\n\n\t\/\/ Give doozer time to get through initial Nops\n\ttime.Sleep(1e9*60)\n\n\t\/\/ Kill an attached doozer\n\tsyscall.Kill(d2.Pid, 9)\n\n\n\t\/\/ We should get something here\n\tev := <-ch\n\tassert.NotEqual(t, nil, ev)\n\n\tfor i := 0; i < 1000; i++ {\n\t\tcl.Noop()\n\t}\n}\n\nfunc TestDoozerGoroutines(t *testing.T) {\n\tgs := runtime.Goroutines()\n\n\tfunc() {\n\t\tl := mustListen()\n\t\tdefer l.Close()\n\t\tu := mustListenPacket(l.Addr().String())\n\t\tdefer u.Close()\n\n\t\tgo Main(\"a\", \"\", u, l, nil)\n\n\t\tcl, err := client.Dial(l.Addr().String())\n\t\tassert.Equal(t, nil, err)\n\t\tcl.Noop()\n\t}()\n\n\tassert.T(t, gs+leaked >= runtime.Goroutines(), gs+leaked)\n}\n<|endoftext|>"}
{"text":"<commit_before>package test\n\nimport (\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com\/neptulon\/jsonrpc\"\n\t\"github.com\/neptulon\/jsonrpc\/middleware\"\n\t\"github.com\/neptulon\/neptulon\/test\"\n)\n\ntype echoMsg struct {\n\tMessage string `json:\"message\"`\n}\n\nfunc TestEcho(t *testing.T) {\n\tsh := test.NewTCPServerHelper(t).Start()\n\tdefer sh.Close()\n\n\tjs, err := jsonrpc.NewServer(sh.Server)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\trout, err := jsonrpc.NewRouter(&js.Middleware)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\trout.Request(\"echo\", middleware.Echo)\n\n\tvar wg sync.WaitGroup\n\n\tch := sh.GetTCPClientHelper().Connect()\n\tdefer ch.Close()\n\n\t\/\/ todo: separate echo middleware into \/middleware package\n\t\/\/ todo2: use sender.go rather than this manual handling\n\n\tjc := jsonrpc.UseClient(ch.Client)\n\tjc.ResMiddleware(func(ctx *jsonrpc.ResCtx) error {\n\t\tdefer wg.Done()\n\t\tvar msg echoMsg\n\t\tif err := ctx.Result(&msg); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif msg.Message != \"Hello!\" {\n\t\t\tt.Fatalf(\"expected: %v got: %v\", \"Hello!\", msg.Message)\n\t\t}\n\t\treturn ctx.Next()\n\t})\n\n\twg.Add(1)\n\tjc.SendRequest(\"echo\", echoMsg{Message: \"Hello!\"})\n\twg.Wait()\n}\n<commit_msg>add various helper notes<commit_after>package test\n\nimport (\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com\/neptulon\/jsonrpc\"\n\t\"github.com\/neptulon\/jsonrpc\/middleware\"\n\t\"github.com\/neptulon\/neptulon\/test\"\n)\n\ntype echoMsg struct {\n\tMessage string `json:\"message\"`\n}\n\nfunc TestEcho(t *testing.T) {\n\t\/\/ todo: streamline these like test.NewServerHelper(t).GetRouter().GetClientHelper() \/\/ these could wrap other helpers or directly objects?\n\tsh := test.NewTCPServerHelper(t).Start()\n\tdefer sh.Close()\n\n\tjs, err := jsonrpc.NewServer(sh.Server)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\trout, err := jsonrpc.NewRouter(&js.Middleware)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ -----------------\n\n\trout.Request(\"echo\", middleware.Echo)\n\n\tvar wg sync.WaitGroup\n\n\tch := sh.GetTCPClientHelper().Connect()\n\tdefer ch.Close()\n\n\t\/\/ todo: separate echo middleware into \/middleware package\n\t\/\/ todo2: use sender.go rather than this manual handling\n\t\/\/ todo3: Helper.Middleware function should do the wg.Add(1)\/wg.Done() and Close should wait for it. Also in neptulon\n\n\tjc := jsonrpc.UseClient(ch.Client)\n\tjc.ResMiddleware(func(ctx *jsonrpc.ResCtx) error {\n\t\tdefer wg.Done()\n\t\tvar msg echoMsg\n\t\tif err := ctx.Result(&msg); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif msg.Message != \"Hello!\" {\n\t\t\tt.Fatalf(\"expected: %v got: %v\", \"Hello!\", msg.Message)\n\t\t}\n\t\treturn ctx.Next()\n\t})\n\n\twg.Add(1)\n\tjc.SendRequest(\"echo\", echoMsg{Message: \"Hello!\"})\n\twg.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>package handler\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/Comcast\/webpa-common\/logging\"\n\t\"github.com\/Comcast\/webpa-common\/secure\"\n\t\"github.com\/go-kit\/kit\/log\"\n)\n\nconst (\n\t\/\/ The Content-Type value for JSON\n\tJsonContentType string = \"application\/json; charset=UTF-8\"\n\n\t\/\/ The Content-Type header\n\tContentTypeHeader string = \"Content-Type\"\n\n\t\/\/ The X-Content-Type-Options header\n\tContentTypeOptionsHeader string = \"X-Content-Type-Options\"\n\n\t\/\/ NoSniff is the value used for content options for errors written by this package\n\tNoSniff string = \"nosniff\"\n)\n\n\/\/ WriteJsonError writes a standard JSON error to the response\nfunc WriteJsonError(response http.ResponseWriter, code int, message string) error {\n\tresponse.Header().Set(ContentTypeHeader, JsonContentType)\n\tresponse.Header().Set(ContentTypeOptionsHeader, NoSniff)\n\n\tresponse.WriteHeader(code)\n\t_, err := fmt.Fprintf(response, `{\"message\": \"%s\"}`, message)\n\treturn err\n}\n\n\/\/ AuthorizationHandler provides decoration for http.Handler instances and will\n\/\/ ensure that requests pass the validator.  Note that secure.Validators is a Validator\n\/\/ implementation that allows chaining validators together via logical OR.\ntype AuthorizationHandler struct {\n\tHeaderName          string\n\tForbiddenStatusCode int\n\tValidator           secure.Validator\n\tLogger              log.Logger\n}\n\n\/\/ headerName returns the authorization header to use, either a.HeaderName\n\/\/ or secure.AuthorizationHeader if no header is supplied\nfunc (a AuthorizationHandler) headerName() string {\n\tif len(a.HeaderName) > 0 {\n\t\treturn a.HeaderName\n\t}\n\n\treturn secure.AuthorizationHeader\n}\n\n\/\/ forbiddenStatusCode returns a.ForbiddenStatusCode if supplied, otherwise\n\/\/ http.StatusForbidden is returned\nfunc (a AuthorizationHandler) forbiddenStatusCode() int {\n\tif a.ForbiddenStatusCode > 0 {\n\t\treturn a.ForbiddenStatusCode\n\t}\n\n\treturn http.StatusForbidden\n}\n\nfunc (a AuthorizationHandler) logger() log.Logger {\n\tif a.Logger != nil {\n\t\treturn a.Logger\n\t}\n\n\treturn logging.DefaultLogger()\n}\n\n\/\/ Decorate provides an Alice-compatible constructor that validates requests\n\/\/ using the configuration specified.\nfunc (a AuthorizationHandler) Decorate(delegate http.Handler) http.Handler {\n\t\/\/ if there is no validator, there's no point in decorating anything\n\tif a.Validator == nil {\n\t\treturn delegate\n\t}\n\n\tvar (\n\t\theaderName          = a.headerName()\n\t\tforbiddenStatusCode = a.forbiddenStatusCode()\n\t\tlogger              = a.logger()\n\t\terrorLog            = logging.Error(logger)\n\t\tdebugLog            = logging.Debug(logger)\n\t)\n\n\treturn http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {\n\t\theaderValue := request.Header.Get(headerName)\n\t\tif len(headerValue) == 0 {\n\t\t\terrorLog.Log(logging.MessageKey(), \"missing header\", \"name\", headerName)\n\t\t\tWriteJsonError(response, forbiddenStatusCode, fmt.Sprintf(\"missing header: %s\", headerName))\n\t\t\treturn\n\t\t}\n\n\t\ttoken, err := secure.ParseAuthorization(headerValue)\n\t\tif err != nil {\n\t\t\terrorLog.Log(logging.MessageKey(), \"invalid authorization header\", \"name\", headerName, \"token\", headerValue, logging.ErrorKey(), err)\n\t\t\tWriteJsonError(response, forbiddenStatusCode, fmt.Sprintf(\"Invalid authorization header [%s]: %s\", headerName, err.Error()))\n\t\t\treturn\n\t\t}\n\n\t\tctx := context.Background()\n\t\tctx = context.WithValue(ctx, \"method\", request.Method)\n\t\tctx = context.WithValue(ctx, \"path\", request.URL.Path)\n\n\t\tvalid, err := a.Validator.Validate(ctx, token)\n\t\tif err == nil && valid {\n\t\t\t\/\/ if any validator approves, stop and invoke the delegate\n\t\t\tdelegate.ServeHTTP(response, request)\n\t\t\treturn\n\t\t}\n\n\t\terrorLog.Log(\n\t\t\tlogging.MessageKey(), \"request denied\",\n\t\t\t\"validator-response\", valid,\n\t\t\t\"validator-error\", err,\n\t\t\t\"token\", headerValue,\n\t\t\t\"method\", request.Method,\n\t\t\t\"url\", request.URL,\n\t\t\t\"user-agent\", request.Header.Get(\"User-Agent\"),\n\t\t\t\"content-length\", request.ContentLength,\n\t\t\t\"remoteAddress\", request.RemoteAddr,\n\t\t)\n\n\t\tWriteJsonError(response, forbiddenStatusCode, \"request denied\")\n\t})\n}\n<commit_msg>remove unnecessary debugLog<commit_after>package handler\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/Comcast\/webpa-common\/logging\"\n\t\"github.com\/Comcast\/webpa-common\/secure\"\n\t\"github.com\/go-kit\/kit\/log\"\n)\n\nconst (\n\t\/\/ The Content-Type value for JSON\n\tJsonContentType string = \"application\/json; charset=UTF-8\"\n\n\t\/\/ The Content-Type header\n\tContentTypeHeader string = \"Content-Type\"\n\n\t\/\/ The X-Content-Type-Options header\n\tContentTypeOptionsHeader string = \"X-Content-Type-Options\"\n\n\t\/\/ NoSniff is the value used for content options for errors written by this package\n\tNoSniff string = \"nosniff\"\n)\n\n\/\/ WriteJsonError writes a standard JSON error to the response\nfunc WriteJsonError(response http.ResponseWriter, code int, message string) error {\n\tresponse.Header().Set(ContentTypeHeader, JsonContentType)\n\tresponse.Header().Set(ContentTypeOptionsHeader, NoSniff)\n\n\tresponse.WriteHeader(code)\n\t_, err := fmt.Fprintf(response, `{\"message\": \"%s\"}`, message)\n\treturn err\n}\n\n\/\/ AuthorizationHandler provides decoration for http.Handler instances and will\n\/\/ ensure that requests pass the validator.  Note that secure.Validators is a Validator\n\/\/ implementation that allows chaining validators together via logical OR.\ntype AuthorizationHandler struct {\n\tHeaderName          string\n\tForbiddenStatusCode int\n\tValidator           secure.Validator\n\tLogger              log.Logger\n}\n\n\/\/ headerName returns the authorization header to use, either a.HeaderName\n\/\/ or secure.AuthorizationHeader if no header is supplied\nfunc (a AuthorizationHandler) headerName() string {\n\tif len(a.HeaderName) > 0 {\n\t\treturn a.HeaderName\n\t}\n\n\treturn secure.AuthorizationHeader\n}\n\n\/\/ forbiddenStatusCode returns a.ForbiddenStatusCode if supplied, otherwise\n\/\/ http.StatusForbidden is returned\nfunc (a AuthorizationHandler) forbiddenStatusCode() int {\n\tif a.ForbiddenStatusCode > 0 {\n\t\treturn a.ForbiddenStatusCode\n\t}\n\n\treturn http.StatusForbidden\n}\n\nfunc (a AuthorizationHandler) logger() log.Logger {\n\tif a.Logger != nil {\n\t\treturn a.Logger\n\t}\n\n\treturn logging.DefaultLogger()\n}\n\n\/\/ Decorate provides an Alice-compatible constructor that validates requests\n\/\/ using the configuration specified.\nfunc (a AuthorizationHandler) Decorate(delegate http.Handler) http.Handler {\n\t\/\/ if there is no validator, there's no point in decorating anything\n\tif a.Validator == nil {\n\t\treturn delegate\n\t}\n\n\tvar (\n\t\theaderName          = a.headerName()\n\t\tforbiddenStatusCode = a.forbiddenStatusCode()\n\t\tlogger              = a.logger()\n\t\terrorLog            = logging.Error(logger)\n\t)\n\n\treturn http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {\n\t\theaderValue := request.Header.Get(headerName)\n\t\tif len(headerValue) == 0 {\n\t\t\terrorLog.Log(logging.MessageKey(), \"missing header\", \"name\", headerName)\n\t\t\tWriteJsonError(response, forbiddenStatusCode, fmt.Sprintf(\"missing header: %s\", headerName))\n\t\t\treturn\n\t\t}\n\n\t\ttoken, err := secure.ParseAuthorization(headerValue)\n\t\tif err != nil {\n\t\t\terrorLog.Log(logging.MessageKey(), \"invalid authorization header\", \"name\", headerName, \"token\", headerValue, logging.ErrorKey(), err)\n\t\t\tWriteJsonError(response, forbiddenStatusCode, fmt.Sprintf(\"Invalid authorization header [%s]: %s\", headerName, err.Error()))\n\t\t\treturn\n\t\t}\n\n\t\tctx := context.Background()\n\t\tctx = context.WithValue(ctx, \"method\", request.Method)\n\t\tctx = context.WithValue(ctx, \"path\", request.URL.Path)\n\n\t\tvalid, err := a.Validator.Validate(ctx, token)\n\t\tif err == nil && valid {\n\t\t\t\/\/ if any validator approves, stop and invoke the delegate\n\t\t\tdelegate.ServeHTTP(response, request)\n\t\t\treturn\n\t\t}\n\n\t\terrorLog.Log(\n\t\t\tlogging.MessageKey(), \"request denied\",\n\t\t\t\"validator-response\", valid,\n\t\t\t\"validator-error\", err,\n\t\t\t\"token\", headerValue,\n\t\t\t\"method\", request.Method,\n\t\t\t\"url\", request.URL,\n\t\t\t\"user-agent\", request.Header.Get(\"User-Agent\"),\n\t\t\t\"content-length\", request.ContentLength,\n\t\t\t\"remoteAddress\", request.RemoteAddr,\n\t\t)\n\n\t\tWriteJsonError(response, forbiddenStatusCode, \"request denied\")\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/flynn\/flynn\/controller\/client\"\n\tct \"github.com\/flynn\/flynn\/controller\/types\"\n\t\"github.com\/flynn\/flynn\/host\/types\"\n\ttc \"github.com\/flynn\/flynn\/test\/cluster\"\n\t\"github.com\/flynn\/flynn\/updater\/types\"\n\tc \"github.com\/flynn\/go-check\"\n)\n\ntype ReleaseSuite struct {\n\tHelper\n}\n\nvar _ = c.ConcurrentSuite(&ReleaseSuite{})\n\nfunc (s *ReleaseSuite) addReleaseHosts(t *c.C) *tc.BootResult {\n\tres, err := testCluster.AddReleaseHosts()\n\tt.Assert(err, c.IsNil)\n\tt.Assert(res.Instances, c.HasLen, 4)\n\treturn res\n}\n\nvar releaseScript = bytes.NewReader([]byte(`\nexport TUF_TARGETS_PASSPHRASE=\"flynn-test\"\nexport TUF_SNAPSHOT_PASSPHRASE=\"flynn-test\"\nexport TUF_TIMESTAMP_PASSPHRASE=\"flynn-test\"\n\nexport GOPATH=~\/go\nsrc=\"${GOPATH}\/src\/github.com\/flynn\/flynn\"\n\n# send all output to stderr so only version.json is output to stdout\n(\n\n  # rebuild components.\n  #\n  # ideally we would use tup to do this, but it hangs waiting on the\n  # FUSE socket after building, so for now we do it manually.\n  #\n  # See https:\/\/github.com\/flynn\/flynn\/issues\/949\n  pushd \"${src}\" >\/dev\/null\n  sed \"s\/{{TUF-ROOT-KEYS}}\/$(tuf --dir test\/release root-keys)\/g\" host\/cli\/root_keys.go.tmpl > host\/cli\/root_keys.go\n  vpkg=\"github.com\/flynn\/flynn\/pkg\/version\"\n  go build -o host\/bin\/flynn-host -ldflags=\"-X ${vpkg}.commit notdev -X ${vpkg}.branch dev -X ${vpkg}.tag v20160711.0-test -X ${vpkg}.dirty false\" .\/host\n  gzip -9 --keep --force host\/bin\/flynn-host\n  sed \"s\/{{FLYNN-HOST-CHECKSUM}}\/$(sha512sum host\/bin\/flynn-host.gz | cut -d \" \" -f 1)\/g\" script\/install-flynn.tmpl > script\/install-flynn\n\n  # create new images\n  test\/scripts\/wait-for-docker\n  for name in $(docker images | grep ^flynn | awk '{print $1}'); do\n    docker build -t $name - < <(echo -e \"FROM $name\\nRUN \/bin\/true\")\n  done\n\n  util\/release\/flynn-release manifest util\/release\/version_template.json > version.json\n  popd >\/dev\/null\n\n  \"${src}\/script\/export-components\" --no-compress \"${src}\/test\/release\"\n  \"${src}\/script\/release-channel\" --tuf-dir \"${src}\/test\/release\" --no-sync --no-changelog \"stable\" \"v20160711.0-test\"\n\n  dir=$(mktemp --directory)\n  ln -s \"${src}\/test\/release\/repository\" \"${dir}\/tuf\"\n  ln -s \"${src}\/script\/install-flynn\" \"${dir}\/install-flynn\"\n\n  # create a slug for testing slug based app updates\n  tar c -C \"${src}\/test\/apps\/http\" . | docker run -i -a stdin -a stdout -a stderr flynn\/slugbuilder - > \"${dir}\/slug.tgz\"\n\n  # start a file server to serve the exported components\n  sudo start-stop-daemon \\\n    --start \\\n    --background \\\n    --chdir \"${dir}\" \\\n    --exec \"${src}\/test\/bin\/flynn-test-file-server\"\n) >&2\n\ncat \"${src}\/version.json\"\n`))\n\nvar installScript = template.Must(template.New(\"install-script\").Parse(`\n# download to a tmp file so the script fails on download error rather than\n# executing nothing and succeeding\ncurl -sL --fail http:\/\/{{ .Blobstore }}\/install-flynn > \/tmp\/install-flynn\nbash -e \/tmp\/install-flynn -r \"http:\/\/{{ .Blobstore }}\"\n`))\n\nvar updateScript = template.Must(template.New(\"update-script\").Parse(`\ntimeout --signal=QUIT --kill-after=10 10m bash -ex <<-SCRIPT\ncd ~\/go\/src\/github.com\/flynn\/flynn\ntuf --dir test\/release root-keys | tuf-client init --store \/tmp\/tuf.db http:\/\/{{ .Blobstore }}\/tuf\necho stable | sudo tee \/etc\/flynn\/channel.txt\nflynn-host update --repository http:\/\/{{ .Blobstore }}\/tuf --tuf-db \/tmp\/tuf.db\nSCRIPT\n`))\n\nfunc (s *ReleaseSuite) TestReleaseImages(t *c.C) {\n\tif testCluster == nil {\n\t\tt.Skip(\"cannot boot release cluster\")\n\t}\n\n\t\/\/ stream script output to t.Log\n\tlogReader, logWriter := io.Pipe()\n\tdefer logWriter.Close()\n\tgo func() {\n\t\tbuf := bufio.NewReader(logReader)\n\t\tfor {\n\t\t\tline, err := buf.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdebug(t, line[0:len(line)-1])\n\t\t}\n\t}()\n\n\t\/\/ boot the release cluster, release components to a blobstore and output the new version.json\n\treleaseCluster := s.addReleaseHosts(t)\n\tbuildHost := releaseCluster.Instances[0]\n\tvar versionJSON bytes.Buffer\n\tt.Assert(buildHost.Run(\"bash -ex\", &tc.Streams{Stdin: releaseScript, Stdout: &versionJSON, Stderr: logWriter}), c.IsNil)\n\tvar versions map[string]string\n\tt.Assert(json.Unmarshal(versionJSON.Bytes(), &versions), c.IsNil)\n\n\t\/\/ install Flynn from the blobstore on the vanilla host\n\tblobstore := struct{ Blobstore string }{buildHost.IP + \":8080\"}\n\tinstallHost := releaseCluster.Instances[3]\n\tvar script bytes.Buffer\n\tinstallScript.Execute(&script, blobstore)\n\tvar installOutput bytes.Buffer\n\tout := io.MultiWriter(logWriter, &installOutput)\n\tt.Assert(installHost.Run(\"sudo bash -ex\", &tc.Streams{Stdin: &script, Stdout: out, Stderr: out}), c.IsNil)\n\n\t\/\/ check the flynn-host version is correct\n\tvar hostVersion bytes.Buffer\n\tt.Assert(installHost.Run(\"flynn-host version\", &tc.Streams{Stdout: &hostVersion}), c.IsNil)\n\tt.Assert(strings.TrimSpace(hostVersion.String()), c.Equals, \"v20160711.0-test\")\n\n\t\/\/ check rebuilt images were downloaded\n\tfor name, id := range versions {\n\t\texpected := fmt.Sprintf(\"%s image %s downloaded\", name, id)\n\t\tif !strings.Contains(installOutput.String(), expected) {\n\t\t\tt.Fatalf(`expected install to download %s %s`, name, id)\n\t\t}\n\t}\n\n\t\/\/ installing on an instance with Flynn running should fail\n\tscript.Reset()\n\tinstallScript.Execute(&script, blobstore)\n\tinstallOutput.Reset()\n\terr := buildHost.Run(\"sudo bash -ex\", &tc.Streams{Stdin: &script, Stdout: out, Stderr: out})\n\tif err == nil || !strings.Contains(installOutput.String(), \"ERROR: Flynn is already installed.\") {\n\t\tt.Fatal(\"expected Flynn install to fail but it didn't\")\n\t}\n\n\t\/\/ create a controller client for the release cluster\n\tpin, err := base64.StdEncoding.DecodeString(releaseCluster.ControllerPin)\n\tt.Assert(err, c.IsNil)\n\tclient, err := controller.NewClientWithConfig(\n\t\t\"https:\/\/\"+buildHost.IP,\n\t\treleaseCluster.ControllerKey,\n\t\tcontroller.Config{Pin: pin, Domain: releaseCluster.ControllerDomain},\n\t)\n\tt.Assert(err, c.IsNil)\n\n\t\/\/ deploy a slug based app + Redis resource\n\tslugApp := &ct.App{}\n\tt.Assert(client.CreateApp(slugApp), c.IsNil)\n\tgitreceive, err := client.GetAppRelease(\"gitreceive\")\n\tt.Assert(err, c.IsNil)\n\timageArtifact, err := client.GetArtifact(gitreceive.Env[\"SLUGRUNNER_IMAGE_ID\"])\n\tt.Assert(err, c.IsNil)\n\tslugArtifact := &ct.Artifact{Type: host.ArtifactTypeFile, URI: fmt.Sprintf(\"http:\/\/%s:8080\/slug.tgz\", buildHost.IP)}\n\tt.Assert(client.CreateArtifact(slugArtifact), c.IsNil)\n\tresource, err := client.ProvisionResource(&ct.ResourceReq{ProviderID: \"redis\", Apps: []string{slugApp.ID}})\n\tt.Assert(err, c.IsNil)\n\trelease := &ct.Release{\n\t\tArtifactIDs: []string{imageArtifact.ID, slugArtifact.ID},\n\t\tProcesses:   map[string]ct.ProcessType{\"web\": {Args: []string{\"\/runner\/init\", \"bin\/http\"}}},\n\t\tMeta:        map[string]string{\"git\": \"true\"},\n\t\tEnv:         resource.Env,\n\t}\n\tt.Assert(client.CreateRelease(release), c.IsNil)\n\tt.Assert(client.SetAppRelease(slugApp.ID, release.ID), c.IsNil)\n\twatcher, err := client.WatchJobEvents(slugApp.ID, release.ID)\n\tt.Assert(err, c.IsNil)\n\tdefer watcher.Close()\n\tt.Assert(client.PutFormation(&ct.Formation{\n\t\tAppID:     slugApp.ID,\n\t\tReleaseID: release.ID,\n\t\tProcesses: map[string]int{\"web\": 1},\n\t}), c.IsNil)\n\terr = watcher.WaitFor(ct.JobEvents{\"web\": {ct.JobStateUp: 1}}, scaleTimeout, nil)\n\tt.Assert(err, c.IsNil)\n\n\t\/\/ run a cluster update from the blobstore\n\tupdateHost := releaseCluster.Instances[1]\n\tscript.Reset()\n\tupdateScript.Execute(&script, blobstore)\n\tvar updateOutput bytes.Buffer\n\tout = io.MultiWriter(logWriter, &updateOutput)\n\tt.Assert(updateHost.Run(\"bash -ex\", &tc.Streams{Stdin: &script, Stdout: out, Stderr: out}), c.IsNil)\n\n\t\/\/ check rebuilt images were downloaded\n\tfor name := range versions {\n\t\tfor _, host := range releaseCluster.Instances[0:2] {\n\t\t\texpected := fmt.Sprintf(`\"pulled image\" host=%s name=%s`, host.ID, name)\n\t\t\tif !strings.Contains(updateOutput.String(), expected) {\n\t\t\t\tt.Fatalf(`expected update to download %s on host %s`, name, host.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\tassertImage := func(uri, image string) {\n\t\tu, err := url.Parse(uri)\n\t\tt.Assert(err, c.IsNil)\n\t\tt.Assert(u.Query().Get(\"id\"), c.Equals, versions[image])\n\t}\n\n\t\/\/ check system apps were deployed correctly\n\tfor _, app := range updater.SystemApps {\n\t\tif app.ImageOnly {\n\t\t\tcontinue \/\/ we don't deploy ImageOnly updates\n\t\t}\n\t\tif app.Image == \"\" {\n\t\t\tapp.Image = \"flynn\/\" + app.Name\n\t\t}\n\t\tdebugf(t, \"checking new %s release is using image %s\", app.Name, versions[app.Image])\n\t\texpected := fmt.Sprintf(`\"finished deploy of system app\" name=%s`, app.Name)\n\t\tif !strings.Contains(updateOutput.String(), expected) {\n\t\t\tt.Fatalf(`expected update to deploy %s`, app.Name)\n\t\t}\n\t\trelease, err := client.GetAppRelease(app.Name)\n\t\tt.Assert(err, c.IsNil)\n\t\tdebugf(t, \"new %s release ID: %s\", app.Name, release.ID)\n\t\tartifact, err := client.GetArtifact(release.ImageArtifactID())\n\t\tt.Assert(err, c.IsNil)\n\t\tdebugf(t, \"new %s artifact: %+v\", app.Name, artifact)\n\t\tassertImage(artifact.URI, app.Image)\n\t}\n\n\t\/\/ check gitreceive has the correct slug env vars\n\tgitreceive, err = client.GetAppRelease(\"gitreceive\")\n\tt.Assert(err, c.IsNil)\n\tfor _, name := range []string{\"slugbuilder\", \"slugrunner\"} {\n\t\tartifact, err := client.GetArtifact(gitreceive.Env[strings.ToUpper(name)+\"_IMAGE_ID\"])\n\t\tt.Assert(err, c.IsNil)\n\t\tassertImage(artifact.URI, \"flynn\/\"+name)\n\t}\n\n\t\/\/ check slug based app was deployed correctly\n\trelease, err = client.GetAppRelease(slugApp.Name)\n\tt.Assert(err, c.IsNil)\n\timageArtifact, err = client.GetArtifact(release.ImageArtifactID())\n\tt.Assert(err, c.IsNil)\n\tassertImage(imageArtifact.URI, \"flynn\/slugrunner\")\n\n\t\/\/ check Redis app was deployed correctly\n\trelease, err = client.GetAppRelease(resource.Env[\"FLYNN_REDIS\"])\n\tt.Assert(err, c.IsNil)\n\timageArtifact, err = client.GetArtifact(release.ImageArtifactID())\n\tt.Assert(err, c.IsNil)\n\tassertImage(imageArtifact.URI, \"flynn\/redis\")\n}\n<commit_msg>test: Fix update in TestReleaseImages<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/flynn\/flynn\/controller\/client\"\n\tct \"github.com\/flynn\/flynn\/controller\/types\"\n\t\"github.com\/flynn\/flynn\/host\/types\"\n\ttc \"github.com\/flynn\/flynn\/test\/cluster\"\n\t\"github.com\/flynn\/flynn\/updater\/types\"\n\tc \"github.com\/flynn\/go-check\"\n)\n\ntype ReleaseSuite struct {\n\tHelper\n}\n\nvar _ = c.ConcurrentSuite(&ReleaseSuite{})\n\nfunc (s *ReleaseSuite) addReleaseHosts(t *c.C) *tc.BootResult {\n\tres, err := testCluster.AddReleaseHosts()\n\tt.Assert(err, c.IsNil)\n\tt.Assert(res.Instances, c.HasLen, 4)\n\treturn res\n}\n\nvar releaseScript = bytes.NewReader([]byte(`\nexport TUF_TARGETS_PASSPHRASE=\"flynn-test\"\nexport TUF_SNAPSHOT_PASSPHRASE=\"flynn-test\"\nexport TUF_TIMESTAMP_PASSPHRASE=\"flynn-test\"\n\nexport GOPATH=~\/go\nsrc=\"${GOPATH}\/src\/github.com\/flynn\/flynn\"\n\n# send all output to stderr so only version.json is output to stdout\n(\n\n  # rebuild components.\n  #\n  # ideally we would use tup to do this, but it hangs waiting on the\n  # FUSE socket after building, so for now we do it manually.\n  #\n  # See https:\/\/github.com\/flynn\/flynn\/issues\/949\n  pushd \"${src}\" >\/dev\/null\n  sed \"s\/{{TUF-ROOT-KEYS}}\/$(tuf --dir test\/release root-keys)\/g\" host\/cli\/root_keys.go.tmpl > host\/cli\/root_keys.go\n  vpkg=\"github.com\/flynn\/flynn\/pkg\/version\"\n  go build -o host\/bin\/flynn-host -ldflags=\"-X ${vpkg}.commit notdev -X ${vpkg}.branch dev -X ${vpkg}.tag v20160711.0-test -X ${vpkg}.dirty false\" .\/host\n  gzip -9 --keep --force host\/bin\/flynn-host\n  sed \"s\/{{FLYNN-HOST-CHECKSUM}}\/$(sha512sum host\/bin\/flynn-host.gz | cut -d \" \" -f 1)\/g\" script\/install-flynn.tmpl > script\/install-flynn\n\n  # create new images\n  test\/scripts\/wait-for-docker\n  for name in $(docker images | grep ^flynn | awk '{print $1}'); do\n    docker build -t $name - < <(echo -e \"FROM $name\\nRUN \/bin\/true\")\n  done\n\n  util\/release\/flynn-release manifest util\/release\/version_template.json > version.json\n  popd >\/dev\/null\n\n  \"${src}\/script\/export-components\" --no-compress \"${src}\/test\/release\"\n  \"${src}\/script\/release-channel\" --tuf-dir \"${src}\/test\/release\" --no-sync --no-changelog \"stable\" \"v20160711.0-test\"\n\n  dir=$(mktemp --directory)\n  ln -s \"${src}\/test\/release\/repository\" \"${dir}\/tuf\"\n  ln -s \"${src}\/script\/install-flynn\" \"${dir}\/install-flynn\"\n\n  # create a slug for testing slug based app updates\n  tar c -C \"${src}\/test\/apps\/http\" . | docker run -i -a stdin -a stdout -a stderr flynn\/slugbuilder - > \"${dir}\/slug.tgz\"\n\n  # start a file server to serve the exported components\n  sudo start-stop-daemon \\\n    --start \\\n    --background \\\n    --chdir \"${dir}\" \\\n    --exec \"${src}\/test\/bin\/flynn-test-file-server\"\n) >&2\n\ncat \"${src}\/version.json\"\n`))\n\nvar installScript = template.Must(template.New(\"install-script\").Parse(`\n# download to a tmp file so the script fails on download error rather than\n# executing nothing and succeeding\ncurl -sL --fail http:\/\/{{ .Blobstore }}\/install-flynn > \/tmp\/install-flynn\nbash -e \/tmp\/install-flynn -r \"http:\/\/{{ .Blobstore }}\"\n`))\n\nvar updateScript = template.Must(template.New(\"update-script\").Parse(`\ntimeout --signal=QUIT --kill-after=10 10m bash -ex <<-SCRIPT\ncd ~\/go\/src\/github.com\/flynn\/flynn\ntuf --dir test\/release root-keys | tuf-client init --store \/tmp\/tuf.db http:\/\/{{ .Blobstore }}\/tuf\necho stable | sudo tee \/etc\/flynn\/channel.txt\nexport DISCOVERD=\"{{ .Discoverd }}\"\nflynn-host update --repository http:\/\/{{ .Blobstore }}\/tuf --tuf-db \/tmp\/tuf.db\nSCRIPT\n`))\n\nfunc (s *ReleaseSuite) TestReleaseImages(t *c.C) {\n\tif testCluster == nil {\n\t\tt.Skip(\"cannot boot release cluster\")\n\t}\n\n\t\/\/ stream script output to t.Log\n\tlogReader, logWriter := io.Pipe()\n\tdefer logWriter.Close()\n\tgo func() {\n\t\tbuf := bufio.NewReader(logReader)\n\t\tfor {\n\t\t\tline, err := buf.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdebug(t, line[0:len(line)-1])\n\t\t}\n\t}()\n\n\t\/\/ boot the release cluster, release components to a blobstore and output the new version.json\n\treleaseCluster := s.addReleaseHosts(t)\n\tbuildHost := releaseCluster.Instances[0]\n\tvar versionJSON bytes.Buffer\n\tt.Assert(buildHost.Run(\"bash -ex\", &tc.Streams{Stdin: releaseScript, Stdout: &versionJSON, Stderr: logWriter}), c.IsNil)\n\tvar versions map[string]string\n\tt.Assert(json.Unmarshal(versionJSON.Bytes(), &versions), c.IsNil)\n\n\t\/\/ install Flynn from the blobstore on the vanilla host\n\tblobstoreAddr := buildHost.IP + \":8080\"\n\tinstallHost := releaseCluster.Instances[3]\n\tvar script bytes.Buffer\n\tinstallScript.Execute(&script, map[string]string{\"Blobstore\": blobstoreAddr})\n\tvar installOutput bytes.Buffer\n\tout := io.MultiWriter(logWriter, &installOutput)\n\tt.Assert(installHost.Run(\"sudo bash -ex\", &tc.Streams{Stdin: &script, Stdout: out, Stderr: out}), c.IsNil)\n\n\t\/\/ check the flynn-host version is correct\n\tvar hostVersion bytes.Buffer\n\tt.Assert(installHost.Run(\"flynn-host version\", &tc.Streams{Stdout: &hostVersion}), c.IsNil)\n\tt.Assert(strings.TrimSpace(hostVersion.String()), c.Equals, \"v20160711.0-test\")\n\n\t\/\/ check rebuilt images were downloaded\n\tfor name, id := range versions {\n\t\texpected := fmt.Sprintf(\"%s image %s downloaded\", name, id)\n\t\tif !strings.Contains(installOutput.String(), expected) {\n\t\t\tt.Fatalf(`expected install to download %s %s`, name, id)\n\t\t}\n\t}\n\n\t\/\/ installing on an instance with Flynn running should fail\n\tscript.Reset()\n\tinstallScript.Execute(&script, map[string]string{\"Blobstore\": blobstoreAddr})\n\tinstallOutput.Reset()\n\terr := buildHost.Run(\"sudo bash -ex\", &tc.Streams{Stdin: &script, Stdout: out, Stderr: out})\n\tif err == nil || !strings.Contains(installOutput.String(), \"ERROR: Flynn is already installed.\") {\n\t\tt.Fatal(\"expected Flynn install to fail but it didn't\")\n\t}\n\n\t\/\/ create a controller client for the release cluster\n\tpin, err := base64.StdEncoding.DecodeString(releaseCluster.ControllerPin)\n\tt.Assert(err, c.IsNil)\n\tclient, err := controller.NewClientWithConfig(\n\t\t\"https:\/\/\"+buildHost.IP,\n\t\treleaseCluster.ControllerKey,\n\t\tcontroller.Config{Pin: pin, Domain: releaseCluster.ControllerDomain},\n\t)\n\tt.Assert(err, c.IsNil)\n\n\t\/\/ deploy a slug based app + Redis resource\n\tslugApp := &ct.App{}\n\tt.Assert(client.CreateApp(slugApp), c.IsNil)\n\tgitreceive, err := client.GetAppRelease(\"gitreceive\")\n\tt.Assert(err, c.IsNil)\n\timageArtifact, err := client.GetArtifact(gitreceive.Env[\"SLUGRUNNER_IMAGE_ID\"])\n\tt.Assert(err, c.IsNil)\n\tslugArtifact := &ct.Artifact{Type: host.ArtifactTypeFile, URI: fmt.Sprintf(\"http:\/\/%s:8080\/slug.tgz\", buildHost.IP)}\n\tt.Assert(client.CreateArtifact(slugArtifact), c.IsNil)\n\tresource, err := client.ProvisionResource(&ct.ResourceReq{ProviderID: \"redis\", Apps: []string{slugApp.ID}})\n\tt.Assert(err, c.IsNil)\n\trelease := &ct.Release{\n\t\tArtifactIDs: []string{imageArtifact.ID, slugArtifact.ID},\n\t\tProcesses:   map[string]ct.ProcessType{\"web\": {Args: []string{\"\/runner\/init\", \"bin\/http\"}}},\n\t\tMeta:        map[string]string{\"git\": \"true\"},\n\t\tEnv:         resource.Env,\n\t}\n\tt.Assert(client.CreateRelease(release), c.IsNil)\n\tt.Assert(client.SetAppRelease(slugApp.ID, release.ID), c.IsNil)\n\twatcher, err := client.WatchJobEvents(slugApp.ID, release.ID)\n\tt.Assert(err, c.IsNil)\n\tdefer watcher.Close()\n\tt.Assert(client.PutFormation(&ct.Formation{\n\t\tAppID:     slugApp.ID,\n\t\tReleaseID: release.ID,\n\t\tProcesses: map[string]int{\"web\": 1},\n\t}), c.IsNil)\n\terr = watcher.WaitFor(ct.JobEvents{\"web\": {ct.JobStateUp: 1}}, scaleTimeout, nil)\n\tt.Assert(err, c.IsNil)\n\n\t\/\/ run a cluster update from the blobstore\n\tupdateHost := releaseCluster.Instances[1]\n\tscript.Reset()\n\tupdateScript.Execute(&script, map[string]string{\"Blobstore\": blobstoreAddr, \"Discoverd\": updateHost.IP + \":1111\"})\n\tvar updateOutput bytes.Buffer\n\tout = io.MultiWriter(logWriter, &updateOutput)\n\tt.Assert(updateHost.Run(\"bash -ex\", &tc.Streams{Stdin: &script, Stdout: out, Stderr: out}), c.IsNil)\n\n\t\/\/ check rebuilt images were downloaded\n\tfor name := range versions {\n\t\tfor _, host := range releaseCluster.Instances[0:2] {\n\t\t\texpected := fmt.Sprintf(`\"pulled image\" host=%s name=%s`, host.ID, name)\n\t\t\tif !strings.Contains(updateOutput.String(), expected) {\n\t\t\t\tt.Fatalf(`expected update to download %s on host %s`, name, host.ID)\n\t\t\t}\n\t\t}\n\t}\n\n\tassertImage := func(uri, image string) {\n\t\tu, err := url.Parse(uri)\n\t\tt.Assert(err, c.IsNil)\n\t\tt.Assert(u.Query().Get(\"id\"), c.Equals, versions[image])\n\t}\n\n\t\/\/ check system apps were deployed correctly\n\tfor _, app := range updater.SystemApps {\n\t\tif app.ImageOnly {\n\t\t\tcontinue \/\/ we don't deploy ImageOnly updates\n\t\t}\n\t\tif app.Image == \"\" {\n\t\t\tapp.Image = \"flynn\/\" + app.Name\n\t\t}\n\t\tdebugf(t, \"checking new %s release is using image %s\", app.Name, versions[app.Image])\n\t\texpected := fmt.Sprintf(`\"finished deploy of system app\" name=%s`, app.Name)\n\t\tif !strings.Contains(updateOutput.String(), expected) {\n\t\t\tt.Fatalf(`expected update to deploy %s`, app.Name)\n\t\t}\n\t\trelease, err := client.GetAppRelease(app.Name)\n\t\tt.Assert(err, c.IsNil)\n\t\tdebugf(t, \"new %s release ID: %s\", app.Name, release.ID)\n\t\tartifact, err := client.GetArtifact(release.ImageArtifactID())\n\t\tt.Assert(err, c.IsNil)\n\t\tdebugf(t, \"new %s artifact: %+v\", app.Name, artifact)\n\t\tassertImage(artifact.URI, app.Image)\n\t}\n\n\t\/\/ check gitreceive has the correct slug env vars\n\tgitreceive, err = client.GetAppRelease(\"gitreceive\")\n\tt.Assert(err, c.IsNil)\n\tfor _, name := range []string{\"slugbuilder\", \"slugrunner\"} {\n\t\tartifact, err := client.GetArtifact(gitreceive.Env[strings.ToUpper(name)+\"_IMAGE_ID\"])\n\t\tt.Assert(err, c.IsNil)\n\t\tassertImage(artifact.URI, \"flynn\/\"+name)\n\t}\n\n\t\/\/ check slug based app was deployed correctly\n\trelease, err = client.GetAppRelease(slugApp.Name)\n\tt.Assert(err, c.IsNil)\n\timageArtifact, err = client.GetArtifact(release.ImageArtifactID())\n\tt.Assert(err, c.IsNil)\n\tassertImage(imageArtifact.URI, \"flynn\/slugrunner\")\n\n\t\/\/ check Redis app was deployed correctly\n\trelease, err = client.GetAppRelease(resource.Env[\"FLYNN_REDIS\"])\n\tt.Assert(err, c.IsNil)\n\timageArtifact, err = client.GetArtifact(release.ImageArtifactID())\n\tt.Assert(err, c.IsNil)\n\tassertImage(imageArtifact.URI, \"flynn\/redis\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"log\"\n\t\"math\"\n\n\t\"buildblast\/physics\"\n\t\"buildblast\/coords\"\n)\n\ntype PlayerState struct {\n\tpos coords.World\n\t\/\/ JavaScript performance.now() timestamp.\n\tt float64\n}\n\ntype PlayerStateRingBuffer struct {\n\tbuf []PlayerState\n\toffset int\n}\n\nfunc NewPlayerStateRingBuffer() *PlayerStateRingBuffer {\n\tp := new(PlayerStateRingBuffer)\n\tp.buf = make([]PlayerState, 100)\n\treturn p\n}\n\nfunc (p *PlayerStateRingBuffer) AddState(t float64, pos coords.World) {\n\tp.buf[p.offset] = PlayerState{pos, t}\n\tp.offset++\n\tif p.offset >= len(p.buf) {\n\t\tp.offset = 0\n\t}\n}\n\n\/\/ If t > most recent time added, return most recent\n\/\/ position added. If t < ring buffer history, return\n\/\/ oldest position stored. If t == an entry in the\n\/\/ ring buffer, return that entry. If t is between\n\/\/ two entries in the ring buffer, interpolate\n\/\/ between them.\nfunc (p *PlayerStateRingBuffer) PositionAt(t float64) coords.World {\n\tl := len(p.buf)\n\n\tnewest := p.buf[((p.offset - 1) + l) % l]\n\tif newest.t <= t {\n\t\t\/\/ We could extrapolate, but this should do.\n\t\treturn newest.pos\n\t}\n\n\toldest := p.buf[(p.offset + l) % l]\n\tif oldest.t >= t {\n\t\treturn oldest.pos\n\t}\n\n\tvar older PlayerState\n\tvar newer PlayerState\n\tfor i := 1; i <= l; i++ {\n\t\tolder = p.buf[((p.offset - i) + l) % l]\n\t\tif older.t <= t {\n\t\t\tbreak\n\t\t}\n\t\tnewer = older\n\t}\n\n\tif older.t == t {\n\t\treturn older.pos\n\t}\n\n\tp1 := older.pos\n\tp3 := newer.pos\n\n\t\/\/ t1        t2     t3\n\t\/\/ |          |     |\n\t\/\/ older.t    t   newer.t\n\tt13 := newer.t - older.t\n\tt12 := t - older.t\n\n\tr := t12 \/ t13\n\tp13 := coords.Vec3{\n\t\tX: p3.X - p1.X,\n\t\tY: p3.Y - p1.Y,\n\t\tZ: p3.Z - p1.Z,\n\t}\n\n\treturn coords.World{\n\t\tX: p1.X + p13.X*r,\n\t\tY: p1.Y + p13.Y*r,\n\t\tZ: p1.Z + p13.Z*r,\n\t}\n}\n\ntype ControlState struct {\n\tForward         bool\n\tLeft            bool\n\tRight           bool\n\tBack            bool\n\tJump            bool\n\tActivateBlaster bool\n\tLat             float64\n\tLon             float64\n\n\tTimestamp float64 \/\/ In ms\n}\n\nvar PLAYER_EYE_HEIGHT = 1.6;\nvar PLAYER_HEIGHT = 1.75;\nvar PLAYER_BODY_HEIGHT = 1.3;\nvar PLAYER_DIST_CENTER_EYE = PLAYER_EYE_HEIGHT - PLAYER_BODY_HEIGHT\/2;\nvar PLAYER_HALF_EXTENTS = coords.Vec3{\n\t0.2,\n\tPLAYER_HEIGHT \/ 2,\n\t0.2,\n};\nvar PLAYER_CENTER_OFFSET = coords.Vec3{\n\t0,\n\t-PLAYER_DIST_CENTER_EYE,\n\t0,\n};\n\n\/\/ Gameplay state defaults\nvar PLAYER_MAX_HP = 100;\n\ntype Player struct {\n\tpos       coords.World\n\tvy        float64\n\tbox       physics.Box\n\tcontrols  *ControlState\n\thistory   *PlayerStateRingBuffer\n\n\t\/\/ Gameplay state\n\thp        int\n}\n\nfunc NewPlayer() *Player {\n\treturn &Player{\n\t\tpos: coords.World{\n\t\t\tX: 0,\n\t\t\tY: 27,\n\t\t\tZ: 0,\n\t\t},\n\t\tcontrols: &ControlState{},\n\t\thp: PLAYER_MAX_HP,\n\t}\n}\n\nfunc (p *Player) simulateStep(c *Client, w *World) (*MsgPlayerState, *MsgDebugRay) {\n\tvar controls *ControlState\n\tselect {\n\t\tcase controls = <-c.ControlState:\n\t\tdefault: return nil, nil\n\t}\n\n\tdt := (controls.Timestamp - p.controls.Timestamp) \/ 1000\n\n\tif dt > 1.0 {\n\t\tlog.Println(\"WARN: Attempt to simulate step with dt of \", dt, \" which is too large. Clipping.\")\n\t\tdt = 1.0\n\t}\n\n\tp.simulateTick(dt, c.world, controls)\n\tvar msgDebugRay *MsgDebugRay\n\tif controls.ActivateBlaster {\n\t\ttarget := FindIntersection(c.world, p, controls)\n\t\tif target != nil {\n\t\t\tmsgDebugRay = &MsgDebugRay{\n\t\t\t\tPos: *target,\n\t\t\t}\n\t\t}\n\t}\n\n\tp.controls = controls\n\n\treturn &MsgPlayerState{\n\t\tPos: p.pos,\n\t\tVelocityY: p.vy,\n\t\tTimestamp: controls.Timestamp,\n\t\tHp: p.hp,\n\t}, msgDebugRay\n}\n\nfunc (p *Player) simulateTick(dt float64, world *World, controls *ControlState) {\n\tp.vy += dt * -9.81\n\n\tfw := 0.0\n\tif controls.Forward {\n\t\tfw = 1 * dt * 10\n\t} else if controls.Back {\n\t\tfw = -1 * dt * 10\n\t}\n\n\trt := 0.0\n\tif controls.Right {\n\t\trt = 1 * dt * 10\n\t} else if controls.Left {\n\t\trt = -1 * dt * 10\n\t}\n\n\tcos := math.Cos\n\tsin := math.Sin\n\n\tmove := coords.Vec3{\n\t\tX: -cos(controls.Lon) * fw + sin(controls.Lon) * rt,\n\t\tY: p.vy * dt,\n\t\tZ: -sin(controls.Lon) * fw - cos(controls.Lon) * rt,\n\t}\n\n\tbox := physics.NewBoxOffset(p.pos, PLAYER_HALF_EXTENTS, PLAYER_CENTER_OFFSET)\n\n\tmove = box.AttemptMove(world, move)\n\n\tif (move.Y == 0) {\n\t\tif (controls.Jump) {\n\t\t\tp.vy = 6\n\t\t} else {\n\t\t\tp.vy = 0\n\t\t}\n\t}\n\n\tp.pos.X += move.X\n\tp.pos.Y += move.Y\n\tp.pos.Z += move.Z\n}\n\nfunc (p *Player) hurt(dmg int) bool {\n\tp.hp -= dmg\n\treturn p.dead()\n}\n\nfunc (p *Player) heal(hps int) {\n\tp.hp += hps\n}\n\nfunc (p *Player) dead() bool {\n\treturn p.hp <= 0\n}\n<commit_msg>Cleanup. Move history buffer to bottom.<commit_after>package main\n\nimport (\n\t\"log\"\n\t\"math\"\n\n\t\"buildblast\/physics\"\n\t\"buildblast\/coords\"\n)\n\n\ntype ControlState struct {\n\tForward         bool\n\tLeft            bool\n\tRight           bool\n\tBack            bool\n\tJump            bool\n\tActivateBlaster bool\n\tLat             float64\n\tLon             float64\n\n\tTimestamp float64 \/\/ In ms\n}\n\nvar PLAYER_EYE_HEIGHT = 1.6;\nvar PLAYER_HEIGHT = 1.75;\nvar PLAYER_BODY_HEIGHT = 1.3;\nvar PLAYER_DIST_CENTER_EYE = PLAYER_EYE_HEIGHT - PLAYER_BODY_HEIGHT\/2;\nvar PLAYER_HALF_EXTENTS = coords.Vec3{\n\t0.2,\n\tPLAYER_HEIGHT \/ 2,\n\t0.2,\n};\nvar PLAYER_CENTER_OFFSET = coords.Vec3{\n\t0,\n\t-PLAYER_DIST_CENTER_EYE,\n\t0,\n};\n\n\/\/ Gameplay state defaults\nvar PLAYER_MAX_HP = 100;\n\ntype Player struct {\n\tpos       coords.World\n\tvy        float64\n\tbox       physics.Box\n\tcontrols  *ControlState\n\thistory   *PlayerHistory\n\n\t\/\/ Gameplay state\n\thp        int\n}\n\nfunc NewPlayer() *Player {\n\treturn &Player{\n\t\tpos: coords.World{\n\t\t\tX: 0,\n\t\t\tY: 27,\n\t\t\tZ: 0,\n\t\t},\n\t\tcontrols: &ControlState{},\n\t\thistory: NewPlayerHistory(),\n\t\thp: PLAYER_MAX_HP,\n\t}\n}\n\nfunc (p *Player) simulateStep(c *Client, w *World) (*MsgPlayerState, *MsgDebugRay) {\n\tvar controls *ControlState\n\tselect {\n\t\tcase controls = <-c.ControlState:\n\t\tdefault: return nil, nil\n\t}\n\n\tdt := (controls.Timestamp - p.controls.Timestamp) \/ 1000\n\n\tif dt > 1.0 {\n\t\tlog.Println(\"WARN: Attempt to simulate step with dt of \", dt, \" which is too large. Clipping.\")\n\t\tdt = 1.0\n\t}\n\n\tp.simulateTick(dt, c.world, controls)\n\tvar msgDebugRay *MsgDebugRay\n\tif controls.ActivateBlaster {\n\t\ttarget := FindIntersection(c.world, p, controls)\n\t\tif target != nil {\n\t\t\tmsgDebugRay = &MsgDebugRay{\n\t\t\t\tPos: *target,\n\t\t\t}\n\t\t}\n\t}\n\n\tp.controls = controls\n\tp.history.Add(controls.Timestamp, p.pos)\n\n\treturn &MsgPlayerState{\n\t\tPos: p.pos,\n\t\tVelocityY: p.vy,\n\t\tTimestamp: controls.Timestamp,\n\t\tHp: p.hp,\n\t}, msgDebugRay\n}\n\nfunc (p *Player) simulateTick(dt float64, world *World, controls *ControlState) {\n\tp.vy += dt * -9.81\n\n\tfw := 0.0\n\tif controls.Forward {\n\t\tfw = 1 * dt * 10\n\t} else if controls.Back {\n\t\tfw = -1 * dt * 10\n\t}\n\n\trt := 0.0\n\tif controls.Right {\n\t\trt = 1 * dt * 10\n\t} else if controls.Left {\n\t\trt = -1 * dt * 10\n\t}\n\n\tcos := math.Cos\n\tsin := math.Sin\n\n\tmove := coords.Vec3{\n\t\tX: -cos(controls.Lon) * fw + sin(controls.Lon) * rt,\n\t\tY: p.vy * dt,\n\t\tZ: -sin(controls.Lon) * fw - cos(controls.Lon) * rt,\n\t}\n\n\tbox := physics.NewBoxOffset(p.pos, PLAYER_HALF_EXTENTS, PLAYER_CENTER_OFFSET)\n\n\tmove = box.AttemptMove(world, move)\n\n\tif (move.Y == 0) {\n\t\tif (controls.Jump) {\n\t\t\tp.vy = 6\n\t\t} else {\n\t\t\tp.vy = 0\n\t\t}\n\t}\n\n\tp.pos.X += move.X\n\tp.pos.Y += move.Y\n\tp.pos.Z += move.Z\n}\n\nfunc (p *Player) hurt(dmg int) bool {\n\tp.hp -= dmg\n\treturn p.dead()\n}\n\nfunc (p *Player) heal(hps int) {\n\tp.hp += hps\n}\n\nfunc (p *Player) dead() bool {\n\treturn p.hp <= 0\n}\n\ntype PlayerHistoryEntry struct {\n\tpos coords.World\n\t\/\/ JavaScript performance.now() timestamp.\n\tt float64\n}\n\ntype PlayerHistory struct {\n\tbuf []PlayerHistoryEntry\n\toffset int\n}\n\nfunc NewPlayerHistory() *PlayerHistory {\n\tp := new(PlayerHistory)\n\tp.buf = make([]PlayerHistoryEntry, 100)\n\treturn p\n}\n\nfunc (p *PlayerHistory) Add(t float64, pos coords.World) {\n\tp.buf[p.offset] = PlayerHistoryEntry{pos, t}\n\tp.offset++\n\tif p.offset >= len(p.buf) {\n\t\tp.offset = 0\n\t}\n}\n\n\/\/ If t > most recent time added, return most recent\n\/\/ position added. If t < ring buffer history, return\n\/\/ oldest position stored. If t == an entry in the\n\/\/ ring buffer, return that entry. If t is between\n\/\/ two entries in the ring buffer, interpolate\n\/\/ between them.\nfunc (p *PlayerHistory) PositionAt(t float64) coords.World {\n\tl := len(p.buf)\n\n\tnewest := p.buf[((p.offset - 1) + l) % l]\n\tif newest.t <= t {\n\t\t\/\/ We could extrapolate, but this should do.\n\t\treturn newest.pos\n\t}\n\n\toldest := p.buf[(p.offset + l) % l]\n\tif oldest.t >= t {\n\t\treturn oldest.pos\n\t}\n\n\tvar older PlayerHistoryEntry\n\tvar newer PlayerHistoryEntry\n\tfor i := 1; i <= l; i++ {\n\t\tolder = p.buf[((p.offset - i) + l) % l]\n\t\tif older.t <= t {\n\t\t\tbreak\n\t\t}\n\t\tnewer = older\n\t}\n\n\tif older.t == t {\n\t\treturn older.pos\n\t}\n\n\tp1 := older.pos\n\tp3 := newer.pos\n\n\t\/\/ t1        t2     t3\n\t\/\/ |          |     |\n\t\/\/ older.t    t   newer.t\n\tt13 := newer.t - older.t\n\tt12 := t - older.t\n\n\tr := t12 \/ t13\n\tp13 := coords.Vec3{\n\t\tX: p3.X - p1.X,\n\t\tY: p3.Y - p1.Y,\n\t\tZ: p3.Z - p1.Z,\n\t}\n\n\treturn coords.World{\n\t\tX: p1.X + p13.X*r,\n\t\tY: p1.Y + p13.Y*r,\n\t\tZ: p1.Z + p13.Z*r,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package inigo_test\n\nimport (\n\t\"fmt\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry-incubator\/inigo\/fixtures\"\n\t\"github.com\/cloudfoundry-incubator\/inigo\/helpers\"\n\t\"github.com\/cloudfoundry-incubator\/inigo\/loggredile\"\n\t\"github.com\/cloudfoundry-incubator\/runtime-schema\/models\"\n\t\"github.com\/nu7hatch\/gouuid\"\n\t\"github.com\/tedsuo\/ifrit\"\n\n\t\"github.com\/cloudfoundry-incubator\/inigo\/inigo_server\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\tarchive_helper \"github.com\/pivotal-golang\/archiver\/extractor\/test_helper\"\n)\n\nvar _ = Describe(\"Convergence to desired state\", func() {\n\tvar desiredAppRequest models.DesireAppRequestFromCC\n\tvar appId string\n\tvar processGuid string\n\n\tvar tpsProcess ifrit.Process\n\tvar tpsAddr string\n\n\tvar logOutput *gbytes.Buffer\n\tvar stop chan<- bool\n\n\tCONVERGE_REPEAT_INTERVAL := time.Duration(LONG_TIMEOUT) * time.Second\n\tLONGER_TIMEOUT := 2 * LONG_TIMEOUT\n\n\tBeforeEach(func() {\n\t\tguid, err := uuid.NewV4()\n\t\tif err != nil {\n\t\t\tpanic(\"Failed to generate App ID\")\n\t\t}\n\t\tappId = guid.String()\n\n\t\tguid, err = uuid.NewV4()\n\t\tif err != nil {\n\t\t\tpanic(\"Failed to generate Process Guid\")\n\t\t}\n\t\tprocessGuid = guid.String()\n\n\t\tsuiteContext.FileServerRunner.Start()\n\t\tsuiteContext.AuctioneerRunner.Start()\n\t\tsuiteContext.AppManagerRunner.Start()\n\t\tsuiteContext.RouteEmitterRunner.Start()\n\t\tsuiteContext.RouterRunner.Start()\n\t\tsuiteContext.ConvergerRunner.Start(CONVERGE_REPEAT_INTERVAL, 30*time.Second, 5*time.Minute, 30*time.Second, 300*time.Second)\n\n\t\ttpsProcess = ifrit.Envoke(suiteContext.TPSRunner)\n\t\ttpsAddr = fmt.Sprintf(\"http:\/\/127.0.0.1:%d\", suiteContext.TPSPort)\n\n\t\tarchive_helper.CreateZipArchive(\"\/tmp\/simple-echo-droplet.zip\", fixtures.HelloWorldIndexApp())\n\t\tinigo_server.UploadFile(\"simple-echo-droplet.zip\", \"\/tmp\/simple-echo-droplet.zip\")\n\n\t\tsuiteContext.FileServerRunner.ServeFile(\"some-lifecycle-bundle.tgz\", suiteContext.SharedContext.CircusZipPath)\n\n\t\tlogOutput, stop = loggredile.StreamIntoGBuffer(\n\t\t\tsuiteContext.LoggregatorRunner.Config.OutgoingPort,\n\t\t\tfmt.Sprintf(\"\/tail\/?app=%s\", appId),\n\t\t\t\"App\",\n\t\t)\n\t})\n\n\tAfterEach(func() {\n\t\ttpsProcess.Signal(syscall.SIGKILL)\n\t\tEventually(tpsProcess.Wait()).Should(Receive())\n\t\tclose(stop)\n\t})\n\n\tFDescribe(\"Executor fault tolerance\", func() {\n\t\tContext(\"When starting a long-running process and then bouncing the executor\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tsuiteContext.ExecutorRunner.Start()\n\t\t\t\tsuiteContext.RepRunner.Start()\n\n\t\t\t\tdesiredAppRequest = models.DesireAppRequestFromCC{\n\t\t\t\t\tProcessGuid:  processGuid,\n\t\t\t\t\tDropletUri:   inigo_server.DownloadUrl(\"simple-echo-droplet.zip\"),\n\t\t\t\t\tStack:        suiteContext.RepStack,\n\t\t\t\t\tEnvironment:  []models.EnvironmentVariable{{Key: \"VCAP_APPLICATION\", Value: \"{}\"}},\n\t\t\t\t\tNumInstances: 1,\n\t\t\t\t\tRoutes:       []string{\"route-to-simple\"},\n\t\t\t\t\tStartCommand: \".\/run\",\n\t\t\t\t\tLogGuid:      appId,\n\t\t\t\t}\n\n\t\t\t\terr := suiteContext.NatsRunner.MessageBus.Publish(\"diego.desire.app\", desiredAppRequest.ToJSON())\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t\trunning_lrps_poller := helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller := helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(HaveLen(1))\n\t\t\t\tEventually(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(Equal([]string{\"0\"}))\n\t\t\t})\n\n\t\t\tIt(\"Eventually brings the long-running process up\", func() {\n\t\t\t\tsuiteContext.ExecutorRunner.Stop()\n\n\t\t\t\trunning_lrps_poller := helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller := helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(BeEmpty())\n\t\t\t\tEventually(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(BeEmpty())\n\n\t\t\t\tsuiteContext.ExecutorRunner.Start()\n\n\t\t\t\trunning_lrps_poller = helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller = helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(HaveLen(1))\n\t\t\t\tEventually(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(Equal([]string{\"0\"}))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"When trying to start a long-running process before the executor is up\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tsuiteContext.RepRunner.Start()\n\n\t\t\t\tdesiredAppRequest = models.DesireAppRequestFromCC{\n\t\t\t\t\tProcessGuid:  processGuid,\n\t\t\t\t\tDropletUri:   inigo_server.DownloadUrl(\"simple-echo-droplet.zip\"),\n\t\t\t\t\tStack:        suiteContext.RepStack,\n\t\t\t\t\tEnvironment:  []models.EnvironmentVariable{{Key: \"VCAP_APPLICATION\", Value: \"{}\"}},\n\t\t\t\t\tNumInstances: 1,\n\t\t\t\t\tRoutes:       []string{\"route-to-simple\"},\n\t\t\t\t\tStartCommand: \".\/run\",\n\t\t\t\t\tLogGuid:      appId,\n\t\t\t\t}\n\n\t\t\t\terr := suiteContext.NatsRunner.MessageBus.Publish(\"diego.desire.app\", desiredAppRequest.ToJSON())\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t\trunning_lrps_poller := helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller := helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tConsistently(running_lrps_poller, LONGER_TIMEOUT).Should(BeEmpty())\n\t\t\t\tConsistently(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(BeEmpty())\n\t\t\t})\n\n\t\t\tIt(\"Eventually brings the long-running process up\", func() {\n\t\t\t\tsuiteContext.ExecutorRunner.Start()\n\n\t\t\t\trunning_lrps_poller := helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller := helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(HaveLen(1))\n\t\t\t\tEventually(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(Equal([]string{\"0\"}))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"When the original request to stop a long-running process is lost\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tsuiteContext.RepRunner.Start()\n\t\t\t\tsuiteContext.ExecutorRunner.Start()\n\n\t\t\t\tdesiredAppRequest = models.DesireAppRequestFromCC{\n\t\t\t\t\tProcessGuid:  processGuid,\n\t\t\t\t\tDropletUri:   inigo_server.DownloadUrl(\"simple-echo-droplet.zip\"),\n\t\t\t\t\tStack:        suiteContext.RepStack,\n\t\t\t\t\tEnvironment:  []models.EnvironmentVariable{{Key: \"VCAP_APPLICATION\", Value: \"{}\"}},\n\t\t\t\t\tNumInstances: 1,\n\t\t\t\t\tRoutes:       []string{\"route-to-simple\"},\n\t\t\t\t\tStartCommand: \".\/run\",\n\t\t\t\t\tLogGuid:      appId,\n\t\t\t\t}\n\n\t\t\t\terr := suiteContext.NatsRunner.MessageBus.Publish(\"diego.desire.app\", desiredAppRequest.ToJSON())\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t\trunning_lrps_poller := helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller := helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(HaveLen(1))\n\t\t\t\tEventually(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(Equal([]string{\"0\"}))\n\t\t\t})\n\n\t\t\tIt(\"Eventually brings the long-running process down\", func() {\n\t\t\t\tsuiteContext.RepRunner.Stop()\n\n\t\t\t\tdesiredAppStopRequest := models.DesireAppRequestFromCC{\n\t\t\t\t\tProcessGuid:  processGuid,\n\t\t\t\t\tDropletUri:   inigo_server.DownloadUrl(\"simple-echo-droplet.zip\"),\n\t\t\t\t\tStack:        suiteContext.RepStack,\n\t\t\t\t\tEnvironment:  []models.EnvironmentVariable{{Key: \"VCAP_APPLICATION\", Value: \"{}\"}},\n\t\t\t\t\tNumInstances: 0,\n\t\t\t\t\tRoutes:       []string{\"route-to-simple\"},\n\t\t\t\t\tStartCommand: \".\/run\",\n\t\t\t\t\tLogGuid:      appId,\n\t\t\t\t}\n\n\t\t\t\terr := suiteContext.NatsRunner.MessageBus.Publish(\"diego.desire.app\", desiredAppStopRequest.ToJSON())\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t\trunning_lrps_poller := helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(HaveLen(1))\n\n\t\t\t\trunning_lrps_poller = helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\tConsistently(running_lrps_poller, LONGER_TIMEOUT).Should(HaveLen(1))\n\n\t\t\t\tsuiteContext.RepRunner.Start()\n\n\t\t\t\trunning_lrps_poller = helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller := helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(BeEmpty())\n\t\t\t\tEventually(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(BeEmpty())\n\t\t\t})\n\t\t})\n\t})\n})\n<commit_msg>Ooops... unfocus tests<commit_after>package inigo_test\n\nimport (\n\t\"fmt\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry-incubator\/inigo\/fixtures\"\n\t\"github.com\/cloudfoundry-incubator\/inigo\/helpers\"\n\t\"github.com\/cloudfoundry-incubator\/inigo\/loggredile\"\n\t\"github.com\/cloudfoundry-incubator\/runtime-schema\/models\"\n\t\"github.com\/nu7hatch\/gouuid\"\n\t\"github.com\/tedsuo\/ifrit\"\n\n\t\"github.com\/cloudfoundry-incubator\/inigo\/inigo_server\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\tarchive_helper \"github.com\/pivotal-golang\/archiver\/extractor\/test_helper\"\n)\n\nvar _ = Describe(\"Convergence to desired state\", func() {\n\tvar desiredAppRequest models.DesireAppRequestFromCC\n\tvar appId string\n\tvar processGuid string\n\n\tvar tpsProcess ifrit.Process\n\tvar tpsAddr string\n\n\tvar logOutput *gbytes.Buffer\n\tvar stop chan<- bool\n\n\tCONVERGE_REPEAT_INTERVAL := time.Duration(LONG_TIMEOUT) * time.Second\n\tLONGER_TIMEOUT := 2 * LONG_TIMEOUT\n\n\tBeforeEach(func() {\n\t\tguid, err := uuid.NewV4()\n\t\tif err != nil {\n\t\t\tpanic(\"Failed to generate App ID\")\n\t\t}\n\t\tappId = guid.String()\n\n\t\tguid, err = uuid.NewV4()\n\t\tif err != nil {\n\t\t\tpanic(\"Failed to generate Process Guid\")\n\t\t}\n\t\tprocessGuid = guid.String()\n\n\t\tsuiteContext.FileServerRunner.Start()\n\t\tsuiteContext.AuctioneerRunner.Start()\n\t\tsuiteContext.AppManagerRunner.Start()\n\t\tsuiteContext.RouteEmitterRunner.Start()\n\t\tsuiteContext.RouterRunner.Start()\n\t\tsuiteContext.ConvergerRunner.Start(CONVERGE_REPEAT_INTERVAL, 30*time.Second, 5*time.Minute, 30*time.Second, 300*time.Second)\n\n\t\ttpsProcess = ifrit.Envoke(suiteContext.TPSRunner)\n\t\ttpsAddr = fmt.Sprintf(\"http:\/\/127.0.0.1:%d\", suiteContext.TPSPort)\n\n\t\tarchive_helper.CreateZipArchive(\"\/tmp\/simple-echo-droplet.zip\", fixtures.HelloWorldIndexApp())\n\t\tinigo_server.UploadFile(\"simple-echo-droplet.zip\", \"\/tmp\/simple-echo-droplet.zip\")\n\n\t\tsuiteContext.FileServerRunner.ServeFile(\"some-lifecycle-bundle.tgz\", suiteContext.SharedContext.CircusZipPath)\n\n\t\tlogOutput, stop = loggredile.StreamIntoGBuffer(\n\t\t\tsuiteContext.LoggregatorRunner.Config.OutgoingPort,\n\t\t\tfmt.Sprintf(\"\/tail\/?app=%s\", appId),\n\t\t\t\"App\",\n\t\t)\n\t})\n\n\tAfterEach(func() {\n\t\ttpsProcess.Signal(syscall.SIGKILL)\n\t\tEventually(tpsProcess.Wait()).Should(Receive())\n\t\tclose(stop)\n\t})\n\n\tDescribe(\"Executor fault tolerance\", func() {\n\t\tContext(\"When starting a long-running process and then bouncing the executor\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tsuiteContext.ExecutorRunner.Start()\n\t\t\t\tsuiteContext.RepRunner.Start()\n\n\t\t\t\tdesiredAppRequest = models.DesireAppRequestFromCC{\n\t\t\t\t\tProcessGuid:  processGuid,\n\t\t\t\t\tDropletUri:   inigo_server.DownloadUrl(\"simple-echo-droplet.zip\"),\n\t\t\t\t\tStack:        suiteContext.RepStack,\n\t\t\t\t\tEnvironment:  []models.EnvironmentVariable{{Key: \"VCAP_APPLICATION\", Value: \"{}\"}},\n\t\t\t\t\tNumInstances: 1,\n\t\t\t\t\tRoutes:       []string{\"route-to-simple\"},\n\t\t\t\t\tStartCommand: \".\/run\",\n\t\t\t\t\tLogGuid:      appId,\n\t\t\t\t}\n\n\t\t\t\terr := suiteContext.NatsRunner.MessageBus.Publish(\"diego.desire.app\", desiredAppRequest.ToJSON())\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t\trunning_lrps_poller := helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller := helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(HaveLen(1))\n\t\t\t\tEventually(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(Equal([]string{\"0\"}))\n\t\t\t})\n\n\t\t\tIt(\"Eventually brings the long-running process up\", func() {\n\t\t\t\tsuiteContext.ExecutorRunner.Stop()\n\n\t\t\t\trunning_lrps_poller := helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller := helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(BeEmpty())\n\t\t\t\tEventually(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(BeEmpty())\n\n\t\t\t\tsuiteContext.ExecutorRunner.Start()\n\n\t\t\t\trunning_lrps_poller = helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller = helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(HaveLen(1))\n\t\t\t\tEventually(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(Equal([]string{\"0\"}))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"When trying to start a long-running process before the executor is up\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tsuiteContext.RepRunner.Start()\n\n\t\t\t\tdesiredAppRequest = models.DesireAppRequestFromCC{\n\t\t\t\t\tProcessGuid:  processGuid,\n\t\t\t\t\tDropletUri:   inigo_server.DownloadUrl(\"simple-echo-droplet.zip\"),\n\t\t\t\t\tStack:        suiteContext.RepStack,\n\t\t\t\t\tEnvironment:  []models.EnvironmentVariable{{Key: \"VCAP_APPLICATION\", Value: \"{}\"}},\n\t\t\t\t\tNumInstances: 1,\n\t\t\t\t\tRoutes:       []string{\"route-to-simple\"},\n\t\t\t\t\tStartCommand: \".\/run\",\n\t\t\t\t\tLogGuid:      appId,\n\t\t\t\t}\n\n\t\t\t\terr := suiteContext.NatsRunner.MessageBus.Publish(\"diego.desire.app\", desiredAppRequest.ToJSON())\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t\trunning_lrps_poller := helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller := helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tConsistently(running_lrps_poller, LONGER_TIMEOUT).Should(BeEmpty())\n\t\t\t\tConsistently(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(BeEmpty())\n\t\t\t})\n\n\t\t\tIt(\"Eventually brings the long-running process up\", func() {\n\t\t\t\tsuiteContext.ExecutorRunner.Start()\n\n\t\t\t\trunning_lrps_poller := helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller := helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(HaveLen(1))\n\t\t\t\tEventually(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(Equal([]string{\"0\"}))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"When the original request to stop a long-running process is lost\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tsuiteContext.RepRunner.Start()\n\t\t\t\tsuiteContext.ExecutorRunner.Start()\n\n\t\t\t\tdesiredAppRequest = models.DesireAppRequestFromCC{\n\t\t\t\t\tProcessGuid:  processGuid,\n\t\t\t\t\tDropletUri:   inigo_server.DownloadUrl(\"simple-echo-droplet.zip\"),\n\t\t\t\t\tStack:        suiteContext.RepStack,\n\t\t\t\t\tEnvironment:  []models.EnvironmentVariable{{Key: \"VCAP_APPLICATION\", Value: \"{}\"}},\n\t\t\t\t\tNumInstances: 1,\n\t\t\t\t\tRoutes:       []string{\"route-to-simple\"},\n\t\t\t\t\tStartCommand: \".\/run\",\n\t\t\t\t\tLogGuid:      appId,\n\t\t\t\t}\n\n\t\t\t\terr := suiteContext.NatsRunner.MessageBus.Publish(\"diego.desire.app\", desiredAppRequest.ToJSON())\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t\trunning_lrps_poller := helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller := helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(HaveLen(1))\n\t\t\t\tEventually(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(Equal([]string{\"0\"}))\n\t\t\t})\n\n\t\t\tIt(\"Eventually brings the long-running process down\", func() {\n\t\t\t\tsuiteContext.RepRunner.Stop()\n\n\t\t\t\tdesiredAppStopRequest := models.DesireAppRequestFromCC{\n\t\t\t\t\tProcessGuid:  processGuid,\n\t\t\t\t\tDropletUri:   inigo_server.DownloadUrl(\"simple-echo-droplet.zip\"),\n\t\t\t\t\tStack:        suiteContext.RepStack,\n\t\t\t\t\tEnvironment:  []models.EnvironmentVariable{{Key: \"VCAP_APPLICATION\", Value: \"{}\"}},\n\t\t\t\t\tNumInstances: 0,\n\t\t\t\t\tRoutes:       []string{\"route-to-simple\"},\n\t\t\t\t\tStartCommand: \".\/run\",\n\t\t\t\t\tLogGuid:      appId,\n\t\t\t\t}\n\n\t\t\t\terr := suiteContext.NatsRunner.MessageBus.Publish(\"diego.desire.app\", desiredAppStopRequest.ToJSON())\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t\trunning_lrps_poller := helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(HaveLen(1))\n\n\t\t\t\trunning_lrps_poller = helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\tConsistently(running_lrps_poller, LONGER_TIMEOUT).Should(HaveLen(1))\n\n\t\t\t\tsuiteContext.RepRunner.Start()\n\n\t\t\t\trunning_lrps_poller = helpers.RunningLRPInstancesPoller(tpsAddr, processGuid)\n\t\t\t\thello_world_instance_poller := helpers.HelloWorldInstancePoller(suiteContext.RouterRunner.Addr(), \"route-to-simple\")\n\t\t\t\tEventually(running_lrps_poller, LONGER_TIMEOUT).Should(BeEmpty())\n\t\t\t\tEventually(hello_world_instance_poller, LONGER_TIMEOUT, 1).Should(BeEmpty())\n\t\t\t})\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package wspacego\n\nimport (\n\t. \"github.com\/r7kamura\/gospel\"\n\t\"testing\"\n)\n\nfunc TestConerter(t *testing.T) {\n\tDescribe(t, \"whitespace のソースを文字や読みやすい文字列に変換する\", func() {\n\t\tContext(\"インスタンスの生成\", func() {\n\t\t\tIt(\"インスタンスが作成されること\", func() {\n\t\t\t\tExpect(NewConverter()).To(Exist)\n\t\t\t})\n\t\t})\n\t\tContext(\"スタックに関連する命令の生成\", func() {\n\t\t\tIt(\"スタックに１をプッシュするコマンドが作成されること\", func() {\n\t\t\t\tdata := []byte{' ', '\\t', '\\n'}\n\t\t\t\tsut := NewConverter()\n\t\t\t\tcmd, seek, err := sut.stackManipulation(data)\n\t\t\t\tExpect(err).To(NotExist)\n\t\t\t\tExpect(seek).To(Equal, len(data))\n\t\t\t\tExpect(cmd).To(Exist)\n\t\t\t\tExpect(cmd).To(Equal, NewSubCommandWithParam(\"stack\", \"push\", 1))\n\t\t\t})\n\t\t\tIt(\"スタックに2をプッシュするコマンドが作成されること\", func() {\n\t\t\t\tdata := []byte{' ', '\\t', ' ', '\\n'}\n\t\t\t\tsut := NewConverter()\n\t\t\t\tcmd, seek, err := sut.stackManipulation(data)\n\t\t\t\tExpect(err).To(NotExist)\n\t\t\t\tExpect(seek).To(Equal, len(data))\n\t\t\t\tExpect(cmd).To(Exist)\n\t\t\t\tExpect(cmd).To(Equal, NewSubCommandWithParam(\"stack\", \"push\", 2))\n\t\t\t})\n\t\t\tIt(\"スタックに4をプッシュするコマンドが作成されること\", func() {\n\t\t\t\tdata := []byte{' ', '\\t', ' ', ' ', '\\n'}\n\t\t\t\tsut := NewConverter()\n\t\t\t\tcmd, seek, err := sut.stackManipulation(data)\n\t\t\t\tExpect(err).To(NotExist)\n\t\t\t\tExpect(seek).To(Equal, len(data))\n\t\t\t\tExpect(cmd).To(Exist)\n\t\t\t\tExpect(cmd).To(Equal, NewSubCommandWithParam(\"stack\", \"push\", 4))\n\t\t\t})\n\t\t\tIt(\"スタックをコピーするコマンドが作成されること\", func() {\n\t\t\t\tdata := []byte{'\\n', ' '}\n\t\t\t\tsut := NewConverter()\n\t\t\t\tcmd, seek, err := sut.stackManipulation(data)\n\t\t\t\tExpect(err).To(NotExist)\n\t\t\t\tExpect(seek).To(Equal, len(data))\n\t\t\t\tExpect(cmd).To(Exist)\n\t\t\t\tExpect(cmd).To(Equal, NewSubCommand(\"stack\", \"copy\"))\n\t\t\t})\n\t\t})\n\t})\n}\n<commit_msg>スタックトップと２番目の値を入れ替える命令が作成されることを確認するテストケースを追加<commit_after>package wspacego\n\nimport (\n\t. \"github.com\/r7kamura\/gospel\"\n\t\"testing\"\n)\n\nfunc TestConerter(t *testing.T) {\n\tDescribe(t, \"whitespace のソースを文字や読みやすい文字列に変換する\", func() {\n\t\tContext(\"インスタンスの生成\", func() {\n\t\t\tIt(\"インスタンスが作成されること\", func() {\n\t\t\t\tExpect(NewConverter()).To(Exist)\n\t\t\t})\n\t\t})\n\t\tContext(\"スタックに関連する命令の生成\", func() {\n\t\t\tIt(\"スタックに１をプッシュするコマンドが作成されること\", func() {\n\t\t\t\tdata := []byte{' ', '\\t', '\\n'}\n\t\t\t\tsut := NewConverter()\n\t\t\t\tcmd, seek, err := sut.stackManipulation(data)\n\t\t\t\tExpect(err).To(NotExist)\n\t\t\t\tExpect(seek).To(Equal, len(data))\n\t\t\t\tExpect(cmd).To(Exist)\n\t\t\t\tExpect(cmd).To(Equal, NewSubCommandWithParam(\"stack\", \"push\", 1))\n\t\t\t})\n\t\t\tIt(\"スタックに2をプッシュするコマンドが作成されること\", func() {\n\t\t\t\tdata := []byte{' ', '\\t', ' ', '\\n'}\n\t\t\t\tsut := NewConverter()\n\t\t\t\tcmd, seek, err := sut.stackManipulation(data)\n\t\t\t\tExpect(err).To(NotExist)\n\t\t\t\tExpect(seek).To(Equal, len(data))\n\t\t\t\tExpect(cmd).To(Exist)\n\t\t\t\tExpect(cmd).To(Equal, NewSubCommandWithParam(\"stack\", \"push\", 2))\n\t\t\t})\n\t\t\tIt(\"スタックに4をプッシュするコマンドが作成されること\", func() {\n\t\t\t\tdata := []byte{' ', '\\t', ' ', ' ', '\\n'}\n\t\t\t\tsut := NewConverter()\n\t\t\t\tcmd, seek, err := sut.stackManipulation(data)\n\t\t\t\tExpect(err).To(NotExist)\n\t\t\t\tExpect(seek).To(Equal, len(data))\n\t\t\t\tExpect(cmd).To(Exist)\n\t\t\t\tExpect(cmd).To(Equal, NewSubCommandWithParam(\"stack\", \"push\", 4))\n\t\t\t})\n\t\t\tIt(\"スタックをコピーするコマンドが作成されること\", func() {\n\t\t\t\tdata := []byte{'\\n', ' '}\n\t\t\t\tsut := NewConverter()\n\t\t\t\tcmd, seek, err := sut.stackManipulation(data)\n\t\t\t\tExpect(err).To(NotExist)\n\t\t\t\tExpect(seek).To(Equal, len(data))\n\t\t\t\tExpect(cmd).To(Exist)\n\t\t\t\tExpect(cmd).To(Equal, NewSubCommand(\"stack\", \"copy\"))\n\t\t\t})\n\t\t\tIt(\"スタックをコピーするコマンドが作成されること\", func() {\n\t\t\t\tdata := []byte{'\\n', '\\t'}\n\t\t\t\tsut := NewConverter()\n\t\t\t\tcmd, seek, err := sut.stackManipulation(data)\n\t\t\t\tExpect(err).To(NotExist)\n\t\t\t\tExpect(seek).To(Equal, len(data))\n\t\t\t\tExpect(cmd).To(Exist)\n\t\t\t\tExpect(cmd).To(Equal, NewSubCommand(\"stack\", \"swap\"))\n\t\t\t})\n\t\t})\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package core\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n\n\tmath2 \"github.com\/ipfs\/go-ipfs\/thirdparty\/math2\"\n\tlgbl \"gx\/ipfs\/QmZ4zF1mBrt8C2mSCM4ZYE4aAnv78f7GvrzufJC4G5tecK\/go-libp2p-loggables\"\n\n\tpeer \"gx\/ipfs\/QmQsErDt8Qgw1XrsXf2BpEzDgGWtB1YLsTAARBup5b6B9W\/go-libp2p-peer\"\n\tgoprocess \"gx\/ipfs\/QmSF8fPo3jgVBAy8fpdjjYqgG87dkJgUprRBHRd2tmfgpP\/goprocess\"\n\tprocctx \"gx\/ipfs\/QmSF8fPo3jgVBAy8fpdjjYqgG87dkJgUprRBHRd2tmfgpP\/goprocess\/context\"\n\tperiodicproc \"gx\/ipfs\/QmSF8fPo3jgVBAy8fpdjjYqgG87dkJgUprRBHRd2tmfgpP\/goprocess\/periodic\"\n\tconfig \"gx\/ipfs\/QmYVqYJTVjetcf1guieEgWpK1PZtHPytP624vKzTF1P3r2\/go-ipfs-config\"\n\tinet \"gx\/ipfs\/QmZNJyx9GGCX4GeuHnLB8fxaxMLs4MjTjHokxfQcCd6Nve\/go-libp2p-net\"\n\tpstore \"gx\/ipfs\/Qmda4cPRvSRyox3SqgJN6DfSZGU5TtHufPTp9uXjFj71X6\/go-libp2p-peerstore\"\n\thost \"gx\/ipfs\/QmeMYW7Nj8jnnEfs9qhm7SxKkoDPUWXu3MsxX6BFwz34tf\/go-libp2p-host\"\n)\n\n\/\/ ErrNotEnoughBootstrapPeers signals that we do not have enough bootstrap\n\/\/ peers to bootstrap correctly.\nvar ErrNotEnoughBootstrapPeers = errors.New(\"not enough bootstrap peers to bootstrap\")\n\n\/\/ BootstrapConfig specifies parameters used in an IpfsNode's network\n\/\/ bootstrapping process.\ntype BootstrapConfig struct {\n\n\t\/\/ MinPeerThreshold governs whether to bootstrap more connections. If the\n\t\/\/ node has less open connections than this number, it will open connections\n\t\/\/ to the bootstrap nodes. From there, the routing system should be able\n\t\/\/ to use the connections to the bootstrap nodes to connect to even more\n\t\/\/ peers. Routing systems like the IpfsDHT do so in their own Bootstrap\n\t\/\/ process, which issues random queries to find more peers.\n\tMinPeerThreshold int\n\n\t\/\/ Period governs the periodic interval at which the node will\n\t\/\/ attempt to bootstrap. The bootstrap process is not very expensive, so\n\t\/\/ this threshold can afford to be small (<=30s).\n\tPeriod time.Duration\n\n\t\/\/ ConnectionTimeout determines how long to wait for a bootstrap\n\t\/\/ connection attempt before cancelling it.\n\tConnectionTimeout time.Duration\n\n\t\/\/ BootstrapPeers is a function that returns a set of bootstrap peers\n\t\/\/ for the bootstrap process to use. This makes it possible for clients\n\t\/\/ to control the peers the process uses at any moment.\n\tBootstrapPeers func() []pstore.PeerInfo\n}\n\n\/\/ DefaultBootstrapConfig specifies default sane parameters for bootstrapping.\nvar DefaultBootstrapConfig = BootstrapConfig{\n\tMinPeerThreshold:  4,\n\tPeriod:            30 * time.Second,\n\tConnectionTimeout: (30 * time.Second) \/ 3, \/\/ Perod \/ 3\n}\n\nfunc BootstrapConfigWithPeers(pis []pstore.PeerInfo) BootstrapConfig {\n\tcfg := DefaultBootstrapConfig\n\tcfg.BootstrapPeers = func() []pstore.PeerInfo {\n\t\treturn pis\n\t}\n\treturn cfg\n}\n\n\/\/ Bootstrap kicks off IpfsNode bootstrapping. This function will periodically\n\/\/ check the number of open connections and -- if there are too few -- initiate\n\/\/ connections to well-known bootstrap peers. It also kicks off subsystem\n\/\/ bootstrapping (i.e. routing).\nfunc Bootstrap(n *IpfsNode, cfg BootstrapConfig) (io.Closer, error) {\n\n\t\/\/ make a signal to wait for one bootstrap round to complete.\n\tdoneWithRound := make(chan struct{})\n\n\t\/\/ the periodic bootstrap function -- the connection supervisor\n\tperiodic := func(worker goprocess.Process) {\n\t\tctx := procctx.OnClosingContext(worker)\n\t\tdefer log.EventBegin(ctx, \"periodicBootstrap\", n.Identity).Done()\n\n\t\tif err := bootstrapRound(ctx, n.PeerHost, cfg); err != nil {\n\t\t\tlog.Event(ctx, \"bootstrapError\", n.Identity, lgbl.Error(err))\n\t\t\tlog.Debugf(\"%s bootstrap error: %s\", n.Identity, err)\n\t\t}\n\n\t\t<-doneWithRound\n\t}\n\n\t\/\/ kick off the node's periodic bootstrapping\n\tproc := periodicproc.Tick(cfg.Period, periodic)\n\tproc.Go(periodic) \/\/ run one right now.\n\n\t\/\/ kick off Routing.Bootstrap\n\tif n.Routing != nil {\n\t\tctx := procctx.OnClosingContext(proc)\n\t\tif err := n.Routing.Bootstrap(ctx); err != nil {\n\t\t\tproc.Close()\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdoneWithRound <- struct{}{}\n\tclose(doneWithRound) \/\/ it no longer blocks periodic\n\treturn proc, nil\n}\n\nfunc bootstrapRound(ctx context.Context, host host.Host, cfg BootstrapConfig) error {\n\n\tctx, cancel := context.WithTimeout(ctx, cfg.ConnectionTimeout)\n\tdefer cancel()\n\tid := host.ID()\n\n\t\/\/ get bootstrap peers from config. retrieving them here makes\n\t\/\/ sure we remain observant of changes to client configuration.\n\tpeers := cfg.BootstrapPeers()\n\tif len(peers) == 0 {\n\t\tlog.Error(\"no bootstrap nodes configured: go-ipfs may have difficulty connecting to the network\")\n\t}\n\t\/\/ determine how many bootstrap connections to open\n\tconnected := host.Network().Peers()\n\tif len(connected) >= cfg.MinPeerThreshold {\n\t\tlog.Event(ctx, \"bootstrapSkip\", id)\n\t\tlog.Debugf(\"%s core bootstrap skipped -- connected to %d (> %d) nodes\",\n\t\t\tid, len(connected), cfg.MinPeerThreshold)\n\t\treturn nil\n\t}\n\tnumToDial := cfg.MinPeerThreshold - len(connected)\n\n\t\/\/ filter out bootstrap nodes we are already connected to\n\tvar notConnected []pstore.PeerInfo\n\tfor _, p := range peers {\n\t\tif host.Network().Connectedness(p.ID) != inet.Connected {\n\t\t\tnotConnected = append(notConnected, p)\n\t\t}\n\t}\n\n\t\/\/ if connected to all bootstrap peer candidates, exit\n\tif len(notConnected) < 1 {\n\t\tlog.Debugf(\"%s no more bootstrap peers to create %d connections\", id, numToDial)\n\t\treturn ErrNotEnoughBootstrapPeers\n\t}\n\n\t\/\/ connect to a random susbset of bootstrap candidates\n\trandSubset := randomSubsetOfPeers(notConnected, numToDial)\n\n\tdefer log.EventBegin(ctx, \"bootstrapStart\", id).Done()\n\tlog.Debugf(\"%s bootstrapping to %d nodes: %s\", id, numToDial, randSubset)\n\treturn bootstrapConnect(ctx, host, randSubset)\n}\n\nfunc bootstrapConnect(ctx context.Context, ph host.Host, peers []pstore.PeerInfo) error {\n\tif len(peers) < 1 {\n\t\treturn ErrNotEnoughBootstrapPeers\n\t}\n\n\terrs := make(chan error, len(peers))\n\tvar wg sync.WaitGroup\n\tfor _, p := range peers {\n\n\t\t\/\/ performed asynchronously because when performed synchronously, if\n\t\t\/\/ one `Connect` call hangs, subsequent calls are more likely to\n\t\t\/\/ fail\/abort due to an expiring context.\n\t\t\/\/ Also, performed asynchronously for dial speed.\n\n\t\twg.Add(1)\n\t\tgo func(p pstore.PeerInfo) {\n\t\t\tdefer wg.Done()\n\t\t\tdefer log.EventBegin(ctx, \"bootstrapDial\", ph.ID(), p.ID).Done()\n\t\t\tlog.Debugf(\"%s bootstrapping to %s\", ph.ID(), p.ID)\n\n\t\t\tph.Peerstore().AddAddrs(p.ID, p.Addrs, pstore.PermanentAddrTTL)\n\t\t\tif err := ph.Connect(ctx, p); err != nil {\n\t\t\t\tlog.Event(ctx, \"bootstrapDialFailed\", p.ID)\n\t\t\t\tlog.Debugf(\"failed to bootstrap with %v: %s\", p.ID, err)\n\t\t\t\terrs <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Event(ctx, \"bootstrapDialSuccess\", p.ID)\n\t\t\tlog.Infof(\"bootstrapped with %v\", p.ID)\n\t\t}(p)\n\t}\n\twg.Wait()\n\n\t\/\/ our failure condition is when no connection attempt succeeded.\n\t\/\/ So drain the errs channel, counting the results.\n\tclose(errs)\n\tcount := 0\n\tvar err error\n\tfor err = range errs {\n\t\tif err != nil {\n\t\t\tcount++\n\t\t}\n\t}\n\tif count == len(peers) {\n\t\treturn fmt.Errorf(\"failed to bootstrap. %s\", err)\n\t}\n\treturn nil\n}\n\nfunc toPeerInfos(bpeers []config.BootstrapPeer) []pstore.PeerInfo {\n\tpinfos := make(map[peer.ID]*pstore.PeerInfo)\n\tfor _, bootstrap := range bpeers {\n\t\tpinfo, ok := pinfos[bootstrap.ID()]\n\t\tif !ok {\n\t\t\tpinfo = new(pstore.PeerInfo)\n\t\t\tpinfos[bootstrap.ID()] = pinfo\n\t\t\tpinfo.ID = bootstrap.ID()\n\t\t}\n\n\t\tpinfo.Addrs = append(pinfo.Addrs, bootstrap.Transport())\n\t}\n\n\tvar peers []pstore.PeerInfo\n\tfor _, pinfo := range pinfos {\n\t\tpeers = append(peers, *pinfo)\n\t}\n\n\treturn peers\n}\n\nfunc randomSubsetOfPeers(in []pstore.PeerInfo, max int) []pstore.PeerInfo {\n\tn := math2.IntMin(max, len(in))\n\tvar out []pstore.PeerInfo\n\tfor _, val := range rand.Perm(len(in)) {\n\t\tout = append(out, in[val])\n\t\tif len(out) >= n {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn out\n}\n<commit_msg>make warnings on no bootstrap peers less noisy<commit_after>package core\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n\n\tmath2 \"github.com\/ipfs\/go-ipfs\/thirdparty\/math2\"\n\tlgbl \"gx\/ipfs\/QmZ4zF1mBrt8C2mSCM4ZYE4aAnv78f7GvrzufJC4G5tecK\/go-libp2p-loggables\"\n\n\tpeer \"gx\/ipfs\/QmQsErDt8Qgw1XrsXf2BpEzDgGWtB1YLsTAARBup5b6B9W\/go-libp2p-peer\"\n\tgoprocess \"gx\/ipfs\/QmSF8fPo3jgVBAy8fpdjjYqgG87dkJgUprRBHRd2tmfgpP\/goprocess\"\n\tprocctx \"gx\/ipfs\/QmSF8fPo3jgVBAy8fpdjjYqgG87dkJgUprRBHRd2tmfgpP\/goprocess\/context\"\n\tperiodicproc \"gx\/ipfs\/QmSF8fPo3jgVBAy8fpdjjYqgG87dkJgUprRBHRd2tmfgpP\/goprocess\/periodic\"\n\tconfig \"gx\/ipfs\/QmYVqYJTVjetcf1guieEgWpK1PZtHPytP624vKzTF1P3r2\/go-ipfs-config\"\n\tinet \"gx\/ipfs\/QmZNJyx9GGCX4GeuHnLB8fxaxMLs4MjTjHokxfQcCd6Nve\/go-libp2p-net\"\n\tpstore \"gx\/ipfs\/Qmda4cPRvSRyox3SqgJN6DfSZGU5TtHufPTp9uXjFj71X6\/go-libp2p-peerstore\"\n\thost \"gx\/ipfs\/QmeMYW7Nj8jnnEfs9qhm7SxKkoDPUWXu3MsxX6BFwz34tf\/go-libp2p-host\"\n)\n\n\/\/ ErrNotEnoughBootstrapPeers signals that we do not have enough bootstrap\n\/\/ peers to bootstrap correctly.\nvar ErrNotEnoughBootstrapPeers = errors.New(\"not enough bootstrap peers to bootstrap\")\n\n\/\/ BootstrapConfig specifies parameters used in an IpfsNode's network\n\/\/ bootstrapping process.\ntype BootstrapConfig struct {\n\n\t\/\/ MinPeerThreshold governs whether to bootstrap more connections. If the\n\t\/\/ node has less open connections than this number, it will open connections\n\t\/\/ to the bootstrap nodes. From there, the routing system should be able\n\t\/\/ to use the connections to the bootstrap nodes to connect to even more\n\t\/\/ peers. Routing systems like the IpfsDHT do so in their own Bootstrap\n\t\/\/ process, which issues random queries to find more peers.\n\tMinPeerThreshold int\n\n\t\/\/ Period governs the periodic interval at which the node will\n\t\/\/ attempt to bootstrap. The bootstrap process is not very expensive, so\n\t\/\/ this threshold can afford to be small (<=30s).\n\tPeriod time.Duration\n\n\t\/\/ ConnectionTimeout determines how long to wait for a bootstrap\n\t\/\/ connection attempt before cancelling it.\n\tConnectionTimeout time.Duration\n\n\t\/\/ BootstrapPeers is a function that returns a set of bootstrap peers\n\t\/\/ for the bootstrap process to use. This makes it possible for clients\n\t\/\/ to control the peers the process uses at any moment.\n\tBootstrapPeers func() []pstore.PeerInfo\n}\n\n\/\/ DefaultBootstrapConfig specifies default sane parameters for bootstrapping.\nvar DefaultBootstrapConfig = BootstrapConfig{\n\tMinPeerThreshold:  4,\n\tPeriod:            30 * time.Second,\n\tConnectionTimeout: (30 * time.Second) \/ 3, \/\/ Perod \/ 3\n}\n\nfunc BootstrapConfigWithPeers(pis []pstore.PeerInfo) BootstrapConfig {\n\tcfg := DefaultBootstrapConfig\n\tcfg.BootstrapPeers = func() []pstore.PeerInfo {\n\t\treturn pis\n\t}\n\treturn cfg\n}\n\n\/\/ Bootstrap kicks off IpfsNode bootstrapping. This function will periodically\n\/\/ check the number of open connections and -- if there are too few -- initiate\n\/\/ connections to well-known bootstrap peers. It also kicks off subsystem\n\/\/ bootstrapping (i.e. routing).\nfunc Bootstrap(n *IpfsNode, cfg BootstrapConfig) (io.Closer, error) {\n\n\t\/\/ make a signal to wait for one bootstrap round to complete.\n\tdoneWithRound := make(chan struct{})\n\n\t\/\/ the periodic bootstrap function -- the connection supervisor\n\tperiodic := func(worker goprocess.Process) {\n\t\tctx := procctx.OnClosingContext(worker)\n\t\tdefer log.EventBegin(ctx, \"periodicBootstrap\", n.Identity).Done()\n\n\t\tif err := bootstrapRound(ctx, n.PeerHost, cfg); err != nil {\n\t\t\tlog.Event(ctx, \"bootstrapError\", n.Identity, lgbl.Error(err))\n\t\t\tlog.Debugf(\"%s bootstrap error: %s\", n.Identity, err)\n\t\t}\n\n\t\t<-doneWithRound\n\t}\n\n\t\/\/ kick off the node's periodic bootstrapping\n\tproc := periodicproc.Tick(cfg.Period, periodic)\n\tproc.Go(periodic) \/\/ run one right now.\n\n\t\/\/ kick off Routing.Bootstrap\n\tif n.Routing != nil {\n\t\tctx := procctx.OnClosingContext(proc)\n\t\tif err := n.Routing.Bootstrap(ctx); err != nil {\n\t\t\tproc.Close()\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdoneWithRound <- struct{}{}\n\tclose(doneWithRound) \/\/ it no longer blocks periodic\n\treturn proc, nil\n}\n\nfunc bootstrapRound(ctx context.Context, host host.Host, cfg BootstrapConfig) error {\n\n\tctx, cancel := context.WithTimeout(ctx, cfg.ConnectionTimeout)\n\tdefer cancel()\n\tid := host.ID()\n\n\t\/\/ get bootstrap peers from config. retrieving them here makes\n\t\/\/ sure we remain observant of changes to client configuration.\n\tpeers := cfg.BootstrapPeers()\n\t\/\/ determine how many bootstrap connections to open\n\tconnected := host.Network().Peers()\n\tif len(connected) >= cfg.MinPeerThreshold {\n\t\tlog.Event(ctx, \"bootstrapSkip\", id)\n\t\tlog.Debugf(\"%s core bootstrap skipped -- connected to %d (> %d) nodes\",\n\t\t\tid, len(connected), cfg.MinPeerThreshold)\n\t\treturn nil\n\t}\n\tnumToDial := cfg.MinPeerThreshold - len(connected)\n\n\t\/\/ filter out bootstrap nodes we are already connected to\n\tvar notConnected []pstore.PeerInfo\n\tfor _, p := range peers {\n\t\tif host.Network().Connectedness(p.ID) != inet.Connected {\n\t\t\tnotConnected = append(notConnected, p)\n\t\t}\n\t}\n\n\t\/\/ if connected to all bootstrap peer candidates, exit\n\tif len(notConnected) < 1 {\n\t\tlog.Debugf(\"%s no more bootstrap peers to create %d connections\", id, numToDial)\n\t\tif len(peers) == 0 {\n\t\t\t\/\/ We *need* to bootstrap but we have no bootstrap peers\n\t\t\t\/\/ configured *at all*, inform the user.\n\t\t\tlog.Error(\"no bootstrap nodes configured: go-ipfs may have difficulty connecting to the network\")\n\t\t}\n\t\treturn ErrNotEnoughBootstrapPeers\n\t}\n\n\t\/\/ connect to a random susbset of bootstrap candidates\n\trandSubset := randomSubsetOfPeers(notConnected, numToDial)\n\n\tdefer log.EventBegin(ctx, \"bootstrapStart\", id).Done()\n\tlog.Debugf(\"%s bootstrapping to %d nodes: %s\", id, numToDial, randSubset)\n\treturn bootstrapConnect(ctx, host, randSubset)\n}\n\nfunc bootstrapConnect(ctx context.Context, ph host.Host, peers []pstore.PeerInfo) error {\n\tif len(peers) < 1 {\n\t\treturn ErrNotEnoughBootstrapPeers\n\t}\n\n\terrs := make(chan error, len(peers))\n\tvar wg sync.WaitGroup\n\tfor _, p := range peers {\n\n\t\t\/\/ performed asynchronously because when performed synchronously, if\n\t\t\/\/ one `Connect` call hangs, subsequent calls are more likely to\n\t\t\/\/ fail\/abort due to an expiring context.\n\t\t\/\/ Also, performed asynchronously for dial speed.\n\n\t\twg.Add(1)\n\t\tgo func(p pstore.PeerInfo) {\n\t\t\tdefer wg.Done()\n\t\t\tdefer log.EventBegin(ctx, \"bootstrapDial\", ph.ID(), p.ID).Done()\n\t\t\tlog.Debugf(\"%s bootstrapping to %s\", ph.ID(), p.ID)\n\n\t\t\tph.Peerstore().AddAddrs(p.ID, p.Addrs, pstore.PermanentAddrTTL)\n\t\t\tif err := ph.Connect(ctx, p); err != nil {\n\t\t\t\tlog.Event(ctx, \"bootstrapDialFailed\", p.ID)\n\t\t\t\tlog.Debugf(\"failed to bootstrap with %v: %s\", p.ID, err)\n\t\t\t\terrs <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Event(ctx, \"bootstrapDialSuccess\", p.ID)\n\t\t\tlog.Infof(\"bootstrapped with %v\", p.ID)\n\t\t}(p)\n\t}\n\twg.Wait()\n\n\t\/\/ our failure condition is when no connection attempt succeeded.\n\t\/\/ So drain the errs channel, counting the results.\n\tclose(errs)\n\tcount := 0\n\tvar err error\n\tfor err = range errs {\n\t\tif err != nil {\n\t\t\tcount++\n\t\t}\n\t}\n\tif count == len(peers) {\n\t\treturn fmt.Errorf(\"failed to bootstrap. %s\", err)\n\t}\n\treturn nil\n}\n\nfunc toPeerInfos(bpeers []config.BootstrapPeer) []pstore.PeerInfo {\n\tpinfos := make(map[peer.ID]*pstore.PeerInfo)\n\tfor _, bootstrap := range bpeers {\n\t\tpinfo, ok := pinfos[bootstrap.ID()]\n\t\tif !ok {\n\t\t\tpinfo = new(pstore.PeerInfo)\n\t\t\tpinfos[bootstrap.ID()] = pinfo\n\t\t\tpinfo.ID = bootstrap.ID()\n\t\t}\n\n\t\tpinfo.Addrs = append(pinfo.Addrs, bootstrap.Transport())\n\t}\n\n\tvar peers []pstore.PeerInfo\n\tfor _, pinfo := range pinfos {\n\t\tpeers = append(peers, *pinfo)\n\t}\n\n\treturn peers\n}\n\nfunc randomSubsetOfPeers(in []pstore.PeerInfo, max int) []pstore.PeerInfo {\n\tn := math2.IntMin(max, len(in))\n\tvar out []pstore.PeerInfo\n\tfor _, val := range rand.Perm(len(in)) {\n\t\tout = append(out, in[val])\n\t\tif len(out) >= n {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn out\n}\n<|endoftext|>"}
{"text":"<commit_before>package event\n\nimport \"io\"\n\n\/\/ SubscriptionOpt represents a subscriber option. Use the options exposed by the implementation of choice.\ntype SubscriptionOpt = func(interface{}) error\n\n\/\/ EmitterOpt represents an emitter option. Use the options exposed by the implementation of choice.\ntype EmitterOpt = func(interface{}) error\n\n\/\/ CancelFunc closes a subscriber.\ntype CancelFunc = func()\n\n\/\/ Emitter represents an actor that emits events onto the eventbus.\ntype Emitter interface {\n\tio.Closer\n\n\t\/\/ Emit emits an event onto the eventbus. If any channel subscribed to the topic is blocked,\n\t\/\/ calls to Emit will block.\n\t\/\/\n\t\/\/ Calling this function with wrong event type will cause a panic.\n\tEmit(evt interface{})\n}\n\n\/\/ Subscription represents a subscription to one or multiple event types.\ntype Subscription interface {\n\tio.Closer\n\n\t\/\/ Out returns the channel from which to consume events.\n\tOut() <-chan interface{}\n}\n\n\/\/ Bus is an interface for a type-based event delivery system.\ntype Bus interface {\n\t\/\/ Subscribe creates a new Subscription.\n\t\/\/\n\t\/\/ eventType can be either a pointer to a single event type, or a slice of pointers to\n\t\/\/ subscribe to multiple event types at once, under a single subscription (and channel).\n\t\/\/\n\t\/\/ Failing to drain the channel may cause publishers to block.\n\t\/\/\n\t\/\/ Simple example\n\t\/\/\n\t\/\/  sub, err := eventbus.Subscribe(new(EventType))\n\t\/\/  defer sub.Close()\n\t\/\/  for e := range sub.Out() {\n\t\/\/    event := e.(EventType) \/\/ guaranteed safe\n\t\/\/    [...]\n\t\/\/  }\n\t\/\/\n\t\/\/ Multi-type example\n\t\/\/\n\t\/\/  sub, err := eventbus.Subscribe([]interface{}{new(EventA), new(EventB)})\n\t\/\/  defer sub.Close()\n\t\/\/  for e := range sub.Out() {\n\t\/\/    select e.(type):\n\t\/\/      case EventA:\n\t\/\/        [...]\n\t\/\/      case EventB:\n\t\/\/        [...]\n\t\/\/    }\n\t\/\/  }\n\tSubscribe(eventType interface{}, opts ...SubscriptionOpt) (Subscription, error)\n\n\t\/\/ Emitter creates a new event emitter.\n\t\/\/\n\t\/\/ eventType accepts typed nil pointers, and uses the type information for wiring purposes.\n\t\/\/\n\t\/\/ Example:\n\t\/\/  em, err := eventbus.Emitter(new(EventT))\n\t\/\/  defer em.Close() \/\/ MUST call this after being done with the emitter\n\t\/\/  em.Emit(EventT{})\n\tEmitter(eventType interface{}, opts ...EmitterOpt) (Emitter, error)\n}\n<commit_msg>Return error in Emit<commit_after>package event\n\nimport \"io\"\n\n\/\/ SubscriptionOpt represents a subscriber option. Use the options exposed by the implementation of choice.\ntype SubscriptionOpt = func(interface{}) error\n\n\/\/ EmitterOpt represents an emitter option. Use the options exposed by the implementation of choice.\ntype EmitterOpt = func(interface{}) error\n\n\/\/ CancelFunc closes a subscriber.\ntype CancelFunc = func()\n\n\/\/ Emitter represents an actor that emits events onto the eventbus.\ntype Emitter interface {\n\tio.Closer\n\n\t\/\/ Emit emits an event onto the eventbus. If any channel subscribed to the topic is blocked,\n\t\/\/ calls to Emit will block.\n\t\/\/\n\t\/\/ Calling this function with wrong event type will cause a panic.\n\tEmit(evt interface{}) error\n}\n\n\/\/ Subscription represents a subscription to one or multiple event types.\ntype Subscription interface {\n\tio.Closer\n\n\t\/\/ Out returns the channel from which to consume events.\n\tOut() <-chan interface{}\n}\n\n\/\/ Bus is an interface for a type-based event delivery system.\ntype Bus interface {\n\t\/\/ Subscribe creates a new Subscription.\n\t\/\/\n\t\/\/ eventType can be either a pointer to a single event type, or a slice of pointers to\n\t\/\/ subscribe to multiple event types at once, under a single subscription (and channel).\n\t\/\/\n\t\/\/ Failing to drain the channel may cause publishers to block.\n\t\/\/\n\t\/\/ Simple example\n\t\/\/\n\t\/\/  sub, err := eventbus.Subscribe(new(EventType))\n\t\/\/  defer sub.Close()\n\t\/\/  for e := range sub.Out() {\n\t\/\/    event := e.(EventType) \/\/ guaranteed safe\n\t\/\/    [...]\n\t\/\/  }\n\t\/\/\n\t\/\/ Multi-type example\n\t\/\/\n\t\/\/  sub, err := eventbus.Subscribe([]interface{}{new(EventA), new(EventB)})\n\t\/\/  defer sub.Close()\n\t\/\/  for e := range sub.Out() {\n\t\/\/    select e.(type):\n\t\/\/      case EventA:\n\t\/\/        [...]\n\t\/\/      case EventB:\n\t\/\/        [...]\n\t\/\/    }\n\t\/\/  }\n\tSubscribe(eventType interface{}, opts ...SubscriptionOpt) (Subscription, error)\n\n\t\/\/ Emitter creates a new event emitter.\n\t\/\/\n\t\/\/ eventType accepts typed nil pointers, and uses the type information for wiring purposes.\n\t\/\/\n\t\/\/ Example:\n\t\/\/  em, err := eventbus.Emitter(new(EventT))\n\t\/\/  defer em.Close() \/\/ MUST call this after being done with the emitter\n\t\/\/  em.Emit(EventT{})\n\tEmitter(eventType interface{}, opts ...EmitterOpt) (Emitter, error)\n}\n<|endoftext|>"}
{"text":"<commit_before>package eval\n\nimport (\n\t\"github.com\/nitrogen-lang\/nitrogen\/src\/ast\"\n\t\"github.com\/nitrogen-lang\/nitrogen\/src\/object\"\n)\n\nfunc (i *Interpreter) evalAssignment(stmt *ast.AssignStatement, env *object.Environment) object.Object {\n\tif left, ok := stmt.Left.(*ast.IndexExpression); ok {\n\t\treturn i.assignIndexedValue(left, stmt.Value, env)\n\t}\n\n\tident, ok := stmt.Left.(*ast.Identifier)\n\tif !ok {\n\t\treturn object.NewException(\"Invalid variable name, expected identifier, got %s\",\n\t\t\tstmt.Left.String())\n\t}\n\n\treturn i.assignIdentValue(ident, stmt.Value, false, env)\n}\n\nfunc (i *Interpreter) assignIdentValue(\n\tname *ast.Identifier,\n\tval ast.Expression,\n\tnew bool,\n\tenv *object.Environment) object.Object {\n\t\/\/ Protect builtin functions\n\tif builtin := getBuiltin(name.Value); builtin != nil {\n\t\treturn object.NewException(\n\t\t\t\"Attempted redeclaration of builtin function '%s'\",\n\t\t\tname.Value,\n\t\t)\n\t}\n\n\tif !new { \/\/ Variables must be declared before use\n\t\tif _, exists := env.Get(name.Value); !exists {\n\t\t\treturn object.NewException(\"Assignment to uninitialized variable %s\", name.Value)\n\t\t}\n\t}\n\n\tif env.IsConst(name.Value) {\n\t\treturn object.NewException(\"Assignment to declared constant %s\", name.Value)\n\t}\n\n\tevaled := i.Eval(val, env)\n\tif isException(evaled) {\n\t\treturn evaled\n\t}\n\n\t\/\/ Ignore error since we check for consant above\n\tif new {\n\t\tenv.Create(name.Value, evaled)\n\t} else {\n\t\tenv.Set(name.Value, evaled)\n\t}\n\treturn object.NullConst\n}\n\nfunc (i *Interpreter) assignConstIdentValue(\n\tname *ast.Identifier,\n\tval ast.Expression,\n\tenv *object.Environment) object.Object {\n\t\/\/ Protect builtin functions\n\tif builtin := getBuiltin(name.Value); builtin != nil {\n\t\treturn object.NewException(\n\t\t\t\"Attempted redeclaration of builtin function '%s'\",\n\t\t\tname.Value,\n\t\t)\n\t}\n\n\tif _, exists := env.Get(name.Value); exists { \/\/ Constants can't redeclare an existing var\n\t\treturn object.NewException(\"Can't assign constant to variable `%s`\", name.Value)\n\t}\n\n\tevaled := i.Eval(val, env)\n\tif isException(evaled) {\n\t\treturn evaled\n\t}\n\n\tif !object.ObjectIs(evaled, object.IntergerObj, object.FloatObj, object.StringObj, object.NullObj, object.BooleanObj, object.ModuleObj) {\n\t\treturn object.NewException(\"Constants must be int, float, string, bool or null\")\n\t}\n\n\t\/\/ Ignore error since we check above\n\tenv.CreateConst(name.Value, evaled)\n\treturn object.NullConst\n}\n\nfunc (i *Interpreter) assignIndexedValue(\n\te *ast.IndexExpression,\n\tval ast.Expression,\n\tenv *object.Environment) object.Object {\n\tindexed := i.Eval(e.Left, env)\n\tif isException(indexed) {\n\t\treturn indexed\n\t}\n\n\tindex := i.Eval(e.Index, env)\n\tif isException(indexed) {\n\t\treturn indexed\n\t}\n\n\tswitch indexed.Type() {\n\tcase object.ArrayObj:\n\t\treturn i.assignArrayIndex(indexed.(*object.Array), index, val, env)\n\tcase object.HashObj:\n\t\treturn i.assignHashMapIndex(indexed.(*object.Hash), index, val, env)\n\t}\n\treturn object.NullConst\n}\n\nfunc (i *Interpreter) assignArrayIndex(\n\tarray *object.Array,\n\tindex object.Object,\n\tval ast.Expression,\n\tenv *object.Environment) object.Object {\n\n\tin, ok := index.(*object.Integer)\n\tif !ok {\n\t\treturn object.NewException(\"Invalid array index type %s\", index.(object.Object).Type())\n\t}\n\n\tvalue := i.Eval(val, env)\n\tif isException(value) {\n\t\treturn value\n\t}\n\n\tif in.Value < 0 || in.Value > int64(len(array.Elements)-1) {\n\t\treturn object.NewException(\"Index out of bounds: %s\", index.Inspect())\n\t}\n\n\tarray.Elements[in.Value] = value\n\treturn object.NullConst\n}\n\nfunc (i *Interpreter) assignHashMapIndex(\n\thashmap *object.Hash,\n\tindex object.Object,\n\tval ast.Expression,\n\tenv *object.Environment) object.Object {\n\n\thashable, ok := index.(object.Hashable)\n\tif !ok {\n\t\treturn object.NewException(\"Invalid index type %s\", index.Type())\n\t}\n\n\tvalue := i.Eval(val, env)\n\tif isException(value) {\n\t\treturn value\n\t}\n\n\thashmap.Pairs[hashable.HashKey()] = object.HashPair{\n\t\tKey:   index,\n\t\tValue: value,\n\t}\n\treturn object.NullConst\n}\n<commit_msg>Implement assignment to a module variable<commit_after>package eval\n\nimport (\n\t\"github.com\/nitrogen-lang\/nitrogen\/src\/ast\"\n\t\"github.com\/nitrogen-lang\/nitrogen\/src\/object\"\n)\n\nfunc (i *Interpreter) evalAssignment(stmt *ast.AssignStatement, env *object.Environment) object.Object {\n\tif left, ok := stmt.Left.(*ast.IndexExpression); ok {\n\t\treturn i.assignIndexedValue(left, stmt.Value, env)\n\t}\n\n\tident, ok := stmt.Left.(*ast.Identifier)\n\tif !ok {\n\t\treturn object.NewException(\"Invalid variable name, expected identifier, got %s\",\n\t\t\tstmt.Left.String())\n\t}\n\n\treturn i.assignIdentValue(ident, stmt.Value, false, env)\n}\n\nfunc (i *Interpreter) assignIdentValue(\n\tname *ast.Identifier,\n\tval ast.Expression,\n\tnew bool,\n\tenv *object.Environment) object.Object {\n\t\/\/ Protect builtin functions\n\tif builtin := getBuiltin(name.Value); builtin != nil {\n\t\treturn object.NewException(\n\t\t\t\"Attempted redeclaration of builtin function '%s'\",\n\t\t\tname.Value,\n\t\t)\n\t}\n\n\tif !new { \/\/ Variables must be declared before use\n\t\tif _, exists := env.Get(name.Value); !exists {\n\t\t\treturn object.NewException(\"Assignment to uninitialized variable %s\", name.Value)\n\t\t}\n\t}\n\n\tif env.IsConst(name.Value) {\n\t\treturn object.NewException(\"Assignment to declared constant %s\", name.Value)\n\t}\n\n\tevaled := i.Eval(val, env)\n\tif isException(evaled) {\n\t\treturn evaled\n\t}\n\n\t\/\/ Ignore error since we check for consant above\n\tif new {\n\t\tenv.Create(name.Value, evaled)\n\t} else {\n\t\tenv.Set(name.Value, evaled)\n\t}\n\treturn object.NullConst\n}\n\nfunc (i *Interpreter) assignConstIdentValue(\n\tname *ast.Identifier,\n\tval ast.Expression,\n\tenv *object.Environment) object.Object {\n\t\/\/ Protect builtin functions\n\tif builtin := getBuiltin(name.Value); builtin != nil {\n\t\treturn object.NewException(\n\t\t\t\"Attempted redeclaration of builtin function '%s'\",\n\t\t\tname.Value,\n\t\t)\n\t}\n\n\tif _, exists := env.Get(name.Value); exists { \/\/ Constants can't redeclare an existing var\n\t\treturn object.NewException(\"Can't assign constant to variable `%s`\", name.Value)\n\t}\n\n\tevaled := i.Eval(val, env)\n\tif isException(evaled) {\n\t\treturn evaled\n\t}\n\n\tif !object.ObjectIs(evaled, object.IntergerObj, object.FloatObj, object.StringObj, object.NullObj, object.BooleanObj, object.ModuleObj) {\n\t\treturn object.NewException(\"Constants must be int, float, string, bool or null\")\n\t}\n\n\t\/\/ Ignore error since we check above\n\tenv.CreateConst(name.Value, evaled)\n\treturn object.NullConst\n}\n\nfunc (i *Interpreter) assignIndexedValue(\n\te *ast.IndexExpression,\n\tval ast.Expression,\n\tenv *object.Environment) object.Object {\n\tindexed := i.Eval(e.Left, env)\n\tif isException(indexed) {\n\t\treturn indexed\n\t}\n\n\tindex := i.Eval(e.Index, env)\n\tif isException(indexed) {\n\t\treturn indexed\n\t}\n\n\tswitch indexed.Type() {\n\tcase object.ArrayObj:\n\t\treturn i.assignArrayIndex(indexed.(*object.Array), index, val, env)\n\tcase object.HashObj:\n\t\treturn i.assignHashMapIndex(indexed.(*object.Hash), index, val, env)\n\tcase object.ModuleObj:\n\t\treturn i.assignModuleVariable(indexed.(*object.Module), index, val, env)\n\t}\n\treturn object.NullConst\n}\n\nfunc (i *Interpreter) assignArrayIndex(\n\tarray *object.Array,\n\tindex object.Object,\n\tval ast.Expression,\n\tenv *object.Environment) object.Object {\n\n\tin, ok := index.(*object.Integer)\n\tif !ok {\n\t\treturn object.NewException(\"Invalid array index type %s\", index.(object.Object).Type())\n\t}\n\n\tvalue := i.Eval(val, env)\n\tif isException(value) {\n\t\treturn value\n\t}\n\n\tif in.Value < 0 || in.Value > int64(len(array.Elements)-1) {\n\t\treturn object.NewException(\"Index out of bounds: %s\", index.Inspect())\n\t}\n\n\tarray.Elements[in.Value] = value\n\treturn object.NullConst\n}\n\nfunc (i *Interpreter) assignHashMapIndex(\n\thashmap *object.Hash,\n\tindex object.Object,\n\tval ast.Expression,\n\tenv *object.Environment) object.Object {\n\n\thashable, ok := index.(object.Hashable)\n\tif !ok {\n\t\treturn object.NewException(\"Invalid index type %s\", index.Type())\n\t}\n\n\tvalue := i.Eval(val, env)\n\tif isException(value) {\n\t\treturn value\n\t}\n\n\thashmap.Pairs[hashable.HashKey()] = object.HashPair{\n\t\tKey:   index,\n\t\tValue: value,\n\t}\n\treturn object.NullConst\n}\n\nfunc (i *Interpreter) assignModuleVariable(\n\tmodule *object.Module,\n\tindex object.Object,\n\tval ast.Expression,\n\tenv *object.Environment) object.Object {\n\n\thashable, ok := index.(*object.String)\n\tif !ok {\n\t\treturn object.NewException(\"Invalid index type %s\", index.Type())\n\t}\n\n\tif _, exists := module.Vars[hashable.Value]; !exists {\n\t\treturn object.NewException(\"Module %s has no assignable variable %s\", module.Name, hashable.Value)\n\t}\n\n\tvalue := i.Eval(val, env)\n\tif isException(value) {\n\t\treturn value\n\t}\n\n\tmodule.Vars[hashable.Value] = value\n\treturn object.NullConst\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 The Hugo Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package create provides functions to create new content.\npackage create\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/gohugoio\/hugo\/hugofs\/glob\"\n\n\t\"github.com\/gohugoio\/hugo\/common\/paths\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"github.com\/gohugoio\/hugo\/common\/hexec\"\n\t\"github.com\/gohugoio\/hugo\/hugofs\/files\"\n\n\t\"github.com\/gohugoio\/hugo\/hugofs\"\n\n\t\"github.com\/gohugoio\/hugo\/helpers\"\n\t\"github.com\/gohugoio\/hugo\/hugolib\"\n\t\"github.com\/spf13\/afero\"\n)\n\nconst (\n\t\/\/ DefaultArchetypeTemplateTemplate is the template used in 'hugo new site'\n\t\/\/ and the template we use as a fall back.\n\tDefaultArchetypeTemplateTemplate = `---\ntitle: \"{{ replace .Name \"-\" \" \" | title }}\"\ndate: {{ .Date }}\ndraft: true\n---\n\n`\n)\n\n\/\/ NewContent creates a new content file in h (or a full bundle if the archetype is a directory)\n\/\/ in targetPath.\nfunc NewContent(h *hugolib.HugoSites, kind, targetPath string) error {\n\tif h.BaseFs.Content.Dirs == nil {\n\t\treturn errors.New(\"no existing content directory configured for this project\")\n\t}\n\n\tcf := hugolib.NewContentFactory(h)\n\n\tif kind == \"\" {\n\t\tkind = cf.SectionFromFilename(targetPath)\n\t}\n\n\tb := &contentBuilder{\n\t\tarcheTypeFs: h.PathSpec.BaseFs.Archetypes.Fs,\n\t\tsourceFs:    h.PathSpec.Fs.Source,\n\t\tps:          h.PathSpec,\n\t\th:           h,\n\t\tcf:          cf,\n\n\t\tkind:       kind,\n\t\ttargetPath: targetPath,\n\t}\n\n\text := paths.Ext(targetPath)\n\n\tb.setArcheTypeFilenameToUse(ext)\n\n\twithBuildLock := func() (string, error) {\n\t\tunlock, err := h.BaseFs.LockBuild()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to acquire a build lock: %s\", err)\n\t\t}\n\t\tdefer unlock()\n\n\t\tif b.isDir {\n\t\t\treturn \"\", b.buildDir()\n\t\t}\n\n\t\tif ext == \"\" {\n\t\t\treturn \"\", errors.Errorf(\"failed to resolve %q to a archetype template\", targetPath)\n\t\t}\n\n\t\tif !files.IsContentFile(b.targetPath) {\n\t\t\treturn \"\", errors.Errorf(\"target path %q is not a known content format\", b.targetPath)\n\t\t}\n\n\t\treturn b.buildFile()\n\n\t}\n\n\tfilename, err := withBuildLock()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif filename != \"\" {\n\t\treturn b.openInEditorIfConfigured(filename)\n\t}\n\n\treturn nil\n\n}\n\ntype contentBuilder struct {\n\tarcheTypeFs afero.Fs\n\tsourceFs    afero.Fs\n\n\tps *helpers.PathSpec\n\th  *hugolib.HugoSites\n\tcf hugolib.ContentFactory\n\n\t\/\/ Builder state\n\tarchetypeFilename string\n\ttargetPath        string\n\tkind              string\n\tisDir             bool\n\tdirMap            archetypeMap\n}\n\nfunc (b *contentBuilder) buildDir() error {\n\t\/\/ Split the dir into content files and the rest.\n\tif err := b.mapArcheTypeDir(); err != nil {\n\t\treturn err\n\t}\n\n\tvar contentTargetFilenames []string\n\tvar baseDir string\n\n\tfor _, fi := range b.dirMap.contentFiles {\n\t\ttargetFilename := filepath.Join(b.targetPath, strings.TrimPrefix(fi.Meta().Path, b.archetypeFilename))\n\t\tabs, err := b.cf.CreateContentPlaceHolder(targetFilename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif baseDir == \"\" {\n\t\t\tbaseDir = strings.TrimSuffix(abs, targetFilename)\n\t\t}\n\n\t\tcontentTargetFilenames = append(contentTargetFilenames, abs)\n\t}\n\n\tvar contentInclusionFilter *glob.FilenameFilter\n\tif !b.dirMap.siteUsed {\n\t\t\/\/ We don't need to build everything.\n\t\tcontentInclusionFilter = glob.NewFilenameFilterForInclusionFunc(func(filename string) bool {\n\t\t\tfilename = strings.TrimPrefix(filename, string(os.PathSeparator))\n\t\t\tfor _, cn := range contentTargetFilenames {\n\t\t\t\tif strings.Contains(cn, filename) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\n\t}\n\n\tif err := b.h.Build(hugolib.BuildCfg{NoBuildLock: true, SkipRender: true, ContentInclusionFilter: contentInclusionFilter}); err != nil {\n\t\treturn err\n\t}\n\n\tfor i, filename := range contentTargetFilenames {\n\t\tif err := b.applyArcheType(filename, b.dirMap.contentFiles[i].Meta().Path); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Copy the rest as is.\n\tfor _, f := range b.dirMap.otherFiles {\n\t\tmeta := f.Meta()\n\t\tfilename := meta.Path\n\n\t\tin, err := meta.Open()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to open non-content file\")\n\t\t}\n\n\t\ttargetFilename := filepath.Join(baseDir, b.targetPath, strings.TrimPrefix(filename, b.archetypeFilename))\n\t\ttargetDir := filepath.Dir(targetFilename)\n\n\t\tif err := b.sourceFs.MkdirAll(targetDir, 0o777); err != nil && !os.IsExist(err) {\n\t\t\treturn errors.Wrapf(err, \"failed to create target directory for %q\", targetDir)\n\t\t}\n\n\t\tout, err := b.sourceFs.Create(targetFilename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = io.Copy(out, in)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tin.Close()\n\t\tout.Close()\n\t}\n\treturn nil\n}\n\nfunc (b *contentBuilder) buildFile() (string, error) {\n\tcontentPlaceholderAbsFilename, err := b.cf.CreateContentPlaceHolder(b.targetPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tusesSite, err := b.usesSiteVar(b.archetypeFilename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar contentInclusionFilter *glob.FilenameFilter\n\tif !usesSite {\n\t\t\/\/ We don't need to build everything.\n\t\tcontentInclusionFilter = glob.NewFilenameFilterForInclusionFunc(func(filename string) bool {\n\t\t\tfilename = strings.TrimPrefix(filename, string(os.PathSeparator))\n\t\t\treturn strings.Contains(contentPlaceholderAbsFilename, filename)\n\t\t})\n\t}\n\n\tif err := b.h.Build(hugolib.BuildCfg{NoBuildLock: true, SkipRender: true, ContentInclusionFilter: contentInclusionFilter}); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := b.applyArcheType(contentPlaceholderAbsFilename, b.archetypeFilename); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tb.h.Log.Infof(\"Content %q created\", contentPlaceholderAbsFilename)\n\n\treturn contentPlaceholderAbsFilename, nil\n}\n\nfunc (b *contentBuilder) setArcheTypeFilenameToUse(ext string) {\n\tvar pathsToCheck []string\n\n\tif b.kind != \"\" {\n\t\tpathsToCheck = append(pathsToCheck, b.kind+ext)\n\t}\n\tpathsToCheck = append(pathsToCheck, \"default\"+ext, \"default\")\n\n\tfor _, p := range pathsToCheck {\n\t\tfi, err := b.archeTypeFs.Stat(p)\n\t\tif err == nil {\n\t\t\tb.archetypeFilename = p\n\t\t\tb.isDir = fi.IsDir()\n\t\t\treturn\n\t\t}\n\t}\n\n}\n\nfunc (b *contentBuilder) applyArcheType(contentFilename, archetypeFilename string) error {\n\tp := b.h.GetContentPage(contentFilename)\n\tif p == nil {\n\t\tpanic(fmt.Sprintf(\"[BUG] no Page found for %q\", contentFilename))\n\t}\n\n\tf, err := b.sourceFs.Create(contentFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tif archetypeFilename == \"\" {\n\t\treturn b.cf.AppplyArchetypeTemplate(f, p, b.kind, DefaultArchetypeTemplateTemplate)\n\t}\n\n\treturn b.cf.AppplyArchetypeFilename(f, p, b.kind, archetypeFilename)\n\n}\n\nfunc (b *contentBuilder) mapArcheTypeDir() error {\n\tvar m archetypeMap\n\n\twalkFn := func(path string, fi hugofs.FileMetaInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif fi.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tfil := fi.(hugofs.FileMetaInfo)\n\n\t\tif files.IsContentFile(path) {\n\t\t\tm.contentFiles = append(m.contentFiles, fil)\n\t\t\tif !m.siteUsed {\n\t\t\t\tm.siteUsed, err = b.usesSiteVar(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tm.otherFiles = append(m.otherFiles, fil)\n\n\t\treturn nil\n\t}\n\n\twalkCfg := hugofs.WalkwayConfig{\n\t\tWalkFn: walkFn,\n\t\tFs:     b.archeTypeFs,\n\t\tRoot:   b.archetypeFilename,\n\t}\n\n\tw := hugofs.NewWalkway(walkCfg)\n\n\tif err := w.Walk(); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to walk archetype dir %q\", b.archetypeFilename)\n\t}\n\n\tb.dirMap = m\n\n\treturn nil\n}\n\nfunc (b *contentBuilder) openInEditorIfConfigured(filename string) error {\n\teditor := b.h.Cfg.GetString(\"newContentEditor\")\n\tif editor == \"\" {\n\t\treturn nil\n\t}\n\n\tb.h.Log.Infof(\"Editing %q with %q ...\\n\", filename, editor)\n\n\tcmd, err := hexec.SafeCommand(editor, filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\treturn cmd.Run()\n}\n\nfunc (b *contentBuilder) usesSiteVar(filename string) (bool, error) {\n\tif filename == \"\" {\n\t\treturn false, nil\n\t}\n\tbb, err := afero.ReadFile(b.archeTypeFs, filename)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to open archetype file\")\n\t}\n\n\treturn bytes.Contains(bb, []byte(\".Site\")) || bytes.Contains(bb, []byte(\"site.\")), nil\n\n}\n\ntype archetypeMap struct {\n\t\/\/ These needs to be parsed and executed as Go templates.\n\tcontentFiles []hugofs.FileMetaInfo\n\t\/\/ These are just copied to destination.\n\totherFiles []hugofs.FileMetaInfo\n\t\/\/ If the templates needs a fully built site. This can potentially be\n\t\/\/ expensive, so only do when needed.\n\tsiteUsed bool\n}\n<commit_msg>create: Always print \"Content ... created\"<commit_after>\/\/ Copyright 2019 The Hugo Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package create provides functions to create new content.\npackage create\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/gohugoio\/hugo\/hugofs\/glob\"\n\n\t\"github.com\/gohugoio\/hugo\/common\/paths\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"github.com\/gohugoio\/hugo\/common\/hexec\"\n\t\"github.com\/gohugoio\/hugo\/hugofs\/files\"\n\n\t\"github.com\/gohugoio\/hugo\/hugofs\"\n\n\t\"github.com\/gohugoio\/hugo\/helpers\"\n\t\"github.com\/gohugoio\/hugo\/hugolib\"\n\t\"github.com\/spf13\/afero\"\n)\n\nconst (\n\t\/\/ DefaultArchetypeTemplateTemplate is the template used in 'hugo new site'\n\t\/\/ and the template we use as a fall back.\n\tDefaultArchetypeTemplateTemplate = `---\ntitle: \"{{ replace .Name \"-\" \" \" | title }}\"\ndate: {{ .Date }}\ndraft: true\n---\n\n`\n)\n\n\/\/ NewContent creates a new content file in h (or a full bundle if the archetype is a directory)\n\/\/ in targetPath.\nfunc NewContent(h *hugolib.HugoSites, kind, targetPath string) error {\n\tif h.BaseFs.Content.Dirs == nil {\n\t\treturn errors.New(\"no existing content directory configured for this project\")\n\t}\n\n\tcf := hugolib.NewContentFactory(h)\n\n\tif kind == \"\" {\n\t\tkind = cf.SectionFromFilename(targetPath)\n\t}\n\n\tb := &contentBuilder{\n\t\tarcheTypeFs: h.PathSpec.BaseFs.Archetypes.Fs,\n\t\tsourceFs:    h.PathSpec.Fs.Source,\n\t\tps:          h.PathSpec,\n\t\th:           h,\n\t\tcf:          cf,\n\n\t\tkind:       kind,\n\t\ttargetPath: targetPath,\n\t}\n\n\text := paths.Ext(targetPath)\n\n\tb.setArcheTypeFilenameToUse(ext)\n\n\twithBuildLock := func() (string, error) {\n\t\tunlock, err := h.BaseFs.LockBuild()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to acquire a build lock: %s\", err)\n\t\t}\n\t\tdefer unlock()\n\n\t\tif b.isDir {\n\t\t\treturn \"\", b.buildDir()\n\t\t}\n\n\t\tif ext == \"\" {\n\t\t\treturn \"\", errors.Errorf(\"failed to resolve %q to a archetype template\", targetPath)\n\t\t}\n\n\t\tif !files.IsContentFile(b.targetPath) {\n\t\t\treturn \"\", errors.Errorf(\"target path %q is not a known content format\", b.targetPath)\n\t\t}\n\n\t\treturn b.buildFile()\n\n\t}\n\n\tfilename, err := withBuildLock()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif filename != \"\" {\n\t\treturn b.openInEditorIfConfigured(filename)\n\t}\n\n\treturn nil\n\n}\n\ntype contentBuilder struct {\n\tarcheTypeFs afero.Fs\n\tsourceFs    afero.Fs\n\n\tps *helpers.PathSpec\n\th  *hugolib.HugoSites\n\tcf hugolib.ContentFactory\n\n\t\/\/ Builder state\n\tarchetypeFilename string\n\ttargetPath        string\n\tkind              string\n\tisDir             bool\n\tdirMap            archetypeMap\n}\n\nfunc (b *contentBuilder) buildDir() error {\n\t\/\/ Split the dir into content files and the rest.\n\tif err := b.mapArcheTypeDir(); err != nil {\n\t\treturn err\n\t}\n\n\tvar contentTargetFilenames []string\n\tvar baseDir string\n\n\tfor _, fi := range b.dirMap.contentFiles {\n\t\ttargetFilename := filepath.Join(b.targetPath, strings.TrimPrefix(fi.Meta().Path, b.archetypeFilename))\n\t\tabs, err := b.cf.CreateContentPlaceHolder(targetFilename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif baseDir == \"\" {\n\t\t\tbaseDir = strings.TrimSuffix(abs, targetFilename)\n\t\t}\n\n\t\tcontentTargetFilenames = append(contentTargetFilenames, abs)\n\t}\n\n\tvar contentInclusionFilter *glob.FilenameFilter\n\tif !b.dirMap.siteUsed {\n\t\t\/\/ We don't need to build everything.\n\t\tcontentInclusionFilter = glob.NewFilenameFilterForInclusionFunc(func(filename string) bool {\n\t\t\tfilename = strings.TrimPrefix(filename, string(os.PathSeparator))\n\t\t\tfor _, cn := range contentTargetFilenames {\n\t\t\t\tif strings.Contains(cn, filename) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\n\t}\n\n\tif err := b.h.Build(hugolib.BuildCfg{NoBuildLock: true, SkipRender: true, ContentInclusionFilter: contentInclusionFilter}); err != nil {\n\t\treturn err\n\t}\n\n\tfor i, filename := range contentTargetFilenames {\n\t\tif err := b.applyArcheType(filename, b.dirMap.contentFiles[i].Meta().Path); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Copy the rest as is.\n\tfor _, f := range b.dirMap.otherFiles {\n\t\tmeta := f.Meta()\n\t\tfilename := meta.Path\n\n\t\tin, err := meta.Open()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to open non-content file\")\n\t\t}\n\n\t\ttargetFilename := filepath.Join(baseDir, b.targetPath, strings.TrimPrefix(filename, b.archetypeFilename))\n\t\ttargetDir := filepath.Dir(targetFilename)\n\n\t\tif err := b.sourceFs.MkdirAll(targetDir, 0o777); err != nil && !os.IsExist(err) {\n\t\t\treturn errors.Wrapf(err, \"failed to create target directory for %q\", targetDir)\n\t\t}\n\n\t\tout, err := b.sourceFs.Create(targetFilename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = io.Copy(out, in)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tin.Close()\n\t\tout.Close()\n\t}\n\treturn nil\n}\n\nfunc (b *contentBuilder) buildFile() (string, error) {\n\tcontentPlaceholderAbsFilename, err := b.cf.CreateContentPlaceHolder(b.targetPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tusesSite, err := b.usesSiteVar(b.archetypeFilename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar contentInclusionFilter *glob.FilenameFilter\n\tif !usesSite {\n\t\t\/\/ We don't need to build everything.\n\t\tcontentInclusionFilter = glob.NewFilenameFilterForInclusionFunc(func(filename string) bool {\n\t\t\tfilename = strings.TrimPrefix(filename, string(os.PathSeparator))\n\t\t\treturn strings.Contains(contentPlaceholderAbsFilename, filename)\n\t\t})\n\t}\n\n\tif err := b.h.Build(hugolib.BuildCfg{NoBuildLock: true, SkipRender: true, ContentInclusionFilter: contentInclusionFilter}); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := b.applyArcheType(contentPlaceholderAbsFilename, b.archetypeFilename); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tb.h.Log.Printf(\"Content %q created\", contentPlaceholderAbsFilename)\n\n\treturn contentPlaceholderAbsFilename, nil\n}\n\nfunc (b *contentBuilder) setArcheTypeFilenameToUse(ext string) {\n\tvar pathsToCheck []string\n\n\tif b.kind != \"\" {\n\t\tpathsToCheck = append(pathsToCheck, b.kind+ext)\n\t}\n\tpathsToCheck = append(pathsToCheck, \"default\"+ext, \"default\")\n\n\tfor _, p := range pathsToCheck {\n\t\tfi, err := b.archeTypeFs.Stat(p)\n\t\tif err == nil {\n\t\t\tb.archetypeFilename = p\n\t\t\tb.isDir = fi.IsDir()\n\t\t\treturn\n\t\t}\n\t}\n\n}\n\nfunc (b *contentBuilder) applyArcheType(contentFilename, archetypeFilename string) error {\n\tp := b.h.GetContentPage(contentFilename)\n\tif p == nil {\n\t\tpanic(fmt.Sprintf(\"[BUG] no Page found for %q\", contentFilename))\n\t}\n\n\tf, err := b.sourceFs.Create(contentFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tif archetypeFilename == \"\" {\n\t\treturn b.cf.AppplyArchetypeTemplate(f, p, b.kind, DefaultArchetypeTemplateTemplate)\n\t}\n\n\treturn b.cf.AppplyArchetypeFilename(f, p, b.kind, archetypeFilename)\n\n}\n\nfunc (b *contentBuilder) mapArcheTypeDir() error {\n\tvar m archetypeMap\n\n\twalkFn := func(path string, fi hugofs.FileMetaInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif fi.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tfil := fi.(hugofs.FileMetaInfo)\n\n\t\tif files.IsContentFile(path) {\n\t\t\tm.contentFiles = append(m.contentFiles, fil)\n\t\t\tif !m.siteUsed {\n\t\t\t\tm.siteUsed, err = b.usesSiteVar(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tm.otherFiles = append(m.otherFiles, fil)\n\n\t\treturn nil\n\t}\n\n\twalkCfg := hugofs.WalkwayConfig{\n\t\tWalkFn: walkFn,\n\t\tFs:     b.archeTypeFs,\n\t\tRoot:   b.archetypeFilename,\n\t}\n\n\tw := hugofs.NewWalkway(walkCfg)\n\n\tif err := w.Walk(); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to walk archetype dir %q\", b.archetypeFilename)\n\t}\n\n\tb.dirMap = m\n\n\treturn nil\n}\n\nfunc (b *contentBuilder) openInEditorIfConfigured(filename string) error {\n\teditor := b.h.Cfg.GetString(\"newContentEditor\")\n\tif editor == \"\" {\n\t\treturn nil\n\t}\n\n\tb.h.Log.Printf(\"Editing %q with %q ...\\n\", filename, editor)\n\n\tcmd, err := hexec.SafeCommand(editor, filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\treturn cmd.Run()\n}\n\nfunc (b *contentBuilder) usesSiteVar(filename string) (bool, error) {\n\tif filename == \"\" {\n\t\treturn false, nil\n\t}\n\tbb, err := afero.ReadFile(b.archeTypeFs, filename)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"failed to open archetype file\")\n\t}\n\n\treturn bytes.Contains(bb, []byte(\".Site\")) || bytes.Contains(bb, []byte(\"site.\")), nil\n\n}\n\ntype archetypeMap struct {\n\t\/\/ These needs to be parsed and executed as Go templates.\n\tcontentFiles []hugofs.FileMetaInfo\n\t\/\/ These are just copied to destination.\n\totherFiles []hugofs.FileMetaInfo\n\t\/\/ If the templates needs a fully built site. This can potentially be\n\t\/\/ expensive, so only do when needed.\n\tsiteUsed bool\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2014 Steve Francia <spf@spf13.com>.\n\/\/\n\/\/ Licensed under the Simple Public License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/opensource.org\/licenses\/Simple-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage create\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cast\"\n\t\"github.com\/spf13\/hugo\/helpers\"\n\t\"github.com\/spf13\/hugo\/hugofs\"\n\t\"github.com\/spf13\/hugo\/hugolib\"\n\t\"github.com\/spf13\/hugo\/parser\"\n\tjww \"github.com\/spf13\/jwalterweatherman\"\n\t\"github.com\/spf13\/viper\"\n)\n\nfunc NewContent(kind, name string) (err error) {\n\tjww.INFO.Println(\"attempting to create \", name, \"of\", kind)\n\n\tlocation := FindArchetype(kind)\n\n\tvar by []byte\n\n\tif location != \"\" {\n\t\tby, err = ioutil.ReadFile(location)\n\t\tif err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t}\n\t}\n\tif location == \"\" || err != nil {\n\t\tby = []byte(\"+++\\n title = \\\"title\\\"\\n draft = true \\n+++\\n\")\n\t}\n\n\tpsr, err := parser.ReadFrom(bytes.NewReader(by))\n\tif err != nil {\n\t\treturn err\n\t}\n\tmetadata, err := psr.Metadata()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnewmetadata, err := cast.ToStringMapE(metadata)\n\tif err != nil {\n\t\tjww.ERROR.Println(\"Error processing archetype file:\", location)\n\t\treturn err\n\t}\n\n\tfor k, _ := range newmetadata {\n\t\tswitch strings.ToLower(k) {\n\t\tcase \"date\":\n\t\t\tnewmetadata[k] = time.Now()\n\t\tcase \"title\":\n\t\t\tnewmetadata[k] = helpers.MakeTitle(helpers.Filename(name))\n\t\t}\n\t}\n\n\tcaseimatch := func(m map[string]interface{}, key string) bool {\n\t\tfor k, _ := range m {\n\t\t\tif strings.ToLower(k) == strings.ToLower(key) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tif !caseimatch(newmetadata, \"date\") {\n\t\tnewmetadata[\"date\"] = time.Now()\n\t}\n\n\tif !caseimatch(newmetadata, \"title\") {\n\t\tnewmetadata[\"title\"] = helpers.MakeTitle(helpers.Filename(name))\n\t}\n\n\tpage, err := hugolib.NewPage(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif x := viper.GetString(\"MetaDataFormat\"); x == \"json\" || x == \"yaml\" || x == \"toml\" {\n\t\tnewmetadata[\"date\"] = time.Now().Format(time.RFC3339)\n\t}\n\n\t\/\/page.Dir = viper.GetString(\"sourceDir\")\n\tpage.SetSourceMetaData(newmetadata, parser.FormatToLeadRune(viper.GetString(\"MetaDataFormat\")))\n\tpage.SetSourceContent(psr.Content())\n\tif err = page.SafeSaveSourceAs(filepath.Join(viper.GetString(\"contentDir\"), name)); err != nil {\n\t\treturn\n\t}\n\tjww.FEEDBACK.Println(helpers.AbsPathify(filepath.Join(viper.GetString(\"contentDir\"), name)), \"created\")\n\n\teditor := viper.GetString(\"NewContentEditor\")\n\n\tif editor != \"\" {\n\t\tjww.FEEDBACK.Printf(\"Editing %s in %s.\\n\", name, editor)\n\n\t\tcmd := exec.Command(editor, path.Join(viper.GetString(\"contentDir\"), name))\n\t\tcmd.Stdin = os.Stdin\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\n\t\tif err = cmd.Run(); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc FindArchetype(kind string) (outpath string) {\n\tsearch := []string{helpers.AbsPathify(viper.GetString(\"archetypeDir\"))}\n\n\tif viper.GetString(\"theme\") != \"\" {\n\t\tthemeDir := filepath.Join(helpers.AbsPathify(\"themes\/\"+viper.GetString(\"theme\")), \"\/archetypes\/\")\n\t\tif _, err := os.Stat(themeDir); os.IsNotExist(err) {\n\t\t\tjww.ERROR.Println(\"Unable to find archetypes directory for theme :\", viper.GetString(\"theme\"), \"in\", themeDir)\n\t\t} else {\n\t\t\tsearch = append(search, themeDir)\n\t\t}\n\t}\n\n\tfor _, x := range search {\n\t\t\/\/ If the new content isn't in a subdirectory, kind == \"\".\n\t\t\/\/ Therefore it should be excluded otherwise `is a directory`\n\t\t\/\/ error will occur. github.com\/spf13\/hugo\/issues\/411\n\t\tvar pathsToCheck []string\n\n\t\tif kind == \"\" {\n\t\t\tpathsToCheck = []string{\"default.md\", \"default\"}\n\t\t} else {\n\t\t\tpathsToCheck = []string{kind + \".md\", kind, \"default.md\", \"default\"}\n\t\t}\n\t\tfor _, p := range pathsToCheck {\n\t\t\tcurpath := filepath.Join(x, p)\n\t\t\tjww.DEBUG.Println(\"checking\", curpath, \"for archetypes\")\n\t\t\tif exists, _ := helpers.Exists(curpath, hugofs.SourceFs); exists {\n\t\t\t\tjww.INFO.Println(\"curpath: \" + curpath)\n\t\t\t\treturn curpath\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\"\n}\n<commit_msg>Handle empty front matter in archetype.<commit_after>\/\/ Copyright © 2014 Steve Francia <spf@spf13.com>.\n\/\/\n\/\/ Licensed under the Simple Public License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/opensource.org\/licenses\/Simple-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage create\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cast\"\n\t\"github.com\/spf13\/hugo\/helpers\"\n\t\"github.com\/spf13\/hugo\/hugofs\"\n\t\"github.com\/spf13\/hugo\/hugolib\"\n\t\"github.com\/spf13\/hugo\/parser\"\n\tjww \"github.com\/spf13\/jwalterweatherman\"\n\t\"github.com\/spf13\/viper\"\n)\n\nfunc NewContent(kind, name string) (err error) {\n\tjww.INFO.Println(\"attempting to create \", name, \"of\", kind)\n\n\tlocation := FindArchetype(kind)\n\n\tvar by []byte\n\n\tif location != \"\" {\n\t\tby, err = ioutil.ReadFile(location)\n\t\tif err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t}\n\t}\n\tif location == \"\" || err != nil {\n\t\tby = []byte(\"+++\\n title = \\\"title\\\"\\n draft = true \\n+++\\n\")\n\t}\n\n\tpsr, err := parser.ReadFrom(bytes.NewReader(by))\n\tif err != nil {\n\t\treturn err\n\t}\n\tmetadata, err := psr.Metadata()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnewmetadata, err := cast.ToStringMapE(metadata)\n\tif err != nil {\n\t\tjww.ERROR.Println(\"Error processing archetype file:\", location)\n\t\treturn err\n\t}\n\n\tfor k, _ := range newmetadata {\n\t\tswitch strings.ToLower(k) {\n\t\tcase \"date\":\n\t\t\tnewmetadata[k] = time.Now()\n\t\tcase \"title\":\n\t\t\tnewmetadata[k] = helpers.MakeTitle(helpers.Filename(name))\n\t\t}\n\t}\n\n\tcaseimatch := func(m map[string]interface{}, key string) bool {\n\t\tfor k, _ := range m {\n\t\t\tif strings.ToLower(k) == strings.ToLower(key) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tif newmetadata == nil {\n\t\tnewmetadata = make(map[string]interface{})\n\t}\n\n\tif !caseimatch(newmetadata, \"date\") {\n\t\tnewmetadata[\"date\"] = time.Now()\n\t}\n\n\tif !caseimatch(newmetadata, \"title\") {\n\t\tnewmetadata[\"title\"] = helpers.MakeTitle(helpers.Filename(name))\n\t}\n\n\tpage, err := hugolib.NewPage(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif x := viper.GetString(\"MetaDataFormat\"); x == \"json\" || x == \"yaml\" || x == \"toml\" {\n\t\tnewmetadata[\"date\"] = time.Now().Format(time.RFC3339)\n\t}\n\n\t\/\/page.Dir = viper.GetString(\"sourceDir\")\n\tpage.SetSourceMetaData(newmetadata, parser.FormatToLeadRune(viper.GetString(\"MetaDataFormat\")))\n\tpage.SetSourceContent(psr.Content())\n\tif err = page.SafeSaveSourceAs(filepath.Join(viper.GetString(\"contentDir\"), name)); err != nil {\n\t\treturn\n\t}\n\tjww.FEEDBACK.Println(helpers.AbsPathify(filepath.Join(viper.GetString(\"contentDir\"), name)), \"created\")\n\n\teditor := viper.GetString(\"NewContentEditor\")\n\n\tif editor != \"\" {\n\t\tjww.FEEDBACK.Printf(\"Editing %s in %s.\\n\", name, editor)\n\n\t\tcmd := exec.Command(editor, path.Join(viper.GetString(\"contentDir\"), name))\n\t\tcmd.Stdin = os.Stdin\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\n\t\tif err = cmd.Run(); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc FindArchetype(kind string) (outpath string) {\n\tsearch := []string{helpers.AbsPathify(viper.GetString(\"archetypeDir\"))}\n\n\tif viper.GetString(\"theme\") != \"\" {\n\t\tthemeDir := filepath.Join(helpers.AbsPathify(\"themes\/\"+viper.GetString(\"theme\")), \"\/archetypes\/\")\n\t\tif _, err := os.Stat(themeDir); os.IsNotExist(err) {\n\t\t\tjww.ERROR.Println(\"Unable to find archetypes directory for theme :\", viper.GetString(\"theme\"), \"in\", themeDir)\n\t\t} else {\n\t\t\tsearch = append(search, themeDir)\n\t\t}\n\t}\n\n\tfor _, x := range search {\n\t\t\/\/ If the new content isn't in a subdirectory, kind == \"\".\n\t\t\/\/ Therefore it should be excluded otherwise `is a directory`\n\t\t\/\/ error will occur. github.com\/spf13\/hugo\/issues\/411\n\t\tvar pathsToCheck []string\n\n\t\tif kind == \"\" {\n\t\t\tpathsToCheck = []string{\"default.md\", \"default\"}\n\t\t} else {\n\t\t\tpathsToCheck = []string{kind + \".md\", kind, \"default.md\", \"default\"}\n\t\t}\n\t\tfor _, p := range pathsToCheck {\n\t\t\tcurpath := filepath.Join(x, p)\n\t\t\tjww.DEBUG.Println(\"checking\", curpath, \"for archetypes\")\n\t\t\tif exists, _ := helpers.Exists(curpath, hugofs.SourceFs); exists {\n\t\t\t\tjww.INFO.Println(\"curpath: \" + curpath)\n\t\t\t\treturn curpath\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package crypto\n\nimport (\n\t\"crypto\/ecdsa\"\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"sync\"\n)\n\nconst (\n\tpemKeyPath = \"priv_key.pem\"\n)\n\ntype PemKey struct {\n\tl    sync.Mutex\n\tpath string\n}\n\nfunc NewPemKey(base string) *PemKey {\n\tpath := filepath.Join(base, pemKeyPath)\n\tpemKey := &PemKey{\n\t\tpath: path,\n\t}\n\treturn pemKey\n}\n\nfunc (k *PemKey) ReadKey() (*ecdsa.PrivateKey, error) {\n\tk.l.Lock()\n\tdefer k.l.Unlock()\n\n\t\/\/ Read the file\n\tbuf, err := ioutil.ReadFile(k.path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Check for no key\n\tif len(buf) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t\/\/ Decode the PEM key\n\tblock, _ := pem.Decode(buf)\n\tif block == nil {\n\t\treturn nil, fmt.Errorf(\"Error decoding PEM block from data\")\n\t}\n\treturn x509.ParseECPrivateKey(block.Bytes)\n}\n\nfunc (k *PemKey) WriteKey(key *ecdsa.PrivateKey) error {\n\tk.l.Lock()\n\tdefer k.l.Unlock()\n\n\tb, err := x509.MarshalECPrivateKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpemBlock := &pem.Block{Type: \"EC PRIVATE KEY\", Bytes: b}\n\tdata := pem.EncodeToMemory(pemBlock)\n\treturn ioutil.WriteFile(k.path, data, 0755)\n}\n\ntype PemDump struct {\n\tPublicKey  string\n\tPrivateKey string\n}\n\nfunc GeneratePemKey() (*PemDump, error) {\n\tkey, err := GenerateECDSAKey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpub := fmt.Sprintf(\"0x%X\", FromECDSAPub(&key.PublicKey))\n\n\tb, err := x509.MarshalECPrivateKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpemBlock := &pem.Block{Type: \"EC PRIVATE KEY\", Bytes: b}\n\tdata := pem.EncodeToMemory(pemBlock)\n\n\tpemDump := PemDump{\n\t\tPublicKey:  pub,\n\t\tPrivateKey: string(data),\n\t}\n\n\treturn &pemDump, err\n}\n<commit_msg>Added exported method to read the private key from buffer<commit_after>package crypto\n\nimport (\n\t\"crypto\/ecdsa\"\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"sync\"\n)\n\nconst (\n\tpemKeyPath = \"priv_key.pem\"\n)\n\ntype PemKey struct {\n\tl    sync.Mutex\n\tpath string\n}\n\nfunc NewPemKey(base string) *PemKey {\n\tpath := filepath.Join(base, pemKeyPath)\n\tpemKey := &PemKey{\n\t\tpath: path,\n\t}\n\treturn pemKey\n}\n\nfunc (k *PemKey) ReadKey() (*ecdsa.PrivateKey, error) {\n\tk.l.Lock()\n\tdefer k.l.Unlock()\n\n\t\/\/ Read the file\n\tbuf, err := ioutil.ReadFile(k.path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn k.ReadKeyFromBuf(buf)\n}\n\nfunc (k *PemKey) ReadKeyFromBuf(buf []byte) (*ecdsa.PrivateKey, error) {\n\tif len(buf) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tblock, _ := pem.Decode(buf)\n\tif block == nil {\n\t\treturn nil, fmt.Errorf(\"Error decoding PEM block from data\")\n\t}\n\treturn x509.ParseECPrivateKey(block.Bytes)\n}\n\nfunc (k *PemKey) WriteKey(key *ecdsa.PrivateKey) error {\n\tk.l.Lock()\n\tdefer k.l.Unlock()\n\n\tb, err := x509.MarshalECPrivateKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpemBlock := &pem.Block{Type: \"EC PRIVATE KEY\", Bytes: b}\n\tdata := pem.EncodeToMemory(pemBlock)\n\treturn ioutil.WriteFile(k.path, data, 0755)\n}\n\ntype PemDump struct {\n\tPublicKey  string\n\tPrivateKey string\n}\n\nfunc GeneratePemKey() (*PemDump, error) {\n\tkey, err := GenerateECDSAKey()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpub := fmt.Sprintf(\"0x%X\", FromECDSAPub(&key.PublicKey))\n\n\tb, err := x509.MarshalECPrivateKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpemBlock := &pem.Block{Type: \"EC PRIVATE KEY\", Bytes: b}\n\tdata := pem.EncodeToMemory(pemBlock)\n\n\tpemDump := PemDump{\n\t\tPublicKey:  pub,\n\t\tPrivateKey: string(data),\n\t}\n\n\treturn &pemDump, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package sysinfo\n\nimport (\n\t\"bufio\"\n\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/adrg\/unit\"\n)\n\ntype Memory struct {\n\tTotal      uint64\n\tFree       uint64\n\tUsed       uint64\n\tCached     uint64\n\tActive     uint64\n\tInactive   uint64\n\tSwapTotal  uint64\n\tSwapFree   uint64\n\tSwapUsed   uint64\n\tSwapCached uint64\n\tBuffers    uint64\n\n\tUnit unit.Memory\n}\n\nfunc (m *Memory) PercentUsed() float64 {\n\treturn float64(m.Used) \/ float64(m.Total) * 100.0\n}\n\nfunc (m *Memory) PercentFree() float64 {\n\treturn float64(m.Free) \/ float64(m.Total) * 100.0\n}\n\nfunc (m *Memory) PercentSwapUsed() float64 {\n\treturn float64(m.SwapUsed) \/ float64(m.SwapTotal) * 100.0\n}\n\nfunc (m *Memory) PercentSwapFree() float64 {\n\treturn float64(m.SwapFree) \/ float64(m.SwapTotal) * 100.0\n}\n\nfunc MemoryInfo() (*Memory, error) {\n\tmem := &Memory{Unit: unit.Kibibyte}\n\n\tfile, err := os.Open(\"\/proc\/meminfo\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tfields := strings.Fields(scanner.Text())\n\t\tif len(fields) < 2 {\n\t\t\treturn nil, ErrInvalidFileFormat\n\t\t}\n\n\t\tvalue, err := strconv.ParseUint(fields[1], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, ErrInvalidFileFormat\n\t\t}\n\n\t\tkey := strings.ToLower(strings.TrimSuffix(fields[0], \":\"))\n\t\tswitch key {\n\t\tcase \"memtotal\":\n\t\t\tmem.Total = value\n\t\tcase \"memfree\":\n\t\t\tmem.Free = value\n\t\tcase \"cached\":\n\t\t\tmem.Cached = value\n\t\tcase \"swaptotal\":\n\t\t\tmem.SwapTotal = value\n\t\tcase \"swapfree\":\n\t\t\tmem.SwapFree = value\n\t\tcase \"swapcached\":\n\t\t\tmem.SwapCached = value\n\t\tcase \"buffers\":\n\t\t\tmem.Buffers = value\n\t\tcase \"active\":\n\t\t\tmem.Active = value\n\t\tcase \"inactive\":\n\t\t\tmem.Inactive = value\n\t\t}\n\t}\n\n\tif err = scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmem.Free = mem.Free + mem.Cached + mem.Buffers\n\tmem.Used = mem.Total - mem.Free\n\tmem.SwapUsed = mem.SwapTotal - mem.SwapFree\n\n\treturn mem, nil\n}\n<commit_msg>Remove unit of measurement from Memory structure<commit_after>package sysinfo\n\nimport (\n\t\"bufio\"\n\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype Memory struct {\n\tTotal      uint64\n\tFree       uint64\n\tUsed       uint64\n\tCached     uint64\n\tActive     uint64\n\tInactive   uint64\n\tSwapTotal  uint64\n\tSwapFree   uint64\n\tSwapUsed   uint64\n\tSwapCached uint64\n\tBuffers    uint64\n}\n\nfunc (m *Memory) PercentUsed() float64 {\n\treturn float64(m.Used) \/ float64(m.Total) * 100.0\n}\n\nfunc (m *Memory) PercentFree() float64 {\n\treturn float64(m.Free) \/ float64(m.Total) * 100.0\n}\n\nfunc (m *Memory) PercentSwapUsed() float64 {\n\treturn float64(m.SwapUsed) \/ float64(m.SwapTotal) * 100.0\n}\n\nfunc (m *Memory) PercentSwapFree() float64 {\n\treturn float64(m.SwapFree) \/ float64(m.SwapTotal) * 100.0\n}\n\nfunc MemoryInfo() (*Memory, error) {\n\tmem := &Memory{}\n\n\tfile, err := os.Open(\"\/proc\/meminfo\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tfields := strings.Fields(scanner.Text())\n\t\tif len(fields) < 2 {\n\t\t\treturn nil, ErrInvalidFileFormat\n\t\t}\n\n\t\tvalue, err := strconv.ParseUint(fields[1], 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, ErrInvalidFileFormat\n\t\t}\n\n\t\tkey := strings.ToLower(strings.TrimSuffix(fields[0], \":\"))\n\t\tswitch key {\n\t\tcase \"memtotal\":\n\t\t\tmem.Total = value\n\t\tcase \"memfree\":\n\t\t\tmem.Free = value\n\t\tcase \"cached\":\n\t\t\tmem.Cached = value\n\t\tcase \"swaptotal\":\n\t\t\tmem.SwapTotal = value\n\t\tcase \"swapfree\":\n\t\t\tmem.SwapFree = value\n\t\tcase \"swapcached\":\n\t\t\tmem.SwapCached = value\n\t\tcase \"buffers\":\n\t\t\tmem.Buffers = value\n\t\tcase \"active\":\n\t\t\tmem.Active = value\n\t\tcase \"inactive\":\n\t\t\tmem.Inactive = value\n\t\t}\n\t}\n\n\tif err = scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmem.Free = mem.Free + mem.Cached + mem.Buffers\n\tmem.Used = mem.Total - mem.Free\n\tmem.SwapUsed = mem.SwapTotal - mem.SwapFree\n\n\treturn mem, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2021 Uber Technologies, Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\npackage yarpcerrors\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\t\/\/ CodeOK means no error; returned on success\n\tCodeOK Code = 0\n\n\t\/\/ CodeCancelled means the operation was cancelled, typically by the caller.\n\tCodeCancelled Code = 1\n\n\t\/\/ CodeUnknown means an unknown error. Errors raised by APIs\n\t\/\/ that do not return enough error information\n\t\/\/ may be converted to this error.\n\tCodeUnknown Code = 2\n\n\t\/\/ CodeInvalidArgument means the client specified an invalid argument.\n\t\/\/ Note that this differs from `FailedPrecondition`. `InvalidArgument`\n\t\/\/ indicates arguments that are problematic regardless of the state of\n\t\/\/ the system (e.g., a malformed file name).\n\tCodeInvalidArgument Code = 3\n\n\t\/\/ CodeDeadlineExceeded means the deadline expired before the operation could\n\t\/\/ complete. For operations that change the state of the system, this error\n\t\/\/ may be returned even if the operation has completed successfully. For example,\n\t\/\/ a successful response from a server could have been delayed long\n\t\/\/ enough for the deadline to expire.\n\tCodeDeadlineExceeded Code = 4\n\n\t\/\/ CodeNotFound means some requested entity (e.g., file or directory) was not found.\n\t\/\/ For privacy reasons, this code *may* be returned when the client\n\t\/\/ does not have the access rights to the entity, though such usage is\n\t\/\/ discouraged.\n\tCodeNotFound Code = 5\n\n\t\/\/ CodeAlreadyExists means the entity that a client attempted to create\n\t\/\/ (e.g., file or directory) already exists.\n\tCodeAlreadyExists Code = 6\n\n\t\/\/ CodePermissionDenied means the caller does not have permission to execute\n\t\/\/ the specified operation. `PermissionDenied` must not be used for rejections\n\t\/\/ caused by exhausting some resource (use `ResourceExhausted`\n\t\/\/ instead for those errors). `PermissionDenied` must not be\n\t\/\/ used if the caller can not be identified (use `Unauthenticated`\n\t\/\/ instead for those errors).\n\tCodePermissionDenied Code = 7\n\n\t\/\/ CodeResourceExhausted means some resource has been exhausted, perhaps a per-user\n\t\/\/ quota, or perhaps the entire file system is out of space.\n\tCodeResourceExhausted Code = 8\n\n\t\/\/ CodeFailedPrecondition means the operation was rejected because the system is not\n\t\/\/ in a state required for the operation's execution. For example, the directory\n\t\/\/ to be deleted is non-empty, an rmdir operation is applied to\n\t\/\/ a non-directory, etc.\n\t\/\/\n\t\/\/ Service implementors can use the following guidelines to decide\n\t\/\/ between `FailedPrecondition`, `Aborted`, and `Unavailable`:\n\t\/\/  (a) Use `Unavailable` if the client can retry just the failing call.\n\t\/\/  (b) Use `Aborted` if the client should retry at a higher level\n\t\/\/      (e.g., restarting a read-modify-write sequence).\n\t\/\/  (c) Use `FailedPrecondition` if the client should not retry until\n\t\/\/      the system state has been explicitly fixed. E.g., if an \"rmdir\"\n\t\/\/      fails because the directory is non-empty, `FailedPrecondition`\n\t\/\/      should be returned since the client should not retry unless\n\t\/\/      the files are deleted from the directory.\n\tCodeFailedPrecondition Code = 9\n\n\t\/\/ CodeAborted means the operation was aborted, typically due to a concurrency issue\n\t\/\/ such as a sequencer check failure or transaction abort.\n\t\/\/\n\t\/\/ See the guidelines above for deciding between `FailedPrecondition`,\n\t\/\/ `Aborted`, and `Unavailable`.\n\tCodeAborted Code = 10\n\n\t\/\/ CodeOutOfRange means the operation was attempted past the valid range.\n\t\/\/ E.g., seeking or reading past end-of-file.\n\t\/\/\n\t\/\/ Unlike `InvalidArgument`, this error indicates a problem that may\n\t\/\/ be fixed if the system state changes. For example, a 32-bit file\n\t\/\/ system will generate `InvalidArgument` if asked to read at an\n\t\/\/ offset that is not in the range [0,2^32-1], but it will generate\n\t\/\/ `OutOfRange` if asked to read from an offset past the current\n\t\/\/ file size.\n\t\/\/\n\t\/\/ There is a fair bit of overlap between `FailedPrecondition` and\n\t\/\/ `OutOfRange`.  We recommend using `OutOfRange` (the more specific\n\t\/\/ error) when it applies so that callers who are iterating through\n\t\/\/ a space can easily look for an `OutOfRange` error to detect when\n\t\/\/ they are done.\n\tCodeOutOfRange Code = 11\n\n\t\/\/ CodeUnimplemented means the operation is not implemented or is not\n\t\/\/ supported\/enabled in this service.\n\tCodeUnimplemented Code = 12\n\n\t\/\/ CodeInternal means an internal error. This means that some invariants expected\n\t\/\/ by the underlying system have been broken. This error code is reserved\n\t\/\/ for serious errors.\n\tCodeInternal Code = 13\n\n\t\/\/ CodeUnavailable means the service is currently unavailable. This is most likely a\n\t\/\/ transient condition, which can be corrected by retrying with a backoff.\n\t\/\/\n\t\/\/ See the guidelines above for deciding between `FailedPrecondition`,\n\t\/\/ `Aborted`, and `Unavailable`.\n\tCodeUnavailable Code = 14\n\n\t\/\/ CodeDataLoss means unrecoverable data loss or corruption.\n\tCodeDataLoss Code = 15\n\n\t\/\/ CodeUnauthenticated means the request does not have valid authentication\n\t\/\/ credentials for the operation.\n\tCodeUnauthenticated Code = 16\n)\n\nvar (\n\t_codeToString = map[Code]string{\n\t\tCodeOK:                 \"ok\",\n\t\tCodeCancelled:          \"cancelled\",\n\t\tCodeUnknown:            \"unknown\",\n\t\tCodeInvalidArgument:    \"invalid-argument\",\n\t\tCodeDeadlineExceeded:   \"deadline-exceeded\",\n\t\tCodeNotFound:           \"not-found\",\n\t\tCodeAlreadyExists:      \"already-exists\",\n\t\tCodePermissionDenied:   \"permission-denied\",\n\t\tCodeResourceExhausted:  \"resource-exhausted\",\n\t\tCodeFailedPrecondition: \"failed-precondition\",\n\t\tCodeAborted:            \"aborted\",\n\t\tCodeOutOfRange:         \"out-of-range\",\n\t\tCodeUnimplemented:      \"unimplemented\",\n\t\tCodeInternal:           \"internal\",\n\t\tCodeUnavailable:        \"unavailable\",\n\t\tCodeDataLoss:           \"data-loss\",\n\t\tCodeUnauthenticated:    \"unauthenticated\",\n\t}\n\t_stringToCode = map[string]Code{\n\t\t\"ok\":                  CodeOK,\n\t\t\"cancelled\":           CodeCancelled,\n\t\t\"unknown\":             CodeUnknown,\n\t\t\"invalid-argument\":    CodeInvalidArgument,\n\t\t\"deadline-exceeded\":   CodeDeadlineExceeded,\n\t\t\"not-found\":           CodeNotFound,\n\t\t\"already-exists\":      CodeAlreadyExists,\n\t\t\"permission-denied\":   CodePermissionDenied,\n\t\t\"resource-exhausted\":  CodeResourceExhausted,\n\t\t\"failed-precondition\": CodeFailedPrecondition,\n\t\t\"aborted\":             CodeAborted,\n\t\t\"out-of-range\":        CodeOutOfRange,\n\t\t\"unimplemented\":       CodeUnimplemented,\n\t\t\"internal\":            CodeInternal,\n\t\t\"unavailable\":         CodeUnavailable,\n\t\t\"data-loss\":           CodeDataLoss,\n\t\t\"unauthenticated\":     CodeUnauthenticated,\n\t}\n)\n\n\/\/ Code represents the type of error for an RPC call.\n\/\/\n\/\/ Sometimes multiple error codes may apply. Services should return\n\/\/ the most specific error code that applies. For example, prefer\n\/\/ `OutOfRange` over `FailedPrecondition` if both codes apply.\n\/\/ Similarly prefer `NotFound` or `AlreadyExists` over `FailedPrecondition`.\n\/\/\n\/\/ These codes are meant to match gRPC status codes.\n\/\/ https:\/\/godoc.org\/google.golang.org\/grpc\/codes#Code\ntype Code int\n\n\/\/ String returns the the string representation of the Code.\nfunc (c Code) String() string {\n\ts, ok := _codeToString[c]\n\tif ok {\n\t\treturn s\n\t}\n\treturn strconv.Itoa(int(c))\n}\n\n\/\/ MarshalText implements encoding.TextMarshaler.\nfunc (c Code) MarshalText() ([]byte, error) {\n\ts, ok := _codeToString[c]\n\tif ok {\n\t\treturn []byte(s), nil\n\t}\n\treturn nil, fmt.Errorf(\"unknown code: %d\", int(c))\n}\n\n\/\/ UnmarshalText implements encoding.TextUnmarshaler.\nfunc (c *Code) UnmarshalText(text []byte) error {\n\ti, ok := _stringToCode[strings.ToLower(string(text))]\n\tif !ok {\n\t\treturn fmt.Errorf(\"unknown code string: %s\", string(text))\n\t}\n\t*c = i\n\treturn nil\n}\n\n\/\/ MarshalJSON implements json.Marshaler.\nfunc (c Code) MarshalJSON() ([]byte, error) {\n\ts, ok := _codeToString[c]\n\tif ok {\n\t\treturn []byte(`\"` + s + `\"`), nil\n\t}\n\treturn nil, fmt.Errorf(\"unknown code: %d\", int(c))\n}\n\n\/\/ UnmarshalJSON implements json.Unmarshaler.\nfunc (c *Code) UnmarshalJSON(text []byte) error {\n\ts := string(text)\n\tif len(s) < 3 || s[0] != '\"' || s[len(s)-1] != '\"' {\n\t\treturn fmt.Errorf(\"invalid code string: %s\", s)\n\t}\n\ti, ok := _stringToCode[strings.ToLower(s[1:len(s)-1])]\n\tif !ok {\n\t\treturn fmt.Errorf(\"unknown code string: %s\", s)\n\t}\n\t*c = i\n\treturn nil\n}\n<commit_msg>Doc: added documentation to error to mention if they are considered as client or server error (#2050)<commit_after>\/\/ Copyright (c) 2021 Uber Technologies, Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\npackage yarpcerrors\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\t\/\/ CodeOK means no error; returned on success\n\tCodeOK Code = 0\n\n\t\/\/ CodeCancelled means the operation was cancelled, typically by the caller.\n\t\/\/ This is considered as a client error.\n\tCodeCancelled Code = 1\n\n\t\/\/ CodeUnknown means an unknown error. Errors raised by APIs\n\t\/\/ that do not return enough error information\n\t\/\/ may be converted to this error.\n\t\/\/ This is considered as a server error.\n\tCodeUnknown Code = 2\n\n\t\/\/ CodeInvalidArgument means the client specified an invalid argument.\n\t\/\/ Note that this differs from `FailedPrecondition`. `InvalidArgument`\n\t\/\/ indicates arguments that are problematic regardless of the state of\n\t\/\/ the system (e.g., a malformed file name).\n\t\/\/ This is considered as a client error.\n\tCodeInvalidArgument Code = 3\n\n\t\/\/ CodeDeadlineExceeded means the deadline expired before the operation could\n\t\/\/ complete. For operations that change the state of the system, this error\n\t\/\/ may be returned even if the operation has completed successfully. For example,\n\t\/\/ a successful response from a server could have been delayed long\n\t\/\/ enough for the deadline to expire.\n\t\/\/ This is considered as a server error.\n\tCodeDeadlineExceeded Code = 4\n\n\t\/\/ CodeNotFound means some requested entity (e.g., file or directory) was not found.\n\t\/\/ For privacy reasons, this code *may* be returned when the client\n\t\/\/ does not have the access rights to the entity, though such usage is\n\t\/\/ discouraged.\n\t\/\/ This is considered as a client error.\n\tCodeNotFound Code = 5\n\n\t\/\/ CodeAlreadyExists means the entity that a client attempted to create\n\t\/\/ (e.g., file or directory) already exists.\n\t\/\/ This is considered as a client error.\n\tCodeAlreadyExists Code = 6\n\n\t\/\/ CodePermissionDenied means the caller does not have permission to execute\n\t\/\/ the specified operation. `PermissionDenied` must not be used for rejections\n\t\/\/ caused by exhausting some resource (use `ResourceExhausted`\n\t\/\/ instead for those errors). `PermissionDenied` must not be\n\t\/\/ used if the caller can not be identified (use `Unauthenticated`\n\t\/\/ instead for those errors).\n\t\/\/ This is considered as a client error.\n\tCodePermissionDenied Code = 7\n\n\t\/\/ CodeResourceExhausted means some resource has been exhausted, perhaps a per-user\n\t\/\/ quota, or perhaps the entire file system is out of space.\n\t\/\/ This is considered as a client error.\n\tCodeResourceExhausted Code = 8\n\n\t\/\/ CodeFailedPrecondition means the operation was rejected because the system is not\n\t\/\/ in a state required for the operation's execution. For example, the directory\n\t\/\/ to be deleted is non-empty, an rmdir operation is applied to\n\t\/\/ a non-directory, etc.\n\t\/\/\n\t\/\/ Service implementors can use the following guidelines to decide\n\t\/\/ between `FailedPrecondition`, `Aborted`, and `Unavailable`:\n\t\/\/  (a) Use `Unavailable` if the client can retry just the failing call.\n\t\/\/  (b) Use `Aborted` if the client should retry at a higher level\n\t\/\/      (e.g., restarting a read-modify-write sequence).\n\t\/\/  (c) Use `FailedPrecondition` if the client should not retry until\n\t\/\/      the system state has been explicitly fixed. E.g., if an \"rmdir\"\n\t\/\/      fails because the directory is non-empty, `FailedPrecondition`\n\t\/\/      should be returned since the client should not retry unless\n\t\/\/      the files are deleted from the directory.\n\t\/\/ This is considered as a client error.\n\tCodeFailedPrecondition Code = 9\n\n\t\/\/ CodeAborted means the operation was aborted, typically due to a concurrency issue\n\t\/\/ such as a sequencer check failure or transaction abort.\n\t\/\/\n\t\/\/ See the guidelines above for deciding between `FailedPrecondition`,\n\t\/\/ `Aborted`, and `Unavailable`.\n\t\/\/ This is considered as a client error.\n\tCodeAborted Code = 10\n\n\t\/\/ CodeOutOfRange means the operation was attempted past the valid range.\n\t\/\/ E.g., seeking or reading past end-of-file.\n\t\/\/\n\t\/\/ Unlike `InvalidArgument`, this error indicates a problem that may\n\t\/\/ be fixed if the system state changes. For example, a 32-bit file\n\t\/\/ system will generate `InvalidArgument` if asked to read at an\n\t\/\/ offset that is not in the range [0,2^32-1], but it will generate\n\t\/\/ `OutOfRange` if asked to read from an offset past the current\n\t\/\/ file size.\n\t\/\/\n\t\/\/ There is a fair bit of overlap between `FailedPrecondition` and\n\t\/\/ `OutOfRange`.  We recommend using `OutOfRange` (the more specific\n\t\/\/ error) when it applies so that callers who are iterating through\n\t\/\/ a space can easily look for an `OutOfRange` error to detect when\n\t\/\/ they are done.\n\t\/\/ This is considered as a client error.\n\tCodeOutOfRange Code = 11\n\n\t\/\/ CodeUnimplemented means the operation is not implemented or is not\n\t\/\/ supported\/enabled in this service.\n\t\/\/ This is considered as a client error.\n\tCodeUnimplemented Code = 12\n\n\t\/\/ CodeInternal means an internal error. This means that some invariants expected\n\t\/\/ by the underlying system have been broken. This error code is reserved\n\t\/\/ for serious errors.\n\t\/\/ This is considered as a server error.\n\tCodeInternal Code = 13\n\n\t\/\/ CodeUnavailable means the service is currently unavailable. This is most likely a\n\t\/\/ transient condition, which can be corrected by retrying with a backoff.\n\t\/\/\n\t\/\/ See the guidelines above for deciding between `FailedPrecondition`,\n\t\/\/ `Aborted`, and `Unavailable`.\n\t\/\/ This is considered as a server error.\n\tCodeUnavailable Code = 14\n\n\t\/\/ CodeDataLoss means unrecoverable data loss or corruption.\n\t\/\/ This is considered as a server error.\n\tCodeDataLoss Code = 15\n\n\t\/\/ CodeUnauthenticated means the request does not have valid authentication\n\t\/\/ credentials for the operation.\n\t\/\/ This is considered as a client error.\n\tCodeUnauthenticated Code = 16\n)\n\nvar (\n\t_codeToString = map[Code]string{\n\t\tCodeOK:                 \"ok\",\n\t\tCodeCancelled:          \"cancelled\",\n\t\tCodeUnknown:            \"unknown\",\n\t\tCodeInvalidArgument:    \"invalid-argument\",\n\t\tCodeDeadlineExceeded:   \"deadline-exceeded\",\n\t\tCodeNotFound:           \"not-found\",\n\t\tCodeAlreadyExists:      \"already-exists\",\n\t\tCodePermissionDenied:   \"permission-denied\",\n\t\tCodeResourceExhausted:  \"resource-exhausted\",\n\t\tCodeFailedPrecondition: \"failed-precondition\",\n\t\tCodeAborted:            \"aborted\",\n\t\tCodeOutOfRange:         \"out-of-range\",\n\t\tCodeUnimplemented:      \"unimplemented\",\n\t\tCodeInternal:           \"internal\",\n\t\tCodeUnavailable:        \"unavailable\",\n\t\tCodeDataLoss:           \"data-loss\",\n\t\tCodeUnauthenticated:    \"unauthenticated\",\n\t}\n\t_stringToCode = map[string]Code{\n\t\t\"ok\":                  CodeOK,\n\t\t\"cancelled\":           CodeCancelled,\n\t\t\"unknown\":             CodeUnknown,\n\t\t\"invalid-argument\":    CodeInvalidArgument,\n\t\t\"deadline-exceeded\":   CodeDeadlineExceeded,\n\t\t\"not-found\":           CodeNotFound,\n\t\t\"already-exists\":      CodeAlreadyExists,\n\t\t\"permission-denied\":   CodePermissionDenied,\n\t\t\"resource-exhausted\":  CodeResourceExhausted,\n\t\t\"failed-precondition\": CodeFailedPrecondition,\n\t\t\"aborted\":             CodeAborted,\n\t\t\"out-of-range\":        CodeOutOfRange,\n\t\t\"unimplemented\":       CodeUnimplemented,\n\t\t\"internal\":            CodeInternal,\n\t\t\"unavailable\":         CodeUnavailable,\n\t\t\"data-loss\":           CodeDataLoss,\n\t\t\"unauthenticated\":     CodeUnauthenticated,\n\t}\n)\n\n\/\/ Code represents the type of error for an RPC call.\n\/\/\n\/\/ Sometimes multiple error codes may apply. Services should return\n\/\/ the most specific error code that applies. For example, prefer\n\/\/ `OutOfRange` over `FailedPrecondition` if both codes apply.\n\/\/ Similarly prefer `NotFound` or `AlreadyExists` over `FailedPrecondition`.\n\/\/\n\/\/ These codes are meant to match gRPC status codes.\n\/\/ https:\/\/godoc.org\/google.golang.org\/grpc\/codes#Code\ntype Code int\n\n\/\/ String returns the the string representation of the Code.\nfunc (c Code) String() string {\n\ts, ok := _codeToString[c]\n\tif ok {\n\t\treturn s\n\t}\n\treturn strconv.Itoa(int(c))\n}\n\n\/\/ MarshalText implements encoding.TextMarshaler.\nfunc (c Code) MarshalText() ([]byte, error) {\n\ts, ok := _codeToString[c]\n\tif ok {\n\t\treturn []byte(s), nil\n\t}\n\treturn nil, fmt.Errorf(\"unknown code: %d\", int(c))\n}\n\n\/\/ UnmarshalText implements encoding.TextUnmarshaler.\nfunc (c *Code) UnmarshalText(text []byte) error {\n\ti, ok := _stringToCode[strings.ToLower(string(text))]\n\tif !ok {\n\t\treturn fmt.Errorf(\"unknown code string: %s\", string(text))\n\t}\n\t*c = i\n\treturn nil\n}\n\n\/\/ MarshalJSON implements json.Marshaler.\nfunc (c Code) MarshalJSON() ([]byte, error) {\n\ts, ok := _codeToString[c]\n\tif ok {\n\t\treturn []byte(`\"` + s + `\"`), nil\n\t}\n\treturn nil, fmt.Errorf(\"unknown code: %d\", int(c))\n}\n\n\/\/ UnmarshalJSON implements json.Unmarshaler.\nfunc (c *Code) UnmarshalJSON(text []byte) error {\n\ts := string(text)\n\tif len(s) < 3 || s[0] != '\"' || s[len(s)-1] != '\"' {\n\t\treturn fmt.Errorf(\"invalid code string: %s\", s)\n\t}\n\ti, ok := _stringToCode[strings.ToLower(s[1:len(s)-1])]\n\tif !ok {\n\t\treturn fmt.Errorf(\"unknown code string: %s\", s)\n\t}\n\t*c = i\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\n\/\/ index template\nconst index = `[[define \"index\"]]<!doctype html>\n<html ng-app=\"prim\" ng-strict-di lang=\"en\">\n[[template \"head\" . ]]\n<body>\n<ng-include src=\"'pages\/global.html'\"><\/ng-include>\n<div class=\"header\">\n[[template \"header\" . ]]\n<\/div>\n<div ng-view><\/div>\n<\/body>\n<\/html>[[end]]`\n\n\/\/ head items\nconst head = `[[define \"head\"]]<head>\n<base href=\"\/[[ .base ]]\">\n<title data-ng-bind=\"page.title\">[[ .title ]]<\/title>\n<meta charset=\"utf-8\" \/>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" \/>\n<meta name=\"description\" content=\"[[ .desc ]]\" \/>[[if .nsfw -]]\n<meta name=\"rating\" content=\"adult\" \/>\n<meta name=\"rating\" content=\"RTA-5042-1996-1400-1577-RTA\" \/>\n[[- end]]\n<link rel=\"stylesheet\" href=\"\/assets\/prim\/[[ .primcss ]]\" \/>\n<link rel=\"stylesheet\" href=\"\/assets\/styles\/[[ .style ]]\" \/>\n<link rel=\"stylesheet\" href=\"https:\/\/maxcdn.bootstrapcdn.com\/font-awesome\/4.4.0\/css\/font-awesome.min.css\">\n<script src=\"\/assets\/prim\/[[ .primjs ]]\"><\/script>\n[[template \"angular\" . ]][[template \"headinclude\" . ]]\n<\/head>[[end]]`\n\n\/\/ angular config\nconst angular = `[[define \"angular\"]]<script>\nangular.module('prim').constant('config',{\nib_id:[[ .ib ]],\ntitle:'[[ .title ]]',\nimg_srv:'\/\/[[ .imgsrv ]]',\napi_srv:'\/\/[[ .apisrv ]]',\ncsrf_token:'[[ .csrf ]]'\n});\n<\/script>[[end]]`\n\n\/\/ site header\nconst header = `[[define \"header\"]]<div class=\"header_bar\">\n<div class=\"left\">\n<div class=\"nav_menu\" ng-controller=\"NavMenuCtrl as navmenu\">\n<ul click-off=\"navmenu.close\" ng-click=\"navmenu.toggle()\" ng-mouseenter=\"navmenu.open()\" ng-mouseleave=\"navmenu.close()\">\n<li class=\"n1\"><a href><i class=\"fa fa-fw fa-bars\"><\/i><\/a>\n<ul ng-if=\"navmenu.visible\">\n[[template \"navmenuinclude\" . ]][[template \"navmenu\" . ]]\n<\/ul>\n<\/li>\n<\/ul>\n<\/div>\n<div class=\"nav_items\" ng-controller=\"NavItemsCtrl as navitems\">\n<ul>\n<ng-include src=\"'pages\/menus\/nav.html'\"><\/ng-include>\n<\/ul>\n<\/div>\n<\/div>\n<div class=\"right\">\n<div class=\"user_menu\">\n<div ng-if=\"!authState.isAuthenticated\" class=\"login\">\n<a href=\"account\" class=\"button-login\">Sign in<\/a>\n<\/div>\n<div ng-if=\"authState.isAuthenticated\" ng-controller=\"UserMenuCtrl as usermenu\">\n<ul click-off=\"usermenu.close\" ng-click=\"usermenu.toggle()\" ng-mouseenter=\"usermenu.open()\" ng-mouseleave=\"usermenu.close()\">\n<li>\n<div class=\"avatar avatar-medium\">\n<div class=\"avatar-inner\">\n<a href>\n<img ng-src=\"{{authState.avatar}}\" \/>\n<\/a>\n<\/div>\n<\/div>\n<ul ng-if=\"usermenu.visible\">\n<ng-include src=\"'pages\/menus\/user.html'\"><\/ng-include>\n<\/ul>\n<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<div class=\"site_logo\">\n<a href=\"\/[[ .base ]]\">\n<img src=\"\/assets\/logo\/[[ .logo ]]\" title=\"[[ .title ]]\" \/>\n<\/a>\n<\/div>\n<\/div>\n<\/div>[[end]]`\n\nconst navmenu = `[[define \"navmenu\"]][[ range $ib := .imageboards]]<li><a target=\"_self\" href=\"\/\/[[ $ib.Address ]]\/\">[[ $ib.Title ]]<\/a><\/li>\n[[end]][[end]]`\n<commit_msg>move stylesheets above js<commit_after>package main\n\n\/\/ index template\nconst index = `[[define \"index\"]]<!doctype html>\n<html ng-app=\"prim\" ng-strict-di lang=\"en\">\n[[template \"head\" . ]]\n<body>\n<ng-include src=\"'pages\/global.html'\"><\/ng-include>\n<div class=\"header\">\n[[template \"header\" . ]]\n<\/div>\n<div ng-view><\/div>\n<\/body>\n<\/html>[[end]]`\n\n\/\/ head items\nconst head = `[[define \"head\"]]<head>\n<base href=\"\/[[ .base ]]\">\n<title data-ng-bind=\"page.title\">[[ .title ]]<\/title>\n<meta charset=\"utf-8\" \/>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" \/>\n<meta name=\"description\" content=\"[[ .desc ]]\" \/>[[if .nsfw -]]\n<meta name=\"rating\" content=\"adult\" \/>\n<meta name=\"rating\" content=\"RTA-5042-1996-1400-1577-RTA\" \/>\n[[- end]]\n<link rel=\"stylesheet\" href=\"\/assets\/prim\/[[ .primcss ]]\" \/>\n<link rel=\"stylesheet\" href=\"\/assets\/styles\/[[ .style ]]\" \/>\n<link rel=\"stylesheet\" href=\"https:\/\/maxcdn.bootstrapcdn.com\/font-awesome\/4.4.0\/css\/font-awesome.min.css\">\n<script src=\"\/assets\/prim\/[[ .primjs ]]\"><\/script>\n[[template \"angular\" . ]][[template \"headinclude\" . ]]\n<\/head>[[end]]`\n\n\/\/ angular config\nconst angular = `[[define \"angular\"]]<script>\nangular.module('prim').constant('config',{\nib_id:[[ .ib ]],\ntitle:'[[ .title ]]',\nimg_srv:'\/\/[[ .imgsrv ]]',\napi_srv:'\/\/[[ .apisrv ]]',\ncsrf_token:'[[ .csrf ]]'\n});\n<\/script>[[end]]`\n\n\/\/ site header\nconst header = `[[define \"header\"]]<div class=\"header_bar\">\n<div class=\"left\">\n<div class=\"nav_menu\" ng-controller=\"NavMenuCtrl as navmenu\">\n<ul click-off=\"navmenu.close\" ng-click=\"navmenu.toggle()\" ng-mouseenter=\"navmenu.open()\" ng-mouseleave=\"navmenu.close()\">\n<li class=\"n1\"><a href><i class=\"fa fa-fw fa-bars\"><\/i><\/a>\n<ul ng-if=\"navmenu.visible\">\n[[template \"navmenuinclude\" . ]][[template \"navmenu\" . ]]\n<\/ul>\n<\/li>\n<\/ul>\n<\/div>\n<div class=\"nav_items\" ng-controller=\"NavItemsCtrl as navitems\">\n<ul>\n<ng-include src=\"'pages\/menus\/nav.html'\"><\/ng-include>\n<\/ul>\n<\/div>\n<\/div>\n<div class=\"right\">\n<div class=\"user_menu\">\n<div ng-if=\"!authState.isAuthenticated\" class=\"login\">\n<a href=\"account\" class=\"button-login\">Sign in<\/a>\n<\/div>\n<div ng-if=\"authState.isAuthenticated\" ng-controller=\"UserMenuCtrl as usermenu\">\n<ul click-off=\"usermenu.close\" ng-click=\"usermenu.toggle()\" ng-mouseenter=\"usermenu.open()\" ng-mouseleave=\"usermenu.close()\">\n<li>\n<div class=\"avatar avatar-medium\">\n<div class=\"avatar-inner\">\n<a href>\n<img ng-src=\"{{authState.avatar}}\" \/>\n<\/a>\n<\/div>\n<\/div>\n<ul ng-if=\"usermenu.visible\">\n<ng-include src=\"'pages\/menus\/user.html'\"><\/ng-include>\n<\/ul>\n<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<div class=\"site_logo\">\n<a href=\"\/[[ .base ]]\"><img src=\"\/assets\/logo\/[[ .logo ]]\" \/><\/a>\n<\/div>\n<\/div>\n<\/div>[[end]]`\n\nconst navmenu = `[[define \"navmenu\"]][[ range $ib := .imageboards]]<li><a target=\"_self\" href=\"\/\/[[ $ib.Address ]]\/\">[[ $ib.Title ]]<\/a><\/li>\n[[end]][[end]]`\n<|endoftext|>"}
{"text":"<commit_before>package waveguide\n\nimport \"html\/template\"\n\nvar tmpl = template.Must(template.New(\"\").Parse(`\n{{define \"header\"}}\n<html>\n        <head>\n                <title>Waveguide<\/title>\n                <style>\n                        body {\n                                font-family: monospace;\n                        }\n                        table {\n                                border-collapse: separate;\n                                font-size: 12pt;\n                        }\n                        th {\n                                text-align: left;\n                        }\n                        th, td {\n                                padding: 0 1em 0.5ex 0;\n                        }\n                        form {\n                        \tmargin: 0\n                        }\n                <\/style>\n        <\/head>\n        <body>\n{{end}}\n\n{{define \"footer\"}}\n\t<\/body>\n<\/html>\n{{end}}\n\n{{define \"root\"}}\n{{template \"header\"}}\n                <table>\n                \t{{if .Spots}}\n\t\t\t\t<thead>\n\t\t\t\t\t<th>Location<\/th>\n\t\t\t\t\t<th>Coordinates<\/th>\n\t\t\t\t\t<th>Conditions<\/th>\n\t\t\t\t\t<th>Wave Height<\/th>\n\t\t\t\t\t<th>Last Updated<\/th>\n\t\t\t\t<\/thead>\n\t\t\t\t<tbody>\n\t\t\t\t\t{{range .Spots}}\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><a href=\"{{.MapURL}}\">{{.HTMLName}}<\/a><\/td>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t{{if .HasCoordinates}}\n\t\t\t\t\t\t\t\t\t<a href=\"{{.ClearCoordsURL}}\">❌<\/a>\n\t\t\t\t\t\t\t\t\t<a href=\"{{.MapsURL}}\">{{.FormattedCoordinates}}<\/a>\n\t\t\t\t\t\t\t\t{{else}}\n\t\t\t\t\t\t\t\t\t<form action=\"\/coords\" method=\"post\">\n\t\t\t\t\t\t\t\t\t\t<input type=\"hidden\" name=\"path\" value=\"{{.MswPath}}\" \/>\n\t\t\t\t\t\t\t\t\t\t<input name=\"coordinates\" \/>\n\t\t\t\t\t\t\t\t\t\t<button type=\"submit\">Submit<\/button>\n\t\t\t\t\t\t\t\t\t<\/form>\n\t\t\t\t\t\t\t\t{{end}}\n\t\t\t\t\t\t\t<\/td>\n\t\t\t\t\t\t\t<td><a href=\"{{.ReportURL}}\">{{.Cond.Stars}}<\/a><\/td>\n\t\t\t\t\t\t\t<td>{{.Cond.WaveHeight}}<\/td>\n\t\t\t\t\t\t\t<td>{{.Cond.HowLong}} ago<\/td>\n\t\t\t\t\t\t<\/tr>\n\t\t\t\t\t{{end}}\n\t\t\t\t<\/tbody>\n\t\t\t{{else}}\n\t\t\t\tThere's no data yet. You can get some by visiting <a href=\"\/update_all\">\/update_all<\/a>.\n\t\t\t{{end}}\n                <\/table>\n{{template \"footer\"}}\n{{end}}\n\n{{define \"action_response\"}}\n{{template \"header\"}}\n\t\t<div><a href=\"\/\">← home<\/a><\/div>\n\t\t<div id=\"message\">{{.Message}}<\/div>\n{{template \"footer\"}}\n{{end}}\n\n{{define \"map\"}}\n<!DOCTYPE html>\n<html>\n  <head>\n    <title>Waveguide<\/title>\n    <meta name=\"viewport\" content=\"initial-scale=1.0\">\n    <meta charset=\"utf-8\">\n    <style>\n      \/* Always set the map height explicitly to define the size of the div\n       * element that contains the map. *\/\n      #map {\n        height: 100%;\n      }\n      \/* Optional: Makes the sample page fill the window. *\/\n      html, body {\n        height: 100%;\n        margin: 0;\n        padding: 0;\n      }\n    <\/style>\n  <\/head>\n  <body>\n    <div id=\"map\"><\/div>\n    <script>\n      var map;\n      function initMap() {\n        map = new google.maps.Map(document.getElementById('map'), {\n          center: {lat: 20.8020856, lng: -156.8984559},\n          zoom: 2\n        });\n\n\tvar spots = [\n\t\t{{range .}}\n\t\t\t{title: '{{.Name}} {{.Cond.Stars}}', lat: {{.Coordinates.Lat}}, lng: {{.Coordinates.Lng}}, rating: {{.Cond.Rating}} },\n\t\t{{end}}\n\t]\n\tfor (var i = 0; i < spots.length; i++) {\n\t\tvar s = spots[i]\n\t\tif (s.lat == 0 && s.lng == 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tvar marker = new google.maps.Marker({\n\t\t  position: {lat: s.lat, lng: s.lng},\n\t\t  map: map,\n\t\t  title: s.title,\n\t\t  label: {\n\t\t    text: s.title,\n\t\t  },\n  \t\t});\n\t}\n      }\n    <\/script>\n    <script src=\"https:\/\/maps.googleapis.com\/maps\/api\/js?key=AIzaSyDZ8Bm6MbFrfZ37ko8UTCDErLVQa5DBn8M&callback=initMap\"\n    async defer><\/script>\n  <\/body>\n<\/html>\n{{end}}\n`))\n<commit_msg>Clean up the map view by removing the labels and stars.<commit_after>package waveguide\n\nimport \"html\/template\"\n\nvar tmpl = template.Must(template.New(\"\").Parse(`\n{{define \"header\"}}\n<html>\n        <head>\n                <title>Waveguide<\/title>\n                <style>\n                        body {\n                                font-family: monospace;\n                        }\n                        table {\n                                border-collapse: separate;\n                                font-size: 12pt;\n                        }\n                        th {\n                                text-align: left;\n                        }\n                        th, td {\n                                padding: 0 1em 0.5ex 0;\n                        }\n                        form {\n                        \tmargin: 0\n                        }\n                <\/style>\n        <\/head>\n        <body>\n{{end}}\n\n{{define \"footer\"}}\n\t<\/body>\n<\/html>\n{{end}}\n\n{{define \"root\"}}\n{{template \"header\"}}\n                <table>\n                \t{{if .Spots}}\n\t\t\t\t<thead>\n\t\t\t\t\t<th>Location<\/th>\n\t\t\t\t\t<th>Coordinates<\/th>\n\t\t\t\t\t<th>Conditions<\/th>\n\t\t\t\t\t<th>Wave Height<\/th>\n\t\t\t\t\t<th>Last Updated<\/th>\n\t\t\t\t<\/thead>\n\t\t\t\t<tbody>\n\t\t\t\t\t{{range .Spots}}\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td><a href=\"{{.MapURL}}\">{{.HTMLName}}<\/a><\/td>\n\t\t\t\t\t\t\t<td>\n\t\t\t\t\t\t\t\t{{if .HasCoordinates}}\n\t\t\t\t\t\t\t\t\t<a href=\"{{.ClearCoordsURL}}\">❌<\/a>\n\t\t\t\t\t\t\t\t\t<a href=\"{{.MapsURL}}\">{{.FormattedCoordinates}}<\/a>\n\t\t\t\t\t\t\t\t{{else}}\n\t\t\t\t\t\t\t\t\t<form action=\"\/coords\" method=\"post\">\n\t\t\t\t\t\t\t\t\t\t<input type=\"hidden\" name=\"path\" value=\"{{.MswPath}}\" \/>\n\t\t\t\t\t\t\t\t\t\t<input name=\"coordinates\" \/>\n\t\t\t\t\t\t\t\t\t\t<button type=\"submit\">Submit<\/button>\n\t\t\t\t\t\t\t\t\t<\/form>\n\t\t\t\t\t\t\t\t{{end}}\n\t\t\t\t\t\t\t<\/td>\n\t\t\t\t\t\t\t<td><a href=\"{{.ReportURL}}\">{{.Cond.Stars}}<\/a><\/td>\n\t\t\t\t\t\t\t<td>{{.Cond.WaveHeight}}<\/td>\n\t\t\t\t\t\t\t<td>{{.Cond.HowLong}} ago<\/td>\n\t\t\t\t\t\t<\/tr>\n\t\t\t\t\t{{end}}\n\t\t\t\t<\/tbody>\n\t\t\t{{else}}\n\t\t\t\tThere's no data yet. You can get some by visiting <a href=\"\/update_all\">\/update_all<\/a>.\n\t\t\t{{end}}\n                <\/table>\n{{template \"footer\"}}\n{{end}}\n\n{{define \"action_response\"}}\n{{template \"header\"}}\n\t\t<div><a href=\"\/\">← home<\/a><\/div>\n\t\t<div id=\"message\">{{.Message}}<\/div>\n{{template \"footer\"}}\n{{end}}\n\n{{define \"map\"}}\n<!DOCTYPE html>\n<html>\n  <head>\n    <title>Waveguide<\/title>\n    <meta name=\"viewport\" content=\"initial-scale=1.0\">\n    <meta charset=\"utf-8\">\n    <style>\n      \/* Always set the map height explicitly to define the size of the div\n       * element that contains the map. *\/\n      #map {\n        height: 100%;\n      }\n      \/* Optional: Makes the sample page fill the window. *\/\n      html, body {\n        height: 100%;\n        margin: 0;\n        padding: 0;\n      }\n    <\/style>\n  <\/head>\n  <body>\n    <div id=\"map\"><\/div>\n    <script>\n      var map;\n      function initMap() {\n        map = new google.maps.Map(document.getElementById('map'), {\n          center: {lat: 20.8020856, lng: -156.8984559},\n          zoom: 2\n        });\n\n\tvar spots = [\n\t\t{{range .}}\n\t\t\t{title: '{{.Name}} {{.Cond.Stars}}', lat: {{.Coordinates.Lat}}, lng: {{.Coordinates.Lng}}, rating: {{.Cond.Rating}} },\n\t\t{{end}}\n\t]\n\tfor (var i = 0; i < spots.length; i++) {\n\t\tvar s = spots[i]\n\t\tif (s.lat == 0 && s.lng == 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tvar marker = new google.maps.Marker({\n\t\t  position: {lat: s.lat, lng: s.lng},\n\t\t  map: map,\n\t\t  title: s.title,\n  \t\t});\n\t}\n      }\n    <\/script>\n    <script src=\"https:\/\/maps.googleapis.com\/maps\/api\/js?key=AIzaSyDZ8Bm6MbFrfZ37ko8UTCDErLVQa5DBn8M&callback=initMap\"\n    async defer><\/script>\n  <\/body>\n<\/html>\n{{end}}\n`))\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nvar templContent = `<!doctype html>\n<html>\n  <head>\n    <meta charset=\"utf-8\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"chrome=1\">\n    <title><\/title>\n    <style text=\"text\/css\">\n.markdown-body {\n\t\tmargin: 0 auto;\n\t\tfont: 13px Helvetica, arial, freesans, clean, sans-serif;\n\t\twidth: 800px;\n    font-size: 14px;\n    line-height: 1.6;\n}\n.markdown-body > *:first-child {\n    margin-top: 0 !important;\n}\n.markdown-body > *:last-child {\n    margin-bottom: 0 !important;\n}\n.markdown-body a {\n    text-decoration: none;\n}\n.markdown-body a:hover {\n    text-decoration: underline;\n}\n.markdown-body a.absent {\n    color: #CC0000;\n}\n.markdown-body a.anchor {\n    bottom: 0;\n    cursor: pointer;\n    display: block;\n    left: 0;\n    margin-left: -30px;\n    padding-left: 30px;\n    position: absolute;\n    top: 0;\n}\n.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6 {\n    cursor: text;\n    font-weight: bold;\n    margin: 20px 0 10px;\n    padding: 0;\n    position: relative;\n}\n.markdown-body h1 .mini-icon-link, .markdown-body h2 .mini-icon-link, .markdown-body h3 .mini-icon-link, .markdown-body h4 .mini-icon-link, .markdown-body h5 .mini-icon-link, .markdown-body h6 .mini-icon-link {\n    color: #000000;\n    display: none;\n}\n.markdown-body h1:hover a.anchor, .markdown-body h2:hover a.anchor, .markdown-body h3:hover a.anchor, .markdown-body h4:hover a.anchor, .markdown-body h5:hover a.anchor, .markdown-body h6:hover a.anchor {\n    line-height: 1;\n    margin-left: -22px;\n    padding-left: 0;\n    text-decoration: none;\n    top: 15%;\n}\n.markdown-body h1:hover a.anchor .mini-icon-link, .markdown-body h2:hover a.anchor .mini-icon-link, .markdown-body h3:hover a.anchor .mini-icon-link, .markdown-body h4:hover a.anchor .mini-icon-link, .markdown-body h5:hover a.anchor .mini-icon-link, .markdown-body h6:hover a.anchor .mini-icon-link {\n    display: inline-block;\n}\n.markdown-body h1 tt, .markdown-body h1 code, .markdown-body h2 tt, .markdown-body h2 code, .markdown-body h3 tt, .markdown-body h3 code, .markdown-body h4 tt, .markdown-body h4 code, .markdown-body h5 tt, .markdown-body h5 code, .markdown-body h6 tt, .markdown-body h6 code {\n    font-size: inherit;\n}\n.markdown-body h1 {\n    color: #000000;\n    font-size: 28px;\n}\n.markdown-body h2 {\n    border-bottom: 1px solid #CCCCCC;\n    color: #000000;\n    font-size: 24px;\n}\n.markdown-body h3 {\n    font-size: 18px;\n}\n.markdown-body h4 {\n    font-size: 16px;\n}\n.markdown-body h5 {\n    font-size: 14px;\n}\n.markdown-body h6 {\n    color: #777777;\n    font-size: 14px;\n}\n.markdown-body p, .markdown-body blockquote, .markdown-body ul, .markdown-body ol, .markdown-body dl, .markdown-body table, .markdown-body pre {\n    margin: 15px 0;\n}\n.markdown-body hr {\n    border: 0 none;\n    color: #CCCCCC;\n    height: 4px;\n    padding: 0;\n}\n.markdown-body > h2:first-child, .markdown-body > h1:first-child, .markdown-body > h1:first-child + h2, .markdown-body > h3:first-child, .markdown-body > h4:first-child, .markdown-body > h5:first-child, .markdown-body > h6:first-child {\n    margin-top: 0;\n    padding-top: 0;\n}\n.markdown-body a:first-child h1, .markdown-body a:first-child h2, .markdown-body a:first-child h3, .markdown-body a:first-child h4, .markdown-body a:first-child h5, .markdown-body a:first-child h6 {\n    margin-top: 0;\n    padding-top: 0;\n}\n.markdown-body h1 + p, .markdown-body h2 + p, .markdown-body h3 + p, .markdown-body h4 + p, .markdown-body h5 + p, .markdown-body h6 + p {\n    margin-top: 0;\n}\n.markdown-body li p.first {\n    display: inline-block;\n}\n.markdown-body ul, .markdown-body ol {\n    padding-left: 30px;\n}\n.markdown-body ul.no-list, .markdown-body ol.no-list {\n    list-style-type: none;\n    padding: 0;\n}\n.markdown-body ul li > *:first-child, .markdown-body ol li > *:first-child {\n    margin-top: 0;\n}\n.markdown-body ul ul, .markdown-body ul ol, .markdown-body ol ol, .markdown-body ol ul {\n    margin-bottom: 0;\n}\n.markdown-body dl {\n    padding: 0;\n}\n.markdown-body dl dt {\n    font-size: 14px;\n    font-style: italic;\n    font-weight: bold;\n    margin: 15px 0 5px;\n    padding: 0;\n}\n.markdown-body dl dt:first-child {\n    padding: 0;\n}\n.markdown-body dl dt > *:first-child {\n    margin-top: 0;\n}\n.markdown-body dl dt > *:last-child {\n    margin-bottom: 0;\n}\n.markdown-body dl dd {\n    margin: 0 0 15px;\n    padding: 0 15px;\n}\n.markdown-body dl dd > *:first-child {\n    margin-top: 0;\n}\n.markdown-body dl dd > *:last-child {\n    margin-bottom: 0;\n}\n.markdown-body blockquote {\n    border-left: 4px solid #DDDDDD;\n    color: #777777;\n    padding: 0 15px;\n}\n.markdown-body blockquote > *:first-child {\n    margin-top: 0;\n}\n.markdown-body blockquote > *:last-child {\n    margin-bottom: 0;\n}\n.markdown-body table th {\n    font-weight: bold;\n}\n.markdown-body table th, .markdown-body table td {\n    border: 1px solid #CCCCCC;\n    padding: 6px 13px;\n}\n.markdown-body table tr {\n    background-color: #FFFFFF;\n    border-top: 1px solid #CCCCCC;\n}\n.markdown-body table tr:nth-child(2n) {\n    background-color: #F8F8F8;\n}\n.markdown-body img {\n    max-width: 100%;\n}\n.markdown-body span.frame {\n    display: block;\n    overflow: hidden;\n}\n.markdown-body span.frame > span {\n    border: 1px solid #DDDDDD;\n    display: block;\n    float: left;\n    margin: 13px 0 0;\n    overflow: hidden;\n    padding: 7px;\n    width: auto;\n}\n.markdown-body span.frame span img {\n    display: block;\n    float: left;\n}\n.markdown-body span.frame span span {\n    clear: both;\n    color: #333333;\n    display: block;\n    padding: 5px 0 0;\n}\n.markdown-body span.align-center {\n    clear: both;\n    display: block;\n    overflow: hidden;\n}\n.markdown-body span.align-center > span {\n    display: block;\n    margin: 13px auto 0;\n    overflow: hidden;\n    text-align: center;\n}\n.markdown-body span.align-center span img {\n    margin: 0 auto;\n    text-align: center;\n}\n.markdown-body span.align-right {\n    clear: both;\n    display: block;\n    overflow: hidden;\n}\n.markdown-body span.align-right > span {\n    display: block;\n    margin: 13px 0 0;\n    overflow: hidden;\n    text-align: right;\n}\n.markdown-body span.align-right span img {\n    margin: 0;\n    text-align: right;\n}\n.markdown-body span.float-left {\n    display: block;\n    float: left;\n    margin-right: 13px;\n    overflow: hidden;\n}\n.markdown-body span.float-left span {\n    margin: 13px 0 0;\n}\n.markdown-body span.float-right {\n    display: block;\n    float: right;\n    margin-left: 13px;\n    overflow: hidden;\n}\n.markdown-body span.float-right > span {\n    display: block;\n    margin: 13px auto 0;\n    overflow: hidden;\n    text-align: right;\n}\n.markdown-body code, .markdown-body tt {\n\t\tfont-family: Consolas, \"Liberation Mono\", Courier, monospace;\n    background-color: #F8F8F8;\n    border: 1px solid #EAEAEA;\n    border-radius: 3px 3px 3px 3px;\n    margin: 0 2px;\n    padding: 0 5px;\n    white-space: nowrap;\n}\n.markdown-body pre > code {\n\t\tfont-size: 14px;\n    background: none repeat scroll 0 0 transparent;\n    border: medium none;\n    margin: 0;\n    padding: 0;\n    white-space: pre;\n}\n.markdown-body .highlight pre, .markdown-body pre {\n    background-color: #F8F8F8;\n    border: 1px solid #CCCCCC;\n    border-radius: 3px 3px 3px 3px;\n    font-size: 13px;\n    line-height: 19px;\n    overflow: auto;\n    padding: 6px 10px;\n}\n.markdown-body pre code, .markdown-body pre tt {\n    background-color: transparent;\n    border: medium none;\n}\n    <\/style>\n\t<\/head>\n\t<body>\n\t<div class=\"markdown-body\">{{.Content}}<\/div>\n\t<\/body>\n<\/html>\n`<commit_msg>tabify<commit_after>package main\n\nvar templContent = `<!doctype html>\n<html>\n\t<head>\n\t\t<meta charset=\"utf-8\">\n\t\t<meta http-equiv=\"X-UA-Compatible\" content=\"chrome=1\">\n\t\t<title><\/title>\n\t\t<style text=\"text\/css\">\n.markdown-body {\n\t\tmargin: 0 auto;\n\t\tfont: 13px Helvetica, arial, freesans, clean, sans-serif;\n\t\twidth: 800px;\n\t\tfont-size: 14px;\n\t\tline-height: 1.6;\n}\n.markdown-body > *:first-child {\n\t\tmargin-top: 0 !important;\n}\n.markdown-body > *:last-child {\n\t\tmargin-bottom: 0 !important;\n}\n.markdown-body a {\n\t\ttext-decoration: none;\n}\n.markdown-body a:hover {\n\t\ttext-decoration: underline;\n}\n.markdown-body a.absent {\n\t\tcolor: #CC0000;\n}\n.markdown-body a.anchor {\n\t\tbottom: 0;\n\t\tcursor: pointer;\n\t\tdisplay: block;\n\t\tleft: 0;\n\t\tmargin-left: -30px;\n\t\tpadding-left: 30px;\n\t\tposition: absolute;\n\t\ttop: 0;\n}\n.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6 {\n\t\tcursor: text;\n\t\tfont-weight: bold;\n\t\tmargin: 20px 0 10px;\n\t\tpadding: 0;\n\t\tposition: relative;\n}\n.markdown-body h1 .mini-icon-link, .markdown-body h2 .mini-icon-link, .markdown-body h3 .mini-icon-link, .markdown-body h4 .mini-icon-link, .markdown-body h5 .mini-icon-link, .markdown-body h6 .mini-icon-link {\n\t\tcolor: #000000;\n\t\tdisplay: none;\n}\n.markdown-body h1:hover a.anchor, .markdown-body h2:hover a.anchor, .markdown-body h3:hover a.anchor, .markdown-body h4:hover a.anchor, .markdown-body h5:hover a.anchor, .markdown-body h6:hover a.anchor {\n\t\tline-height: 1;\n\t\tmargin-left: -22px;\n\t\tpadding-left: 0;\n\t\ttext-decoration: none;\n\t\ttop: 15%;\n}\n.markdown-body h1:hover a.anchor .mini-icon-link, .markdown-body h2:hover a.anchor .mini-icon-link, .markdown-body h3:hover a.anchor .mini-icon-link, .markdown-body h4:hover a.anchor .mini-icon-link, .markdown-body h5:hover a.anchor .mini-icon-link, .markdown-body h6:hover a.anchor .mini-icon-link {\n\t\tdisplay: inline-block;\n}\n.markdown-body h1 tt, .markdown-body h1 code, .markdown-body h2 tt, .markdown-body h2 code, .markdown-body h3 tt, .markdown-body h3 code, .markdown-body h4 tt, .markdown-body h4 code, .markdown-body h5 tt, .markdown-body h5 code, .markdown-body h6 tt, .markdown-body h6 code {\n\t\tfont-size: inherit;\n}\n.markdown-body h1 {\n\t\tcolor: #000000;\n\t\tfont-size: 28px;\n}\n.markdown-body h2 {\n\t\tborder-bottom: 1px solid #CCCCCC;\n\t\tcolor: #000000;\n\t\tfont-size: 24px;\n}\n.markdown-body h3 {\n\t\tfont-size: 18px;\n}\n.markdown-body h4 {\n\t\tfont-size: 16px;\n}\n.markdown-body h5 {\n\t\tfont-size: 14px;\n}\n.markdown-body h6 {\n\t\tcolor: #777777;\n\t\tfont-size: 14px;\n}\n.markdown-body p, .markdown-body blockquote, .markdown-body ul, .markdown-body ol, .markdown-body dl, .markdown-body table, .markdown-body pre {\n\t\tmargin: 15px 0;\n}\n.markdown-body hr {\n\t\tborder: 0 none;\n\t\tcolor: #CCCCCC;\n\t\theight: 4px;\n\t\tpadding: 0;\n}\n.markdown-body > h2:first-child, .markdown-body > h1:first-child, .markdown-body > h1:first-child + h2, .markdown-body > h3:first-child, .markdown-body > h4:first-child, .markdown-body > h5:first-child, .markdown-body > h6:first-child {\n\t\tmargin-top: 0;\n\t\tpadding-top: 0;\n}\n.markdown-body a:first-child h1, .markdown-body a:first-child h2, .markdown-body a:first-child h3, .markdown-body a:first-child h4, .markdown-body a:first-child h5, .markdown-body a:first-child h6 {\n\t\tmargin-top: 0;\n\t\tpadding-top: 0;\n}\n.markdown-body h1 + p, .markdown-body h2 + p, .markdown-body h3 + p, .markdown-body h4 + p, .markdown-body h5 + p, .markdown-body h6 + p {\n\t\tmargin-top: 0;\n}\n.markdown-body li p.first {\n\t\tdisplay: inline-block;\n}\n.markdown-body ul, .markdown-body ol {\n\t\tpadding-left: 30px;\n}\n.markdown-body ul.no-list, .markdown-body ol.no-list {\n\t\tlist-style-type: none;\n\t\tpadding: 0;\n}\n.markdown-body ul li > *:first-child, .markdown-body ol li > *:first-child {\n\t\tmargin-top: 0;\n}\n.markdown-body ul ul, .markdown-body ul ol, .markdown-body ol ol, .markdown-body ol ul {\n\t\tmargin-bottom: 0;\n}\n.markdown-body dl {\n\t\tpadding: 0;\n}\n.markdown-body dl dt {\n\t\tfont-size: 14px;\n\t\tfont-style: italic;\n\t\tfont-weight: bold;\n\t\tmargin: 15px 0 5px;\n\t\tpadding: 0;\n}\n.markdown-body dl dt:first-child {\n\t\tpadding: 0;\n}\n.markdown-body dl dt > *:first-child {\n\t\tmargin-top: 0;\n}\n.markdown-body dl dt > *:last-child {\n\t\tmargin-bottom: 0;\n}\n.markdown-body dl dd {\n\t\tmargin: 0 0 15px;\n\t\tpadding: 0 15px;\n}\n.markdown-body dl dd > *:first-child {\n\t\tmargin-top: 0;\n}\n.markdown-body dl dd > *:last-child {\n\t\tmargin-bottom: 0;\n}\n.markdown-body blockquote {\n\t\tborder-left: 4px solid #DDDDDD;\n\t\tcolor: #777777;\n\t\tpadding: 0 15px;\n}\n.markdown-body blockquote > *:first-child {\n\t\tmargin-top: 0;\n}\n.markdown-body blockquote > *:last-child {\n\t\tmargin-bottom: 0;\n}\n.markdown-body table th {\n\t\tfont-weight: bold;\n}\n.markdown-body table th, .markdown-body table td {\n\t\tborder: 1px solid #CCCCCC;\n\t\tpadding: 6px 13px;\n}\n.markdown-body table tr {\n\t\tbackground-color: #FFFFFF;\n\t\tborder-top: 1px solid #CCCCCC;\n}\n.markdown-body table tr:nth-child(2n) {\n\t\tbackground-color: #F8F8F8;\n}\n.markdown-body img {\n\t\tmax-width: 100%;\n}\n.markdown-body span.frame {\n\t\tdisplay: block;\n\t\toverflow: hidden;\n}\n.markdown-body span.frame > span {\n\t\tborder: 1px solid #DDDDDD;\n\t\tdisplay: block;\n\t\tfloat: left;\n\t\tmargin: 13px 0 0;\n\t\toverflow: hidden;\n\t\tpadding: 7px;\n\t\twidth: auto;\n}\n.markdown-body span.frame span img {\n\t\tdisplay: block;\n\t\tfloat: left;\n}\n.markdown-body span.frame span span {\n\t\tclear: both;\n\t\tcolor: #333333;\n\t\tdisplay: block;\n\t\tpadding: 5px 0 0;\n}\n.markdown-body span.align-center {\n\t\tclear: both;\n\t\tdisplay: block;\n\t\toverflow: hidden;\n}\n.markdown-body span.align-center > span {\n\t\tdisplay: block;\n\t\tmargin: 13px auto 0;\n\t\toverflow: hidden;\n\t\ttext-align: center;\n}\n.markdown-body span.align-center span img {\n\t\tmargin: 0 auto;\n\t\ttext-align: center;\n}\n.markdown-body span.align-right {\n\t\tclear: both;\n\t\tdisplay: block;\n\t\toverflow: hidden;\n}\n.markdown-body span.align-right > span {\n\t\tdisplay: block;\n\t\tmargin: 13px 0 0;\n\t\toverflow: hidden;\n\t\ttext-align: right;\n}\n.markdown-body span.align-right span img {\n\t\tmargin: 0;\n\t\ttext-align: right;\n}\n.markdown-body span.float-left {\n\t\tdisplay: block;\n\t\tfloat: left;\n\t\tmargin-right: 13px;\n\t\toverflow: hidden;\n}\n.markdown-body span.float-left span {\n\t\tmargin: 13px 0 0;\n}\n.markdown-body span.float-right {\n\t\tdisplay: block;\n\t\tfloat: right;\n\t\tmargin-left: 13px;\n\t\toverflow: hidden;\n}\n.markdown-body span.float-right > span {\n\t\tdisplay: block;\n\t\tmargin: 13px auto 0;\n\t\toverflow: hidden;\n\t\ttext-align: right;\n}\n.markdown-body code, .markdown-body tt {\n\t\tfont-family: Consolas, \"Liberation Mono\", Courier, monospace;\n\t\tbackground-color: #F8F8F8;\n\t\tborder: 1px solid #EAEAEA;\n\t\tborder-radius: 3px 3px 3px 3px;\n\t\tmargin: 0 2px;\n\t\tpadding: 0 5px;\n\t\twhite-space: nowrap;\n}\n.markdown-body pre > code {\n\t\tfont-size: 14px;\n\t\tbackground: none repeat scroll 0 0 transparent;\n\t\tborder: medium none;\n\t\tmargin: 0;\n\t\tpadding: 0;\n\t\twhite-space: pre;\n}\n.markdown-body .highlight pre, .markdown-body pre {\n\t\tbackground-color: #F8F8F8;\n\t\tborder: 1px solid #CCCCCC;\n\t\tborder-radius: 3px 3px 3px 3px;\n\t\tfont-size: 13px;\n\t\tline-height: 19px;\n\t\toverflow: auto;\n\t\tpadding: 6px 10px;\n}\n.markdown-body pre code, .markdown-body pre tt {\n\t\tbackground-color: transparent;\n\t\tborder: medium none;\n}\n\t\t<\/style>\n\t<\/head>\n\t<body>\n\t<div class=\"markdown-body\">{{.Content}}<\/div>\n\t<\/body>\n<\/html>\n`<|endoftext|>"}
{"text":"<commit_before><commit_msg>refactor: Simplify condition<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 The Kubernetes Authors.\n\/\/ SPDX-License-Identifier: Apache-2.0\n\npackage krusty_test\n\nimport (\n\t\"testing\"\n\n\tkusttest_test \"sigs.k8s.io\/kustomize\/api\/testutils\/kusttest\"\n)\n\nfunc TestValidatingWebhookCombinedNamespaces(t *testing.T) {\n  th := kusttest_test.MakeHarness(t)\n  th.WriteK(\"base\", `\nresources:\n- service.yaml\n- validatingwebhook.yaml\n`)\n  th.WriteF(\"base\/service.yaml\", `\napiVersion: v1\nkind: Service\nmetadata:\n  name: admission\n  namespace: base-namespace\nspec:\n  type: ClusterIP\n  ports:\n    - name: https-webhook\n      port: 443\n      targetPort: webhook\n`)\n    th.WriteF(\"base\/validatingwebhook.yaml\", `\napiVersion: admissionregistration.k8s.io\/v1\nkind: ValidatingWebhookConfiguration\nmetadata:\n  name: validatingwebhook\nwebhooks:\n  - name: validate\n    matchPolicy: Equivalent\n    rules:\n      - apiGroups:\n          - networking.k8s.io\n        apiVersions:\n          - v1beta1\n        operations:\n          - CREATE\n          - UPDATE\n        resources:\n          - ingresses\n    failurePolicy: Fail\n    sideEffects: None\n    admissionReviewVersions:\n      - v1\n      - v1beta1\n    clientConfig:\n      service:\n        namespace: base-namespace\n        name: admission\n        path: \/networking\/v1beta1\/ingresses\n`)\n  th.WriteK(\"overlay\", `\nnamespace: merge-namespace\nresources:\n- ..\/base\npatchesStrategicMerge:\n- validatingwebhookdelete.yaml\n`)\n    th.WriteF(\"overlay\/validatingwebhookdelete.yaml\", `\napiVersion: admissionregistration.k8s.io\/v1\nkind: ValidatingWebhookConfiguration\nmetadata:\n  name: validatingwebhook\n$patch: delete\n`)\n\tth.WriteK(\"combined\", `\nresources:\n- ..\/base\n- ..\/overlay\n`)\n\tm := th.Run(\"combined\", th.MakeDefaultOptions())\n\tth.AssertActualEqualsExpected(m, `\napiVersion: v1\nkind: Service\nmetadata:\n  name: admission\n  namespace: base-namespace\nspec:\n  ports:\n  - name: https-webhook\n    port: 443\n    targetPort: webhook\n  type: ClusterIP\n---\napiVersion: admissionregistration.k8s.io\/v1\nkind: ValidatingWebhookConfiguration\nmetadata:\n  name: validatingwebhook\nwebhooks:\n- admissionReviewVersions:\n  - v1\n  - v1beta1\n  clientConfig:\n    service:\n      name: admission\n      namespace: base-namespace\n      path: \/networking\/v1beta1\/ingresses\n  failurePolicy: Fail\n  matchPolicy: Equivalent\n  name: validate\n  rules:\n  - apiGroups:\n    - networking.k8s.io\n    apiVersions:\n    - v1beta1\n    operations:\n    - CREATE\n    - UPDATE\n    resources:\n    - ingresses\n  sideEffects: None\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: admission\n  namespace: merge-namespace\nspec:\n  ports:\n  - name: https-webhook\n    port: 443\n    targetPort: webhook\n  type: ClusterIP\n`)\n}\n\n\n<commit_msg>added comment referring test to issue 3732<commit_after>\/\/ Copyright 2019 The Kubernetes Authors.\n\/\/ SPDX-License-Identifier: Apache-2.0\n\npackage krusty_test\n\nimport (\n\t\"testing\"\n\n\tkusttest_test \"sigs.k8s.io\/kustomize\/api\/testutils\/kusttest\"\n)\n\n\/\/ Reproduce issue #3732\nfunc TestValidatingWebhookCombinedNamespaces(t *testing.T) {\n  th := kusttest_test.MakeHarness(t)\n  th.WriteK(\"base\", `\nresources:\n- service.yaml\n- validatingwebhook.yaml\n`)\n  th.WriteF(\"base\/service.yaml\", `\napiVersion: v1\nkind: Service\nmetadata:\n  name: admission\n  namespace: base-namespace\nspec:\n  type: ClusterIP\n  ports:\n    - name: https-webhook\n      port: 443\n      targetPort: webhook\n`)\n    th.WriteF(\"base\/validatingwebhook.yaml\", `\napiVersion: admissionregistration.k8s.io\/v1\nkind: ValidatingWebhookConfiguration\nmetadata:\n  name: validatingwebhook\nwebhooks:\n  - name: validate\n    matchPolicy: Equivalent\n    rules:\n      - apiGroups:\n          - networking.k8s.io\n        apiVersions:\n          - v1beta1\n        operations:\n          - CREATE\n          - UPDATE\n        resources:\n          - ingresses\n    failurePolicy: Fail\n    sideEffects: None\n    admissionReviewVersions:\n      - v1\n      - v1beta1\n    clientConfig:\n      service:\n        namespace: base-namespace\n        name: admission\n        path: \/networking\/v1beta1\/ingresses\n`)\n  th.WriteK(\"overlay\", `\nnamespace: merge-namespace\nresources:\n- ..\/base\npatchesStrategicMerge:\n- validatingwebhookdelete.yaml\n`)\n    th.WriteF(\"overlay\/validatingwebhookdelete.yaml\", `\napiVersion: admissionregistration.k8s.io\/v1\nkind: ValidatingWebhookConfiguration\nmetadata:\n  name: validatingwebhook\n$patch: delete\n`)\n\tth.WriteK(\"combined\", `\nresources:\n- ..\/base\n- ..\/overlay\n`)\n\tm := th.Run(\"combined\", th.MakeDefaultOptions())\n\tth.AssertActualEqualsExpected(m, `\napiVersion: v1\nkind: Service\nmetadata:\n  name: admission\n  namespace: base-namespace\nspec:\n  ports:\n  - name: https-webhook\n    port: 443\n    targetPort: webhook\n  type: ClusterIP\n---\napiVersion: admissionregistration.k8s.io\/v1\nkind: ValidatingWebhookConfiguration\nmetadata:\n  name: validatingwebhook\nwebhooks:\n- admissionReviewVersions:\n  - v1\n  - v1beta1\n  clientConfig:\n    service:\n      name: admission\n      namespace: base-namespace\n      path: \/networking\/v1beta1\/ingresses\n  failurePolicy: Fail\n  matchPolicy: Equivalent\n  name: validate\n  rules:\n  - apiGroups:\n    - networking.k8s.io\n    apiVersions:\n    - v1beta1\n    operations:\n    - CREATE\n    - UPDATE\n    resources:\n    - ingresses\n  sideEffects: None\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: admission\n  namespace: merge-namespace\nspec:\n  ports:\n  - name: https-webhook\n    port: 443\n    targetPort: webhook\n  type: ClusterIP\n`)\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Code generated by goagen v1.1.0, command line:\n\/\/ $ goagen\n\/\/ --design=github.com\/tikasan\/eventory\/design\n\/\/ --out=$(GOPATH)\n\/\/ --version=v1.1.0-dirty\n\/\/\n\/\/ API \"eventory\": Models\n\/\/\n\/\/ The content of this file is auto-generated, DO NOT MODIFY\n\npackage models\n\nimport (\n\t\"time\"\n\n\t\"github.com\/goadesign\/goa\"\n\t\"github.com\/jinzhu\/gorm\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ ユーザーのキープ状態\ntype UserFollowEvent struct {\n\tID             int `gorm:\"primary_key\"` \/\/ primary key\n\tBatchProcessed bool\n\tEventID        int \/\/ Belongs To Event\n\tStatus         string\n\tUserID         int        \/\/ Belongs To User\n\tCreatedAt      time.Time  \/\/ timestamp\n\tDeletedAt      *time.Time \/\/ nullable timestamp (soft delete)\n\tUpdatedAt      time.Time  \/\/ timestamp\n\tEvent          Event\n\tUser           User\n}\n\n\/\/ TableName overrides the table name settings in Gorm to force a specific table name\n\/\/ in the database.\nfunc (m UserFollowEvent) TableName() string {\n\treturn \"user_follow_events\"\n\n}\n\n\/\/ UserFollowEventDB is the implementation of the storage interface for\n\/\/ UserFollowEvent.\ntype UserFollowEventDB struct {\n\tDb *gorm.DB\n}\n\n\/\/ NewUserFollowEventDB creates a new storage type.\nfunc NewUserFollowEventDB(db *gorm.DB) *UserFollowEventDB {\n\treturn &UserFollowEventDB{Db: db}\n}\n\n\/\/ DB returns the underlying database.\nfunc (m *UserFollowEventDB) DB() interface{} {\n\treturn m.Db\n}\n\n\/\/ UserFollowEventStorage represents the storage interface.\ntype UserFollowEventStorage interface {\n\tDB() interface{}\n\tList(ctx context.Context) ([]*UserFollowEvent, error)\n\tGet(ctx context.Context, id int) (*UserFollowEvent, error)\n\tAdd(ctx context.Context, userfollowevent *UserFollowEvent) error\n\tUpdate(ctx context.Context, userfollowevent *UserFollowEvent) error\n\tDelete(ctx context.Context, id int) error\n}\n\n\/\/ TableName overrides the table name settings in Gorm to force a specific table name\n\/\/ in the database.\nfunc (m *UserFollowEventDB) TableName() string {\n\treturn \"user_follow_events\"\n\n}\n\n\/\/ Belongs To Relationships\n\n\/\/ UserFollowEventFilterByEvent is a gorm filter for a Belongs To relationship.\nfunc UserFollowEventFilterByEvent(eventID int, originaldb *gorm.DB) func(db *gorm.DB) *gorm.DB {\n\n\tif eventID > 0 {\n\n\t\treturn func(db *gorm.DB) *gorm.DB {\n\t\t\treturn db.Where(\"event_id = ?\", eventID)\n\n\t\t}\n\t}\n\treturn func(db *gorm.DB) *gorm.DB { return db }\n}\n\n\/\/ Belongs To Relationships\n\n\/\/ UserFollowEventFilterByUser is a gorm filter for a Belongs To relationship.\nfunc UserFollowEventFilterByUser(userID int, originaldb *gorm.DB) func(db *gorm.DB) *gorm.DB {\n\n\tif userID > 0 {\n\n\t\treturn func(db *gorm.DB) *gorm.DB {\n\t\t\treturn db.Where(\"user_id = ?\", userID)\n\n\t\t}\n\t}\n\treturn func(db *gorm.DB) *gorm.DB { return db }\n}\n\n\/\/ CRUD Functions\n\n\/\/ Get returns a single UserFollowEvent as a Database Model\n\/\/ This is more for use internally, and probably not what you want in  your controllers\n\nfunc (m *UserFollowEventDB) Get(ctx context.Context, id int) (*UserFollowEvent, error) {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"get\"}, time.Now())\n\n\tvar native UserFollowEvent\n\terr := m.Db.Table(m.TableName()).Where(\"id = ?\", id).Find(&native).Error\n\tif err == gorm.ErrRecordNotFound {\n\t\treturn nil, err\n\t}\n\n\treturn &native, err\n}\n\nfunc (m *UserFollowEventDB) GetByUserAndEvent(ctx context.Context, userID int, eventID int) (*UserFollowEvent, error) {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"get\"}, time.Now())\n\n\tvar native UserFollowEvent\n\terr := m.Db.Table(m.TableName()).Where(\"user_id = ?\", userID).Where(\"event_id = ?\", eventID).Find(&native).Error\n\tif err == gorm.ErrRecordNotFound {\n\t\treturn nil, err\n\t}\n\treturn &native, err\n}\n\n\/\/ List returns an array of UserFollowEvent\nfunc (m *UserFollowEventDB) List(ctx context.Context) ([]*UserFollowEvent, error) {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"list\"}, time.Now())\n\n\tvar objs []*UserFollowEvent\n\terr := m.Db.Table(m.TableName()).Find(&objs).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn nil, err\n\t}\n\n\treturn objs, nil\n}\n\n\/\/ Add creates a new record.\nfunc (m *UserFollowEventDB) Add(ctx context.Context, model *UserFollowEvent) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"add\"}, time.Now())\n\n\terr := m.Db.Create(model).Error\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error adding UserFollowEvent\", \"error\", err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ User Follow Genre\nfunc (m *UserFollowEventDB) UserFollowEvent(ctx context.Context, model *UserFollowEvent) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowGenre\", \"follow\"}, time.Now())\n\n\t\/\/ 過去に一度でもフォロー操作をしたことがあるか\n\tufe, err := m.GetByUserAndEvent(ctx, model.UserID, model.EventID)\n\tif err != nil {\n\t\t\/\/ レコードが存在しないので、フォローレコードを追加する\n\t\terr := m.Db.Create(model).Error\n\t\tif err != nil {\n\t\t\tgoa.LogError(ctx, \"error adding UserFollowGenre\", \"error\", err.Error())\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ 過去に使ったレコードからdeleted_atをnullにして復活させる\n\tufe.DeletedAt = nil\n\terr = m.Db.Model(ufe).Updates(model).Error\n\treturn nil\n}\n\nfunc (m *UserFollowEventDB) UserUnfollowEvent(ctx context.Context, model *UserFollowEvent) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowGenre\", \"unfollow\"}, time.Now())\n\n\tvar obj UserFollowGenre\n\terr := m.Db.Delete(&obj, m.Db.Where(\"user_id = ?\", model.UserID).Where(\"genre_id = ?\", model.EventID)).Error\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error deleting UserFollowGenre\", \"error\", err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Update modifies a single record.\nfunc (m *UserFollowEventDB) Update(ctx context.Context, model *UserFollowEvent) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"update\"}, time.Now())\n\n\tobj, err := m.Get(ctx, model.UserID)\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error updating UserFollowEvent\", \"error\", err.Error())\n\t\treturn err\n\t}\n\terr = m.Db.Model(obj).Updates(model).Error\n\n\treturn err\n}\n\n\/\/ Upsert modifies a single record.\nfunc (m *UserFollowEventDB) Upsert(ctx context.Context, model *UserFollowEvent) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"update\"}, time.Now())\n\n\terr := m.Db.Create(model).Error\n\tif err != nil {\n\t\tobj, err := m.GetByUserAndEvent(ctx, model.UserID, model.EventID)\n\t\tif err != nil {\n\t\t\tgoa.LogError(ctx, \"error upsert UserFollowEvent\", \"error\", err.Error())\n\t\t\treturn err\n\t\t}\n\t\terr = m.Db.Model(obj).Updates(model).Error\n\t}\n\treturn err\n}\n\n\/\/ Delete removes a single record.\nfunc (m *UserFollowEventDB) Delete(ctx context.Context, id int) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"delete\"}, time.Now())\n\n\tvar obj UserFollowEvent\n\n\terr := m.Db.Delete(&obj, id).Error\n\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error deleting UserFollowEvent\", \"error\", err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *UserFollowEventDB) FixUserFollow(ctx context.Context) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"delete\"}, time.Now())\n\n\toneAgo := time.Now()\n\toneAgo = oneAgo.AddDate(0, 0, -1)\n\tmodel := UserFollowEvent{}\n\tmodel.BatchProcessed = true\n\terr := m.Db.Table(m.TableName()).Updates(model).Where(\"created_at > ?\", oneAgo).Error\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error updating UserFollowEvent\", \"error\", err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>whereが効くように書き直した<commit_after>\/\/ Code generated by goagen v1.1.0, command line:\n\/\/ $ goagen\n\/\/ --design=github.com\/tikasan\/eventory\/design\n\/\/ --out=$(GOPATH)\n\/\/ --version=v1.1.0-dirty\n\/\/\n\/\/ API \"eventory\": Models\n\/\/\n\/\/ The content of this file is auto-generated, DO NOT MODIFY\n\npackage models\n\nimport (\n\t\"time\"\n\n\t\"github.com\/goadesign\/goa\"\n\t\"github.com\/jinzhu\/gorm\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ ユーザーのキープ状態\ntype UserFollowEvent struct {\n\tID             int `gorm:\"primary_key\"` \/\/ primary key\n\tBatchProcessed bool\n\tEventID        int \/\/ Belongs To Event\n\tStatus         string\n\tUserID         int        \/\/ Belongs To User\n\tCreatedAt      time.Time  \/\/ timestamp\n\tDeletedAt      *time.Time \/\/ nullable timestamp (soft delete)\n\tUpdatedAt      time.Time  \/\/ timestamp\n\tEvent          Event\n\tUser           User\n}\n\n\/\/ TableName overrides the table name settings in Gorm to force a specific table name\n\/\/ in the database.\nfunc (m UserFollowEvent) TableName() string {\n\treturn \"user_follow_events\"\n\n}\n\n\/\/ UserFollowEventDB is the implementation of the storage interface for\n\/\/ UserFollowEvent.\ntype UserFollowEventDB struct {\n\tDb *gorm.DB\n}\n\n\/\/ NewUserFollowEventDB creates a new storage type.\nfunc NewUserFollowEventDB(db *gorm.DB) *UserFollowEventDB {\n\treturn &UserFollowEventDB{Db: db}\n}\n\n\/\/ DB returns the underlying database.\nfunc (m *UserFollowEventDB) DB() interface{} {\n\treturn m.Db\n}\n\n\/\/ UserFollowEventStorage represents the storage interface.\ntype UserFollowEventStorage interface {\n\tDB() interface{}\n\tList(ctx context.Context) ([]*UserFollowEvent, error)\n\tGet(ctx context.Context, id int) (*UserFollowEvent, error)\n\tAdd(ctx context.Context, userfollowevent *UserFollowEvent) error\n\tUpdate(ctx context.Context, userfollowevent *UserFollowEvent) error\n\tDelete(ctx context.Context, id int) error\n}\n\n\/\/ TableName overrides the table name settings in Gorm to force a specific table name\n\/\/ in the database.\nfunc (m *UserFollowEventDB) TableName() string {\n\treturn \"user_follow_events\"\n\n}\n\n\/\/ Belongs To Relationships\n\n\/\/ UserFollowEventFilterByEvent is a gorm filter for a Belongs To relationship.\nfunc UserFollowEventFilterByEvent(eventID int, originaldb *gorm.DB) func(db *gorm.DB) *gorm.DB {\n\n\tif eventID > 0 {\n\n\t\treturn func(db *gorm.DB) *gorm.DB {\n\t\t\treturn db.Where(\"event_id = ?\", eventID)\n\n\t\t}\n\t}\n\treturn func(db *gorm.DB) *gorm.DB { return db }\n}\n\n\/\/ Belongs To Relationships\n\n\/\/ UserFollowEventFilterByUser is a gorm filter for a Belongs To relationship.\nfunc UserFollowEventFilterByUser(userID int, originaldb *gorm.DB) func(db *gorm.DB) *gorm.DB {\n\n\tif userID > 0 {\n\n\t\treturn func(db *gorm.DB) *gorm.DB {\n\t\t\treturn db.Where(\"user_id = ?\", userID)\n\n\t\t}\n\t}\n\treturn func(db *gorm.DB) *gorm.DB { return db }\n}\n\n\/\/ CRUD Functions\n\n\/\/ Get returns a single UserFollowEvent as a Database Model\n\/\/ This is more for use internally, and probably not what you want in  your controllers\n\nfunc (m *UserFollowEventDB) Get(ctx context.Context, id int) (*UserFollowEvent, error) {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"get\"}, time.Now())\n\n\tvar native UserFollowEvent\n\terr := m.Db.Table(m.TableName()).Where(\"id = ?\", id).Find(&native).Error\n\tif err == gorm.ErrRecordNotFound {\n\t\treturn nil, err\n\t}\n\n\treturn &native, err\n}\n\nfunc (m *UserFollowEventDB) GetByUserAndEvent(ctx context.Context, userID int, eventID int) (*UserFollowEvent, error) {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"get\"}, time.Now())\n\n\tvar native UserFollowEvent\n\terr := m.Db.Table(m.TableName()).Where(\"user_id = ?\", userID).Where(\"event_id = ?\", eventID).Find(&native).Error\n\tif err == gorm.ErrRecordNotFound {\n\t\treturn nil, err\n\t}\n\treturn &native, err\n}\n\n\/\/ List returns an array of UserFollowEvent\nfunc (m *UserFollowEventDB) List(ctx context.Context) ([]*UserFollowEvent, error) {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"list\"}, time.Now())\n\n\tvar objs []*UserFollowEvent\n\terr := m.Db.Table(m.TableName()).Find(&objs).Error\n\tif err != nil && err != gorm.ErrRecordNotFound {\n\t\treturn nil, err\n\t}\n\n\treturn objs, nil\n}\n\n\/\/ Add creates a new record.\nfunc (m *UserFollowEventDB) Add(ctx context.Context, model *UserFollowEvent) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"add\"}, time.Now())\n\n\terr := m.Db.Create(model).Error\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error adding UserFollowEvent\", \"error\", err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ User Follow Genre\nfunc (m *UserFollowEventDB) UserFollowEvent(ctx context.Context, model *UserFollowEvent) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowGenre\", \"follow\"}, time.Now())\n\n\t\/\/ 過去に一度でもフォロー操作をしたことがあるか\n\tufe, err := m.GetByUserAndEvent(ctx, model.UserID, model.EventID)\n\tif err != nil {\n\t\t\/\/ レコードが存在しないので、フォローレコードを追加する\n\t\terr := m.Db.Create(model).Error\n\t\tif err != nil {\n\t\t\tgoa.LogError(ctx, \"error adding UserFollowGenre\", \"error\", err.Error())\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ 過去に使ったレコードからdeleted_atをnullにして復活させる\n\tufe.DeletedAt = nil\n\terr = m.Db.Model(ufe).Updates(model).Error\n\treturn nil\n}\n\nfunc (m *UserFollowEventDB) UserUnfollowEvent(ctx context.Context, model *UserFollowEvent) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowGenre\", \"unfollow\"}, time.Now())\n\n\tvar obj UserFollowGenre\n\terr := m.Db.Delete(&obj, m.Db.Where(\"user_id = ?\", model.UserID).Where(\"genre_id = ?\", model.EventID)).Error\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error deleting UserFollowGenre\", \"error\", err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Update modifies a single record.\nfunc (m *UserFollowEventDB) Update(ctx context.Context, model *UserFollowEvent) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"update\"}, time.Now())\n\n\tobj, err := m.Get(ctx, model.UserID)\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error updating UserFollowEvent\", \"error\", err.Error())\n\t\treturn err\n\t}\n\terr = m.Db.Model(obj).Updates(model).Error\n\n\treturn err\n}\n\n\/\/ Upsert modifies a single record.\nfunc (m *UserFollowEventDB) Upsert(ctx context.Context, model *UserFollowEvent) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"update\"}, time.Now())\n\n\terr := m.Db.Create(model).Error\n\tif err != nil {\n\t\tobj, err := m.GetByUserAndEvent(ctx, model.UserID, model.EventID)\n\t\tif err != nil {\n\t\t\tgoa.LogError(ctx, \"error upsert UserFollowEvent\", \"error\", err.Error())\n\t\t\treturn err\n\t\t}\n\t\terr = m.Db.Model(obj).Updates(model).Error\n\t}\n\treturn err\n}\n\n\/\/ Delete removes a single record.\nfunc (m *UserFollowEventDB) Delete(ctx context.Context, id int) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"delete\"}, time.Now())\n\n\tvar obj UserFollowEvent\n\n\terr := m.Db.Delete(&obj, id).Error\n\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error deleting UserFollowEvent\", \"error\", err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *UserFollowEventDB) FixUserFollow(ctx context.Context) error {\n\tdefer goa.MeasureSince([]string{\"goa\", \"db\", \"userFollowEvent\", \"delete\"}, time.Now())\n\n\toneAgo := time.Now()\n\toneAgo = oneAgo.AddDate(0, 0, -1)\n\tmodel := UserFollowEvent{}\n\tmodel.BatchProcessed = true\n\terr := m.Db.Table(m.TableName()).Where(\"updated_at < ?\", oneAgo.Format(\"2006-01-02 15:04:05\")).Updates(model).Error\n\tif err != nil {\n\t\tgoa.LogError(ctx, \"error updating UserFollowEvent\", \"error\", err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package base\n\nimport (\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"testing\"\n)\n\nfunc TestEncodeMD5(t *testing.T) {\n\tif checksum := EncodeMD5(\"foobar\"); checksum != \"3858f62230ac3c915f300c664312c63f\" {\n\t\tt.Errorf(\"got the wrong md5sum for string foobar: %s\", checksum)\n\t}\n\n}\n\nfunc TestEncodeSha1(t *testing.T) {\n\tif checksum := EncodeSha1(\"foobar\"); checksum != \"8843d7f92416211de9ebb963ff4ce28125932878\" {\n\t\tt.Errorf(\"got the wrong sha1sum for string foobar: %s\", checksum)\n\t}\n}\n\nfunc TestShortSha(t *testing.T) {\n\tif result := ShortSha(\"veryverylong\"); result != \"veryverylo\" {\n\t\tt.Errorf(\"got the wrong sha1sum for string foobar: %s\", result)\n\t}\n}\n\n\/\/ TODO: Test DetectEncoding()\n\nfunc TestBasicAuthDecode(t *testing.T) {\n\tif _, _, err := BasicAuthDecode(\"?\"); err.Error() != \"illegal base64 data at input byte 0\" {\n\t\tt.Errorf(\"BasicAuthDecode should fail due to illeagl data: %v\", err)\n\t}\n\n\tuser, pass, err := BasicAuthDecode(\"Zm9vOmJhcg==\")\n\tif err != nil {\n\t\tt.Errorf(\"err should be nil but is: %v\", err)\n\t}\n\tif user != \"foo\" {\n\t\tt.Errorf(\"user should be foo but is: %s\", user)\n\t}\n\tif pass != \"bar\" {\n\t\tt.Errorf(\"pass should be foo but is: %s\", pass)\n\t}\n}\n\nfunc TestBasicAuthEncode(t *testing.T) {\n\tif auth := BasicAuthEncode(\"foo\", \"bar\"); auth != \"Zm9vOmJhcg==\" {\n\t\tt.Errorf(\"auth should be Zm9vOmJhcg== but is: %s\", auth)\n\t}\n}\n\nfunc TestGetRandomString(t *testing.T) {\n\tif len(GetRandomString(4)) != 4 {\n\t\tt.Error(\"expected GetRandomString to be of len 4\")\n\t}\n}\n\n\/\/ TODO: Test PBKDF2()\n\/\/ TODO: Test VerifyTimeLimitCode()\n\/\/ TODO: Test CreateTimeLimitCode()\n\nfunc TestHashEmail(t *testing.T) {\n\tif hash := HashEmail(\"lunny@gitea.io\"); hash != \"1b6d0c0e124d47ded12cd7115addeb11\" {\n\t\tt.Errorf(\"unexpected email hash: %s\", hash)\n\t}\n}\n\n\/\/ TODO: AvatarLink()\n\/\/ TODO: computeTimeDiff()\n\/\/ TODO: TimeSincePro()\n\/\/ TODO: timeSince()\n\/\/ TODO: RawTimeSince()\n\/\/ TODO: TimeSince()\n\/\/ TODO: logn()\n\/\/ TODO: humanateBytes()\n\nfunc TestFileSize(t *testing.T) {\n\tvar size int64\n\tsize = 512\n\tassert.Equal(t, \"512B\", FileSize(size))\n\tsize = size * 1024\n\tassert.Equal(t, \"512KB\", FileSize(size))\n\tsize = size * 1024\n\tassert.Equal(t, \"512MB\", FileSize(size))\n\tsize = size * 1024\n\tassert.Equal(t, \"512GB\", FileSize(size))\n\tsize = size * 1024\n\tassert.Equal(t, \"512TB\", FileSize(size))\n\tsize = size * 1024\n\tassert.Equal(t, \"512PB\", FileSize(size))\n\t\/\/size = size * 1024 TODO: Fix bug for EB\n\t\/\/assert.Equal(t, \"512EB\", FileSize(size))\n}\n\n\/\/ TODO: Subtract()\n\/\/ TODO: EllipsisString()\n\/\/ TODO: TruncateString()\n\/\/ TODO: StringsToInt64s()\n\/\/ TODO: Int64sToStrings()\n\/\/ TODO: Int64sToMap()\n\/\/ TODO: IsLetter()\n\/\/ TODO: IsTextFile()\n\/\/ TODO: IsImageFile()\n\/\/ TODO: IsPDFFile()\n<commit_msg>Use testify\/assert for all tests in tool_test.go<commit_after>package base\n\nimport (\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"testing\"\n)\n\nfunc TestEncodeMD5(t *testing.T) {\n\tassert.Equal(t, \"3858f62230ac3c915f300c664312c63f\", EncodeMD5(\"foobar\"))\n}\n\nfunc TestEncodeSha1(t *testing.T) {\n\tassert.Equal(t, \"8843d7f92416211de9ebb963ff4ce28125932878\", EncodeSha1(\"foobar\"))\n}\n\nfunc TestShortSha(t *testing.T) {\n\tassert.Equal(t, \"veryverylo\", ShortSha(\"veryverylong\"))\n}\n\n\/\/ TODO: Test DetectEncoding()\n\nfunc TestBasicAuthDecode(t *testing.T) {\n\t_, _, err := BasicAuthDecode(\"?\")\n\tassert.Equal(t, \"illegal base64 data at input byte 0\", err.Error())\n\n\tuser, pass, err := BasicAuthDecode(\"Zm9vOmJhcg==\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"foo\", user)\n\tassert.Equal(t, \"bar\", pass)\n}\n\nfunc TestBasicAuthEncode(t *testing.T) {\n\tassert.Equal(t, \"Zm9vOmJhcg==\", BasicAuthEncode(\"foo\", \"bar\"))\n}\n\nfunc TestGetRandomString(t *testing.T) {\n\tassert.Len(t, GetRandomString(4), 4)\n}\n\n\/\/ TODO: Test PBKDF2()\n\/\/ TODO: Test VerifyTimeLimitCode()\n\/\/ TODO: Test CreateTimeLimitCode()\n\nfunc TestHashEmail(t *testing.T) {\n\tassert.Equal(t, \"d41d8cd98f00b204e9800998ecf8427e\", HashEmail(\"\"))\n\tassert.Equal(t, \"353cbad9b58e69c96154ad99f92bedc7\", HashEmail(\"gitea@example.com\"))\n}\n\n\/\/ TODO: AvatarLink()\n\/\/ TODO: computeTimeDiff()\n\/\/ TODO: TimeSincePro()\n\/\/ TODO: timeSince()\n\/\/ TODO: RawTimeSince()\n\/\/ TODO: TimeSince()\n\/\/ TODO: logn()\n\/\/ TODO: humanateBytes()\n\nfunc TestFileSize(t *testing.T) {\n\tvar size int64\n\tsize = 512\n\tassert.Equal(t, \"512B\", FileSize(size))\n\tsize = size * 1024\n\tassert.Equal(t, \"512KB\", FileSize(size))\n\tsize = size * 1024\n\tassert.Equal(t, \"512MB\", FileSize(size))\n\tsize = size * 1024\n\tassert.Equal(t, \"512GB\", FileSize(size))\n\tsize = size * 1024\n\tassert.Equal(t, \"512TB\", FileSize(size))\n\tsize = size * 1024\n\tassert.Equal(t, \"512PB\", FileSize(size))\n\t\/\/size = size * 1024 TODO: Fix bug for EB\n\t\/\/assert.Equal(t, \"512EB\", FileSize(size))\n}\n\n\/\/ TODO: Subtract()\n\/\/ TODO: EllipsisString()\n\/\/ TODO: TruncateString()\n\/\/ TODO: StringsToInt64s()\n\/\/ TODO: Int64sToStrings()\n\/\/ TODO: Int64sToMap()\n\/\/ TODO: IsLetter()\n\/\/ TODO: IsTextFile()\n\/\/ TODO: IsImageFile()\n\/\/ TODO: IsPDFFile()\n<|endoftext|>"}
{"text":"<commit_before>package mc\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/materials-commons\/config\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/app\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"SqlProjectDBOpener\", func() {\n\tContext(\"Open\/Create Tests\", func() {\n\t\tvar (\n\t\t\tprojectDBSpec ProjectDBSpec\n\t\t\tprojectOpener sqlProjectDBOpener = sqlProjectDBOpener{\n\t\t\t\tconfiger: configConfiger{},\n\t\t\t}\n\t\t)\n\t\tBeforeEach(func() {\n\t\t\tconfig.Set(\"mcconfigdir\", \".materialscommons\")\n\t\t\tos.Mkdir(\".materialscommons\", 0777)\n\t\t\tprojectDBSpec = ProjectDBSpec{\n\t\t\t\tPath:      \"\/tmp\",\n\t\t\t\tName:      \"proj1\",\n\t\t\t\tProjectID: \"proj1id\",\n\t\t\t}\n\t\t})\n\n\t\tAfterEach(func() {\n\t\t\tos.RemoveAll(\".materialscommons\")\n\t\t})\n\n\t\tDescribe(\"CreateProjectDB method tests\", func() {\n\t\t\tIt(\"Should return an error if the path doesn't exist\", func() {\n\t\t\t\tos.RemoveAll(\".materialscommons\")\n\t\t\t\tpdb, err := projectOpener.CreateProjectDB(projectDBSpec)\n\t\t\t\tExpect(err).To(Equal(app.ErrNotFound))\n\t\t\t\tExpect(pdb).To(BeNil())\n\t\t\t})\n\n\t\t\tIt(\"Should return an error if the project already exists\", func() {\n\t\t\t\tioutil.WriteFile(filepath.Join(\".materialscommons\", \"proj1.db\"), []byte(\"hello\"), 0777)\n\t\t\t\tpdb, err := projectOpener.CreateProjectDB(projectDBSpec)\n\t\t\t\tExpect(err).To(Equal(app.ErrExists))\n\t\t\t\tExpect(pdb).To(BeNil())\n\t\t\t})\n\n\t\t\tIt(\"Should create the project when it doesn't exist\", func() {\n\t\t\t\tpdb, err := projectOpener.CreateProjectDB(projectDBSpec)\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(pdb).NotTo(BeNil())\n\n\t\t\t\t\/\/ Test the projects contents\n\t\t\t\tsqlpdb := pdb.(*sqlProjectDB)\n\t\t\t\tdb := sqlpdb.db\n\t\t\t\tvar projects []Project\n\t\t\t\terr = db.Select(&projects, \"select * from project\")\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(projects).To(HaveLen(1))\n\t\t\t\tproj := projects[0]\n\t\t\t\tExpect(proj.ProjectID).To(Equal(\"proj1id\"))\n\t\t\t\tExpect(proj.Name).To(Equal(\"proj1\"))\n\t\t\t\tExpect(proj.Path).To(Equal(\"\/tmp\"))\n\t\t\t})\n\t\t})\n\n\t\tDescribe(\"OpenProjectDB method tests\", func() {\n\t\t\tIt(\"Should return an error when the project doesn't exist\", func() {\n\t\t\t\tpdb, err := projectOpener.OpenProjectDB(\"does-not-exist\")\n\t\t\t\tExpect(err).To(Equal(app.ErrNotFound))\n\t\t\t\tExpect(pdb).To(BeNil())\n\t\t\t})\n\n\t\t\tIt(\"Should open an existing project\", func() {\n\t\t\t\t\/\/ Create the project\n\t\t\t\tpdb, err := projectOpener.CreateProjectDB(projectDBSpec)\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(pdb).NotTo(BeNil())\n\n\t\t\t\t\/\/ Open the project and test its contents\n\t\t\t\tpdb, err = projectOpener.OpenProjectDB(\"proj1\")\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(pdb).NotTo(BeNil())\n\t\t\t\tsqlpdb := pdb.(*sqlProjectDB)\n\t\t\t\tdb := sqlpdb.db\n\t\t\t\tvar projects []Project\n\t\t\t\terr = db.Select(&projects, \"select * from project\")\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(projects).To(HaveLen(1))\n\t\t\t\tproj := projects[0]\n\t\t\t\tExpect(proj.ProjectID).To(Equal(\"proj1id\"))\n\t\t\t\tExpect(proj.Name).To(Equal(\"proj1\"))\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"PathToName method tests\", func() {\n\t\tvar (\n\t\t\tprojectOpener sqlProjectDBOpener = sqlProjectDBOpener{\n\t\t\t\tconfiger: configConfiger{},\n\t\t\t}\n\t\t)\n\n\t\tIt(\"Should return last element of path that has .db extension without .db\", func() {\n\t\t\tpath := \"\/tmp\/this.db\"\n\t\t\tname := projectOpener.PathToName(path)\n\t\t\tExpect(name).To(Equal(\"this\"))\n\t\t})\n\n\t\tIt(\"Should return return last element of path for a name that has multiple dots without .db extension\", func() {\n\t\t\tpath := \"\/tmp\/this.is.name.db\"\n\t\t\tname := projectOpener.PathToName(path)\n\t\t\tExpect(name).To(Equal(\"this.is.name\"))\n\t\t})\n\t})\n})\n<commit_msg>Formatting change add line between variable declarations and BeforeEach()<commit_after>package mc\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/materials-commons\/config\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/app\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"SqlProjectDBOpener\", func() {\n\tContext(\"Open\/Create Tests\", func() {\n\t\tvar (\n\t\t\tprojectDBSpec ProjectDBSpec\n\t\t\tprojectOpener sqlProjectDBOpener = sqlProjectDBOpener{\n\t\t\t\tconfiger: configConfiger{},\n\t\t\t}\n\t\t)\n\n\t\tBeforeEach(func() {\n\t\t\tconfig.Set(\"mcconfigdir\", \".materialscommons\")\n\t\t\tos.Mkdir(\".materialscommons\", 0777)\n\t\t\tprojectDBSpec = ProjectDBSpec{\n\t\t\t\tPath:      \"\/tmp\",\n\t\t\t\tName:      \"proj1\",\n\t\t\t\tProjectID: \"proj1id\",\n\t\t\t}\n\t\t})\n\n\t\tAfterEach(func() {\n\t\t\tos.RemoveAll(\".materialscommons\")\n\t\t})\n\n\t\tDescribe(\"CreateProjectDB method tests\", func() {\n\t\t\tIt(\"Should return an error if the path doesn't exist\", func() {\n\t\t\t\tos.RemoveAll(\".materialscommons\")\n\t\t\t\tpdb, err := projectOpener.CreateProjectDB(projectDBSpec)\n\t\t\t\tExpect(err).To(Equal(app.ErrNotFound))\n\t\t\t\tExpect(pdb).To(BeNil())\n\t\t\t})\n\n\t\t\tIt(\"Should return an error if the project already exists\", func() {\n\t\t\t\tioutil.WriteFile(filepath.Join(\".materialscommons\", \"proj1.db\"), []byte(\"hello\"), 0777)\n\t\t\t\tpdb, err := projectOpener.CreateProjectDB(projectDBSpec)\n\t\t\t\tExpect(err).To(Equal(app.ErrExists))\n\t\t\t\tExpect(pdb).To(BeNil())\n\t\t\t})\n\n\t\t\tIt(\"Should create the project when it doesn't exist\", func() {\n\t\t\t\tpdb, err := projectOpener.CreateProjectDB(projectDBSpec)\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(pdb).NotTo(BeNil())\n\n\t\t\t\t\/\/ Test the projects contents\n\t\t\t\tsqlpdb := pdb.(*sqlProjectDB)\n\t\t\t\tdb := sqlpdb.db\n\t\t\t\tvar projects []Project\n\t\t\t\terr = db.Select(&projects, \"select * from project\")\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(projects).To(HaveLen(1))\n\t\t\t\tproj := projects[0]\n\t\t\t\tExpect(proj.ProjectID).To(Equal(\"proj1id\"))\n\t\t\t\tExpect(proj.Name).To(Equal(\"proj1\"))\n\t\t\t\tExpect(proj.Path).To(Equal(\"\/tmp\"))\n\t\t\t})\n\t\t})\n\n\t\tDescribe(\"OpenProjectDB method tests\", func() {\n\t\t\tIt(\"Should return an error when the project doesn't exist\", func() {\n\t\t\t\tpdb, err := projectOpener.OpenProjectDB(\"does-not-exist\")\n\t\t\t\tExpect(err).To(Equal(app.ErrNotFound))\n\t\t\t\tExpect(pdb).To(BeNil())\n\t\t\t})\n\n\t\t\tIt(\"Should open an existing project\", func() {\n\t\t\t\t\/\/ Create the project\n\t\t\t\tpdb, err := projectOpener.CreateProjectDB(projectDBSpec)\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(pdb).NotTo(BeNil())\n\n\t\t\t\t\/\/ Open the project and test its contents\n\t\t\t\tpdb, err = projectOpener.OpenProjectDB(\"proj1\")\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(pdb).NotTo(BeNil())\n\t\t\t\tsqlpdb := pdb.(*sqlProjectDB)\n\t\t\t\tdb := sqlpdb.db\n\t\t\t\tvar projects []Project\n\t\t\t\terr = db.Select(&projects, \"select * from project\")\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(projects).To(HaveLen(1))\n\t\t\t\tproj := projects[0]\n\t\t\t\tExpect(proj.ProjectID).To(Equal(\"proj1id\"))\n\t\t\t\tExpect(proj.Name).To(Equal(\"proj1\"))\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"PathToName method tests\", func() {\n\t\tvar (\n\t\t\tprojectOpener sqlProjectDBOpener = sqlProjectDBOpener{\n\t\t\t\tconfiger: configConfiger{},\n\t\t\t}\n\t\t)\n\n\t\tIt(\"Should return last element of path that has .db extension without .db\", func() {\n\t\t\tpath := \"\/tmp\/this.db\"\n\t\t\tname := projectOpener.PathToName(path)\n\t\t\tExpect(name).To(Equal(\"this\"))\n\t\t})\n\n\t\tIt(\"Should return return last element of path for a name that has multiple dots without .db extension\", func() {\n\t\t\tpath := \"\/tmp\/this.is.name.db\"\n\t\t\tname := projectOpener.PathToName(path)\n\t\t\tExpect(name).To(Equal(\"this.is.name\"))\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package main_test\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-tcp-router\/testutil\"\n\t\"github.com\/cloudfoundry-incubator\/cf-tcp-router\/utils\"\n\t\"github.com\/cloudfoundry-incubator\/routing-api\"\n\troutingtestrunner \"github.com\/cloudfoundry-incubator\/routing-api\/cmd\/routing-api\/testrunner\"\n\t\"github.com\/cloudfoundry\/storeadapter\"\n\t\"github.com\/cloudfoundry\/storeadapter\/storerunner\/etcdstorerunner\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\n\t\"testing\"\n)\n\nvar (\n\trouterConfigurerPath    string\n\troutingAPIBinPath       string\n\trouterConfigurerPort    int\n\thaproxyConfigFile       string\n\thaproxyConfigBackupFile string\n\thaproxyBaseConfigFile   string\n\n\tetcdPort    int\n\tetcdUrl     string\n\tetcdRunner  *etcdstorerunner.ETCDClusterRunner\n\tetcdAdapter storeadapter.StoreAdapter\n\n\troutingAPIAddress      string\n\troutingAPIArgs         routingtestrunner.Args\n\troutingAPIPort         uint16\n\troutingAPIIP           string\n\troutingAPISystemDomain string\n\troutingApiClient       routing_api.Client\n)\n\nfunc TestRouterConfigurer(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"RouterConfigurer Suite\")\n}\n\nvar _ = SynchronizedBeforeSuite(func() []byte {\n\trouterConfigurer, err := gexec.Build(\"github.com\/cloudfoundry-incubator\/cf-tcp-router\/cmd\/router-configurer\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\troutingAPIBin, err := gexec.Build(\"github.com\/cloudfoundry-incubator\/routing-api\/cmd\/routing-api\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\tpayload, err := json.Marshal(map[string]string{\n\t\t\"router-configurer\": routerConfigurer,\n\t\t\"routing-api\":       routingAPIBin,\n\t})\n\n\tExpect(err).NotTo(HaveOccurred())\n\n\treturn payload\n}, func(payload []byte) {\n\tcontext := map[string]string{}\n\n\terr := json.Unmarshal(payload, &context)\n\tExpect(err).NotTo(HaveOccurred())\n\n\trouterConfigurerPort = 7000 + GinkgoParallelNode()\n\trouterConfigurerPath = context[\"router-configurer\"]\n\troutingAPIBinPath = context[\"routing-api\"]\n})\n\nvar _ = BeforeEach(func() {\n\trandomFileName := testutil.RandomFileName(\"haproxy_\", \".cfg\")\n\trandomBackupFileName := fmt.Sprintf(\"%s.bak\", randomFileName)\n\trandomBaseFileName := testutil.RandomFileName(\"haproxy_base_\", \".cfg\")\n\thaproxyConfigFile = path.Join(os.TempDir(), randomFileName)\n\thaproxyConfigBackupFile = path.Join(os.TempDir(), randomBackupFileName)\n\thaproxyBaseConfigFile = path.Join(os.TempDir(), randomBaseFileName)\n\n\terr := utils.WriteToFile(\n\t\t[]byte(\n\t\t\t`global maxconn 4096\ndefaults\n  log global\n  timeout connect 300000\n  timeout client 300000\n  timeout server 300000\n  maxconn 2000`),\n\t\thaproxyBaseConfigFile)\n\tExpect(err).ShouldNot(HaveOccurred())\n\tExpect(utils.FileExists(haproxyBaseConfigFile)).To(BeTrue())\n\n\terr = utils.CopyFile(haproxyBaseConfigFile, haproxyConfigFile)\n\tExpect(err).ShouldNot(HaveOccurred())\n\tExpect(utils.FileExists(haproxyConfigFile)).To(BeTrue())\n\n\tetcdPort = 4001 + GinkgoParallelNode()\n\tetcdUrl = fmt.Sprintf(\"http:\/\/127.0.0.1:%d\", etcdPort)\n\tetcdRunner = etcdstorerunner.NewETCDClusterRunner(etcdPort, 1, nil)\n\tetcdRunner.Start()\n\n\tetcdAdapter = etcdRunner.Adapter(nil)\n\n\troutingAPIPort = uint16(6900 + GinkgoParallelNode())\n\troutingAPIIP = \"127.0.0.1\"\n\troutingAPISystemDomain = \"example.com\"\n\troutingAPIAddress = fmt.Sprintf(\"http:\/\/%s:%d\", routingAPIIP, routingAPIPort)\n\n\troutingAPIArgs = routingtestrunner.Args{\n\t\tPort:         routingAPIPort,\n\t\tIP:           routingAPIIP,\n\t\tSystemDomain: routingAPISystemDomain,\n\t\tConfigPath:   createConfig(),\n\t\tEtcdCluster:  etcdUrl,\n\t\tDevMode:      true,\n\t}\n\troutingApiClient = routing_api.NewClient(routingAPIAddress)\n})\n\nvar _ = AfterEach(func() {\n\terr := os.Remove(haproxyConfigFile)\n\tExpect(err).ShouldNot(HaveOccurred())\n\n\tos.Remove(haproxyConfigBackupFile)\n\n\tetcdAdapter.Disconnect()\n\tetcdRunner.Reset()\n\tetcdRunner.Stop()\n})\n\nvar _ = SynchronizedAfterSuite(func() {\n}, func() {\n\tgexec.CleanupBuildArtifacts()\n})\n\nfunc createConfig() string {\n\tconfigFilePath := fmt.Sprintf(\"\/tmp\/example_%d.yml\", GinkgoParallelNode())\n\terr := utils.WriteToFile(\n\t\t[]byte(\n\t\t\t`log_guid: \"my_logs\"\nuaa_verification_key: \"-----BEGIN PUBLIC KEY-----\n\n      MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHFr+KICms+tuT1OXJwhCUmR2d\n\n      KVy7psa8xzElSyzqx7oJyfJ1JZyOzToj9T5SfTIq396agbHJWVfYphNahvZ\/7uMX\n\n      qHxf+ZH9BL1gk9Y6kCnbM5R60gfwjyW1\/dQPjOzn9N394zd2FJoFHwdq9Qs0wBug\n\n      spULZVNRxq7veq\/fzwIDAQAB\n\n      -----END PUBLIC KEY-----\"\n\ndebug_address: \"1.2.3.4:1234\"\nmetron_config:\n  address: \"1.2.3.4\"\n  port: \"4567\"\nmetrics_reporting_interval: \"500ms\"\nstatsd_endpoint: \"localhost:8125\"\nstatsd_client_flush_interval: \"10ms\"\nmax_concurrent_etcd_requests: 10\nrouter_groups:\n- name: \"default-tcp\"\n  type: \"tcp\"\n  reservable_ports: \"1024-65535\"\n`),\n\t\tconfigFilePath)\n\tExpect(err).ShouldNot(HaveOccurred())\n\tExpect(utils.FileExists(configFilePath)).To(BeTrue())\n\n\treturn configFilePath\n}\n<commit_msg>Remove max_concurrent_etcd_requests from unit tests<commit_after>package main_test\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-tcp-router\/testutil\"\n\t\"github.com\/cloudfoundry-incubator\/cf-tcp-router\/utils\"\n\t\"github.com\/cloudfoundry-incubator\/routing-api\"\n\troutingtestrunner \"github.com\/cloudfoundry-incubator\/routing-api\/cmd\/routing-api\/testrunner\"\n\t\"github.com\/cloudfoundry\/storeadapter\"\n\t\"github.com\/cloudfoundry\/storeadapter\/storerunner\/etcdstorerunner\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\n\t\"testing\"\n)\n\nvar (\n\trouterConfigurerPath    string\n\troutingAPIBinPath       string\n\trouterConfigurerPort    int\n\thaproxyConfigFile       string\n\thaproxyConfigBackupFile string\n\thaproxyBaseConfigFile   string\n\n\tetcdPort    int\n\tetcdUrl     string\n\tetcdRunner  *etcdstorerunner.ETCDClusterRunner\n\tetcdAdapter storeadapter.StoreAdapter\n\n\troutingAPIAddress      string\n\troutingAPIArgs         routingtestrunner.Args\n\troutingAPIPort         uint16\n\troutingAPIIP           string\n\troutingAPISystemDomain string\n\troutingApiClient       routing_api.Client\n)\n\nfunc TestRouterConfigurer(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"RouterConfigurer Suite\")\n}\n\nvar _ = SynchronizedBeforeSuite(func() []byte {\n\trouterConfigurer, err := gexec.Build(\"github.com\/cloudfoundry-incubator\/cf-tcp-router\/cmd\/router-configurer\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\troutingAPIBin, err := gexec.Build(\"github.com\/cloudfoundry-incubator\/routing-api\/cmd\/routing-api\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\tpayload, err := json.Marshal(map[string]string{\n\t\t\"router-configurer\": routerConfigurer,\n\t\t\"routing-api\":       routingAPIBin,\n\t})\n\n\tExpect(err).NotTo(HaveOccurred())\n\n\treturn payload\n}, func(payload []byte) {\n\tcontext := map[string]string{}\n\n\terr := json.Unmarshal(payload, &context)\n\tExpect(err).NotTo(HaveOccurred())\n\n\trouterConfigurerPort = 7000 + GinkgoParallelNode()\n\trouterConfigurerPath = context[\"router-configurer\"]\n\troutingAPIBinPath = context[\"routing-api\"]\n})\n\nvar _ = BeforeEach(func() {\n\trandomFileName := testutil.RandomFileName(\"haproxy_\", \".cfg\")\n\trandomBackupFileName := fmt.Sprintf(\"%s.bak\", randomFileName)\n\trandomBaseFileName := testutil.RandomFileName(\"haproxy_base_\", \".cfg\")\n\thaproxyConfigFile = path.Join(os.TempDir(), randomFileName)\n\thaproxyConfigBackupFile = path.Join(os.TempDir(), randomBackupFileName)\n\thaproxyBaseConfigFile = path.Join(os.TempDir(), randomBaseFileName)\n\n\terr := utils.WriteToFile(\n\t\t[]byte(\n\t\t\t`global maxconn 4096\ndefaults\n  log global\n  timeout connect 300000\n  timeout client 300000\n  timeout server 300000\n  maxconn 2000`),\n\t\thaproxyBaseConfigFile)\n\tExpect(err).ShouldNot(HaveOccurred())\n\tExpect(utils.FileExists(haproxyBaseConfigFile)).To(BeTrue())\n\n\terr = utils.CopyFile(haproxyBaseConfigFile, haproxyConfigFile)\n\tExpect(err).ShouldNot(HaveOccurred())\n\tExpect(utils.FileExists(haproxyConfigFile)).To(BeTrue())\n\n\tetcdPort = 4001 + GinkgoParallelNode()\n\tetcdUrl = fmt.Sprintf(\"http:\/\/127.0.0.1:%d\", etcdPort)\n\tetcdRunner = etcdstorerunner.NewETCDClusterRunner(etcdPort, 1, nil)\n\tetcdRunner.Start()\n\n\tetcdAdapter = etcdRunner.Adapter(nil)\n\n\troutingAPIPort = uint16(6900 + GinkgoParallelNode())\n\troutingAPIIP = \"127.0.0.1\"\n\troutingAPISystemDomain = \"example.com\"\n\troutingAPIAddress = fmt.Sprintf(\"http:\/\/%s:%d\", routingAPIIP, routingAPIPort)\n\n\troutingAPIArgs = routingtestrunner.Args{\n\t\tPort:         routingAPIPort,\n\t\tIP:           routingAPIIP,\n\t\tSystemDomain: routingAPISystemDomain,\n\t\tConfigPath:   createConfig(),\n\t\tEtcdCluster:  etcdUrl,\n\t\tDevMode:      true,\n\t}\n\troutingApiClient = routing_api.NewClient(routingAPIAddress)\n})\n\nvar _ = AfterEach(func() {\n\terr := os.Remove(haproxyConfigFile)\n\tExpect(err).ShouldNot(HaveOccurred())\n\n\tos.Remove(haproxyConfigBackupFile)\n\n\tetcdAdapter.Disconnect()\n\tetcdRunner.Reset()\n\tetcdRunner.Stop()\n})\n\nvar _ = SynchronizedAfterSuite(func() {\n}, func() {\n\tgexec.CleanupBuildArtifacts()\n})\n\nfunc createConfig() string {\n\tconfigFilePath := fmt.Sprintf(\"\/tmp\/example_%d.yml\", GinkgoParallelNode())\n\terr := utils.WriteToFile(\n\t\t[]byte(\n\t\t\t`log_guid: \"my_logs\"\nuaa_verification_key: \"-----BEGIN PUBLIC KEY-----\n\n      MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHFr+KICms+tuT1OXJwhCUmR2d\n\n      KVy7psa8xzElSyzqx7oJyfJ1JZyOzToj9T5SfTIq396agbHJWVfYphNahvZ\/7uMX\n\n      qHxf+ZH9BL1gk9Y6kCnbM5R60gfwjyW1\/dQPjOzn9N394zd2FJoFHwdq9Qs0wBug\n\n      spULZVNRxq7veq\/fzwIDAQAB\n\n      -----END PUBLIC KEY-----\"\n\ndebug_address: \"1.2.3.4:1234\"\nmetron_config:\n  address: \"1.2.3.4\"\n  port: \"4567\"\nmetrics_reporting_interval: \"500ms\"\nstatsd_endpoint: \"localhost:8125\"\nstatsd_client_flush_interval: \"10ms\"\nrouter_groups:\n- name: \"default-tcp\"\n  type: \"tcp\"\n  reservable_ports: \"1024-65535\"\n`),\n\t\tconfigFilePath)\n\tExpect(err).ShouldNot(HaveOccurred())\n\tExpect(utils.FileExists(configFilePath)).To(BeTrue())\n\n\treturn configFilePath\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/kless\/term\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nvar argNum = 0\n\nvar ignorePackageName = flag.Bool(\"a\", false, \"always use all instances; ignore detected package name\")\nvar args []string\n\nfunc main() {\n\tlog.SetFlags(0)\n\n\tflag.Parse()\n\targs = flag.Args()\n\n\tvar cluster string\n\n\tenvCluster := getNextArg(\"environment not given\")\n\tenvClusterSplit := strings.Split(envCluster, \"\/\")\n\tenv := envClusterSplit[0]\n\tif len(envClusterSplit) > 1 {\n\t\tcluster = envClusterSplit[1]\n\t}\n\n\tcmd := getNextArg(\"command not given\")\n\n\tprojectName, err := detectProjectName()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tvar packageName string\n\tif !*ignorePackageName {\n\t\tpackageName, err = detectPackageName()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t}\n\n\tawsConf, err := getAWSConf(projectName)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tjob, err := NewJob(awsConf, env, cluster, projectName, packageName,\n\t\tos.Stdout, term.IsTerminal(syscall.Stdout))\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tswitch cmd {\n\tcase \"deploy\":\n\t\tversion := getNextArg(\"version not given\")\n\t\terr = job.Deploy(version)\n\tcase \"exec\":\n\t\tcmd := getRemainingArgsAsString(\"command not given\")\n\t\terrs := job.Exec(cmd)\n\t\tif len(errs) > 0 {\n\t\t\terrStrings := make([]string, len(errs))\n\t\t\tfor i, err := range errs {\n\t\t\t\terrStrings[i] = err.Error()\n\t\t\t}\n\t\t\tlog.Fatalf(strings.Join(errStrings, \"\\n\"))\n\t\t}\n\tcase \"ssh\":\n\t\thostName := getNextArg(\"\")\n\t\tsshArgs := getRemainingArgsAsSlice(\"\")\n\t\terr = job.Ssh(hostName, sshArgs)\n\tcase \"scp\":\n\t\tif len(args) <= argNum {\n\t\t\tlog.Fatalln(\"you must give at least one source file\")\n\t\t}\n\t\terr = job.Scp(args[argNum:])\n\tcase \"ls\":\n\t\terr = job.List()\n\tcase \"hostname\":\n\t\tinstanceName := getNextArg(\"instance name not given\")\n\t\terr = job.Hostname(instanceName)\n\tdefault:\n\t\tlog.Fatalf(\"command not recognised: %s\\n\", cmd)\n\t}\n\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc fatalUsageError(errMsg string) {\n\tfmt.Fprintln(os.Stderr, \"fatal: \"+errMsg+\"\\n\")\n\tusage()\n\tos.Exit(1)\n}\n\nfunc getNextArg(errMsg string) (val string) {\n\tif len(args) >= (argNum + 1) {\n\t\tval = args[argNum]\n\t\targNum += 1\n\t} else if errMsg != \"\" {\n\t\tfatalUsageError(errMsg)\n\t}\n\treturn\n}\n\nfunc getRemainingArgsAsString(errMsg string) (val string) {\n\tremainingArgs := args[argNum:]\n\tif len(remainingArgs) >= 1 {\n\t\tval = strings.Join(remainingArgs, \" \")\n\t} else {\n\t\tlog.Fatalln(errMsg)\n\t}\n\treturn\n}\n\nfunc getRemainingArgsAsSlice(errMsg string) (val []string) {\n\tval = args[argNum:]\n\tif errMsg != \"\" && len(val) == 0 {\n\t\tlog.Fatalln(errMsg)\n\t}\n\treturn\n}\n\nfunc findDotfileAndRead(fn string, errName string) (value string, err error) {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar newDir string\n\tfor {\n\t\tif fBytes, err := ioutil.ReadFile(path.Join(dir, fn)); err == nil && len(fBytes) > 0 {\n\t\t\treturn strings.TrimSpace(string(fBytes)), nil\n\t\t}\n\n\t\tnewDir = path.Dir(dir)\n\t\tif dir == newDir {\n\t\t\tbreak\n\t\t}\n\t\tdir = newDir\n\t}\n\n\treturn \"\", errors.New(\n\t\tfmt.Sprintf(\"%s not found. Please ensure your project is configured properly.\", errName))\n}\n\nfunc detectProjectName() (projectName string, err error) {\n\treturn findDotfileAndRead(\".mxm-project\", \"Project name\")\n}\n\nfunc detectPackageName() (packageName string, err error) {\n\tpackageName, _ = findDotfileAndRead(\".mxm-package\", \"Package name\")\n\treturn\n}\n\nfunc formatTable(fields [][]string) (out string) {\n\tif len(fields) == 0 {\n\t\treturn\n\t}\n\toutBuf := new(bytes.Buffer)\n\tnumFields := len(fields[0])\n\tmaxIndex := numFields - 1\n\tmaxWidths := make([]int, numFields)\n\tfor _, f := range fields {\n\t\tfor i, c := range f {\n\t\t\tif lenc := len(c); lenc > maxWidths[i] {\n\t\t\t\tmaxWidths[i] = lenc\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, f := range fields {\n\t\tfor i := 0; i < numFields; i++ {\n\t\t\tc := f[i]\n\t\t\toutBuf.WriteString(c)\n\t\t\tif i < maxIndex {\n\t\t\t\toutBuf.Write(\n\t\t\t\t\tbytes.Repeat([]byte(\" \"), maxWidths[i] - len(c) + 2))\n\t\t\t}\n\t\t}\n\t\toutBuf.WriteRune('\\n')\n\t}\n\n\tout = outBuf.String()\n\n\treturn\n}\n<commit_msg>Don't filter by package by default<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/kless\/term\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nvar argNum = 0\n\nvar filterPackageName = flag.Bool(\"p\", false, \"filter by package name; detect it by default\")\nvar packageName = flag.String(\"package\", \"\", \"package name to filter by\")\nvar args []string\n\nfunc main() {\n\tlog.SetFlags(0)\n\n\tflag.Parse()\n\targs = flag.Args()\n\n\tvar cluster string\n\n\tenvCluster := getNextArg(\"environment not given\")\n\tenvClusterSplit := strings.Split(envCluster, \"\/\")\n\tenv := envClusterSplit[0]\n\tif len(envClusterSplit) > 1 {\n\t\tcluster = envClusterSplit[1]\n\t}\n\n\tcmd := getNextArg(\"command not given\")\n\n\tprojectName, err := detectProjectName()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tif *filterPackageName && *packageName == \"\" {\n\t\t*packageName, err = detectPackageName()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t}\n\n\tawsConf, err := getAWSConf(projectName)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tjob, err := NewJob(awsConf, env, cluster, projectName, *packageName,\n\t\tos.Stdout, term.IsTerminal(syscall.Stdout))\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tswitch cmd {\n\tcase \"deploy\":\n\t\tversion := getNextArg(\"version not given\")\n\t\terr = job.Deploy(version)\n\tcase \"exec\":\n\t\tcmd := getRemainingArgsAsString(\"command not given\")\n\t\terrs := job.Exec(cmd)\n\t\tif len(errs) > 0 {\n\t\t\terrStrings := make([]string, len(errs))\n\t\t\tfor i, err := range errs {\n\t\t\t\terrStrings[i] = err.Error()\n\t\t\t}\n\t\t\tlog.Fatalf(strings.Join(errStrings, \"\\n\"))\n\t\t}\n\tcase \"ssh\":\n\t\thostName := getNextArg(\"\")\n\t\tsshArgs := getRemainingArgsAsSlice(\"\")\n\t\terr = job.Ssh(hostName, sshArgs)\n\tcase \"scp\":\n\t\tif len(args) <= argNum {\n\t\t\tlog.Fatalln(\"you must give at least one source file\")\n\t\t}\n\t\terr = job.Scp(args[argNum:])\n\tcase \"ls\":\n\t\terr = job.List()\n\tcase \"hostname\":\n\t\tinstanceName := getNextArg(\"instance name not given\")\n\t\terr = job.Hostname(instanceName)\n\tdefault:\n\t\tlog.Fatalf(\"command not recognised: %s\\n\", cmd)\n\t}\n\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n\nfunc fatalUsageError(errMsg string) {\n\tfmt.Fprintln(os.Stderr, \"fatal: \"+errMsg+\"\\n\")\n\tusage()\n\tos.Exit(1)\n}\n\nfunc getNextArg(errMsg string) (val string) {\n\tif len(args) >= (argNum + 1) {\n\t\tval = args[argNum]\n\t\targNum += 1\n\t} else if errMsg != \"\" {\n\t\tfatalUsageError(errMsg)\n\t}\n\treturn\n}\n\nfunc getRemainingArgsAsString(errMsg string) (val string) {\n\tremainingArgs := args[argNum:]\n\tif len(remainingArgs) >= 1 {\n\t\tval = strings.Join(remainingArgs, \" \")\n\t} else {\n\t\tlog.Fatalln(errMsg)\n\t}\n\treturn\n}\n\nfunc getRemainingArgsAsSlice(errMsg string) (val []string) {\n\tval = args[argNum:]\n\tif errMsg != \"\" && len(val) == 0 {\n\t\tlog.Fatalln(errMsg)\n\t}\n\treturn\n}\n\nfunc findDotfileAndRead(fn string, errName string) (value string, err error) {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar newDir string\n\tfor {\n\t\tif fBytes, err := ioutil.ReadFile(path.Join(dir, fn)); err == nil && len(fBytes) > 0 {\n\t\t\treturn strings.TrimSpace(string(fBytes)), nil\n\t\t}\n\n\t\tnewDir = path.Dir(dir)\n\t\tif dir == newDir {\n\t\t\tbreak\n\t\t}\n\t\tdir = newDir\n\t}\n\n\treturn \"\", errors.New(\n\t\tfmt.Sprintf(\"%s not found. Please ensure your project is configured properly.\", errName))\n}\n\nfunc detectProjectName() (projectName string, err error) {\n\treturn findDotfileAndRead(\".mxm-project\", \"Project name\")\n}\n\nfunc detectPackageName() (packageName string, err error) {\n\treturn findDotfileAndRead(\".mxm-package\", \"Package name\")\n}\n\nfunc formatTable(fields [][]string) (out string) {\n\tif len(fields) == 0 {\n\t\treturn\n\t}\n\toutBuf := new(bytes.Buffer)\n\tnumFields := len(fields[0])\n\tmaxIndex := numFields - 1\n\tmaxWidths := make([]int, numFields)\n\tfor _, f := range fields {\n\t\tfor i, c := range f {\n\t\t\tif lenc := len(c); lenc > maxWidths[i] {\n\t\t\t\tmaxWidths[i] = lenc\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, f := range fields {\n\t\tfor i := 0; i < numFields; i++ {\n\t\t\tc := f[i]\n\t\t\toutBuf.WriteString(c)\n\t\t\tif i < maxIndex {\n\t\t\t\toutBuf.Write(\n\t\t\t\t\tbytes.Repeat([]byte(\" \"), maxWidths[i] - len(c) + 2))\n\t\t\t}\n\t\t}\n\t\toutBuf.WriteRune('\\n')\n\t}\n\n\tout = outBuf.String()\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package v7_test\n\nimport (\n\t\"errors\"\n\n\t\"code.cloudfoundry.org\/cli\/command\/commandfakes\"\n\t. \"code.cloudfoundry.org\/cli\/command\/v7\"\n\t\"code.cloudfoundry.org\/cli\/command\/v7\/v7fakes\"\n\t\"code.cloudfoundry.org\/cli\/util\/ui\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gbytes\"\n)\n\nvar _ = Describe(\"share-service Command\", func() {\n\tvar (\n\t\tcmd             ShareServiceCommand\n\t\ttestUI          *ui.UI\n\t\tfakeConfig      *commandfakes.FakeConfig\n\t\tfakeSharedActor *commandfakes.FakeSharedActor\n\t\tfakeActor       *v7fakes.FakeActor\n\t\texecuteErr      error\n\t)\n\n\tBeforeEach(func() {\n\t\ttestUI = ui.NewTestUI(nil, NewBuffer(), NewBuffer())\n\t\tfakeConfig = new(commandfakes.FakeConfig)\n\t\tfakeSharedActor = new(commandfakes.FakeSharedActor)\n\t\tfakeActor = new(v7fakes.FakeActor)\n\n\t\tcmd = ShareServiceCommand{\n\t\t\tBaseCommand: BaseCommand{\n\t\t\t\tUI:          testUI,\n\t\t\t\tConfig:      fakeConfig,\n\t\t\t\tSharedActor: fakeSharedActor,\n\t\t\t\tActor:       fakeActor,\n\t\t\t},\n\t\t}\n\t})\n\n\tJustBeforeEach(func() {\n\t\texecuteErr = cmd.Execute(nil)\n\t})\n\n\tContext(\"user not targeting space\", func() {\n\t\tBeforeEach(func() {\n\t\t\tfakeSharedActor.CheckTargetReturns(errors.New(\"space not targeted\"))\n\t\t})\n\n\t\tIt(\"checks the user is logged in, and targeting an org and space\", func() {\n\t\t\tExpect(fakeSharedActor.CheckTargetCallCount()).To(Equal(1))\n\t\t\torgChecked, spaceChecked := fakeSharedActor.CheckTargetArgsForCall(0)\n\t\t\tExpect(orgChecked).To(BeTrue())\n\t\t\tExpect(spaceChecked).To(BeTrue())\n\t\t})\n\n\t\tIt(\"fails the command\", func() {\n\t\t\tExpect(executeErr).To(Not(BeNil()))\n\t\t\tExpect(executeErr.Error()).To(ContainSubstring(\"space not targeted\"))\n\t\t})\n\t})\n\n})\n<commit_msg>Moved target check outside of context<commit_after>package v7_test\n\nimport (\n\t\"errors\"\n\n\t\"code.cloudfoundry.org\/cli\/command\/commandfakes\"\n\t. \"code.cloudfoundry.org\/cli\/command\/v7\"\n\t\"code.cloudfoundry.org\/cli\/command\/v7\/v7fakes\"\n\t\"code.cloudfoundry.org\/cli\/util\/ui\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gbytes\"\n)\n\nvar _ = Describe(\"share-service Command\", func() {\n\tvar (\n\t\tcmd             ShareServiceCommand\n\t\ttestUI          *ui.UI\n\t\tfakeConfig      *commandfakes.FakeConfig\n\t\tfakeSharedActor *commandfakes.FakeSharedActor\n\t\tfakeActor       *v7fakes.FakeActor\n\t\texecuteErr      error\n\t)\n\n\tBeforeEach(func() {\n\t\ttestUI = ui.NewTestUI(nil, NewBuffer(), NewBuffer())\n\t\tfakeConfig = new(commandfakes.FakeConfig)\n\t\tfakeSharedActor = new(commandfakes.FakeSharedActor)\n\t\tfakeActor = new(v7fakes.FakeActor)\n\n\t\tcmd = ShareServiceCommand{\n\t\t\tBaseCommand: BaseCommand{\n\t\t\t\tUI:          testUI,\n\t\t\t\tConfig:      fakeConfig,\n\t\t\t\tSharedActor: fakeSharedActor,\n\t\t\t\tActor:       fakeActor,\n\t\t\t},\n\t\t}\n\t})\n\n\tJustBeforeEach(func() {\n\t\texecuteErr = cmd.Execute(nil)\n\t})\n\n\tIt(\"checks the user is logged in, and targeting an org and space\", func() {\n\t\tExpect(fakeSharedActor.CheckTargetCallCount()).To(Equal(1))\n\t\torgChecked, spaceChecked := fakeSharedActor.CheckTargetArgsForCall(0)\n\t\tExpect(orgChecked).To(BeTrue())\n\t\tExpect(spaceChecked).To(BeTrue())\n\t})\n\n\tContext(\"user not targeting space\", func() {\n\t\tBeforeEach(func() {\n\t\t\tfakeSharedActor.CheckTargetReturns(errors.New(\"space not targeted\"))\n\t\t})\n\n\t\tIt(\"fails the command\", func() {\n\t\t\tExpect(executeErr).To(Not(BeNil()))\n\t\t\tExpect(executeErr.Error()).To(ContainSubstring(\"space not targeted\"))\n\t\t})\n\t})\n\n})\n<|endoftext|>"}
{"text":"<commit_before>package monico\n\nimport (\n\t\"os\"\n\t\"time\"\n)\n\ntype Moniter struct {\n\tpath        string\n\tlastModTime time.Time\n}\n\nfunc NewMoniter(path string) (*Moniter, error) {\n\tinfo, err := os.Stat(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Moniter{\n\t\tpath:        path,\n\t\tlastModTime: info.ModTime(),\n\t}, nil\n}\n\nfunc NewMoniterWithWD() (*Moniter, error) {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewMoniter(wd)\n}\n\nfunc (m *Moniter) Path() string {\n\treturn m.path\n}\n\nfunc (m *Moniter) Modified() (bool, error) {\n\tinfo, err := os.Stat(m.path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn !m.lastModTime.Equal(info.ModTime()), nil\n}\n\nfunc (m *Moniter) LastModTime() time.Time {\n\treturn m.lastModTime\n}\n\nfunc (m *Moniter) UpdateModTime() error {\n\tinfo, err := os.Stat(m.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.lastModTime = info.ModTime()\n\treturn nil\n}\n<commit_msg>Remove Path<commit_after>package monico\n\nimport (\n\t\"os\"\n\t\"time\"\n)\n\ntype Moniter struct {\n\tpath        string\n\tlastModTime time.Time\n}\n\nfunc NewMoniter(path string) (*Moniter, error) {\n\tinfo, err := os.Stat(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Moniter{\n\t\tpath:        path,\n\t\tlastModTime: info.ModTime(),\n\t}, nil\n}\n\nfunc NewMoniterWithWD() (*Moniter, error) {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewMoniter(wd)\n}\n\nfunc (m *Moniter) Modified() (bool, error) {\n\tinfo, err := os.Stat(m.path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn !m.lastModTime.Equal(info.ModTime()), nil\n}\n\nfunc (m *Moniter) LastModTime() time.Time {\n\treturn m.lastModTime\n}\n\nfunc (m *Moniter) UpdateModTime() error {\n\tinfo, err := os.Stat(m.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.lastModTime = info.ModTime()\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage logs\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar record = struct {\n\tError   error                  `json:\"err\"`\n\tLevel   int                    `json:\"v\"`\n\tMessage string                 `json:\"msg\"`\n\tTime    time.Time              `json:\"ts\"`\n\tFields  map[string]interface{} `json:\"fields\"`\n}{\n\tError:   fmt.Errorf(\"test for error:%s\", \"default\"),\n\tLevel:   2,\n\tMessage: \"test\",\n\tTime:    time.Unix(0, 123),\n\tFields: map[string]interface{}{\n\t\t\"str\":     \"foo\",\n\t\t\"int64-1\": int64(1),\n\t\t\"int64-2\": int64(1),\n\t\t\"float64\": float64(1.0),\n\t\t\"string1\": \"\\n\",\n\t\t\"string2\": \"💩\",\n\t\t\"string3\": \"🤔\",\n\t\t\"string4\": \"🙊\",\n\t\t\"bool\":    true,\n\t\t\"request\": struct {\n\t\t\tMethod  string `json:\"method\"`\n\t\t\tTimeout int    `json:\"timeout\"`\n\t\t\tsecret  string `json:\"secret\"`\n\t\t}{\n\t\t\tMethod:  \"GET\",\n\t\t\tTimeout: 10,\n\t\t\tsecret:  \"pony\",\n\t\t},\n\t},\n}\n\nfunc BenchmarkInfoLoggerInfo(b *testing.B) {\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tjLogger := NewJSONLogger(nil)\n\t\t\tjLogger.Info(\"test\",\n\t\t\t\t\"str\", \"foo\",\n\t\t\t\t\"int64-1\", int64(1),\n\t\t\t\t\"int64-2\", int64(1),\n\t\t\t\t\"float64\", float64(1.0),\n\t\t\t\t\"string1\", \"\\n\",\n\t\t\t\t\"string2\", \"💩\",\n\t\t\t\t\"string3\", \"🤔\",\n\t\t\t\t\"string4\", \"🙊\",\n\t\t\t\t\"bool\", true,\n\t\t\t\t\"request\", struct {\n\t\t\t\t\tMethod  string `json:\"method\"`\n\t\t\t\t\tTimeout int    `json:\"timeout\"`\n\t\t\t\t\tsecret  string `json:\"secret\"`\n\t\t\t\t}{\n\t\t\t\t\tMethod:  \"GET\",\n\t\t\t\t\tTimeout: 10,\n\t\t\t\t\tsecret:  \"pony\",\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t})\n}\n\nfunc BenchmarkInfoLoggerInfoStandardJSON(b *testing.B) {\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tjson.Marshal(record)\n\t\t}\n\t})\n}\n\nfunc BenchmarkZapLoggerError(b *testing.B) {\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tjLogger := NewJSONLogger(nil)\n\t\t\tjLogger.Error(fmt.Errorf(\"test for error:%s\", \"default\"),\n\t\t\t\t\"test\",\n\t\t\t\t\"str\", \"foo\",\n\t\t\t\t\"int64-1\", int64(1),\n\t\t\t\t\"int64-2\", int64(1),\n\t\t\t\t\"float64\", float64(1.0),\n\t\t\t\t\"string1\", \"\\n\",\n\t\t\t\t\"string2\", \"💩\",\n\t\t\t\t\"string3\", \"🤔\",\n\t\t\t\t\"string4\", \"🙊\",\n\t\t\t\t\"bool\", true,\n\t\t\t\t\"request\", struct {\n\t\t\t\t\tMethod  string `json:\"method\"`\n\t\t\t\t\tTimeout int    `json:\"timeout\"`\n\t\t\t\t\tsecret  string `json:\"secret\"`\n\t\t\t\t}{\n\t\t\t\t\tMethod:  \"GET\",\n\t\t\t\t\tTimeout: 10,\n\t\t\t\t\tsecret:  \"pony\",\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t})\n}\nfunc BenchmarkZapLoggerErrorStandardJSON(b *testing.B) {\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tjson.Marshal(record)\n\t\t}\n\t})\n}\n\nfunc BenchmarkZapLoggerV(b *testing.B) {\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tjLogger := NewJSONLogger(nil)\n\t\t\tjLogger.V(1).Info(\"test\",\n\t\t\t\t\"str\", \"foo\",\n\t\t\t\t\"int64-1\", int64(1),\n\t\t\t\t\"int64-2\", int64(1),\n\t\t\t\t\"float64\", float64(1.0),\n\t\t\t\t\"string1\", \"\\n\",\n\t\t\t\t\"string2\", \"💩\",\n\t\t\t\t\"string3\", \"🤔\",\n\t\t\t\t\"string4\", \"🙊\",\n\t\t\t\t\"bool\", true,\n\t\t\t\t\"request\", struct {\n\t\t\t\t\tMethod  string `json:\"method\"`\n\t\t\t\t\tTimeout int    `json:\"timeout\"`\n\t\t\t\t\tsecret  string `json:\"secret\"`\n\t\t\t\t}{\n\t\t\t\t\tMethod:  \"GET\",\n\t\t\t\t\tTimeout: 10,\n\t\t\t\t\tsecret:  \"pony\",\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t})\n}\n<commit_msg>Cleanup json logging benchmarks<commit_after>\/*\nCopyright 2020 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage logs\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"go.uber.org\/zap\/zapcore\"\n)\n\nfunc BenchmarkInfoLoggerInfo(b *testing.B) {\n\tlogger := NewJSONLogger(zapcore.AddSync(&writeSyncer{}))\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tlogger.Info(\"test\",\n\t\t\t\t\"str\", \"foo\",\n\t\t\t\t\"int64-1\", int64(1),\n\t\t\t\t\"int64-2\", int64(1),\n\t\t\t\t\"float64\", float64(1.0),\n\t\t\t\t\"string1\", \"\\n\",\n\t\t\t\t\"string2\", \"💩\",\n\t\t\t\t\"string3\", \"🤔\",\n\t\t\t\t\"string4\", \"🙊\",\n\t\t\t\t\"bool\", true,\n\t\t\t\t\"request\", struct {\n\t\t\t\t\tMethod  string `json:\"method\"`\n\t\t\t\t\tTimeout int    `json:\"timeout\"`\n\t\t\t\t\tsecret  string `json:\"secret\"`\n\t\t\t\t}{\n\t\t\t\t\tMethod:  \"GET\",\n\t\t\t\t\tTimeout: 10,\n\t\t\t\t\tsecret:  \"pony\",\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t})\n}\n\nfunc BenchmarkZapLoggerError(b *testing.B) {\n\tlogger := NewJSONLogger(zapcore.AddSync(&writeSyncer{}))\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tlogger.Error(fmt.Errorf(\"test for error:%s\", \"default\"),\n\t\t\t\t\"test\",\n\t\t\t\t\"str\", \"foo\",\n\t\t\t\t\"int64-1\", int64(1),\n\t\t\t\t\"int64-2\", int64(1),\n\t\t\t\t\"float64\", float64(1.0),\n\t\t\t\t\"string1\", \"\\n\",\n\t\t\t\t\"string2\", \"💩\",\n\t\t\t\t\"string3\", \"🤔\",\n\t\t\t\t\"string4\", \"🙊\",\n\t\t\t\t\"bool\", true,\n\t\t\t\t\"request\", struct {\n\t\t\t\t\tMethod  string `json:\"method\"`\n\t\t\t\t\tTimeout int    `json:\"timeout\"`\n\t\t\t\t\tsecret  string `json:\"secret\"`\n\t\t\t\t}{\n\t\t\t\t\tMethod:  \"GET\",\n\t\t\t\t\tTimeout: 10,\n\t\t\t\t\tsecret:  \"pony\",\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t})\n}\n\nfunc BenchmarkZapLoggerV(b *testing.B) {\n\tlogger := NewJSONLogger(zapcore.AddSync(&writeSyncer{}))\n\tb.ResetTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tlogger.V(1).Info(\"test\",\n\t\t\t\t\"str\", \"foo\",\n\t\t\t\t\"int64-1\", int64(1),\n\t\t\t\t\"int64-2\", int64(1),\n\t\t\t\t\"float64\", float64(1.0),\n\t\t\t\t\"string1\", \"\\n\",\n\t\t\t\t\"string2\", \"💩\",\n\t\t\t\t\"string3\", \"🤔\",\n\t\t\t\t\"string4\", \"🙊\",\n\t\t\t\t\"bool\", true,\n\t\t\t\t\"request\", struct {\n\t\t\t\t\tMethod  string `json:\"method\"`\n\t\t\t\t\tTimeout int    `json:\"timeout\"`\n\t\t\t\t\tsecret  string `json:\"secret\"`\n\t\t\t\t}{\n\t\t\t\t\tMethod:  \"GET\",\n\t\t\t\t\tTimeout: 10,\n\t\t\t\t\tsecret:  \"pony\",\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t})\n}\n\ntype writeSyncer struct{}\n\nvar _ zapcore.WriteSyncer = (*writeSyncer)(nil)\n\nfunc (w writeSyncer) Write(p []byte) (n int, err error) {\n\treturn len(p), nil\n}\n\nfunc (w writeSyncer) Sync() error {\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package stemcell\n\nimport (\n\tbosherr \"github.com\/cloudfoundry\/bosh-utils\/errors\"\n\tboshlog \"github.com\/cloudfoundry\/bosh-utils\/logger\"\n\n\t\"fmt\"\n\tsl \"github.com\/maximilien\/softlayer-go\/softlayer\"\n)\n\ntype SoftLayerFinder struct {\n\tclient sl.Client\n\tlogger boshlog.Logger\n}\n\nfunc NewSoftLayerFinder(client sl.Client, logger boshlog.Logger) SoftLayerFinder {\n\treturn SoftLayerFinder{client: client, logger: logger}\n}\n\nfunc (f SoftLayerFinder) FindById(id int) (Stemcell, bool, error) {\n\taccountService, err := f.client.GetSoftLayer_Account_Service()\n\tif err != nil {\n\t\treturn nil, false, bosherr.WrapError(err, \"Getting SoftLayer AccountService\")\n\t}\n\n\tstemcell, found, err := f.findByIdInVirtualDiskImages(id, accountService)\n\tif err != nil {\n\t\treturn stemcell, found, err\n\t}\n\n\tif found {\n\t\treturn stemcell, found, nil\n\t} else {\n\t\tstemcell, found, err = f.findByIdInVirtualGuestDeviceTemplateGroups(id, accountService)\n\t\tif err != nil {\n\t\t\treturn stemcell, found, err\n\t\t}\n\t}\n\n\treturn stemcell, found, nil\n}\n\nfunc (f SoftLayerFinder) Find(uuid string) (Stemcell, bool, error) {\n\taccountService, err := f.client.GetSoftLayer_Account_Service()\n\tif err != nil {\n\t\treturn nil, false, bosherr.WrapError(err, \"Getting SoftLayer AccountService\")\n\t}\n\n\tstemcell, found, err := f.findInVirtualDiskImages(uuid, accountService)\n\tif err != nil {\n\t\treturn stemcell, found, err\n\t}\n\n\tif found {\n\t\treturn stemcell, found, nil\n\t} else {\n\t\tstemcell, found, err = f.findInVirtualGuestDeviceTemplateGroups(uuid, accountService)\n\t\tif err != nil {\n\t\t\treturn stemcell, found, err\n\t\t}\n\t}\n\n\treturn stemcell, found, nil\n}\n\nfunc (f SoftLayerFinder) findInVirtualDiskImages(uuid string, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {\n\tfilters := fmt.Sprintf(`{\"virtualDiskImages\":{\"uuid\":{\"operation\":\"%s\"}}}`, uuid)\n\tvirtualDiskImages, err := accountService.GetVirtualDiskImagesWithFilter(filters)\n\tif err != nil {\n\t\treturn nil, false, bosherr.WrapError(err, \"Getting virtual disk images\")\n\t}\n\n\tfor _, vdImage := range virtualDiskImages {\n\t\tif vdImage.Uuid == uuid {\n\t\t\treturn NewSoftLayerStemcell(vdImage.Id, vdImage.Uuid, VirtualDiskImageKind, f.client, f.logger), true, nil\n\t\t}\n\t}\n\n\treturn nil, false, nil\n}\n\nfunc (f SoftLayerFinder) findByIdInVirtualDiskImages(id int, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {\n\tfilters := fmt.Sprintf(`{\"virtualDiskImages\":{\"id\":{\"operation\":\"%d\"}}}`, id)\n\tvirtualDiskImages, err := accountService.GetVirtualDiskImagesWithFilter(filters)\n\tif err != nil {\n\t\treturn nil, false, bosherr.WrapError(err, \"Getting virtual disk images\")\n\t}\n\n\tfor _, vdImage := range virtualDiskImages {\n\t\tif vdImage.Id == id {\n\t\t\treturn NewSoftLayerStemcell(vdImage.Id, vdImage.Uuid, VirtualDiskImageKind, f.client, f.logger), true, nil\n\t\t}\n\t}\n\n\treturn nil, false, nil\n}\n\nfunc (f SoftLayerFinder) findInVirtualGuestDeviceTemplateGroups(uuid string, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {\n\tfilters := fmt.Sprintf(`\"blockDeviceTemplateGroups\":{\"globalIdentifier\":{\"operation\":\"%s\"}}}`, uuid)\n\tvgdtgGroups, err := accountService.GetBlockDeviceTemplateGroupsWithFilter(filters)\n\tif err != nil {\n\t\treturn nil, false, bosherr.WrapError(err, \"Getting virtual guest device template groups\")\n\t}\n\n\tfor _, vgdtgGroup := range vgdtgGroups {\n\t\tif vgdtgGroup.GlobalIdentifier == uuid {\n\t\t\treturn NewSoftLayerStemcell(vgdtgGroup.Id, vgdtgGroup.GlobalIdentifier, VirtualGuestDeviceTemplateGroupKind, f.client, f.logger), true, nil\n\t\t}\n\t}\n\n\treturn nil, false, nil\n}\n\nfunc (f SoftLayerFinder) findByIdInVirtualGuestDeviceTemplateGroups(id int, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {\n\tfilters := fmt.Sprintf(`\"blockDeviceTemplateGroups\":{\"accountId\":{\"operation\":\"%d\"}}}`, id)\n\tvgdtgGroups, err := accountService.GetBlockDeviceTemplateGroupsWithFilter(filters)\n\tif err != nil {\n\t\treturn nil, false, bosherr.WrapError(err, \"Getting virtual guest device template groups\")\n\t}\n\n\tfor _, vgdtgGroup := range vgdtgGroups {\n\t\tif vgdtgGroup.Id == id {\n\t\t\treturn NewSoftLayerStemcell(vgdtgGroup.Id, vgdtgGroup.GlobalIdentifier, VirtualGuestDeviceTemplateGroupKind, f.client, f.logger), true, nil\n\t\t}\n\t}\n\n\treturn nil, false, nil\n}\n<commit_msg>Fixed a bug where to query stemcell with filter<commit_after>package stemcell\n\nimport (\n\tbosherr \"github.com\/cloudfoundry\/bosh-utils\/errors\"\n\tboshlog \"github.com\/cloudfoundry\/bosh-utils\/logger\"\n\n\t\"fmt\"\n\tsl \"github.com\/maximilien\/softlayer-go\/softlayer\"\n)\n\ntype SoftLayerFinder struct {\n\tclient sl.Client\n\tlogger boshlog.Logger\n}\n\nfunc NewSoftLayerFinder(client sl.Client, logger boshlog.Logger) SoftLayerFinder {\n\treturn SoftLayerFinder{client: client, logger: logger}\n}\n\nfunc (f SoftLayerFinder) FindById(id int) (Stemcell, bool, error) {\n\taccountService, err := f.client.GetSoftLayer_Account_Service()\n\tif err != nil {\n\t\treturn nil, false, bosherr.WrapError(err, \"Getting SoftLayer AccountService\")\n\t}\n\n\tstemcell, found, err := f.findByIdInVirtualDiskImages(id, accountService)\n\tif err != nil {\n\t\treturn stemcell, found, err\n\t}\n\n\tif found {\n\t\treturn stemcell, found, nil\n\t} else {\n\t\tstemcell, found, err = f.findByIdInVirtualGuestDeviceTemplateGroups(id, accountService)\n\t\tif err != nil {\n\t\t\treturn stemcell, found, err\n\t\t}\n\t}\n\n\treturn stemcell, found, nil\n}\n\nfunc (f SoftLayerFinder) Find(uuid string) (Stemcell, bool, error) {\n\taccountService, err := f.client.GetSoftLayer_Account_Service()\n\tif err != nil {\n\t\treturn nil, false, bosherr.WrapError(err, \"Getting SoftLayer AccountService\")\n\t}\n\n\tstemcell, found, err := f.findInVirtualDiskImages(uuid, accountService)\n\tif err != nil {\n\t\treturn stemcell, found, err\n\t}\n\n\tif found {\n\t\treturn stemcell, found, nil\n\t} else {\n\t\tstemcell, found, err = f.findInVirtualGuestDeviceTemplateGroups(uuid, accountService)\n\t\tif err != nil {\n\t\t\treturn stemcell, found, err\n\t\t}\n\t}\n\n\treturn stemcell, found, nil\n}\n\nfunc (f SoftLayerFinder) findInVirtualDiskImages(uuid string, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {\n\tfilters := fmt.Sprintf(`{\"virtualDiskImages\":{\"uuid\":{\"operation\":\"%s\"}}}`, uuid)\n\tvirtualDiskImages, err := accountService.GetVirtualDiskImagesWithFilter(filters)\n\tif err != nil {\n\t\treturn nil, false, bosherr.WrapError(err, \"Getting virtual disk images\")\n\t}\n\n\tfor _, vdImage := range virtualDiskImages {\n\t\tif vdImage.Uuid == uuid {\n\t\t\treturn NewSoftLayerStemcell(vdImage.Id, vdImage.Uuid, VirtualDiskImageKind, f.client, f.logger), true, nil\n\t\t}\n\t}\n\n\treturn nil, false, nil\n}\n\nfunc (f SoftLayerFinder) findByIdInVirtualDiskImages(id int, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {\n\tfilters := fmt.Sprintf(`{\"virtualDiskImages\":{\"id\":{\"operation\":\"%d\"}}}`, id)\n\tvirtualDiskImages, err := accountService.GetVirtualDiskImagesWithFilter(filters)\n\tif err != nil {\n\t\treturn nil, false, bosherr.WrapError(err, \"Getting virtual disk images\")\n\t}\n\n\tfor _, vdImage := range virtualDiskImages {\n\t\tif vdImage.Id == id {\n\t\t\treturn NewSoftLayerStemcell(vdImage.Id, vdImage.Uuid, VirtualDiskImageKind, f.client, f.logger), true, nil\n\t\t}\n\t}\n\n\treturn nil, false, nil\n}\n\nfunc (f SoftLayerFinder) findInVirtualGuestDeviceTemplateGroups(uuid string, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {\n\tfilters := fmt.Sprintf(`{\"blockDeviceTemplateGroups\":{\"globalIdentifier\":{\"operation\":\"%s\"}}}`, uuid)\n\tvgdtgGroups, err := accountService.GetBlockDeviceTemplateGroupsWithFilter(filters)\n\tif err != nil {\n\t\treturn nil, false, bosherr.WrapError(err, \"Getting virtual guest device template groups\")\n\t}\n\n\tfor _, vgdtgGroup := range vgdtgGroups {\n\t\tif vgdtgGroup.GlobalIdentifier == uuid {\n\t\t\treturn NewSoftLayerStemcell(vgdtgGroup.Id, vgdtgGroup.GlobalIdentifier, VirtualGuestDeviceTemplateGroupKind, f.client, f.logger), true, nil\n\t\t}\n\t}\n\n\treturn nil, false, nil\n}\n\nfunc (f SoftLayerFinder) findByIdInVirtualGuestDeviceTemplateGroups(id int, accountService sl.SoftLayer_Account_Service) (Stemcell, bool, error) {\n\tfilters := fmt.Sprintf(`{\"blockDeviceTemplateGroups\":{\"id\":{\"operation\":\"%d\"}}}`, id)\n\tvgdtgGroups, err := accountService.GetBlockDeviceTemplateGroupsWithFilter(filters)\n\tif err != nil {\n\t\treturn nil, false, bosherr.WrapError(err, \"Getting virtual guest device template groups\")\n\t}\n\n\tfor _, vgdtgGroup := range vgdtgGroups {\n\t\tif vgdtgGroup.Id == id {\n\t\t\treturn NewSoftLayerStemcell(vgdtgGroup.Id, vgdtgGroup.GlobalIdentifier, VirtualGuestDeviceTemplateGroupKind, f.client, f.logger), true, nil\n\t\t}\n\t}\n\n\treturn nil, false, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package ast\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/elliotchance\/c2go\/util\"\n)\n\nfunc formatMultiLine(o interface{}) string {\n\ts := fmt.Sprintf(\"%#v\", o)\n\ts = strings.Replace(s, \"{\", \"{\\n\", -1)\n\ts = strings.Replace(s, \", \", \"\\n\", -1)\n\n\treturn s\n}\n\nfunc runNodeTests(t *testing.T, tests map[string]Node) {\n\ti := 1\n\tfor line, expected := range tests {\n\t\ttestName := fmt.Sprintf(\"Example%d\", i)\n\t\ti++\n\n\t\tt.Run(testName, func(t *testing.T) {\n\t\t\t\/\/ Append the name of the struct onto the front. This would make the\n\t\t\t\/\/ complete line it would normally be parsing.\n\t\t\tname := reflect.TypeOf(expected).Elem().Name()\n\t\t\tactual := Parse(name + \" \" + line)\n\n\t\t\tif !reflect.DeepEqual(expected, actual) {\n\t\t\t\tt.Errorf(\"%s\", util.ShowDiff(formatMultiLine(expected),\n\t\t\t\t\tformatMultiLine(actual)))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestPrint(t *testing.T) {\n\tcond := &ConditionalOperator{}\n\tcond.AddChild(&ImplicitCastExpr{})\n\tcond.AddChild(&ImplicitCastExpr{})\n\ts := Atos(cond)\n\tif len(s) == 0 {\n\t\tt.Fatalf(\"Cannot convert AST tree : %#v\", cond)\n\t}\n\tlines := strings.Split(s, \"\\n\")\n\tvar amount int\n\tfor _, l := range lines {\n\t\tif strings.Contains(l, \"ImplicitCastExpr\") {\n\t\t\tamount++\n\t\t}\n\t}\n\tif amount != 2 {\n\t\tt.Error(\"Not correct design of output\")\n\t}\n}\n\nvar lines = []string{\n\t\/\/ c2go ast sqlite3.c | head -5000 | sed 's\/^[ |`-]*\/\/' | sed 's\/<<<NULL>>>\/NullStmt\/g' | gawk 'length > 0 {print \"`\" $0 \"`,\"}'\n}\n\nfunc BenchmarkParse(b *testing.B) {\n\tfor n := 0; n < b.N; n++ {\n\t\tfor _, line := range lines {\n\t\t\tParse(line)\n\t\t}\n\t}\n}\n<commit_msg>Revert \"gofmt (#751)\". Fixes #757 (#758)<commit_after>package ast\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/elliotchance\/c2go\/util\"\n)\n\nfunc formatMultiLine(o interface{}) string {\n\ts := fmt.Sprintf(\"%#v\", o)\n\ts = strings.Replace(s, \"{\", \"{\\n\", -1)\n\ts = strings.Replace(s, \", \", \"\\n\", -1)\n\n\treturn s\n}\n\nfunc runNodeTests(t *testing.T, tests map[string]Node) {\n\ti := 1\n\tfor line, expected := range tests {\n\t\ttestName := fmt.Sprintf(\"Example%d\", i)\n\t\ti++\n\n\t\tt.Run(testName, func(t *testing.T) {\n\t\t\t\/\/ Append the name of the struct onto the front. This would make the\n\t\t\t\/\/ complete line it would normally be parsing.\n\t\t\tname := reflect.TypeOf(expected).Elem().Name()\n\t\t\tactual := Parse(name + \" \" + line)\n\n\t\t\tif !reflect.DeepEqual(expected, actual) {\n\t\t\t\tt.Errorf(\"%s\", util.ShowDiff(formatMultiLine(expected),\n\t\t\t\t\tformatMultiLine(actual)))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestPrint(t *testing.T) {\n\tcond := &ConditionalOperator{}\n\tcond.AddChild(&ImplicitCastExpr{})\n\tcond.AddChild(&ImplicitCastExpr{})\n\ts := Atos(cond)\n\tif len(s) == 0 {\n\t\tt.Fatalf(\"Cannot convert AST tree : %#v\", cond)\n\t}\n\tlines := strings.Split(s, \"\\n\")\n\tvar amount int\n\tfor _, l := range lines {\n\t\tif strings.Contains(l, \"ImplicitCastExpr\") {\n\t\t\tamount++\n\t\t}\n\t}\n\tif amount != 2 {\n\t\tt.Error(\"Not correct design of output\")\n\t}\n}\n\nvar lines = []string{\n\/\/ c2go ast sqlite3.c | head -5000 | sed 's\/^[ |`-]*\/\/' | sed 's\/<<<NULL>>>\/NullStmt\/g' | gawk 'length > 0 {print \"`\" $0 \"`,\"}'\n}\n\nfunc BenchmarkParse(b *testing.B) {\n\tfor n := 0; n < b.N; n++ {\n\t\tfor _, line := range lines {\n\t\t\tParse(line)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Koichi Shiraishi. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage context\n\nimport (\n\t\"go\/build\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"sync\"\n)\n\n\/\/ A Context specifies the supporting context for a build and embedded\n\/\/ build.Context type struct.\ntype Build struct {\n\tTool string\n\tbuild.Context\n}\n\n\/\/ GoPath return the new GOPATH estimated from the path p directory structure.\nfunc (ctxt *Build) buildContext(p string) (string, string) {\n\ttool := \"go\"\n\n\t\/\/ Get original $GOPATH path.\n\tgoPath := os.Getenv(\"GOPATH\")\n\n\t\/\/ Get runtime $GOROOT path and join to goPath.\n\tr := runtime.GOROOT()\n\tif r != \"\" {\n\t\tgoPath = goPath + string(filepath.ListSeparator) + r\n\t}\n\n\t\/\/ Cleanup directory path.\n\tp = filepath.Clean(p)\n\n\t\/\/ Check the path p are Gb directory structure.\n\t\/\/ If yes, append gb root and vendor path to the goPath lists.\n\tif gbpath, yes := ctxt.isGb(p); yes {\n\t\tgoPath = gbpath + string(filepath.ListSeparator) +\n\t\t\tfilepath.Join(gbpath, \"vendor\") + string(filepath.ListSeparator) +\n\t\t\tgoPath\n\t\ttool = \"gb\"\n\t}\n\n\treturn goPath, tool\n}\n\n\/\/ isGb return the gb package root path if p is gb project directory structure.\nfunc (ctxt *Build) isGb(p string) (string, bool) {\n\tctxt.Context = build.Default\n\n\tvar pkgRoot string\n\tfor {\n\t\tpkg, err := ctxt.ImportDir(p, build.IgnoreVendor)\n\t\tif err != nil {\n\t\t\treturn \"\", err != nil\n\t\t\tbreak\n\t\t}\n\n\t\tif pkg.Name == \"main\" {\n\t\t\tpkgRoot = pkg.Dir\n\t\t\tbreak\n\t\t}\n\t\tp = filepath.Dir(p)\n\t\tcontinue\n\t}\n\n\t\/\/ gb project directory is `..\/..\/pkgRoot`\n\tprojRoot, src := filepath.Split(filepath.Dir(pkgRoot))\n\n\tmanifest := filepath.Join(filepath.Clean(projRoot), \"vendor\/manifest\")\n\t_, err := os.Stat(manifest)\n\n\treturn filepath.Clean(projRoot), (err == nil && src == \"src\")\n}\n\n\/\/ contextMu Mutex lock for SetContext.\nvar contextMu sync.Mutex\n\n\/\/ SetContext sets the go\/build Default.GOPATH and $GOPATH to GoPath(p)\n\/\/ under a mutex.\n\/\/ The returned function restores Default.GOPATH to its original value and\n\/\/ unlocks the mutex.\n\/\/\n\/\/ This function intended to be used to the go\/build Default.\nfunc (c *Build) SetContext(p string) func() {\n\tcontextMu.Lock()\n\toriginal := build.Default.GOPATH\n\n\tbuild.Default.GOPATH, c.Tool = c.buildContext(p)\n\tos.Setenv(\"GOPATH\", build.Default.GOPATH)\n\n\treturn func() {\n\t\tbuild.Default.GOPATH = original\n\t\tos.Setenv(\"GOPATH\", build.Default.GOPATH)\n\t\tcontextMu.Unlock()\n\t}\n}\n<commit_msg>Fix isGo break timing is pkg.Name == 'main' or rootDir == pkg.Dir<commit_after>\/\/ Copyright 2016 Koichi Shiraishi. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage context\n\nimport (\n\t\"go\/build\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"sync\"\n)\n\n\/\/ A Context specifies the supporting context for a build and embedded\n\/\/ build.Context type struct.\ntype Build struct {\n\tTool string\n\tbuild.Context\n}\n\n\/\/ GoPath return the new GOPATH estimated from the path p directory structure.\nfunc (ctxt *Build) buildContext(p string) (string, string) {\n\ttool := \"go\"\n\n\t\/\/ Get original $GOPATH path.\n\tgoPath := os.Getenv(\"GOPATH\")\n\n\t\/\/ Get runtime $GOROOT path and join to goPath.\n\tr := runtime.GOROOT()\n\tif r != \"\" {\n\t\tgoPath = goPath + string(filepath.ListSeparator) + r\n\t}\n\n\t\/\/ Cleanup directory path.\n\tp = filepath.Clean(p)\n\n\t\/\/ Check the path p are Gb directory structure.\n\t\/\/ If yes, append gb root and vendor path to the goPath lists.\n\tif gbpath, yes := ctxt.isGb(p); yes {\n\t\tgoPath = gbpath + string(filepath.ListSeparator) +\n\t\t\tfilepath.Join(gbpath, \"vendor\") + string(filepath.ListSeparator) +\n\t\t\tgoPath\n\t\ttool = \"gb\"\n\t}\n\n\treturn goPath, tool\n}\n\n\/\/ isGb return the gb package root path if p is gb project directory structure.\nfunc (ctxt *Build) isGb(p string) (string, bool) {\n\tctxt.Context = build.Default\n\n\tvar pkgRoot string\n\tfor {\n\t\tpkg, _ := ctxt.ImportDir(p, build.IgnoreVendor)\n\t\trootDir := FindVcsRoot(p)\n\n\t\tif pkg.Name == \"main\" || rootDir == pkg.Dir {\n\t\t\tpkgRoot = pkg.Dir\n\t\t\tbreak\n\t\t}\n\t\tp = filepath.Dir(p)\n\t\tcontinue\n\t}\n\n\t\/\/ gb project directory is `..\/..\/pkgRoot`\n\tprojRoot, src := filepath.Split(filepath.Dir(pkgRoot))\n\n\tmanifest := filepath.Join(filepath.Clean(projRoot), \"vendor\/manifest\")\n\t_, err := os.Stat(manifest)\n\n\treturn filepath.Clean(projRoot), (err == nil && src == \"src\")\n}\n\n\/\/ contextMu Mutex lock for SetContext.\nvar contextMu sync.Mutex\n\n\/\/ SetContext sets the go\/build Default.GOPATH and $GOPATH to GoPath(p)\n\/\/ under a mutex.\n\/\/ The returned function restores Default.GOPATH to its original value and\n\/\/ unlocks the mutex.\n\/\/\n\/\/ This function intended to be used to the go\/build Default.\nfunc (c *Build) SetContext(p string) func() {\n\tcontextMu.Lock()\n\toriginal := build.Default.GOPATH\n\n\tbuild.Default.GOPATH, c.Tool = c.buildContext(p)\n\tos.Setenv(\"GOPATH\", build.Default.GOPATH)\n\n\treturn func() {\n\t\tbuild.Default.GOPATH = original\n\t\tos.Setenv(\"GOPATH\", build.Default.GOPATH)\n\t\tcontextMu.Unlock()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t. \"github.com\/eaciit\/hdc\/hive\"\n\t\"time\"\n)\n\nvar h *Hive\nvar q string\n\ntype Sample7 struct {\n\tCode        string `tag_name:\"code\"`\n\tDescription string `tag_name:\"description\"`\n\tTotal_emp   int    `tag_name:\"total_emp\"`\n\tSalary      int    `tag_name:\"salary\"`\n}\n\ntype SampleParse struct {\n\tCode        string    `tag_name:\"code\"`\n\tDescription string    `tag_name:\"description\"`\n\tTotal_emp   int       `tag_name:\"total_emp\"`\n\tSalary      int       `tag_name:\"salary\"`\n\tDate        time.Time `tag_name:\"date\"`\n}\n\nfunc main() {\n\th = HiveConfig(\"192.168.0.223:10000\", \"default\", \"developer\", \"b1gD@T@\", \"\")\n\tq = \"select * from sample_07 limit 20;\"\n\n\t\/\/for now this function just provide  csv type\n\tTestParseOutput()\n\n\t\/\/Exec Query and Process with DoSomething Function PerLine | EXECPERLINE only support for csv or tsv\n\th.OutputType = \"csv\"\n\tTestExecPerLine()\n\n\t\/\/ Exec Query and wait until all line fetched | EXEC only support for csv or tsv\n\th.OutputType = \"tsv\"\n\tTestExec()\n}\n\nfunc DoSomething(res string) {\n\ttmp := Sample7{}\n\th.ParseOutput(res, &tmp)\n\tfmt.Println(tmp)\n}\n\nfunc TestExec() {\n\tres, e := h.Exec(q)\n\n\tif e != nil {\n\t\tfmt.Printf(\"error: \\n%v\\n\", e)\n\t} else {\n\t\tfmt.Println(res)\n\t}\n}\n\nfunc TestExecPerLine() {\n\te := h.ExecLine(q, DoSomething)\n\n\tif e != nil {\n\t\tfmt.Printf(\"error: \\n%v\\n\", e)\n\t}\n}\n\nfunc TestParseOutput() {\n\th.Header = []string{\"code\", \"description\", \"total_emp\", \"salary\", \"Date\"}\n\n\th.OutputType = \"csv\"\n\th.DateFormat = \"YYYY-MM-DD\"\n\tres := \"'00-0000','All Occupations CSV','134354250','40690','2014-05-01'\"\n\ttmp := SampleParse{}\n\th.ParseOutput(res, &tmp)\n\tfmt.Println(tmp)\n\n\th.OutputType = \"tsv\"\n\th.DateFormat = \"YYYY-MMM-DD\"\n\tres = \"00-0000\\tAll Occupations TSV\\t134354250\\t40690\\t2014-Dec-05\"\n\ttmp = SampleParse{}\n\th.ParseOutput(res, &tmp)\n\tfmt.Println(tmp)\n\n\th.OutputType = \"json\"\n\tres = \"{ \\\"code\\\" : \\\"00-0000\\\" , \\\"description\\\" : \\\"All Occupations JSON\\\", \\\"total_emp\\\" : 134354, \\\"salary\\\" : 40690,\\\"Date\\\" : \\\"2012-04-23T18:25:43Z\\\" }\"\n\ttmp = SampleParse{}\n\th.ParseOutput(res, &tmp)\n\tfmt.Println(tmp)\n}\n<commit_msg>detect data type parse out<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t. \"github.com\/eaciit\/hdc\/hive\"\n\t\"time\"\n)\n\nvar h *Hive\nvar q string\n\ntype Sample7 struct {\n\tCode        string `tag_name:\"code\"`\n\tDescription string `tag_name:\"description\"`\n\tTotal_emp   int    `tag_name:\"total_emp\"`\n\tSalary      int    `tag_name:\"salary\"`\n}\n\ntype SampleParse struct {\n\tCode        string    `tag_name:\"code\"`\n\tDescription string    `tag_name:\"description\"`\n\tTotal_emp   int       `tag_name:\"total_emp\"`\n\tSalary      int       `tag_name:\"salary\"`\n\tDate        time.Time `tag_name:\"date\"`\n}\n\nfunc main() {\n\th = HiveConfig(\"192.168.0.223:10000\", \"default\", \"developer\", \"b1gD@T@\", \"\")\n\tq = \"select * from sample_07 limit 20;\"\n\n\t\/\/for now this function just provide  csv type\n\tTestParseOutput()\n\n\t\/\/Exec Query and Process with DoSomething Function PerLine | EXECPERLINE only support for csv or tsv\n\th.OutputType = \"csv\"\n\tTestExecPerLine()\n\n\t\/\/ Exec Query and wait until all line fetched | EXEC only support for csv or tsv\n\th.OutputType = \"tsv\"\n\tTestExec()\n}\n\nfunc DoSomething(res string) {\n\ttmp := Sample7{}\n\th.ParseOutput(res, &tmp)\n\tfmt.Println(tmp)\n}\n\nfunc TestExec() {\n\tres, e := h.Exec(q)\n\n\tif e != nil {\n\t\tfmt.Printf(\"error: \\n%v\\n\", e)\n\t} else {\n\t\tfmt.Println(res)\n\t}\n}\n\nfunc TestExecPerLine() {\n\te := h.ExecLine(q, DoSomething)\n\n\tif e != nil {\n\t\tfmt.Printf(\"error: \\n%v\\n\", e)\n\t}\n}\n\nfunc TestParseOutput() {\n\th.Header = []string{\"code\", \"description\", \"total_emp\", \"salary\", \"Date\"}\n\n\th.OutputType = \"csv\"\n\th.DateFormat = \"YYYY-MM-DD\"\n\tres := \"'00-0000','All Occupations CSV','134354250','40690','2014-05-01'\"\n\ttmp := SampleParse{}\n\th.ParseOutput(res, &tmp)\n\tfmt.Println(tmp)\n\n\th.OutputType = \"tsv\"\n\th.DateFormat = \"YYYY-MMM-DD\"\n\tres = \"00-0000\\tAll Occupations TSV\\t134354250\\t40690\\t2014-Dec-05\"\n\ttmp = SampleParse{}\n\th.ParseOutput(res, &tmp)\n\tfmt.Println(tmp)\n\n\t\/\/try to parse json with different line\n\th.OutputType = \"json\"\n\tres = \"{ \\\"code\\\" : \\\"00-0000\\\" , \\\"description\\\" : \\\"All Occupations JSON\\\" \"\n\ttmp = SampleParse{}\n\th.ParseOutput(res, &tmp)\n\tfmt.Println(tmp)\n\n\tres = \", \\\"total_emp\\\" : 134354, \\\"salary\\\" : 40690,\\\"Date\\\" : \\\"2012-04-23T18:25:43Z\\\" }\"\n\ttmp = SampleParse{}\n\th.ParseOutput(res, &tmp)\n\tfmt.Println(tmp)\n}\n<|endoftext|>"}
{"text":"<commit_before>package libaudit\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"syscall\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ EventCallback is the function signature for any function that wants to receive an AuditEvent as soon as\n\/\/ it is received from the kernel. Error channel will be used to indicate any error that happens while receiving\n\/\/ messages.\ntype EventCallback func(*AuditEvent, chan error, ...interface{})\n\n\/\/ RawEventCallback is similar to EventCallback and provides a function signature but the difference is that the function\n\/\/ will receive only the message string which contains the audit event and not the parsed AuditEvent struct.\ntype RawEventCallback func(string, chan error, ...interface{})\n\n\/\/ AuditEvent holds a parsed audit message.\n\/\/ Serial holds the serial number for the message.\n\/\/ Timestamp holds the unix timestamp of the message.\n\/\/ Type indicates the type of the audit message.\n\/\/ Data holds a map of field values of audit messages where keys => field names and values => field values.\n\/\/ Raw string holds the original audit message received from kernel.\ntype AuditEvent struct {\n\tSerial    string\n\tTimestamp string\n\tType      string\n\tData      map[string]string\n\tRaw       string\n}\n\n\/\/NewAuditEvent takes a NetlinkMessage passed from the netlink connection\n\/\/and parses the data from the message header to return an AuditEvent struct.\nfunc NewAuditEvent(msg NetlinkMessage) (*AuditEvent, error) {\n\tx, err := ParseAuditEvent(string(msg.Data[:]), auditConstant(msg.Header.Type), true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif (*x).Type == \"auditConstant(\"+strconv.Itoa(int(msg.Header.Type))+\")\" {\n\t\treturn nil, fmt.Errorf(\"NewAuditEvent failed: unknown message type %d\", msg.Header.Type)\n\t}\n\n\treturn x, nil\n}\n\n\/\/ GetAuditEvents receives audit messages from the kernel and parses them to AuditEvent struct.\n\/\/ It passes them along the callback function and the error channel is used to indicate any error that happens while\n\/\/ receiving the message. Code that receives the message runs inside a go-routine.\n\/\/ Please note that error channel is not a buffered one and client should provide a routine on their side that continously\n\/\/ empties it, otherwise the call will be blocked for eg at : ec <- fmt.Errorf(\"error receiving events -%d\", err)\n\/\/ and the message recpetion will be blocked\nfunc GetAuditEvents(s *NetlinkConnection, cb EventCallback, ec chan error, args ...interface{}) {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tdefault:\n\t\t\t\tmsgs, _ := s.Receive(syscall.NLMSG_HDRLEN+MAX_AUDIT_MESSAGE_LENGTH, 0)\n\t\t\t\tfor _, msg := range msgs {\n\t\t\t\t\tif msg.Header.Type == syscall.NLMSG_ERROR {\n\t\t\t\t\t\terr := int32(nativeEndian().Uint32(msg.Data[0:4]))\n\t\t\t\t\t\tif err != 0 {\n\t\t\t\t\t\t\tec <- fmt.Errorf(\"error receiving events -%d\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnae, err := NewAuditEvent(msg)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tec <- err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcb(nae, ec, args...)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\/\/ GetRawAuditEvents receives raw audit messages from kernel parses them to AuditEvent struct.\n\/\/ It passes them along the raw callback function and error channel is to indicate any error that happens while\n\/\/ receiving the message. Code that receives the message runs inside a go-routine.\n\/\/ Please note that error channel is not a buffered one and client should provide a routine on their side that continously\n\/\/ empties it, otherwise the call will be blocked for eg at : ec <- fmt.Errorf(\"error receiving events -%d\", err)\n\/\/ and the message recpetion will be blocked\nfunc GetRawAuditEvents(s *NetlinkConnection, cb RawEventCallback, ec chan error, args ...interface{}) {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tdefault:\n\t\t\t\tmsgs, _ := s.Receive(syscall.NLMSG_HDRLEN+MAX_AUDIT_MESSAGE_LENGTH, 0)\n\t\t\t\tfor _, msg := range msgs {\n\t\t\t\t\tm := \"\"\n\t\t\t\t\tif msg.Header.Type == syscall.NLMSG_ERROR {\n\t\t\t\t\t\terr := int32(nativeEndian().Uint32(msg.Data[0:4]))\n\t\t\t\t\t\tif err != 0 {\n\t\t\t\t\t\t\tec <- fmt.Errorf(\"error receiving events -%d\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tType := auditConstant(msg.Header.Type)\n\t\t\t\t\t\tif Type.String() == \"auditConstant(\"+strconv.Itoa(int(msg.Header.Type))+\")\" {\n\t\t\t\t\t\t\tec <- errors.New(\"Unknown Type: \" + string(msg.Header.Type))\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tm = \"type=\" + Type.String()[6:] + \" msg=\" + string(msg.Data[:]) + \"\\n\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcb(m, ec, args...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\/\/ GetAuditMessages is a blocking function (runs in forever for loop) that\n\/\/ receives audit messages from kernel and parses them to AuditEvent.\n\/\/ It passes them along the callback cb and the error channel is used to indicate any error\n\/\/ that happens while receiving the message.\n\/\/ It will return when a signal is received on the done channel.\n\/\/ Please note that error channel is not a buffered one and client should provide a routine on their side that continously\n\/\/ empties it, otherwise the call will be blocked for eg. at : ec <- fmt.Errorf(\"error receiving events -%d\", err)\n\/\/ and the message recpetion will be blocked\nfunc GetAuditMessages(s *NetlinkConnection, cb EventCallback, ec *chan error, done *chan bool, args ...interface{}) {\n\tfor {\n\t\tselect {\n\t\tcase <-*done:\n\t\t\treturn\n\t\tdefault:\n\t\t\tmsgs, _ := s.Receive(syscall.NLMSG_HDRLEN+MAX_AUDIT_MESSAGE_LENGTH, 0)\n\t\t\tfor _, msg := range msgs {\n\t\t\t\tif msg.Header.Type == syscall.NLMSG_ERROR {\n\t\t\t\t\terr := int32(nativeEndian().Uint32(msg.Data[0:4]))\n\t\t\t\t\tif err != 0 {\n\t\t\t\t\t\t*ec <- fmt.Errorf(\"error receiving events -%d\", err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnae, err := NewAuditEvent(msg)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t*ec <- err\n\t\t\t\t\t}\n\t\t\t\t\tcb(nae, *ec, args...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n<commit_msg>Change GetAuditEvent API to avoid passing errors through channels Pass directly to the callbacks instead<commit_after>package libaudit\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"syscall\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ EventCallback is the function signature for any function that wants to receive an AuditEvent as soon as\n\/\/ it is received from the kernel. Error will be set to indicate any error that happens while receiving\n\/\/ messages.\ntype EventCallback func(*AuditEvent, error, ...interface{})\n\n\/\/ RawEventCallback is similar to EventCallback and provides a function signature but the difference is that the function\n\/\/ will receive only the message string which contains the audit event and not the parsed AuditEvent struct.\ntype RawEventCallback func(string, error, ...interface{})\n\n\/\/ AuditEvent holds a parsed audit message.\n\/\/ Serial holds the serial number for the message.\n\/\/ Timestamp holds the unix timestamp of the message.\n\/\/ Type indicates the type of the audit message.\n\/\/ Data holds a map of field values of audit messages where keys => field names and values => field values.\n\/\/ Raw string holds the original audit message received from kernel.\ntype AuditEvent struct {\n\tSerial    string\n\tTimestamp string\n\tType      string\n\tData      map[string]string\n\tRaw       string\n}\n\n\/\/NewAuditEvent takes a NetlinkMessage passed from the netlink connection\n\/\/and parses the data from the message header to return an AuditEvent struct.\nfunc NewAuditEvent(msg NetlinkMessage) (*AuditEvent, error) {\n\tx, err := ParseAuditEvent(string(msg.Data[:]), auditConstant(msg.Header.Type), true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif (*x).Type == \"auditConstant(\"+strconv.Itoa(int(msg.Header.Type))+\")\" {\n\t\treturn nil, fmt.Errorf(\"NewAuditEvent failed: unknown message type %d\", msg.Header.Type)\n\t}\n\n\treturn x, nil\n}\n\n\/\/ GetAuditEvents receives audit messages from the kernel and parses them to AuditEvent struct.\n\/\/ It passes them along the callback function and if any error occurs while receiving the message,\n\/\/ the same will be passed in the callback as well.\n\/\/ Code that receives the message runs inside a go-routine.\nfunc GetAuditEvents(s Netlink, cb EventCallback, args ...interface{}) {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tdefault:\n\t\t\t\tmsgs, _ := s.Receive(syscall.NLMSG_HDRLEN+MAX_AUDIT_MESSAGE_LENGTH, 0)\n\t\t\t\tfor _, msg := range msgs {\n\t\t\t\t\tif msg.Header.Type == syscall.NLMSG_ERROR {\n\t\t\t\t\t\terr := int32(nativeEndian().Uint32(msg.Data[0:4]))\n\t\t\t\t\t\tif err != 0 {\n\t\t\t\t\t\t\tcb(nil, fmt.Errorf(\"error receiving events %d\", err), args...)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnae, err := NewAuditEvent(msg)\n\t\t\t\t\t\tcb(nae, err, args...)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\/\/ GetRawAuditEvents receives raw audit messages from kernel parses them to AuditEvent struct.\n\/\/ It passes them along the callback function and if any error occurs while receiving the message,\n\/\/ the same will be passed in the callback as well.\n\/\/ Code that receives the message runs inside a go-routine.\nfunc GetRawAuditEvents(s Netlink, cb RawEventCallback, args ...interface{}) {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tdefault:\n\t\t\t\tmsgs, _ := s.Receive(syscall.NLMSG_HDRLEN+MAX_AUDIT_MESSAGE_LENGTH, 0)\n\t\t\t\tfor _, msg := range msgs {\n\t\t\t\t\tvar (\n\t\t\t\t\t\tm   string\n\t\t\t\t\t\terr error\n\t\t\t\t\t)\n\t\t\t\t\tif msg.Header.Type == syscall.NLMSG_ERROR {\n\t\t\t\t\t\tv := int32(nativeEndian().Uint32(msg.Data[0:4]))\n\t\t\t\t\t\tif v != 0 {\n\t\t\t\t\t\t\tcb(m, fmt.Errorf(\"error receiving events %d\", v), args...)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tType := auditConstant(msg.Header.Type)\n\t\t\t\t\t\tif Type.String() == \"auditConstant(\"+strconv.Itoa(int(msg.Header.Type))+\")\" {\n\t\t\t\t\t\t\terr = errors.New(\"Unknown Type: \" + string(msg.Header.Type))\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tm = \"type=\" + Type.String()[6:] + \" msg=\" + string(msg.Data[:]) + \"\\n\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcb(m, err, args...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\/\/ GetAuditMessages is a blocking function (runs in forever for loop) that\n\/\/ receives audit messages from kernel and parses them to AuditEvent.\n\/\/ It passes them along the callback function and if any error occurs while receiving the message,\n\/\/ the same will be passed in the callback as well.\n\/\/ It will return when a signal is received on the done channel.\nfunc GetAuditMessages(s Netlink, cb EventCallback, done *chan bool, args ...interface{}) {\n\tfor {\n\t\tselect {\n\t\tcase <-*done:\n\t\t\treturn\n\t\tdefault:\n\t\t\tmsgs, _ := s.Receive(syscall.NLMSG_HDRLEN+MAX_AUDIT_MESSAGE_LENGTH, 0)\n\t\t\tfor _, msg := range msgs {\n\t\t\t\tif msg.Header.Type == syscall.NLMSG_ERROR {\n\t\t\t\t\tv := int32(nativeEndian().Uint32(msg.Data[0:4]))\n\t\t\t\t\tif v != 0 {\n\t\t\t\t\t\tcb(nil, fmt.Errorf(\"error receiving events %d\", v), args...)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnae, err := NewAuditEvent(msg)\n\t\t\t\t\tcb(nae, err, args...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package bothandlers\n\nimport (\n\t\"fmt\"\n\t\"github.com\/djosephsen\/hal\"\n\t\"time\"\n\t\"strings\"\n)\n\nvar ListChores = &hal.Handler{\n\tMethod:  hal.RESPOND,\n\tPattern: `(list chores)|(chore list)`,\n\tRun: func(res *hal.Response) error {\n\t\tvar reply string\n\t\tif len(res.Robot.Chores) == 0{\n\t\t\treply=`No chores have been registered (sorry?)`\n\t\t}else{\n\t\t\treply=`Name  :small_blue_diamond:  Schedule  :small_blue_diamond:  Firing in  :small_blue_diamond: Current State`\n\t\t\tfor _,c := range res.Robot.Chores{\n\t\t\t\treply = fmt.Sprintf(\"%s\\n%s:small_blue_diamond:%s:small_blue_diamond:%v:small_blue_diamond:%s\",reply,c.Name, c.Sched, c.Next.Sub(time.Now()), c.State)\n\t\t\t}\n\t\t}\n\t\treturn res.Reply(reply)\n\t},\n}\n\nvar ListRooms = &hal.Handler{\n\tMethod:  hal.RESPOND,\n\tPattern: `(what room)|(list *room)|(room *list)`,\n\tRun: func(res *hal.Response) error {\n\t\troom := res.Message.Room\n\t\treply := fmt.Sprintf(\"Current room is: %s\",room)\n\t\treturn res.Send(reply)\n\t},\n}\n\nvar StopChore = &hal.Handler{\n\tMethod:  hal.RESPOND,\n\tPattern: `(stop chore)|(chore stop)`,\n\tRun: func(res *hal.Response) error {\n\t\tvar reply string\n\t\tcname:=strings.SplitAfterN(res.Match[0],` `,3)\n\t\tc:=hal.GetChoreByName(cname[2],res.Robot)\n\t\thal.KillChore(c)\n\t\treply = fmt.Sprintf(\"%s\\n%s:small_blue_diamond:%s:small_blue_diamond:%v:small_blue_diamond:%s\",reply,c.Name, c.Sched, c.Next.Sub(time.Now()), c.State)\n\t\treturn res.Reply(reply)\n\t},\n}\n<commit_msg>adding a chore kill command<commit_after>package bothandlers\n\nimport (\n\t\"fmt\"\n\t\"github.com\/djosephsen\/hal\"\n\t\"time\"\n\t\"strings\"\n)\n\nvar ListRooms = &hal.Handler{\n\tMethod:  hal.RESPOND,\n\tPattern: `(what room)|(list *room)|(room *list)`,\n\tRun: func(res *hal.Response) error {\n\t\troom := res.Message.Room\n\t\treply := fmt.Sprintf(\"Current room is: %s\",room)\n\t\treturn res.Send(reply)\n\t},\n}\n\n\nvar ListChores = &hal.Handler{\n\tMethod:  hal.RESPOND,\n\tPattern: `(list chores)|(chore list)`,\n\tRun: func(res *hal.Response) error {\n\t\tvar reply string\n\t\tif len(res.Robot.Chores) == 0{\n\t\t\treply=`No chores have been registered (sorry?)`\n\t\t}else{\n\t\t\treply=`Name  :small_blue_diamond:  Schedule  :small_blue_diamond:  Firing in  :small_blue_diamond: Current State`\n\t\t\tfor _,c := range res.Robot.Chores{\n\t\t\t\treply = fmt.Sprintf(\"%s\\n%s:small_blue_diamond:%s:small_blue_diamond:%v:small_blue_diamond:%s\",reply,c.Name, c.Sched, c.Next.Sub(time.Now()), c.State)\n\t\t\t}\n\t\t}\n\t\treturn res.Reply(reply)\n\t},\n}\n\nvar StopChore = &hal.Handler{\n\tMethod:  hal.RESPOND,\n\tPattern: `(stop chore)|(chore stop)`,\n\tRun: func(res *hal.Response) error {\n\t\tvar reply string\n\t\tcname:=strings.SplitAfterN(res.Match[0],` `,3)\n\t\tc:=hal.GetChoreByName(cname[2],res.Robot)\n\t\thal.KillChore(c)\n\t\treply = fmt.Sprintf(\"%s\\n%s:small_blue_diamond:%s:small_blue_diamond:%v:small_blue_diamond:%s\",reply,c.Name, c.Sched, c.Next.Sub(time.Now()), c.State)\n\t\treturn res.Reply(reply)\n\t},\n}\n<|endoftext|>"}
{"text":"<commit_before>package headlessChrome\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/integrii\/interactive\"\n)\n\n\/\/ Debug enables debug output for this package to console\nvar Debug bool\n\n\/\/ BrowserStartupTime is how long chrome has to startup the console\n\/\/ before we consider it a failure\nvar BrowserStartupTime = time.Second * 20\n\n\/\/ ChromePath is the command to execute chrome\nvar ChromePath = ChromePathMacOS\nvar ChromePathMacOS = `\/Applications\/Google Chrome.app\/Contents\/MacOS\/Google Chrome`\nvar ChromePathDocker = `\/opt\/google\/chrome-unstable\/chrome`\n\n\/\/ Args are the args that will be used to start chrome\nvar Args = []string{\n\t\"--headless\",\n\t\"--disable-gpu\",\n\t\"--repl\",\n\t\/\/ \"--dump-dom\",\n\t\/\/ \"--window-size=1024,768\",\n\t\/\/ \"--user-agent=Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/61.0.3163.100 Safari\/537.36\",\n\t\/\/ \"--verbose\",\n}\n\nconst expectedFirstLine = `Type a Javascript expression to evaluate or \"quit\" to exit.`\nconst promptPrefix = `>>>`\n\n\/\/ outputSanitizer puts output coming from the consolw that\n\/\/ does not begin with the input prompt into the session\n\/\/ output channel\nfunc (cs *ChromeSession) outputSanitizer() {\n\tfor text := range cs.Session.Output {\n\t\tdebug(\"raw output:\", text)\n\t\tif !strings.HasPrefix(text, promptPrefix) {\n\t\t\tcs.Output <- text\n\t\t}\n\t}\n}\n\n\/\/ ChromeSession is an interactive console Session with a Chrome\n\/\/ instance.\ntype ChromeSession struct {\n\tSession *interactive.Session\n\tOutput  chan string\n\tInput   chan string\n}\n\n\/\/ Exit exits the running command out by ossuing a 'quit'\n\/\/ to the chrome console\nfunc (cs *ChromeSession) Exit() {\n\tcs.Session.Write(`;quit`)\n\tcs.Session.Exit()\n}\n\n\/\/ Write writes to the Session\nfunc (cs *ChromeSession) Write(s string) {\n\tdebug(\"write:\", s)\n\tcs.Session.Write(s)\n}\n\n\/\/ outputPrinter prints all outputs from the output channel to the cli\nfunc (cs *ChromeSession) outputPrinter() {\n\tfor l := range cs.Session.Output {\n\t\tdebug(\"read:\", l)\n\t\tfmt.Println(l)\n\t}\n}\n\n\/\/ ForceClose issues a force kill to the command\nfunc (cs *ChromeSession) ForceClose() {\n\tcs.Session.ForceClose()\n}\n\n\/\/ ClickSelector calls a click() on the supplied selector\nfunc (cs *ChromeSession) ClickSelector(s string) {\n\tcs.Write(`document.querySelector(\"` + s + `\").click()`)\n}\n\n\/\/ ClickItemWithInnerHTML clicks an item that has the matching inner html\nfunc (cs *ChromeSession) ClickItemWithInnerHTML(elementType string, s string, itemIndex int) {\n\tcs.Write(`var x = $(\"` + elementType + `\").filter(function(idx) { return this.innerHTML == \"` + s + `\"});x[` + strconv.Itoa(itemIndex) + `].click()`)\n}\n\n\/\/ GetItemWithInnerHTML fetches the item with the specified innerHTML content\nfunc (cs *ChromeSession) GetItemWithInnerHTML(elementType string, s string, itemIndex int) {\n\tcs.Write(`var x = $(\"` + elementType + `\").filter(function(idx) { return this.innerHTML == \"` + s + `\"});x[` + strconv.Itoa(itemIndex) + `]`)\n}\n\n\/\/ GetContentOfItemWithClasses fetches the content of the element with the specified classes\nfunc (cs *ChromeSession) GetContentOfItemWithClasses(classes string, itemIndex int) {\n\tcs.Write(`document.getElementsByClassName(\"` + classes + `\")[` + strconv.Itoa(itemIndex) + `].innerHTML`)\n}\n\n\/\/ GetValueOfItemWithClasses returns the form value of the specified item\nfunc (cs *ChromeSession) GetValueOfItemWithClasses(classes string, itemIndex int) {\n\tcs.Write(`document.getElementsByClassName(\"` + classes + `\")[` + strconv.Itoa(itemIndex) + `].value`)\n}\n\n\/\/ GetContentOfItemWithSelector gets the content of an element with the specified selector\nfunc (cs *ChromeSession) GetContentOfItemWithSelector(selector string) {\n\tcs.Write(`document.querySelector(\"` + selector + `\").innerHTML()`)\n}\n\n\/\/ ClickItemWithClasses clicks on the first item it finds with the provided classes.\n\/\/ Multiple classes are separated by spaces\nfunc (cs *ChromeSession) ClickItemWithClasses(classes string, itemIndex int) {\n\tcs.Write(`document.getElementsByClassName(\"` + classes + `\")[` + strconv.Itoa(itemIndex) + `].click()`)\n}\n\n\/\/ SetTextByID sets the text on the div with the specified id\nfunc (cs *ChromeSession) SetTextByID(id string, text string) {\n\tcs.Write(`document.getElementById(\"` + id + `\").innerHTML = \"` + text + `\"`)\n}\n\n\/\/ ClickItemWithID clicks an item with the specified id\nfunc (cs *ChromeSession) ClickItemWithID(id string) {\n\tcs.Write(`document.getElementById(\"` + id + `\").click()`)\n}\n\n\/\/ SetTextByClasses sets the text on the div with the specified id\nfunc (cs *ChromeSession) SetTextByClasses(classes string, itemIndex int, text string) {\n\tcs.Write(`document.getElementsByClassName(\"` + classes + `\")[` + strconv.Itoa(itemIndex) + `].innerHTML = \"` + text + `\"`)\n}\n\n\/\/ SetInputTextByClasses sets the input text for an input field\nfunc (cs *ChromeSession) SetInputTextByClasses(classes string, itemIndex int, text string) {\n\tcs.Write(`document.getElementsByClassName(\"` + classes + `\")[` + strconv.Itoa(itemIndex) + `].value = \"` + text + `\"`)\n}\n\n\/\/ NewBrowserWithTimeout starts a new chrome headless session\n\/\/ but limits how long it can run before its killed forcefully.\n\/\/ A time limit of 0 means there is not a time limit\nfunc NewBrowserWithTimeout(url string, timeout time.Duration) (*ChromeSession, error) {\n\tvar err error\n\n\tdebug(\"Creating a new browser pointed to\", url)\n\n\tchromeSession := ChromeSession{}\n\tchromeSession.Output = make(chan string, 5000)\n\n\t\/\/ add url as last arg and create new Session\n\targs := append(Args, url)\n\tdebug(ChromePath, args)\n\tchromeSession.Session, err = interactive.NewSessionWithTimeout(ChromePath, args, timeout)\n\tif err != nil {\n\t\treturn &chromeSession, err\n\t}\n\n\t\/\/ map output and input channels for easy use\n\tchromeSession.Input = chromeSession.Session.Input\n\tgo chromeSession.outputSanitizer()\n\n\t\/\/ wait for the console ready line from the browser\n\t\/\/ and if it does not start in time, throw an error\n\tstartupTime := time.NewTimer(BrowserStartupTime)\n\tfor {\n\t\tselect {\n\t\tcase <-startupTime.C:\n\t\t\tdebug(\"ERROR: Browser failed to start before browser startup time cutoff\")\n\t\t\tchromeSession.ForceClose() \/\/ force cloe the session because it failed\n\t\t\terr = errors.New(\"Chrome console failed to init in the alotted time\")\n\t\t\treturn &chromeSession, err\n\t\tcase line := <-chromeSession.Output:\n\t\t\tif strings.Contains(line, expectedFirstLine) {\n\t\t\t\tdebug(\"Chrome console REPL ready\")\n\t\t\t\treturn &chromeSession, err\n\t\t\t}\n\t\t\tdebug(\"WARNING: Unespected first line when initializing headless Chrome console:\", line)\n\t\t}\n\t}\n}\n\n\/\/ NewBrowser starts a new chrome headless Session.\nfunc NewBrowser(url string) (*ChromeSession, error) {\n\treturn NewBrowserWithTimeout(url, 0)\n}\n\nfunc debug(s ...interface{}) {\n\tif Debug {\n\t\tfmt.Println(s...)\n\t}\n}\n<commit_msg>graceful shutdown when calling exit<commit_after>package headlessChrome\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/integrii\/interactive\"\n)\n\n\/\/ Debug enables debug output for this package to console\nvar Debug bool\n\n\/\/ BrowserStartupTime is how long chrome has to startup the console\n\/\/ before we consider it a failure\nvar BrowserStartupTime = time.Second * 20\n\n\/\/ ChromePath is the command to execute chrome\nvar ChromePath = ChromePathMacOS\n\n\/\/ ChromePathMacOS is where chrome normally lives on MacOS\nvar ChromePathMacOS = `\/Applications\/Google Chrome.app\/Contents\/MacOS\/Google Chrome`\n\n\/\/ ChromePathDocker is where chrome normally lives in the project's docker container\nvar ChromePathDocker = `\/opt\/google\/chrome-unstable\/chrome`\n\n\/\/ Args are the args that will be used to start chrome\nvar Args = []string{\n\t\"--headless\",\n\t\"--disable-gpu\",\n\t\"--repl\",\n\t\/\/ \"--dump-dom\",\n\t\/\/ \"--window-size=1024,768\",\n\t\/\/ \"--user-agent=Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/61.0.3163.100 Safari\/537.36\",\n\t\/\/ \"--verbose\",\n}\n\nconst expectedFirstLine = `Type a Javascript expression to evaluate or \"quit\" to exit.`\nconst promptPrefix = `>>>`\n\n\/\/ outputSanitizer puts output coming from the consolw that\n\/\/ does not begin with the input prompt into the session\n\/\/ output channel\nfunc (cs *ChromeSession) outputSanitizer() {\n\tfor text := range cs.Session.Output {\n\t\tdebug(\"raw output:\", text)\n\t\tif !strings.HasPrefix(text, promptPrefix) {\n\t\t\tcs.Output <- text\n\t\t}\n\t}\n}\n\n\/\/ ChromeSession is an interactive console Session with a Chrome\n\/\/ instance.\ntype ChromeSession struct {\n\tSession *interactive.Session\n\tOutput  chan string\n\tInput   chan string\n}\n\n\/\/ Exit exits the running command out by ossuing a 'quit'\n\/\/ to the chrome console\nfunc (cs *ChromeSession) Exit() {\n\tcs.Session.Write(`;quit`)\n\tcs.Session.Exit()  \/\/ exit the process with an interrupt signal\n\tcs.Session.Close() \/\/ close the tty session\n}\n\n\/\/ Write writes to the Session\nfunc (cs *ChromeSession) Write(s string) {\n\tdebug(\"write:\", s)\n\tcs.Session.Write(s)\n}\n\n\/\/ outputPrinter prints all outputs from the output channel to the cli\nfunc (cs *ChromeSession) outputPrinter() {\n\tfor l := range cs.Session.Output {\n\t\tdebug(\"read:\", l)\n\t\tfmt.Println(l)\n\t}\n}\n\n\/\/ ForceClose issues a force kill to the command\nfunc (cs *ChromeSession) ForceClose() {\n\tcs.Session.ForceClose()\n}\n\n\/\/ ClickSelector calls a click() on the supplied selector\nfunc (cs *ChromeSession) ClickSelector(s string) {\n\tcs.Write(`document.querySelector(\"` + s + `\").click()`)\n}\n\n\/\/ ClickItemWithInnerHTML clicks an item that has the matching inner html\nfunc (cs *ChromeSession) ClickItemWithInnerHTML(elementType string, s string, itemIndex int) {\n\tcs.Write(`var x = $(\"` + elementType + `\").filter(function(idx) { return this.innerHTML == \"` + s + `\"});x[` + strconv.Itoa(itemIndex) + `].click()`)\n}\n\n\/\/ GetItemWithInnerHTML fetches the item with the specified innerHTML content\nfunc (cs *ChromeSession) GetItemWithInnerHTML(elementType string, s string, itemIndex int) {\n\tcs.Write(`var x = $(\"` + elementType + `\").filter(function(idx) { return this.innerHTML == \"` + s + `\"});x[` + strconv.Itoa(itemIndex) + `]`)\n}\n\n\/\/ GetContentOfItemWithClasses fetches the content of the element with the specified classes\nfunc (cs *ChromeSession) GetContentOfItemWithClasses(classes string, itemIndex int) {\n\tcs.Write(`document.getElementsByClassName(\"` + classes + `\")[` + strconv.Itoa(itemIndex) + `].innerHTML`)\n}\n\n\/\/ GetValueOfItemWithClasses returns the form value of the specified item\nfunc (cs *ChromeSession) GetValueOfItemWithClasses(classes string, itemIndex int) {\n\tcs.Write(`document.getElementsByClassName(\"` + classes + `\")[` + strconv.Itoa(itemIndex) + `].value`)\n}\n\n\/\/ GetContentOfItemWithSelector gets the content of an element with the specified selector\nfunc (cs *ChromeSession) GetContentOfItemWithSelector(selector string) {\n\tcs.Write(`document.querySelector(\"` + selector + `\").innerHTML()`)\n}\n\n\/\/ ClickItemWithClasses clicks on the first item it finds with the provided classes.\n\/\/ Multiple classes are separated by spaces\nfunc (cs *ChromeSession) ClickItemWithClasses(classes string, itemIndex int) {\n\tcs.Write(`document.getElementsByClassName(\"` + classes + `\")[` + strconv.Itoa(itemIndex) + `].click()`)\n}\n\n\/\/ SetTextByID sets the text on the div with the specified id\nfunc (cs *ChromeSession) SetTextByID(id string, text string) {\n\tcs.Write(`document.getElementById(\"` + id + `\").innerHTML = \"` + text + `\"`)\n}\n\n\/\/ ClickItemWithID clicks an item with the specified id\nfunc (cs *ChromeSession) ClickItemWithID(id string) {\n\tcs.Write(`document.getElementById(\"` + id + `\").click()`)\n}\n\n\/\/ SetTextByClasses sets the text on the div with the specified id\nfunc (cs *ChromeSession) SetTextByClasses(classes string, itemIndex int, text string) {\n\tcs.Write(`document.getElementsByClassName(\"` + classes + `\")[` + strconv.Itoa(itemIndex) + `].innerHTML = \"` + text + `\"`)\n}\n\n\/\/ SetInputTextByClasses sets the input text for an input field\nfunc (cs *ChromeSession) SetInputTextByClasses(classes string, itemIndex int, text string) {\n\tcs.Write(`document.getElementsByClassName(\"` + classes + `\")[` + strconv.Itoa(itemIndex) + `].value = \"` + text + `\"`)\n}\n\n\/\/ NewBrowserWithTimeout starts a new chrome headless session\n\/\/ but limits how long it can run before its killed forcefully.\n\/\/ A time limit of 0 means there is not a time limit\nfunc NewBrowserWithTimeout(url string, timeout time.Duration) (*ChromeSession, error) {\n\tvar err error\n\n\tdebug(\"Creating a new browser pointed to\", url)\n\n\tchromeSession := ChromeSession{}\n\tchromeSession.Output = make(chan string, 5000)\n\n\t\/\/ add url as last arg and create new Session\n\targs := append(Args, url)\n\tdebug(ChromePath, args)\n\tchromeSession.Session, err = interactive.NewSessionWithTimeout(ChromePath, args, timeout)\n\tif err != nil {\n\t\treturn &chromeSession, err\n\t}\n\n\t\/\/ map output and input channels for easy use\n\tchromeSession.Input = chromeSession.Session.Input\n\tgo chromeSession.outputSanitizer()\n\n\t\/\/ wait for the console ready line from the browser\n\t\/\/ and if it does not start in time, throw an error\n\tstartupTime := time.NewTimer(BrowserStartupTime)\n\tfor {\n\t\tselect {\n\t\tcase <-startupTime.C:\n\t\t\tdebug(\"ERROR: Browser failed to start before browser startup time cutoff\")\n\t\t\tchromeSession.ForceClose() \/\/ force cloe the session because it failed\n\t\t\terr = errors.New(\"Chrome console failed to init in the alotted time\")\n\t\t\treturn &chromeSession, err\n\t\tcase line := <-chromeSession.Output:\n\t\t\tif strings.Contains(line, expectedFirstLine) {\n\t\t\t\tdebug(\"Chrome console REPL ready\")\n\t\t\t\treturn &chromeSession, err\n\t\t\t}\n\t\t\tdebug(\"WARNING: Unespected first line when initializing headless Chrome console:\", line)\n\t\t}\n\t}\n}\n\n\/\/ NewBrowser starts a new chrome headless Session.\nfunc NewBrowser(url string) (*ChromeSession, error) {\n\treturn NewBrowserWithTimeout(url, 0)\n}\n\nfunc debug(s ...interface{}) {\n\tif Debug {\n\t\tfmt.Println(s...)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package AuthorizeCIM\n\nimport (\n\t\"net\/http\"\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar api_endpoint string\nvar apiName string\nvar apiKey string\nvar testMode string\n\nvar CurrentUser User\n\nfunc SetAPIInfo(name string, key string, mode string) {\n\tapiKey = key\n\tapiName = name\n\tif mode == \"test\" {\n\t\ttestMode = \"testMode\"\n\t\tapi_endpoint = \"https:\/\/apitest.authorize.net\/xml\/v1\/request.api\"\n\t} else {\n\t\ttestMode = \"liveMode\"\n\t\tapi_endpoint = \"https:\/\/api.authorize.net\/xml\/v1\/request.api\"\n\t}\n}\n\nfunc MakeUser (userID string) User {\n\tCurrentUser = User{ID: \"55\", Email: userID, ProfileID: \"0\"}\n\treturn CurrentUser\n}\n\nfunc CreateCustomerProfile(userInfo AuthUser) (string, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tprofile := Profile{MerchantCustomerID: userInfo.Uuid, Description: userInfo.Description, Email: userInfo.Email}\n\trequest := CreateCustomerProfileRequest{authToken, profile}\n\tnewprofile := NewCustomerProfile{request}\n\tjsoned, _ := json.Marshal(newprofile)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tsuccess := FindResultCode(outgoing)\n\tvar new_uuid string\n\tif success {\n\t\tnew_uuid = outgoing[\"customerProfileId\"].(string)\n\t\tCurrentUser.ProfileID = new_uuid\n\t} else {\n\t\tnew_uuid = \"0\"\n\t}\n\t\/\/ Delay for Authorize.net\n\ttime.Sleep(3 * time.Second)\n\treturn new_uuid, success\n}\n\n\nfunc GetCustomerProfile(profileID string) (map[string]interface{}, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tprofile := getCustomerProfileRequest{authToken, profileID}\n\tinput := CustomerProfile{profile}\n\tjsoned, _ := json.Marshal(input)\n\toutgoing, _ :=SendRequest(string(jsoned))\n\tsuccess := FindResultCode(outgoing)\n\tfmt.Println(outgoing)\n\tuserProfile := outgoing[\"profile\"].(map[string]interface{})\n\tfmt.Println(userProfile)\n\treturn outgoing, success\n}\n\n\nfunc GetAllProfiles() []interface{} {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tprofilerequest := getCustomerProfileIdsRequest{authToken}\n\tall := AllCustomerProfileIds{profilerequest}\n\tjsoned, _ := json.Marshal(all)\n\toutgoing, _ :=SendRequest(string(jsoned))\n\treturn outgoing[\"ids\"].([]interface{})\n}\n\n\nfunc DeleteCustomerProfile(profileID string) bool {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tprofile := deleteCustomerProfileRequest{authToken, profileID}\n\tinput := deleteCustomerProfile{profile}\n\tjsoned, _ := json.Marshal(input)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\treturn status\n}\n\n\nfunc CreateCustomerBillingProfile(profileID string, creditCard CreditCard, address Address) (string, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tpaymentProfile := PaymentBillingProfile{Address: address, Payment: Payment{CreditCard:creditCard}}\n\trequest := CreateCustomerBillingProfileRequest{authToken, profileID, paymentProfile, testMode}\n\tnewprofile := NewCustomerBillingProfile{request}\n\tjsoned, _ := json.Marshal(newprofile)\n\toutgoing, _ :=SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\tvar new_paymentID string\n\tif status {\n\t\tnew_paymentID = outgoing[\"customerPaymentProfileId\"].(string)\n\t} else {\n\t\tnew_paymentID = \"0\"\n\t}\n\t\/\/ Delay for Authorize.net\n\ttime.Sleep(3 * time.Second)\n\treturn new_paymentID, status\n}\n\n\n\nfunc GetCustomerPaymentProfile(profileID string, paymentID string) (map[string]interface{}, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tprofile := CustomerPaymentProfileRequest{authToken, profileID, paymentID}\n\tinput := getCustomerPaymentProfileRequest{profile}\n\tjsoned, _ := json.Marshal(input)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tsuccess := FindResultCode(outgoing)\n\tfmt.Println(CurrentUser)\n\treturn outgoing[\"paymentProfile\"].(map[string]interface{}), success\n}\n\n\nfunc UpdateCustomerPaymentProfile(profileID string, paymentID string, creditCard CreditCard, address Address) bool {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tnew_billing := UpdatePaymentBillingProfile{Address: address, Payment: Payment{CreditCard:creditCard}, CustomerPaymentProfileId: paymentID}\n\tprofile := updateCustomerPaymentProfileRequest{authToken, profileID, new_billing, testMode}\n\tinput := changeCustomerPaymentProfileRequest{profile}\n\tjsoned, _ := json.Marshal(input)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\treturn status\n}\n\n\nfunc DeleteCustomerPaymentProfile(profileID string, paymentID string) bool {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tprofile := deleteCustomerPaymentProfile{authToken, profileID, paymentID}\n\tinput := deleteCustomerPaymentProfileRequest{profile}\n\tjsoned, _ := json.Marshal(input)\n\toutgoing, _ :=SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\treturn status\n}\n\nfunc SendRequest(input string) (map[string]interface{}, interface{}) {\n\treq, err := http.NewRequest(\"POST\", api_endpoint, bytes.NewBuffer([]byte(input)))\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\terrors := false\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tbody = bytes.TrimPrefix(body, []byte(\"\\xef\\xbb\\xbf\"))\n\tvar dat map[string]interface{}\n\t\/\/fmt.Printf(string(body))\n\terr = json.Unmarshal(body, &dat)\n\tif err!=nil {\n\t\tpanic(err)\n\t}\n\treturn dat, errors\n}\n\n\n\nfunc CreateTransaction(profileID string, paymentID string, item LineItem, amount string) (map[string]interface{}, bool, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\titems := LineItems{LineItem: item}\n\tsubProfile := SubProfile{CustomerPaymentProfileId: paymentID}\n\ttransProfile := TranProfile{CustomerProfileId: profileID, SubProfile: subProfile}\n\ttransaction := TransactionRequest{TransactionType: \"authCaptureTransaction\", Amount: amount, TranProfile: transProfile, LineItems: items}\n\ttranxrequest := CreateTransactionRequest{MerchantAuthentication: authToken, RefID: \"none33\", TransactionRequest: transaction}\n\tdoTranx := DoCreateTransaction{tranxrequest}\n\tjsoned, _ := json.Marshal(doTranx)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tvar status, approved bool\n\tvar response map[string]interface{}\n\ttransxResponse := outgoing[\"transactionResponse\"].(map[string]interface{})\n\tif transxResponse[\"responseCode\"]!=nil {\n\t\tif transxResponse[\"responseCode\"].(string) != \"1\" {\n\t\t\tapproved = false\n\t\t\tstatus = true\n\t\t\tresponse = transxResponse\n\t\t} else {\n\t\t\tstatus = FindResultCode(outgoing)\n\t\t\tapproved = TransactionApproved(outgoing)\n\t\t\tresponse = outgoing[\"transactionResponse\"].(map[string]interface{})\n\t\t}\n\t} else {\n\t\tapproved = false\n\t\tstatus = false\n\t\tresponse = map[string]interface{}{}\n\t}\n\n\treturn response, approved, status\n}\n\n\nfunc TestConnection() bool {\n\tauthToken := AuthenticateTestRequest{MerchantAuthentication{Name: apiName, TransactionKey: apiKey}}\n\tauthnettest := AuthorizeNetTest{AuthenticateTestRequest:authToken}\n\tjsoned, _ := json.Marshal(authnettest)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\treturn status\n}\n\n\nfunc CreateShippingAddress(profileID string, address Address) (string, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tcustomerShipping := CustomerShippingAddress{authToken,profileID,address}\n\tcustomerShippingRequest := CustomerShippingAddressRequest{customerShipping}\n\tjsoned, _ := json.Marshal(customerShippingRequest)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tsuccess := FindResultCode(outgoing)\n\tvar new_address_id string\n\tif !success {\n\t\tnew_address_id = \"0\"\n\t} else {\n\t\tnew_address_id = outgoing[\"customerAddressId\"].(string)\n\t}\n\t\/\/ Delay for Authorize.net\n\ttime.Sleep(3 * time.Second)\n\treturn new_address_id, success\n}\n\nfunc GetShippingAddress(profileID string, shippingID string) (map[string]interface{}, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tcustomerShipping := GetCustomerShippingAddress{authToken,profileID,shippingID}\n\tcustomerShippingRequest := GetCustomerShippingAddressRequest{customerShipping}\n\tjsoned, _ := json.Marshal(customerShippingRequest)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tsuccess := FindResultCode(outgoing)\n\treturn outgoing[\"address\"].(map[string]interface{}), success\n}\n\nfunc DeleteShippingAddress(profileID string, shippingID string) bool {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tcustomerShipping := GetCustomerShippingAddress{authToken,profileID,shippingID}\n\tcustomerShippingRequest := DeleteCustomerShippingAddressRequest{customerShipping}\n\tjsoned, _ := json.Marshal(customerShippingRequest)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\treturn status\n}\n\n\nfunc GetTransactionDetails(tranID string) map[string]interface{} {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\ttransDetails := TransactionDetails{authToken,tranID}\n\ttransactionRequest := TransactionDetailsRequest{transDetails}\n\tjsoned, _ := json.Marshal(transactionRequest)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tif outgoing[\"transaction\"]!=nil {\n\t\treturn outgoing[\"transaction\"].(map[string]interface{})\n\t}\n\treturn map[string]interface{}{}\n}\n\n\nfunc FindResultCode(incoming map[string]interface{}) bool {\n\tmessages, _ := incoming[\"messages\"].(map[string]interface{})\n\tif messages!=nil {\n\t\tif messages[\"resultCode\"] == \"Ok\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc TransactionApproved(incoming map[string]interface{}) bool {\n\tif incoming!=nil {\n\t\tmessages, _ := incoming[\"transactionResponse\"].(map[string]interface{})\n\t\tif messages[\"responseCode\"] == \"1\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc CreateSubscription(newSubscription Subscription) (string, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tsubscriptonSubmit := CreateSubscriptionRequest{ARBCreateSubscription{authToken, newSubscription}}\n\tjsoned, _ := json.Marshal(subscriptonSubmit)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\tif status {\n\t\treturn outgoing[\"subscriptionId\"].(string), status\n\t}\n\treturn \"0\", status\n}\n\n\n\nfunc RefundTransactions(){\n\n}\n\nfunc VoidTransaction(){\n\n}\n\nfunc DeleteSubscription(){\n\n}\n\nfunc UpdateSubscription(){\n\n}\n\nfunc GetSubscriptions(){\n\n}\n\n<commit_msg>rebuild on travis<commit_after>package AuthorizeCIM\n\nimport (\n\t\"net\/http\"\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar api_endpoint string\nvar apiName string\nvar apiKey string\nvar testMode string\n\nvar CurrentUser User\n\nfunc SetAPIInfo(name string, key string, mode string) {\n\tapiKey = key\n\tapiName = name\n\tif mode == \"test\" {\n\t\ttestMode = \"testMode\"\n\t\tapi_endpoint = \"https:\/\/apitest.authorize.net\/xml\/v1\/request.api\"\n\t} else {\n\t\ttestMode = \"liveMode\"\n\t\tapi_endpoint = \"https:\/\/api.authorize.net\/xml\/v1\/request.api\"\n\t}\n}\n\nfunc MakeUser (userID string) User {\n\tCurrentUser = User{ID: \"55\", Email: userID, ProfileID: \"0\"}\n\treturn CurrentUser\n}\n\nfunc CreateCustomerProfile(userInfo AuthUser) (string, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tprofile := Profile{MerchantCustomerID: userInfo.Uuid, Description: userInfo.Description, Email: userInfo.Email}\n\trequest := CreateCustomerProfileRequest{authToken, profile}\n\tnewprofile := NewCustomerProfile{request}\n\tjsoned, _ := json.Marshal(newprofile)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tsuccess := FindResultCode(outgoing)\n\tvar new_uuid string\n\tif success {\n\t\tnew_uuid = outgoing[\"customerProfileId\"].(string)\n\t\tCurrentUser.ProfileID = new_uuid\n\t} else {\n\t\tnew_uuid = \"0\"\n\t}\n\t\/\/ Delay for Authorize.net\n\ttime.Sleep(3 * time.Second)\n\treturn new_uuid, success\n}\n\n\nfunc GetCustomerProfile(profileID string) (map[string]interface{}, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tprofile := getCustomerProfileRequest{authToken, profileID}\n\tinput := CustomerProfile{profile}\n\tjsoned, _ := json.Marshal(input)\n\toutgoing, _ :=SendRequest(string(jsoned))\n\tsuccess := FindResultCode(outgoing)\n\tfmt.Println(outgoing)\n\tuserProfile := outgoing[\"profile\"].(map[string]interface{})\n\tfmt.Println(userProfile)\n\treturn outgoing, success\n}\n\n\nfunc GetAllProfiles() []interface{} {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tprofilerequest := getCustomerProfileIdsRequest{authToken}\n\tall := AllCustomerProfileIds{profilerequest}\n\tjsoned, _ := json.Marshal(all)\n\toutgoing, _ :=SendRequest(string(jsoned))\n\treturn outgoing[\"ids\"].([]interface{})\n}\n\n\nfunc DeleteCustomerProfile(profileID string) bool {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tprofile := deleteCustomerProfileRequest{authToken, profileID}\n\tinput := deleteCustomerProfile{profile}\n\tjsoned, _ := json.Marshal(input)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\treturn status\n}\n\n\nfunc CreateCustomerBillingProfile(profileID string, creditCard CreditCard, address Address) (string, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tpaymentProfile := PaymentBillingProfile{Address: address, Payment: Payment{CreditCard:creditCard}}\n\trequest := CreateCustomerBillingProfileRequest{authToken, profileID, paymentProfile, testMode}\n\tnewprofile := NewCustomerBillingProfile{request}\n\tjsoned, _ := json.Marshal(newprofile)\n\toutgoing, _ :=SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\tvar new_paymentID string\n\tif status {\n\t\tnew_paymentID = outgoing[\"customerPaymentProfileId\"].(string)\n\t} else {\n\t\tnew_paymentID = \"0\"\n\t}\n\t\/\/ Delay for Authorize.net\n\ttime.Sleep(3 * time.Second)\n\treturn new_paymentID, status\n}\n\n\n\nfunc GetCustomerPaymentProfile(profileID string, paymentID string) (map[string]interface{}, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tprofile := CustomerPaymentProfileRequest{authToken, profileID, paymentID}\n\tinput := getCustomerPaymentProfileRequest{profile}\n\tjsoned, _ := json.Marshal(input)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tsuccess := FindResultCode(outgoing)\n\tfmt.Println(CurrentUser)\n\treturn outgoing[\"paymentProfile\"].(map[string]interface{}), success\n}\n\n\nfunc UpdateCustomerPaymentProfile(profileID string, paymentID string, creditCard CreditCard, address Address) bool {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tnew_billing := UpdatePaymentBillingProfile{Address: address, Payment: Payment{CreditCard:creditCard}, CustomerPaymentProfileId: paymentID}\n\tprofile := updateCustomerPaymentProfileRequest{authToken, profileID, new_billing, testMode}\n\tinput := changeCustomerPaymentProfileRequest{profile}\n\tjsoned, _ := json.Marshal(input)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\treturn status\n}\n\n\nfunc DeleteCustomerPaymentProfile(profileID string, paymentID string) bool {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tprofile := deleteCustomerPaymentProfile{authToken, profileID, paymentID}\n\tinput := deleteCustomerPaymentProfileRequest{profile}\n\tjsoned, _ := json.Marshal(input)\n\toutgoing, _ :=SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\treturn status\n}\n\nfunc SendRequest(input string) (map[string]interface{}, interface{}) {\n\treq, err := http.NewRequest(\"POST\", api_endpoint, bytes.NewBuffer([]byte(input)))\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\terrors := false\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tbody = bytes.TrimPrefix(body, []byte(\"\\xef\\xbb\\xbf\"))\n\tvar dat map[string]interface{}\n\t\/\/fmt.Printf(string(body))\n\terr = json.Unmarshal(body, &dat)\n\tif err!=nil {\n\t\tpanic(err)\n\t}\n\treturn dat, errors\n}\n\n\n\nfunc CreateTransaction(profileID string, paymentID string, item LineItem, amount string) (map[string]interface{}, bool, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\titems := LineItems{LineItem: item}\n\tsubProfile := SubProfile{CustomerPaymentProfileId: paymentID}\n\ttransProfile := TranProfile{CustomerProfileId: profileID, SubProfile: subProfile}\n\ttransaction := TransactionRequest{TransactionType: \"authCaptureTransaction\", Amount: amount, TranProfile: transProfile, LineItems: items}\n\ttranxrequest := CreateTransactionRequest{MerchantAuthentication: authToken, RefID: \"none33\", TransactionRequest: transaction}\n\tdoTranx := DoCreateTransaction{tranxrequest}\n\tjsoned, _ := json.Marshal(doTranx)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tvar status, approved bool\n\tvar response map[string]interface{}\n\ttransxResponse := outgoing[\"transactionResponse\"].(map[string]interface{})\n\tif transxResponse[\"responseCode\"]!=nil {\n\t\tif transxResponse[\"responseCode\"].(string) != \"1\" {\n\t\t\tapproved = false\n\t\t\tstatus = true\n\t\t\tresponse = transxResponse\n\t\t} else {\n\t\t\tstatus = FindResultCode(outgoing)\n\t\t\tapproved = TransactionApproved(outgoing)\n\t\t\tresponse = outgoing[\"transactionResponse\"].(map[string]interface{})\n\t\t}\n\t} else {\n\t\tapproved = false\n\t\tstatus = false\n\t\tresponse = map[string]interface{}{}\n\t}\n\n\treturn response, approved, status\n}\n\n\nfunc TestConnection() bool {\n\tauthToken := AuthenticateTestRequest{MerchantAuthentication{Name: apiName, TransactionKey: apiKey}}\n\tauthnettest := AuthorizeNetTest{AuthenticateTestRequest:authToken}\n\tjsoned, _ := json.Marshal(authnettest)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\treturn status\n}\n\n\nfunc CreateShippingAddress(profileID string, address Address) (string, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tcustomerShipping := CustomerShippingAddress{authToken,profileID,address}\n\tcustomerShippingRequest := CustomerShippingAddressRequest{customerShipping}\n\tjsoned, _ := json.Marshal(customerShippingRequest)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tsuccess := FindResultCode(outgoing)\n\tvar new_address_id string\n\tif !success {\n\t\tnew_address_id = \"0\"\n\t} else {\n\t\tnew_address_id = outgoing[\"customerAddressId\"].(string)\n\t}\n\t\/\/ Delay for Authorize.net\n\ttime.Sleep(3 * time.Second)\n\treturn new_address_id, success\n}\n\nfunc GetShippingAddress(profileID string, shippingID string) (map[string]interface{}, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tcustomerShipping := GetCustomerShippingAddress{authToken,profileID,shippingID}\n\tcustomerShippingRequest := GetCustomerShippingAddressRequest{customerShipping}\n\tjsoned, _ := json.Marshal(customerShippingRequest)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tsuccess := FindResultCode(outgoing)\n\treturn outgoing[\"address\"].(map[string]interface{}), success\n}\n\nfunc DeleteShippingAddress(profileID string, shippingID string) bool {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tcustomerShipping := GetCustomerShippingAddress{authToken,profileID,shippingID}\n\tcustomerShippingRequest := DeleteCustomerShippingAddressRequest{customerShipping}\n\tjsoned, _ := json.Marshal(customerShippingRequest)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\treturn status\n}\n\n\nfunc GetTransactionDetails(tranID string) map[string]interface{} {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\ttransDetails := TransactionDetails{authToken,tranID}\n\ttransactionRequest := TransactionDetailsRequest{transDetails}\n\tjsoned, _ := json.Marshal(transactionRequest)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tif outgoing[\"transaction\"]!=nil {\n\t\treturn outgoing[\"transaction\"].(map[string]interface{})\n\t}\n\treturn map[string]interface{}{}\n}\n\n\nfunc FindResultCode(incoming map[string]interface{}) bool {\n\tmessages, _ := incoming[\"messages\"].(map[string]interface{})\n\tif messages!=nil {\n\t\tif messages[\"resultCode\"] == \"Ok\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc TransactionApproved(incoming map[string]interface{}) bool {\n\tif incoming!=nil {\n\t\tmessages, _ := incoming[\"transactionResponse\"].(map[string]interface{})\n\t\tif messages[\"responseCode\"] == \"1\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\nfunc CreateSubscription(newSubscription Subscription) (string, bool) {\n\tauthToken := MerchantAuthentication{Name: apiName, TransactionKey: apiKey}\n\tsubscriptonSubmit := CreateSubscriptionRequest{ARBCreateSubscription{authToken, newSubscription}}\n\tjsoned, _ := json.Marshal(subscriptonSubmit)\n\toutgoing, _ := SendRequest(string(jsoned))\n\tstatus := FindResultCode(outgoing)\n\tif status {\n\t\treturn outgoing[\"subscriptionId\"].(string), status\n\t}\n\treturn \"0\", status\n}\n\n\nfunc RefundTransactions(){\n\n}\n\nfunc VoidTransaction(){\n\n}\n\nfunc DeleteSubscription(){\n\n}\n\nfunc UpdateSubscription(){\n\n}\n\nfunc GetSubscriptions(){\n\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/Zenika\/MARCEL\/backend\/agenda\"\n\t\"github.com\/Zenika\/MARCEL\/backend\/auth\"\n\t\"github.com\/Zenika\/MARCEL\/backend\/weather\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/rs\/cors\"\n\t\"net\/http\"\n)\n\nfunc main() {\n\n\tc := cors.New(cors.Options{\n\t\t\/\/AllowedOrigins:   []string{\"*\"},\n\t\tAllowedOrigins:   []string{\"http:\/\/localhost:*\"},\n\t\tAllowedMethods:   []string{\"GET\", \"POST\", \"DELETE\", \"OPTION\", \"PUT\"},\n\t\tAllowCredentials: true,\n\t})\n\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"\/api\/v1\/weather\/forecast\/{nbForecasts:[0-9]+}\", weather.GetForecastWeatherHandler)\n\tr.HandleFunc(\"\/api\/v1\/agenda\/incoming\/{nbEvents:[0-9]*}\", agenda.GetNextEvents)\n\tr.HandleFunc(\"\/api\/v1\/GoogleLogin\", auth.HandleGoogleLogin)\n\tr.HandleFunc(\"\/api\/v1\/GoogleCallback\", auth.HandleGoogleCallback)\n\n\thandler := c.Handler(r)\n\thttp.ListenAndServe(\":8090\", handler)\n}\n<commit_msg>for dev : allow * for CORS<commit_after>package main\n\nimport (\n\t\"github.com\/Zenika\/MARCEL\/backend\/agenda\"\n\t\"github.com\/Zenika\/MARCEL\/backend\/auth\"\n\t\"github.com\/Zenika\/MARCEL\/backend\/weather\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/rs\/cors\"\n\t\"net\/http\"\n)\n\nfunc main() {\n\n\tc := cors.New(cors.Options{\n\t\tAllowedOrigins:   []string{\"*\"},\n\t\t\/\/AllowedOrigins:   []string{\"http:\/\/localhost:*\"},\n\t\tAllowedMethods:   []string{\"GET\", \"POST\", \"DELETE\", \"OPTION\", \"PUT\"},\n\t\tAllowCredentials: true,\n\t})\n\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"\/api\/v1\/weather\/forecast\/{nbForecasts:[0-9]+}\", weather.GetForecastWeatherHandler)\n\tr.HandleFunc(\"\/api\/v1\/agenda\/incoming\/{nbEvents:[0-9]*}\", agenda.GetNextEvents)\n\tr.HandleFunc(\"\/api\/v1\/GoogleLogin\", auth.HandleGoogleLogin)\n\tr.HandleFunc(\"\/api\/v1\/GoogleCallback\", auth.HandleGoogleCallback)\n\n\thandler := c.Handler(r)\n\n\thttp.ListenAndServe(\":8090\", handler)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Paul Jolly <paul@myitcv.org.uk>. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nPackage neovim implements support for writing Neovim plugins in Go. It also\nimplements a tool for generating the MSGPACK-based API against a Neovim instance.\n\nAll API methods are supported, as are notifications. See Subscription for an example\nof how to register a subscription on a given topic.\n\nClient\n\nEverything starts from Client:\n\n\t_, err := neovim.NewUnixClient(\"unix\", nil, &net.UnixAddr{Name: \"\/tmp\/neovim\"})\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create new Unix client: %v\", errgo.Details(err))\n\t}\n\nSee the examples for further usage patterns.\n\nConcurrency\n\nA single Client may safely be used by multiple goroutines. Calls to API methods are blocking\nby design.\n\nGenerating the API\n\nSee the github repo for details on re-generating the API.\n\nCompatibility\n\nThere are currently no checks to verify a connected Neovim instance exposes the same API\nagainst which the neovim package was generated. This is future work (and probably needs\nsome work on the Neovim side).\n\nErrors\n\nErrors returned by this package are created using errgo at http:\/\/godoc.org\/github.com\/juju\/errgo.\nHence errors may be inspected using functions like errgo.Details for example:\n\n\t_, err := client.GetCurrentBuffer()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get current buffer: %v\", errgo.Details(err))\n\t}\n*\/\npackage neovim\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\/exec\"\n\t\"sync\/atomic\"\n\n\t\"github.com\/juju\/errgo\"\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/vmihailenco\/msgpack\"\n)\n\n\/\/ NewUnixClient is a convenience method for creating a new *Client. Method signature matches\n\/\/ that of net.DialUnix\nfunc NewUnixClient(_net string, laddr, raddr *net.UnixAddr) (*Client, error) {\n\tc, err := net.DialUnix(_net, laddr, raddr)\n\tif err != nil {\n\t\treturn nil, errgo.Notef(err, \"Could not establish connection to Neovim, _net %v, laddr %v, %v\", _net, laddr, raddr)\n\t}\n\treturn NewClient(c)\n}\n\n\/\/ NewCmdClient creates a new Client that is linked via stdin\/stdout to the\n\/\/ supplied exec.Cmd, which is assumed to launch Neovim. The Neovim flag\n\/\/ --embedded-mode is added if it is missing, and the exec.Cmd is started\n\/\/ as part of creating the client. Calling Close() will close stdin on the\n\/\/ embedded Neovim instance, thereby ending the process\nfunc NewCmdClient(c *exec.Cmd) (*Client, error) {\n\tstdin, err := c.StdinPipe()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get a stdin pipe to embedded nvim: %v\\n\", err)\n\t}\n\tstdout, err := c.StdoutPipe()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get a stdout pipe to embedded nvim: %v\\n\", err)\n\t}\n\twrap := &stdWrapper{stdin: stdin, stdout: stdout}\n\n\t\/\/ ensure that we have --embedded-mode\n\tfound := false\n\tfor i := range c.Args {\n\t\tif c.Args[i] == \"--embedded-mode\" {\n\t\t\tfound = true\n\t\t}\n\t}\n\n\tif !found {\n\t\tc.Args = append(c.Args, \"--embedded-mode\")\n\t}\n\n\terr = c.Start()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not start the cmd: %v\\n\", err)\n\t}\n\n\treturn NewClient(wrap)\n}\n\n\/\/ NewClient creates a new Client\nfunc NewClient(c io.ReadWriteCloser) (*Client, error) {\n\tres := &Client{rw: c}\n\tres.respMap = newSyncMap()\n\tres.dec = msgpack.NewDecoder(c)\n\tres.enc = msgpack.NewEncoder(c)\n\tres.SubChan = make(chan Subscription)\n\tres.UnsubChan = make(chan Subscription)\n\tgo res.doListen()\n\treturn res, nil\n}\n\n\/\/ Close cleanly kills the client connection to Neovim\nfunc (c *Client) Close() error {\n\terr := c.rw.Close()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not cleanly close client: %v\\n\", err)\n\t}\n\t\/\/ TODO improve this\n\treturn nil\n}\n\nfunc (c *Client) doListen() {\n\t\/\/ TODO need kill channel\n\n\t\/\/ TODO look at the semantics of making this buffered...\n\tsubEvents := make(chan SubscriptionEvent, 10)\n\tgo c.doSubscriptionManager(subEvents)\n\n\tdec := c.dec\n\tfor {\n\t\t\/\/ TODO need better handling of EOF, i.e. client dies\n\t\t_, err := dec.DecodeSliceLen()\n\t\tif err != nil {\n\t\t\tif err.Error() == \"EOF\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlog.Fatalf(\"Could not decode message slice length: %v\", err)\n\t\t}\n\n\t\tt, err := dec.DecodeInt()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Could not decode message type: %v\", err)\n\t\t}\n\n\t\tswitch t {\n\t\tcase 1:\n\t\t\t\/\/ handle response\n\t\t\treqID, err := dec.DecodeUint32()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not decode request id: %v\", err)\n\t\t\t}\n\n\t\t\t\/\/ do we have an error?\n\t\t\tre, err := dec.DecodeInterface()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not decode response error: %v\", err)\n\t\t\t}\n\t\t\tif re != nil {\n\t\t\t\tlog.Fatalf(\"Got a response error: %v\", re)\n\t\t\t}\n\n\t\t\t\/\/ no, carry on\n\t\t\trh, err := c.respMap.Get(reqID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not get response holder for %v: %v\", reqID, err)\n\t\t\t}\n\n\t\t\t\/\/ we have a valid response, dispatch to our decoder for the response\n\t\t\tres, err := rh.dec()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not decode response: %v\\n\", err)\n\t\t\t}\n\n\t\t\tresp := &response{obj: res, err: nil}\n\t\t\trh.ch <- resp\n\t\tcase 2:\n\t\t\t\/\/ handle notification\n\t\t\ttopic, err := dec.DecodeString()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not decode topic: %v\", err)\n\t\t\t}\n\n\t\t\t\/\/ TODO this could be more efficient?\n\t\t\tobj, err := dec.DecodeInterface()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not decode obj payload: %v\", err)\n\t\t\t}\n\n\t\t\tev := SubscriptionEvent{\n\t\t\t\tTopic: topic,\n\t\t\t\tValue: obj,\n\t\t\t}\n\n\t\t\tsubEvents <- ev\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Unexpected type of message: %v\\n\", t)\n\t\t}\n\t}\n}\n\nfunc (c *Client) doSubscriptionManager(se chan SubscriptionEvent) {\n\tsubs := make(map[string]map[chan SubscriptionEvent]struct{})\n\n\tsendOrClose := func(c chan error, e error) {\n\t\tif c != nil {\n\t\t\tif e != nil {\n\t\t\t\tc <- e\n\t\t\t} else {\n\t\t\t\tclose(c)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase event := <-se:\n\t\t\t\/\/ TODO should we really swallow events on topics for which we have no subs?\n\t\t\tif chans, ok := subs[event.Topic]; ok {\n\t\t\t\tfor k := range chans {\n\t\t\t\t\tk <- event\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Got an event for which we have no subs on topic %v\\n\", event.Topic)\n\t\t\t}\n\t\tcase sub := <-c.SubChan:\n\t\t\tm, ok := subs[sub.Topic]\n\t\t\tif !ok {\n\t\t\t\tm = make(map[chan SubscriptionEvent]struct{})\n\t\t\t\tsubs[sub.Topic] = m\n\t\t\t}\n\t\t\tif _, ok := m[sub.Events]; ok {\n\t\t\t\tsendOrClose(sub.Error, errors.Errorf(\"Already have subscription for topic %v on this channel\", sub.Topic))\n\t\t\t}\n\t\t\tm[sub.Events] = struct{}{}\n\t\t\tsendOrClose(sub.Error, nil)\n\t\tcase unsub := <-c.UnsubChan:\n\t\t\tm, ok := subs[unsub.Topic]\n\t\t\tif !ok {\n\t\t\t\tsendOrClose(unsub.Error, errors.Errorf(\"We don't have any subscriptions for topic %v\", unsub.Topic))\n\t\t\t}\n\t\t\tif _, ok := m[unsub.Events]; !ok {\n\t\t\t\tsendOrClose(unsub.Error, errors.Errorf(\"We don't have a subscription on topic %v on this channel\", unsub.Topic))\n\t\t\t}\n\t\t\tdelete(m, unsub.Events)\n\t\t\tsendOrClose(unsub.Error, nil)\n\t\t}\n\t}\n}\n\nfunc (c *Client) makeCall(reqMethID neovimMethodID, e encoder, d decoder) (chan *response, error) {\n\treqType := 0\n\treqID := c.nextReqID()\n\tenc := c.enc\n\n\tres := make(chan *response)\n\trh := &responseHolder{dec: d, ch: res}\n\terr := c.respMap.Put(reqID, rh)\n\tif err != nil {\n\t\treturn nil, errgo.NoteMask(err, \"Could not store response holder\")\n\t}\n\n\terr = enc.EncodeSliceLen(4)\n\tif err != nil {\n\t\treturn nil, errgo.NoteMask(err, \"Could not encode request length\")\n\t}\n\n\terr = enc.EncodeInt(reqType)\n\tif err != nil {\n\t\treturn nil, errgo.NoteMask(err, \"Could not encode request type\")\n\t}\n\n\terr = enc.EncodeUint32(reqID)\n\tif err != nil {\n\t\treturn nil, errgo.NoteMask(err, \"Could not encode request ID\")\n\t}\n\n\terr = enc.EncodeUint32(uint32(reqMethID))\n\tif err != nil {\n\t\treturn nil, errgo.NoteMask(err, \"Could not encode request method ID\")\n\t}\n\n\terr = e()\n\tif err != nil {\n\t\treturn nil, errgo.NoteMask(err, \"Could not encode method args \")\n\t}\n\n\t\/\/ TODO need a flush here?\n\n\treturn res, nil\n}\n\nfunc (c *Client) nextReqID() uint32 {\n\treturn atomic.AddUint32(&c.nextReq, 1)\n}\n\nfunc (c *Client) panicOrReturn(e error) error {\n\tif e != nil && c.PanicOnError {\n\t\tpanic(e)\n\t}\n\treturn e\n}\n<commit_msg>Add some debugging for Travis<commit_after>\/\/ Copyright 2014 Paul Jolly <paul@myitcv.org.uk>. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nPackage neovim implements support for writing Neovim plugins in Go. It also\nimplements a tool for generating the MSGPACK-based API against a Neovim instance.\n\nAll API methods are supported, as are notifications. See Subscription for an example\nof how to register a subscription on a given topic.\n\nClient\n\nEverything starts from Client:\n\n\t_, err := neovim.NewUnixClient(\"unix\", nil, &net.UnixAddr{Name: \"\/tmp\/neovim\"})\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create new Unix client: %v\", errgo.Details(err))\n\t}\n\nSee the examples for further usage patterns.\n\nConcurrency\n\nA single Client may safely be used by multiple goroutines. Calls to API methods are blocking\nby design.\n\nGenerating the API\n\nSee the github repo for details on re-generating the API.\n\nCompatibility\n\nThere are currently no checks to verify a connected Neovim instance exposes the same API\nagainst which the neovim package was generated. This is future work (and probably needs\nsome work on the Neovim side).\n\nErrors\n\nErrors returned by this package are created using errgo at http:\/\/godoc.org\/github.com\/juju\/errgo.\nHence errors may be inspected using functions like errgo.Details for example:\n\n\t_, err := client.GetCurrentBuffer()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get current buffer: %v\", errgo.Details(err))\n\t}\n*\/\npackage neovim\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"sync\/atomic\"\n\n\t\"github.com\/juju\/errgo\"\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/vmihailenco\/msgpack\"\n)\n\n\/\/ NewUnixClient is a convenience method for creating a new *Client. Method signature matches\n\/\/ that of net.DialUnix\nfunc NewUnixClient(_net string, laddr, raddr *net.UnixAddr) (*Client, error) {\n\tc, err := net.DialUnix(_net, laddr, raddr)\n\tif err != nil {\n\t\treturn nil, errgo.Notef(err, \"Could not establish connection to Neovim, _net %v, laddr %v, %v\", _net, laddr, raddr)\n\t}\n\treturn NewClient(c)\n}\n\n\/\/ NewCmdClient creates a new Client that is linked via stdin\/stdout to the\n\/\/ supplied exec.Cmd, which is assumed to launch Neovim. The Neovim flag\n\/\/ --embedded-mode is added if it is missing, and the exec.Cmd is started\n\/\/ as part of creating the client. Calling Close() will close stdin on the\n\/\/ embedded Neovim instance, thereby ending the process\nfunc NewCmdClient(c *exec.Cmd) (*Client, error) {\n\tstdin, err := c.StdinPipe()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get a stdin pipe to embedded nvim: %v\\n\", err)\n\t}\n\tstdout, err := c.StdoutPipe()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get a stdout pipe to embedded nvim: %v\\n\", err)\n\t}\n\twrap := &stdWrapper{stdin: stdin, stdout: stdout}\n\n\t\/\/ ensure that we have --embedded-mode\n\tfound := false\n\tfor i := range c.Args {\n\t\tif c.Args[i] == \"--embedded-mode\" {\n\t\t\tfound = true\n\t\t}\n\t}\n\n\tif !found {\n\t\tc.Args = append(c.Args, \"--embedded-mode\")\n\t}\n\n\terr = c.Start()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not start the cmd: %v\\n\", err)\n\t}\n\n\treturn NewClient(wrap)\n}\n\n\/\/ NewClient creates a new Client\nfunc NewClient(c io.ReadWriteCloser) (*Client, error) {\n\tres := &Client{rw: c}\n\tres.respMap = newSyncMap()\n\tres.dec = msgpack.NewDecoder(c)\n\tres.enc = msgpack.NewEncoder(c)\n\tres.SubChan = make(chan Subscription)\n\tres.UnsubChan = make(chan Subscription)\n\tgo res.doListen()\n\treturn res, nil\n}\n\n\/\/ Close cleanly kills the client connection to Neovim\nfunc (c *Client) Close() error {\n\terr := c.rw.Close()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not cleanly close client: %v\\n\", err)\n\t}\n\t\/\/ TODO improve this\n\treturn nil\n}\n\nfunc (c *Client) doListen() {\n\t\/\/ TODO need kill channel\n\n\t\/\/ TODO look at the semantics of making this buffered...\n\tsubEvents := make(chan SubscriptionEvent, 10)\n\tgo c.doSubscriptionManager(subEvents)\n\n\tdec := c.dec\n\tfor {\n\t\t\/\/ TODO need better handling of EOF, i.e. client dies\n\t\t_, err := dec.DecodeSliceLen()\n\t\tif err != nil {\n\t\t\tif err.Error() == \"EOF\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlog.Fatalf(\"Could not decode message slice length: %v\", err)\n\t\t}\n\n\t\tt, err := dec.DecodeInt()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Could not decode message type: %v\", err)\n\t\t}\n\n\t\tswitch t {\n\t\tcase 1:\n\t\t\t\/\/ handle response\n\t\t\treqID, err := dec.DecodeUint32()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not decode request id: %v\", err)\n\t\t\t}\n\n\t\t\t\/\/ do we have an error?\n\t\t\tre, err := dec.DecodeInterface()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not decode response error: %v\", err)\n\t\t\t}\n\t\t\tif re != nil {\n\t\t\t\tlog.Fatalf(\"Got a response error for request %v: %v\", reqID, re)\n\t\t\t}\n\n\t\t\t\/\/ no, carry on\n\t\t\trh, err := c.respMap.Get(reqID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not get response holder for %v: %v\", reqID, err)\n\t\t\t}\n\n\t\t\t\/\/ we have a valid response, dispatch to our decoder for the response\n\t\t\tres, err := rh.dec()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not decode response: %v\\n\", err)\n\t\t\t}\n\n\t\t\tresp := &response{obj: res, err: nil}\n\t\t\trh.ch <- resp\n\t\tcase 2:\n\t\t\t\/\/ handle notification\n\t\t\ttopic, err := dec.DecodeString()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not decode topic: %v\", err)\n\t\t\t}\n\n\t\t\t\/\/ TODO this could be more efficient?\n\t\t\tobj, err := dec.DecodeInterface()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not decode obj payload: %v\", err)\n\t\t\t}\n\n\t\t\tev := SubscriptionEvent{\n\t\t\t\tTopic: topic,\n\t\t\t\tValue: obj,\n\t\t\t}\n\n\t\t\tsubEvents <- ev\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Unexpected type of message: %v\\n\", t)\n\t\t}\n\t}\n}\n\nfunc (c *Client) doSubscriptionManager(se chan SubscriptionEvent) {\n\tsubs := make(map[string]map[chan SubscriptionEvent]struct{})\n\n\tsendOrClose := func(c chan error, e error) {\n\t\tif c != nil {\n\t\t\tif e != nil {\n\t\t\t\tc <- e\n\t\t\t} else {\n\t\t\t\tclose(c)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase event := <-se:\n\t\t\t\/\/ TODO should we really swallow events on topics for which we have no subs?\n\t\t\tif chans, ok := subs[event.Topic]; ok {\n\t\t\t\tfor k := range chans {\n\t\t\t\t\tk <- event\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Got an event for which we have no subs on topic %v\\n\", event.Topic)\n\t\t\t}\n\t\tcase sub := <-c.SubChan:\n\t\t\tm, ok := subs[sub.Topic]\n\t\t\tif !ok {\n\t\t\t\tm = make(map[chan SubscriptionEvent]struct{})\n\t\t\t\tsubs[sub.Topic] = m\n\t\t\t}\n\t\t\tif _, ok := m[sub.Events]; ok {\n\t\t\t\tsendOrClose(sub.Error, errors.Errorf(\"Already have subscription for topic %v on this channel\", sub.Topic))\n\t\t\t}\n\t\t\tm[sub.Events] = struct{}{}\n\t\t\tsendOrClose(sub.Error, nil)\n\t\tcase unsub := <-c.UnsubChan:\n\t\t\tm, ok := subs[unsub.Topic]\n\t\t\tif !ok {\n\t\t\t\tsendOrClose(unsub.Error, errors.Errorf(\"We don't have any subscriptions for topic %v\", unsub.Topic))\n\t\t\t}\n\t\t\tif _, ok := m[unsub.Events]; !ok {\n\t\t\t\tsendOrClose(unsub.Error, errors.Errorf(\"We don't have a subscription on topic %v on this channel\", unsub.Topic))\n\t\t\t}\n\t\t\tdelete(m, unsub.Events)\n\t\t\tsendOrClose(unsub.Error, nil)\n\t\t}\n\t}\n}\n\nfunc (c *Client) makeCall(reqMethID neovimMethodID, e encoder, d decoder) (chan *response, error) {\n\treqType := 0\n\treqID := c.nextReqID()\n\tenc := c.enc\n\n\tfmt.Fprintf(os.Stderr, \"Call id %v: %v\\n\", reqID, reqMethID)\n\n\tres := make(chan *response)\n\trh := &responseHolder{dec: d, ch: res}\n\terr := c.respMap.Put(reqID, rh)\n\tif err != nil {\n\t\treturn nil, errgo.NoteMask(err, \"Could not store response holder\")\n\t}\n\n\terr = enc.EncodeSliceLen(4)\n\tif err != nil {\n\t\treturn nil, errgo.NoteMask(err, \"Could not encode request length\")\n\t}\n\n\terr = enc.EncodeInt(reqType)\n\tif err != nil {\n\t\treturn nil, errgo.NoteMask(err, \"Could not encode request type\")\n\t}\n\n\terr = enc.EncodeUint32(reqID)\n\tif err != nil {\n\t\treturn nil, errgo.NoteMask(err, \"Could not encode request ID\")\n\t}\n\n\terr = enc.EncodeUint32(uint32(reqMethID))\n\tif err != nil {\n\t\treturn nil, errgo.NoteMask(err, \"Could not encode request method ID\")\n\t}\n\n\terr = e()\n\tif err != nil {\n\t\treturn nil, errgo.NoteMask(err, \"Could not encode method args \")\n\t}\n\n\t\/\/ TODO need a flush here?\n\n\treturn res, nil\n}\n\nfunc (c *Client) nextReqID() uint32 {\n\treturn atomic.AddUint32(&c.nextReq, 1)\n}\n\nfunc (c *Client) panicOrReturn(e error) error {\n\tif e != nil && c.PanicOnError {\n\t\tpanic(e)\n\t}\n\treturn e\n}\n<|endoftext|>"}
{"text":"<commit_before>package net\n\nimport (\n\t\"sync\"\n\n\thandshake \"github.com\/jbenet\/go-ipfs\/net\/handshake\"\n\tpb \"github.com\/jbenet\/go-ipfs\/net\/handshake\/pb\"\n\n\tggio \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/gogoprotobuf\/io\"\n\tma \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr\"\n)\n\n\/\/ IDService is a structure that implements ProtocolIdentify.\n\/\/ It is a trivial service that gives the other peer some\n\/\/ useful information about the local peer. A sort of hello.\n\/\/\n\/\/ The IDService sends:\n\/\/  * Our IPFS Protocol Version\n\/\/  * Our IPFS Agent Version\n\/\/  * Our public Listen Addresses\ntype IDService struct {\n\tNetwork Network\n\n\t\/\/ connections undergoing identification\n\t\/\/ for wait purposes\n\tcurrid map[Conn]chan struct{}\n\tcurrmu sync.RWMutex\n}\n\nfunc NewIDService(n Network) *IDService {\n\ts := &IDService{\n\t\tNetwork: n,\n\t\tcurrid:  make(map[Conn]chan struct{}),\n\t}\n\tn.SetHandler(ProtocolIdentify, s.RequestHandler)\n\treturn s\n}\n\nfunc (ids *IDService) IdentifyConn(c Conn) {\n\tids.currmu.Lock()\n\tif _, found := ids.currid[c]; found {\n\t\tids.currmu.Unlock()\n\t\tlog.Debugf(\"IdentifyConn called twice on: %s\", c)\n\t\treturn \/\/ already identifying it.\n\t}\n\tids.currid[c] = make(chan struct{})\n\tids.currmu.Unlock()\n\n\ts, err := c.NewStreamWithProtocol(ProtocolIdentify)\n\tif err != nil {\n\t\tlog.Error(\"network: unable to open initial stream for %s\", ProtocolIdentify)\n\t\tlog.Event(ids.Network.CtxGroup().Context(), \"IdentifyOpenFailed\", c.RemotePeer())\n\t}\n\n\t\/\/ ok give the response to our handler.\n\tids.ResponseHandler(s)\n\n\tids.currmu.Lock()\n\tch, found := ids.currid[c]\n\tdelete(ids.currid, c)\n\tids.currmu.Unlock()\n\n\tif !found {\n\t\tlog.Errorf(\"IdentifyConn failed to find channel (programmer error) for %s\", c)\n\t\treturn\n\t}\n\n\tclose(ch) \/\/ release everyone waiting.\n}\n\nfunc (ids *IDService) RequestHandler(s Stream) {\n\tdefer s.Close()\n\tc := s.Conn()\n\n\tw := ggio.NewDelimitedWriter(s)\n\tmes := pb.Handshake3{}\n\tids.populateMessage(&mes, s.Conn())\n\tw.WriteMsg(&mes)\n\n\tlog.Debugf(\"%s sent message to %s %s\", ProtocolIdentify,\n\t\tc.RemotePeer(), c.RemoteMultiaddr())\n}\n\nfunc (ids *IDService) ResponseHandler(s Stream) {\n\tdefer s.Close()\n\tc := s.Conn()\n\n\tr := ggio.NewDelimitedReader(s, 2048)\n\tmes := pb.Handshake3{}\n\tif err := r.ReadMsg(&mes); err != nil {\n\t\tlog.Errorf(\"%s error receiving message from %s %s\", ProtocolIdentify,\n\t\t\tc.RemotePeer(), c.RemoteMultiaddr())\n\t\treturn\n\t}\n\tids.consumeMessage(&mes, c)\n\n\tlog.Debugf(\"%s received message from %s %s\", ProtocolIdentify,\n\t\tc.RemotePeer(), c.RemoteMultiaddr())\n}\n\nfunc (ids *IDService) populateMessage(mes *pb.Handshake3, c Conn) {\n\n\t\/\/ set protocols this node is currently handling\n\tprotos := ids.Network.Protocols()\n\tmes.Protocols = make([]string, len(protos))\n\tfor i, p := range protos {\n\t\tmes.Protocols[i] = string(p)\n\t}\n\n\t\/\/ observed address so other side is informed of their\n\t\/\/ \"public\" address, at least in relation to us.\n\tmes.ObservedAddr = c.RemoteMultiaddr().Bytes()\n\n\t\/\/ set listen addrs\n\tladdrs, err := ids.Network.InterfaceListenAddresses()\n\tif err != nil {\n\t\tlog.Error(err)\n\t} else {\n\t\tmes.ListenAddrs = make([][]byte, len(laddrs))\n\t\tfor i, addr := range laddrs {\n\t\t\tmes.ListenAddrs[i] = addr.Bytes()\n\t\t}\n\t\tlog.Debugf(\"%s sent listen addrs to %s: %s\", c.LocalPeer(), c.RemotePeer(), laddrs)\n\t}\n\n\t\/\/ set protocol versions\n\tmes.H1 = handshake.NewHandshake1(\"\", \"\")\n}\n\nfunc (ids *IDService) consumeMessage(mes *pb.Handshake3, c Conn) {\n\tp := c.RemotePeer()\n\n\t\/\/ mes.Protocols\n\t\/\/ mes.ObservedAddr\n\n\t\/\/ mes.ListenAddrs\n\tladdrs := mes.GetListenAddrs()\n\tlmaddrs := make([]ma.Multiaddr, 0, len(laddrs))\n\tfor _, addr := range laddrs {\n\t\tmaddr, err := ma.NewMultiaddrBytes(addr)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"%s failed to parse multiaddr from %s %s\", ProtocolIdentify, p,\n\t\t\t\tc.RemoteMultiaddr())\n\t\t\tcontinue\n\t\t}\n\t\tlmaddrs = append(lmaddrs, maddr)\n\t}\n\n\t\/\/ update our peerstore with the addresses.\n\tids.Network.Peerstore().AddAddresses(p, lmaddrs)\n\tlog.Debugf(\"%s received listen addrs for %s: %s\", c.LocalPeer(), c.RemotePeer(), lmaddrs)\n\n\t\/\/ get protocol versions\n\tpv := *mes.H1.ProtocolVersion\n\tav := *mes.H1.AgentVersion\n\tids.Network.Peerstore().Put(p, \"ProtocolVersion\", pv)\n\tids.Network.Peerstore().Put(p, \"AgentVersion\", av)\n}\n\n\/\/ IdentifyWait returns a channel which will be closed once\n\/\/ \"ProtocolIdentify\" (handshake3) finishes on given conn.\n\/\/ This happens async so the connection can start to be used\n\/\/ even if handshake3 knowledge is not necesary.\n\/\/ Users **MUST** call IdentifyWait _after_ IdentifyConn\nfunc (ids *IDService) IdentifyWait(c Conn) <-chan struct{} {\n\tids.currmu.Lock()\n\tch, found := ids.currid[c]\n\tids.currmu.Unlock()\n\tif found {\n\t\treturn ch\n\t}\n\n\t\/\/ if not found, it means we are already done identifying it, or\n\t\/\/ haven't even started. either way, return a new channel closed.\n\tch = make(chan struct{})\n\tclose(ch)\n\treturn ch\n}\n<commit_msg>net\/id: when dup id, wait on it.<commit_after>package net\n\nimport (\n\t\"sync\"\n\n\thandshake \"github.com\/jbenet\/go-ipfs\/net\/handshake\"\n\tpb \"github.com\/jbenet\/go-ipfs\/net\/handshake\/pb\"\n\n\tggio \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/gogoprotobuf\/io\"\n\tma \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr\"\n)\n\n\/\/ IDService is a structure that implements ProtocolIdentify.\n\/\/ It is a trivial service that gives the other peer some\n\/\/ useful information about the local peer. A sort of hello.\n\/\/\n\/\/ The IDService sends:\n\/\/  * Our IPFS Protocol Version\n\/\/  * Our IPFS Agent Version\n\/\/  * Our public Listen Addresses\ntype IDService struct {\n\tNetwork Network\n\n\t\/\/ connections undergoing identification\n\t\/\/ for wait purposes\n\tcurrid map[Conn]chan struct{}\n\tcurrmu sync.RWMutex\n}\n\nfunc NewIDService(n Network) *IDService {\n\ts := &IDService{\n\t\tNetwork: n,\n\t\tcurrid:  make(map[Conn]chan struct{}),\n\t}\n\tn.SetHandler(ProtocolIdentify, s.RequestHandler)\n\treturn s\n}\n\nfunc (ids *IDService) IdentifyConn(c Conn) {\n\tids.currmu.Lock()\n\tif wait, found := ids.currid[c]; found {\n\t\tids.currmu.Unlock()\n\t\tlog.Debugf(\"IdentifyConn called twice on: %s\", c)\n\t\t<-wait \/\/ already identifying it. wait for it.\n\t\treturn\n\t}\n\tids.currid[c] = make(chan struct{})\n\tids.currmu.Unlock()\n\n\ts, err := c.NewStreamWithProtocol(ProtocolIdentify)\n\tif err != nil {\n\t\tlog.Error(\"network: unable to open initial stream for %s\", ProtocolIdentify)\n\t\tlog.Event(ids.Network.CtxGroup().Context(), \"IdentifyOpenFailed\", c.RemotePeer())\n\t}\n\n\t\/\/ ok give the response to our handler.\n\tids.ResponseHandler(s)\n\n\tids.currmu.Lock()\n\tch, found := ids.currid[c]\n\tdelete(ids.currid, c)\n\tids.currmu.Unlock()\n\n\tif !found {\n\t\tlog.Errorf(\"IdentifyConn failed to find channel (programmer error) for %s\", c)\n\t\treturn\n\t}\n\n\tclose(ch) \/\/ release everyone waiting.\n}\n\nfunc (ids *IDService) RequestHandler(s Stream) {\n\tdefer s.Close()\n\tc := s.Conn()\n\n\tw := ggio.NewDelimitedWriter(s)\n\tmes := pb.Handshake3{}\n\tids.populateMessage(&mes, s.Conn())\n\tw.WriteMsg(&mes)\n\n\tlog.Debugf(\"%s sent message to %s %s\", ProtocolIdentify,\n\t\tc.RemotePeer(), c.RemoteMultiaddr())\n}\n\nfunc (ids *IDService) ResponseHandler(s Stream) {\n\tdefer s.Close()\n\tc := s.Conn()\n\n\tr := ggio.NewDelimitedReader(s, 2048)\n\tmes := pb.Handshake3{}\n\tif err := r.ReadMsg(&mes); err != nil {\n\t\tlog.Errorf(\"%s error receiving message from %s %s\", ProtocolIdentify,\n\t\t\tc.RemotePeer(), c.RemoteMultiaddr())\n\t\treturn\n\t}\n\tids.consumeMessage(&mes, c)\n\n\tlog.Debugf(\"%s received message from %s %s\", ProtocolIdentify,\n\t\tc.RemotePeer(), c.RemoteMultiaddr())\n}\n\nfunc (ids *IDService) populateMessage(mes *pb.Handshake3, c Conn) {\n\n\t\/\/ set protocols this node is currently handling\n\tprotos := ids.Network.Protocols()\n\tmes.Protocols = make([]string, len(protos))\n\tfor i, p := range protos {\n\t\tmes.Protocols[i] = string(p)\n\t}\n\n\t\/\/ observed address so other side is informed of their\n\t\/\/ \"public\" address, at least in relation to us.\n\tmes.ObservedAddr = c.RemoteMultiaddr().Bytes()\n\n\t\/\/ set listen addrs\n\tladdrs, err := ids.Network.InterfaceListenAddresses()\n\tif err != nil {\n\t\tlog.Error(err)\n\t} else {\n\t\tmes.ListenAddrs = make([][]byte, len(laddrs))\n\t\tfor i, addr := range laddrs {\n\t\t\tmes.ListenAddrs[i] = addr.Bytes()\n\t\t}\n\t\tlog.Debugf(\"%s sent listen addrs to %s: %s\", c.LocalPeer(), c.RemotePeer(), laddrs)\n\t}\n\n\t\/\/ set protocol versions\n\tmes.H1 = handshake.NewHandshake1(\"\", \"\")\n}\n\nfunc (ids *IDService) consumeMessage(mes *pb.Handshake3, c Conn) {\n\tp := c.RemotePeer()\n\n\t\/\/ mes.Protocols\n\t\/\/ mes.ObservedAddr\n\n\t\/\/ mes.ListenAddrs\n\tladdrs := mes.GetListenAddrs()\n\tlmaddrs := make([]ma.Multiaddr, 0, len(laddrs))\n\tfor _, addr := range laddrs {\n\t\tmaddr, err := ma.NewMultiaddrBytes(addr)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"%s failed to parse multiaddr from %s %s\", ProtocolIdentify, p,\n\t\t\t\tc.RemoteMultiaddr())\n\t\t\tcontinue\n\t\t}\n\t\tlmaddrs = append(lmaddrs, maddr)\n\t}\n\n\t\/\/ update our peerstore with the addresses.\n\tids.Network.Peerstore().AddAddresses(p, lmaddrs)\n\tlog.Debugf(\"%s received listen addrs for %s: %s\", c.LocalPeer(), c.RemotePeer(), lmaddrs)\n\n\t\/\/ get protocol versions\n\tpv := *mes.H1.ProtocolVersion\n\tav := *mes.H1.AgentVersion\n\tids.Network.Peerstore().Put(p, \"ProtocolVersion\", pv)\n\tids.Network.Peerstore().Put(p, \"AgentVersion\", av)\n}\n\n\/\/ IdentifyWait returns a channel which will be closed once\n\/\/ \"ProtocolIdentify\" (handshake3) finishes on given conn.\n\/\/ This happens async so the connection can start to be used\n\/\/ even if handshake3 knowledge is not necesary.\n\/\/ Users **MUST** call IdentifyWait _after_ IdentifyConn\nfunc (ids *IDService) IdentifyWait(c Conn) <-chan struct{} {\n\tids.currmu.Lock()\n\tch, found := ids.currid[c]\n\tids.currmu.Unlock()\n\tif found {\n\t\treturn ch\n\t}\n\n\t\/\/ if not found, it means we are already done identifying it, or\n\t\/\/ haven't even started. either way, return a new channel closed.\n\tch = make(chan struct{})\n\tclose(ch)\n\treturn ch\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"text\/tabwriter\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/compute\/servers\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/identity\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/utils\"\n)\n\nfunc main() {\n\tao, err := utils.AuthOptions()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ta, err := identity.Authenticate(ao)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsc, err := identity.GetServiceCatalog(a)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\teps, err := findAllComputeEndpoints(sc)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tn := 0\n\tw := new(tabwriter.Writer)\n\tw.Init(os.Stdout, 2, 8, 2, ' ', 0)\n\tfmt.Fprintln(w, \"ID\\tName\\tRegion\\tIPv4\\tIPv6\\t\")\n\tfor _, ep := range eps {\n\t\tclient := servers.NewClient(ep.PublicURL, a, ao)\n\n\t\tlistResults, err := servers.List(client)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tsvrs, err := servers.GetServers(listResults)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tn = n + len(svrs)\n\n\t\tfor _, s := range svrs {\n\t\t\tfmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\t%s\\t\\n\", s.Id, s.Name, ep.Region, s.AccessIPv4, s.AccessIPv6)\n\t\t}\n\t}\n\tw.Flush()\n\tfmt.Printf(\"--------\\n%d servers listed.\\n\", n)\n}\n\n\nfunc findAllComputeEndpoints(sc *identity.ServiceCatalog) ([]identity.Endpoint, error) {\n\tces, err := sc.CatalogEntries()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, ce := range ces {\n\t\tif ce.Type == \"compute\" {\n\t\t\treturn ce.Endpoints, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"Compute endpoint not found.\")\n}\n\n<commit_msg>Add support for region name<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"text\/tabwriter\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/compute\/servers\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/identity\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/utils\"\n)\n\nfunc main() {\n\tao, err := utils.AuthOptions()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ta, err := identity.Authenticate(ao)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsc, err := identity.GetServiceCatalog(a)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\teps, err := findAllComputeEndpoints(sc)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tregion := os.Getenv(\"OS_REGION_NAME\")\n\n\tn := 0\n\tw := new(tabwriter.Writer)\n\tw.Init(os.Stdout, 2, 8, 2, ' ', 0)\n\tfmt.Fprintln(w, \"ID\\tName\\tRegion\\tIPv4\\tIPv6\\t\")\n\tfor _, ep := range eps {\n\t\tif (region != \"\") && (region != ep.Region) {\n\t\t\tcontinue\n\t\t}\n\n\t\tclient := servers.NewClient(ep.PublicURL, a, ao)\n\n\t\tlistResults, err := servers.List(client)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tsvrs, err := servers.GetServers(listResults)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tn = n + len(svrs)\n\n\t\tfor _, s := range svrs {\n\t\t\tfmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\t%s\\t\\n\", s.Id, s.Name, ep.Region, s.AccessIPv4, s.AccessIPv6)\n\t\t}\n\t}\n\tw.Flush()\n\tfmt.Printf(\"--------\\n%d servers listed.\\n\", n)\n}\n\n\nfunc findAllComputeEndpoints(sc *identity.ServiceCatalog) ([]identity.Endpoint, error) {\n\tces, err := sc.CatalogEntries()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, ce := range ces {\n\t\tif ce.Type == \"compute\" {\n\t\t\treturn ce.Endpoints, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"Compute endpoint not found.\")\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build windows\n\npackage pluginaction_test\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\n\t. \"code.cloudfoundry.org\/cli\/actor\/pluginaction\"\n\t\"code.cloudfoundry.org\/cli\/actor\/pluginaction\/pluginactionfakes\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"install actions\", func() {\n\tvar (\n\t\tactor      *Actor\n\t\tfakeConfig *pluginactionfakes.FakeConfig\n\t\ttempDir    string\n\t)\n\n\tBeforeEach(func() {\n\t\tfakeConfig = new(pluginactionfakes.FakeConfig)\n\t\tvar err error\n\t\ttempPluginDir, err = ioutil.TempDir(\"\", \"\")\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tactor = NewActor(fakeConfig, nil)\n\t})\n\n\tAfterEach(func() {\n\t\terr := os.RemoveAll(tempPluginDir)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t})\n\n\tDescribe(\"CreateExecutableCopy\", func() {\n\t\tContext(\"when the file exists\", func() {\n\t\t\tvar pluginPath string\n\n\t\t\tBeforeEach(func() {\n\t\t\t\ttempFile, err := ioutil.TempFile(\"\", \"\")\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t_, err = tempFile.WriteString(\"cthulhu\")\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\terr = tempFile.Close()\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\tpluginPath = tempFile.Name()\n\t\t\t})\n\n\t\t\tAfterEach(func() {\n\t\t\t\terr := os.Remove(pluginPath)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"adds .exe to the end of the filename\", func() {\n\t\t\t\tcopyPath, err := actor.CreateExecutableCopy(pluginPath, tempPluginDir)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\tExpect(copyPath).To(HaveSuffix(\".exe\"))\n\t\t\t})\n\t\t})\n\t})\n})\n<commit_msg>still fixing windows units<commit_after>\/\/ +build windows\n\npackage pluginaction_test\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\n\t. \"code.cloudfoundry.org\/cli\/actor\/pluginaction\"\n\t\"code.cloudfoundry.org\/cli\/actor\/pluginaction\/pluginactionfakes\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"install actions\", func() {\n\tvar (\n\t\tactor         *Actor\n\t\tfakeConfig    *pluginactionfakes.FakeConfig\n\t\ttempPluginDir string\n\t)\n\n\tBeforeEach(func() {\n\t\tfakeConfig = new(pluginactionfakes.FakeConfig)\n\t\tvar err error\n\t\ttempPluginDir, err = ioutil.TempDir(\"\", \"\")\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tactor = NewActor(fakeConfig, nil)\n\t})\n\n\tAfterEach(func() {\n\t\terr := os.RemoveAll(tempPluginDir)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t})\n\n\tDescribe(\"CreateExecutableCopy\", func() {\n\t\tContext(\"when the file exists\", func() {\n\t\t\tvar pluginPath string\n\n\t\t\tBeforeEach(func() {\n\t\t\t\ttempFile, err := ioutil.TempFile(\"\", \"\")\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t_, err = tempFile.WriteString(\"cthulhu\")\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\terr = tempFile.Close()\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\tpluginPath = tempFile.Name()\n\t\t\t})\n\n\t\t\tAfterEach(func() {\n\t\t\t\terr := os.Remove(pluginPath)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"adds .exe to the end of the filename\", func() {\n\t\t\t\tcopyPath, err := actor.CreateExecutableCopy(pluginPath, tempPluginDir)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\tExpect(copyPath).To(HaveSuffix(\".exe\"))\n\t\t\t})\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"github.com\/dotcloud\/docker\/future\"\n\t\"github.com\/dotcloud\/docker\/rcli\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n)\n\n\/\/ Run docker in \"simple mode\": run a single command and return.\nfunc SimpleMode(args []string) error {\n\tvar oldState *State\n\tvar err error\n\tif IsTerminal(0) && os.Getenv(\"NORAW\") == \"\" {\n\t\toldState, err = MakeRaw(0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer Restore(0, oldState)\n\t}\n\t\/\/ FIXME: we want to use unix sockets here, but net.UnixConn doesn't expose\n\t\/\/ CloseWrite(), which we need to cleanly signal that stdin is closed without\n\t\/\/ closing the connection.\n\t\/\/ See http:\/\/code.google.com\/p\/go\/issues\/detail?id=3345\n\tconn, err := rcli.Call(\"tcp\", \"127.0.0.1:4242\", args...)\n\tif err != nil {\n\t\treturn err\n\t}\n\treceive_stdout := future.Go(func() error {\n\t\t_, err := io.Copy(os.Stdout, conn)\n\t\treturn err\n\t})\n\tsend_stdin := future.Go(func() error {\n\t\t_, err := io.Copy(conn, os.Stdin)\n\t\tif err := conn.CloseWrite(); err != nil {\n\t\t\tlog.Printf(\"Couldn't send EOF: \" + err.Error())\n\t\t}\n\t\treturn err\n\t})\n\tif err := <-receive_stdout; err != nil {\n\t\treturn err\n\t}\n\tif oldState != nil {\n\t\tRestore(0, oldState)\n\t}\n\tif !IsTerminal(0) {\n\t\tif err := <-send_stdin; err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Run docker in \"interactive mode\": run a bash-compatible shell capable of running docker commands.\nfunc InteractiveMode(scripts ...string) error {\n\t\/\/ Determine path of current docker binary\n\tdockerPath, err := exec.LookPath(os.Args[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tdockerPath, err = filepath.Abs(dockerPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Create a temp directory\n\ttmp, err := ioutil.TempDir(\"\", \"docker-shell\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(tmp)\n\n\t\/\/ For each command, create an alias in temp directory\n\t\/\/ FIXME: generate this list dynamically with introspection of some sort\n\t\/\/ It might make sense to merge docker and dockerd to keep that introspection\n\t\/\/ within a single binary.\n\tfor _, cmd := range []string{\n\t\t\"help\",\n\t\t\"run\",\n\t\t\"ps\",\n\t\t\"pull\",\n\t\t\"put\",\n\t\t\"rm\",\n\t\t\"kill\",\n\t\t\"wait\",\n\t\t\"stop\",\n\t\t\"start\",\n\t\t\"restart\",\n\t\t\"logs\",\n\t\t\"diff\",\n\t\t\"commit\",\n\t\t\"attach\",\n\t\t\"info\",\n\t\t\"tar\",\n\t\t\"web\",\n\t\t\"images\",\n\t\t\"docker\",\n\t} {\n\t\tif err := os.Symlink(dockerPath, path.Join(tmp, cmd)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Run $SHELL with PATH set to temp directory\n\trcfile, err := ioutil.TempFile(\"\", \"docker-shell-rc\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tio.WriteString(rcfile, \"enable -n help\\n\")\n\tos.Setenv(\"PATH\", tmp+\":\"+os.Getenv(\"PATH\"))\n\tos.Setenv(\"PS1\", \"\\\\h docker> \")\n\tshell := exec.Command(\"\/bin\/bash\", append([]string{\"--rcfile\", rcfile.Name()}, scripts...)...)\n\tshell.Stdin = os.Stdin\n\tshell.Stdout = os.Stdout\n\tshell.Stderr = os.Stderr\n\tif err := shell.Run(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>Automatically remove the rcfile generated by docker -i from \/tmp<commit_after>package client\n\nimport (\n\t\"github.com\/dotcloud\/docker\/future\"\n\t\"github.com\/dotcloud\/docker\/rcli\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n)\n\n\/\/ Run docker in \"simple mode\": run a single command and return.\nfunc SimpleMode(args []string) error {\n\tvar oldState *State\n\tvar err error\n\tif IsTerminal(0) && os.Getenv(\"NORAW\") == \"\" {\n\t\toldState, err = MakeRaw(0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer Restore(0, oldState)\n\t}\n\t\/\/ FIXME: we want to use unix sockets here, but net.UnixConn doesn't expose\n\t\/\/ CloseWrite(), which we need to cleanly signal that stdin is closed without\n\t\/\/ closing the connection.\n\t\/\/ See http:\/\/code.google.com\/p\/go\/issues\/detail?id=3345\n\tconn, err := rcli.Call(\"tcp\", \"127.0.0.1:4242\", args...)\n\tif err != nil {\n\t\treturn err\n\t}\n\treceive_stdout := future.Go(func() error {\n\t\t_, err := io.Copy(os.Stdout, conn)\n\t\treturn err\n\t})\n\tsend_stdin := future.Go(func() error {\n\t\t_, err := io.Copy(conn, os.Stdin)\n\t\tif err := conn.CloseWrite(); err != nil {\n\t\t\tlog.Printf(\"Couldn't send EOF: \" + err.Error())\n\t\t}\n\t\treturn err\n\t})\n\tif err := <-receive_stdout; err != nil {\n\t\treturn err\n\t}\n\tif oldState != nil {\n\t\tRestore(0, oldState)\n\t}\n\tif !IsTerminal(0) {\n\t\tif err := <-send_stdin; err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Run docker in \"interactive mode\": run a bash-compatible shell capable of running docker commands.\nfunc InteractiveMode(scripts ...string) error {\n\t\/\/ Determine path of current docker binary\n\tdockerPath, err := exec.LookPath(os.Args[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tdockerPath, err = filepath.Abs(dockerPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Create a temp directory\n\ttmp, err := ioutil.TempDir(\"\", \"docker-shell\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(tmp)\n\n\t\/\/ For each command, create an alias in temp directory\n\t\/\/ FIXME: generate this list dynamically with introspection of some sort\n\t\/\/ It might make sense to merge docker and dockerd to keep that introspection\n\t\/\/ within a single binary.\n\tfor _, cmd := range []string{\n\t\t\"help\",\n\t\t\"run\",\n\t\t\"ps\",\n\t\t\"pull\",\n\t\t\"put\",\n\t\t\"rm\",\n\t\t\"kill\",\n\t\t\"wait\",\n\t\t\"stop\",\n\t\t\"start\",\n\t\t\"restart\",\n\t\t\"logs\",\n\t\t\"diff\",\n\t\t\"commit\",\n\t\t\"attach\",\n\t\t\"info\",\n\t\t\"tar\",\n\t\t\"web\",\n\t\t\"images\",\n\t\t\"docker\",\n\t} {\n\t\tif err := os.Symlink(dockerPath, path.Join(tmp, cmd)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Run $SHELL with PATH set to temp directory\n\trcfile, err := ioutil.TempFile(\"\", \"docker-shell-rc\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.Remove(rcfile.Name())\n\tio.WriteString(rcfile, \"enable -n help\\n\")\n\tos.Setenv(\"PATH\", tmp+\":\"+os.Getenv(\"PATH\"))\n\tos.Setenv(\"PS1\", \"\\\\h docker> \")\n\tshell := exec.Command(\"\/bin\/bash\", append([]string{\"--rcfile\", rcfile.Name()}, scripts...)...)\n\tshell.Stdin = os.Stdin\n\tshell.Stdout = os.Stdout\n\tshell.Stderr = os.Stderr\n\tif err := shell.Run(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/pivotal-golang\/s3cli\/config\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\/s3manager\"\n)\n\n\/\/ S3Blobstore encapsulates interactions with an S3 compatible blobstore\ntype S3Blobstore struct {\n\ts3Client    *s3.S3\n\ts3cliConfig *config.S3Cli\n}\n\nvar errorInvalidCredentialsSourceValue = errors.New(\"the client operates in read only mode. Change 'credentials_source' parameter value \")\nvar oneTB = int64(1000 * 1024 * 1024 * 1024)\n\n\/\/ New returns a BlobstoreClient if the configuration file backing configFile is valid\nfunc New(s3Client *s3.S3, s3cliConfig *config.S3Cli) (S3Blobstore, error) {\n\treturn S3Blobstore{s3Client: s3Client, s3cliConfig: s3cliConfig}, nil\n}\n\n\/\/ Get fetches a blob from an S3 compatible blobstore\n\/\/ Destination will be overwritten if exists\nfunc (client *S3Blobstore) Get(src string, dest io.WriterAt) error {\n\tdownloader := s3manager.NewDownloaderWithClient(client.s3Client)\n\n\t_, err := downloader.Download(dest, &s3.GetObjectInput{\n\t\tBucket: aws.String(client.s3cliConfig.BucketName),\n\t\tKey:    aws.String(src),\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Put uploads a blob to an S3 compatible blobstore\nfunc (client *S3Blobstore) Put(src io.ReadSeeker, dest string) error {\n\tcfg := client.s3cliConfig\n\tif cfg.CredentialsSource == config.NoneCredentialsSource {\n\t\treturn errorInvalidCredentialsSourceValue\n\t}\n\n\tuploader := s3manager.NewUploaderWithClient(client.s3Client, func(u *s3manager.Uploader) {\n\t\tu.LeavePartsOnError = false\n\n\t\tif !cfg.MultipartUpload {\n\t\t\t\/\/ disable multipart uploads by way of large PartSize configuration\n\t\t\tu.PartSize = oneTB\n\t\t}\n\t})\n\tuploadInput := &s3manager.UploadInput{\n\t\tBody:   src,\n\t\tBucket: aws.String(cfg.BucketName),\n\t\tKey:    aws.String(dest),\n\t}\n\tif cfg.ServerSideEncryption != \"\" {\n\t\tuploadInput.ServerSideEncryption = aws.String(cfg.ServerSideEncryption)\n\t}\n\tif cfg.SSEKMSKeyID != \"\" {\n\t\tuploadInput.SSEKMSKeyId = aws.String(cfg.SSEKMSKeyID)\n\t}\n\n\tretry := 0\n\tmaxRetries := 3\n\tfor {\n\t\tputResult, err := uploader.Upload(uploadInput)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(s3manager.MultiUploadFailure); ok {\n\t\t\t\tif retry == maxRetries {\n\t\t\t\t\tlog.Println(\"Upload retry limit exceeded:\", err.Error())\n\t\t\t\t\treturn fmt.Errorf(\"upload retry limit exceeded: %s\", err.Error())\n\t\t\t\t}\n\t\t\t\tretry++\n\t\t\t\ttime.Sleep(time.Second * time.Duration(retry))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Println(\"Upload failed:\", err.Error())\n\t\t\treturn fmt.Errorf(\"upload failure: %s\", err.Error())\n\t\t}\n\n\t\tlog.Println(\"Successfully uploaded file to\", putResult.Location)\n\t\treturn nil\n\t}\n}\n\n\/\/ Delete removes a blob from an S3 compatible blobstore. If the object does\n\/\/ not exist, Delete does not return an error.\nfunc (client *S3Blobstore) Delete(dest string) error {\n\tif client.s3cliConfig.CredentialsSource == config.NoneCredentialsSource {\n\t\treturn errorInvalidCredentialsSourceValue\n\t}\n\n\tdeleteParams := &s3.DeleteObjectInput{\n\t\tBucket: aws.String(client.s3cliConfig.BucketName),\n\t\tKey:    aws.String(dest),\n\t}\n\n\t_, err := client.s3Client.DeleteObject(deleteParams)\n\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif reqErr, ok := err.(awserr.RequestFailure); ok {\n\t\tif reqErr.StatusCode() == 404 {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ Exists checks if blob exists in an S3 compatible blobstore\nfunc (client *S3Blobstore) Exists(dest string) (bool, error) {\n\n\texistsParams := &s3.HeadObjectInput{\n\t\tBucket: aws.String(client.s3cliConfig.BucketName),\n\t\tKey:    aws.String(dest),\n\t}\n\n\t_, err := client.s3Client.HeadObject(existsParams)\n\n\tif err == nil {\n\t\tlog.Printf(\"File '%s' exists in bucket '%s'\\n\", dest, client.s3cliConfig.BucketName)\n\t\treturn true, nil\n\t}\n\n\tif reqErr, ok := err.(awserr.RequestFailure); ok {\n\t\tif reqErr.StatusCode() == 404 {\n\t\t\tlog.Printf(\"File '%s' does not exist in bucket '%s'\\n\", dest, client.s3cliConfig.BucketName)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn false, err\n}\n<commit_msg>Time out when network partition occurs<commit_after>package client\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/pivotal-golang\/s3cli\/config\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\/s3manager\"\n)\n\n\/\/ S3Blobstore encapsulates interactions with an S3 compatible blobstore\ntype S3Blobstore struct {\n\ts3Client    *s3.S3\n\ts3cliConfig *config.S3Cli\n}\n\nvar errorInvalidCredentialsSourceValue = errors.New(\"the client operates in read only mode. Change 'credentials_source' parameter value \")\nvar oneTB = int64(1000 * 1024 * 1024 * 1024)\n\n\/\/ New returns a BlobstoreClient if the configuration file backing configFile is valid\nfunc New(s3Client *s3.S3, s3cliConfig *config.S3Cli) (S3Blobstore, error) {\n\treturn S3Blobstore{s3Client: s3Client, s3cliConfig: s3cliConfig}, nil\n}\n\n\/\/ Get fetches a blob from an S3 compatible blobstore\n\/\/ Destination will be overwritten if exists\nfunc (client *S3Blobstore) Get(src string, dest io.WriterAt) error {\n\tsetConcurrency := func(d *s3manager.Downloader) {\n\t\td.Concurrency = 105 \/\/ creates 525MB buffer, to avoid hanging on download w\/ broken network\n\t}\n\tdownloader := s3manager.NewDownloaderWithClient(client.s3Client, setConcurrency)\n\n\t_, err := downloader.Download(dest, &s3.GetObjectInput{\n\t\tBucket: aws.String(client.s3cliConfig.BucketName),\n\t\tKey:    aws.String(src),\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Put uploads a blob to an S3 compatible blobstore\nfunc (client *S3Blobstore) Put(src io.ReadSeeker, dest string) error {\n\tcfg := client.s3cliConfig\n\tif cfg.CredentialsSource == config.NoneCredentialsSource {\n\t\treturn errorInvalidCredentialsSourceValue\n\t}\n\n\tuploader := s3manager.NewUploaderWithClient(client.s3Client, func(u *s3manager.Uploader) {\n\t\tu.LeavePartsOnError = false\n\n\t\tif !cfg.MultipartUpload {\n\t\t\t\/\/ disable multipart uploads by way of large PartSize configuration\n\t\t\tu.PartSize = oneTB\n\t\t}\n\t})\n\tuploadInput := &s3manager.UploadInput{\n\t\tBody:   src,\n\t\tBucket: aws.String(cfg.BucketName),\n\t\tKey:    aws.String(dest),\n\t}\n\tif cfg.ServerSideEncryption != \"\" {\n\t\tuploadInput.ServerSideEncryption = aws.String(cfg.ServerSideEncryption)\n\t}\n\tif cfg.SSEKMSKeyID != \"\" {\n\t\tuploadInput.SSEKMSKeyId = aws.String(cfg.SSEKMSKeyID)\n\t}\n\n\tretry := 0\n\tmaxRetries := 3\n\tfor {\n\t\tputResult, err := uploader.Upload(uploadInput)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(s3manager.MultiUploadFailure); ok {\n\t\t\t\tif retry == maxRetries {\n\t\t\t\t\tlog.Println(\"Upload retry limit exceeded:\", err.Error())\n\t\t\t\t\treturn fmt.Errorf(\"upload retry limit exceeded: %s\", err.Error())\n\t\t\t\t}\n\t\t\t\tretry++\n\t\t\t\ttime.Sleep(time.Second * time.Duration(retry))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Println(\"Upload failed:\", err.Error())\n\t\t\treturn fmt.Errorf(\"upload failure: %s\", err.Error())\n\t\t}\n\n\t\tlog.Println(\"Successfully uploaded file to\", putResult.Location)\n\t\treturn nil\n\t}\n}\n\n\/\/ Delete removes a blob from an S3 compatible blobstore. If the object does\n\/\/ not exist, Delete does not return an error.\nfunc (client *S3Blobstore) Delete(dest string) error {\n\tif client.s3cliConfig.CredentialsSource == config.NoneCredentialsSource {\n\t\treturn errorInvalidCredentialsSourceValue\n\t}\n\n\tdeleteParams := &s3.DeleteObjectInput{\n\t\tBucket: aws.String(client.s3cliConfig.BucketName),\n\t\tKey:    aws.String(dest),\n\t}\n\n\t_, err := client.s3Client.DeleteObject(deleteParams)\n\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif reqErr, ok := err.(awserr.RequestFailure); ok {\n\t\tif reqErr.StatusCode() == 404 {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ Exists checks if blob exists in an S3 compatible blobstore\nfunc (client *S3Blobstore) Exists(dest string) (bool, error) {\n\n\texistsParams := &s3.HeadObjectInput{\n\t\tBucket: aws.String(client.s3cliConfig.BucketName),\n\t\tKey:    aws.String(dest),\n\t}\n\n\t_, err := client.s3Client.HeadObject(existsParams)\n\n\tif err == nil {\n\t\tlog.Printf(\"File '%s' exists in bucket '%s'\\n\", dest, client.s3cliConfig.BucketName)\n\t\treturn true, nil\n\t}\n\n\tif reqErr, ok := err.(awserr.RequestFailure); ok {\n\t\tif reqErr.StatusCode() == 404 {\n\t\t\tlog.Printf(\"File '%s' does not exist in bucket '%s'\\n\", dest, client.s3cliConfig.BucketName)\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn false, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Helper functions to make constructing templates and sets easier.\n\npackage template\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\n\/\/ Functions and methods to parse a single template.\n\n\/\/ Must is a helper that wraps a call to a function returning (*Template, os.Error)\n\/\/ and panics if the error is non-nil. It is intended for use in variable initializations\n\/\/ such as\n\/\/\tvar t = template.Must(template.Parse(\"text\"))\nfunc Must(t *Template, err os.Error) *Template {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn t\n}\n\n\/\/ ParseFile creates a new Template and parses the template definition from\n\/\/ the named file.  The template name is the base name of the file.\nfunc ParseFile(filename string) (*Template, os.Error) {\n\tt := New(filepath.Base(filename))\n\treturn t.ParseFile(filename)\n}\n\n\/\/ parseFileInSet creates a new Template and parses the template\n\/\/ definition from the named file. The template name is the base name\n\/\/ of the file. It also adds the template to the set. Function bindings are\n\/\/ checked against those in the set.\nfunc parseFileInSet(filename string, set *Set) (*Template, os.Error) {\n\tt := New(filepath.Base(filename))\n\treturn t.parseFileInSet(filename, set)\n}\n\n\/\/ ParseFile reads the template definition from a file and parses it to\n\/\/ construct an internal representation of the template for execution.\nfunc (t *Template) ParseFile(filename string) (*Template, os.Error) {\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn t, err\n\t}\n\treturn t.Parse(string(b))\n}\n\n\/\/ parseFileInSet is the same as ParseFile except that function bindings\n\/\/ are checked against those in the set and the template is added\n\/\/ to the set.\nfunc (t *Template) parseFileInSet(filename string, set *Set) (*Template, os.Error) {\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn t, err\n\t}\n\treturn t.ParseInSet(string(b), set)\n}\n\n\/\/ Functions and methods to parse a set.\n\n\/\/ SetMust is a helper that wraps a call to a function returning (*Set, os.Error)\n\/\/ and panics if the error is non-nil. It is intended for use in variable initializations\n\/\/ such as\n\/\/\tvar s = template.SetMust(template.ParseSetFile(\"file\"))\nfunc SetMust(s *Set, err os.Error) *Set {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s\n}\n\n\/\/ ParseFile parses the named files into a set of named templates.\n\/\/ Each file must be parseable by itself. Parsing stops if an error is\n\/\/ encountered.\nfunc (s *Set) ParseFile(filenames ...string) (*Set, os.Error) {\n\tfor _, filename := range filenames {\n\t\tb, err := ioutil.ReadFile(filename)\n\t\tif err != nil {\n\t\t\treturn s, err\n\t\t}\n\t\t_, err = s.Parse(string(b))\n\t\tif err != nil {\n\t\t\treturn s, err\n\t\t}\n\t}\n\treturn s, nil\n}\n\n\/\/ ParseSetFile creates a new Set and parses the set definition from the\n\/\/ named files. Each file must be individually parseable.\nfunc ParseSetFile(filenames ...string) (*Set, os.Error) {\n\ts := new(Set)\n\tfor _, filename := range filenames {\n\t\tb, err := ioutil.ReadFile(filename)\n\t\tif err != nil {\n\t\t\treturn s, err\n\t\t}\n\t\t_, err = s.Parse(string(b))\n\t\tif err != nil {\n\t\t\treturn s, err\n\t\t}\n\t}\n\treturn s, nil\n}\n\n\/\/ ParseFiles parses the set definition from the files identified by the\n\/\/ pattern.  The pattern is processed by filepath.Glob and must match at\n\/\/ least one file.\nfunc (s *Set) ParseFiles(pattern string) (*Set, os.Error) {\n\tfilenames, err := filepath.Glob(pattern)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\tif len(filenames) == 0 {\n\t\treturn s, fmt.Errorf(\"pattern matches no files: %#q\", pattern)\n\t}\n\treturn s.ParseFile(filenames...)\n}\n\n\/\/ ParseSetFiles creates a new Set and parses the set definition from the\n\/\/ files identified by the pattern. The pattern is processed by filepath.Glob\n\/\/ and must match at least one file.\nfunc ParseSetFiles(pattern string) (*Set, os.Error) {\n\tset, err := new(Set).ParseFiles(pattern)\n\tif err != nil {\n\t\treturn set, err\n\t}\n\treturn set, nil\n}\n\n\/\/ Functions and methods to parse stand-alone template files into a set.\n\n\/\/ ParseTemplateFile parses the named template files and adds\n\/\/ them to the set. Each template will named the base name of\n\/\/ its file.\n\/\/ Unlike with ParseFile, each file should be a stand-alone template\n\/\/ definition suitable for Template.Parse (not Set.Parse); that is, the\n\/\/ file does not contain {{define}} clauses. ParseTemplateFile is\n\/\/ therefore equivalent to calling the ParseFile function to create\n\/\/ individual templates, which are then added to the set.\n\/\/ Each file must be parseable by itself. Parsing stops if an error is\n\/\/ encountered.\nfunc (s *Set) ParseTemplateFile(filenames ...string) (*Set, os.Error) {\n\tfor _, filename := range filenames {\n\t\t_, err := parseFileInSet(filename, s)\n\t\tif err != nil {\n\t\t\treturn s, err\n\t\t}\n\t}\n\treturn s, nil\n}\n\n\/\/ ParseTemplateFiles parses the template files matched by the\n\/\/ patern and adds them to the set. Each template will named\n\/\/ the base name of its file.\n\/\/ Unlike with ParseFiles, each file should be a stand-alone template\n\/\/ definition suitable for Template.Parse (not Set.Parse); that is, the\n\/\/ file does not contain {{define}} clauses. ParseTemplateFiles is\n\/\/ therefore equivalent to calling the ParseFile function to create\n\/\/ individual templates, which are then added to the set.\n\/\/ Each file must be parseable by itself. Parsing stops if an error is\n\/\/ encountered.\nfunc (s *Set) ParseTemplateFiles(pattern string) (*Set, os.Error) {\n\tfilenames, err := filepath.Glob(pattern)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\tfor _, filename := range filenames {\n\t\t_, err := parseFileInSet(filename, s)\n\t\tif err != nil {\n\t\t\treturn s, err\n\t\t}\n\t}\n\treturn s, nil\n}\n\n\/\/ ParseTemplateFile creates a set by parsing the named files,\n\/\/ each of which defines a single template. Each template will\n\/\/ named the base name of its file.\n\/\/ Unlike with ParseFile, each file should be a stand-alone template\n\/\/ definition suitable for Template.Parse (not Set.Parse); that is, the\n\/\/ file does not contain {{define}} clauses. ParseTemplateFile is\n\/\/ therefore equivalent to calling the ParseFile function to create\n\/\/ individual templates, which are then added to the set.\n\/\/ Each file must be parseable by itself. Parsing stops if an error is\n\/\/ encountered.\nfunc ParseTemplateFile(filenames ...string) (*Set, os.Error) {\n\tset := new(Set)\n\tfor _, filename := range filenames {\n\t\tt, err := ParseFile(filename)\n\t\tif err != nil {\n\t\t\treturn set, err\n\t\t}\n\t\tif err := set.add(t); err != nil {\n\t\t\treturn set, err\n\t\t}\n\t}\n\treturn set, nil\n}\n\n\/\/ ParseTemplateFiles creates a set by parsing the files matched\n\/\/ by the pattern, each of which defines a single template. Each\n\/\/ template will named the base name of its file.\n\/\/ Unlike with ParseFiles, each file should be a stand-alone template\n\/\/ definition suitable for Template.Parse (not Set.Parse); that is, the\n\/\/ file does not contain {{define}} clauses. ParseTemplateFiles is\n\/\/ therefore equivalent to calling the ParseFile function to create\n\/\/ individual templates, which are then added to the set.\n\/\/ Each file must be parseable by itself. Parsing stops if an error is\n\/\/ encountered.\nfunc ParseTemplateFiles(pattern string) (*Set, os.Error) {\n\tset := new(Set)\n\tfilenames, err := filepath.Glob(pattern)\n\tif err != nil {\n\t\treturn set, err\n\t}\n\tfor _, filename := range filenames {\n\t\tt, err := ParseFile(filename)\n\t\tif err != nil {\n\t\t\treturn set, err\n\t\t}\n\t\tif err := set.add(t); err != nil {\n\t\t\treturn set, err\n\t\t}\n\t}\n\treturn set, nil\n}\n<commit_msg>exp\/template: ensure that a valid Set is returned even on error.<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Helper functions to make constructing templates and sets easier.\n\npackage template\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\n\/\/ Functions and methods to parse a single template.\n\n\/\/ Must is a helper that wraps a call to a function returning (*Template, os.Error)\n\/\/ and panics if the error is non-nil. It is intended for use in variable initializations\n\/\/ such as\n\/\/\tvar t = template.Must(template.Parse(\"text\"))\nfunc Must(t *Template, err os.Error) *Template {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn t\n}\n\n\/\/ ParseFile creates a new Template and parses the template definition from\n\/\/ the named file.  The template name is the base name of the file.\nfunc ParseFile(filename string) (*Template, os.Error) {\n\tt := New(filepath.Base(filename))\n\treturn t.ParseFile(filename)\n}\n\n\/\/ parseFileInSet creates a new Template and parses the template\n\/\/ definition from the named file. The template name is the base name\n\/\/ of the file. It also adds the template to the set. Function bindings are\n\/\/ checked against those in the set.\nfunc parseFileInSet(filename string, set *Set) (*Template, os.Error) {\n\tt := New(filepath.Base(filename))\n\treturn t.parseFileInSet(filename, set)\n}\n\n\/\/ ParseFile reads the template definition from a file and parses it to\n\/\/ construct an internal representation of the template for execution.\nfunc (t *Template) ParseFile(filename string) (*Template, os.Error) {\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn t, err\n\t}\n\treturn t.Parse(string(b))\n}\n\n\/\/ parseFileInSet is the same as ParseFile except that function bindings\n\/\/ are checked against those in the set and the template is added\n\/\/ to the set.\nfunc (t *Template) parseFileInSet(filename string, set *Set) (*Template, os.Error) {\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn t, err\n\t}\n\treturn t.ParseInSet(string(b), set)\n}\n\n\/\/ Functions and methods to parse a set.\n\n\/\/ SetMust is a helper that wraps a call to a function returning (*Set, os.Error)\n\/\/ and panics if the error is non-nil. It is intended for use in variable initializations\n\/\/ such as\n\/\/\tvar s = template.SetMust(template.ParseSetFile(\"file\"))\nfunc SetMust(s *Set, err os.Error) *Set {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s\n}\n\n\/\/ ParseFile parses the named files into a set of named templates.\n\/\/ Each file must be parseable by itself. Parsing stops if an error is\n\/\/ encountered.\nfunc (s *Set) ParseFile(filenames ...string) (*Set, os.Error) {\n\tfor _, filename := range filenames {\n\t\tb, err := ioutil.ReadFile(filename)\n\t\tif err != nil {\n\t\t\treturn s, err\n\t\t}\n\t\t_, err = s.Parse(string(b))\n\t\tif err != nil {\n\t\t\treturn s, err\n\t\t}\n\t}\n\treturn s, nil\n}\n\n\/\/ ParseSetFile creates a new Set and parses the set definition from the\n\/\/ named files. Each file must be individually parseable.\nfunc ParseSetFile(filenames ...string) (*Set, os.Error) {\n\ts := new(Set)\n\ts.init()\n\tfor _, filename := range filenames {\n\t\tb, err := ioutil.ReadFile(filename)\n\t\tif err != nil {\n\t\t\treturn s, err\n\t\t}\n\t\t_, err = s.Parse(string(b))\n\t\tif err != nil {\n\t\t\treturn s, err\n\t\t}\n\t}\n\treturn s, nil\n}\n\n\/\/ ParseFiles parses the set definition from the files identified by the\n\/\/ pattern.  The pattern is processed by filepath.Glob and must match at\n\/\/ least one file.\nfunc (s *Set) ParseFiles(pattern string) (*Set, os.Error) {\n\tfilenames, err := filepath.Glob(pattern)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\tif len(filenames) == 0 {\n\t\treturn s, fmt.Errorf(\"pattern matches no files: %#q\", pattern)\n\t}\n\treturn s.ParseFile(filenames...)\n}\n\n\/\/ ParseSetFiles creates a new Set and parses the set definition from the\n\/\/ files identified by the pattern. The pattern is processed by filepath.Glob\n\/\/ and must match at least one file.\nfunc ParseSetFiles(pattern string) (*Set, os.Error) {\n\tset, err := new(Set).ParseFiles(pattern)\n\tif err != nil {\n\t\treturn set, err\n\t}\n\treturn set, nil\n}\n\n\/\/ Functions and methods to parse stand-alone template files into a set.\n\n\/\/ ParseTemplateFile parses the named template files and adds\n\/\/ them to the set. Each template will named the base name of\n\/\/ its file.\n\/\/ Unlike with ParseFile, each file should be a stand-alone template\n\/\/ definition suitable for Template.Parse (not Set.Parse); that is, the\n\/\/ file does not contain {{define}} clauses. ParseTemplateFile is\n\/\/ therefore equivalent to calling the ParseFile function to create\n\/\/ individual templates, which are then added to the set.\n\/\/ Each file must be parseable by itself. Parsing stops if an error is\n\/\/ encountered.\nfunc (s *Set) ParseTemplateFile(filenames ...string) (*Set, os.Error) {\n\tfor _, filename := range filenames {\n\t\t_, err := parseFileInSet(filename, s)\n\t\tif err != nil {\n\t\t\treturn s, err\n\t\t}\n\t}\n\treturn s, nil\n}\n\n\/\/ ParseTemplateFiles parses the template files matched by the\n\/\/ patern and adds them to the set. Each template will named\n\/\/ the base name of its file.\n\/\/ Unlike with ParseFiles, each file should be a stand-alone template\n\/\/ definition suitable for Template.Parse (not Set.Parse); that is, the\n\/\/ file does not contain {{define}} clauses. ParseTemplateFiles is\n\/\/ therefore equivalent to calling the ParseFile function to create\n\/\/ individual templates, which are then added to the set.\n\/\/ Each file must be parseable by itself. Parsing stops if an error is\n\/\/ encountered.\nfunc (s *Set) ParseTemplateFiles(pattern string) (*Set, os.Error) {\n\tfilenames, err := filepath.Glob(pattern)\n\tif err != nil {\n\t\treturn s, err\n\t}\n\tfor _, filename := range filenames {\n\t\t_, err := parseFileInSet(filename, s)\n\t\tif err != nil {\n\t\t\treturn s, err\n\t\t}\n\t}\n\treturn s, nil\n}\n\n\/\/ ParseTemplateFile creates a set by parsing the named files,\n\/\/ each of which defines a single template. Each template will\n\/\/ named the base name of its file.\n\/\/ Unlike with ParseFile, each file should be a stand-alone template\n\/\/ definition suitable for Template.Parse (not Set.Parse); that is, the\n\/\/ file does not contain {{define}} clauses. ParseTemplateFile is\n\/\/ therefore equivalent to calling the ParseFile function to create\n\/\/ individual templates, which are then added to the set.\n\/\/ Each file must be parseable by itself. Parsing stops if an error is\n\/\/ encountered.\nfunc ParseTemplateFile(filenames ...string) (*Set, os.Error) {\n\tset := new(Set)\n\tset.init()\n\tfor _, filename := range filenames {\n\t\tt, err := ParseFile(filename)\n\t\tif err != nil {\n\t\t\treturn set, err\n\t\t}\n\t\tif err := set.add(t); err != nil {\n\t\t\treturn set, err\n\t\t}\n\t}\n\treturn set, nil\n}\n\n\/\/ ParseTemplateFiles creates a set by parsing the files matched\n\/\/ by the pattern, each of which defines a single template. Each\n\/\/ template will named the base name of its file.\n\/\/ Unlike with ParseFiles, each file should be a stand-alone template\n\/\/ definition suitable for Template.Parse (not Set.Parse); that is, the\n\/\/ file does not contain {{define}} clauses. ParseTemplateFiles is\n\/\/ therefore equivalent to calling the ParseFile function to create\n\/\/ individual templates, which are then added to the set.\n\/\/ Each file must be parseable by itself. Parsing stops if an error is\n\/\/ encountered.\nfunc ParseTemplateFiles(pattern string) (*Set, os.Error) {\n\tset := new(Set)\n\tset.init()\n\tfilenames, err := filepath.Glob(pattern)\n\tif err != nil {\n\t\treturn set, err\n\t}\n\tfor _, filename := range filenames {\n\t\tt, err := ParseFile(filename)\n\t\tif err != nil {\n\t\t\treturn set, err\n\t\t}\n\t\tif err := set.add(t); err != nil {\n\t\t\treturn set, err\n\t\t}\n\t}\n\treturn set, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2010 The Walk Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage walk\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"unsafe\"\n)\n\nimport (\n\t. \"walk\/winapi\"\n\t. \"walk\/winapi\/gdi32\"\n\t. \"walk\/winapi\/kernel32\"\n\t. \"walk\/winapi\/user32\"\n)\n\ntype CloseReason int\n\nconst (\n\tCloseReasonUnknown CloseReason = iota\n\tCloseReasonUser\n)\n\ntype TopLevelWindow struct {\n\tContainerBase\n\towner             RootWidget\n\tclosingPublisher  CloseEventPublisher\n\tcloseReason       CloseReason\n\tprevFocusHWnd     HWND\n\tisInRestoreState  bool\n\tstartingPublisher EventPublisher\n}\n\nfunc (tlw *TopLevelWindow) LayoutFlags() LayoutFlags {\n\treturn ShrinkableHorz | ShrinkableVert | GrowableHorz | GrowableVert | GreedyHorz | GreedyVert\n}\n\nfunc (tlw *TopLevelWindow) SizeHint() Size {\n\treturn tlw.dialogBaseUnitsToPixels(Size{252, 218})\n}\n\nfunc (tlw *TopLevelWindow) Title() string {\n\treturn widgetText(tlw.hWnd)\n}\n\nfunc (tlw *TopLevelWindow) SetTitle(value string) os.Error {\n\treturn setWidgetText(tlw.hWnd, value)\n}\n\nfunc (tlw *TopLevelWindow) Run() int {\n\ttlw.startingPublisher.Publish()\n\n\tvar msg MSG\n\n\tfor tlw.hWnd != 0 {\n\t\tswitch GetMessage(&msg, 0, 0, 0) {\n\t\tcase 0:\n\t\t\treturn int(msg.WParam)\n\n\t\tcase -1:\n\t\t\treturn -1\n\t\t}\n\n\t\tif !IsDialogMessage(tlw.hWnd, &msg) {\n\t\t\tTranslateMessage(&msg)\n\t\t\tDispatchMessage(&msg)\n\t\t}\n\t}\n\n\treturn 0\n}\n\nfunc (tlw *TopLevelWindow) Starting() *Event {\n\treturn tlw.startingPublisher.Event()\n}\n\nfunc (tlw *TopLevelWindow) Owner() RootWidget {\n\treturn tlw.owner\n}\n\nfunc (tlw *TopLevelWindow) SetOwner(value RootWidget) os.Error {\n\ttlw.owner = value\n\n\tvar ownerHWnd HWND\n\tif value != nil {\n\t\townerHWnd = value.BaseWidget().hWnd\n\t}\n\n\tSetLastError(0)\n\tif 0 == SetWindowLong(tlw.hWnd, GWL_HWNDPARENT, int(ownerHWnd)) && GetLastError() != 0 {\n\t\treturn lastError(\"SetWindowLong\")\n\t}\n\n\treturn nil\n}\n\nfunc (tlw *TopLevelWindow) Hide() {\n\ttlw.SetVisible(false)\n}\n\nfunc (tlw *TopLevelWindow) Show() {\n\ttlw.SetVisible(true)\n}\n\nfunc (tlw *TopLevelWindow) close() os.Error {\n\ttlw.Dispose()\n\n\treturn nil\n}\n\nfunc (tlw *TopLevelWindow) Close() os.Error {\n\tSendMessage(tlw.hWnd, WM_CLOSE, 0, 0)\n\n\treturn nil\n}\n\nfunc (tlw *TopLevelWindow) SaveState() os.Error {\n\tvar wp WINDOWPLACEMENT\n\n\twp.Length = uint(unsafe.Sizeof(wp))\n\n\tif !GetWindowPlacement(tlw.hWnd, &wp) {\n\t\treturn lastError(\"GetWindowPlacement\")\n\t}\n\n\tstate := fmt.Sprint(\n\t\twp.Flags, wp.ShowCmd,\n\t\twp.PtMinPosition.X, wp.PtMinPosition.Y,\n\t\twp.PtMaxPosition.X, wp.PtMaxPosition.Y,\n\t\twp.RcNormalPosition.Left, wp.RcNormalPosition.Top,\n\t\twp.RcNormalPosition.Right, wp.RcNormalPosition.Bottom)\n\n\tif err := tlw.putState(state); err != nil {\n\t\treturn err\n\t}\n\n\treturn tlw.ContainerBase.SaveState()\n}\n\nfunc (tlw *TopLevelWindow) RestoreState() os.Error {\n\tif tlw.isInRestoreState {\n\t\treturn nil\n\t}\n\ttlw.isInRestoreState = true\n\tdefer func() {\n\t\ttlw.isInRestoreState = false\n\t}()\n\n\tstate, err := tlw.getState()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif state == \"\" {\n\t\treturn nil\n\t}\n\n\tvar wp WINDOWPLACEMENT\n\n\tif _, err := fmt.Sscan(state,\n\t\t&wp.Flags, &wp.ShowCmd,\n\t\t&wp.PtMinPosition.X, &wp.PtMinPosition.Y,\n\t\t&wp.PtMaxPosition.X, &wp.PtMaxPosition.Y,\n\t\t&wp.RcNormalPosition.Left, &wp.RcNormalPosition.Top,\n\t\t&wp.RcNormalPosition.Right, &wp.RcNormalPosition.Bottom); err != nil {\n\t\treturn err\n\t}\n\n\twp.Length = uint(unsafe.Sizeof(wp))\n\n\tif !SetWindowPlacement(tlw.hWnd, &wp) {\n\t\treturn lastError(\"SetWindowPlacement\")\n\t}\n\n\tif err := tlw.ContainerBase.RestoreState(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (tlw *TopLevelWindow) Closing() *CloseEvent {\n\treturn tlw.closingPublisher.Event()\n}\n\nfunc (tlw *TopLevelWindow) wndProc(hwnd HWND, msg uint, wParam, lParam uintptr) uintptr {\n\tswitch msg {\n\tcase WM_ACTIVATE:\n\t\tswitch LOWORD(uint(wParam)) {\n\t\tcase WA_ACTIVE, WA_CLICKACTIVE:\n\t\t\tif tlw.prevFocusHWnd != 0 {\n\t\t\t\tSetFocus(tlw.prevFocusHWnd)\n\t\t\t}\n\n\t\tcase WA_INACTIVE:\n\t\t\ttlw.prevFocusHWnd = GetFocus()\n\t\t}\n\t\treturn 0\n\n\tcase WM_CLOSE:\n\t\ttlw.closeReason = CloseReasonUnknown\n\t\tvar canceled bool\n\t\ttlw.closingPublisher.Publish(&canceled, tlw.closeReason)\n\t\tif !canceled {\n\t\t\tif tlw.owner != nil {\n\t\t\t\ttlw.owner.SetEnabled(true)\n\t\t\t\tif !SetWindowPos(tlw.owner.BaseWidget().hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW) {\n\t\t\t\t\tlastError(\"SetWindowPos\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttlw.close()\n\t\t}\n\t\treturn 0\n\n\tcase WM_GETMINMAXINFO:\n\t\tmmi := (*MINMAXINFO)(unsafe.Pointer(lParam))\n\t\tvar min Size\n\t\tif tlw.layout != nil {\n\t\t\tmin = tlw.sizeFromClientSize(tlw.layout.MinSize())\n\t\t}\n\t\tmmi.PtMinTrackSize = POINT{\n\t\t\tmaxi(min.Width, tlw.minSize.Width),\n\t\t\tmaxi(min.Height, tlw.minSize.Height),\n\t\t}\n\t\treturn 0\n\n\tcase WM_SYSCOMMAND:\n\t\tif wParam == SC_CLOSE {\n\t\t\ttlw.closeReason = CloseReasonUser\n\t\t}\n\t}\n\n\treturn tlw.ContainerBase.wndProc(hwnd, msg, wParam, lParam)\n}\n<commit_msg>Add a Synchronize function that allows to run a closure within the main thread.<commit_after>\/\/ Copyright 2010 The Walk Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage walk\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"unsafe\"\n\t\"sync\"\n)\n\nimport (\n\t. \"walk\/winapi\"\n\t. \"walk\/winapi\/gdi32\"\n\t. \"walk\/winapi\/kernel32\"\n\t. \"walk\/winapi\/user32\"\n)\n\ntype CloseReason int\n\nconst (\n\tCloseReasonUnknown CloseReason = iota\n\tCloseReasonUser\n)\n\nvar syncFuncs struct {\n\tm     sync.Mutex\n\tfuncs []func()\n}\n\nfunc Synchronize(f func()) {\n\tsyncFuncs.m.Lock()\n\tdefer syncFuncs.m.Unlock()\n\tsyncFuncs.funcs = append(syncFuncs.funcs, f)\n}\n\nfunc runSynchronized() {\n\t\/\/ Clear the list of callbacks first to avoid deadlock\n\t\/\/ if a callback itself calls Synchronize()...\n\tsyncFuncs.m.Lock()\n\tfuncs := syncFuncs.funcs\n\tsyncFuncs.funcs = nil\n\tsyncFuncs.m.Unlock()\n\tfor _, f := range funcs {\n\t\tf()\n\t}\n}\n\ntype TopLevelWindow struct {\n\tContainerBase\n\towner             RootWidget\n\tclosingPublisher  CloseEventPublisher\n\tcloseReason       CloseReason\n\tprevFocusHWnd     HWND\n\tisInRestoreState  bool\n\tstartingPublisher EventPublisher\n}\n\nfunc (tlw *TopLevelWindow) LayoutFlags() LayoutFlags {\n\treturn ShrinkableHorz | ShrinkableVert | GrowableHorz | GrowableVert | GreedyHorz | GreedyVert\n}\n\nfunc (tlw *TopLevelWindow) SizeHint() Size {\n\treturn tlw.dialogBaseUnitsToPixels(Size{252, 218})\n}\n\nfunc (tlw *TopLevelWindow) Title() string {\n\treturn widgetText(tlw.hWnd)\n}\n\nfunc (tlw *TopLevelWindow) SetTitle(value string) os.Error {\n\treturn setWidgetText(tlw.hWnd, value)\n}\n\nfunc (tlw *TopLevelWindow) Run() int {\n\ttlw.startingPublisher.Publish()\n\n\tvar msg MSG\n\n\tfor tlw.hWnd != 0 {\n\t\trunSynchronized()\n\t\tswitch GetMessage(&msg, 0, 0, 0) {\n\t\tcase 0:\n\t\t\treturn int(msg.WParam)\n\n\t\tcase -1:\n\t\t\treturn -1\n\t\t}\n\n\t\tif !IsDialogMessage(tlw.hWnd, &msg) {\n\t\t\tTranslateMessage(&msg)\n\t\t\tDispatchMessage(&msg)\n\t\t}\n\t}\n\n\treturn 0\n}\n\nfunc (tlw *TopLevelWindow) Starting() *Event {\n\treturn tlw.startingPublisher.Event()\n}\n\nfunc (tlw *TopLevelWindow) Owner() RootWidget {\n\treturn tlw.owner\n}\n\nfunc (tlw *TopLevelWindow) SetOwner(value RootWidget) os.Error {\n\ttlw.owner = value\n\n\tvar ownerHWnd HWND\n\tif value != nil {\n\t\townerHWnd = value.BaseWidget().hWnd\n\t}\n\n\tSetLastError(0)\n\tif 0 == SetWindowLong(tlw.hWnd, GWL_HWNDPARENT, int(ownerHWnd)) && GetLastError() != 0 {\n\t\treturn lastError(\"SetWindowLong\")\n\t}\n\n\treturn nil\n}\n\nfunc (tlw *TopLevelWindow) Hide() {\n\ttlw.SetVisible(false)\n}\n\nfunc (tlw *TopLevelWindow) Show() {\n\ttlw.SetVisible(true)\n}\n\nfunc (tlw *TopLevelWindow) close() os.Error {\n\ttlw.Dispose()\n\n\treturn nil\n}\n\nfunc (tlw *TopLevelWindow) Close() os.Error {\n\tSendMessage(tlw.hWnd, WM_CLOSE, 0, 0)\n\n\treturn nil\n}\n\nfunc (tlw *TopLevelWindow) SaveState() os.Error {\n\tvar wp WINDOWPLACEMENT\n\n\twp.Length = uint(unsafe.Sizeof(wp))\n\n\tif !GetWindowPlacement(tlw.hWnd, &wp) {\n\t\treturn lastError(\"GetWindowPlacement\")\n\t}\n\n\tstate := fmt.Sprint(\n\t\twp.Flags, wp.ShowCmd,\n\t\twp.PtMinPosition.X, wp.PtMinPosition.Y,\n\t\twp.PtMaxPosition.X, wp.PtMaxPosition.Y,\n\t\twp.RcNormalPosition.Left, wp.RcNormalPosition.Top,\n\t\twp.RcNormalPosition.Right, wp.RcNormalPosition.Bottom)\n\n\tif err := tlw.putState(state); err != nil {\n\t\treturn err\n\t}\n\n\treturn tlw.ContainerBase.SaveState()\n}\n\nfunc (tlw *TopLevelWindow) RestoreState() os.Error {\n\tif tlw.isInRestoreState {\n\t\treturn nil\n\t}\n\ttlw.isInRestoreState = true\n\tdefer func() {\n\t\ttlw.isInRestoreState = false\n\t}()\n\n\tstate, err := tlw.getState()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif state == \"\" {\n\t\treturn nil\n\t}\n\n\tvar wp WINDOWPLACEMENT\n\n\tif _, err := fmt.Sscan(state,\n\t\t&wp.Flags, &wp.ShowCmd,\n\t\t&wp.PtMinPosition.X, &wp.PtMinPosition.Y,\n\t\t&wp.PtMaxPosition.X, &wp.PtMaxPosition.Y,\n\t\t&wp.RcNormalPosition.Left, &wp.RcNormalPosition.Top,\n\t\t&wp.RcNormalPosition.Right, &wp.RcNormalPosition.Bottom); err != nil {\n\t\treturn err\n\t}\n\n\twp.Length = uint(unsafe.Sizeof(wp))\n\n\tif !SetWindowPlacement(tlw.hWnd, &wp) {\n\t\treturn lastError(\"SetWindowPlacement\")\n\t}\n\n\tif err := tlw.ContainerBase.RestoreState(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (tlw *TopLevelWindow) Closing() *CloseEvent {\n\treturn tlw.closingPublisher.Event()\n}\n\nfunc (tlw *TopLevelWindow) wndProc(hwnd HWND, msg uint, wParam, lParam uintptr) uintptr {\n\tswitch msg {\n\tcase WM_ACTIVATE:\n\t\tswitch LOWORD(uint(wParam)) {\n\t\tcase WA_ACTIVE, WA_CLICKACTIVE:\n\t\t\tif tlw.prevFocusHWnd != 0 {\n\t\t\t\tSetFocus(tlw.prevFocusHWnd)\n\t\t\t}\n\n\t\tcase WA_INACTIVE:\n\t\t\ttlw.prevFocusHWnd = GetFocus()\n\t\t}\n\t\treturn 0\n\n\tcase WM_CLOSE:\n\t\ttlw.closeReason = CloseReasonUnknown\n\t\tvar canceled bool\n\t\ttlw.closingPublisher.Publish(&canceled, tlw.closeReason)\n\t\tif !canceled {\n\t\t\tif tlw.owner != nil {\n\t\t\t\ttlw.owner.SetEnabled(true)\n\t\t\t\tif !SetWindowPos(tlw.owner.BaseWidget().hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW) {\n\t\t\t\t\tlastError(\"SetWindowPos\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttlw.close()\n\t\t}\n\t\treturn 0\n\n\tcase WM_GETMINMAXINFO:\n\t\tmmi := (*MINMAXINFO)(unsafe.Pointer(lParam))\n\t\tvar min Size\n\t\tif tlw.layout != nil {\n\t\t\tmin = tlw.sizeFromClientSize(tlw.layout.MinSize())\n\t\t}\n\t\tmmi.PtMinTrackSize = POINT{\n\t\t\tmaxi(min.Width, tlw.minSize.Width),\n\t\t\tmaxi(min.Height, tlw.minSize.Height),\n\t\t}\n\t\treturn 0\n\n\tcase WM_SYSCOMMAND:\n\t\tif wParam == SC_CLOSE {\n\t\t\ttlw.closeReason = CloseReasonUser\n\t\t}\n\t}\n\n\treturn tlw.ContainerBase.wndProc(hwnd, msg, wParam, lParam)\n}\n<|endoftext|>"}
{"text":"<commit_before>package transport\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/gammazero\/nexus\/logger\"\n\t\"github.com\/gammazero\/nexus\/transport\/serialize\"\n\t\"github.com\/gammazero\/nexus\/wamp\"\n\t\"github.com\/gorilla\/websocket\"\n)\n\n\/\/ WebsocketPeer implements the Peer interface, connecting the Send and Recv\n\/\/ methods to a websocket.\ntype websocketPeer struct {\n\tconn        *websocket.Conn\n\tserializer  serialize.Serializer\n\tpayloadType int\n\n\t\/\/ Used to signal the websocket is closed.\n\tclosed chan struct{}\n\n\t\/\/ Channels communicate with router.\n\trd chan wamp.Message\n\twr chan wamp.Message\n\n\t\/\/ Stop send handler without closing wr channel.\n\tstopSend chan struct{}\n\n\tlog logger.Logger\n}\n\nconst (\n\t\/\/ WAMP uses the following WebSocket subprotocol identifiers for unbatched\n\t\/\/ modes:\n\tjsonWebsocketProtocol    = \"wamp.2.json\"\n\tmsgpackWebsocketProtocol = \"wamp.2.msgpack\"\n\n\tdefaultOutQueueSize = 16\n\tctrlTimeout         = 5 * time.Second\n)\n\ntype DialFunc func(network, addr string) (net.Conn, error)\n\n\/\/ ConnectWebsockerPeer creates a new websockerPeer with the specified config,\n\/\/ and connects it to the websocket server at the specified URL.\n\/\/\n\/\/ queueSize is the maximum number of messages that can be queue to be written\n\/\/ to the websocker.  Once the queue has reached this limit, the WAMP router\n\/\/ will drop messages in order to not block.  A value of < 1 uses the default\n\/\/ size.\nfunc ConnectWebsocketPeer(url string, serialization serialize.Serialization, tlsConfig *tls.Config, dial DialFunc, outQueueSize int, logger logger.Logger) (wamp.Peer, error) {\n\tvar (\n\t\tprotocol    string\n\t\tpayloadType int\n\t\tserializer  serialize.Serializer\n\t)\n\n\tswitch serialization {\n\tcase serialize.JSON:\n\t\tprotocol = jsonWebsocketProtocol\n\t\tpayloadType = websocket.TextMessage\n\t\tserializer = &serialize.JSONSerializer{}\n\tcase serialize.MSGPACK:\n\t\tprotocol = msgpackWebsocketProtocol\n\t\tpayloadType = websocket.BinaryMessage\n\t\tserializer = &serialize.MessagePackSerializer{}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported serialization: %v\", serialization)\n\t}\n\n\tdialer := websocket.Dialer{\n\t\tSubprotocols:    []string{protocol},\n\t\tTLSClientConfig: tlsConfig,\n\t\tProxy:           http.ProxyFromEnvironment,\n\t\tNetDial:         dial,\n\t}\n\tconn, _, err := dialer.Dial(url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewWebsocketPeer(conn, serializer, payloadType, outQueueSize, logger), nil\n}\n\n\/\/ NewWebsockerPeer creates a websocket peer from an existing websocket\n\/\/ connection.  This is used for for hanndling clients connecting to the WAMP\n\/\/ service.\nfunc NewWebsocketPeer(conn *websocket.Conn, serializer serialize.Serializer, payloadType int, outQueueSize int, logger logger.Logger) wamp.Peer {\n\tif outQueueSize < 1 {\n\t\toutQueueSize = defaultOutQueueSize\n\t}\n\tw := &websocketPeer{\n\t\tconn:        conn,\n\t\tserializer:  serializer,\n\t\tpayloadType: payloadType,\n\t\tclosed:      make(chan struct{}),\n\t\tstopSend:    make(chan struct{}),\n\n\t\t\/\/ Messages read from the websocket can be handled immediately, since\n\t\t\/\/ they have traveled over the websocket and the read channel does not\n\t\t\/\/ need to be more than size 1.\n\t\trd: make(chan wamp.Message, 1),\n\n\t\t\/\/ The channel for messages being written to the websocket sould be\n\t\t\/\/ large enough to prevent blocking while waiting for a slow websocket\n\t\t\/\/ to send messages.  For this reason it may be necessary for these\n\t\t\/\/ messages to be put into an outbound queue that can grow.\n\t\twr: make(chan wamp.Message, outQueueSize),\n\n\t\tlog: logger,\n\t}\n\t\/\/ Sending to and receiving from websocket is handled concurrently.\n\tgo w.recvHandler()\n\tgo w.sendHandler()\n\n\treturn w\n}\n\nfunc (w *websocketPeer) Recv() <-chan wamp.Message { return w.rd }\n\nfunc (w *websocketPeer) Send(msg wamp.Message) {\n\tselect {\n\tcase w.wr <- msg:\n\tdefault:\n\t\tw.log.Println(\"WARNING: client blocked router.  Dropped:\",\n\t\t\tmsg.MessageType())\n\t}\n}\n\nfunc (w *websocketPeer) Close() {\n\tcloseMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure,\n\t\t\"goodbye\")\n\terr := w.conn.WriteControl(websocket.CloseMessage, closeMsg,\n\t\ttime.Now().Add(ctrlTimeout))\n\tif err != nil {\n\t\tw.log.Println(\"Error sending close message:\", err)\n\t}\n\tclose(w.closed)\n\tif err = w.conn.Close(); err != nil {\n\t\tw.log.Println(\"Error closing connection:\", err)\n\t}\n}\n\n\/\/ sendHandler pulls messages from the write channel, and pushes them to the\n\/\/ websocket.\nfunc (w *websocketPeer) sendHandler() {\n\tfor {\n\t\tselect {\n\t\tcase msg, open := <-w.wr:\n\t\t\tif !open {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tb, err := w.serializer.Serialize(msg.(wamp.Message))\n\t\t\tif err != nil {\n\t\t\t\tw.log.Print(err)\n\t\t\t}\n\n\t\t\tif err = w.conn.WriteMessage(w.payloadType, b); err != nil {\n\t\t\t\tw.log.Print(err)\n\t\t\t}\n\t\tcase <-w.stopSend:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ recvHandler pulls messages from the websocket and pushes them to the read\n\/\/ channel.\nfunc (w *websocketPeer) recvHandler() {\n\tfor {\n\t\tmsgType, b, err := w.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tselect {\n\t\t\tcase <-w.closed:\n\t\t\t\tw.log.Print(\"Peer connection closed\")\n\t\t\tdefault:\n\t\t\t\tw.log.Println(\"Cannot read from peer:\", err)\n\t\t\t\tw.conn.Close()\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tif msgType == websocket.CloseMessage {\n\t\t\tw.conn.Close()\n\t\t\tbreak\n\t\t}\n\n\t\tmsg, err := w.serializer.Deserialize(b)\n\t\tif err != nil {\n\t\t\t\/\/ TODO: something more than merely logging?\n\t\t\tw.log.Println(\"Cannot deserialize peer message:\", err)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ It is OK for the router to block a client since routing should be\n\t\t\/\/ very quick compared to the time to transfer a message over\n\t\t\/\/ websocket, and a blocked client will not block other clients.\n\t\tw.rd <- msg\n\t}\n\t\/\/ Close read channel, cause router to remove session if not already.\n\tclose(w.rd)\n\t\/\/ Stop sendHandler, without closing write channel.\n\tclose(w.stopSend)\n}\n<commit_msg>cleanup websocket close<commit_after>package transport\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/gammazero\/nexus\/logger\"\n\t\"github.com\/gammazero\/nexus\/transport\/serialize\"\n\t\"github.com\/gammazero\/nexus\/wamp\"\n\t\"github.com\/gorilla\/websocket\"\n)\n\n\/\/ WebsocketPeer implements the Peer interface, connecting the Send and Recv\n\/\/ methods to a websocket.\ntype websocketPeer struct {\n\tconn        *websocket.Conn\n\tserializer  serialize.Serializer\n\tpayloadType int\n\n\t\/\/ Used to signal the websocket is closed explicitly.\n\tclosed chan struct{}\n\n\t\/\/ Channels communicate with router.\n\trd chan wamp.Message\n\twr chan wamp.Message\n\n\twsWriterDone chan struct{}\n\n\tlog logger.Logger\n}\n\nconst (\n\t\/\/ WAMP uses the following WebSocket subprotocol identifiers for unbatched\n\t\/\/ modes:\n\tjsonWebsocketProtocol    = \"wamp.2.json\"\n\tmsgpackWebsocketProtocol = \"wamp.2.msgpack\"\n\n\tdefaultOutQueueSize = 16\n\tctrlTimeout         = 5 * time.Second\n)\n\ntype DialFunc func(network, addr string) (net.Conn, error)\n\n\/\/ ConnectWebsockerPeer creates a new websockerPeer with the specified config,\n\/\/ and connects it to the websocket server at the specified URL.\n\/\/\n\/\/ queueSize is the maximum number of messages that can be queue to be written\n\/\/ to the websocker.  Once the queue has reached this limit, the WAMP router\n\/\/ will drop messages in order to not block.  A value of < 1 uses the default\n\/\/ size.\nfunc ConnectWebsocketPeer(url string, serialization serialize.Serialization, tlsConfig *tls.Config, dial DialFunc, outQueueSize int, logger logger.Logger) (wamp.Peer, error) {\n\tvar (\n\t\tprotocol    string\n\t\tpayloadType int\n\t\tserializer  serialize.Serializer\n\t)\n\n\tswitch serialization {\n\tcase serialize.JSON:\n\t\tprotocol = jsonWebsocketProtocol\n\t\tpayloadType = websocket.TextMessage\n\t\tserializer = &serialize.JSONSerializer{}\n\tcase serialize.MSGPACK:\n\t\tprotocol = msgpackWebsocketProtocol\n\t\tpayloadType = websocket.BinaryMessage\n\t\tserializer = &serialize.MessagePackSerializer{}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported serialization: %v\", serialization)\n\t}\n\n\tdialer := websocket.Dialer{\n\t\tSubprotocols:    []string{protocol},\n\t\tTLSClientConfig: tlsConfig,\n\t\tProxy:           http.ProxyFromEnvironment,\n\t\tNetDial:         dial,\n\t}\n\tconn, _, err := dialer.Dial(url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewWebsocketPeer(conn, serializer, payloadType, outQueueSize, logger), nil\n}\n\n\/\/ NewWebsockerPeer creates a websocket peer from an existing websocket\n\/\/ connection.  This is used for for hanndling clients connecting to the WAMP\n\/\/ service.\nfunc NewWebsocketPeer(conn *websocket.Conn, serializer serialize.Serializer, payloadType int, outQueueSize int, logger logger.Logger) wamp.Peer {\n\tif outQueueSize < 1 {\n\t\toutQueueSize = defaultOutQueueSize\n\t}\n\tw := &websocketPeer{\n\t\tconn:         conn,\n\t\tserializer:   serializer,\n\t\tpayloadType:  payloadType,\n\t\tclosed:       make(chan struct{}),\n\t\twsWriterDone: make(chan struct{}),\n\n\t\t\/\/ Messages read from the websocket can be handled immediately, since\n\t\t\/\/ they have traveled over the websocket and the read channel does not\n\t\t\/\/ need to be more than size 1.\n\t\trd: make(chan wamp.Message, 1),\n\n\t\t\/\/ The channel for messages being written to the websocket sould be\n\t\t\/\/ large enough to prevent blocking while waiting for a slow websocket\n\t\t\/\/ to send messages.  For this reason it may be necessary for these\n\t\t\/\/ messages to be put into an outbound queue that can grow.\n\t\twr: make(chan wamp.Message, outQueueSize),\n\n\t\tlog: logger,\n\t}\n\t\/\/ Sending to and receiving from websocket is handled concurrently.\n\tgo w.recvHandler()\n\tgo w.sendHandler()\n\n\treturn w\n}\n\nfunc (w *websocketPeer) Recv() <-chan wamp.Message { return w.rd }\n\nfunc (w *websocketPeer) Send(msg wamp.Message) {\n\tselect {\n\tcase w.wr <- msg:\n\tdefault:\n\t\tw.log.Println(\"WARNING: client blocked router.  Dropped:\",\n\t\t\tmsg.MessageType())\n\t}\n}\n\n\/\/ Close closes the websocker peer.  This closes the local send channel, and\n\/\/ sends a close control message to the websocket to tell the other side to\n\/\/ close.\n\/\/\n\/\/ *** Do not call Send after calling Close. ***\nfunc (w *websocketPeer) Close() {\n\t\/\/ Tell sendHandler to exit, allowing it to finish sending any queued\n\t\/\/ messages.  Do not close wr channel in case there are incoming messages\n\t\/\/ during close.\n\tw.wr <- nil\n\t<-w.wsWriterDone\n\n\tcloseMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure,\n\t\t\"goodbye\")\n\n\t\/\/ Tell recvHandler to close.\n\tclose(w.closed)\n\n\t\/\/ Ignore errors since websocket may have been closed by other side first\n\t\/\/ in response to a goodbye message.\n\tw.conn.WriteControl(websocket.CloseMessage, closeMsg,\n\t\ttime.Now().Add(ctrlTimeout))\n\tw.conn.Close()\n}\n\n\/\/ sendHandler pulls messages from the write channel, and pushes them to the\n\/\/ websocket.\nfunc (w *websocketPeer) sendHandler() {\n\tdefer close(w.wsWriterDone)\n\tfor msg := range w.wr {\n\t\tif msg == nil {\n\t\t\treturn\n\t\t}\n\t\tb, err := w.serializer.Serialize(msg.(wamp.Message))\n\t\tif err != nil {\n\t\t\tw.log.Print(err)\n\t\t}\n\n\t\tif err = w.conn.WriteMessage(w.payloadType, b); err != nil {\n\t\t\tw.log.Print(err)\n\t\t}\n\t}\n}\n\n\/\/ recvHandler pulls messages from the websocket and pushes them to the read\n\/\/ channel.\nfunc (w *websocketPeer) recvHandler() {\n\tfor {\n\t\tmsgType, b, err := w.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tselect {\n\t\t\tcase <-w.closed:\n\t\t\t\t\/\/ Peer was closed explicitly. sendHandler should have already\n\t\t\t\t\/\/ been told to exit.\n\t\t\tdefault:\n\t\t\t\t\/\/ Peer received control message to close.  Cause sendHandler\n\t\t\t\t\/\/ to exit without closing the write channel (in case writes\n\t\t\t\t\/\/ still happening) and allow it to finish sending any queued\n\t\t\t\t\/\/ messages.\n\t\t\t\tw.wr <- nil\n\t\t\t\t<-w.wsWriterDone\n\n\t\t\t\t\/\/ Close websocket connection.\n\t\t\t\tw.conn.Close()\n\t\t\t}\n\t\t\tif !strings.HasPrefix(err.Error(), \"websocket: close 1000\") {\n\t\t\t\tw.log.Print(err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tif msgType == websocket.CloseMessage {\n\t\t\tw.conn.Close()\n\t\t\tbreak\n\t\t}\n\n\t\tmsg, err := w.serializer.Deserialize(b)\n\t\tif err != nil {\n\t\t\t\/\/ TODO: something more than merely logging?\n\t\t\tw.log.Println(\"Cannot deserialize peer message:\", err)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ It is OK for the router to block a client since routing should be\n\t\t\/\/ very quick compared to the time to transfer a message over\n\t\t\/\/ websocket, and a blocked client will not block other clients.\n\t\tw.rd <- msg\n\t}\n\t\/\/ Close read channel, cause router to remove session if not already.\n\tclose(w.rd)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage http\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an\n\/\/ HTTP response or the Cookie header of an HTTP request.\n\/\/\n\/\/ See https:\/\/tools.ietf.org\/html\/rfc6265 for details.\ntype Cookie struct {\n\tName  string\n\tValue string\n\n\tPath       string    \/\/ optional\n\tDomain     string    \/\/ optional\n\tExpires    time.Time \/\/ optional\n\tRawExpires string    \/\/ for reading cookies only\n\n\t\/\/ MaxAge=0 means no 'Max-Age' attribute specified.\n\t\/\/ MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'\n\t\/\/ MaxAge>0 means Max-Age attribute present and given in seconds\n\tMaxAge   int\n\tSecure   bool\n\tHttpOnly bool\n\tSameSite SameSite\n\tRaw      string\n\tUnparsed []string \/\/ Raw text of unparsed attribute-value pairs\n}\n\n\/\/ SameSite allows a server define a cookie attribute making it impossible for\n\/\/ the browser to send this cookie along with cross-site requests. The main\n\/\/ goal is mitigate the risk of cross-origin information leakage, and provides\n\/\/ some protection against cross-site request forgery attacks.\n\/\/\n\/\/ See https:\/\/tools.ietf.org\/html\/draft-ietf-httpbis-cookie-same-site-00 for details.\ntype SameSite int\n\nconst (\n\tSameSiteDefaultMode SameSite = iota + 1\n\tSameSiteLaxMode\n\tSameSiteStrictMode\n)\n\n\/\/ readSetCookies parses all \"Set-Cookie\" values from\n\/\/ the header h and returns the successfully parsed Cookies.\nfunc readSetCookies(h Header) []*Cookie {\n\tcookieCount := len(h[\"Set-Cookie\"])\n\tif cookieCount == 0 {\n\t\treturn []*Cookie{}\n\t}\n\tcookies := make([]*Cookie, 0, cookieCount)\n\tfor _, line := range h[\"Set-Cookie\"] {\n\t\tparts := strings.Split(strings.TrimSpace(line), \";\")\n\t\tif len(parts) == 1 && parts[0] == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tparts[0] = strings.TrimSpace(parts[0])\n\t\tj := strings.Index(parts[0], \"=\")\n\t\tif j < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tname, value := parts[0][:j], parts[0][j+1:]\n\t\tif !isCookieNameValid(name) {\n\t\t\tcontinue\n\t\t}\n\t\tvalue, ok := parseCookieValue(value, true)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tc := &Cookie{\n\t\t\tName:  name,\n\t\t\tValue: value,\n\t\t\tRaw:   line,\n\t\t}\n\t\tfor i := 1; i < len(parts); i++ {\n\t\t\tparts[i] = strings.TrimSpace(parts[i])\n\t\t\tif len(parts[i]) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tattr, val := parts[i], \"\"\n\t\t\tif j := strings.Index(attr, \"=\"); j >= 0 {\n\t\t\t\tattr, val = attr[:j], attr[j+1:]\n\t\t\t}\n\t\t\tlowerAttr := strings.ToLower(attr)\n\t\t\tval, ok = parseCookieValue(val, false)\n\t\t\tif !ok {\n\t\t\t\tc.Unparsed = append(c.Unparsed, parts[i])\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch lowerAttr {\n\t\t\tcase \"samesite\":\n\t\t\t\tlowerVal := strings.ToLower(val)\n\t\t\t\tswitch lowerVal {\n\t\t\t\tcase \"lax\":\n\t\t\t\t\tc.SameSite = SameSiteLaxMode\n\t\t\t\tcase \"strict\":\n\t\t\t\t\tc.SameSite = SameSiteStrictMode\n\t\t\t\tdefault:\n\t\t\t\t\tc.SameSite = SameSiteDefaultMode\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\tcase \"secure\":\n\t\t\t\tc.Secure = true\n\t\t\t\tcontinue\n\t\t\tcase \"httponly\":\n\t\t\t\tc.HttpOnly = true\n\t\t\t\tcontinue\n\t\t\tcase \"domain\":\n\t\t\t\tc.Domain = val\n\t\t\t\tcontinue\n\t\t\tcase \"max-age\":\n\t\t\t\tsecs, err := strconv.Atoi(val)\n\t\t\t\tif err != nil || secs != 0 && val[0] == '0' {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif secs <= 0 {\n\t\t\t\t\tsecs = -1\n\t\t\t\t}\n\t\t\t\tc.MaxAge = secs\n\t\t\t\tcontinue\n\t\t\tcase \"expires\":\n\t\t\t\tc.RawExpires = val\n\t\t\t\texptime, err := time.Parse(time.RFC1123, val)\n\t\t\t\tif err != nil {\n\t\t\t\t\texptime, err = time.Parse(\"Mon, 02-Jan-2006 15:04:05 MST\", val)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tc.Expires = time.Time{}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tc.Expires = exptime.UTC()\n\t\t\t\tcontinue\n\t\t\tcase \"path\":\n\t\t\t\tc.Path = val\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.Unparsed = append(c.Unparsed, parts[i])\n\t\t}\n\t\tcookies = append(cookies, c)\n\t}\n\treturn cookies\n}\n\n\/\/ SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers.\n\/\/ The provided cookie must have a valid Name. Invalid cookies may be\n\/\/ silently dropped.\nfunc SetCookie(w ResponseWriter, cookie *Cookie) {\n\tif v := cookie.String(); v != \"\" {\n\t\tw.Header().Add(\"Set-Cookie\", v)\n\t}\n}\n\n\/\/ String returns the serialization of the cookie for use in a Cookie\n\/\/ header (if only Name and Value are set) or a Set-Cookie response\n\/\/ header (if other fields are set).\n\/\/ If c is nil or c.Name is invalid, the empty string is returned.\nfunc (c *Cookie) String() string {\n\tif c == nil || !isCookieNameValid(c.Name) {\n\t\treturn \"\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(sanitizeCookieName(c.Name))\n\tb.WriteRune('=')\n\tb.WriteString(sanitizeCookieValue(c.Value))\n\n\tif len(c.Path) > 0 {\n\t\tb.WriteString(\"; Path=\")\n\t\tb.WriteString(sanitizeCookiePath(c.Path))\n\t}\n\tif len(c.Domain) > 0 {\n\t\tif validCookieDomain(c.Domain) {\n\t\t\t\/\/ A c.Domain containing illegal characters is not\n\t\t\t\/\/ sanitized but simply dropped which turns the cookie\n\t\t\t\/\/ into a host-only cookie. A leading dot is okay\n\t\t\t\/\/ but won't be sent.\n\t\t\td := c.Domain\n\t\t\tif d[0] == '.' {\n\t\t\t\td = d[1:]\n\t\t\t}\n\t\t\tb.WriteString(\"; Domain=\")\n\t\t\tb.WriteString(d)\n\t\t} else {\n\t\t\tlog.Printf(\"net\/http: invalid Cookie.Domain %q; dropping domain attribute\", c.Domain)\n\t\t}\n\t}\n\tvar buf [len(TimeFormat)]byte\n\tif validCookieExpires(c.Expires) {\n\t\tb.WriteString(\"; Expires=\")\n\t\tb.Write(c.Expires.UTC().AppendFormat(buf[:0], TimeFormat))\n\t}\n\tif c.MaxAge > 0 {\n\t\tb.WriteString(\"; Max-Age=\")\n\t\tb.Write(strconv.AppendInt(buf[:0], int64(c.MaxAge), 10))\n\t} else if c.MaxAge < 0 {\n\t\tb.WriteString(\"; Max-Age=0\")\n\t}\n\tif c.HttpOnly {\n\t\tb.WriteString(\"; HttpOnly\")\n\t}\n\tif c.Secure {\n\t\tb.WriteString(\"; Secure\")\n\t}\n\tswitch c.SameSite {\n\tcase SameSiteDefaultMode:\n\t\tb.WriteString(\"; SameSite\")\n\tcase SameSiteLaxMode:\n\t\tb.WriteString(\"; SameSite=Lax\")\n\tcase SameSiteStrictMode:\n\t\tb.WriteString(\"; SameSite=Strict\")\n\t}\n\treturn b.String()\n}\n\n\/\/ readCookies parses all \"Cookie\" values from the header h and\n\/\/ returns the successfully parsed Cookies.\n\/\/\n\/\/ if filter isn't empty, only cookies of that name are returned\nfunc readCookies(h Header, filter string) []*Cookie {\n\tlines, ok := h[\"Cookie\"]\n\tif !ok {\n\t\treturn []*Cookie{}\n\t}\n\n\tcookies := []*Cookie{}\n\tfor _, line := range lines {\n\t\tparts := strings.Split(strings.TrimSpace(line), \";\")\n\t\tif len(parts) == 1 && parts[0] == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Per-line attributes\n\t\tfor i := 0; i < len(parts); i++ {\n\t\t\tparts[i] = strings.TrimSpace(parts[i])\n\t\t\tif len(parts[i]) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tname, val := parts[i], \"\"\n\t\t\tif j := strings.Index(name, \"=\"); j >= 0 {\n\t\t\t\tname, val = name[:j], name[j+1:]\n\t\t\t}\n\t\t\tif !isCookieNameValid(name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif filter != \"\" && filter != name {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tval, ok := parseCookieValue(val, true)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcookies = append(cookies, &Cookie{Name: name, Value: val})\n\t\t}\n\t}\n\treturn cookies\n}\n\n\/\/ validCookieDomain returns whether v is a valid cookie domain-value.\nfunc validCookieDomain(v string) bool {\n\tif isCookieDomainName(v) {\n\t\treturn true\n\t}\n\tif net.ParseIP(v) != nil && !strings.Contains(v, \":\") {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ validCookieExpires returns whether v is a valid cookie expires-value.\nfunc validCookieExpires(t time.Time) bool {\n\t\/\/ IETF RFC 6265 Section 5.1.1.5, the year must not be less than 1601\n\treturn t.Year() >= 1601\n}\n\n\/\/ isCookieDomainName returns whether s is a valid domain name or a valid\n\/\/ domain name with a leading dot '.'.  It is almost a direct copy of\n\/\/ package net's isDomainName.\nfunc isCookieDomainName(s string) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\tif len(s) > 255 {\n\t\treturn false\n\t}\n\n\tif s[0] == '.' {\n\t\t\/\/ A cookie a domain attribute may start with a leading dot.\n\t\ts = s[1:]\n\t}\n\tlast := byte('.')\n\tok := false \/\/ Ok once we've seen a letter.\n\tpartlen := 0\n\tfor i := 0; i < len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\tdefault:\n\t\t\treturn false\n\t\tcase 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':\n\t\t\t\/\/ No '_' allowed here (in contrast to package net).\n\t\t\tok = true\n\t\t\tpartlen++\n\t\tcase '0' <= c && c <= '9':\n\t\t\t\/\/ fine\n\t\t\tpartlen++\n\t\tcase c == '-':\n\t\t\t\/\/ Byte before dash cannot be dot.\n\t\t\tif last == '.' {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpartlen++\n\t\tcase c == '.':\n\t\t\t\/\/ Byte before dot cannot be dot, dash.\n\t\t\tif last == '.' || last == '-' {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif partlen > 63 || partlen == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpartlen = 0\n\t\t}\n\t\tlast = c\n\t}\n\tif last == '-' || partlen > 63 {\n\t\treturn false\n\t}\n\n\treturn ok\n}\n\nvar cookieNameSanitizer = strings.NewReplacer(\"\\n\", \"-\", \"\\r\", \"-\")\n\nfunc sanitizeCookieName(n string) string {\n\treturn cookieNameSanitizer.Replace(n)\n}\n\n\/\/ https:\/\/tools.ietf.org\/html\/rfc6265#section-4.1.1\n\/\/ cookie-value      = *cookie-octet \/ ( DQUOTE *cookie-octet DQUOTE )\n\/\/ cookie-octet      = %x21 \/ %x23-2B \/ %x2D-3A \/ %x3C-5B \/ %x5D-7E\n\/\/           ; US-ASCII characters excluding CTLs,\n\/\/           ; whitespace DQUOTE, comma, semicolon,\n\/\/           ; and backslash\n\/\/ We loosen this as spaces and commas are common in cookie values\n\/\/ but we produce a quoted cookie-value in when value starts or ends\n\/\/ with a comma or space.\n\/\/ See https:\/\/golang.org\/issue\/7243 for the discussion.\nfunc sanitizeCookieValue(v string) string {\n\tv = sanitizeOrWarn(\"Cookie.Value\", validCookieValueByte, v)\n\tif len(v) == 0 {\n\t\treturn v\n\t}\n\tif strings.IndexByte(v, ' ') >= 0 || strings.IndexByte(v, ',') >= 0 {\n\t\treturn `\"` + v + `\"`\n\t}\n\treturn v\n}\n\nfunc validCookieValueByte(b byte) bool {\n\treturn 0x20 <= b && b < 0x7f && b != '\"' && b != ';' && b != '\\\\'\n}\n\n\/\/ path-av           = \"Path=\" path-value\n\/\/ path-value        = <any CHAR except CTLs or \";\">\nfunc sanitizeCookiePath(v string) string {\n\treturn sanitizeOrWarn(\"Cookie.Path\", validCookiePathByte, v)\n}\n\nfunc validCookiePathByte(b byte) bool {\n\treturn 0x20 <= b && b < 0x7f && b != ';'\n}\n\nfunc sanitizeOrWarn(fieldName string, valid func(byte) bool, v string) string {\n\tok := true\n\tfor i := 0; i < len(v); i++ {\n\t\tif valid(v[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\"net\/http: invalid byte %q in %s; dropping invalid bytes\", v[i], fieldName)\n\t\tok = false\n\t\tbreak\n\t}\n\tif ok {\n\t\treturn v\n\t}\n\tbuf := make([]byte, 0, len(v))\n\tfor i := 0; i < len(v); i++ {\n\t\tif b := v[i]; valid(b) {\n\t\t\tbuf = append(buf, b)\n\t\t}\n\t}\n\treturn string(buf)\n}\n\nfunc parseCookieValue(raw string, allowDoubleQuote bool) (string, bool) {\n\t\/\/ Strip the quotes, if present.\n\tif allowDoubleQuote && len(raw) > 1 && raw[0] == '\"' && raw[len(raw)-1] == '\"' {\n\t\traw = raw[1 : len(raw)-1]\n\t}\n\tfor i := 0; i < len(raw); i++ {\n\t\tif !validCookieValueByte(raw[i]) {\n\t\t\treturn \"\", false\n\t\t}\n\t}\n\treturn raw, true\n}\n\nfunc isCookieNameValid(raw string) bool {\n\tif raw == \"\" {\n\t\treturn false\n\t}\n\treturn strings.IndexFunc(raw, isNotToken) < 0\n}\n<commit_msg>net\/http: add missing words to SameSite doc\/comments<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage http\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an\n\/\/ HTTP response or the Cookie header of an HTTP request.\n\/\/\n\/\/ See https:\/\/tools.ietf.org\/html\/rfc6265 for details.\ntype Cookie struct {\n\tName  string\n\tValue string\n\n\tPath       string    \/\/ optional\n\tDomain     string    \/\/ optional\n\tExpires    time.Time \/\/ optional\n\tRawExpires string    \/\/ for reading cookies only\n\n\t\/\/ MaxAge=0 means no 'Max-Age' attribute specified.\n\t\/\/ MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'\n\t\/\/ MaxAge>0 means Max-Age attribute present and given in seconds\n\tMaxAge   int\n\tSecure   bool\n\tHttpOnly bool\n\tSameSite SameSite\n\tRaw      string\n\tUnparsed []string \/\/ Raw text of unparsed attribute-value pairs\n}\n\n\/\/ SameSite allows a server to define a cookie attribute making it impossible for\n\/\/ the browser to send this cookie along with cross-site requests. The main\n\/\/ goal is to mitigate the risk of cross-origin information leakage, and provides\n\/\/ some protection against cross-site request forgery attacks.\n\/\/\n\/\/ See https:\/\/tools.ietf.org\/html\/draft-ietf-httpbis-cookie-same-site-00 for details.\ntype SameSite int\n\nconst (\n\tSameSiteDefaultMode SameSite = iota + 1\n\tSameSiteLaxMode\n\tSameSiteStrictMode\n)\n\n\/\/ readSetCookies parses all \"Set-Cookie\" values from\n\/\/ the header h and returns the successfully parsed Cookies.\nfunc readSetCookies(h Header) []*Cookie {\n\tcookieCount := len(h[\"Set-Cookie\"])\n\tif cookieCount == 0 {\n\t\treturn []*Cookie{}\n\t}\n\tcookies := make([]*Cookie, 0, cookieCount)\n\tfor _, line := range h[\"Set-Cookie\"] {\n\t\tparts := strings.Split(strings.TrimSpace(line), \";\")\n\t\tif len(parts) == 1 && parts[0] == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tparts[0] = strings.TrimSpace(parts[0])\n\t\tj := strings.Index(parts[0], \"=\")\n\t\tif j < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tname, value := parts[0][:j], parts[0][j+1:]\n\t\tif !isCookieNameValid(name) {\n\t\t\tcontinue\n\t\t}\n\t\tvalue, ok := parseCookieValue(value, true)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tc := &Cookie{\n\t\t\tName:  name,\n\t\t\tValue: value,\n\t\t\tRaw:   line,\n\t\t}\n\t\tfor i := 1; i < len(parts); i++ {\n\t\t\tparts[i] = strings.TrimSpace(parts[i])\n\t\t\tif len(parts[i]) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tattr, val := parts[i], \"\"\n\t\t\tif j := strings.Index(attr, \"=\"); j >= 0 {\n\t\t\t\tattr, val = attr[:j], attr[j+1:]\n\t\t\t}\n\t\t\tlowerAttr := strings.ToLower(attr)\n\t\t\tval, ok = parseCookieValue(val, false)\n\t\t\tif !ok {\n\t\t\t\tc.Unparsed = append(c.Unparsed, parts[i])\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch lowerAttr {\n\t\t\tcase \"samesite\":\n\t\t\t\tlowerVal := strings.ToLower(val)\n\t\t\t\tswitch lowerVal {\n\t\t\t\tcase \"lax\":\n\t\t\t\t\tc.SameSite = SameSiteLaxMode\n\t\t\t\tcase \"strict\":\n\t\t\t\t\tc.SameSite = SameSiteStrictMode\n\t\t\t\tdefault:\n\t\t\t\t\tc.SameSite = SameSiteDefaultMode\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\tcase \"secure\":\n\t\t\t\tc.Secure = true\n\t\t\t\tcontinue\n\t\t\tcase \"httponly\":\n\t\t\t\tc.HttpOnly = true\n\t\t\t\tcontinue\n\t\t\tcase \"domain\":\n\t\t\t\tc.Domain = val\n\t\t\t\tcontinue\n\t\t\tcase \"max-age\":\n\t\t\t\tsecs, err := strconv.Atoi(val)\n\t\t\t\tif err != nil || secs != 0 && val[0] == '0' {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif secs <= 0 {\n\t\t\t\t\tsecs = -1\n\t\t\t\t}\n\t\t\t\tc.MaxAge = secs\n\t\t\t\tcontinue\n\t\t\tcase \"expires\":\n\t\t\t\tc.RawExpires = val\n\t\t\t\texptime, err := time.Parse(time.RFC1123, val)\n\t\t\t\tif err != nil {\n\t\t\t\t\texptime, err = time.Parse(\"Mon, 02-Jan-2006 15:04:05 MST\", val)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tc.Expires = time.Time{}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tc.Expires = exptime.UTC()\n\t\t\t\tcontinue\n\t\t\tcase \"path\":\n\t\t\t\tc.Path = val\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.Unparsed = append(c.Unparsed, parts[i])\n\t\t}\n\t\tcookies = append(cookies, c)\n\t}\n\treturn cookies\n}\n\n\/\/ SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers.\n\/\/ The provided cookie must have a valid Name. Invalid cookies may be\n\/\/ silently dropped.\nfunc SetCookie(w ResponseWriter, cookie *Cookie) {\n\tif v := cookie.String(); v != \"\" {\n\t\tw.Header().Add(\"Set-Cookie\", v)\n\t}\n}\n\n\/\/ String returns the serialization of the cookie for use in a Cookie\n\/\/ header (if only Name and Value are set) or a Set-Cookie response\n\/\/ header (if other fields are set).\n\/\/ If c is nil or c.Name is invalid, the empty string is returned.\nfunc (c *Cookie) String() string {\n\tif c == nil || !isCookieNameValid(c.Name) {\n\t\treturn \"\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(sanitizeCookieName(c.Name))\n\tb.WriteRune('=')\n\tb.WriteString(sanitizeCookieValue(c.Value))\n\n\tif len(c.Path) > 0 {\n\t\tb.WriteString(\"; Path=\")\n\t\tb.WriteString(sanitizeCookiePath(c.Path))\n\t}\n\tif len(c.Domain) > 0 {\n\t\tif validCookieDomain(c.Domain) {\n\t\t\t\/\/ A c.Domain containing illegal characters is not\n\t\t\t\/\/ sanitized but simply dropped which turns the cookie\n\t\t\t\/\/ into a host-only cookie. A leading dot is okay\n\t\t\t\/\/ but won't be sent.\n\t\t\td := c.Domain\n\t\t\tif d[0] == '.' {\n\t\t\t\td = d[1:]\n\t\t\t}\n\t\t\tb.WriteString(\"; Domain=\")\n\t\t\tb.WriteString(d)\n\t\t} else {\n\t\t\tlog.Printf(\"net\/http: invalid Cookie.Domain %q; dropping domain attribute\", c.Domain)\n\t\t}\n\t}\n\tvar buf [len(TimeFormat)]byte\n\tif validCookieExpires(c.Expires) {\n\t\tb.WriteString(\"; Expires=\")\n\t\tb.Write(c.Expires.UTC().AppendFormat(buf[:0], TimeFormat))\n\t}\n\tif c.MaxAge > 0 {\n\t\tb.WriteString(\"; Max-Age=\")\n\t\tb.Write(strconv.AppendInt(buf[:0], int64(c.MaxAge), 10))\n\t} else if c.MaxAge < 0 {\n\t\tb.WriteString(\"; Max-Age=0\")\n\t}\n\tif c.HttpOnly {\n\t\tb.WriteString(\"; HttpOnly\")\n\t}\n\tif c.Secure {\n\t\tb.WriteString(\"; Secure\")\n\t}\n\tswitch c.SameSite {\n\tcase SameSiteDefaultMode:\n\t\tb.WriteString(\"; SameSite\")\n\tcase SameSiteLaxMode:\n\t\tb.WriteString(\"; SameSite=Lax\")\n\tcase SameSiteStrictMode:\n\t\tb.WriteString(\"; SameSite=Strict\")\n\t}\n\treturn b.String()\n}\n\n\/\/ readCookies parses all \"Cookie\" values from the header h and\n\/\/ returns the successfully parsed Cookies.\n\/\/\n\/\/ if filter isn't empty, only cookies of that name are returned\nfunc readCookies(h Header, filter string) []*Cookie {\n\tlines, ok := h[\"Cookie\"]\n\tif !ok {\n\t\treturn []*Cookie{}\n\t}\n\n\tcookies := []*Cookie{}\n\tfor _, line := range lines {\n\t\tparts := strings.Split(strings.TrimSpace(line), \";\")\n\t\tif len(parts) == 1 && parts[0] == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Per-line attributes\n\t\tfor i := 0; i < len(parts); i++ {\n\t\t\tparts[i] = strings.TrimSpace(parts[i])\n\t\t\tif len(parts[i]) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tname, val := parts[i], \"\"\n\t\t\tif j := strings.Index(name, \"=\"); j >= 0 {\n\t\t\t\tname, val = name[:j], name[j+1:]\n\t\t\t}\n\t\t\tif !isCookieNameValid(name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif filter != \"\" && filter != name {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tval, ok := parseCookieValue(val, true)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcookies = append(cookies, &Cookie{Name: name, Value: val})\n\t\t}\n\t}\n\treturn cookies\n}\n\n\/\/ validCookieDomain returns whether v is a valid cookie domain-value.\nfunc validCookieDomain(v string) bool {\n\tif isCookieDomainName(v) {\n\t\treturn true\n\t}\n\tif net.ParseIP(v) != nil && !strings.Contains(v, \":\") {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ validCookieExpires returns whether v is a valid cookie expires-value.\nfunc validCookieExpires(t time.Time) bool {\n\t\/\/ IETF RFC 6265 Section 5.1.1.5, the year must not be less than 1601\n\treturn t.Year() >= 1601\n}\n\n\/\/ isCookieDomainName returns whether s is a valid domain name or a valid\n\/\/ domain name with a leading dot '.'.  It is almost a direct copy of\n\/\/ package net's isDomainName.\nfunc isCookieDomainName(s string) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\tif len(s) > 255 {\n\t\treturn false\n\t}\n\n\tif s[0] == '.' {\n\t\t\/\/ A cookie a domain attribute may start with a leading dot.\n\t\ts = s[1:]\n\t}\n\tlast := byte('.')\n\tok := false \/\/ Ok once we've seen a letter.\n\tpartlen := 0\n\tfor i := 0; i < len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\tdefault:\n\t\t\treturn false\n\t\tcase 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':\n\t\t\t\/\/ No '_' allowed here (in contrast to package net).\n\t\t\tok = true\n\t\t\tpartlen++\n\t\tcase '0' <= c && c <= '9':\n\t\t\t\/\/ fine\n\t\t\tpartlen++\n\t\tcase c == '-':\n\t\t\t\/\/ Byte before dash cannot be dot.\n\t\t\tif last == '.' {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpartlen++\n\t\tcase c == '.':\n\t\t\t\/\/ Byte before dot cannot be dot, dash.\n\t\t\tif last == '.' || last == '-' {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif partlen > 63 || partlen == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpartlen = 0\n\t\t}\n\t\tlast = c\n\t}\n\tif last == '-' || partlen > 63 {\n\t\treturn false\n\t}\n\n\treturn ok\n}\n\nvar cookieNameSanitizer = strings.NewReplacer(\"\\n\", \"-\", \"\\r\", \"-\")\n\nfunc sanitizeCookieName(n string) string {\n\treturn cookieNameSanitizer.Replace(n)\n}\n\n\/\/ https:\/\/tools.ietf.org\/html\/rfc6265#section-4.1.1\n\/\/ cookie-value      = *cookie-octet \/ ( DQUOTE *cookie-octet DQUOTE )\n\/\/ cookie-octet      = %x21 \/ %x23-2B \/ %x2D-3A \/ %x3C-5B \/ %x5D-7E\n\/\/           ; US-ASCII characters excluding CTLs,\n\/\/           ; whitespace DQUOTE, comma, semicolon,\n\/\/           ; and backslash\n\/\/ We loosen this as spaces and commas are common in cookie values\n\/\/ but we produce a quoted cookie-value in when value starts or ends\n\/\/ with a comma or space.\n\/\/ See https:\/\/golang.org\/issue\/7243 for the discussion.\nfunc sanitizeCookieValue(v string) string {\n\tv = sanitizeOrWarn(\"Cookie.Value\", validCookieValueByte, v)\n\tif len(v) == 0 {\n\t\treturn v\n\t}\n\tif strings.IndexByte(v, ' ') >= 0 || strings.IndexByte(v, ',') >= 0 {\n\t\treturn `\"` + v + `\"`\n\t}\n\treturn v\n}\n\nfunc validCookieValueByte(b byte) bool {\n\treturn 0x20 <= b && b < 0x7f && b != '\"' && b != ';' && b != '\\\\'\n}\n\n\/\/ path-av           = \"Path=\" path-value\n\/\/ path-value        = <any CHAR except CTLs or \";\">\nfunc sanitizeCookiePath(v string) string {\n\treturn sanitizeOrWarn(\"Cookie.Path\", validCookiePathByte, v)\n}\n\nfunc validCookiePathByte(b byte) bool {\n\treturn 0x20 <= b && b < 0x7f && b != ';'\n}\n\nfunc sanitizeOrWarn(fieldName string, valid func(byte) bool, v string) string {\n\tok := true\n\tfor i := 0; i < len(v); i++ {\n\t\tif valid(v[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\"net\/http: invalid byte %q in %s; dropping invalid bytes\", v[i], fieldName)\n\t\tok = false\n\t\tbreak\n\t}\n\tif ok {\n\t\treturn v\n\t}\n\tbuf := make([]byte, 0, len(v))\n\tfor i := 0; i < len(v); i++ {\n\t\tif b := v[i]; valid(b) {\n\t\t\tbuf = append(buf, b)\n\t\t}\n\t}\n\treturn string(buf)\n}\n\nfunc parseCookieValue(raw string, allowDoubleQuote bool) (string, bool) {\n\t\/\/ Strip the quotes, if present.\n\tif allowDoubleQuote && len(raw) > 1 && raw[0] == '\"' && raw[len(raw)-1] == '\"' {\n\t\traw = raw[1 : len(raw)-1]\n\t}\n\tfor i := 0; i < len(raw); i++ {\n\t\tif !validCookieValueByte(raw[i]) {\n\t\t\treturn \"\", false\n\t\t}\n\t}\n\treturn raw, true\n}\n\nfunc isCookieNameValid(raw string) bool {\n\tif raw == \"\" {\n\t\treturn false\n\t}\n\treturn strings.IndexFunc(raw, isNotToken) < 0\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage http\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an\n\/\/ HTTP response or the Cookie header of an HTTP request.\n\/\/\n\/\/ See https:\/\/tools.ietf.org\/html\/rfc6265 for details.\ntype Cookie struct {\n\tName  string\n\tValue string\n\n\tPath       string    \/\/ optional\n\tDomain     string    \/\/ optional\n\tExpires    time.Time \/\/ optional\n\tRawExpires string    \/\/ for reading cookies only\n\n\t\/\/ MaxAge=0 means no 'Max-Age' attribute specified.\n\t\/\/ MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'\n\t\/\/ MaxAge>0 means Max-Age attribute present and given in seconds\n\tMaxAge   int\n\tSecure   bool\n\tHttpOnly bool\n\tSameSite SameSite\n\tRaw      string\n\tUnparsed []string \/\/ Raw text of unparsed attribute-value pairs\n}\n\n\/\/ SameSite allows a server to define a cookie attribute making it impossible for\n\/\/ the browser to send this cookie along with cross-site requests. The main\n\/\/ goal is to mitigate the risk of cross-origin information leakage, and provides\n\/\/ some protection against cross-site request forgery attacks.\n\/\/\n\/\/ See https:\/\/tools.ietf.org\/html\/draft-ietf-httpbis-cookie-same-site-00 for details.\ntype SameSite int\n\nconst (\n\tSameSiteDefaultMode SameSite = iota + 1\n\tSameSiteLaxMode\n\tSameSiteStrictMode\n)\n\n\/\/ readSetCookies parses all \"Set-Cookie\" values from\n\/\/ the header h and returns the successfully parsed Cookies.\nfunc readSetCookies(h Header) []*Cookie {\n\tcookieCount := len(h[\"Set-Cookie\"])\n\tif cookieCount == 0 {\n\t\treturn []*Cookie{}\n\t}\n\tcookies := make([]*Cookie, 0, cookieCount)\n\tfor _, line := range h[\"Set-Cookie\"] {\n\t\tparts := strings.Split(strings.TrimSpace(line), \";\")\n\t\tif len(parts) == 1 && parts[0] == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tparts[0] = strings.TrimSpace(parts[0])\n\t\tj := strings.Index(parts[0], \"=\")\n\t\tif j < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tname, value := parts[0][:j], parts[0][j+1:]\n\t\tif !isCookieNameValid(name) {\n\t\t\tcontinue\n\t\t}\n\t\tvalue, ok := parseCookieValue(value, true)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tc := &Cookie{\n\t\t\tName:  name,\n\t\t\tValue: value,\n\t\t\tRaw:   line,\n\t\t}\n\t\tfor i := 1; i < len(parts); i++ {\n\t\t\tparts[i] = strings.TrimSpace(parts[i])\n\t\t\tif len(parts[i]) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tattr, val := parts[i], \"\"\n\t\t\tif j := strings.Index(attr, \"=\"); j >= 0 {\n\t\t\t\tattr, val = attr[:j], attr[j+1:]\n\t\t\t}\n\t\t\tlowerAttr := strings.ToLower(attr)\n\t\t\tval, ok = parseCookieValue(val, false)\n\t\t\tif !ok {\n\t\t\t\tc.Unparsed = append(c.Unparsed, parts[i])\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch lowerAttr {\n\t\t\tcase \"samesite\":\n\t\t\t\tlowerVal := strings.ToLower(val)\n\t\t\t\tswitch lowerVal {\n\t\t\t\tcase \"lax\":\n\t\t\t\t\tc.SameSite = SameSiteLaxMode\n\t\t\t\tcase \"strict\":\n\t\t\t\t\tc.SameSite = SameSiteStrictMode\n\t\t\t\tdefault:\n\t\t\t\t\tc.SameSite = SameSiteDefaultMode\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\tcase \"secure\":\n\t\t\t\tc.Secure = true\n\t\t\t\tcontinue\n\t\t\tcase \"httponly\":\n\t\t\t\tc.HttpOnly = true\n\t\t\t\tcontinue\n\t\t\tcase \"domain\":\n\t\t\t\tc.Domain = val\n\t\t\t\tcontinue\n\t\t\tcase \"max-age\":\n\t\t\t\tsecs, err := strconv.Atoi(val)\n\t\t\t\tif err != nil || secs != 0 && val[0] == '0' {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif secs <= 0 {\n\t\t\t\t\tsecs = -1\n\t\t\t\t}\n\t\t\t\tc.MaxAge = secs\n\t\t\t\tcontinue\n\t\t\tcase \"expires\":\n\t\t\t\tc.RawExpires = val\n\t\t\t\texptime, err := time.Parse(time.RFC1123, val)\n\t\t\t\tif err != nil {\n\t\t\t\t\texptime, err = time.Parse(\"Mon, 02-Jan-2006 15:04:05 MST\", val)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tc.Expires = time.Time{}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tc.Expires = exptime.UTC()\n\t\t\t\tcontinue\n\t\t\tcase \"path\":\n\t\t\t\tc.Path = val\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.Unparsed = append(c.Unparsed, parts[i])\n\t\t}\n\t\tcookies = append(cookies, c)\n\t}\n\treturn cookies\n}\n\n\/\/ SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers.\n\/\/ The provided cookie must have a valid Name. Invalid cookies may be\n\/\/ silently dropped.\nfunc SetCookie(w ResponseWriter, cookie *Cookie) {\n\tif v := cookie.String(); v != \"\" {\n\t\tw.Header().Add(\"Set-Cookie\", v)\n\t}\n}\n\n\/\/ String returns the serialization of the cookie for use in a Cookie\n\/\/ header (if only Name and Value are set) or a Set-Cookie response\n\/\/ header (if other fields are set).\n\/\/ If c is nil or c.Name is invalid, the empty string is returned.\nfunc (c *Cookie) String() string {\n\tif c == nil || !isCookieNameValid(c.Name) {\n\t\treturn \"\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(sanitizeCookieName(c.Name))\n\tb.WriteRune('=')\n\tb.WriteString(sanitizeCookieValue(c.Value))\n\n\tif len(c.Path) > 0 {\n\t\tb.WriteString(\"; Path=\")\n\t\tb.WriteString(sanitizeCookiePath(c.Path))\n\t}\n\tif len(c.Domain) > 0 {\n\t\tif validCookieDomain(c.Domain) {\n\t\t\t\/\/ A c.Domain containing illegal characters is not\n\t\t\t\/\/ sanitized but simply dropped which turns the cookie\n\t\t\t\/\/ into a host-only cookie. A leading dot is okay\n\t\t\t\/\/ but won't be sent.\n\t\t\td := c.Domain\n\t\t\tif d[0] == '.' {\n\t\t\t\td = d[1:]\n\t\t\t}\n\t\t\tb.WriteString(\"; Domain=\")\n\t\t\tb.WriteString(d)\n\t\t} else {\n\t\t\tlog.Printf(\"net\/http: invalid Cookie.Domain %q; dropping domain attribute\", c.Domain)\n\t\t}\n\t}\n\tvar buf [len(TimeFormat)]byte\n\tif validCookieExpires(c.Expires) {\n\t\tb.WriteString(\"; Expires=\")\n\t\tb.Write(c.Expires.UTC().AppendFormat(buf[:0], TimeFormat))\n\t}\n\tif c.MaxAge > 0 {\n\t\tb.WriteString(\"; Max-Age=\")\n\t\tb.Write(strconv.AppendInt(buf[:0], int64(c.MaxAge), 10))\n\t} else if c.MaxAge < 0 {\n\t\tb.WriteString(\"; Max-Age=0\")\n\t}\n\tif c.HttpOnly {\n\t\tb.WriteString(\"; HttpOnly\")\n\t}\n\tif c.Secure {\n\t\tb.WriteString(\"; Secure\")\n\t}\n\tswitch c.SameSite {\n\tcase SameSiteDefaultMode:\n\t\tb.WriteString(\"; SameSite\")\n\tcase SameSiteLaxMode:\n\t\tb.WriteString(\"; SameSite=Lax\")\n\tcase SameSiteStrictMode:\n\t\tb.WriteString(\"; SameSite=Strict\")\n\t}\n\treturn b.String()\n}\n\n\/\/ readCookies parses all \"Cookie\" values from the header h and\n\/\/ returns the successfully parsed Cookies.\n\/\/\n\/\/ if filter isn't empty, only cookies of that name are returned\nfunc readCookies(h Header, filter string) []*Cookie {\n\tlines, ok := h[\"Cookie\"]\n\tif !ok {\n\t\treturn []*Cookie{}\n\t}\n\n\tcookies := []*Cookie{}\n\tfor _, line := range lines {\n\t\tparts := strings.Split(strings.TrimSpace(line), \";\")\n\t\tif len(parts) == 1 && parts[0] == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Per-line attributes\n\t\tfor i := 0; i < len(parts); i++ {\n\t\t\tparts[i] = strings.TrimSpace(parts[i])\n\t\t\tif len(parts[i]) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tname, val := parts[i], \"\"\n\t\t\tif j := strings.Index(name, \"=\"); j >= 0 {\n\t\t\t\tname, val = name[:j], name[j+1:]\n\t\t\t}\n\t\t\tif !isCookieNameValid(name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif filter != \"\" && filter != name {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tval, ok := parseCookieValue(val, true)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcookies = append(cookies, &Cookie{Name: name, Value: val})\n\t\t}\n\t}\n\treturn cookies\n}\n\n\/\/ validCookieDomain returns whether v is a valid cookie domain-value.\nfunc validCookieDomain(v string) bool {\n\tif isCookieDomainName(v) {\n\t\treturn true\n\t}\n\tif net.ParseIP(v) != nil && !strings.Contains(v, \":\") {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ validCookieExpires returns whether v is a valid cookie expires-value.\nfunc validCookieExpires(t time.Time) bool {\n\t\/\/ IETF RFC 6265 Section 5.1.1.5, the year must not be less than 1601\n\treturn t.Year() >= 1601\n}\n\n\/\/ isCookieDomainName returns whether s is a valid domain name or a valid\n\/\/ domain name with a leading dot '.'.  It is almost a direct copy of\n\/\/ package net's isDomainName.\nfunc isCookieDomainName(s string) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\tif len(s) > 255 {\n\t\treturn false\n\t}\n\n\tif s[0] == '.' {\n\t\t\/\/ A cookie a domain attribute may start with a leading dot.\n\t\ts = s[1:]\n\t}\n\tlast := byte('.')\n\tok := false \/\/ Ok once we've seen a letter.\n\tpartlen := 0\n\tfor i := 0; i < len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\tdefault:\n\t\t\treturn false\n\t\tcase 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':\n\t\t\t\/\/ No '_' allowed here (in contrast to package net).\n\t\t\tok = true\n\t\t\tpartlen++\n\t\tcase '0' <= c && c <= '9':\n\t\t\t\/\/ fine\n\t\t\tpartlen++\n\t\tcase c == '-':\n\t\t\t\/\/ Byte before dash cannot be dot.\n\t\t\tif last == '.' {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpartlen++\n\t\tcase c == '.':\n\t\t\t\/\/ Byte before dot cannot be dot, dash.\n\t\t\tif last == '.' || last == '-' {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif partlen > 63 || partlen == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpartlen = 0\n\t\t}\n\t\tlast = c\n\t}\n\tif last == '-' || partlen > 63 {\n\t\treturn false\n\t}\n\n\treturn ok\n}\n\nvar cookieNameSanitizer = strings.NewReplacer(\"\\n\", \"-\", \"\\r\", \"-\")\n\nfunc sanitizeCookieName(n string) string {\n\treturn cookieNameSanitizer.Replace(n)\n}\n\n\/\/ https:\/\/tools.ietf.org\/html\/rfc6265#section-4.1.1\n\/\/ cookie-value      = *cookie-octet \/ ( DQUOTE *cookie-octet DQUOTE )\n\/\/ cookie-octet      = %x21 \/ %x23-2B \/ %x2D-3A \/ %x3C-5B \/ %x5D-7E\n\/\/           ; US-ASCII characters excluding CTLs,\n\/\/           ; whitespace DQUOTE, comma, semicolon,\n\/\/           ; and backslash\n\/\/ We loosen this as spaces and commas are common in cookie values\n\/\/ but we produce a quoted cookie-value in when value starts or ends\n\/\/ with a comma or space.\n\/\/ See https:\/\/golang.org\/issue\/7243 for the discussion.\nfunc sanitizeCookieValue(v string) string {\n\tv = sanitizeOrWarn(\"Cookie.Value\", validCookieValueByte, v)\n\tif len(v) == 0 {\n\t\treturn v\n\t}\n\tif strings.IndexByte(v, ' ') >= 0 || strings.IndexByte(v, ',') >= 0 {\n\t\treturn `\"` + v + `\"`\n\t}\n\treturn v\n}\n\nfunc validCookieValueByte(b byte) bool {\n\treturn 0x20 <= b && b < 0x7f && b != '\"' && b != ';' && b != '\\\\'\n}\n\n\/\/ path-av           = \"Path=\" path-value\n\/\/ path-value        = <any CHAR except CTLs or \";\">\nfunc sanitizeCookiePath(v string) string {\n\treturn sanitizeOrWarn(\"Cookie.Path\", validCookiePathByte, v)\n}\n\nfunc validCookiePathByte(b byte) bool {\n\treturn 0x20 <= b && b < 0x7f && b != ';'\n}\n\nfunc sanitizeOrWarn(fieldName string, valid func(byte) bool, v string) string {\n\tok := true\n\tfor i := 0; i < len(v); i++ {\n\t\tif valid(v[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\"net\/http: invalid byte %q in %s; dropping invalid bytes\", v[i], fieldName)\n\t\tok = false\n\t\tbreak\n\t}\n\tif ok {\n\t\treturn v\n\t}\n\tbuf := make([]byte, 0, len(v))\n\tfor i := 0; i < len(v); i++ {\n\t\tif b := v[i]; valid(b) {\n\t\t\tbuf = append(buf, b)\n\t\t}\n\t}\n\treturn string(buf)\n}\n\nfunc parseCookieValue(raw string, allowDoubleQuote bool) (string, bool) {\n\t\/\/ Strip the quotes, if present.\n\tif allowDoubleQuote && len(raw) > 1 && raw[0] == '\"' && raw[len(raw)-1] == '\"' {\n\t\traw = raw[1 : len(raw)-1]\n\t}\n\tfor i := 0; i < len(raw); i++ {\n\t\tif !validCookieValueByte(raw[i]) {\n\t\t\treturn \"\", false\n\t\t}\n\t}\n\treturn raw, true\n}\n\nfunc isCookieNameValid(raw string) bool {\n\tif raw == \"\" {\n\t\treturn false\n\t}\n\treturn strings.IndexFunc(raw, isNotToken) < 0\n}\n<commit_msg>net\/http: fix typo in the SameSite docs<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage http\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an\n\/\/ HTTP response or the Cookie header of an HTTP request.\n\/\/\n\/\/ See https:\/\/tools.ietf.org\/html\/rfc6265 for details.\ntype Cookie struct {\n\tName  string\n\tValue string\n\n\tPath       string    \/\/ optional\n\tDomain     string    \/\/ optional\n\tExpires    time.Time \/\/ optional\n\tRawExpires string    \/\/ for reading cookies only\n\n\t\/\/ MaxAge=0 means no 'Max-Age' attribute specified.\n\t\/\/ MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'\n\t\/\/ MaxAge>0 means Max-Age attribute present and given in seconds\n\tMaxAge   int\n\tSecure   bool\n\tHttpOnly bool\n\tSameSite SameSite\n\tRaw      string\n\tUnparsed []string \/\/ Raw text of unparsed attribute-value pairs\n}\n\n\/\/ SameSite allows a server to define a cookie attribute making it impossible for\n\/\/ the browser to send this cookie along with cross-site requests. The main\n\/\/ goal is to mitigate the risk of cross-origin information leakage, and provide\n\/\/ some protection against cross-site request forgery attacks.\n\/\/\n\/\/ See https:\/\/tools.ietf.org\/html\/draft-ietf-httpbis-cookie-same-site-00 for details.\ntype SameSite int\n\nconst (\n\tSameSiteDefaultMode SameSite = iota + 1\n\tSameSiteLaxMode\n\tSameSiteStrictMode\n)\n\n\/\/ readSetCookies parses all \"Set-Cookie\" values from\n\/\/ the header h and returns the successfully parsed Cookies.\nfunc readSetCookies(h Header) []*Cookie {\n\tcookieCount := len(h[\"Set-Cookie\"])\n\tif cookieCount == 0 {\n\t\treturn []*Cookie{}\n\t}\n\tcookies := make([]*Cookie, 0, cookieCount)\n\tfor _, line := range h[\"Set-Cookie\"] {\n\t\tparts := strings.Split(strings.TrimSpace(line), \";\")\n\t\tif len(parts) == 1 && parts[0] == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tparts[0] = strings.TrimSpace(parts[0])\n\t\tj := strings.Index(parts[0], \"=\")\n\t\tif j < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tname, value := parts[0][:j], parts[0][j+1:]\n\t\tif !isCookieNameValid(name) {\n\t\t\tcontinue\n\t\t}\n\t\tvalue, ok := parseCookieValue(value, true)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tc := &Cookie{\n\t\t\tName:  name,\n\t\t\tValue: value,\n\t\t\tRaw:   line,\n\t\t}\n\t\tfor i := 1; i < len(parts); i++ {\n\t\t\tparts[i] = strings.TrimSpace(parts[i])\n\t\t\tif len(parts[i]) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tattr, val := parts[i], \"\"\n\t\t\tif j := strings.Index(attr, \"=\"); j >= 0 {\n\t\t\t\tattr, val = attr[:j], attr[j+1:]\n\t\t\t}\n\t\t\tlowerAttr := strings.ToLower(attr)\n\t\t\tval, ok = parseCookieValue(val, false)\n\t\t\tif !ok {\n\t\t\t\tc.Unparsed = append(c.Unparsed, parts[i])\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch lowerAttr {\n\t\t\tcase \"samesite\":\n\t\t\t\tlowerVal := strings.ToLower(val)\n\t\t\t\tswitch lowerVal {\n\t\t\t\tcase \"lax\":\n\t\t\t\t\tc.SameSite = SameSiteLaxMode\n\t\t\t\tcase \"strict\":\n\t\t\t\t\tc.SameSite = SameSiteStrictMode\n\t\t\t\tdefault:\n\t\t\t\t\tc.SameSite = SameSiteDefaultMode\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\tcase \"secure\":\n\t\t\t\tc.Secure = true\n\t\t\t\tcontinue\n\t\t\tcase \"httponly\":\n\t\t\t\tc.HttpOnly = true\n\t\t\t\tcontinue\n\t\t\tcase \"domain\":\n\t\t\t\tc.Domain = val\n\t\t\t\tcontinue\n\t\t\tcase \"max-age\":\n\t\t\t\tsecs, err := strconv.Atoi(val)\n\t\t\t\tif err != nil || secs != 0 && val[0] == '0' {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif secs <= 0 {\n\t\t\t\t\tsecs = -1\n\t\t\t\t}\n\t\t\t\tc.MaxAge = secs\n\t\t\t\tcontinue\n\t\t\tcase \"expires\":\n\t\t\t\tc.RawExpires = val\n\t\t\t\texptime, err := time.Parse(time.RFC1123, val)\n\t\t\t\tif err != nil {\n\t\t\t\t\texptime, err = time.Parse(\"Mon, 02-Jan-2006 15:04:05 MST\", val)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tc.Expires = time.Time{}\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tc.Expires = exptime.UTC()\n\t\t\t\tcontinue\n\t\t\tcase \"path\":\n\t\t\t\tc.Path = val\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.Unparsed = append(c.Unparsed, parts[i])\n\t\t}\n\t\tcookies = append(cookies, c)\n\t}\n\treturn cookies\n}\n\n\/\/ SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers.\n\/\/ The provided cookie must have a valid Name. Invalid cookies may be\n\/\/ silently dropped.\nfunc SetCookie(w ResponseWriter, cookie *Cookie) {\n\tif v := cookie.String(); v != \"\" {\n\t\tw.Header().Add(\"Set-Cookie\", v)\n\t}\n}\n\n\/\/ String returns the serialization of the cookie for use in a Cookie\n\/\/ header (if only Name and Value are set) or a Set-Cookie response\n\/\/ header (if other fields are set).\n\/\/ If c is nil or c.Name is invalid, the empty string is returned.\nfunc (c *Cookie) String() string {\n\tif c == nil || !isCookieNameValid(c.Name) {\n\t\treturn \"\"\n\t}\n\tvar b strings.Builder\n\tb.WriteString(sanitizeCookieName(c.Name))\n\tb.WriteRune('=')\n\tb.WriteString(sanitizeCookieValue(c.Value))\n\n\tif len(c.Path) > 0 {\n\t\tb.WriteString(\"; Path=\")\n\t\tb.WriteString(sanitizeCookiePath(c.Path))\n\t}\n\tif len(c.Domain) > 0 {\n\t\tif validCookieDomain(c.Domain) {\n\t\t\t\/\/ A c.Domain containing illegal characters is not\n\t\t\t\/\/ sanitized but simply dropped which turns the cookie\n\t\t\t\/\/ into a host-only cookie. A leading dot is okay\n\t\t\t\/\/ but won't be sent.\n\t\t\td := c.Domain\n\t\t\tif d[0] == '.' {\n\t\t\t\td = d[1:]\n\t\t\t}\n\t\t\tb.WriteString(\"; Domain=\")\n\t\t\tb.WriteString(d)\n\t\t} else {\n\t\t\tlog.Printf(\"net\/http: invalid Cookie.Domain %q; dropping domain attribute\", c.Domain)\n\t\t}\n\t}\n\tvar buf [len(TimeFormat)]byte\n\tif validCookieExpires(c.Expires) {\n\t\tb.WriteString(\"; Expires=\")\n\t\tb.Write(c.Expires.UTC().AppendFormat(buf[:0], TimeFormat))\n\t}\n\tif c.MaxAge > 0 {\n\t\tb.WriteString(\"; Max-Age=\")\n\t\tb.Write(strconv.AppendInt(buf[:0], int64(c.MaxAge), 10))\n\t} else if c.MaxAge < 0 {\n\t\tb.WriteString(\"; Max-Age=0\")\n\t}\n\tif c.HttpOnly {\n\t\tb.WriteString(\"; HttpOnly\")\n\t}\n\tif c.Secure {\n\t\tb.WriteString(\"; Secure\")\n\t}\n\tswitch c.SameSite {\n\tcase SameSiteDefaultMode:\n\t\tb.WriteString(\"; SameSite\")\n\tcase SameSiteLaxMode:\n\t\tb.WriteString(\"; SameSite=Lax\")\n\tcase SameSiteStrictMode:\n\t\tb.WriteString(\"; SameSite=Strict\")\n\t}\n\treturn b.String()\n}\n\n\/\/ readCookies parses all \"Cookie\" values from the header h and\n\/\/ returns the successfully parsed Cookies.\n\/\/\n\/\/ if filter isn't empty, only cookies of that name are returned\nfunc readCookies(h Header, filter string) []*Cookie {\n\tlines, ok := h[\"Cookie\"]\n\tif !ok {\n\t\treturn []*Cookie{}\n\t}\n\n\tcookies := []*Cookie{}\n\tfor _, line := range lines {\n\t\tparts := strings.Split(strings.TrimSpace(line), \";\")\n\t\tif len(parts) == 1 && parts[0] == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Per-line attributes\n\t\tfor i := 0; i < len(parts); i++ {\n\t\t\tparts[i] = strings.TrimSpace(parts[i])\n\t\t\tif len(parts[i]) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tname, val := parts[i], \"\"\n\t\t\tif j := strings.Index(name, \"=\"); j >= 0 {\n\t\t\t\tname, val = name[:j], name[j+1:]\n\t\t\t}\n\t\t\tif !isCookieNameValid(name) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif filter != \"\" && filter != name {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tval, ok := parseCookieValue(val, true)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcookies = append(cookies, &Cookie{Name: name, Value: val})\n\t\t}\n\t}\n\treturn cookies\n}\n\n\/\/ validCookieDomain returns whether v is a valid cookie domain-value.\nfunc validCookieDomain(v string) bool {\n\tif isCookieDomainName(v) {\n\t\treturn true\n\t}\n\tif net.ParseIP(v) != nil && !strings.Contains(v, \":\") {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ validCookieExpires returns whether v is a valid cookie expires-value.\nfunc validCookieExpires(t time.Time) bool {\n\t\/\/ IETF RFC 6265 Section 5.1.1.5, the year must not be less than 1601\n\treturn t.Year() >= 1601\n}\n\n\/\/ isCookieDomainName returns whether s is a valid domain name or a valid\n\/\/ domain name with a leading dot '.'.  It is almost a direct copy of\n\/\/ package net's isDomainName.\nfunc isCookieDomainName(s string) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\tif len(s) > 255 {\n\t\treturn false\n\t}\n\n\tif s[0] == '.' {\n\t\t\/\/ A cookie a domain attribute may start with a leading dot.\n\t\ts = s[1:]\n\t}\n\tlast := byte('.')\n\tok := false \/\/ Ok once we've seen a letter.\n\tpartlen := 0\n\tfor i := 0; i < len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\tdefault:\n\t\t\treturn false\n\t\tcase 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z':\n\t\t\t\/\/ No '_' allowed here (in contrast to package net).\n\t\t\tok = true\n\t\t\tpartlen++\n\t\tcase '0' <= c && c <= '9':\n\t\t\t\/\/ fine\n\t\t\tpartlen++\n\t\tcase c == '-':\n\t\t\t\/\/ Byte before dash cannot be dot.\n\t\t\tif last == '.' {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpartlen++\n\t\tcase c == '.':\n\t\t\t\/\/ Byte before dot cannot be dot, dash.\n\t\t\tif last == '.' || last == '-' {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif partlen > 63 || partlen == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tpartlen = 0\n\t\t}\n\t\tlast = c\n\t}\n\tif last == '-' || partlen > 63 {\n\t\treturn false\n\t}\n\n\treturn ok\n}\n\nvar cookieNameSanitizer = strings.NewReplacer(\"\\n\", \"-\", \"\\r\", \"-\")\n\nfunc sanitizeCookieName(n string) string {\n\treturn cookieNameSanitizer.Replace(n)\n}\n\n\/\/ https:\/\/tools.ietf.org\/html\/rfc6265#section-4.1.1\n\/\/ cookie-value      = *cookie-octet \/ ( DQUOTE *cookie-octet DQUOTE )\n\/\/ cookie-octet      = %x21 \/ %x23-2B \/ %x2D-3A \/ %x3C-5B \/ %x5D-7E\n\/\/           ; US-ASCII characters excluding CTLs,\n\/\/           ; whitespace DQUOTE, comma, semicolon,\n\/\/           ; and backslash\n\/\/ We loosen this as spaces and commas are common in cookie values\n\/\/ but we produce a quoted cookie-value in when value starts or ends\n\/\/ with a comma or space.\n\/\/ See https:\/\/golang.org\/issue\/7243 for the discussion.\nfunc sanitizeCookieValue(v string) string {\n\tv = sanitizeOrWarn(\"Cookie.Value\", validCookieValueByte, v)\n\tif len(v) == 0 {\n\t\treturn v\n\t}\n\tif strings.IndexByte(v, ' ') >= 0 || strings.IndexByte(v, ',') >= 0 {\n\t\treturn `\"` + v + `\"`\n\t}\n\treturn v\n}\n\nfunc validCookieValueByte(b byte) bool {\n\treturn 0x20 <= b && b < 0x7f && b != '\"' && b != ';' && b != '\\\\'\n}\n\n\/\/ path-av           = \"Path=\" path-value\n\/\/ path-value        = <any CHAR except CTLs or \";\">\nfunc sanitizeCookiePath(v string) string {\n\treturn sanitizeOrWarn(\"Cookie.Path\", validCookiePathByte, v)\n}\n\nfunc validCookiePathByte(b byte) bool {\n\treturn 0x20 <= b && b < 0x7f && b != ';'\n}\n\nfunc sanitizeOrWarn(fieldName string, valid func(byte) bool, v string) string {\n\tok := true\n\tfor i := 0; i < len(v); i++ {\n\t\tif valid(v[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tlog.Printf(\"net\/http: invalid byte %q in %s; dropping invalid bytes\", v[i], fieldName)\n\t\tok = false\n\t\tbreak\n\t}\n\tif ok {\n\t\treturn v\n\t}\n\tbuf := make([]byte, 0, len(v))\n\tfor i := 0; i < len(v); i++ {\n\t\tif b := v[i]; valid(b) {\n\t\t\tbuf = append(buf, b)\n\t\t}\n\t}\n\treturn string(buf)\n}\n\nfunc parseCookieValue(raw string, allowDoubleQuote bool) (string, bool) {\n\t\/\/ Strip the quotes, if present.\n\tif allowDoubleQuote && len(raw) > 1 && raw[0] == '\"' && raw[len(raw)-1] == '\"' {\n\t\traw = raw[1 : len(raw)-1]\n\t}\n\tfor i := 0; i < len(raw); i++ {\n\t\tif !validCookieValueByte(raw[i]) {\n\t\t\treturn \"\", false\n\t\t}\n\t}\n\treturn raw, true\n}\n\nfunc isCookieNameValid(raw string) bool {\n\tif raw == \"\" {\n\t\treturn false\n\t}\n\treturn strings.IndexFunc(raw, isNotToken) < 0\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Provides a midi master clock and various other utils for working with midi\npackage midi\n\nimport (\n\t\"os\"\n\t\"time\"\n)\n\nconst (\n\tSTART    = 0xfa\n\tSTOP     = 0xfc\n\tTICK     = 0xf8\n\tCONTINUE = 0xfb\n)\n\ntype Clock struct {\n\tcmd       chan []byte\n\tpulseRate chan time.Duration\n\tdev       *os.File\n}\n\n\/\/ Create a new midi clock. The clock starts to send tick events as soon as it is created.\n\/\/dev, err := os.OpenFile(\"\/dev\/snd\/midiC1D0\", os.O_WRONLY, 0664)\n\/\/if err != nil {\n\/\/\tlog.Fatal(err)\n\/\/}\n\/\/\n\/\/clk := midi.NewClock(dev)\n\/\/clk.SetBpm(120.00)\n\/\/clk.Start()\nfunc NewClock(midiDevice *os.File) *Clock {\n\tclk := new(Clock)\n\tclk.dev = midiDevice\n\tclk.cmd = make(chan []byte)\n\tclk.pulseRate = make(chan time.Duration)\n\n\tgo clk.run()\n\n\treturn clk\n}\n\n\/\/ Change the BPM of the clock\nfunc (clk *Clock) SetBpm(bpm float64) {\n\tclk.pulseRate <- bpmToPulseInterval(bpm)\n}\n\n\/\/ Send MIDI sequencer start event\nfunc (clk *Clock) Start() {\n\tclk.cmd <- []byte{START}\n}\n\n\/\/ Send MIDI sequencer stop event\nfunc (clk *Clock) Stop() {\n\tclk.cmd <- []byte{STOP}\n}\n\n\/\/ Send MIDI sequencer stop event\nfunc (clk *Clock) Continue() {\n\tclk.cmd <- []byte{CONTINUE}\n}\n\nfunc (clk *Clock) run() {\n\tpulseRate := bpmToPulseInterval(120)\n\ttick := []byte{TICK}\n\tvar t VarTicker\n\tt.SetDuration(pulseRate)\n\n\tgo func() {\n\t\tfor range t.C {\n\t\t\tclk.dev.Write(tick)\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase newPulseRate := <-clk.pulseRate:\n\t\t\tt.SetDuration(newPulseRate)\n\t\tcase cmd := <-clk.cmd:\n\t\t\tclk.dev.Write(cmd)\n\t\t}\n\t}\n\n}\n\n\/\/ Converts bpm to a 24ppqn pulse interval in microseconds\nfunc bpmToPulseInterval(bpm float64) time.Duration {\n\treturn time.Duration((6000000\/(bpm\/10))\/24) * time.Microsecond\n}\n<commit_msg>Renamed constants<commit_after>\/\/ Provides a midi master clock and various other utils for working with midi\npackage midi\n\nimport (\n\t\"os\"\n\t\"time\"\n)\n\nconst (\n\tStart    = 0xfa\n\tStop     = 0xfc\n\tTick     = 0xf8\n\tContinue = 0xfb\n)\n\ntype Clock struct {\n\tcmd       chan []byte\n\tpulseRate chan time.Duration\n\tdev       *os.File\n}\n\n\/\/ Create a new midi clock. The clock starts to send tick events as soon as it is created.\n\/\/dev, err := os.OpenFile(\"\/dev\/snd\/midiC1D0\", os.O_WRONLY, 0664)\n\/\/if err != nil {\n\/\/\tlog.Fatal(err)\n\/\/}\n\/\/\n\/\/clk := midi.NewClock(dev)\n\/\/clk.SetBpm(120.00)\n\/\/clk.Start()\nfunc NewClock(midiDevice *os.File) *Clock {\n\tclk := new(Clock)\n\tclk.dev = midiDevice\n\tclk.cmd = make(chan []byte)\n\tclk.pulseRate = make(chan time.Duration)\n\n\tgo clk.run()\n\n\treturn clk\n}\n\n\/\/ Change the BPM of the clock\nfunc (clk *Clock) SetBpm(bpm float64) {\n\tclk.pulseRate <- bpmToPulseInterval(bpm)\n}\n\n\/\/ Send MIDI sequencer start event\nfunc (clk *Clock) Start() {\n\tclk.cmd <- []byte{Start}\n}\n\n\/\/ Send MIDI sequencer stop event\nfunc (clk *Clock) Stop() {\n\tclk.cmd <- []byte{Stop}\n}\n\n\/\/ Send MIDI sequencer stop event\nfunc (clk *Clock) Continue() {\n\tclk.cmd <- []byte{Continue}\n}\n\nfunc (clk *Clock) run() {\n\tpulseRate := bpmToPulseInterval(120)\n\ttick := []byte{Tick}\n\tvar t VarTicker\n\tt.SetDuration(pulseRate)\n\n\tgo func() {\n\t\tfor range t.C {\n\t\t\tclk.dev.Write(tick)\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase newPulseRate := <-clk.pulseRate:\n\t\t\tt.SetDuration(newPulseRate)\n\t\tcase cmd := <-clk.cmd:\n\t\t\tclk.dev.Write(cmd)\n\t\t}\n\t}\n\n}\n\n\/\/ Converts bpm to a 24ppqn pulse interval in microseconds\nfunc bpmToPulseInterval(bpm float64) time.Duration {\n\treturn time.Duration((6000000\/(bpm\/10))\/24) * time.Microsecond\n}\n<|endoftext|>"}
{"text":"<commit_before>package tests_test\n\nimport (\n\t\"flag\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t\"github.com\/onsi\/ginkgo\/extensions\/table\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/intstr\"\n\n\tv12 \"kubevirt.io\/kubevirt\/pkg\/api\/v1\"\n\t\"kubevirt.io\/kubevirt\/pkg\/kubecli\"\n\t\"kubevirt.io\/kubevirt\/tests\"\n)\n\nvar _ = Describe(\"Probes\", func() {\n\tflag.Parse()\n\n\tvirtClient, err := kubecli.GetKubevirtClient()\n\ttests.PanicOnError(err)\n\n\tBeforeEach(func() {\n\t\ttests.BeforeTestCleanup()\n\t})\n\n\tContext(\"for readiness\", func() {\n\n\t\ttcpProbe := &v12.Probe{\n\t\t\tPeriodSeconds:       5,\n\t\t\tInitialDelaySeconds: 5,\n\t\t\tHandler: v12.Handler{\n\n\t\t\t\tTCPSocket: &v1.TCPSocketAction{\n\t\t\t\t\tPort: intstr.Parse(\"1500\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\thttpProbe := &v12.Probe{\n\t\t\tPeriodSeconds:       5,\n\t\t\tInitialDelaySeconds: 5,\n\t\t\tHandler: v12.Handler{\n\n\t\t\t\tHTTPGet: &v1.HTTPGetAction{\n\t\t\t\t\tPort: intstr.Parse(\"1500\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\ttable.DescribeTable(\"should succeed\", func(readinessProbe *v12.Probe, serverStarter func(vmi *v12.VirtualMachineInstance, port int)) {\n\t\t\tBy(\"Specifying a VMI with a readiness probe\")\n\t\t\tvmi := tests.NewRandomVMIWithEphemeralDiskAndUserdata(tests.ContainerDiskFor(tests.ContainerDiskCirros), \"#!\/bin\/bash\\necho 'hello'\\n\")\n\t\t\tvmi.Spec.ReadinessProbe = readinessProbe\n\t\t\tvmi, err = virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Create(vmi)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\ttests.WaitForSuccessfulVMIStart(vmi)\n\n\t\t\tExpect(podReady(tests.GetRunningPodByVirtualMachineInstance(vmi, tests.NamespaceTestDefault))).To(Equal(v1.ConditionFalse))\n\n\t\t\tBy(\"Starting the server inside the VMI\")\n\t\t\tserverStarter(vmi, 1500)\n\n\t\t\tBy(\"Checking that the VMI will be marked as ready to receive traffic\")\n\t\t\tEventually(func() v1.ConditionStatus {\n\t\t\t\tpod := tests.GetRunningPodByVirtualMachineInstance(vmi, tests.NamespaceTestDefault)\n\t\t\t\treturn podReady(pod)\n\t\t\t}, 30, 1).Should(Equal(v1.ConditionTrue))\n\t\t},\n\t\t\ttable.Entry(\"with working TCP probe and tcp server\", tcpProbe, tests.StartTCPServer),\n\t\t\ttable.Entry(\"with working HTTP probe and http server\", httpProbe, tests.StartHTTPServer),\n\t\t)\n\n\t\ttable.DescribeTable(\"should fail\", func(readinessProbe *v12.Probe) {\n\t\t\tBy(\"Specifying a VMI with a readiness probe\")\n\t\t\tvmi := tests.NewRandomVMIWithEphemeralDiskAndUserdata(tests.ContainerDiskFor(tests.ContainerDiskCirros), \"#!\/bin\/bash\\necho 'hello'\\n\")\n\t\t\tvmi.Spec.ReadinessProbe = readinessProbe\n\t\t\tvmi, err = virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Create(vmi)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\ttests.WaitForSuccessfulVMIStart(vmi)\n\n\t\t\tExpect(podReady(tests.GetRunningPodByVirtualMachineInstance(vmi, tests.NamespaceTestDefault))).To(Equal(v1.ConditionFalse))\n\n\t\t\tBy(\"Checking that the VMI will consistently stay in a not-ready state\")\n\t\t\tConsistently(func() v1.ConditionStatus {\n\t\t\t\tpod := tests.GetRunningPodByVirtualMachineInstance(vmi, tests.NamespaceTestDefault)\n\t\t\t\treturn podReady(pod)\n\t\t\t}, 30, 1).Should(Equal(v1.ConditionFalse))\n\t\t},\n\t\t\ttable.Entry(\"with working TCP probe and no running server\", tcpProbe),\n\t\t\ttable.Entry(\"with working HTTP probe and no running server\", httpProbe),\n\t\t)\n\t})\n})\n\nfunc podReady(pod *v1.Pod) v1.ConditionStatus {\n\tfor _, cond := range pod.Status.Conditions {\n\t\tif cond.Type == v1.PodReady {\n\t\t\treturn cond.Status\n\t\t}\n\t}\n\treturn v1.ConditionFalse\n}\n<commit_msg>Functional tests for liveness probes<commit_after>package tests_test\n\nimport (\n\t\"flag\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t\"github.com\/onsi\/ginkgo\/extensions\/table\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"k8s.io\/api\/core\/v1\"\n\tv13 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/intstr\"\n\n\tv12 \"kubevirt.io\/kubevirt\/pkg\/api\/v1\"\n\t\"kubevirt.io\/kubevirt\/pkg\/kubecli\"\n\t\"kubevirt.io\/kubevirt\/tests\"\n)\n\nvar _ = Describe(\"Probes\", func() {\n\tflag.Parse()\n\n\tvirtClient, err := kubecli.GetKubevirtClient()\n\ttests.PanicOnError(err)\n\n\tBeforeEach(func() {\n\t\ttests.BeforeTestCleanup()\n\t})\n\n\tContext(\"for readiness\", func() {\n\n\t\ttcpProbe := &v12.Probe{\n\t\t\tPeriodSeconds:       5,\n\t\t\tInitialDelaySeconds: 5,\n\t\t\tHandler: v12.Handler{\n\n\t\t\t\tTCPSocket: &v1.TCPSocketAction{\n\t\t\t\t\tPort: intstr.Parse(\"1500\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\thttpProbe := &v12.Probe{\n\t\t\tPeriodSeconds:       5,\n\t\t\tInitialDelaySeconds: 5,\n\t\t\tHandler: v12.Handler{\n\n\t\t\t\tHTTPGet: &v1.HTTPGetAction{\n\t\t\t\t\tPort: intstr.Parse(\"1500\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\ttable.DescribeTable(\"should succeed\", func(readinessProbe *v12.Probe, serverStarter func(vmi *v12.VirtualMachineInstance, port int)) {\n\t\t\tBy(\"Specifying a VMI with a readiness probe\")\n\t\t\tvmi := tests.NewRandomVMIWithEphemeralDiskAndUserdata(tests.ContainerDiskFor(tests.ContainerDiskCirros), \"#!\/bin\/bash\\necho 'hello'\\n\")\n\t\t\tvmi.Spec.ReadinessProbe = readinessProbe\n\t\t\tvmi, err = virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Create(vmi)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\/\/ It may come to modify retries on the VMI because of the kubelet updating the pod, which can trigger controllers more often\n\t\t\ttests.WaitForSuccessfulVMIStartIgnoreWarnings(vmi)\n\n\t\t\tExpect(podReady(tests.GetRunningPodByVirtualMachineInstance(vmi, tests.NamespaceTestDefault))).To(Equal(v1.ConditionFalse))\n\n\t\t\tBy(\"Starting the server inside the VMI\")\n\t\t\tserverStarter(vmi, 1500)\n\n\t\t\tBy(\"Checking that the VMI will be marked as ready to receive traffic\")\n\t\t\tEventually(func() v1.ConditionStatus {\n\t\t\t\tpod := tests.GetRunningPodByVirtualMachineInstance(vmi, tests.NamespaceTestDefault)\n\t\t\t\treturn podReady(pod)\n\t\t\t}, 30, 1).Should(Equal(v1.ConditionTrue))\n\t\t},\n\t\t\ttable.Entry(\"with working TCP probe and tcp server\", tcpProbe, tests.StartTCPServer),\n\t\t\ttable.Entry(\"with working HTTP probe and http server\", httpProbe, tests.StartHTTPServer),\n\t\t)\n\n\t\ttable.DescribeTable(\"should fail\", func(readinessProbe *v12.Probe) {\n\t\t\tBy(\"Specifying a VMI with a readiness probe\")\n\t\t\tvmi := tests.NewRandomVMIWithEphemeralDiskAndUserdata(tests.ContainerDiskFor(tests.ContainerDiskCirros), \"#!\/bin\/bash\\necho 'hello'\\n\")\n\t\t\tvmi.Spec.ReadinessProbe = readinessProbe\n\t\t\tvmi, err = virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Create(vmi)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\/\/ It may come to modify retries on the VMI because of the kubelet updating the pod, which can trigger controllers more often\n\t\t\ttests.WaitForSuccessfulVMIStartIgnoreWarnings(vmi)\n\n\t\t\tExpect(podReady(tests.GetRunningPodByVirtualMachineInstance(vmi, tests.NamespaceTestDefault))).To(Equal(v1.ConditionFalse))\n\n\t\t\tBy(\"Checking that the VMI will consistently stay in a not-ready state\")\n\t\t\tConsistently(func() v1.ConditionStatus {\n\t\t\t\tpod := tests.GetRunningPodByVirtualMachineInstance(vmi, tests.NamespaceTestDefault)\n\t\t\t\treturn podReady(pod)\n\t\t\t}, 30, 1).Should(Equal(v1.ConditionFalse))\n\t\t},\n\t\t\ttable.Entry(\"with working TCP probe and no running server\", tcpProbe),\n\t\t\ttable.Entry(\"with working HTTP probe and no running server\", httpProbe),\n\t\t)\n\t})\n\n\tContext(\"for liveness\", func() {\n\n\t\ttcpProbe := &v12.Probe{\n\t\t\tPeriodSeconds:       5,\n\t\t\tInitialDelaySeconds: 30,\n\t\t\tHandler: v12.Handler{\n\n\t\t\t\tTCPSocket: &v1.TCPSocketAction{\n\t\t\t\t\tPort: intstr.Parse(\"1500\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\thttpProbe := &v12.Probe{\n\t\t\tPeriodSeconds:       5,\n\t\t\tInitialDelaySeconds: 30,\n\t\t\tHandler: v12.Handler{\n\n\t\t\t\tHTTPGet: &v1.HTTPGetAction{\n\t\t\t\t\tPort: intstr.Parse(\"1500\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\ttable.DescribeTable(\"should not fail the VMI\", func(livenessProbe *v12.Probe, serverStarter func(vmi *v12.VirtualMachineInstance, port int)) {\n\t\t\tBy(\"Specifying a VMI with a readiness probe\")\n\t\t\tvmi := tests.NewRandomVMIWithEphemeralDiskAndUserdata(tests.ContainerDiskFor(tests.ContainerDiskCirros), \"#!\/bin\/bash\\necho 'hello'\\n\")\n\t\t\tvmi.Spec.LivenessProbe = livenessProbe\n\t\t\tvmi, err = virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Create(vmi)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\/\/ It may come to modify retries on the VMI because of the kubelet updating the pod, which can trigger controllers more often\n\t\t\ttests.WaitForSuccessfulVMIStartIgnoreWarnings(vmi)\n\n\t\t\tBy(\"Starting the server inside the VMI\")\n\t\t\tserverStarter(vmi, 1500)\n\n\t\t\tBy(\"Checking that the VMI is still running after a minute\")\n\t\t\tConsistently(func() bool {\n\t\t\t\tvmi, err := virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Get(vmi.Name, &v13.GetOptions{})\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\treturn vmi.IsFinal()\n\t\t\t}, 60, 1).Should(Not(BeTrue()))\n\t\t},\n\t\t\ttable.Entry(\"with working TCP probe and tcp server\", tcpProbe, tests.StartTCPServer),\n\t\t\ttable.Entry(\"with working HTTP probe and http server\", httpProbe, tests.StartHTTPServer),\n\t\t)\n\n\t\ttable.DescribeTable(\"should fail the VMI\", func(livenessProbe *v12.Probe) {\n\t\t\tBy(\"Specifying a VMI with a readiness probe\")\n\t\t\tvmi := tests.NewRandomVMIWithEphemeralDiskAndUserdata(tests.ContainerDiskFor(tests.ContainerDiskCirros), \"#!\/bin\/bash\\necho 'hello'\\n\")\n\t\t\tvmi.Spec.LivenessProbe = livenessProbe\n\t\t\tvmi, err = virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Create(vmi)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\/\/ It may come to modify retries on the VMI because of the kubelet updating the pod, which can trigger controllers more often\n\t\t\ttests.WaitForSuccessfulVMIStartIgnoreWarnings(vmi)\n\n\t\t\tBy(\"Checking that the VMI is in a final state after a minute\")\n\t\t\tEventually(func() bool {\n\t\t\t\tvmi, err := virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Get(vmi.Name, &v13.GetOptions{})\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\treturn vmi.IsFinal()\n\t\t\t}, 60, 1).Should(BeTrue())\n\t\t},\n\t\t\ttable.Entry(\"with working TCP probe and no running server\", tcpProbe),\n\t\t\ttable.Entry(\"with working HTTP probe and no running server\", httpProbe),\n\t\t)\n\t})\n})\n\nfunc podReady(pod *v1.Pod) v1.ConditionStatus {\n\tfor _, cond := range pod.Status.Conditions {\n\t\tif cond.Type == v1.PodReady {\n\t\t\treturn cond.Status\n\t\t}\n\t}\n\treturn v1.ConditionFalse\n}\n<|endoftext|>"}
{"text":"<commit_before>package conn\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\thandshake \"github.com\/jbenet\/go-ipfs\/net\/handshake\"\n\thspb \"github.com\/jbenet\/go-ipfs\/net\/handshake\/pb\"\n\tu \"github.com\/jbenet\/go-ipfs\/util\"\n\n\tcontext \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/go.net\/context\"\n\tproto \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/goprotobuf\/proto\"\n\tma \"github.com\/jbenet\/go-multiaddr\"\n)\n\n\/\/ Handshake1 exchanges local and remote versions and compares them\n\/\/ closes remote and returns an error in case of major difference\nfunc Handshake1(ctx context.Context, c Conn) error {\n\trpeer := c.RemotePeer()\n\tlpeer := c.LocalPeer()\n\n\tvar remoteH, localH *hspb.Handshake1\n\tlocalH = handshake.Handshake1Msg()\n\n\tmyVerBytes, err := proto.Marshal(localH)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Out() <- myVerBytes\n\tlog.Debugf(\"Sent my version (%s) to %s\", localH, rpeer)\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\n\tcase <-c.Closing():\n\t\treturn errors.New(\"remote closed connection during version exchange\")\n\n\tcase data, ok := <-c.In():\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"error retrieving from conn: %v\", rpeer)\n\t\t}\n\n\t\tremoteH = new(hspb.Handshake1)\n\t\terr = proto.Unmarshal(data, remoteH)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not decode remote version: %q\", err)\n\t\t}\n\n\t\tlog.Debugf(\"Received remote version (%s) from %s\", remoteH, rpeer)\n\t}\n\n\tif err := handshake.Handshake1Compatible(localH, remoteH); err != nil {\n\t\tlog.Infof(\"%s (%s) incompatible version with %s (%s)\", lpeer, localH, rpeer, remoteH)\n\t\treturn err\n\t}\n\n\tlog.Debugf(\"%s version handshake compatible %s\", lpeer, rpeer)\n\treturn nil\n}\n\n\/\/ Handshake3 exchanges local and remote service information\nfunc Handshake3(ctx context.Context, c Conn) error {\n\trpeer := c.RemotePeer()\n\tlpeer := c.LocalPeer()\n\n\tvar remoteH, localH *hspb.Handshake3\n\tlocalH = handshake.Handshake3Msg(lpeer)\n\n\trma := c.RemoteMultiaddr()\n\tlocalH.ObservedAddr = proto.String(rma.String())\n\n\tlocalB, err := proto.Marshal(localH)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Out() <- localB\n\tlog.Debugf(\"Handshake1: sent to %s\", rpeer)\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\n\tcase <-c.Closing():\n\t\treturn errors.New(\"Handshake3: error remote connection closed\")\n\n\tcase remoteB, ok := <-c.In():\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Handshake3 error receiving from conn: %v\", rpeer)\n\t\t}\n\n\t\tremoteH = new(hspb.Handshake3)\n\t\terr = proto.Unmarshal(remoteB, remoteH)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Handshake3 could not decode remote msg: %q\", err)\n\t\t}\n\n\t\tlog.Debugf(\"Handshake3 received from %s\", rpeer)\n\t}\n\n\tif err := handshake.Handshake3UpdatePeer(rpeer, remoteH); err != nil {\n\t\tlog.Errorf(\"Handshake3 failed to update %s\", rpeer)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc CheckNAT(obsaddr string) (bool, error) {\n\toma, err := ma.NewMultiaddr(obsaddr)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\taddrs, err := u.GetLocalAddresses()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\t_ = oma\n\t_ = addrs\n\n\tpanic(\"not yet implemented!\")\n}\n<commit_msg>print NAT if detected<commit_after>package conn\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\thandshake \"github.com\/jbenet\/go-ipfs\/net\/handshake\"\n\thspb \"github.com\/jbenet\/go-ipfs\/net\/handshake\/pb\"\n\tu \"github.com\/jbenet\/go-ipfs\/util\"\n\n\tcontext \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/go.net\/context\"\n\tproto \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/goprotobuf\/proto\"\n\tma \"github.com\/jbenet\/go-multiaddr\"\n)\n\n\/\/ Handshake1 exchanges local and remote versions and compares them\n\/\/ closes remote and returns an error in case of major difference\nfunc Handshake1(ctx context.Context, c Conn) error {\n\trpeer := c.RemotePeer()\n\tlpeer := c.LocalPeer()\n\n\tvar remoteH, localH *hspb.Handshake1\n\tlocalH = handshake.Handshake1Msg()\n\n\tmyVerBytes, err := proto.Marshal(localH)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Out() <- myVerBytes\n\tlog.Debugf(\"Sent my version (%s) to %s\", localH, rpeer)\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\n\tcase <-c.Closing():\n\t\treturn errors.New(\"remote closed connection during version exchange\")\n\n\tcase data, ok := <-c.In():\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"error retrieving from conn: %v\", rpeer)\n\t\t}\n\n\t\tremoteH = new(hspb.Handshake1)\n\t\terr = proto.Unmarshal(data, remoteH)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not decode remote version: %q\", err)\n\t\t}\n\n\t\tlog.Debugf(\"Received remote version (%s) from %s\", remoteH, rpeer)\n\t}\n\n\tif err := handshake.Handshake1Compatible(localH, remoteH); err != nil {\n\t\tlog.Infof(\"%s (%s) incompatible version with %s (%s)\", lpeer, localH, rpeer, remoteH)\n\t\treturn err\n\t}\n\n\tlog.Debugf(\"%s version handshake compatible %s\", lpeer, rpeer)\n\treturn nil\n}\n\n\/\/ Handshake3 exchanges local and remote service information\nfunc Handshake3(ctx context.Context, c Conn) error {\n\trpeer := c.RemotePeer()\n\tlpeer := c.LocalPeer()\n\n\tvar remoteH, localH *hspb.Handshake3\n\tlocalH = handshake.Handshake3Msg(lpeer)\n\n\trma := c.RemoteMultiaddr()\n\tlocalH.ObservedAddr = proto.String(rma.String())\n\n\tlocalB, err := proto.Marshal(localH)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Out() <- localB\n\tlog.Debugf(\"Handshake1: sent to %s\", rpeer)\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\n\tcase <-c.Closing():\n\t\treturn errors.New(\"Handshake3: error remote connection closed\")\n\n\tcase remoteB, ok := <-c.In():\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Handshake3 error receiving from conn: %v\", rpeer)\n\t\t}\n\n\t\tremoteH = new(hspb.Handshake3)\n\t\terr = proto.Unmarshal(remoteB, remoteH)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Handshake3 could not decode remote msg: %q\", err)\n\t\t}\n\n\t\tlog.Debugf(\"Handshake3 received from %s\", rpeer)\n\t}\n\n\tif err := handshake.Handshake3UpdatePeer(rpeer, remoteH); err != nil {\n\t\tlog.Errorf(\"Handshake3 failed to update %s\", rpeer)\n\t\treturn err\n\t}\n\n\tnat, err := CheckNAT(remoteH.GetObservedAddr())\n\tif err != nil {\n\t\tlog.Errorf(\"Error in NAT detection: %s\", err)\n\t}\n\tif nat {\n\t\tlog.Warning(\"We are probably behind a NAT!\")\n\t}\n\n\treturn nil\n}\n\nfunc CheckNAT(obsaddr string) (bool, error) {\n\toma, err := ma.NewMultiaddr(obsaddr)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\taddrs, err := u.GetLocalAddresses()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tomastr := oma.String()\n\tfor _, addr := range addrs {\n\t\tif strings.HasPrefix(addr.String(), omastr) {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\n\treturn true, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package wallet\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/NebulousLabs\/Sia\/crypto\"\n\t\"github.com\/NebulousLabs\/Sia\/encoding\"\n\t\"github.com\/NebulousLabs\/Sia\/modules\"\n\t\"github.com\/NebulousLabs\/Sia\/persist\"\n\t\"github.com\/NebulousLabs\/fastrand\"\n\n\t\"github.com\/NebulousLabs\/bolt\"\n)\n\nconst (\n\tlogFile    = modules.WalletDir + \".log\"\n\tdbFile     = modules.WalletDir + \".db\"\n\tcompatFile = modules.WalletDir + \".json\"\n)\n\nvar (\n\tdbMetadata = persist.Metadata{\n\t\tHeader:  \"Wallet Database\",\n\t\tVersion: \"1.1.0\",\n\t}\n)\n\n\/\/ spendableKeyFile stores an encrypted spendable key on disk.\ntype spendableKeyFile struct {\n\tUID                    uniqueID\n\tEncryptionVerification crypto.Ciphertext\n\tSpendableKey           crypto.Ciphertext\n}\n\n\/\/ openDB loads the set database and populates it with the necessary buckets.\nfunc (w *Wallet) openDB(filename string) (err error) {\n\tw.db, err = persist.OpenDatabase(dbMetadata, filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ initialize the database\n\terr = w.db.Update(func(tx *bolt.Tx) error {\n\t\tfor _, b := range dbBuckets {\n\t\t\t_, err := tx.CreateBucketIfNotExists(b)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not create bucket %v: %v\", string(b), err)\n\t\t\t}\n\t\t}\n\t\t\/\/ if the wallet does not have a UID, create one\n\t\tif tx.Bucket(bucketWallet).Get(keyUID) == nil {\n\t\t\tuid := make([]byte, len(uniqueID{}))\n\t\t\tfastrand.Read(uid[:])\n\t\t\ttx.Bucket(bucketWallet).Put(keyUID, uid)\n\t\t}\n\t\t\/\/ if fields in bucketWallet are nil, set them to zero to prevent unmarshal errors\n\t\twb := tx.Bucket(bucketWallet)\n\t\tif wb.Get(keyConsensusHeight) == nil {\n\t\t\twb.Put(keyConsensusHeight, encoding.Marshal(uint64(0)))\n\t\t}\n\t\tif wb.Get(keyAuxiliarySeedFiles) == nil {\n\t\t\twb.Put(keyAuxiliarySeedFiles, encoding.Marshal([]seedFile{}))\n\t\t}\n\t\tif wb.Get(keySpendableKeyFiles) == nil {\n\t\t\twb.Put(keySpendableKeyFiles, encoding.Marshal([]spendableKeyFile{}))\n\t\t}\n\n\t\t\/\/ check whether wallet is encrypted\n\t\tw.encrypted = tx.Bucket(bucketWallet).Get(keyEncryptionVerification) != nil\n\t\treturn nil\n\t})\n\treturn err\n}\n\n\/\/ initPersist loads all of the wallet's persistence files into memory,\n\/\/ creating them if they do not exist.\nfunc (w *Wallet) initPersist() error {\n\t\/\/ Create a directory for the wallet without overwriting an existing\n\t\/\/ directory.\n\terr := os.MkdirAll(w.persistDir, 0700)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Start logging.\n\tw.log, err = persist.NewFileLogger(filepath.Join(w.persistDir, logFile))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Open the database.\n\tdbFilename := filepath.Join(w.persistDir, dbFile)\n\tcompatFilename := filepath.Join(w.persistDir, compatFile)\n\t_, dbErr := os.Stat(dbFilename)\n\t_, compatErr := os.Stat(compatFilename)\n\tif dbErr != nil && compatErr == nil {\n\t\t\/\/ database does not exist, but old persist does; convert it\n\t\terr = w.convertPersistFrom112To120(dbFilename, compatFilename)\n\t} else {\n\t\t\/\/ either database exists or neither exists; open\/create the database\n\t\terr = w.openDB(filepath.Join(w.persistDir, dbFile))\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.tg.AfterStop(func() { w.db.Close() })\n\n\treturn nil\n}\n\n\/\/ createBackup copies the wallet database to dst.\nfunc (w *Wallet) createBackup(dst io.Writer) error {\n\t_, err := w.dbTx.WriteTo(dst)\n\treturn err\n}\n\n\/\/ CreateBackup creates a backup file at the desired filepath.\nfunc (w *Wallet) CreateBackup(backupFilepath string) error {\n\tif err := w.tg.Add(); err != nil {\n\t\treturn err\n\t}\n\tdefer w.tg.Done()\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\tf, err := os.Create(backupFilepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn w.createBackup(f)\n}\n\n\/\/ compat112Persist is the structure of the wallet.json file used in v1.1.2\ntype compat112Persist struct {\n\tUID                    uniqueID\n\tEncryptionVerification crypto.Ciphertext\n\tPrimarySeedFile        seedFile\n\tPrimarySeedProgress    uint64\n\tAuxiliarySeedFiles     []seedFile\n\tUnseededKeys           []spendableKeyFile\n}\n\n\/\/ compat112Meta is the metadata of the wallet.json file used in v1.1.2\nvar compat112Meta = persist.Metadata{\n\tHeader:  \"Wallet Settings\",\n\tVersion: \"0.4.0\",\n}\n\n\/\/ convertPersistFrom112To120 converts an old (pre-v1.2.0) wallet.json file to\n\/\/ a wallet.db database.\nfunc (w *Wallet) convertPersistFrom112To120(dbFilename, compatFilename string) error {\n\tvar data compat112Persist\n\terr := persist.LoadFile(compat112Meta, &data, compatFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw.db, err = persist.OpenDatabase(dbMetadata, dbFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ initialize the database\n\terr = w.db.Update(func(tx *bolt.Tx) error {\n\t\tfor _, b := range dbBuckets {\n\t\t\t_, err := tx.CreateBucket(b)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not create bucket %v: %v\", string(b), err)\n\t\t\t}\n\t\t}\n\t\t\/\/ set UID, verification, seeds, and seed progress\n\t\ttx.Bucket(bucketWallet).Put(keyUID, data.UID[:])\n\t\ttx.Bucket(bucketWallet).Put(keyEncryptionVerification, data.EncryptionVerification)\n\t\ttx.Bucket(bucketWallet).Put(keyPrimarySeedFile, encoding.Marshal(data.PrimarySeedFile))\n\t\ttx.Bucket(bucketWallet).Put(keyAuxiliarySeedFiles, encoding.Marshal(data.AuxiliarySeedFiles))\n\t\ttx.Bucket(bucketWallet).Put(keySpendableKeyFiles, encoding.Marshal(data.UnseededKeys))\n\t\t\/\/ old wallets had a \"preload depth\" of 25\n\t\tdbPutPrimarySeedProgress(tx, data.PrimarySeedProgress+25)\n\n\t\t\/\/ set consensus height and CCID to zero so that a full rescan is\n\t\t\/\/ triggered\n\t\tdbPutConsensusHeight(tx, 0)\n\t\tdbPutConsensusChangeID(tx, modules.ConsensusChangeBeginning)\n\t\treturn nil\n\t})\n\tw.encrypted = true\n\treturn err\n}\n\n\/*\n\/\/ LoadBackup loads a backup file from the provided filepath. The backup file\n\/\/ primary seed is loaded as an auxiliary seed.\nfunc (w *Wallet) LoadBackup(masterKey, backupMasterKey crypto.TwofishKey, backupFilepath string) error {\n\tif err := w.tg.Add(); err != nil {\n\t\treturn err\n\t}\n\tdefer w.tg.Done()\n\n\tlockID := w.mu.Lock()\n\tdefer w.mu.Unlock(lockID)\n\n\t\/\/ Load all of the seed files, check for duplicates, re-encrypt them (but\n\t\/\/ keep the UID), and add them to the walletPersist object)\n\tvar backupPersist walletPersist\n\terr := persist.LoadFile(settingsMetadata, &backupPersist, backupFilepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbackupSeeds := append(backupPersist.AuxiliarySeedFiles, backupPersist.PrimarySeedFile)\n\tTODO: more\n}\n*\/\n<commit_msg>migrate wallet to new persist<commit_after>package wallet\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/NebulousLabs\/Sia\/crypto\"\n\t\"github.com\/NebulousLabs\/Sia\/encoding\"\n\t\"github.com\/NebulousLabs\/Sia\/modules\"\n\t\"github.com\/NebulousLabs\/Sia\/persist\"\n\t\"github.com\/NebulousLabs\/fastrand\"\n\n\t\"github.com\/NebulousLabs\/bolt\"\n)\n\nconst (\n\tlogFile    = modules.WalletDir + \".log\"\n\tdbFile     = modules.WalletDir + \".db\"\n\tcompatFile = modules.WalletDir + \".json\"\n)\n\nvar (\n\tdbMetadata = persist.Metadata{\n\t\tHeader:  \"Wallet Database\",\n\t\tVersion: \"1.1.0\",\n\t}\n)\n\n\/\/ spendableKeyFile stores an encrypted spendable key on disk.\ntype spendableKeyFile struct {\n\tUID                    uniqueID\n\tEncryptionVerification crypto.Ciphertext\n\tSpendableKey           crypto.Ciphertext\n}\n\n\/\/ openDB loads the set database and populates it with the necessary buckets.\nfunc (w *Wallet) openDB(filename string) (err error) {\n\tw.db, err = persist.OpenDatabase(dbMetadata, filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ initialize the database\n\terr = w.db.Update(func(tx *bolt.Tx) error {\n\t\tfor _, b := range dbBuckets {\n\t\t\t_, err := tx.CreateBucketIfNotExists(b)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not create bucket %v: %v\", string(b), err)\n\t\t\t}\n\t\t}\n\t\t\/\/ if the wallet does not have a UID, create one\n\t\tif tx.Bucket(bucketWallet).Get(keyUID) == nil {\n\t\t\tuid := make([]byte, len(uniqueID{}))\n\t\t\tfastrand.Read(uid[:])\n\t\t\ttx.Bucket(bucketWallet).Put(keyUID, uid)\n\t\t}\n\t\t\/\/ if fields in bucketWallet are nil, set them to zero to prevent unmarshal errors\n\t\twb := tx.Bucket(bucketWallet)\n\t\tif wb.Get(keyConsensusHeight) == nil {\n\t\t\twb.Put(keyConsensusHeight, encoding.Marshal(uint64(0)))\n\t\t}\n\t\tif wb.Get(keyAuxiliarySeedFiles) == nil {\n\t\t\twb.Put(keyAuxiliarySeedFiles, encoding.Marshal([]seedFile{}))\n\t\t}\n\t\tif wb.Get(keySpendableKeyFiles) == nil {\n\t\t\twb.Put(keySpendableKeyFiles, encoding.Marshal([]spendableKeyFile{}))\n\t\t}\n\n\t\t\/\/ check whether wallet is encrypted\n\t\tw.encrypted = tx.Bucket(bucketWallet).Get(keyEncryptionVerification) != nil\n\t\treturn nil\n\t})\n\treturn err\n}\n\n\/\/ initPersist loads all of the wallet's persistence files into memory,\n\/\/ creating them if they do not exist.\nfunc (w *Wallet) initPersist() error {\n\t\/\/ Create a directory for the wallet without overwriting an existing\n\t\/\/ directory.\n\terr := os.MkdirAll(w.persistDir, 0700)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Start logging.\n\tw.log, err = persist.NewFileLogger(filepath.Join(w.persistDir, logFile))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Open the database.\n\tdbFilename := filepath.Join(w.persistDir, dbFile)\n\tcompatFilename := filepath.Join(w.persistDir, compatFile)\n\t_, dbErr := os.Stat(dbFilename)\n\t_, compatErr := os.Stat(compatFilename)\n\tif dbErr != nil && compatErr == nil {\n\t\t\/\/ database does not exist, but old persist does; convert it\n\t\terr = w.convertPersistFrom112To120(dbFilename, compatFilename)\n\t} else {\n\t\t\/\/ either database exists or neither exists; open\/create the database\n\t\terr = w.openDB(filepath.Join(w.persistDir, dbFile))\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.tg.AfterStop(func() { w.db.Close() })\n\n\treturn nil\n}\n\n\/\/ createBackup copies the wallet database to dst.\nfunc (w *Wallet) createBackup(dst io.Writer) error {\n\t_, err := w.dbTx.WriteTo(dst)\n\treturn err\n}\n\n\/\/ CreateBackup creates a backup file at the desired filepath.\nfunc (w *Wallet) CreateBackup(backupFilepath string) error {\n\tif err := w.tg.Add(); err != nil {\n\t\treturn err\n\t}\n\tdefer w.tg.Done()\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\tf, err := os.Create(backupFilepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\treturn w.createBackup(f)\n}\n\n\/\/ compat112Persist is the structure of the wallet.json file used in v1.1.2\ntype compat112Persist struct {\n\tUID                    uniqueID\n\tEncryptionVerification crypto.Ciphertext\n\tPrimarySeedFile        seedFile\n\tPrimarySeedProgress    uint64\n\tAuxiliarySeedFiles     []seedFile\n\tUnseededKeys           []spendableKeyFile\n}\n\n\/\/ compat112Meta is the metadata of the wallet.json file used in v1.1.2\nvar compat112Meta = persist.Metadata{\n\tHeader:  \"Wallet Settings\",\n\tVersion: \"0.4.0\",\n}\n\n\/\/ convertPersistFrom112To120 converts an old (pre-v1.2.0) wallet.json file to\n\/\/ a wallet.db database.\nfunc (w *Wallet) convertPersistFrom112To120(dbFilename, compatFilename string) error {\n\tvar data compat112Persist\n\terr := persist.LoadJSON(compat112Meta, &data, compatFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw.db, err = persist.OpenDatabase(dbMetadata, dbFilename)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ initialize the database\n\terr = w.db.Update(func(tx *bolt.Tx) error {\n\t\tfor _, b := range dbBuckets {\n\t\t\t_, err := tx.CreateBucket(b)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not create bucket %v: %v\", string(b), err)\n\t\t\t}\n\t\t}\n\t\t\/\/ set UID, verification, seeds, and seed progress\n\t\ttx.Bucket(bucketWallet).Put(keyUID, data.UID[:])\n\t\ttx.Bucket(bucketWallet).Put(keyEncryptionVerification, data.EncryptionVerification)\n\t\ttx.Bucket(bucketWallet).Put(keyPrimarySeedFile, encoding.Marshal(data.PrimarySeedFile))\n\t\ttx.Bucket(bucketWallet).Put(keyAuxiliarySeedFiles, encoding.Marshal(data.AuxiliarySeedFiles))\n\t\ttx.Bucket(bucketWallet).Put(keySpendableKeyFiles, encoding.Marshal(data.UnseededKeys))\n\t\t\/\/ old wallets had a \"preload depth\" of 25\n\t\tdbPutPrimarySeedProgress(tx, data.PrimarySeedProgress+25)\n\n\t\t\/\/ set consensus height and CCID to zero so that a full rescan is\n\t\t\/\/ triggered\n\t\tdbPutConsensusHeight(tx, 0)\n\t\tdbPutConsensusChangeID(tx, modules.ConsensusChangeBeginning)\n\t\treturn nil\n\t})\n\tw.encrypted = true\n\treturn err\n}\n\n\/*\n\/\/ LoadBackup loads a backup file from the provided filepath. The backup file\n\/\/ primary seed is loaded as an auxiliary seed.\nfunc (w *Wallet) LoadBackup(masterKey, backupMasterKey crypto.TwofishKey, backupFilepath string) error {\n\tif err := w.tg.Add(); err != nil {\n\t\treturn err\n\t}\n\tdefer w.tg.Done()\n\n\tlockID := w.mu.Lock()\n\tdefer w.mu.Unlock(lockID)\n\n\t\/\/ Load all of the seed files, check for duplicates, re-encrypt them (but\n\t\/\/ keep the UID), and add them to the walletPersist object)\n\tvar backupPersist walletPersist\n\terr := persist.LoadFile(settingsMetadata, &backupPersist, backupFilepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbackupSeeds := append(backupPersist.AuxiliarySeedFiles, backupPersist.PrimarySeedFile)\n\tTODO: more\n}\n*\/\n<|endoftext|>"}
{"text":"<commit_before>package controllers\n\nimport (\n\t\"github.com\/robfig\/revel\"\n\t\"os\"\n\tfpath \"path\/filepath\"\n\t\"strings\"\n)\n\ntype Static struct {\n\t*revel.Controller\n}\n\n\/\/ This method handles requests for files. The supplied prefix may be absolute\n\/\/ or relative. If the prefix is relative it is assumed to be relative to the\n\/\/ application directory. The filepath may either be just a file or an\n\/\/ additional filepath to search for the given file. This response may return\n\/\/ the following responses in the event of an error or invalid request;\n\/\/   403(Forbidden): If the prefix filepath combination results in a directory.\n\/\/   404(Not found): If the prefix and filepath combination results in a non-existent file.\n\/\/   500(Internal Server Error): There are a few edge cases that would likely indicate some configuration error outside of revel.\n\/\/\n\/\/ Note that when defining routes in routes\/conf the parameters must not have\n\/\/ spaces around the comma.\n\/\/   Bad:  Static.Serve(\"public\/img\", \"favicon.png\")\n\/\/   Good: Static.Serve(\"public\/img\",\"favicon.png\")\n\/\/\n\/\/ Examples:\n\/\/ Serving a directory\n\/\/   Route (conf\/routes):\n\/\/     GET \/public\/{<.*>filepath} Static.Serve(\"public\")\n\/\/   Request:\n\/\/     public\/js\/sessvars.js\n\/\/   Calls\n\/\/     Static.Serve(\"public\",\"js\/sessvars.js\")\n\/\/\n\/\/ Serving a file\n\/\/   Route (conf\/routes):\n\/\/     GET \/favicon.ico Static.Serve(\"public\/img\",\"favicon.png\")\n\/\/   Request:\n\/\/     favicon.ico\n\/\/   Calls:\n\/\/     Static.Serve(\"public\/img\", \"favicon.png\")\nfunc (c Static) Serve(prefix, filepath string) revel.Result {\n\tvar basePath string\n\n\tif !fpath.IsAbs(prefix) {\n\t\tbasePath = revel.BasePath\n\t}\n\n\tbasePathPrefix := fpath.Join(basePath, fpath.FromSlash(prefix))\n\tfname := fpath.Join(basePathPrefix, fpath.FromSlash(filepath))\n\tif !strings.HasPrefix(fname, basePathPrefix) {\n\t\trevel.WARN.Printf(\"Attempted to read file outside of base path: %s\", fname)\n\t\treturn c.NotFound(\"\")\n\t}\n\n\tfinfo, err := os.Stat(fname)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\trevel.WARN.Printf(\"File not found (%s): %s \", fname, err)\n\t\t\treturn c.NotFound(\"File not found\")\n\t\t}\n\t\trevel.ERROR.Printf(\"Error trying to get fileinfo for '%s': %s\", fname, err)\n\t\treturn c.RenderError(err)\n\t}\n\n\tif finfo.Mode().IsDir() {\n\t\trevel.WARN.Printf(\"Attempted directory listing of %s\", fname)\n\t\treturn c.Forbidden(\"Directory listing not allowed\")\n\t}\n\n\tfile, err := os.Open(fname)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\trevel.WARN.Printf(\"File not found (%s): %s \", fname, err)\n\t\t\treturn c.NotFound(\"File not found\")\n\t\t}\n\t\trevel.ERROR.Printf(\"Error opening '%s': %s\", fname, err)\n\t\treturn c.RenderError(err)\n\t}\n\treturn c.RenderFile(file, revel.Inline)\n}\n\n\/\/ This method allows modules to serve binary files. The parameters are the same\n\/\/ as Static.Serve with the additional module name pre-pended to the list of\n\/\/ arguments.\nfunc (c Static) ServeModule(moduleName, prefix, filepath string) revel.Result {\n\tvar basePath string\n\tfor _, module := range revel.Modules {\n\t\tif module.Name == moduleName {\n\t\t\tbasePath = module.Path\n\t\t}\n\t}\n\n\tabsPath := fpath.Join(basePath, fpath.FromSlash(prefix))\n\n\treturn c.Serve(absPath, filepath)\n}\n<commit_msg>#379: return 500 on not-exist public file path<commit_after>package controllers\n\nimport (\n\t\"github.com\/robfig\/revel\"\n\t\"os\"\n\tfpath \"path\/filepath\"\n\t\"strings\"\n\t\"syscall\"\n)\n\ntype Static struct {\n\t*revel.Controller\n}\n\n\/\/ This method handles requests for files. The supplied prefix may be absolute\n\/\/ or relative. If the prefix is relative it is assumed to be relative to the\n\/\/ application directory. The filepath may either be just a file or an\n\/\/ additional filepath to search for the given file. This response may return\n\/\/ the following responses in the event of an error or invalid request;\n\/\/   403(Forbidden): If the prefix filepath combination results in a directory.\n\/\/   404(Not found): If the prefix and filepath combination results in a non-existent file.\n\/\/   500(Internal Server Error): There are a few edge cases that would likely indicate some configuration error outside of revel.\n\/\/\n\/\/ Note that when defining routes in routes\/conf the parameters must not have\n\/\/ spaces around the comma.\n\/\/   Bad:  Static.Serve(\"public\/img\", \"favicon.png\")\n\/\/   Good: Static.Serve(\"public\/img\",\"favicon.png\")\n\/\/\n\/\/ Examples:\n\/\/ Serving a directory\n\/\/   Route (conf\/routes):\n\/\/     GET \/public\/{<.*>filepath} Static.Serve(\"public\")\n\/\/   Request:\n\/\/     public\/js\/sessvars.js\n\/\/   Calls\n\/\/     Static.Serve(\"public\",\"js\/sessvars.js\")\n\/\/\n\/\/ Serving a file\n\/\/   Route (conf\/routes):\n\/\/     GET \/favicon.ico Static.Serve(\"public\/img\",\"favicon.png\")\n\/\/   Request:\n\/\/     favicon.ico\n\/\/   Calls:\n\/\/     Static.Serve(\"public\/img\", \"favicon.png\")\nfunc (c Static) Serve(prefix, filepath string) revel.Result {\n\tvar basePath string\n\n\tif !fpath.IsAbs(prefix) {\n\t\tbasePath = revel.BasePath\n\t}\n\n\tbasePathPrefix := fpath.Join(basePath, fpath.FromSlash(prefix))\n\tfname := fpath.Join(basePathPrefix, fpath.FromSlash(filepath))\n\tif !strings.HasPrefix(fname, basePathPrefix) {\n\t\trevel.WARN.Printf(\"Attempted to read file outside of base path: %s\", fname)\n\t\treturn c.NotFound(\"\")\n\t}\n\n\tfinfo, err := os.Stat(fname)\n\tif err != nil {\n\t\tif os.IsNotExist(err) || isNotDir(err) {\n\t\t\trevel.WARN.Printf(\"File not found (%s): %s \", fname, err)\n\t\t\treturn c.NotFound(\"File not found\")\n\t\t}\n\t\trevel.ERROR.Printf(\"Error trying to get fileinfo for '%s': %s\", fname, err)\n\t\treturn c.RenderError(err)\n\t}\n\n\tif finfo.Mode().IsDir() {\n\t\trevel.WARN.Printf(\"Attempted directory listing of %s\", fname)\n\t\treturn c.Forbidden(\"Directory listing not allowed\")\n\t}\n\n\tfile, err := os.Open(fname)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\trevel.WARN.Printf(\"File not found (%s): %s \", fname, err)\n\t\t\treturn c.NotFound(\"File not found\")\n\t\t}\n\t\trevel.ERROR.Printf(\"Error opening '%s': %s\", fname, err)\n\t\treturn c.RenderError(err)\n\t}\n\treturn c.RenderFile(file, revel.Inline)\n}\n\n\/\/ This method allows modules to serve binary files. The parameters are the same\n\/\/ as Static.Serve with the additional module name pre-pended to the list of\n\/\/ arguments.\nfunc (c Static) ServeModule(moduleName, prefix, filepath string) revel.Result {\n\tvar basePath string\n\tfor _, module := range revel.Modules {\n\t\tif module.Name == moduleName {\n\t\t\tbasePath = module.Path\n\t\t}\n\t}\n\n\tabsPath := fpath.Join(basePath, fpath.FromSlash(prefix))\n\n\treturn c.Serve(absPath, filepath)\n}\n\nfunc isNotDir(err error) bool {\n\tswitch pe := err.(type) {\n\tcase nil:\n\t\treturn false\n\tcase *os.PathError:\n\t\terr = pe.Err\n\tcase *os.LinkError:\n\t\terr = pe.Err\n\t}\n\treturn err == syscall.ENOTDIR\n}\n<|endoftext|>"}
{"text":"<commit_before>package pps\n\nimport (\n\t\"fmt\"\n\n\t. \"github.com\/pachyderm\/pachyderm\/src\/client\/pfs\"\n\tppsclient \"github.com\/pachyderm\/pachyderm\/src\/client\/pps\"\n)\n\nfunc JobRepo(job *ppsclient.Job) *Repo {\n\treturn &Repo{Name: fmt.Sprintf(\"job-%s\", job.ID)}\n}\n\nfunc PipelineRepo(pipeline *ppsclient.Pipeline) *Repo {\n\treturn &Repo{Name: pipeline.Name}\n}\n<commit_msg>Fix dot import<commit_after>package pps\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\/pfs\"\n\tppsclient \"github.com\/pachyderm\/pachyderm\/src\/client\/pps\"\n)\n\nfunc JobRepo(job *ppsclient.Job) *pfs.Repo {\n\treturn &pfs.Repo{Name: fmt.Sprintf(\"job-%s\", job.ID)}\n}\n\nfunc PipelineRepo(pipeline *ppsclient.Pipeline) *pfs.Repo {\n\treturn &pfs.Repo{Name: pipeline.Name}\n}\n<|endoftext|>"}
{"text":"<commit_before>package find_breaks\n\nimport (\n\t\"context\"\n\t\"io\/ioutil\"\n\t\"testing\"\n\t\"time\"\n\n\tassert \"github.com\/stretchr\/testify\/require\"\n\n\t\"go.skia.org\/infra\/go\/deepequal\"\n\t\"go.skia.org\/infra\/go\/git\"\n\t\"go.skia.org\/infra\/go\/git\/repograph\"\n\tgit_testutils \"go.skia.org\/infra\/go\/git\/testutils\"\n\t\"go.skia.org\/infra\/go\/testutils\"\n)\n\n\/\/ setupHelper is a shared function used for reducing boilerplate when setting\n\/\/ up test inputs. The provided func is used to build the git repo which will\n\/\/ be used by the test.\nfunc setupHelper(t *testing.T, setup func(context.Context, *git_testutils.GitBuilder)) (*repograph.Graph, func()) {\n\ttestutils.MediumTest(t)\n\tctx := context.Background()\n\tgb := git_testutils.GitInit(t, ctx)\n\twd, err := ioutil.TempDir(\"\", \"\")\n\tassert.NoError(t, err)\n\tsetup(ctx, gb)\n\tcleanup := func() {\n\t\tgb.Cleanup()\n\t\ttestutils.RemoveAll(t, wd)\n\t}\n\trepo, err := repograph.NewGraph(ctx, gb.RepoUrl(), wd)\n\tassert.NoError(t, err)\n\tassert.NoError(t, repo.Update(ctx))\n\treturn repo, cleanup\n}\n\n\/\/ TestCommitSlices1 uses a simple, single-branch git repo:\n\/\/\n\/\/      e\n\/\/      |\n\/\/      d\n\/\/      |\n\/\/      c\n\/\/      |\n\/\/      b\n\/\/      |\n\/\/      a\n\/\/\nfunc TestCommitSlices1(t *testing.T) {\n\tnow := time.Now().Round(time.Second)\n\tvar a, b, c, d, e string\n\trepo, cleanup := setupHelper(t, func(ctx context.Context, gb *git_testutils.GitBuilder) {\n\t\tts := now.Add(-30 * time.Minute)\n\t\ta = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tb = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tc = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\td = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\te = gb.CommitGenAt(ctx, \"file\", ts)\n\t})\n\tdefer cleanup()\n\n\t\/\/ Make sure we get all of the commits in one slice.\n\tslices := commitSlices(repo, time.Time{}, now)\n\tassert.Equal(t, 1, len(slices))\n\tassert.Equal(t, 5, len(slices[0]))\n\tdeepequal.AssertDeepEqual(t, []string{a, b, c, d, e}, slices[0])\n\n\t\/\/ Make sure the timestamp cutoffs work.\n\tend := now.Add(-22 * time.Minute)\n\tstart := now.Add(-30 * time.Minute)\n\tslices = commitSlices(repo, start, end)\n\tassert.Equal(t, 1, len(slices))\n\tassert.Equal(t, 4, len(slices[0]))\n\tdeepequal.AssertDeepEqual(t, []string{a, b, c, d}, slices[0])\n\n\t\/\/ Test the edges of the timestamp cutoffs.\n\tslices = commitSlices(repo, start.Add(2*time.Second), end.Add(-2*time.Second))\n\tassert.Equal(t, 1, len(slices))\n\tassert.Equal(t, 3, len(slices[0]))\n\tdeepequal.AssertDeepEqual(t, []string{b, c, d}, slices[0])\n\n\t\/\/ We shouldn't return empty slices.\n\tslices = commitSlices(repo, now.Add(30*time.Minute), now.Add(60*time.Minute))\n\tassert.Equal(t, 0, len(slices))\n}\n\n\/\/ TestCommitSlices2 uses a git repo with two diverging branches:\n\/\/\n\/\/      d   c\n\/\/      | \/\n\/\/      b\n\/\/      |\n\/\/      a\n\/\/\nfunc TestCommitSlices2(t *testing.T) {\n\tvar a, b, c, d string\n\trepo, cleanup := setupHelper(t, func(ctx context.Context, gb *git_testutils.GitBuilder) {\n\t\tts := time.Now().Add(-30 * time.Minute)\n\t\ta = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tb = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tgb.CreateBranchTrackBranch(ctx, \"otherBranch\", \"master\")\n\t\tc = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tgb.CheckoutBranch(ctx, \"master\")\n\t\td = gb.CommitGenAt(ctx, \"file\", ts)\n\t})\n\tdefer cleanup()\n\n\t\/\/ Entire repo. We should get two slices.\n\tslices := commitSlices(repo, time.Time{}, time.Now())\n\tassert.Equal(t, 2, len(slices))\n\tassert.Equal(t, 3, len(slices[0]))\n\tassert.Equal(t, 3, len(slices[1]))\n\tdeepequal.AssertDeepEqual(t, []string{a, b, d}, slices[0])\n\tdeepequal.AssertDeepEqual(t, []string{a, b, c}, slices[1])\n}\n\n\/\/ TestCommitSlices3 uses a git repo with two merging branches:\n\/\/\n\/\/      d\n\/\/      |\n\/\/      c\n\/\/      | \\\n\/\/      a   b\n\/\/\nfunc TestCommitSlices3(t *testing.T) {\n\tvar a, b, c, d string\n\trepo, cleanup := setupHelper(t, func(ctx context.Context, gb *git_testutils.GitBuilder) {\n\t\tts := time.Now().Add(-30 * time.Minute)\n\t\ta = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tgb.CreateOrphanBranch(ctx, \"branch2\")\n\t\tgb.AddGen(ctx, \"file2\")\n\t\tb = gb.CommitGenAt(ctx, \"file2\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tgb.CheckoutBranch(ctx, \"master\")\n\t\tc = gb.MergeBranch(ctx, \"branch2\")\n\t\t_, err := git.GitDir(gb.Dir()).Git(ctx, \"branch\", \"-D\", \"branch2\")\n\t\tassert.NoError(t, err)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\td = gb.CommitGenAt(ctx, \"file\", ts)\n\t})\n\tdefer cleanup()\n\n\t\/\/ Entire repo. We should get two slices.\n\tslices := commitSlices(repo, time.Time{}, time.Now())\n\tassert.Equal(t, 2, len(slices))\n\tassert.Equal(t, 3, len(slices[0]))\n\tassert.Equal(t, 3, len(slices[1]))\n\tdeepequal.AssertDeepEqual(t, []string{a, c, d}, slices[0])\n\tdeepequal.AssertDeepEqual(t, []string{b, c, d}, slices[1])\n}\n\n\/\/ TestCommitSlices4 uses a git repo with a branch which diverges and then\n\/\/ merges again:\n\/\/\n\/\/      f\n\/\/      |\n\/\/      e\n\/\/      | \\\n\/\/      |   d\n\/\/      |   |\n\/\/      c   |\n\/\/      | \/\n\/\/      b\n\/\/      |\n\/\/      a\n\/\/\nfunc TestCommitSlices4(t *testing.T) {\n\tvar a, b, c, d, e, f string\n\trepo, cleanup := setupHelper(t, func(ctx context.Context, gb *git_testutils.GitBuilder) {\n\t\tts := time.Now().Add(-30 * time.Minute)\n\t\ta = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tb = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tc = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tgb.CreateBranchAtCommit(ctx, \"branch2\", b)\n\t\td = gb.CommitGenAt(ctx, \"file2\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tgb.CheckoutBranch(ctx, \"master\")\n\t\te = gb.MergeBranch(ctx, \"branch2\")\n\t\t_, err := git.GitDir(gb.Dir()).Git(ctx, \"branch\", \"-D\", \"branch2\")\n\t\tassert.NoError(t, err)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tf = gb.CommitGenAt(ctx, \"file\", ts)\n\t})\n\tdefer cleanup()\n\n\t\/\/ Entire repo. We should get two slices.\n\tslices := commitSlices(repo, time.Time{}, time.Now())\n\tassert.Equal(t, 2, len(slices))\n\tassert.Equal(t, 5, len(slices[0]))\n\tassert.Equal(t, 5, len(slices[1]))\n\tdeepequal.AssertDeepEqual(t, []string{a, b, c, e, f}, slices[0])\n\tdeepequal.AssertDeepEqual(t, []string{a, b, d, e, f}, slices[1])\n}\n<commit_msg>Resize CommitSlices tests<commit_after>package find_breaks\n\nimport (\n\t\"context\"\n\t\"io\/ioutil\"\n\t\"testing\"\n\t\"time\"\n\n\tassert \"github.com\/stretchr\/testify\/require\"\n\n\t\"go.skia.org\/infra\/go\/deepequal\"\n\t\"go.skia.org\/infra\/go\/git\"\n\t\"go.skia.org\/infra\/go\/git\/repograph\"\n\tgit_testutils \"go.skia.org\/infra\/go\/git\/testutils\"\n\t\"go.skia.org\/infra\/go\/testutils\"\n)\n\n\/\/ setupHelper is a shared function used for reducing boilerplate when setting\n\/\/ up test inputs. The provided func is used to build the git repo which will\n\/\/ be used by the test.\nfunc setupHelper(t *testing.T, setup func(context.Context, *git_testutils.GitBuilder)) (*repograph.Graph, func()) {\n\ttestutils.LargeTest(t)\n\tctx := context.Background()\n\tgb := git_testutils.GitInit(t, ctx)\n\twd, err := ioutil.TempDir(\"\", \"\")\n\tassert.NoError(t, err)\n\tsetup(ctx, gb)\n\tcleanup := func() {\n\t\tgb.Cleanup()\n\t\ttestutils.RemoveAll(t, wd)\n\t}\n\trepo, err := repograph.NewGraph(ctx, gb.RepoUrl(), wd)\n\tassert.NoError(t, err)\n\tassert.NoError(t, repo.Update(ctx))\n\treturn repo, cleanup\n}\n\n\/\/ TestCommitSlices1 uses a simple, single-branch git repo:\n\/\/\n\/\/      e\n\/\/      |\n\/\/      d\n\/\/      |\n\/\/      c\n\/\/      |\n\/\/      b\n\/\/      |\n\/\/      a\n\/\/\nfunc TestCommitSlices1(t *testing.T) {\n\tnow := time.Now().Round(time.Second)\n\tvar a, b, c, d, e string\n\trepo, cleanup := setupHelper(t, func(ctx context.Context, gb *git_testutils.GitBuilder) {\n\t\tts := now.Add(-30 * time.Minute)\n\t\ta = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tb = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tc = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\td = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\te = gb.CommitGenAt(ctx, \"file\", ts)\n\t})\n\tdefer cleanup()\n\n\t\/\/ Make sure we get all of the commits in one slice.\n\tslices := commitSlices(repo, time.Time{}, now)\n\tassert.Equal(t, 1, len(slices))\n\tassert.Equal(t, 5, len(slices[0]))\n\tdeepequal.AssertDeepEqual(t, []string{a, b, c, d, e}, slices[0])\n\n\t\/\/ Make sure the timestamp cutoffs work.\n\tend := now.Add(-22 * time.Minute)\n\tstart := now.Add(-30 * time.Minute)\n\tslices = commitSlices(repo, start, end)\n\tassert.Equal(t, 1, len(slices))\n\tassert.Equal(t, 4, len(slices[0]))\n\tdeepequal.AssertDeepEqual(t, []string{a, b, c, d}, slices[0])\n\n\t\/\/ Test the edges of the timestamp cutoffs.\n\tslices = commitSlices(repo, start.Add(2*time.Second), end.Add(-2*time.Second))\n\tassert.Equal(t, 1, len(slices))\n\tassert.Equal(t, 3, len(slices[0]))\n\tdeepequal.AssertDeepEqual(t, []string{b, c, d}, slices[0])\n\n\t\/\/ We shouldn't return empty slices.\n\tslices = commitSlices(repo, now.Add(30*time.Minute), now.Add(60*time.Minute))\n\tassert.Equal(t, 0, len(slices))\n}\n\n\/\/ TestCommitSlices2 uses a git repo with two diverging branches:\n\/\/\n\/\/      d   c\n\/\/      | \/\n\/\/      b\n\/\/      |\n\/\/      a\n\/\/\nfunc TestCommitSlices2(t *testing.T) {\n\tvar a, b, c, d string\n\trepo, cleanup := setupHelper(t, func(ctx context.Context, gb *git_testutils.GitBuilder) {\n\t\tts := time.Now().Add(-30 * time.Minute)\n\t\ta = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tb = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tgb.CreateBranchTrackBranch(ctx, \"otherBranch\", \"master\")\n\t\tc = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tgb.CheckoutBranch(ctx, \"master\")\n\t\td = gb.CommitGenAt(ctx, \"file\", ts)\n\t})\n\tdefer cleanup()\n\n\t\/\/ Entire repo. We should get two slices.\n\tslices := commitSlices(repo, time.Time{}, time.Now())\n\tassert.Equal(t, 2, len(slices))\n\tassert.Equal(t, 3, len(slices[0]))\n\tassert.Equal(t, 3, len(slices[1]))\n\tdeepequal.AssertDeepEqual(t, []string{a, b, d}, slices[0])\n\tdeepequal.AssertDeepEqual(t, []string{a, b, c}, slices[1])\n}\n\n\/\/ TestCommitSlices3 uses a git repo with two merging branches:\n\/\/\n\/\/      d\n\/\/      |\n\/\/      c\n\/\/      | \\\n\/\/      a   b\n\/\/\nfunc TestCommitSlices3(t *testing.T) {\n\tvar a, b, c, d string\n\trepo, cleanup := setupHelper(t, func(ctx context.Context, gb *git_testutils.GitBuilder) {\n\t\tts := time.Now().Add(-30 * time.Minute)\n\t\ta = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tgb.CreateOrphanBranch(ctx, \"branch2\")\n\t\tgb.AddGen(ctx, \"file2\")\n\t\tb = gb.CommitGenAt(ctx, \"file2\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tgb.CheckoutBranch(ctx, \"master\")\n\t\tc = gb.MergeBranch(ctx, \"branch2\")\n\t\t_, err := git.GitDir(gb.Dir()).Git(ctx, \"branch\", \"-D\", \"branch2\")\n\t\tassert.NoError(t, err)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\td = gb.CommitGenAt(ctx, \"file\", ts)\n\t})\n\tdefer cleanup()\n\n\t\/\/ Entire repo. We should get two slices.\n\tslices := commitSlices(repo, time.Time{}, time.Now())\n\tassert.Equal(t, 2, len(slices))\n\tassert.Equal(t, 3, len(slices[0]))\n\tassert.Equal(t, 3, len(slices[1]))\n\tdeepequal.AssertDeepEqual(t, []string{a, c, d}, slices[0])\n\tdeepequal.AssertDeepEqual(t, []string{b, c, d}, slices[1])\n}\n\n\/\/ TestCommitSlices4 uses a git repo with a branch which diverges and then\n\/\/ merges again:\n\/\/\n\/\/      f\n\/\/      |\n\/\/      e\n\/\/      | \\\n\/\/      |   d\n\/\/      |   |\n\/\/      c   |\n\/\/      | \/\n\/\/      b\n\/\/      |\n\/\/      a\n\/\/\nfunc TestCommitSlices4(t *testing.T) {\n\tvar a, b, c, d, e, f string\n\trepo, cleanup := setupHelper(t, func(ctx context.Context, gb *git_testutils.GitBuilder) {\n\t\tts := time.Now().Add(-30 * time.Minute)\n\t\ta = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tb = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tc = gb.CommitGenAt(ctx, \"file\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tgb.CreateBranchAtCommit(ctx, \"branch2\", b)\n\t\td = gb.CommitGenAt(ctx, \"file2\", ts)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tgb.CheckoutBranch(ctx, \"master\")\n\t\te = gb.MergeBranch(ctx, \"branch2\")\n\t\t_, err := git.GitDir(gb.Dir()).Git(ctx, \"branch\", \"-D\", \"branch2\")\n\t\tassert.NoError(t, err)\n\n\t\tts = ts.Add(2 * time.Minute)\n\t\tf = gb.CommitGenAt(ctx, \"file\", ts)\n\t})\n\tdefer cleanup()\n\n\t\/\/ Entire repo. We should get two slices.\n\tslices := commitSlices(repo, time.Time{}, time.Now())\n\tassert.Equal(t, 2, len(slices))\n\tassert.Equal(t, 5, len(slices[0]))\n\tassert.Equal(t, 5, len(slices[1]))\n\tdeepequal.AssertDeepEqual(t, []string{a, b, c, e, f}, slices[0])\n\tdeepequal.AssertDeepEqual(t, []string{a, b, d, e, f}, slices[1])\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2014 Jason Woods.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage codecs\n\nimport (\n  \"errors\"\n  \"fmt\"\n  \"lc-lib\/core\"\n  \"regexp\"\n  \"strings\"\n  \"sync\"\n  \"time\"\n)\n\nconst (\n  codecMultiline_What_Previous = 0x00000001\n  codecMultiline_What_Next     = 0x00000002\n)\n\ntype CodecMultilineFactory struct {\n  Pattern         string        `config:\"pattern\"`\n  What            string        `config:\"what\"`\n  Negate          bool          `config:\"negate\"`\n  PreviousTimeout time.Duration `config:\"previous timeout\"`\n\n  matcher *regexp.Regexp\n  what    int\n}\n\ntype CodecMultiline struct {\n  config        *CodecMultilineFactory\n  last_offset   int64\n  callback_func core.CodecCallbackFunc\n\n  end_offset   int64\n  start_offset int64\n  line         uint64\n  buffer       []string\n  timer_lock   *sync.Mutex\n  timer_chan   chan bool\n}\n\nfunc NewMultilineCodecFactory(config *core.Config, config_path string, unused map[string]interface{}, name string) (core.CodecFactory, error) {\n  var err error\n\n  result := &CodecMultilineFactory{}\n  if err = config.PopulateConfig(result, config_path, unused); err != nil {\n    return nil, err\n  }\n\n  if result.Pattern == \"\" {\n    return nil, errors.New(\"Multiline codec pattern must be specified.\")\n  }\n\n  result.matcher, err = regexp.Compile(result.Pattern)\n  if err != nil {\n    return nil, fmt.Errorf(\"Failed to compile multiline codec pattern, '%s'.\", err)\n  }\n\n  if result.What == \"\" || result.What == \"previous\" {\n    result.what = codecMultiline_What_Previous\n  } else if result.What == \"next\" {\n    result.what = codecMultiline_What_Next\n  }\n\n  return result, nil\n}\n\nfunc (f *CodecMultilineFactory) NewCodec(callback_func core.CodecCallbackFunc, offset int64) core.Codec {\n  c := &CodecMultiline{\n    config:        f,\n    last_offset:   offset,\n    callback_func: callback_func,\n  }\n\n  \/\/ TODO: Make this more performant - use similiar methodology to Go's internal network deadlines\n  if f.PreviousTimeout != 0 {\n    c.timer_lock = new(sync.Mutex)\n    c.timer_chan = make(chan bool, 1)\n\n    go func() {\n      var active bool\n\n      timer := time.NewTimer(0)\n\n      for {\n        select {\n        case shutdown := <-c.timer_chan:\n          timer.Stop()\n          if shutdown {\n            \/\/ Shutdown signal so end the routine\n            break\n          }\n          timer.Reset(c.config.PreviousTimeout)\n          active = true\n        case <-timer.C:\n          if active {\n            \/\/ Surround flush in mutex to prevent data getting modified by a new line while we flush\n            c.timer_lock.Lock()\n            c.flush()\n            c.timer_lock.Unlock()\n            active = false\n          }\n        }\n      }\n    }()\n  }\n  return c\n}\n\nfunc (c *CodecMultiline) Teardown() int64 {\n  return c.last_offset\n}\n\nfunc (c *CodecMultiline) Event(start_offset int64, end_offset int64, line uint64, text string) {\n  \/\/ TODO(driskell): If we are using previous and we match on the very first line read,\n  \/\/ then this is because we've started in the middle of a multiline event (the first line\n  \/\/ should never match) - so we could potentially offer an option to discard this.\n  \/\/ The benefit would be that when using previous_timeout, we could discard any extraneous\n  \/\/ event data that did not get written in time, if the user so wants it, in order to prevent\n  \/\/ odd incomplete data. It would be a signal from the user, \"I will worry about the buffering\n  \/\/ issues my programs may have - you just make sure to write each event either completely or\n  \/\/ partially, always with the FIRST line correct (which could be the important one).\"\n  match_failed := c.config.Negate == c.config.matcher.MatchString(text)\n  if c.config.what == codecMultiline_What_Previous {\n    if c.config.PreviousTimeout != 0 {\n      \/\/ Prevent a flush happening while we're modifying the stored data\n      c.timer_lock.Lock()\n    }\n    if match_failed {\n      c.flush()\n    }\n  }\n  if len(c.buffer) == 0 {\n    c.line = line\n    c.start_offset = start_offset\n  }\n  c.end_offset = end_offset\n  c.buffer = append(c.buffer, text)\n  if c.config.what == codecMultiline_What_Previous {\n    if c.config.PreviousTimeout != 0 {\n      \/\/ Reset the timer and unlock\n      c.timer_chan <- false\n      c.timer_lock.Unlock()\n    }\n  } else if c.config.what == codecMultiline_What_Next && match_failed {\n    c.flush()\n  }\n}\n\nfunc (c *CodecMultiline) flush() {\n  if len(c.buffer) == 0 {\n    return\n  }\n\n  text := strings.Join(c.buffer, \"\\n\")\n\n  \/\/ Set last offset - this is returned in Teardown so if we're mid multiline and crash, we start this multiline again\n  c.last_offset = c.end_offset\n  c.buffer = nil\n\n  c.callback_func(c.start_offset, c.end_offset, c.line, text)\n}\n\n\/\/ Register the codec\nfunc init() {\n  core.RegisterCodec(\"multiline\", NewMultilineCodecFactory)\n}\n<commit_msg>Improve previous_timeout routines<commit_after>\/*\n * Copyright 2014 Jason Woods.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage codecs\n\nimport (\n  \"errors\"\n  \"fmt\"\n  \"lc-lib\/core\"\n  \"regexp\"\n  \"strings\"\n  \"sync\"\n  \"time\"\n)\n\nconst (\n  codecMultiline_What_Previous = 0x00000001\n  codecMultiline_What_Next     = 0x00000002\n)\n\ntype CodecMultilineFactory struct {\n  Pattern         string        `config:\"pattern\"`\n  What            string        `config:\"what\"`\n  Negate          bool          `config:\"negate\"`\n  PreviousTimeout time.Duration `config:\"previous timeout\"`\n\n  matcher *regexp.Regexp\n  what    int\n}\n\ntype CodecMultiline struct {\n  config        *CodecMultilineFactory\n  last_offset   int64\n  callback_func core.CodecCallbackFunc\n\n  end_offset     int64\n  start_offset   int64\n  line           uint64\n  buffer         []string\n  timer_lock     sync.Mutex\n  timer_stop     chan interface{}\n  timer_wait     sync.WaitGroup\n  timer_deadline time.Time\n}\n\nfunc NewMultilineCodecFactory(config *core.Config, config_path string, unused map[string]interface{}, name string) (core.CodecFactory, error) {\n  var err error\n\n  result := &CodecMultilineFactory{}\n  if err = config.PopulateConfig(result, config_path, unused); err != nil {\n    return nil, err\n  }\n\n  if result.Pattern == \"\" {\n    return nil, errors.New(\"Multiline codec pattern must be specified.\")\n  }\n\n  result.matcher, err = regexp.Compile(result.Pattern)\n  if err != nil {\n    return nil, fmt.Errorf(\"Failed to compile multiline codec pattern, '%s'.\", err)\n  }\n\n  if result.What == \"\" || result.What == \"previous\" {\n    result.what = codecMultiline_What_Previous\n  } else if result.What == \"next\" {\n    result.what = codecMultiline_What_Next\n  }\n\n  return result, nil\n}\n\nfunc (f *CodecMultilineFactory) NewCodec(callback_func core.CodecCallbackFunc, offset int64) core.Codec {\n  c := &CodecMultiline{\n    config:        f,\n    last_offset:   offset,\n    callback_func: callback_func,\n  }\n\n  \/\/ Start the \"previous timeout\" routine that will auto flush at deadline\n  if f.PreviousTimeout != 0 {\n    c.timer_stop = make(chan interface{})\n    c.timer_wait.Add(1)\n\n    c.timer_deadline = time.Now().Add(f.PreviousTimeout)\n\n    go c.deadlineRoutine()\n  }\n  return c\n}\n\nfunc (c *CodecMultiline) Teardown() int64 {\n  if c.config.PreviousTimeout != 0 {\n    close(c.timer_stop)\n    c.timer_wait.Wait()\n  }\n\n  return c.last_offset\n}\n\nfunc (c *CodecMultiline) Event(start_offset int64, end_offset int64, line uint64, text string) {\n  \/\/ TODO(driskell): If we are using previous and we match on the very first line read,\n  \/\/ then this is because we've started in the middle of a multiline event (the first line\n  \/\/ should never match) - so we could potentially offer an option to discard this.\n  \/\/ The benefit would be that when using previous_timeout, we could discard any extraneous\n  \/\/ event data that did not get written in time, if the user so wants it, in order to prevent\n  \/\/ odd incomplete data. It would be a signal from the user, \"I will worry about the buffering\n  \/\/ issues my programs may have - you just make sure to write each event either completely or\n  \/\/ partially, always with the FIRST line correct (which could be the important one).\"\n  match_failed := c.config.Negate == c.config.matcher.MatchString(text)\n  if c.config.what == codecMultiline_What_Previous {\n    if c.config.PreviousTimeout != 0 {\n      \/\/ Prevent a flush happening while we're modifying the stored data\n      c.timer_lock.Lock()\n    }\n    if match_failed {\n      c.flush()\n    }\n  }\n  if len(c.buffer) == 0 {\n    c.line = line\n    c.start_offset = start_offset\n  }\n  c.end_offset = end_offset\n  c.buffer = append(c.buffer, text)\n  if c.config.what == codecMultiline_What_Previous {\n    if c.config.PreviousTimeout != 0 {\n      \/\/ Reset the timer and unlock\n      c.timer_deadline = time.Now().Add(c.config.PreviousTimeout)\n      c.timer_lock.Unlock()\n    }\n  } else if c.config.what == codecMultiline_What_Next && match_failed {\n    c.flush()\n  }\n}\n\nfunc (c *CodecMultiline) flush() {\n  if len(c.buffer) == 0 {\n    return\n  }\n\n  text := strings.Join(c.buffer, \"\\n\")\n\n  \/\/ Set last offset - this is returned in Teardown so if we're mid multiline and crash, we start this multiline again\n  c.last_offset = c.end_offset\n  c.buffer = nil\n\n  c.callback_func(c.start_offset, c.end_offset, c.line, text)\n}\n\nfunc (c *CodecMultiline) deadlineRoutine() {\n  timer := time.NewTimer(0)\n\nDeadlineLoop:\n  for {\n    select {\n    case <-c.timer_stop:\n      timer.Stop()\n\n      \/\/ Shutdown signal so end the routine\n      break DeadlineLoop\n    case now := <-timer.C:\n      c.timer_lock.Lock()\n\n      \/\/ Have we reached the target time?\n      if !now.After(c.timer_deadline) {\n        \/\/ Deadline moved, update the timer\n        timer.Reset(c.timer_deadline.Sub(now))\n      }\n\n      c.flush()\n\n      c.timer_lock.Unlock()\n    }\n  }\n\n  c.timer_wait.Done()\n}\n\n\/\/ Register the codec\nfunc init() {\n  core.RegisterCodec(\"multiline\", NewMultilineCodecFactory)\n}\n<|endoftext|>"}
{"text":"<commit_before>package daemon\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\n\t\"github.com\/docker\/docker\/engine\"\n\t\"github.com\/docker\/docker\/runconfig\"\n)\n\nfunc (daemon *Daemon) ContainerInspect(job *engine.Job) engine.Status {\n\tif len(job.Args) != 1 {\n\t\treturn job.Errorf(\"usage: %s NAME\", job.Name)\n\t}\n\tname := job.Args[0]\n\tif container := daemon.Get(name); container != nil {\n\t\tcontainer.Lock()\n\t\tdefer container.Unlock()\n\t\tif job.GetenvBool(\"raw\") {\n\t\t\tb, err := json.Marshal(&struct {\n\t\t\t\t*Container\n\t\t\t\tHostConfig *runconfig.HostConfig\n\t\t\t}{container, container.hostConfig})\n\t\t\tif err != nil {\n\t\t\t\treturn job.Error(err)\n\t\t\t}\n\t\t\tjob.Stdout.Write(b)\n\t\t\treturn engine.StatusOK\n\t\t}\n\n\t\tout := &engine.Env{}\n\t\tout.SetJson(\"Id\", container.ID)\n\t\tout.SetAuto(\"Created\", container.Created)\n\t\tout.SetJson(\"Path\", container.Path)\n\t\tout.SetList(\"Args\", container.Args)\n\t\tout.SetJson(\"Config\", container.Config)\n\t\tout.SetJson(\"State\", container.State)\n\t\tout.Set(\"Image\", container.ImageID)\n\t\tout.SetJson(\"NetworkSettings\", container.NetworkSettings)\n\t\tout.Set(\"ResolvConfPath\", container.ResolvConfPath)\n\t\tout.Set(\"HostnamePath\", container.HostnamePath)\n\t\tout.Set(\"HostsPath\", container.HostsPath)\n\t\tout.SetJson(\"Name\", container.Name)\n\t\tout.SetInt(\"RestartCount\", container.RestartCount)\n\t\tout.Set(\"Driver\", container.Driver)\n\t\tout.Set(\"ExecDriver\", container.ExecDriver)\n\t\tout.Set(\"MountLabel\", container.MountLabel)\n\t\tout.Set(\"ProcessLabel\", container.ProcessLabel)\n\t\tout.SetJson(\"Volumes\", container.Volumes)\n\t\tout.SetJson(\"VolumesRW\", container.VolumesRW)\n\t\tout.SetJson(\"AppArmorProfile\", container.AppArmorProfile)\n\n\t\tout.SetList(\"ExecIDs\", container.GetExecIDs())\n\n\t\tif children, err := daemon.Children(container.Name); err == nil {\n\t\t\tfor linkAlias, child := range children {\n\t\t\t\tcontainer.hostConfig.Links = append(container.hostConfig.Links, fmt.Sprintf(\"%s:%s\", child.Name, linkAlias))\n\t\t\t}\n\t\t}\n\n\t\tout.SetJson(\"HostConfig\", container.hostConfig)\n\n\t\tcheckpoints := make([]*ContainerCheckpoint, 0, len(container.Checkpoints))\n\t\t\/\/ Make checkpoint list with ordering by creation time\n\t\tfor _, checkpoint := range container.Checkpoints {\n\t\t\tcheckpoints = append(checkpoints, checkpoint)\n\t\t\tfor i := len(checkpoints)-1; i >= 0; i-- {\n\t\t\t\tif checkpoints[i].CreatedAt.Before(checkpoint.CreatedAt) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcheckpoints[i+1], checkpoints[i] = checkpoints[i], checkpoint\n\t\t\t}\n\t\t}\n\t\tout.SetJson(\"Checkpoints\", checkpoints)\n\n\t\tcontainer.hostConfig.Links = nil\n\t\tif _, err := out.WriteTo(job.Stdout); err != nil {\n\t\t\treturn job.Error(err)\n\t\t}\n\t\treturn engine.StatusOK\n\t}\n\treturn job.Errorf(\"No such container: %s\", name)\n}\n\nfunc (daemon *Daemon) ContainerExecInspect(job *engine.Job) engine.Status {\n\tif len(job.Args) != 1 {\n\t\treturn job.Errorf(\"usage: %s ID\", job.Name)\n\t}\n\tid := job.Args[0]\n\teConfig, err := daemon.getExecConfig(id)\n\tif err != nil {\n\t\treturn job.Error(err)\n\t}\n\n\tb, err := json.Marshal(*eConfig)\n\tif err != nil {\n\t\treturn job.Error(err)\n\t}\n\tjob.Stdout.Write(b)\n\treturn engine.StatusOK\n}\n<commit_msg>fix incorrect slice index<commit_after>package daemon\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\n\t\"github.com\/docker\/docker\/engine\"\n\t\"github.com\/docker\/docker\/runconfig\"\n)\n\nfunc (daemon *Daemon) ContainerInspect(job *engine.Job) engine.Status {\n\tif len(job.Args) != 1 {\n\t\treturn job.Errorf(\"usage: %s NAME\", job.Name)\n\t}\n\tname := job.Args[0]\n\tif container := daemon.Get(name); container != nil {\n\t\tcontainer.Lock()\n\t\tdefer container.Unlock()\n\t\tif job.GetenvBool(\"raw\") {\n\t\t\tb, err := json.Marshal(&struct {\n\t\t\t\t*Container\n\t\t\t\tHostConfig *runconfig.HostConfig\n\t\t\t}{container, container.hostConfig})\n\t\t\tif err != nil {\n\t\t\t\treturn job.Error(err)\n\t\t\t}\n\t\t\tjob.Stdout.Write(b)\n\t\t\treturn engine.StatusOK\n\t\t}\n\n\t\tout := &engine.Env{}\n\t\tout.SetJson(\"Id\", container.ID)\n\t\tout.SetAuto(\"Created\", container.Created)\n\t\tout.SetJson(\"Path\", container.Path)\n\t\tout.SetList(\"Args\", container.Args)\n\t\tout.SetJson(\"Config\", container.Config)\n\t\tout.SetJson(\"State\", container.State)\n\t\tout.Set(\"Image\", container.ImageID)\n\t\tout.SetJson(\"NetworkSettings\", container.NetworkSettings)\n\t\tout.Set(\"ResolvConfPath\", container.ResolvConfPath)\n\t\tout.Set(\"HostnamePath\", container.HostnamePath)\n\t\tout.Set(\"HostsPath\", container.HostsPath)\n\t\tout.SetJson(\"Name\", container.Name)\n\t\tout.SetInt(\"RestartCount\", container.RestartCount)\n\t\tout.Set(\"Driver\", container.Driver)\n\t\tout.Set(\"ExecDriver\", container.ExecDriver)\n\t\tout.Set(\"MountLabel\", container.MountLabel)\n\t\tout.Set(\"ProcessLabel\", container.ProcessLabel)\n\t\tout.SetJson(\"Volumes\", container.Volumes)\n\t\tout.SetJson(\"VolumesRW\", container.VolumesRW)\n\t\tout.SetJson(\"AppArmorProfile\", container.AppArmorProfile)\n\n\t\tout.SetList(\"ExecIDs\", container.GetExecIDs())\n\n\t\tif children, err := daemon.Children(container.Name); err == nil {\n\t\t\tfor linkAlias, child := range children {\n\t\t\t\tcontainer.hostConfig.Links = append(container.hostConfig.Links, fmt.Sprintf(\"%s:%s\", child.Name, linkAlias))\n\t\t\t}\n\t\t}\n\n\t\tout.SetJson(\"HostConfig\", container.hostConfig)\n\n\t\tcheckpoints := make([]*ContainerCheckpoint, 0, len(container.Checkpoints))\n\t\t\/\/ Make checkpoint list with ordering by creation time\n\t\tfor _, checkpoint := range container.Checkpoints {\n\t\t\tcheckpoints = append(checkpoints, checkpoint)\n\t\t\tfor i := len(checkpoints)-1; i > 0; i-- {\n\t\t\t\tif checkpoints[i-1].CreatedAt.Before(checkpoint.CreatedAt) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcheckpoints[i], checkpoints[i-1] = checkpoints[i-1], checkpoint\n\t\t\t}\n\t\t}\n\t\tout.SetJson(\"Checkpoints\", checkpoints)\n\n\t\tcontainer.hostConfig.Links = nil\n\t\tif _, err := out.WriteTo(job.Stdout); err != nil {\n\t\t\treturn job.Error(err)\n\t\t}\n\t\treturn engine.StatusOK\n\t}\n\treturn job.Errorf(\"No such container: %s\", name)\n}\n\nfunc (daemon *Daemon) ContainerExecInspect(job *engine.Job) engine.Status {\n\tif len(job.Args) != 1 {\n\t\treturn job.Errorf(\"usage: %s ID\", job.Name)\n\t}\n\tid := job.Args[0]\n\teConfig, err := daemon.getExecConfig(id)\n\tif err != nil {\n\t\treturn job.Error(err)\n\t}\n\n\tb, err := json.Marshal(*eConfig)\n\tif err != nil {\n\t\treturn job.Error(err)\n\t}\n\tjob.Stdout.Write(b)\n\treturn engine.StatusOK\n}\n<|endoftext|>"}
{"text":"<commit_before>package quic\n\nimport (\n\t\"bytes\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"Public Header\", func() {\n\tIt(\"parses intial client header\", func() {\n\t\tb := bytes.NewReader([]byte{0xd, 0xf6, 0x19, 0x86, 0x66, 0x9b, 0x9f, 0xfa, 0x4c, 0x51, 0x30, 0x33, 0x30, 0x1})\n\t\tpublicHeader, err := ParsePublicHeader(b)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tExpect(publicHeader.VersionFlag).To(BeTrue())\n\t\tExpect(publicHeader.ResetFlag).To(BeFalse())\n\t\tExpect(publicHeader.ConnectionIDLength).To(Equal(uint8(8)))\n\t\tExpect(publicHeader.ConnectionID).ToNot(BeZero())\n\t\tExpect(publicHeader.QuicVersion).To(Equal(uint32(0x51303330)))\n\t\tExpect(publicHeader.PacketNumberLength).To(Equal(uint8(1)))\n\t\tExpect(publicHeader.PacketNumber).To(Equal(uint64(1)))\n\t})\n})\n<commit_msg>improve public header tests<commit_after>package quic\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"Public Header\", func() {\n\tContext(\"when parsing\", func() {\n\t\tIt(\"accepts a sample client header\", func() {\n\t\t\tb := bytes.NewReader([]byte{0x0d, 0xf6, 0x19, 0x86, 0x66, 0x9b, 0x9f, 0xfa, 0x4c, 0x51, 0x30, 0x33, 0x30, 0x01})\n\t\t\tpublicHeader, err := ParsePublicHeader(b)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(publicHeader.VersionFlag).To(BeTrue())\n\t\t\tExpect(publicHeader.ResetFlag).To(BeFalse())\n\t\t\tExpect(publicHeader.ConnectionIDLength).To(Equal(uint8(8)))\n\t\t\tExpect(publicHeader.ConnectionID).To(Equal(uint64(0xf61986669b9ffa4c)))\n\t\t\tExpect(publicHeader.QuicVersion).To(Equal(binary.BigEndian.Uint32([]byte(\"Q030\"))))\n\t\t\tExpect(publicHeader.PacketNumberLength).To(Equal(uint8(1)))\n\t\t\tExpect(publicHeader.PacketNumber).To(Equal(uint64(1)))\n\t\t\tExpect(b.Len()).To(BeZero())\n\t\t})\n\n\t\tIt(\"accepts 4-byte connection IDs\", func() {\n\t\t\tb := bytes.NewReader([]byte{0x08, 0x9b, 0x9f, 0xfa, 0x4c, 0x01})\n\t\t\tpublicHeader, err := ParsePublicHeader(b)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(publicHeader.VersionFlag).To(BeFalse())\n\t\t\tExpect(publicHeader.ConnectionIDLength).To(Equal(uint8(4)))\n\t\t\tExpect(publicHeader.ConnectionID).To(Equal(uint64(0x9b9ffa4c)))\n\t\t\tExpect(b.Len()).To(BeZero())\n\t\t})\n\n\t\tIt(\"accepts 1-byte connection IDs\", func() {\n\t\t\tb := bytes.NewReader([]byte{0x04, 0x4c, 0x01})\n\t\t\tpublicHeader, err := ParsePublicHeader(b)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(publicHeader.VersionFlag).To(BeFalse())\n\t\t\tExpect(publicHeader.ConnectionIDLength).To(Equal(uint8(1)))\n\t\t\tExpect(publicHeader.ConnectionID).To(Equal(uint64(0x4c)))\n\t\t\tExpect(b.Len()).To(BeZero())\n\t\t})\n\n\t\tIt(\"accepts 0-byte connection ID\", func() {\n\t\t\tb := bytes.NewReader([]byte{0x00, 0x01})\n\t\t\tpublicHeader, err := ParsePublicHeader(b)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(publicHeader.VersionFlag).To(BeFalse())\n\t\t\tExpect(publicHeader.ConnectionIDLength).To(Equal(uint8(0)))\n\t\t\tExpect(b.Len()).To(BeZero())\n\t\t})\n\n\t\tIt(\"accepts 2-byte packet numbers\", func() {\n\t\t\tb := bytes.NewReader([]byte{0x10, 0xde, 0xca})\n\t\t\tpublicHeader, err := ParsePublicHeader(b)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(publicHeader.PacketNumberLength).To(Equal(uint8(2)))\n\t\t\tExpect(publicHeader.PacketNumber).To(Equal(uint64(0xdeca)))\n\t\t\tExpect(b.Len()).To(BeZero())\n\t\t})\n\n\t\tIt(\"accepts 4-byte packet numbers\", func() {\n\t\t\tb := bytes.NewReader([]byte{0x20, 0xde, 0xca, 0xfb, 0xad})\n\t\t\tpublicHeader, err := ParsePublicHeader(b)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(publicHeader.PacketNumberLength).To(Equal(uint8(4)))\n\t\t\tExpect(publicHeader.PacketNumber).To(Equal(uint64(0xdecafbad)))\n\t\t\tExpect(b.Len()).To(BeZero())\n\t\t})\n\n\t\tIt(\"accepts 6-byte packet numbers\", func() {\n\t\t\tb := bytes.NewReader([]byte{0x30, 0xde, 0xca, 0xfb, 0xad, 0x42, 0x23})\n\t\t\tpublicHeader, err := ParsePublicHeader(b)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(publicHeader.PacketNumberLength).To(Equal(uint8(6)))\n\t\t\tExpect(publicHeader.PacketNumber).To(Equal(uint64(0xdecafbad4223)))\n\t\t\tExpect(b.Len()).To(BeZero())\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The JoeFriday authors.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package mem gets and processes \/proc\/meminfo, returning the data in the\n\/\/ appropriate format.\npackage mem\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n\n\tfb \"github.com\/google\/flatbuffers\/go\"\n\tjoe \"github.com\/mohae\/joefriday\"\n)\n\ntype Info struct {\n\tTimestamp    int64\n\tMemTotal     int\n\tMemFree      int\n\tMemAvailable int\n\tBuffers      int\n\tCached       int\n\tSwapCached   int\n\tActive       int\n\tInactive     int\n\tSwapTotal    int\n\tSwapFree     int\n}\n\n\/\/ Serialize serializes the Info using flatbuffers.\nfunc (i *Info) Serialize() []byte {\n\tbuilder := fb.NewBuilder(0)\n\tDataStart(builder)\n\tDataAddTimestamp(builder, int64(i.Timestamp))\n\tDataAddMemTotal(builder, int64(i.MemTotal))\n\tDataAddMemFree(builder, int64(i.MemFree))\n\tDataAddMemAvailable(builder, int64(i.MemAvailable))\n\tDataAddBuffers(builder, int64(i.Buffers))\n\tDataAddCached(builder, int64(i.Cached))\n\tDataAddSwapCached(builder, int64(i.SwapCached))\n\tDataAddActive(builder, int64(i.Active))\n\tDataAddInactive(builder, int64(i.Inactive))\n\tDataAddSwapTotal(builder, int64(i.SwapTotal))\n\tDataAddSwapFree(builder, int64(i.SwapFree))\n\tbuilder.Finish(DataEnd(builder))\n\treturn builder.Bytes[builder.Head():]\n}\n\n\/\/ Deserialize deserializes bytes representing flatbuffers serialized Data\n\/\/ into *Info.  If the bytes are not from flatbuffers serialization of\n\/\/ Data, it is a programmer error and a panic will occur.\nfunc Deserialize(p []byte) *Info {\n\tdata := GetRootAsData(p, 0)\n\tinfo := &Info{}\n\tinfo.Timestamp = data.Timestamp()\n\tinfo.MemTotal = int(data.MemTotal())\n\tinfo.MemFree = int(data.MemFree())\n\tinfo.MemAvailable = int(data.MemAvailable())\n\tinfo.Buffers = int(data.Buffers())\n\tinfo.Cached = int(data.Cached())\n\tinfo.SwapCached = int(data.SwapCached())\n\tinfo.Active = int(data.Active())\n\tinfo.Inactive = int(data.Inactive())\n\tinfo.SwapTotal = int(data.SwapTotal())\n\tinfo.SwapFree = int(data.SwapFree())\n\treturn info\n}\n\n\/\/ GetInfo returns some of the results of \/proc\/meminfo.\nfunc GetInfo() (*Info, error) {\n\tvar l, i int\n\tvar name string\n\tvar err error\n\tvar v byte\n\tt := time.Now().UTC().UnixNano()\n\tf, err := os.Open(\"\/proc\/meminfo\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tbuf := bufio.NewReader(f)\n\tinf := &Info{Timestamp: t}\n\tvar pos int\n\tline := make([]byte, 0, 50)\n\tval := make([]byte, 0, 32)\n\tfor {\n\t\tif l == 16 {\n\t\t\tbreak\n\t\t}\n\t\tline, err = buf.ReadSlice('\\n')\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"error reading output bytes: %s\", err)\n\t\t}\n\t\tl++\n\t\tif l > 8 && l < 15 {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ first grab the key name (everything up to the ':')\n\t\tfor i, v = range line {\n\t\t\tif v == 0x3A {\n\t\t\t\tpos = i + 1\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tval = append(val, v)\n\t\t}\n\t\tname = string(val[:])\n\t\tval = val[:0]\n\t\t\/\/ skip all spaces\n\t\tfor i, v = range line[pos:] {\n\t\t\tif v != 0x20 {\n\t\t\t\tpos += i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t\/\/ grab the numbers\n\t\tfor _, v = range line[pos:] {\n\t\t\tif v == 0x20 || v == '\\r' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tval = append(val, v)\n\t\t}\n\t\t\/\/ any conversion error results in 0\n\t\ti, err = strconv.Atoi(string(val[:]))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%s: %s\", name, err)\n\t\t}\n\t\tval = val[:0]\n\t\tif name == \"MemTotal\" {\n\t\t\tinf.MemTotal = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"MemFree\" {\n\t\t\tinf.MemFree = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"MemAvailable\" {\n\t\t\tinf.MemAvailable = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"Buffers\" {\n\t\t\tinf.Buffers = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"Cached\" {\n\t\t\tinf.MemAvailable = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"SwapCached\" {\n\t\t\tinf.SwapCached = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"Active\" {\n\t\t\tinf.Active = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"Inactive\" {\n\t\t\tinf.Inactive = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"SwapTotal\" {\n\t\t\tinf.SwapTotal = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"SwapFree\" {\n\t\t\tinf.SwapFree = i\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn inf, nil\n}\n\n\/\/ GetData returns the current meminfo as flatbuffer serialized bytes.\nfunc GetData() ([]byte, error) {\n\tinf, err := GetInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn inf.Serialize(), nil\n}\n\n\/\/ DataTicker gathers the meminfo on a ticker, whose interval is defined by\n\/\/ the received duration, and sends the results to the channel.  The output\n\/\/ is Flatbuffers serialized Data.  Any error encountered during processing\n\/\/ is sent to the error channel.  Processing will continue\n\/\/\n\/\/ Either closing the done channel or sending struct{} to the done channel\n\/\/ will result in function exit.  The out channel is closed on exit.\n\/\/\n\/\/ This pre-allocates the builder and everything other than the []byte that\n\/\/ gets sent to the out channel to reduce allocations, as this is expected\n\/\/ to be both a frequent and a long-running process.  Doing so reduces\n\/\/ byte allocations per tick just ~ 42%.\nfunc DataTicker(interval time.Duration, outCh chan []byte, done chan struct{}, errCh chan error) {\n\tticker := time.NewTicker(interval)\n\tdefer ticker.Stop()\n\tdefer close(outCh)\n\t\/\/ predeclare some vars\n\tvar l, i, pos int\n\tvar t int64\n\tvar v byte\n\tvar name string\n\t\/\/ premake some temp slices\n\tline := make([]byte, 0, 64)\n\tval := make([]byte, 0, 32)\n\t\/\/ just reset the bldr at the end of every ticker\n\tbldr := fb.NewBuilder(0)\n\tvar buf bufio.Reader\n\t\/\/ ticker\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\td, _ := ioutil.ReadFile(\"\/proc\/meminfo\")\n\t\t\tfmt.Println(string(d))\n\t\t\t\/\/ The current timestamp is always in UTC\n\t\t\tt = time.Now().UTC().UnixNano()\n\t\t\tf, err := os.Open(\"\/proc\/meminfo\")\n\t\t\tif err != nil {\n\t\t\t\terrCh <- joe.Error{Type: \"mem\", Op: \"open \/proc\/meminfo\", Err: err}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbuf.Reset(f)\n\t\t\tDataStart(bldr)\n\t\t\tDataAddTimestamp(bldr, t)\n\t\t\tfor {\n\t\t\t\tif l == 16 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfmt.Println(l)\n\t\t\t\tline, _, err = buf.ReadLine()\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == io.EOF {\n\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\terrCh <- joe.Error{Type: \"mem\", Op: \"read command results\", Err: err}\n\t\t\t\t\tfmt.Println(line)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfmt.Println(line)\n\t\t\t\tl++\n\t\t\t\tif l > 8 && l < 15 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t\/\/ first grab the key name (everything up to the ':')\n\t\t\t\tfor i, v = range line {\n\t\t\t\t\tif v == 0x3A {\n\t\t\t\t\t\tpos = i + 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tval = append(val, v)\n\t\t\t\t}\n\t\t\t\tname = string(val[:])\n\t\t\t\tval = val[:0]\n\t\t\t\t\/\/ skip all spaces\n\t\t\t\tfor i, v = range line[pos:] {\n\t\t\t\t\tif v != 0x20 {\n\t\t\t\t\t\tpos += i\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ grab the numbers\n\t\t\t\tfor _, v = range line[pos:] {\n\t\t\t\t\tif v == 0x20 || v == '\\r' {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tval = append(val, v)\n\t\t\t\t}\n\t\t\t\t\/\/ any conversion error results in 0\n\t\t\t\ti, err = strconv.Atoi(string(val[:]))\n\t\t\t\tif err != nil {\n\t\t\t\t\terrCh <- joe.Error{Type: \"mem\", Op: \"convert to int\", Err: err}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tval = val[:0]\n\t\t\t\tif name == \"MemTotal\" {\n\t\t\t\t\tDataAddMemTotal(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"MemFree\" {\n\t\t\t\t\tDataAddMemFree(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"MemAvailable\" {\n\t\t\t\t\tDataAddMemAvailable(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"Buffers\" {\n\t\t\t\t\tDataAddBuffers(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"Cached\" {\n\t\t\t\t\tDataAddMemAvailable(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"SwapCached\" {\n\t\t\t\t\tDataAddSwapCached(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"Active\" {\n\t\t\t\t\tDataAddActive(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"Inactive\" {\n\t\t\t\t\tDataAddInactive(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"SwapTotal\" {\n\t\t\t\t\tDataAddSwapTotal(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"SwapFree\" {\n\t\t\t\t\tDataAddSwapFree(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tf.Close()\n\t\t\tbldr.Finish(DataEnd(bldr))\n\t\t\tdata := bldr.Bytes[bldr.Head():]\n\t\t\toutCh <- data\n\t\t\tbldr.Reset()\n\t\t\tfmt.Println(\"meminfo\")\n\t\t\ttime.Sleep(time.Second)\n\t\t\tl = 0\n\t\t}\n\t}\n}\n\nfunc (d *Data) String() string {\n\treturn fmt.Sprintf(\"Timestamp: %v\\nMemTotal:\\t%d\\tMemFree:\\t%d\\tMemAvailable:\\t%d\\tActive:\\t%d\\tInactive:\\t%d\\nCached:\\t\\t%d\\tBuffers\\t:%d\\nSwapTotal:\\t%d\\tSwapCached:\\t%d\\tSwapFree:\\t%d\\n\", time.Unix(0, d.Timestamp()).UTC(), d.MemTotal(), d.MemFree(), d.MemAvailable(), d.Active(), d.Inactive(), d.Cached(), d.Buffers(), d.SwapTotal(), d.SwapCached(), d.SwapFree())\n}\n<commit_msg>add Stringer implementation to mem.Info<commit_after>\/\/ Copyright 2016 The JoeFriday authors.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package mem gets and processes \/proc\/meminfo, returning the data in the\n\/\/ appropriate format.\npackage mem\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n\n\tfb \"github.com\/google\/flatbuffers\/go\"\n\tjoe \"github.com\/mohae\/joefriday\"\n)\n\ntype Info struct {\n\tTimestamp    int64\n\tMemTotal     int\n\tMemFree      int\n\tMemAvailable int\n\tBuffers      int\n\tCached       int\n\tSwapCached   int\n\tActive       int\n\tInactive     int\n\tSwapTotal    int\n\tSwapFree     int\n}\n\n\/\/ Serialize serializes the Info using flatbuffers.\nfunc (i *Info) Serialize() []byte {\n\tbuilder := fb.NewBuilder(0)\n\tDataStart(builder)\n\tDataAddTimestamp(builder, int64(i.Timestamp))\n\tDataAddMemTotal(builder, int64(i.MemTotal))\n\tDataAddMemFree(builder, int64(i.MemFree))\n\tDataAddMemAvailable(builder, int64(i.MemAvailable))\n\tDataAddBuffers(builder, int64(i.Buffers))\n\tDataAddCached(builder, int64(i.Cached))\n\tDataAddSwapCached(builder, int64(i.SwapCached))\n\tDataAddActive(builder, int64(i.Active))\n\tDataAddInactive(builder, int64(i.Inactive))\n\tDataAddSwapTotal(builder, int64(i.SwapTotal))\n\tDataAddSwapFree(builder, int64(i.SwapFree))\n\tbuilder.Finish(DataEnd(builder))\n\treturn builder.Bytes[builder.Head():]\n}\n\n\/\/ Deserialize deserializes bytes representing flatbuffers serialized Data\n\/\/ into *Info.  If the bytes are not from flatbuffers serialization of\n\/\/ Data, it is a programmer error and a panic will occur.\nfunc Deserialize(p []byte) *Info {\n\tdata := GetRootAsData(p, 0)\n\tinfo := &Info{}\n\tinfo.Timestamp = data.Timestamp()\n\tinfo.MemTotal = int(data.MemTotal())\n\tinfo.MemFree = int(data.MemFree())\n\tinfo.MemAvailable = int(data.MemAvailable())\n\tinfo.Buffers = int(data.Buffers())\n\tinfo.Cached = int(data.Cached())\n\tinfo.SwapCached = int(data.SwapCached())\n\tinfo.Active = int(data.Active())\n\tinfo.Inactive = int(data.Inactive())\n\tinfo.SwapTotal = int(data.SwapTotal())\n\tinfo.SwapFree = int(data.SwapFree())\n\treturn info\n}\n\nfunc (d *Info) String() string {\n\treturn fmt.Sprintf(\"Timestamp: %v\\nMemTotal:\\t%d\\tMemFree:\\t%d\\tMemAvailable:\\t%d\\tActive:\\t%d\\tInactive:\\t%d\\nCached:\\t\\t%d\\tBuffers\\t:%d\\nSwapTotal:\\t%d\\tSwapCached:\\t%d\\tSwapFree:\\t%d\\n\", time.Unix(0, d.Timestamp).UTC(), d.MemTotal, d.MemFree, d.MemAvailable, d.Active, d.Inactive, d.Cached, d.Buffers, d.SwapTotal, d.SwapCached, d.SwapFree)\n}\n\n\/\/ GetInfo returns some of the results of \/proc\/meminfo.\nfunc GetInfo() (*Info, error) {\n\tvar l, i int\n\tvar name string\n\tvar err error\n\tvar v byte\n\tt := time.Now().UTC().UnixNano()\n\tf, err := os.Open(\"\/proc\/meminfo\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tbuf := bufio.NewReader(f)\n\tinf := &Info{Timestamp: t}\n\tvar pos int\n\tline := make([]byte, 0, 50)\n\tval := make([]byte, 0, 32)\n\tfor {\n\t\tif l == 16 {\n\t\t\tbreak\n\t\t}\n\t\tline, err = buf.ReadSlice('\\n')\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"error reading output bytes: %s\", err)\n\t\t}\n\t\tl++\n\t\tif l > 8 && l < 15 {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ first grab the key name (everything up to the ':')\n\t\tfor i, v = range line {\n\t\t\tif v == 0x3A {\n\t\t\t\tpos = i + 1\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tval = append(val, v)\n\t\t}\n\t\tname = string(val[:])\n\t\tval = val[:0]\n\t\t\/\/ skip all spaces\n\t\tfor i, v = range line[pos:] {\n\t\t\tif v != 0x20 {\n\t\t\t\tpos += i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t\/\/ grab the numbers\n\t\tfor _, v = range line[pos:] {\n\t\t\tif v == 0x20 || v == '\\r' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tval = append(val, v)\n\t\t}\n\t\t\/\/ any conversion error results in 0\n\t\ti, err = strconv.Atoi(string(val[:]))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%s: %s\", name, err)\n\t\t}\n\t\tval = val[:0]\n\t\tif name == \"MemTotal\" {\n\t\t\tinf.MemTotal = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"MemFree\" {\n\t\t\tinf.MemFree = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"MemAvailable\" {\n\t\t\tinf.MemAvailable = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"Buffers\" {\n\t\t\tinf.Buffers = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"Cached\" {\n\t\t\tinf.MemAvailable = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"SwapCached\" {\n\t\t\tinf.SwapCached = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"Active\" {\n\t\t\tinf.Active = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"Inactive\" {\n\t\t\tinf.Inactive = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"SwapTotal\" {\n\t\t\tinf.SwapTotal = i\n\t\t\tcontinue\n\t\t}\n\t\tif name == \"SwapFree\" {\n\t\t\tinf.SwapFree = i\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn inf, nil\n}\n\n\/\/ GetData returns the current meminfo as flatbuffer serialized bytes.\nfunc GetData() ([]byte, error) {\n\tinf, err := GetInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn inf.Serialize(), nil\n}\n\n\/\/ DataTicker gathers the meminfo on a ticker, whose interval is defined by\n\/\/ the received duration, and sends the results to the channel.  The output\n\/\/ is Flatbuffers serialized Data.  Any error encountered during processing\n\/\/ is sent to the error channel.  Processing will continue\n\/\/\n\/\/ Either closing the done channel or sending struct{} to the done channel\n\/\/ will result in function exit.  The out channel is closed on exit.\n\/\/\n\/\/ This pre-allocates the builder and everything other than the []byte that\n\/\/ gets sent to the out channel to reduce allocations, as this is expected\n\/\/ to be both a frequent and a long-running process.  Doing so reduces\n\/\/ byte allocations per tick just ~ 42%.\nfunc DataTicker(interval time.Duration, outCh chan []byte, done chan struct{}, errCh chan error) {\n\tticker := time.NewTicker(interval)\n\tdefer ticker.Stop()\n\tdefer close(outCh)\n\t\/\/ predeclare some vars\n\tvar l, i, pos int\n\tvar t int64\n\tvar v byte\n\tvar name string\n\t\/\/ premake some temp slices\n\tline := make([]byte, 0, 64)\n\tval := make([]byte, 0, 32)\n\t\/\/ just reset the bldr at the end of every ticker\n\tbldr := fb.NewBuilder(0)\n\tvar buf bufio.Reader\n\t\/\/ ticker\n\tfor {\n\t\tselect {\n\t\tcase <-done:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\td, _ := ioutil.ReadFile(\"\/proc\/meminfo\")\n\t\t\tfmt.Println(string(d))\n\t\t\t\/\/ The current timestamp is always in UTC\n\t\t\tt = time.Now().UTC().UnixNano()\n\t\t\tf, err := os.Open(\"\/proc\/meminfo\")\n\t\t\tif err != nil {\n\t\t\t\terrCh <- joe.Error{Type: \"mem\", Op: \"open \/proc\/meminfo\", Err: err}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbuf.Reset(f)\n\t\t\tDataStart(bldr)\n\t\t\tDataAddTimestamp(bldr, t)\n\t\t\tfor {\n\t\t\t\tif l == 16 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfmt.Println(l)\n\t\t\t\tline, _, err = buf.ReadLine()\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == io.EOF {\n\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\terrCh <- joe.Error{Type: \"mem\", Op: \"read command results\", Err: err}\n\t\t\t\t\tfmt.Println(line)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfmt.Println(line)\n\t\t\t\tl++\n\t\t\t\tif l > 8 && l < 15 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t\/\/ first grab the key name (everything up to the ':')\n\t\t\t\tfor i, v = range line {\n\t\t\t\t\tif v == 0x3A {\n\t\t\t\t\t\tpos = i + 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tval = append(val, v)\n\t\t\t\t}\n\t\t\t\tname = string(val[:])\n\t\t\t\tval = val[:0]\n\t\t\t\t\/\/ skip all spaces\n\t\t\t\tfor i, v = range line[pos:] {\n\t\t\t\t\tif v != 0x20 {\n\t\t\t\t\t\tpos += i\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ grab the numbers\n\t\t\t\tfor _, v = range line[pos:] {\n\t\t\t\t\tif v == 0x20 || v == '\\r' {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tval = append(val, v)\n\t\t\t\t}\n\t\t\t\t\/\/ any conversion error results in 0\n\t\t\t\ti, err = strconv.Atoi(string(val[:]))\n\t\t\t\tif err != nil {\n\t\t\t\t\terrCh <- joe.Error{Type: \"mem\", Op: \"convert to int\", Err: err}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tval = val[:0]\n\t\t\t\tif name == \"MemTotal\" {\n\t\t\t\t\tDataAddMemTotal(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"MemFree\" {\n\t\t\t\t\tDataAddMemFree(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"MemAvailable\" {\n\t\t\t\t\tDataAddMemAvailable(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"Buffers\" {\n\t\t\t\t\tDataAddBuffers(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"Cached\" {\n\t\t\t\t\tDataAddMemAvailable(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"SwapCached\" {\n\t\t\t\t\tDataAddSwapCached(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"Active\" {\n\t\t\t\t\tDataAddActive(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"Inactive\" {\n\t\t\t\t\tDataAddInactive(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"SwapTotal\" {\n\t\t\t\t\tDataAddSwapTotal(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif name == \"SwapFree\" {\n\t\t\t\t\tDataAddSwapFree(bldr, int64(i))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tf.Close()\n\t\t\tbldr.Finish(DataEnd(bldr))\n\t\t\tdata := bldr.Bytes[bldr.Head():]\n\t\t\toutCh <- data\n\t\t\tbldr.Reset()\n\t\t\tfmt.Println(\"meminfo\")\n\t\t\ttime.Sleep(time.Second)\n\t\t\tl = 0\n\t\t}\n\t}\n}\n\nfunc (d *Data) String() string {\n\treturn fmt.Sprintf(\"Timestamp: %v\\nMemTotal:\\t%d\\tMemFree:\\t%d\\tMemAvailable:\\t%d\\tActive:\\t%d\\tInactive:\\t%d\\nCached:\\t\\t%d\\tBuffers\\t:%d\\nSwapTotal:\\t%d\\tSwapCached:\\t%d\\tSwapFree:\\t%d\\n\", time.Unix(0, d.Timestamp()).UTC(), d.MemTotal(), d.MemFree(), d.MemAvailable(), d.Active(), d.Inactive(), d.Cached(), d.Buffers(), d.SwapTotal(), d.SwapCached(), d.SwapFree())\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"reflect\"\n\n\t\"github.com\/STNS\/STNS\/attribute\"\n\t\"github.com\/STNS\/STNS\/config\"\n\t\"github.com\/ant0ine\/go-json-rest\/rest\"\n)\n\ntype Query struct {\n\tresource string\n\tcolumn   string\n}\n\nfunc (q Query) Get(value string) attribute.UserGroups {\n\tvar attr attribute.UserGroups\n\tvar resource attribute.UserGroups\n\n\tif q.resource == \"user\" {\n\t\tresource = config.All.Users\n\t} else if q.resource == \"group\" {\n\t\tresource = config.All.Groups\n\t}\n\tif q.column == \"id\" {\n\t\tattr = resource.GetById(value)\n\t} else if q.column == \"name\" {\n\t\tattr = resource.GetByName(value)\n\t} else if q.column == \"list\" {\n\t\tattr = resource\n\t}\n\treturn attr\n}\n\nfunc Get(w rest.ResponseWriter, r *rest.Request) {\n\tvalue := r.PathParam(\"value\")\n\tcolumn := r.PathParam(\"column\")\n\tresource_name := r.PathParam(\"resource_name\")\n\tquery := Query{resource_name, column}\n\n\tattr := query.Get(value)\n\tif attr == nil || reflect.ValueOf(attr).IsNil() {\n\t\trest.NotFound(w, r)\n\t\treturn\n\t}\n\tw.WriteJson(attr)\n}\nfunc GetList(w rest.ResponseWriter, r *rest.Request) {\n\tresource_name := r.PathParam(\"resource_name\")\n\n\tquery := Query{resource_name, \"list\"}\n\tresource := query.Get(\"\")\n\n\tif resource == nil || reflect.ValueOf(resource).IsNil() {\n\t\trest.NotFound(w, r)\n\t\treturn\n\t}\n\n\tw.WriteJson(resource)\n}\n\nfunc HealthChech(w rest.ResponseWriter, r *rest.Request) {\n\tw.WriteJson(\"success\")\n}\n<commit_msg>refact api<commit_after>package api\n\nimport (\n\t\"reflect\"\n\n\t\"github.com\/STNS\/STNS\/attribute\"\n\t\"github.com\/STNS\/STNS\/config\"\n\t\"github.com\/ant0ine\/go-json-rest\/rest\"\n)\n\ntype Query struct {\n\tresource string\n\tcolumn   string\n\tvalue    string\n}\n\nfunc (q Query) Get(value string) attribute.UserGroups {\n\tvar attr attribute.UserGroups\n\tvar resource attribute.UserGroups\n\n\tif q.resource == \"user\" {\n\t\tresource = config.All.Users\n\t} else if q.resource == \"group\" {\n\t\tresource = config.All.Groups\n\t}\n\tif q.column == \"id\" {\n\t\tattr = resource.GetById(q.value)\n\t} else if q.column == \"name\" {\n\t\tattr = resource.GetByName(q.value)\n\t} else if q.column == \"list\" {\n\t\tattr = resource\n\t}\n\treturn attr\n}\n\nfunc Get(w rest.ResponseWriter, r *rest.Request) {\n\tvalue := r.PathParam(\"value\")\n\tcolumn := r.PathParam(\"column\")\n\tresource_name := r.PathParam(\"resource_name\")\n\tquery := Query{resource_name, column, value}\n\tquery.Response(w, r)\n}\nfunc GetList(w rest.ResponseWriter, r *rest.Request) {\n\tresource_name := r.PathParam(\"resource_name\")\n\tquery := Query{resource_name, \"list\", \"\"}\n\tquery.Response(w, r)\n}\n\nfunc (q Query) Response(w rest.ResponseWriter, r *rest.Request) {\n\tresource := query.Get()\n\tif resource == nil || reflect.ValueOf(resource).IsNil() {\n\t\trest.NotFound(w, r)\n\t\treturn\n\t}\n\tw.WriteJson(resource)\n}\n\nfunc HealthChech(w rest.ResponseWriter, r *rest.Request) {\n\tw.WriteJson(\"success\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\n\/\/ TODO: Start documenting the error codes to the frontend.\n\nimport (\n\t\"hnews\/services\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com\/gin-gonic\/gin\"\n)\n\nconst (\n\tdebug = true\n)\n\n\/\/ StartAPI sets up the API and starts it on Heroku port or :8080\nfunc StartAPI() {\n\tr := gin.Default()\n\tif debug {\n\t\tgin.SetMode(gin.DebugMode)\n\t} else {\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\n\t\/\/ GET News from index :from: to index :to:\n\tr.GET(\"\/v1\/news\", func(c *gin.Context) {\n\t\tfrom, err0 := strconv.Atoi(c.Query(\"from\"))\n\t\tto, err1 := strconv.Atoi(c.Query(\"to\"))\n\t\tif err0 != nil || err1 != nil || from <= 0 {\n\t\t\tc.String(http.StatusBadRequest, \"Bad index\")\n\t\t\treturn\n\t\t}\n\n\t\tnews := services.ReadNews(from, to)\n\t\tc.JSON(http.StatusOK, gin.H{\"values\": news})\n\t})\n\n\t\/** Comment Endpoint **\/\n\t\/\/ Gives the comments from a i to j given the provided news id.\n\tr.GET(\"\/v1\/comments\", func(c *gin.Context) {\n\t\tfrom, err0 := strconv.Atoi(c.Query(\"from\"))\n\t\tto, err1 := strconv.Atoi(c.Query(\"to\"))\n\t\tif err0 != nil || err1 != nil || from <= 0 {\n\t\t\tc.String(http.StatusBadRequest, \"Bad index\")\n\t\t\treturn\n\t\t}\n\n\t\tid, err := strconv.Atoi(c.Query(\"newsid\"))\n\t\tif err != nil {\n\t\t\tc.String(http.StatusBadRequest, \"Not a valid item id\")\n\t\t\treturn\n\t\t}\n\n\t\tcomments := services.ReadComments(id, from, to)\n\t\tc.JSON(http.StatusOK, gin.H{\"values\": comments})\n\t})\n\n\t\/** Login wrapper for login-service **\/\n\tr.POST(\"\/v1\/login\", func(c *gin.Context) {\n\t\tusername := c.Query(\"username\")\n\t\tpassword := c.Query(\"password\")\n\n\t\turl := \"http:\/\/localhost:3000\/v1\/login\"\n\t\treq, _ := http.NewRequest(\"POST\", url, nil)\n\n\t\tvalues := req.URL.Query()\n\t\tvalues.Add(\"username\", username)\n\t\tvalues.Add(\"password\", password)\n\t\treq.URL.RawQuery = values.Encode()\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tcontent, _ := ioutil.ReadAll(resp.Body)\n\t\t\tc.String(resp.StatusCode, string(content))\n\t\t}\n\t})\n\n\t\/** Entry wrapper for login-service **\/\n\tr.POST(\"\/v1\/login\/entry\/upvote\", func(c *gin.Context) {\n\t\tid := c.Query(\"id\")\n\t\tapikey := c.Query(\"apikey\")\n\n\t\turl := \"http:\/\/localhost:3000\/v1\/login\/entry\/upvote\"\n\t\treq, _ := http.NewRequest(\"POST\", url, nil)\n\n\t\tvalues := req.URL.Query()\n\t\tvalues.Add(\"id\", id)\n\t\tvalues.Add(\"apikey\", apikey)\n\t\treq.URL.RawQuery = values.Encode()\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tcontent, _ := ioutil.ReadAll(resp.Body)\n\t\t\tc.String(resp.StatusCode, string(content))\n\t\t}\n\t})\n\n\tr.POST(\"\/v1\/login\/entry\/comment\", func(c *gin.Context) {\n\t\tid := c.Query(\"id\")\n\t\tcomment := c.Query(\"comment\")\n\t\tapikey := c.Query(\"apikey\")\n\n\t\turl := \"http:\/\/localhost:3000\/v1\/login\/entry\/comment\"\n\t\treq, _ := http.NewRequest(\"POST\", url, nil)\n\n\t\tvalues := req.URL.Query()\n\t\tvalues.Add(\"id\", id)\n\t\tvalues.Add(\"comment\", comment)\n\t\tvalues.Add(\"apikey\", apikey)\n\t\treq.URL.RawQuery = values.Encode()\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tcontent, _ := ioutil.ReadAll(resp.Body)\n\t\t\tc.String(resp.StatusCode, string(content))\n\t\t}\n\t})\n\n\t\/** Comment wrapper for login-service **\/\n\tr.POST(\"\/v1\/login\/comment\/upvote\", func(c *gin.Context) {\n\t\tid := c.Query(\"id\")\n\t\tapikey := c.Query(\"apikey\")\n\n\t\turl := \"http:\/\/localhost:3000\/v1\/login\/comment\/upvote\"\n\t\treq, _ := http.NewRequest(\"POST\", url, nil)\n\n\t\tvalues := req.URL.Query()\n\t\tvalues.Add(\"id\", id)\n\t\tvalues.Add(\"apikey\", apikey)\n\t\treq.URL.RawQuery = values.Encode()\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tcontent, _ := ioutil.ReadAll(resp.Body)\n\t\t\tc.String(resp.StatusCode, string(content))\n\t\t}\n\t})\n\n\tr.POST(\"\/v1\/login\/commment\/reply\", func(c *gin.Context) {\n\t\tid := c.Query(\"id\")\n\t\treply := c.Query(\"reply\")\n\t\tapikey := c.Query(\"apikey\")\n\n\t\turl := \"http:\/\/localhost:3000\/v1\/login\/comment\/reply\"\n\t\treq, _ := http.NewRequest(\"POST\", url, nil)\n\n\t\tvalues := req.URL.Query()\n\t\tvalues.Add(\"id\", id)\n\t\tvalues.Add(\"reply\", reply)\n\t\tvalues.Add(\"apikey\", apikey)\n\t\treq.URL.RawQuery = values.Encode()\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tcontent, _ := ioutil.ReadAll(resp.Body)\n\t\t\tc.String(resp.StatusCode, string(content))\n\t\t}\n\t})\n\n\tr.Run(\":\" + getPort()) \/\/ listen and serve on 0.0.0.0:8080\n}\n\n\/\/ Tries to get Heroku port otherwise return default 8080\nfunc getPort() string {\n\tport := os.Getenv(\"PORT\")\n\tlog.Println(port)\n\tif port != \"\" {\n\t\treturn port\n\t}\n\treturn \"8080\"\n}\n<commit_msg>Changed login to return JSON, not string.<commit_after>package api\n\n\/\/ TODO: Start documenting the error codes to the frontend.\n\/\/ TODO: Disable debug mode in Gin\n\/\/ TODO: Disable debug mode in Sinatra\n\nimport (\n\t\"hnews\/services\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com\/gin-gonic\/gin\"\n)\n\nconst (\n\tdebug = true\n)\n\n\/\/ StartAPI sets up the API and starts it on Heroku port or :8080\nfunc StartAPI() {\n\tr := gin.Default()\n\tif debug {\n\t\tgin.SetMode(gin.DebugMode)\n\t} else {\n\t\tgin.SetMode(gin.ReleaseMode)\n\t}\n\n\t\/\/ GET News from index :from: to index :to:\n\tr.GET(\"\/v1\/news\", func(c *gin.Context) {\n\t\tfrom, err0 := strconv.Atoi(c.Query(\"from\"))\n\t\tto, err1 := strconv.Atoi(c.Query(\"to\"))\n\t\tif err0 != nil || err1 != nil || from <= 0 {\n\t\t\tc.String(http.StatusBadRequest, \"Bad index\")\n\t\t\treturn\n\t\t}\n\n\t\tnews := services.ReadNews(from, to)\n\t\tc.JSON(http.StatusOK, gin.H{\"values\": news})\n\t})\n\n\t\/** Comment Endpoint **\/\n\t\/\/ Gives the comments from a i to j given the provided news id.\n\tr.GET(\"\/v1\/comments\", func(c *gin.Context) {\n\t\tfrom, err0 := strconv.Atoi(c.Query(\"from\"))\n\t\tto, err1 := strconv.Atoi(c.Query(\"to\"))\n\t\tif err0 != nil || err1 != nil || from <= 0 {\n\t\t\tc.String(http.StatusBadRequest, \"Bad index\")\n\t\t\treturn\n\t\t}\n\n\t\tid, err := strconv.Atoi(c.Query(\"newsid\"))\n\t\tif err != nil {\n\t\t\tc.String(http.StatusBadRequest, \"Not a valid item id\")\n\t\t\treturn\n\t\t}\n\n\t\tcomments := services.ReadComments(id, from, to)\n\t\tc.JSON(http.StatusOK, gin.H{\"values\": comments})\n\t})\n\n\t\/** Login wrapper for login-service **\/\n\tr.POST(\"\/v1\/login\", func(c *gin.Context) {\n\t\tusername := c.Query(\"username\")\n\t\tpassword := c.Query(\"password\")\n\n\t\turl := \"http:\/\/localhost:3000\/v1\/login\"\n\t\treq, _ := http.NewRequest(\"POST\", url, nil)\n\n\t\tvalues := req.URL.Query()\n\t\tvalues.Add(\"username\", username)\n\t\tvalues.Add(\"password\", password)\n\t\treq.URL.RawQuery = values.Encode()\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tcontent, _ := ioutil.ReadAll(resp.Body)\n\t\t\tc.JSON(resp.StatusCode, string(content))\n\t\t}\n\t})\n\n\t\/** Entry wrapper for login-service **\/\n\tr.POST(\"\/v1\/login\/entry\/upvote\", func(c *gin.Context) {\n\t\tid := c.Query(\"id\")\n\t\tapikey := c.Query(\"apikey\")\n\n\t\turl := \"http:\/\/localhost:3000\/v1\/login\/entry\/upvote\"\n\t\treq, _ := http.NewRequest(\"POST\", url, nil)\n\n\t\tvalues := req.URL.Query()\n\t\tvalues.Add(\"id\", id)\n\t\tvalues.Add(\"apikey\", apikey)\n\t\treq.URL.RawQuery = values.Encode()\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tcontent, _ := ioutil.ReadAll(resp.Body)\n\t\t\tc.JSON(resp.StatusCode, string(content))\n\t\t}\n\t})\n\n\tr.POST(\"\/v1\/login\/entry\/comment\", func(c *gin.Context) {\n\t\tid := c.Query(\"id\")\n\t\tcomment := c.Query(\"comment\")\n\t\tapikey := c.Query(\"apikey\")\n\n\t\turl := \"http:\/\/localhost:3000\/v1\/login\/entry\/comment\"\n\t\treq, _ := http.NewRequest(\"POST\", url, nil)\n\n\t\tvalues := req.URL.Query()\n\t\tvalues.Add(\"id\", id)\n\t\tvalues.Add(\"comment\", comment)\n\t\tvalues.Add(\"apikey\", apikey)\n\t\treq.URL.RawQuery = values.Encode()\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tcontent, _ := ioutil.ReadAll(resp.Body)\n\t\t\tc.JSON(resp.StatusCode, string(content))\n\t\t}\n\t})\n\n\t\/** Comment wrapper for login-service **\/\n\tr.POST(\"\/v1\/login\/comment\/upvote\", func(c *gin.Context) {\n\t\tid := c.Query(\"id\")\n\t\tapikey := c.Query(\"apikey\")\n\n\t\turl := \"http:\/\/localhost:3000\/v1\/login\/comment\/upvote\"\n\t\treq, _ := http.NewRequest(\"POST\", url, nil)\n\n\t\tvalues := req.URL.Query()\n\t\tvalues.Add(\"id\", id)\n\t\tvalues.Add(\"apikey\", apikey)\n\t\treq.URL.RawQuery = values.Encode()\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tcontent, _ := ioutil.ReadAll(resp.Body)\n\t\t\tc.JSON(resp.StatusCode, string(content))\n\t\t}\n\t})\n\n\tr.POST(\"\/v1\/login\/commment\/reply\", func(c *gin.Context) {\n\t\tid := c.Query(\"id\")\n\t\treply := c.Query(\"reply\")\n\t\tapikey := c.Query(\"apikey\")\n\n\t\turl := \"http:\/\/localhost:3000\/v1\/login\/comment\/reply\"\n\t\treq, _ := http.NewRequest(\"POST\", url, nil)\n\n\t\tvalues := req.URL.Query()\n\t\tvalues.Add(\"id\", id)\n\t\tvalues.Add(\"reply\", reply)\n\t\tvalues.Add(\"apikey\", apikey)\n\t\treq.URL.RawQuery = values.Encode()\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tcontent, _ := ioutil.ReadAll(resp.Body)\n\t\t\tc.JSON(resp.StatusCode, string(content))\n\t\t}\n\t})\n\n\tr.Run(\":\" + getPort()) \/\/ listen and serve on 0.0.0.0:8080\n}\n\n\/\/ Tries to get Heroku port otherwise return default 8080\nfunc getPort() string {\n\tport := os.Getenv(\"PORT\")\n\tlog.Println(port)\n\tif port != \"\" {\n\t\treturn port\n\t}\n\treturn \"8080\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package cache\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc TestCacheMemory1(t *testing.T) {\n\tConvey(\"cache memory\", t, func() {\n\t\tc := New(Options{\n\t\t\tName:    \"test\",\n\t\t\tAdapter: \"memory\",\n\t\t\tConfig: map[string]interface{}{\n\t\t\t\t\"bytesLimit\": int64(1024), \/\/ 1KB\n\t\t\t},\n\t\t})\n\n\t\tConvey(\"set\", func() {\n\t\t\terr := c.Set(\"test\", \"1\", 6)\n\t\t\tSo(err, ShouldBeNil)\n\t\t})\n\n\t\tConvey(\"get\", func() {\n\t\t\tv := c.Get(\"test\")\n\t\t\tSo(v, ShouldEqual, \"1\")\n\t\t})\n\n\t\tConvey(\"gc\", func() {\n\t\t\tfor i := 0; i <= 100; i++ {\n\t\t\t\tkey := \"test\" + strconv.Itoa(i)\n\t\t\t\terr := c.Set(key, i, 6)\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t}\n\t\t\tv := c.Get(\"test100\")\n\t\t\tSo(v, ShouldEqual, 100)\n\t\t\tv = c.Get(\"test1\")\n\t\t\tSo(v, ShouldBeNil)\n\t\t})\n\t})\n}\n<commit_msg>add benchmark test<commit_after>package cache\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"testing\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\n\/\/ init a global cacher\nvar testCache Cacher\n\nfunc TestCacheMemory1(t *testing.T) {\n\tConvey(\"cache memory\", t, func() {\n\t\tc := New(Options{\n\t\t\tName:    \"test2\",\n\t\t\tAdapter: \"memory\",\n\t\t\tConfig: map[string]interface{}{\n\t\t\t\t\"bytesLimit\": int64(1024), \/\/ 1KB\n\t\t\t},\n\t\t})\n\n\t\tConvey(\"set\", func() {\n\t\t\terr := c.Set(\"test\", \"1\", 6)\n\t\t\tSo(err, ShouldBeNil)\n\t\t})\n\n\t\tConvey(\"get\", func() {\n\t\t\tv := c.Get(\"test\")\n\t\t\tSo(v, ShouldEqual, \"1\")\n\t\t})\n\n\t\tConvey(\"gc\", func() {\n\t\t\tfor i := 0; i <= 100; i++ {\n\t\t\t\tkey := \"test\" + strconv.Itoa(i)\n\t\t\t\terr := c.Set(key, i, 6)\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t}\n\t\t\tv := c.Get(\"test100\")\n\t\t\tSo(v, ShouldEqual, 100)\n\t\t\tv = c.Get(\"test1\")\n\t\t\tSo(v, ShouldBeNil)\n\t\t})\n\t})\n}\n\nfunc BenchmarkCacheMemorySet(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\ttestCache.Set(fmt.Sprintf(\"test%d\", i), 1, 1800)\n\t}\n}\n\nfunc BenchmarkCacheMemoryGet(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\ttestCache.Get(fmt.Sprintf(\"test%d\", i))\n\t}\n}\n\nfunc init() {\n\ttestCache = New(Options{\n\t\tName:    \"test\",\n\t\tAdapter: \"memory\",\n\t\tConfig: map[string]interface{}{\n\t\t\t\"bytesLimit\": int64(1024 * 1024), \/\/ 1MB\n\t\t},\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package api provide the server side Goed API\n\/\/ via RPC over local socket.\n\/\/ See client\/ for the client implementation.\npackage api\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/rpc\"\n\t\"time\"\n\n\t\"github.com\/tcolar\/goed\/actions\"\n\t\"github.com\/tcolar\/goed\/core\"\n)\n\ntype Api struct {\n}\n\nfunc (a *Api) Start() {\n\tr := new(GoedRpc)\n\trpc.Register(r)\n\trpc.HandleHTTP()\n\tl, err := net.Listen(\"unix\", core.Socket)\n\tif err != nil {\n\t\tlog.Fatalf(\"Socket listen error %s : \\n\", core.Socket, err.Error())\n\t}\n\n\tgo func() {\n\t\terr = http.Serve(l, nil)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n}\n\n\/\/ Goed RPC functions holder\ntype GoedRpc struct{}\n\ntype RpcStruct struct {\n\tData []string\n}\n\nfunc (r *GoedRpc) Action(args RpcStruct, res *RpcStruct) error {\n\tresults, err := actions.Exec(args.Data[0], args.Data[1:])\n\tfor _, r := range results {\n\t\tres.Data = append(res.Data, r)\n\t}\n\treturn err\n}\n\nfunc (r *GoedRpc) Open(args []interface{}, _ *struct{}) error {\n\tvid := actions.Ar.EdOpen(args[1].(string), -1, args[0].(string), true)\n\tactions.Ar.EdActivateView(vid)\n\tactions.Ar.EdRender()\n\treturn nil\n}\n\nfunc (r *GoedRpc) Edit(args []interface{}, _ *struct{}) error {\n\tcurView := actions.Ar.EdCurView()\n\tvid := actions.Ar.EdOpen(args[1].(string), -1, args[0].(string), true)\n\tactions.Ar.EdActivateView(vid)\n\tactions.Ar.EdRender()\n\t\/\/ Wait til file closed\n\tfor {\n\t\tv := core.Ed.ViewById(vid)\n\t\tif v.Terminated() {\n\t\t\tactions.Ar.EdActivateView(curView)\n\t\t\tactions.Ar.EdRender()\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(250 * time.Millisecond)\n\t}\n}\n<commit_msg>Fix edit action<commit_after>\/\/ Package api provide the server side Goed API\n\/\/ via RPC over local socket.\n\/\/ See client\/ for the client implementation.\npackage api\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/rpc\"\n\t\"time\"\n\n\t\"github.com\/tcolar\/goed\/actions\"\n\t\"github.com\/tcolar\/goed\/core\"\n)\n\ntype Api struct {\n}\n\nfunc (a *Api) Start() {\n\tr := new(GoedRpc)\n\trpc.Register(r)\n\trpc.HandleHTTP()\n\tl, err := net.Listen(\"unix\", core.Socket)\n\tif err != nil {\n\t\tlog.Fatalf(\"Socket listen error %s : \\n\", core.Socket, err.Error())\n\t}\n\n\tgo func() {\n\t\terr = http.Serve(l, nil)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n}\n\n\/\/ Goed RPC functions holder\ntype GoedRpc struct{}\n\ntype RpcStruct struct {\n\tData []string\n}\n\nfunc (r *GoedRpc) Action(args RpcStruct, res *RpcStruct) error {\n\tresults, err := actions.Exec(args.Data[0], args.Data[1:])\n\tfor _, r := range results {\n\t\tres.Data = append(res.Data, r)\n\t}\n\treturn err\n}\n\nfunc (r *GoedRpc) Open(args []interface{}, _ *struct{}) error {\n\tvid := actions.Ar.EdOpen(args[1].(string), -1, args[0].(string), true)\n\tactions.Ar.EdActivateView(vid)\n\tactions.Ar.EdRender()\n\treturn nil\n}\n\nfunc (r *GoedRpc) Edit(args []interface{}, _ *struct{}) error {\n\tprevView := actions.Ar.EdCurView()\n\tvid := actions.Ar.EdOpen(args[1].(string), -1, args[0].(string), true)\n\tactions.Ar.EdActivateView(vid)\n\tactions.Ar.EdRender()\n\t\/\/ Wait til file closed\n\tfor {\n\t\tv := core.Ed.ViewById(vid)\n\t\tif v == nil {\n\t\t\t\/\/ switch back to the original view\n\t\t\tactions.Ar.EdActivateView(prevView)\n\t\t\tactions.Ar.EdRender()\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(250 * time.Millisecond)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/ianremmler\/clac\"\n\t\"golang.org\/x\/crypto\/ssh\/terminal\"\n\t\"robpike.io\/ivy\/value\"\n)\n\ntype runMode int\n\nconst (\n\tcliMode runMode = iota\n\ttuiMode\n\tdmenuMode\n)\n\nvar (\n\t\/\/ flags\n\tdoDmenu          = false\n\tdoInitStack      = false\n\tdoHexOut         = false\n\tcliPrec     uint = 12\n\n\tcl      = clac.New()\n\tlastErr error\n)\n\nvar cmdMap = map[string]func() error{\n\t\"neg\":    cl.Neg,\n\t\"n\":      cl.Neg,\n\t\"abs\":    cl.Abs,\n\t\"a\":      cl.Abs,\n\t\"inv\":    cl.Inv,\n\t\"i\":      cl.Inv,\n\t\"+\":      cl.Add,\n\t\"-\":      cl.Sub,\n\t\"*\":      cl.Mul,\n\t\"x\":      cl.Mul,\n\t\"\/\":      cl.Div,\n\t\"div\":    cl.IntDiv,\n\t\"%\":      cl.Mod,\n\t\"exp\":    cl.Exp,\n\t\"^\":      cl.Pow,\n\t\"2^\":     cl.Pow2,\n\t\"10^\":    cl.Pow10,\n\t\"logn\":   cl.LogN,\n\t\"ln\":     cl.Ln,\n\t\"log\":    cl.Log,\n\t\"lg\":     cl.Lg,\n\t\"sqrt\":   cl.Sqrt,\n\t\"!\":      cl.Factorial,\n\t\"comb\":   cl.Comb,\n\t\"perm\":   cl.Perm,\n\t\"sin\":    cl.Sin,\n\t\"cos\":    cl.Cos,\n\t\"tan\":    cl.Tan,\n\t\"asin\":   cl.Asin,\n\t\"acos\":   cl.Acos,\n\t\"atan\":   cl.Atan,\n\t\"atan2\":  cl.Atan2,\n\t\"dtor\":   cl.DegToRad,\n\t\"rtod\":   cl.RadToDeg,\n\t\"rtop\":   cl.RectToPolar,\n\t\"ptor\":   cl.PolarToRect,\n\t\"floor\":  cl.Floor,\n\t\"ceil\":   cl.Ceil,\n\t\"trunc\":  cl.Trunc,\n\t\"and\":    cl.And,\n\t\"or\":     cl.Or,\n\t\"xor\":    cl.Xor,\n\t\"not\":    cl.Not,\n\t\"andn\":   cl.AndN,\n\t\"orn\":    cl.OrN,\n\t\"xorn\":   cl.XorN,\n\t\"sum\":    cl.Sum,\n\t\"avg\":    cl.Avg,\n\t\"drop\":   cl.Drop,\n\t\"k\":      cl.Drop,\n\t\"dropn\":  cl.DropN,\n\t\"dropr\":  cl.DropR,\n\t\"dup\":    cl.Dup,\n\t\"d\":      cl.Dup,\n\t\"dupn\":   cl.DupN,\n\t\"dupr\":   cl.DupR,\n\t\"pick\":   cl.Pick,\n\t\"p\":      cl.Pick,\n\t\"swap\":   cl.Swap,\n\t\"s\":      cl.Swap,\n\t\"depth\":  cl.Depth,\n\t\"min\":    cl.Min,\n\t\"max\":    cl.Max,\n\t\"minn\":   cl.MinN,\n\t\"maxn\":   cl.MaxN,\n\t\"rot\":    cl.Rot,\n\t\"rotr\":   cl.RotR,\n\t\"unrot\":  cl.Unrot,\n\t\"unrotr\": cl.UnrotR,\n\t\"mag\":    cl.Mag,\n\t\"hyp\":    cl.Hypot,\n\t\"dot\":    cl.Dot,\n\t\"dot3\":   cl.Dot3,\n\t\"cross\":  cl.Cross,\n\t\"pi\":     constant(clac.Pi),\n\t\"e\":      constant(clac.E),\n\t\"phi\":    constant(clac.Phi),\n}\n\nvar uiCmdMap = map[string]func() error{\n\t\"undo\":  cl.Undo,\n\t\"u\":     cl.Undo,\n\t\"redo\":  cl.Redo,\n\t\"r\":     cl.Redo,\n\t\"clear\": cl.Clear,\n\t\"c\":     cl.Clear,\n\t\"reset\": cl.Reset,\n\t\"quit\":  quit,\n\t\"q\":     quit,\n}\n\ntype term struct {\n\tio.Reader\n\tio.Writer\n}\n\nfunc init() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"clac: \")\n\tflag.BoolVar(&doDmenu, \"d\", doDmenu, \"dmenu mode\")\n\tflag.BoolVar(&doHexOut, \"x\", doHexOut, \"hexidecimal output\")\n\tflag.UintVar(&cliPrec, \"p\", cliPrec, \"output precision\")\n\tflag.BoolVar(&doInitStack, \"i\", doInitStack, \"initialize stack\")\n}\n\nfunc main() {\n\tflag.Parse()\n\tvar mode runMode\n\tmode, lastErr = processCmdLine()\n\tswitch mode {\n\tcase cliMode:\n\t\tcliRun()\n\tcase tuiMode:\n\t\ttuiRun()\n\tcase dmenuMode:\n\t\tdmenuRun()\n\t}\n}\n\nfunc constant(v value.Value) func() error {\n\treturn func() error { return cl.Push(v) }\n}\n\nfunc cliRun() {\n\tfmt.Println(stackStr(cl.Stack()))\n\tif lastErr != nil {\n\t\tlog.Fatal(lastErr)\n\t}\n}\n\nfunc uiSetup() {\n\tfor cmd, fn := range uiCmdMap {\n\t\tcmdMap[cmd] = fn\n\t}\n\tuiCmdMap = nil\n}\n\nfunc tuiRun() {\n\tuiSetup()\n\tif !terminal.IsTerminal(syscall.Stdin) {\n\t\tlog.Fatalln(\"this doesn't look like an interactive terminal\")\n\t}\n\toldTrmState, err := terminal.MakeRaw(syscall.Stdin)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\ttrm := terminal.NewTerminal(term{os.Stdin, os.Stdout}, \"\")\n\tfor lastErr != io.EOF {\n\t\ttuiPrintStack(cl.Stack())\n\t\tvar input string\n\t\tinput, lastErr = trm.ReadLine()\n\t\tif lastErr == nil {\n\t\t\tlastErr = processInput(input)\n\t\t}\n\t}\n\tterminal.Restore(syscall.Stdin, oldTrmState)\n}\n\nfunc dmenuSetup() {\n\tuiSetup()\n\tcmdMap[\"hex\"] = func() error { doHexOut = true; return nil }\n\tcmdMap[\"dec\"] = func() error { doHexOut = false; return nil }\n\tcmdMap[\"conv\"] = dmenuConv\n}\n\nfunc dmenuRun() {\n\tdmenuSetup()\n\tfor {\n\t\tstack := stackStr(cl.Stack())\n\t\tif len(stack) > 0 {\n\t\t\tstack = \" \" + stack\n\t\t}\n\t\tout, err := exec.Command(\"dmenu\", \"-p\", \"clac:\"+stack).Output()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif err := processInput(string(out)); err != nil {\n\t\t\texec.Command(\"dmenu\", \"-p\", \"clac: \"+err.Error()).Run()\n\t\t}\n\t}\n}\n\nfunc dmenuConv() error {\n\tval, err := cl.Pop()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvalStr := stackStr(clac.Stack{val})\n\thave, err := exec.Command(\"dmenu\", \"-p\", \"clac: conv: have: \"+valStr).Output()\n\tif err != nil {\n\t\treturn errors.New(\"abort\")\n\t}\n\twant, err := exec.Command(\"dmenu\", \"-p\", \"clac: conv: want:\").Output()\n\tif err != nil {\n\t\treturn errors.New(\"abort\")\n\t}\n\thaveStr := valStr + \" \" + strings.TrimSpace(string(have))\n\twantStr := strings.TrimSpace(string(want))\n\tout, err := exec.Command(\"units\", \"-t\", haveStr, wantStr).Output()\n\tif err != nil {\n\t\terrStr := strings.SplitN(string(out), \"\\n\", 2)[0]\n\t\tif errStr != \"\" {\n\t\t\treturn errors.New(errStr)\n\t\t}\n\t\treturn err\n\t}\n\tnum, err := clac.ParseNum(strings.TrimSpace(string(out)))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn cl.Push(num)\n}\n\nfunc processCmdLine() (runMode, error) {\n\tinput := \"\"\n\tif stat, err := os.Stdin.Stat(); err == nil && stat.Mode()&os.ModeNamedPipe != 0 {\n\t\tif pipeInput, err := ioutil.ReadAll(os.Stdin); err == nil {\n\t\t\tinput = string(pipeInput)\n\t\t}\n\t}\n\tif len(flag.Args()) > 0 {\n\t\tinput += \" \" + strings.Join(flag.Args(), \" \")\n\t}\n\tmode := cliMode\n\tswitch {\n\tcase doDmenu:\n\t\tmode = dmenuMode\n\tcase doInitStack || input == \"\":\n\t\tmode = tuiMode\n\t}\n\tcl.EnableHistory(mode != cliMode)\n\terr := processInput(string(input))\n\treturn mode, err\n}\n\nfunc stackStr(stack clac.Stack) string {\n\tout := \"\"\n\tif doHexOut {\n\t\tclac.SetFormat(\"%#x\")\n\t} else {\n\t\tclac.SetFormat(fmt.Sprintf(\"%%.%dg\", cliPrec))\n\t}\n\tfor i := range stack {\n\t\tval := stack[len(stack)-i-1]\n\t\tvar err error\n\t\tif doHexOut {\n\t\t\tval, err = clac.Trunc(val)\n\t\t}\n\t\tif err != nil {\n\t\t\tout += err.Error()\n\t\t} else {\n\t\t\tout += clac.Sprint(val)\n\t\t}\n\t\tif i < len(stack)-1 {\n\t\t\tout += \" \"\n\t\t}\n\t}\n\treturn out\n}\n\nfunc quit() error {\n\tos.Exit(0)\n\treturn nil\n}\n\nfunc processInput(input string) error {\n\tscanner := bufio.NewScanner(strings.NewReader(input))\n\tscanner.Split(bufio.ScanWords)\n\tfor scanner.Scan() {\n\t\ttok := scanner.Text()\n\t\tif num, err := clac.ParseNum(tok); err == nil {\n\t\t\tif err = cl.Exec(func() error { return cl.Push(num) }); err != nil {\n\t\t\t\treturn fmt.Errorf(\"push: %s\", err)\n\t\t\t}\n\t\t} else if cmd, ok := cmdMap[tok]; ok {\n\t\t\tif err := cl.Exec(cmd); err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s: %s\", tok, err)\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"invalid input: \\\"%s\\\"\", tok)\n\t\t}\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc tuiPrintStack(stack clac.Stack) {\n\tcols, rows, err := terminal.GetSize(syscall.Stdout)\n\tif err != nil {\n\t\trows = len(stack) + 1\n\t}\n\t\/\/ ensure sane width\n\tif cols < 20 {\n\t\tcols = 20\n\t}\n\tclearScreen()\n\n\tdataCols := cols - 4\n\thexCols := dataCols \/ 2\n\tfloatCols := dataCols - hexCols\n\tfloatFmt := fmt.Sprintf(\"%%%d.%dg\", floatCols-1, floatCols-8)\n\thexFmt := fmt.Sprintf(\"%%#%dx\", hexCols-3)\n\tfor i := rows - 3; i >= 0; i-- {\n\t\tline := fmt.Sprintf(\"%02d:\", i)\n\t\tif i < len(stack) {\n\t\t\tclac.SetFormat(floatFmt)\n\t\t\tline += fmt.Sprintf(fmt.Sprintf(\" %%%ds\", floatCols), clac.Sprint(stack[i]))\n\t\t\tif val, err := clac.Trunc(stack[i]); err == nil {\n\t\t\t\tclac.SetFormat(hexFmt)\n\t\t\t\thexStr := fmt.Sprintf(fmt.Sprintf(\" %%%ds\", hexCols-1), clac.Sprint(val))\n\t\t\t\tif len(hexStr) > hexCols {\n\t\t\t\t\thexStr = hexStr[:hexCols-1] + \"…\"\n\t\t\t\t}\n\t\t\t\tline += hexStr\n\t\t\t}\n\t\t}\n\t\tfmt.Println(line + \"\\r\")\n\t}\n\tinfo := \"\"\n\tif lastErr != nil {\n\t\tinfo = fmt.Sprintf(\"[ %s ]\", lastErr)\n\t}\n\tfmt.Println(info + strings.Repeat(\"-\", cols-len(info)))\n\tfmt.Print(\"\\r\")\n}\n\nfunc clearScreen() {\n\tfmt.Print(\"\\033[2J\\033[H\")\n}\n<commit_msg>Be quiet when canceling unit conversion.<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/ianremmler\/clac\"\n\t\"golang.org\/x\/crypto\/ssh\/terminal\"\n\t\"robpike.io\/ivy\/value\"\n)\n\ntype runMode int\n\nconst (\n\tcliMode runMode = iota\n\ttuiMode\n\tdmenuMode\n)\n\nvar (\n\t\/\/ flags\n\tdoDmenu          = false\n\tdoInitStack      = false\n\tdoHexOut         = false\n\tcliPrec     uint = 12\n\n\tcl      = clac.New()\n\tlastErr error\n)\n\nvar cmdMap = map[string]func() error{\n\t\"neg\":    cl.Neg,\n\t\"n\":      cl.Neg,\n\t\"abs\":    cl.Abs,\n\t\"a\":      cl.Abs,\n\t\"inv\":    cl.Inv,\n\t\"i\":      cl.Inv,\n\t\"+\":      cl.Add,\n\t\"-\":      cl.Sub,\n\t\"*\":      cl.Mul,\n\t\"x\":      cl.Mul,\n\t\"\/\":      cl.Div,\n\t\"div\":    cl.IntDiv,\n\t\"%\":      cl.Mod,\n\t\"exp\":    cl.Exp,\n\t\"^\":      cl.Pow,\n\t\"2^\":     cl.Pow2,\n\t\"10^\":    cl.Pow10,\n\t\"logn\":   cl.LogN,\n\t\"ln\":     cl.Ln,\n\t\"log\":    cl.Log,\n\t\"lg\":     cl.Lg,\n\t\"sqrt\":   cl.Sqrt,\n\t\"!\":      cl.Factorial,\n\t\"comb\":   cl.Comb,\n\t\"perm\":   cl.Perm,\n\t\"sin\":    cl.Sin,\n\t\"cos\":    cl.Cos,\n\t\"tan\":    cl.Tan,\n\t\"asin\":   cl.Asin,\n\t\"acos\":   cl.Acos,\n\t\"atan\":   cl.Atan,\n\t\"atan2\":  cl.Atan2,\n\t\"dtor\":   cl.DegToRad,\n\t\"rtod\":   cl.RadToDeg,\n\t\"rtop\":   cl.RectToPolar,\n\t\"ptor\":   cl.PolarToRect,\n\t\"floor\":  cl.Floor,\n\t\"ceil\":   cl.Ceil,\n\t\"trunc\":  cl.Trunc,\n\t\"and\":    cl.And,\n\t\"or\":     cl.Or,\n\t\"xor\":    cl.Xor,\n\t\"not\":    cl.Not,\n\t\"andn\":   cl.AndN,\n\t\"orn\":    cl.OrN,\n\t\"xorn\":   cl.XorN,\n\t\"sum\":    cl.Sum,\n\t\"avg\":    cl.Avg,\n\t\"drop\":   cl.Drop,\n\t\"k\":      cl.Drop,\n\t\"dropn\":  cl.DropN,\n\t\"dropr\":  cl.DropR,\n\t\"dup\":    cl.Dup,\n\t\"d\":      cl.Dup,\n\t\"dupn\":   cl.DupN,\n\t\"dupr\":   cl.DupR,\n\t\"pick\":   cl.Pick,\n\t\"p\":      cl.Pick,\n\t\"swap\":   cl.Swap,\n\t\"s\":      cl.Swap,\n\t\"depth\":  cl.Depth,\n\t\"min\":    cl.Min,\n\t\"max\":    cl.Max,\n\t\"minn\":   cl.MinN,\n\t\"maxn\":   cl.MaxN,\n\t\"rot\":    cl.Rot,\n\t\"rotr\":   cl.RotR,\n\t\"unrot\":  cl.Unrot,\n\t\"unrotr\": cl.UnrotR,\n\t\"mag\":    cl.Mag,\n\t\"hyp\":    cl.Hypot,\n\t\"dot\":    cl.Dot,\n\t\"dot3\":   cl.Dot3,\n\t\"cross\":  cl.Cross,\n\t\"pi\":     constant(clac.Pi),\n\t\"e\":      constant(clac.E),\n\t\"phi\":    constant(clac.Phi),\n}\n\nvar uiCmdMap = map[string]func() error{\n\t\"undo\":  cl.Undo,\n\t\"u\":     cl.Undo,\n\t\"redo\":  cl.Redo,\n\t\"r\":     cl.Redo,\n\t\"clear\": cl.Clear,\n\t\"c\":     cl.Clear,\n\t\"reset\": cl.Reset,\n\t\"quit\":  quit,\n\t\"q\":     quit,\n}\n\ntype term struct {\n\tio.Reader\n\tio.Writer\n}\n\nfunc init() {\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"clac: \")\n\tflag.BoolVar(&doDmenu, \"d\", doDmenu, \"dmenu mode\")\n\tflag.BoolVar(&doHexOut, \"x\", doHexOut, \"hexidecimal output\")\n\tflag.UintVar(&cliPrec, \"p\", cliPrec, \"output precision\")\n\tflag.BoolVar(&doInitStack, \"i\", doInitStack, \"initialize stack\")\n}\n\nfunc main() {\n\tflag.Parse()\n\tvar mode runMode\n\tmode, lastErr = processCmdLine()\n\tswitch mode {\n\tcase cliMode:\n\t\tcliRun()\n\tcase tuiMode:\n\t\ttuiRun()\n\tcase dmenuMode:\n\t\tdmenuRun()\n\t}\n}\n\nfunc constant(v value.Value) func() error {\n\treturn func() error { return cl.Push(v) }\n}\n\nfunc cliRun() {\n\tfmt.Println(stackStr(cl.Stack()))\n\tif lastErr != nil {\n\t\tlog.Fatal(lastErr)\n\t}\n}\n\nfunc uiSetup() {\n\tfor cmd, fn := range uiCmdMap {\n\t\tcmdMap[cmd] = fn\n\t}\n\tuiCmdMap = nil\n}\n\nfunc tuiRun() {\n\tuiSetup()\n\tif !terminal.IsTerminal(syscall.Stdin) {\n\t\tlog.Fatalln(\"this doesn't look like an interactive terminal\")\n\t}\n\toldTrmState, err := terminal.MakeRaw(syscall.Stdin)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\ttrm := terminal.NewTerminal(term{os.Stdin, os.Stdout}, \"\")\n\tfor lastErr != io.EOF {\n\t\ttuiPrintStack(cl.Stack())\n\t\tvar input string\n\t\tinput, lastErr = trm.ReadLine()\n\t\tif lastErr == nil {\n\t\t\tlastErr = processInput(input)\n\t\t}\n\t}\n\tterminal.Restore(syscall.Stdin, oldTrmState)\n}\n\nfunc dmenuSetup() {\n\tuiSetup()\n\tcmdMap[\"hex\"] = func() error { doHexOut = true; return nil }\n\tcmdMap[\"dec\"] = func() error { doHexOut = false; return nil }\n\tcmdMap[\"conv\"] = dmenuConv\n}\n\nfunc dmenuRun() {\n\tdmenuSetup()\n\tfor {\n\t\tstack := stackStr(cl.Stack())\n\t\tif len(stack) > 0 {\n\t\t\tstack = \" \" + stack\n\t\t}\n\t\tout, err := exec.Command(\"dmenu\", \"-p\", \"clac:\"+stack).Output()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif err := processInput(string(out)); err != nil {\n\t\t\texec.Command(\"dmenu\", \"-p\", \"clac: \"+err.Error()).Run()\n\t\t}\n\t}\n}\n\nfunc dmenuConv() error {\n\tval, err := cl.Pop()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvalStr := stackStr(clac.Stack{val})\n\thave, err := exec.Command(\"dmenu\", \"-p\", \"clac: conv: have: \"+valStr).Output()\n\tif err != nil {\n\t\treturn clac.ErrNoHistUpdate\n\t}\n\twant, err := exec.Command(\"dmenu\", \"-p\", \"clac: conv: want:\").Output()\n\tif err != nil {\n\t\treturn clac.ErrNoHistUpdate\n\t}\n\thaveStr := valStr + \" \" + strings.TrimSpace(string(have))\n\twantStr := strings.TrimSpace(string(want))\n\tout, err := exec.Command(\"units\", \"-t\", haveStr, wantStr).Output()\n\tif err != nil {\n\t\terrStr := strings.SplitN(string(out), \"\\n\", 2)[0]\n\t\tif errStr != \"\" {\n\t\t\treturn errors.New(errStr)\n\t\t}\n\t\treturn err\n\t}\n\tnum, err := clac.ParseNum(strings.TrimSpace(string(out)))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn cl.Push(num)\n}\n\nfunc processCmdLine() (runMode, error) {\n\tinput := \"\"\n\tif stat, err := os.Stdin.Stat(); err == nil && stat.Mode()&os.ModeNamedPipe != 0 {\n\t\tif pipeInput, err := ioutil.ReadAll(os.Stdin); err == nil {\n\t\t\tinput = string(pipeInput)\n\t\t}\n\t}\n\tif len(flag.Args()) > 0 {\n\t\tinput += \" \" + strings.Join(flag.Args(), \" \")\n\t}\n\tmode := cliMode\n\tswitch {\n\tcase doDmenu:\n\t\tmode = dmenuMode\n\tcase doInitStack || input == \"\":\n\t\tmode = tuiMode\n\t}\n\tcl.EnableHistory(mode != cliMode)\n\terr := processInput(string(input))\n\treturn mode, err\n}\n\nfunc stackStr(stack clac.Stack) string {\n\tout := \"\"\n\tif doHexOut {\n\t\tclac.SetFormat(\"%#x\")\n\t} else {\n\t\tclac.SetFormat(fmt.Sprintf(\"%%.%dg\", cliPrec))\n\t}\n\tfor i := range stack {\n\t\tval := stack[len(stack)-i-1]\n\t\tvar err error\n\t\tif doHexOut {\n\t\t\tval, err = clac.Trunc(val)\n\t\t}\n\t\tif err != nil {\n\t\t\tout += err.Error()\n\t\t} else {\n\t\t\tout += clac.Sprint(val)\n\t\t}\n\t\tif i < len(stack)-1 {\n\t\t\tout += \" \"\n\t\t}\n\t}\n\treturn out\n}\n\nfunc quit() error {\n\tos.Exit(0)\n\treturn nil\n}\n\nfunc processInput(input string) error {\n\tscanner := bufio.NewScanner(strings.NewReader(input))\n\tscanner.Split(bufio.ScanWords)\n\tfor scanner.Scan() {\n\t\ttok := scanner.Text()\n\t\tif num, err := clac.ParseNum(tok); err == nil {\n\t\t\tif err = cl.Exec(func() error { return cl.Push(num) }); err != nil {\n\t\t\t\treturn fmt.Errorf(\"push: %s\", err)\n\t\t\t}\n\t\t} else if cmd, ok := cmdMap[tok]; ok {\n\t\t\tif err := cl.Exec(cmd); err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s: %s\", tok, err)\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"invalid input: \\\"%s\\\"\", tok)\n\t\t}\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc tuiPrintStack(stack clac.Stack) {\n\tcols, rows, err := terminal.GetSize(syscall.Stdout)\n\tif err != nil {\n\t\trows = len(stack) + 1\n\t}\n\t\/\/ ensure sane width\n\tif cols < 20 {\n\t\tcols = 20\n\t}\n\tclearScreen()\n\n\tdataCols := cols - 4\n\thexCols := dataCols \/ 2\n\tfloatCols := dataCols - hexCols\n\tfloatFmt := fmt.Sprintf(\"%%%d.%dg\", floatCols-1, floatCols-8)\n\thexFmt := fmt.Sprintf(\"%%#%dx\", hexCols-3)\n\tfor i := rows - 3; i >= 0; i-- {\n\t\tline := fmt.Sprintf(\"%02d:\", i)\n\t\tif i < len(stack) {\n\t\t\tclac.SetFormat(floatFmt)\n\t\t\tline += fmt.Sprintf(fmt.Sprintf(\" %%%ds\", floatCols), clac.Sprint(stack[i]))\n\t\t\tif val, err := clac.Trunc(stack[i]); err == nil {\n\t\t\t\tclac.SetFormat(hexFmt)\n\t\t\t\thexStr := fmt.Sprintf(fmt.Sprintf(\" %%%ds\", hexCols-1), clac.Sprint(val))\n\t\t\t\tif len(hexStr) > hexCols {\n\t\t\t\t\thexStr = hexStr[:hexCols-1] + \"…\"\n\t\t\t\t}\n\t\t\t\tline += hexStr\n\t\t\t}\n\t\t}\n\t\tfmt.Println(line + \"\\r\")\n\t}\n\tinfo := \"\"\n\tif lastErr != nil {\n\t\tinfo = fmt.Sprintf(\"[ %s ]\", lastErr)\n\t}\n\tfmt.Println(info + strings.Repeat(\"-\", cols-len(info)))\n\tfmt.Print(\"\\r\")\n}\n\nfunc clearScreen() {\n\tfmt.Print(\"\\033[2J\\033[H\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"os\"\n\n\t\"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/gonuts\/flag\"\n\t\"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/commander\"\n\tconfig \"github.com\/jbenet\/go-ipfs\/config\"\n\tci \"github.com\/jbenet\/go-ipfs\/crypto\"\n\tspipe \"github.com\/jbenet\/go-ipfs\/crypto\/spipe\"\n\tu \"github.com\/jbenet\/go-ipfs\/util\"\n)\n\nvar cmdIpfsInit = &commander.Command{\n\tUsageLine: \"init\",\n\tShort:     \"Initialize ipfs local configuration\",\n\tLong: `ipfs init\n\n\tInitializes ipfs configuration files and generates a\n\tnew keypair.\n`,\n\tRun:  initCmd,\n\tFlag: *flag.NewFlagSet(\"ipfs-init\", flag.ExitOnError),\n}\n\nfunc init() {\n\tcmdIpfsInit.Flag.Int(\"b\", 4096, \"number of bits for keypair\")\n\tcmdIpfsInit.Flag.String(\"p\", \"\", \"passphrase for encrypting keys\")\n\tcmdIpfsInit.Flag.Bool(\"f\", false, \"force overwrite of existing config\")\n}\n\nfunc initCmd(c *commander.Command, inp []string) error {\n\tconfigpath, err := getConfigDir(c.Parent)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif configpath == \"\" {\n\t\tconfigpath, err = u.TildeExpansion(\"~\/.go-ipfs\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tu.POut(\"initializing ipfs node at %s\\n\", configpath)\n\tfilename, err := config.Filename(configpath + \"\/config\")\n\tif err != nil {\n\t\treturn errors.New(\"Couldn't get home directory path\")\n\t}\n\n\tfi, err := os.Lstat(filename)\n\tforce, ok := c.Flag.Lookup(\"f\").Value.Get().(bool)\n\tif !ok {\n\t\treturn errors.New(\"failed to parse force flag\")\n\t}\n\tif fi != nil || (err != nil && !os.IsNotExist(err)) {\n\t\tif !force {\n\t\t\treturn errors.New(\"ipfs configuration file already exists!\\nReinitializing would overwrite your keys.\\n(use -f to force overwrite)\")\n\t\t}\n\t}\n\tcfg := new(config.Config)\n\n\tcfg.Datastore = config.Datastore{}\n\tdspath, err := u.TildeExpansion(\"~\/.go-ipfs\/datastore\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.Datastore.Path = dspath\n\tcfg.Datastore.Type = \"leveldb\"\n\n\tcfg.Identity = config.Identity{}\n\n\t\/\/ setup the node addresses.\n\tcfg.Addresses = config.Addresses{\n\t\tSwarm: \"\/ip4\/0.0.0.0\/tcp\/4001\",\n\t\tAPI:   \"\/ip4\/127.0.0.1\/tcp\/5001\",\n\t}\n\n\tnbits, ok := c.Flag.Lookup(\"b\").Value.Get().(int)\n\tif !ok {\n\t\treturn errors.New(\"failed to get bits flag\")\n\t}\n\tif nbits < 1024 {\n\t\treturn errors.New(\"Bitsize less than 1024 is considered unsafe.\")\n\t}\n\n\tu.POut(\"generating key pair\\n\")\n\tsk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ currently storing key unencrypted. in the future we need to encrypt it.\n\t\/\/ TODO(security)\n\tskbytes, err := sk.Bytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.Identity.PrivKey = base64.StdEncoding.EncodeToString(skbytes)\n\n\tid, err := spipe.IDFromPubKey(pk)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.Identity.PeerID = id.Pretty()\n\n\t\/\/ Use these hardcoded bootstrap peers for now.\n\tcfg.Bootstrap = []*config.BootstrapPeer{\n\t\t&config.BootstrapPeer{\n\t\t\t\/\/ mars.i.ipfs.io\n\t\t\tPeerID:  \"QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ\",\n\t\t\tAddress: \"\/ip4\/104.131.131.82\/tcp\/4001\",\n\t\t},\n\t}\n\n\tpath, err := u.TildeExpansion(config.DefaultConfigFilePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = config.WriteConfigFile(path, cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>Implement ipfs init -d (change datastore location)<commit_after>package main\n\nimport (\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"os\"\n\n\t\"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/gonuts\/flag\"\n\t\"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/commander\"\n\tconfig \"github.com\/jbenet\/go-ipfs\/config\"\n\tci \"github.com\/jbenet\/go-ipfs\/crypto\"\n\tspipe \"github.com\/jbenet\/go-ipfs\/crypto\/spipe\"\n\tu \"github.com\/jbenet\/go-ipfs\/util\"\n)\n\nvar cmdIpfsInit = &commander.Command{\n\tUsageLine: \"init\",\n\tShort:     \"Initialize ipfs local configuration\",\n\tLong: `ipfs init\n\n\tInitializes ipfs configuration files and generates a\n\tnew keypair.\n`,\n\tRun:  initCmd,\n\tFlag: *flag.NewFlagSet(\"ipfs-init\", flag.ExitOnError),\n}\n\nfunc init() {\n\tcmdIpfsInit.Flag.Int(\"b\", 4096, \"number of bits for keypair\")\n\tcmdIpfsInit.Flag.String(\"p\", \"\", \"passphrase for encrypting keys\")\n\tcmdIpfsInit.Flag.Bool(\"f\", false, \"force overwrite of existing config\")\n\tcmdIpfsInit.Flag.String(\"d\", \"\", \"Change default datastore location\")\n}\n\nfunc initCmd(c *commander.Command, inp []string) error {\n\tconfigpath, err := getConfigDir(c.Parent)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif configpath == \"\" {\n\t\tconfigpath, err = u.TildeExpansion(\"~\/.go-ipfs\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tu.POut(\"initializing ipfs node at %s\\n\", configpath)\n\tfilename, err := config.Filename(configpath + \"\/config\")\n\tif err != nil {\n\t\treturn errors.New(\"Couldn't get home directory path\")\n\t}\n\n\tdspath, ok := c.Flag.Lookup(\"d\").Value.Get().(string)\n\tif !ok {\n\t\treturn errors.New(\"failed to parse datastore flag\")\n\t}\n\n\tfi, err := os.Lstat(filename)\n\tforce, ok := c.Flag.Lookup(\"f\").Value.Get().(bool)\n\tif !ok {\n\t\treturn errors.New(\"failed to parse force flag\")\n\t}\n\tif fi != nil || (err != nil && !os.IsNotExist(err)) {\n\t\tif !force {\n\t\t\treturn errors.New(\"ipfs configuration file already exists!\\nReinitializing would overwrite your keys.\\n(use -f to force overwrite)\")\n\t\t}\n\t}\n\tcfg := new(config.Config)\n\n\tcfg.Datastore = config.Datastore{}\n\tif len(dspath) == 0 {\n\t\tdspath, err = u.TildeExpansion(\"~\/.go-ipfs\/datastore\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tcfg.Datastore.Path = dspath\n\tcfg.Datastore.Type = \"leveldb\"\n\n\tcfg.Identity = config.Identity{}\n\n\t\/\/ setup the node addresses.\n\tcfg.Addresses = config.Addresses{\n\t\tSwarm: \"\/ip4\/0.0.0.0\/tcp\/4001\",\n\t\tAPI:   \"\/ip4\/127.0.0.1\/tcp\/5001\",\n\t}\n\n\tnbits, ok := c.Flag.Lookup(\"b\").Value.Get().(int)\n\tif !ok {\n\t\treturn errors.New(\"failed to get bits flag\")\n\t}\n\tif nbits < 1024 {\n\t\treturn errors.New(\"Bitsize less than 1024 is considered unsafe.\")\n\t}\n\n\tu.POut(\"generating key pair\\n\")\n\tsk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ currently storing key unencrypted. in the future we need to encrypt it.\n\t\/\/ TODO(security)\n\tskbytes, err := sk.Bytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.Identity.PrivKey = base64.StdEncoding.EncodeToString(skbytes)\n\n\tid, err := spipe.IDFromPubKey(pk)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.Identity.PeerID = id.Pretty()\n\n\t\/\/ Use these hardcoded bootstrap peers for now.\n\tcfg.Bootstrap = []*config.BootstrapPeer{\n\t\t&config.BootstrapPeer{\n\t\t\t\/\/ mars.i.ipfs.io\n\t\t\tPeerID:  \"QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ\",\n\t\t\tAddress: \"\/ip4\/104.131.131.82\/tcp\/4001\",\n\t\t},\n\t}\n\n\tpath, err := u.TildeExpansion(config.DefaultConfigFilePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = config.WriteConfigFile(path, cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/go-kit\/kit\/log\/level\"\n\t\"github.com\/grafana\/loki\/pkg\/helpers\"\n\t\"github.com\/grafana\/loki\/pkg\/loki\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/prometheus\/common\/version\"\n\t\"github.com\/weaveworks\/common\/tracing\"\n\n\t\"github.com\/cortexproject\/cortex\/pkg\/util\"\n\t\"github.com\/cortexproject\/cortex\/pkg\/util\/flagext\"\n\t\"github.com\/cortexproject\/cortex\/pkg\/util\/validation\"\n)\n\nfunc init() {\n\tprometheus.MustRegister(version.NewCollector(\"loki\"))\n}\n\nfunc main() {\n\tvar (\n\t\tcfg        loki.Config\n\t\tconfigFile = \"\"\n\t)\n\tflag.StringVar(&configFile, \"config.file\", \"\", \"Configuration file to load.\")\n\tflagext.RegisterFlags(&cfg)\n\tflag.Parse()\n\n\t\/\/ LimitsConfig has a customer UnmarshalYAML that will set the defaults to a global.\n\t\/\/ This global is set to the config passed into the last call to `NewOverrides`. If we don't\n\t\/\/ call it atleast once, the defaults are set to an empty struct.\n\t\/\/ We call it with the flag values so that the config file unmarshalling only overrides the values set in the config.\n\tif _, err := validation.NewOverrides(cfg.LimitsConfig); err != nil {\n\t\tlevel.Error(util.Logger).Log(\"msg\", \"error loading limits\", \"err\", err)\n\t\tos.Exit(1)\n\t}\n\n\tutil.InitLogger(&cfg.Server)\n\n\tif configFile != \"\" {\n\t\tif err := helpers.LoadConfig(configFile, &cfg); err != nil {\n\t\t\tlevel.Error(util.Logger).Log(\"msg\", \"error loading config\", \"filename\", configFile, \"err\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\t\/\/ Setting the environment variable JAEGER_AGENT_HOST enables tracing\n\ttrace := tracing.NewFromEnv(fmt.Sprintf(\"loki-%s\", cfg.Target))\n\tdefer func() {\n\t\tif err := trace.Close(); err != nil {\n\t\t\tlevel.Error(util.Logger).Log(\"msg\", \"error closing tracing\", \"err\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\tt, err := loki.New(cfg)\n\tif err != nil {\n\t\tlevel.Error(util.Logger).Log(\"msg\", \"error initialising loki\", \"err\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlevel.Info(util.Logger).Log(\"msg\", \"Starting Loki\", \"version\", version.Info())\n\n\tif err := t.Run(); err != nil {\n\t\tlevel.Error(util.Logger).Log(\"msg\", \"error running loki\", \"err\", err)\n\t}\n\n\tif err := t.Stop(); err != nil {\n\t\tlevel.Error(util.Logger).Log(\"msg\", \"error stopping loki\", \"err\", err)\n\t\tos.Exit(1)\n\t}\n}\n<commit_msg>fix(loki): honor log level from config file (#657)<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/go-kit\/kit\/log\/level\"\n\t\"github.com\/grafana\/loki\/pkg\/helpers\"\n\t\"github.com\/grafana\/loki\/pkg\/loki\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/prometheus\/common\/version\"\n\t\"github.com\/weaveworks\/common\/tracing\"\n\n\t\"github.com\/cortexproject\/cortex\/pkg\/util\"\n\t\"github.com\/cortexproject\/cortex\/pkg\/util\/flagext\"\n\t\"github.com\/cortexproject\/cortex\/pkg\/util\/validation\"\n)\n\nfunc init() {\n\tprometheus.MustRegister(version.NewCollector(\"loki\"))\n}\n\nfunc main() {\n\tvar (\n\t\tcfg        loki.Config\n\t\tconfigFile = \"\"\n\t)\n\tflag.StringVar(&configFile, \"config.file\", \"\", \"Configuration file to load.\")\n\tflagext.RegisterFlags(&cfg)\n\tflag.Parse()\n\n\t\/\/ LimitsConfig has a customer UnmarshalYAML that will set the defaults to a global.\n\t\/\/ This global is set to the config passed into the last call to `NewOverrides`. If we don't\n\t\/\/ call it atleast once, the defaults are set to an empty struct.\n\t\/\/ We call it with the flag values so that the config file unmarshalling only overrides the values set in the config.\n\tif _, err := validation.NewOverrides(cfg.LimitsConfig); err != nil {\n\t\tlevel.Error(util.Logger).Log(\"msg\", \"error loading limits\", \"err\", err)\n\t\tos.Exit(1)\n\t}\n\n\tutil.InitLogger(&cfg.Server)\n\n\tif configFile != \"\" {\n\t\tif err := helpers.LoadConfig(configFile, &cfg); err != nil {\n\t\t\tlevel.Error(util.Logger).Log(\"msg\", \"error loading config\", \"filename\", configFile, \"err\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\t\/\/ Re-init the logger which will now honor a different log level set in cfg.Server\n\tutil.InitLogger(&cfg.Server)\n\n\t\/\/ Setting the environment variable JAEGER_AGENT_HOST enables tracing\n\ttrace := tracing.NewFromEnv(fmt.Sprintf(\"loki-%s\", cfg.Target))\n\tdefer func() {\n\t\tif err := trace.Close(); err != nil {\n\t\t\tlevel.Error(util.Logger).Log(\"msg\", \"error closing tracing\", \"err\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\tt, err := loki.New(cfg)\n\tif err != nil {\n\t\tlevel.Error(util.Logger).Log(\"msg\", \"error initialising loki\", \"err\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlevel.Info(util.Logger).Log(\"msg\", \"Starting Loki\", \"version\", version.Info())\n\n\tif err := t.Run(); err != nil {\n\t\tlevel.Error(util.Logger).Log(\"msg\", \"error running loki\", \"err\", err)\n\t}\n\n\tif err := t.Stop(); err != nil {\n\t\tlevel.Error(util.Logger).Log(\"msg\", \"error stopping loki\", \"err\", err)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/tatsushid\/go-fastping\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n)\n\ntype response struct {\n\taddr *net.IPAddr\n\trtt  time.Duration\n}\n\nfunc main() {\n\tif len(os.Args) != 2 {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s {hostname}\\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\tp := fastping.NewPinger()\n\tra, err := net.ResolveIPAddr(\"ip4:icmp\", os.Args[1])\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tresults := make(map[string]*response)\n\tresults[ra.String()] = nil\n\tp.AddIPAddr(ra)\n\n\tonRecv, onIdle := make(chan *response), make(chan bool)\n\tp.AddHandler(\"receive\", func(addr *net.IPAddr, t time.Duration) {\n\t\tonRecv <- &response{addr: addr, rtt: t}\n\t})\n\tp.AddHandler(\"idle\", func() {\n\t\tonIdle <- true\n\t})\n\n\tp.MaxRTT = time.Second\n\tp.RunLoop()\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tsignal.Notify(c, syscall.SIGTERM)\n\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-c:\n\t\t\tfmt.Println(\"get interrupted\")\n\t\t\tbreak loop\n\t\tcase res := <-onRecv:\n\t\t\tif _, ok := results[res.addr.String()]; ok {\n\t\t\t\tresults[res.addr.String()] = res\n\t\t\t}\n\t\tcase <-onIdle:\n\t\t\tfor host, r := range results {\n\t\t\t\tif r == nil {\n\t\t\t\t\tfmt.Printf(\"%s : unreachable %v\\n\", host, time.Now())\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\"%s : %v %v\\n\", host, r.rtt, time.Now())\n\t\t\t\t}\n\t\t\t\tresults[host] = nil\n\t\t\t}\n\t\tcase <-p.Done():\n\t\t\tif err = p.Err(); err != nil {\n\t\t\t\tfmt.Println(\"Ping failed:\", err)\n\t\t\t}\n\t\t\tbreak loop\n\t\t}\n\t}\n\tsignal.Stop(c)\n\tp.Stop()\n}\n<commit_msg>Add error handlings<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/tatsushid\/go-fastping\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n)\n\ntype response struct {\n\taddr *net.IPAddr\n\trtt  time.Duration\n}\n\nfunc main() {\n\tif len(os.Args) != 2 {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s {hostname}\\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\tp := fastping.NewPinger()\n\tra, err := net.ResolveIPAddr(\"ip4:icmp\", os.Args[1])\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tresults := make(map[string]*response)\n\tresults[ra.String()] = nil\n\tp.AddIPAddr(ra)\n\n\tonRecv, onIdle := make(chan *response), make(chan bool)\n\terr = p.AddHandler(\"receive\", func(addr *net.IPAddr, t time.Duration) {\n\t\tonRecv <- &response{addr: addr, rtt: t}\n\t})\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\terr = p.AddHandler(\"idle\", func() {\n\t\tonIdle <- true\n\t})\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tp.MaxRTT = time.Second\n\tp.RunLoop()\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tsignal.Notify(c, syscall.SIGTERM)\n\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-c:\n\t\t\tfmt.Println(\"get interrupted\")\n\t\t\tbreak loop\n\t\tcase res := <-onRecv:\n\t\t\tif _, ok := results[res.addr.String()]; ok {\n\t\t\t\tresults[res.addr.String()] = res\n\t\t\t}\n\t\tcase <-onIdle:\n\t\t\tfor host, r := range results {\n\t\t\t\tif r == nil {\n\t\t\t\t\tfmt.Printf(\"%s : unreachable %v\\n\", host, time.Now())\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\"%s : %v %v\\n\", host, r.rtt, time.Now())\n\t\t\t\t}\n\t\t\t\tresults[host] = nil\n\t\t\t}\n\t\tcase <-p.Done():\n\t\t\tif err = p.Err(); err != nil {\n\t\t\t\tfmt.Println(\"Ping failed:\", err)\n\t\t\t}\n\t\t\tbreak loop\n\t\t}\n\t}\n\tsignal.Stop(c)\n\tp.Stop()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2017 ben dewan <benj.dewan@gmail.com>\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\npackage cmd\n\nimport (\n\t\"log\"\n\t\"sync\"\n\n\t\"github.com\/benjdewan\/pachelbel\/config\"\n\t\"github.com\/benjdewan\/pachelbel\/connection\"\n\t\"github.com\/golang-collections\/go-datastructures\/queue\"\n\t\"github.com\/gosuri\/uiprogress\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ provisionCmd represents the provision command\nvar provisionCmd = &cobra.Command{\n\tUse:   \"provision\",\n\tShort: \"Idempotent provisioner of compose deployments\",\n\tLong: `pachelbel provision reads in YAML configuration(s) describing a list of\ndeployments that should exist in a list of clusters of specified sizes,\nand ensures they do.\n\nIf the deployments do not exist, they are created. If they exist, but are\nthe wrong size they are scaled. If they are deployed as specified in the\nconfiguration no actions are taken.`,\n\tRun: doProvision,\n}\n\nfunc doProvision(cmd *cobra.Command, args []string) {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"The 'provision' command requires at least one configuration file or directory as input\")\n\t}\n\tconfig.BuildClusterFilter(viper.GetStringSlice(\"cluster\"))\n\tconfig.BuildDatacenterFilter(viper.GetStringSlice(\"datacenter\"))\n\n\tverbose := viper.GetBool(\"verbose\")\n\tdeployments, err := config.ReadFiles(args, verbose)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcxn, err := connection.Init(viper.GetString(\"api-key\"),\n\t\tviper.GetInt(\"polling-interval\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcxn.MaxNameLength = config.MaxNameLength(deployments)\n\n\terrQueue := queue.New(int64(len(deployments)))\n\tvar wg sync.WaitGroup\n\twg.Add(len(deployments))\n\tuiprogress.Start()\n\tfor _, deployment := range deployments {\n\t\tgo connection.Provision(cxn, deployment, errQueue, &wg)\n\t}\n\twg.Wait()\n\tflush(errQueue)\n\tuiprogress.Stop()\n\n\terrQueue = queue.New(0)\n\tcxn.ConnectionStringsYAML(viper.GetString(\"output\"), errQueue)\n\tflush(errQueue)\n}\n\nfunc init() {\n\tRootCmd.AddCommand(provisionCmd)\n\tprovisionCmd.Flags().StringSliceP(\"cluster\", \"c\", []string{},\n\t\t`By default pachelbel provision will provision every deployment\n\t\t\tprovided. Use this flag to limit pachelbel to only\n\t\t\tprocess deployments to the specified cluster.\n\n\t\t\tThis flag can be repeated to specify multiple clusters`)\n\tprovisionCmd.Flags().StringSliceP(\"datacenter\", \"d\", []string{},\n\t\t`By default pachelbel provision will provision every\n\t\t\tdeployment provided. Use this flat to limit pachelbel\n\t\t\tto only process deployments to the specified\n\t\t\tdatacenter.\n\n\t\t\tThis flag can be repeated to specify multiple datacenters.`)\n\tprovisionCmd.Flags().StringP(\"output\", \"o\", \".\/connection-strings.yml\",\n\t\t`The file to write connection string information to.`)\n\tprovisionCmd.Flags().IntP(\"polling-interval\", \"p\", 5,\n\t\t`The polling interval, in seconds, to use when\n\t\t\twaiting for a provisioning recipe to complete`)\n\n\tviper.BindPFlag(\"cluster\", provisionCmd.Flags().Lookup(\"cluster\"))\n\tviper.BindPFlag(\"datacenter\", provisionCmd.Flags().Lookup(\"datacenter\"))\n\tviper.BindPFlag(\"output\", provisionCmd.Flags().Lookup(\"output\"))\n\tviper.BindPFlag(\"polling-interval\", provisionCmd.Flags().Lookup(\"polling-interval\"))\n}\n\nfunc flush(errQueue *queue.Queue) {\n\tif !errQueue.Empty() {\n\t\titems, qErr := errQueue.Get(errQueue.Len())\n\t\tif qErr != nil {\n\t\t\t\/\/ Get() only returns an error if Dispose() has already\n\t\t\t\/\/ been called on the queue.\n\t\t\tpanic(qErr)\n\t\t}\n\t\tfor _, unknown := range items {\n\t\t\tswitch item := unknown.(type) {\n\t\t\tcase error:\n\t\t\t\tlog.Printf(\"Error: %v\", item)\n\t\t\tdefault:\n\t\t\t\tlog.Fatalf(\"Only errors should be in the error queue. Found %v\", item)\n\t\t\t}\n\t\t}\n\t}\n\terrQueue.Dispose()\n}\n<commit_msg>Ensure we fail on error<commit_after>\/\/ Copyright © 2017 ben dewan <benj.dewan@gmail.com>\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\npackage cmd\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com\/benjdewan\/pachelbel\/config\"\n\t\"github.com\/benjdewan\/pachelbel\/connection\"\n\t\"github.com\/golang-collections\/go-datastructures\/queue\"\n\t\"github.com\/gosuri\/uiprogress\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ provisionCmd represents the provision command\nvar provisionCmd = &cobra.Command{\n\tUse:   \"provision\",\n\tShort: \"Idempotent provisioner of compose deployments\",\n\tLong: `pachelbel provision reads in YAML configuration(s) describing a list of\ndeployments that should exist in a list of clusters of specified sizes,\nand ensures they do.\n\nIf the deployments do not exist, they are created. If they exist, but are\nthe wrong size they are scaled. If they are deployed as specified in the\nconfiguration no actions are taken.`,\n\tRun: doProvision,\n}\n\nfunc doProvision(cmd *cobra.Command, args []string) {\n\tif len(args) == 0 {\n\t\tlog.Fatal(\"The 'provision' command requires at least one configuration file or directory as input\")\n\t}\n\tconfig.BuildClusterFilter(viper.GetStringSlice(\"cluster\"))\n\tconfig.BuildDatacenterFilter(viper.GetStringSlice(\"datacenter\"))\n\n\tverbose := viper.GetBool(\"verbose\")\n\tdeployments, err := config.ReadFiles(args, verbose)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcxn, err := connection.Init(viper.GetString(\"api-key\"),\n\t\tviper.GetInt(\"polling-interval\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcxn.MaxNameLength = config.MaxNameLength(deployments)\n\n\terrQueue := queue.New(int64(len(deployments)))\n\tvar wg sync.WaitGroup\n\twg.Add(len(deployments))\n\tuiprogress.Start()\n\tfor _, deployment := range deployments {\n\t\tgo connection.Provision(cxn, deployment, errQueue, &wg)\n\t}\n\twg.Wait()\n\tflush(errQueue)\n\tuiprogress.Stop()\n\n\terrQueue = queue.New(0)\n\tcxn.ConnectionStringsYAML(viper.GetString(\"output\"), errQueue)\n\tflush(errQueue)\n}\n\nfunc init() {\n\tRootCmd.AddCommand(provisionCmd)\n\tprovisionCmd.Flags().StringSliceP(\"cluster\", \"c\", []string{},\n\t\t`By default pachelbel provision will provision every deployment\n\t\t\tprovided. Use this flag to limit pachelbel to only\n\t\t\tprocess deployments to the specified cluster.\n\n\t\t\tThis flag can be repeated to specify multiple clusters`)\n\tprovisionCmd.Flags().StringSliceP(\"datacenter\", \"d\", []string{},\n\t\t`By default pachelbel provision will provision every\n\t\t\tdeployment provided. Use this flat to limit pachelbel\n\t\t\tto only process deployments to the specified\n\t\t\tdatacenter.\n\n\t\t\tThis flag can be repeated to specify multiple datacenters.`)\n\tprovisionCmd.Flags().StringP(\"output\", \"o\", \".\/connection-strings.yml\",\n\t\t`The file to write connection string information to.`)\n\tprovisionCmd.Flags().IntP(\"polling-interval\", \"p\", 5,\n\t\t`The polling interval, in seconds, to use when\n\t\t\twaiting for a provisioning recipe to complete`)\n\n\tviper.BindPFlag(\"cluster\", provisionCmd.Flags().Lookup(\"cluster\"))\n\tviper.BindPFlag(\"datacenter\", provisionCmd.Flags().Lookup(\"datacenter\"))\n\tviper.BindPFlag(\"output\", provisionCmd.Flags().Lookup(\"output\"))\n\tviper.BindPFlag(\"polling-interval\", provisionCmd.Flags().Lookup(\"polling-interval\"))\n}\n\nfunc flush(errQueue *queue.Queue) {\n\tif !errQueue.Empty() {\n\t\titems, qErr := errQueue.Get(errQueue.Len())\n\t\tif qErr != nil {\n\t\t\t\/\/ Get() only returns an error if Dispose() has already\n\t\t\t\/\/ been called on the queue.\n\t\t\tpanic(qErr)\n\t\t}\n\t\tfor _, unknown := range items {\n\t\t\tswitch item := unknown.(type) {\n\t\t\tcase error:\n\t\t\t\tlog.Printf(\"Error: %v\", item)\n\t\t\tdefault:\n\t\t\t\tlog.Fatalf(\"Only errors should be in the error queue. Found %v\", item)\n\t\t\t}\n\t\t}\n\t\tos.Exit(1)\n\t}\n\terrQueue.Dispose()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 The Periph Authors. All rights reserved.\n\/\/ Use of this source code is governed under the Apache License, Version 2.0\n\/\/ that can be found in the LICENSE file.\n\n\/\/ push cross compiles one or multiple executables and pushes them to a micro\n\/\/ computer over ssh.\npackage main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\/\/ run is a shorthand for exec.Command().Run().\nfunc run(name string, arg ...string) error {\n\tc := exec.Command(name, arg...)\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\treturn c.Run()\n}\n\ntype tool int\n\nconst (\n\tnone tool = iota\n\trsync\n\tpscp\n\tscp\n)\nconst toolName = \"nonersyncpscpscp\"\n\nvar toolIndex = [...]uint8{0, 4, 9, 13, 16}\n\nfunc (i tool) String() string {\n\tif i < 0 || i >= tool(len(toolIndex)-1) {\n\t\treturn fmt.Sprintf(\"tool(%d)\", i)\n\t}\n\treturn toolName[toolIndex[i]:toolIndex[i+1]]\n}\n\nfunc (t tool) push(verbose bool, src string, pkgs []string, host, rel string) error {\n\tdst := fmt.Sprintf(\"%s:%s\", host, rel)\n\tvar args []string\n\tswitch t {\n\tcase rsync:\n\t\t\/\/ Push all files via rsync. This is the fastest method.\n\t\targs = []string{\"--archive\", \"--info=progress2\", \"--compress\", src + \"\/\", dst}\n\t\tif verbose {\n\t\t\targs = append([]string{\"-v\"}, args...)\n\t\t}\n\tcase pscp, scp:\n\t\t\/\/ Push all files via pscp\/scp, provided by PuTTY\/OpenSSH.\n\t\t\/\/\n\t\t\/\/ It is slower than rsync and will fail if one of the destination\n\t\t\/\/ executable is under use, but it is a reasonable fallback.\n\t\t\/\/ TODO(maruel): pscp\/scp with an alternate name, then plink\/ssh in to\n\t\t\/\/ rename the files.\n\t\targs = []string{\"-C\", \"-p\", \"-r\"}\n\t\tfor _, pkg := range pkgs {\n\t\t\targs = append(args, filepath.Join(src, filepath.Base(pkg)))\n\t\t}\n\t\tif verbose {\n\t\t\targs = append([]string{\"-v\"}, args...)\n\t\t}\n\t\targs = append(args, dst)\n\tdefault:\n\t\treturn errors.New(\"please make sure at least one of rsync, scp or pscp is in PATH\")\n\t}\n\tif err := run(t.String(), args...); err != nil {\n\t\treturn err\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\t\/\/ On Windows, the +x bit is lost, so we are required to ssh in to change\n\t\t\/\/ the file mode.\n\t\targs = []string{host, \"chmod\", \"+x\"}\n\t\tfor _, pkg := range pkgs {\n\t\t\targs = append(args, filepath.Join(rel, filepath.Base(pkg)))\n\t\t}\n\t\tswitch t {\n\t\tcase rsync, scp:\n\t\t\treturn run(\"ssh\", args...)\n\t\tcase pscp:\n\t\t\treturn run(\"plink\", args...)\n\t\t}\n\t}\n\treturn nil\n\n}\n\n\/\/ detect returns which tool to use.\nfunc detect() tool {\n\tif _, err := exec.Command(\"rsync\", \"--version\").CombinedOutput(); err == nil {\n\t\treturn rsync\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\tif _, err := exec.Command(\"pscp\", \"-V\").CombinedOutput(); err == nil {\n\t\t\treturn pscp\n\t\t}\n\t}\n\t_, err := exec.Command(\"scp\", \"-V\").CombinedOutput()\n\tif err2, ok := err.(*exec.Error); ok && err2.Err == exec.ErrNotFound {\n\t\treturn none\n\t}\n\treturn scp\n}\n\n\/\/ toPkg returns one or multiple packages matching the relpath.\nfunc toPkg(item string) ([]string, error) {\n\tout, err := exec.Command(\"go\", \"list\", item).CombinedOutput()\n\ts := strings.TrimSpace(string(out))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list package %q: %v\\n%s\", item, err, s)\n\t}\n\treturn strings.Split(s, \"\\n\"), nil\n}\n\n\/\/ pushInner does the actual work: build then push.\nfunc pushInner(verbose bool, t tool, pkgs []string, tags string, host, rel, d string) error {\n\t\/\/ First build everything.\n\tfor _, pkg := range pkgs {\n\t\tfmt.Printf(\"- Building %s\\n\", pkg)\n\t\targs := []string{\"build\", \"-v\", \"-o\", filepath.Join(d, filepath.Base(pkg))}\n\t\tif tags != \"\" {\n\t\t\targs = append(args, \"-tags\", tags)\n\t\t}\n\t\targs = append(args, pkg)\n\t\tif err := run(\"go\", args...); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Failed to build %s\\n\", pkg)\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Then push it all as one swoop.\n\tfmt.Printf(\"- Pushing %d executables to %s in %s via %s\\n\", len(pkgs), rel, host, t)\n\treturn t.push(verbose, d, pkgs, host, rel)\n}\n\n\/\/ push wraps pushInner with a temporary directory.\nfunc push(verbose bool, t tool, items []string, tags string, host, rel string) error {\n\t\/\/ First convert the passed strings into real package names.\n\tvar pkgs []string\n\tfor _, item := range items {\n\t\ti, err := toPkg(item)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpkgs = append(pkgs, i...)\n\t}\n\n\td, err := ioutil.TempDir(\"\", \"push\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = pushInner(verbose, t, pkgs, tags, host, rel, d)\n\tif err1 := os.RemoveAll(d); err == nil {\n\t\terr = err1\n\t}\n\treturn err\n}\n\nfunc mainImpl() error {\n\tgoarch := flag.String(\"goarch\", \"arm\", \"GOARCH value to use\")\n\tgoarm := flag.String(\"goarm\", \"6\", \"GOARM value to use\")\n\tgoos := flag.String(\"goos\", \"linux\", \"GOOS value to use\")\n\ttags := flag.String(\"tags\", \"\", \"build tags to pass\")\n\trel := flag.String(\"rel\", \".\", \"directory on remote host to push files into\")\n\thost := flag.String(\"host\", os.Getenv(\"PUSH_HOST\"), \"host to push to; defaults to content of environment variable PUSH_HOST\")\n\tverbose := flag.Bool(\"v\", false, \"verbose output\")\n\tflag.Parse()\n\tpkgs := flag.Args()\n\tif len(pkgs) == 0 {\n\t\tfmt.Printf(\"Note: No argument provided, defaulting to the current directory.\\n\")\n\t\tpkgs = []string{\".\"}\n\t}\n\tif !*verbose {\n\t\tlog.SetOutput(ioutil.Discard)\n\t}\n\n\tt := detect()\n\tif t == none {\n\t\treturn errors.New(\"Please make sure at least one of rsync, scp or pscp is in PATH\")\n\t}\n\n\t\/\/ Simplify our life and just set it process wide.\n\tos.Setenv(\"GOARCH\", *goarch)\n\tos.Setenv(\"GOARM\", *goarm)\n\tos.Setenv(\"GOOS\", *goos)\n\treturn push(*verbose, t, pkgs, *tags, *host, *rel)\n}\n\nfunc main() {\n\tif err := mainImpl(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"push: %s\\n\\nVisit https:\/\/github.com\/periph\/bootstrap#troubleshooting-push for help.\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n<commit_msg>push: don't push if -host is not provided<commit_after>\/\/ Copyright 2017 The Periph Authors. All rights reserved.\n\/\/ Use of this source code is governed under the Apache License, Version 2.0\n\/\/ that can be found in the LICENSE file.\n\n\/\/ push cross compiles one or multiple executables and pushes them to a micro\n\/\/ computer over ssh.\npackage main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\/\/ run is a shorthand for exec.Command().Run().\nfunc run(name string, arg ...string) error {\n\tc := exec.Command(name, arg...)\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\treturn c.Run()\n}\n\ntype tool int\n\nconst (\n\tnone tool = iota\n\trsync\n\tpscp\n\tscp\n)\nconst toolName = \"nonersyncpscpscp\"\n\nvar toolIndex = [...]uint8{0, 4, 9, 13, 16}\n\nfunc (i tool) String() string {\n\tif i < 0 || i >= tool(len(toolIndex)-1) {\n\t\treturn fmt.Sprintf(\"tool(%d)\", i)\n\t}\n\treturn toolName[toolIndex[i]:toolIndex[i+1]]\n}\n\nfunc (t tool) push(verbose bool, src string, pkgs []string, host, rel string) error {\n\tdst := fmt.Sprintf(\"%s:%s\", host, rel)\n\tvar args []string\n\tswitch t {\n\tcase rsync:\n\t\t\/\/ Push all files via rsync. This is the fastest method.\n\t\targs = []string{\"--archive\", \"--info=progress2\", \"--compress\", src + \"\/\", dst}\n\t\tif verbose {\n\t\t\targs = append([]string{\"-v\"}, args...)\n\t\t}\n\tcase pscp, scp:\n\t\t\/\/ Push all files via pscp\/scp, provided by PuTTY\/OpenSSH.\n\t\t\/\/\n\t\t\/\/ It is slower than rsync and will fail if one of the destination\n\t\t\/\/ executable is under use, but it is a reasonable fallback.\n\t\t\/\/ TODO(maruel): pscp\/scp with an alternate name, then plink\/ssh in to\n\t\t\/\/ rename the files.\n\t\targs = []string{\"-C\", \"-p\", \"-r\"}\n\t\tfor _, pkg := range pkgs {\n\t\t\targs = append(args, filepath.Join(src, filepath.Base(pkg)))\n\t\t}\n\t\tif verbose {\n\t\t\targs = append([]string{\"-v\"}, args...)\n\t\t}\n\t\targs = append(args, dst)\n\tdefault:\n\t\treturn errors.New(\"please make sure at least one of rsync, scp or pscp is in PATH\")\n\t}\n\tif err := run(t.String(), args...); err != nil {\n\t\treturn err\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\t\/\/ On Windows, the +x bit is lost, so we are required to ssh in to change\n\t\t\/\/ the file mode.\n\t\targs = []string{host, \"chmod\", \"+x\"}\n\t\tfor _, pkg := range pkgs {\n\t\t\targs = append(args, filepath.Join(rel, filepath.Base(pkg)))\n\t\t}\n\t\tswitch t {\n\t\tcase rsync, scp:\n\t\t\treturn run(\"ssh\", args...)\n\t\tcase pscp:\n\t\t\treturn run(\"plink\", args...)\n\t\t}\n\t}\n\treturn nil\n\n}\n\n\/\/ detect returns which tool to use.\nfunc detect() tool {\n\tif _, err := exec.Command(\"rsync\", \"--version\").CombinedOutput(); err == nil {\n\t\treturn rsync\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\tif _, err := exec.Command(\"pscp\", \"-V\").CombinedOutput(); err == nil {\n\t\t\treturn pscp\n\t\t}\n\t}\n\t_, err := exec.Command(\"scp\", \"-V\").CombinedOutput()\n\tif err2, ok := err.(*exec.Error); ok && err2.Err == exec.ErrNotFound {\n\t\treturn none\n\t}\n\treturn scp\n}\n\n\/\/ toPkg returns one or multiple packages matching the relpath.\nfunc toPkg(item string) ([]string, error) {\n\tout, err := exec.Command(\"go\", \"list\", item).CombinedOutput()\n\ts := strings.TrimSpace(string(out))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list package %q: %v\\n%s\", item, err, s)\n\t}\n\treturn strings.Split(s, \"\\n\"), nil\n}\n\n\/\/ pushInner does the actual work: build then push.\nfunc pushInner(verbose bool, t tool, pkgs []string, tags string, host, rel, d string) error {\n\t\/\/ First build everything.\n\tfor _, pkg := range pkgs {\n\t\tfmt.Printf(\"- Building %s\\n\", pkg)\n\t\targs := []string{\"build\", \"-v\", \"-o\", filepath.Join(d, filepath.Base(pkg))}\n\t\tif tags != \"\" {\n\t\t\targs = append(args, \"-tags\", tags)\n\t\t}\n\t\targs = append(args, pkg)\n\t\tif err := run(\"go\", args...); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Failed to build %s\\n\", pkg)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif host == \"\" {\n\t\tfmt.Printf(\"Note: -host not provided, not pushing.\\n\")\n\t\treturn nil\n\t}\n\t\/\/ Then push it all as one swoop.\n\tfmt.Printf(\"- Pushing %d executables to %s in %s via %s\\n\", len(pkgs), rel, host, t)\n\treturn t.push(verbose, d, pkgs, host, rel)\n}\n\n\/\/ push wraps pushInner with a temporary directory.\nfunc push(verbose bool, t tool, items []string, tags string, host, rel string) error {\n\t\/\/ First convert the passed strings into real package names.\n\tvar pkgs []string\n\tfor _, item := range items {\n\t\ti, err := toPkg(item)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpkgs = append(pkgs, i...)\n\t}\n\n\td, err := ioutil.TempDir(\"\", \"push\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = pushInner(verbose, t, pkgs, tags, host, rel, d)\n\tif err1 := os.RemoveAll(d); err == nil {\n\t\terr = err1\n\t}\n\treturn err\n}\n\nfunc mainImpl() error {\n\tgoarch := flag.String(\"goarch\", \"arm\", \"GOARCH value to use\")\n\tgoarm := flag.String(\"goarm\", \"6\", \"GOARM value to use\")\n\tgoos := flag.String(\"goos\", \"linux\", \"GOOS value to use\")\n\ttags := flag.String(\"tags\", \"\", \"build tags to pass\")\n\trel := flag.String(\"rel\", \".\", \"directory on remote host to push files into\")\n\thost := flag.String(\"host\", os.Getenv(\"PUSH_HOST\"), \"host to push to; defaults to content of environment variable PUSH_HOST\")\n\tverbose := flag.Bool(\"v\", false, \"verbose output\")\n\tflag.Parse()\n\tpkgs := flag.Args()\n\tif len(pkgs) == 0 {\n\t\tfmt.Printf(\"Note: No argument provided, defaulting to the current directory.\\n\")\n\t\tpkgs = []string{\".\"}\n\t}\n\tif !*verbose {\n\t\tlog.SetOutput(ioutil.Discard)\n\t}\n\n\tt := detect()\n\tif t == none {\n\t\treturn errors.New(\"Please make sure at least one of rsync, scp or pscp is in PATH\")\n\t}\n\n\t\/\/ Simplify our life and just set it process wide.\n\tos.Setenv(\"GOARCH\", *goarch)\n\tos.Setenv(\"GOARM\", *goarm)\n\tos.Setenv(\"GOOS\", *goos)\n\treturn push(*verbose, t, pkgs, *tags, *host, *rel)\n}\n\nfunc main() {\n\tif err := mainImpl(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"push: %s\\n\\nVisit https:\/\/github.com\/periph\/bootstrap#troubleshooting-push for help.\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2017 Aqua Security Software Ltd. <info@aquasec.com>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"os\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com\/spf13\/viper\"\n)\n\nfunc TestCheckVersion(t *testing.T) {\n\tkubeoutput := `Client Version: version.Info{Major:\"1\", Minor:\"7\", GitVersion:\"v1.7.0\", GitCommit:\"d3ada0119e776222f11ec7945e6d860061339aad\", GitTreeState:\"clean\", BuildDate:\"2017-06-30T09:51:01Z\", GoVersion:\"go1.8.3\", Compiler:\"gc\", Platform:\"darwin\/amd64\"}\n\tServer Version: version.Info{Major:\"1\", Minor:\"7\", GitVersion:\"v1.7.0\", GitCommit:\"d3ada0119e776222f11ec7945e6d860061339aad\", GitTreeState:\"clean\", BuildDate:\"2017-07-26T00:12:31Z\", GoVersion:\"go1.8.3\", Compiler:\"gc\", Platform:\"linux\/amd64\"}`\n\tcases := []struct {\n\t\tt     string\n\t\ts     string\n\t\tmajor string\n\t\tminor string\n\t\texp   string\n\t}{\n\t\t{t: \"Client\", s: kubeoutput, major: \"1\", minor: \"7\"},\n\t\t{t: \"Server\", s: kubeoutput, major: \"1\", minor: \"7\"},\n\t\t{t: \"Client\", s: kubeoutput, major: \"1\", minor: \"6\", exp: \"Unexpected Client version 1.7\"},\n\t\t{t: \"Client\", s: kubeoutput, major: \"2\", minor: \"0\", exp: \"Unexpected Client version 1.7\"},\n\t\t{t: \"Server\", s: \"something unexpected\", major: \"2\", minor: \"0\", exp: \"Couldn't find Server version from kubectl output 'something unexpected'\"},\n\t}\n\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\tm := checkVersion(c.t, c.s, c.major, c.minor)\n\t\t\tif m != c.exp {\n\t\t\t\tt.Fatalf(\"Got: %s, expected: %s\", m, c.exp)\n\t\t\t}\n\t\t})\n\t}\n\n}\n\nfunc TestVersionMatch(t *testing.T) {\n\tminor := regexVersionMinor\n\tmajor := regexVersionMajor\n\tclient := `Client Version: version.Info{Major:\"1\", Minor:\"7\", GitVersion:\"v1.7.0\", GitCommit:\"d3ada0119e776222f11ec7945e6d860061339aad\", GitTreeState:\"clean\", BuildDate:\"2017-06-30T09:51:01Z\", GoVersion:\"go1.8.3\", Compiler:\"gc\", Platform:\"darwin\/amd64\"}`\n\tserver := `Server Version: version.Info{Major:\"1\", Minor:\"7\", GitVersion:\"v1.7.0\", GitCommit:\"d3ada0119e776222f11ec7945e6d860061339aad\", GitTreeState:\"clean\", BuildDate:\"2017-07-26T00:12:31Z\", GoVersion:\"go1.8.3\", Compiler:\"gc\", Platform:\"linux\/amd64\"}`\n\n\tcases := []struct {\n\t\tr   *regexp.Regexp\n\t\ts   string\n\t\texp string\n\t}{\n\t\t{r: major, s: server, exp: \"1\"},\n\t\t{r: minor, s: server, exp: \"7\"},\n\t\t{r: major, s: client, exp: \"1\"},\n\t\t{r: minor, s: client, exp: \"7\"},\n\t\t{r: major, s: \"Some unexpected string\"},\n\t\t{r: minor}, \/\/ Checking that we don't fall over if the string is empty\n\t}\n\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\tm := versionMatch(c.r, c.s)\n\t\t\tif m != c.exp {\n\t\t\t\tt.Fatalf(\"Got %s expected %s\", m, c.exp)\n\t\t\t}\n\t\t})\n\t}\n}\n\nvar g string\nvar e []error\nvar eIndex int\n\nfunc fakeps(proc string) string {\n\treturn g\n}\n\nfunc fakestat(file string) (os.FileInfo, error) {\n\terr := e[eIndex]\n\teIndex++\n\treturn nil, err\n}\n\nfunc TestVerifyBin(t *testing.T) {\n\tcases := []struct {\n\t\tproc  string\n\t\tpsOut string\n\t\texp   bool\n\t}{\n\t\t{proc: \"single\", psOut: \"single\", exp: true},\n\t\t{proc: \"single\", psOut: \"\", exp: false},\n\t\t{proc: \"two words\", psOut: \"two words\", exp: true},\n\t\t{proc: \"two words\", psOut: \"\", exp: false},\n\t\t{proc: \"cmd\", psOut: \"cmd param1 param2\", exp: true},\n\t\t{proc: \"cmd param\", psOut: \"cmd param1 param2\", exp: true},\n\t\t{proc: \"cmd param\", psOut: \"cmd\", exp: false},\n\t}\n\n\tpsFunc = fakeps\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\tg = c.psOut\n\t\t\tv := verifyBin(c.proc)\n\t\t\tif v != c.exp {\n\t\t\t\tt.Fatalf(\"Expected %v got %v\", c.exp, v)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestFindExecutable(t *testing.T) {\n\tcases := []struct {\n\t\tcandidates []string \/\/ list of executables we'd consider\n\t\tpsOut      string   \/\/ fake output from ps\n\t\texp        string   \/\/ the one we expect to find in the (fake) ps output\n\t\texpErr     bool\n\t}{\n\t\t{candidates: []string{\"one\", \"two\", \"three\"}, psOut: \"two\", exp: \"two\"},\n\t\t{candidates: []string{\"one\", \"two\", \"three\"}, psOut: \"two three\", exp: \"two\"},\n\t\t{candidates: []string{\"one double\", \"two double\", \"three double\"}, psOut: \"two double is running\", exp: \"two double\"},\n\t\t{candidates: []string{\"one\", \"two\", \"three\"}, psOut: \"blah\", expErr: true},\n\t\t{candidates: []string{\"one double\", \"two double\", \"three double\"}, psOut: \"two\", expErr: true},\n\t\t{candidates: []string{\"apiserver\", \"kube-apiserver\"}, psOut: \"kube-apiserver\", exp: \"kube-apiserver\"},\n\t\t{candidates: []string{\"apiserver\", \"kube-apiserver\", \"hyperkube-apiserver\"}, psOut: \"kube-apiserver\", exp: \"kube-apiserver\"},\n\t}\n\n\tpsFunc = fakeps\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\tg = c.psOut\n\t\t\te, err := findExecutable(c.candidates)\n\t\t\tif e != c.exp {\n\t\t\t\tt.Fatalf(\"Expected %v got %v\", c.exp, e)\n\t\t\t}\n\n\t\t\tif err == nil && c.expErr {\n\t\t\t\tt.Fatalf(\"Expected error\")\n\t\t\t}\n\n\t\t\tif err != nil && !c.expErr {\n\t\t\t\tt.Fatalf(\"Didn't expect error: %v\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetBinaries(t *testing.T) {\n\tcases := []struct {\n\t\tconfig map[string]interface{}\n\t\tpsOut  string\n\t\texp    map[string]string\n\t}{\n\t\t{\n\t\t\tconfig: map[string]interface{}{\"apiserver\": []string{\"apiserver\", \"kube-apiserver\"}},\n\t\t\tpsOut:  \"kube-apiserver\",\n\t\t\texp:    map[string]string{\"apiserver\": \"kube-apiserver\"},\n\t\t},\n\t\t{\n\t\t\tconfig: map[string]interface{}{\"apiserver\": []string{\"apiserver\", \"kube-apiserver\"}, \"thing\": []string{\"something else\", \"thing\"}},\n\t\t\tpsOut:  \"kube-apiserver thing\",\n\t\t\texp:    map[string]string{\"apiserver\": \"kube-apiserver\", \"thing\": \"thing\"},\n\t\t},\n\t}\n\n\tv := viper.New()\n\tpsFunc = fakeps\n\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\tg = c.psOut\n\t\t\tfor k, val := range c.config {\n\t\t\t\tv.Set(k, val)\n\t\t\t}\n\t\t\tm := getBinaries(v, false)\n\t\t\tif !reflect.DeepEqual(m, c.exp) {\n\t\t\t\tt.Fatalf(\"Got %v\\nExpected %v\", m, c.exp)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMultiWordReplace(t *testing.T) {\n\tcases := []struct {\n\t\tinput   string\n\t\tsub     string\n\t\tsubname string\n\t\toutput  string\n\t}{\n\t\t{input: \"Here's a file with no substitutions\", sub: \"blah\", subname: \"blah\", output: \"Here's a file with no substitutions\"},\n\t\t{input: \"Here's a file with a substitution\", sub: \"blah\", subname: \"substitution\", output: \"Here's a file with a blah\"},\n\t\t{input: \"Here's a file with multi-word substitutions\", sub: \"multi word\", subname: \"multi-word\", output: \"Here's a file with 'multi word' substitutions\"},\n\t\t{input: \"Here's a file with several several substitutions several\", sub: \"blah\", subname: \"several\", output: \"Here's a file with blah blah substitutions blah\"},\n\t}\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\ts := multiWordReplace(c.input, c.subname, c.sub)\n\t\t\tif s != c.output {\n\t\t\t\tt.Fatalf(\"Expected %s got %s\", c.output, s)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestFindConfigFile(t *testing.T) {\n\tcases := []struct {\n\t\tinput       []string\n\t\tstatResults []error\n\t\texp         string\n\t}{\n\t\t{input: []string{\"myfile\"}, statResults: []error{nil}, exp: \"myfile\"},\n\t\t{input: []string{\"thisfile\", \"thatfile\"}, statResults: []error{os.ErrNotExist, nil}, exp: \"thatfile\"},\n\t\t{input: []string{\"thisfile\", \"thatfile\"}, statResults: []error{os.ErrNotExist, os.ErrNotExist}, exp: \"\"},\n\t}\n\n\tstatFunc = fakestat\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\te = c.statResults\n\t\t\teIndex = 0\n\t\t\tconf := findConfigFile(c.input)\n\t\t\tif conf != c.exp {\n\t\t\t\tt.Fatalf(\"Got %s expected %s\", conf, c.exp)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetConfigFiles(t *testing.T) {\n\tcases := []struct {\n\t\tconfig      map[string]interface{}\n\t\texp         map[string]string\n\t\tstatResults []error\n\t}{\n\t\t{\n\t\t\tconfig:      map[string]interface{}{\"apiserver\": []string{\"apiserver\", \"kube-apiserver\"}},\n\t\t\tstatResults: []error{os.ErrNotExist, nil},\n\t\t\texp:         map[string]string{\"apiserver\": \"kube-apiserver\"},\n\t\t},\n\t\t{\n\t\t\tconfig:      map[string]interface{}{\"apiserver\": []string{\"apiserver\", \"kube-apiserver\"}, \"thing\": []string{\"\/my\/file\/thing\"}},\n\t\t\tstatResults: []error{os.ErrNotExist, nil, nil},\n\t\t\texp:         map[string]string{\"apiserver\": \"kube-apiserver\", \"thing\": \"\/my\/file\/thing\"},\n\t\t},\n\t}\n\n\tv := viper.New()\n\tstatFunc = fakestat\n\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\tfor k, val := range c.config {\n\t\t\t\tv.Set(k, val)\n\t\t\t}\n\t\t\te = c.statResults\n\t\t\teIndex = 0\n\n\t\t\tm := getConfigFiles(v)\n\t\t\tif !reflect.DeepEqual(m, c.exp) {\n\t\t\t\tt.Fatalf(\"Got %v\\nExpected %v\", m, c.exp)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMakeSubsitutions(t *testing.T) {\n\tcases := []struct {\n\t\tinput string\n\t\tsubst map[string]string\n\t\texp   string\n\t}{\n\t\t{input: \"Replace $thisbin\", subst: map[string]string{\"this\": \"that\"}, exp: \"Replace that\"},\n\t\t{input: \"Replace $thisbin\", subst: map[string]string{\"this\": \"that\", \"here\": \"there\"}, exp: \"Replace that\"},\n\t\t{input: \"Replace $thisbin and $herebin\", subst: map[string]string{\"this\": \"that\", \"here\": \"there\"}, exp: \"Replace that and there\"},\n\t}\n\tfor _, c := range cases {\n\t\tt.Run(c.input, func(t *testing.T) {\n\t\t\ts := makeSubstitutions(c.input, \"bin\", c.subst)\n\t\t\tif s != c.exp {\n\t\t\t\tt.Fatalf(\"Got %s expected %s\", s, c.exp)\n\t\t\t}\n\t\t})\n\t}\n}\n<commit_msg>Fix and add tests<commit_after>\/\/ Copyright © 2017 Aqua Security Software Ltd. <info@aquasec.com>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"os\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com\/spf13\/viper\"\n)\n\nfunc TestCheckVersion(t *testing.T) {\n\tkubeoutput := `Client Version: version.Info{Major:\"1\", Minor:\"7\", GitVersion:\"v1.7.0\", GitCommit:\"d3ada0119e776222f11ec7945e6d860061339aad\", GitTreeState:\"clean\", BuildDate:\"2017-06-30T09:51:01Z\", GoVersion:\"go1.8.3\", Compiler:\"gc\", Platform:\"darwin\/amd64\"}\n\tServer Version: version.Info{Major:\"1\", Minor:\"7\", GitVersion:\"v1.7.0\", GitCommit:\"d3ada0119e776222f11ec7945e6d860061339aad\", GitTreeState:\"clean\", BuildDate:\"2017-07-26T00:12:31Z\", GoVersion:\"go1.8.3\", Compiler:\"gc\", Platform:\"linux\/amd64\"}`\n\tcases := []struct {\n\t\tt     string\n\t\ts     string\n\t\tmajor string\n\t\tminor string\n\t\texp   string\n\t}{\n\t\t{t: \"Client\", s: kubeoutput, major: \"1\", minor: \"7\"},\n\t\t{t: \"Server\", s: kubeoutput, major: \"1\", minor: \"7\"},\n\t\t{t: \"Client\", s: kubeoutput, major: \"1\", minor: \"6\", exp: \"Unexpected Client version 1.7\"},\n\t\t{t: \"Client\", s: kubeoutput, major: \"2\", minor: \"0\", exp: \"Unexpected Client version 1.7\"},\n\t\t{t: \"Server\", s: \"something unexpected\", major: \"2\", minor: \"0\", exp: \"Couldn't find Server version from kubectl output 'something unexpected'\"},\n\t}\n\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\tm := checkVersion(c.t, c.s, c.major, c.minor)\n\t\t\tif m != c.exp {\n\t\t\t\tt.Fatalf(\"Got: %s, expected: %s\", m, c.exp)\n\t\t\t}\n\t\t})\n\t}\n\n}\n\nfunc TestVersionMatch(t *testing.T) {\n\tminor := regexVersionMinor\n\tmajor := regexVersionMajor\n\tclient := `Client Version: version.Info{Major:\"1\", Minor:\"7\", GitVersion:\"v1.7.0\", GitCommit:\"d3ada0119e776222f11ec7945e6d860061339aad\", GitTreeState:\"clean\", BuildDate:\"2017-06-30T09:51:01Z\", GoVersion:\"go1.8.3\", Compiler:\"gc\", Platform:\"darwin\/amd64\"}`\n\tserver := `Server Version: version.Info{Major:\"1\", Minor:\"7\", GitVersion:\"v1.7.0\", GitCommit:\"d3ada0119e776222f11ec7945e6d860061339aad\", GitTreeState:\"clean\", BuildDate:\"2017-07-26T00:12:31Z\", GoVersion:\"go1.8.3\", Compiler:\"gc\", Platform:\"linux\/amd64\"}`\n\n\tcases := []struct {\n\t\tr   *regexp.Regexp\n\t\ts   string\n\t\texp string\n\t}{\n\t\t{r: major, s: server, exp: \"1\"},\n\t\t{r: minor, s: server, exp: \"7\"},\n\t\t{r: major, s: client, exp: \"1\"},\n\t\t{r: minor, s: client, exp: \"7\"},\n\t\t{r: major, s: \"Some unexpected string\"},\n\t\t{r: minor}, \/\/ Checking that we don't fall over if the string is empty\n\t}\n\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\tm := versionMatch(c.r, c.s)\n\t\t\tif m != c.exp {\n\t\t\t\tt.Fatalf(\"Got %s expected %s\", m, c.exp)\n\t\t\t}\n\t\t})\n\t}\n}\n\nvar g string\nvar e []error\nvar eIndex int\n\nfunc fakeps(proc string) string {\n\treturn g\n}\n\nfunc fakestat(file string) (os.FileInfo, error) {\n\terr := e[eIndex]\n\teIndex++\n\treturn nil, err\n}\n\nfunc TestVerifyBin(t *testing.T) {\n\tcases := []struct {\n\t\tproc  string\n\t\tpsOut string\n\t\texp   bool\n\t}{\n\t\t{proc: \"single\", psOut: \"single\", exp: true},\n\t\t{proc: \"single\", psOut: \"\", exp: false},\n\t\t{proc: \"two words\", psOut: \"two words\", exp: true},\n\t\t{proc: \"two words\", psOut: \"\", exp: false},\n\t\t{proc: \"cmd\", psOut: \"cmd param1 param2\", exp: true},\n\t\t{proc: \"cmd param\", psOut: \"cmd param1 param2\", exp: true},\n\t\t{proc: \"cmd param\", psOut: \"cmd\", exp: false},\n\t}\n\n\tpsFunc = fakeps\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\tg = c.psOut\n\t\t\tv := verifyBin(c.proc)\n\t\t\tif v != c.exp {\n\t\t\t\tt.Fatalf(\"Expected %v got %v\", c.exp, v)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestFindExecutable(t *testing.T) {\n\tcases := []struct {\n\t\tcandidates []string \/\/ list of executables we'd consider\n\t\tpsOut      string   \/\/ fake output from ps\n\t\texp        string   \/\/ the one we expect to find in the (fake) ps output\n\t\texpErr     bool\n\t}{\n\t\t{candidates: []string{\"one\", \"two\", \"three\"}, psOut: \"two\", exp: \"two\"},\n\t\t{candidates: []string{\"one\", \"two\", \"three\"}, psOut: \"two three\", exp: \"two\"},\n\t\t{candidates: []string{\"one double\", \"two double\", \"three double\"}, psOut: \"two double is running\", exp: \"two double\"},\n\t\t{candidates: []string{\"one\", \"two\", \"three\"}, psOut: \"blah\", expErr: true},\n\t\t{candidates: []string{\"one double\", \"two double\", \"three double\"}, psOut: \"two\", expErr: true},\n\t\t{candidates: []string{\"apiserver\", \"kube-apiserver\"}, psOut: \"kube-apiserver\", exp: \"kube-apiserver\"},\n\t\t{candidates: []string{\"apiserver\", \"kube-apiserver\", \"hyperkube-apiserver\"}, psOut: \"kube-apiserver\", exp: \"kube-apiserver\"},\n\t}\n\n\tpsFunc = fakeps\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\tg = c.psOut\n\t\t\te, err := findExecutable(c.candidates)\n\t\t\tif e != c.exp {\n\t\t\t\tt.Fatalf(\"Expected %v got %v\", c.exp, e)\n\t\t\t}\n\n\t\t\tif err == nil && c.expErr {\n\t\t\t\tt.Fatalf(\"Expected error\")\n\t\t\t}\n\n\t\t\tif err != nil && !c.expErr {\n\t\t\t\tt.Fatalf(\"Didn't expect error: %v\", err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetBinaries(t *testing.T) {\n\tcases := []struct {\n\t\tconfig map[string]interface{}\n\t\tpsOut  string\n\t\texp    map[string]string\n\t}{\n\t\t{\n\t\t\tconfig: map[string]interface{}{\"components\": []string{\"apiserver\"}, \"apiserver\": map[string]interface{}{\"bins\": []string{\"apiserver\", \"kube-apiserver\"}}},\n\t\t\tpsOut:  \"kube-apiserver\",\n\t\t\texp:    map[string]string{\"apiserver\": \"kube-apiserver\"},\n\t\t},\n\t\t{\n\t\t\t\/\/ \"thing\" is not in the list of components\n\t\t\tconfig: map[string]interface{}{\"components\": []string{\"apiserver\"}, \"apiserver\": map[string]interface{}{\"bins\": []string{\"apiserver\", \"kube-apiserver\"}}, \"thing\": map[string]interface{}{\"bins\": []string{\"something else\", \"thing\"}}},\n\t\t\tpsOut:  \"kube-apiserver thing\",\n\t\t\texp:    map[string]string{\"apiserver\": \"kube-apiserver\"},\n\t\t},\n\t\t{\n\t\t\t\/\/ \"anotherthing\" in list of components but doesn't have a defintion\n\t\t\tconfig: map[string]interface{}{\"components\": []string{\"apiserver\", \"anotherthing\"}, \"apiserver\": map[string]interface{}{\"bins\": []string{\"apiserver\", \"kube-apiserver\"}}, \"thing\": map[string]interface{}{\"bins\": []string{\"something else\", \"thing\"}}},\n\t\t\tpsOut:  \"kube-apiserver thing\",\n\t\t\texp:    map[string]string{\"apiserver\": \"kube-apiserver\"},\n\t\t},\n\t\t{\n\t\t\t\/\/ more than one component\n\t\t\tconfig: map[string]interface{}{\"components\": []string{\"apiserver\", \"thing\"}, \"apiserver\": map[string]interface{}{\"bins\": []string{\"apiserver\", \"kube-apiserver\"}}, \"thing\": map[string]interface{}{\"bins\": []string{\"something else\", \"thing\"}}},\n\t\t\tpsOut:  \"kube-apiserver thing\",\n\t\t\texp:    map[string]string{\"apiserver\": \"kube-apiserver\", \"thing\": \"thing\"},\n\t\t},\n\t\t{\n\t\t\t\/\/ default binary to component name\n\t\t\tconfig: map[string]interface{}{\"components\": []string{\"apiserver\", \"thing\"}, \"apiserver\": map[string]interface{}{\"bins\": []string{\"apiserver\", \"kube-apiserver\"}}, \"thing\": map[string]interface{}{\"bins\": []string{\"something else\", \"thing\"}, \"optional\": true}},\n\t\t\tpsOut:  \"kube-apiserver otherthing\",\n\t\t\texp:    map[string]string{\"apiserver\": \"kube-apiserver\", \"thing\": \"thing\"},\n\t\t},\n\t}\n\n\tv := viper.New()\n\tpsFunc = fakeps\n\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\tg = c.psOut\n\t\t\tfor k, val := range c.config {\n\t\t\t\tv.Set(k, val)\n\t\t\t}\n\t\t\tm := getBinaries(v)\n\t\t\tif !reflect.DeepEqual(m, c.exp) {\n\t\t\t\tt.Fatalf(\"Got %v\\nExpected %v\", m, c.exp)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMultiWordReplace(t *testing.T) {\n\tcases := []struct {\n\t\tinput   string\n\t\tsub     string\n\t\tsubname string\n\t\toutput  string\n\t}{\n\t\t{input: \"Here's a file with no substitutions\", sub: \"blah\", subname: \"blah\", output: \"Here's a file with no substitutions\"},\n\t\t{input: \"Here's a file with a substitution\", sub: \"blah\", subname: \"substitution\", output: \"Here's a file with a blah\"},\n\t\t{input: \"Here's a file with multi-word substitutions\", sub: \"multi word\", subname: \"multi-word\", output: \"Here's a file with 'multi word' substitutions\"},\n\t\t{input: \"Here's a file with several several substitutions several\", sub: \"blah\", subname: \"several\", output: \"Here's a file with blah blah substitutions blah\"},\n\t}\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\ts := multiWordReplace(c.input, c.subname, c.sub)\n\t\t\tif s != c.output {\n\t\t\t\tt.Fatalf(\"Expected %s got %s\", c.output, s)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestFindConfigFile(t *testing.T) {\n\tcases := []struct {\n\t\tinput       []string\n\t\tstatResults []error\n\t\texp         string\n\t}{\n\t\t{input: []string{\"myfile\"}, statResults: []error{nil}, exp: \"myfile\"},\n\t\t{input: []string{\"thisfile\", \"thatfile\"}, statResults: []error{os.ErrNotExist, nil}, exp: \"thatfile\"},\n\t\t{input: []string{\"thisfile\", \"thatfile\"}, statResults: []error{os.ErrNotExist, os.ErrNotExist}, exp: \"\"},\n\t}\n\n\tstatFunc = fakestat\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\te = c.statResults\n\t\t\teIndex = 0\n\t\t\tconf := findConfigFile(c.input)\n\t\t\tif conf != c.exp {\n\t\t\t\tt.Fatalf(\"Got %s expected %s\", conf, c.exp)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetConfigFiles(t *testing.T) {\n\tcases := []struct {\n\t\tconfig      map[string]interface{}\n\t\texp         map[string]string\n\t\tstatResults []error\n\t}{\n\t\t{\n\t\t\tconfig:      map[string]interface{}{\"components\": []string{\"apiserver\"}, \"apiserver\": map[string]interface{}{\"confs\": []string{\"apiserver\", \"kube-apiserver\"}}},\n\t\t\tstatResults: []error{os.ErrNotExist, nil},\n\t\t\texp:         map[string]string{\"apiserver\": \"kube-apiserver\"},\n\t\t},\n\t\t{\n\t\t\t\/\/ Component \"thing\" isn't included in the list of components\n\t\t\tconfig: map[string]interface{}{\n\t\t\t\t\"components\": []string{\"apiserver\"},\n\t\t\t\t\"apiserver\":  map[string]interface{}{\"confs\": []string{\"apiserver\", \"kube-apiserver\"}},\n\t\t\t\t\"thing\":      map[string]interface{}{\"confs\": []string{\"\/my\/file\/thing\"}}},\n\t\t\tstatResults: []error{os.ErrNotExist, nil},\n\t\t\texp:         map[string]string{\"apiserver\": \"kube-apiserver\"},\n\t\t},\n\t\t{\n\t\t\t\/\/ More than one component\n\t\t\tconfig: map[string]interface{}{\n\t\t\t\t\"components\": []string{\"apiserver\", \"thing\"},\n\t\t\t\t\"apiserver\":  map[string]interface{}{\"confs\": []string{\"apiserver\", \"kube-apiserver\"}},\n\t\t\t\t\"thing\":      map[string]interface{}{\"confs\": []string{\"\/my\/file\/thing\"}}},\n\t\t\tstatResults: []error{os.ErrNotExist, nil, nil},\n\t\t\texp:         map[string]string{\"apiserver\": \"kube-apiserver\", \"thing\": \"\/my\/file\/thing\"},\n\t\t},\n\t\t{\n\t\t\t\/\/ Default thing to specified default config\n\t\t\tconfig: map[string]interface{}{\n\t\t\t\t\"components\": []string{\"apiserver\", \"thing\"},\n\t\t\t\t\"apiserver\":  map[string]interface{}{\"confs\": []string{\"apiserver\", \"kube-apiserver\"}},\n\t\t\t\t\"thing\":      map[string]interface{}{\"confs\": []string{\"\/my\/file\/thing\"}, \"defaultconf\": \"another\/thing\"}},\n\t\t\tstatResults: []error{os.ErrNotExist, nil, os.ErrNotExist},\n\t\t\texp:         map[string]string{\"apiserver\": \"kube-apiserver\", \"thing\": \"another\/thing\"},\n\t\t},\n\t\t{\n\t\t\t\/\/ Default thing to component name\n\t\t\tconfig: map[string]interface{}{\n\t\t\t\t\"components\": []string{\"apiserver\", \"thing\"},\n\t\t\t\t\"apiserver\":  map[string]interface{}{\"confs\": []string{\"apiserver\", \"kube-apiserver\"}},\n\t\t\t\t\"thing\":      map[string]interface{}{\"confs\": []string{\"\/my\/file\/thing\"}}},\n\t\t\tstatResults: []error{os.ErrNotExist, nil, os.ErrNotExist},\n\t\t\texp:         map[string]string{\"apiserver\": \"kube-apiserver\", \"thing\": \"thing\"},\n\t\t},\n\t}\n\n\tv := viper.New()\n\tstatFunc = fakestat\n\n\tfor id, c := range cases {\n\t\tt.Run(strconv.Itoa(id), func(t *testing.T) {\n\t\t\tfor k, val := range c.config {\n\t\t\t\tv.Set(k, val)\n\t\t\t}\n\t\t\te = c.statResults\n\t\t\teIndex = 0\n\n\t\t\tm := getConfigFiles(v)\n\t\t\tif !reflect.DeepEqual(m, c.exp) {\n\t\t\t\tt.Fatalf(\"Got %v\\nExpected %v\", m, c.exp)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMakeSubsitutions(t *testing.T) {\n\tcases := []struct {\n\t\tinput string\n\t\tsubst map[string]string\n\t\texp   string\n\t}{\n\t\t{input: \"Replace $thisbin\", subst: map[string]string{\"this\": \"that\"}, exp: \"Replace that\"},\n\t\t{input: \"Replace $thisbin\", subst: map[string]string{\"this\": \"that\", \"here\": \"there\"}, exp: \"Replace that\"},\n\t\t{input: \"Replace $thisbin and $herebin\", subst: map[string]string{\"this\": \"that\", \"here\": \"there\"}, exp: \"Replace that and there\"},\n\t}\n\tfor _, c := range cases {\n\t\tt.Run(c.input, func(t *testing.T) {\n\t\t\ts := makeSubstitutions(c.input, \"bin\", c.subst)\n\t\t\tif s != c.exp {\n\t\t\t\tt.Fatalf(\"Got %s expected %s\", s, c.exp)\n\t\t\t}\n\t\t})\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\n\t\"github.com\/sbinet\/go-commander\"\n\t\"github.com\/sbinet\/go-flag\"\n)\n\nfunc hwaf_make_cmd_self_init() *commander.Command {\n\tcmd := &commander.Command{\n\t\tRun:       hwaf_run_cmd_self_init,\n\t\tUsageLine: \"self-init [options] <workarea>\",\n\t\tShort:     \"initialize hwaf proper\",\n\t\tLong: `\nself-init initializes hwaf internal files.\n\nex:\n $ hwaf self-init\n`,\n\t\tFlag: *flag.NewFlagSet(\"hwaf-self-init\", flag.ExitOnError),\n\t}\n\tcmd.Flag.Bool(\"q\", false, \"only print error and warning messages, all other output will be suppressed\")\n\n\treturn cmd\n}\n\nfunc hwaf_run_cmd_self_init(cmd *commander.Command, args []string) {\n\tvar err error\n\tn := \"hwaf-\" + cmd.Name()\n\n\tswitch len(args) {\n\tcase 0:\n\t\t\/\/ ok\n\tdefault:\n\t\terr = fmt.Errorf(\"%s: does NOT take any argument\", n)\n\t\thandle_err(err)\n\t}\n\n\tquiet := cmd.Flag.Lookup(\"q\").Value.Get().(bool)\n\n\tif !quiet {\n\t\tfmt.Printf(\"%s: self-init...\\n\", n)\n\t}\n\n\ttop := hwaf_root()\n\tif !path_exists(top) {\n\t\terr = os.MkdirAll(top, 0700)\n\t\thandle_err(err)\n\t}\n\n\t\/\/ add hep-waftools cache\n\thwaf_tools := filepath.Join(top, \"tools\")\n\tif path_exists(hwaf_tools) {\n\t\terr = os.RemoveAll(hwaf_tools)\n\t\thandle_err(err)\n\t}\n\tgit := exec.Command(\n\t\t\"git\", \"clone\", \"git:\/\/github.com\/mana-fwk\/hep-waftools\",\n\t\thwaf_tools,\n\t)\n\tif !quiet {\n\t\tgit.Stdout = os.Stdout\n\t\tgit.Stderr = os.Stderr\n\t}\n\terr = git.Run()\n\thandle_err(err)\n\n\t\/\/ add bin dir\n\tbin := filepath.Join(top, \"bin\")\n\tif !path_exists(bin) {\n\t\terr = os.MkdirAll(bin, 0700)\n\t\thandle_err(err)\n\t}\n\t\n\t\/\/ add waf-bin\n\twaf_fname := filepath.Join(bin, \"waf\")\n\tif path_exists(waf_fname) {\n\t\terr = os.Remove(waf_fname)\n\t\thandle_err(err)\n\t}\n\twaf, err := os.OpenFile(waf_fname, os.O_WRONLY|os.O_CREATE, 0777)\n\thandle_err(err)\n\tdefer func() {\n\t\terr = waf.Sync()\n\t\thandle_err(err)\n\t\terr = waf.Close()\n\t\thandle_err(err)\n\t}()\n\n\tresp, err := http.Get(\"https:\/\/github.com\/mana-fwk\/hwaf\/raw\/master\/waf\")\n\thandle_err(err)\n\tdefer resp.Body.Close()\n\t_, err = io.Copy(waf, resp.Body)\n\thandle_err(err)\n\t\n\tif !quiet {\n\t\tfmt.Printf(\"%s: self-init... [ok]\\n\", n)\n\t}\n}\n\n\/\/ EOF\n<commit_msg>self-init: typos<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\n\t\"github.com\/sbinet\/go-commander\"\n\t\"github.com\/sbinet\/go-flag\"\n)\n\nfunc hwaf_make_cmd_self_init() *commander.Command {\n\tcmd := &commander.Command{\n\t\tRun:       hwaf_run_cmd_self_init,\n\t\tUsageLine: \"self-init [options] <workarea>\",\n\t\tShort:     \"initialize hwaf itself\",\n\t\tLong: `\nself-init initializes hwaf internal files.\n\nex:\n $ hwaf self-init\n`,\n\t\tFlag: *flag.NewFlagSet(\"hwaf-self-init\", flag.ExitOnError),\n\t}\n\tcmd.Flag.Bool(\"q\", false, \"only print error and warning messages, all other output will be suppressed\")\n\n\treturn cmd\n}\n\nfunc hwaf_run_cmd_self_init(cmd *commander.Command, args []string) {\n\tvar err error\n\tn := \"hwaf-\" + cmd.Name()\n\n\tswitch len(args) {\n\tcase 0:\n\t\t\/\/ ok\n\tdefault:\n\t\terr = fmt.Errorf(\"%s: does NOT take any argument\", n)\n\t\thandle_err(err)\n\t}\n\n\tquiet := cmd.Flag.Lookup(\"q\").Value.Get().(bool)\n\n\tif !quiet {\n\t\tfmt.Printf(\"%s: self-init...\\n\", n)\n\t}\n\n\ttop := hwaf_root()\n\tif !path_exists(top) {\n\t\terr = os.MkdirAll(top, 0700)\n\t\thandle_err(err)\n\t}\n\n\t\/\/ add hep-waftools cache\n\thwaf_tools := filepath.Join(top, \"tools\")\n\tif path_exists(hwaf_tools) {\n\t\terr = os.RemoveAll(hwaf_tools)\n\t\thandle_err(err)\n\t}\n\tgit := exec.Command(\n\t\t\"git\", \"clone\", \"git:\/\/github.com\/mana-fwk\/hep-waftools\",\n\t\thwaf_tools,\n\t)\n\tif !quiet {\n\t\tgit.Stdout = os.Stdout\n\t\tgit.Stderr = os.Stderr\n\t}\n\terr = git.Run()\n\thandle_err(err)\n\n\t\/\/ add bin dir\n\tbin := filepath.Join(top, \"bin\")\n\tif !path_exists(bin) {\n\t\terr = os.MkdirAll(bin, 0700)\n\t\thandle_err(err)\n\t}\n\t\n\t\/\/ add waf-bin\n\twaf_fname := filepath.Join(bin, \"waf\")\n\tif path_exists(waf_fname) {\n\t\terr = os.Remove(waf_fname)\n\t\thandle_err(err)\n\t}\n\twaf, err := os.OpenFile(waf_fname, os.O_WRONLY|os.O_CREATE, 0777)\n\thandle_err(err)\n\tdefer func() {\n\t\terr = waf.Sync()\n\t\thandle_err(err)\n\t\terr = waf.Close()\n\t\thandle_err(err)\n\t}()\n\n\tresp, err := http.Get(\"https:\/\/github.com\/mana-fwk\/hwaf\/raw\/master\/waf\")\n\thandle_err(err)\n\tdefer resp.Body.Close()\n\t_, err = io.Copy(waf, resp.Body)\n\thandle_err(err)\n\t\n\tif !quiet {\n\t\tfmt.Printf(\"%s: self-init... [ok]\\n\", n)\n\t}\n}\n\n\/\/ EOF\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build darwin\n\npackage roomba_api\n\nimport \"path\/filepath\"\n\nfunc listAllPorts() ([]string, error) {\n\treturn filepath.Glob(\"\/dev\/cu.B*\") \/\/usbserial*\")\n}\n<commit_msg>Mac OS X serial ports are actually more like \/dev\/cu.*<commit_after>\/\/ +build darwin\n\npackage roomba_api\n\nimport \"path\/filepath\"\n\nfunc listAllPorts() ([]string, error) {\n\treturn filepath.Glob(\"\/dev\/cu.*\") \/\/usbserial*\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package event_lib\n\nimport (\n\t\"github.com\/globalsign\/mgo\/bson\"\n\t\"scal\"\n\t\"scal\/storage\"\n\t\"time\"\n)\n\ntype EventRevisionModel struct {\n\tEventId   string    `bson:\"eventId,objectid\" json:\"eventId\"`\n\tEventType string    `bson:\"eventType\" json:\"eventType\"`\n\tSha1      string    `bson:\"sha1\" json:\"sha1\"`\n\tTime      time.Time `bson:\"time\" json:\"time\"`\n\t\/\/ InvitedEmails []string    `bson:\"invitedEmails\" json:\"invitedEmails\"`\n}\n\nfunc (model EventRevisionModel) Collection() string {\n\treturn storage.C_revision\n}\n\nfunc LoadLastRevisionModel(db storage.Database, eventIdHex *string) (\n\t*EventRevisionModel,\n\terror,\n) {\n\teventRev := EventRevisionModel{}\n\teventId := bson.ObjectIdHex(*eventIdHex)\n\terr := db.First(\n\t\tscal.M{\n\t\t\t\"eventId\": eventId,\n\t\t},\n\t\t\"-time\",\n\t\t&eventRev,\n\t)\n\treturn &eventRev, err\n}\n<commit_msg>fix fmt: revision.go<commit_after>package event_lib\n\nimport (\n\t\"scal\"\n\t\"scal\/storage\"\n\t\"time\"\n\n\t\"github.com\/globalsign\/mgo\/bson\"\n)\n\ntype EventRevisionModel struct {\n\tEventId   string    `bson:\"eventId,objectid\" json:\"eventId\"`\n\tEventType string    `bson:\"eventType\" json:\"eventType\"`\n\tSha1      string    `bson:\"sha1\" json:\"sha1\"`\n\tTime      time.Time `bson:\"time\" json:\"time\"`\n\t\/\/ InvitedEmails []string    `bson:\"invitedEmails\" json:\"invitedEmails\"`\n}\n\nfunc (model EventRevisionModel) Collection() string {\n\treturn storage.C_revision\n}\n\nfunc LoadLastRevisionModel(db storage.Database, eventIdHex *string) (\n\t*EventRevisionModel,\n\terror,\n) {\n\teventRev := EventRevisionModel{}\n\teventId := bson.ObjectIdHex(*eventIdHex)\n\terr := db.First(\n\t\tscal.M{\n\t\t\t\"eventId\": eventId,\n\t\t},\n\t\t\"-time\",\n\t\t&eventRev,\n\t)\n\treturn &eventRev, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package plugin\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/neovim\/go-client\/nvim\"\n)\n\n\/\/ Plugin represents a remote plugin.\ntype Plugin struct {\n\tNvim        *nvim.Nvim\n\tpluginSpecs []*pluginSpec\n\n\t\/\/ Event\/pattern counters used to generate unique paths for autocmds.\n\teventPathCounts map[string]int\n}\n\n\/\/ New returns an intialized plugin.\nfunc New(v *nvim.Nvim) *Plugin {\n\tp := &Plugin{\n\t\tNvim:            v,\n\t\teventPathCounts: make(map[string]int),\n\t}\n\n\t\/\/ Disable support for \"specs\" method until path mechanism for supporting\n\t\/\/ binary exectables with Nvim is worked out.\n\t\/\/ err := v.RegisterHandler(\"specs\", func(path string) ([]*pluginSpec, error) {\n\t\/\/  return p.pluginSpecs, nil\n\t\/\/ })\n\n\treturn p\n}\n\ntype pluginSpec struct {\n\tsm   string\n\tType string            `msgpack:\"type\"`\n\tName string            `msgpack:\"name\"`\n\tSync bool              `msgpack:\"sync\"`\n\tOpts map[string]string `msgpack:\"opts\"`\n}\n\nfunc (spec *pluginSpec) path() string {\n\tif i := strings.Index(spec.sm, \":\"); i > 0 {\n\t\treturn spec.sm[:i]\n\t}\n\treturn \"\"\n}\n\nfunc isSync(f interface{}) bool {\n\tt := reflect.TypeOf(f)\n\treturn t.Kind() == reflect.Func && t.NumOut() > 0\n}\n\nfunc (p *Plugin) handle(fn interface{}, spec *pluginSpec) {\n\tp.pluginSpecs = append(p.pluginSpecs, spec)\n\tif p.Nvim == nil {\n\t\treturn\n\t}\n\tif err := p.Nvim.RegisterHandler(spec.sm, fn); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Handle registers fn as a MessagePack RPC handler for the specified method\n\/\/ name. The function signature for fn is one of\n\/\/\n\/\/  func([v *nvim.Nvim,] {args}) ({resultType}, error)\n\/\/  func([v *nvim.Nvim,] {args}) error\n\/\/  func([v *nvim.Nvim,] {args})\n\/\/\n\/\/ where {args} is zero or more arguments and {resultType} is the type of of a\n\/\/ return value. Call the handler from Nvim using the rpcnotify and rpcrequest\n\/\/ functions:\n\/\/\n\/\/  :help rpcrequest()\n\/\/  :help rpcnotify()\nfunc (p *Plugin) Handle(method string, fn interface{}) {\n\tif p.Nvim == nil {\n\t\treturn\n\t}\n\tif err := p.Nvim.RegisterHandler(method, fn); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ FunctionOptions specifies function options.\ntype FunctionOptions struct {\n\t\/\/ Name is the name of the function in Nvim. The name must be made of\n\t\/\/ alphanumeric characters and '_', and must start with a capital letter.\n\tName string\n\n\t\/\/ Eval is an expression evaluated in Nvim. The result is passed the\n\t\/\/ handler function.\n\tEval string\n}\n\n\/\/ HandleFunction registers fn as a handler for a Nvim function. The function\n\/\/ signature for fn is one of\n\/\/\n\/\/  func([v *nvim.Nvim,] args {arrayType} [, eval {evalType}]) ({resultType}, error)\n\/\/  func([v *nvim.Nvim,] args {arrayType} [, eval {evalType}]) error\n\/\/\n\/\/ where {arrayType} is a type that can be unmarshaled from a MessagePack\n\/\/ array, {evalType} is a type compatible with the Eval option expression and\n\/\/ {resultType} is the type of function result.\n\/\/\n\/\/ If options.Eval == \"*\", then HandleFunction constructs the expression to\n\/\/ evaluate in Nvim from the type of fn's last argument. The last argument is\n\/\/ assumed to be a pointer to a struct type with 'eval' field tags set to the\n\/\/ expression to evaluate for each field. Nested structs are supported. The\n\/\/ expression for the function\n\/\/\n\/\/  func example(eval *struct{\n\/\/      GOPATH string `eval:\"$GOPATH\"`\n\/\/      Cwd    string `eval:\"getcwd()\"`\n\/\/  })\n\/\/\n\/\/ is\n\/\/\n\/\/  {'GOPATH': $GOPATH, Cwd: getcwd()}\nfunc (p *Plugin) HandleFunction(options *FunctionOptions, fn interface{}) {\n\tm := make(map[string]string)\n\tif options.Eval != \"\" {\n\t\tm[\"eval\"] = eval(options.Eval, fn)\n\t}\n\tp.handle(fn, &pluginSpec{\n\t\tsm:   \"0:function:\" + options.Name,\n\t\tType: \"function\",\n\t\tName: options.Name,\n\t\tSync: isSync(fn),\n\t\tOpts: m,\n\t})\n}\n\n\/\/ CommandOptions specifies command options.\ntype CommandOptions struct {\n\t\/\/ Name is the name of the command in Nvim. The name must be made of\n\t\/\/ alphanumeric characters and '_', and must start with a capital\n\t\/\/ letter.\n\tName string\n\n\t\/\/ NArgs specifies the number command arguments.\n\t\/\/\n\t\/\/  0   No arguments are allowed\n\t\/\/  1   Exactly one argument is required, it includes spaces\n\t\/\/  *   Any number of arguments are allowed (0, 1, or many),\n\t\/\/      separated by white space\n\t\/\/  ?   0 or 1 arguments are allowed\n\t\/\/  +   Arguments must be supplied, but any number are allowed\n\tNArgs string\n\n\t\/\/ Range specifies that the command accepts a range.\n\t\/\/\n\t\/\/  .   Range allowed, default is current line. The value\n\t\/\/      \".\" is converted to \"\" for Nvim.\n\t\/\/  %   Range allowed, default is whole file (1,$)\n\t\/\/  N   A count (default N) which is specified in the line\n\t\/\/      number position (like |:split|); allows for zero line\n\t\/\/\t    number.\n\t\/\/\n\t\/\/  :help :command-range\n\tRange string\n\n\t\/\/ Count specfies that thecommand accepts a count.\n\t\/\/\n\t\/\/  N   A count (default N) which is specified either in the line\n\t\/\/\t    number position, or as an initial argument (like |:Next|).\n\t\/\/      Specifying -count (without a default) acts like -count=0\n\t\/\/\n\t\/\/  :help :command-count\n\tCount string\n\n\t\/\/ Addr sepcifies the domain for the range option\n\t\/\/\n\t\/\/  lines           Range of lines (this is the default)\n\t\/\/  arguments       Range for arguments\n\t\/\/  buffers         Range for buffers (also not loaded buffers)\n\t\/\/  loaded_buffers  Range for loaded buffers\n\t\/\/  windows         Range for windows\n\t\/\/  tabs            Range for tab pages\n\t\/\/\n\t\/\/  :help command-addr\n\tAddr string\n\n\t\/\/ Eval is evaluated in Nvim and the result is passed as an argument.\n\tEval string\n\n\t\/\/ Complete specifies command completion.\n\t\/\/\n\t\/\/  :help :command-complete\n\tComplete string\n\n\t\/\/ Bang specifies that the command can take a ! modifier (like :q or :w).\n\tBang bool\n\n\t\/\/ Register specifes that the first argument to the command can be an\n\t\/\/ optional register name (like :del, :put, :yank).\n\tRegister bool\n\n\t\/\/ Bar specifies that the command can be followed by a \"|\" and another\n\t\/\/ command.  A \"|\" inside the command argument is not allowed then. Also\n\t\/\/ checks for a \" to start a comment.\n\tBar bool\n}\n\n\/\/ HandleCommand registers fn as a handler for a Nvim command. The arguments\n\/\/ to the function fn are:\n\/\/\n\/\/  v *nvim.Nvim        optional\n\/\/  args []string       when options.NArgs != \"\"\n\/\/  range [2]int        when options.Range == \".\" or Range == \"%\"\n\/\/  range int           when options.Range == N or Count != \"\"\n\/\/  bang bool           when options.Bang == true\n\/\/  register string     when options.Register == true\n\/\/  eval interface{}    when options.Eval != \"\"\n\/\/\n\/\/ The function fn must return an error.\n\/\/\n\/\/ If options.Eval == \"*\", then HandleCommand constructs the expression to\n\/\/ evaluate in Nvim from the type of fn's last argument. See the\n\/\/ HandleFunction documentation for information on how the expression is\n\/\/ generated.\nfunc (p *Plugin) HandleCommand(options *CommandOptions, fn interface{}) {\n\tm := make(map[string]string)\n\n\tif options.NArgs != \"\" {\n\t\tm[\"nargs\"] = options.NArgs\n\t}\n\n\tif options.Range != \"\" {\n\t\tif options.Range == \".\" {\n\t\t\toptions.Range = \"\"\n\t\t}\n\t\tm[\"range\"] = options.Range\n\t} else if options.Count != \"\" {\n\t\tm[\"count\"] = options.Count\n\t}\n\n\tif options.Bang {\n\t\tm[\"bang\"] = \"\"\n\t}\n\n\tif options.Register {\n\t\tm[\"register\"] = \"\"\n\t}\n\n\tif options.Eval != \"\" {\n\t\tm[\"eval\"] = eval(options.Eval, fn)\n\t}\n\n\tif options.Addr != \"\" {\n\t\tm[\"addr\"] = options.Addr\n\t}\n\n\tif options.Bar {\n\t\tm[\"bar\"] = \"\"\n\t}\n\n\tif options.Complete != \"\" {\n\t\tm[\"complete\"] = options.Complete\n\t}\n\n\tp.handle(fn, &pluginSpec{\n\t\tsm:   \"0:command:\" + options.Name,\n\t\tType: \"command\",\n\t\tName: options.Name,\n\t\tSync: isSync(fn),\n\t\tOpts: m,\n\t})\n}\n\n\/\/ AutocmdOptions specifies autocmd options.\ntype AutocmdOptions struct {\n\t\/\/ Event is the event name.\n\tEvent string\n\n\t\/\/ Group specifies the autocmd group.\n\tGroup string\n\n\t\/\/ Pattern specifies an autocmd pattern.\n\t\/\/\n\t\/\/  :help autocmd-patterns\n\tPattern string\n\n\t\/\/ Nested allows nested autocmds.\n\t\/\/\n\t\/\/  :help autocmd-nested\n\tNested bool\n\n\t\/\/ Eval is evaluated in Nvim and the result is passed the the handler\n\t\/\/ function.\n\tEval string\n}\n\n\/\/ HandleAutocmd registers fn as a handler an autocmnd event.\n\/\/\n\/\/ If options.Eval == \"*\", then HandleAutocmd constructs the expression to\n\/\/ evaluate in Nvim from the type of fn's last argument. See the HandleFunction\n\/\/ documentation for information on how the expression is generated.\nfunc (p *Plugin) HandleAutocmd(options *AutocmdOptions, fn interface{}) {\n\tpattern := \"\"\n\tm := make(map[string]string)\n\tif options.Group != \"\" {\n\t\tm[\"group\"] = options.Group\n\t}\n\tif options.Pattern != \"\" {\n\t\tm[\"pattern\"] = options.Pattern\n\t\tpattern = options.Pattern\n\t}\n\tif options.Nested {\n\t\tm[\"nested\"] = \"1\"\n\t}\n\tif options.Eval != \"\" {\n\t\tm[\"eval\"] = eval(options.Eval, fn)\n\t}\n\n\t\/\/ Compute unique path for event and pattern.\n\tep := options.Event + \":\" + pattern\n\ti := p.eventPathCounts[ep]\n\tp.eventPathCounts[ep] = i + 1\n\tsm := fmt.Sprintf(\"%d:autocmd:%s\", i, ep)\n\n\tp.handle(fn, &pluginSpec{\n\t\tsm:   sm,\n\t\tType: \"autocmd\",\n\t\tName: options.Event,\n\t\tSync: isSync(fn),\n\t\tOpts: m,\n\t})\n}\n\n\/\/ RegisterForTests registers the plugin with Nvim. Use this method for testing\n\/\/ plugins in an embedded instance of Nvim.\nfunc (p *Plugin) RegisterForTests() error {\n\tspecs := make(map[string][]*pluginSpec)\n\tfor _, spec := range p.pluginSpecs {\n\t\tspecs[spec.path()] = append(specs[spec.path()], spec)\n\t}\n\tconst host = \"nvim-go-test\"\n\tfor path, specs := range specs {\n\t\tif err := p.Nvim.Call(\"remote#host#RegisterPlugin\", nil, host, path, specs); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr := p.Nvim.Call(\"remote#host#Register\", nil, host, \"x\", p.Nvim.ChannelID())\n\treturn err\n}\n\nfunc eval(eval string, f interface{}) string {\n\tif eval != \"*\" {\n\t\treturn eval\n\t}\n\tft := reflect.TypeOf(f)\n\tif ft.Kind() != reflect.Func || ft.NumIn() < 1 {\n\t\tpanic(`Eval: \"*\" option requires function with at least one argument`)\n\t}\n\targt := ft.In(ft.NumIn() - 1)\n\tif argt.Kind() != reflect.Ptr || argt.Elem().Kind() != reflect.Struct {\n\t\tpanic(`Eval: \"*\" option requires function with pointer to struct as last argument`)\n\t}\n\treturn structEval(argt.Elem())\n}\n\nfunc structEval(t reflect.Type) string {\n\tbuf := []byte{'{'}\n\tsep := \"\"\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tsf := t.Field(i)\n\t\tif sf.Anonymous {\n\t\t\tpanic(`Eval: \"*\" does not support anonymous fields`)\n\t\t}\n\n\t\teval := sf.Tag.Get(\"eval\")\n\t\tif eval == \"\" {\n\t\t\tft := sf.Type\n\t\t\tif ft.Kind() == reflect.Ptr {\n\t\t\t\tft = ft.Elem()\n\t\t\t}\n\t\t\tif ft.Kind() == reflect.Struct {\n\t\t\t\teval = structEval(ft)\n\t\t\t}\n\t\t}\n\n\t\tif eval == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tname := strings.Split(sf.Tag.Get(\"msgpack\"), \",\")[0]\n\t\tif name == \"\" {\n\t\t\tname = sf.Name\n\t\t}\n\n\t\tbuf = append(buf, sep...)\n\t\tbuf = append(buf, \"'\"...)\n\t\tbuf = append(buf, name...)\n\t\tbuf = append(buf, \"': \"...)\n\t\tbuf = append(buf, eval...)\n\t\tsep = \", \"\n\t}\n\tbuf = append(buf, '}')\n\treturn string(buf)\n}\n\ntype byServiceMethod []*pluginSpec\n\nfunc (a byServiceMethod) Len() int           { return len(a) }\nfunc (a byServiceMethod) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a byServiceMethod) Less(i, j int) bool { return a[i].sm < a[j].sm }\n\nfunc (p *Plugin) Manifest(host string) []byte {\n\tvar buf bytes.Buffer\n\n\t\/\/ Sort for consistent order on output.\n\tsort.Sort(byServiceMethod(p.pluginSpecs))\n\tescape := strings.NewReplacer(\"'\", \"''\").Replace\n\n\tprevPath := \"\"\n\tfor _, spec := range p.pluginSpecs {\n\t\tpath := spec.path()\n\t\tif path != prevPath {\n\t\t\tif prevPath != \"\" {\n\t\t\t\tfmt.Fprintf(&buf, \"\\\\ )\")\n\t\t\t}\n\t\t\tfmt.Fprintf(&buf, \"call remote#host#RegisterPlugin('%s', '%s', [\\n\", host, path)\n\t\t\tprevPath = path\n\t\t}\n\n\t\tsync := \"0\"\n\t\tif spec.Sync {\n\t\t\tsync = \"1\"\n\t\t}\n\n\t\tfmt.Fprintf(&buf, \"\\\\ {'type': '%s', 'name': '%s', 'sync': %s, 'opts': {\", spec.Type, spec.Name, sync)\n\n\t\tvar keys []string\n\t\tfor k := range spec.Opts {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Strings(keys)\n\n\t\toptDelim := \"\"\n\t\tfor _, k := range keys {\n\t\t\tfmt.Fprintf(&buf, \"%s'%s': '%s'\", optDelim, k, escape(spec.Opts[k]))\n\t\t\toptDelim = \", \"\n\t\t}\n\n\t\tfmt.Fprintf(&buf, \"}},\\n\")\n\t}\n\tif prevPath != \"\" {\n\t\tfmt.Fprintf(&buf, \"\\\\ ])\\n\")\n\t}\n\treturn buf.Bytes()\n}\n<commit_msg>nvim\/plugin: support once to AutocmdOptions<commit_after>package plugin\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/neovim\/go-client\/nvim\"\n)\n\n\/\/ Plugin represents a remote plugin.\ntype Plugin struct {\n\tNvim        *nvim.Nvim\n\tpluginSpecs []*pluginSpec\n\n\t\/\/ Event\/pattern counters used to generate unique paths for autocmds.\n\teventPathCounts map[string]int\n}\n\n\/\/ New returns an intialized plugin.\nfunc New(v *nvim.Nvim) *Plugin {\n\tp := &Plugin{\n\t\tNvim:            v,\n\t\teventPathCounts: make(map[string]int),\n\t}\n\n\t\/\/ Disable support for \"specs\" method until path mechanism for supporting\n\t\/\/ binary exectables with Nvim is worked out.\n\t\/\/ err := v.RegisterHandler(\"specs\", func(path string) ([]*pluginSpec, error) {\n\t\/\/  return p.pluginSpecs, nil\n\t\/\/ })\n\n\treturn p\n}\n\ntype pluginSpec struct {\n\tsm   string\n\tType string            `msgpack:\"type\"`\n\tName string            `msgpack:\"name\"`\n\tSync bool              `msgpack:\"sync\"`\n\tOpts map[string]string `msgpack:\"opts\"`\n}\n\nfunc (spec *pluginSpec) path() string {\n\tif i := strings.Index(spec.sm, \":\"); i > 0 {\n\t\treturn spec.sm[:i]\n\t}\n\treturn \"\"\n}\n\nfunc isSync(f interface{}) bool {\n\tt := reflect.TypeOf(f)\n\treturn t.Kind() == reflect.Func && t.NumOut() > 0\n}\n\nfunc (p *Plugin) handle(fn interface{}, spec *pluginSpec) {\n\tp.pluginSpecs = append(p.pluginSpecs, spec)\n\tif p.Nvim == nil {\n\t\treturn\n\t}\n\tif err := p.Nvim.RegisterHandler(spec.sm, fn); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Handle registers fn as a MessagePack RPC handler for the specified method\n\/\/ name. The function signature for fn is one of\n\/\/\n\/\/  func([v *nvim.Nvim,] {args}) ({resultType}, error)\n\/\/  func([v *nvim.Nvim,] {args}) error\n\/\/  func([v *nvim.Nvim,] {args})\n\/\/\n\/\/ where {args} is zero or more arguments and {resultType} is the type of of a\n\/\/ return value. Call the handler from Nvim using the rpcnotify and rpcrequest\n\/\/ functions:\n\/\/\n\/\/  :help rpcrequest()\n\/\/  :help rpcnotify()\nfunc (p *Plugin) Handle(method string, fn interface{}) {\n\tif p.Nvim == nil {\n\t\treturn\n\t}\n\tif err := p.Nvim.RegisterHandler(method, fn); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ FunctionOptions specifies function options.\ntype FunctionOptions struct {\n\t\/\/ Name is the name of the function in Nvim. The name must be made of\n\t\/\/ alphanumeric characters and '_', and must start with a capital letter.\n\tName string\n\n\t\/\/ Eval is an expression evaluated in Nvim. The result is passed the\n\t\/\/ handler function.\n\tEval string\n}\n\n\/\/ HandleFunction registers fn as a handler for a Nvim function. The function\n\/\/ signature for fn is one of\n\/\/\n\/\/  func([v *nvim.Nvim,] args {arrayType} [, eval {evalType}]) ({resultType}, error)\n\/\/  func([v *nvim.Nvim,] args {arrayType} [, eval {evalType}]) error\n\/\/\n\/\/ where {arrayType} is a type that can be unmarshaled from a MessagePack\n\/\/ array, {evalType} is a type compatible with the Eval option expression and\n\/\/ {resultType} is the type of function result.\n\/\/\n\/\/ If options.Eval == \"*\", then HandleFunction constructs the expression to\n\/\/ evaluate in Nvim from the type of fn's last argument. The last argument is\n\/\/ assumed to be a pointer to a struct type with 'eval' field tags set to the\n\/\/ expression to evaluate for each field. Nested structs are supported. The\n\/\/ expression for the function\n\/\/\n\/\/  func example(eval *struct{\n\/\/      GOPATH string `eval:\"$GOPATH\"`\n\/\/      Cwd    string `eval:\"getcwd()\"`\n\/\/  })\n\/\/\n\/\/ is\n\/\/\n\/\/  {'GOPATH': $GOPATH, Cwd: getcwd()}\nfunc (p *Plugin) HandleFunction(options *FunctionOptions, fn interface{}) {\n\tm := make(map[string]string)\n\tif options.Eval != \"\" {\n\t\tm[\"eval\"] = eval(options.Eval, fn)\n\t}\n\tp.handle(fn, &pluginSpec{\n\t\tsm:   \"0:function:\" + options.Name,\n\t\tType: \"function\",\n\t\tName: options.Name,\n\t\tSync: isSync(fn),\n\t\tOpts: m,\n\t})\n}\n\n\/\/ CommandOptions specifies command options.\ntype CommandOptions struct {\n\t\/\/ Name is the name of the command in Nvim. The name must be made of\n\t\/\/ alphanumeric characters and '_', and must start with a capital\n\t\/\/ letter.\n\tName string\n\n\t\/\/ NArgs specifies the number command arguments.\n\t\/\/\n\t\/\/  0   No arguments are allowed\n\t\/\/  1   Exactly one argument is required, it includes spaces\n\t\/\/  *   Any number of arguments are allowed (0, 1, or many),\n\t\/\/      separated by white space\n\t\/\/  ?   0 or 1 arguments are allowed\n\t\/\/  +   Arguments must be supplied, but any number are allowed\n\tNArgs string\n\n\t\/\/ Range specifies that the command accepts a range.\n\t\/\/\n\t\/\/  .   Range allowed, default is current line. The value\n\t\/\/      \".\" is converted to \"\" for Nvim.\n\t\/\/  %   Range allowed, default is whole file (1,$)\n\t\/\/  N   A count (default N) which is specified in the line\n\t\/\/      number position (like |:split|); allows for zero line\n\t\/\/\t    number.\n\t\/\/\n\t\/\/  :help :command-range\n\tRange string\n\n\t\/\/ Count specfies that thecommand accepts a count.\n\t\/\/\n\t\/\/  N   A count (default N) which is specified either in the line\n\t\/\/\t    number position, or as an initial argument (like |:Next|).\n\t\/\/      Specifying -count (without a default) acts like -count=0\n\t\/\/\n\t\/\/  :help :command-count\n\tCount string\n\n\t\/\/ Addr sepcifies the domain for the range option\n\t\/\/\n\t\/\/  lines           Range of lines (this is the default)\n\t\/\/  arguments       Range for arguments\n\t\/\/  buffers         Range for buffers (also not loaded buffers)\n\t\/\/  loaded_buffers  Range for loaded buffers\n\t\/\/  windows         Range for windows\n\t\/\/  tabs            Range for tab pages\n\t\/\/\n\t\/\/  :help command-addr\n\tAddr string\n\n\t\/\/ Eval is evaluated in Nvim and the result is passed as an argument.\n\tEval string\n\n\t\/\/ Complete specifies command completion.\n\t\/\/\n\t\/\/  :help :command-complete\n\tComplete string\n\n\t\/\/ Bang specifies that the command can take a ! modifier (like :q or :w).\n\tBang bool\n\n\t\/\/ Register specifes that the first argument to the command can be an\n\t\/\/ optional register name (like :del, :put, :yank).\n\tRegister bool\n\n\t\/\/ Bar specifies that the command can be followed by a \"|\" and another\n\t\/\/ command.  A \"|\" inside the command argument is not allowed then. Also\n\t\/\/ checks for a \" to start a comment.\n\tBar bool\n}\n\n\/\/ HandleCommand registers fn as a handler for a Nvim command. The arguments\n\/\/ to the function fn are:\n\/\/\n\/\/  v *nvim.Nvim        optional\n\/\/  args []string       when options.NArgs != \"\"\n\/\/  range [2]int        when options.Range == \".\" or Range == \"%\"\n\/\/  range int           when options.Range == N or Count != \"\"\n\/\/  bang bool           when options.Bang == true\n\/\/  register string     when options.Register == true\n\/\/  eval interface{}    when options.Eval != \"\"\n\/\/\n\/\/ The function fn must return an error.\n\/\/\n\/\/ If options.Eval == \"*\", then HandleCommand constructs the expression to\n\/\/ evaluate in Nvim from the type of fn's last argument. See the\n\/\/ HandleFunction documentation for information on how the expression is\n\/\/ generated.\nfunc (p *Plugin) HandleCommand(options *CommandOptions, fn interface{}) {\n\tm := make(map[string]string)\n\n\tif options.NArgs != \"\" {\n\t\tm[\"nargs\"] = options.NArgs\n\t}\n\n\tif options.Range != \"\" {\n\t\tif options.Range == \".\" {\n\t\t\toptions.Range = \"\"\n\t\t}\n\t\tm[\"range\"] = options.Range\n\t} else if options.Count != \"\" {\n\t\tm[\"count\"] = options.Count\n\t}\n\n\tif options.Bang {\n\t\tm[\"bang\"] = \"\"\n\t}\n\n\tif options.Register {\n\t\tm[\"register\"] = \"\"\n\t}\n\n\tif options.Eval != \"\" {\n\t\tm[\"eval\"] = eval(options.Eval, fn)\n\t}\n\n\tif options.Addr != \"\" {\n\t\tm[\"addr\"] = options.Addr\n\t}\n\n\tif options.Bar {\n\t\tm[\"bar\"] = \"\"\n\t}\n\n\tif options.Complete != \"\" {\n\t\tm[\"complete\"] = options.Complete\n\t}\n\n\tp.handle(fn, &pluginSpec{\n\t\tsm:   \"0:command:\" + options.Name,\n\t\tType: \"command\",\n\t\tName: options.Name,\n\t\tSync: isSync(fn),\n\t\tOpts: m,\n\t})\n}\n\n\/\/ AutocmdOptions specifies autocmd options.\ntype AutocmdOptions struct {\n\t\/\/ Event is the event name.\n\tEvent string\n\n\t\/\/ Group specifies the autocmd group.\n\tGroup string\n\n\t\/\/ Pattern specifies an autocmd pattern.\n\t\/\/\n\t\/\/  :help autocmd-patterns\n\tPattern string\n\n\t\/\/ Nested allows nested autocmds.\n\t\/\/\n\t\/\/  :help autocmd-nested\n\tNested bool\n\n\t\/\/ Once supplys the command is executed once, then removed (\"one shot\").\n\t\/\/\n\t\/\/  :help autocmd-once\n\tOnce bool\n\n\t\/\/ Eval is evaluated in Nvim and the result is passed the the handler\n\t\/\/ function.\n\tEval string\n}\n\n\/\/ HandleAutocmd registers fn as a handler an autocmnd event.\n\/\/\n\/\/ If options.Eval == \"*\", then HandleAutocmd constructs the expression to\n\/\/ evaluate in Nvim from the type of fn's last argument. See the HandleFunction\n\/\/ documentation for information on how the expression is generated.\nfunc (p *Plugin) HandleAutocmd(options *AutocmdOptions, fn interface{}) {\n\tpattern := \"\"\n\tm := make(map[string]string)\n\tif options.Group != \"\" {\n\t\tm[\"group\"] = options.Group\n\t}\n\tif options.Pattern != \"\" {\n\t\tm[\"pattern\"] = options.Pattern\n\t\tpattern = options.Pattern\n\t}\n\tif options.Nested {\n\t\tm[\"nested\"] = \"1\"\n\t}\n\tif options.Once {\n\t\tm[\"once\"] = \"1\"\n\t}\n\tif options.Eval != \"\" {\n\t\tm[\"eval\"] = eval(options.Eval, fn)\n\t}\n\n\t\/\/ Compute unique path for event and pattern.\n\tep := options.Event + \":\" + pattern\n\ti := p.eventPathCounts[ep]\n\tp.eventPathCounts[ep] = i + 1\n\tsm := fmt.Sprintf(\"%d:autocmd:%s\", i, ep)\n\n\tp.handle(fn, &pluginSpec{\n\t\tsm:   sm,\n\t\tType: \"autocmd\",\n\t\tName: options.Event,\n\t\tSync: isSync(fn),\n\t\tOpts: m,\n\t})\n}\n\n\/\/ RegisterForTests registers the plugin with Nvim. Use this method for testing\n\/\/ plugins in an embedded instance of Nvim.\nfunc (p *Plugin) RegisterForTests() error {\n\tspecs := make(map[string][]*pluginSpec)\n\tfor _, spec := range p.pluginSpecs {\n\t\tspecs[spec.path()] = append(specs[spec.path()], spec)\n\t}\n\tconst host = \"nvim-go-test\"\n\tfor path, specs := range specs {\n\t\tif err := p.Nvim.Call(\"remote#host#RegisterPlugin\", nil, host, path, specs); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr := p.Nvim.Call(\"remote#host#Register\", nil, host, \"x\", p.Nvim.ChannelID())\n\treturn err\n}\n\nfunc eval(eval string, f interface{}) string {\n\tif eval != \"*\" {\n\t\treturn eval\n\t}\n\tft := reflect.TypeOf(f)\n\tif ft.Kind() != reflect.Func || ft.NumIn() < 1 {\n\t\tpanic(`Eval: \"*\" option requires function with at least one argument`)\n\t}\n\targt := ft.In(ft.NumIn() - 1)\n\tif argt.Kind() != reflect.Ptr || argt.Elem().Kind() != reflect.Struct {\n\t\tpanic(`Eval: \"*\" option requires function with pointer to struct as last argument`)\n\t}\n\treturn structEval(argt.Elem())\n}\n\nfunc structEval(t reflect.Type) string {\n\tbuf := []byte{'{'}\n\tsep := \"\"\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tsf := t.Field(i)\n\t\tif sf.Anonymous {\n\t\t\tpanic(`Eval: \"*\" does not support anonymous fields`)\n\t\t}\n\n\t\teval := sf.Tag.Get(\"eval\")\n\t\tif eval == \"\" {\n\t\t\tft := sf.Type\n\t\t\tif ft.Kind() == reflect.Ptr {\n\t\t\t\tft = ft.Elem()\n\t\t\t}\n\t\t\tif ft.Kind() == reflect.Struct {\n\t\t\t\teval = structEval(ft)\n\t\t\t}\n\t\t}\n\n\t\tif eval == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tname := strings.Split(sf.Tag.Get(\"msgpack\"), \",\")[0]\n\t\tif name == \"\" {\n\t\t\tname = sf.Name\n\t\t}\n\n\t\tbuf = append(buf, sep...)\n\t\tbuf = append(buf, \"'\"...)\n\t\tbuf = append(buf, name...)\n\t\tbuf = append(buf, \"': \"...)\n\t\tbuf = append(buf, eval...)\n\t\tsep = \", \"\n\t}\n\tbuf = append(buf, '}')\n\treturn string(buf)\n}\n\ntype byServiceMethod []*pluginSpec\n\nfunc (a byServiceMethod) Len() int           { return len(a) }\nfunc (a byServiceMethod) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a byServiceMethod) Less(i, j int) bool { return a[i].sm < a[j].sm }\n\nfunc (p *Plugin) Manifest(host string) []byte {\n\tvar buf bytes.Buffer\n\n\t\/\/ Sort for consistent order on output.\n\tsort.Sort(byServiceMethod(p.pluginSpecs))\n\tescape := strings.NewReplacer(\"'\", \"''\").Replace\n\n\tprevPath := \"\"\n\tfor _, spec := range p.pluginSpecs {\n\t\tpath := spec.path()\n\t\tif path != prevPath {\n\t\t\tif prevPath != \"\" {\n\t\t\t\tfmt.Fprintf(&buf, \"\\\\ )\")\n\t\t\t}\n\t\t\tfmt.Fprintf(&buf, \"call remote#host#RegisterPlugin('%s', '%s', [\\n\", host, path)\n\t\t\tprevPath = path\n\t\t}\n\n\t\tsync := \"0\"\n\t\tif spec.Sync {\n\t\t\tsync = \"1\"\n\t\t}\n\n\t\tfmt.Fprintf(&buf, \"\\\\ {'type': '%s', 'name': '%s', 'sync': %s, 'opts': {\", spec.Type, spec.Name, sync)\n\n\t\tvar keys []string\n\t\tfor k := range spec.Opts {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Strings(keys)\n\n\t\toptDelim := \"\"\n\t\tfor _, k := range keys {\n\t\t\tfmt.Fprintf(&buf, \"%s'%s': '%s'\", optDelim, k, escape(spec.Opts[k]))\n\t\t\toptDelim = \", \"\n\t\t}\n\n\t\tfmt.Fprintf(&buf, \"}},\\n\")\n\t}\n\tif prevPath != \"\" {\n\t\tfmt.Fprintf(&buf, \"\\\\ ])\\n\")\n\t}\n\treturn buf.Bytes()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage oci\n\nimport (\n\tspecs \"github.com\/opencontainers\/runtime-spec\/specs-go\"\n)\n\nfunc defaultMounts() []specs.Mount {\n\treturn []specs.Mount{\n\t\t{\n\t\t\tDestination: \"\/proc\",\n\t\t\tType:        \"procfs\",\n\t\t\tSource:      \"proc\",\n\t\t\tOptions:     []string{\"nosuid\", \"noexec\"},\n\t\t},\n\t\t{\n\t\t\tDestination: \"\/dev\",\n\t\t\tType:        \"devfs\",\n\t\t\tSource:      \"devfs\",\n\t\t\tOptions:     []string{},\n\t\t},\n\t\t{\n\t\t\tDestination: \"\/dev\/fd\",\n\t\t\tType:        \"fdescfs\",\n\t\t\tSource:      \"fdescfs\",\n\t\t\tOptions:     []string{},\n\t\t},\n\t\t{\n\t\t\tDestination: \"\/dev\/mqueue\",\n\t\t\tType:        \"mqueue\",\n\t\t\tSource:      \"mqueue\",\n\t\t\tOptions:     []string{\"nosuid\", \"noexec\"},\n\t\t},\n\t\t{\n\t\t\tDestination: \"\/dev\/shm\",\n\t\t\tType:        \"tmpfs\",\n\t\t\tSource:      \"shm\",\n\t\t\tOptions:     []string{\"nosuid\", \"noexec\", \"mode=1777\"},\n\t\t},\n\t}\n}\n<commit_msg>Remove mountpoints not commonly mounted on FreeBSD<commit_after>\/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage oci\n\nimport (\n\tspecs \"github.com\/opencontainers\/runtime-spec\/specs-go\"\n)\n\nfunc defaultMounts() []specs.Mount {\n\treturn []specs.Mount{\n\t\t{\n\t\t\tDestination: \"\/dev\",\n\t\t\tType:        \"devfs\",\n\t\t\tSource:      \"devfs\",\n\t\t\tOptions:     []string{},\n\t\t},\n\t\t{\n\t\t\tDestination: \"\/dev\/fd\",\n\t\t\tType:        \"fdescfs\",\n\t\t\tSource:      \"fdescfs\",\n\t\t\tOptions:     []string{},\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package auction_cell_rep\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com\/cloudfoundry-incubator\/auction\/auctiontypes\"\n\t\"github.com\/cloudfoundry-incubator\/executor\"\n\t\"github.com\/cloudfoundry-incubator\/rep\"\n\tBbs \"github.com\/cloudfoundry-incubator\/runtime-schema\/bbs\"\n\t\"github.com\/cloudfoundry-incubator\/runtime-schema\/models\"\n\t\"github.com\/pivotal-golang\/lager\"\n)\n\ntype AuctionCellRep struct {\n\tcellID                string\n\tstack                 string\n\tgenerateContainerGuid func() (string, error)\n\tbbs                   Bbs.RepBBS\n\tclient                executor.Client\n\tlogger                lager.Logger\n}\n\nfunc New(cellID string, stack string, generateContainerGuid func() (string, error), bbs Bbs.RepBBS, client executor.Client, logger lager.Logger) *AuctionCellRep {\n\treturn &AuctionCellRep{\n\t\tcellID: cellID,\n\t\tstack:  stack,\n\t\tgenerateContainerGuid: generateContainerGuid,\n\t\tbbs:    bbs,\n\t\tclient: client,\n\t\tlogger: logger.Session(\"auction-delegate\"),\n\t}\n}\n\nfunc (a *AuctionCellRep) State() (auctiontypes.CellState, error) {\n\tlogger := a.logger.Session(\"auction-state\")\n\tlogger.Info(\"providing\")\n\n\ttotalResources, err := a.fetchResourcesVia(a.client.TotalResources)\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-get-total-resources\", err)\n\t\treturn auctiontypes.CellState{}, err\n\t}\n\n\tavailableResources, err := a.fetchResourcesVia(a.client.RemainingResources)\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-get-remaining-resource\", err)\n\t\treturn auctiontypes.CellState{}, err\n\t}\n\n\tlrpContainers, err := a.client.ListContainers(executor.Tags{\n\t\trep.LifecycleTag: rep.LRPLifecycle,\n\t})\n\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-fetch-containers\", err)\n\t\treturn auctiontypes.CellState{}, err\n\t}\n\n\tlrps := []auctiontypes.LRP{}\n\n\tfor _, container := range lrpContainers {\n\t\tindex, _ := strconv.Atoi(container.Tags[rep.ProcessIndexTag])\n\t\tlrp := auctiontypes.LRP{\n\t\t\tProcessGuid: container.Tags[rep.ProcessGuidTag],\n\t\t\tIndex:       index,\n\t\t\tMemoryMB:    container.MemoryMB,\n\t\t\tDiskMB:      container.DiskMB,\n\t\t}\n\t\tlrps = append(lrps, lrp)\n\t}\n\n\tstate := auctiontypes.CellState{\n\t\tStack:              a.stack,\n\t\tAvailableResources: availableResources,\n\t\tTotalResources:     totalResources,\n\t\tLRPs:               lrps,\n\t}\n\n\ta.logger.Session(\"provided\", lager.Data{\"state\": state})\n\n\treturn state, nil\n}\n\nfunc (a *AuctionCellRep) Perform(work auctiontypes.Work) (auctiontypes.Work, error) {\n\tvar failedWork = auctiontypes.Work{}\n\n\tlogger := a.logger.Session(\"auction-work\", lager.Data{\n\t\t\"lrp-starts\": len(work.LRPStarts),\n\t\t\"tasks\":      len(work.Tasks),\n\t})\n\n\tfor _, start := range work.LRPStarts {\n\t\tstartLogger := logger.Session(\"lrp-start-instance\", lager.Data{\n\t\t\t\"process-guid\": start.DesiredLRP.ProcessGuid,\n\t\t\t\"index\":        start.Index,\n\t\t\t\"memory-mb\":    start.DesiredLRP.MemoryMB,\n\t\t\t\"disk-mb\":      start.DesiredLRP.DiskMB,\n\t\t})\n\t\tstartLogger.Info(\"starting\")\n\t\terr := a.startLRP(start, startLogger)\n\t\tif err != nil {\n\t\t\tstartLogger.Error(\"failed-to-start\", err)\n\t\t\tfailedWork.LRPStarts = append(failedWork.LRPStarts, start)\n\t\t} else {\n\t\t\tstartLogger.Info(\"started\")\n\t\t}\n\t}\n\n\tfor _, task := range work.Tasks {\n\t\ttaskLogger := logger.Session(\"task-start\", lager.Data{\n\t\t\t\"task-guid\": task.TaskGuid,\n\t\t\t\"memory-mb\": task.MemoryMB,\n\t\t\t\"disk-mb\":   task.DiskMB,\n\t\t})\n\t\ttaskLogger.Info(\"starting\")\n\t\terr := a.startTask(task, taskLogger)\n\t\tif err != nil {\n\t\t\ttaskLogger.Error(\"failed-to-start\", err)\n\t\t\tfailedWork.Tasks = append(failedWork.Tasks, task)\n\t\t} else {\n\t\t\ttaskLogger.Info(\"started\")\n\t\t}\n\t}\n\n\treturn failedWork, nil\n}\n\nfunc (a *AuctionCellRep) startLRP(lrpStart models.LRPStart, logger lager.Logger) error {\n\n\tcontainerGuidString, err := a.generateContainerGuid()\n\tif err != nil {\n\t\tlogger.Error(\"generating-instance-guid-failed\", err)\n\t\treturn err\n\t}\n\n\tlogger = logger.WithData(lager.Data{\"instance-guid\": containerGuidString})\n\tlogger.Info(\"reserving\")\n\t_, err = a.client.AllocateContainer(executor.Container{\n\t\tGuid: containerGuidString,\n\n\t\tTags: executor.Tags{\n\t\t\trep.LifecycleTag:    rep.LRPLifecycle,\n\t\t\trep.DomainTag:       lrpStart.DesiredLRP.Domain,\n\t\t\trep.ProcessGuidTag:  lrpStart.DesiredLRP.ProcessGuid,\n\t\t\trep.ProcessIndexTag: strconv.Itoa(lrpStart.Index),\n\t\t},\n\n\t\tMemoryMB:     lrpStart.DesiredLRP.MemoryMB,\n\t\tDiskMB:       lrpStart.DesiredLRP.DiskMB,\n\t\tCPUWeight:    lrpStart.DesiredLRP.CPUWeight,\n\t\tRootFSPath:   lrpStart.DesiredLRP.RootFSPath,\n\t\tPorts:        a.convertPortMappings(lrpStart.DesiredLRP.Ports),\n\t\tStartTimeout: lrpStart.DesiredLRP.StartTimeout,\n\n\t\tLog: executor.LogConfig{\n\t\t\tGuid:       lrpStart.DesiredLRP.LogGuid,\n\t\t\tSourceName: lrpStart.DesiredLRP.LogSource,\n\t\t\tIndex:      &lrpStart.Index,\n\t\t},\n\n\t\tSetup:   lrpStart.DesiredLRP.Setup,\n\t\tAction:  lrpStart.DesiredLRP.Action,\n\t\tMonitor: lrpStart.DesiredLRP.Monitor,\n\n\t\tEnv: append([]executor.EnvironmentVariable{\n\t\t\t{Name: \"INSTANCE_GUID\", Value: containerGuidString},\n\t\t\t{Name: \"INSTANCE_INDEX\", Value: strconv.Itoa(lrpStart.Index)},\n\t\t}, executor.EnvironmentVariablesFromModel(lrpStart.DesiredLRP.EnvironmentVariables)...),\n\t})\n\n\tif err != nil {\n\t\tlogger.Error(\"failed-reserving\", err)\n\t\treturn err\n\t}\n\tlogger.Info(\"succeeded-reserving\")\n\n\tgo func() {\n\t\tlrpKey := models.NewActualLRPKey(\n\t\t\tlrpStart.DesiredLRP.ProcessGuid,\n\t\t\tlrpStart.Index,\n\t\t\tlrpStart.DesiredLRP.Domain,\n\t\t)\n\t\tlrpContainerKey := models.NewActualLRPContainerKey(\n\t\t\tcontainerGuidString,\n\t\t\ta.cellID,\n\t\t)\n\n\t\tlogger.Info(\"announcing-to-bbs\")\n\t\tclaimErr := a.bbs.ClaimActualLRP(lrpKey, lrpContainerKey, logger)\n\t\tif claimErr != nil {\n\t\t\tlogger.Error(\"failed-announcing-to-bbs\", claimErr)\n\t\t\ta.client.DeleteContainer(containerGuidString)\n\t\t\treturn\n\t\t}\n\t\tlogger.Info(\"succeeded-announcing-to-bbs\")\n\n\t\tlogger.Info(\"running-container\")\n\t\trunErr := a.client.RunContainer(containerGuidString)\n\t\tif runErr != nil {\n\t\t\tlogger.Error(\"failed-running-container\", runErr)\n\t\t\ta.client.DeleteContainer(containerGuidString)\n\t\t\ta.bbs.RemoveActualLRP(lrpKey, lrpContainerKey, logger)\n\t\t}\n\t\tlogger.Info(\"succeeded-running-container\")\n\t}()\n\n\treturn nil\n}\n\nfunc (a *AuctionCellRep) startTask(task models.Task, logger lager.Logger) error {\n\tif task.Stack != a.stack {\n\t\treturn errors.New(fmt.Sprintf(\"stack mismatch: task requested stack '%s', rep provides stack '%s'\", task.Stack, a.stack))\n\t}\n\n\tlogger.Info(\"allocating-container\")\n\t_, err := a.client.AllocateContainer(executor.Container{\n\t\tGuid: task.TaskGuid,\n\n\t\tTags: executor.Tags{\n\t\t\trep.LifecycleTag:  rep.TaskLifecycle,\n\t\t\trep.DomainTag:     task.Domain,\n\t\t\trep.ResultFileTag: task.ResultFile,\n\t\t},\n\n\t\tDiskMB:     task.DiskMB,\n\t\tMemoryMB:   task.MemoryMB,\n\t\tCPUWeight:  task.CPUWeight,\n\t\tRootFSPath: task.RootFSPath,\n\t\tLog: executor.LogConfig{\n\t\t\tGuid:       task.LogGuid,\n\t\t\tSourceName: task.LogSource,\n\t\t},\n\n\t\tAction: task.Action,\n\n\t\tEnv: executor.EnvironmentVariablesFromModel(task.EnvironmentVariables),\n\t})\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-allocate-container\", err)\n\t\treturn err\n\t}\n\tlogger.Info(\"successfully-allocated-container\")\n\n\tgo func() {\n\t\tlogger.Info(\"starting-task\")\n\t\terr = a.bbs.StartTask(task.TaskGuid, a.cellID)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed-to-mark-task-started\", err)\n\t\t\ta.client.DeleteContainer(task.TaskGuid)\n\t\t\treturn\n\t\t}\n\t\tlogger.Info(\"successfully-started-task\")\n\n\t\tlogger.Info(\"running-task\")\n\t\terr = a.client.RunContainer(task.TaskGuid)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed-to-run-task\", err)\n\t\t\ta.client.DeleteContainer(task.TaskGuid)\n\t\t\ta.markTaskAsFailed(logger, task.TaskGuid, err)\n\t\t\treturn\n\t\t}\n\t\tlogger.Info(\"successfully-ran-task\")\n\t}()\n\n\treturn nil\n}\n\nfunc (a *AuctionCellRep) convertPortMappings(containerPorts []uint32) []executor.PortMapping {\n\tout := []executor.PortMapping{}\n\tfor _, port := range containerPorts {\n\t\tout = append(out, executor.PortMapping{\n\t\t\tContainerPort: port,\n\t\t})\n\t}\n\n\treturn out\n}\n\nfunc (a *AuctionCellRep) fetchResourcesVia(fetcher func() (executor.ExecutorResources, error)) (auctiontypes.Resources, error) {\n\tresources, err := fetcher()\n\tif err != nil {\n\t\treturn auctiontypes.Resources{}, err\n\t}\n\treturn auctiontypes.Resources{\n\t\tMemoryMB:   resources.MemoryMB,\n\t\tDiskMB:     resources.DiskMB,\n\t\tContainers: resources.Containers,\n\t}, nil\n}\n\nfunc (a *AuctionCellRep) markTaskAsFailed(logger lager.Logger, taskGuid string, err error) {\n\tlogger.Info(\"complete-task\")\n\terr = a.bbs.CompleteTask(taskGuid, true, \"failed to run container - \"+err.Error(), \"\")\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-complete-task\", err)\n\t}\n\tlogger.Info(\"successfully-completed-task\")\n}\n<commit_msg>Add missing return statement<commit_after>package auction_cell_rep\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com\/cloudfoundry-incubator\/auction\/auctiontypes\"\n\t\"github.com\/cloudfoundry-incubator\/executor\"\n\t\"github.com\/cloudfoundry-incubator\/rep\"\n\tBbs \"github.com\/cloudfoundry-incubator\/runtime-schema\/bbs\"\n\t\"github.com\/cloudfoundry-incubator\/runtime-schema\/models\"\n\t\"github.com\/pivotal-golang\/lager\"\n)\n\ntype AuctionCellRep struct {\n\tcellID                string\n\tstack                 string\n\tgenerateContainerGuid func() (string, error)\n\tbbs                   Bbs.RepBBS\n\tclient                executor.Client\n\tlogger                lager.Logger\n}\n\nfunc New(cellID string, stack string, generateContainerGuid func() (string, error), bbs Bbs.RepBBS, client executor.Client, logger lager.Logger) *AuctionCellRep {\n\treturn &AuctionCellRep{\n\t\tcellID: cellID,\n\t\tstack:  stack,\n\t\tgenerateContainerGuid: generateContainerGuid,\n\t\tbbs:    bbs,\n\t\tclient: client,\n\t\tlogger: logger.Session(\"auction-delegate\"),\n\t}\n}\n\nfunc (a *AuctionCellRep) State() (auctiontypes.CellState, error) {\n\tlogger := a.logger.Session(\"auction-state\")\n\tlogger.Info(\"providing\")\n\n\ttotalResources, err := a.fetchResourcesVia(a.client.TotalResources)\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-get-total-resources\", err)\n\t\treturn auctiontypes.CellState{}, err\n\t}\n\n\tavailableResources, err := a.fetchResourcesVia(a.client.RemainingResources)\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-get-remaining-resource\", err)\n\t\treturn auctiontypes.CellState{}, err\n\t}\n\n\tlrpContainers, err := a.client.ListContainers(executor.Tags{\n\t\trep.LifecycleTag: rep.LRPLifecycle,\n\t})\n\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-fetch-containers\", err)\n\t\treturn auctiontypes.CellState{}, err\n\t}\n\n\tlrps := []auctiontypes.LRP{}\n\n\tfor _, container := range lrpContainers {\n\t\tindex, _ := strconv.Atoi(container.Tags[rep.ProcessIndexTag])\n\t\tlrp := auctiontypes.LRP{\n\t\t\tProcessGuid: container.Tags[rep.ProcessGuidTag],\n\t\t\tIndex:       index,\n\t\t\tMemoryMB:    container.MemoryMB,\n\t\t\tDiskMB:      container.DiskMB,\n\t\t}\n\t\tlrps = append(lrps, lrp)\n\t}\n\n\tstate := auctiontypes.CellState{\n\t\tStack:              a.stack,\n\t\tAvailableResources: availableResources,\n\t\tTotalResources:     totalResources,\n\t\tLRPs:               lrps,\n\t}\n\n\ta.logger.Session(\"provided\", lager.Data{\"state\": state})\n\n\treturn state, nil\n}\n\nfunc (a *AuctionCellRep) Perform(work auctiontypes.Work) (auctiontypes.Work, error) {\n\tvar failedWork = auctiontypes.Work{}\n\n\tlogger := a.logger.Session(\"auction-work\", lager.Data{\n\t\t\"lrp-starts\": len(work.LRPStarts),\n\t\t\"tasks\":      len(work.Tasks),\n\t})\n\n\tfor _, start := range work.LRPStarts {\n\t\tstartLogger := logger.Session(\"lrp-start-instance\", lager.Data{\n\t\t\t\"process-guid\": start.DesiredLRP.ProcessGuid,\n\t\t\t\"index\":        start.Index,\n\t\t\t\"memory-mb\":    start.DesiredLRP.MemoryMB,\n\t\t\t\"disk-mb\":      start.DesiredLRP.DiskMB,\n\t\t})\n\t\tstartLogger.Info(\"starting\")\n\t\terr := a.startLRP(start, startLogger)\n\t\tif err != nil {\n\t\t\tstartLogger.Error(\"failed-to-start\", err)\n\t\t\tfailedWork.LRPStarts = append(failedWork.LRPStarts, start)\n\t\t} else {\n\t\t\tstartLogger.Info(\"started\")\n\t\t}\n\t}\n\n\tfor _, task := range work.Tasks {\n\t\ttaskLogger := logger.Session(\"task-start\", lager.Data{\n\t\t\t\"task-guid\": task.TaskGuid,\n\t\t\t\"memory-mb\": task.MemoryMB,\n\t\t\t\"disk-mb\":   task.DiskMB,\n\t\t})\n\t\ttaskLogger.Info(\"starting\")\n\t\terr := a.startTask(task, taskLogger)\n\t\tif err != nil {\n\t\t\ttaskLogger.Error(\"failed-to-start\", err)\n\t\t\tfailedWork.Tasks = append(failedWork.Tasks, task)\n\t\t} else {\n\t\t\ttaskLogger.Info(\"started\")\n\t\t}\n\t}\n\n\treturn failedWork, nil\n}\n\nfunc (a *AuctionCellRep) startLRP(lrpStart models.LRPStart, logger lager.Logger) error {\n\n\tcontainerGuidString, err := a.generateContainerGuid()\n\tif err != nil {\n\t\tlogger.Error(\"generating-instance-guid-failed\", err)\n\t\treturn err\n\t}\n\n\tlogger = logger.WithData(lager.Data{\"instance-guid\": containerGuidString})\n\tlogger.Info(\"reserving\")\n\t_, err = a.client.AllocateContainer(executor.Container{\n\t\tGuid: containerGuidString,\n\n\t\tTags: executor.Tags{\n\t\t\trep.LifecycleTag:    rep.LRPLifecycle,\n\t\t\trep.DomainTag:       lrpStart.DesiredLRP.Domain,\n\t\t\trep.ProcessGuidTag:  lrpStart.DesiredLRP.ProcessGuid,\n\t\t\trep.ProcessIndexTag: strconv.Itoa(lrpStart.Index),\n\t\t},\n\n\t\tMemoryMB:     lrpStart.DesiredLRP.MemoryMB,\n\t\tDiskMB:       lrpStart.DesiredLRP.DiskMB,\n\t\tCPUWeight:    lrpStart.DesiredLRP.CPUWeight,\n\t\tRootFSPath:   lrpStart.DesiredLRP.RootFSPath,\n\t\tPorts:        a.convertPortMappings(lrpStart.DesiredLRP.Ports),\n\t\tStartTimeout: lrpStart.DesiredLRP.StartTimeout,\n\n\t\tLog: executor.LogConfig{\n\t\t\tGuid:       lrpStart.DesiredLRP.LogGuid,\n\t\t\tSourceName: lrpStart.DesiredLRP.LogSource,\n\t\t\tIndex:      &lrpStart.Index,\n\t\t},\n\n\t\tSetup:   lrpStart.DesiredLRP.Setup,\n\t\tAction:  lrpStart.DesiredLRP.Action,\n\t\tMonitor: lrpStart.DesiredLRP.Monitor,\n\n\t\tEnv: append([]executor.EnvironmentVariable{\n\t\t\t{Name: \"INSTANCE_GUID\", Value: containerGuidString},\n\t\t\t{Name: \"INSTANCE_INDEX\", Value: strconv.Itoa(lrpStart.Index)},\n\t\t}, executor.EnvironmentVariablesFromModel(lrpStart.DesiredLRP.EnvironmentVariables)...),\n\t})\n\n\tif err != nil {\n\t\tlogger.Error(\"failed-reserving\", err)\n\t\treturn err\n\t}\n\tlogger.Info(\"succeeded-reserving\")\n\n\tgo func() {\n\t\tlrpKey := models.NewActualLRPKey(\n\t\t\tlrpStart.DesiredLRP.ProcessGuid,\n\t\t\tlrpStart.Index,\n\t\t\tlrpStart.DesiredLRP.Domain,\n\t\t)\n\t\tlrpContainerKey := models.NewActualLRPContainerKey(\n\t\t\tcontainerGuidString,\n\t\t\ta.cellID,\n\t\t)\n\n\t\tlogger.Info(\"announcing-to-bbs\")\n\t\tclaimErr := a.bbs.ClaimActualLRP(lrpKey, lrpContainerKey, logger)\n\t\tif claimErr != nil {\n\t\t\tlogger.Error(\"failed-announcing-to-bbs\", claimErr)\n\t\t\ta.client.DeleteContainer(containerGuidString)\n\t\t\treturn\n\t\t}\n\t\tlogger.Info(\"succeeded-announcing-to-bbs\")\n\n\t\tlogger.Info(\"running-container\")\n\t\trunErr := a.client.RunContainer(containerGuidString)\n\t\tif runErr != nil {\n\t\t\tlogger.Error(\"failed-running-container\", runErr)\n\t\t\ta.client.DeleteContainer(containerGuidString)\n\t\t\ta.bbs.RemoveActualLRP(lrpKey, lrpContainerKey, logger)\n\t\t\treturn\n\t\t}\n\t\tlogger.Info(\"succeeded-running-container\")\n\t}()\n\n\treturn nil\n}\n\nfunc (a *AuctionCellRep) startTask(task models.Task, logger lager.Logger) error {\n\tif task.Stack != a.stack {\n\t\treturn errors.New(fmt.Sprintf(\"stack mismatch: task requested stack '%s', rep provides stack '%s'\", task.Stack, a.stack))\n\t}\n\n\tlogger.Info(\"allocating-container\")\n\t_, err := a.client.AllocateContainer(executor.Container{\n\t\tGuid: task.TaskGuid,\n\n\t\tTags: executor.Tags{\n\t\t\trep.LifecycleTag:  rep.TaskLifecycle,\n\t\t\trep.DomainTag:     task.Domain,\n\t\t\trep.ResultFileTag: task.ResultFile,\n\t\t},\n\n\t\tDiskMB:     task.DiskMB,\n\t\tMemoryMB:   task.MemoryMB,\n\t\tCPUWeight:  task.CPUWeight,\n\t\tRootFSPath: task.RootFSPath,\n\t\tLog: executor.LogConfig{\n\t\t\tGuid:       task.LogGuid,\n\t\t\tSourceName: task.LogSource,\n\t\t},\n\n\t\tAction: task.Action,\n\n\t\tEnv: executor.EnvironmentVariablesFromModel(task.EnvironmentVariables),\n\t})\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-allocate-container\", err)\n\t\treturn err\n\t}\n\tlogger.Info(\"successfully-allocated-container\")\n\n\tgo func() {\n\t\tlogger.Info(\"starting-task\")\n\t\terr = a.bbs.StartTask(task.TaskGuid, a.cellID)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed-to-mark-task-started\", err)\n\t\t\ta.client.DeleteContainer(task.TaskGuid)\n\t\t\treturn\n\t\t}\n\t\tlogger.Info(\"successfully-started-task\")\n\n\t\tlogger.Info(\"running-task\")\n\t\terr = a.client.RunContainer(task.TaskGuid)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed-to-run-task\", err)\n\t\t\ta.client.DeleteContainer(task.TaskGuid)\n\t\t\ta.markTaskAsFailed(logger, task.TaskGuid, err)\n\t\t\treturn\n\t\t}\n\t\tlogger.Info(\"successfully-ran-task\")\n\t}()\n\n\treturn nil\n}\n\nfunc (a *AuctionCellRep) convertPortMappings(containerPorts []uint32) []executor.PortMapping {\n\tout := []executor.PortMapping{}\n\tfor _, port := range containerPorts {\n\t\tout = append(out, executor.PortMapping{\n\t\t\tContainerPort: port,\n\t\t})\n\t}\n\n\treturn out\n}\n\nfunc (a *AuctionCellRep) fetchResourcesVia(fetcher func() (executor.ExecutorResources, error)) (auctiontypes.Resources, error) {\n\tresources, err := fetcher()\n\tif err != nil {\n\t\treturn auctiontypes.Resources{}, err\n\t}\n\treturn auctiontypes.Resources{\n\t\tMemoryMB:   resources.MemoryMB,\n\t\tDiskMB:     resources.DiskMB,\n\t\tContainers: resources.Containers,\n\t}, nil\n}\n\nfunc (a *AuctionCellRep) markTaskAsFailed(logger lager.Logger, taskGuid string, err error) {\n\tlogger.Info(\"complete-task\")\n\terr = a.bbs.CompleteTask(taskGuid, true, \"failed to run container - \"+err.Error(), \"\")\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-complete-task\", err)\n\t}\n\tlogger.Info(\"successfully-completed-task\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package authentication\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\/\/ \"github.com\/stuphlabs\/pullcord\"\n\t\"testing\"\n)\n\nfunc TestBadIdentifier(t *testing.T) {\n\tidentifier := \"test_user\"\n\tpassword := \"SuperAwes0meP@ssword\"\n\n\tstore := InMemPwdStore{}\n\terr := store.CheckPassword(identifier, password)\n\n\tassert.Error(t, err)\n\tassert.Equal(t, NoSuchIdentifierError, err)\n}\n\nfunc TestGoodPassword(t *testing.T) {\n\tidentifier := \"test_user\"\n\tpassword := \"SuperAwes0meP@ssword\"\n\n\thashStruct, err := GetPbkdf2Hash(password, Pbkdf2MinIterations)\n\tassert.NoError(t, err)\n\tstore := InMemPwdStore{\n\t\tmap[string]*Pbkdf2Hash{\n\t\t\tidentifier: hashStruct,\n\t\t},\n\t}\n\n\terr = store.CheckPassword(identifier, password)\n\tassert.NoError(t, err)\n}\n\nfunc TestBadPassword(t *testing.T) {\n\tidentifier := \"test_user\"\n\tpassword := \"SuperAwes0meP@ssword\"\n\tbadPassword := \"someOtherPassword\"\n\n\thashStruct, err := GetPbkdf2Hash(password, Pbkdf2MinIterations)\n\tassert.NoError(t, err)\n\tstore := InMemPwdStore{\n\t\tmap[string]*Pbkdf2Hash{\n\t\t\tidentifier: hashStruct,\n\t\t},\n\t}\n\n\terr = store.CheckPassword(identifier, badPassword)\n\tassert.Error(t, err)\n\tassert.Equal(t, BadPasswordError, err)\n}\n\nfunc TestGoodPasswordFromHash(t *testing.T) {\n\tidentifier := \"test_user\"\n\tpassword := \"SuperAwes0meP@ssword\"\n\tjsonData := `{\n\t\t\"test_user\": {\n\t\t\t\"Salt\": \"RMM0WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ==\",\n\t\t\t\"Iterations\" : 4096,\n\t\t\t\"Hash\": \"3Ezu0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t}\n\t}`\n\n\tvar store InMemPwdStore\n\terr := json.Unmarshal([]byte(jsonData), &store)\n\tassert.NoError(t, err)\n\n\terr = store.CheckPassword(identifier, password)\n\tassert.NoError(t, err)\n}\n\nfunc TestBadPasswordFromHash(t *testing.T) {\n\tidentifier := \"test_user\"\n\tpassword := \"someOtherPassword\"\n\tjsonData := `{\n\t\t\"test_user\": {\n\t\t\t\"Salt\": \"RMM0WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ==\",\n\t\t\t\"Iterations\": 4096,\n\t\t\t\"Hash\": \"3Ezu0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t}\n\t}`\n\n\tvar store InMemPwdStore\n\terr := json.Unmarshal([]byte(jsonData), &store)\n\tassert.NoError(t, err)\n\n\terr = store.CheckPassword(identifier, password)\n\tassert.Error(t, err)\n\tassert.Equal(t, BadPasswordError, err)\n}\n\nfunc TestInsufficientIterationsHash(t *testing.T) {\n\tjsonData := `{\n\t\t\"test_user\": {\n\t\t\t\"Salt\": \"RMM0WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ==\",\n\t\t\t\"Iterations\": 4095,\n\t\t\t\"Hash\": \"3Ezu0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t}\n\t}`\n\n\tvar store InMemPwdStore\n\terr := json.Unmarshal([]byte(jsonData), &store)\n\tassert.Error(t, err)\n\tassert.Equal(t, InsufficientIterationsError, err)\n}\n\nfunc TestInsufficientIterations(t *testing.T) {\n\t\/\/identifier := \"test_user\"\n\tpassword := \"SuperAwes0meP@ssword\"\n\titerations := Pbkdf2MinIterations - 1\n\n\t_, err := GetPbkdf2Hash(password, iterations)\n\tassert.Error(t, err)\n\tassert.Equal(t, InsufficientIterationsError, err)\n}\n\nfunc TestIncorrectSaltLengthError(t *testing.T) {\n\tjsonData := `{\n\t\t\"test_user\": {\n\t\t\t\"Salt\": \"WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ==\",\n\t\t\t\"Iterations\": 4096,\n\t\t\t\"Hash\": \"3Ezu0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t}\n\t}`\n\n\tvar store InMemPwdStore\n\terr := json.Unmarshal([]byte(jsonData), &store)\n\tassert.Error(t, err)\n\tassert.Equal(t, IncorrectSaltLengthError, err)\n}\n\nfunc TestIncorrectHashLengthError(t *testing.T) {\n\tjsonData := `{\n\t\t\"test_user\": {\n\t\t\t\"Salt\": \"RMM0WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ==\",\n\t\t\t\"Iterations\": 4096,\n\t\t\t\"Hash\": \"0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t}\n\t}`\n\n\tvar store InMemPwdStore\n\terr := json.Unmarshal([]byte(jsonData), &store)\n\tassert.Error(t, err)\n\tassert.Equal(t, IncorrectHashLengthError, err)\n}\n\nfunc TestBadBase64Error(t *testing.T) {\n\t\/\/identifier := \"test_user\"\n\tjsonData := `{\n\t\t\"test_user\": {\n\t\t\t\"Salt\": \"RMM0WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ\",\n\t\t\t\"Iterations\": 4096,\n\t\t\t\"Hash\": \"3Ezu0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t}\n\t}`\n\n\tvar store InMemPwdStore\n\terr := json.Unmarshal([]byte(jsonData), &store)\n\tassert.Error(t, err)\n}\n\n<commit_msg>Adding config tests, which gets us to coverage of all of the InMemPwdStore except handling of errors from crypto\/rand.Read().<commit_after>package authentication\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/fitstar\/falcore\"\n\t\"github.com\/proidiot\/gone\/errors\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stuphlabs\/pullcord\/config\"\n\tconfigutil \"github.com\/stuphlabs\/pullcord\/config\/util\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestBadIdentifier(t *testing.T) {\n\tidentifier := \"test_user\"\n\tpassword := \"SuperAwes0meP@ssword\"\n\n\tstore := InMemPwdStore{}\n\terr := store.CheckPassword(identifier, password)\n\n\tassert.Error(t, err)\n\tassert.Equal(t, NoSuchIdentifierError, err)\n}\n\nfunc TestGoodPassword(t *testing.T) {\n\tidentifier := \"test_user\"\n\tpassword := \"SuperAwes0meP@ssword\"\n\n\thashStruct, err := GetPbkdf2Hash(password, Pbkdf2MinIterations)\n\tassert.NoError(t, err)\n\tstore := InMemPwdStore{\n\t\tmap[string]*Pbkdf2Hash{\n\t\t\tidentifier: hashStruct,\n\t\t},\n\t}\n\n\terr = store.CheckPassword(identifier, password)\n\tassert.NoError(t, err)\n}\n\nfunc TestBadPassword(t *testing.T) {\n\tidentifier := \"test_user\"\n\tpassword := \"SuperAwes0meP@ssword\"\n\tbadPassword := \"someOtherPassword\"\n\n\thashStruct, err := GetPbkdf2Hash(password, Pbkdf2MinIterations)\n\tassert.NoError(t, err)\n\tstore := InMemPwdStore{\n\t\tmap[string]*Pbkdf2Hash{\n\t\t\tidentifier: hashStruct,\n\t\t},\n\t}\n\n\terr = store.CheckPassword(identifier, badPassword)\n\tassert.Error(t, err)\n\tassert.Equal(t, BadPasswordError, err)\n}\n\nfunc TestGoodPasswordFromHash(t *testing.T) {\n\tidentifier := \"test_user\"\n\tpassword := \"SuperAwes0meP@ssword\"\n\tjsonData := `{\n\t\t\"test_user\": {\n\t\t\t\"Salt\": \"RMM0WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ==\",\n\t\t\t\"Iterations\" : 4096,\n\t\t\t\"Hash\": \"3Ezu0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t}\n\t}`\n\n\tvar store InMemPwdStore\n\terr := json.Unmarshal([]byte(jsonData), &store)\n\tassert.NoError(t, err)\n\n\terr = store.CheckPassword(identifier, password)\n\tassert.NoError(t, err)\n}\n\nfunc TestBadPasswordFromHash(t *testing.T) {\n\tidentifier := \"test_user\"\n\tpassword := \"someOtherPassword\"\n\tjsonData := `{\n\t\t\"test_user\": {\n\t\t\t\"Salt\": \"RMM0WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ==\",\n\t\t\t\"Iterations\": 4096,\n\t\t\t\"Hash\": \"3Ezu0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t}\n\t}`\n\n\tvar store InMemPwdStore\n\terr := json.Unmarshal([]byte(jsonData), &store)\n\tassert.NoError(t, err)\n\n\terr = store.CheckPassword(identifier, password)\n\tassert.Error(t, err)\n\tassert.Equal(t, BadPasswordError, err)\n}\n\nfunc TestInsufficientIterationsHash(t *testing.T) {\n\tjsonData := `{\n\t\t\"test_user\": {\n\t\t\t\"Salt\": \"RMM0WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ==\",\n\t\t\t\"Iterations\": 4095,\n\t\t\t\"Hash\": \"3Ezu0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t}\n\t}`\n\n\tvar store InMemPwdStore\n\terr := json.Unmarshal([]byte(jsonData), &store)\n\tassert.Error(t, err)\n\tassert.Equal(t, InsufficientIterationsError, err)\n}\n\nfunc TestInsufficientIterations(t *testing.T) {\n\t\/\/identifier := \"test_user\"\n\tpassword := \"SuperAwes0meP@ssword\"\n\titerations := Pbkdf2MinIterations - 1\n\n\t_, err := GetPbkdf2Hash(password, iterations)\n\tassert.Error(t, err)\n\tassert.Equal(t, InsufficientIterationsError, err)\n}\n\nfunc TestIncorrectSaltLengthError(t *testing.T) {\n\tjsonData := `{\n\t\t\"test_user\": {\n\t\t\t\"Salt\": \"WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ==\",\n\t\t\t\"Iterations\": 4096,\n\t\t\t\"Hash\": \"3Ezu0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t}\n\t}`\n\n\tvar store InMemPwdStore\n\terr := json.Unmarshal([]byte(jsonData), &store)\n\tassert.Error(t, err)\n\tassert.Equal(t, IncorrectSaltLengthError, err)\n}\n\nfunc TestIncorrectHashLengthError(t *testing.T) {\n\tjsonData := `{\n\t\t\"test_user\": {\n\t\t\t\"Salt\": \"RMM0WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ==\",\n\t\t\t\"Iterations\": 4096,\n\t\t\t\"Hash\": \"0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t}\n\t}`\n\n\tvar store InMemPwdStore\n\terr := json.Unmarshal([]byte(jsonData), &store)\n\tassert.Error(t, err)\n\tassert.Equal(t, IncorrectHashLengthError, err)\n}\n\nfunc TestBadBase64Error(t *testing.T) {\n\t\/\/identifier := \"test_user\"\n\tjsonData := `{\n\t\t\"test_user\": {\n\t\t\t\"Salt\": \"RMM0WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ\",\n\t\t\t\"Iterations\": 4096,\n\t\t\t\"Hash\": \"3Ezu0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t}\n\t}`\n\n\tvar store InMemPwdStore\n\terr := json.Unmarshal([]byte(jsonData), &store)\n\tassert.Error(t, err)\n}\n\nfunc TestInMemPwdStoreFromConfig(t *testing.T) {\n\ttype testStruct struct {\n\t\tvalidator func(json.Unmarshaler) error\n\t\tdata string\n\t\tserverValidate func(*falcore.Server, error)\n\t}\n\n\ttestData := []testStruct {\n\t\ttestStruct {\n\t\t\tfunc(i json.Unmarshaler) error {\n\t\t\t\treturn errors.New(\n\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\"Not expecting validator to\" +\n\t\t\t\t\t\t\" actually run, but it was\" +\n\t\t\t\t\t\t\" run with: %v\",\n\t\t\t\t\t\ti,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t},\n\t\t\t``,\n\t\t\tfunc(s *falcore.Server, e error) {\n\t\t\t\tassert.Error(\n\t\t\t\t\tt,\n\t\t\t\t\te,\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing an incomplete\" +\n\t\t\t\t\t\" validator resource should produce\" +\n\t\t\t\t\t\" an error.\",\n\t\t\t\t)\n\t\t\t\tif e != nil {\n\t\t\t\tassert.False(\n\t\t\t\t\tt,\n\t\t\t\t\tstrings.HasPrefix(\n\t\t\t\t\t\te.Error(),\n\t\t\t\t\t\t\"Not expecting validator to\" +\n\t\t\t\t\t\t\" actually run\",\n\t\t\t\t\t),\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing an incomplete\" +\n\t\t\t\t\t\" validator resource should produce\" +\n\t\t\t\t\t\" an error apart from any created by\" +\n\t\t\t\t\t\" the validator.\",\n\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tassert.Nil(\n\t\t\t\t\tt,\n\t\t\t\t\ts,\n\t\t\t\t\t\"A server created from a config\" +\n\t\t\t\t\t\" containing an incomplete validator\" +\n\t\t\t\t\t\" resource should be nil.\",\n\t\t\t\t)\n\t\t\t},\n\t\t},\n\t\ttestStruct {\n\t\t\tfunc(i json.Unmarshaler) error {\n\t\t\t\treturn errors.New(\n\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\"Not expecting validator to\" +\n\t\t\t\t\t\t\" actually run, but it was\" +\n\t\t\t\t\t\t\" run with: %v\",\n\t\t\t\t\t\ti,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t},\n\t\t\t`{\n\t\t\t\t\"type\": \"inmempwdstore\",\n\t\t\t\t\"data\": [\"test_user\"]\n\t\t\t}`,\n\t\t\tfunc(s *falcore.Server, e error) {\n\t\t\t\tassert.Error(\n\t\t\t\t\tt,\n\t\t\t\t\te,\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing an incomplete\" +\n\t\t\t\t\t\" inmempwdstore resource should\" +\n\t\t\t\t\t\" produce an error.\",\n\t\t\t\t)\n\t\t\t\tif e != nil {\n\t\t\t\tassert.False(\n\t\t\t\t\tt,\n\t\t\t\t\tstrings.HasPrefix(\n\t\t\t\t\t\te.Error(),\n\t\t\t\t\t\t\"Not expecting validator to\" +\n\t\t\t\t\t\t\" actually run\",\n\t\t\t\t\t),\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing an incomplete\" +\n\t\t\t\t\t\" validator resource should produce\" +\n\t\t\t\t\t\" an error apart from any created by\" +\n\t\t\t\t\t\" the validator.\",\n\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tassert.Nil(\n\t\t\t\t\tt,\n\t\t\t\t\ts,\n\t\t\t\t\t\"A server created from a config\" +\n\t\t\t\t\t\" containing an incomplete\" +\n\t\t\t\t\t\" inmempwdstore resource should\" +\n\t\t\t\t\t\" be nil.\",\n\t\t\t\t)\n\t\t\t},\n\t\t},\n\t\ttestStruct {\n\t\t\tfunc(i json.Unmarshaler) error {\n\t\t\t\treturn errors.New(\n\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\"Not expecting validator to\" +\n\t\t\t\t\t\t\" actually run, but it was\" +\n\t\t\t\t\t\t\" run with: %v\",\n\t\t\t\t\t\ti,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t},\n\t\t\t`{\n\t\t\t\t\"type\": \"inmempwdstore\",\n\t\t\t\t\"data\": {\n\t\t\t\t\t\"test_user\": {}\n\t\t\t\t}\n\t\t\t}`,\n\t\t\tfunc(s *falcore.Server, e error) {\n\t\t\t\tassert.Error(\n\t\t\t\t\tt,\n\t\t\t\t\te,\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing an invalid\" +\n\t\t\t\t\t\" nested resource should produce an\" +\n\t\t\t\t\t\" error.\",\n\t\t\t\t)\n\t\t\t\tif e != nil {\n\t\t\t\tassert.False(\n\t\t\t\t\tt,\n\t\t\t\t\tstrings.HasPrefix(\n\t\t\t\t\t\te.Error(),\n\t\t\t\t\t\t\"Not expecting validator to\" +\n\t\t\t\t\t\t\" actually run\",\n\t\t\t\t\t),\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing an invalid\" +\n\t\t\t\t\t\" nested resource should produce an\" +\n\t\t\t\t\t\" error apart from any created by\" +\n\t\t\t\t\t\" the validator.\",\n\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tassert.Nil(\n\t\t\t\t\tt,\n\t\t\t\t\ts,\n\t\t\t\t\t\"A server created from a config\" +\n\t\t\t\t\t\" containing an invalid nested\" +\n\t\t\t\t\t\" resource should be nil.\",\n\t\t\t\t)\n\t\t\t},\n\t\t},\n\t\ttestStruct {\n\t\t\tfunc(i json.Unmarshaler) error {\n\t\t\t\tswitch i := i.(type) {\n\t\t\t\tcase *InMemPwdStore:\n\t\t\t\t\t\/\/ do nothing\n\t\t\t\tdefault:\n\t\t\t\t\treturn errors.New(\n\t\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\t\"Expecting\" +\n\t\t\t\t\t\t\t\" unmarsheled\" +\n\t\t\t\t\t\t\t\" resource to be a\" +\n\t\t\t\t\t\t\t\" inmempwdstore,\" +\n\t\t\t\t\t\t\t\" but instead got: %v\",\n\t\t\t\t\t\t\ti,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\t`{\n\t\t\t\t\"type\": \"inmempwdstore\",\n\t\t\t\t\"data\": {\n\t\t\t\t\t\"test_user\": {\n\t\t\t\t\t\t\"salt\": \"RMM0WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ==\",\n\t\t\t\t\t\t\"iterations\": 4096,\n\t\t\t\t\t\t\"hash\": \"3Ezu0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}`,\n\t\t\tfunc(s *falcore.Server, e error) {\n\t\t\t\tassert.NoError(\n\t\t\t\t\tt,\n\t\t\t\t\te,\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing only a passing\" +\n\t\t\t\t\t\" validator resource should not\" +\n\t\t\t\t\t\" produce an error. The most likely\" +\n\t\t\t\t\t\" explanation is that the validator\" +\n\t\t\t\t\t\" resource is not passing.\",\n\t\t\t\t)\n\t\t\t\tassert.NotNil(\n\t\t\t\t\tt,\n\t\t\t\t\ts,\n\t\t\t\t\t\"A server created from a config\" +\n\t\t\t\t\t\" containing only a\" +\n\t\t\t\t\t\" passing validator resource should\" +\n\t\t\t\t\t\" not be nil. The most likely\" +\n\t\t\t\t\t\" explanation is that the validator\" +\n\t\t\t\t\t\" resource is not passing.\",\n\t\t\t\t)\n\t\t\t},\n\t\t},\n\t\ttestStruct {\n\t\t\tfunc(i json.Unmarshaler) error {\n\t\t\t\tswitch i := i.(type) {\n\t\t\t\tcase *InMemPwdStore:\n\t\t\t\t\t\/\/ do nothing\n\t\t\t\tdefault:\n\t\t\t\t\treturn errors.New(\n\t\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\t\"Expecting\" +\n\t\t\t\t\t\t\t\" unmarsheled\" +\n\t\t\t\t\t\t\t\" resource to be a\" +\n\t\t\t\t\t\t\t\" inmempwdstore,\" +\n\t\t\t\t\t\t\t\" but instead got: %v\",\n\t\t\t\t\t\t\ti,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\t`{\n\t\t\t\t\"type\": \"inmempwdstore\",\n\t\t\t\t\"data\": {\n\t\t\t\t\t\"test_user\": {\n\t\t\t\t\t\t\"salt\": 7,\n\t\t\t\t\t\t\"iterations\": 4096,\n\t\t\t\t\t\t\"hash\": -5\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}`,\n\t\t\tfunc(s *falcore.Server, e error) {\n\t\t\t\tassert.Error(\n\t\t\t\t\tt,\n\t\t\t\t\te,\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing a nested\" +\n\t\t\t\t\t\" resource with the wrong type\" +\n\t\t\t\t\t\" should produce an error.\",\n\t\t\t\t)\n\t\t\t\tassert.Nil(\n\t\t\t\t\tt,\n\t\t\t\t\ts,\n\t\t\t\t\t\"A server created from a config\" +\n\t\t\t\t\t\" containing a nested resource with\" +\n\t\t\t\t\t\" the wrong type should be nil.\",\n\t\t\t\t)\n\t\t\t},\n\t\t},\n\t\ttestStruct {\n\t\t\tfunc(i json.Unmarshaler) error {\n\t\t\t\tswitch i := i.(type) {\n\t\t\t\tcase *InMemPwdStore:\n\t\t\t\t\t\/\/ do nothing\n\t\t\t\tdefault:\n\t\t\t\t\treturn errors.New(\n\t\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\t\"Expecting\" +\n\t\t\t\t\t\t\t\" unmarsheled\" +\n\t\t\t\t\t\t\t\" resource to be a\" +\n\t\t\t\t\t\t\t\" inmempwdstore,\" +\n\t\t\t\t\t\t\t\" but instead got: %v\",\n\t\t\t\t\t\t\ti,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\t`{\n\t\t\t\t\"type\": \"inmempwdstore\",\n\t\t\t\t\"data\": {\n\t\t\t\t\t\"test_user\": {\n\t\t\t\t\t\t\"salt\": \"RMM0WEV4s0vxZWb9Yvw0ooBU1Bs9louzqNsa+\/E\/SVzZg+ez72TLoXL8pFOOzk2aOFO5XLtbSECYKUK7XtF+ZQ==\",\n\t\t\t\t\t\t\"iterations\": \"Four thousand ninety six\",,\n\t\t\t\t\t\t\"hash\": \"3Ezu0RAlDXNhkvnVq0H4z\/0dUrItfd2CyYR06u\/arA6f9XAeAA0UWWB\/9y\/0fQOVmZi7XxyiePtR\/hC33tNWXg==\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}`,\n\t\t\tfunc(s *falcore.Server, e error) {\n\t\t\t\tassert.Error(\n\t\t\t\t\tt,\n\t\t\t\t\te,\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing a nested\" +\n\t\t\t\t\t\" resource with the wrong type\" +\n\t\t\t\t\t\" should produce an error.\",\n\t\t\t\t)\n\t\t\t\tassert.Nil(\n\t\t\t\t\tt,\n\t\t\t\t\ts,\n\t\t\t\t\t\"A server created from a config\" +\n\t\t\t\t\t\" containing a nested resource with\" +\n\t\t\t\t\t\" the wrong type should be nil.\",\n\t\t\t\t)\n\t\t\t},\n\t\t},\n\t\ttestStruct {\n\t\t\tfunc(i json.Unmarshaler) error {\n\t\t\t\treturn errors.New(\n\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\"Not expecting validator to\" +\n\t\t\t\t\t\t\" actually run, but it was\" +\n\t\t\t\t\t\t\" run with: %v\",\n\t\t\t\t\t\ti,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t},\n\t\t\t`{\n\t\t\t\t\"type\": \"inmempwdstore\",\n\t\t\t\t\"data\": 42\n\t\t\t}`,\n\t\t\tfunc(s *falcore.Server, e error) {\n\t\t\t\tassert.Error(\n\t\t\t\t\tt,\n\t\t\t\t\te,\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing an invalid\" +\n\t\t\t\t\t\" inmempwdstore resource should\" +\n\t\t\t\t\t\" produce an error.\",\n\t\t\t\t)\n\t\t\t\tif e != nil {\n\t\t\t\tassert.False(\n\t\t\t\t\tt,\n\t\t\t\t\tstrings.HasPrefix(\n\t\t\t\t\t\te.Error(),\n\t\t\t\t\t\t\"Not expecting validator to\" +\n\t\t\t\t\t\t\" actually run\",\n\t\t\t\t\t),\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing an invalid\" +\n\t\t\t\t\t\" validator resource should produce\" +\n\t\t\t\t\t\" an error apart from any created by\" +\n\t\t\t\t\t\" the validator.\",\n\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tassert.Nil(\n\t\t\t\t\tt,\n\t\t\t\t\ts,\n\t\t\t\t\t\"A server created from a config\" +\n\t\t\t\t\t\" containing an invalid\" +\n\t\t\t\t\t\" inmempwdstore resource should\" +\n\t\t\t\t\t\" be nil.\",\n\t\t\t\t)\n\t\t\t},\n\t\t},\n\t\ttestStruct {\n\t\t\tfunc(i json.Unmarshaler) error {\n\t\t\t\tswitch i := i.(type) {\n\t\t\t\tcase *InMemPwdStore:\n\t\t\t\t\t\/\/ do nothing\n\t\t\t\tdefault:\n\t\t\t\t\treturn errors.New(\n\t\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\t\"Expecting\" +\n\t\t\t\t\t\t\t\" unmarsheled\" +\n\t\t\t\t\t\t\t\" resource to be a\" +\n\t\t\t\t\t\t\t\" inmempwdstore,\" +\n\t\t\t\t\t\t\t\" but instead got: %v\",\n\t\t\t\t\t\t\ti,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\t`{\n\t\t\t\t\"type\": \"inmempwdstore\",\n\t\t\t\t\"data\": {}\n\t\t\t}`,\n\t\t\tfunc(s *falcore.Server, e error) {\n\t\t\t\tassert.NoError(\n\t\t\t\t\tt,\n\t\t\t\t\te,\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing only a passing\" +\n\t\t\t\t\t\" validator resource (even if that\" +\n\t\t\t\t\t\" resource is an empty\" +\n\t\t\t\t\t\" inmempwdstore) should not  produce\" +\n\t\t\t\t\t\" an error. The most likely\" +\n\t\t\t\t\t\" explanation is that the validator\" +\n\t\t\t\t\t\" resource is not passing.\",\n\t\t\t\t)\n\t\t\t\tassert.NotNil(\n\t\t\t\t\tt,\n\t\t\t\t\ts,\n\t\t\t\t\t\"A server created from a config\" +\n\t\t\t\t\t\" containing only a passing\" +\n\t\t\t\t\t\" validator resource (even if that\" +\n\t\t\t\t\t\" resource is an empty\" +\n\t\t\t\t\t\" inmempwdstore) should  not be nil.\" +\n\t\t\t\t\t\" The most likely  explanation is\" +\n\t\t\t\t\t\" that the validator resource is not\" +\n\t\t\t\t\t\" passing.\",\n\t\t\t\t)\n\t\t\t},\n\t\t},\n\t\ttestStruct {\n\t\t\tfunc(i json.Unmarshaler) error {\n\t\t\t\treturn errors.New(\n\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\"Not expecting validator to\" +\n\t\t\t\t\t\t\" actually run, but it was\" +\n\t\t\t\t\t\t\" run with: %v\",\n\t\t\t\t\t\ti,\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t},\n\t\t\t`{\n\t\t\t\t\"type\": \"inmempwdstore\",\n\t\t\t\t\"data\": {\n\t\t\t\t\t\"test_user\": {\n\t\t\t\t\t\t\"hash\": \"hey does this look base64 to you?\",\n\t\t\t\t\t\t\"iterations\": 4096,\n\t\t\t\t\t\t\"salt\": \"maybe it's base65?\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}`,\n\t\t\tfunc(s *falcore.Server, e error) {\n\t\t\t\tassert.Error(\n\t\t\t\t\tt,\n\t\t\t\t\te,\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing an invalid\" +\n\t\t\t\t\t\" nested resource should produce an\" +\n\t\t\t\t\t\" error.\",\n\t\t\t\t)\n\t\t\t\tif e != nil {\n\t\t\t\tassert.False(\n\t\t\t\t\tt,\n\t\t\t\t\tstrings.HasPrefix(\n\t\t\t\t\t\te.Error(),\n\t\t\t\t\t\t\"Not expecting validator to\" +\n\t\t\t\t\t\t\" actually run\",\n\t\t\t\t\t),\n\t\t\t\t\t\"Attempting to create a server from\" +\n\t\t\t\t\t\" a config containing an invalid\" +\n\t\t\t\t\t\" nested resource should produce an\" +\n\t\t\t\t\t\" error apart from any created by\" +\n\t\t\t\t\t\" the validator.\",\n\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tassert.Nil(\n\t\t\t\t\tt,\n\t\t\t\t\ts,\n\t\t\t\t\t\"A server created from a config\" +\n\t\t\t\t\t\" containing an invalid nested\" +\n\t\t\t\t\t\" resource should be nil.\",\n\t\t\t\t)\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, v := range testData {\n\t\tn, e := configutil.GenerateValidator(v.validator)\n\t\tassert.NoError(\n\t\t\tt,\n\t\t\te,\n\t\t\t\"Generating a validator resource type should not\" +\n\t\t\t\" produce an error.\",\n\t\t)\n\t\tassert.NotEqual(\n\t\t\tt,\n\t\t\tn,\n\t\t\t\"\",\n\t\t\t\"A generated validator resource type should not have\" +\n\t\t\t\" an empty resource type name.\",\n\t\t)\n\n\t\ts, e := config.ServerFromReader(\n\t\t\tstrings.NewReader(\n\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t`{\n\t\t\t\t\t\t\"resources\": {\n\t\t\t\t\t\t\t\"validator\": {\n\t\t\t\t\t\t\t\t\"type\": \"%s\",\n\t\t\t\t\t\t\t\t\"data\": %s\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"pipeline\": [\"validator\"],\n\t\t\t\t\t\t\"port\": 80\n\t\t\t\t\t}`,\n\t\t\t\t\tn,\n\t\t\t\t\tv.data,\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t\tv.serverValidate(s, e)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package ar\n\nimport (\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/ test whether fileInfo implements os.FileInfo\nvar _ os.FileInfo = new(fileInfo)\n\nvar testCommon = \"!<arch>\\n\" +\n\t\"debian-binary   1385068169  0     0     100644  4         `\\n\" +\n\t\"2.0\\n\" +\n\t\"control.tar.gz  1385068169  0     0     100644  0         `\\n\"\n\nvar testCommonFileHeaders = []struct {\n\tin   string\n\twant *fileInfo\n\terr  string\n}{\n\t{\n\t\tin: \"debian-binary   1385068169  0     0     100644  4         `\\n\",\n\t\twant: &fileInfo{\n\t\t\tname:  \"debian-binary\",\n\t\t\tmtime: time.Unix(1385068169, 0),\n\t\t\tmode:  os.FileMode(0100644) & os.ModePerm,\n\t\t\tsize:  4,\n\t\t},\n\t},\n\t{\n\t\tin: \"debian-binary   1385068169  0     0     644     4         `\\n\",\n\t\twant: &fileInfo{\n\t\t\tname:  \"debian-binary\",\n\t\t\tmtime: time.Unix(1385068169, 0),\n\t\t\tmode:  os.FileMode(0644),\n\t\t\tsize:  4,\n\t\t},\n\t},\n\t{\n\t\tin:  \"debian-binary   1385068169  0     0     120644  4         `\\n\",\n\t\terr: \"feature not implemented: non-regular files\",\n\t},\n\t{\n\t\tin:  \"debian-binary   1385068169  0     0     220644  4         `\\n\",\n\t\terr: \"corrupt archive: invalid file mode\",\n\t},\n}\n\nfunc TestReadFileHeader(t *testing.T) {\n\tfor i, test := range testCommonFileHeaders {\n\t\tgot, err := readFileHeader(strings.NewReader(test.in))\n\t\tswitch {\n\t\tcase err == nil && test.err != \"\":\n\t\t\tt.Errorf(\"%d: got no err, expected err %v\", i, test.err)\n\t\t\tcontinue\n\t\tcase err != nil && test.err != err.Error():\n\t\t\tt.Errorf(\"%d: got err %q, expected err %q\", i, err, test.err)\n\t\t\tcontinue\n\t\tcase err == nil && test.err == \"\":\n\t\t\t\/\/ no error as expected\n\t\tcase err != nil && test.err == err.Error():\n\t\t\tt.Logf(\"%d: got expected error %q\", i, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !reflect.DeepEqual(got, test.want) {\n\t\t\tt.Errorf(\"%d: got %#v, expected %+v\", i, got, test.want)\n\t\t} else {\n\t\t\tt.Logf(\"%d: got %#v\", i, got)\n\t\t}\n\t}\n}\n\nfunc BenchmarkReadFileHeader(b *testing.B) {\n\tr := strings.NewReader(\"debian-binary   1385068169  0     0     100644  4         `\\n\")\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = readFileHeader(r)\n\t\tb.SetBytes(60)\n\t\tr.Seek(0, 0)\n\t}\n\n}\n\nvar testMagic = []struct {\n\tin   io.Reader\n\twant error\n}{\n\t{\n\t\tin: strings.NewReader(magic),\n\t},\n\t{\n\t\tin:   strings.NewReader(strings.Repeat(\"a\", len(magic))),\n\t\twant: CorruptArchiveError(\"global archive header not found\"),\n\t},\n\t{\n\t\tin:   strings.NewReader(\"!\"),\n\t\twant: io.ErrUnexpectedEOF,\n\t},\n\t{\n\t\tin:   strings.NewReader(\"\"),\n\t\twant: io.EOF,\n\t},\n}\n\nfunc TestReadMagic(t *testing.T) {\n\tfor i, test := range testMagic {\n\t\tgot := checkMagic(test.in)\n\t\tif !reflect.DeepEqual(got, test.want) {\n\t\t\tt.Errorf(\"%d: got %#v, expected %+v\", i, got, test.want)\n\t\t} else {\n\t\t\tt.Logf(\"%d: got %#v\", i, got)\n\t\t}\n\t}\n}\n\nfunc TestFileInfo(t *testing.T) {\n\ttest := &fileInfo{\n\t\tname:  \"debian-binary\",\n\t\tmtime: time.Unix(1385068169, 0),\n\t\tmode:  os.FileMode(0644),\n\t\tsize:  4,\n\t}\n\n\tif test.IsDir() != false {\n\t\tt.Error(\"IsDir\")\n\t}\n\tif test.Mode() != os.FileMode(0644) {\n\t\tt.Error(\"Mode\")\n\t}\n\tif test.ModTime() != time.Unix(1385068169, 0) {\n\t\tt.Error(\"ModTime\")\n\t}\n\tif test.Name() != \"debian-binary\" {\n\t\tt.Error(\"Name\")\n\t}\n\tif test.Size() != 4 {\n\t\tt.Error(\"Size\")\n\t}\n\tif test.Sys() != nil {\n\t\tt.Error(\"Sys\")\n\t}\n}\n\nfunc TestReaderBasics(t *testing.T) {\n\ttest := strings.NewReader(testCommon)\n\tr := NewReader(test)\n\tfi, err := r.Next()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t\treturn\n\t}\n\tif fi.Mode() != os.FileMode(0644) {\n\t\tt.Error(\"Mode\")\n\t}\n\tif fi.Name() != \"debian-binary\" {\n\t\tt.Error(\"Name\")\n\t}\n\tif fi.Size() != 4 {\n\t\tt.Error(\"Size\")\n\t}\n\tif fi.ModTime() != time.Unix(1385068169, 0) {\n\t\tt.Error(\"ModTime\")\n\t}\n\n\tif content, err := ioutil.ReadAll(r); err != nil {\n\t\tt.Error(err)\n\t} else if string(content) != \"2.0\\n\" {\n\t\tt.Error(\"Content\")\n\t}\n\tfi, err = r.Next()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t\treturn\n\t}\n\tif fi.Mode() != os.FileMode(0644) {\n\t\tt.Error(\"Mode2\")\n\t}\n\tif fi.Name() != \"control.tar.gz\" {\n\t\tt.Error(\"Name2\")\n\t}\n\tif fi.Size() != 0 {\n\t\tt.Error(\"Size2\")\n\t}\n\tif fi.ModTime() != time.Unix(1385068169, 0) {\n\t\tt.Error(\"ModTime2\")\n\t}\n\n\tif content, err := ioutil.ReadAll(r); err != nil {\n\t\tt.Error(err)\n\t} else if string(content) != \"\" {\n\t\tt.Error(\"Content2\")\n\t}\n\n\tfi, err = r.Next()\n\tif err != io.EOF {\n\t\tt.Errorf(\"expected EOF, got %v\", err)\n\t}\n}\n\nfunc BenchmarkReader(b *testing.B) {\n\t\/\/ contains 2 files\n\ttest := strings.NewReader(testCommon)\n\tr := NewReader(test)\n\n\tvar err error\n\tvar read int64\n\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tfor j := 0; j < 2; j++ {\n\t\t\t_, err = r.Next()\n\t\t\tif err != nil {\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tread += 60\n\t\t\tn, err := io.Copy(ioutil.Discard, r)\n\t\t\tif err != nil {\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tread += n\n\t\t}\n\t\tb.SetBytes(read)\n\t\tread = 0\n\t\ttest.Seek(0, 0)\n\t\tr.Reset(test)\n\t}\n\n}\n<commit_msg>Use bytes Reader to avoid copies.<commit_after>package ar\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/ test whether fileInfo implements os.FileInfo\nvar _ os.FileInfo = new(fileInfo)\n\nvar testCommon = \"!<arch>\\n\" +\n\t\"debian-binary   1385068169  0     0     100644  4         `\\n\" +\n\t\"2.0\\n\" +\n\t\"control.tar.gz  1385068169  0     0     100644  0         `\\n\"\n\nvar testCommonFileHeaders = []struct {\n\tin   string\n\twant *fileInfo\n\terr  string\n}{\n\t{\n\t\tin: \"debian-binary   1385068169  0     0     100644  4         `\\n\",\n\t\twant: &fileInfo{\n\t\t\tname:  \"debian-binary\",\n\t\t\tmtime: time.Unix(1385068169, 0),\n\t\t\tmode:  os.FileMode(0100644) & os.ModePerm,\n\t\t\tsize:  4,\n\t\t},\n\t},\n\t{\n\t\tin: \"debian-binary   1385068169  0     0     644     4         `\\n\",\n\t\twant: &fileInfo{\n\t\t\tname:  \"debian-binary\",\n\t\t\tmtime: time.Unix(1385068169, 0),\n\t\t\tmode:  os.FileMode(0644),\n\t\t\tsize:  4,\n\t\t},\n\t},\n\t{\n\t\tin:  \"debian-binary   1385068169  0     0     120644  4         `\\n\",\n\t\terr: \"feature not implemented: non-regular files\",\n\t},\n\t{\n\t\tin:  \"debian-binary   1385068169  0     0     220644  4         `\\n\",\n\t\terr: \"corrupt archive: invalid file mode\",\n\t},\n}\n\nfunc TestReadFileHeader(t *testing.T) {\n\tfor i, test := range testCommonFileHeaders {\n\t\tgot, err := readFileHeader(strings.NewReader(test.in))\n\t\tswitch {\n\t\tcase err == nil && test.err != \"\":\n\t\t\tt.Errorf(\"%d: got no err, expected err %v\", i, test.err)\n\t\t\tcontinue\n\t\tcase err != nil && test.err != err.Error():\n\t\t\tt.Errorf(\"%d: got err %q, expected err %q\", i, err, test.err)\n\t\t\tcontinue\n\t\tcase err == nil && test.err == \"\":\n\t\t\t\/\/ no error as expected\n\t\tcase err != nil && test.err == err.Error():\n\t\t\tt.Logf(\"%d: got expected error %q\", i, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif !reflect.DeepEqual(got, test.want) {\n\t\t\tt.Errorf(\"%d: got %#v, expected %+v\", i, got, test.want)\n\t\t} else {\n\t\t\tt.Logf(\"%d: got %#v\", i, got)\n\t\t}\n\t}\n}\n\nfunc BenchmarkReadFileHeader(b *testing.B) {\n\tr := bytes.NewReader([]byte(\"debian-binary   1385068169  0     0     100644  4         `\\n\"))\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\t_, _ = readFileHeader(r)\n\t\tb.SetBytes(60)\n\t\tr.Seek(0, 0)\n\t}\n\n}\n\nvar testMagic = []struct {\n\tin   io.Reader\n\twant error\n}{\n\t{\n\t\tin: strings.NewReader(magic),\n\t},\n\t{\n\t\tin:   strings.NewReader(strings.Repeat(\"a\", len(magic))),\n\t\twant: CorruptArchiveError(\"global archive header not found\"),\n\t},\n\t{\n\t\tin:   strings.NewReader(\"!\"),\n\t\twant: io.ErrUnexpectedEOF,\n\t},\n\t{\n\t\tin:   strings.NewReader(\"\"),\n\t\twant: io.EOF,\n\t},\n}\n\nfunc TestReadMagic(t *testing.T) {\n\tfor i, test := range testMagic {\n\t\tgot := checkMagic(test.in)\n\t\tif !reflect.DeepEqual(got, test.want) {\n\t\t\tt.Errorf(\"%d: got %#v, expected %+v\", i, got, test.want)\n\t\t} else {\n\t\t\tt.Logf(\"%d: got %#v\", i, got)\n\t\t}\n\t}\n}\n\nfunc TestFileInfo(t *testing.T) {\n\ttest := &fileInfo{\n\t\tname:  \"debian-binary\",\n\t\tmtime: time.Unix(1385068169, 0),\n\t\tmode:  os.FileMode(0644),\n\t\tsize:  4,\n\t}\n\n\tif test.IsDir() != false {\n\t\tt.Error(\"IsDir\")\n\t}\n\tif test.Mode() != os.FileMode(0644) {\n\t\tt.Error(\"Mode\")\n\t}\n\tif test.ModTime() != time.Unix(1385068169, 0) {\n\t\tt.Error(\"ModTime\")\n\t}\n\tif test.Name() != \"debian-binary\" {\n\t\tt.Error(\"Name\")\n\t}\n\tif test.Size() != 4 {\n\t\tt.Error(\"Size\")\n\t}\n\tif test.Sys() != nil {\n\t\tt.Error(\"Sys\")\n\t}\n}\n\nfunc TestReaderBasics(t *testing.T) {\n\ttest := strings.NewReader(testCommon)\n\tr := NewReader(test)\n\tfi, err := r.Next()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t\treturn\n\t}\n\tif fi.Mode() != os.FileMode(0644) {\n\t\tt.Error(\"Mode\")\n\t}\n\tif fi.Name() != \"debian-binary\" {\n\t\tt.Error(\"Name\")\n\t}\n\tif fi.Size() != 4 {\n\t\tt.Error(\"Size\")\n\t}\n\tif fi.ModTime() != time.Unix(1385068169, 0) {\n\t\tt.Error(\"ModTime\")\n\t}\n\n\tif content, err := ioutil.ReadAll(r); err != nil {\n\t\tt.Error(err)\n\t} else if string(content) != \"2.0\\n\" {\n\t\tt.Error(\"Content\")\n\t}\n\tfi, err = r.Next()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t\treturn\n\t}\n\tif fi.Mode() != os.FileMode(0644) {\n\t\tt.Error(\"Mode2\")\n\t}\n\tif fi.Name() != \"control.tar.gz\" {\n\t\tt.Error(\"Name2\")\n\t}\n\tif fi.Size() != 0 {\n\t\tt.Error(\"Size2\")\n\t}\n\tif fi.ModTime() != time.Unix(1385068169, 0) {\n\t\tt.Error(\"ModTime2\")\n\t}\n\n\tif content, err := ioutil.ReadAll(r); err != nil {\n\t\tt.Error(err)\n\t} else if string(content) != \"\" {\n\t\tt.Error(\"Content2\")\n\t}\n\n\tfi, err = r.Next()\n\tif err != io.EOF {\n\t\tt.Errorf(\"expected EOF, got %v\", err)\n\t}\n}\n\nfunc BenchmarkReader(b *testing.B) {\n\t\/\/ contains 2 files\n\ttest := bytes.NewReader([]byte(testCommon))\n\tr := NewReader(test)\n\n\tvar err error\n\tvar read int64\n\n\tb.ReportAllocs()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tfor j := 0; j < 2; j++ {\n\t\t\t_, err = r.Next()\n\t\t\tif err != nil {\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tread += 60\n\t\t\tn, err := io.Copy(ioutil.Discard, r)\n\t\t\tif err != nil {\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tread += n\n\t\t}\n\t\tb.SetBytes(read)\n\t\tread = 0\n\t\ttest.Seek(0, 0)\n\t\tr.Reset(test)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package signprocessor\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/mrjones\/oauth\"\n\t\"github.com\/zabawaba99\/fireauth\"\n\t\"github.com\/zabawaba99\/firego\"\n\n\t\"golang.org\/x\/oauth2\"\n)\n\nfunc EventLoop() {\n\tdata := make(fireauth.Data)\n\toptions := fireauth.Option{\n\t\tAdmin: true,\n\t}\n\ttoken, _ := fireauth.New(Secrets.FireBaseSecret).CreateToken(data, &options)\n\tf := firego.New(Config.FireBaseDB, nil)\n\tf.Auth(token)\n\n\tt := oauth.NewConsumer(Secrets.TwitterKey, Secrets.TwitterSecret, oauth.ServiceProvider{\n\t\tRequestTokenUrl:   \"https:\/\/api.twitter.com\/oauth\/request_token\",\n\t\tAuthorizeTokenUrl: \"https:\/\/api.twitter.com\/oauth\/authorize\",\n\t\tAccessTokenUrl:    \"https:\/\/api.twitter.com\/oauth\/access_token\",\n\t})\n\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: Secrets.GithubToken},\n\t)\n\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\tgh := github.NewClient(tc)\n\n\tnotifications := make(chan firego.Event)\n\tif err := f.Watch(notifications); err != nil {\n\t\tlog.Fatalf(\"Error setting up watch: %v\", err)\n\t}\n\n\tdefer f.StopWatching()\n\tfor event := range notifications {\n\t\tif event.Path == \"\/\" && event.Data != nil {\n\t\t\tif users, ok := event.Data.(map[string]interface{})[\"users\"]; ok {\n\t\t\t\tfor uid, d := range users.(map[string]interface{}) {\n\t\t\t\t\tdetails := d.(map[string]interface{})\n\t\t\t\t\tif process(uid, details, t, gh) {\n\t\t\t\t\t\tf.Child(\"users\").Child(uid).Remove()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if event.Type == \"put\" && strings.HasPrefix(event.Path, \"\/users\/\") {\n\t\t\tuid := strings.TrimPrefix(event.Path, \"\/users\/\")\n\t\t\tif details, ok := event.Data.(map[string]interface{}); ok {\n\t\t\t\tif process(uid, details, t, gh) {\n\t\t\t\t\tf.Child(\"users\").Child(uid).Remove()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"Notifications have stopped\\n\")\n}\n\nfunc process(uid string, details map[string]interface{}, t *oauth.Consumer, gh *github.Client) bool {\n\tlinkProfile := details[\"linkProfile\"].(bool)\n\tlink := details[\"link\"].(string)\n\tpersonalPage := details[\"personalPage\"].(string)\n\tname := details[\"name\"].(string)\n\ttitle := details[\"title\"].(string)\n\taffiliation := details[\"affiliation\"].(string)\n\n\tsecret := details[\"twitterSecret\"].(string)\n\ttoken := details[\"twitterToken\"].(string)\n\ttclient, err := t.MakeHttpClient(&oauth.AccessToken{Token: token, Secret: secret})\n\tresp, err := tclient.Get(\"https:\/\/api.twitter.com\/1.1\/account\/verify_credentials.json?skip_status=true&include_entities=false\")\n\tif err != nil {\n\t\tlog.Printf(\"Twitter API error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\tdefer resp.Body.Close()\n\n\tbits, _ := ioutil.ReadAll(resp.Body)\n\n\tvar user map[string]interface{}\n\tjson.Unmarshal(bits, &user)\n\tegg := user[\"default_profile_image\"].(bool)\n\tcreated, _ := time.Parse(time.RubyDate, user[\"created_at\"].(string))\n\tdescription := user[\"description\"].(string)\n\tfollowers := int(user[\"followers_count\"].(float64))\n\tfollowing := int(user[\"friends_count\"].(float64))\n\tdisplayName := user[\"name\"].(string)\n\thandle := user[\"screen_name\"].(string)\n\ttweets := int(user[\"statuses_count\"].(float64))\n\tvar url string\n\tswitch user[\"url\"].(type) {\n\tcase string:\n\t\turl = user[\"url\"].(string)\n\t}\n\n\tif name == \"\" {\n\t\tlog.Printf(\"No signatory name specified for %s (%s)\", uid, handle)\n\t\treturn false\n\t}\n\n\tif score := Score(handle, displayName, url, created, followers, following, tweets, egg, description, personalPage); score < 0 {\n\t\tlog.Printf(\"Not creating pull for %s (%s) due to score %d\", uid, handle, score)\n\t\treturn false\n\t}\n\n\tvar linkMd, affiliationMd, titleMd string\n\tif linkProfile {\n\t\tlinkMd = fmt.Sprintf(\"  link: https:\/\/twitter.com\/%s\\n\", handle)\n\t} else if link != \"\" {\n\t\tlinkMd = fmt.Sprintf(\"  link: %s\\n\", link)\n\t}\n\tif affiliation != \"\" {\n\t\taffiliationMd = fmt.Sprintf(\"  affiliation: \\\"%s\\\"\\n\", affiliation)\n\t}\n\tif title != \"\" {\n\t\ttitleMd = fmt.Sprintf(\"  occupation_title: \\\"%s\\\"\\n\", title)\n\t}\n\tcontents := fmt.Sprintf(\"---\\n  name: \\\"%s\\\"\\n%s%s%s---\", name, linkMd, affiliationMd, titleMd)\n\n\tbody := fmt.Sprintf(`Twitter user: https:\/\/twitter.com\/%s\nCreated: %v, Followers: %d, Following: %d, Tweets: %d, Egg: %v\n\nTwitter profile fields:\nName: %s\nWebsite: %s\nTagline: %s\n\nPersonal page: %s\n\nSignature file contents:\n%s`,\n\t\thandle,\n\t\tcreated, followers, following, tweets, egg,\n\t\tdisplayName,\n\t\turl,\n\t\tdescription,\n\t\tpersonalPage,\n\t\tfmt.Sprintf(\"```\\n%s\\n```\", contents),\n\t)\n\n\t\/\/ Ensure we are forking from a clean state.\n\tg := gh.Git\n\tref, _, err := g.GetRef(\"neveragaindottech\", \"neveragaindottech.github.io\", \"heads\/master\")\n\tif err != nil {\n\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\trefStr := fmt.Sprintf(\"heads\/signbot\/%s\", uid)\n\tref.Ref = &refStr\n\tif _, _, err = g.UpdateRef(Config.GithubUser, \"neveragaindottech.github.io\", ref, true); err != nil {\n\t\tif _, _, err = g.CreateRef(Config.GithubUser, \"neveragaindottech.github.io\", ref); err != nil {\n\t\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\t\treturn false\n\t\t}\n\t}\n\tbaseC, _, err := g.GetCommit(Config.GithubUser, \"neveragaindottech.github.io\", *ref.Object.SHA)\n\tif err != nil {\n\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\tpath := fmt.Sprintf(\"_signatures\/%s.md\", uid)\n\tmode := \"100644\"\n\tkind := \"blob\"\n\tnewT, _, err := g.CreateTree(Config.GithubUser, \"neveragaindottech.github.io\", *baseC.Tree.SHA, []github.TreeEntry{\n\t\t{Path: &path, Mode: &mode, Type: &kind, Content: &contents},\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\tdesc := fmt.Sprintf(\"SignBot: Add signatory '%s' (%s)\", name, handle)\n\tnewC, _, err := g.CreateCommit(Config.GithubUser, \"neveragaindottech.github.io\", &github.Commit{\n\t\tMessage: &desc,\n\t\tTree:    newT,\n\t\tParents: []github.Commit{*baseC},\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\tif _, _, err = g.UpdateRef(Config.GithubUser, \"neveragaindottech.github.io\", &github.Reference{\n\t\tRef: &refStr,\n\t\tObject: &github.GitObject{\n\t\t\tSHA: newC.SHA,\n\t\t},\n\t}, false); err != nil {\n\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\tp := gh.PullRequests\n\tbranchName := fmt.Sprintf(\"%s:signbot\/%s\", Config.GithubUser, uid)\n\tmaster := \"master\"\n\t_, _, err = p.Create(\"neveragaindottech\", \"neveragaindottech.github.io\", &github.NewPullRequest{\n\t\tTitle: &desc,\n\t\tHead:  &branchName,\n\t\tBase:  &master,\n\t\tBody:  &body,\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\tfmt.Printf(\"Processed %s (https:\/\/twitter.com\/%s)\\n\", uid, handle)\n\treturn true\n}\n<commit_msg>add newline after ---<commit_after>package signprocessor\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/mrjones\/oauth\"\n\t\"github.com\/zabawaba99\/fireauth\"\n\t\"github.com\/zabawaba99\/firego\"\n\n\t\"golang.org\/x\/oauth2\"\n)\n\nfunc EventLoop() {\n\tdata := make(fireauth.Data)\n\toptions := fireauth.Option{\n\t\tAdmin: true,\n\t}\n\ttoken, _ := fireauth.New(Secrets.FireBaseSecret).CreateToken(data, &options)\n\tf := firego.New(Config.FireBaseDB, nil)\n\tf.Auth(token)\n\n\tt := oauth.NewConsumer(Secrets.TwitterKey, Secrets.TwitterSecret, oauth.ServiceProvider{\n\t\tRequestTokenUrl:   \"https:\/\/api.twitter.com\/oauth\/request_token\",\n\t\tAuthorizeTokenUrl: \"https:\/\/api.twitter.com\/oauth\/authorize\",\n\t\tAccessTokenUrl:    \"https:\/\/api.twitter.com\/oauth\/access_token\",\n\t})\n\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: Secrets.GithubToken},\n\t)\n\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\tgh := github.NewClient(tc)\n\n\tnotifications := make(chan firego.Event)\n\tif err := f.Watch(notifications); err != nil {\n\t\tlog.Fatalf(\"Error setting up watch: %v\", err)\n\t}\n\n\tdefer f.StopWatching()\n\tfor event := range notifications {\n\t\tif event.Path == \"\/\" && event.Data != nil {\n\t\t\tif users, ok := event.Data.(map[string]interface{})[\"users\"]; ok {\n\t\t\t\tfor uid, d := range users.(map[string]interface{}) {\n\t\t\t\t\tdetails := d.(map[string]interface{})\n\t\t\t\t\tif process(uid, details, t, gh) {\n\t\t\t\t\t\tf.Child(\"users\").Child(uid).Remove()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if event.Type == \"put\" && strings.HasPrefix(event.Path, \"\/users\/\") {\n\t\t\tuid := strings.TrimPrefix(event.Path, \"\/users\/\")\n\t\t\tif details, ok := event.Data.(map[string]interface{}); ok {\n\t\t\t\tif process(uid, details, t, gh) {\n\t\t\t\t\tf.Child(\"users\").Child(uid).Remove()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"Notifications have stopped\\n\")\n}\n\nfunc process(uid string, details map[string]interface{}, t *oauth.Consumer, gh *github.Client) bool {\n\tlinkProfile := details[\"linkProfile\"].(bool)\n\tlink := details[\"link\"].(string)\n\tpersonalPage := details[\"personalPage\"].(string)\n\tname := details[\"name\"].(string)\n\ttitle := details[\"title\"].(string)\n\taffiliation := details[\"affiliation\"].(string)\n\n\tsecret := details[\"twitterSecret\"].(string)\n\ttoken := details[\"twitterToken\"].(string)\n\ttclient, err := t.MakeHttpClient(&oauth.AccessToken{Token: token, Secret: secret})\n\tresp, err := tclient.Get(\"https:\/\/api.twitter.com\/1.1\/account\/verify_credentials.json?skip_status=true&include_entities=false\")\n\tif err != nil {\n\t\tlog.Printf(\"Twitter API error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\tdefer resp.Body.Close()\n\n\tbits, _ := ioutil.ReadAll(resp.Body)\n\n\tvar user map[string]interface{}\n\tjson.Unmarshal(bits, &user)\n\tegg := user[\"default_profile_image\"].(bool)\n\tcreated, _ := time.Parse(time.RubyDate, user[\"created_at\"].(string))\n\tdescription := user[\"description\"].(string)\n\tfollowers := int(user[\"followers_count\"].(float64))\n\tfollowing := int(user[\"friends_count\"].(float64))\n\tdisplayName := user[\"name\"].(string)\n\thandle := user[\"screen_name\"].(string)\n\ttweets := int(user[\"statuses_count\"].(float64))\n\tvar url string\n\tswitch user[\"url\"].(type) {\n\tcase string:\n\t\turl = user[\"url\"].(string)\n\t}\n\n\tif name == \"\" {\n\t\tlog.Printf(\"No signatory name specified for %s (%s)\", uid, handle)\n\t\treturn false\n\t}\n\n\tif score := Score(handle, displayName, url, created, followers, following, tweets, egg, description, personalPage); score < 0 {\n\t\tlog.Printf(\"Not creating pull for %s (%s) due to score %d\", uid, handle, score)\n\t\treturn false\n\t}\n\n\tvar linkMd, affiliationMd, titleMd string\n\tif linkProfile {\n\t\tlinkMd = fmt.Sprintf(\"  link: https:\/\/twitter.com\/%s\\n\", handle)\n\t} else if link != \"\" {\n\t\tlinkMd = fmt.Sprintf(\"  link: %s\\n\", link)\n\t}\n\tif affiliation != \"\" {\n\t\taffiliationMd = fmt.Sprintf(\"  affiliation: \\\"%s\\\"\\n\", affiliation)\n\t}\n\tif title != \"\" {\n\t\ttitleMd = fmt.Sprintf(\"  occupation_title: \\\"%s\\\"\\n\", title)\n\t}\n\tcontents := fmt.Sprintf(\"---\\n  name: \\\"%s\\\"\\n%s%s%s---\\n\", name, linkMd, affiliationMd, titleMd)\n\n\tbody := fmt.Sprintf(`Twitter user: https:\/\/twitter.com\/%s\nCreated: %v, Followers: %d, Following: %d, Tweets: %d, Egg: %v\n\nTwitter profile fields:\nName: %s\nWebsite: %s\nTagline: %s\n\nPersonal page: %s\n\nSignature file contents:\n%s`,\n\t\thandle,\n\t\tcreated, followers, following, tweets, egg,\n\t\tdisplayName,\n\t\turl,\n\t\tdescription,\n\t\tpersonalPage,\n\t\tfmt.Sprintf(\"```\\n%s\\n```\", contents),\n\t)\n\n\t\/\/ Ensure we are forking from a clean state.\n\tg := gh.Git\n\tref, _, err := g.GetRef(\"neveragaindottech\", \"neveragaindottech.github.io\", \"heads\/master\")\n\tif err != nil {\n\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\trefStr := fmt.Sprintf(\"heads\/signbot\/%s\", uid)\n\tref.Ref = &refStr\n\tif _, _, err = g.UpdateRef(Config.GithubUser, \"neveragaindottech.github.io\", ref, true); err != nil {\n\t\tif _, _, err = g.CreateRef(Config.GithubUser, \"neveragaindottech.github.io\", ref); err != nil {\n\t\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\t\treturn false\n\t\t}\n\t}\n\tbaseC, _, err := g.GetCommit(Config.GithubUser, \"neveragaindottech.github.io\", *ref.Object.SHA)\n\tif err != nil {\n\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\tpath := fmt.Sprintf(\"_signatures\/%s.md\", uid)\n\tmode := \"100644\"\n\tkind := \"blob\"\n\tnewT, _, err := g.CreateTree(Config.GithubUser, \"neveragaindottech.github.io\", *baseC.Tree.SHA, []github.TreeEntry{\n\t\t{Path: &path, Mode: &mode, Type: &kind, Content: &contents},\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\tdesc := fmt.Sprintf(\"SignBot: Add signatory '%s' (%s)\", name, handle)\n\tnewC, _, err := g.CreateCommit(Config.GithubUser, \"neveragaindottech.github.io\", &github.Commit{\n\t\tMessage: &desc,\n\t\tTree:    newT,\n\t\tParents: []github.Commit{*baseC},\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\tif _, _, err = g.UpdateRef(Config.GithubUser, \"neveragaindottech.github.io\", &github.Reference{\n\t\tRef: &refStr,\n\t\tObject: &github.GitObject{\n\t\t\tSHA: newC.SHA,\n\t\t},\n\t}, false); err != nil {\n\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\tp := gh.PullRequests\n\tbranchName := fmt.Sprintf(\"%s:signbot\/%s\", Config.GithubUser, uid)\n\tmaster := \"master\"\n\t_, _, err = p.Create(\"neveragaindottech\", \"neveragaindottech.github.io\", &github.NewPullRequest{\n\t\tTitle: &desc,\n\t\tHead:  &branchName,\n\t\tBase:  &master,\n\t\tBody:  &body,\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"Error: %v processing %s\", err, uid)\n\t\treturn false\n\t}\n\tfmt.Printf(\"Processed %s (https:\/\/twitter.com\/%s)\\n\", uid, handle)\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>package zim\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\n\txz \"github.com\/remyoudompheng\/go-liblzma\"\n)\n\nconst (\n\tRedirectEntry   uint16 = 0xffff\n\tLinkTargetEntry        = 0xfffe\n\tDeletedEntry           = 0xfffd\n)\n\ntype Article struct {\n\tURLPtr     uint64\n\tMimetype   uint16\n\tNamespace  byte\n\tURL        string\n\tTitle      string\n\tBlob       uint32\n\tCluster    uint32\n\tRedirectTo *Article\n}\n\nfunc (z *ZimReader) FillArticleAt(a *Article, offset uint64) *Article {\n\ta.URLPtr = offset\n\n\tmimeIdx, err := readInt16(z.mmap[offset : offset+2])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ta.Mimetype = mimeIdx\n\n\t\/\/ Linktarget or Target Entry\n\tif mimeIdx == LinkTargetEntry || mimeIdx == DeletedEntry {\n\t\t\/\/TODO\n\t\treturn nil\n\t}\n\n\ta.Namespace = z.mmap[offset+3]\n\n\ta.Cluster, err = readInt32(z.mmap[offset+8 : offset+8+4])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ta.Blob, err = readInt32(z.mmap[offset+12 : offset+12+4])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Redirect\n\tif mimeIdx == RedirectEntry {\n\t\t\/\/ check for a possible loop: the redirect could point to the same target\n\t\tif z.GetUrlOffsetAtIdx(a.Cluster) != offset {\n\t\t\t\/\/ redirect ptr share the same memory offset than Cluster number\n\t\t\ta.RedirectTo = z.getArticleAt(z.GetUrlOffsetAtIdx(a.Cluster))\n\t\t}\n\n\t\tb := bytes.NewBuffer(z.mmap[offset+12:])\n\t\ta.URL, err = b.ReadString('\\x00')\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ta.URL = strings.TrimRight(string(a.URL), \"\\x00\")\n\n\t\ta.Title, err = b.ReadString('\\x00')\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ta.Title = strings.TrimRight(string(a.Title), \"\\x00\")\n\n\t\treturn a\n\t}\n\n\tb := bytes.NewBuffer(z.mmap[offset+16:])\n\ta.URL, err = b.ReadString('\\x00')\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ta.URL = strings.TrimRight(string(a.URL), \"\\x00\")\n\n\ta.Title, err = b.ReadString('\\x00')\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ta.Title = strings.TrimRight(string(a.Title), \"\\x00\")\n\n\treturn a\n}\n\n\/\/ get the article (Directory) pointed by the offset found in URLpos or Titlepos\nfunc (z *ZimReader) getArticleAt(offset uint64) *Article {\n\ta := new(Article)\n\tz.FillArticleAt(a, offset)\n\treturn a\n}\n\n\/\/ return the uncompressed data associated with this article\nfunc (a *Article) Data(z *ZimReader) []byte {\n\tstart, end := z.getClusterOffsetsAtIdx(a.Cluster)\n\tcompression := uint8(z.mmap[start])\n\n\t\/\/ LZMA\n\tif compression == 4 {\n\t\tb := bytes.NewBuffer(z.mmap[start+1 : end+1])\n\t\tdec, err := xz.NewReader(b)\n\t\tdefer dec.Close()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t\/\/ the decoded chunk are around 1MB\n\t\t\/\/ TODO: on smaller devices need to read stream rather than ReadAll\n\t\tblob, err := ioutil.ReadAll(dec)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t\/\/ blob starts at offset, blob ends at offset\n\t\tvar bs, be uint32\n\n\t\tbs, err = readInt32(blob[a.Blob*4 : a.Blob*4+4])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tbe, err = readInt32(blob[a.Blob*4+4 : a.Blob*4+4+4])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\treturn blob[bs:be]\n\t}\n\n\treturn nil\n}\n\n\/\/ return the url prefixed by the namespace\nfunc (a *Article) FullURL() string {\n\treturn string(a.Namespace) + \"\/\" + a.URL\n}\n\nfunc (a *Article) getBlobOffsetsAtIdx(z *ZimReader) (start, end uint64) {\n\tidx := a.Blob\n\toffset := z.clusterPtrPos + uint64(idx)*8\n\tstart, err := readInt64(z.mmap[offset : offset+8])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\toffset = z.clusterPtrPos + uint64(idx+1)*8\n\tend, err = readInt64(z.mmap[offset : offset+8])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}\n\nfunc (a *Article) String() string {\n\treturn fmt.Sprintf(\"Mime: 0x%x URL: [%s], Title: [%s], Cluster: 0x%x Blob: 0x%x\",\n\t\ta.Mimetype, a.URL, a.Title, a.Cluster, a.Blob)\n}\n<commit_msg>do not try to read data on redirect\/deleted entry<commit_after>package zim\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\n\txz \"github.com\/remyoudompheng\/go-liblzma\"\n)\n\nconst (\n\tRedirectEntry   uint16 = 0xffff\n\tLinkTargetEntry        = 0xfffe\n\tDeletedEntry           = 0xfffd\n)\n\ntype Article struct {\n\tURLPtr     uint64\n\tMimetype   uint16\n\tNamespace  byte\n\tURL        string\n\tTitle      string\n\tBlob       uint32\n\tCluster    uint32\n\tRedirectTo *Article\n}\n\nfunc (z *ZimReader) FillArticleAt(a *Article, offset uint64) *Article {\n\ta.URLPtr = offset\n\n\tmimeIdx, err := readInt16(z.mmap[offset : offset+2])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ta.Mimetype = mimeIdx\n\n\t\/\/ Linktarget or Target Entry\n\tif mimeIdx == LinkTargetEntry || mimeIdx == DeletedEntry {\n\t\t\/\/TODO\n\t\treturn nil\n\t}\n\n\ta.Namespace = z.mmap[offset+3]\n\n\ta.Cluster, err = readInt32(z.mmap[offset+8 : offset+8+4])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ta.Blob, err = readInt32(z.mmap[offset+12 : offset+12+4])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Redirect\n\tif mimeIdx == RedirectEntry {\n\t\t\/\/ check for a possible loop: the redirect could point to the same target\n\t\tif z.GetUrlOffsetAtIdx(a.Cluster) != offset {\n\t\t\t\/\/ redirect ptr share the same memory offset than Cluster number\n\t\t\ta.RedirectTo = z.getArticleAt(z.GetUrlOffsetAtIdx(a.Cluster))\n\t\t}\n\n\t\tb := bytes.NewBuffer(z.mmap[offset+12:])\n\t\ta.URL, err = b.ReadString('\\x00')\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ta.URL = strings.TrimRight(string(a.URL), \"\\x00\")\n\n\t\ta.Title, err = b.ReadString('\\x00')\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\ta.Title = strings.TrimRight(string(a.Title), \"\\x00\")\n\n\t\treturn a\n\t}\n\n\tb := bytes.NewBuffer(z.mmap[offset+16:])\n\ta.URL, err = b.ReadString('\\x00')\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ta.URL = strings.TrimRight(string(a.URL), \"\\x00\")\n\n\ta.Title, err = b.ReadString('\\x00')\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ta.Title = strings.TrimRight(string(a.Title), \"\\x00\")\n\n\treturn a\n}\n\n\/\/ get the article (Directory) pointed by the offset found in URLpos or Titlepos\nfunc (z *ZimReader) getArticleAt(offset uint64) *Article {\n\ta := new(Article)\n\tz.FillArticleAt(a, offset)\n\treturn a\n}\n\n\/\/ return the uncompressed data associated with this article\nfunc (a *Article) Data(z *ZimReader) []byte {\n\t\/\/ ensure we have data to read\n\tif a.Mimetype == RedirectEntry || a.Mimetype == LinkTargetEntry || a.Mimetype == DeletedEntry {\n\t\treturn nil\n\t}\n\tstart, end := z.getClusterOffsetsAtIdx(a.Cluster)\n\tcompression := uint8(z.mmap[start])\n\n\t\/\/ LZMA\n\tif compression == 4 {\n\t\tb := bytes.NewBuffer(z.mmap[start+1 : end+1])\n\t\tdec, err := xz.NewReader(b)\n\t\tdefer dec.Close()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t\/\/ the decoded chunk are around 1MB\n\t\t\/\/ TODO: on smaller devices need to read stream rather than ReadAll\n\t\tblob, err := ioutil.ReadAll(dec)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\t\/\/ blob starts at offset, blob ends at offset\n\t\tvar bs, be uint32\n\n\t\tbs, err = readInt32(blob[a.Blob*4 : a.Blob*4+4])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tbe, err = readInt32(blob[a.Blob*4+4 : a.Blob*4+4+4])\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\treturn blob[bs:be]\n\t}\n\n\treturn nil\n}\n\n\/\/ return the url prefixed by the namespace\nfunc (a *Article) FullURL() string {\n\treturn string(a.Namespace) + \"\/\" + a.URL\n}\n\nfunc (a *Article) getBlobOffsetsAtIdx(z *ZimReader) (start, end uint64) {\n\tidx := a.Blob\n\toffset := z.clusterPtrPos + uint64(idx)*8\n\tstart, err := readInt64(z.mmap[offset : offset+8])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\toffset = z.clusterPtrPos + uint64(idx+1)*8\n\tend, err = readInt64(z.mmap[offset : offset+8])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}\n\nfunc (a *Article) String() string {\n\treturn fmt.Sprintf(\"Mime: 0x%x URL: [%s], Title: [%s], Cluster: 0x%x Blob: 0x%x\",\n\t\ta.Mimetype, a.URL, a.Title, a.Cluster, a.Blob)\n}\n<|endoftext|>"}
{"text":"<commit_before>package dummy\n\nimport \"fmt\"\n\ntype MinimumError struct {\n\tDefined, Specified float64\n}\n\nfunc (err MinimumError) Error() string {\n\treturn fmt.Sprintf(\"MinimumError: %f is defined as minimum, but specified %f\", err.Defined, err.Specified)\n}\n\nfunc Minimum(defined float64, specified interface{}) error {\n\tif specified < defined {\n\t\treturn MinimuError{defined, specified}\n\t}\n\treturn nil\n}\n\ntype MaximumError struct {\n\tDefined, Specified float64\n}\n\nfunc (err MaximumError) Error() string {\n\treturn fmt.Sprintf(\"MaximumError: %f is defined as maximum, but specified %f\", err.Defined, err.Specified)\n}\n\nfunc Minimum(defined float64, specified interface{}) error {\n\tif specified > defined {\n\t\treturn MaximumError{defined, specified}\n\t}\n\treturn nil\n}\n\ntype MaxItemsError struct {\n\tMax    int\n\tLength int\n}\n\nfunc (err MaxItemsError) Error() string {\n\treturn fmt.Sprintf(\"MaxItemError: %d is defined as max, but actual %d\", err.Max, err.Length)\n}\n\nfunc MaxItems(max int, items []interface{}) error {\n\tlength := len(items)\n\tif length > max {\n\t\treturn MaxItemsError{max, length}\n\t}\n\treturn nil\n}\n\ntype MinItemError struct {\n\tMin    int\n\tLength int\n}\n\nfunc (err MinItemsError) Error() string {\n\treturn fmt.Sprintf(\"MinItemError: %d is defined as max, but actual %d\", err.Min, err.Length)\n}\n\nfunc MinItems(min int, items []interface{}) error {\n\tlength := len(items)\n\tif length < min {\n\t\treturn MinItemsError{min, length}\n\t}\n\treturn nil\n}\n\ntype UniqueItemError struct {\n\tItem interface{}\n}\n\nfunc (err UniqueItemError) Error() string {\n\treturn fmt.Sprintf(\"UniqueItemError: %v is duplicated\", err.Item)\n}\n\nfunc UniqueItems(items []interface{}) error {\n\tfor i, item := range items {\n\t\trests := items[i+1:]\n\t\tfor _, rest := range rests {\n\t\t\tif item == rest {\n\t\t\t\treturn UniqueItemError{item}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Fix typo<commit_after>package dummy\n\nimport \"fmt\"\n\ntype MaximumError struct {\n\tDefined, Specified float64\n}\n\nfunc (err MaximumError) Error() string {\n\treturn fmt.Sprintf(\"MaximumError: %f is defined as maximum, but specified %f\", err.Defined, err.Specified)\n}\n\nfunc Maximum(defined float64, specified interface{}) error {\n\tif specified > defined {\n\t\treturn MaximumError{defined, specified}\n\t}\n\treturn nil\n}\n\ntype MinimumError struct {\n\tDefined, Specified float64\n}\n\nfunc (err MinimumError) Error() string {\n\treturn fmt.Sprintf(\"MinimumError: %f is defined as minimum, but specified %f\", err.Defined, err.Specified)\n}\n\nfunc Minimum(defined float64, specified interface{}) error {\n\tif specified < defined {\n\t\treturn MinimuError{defined, specified}\n\t}\n\treturn nil\n}\n\ntype MaxItemsError struct {\n\tMax    int\n\tLength int\n}\n\nfunc (err MaxItemsError) Error() string {\n\treturn fmt.Sprintf(\"MaxItemError: %d is defined as max, but actual %d\", err.Max, err.Length)\n}\n\nfunc MaxItems(max int, items []interface{}) error {\n\tlength := len(items)\n\tif length > max {\n\t\treturn MaxItemsError{max, length}\n\t}\n\treturn nil\n}\n\ntype MinItemError struct {\n\tMin    int\n\tLength int\n}\n\nfunc (err MinItemsError) Error() string {\n\treturn fmt.Sprintf(\"MinItemError: %d is defined as max, but actual %d\", err.Min, err.Length)\n}\n\nfunc MinItems(min int, items []interface{}) error {\n\tlength := len(items)\n\tif length < min {\n\t\treturn MinItemsError{min, length}\n\t}\n\treturn nil\n}\n\ntype UniqueItemError struct {\n\tItem interface{}\n}\n\nfunc (err UniqueItemError) Error() string {\n\treturn fmt.Sprintf(\"UniqueItemError: %v is duplicated\", err.Item)\n}\n\nfunc UniqueItems(items []interface{}) error {\n\tfor i, item := range items {\n\t\trests := items[i+1:]\n\t\tfor _, rest := range rests {\n\t\t\tif item == rest {\n\t\t\t\treturn UniqueItemError{item}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/tendermint\/abci\/client\"\n\t\"github.com\/tendermint\/abci\/types\"\n\t. \"github.com\/tendermint\/go-common\"\n\t\"github.com\/urfave\/cli\"\n)\n\n\/\/structure for data passed to print response\n\/\/ variables must be exposed for JSON to read\ntype response struct {\n\tRes       types.Result\n\tData      string\n\tPrintCode bool\n\tCode      string\n}\n\nfunc newResponse(res types.Result, data string, printCode bool) *response {\n\trsp := &response{\n\t\tRes:       res,\n\t\tData:      data,\n\t\tPrintCode: printCode,\n\t\tCode:      \"\",\n\t}\n\n\tif printCode {\n\t\trsp.Code = res.Code.String()\n\t}\n\n\treturn rsp\n}\n\n\/\/ client is a global variable so it can be reused by the console\nvar client abcicli.Client\n\nfunc main() {\n\n\t\/\/workaround for the cli library (https:\/\/github.com\/urfave\/cli\/issues\/565)\n\tcli.OsExiter = func(_ int) {}\n\n\tapp := cli.NewApp()\n\tapp.Name = \"bft-cli\"\n\tapp.Usage = \"bft-cli [command] [args...]\"\n\tapp.Version = \"0.0.1\"\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"address\",\n\t\t\tValue: \"tcp:\/\/127.0.0.1:46658\",\n\t\t\tUsage: \"address of application socket\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"bft\",\n\t\t\tValue: \"socket\",\n\t\t\tUsage: \"socket or grpc\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"verbose\",\n\t\t\tUsage: \"print the command and results as if it were a console session\",\n\t\t},\n\t\t\/*cli.StringFlag{\n      \t\tName: \"lang\",\n      \t\tValue: \"english\",\n      \t\tUsage: \"language for the greeting\",\n    \t},*\/\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:  \"batch\",\n\t\t\tUsage: \"Run a batch of bft commands against an application\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdBatch(app, c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"console\",\n\t\t\tUsage: \"Start an interactive bft console for multiple commands\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdConsole(app, c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"echo\",\n\t\t\tUsage: \"Have the application echo a message\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdEcho(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"info\",\n\t\t\tUsage: \"Get some info about the application\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdInfo(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"set_option\",\n\t\t\tUsage: \"Set an option on the application\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdSetOption(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"publish_bftx\",\t\t\/\/\"deliver_tx\",\n\t\t\tUsage: \"Deliver a new bftx to application\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdDeliverTx(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"check_bftx\",\n\t\t\tUsage: \"Validate a bftx\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdCheckTx(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"commit\",\n\t\t\tUsage: \"Commit the application state and return the Merkle root hash\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdCommit(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"query\",\n\t\t\tUsage: \"Query application state\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdQuery(c)\n\t\t\t},\n\t\t},\n\t}\n\tapp.Before = before\n\terr := app.Run(os.Args)\n\tif err != nil {\n\t\tExit(err.Error())\n\t}\n\n}\n\nfunc before(c *cli.Context) error {\n\tintroduction(c)\n\tif client == nil {\n\t\tvar err error\n\t\tclient, err = abcicli.NewClient(c.GlobalString(\"address\"), c.GlobalString(\"bft\"), false)\n\t\tif err != nil {\n\t\t\tExit(err.Error())\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ badCmd is called when we invoke with an invalid first argument (just for console for now)\nfunc badCmd(c *cli.Context, cmd string) {\n\tfmt.Println(\"Unknown command:\", cmd)\n\tfmt.Println(\"Please try one of the following:\")\n\tfmt.Println(\"\")\n\tcli.DefaultAppComplete(c)\n}\n\n\/\/Generates new Args array based off of previous call args to maintain flag persistence\nfunc persistentArgs(line []byte) []string {\n\n\t\/\/generate the arguments to run from orginal os.Args\n\t\/\/ to maintain flag arguments\n\targs := os.Args\n\targs = args[:len(args)-1] \/\/ remove the previous command argument\n\n\tif len(line) > 0 { \/\/prevents introduction of extra space leading to argument parse errors\n\t\targs = append(args, strings.Split(string(line), \" \")...)\n\t}\n\treturn args\n}\n\n\/\/--------------------------------------------------------------------------------\n\nfunc cmdBatch(app *cli.App, c *cli.Context) error {\n\tbufReader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tline, more, err := bufReader.ReadLine()\n\t\tif more {\n\t\t\treturn errors.New(\"Input line is too long\")\n\t\t} else if err == io.EOF {\n\t\t\tbreak\n\t\t} else if len(line) == 0 {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\targs := persistentArgs(line)\n\t\tapp.Run(args) \/\/cli prints error within its func call\n\t}\n\treturn nil\n}\n\nfunc cmdConsole(app *cli.App, c *cli.Context) error {\n\t\/\/ don't hard exit on mistyped commands (eg. check vs check_tx)\n\tapp.CommandNotFound = badCmd\n\n\tfor {\n\t\tfmt.Printf(\"\\n> \")\n\t\tbufReader := bufio.NewReader(os.Stdin)\n\t\tline, more, err := bufReader.ReadLine()\n\t\tif more {\n\t\t\treturn errors.New(\"Input is too long\")\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\targs := persistentArgs(line)\n\t\tapp.Run(args) \/\/cli prints error within its func call\n\t}\n}\n\n\/\/ Have the application echo a message\nfunc cmdEcho(c *cli.Context) error {\n\targs := c.Args()\n\tif len(args) != 1 {\n\t\treturn errors.New(\"Command echo takes 1 argument\")\n\t}\n\tres := client.EchoSync(args[0])\n\trsp := newResponse(res, string(res.Data), false)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/ Get some info from the application\nfunc cmdInfo(c *cli.Context) error {\n\tresInfo, err := client.InfoSync()\n\tif err != nil {\n\t\treturn err\n\t}\n\trsp := newResponse(types.Result{}, string(resInfo.Data), false)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/ Set an option on the application\nfunc cmdSetOption(c *cli.Context) error {\n\targs := c.Args()\n\tif len(args) != 2 {\n\t\treturn errors.New(\"Command set_option takes 2 arguments (key, value)\")\n\t}\n\tres := client.SetOptionSync(args[0], args[1])\n\trsp := newResponse(res, Fmt(\"%s=%s\", args[0], args[1]), false)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/ Append a new tx to application\nfunc cmdDeliverTx(c *cli.Context) error {\n\targs := c.Args()\n\tif len(args) != 1 {\n\t\treturn errors.New(\"Command deliver_tx takes 1 argument\")\n\t}\n\ttxBytes, err := stringOrHexToBytes(c.Args()[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tres := client.DeliverTxSync(txBytes)\n\trsp := newResponse(res, string(res.Data), true)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/ Validate a tx\nfunc cmdCheckTx(c *cli.Context) error {\n\targs := c.Args()\n\tif len(args) != 1 {\n\t\treturn errors.New(\"Command check_tx takes 1 argument\")\n\t}\n\ttxBytes, err := stringOrHexToBytes(c.Args()[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tres := client.CheckTxSync(txBytes)\n\trsp := newResponse(res, string(res.Data), true)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/ Get application Merkle root hash\nfunc cmdCommit(c *cli.Context) error {\n\tres := client.CommitSync()\n\trsp := newResponse(res, Fmt(\"0x%X\", res.Data), false)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/ Query application state\nfunc cmdQuery(c *cli.Context) error {\n\targs := c.Args()\n\tif len(args) != 1 {\n\t\treturn errors.New(\"Command query takes 1 argument\")\n\t}\n\tqueryBytes, err := stringOrHexToBytes(c.Args()[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tres := client.QuerySync(queryBytes)\n\trsp := newResponse(res, string(res.Data), true)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/--------------------------------------------------------------------------------\n\nfunc printResponse(c *cli.Context, rsp *response) {\n\n\tverbose := c.GlobalBool(\"verbose\")\n\n\tif verbose {\n\t\tfmt.Println(\">\", c.Command.Name, strings.Join(c.Args(), \" \"))\n\t}\n\n\tif rsp.PrintCode {\n\t\tfmt.Printf(\"-> code: %s\\n\", rsp.Code)\n\t}\n\n\t\/\/if pr.res.Error != \"\" {\n\t\/\/\tfmt.Printf(\"-> error: %s\\n\", pr.res.Error)\n\t\/\/}\n\n\tif rsp.Data != \"\" {\n\t\tfmt.Printf(\"-> blockfreight data: %s\\n\", rsp.Data)\n\t}\n\tif rsp.Res.Log != \"\" {\n\t\tfmt.Printf(\"-> log: %s\\n\", rsp.Res.Log)\n\t}\n\n\tif verbose {\n\t\tfmt.Println(\"\")\n\t}\n\n}\n\n\/\/ NOTE: s is interpreted as a string unless prefixed with 0x\nfunc stringOrHexToBytes(s string) ([]byte, error) {\n\tif len(s) > 2 && strings.ToLower(s[:2]) == \"0x\" {\n\t\tb, err := hex.DecodeString(s[2:])\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Error decoding hex argument: %s\", err.Error())\n\t\t\treturn nil, err\n\t\t}\n\t\treturn b, nil\n\t}\n\n\tif !strings.HasPrefix(s, \"\\\"\") || !strings.HasSuffix(s, \"\\\"\") {\n\t\terr := fmt.Errorf(\"Invalid string arg: \\\"%s\\\". Must be quoted or a \\\"0x\\\"-prefixed hex string\", s)\n\t\treturn nil, err\n\t}\n\n\treturn []byte(s[1 : len(s)-1]), nil\n}\n\nfunc introduction (c *cli.Context) {\n\tfmt.Println(\"\\n...........................................\")\n\tfmt.Println(\"Blockfreight™ Go App\")\n\tfmt.Println(\"Address \"+c.GlobalString(\"address\"))\n\tfmt.Println(\"BFT Implementation:  \"+c.GlobalString(\"bft\"))\n\tfmt.Println(\"...........................................\\n\")\n\t\/*name := \"Blockfreight Community\"\n    if c.NArg() > 0 {\n      name = c.Args().Get(0)\n    }\n    if c.String(\"lang\") == \"ES\" {\t\/\/ISO 639-1\n      fmt.Println(\"Hola\", name)\n    } else {\n      fmt.Println(\"Hello\", name)\n    }*\/\n}<commit_msg>Modify publish_bftx and query giving []byte as parameter from reading JSON<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/tendermint\/abci\/client\"\n\t\"github.com\/tendermint\/abci\/types\"\n\t. \"github.com\/tendermint\/go-common\"\n\t\"github.com\/urfave\/cli\"\n\t\"github.com\/blockfreight\/blockfreight-alpha\/blockfreight\/bft\/validator\"\n)\n\n\/\/structure for data passed to print response\n\/\/ variables must be exposed for JSON to read\ntype response struct {\n\tRes       types.Result\n\tData      string\n\tPrintCode bool\n\tCode      string\n}\n\nfunc newResponse(res types.Result, data string, printCode bool) *response {\n\trsp := &response{\n\t\tRes:       res,\n\t\tData:      data,\n\t\tPrintCode: printCode,\n\t\tCode:      \"\",\n\t}\n\n\tif printCode {\n\t\trsp.Code = res.Code.String()\n\t}\n\n\treturn rsp\n}\n\n\/\/ client is a global variable so it can be reused by the console\nvar client abcicli.Client\n\nfunc main() {\n\n\t\/\/workaround for the cli library (https:\/\/github.com\/urfave\/cli\/issues\/565)\n\tcli.OsExiter = func(_ int) {}\n\n\tapp := cli.NewApp()\n\tapp.Name = \"bft-cli\"\n\tapp.Usage = \"bft-cli [command] [args...]\"\n\tapp.Version = \"0.0.1\"\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"address\",\n\t\t\tValue: \"tcp:\/\/127.0.0.1:46658\",\n\t\t\tUsage: \"address of application socket\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"bft\",\n\t\t\tValue: \"socket\",\n\t\t\tUsage: \"socket or grpc\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"verbose\",\n\t\t\tUsage: \"print the command and results as if it were a console session\",\n\t\t},\n\t\t\/*cli.StringFlag{\n      \t\tName: \"lang\",\n      \t\tValue: \"english\",\n      \t\tUsage: \"language for the greeting\",\n    \t},*\/\n    \tcli.StringFlag{\n      \t\tName: \"json_path\",\n      \t\tValue: \".\/files\/bf_tx_example.json\",\n      \t\tUsage: \"define the source path where the json is\",\n    \t},\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:  \"batch\",\n\t\t\tUsage: \"Run a batch of bft commands against an application\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdBatch(app, c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"console\",\n\t\t\tUsage: \"Start an interactive bft console for multiple commands\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdConsole(app, c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"echo\",\n\t\t\tUsage: \"Have the application echo a message\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdEcho(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"info\",\n\t\t\tUsage: \"Get some info about the application\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdInfo(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"set_option\",\n\t\t\tUsage: \"Set an option on the application\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdSetOption(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"publish_bftx\",\t\t\/\/\"deliver_tx\",\n\t\t\tUsage: \"Deliver a new bftx to application\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdDeliverTx(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"check_bftx\",\n\t\t\tUsage: \"Validate a bftx\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdCheckTx(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"commit\",\n\t\t\tUsage: \"Commit the application state and return the Merkle root hash\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdCommit(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"query\",\n\t\t\tUsage: \"Query application state\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdQuery(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"validate_bol\",\n\t\t\tUsage: \"Verify the structure of the bill of lading\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn cmdValidateBol(c)\n\t\t\t},\n\t\t},\n\t}\n\tapp.Before = before\n\terr := app.Run(os.Args)\n\tif err != nil {\n\t\tExit(err.Error())\n\t}\n\n}\n\nfunc before(c *cli.Context) error {\n\tintroduction(c)\n\tif client == nil {\n\t\tvar err error\n\t\tclient, err = abcicli.NewClient(c.GlobalString(\"address\"), c.GlobalString(\"bft\"), false)\n\t\tif err != nil {\n\t\t\tExit(err.Error())\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ badCmd is called when we invoke with an invalid first argument (just for console for now)\nfunc badCmd(c *cli.Context, cmd string) {\n\tfmt.Println(\"Unknown command:\", cmd)\n\tfmt.Println(\"Please try one of the following:\")\n\tfmt.Println(\"\")\n\tcli.DefaultAppComplete(c)\n}\n\n\/\/Generates new Args array based off of previous call args to maintain flag persistence\nfunc persistentArgs(line []byte) []string {\n\n\t\/\/generate the arguments to run from orginal os.Args\n\t\/\/ to maintain flag arguments\n\targs := os.Args\n\targs = args[:len(args)-1] \/\/ remove the previous command argument\n\n\tif len(line) > 0 { \/\/prevents introduction of extra space leading to argument parse errors\n\t\targs = append(args, strings.Split(string(line), \" \")...)\n\t}\n\treturn args\n}\n\n\/\/--------------------------------------------------------------------------------\n\nfunc cmdBatch(app *cli.App, c *cli.Context) error {\n\tbufReader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tline, more, err := bufReader.ReadLine()\n\t\tif more {\n\t\t\treturn errors.New(\"Input line is too long\")\n\t\t} else if err == io.EOF {\n\t\t\tbreak\n\t\t} else if len(line) == 0 {\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\targs := persistentArgs(line)\n\t\tapp.Run(args) \/\/cli prints error within its func call\n\t}\n\treturn nil\n}\n\nfunc cmdConsole(app *cli.App, c *cli.Context) error {\n\t\/\/ don't hard exit on mistyped commands (eg. check vs check_tx)\n\tapp.CommandNotFound = badCmd\n\n\tfor {\n\t\tfmt.Printf(\"\\n> \")\n\t\tbufReader := bufio.NewReader(os.Stdin)\n\t\tline, more, err := bufReader.ReadLine()\n\t\tif more {\n\t\t\treturn errors.New(\"Input is too long\")\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\targs := persistentArgs(line)\n\t\tapp.Run(args) \/\/cli prints error within its func call\n\t}\n}\n\n\/\/ Have the application echo a message\nfunc cmdEcho(c *cli.Context) error {\n\targs := c.Args()\n\tif len(args) != 1 {\n\t\treturn errors.New(\"Command echo takes 1 argument\")\n\t}\n\tres := client.EchoSync(args[0])\n\trsp := newResponse(res, string(res.Data), false)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/ Get some info from the application\nfunc cmdInfo(c *cli.Context) error {\n\tresInfo, err := client.InfoSync()\n\tif err != nil {\n\t\treturn err\n\t}\n\trsp := newResponse(types.Result{}, string(resInfo.Data), false)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/ Set an option on the application\nfunc cmdSetOption(c *cli.Context) error {\n\targs := c.Args()\n\tif len(args) != 2 {\n\t\treturn errors.New(\"Command set_option takes 2 arguments (key, value)\")\n\t}\n\tres := client.SetOptionSync(args[0], args[1])\n\trsp := newResponse(res, Fmt(\"%s=%s\", args[0], args[1]), false)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/ Append a new tx to application\nfunc cmdDeliverTx(c *cli.Context) error {\n\targs := c.Args()\n\tif len(args) != 1 {\n\t\treturn errors.New(\"Command deliver_tx takes 1 argument\")\n\t}\n\t\/*txBytes, err := stringOrHexToBytes(c.Args()[0])\n\tif err != nil {\n\t\treturn err\n\t}*\/\n\ttxBytes := validator.ReadJSON(args[0])\n\tres := client.DeliverTxSync(txBytes)\n\trsp := newResponse(res, string(res.Data), true)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/ Validate a tx\nfunc cmdCheckTx(c *cli.Context) error {\n\targs := c.Args()\n\tif len(args) != 1 {\n\t\treturn errors.New(\"Command check_tx takes 1 argument\")\n\t}\n\ttxBytes, err := stringOrHexToBytes(c.Args()[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tres := client.CheckTxSync(txBytes)\n\trsp := newResponse(res, string(res.Data), true)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/ Get application Merkle root hash\nfunc cmdCommit(c *cli.Context) error {\n\tres := client.CommitSync()\n\trsp := newResponse(res, Fmt(\"0x%X\", res.Data), false)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/ Query application state\nfunc cmdQuery(c *cli.Context) error {\n\targs := c.Args()\n\tif len(args) != 1 {\n\t\treturn errors.New(\"Command query takes 1 argument\")\n\t}\n\t\/*queryBytes, err := stringOrHexToBytes(c.Args()[0])\n\tif err != nil {\n\t\treturn err\n\t}*\/\n\tqueryBytes := validator.ReadJSON(args[0])\n\tres := client.QuerySync(queryBytes)\n\trsp := newResponse(res, string(res.Data), true)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/Verify the structure of the bill of lading\nfunc cmdValidateBol(c *cli.Context) error {\n\targs := c.Args()\n\tif len(args) > 1 {\n\t\treturn errors.New(\"Command validate_bol takes 1 argument\")\n\t}\n\tres := client.EchoSync(validator.ValidateBoL(args[0], false))\n\trsp := newResponse(res, string(res.Data), false)\n\tprintResponse(c, rsp)\n\treturn nil\n}\n\n\/\/--------------------------------------------------------------------------------\n\nfunc printResponse(c *cli.Context, rsp *response) {\n\n\tverbose := c.GlobalBool(\"verbose\")\n\n\tif verbose {\n\t\tfmt.Println(\">\", c.Command.Name, strings.Join(c.Args(), \" \"))\n\t}\n\n\tif rsp.PrintCode {\n\t\tfmt.Printf(\"-> code: %s\\n\", rsp.Code)\n\t}\n\n\t\/\/if pr.res.Error != \"\" {\n\t\/\/\tfmt.Printf(\"-> error: %s\\n\", pr.res.Error)\n\t\/\/}\n\n\tif rsp.Data != \"\" {\n\t\tfmt.Printf(\"-> blockfreight data: %s\\n\", rsp.Data)\n\t}\n\tif rsp.Res.Log != \"\" {\n\t\tfmt.Printf(\"-> log: %s\\n\", rsp.Res.Log)\n\t}\n\n\tif verbose {\n\t\tfmt.Println(\"\")\n\t}\n\n}\n\n\/\/ NOTE: s is interpreted as a string unless prefixed with 0x\nfunc stringOrHexToBytes(s string) ([]byte, error) {\n\tif len(s) > 2 && strings.ToLower(s[:2]) == \"0x\" {\n\t\tb, err := hex.DecodeString(s[2:])\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Error decoding hex argument: %s\", err.Error())\n\t\t\treturn nil, err\n\t\t}\n\t\treturn b, nil\n\t}\n\n\tif !strings.HasPrefix(s, \"\\\"\") || !strings.HasSuffix(s, \"\\\"\") {\n\t\terr := fmt.Errorf(\"Invalid string arg: \\\"%s\\\". Must be quoted or a \\\"0x\\\"-prefixed hex string\", s)\n\t\treturn nil, err\n\t}\n\treturn []byte(s[1 : len(s)-1]), nil\n}\n\nfunc introduction (c *cli.Context) {\n\tfmt.Println(\"\\n...........................................\")\n\tfmt.Println(\"Blockfreight™ Go App\")\n\tfmt.Println(\"Address \"+c.GlobalString(\"address\"))\n\tfmt.Println(\"BFT Implementation:  \"+c.GlobalString(\"bft\"))\n\tfmt.Println(\"...........................................\\n\")\n\t\/*name := \"Blockfreight Community\"\n    if c.NArg() > 0 {\n      name = c.Args().Get(0)\n    }\n    if c.String(\"lang\") == \"ES\" {\t\/\/ISO 639-1\n      fmt.Println(\"Hola\", name)\n    } else {\n      fmt.Println(\"Hello\", name)\n    }*\/\n}<|endoftext|>"}
{"text":"<commit_before>package toiltest\n\n\n\/\/ ToilRecorder is an implementation of toil.Toiler, as well as an implementation\n\/\/ of toil.Recovereder and toil.Terminateder too; it counts the number of times\n\/\/ its Toil() method has been called and has not returned (i.e., is blocking) as\n\/\/ well as allows custom code to run when its Recovered(), Terminated(), or Toil()\n\/\/ methods are called.\ntype ToilRecorder struct {\n\tpanicCh     chan struct{value interface{}}\n\tterminateCh chan struct{doneCh chan struct{}}\n\tnumToiling int\n\n\trecoveredFunc  func(interface{})\n\tterminatedFunc func()\n\ttoilFunc       func()\n\n\treturnedNoticeFunc  func()\n\tpanickedNoticeFunc  func(interface{})\n\trecoveredNoticeFunc func(interface{})\n}\n\n\n\/\/ NewRecorder returns an initialized ToilRecorder.\nfunc NewRecorder() *ToilRecorder {\n\tpanicCh := make(chan struct{value interface{}})\n\n\tterminateCh := make(chan struct{doneCh chan struct{}})\n\n\ttoilRecorder := ToilRecorder{\n\t\tpanicCh:panicCh,\n\t\tterminateCh:terminateCh,\n\t}\n\n\treturn &toilRecorder\n}\n\n\n\/\/ RecoveredFunc registers the \"recovered function\" that will be called as part of when the\n\/\/ ToilRecorder's Recovered() method is called.\nfunc (toiler *ToilRecorder) RecoveredFunc(fn func(interface{})) {\n\ttoiler.recoveredFunc = fn\n}\n\n\/\/ TerminateFunc registers the \"terminated function\" that will be called as part of when the\n\/\/ ToilRecorder's Terminated() method is called.\nfunc (toiler *ToilRecorder) TerminatedFunc(fn func()) {\n\ttoiler.terminatedFunc = fn\n}\n\n\/\/ ToilFunc registers the \"toil function\" that will be called as part of when the\n\/\/ ToilRecorder's Toil() method is called.\nfunc (toiler *ToilRecorder) ToilFunc(fn func()) {\n\ttoiler.toilFunc = fn\n}\n\n\n\n\n\/\/ ReturnedNoticeFunc registers the func that will be called as part of when the\n\/\/ ReturnedNotice() method is called.\nfunc (toiler *ToilRecorder) ReturnedNoticeFunc(fn func()) {\n\ttoiler.returnedNoticeFunc = fn\n}\n\n\/\/ PanickedNoticeFunc registers the func that will be called as part of when the\n\/\/ PanickedNotice() method is called.\nfunc (toiler *ToilRecorder) PanickedNoticeFunc(fn func(interface{})) {\n\ttoiler.panickedNoticeFunc = fn\n}\n\n\/\/ RecoveredNoticeFunc registers the func that will be called as part of when the\n\/\/ RecoveredNotice() method is called.\nfunc (toiler *ToilRecorder) RecoveredNoticeFunc(fn func(interface{})) {\n\ttoiler.recoveredNoticeFunc = fn\n}\n\n\n\n\/\/ NumToiling returns the number of active calls to its Toil() method.\nfunc (toiler *ToilRecorder) NumToiling() int {\n\treturn toiler.numToiling\n}\n\n\n\/\/ Panic causes one of the still active (i.e., blocking) calls to Toil()\n\/\/ on itself to panic().\n\/\/\n\/\/ If there are not active (i.e., blocking) calls to Toil() on itself,\n\/\/ then it will block until there is one.\n\/\/\n\/\/ One use for this method is to check if its Recovered() method was\n\/\/ call by the toil.Group it is in (due to the panic()).\nfunc (toiler *ToilRecorder) Panic(value interface{}) {\n\n\ttoiler.panicCh <- struct{value interface{}}{\n\t\tvalue:value,\n\t}\n\n\/\/@TODO: Is there a way to wait for this to complete?\n}\n\n\n\/\/ Terminate causes one of the still active (i.e., blocking) calls to Toil()\n\/\/ on itself to return gracefully.\n\/\/\n\/\/ If there are not active (i.e., blocking) calls to Toil() on itself,\n\/\/ then it will block until there is one.\n\/\/\n\/\/ One use for this method is to check if its Terminated() method was\n\/\/ call by the toil.Group it is in (due to the gracefull return).\nfunc (toiler *ToilRecorder) Terminate() {\n\tdoneCh := make(chan struct{})\n\n\ttoiler.terminateCh <- struct{doneCh chan struct{}}{\n\t\tdoneCh:doneCh,\n\t}\n\n\t<-doneCh\n}\n\n\n\/\/ Toil is part of the toil.Toiler interface.\nfunc (toiler *ToilRecorder) Toil() {\n\ttoiler.numToiling++\n\n\tif nil != toiler.toilFunc {\n\t\ttoiler.toilFunc()\n\t}\n\n\tvar doneCh chan struct{}\n\n\tselect {\n\tcase panicRequest := <-toiler.panicCh:\n\t\tpanic(panicRequest.value)\n\tcase terminateRequest := <-toiler.terminateCh:\n\t\tdoneCh = terminateRequest.doneCh\n\t}\n\n\ttoiler.numToiling--\n\n\tif nil != doneCh {\n\t\tdoneCh <- struct{}{}\n\t}\n}\n\n\n\/\/ Recovered is part of the toil.toilRecovereder interface.\nfunc (toiler *ToilRecorder) Recovered(panicValue interface{}) {\n\tif nil != toiler.recoveredFunc {\n\t\ttoiler.recoveredFunc(panicValue)\n\t}\n}\n\n\n\/\/ Terminated is part of the toil.toilTerminateder interface.\nfunc (toiler *ToilRecorder) Terminated() {\n\tif nil != toiler.terminatedFunc {\n\t\ttoiler.terminatedFunc()\n\t}\n}\n\n\n\n\n\/\/ ReturnedNotice will call the func registerd with the call to the\n\/\/ ReturnedNoticeFunc method.\nfunc (toiler *ToilRecorder) ReturnedNotice() {\n\tif nil != toiler.returnedNoticeFunc {\n\t\ttoiler.returnedNoticeFunc()\n\t}\n}\n\n\/\/ PanickedNotice will call the func registerd with the call to the\n\/\/ PanickedNoticeFunc method.\nfunc (toiler *ToilRecorder) PanickedNotice(panicValue interface{}) {\n\tif nil != toiler.panickedNoticeFunc {\n\t\ttoiler.panickedNoticeFunc(panicValue)\n\t}\n}\n\n\/\/ RecoveredNotice will call the func registerd with the call to the\n\/\/ RecoveredNoticeFunc method.\nfunc (toiler *ToilRecorder) RecoveredNotice(panicValue interface{}) {\n\tif nil != toiler.recoveredNoticeFunc {\n\t\ttoiler.recoveredNoticeFunc(panicValue)\n\t}\n}\n<commit_msg>removed recoveredFunc related stuff.<commit_after>package toiltest\n\n\n\/\/ ToilRecorder is an implementation of toil.Toiler, as well as has PanickedNotice,\n\/\/ ReturnedNotice and RecoveredNotice methods as well. It counts the number of times\n\/\/ its Toil() method has been called and has not returned (i.e., is blocking) as\n\/\/ well as allows custom code to run when its PanickedNotice, ReturnedNotice(),\n\/\/ RecoveredNotice(), or Toil() methods are called.\ntype ToilRecorder struct {\n\tpanicCh     chan struct{value interface{}}\n\tterminateCh chan struct{doneCh chan struct{}}\n\tnumToiling int\n\n\tterminatedFunc func()\n\ttoilFunc       func()\n\n\treturnedNoticeFunc  func()\n\tpanickedNoticeFunc  func(interface{})\n\trecoveredNoticeFunc func(interface{})\n}\n\n\n\/\/ NewRecorder returns an initialized ToilRecorder.\nfunc NewRecorder() *ToilRecorder {\n\tpanicCh := make(chan struct{value interface{}})\n\n\tterminateCh := make(chan struct{doneCh chan struct{}})\n\n\ttoilRecorder := ToilRecorder{\n\t\tpanicCh:panicCh,\n\t\tterminateCh:terminateCh,\n\t}\n\n\treturn &toilRecorder\n}\n\n\n\/\/ TerminateFunc registers the \"terminated function\" that will be called as part of when the\n\/\/ ToilRecorder's Terminated() method is called.\nfunc (toiler *ToilRecorder) TerminatedFunc(fn func()) {\n\ttoiler.terminatedFunc = fn\n}\n\n\/\/ ToilFunc registers the \"toil function\" that will be called as part of when the\n\/\/ ToilRecorder's Toil() method is called.\nfunc (toiler *ToilRecorder) ToilFunc(fn func()) {\n\ttoiler.toilFunc = fn\n}\n\n\n\n\n\/\/ ReturnedNoticeFunc registers the func that will be called as part of when the\n\/\/ ReturnedNotice() method is called.\nfunc (toiler *ToilRecorder) ReturnedNoticeFunc(fn func()) {\n\ttoiler.returnedNoticeFunc = fn\n}\n\n\/\/ PanickedNoticeFunc registers the func that will be called as part of when the\n\/\/ PanickedNotice() method is called.\nfunc (toiler *ToilRecorder) PanickedNoticeFunc(fn func(interface{})) {\n\ttoiler.panickedNoticeFunc = fn\n}\n\n\/\/ RecoveredNoticeFunc registers the func that will be called as part of when the\n\/\/ RecoveredNotice() method is called.\nfunc (toiler *ToilRecorder) RecoveredNoticeFunc(fn func(interface{})) {\n\ttoiler.recoveredNoticeFunc = fn\n}\n\n\n\n\/\/ NumToiling returns the number of active calls to its Toil() method.\nfunc (toiler *ToilRecorder) NumToiling() int {\n\treturn toiler.numToiling\n}\n\n\n\/\/ Panic causes one of the still active (i.e., blocking) calls to Toil()\n\/\/ on itself to panic().\n\/\/\n\/\/ If there are not active (i.e., blocking) calls to Toil() on itself,\n\/\/ then it will block until there is one.\n\/\/\n\/\/ One use for this method is to check if its RecoveredNotice() method was\n\/\/ called by the toil.Group it is in (due to the panic()).\nfunc (toiler *ToilRecorder) Panic(value interface{}) {\n\n\ttoiler.panicCh <- struct{value interface{}}{\n\t\tvalue:value,\n\t}\n\n\/\/@TODO: Is there a way to wait for this to complete?\n}\n\n\n\/\/ Terminate causes one of the still active (i.e., blocking) calls to Toil()\n\/\/ on itself to return gracefully.\n\/\/\n\/\/ If there are not active (i.e., blocking) calls to Toil() on itself,\n\/\/ then it will block until there is one.\n\/\/\n\/\/ One use for this method is to check if its Terminated() method was\n\/\/ call by the toil.Group it is in (due to the gracefull return).\nfunc (toiler *ToilRecorder) Terminate() {\n\tdoneCh := make(chan struct{})\n\n\ttoiler.terminateCh <- struct{doneCh chan struct{}}{\n\t\tdoneCh:doneCh,\n\t}\n\n\t<-doneCh\n}\n\n\n\/\/ Toil is part of the toil.Toiler interface.\nfunc (toiler *ToilRecorder) Toil() {\n\ttoiler.numToiling++\n\n\tif nil != toiler.toilFunc {\n\t\ttoiler.toilFunc()\n\t}\n\n\tvar doneCh chan struct{}\n\n\tselect {\n\tcase panicRequest := <-toiler.panicCh:\n\t\tpanic(panicRequest.value)\n\tcase terminateRequest := <-toiler.terminateCh:\n\t\tdoneCh = terminateRequest.doneCh\n\t}\n\n\ttoiler.numToiling--\n\n\tif nil != doneCh {\n\t\tdoneCh <- struct{}{}\n\t}\n}\n\n\n\/\/ Terminated is part of the toil.toilTerminateder interface.\nfunc (toiler *ToilRecorder) Terminated() {\n\tif nil != toiler.terminatedFunc {\n\t\ttoiler.terminatedFunc()\n\t}\n}\n\n\n\n\n\/\/ ReturnedNotice will call the func registerd with the call to the\n\/\/ ReturnedNoticeFunc method.\nfunc (toiler *ToilRecorder) ReturnedNotice() {\n\tif nil != toiler.returnedNoticeFunc {\n\t\ttoiler.returnedNoticeFunc()\n\t}\n}\n\n\/\/ PanickedNotice will call the func registerd with the call to the\n\/\/ PanickedNoticeFunc method.\nfunc (toiler *ToilRecorder) PanickedNotice(panicValue interface{}) {\n\tif nil != toiler.panickedNoticeFunc {\n\t\ttoiler.panickedNoticeFunc(panicValue)\n\t}\n}\n\n\/\/ RecoveredNotice will call the func registerd with the call to the\n\/\/ RecoveredNoticeFunc method.\nfunc (toiler *ToilRecorder) RecoveredNotice(panicValue interface{}) {\n\tif nil != toiler.recoveredNoticeFunc {\n\t\ttoiler.recoveredNoticeFunc(panicValue)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2015-2017 Gravitational, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"golang.org\/x\/crypto\/ssh\"\n\n\t\"github.com\/gravitational\/teleport\/lib\/backend\"\n\t\"github.com\/gravitational\/teleport\/lib\/client\"\n\t\"github.com\/gravitational\/teleport\/lib\/defaults\"\n\t\"github.com\/gravitational\/teleport\/lib\/service\"\n\t\"github.com\/gravitational\/teleport\/lib\/utils\"\n\t\"github.com\/gravitational\/teleport\/tool\/tsh\/common\"\n\n\t\"gopkg.in\/check.v1\"\n)\n\n\/\/ bootstrap check\nfunc TestTshMain(t *testing.T) {\n\tutils.InitLoggerForTests(testing.Verbose())\n\tcheck.TestingT(t)\n}\n\n\/\/ register test suite\ntype MainTestSuite struct{}\n\nvar _ = check.Suite(&MainTestSuite{})\n\nfunc (s *MainTestSuite) SetUpSuite(c *check.C) {\n\tdir := client.FullProfilePath(\"\")\n\tos.RemoveAll(dir)\n}\n\nfunc (s *MainTestSuite) TestMakeClient(c *check.C) {\n\tvar conf CLIConf\n\n\t\/\/ empty config won't work:\n\ttc, err := makeClient(&conf, true)\n\tc.Assert(tc, check.IsNil)\n\tc.Assert(err, check.NotNil)\n\n\t\/\/ minimal configuration (with defaults)\n\tconf.Proxy = \"proxy\"\n\tconf.UserHost = \"localhost\"\n\ttc, err = makeClient(&conf, true)\n\tc.Assert(err, check.IsNil)\n\tc.Assert(tc, check.NotNil)\n\tc.Assert(tc.Config.SSHProxyAddr, check.Equals, \"proxy:3023\")\n\tc.Assert(tc.Config.WebProxyAddr, check.Equals, \"proxy:3080\")\n\tlocalUser, err := client.Username()\n\tc.Assert(err, check.IsNil)\n\tc.Assert(tc.Config.HostLogin, check.Equals, localUser)\n\tc.Assert(tc.Config.KeyTTL, check.Equals, defaults.CertDuration)\n\n\t\/\/ specific configuration\n\tconf.MinsToLive = 5\n\tconf.UserHost = \"root@localhost\"\n\tconf.NodePort = 46528\n\tconf.LocalForwardPorts = []string{\"80:remote:180\"}\n\tconf.DynamicForwardedPorts = []string{\":8080\"}\n\ttc, err = makeClient(&conf, true)\n\tc.Assert(err, check.IsNil)\n\tc.Assert(tc.Config.KeyTTL, check.Equals, time.Minute*time.Duration(conf.MinsToLive))\n\tc.Assert(tc.Config.HostLogin, check.Equals, \"root\")\n\tc.Assert(tc.Config.LocalForwardPorts, check.DeepEquals, client.ForwardedPorts{\n\t\t{\n\t\t\tSrcIP:    \"127.0.0.1\",\n\t\t\tSrcPort:  80,\n\t\t\tDestHost: \"remote\",\n\t\t\tDestPort: 180,\n\t\t},\n\t})\n\tc.Assert(tc.Config.DynamicForwardedPorts, check.DeepEquals, client.DynamicForwardedPorts{\n\t\t{\n\t\t\tSrcIP:   \"127.0.0.1\",\n\t\t\tSrcPort: 8080,\n\t\t},\n\t})\n\n\t\/\/ Set up a test proxy service.\n\tports, err := utils.GetFreeTCPPorts(3)\n\tc.Assert(err, check.IsNil)\n\tauthAddr := utils.MustParseAddr(fmt.Sprintf(\"127.0.0.1:%v\", ports.Pop()))\n\tproxyWebAddr := utils.MustParseAddr(fmt.Sprintf(\"127.0.0.1:%v\", ports.Pop()))\n\tproxyPublicSSHAddr := utils.MustParseAddr(fmt.Sprintf(\"127.0.0.1:%v\", ports.Pop()))\n\n\tcfg := service.MakeDefaultConfig()\n\tcfg.DataDir = c.MkDir()\n\tcfg.Auth.StorageConfig.Params = backend.Params{defaults.BackendPath: filepath.Join(cfg.DataDir, defaults.BackendDir)}\n\tcfg.AuthServers = []utils.NetAddr{*authAddr}\n\tcfg.SSH.Enabled = false\n\tcfg.Auth.Enabled = true\n\tcfg.Auth.SSHAddr = *authAddr\n\tcfg.Proxy.Enabled = true\n\tcfg.Proxy.WebAddr = *proxyWebAddr\n\tcfg.Proxy.SSHPublicAddrs = []utils.NetAddr{*proxyPublicSSHAddr}\n\tcfg.Proxy.DisableReverseTunnel = true\n\tcfg.Proxy.DisableWebInterface = true\n\n\tproxy, err := service.NewTeleport(cfg)\n\tc.Assert(err, check.IsNil)\n\tc.Assert(proxy.Start(), check.IsNil)\n\tdefer proxy.Close()\n\n\t\/\/ Wait for proxy to become ready.\n\teventCh := make(chan service.Event, 1)\n\tproxy.WaitForEvent(proxy.ExitContext(), service.ProxyWebServerReady, eventCh)\n\tselect {\n\tcase <-eventCh:\n\tcase <-time.After(10 * time.Second):\n\t\tc.Fatal(\"proxy web server didn't start after 10s\")\n\t}\n\n\t\/\/ With provided identity file.\n\t\/\/\n\t\/\/ makeClient should call Ping on the proxy to fetch SSHProxyAddr, which is\n\t\/\/ different from the default.\n\tconf = CLIConf{\n\t\tProxy:              proxyWebAddr.String(),\n\t\tIdentityFileIn:     \"..\/..\/fixtures\/certs\/identities\/key-cert-ca.pem\",\n\t\tContext:            context.Background(),\n\t\tInsecureSkipVerify: true,\n\t}\n\ttc, err = makeClient(&conf, true)\n\tc.Assert(err, check.IsNil)\n\tc.Assert(tc, check.NotNil)\n\tc.Assert(tc.Config.WebProxyAddr, check.Equals, proxyWebAddr.String())\n\tc.Assert(tc.Config.SSHProxyAddr, check.Equals, proxyPublicSSHAddr.String())\n}\n\nfunc (s *MainTestSuite) TestIdentityRead(c *check.C) {\n\t\/\/ 3 different types of identities\n\tids := []string{\n\t\t\"cert-key.pem\", \/\/ cert + key concatenated togther, cert first\n\t\t\"key-cert.pem\", \/\/ cert + key concatenated togther, key first\n\t\t\"key\",          \/\/ two separate files: key and key-cert.pub\n\t}\n\tfor _, id := range ids {\n\t\t\/\/ test reading:\n\t\tk, cb, err := common.LoadIdentity(fmt.Sprintf(\"..\/..\/fixtures\/certs\/identities\/%s\", id))\n\t\tc.Assert(err, check.IsNil)\n\t\tc.Assert(k, check.NotNil)\n\t\tc.Assert(cb, check.IsNil)\n\n\t\t\/\/ test creating an auth method from the key:\n\t\tam, err := authFromIdentity(k)\n\t\tc.Assert(err, check.IsNil)\n\t\tc.Assert(am, check.NotNil)\n\t}\n\tk, _, err := common.LoadIdentity(\"..\/..\/fixtures\/certs\/identities\/lonekey\")\n\tc.Assert(k, check.IsNil)\n\tc.Assert(err, check.NotNil)\n\n\t\/\/ lets read an indentity which includes a CA cert\n\tk, hostAuthCallback, err := common.LoadIdentity(\"..\/..\/fixtures\/certs\/identities\/key-cert-ca.pem\")\n\tc.Assert(err, check.IsNil)\n\tc.Assert(k, check.NotNil)\n\tc.Assert(hostAuthCallback, check.NotNil)\n\t\/\/ prepare the cluster CA separately\n\tcertBytes, err := ioutil.ReadFile(\"..\/..\/fixtures\/certs\/identities\/ca.pem\")\n\tc.Assert(err, check.IsNil)\n\t_, hosts, cert, _, _, err := ssh.ParseKnownHosts(certBytes)\n\tc.Assert(err, check.IsNil)\n\tvar a net.Addr\n\t\/\/ host auth callback must succeed\n\terr = hostAuthCallback(hosts[0], a, cert)\n\tc.Assert(err, check.IsNil)\n\n\t\/\/ load an identity which include TLS certificates\n\tk, _, err = common.LoadIdentity(\"..\/..\/fixtures\/certs\/identities\/tls.pem\")\n\tc.Assert(err, check.IsNil)\n\tc.Assert(k, check.NotNil)\n\tc.Assert(k.TLSCert, check.NotNil)\n\t\/\/ generate a TLS client config\n\tconf, err := k.ClientTLSConfig()\n\tc.Assert(err, check.IsNil)\n\tc.Assert(conf, check.NotNil)\n\t\/\/ ensure that at least root CA was successfully loaded\n\tif len(conf.RootCAs.Subjects()) < 1 {\n\t\tc.Errorf(\"Failed to load TLS CAs from identity file\")\n\t}\n}\n\nfunc (s *MainTestSuite) TestOptions(c *check.C) {\n\ttests := []struct {\n\t\tinOptions  []string\n\t\toutError   bool\n\t\toutOptions Options\n\t}{\n\t\t\/\/ Valid\n\t\t{\n\t\t\tinOptions: []string{\n\t\t\t\t\"AddKeysToAgent yes\",\n\t\t\t},\n\t\t\toutError: false,\n\t\t\toutOptions: Options{\n\t\t\t\tAddKeysToAgent:        true,\n\t\t\t\tForwardAgent:          false,\n\t\t\t\tRequestTTY:            false,\n\t\t\t\tStrictHostKeyChecking: true,\n\t\t\t},\n\t\t},\n\t\t\/\/ Valid\n\t\t{\n\t\t\tinOptions: []string{\n\t\t\t\t\"AddKeysToAgent=yes\",\n\t\t\t},\n\t\t\toutError: false,\n\t\t\toutOptions: Options{\n\t\t\t\tAddKeysToAgent:        true,\n\t\t\t\tForwardAgent:          false,\n\t\t\t\tRequestTTY:            false,\n\t\t\t\tStrictHostKeyChecking: true,\n\t\t\t},\n\t\t},\n\t\t\/\/ Invalid value.\n\t\t{\n\t\t\tinOptions: []string{\n\t\t\t\t\"AddKeysToAgent foo\",\n\t\t\t},\n\t\t\toutError:   true,\n\t\t\toutOptions: Options{},\n\t\t},\n\t\t\/\/ Invalid key.\n\t\t{\n\t\t\tinOptions: []string{\n\t\t\t\t\"foo foo\",\n\t\t\t},\n\t\t\toutError:   true,\n\t\t\toutOptions: Options{},\n\t\t},\n\t\t\/\/ Incomplete option.\n\t\t{\n\t\t\tinOptions: []string{\n\t\t\t\t\"AddKeysToAgent\",\n\t\t\t},\n\t\t\toutError:   true,\n\t\t\toutOptions: Options{},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\toptions, err := parseOptions(tt.inOptions)\n\t\tif tt.outError {\n\t\t\tc.Assert(err, check.NotNil)\n\t\t\tcontinue\n\t\t} else {\n\t\t\tc.Assert(err, check.IsNil)\n\t\t}\n\n\t\tc.Assert(options.AddKeysToAgent, check.Equals, tt.outOptions.AddKeysToAgent)\n\t\tc.Assert(options.ForwardAgent, check.Equals, tt.outOptions.ForwardAgent)\n\t\tc.Assert(options.RequestTTY, check.Equals, tt.outOptions.RequestTTY)\n\t\tc.Assert(options.StrictHostKeyChecking, check.Equals, tt.outOptions.StrictHostKeyChecking)\n\t}\n}\n<commit_msg>Auto assign listening ports in tool\/tsh tests<commit_after>\/*\nCopyright 2015-2017 Gravitational, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"golang.org\/x\/crypto\/ssh\"\n\n\t\"github.com\/gravitational\/teleport\"\n\t\"github.com\/gravitational\/teleport\/lib\/backend\"\n\t\"github.com\/gravitational\/teleport\/lib\/client\"\n\t\"github.com\/gravitational\/teleport\/lib\/defaults\"\n\t\"github.com\/gravitational\/teleport\/lib\/service\"\n\t\"github.com\/gravitational\/teleport\/lib\/services\"\n\t\"github.com\/gravitational\/teleport\/lib\/utils\"\n\t\"github.com\/gravitational\/teleport\/tool\/tsh\/common\"\n\n\t\"gopkg.in\/check.v1\"\n)\n\n\/\/ bootstrap check\nfunc TestTshMain(t *testing.T) {\n\tutils.InitLoggerForTests(testing.Verbose())\n\tcheck.TestingT(t)\n}\n\n\/\/ register test suite\ntype MainTestSuite struct{}\n\nvar _ = check.Suite(&MainTestSuite{})\n\nfunc (s *MainTestSuite) SetUpSuite(c *check.C) {\n\tdir := client.FullProfilePath(\"\")\n\tos.RemoveAll(dir)\n}\n\nfunc (s *MainTestSuite) TestMakeClient(c *check.C) {\n\tvar conf CLIConf\n\n\t\/\/ empty config won't work:\n\ttc, err := makeClient(&conf, true)\n\tc.Assert(tc, check.IsNil)\n\tc.Assert(err, check.NotNil)\n\n\t\/\/ minimal configuration (with defaults)\n\tconf.Proxy = \"proxy\"\n\tconf.UserHost = \"localhost\"\n\ttc, err = makeClient(&conf, true)\n\tc.Assert(err, check.IsNil)\n\tc.Assert(tc, check.NotNil)\n\tc.Assert(tc.Config.SSHProxyAddr, check.Equals, \"proxy:3023\")\n\tc.Assert(tc.Config.WebProxyAddr, check.Equals, \"proxy:3080\")\n\tlocalUser, err := client.Username()\n\tc.Assert(err, check.IsNil)\n\tc.Assert(tc.Config.HostLogin, check.Equals, localUser)\n\tc.Assert(tc.Config.KeyTTL, check.Equals, defaults.CertDuration)\n\n\t\/\/ specific configuration\n\tconf.MinsToLive = 5\n\tconf.UserHost = \"root@localhost\"\n\tconf.NodePort = 46528\n\tconf.LocalForwardPorts = []string{\"80:remote:180\"}\n\tconf.DynamicForwardedPorts = []string{\":8080\"}\n\ttc, err = makeClient(&conf, true)\n\tc.Assert(err, check.IsNil)\n\tc.Assert(tc.Config.KeyTTL, check.Equals, time.Minute*time.Duration(conf.MinsToLive))\n\tc.Assert(tc.Config.HostLogin, check.Equals, \"root\")\n\tc.Assert(tc.Config.LocalForwardPorts, check.DeepEquals, client.ForwardedPorts{\n\t\t{\n\t\t\tSrcIP:    \"127.0.0.1\",\n\t\t\tSrcPort:  80,\n\t\t\tDestHost: \"remote\",\n\t\t\tDestPort: 180,\n\t\t},\n\t})\n\tc.Assert(tc.Config.DynamicForwardedPorts, check.DeepEquals, client.DynamicForwardedPorts{\n\t\t{\n\t\t\tSrcIP:   \"127.0.0.1\",\n\t\t\tSrcPort: 8080,\n\t\t},\n\t})\n\n\trandomLocalAddr := utils.NetAddr{AddrNetwork: \"tcp\", Addr: \"127.0.0.1:0\"}\n\tconst staticToken = \"test-static-token\"\n\n\t\/\/ Set up a test auth server.\n\t\/\/\n\t\/\/ We need this to get a random port assigned to it and allow parallel\n\t\/\/ execution of this test.\n\tcfg := service.MakeDefaultConfig()\n\tcfg.DataDir = c.MkDir()\n\tcfg.AuthServers = []utils.NetAddr{randomLocalAddr}\n\tcfg.Auth.StorageConfig.Params = backend.Params{defaults.BackendPath: filepath.Join(cfg.DataDir, defaults.BackendDir)}\n\tcfg.Auth.StaticTokens, err = services.NewStaticTokens(services.StaticTokensSpecV2{\n\t\tStaticTokens: []services.ProvisionTokenV1{{\n\t\t\tRoles:   []teleport.Role{teleport.RoleProxy},\n\t\t\tExpires: time.Now().Add(time.Minute),\n\t\t\tToken:   staticToken,\n\t\t}},\n\t})\n\tcfg.SSH.Enabled = false\n\tcfg.Auth.Enabled = true\n\tcfg.Auth.SSHAddr = randomLocalAddr\n\tcfg.Proxy.Enabled = false\n\n\tauth, err := service.NewTeleport(cfg)\n\tc.Assert(err, check.IsNil)\n\tc.Assert(auth.Start(), check.IsNil)\n\tdefer auth.Close()\n\n\t\/\/ Wait for proxy to become ready.\n\teventCh := make(chan service.Event, 1)\n\tauth.WaitForEvent(auth.ExitContext(), service.AuthTLSReady, eventCh)\n\tselect {\n\tcase <-eventCh:\n\tcase <-time.After(10 * time.Second):\n\t\tc.Fatal(\"auth server didn't start after 10s\")\n\t}\n\n\tauthAddr, err := auth.AuthSSHAddr()\n\tc.Assert(err, check.IsNil)\n\n\t\/\/ Set up a test proxy service.\n\tproxyPublicSSHAddr := utils.NetAddr{AddrNetwork: \"tcp\", Addr: \"proxy.example.com:22\"}\n\tcfg = service.MakeDefaultConfig()\n\tcfg.DataDir = c.MkDir()\n\tcfg.AuthServers = []utils.NetAddr{*authAddr}\n\tcfg.Token = staticToken\n\tcfg.SSH.Enabled = false\n\tcfg.Auth.Enabled = false\n\tcfg.Proxy.Enabled = true\n\tcfg.Proxy.WebAddr = randomLocalAddr\n\tcfg.Proxy.SSHPublicAddrs = []utils.NetAddr{proxyPublicSSHAddr}\n\tcfg.Proxy.DisableReverseTunnel = true\n\tcfg.Proxy.DisableWebInterface = true\n\n\tproxy, err := service.NewTeleport(cfg)\n\tc.Assert(err, check.IsNil)\n\tc.Assert(proxy.Start(), check.IsNil)\n\tdefer proxy.Close()\n\n\t\/\/ Wait for proxy to become ready.\n\tproxy.WaitForEvent(proxy.ExitContext(), service.ProxyWebServerReady, eventCh)\n\tselect {\n\tcase <-eventCh:\n\tcase <-time.After(10 * time.Second):\n\t\tc.Fatal(\"proxy web server didn't start after 10s\")\n\t}\n\n\tproxyWebAddr, err := proxy.ProxyWebAddr()\n\tc.Assert(err, check.IsNil)\n\n\t\/\/ With provided identity file.\n\t\/\/\n\t\/\/ makeClient should call Ping on the proxy to fetch SSHProxyAddr, which is\n\t\/\/ different from the default.\n\tconf = CLIConf{\n\t\tProxy:              proxyWebAddr.String(),\n\t\tIdentityFileIn:     \"..\/..\/fixtures\/certs\/identities\/key-cert-ca.pem\",\n\t\tContext:            context.Background(),\n\t\tInsecureSkipVerify: true,\n\t}\n\ttc, err = makeClient(&conf, true)\n\tc.Assert(err, check.IsNil)\n\tc.Assert(tc, check.NotNil)\n\tc.Assert(tc.Config.WebProxyAddr, check.Equals, proxyWebAddr.String())\n\tc.Assert(tc.Config.SSHProxyAddr, check.Equals, proxyPublicSSHAddr.String())\n}\n\nfunc (s *MainTestSuite) TestIdentityRead(c *check.C) {\n\t\/\/ 3 different types of identities\n\tids := []string{\n\t\t\"cert-key.pem\", \/\/ cert + key concatenated togther, cert first\n\t\t\"key-cert.pem\", \/\/ cert + key concatenated togther, key first\n\t\t\"key\",          \/\/ two separate files: key and key-cert.pub\n\t}\n\tfor _, id := range ids {\n\t\t\/\/ test reading:\n\t\tk, cb, err := common.LoadIdentity(fmt.Sprintf(\"..\/..\/fixtures\/certs\/identities\/%s\", id))\n\t\tc.Assert(err, check.IsNil)\n\t\tc.Assert(k, check.NotNil)\n\t\tc.Assert(cb, check.IsNil)\n\n\t\t\/\/ test creating an auth method from the key:\n\t\tam, err := authFromIdentity(k)\n\t\tc.Assert(err, check.IsNil)\n\t\tc.Assert(am, check.NotNil)\n\t}\n\tk, _, err := common.LoadIdentity(\"..\/..\/fixtures\/certs\/identities\/lonekey\")\n\tc.Assert(k, check.IsNil)\n\tc.Assert(err, check.NotNil)\n\n\t\/\/ lets read an indentity which includes a CA cert\n\tk, hostAuthCallback, err := common.LoadIdentity(\"..\/..\/fixtures\/certs\/identities\/key-cert-ca.pem\")\n\tc.Assert(err, check.IsNil)\n\tc.Assert(k, check.NotNil)\n\tc.Assert(hostAuthCallback, check.NotNil)\n\t\/\/ prepare the cluster CA separately\n\tcertBytes, err := ioutil.ReadFile(\"..\/..\/fixtures\/certs\/identities\/ca.pem\")\n\tc.Assert(err, check.IsNil)\n\t_, hosts, cert, _, _, err := ssh.ParseKnownHosts(certBytes)\n\tc.Assert(err, check.IsNil)\n\tvar a net.Addr\n\t\/\/ host auth callback must succeed\n\terr = hostAuthCallback(hosts[0], a, cert)\n\tc.Assert(err, check.IsNil)\n\n\t\/\/ load an identity which include TLS certificates\n\tk, _, err = common.LoadIdentity(\"..\/..\/fixtures\/certs\/identities\/tls.pem\")\n\tc.Assert(err, check.IsNil)\n\tc.Assert(k, check.NotNil)\n\tc.Assert(k.TLSCert, check.NotNil)\n\t\/\/ generate a TLS client config\n\tconf, err := k.ClientTLSConfig()\n\tc.Assert(err, check.IsNil)\n\tc.Assert(conf, check.NotNil)\n\t\/\/ ensure that at least root CA was successfully loaded\n\tif len(conf.RootCAs.Subjects()) < 1 {\n\t\tc.Errorf(\"Failed to load TLS CAs from identity file\")\n\t}\n}\n\nfunc (s *MainTestSuite) TestOptions(c *check.C) {\n\ttests := []struct {\n\t\tinOptions  []string\n\t\toutError   bool\n\t\toutOptions Options\n\t}{\n\t\t\/\/ Valid\n\t\t{\n\t\t\tinOptions: []string{\n\t\t\t\t\"AddKeysToAgent yes\",\n\t\t\t},\n\t\t\toutError: false,\n\t\t\toutOptions: Options{\n\t\t\t\tAddKeysToAgent:        true,\n\t\t\t\tForwardAgent:          false,\n\t\t\t\tRequestTTY:            false,\n\t\t\t\tStrictHostKeyChecking: true,\n\t\t\t},\n\t\t},\n\t\t\/\/ Valid\n\t\t{\n\t\t\tinOptions: []string{\n\t\t\t\t\"AddKeysToAgent=yes\",\n\t\t\t},\n\t\t\toutError: false,\n\t\t\toutOptions: Options{\n\t\t\t\tAddKeysToAgent:        true,\n\t\t\t\tForwardAgent:          false,\n\t\t\t\tRequestTTY:            false,\n\t\t\t\tStrictHostKeyChecking: true,\n\t\t\t},\n\t\t},\n\t\t\/\/ Invalid value.\n\t\t{\n\t\t\tinOptions: []string{\n\t\t\t\t\"AddKeysToAgent foo\",\n\t\t\t},\n\t\t\toutError:   true,\n\t\t\toutOptions: Options{},\n\t\t},\n\t\t\/\/ Invalid key.\n\t\t{\n\t\t\tinOptions: []string{\n\t\t\t\t\"foo foo\",\n\t\t\t},\n\t\t\toutError:   true,\n\t\t\toutOptions: Options{},\n\t\t},\n\t\t\/\/ Incomplete option.\n\t\t{\n\t\t\tinOptions: []string{\n\t\t\t\t\"AddKeysToAgent\",\n\t\t\t},\n\t\t\toutError:   true,\n\t\t\toutOptions: Options{},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\toptions, err := parseOptions(tt.inOptions)\n\t\tif tt.outError {\n\t\t\tc.Assert(err, check.NotNil)\n\t\t\tcontinue\n\t\t} else {\n\t\t\tc.Assert(err, check.IsNil)\n\t\t}\n\n\t\tc.Assert(options.AddKeysToAgent, check.Equals, tt.outOptions.AddKeysToAgent)\n\t\tc.Assert(options.ForwardAgent, check.Equals, tt.outOptions.ForwardAgent)\n\t\tc.Assert(options.RequestTTY, check.Equals, tt.outOptions.RequestTTY)\n\t\tc.Assert(options.StrictHostKeyChecking, check.Equals, tt.outOptions.StrictHostKeyChecking)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package vmx\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"path\/filepath\"\n\n\tvmwcommon \"github.com\/hashicorp\/packer\/builder\/vmware\/common\"\n\t\"github.com\/hashicorp\/packer\/helper\/multistep\"\n\t\"github.com\/hashicorp\/packer\/packer\"\n)\n\n\/\/ StepCloneVMX takes a VMX file and clones the VM into the output directory.\ntype StepCloneVMX struct {\n\tOutputDir string\n\tPath      string\n\tVMName    string\n}\n\ntype vmxAdapter struct {\n\t\/\/ The string portion of the address used in the vmx file\n\tstrAddr string\n\t\/\/ Max address for adapter, controller, or controller channel\n\taAddrMax int\n\t\/\/ Max address for device or channel supported by adapter\n\tdAddrMax int\n}\n\nconst (\n\t\/\/ VMware Configuration Maximums - Virtual Hardware Versions 13\/14\n\t\/\/\n\t\/\/ Specifying the max numbers for the adapter\/controller:bus\/channel\n\t\/\/ *address* as opposed to specifying the maximums as per the VMware\n\t\/\/ documentation allows consistent (inclusive) treatment when looping\n\t\/\/ over each adapter\/controller type\n\t\/\/\n\t\/\/ SCSI - Address range: scsi0:0 to scsi3:15\n\tscsiAddrName       = \"scsi\" \/\/ String part of address used in the vmx file\n\tmaxSCSIAdapterAddr = 3      \/\/ Max 4 adapters\n\tmaxSCSIDeviceAddr  = 15     \/\/ Max 15 devices per adapter; ID 7 is the HBA\n\t\/\/ SATA - Address range: sata0:0 to scsi3:29\n\tsataAddrName       = \"sata\" \/\/ String part of address used in the vmx file\n\tmaxSATAAdapterAddr = 3      \/\/ Max 4 controllers\n\tmaxSATADeviceAddr  = 29     \/\/ Max 30 devices per controller\n\t\/\/ NVMe - Address range: nvme0:0 to nvme3:14\n\tnvmeAddrName       = \"nvme\" \/\/ String part of address used in the vmx file\n\tmaxNVMeAdapterAddr = 3      \/\/ Max 4 adapters\n\tmaxNVMeDeviceAddr  = 14     \/\/ Max 15 devices per adapter\n\t\/\/ IDE - Address range: ide0:0 to ide1:1\n\tideAddrName       = \"ide\" \/\/ String part of address used in the vmx file\n\tmaxIDEAdapterAddr = 1     \/\/ One controller with primary\/secondary channels\n\tmaxIDEDeviceAddr  = 1     \/\/ Each channel supports master and slave\n)\n\nvar (\n\tscsiAdapter = vmxAdapter{\n\t\tstrAddr:  scsiAddrName,\n\t\taAddrMax: maxSCSIAdapterAddr,\n\t\tdAddrMax: maxSCSIDeviceAddr,\n\t}\n\tsataAdapter = vmxAdapter{\n\t\tstrAddr:  sataAddrName,\n\t\taAddrMax: maxSATAAdapterAddr,\n\t\tdAddrMax: maxSATADeviceAddr,\n\t}\n\tnvmeAdapter = vmxAdapter{\n\t\tstrAddr:  nvmeAddrName,\n\t\taAddrMax: maxNVMeAdapterAddr,\n\t\tdAddrMax: maxNVMeDeviceAddr,\n\t}\n\tideAdapter = vmxAdapter{\n\t\tstrAddr:  ideAddrName,\n\t\taAddrMax: maxIDEAdapterAddr,\n\t\tdAddrMax: maxIDEDeviceAddr,\n\t}\n)\n\nfunc (s *StepCloneVMX) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {\n\tdriver := state.Get(\"driver\").(vmwcommon.Driver)\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\t\/\/ Set the path we want for the new .vmx file and clone\n\tvmxPath := filepath.Join(s.OutputDir, s.VMName+\".vmx\")\n\tui.Say(\"Cloning source VM...\")\n\tlog.Printf(\"Cloning from: %s\", s.Path)\n\tlog.Printf(\"Cloning to: %s\", vmxPath)\n\tif err := driver.Clone(vmxPath, s.Path); err != nil {\n\t\tstate.Put(\"error\", err)\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Read in the machine configuration from the cloned VMX file\n\t\/\/\n\t\/\/ * The main driver needs the path to the vmx (set above) and the\n\t\/\/ network type so that it can work out things like IP's and MAC\n\t\/\/ addresses\n\t\/\/ * The disk compaction step needs the paths to all attached disks\n\tvmxData, err := vmwcommon.ReadVMX(vmxPath)\n\tif err != nil {\n\t\tstate.Put(\"error\", err)\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Search across all adapter types to get the filenames of attached disks\n\tallDiskAdapters := []vmxAdapter{\n\t\tscsiAdapter,\n\t\tsataAdapter,\n\t\tnvmeAdapter,\n\t\tideAdapter,\n\t}\n\tvar diskFilenames []string\n\tfor _, adapter := range allDiskAdapters {\n\t\tdiskFilenames = append(diskFilenames, getAttachedDisks(adapter, vmxData)...)\n\t}\n\n\t\/\/ Write out the relative, host filesystem paths to the disks\n\tvar diskFullPaths []string\n\tfor _, diskFilename := range diskFilenames {\n\t\tlog.Printf(\"Found attached disk with filename: %s\", diskFilename)\n\t\tdiskFullPaths = append(diskFullPaths, filepath.Join(s.OutputDir, diskFilename))\n\t}\n\n\tif len(diskFullPaths) == 0 {\n\t\tstate.Put(\"error\", fmt.Errorf(\"Could not enumerate disk info from the vmx file\"))\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Determine the network type by reading out of the .vmx\n\tvar networkType string\n\tif _, ok := vmxData[\"ethernet0.connectiontype\"]; ok {\n\t\tnetworkType = vmxData[\"ethernet0.connectiontype\"]\n\t\tlog.Printf(\"Discovered the network type: %s\", networkType)\n\t}\n\tif networkType == \"\" {\n\t\tnetworkType = \"nat\"\n\t\tlog.Printf(\"Defaulting to network type: %s\", networkType)\n\t}\n\n\t\/\/ Stash all required information in our state bag\n\tstate.Put(\"vmx_path\", vmxPath)\n\tstate.Put(\"disk_full_paths\", diskFullPaths)\n\tstate.Put(\"vmnetwork\", networkType)\n\n\treturn multistep.ActionContinue\n}\n\nfunc (s *StepCloneVMX) Cleanup(state multistep.StateBag) {\n}\n\nfunc getAttachedDisks(a vmxAdapter, data map[string]string) (attachedDisks []string) {\n\t\/\/ Loop over possible adapter, controller or controller channel\n\tfor x := 0; x <= a.aAddrMax; x++ {\n\t\t\/\/ Loop over possible addresses for attached devices\n\t\tfor y := 0; y <= a.dAddrMax; y++ {\n\t\t\taddress := fmt.Sprintf(\"%s%d:%d.filename\", a.strAddr, x, y)\n\t\t\tif device, _ := data[address]; filepath.Ext(device) == \".vmdk\" {\n\t\t\t\tattachedDisks = append(attachedDisks, device)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n<commit_msg>Use regex based approach to detect attached disks<commit_after>package vmx\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\n\tvmwcommon \"github.com\/hashicorp\/packer\/builder\/vmware\/common\"\n\t\"github.com\/hashicorp\/packer\/helper\/multistep\"\n\t\"github.com\/hashicorp\/packer\/packer\"\n)\n\n\/\/ StepCloneVMX takes a VMX file and clones the VM into the output directory.\ntype StepCloneVMX struct {\n\tOutputDir string\n\tPath      string\n\tVMName    string\n}\n\ntype vmxAdapter struct {\n\tdiskPathKeyRe string\n}\n\nvar (\n\t\/\/ The VMX file stores the path to a configured disk, and information\n\t\/\/ about that disks attachment to a virtual adapter\/controller, as a\n\t\/\/ key\/value pair.\n\t\/\/ For a virtual disk attached to bus ID 3 of the virtual machines\n\t\/\/ first SCSI adapter the key\/value pair would look something like:\n\t\/\/ scsi0:3.fileName = \"relative\/path\/to\/scsiDisk.vmdk\"\n\t\/\/ The supported adapter types and configuration maximums for each type\n\t\/\/ vary according to the VMware platform type and version, and the\n\t\/\/ Virtual Machine Hardware version used. See the 'Virtual Machine\n\t\/\/ Maximums' section within VMware's 'Configuration Maximums'\n\t\/\/ documentation for each platform:\n\t\/\/ https:\/\/kb.vmware.com\/s\/article\/1003497\n\t\/\/ Information about the supported Virtual Machine Hardware versions:\n\t\/\/ https:\/\/kb.vmware.com\/s\/article\/1003746\n\t\/\/ The following regexp's are used to match all possible disk attachment\n\t\/\/ points that may be found in the VMX file across all VMware\n\t\/\/ platforms\/versions and Virtual Machine Hardware versions\n\tscsiAdapter = vmxAdapter{\n\t\tdiskPathKeyRe: `(?i)^scsi[[:digit:]]:[[:digit:]]{1,2}\\.fileName`,\n\t}\n\tsataAdapter = vmxAdapter{\n\t\tdiskPathKeyRe: `(?i)^sata[[:digit:]]:[[:digit:]]{1,2}\\.fileName`,\n\t}\n\tnvmeAdapter = vmxAdapter{\n\t\tdiskPathKeyRe: `(?i)^nvme[[:digit:]]:[[:digit:]]{1,2}\\.fileName`,\n\t}\n\tideAdapter = vmxAdapter{\n\t\tdiskPathKeyRe: `(?i)^ide[[:digit:]]:[[:digit:]]\\.fileName`,\n\t}\n)\n\nfunc (s *StepCloneVMX) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {\n\tdriver := state.Get(\"driver\").(vmwcommon.Driver)\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\t\/\/ Set the path we want for the new .vmx file and clone\n\tvmxPath := filepath.Join(s.OutputDir, s.VMName+\".vmx\")\n\tui.Say(\"Cloning source VM...\")\n\tlog.Printf(\"Cloning from: %s\", s.Path)\n\tlog.Printf(\"Cloning to: %s\", vmxPath)\n\tif err := driver.Clone(vmxPath, s.Path); err != nil {\n\t\tstate.Put(\"error\", err)\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Read in the machine configuration from the cloned VMX file\n\t\/\/\n\t\/\/ * The main driver needs the path to the vmx (set above) and the\n\t\/\/ network type so that it can work out things like IP's and MAC\n\t\/\/ addresses\n\t\/\/ * The disk compaction step needs the paths to all attached disks\n\tvmxData, err := vmwcommon.ReadVMX(vmxPath)\n\tif err != nil {\n\t\tstate.Put(\"error\", err)\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Search across all adapter types to get the filenames of attached disks\n\tallDiskAdapters := []vmxAdapter{\n\t\tscsiAdapter,\n\t\tsataAdapter,\n\t\tnvmeAdapter,\n\t\tideAdapter,\n\t}\n\tvar diskFilenames []string\n\tfor _, adapter := range allDiskAdapters {\n\t\tdiskFilenames = append(diskFilenames, getAttachedDisks(adapter, vmxData)...)\n\t}\n\n\t\/\/ Write out the relative, host filesystem paths to the disks\n\tvar diskFullPaths []string\n\tfor _, diskFilename := range diskFilenames {\n\t\tlog.Printf(\"Found attached disk with filename: %s\", diskFilename)\n\t\tdiskFullPaths = append(diskFullPaths, filepath.Join(s.OutputDir, diskFilename))\n\t}\n\n\tif len(diskFullPaths) == 0 {\n\t\tstate.Put(\"error\", fmt.Errorf(\"Could not enumerate disk info from the vmx file\"))\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Determine the network type by reading out of the .vmx\n\tvar networkType string\n\tif _, ok := vmxData[\"ethernet0.connectiontype\"]; ok {\n\t\tnetworkType = vmxData[\"ethernet0.connectiontype\"]\n\t\tlog.Printf(\"Discovered the network type: %s\", networkType)\n\t}\n\tif networkType == \"\" {\n\t\tnetworkType = \"nat\"\n\t\tlog.Printf(\"Defaulting to network type: %s\", networkType)\n\t}\n\n\t\/\/ Stash all required information in our state bag\n\tstate.Put(\"vmx_path\", vmxPath)\n\tstate.Put(\"disk_full_paths\", diskFullPaths)\n\tstate.Put(\"vmnetwork\", networkType)\n\n\treturn multistep.ActionContinue\n}\n\nfunc (s *StepCloneVMX) Cleanup(state multistep.StateBag) {\n}\n\nfunc getAttachedDisks(a vmxAdapter, data map[string]string) (attachedDisks []string) {\n\tpathKeyRe := regexp.MustCompile(a.diskPathKeyRe)\n\tfor k, v := range data {\n\t\tmatch := pathKeyRe.FindString(k)\n\t\tif match != \"\" && filepath.Ext(v) == \".vmdk\" {\n\t\t\tattachedDisks = append(attachedDisks, v)\n\t\t}\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package shark\n\nimport(\n\t\"strings\"\n\t\"os\"\n\t\"libxml\"\n\t\"fmt\"\n\txml \"libxml\/tree\"\n\ttp \"tritium\/proto\"\n\t\"libxml\/xpath\"\n\t\"rubex\"\n)\n\nfunc (ctx *Ctx) runBuiltIn(fun *Function, scope *Scope, ins *tp.Instruction, args []interface{}) (returnValue interface{}) {\n\treturnValue = \"\"\n\tswitch fun.Name {\n\tcase \"this\":\n\t\treturnValue = scope.Value\n\tcase \"yield\": \n\t\tmyYieldBlock := ctx.yieldBlock()\n\t\tctx.Yields = ctx.Yields[:(len(ctx.Yields)-1)]\n\t\tif (ctx.yieldBlock() != nil) {\n\t\t\treturnValue = ctx.runChildren(scope, myYieldBlock.Ins)\n\t\t} else {\n\t\t\tctx.Log.Error(\"yield() failure\")\n\t\t}\n\t\tctx.Yields = append(ctx.Yields, myYieldBlock)\n\n\tcase \"var.Text\":\n\t\tval := ctx.Env[args[0].(string)]\n\t\treturnValue = val\n\t\tif len(ins.Children) > 0 {\n\t\t\tts := &Scope{Value: val}\n\t\t\tctx.runChildren(ts, ins)\n\t\t\treturnValue = ts.Value\n\t\t\tctx.Env[args[0].(string)] = returnValue.(string)\n\t\t}\n\tcase \"var.Text.Text\":\n\t\tctx.Env[args[0].(string)] = args[1].(string)\n\t\treturnValue = args[1].(string)\n\tcase \"deprecated.Text\":\n\t\tctx.Log.Info(args[0].(string))\n\tcase \"match.Text\":\n\t\t\/\/ Setup stacks\n\t\tagainst, ok := args[0].(string)\n\t\tif !ok {\n\t\t\tctx.Log.Error(\"AH!\")\n\t\t}\n\t\tctx.MatchStack = append(ctx.MatchStack, against)\n\t\tctx.MatchShouldContinue = append(ctx.MatchShouldContinue, true)\n\t\n\t\t\/\/ Run children\n\t\tctx.runChildren(scope, ins)\n\t\n\t\tif ctx.matchShouldContinue() {\n\t\t\treturnValue = \"false\"\n\t\t} else {\n\t\t\treturnValue = \"true\"\n\t\t}\n\t\n\t\t\/\/ Clear\n\t\tctx.MatchShouldContinue = ctx.MatchShouldContinue[:len(ctx.MatchShouldContinue)-1]\n\t\tctx.MatchStack = ctx.MatchStack[:len(ctx.MatchStack)-1]\n\tcase \"with.Text\":\n\t\treturnValue = \"false\"\n\t\tif ctx.matchShouldContinue() {\n\t\t\tif args[0].(string) == ctx.matchTarget() {\n\t\t\t\tctx.MatchShouldContinue[len(ctx.MatchShouldContinue)-1] = false\n\t\t\t\tctx.runChildren(scope, ins)\n\t\t\t\treturnValue = \"true\"\n\t\t\t}\n\t\t}\n\tcase \"with.Regexp\":\n\t\treturnValue = \"false\"\n\t\tif ctx.matchShouldContinue() {\n\t\t\t\/\/println(matcher.MatchAgainst, matchWith)\n\t\t\tif (args[0].(*rubex.Regexp)).Match([]uint8(ctx.matchTarget())) {\n\t\t\t\tctx.MatchShouldContinue[len(ctx.MatchShouldContinue)-1] = false\n\t\t\t\tctx.runChildren(scope, ins)\n\t\t\t\treturnValue = \"true\"\n\t\t\t}\n\t\t}\n\tcase \"not.Text\":\n\t\treturnValue = \"false\"\n\t\tif ctx.matchShouldContinue() {\n\t\t\tif args[0].(string) != ctx.matchTarget() {\n\t\t\t\tctx.MatchShouldContinue[len(ctx.MatchShouldContinue)-1] = false\n\t\t\t\tctx.runChildren(scope, ins)\n\t\t\t\treturnValue = \"true\"\n\t\t\t}\n\t\t}\n\tcase \"not.Regexp\":\n\t\treturnValue = \"false\"\n\t\tif ctx.matchShouldContinue() {\n\t\t\t\/\/println(matcher.MatchAgainst, matchWith)\n\t\t\tif !(args[0].(*rubex.Regexp)).Match([]uint8(ctx.matchTarget())) {\n\t\t\t\tctx.MatchShouldContinue[len(ctx.MatchShouldContinue)-1] = false\n\t\t\t\tctx.runChildren(scope, ins)\n\t\t\t\treturnValue = \"true\"\n\t\t\t}\n\t\t}\n\tcase \"regexp.Text.Text\":\n\t\tmode := rubex.ONIG_OPTION_DEFAULT\n\t\tif strings.Index(args[1].(string), \"i\") >= 0 {\n\t\t\tmode = rubex.ONIG_OPTION_IGNORECASE\n\t\t}\n\t\tif strings.Index(args[1].(string), \"m\") >= 0 {\n\t\t\tmode = rubex.ONIG_OPTION_MULTILINE\n\t\t}\n\t\tvar err os.Error\n\t\treturnValue, err = rubex.NewRegexp(args[0].(string), mode)\n\t\tif err != nil {\n\t\t\tctx.Log.Error(\"Invalid regexp\")\n\t\t}\n\tcase \"export.Text\":\n\t\tval := make([]string, 2)\n\t\tval[0] = args[0].(string)\n\t\tts := &Scope{Value:\"\"}\n\t\tctx.runChildren(ts, ins)\n\t\tval[1] = ts.Value.(string)\n\t\tctx.Exports = append(ctx.Exports, val)\n\tcase \"log.Text\":\n\t\tctx.Logs = append(ctx.Logs, args[0].(string))\n\n\t\/\/ ATOMIC FUNCTIONS\n\tcase \"concat.Text.Text\":\n\t\t\/\/println(\"Concat:\", args[0].(string), \"+\", args[1].(string))\n\t\treturnValue = args[0].(string) + args[1].(string)\n\tcase \"concat.Text.Text.Text\": \/\/REMOVE\n\t\treturnValue = args[0].(string) + args[1].(string) + args[2].(string)\n\tcase \"downcase.Text\":\n\t\treturnValue = strings.ToLower(args[0].(string))\n\t\treturn\n\tcase \"upcase.Text\":\n\t\treturnValue = strings.ToUpper(args[0].(string))\n\t\treturn\n\tcase \"index.XMLNode\":\n\t\treturnValue = fmt.Sprintf(\"%d\", scope.Index + 1)\n\t\n\t\/\/ TEXT FUNCTIONS\n\tcase \"set.Text\":\n\t\tscope.Value = args[0]\n\tcase \"append.Text\":\n\t\tscope.Value = scope.Value.(string) + args[0].(string)\n\tcase \"prepend.Text\":\n\t\tscope.Value = args[0].(string) + scope.Value.(string)\n\tcase \"replace.Text\":\n\t\tts := &Scope{Value:\"\"}\n\t\tctx.runChildren(ts, ins)\n\t\tscope.Value = strings.Replace(scope.Value.(string), args[0].(string), ts.Value.(string), -1)\n\tcase \"replace.Regexp\":\n\t\tregexp := args[0].(*rubex.Regexp)\n\t\tscope.Value = regexp.GsubFunc(scope.Value.(string), func(match string, captures map[string]string) string {\n\t\t\tusesGlobal := (ctx.Env[\"use_global_replace_vars\"] == \"true\")\n\n\t\t\tfor name, capture := range captures {\n\t\t\t\tif usesGlobal {\n\t\t\t\t\t\/\/println(\"setting $\", name, \"to\", capture)\n\t\t\t\t\tctx.Env[name] = capture\n\t\t\t\t}\n\t\t\t\tctx.vars()[name] = capture\n\t\t\t}\n\n\t\t\treplacementScope := &Scope{Value:match}\n\t\t\tctx.runChildren(replacementScope, ins)\n\t\t\t\/\/println(ins.String())\n\t\t\n\t\t\t\/\/println(\"Replacement:\", replacementScope.Value.(string))\n\t\t\tinnerReplacer := rubex.MustCompile(`[\\\\$](\\d)`)\n\t\t\treturn innerReplacer.GsubFunc(replacementScope.Value.(string), func(_ string, numeric_captures map[string]string) string {\n\t\t\t\tcapture := numeric_captures[\"1\"]\n\t\t\t\tvar val string\n\t\t\t\tif usesGlobal {\n\t\t\t\t\tval = ctx.Env[capture]\n\t\t\t\t} else {\n\t\t\t\t\tval = ctx.vars()[capture].(string)\n\t\t\t\t}\n\t\t\t\treturn val\n\t\t    })\n\t\t})\n\t\treturnValue = scope.Value\n\n\t\/\/ XML FUNCTIONS\n\tcase \"xml\":\n\t\tdoc := libxml.XmlParseString(scope.Value.(string))\n\t\tns := &Scope{Value:doc}\n\t\tctx.runChildren(ns, ins)\n\t\tscope.Value = doc.String()\n\t\treturnValue = scope.Value\n\t\tdoc.Free()\n\tcase \"html\":\n\t\tdoc := libxml.HtmlParseString(scope.Value.(string))\n\t\tns := &Scope{Value:doc}\n\t\tctx.runChildren(ns, ins)\n\t\tscope.Value = doc.DumpHTML()\n\t\treturnValue = scope.Value\n\t\tdoc.Free()\n\tcase \"html_fragment\":\n\t\tdoc := libxml.HtmlParseFragment(scope.Value.(string))\n\t\tns := &Scope{Value: doc.RootElement()}\n\t\tctx.runChildren(ns, ins)\n\t\tscope.Value = ns.Value.(xml.Node).Content()\n\t\treturnValue = scope.Value\n\t\tdoc.Free()\n\tcase \"select.Text\":\n\t\t\/\/ TODO reuse XPath object\n\t\tnode := scope.Value.(xml.Node)\n\t\txpCtx := xpath.NewXPath(node.Doc())\n\t\txpath := xpath.CompileXPath(args[0].(string))\n\t\t\/\/xpath := ctx.XPath(args[0].(string))\n\t\tnodeSet := xpCtx.SearchByCompiledXPath(node, xpath).Slice()\n\t\tdefer xpCtx.Free()\n\t\tif len(nodeSet) == 0 {\n\t\t\treturnValue = \"false\"\n\t\t} else {\n\t\t\treturnValue = \"true\"\n\t\t}\n\n\t\tfor index, node := range(nodeSet) {\n\t\t\tif (node != nil) && node.IsLinked() && node.IsValid() {\n\t\t\t\tns := &Scope{Value: node, Index: index}\n\t\t\t\tctx.runChildren(ns, ins)\n\t\t\t}\n\t\t}\n\tcase \"position.Text\":\n\t\treturnValue = Positions[args[0].(string)]\n\t\n\t\/\/ SHARED NODE FUNCTIONS\n\tcase \"remove\":\n\t\tscope.Value.(xml.Node).Remove()\n\tcase \"inner\", \"inner_text\", \"text\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tts := &Scope{Value:node.Content()}\n\t\tctx.runChildren(ts, ins)\n\t\tval := ts.Value.(string)\n\t\t_, ok := node.(*xml.Element)\n\t\tif ok && node.IsLinked() {\n\t\t\tnode.SetContent(val)\n\t\t}\n\t\treturnValue = val\n\tcase \"value\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tts := &Scope{Value:node.Content()}\n\t\tctx.runChildren(ts, ins)\n\t\tval := ts.Value.(string)\n\t\t_, ok := node.(*xml.Attribute)\n\t\tif ok && node.IsLinked() {\n\t\t\tnode.SetContent(val)\n\t\t}\n\t\treturnValue = val\n\tcase \"name\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tts := &Scope{Value:node.Name()}\n\t\tctx.runChildren(ts, ins)\n\t\tnode.SetName(ts.Value.(string))\n\t\treturnValue = ts.Value.(string)\n\tcase \"dup\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tnewNode := node.Duplicate()\n\t\t_, isElement := node.(*xml.Element)\n\t\tif isElement {\n\t\t\tMoveFunc(newNode, node, AFTER)\n\t\t}\n\t\tns := &Scope{Value:newNode}\n\t\tctx.runChildren(ns, ins)\n\tcase \"fetch.Text\":\n\t\tsearchNode := scope.Value.(xml.Node)\n\t\txPathObj := xpath.NewXPath(searchNode.Doc())\n\t\tnodeSet := xPathObj.Search(searchNode, args[0].(string))\n\t\tif nodeSet.Size() > 0 {\n\t\t\tnode := nodeSet.First()\n\t\t\tattr, ok := node.(*xml.Attribute)\n\t\t\tif ok {\n\t\t\t\treturnValue = attr.Content()\n\t\t\t} else {\n\t\t\t\treturnValue = node.String()\n\t\t\t}\n\t\t}\n\t\txPathObj.Free()\n\n\t\/\/ LIBXML FUNCTIONS\n\tcase \"insert_at.Position.Text\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tposition := args[0].(Position)\n\t\ttagName := args[1].(string)\n\t\telement := node.Doc().NewElement(tagName)\n\t\tMoveFunc(element, node, position)\n\t\tns := &Scope{Value: element}\n\t\tctx.runChildren(ns, ins)\n\tcase \"inject_at.Position.Text\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tposition := args[0].(Position)\n\t\tnodeSet := node.Doc().ParseHtmlFragment(args[1].(string))\n\t\tfor _, newNode := range(nodeSet) {\n\t\t\tMoveFunc(newNode, node, position)\n\t\t}\n\t\tif len(nodeSet) > 0 {\n\t\t\telement, ok := nodeSet[0].(*xml.Element)\n\t\t\tif ok {\n\t\t\t\t\/\/ successfully ran scope\n\t\t\t\treturnValue = \"true\"\n\t\t\t\tns := &Scope{Value: element}\n\t\t\t\tctx.runChildren(ns, ins)\n\t\t\t}\n\t\t} else {\n\t\t\treturnValue = \"false\"\n\t\t}\n\tcase \"cdata.Text\":\n\t\telem, ok := scope.Value.(*xml.Element)\n\t\tif ok {\n\t\t\telem.SetCDataContent(args[0].(string))\n\t\t}\n\tcase \"move.XMLNode.XMLNode.Position\", \"move.Node.Node.Position\":\n\t\t\/\/for name, value := range(ctx.LocalVar) {\n\t\t\/\/\tprintln(name, \":\", value)\n\t\t\/\/}\n\t\tMoveFunc(args[0].(xml.Node), args[1].(xml.Node), args[2].(Position))\n\tcase \"wrap_text_children.Text\":\n\t\treturnValue = \"false\"\n\t\tchild := scope.Value.(xml.Node).First()\n\t\tindex := 0\n\t\ttagName := args[0].(string)\n\t\tfor child != nil {\n\t\t\ttext, ok := child.(*xml.Text)\n\t\t\tchildNext := child.Next()\n\t\t\tif ok {\n\t\t\t\treturnValue = \"true\"\n\t\t\t\twrap := text.Wrap(tagName)\n\t\t\t\tns := &Scope{wrap, index}\n\t\t\t\tctx.runChildren(ns, ins)\n\t\t\t\tindex++\n\t\t\t}\n\t\t\tchild = childNext\n\t\t}\n\n\t\/\/ ATTRIBUTE FUNCTIONS\n\tcase \"attribute.Text\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tname := args[0].(string)\n\t\t_, ok := node.(*xml.Element)\n\t\tif ok == true {\n\t\t\tattr, _ := node.Attribute(name)\n\t\t\t\n\t\t\tas := &Scope{Value:attr}\n\t\t\tctx.runChildren(as, ins)\n\t\t\tif attr.IsLinked() && (attr.Content() == \"\") {\n\t\t\t\tattr.Remove()\n\t\t\t}\n\t\t\tif !attr.IsLinked() {\n\t\t\t\tattr.Free()\n\t\t\t}\n\t\t\treturnValue = \"true\"\n\t\t}\n\tcase \"to_text.XMLNode\":\n\t\treturnValue = scope.Value.(xml.Node).String()\n\tdefault:\n\t\tctx.Log.Error(\"Must implement \" + fun.Name)\n\t}\n\treturn\n}<commit_msg>a node which si linked, is already checked for being valid<commit_after>package shark\n\nimport(\n\t\"strings\"\n\t\"os\"\n\t\"libxml\"\n\t\"fmt\"\n\txml \"libxml\/tree\"\n\ttp \"tritium\/proto\"\n\t\"libxml\/xpath\"\n\t\"rubex\"\n)\n\nfunc (ctx *Ctx) runBuiltIn(fun *Function, scope *Scope, ins *tp.Instruction, args []interface{}) (returnValue interface{}) {\n\treturnValue = \"\"\n\tswitch fun.Name {\n\tcase \"this\":\n\t\treturnValue = scope.Value\n\tcase \"yield\": \n\t\tmyYieldBlock := ctx.yieldBlock()\n\t\tctx.Yields = ctx.Yields[:(len(ctx.Yields)-1)]\n\t\tif (ctx.yieldBlock() != nil) {\n\t\t\treturnValue = ctx.runChildren(scope, myYieldBlock.Ins)\n\t\t} else {\n\t\t\tctx.Log.Error(\"yield() failure\")\n\t\t}\n\t\tctx.Yields = append(ctx.Yields, myYieldBlock)\n\n\tcase \"var.Text\":\n\t\tval := ctx.Env[args[0].(string)]\n\t\treturnValue = val\n\t\tif len(ins.Children) > 0 {\n\t\t\tts := &Scope{Value: val}\n\t\t\tctx.runChildren(ts, ins)\n\t\t\treturnValue = ts.Value\n\t\t\tctx.Env[args[0].(string)] = returnValue.(string)\n\t\t}\n\tcase \"var.Text.Text\":\n\t\tctx.Env[args[0].(string)] = args[1].(string)\n\t\treturnValue = args[1].(string)\n\tcase \"deprecated.Text\":\n\t\tctx.Log.Info(args[0].(string))\n\tcase \"match.Text\":\n\t\t\/\/ Setup stacks\n\t\tagainst, ok := args[0].(string)\n\t\tif !ok {\n\t\t\tctx.Log.Error(\"AH!\")\n\t\t}\n\t\tctx.MatchStack = append(ctx.MatchStack, against)\n\t\tctx.MatchShouldContinue = append(ctx.MatchShouldContinue, true)\n\t\n\t\t\/\/ Run children\n\t\tctx.runChildren(scope, ins)\n\t\n\t\tif ctx.matchShouldContinue() {\n\t\t\treturnValue = \"false\"\n\t\t} else {\n\t\t\treturnValue = \"true\"\n\t\t}\n\t\n\t\t\/\/ Clear\n\t\tctx.MatchShouldContinue = ctx.MatchShouldContinue[:len(ctx.MatchShouldContinue)-1]\n\t\tctx.MatchStack = ctx.MatchStack[:len(ctx.MatchStack)-1]\n\tcase \"with.Text\":\n\t\treturnValue = \"false\"\n\t\tif ctx.matchShouldContinue() {\n\t\t\tif args[0].(string) == ctx.matchTarget() {\n\t\t\t\tctx.MatchShouldContinue[len(ctx.MatchShouldContinue)-1] = false\n\t\t\t\tctx.runChildren(scope, ins)\n\t\t\t\treturnValue = \"true\"\n\t\t\t}\n\t\t}\n\tcase \"with.Regexp\":\n\t\treturnValue = \"false\"\n\t\tif ctx.matchShouldContinue() {\n\t\t\t\/\/println(matcher.MatchAgainst, matchWith)\n\t\t\tif (args[0].(*rubex.Regexp)).Match([]uint8(ctx.matchTarget())) {\n\t\t\t\tctx.MatchShouldContinue[len(ctx.MatchShouldContinue)-1] = false\n\t\t\t\tctx.runChildren(scope, ins)\n\t\t\t\treturnValue = \"true\"\n\t\t\t}\n\t\t}\n\tcase \"not.Text\":\n\t\treturnValue = \"false\"\n\t\tif ctx.matchShouldContinue() {\n\t\t\tif args[0].(string) != ctx.matchTarget() {\n\t\t\t\tctx.MatchShouldContinue[len(ctx.MatchShouldContinue)-1] = false\n\t\t\t\tctx.runChildren(scope, ins)\n\t\t\t\treturnValue = \"true\"\n\t\t\t}\n\t\t}\n\tcase \"not.Regexp\":\n\t\treturnValue = \"false\"\n\t\tif ctx.matchShouldContinue() {\n\t\t\t\/\/println(matcher.MatchAgainst, matchWith)\n\t\t\tif !(args[0].(*rubex.Regexp)).Match([]uint8(ctx.matchTarget())) {\n\t\t\t\tctx.MatchShouldContinue[len(ctx.MatchShouldContinue)-1] = false\n\t\t\t\tctx.runChildren(scope, ins)\n\t\t\t\treturnValue = \"true\"\n\t\t\t}\n\t\t}\n\tcase \"regexp.Text.Text\":\n\t\tmode := rubex.ONIG_OPTION_DEFAULT\n\t\tif strings.Index(args[1].(string), \"i\") >= 0 {\n\t\t\tmode = rubex.ONIG_OPTION_IGNORECASE\n\t\t}\n\t\tif strings.Index(args[1].(string), \"m\") >= 0 {\n\t\t\tmode = rubex.ONIG_OPTION_MULTILINE\n\t\t}\n\t\tvar err os.Error\n\t\treturnValue, err = rubex.NewRegexp(args[0].(string), mode)\n\t\tif err != nil {\n\t\t\tctx.Log.Error(\"Invalid regexp\")\n\t\t}\n\tcase \"export.Text\":\n\t\tval := make([]string, 2)\n\t\tval[0] = args[0].(string)\n\t\tts := &Scope{Value:\"\"}\n\t\tctx.runChildren(ts, ins)\n\t\tval[1] = ts.Value.(string)\n\t\tctx.Exports = append(ctx.Exports, val)\n\tcase \"log.Text\":\n\t\tctx.Logs = append(ctx.Logs, args[0].(string))\n\n\t\/\/ ATOMIC FUNCTIONS\n\tcase \"concat.Text.Text\":\n\t\t\/\/println(\"Concat:\", args[0].(string), \"+\", args[1].(string))\n\t\treturnValue = args[0].(string) + args[1].(string)\n\tcase \"concat.Text.Text.Text\": \/\/REMOVE\n\t\treturnValue = args[0].(string) + args[1].(string) + args[2].(string)\n\tcase \"downcase.Text\":\n\t\treturnValue = strings.ToLower(args[0].(string))\n\t\treturn\n\tcase \"upcase.Text\":\n\t\treturnValue = strings.ToUpper(args[0].(string))\n\t\treturn\n\tcase \"index.XMLNode\":\n\t\treturnValue = fmt.Sprintf(\"%d\", scope.Index + 1)\n\t\n\t\/\/ TEXT FUNCTIONS\n\tcase \"set.Text\":\n\t\tscope.Value = args[0]\n\tcase \"append.Text\":\n\t\tscope.Value = scope.Value.(string) + args[0].(string)\n\tcase \"prepend.Text\":\n\t\tscope.Value = args[0].(string) + scope.Value.(string)\n\tcase \"replace.Text\":\n\t\tts := &Scope{Value:\"\"}\n\t\tctx.runChildren(ts, ins)\n\t\tscope.Value = strings.Replace(scope.Value.(string), args[0].(string), ts.Value.(string), -1)\n\tcase \"replace.Regexp\":\n\t\tregexp := args[0].(*rubex.Regexp)\n\t\tscope.Value = regexp.GsubFunc(scope.Value.(string), func(match string, captures map[string]string) string {\n\t\t\tusesGlobal := (ctx.Env[\"use_global_replace_vars\"] == \"true\")\n\n\t\t\tfor name, capture := range captures {\n\t\t\t\tif usesGlobal {\n\t\t\t\t\t\/\/println(\"setting $\", name, \"to\", capture)\n\t\t\t\t\tctx.Env[name] = capture\n\t\t\t\t}\n\t\t\t\tctx.vars()[name] = capture\n\t\t\t}\n\n\t\t\treplacementScope := &Scope{Value:match}\n\t\t\tctx.runChildren(replacementScope, ins)\n\t\t\t\/\/println(ins.String())\n\t\t\n\t\t\t\/\/println(\"Replacement:\", replacementScope.Value.(string))\n\t\t\tinnerReplacer := rubex.MustCompile(`[\\\\$](\\d)`)\n\t\t\treturn innerReplacer.GsubFunc(replacementScope.Value.(string), func(_ string, numeric_captures map[string]string) string {\n\t\t\t\tcapture := numeric_captures[\"1\"]\n\t\t\t\tvar val string\n\t\t\t\tif usesGlobal {\n\t\t\t\t\tval = ctx.Env[capture]\n\t\t\t\t} else {\n\t\t\t\t\tval = ctx.vars()[capture].(string)\n\t\t\t\t}\n\t\t\t\treturn val\n\t\t    })\n\t\t})\n\t\treturnValue = scope.Value\n\n\t\/\/ XML FUNCTIONS\n\tcase \"xml\":\n\t\tdoc := libxml.XmlParseString(scope.Value.(string))\n\t\tns := &Scope{Value:doc}\n\t\tctx.runChildren(ns, ins)\n\t\tscope.Value = doc.String()\n\t\treturnValue = scope.Value\n\t\tdoc.Free()\n\tcase \"html\":\n\t\tdoc := libxml.HtmlParseString(scope.Value.(string))\n\t\tns := &Scope{Value:doc}\n\t\tctx.runChildren(ns, ins)\n\t\tscope.Value = doc.DumpHTML()\n\t\treturnValue = scope.Value\n\t\tdoc.Free()\n\tcase \"html_fragment\":\n\t\tdoc := libxml.HtmlParseFragment(scope.Value.(string))\n\t\tns := &Scope{Value: doc.RootElement()}\n\t\tctx.runChildren(ns, ins)\n\t\tscope.Value = ns.Value.(xml.Node).Content()\n\t\treturnValue = scope.Value\n\t\tdoc.Free()\n\tcase \"select.Text\":\n\t\t\/\/ TODO reuse XPath object\n\t\tnode := scope.Value.(xml.Node)\n\t\txpCtx := xpath.NewXPath(node.Doc())\n\t\txpath := xpath.CompileXPath(args[0].(string))\n\t\t\/\/xpath := ctx.XPath(args[0].(string))\n\t\tnodeSet := xpCtx.SearchByCompiledXPath(node, xpath).Slice()\n\t\tprintln(\"Node search for\", args[0].(string), \"returned this many results\", len(nodeSet))\n\t\tdefer xpCtx.Free()\n\t\tif len(nodeSet) == 0 {\n\t\t\treturnValue = \"false\"\n\t\t} else {\n\t\t\treturnValue = \"true\"\n\t\t}\n\n\t\tfor index, node := range(nodeSet) {\n\t\t\tif (node != nil) && node.IsLinked() {\n\t\t\t\tns := &Scope{Value: node, Index: index}\n\t\t\t\tctx.runChildren(ns, ins)\n\t\t\t}\n\t\t}\n\tcase \"position.Text\":\n\t\treturnValue = Positions[args[0].(string)]\n\t\n\t\/\/ SHARED NODE FUNCTIONS\n\tcase \"remove\":\n\t\tscope.Value.(xml.Node).Remove()\n\tcase \"inner\", \"inner_text\", \"text\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tts := &Scope{Value:node.Content()}\n\t\tctx.runChildren(ts, ins)\n\t\tval := ts.Value.(string)\n\t\t_, ok := node.(*xml.Element)\n\t\tif ok && node.IsLinked() {\n\t\t\tnode.SetContent(val)\n\t\t}\n\t\treturnValue = val\n\tcase \"value\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tts := &Scope{Value:node.Content()}\n\t\tctx.runChildren(ts, ins)\n\t\tval := ts.Value.(string)\n\t\t_, ok := node.(*xml.Attribute)\n\t\tif ok && node.IsLinked() {\n\t\t\tnode.SetContent(val)\n\t\t}\n\t\treturnValue = val\n\tcase \"name\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tts := &Scope{Value:node.Name()}\n\t\tctx.runChildren(ts, ins)\n\t\tnode.SetName(ts.Value.(string))\n\t\treturnValue = ts.Value.(string)\n\tcase \"dup\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tnewNode := node.Duplicate()\n\t\t_, isElement := node.(*xml.Element)\n\t\tif isElement {\n\t\t\tMoveFunc(newNode, node, AFTER)\n\t\t}\n\t\tns := &Scope{Value:newNode}\n\t\tctx.runChildren(ns, ins)\n\tcase \"fetch.Text\":\n\t\tsearchNode := scope.Value.(xml.Node)\n\t\txPathObj := xpath.NewXPath(searchNode.Doc())\n\t\tnodeSet := xPathObj.Search(searchNode, args[0].(string))\n\t\tif nodeSet.Size() > 0 {\n\t\t\tnode := nodeSet.First()\n\t\t\tattr, ok := node.(*xml.Attribute)\n\t\t\tif ok {\n\t\t\t\treturnValue = attr.Content()\n\t\t\t} else {\n\t\t\t\treturnValue = node.String()\n\t\t\t}\n\t\t}\n\t\txPathObj.Free()\n\n\t\/\/ LIBXML FUNCTIONS\n\tcase \"insert_at.Position.Text\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tposition := args[0].(Position)\n\t\ttagName := args[1].(string)\n\t\telement := node.Doc().NewElement(tagName)\n\t\tMoveFunc(element, node, position)\n\t\tns := &Scope{Value: element}\n\t\tctx.runChildren(ns, ins)\n\tcase \"inject_at.Position.Text\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tposition := args[0].(Position)\n\t\tnodeSet := node.Doc().ParseHtmlFragment(args[1].(string))\n\t\tfor _, newNode := range(nodeSet) {\n\t\t\tMoveFunc(newNode, node, position)\n\t\t}\n\t\tif len(nodeSet) > 0 {\n\t\t\telement, ok := nodeSet[0].(*xml.Element)\n\t\t\tif ok {\n\t\t\t\t\/\/ successfully ran scope\n\t\t\t\treturnValue = \"true\"\n\t\t\t\tns := &Scope{Value: element}\n\t\t\t\tctx.runChildren(ns, ins)\n\t\t\t}\n\t\t} else {\n\t\t\treturnValue = \"false\"\n\t\t}\n\tcase \"cdata.Text\":\n\t\telem, ok := scope.Value.(*xml.Element)\n\t\tif ok {\n\t\t\telem.SetCDataContent(args[0].(string))\n\t\t}\n\tcase \"move.XMLNode.XMLNode.Position\", \"move.Node.Node.Position\":\n\t\t\/\/for name, value := range(ctx.LocalVar) {\n\t\t\/\/\tprintln(name, \":\", value)\n\t\t\/\/}\n\t\tMoveFunc(args[0].(xml.Node), args[1].(xml.Node), args[2].(Position))\n\tcase \"wrap_text_children.Text\":\n\t\treturnValue = \"false\"\n\t\tchild := scope.Value.(xml.Node).First()\n\t\tindex := 0\n\t\ttagName := args[0].(string)\n\t\tfor child != nil {\n\t\t\ttext, ok := child.(*xml.Text)\n\t\t\tchildNext := child.Next()\n\t\t\tif ok {\n\t\t\t\treturnValue = \"true\"\n\t\t\t\twrap := text.Wrap(tagName)\n\t\t\t\tns := &Scope{wrap, index}\n\t\t\t\tctx.runChildren(ns, ins)\n\t\t\t\tindex++\n\t\t\t}\n\t\t\tchild = childNext\n\t\t}\n\n\t\/\/ ATTRIBUTE FUNCTIONS\n\tcase \"attribute.Text\":\n\t\tnode := scope.Value.(xml.Node)\n\t\tname := args[0].(string)\n\t\t_, ok := node.(*xml.Element)\n\t\tif ok == true {\n\t\t\tattr, _ := node.Attribute(name)\n\t\t\t\n\t\t\tas := &Scope{Value:attr}\n\t\t\tctx.runChildren(as, ins)\n\t\t\tif attr.IsLinked() && (attr.Content() == \"\") {\n\t\t\t\tattr.Remove()\n\t\t\t}\n\t\t\tif !attr.IsLinked() {\n\t\t\t\tattr.Free()\n\t\t\t}\n\t\t\treturnValue = \"true\"\n\t\t}\n\tcase \"to_text.XMLNode\":\n\t\treturnValue = scope.Value.(xml.Node).String()\n\tdefault:\n\t\tctx.Log.Error(\"Must implement \" + fun.Name)\n\t}\n\treturn\n}<|endoftext|>"}
{"text":"<commit_before>package util\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"net\/http\"\n)\n\n\/\/ A comma, as defined in https:\/\/tools.ietf.org\/html\/rfc7230#section-7, with\n\/\/ OWS defined in https:\/\/tools.ietf.org\/html\/rfc7230#appendix-B. This is\n\/\/ commonly used as a separator in header field value definitions.\nvar Comma *regexp.Regexp = regexp.MustCompile(`[ \\t]*,[ \\t]*`)\n\n\/\/ Conditional request headers that ServeHTTP may receive and need to be sent with fetchURL.\n\/\/ https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTTP\/Conditional_requests#Conditional_headers\nvar ConditionalRequestHeaders = map[string]bool{\n\t\"If-Match\":            true,\n\t\"If-None-Match\":       true,\n\t\"If-Modified-Since\":   true,\n\t\"If-Unmodified-Since\": true,\n\t\"If-Range\":            true,\n}\n\n\/\/ The following hop-by-hop headers should be removed even when not specified\n\/\/ in Connection, for backwards compatibility with downstream servers that were\n\/\/ written against RFC 2616, and expect gateways to behave according to\n\/\/ https:\/\/tools.ietf.org\/html\/rfc2616#section-13.5.1. (Note: \"Trailers\" is a\n\/\/ typo there; should be \"Trailer\".)\n\/\/\n\/\/ Connection header should also be removed per\n\/\/ https:\/\/tools.ietf.org\/html\/rfc7230#section-6.1.\n\/\/\n\/\/ Proxy-Connection should also be deleted, per\n\/\/ https:\/\/github.com\/WICG\/webpackage\/pull\/339.\nvar legacyHeaders = map[string]bool{\n\t\"Connection\": true,\n\t\"Keep-Alive\": true,\n\t\"Proxy-Authenticate\": true,\n\t\"Proxy-Authorization\": true,\n\t\"Proxy-Connection\": true,\n\t\"TE\": true,\n\t\"Trailer\": true,\n\t\"Transfer-Encoding\": true,\n\t\"Upgrade\": true,\n}\n\n\/\/ Via is implicitly forwarded and disallowed to be included in\n\/\/ config.ForwardedRequestHeaders\nvar notForwardedRequestHeader = map[string]bool{\n\t\"Via\": true,\n}\n\n\/\/ Remove hop-by-hop headers, per https:\/\/tools.ietf.org\/html\/rfc7230#section-6.1.\nfunc RemoveHopByHopHeaders(h http.Header) {\n\tif connections, ok := h[http.CanonicalHeaderKey(\"Connection\")]; ok {\n\t\tfor _, connection := range connections {\n\t\t\theaderNames := Comma.Split(connection, -1)\n\t\t\tfor _, headerName := range headerNames {\n\t\t\t\th.Del(headerName)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor headerName, _ := range legacyHeaders {\n\t\th.Del(headerName)\n\t}\n}\n\nfunc haveInvalidForwardedRequestHeader(h string) string {\n\tif _, ok := legacyHeaders[http.CanonicalHeaderKey(h)]; ok {\n\t\treturn fmt.Sprintf(\"have hop-by-hop header of %s\", h)\n\t}\n\tif _, ok := ConditionalRequestHeaders[http.CanonicalHeaderKey(h)]; ok {\n\t\treturn fmt.Sprintf(\"have conditional request header of %s\", h)\n\t}\n\tif _, ok := notForwardedRequestHeader[http.CanonicalHeaderKey(h)]; ok {\n\t\treturn fmt.Sprintf(\"include request header of %s\", h)\n\t}\n\treturn \"\"\n}\n<commit_msg>fix entries of hop-by-hop header (#311)<commit_after>package util\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"net\/http\"\n)\n\n\/\/ A comma, as defined in https:\/\/tools.ietf.org\/html\/rfc7230#section-7, with\n\/\/ OWS defined in https:\/\/tools.ietf.org\/html\/rfc7230#appendix-B. This is\n\/\/ commonly used as a separator in header field value definitions.\nvar Comma *regexp.Regexp = regexp.MustCompile(`[ \\t]*,[ \\t]*`)\n\n\/\/ Conditional request headers that ServeHTTP may receive and need to be sent with fetchURL.\n\/\/ https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/HTTP\/Conditional_requests#Conditional_headers\nvar ConditionalRequestHeaders = map[string]bool{\n\t\"If-Match\":            true,\n\t\"If-None-Match\":       true,\n\t\"If-Modified-Since\":   true,\n\t\"If-Unmodified-Since\": true,\n\t\"If-Range\":            true,\n}\n\n\/\/ The following hop-by-hop headers should be removed even when not specified\n\/\/ in Connection, for backwards compatibility with downstream servers that were\n\/\/ written against RFC 2616, and expect gateways to behave according to\n\/\/ https:\/\/tools.ietf.org\/html\/rfc2616#section-13.5.1. (Note: \"Trailers\" is a\n\/\/ typo there; should be \"Trailer\".)\n\/\/\n\/\/ Connection header should also be removed per\n\/\/ https:\/\/tools.ietf.org\/html\/rfc7230#section-6.1.\n\/\/\n\/\/ Proxy-Connection should also be deleted, per\n\/\/ https:\/\/github.com\/WICG\/webpackage\/pull\/339.\nvar legacyHeaders = map[string]bool{\n\t\"Connection\": true,\n\t\"Keep-Alive\": true,\n\t\"Proxy-Authenticate\": true,\n\t\"Proxy-Connection\": true,\n\t\"Trailer\": true,\n\t\"Transfer-Encoding\": true,\n\t\"Upgrade\": true,\n}\n\n\/\/ Via is implicitly forwarded and disallowed to be included in\n\/\/ config.ForwardedRequestHeaders\nvar notForwardedRequestHeader = map[string]bool{\n\t\"Via\": true,\n}\n\n\/\/ Remove hop-by-hop headers, per https:\/\/tools.ietf.org\/html\/rfc7230#section-6.1.\nfunc RemoveHopByHopHeaders(h http.Header) {\n\tif connections, ok := h[http.CanonicalHeaderKey(\"Connection\")]; ok {\n\t\tfor _, connection := range connections {\n\t\t\theaderNames := Comma.Split(connection, -1)\n\t\t\tfor _, headerName := range headerNames {\n\t\t\t\th.Del(headerName)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor headerName, _ := range legacyHeaders {\n\t\th.Del(headerName)\n\t}\n}\n\nfunc haveInvalidForwardedRequestHeader(h string) string {\n\tif _, ok := legacyHeaders[http.CanonicalHeaderKey(h)]; ok {\n\t\treturn fmt.Sprintf(\"have hop-by-hop header of %s\", h)\n\t}\n\tif _, ok := ConditionalRequestHeaders[http.CanonicalHeaderKey(h)]; ok {\n\t\treturn fmt.Sprintf(\"have conditional request header of %s\", h)\n\t}\n\tif _, ok := notForwardedRequestHeader[http.CanonicalHeaderKey(h)]; ok {\n\t\treturn fmt.Sprintf(\"include request header of %s\", h)\n\t}\n\treturn \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build integration\n\npackage integration\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/openshift\/origin\/pkg\/dockerregistry\"\n)\n\nfunc TestRegistryClientConnect(t *testing.T) {\n\tc := dockerregistry.NewClient()\n\tconn, err := c.Connect(\"docker.io\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor _, s := range []string{\"index.docker.io\", \"https:\/\/docker.io\", \"https:\/\/index.docker.io\"} {\n\t\totherConn, err := c.Connect(s, false)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s: can't connect: %v\", s, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(otherConn, conn) {\n\t\t\tt.Errorf(\"%s: did not reuse connection: %#v %#v\", s, conn, otherConn)\n\t\t}\n\t}\n\n\totherConn, err := c.Connect(\"index.docker.io:443\", false)\n\tif err != nil || reflect.DeepEqual(otherConn, conn) {\n\t\tt.Errorf(\"should not have reused index.docker.io:443: %v\", err)\n\t}\n\n\tif _, err := c.Connect(\"http:\/\/ba%3\/\", false); err == nil {\n\t\tt.Error(\"Unexpected non-error\")\n\t}\n}\n\nfunc TestRegistryClientConnectPulpRegistry(t *testing.T) {\n\tc := dockerregistry.NewClient()\n\tconn, err := c.Connect(\"registry.access.redhat.com\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\timage, err := conn.ImageByTag(\"library\", \"rhel\", \"latest\")\n\tif err != nil {\n\t\tt.Fatalf(\"unable to retrieve image info: %v\", err)\n\t}\n\tif len(image.ID) == 0 {\n\t\tt.Fatalf(\"image had no ID: %#v\", image)\n\t}\n}\n\nfunc TestRegistryClientV2DockerHub(t *testing.T) {\n\tc := dockerregistry.NewClient()\n\tconn, err := c.Connect(\"index.docker.io\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\timage, err := conn.ImageByTag(\"kubernetes\", \"guestbook\", \"latest\")\n\t\/\/ The V2 docker hub registry seems to have a bug for this repo, should eventually get fixed\n\tif !dockerregistry.IsTagNotFound(err) {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\t\/\/ a v1 only path\n\tconn, err = c.Connect(\"registry.hub.docker.com\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\timage, err = conn.ImageByTag(\"kubernetes\", \"guestbook\", \"latest\")\n\tif err != nil {\n\t\tt.Fatalf(\"unable to retrieve image info: %v\", err)\n\t}\n\tif len(image.ID) == 0 {\n\t\tt.Fatalf(\"image had no ID: %#v\", image)\n\t}\n}\n\nfunc TestRegistryClientRegistryNotFound(t *testing.T) {\n\tconn, err := dockerregistry.NewClient().Connect(\"localhost:65000\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif _, err := conn.ImageByID(\"foo\", \"bar\", \"baz\"); !dockerregistry.IsRegistryNotFound(err) {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestRegistryClientImage(t *testing.T) {\n\tfor _, v2 := range []bool{true, false} {\n\t\thost := \"index.docker.io\"\n\t\tif !v2 {\n\t\t\thost = \"registry.hub.docker.com\"\n\t\t}\n\t\tconn, err := dockerregistry.NewClient().Connect(host, false)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif _, err := conn.ImageByTag(\"openshift\", \"origin-not-found\", \"latest\"); !dockerregistry.IsRepositoryNotFound(err) && !dockerregistry.IsTagNotFound(err) {\n\t\t\tt.Errorf(\"V2=%t: unexpected error: %v\", v2, err)\n\t\t}\n\n\t\timage, err := conn.ImageByTag(\"openshift\", \"origin\", \"latest\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"V2=%t: %v\", v2, err)\n\t\t}\n\t\tif len(image.ContainerConfig.Entrypoint) == 0 {\n\t\t\tt.Errorf(\"V2=%t: unexpected image: %#v\", v2, image)\n\t\t}\n\t\tif v2 && !image.PullByID {\n\t\t\tt.Errorf(\"V2=%t: should be able to pull by ID %s\", v2, image.ID)\n\t\t}\n\n\t\tother, err := conn.ImageByID(\"openshift\", \"origin\", image.ID)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif !reflect.DeepEqual(other.ContainerConfig.Entrypoint, image.ContainerConfig.Entrypoint) {\n\t\t\tt.Errorf(\"V2=%t: unexpected image: %#v\", v2, other)\n\t\t}\n\t}\n}\n\nfunc TestRegistryClientQuayIOImage(t *testing.T) {\n\tconn, err := dockerregistry.NewClient().Connect(\"quay.io\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t_, err = conn.ImageByTag(\"coreos\", \"etcd\", \"latest\")\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %v\", err)\n\t}\n}\n<commit_msg>Disable quay.io test<commit_after>\/\/ +build integration\n\npackage integration\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/openshift\/origin\/pkg\/dockerregistry\"\n)\n\nfunc TestRegistryClientConnect(t *testing.T) {\n\tc := dockerregistry.NewClient()\n\tconn, err := c.Connect(\"docker.io\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor _, s := range []string{\"index.docker.io\", \"https:\/\/docker.io\", \"https:\/\/index.docker.io\"} {\n\t\totherConn, err := c.Connect(s, false)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%s: can't connect: %v\", s, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(otherConn, conn) {\n\t\t\tt.Errorf(\"%s: did not reuse connection: %#v %#v\", s, conn, otherConn)\n\t\t}\n\t}\n\n\totherConn, err := c.Connect(\"index.docker.io:443\", false)\n\tif err != nil || reflect.DeepEqual(otherConn, conn) {\n\t\tt.Errorf(\"should not have reused index.docker.io:443: %v\", err)\n\t}\n\n\tif _, err := c.Connect(\"http:\/\/ba%3\/\", false); err == nil {\n\t\tt.Error(\"Unexpected non-error\")\n\t}\n}\n\nfunc TestRegistryClientConnectPulpRegistry(t *testing.T) {\n\tc := dockerregistry.NewClient()\n\tconn, err := c.Connect(\"registry.access.redhat.com\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\timage, err := conn.ImageByTag(\"library\", \"rhel\", \"latest\")\n\tif err != nil {\n\t\tt.Fatalf(\"unable to retrieve image info: %v\", err)\n\t}\n\tif len(image.ID) == 0 {\n\t\tt.Fatalf(\"image had no ID: %#v\", image)\n\t}\n}\n\nfunc TestRegistryClientV2DockerHub(t *testing.T) {\n\tc := dockerregistry.NewClient()\n\tconn, err := c.Connect(\"index.docker.io\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\timage, err := conn.ImageByTag(\"kubernetes\", \"guestbook\", \"latest\")\n\t\/\/ The V2 docker hub registry seems to have a bug for this repo, should eventually get fixed\n\tif !dockerregistry.IsTagNotFound(err) {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\n\t\/\/ a v1 only path\n\tconn, err = c.Connect(\"registry.hub.docker.com\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\timage, err = conn.ImageByTag(\"kubernetes\", \"guestbook\", \"latest\")\n\tif err != nil {\n\t\tt.Fatalf(\"unable to retrieve image info: %v\", err)\n\t}\n\tif len(image.ID) == 0 {\n\t\tt.Fatalf(\"image had no ID: %#v\", image)\n\t}\n}\n\nfunc TestRegistryClientRegistryNotFound(t *testing.T) {\n\tconn, err := dockerregistry.NewClient().Connect(\"localhost:65000\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif _, err := conn.ImageByID(\"foo\", \"bar\", \"baz\"); !dockerregistry.IsRegistryNotFound(err) {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestRegistryClientImage(t *testing.T) {\n\tfor _, v2 := range []bool{true, false} {\n\t\thost := \"index.docker.io\"\n\t\tif !v2 {\n\t\t\thost = \"registry.hub.docker.com\"\n\t\t}\n\t\tconn, err := dockerregistry.NewClient().Connect(host, false)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif _, err := conn.ImageByTag(\"openshift\", \"origin-not-found\", \"latest\"); !dockerregistry.IsRepositoryNotFound(err) && !dockerregistry.IsTagNotFound(err) {\n\t\t\tt.Errorf(\"V2=%t: unexpected error: %v\", v2, err)\n\t\t}\n\n\t\timage, err := conn.ImageByTag(\"openshift\", \"origin\", \"latest\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"V2=%t: %v\", v2, err)\n\t\t}\n\t\tif len(image.ContainerConfig.Entrypoint) == 0 {\n\t\t\tt.Errorf(\"V2=%t: unexpected image: %#v\", v2, image)\n\t\t}\n\t\tif v2 && !image.PullByID {\n\t\t\tt.Errorf(\"V2=%t: should be able to pull by ID %s\", v2, image.ID)\n\t\t}\n\n\t\tother, err := conn.ImageByID(\"openshift\", \"origin\", image.ID)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif !reflect.DeepEqual(other.ContainerConfig.Entrypoint, image.ContainerConfig.Entrypoint) {\n\t\t\tt.Errorf(\"V2=%t: unexpected image: %#v\", v2, other)\n\t\t}\n\t}\n}\n\nfunc TestRegistryClientQuayIOImage(t *testing.T) {\n\tconn, err := dockerregistry.NewClient().Connect(\"quay.io\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t_, err = conn.ImageByTag(\"coreos\", \"etcd\", \"latest\")\n\tif err != nil {\n\t\tt.Skip(\"SKIPPING: unexpected error from quay.io: %v\", err)\n\t\t\/\/t.Errorf(\"unexpected error: %v\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package vcsclient\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"sourcegraph.com\/sourcegraph\/vcsstore\/git\"\n)\n\ntype gitTransport struct {\n\tclient   *Client\n\tcloneURL *url.URL\n}\n\nvar _ git.GitTransport = &gitTransport{}\n\nfunc (t *gitTransport) InfoRefs(w io.Writer, service string) error {\n\trp := &repository{client: t.client, vcsType: \"git\", cloneURL: t.cloneURL}\n\turlQuery := struct {\n\t\tService string `url:\"service\"`\n\t}{\n\t\tService: service,\n\t}\n\tu, err := rp.url(git.RouteGitInfoRefs, nil, urlQuery)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu = t.client.BaseURL.ResolveReference(u)\n\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar out bytes.Buffer\n\t_, err = t.client.Do(req, &out)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(w, &out)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (t *gitTransport) ReceivePack(w io.Writer, rdr io.Reader, opt git.GitTransportOpt) error {\n\trp := &repository{client: t.client, vcsType: \"git\", cloneURL: t.cloneURL}\n\tu, err := rp.url(git.RouteGitReceivePack, nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu = t.client.BaseURL.ResolveReference(u)\n\n\treq, err := http.NewRequest(\"POST\", u.String(), rdr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"content-encoding\", opt.ContentEncoding)\n\n\tvar out bytes.Buffer\n\t_, err = t.client.Do(req, &out)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(w, &out)\n\n\treturn nil\n}\n\nfunc (t *gitTransport) UploadPack(w io.Writer, rdr io.Reader, opt git.GitTransportOpt) error {\n\trp := &repository{client: t.client, vcsType: \"git\", cloneURL: t.cloneURL}\n\tu, err := rp.url(git.RouteGitUploadPack, nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu = t.client.BaseURL.ResolveReference(u)\n\n\treq, err := http.NewRequest(\"POST\", u.String(), rdr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"content-encoding\", opt.ContentEncoding)\n\n\tvar out bytes.Buffer\n\t_, err = t.client.Do(req, &out)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(w, &out)\n\n\treturn nil\n}\n<commit_msg>fix git client<commit_after>package vcsclient\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"sourcegraph.com\/sourcegraph\/vcsstore\/git\"\n)\n\ntype gitTransport struct {\n\tclient   *Client\n\tcloneURL *url.URL\n}\n\nvar _ git.GitTransport = &gitTransport{}\n\nfunc (t *gitTransport) InfoRefs(w io.Writer, service string) error {\n\trp := &repository{client: t.client, vcsType: \"git\", cloneURL: t.cloneURL}\n\turlQuery := struct {\n\t\tService string `url:\"service\"`\n\t}{\n\t\tService: \"git-\" + service,\n\t}\n\tu, err := rp.url(git.RouteGitInfoRefs, nil, urlQuery)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu = t.client.BaseURL.ResolveReference(u)\n\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"User-Agent\", \"git\/1.9.1\") \/\/ TODO: kludge\n\tvar out bytes.Buffer\n\t_, err = t.client.Do(req, &out)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(w, &out)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (t *gitTransport) ReceivePack(w io.Writer, rdr io.Reader, opt git.GitTransportOpt) error {\n\trp := &repository{client: t.client, vcsType: \"git\", cloneURL: t.cloneURL}\n\tu, err := rp.url(git.RouteGitReceivePack, nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu = t.client.BaseURL.ResolveReference(u)\n\n\treq, err := http.NewRequest(\"POST\", u.String(), rdr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"User-Agent\", \"git\/1.9.1\") \/\/ TODO: kludge\n\treq.Header.Set(\"content-encoding\", opt.ContentEncoding)\n\n\tvar out bytes.Buffer\n\t_, err = t.client.Do(req, &out)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(w, &out)\n\n\treturn nil\n}\n\nfunc (t *gitTransport) UploadPack(w io.Writer, rdr io.Reader, opt git.GitTransportOpt) error {\n\trp := &repository{client: t.client, vcsType: \"git\", cloneURL: t.cloneURL}\n\tu, err := rp.url(git.RouteGitUploadPack, nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu = t.client.BaseURL.ResolveReference(u)\n\n\treq, err := http.NewRequest(\"POST\", u.String(), rdr)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"User-Agent\", \"git\/1.9.1\") \/\/ TODO: kludge\n\treq.Header.Set(\"content-encoding\", opt.ContentEncoding)\n\n\tvar out bytes.Buffer\n\t_, err = t.client.Do(req, &out)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(w, &out)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n\/\/ not use this file except in compliance with the License. A copy of the\n\/\/ License is located at\n\/\/\n\/\/\thttp:\/\/aws.amazon.com\/apache2.0\/\n\/\/\n\/\/ or in the \"license\" file accompanying this file. This file is distributed\n\/\/ on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n\/\/ express or implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\npackage handlers\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/cihub\/seelog\"\n)\n\n\/\/ LoggingHandler is used to log all requests for an endpoint.\ntype LoggingHandler struct{ h http.Handler }\n\n\/\/ NewLoggingHandler creates a new LoggingHandler object.\nfunc NewLoggingHandler(handler http.Handler) LoggingHandler {\n\treturn LoggingHandler{h: handler}\n}\n\n\/\/ ServeHTTP logs the method and remote address of the request.\nfunc (lh LoggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tseelog.Info(\"Handling http request\", \"method\", r.Method, \"from\", r.RemoteAddr)\n\tlh.h.ServeHTTP(w, r)\n}\n<commit_msg>Change log line handling http request to DEBUG<commit_after>\/\/ Copyright 2014-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n\/\/ not use this file except in compliance with the License. A copy of the\n\/\/ License is located at\n\/\/\n\/\/\thttp:\/\/aws.amazon.com\/apache2.0\/\n\/\/\n\/\/ or in the \"license\" file accompanying this file. This file is distributed\n\/\/ on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n\/\/ express or implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\npackage handlers\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/cihub\/seelog\"\n)\n\n\/\/ LoggingHandler is used to log all requests for an endpoint.\ntype LoggingHandler struct{ h http.Handler }\n\n\/\/ NewLoggingHandler creates a new LoggingHandler object.\nfunc NewLoggingHandler(handler http.Handler) LoggingHandler {\n\treturn LoggingHandler{h: handler}\n}\n\n\/\/ ServeHTTP logs the method and remote address of the request.\nfunc (lh LoggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tseelog.Debug(\"Handling http request\", \"method\", r.Method, \"from\", r.RemoteAddr)\n\tlh.h.ServeHTTP(w, r)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build datasources\n\npackage sources\n\nimport (\n\t\"log\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/OWASP\/Amass\/amass\/core\"\n)\n\nfunc TestThreaTCrowd(t *testing.T) {\n\tconfig := &core.Config{}\n\tconfig.AddDomain(\"google.com\")\n\tbuf := new(strings.Builder)\n\tconfig.Log = log.New(buf, \"\", log.Lmicroseconds)\n\n\tout := make(chan *core.Request)\n\tbus := core.NewEventBus()\n\tbus.Subscribe(core.NewNameTopic, func(req *core.Request) {\n\t\tout <- req\n\t})\n\tdefer bus.Stop()\n\n\tsrv := NewThreatCrowd(config, bus)\n\tsrv.Start()\n\tdefer srv.Stop()\n\n\tcount := 0\n\texpected := 10\n\tdone := time.After(time.Second * 30)\n\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-out:\n\t\t\tcount++\n\t\t\tif count == expected {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-done:\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\tif count < expected {\n\t\tt.Errorf(\"Found %d names, expected at least %d instead\", count, expected)\n\t}\n}\n<commit_msg>fix threadcrowd_test name<commit_after>\/\/ +build datasources\n\npackage sources\n\nimport (\n\t\"log\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/OWASP\/Amass\/amass\/core\"\n)\n\nfunc TestThreatCrowd(t *testing.T) {\n\tconfig := &core.Config{}\n\tconfig.AddDomain(\"google.com\")\n\tbuf := new(strings.Builder)\n\tconfig.Log = log.New(buf, \"\", log.Lmicroseconds)\n\n\tout := make(chan *core.Request)\n\tbus := core.NewEventBus()\n\tbus.Subscribe(core.NewNameTopic, func(req *core.Request) {\n\t\tout <- req\n\t})\n\tdefer bus.Stop()\n\n\tsrv := NewThreatCrowd(config, bus)\n\tsrv.Start()\n\tdefer srv.Stop()\n\n\tcount := 0\n\texpected := 10\n\tdone := time.After(time.Second * 30)\n\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-out:\n\t\t\tcount++\n\t\t\tif count == expected {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-done:\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\tif count < expected {\n\t\tt.Errorf(\"Found %d names, expected at least %d instead\", count, expected)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar prefixes = \"0123456789abcdef\"\n\ntype CacheEntry struct {\n\tHTTPCode int\n\tExpires  time.Time\n}\n\ntype diskCacheEntry struct {\n\tData []byte\n\tCacheEntry\n}\n\ntype DiskCache struct {\n\tcacheRoot  string\n\tcacheFiles map[string]CacheEntry\n\tsync.RWMutex\n}\n\nfunc (d *DiskCache) init() {\n\td.Lock()\n\tdefer d.Unlock()\n\n\tif d.cacheFiles == nil {\n\t\tlog.Fatalf(\"Tried to load uninitialized cache.\")\n\t}\n\n\tos.Mkdir(d.cacheRoot, 0770)\n\n\tfor _, dir := range prefixes {\n\t\tdirName := d.cacheRoot + \"\/\" + string(dir)\n\t\terr := os.Mkdir(dirName, 0770)\n\t\tif err != nil {\n\t\t\t\/\/Either cannot create directory, or directory already exists, let's try opening it to find out.\n\t\t\tdirf, derr := os.Open(dirName)\n\t\t\tif derr != nil {\n\t\t\t\t\/\/ Couldn't open directory, panic.\n\t\t\t\tlog.Fatalf(\"Couldn't create or open %s: %s\/%s\", dirName, err, derr)\n\t\t\t}\n\n\t\t\tfiles, err := dirf.Readdirnames(0)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Couldn't read %s: %s\", dirName, err)\n\t\t\t}\n\n\t\t\tvar de diskCacheEntry\n\t\t\tfor _, filename := range files {\n\t\t\t\tfullname := dirName + \"\/\" + filename\n\n\t\t\t\tjsondata, err := ioutil.ReadFile(fullname)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"Failed to read %s: %s\", fullname, err)\n\t\t\t\t}\n\n\t\t\t\terr = json.Unmarshal(jsondata, &de)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Recovering from cache consistency error for %s: %s \", fullname, err)\n\t\t\t\t}\n\n\t\t\t\tif err != nil || time.Now().After(de.Expires) {\n\t\t\t\t\terr := os.Remove(fullname)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatalf(\"Failed to remove expired cache entry %s: %s\", fullname, err)\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\td.cacheFiles[filename] = de.CacheEntry\n\t\t\t}\n\t\t}\n\t}\n}\n\nvar cleanOnce = &sync.Once{}\n\nfunc (d *DiskCache) clean() {\n\tlog.Printf(\"Cleaning Up.\")\n\tnow := time.Now()\n\n\tcleancount := 0\n\tfor tag, ce := range d.cacheFiles {\n\t\tif now.After(ce.Expires) {\n\t\t\tos.Remove(d.filename(tag))\n\t\t\tdelete(d.cacheFiles, tag)\n\n\t\t\tcleancount++\n\t\t}\n\t}\n\tlog.Printf(\"Cleaned up %d entries.\", cleancount)\n\tcleanOnce = &sync.Once{}\n}\n\nvar storeCount int64\n\nfunc (d *DiskCache) filename(tag string) string {\n\treturn d.cacheRoot + \"\/\" + string(tag[0]) + \"\/\" + tag\n}\n\nfunc (d *DiskCache) Store(cacheTag string, HTTPCode int, data []byte, Expires time.Time) error {\n\td.Lock()\n\tdefer d.Unlock()\n\n\tif d.cacheFiles == nil {\n\t\tlog.Fatalf(\"Tried to store to uninitialized cache.\")\n\t}\n\n\tstoreCount++\n\tif storeCount%500 == 0 {\n\t\tgo cleanOnce.Do(func() { d.clean() })\n\t}\n\n\tce := CacheEntry{HTTPCode, Expires}\n\n\tde := diskCacheEntry{data, ce}\n\tjsondata, err := json.Marshal(&de)\n\tif err != nil {\n\t\tlog.Printf(\"Unknown JSON Marshal Error: %s\", err)\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(d.filename(cacheTag), jsondata, 0660)\n\tif err != nil {\n\t\tlog.Printf(\"Unknown File Error: %s\", err)\n\t\treturn err\n\t}\n\n\tlog.Printf(\"Stored Cache for %s Expires: %s\", cacheTag, ce.Expires)\n\td.cacheFiles[cacheTag] = ce\n\treturn nil\n}\n\nfunc (d *DiskCache) Get(cacheTag string) (int, []byte, time.Time, error) {\n\td.RLock()\n\tdefer d.RUnlock()\n\n\tif d.cacheFiles == nil {\n\t\tlog.Fatalf(\"Tried to get from uninitialized cache.\")\n\t}\n\n\tce, exists := d.cacheFiles[cacheTag]\n\tif !exists || time.Now().After(ce.Expires) {\n\t\treturn 0, nil, ce.Expires, fmt.Errorf(\"Not cached.\")\n\t}\n\n\tjsondata, err := ioutil.ReadFile(d.filename(cacheTag))\n\tif err != nil {\n\t\tdelete(d.cacheFiles, cacheTag)\n\t\treturn 0, nil, ce.Expires, fmt.Errorf(\"Cache error - File not found.\")\n\t}\n\n\tvar de diskCacheEntry\n\terr = json.Unmarshal(jsondata, &de)\n\tif err != nil || de.Expires != ce.Expires {\n\t\tlog.Printf(\"Cache consistency error: %s (Got: %s Expected: %s)\", err, de.Expires, ce.Expires)\n\n\t\tdelete(d.cacheFiles, cacheTag)\n\t\treturn 0, nil, ce.Expires, fmt.Errorf(\"Cache error - Cache invalid.\")\n\t}\n\n\treturn ce.HTTPCode, de.Data, ce.Expires, nil\n}\n\nfunc (d *DiskCache) LogStats() {\n\td.RLock()\n\tdefer d.RUnlock()\n\n\tentries := 0\n\texpired := 0\n\n\tnow := time.Now()\n\tfor _, ce := range d.cacheFiles {\n\t\tentries++\n\t\tif now.After(ce.Expires) {\n\t\t\texpired++\n\t\t}\n\t}\n\n\tlog.Printf(\"Cache Entries: %d  Expired Entries: %d\", entries, expired)\n}\n\nfunc NewDiskCache(rootDir string) *DiskCache {\n\tvar dc DiskCache\n\n\tdc.cacheRoot = rootDir\n\tdc.cacheFiles = make(map[string]CacheEntry)\n\n\tdc.init()\n\n\treturn &dc\n}\n<commit_msg>removed debug logging<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar prefixes = \"0123456789abcdef\"\n\ntype CacheEntry struct {\n\tHTTPCode int\n\tExpires  time.Time\n}\n\ntype diskCacheEntry struct {\n\tData []byte\n\tCacheEntry\n}\n\ntype DiskCache struct {\n\tcacheRoot  string\n\tcacheFiles map[string]CacheEntry\n\tsync.RWMutex\n}\n\nfunc (d *DiskCache) init() {\n\td.Lock()\n\tdefer d.Unlock()\n\n\tif d.cacheFiles == nil {\n\t\tlog.Fatalf(\"Tried to load uninitialized cache.\")\n\t}\n\n\tos.Mkdir(d.cacheRoot, 0770)\n\n\tfor _, dir := range prefixes {\n\t\tdirName := d.cacheRoot + \"\/\" + string(dir)\n\t\terr := os.Mkdir(dirName, 0770)\n\t\tif err != nil {\n\t\t\t\/\/Either cannot create directory, or directory already exists, let's try opening it to find out.\n\t\t\tdirf, derr := os.Open(dirName)\n\t\t\tif derr != nil {\n\t\t\t\t\/\/ Couldn't open directory, panic.\n\t\t\t\tlog.Fatalf(\"Couldn't create or open %s: %s\/%s\", dirName, err, derr)\n\t\t\t}\n\n\t\t\tfiles, err := dirf.Readdirnames(0)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Couldn't read %s: %s\", dirName, err)\n\t\t\t}\n\n\t\t\tvar de diskCacheEntry\n\t\t\tfor _, filename := range files {\n\t\t\t\tfullname := dirName + \"\/\" + filename\n\n\t\t\t\tjsondata, err := ioutil.ReadFile(fullname)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"Failed to read %s: %s\", fullname, err)\n\t\t\t\t}\n\n\t\t\t\terr = json.Unmarshal(jsondata, &de)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Recovering from cache consistency error for %s: %s \", fullname, err)\n\t\t\t\t}\n\n\t\t\t\tif err != nil || time.Now().After(de.Expires) {\n\t\t\t\t\terr := os.Remove(fullname)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatalf(\"Failed to remove expired cache entry %s: %s\", fullname, err)\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\td.cacheFiles[filename] = de.CacheEntry\n\t\t\t}\n\t\t}\n\t}\n}\n\nvar cleanOnce = &sync.Once{}\n\nfunc (d *DiskCache) clean() {\n\tlog.Printf(\"Cleaning Up.\")\n\tnow := time.Now()\n\n\tcleancount := 0\n\tfor tag, ce := range d.cacheFiles {\n\t\tif now.After(ce.Expires) {\n\t\t\tos.Remove(d.filename(tag))\n\t\t\tdelete(d.cacheFiles, tag)\n\n\t\t\tcleancount++\n\t\t}\n\t}\n\tlog.Printf(\"Cleaned up %d entries.\", cleancount)\n\tcleanOnce = &sync.Once{}\n}\n\nvar storeCount int64\n\nfunc (d *DiskCache) filename(tag string) string {\n\treturn d.cacheRoot + \"\/\" + string(tag[0]) + \"\/\" + tag\n}\n\nfunc (d *DiskCache) Store(cacheTag string, HTTPCode int, data []byte, Expires time.Time) error {\n\td.Lock()\n\tdefer d.Unlock()\n\n\tif d.cacheFiles == nil {\n\t\tlog.Fatalf(\"Tried to store to uninitialized cache.\")\n\t}\n\n\tstoreCount++\n\tif storeCount%500 == 0 {\n\t\tgo cleanOnce.Do(func() { d.clean() })\n\t}\n\n\tce := CacheEntry{HTTPCode, Expires}\n\n\tde := diskCacheEntry{data, ce}\n\tjsondata, err := json.Marshal(&de)\n\tif err != nil {\n\t\tlog.Printf(\"Unknown JSON Marshal Error: %s\", err)\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(d.filename(cacheTag), jsondata, 0660)\n\tif err != nil {\n\t\tlog.Printf(\"Unknown File Error: %s\", err)\n\t\treturn err\n\t}\n\n\td.cacheFiles[cacheTag] = ce\n\treturn nil\n}\n\nfunc (d *DiskCache) Get(cacheTag string) (int, []byte, time.Time, error) {\n\td.RLock()\n\tdefer d.RUnlock()\n\n\tif d.cacheFiles == nil {\n\t\tlog.Fatalf(\"Tried to get from uninitialized cache.\")\n\t}\n\n\tce, exists := d.cacheFiles[cacheTag]\n\tif !exists || time.Now().After(ce.Expires) {\n\t\treturn 0, nil, ce.Expires, fmt.Errorf(\"Not cached.\")\n\t}\n\n\tjsondata, err := ioutil.ReadFile(d.filename(cacheTag))\n\tif err != nil {\n\t\tdelete(d.cacheFiles, cacheTag)\n\t\treturn 0, nil, ce.Expires, fmt.Errorf(\"Cache error - File not found.\")\n\t}\n\n\tvar de diskCacheEntry\n\terr = json.Unmarshal(jsondata, &de)\n\tif err != nil || de.Expires != ce.Expires {\n\t\tlog.Printf(\"Cache consistency error: %s (Got: %s Expected: %s)\", err, de.Expires, ce.Expires)\n\n\t\tdelete(d.cacheFiles, cacheTag)\n\t\treturn 0, nil, ce.Expires, fmt.Errorf(\"Cache error - Cache invalid.\")\n\t}\n\n\treturn ce.HTTPCode, de.Data, ce.Expires, nil\n}\n\nfunc (d *DiskCache) LogStats() {\n\td.RLock()\n\tdefer d.RUnlock()\n\n\tentries := 0\n\texpired := 0\n\n\tnow := time.Now()\n\tfor _, ce := range d.cacheFiles {\n\t\tentries++\n\t\tif now.After(ce.Expires) {\n\t\t\texpired++\n\t\t}\n\t}\n\n\tlog.Printf(\"Cache Entries: %d  Expired Entries: %d\", entries, expired)\n}\n\nfunc NewDiskCache(rootDir string) *DiskCache {\n\tvar dc DiskCache\n\n\tdc.cacheRoot = rootDir\n\tdc.cacheFiles = make(map[string]CacheEntry)\n\n\tdc.init()\n\n\treturn &dc\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package graphite implements sending metrics to Graphite via the Carbon text API\n\/\/\n\/\/ This can be done by sending metrics one at a time or by buffering them through a channel.\npackage graphite\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n)\n\n\/\/ Graphite is the struct by which we interface with the library. At minimum you must set\n\/\/ Host and Port fields.\ntype Graphite struct {\n\tHost    string\n\tPort    uint16\n\tTimeout time.Duration\n\tconn    net.Conn\n}\n\n\/\/ Metric is contains fields used for sending metrics to Graphite. If Timestamp is not set,\n\/\/ one is generated when sent.\ntype Metric struct {\n\tName      string\n\tValue     string\n\tTimestamp int64\n}\n\n\/\/ defaultTimeout is the default connection timeout used by DialTimeout.\nconst (\n\tdefaultTimeout = 30\n)\n\nvar doneSending bool\n\n\/\/ connect is the unexported function used for connecting\nfunc connect(host string, port uint16, timeout time.Duration) (net.Conn, error) {\n\tconnectAddr := fmt.Sprintf(\"%s:%d\", host, port)\n\n\treturn net.DialTimeout(\"tcp\", connectAddr, timeout)\n}\n\n\/\/ sendMetric is the unexported function to send a single metric to Graphite.\nfunc sendMetric(conn net.Conn, metric Metric) {\n\tlog.Printf(\"sending %s\", metric.Name)\n\tfmt.Fprintf(conn, \"%s %s %s\", metric.Name, metric.Value, metric.Timestamp)\n}\n\n\/\/ chanSendMetrics sends a Metric slice to the given channel\nfunc chanSendMetrics(ch chan Metric, buffer []Metric) {\n\tfor _, item := range buffer {\n\t\tif len(item.Name) > 0 {\n\t\t\tlog.Printf(\"buffering %s\", item.Name)\n\t\t\tch <- item\n\t\t}\n\t}\n}\n\n\/\/ chanRecvMetrics reads `bufsz` numbered metrics off of the given channel and\n\/\/ sends them to Graphite.\nfunc chanRecvMetrics(ch chan Metric, conn net.Conn, bufsz int) {\n\tfor i := 0; i < bufsz; i++ {\n\t\titem := <-ch\n\t\tsendMetric(conn, item)\n\t}\n\n\tdoneSending = true\n}\n\n\/\/ Connect wraps the unexported connect function.\nfunc (g *Graphite) Connect() {\n\tvar (\n\t\terr     error\n\t\ttimeout time.Duration\n\t)\n\n\tif g.Timeout == 0 {\n\t\tg.Timeout = defaultTimeout\n\t}\n\n\ttimeout = g.Timeout * time.Second\n\n\tg.conn, err = connect(g.Host, g.Port, timeout)\n\tfor err != nil {\n\t\tlog.Printf(err.Error())\n\t\tlog.Printf(fmt.Sprintf(\"error connecting, retrying in %d seconds\", int(timeout.Seconds())))\n\t\ttime.Sleep(timeout)\n\n\t\ttimeout = (g.Timeout + 5) * time.Second\n\t\tg.conn, err = connect(g.Host, g.Port, timeout)\n\t}\n}\n\n\/\/ SendMetric is used to send a single metric to Graphite.\n\/\/ Sets metric.Timestamp to current Unix time if necessary.\nfunc (g *Graphite) SendMetric(metric Metric) {\n\tif metric.Timestamp == 0 {\n\t\tmetric.Timestamp = time.Now().Unix()\n\t}\n\n\tsendMetric(g.conn, metric)\n}\n\n\/\/ Sendall is used to buffered metrics to Graphite via a channel and go routines.\nfunc (g *Graphite) Sendall(buf []Metric) {\n\tdoneSending = false\n\n\tch := make(chan Metric, len(buf))\n\tgo chanSendMetrics(ch, buf)\n\tgo chanRecvMetrics(ch, g.conn, len(buf))\n\n\tfor doneSending == false {\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}\n<commit_msg>create an explicit graphite interface<commit_after>\/\/ Package graphite implements sending metrics to Graphite via the Carbon text API\n\/\/\n\/\/ This can be done by sending metrics one at a time or by buffering them through a channel.\npackage graphite\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n)\n\n\/\/ Interface type for Graphite.\ntype Graphite interface {\n\tConnect()\n\tSendMetric()\n\tSendall()\n\tchanRecv()\n\tchanSend()\n\tsendMetric()\n}\n\n\/\/ Graphite is how we interface with the library. At minimum you must set\n\/\/ Host and Port fields.\ntype GraphiteServer struct {\n\tHost    string\n\tPort    uint16\n\tTimeout time.Duration\n\tconn    net.Conn\n}\n\n\/\/ Metric is contains fields used for sending metrics to Graphite. If Timestamp is not set,\n\/\/ one is generated when sent.\ntype Metric struct {\n\tName      string\n\tValue     string\n\tTimestamp int64\n}\n\n\/\/ defaultTimeout is the default connection timeout used by DialTimeout.\nconst (\n\tdefaultTimeout = 30\n)\n\nvar doneSending = false\n\n\/\/ connect is the unexported function used for connecting\nfunc connect(host string, port uint16, timeout time.Duration) (net.Conn, error) {\n\tconnectAddr := fmt.Sprintf(\"%s:%d\", host, port)\n\n\treturn net.DialTimeout(\"tcp\", connectAddr, timeout)\n}\n\n\/\/ Connect wraps the unexported connect function.\n\/\/ Sets a connection timeout if unset.\nfunc (g *GraphiteServer) Connect() {\n\tvar (\n\t\terr     error\n\t\ttimeout time.Duration\n\t)\n\n\tif g.Timeout == 0 {\n\t\tg.Timeout = defaultTimeout\n\t}\n\n\ttimeout = g.Timeout * time.Second\n\n\tg.conn, err = connect(g.Host, g.Port, timeout)\n\tfor err != nil {\n\t\tlog.Printf(err.Error())\n\t\tlog.Printf(fmt.Sprintf(\"error connecting, retrying in %d seconds\", int(timeout.Seconds())))\n\t\ttime.Sleep(timeout)\n\n\t\ttimeout = (g.Timeout + 5) * time.Second\n\t\tg.conn, err = connect(g.Host, g.Port, timeout)\n\t}\n}\n\n\/\/ SendMetric is used to send a single metric to Graphite.\n\/\/ Sets metric.Timestamp to current Unix time if necessary.\nfunc (g *GraphiteServer) SendMetric(metric Metric) {\n\tif metric.Timestamp == 0 {\n\t\tmetric.Timestamp = time.Now().Unix()\n\t}\n\n\tg.sendMetric(metric)\n}\n\n\/\/ Sendall is used to buffered metrics to Graphite via a channel and go routines.\nfunc (g *GraphiteServer) Sendall(buf []Metric) {\n\tdoneSending = false\n\n\tch := make(chan Metric, len(buf))\n\tgo g.chanSend(ch, buf)\n\tgo g.chanRecv(ch, len(buf))\n\n\tfor doneSending == false {\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}\n\n\/\/ chanRecvMetrics reads `bufsz` numbered metrics off of the given channel and\n\/\/ sends them to Graphite.\nfunc (g *GraphiteServer) chanRecv(ch chan Metric, bufsz int) {\n\tfor i := 0; i < bufsz; i++ {\n\t\titem := <-ch\n\t\tg.sendMetric(item)\n\t}\n\n\tdoneSending = true\n}\n\n\/\/ chanSendMetrics sends a Metric slice to the given channel\nfunc (g *GraphiteServer) chanSend(ch chan Metric, buffer []Metric) {\n\tfor _, item := range buffer {\n\t\tif len(item.Name) > 0 {\n\t\t\tlog.Printf(\"buffering %s\", item.Name)\n\t\t\tch <- item\n\t\t}\n\t}\n}\n\n\/\/ sendMetric is the unexported function to send a single metric to Graphite.\nfunc (g *GraphiteServer) sendMetric(metric Metric) {\n\tlog.Printf(\"sending %s\", metric.Name)\n\tfmt.Fprintf(g.conn, \"%s %s %d\\n\", metric.Name, metric.Value, metric.Timestamp)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nMEL app backend.\n\n\n\nAuthor:\t\tAlastair Hughes\nContact:\t<hobbitalastair at yandex dot com>\n*\/\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"database\/sql\"\n\t_ \"github.com\/mattn\/go-sqlite3\"\n)\n\n\/\/ internalError ends the request and logs an internal error.\nfunc internalError(fail func(int), err error) {\n\tfail(http.StatusInternalServerError)\n\tlog.Printf(\"%q\\n\", err)\n}\n\n\/\/ Authenticate the given HTTP request.\nfunc authenticate(fail func(int), request *http.Request, db *sql.DB) (string, bool) {\n\tuser, password, ok := request.BasicAuth()\n\tif !ok {\n\t\tfail(http.StatusUnauthorized)\n\t\treturn user, ok\n\t}\n\n\t\/\/ dbname and dbpassword are empty values to pass to Scan; we never use them\n\t\/\/ elsewhere.\n\tdbname := \"\"\n\t\/\/ FIXME: This is not \"best-practice\".\n\t\/\/\tWe should salt the password (using a locally stored value), and maybe\n\t\/\/\tuse encrypt(name+password) to avoid duplicated passwords being obvious?\n\terr := db.QueryRow(\"SELECT name FROM users WHERE name=? and password=?\", user, password).Scan(&dbname)\n\tif err == sql.ErrNoRows {\n\t\tfail(http.StatusForbidden)\n\t} else if err != nil {\n\t\tinternalError(fail, err)\n\t}\n\n\treturn user, err == nil\n}\n\n\/\/ ListProjects responds with the list of projects for the given user.\nfunc ListProjects(fail func(int), encoder *json.Encoder, user string, db *sql.DB) {\n\t\/\/ TODO: This should also return projects which this user owns.\n\t\/\/\tImplement that as a view in the database?\n\trows, err := db.Query(\"SELECT id FROM views WHERE name=?\", user)\n\tif err != nil {\n\t\tinternalError(fail, err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tid := -1\n\t\terr = rows.Scan(&id)\n\t\tif err != nil {\n\t\t\tinternalError(fail, err)\n\t\t\treturn\n\t\t}\n\t\terr = encoder.Encode(id)\n\t\tif err != nil {\n\t\t\tinternalError(fail, err)\n\t\t\treturn\n\t\t}\n\t}\n\tif err != nil {\n\t\tinternalError(fail, err)\n\t\treturn\n\t}\n}\n\n\/\/ Flag responds with the current state of the flag.\nfunc Flag(fail func(int), encoder *json.Encoder, pid int, user string, db *sql.DB) {\n\t\/\/ TODO: We need to authenticate the user here.\n\tflag := false\n\terr := db.QueryRow(\"SELECT flag FROM project WHERE id=?\", pid).Scan(&flag)\n\tif err != nil {\n\t\tinternalError(fail, err)\n\t\treturn\n\t}\n\tencoder.Encode(flag)\n}\n\n\/\/ Project responds with the details of the given project.\nfunc Project(fail func(int), encoder *json.Encoder, pid int, user string, db *sql.DB) {\n\t\/\/ TODO: We need to authenticate the user here.\n\tname, percentage, description := \"\", \"\", \"\"\n\terr := db.QueryRow(\"SELECT name, percentage, description FROM project WHERE id=?\", pid).Scan(&name, &percentage, &description)\n\tif err != nil {\n\t\tinternalError(fail, err)\n\t\treturn\n\t}\n\tencoder.Encode(name)\n\tencoder.Encode(percentage)\n\tencoder.Encode(description)\n}\n\n\/\/ Handle a single HTTP request.\nfunc handle(writer http.ResponseWriter, request *http.Request) {\n\t\/\/ Wrapper for failing functions.\n\tfail := func(status int) { http.Error(writer, http.StatusText(status), status) }\n\n\t\/\/ Open the database.\n\t\/\/ FIXME: I'm using sqlite3 here which only seems to report errors when\n\t\/\/\tactually executing a query; I'll need to test this on other systems as well.\n\tdb, err := sql.Open(\"sqlite3\", \"test.db\") \/\/ TODO: Should be the actual db, ...\n\tif err != nil {\n\t\tlog.Printf(\"Error opening DB: %q\\n\", err)\n\t\tfail(http.StatusInternalServerError)\n\t}\n\n\t\/\/ Authenticate.\n\tuser, ok := authenticate(fail, request, db)\n\tif !ok {\n\t\treturn\n\t}\n\n\t\/\/ Parse the URL and return the corresponding value.\n\t\/\/ TODO: This assumes GET requests...\n\tenc := json.NewEncoder(writer)\n\tenc.SetEscapeHTML(true)\n\tpaths := strings.Split(strings.TrimPrefix(request.URL.Path, \"\/\"), \"\/\")\n\n\t\/\/ FIXME: Match using regular expressions instead?\n\tif len(paths) < 1 || paths[0] != \"projects\" {\n\t\thttp.NotFound(writer, request)\n\t} else if len(paths) == 1 {\n\t\tListProjects(fail, enc, user, db)\n\t} else {\n\t\t\/\/ Grab the project ID from the URL.\n\t\tpid, err := strconv.Atoi(paths[1])\n\t\tif err != nil {\n\t\t\thttp.NotFound(writer, request)\n\t\t\treturn\n\t\t}\n\n\t\tif len(paths) == 2 {\n\t\t\tProject(fail, enc, pid, user, db)\n\t\t} else if len(paths) == 3 && paths[2] == \"flag\" {\n\t\t\tFlag(fail, enc, pid, user, db)\n\t\t} else {\n\t\t\thttp.NotFound(writer, request)\n\t\t}\n\t}\n}\n\nfunc main() {\n\tfmt.Printf(\"Starting server on :8080...\\n\")\n\thttp.ListenAndServe(\":8080\", http.HandlerFunc(handle))\n}\n\n\/\/ vim: sw=4 ts=4 noexpandtab\n<commit_msg>Initial implementation with salted passwords<commit_after>\/*\nMEL app backend.\n\n\n\nAuthor:\t\tAlastair Hughes\nContact:\t<hobbitalastair at yandex dot com>\n*\/\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"database\/sql\"\n\t_ \"github.com\/mattn\/go-sqlite3\"\n\t\"golang.org\/x\/crypto\/scrypt\"\n)\n\n\/\/ internalError ends the request and logs an internal error.\nfunc internalError(fail func(int), err error) {\n\tfail(http.StatusInternalServerError)\n\tlog.Printf(\"%q\\n\", err)\n}\n\n\/\/ Authenticate the given HTTP request.\nfunc authenticate(fail func(int), request *http.Request, db *sql.DB) (string, bool) {\n\tuser, password, ok := request.BasicAuth()\n\tif !ok {\n\t\tfail(http.StatusUnauthorized)\n\t\treturn user, false\n\t}\n\n\t\/\/ Retrieve the salt and database password.\n\tsalt := []byte(\"\")\n\tdbpassword := []byte(\"\")\n\terr := db.QueryRow(\"SELECT salt, password FROM users WHERE name=?\", user).Scan(&salt, &dbpassword)\n\tif err == sql.ErrNoRows {\n\t\tfail(http.StatusForbidden)\n\t\treturn user, false\n\t} else if err != nil {\n\t\tinternalError(fail, err)\n\t\treturn user, false\n\t}\n\n\t\/\/ Check the password. We salt and encrypt it to avoid potential security\n\t\/\/ issues if the db is stolen.\n\t\/\/ This appears to be reasonably close to \"best practice\", but the 1<<20\n\t\/\/ value probably should be checked for sanity.\n\t\/\/ FIXME: We don't store the 1<<20 value in the db, but it should be\n\t\/\/ increased as compute power grows. Doing so is complicated since some way\n\t\/\/ of migrating users from the old value would also need to be implemented.\n\tkey, err := scrypt.Key([]byte(password), salt, 1<<20, 8, 1, 256)\n\tif err != nil {\n\t\tinternalError(fail, err)\n\t\treturn user, false\n\t}\n\treturn user, string(key) == string(dbpassword)\n}\n\n\/\/ ListProjects responds with the list of projects for the given user.\nfunc ListProjects(fail func(int), encoder *json.Encoder, user string, db *sql.DB) {\n\t\/\/ TODO: This should also return projects which this user owns.\n\t\/\/\tImplement that as a view in the database?\n\trows, err := db.Query(\"SELECT id FROM views WHERE name=?\", user)\n\tif err != nil {\n\t\tinternalError(fail, err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tid := -1\n\t\terr = rows.Scan(&id)\n\t\tif err != nil {\n\t\t\tinternalError(fail, err)\n\t\t\treturn\n\t\t}\n\t\terr = encoder.Encode(id)\n\t\tif err != nil {\n\t\t\tinternalError(fail, err)\n\t\t\treturn\n\t\t}\n\t}\n\tif err != nil {\n\t\tinternalError(fail, err)\n\t\treturn\n\t}\n}\n\n\/\/ Flag responds with the current state of the flag.\nfunc Flag(fail func(int), encoder *json.Encoder, pid int, user string, db *sql.DB) {\n\t\/\/ TODO: We need to authenticate the user here.\n\tflag := false\n\terr := db.QueryRow(\"SELECT flag FROM project WHERE id=?\", pid).Scan(&flag)\n\tif err != nil {\n\t\tinternalError(fail, err)\n\t\treturn\n\t}\n\tencoder.Encode(flag)\n}\n\n\/\/ Project responds with the details of the given project.\nfunc Project(fail func(int), encoder *json.Encoder, pid int, user string, db *sql.DB) {\n\t\/\/ TODO: We need to authenticate the user here.\n\tname, percentage, description := \"\", \"\", \"\"\n\terr := db.QueryRow(\"SELECT name, percentage, description FROM project WHERE id=?\", pid).Scan(&name, &percentage, &description)\n\tif err != nil {\n\t\tinternalError(fail, err)\n\t\treturn\n\t}\n\tencoder.Encode(name)\n\tencoder.Encode(percentage)\n\tencoder.Encode(description)\n}\n\n\/\/ Handle a single HTTP request.\nfunc handle(writer http.ResponseWriter, request *http.Request) {\n\t\/\/ Wrapper for failing functions.\n\tfail := func(status int) { http.Error(writer, http.StatusText(status), status) }\n\n\t\/\/ Open the database.\n\t\/\/ FIXME: I'm using sqlite3 here which only seems to report errors when\n\t\/\/\tactually executing a query; I'll need to test this on other systems as well.\n\tdb, err := sql.Open(\"sqlite3\", \"test.db\") \/\/ TODO: Should be the actual db, ...\n\tif err != nil {\n\t\tlog.Printf(\"Error opening DB: %q\\n\", err)\n\t\tfail(http.StatusInternalServerError)\n\t}\n\n\t\/\/ Authenticate.\n\tuser, ok := authenticate(fail, request, db)\n\tif !ok {\n\t\treturn\n\t}\n\n\t\/\/ Parse the URL and return the corresponding value.\n\t\/\/ TODO: This assumes GET requests...\n\tenc := json.NewEncoder(writer)\n\tenc.SetEscapeHTML(true)\n\tpaths := strings.Split(strings.TrimPrefix(request.URL.Path, \"\/\"), \"\/\")\n\n\t\/\/ FIXME: Match using regular expressions instead?\n\tif len(paths) < 1 || paths[0] != \"projects\" {\n\t\thttp.NotFound(writer, request)\n\t} else if len(paths) == 1 {\n\t\tListProjects(fail, enc, user, db)\n\t} else {\n\t\t\/\/ Grab the project ID from the URL.\n\t\tpid, err := strconv.Atoi(paths[1])\n\t\tif err != nil {\n\t\t\thttp.NotFound(writer, request)\n\t\t\treturn\n\t\t}\n\n\t\tif len(paths) == 2 {\n\t\t\tProject(fail, enc, pid, user, db)\n\t\t} else if len(paths) == 3 && paths[2] == \"flag\" {\n\t\t\tFlag(fail, enc, pid, user, db)\n\t\t} else {\n\t\t\thttp.NotFound(writer, request)\n\t\t}\n\t}\n}\n\nfunc main() {\n\tfmt.Printf(\"Starting server on :8080...\\n\")\n\thttp.ListenAndServe(\":8080\", http.HandlerFunc(handle))\n}\n\n\/\/ vim: sw=4 ts=4 noexpandtab\n<|endoftext|>"}
{"text":"<commit_before>\/\/\r\n\/\/\r\n\/\/\r\npackage main\r\n\r\nimport (\r\n    \"fmt\"\r\n    \"flag\"\r\n    \"gopkg.in\/yaml.v2\"\r\n    \"io\/ioutil\"\r\n    \"path\/filepath\"\r\n    \"os\/exec\"\r\n    \"os\"\r\n    \"strings\"\r\n    \"unsafe\"\r\n)\r\n\r\n\/\/\r\n\/\/ data structures\r\n\/\/\r\ntype Target struct {\r\n    Name string\r\n    Type string\r\n}\r\ntype StringList struct {\r\n    Type string\r\n    Target string\r\n    Debug []string `yaml:\",flow\"`\r\n    Release []string `yaml:\",flow\"`\r\n    List []string `yaml:\",flow\"`\r\n}\r\ntype Variable struct {\r\n    Name string\r\n    Value string\r\n    Type string\r\n    Build string\r\n}\r\ntype Build struct {\r\n    Name string\r\n    Command string\r\n    Files []string `yaml:\",flow\"`\r\n}\r\n\r\ntype Data struct {\r\n    Target []Target `yaml:\",flow\"`\r\n    Include []StringList `yaml:\",flow\"`\r\n    Variable []Variable `yaml:\",flow\"`\r\n    Define []StringList `yaml:\",flow\"`\r\n    Option []StringList `yaml:\",flow\"`\r\n    Archive_Option []StringList `yaml:\",flow\"`\r\n    Convert_Option []StringList `yaml:\",flow\"`\r\n    Prebuild []Build `yaml:\",flow\"`\r\n    Postbuild []Build `yaml:\",flow\"`\r\n    Source []StringList `yaml:\",flow\"`\r\n    Convert_List []StringList `yaml:\",flow\"`\r\n    Subdir []StringList `yaml:\",flow\"`\r\n}\r\n\r\n\/\/\r\n\/\/ error\r\n\/\/\r\n\r\ntype MyError struct {\r\n    str string\r\n}\r\nfunc (m MyError) Error() string {\r\n    return m.str\r\n}\r\n\r\n\/\/\r\n\/\/ build information\r\n\/\/\r\n\r\n\/\/\r\ntype BuildCommand struct {\r\n    cmd string\r\n    args string\r\n    title string\r\n}\r\n\r\n\/\/\r\ntype BuildResult struct {\r\n    success bool\r\n    create_list []string\r\n}\r\n\r\n\/\/\r\ntype BuildInfo struct {\r\n    variables map[string] string\r\n    includes string\r\n    defines string\r\n    options string\r\n    archive_options string\r\n    convert_options string\r\n    select_target string\r\n    target string\r\n    subdir []string\r\n    create_list []string\r\n}\r\n\r\n\/\/\r\n\/\/ global variables\r\n\/\/\r\nvar (\r\n    isDebug bool\r\n    isRelease bool\r\n    target_type string\r\n    target_name string\r\n    outputdir string\r\n\r\n    need_dir_list []string\r\n    command_list []BuildCommand\r\n)\r\n\r\n\/\/\r\n\/\/\r\n\/\/ build functions\r\n\/\/\r\n\/\/\r\n\r\n\/\/\r\n\/\/\r\n\/\/\r\nfunc getList(block []StringList,target_name string) []string {\r\n    lists := [] string{}\r\n    for _,i := range block {\r\n        if (i.Type == \"\" || i.Type == target_type) && (i.Target == \"\" || i.Target == target_name) {\r\n            for _,l := range i.List {\r\n                lists = append(lists,l)\r\n            }\r\n            if isDebug == true {\r\n                for _,d := range i.Debug {\r\n                    lists = append(lists,d)\r\n                }\r\n            } else {\r\n                for _,r := range i.Release {\r\n                    lists = append(lists,r)\r\n                }\r\n            }\r\n        }\r\n    }\r\n    return lists\r\n}\r\n\r\n\/\/\r\n\/\/ archive objects\r\n\/\/\r\nfunc create_archive(info BuildInfo,odir string,create_list []string,target_name string) string {\r\n    arname := odir\r\n    if target_type == \"WIN32\" {\r\n        arname += target_name + \".lib\"\r\n    } else {\r\n        arname += \"lib\" + target_name + \".a\"\r\n    }\r\n    arname = filepath.ToSlash(filepath.Clean(arname))\r\n\r\n    archiver := info.variables[\"archiver\"]\r\n    alist := \"\"\r\n    for _,l := range create_list {\r\n        alist += \" \" + l\r\n    }\r\n\r\n    t := fmt.Sprintf(\"Library: %s\",arname)\r\n    cmd := BuildCommand{\r\n        cmd : archiver,\r\n        args : info.archive_options+arname+alist,\r\n        title : t }\r\n    command_list = append(command_list,cmd)\r\n\r\n    return arname\r\n}\r\n\r\n\/\/\r\n\/\/ link objects\r\n\/\/\r\nfunc create_link(info BuildInfo,odir string,create_list []string,target_name string) {\r\n    trname := odir\r\n    if target_type == \"WIN32\" {\r\n        trname += target_name + \".exe\"\r\n    } else {\r\n        trname += target_name\r\n    }\r\n    trname = filepath.ToSlash(filepath.Clean(trname))\r\n\r\n    linker := info.variables[\"linker\"]\r\n\r\n    create_list = append(info.create_list,create_list...)\r\n\r\n    flist := \"\"\r\n    for _,l := range create_list {\r\n        flist += \" \" + l\r\n    }\r\n\r\n    t := fmt.Sprintf(\"Linking: %s\",trname)\r\n    cmd := BuildCommand{\r\n        cmd : linker,\r\n        args : \"-o \" + trname + flist,\r\n        title : t }\r\n    command_list = append(command_list,cmd)\r\n    \/\/fmt.Println(\"-o \" + NowTarget.Name + flist)\r\n}\r\n\r\n\/\/\r\n\/\/ convert objects\r\n\/\/\r\nfunc create_convert(info BuildInfo,loaddir string,odir string,create_list []string,target_name string) {\r\n    cvname := odir + target_name\r\n    cvname = filepath.ToSlash(filepath.Clean(cvname))\r\n    clist := \"\"\r\n    converter := info.variables[\"converter\"]\r\n\r\n    for _,f := range create_list {\r\n        clist += \" \" + filepath.ToSlash(filepath.Clean(loaddir+f))\r\n    }\r\n\r\n    t := fmt.Sprintf(\"Convert: %s\",cvname)\r\n    cmd := BuildCommand{\r\n        cmd : converter,\r\n        args : info.convert_options+\"-o \"+cvname+clist,\r\n        title : t }\r\n    command_list = append(command_list,cmd)\r\n}\r\n\r\n\r\n\/\/\r\n\/\/ build main\r\n\/\/\r\nfunc build(info BuildInfo,pathname string) (result BuildResult,err error) {\r\n    loaddir := pathname\r\n    if loaddir == \"\" {\r\n        loaddir = \".\/\"\r\n    } else {\r\n        loaddir += \"\/\"\r\n    }\r\n    my_yaml := loaddir+\"make.yml\"\r\n    buf, err := ioutil.ReadFile(my_yaml)\r\n    if err != nil {\r\n        e := MyError{ str : my_yaml + \": \" + err.Error() }\r\n        result.success = false\r\n        return result,e\r\n    }\r\n\r\n    var d Data\r\n    err = yaml.Unmarshal(buf, &d)\r\n    if err != nil {\r\n        e := MyError { str : my_yaml + \": \" + err.Error() }\r\n        result.success = false\r\n        return result,e\r\n    }\r\n\r\n    \/\/\r\n    \/\/ select target\r\n    \/\/\r\n    var NowTarget Target\r\n    for _,t := range d.Target {\r\n        if info.select_target == \"\" || t.Name == info.select_target {\r\n            NowTarget = t\r\n            if info.target == \"\" {\r\n                info.target = t.Name\r\n            }\r\n            break\r\n        }\r\n    }\r\n    if NowTarget.Name == \"\" {\r\n        e := MyError{ str : \"No Target\" }\r\n        result.success = false\r\n        return result,e\r\n    }\r\n    info.select_target = \"\"\r\n\r\n    opt_pre := info.variables[\"option_prefix\"]\r\n    \/\/\r\n    \/\/ get rules\r\n    \/\/\r\n    for _,v := range d.Variable {\r\n        if v.Type == \"\" || v.Type == target_type {\r\n            info.variables[v.Name] = v.Value\r\n        }\r\n    }\r\n    for _,i := range getList(d.Include,info.target) {\r\n        abs, err := filepath.Abs(i)\r\n        if err != nil {\r\n            result.success = false\r\n            return result,err\r\n        }\r\n        info.includes += \" \" + opt_pre + \"I\" + abs\r\n    }\r\n    for _,d := range getList(d.Define,info.target) {\r\n        info.defines += \" \" + opt_pre + \"D\" + d\r\n    }\r\n    for _,o := range getList(d.Option,info.target) {\r\n        info.options += \" \" + opt_pre + o\r\n    }\r\n    for _,a := range getList(d.Archive_Option,info.target) {\r\n        info.archive_options += \" \" + opt_pre + a + \" \"\r\n    }\r\n    for _,c := range getList(d.Convert_Option,info.target) {\r\n        info.convert_options +=  c + \" \"\r\n    }\r\n\r\n    files := getList(d.Source,info.target)\r\n    cvfiles := getList(d.Convert_List,info.target)\r\n\r\n    subdirs := getList(d.Subdir,info.target)\r\n    for _,s := range subdirs {\r\n        sd := loaddir+s\r\n        var r,e = build(info,sd)\r\n        if r.success == false {\r\n            return r,e\r\n        }\r\n        info.create_list = append(info.create_list,r.create_list...)\r\n    }\r\n\r\n    compiler := info.variables[\"compiler\"]\r\n\r\n    arg1 := info.includes + info.defines + info.options\r\n    odir := outputdir + \"\/\" + loaddir\r\n    need_dir_list = append(need_dir_list,filepath.Clean(odir))\r\n\r\n    create_list := []string{}\r\n    for _,f := range files {\r\n        sname := filepath.ToSlash(filepath.Clean(loaddir+f))\r\n        oname := filepath.ToSlash(filepath.Clean(odir+f+\".o\"))\r\n        create_list = append(create_list,oname)\r\n\r\n        t := fmt.Sprintf(\"Compile: %s\",sname)\r\n        cmd := BuildCommand{\r\n            cmd : compiler,\r\n            args : arg1+\" -o \"+oname+\" \"+sname,\r\n            title : t }\r\n        command_list = append(command_list,cmd)\r\n    }\r\n\r\n    if NowTarget.Type == \"library\" {\r\n        \/\/ archive\r\n        if len(create_list) > 0 {\r\n            arname := create_archive(info,odir,create_list,NowTarget.Name)\r\n            result.create_list = append(info.create_list,arname)\r\n            \/\/fmt.Println(info.archive_options+arname+alist)\r\n        } else {\r\n            fmt.Println(\"There are no files to build.\")\r\n        }\r\n    } else if NowTarget.Type == \"execute\" {\r\n        \/\/ link program\r\n        if len(create_list) > 0 && len(info.create_list) > 0 {\r\n            create_link(info,odir,create_list,NowTarget.Name)\r\n        } else {\r\n            fmt.Println(\"There are no files to build.\")\r\n        }\r\n    } else if NowTarget.Type == \"convert\" {\r\n        if len(cvfiles) > 0 {\r\n            create_convert(info,loaddir,odir,cvfiles,NowTarget.Name)\r\n        } else {\r\n            fmt.Println(\"There are no files to convert.\")\r\n        }\r\n    } else {\r\n        \/\/\r\n        \/\/ othre...\r\n        \/\/\r\n        result.create_list = append(info.create_list,create_list...)\r\n    }\r\n    result.success = true\r\n    return result,nil\r\n}\r\n\r\nfunc main() {\r\n\r\n    flag.BoolVar(&isRelease,\"release\",false,\"release build\")\r\n    flag.BoolVar(&isDebug,\"debug\",true,\"debug build\")\r\n    flag.StringVar(&target_type,\"type\",\"default\",\"build target type\")\r\n    flag.StringVar(&target_name,\"t\",\"\",\"build target name\")\r\n    flag.StringVar(&outputdir,\"o\",\"build\",\"build directory\")\r\n    flag.Parse()\r\n\r\n    outputdir += \"\/\" + target_type + \"\/\"\r\n    if isRelease {\r\n        isDebug = false\r\n        outputdir += \"Release\"\r\n    } else {\r\n        outputdir += \"Debug\"\r\n    }\r\n\r\n    build_info := BuildInfo{\r\n        variables : map[string] string{\"option_prefix\":\"-\"},\r\n        includes : \"\",\r\n        defines : \"\",\r\n        select_target : target_name,\r\n        target: target_name }\r\n    var r,err = build(build_info,\"\")\r\n    if r.success == false {\r\n        fmt.Println(\"Error:\",err.Error())\r\n        os.Exit(1)\r\n    }\r\n\r\n    \/\/ setup directories\r\n    for _,nd := range need_dir_list {\r\n        os.MkdirAll(nd,os.ModePerm)\r\n    }\r\n\r\n    \/\/ execute build\r\n    nlen := len(command_list)\r\n    if nlen > 0 {\r\n        for i,bs := range command_list {\r\n            t := fmt.Sprintf(\"[%d\/%d] %s\",i+1,nlen,bs.title)\r\n            fmt.Println(t)\r\n            fmt.Println(bs.cmd + \":\"+ bs.args)\r\n            arg_list := strings.Split(bs.args,\" \")\r\n            c,_ := exec.Command(bs.cmd,arg_list[0:]...).CombinedOutput()\r\n            msg := *(*string)(unsafe.Pointer(&c))\r\n            if msg != \"\" {\r\n                fmt.Println(msg)\r\n            }\r\n        }\r\n    }\r\n}\r\n\/\/\r\n\/\/\r\n<commit_msg>minimal update.<commit_after>\/\/\r\n\/\/\r\n\/\/\r\npackage main\r\n\r\nimport (\r\n    \"fmt\"\r\n    \"flag\"\r\n    \"gopkg.in\/yaml.v2\"\r\n    \"io\/ioutil\"\r\n    \"path\/filepath\"\r\n    \"os\/exec\"\r\n    \"os\"\r\n    \"strings\"\r\n    \"unsafe\"\r\n)\r\n\r\n\/\/\r\n\/\/ data structures\r\n\/\/\r\ntype Target struct {\r\n    Name string\r\n    Type string\r\n}\r\ntype StringList struct {\r\n    Type string\r\n    Target string\r\n    Debug []string `yaml:\",flow\"`\r\n    Release []string `yaml:\",flow\"`\r\n    List []string `yaml:\",flow\"`\r\n}\r\ntype Variable struct {\r\n    Name string\r\n    Value string\r\n    Type string\r\n    Build string\r\n}\r\ntype Build struct {\r\n    Name string\r\n    Command string\r\n    Files []string `yaml:\",flow\"`\r\n}\r\n\r\ntype Data struct {\r\n    Target []Target `yaml:\",flow\"`\r\n    Include []StringList `yaml:\",flow\"`\r\n    Variable []Variable `yaml:\",flow\"`\r\n    Define []StringList `yaml:\",flow\"`\r\n    Option []StringList `yaml:\",flow\"`\r\n    Archive_Option []StringList `yaml:\",flow\"`\r\n    Convert_Option []StringList `yaml:\",flow\"`\r\n    Prebuild []Build `yaml:\",flow\"`\r\n    Postbuild []Build `yaml:\",flow\"`\r\n    Source []StringList `yaml:\",flow\"`\r\n    Convert_List []StringList `yaml:\",flow\"`\r\n    Subdir []StringList `yaml:\",flow\"`\r\n}\r\n\r\n\/\/\r\n\/\/ error\r\n\/\/\r\n\r\ntype MyError struct {\r\n    str string\r\n}\r\nfunc (m MyError) Error() string {\r\n    return m.str\r\n}\r\n\r\n\/\/\r\n\/\/ build information\r\n\/\/\r\n\r\n\/\/\r\ntype BuildCommand struct {\r\n    cmd string\r\n    args string\r\n    title string\r\n}\r\n\r\n\/\/\r\ntype BuildResult struct {\r\n    success bool\r\n    create_list []string\r\n}\r\n\r\n\/\/\r\ntype BuildInfo struct {\r\n    variables map[string] string\r\n    includes string\r\n    defines string\r\n    options string\r\n    archive_options string\r\n    convert_options string\r\n    select_target string\r\n    target string\r\n    subdir []string\r\n    create_list []string\r\n}\r\n\r\n\/\/\r\n\/\/ global variables\r\n\/\/\r\nvar (\r\n    isDebug bool\r\n    isRelease bool\r\n    target_type string\r\n    target_name string\r\n    outputdir string\r\n\r\n    need_dir_list []string\r\n    command_list []BuildCommand\r\n)\r\n\r\n\/\/\r\n\/\/\r\n\/\/ build functions\r\n\/\/\r\n\/\/\r\n\r\n\/\/\r\n\/\/\r\n\/\/\r\nfunc getList(block []StringList,target_name string) []string {\r\n    lists := [] string{}\r\n    for _,i := range block {\r\n        if (i.Type == \"\" || i.Type == target_type) && (i.Target == \"\" || i.Target == target_name) {\r\n            for _,l := range i.List {\r\n                lists = append(lists,l)\r\n            }\r\n            if isDebug == true {\r\n                for _,d := range i.Debug {\r\n                    lists = append(lists,d)\r\n                }\r\n            } else {\r\n                for _,r := range i.Release {\r\n                    lists = append(lists,r)\r\n                }\r\n            }\r\n        }\r\n    }\r\n    return lists\r\n}\r\n\r\n\/\/\r\n\/\/ archive objects\r\n\/\/\r\nfunc create_archive(info BuildInfo,odir string,create_list []string,target_name string) string {\r\n    arname := odir\r\n    if target_type == \"WIN32\" {\r\n        arname += target_name + \".lib\"\r\n    } else {\r\n        arname += \"lib\" + target_name + \".a\"\r\n    }\r\n    arname = filepath.ToSlash(filepath.Clean(arname))\r\n\r\n    archiver := info.variables[\"archiver\"]\r\n    alist := \"\"\r\n    for _,l := range create_list {\r\n        alist += \" \" + l\r\n    }\r\n\r\n    t := fmt.Sprintf(\"Library: %s\",arname)\r\n    cmd := BuildCommand{\r\n        cmd : archiver,\r\n        args : info.archive_options+arname+alist,\r\n        title : t }\r\n    command_list = append(command_list,cmd)\r\n\r\n    return arname\r\n}\r\n\r\n\/\/\r\n\/\/ link objects\r\n\/\/\r\nfunc create_link(info BuildInfo,odir string,create_list []string,target_name string) {\r\n    trname := odir\r\n    if target_type == \"WIN32\" {\r\n        trname += target_name + \".exe\"\r\n    } else {\r\n        trname += target_name\r\n    }\r\n    trname = filepath.ToSlash(filepath.Clean(trname))\r\n\r\n    linker := info.variables[\"linker\"]\r\n\r\n    create_list = append(info.create_list,create_list...)\r\n\r\n    flist := \"\"\r\n    for _,l := range create_list {\r\n        flist += \" \" + l\r\n    }\r\n\r\n    t := fmt.Sprintf(\"Linking: %s\",trname)\r\n    cmd := BuildCommand{\r\n        cmd : linker,\r\n        args : \"-o \" + trname + flist,\r\n        title : t }\r\n    command_list = append(command_list,cmd)\r\n    \/\/fmt.Println(\"-o \" + NowTarget.Name + flist)\r\n}\r\n\r\n\/\/\r\n\/\/ convert objects\r\n\/\/\r\nfunc create_convert(info BuildInfo,loaddir string,odir string,create_list []string,target_name string) {\r\n    cvname := odir + target_name\r\n    cvname = filepath.ToSlash(filepath.Clean(cvname))\r\n    clist := \"\"\r\n    converter := info.variables[\"converter\"]\r\n\r\n    for _,f := range create_list {\r\n        clist += \" \" + filepath.ToSlash(filepath.Clean(loaddir+f))\r\n    }\r\n\r\n    t := fmt.Sprintf(\"Convert: %s\",cvname)\r\n    cmd := BuildCommand{\r\n        cmd : converter,\r\n        args : info.convert_options+\"-o \"+cvname+clist,\r\n        title : t }\r\n    command_list = append(command_list,cmd)\r\n}\r\n\r\n\r\n\/\/\r\n\/\/ build main\r\n\/\/\r\nfunc build(info BuildInfo,pathname string) (result BuildResult,err error) {\r\n    loaddir := pathname\r\n    if loaddir == \"\" {\r\n        loaddir = \".\/\"\r\n    } else {\r\n        loaddir += \"\/\"\r\n    }\r\n    my_yaml := loaddir+\"make.yml\"\r\n    buf, err := ioutil.ReadFile(my_yaml)\r\n    if err != nil {\r\n        e := MyError{ str : my_yaml + \": \" + err.Error() }\r\n        result.success = false\r\n        return result,e\r\n    }\r\n\r\n    var d Data\r\n    err = yaml.Unmarshal(buf, &d)\r\n    if err != nil {\r\n        e := MyError { str : my_yaml + \": \" + err.Error() }\r\n        result.success = false\r\n        return result,e\r\n    }\r\n\r\n    \/\/\r\n    \/\/ select target\r\n    \/\/\r\n    var NowTarget Target\r\n    for _,t := range d.Target {\r\n        if info.select_target == \"\" || t.Name == info.select_target {\r\n            NowTarget = t\r\n            if info.target == \"\" {\r\n                info.target = t.Name\r\n            }\r\n            break\r\n        }\r\n    }\r\n    if NowTarget.Name == \"\" {\r\n        e := MyError{ str : \"No Target\" }\r\n        result.success = false\r\n        return result,e\r\n    }\r\n    info.select_target = \"\"\r\n\r\n    opt_pre := info.variables[\"option_prefix\"]\r\n    \/\/\r\n    \/\/ get rules\r\n    \/\/\r\n    for _,v := range d.Variable {\r\n        if v.Type == \"\" || v.Type == target_type {\r\n            info.variables[v.Name] = v.Value\r\n        }\r\n    }\r\n    for _,i := range getList(d.Include,info.target) {\r\n        abs, err := filepath.Abs(i)\r\n        if err != nil {\r\n            result.success = false\r\n            return result,err\r\n        }\r\n        info.includes += opt_pre + \"I\" + abs + \" \"\r\n    }\r\n    for _,d := range getList(d.Define,info.target) {\r\n        info.defines += opt_pre + \"D\" + d + \" \"\r\n    }\r\n    for _,o := range getList(d.Option,info.target) {\r\n        info.options += opt_pre + o + \" \"\r\n    }\r\n    for _,a := range getList(d.Archive_Option,info.target) {\r\n        info.archive_options += opt_pre + a + \" \"\r\n    }\r\n    for _,c := range getList(d.Convert_Option,info.target) {\r\n        info.convert_options +=  c + \" \"\r\n    }\r\n\r\n    files := getList(d.Source,info.target)\r\n    cvfiles := getList(d.Convert_List,info.target)\r\n\r\n    \/\/ sub-directories\r\n    subdirs := getList(d.Subdir,info.target)\r\n    for _,s := range subdirs {\r\n        sd := loaddir+s\r\n        var r,e = build(info,sd)\r\n        if r.success == false {\r\n            return r,e\r\n        }\r\n        info.create_list = append(info.create_list,r.create_list...)\r\n    }\r\n\r\n    compiler := info.variables[\"compiler\"]\r\n\r\n    arg1 := info.includes + info.defines + info.options\r\n    odir := outputdir + \"\/\" + loaddir\r\n    need_dir_list = append(need_dir_list,filepath.Clean(odir))\r\n\r\n    create_list := []string{}\r\n    for _,f := range files {\r\n        sname := filepath.ToSlash(filepath.Clean(loaddir+f))\r\n        oname := filepath.ToSlash(filepath.Clean(odir+f+\".o\"))\r\n        create_list = append(create_list,oname)\r\n\r\n        t := fmt.Sprintf(\"Compile: %s\",sname)\r\n        cmd := BuildCommand{\r\n            cmd : compiler,\r\n            args : arg1+\"-o \"+oname+\" \"+sname,\r\n            title : t }\r\n        command_list = append(command_list,cmd)\r\n    }\r\n\r\n    if NowTarget.Type == \"library\" {\r\n        \/\/ archive\r\n        if len(create_list) > 0 {\r\n            arname := create_archive(info,odir,create_list,NowTarget.Name)\r\n            result.create_list = append(info.create_list,arname)\r\n            \/\/fmt.Println(info.archive_options+arname+alist)\r\n        } else {\r\n            fmt.Println(\"There are no files to build.\")\r\n        }\r\n    } else if NowTarget.Type == \"execute\" {\r\n        \/\/ link program\r\n        if len(create_list) > 0 && len(info.create_list) > 0 {\r\n            create_link(info,odir,create_list,NowTarget.Name)\r\n        } else {\r\n            fmt.Println(\"There are no files to build.\")\r\n        }\r\n    } else if NowTarget.Type == \"convert\" {\r\n        if len(cvfiles) > 0 {\r\n            create_convert(info,loaddir,odir,cvfiles,NowTarget.Name)\r\n        } else {\r\n            fmt.Println(\"There are no files to convert.\")\r\n        }\r\n    } else {\r\n        \/\/\r\n        \/\/ othre...\r\n        \/\/\r\n        result.create_list = append(info.create_list,create_list...)\r\n    }\r\n    result.success = true\r\n    return result,nil\r\n}\r\n\r\nfunc main() {\r\n\r\n    flag.BoolVar(&isRelease,\"release\",false,\"release build\")\r\n    flag.BoolVar(&isDebug,\"debug\",true,\"debug build\")\r\n    flag.StringVar(&target_type,\"type\",\"default\",\"build target type\")\r\n    flag.StringVar(&target_name,\"t\",\"\",\"build target name\")\r\n    flag.StringVar(&outputdir,\"o\",\"build\",\"build directory\")\r\n    flag.Parse()\r\n\r\n    outputdir += \"\/\" + target_type + \"\/\"\r\n    if isRelease {\r\n        isDebug = false\r\n        outputdir += \"Release\"\r\n    } else {\r\n        outputdir += \"Debug\"\r\n    }\r\n\r\n    build_info := BuildInfo{\r\n        variables : map[string] string{\"option_prefix\":\"-\"},\r\n        includes : \"\",\r\n        defines : \"\",\r\n        select_target : target_name,\r\n        target: target_name }\r\n    var r,err = build(build_info,\"\")\r\n    if r.success == false {\r\n        fmt.Println(\"Error:\",err.Error())\r\n        os.Exit(1)\r\n    }\r\n\r\n    \/\/ setup directories\r\n    for _,nd := range need_dir_list {\r\n        os.MkdirAll(nd,os.ModePerm)\r\n    }\r\n\r\n    \/\/ execute build\r\n    nlen := len(command_list)\r\n    if nlen > 0 {\r\n        for i,bs := range command_list {\r\n            t := fmt.Sprintf(\"[%d\/%d] %s\",i+1,nlen,bs.title)\r\n            fmt.Println(t)\r\n            \/\/fmt.Println(bs.cmd + \":\"+ bs.args)\r\n            arg_list := strings.Split(bs.args,\" \")\r\n            c,_ := exec.Command(bs.cmd,arg_list[0:]...).CombinedOutput()\r\n            msg := *(*string)(unsafe.Pointer(&c))\r\n            if msg != \"\" {\r\n                fmt.Println(msg)\r\n            }\r\n        }\r\n    }\r\n}\r\n\/\/\r\n\/\/\r\n<|endoftext|>"}
{"text":"<commit_before>package asp\n\nimport (\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"unicode\"\n\t\"unicode\/utf8\"\n)\n\n\/\/ Token types.\nconst (\n\tEOF = -(iota + 1)\n\tIdent\n\tInt\n\tString\n\tLexOperator\n\tEOL\n\tUnindent\n)\n\n\/\/ A Token describes each individual lexical element emitted by the lexer.\ntype Token struct {\n\t\/\/ Type of token. If > 0 this is the literal character value; if < 0 it is one of the types above.\n\tType rune\n\t\/\/ The literal text of the token. Strings are lightly normalised to always be surrounded by quotes (but only one).\n\tValue string\n\t\/\/ The position in the input that the token occurred at.\n\tPos Position\n}\n\n\/\/ String implements the fmt.Stringer interface\nfunc (tok Token) String() string {\n\tif tok.Value != \"\" {\n\t\treturn tok.Value\n\t}\n\treturn reverseSymbol(tok.Type)\n}\n\n\/\/ EndPos returns the end position of a token\nfunc (tok Token) EndPos() Position {\n\tend := tok.Pos\n\tend.Offset += len(tok.Value)\n\tend.Column += len(tok.Value)\n\n\treturn end\n}\n\ntype namer interface {\n\tName() string\n}\n\n\/\/ NameOfReader returns a name for the given reader, if one can be determined.\nfunc NameOfReader(r io.Reader) string {\n\tif n, ok := r.(namer); ok {\n\t\treturn n.Name()\n\t}\n\treturn \"\"\n}\n\n\/\/ newLexer creates a new lex instance.\nfunc newLexer(r io.Reader) *lex {\n\t\/\/ Read the entire file upfront to avoid bufio etc.\n\t\/\/ This should work OK as long as BUILD files are relatively small.\n\tb, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\tfail(Position{Filename: NameOfReader(r)}, err.Error())\n\t}\n\t\/\/ If the file doesn't end in a newline, we will reject it with an \"unexpected end of file\"\n\t\/\/ error. That's a bit crap so quietly fix it up here.\n\tif len(b) > 0 && b[len(b)-1] != '\\n' {\n\t\tb = append(b, '\\n')\n\t}\n\tl := &lex{\n\t\tb:        append(b, 0, 0), \/\/ Null-terminating the buffer makes things easier later.\n\t\tfilename: NameOfReader(r),\n\t\tindents:  []int{0},\n\t}\n\tl.Next() \/\/ Initial value is zero, this forces it to populate itself.\n\t\/\/ Discard any leading newlines, they are just an annoyance.\n\tfor l.Peek().Type == EOL {\n\t\tl.Next()\n\t}\n\treturn l\n}\n\n\/\/ A lex is a lexer for a single BUILD file.\ntype lex struct {\n\tb      []byte\n\ti      int\n\tline   int\n\tcol    int\n\tindent int\n\t\/\/ The next token. We always look one token ahead in order to facilitate both Peek() and Next().\n\tnext     Token\n\tfilename string\n\t\/\/ Used to track how many braces we're within.\n\tbraces int\n\t\/\/ Pending unindent tokens. This is a bit yuck but means the parser doesn't need to\n\t\/\/ concern itself about indentation.\n\tunindents int\n\t\/\/ Current levels of indentation\n\tindents []int\n\t\/\/ Remember whether the last token we output was an end-of-line so we don't emit multiple in sequence.\n\tlastEOL bool\n}\n\n\/\/ reverseSymbol looks up a symbol's name from the lexer.\nfunc reverseSymbol(sym rune) string {\n\tswitch sym {\n\tcase EOF:\n\t\treturn \"end of file\"\n\tcase Ident:\n\t\treturn \"identifier\"\n\tcase Int:\n\t\treturn \"integer\"\n\tcase String:\n\t\treturn \"string\"\n\tcase LexOperator:\n\t\treturn \"operator\"\n\tcase EOL:\n\t\treturn \"end of line\"\n\tcase Unindent:\n\t\treturn \"unindent\"\n\t}\n\treturn string(sym) \/\/ literal character\n}\n\n\/\/ reverseSymbols looks up a series of symbol's names from the lexer.\nfunc reverseSymbols(syms []rune) []string {\n\tret := make([]string, len(syms))\n\tfor i, sym := range syms {\n\t\tret[i] = reverseSymbol(sym)\n\t}\n\treturn ret\n}\n\n\/\/ Peek at the next token\nfunc (l *lex) Peek() Token {\n\treturn l.next\n}\n\n\/\/ Next consumes and returns the next token.\nfunc (l *lex) Next() Token {\n\tret := l.next\n\tl.next = l.nextToken()\n\tl.lastEOL = l.next.Type == EOL || l.next.Type == Unindent\n\treturn ret\n}\n\n\/\/ AssignFollows is a hack to do extra lookahead which makes it easier to parse\n\/\/ named call arguments. It returns true if the token after next is an assign operator.\nfunc (l *lex) AssignFollows() bool {\n\tl.stripSpaces()\n\treturn l.b[l.i] == '=' && l.b[l.i+1] != '='\n}\n\nfunc (l *lex) stripSpaces() {\n\tfor l.b[l.i] == ' ' {\n\t\tl.i++\n\t\tl.col++\n\t}\n}\n\n\/\/ nextToken consumes and returns the next token.\nfunc (l *lex) nextToken() Token {\n\tl.stripSpaces()\n\tpos := Position{\n\t\tFilename: l.filename,\n\t\t\/\/ These are all 1-indexed for niceness.\n\t\tOffset: l.i + 1,\n\t\tLine:   l.line + 1,\n\t\tColumn: l.col + 1,\n\t}\n\tif l.unindents > 0 {\n\t\tl.unindents--\n\t\treturn Token{Type: Unindent, Pos: pos}\n\t}\n\tb := l.b[l.i]\n\trawString := b == 'r' && (l.b[l.i+1] == '\"' || l.b[l.i+1] == '\\'')\n\tfString := b == 'f' && (l.b[l.i+1] == '\"' || l.b[l.i+1] == '\\'')\n\tif rawString || fString {\n\t\tl.i++\n\t\tl.col++\n\t\tb = l.b[l.i]\n\t} else if (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || b >= utf8.RuneSelf {\n\t\treturn l.consumeIdent(pos)\n\t}\n\tl.i++\n\tl.col++\n\tswitch b {\n\tcase 0:\n\t\t\/\/ End of file (we null terminate it above so this is easy to spot)\n\t\treturn Token{Type: EOF, Pos: pos}\n\tcase '\\r':\n\t\treturn l.nextToken()\n\tcase '\\n':\n\t\t\/\/ End of line, read indent to next non-space character\n\t\tlastIndent := l.indent\n\t\tl.line++\n\t\tl.col = 0\n\t\tindent := 0\n\t\tfor l.b[l.i] == ' ' {\n\t\t\tl.i++\n\t\t\tl.col++\n\t\t\tindent++\n\t\t}\n\t\tif l.b[l.i] == '\\n' {\n\t\t\treturn l.nextToken()\n\t\t}\n\t\tif l.braces == 0 {\n\t\t\tl.indent = indent\n\t\t}\n\t\tif lastIndent > l.indent && l.braces == 0 {\n\t\t\tpos.Line++ \/\/ Works better if it's at the new position\n\t\t\tpos.Column = l.col + 1\n\t\t\tfor l.indents[len(l.indents)-1] > l.indent {\n\t\t\t\tl.unindents++\n\t\t\t\tl.indents = l.indents[:len(l.indents)-1]\n\t\t\t}\n\t\t\tif l.indent != l.indents[len(l.indents)-1] {\n\t\t\t\tfail(pos, \"Unexpected indent\")\n\t\t\t}\n\t\t} else if lastIndent != l.indent {\n\t\t\tl.indents = append(l.indents, l.indent)\n\t\t}\n\t\tif l.braces == 0 && !l.lastEOL {\n\t\t\treturn Token{Type: EOL, Pos: pos}\n\t\t}\n\t\treturn l.nextToken()\n\tcase '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':\n\t\treturn l.consumeInteger(b, pos)\n\tcase '\"', '\\'':\n\t\t\/\/ String literal, consume to end.\n\t\treturn l.consumePossiblyTripleQuotedString(b, pos, rawString, fString)\n\tcase '(', '[', '{':\n\t\tl.braces++\n\t\treturn Token{Type: rune(b), Value: string(b), Pos: pos}\n\tcase ')', ']', '}':\n\t\tif l.braces > 0 { \/\/ Don't let it go negative, it fouls things up\n\t\t\tl.braces--\n\t\t}\n\t\treturn Token{Type: rune(b), Value: string(b), Pos: pos}\n\tcase '=', '!', '+', '<', '>':\n\t\t\/\/ Look ahead one byte to see if this is an augmented assignment or comparison.\n\t\tif l.b[l.i] == '=' {\n\t\t\tl.i++\n\t\t\tl.col++\n\t\t\treturn Token{Type: LexOperator, Value: string([]byte{b, l.b[l.i-1]}), Pos: pos}\n\t\t}\n\t\tfallthrough\n\tcase ',', '.', '%', '*', '|', '&', ':', '\/':\n\t\treturn Token{Type: rune(b), Value: string(b), Pos: pos}\n\tcase '#':\n\t\t\/\/ Comment character, consume to end of line.\n\t\tfor l.b[l.i] != '\\n' && l.b[l.i] != 0 {\n\t\t\tl.i++\n\t\t\tl.col++\n\t\t}\n\t\treturn l.nextToken() \/\/ Comments aren't tokens themselves.\n\tcase '-':\n\t\t\/\/ We lex unary - with the integer if possible.\n\t\tif l.b[l.i] >= '0' && l.b[l.i] <= '9' {\n\t\t\treturn l.consumeInteger(b, pos)\n\t\t}\n\t\treturn Token{Type: rune(b), Value: string(b), Pos: pos}\n\tcase '\\t':\n\t\tfail(pos, \"Tabs are not permitted in BUILD files, use space-based indentation instead\")\n\tdefault:\n\t\tfail(pos, \"Unknown symbol %c\", b)\n\t}\n\tpanic(\"unreachable\")\n}\n\n\/\/ consumeInteger consumes all characters until the end of an integer literal is reached.\nfunc (l *lex) consumeInteger(initial byte, pos Position) Token {\n\ts := make([]byte, 1, 10)\n\ts[0] = initial\n\tfor c := l.b[l.i]; c >= '0' && c <= '9'; c = l.b[l.i] {\n\t\tl.i++\n\t\tl.col++\n\t\ts = append(s, c)\n\t}\n\treturn Token{Type: Int, Value: string(s), Pos: pos}\n}\n\n\/\/ consumePossiblyTripleQuotedString consumes all characters until the end of a string token.\nfunc (l *lex) consumePossiblyTripleQuotedString(quote byte, pos Position, raw, fString bool) Token {\n\tif l.b[l.i] == quote && l.b[l.i+1] == quote {\n\t\tl.i += 2 \/\/ Jump over initial quote\n\t\tl.col += 2\n\t\treturn l.consumeString(quote, pos, true, raw, fString)\n\t}\n\treturn l.consumeString(quote, pos, false, raw, fString)\n}\n\n\/\/ consumeString consumes all characters until the end of a string literal is reached.\nfunc (l *lex) consumeString(quote byte, pos Position, multiline, raw, fString bool) Token {\n\ts := make([]byte, 1, 100) \/\/ 100 chars is typically enough for a single string literal.\n\ts[0] = '\"'\n\tescaped := false\n\tfor {\n\t\tc := l.b[l.i]\n\t\tl.i++\n\t\tl.col++\n\t\tif escaped {\n\t\t\tif c == 'n' {\n\t\t\t\ts = append(s, '\\n')\n\t\t\t} else if c == '\\n' && multiline {\n\t\t\t\tl.line++\n\t\t\t\tl.col = 0\n\t\t\t} else if c == '\\\\' || c == '\\'' || c == '\"' {\n\t\t\t\ts = append(s, c)\n\t\t\t} else {\n\t\t\t\ts = append(s, '\\\\', c)\n\t\t\t}\n\t\t\tescaped = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch c {\n\t\tcase quote:\n\t\t\tif !multiline || (l.b[l.i] == quote && l.b[l.i+1] == quote) {\n\t\t\t\ts = append(s, '\"')\n\t\t\t\tif multiline {\n\t\t\t\t\tl.i += 2\n\t\t\t\t\tl.col += 2\n\t\t\t\t}\n\t\t\t\ttoken := Token{Type: String, Value: string(s), Pos: pos}\n\t\t\t\tif fString {\n\t\t\t\t\ttoken.Value = \"f\" + token.Value\n\t\t\t\t}\n\t\t\t\treturn token\n\t\t\t}\n\t\t\ts = append(s, c)\n\t\tcase '\\n':\n\t\t\tif multiline {\n\t\t\t\tl.line++\n\t\t\t\tl.col = 0\n\t\t\t\ts = append(s, c)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfallthrough\n\t\tcase 0:\n\t\t\tfail(pos, \"Unterminated string literal\")\n\t\tcase '\\\\':\n\t\t\tif !raw {\n\t\t\t\tescaped = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\ts = append(s, c)\n\t\t}\n\t}\n}\n\n\/\/ consumeIdent consumes all characters of an identifier.\nfunc (l *lex) consumeIdent(pos Position) Token {\n\ts := make([]rune, 0, 100)\n\tfor {\n\t\tc := rune(l.b[l.i])\n\t\tif c >= utf8.RuneSelf {\n\t\t\t\/\/ Multi-byte encoded in utf-8.\n\t\t\tr, n := utf8.DecodeRune(l.b[l.i:])\n\t\t\tc = r\n\t\t\tl.i += n\n\t\t\tl.col += n\n\t\t\tif !unicode.IsLetter(c) && !unicode.IsDigit(c) {\n\t\t\t\tfail(pos, \"Illegal Unicode identifier %c\", c)\n\t\t\t}\n\t\t\ts = append(s, c)\n\t\t\tcontinue\n\t\t}\n\t\tl.i++\n\t\tl.col++\n\t\tswitch c {\n\t\tcase ' ':\n\t\t\t\/\/ End of identifier, but no unconsuming needed.\n\t\t\treturn Token{Type: Ident, Value: string(s), Pos: pos}\n\t\tcase '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':\n\t\t\ts = append(s, c)\n\t\tdefault:\n\t\t\t\/\/ End of identifier. Unconsume the last character so it gets handled next time.\n\t\t\tl.i--\n\t\t\tl.col--\n\t\t\treturn Token{Type: Ident, Value: string(s), Pos: pos}\n\t\t}\n\t}\n}\n<commit_msg>Refactor the variable names in the lexer so it's easier to follow (#2185)<commit_after>package asp\n\nimport (\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"unicode\"\n\t\"unicode\/utf8\"\n)\n\n\/\/ Token types.\nconst (\n\tEOF = -(iota + 1)\n\tIdent\n\tInt\n\tString\n\tLexOperator\n\tEOL\n\tUnindent\n)\n\n\/\/ A Token describes each individual lexical element emitted by the lexer.\ntype Token struct {\n\t\/\/ Type of token. If > 0 this is the literal character value; if < 0 it is one of the types above.\n\tType rune\n\t\/\/ The literal text of the token. Strings are lightly normalised to always be surrounded by quotes (but only one).\n\tValue string\n\t\/\/ The position in the input that the token occurred at.\n\tPos Position\n}\n\n\/\/ String implements the fmt.Stringer interface\nfunc (tok Token) String() string {\n\tif tok.Value != \"\" {\n\t\treturn tok.Value\n\t}\n\treturn reverseSymbol(tok.Type)\n}\n\n\/\/ EndPos returns the end position of a token\nfunc (tok Token) EndPos() Position {\n\tend := tok.Pos\n\tend.Offset += len(tok.Value)\n\tend.Column += len(tok.Value)\n\n\treturn end\n}\n\ntype namer interface {\n\tName() string\n}\n\n\/\/ NameOfReader returns a name for the given reader, if one can be determined.\nfunc NameOfReader(r io.Reader) string {\n\tif n, ok := r.(namer); ok {\n\t\treturn n.Name()\n\t}\n\treturn \"\"\n}\n\n\/\/ newLexer creates a new lex instance.\nfunc newLexer(r io.Reader) *lex {\n\t\/\/ Read the entire file upfront to avoid bufio etc.\n\t\/\/ This should work OK as long as BUILD files are relatively small.\n\tb, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\tfail(Position{Filename: NameOfReader(r)}, err.Error())\n\t}\n\t\/\/ If the file doesn't end in a newline, we will reject it with an \"unexpected end of file\"\n\t\/\/ error. That's a bit crap so quietly fix it up here.\n\tif len(b) > 0 && b[len(b)-1] != '\\n' {\n\t\tb = append(b, '\\n')\n\t}\n\tl := &lex{\n\t\tbytes:    append(b, 0, 0), \/\/ Null-terminating the buffer makes things easier later.\n\t\tfilename: NameOfReader(r),\n\t\tindents:  []int{0},\n\t}\n\tl.Next() \/\/ Initial value is zero, this forces it to populate itself.\n\t\/\/ Discard any leading newlines, they are just an annoyance.\n\tfor l.Peek().Type == EOL {\n\t\tl.Next()\n\t}\n\treturn l\n}\n\n\/\/ A lex is a lexer for a single BUILD file.\ntype lex struct {\n\t\/\/ The raw bytes we're lexing\n\tbytes []byte\n\t\/\/ The current position of the lexer in the byte buffer\n\tpos int\n\t\/\/ The line and column we're on\n\tline, col int\n\t\/\/ The current level of indentation we're on in the file\n\tindent int\n\t\/\/ The next token. We always look one token ahead in order to facilitate both Peek() and Next().\n\tnext Token\n\t\/\/ The name of the file we're parsing. Can be unset if we're parsing a non-file reader.\n\tfilename string\n\t\/\/ Used to track how many braces we're within.\n\tbraces int\n\t\/\/ Pending unindent tokens. This is a bit yuck but means the parser doesn't need to\n\t\/\/ concern itself about indentation.\n\tunindents int\n\t\/\/ Current levels of indentation\n\tindents []int\n\t\/\/ Remember whether the last token we output was an end-of-line so we don't emit multiple in sequence.\n\tlastEOL bool\n}\n\n\/\/ reverseSymbol looks up a symbol's name from the lexer.\nfunc reverseSymbol(sym rune) string {\n\tswitch sym {\n\tcase EOF:\n\t\treturn \"end of file\"\n\tcase Ident:\n\t\treturn \"identifier\"\n\tcase Int:\n\t\treturn \"integer\"\n\tcase String:\n\t\treturn \"string\"\n\tcase LexOperator:\n\t\treturn \"operator\"\n\tcase EOL:\n\t\treturn \"end of line\"\n\tcase Unindent:\n\t\treturn \"unindent\"\n\t}\n\treturn string(sym) \/\/ literal character\n}\n\n\/\/ reverseSymbols looks up a series of symbol's names from the lexer.\nfunc reverseSymbols(syms []rune) []string {\n\tret := make([]string, len(syms))\n\tfor i, sym := range syms {\n\t\tret[i] = reverseSymbol(sym)\n\t}\n\treturn ret\n}\n\n\/\/ Peek at the next token\nfunc (l *lex) Peek() Token {\n\treturn l.next\n}\n\n\/\/ Next consumes and returns the next token.\nfunc (l *lex) Next() Token {\n\tret := l.next\n\tl.next = l.nextToken()\n\tl.lastEOL = l.next.Type == EOL || l.next.Type == Unindent\n\treturn ret\n}\n\n\/\/ AssignFollows is a hack to do extra lookahead which makes it easier to parse\n\/\/ named call arguments. It returns true if the token after next is an assign operator.\nfunc (l *lex) AssignFollows() bool {\n\tl.stripSpaces()\n\treturn l.bytes[l.pos] == '=' && l.bytes[l.pos+1] != '='\n}\n\nfunc (l *lex) stripSpaces() {\n\tfor l.bytes[l.pos] == ' ' {\n\t\tl.pos++\n\t\tl.col++\n\t}\n}\n\n\/\/ nextToken consumes and returns the next token.\nfunc (l *lex) nextToken() Token {\n\tl.stripSpaces()\n\tpos := Position{\n\t\tFilename: l.filename,\n\t\t\/\/ These are all 1-indexed for niceness.\n\t\tOffset: l.pos + 1,\n\t\tLine:   l.line + 1,\n\t\tColumn: l.col + 1,\n\t}\n\tif l.unindents > 0 {\n\t\tl.unindents--\n\t\treturn Token{Type: Unindent, Pos: pos}\n\t}\n\tnext := l.bytes[l.pos]\n\trawString := next == 'r' && (l.bytes[l.pos+1] == '\"' || l.bytes[l.pos+1] == '\\'')\n\tfString := next == 'f' && (l.bytes[l.pos+1] == '\"' || l.bytes[l.pos+1] == '\\'')\n\tif rawString || fString {\n\t\tl.pos++\n\t\tl.col++\n\t\tnext = l.bytes[l.pos]\n\t} else if (next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z') || next == '_' || next >= utf8.RuneSelf {\n\t\treturn l.consumeIdent(pos)\n\t}\n\tl.pos++\n\tl.col++\n\tswitch next {\n\tcase 0:\n\t\t\/\/ End of file (we null terminate it above so this is easy to spot)\n\t\treturn Token{Type: EOF, Pos: pos}\n\tcase '\\r':\n\t\treturn l.nextToken()\n\tcase '\\n':\n\t\t\/\/ End of line, read indent to next non-space character\n\t\tlastIndent := l.indent\n\t\tl.line++\n\t\tl.col = 0\n\t\tindent := 0\n\t\tfor l.bytes[l.pos] == ' ' {\n\t\t\tl.pos++\n\t\t\tl.col++\n\t\t\tindent++\n\t\t}\n\t\tif l.bytes[l.pos] == '\\n' {\n\t\t\treturn l.nextToken()\n\t\t}\n\t\tif l.braces == 0 {\n\t\t\tl.indent = indent\n\t\t}\n\t\tif lastIndent > l.indent && l.braces == 0 {\n\t\t\tpos.Line++ \/\/ Works better if it's at the new position\n\t\t\tpos.Column = l.col + 1\n\t\t\tfor l.indents[len(l.indents)-1] > l.indent {\n\t\t\t\tl.unindents++\n\t\t\t\tl.indents = l.indents[:len(l.indents)-1]\n\t\t\t}\n\t\t\tif l.indent != l.indents[len(l.indents)-1] {\n\t\t\t\tfail(pos, \"Unexpected indent\")\n\t\t\t}\n\t\t} else if lastIndent != l.indent {\n\t\t\tl.indents = append(l.indents, l.indent)\n\t\t}\n\t\tif l.braces == 0 && !l.lastEOL {\n\t\t\treturn Token{Type: EOL, Pos: pos}\n\t\t}\n\t\treturn l.nextToken()\n\tcase '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':\n\t\treturn l.consumeInteger(next, pos)\n\tcase '\"', '\\'':\n\t\t\/\/ String literal, consume to end.\n\t\treturn l.consumePossiblyTripleQuotedString(next, pos, rawString, fString)\n\tcase '(', '[', '{':\n\t\tl.braces++\n\t\treturn Token{Type: rune(next), Value: string(next), Pos: pos}\n\tcase ')', ']', '}':\n\t\tif l.braces > 0 { \/\/ Don't let it go negative, it fouls things up\n\t\t\tl.braces--\n\t\t}\n\t\treturn Token{Type: rune(next), Value: string(next), Pos: pos}\n\tcase '=', '!', '+', '<', '>':\n\t\t\/\/ Look ahead one byte to see if this is an augmented assignment or comparison.\n\t\tif l.bytes[l.pos] == '=' {\n\t\t\tl.pos++\n\t\t\tl.col++\n\t\t\treturn Token{Type: LexOperator, Value: string([]byte{next, l.bytes[l.pos-1]}), Pos: pos}\n\t\t}\n\t\tfallthrough\n\tcase ',', '.', '%', '*', '|', '&', ':', '\/':\n\t\treturn Token{Type: rune(next), Value: string(next), Pos: pos}\n\tcase '#':\n\t\t\/\/ Comment character, consume to end of line.\n\t\tfor l.bytes[l.pos] != '\\n' && l.bytes[l.pos] != 0 {\n\t\t\tl.pos++\n\t\t\tl.col++\n\t\t}\n\t\treturn l.nextToken() \/\/ Comments aren't tokens themselves.\n\tcase '-':\n\t\t\/\/ We lex unary - with the integer if possible.\n\t\tif l.bytes[l.pos] >= '0' && l.bytes[l.pos] <= '9' {\n\t\t\treturn l.consumeInteger(next, pos)\n\t\t}\n\t\treturn Token{Type: rune(next), Value: string(next), Pos: pos}\n\tcase '\\t':\n\t\tfail(pos, \"Tabs are not permitted in BUILD files, use space-based indentation instead\")\n\tdefault:\n\t\tfail(pos, \"Unknown symbol %c\", next)\n\t}\n\tpanic(\"unreachable\")\n}\n\n\/\/ consumeInteger consumes all characters until the end of an integer literal is reached.\nfunc (l *lex) consumeInteger(initial byte, pos Position) Token {\n\tvalue := make([]byte, 1, 10)\n\tvalue[0] = initial\n\tfor next := l.bytes[l.pos]; next >= '0' && next <= '9'; next = l.bytes[l.pos] {\n\t\tl.pos++\n\t\tl.col++\n\t\tvalue = append(value, next)\n\t}\n\treturn Token{Type: Int, Value: string(value), Pos: pos}\n}\n\n\/\/ consumePossiblyTripleQuotedString consumes all characters until the end of a string token.\nfunc (l *lex) consumePossiblyTripleQuotedString(quote byte, pos Position, raw, fString bool) Token {\n\tif l.bytes[l.pos] == quote && l.bytes[l.pos+1] == quote {\n\t\tl.pos += 2 \/\/ Jump over initial quote\n\t\tl.col += 2\n\t\treturn l.consumeString(quote, pos, true, raw, fString)\n\t}\n\treturn l.consumeString(quote, pos, false, raw, fString)\n}\n\n\/\/ consumeString consumes all characters until the end of a string literal is reached.\nfunc (l *lex) consumeString(quote byte, pos Position, multiline, raw, fString bool) Token {\n\tvalue := make([]byte, 1, 100) \/\/ 100 chars is typically enough for a single string literal.\n\tvalue[0] = '\"'\n\tescaped := false\n\tfor {\n\t\tnext := l.bytes[l.pos]\n\t\tl.pos++\n\t\tl.col++\n\t\tif escaped {\n\t\t\tif next == 'n' {\n\t\t\t\tvalue = append(value, '\\n')\n\t\t\t} else if next == '\\n' && multiline {\n\t\t\t\tl.line++\n\t\t\t\tl.col = 0\n\t\t\t} else if next == '\\\\' || next == '\\'' || next == '\"' {\n\t\t\t\tvalue = append(value, next)\n\t\t\t} else {\n\t\t\t\tvalue = append(value, '\\\\', next)\n\t\t\t}\n\t\t\tescaped = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch next {\n\t\tcase quote:\n\t\t\tif !multiline || (l.bytes[l.pos] == quote && l.bytes[l.pos+1] == quote) {\n\t\t\t\tvalue = append(value, '\"')\n\t\t\t\tif multiline {\n\t\t\t\t\tl.pos += 2\n\t\t\t\t\tl.col += 2\n\t\t\t\t}\n\t\t\t\ttoken := Token{Type: String, Value: string(value), Pos: pos}\n\t\t\t\tif fString {\n\t\t\t\t\ttoken.Value = \"f\" + token.Value\n\t\t\t\t}\n\t\t\t\treturn token\n\t\t\t}\n\t\t\tvalue = append(value, next)\n\t\tcase '\\n':\n\t\t\tif multiline {\n\t\t\t\tl.line++\n\t\t\t\tl.col = 0\n\t\t\t\tvalue = append(value, next)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfallthrough\n\t\tcase 0:\n\t\t\tfail(pos, \"Unterminated string literal\")\n\t\tcase '\\\\':\n\t\t\tif !raw {\n\t\t\t\tescaped = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\tvalue = append(value, next)\n\t\t}\n\t}\n}\n\n\/\/ consumeIdent consumes all characters of an identifier.\nfunc (l *lex) consumeIdent(pos Position) Token {\n\ts := make([]rune, 0, 100)\n\tfor {\n\t\tc := rune(l.bytes[l.pos])\n\t\tif c >= utf8.RuneSelf {\n\t\t\t\/\/ Multi-byte encoded in utf-8.\n\t\t\tr, n := utf8.DecodeRune(l.bytes[l.pos:])\n\t\t\tc = r\n\t\t\tl.pos += n\n\t\t\tl.col += n\n\t\t\tif !unicode.IsLetter(c) && !unicode.IsDigit(c) {\n\t\t\t\tfail(pos, \"Illegal Unicode identifier %c\", c)\n\t\t\t}\n\t\t\ts = append(s, c)\n\t\t\tcontinue\n\t\t}\n\t\tl.pos++\n\t\tl.col++\n\t\tswitch c {\n\t\tcase ' ':\n\t\t\t\/\/ End of identifier, but no unconsuming needed.\n\t\t\treturn Token{Type: Ident, Value: string(s), Pos: pos}\n\t\tcase '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':\n\t\t\ts = append(s, c)\n\t\tdefault:\n\t\t\t\/\/ End of identifier. Unconsume the last character so it gets handled next time.\n\t\t\tl.pos--\n\t\t\tl.col--\n\t\t\treturn Token{Type: Ident, Value: string(s), Pos: pos}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"log\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"os\"\n)\n\nfunc postForm(uri string, params map[string]string, files map[string][]byte) (err error) {\n\tbody := &bytes.Buffer{}\n\tw := multipart.NewWriter(body)\n\tfor field, value := range params {\n\t\terr = w.WriteField(field, value)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tfor name, data := range files {\n\t\tpart, er := w.CreateFormFile(name, \"rep.html\")\n\t\tif er != nil {\n\t\t\terr = er\n\t\t\treturn er\n\t\t}\n\t\t_, er = part.Write(data)\n\t\tif er != nil {\n\t\t\terr = er\n\t\t\treturn\n\t\t}\n\t}\n\tif err = w.Close(); err != nil {\n\t\treturn\n\t}\n\t\/\/log.Println(\"boundary:\", w.Boundary(), len(body.Bytes()))\n\treq, err := http.NewRequest(\"POST\", uri, body)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = w.Close(); err != nil {\n\t\treturn\n\t}\n\n\treq.Header.Set(\"Content-Type\", w.FormDataContentType())\n\t\/\/req.ContentLength += 68\n\tvar client http.Client\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\tio.Copy(os.Stderr, res.Body)\n\treturn\n}\n\nfunc sendNotify(msg string, users ...string) (err error) {\n\tparams := map[string]string{\n\t\t\"username\": \"sunshengxiang01\",\n\t\t\"tel\":      \"185123\",\n\t}\n\terr = postForm(\"http:\/\/localhost:8080\", params, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn nil\n}\n\nfunc init() {\n\t\/\/\tsendNotify(\"hi body\", \"sunshengxiang01\")\n}\n<commit_msg>add notify<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"log\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"os\"\n)\n\nfunc postForm(uri string, params map[string]string, files map[string][]byte) (err error) {\n\tbody := &bytes.Buffer{}\n\tw := multipart.NewWriter(body)\n\tfor field, value := range params {\n\t\terr = w.WriteField(field, value)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tfor name, data := range files {\n\t\tpart, er := w.CreateFormFile(name, \"rep.html\")\n\t\tif er != nil {\n\t\t\terr = er\n\t\t\treturn er\n\t\t}\n\t\t_, er = part.Write(data)\n\t\tif er != nil {\n\t\t\terr = er\n\t\t\treturn\n\t\t}\n\t}\n\tif err = w.Close(); err != nil {\n\t\treturn\n\t}\n\tlog.Println(\"boundary:\", w.Boundary(), len(body.Bytes()))\n\treq, err := http.NewRequest(\"POST\", uri, body)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = w.Close(); err != nil {\n\t\treturn\n\t}\n\n\treq.Header.Set(\"Content-Type\", w.FormDataContentType())\n\t\/\/req.ContentLength += 68\n\tvar client http.Client\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\tio.Copy(os.Stderr, res.Body)\n\treturn\n}\n\nfunc sendNotify(msg string, users ...string) (err error) {\n\tparams := map[string]string{\n\t\t\"username\": \"sunshengxiang01\",\n\t\t\"tel\":      \"185123\",\n\t}\n\terr = postForm(\"http:\/\/localhost:8080\", params, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn nil\n}\n\nfunc init() {\n\t\/\/\tsendNotify(\"hi body\", \"sunshengxiang01\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package jiralert\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/andygrunwald\/go-jira\"\n\t\"github.com\/free\/jiralert\/alertmanager\"\n\tlog \"github.com\/golang\/glog\"\n\t\"github.com\/trivago\/tgo\/tcontainer\"\n)\n\n\/\/ Receiver wraps a JIRA client corresponding to a specific Alertmanager receiver, with its configuration and templates.\ntype Receiver struct {\n\tconf   *ReceiverConfig\n\ttmpl   *Template\n\tclient *jira.Client\n}\n\n\/\/ NewReceiver creates a Receiver using the provided configuration and template.\nfunc NewReceiver(c *ReceiverConfig, t *Template) (*Receiver, error) {\n\tclient, err := jira.NewClient(http.DefaultClient, c.APIURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient.Authentication.SetBasicAuth(c.User, string(c.Password))\n\n\treturn &Receiver{conf: c, tmpl: t, client: client}, nil\n}\n\n\/\/ Notify implements the Notifier interface.\nfunc (r *Receiver) Notify(data *alertmanager.Data) (bool, error) {\n\tproject := r.tmpl.Execute(r.conf.Project, data)\n\t\/\/ check errors from r.tmpl.Execute()\n\tif r.tmpl.err != nil {\n\t\treturn false, r.tmpl.err\n\t}\n\t\/\/ Looks like an ALERT metric name, with spaces removed.\n\tissueLabel := toIssueLabel(data.GroupLabels)\n\n\tissue, retry, err := r.search(project, issueLabel)\n\tif err != nil {\n\t\treturn retry, err\n\t}\n\n\tif issue != nil {\n\t\t\/\/ The set of JIRA status categories is fixed, this is a safe check to make.\n\t\tif issue.Fields.Status.StatusCategory.Key != \"done\" {\n\t\t\t\/\/ Issue is in a \"to do\" or \"in progress\" state, all done here.\n\t\t\tlog.V(1).Infof(\"Issue %s for %s is unresolved, nothing to do\", issue.Key, issueLabel)\n\t\t\treturn false, nil\n\t\t}\n\t\tif r.conf.WontFixResolution != \"\" && issue.Fields.Resolution.Name == r.conf.WontFixResolution {\n\t\t\t\/\/ Issue is resolved as \"Won't Fix\" or equivalent, log a message just in case.\n\t\t\tlog.Infof(\"Issue %s for %s is resolved as %q, not reopening\", issue.Key, issueLabel, issue.Fields.Resolution.Name)\n\t\t\treturn false, nil\n\t\t}\n\t\tlog.Infof(\"Issue %s for %s was resolved, reopening\", issue.Key, issueLabel)\n\t\treturn r.reopen(issue.Key)\n\t}\n\n\tlog.Infof(\"No issue matching %s found, creating new issue\", issueLabel)\n\tissue = &jira.Issue{\n\t\tFields: &jira.IssueFields{\n\t\t\tProject:     jira.Project{Key: project},\n\t\t\tType:        jira.IssueType{Name: r.tmpl.Execute(r.conf.IssueType, data)},\n\t\t\tDescription: r.tmpl.Execute(r.conf.Description, data),\n\t\t\tSummary:     r.tmpl.Execute(r.conf.Summary, data),\n\t\t\tLabels: []string{\n\t\t\t\tissueLabel,\n\t\t\t},\n\t\t\tUnknowns: tcontainer.NewMarshalMap(),\n\t\t},\n\t}\n\tif r.conf.Priority != \"\" {\n\t\tissue.Fields.Priority = &jira.Priority{Name: r.tmpl.Execute(r.conf.Priority, data)}\n\t}\n\n\t\/\/ Add Components\n\tissue.Fields.Components = make([]*jira.Component, 0, len(r.conf.Components))\n\tfor _, component := range r.conf.Components {\n\t\tissue.Fields.Components = append(issue.Fields.Components, &jira.Component{Name: component})\n\t}\n\n\t\/\/ Add Labels\n\tif r.conf.AddGroupLabels {\n\t\tfor k, v := range data.GroupLabels {\n\t\t\tissue.Fields.Labels = append(issue.Fields.Labels, fmt.Sprintf(\"%s=%q\", k, v))\n\t\t}\n\t}\n\n\tfor key, value := range r.conf.Fields {\n\t\tissue.Fields.Unknowns[key] = r.tmpl.Execute(fmt.Sprint(value), data)\n\t}\n\t\/\/ check errors from r.tmpl.Execute()\n\tif r.tmpl.err != nil {\n\t\treturn false, r.tmpl.err\n\t}\n\tretry, err = r.create(issue)\n\tif err != nil {\n\t\tlog.Infof(\"Issue created: key=%s ID=%s\", issue.Key, issue.ID)\n\t}\n\treturn retry, err\n}\n\n\/\/ toIssueLabel returns the group labels in the form of an ALERT metric name, with all spaces removed.\nfunc toIssueLabel(groupLabels alertmanager.KV) string {\n\tbuf := bytes.NewBufferString(\"ALERT{\")\n\tfor _, p := range groupLabels.SortedPairs() {\n\t\tbuf.WriteString(p.Name)\n\t\tbuf.WriteString(fmt.Sprintf(\"=%q,\", p.Value))\n\t}\n\tbuf.Truncate(buf.Len() - 1)\n\tbuf.WriteString(\"}\")\n\treturn strings.Replace(buf.String(), \" \", \"\", -1)\n}\n\nfunc (r *Receiver) search(project, issueLabel string) (*jira.Issue, bool, error) {\n\tquery := fmt.Sprintf(\"project=%s and labels=%q order by key\", project, issueLabel)\n\toptions := &jira.SearchOptions{\n\t\tFields:     []string{\"summary\", \"status\", \"resolution\"},\n\t\tMaxResults: 50,\n\t}\n\tlog.V(1).Infof(\"search: query=%v options=%+v\", query, options)\n\tissues, resp, err := r.client.Issue.Search(query, options)\n\tif err != nil {\n\t\tretry, err := handleJiraError(resp, err)\n\t\treturn nil, retry, err\n\t}\n\tif len(issues) > 0 {\n\t\tif len(issues) > 1 {\n\t\t\t\/\/ Swallow it, but log an error.\n\t\t\tlog.Errorf(\"More than one issue matched %s, will only update first: %+v\", query, issues)\n\t\t}\n\t\tlog.V(1).Infof(\"  found: %+v\", issues[0])\n\t\treturn &issues[0], false, nil\n\t}\n\tlog.V(1).Infof(\"  no results\")\n\treturn nil, false, nil\n}\n\nfunc (r *Receiver) reopen(issueKey string) (bool, error) {\n\ttransitions, resp, err := r.client.Issue.GetTransitions(issueKey)\n\tif err != nil {\n\t\treturn handleJiraError(resp, err)\n\t}\n\tfor _, t := range transitions {\n\t\tif t.Name == r.conf.ReopenState {\n\t\t\tlog.V(1).Infof(\"reopen: issueKey=%v transitionID=%v\", issueKey, t.ID)\n\t\t\tresp, err = r.client.Issue.DoTransition(issueKey, t.ID)\n\t\t\tif err != nil {\n\t\t\t\treturn handleJiraError(resp, err)\n\t\t\t}\n\t\t\tlog.V(1).Infof(\"  done\")\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn false, fmt.Errorf(\"JIRA state %q does not exist or no transition possible for %s\", r.conf.ReopenState, issueKey)\n}\n\nfunc (r *Receiver) create(issue *jira.Issue) (bool, error) {\n\tlog.V(1).Infof(\"create: issue=%v\", *issue)\n\tissue, resp, err := r.client.Issue.Create(issue)\n\tif err != nil {\n\t\treturn handleJiraError(resp, err)\n\t}\n\n\tlog.V(1).Infof(\"  done: key=%s ID=%s\", issue.Key, issue.ID)\n\treturn false, nil\n}\n\nfunc handleJiraError(resp *jira.Response, err error) (bool, error) {\n\tlog.V(1).Infof(\"handleJiraError: err=%s, req=%s\", err, resp.Request.URL)\n\tif resp != nil && resp.StatusCode\/100 != 2 {\n\t\tretry := resp.StatusCode == 500 || resp.StatusCode == 503\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\t\/\/ go-jira error message is not particularly helpful, replace it\n\t\treturn retry, fmt.Errorf(\"JIRA request %s returned status %s, body %q\", resp.Request.URL, resp.Status, string(body))\n\t}\n\treturn false, err\n}\n<commit_msg>Fix issue #4 nil pointer dereference in log message.<commit_after>package jiralert\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/andygrunwald\/go-jira\"\n\t\"github.com\/free\/jiralert\/alertmanager\"\n\tlog \"github.com\/golang\/glog\"\n\t\"github.com\/trivago\/tgo\/tcontainer\"\n)\n\n\/\/ Receiver wraps a JIRA client corresponding to a specific Alertmanager receiver, with its configuration and templates.\ntype Receiver struct {\n\tconf   *ReceiverConfig\n\ttmpl   *Template\n\tclient *jira.Client\n}\n\n\/\/ NewReceiver creates a Receiver using the provided configuration and template.\nfunc NewReceiver(c *ReceiverConfig, t *Template) (*Receiver, error) {\n\tclient, err := jira.NewClient(http.DefaultClient, c.APIURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient.Authentication.SetBasicAuth(c.User, string(c.Password))\n\n\treturn &Receiver{conf: c, tmpl: t, client: client}, nil\n}\n\n\/\/ Notify implements the Notifier interface.\nfunc (r *Receiver) Notify(data *alertmanager.Data) (bool, error) {\n\tproject := r.tmpl.Execute(r.conf.Project, data)\n\t\/\/ check errors from r.tmpl.Execute()\n\tif r.tmpl.err != nil {\n\t\treturn false, r.tmpl.err\n\t}\n\t\/\/ Looks like an ALERT metric name, with spaces removed.\n\tissueLabel := toIssueLabel(data.GroupLabels)\n\n\tissue, retry, err := r.search(project, issueLabel)\n\tif err != nil {\n\t\treturn retry, err\n\t}\n\n\tif issue != nil {\n\t\t\/\/ The set of JIRA status categories is fixed, this is a safe check to make.\n\t\tif issue.Fields.Status.StatusCategory.Key != \"done\" {\n\t\t\t\/\/ Issue is in a \"to do\" or \"in progress\" state, all done here.\n\t\t\tlog.V(1).Infof(\"Issue %s for %s is unresolved, nothing to do\", issue.Key, issueLabel)\n\t\t\treturn false, nil\n\t\t}\n\t\tif r.conf.WontFixResolution != \"\" && issue.Fields.Resolution.Name == r.conf.WontFixResolution {\n\t\t\t\/\/ Issue is resolved as \"Won't Fix\" or equivalent, log a message just in case.\n\t\t\tlog.Infof(\"Issue %s for %s is resolved as %q, not reopening\", issue.Key, issueLabel, issue.Fields.Resolution.Name)\n\t\t\treturn false, nil\n\t\t}\n\t\tlog.Infof(\"Issue %s for %s was resolved, reopening\", issue.Key, issueLabel)\n\t\treturn r.reopen(issue.Key)\n\t}\n\n\tlog.Infof(\"No issue matching %s found, creating new issue\", issueLabel)\n\tissue = &jira.Issue{\n\t\tFields: &jira.IssueFields{\n\t\t\tProject:     jira.Project{Key: project},\n\t\t\tType:        jira.IssueType{Name: r.tmpl.Execute(r.conf.IssueType, data)},\n\t\t\tDescription: r.tmpl.Execute(r.conf.Description, data),\n\t\t\tSummary:     r.tmpl.Execute(r.conf.Summary, data),\n\t\t\tLabels: []string{\n\t\t\t\tissueLabel,\n\t\t\t},\n\t\t\tUnknowns: tcontainer.NewMarshalMap(),\n\t\t},\n\t}\n\tif r.conf.Priority != \"\" {\n\t\tissue.Fields.Priority = &jira.Priority{Name: r.tmpl.Execute(r.conf.Priority, data)}\n\t}\n\n\t\/\/ Add Components\n\tissue.Fields.Components = make([]*jira.Component, 0, len(r.conf.Components))\n\tfor _, component := range r.conf.Components {\n\t\tissue.Fields.Components = append(issue.Fields.Components, &jira.Component{Name: component})\n\t}\n\n\t\/\/ Add Labels\n\tif r.conf.AddGroupLabels {\n\t\tfor k, v := range data.GroupLabels {\n\t\t\tissue.Fields.Labels = append(issue.Fields.Labels, fmt.Sprintf(\"%s=%q\", k, v))\n\t\t}\n\t}\n\n\tfor key, value := range r.conf.Fields {\n\t\tissue.Fields.Unknowns[key] = r.tmpl.Execute(fmt.Sprint(value), data)\n\t}\n\t\/\/ check errors from r.tmpl.Execute()\n\tif r.tmpl.err != nil {\n\t\treturn false, r.tmpl.err\n\t}\n\tretry, err = r.create(issue)\n\tif err != nil {\n\t\tlog.Infof(\"Issue created: key=%s ID=%s\", issue.Key, issue.ID)\n\t}\n\treturn retry, err\n}\n\n\/\/ toIssueLabel returns the group labels in the form of an ALERT metric name, with all spaces removed.\nfunc toIssueLabel(groupLabels alertmanager.KV) string {\n\tbuf := bytes.NewBufferString(\"ALERT{\")\n\tfor _, p := range groupLabels.SortedPairs() {\n\t\tbuf.WriteString(p.Name)\n\t\tbuf.WriteString(fmt.Sprintf(\"=%q,\", p.Value))\n\t}\n\tbuf.Truncate(buf.Len() - 1)\n\tbuf.WriteString(\"}\")\n\treturn strings.Replace(buf.String(), \" \", \"\", -1)\n}\n\nfunc (r *Receiver) search(project, issueLabel string) (*jira.Issue, bool, error) {\n\tquery := fmt.Sprintf(\"project=%s and labels=%q order by key\", project, issueLabel)\n\toptions := &jira.SearchOptions{\n\t\tFields:     []string{\"summary\", \"status\", \"resolution\"},\n\t\tMaxResults: 50,\n\t}\n\tlog.V(1).Infof(\"search: query=%v options=%+v\", query, options)\n\tissues, resp, err := r.client.Issue.Search(query, options)\n\tif err != nil {\n\t\tretry, err := handleJiraError(\"Issue.Search\", resp, err)\n\t\treturn nil, retry, err\n\t}\n\tif len(issues) > 0 {\n\t\tif len(issues) > 1 {\n\t\t\t\/\/ Swallow it, but log an error.\n\t\t\tlog.Errorf(\"More than one issue matched %s, will only update first: %+v\", query, issues)\n\t\t}\n\t\tlog.V(1).Infof(\"  found: %+v\", issues[0])\n\t\treturn &issues[0], false, nil\n\t}\n\tlog.V(1).Infof(\"  no results\")\n\treturn nil, false, nil\n}\n\nfunc (r *Receiver) reopen(issueKey string) (bool, error) {\n\ttransitions, resp, err := r.client.Issue.GetTransitions(issueKey)\n\tif err != nil {\n\t\treturn handleJiraError(\"Issue.GetTransitions\", resp, err)\n\t}\n\tfor _, t := range transitions {\n\t\tif t.Name == r.conf.ReopenState {\n\t\t\tlog.V(1).Infof(\"reopen: issueKey=%v transitionID=%v\", issueKey, t.ID)\n\t\t\tresp, err = r.client.Issue.DoTransition(issueKey, t.ID)\n\t\t\tif err != nil {\n\t\t\t\treturn handleJiraError(\"Issue.DoTransition\", resp, err)\n\t\t\t}\n\t\t\tlog.V(1).Infof(\"  done\")\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn false, fmt.Errorf(\"JIRA state %q does not exist or no transition possible for %s\", r.conf.ReopenState, issueKey)\n}\n\nfunc (r *Receiver) create(issue *jira.Issue) (bool, error) {\n\tlog.V(1).Infof(\"create: issue=%v\", *issue)\n\tissue, resp, err := r.client.Issue.Create(issue)\n\tif err != nil {\n\t\treturn handleJiraError(\"Issue.Create\", resp, err)\n\t}\n\n\tlog.V(1).Infof(\"  done: key=%s ID=%s\", issue.Key, issue.ID)\n\treturn false, nil\n}\n\nfunc handleJiraError(api string, resp *jira.Response, err error) (bool, error) {\n\tif resp == nil || resp.Request == nil {\n\t\tlog.V(1).Infof(\"handleJiraError: api=%s, err=%s\", api, err)\n\t} else {\n\t\tlog.V(1).Infof(\"handleJiraError: api=%s, url=%s, err=%s\", api, resp.Request.URL, err)\n\t}\n\n\tif resp != nil && resp.StatusCode\/100 != 2 {\n\t\tretry := resp.StatusCode == 500 || resp.StatusCode == 503\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\t\/\/ go-jira error message is not particularly helpful, replace it\n\t\treturn retry, fmt.Errorf(\"JIRA request %s returned status %s, body %q\", resp.Request.URL, resp.Status, string(body))\n\t}\n\treturn false, fmt.Errorf(\"JIRA request %s failed: %s\", api, err)\n}\n<|endoftext|>"}
{"text":"<commit_before>package commands\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/spf13\/cobra\"\n\tjww \"github.com\/spf13\/jwalterweatherman\"\n\n\t\"github.com\/bytom\/api\"\n\t\"github.com\/bytom\/blockchain\/txbuilder\"\n\t\"github.com\/bytom\/protocol\/bc\/types\"\n\t\"github.com\/bytom\/util\"\n)\n\nfunc init() {\n\tbuildTransactionCmd.PersistentFlags().StringVarP(&buildType, \"type\", \"t\", \"\", \"transaction type, valid types: 'issue', 'spend'\")\n\tbuildTransactionCmd.PersistentFlags().StringVarP(&receiverProgram, \"receiver\", \"r\", \"\", \"program of receiver\")\n\tbuildTransactionCmd.PersistentFlags().StringVarP(&address, \"address\", \"a\", \"\", \"address of receiver\")\n\tbuildTransactionCmd.PersistentFlags().StringVarP(&btmGas, \"gas\", \"g\", \"20000000\", \"program of receiver\")\n\tbuildTransactionCmd.PersistentFlags().BoolVar(&pretty, \"pretty\", false, \"pretty print json result\")\n\tbuildTransactionCmd.PersistentFlags().BoolVar(&alias, \"alias\", false, \"use alias build transaction\")\n\n\tsignTransactionCmd.PersistentFlags().StringVarP(&password, \"password\", \"p\", \"\", \"password of the account which sign these transaction(s)\")\n\tsignTransactionCmd.PersistentFlags().BoolVar(&pretty, \"pretty\", false, \"pretty print json result\")\n\n\tsignSubTransactionCmd.PersistentFlags().StringVarP(&password, \"password\", \"p\", \"\", \"password of the account which sign these transaction(s)\")\n\n\tlistTransactionsCmd.PersistentFlags().StringVar(&txID, \"id\", \"\", \"transaction id\")\n\tlistTransactionsCmd.PersistentFlags().StringVar(&account, \"account_id\", \"\", \"account id\")\n\tlistTransactionsCmd.PersistentFlags().BoolVar(&detail, \"detail\", false, \"list transactions details\")\n}\n\nvar (\n\tbuildType       = \"\"\n\tbtmGas          = \"\"\n\treceiverProgram = \"\"\n\taddress         = \"\"\n\tpassword        = \"\"\n\tpretty          = false\n\talias           = false\n\ttxID            = \"\"\n\taccount         = \"\"\n\tdetail          = false\n)\n\nvar buildIssueReqFmt = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"amount\":%s, \"account_id\": \"%s\"},\n\t\t{\"type\": \"issue\", \"asset_id\": \"%s\", \"amount\": %s},\n\t\t{\"type\": \"control_address\", \"asset_id\": \"%s\", \"amount\": %s, \"address\": \"%s\"}\n\t]}`\n\nvar buildIssueReqFmtByAlias = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"BTM\", \"amount\":%s, \"account_alias\": \"%s\"},\n\t\t{\"type\": \"issue\", \"asset_alias\": \"%s\", \"amount\": %s},\n\t\t{\"type\": \"control_address\", \"asset_alias\": \"%s\", \"amount\": %s, \"address\": \"%s\"}\n\t]}`\n\nvar buildSpendReqFmt = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"amount\":%s, \"account_id\": \"%s\"},\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"%s\",\"amount\": %s,\"account_id\": \"%s\"},\n\t\t{\"type\": \"control_receiver\", \"asset_id\": \"%s\", \"amount\": %s, \"receiver\":{\"control_program\": \"%s\",\"expires_at\":\"2017-12-28T12:52:06.78309768+08:00\"}}\n\t]}`\n\nvar buildSpendReqFmtByAlias = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"BTM\", \"amount\":%s, \"account_alias\": \"%s\"},\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"%s\",\"amount\": %s,\"account_alias\": \"%s\"},\n\t\t{\"type\": \"control_receiver\", \"asset_alias\": \"%s\", \"amount\": %s, \"receiver\":{\"control_program\": \"%s\",\"expires_at\":\"2017-12-28T12:52:06.78309768+08:00\"}}\n\t]}`\n\nvar buildRetireReqFmt = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"amount\":%s, \"account_id\": \"%s\"},\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"%s\",\"amount\": %s,\"account_id\": \"%s\"},\n\t\t{\"type\": \"retire\", \"asset_id\": \"%s\",\"amount\": %s,\"account_id\": \"%s\"}\n\t]}`\n\nvar buildRetireReqFmtByAlias = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"BTM\", \"amount\":%s, \"account_alias\": \"%s\"},\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"%s\",\"amount\": %s,\"account_alias\": \"%s\"},\n\t\t{\"type\": \"retire\", \"asset_alias\": \"%s\",\"amount\": %s,\"account_alias\": \"%s\"}\n\t]}`\n\nvar buildControlAddressReqFmt = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"amount\":%s, \"account_id\": \"%s\"},\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"%s\",\"amount\": %s,\"account_id\": \"%s\"},\n\t\t{\"type\": \"control_address\", \"asset_id\": \"%s\", \"amount\": %s,\"address\": \"%s\"}\n\t]}`\n\nvar buildControlAddressReqFmtByAlias = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"BTM\", \"amount\":%s, \"account_alias\": \"%s\"},\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"%s\",\"amount\": %s, \"account_alias\": \"%s\"},\n\t\t{\"type\": \"control_address\", \"asset_alias\": \"%s\", \"amount\": %s,\"address\": \"%s\"}\n\t]}`\n\nvar buildTransactionCmd = &cobra.Command{\n\tUse:   \"build-transaction <accountID|alias> <assetID|alias> <amount>\",\n\tShort: \"Build one transaction template,default use account id and asset id\",\n\tArgs:  cobra.RangeArgs(3, 4),\n\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\tcmd.MarkFlagRequired(\"type\")\n\t\tif buildType == \"spend\" {\n\t\t\tcmd.MarkFlagRequired(\"receiver\")\n\t\t}\n\t},\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tvar buildReqStr string\n\t\taccountInfo := args[0]\n\t\tassetInfo := args[1]\n\t\tamount := args[2]\n\t\tswitch buildType {\n\t\tcase \"issue\":\n\t\t\tif alias {\n\t\t\t\tbuildReqStr = fmt.Sprintf(buildIssueReqFmtByAlias, btmGas, accountInfo, assetInfo, amount, assetInfo, amount, address)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbuildReqStr = fmt.Sprintf(buildIssueReqFmt, btmGas, accountInfo, assetInfo, amount, assetInfo, amount, address)\n\t\tcase \"spend\":\n\t\t\tif alias {\n\t\t\t\tbuildReqStr = fmt.Sprintf(buildSpendReqFmtByAlias, btmGas, accountInfo, assetInfo, amount, accountInfo, assetInfo, amount, receiverProgram)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbuildReqStr = fmt.Sprintf(buildSpendReqFmt, btmGas, accountInfo, assetInfo, amount, accountInfo, assetInfo, amount, receiverProgram)\n\t\tcase \"retire\":\n\t\t\tif alias {\n\t\t\t\tbuildReqStr = fmt.Sprintf(buildRetireReqFmtByAlias, btmGas, accountInfo, assetInfo, amount, accountInfo, assetInfo, amount, accountInfo)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbuildReqStr = fmt.Sprintf(buildRetireReqFmt, btmGas, accountInfo, assetInfo, amount, accountInfo, assetInfo, amount, accountInfo)\n\t\tcase \"address\":\n\t\t\tif alias {\n\t\t\t\tbuildReqStr = fmt.Sprintf(buildControlAddressReqFmtByAlias, btmGas, accountInfo, assetInfo, amount, accountInfo, assetInfo, amount, address)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbuildReqStr = fmt.Sprintf(buildControlAddressReqFmt, btmGas, accountInfo, assetInfo, amount, accountInfo, assetInfo, amount, address)\n\t\tdefault:\n\t\t\tjww.ERROR.Println(\"Invalid transaction template type\")\n\t\t\tos.Exit(util.ErrLocalExe)\n\t\t}\n\n\t\tvar buildReq api.BuildRequest\n\t\tif err := json.Unmarshal([]byte(buildReqStr), &buildReq); err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t\tos.Exit(util.ErrLocalExe)\n\t\t}\n\n\t\tdata, exitCode := util.ClientCall(\"\/build-transaction\", &buildReq)\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\n\t\tif pretty {\n\t\t\tprintJSON(data)\n\t\t\treturn\n\t\t}\n\n\t\tdataMap, ok := data.(map[string]interface{})\n\t\tif ok != true {\n\t\t\tjww.ERROR.Println(\"invalid type assertion\")\n\t\t\tos.Exit(util.ErrLocalParse)\n\t\t}\n\n\t\trawTemplate, err := json.Marshal(dataMap)\n\t\tif err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t\tos.Exit(util.ErrLocalParse)\n\t\t}\n\n\t\tjww.FEEDBACK.Printf(\"Template Type: %s\\n%s\\n\", buildType, string(rawTemplate))\n\t},\n}\n\nvar signTransactionCmd = &cobra.Command{\n\tUse:   \"sign-transaction  <json templates>\",\n\tShort: \"Sign transaction templates with account password\",\n\tArgs:  cobra.ExactArgs(1),\n\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\tcmd.MarkFlagRequired(\"password\")\n\t},\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\ttemplate := txbuilder.Template{}\n\n\t\terr := json.Unmarshal([]byte(args[0]), &template)\n\t\tif err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t\tos.Exit(util.ErrLocalExe)\n\t\t}\n\n\t\tvar req = struct {\n\t\t\tPassword string             `json:\"password\"`\n\t\t\tTxs      txbuilder.Template `json:\"transaction\"`\n\t\t}{Password: password, Txs: template}\n\n\t\tjww.FEEDBACK.Printf(\"\\n\\n\")\n\t\tdata, exitCode := util.ClientCall(\"\/sign-transaction\", &req)\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\n\t\tif pretty {\n\t\t\tprintJSON(data)\n\t\t\treturn\n\t\t}\n\n\t\tdataMap, ok := data.(map[string]interface{})\n\t\tif ok != true {\n\t\t\tjww.ERROR.Println(\"invalid type assertion\")\n\t\t\tos.Exit(util.ErrLocalParse)\n\t\t}\n\n\t\trawSign, err := json.Marshal(dataMap)\n\t\tif err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t\tos.Exit(util.ErrLocalParse)\n\t\t}\n\t\tjww.FEEDBACK.Printf(\"\\nSign Template:\\n%s\\n\", string(rawSign))\n\t},\n}\n\nvar submitTransactionCmd = &cobra.Command{\n\tUse:   \"submit-transaction  <signed json raw_transaction>\",\n\tShort: \"Submit signed transaction template\",\n\tArgs:  cobra.ExactArgs(1),\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tvar ins = struct {\n\t\t\tTx types.Tx `json:\"raw_transaction\"`\n\t\t}{}\n\n\t\terr := json.Unmarshal([]byte(args[0]), &ins)\n\t\tif err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t\tos.Exit(util.ErrLocalExe)\n\t\t}\n\n\t\tdata, exitCode := util.ClientCall(\"\/submit-transaction\", &ins)\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\n\t\tprintJSON(data)\n\t},\n}\n\nvar signSubTransactionCmd = &cobra.Command{\n\tUse:   \"sign-submit-transaction  <json templates>\",\n\tShort: \"Sign and Submit transaction templates with account password\",\n\tArgs:  cobra.ExactArgs(1),\n\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\tcmd.MarkFlagRequired(\"password\")\n\t},\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\ttemplate := txbuilder.Template{}\n\n\t\terr := json.Unmarshal([]byte(args[0]), &template)\n\t\tif err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t\tos.Exit(util.ErrLocalExe)\n\t\t}\n\n\t\tvar req = struct {\n\t\t\tPassword string           `json:\"password\"`\n\t\t\tTxs      txbuilder.Template `json:\"transaction\"`\n\t\t}{Password: password, Txs: template}\n\n\t\tjww.FEEDBACK.Printf(\"\\n\\n\")\n\t\tdata, exitCode := util.ClientCall(\"\/sign-submit-transaction\", &req)\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\n\t\tprintJSON(data)\n\t},\n}\n\nvar getTransactionCmd = &cobra.Command{\n\tUse:   \"get-transaction <hash>\",\n\tShort: \"get the transaction by matching the given transaction hash\",\n\tArgs:  cobra.ExactArgs(1),\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\ttxInfo := &struct {\n\t\t\tTxID string `json:\"tx_id\"`\n\t\t}{TxID: args[0]}\n\n\t\tdata, exitCode := util.ClientCall(\"\/get-transaction\", txInfo)\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\n\t\tprintJSON(data)\n\t},\n}\n\nvar listTransactionsCmd = &cobra.Command{\n\tUse:   \"list-transactions\",\n\tShort: \"List the transactions\",\n\tArgs:  cobra.NoArgs,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tfilter := struct {\n\t\t\tID        string `json:\"id\"`\n\t\t\tAccountID string `json:\"account_id\"`\n\t\t\tDetail    bool   `json:\"detail\"`\n\t\t}{ID: txID, AccountID: account, Detail: detail}\n\n\t\tdata, exitCode := util.ClientCall(\"\/list-transactions\", &filter)\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\n\t\tprintJSONList(data)\n\t},\n}\n\nvar gasRateCmd = &cobra.Command{\n\tUse:   \"gas-rate\",\n\tShort: \"Print the current gas rate\",\n\tArgs:  cobra.NoArgs,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tdata, exitCode := util.ClientCall(\"\/gas-rate\")\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\t\tprintJSON(data)\n\t},\n}\n<commit_msg>fix usage of build-transaction<commit_after>package commands\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/spf13\/cobra\"\n\tjww \"github.com\/spf13\/jwalterweatherman\"\n\n\t\"github.com\/bytom\/api\"\n\t\"github.com\/bytom\/blockchain\/txbuilder\"\n\t\"github.com\/bytom\/protocol\/bc\/types\"\n\t\"github.com\/bytom\/util\"\n)\n\nfunc init() {\n\tbuildTransactionCmd.PersistentFlags().StringVarP(&buildType, \"type\", \"t\", \"\", \"transaction type, valid types: 'issue', 'spend'\")\n\tbuildTransactionCmd.PersistentFlags().StringVarP(&receiverProgram, \"receiver\", \"r\", \"\", \"program of receiver\")\n\tbuildTransactionCmd.PersistentFlags().StringVarP(&address, \"address\", \"a\", \"\", \"address of receiver\")\n\tbuildTransactionCmd.PersistentFlags().StringVarP(&btmGas, \"gas\", \"g\", \"20000000\", \"gas of this transaction\")\n\tbuildTransactionCmd.PersistentFlags().BoolVar(&pretty, \"pretty\", false, \"pretty print json result\")\n\tbuildTransactionCmd.PersistentFlags().BoolVar(&alias, \"alias\", false, \"use alias build transaction\")\n\n\tsignTransactionCmd.PersistentFlags().StringVarP(&password, \"password\", \"p\", \"\", \"password of the account which sign these transaction(s)\")\n\tsignTransactionCmd.PersistentFlags().BoolVar(&pretty, \"pretty\", false, \"pretty print json result\")\n\n\tsignSubTransactionCmd.PersistentFlags().StringVarP(&password, \"password\", \"p\", \"\", \"password of the account which sign these transaction(s)\")\n\n\tlistTransactionsCmd.PersistentFlags().StringVar(&txID, \"id\", \"\", \"transaction id\")\n\tlistTransactionsCmd.PersistentFlags().StringVar(&account, \"account_id\", \"\", \"account id\")\n\tlistTransactionsCmd.PersistentFlags().BoolVar(&detail, \"detail\", false, \"list transactions details\")\n}\n\nvar (\n\tbuildType       = \"\"\n\tbtmGas          = \"\"\n\treceiverProgram = \"\"\n\taddress         = \"\"\n\tpassword        = \"\"\n\tpretty          = false\n\talias           = false\n\ttxID            = \"\"\n\taccount         = \"\"\n\tdetail          = false\n)\n\nvar buildIssueReqFmt = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"amount\":%s, \"account_id\": \"%s\"},\n\t\t{\"type\": \"issue\", \"asset_id\": \"%s\", \"amount\": %s},\n\t\t{\"type\": \"control_address\", \"asset_id\": \"%s\", \"amount\": %s, \"address\": \"%s\"}\n\t]}`\n\nvar buildIssueReqFmtByAlias = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"BTM\", \"amount\":%s, \"account_alias\": \"%s\"},\n\t\t{\"type\": \"issue\", \"asset_alias\": \"%s\", \"amount\": %s},\n\t\t{\"type\": \"control_address\", \"asset_alias\": \"%s\", \"amount\": %s, \"address\": \"%s\"}\n\t]}`\n\nvar buildSpendReqFmt = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"amount\":%s, \"account_id\": \"%s\"},\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"%s\",\"amount\": %s,\"account_id\": \"%s\"},\n\t\t{\"type\": \"control_receiver\", \"asset_id\": \"%s\", \"amount\": %s, \"receiver\":{\"control_program\": \"%s\",\"expires_at\":\"2017-12-28T12:52:06.78309768+08:00\"}}\n\t]}`\n\nvar buildSpendReqFmtByAlias = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"BTM\", \"amount\":%s, \"account_alias\": \"%s\"},\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"%s\",\"amount\": %s,\"account_alias\": \"%s\"},\n\t\t{\"type\": \"control_receiver\", \"asset_alias\": \"%s\", \"amount\": %s, \"receiver\":{\"control_program\": \"%s\",\"expires_at\":\"2017-12-28T12:52:06.78309768+08:00\"}}\n\t]}`\n\nvar buildRetireReqFmt = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"amount\":%s, \"account_id\": \"%s\"},\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"%s\",\"amount\": %s,\"account_id\": \"%s\"},\n\t\t{\"type\": \"retire\", \"asset_id\": \"%s\",\"amount\": %s,\"account_id\": \"%s\"}\n\t]}`\n\nvar buildRetireReqFmtByAlias = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"BTM\", \"amount\":%s, \"account_alias\": \"%s\"},\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"%s\",\"amount\": %s,\"account_alias\": \"%s\"},\n\t\t{\"type\": \"retire\", \"asset_alias\": \"%s\",\"amount\": %s,\"account_alias\": \"%s\"}\n\t]}`\n\nvar buildControlAddressReqFmt = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\", \"amount\":%s, \"account_id\": \"%s\"},\n\t\t{\"type\": \"spend_account\", \"asset_id\": \"%s\",\"amount\": %s,\"account_id\": \"%s\"},\n\t\t{\"type\": \"control_address\", \"asset_id\": \"%s\", \"amount\": %s,\"address\": \"%s\"}\n\t]}`\n\nvar buildControlAddressReqFmtByAlias = `\n\t{\"actions\": [\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"BTM\", \"amount\":%s, \"account_alias\": \"%s\"},\n\t\t{\"type\": \"spend_account\", \"asset_alias\": \"%s\",\"amount\": %s, \"account_alias\": \"%s\"},\n\t\t{\"type\": \"control_address\", \"asset_alias\": \"%s\", \"amount\": %s,\"address\": \"%s\"}\n\t]}`\n\nvar buildTransactionCmd = &cobra.Command{\n\tUse:   \"build-transaction <accountID|alias> <assetID|alias> <amount>\",\n\tShort: \"Build one transaction template,default use account id and asset id\",\n\tArgs:  cobra.RangeArgs(3, 4),\n\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\tcmd.MarkFlagRequired(\"type\")\n\t\tif buildType == \"spend\" {\n\t\t\tcmd.MarkFlagRequired(\"receiver\")\n\t\t}\n\t},\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tvar buildReqStr string\n\t\taccountInfo := args[0]\n\t\tassetInfo := args[1]\n\t\tamount := args[2]\n\t\tswitch buildType {\n\t\tcase \"issue\":\n\t\t\tif alias {\n\t\t\t\tbuildReqStr = fmt.Sprintf(buildIssueReqFmtByAlias, btmGas, accountInfo, assetInfo, amount, assetInfo, amount, address)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbuildReqStr = fmt.Sprintf(buildIssueReqFmt, btmGas, accountInfo, assetInfo, amount, assetInfo, amount, address)\n\t\tcase \"spend\":\n\t\t\tif alias {\n\t\t\t\tbuildReqStr = fmt.Sprintf(buildSpendReqFmtByAlias, btmGas, accountInfo, assetInfo, amount, accountInfo, assetInfo, amount, receiverProgram)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbuildReqStr = fmt.Sprintf(buildSpendReqFmt, btmGas, accountInfo, assetInfo, amount, accountInfo, assetInfo, amount, receiverProgram)\n\t\tcase \"retire\":\n\t\t\tif alias {\n\t\t\t\tbuildReqStr = fmt.Sprintf(buildRetireReqFmtByAlias, btmGas, accountInfo, assetInfo, amount, accountInfo, assetInfo, amount, accountInfo)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbuildReqStr = fmt.Sprintf(buildRetireReqFmt, btmGas, accountInfo, assetInfo, amount, accountInfo, assetInfo, amount, accountInfo)\n\t\tcase \"address\":\n\t\t\tif alias {\n\t\t\t\tbuildReqStr = fmt.Sprintf(buildControlAddressReqFmtByAlias, btmGas, accountInfo, assetInfo, amount, accountInfo, assetInfo, amount, address)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbuildReqStr = fmt.Sprintf(buildControlAddressReqFmt, btmGas, accountInfo, assetInfo, amount, accountInfo, assetInfo, amount, address)\n\t\tdefault:\n\t\t\tjww.ERROR.Println(\"Invalid transaction template type\")\n\t\t\tos.Exit(util.ErrLocalExe)\n\t\t}\n\n\t\tvar buildReq api.BuildRequest\n\t\tif err := json.Unmarshal([]byte(buildReqStr), &buildReq); err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t\tos.Exit(util.ErrLocalExe)\n\t\t}\n\n\t\tdata, exitCode := util.ClientCall(\"\/build-transaction\", &buildReq)\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\n\t\tif pretty {\n\t\t\tprintJSON(data)\n\t\t\treturn\n\t\t}\n\n\t\tdataMap, ok := data.(map[string]interface{})\n\t\tif ok != true {\n\t\t\tjww.ERROR.Println(\"invalid type assertion\")\n\t\t\tos.Exit(util.ErrLocalParse)\n\t\t}\n\n\t\trawTemplate, err := json.Marshal(dataMap)\n\t\tif err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t\tos.Exit(util.ErrLocalParse)\n\t\t}\n\n\t\tjww.FEEDBACK.Printf(\"Template Type: %s\\n%s\\n\", buildType, string(rawTemplate))\n\t},\n}\n\nvar signTransactionCmd = &cobra.Command{\n\tUse:   \"sign-transaction  <json templates>\",\n\tShort: \"Sign transaction templates with account password\",\n\tArgs:  cobra.ExactArgs(1),\n\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\tcmd.MarkFlagRequired(\"password\")\n\t},\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\ttemplate := txbuilder.Template{}\n\n\t\terr := json.Unmarshal([]byte(args[0]), &template)\n\t\tif err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t\tos.Exit(util.ErrLocalExe)\n\t\t}\n\n\t\tvar req = struct {\n\t\t\tPassword string             `json:\"password\"`\n\t\t\tTxs      txbuilder.Template `json:\"transaction\"`\n\t\t}{Password: password, Txs: template}\n\n\t\tjww.FEEDBACK.Printf(\"\\n\\n\")\n\t\tdata, exitCode := util.ClientCall(\"\/sign-transaction\", &req)\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\n\t\tif pretty {\n\t\t\tprintJSON(data)\n\t\t\treturn\n\t\t}\n\n\t\tdataMap, ok := data.(map[string]interface{})\n\t\tif ok != true {\n\t\t\tjww.ERROR.Println(\"invalid type assertion\")\n\t\t\tos.Exit(util.ErrLocalParse)\n\t\t}\n\n\t\trawSign, err := json.Marshal(dataMap)\n\t\tif err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t\tos.Exit(util.ErrLocalParse)\n\t\t}\n\t\tjww.FEEDBACK.Printf(\"\\nSign Template:\\n%s\\n\", string(rawSign))\n\t},\n}\n\nvar submitTransactionCmd = &cobra.Command{\n\tUse:   \"submit-transaction  <signed json raw_transaction>\",\n\tShort: \"Submit signed transaction template\",\n\tArgs:  cobra.ExactArgs(1),\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tvar ins = struct {\n\t\t\tTx types.Tx `json:\"raw_transaction\"`\n\t\t}{}\n\n\t\terr := json.Unmarshal([]byte(args[0]), &ins)\n\t\tif err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t\tos.Exit(util.ErrLocalExe)\n\t\t}\n\n\t\tdata, exitCode := util.ClientCall(\"\/submit-transaction\", &ins)\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\n\t\tprintJSON(data)\n\t},\n}\n\nvar signSubTransactionCmd = &cobra.Command{\n\tUse:   \"sign-submit-transaction  <json templates>\",\n\tShort: \"Sign and Submit transaction templates with account password\",\n\tArgs:  cobra.ExactArgs(1),\n\tPreRun: func(cmd *cobra.Command, args []string) {\n\t\tcmd.MarkFlagRequired(\"password\")\n\t},\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\ttemplate := txbuilder.Template{}\n\n\t\terr := json.Unmarshal([]byte(args[0]), &template)\n\t\tif err != nil {\n\t\t\tjww.ERROR.Println(err)\n\t\t\tos.Exit(util.ErrLocalExe)\n\t\t}\n\n\t\tvar req = struct {\n\t\t\tPassword string           `json:\"password\"`\n\t\t\tTxs      txbuilder.Template `json:\"transaction\"`\n\t\t}{Password: password, Txs: template}\n\n\t\tjww.FEEDBACK.Printf(\"\\n\\n\")\n\t\tdata, exitCode := util.ClientCall(\"\/sign-submit-transaction\", &req)\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\n\t\tprintJSON(data)\n\t},\n}\n\nvar getTransactionCmd = &cobra.Command{\n\tUse:   \"get-transaction <hash>\",\n\tShort: \"get the transaction by matching the given transaction hash\",\n\tArgs:  cobra.ExactArgs(1),\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\ttxInfo := &struct {\n\t\t\tTxID string `json:\"tx_id\"`\n\t\t}{TxID: args[0]}\n\n\t\tdata, exitCode := util.ClientCall(\"\/get-transaction\", txInfo)\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\n\t\tprintJSON(data)\n\t},\n}\n\nvar listTransactionsCmd = &cobra.Command{\n\tUse:   \"list-transactions\",\n\tShort: \"List the transactions\",\n\tArgs:  cobra.NoArgs,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tfilter := struct {\n\t\t\tID        string `json:\"id\"`\n\t\t\tAccountID string `json:\"account_id\"`\n\t\t\tDetail    bool   `json:\"detail\"`\n\t\t}{ID: txID, AccountID: account, Detail: detail}\n\n\t\tdata, exitCode := util.ClientCall(\"\/list-transactions\", &filter)\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\n\t\tprintJSONList(data)\n\t},\n}\n\nvar gasRateCmd = &cobra.Command{\n\tUse:   \"gas-rate\",\n\tShort: \"Print the current gas rate\",\n\tArgs:  cobra.NoArgs,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tdata, exitCode := util.ClientCall(\"\/gas-rate\")\n\t\tif exitCode != util.Success {\n\t\t\tos.Exit(exitCode)\n\t\t}\n\t\tprintJSON(data)\n\t},\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/fission\/fission-workflows\/cmd\/fission-workflows-bundle\/bundle\"\n\t\"github.com\/fission\/fission-workflows\/pkg\/fes\/backend\/nats\"\n\t\"github.com\/fission\/fission-workflows\/pkg\/util\"\n\tnatsio \"github.com\/nats-io\/go-nats\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"github.com\/urfave\/cli\"\n)\n\nfunc main() {\n\tctx := context.Background()\n\n\tcliApp := createCli()\n\tcliApp.Action = func(c *cli.Context) error {\n\t\tsetupLogging(c)\n\n\t\treturn bundle.Run(ctx, &bundle.Options{\n\t\t\tNats:                 parseNatsOptions(c),\n\t\t\tFission:              parseFissionOptions(c),\n\t\t\tInternalRuntime:      c.Bool(\"internal\"),\n\t\t\tInvocationController: c.Bool(\"controller\") || c.Bool(\"invocation-controller\"),\n\t\t\tWorkflowController:   c.Bool(\"controller\") || c.Bool(\"workflow-controller\"),\n\t\t\tAdminAPI:             c.Bool(\"api\") || c.Bool(\"api-admin\"),\n\t\t\tWorkflowAPI:          c.Bool(\"api\") || c.Bool(\"api-workflow\"),\n\t\t\tInvocationAPI:        c.Bool(\"api\") || c.Bool(\"api-workflow-invocation\"),\n\t\t\tHTTPGateway:          c.Bool(\"api\") || c.Bool(\"api-http\"),\n\t\t\tMetrics:              c.Bool(\"metrics\") || c.Bool(\"metrics\"),\n\t\t})\n\t}\n\tcliApp.Run(os.Args)\n}\n\nfunc setupLogging(c *cli.Context) {\n\tif c.Bool(\"debug\") {\n\t\tlogrus.SetLevel(logrus.DebugLevel)\n\t} else {\n\t\tlogrus.SetLevel(logrus.InfoLevel)\n\t}\n}\n\nfunc parseFissionOptions(c *cli.Context) *bundle.FissionOptions {\n\tif !c.Bool(\"fission\") {\n\t\treturn nil\n\t}\n\n\treturn &bundle.FissionOptions{\n\t\tExecutorAddress: c.String(\"fission-executor\"),\n\t\tControllerAddr:  c.String(\"fission-controller\"),\n\t\tRouterAddr:      c.String(\"fission-router\"),\n\t}\n}\n\nfunc parseNatsOptions(c *cli.Context) *nats.Config {\n\tif !c.Bool(\"nats\") {\n\t\treturn nil\n\t}\n\n\tclient := c.String(\"nats-client\")\n\tif client == \"\" {\n\t\tclient = fmt.Sprintf(\"workflow-bundle-%s\", util.UID())\n\t}\n\n\treturn &nats.Config{\n\t\tURL:     c.String(\"nats-url\"),\n\t\tCluster: c.String(\"nats-cluster\"),\n\t\tClient:  client,\n\t}\n}\n\nfunc createCli() *cli.App {\n\n\tcliApp := cli.NewApp()\n\n\tcliApp.Flags = []cli.Flag{\n\t\t\/\/ Generic\n\t\tcli.BoolFlag{\n\t\t\tName:   \"d, debug\",\n\t\t\tEnvVar: \"WORKFLOW_DEBUG\",\n\t\t},\n\n\t\t\/\/ NATS\n\t\tcli.StringFlag{\n\t\t\tName:   \"nats-url\",\n\t\t\tUsage:  \"URL to the data store used by the NATS event store.\",\n\t\t\tValue:  natsio.DefaultURL, \/\/ http:\/\/nats-streaming.fission\n\t\t\tEnvVar: \"ES_NATS_URL\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"nats-cluster\",\n\t\t\tUsage:  \"Cluster name used for the NATS event store (if needed)\",\n\t\t\tValue:  \"test-cluster\", \/\/ mqtrigger\n\t\t\tEnvVar: \"ES_NATS_CLUSTER\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"nats-client\",\n\t\t\tUsage:  \"Client name used for the NATS event store. By default it will generate a unique clientID.\",\n\t\t\tEnvVar: \"ES_NATS_CLIENT\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"nats\",\n\t\t\tUsage: \"Use NATS as the event store\",\n\t\t},\n\n\t\t\/\/ Fission\n\t\tcli.BoolFlag{\n\t\t\tName:  \"fission\",\n\t\t\tUsage: \"Use Fission as a function environment\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"fission-executor\",\n\t\t\tUsage:  \"Address of the Fission executor to optimize executions\",\n\t\t\tValue:  \"http:\/\/executor.fission\",\n\t\t\tEnvVar: \"FNENV_FISSION_EXECUTOR\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"fission-controller\",\n\t\t\tUsage:  \"Address of the Fission controller for resolving functions\",\n\t\t\tValue:  \"http:\/\/controller.fission\",\n\t\t\tEnvVar: \"FNENV_FISSION_CONTROLLER\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"fission-router\",\n\t\t\tUsage:  \"Address of the Fission router for executing functions\",\n\t\t\tValue:  \"http:\/\/router.fission\",\n\t\t\tEnvVar: \"FNENV_FISSION_ROUTER\",\n\t\t},\n\n\t\t\/\/ Components\n\t\tcli.BoolFlag{\n\t\t\tName:  \"internal\",\n\t\t\tUsage: \"Use internal function runtime\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"controller\",\n\t\t\tUsage: \"Run the controller with all components\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"workflow-controller\",\n\t\t\tUsage: \"Run the workflow controller\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"invocation-controller\",\n\t\t\tUsage: \"Run the invocation controller\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"api-http\",\n\t\t\tUsage: \"Serve the http apis of the apis\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"api-workflow-invocation\",\n\t\t\tUsage: \"Serve the workflow invocation gRPC api\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"api-workflow\",\n\t\t\tUsage: \"Serve the workflow gRPC api\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"api-admin\",\n\t\t\tUsage: \"Serve the admin gRPC api\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"metrics\",\n\t\t\tUsage: \"Serve prometheus metrics\",\n\t\t},\n\t}\n\n\treturn cliApp\n}\n<commit_msg>Handle system termination signals (#152)<commit_after>package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/fission\/fission-workflows\/cmd\/fission-workflows-bundle\/bundle\"\n\t\"github.com\/fission\/fission-workflows\/pkg\/fes\/backend\/nats\"\n\t\"github.com\/fission\/fission-workflows\/pkg\/util\"\n\tnatsio \"github.com\/nats-io\/go-nats\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"github.com\/urfave\/cli\"\n)\n\nfunc main() {\n\tctx, cancelFn := context.WithCancel(context.Background())\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt, os.Kill, syscall.SIGTERM)\n\tgo func() {\n\t\tfor sig := range c {\n\t\t\tfmt.Println(\"Received signal: \", sig)\n\t\t\tgo func() {\n\t\t\t\ttime.Sleep(30 * time.Second)\n\t\t\t\tfmt.Println(\"Deadline exceeded; forcing shutdown.\")\n\t\t\t\tos.Exit(0)\n\t\t\t}()\n\t\t\tcancelFn()\n\t\t\tbreak\n\t\t}\n\t}()\n\n\tcliApp := createCli()\n\tcliApp.Action = func(c *cli.Context) error {\n\t\tsetupLogging(c)\n\n\t\treturn bundle.Run(ctx, &bundle.Options{\n\t\t\tNats:                 parseNatsOptions(c),\n\t\t\tFission:              parseFissionOptions(c),\n\t\t\tInternalRuntime:      c.Bool(\"internal\"),\n\t\t\tInvocationController: c.Bool(\"controller\") || c.Bool(\"invocation-controller\"),\n\t\t\tWorkflowController:   c.Bool(\"controller\") || c.Bool(\"workflow-controller\"),\n\t\t\tAdminAPI:             c.Bool(\"api\") || c.Bool(\"api-admin\"),\n\t\t\tWorkflowAPI:          c.Bool(\"api\") || c.Bool(\"api-workflow\"),\n\t\t\tInvocationAPI:        c.Bool(\"api\") || c.Bool(\"api-workflow-invocation\"),\n\t\t\tHTTPGateway:          c.Bool(\"api\") || c.Bool(\"api-http\"),\n\t\t\tMetrics:              c.Bool(\"metrics\") || c.Bool(\"metrics\"),\n\t\t})\n\t}\n\tcliApp.Run(os.Args)\n}\n\nfunc setupLogging(c *cli.Context) {\n\tif c.Bool(\"debug\") {\n\t\tlogrus.SetLevel(logrus.DebugLevel)\n\t} else {\n\t\tlogrus.SetLevel(logrus.InfoLevel)\n\t}\n}\n\nfunc parseFissionOptions(c *cli.Context) *bundle.FissionOptions {\n\tif !c.Bool(\"fission\") {\n\t\treturn nil\n\t}\n\n\treturn &bundle.FissionOptions{\n\t\tExecutorAddress: c.String(\"fission-executor\"),\n\t\tControllerAddr:  c.String(\"fission-controller\"),\n\t\tRouterAddr:      c.String(\"fission-router\"),\n\t}\n}\n\nfunc parseNatsOptions(c *cli.Context) *nats.Config {\n\tif !c.Bool(\"nats\") {\n\t\treturn nil\n\t}\n\n\tclient := c.String(\"nats-client\")\n\tif client == \"\" {\n\t\tclient = fmt.Sprintf(\"workflow-bundle-%s\", util.UID())\n\t}\n\n\treturn &nats.Config{\n\t\tURL:     c.String(\"nats-url\"),\n\t\tCluster: c.String(\"nats-cluster\"),\n\t\tClient:  client,\n\t}\n}\n\nfunc createCli() *cli.App {\n\n\tcliApp := cli.NewApp()\n\n\tcliApp.Flags = []cli.Flag{\n\t\t\/\/ Generic\n\t\tcli.BoolFlag{\n\t\t\tName:   \"d, debug\",\n\t\t\tEnvVar: \"WORKFLOW_DEBUG\",\n\t\t},\n\n\t\t\/\/ NATS\n\t\tcli.StringFlag{\n\t\t\tName:   \"nats-url\",\n\t\t\tUsage:  \"URL to the data store used by the NATS event store.\",\n\t\t\tValue:  natsio.DefaultURL, \/\/ http:\/\/nats-streaming.fission\n\t\t\tEnvVar: \"ES_NATS_URL\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"nats-cluster\",\n\t\t\tUsage:  \"Cluster name used for the NATS event store (if needed)\",\n\t\t\tValue:  \"test-cluster\", \/\/ mqtrigger\n\t\t\tEnvVar: \"ES_NATS_CLUSTER\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"nats-client\",\n\t\t\tUsage:  \"Client name used for the NATS event store. By default it will generate a unique clientID.\",\n\t\t\tEnvVar: \"ES_NATS_CLIENT\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"nats\",\n\t\t\tUsage: \"Use NATS as the event store\",\n\t\t},\n\n\t\t\/\/ Fission\n\t\tcli.BoolFlag{\n\t\t\tName:  \"fission\",\n\t\t\tUsage: \"Use Fission as a function environment\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"fission-executor\",\n\t\t\tUsage:  \"Address of the Fission executor to optimize executions\",\n\t\t\tValue:  \"http:\/\/executor.fission\",\n\t\t\tEnvVar: \"FNENV_FISSION_EXECUTOR\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"fission-controller\",\n\t\t\tUsage:  \"Address of the Fission controller for resolving functions\",\n\t\t\tValue:  \"http:\/\/controller.fission\",\n\t\t\tEnvVar: \"FNENV_FISSION_CONTROLLER\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"fission-router\",\n\t\t\tUsage:  \"Address of the Fission router for executing functions\",\n\t\t\tValue:  \"http:\/\/router.fission\",\n\t\t\tEnvVar: \"FNENV_FISSION_ROUTER\",\n\t\t},\n\n\t\t\/\/ Components\n\t\tcli.BoolFlag{\n\t\t\tName:  \"internal\",\n\t\t\tUsage: \"Use internal function runtime\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"controller\",\n\t\t\tUsage: \"Run the controller with all components\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"workflow-controller\",\n\t\t\tUsage: \"Run the workflow controller\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"invocation-controller\",\n\t\t\tUsage: \"Run the invocation controller\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"api-http\",\n\t\t\tUsage: \"Serve the http apis of the apis\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"api-workflow-invocation\",\n\t\t\tUsage: \"Serve the workflow invocation gRPC api\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"api-workflow\",\n\t\t\tUsage: \"Serve the workflow gRPC api\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"api-admin\",\n\t\t\tUsage: \"Serve the admin gRPC api\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"metrics\",\n\t\t\tUsage: \"Serve prometheus metrics\",\n\t\t},\n\t}\n\n\treturn cliApp\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage alpha\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/cobra\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/version\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/cmd\/options\"\n\tcmdutil \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/cmd\/util\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/constants\"\n\tkubeletphase \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/phases\/kubelet\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/preflight\"\n\tkubeconfigutil \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/util\/kubeconfig\"\n\tutilsexec \"k8s.io\/utils\/exec\"\n)\n\nvar (\n\tkubeletConfigDownloadLongDesc = cmdutil.LongDesc(`\n\t\tDownload the kubelet configuration from a ConfigMap of the form \"kubelet-config-1.X\" in the cluster,\n\t\twhere X is the minor version of the kubelet. Either kubeadm autodetects the kubelet version by exec-ing\n\t\t\"kubelet --version\" or respects the --kubelet-version parameter.\n\t\t` + cmdutil.AlphaDisclaimer)\n\n\tkubeletConfigDownloadExample = cmdutil.Examples(fmt.Sprintf(`\n\t\t# Download the kubelet configuration from the ConfigMap in the cluster. Autodetect the kubelet version.\n\t\tkubeadm alpha phase kubelet config download\n\n\t\t# Download the kubelet configuration from the ConfigMap in the cluster. Use a specific desired kubelet version.\n\t\tkubeadm alpha phase kubelet config download --kubelet-version %s\n\t\t`, constants.CurrentKubernetesVersion))\n\n\tkubeletConfigEnableDynamicLongDesc = cmdutil.LongDesc(`\n\t\tEnable or update dynamic kubelet configuration for a Node, against the kubelet-config-1.X ConfigMap in the cluster,\n\t\twhere X is the minor version of the desired kubelet version.\n\n\t\tWARNING: This feature is still experimental, and disabled by default. Enable only if you know what you are doing, as it\n\t\tmay have surprising side-effects at this stage.\n\n\t\t` + cmdutil.AlphaDisclaimer)\n\n\tkubeletConfigEnableDynamicExample = cmdutil.Examples(fmt.Sprintf(`\n\t\t# Enable dynamic kubelet configuration for a Node.\n\t\tkubeadm alpha phase kubelet enable-dynamic-config --node-name node-1 --kubelet-version %s\n\n\t\tWARNING: This feature is still experimental, and disabled by default. Enable only if you know what you are doing, as it\n\t\tmay have surprising side-effects at this stage.\n\t\t`, constants.CurrentKubernetesVersion))\n)\n\n\/\/ newCmdKubeletUtility returns command for `kubeadm phase kubelet`\nfunc newCmdKubeletUtility() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"kubelet\",\n\t\tShort: \"Commands related to handling the kubelet\",\n\t\tLong:  cmdutil.MacroCommandLongDescription,\n\t}\n\n\tcmd.AddCommand(newCmdKubeletConfig())\n\treturn cmd\n}\n\n\/\/ newCmdKubeletConfig returns command for `kubeadm phase kubelet config`\nfunc newCmdKubeletConfig() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"config\",\n\t\tShort: \"Utilities for kubelet configuration\",\n\t\tLong:  cmdutil.MacroCommandLongDescription,\n\t}\n\n\tcmd.AddCommand(newCmdKubeletConfigDownload())\n\tcmd.AddCommand(newCmdKubeletConfigEnableDynamic())\n\treturn cmd\n}\n\n\/\/ newCmdKubeletConfigDownload calls cobra.Command for downloading the kubelet configuration from the kubelet-config-1.X ConfigMap in the cluster\nfunc newCmdKubeletConfigDownload() *cobra.Command {\n\tvar kubeletVersionStr string\n\t\/\/ TODO: Be smarter about this and be able to load multiple kubeconfig files in different orders of precedence\n\tkubeConfigFile := constants.GetKubeletKubeConfigPath()\n\n\tcmd := &cobra.Command{\n\t\tUse:     \"download\",\n\t\tShort:   \"Download the kubelet configuration from the cluster ConfigMap kubelet-config-1.X, where X is the minor version of the kubelet\",\n\t\tLong:    kubeletConfigDownloadLongDesc,\n\t\tExample: kubeletConfigDownloadExample,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tkubeletVersion, err := getKubeletVersion(kubeletVersionStr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tclient, err := kubeconfigutil.ClientSetFromFile(kubeConfigFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn kubeletphase.DownloadConfig(client, kubeletVersion, constants.KubeletRunDirectory)\n\t\t},\n\t}\n\n\toptions.AddKubeConfigFlag(cmd.Flags(), &kubeConfigFile)\n\tcmd.Flags().StringVar(&kubeletVersionStr, \"kubelet-version\", kubeletVersionStr, \"The desired version for the kubelet. Defaults to being autodetected from 'kubelet --version'.\")\n\treturn cmd\n}\n\nfunc getKubeletVersion(kubeletVersionStr string) (*version.Version, error) {\n\tif len(kubeletVersionStr) > 0 {\n\t\treturn version.ParseSemantic(kubeletVersionStr)\n\t}\n\treturn preflight.GetKubeletVersion(utilsexec.New())\n}\n\n\/\/ newCmdKubeletConfigEnableDynamic calls cobra.Command for enabling dynamic kubelet configuration on node\n\/\/ This feature is still in alpha and an experimental state\nfunc newCmdKubeletConfigEnableDynamic() *cobra.Command {\n\tvar nodeName, kubeletVersionStr string\n\tvar kubeConfigFile string\n\n\tcmd := &cobra.Command{\n\t\tUse:     \"enable-dynamic\",\n\t\tShort:   \"EXPERIMENTAL: Enable or update dynamic kubelet configuration for a Node\",\n\t\tLong:    kubeletConfigEnableDynamicLongDesc,\n\t\tExample: kubeletConfigEnableDynamicExample,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif len(nodeName) == 0 {\n\t\t\t\treturn errors.New(\"the --node-name argument is required\")\n\t\t\t}\n\t\t\tif len(kubeletVersionStr) == 0 {\n\t\t\t\treturn errors.New(\"the --kubelet-version argument is required\")\n\t\t\t}\n\n\t\t\tkubeletVersion, err := version.ParseSemantic(kubeletVersionStr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tkubeConfigFile = cmdutil.GetKubeConfigPath(kubeConfigFile)\n\t\t\tclient, err := kubeconfigutil.ClientSetFromFile(kubeConfigFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn kubeletphase.EnableDynamicConfigForNode(client, nodeName, kubeletVersion)\n\t\t},\n\t}\n\n\toptions.AddKubeConfigFlag(cmd.Flags(), &kubeConfigFile)\n\tcmd.Flags().StringVar(&nodeName, options.NodeName, nodeName, \"Name of the node that should enable the dynamic kubelet configuration\")\n\tcmd.Flags().StringVar(&kubeletVersionStr, \"kubelet-version\", kubeletVersionStr, \"The desired version for the kubelet\")\n\treturn cmd\n}\n<commit_msg>Deleted extra 'phase' in command example<commit_after>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage alpha\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/cobra\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/version\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/cmd\/options\"\n\tcmdutil \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/cmd\/util\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/constants\"\n\tkubeletphase \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/phases\/kubelet\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/preflight\"\n\tkubeconfigutil \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/util\/kubeconfig\"\n\tutilsexec \"k8s.io\/utils\/exec\"\n)\n\nvar (\n\tkubeletConfigDownloadLongDesc = cmdutil.LongDesc(`\n\t\tDownload the kubelet configuration from a ConfigMap of the form \"kubelet-config-1.X\" in the cluster,\n\t\twhere X is the minor version of the kubelet. Either kubeadm autodetects the kubelet version by exec-ing\n\t\t\"kubelet --version\" or respects the --kubelet-version parameter.\n\t\t` + cmdutil.AlphaDisclaimer)\n\n\tkubeletConfigDownloadExample = cmdutil.Examples(fmt.Sprintf(`\n\t\t# Download the kubelet configuration from the ConfigMap in the cluster. Autodetect the kubelet version.\n\t\tkubeadm alpha kubelet config download\n\n\t\t# Download the kubelet configuration from the ConfigMap in the cluster. Use a specific desired kubelet version.\n\t\tkubeadm alpha kubelet config download --kubelet-version %s\n\t\t`, constants.CurrentKubernetesVersion))\n\n\tkubeletConfigEnableDynamicLongDesc = cmdutil.LongDesc(`\n\t\tEnable or update dynamic kubelet configuration for a Node, against the kubelet-config-1.X ConfigMap in the cluster,\n\t\twhere X is the minor version of the desired kubelet version.\n\n\t\tWARNING: This feature is still experimental, and disabled by default. Enable only if you know what you are doing, as it\n\t\tmay have surprising side-effects at this stage.\n\n\t\t` + cmdutil.AlphaDisclaimer)\n\n\tkubeletConfigEnableDynamicExample = cmdutil.Examples(fmt.Sprintf(`\n\t\t# Enable dynamic kubelet configuration for a Node.\n\t\tkubeadm alpha phase kubelet enable-dynamic-config --node-name node-1 --kubelet-version %s\n\n\t\tWARNING: This feature is still experimental, and disabled by default. Enable only if you know what you are doing, as it\n\t\tmay have surprising side-effects at this stage.\n\t\t`, constants.CurrentKubernetesVersion))\n)\n\n\/\/ newCmdKubeletUtility returns command for `kubeadm phase kubelet`\nfunc newCmdKubeletUtility() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"kubelet\",\n\t\tShort: \"Commands related to handling the kubelet\",\n\t\tLong:  cmdutil.MacroCommandLongDescription,\n\t}\n\n\tcmd.AddCommand(newCmdKubeletConfig())\n\treturn cmd\n}\n\n\/\/ newCmdKubeletConfig returns command for `kubeadm phase kubelet config`\nfunc newCmdKubeletConfig() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"config\",\n\t\tShort: \"Utilities for kubelet configuration\",\n\t\tLong:  cmdutil.MacroCommandLongDescription,\n\t}\n\n\tcmd.AddCommand(newCmdKubeletConfigDownload())\n\tcmd.AddCommand(newCmdKubeletConfigEnableDynamic())\n\treturn cmd\n}\n\n\/\/ newCmdKubeletConfigDownload calls cobra.Command for downloading the kubelet configuration from the kubelet-config-1.X ConfigMap in the cluster\nfunc newCmdKubeletConfigDownload() *cobra.Command {\n\tvar kubeletVersionStr string\n\t\/\/ TODO: Be smarter about this and be able to load multiple kubeconfig files in different orders of precedence\n\tkubeConfigFile := constants.GetKubeletKubeConfigPath()\n\n\tcmd := &cobra.Command{\n\t\tUse:     \"download\",\n\t\tShort:   \"Download the kubelet configuration from the cluster ConfigMap kubelet-config-1.X, where X is the minor version of the kubelet\",\n\t\tLong:    kubeletConfigDownloadLongDesc,\n\t\tExample: kubeletConfigDownloadExample,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tkubeletVersion, err := getKubeletVersion(kubeletVersionStr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tclient, err := kubeconfigutil.ClientSetFromFile(kubeConfigFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn kubeletphase.DownloadConfig(client, kubeletVersion, constants.KubeletRunDirectory)\n\t\t},\n\t}\n\n\toptions.AddKubeConfigFlag(cmd.Flags(), &kubeConfigFile)\n\tcmd.Flags().StringVar(&kubeletVersionStr, \"kubelet-version\", kubeletVersionStr, \"The desired version for the kubelet. Defaults to being autodetected from 'kubelet --version'.\")\n\treturn cmd\n}\n\nfunc getKubeletVersion(kubeletVersionStr string) (*version.Version, error) {\n\tif len(kubeletVersionStr) > 0 {\n\t\treturn version.ParseSemantic(kubeletVersionStr)\n\t}\n\treturn preflight.GetKubeletVersion(utilsexec.New())\n}\n\n\/\/ newCmdKubeletConfigEnableDynamic calls cobra.Command for enabling dynamic kubelet configuration on node\n\/\/ This feature is still in alpha and an experimental state\nfunc newCmdKubeletConfigEnableDynamic() *cobra.Command {\n\tvar nodeName, kubeletVersionStr string\n\tvar kubeConfigFile string\n\n\tcmd := &cobra.Command{\n\t\tUse:     \"enable-dynamic\",\n\t\tShort:   \"EXPERIMENTAL: Enable or update dynamic kubelet configuration for a Node\",\n\t\tLong:    kubeletConfigEnableDynamicLongDesc,\n\t\tExample: kubeletConfigEnableDynamicExample,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif len(nodeName) == 0 {\n\t\t\t\treturn errors.New(\"the --node-name argument is required\")\n\t\t\t}\n\t\t\tif len(kubeletVersionStr) == 0 {\n\t\t\t\treturn errors.New(\"the --kubelet-version argument is required\")\n\t\t\t}\n\n\t\t\tkubeletVersion, err := version.ParseSemantic(kubeletVersionStr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tkubeConfigFile = cmdutil.GetKubeConfigPath(kubeConfigFile)\n\t\t\tclient, err := kubeconfigutil.ClientSetFromFile(kubeConfigFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn kubeletphase.EnableDynamicConfigForNode(client, nodeName, kubeletVersion)\n\t\t},\n\t}\n\n\toptions.AddKubeConfigFlag(cmd.Flags(), &kubeConfigFile)\n\tcmd.Flags().StringVar(&nodeName, options.NodeName, nodeName, \"Name of the node that should enable the dynamic kubelet configuration\")\n\tcmd.Flags().StringVar(&kubeletVersionStr, \"kubelet-version\", kubeletVersionStr, \"The desired version for the kubelet\")\n\treturn cmd\n}\n<|endoftext|>"}
{"text":"<commit_before>package rpc\n\nimport (\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ MuxConn is a connection that can be used bi-directionally for RPC. Normally,\n\/\/ Go RPC only allows client-to-server connections. This allows the client\n\/\/ to actually act as a server as well.\n\/\/\n\/\/ MuxConn works using a fairly dumb multiplexing technique of simply\n\/\/ framing every piece of data sent into a prefix + data format. Streams\n\/\/ are established using a subset of the TCP protocol. Only a subset is\n\/\/ necessary since we assume ordering on the underlying RWC.\ntype MuxConn struct {\n\tcurId   uint32\n\trwc     io.ReadWriteCloser\n\tstreams map[uint32]*Stream\n\tmu      sync.RWMutex\n\twlock   sync.Mutex\n}\n\ntype muxPacketType byte\n\nconst (\n\tmuxPacketSyn muxPacketType = iota\n\tmuxPacketAck\n\tmuxPacketFin\n\tmuxPacketData\n)\n\nfunc NewMuxConn(rwc io.ReadWriteCloser) *MuxConn {\n\tm := &MuxConn{\n\t\trwc:     rwc,\n\t\tstreams: make(map[uint32]*Stream),\n\t}\n\n\tgo m.loop()\n\n\treturn m\n}\n\n\/\/ Close closes the underlying io.ReadWriteCloser. This will also close\n\/\/ all streams that are open.\nfunc (m *MuxConn) Close() error {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\t\/\/ Close all the streams\n\tfor _, w := range m.streams {\n\t\tw.Close()\n\t}\n\tm.streams = make(map[uint32]*Stream)\n\n\treturn m.rwc.Close()\n}\n\n\/\/ Accept accepts a multiplexed connection with the given ID. This\n\/\/ will block until a request is made to connect.\nfunc (m *MuxConn) Accept(id uint32) (io.ReadWriteCloser, error) {\n\tstream, err := m.openStream(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ If the stream isn't closed, then it is already open somehow\n\tstream.mu.Lock()\n\tif stream.state != streamStateSynRecv && stream.state != streamStateClosed {\n\t\tstream.mu.Unlock()\n\t\treturn nil, fmt.Errorf(\"Stream %d already open in bad state: %d\", id, stream.state)\n\t}\n\n\tif stream.state == streamStateSynRecv {\n\t\t\/\/ Fast track establishing since we already got the syn\n\t\tstream.setState(streamStateEstablished)\n\t\tstream.mu.Unlock()\n\t}\n\n\tif stream.state != streamStateEstablished {\n\t\t\/\/ Go into the listening state\n\t\tstream.setState(streamStateListen)\n\n\t\t\/\/ Register a state change listener to wait for changes\n\t\tstateCh := make(chan streamState, 10)\n\t\tstream.registerStateListener(stateCh)\n\t\tdefer func() {\n\t\t\tstream.mu.Lock()\n\t\t\tdefer stream.mu.Unlock()\n\t\t\tstream.deregisterStateListener(stateCh)\n\t\t}()\n\n\t\tstream.mu.Unlock()\n\n\t\t\/\/ Wait for the connection to establish\n\tACCEPT_ESTABLISH_LOOP:\n\t\tfor {\n\t\t\tstate := <-stateCh\n\t\t\tswitch state {\n\t\t\tcase streamStateListen:\n\t\t\tcase streamStateEstablished:\n\t\t\t\tbreak ACCEPT_ESTABLISH_LOOP\n\t\t\tdefault:\n\t\t\t\tdefer stream.mu.Unlock()\n\t\t\t\treturn nil, fmt.Errorf(\"Stream %d went to bad state: %d\", id, stream.state)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Send the ack down\n\tif _, err := m.write(stream.id, muxPacketAck, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn stream, nil\n}\n\n\/\/ Dial opens a connection to the remote end using the given stream ID.\n\/\/ An Accept on the remote end will only work with if the IDs match.\nfunc (m *MuxConn) Dial(id uint32) (io.ReadWriteCloser, error) {\n\tstream, err := m.openStream(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ If the stream isn't closed, then it is already open somehow\n\tstream.mu.Lock()\n\tif stream.state != streamStateClosed {\n\t\tstream.mu.Unlock()\n\t\treturn nil, fmt.Errorf(\"Stream %d already open in bad state: %d\", id, stream.state)\n\t}\n\n\t\/\/ Open a connection\n\tif _, err := m.write(stream.id, muxPacketSyn, nil); err != nil {\n\t\treturn nil, err\n\t}\n\tstream.setState(streamStateSynSent)\n\n\t\/\/ Register a state change listener to wait for changes\n\tstateCh := make(chan streamState, 10)\n\tstream.registerStateListener(stateCh)\n\tdefer func() {\n\t\tstream.mu.Lock()\n\t\tdefer stream.mu.Unlock()\n\t\tstream.deregisterStateListener(stateCh)\n\t}()\n\n\tstream.mu.Unlock()\n\n\tfor {\n\t\tstate := <-stateCh\n\t\tswitch state {\n\t\tcase streamStateSynSent:\n\t\tcase streamStateEstablished:\n\t\t\treturn stream, nil\n\t\tdefault:\n\t\t\tdefer stream.mu.Unlock()\n\t\t\treturn nil, fmt.Errorf(\"Stream %d went to bad state: %d\", id, stream.state)\n\t\t}\n\t}\n}\n\n\/\/ NextId returns the next available stream ID that isn't currently\n\/\/ taken.\nfunc (m *MuxConn) NextId() uint32 {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tfor {\n\t\tresult := m.curId\n\t\tm.curId++\n\t\tif _, ok := m.streams[result]; !ok {\n\t\t\treturn result\n\t\t}\n\t}\n}\n\nfunc (m *MuxConn) openStream(id uint32) (*Stream, error) {\n\t\/\/ First grab a read-lock if we have the stream already we can\n\t\/\/ cheaply return it.\n\tm.mu.RLock()\n\tif stream, ok := m.streams[id]; ok {\n\t\tm.mu.RUnlock()\n\t\treturn stream, nil\n\t}\n\n\t\/\/ Now acquire a full blown write lock so we can create the stream\n\tm.mu.RUnlock()\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\t\/\/ We have to check this again because there is a time period\n\t\/\/ above where we couldn't lost this lock.\n\tif stream, ok := m.streams[id]; ok {\n\t\treturn stream, nil\n\t}\n\n\t\/\/ Create the stream object and channel where data will be sent to\n\tdataR, dataW := io.Pipe()\n\twriteCh := make(chan []byte, 256)\n\n\t\/\/ Set the data channel so we can write to it.\n\tstream := &Stream{\n\t\tid:          id,\n\t\tmux:         m,\n\t\treader:      dataR,\n\t\twriteCh:     writeCh,\n\t\tstateChange: make(map[chan<- streamState]struct{}),\n\t}\n\tstream.setState(streamStateClosed)\n\n\t\/\/ Start the goroutine that will read from the queue and write\n\t\/\/ data out.\n\tgo func() {\n\t\tdefer dataW.Close()\n\n\t\tfor {\n\t\t\tdata := <-writeCh\n\t\t\tif data == nil {\n\t\t\t\t\/\/ A nil is a tombstone letting us know we're done\n\t\t\t\t\/\/ accepting data.\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif _, err := dataW.Write(data); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tm.streams[id] = stream\n\treturn m.streams[id], nil\n}\n\nfunc (m *MuxConn) loop() {\n\tdefer func() {\n\t\tm.mu.Lock()\n\t\tdefer m.mu.Unlock()\n\t\tfor _, w := range m.streams {\n\t\t\tw.mu.Lock()\n\t\t\tw.remoteClose()\n\t\t\tw.mu.Unlock()\n\t\t}\n\t}()\n\n\tvar id uint32\n\tvar packetType muxPacketType\n\tvar length int32\n\tfor {\n\t\tif err := binary.Read(m.rwc, binary.BigEndian, &id); err != nil {\n\t\t\tlog.Printf(\"[ERR] Error reading stream ID: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tif err := binary.Read(m.rwc, binary.BigEndian, &packetType); err != nil {\n\t\t\tlog.Printf(\"[ERR] Error reading packet type: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tif err := binary.Read(m.rwc, binary.BigEndian, &length); err != nil {\n\t\t\tlog.Printf(\"[ERR] Error reading length: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ TODO(mitchellh): probably would be better to re-use a buffer...\n\t\tdata := make([]byte, length)\n\t\tif length > 0 {\n\t\t\tif _, err := m.rwc.Read(data); err != nil {\n\t\t\t\tlog.Printf(\"[ERR] Error reading data: %s\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tstream, err := m.openStream(id)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[ERR] Error opening stream %d: %s\", id, err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/log.Printf(\"[DEBUG] Stream %d received packet %d\", id, packetType)\n\t\tswitch packetType {\n\t\tcase muxPacketAck:\n\t\t\tstream.mu.Lock()\n\t\t\tswitch stream.state {\n\t\t\tcase streamStateSynSent:\n\t\t\t\tstream.setState(streamStateEstablished)\n\t\t\tcase streamStateFinWait1:\n\t\t\t\tstream.setState(streamStateFinWait2)\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"[ERR] Ack received for stream in state: %d\", stream.state)\n\t\t\t}\n\t\t\tstream.mu.Unlock()\n\t\tcase muxPacketSyn:\n\t\t\tstream.mu.Lock()\n\t\t\tswitch stream.state {\n\t\t\tcase streamStateClosed:\n\t\t\t\tstream.setState(streamStateSynRecv)\n\t\t\tcase streamStateListen:\n\t\t\t\tstream.setState(streamStateEstablished)\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"[ERR] Syn received for stream in state: %d\", stream.state)\n\t\t\t}\n\t\t\tstream.mu.Unlock()\n\t\tcase muxPacketFin:\n\t\t\tstream.mu.Lock()\n\t\t\tswitch stream.state {\n\t\t\tcase streamStateEstablished:\n\t\t\t\tstream.setState(streamStateCloseWait)\n\t\t\t\tm.write(id, muxPacketAck, nil)\n\n\t\t\t\t\/\/ Close the writer on our end since we won't receive any\n\t\t\t\t\/\/ more data.\n\t\t\t\tstream.writeCh <- nil\n\t\t\tcase streamStateFinWait1:\n\t\t\t\tfallthrough\n\t\t\tcase streamStateFinWait2:\n\t\t\t\tstream.remoteClose()\n\n\t\t\t\t\/\/ Remove this stream from being active so that it\n\t\t\t\t\/\/ can be re-used\n\t\t\t\tm.mu.Lock()\n\t\t\t\tdelete(m.streams, stream.id)\n\t\t\t\tm.mu.Unlock()\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"[ERR] Fin received for stream %d in state: %d\", id, stream.state)\n\t\t\t}\n\t\t\tstream.mu.Unlock()\n\n\t\tcase muxPacketData:\n\t\t\tstream.mu.Lock()\n\t\t\tif stream.state == streamStateEstablished {\n\t\t\t\tselect {\n\t\t\t\tcase stream.writeCh <- data:\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(fmt.Sprintf(\"Failed to write data, buffer full for stream %d\", id))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"[ERR] Data received for stream in state: %d\", stream.state)\n\t\t\t}\n\t\t\tstream.mu.Unlock()\n\t\t}\n\t}\n}\n\nfunc (m *MuxConn) write(id uint32, dataType muxPacketType, p []byte) (int, error) {\n\tm.wlock.Lock()\n\tdefer m.wlock.Unlock()\n\n\tif err := binary.Write(m.rwc, binary.BigEndian, id); err != nil {\n\t\treturn 0, err\n\t}\n\tif err := binary.Write(m.rwc, binary.BigEndian, byte(dataType)); err != nil {\n\t\treturn 0, err\n\t}\n\tif err := binary.Write(m.rwc, binary.BigEndian, int32(len(p))); err != nil {\n\t\treturn 0, err\n\t}\n\tif len(p) == 0 {\n\t\treturn 0, nil\n\t}\n\treturn m.rwc.Write(p)\n}\n\n\/\/ Stream is a single stream of data and implements io.ReadWriteCloser\ntype Stream struct {\n\tid           uint32\n\tmux          *MuxConn\n\treader       io.Reader\n\tstate        streamState\n\tstateChange  map[chan<- streamState]struct{}\n\tstateUpdated time.Time\n\tmu           sync.Mutex\n\twriteCh      chan<- []byte\n}\n\ntype streamState byte\n\nconst (\n\tstreamStateClosed streamState = iota\n\tstreamStateListen\n\tstreamStateSynRecv\n\tstreamStateSynSent\n\tstreamStateEstablished\n\tstreamStateFinWait1\n\tstreamStateFinWait2\n\tstreamStateCloseWait\n)\n\nfunc (s *Stream) Close() error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tif s.state != streamStateEstablished && s.state != streamStateCloseWait {\n\t\treturn fmt.Errorf(\"Stream in bad state: %d\", s.state)\n\t}\n\n\tif s.state == streamStateEstablished {\n\t\ts.setState(streamStateFinWait1)\n\t} else {\n\t\ts.remoteClose()\n\t}\n\n\ts.mux.write(s.id, muxPacketFin, nil)\n\treturn nil\n}\n\nfunc (s *Stream) Read(p []byte) (int, error) {\n\treturn s.reader.Read(p)\n}\n\nfunc (s *Stream) Write(p []byte) (int, error) {\n\ts.mu.Lock()\n\tstate := s.state\n\ts.mu.Unlock()\n\n\tif state != streamStateEstablished {\n\t\treturn 0, fmt.Errorf(\"Stream %d in bad state to send: %d\", s.id, state)\n\t}\n\n\treturn s.mux.write(s.id, muxPacketData, p)\n}\n\nfunc (s *Stream) remoteClose() {\n\ts.setState(streamStateClosed)\n\ts.writeCh <- nil\n}\n\nfunc (s *Stream) registerStateListener(ch chan<- streamState) {\n\ts.stateChange[ch] = struct{}{}\n}\n\nfunc (s *Stream) deregisterStateListener(ch chan<- streamState) {\n\tdelete(s.stateChange, ch)\n}\n\nfunc (s *Stream) setState(state streamState) {\n\ts.state = state\n\ts.stateUpdated = time.Now().UTC()\n\tfor ch, _ := range s.stateChange {\n\t\tselect {\n\t\tcase ch <- state:\n\t\tdefault:\n\t\t}\n\t}\n}\n<commit_msg>packer\/rpc: update some comments<commit_after>package rpc\n\nimport (\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ MuxConn is able to multiplex multiple streams on top of any\n\/\/ io.ReadWriteCloser. These streams act like TCP connections (Dial, Accept,\n\/\/ Close, full duplex, etc.).\n\/\/\n\/\/ The underlying io.ReadWriteCloser is expected to guarantee delivery\n\/\/ and ordering, such as TCP. Congestion control and such aren't implemented\n\/\/ by the streams, so that is also up to the underlying connection.\n\/\/\n\/\/ MuxConn works using a fairly dumb multiplexing technique of simply\n\/\/ framing every piece of data sent into a prefix + data format. Streams\n\/\/ are established using a subset of the TCP protocol. Only a subset is\n\/\/ necessary since we assume ordering on the underlying RWC.\ntype MuxConn struct {\n\tcurId   uint32\n\trwc     io.ReadWriteCloser\n\tstreams map[uint32]*Stream\n\tmu      sync.RWMutex\n\twlock   sync.Mutex\n}\n\ntype muxPacketType byte\n\nconst (\n\tmuxPacketSyn muxPacketType = iota\n\tmuxPacketAck\n\tmuxPacketFin\n\tmuxPacketData\n)\n\n\/\/ Create a new MuxConn around any io.ReadWriteCloser.\nfunc NewMuxConn(rwc io.ReadWriteCloser) *MuxConn {\n\tm := &MuxConn{\n\t\trwc:     rwc,\n\t\tstreams: make(map[uint32]*Stream),\n\t}\n\n\tgo m.loop()\n\n\treturn m\n}\n\n\/\/ Close closes the underlying io.ReadWriteCloser. This will also close\n\/\/ all streams that are open.\nfunc (m *MuxConn) Close() error {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\t\/\/ Close all the streams\n\tfor _, w := range m.streams {\n\t\tw.Close()\n\t}\n\tm.streams = make(map[uint32]*Stream)\n\n\t\/\/ Close the actual connection. This will also force the loop\n\t\/\/ to end since it'll read EOF or closed connection.\n\treturn m.rwc.Close()\n}\n\n\/\/ Accept accepts a multiplexed connection with the given ID. This\n\/\/ will block until a request is made to connect.\nfunc (m *MuxConn) Accept(id uint32) (io.ReadWriteCloser, error) {\n\tstream, err := m.openStream(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ If the stream isn't closed, then it is already open somehow\n\tstream.mu.Lock()\n\tif stream.state != streamStateSynRecv && stream.state != streamStateClosed {\n\t\tstream.mu.Unlock()\n\t\treturn nil, fmt.Errorf(\"Stream %d already open in bad state: %d\", id, stream.state)\n\t}\n\n\tif stream.state == streamStateSynRecv {\n\t\t\/\/ Fast track establishing since we already got the syn\n\t\tstream.setState(streamStateEstablished)\n\t\tstream.mu.Unlock()\n\t}\n\n\tif stream.state != streamStateEstablished {\n\t\t\/\/ Go into the listening state\n\t\tstream.setState(streamStateListen)\n\n\t\t\/\/ Register a state change listener to wait for changes\n\t\tstateCh := make(chan streamState, 10)\n\t\tstream.registerStateListener(stateCh)\n\t\tdefer func() {\n\t\t\tstream.mu.Lock()\n\t\t\tdefer stream.mu.Unlock()\n\t\t\tstream.deregisterStateListener(stateCh)\n\t\t}()\n\n\t\tstream.mu.Unlock()\n\n\t\t\/\/ Wait for the connection to establish\n\tACCEPT_ESTABLISH_LOOP:\n\t\tfor {\n\t\t\tstate := <-stateCh\n\t\t\tswitch state {\n\t\t\tcase streamStateListen:\n\t\t\tcase streamStateEstablished:\n\t\t\t\tbreak ACCEPT_ESTABLISH_LOOP\n\t\t\tdefault:\n\t\t\t\tdefer stream.mu.Unlock()\n\t\t\t\treturn nil, fmt.Errorf(\"Stream %d went to bad state: %d\", id, stream.state)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Send the ack down\n\tif _, err := m.write(stream.id, muxPacketAck, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn stream, nil\n}\n\n\/\/ Dial opens a connection to the remote end using the given stream ID.\n\/\/ An Accept on the remote end will only work with if the IDs match.\nfunc (m *MuxConn) Dial(id uint32) (io.ReadWriteCloser, error) {\n\tstream, err := m.openStream(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ If the stream isn't closed, then it is already open somehow\n\tstream.mu.Lock()\n\tif stream.state != streamStateClosed {\n\t\tstream.mu.Unlock()\n\t\treturn nil, fmt.Errorf(\"Stream %d already open in bad state: %d\", id, stream.state)\n\t}\n\n\t\/\/ Open a connection\n\tif _, err := m.write(stream.id, muxPacketSyn, nil); err != nil {\n\t\treturn nil, err\n\t}\n\tstream.setState(streamStateSynSent)\n\n\t\/\/ Register a state change listener to wait for changes\n\tstateCh := make(chan streamState, 10)\n\tstream.registerStateListener(stateCh)\n\tdefer func() {\n\t\tstream.mu.Lock()\n\t\tdefer stream.mu.Unlock()\n\t\tstream.deregisterStateListener(stateCh)\n\t}()\n\n\tstream.mu.Unlock()\n\n\tfor {\n\t\tstate := <-stateCh\n\t\tswitch state {\n\t\tcase streamStateSynSent:\n\t\tcase streamStateEstablished:\n\t\t\treturn stream, nil\n\t\tdefault:\n\t\t\tdefer stream.mu.Unlock()\n\t\t\treturn nil, fmt.Errorf(\"Stream %d went to bad state: %d\", id, stream.state)\n\t\t}\n\t}\n}\n\n\/\/ NextId returns the next available stream ID that isn't currently\n\/\/ taken.\nfunc (m *MuxConn) NextId() uint32 {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\tfor {\n\t\tresult := m.curId\n\t\tm.curId++\n\t\tif _, ok := m.streams[result]; !ok {\n\t\t\treturn result\n\t\t}\n\t}\n}\n\nfunc (m *MuxConn) openStream(id uint32) (*Stream, error) {\n\t\/\/ First grab a read-lock if we have the stream already we can\n\t\/\/ cheaply return it.\n\tm.mu.RLock()\n\tif stream, ok := m.streams[id]; ok {\n\t\tm.mu.RUnlock()\n\t\treturn stream, nil\n\t}\n\n\t\/\/ Now acquire a full blown write lock so we can create the stream\n\tm.mu.RUnlock()\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\t\/\/ We have to check this again because there is a time period\n\t\/\/ above where we couldn't lost this lock.\n\tif stream, ok := m.streams[id]; ok {\n\t\treturn stream, nil\n\t}\n\n\t\/\/ Create the stream object and channel where data will be sent to\n\tdataR, dataW := io.Pipe()\n\twriteCh := make(chan []byte, 256)\n\n\t\/\/ Set the data channel so we can write to it.\n\tstream := &Stream{\n\t\tid:          id,\n\t\tmux:         m,\n\t\treader:      dataR,\n\t\twriteCh:     writeCh,\n\t\tstateChange: make(map[chan<- streamState]struct{}),\n\t}\n\tstream.setState(streamStateClosed)\n\n\t\/\/ Start the goroutine that will read from the queue and write\n\t\/\/ data out.\n\tgo func() {\n\t\tdefer dataW.Close()\n\n\t\tfor {\n\t\t\tdata := <-writeCh\n\t\t\tif data == nil {\n\t\t\t\t\/\/ A nil is a tombstone letting us know we're done\n\t\t\t\t\/\/ accepting data.\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif _, err := dataW.Write(data); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tm.streams[id] = stream\n\treturn m.streams[id], nil\n}\n\nfunc (m *MuxConn) loop() {\n\t\/\/ Force close every stream that we know about when we exit so\n\t\/\/ that they all read EOF and don't block forever.\n\tdefer func() {\n\t\tm.mu.Lock()\n\t\tdefer m.mu.Unlock()\n\t\tfor _, w := range m.streams {\n\t\t\tw.mu.Lock()\n\t\t\tw.remoteClose()\n\t\t\tw.mu.Unlock()\n\t\t}\n\t}()\n\n\tvar id uint32\n\tvar packetType muxPacketType\n\tvar length int32\n\tfor {\n\t\tif err := binary.Read(m.rwc, binary.BigEndian, &id); err != nil {\n\t\t\tlog.Printf(\"[ERR] Error reading stream ID: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tif err := binary.Read(m.rwc, binary.BigEndian, &packetType); err != nil {\n\t\t\tlog.Printf(\"[ERR] Error reading packet type: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tif err := binary.Read(m.rwc, binary.BigEndian, &length); err != nil {\n\t\t\tlog.Printf(\"[ERR] Error reading length: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ TODO(mitchellh): probably would be better to re-use a buffer...\n\t\tdata := make([]byte, length)\n\t\tif length > 0 {\n\t\t\tif _, err := m.rwc.Read(data); err != nil {\n\t\t\t\tlog.Printf(\"[ERR] Error reading data: %s\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tstream, err := m.openStream(id)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[ERR] Error opening stream %d: %s\", id, err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/log.Printf(\"[DEBUG] Stream %d received packet %d\", id, packetType)\n\t\tswitch packetType {\n\t\tcase muxPacketAck:\n\t\t\tstream.mu.Lock()\n\t\t\tswitch stream.state {\n\t\t\tcase streamStateSynSent:\n\t\t\t\tstream.setState(streamStateEstablished)\n\t\t\tcase streamStateFinWait1:\n\t\t\t\tstream.setState(streamStateFinWait2)\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"[ERR] Ack received for stream in state: %d\", stream.state)\n\t\t\t}\n\t\t\tstream.mu.Unlock()\n\t\tcase muxPacketSyn:\n\t\t\tstream.mu.Lock()\n\t\t\tswitch stream.state {\n\t\t\tcase streamStateClosed:\n\t\t\t\tstream.setState(streamStateSynRecv)\n\t\t\tcase streamStateListen:\n\t\t\t\tstream.setState(streamStateEstablished)\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"[ERR] Syn received for stream in state: %d\", stream.state)\n\t\t\t}\n\t\t\tstream.mu.Unlock()\n\t\tcase muxPacketFin:\n\t\t\tstream.mu.Lock()\n\t\t\tswitch stream.state {\n\t\t\tcase streamStateEstablished:\n\t\t\t\tstream.setState(streamStateCloseWait)\n\t\t\t\tm.write(id, muxPacketAck, nil)\n\n\t\t\t\t\/\/ Close the writer on our end since we won't receive any\n\t\t\t\t\/\/ more data.\n\t\t\t\tstream.writeCh <- nil\n\t\t\tcase streamStateFinWait1:\n\t\t\t\tfallthrough\n\t\t\tcase streamStateFinWait2:\n\t\t\t\tstream.remoteClose()\n\n\t\t\t\t\/\/ Remove this stream from being active so that it\n\t\t\t\t\/\/ can be re-used\n\t\t\t\tm.mu.Lock()\n\t\t\t\tdelete(m.streams, stream.id)\n\t\t\t\tm.mu.Unlock()\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"[ERR] Fin received for stream %d in state: %d\", id, stream.state)\n\t\t\t}\n\t\t\tstream.mu.Unlock()\n\n\t\tcase muxPacketData:\n\t\t\tstream.mu.Lock()\n\t\t\tif stream.state == streamStateEstablished {\n\t\t\t\tselect {\n\t\t\t\tcase stream.writeCh <- data:\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(fmt.Sprintf(\"Failed to write data, buffer full for stream %d\", id))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"[ERR] Data received for stream in state: %d\", stream.state)\n\t\t\t}\n\t\t\tstream.mu.Unlock()\n\t\t}\n\t}\n}\n\nfunc (m *MuxConn) write(id uint32, dataType muxPacketType, p []byte) (int, error) {\n\tm.wlock.Lock()\n\tdefer m.wlock.Unlock()\n\n\tif err := binary.Write(m.rwc, binary.BigEndian, id); err != nil {\n\t\treturn 0, err\n\t}\n\tif err := binary.Write(m.rwc, binary.BigEndian, byte(dataType)); err != nil {\n\t\treturn 0, err\n\t}\n\tif err := binary.Write(m.rwc, binary.BigEndian, int32(len(p))); err != nil {\n\t\treturn 0, err\n\t}\n\tif len(p) == 0 {\n\t\treturn 0, nil\n\t}\n\treturn m.rwc.Write(p)\n}\n\n\/\/ Stream is a single stream of data and implements io.ReadWriteCloser.\n\/\/ A Stream is full-duplex so you can write data as well as read data.\ntype Stream struct {\n\tid           uint32\n\tmux          *MuxConn\n\treader       io.Reader\n\tstate        streamState\n\tstateChange  map[chan<- streamState]struct{}\n\tstateUpdated time.Time\n\tmu           sync.Mutex\n\twriteCh      chan<- []byte\n}\n\ntype streamState byte\n\nconst (\n\tstreamStateClosed streamState = iota\n\tstreamStateListen\n\tstreamStateSynRecv\n\tstreamStateSynSent\n\tstreamStateEstablished\n\tstreamStateFinWait1\n\tstreamStateFinWait2\n\tstreamStateCloseWait\n)\n\nfunc (s *Stream) Close() error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\n\tif s.state != streamStateEstablished && s.state != streamStateCloseWait {\n\t\treturn fmt.Errorf(\"Stream in bad state: %d\", s.state)\n\t}\n\n\tif s.state == streamStateEstablished {\n\t\ts.setState(streamStateFinWait1)\n\t} else {\n\t\ts.remoteClose()\n\t}\n\n\ts.mux.write(s.id, muxPacketFin, nil)\n\treturn nil\n}\n\nfunc (s *Stream) Read(p []byte) (int, error) {\n\treturn s.reader.Read(p)\n}\n\nfunc (s *Stream) Write(p []byte) (int, error) {\n\ts.mu.Lock()\n\tstate := s.state\n\ts.mu.Unlock()\n\n\tif state != streamStateEstablished {\n\t\treturn 0, fmt.Errorf(\"Stream %d in bad state to send: %d\", s.id, state)\n\t}\n\n\treturn s.mux.write(s.id, muxPacketData, p)\n}\n\nfunc (s *Stream) remoteClose() {\n\ts.setState(streamStateClosed)\n\ts.writeCh <- nil\n}\n\nfunc (s *Stream) registerStateListener(ch chan<- streamState) {\n\ts.stateChange[ch] = struct{}{}\n}\n\nfunc (s *Stream) deregisterStateListener(ch chan<- streamState) {\n\tdelete(s.stateChange, ch)\n}\n\nfunc (s *Stream) setState(state streamState) {\n\ts.state = state\n\ts.stateUpdated = time.Now().UTC()\n\tfor ch, _ := range s.stateChange {\n\t\tselect {\n\t\tcase ch <- state:\n\t\tdefault:\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package registry\n\nimport (\n\t\"crypto\/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n\n\tconsul \"github.com\/hashicorp\/consul\/api\"\n\thash \"github.com\/mitchellh\/hashstructure\"\n)\n\ntype consulRegistry struct {\n\tAddress string\n\tClient  *consul.Client\n\topts    Options\n\n\t\/\/ connect enabled\n\tconnect bool\n\n\tsync.Mutex\n\tregister map[string]uint64\n}\n\nfunc getDeregisterTTL(t time.Duration) time.Duration {\n\t\/\/ splay slightly for the watcher?\n\tsplay := time.Second * 5\n\tderegTTL := t + splay\n\n\t\/\/ consul has a minimum timeout on deregistration of 1 minute.\n\tif t < time.Minute {\n\t\tderegTTL = time.Minute + splay\n\t}\n\n\treturn deregTTL\n}\n\nfunc newTransport(config *tls.Config) *http.Transport {\n\tif config == nil {\n\t\tconfig = &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t}\n\t}\n\n\tt := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout:   30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tTLSClientConfig:     config,\n\t}\n\truntime.SetFinalizer(&t, func(tr **http.Transport) {\n\t\t(*tr).CloseIdleConnections()\n\t})\n\treturn t\n}\n\nfunc configure(c *consulRegistry, opts ...Option) {\n\t\/\/ set opts\n\tfor _, o := range opts {\n\t\to(&c.opts)\n\t}\n\n\t\/\/ use default config\n\tconfig := consul.DefaultConfig()\n\n\tif c.opts.Context != nil {\n\t\t\/\/ Use the consul config passed in the options, if available\n\t\tif co, ok := c.opts.Context.Value(\"consul_config\").(*consul.Config); ok {\n\t\t\tconfig = co\n\t\t}\n\t\tif cn, ok := c.opts.Context.Value(\"consul_connect\").(bool); ok {\n\t\t\tc.connect = cn\n\t\t}\n\t}\n\n\t\/\/ check if there are any addrs\n\tif len(c.opts.Addrs) > 0 {\n\t\taddr, port, err := net.SplitHostPort(c.opts.Addrs[0])\n\t\tif ae, ok := err.(*net.AddrError); ok && ae.Err == \"missing port in address\" {\n\t\t\tport = \"8500\"\n\t\t\taddr = c.opts.Addrs[0]\n\t\t\tconfig.Address = fmt.Sprintf(\"%s:%s\", addr, port)\n\t\t} else if err == nil {\n\t\t\tconfig.Address = fmt.Sprintf(\"%s:%s\", addr, port)\n\t\t}\n\t}\n\n\t\/\/ requires secure connection?\n\tif c.opts.Secure || c.opts.TLSConfig != nil {\n\t\tif config.HttpClient == nil {\n\t\t\tconfig.HttpClient = new(http.Client)\n\t\t}\n\n\t\tconfig.Scheme = \"https\"\n\t\t\/\/ We're going to support InsecureSkipVerify\n\t\tconfig.HttpClient.Transport = newTransport(c.opts.TLSConfig)\n\t}\n\n\t\/\/ set timeout\n\tif c.opts.Timeout > 0 {\n\t\tconfig.HttpClient.Timeout = c.opts.Timeout\n\t}\n\n\t\/\/ create the client\n\tclient, _ := consul.NewClient(config)\n\n\t\/\/ set address\/client\n\tc.Address = config.Address\n\tc.Client = client\n}\n\nfunc newConsulRegistry(opts ...Option) Registry {\n\tcr := &consulRegistry{\n\t\topts:     Options{},\n\t\tregister: make(map[string]uint64),\n\t}\n\tconfigure(cr, opts...)\n\treturn cr\n}\n\nfunc (c *consulRegistry) Init(opts ...Option) error {\n\tconfigure(c, opts...)\n\treturn nil\n}\n\nfunc (c *consulRegistry) Deregister(s *Service) error {\n\tif len(s.Nodes) == 0 {\n\t\treturn errors.New(\"Require at least one node\")\n\t}\n\n\t\/\/ delete our hash of the service\n\tc.Lock()\n\tdelete(c.register, s.Name)\n\tc.Unlock()\n\n\tnode := s.Nodes[0]\n\treturn c.Client.Agent().ServiceDeregister(node.Id)\n}\n\nfunc (c *consulRegistry) Register(s *Service, opts ...RegisterOption) error {\n\tif len(s.Nodes) == 0 {\n\t\treturn errors.New(\"Require at least one node\")\n\t}\n\n\tvar regTCPCheck bool\n\tvar regInterval time.Duration\n\n\tvar options RegisterOptions\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\tif c.opts.Context != nil {\n\t\tif tcpCheckInterval, ok := c.opts.Context.Value(\"consul_tcp_check\").(time.Duration); ok {\n\t\t\tregTCPCheck = true\n\t\t\tregInterval = tcpCheckInterval\n\t\t}\n\t}\n\n\t\/\/ create hash of service; uint64\n\th, err := hash.Hash(s, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ use first node\n\tnode := s.Nodes[0]\n\n\t\/\/ get existing hash\n\tc.Lock()\n\tv, ok := c.register[s.Name]\n\tc.Unlock()\n\n\t\/\/ if it's already registered and matches then just pass the check\n\tif ok && v == h {\n\t\tif options.TTL == time.Duration(0) {\n\t\t\tservices,_, err := c.Client.Health().Checks(s.Name, nil)\n\t\t\tif err == nil {\n\t\t\t\tfor _, v := range services {\n\t\t\t\t\tif v.ServiceID == node.Id {\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}else{\n\t\t\t\/\/ if the err is nil we're all good, bail out\n\t\t\t\/\/ if not, we don't know what the state is, so full re-register\n\t\t\tif err := c.Client.Agent().PassTTL(\"service:\"+node.Id, \"\"); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ encode the tags\n\ttags := encodeMetadata(node.Metadata)\n\ttags = append(tags, encodeEndpoints(s.Endpoints)...)\n\ttags = append(tags, encodeVersion(s.Version)...)\n\n\tvar check *consul.AgentServiceCheck\n\n\tif regTCPCheck {\n\t\tderegTTL := getDeregisterTTL(regInterval)\n\n\t\tcheck = &consul.AgentServiceCheck{\n\t\t\tTCP:                            fmt.Sprintf(\"%s:%d\", node.Address, node.Port),\n\t\t\tInterval:                       fmt.Sprintf(\"%v\", regInterval),\n\t\t\tDeregisterCriticalServiceAfter: fmt.Sprintf(\"%v\", deregTTL),\n\t\t}\n\n\t\t\/\/ if the TTL is greater than 0 create an associated check\n\t} else if options.TTL > time.Duration(0) {\n\t\tderegTTL := getDeregisterTTL(options.TTL)\n\n\t\tcheck = &consul.AgentServiceCheck{\n\t\t\tTTL: fmt.Sprintf(\"%v\", options.TTL),\n\t\t\tDeregisterCriticalServiceAfter: fmt.Sprintf(\"%v\", deregTTL),\n\t\t}\n\t}\n\n\t\/\/ register the service\n\tasr := &consul.AgentServiceRegistration{\n\t\tID:      node.Id,\n\t\tName:    s.Name,\n\t\tTags:    tags,\n\t\tPort:    node.Port,\n\t\tAddress: node.Address,\n\t\tCheck:   check,\n\t}\n\n\t\/\/ Specify consul connect\n\tif c.connect {\n\t\tasr.Connect = &consul.AgentServiceConnect{\n\t\t\tNative: true,\n\t\t}\n\t}\n\n\tif err := c.Client.Agent().ServiceRegister(asr); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ save our hash of the service\n\tc.Lock()\n\tc.register[s.Name] = h\n\tc.Unlock()\n\n\t\/\/ if the TTL is 0 we don't mess with the checks\n\tif options.TTL == time.Duration(0) {\n\t\treturn nil\n\t}\n\n\t\/\/ pass the healthcheck\n\treturn c.Client.Agent().PassTTL(\"service:\"+node.Id, \"\")\n}\n\nfunc (c *consulRegistry) GetService(name string) ([]*Service, error) {\n\tvar rsp []*consul.ServiceEntry\n\tvar err error\n\n\t\/\/ if we're connect enabled only get connect services\n\tif c.connect {\n\t\trsp, _, err = c.Client.Health().Connect(name, \"\", false, nil)\n\t} else {\n\t\trsp, _, err = c.Client.Health().Service(name, \"\", false, nil)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserviceMap := map[string]*Service{}\n\n\tfor _, s := range rsp {\n\t\tif s.Service.Service != name {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ version is now a tag\n\t\tversion, _ := decodeVersion(s.Service.Tags)\n\t\t\/\/ service ID is now the node id\n\t\tid := s.Service.ID\n\t\t\/\/ key is always the version\n\t\tkey := version\n\n\t\t\/\/ address is service address\n\t\taddress := s.Service.Address\n\n\t\t\/\/ use node address\n\t\tif len(address) == 0 {\n\t\t\taddress = s.Node.Address\n\t\t}\n\n\t\tsvc, ok := serviceMap[key]\n\t\tif !ok {\n\t\t\tsvc = &Service{\n\t\t\t\tEndpoints: decodeEndpoints(s.Service.Tags),\n\t\t\t\tName:      s.Service.Service,\n\t\t\t\tVersion:   version,\n\t\t\t}\n\t\t\tserviceMap[key] = svc\n\t\t}\n\n\t\tvar del bool\n\n\t\tfor _, check := range s.Checks {\n\t\t\t\/\/ delete the node if the status is critical\n\t\t\tif check.Status == \"critical\" {\n\t\t\t\tdel = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t\/\/ if delete then skip the node\n\t\tif del {\n\t\t\tcontinue\n\t\t}\n\n\t\tsvc.Nodes = append(svc.Nodes, &Node{\n\t\t\tId:       id,\n\t\t\tAddress:  address,\n\t\t\tPort:     s.Service.Port,\n\t\t\tMetadata: decodeMetadata(s.Service.Tags),\n\t\t})\n\t}\n\n\tvar services []*Service\n\tfor _, service := range serviceMap {\n\t\tservices = append(services, service)\n\t}\n\treturn services, nil\n}\n\nfunc (c *consulRegistry) ListServices() ([]*Service, error) {\n\trsp, _, err := c.Client.Catalog().Services(nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar services []*Service\n\n\tfor service := range rsp {\n\t\tservices = append(services, &Service{Name: service})\n\t}\n\n\treturn services, nil\n}\n\nfunc (c *consulRegistry) Watch(opts ...WatchOption) (Watcher, error) {\n\treturn newConsulWatcher(c, opts...)\n}\n\nfunc (c *consulRegistry) String() string {\n\treturn \"consul\"\n}\n\nfunc (c *consulRegistry) Options() Options {\n\treturn c.opts\n}\n<commit_msg>go fmt<commit_after>package registry\n\nimport (\n\t\"crypto\/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n\n\tconsul \"github.com\/hashicorp\/consul\/api\"\n\thash \"github.com\/mitchellh\/hashstructure\"\n)\n\ntype consulRegistry struct {\n\tAddress string\n\tClient  *consul.Client\n\topts    Options\n\n\t\/\/ connect enabled\n\tconnect bool\n\n\tsync.Mutex\n\tregister map[string]uint64\n}\n\nfunc getDeregisterTTL(t time.Duration) time.Duration {\n\t\/\/ splay slightly for the watcher?\n\tsplay := time.Second * 5\n\tderegTTL := t + splay\n\n\t\/\/ consul has a minimum timeout on deregistration of 1 minute.\n\tif t < time.Minute {\n\t\tderegTTL = time.Minute + splay\n\t}\n\n\treturn deregTTL\n}\n\nfunc newTransport(config *tls.Config) *http.Transport {\n\tif config == nil {\n\t\tconfig = &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t}\n\t}\n\n\tt := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout:   30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tTLSClientConfig:     config,\n\t}\n\truntime.SetFinalizer(&t, func(tr **http.Transport) {\n\t\t(*tr).CloseIdleConnections()\n\t})\n\treturn t\n}\n\nfunc configure(c *consulRegistry, opts ...Option) {\n\t\/\/ set opts\n\tfor _, o := range opts {\n\t\to(&c.opts)\n\t}\n\n\t\/\/ use default config\n\tconfig := consul.DefaultConfig()\n\n\tif c.opts.Context != nil {\n\t\t\/\/ Use the consul config passed in the options, if available\n\t\tif co, ok := c.opts.Context.Value(\"consul_config\").(*consul.Config); ok {\n\t\t\tconfig = co\n\t\t}\n\t\tif cn, ok := c.opts.Context.Value(\"consul_connect\").(bool); ok {\n\t\t\tc.connect = cn\n\t\t}\n\t}\n\n\t\/\/ check if there are any addrs\n\tif len(c.opts.Addrs) > 0 {\n\t\taddr, port, err := net.SplitHostPort(c.opts.Addrs[0])\n\t\tif ae, ok := err.(*net.AddrError); ok && ae.Err == \"missing port in address\" {\n\t\t\tport = \"8500\"\n\t\t\taddr = c.opts.Addrs[0]\n\t\t\tconfig.Address = fmt.Sprintf(\"%s:%s\", addr, port)\n\t\t} else if err == nil {\n\t\t\tconfig.Address = fmt.Sprintf(\"%s:%s\", addr, port)\n\t\t}\n\t}\n\n\t\/\/ requires secure connection?\n\tif c.opts.Secure || c.opts.TLSConfig != nil {\n\t\tif config.HttpClient == nil {\n\t\t\tconfig.HttpClient = new(http.Client)\n\t\t}\n\n\t\tconfig.Scheme = \"https\"\n\t\t\/\/ We're going to support InsecureSkipVerify\n\t\tconfig.HttpClient.Transport = newTransport(c.opts.TLSConfig)\n\t}\n\n\t\/\/ set timeout\n\tif c.opts.Timeout > 0 {\n\t\tconfig.HttpClient.Timeout = c.opts.Timeout\n\t}\n\n\t\/\/ create the client\n\tclient, _ := consul.NewClient(config)\n\n\t\/\/ set address\/client\n\tc.Address = config.Address\n\tc.Client = client\n}\n\nfunc newConsulRegistry(opts ...Option) Registry {\n\tcr := &consulRegistry{\n\t\topts:     Options{},\n\t\tregister: make(map[string]uint64),\n\t}\n\tconfigure(cr, opts...)\n\treturn cr\n}\n\nfunc (c *consulRegistry) Init(opts ...Option) error {\n\tconfigure(c, opts...)\n\treturn nil\n}\n\nfunc (c *consulRegistry) Deregister(s *Service) error {\n\tif len(s.Nodes) == 0 {\n\t\treturn errors.New(\"Require at least one node\")\n\t}\n\n\t\/\/ delete our hash of the service\n\tc.Lock()\n\tdelete(c.register, s.Name)\n\tc.Unlock()\n\n\tnode := s.Nodes[0]\n\treturn c.Client.Agent().ServiceDeregister(node.Id)\n}\n\nfunc (c *consulRegistry) Register(s *Service, opts ...RegisterOption) error {\n\tif len(s.Nodes) == 0 {\n\t\treturn errors.New(\"Require at least one node\")\n\t}\n\n\tvar regTCPCheck bool\n\tvar regInterval time.Duration\n\n\tvar options RegisterOptions\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\tif c.opts.Context != nil {\n\t\tif tcpCheckInterval, ok := c.opts.Context.Value(\"consul_tcp_check\").(time.Duration); ok {\n\t\t\tregTCPCheck = true\n\t\t\tregInterval = tcpCheckInterval\n\t\t}\n\t}\n\n\t\/\/ create hash of service; uint64\n\th, err := hash.Hash(s, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ use first node\n\tnode := s.Nodes[0]\n\n\t\/\/ get existing hash\n\tc.Lock()\n\tv, ok := c.register[s.Name]\n\tc.Unlock()\n\n\t\/\/ if it's already registered and matches then just pass the check\n\tif ok && v == h {\n\t\tif options.TTL == time.Duration(0) {\n\t\t\tservices, _, err := c.Client.Health().Checks(s.Name, nil)\n\t\t\tif err == nil {\n\t\t\t\tfor _, v := range services {\n\t\t\t\t\tif v.ServiceID == node.Id {\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ if the err is nil we're all good, bail out\n\t\t\t\/\/ if not, we don't know what the state is, so full re-register\n\t\t\tif err := c.Client.Agent().PassTTL(\"service:\"+node.Id, \"\"); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ encode the tags\n\ttags := encodeMetadata(node.Metadata)\n\ttags = append(tags, encodeEndpoints(s.Endpoints)...)\n\ttags = append(tags, encodeVersion(s.Version)...)\n\n\tvar check *consul.AgentServiceCheck\n\n\tif regTCPCheck {\n\t\tderegTTL := getDeregisterTTL(regInterval)\n\n\t\tcheck = &consul.AgentServiceCheck{\n\t\t\tTCP:                            fmt.Sprintf(\"%s:%d\", node.Address, node.Port),\n\t\t\tInterval:                       fmt.Sprintf(\"%v\", regInterval),\n\t\t\tDeregisterCriticalServiceAfter: fmt.Sprintf(\"%v\", deregTTL),\n\t\t}\n\n\t\t\/\/ if the TTL is greater than 0 create an associated check\n\t} else if options.TTL > time.Duration(0) {\n\t\tderegTTL := getDeregisterTTL(options.TTL)\n\n\t\tcheck = &consul.AgentServiceCheck{\n\t\t\tTTL:                            fmt.Sprintf(\"%v\", options.TTL),\n\t\t\tDeregisterCriticalServiceAfter: fmt.Sprintf(\"%v\", deregTTL),\n\t\t}\n\t}\n\n\t\/\/ register the service\n\tasr := &consul.AgentServiceRegistration{\n\t\tID:      node.Id,\n\t\tName:    s.Name,\n\t\tTags:    tags,\n\t\tPort:    node.Port,\n\t\tAddress: node.Address,\n\t\tCheck:   check,\n\t}\n\n\t\/\/ Specify consul connect\n\tif c.connect {\n\t\tasr.Connect = &consul.AgentServiceConnect{\n\t\t\tNative: true,\n\t\t}\n\t}\n\n\tif err := c.Client.Agent().ServiceRegister(asr); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ save our hash of the service\n\tc.Lock()\n\tc.register[s.Name] = h\n\tc.Unlock()\n\n\t\/\/ if the TTL is 0 we don't mess with the checks\n\tif options.TTL == time.Duration(0) {\n\t\treturn nil\n\t}\n\n\t\/\/ pass the healthcheck\n\treturn c.Client.Agent().PassTTL(\"service:\"+node.Id, \"\")\n}\n\nfunc (c *consulRegistry) GetService(name string) ([]*Service, error) {\n\tvar rsp []*consul.ServiceEntry\n\tvar err error\n\n\t\/\/ if we're connect enabled only get connect services\n\tif c.connect {\n\t\trsp, _, err = c.Client.Health().Connect(name, \"\", false, nil)\n\t} else {\n\t\trsp, _, err = c.Client.Health().Service(name, \"\", false, nil)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserviceMap := map[string]*Service{}\n\n\tfor _, s := range rsp {\n\t\tif s.Service.Service != name {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ version is now a tag\n\t\tversion, _ := decodeVersion(s.Service.Tags)\n\t\t\/\/ service ID is now the node id\n\t\tid := s.Service.ID\n\t\t\/\/ key is always the version\n\t\tkey := version\n\n\t\t\/\/ address is service address\n\t\taddress := s.Service.Address\n\n\t\t\/\/ use node address\n\t\tif len(address) == 0 {\n\t\t\taddress = s.Node.Address\n\t\t}\n\n\t\tsvc, ok := serviceMap[key]\n\t\tif !ok {\n\t\t\tsvc = &Service{\n\t\t\t\tEndpoints: decodeEndpoints(s.Service.Tags),\n\t\t\t\tName:      s.Service.Service,\n\t\t\t\tVersion:   version,\n\t\t\t}\n\t\t\tserviceMap[key] = svc\n\t\t}\n\n\t\tvar del bool\n\n\t\tfor _, check := range s.Checks {\n\t\t\t\/\/ delete the node if the status is critical\n\t\t\tif check.Status == \"critical\" {\n\t\t\t\tdel = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t\/\/ if delete then skip the node\n\t\tif del {\n\t\t\tcontinue\n\t\t}\n\n\t\tsvc.Nodes = append(svc.Nodes, &Node{\n\t\t\tId:       id,\n\t\t\tAddress:  address,\n\t\t\tPort:     s.Service.Port,\n\t\t\tMetadata: decodeMetadata(s.Service.Tags),\n\t\t})\n\t}\n\n\tvar services []*Service\n\tfor _, service := range serviceMap {\n\t\tservices = append(services, service)\n\t}\n\treturn services, nil\n}\n\nfunc (c *consulRegistry) ListServices() ([]*Service, error) {\n\trsp, _, err := c.Client.Catalog().Services(nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar services []*Service\n\n\tfor service := range rsp {\n\t\tservices = append(services, &Service{Name: service})\n\t}\n\n\treturn services, nil\n}\n\nfunc (c *consulRegistry) Watch(opts ...WatchOption) (Watcher, error) {\n\treturn newConsulWatcher(c, opts...)\n}\n\nfunc (c *consulRegistry) String() string {\n\treturn \"consul\"\n}\n\nfunc (c *consulRegistry) Options() Options {\n\treturn c.opts\n}\n<|endoftext|>"}
{"text":"<commit_before>package modelhelper\n\nimport (\n\t\"errors\"\n\t\"koding\/db\/models\"\n\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\ntype Bongo struct {\n\tConstructorName string `json:\"constructorName\"`\n\tInstanceId      string `json:\"instanceId\"`\n}\n\ntype MachineContainer struct {\n\tBongo Bongo           `json:\"bongo_\"`\n\tData  *models.Machine `json:\"data\"`\n\t*models.Machine\n}\n\nvar (\n\tMachineColl            = \"jMachines\"\n\tMachineConstructorName = \"JMachine\"\n)\n\nfunc GetMachines(userId bson.ObjectId) ([]*MachineContainer, error) {\n\tmachines := []*models.Machine{}\n\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Find(bson.M{\"users.id\": userId}).All(&machines)\n\t}\n\n\terr := Mongo.Run(MachineColl, query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontainers := []*MachineContainer{}\n\n\tfor _, machine := range machines {\n\t\tbongo := Bongo{\n\t\t\tConstructorName: MachineConstructorName,\n\t\t\tInstanceId:      machine.ObjectId.Hex(),\n\t\t}\n\t\tcontainer := &MachineContainer{bongo, machine, machine}\n\n\t\tcontainers = append(containers, container)\n\t}\n\n\treturn containers, nil\n}\n\nvar (\n\tMachineStateRunning = \"Running\"\n)\n\nfunc GetRunningVms() ([]*models.Machine, error) {\n\tquery := bson.M{\"status.state\": MachineStateRunning}\n\treturn findMachine(query)\n}\n\nfunc GetMachinesByUsername(username string) ([]*models.Machine, error) {\n\tuser, err := GetUser(username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tquery := bson.M{\"users\": bson.M{\n\t\t\"$elemMatch\": bson.M{\"id\": user.ObjectId, \"owner\": true},\n\t}}\n\n\treturn findMachine(query)\n}\n\nfunc GetOwnMachines(userId bson.ObjectId) ([]*MachineContainer, error) {\n\tquery := bson.M{\"users\": bson.M{\n\t\t\"$elemMatch\": bson.M{\"id\": userId, \"owner\": true},\n\t}}\n\n\treturn findMachineContainers(query)\n}\n\nfunc GetSharedMachines(userId bson.ObjectId) ([]*MachineContainer, error) {\n\tquery := bson.M{\"users\": bson.M{\n\t\t\"$elemMatch\": bson.M{\"id\": userId, \"owner\": false, \"permanent\": true},\n\t}}\n\n\treturn findMachineContainers(query)\n}\n\nfunc GetCollabMachines(userId bson.ObjectId) ([]*MachineContainer, error) {\n\tquery := bson.M{\"users\": bson.M{\n\t\t\"$elemMatch\": bson.M{\"id\": userId, \"owner\": false,\n\t\t\t\"permanent\": bson.M{\"$ne\": true}},\n\t}}\n\n\treturn findMachineContainers(query)\n}\n\nfunc findMachineContainers(query bson.M) ([]*MachineContainer, error) {\n\tmachines, err := findMachine(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontainers := []*MachineContainer{}\n\n\tfor _, machine := range machines {\n\t\tbongo := Bongo{\n\t\t\tConstructorName: MachineConstructorName,\n\t\t\tInstanceId:      \"1\", \/\/ TODO: what should go here?\n\t\t}\n\n\t\tcontainer := &MachineContainer{bongo, machine, machine}\n\t\tcontainers = append(containers, container)\n\t}\n\n\treturn containers, nil\n}\n\n\/\/ GetMachineByUid returns the machine by its uid field\nfunc GetMachineByUid(uid string) (*models.Machine, error) {\n\tmachine := &models.Machine{}\n\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Find(bson.M{\"uid\": uid}).One(machine)\n\t}\n\n\terr := Mongo.Run(MachineColl, query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn machine, nil\n}\n\n\/\/ UnshareMachineByUid unshares the machine from all other users except the\n\/\/ owner\nfunc UnshareMachineByUid(uid string) error {\n\tmachine, err := GetMachineByUid(uid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmachineOwner := machine.Owner()\n\tif machineOwner == nil {\n\t\treturn errors.New(\"owner couldnt found\")\n\t}\n\n\towner := []models.MachineUser{*machineOwner}\n\n\ts := Selector{\"_id\": machine.ObjectId}\n\to := Selector{\"$set\": Selector{\n\t\t\"users\": owner,\n\t}}\n\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Update(s, o)\n\t}\n\n\treturn Mongo.Run(MachineColl, query)\n}\n\n\/\/ RemoveUsersFromMachineByIds removes the given users from JMachine document\nfunc RemoveUsersFromMachineByIds(uid string, ids []bson.ObjectId) error {\n\tmachine, err := GetMachineByUid(uid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tusers := make([]models.MachineUser, 0)\n\n\tfor _, user := range machine.Users {\n\t\ttoBeAdded := true\n\t\tfor _, id := range ids {\n\t\t\tif user.Id.Hex() == id.Hex() {\n\t\t\t\ttoBeAdded = false\n\t\t\t}\n\t\t}\n\n\t\tif toBeAdded {\n\t\t\t\/\/ we couldnt find the account in to be removed list, so add it back\n\t\t\tusers = append(users, user)\n\t\t}\n\t}\n\n\ts := Selector{\"_id\": machine.ObjectId}\n\to := Selector{\"$set\": Selector{\n\t\t\"users\": users,\n\t}}\n\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Update(s, o)\n\t}\n\n\treturn Mongo.Run(MachineColl, query)\n}\n\nfunc findMachine(query bson.M) ([]*models.Machine, error) {\n\tmachines := []*models.Machine{}\n\n\tqueryFn := func(c *mgo.Collection) error {\n\t\titer := c.Find(query).Iter()\n\n\t\tvar machine models.Machine\n\t\tfor iter.Next(&machine) {\n\t\t\tvar newMachine models.Machine\n\t\t\tnewMachine = machine\n\n\t\t\tmachines = append(machines, &newMachine)\n\t\t}\n\n\t\treturn iter.Close()\n\t}\n\n\tif err := Mongo.Run(MachineColl, queryFn); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn machines, nil\n}\n\nfunc UpdateMachineAlwaysOn(machineId bson.ObjectId, alwaysOn bool) error {\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Update(\n\t\t\tbson.M{\"_id\": machineId},\n\t\t\tbson.M{\"$set\": bson.M{\"meta.alwaysOn\": alwaysOn}},\n\t\t)\n\t}\n\n\treturn Mongo.Run(MachineColl, query)\n}\n\nfunc CreateMachine(m *models.Machine) error {\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Insert(m)\n\t}\n\n\treturn Mongo.Run(MachineColl, query)\n}\n\n\/\/ DeleteMachine deletes the machine from mongodb, it is here just for cleaning\n\/\/ purposes(after tests), machines should not be removed from database  unless\n\/\/ you are kloud\nfunc DeleteMachine(id bson.ObjectId) error {\n\tselector := bson.M{\"_id\": id}\n\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Remove(selector)\n\t}\n\n\treturn Mongo.Run(MachineColl, query)\n}\n<commit_msg>Go: fix styling<commit_after>package modelhelper\n\nimport (\n\t\"errors\"\n\t\"koding\/db\/models\"\n\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\ntype Bongo struct {\n\tConstructorName string `json:\"constructorName\"`\n\tInstanceId      string `json:\"instanceId\"`\n}\n\ntype MachineContainer struct {\n\tBongo Bongo           `json:\"bongo_\"`\n\tData  *models.Machine `json:\"data\"`\n\t*models.Machine\n}\n\nvar (\n\tMachineColl            = \"jMachines\"\n\tMachineConstructorName = \"JMachine\"\n)\n\nfunc GetMachines(userId bson.ObjectId) ([]*MachineContainer, error) {\n\tmachines := []*models.Machine{}\n\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Find(bson.M{\"users.id\": userId}).All(&machines)\n\t}\n\n\terr := Mongo.Run(MachineColl, query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontainers := []*MachineContainer{}\n\n\tfor _, machine := range machines {\n\t\tbongo := Bongo{\n\t\t\tConstructorName: MachineConstructorName,\n\t\t\tInstanceId:      machine.ObjectId.Hex(),\n\t\t}\n\t\tcontainer := &MachineContainer{bongo, machine, machine}\n\n\t\tcontainers = append(containers, container)\n\t}\n\n\treturn containers, nil\n}\n\nvar (\n\tMachineStateRunning = \"Running\"\n)\n\nfunc GetRunningVms() ([]*models.Machine, error) {\n\tquery := bson.M{\"status.state\": MachineStateRunning}\n\treturn findMachine(query)\n}\n\nfunc GetMachinesByUsername(username string) ([]*models.Machine, error) {\n\tuser, err := GetUser(username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tquery := bson.M{\"users\": bson.M{\n\t\t\"$elemMatch\": bson.M{\"id\": user.ObjectId, \"owner\": true},\n\t}}\n\n\treturn findMachine(query)\n}\n\nfunc GetOwnMachines(userId bson.ObjectId) ([]*MachineContainer, error) {\n\tquery := bson.M{\"users\": bson.M{\n\t\t\"$elemMatch\": bson.M{\"id\": userId, \"owner\": true},\n\t}}\n\n\treturn findMachineContainers(query)\n}\n\nfunc GetSharedMachines(userId bson.ObjectId) ([]*MachineContainer, error) {\n\tquery := bson.M{\"users\": bson.M{\n\t\t\"$elemMatch\": bson.M{\"id\": userId, \"owner\": false, \"permanent\": true},\n\t}}\n\n\treturn findMachineContainers(query)\n}\n\nfunc GetCollabMachines(userId bson.ObjectId) ([]*MachineContainer, error) {\n\tquery := bson.M{\"users\": bson.M{\n\t\t\"$elemMatch\": bson.M{\"id\": userId, \"owner\": false,\n\t\t\t\"permanent\": bson.M{\"$ne\": true}},\n\t}}\n\n\treturn findMachineContainers(query)\n}\n\nfunc findMachineContainers(query bson.M) ([]*MachineContainer, error) {\n\tmachines, err := findMachine(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontainers := []*MachineContainer{}\n\n\tfor _, machine := range machines {\n\t\tbongo := Bongo{\n\t\t\tConstructorName: MachineConstructorName,\n\t\t\tInstanceId:      \"1\", \/\/ TODO: what should go here?\n\t\t}\n\n\t\tcontainer := &MachineContainer{bongo, machine, machine}\n\t\tcontainers = append(containers, container)\n\t}\n\n\treturn containers, nil\n}\n\n\/\/ GetMachineByUid returns the machine by its uid field\nfunc GetMachineByUid(uid string) (*models.Machine, error) {\n\tmachine := &models.Machine{}\n\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Find(bson.M{\"uid\": uid}).One(machine)\n\t}\n\n\terr := Mongo.Run(MachineColl, query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn machine, nil\n}\n\n\/\/ UnshareMachineByUid unshares the machine from all other users except the\n\/\/ owner\nfunc UnshareMachineByUid(uid string) error {\n\tmachine, err := GetMachineByUid(uid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmachineOwner := machine.Owner()\n\tif machineOwner == nil {\n\t\treturn errors.New(\"owner couldnt found\")\n\t}\n\n\towner := []models.MachineUser{*machineOwner}\n\n\ts := Selector{\"_id\": machine.ObjectId}\n\to := Selector{\"$set\": Selector{\n\t\t\"users\": owner,\n\t}}\n\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Update(s, o)\n\t}\n\n\treturn Mongo.Run(MachineColl, query)\n}\n\n\/\/ RemoveUsersFromMachineByIds removes the given users from JMachine document\nfunc RemoveUsersFromMachineByIds(uid string, ids []bson.ObjectId) error {\n\tmachine, err := GetMachineByUid(uid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tusers := make([]models.MachineUser, 0)\n\n\tfor _, user := range machine.Users {\n\t\ttoBeAdded := true\n\t\tfor _, id := range ids {\n\t\t\tif user.Id.Hex() == id.Hex() {\n\t\t\t\ttoBeAdded = false\n\t\t\t}\n\t\t}\n\n\t\tif toBeAdded {\n\t\t\t\/\/ we couldnt find the account in -to be removed list-, so add it\n\t\t\t\/\/ back\n\t\t\tusers = append(users, user)\n\t\t}\n\t}\n\n\ts := Selector{\"_id\": machine.ObjectId}\n\to := Selector{\"$set\": Selector{\n\t\t\"users\": users,\n\t}}\n\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Update(s, o)\n\t}\n\n\treturn Mongo.Run(MachineColl, query)\n}\n\nfunc findMachine(query bson.M) ([]*models.Machine, error) {\n\tmachines := []*models.Machine{}\n\n\tqueryFn := func(c *mgo.Collection) error {\n\t\titer := c.Find(query).Iter()\n\n\t\tvar machine models.Machine\n\t\tfor iter.Next(&machine) {\n\t\t\tvar newMachine models.Machine\n\t\t\tnewMachine = machine\n\n\t\t\tmachines = append(machines, &newMachine)\n\t\t}\n\n\t\treturn iter.Close()\n\t}\n\n\tif err := Mongo.Run(MachineColl, queryFn); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn machines, nil\n}\n\nfunc UpdateMachineAlwaysOn(machineId bson.ObjectId, alwaysOn bool) error {\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Update(\n\t\t\tbson.M{\"_id\": machineId},\n\t\t\tbson.M{\"$set\": bson.M{\"meta.alwaysOn\": alwaysOn}},\n\t\t)\n\t}\n\n\treturn Mongo.Run(MachineColl, query)\n}\n\nfunc CreateMachine(m *models.Machine) error {\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Insert(m)\n\t}\n\n\treturn Mongo.Run(MachineColl, query)\n}\n\n\/\/ DeleteMachine deletes the machine from mongodb, it is here just for cleaning\n\/\/ purposes(after tests), machines should not be removed from database  unless\n\/\/ you are kloud\nfunc DeleteMachine(id bson.ObjectId) error {\n\tselector := bson.M{\"_id\": id}\n\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Remove(selector)\n\t}\n\n\treturn Mongo.Run(MachineColl, query)\n}\n<|endoftext|>"}
{"text":"<commit_before>package py\n\n\/*\n#include \"Python.h\"\nvoid XDecRef(PyObject *o) {\n  Py_XDECREF(o);\n}\n*\/\nimport \"C\"\nimport (\n\t\"pfi\/sensorbee\/py\/mainthread\"\n)\n\n\/\/ Object is a bind of `*C.PyObject`\ntype Object struct {\n\tp *C.PyObject\n}\n\n\/\/ DecRef decrease reference counter of `C.PyObject`\n\/\/ This function is public for API users and\n\/\/ it acquires GIL of Python interpreter.\n\/\/ A user can safely call this method even when its target object is null.\nfunc (o *Object) DecRef() {\n\tmainthread.ExecSync(func() { \/\/ TODO: This Exec should probably be removed.\n\t\tC.XDecRef(o.p)\n\t})\n}\n\n\/\/ decRef decrease reference counter of `C.PyObject`\n\/\/ This function doesn't acquire GIL.\nfunc (o *Object) decRef() {\n\tC.Py_DecRef(o.p)\n}\n<commit_msg>Stop SEGV on Windows.<commit_after>package py\n\n\/*\n#include \"Python.h\"\n*\/\nimport \"C\"\nimport (\n\t\"pfi\/sensorbee\/py\/mainthread\"\n)\n\n\/\/ Object is a bind of `*C.PyObject`\ntype Object struct {\n\tp *C.PyObject\n}\n\n\/\/ DecRef decrease reference counter of `C.PyObject`\n\/\/ This function is public for API users and\n\/\/ it acquires GIL of Python interpreter.\n\/\/ A user can safely call this method even when its target object is null.\nfunc (o *Object) DecRef() {\n\tmainthread.ExecSync(func() { \/\/ TODO: This Exec should probably be removed.\n\t\t\/\/ Py_XDECREF is not used here because it causes SEGV on Windows.\n\t\tif o.p == nil {\n\t\t\treturn\n\t\t}\n\t\tC.Py_DecRef(o.p)\n\t\to.p = nil\n\t})\n}\n\n\/\/ decRef decrease reference counter of `C.PyObject`\n\/\/ This function doesn't acquire GIL.\nfunc (o *Object) decRef() {\n\tC.Py_DecRef(o.p)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"net\/url\"\n\t\"path\"\n\t\"strings\"\n\n\t\"golang.org\/x\/net\/proxy\"\n\t\"golang.org\/x\/net\/websocket\"\n)\n\nvar (\n\tcertsDir = flag.String(\"certs_dir\", \"\", \"Directory of certs for TLS connection to AMQP, or empty for non-TLS connection. \"+\n\t\t\"Expected files are: cacert.pem, cert.pem and key.pem.\")\n\tserverName = flag.String(\"server_name\", \"\", \"Name of the server for TLS verification, or empty for default\")\n\n\ttargetHost = flag.String(\"target_host\", \"\", \"The target host:port to tunnel to\")\n\tport       = flag.Int(\"port\", 8080, \"The local port to listen on\")\n\tlistenAddr = flag.String(\"listen_addr\", \"127.0.0.1\", \"Address to listen on. Empty string for all interfaces.\")\n)\n\nfunc getTlsConfig() (*tls.Config, error) {\n\tif *certsDir == \"\" {\n\t\treturn nil, nil\n\t}\n\n\ttlscfg := &tls.Config{\n\t\tRootCAs:          x509.NewCertPool(),\n\t\tCurvePreferences: []tls.CurveID{tls.CurveP521},\n\t\tMinVersion:       tls.VersionTLS12,\n\t\tCipherSuites:     []uint16{\n            tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n            tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n        },\n\t}\n\tif ca, err := ioutil.ReadFile(path.Join(*certsDir, \"cacert.pem\")); err == nil {\n\t\ttlscfg.RootCAs.AppendCertsFromPEM(ca)\n\t} else {\n\t\treturn nil, fmt.Errorf(\"Failed reading CA certificate: %v\", err)\n\t}\n\n\tif cert, err := tls.LoadX509KeyPair(path.Join(*certsDir, \"\/cert.pem\"), path.Join(*certsDir, \"\/key.pem\")); err == nil {\n\t\ttlscfg.Certificates = append(tlscfg.Certificates, cert)\n\t} else {\n\t\treturn nil, fmt.Errorf(\"Failed reading client certificate: %v\", err)\n\t}\n\n\ttlscfg.ServerName = strings.Split(*targetHost, \":\")[0]\n\tif *serverName != \"\" {\n\t\ttlscfg.ServerName = *serverName\n\t}\n\treturn tlscfg, nil\n}\n\nfunc getWsConfig() (*websocket.Config, error) {\n\turl := url.URL{Scheme: \"ws\", Host: *targetHost}\n\tif *certsDir != \"\" {\n\t\turl.Scheme = \"wss\"\n\t}\n\n\tconfig, err := websocket.NewConfig(url.String(), \"http:\/\/localhost\/\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif config.TlsConfig, err = getTlsConfig(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn config, nil\n}\n\nfunc iocopy(dst io.Writer, src io.Reader, c chan error) {\n\t_, err := io.Copy(dst, src)\n\tc <- err\n}\n\ntype closeable interface {\n\tCloseWrite() error\n}\n\nfunc closeWrite(conn net.Conn) {\n\tif closeme, ok := conn.(closeable); ok {\n\t\tcloseme.CloseWrite()\n\t}\n}\n\nfunc getProxiedConn(turl url.URL) (net.Conn, error) {\n\t\/\/ We first try to get a Socks5 proxied conncetion. If that fails, we're moving on to http{s,}_proxy.\n\tdialer := proxy.FromEnvironment()\n\tif dialer != proxy.Direct {\n\t\treturn dialer.Dial(\"tcp\", turl.Host)\n\t}\n\n\tturl.Scheme = strings.Replace(turl.Scheme, \"ws\", \"http\", 1)\n\tproxyURL, err := http.ProxyFromEnvironment(&http.Request{URL: &turl})\n\tif proxyURL == nil {\n\t\treturn net.Dial(\"tcp\", turl.Host)\n\t}\n\n\tp, err := net.Dial(\"tcp\", proxyURL.Host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcc := httputil.NewProxyClientConn(p, nil)\n\t_, err = cc.Do(&http.Request{\n\t\tMethod: \"CONNECT\",\n\t\tURL:    &url.URL{},\n\t\tHost:   turl.Host,\n\t})\n\tif err != nil && err != httputil.ErrPersistEOF {\n\t\treturn nil, err\n\t}\n\n\tconn, _ := cc.Hijack()\n\n\treturn conn, nil\n}\n\nfunc handleConnection(wsConfig *websocket.Config, conn net.Conn) {\n\tdefer conn.Close()\n\n\ttcp, err := getProxiedConn(*wsConfig.Location)\n\tif err != nil {\n\t\tlog.Print(\"getProxiedConn(): \", err)\n\t\treturn\n\t}\n\n\tif *certsDir != \"\" {\n\t\ttcp = tls.Client(tcp, wsConfig.TlsConfig)\n\t}\n\n\tws, err := websocket.NewClient(wsConfig, tcp)\n\tif err != nil {\n\t\tlog.Print(\"websocket.NewClient(): \", err)\n\t\treturn\n\t}\n\tdefer ws.Close()\n\n\tc := make(chan error, 2)\n\tgo iocopy(ws, conn, c)\n\tgo iocopy(conn, ws, c)\n\n\tfor i := 0; i < 2; i++ {\n\t\tif err := <-c; err != nil {\n\t\t\tfmt.Print(\"io.Copy(): \", err)\n\t\t\treturn\n\t\t}\n\t\t\/\/ If any of the sides closes the connection, we want to close the write channel.\n\t\tcloseWrite(conn)\n\t\tcloseWrite(tcp)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\twsConfig, err := getWsConfig()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tln, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", *listenAddr, *port))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tlog.Print(\"ln.Accept(): \", err)\n\t\t\tcontinue\n\t\t}\n\t\tgo handleConnection(wsConfig, conn)\n\t}\n}\n<commit_msg>Allow other (safe\/secure) curve preferences.<commit_after>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"net\/url\"\n\t\"path\"\n\t\"strings\"\n\n\t\"golang.org\/x\/net\/proxy\"\n\t\"golang.org\/x\/net\/websocket\"\n)\n\nvar (\n\tcertsDir = flag.String(\"certs_dir\", \"\", \"Directory of certs for TLS connection to AMQP, or empty for non-TLS connection. \"+\n\t\t\"Expected files are: cacert.pem, cert.pem and key.pem.\")\n\tserverName = flag.String(\"server_name\", \"\", \"Name of the server for TLS verification, or empty for default\")\n\n\ttargetHost = flag.String(\"target_host\", \"\", \"The target host:port to tunnel to\")\n\tport       = flag.Int(\"port\", 8080, \"The local port to listen on\")\n\tlistenAddr = flag.String(\"listen_addr\", \"127.0.0.1\", \"Address to listen on. Empty string for all interfaces.\")\n)\n\nfunc getTlsConfig() (*tls.Config, error) {\n\tif *certsDir == \"\" {\n\t\treturn nil, nil\n\t}\n\n\ttlscfg := &tls.Config{\n\t\tRootCAs:          x509.NewCertPool(),\n\t\tCurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},\n\t\tMinVersion:       tls.VersionTLS12,\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t},\n\t}\n\tif ca, err := ioutil.ReadFile(path.Join(*certsDir, \"cacert.pem\")); err == nil {\n\t\ttlscfg.RootCAs.AppendCertsFromPEM(ca)\n\t} else {\n\t\treturn nil, fmt.Errorf(\"Failed reading CA certificate: %v\", err)\n\t}\n\n\tif cert, err := tls.LoadX509KeyPair(path.Join(*certsDir, \"\/cert.pem\"), path.Join(*certsDir, \"\/key.pem\")); err == nil {\n\t\ttlscfg.Certificates = append(tlscfg.Certificates, cert)\n\t} else {\n\t\treturn nil, fmt.Errorf(\"Failed reading client certificate: %v\", err)\n\t}\n\n\ttlscfg.ServerName = strings.Split(*targetHost, \":\")[0]\n\tif *serverName != \"\" {\n\t\ttlscfg.ServerName = *serverName\n\t}\n\treturn tlscfg, nil\n}\n\nfunc getWsConfig() (*websocket.Config, error) {\n\turl := url.URL{Scheme: \"ws\", Host: *targetHost}\n\tif *certsDir != \"\" {\n\t\turl.Scheme = \"wss\"\n\t}\n\n\tconfig, err := websocket.NewConfig(url.String(), \"http:\/\/localhost\/\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif config.TlsConfig, err = getTlsConfig(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn config, nil\n}\n\nfunc iocopy(dst io.Writer, src io.Reader, c chan error) {\n\t_, err := io.Copy(dst, src)\n\tc <- err\n}\n\ntype closeable interface {\n\tCloseWrite() error\n}\n\nfunc closeWrite(conn net.Conn) {\n\tif closeme, ok := conn.(closeable); ok {\n\t\tcloseme.CloseWrite()\n\t}\n}\n\nfunc getProxiedConn(turl url.URL) (net.Conn, error) {\n\t\/\/ We first try to get a Socks5 proxied conncetion. If that fails, we're moving on to http{s,}_proxy.\n\tdialer := proxy.FromEnvironment()\n\tif dialer != proxy.Direct {\n\t\treturn dialer.Dial(\"tcp\", turl.Host)\n\t}\n\n\tturl.Scheme = strings.Replace(turl.Scheme, \"ws\", \"http\", 1)\n\tproxyURL, err := http.ProxyFromEnvironment(&http.Request{URL: &turl})\n\tif proxyURL == nil {\n\t\treturn net.Dial(\"tcp\", turl.Host)\n\t}\n\n\tp, err := net.Dial(\"tcp\", proxyURL.Host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcc := httputil.NewProxyClientConn(p, nil)\n\t_, err = cc.Do(&http.Request{\n\t\tMethod: \"CONNECT\",\n\t\tURL:    &url.URL{},\n\t\tHost:   turl.Host,\n\t})\n\tif err != nil && err != httputil.ErrPersistEOF {\n\t\treturn nil, err\n\t}\n\n\tconn, _ := cc.Hijack()\n\n\treturn conn, nil\n}\n\nfunc handleConnection(wsConfig *websocket.Config, conn net.Conn) {\n\tdefer conn.Close()\n\n\ttcp, err := getProxiedConn(*wsConfig.Location)\n\tif err != nil {\n\t\tlog.Print(\"getProxiedConn(): \", err)\n\t\treturn\n\t}\n\n\tif *certsDir != \"\" {\n\t\ttcp = tls.Client(tcp, wsConfig.TlsConfig)\n\t}\n\n\tws, err := websocket.NewClient(wsConfig, tcp)\n\tif err != nil {\n\t\tlog.Print(\"websocket.NewClient(): \", err)\n\t\treturn\n\t}\n\tdefer ws.Close()\n\n\tc := make(chan error, 2)\n\tgo iocopy(ws, conn, c)\n\tgo iocopy(conn, ws, c)\n\n\tfor i := 0; i < 2; i++ {\n\t\tif err := <-c; err != nil {\n\t\t\tfmt.Print(\"io.Copy(): \", err)\n\t\t\treturn\n\t\t}\n\t\t\/\/ If any of the sides closes the connection, we want to close the write channel.\n\t\tcloseWrite(conn)\n\t\tcloseWrite(tcp)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\twsConfig, err := getWsConfig()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tln, err := net.Listen(\"tcp\", fmt.Sprintf(\"%s:%d\", *listenAddr, *port))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tlog.Print(\"ln.Accept(): \", err)\n\t\t\tcontinue\n\t\t}\n\t\tgo handleConnection(wsConfig, conn)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package quic\n\nimport (\n\t\"context\"\n\t\"crypto\/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/protocol\"\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/utils\"\n\t\"github.com\/lucas-clemente\/quic-go\/logging\"\n)\n\ntype client struct {\n\tmutex sync.Mutex\n\n\tconn sendConn\n\t\/\/ If the client is created with DialAddr, we create a packet conn.\n\t\/\/ If it is started with Dial, we take a packet conn as a parameter.\n\tcreatedPacketConn bool\n\n\tuse0RTT bool\n\n\tpacketHandlers packetHandlerManager\n\n\ttlsConf *tls.Config\n\tconfig  *Config\n\n\tsrcConnID  protocol.ConnectionID\n\tdestConnID protocol.ConnectionID\n\n\tinitialPacketNumber  protocol.PacketNumber\n\thasNegotiatedVersion bool\n\tversion              protocol.VersionNumber\n\n\thandshakeChan chan struct{}\n\n\tsession quicSession\n\n\ttracer logging.ConnectionTracer\n\tlogger utils.Logger\n}\n\nvar (\n\t\/\/ make it possible to mock connection ID generation in the tests\n\tgenerateConnectionID           = protocol.GenerateConnectionID\n\tgenerateConnectionIDForInitial = protocol.GenerateConnectionIDForInitial\n)\n\n\/\/ DialAddr establishes a new QUIC connection to a server.\n\/\/ It uses a new UDP connection and closes this connection when the QUIC session is closed.\n\/\/ The hostname for SNI is taken from the given address.\n\/\/ The tls.Config.CipherSuites allows setting of TLS 1.3 cipher suites.\nfunc DialAddr(\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn DialAddrContext(context.Background(), addr, tlsConf, config)\n}\n\n\/\/ DialAddrEarly establishes a new 0-RTT QUIC connection to a server.\n\/\/ It uses a new UDP connection and closes this connection when the QUIC session is closed.\n\/\/ The hostname for SNI is taken from the given address.\n\/\/ The tls.Config.CipherSuites allows setting of TLS 1.3 cipher suites.\nfunc DialAddrEarly(\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (EarlySession, error) {\n\tsess, err := dialAddrContext(context.Background(), addr, tlsConf, config, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tutils.Logger.WithPrefix(utils.DefaultLogger, \"client\").Debugf(\"Returning early session\")\n\treturn sess, nil\n}\n\n\/\/ DialAddrContext establishes a new QUIC connection to a server using the provided context.\n\/\/ See DialAddr for details.\nfunc DialAddrContext(\n\tctx context.Context,\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialAddrContext(ctx, addr, tlsConf, config, false)\n}\n\nfunc dialAddrContext(\n\tctx context.Context,\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n\tuse0RTT bool,\n) (quicSession, error) {\n\tudpAddr, err := net.ResolveUDPAddr(\"udp\", addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tudpConn, err := net.ListenUDP(\"udp\", &net.UDPAddr{IP: net.IPv4zero, Port: 0})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dialContext(ctx, udpConn, udpAddr, addr, tlsConf, config, use0RTT, true)\n}\n\n\/\/ Dial establishes a new QUIC connection to a server using a net.PacketConn.\n\/\/ If the PacketConn satisfies the ECNCapablePacketConn interface (as a net.UDPConn does), ECN support will be enabled.\n\/\/ In this case, ReadMsgUDP will be used instead of ReadFrom to read packets.\n\/\/ The same PacketConn can be used for multiple calls to Dial and Listen,\n\/\/ QUIC connection IDs are used for demultiplexing the different connections.\n\/\/ The host parameter is used for SNI.\n\/\/ The tls.Config must define an application protocol (using NextProtos).\nfunc Dial(\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialContext(context.Background(), pconn, remoteAddr, host, tlsConf, config, false, false)\n}\n\n\/\/ DialEarly establishes a new 0-RTT QUIC connection to a server using a net.PacketConn.\n\/\/ The same PacketConn can be used for multiple calls to Dial and Listen,\n\/\/ QUIC connection IDs are used for demultiplexing the different connections.\n\/\/ The host parameter is used for SNI.\n\/\/ The tls.Config must define an application protocol (using NextProtos).\nfunc DialEarly(\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (EarlySession, error) {\n\treturn dialContext(context.Background(), pconn, remoteAddr, host, tlsConf, config, true, false)\n}\n\n\/\/ DialContext establishes a new QUIC connection to a server using a net.PacketConn using the provided context.\n\/\/ See Dial for details.\nfunc DialContext(\n\tctx context.Context,\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialContext(ctx, pconn, remoteAddr, host, tlsConf, config, false, false)\n}\n\nfunc dialContext(\n\tctx context.Context,\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n\tuse0RTT bool,\n\tcreatedPacketConn bool,\n) (quicSession, error) {\n\tif tlsConf == nil {\n\t\treturn nil, errors.New(\"quic: tls.Config not set\")\n\t}\n\tif err := validateConfig(config); err != nil {\n\t\treturn nil, err\n\t}\n\tconfig = populateClientConfig(config, createdPacketConn)\n\tpacketHandlers, err := getMultiplexer().AddConn(pconn, config.ConnectionIDLength, config.StatelessResetKey, config.Tracer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := newClient(pconn, remoteAddr, config, tlsConf, host, use0RTT, createdPacketConn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.packetHandlers = packetHandlers\n\n\tif c.config.Tracer != nil {\n\t\tc.tracer = c.config.Tracer.TracerForConnection(protocol.PerspectiveClient, c.destConnID)\n\t}\n\tif err := c.dial(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.session, nil\n}\n\nfunc newClient(\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\tconfig *Config,\n\ttlsConf *tls.Config,\n\thost string,\n\tuse0RTT bool,\n\tcreatedPacketConn bool,\n) (*client, error) {\n\tif tlsConf == nil {\n\t\ttlsConf = &tls.Config{}\n\t}\n\tif tlsConf.ServerName == \"\" {\n\t\tsni := host\n\t\tif strings.IndexByte(sni, ':') != -1 {\n\t\t\tvar err error\n\t\t\tsni, _, err = net.SplitHostPort(sni)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\ttlsConf.ServerName = sni\n\t}\n\n\t\/\/ check that all versions are actually supported\n\tif config != nil {\n\t\tfor _, v := range config.Versions {\n\t\t\tif !protocol.IsValidVersion(v) {\n\t\t\t\treturn nil, fmt.Errorf(\"%s is not a valid QUIC version\", v)\n\t\t\t}\n\t\t}\n\t}\n\n\tsrcConnID, err := generateConnectionID(config.ConnectionIDLength)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdestConnID, err := generateConnectionIDForInitial()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &client{\n\t\tsrcConnID:         srcConnID,\n\t\tdestConnID:        destConnID,\n\t\tconn:              newSendConn(pconn, remoteAddr),\n\t\tcreatedPacketConn: createdPacketConn,\n\t\tuse0RTT:           use0RTT,\n\t\ttlsConf:           tlsConf,\n\t\tconfig:            config,\n\t\tversion:           config.Versions[0],\n\t\thandshakeChan:     make(chan struct{}),\n\t\tlogger:            utils.DefaultLogger.WithPrefix(\"client\"),\n\t}\n\treturn c, nil\n}\n\nfunc (c *client) dial(ctx context.Context) error {\n\tc.logger.Infof(\"Starting new connection to %s (%s -> %s), source connection ID %s, destination connection ID %s, version %s\", c.tlsConf.ServerName, c.conn.LocalAddr(), c.conn.RemoteAddr(), c.srcConnID, c.destConnID, c.version)\n\tif c.tracer != nil {\n\t\tc.tracer.StartedConnection(c.conn.LocalAddr(), c.conn.RemoteAddr(), c.version, c.srcConnID, c.destConnID)\n\t}\n\n\tc.mutex.Lock()\n\tc.session = newClientSession(\n\t\tc.conn,\n\t\tc.packetHandlers,\n\t\tc.destConnID,\n\t\tc.srcConnID,\n\t\tc.config,\n\t\tc.tlsConf,\n\t\tc.initialPacketNumber,\n\t\tc.version,\n\t\tc.use0RTT,\n\t\tc.hasNegotiatedVersion,\n\t\tc.tracer,\n\t\tc.logger,\n\t\tc.version,\n\t)\n\tc.mutex.Unlock()\n\tc.packetHandlers.Add(c.srcConnID, c.session)\n\n\terrorChan := make(chan error, 1)\n\tgo func() {\n\t\terr := c.session.run() \/\/ returns as soon as the session is closed\n\t\tif !errors.Is(err, errCloseForRecreating{}) && c.createdPacketConn {\n\t\t\tc.packetHandlers.Destroy()\n\t\t}\n\t\terrorChan <- err\n\t}()\n\n\t\/\/ only set when we're using 0-RTT\n\t\/\/ Otherwise, earlySessionChan will be nil. Receiving from a nil chan blocks forever.\n\tvar earlySessionChan <-chan struct{}\n\tif c.use0RTT {\n\t\tearlySessionChan = c.session.earlySessionReady()\n\t}\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tc.session.shutdown()\n\t\treturn ctx.Err()\n\tcase err := <-errorChan:\n\t\tvar recreateErr *errCloseForRecreating\n\t\tif errors.As(err, &recreateErr) {\n\t\t\tc.initialPacketNumber = recreateErr.nextPacketNumber\n\t\t\tc.version = recreateErr.nextVersion\n\t\t\tc.hasNegotiatedVersion = true\n\t\t\treturn c.dial(ctx)\n\t\t}\n\t\treturn err\n\tcase <-earlySessionChan:\n\t\t\/\/ ready to send 0-RTT data\n\t\treturn nil\n\tcase <-c.session.HandshakeComplete().Done():\n\t\t\/\/ handshake successfully completed\n\t\treturn nil\n\t}\n}\n<commit_msg>remove unnecessary locking<commit_after>package quic\n\nimport (\n\t\"context\"\n\t\"crypto\/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/protocol\"\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/utils\"\n\t\"github.com\/lucas-clemente\/quic-go\/logging\"\n)\n\ntype client struct {\n\tconn sendConn\n\t\/\/ If the client is created with DialAddr, we create a packet conn.\n\t\/\/ If it is started with Dial, we take a packet conn as a parameter.\n\tcreatedPacketConn bool\n\n\tuse0RTT bool\n\n\tpacketHandlers packetHandlerManager\n\n\ttlsConf *tls.Config\n\tconfig  *Config\n\n\tsrcConnID  protocol.ConnectionID\n\tdestConnID protocol.ConnectionID\n\n\tinitialPacketNumber  protocol.PacketNumber\n\thasNegotiatedVersion bool\n\tversion              protocol.VersionNumber\n\n\thandshakeChan chan struct{}\n\n\tsession quicSession\n\n\ttracer logging.ConnectionTracer\n\tlogger utils.Logger\n}\n\nvar (\n\t\/\/ make it possible to mock connection ID generation in the tests\n\tgenerateConnectionID           = protocol.GenerateConnectionID\n\tgenerateConnectionIDForInitial = protocol.GenerateConnectionIDForInitial\n)\n\n\/\/ DialAddr establishes a new QUIC connection to a server.\n\/\/ It uses a new UDP connection and closes this connection when the QUIC session is closed.\n\/\/ The hostname for SNI is taken from the given address.\n\/\/ The tls.Config.CipherSuites allows setting of TLS 1.3 cipher suites.\nfunc DialAddr(\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn DialAddrContext(context.Background(), addr, tlsConf, config)\n}\n\n\/\/ DialAddrEarly establishes a new 0-RTT QUIC connection to a server.\n\/\/ It uses a new UDP connection and closes this connection when the QUIC session is closed.\n\/\/ The hostname for SNI is taken from the given address.\n\/\/ The tls.Config.CipherSuites allows setting of TLS 1.3 cipher suites.\nfunc DialAddrEarly(\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (EarlySession, error) {\n\tsess, err := dialAddrContext(context.Background(), addr, tlsConf, config, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tutils.Logger.WithPrefix(utils.DefaultLogger, \"client\").Debugf(\"Returning early session\")\n\treturn sess, nil\n}\n\n\/\/ DialAddrContext establishes a new QUIC connection to a server using the provided context.\n\/\/ See DialAddr for details.\nfunc DialAddrContext(\n\tctx context.Context,\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialAddrContext(ctx, addr, tlsConf, config, false)\n}\n\nfunc dialAddrContext(\n\tctx context.Context,\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n\tuse0RTT bool,\n) (quicSession, error) {\n\tudpAddr, err := net.ResolveUDPAddr(\"udp\", addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tudpConn, err := net.ListenUDP(\"udp\", &net.UDPAddr{IP: net.IPv4zero, Port: 0})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dialContext(ctx, udpConn, udpAddr, addr, tlsConf, config, use0RTT, true)\n}\n\n\/\/ Dial establishes a new QUIC connection to a server using a net.PacketConn.\n\/\/ If the PacketConn satisfies the ECNCapablePacketConn interface (as a net.UDPConn does), ECN support will be enabled.\n\/\/ In this case, ReadMsgUDP will be used instead of ReadFrom to read packets.\n\/\/ The same PacketConn can be used for multiple calls to Dial and Listen,\n\/\/ QUIC connection IDs are used for demultiplexing the different connections.\n\/\/ The host parameter is used for SNI.\n\/\/ The tls.Config must define an application protocol (using NextProtos).\nfunc Dial(\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialContext(context.Background(), pconn, remoteAddr, host, tlsConf, config, false, false)\n}\n\n\/\/ DialEarly establishes a new 0-RTT QUIC connection to a server using a net.PacketConn.\n\/\/ The same PacketConn can be used for multiple calls to Dial and Listen,\n\/\/ QUIC connection IDs are used for demultiplexing the different connections.\n\/\/ The host parameter is used for SNI.\n\/\/ The tls.Config must define an application protocol (using NextProtos).\nfunc DialEarly(\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (EarlySession, error) {\n\treturn dialContext(context.Background(), pconn, remoteAddr, host, tlsConf, config, true, false)\n}\n\n\/\/ DialContext establishes a new QUIC connection to a server using a net.PacketConn using the provided context.\n\/\/ See Dial for details.\nfunc DialContext(\n\tctx context.Context,\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialContext(ctx, pconn, remoteAddr, host, tlsConf, config, false, false)\n}\n\nfunc dialContext(\n\tctx context.Context,\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n\tuse0RTT bool,\n\tcreatedPacketConn bool,\n) (quicSession, error) {\n\tif tlsConf == nil {\n\t\treturn nil, errors.New(\"quic: tls.Config not set\")\n\t}\n\tif err := validateConfig(config); err != nil {\n\t\treturn nil, err\n\t}\n\tconfig = populateClientConfig(config, createdPacketConn)\n\tpacketHandlers, err := getMultiplexer().AddConn(pconn, config.ConnectionIDLength, config.StatelessResetKey, config.Tracer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := newClient(pconn, remoteAddr, config, tlsConf, host, use0RTT, createdPacketConn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.packetHandlers = packetHandlers\n\n\tif c.config.Tracer != nil {\n\t\tc.tracer = c.config.Tracer.TracerForConnection(protocol.PerspectiveClient, c.destConnID)\n\t}\n\tif err := c.dial(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.session, nil\n}\n\nfunc newClient(\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\tconfig *Config,\n\ttlsConf *tls.Config,\n\thost string,\n\tuse0RTT bool,\n\tcreatedPacketConn bool,\n) (*client, error) {\n\tif tlsConf == nil {\n\t\ttlsConf = &tls.Config{}\n\t}\n\tif tlsConf.ServerName == \"\" {\n\t\tsni := host\n\t\tif strings.IndexByte(sni, ':') != -1 {\n\t\t\tvar err error\n\t\t\tsni, _, err = net.SplitHostPort(sni)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\ttlsConf.ServerName = sni\n\t}\n\n\t\/\/ check that all versions are actually supported\n\tif config != nil {\n\t\tfor _, v := range config.Versions {\n\t\t\tif !protocol.IsValidVersion(v) {\n\t\t\t\treturn nil, fmt.Errorf(\"%s is not a valid QUIC version\", v)\n\t\t\t}\n\t\t}\n\t}\n\n\tsrcConnID, err := generateConnectionID(config.ConnectionIDLength)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdestConnID, err := generateConnectionIDForInitial()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &client{\n\t\tsrcConnID:         srcConnID,\n\t\tdestConnID:        destConnID,\n\t\tconn:              newSendConn(pconn, remoteAddr),\n\t\tcreatedPacketConn: createdPacketConn,\n\t\tuse0RTT:           use0RTT,\n\t\ttlsConf:           tlsConf,\n\t\tconfig:            config,\n\t\tversion:           config.Versions[0],\n\t\thandshakeChan:     make(chan struct{}),\n\t\tlogger:            utils.DefaultLogger.WithPrefix(\"client\"),\n\t}\n\treturn c, nil\n}\n\nfunc (c *client) dial(ctx context.Context) error {\n\tc.logger.Infof(\"Starting new connection to %s (%s -> %s), source connection ID %s, destination connection ID %s, version %s\", c.tlsConf.ServerName, c.conn.LocalAddr(), c.conn.RemoteAddr(), c.srcConnID, c.destConnID, c.version)\n\tif c.tracer != nil {\n\t\tc.tracer.StartedConnection(c.conn.LocalAddr(), c.conn.RemoteAddr(), c.version, c.srcConnID, c.destConnID)\n\t}\n\n\tc.session = newClientSession(\n\t\tc.conn,\n\t\tc.packetHandlers,\n\t\tc.destConnID,\n\t\tc.srcConnID,\n\t\tc.config,\n\t\tc.tlsConf,\n\t\tc.initialPacketNumber,\n\t\tc.version,\n\t\tc.use0RTT,\n\t\tc.hasNegotiatedVersion,\n\t\tc.tracer,\n\t\tc.logger,\n\t\tc.version,\n\t)\n\tc.packetHandlers.Add(c.srcConnID, c.session)\n\n\terrorChan := make(chan error, 1)\n\tgo func() {\n\t\terr := c.session.run() \/\/ returns as soon as the session is closed\n\t\tif !errors.Is(err, errCloseForRecreating{}) && c.createdPacketConn {\n\t\t\tc.packetHandlers.Destroy()\n\t\t}\n\t\terrorChan <- err\n\t}()\n\n\t\/\/ only set when we're using 0-RTT\n\t\/\/ Otherwise, earlySessionChan will be nil. Receiving from a nil chan blocks forever.\n\tvar earlySessionChan <-chan struct{}\n\tif c.use0RTT {\n\t\tearlySessionChan = c.session.earlySessionReady()\n\t}\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tc.session.shutdown()\n\t\treturn ctx.Err()\n\tcase err := <-errorChan:\n\t\tvar recreateErr *errCloseForRecreating\n\t\tif errors.As(err, &recreateErr) {\n\t\t\tc.initialPacketNumber = recreateErr.nextPacketNumber\n\t\t\tc.version = recreateErr.nextVersion\n\t\t\tc.hasNegotiatedVersion = true\n\t\t\treturn c.dial(ctx)\n\t\t}\n\t\treturn err\n\tcase <-earlySessionChan:\n\t\t\/\/ ready to send 0-RTT data\n\t\treturn nil\n\tcase <-c.session.HandshakeComplete().Done():\n\t\t\/\/ handshake successfully completed\n\t\treturn nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package quic\n\nimport (\n\t\"context\"\n\t\"crypto\/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/protocol\"\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/utils\"\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/wire\"\n\t\"github.com\/lucas-clemente\/quic-go\/qlog\"\n)\n\ntype client struct {\n\tmutex sync.Mutex\n\n\tconn connection\n\t\/\/ If the client is created with DialAddr, we create a packet conn.\n\t\/\/ If it is started with Dial, we take a packet conn as a parameter.\n\tcreatedPacketConn bool\n\n\tuse0RTT bool\n\n\tpacketHandlers packetHandlerManager\n\n\tversionNegotiated                utils.AtomicBool \/\/ has the server accepted our version\n\treceivedVersionNegotiationPacket bool\n\tnegotiatedVersions               []protocol.VersionNumber \/\/ the list of versions from the version negotiation packet\n\n\ttlsConf *tls.Config\n\tconfig  *Config\n\n\tsrcConnID  protocol.ConnectionID\n\tdestConnID protocol.ConnectionID\n\n\tinitialPacketNumber protocol.PacketNumber\n\n\tinitialVersion protocol.VersionNumber\n\tversion        protocol.VersionNumber\n\n\thandshakeChan chan struct{}\n\n\tsession quicSession\n\n\tlogger utils.Logger\n}\n\nvar _ packetHandler = &client{}\n\nvar (\n\t\/\/ make it possible to mock connection ID generation in the tests\n\tgenerateConnectionID           = protocol.GenerateConnectionID\n\tgenerateConnectionIDForInitial = protocol.GenerateConnectionIDForInitial\n)\n\n\/\/ DialAddr establishes a new QUIC connection to a server.\n\/\/ It uses a new UDP connection and closes this connection when the QUIC session is closed.\n\/\/ The hostname for SNI is taken from the given address.\n\/\/ The tls.Config.CipherSuites allows setting of TLS 1.3 cipher suites.\nfunc DialAddr(\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn DialAddrContext(context.Background(), addr, tlsConf, config)\n}\n\n\/\/ DialAddrEarly establishes a new 0-RTT QUIC connection to a server.\n\/\/ It uses a new UDP connection and closes this connection when the QUIC session is closed.\n\/\/ The hostname for SNI is taken from the given address.\n\/\/ The tls.Config.CipherSuites allows setting of TLS 1.3 cipher suites.\nfunc DialAddrEarly(\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (EarlySession, error) {\n\tdefer utils.Logger.WithPrefix(utils.DefaultLogger, \"client\").Debugf(\"Returning early session\")\n\treturn dialAddrContext(context.Background(), addr, tlsConf, config, true)\n}\n\n\/\/ DialAddrContext establishes a new QUIC connection to a server using the provided context.\n\/\/ See DialAddr for details.\nfunc DialAddrContext(\n\tctx context.Context,\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialAddrContext(ctx, addr, tlsConf, config, false)\n}\n\nfunc dialAddrContext(\n\tctx context.Context,\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n\tuse0RTT bool,\n) (quicSession, error) {\n\tudpAddr, err := net.ResolveUDPAddr(\"udp\", addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tudpConn, err := net.ListenUDP(\"udp\", &net.UDPAddr{IP: net.IPv4zero, Port: 0})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dialContext(ctx, udpConn, udpAddr, addr, tlsConf, config, use0RTT, true)\n}\n\n\/\/ Dial establishes a new QUIC connection to a server using a net.PacketConn.\n\/\/ The same PacketConn can be used for multiple calls to Dial and Listen,\n\/\/ QUIC connection IDs are used for demultiplexing the different connections.\n\/\/ The host parameter is used for SNI.\n\/\/ The tls.Config must define an application protocol (using NextProtos).\nfunc Dial(\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialContext(context.Background(), pconn, remoteAddr, host, tlsConf, config, false, false)\n}\n\n\/\/ DialEarly establishes a new 0-RTT QUIC connection to a server using a net.PacketConn.\n\/\/ The same PacketConn can be used for multiple calls to Dial and Listen,\n\/\/ QUIC connection IDs are used for demultiplexing the different connections.\n\/\/ The host parameter is used for SNI.\n\/\/ The tls.Config must define an application protocol (using NextProtos).\nfunc DialEarly(\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialContext(context.Background(), pconn, remoteAddr, host, tlsConf, config, true, false)\n}\n\n\/\/ DialContext establishes a new QUIC connection to a server using a net.PacketConn using the provided context.\n\/\/ See Dial for details.\nfunc DialContext(\n\tctx context.Context,\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialContext(ctx, pconn, remoteAddr, host, tlsConf, config, false, false)\n}\n\nfunc dialContext(\n\tctx context.Context,\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n\tuse0RTT bool,\n\tcreatedPacketConn bool,\n) (quicSession, error) {\n\tif tlsConf == nil {\n\t\treturn nil, errors.New(\"quic: tls.Config not set\")\n\t}\n\tconfig = populateClientConfig(config, createdPacketConn)\n\tpacketHandlers, err := getMultiplexer().AddConn(pconn, config.ConnectionIDLength, config.StatelessResetKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := newClient(pconn, remoteAddr, config, tlsConf, host, use0RTT, createdPacketConn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.packetHandlers = packetHandlers\n\n\tvar qlogger qlog.Tracer\n\tif c.config.GetLogWriter != nil {\n\t\tif w := c.config.GetLogWriter(c.destConnID); w != nil {\n\t\t\tqlogger = qlog.NewTracer(w, protocol.PerspectiveClient, c.destConnID)\n\t\t}\n\t}\n\tif err := c.dial(ctx, qlogger); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.session, nil\n}\n\nfunc newClient(\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\tconfig *Config,\n\ttlsConf *tls.Config,\n\thost string,\n\tuse0RTT bool,\n\tcreatedPacketConn bool,\n) (*client, error) {\n\tif tlsConf == nil {\n\t\ttlsConf = &tls.Config{}\n\t}\n\tif tlsConf.ServerName == \"\" {\n\t\tsni := host\n\t\tif strings.IndexByte(sni, ':') != -1 {\n\t\t\tvar err error\n\t\t\tsni, _, err = net.SplitHostPort(sni)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\ttlsConf.ServerName = sni\n\t}\n\n\t\/\/ check that all versions are actually supported\n\tif config != nil {\n\t\tfor _, v := range config.Versions {\n\t\t\tif !protocol.IsValidVersion(v) {\n\t\t\t\treturn nil, fmt.Errorf(\"%s is not a valid QUIC version\", v)\n\t\t\t}\n\t\t}\n\t}\n\n\tsrcConnID, err := generateConnectionID(config.ConnectionIDLength)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdestConnID, err := generateConnectionIDForInitial()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &client{\n\t\tsrcConnID:         srcConnID,\n\t\tdestConnID:        destConnID,\n\t\tconn:              &conn{pconn: pconn, currentAddr: remoteAddr},\n\t\tcreatedPacketConn: createdPacketConn,\n\t\tuse0RTT:           use0RTT,\n\t\ttlsConf:           tlsConf,\n\t\tconfig:            config,\n\t\tversion:           config.Versions[0],\n\t\thandshakeChan:     make(chan struct{}),\n\t\tlogger:            utils.DefaultLogger.WithPrefix(\"client\"),\n\t}\n\treturn c, nil\n}\n\nfunc (c *client) dial(ctx context.Context, qlogger qlog.Tracer) error {\n\tc.logger.Infof(\"Starting new connection to %s (%s -> %s), source connection ID %s, destination connection ID %s, version %s\", c.tlsConf.ServerName, c.conn.LocalAddr(), c.conn.RemoteAddr(), c.srcConnID, c.destConnID, c.version)\n\tif qlogger != nil {\n\t\tqlogger.StartedConnection(c.conn.LocalAddr(), c.conn.LocalAddr(), c.version, c.srcConnID, c.destConnID)\n\t}\n\n\tc.mutex.Lock()\n\tc.session = newClientSession(\n\t\tc.conn,\n\t\tc.packetHandlers,\n\t\tc.destConnID,\n\t\tc.srcConnID,\n\t\tc.config,\n\t\tc.tlsConf,\n\t\tc.initialPacketNumber,\n\t\tc.initialVersion,\n\t\tc.use0RTT,\n\t\tqlogger,\n\t\tc.logger,\n\t\tc.version,\n\t)\n\tc.mutex.Unlock()\n\t\/\/ It's not possible to use the stateless reset token for the client's (first) connection ID,\n\t\/\/ since there's no way to securely communicate it to the server.\n\tc.packetHandlers.Add(c.srcConnID, c)\n\n\terrorChan := make(chan error, 1)\n\tgo func() {\n\t\terr := c.session.run() \/\/ returns as soon as the session is closed\n\t\tif err != errCloseForRecreating && c.createdPacketConn {\n\t\t\tc.packetHandlers.Destroy()\n\t\t}\n\t\terrorChan <- err\n\t}()\n\n\t\/\/ only set when we're using 0-RTT\n\t\/\/ Otherwise, earlySessionChan will be nil. Receiving from a nil chan blocks forever.\n\tvar earlySessionChan <-chan struct{}\n\tif c.use0RTT {\n\t\tearlySessionChan = c.session.earlySessionReady()\n\t}\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tc.session.shutdown()\n\t\treturn ctx.Err()\n\tcase err := <-errorChan:\n\t\tif err == errCloseForRecreating {\n\t\t\treturn c.dial(ctx, qlogger)\n\t\t}\n\t\treturn err\n\tcase <-earlySessionChan:\n\t\t\/\/ ready to send 0-RTT data\n\t\treturn nil\n\tcase <-c.session.HandshakeComplete().Done():\n\t\t\/\/ handshake successfully completed\n\t\treturn nil\n\t}\n}\n\nfunc (c *client) handlePacket(p *receivedPacket) {\n\tif wire.IsVersionNegotiationPacket(p.data) {\n\t\tgo c.handleVersionNegotiationPacket(p)\n\t\treturn\n\t}\n\n\t\/\/ this is the first packet we are receiving\n\t\/\/ since it is not a Version Negotiation Packet, this means the server supports the suggested version\n\tif !c.versionNegotiated.Get() {\n\t\tc.versionNegotiated.Set(true)\n\t}\n\n\tc.session.handlePacket(p)\n}\n\nfunc (c *client) handleVersionNegotiationPacket(p *receivedPacket) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\thdr, _, _, err := wire.ParsePacket(p.data, 0)\n\tif err != nil {\n\t\tc.logger.Debugf(\"Error parsing Version Negotiation packet: %s\", err)\n\t\treturn\n\t}\n\n\t\/\/ ignore delayed \/ duplicated version negotiation packets\n\tif c.receivedVersionNegotiationPacket || c.versionNegotiated.Get() {\n\t\tc.logger.Debugf(\"Received a delayed Version Negotiation packet.\")\n\t\treturn\n\t}\n\n\tfor _, v := range hdr.SupportedVersions {\n\t\tif v == c.version {\n\t\t\t\/\/ The Version Negotiation packet contains the version that we offered.\n\t\t\t\/\/ This might be a packet sent by an attacker (or by a terribly broken server implementation).\n\t\t\treturn\n\t\t}\n\t}\n\n\tc.logger.Infof(\"Received a Version Negotiation packet. Supported Versions: %s\", hdr.SupportedVersions)\n\tnewVersion, ok := protocol.ChooseSupportedVersion(c.config.Versions, hdr.SupportedVersions)\n\tif !ok {\n\t\t\/\/nolint:stylecheck\n\t\tc.session.destroy(fmt.Errorf(\"No compatible QUIC version found. We support %s, server offered %s\", c.config.Versions, hdr.SupportedVersions))\n\t\tc.logger.Debugf(\"No compatible QUIC version found.\")\n\t\treturn\n\t}\n\tc.receivedVersionNegotiationPacket = true\n\tc.negotiatedVersions = hdr.SupportedVersions\n\n\t\/\/ switch to negotiated version\n\tc.initialVersion = c.version\n\tc.version = newVersion\n\n\tc.logger.Infof(\"Switching to QUIC version %s. New connection ID: %s\", newVersion, c.destConnID)\n\tc.initialPacketNumber = c.session.closeForRecreating()\n}\n\nfunc (c *client) shutdown() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tif c.session == nil {\n\t\treturn\n\t}\n\tc.session.shutdown()\n}\n\nfunc (c *client) destroy(e error) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tif c.session == nil {\n\t\treturn\n\t}\n\tc.session.destroy(e)\n}\n\nfunc (c *client) GetVersion() protocol.VersionNumber {\n\tc.mutex.Lock()\n\tv := c.version\n\tc.mutex.Unlock()\n\treturn v\n}\n\nfunc (c *client) getPerspective() protocol.Perspective {\n\treturn protocol.PerspectiveClient\n}\n<commit_msg>set the qlogger as a member variable on the client<commit_after>package quic\n\nimport (\n\t\"context\"\n\t\"crypto\/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/protocol\"\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/utils\"\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/wire\"\n\t\"github.com\/lucas-clemente\/quic-go\/qlog\"\n)\n\ntype client struct {\n\tmutex sync.Mutex\n\n\tconn connection\n\t\/\/ If the client is created with DialAddr, we create a packet conn.\n\t\/\/ If it is started with Dial, we take a packet conn as a parameter.\n\tcreatedPacketConn bool\n\n\tuse0RTT bool\n\n\tpacketHandlers packetHandlerManager\n\n\tversionNegotiated                utils.AtomicBool \/\/ has the server accepted our version\n\treceivedVersionNegotiationPacket bool\n\tnegotiatedVersions               []protocol.VersionNumber \/\/ the list of versions from the version negotiation packet\n\n\ttlsConf *tls.Config\n\tconfig  *Config\n\n\tsrcConnID  protocol.ConnectionID\n\tdestConnID protocol.ConnectionID\n\n\tinitialPacketNumber protocol.PacketNumber\n\n\tinitialVersion protocol.VersionNumber\n\tversion        protocol.VersionNumber\n\n\thandshakeChan chan struct{}\n\n\tsession quicSession\n\n\tqlogger qlog.Tracer\n\tlogger  utils.Logger\n}\n\nvar _ packetHandler = &client{}\n\nvar (\n\t\/\/ make it possible to mock connection ID generation in the tests\n\tgenerateConnectionID           = protocol.GenerateConnectionID\n\tgenerateConnectionIDForInitial = protocol.GenerateConnectionIDForInitial\n)\n\n\/\/ DialAddr establishes a new QUIC connection to a server.\n\/\/ It uses a new UDP connection and closes this connection when the QUIC session is closed.\n\/\/ The hostname for SNI is taken from the given address.\n\/\/ The tls.Config.CipherSuites allows setting of TLS 1.3 cipher suites.\nfunc DialAddr(\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn DialAddrContext(context.Background(), addr, tlsConf, config)\n}\n\n\/\/ DialAddrEarly establishes a new 0-RTT QUIC connection to a server.\n\/\/ It uses a new UDP connection and closes this connection when the QUIC session is closed.\n\/\/ The hostname for SNI is taken from the given address.\n\/\/ The tls.Config.CipherSuites allows setting of TLS 1.3 cipher suites.\nfunc DialAddrEarly(\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (EarlySession, error) {\n\tdefer utils.Logger.WithPrefix(utils.DefaultLogger, \"client\").Debugf(\"Returning early session\")\n\treturn dialAddrContext(context.Background(), addr, tlsConf, config, true)\n}\n\n\/\/ DialAddrContext establishes a new QUIC connection to a server using the provided context.\n\/\/ See DialAddr for details.\nfunc DialAddrContext(\n\tctx context.Context,\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialAddrContext(ctx, addr, tlsConf, config, false)\n}\n\nfunc dialAddrContext(\n\tctx context.Context,\n\taddr string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n\tuse0RTT bool,\n) (quicSession, error) {\n\tudpAddr, err := net.ResolveUDPAddr(\"udp\", addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tudpConn, err := net.ListenUDP(\"udp\", &net.UDPAddr{IP: net.IPv4zero, Port: 0})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn dialContext(ctx, udpConn, udpAddr, addr, tlsConf, config, use0RTT, true)\n}\n\n\/\/ Dial establishes a new QUIC connection to a server using a net.PacketConn.\n\/\/ The same PacketConn can be used for multiple calls to Dial and Listen,\n\/\/ QUIC connection IDs are used for demultiplexing the different connections.\n\/\/ The host parameter is used for SNI.\n\/\/ The tls.Config must define an application protocol (using NextProtos).\nfunc Dial(\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialContext(context.Background(), pconn, remoteAddr, host, tlsConf, config, false, false)\n}\n\n\/\/ DialEarly establishes a new 0-RTT QUIC connection to a server using a net.PacketConn.\n\/\/ The same PacketConn can be used for multiple calls to Dial and Listen,\n\/\/ QUIC connection IDs are used for demultiplexing the different connections.\n\/\/ The host parameter is used for SNI.\n\/\/ The tls.Config must define an application protocol (using NextProtos).\nfunc DialEarly(\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialContext(context.Background(), pconn, remoteAddr, host, tlsConf, config, true, false)\n}\n\n\/\/ DialContext establishes a new QUIC connection to a server using a net.PacketConn using the provided context.\n\/\/ See Dial for details.\nfunc DialContext(\n\tctx context.Context,\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n) (Session, error) {\n\treturn dialContext(ctx, pconn, remoteAddr, host, tlsConf, config, false, false)\n}\n\nfunc dialContext(\n\tctx context.Context,\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\thost string,\n\ttlsConf *tls.Config,\n\tconfig *Config,\n\tuse0RTT bool,\n\tcreatedPacketConn bool,\n) (quicSession, error) {\n\tif tlsConf == nil {\n\t\treturn nil, errors.New(\"quic: tls.Config not set\")\n\t}\n\tconfig = populateClientConfig(config, createdPacketConn)\n\tpacketHandlers, err := getMultiplexer().AddConn(pconn, config.ConnectionIDLength, config.StatelessResetKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := newClient(pconn, remoteAddr, config, tlsConf, host, use0RTT, createdPacketConn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.packetHandlers = packetHandlers\n\n\tif c.config.GetLogWriter != nil {\n\t\tif w := c.config.GetLogWriter(c.destConnID); w != nil {\n\t\t\tc.qlogger = qlog.NewTracer(w, protocol.PerspectiveClient, c.destConnID)\n\t\t}\n\t}\n\tif err := c.dial(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.session, nil\n}\n\nfunc newClient(\n\tpconn net.PacketConn,\n\tremoteAddr net.Addr,\n\tconfig *Config,\n\ttlsConf *tls.Config,\n\thost string,\n\tuse0RTT bool,\n\tcreatedPacketConn bool,\n) (*client, error) {\n\tif tlsConf == nil {\n\t\ttlsConf = &tls.Config{}\n\t}\n\tif tlsConf.ServerName == \"\" {\n\t\tsni := host\n\t\tif strings.IndexByte(sni, ':') != -1 {\n\t\t\tvar err error\n\t\t\tsni, _, err = net.SplitHostPort(sni)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\ttlsConf.ServerName = sni\n\t}\n\n\t\/\/ check that all versions are actually supported\n\tif config != nil {\n\t\tfor _, v := range config.Versions {\n\t\t\tif !protocol.IsValidVersion(v) {\n\t\t\t\treturn nil, fmt.Errorf(\"%s is not a valid QUIC version\", v)\n\t\t\t}\n\t\t}\n\t}\n\n\tsrcConnID, err := generateConnectionID(config.ConnectionIDLength)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdestConnID, err := generateConnectionIDForInitial()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &client{\n\t\tsrcConnID:         srcConnID,\n\t\tdestConnID:        destConnID,\n\t\tconn:              &conn{pconn: pconn, currentAddr: remoteAddr},\n\t\tcreatedPacketConn: createdPacketConn,\n\t\tuse0RTT:           use0RTT,\n\t\ttlsConf:           tlsConf,\n\t\tconfig:            config,\n\t\tversion:           config.Versions[0],\n\t\thandshakeChan:     make(chan struct{}),\n\t\tlogger:            utils.DefaultLogger.WithPrefix(\"client\"),\n\t}\n\treturn c, nil\n}\n\nfunc (c *client) dial(ctx context.Context) error {\n\tc.logger.Infof(\"Starting new connection to %s (%s -> %s), source connection ID %s, destination connection ID %s, version %s\", c.tlsConf.ServerName, c.conn.LocalAddr(), c.conn.RemoteAddr(), c.srcConnID, c.destConnID, c.version)\n\tif c.qlogger != nil {\n\t\tc.qlogger.StartedConnection(c.conn.LocalAddr(), c.conn.LocalAddr(), c.version, c.srcConnID, c.destConnID)\n\t}\n\n\tc.mutex.Lock()\n\tc.session = newClientSession(\n\t\tc.conn,\n\t\tc.packetHandlers,\n\t\tc.destConnID,\n\t\tc.srcConnID,\n\t\tc.config,\n\t\tc.tlsConf,\n\t\tc.initialPacketNumber,\n\t\tc.initialVersion,\n\t\tc.use0RTT,\n\t\tc.qlogger,\n\t\tc.logger,\n\t\tc.version,\n\t)\n\tc.mutex.Unlock()\n\t\/\/ It's not possible to use the stateless reset token for the client's (first) connection ID,\n\t\/\/ since there's no way to securely communicate it to the server.\n\tc.packetHandlers.Add(c.srcConnID, c)\n\n\terrorChan := make(chan error, 1)\n\tgo func() {\n\t\terr := c.session.run() \/\/ returns as soon as the session is closed\n\t\tif err != errCloseForRecreating && c.createdPacketConn {\n\t\t\tc.packetHandlers.Destroy()\n\t\t}\n\t\terrorChan <- err\n\t}()\n\n\t\/\/ only set when we're using 0-RTT\n\t\/\/ Otherwise, earlySessionChan will be nil. Receiving from a nil chan blocks forever.\n\tvar earlySessionChan <-chan struct{}\n\tif c.use0RTT {\n\t\tearlySessionChan = c.session.earlySessionReady()\n\t}\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tc.session.shutdown()\n\t\treturn ctx.Err()\n\tcase err := <-errorChan:\n\t\tif err == errCloseForRecreating {\n\t\t\treturn c.dial(ctx)\n\t\t}\n\t\treturn err\n\tcase <-earlySessionChan:\n\t\t\/\/ ready to send 0-RTT data\n\t\treturn nil\n\tcase <-c.session.HandshakeComplete().Done():\n\t\t\/\/ handshake successfully completed\n\t\treturn nil\n\t}\n}\n\nfunc (c *client) handlePacket(p *receivedPacket) {\n\tif wire.IsVersionNegotiationPacket(p.data) {\n\t\tgo c.handleVersionNegotiationPacket(p)\n\t\treturn\n\t}\n\n\t\/\/ this is the first packet we are receiving\n\t\/\/ since it is not a Version Negotiation Packet, this means the server supports the suggested version\n\tif !c.versionNegotiated.Get() {\n\t\tc.versionNegotiated.Set(true)\n\t}\n\n\tc.session.handlePacket(p)\n}\n\nfunc (c *client) handleVersionNegotiationPacket(p *receivedPacket) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\n\thdr, _, _, err := wire.ParsePacket(p.data, 0)\n\tif err != nil {\n\t\tc.logger.Debugf(\"Error parsing Version Negotiation packet: %s\", err)\n\t\treturn\n\t}\n\n\t\/\/ ignore delayed \/ duplicated version negotiation packets\n\tif c.receivedVersionNegotiationPacket || c.versionNegotiated.Get() {\n\t\tc.logger.Debugf(\"Received a delayed Version Negotiation packet.\")\n\t\treturn\n\t}\n\n\tfor _, v := range hdr.SupportedVersions {\n\t\tif v == c.version {\n\t\t\t\/\/ The Version Negotiation packet contains the version that we offered.\n\t\t\t\/\/ This might be a packet sent by an attacker (or by a terribly broken server implementation).\n\t\t\treturn\n\t\t}\n\t}\n\n\tc.logger.Infof(\"Received a Version Negotiation packet. Supported Versions: %s\", hdr.SupportedVersions)\n\tnewVersion, ok := protocol.ChooseSupportedVersion(c.config.Versions, hdr.SupportedVersions)\n\tif !ok {\n\t\t\/\/nolint:stylecheck\n\t\tc.session.destroy(fmt.Errorf(\"No compatible QUIC version found. We support %s, server offered %s\", c.config.Versions, hdr.SupportedVersions))\n\t\tc.logger.Debugf(\"No compatible QUIC version found.\")\n\t\treturn\n\t}\n\tc.receivedVersionNegotiationPacket = true\n\tc.negotiatedVersions = hdr.SupportedVersions\n\n\t\/\/ switch to negotiated version\n\tc.initialVersion = c.version\n\tc.version = newVersion\n\n\tc.logger.Infof(\"Switching to QUIC version %s. New connection ID: %s\", newVersion, c.destConnID)\n\tc.initialPacketNumber = c.session.closeForRecreating()\n}\n\nfunc (c *client) shutdown() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tif c.session == nil {\n\t\treturn\n\t}\n\tc.session.shutdown()\n}\n\nfunc (c *client) destroy(e error) {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tif c.session == nil {\n\t\treturn\n\t}\n\tc.session.destroy(e)\n}\n\nfunc (c *client) GetVersion() protocol.VersionNumber {\n\tc.mutex.Lock()\n\tv := c.version\n\tc.mutex.Unlock()\n\treturn v\n}\n\nfunc (c *client) getPerspective() protocol.Perspective {\n\treturn protocol.PerspectiveClient\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This is free and unencumbered software released into the public\n\/\/ domain.  For more information, see <http:\/\/unlicense.org> or the\n\/\/ accompanying UNLICENSE file.\n\npackage mocks\n\nimport (\n\t\"go\/ast\"\n\t\"go\/token\"\n\t\"io\"\n\t\"golang.org\/x\/tools\/go\/ast\/astutil\"\n\t\"go\/parser\"\n\t\"os\"\n\t\"go\/format\"\n\t\"bytes\"\n\t\"strconv\"\n)\n\nconst commentHeader = `\/\/ This file was generated by github.com\/nelsam\/hel.  Do not\n\/\/ edit this code by hand unless you *really* know what you're\n\/\/ doing.  Expect any changes made manually to be overwritten\n\/\/ the next time hel regenerates this file.\n\n`\n\n\/\/go:generate hel --type TypeFinder --output mock_type_finder_test.go\n\ntype TypeFinder interface {\n\tExportedTypes() (types []*ast.TypeSpec)\n\tDependencies(inter *ast.InterfaceType) (dependencies []*ast.TypeSpec)\n}\n\ntype Mocks []Mock\n\nfunc (m Mocks) Output(pkg, dir string, chanSize int, dest io.Writer) error {\n\tif _, err := dest.Write([]byte(commentHeader)); err != nil {\n\t\treturn err\n\t}\n\n\tfset := token.NewFileSet()\n\n\tf := &ast.File{\n\t\tName:  &ast.Ident{Name: pkg},\n\t\tDecls: m.decls(chanSize),\n\t}\n\n\tvar b bytes.Buffer\n\tformat.Node(&b, fset, f)\n\n\n\t\/\/ TODO: Determine why adding imports without creating a new ast file\n\t\/\/ will only allow one import to be printed to the file.\n\tfset = token.NewFileSet()\n\tfile, err := parser.ParseFile(fset, pkg, &b, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, fset, err = addImports(file, fset, dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn format.Node(dest, fset, file)\n}\n\nfunc (m Mocks) PrependLocalPackage(name string) {\n\tfor _, m := range m {\n\t\tm.PrependLocalPackage(name)\n\t}\n}\n\nfunc (m Mocks) SetBlockingReturn(blockingReturn bool) {\n\tfor _, m := range m {\n\t\tm.SetBlockingReturn(blockingReturn)\n\t}\n}\n\nfunc (m Mocks) decls(chanSize int) (decls []ast.Decl) {\n\tfor _, mock := range m {\n\t\tdecls = append(decls, mock.Ast(chanSize)...)\n\t}\n\treturn decls\n}\n\nfunc addImports(file *ast.File, fset *token.FileSet, dirPath string) (*ast.File, *token.FileSet, error) {\n\timports, err := getImports(dirPath, fset)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfor _, s := range imports {\n\t\tunquotedPath, err := strconv.Unquote(s.Path.Value)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tif s.Name != nil {\n\t\t\tastutil.AddNamedImport(fset, file, s.Name.Name, unquotedPath)\n\t\t\tcontinue\n\t\t}\n\n\t\tastutil.AddImport(fset, file, unquotedPath)\n\t}\n\n\treturn file, fset, nil\n}\n\nfunc getImports(dirPath string, fset *token.FileSet) ([]*ast.ImportSpec, error) {\n\t\/\/ Grab imports from all files except helheim_test\n\tpkgs, err := parser.ParseDir(fset, dirPath, func(info os.FileInfo) bool {\n\t\treturn info.Name() != \"helheim_test.go\"\n\t}, parser.ImportsOnly)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar imports []*ast.ImportSpec\n\tfor _, p := range pkgs {\n\t\tfiles := p.Files\n\t\tfor _, f := range files {\n\t\t\timports = append(imports, f.Imports...)\n\t\t}\n\t}\n\treturn imports, nil\n}\n\nfunc Generate(finder TypeFinder) (Mocks, error) {\n\tbase := finder.ExportedTypes()\n\tvar types []*ast.TypeSpec\n\tfor _, typ := range base {\n\t\ttypes = append(types, typ)\n\t\tif inter, ok := typ.Type.(*ast.InterfaceType); ok {\n\t\t\ttypes = append(types, finder.Dependencies(inter)...)\n\t\t}\n\t}\n\tm := make(Mocks, 0, len(types))\n\tfor _, typ := range types {\n\t\tnewMock, err := For(typ)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tm = append(m, newMock)\n\t}\n\treturn m, nil\n}\n<commit_msg>Changed addImports to only add imports from non test files<commit_after>\/\/ This is free and unencumbered software released into the public\n\/\/ domain.  For more information, see <http:\/\/unlicense.org> or the\n\/\/ accompanying UNLICENSE file.\n\npackage mocks\n\nimport (\n\t\"go\/ast\"\n\t\"go\/token\"\n\t\"io\"\n\t\"golang.org\/x\/tools\/go\/ast\/astutil\"\n\t\"go\/parser\"\n\t\"os\"\n\t\"go\/format\"\n\t\"bytes\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst commentHeader = `\/\/ This file was generated by github.com\/nelsam\/hel.  Do not\n\/\/ edit this code by hand unless you *really* know what you're\n\/\/ doing.  Expect any changes made manually to be overwritten\n\/\/ the next time hel regenerates this file.\n\n`\n\n\/\/go:generate hel --type TypeFinder --output mock_type_finder_test.go\n\ntype TypeFinder interface {\n\tExportedTypes() (types []*ast.TypeSpec)\n\tDependencies(inter *ast.InterfaceType) (dependencies []*ast.TypeSpec)\n}\n\ntype Mocks []Mock\n\nfunc (m Mocks) Output(pkg, dir string, chanSize int, dest io.Writer) error {\n\tif _, err := dest.Write([]byte(commentHeader)); err != nil {\n\t\treturn err\n\t}\n\n\tfset := token.NewFileSet()\n\n\tf := &ast.File{\n\t\tName:  &ast.Ident{Name: pkg},\n\t\tDecls: m.decls(chanSize),\n\t}\n\n\tvar b bytes.Buffer\n\tformat.Node(&b, fset, f)\n\n\n\t\/\/ TODO: Determine why adding imports without creating a new ast file\n\t\/\/ will only allow one import to be printed to the file.\n\tfset = token.NewFileSet()\n\tfile, err := parser.ParseFile(fset, pkg, &b, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, fset, err = addImports(file, fset, dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn format.Node(dest, fset, file)\n}\n\nfunc (m Mocks) PrependLocalPackage(name string) {\n\tfor _, m := range m {\n\t\tm.PrependLocalPackage(name)\n\t}\n}\n\nfunc (m Mocks) SetBlockingReturn(blockingReturn bool) {\n\tfor _, m := range m {\n\t\tm.SetBlockingReturn(blockingReturn)\n\t}\n}\n\nfunc (m Mocks) decls(chanSize int) (decls []ast.Decl) {\n\tfor _, mock := range m {\n\t\tdecls = append(decls, mock.Ast(chanSize)...)\n\t}\n\treturn decls\n}\n\nfunc addImports(file *ast.File, fset *token.FileSet, dirPath string) (*ast.File, *token.FileSet, error) {\n\timports, err := getImports(dirPath, fset)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tfor _, s := range imports {\n\t\tunquotedPath, err := strconv.Unquote(s.Path.Value)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tif s.Name != nil {\n\t\t\tastutil.AddNamedImport(fset, file, s.Name.Name, unquotedPath)\n\t\t\tcontinue\n\t\t}\n\n\t\tastutil.AddImport(fset, file, unquotedPath)\n\t}\n\n\treturn file, fset, nil\n}\n\nfunc getImports(dirPath string, fset *token.FileSet) ([]*ast.ImportSpec, error) {\n\t\/\/ Grab imports from all files except helheim_test\n\tpkgs, err := parser.ParseDir(fset, dirPath, func(info os.FileInfo) bool {\n\t\treturn !strings.Contains(info.Name(), \"_test.go\")\n\t}, parser.ImportsOnly)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar imports []*ast.ImportSpec\n\tfor _, p := range pkgs {\n\t\tfiles := p.Files\n\t\tfor _, f := range files {\n\t\t\timports = append(imports, f.Imports...)\n\t\t}\n\t}\n\treturn imports, nil\n}\n\nfunc Generate(finder TypeFinder) (Mocks, error) {\n\tbase := finder.ExportedTypes()\n\tvar types []*ast.TypeSpec\n\tfor _, typ := range base {\n\t\ttypes = append(types, typ)\n\t\tif inter, ok := typ.Type.(*ast.InterfaceType); ok {\n\t\t\ttypes = append(types, finder.Dependencies(inter)...)\n\t\t}\n\t}\n\tm := make(Mocks, 0, len(types))\n\tfor _, typ := range types {\n\t\tnewMock, err := For(typ)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tm = append(m, newMock)\n\t}\n\treturn m, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"golang.org\/x\/crypto\/ssh\"\n\t\"golang.org\/x\/crypto\/ssh\/terminal\"\n)\n\nconst MSG_BUFFER int = 50\nconst MAX_MSG_LENGTH int = 512\n\nconst HELP_TEXT string = SYSTEM_MESSAGE_FORMAT + `-> Available commands:\n   \/about               - About this chat.\n   \/exit                - Exit the chat.\n   \/help                - Show this help text.\n   \/list                - List the users that are currently connected.\n   \/beep                - Enable BEL notifications on mention.\n   \/me $ACTION          - Show yourself doing an action.\n   \/nick $NAME          - Rename yourself to a new name.\n   \/whois $NAME         - Display information about another connected user.\n   \/msg $NAME $MESSAGE  - Sends a private message to a user.\n   \/motd                - Prints the Message of the Day\n` + RESET\n\nconst OP_HELP_TEXT string = SYSTEM_MESSAGE_FORMAT + `-> Available operator commands:\n   \/ban $NAME       - Banish a user from the chat\n   \/kick $NAME      - Kick em' out.\n   \/op $NAME        - Promote a user to server operator\n   \/silence $NAME   - Revoke a user's ability to speak\n   \/ban $NAME           - Banish a user from the chat\n   \/kick $NAME          - Kick em' out.\n   \/op $NAME            - Promote a user to server operator.\n   \/silence $NAME       - Revoke a user's ability to speak.\n   \/motd $MESSAGE    - Sets the Message of the Day\n` + RESET\n\nconst ABOUT_TEXT string = SYSTEM_MESSAGE_FORMAT + `-> ssh-chat is made by @shazow.\n\n   It is a custom ssh server built in Go to serve a chat experience\n   instead of a shell.\n\n   Source: https:\/\/github.com\/shazow\/ssh-chat\n\n   For more, visit shazow.net or follow at twitter.com\/shazow\n` + RESET\n\nconst REQUIRED_WAIT time.Duration = time.Second \/ 2\n\ntype Client struct {\n\tServer        *Server\n\tConn          *ssh.ServerConn\n\tMsg           chan string\n\tName          string\n\tColor         string\n\tOp            bool\n\tready         chan struct{}\n\tterm          *terminal.Terminal\n\ttermWidth     int\n\ttermHeight    int\n\tsilencedUntil time.Time\n\tlastTX        time.Time\n\tbeepMe        bool\n}\n\nfunc NewClient(server *Server, conn *ssh.ServerConn) *Client {\n\treturn &Client{\n\t\tServer: server,\n\t\tConn:   conn,\n\t\tName:   conn.User(),\n\t\tColor:  RandomColor256(),\n\t\tMsg:    make(chan string, MSG_BUFFER),\n\t\tready:  make(chan struct{}, 1),\n\t\tlastTX: time.Now(),\n\t}\n}\n\nfunc (c *Client) ColoredName() string {\n\treturn ColorString(c.Color, c.Name)\n}\n\nfunc (c *Client) SysMsg(msg string, args ...interface{}) {\n\tc.Msg <- ContinuousFormat(SYSTEM_MESSAGE_FORMAT, \"-> \"+fmt.Sprintf(msg, args...))\n}\n\nfunc (c *Client) Write(msg string) {\n\tc.term.Write([]byte(msg + \"\\r\\n\"))\n}\n\nfunc (c *Client) WriteLines(msg []string) {\n\tfor _, line := range msg {\n\t\tc.Write(line)\n\t}\n}\n\nfunc (c *Client) Send(msg string) {\n\tif len(msg) > MAX_MSG_LENGTH {\n\t\treturn\n\t}\n\tselect {\n\tcase c.Msg <- msg:\n\tdefault:\n\t\tlogger.Errorf(\"Msg buffer full, dropping: %s (%s)\", c.Name, c.Conn.RemoteAddr())\n\t\tc.Conn.Close()\n\t}\n}\n\nfunc (c *Client) SendLines(msg []string) {\n\tfor _, line := range msg {\n\t\tc.Send(line)\n\t}\n}\n\nfunc (c *Client) IsSilenced() bool {\n\treturn c.silencedUntil.After(time.Now())\n}\n\nfunc (c *Client) Silence(d time.Duration) {\n\tc.silencedUntil = time.Now().Add(d)\n}\n\nfunc (c *Client) Resize(width int, height int) error {\n\terr := c.term.SetSize(width, height)\n\tif err != nil {\n\t\tlogger.Errorf(\"Resize failed: %dx%d\", width, height)\n\t\treturn err\n\t}\n\tc.termWidth, c.termHeight = width, height\n\treturn nil\n}\n\nfunc (c *Client) Rename(name string) {\n\tc.Name = name\n\tc.term.SetPrompt(fmt.Sprintf(\"[%s] \", c.ColoredName()))\n}\n\nfunc (c *Client) Fingerprint() string {\n\treturn c.Conn.Permissions.Extensions[\"fingerprint\"]\n}\n\nfunc (c *Client) handleShell(channel ssh.Channel) {\n\tdefer channel.Close()\n\n\t\/\/ FIXME: This shouldn't live here, need to restructure the call chaining.\n\tc.Server.Add(c)\n\tgo func() {\n\t\t\/\/ Block until done, then remove.\n\t\tc.Conn.Wait()\n\t\tc.Server.Remove(c)\n\t}()\n\n\tgo func() {\n\t\tfor msg := range c.Msg {\n\t\t\tc.Write(msg)\n\t\t}\n\t}()\n\n\tfor {\n\t\tline, err := c.term.ReadLine()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tparts := strings.SplitN(line, \" \", 3)\n\t\tisCmd := strings.HasPrefix(parts[0], \"\/\")\n\n\t\tif isCmd {\n\t\t\t\/\/ TODO: Factor this out.\n\t\t\tswitch parts[0] {\n\t\t\tcase \"\/test-colors\": \/\/ Shh, this command is a secret!\n\t\t\t\tc.Write(ColorString(\"32\", \"Lorem ipsum dolor sit amet,\"))\n\t\t\t\tc.Write(\"consectetur \" + ColorString(\"31;1\", \"adipiscing\") + \" elit.\")\n\t\t\tcase \"\/exit\":\n\t\t\t\tchannel.Close()\n\t\t\tcase \"\/help\":\n\t\t\t\tc.WriteLines(strings.Split(HELP_TEXT, \"\\n\"))\n\t\t\t\tif c.Server.IsOp(c) {\n\t\t\t\t\tc.WriteLines(strings.Split(OP_HELP_TEXT, \"\\n\"))\n\t\t\t\t}\n\t\t\tcase \"\/about\":\n\t\t\t\tc.WriteLines(strings.Split(ABOUT_TEXT, \"\\n\"))\n\t\t\tcase \"\/uptime\":\n\t\t\t\tc.Write(c.Server.Uptime())\n\t\t\tcase \"\/beep\":\n\t\t\t\tc.beepMe = !c.beepMe\n\t\t\t\tif c.beepMe {\n\t\t\t\t\tc.SysMsg(\"I'll beep you good.\")\n\t\t\t\t} else {\n\t\t\t\t\tc.SysMsg(\"No more beeps. :(\")\n\t\t\t\t}\n\t\t\tcase \"\/me\":\n\t\t\t\tme := strings.TrimLeft(line, \"\/me\")\n\t\t\t\tif me == \"\" {\n\t\t\t\t\tme = \" is at a loss for words.\"\n\t\t\t\t}\n\t\t\t\tmsg := fmt.Sprintf(\"** %s%s\", c.ColoredName(), me)\n\t\t\t\tif c.IsSilenced() || len(msg) > 1000 {\n\t\t\t\t\tc.SysMsg(\"Message rejected.\")\n\t\t\t\t} else {\n\t\t\t\t\tc.Server.Broadcast(msg, nil)\n\t\t\t\t}\n\t\t\tcase \"\/nick\":\n\t\t\t\tif len(parts) == 2 {\n\t\t\t\t\tc.Server.Rename(c, parts[1])\n\t\t\t\t} else {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/nick $NAME\")\n\t\t\t\t}\n\t\t\tcase \"\/whois\":\n\t\t\t\tif len(parts) == 2 {\n\t\t\t\t\tclient := c.Server.Who(parts[1])\n\t\t\t\t\tif client != nil {\n\t\t\t\t\t\tversion := RE_STRIP_TEXT.ReplaceAllString(string(client.Conn.ClientVersion()), \"\")\n\t\t\t\t\t\tif len(version) > 100 {\n\t\t\t\t\t\t\tversion = \"Evil Jerk with a superlong string\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\tc.SysMsg(\"%s is %s via %s\", client.ColoredName(), client.Fingerprint(), version)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tc.SysMsg(\"No such name: %s\", parts[1])\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/whois $NAME\")\n\t\t\t\t}\n\t\t\tcase \"\/list\":\n\t\t\t\tnames := \"\"\n\t\t\t\tnameList := c.Server.List(nil)\n\t\t\t\tfor _, name := range nameList {\n\t\t\t\t\tnames += c.Server.Who(name).ColoredName() + SYSTEM_MESSAGE_FORMAT + \", \"\n\t\t\t\t}\n\t\t\t\tif len(names) > 2 {\n\t\t\t\t\tnames = names[:len(names)-2]\n\t\t\t\t}\n\t\t\t\tc.SysMsg(\"%d connected: %s\", len(nameList), names)\n\t\t\tcase \"\/ban\":\n\t\t\t\tif !c.Server.IsOp(c) {\n\t\t\t\t\tc.SysMsg(\"You're not an admin.\")\n\t\t\t\t} else if len(parts) != 2 {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/ban $NAME\")\n\t\t\t\t} else {\n\t\t\t\t\tclient := c.Server.Who(parts[1])\n\t\t\t\t\tif client == nil {\n\t\t\t\t\t\tc.SysMsg(\"No such name: %s\", parts[1])\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfingerprint := client.Fingerprint()\n\t\t\t\t\t\tclient.SysMsg(\"Banned by %s.\", c.ColoredName())\n\t\t\t\t\t\tc.Server.Ban(fingerprint, nil)\n\t\t\t\t\t\tclient.Conn.Close()\n\t\t\t\t\t\tc.Server.Broadcast(fmt.Sprintf(\"* %s was banned by %s\", parts[1], c.ColoredName()), nil)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"\/op\":\n\t\t\t\tif !c.Server.IsOp(c) {\n\t\t\t\t\tc.SysMsg(\"You're not an admin.\")\n\t\t\t\t} else if len(parts) != 2 {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/op $NAME\")\n\t\t\t\t} else {\n\t\t\t\t\tclient := c.Server.Who(parts[1])\n\t\t\t\t\tif client == nil {\n\t\t\t\t\t\tc.SysMsg(\"No such name: %s\", parts[1])\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfingerprint := client.Fingerprint()\n\t\t\t\t\t\tclient.SysMsg(\"Made op by %s.\", c.ColoredName())\n\t\t\t\t\t\tc.Server.Op(fingerprint)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"\/kick\":\n\t\t\t\tif !c.Server.IsOp(c) {\n\t\t\t\t\tc.SysMsg(\"You're not an admin.\")\n\t\t\t\t} else if len(parts) != 2 {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/kick $NAME\")\n\t\t\t\t} else {\n\t\t\t\t\tclient := c.Server.Who(parts[1])\n\t\t\t\t\tif client == nil {\n\t\t\t\t\t\tc.SysMsg(\"No such name: %s\", parts[1])\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclient.SysMsg(\"Kicked by %s.\", c.ColoredName())\n\t\t\t\t\t\tclient.Conn.Close()\n\t\t\t\t\t\tc.Server.Broadcast(fmt.Sprintf(\"* %s was kicked by %s\", parts[1], c.ColoredName()), nil)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"\/silence\":\n\t\t\t\tif !c.Server.IsOp(c) {\n\t\t\t\t\tc.SysMsg(\"You're not an admin.\")\n\t\t\t\t} else if len(parts) < 2 {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/silence $NAME\")\n\t\t\t\t} else {\n\t\t\t\t\tduration := time.Duration(5) * time.Minute\n\t\t\t\t\tif len(parts) >= 3 {\n\t\t\t\t\t\tparsedDuration, err := time.ParseDuration(parts[2])\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\tduration = parsedDuration\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tclient := c.Server.Who(parts[1])\n\t\t\t\t\tif client == nil {\n\t\t\t\t\t\tc.SysMsg(\"No such name: %s\", parts[1])\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclient.Silence(duration)\n\t\t\t\t\t\tclient.SysMsg(\"Silenced for %s by %s.\", duration, c.ColoredName())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"\/msg\": \/* Send a PM *\/\n\t\t\t\t\/* Make sure we have a recipient and a message *\/\n\t\t\t\tif len(parts) < 2 {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/msg $NAME $MESSAGE\")\n\t\t\t\t\tbreak\n\t\t\t\t} else if len(parts) < 3 {\n\t\t\t\t\tc.SysMsg(\"Missing $MESSAGE from: \/msg $NAME $MESSAGE\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t\/* Ask the server to send the message *\/\n\t\t\t\tif err := c.Server.Privmsg(parts[1], parts[2], c); nil != err {\n\t\t\t\t\tc.SysMsg(\"Unable to send message to %v: %v\", parts[1], err)\n\t\t\t\t}\n\t\t\tcase \"\/motd\": \/* print motd *\/\n\t\t\t\tif !c.Server.IsOp(c) {\n\t\t\t\t\tc.Server.MotdUnicast(c)\n\t\t\t\t} else if len(parts) < 2 {\n\t\t\t\t\tc.Server.MotdUnicast(c)\n\t\t\t\t} else {\n\t\t\t\t\tvar newmotd string\n\t\t\t\t\tif (len(parts) == 2) {\n\t\t\t\t\t\tnewmotd = parts[1]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnewmotd = parts[1] + \" \" + parts[2]\n\t\t\t\t\t}\n\t\t\t\t\tc.Server.SetMotd(c, newmotd)\n\t\t\t\t\tc.Server.MotdBroadcast(c)\n\t\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tc.SysMsg(\"Invalid command: %s\", line)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tmsg := fmt.Sprintf(\"%s: %s\", c.ColoredName(), line)\n\t\t\/* Rate limit *\/\n\t\tif time.Now().Sub(c.lastTX) < REQUIRED_WAIT {\n\t\t\tc.SysMsg(\"Rate limiting in effect.\")\n\t\t\tcontinue\n\t\t}\n\t\tif c.IsSilenced() || len(msg) > 1000 || len(line) < 1 {\n\t\t\tc.SysMsg(\"Message rejected.\")\n\t\t\tcontinue\n\t\t}\n\t\tc.Server.Broadcast(msg, c)\n\t\tc.lastTX = time.Now()\n\t}\n\n}\n\nfunc (c *Client) handleChannels(channels <-chan ssh.NewChannel) {\n\tprompt := fmt.Sprintf(\"[%s] \", c.ColoredName())\n\n\thasShell := false\n\n\tfor ch := range channels {\n\t\tif t := ch.ChannelType(); t != \"session\" {\n\t\t\tch.Reject(ssh.UnknownChannelType, fmt.Sprintf(\"unknown channel type: %s\", t))\n\t\t\tcontinue\n\t\t}\n\n\t\tchannel, requests, err := ch.Accept()\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"Could not accept channel: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tdefer channel.Close()\n\n\t\tc.term = terminal.NewTerminal(channel, prompt)\n\t\tc.term.AutoCompleteCallback = c.Server.AutoCompleteFunction\n\n\t\tfor req := range requests {\n\t\t\tvar width, height int\n\t\t\tvar ok bool\n\n\t\t\tswitch req.Type {\n\t\t\tcase \"shell\":\n\t\t\t\tif c.term != nil && !hasShell {\n\t\t\t\t\tgo c.handleShell(channel)\n\t\t\t\t\tok = true\n\t\t\t\t\thasShell = true\n\t\t\t\t}\n\t\t\tcase \"pty-req\":\n\t\t\t\twidth, height, ok = parsePtyRequest(req.Payload)\n\t\t\t\tif ok {\n\t\t\t\t\terr := c.Resize(width, height)\n\t\t\t\t\tok = err == nil\n\t\t\t\t}\n\t\t\tcase \"window-change\":\n\t\t\t\twidth, height, ok = parseWinchRequest(req.Payload)\n\t\t\t\tif ok {\n\t\t\t\t\terr := c.Resize(width, height)\n\t\t\t\t\tok = err == nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif req.WantReply {\n\t\t\t\treq.Reply(ok, nil)\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>clean up duplicate commands in OP_HELP_TEXT<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"golang.org\/x\/crypto\/ssh\"\n\t\"golang.org\/x\/crypto\/ssh\/terminal\"\n)\n\nconst MSG_BUFFER int = 50\nconst MAX_MSG_LENGTH int = 512\n\nconst HELP_TEXT string = SYSTEM_MESSAGE_FORMAT + `-> Available commands:\n   \/about               - About this chat.\n   \/exit                - Exit the chat.\n   \/help                - Show this help text.\n   \/list                - List the users that are currently connected.\n   \/beep                - Enable BEL notifications on mention.\n   \/me $ACTION          - Show yourself doing an action.\n   \/nick $NAME          - Rename yourself to a new name.\n   \/whois $NAME         - Display information about another connected user.\n   \/msg $NAME $MESSAGE  - Sends a private message to a user.\n   \/motd                - Prints the Message of the Day\n` + RESET\n\nconst OP_HELP_TEXT string = SYSTEM_MESSAGE_FORMAT + `-> Available operator commands:\n   \/ban $NAME           - Banish a user from the chat\n   \/kick $NAME          - Kick em' out.\n   \/op $NAME            - Promote a user to server operator.\n   \/silence $NAME       - Revoke a user's ability to speak.\n   \/motd $MESSAGE       - Sets the Message of the Day\n` + RESET\n\nconst ABOUT_TEXT string = SYSTEM_MESSAGE_FORMAT + `-> ssh-chat is made by @shazow.\n\n   It is a custom ssh server built in Go to serve a chat experience\n   instead of a shell.\n\n   Source: https:\/\/github.com\/shazow\/ssh-chat\n\n   For more, visit shazow.net or follow at twitter.com\/shazow\n` + RESET\n\nconst REQUIRED_WAIT time.Duration = time.Second \/ 2\n\ntype Client struct {\n\tServer        *Server\n\tConn          *ssh.ServerConn\n\tMsg           chan string\n\tName          string\n\tColor         string\n\tOp            bool\n\tready         chan struct{}\n\tterm          *terminal.Terminal\n\ttermWidth     int\n\ttermHeight    int\n\tsilencedUntil time.Time\n\tlastTX        time.Time\n\tbeepMe        bool\n}\n\nfunc NewClient(server *Server, conn *ssh.ServerConn) *Client {\n\treturn &Client{\n\t\tServer: server,\n\t\tConn:   conn,\n\t\tName:   conn.User(),\n\t\tColor:  RandomColor256(),\n\t\tMsg:    make(chan string, MSG_BUFFER),\n\t\tready:  make(chan struct{}, 1),\n\t\tlastTX: time.Now(),\n\t}\n}\n\nfunc (c *Client) ColoredName() string {\n\treturn ColorString(c.Color, c.Name)\n}\n\nfunc (c *Client) SysMsg(msg string, args ...interface{}) {\n\tc.Msg <- ContinuousFormat(SYSTEM_MESSAGE_FORMAT, \"-> \"+fmt.Sprintf(msg, args...))\n}\n\nfunc (c *Client) Write(msg string) {\n\tc.term.Write([]byte(msg + \"\\r\\n\"))\n}\n\nfunc (c *Client) WriteLines(msg []string) {\n\tfor _, line := range msg {\n\t\tc.Write(line)\n\t}\n}\n\nfunc (c *Client) Send(msg string) {\n\tif len(msg) > MAX_MSG_LENGTH {\n\t\treturn\n\t}\n\tselect {\n\tcase c.Msg <- msg:\n\tdefault:\n\t\tlogger.Errorf(\"Msg buffer full, dropping: %s (%s)\", c.Name, c.Conn.RemoteAddr())\n\t\tc.Conn.Close()\n\t}\n}\n\nfunc (c *Client) SendLines(msg []string) {\n\tfor _, line := range msg {\n\t\tc.Send(line)\n\t}\n}\n\nfunc (c *Client) IsSilenced() bool {\n\treturn c.silencedUntil.After(time.Now())\n}\n\nfunc (c *Client) Silence(d time.Duration) {\n\tc.silencedUntil = time.Now().Add(d)\n}\n\nfunc (c *Client) Resize(width int, height int) error {\n\terr := c.term.SetSize(width, height)\n\tif err != nil {\n\t\tlogger.Errorf(\"Resize failed: %dx%d\", width, height)\n\t\treturn err\n\t}\n\tc.termWidth, c.termHeight = width, height\n\treturn nil\n}\n\nfunc (c *Client) Rename(name string) {\n\tc.Name = name\n\tc.term.SetPrompt(fmt.Sprintf(\"[%s] \", c.ColoredName()))\n}\n\nfunc (c *Client) Fingerprint() string {\n\treturn c.Conn.Permissions.Extensions[\"fingerprint\"]\n}\n\nfunc (c *Client) handleShell(channel ssh.Channel) {\n\tdefer channel.Close()\n\n\t\/\/ FIXME: This shouldn't live here, need to restructure the call chaining.\n\tc.Server.Add(c)\n\tgo func() {\n\t\t\/\/ Block until done, then remove.\n\t\tc.Conn.Wait()\n\t\tc.Server.Remove(c)\n\t}()\n\n\tgo func() {\n\t\tfor msg := range c.Msg {\n\t\t\tc.Write(msg)\n\t\t}\n\t}()\n\n\tfor {\n\t\tline, err := c.term.ReadLine()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tparts := strings.SplitN(line, \" \", 3)\n\t\tisCmd := strings.HasPrefix(parts[0], \"\/\")\n\n\t\tif isCmd {\n\t\t\t\/\/ TODO: Factor this out.\n\t\t\tswitch parts[0] {\n\t\t\tcase \"\/test-colors\": \/\/ Shh, this command is a secret!\n\t\t\t\tc.Write(ColorString(\"32\", \"Lorem ipsum dolor sit amet,\"))\n\t\t\t\tc.Write(\"consectetur \" + ColorString(\"31;1\", \"adipiscing\") + \" elit.\")\n\t\t\tcase \"\/exit\":\n\t\t\t\tchannel.Close()\n\t\t\tcase \"\/help\":\n\t\t\t\tc.WriteLines(strings.Split(HELP_TEXT, \"\\n\"))\n\t\t\t\tif c.Server.IsOp(c) {\n\t\t\t\t\tc.WriteLines(strings.Split(OP_HELP_TEXT, \"\\n\"))\n\t\t\t\t}\n\t\t\tcase \"\/about\":\n\t\t\t\tc.WriteLines(strings.Split(ABOUT_TEXT, \"\\n\"))\n\t\t\tcase \"\/uptime\":\n\t\t\t\tc.Write(c.Server.Uptime())\n\t\t\tcase \"\/beep\":\n\t\t\t\tc.beepMe = !c.beepMe\n\t\t\t\tif c.beepMe {\n\t\t\t\t\tc.SysMsg(\"I'll beep you good.\")\n\t\t\t\t} else {\n\t\t\t\t\tc.SysMsg(\"No more beeps. :(\")\n\t\t\t\t}\n\t\t\tcase \"\/me\":\n\t\t\t\tme := strings.TrimLeft(line, \"\/me\")\n\t\t\t\tif me == \"\" {\n\t\t\t\t\tme = \" is at a loss for words.\"\n\t\t\t\t}\n\t\t\t\tmsg := fmt.Sprintf(\"** %s%s\", c.ColoredName(), me)\n\t\t\t\tif c.IsSilenced() || len(msg) > 1000 {\n\t\t\t\t\tc.SysMsg(\"Message rejected.\")\n\t\t\t\t} else {\n\t\t\t\t\tc.Server.Broadcast(msg, nil)\n\t\t\t\t}\n\t\t\tcase \"\/nick\":\n\t\t\t\tif len(parts) == 2 {\n\t\t\t\t\tc.Server.Rename(c, parts[1])\n\t\t\t\t} else {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/nick $NAME\")\n\t\t\t\t}\n\t\t\tcase \"\/whois\":\n\t\t\t\tif len(parts) == 2 {\n\t\t\t\t\tclient := c.Server.Who(parts[1])\n\t\t\t\t\tif client != nil {\n\t\t\t\t\t\tversion := RE_STRIP_TEXT.ReplaceAllString(string(client.Conn.ClientVersion()), \"\")\n\t\t\t\t\t\tif len(version) > 100 {\n\t\t\t\t\t\t\tversion = \"Evil Jerk with a superlong string\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\tc.SysMsg(\"%s is %s via %s\", client.ColoredName(), client.Fingerprint(), version)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tc.SysMsg(\"No such name: %s\", parts[1])\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/whois $NAME\")\n\t\t\t\t}\n\t\t\tcase \"\/list\":\n\t\t\t\tnames := \"\"\n\t\t\t\tnameList := c.Server.List(nil)\n\t\t\t\tfor _, name := range nameList {\n\t\t\t\t\tnames += c.Server.Who(name).ColoredName() + SYSTEM_MESSAGE_FORMAT + \", \"\n\t\t\t\t}\n\t\t\t\tif len(names) > 2 {\n\t\t\t\t\tnames = names[:len(names)-2]\n\t\t\t\t}\n\t\t\t\tc.SysMsg(\"%d connected: %s\", len(nameList), names)\n\t\t\tcase \"\/ban\":\n\t\t\t\tif !c.Server.IsOp(c) {\n\t\t\t\t\tc.SysMsg(\"You're not an admin.\")\n\t\t\t\t} else if len(parts) != 2 {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/ban $NAME\")\n\t\t\t\t} else {\n\t\t\t\t\tclient := c.Server.Who(parts[1])\n\t\t\t\t\tif client == nil {\n\t\t\t\t\t\tc.SysMsg(\"No such name: %s\", parts[1])\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfingerprint := client.Fingerprint()\n\t\t\t\t\t\tclient.SysMsg(\"Banned by %s.\", c.ColoredName())\n\t\t\t\t\t\tc.Server.Ban(fingerprint, nil)\n\t\t\t\t\t\tclient.Conn.Close()\n\t\t\t\t\t\tc.Server.Broadcast(fmt.Sprintf(\"* %s was banned by %s\", parts[1], c.ColoredName()), nil)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"\/op\":\n\t\t\t\tif !c.Server.IsOp(c) {\n\t\t\t\t\tc.SysMsg(\"You're not an admin.\")\n\t\t\t\t} else if len(parts) != 2 {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/op $NAME\")\n\t\t\t\t} else {\n\t\t\t\t\tclient := c.Server.Who(parts[1])\n\t\t\t\t\tif client == nil {\n\t\t\t\t\t\tc.SysMsg(\"No such name: %s\", parts[1])\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfingerprint := client.Fingerprint()\n\t\t\t\t\t\tclient.SysMsg(\"Made op by %s.\", c.ColoredName())\n\t\t\t\t\t\tc.Server.Op(fingerprint)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"\/kick\":\n\t\t\t\tif !c.Server.IsOp(c) {\n\t\t\t\t\tc.SysMsg(\"You're not an admin.\")\n\t\t\t\t} else if len(parts) != 2 {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/kick $NAME\")\n\t\t\t\t} else {\n\t\t\t\t\tclient := c.Server.Who(parts[1])\n\t\t\t\t\tif client == nil {\n\t\t\t\t\t\tc.SysMsg(\"No such name: %s\", parts[1])\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclient.SysMsg(\"Kicked by %s.\", c.ColoredName())\n\t\t\t\t\t\tclient.Conn.Close()\n\t\t\t\t\t\tc.Server.Broadcast(fmt.Sprintf(\"* %s was kicked by %s\", parts[1], c.ColoredName()), nil)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"\/silence\":\n\t\t\t\tif !c.Server.IsOp(c) {\n\t\t\t\t\tc.SysMsg(\"You're not an admin.\")\n\t\t\t\t} else if len(parts) < 2 {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/silence $NAME\")\n\t\t\t\t} else {\n\t\t\t\t\tduration := time.Duration(5) * time.Minute\n\t\t\t\t\tif len(parts) >= 3 {\n\t\t\t\t\t\tparsedDuration, err := time.ParseDuration(parts[2])\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\tduration = parsedDuration\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tclient := c.Server.Who(parts[1])\n\t\t\t\t\tif client == nil {\n\t\t\t\t\t\tc.SysMsg(\"No such name: %s\", parts[1])\n\t\t\t\t\t} else {\n\t\t\t\t\t\tclient.Silence(duration)\n\t\t\t\t\t\tclient.SysMsg(\"Silenced for %s by %s.\", duration, c.ColoredName())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase \"\/msg\": \/* Send a PM *\/\n\t\t\t\t\/* Make sure we have a recipient and a message *\/\n\t\t\t\tif len(parts) < 2 {\n\t\t\t\t\tc.SysMsg(\"Missing $NAME from: \/msg $NAME $MESSAGE\")\n\t\t\t\t\tbreak\n\t\t\t\t} else if len(parts) < 3 {\n\t\t\t\t\tc.SysMsg(\"Missing $MESSAGE from: \/msg $NAME $MESSAGE\")\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t\/* Ask the server to send the message *\/\n\t\t\t\tif err := c.Server.Privmsg(parts[1], parts[2], c); nil != err {\n\t\t\t\t\tc.SysMsg(\"Unable to send message to %v: %v\", parts[1], err)\n\t\t\t\t}\n\t\t\tcase \"\/motd\": \/* print motd *\/\n\t\t\t\tif !c.Server.IsOp(c) {\n\t\t\t\t\tc.Server.MotdUnicast(c)\n\t\t\t\t} else if len(parts) < 2 {\n\t\t\t\t\tc.Server.MotdUnicast(c)\n\t\t\t\t} else {\n\t\t\t\t\tvar newmotd string\n\t\t\t\t\tif (len(parts) == 2) {\n\t\t\t\t\t\tnewmotd = parts[1]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnewmotd = parts[1] + \" \" + parts[2]\n\t\t\t\t\t}\n\t\t\t\t\tc.Server.SetMotd(c, newmotd)\n\t\t\t\t\tc.Server.MotdBroadcast(c)\n\t\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tc.SysMsg(\"Invalid command: %s\", line)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tmsg := fmt.Sprintf(\"%s: %s\", c.ColoredName(), line)\n\t\t\/* Rate limit *\/\n\t\tif time.Now().Sub(c.lastTX) < REQUIRED_WAIT {\n\t\t\tc.SysMsg(\"Rate limiting in effect.\")\n\t\t\tcontinue\n\t\t}\n\t\tif c.IsSilenced() || len(msg) > 1000 || len(line) < 1 {\n\t\t\tc.SysMsg(\"Message rejected.\")\n\t\t\tcontinue\n\t\t}\n\t\tc.Server.Broadcast(msg, c)\n\t\tc.lastTX = time.Now()\n\t}\n\n}\n\nfunc (c *Client) handleChannels(channels <-chan ssh.NewChannel) {\n\tprompt := fmt.Sprintf(\"[%s] \", c.ColoredName())\n\n\thasShell := false\n\n\tfor ch := range channels {\n\t\tif t := ch.ChannelType(); t != \"session\" {\n\t\t\tch.Reject(ssh.UnknownChannelType, fmt.Sprintf(\"unknown channel type: %s\", t))\n\t\t\tcontinue\n\t\t}\n\n\t\tchannel, requests, err := ch.Accept()\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"Could not accept channel: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tdefer channel.Close()\n\n\t\tc.term = terminal.NewTerminal(channel, prompt)\n\t\tc.term.AutoCompleteCallback = c.Server.AutoCompleteFunction\n\n\t\tfor req := range requests {\n\t\t\tvar width, height int\n\t\t\tvar ok bool\n\n\t\t\tswitch req.Type {\n\t\t\tcase \"shell\":\n\t\t\t\tif c.term != nil && !hasShell {\n\t\t\t\t\tgo c.handleShell(channel)\n\t\t\t\t\tok = true\n\t\t\t\t\thasShell = true\n\t\t\t\t}\n\t\t\tcase \"pty-req\":\n\t\t\t\twidth, height, ok = parsePtyRequest(req.Payload)\n\t\t\t\tif ok {\n\t\t\t\t\terr := c.Resize(width, height)\n\t\t\t\t\tok = err == nil\n\t\t\t\t}\n\t\t\tcase \"window-change\":\n\t\t\t\twidth, height, ok = parseWinchRequest(req.Payload)\n\t\t\t\tif ok {\n\t\t\t\t\terr := c.Resize(width, height)\n\t\t\t\t\tok = err == nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif req.WantReply {\n\t\t\t\treq.Reply(ok, nil)\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package paypalsdk\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n)\n\n\/\/ NewClient returns new Client struct\n\/\/ APIBase is a base API URL, for testing you can use paypalsdk.APIBaseSandBox\nfunc NewClient(clientID string, secret string, APIBase string) (*Client, error) {\n\tif clientID == \"\" || secret == \"\" || APIBase == \"\" {\n\t\treturn &Client{}, errors.New(\"ClientID, Secret and APIBase are required to create a Client\")\n\t}\n\n\treturn &Client{\n\t\t&http.Client{},\n\t\tclientID,\n\t\tsecret,\n\t\tAPIBase,\n\t\tnil,\n\t\tnil,\n\t}, nil\n}\n\n\/\/ SetLog will set\/change the output destination.\n\/\/ If log file is set paypalsdk will log all requests and responses to this Writer\nfunc (c *Client) SetLog(log io.Writer) error {\n\tc.Log = log\n\treturn nil\n}\n\n\/\/ SetAccessToken sets saved token to current client\nfunc (c *Client) SetAccessToken(token string) error {\n\tc.Token = &TokenResponse{\n\t\tToken: token,\n\t}\n\n\treturn nil\n}\n\n\/\/ Send makes a request to the API, the response body will be\n\/\/ unmarshaled into v, or if v is an io.Writer, the response will\n\/\/ be written to it without decoding\nfunc (c *Client) Send(req *http.Request, v interface{}) error {\n\tvar (\n\t\terr  error\n\t\tresp *http.Response\n\t\tdata []byte\n\t)\n\n\t\/\/ Set default headers\n\treq.Header.Set(\"Accept\", \"application\/json\")\n\treq.Header.Set(\"Accept-Language\", \"en_US\")\n\n\t\/\/ Default values for headers\n\tif req.Header.Get(\"Content-type\") == \"\" {\n\t\treq.Header.Set(\"Content-type\", \"application\/json\")\n\t}\n\n\tresp, err = c.client.Do(req)\n\tc.log(req, resp)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode < 200 || resp.StatusCode > 299 {\n\t\terrResp := &ErrorResponse{Response: resp}\n\t\tdata, err = ioutil.ReadAll(resp.Body)\n\n\t\tif err == nil && len(data) > 0 {\n\t\t\tjson.Unmarshal(data, errResp)\n\t\t}\n\n\t\treturn errResp\n\t}\n\n\tif v != nil {\n\t\tif w, ok := v.(io.Writer); ok {\n\t\t\tio.Copy(w, resp.Body)\n\t\t} else {\n\t\t\terr = json.NewDecoder(resp.Body).Decode(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ SendWithAuth makes a request to the API and apply OAuth2 header automatically.\n\/\/ If the access token soon to be expired or already expired, it will try to get a new one before\n\/\/ making the main request\n\/\/ client.Token will be updated when changed\nfunc (c *Client) SendWithAuth(req *http.Request, v interface{}) error {\n\tif c.Token != nil {\n\t\tif c.Token.ExpiresIn < RequestNewTokenBeforeExpiresIn {\n\t\t\t\/\/ c.Token willbe updated in GetAccessToken call\n\t\t\t_, err := c.GetAccessToken()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+c.Token.Token)\n\t}\n\n\treturn c.Send(req, v)\n}\n\n\/\/ NewRequest constructs a request\n\/\/ Convert payload to a JSON\nfunc (c *Client) NewRequest(method, url string, payload interface{}) (*http.Request, error) {\n\tvar buf io.Reader\n\tif payload != nil {\n\t\tvar b []byte\n\t\tb, err := json.Marshal(&payload)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuf = bytes.NewBuffer(b)\n\t}\n\treturn http.NewRequest(method, url, buf)\n}\n\n\/\/ log will dump request and response to the log file\nfunc (c *Client) log(r *http.Request, resp *http.Response) {\n\tif c.Log != nil {\n\t\treqDump := fmt.Sprintf(\"%s %s. Data: %s\", r.Method, r.URL.String(), r.Form.Encode())\n\t\tdump, _ := ioutil.ReadAll(r.Body)\n\t\tfmt.Println(string(dump))\n\t\trespDump, _ := httputil.DumpResponse(resp, true)\n\n\t\tc.Log.Write([]byte(\"Request: \" + reqDump + \"\\nResponse: \" + string(respDump) + \"\\n\\n\"))\n\t}\n}\n<commit_msg>Fixed panic on logging requests without body (GET)<commit_after>package paypalsdk\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n)\n\n\/\/ NewClient returns new Client struct\n\/\/ APIBase is a base API URL, for testing you can use paypalsdk.APIBaseSandBox\nfunc NewClient(clientID string, secret string, APIBase string) (*Client, error) {\n\tif clientID == \"\" || secret == \"\" || APIBase == \"\" {\n\t\treturn &Client{}, errors.New(\"ClientID, Secret and APIBase are required to create a Client\")\n\t}\n\n\treturn &Client{\n\t\t&http.Client{},\n\t\tclientID,\n\t\tsecret,\n\t\tAPIBase,\n\t\tnil,\n\t\tnil,\n\t}, nil\n}\n\n\/\/ SetLog will set\/change the output destination.\n\/\/ If log file is set paypalsdk will log all requests and responses to this Writer\nfunc (c *Client) SetLog(log io.Writer) error {\n\tc.Log = log\n\treturn nil\n}\n\n\/\/ SetAccessToken sets saved token to current client\nfunc (c *Client) SetAccessToken(token string) error {\n\tc.Token = &TokenResponse{\n\t\tToken: token,\n\t}\n\n\treturn nil\n}\n\n\/\/ Send makes a request to the API, the response body will be\n\/\/ unmarshaled into v, or if v is an io.Writer, the response will\n\/\/ be written to it without decoding\nfunc (c *Client) Send(req *http.Request, v interface{}) error {\n\tvar (\n\t\terr  error\n\t\tresp *http.Response\n\t\tdata []byte\n\t)\n\n\t\/\/ Set default headers\n\treq.Header.Set(\"Accept\", \"application\/json\")\n\treq.Header.Set(\"Accept-Language\", \"en_US\")\n\n\t\/\/ Default values for headers\n\tif req.Header.Get(\"Content-type\") == \"\" {\n\t\treq.Header.Set(\"Content-type\", \"application\/json\")\n\t}\n\n\tresp, err = c.client.Do(req)\n\tc.log(req, resp)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode < 200 || resp.StatusCode > 299 {\n\t\terrResp := &ErrorResponse{Response: resp}\n\t\tdata, err = ioutil.ReadAll(resp.Body)\n\n\t\tif err == nil && len(data) > 0 {\n\t\t\tjson.Unmarshal(data, errResp)\n\t\t}\n\n\t\treturn errResp\n\t}\n\n\tif v != nil {\n\t\tif w, ok := v.(io.Writer); ok {\n\t\t\tio.Copy(w, resp.Body)\n\t\t} else {\n\t\t\terr = json.NewDecoder(resp.Body).Decode(v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ SendWithAuth makes a request to the API and apply OAuth2 header automatically.\n\/\/ If the access token soon to be expired or already expired, it will try to get a new one before\n\/\/ making the main request\n\/\/ client.Token will be updated when changed\nfunc (c *Client) SendWithAuth(req *http.Request, v interface{}) error {\n\tif c.Token != nil {\n\t\tif c.Token.ExpiresIn < RequestNewTokenBeforeExpiresIn {\n\t\t\t\/\/ c.Token willbe updated in GetAccessToken call\n\t\t\t_, err := c.GetAccessToken()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+c.Token.Token)\n\t}\n\n\treturn c.Send(req, v)\n}\n\n\/\/ NewRequest constructs a request\n\/\/ Convert payload to a JSON\nfunc (c *Client) NewRequest(method, url string, payload interface{}) (*http.Request, error) {\n\tvar buf io.Reader\n\tif payload != nil {\n\t\tvar b []byte\n\t\tb, err := json.Marshal(&payload)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuf = bytes.NewBuffer(b)\n\t}\n\treturn http.NewRequest(method, url, buf)\n}\n\n\/\/ log will dump request and response to the log file\nfunc (c *Client) log(r *http.Request, resp *http.Response) {\n\tif c.Log != nil {\n\t\treqDump := fmt.Sprintf(\"%s %s. Data: %s\", r.Method, r.URL.String(), r.Form.Encode())\n\t\trespDump, _ := httputil.DumpResponse(resp, true)\n\n\t\tc.Log.Write([]byte(\"Request: \" + reqDump + \"\\nResponse: \" + string(respDump) + \"\\n\\n\"))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nA smart client for go.\n\nUsage:\n\n client, err := couchbase.Connect(\"http:\/\/myserver:8091\/\")\n handleError(err)\n pool, err := client.GetPool(\"default\")\n handleError(err)\n bucket, err := pool.getBucket(\"MyAwesomeBucket\")\n handleError(err)\n ...\n\nor a shortcut for the bucket directly\n\n bucket, err := couchbase.GetBucket(\"http:\/\/myserver:8091\/\", \"default\", \"default\")\n*\/\npackage couchbase\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"net\/url\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\n\t\"github.com\/dustin\/gomemcached\"\n\t\"github.com\/dustin\/gomemcached\/client\"\n)\n\ntype connectionPool struct {\n\thost        string\n\tname        string\n\tconnections []*memcached.Client\n\tmutex       sync.Mutex\n}\n\nfunc (cp *connectionPool) Close() error {\n\tcp.mutex.Lock()\n\tdefer cp.mutex.Unlock()\n\tfor _, c := range cp.connections {\n\t\tc.Close()\n\t}\n\tcp.connections = []*memcached.Client{}\n\treturn nil\n}\n\nfunc (cp *connectionPool) Get() (*memcached.Client, error) {\n\tcp.mutex.Lock()\n\tdefer cp.mutex.Unlock()\n\n\tif len(cp.connections) == 0 {\n\t\tconn, err := memcached.Connect(\"tcp\", cp.host)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif cp.name != \"default\" {\n\t\t\tconn.Auth(cp.name, \"\")\n\t\t}\n\n\t\tcp.connections = append(cp.connections, conn)\n\t}\n\n\trv := cp.connections[0]\n\tcp.connections = cp.connections[1:]\n\n\treturn rv, nil\n}\n\nfunc (cp *connectionPool) Return(c *memcached.Client) {\n\tcp.mutex.Lock()\n\tdefer cp.mutex.Unlock()\n\n\tif c != nil {\n\t\tif c.IsHealthy() {\n\t\t\tcp.connections = append(cp.connections, c)\n\t\t} else {\n\t\t\tc.Close()\n\t\t}\n\t}\n}\n\n\/\/ Execute a function on a memcached connection to the node owning key \"k\"\n\/\/\n\/\/ Note that this automatically handles transient errors by replaying\n\/\/ your function on a \"not-my-vbucket\" error, so don't assume\n\/\/ your command will only be executed only once.\nfunc (b *Bucket) Do(k string, f func(mc *memcached.Client, vb uint16) error) error {\n\tvb := b.VBHash(k)\n\tfor {\n\t\tmasterId := b.VBucketServerMap.VBucketMap[vb][0]\n\t\tconn, err := b.connections[masterId].Get()\n\t\tdefer b.connections[masterId].Return(conn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = f(conn, uint16(vb))\n\t\tswitch err.(type) {\n\t\tdefault:\n\t\t\treturn err\n\t\tcase gomemcached.MCResponse:\n\t\t\tst := err.(gomemcached.MCResponse).Status\n\t\t\tatomic.AddUint64(&b.pool.client.Statuses[st], 1)\n\t\t\tif st == gomemcached.NOT_MY_VBUCKET {\n\t\t\t\tb.refresh()\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tpanic(\"Unreachable.\")\n}\n\ntype gathered_stats struct {\n\tsn   string\n\tvals map[string]string\n}\n\nfunc getStatsParallel(b *Bucket, offset int, which string, ch chan<- gathered_stats) {\n\tsn := b.VBucketServerMap.ServerList[offset]\n\n\tresults := map[string]string{}\n\tconn, err := b.connections[offset].Get()\n\tdefer b.connections[offset].Return(conn)\n\tif err != nil {\n\t\tch <- gathered_stats{sn, results}\n\t} else {\n\t\tst, err := conn.StatsMap(which)\n\t\tif err == nil {\n\t\t\tch <- gathered_stats{sn, st}\n\t\t} else {\n\t\t\tch <- gathered_stats{sn, results}\n\t\t}\n\t}\n}\n\n\/\/ Get a set of stats from all servers.\n\/\/\n\/\/ Returns a map of server ID -> map of stat key to map value.\nfunc (b *Bucket) GetStats(which string) map[string]map[string]string {\n\trv := map[string]map[string]string{}\n\n\tif b.VBucketServerMap.ServerList == nil {\n\t\treturn rv\n\t}\n\t\/\/ Go grab all the things at once.\n\ttodo := len(b.VBucketServerMap.ServerList)\n\tch := make(chan gathered_stats, todo)\n\n\tfor offset, _ := range b.VBucketServerMap.ServerList {\n\t\tgo getStatsParallel(b, offset, which, ch)\n\t}\n\n\t\/\/ Gather the results\n\tfor i := 0; i < len(b.VBucketServerMap.ServerList); i++ {\n\t\tg := <-ch\n\t\tif len(g.vals) > 0 {\n\t\t\trv[g.sn] = g.vals\n\t\t}\n\t}\n\n\treturn rv\n}\n\nfunc (b *Bucket) doBulkGet(vb uint16, keys []string,\n\tch chan<- map[string]*gomemcached.MCResponse) {\n\n\tmasterId := b.VBucketServerMap.VBucketMap[vb][0]\n\tconn, err := b.connections[masterId].Get()\n\tif err != nil {\n\t\tch <- map[string]*gomemcached.MCResponse{}\n\t}\n\tdefer b.connections[masterId].Return(conn)\n\n\tm, err := conn.GetBulk(vb, keys)\n\tswitch err.(type) {\n\tdefault:\n\t\tch <- m\n\tcase *gomemcached.MCResponse:\n\t\tfmt.Printf(\"Got a memcached error\")\n\t\tst := err.(gomemcached.MCResponse).Status\n\t\tatomic.AddUint64(&b.pool.client.Statuses[st], 1)\n\t\tif st == gomemcached.NOT_MY_VBUCKET {\n\t\t\tb.refresh()\n\t\t}\n\t\tch <- map[string]*gomemcached.MCResponse{}\n\t}\n}\n\nfunc (b *Bucket) processBulkGet(kdm map[uint16][]string,\n\tch chan map[string]*gomemcached.MCResponse) {\n\n\twch := make(chan uint16)\n\n\tworker := func() {\n\t\tfor k := range wch {\n\t\t\tb.doBulkGet(k, kdm[k], ch)\n\t\t}\n\t}\n\n\tfor i := 0; i < 4; i++ {\n\t\tgo worker()\n\t}\n\n\tfor k := range kdm {\n\t\twch <- k\n\t}\n\tclose(wch)\n\n}\nfunc (b *Bucket) GetBulk(keys []string) map[string]*gomemcached.MCResponse {\n\t\/\/ Organize by vbucket\n\tkdm := map[uint16][]string{}\n\tfor _, k := range keys {\n\t\tvb := uint16(b.VBHash(k))\n\t\ta, ok := kdm[vb]\n\t\tif !ok {\n\t\t\ta = []string{}\n\t\t}\n\t\tkdm[vb] = append(a, k)\n\t}\n\n\tch := make(chan map[string]*gomemcached.MCResponse)\n\tdefer close(ch)\n\n\tgo b.processBulkGet(kdm, ch)\n\n\trv := map[string]*gomemcached.MCResponse{}\n\tfor _ = range kdm {\n\t\tm := <-ch\n\t\tfor k, v := range m {\n\t\t\trv[k] = v\n\t\t}\n\t}\n\n\treturn rv\n}\n\n\/\/ Set a value in this bucket.\n\/\/ The value will be serialized into a JSON document.\nfunc (b *Bucket) Set(k string, exp int, v interface{}) error {\n\tdata, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn b.SetRaw(k, exp, data)\n}\n\n\/\/ Set a value in this bucket.\n\/\/ The value will be stored as raw bytes.\nfunc (b *Bucket) SetRaw(k string, exp int, v []byte) error {\n\treturn b.Do(k, func(mc *memcached.Client, vb uint16) error {\n\t\tres, err := mc.Set(vb, k, 0, exp, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif res.Status != gomemcached.SUCCESS {\n\t\t\treturn res\n\t\t}\n\t\treturn nil\n\t})\n}\n\n\/\/ Adds a value to this bucket; like Set except that nothing happens if the key exists.\n\/\/ The value will be serialized into a JSON document.\nfunc (b *Bucket) Add(k string, exp int, v interface{}) (added bool, err error) {\n\tdata, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn b.AddRaw(k, exp, data)\n}\n\n\/\/ Adds a value to this bucket; like SetRaw except that nothing happens if the key exists.\n\/\/ The value will be stored as raw bytes.\nfunc (b *Bucket) AddRaw(k string, exp int, v []byte) (added bool, err error) {\n\terr = b.Do(k, func(mc *memcached.Client, vb uint16) error {\n\t\tswitch res, err := mc.Add(vb, k, 0, exp, v); {\n\t\tcase err != nil:\n\t\t\treturn err\n\t\tcase res.Status == gomemcached.SUCCESS:\n\t\t\tadded = true\n\t\tcase res.Status != gomemcached.KEY_EEXISTS:\n\t\t\treturn res\n\t\t}\n\t\treturn nil\n\t})\n\treturn\n}\n\n\/\/ Get a raw value from this bucket, including its CAS counter.\nfunc (b *Bucket) GetsRaw(k string, cas *uint64) ([]byte, error) {\n\tvar data []byte\n\terr := b.Do(k, func(mc *memcached.Client, vb uint16) error {\n\t\tres, err := mc.Get(vb, k)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif res.Status != gomemcached.SUCCESS {\n\t\t\treturn res\n\t\t}\n\t\tif cas != nil {\n\t\t\t*cas = res.Cas\n\t\t}\n\t\tdata = res.Body\n\t\treturn nil\n\t})\n\treturn data, err\n}\n\n\/\/ Get a value from this bucket, including its CAS counter.\n\/\/ The value is expected to be a JSON stream and will be deserialized\n\/\/ into rv.\nfunc (b *Bucket) Gets(k string, rv interface{}, cas *uint64) error {\n\tdata, err := b.GetsRaw(k, cas)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, rv)\n}\n\n\/\/ Get a value from this bucket.\n\/\/ The value is expected to be a JSON stream and will be deserialized\n\/\/ into rv.\nfunc (b *Bucket) Get(k string, rv interface{}) error {\n\treturn b.Gets(k, rv, nil)\n}\n\n\/\/ Get a raw value from this bucket.\nfunc (b *Bucket) GetRaw(k string) ([]byte, error) {\n\treturn b.GetsRaw(k, nil)\n}\n\n\/\/ Delete a key from this bucket.\nfunc (b *Bucket) Delete(k string) error {\n\treturn b.Do(k, func(mc *memcached.Client, vb uint16) error {\n\t\tres, err := mc.Del(vb, k)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif res.Status != gomemcached.SUCCESS {\n\t\t\treturn res\n\t\t}\n\t\treturn nil\n\t})\n}\n\n\/\/ Increment a key\nfunc (b *Bucket) Incr(k string, amt, def uint64, exp int) (uint64, error) {\n\tvar rv uint64\n\terr := b.Do(k, func(mc *memcached.Client, vb uint16) error {\n\t\tres, err := mc.Incr(vb, k, amt, def, exp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trv = res\n\t\treturn nil\n\t})\n\treturn rv, err\n}\n\ntype ViewRow struct {\n\tID    string\n\tKey   interface{}\n\tValue interface{}\n\tDoc   *interface{}\n}\n\ntype ViewError struct {\n\tFrom   string\n\tReason string\n}\n\nfunc (ve ViewError) Error() string {\n\treturn fmt.Sprintf(\"Node: %v, reason: %v\", ve.From, ve.Reason)\n}\n\ntype ViewResult struct {\n\tTotalRows int `json:\"total_rows\"`\n\tRows      []ViewRow\n\tErrors    []ViewError\n}\n\n\/\/ Document ID type for the startkey_docid parameter in views.\ntype DocId string\n\n\/\/ Perform a view request that can map row values to a custom type.\n\/\/\n\/\/ See the source to View for an example usage.\nfunc (b *Bucket) ViewCustom(ddoc, name string, params map[string]interface{},\n\tvres interface{}) error {\n\n\t\/\/ Pick a random node to service our request.\n\tnode := b.Nodes[rand.Intn(len(b.Nodes))]\n\tu, err := url.Parse(node.CouchAPIBase)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalues := url.Values{}\n\tfor k, v := range params {\n\t\tswitch t := v.(type) {\n\t\tcase DocId:\n\t\t\tvalues[k] = []string{string(t)}\n\t\tcase string:\n\t\t\tvalues[k] = []string{fmt.Sprintf(`\"%s\"`, t)}\n\t\tcase int:\n\t\t\tvalues[k] = []string{fmt.Sprintf(`%d`, t)}\n\t\tcase bool:\n\t\t\tvalues[k] = []string{fmt.Sprintf(`%v`, t)}\n\t\tdefault:\n\t\t\tb, err := json.Marshal(v)\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"unsupported value-type %T in Query, json encoder said %v\", t, err))\n\t\t\t}\n\t\t\tvalues[k] = []string{fmt.Sprintf(`%v`, string(b))}\n\t\t}\n\t}\n\n\tu.Path = fmt.Sprintf(\"\/%s\/_design\/%s\/_view\/%s\", b.Name, ddoc, name)\n\tu.RawQuery = values.Encode()\n\n\tres, err := HttpClient.Get(u.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 200 {\n\t\treturn errors.New(res.Status)\n\t}\n\n\td := json.NewDecoder(res.Body)\n\tif err := d.Decode(vres); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Execute a view\nfunc (b *Bucket) View(ddoc, name string, params map[string]interface{}) (ViewResult, error) {\n\tvres := ViewResult{}\n\treturn vres, b.ViewCustom(ddoc, name, params, &vres)\n}\n<commit_msg>Handle Get() and Return() on nil pools.<commit_after>\/*\nA smart client for go.\n\nUsage:\n\n client, err := couchbase.Connect(\"http:\/\/myserver:8091\/\")\n handleError(err)\n pool, err := client.GetPool(\"default\")\n handleError(err)\n bucket, err := pool.getBucket(\"MyAwesomeBucket\")\n handleError(err)\n ...\n\nor a shortcut for the bucket directly\n\n bucket, err := couchbase.GetBucket(\"http:\/\/myserver:8091\/\", \"default\", \"default\")\n*\/\npackage couchbase\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"net\/url\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\n\t\"github.com\/dustin\/gomemcached\"\n\t\"github.com\/dustin\/gomemcached\/client\"\n)\n\ntype connectionPool struct {\n\thost        string\n\tname        string\n\tconnections []*memcached.Client\n\tmutex       sync.Mutex\n}\n\nfunc (cp *connectionPool) Close() error {\n\tcp.mutex.Lock()\n\tdefer cp.mutex.Unlock()\n\tfor _, c := range cp.connections {\n\t\tc.Close()\n\t}\n\tcp.connections = []*memcached.Client{}\n\treturn nil\n}\n\nfunc (cp *connectionPool) Get() (*memcached.Client, error) {\n\tif cp == nil {\n\t\treturn nil, errors.New(\"no pool\")\n\t}\n\tcp.mutex.Lock()\n\tdefer cp.mutex.Unlock()\n\n\tif len(cp.connections) == 0 {\n\t\tconn, err := memcached.Connect(\"tcp\", cp.host)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif cp.name != \"default\" {\n\t\t\tconn.Auth(cp.name, \"\")\n\t\t}\n\n\t\tcp.connections = append(cp.connections, conn)\n\t}\n\n\trv := cp.connections[0]\n\tcp.connections = cp.connections[1:]\n\n\treturn rv, nil\n}\n\nfunc (cp *connectionPool) Return(c *memcached.Client) {\n\tif cp == nil {\n\t\treturn\n\t}\n\tcp.mutex.Lock()\n\tdefer cp.mutex.Unlock()\n\n\tif c != nil {\n\t\tif c.IsHealthy() {\n\t\t\tcp.connections = append(cp.connections, c)\n\t\t} else {\n\t\t\tc.Close()\n\t\t}\n\t}\n}\n\n\/\/ Execute a function on a memcached connection to the node owning key \"k\"\n\/\/\n\/\/ Note that this automatically handles transient errors by replaying\n\/\/ your function on a \"not-my-vbucket\" error, so don't assume\n\/\/ your command will only be executed only once.\nfunc (b *Bucket) Do(k string, f func(mc *memcached.Client, vb uint16) error) error {\n\tvb := b.VBHash(k)\n\tfor {\n\t\tmasterId := b.VBucketServerMap.VBucketMap[vb][0]\n\t\tconn, err := b.connections[masterId].Get()\n\t\tdefer b.connections[masterId].Return(conn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = f(conn, uint16(vb))\n\t\tswitch err.(type) {\n\t\tdefault:\n\t\t\treturn err\n\t\tcase gomemcached.MCResponse:\n\t\t\tst := err.(gomemcached.MCResponse).Status\n\t\t\tatomic.AddUint64(&b.pool.client.Statuses[st], 1)\n\t\t\tif st == gomemcached.NOT_MY_VBUCKET {\n\t\t\t\tb.refresh()\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tpanic(\"Unreachable.\")\n}\n\ntype gathered_stats struct {\n\tsn   string\n\tvals map[string]string\n}\n\nfunc getStatsParallel(b *Bucket, offset int, which string, ch chan<- gathered_stats) {\n\tsn := b.VBucketServerMap.ServerList[offset]\n\n\tresults := map[string]string{}\n\tconn, err := b.connections[offset].Get()\n\tdefer b.connections[offset].Return(conn)\n\tif err != nil {\n\t\tch <- gathered_stats{sn, results}\n\t} else {\n\t\tst, err := conn.StatsMap(which)\n\t\tif err == nil {\n\t\t\tch <- gathered_stats{sn, st}\n\t\t} else {\n\t\t\tch <- gathered_stats{sn, results}\n\t\t}\n\t}\n}\n\n\/\/ Get a set of stats from all servers.\n\/\/\n\/\/ Returns a map of server ID -> map of stat key to map value.\nfunc (b *Bucket) GetStats(which string) map[string]map[string]string {\n\trv := map[string]map[string]string{}\n\n\tif b.VBucketServerMap.ServerList == nil {\n\t\treturn rv\n\t}\n\t\/\/ Go grab all the things at once.\n\ttodo := len(b.VBucketServerMap.ServerList)\n\tch := make(chan gathered_stats, todo)\n\n\tfor offset, _ := range b.VBucketServerMap.ServerList {\n\t\tgo getStatsParallel(b, offset, which, ch)\n\t}\n\n\t\/\/ Gather the results\n\tfor i := 0; i < len(b.VBucketServerMap.ServerList); i++ {\n\t\tg := <-ch\n\t\tif len(g.vals) > 0 {\n\t\t\trv[g.sn] = g.vals\n\t\t}\n\t}\n\n\treturn rv\n}\n\nfunc (b *Bucket) doBulkGet(vb uint16, keys []string,\n\tch chan<- map[string]*gomemcached.MCResponse) {\n\n\tmasterId := b.VBucketServerMap.VBucketMap[vb][0]\n\tconn, err := b.connections[masterId].Get()\n\tif err != nil {\n\t\tch <- map[string]*gomemcached.MCResponse{}\n\t}\n\tdefer b.connections[masterId].Return(conn)\n\n\tm, err := conn.GetBulk(vb, keys)\n\tswitch err.(type) {\n\tdefault:\n\t\tch <- m\n\tcase *gomemcached.MCResponse:\n\t\tfmt.Printf(\"Got a memcached error\")\n\t\tst := err.(gomemcached.MCResponse).Status\n\t\tatomic.AddUint64(&b.pool.client.Statuses[st], 1)\n\t\tif st == gomemcached.NOT_MY_VBUCKET {\n\t\t\tb.refresh()\n\t\t}\n\t\tch <- map[string]*gomemcached.MCResponse{}\n\t}\n}\n\nfunc (b *Bucket) processBulkGet(kdm map[uint16][]string,\n\tch chan map[string]*gomemcached.MCResponse) {\n\n\twch := make(chan uint16)\n\n\tworker := func() {\n\t\tfor k := range wch {\n\t\t\tb.doBulkGet(k, kdm[k], ch)\n\t\t}\n\t}\n\n\tfor i := 0; i < 4; i++ {\n\t\tgo worker()\n\t}\n\n\tfor k := range kdm {\n\t\twch <- k\n\t}\n\tclose(wch)\n\n}\nfunc (b *Bucket) GetBulk(keys []string) map[string]*gomemcached.MCResponse {\n\t\/\/ Organize by vbucket\n\tkdm := map[uint16][]string{}\n\tfor _, k := range keys {\n\t\tvb := uint16(b.VBHash(k))\n\t\ta, ok := kdm[vb]\n\t\tif !ok {\n\t\t\ta = []string{}\n\t\t}\n\t\tkdm[vb] = append(a, k)\n\t}\n\n\tch := make(chan map[string]*gomemcached.MCResponse)\n\tdefer close(ch)\n\n\tgo b.processBulkGet(kdm, ch)\n\n\trv := map[string]*gomemcached.MCResponse{}\n\tfor _ = range kdm {\n\t\tm := <-ch\n\t\tfor k, v := range m {\n\t\t\trv[k] = v\n\t\t}\n\t}\n\n\treturn rv\n}\n\n\/\/ Set a value in this bucket.\n\/\/ The value will be serialized into a JSON document.\nfunc (b *Bucket) Set(k string, exp int, v interface{}) error {\n\tdata, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn b.SetRaw(k, exp, data)\n}\n\n\/\/ Set a value in this bucket.\n\/\/ The value will be stored as raw bytes.\nfunc (b *Bucket) SetRaw(k string, exp int, v []byte) error {\n\treturn b.Do(k, func(mc *memcached.Client, vb uint16) error {\n\t\tres, err := mc.Set(vb, k, 0, exp, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif res.Status != gomemcached.SUCCESS {\n\t\t\treturn res\n\t\t}\n\t\treturn nil\n\t})\n}\n\n\/\/ Adds a value to this bucket; like Set except that nothing happens if the key exists.\n\/\/ The value will be serialized into a JSON document.\nfunc (b *Bucket) Add(k string, exp int, v interface{}) (added bool, err error) {\n\tdata, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn b.AddRaw(k, exp, data)\n}\n\n\/\/ Adds a value to this bucket; like SetRaw except that nothing happens if the key exists.\n\/\/ The value will be stored as raw bytes.\nfunc (b *Bucket) AddRaw(k string, exp int, v []byte) (added bool, err error) {\n\terr = b.Do(k, func(mc *memcached.Client, vb uint16) error {\n\t\tswitch res, err := mc.Add(vb, k, 0, exp, v); {\n\t\tcase err != nil:\n\t\t\treturn err\n\t\tcase res.Status == gomemcached.SUCCESS:\n\t\t\tadded = true\n\t\tcase res.Status != gomemcached.KEY_EEXISTS:\n\t\t\treturn res\n\t\t}\n\t\treturn nil\n\t})\n\treturn\n}\n\n\/\/ Get a raw value from this bucket, including its CAS counter.\nfunc (b *Bucket) GetsRaw(k string, cas *uint64) ([]byte, error) {\n\tvar data []byte\n\terr := b.Do(k, func(mc *memcached.Client, vb uint16) error {\n\t\tres, err := mc.Get(vb, k)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif res.Status != gomemcached.SUCCESS {\n\t\t\treturn res\n\t\t}\n\t\tif cas != nil {\n\t\t\t*cas = res.Cas\n\t\t}\n\t\tdata = res.Body\n\t\treturn nil\n\t})\n\treturn data, err\n}\n\n\/\/ Get a value from this bucket, including its CAS counter.\n\/\/ The value is expected to be a JSON stream and will be deserialized\n\/\/ into rv.\nfunc (b *Bucket) Gets(k string, rv interface{}, cas *uint64) error {\n\tdata, err := b.GetsRaw(k, cas)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, rv)\n}\n\n\/\/ Get a value from this bucket.\n\/\/ The value is expected to be a JSON stream and will be deserialized\n\/\/ into rv.\nfunc (b *Bucket) Get(k string, rv interface{}) error {\n\treturn b.Gets(k, rv, nil)\n}\n\n\/\/ Get a raw value from this bucket.\nfunc (b *Bucket) GetRaw(k string) ([]byte, error) {\n\treturn b.GetsRaw(k, nil)\n}\n\n\/\/ Delete a key from this bucket.\nfunc (b *Bucket) Delete(k string) error {\n\treturn b.Do(k, func(mc *memcached.Client, vb uint16) error {\n\t\tres, err := mc.Del(vb, k)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif res.Status != gomemcached.SUCCESS {\n\t\t\treturn res\n\t\t}\n\t\treturn nil\n\t})\n}\n\n\/\/ Increment a key\nfunc (b *Bucket) Incr(k string, amt, def uint64, exp int) (uint64, error) {\n\tvar rv uint64\n\terr := b.Do(k, func(mc *memcached.Client, vb uint16) error {\n\t\tres, err := mc.Incr(vb, k, amt, def, exp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trv = res\n\t\treturn nil\n\t})\n\treturn rv, err\n}\n\ntype ViewRow struct {\n\tID    string\n\tKey   interface{}\n\tValue interface{}\n\tDoc   *interface{}\n}\n\ntype ViewError struct {\n\tFrom   string\n\tReason string\n}\n\nfunc (ve ViewError) Error() string {\n\treturn fmt.Sprintf(\"Node: %v, reason: %v\", ve.From, ve.Reason)\n}\n\ntype ViewResult struct {\n\tTotalRows int `json:\"total_rows\"`\n\tRows      []ViewRow\n\tErrors    []ViewError\n}\n\n\/\/ Document ID type for the startkey_docid parameter in views.\ntype DocId string\n\n\/\/ Perform a view request that can map row values to a custom type.\n\/\/\n\/\/ See the source to View for an example usage.\nfunc (b *Bucket) ViewCustom(ddoc, name string, params map[string]interface{},\n\tvres interface{}) error {\n\n\t\/\/ Pick a random node to service our request.\n\tnode := b.Nodes[rand.Intn(len(b.Nodes))]\n\tu, err := url.Parse(node.CouchAPIBase)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalues := url.Values{}\n\tfor k, v := range params {\n\t\tswitch t := v.(type) {\n\t\tcase DocId:\n\t\t\tvalues[k] = []string{string(t)}\n\t\tcase string:\n\t\t\tvalues[k] = []string{fmt.Sprintf(`\"%s\"`, t)}\n\t\tcase int:\n\t\t\tvalues[k] = []string{fmt.Sprintf(`%d`, t)}\n\t\tcase bool:\n\t\t\tvalues[k] = []string{fmt.Sprintf(`%v`, t)}\n\t\tdefault:\n\t\t\tb, err := json.Marshal(v)\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"unsupported value-type %T in Query, json encoder said %v\", t, err))\n\t\t\t}\n\t\t\tvalues[k] = []string{fmt.Sprintf(`%v`, string(b))}\n\t\t}\n\t}\n\n\tu.Path = fmt.Sprintf(\"\/%s\/_design\/%s\/_view\/%s\", b.Name, ddoc, name)\n\tu.RawQuery = values.Encode()\n\n\tres, err := HttpClient.Get(u.String())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != 200 {\n\t\treturn errors.New(res.Status)\n\t}\n\n\td := json.NewDecoder(res.Body)\n\tif err := d.Decode(vres); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Execute a view\nfunc (b *Bucket) View(ddoc, name string, params map[string]interface{}) (ViewResult, error) {\n\tvres := ViewResult{}\n\treturn vres, b.ViewCustom(ddoc, name, params, &vres)\n}\n<|endoftext|>"}
{"text":"<commit_before>package dockertest\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\n\t\"github.com\/crewjam\/errset\"\n\t\"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/api\/types\/container\"\n\t\"github.com\/docker\/docker\/api\/types\/filters\"\n\t\"github.com\/docker\/docker\/api\/types\/network\"\n\t\"github.com\/docker\/docker\/client\"\n)\n\nvar (\n\t\/\/ ErrContainerNotFound is returned by GetContainer if we were\n\t\/\/ unable to find the requested container.\n\tErrContainerNotFound = errors.New(\"failed to locate the container\")\n)\n\n\/\/ DockerClient provides a wrapper for the standard docker client. The intent\n\/\/ is to wrap common operations so the internal of docker's own client are\n\/\/ abstracted. Use NewClient() to construct and produce this struct.\ntype DockerClient struct {\n\tdocker *client.Client\n\tctx    context.Context\n}\n\n\/\/ NewClient produces a *DockerClient struct.\nfunc NewClient(ctx context.Context) (*DockerClient, error) {\n\tdocker, err := client.NewEnvClient()\n\treturn &DockerClient{docker: docker, ctx: ctx}, err\n}\n\n\/\/ ContainerInfo retrieves a single container by id and returns a\n\/\/ *ContainerInfo struct.\nfunc (d *DockerClient) ContainerInfo(id string) (*ContainerInfo, error) {\n\targs := filters.NewArgs()\n\targs.Add(\"id\", id)\n\n\toptions := types.ContainerListOptions{Filters: args, All: true}\n\tcontainers, err := d.docker.ContainerList(d.ctx, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(containers) == 0 {\n\t\treturn nil, ErrContainerNotFound\n\t}\n\n\tinspection, err := d.docker.ContainerInspect(d.ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ContainerInfo{\n\t\tData:     containers[0],\n\t\tState:    inspection.State,\n\t\tJSON:     inspection,\n\t\tWarnings: []string{},\n\t\tclient:   d,\n\t}, nil\n}\n\n\/\/ ListContainers will return a list of *ContainerInfo structs based on the\n\/\/ provided input.\nfunc (d *DockerClient) ListContainers(input *ClientInput) ([]*ContainerInfo, error) {\n\toptions := types.ContainerListOptions{\n\t\tAll:     input.All,\n\t\tSince:   input.Since,\n\t\tBefore:  input.Before,\n\t\tFilters: input.FilterArgs(),\n\t}\n\n\tlisted, err := d.docker.ContainerList(d.ctx, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontainers := make(chan *ContainerInfo)\n\terrs := make(chan error)\n\n\tfor _, entry := range listed {\n\t\tgo func(c types.Container) {\n\t\t\tinfo, err := d.ContainerInfo(c.ID)\n\t\t\tif err != nil {\n\t\t\t\terrs <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontainers <- info\n\t\t}(entry)\n\t}\n\n\tresults := []*ContainerInfo{}\n\terrout := errset.ErrSet{}\n\tfor i := 0; i < len(listed); i++ {\n\t\tselect {\n\t\tcase err := <-errs:\n\t\t\terrout = append(errout, err)\n\t\tcase info := <-containers:\n\t\t\tresults = append(results, info)\n\t\t}\n\t}\n\n\treturn results, errout.ReturnValue()\n}\n\n\/\/ RemoveContainer will delete the requested Container, force terminating\n\/\/ it if necessary.\nfunc (d *DockerClient) RemoveContainer(id string) error {\n\terr := d.docker.ContainerRemove(d.ctx, id, types.ContainerRemoveOptions{Force: true})\n\n\t\/\/ Docker's API does not expose their error structs and their\n\t\/\/ IsErrNotFound does not seem to work.\n\tif err != nil && strings.Contains(err.Error(), \"No such container\") {\n\t\treturn nil\n\t}\n\treturn err\n}\n\n\/\/ RunContainer will run a new c and return the results. By default\n\/\/ all ports that are exposed by the c will be published to the host\n\/\/ randomly. The published ports will be accessible using functions on the\n\/\/ struct:\n\/\/    client, err := NewClient()\n\/\/    c := client.RunContainer(\"testimage\", \"testing\", nil)\n\/\/    port, err := c.Port(80)\n\/\/    port.External\nfunc (d *DockerClient) RunContainer(input *ClientInput) (*ContainerInfo, error) {\n\tbindings, err := input.Ports.Bindings()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tctx, cancel := context.WithTimeout(d.ctx, DefaultServiceTimeout)\n\tdefer cancel()\n\n\tif input.Timeout.Nanoseconds() > 0 {\n\t\tcancel()\n\t\tctx, cancel = context.WithTimeout(d.ctx, input.Timeout)\n\t}\n\n\tfor {\n\t\tcreated, err := d.docker.ContainerCreate(\n\t\t\tctx,\n\t\t\tinput.ContainerConfig(),\n\t\t\t&container.HostConfig{PortBindings: bindings}, &network.NetworkingConfig{}, \"\")\n\t\tif client.IsErrNotFound(err) {\n\t\t\treader, err := d.docker.ImagePull(ctx, input.Image, types.ImagePullOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif _, err := io.Copy(ioutil.Discard, reader); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := d.docker.ContainerStart(ctx, created.ID, types.ContainerStartOptions{}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinfo, err := d.ContainerInfo(created.ID)\n\t\tinfo.Warnings = created.Warnings\n\t\treturn info, err\n\t}\n}\n\n\/\/ Service will return a *Service struct that may be used to spin up\n\/\/ a specific service. See the documentation present on the Service struct\n\/\/ for more information.\nfunc (d *DockerClient) Service(input *ClientInput) *Service {\n\ttimeout := input.Timeout\n\tif timeout.Nanoseconds() == 0 {\n\t\ttimeout = DefaultServiceTimeout\n\t}\n\tctx, _ := context.WithTimeout(d.ctx, timeout)\n\treturn &Service{Context: ctx, Input: input, Client: d}\n}\n<commit_msg>minor move<commit_after>package dockertest\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\n\t\"github.com\/crewjam\/errset\"\n\t\"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/api\/types\/container\"\n\t\"github.com\/docker\/docker\/api\/types\/filters\"\n\t\"github.com\/docker\/docker\/api\/types\/network\"\n\t\"github.com\/docker\/docker\/client\"\n)\n\nvar (\n\t\/\/ ErrContainerNotFound is returned by GetContainer if we were\n\t\/\/ unable to find the requested container.\n\tErrContainerNotFound = errors.New(\"failed to locate the container\")\n)\n\n\/\/ DockerClient provides a wrapper for the standard docker client. The intent\n\/\/ is to wrap common operations so the internal of docker's own client are\n\/\/ abstracted. Use NewClient() to construct and produce this struct.\ntype DockerClient struct {\n\tdocker *client.Client\n\tctx    context.Context\n}\n\n\/\/ ContainerInfo retrieves a single container by id and returns a\n\/\/ *ContainerInfo struct.\nfunc (d *DockerClient) ContainerInfo(id string) (*ContainerInfo, error) {\n\targs := filters.NewArgs()\n\targs.Add(\"id\", id)\n\n\toptions := types.ContainerListOptions{Filters: args, All: true}\n\tcontainers, err := d.docker.ContainerList(d.ctx, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(containers) == 0 {\n\t\treturn nil, ErrContainerNotFound\n\t}\n\n\tinspection, err := d.docker.ContainerInspect(d.ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ContainerInfo{\n\t\tData:     containers[0],\n\t\tState:    inspection.State,\n\t\tJSON:     inspection,\n\t\tWarnings: []string{},\n\t\tclient:   d,\n\t}, nil\n}\n\n\/\/ ListContainers will return a list of *ContainerInfo structs based on the\n\/\/ provided input.\nfunc (d *DockerClient) ListContainers(input *ClientInput) ([]*ContainerInfo, error) {\n\toptions := types.ContainerListOptions{\n\t\tAll:     input.All,\n\t\tSince:   input.Since,\n\t\tBefore:  input.Before,\n\t\tFilters: input.FilterArgs(),\n\t}\n\n\tlisted, err := d.docker.ContainerList(d.ctx, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontainers := make(chan *ContainerInfo)\n\terrs := make(chan error)\n\n\tfor _, entry := range listed {\n\t\tgo func(c types.Container) {\n\t\t\tinfo, err := d.ContainerInfo(c.ID)\n\t\t\tif err != nil {\n\t\t\t\terrs <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcontainers <- info\n\t\t}(entry)\n\t}\n\n\tresults := []*ContainerInfo{}\n\terrout := errset.ErrSet{}\n\tfor i := 0; i < len(listed); i++ {\n\t\tselect {\n\t\tcase err := <-errs:\n\t\t\terrout = append(errout, err)\n\t\tcase info := <-containers:\n\t\t\tresults = append(results, info)\n\t\t}\n\t}\n\n\treturn results, errout.ReturnValue()\n}\n\n\/\/ RemoveContainer will delete the requested Container, force terminating\n\/\/ it if necessary.\nfunc (d *DockerClient) RemoveContainer(id string) error {\n\terr := d.docker.ContainerRemove(d.ctx, id, types.ContainerRemoveOptions{Force: true})\n\n\t\/\/ Docker's API does not expose their error structs and their\n\t\/\/ IsErrNotFound does not seem to work.\n\tif err != nil && strings.Contains(err.Error(), \"No such container\") {\n\t\treturn nil\n\t}\n\treturn err\n}\n\n\/\/ RunContainer will run a new c and return the results. By default\n\/\/ all ports that are exposed by the c will be published to the host\n\/\/ randomly. The published ports will be accessible using functions on the\n\/\/ struct:\n\/\/    client, err := NewClient()\n\/\/    c := client.RunContainer(\"testimage\", \"testing\", nil)\n\/\/    port, err := c.Port(80)\n\/\/    port.External\nfunc (d *DockerClient) RunContainer(input *ClientInput) (*ContainerInfo, error) {\n\tbindings, err := input.Ports.Bindings()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tctx, cancel := context.WithTimeout(d.ctx, DefaultServiceTimeout)\n\tdefer cancel()\n\n\tif input.Timeout.Nanoseconds() > 0 {\n\t\tcancel()\n\t\tctx, cancel = context.WithTimeout(d.ctx, input.Timeout)\n\t}\n\n\tfor {\n\t\tcreated, err := d.docker.ContainerCreate(\n\t\t\tctx,\n\t\t\tinput.ContainerConfig(),\n\t\t\t&container.HostConfig{PortBindings: bindings}, &network.NetworkingConfig{}, \"\")\n\t\tif client.IsErrNotFound(err) {\n\t\t\treader, err := d.docker.ImagePull(ctx, input.Image, types.ImagePullOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif _, err := io.Copy(ioutil.Discard, reader); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := d.docker.ContainerStart(ctx, created.ID, types.ContainerStartOptions{}); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinfo, err := d.ContainerInfo(created.ID)\n\t\tinfo.Warnings = created.Warnings\n\t\treturn info, err\n\t}\n}\n\n\/\/ Service will return a *Service struct that may be used to spin up\n\/\/ a specific service. See the documentation present on the Service struct\n\/\/ for more information.\nfunc (d *DockerClient) Service(input *ClientInput) *Service {\n\ttimeout := input.Timeout\n\tif timeout.Nanoseconds() == 0 {\n\t\ttimeout = DefaultServiceTimeout\n\t}\n\tctx, _ := context.WithTimeout(d.ctx, timeout)\n\treturn &Service{Context: ctx, Input: input, Client: d}\n}\n\n\/\/ NewClient produces a *DockerClient struct.\nfunc NewClient(ctx context.Context) (*DockerClient, error) {\n\tdocker, err := client.NewEnvClient()\n\treturn &DockerClient{docker: docker, ctx: ctx}, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\nThe MIT License (MIT)\n\nCopyright (c) 2015 Hajime Nakagami\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*******************************************************************************\/\n\npackage toybroker\n\nimport (\n\t\"net\"\n\t\"sync\"\n)\n\ntype Client struct {\n\tclientID         string\n\tloginName        string\n\tconn             net.Conn\n\tcurrentMessageID uint16\n\tsync.RWMutex\n}\n\nfunc NewClient(id string, name string, c net.Conn, oldClient *Client) *Client {\n\tclient := &Client{\n\t\tclientID:  id,\n\t\tloginName: name,\n\t\tconn:      c,\n\t}\n\treturn client\n}\n\nfunc (c *Client) GetClientID() string {\n\treturn c.clientID\n}\n\nfunc (c *Client) GetConn() net.Conn {\n\treturn c.conn\n}\n\nfunc (c *Client) getNextMessageID() uint16 {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.currentMessageID++\n\tif c.currentMessageID == 0 {\n\t\tc.currentMessageID++\n\t}\n\treturn c.currentMessageID\n}\n\nfunc (c *Client) Publish(dup bool, qos int, topic string, payload []byte) {\n\tc.conn.Write(packPUBLISH(dup, qos, topic, c.getNextMessageID(), payload))\n}\n\nfunc (c *Client) Send(data []byte) {\n\tc.conn.Write(data)\n}\n<commit_msg>add GetLoginName() method<commit_after>\/*******************************************************************************\nThe MIT License (MIT)\n\nCopyright (c) 2015 Hajime Nakagami\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*******************************************************************************\/\n\npackage toybroker\n\nimport (\n\t\"net\"\n\t\"sync\"\n)\n\ntype Client struct {\n\tclientID         string\n\tloginName        string\n\tconn             net.Conn\n\tcurrentMessageID uint16\n\tsync.RWMutex\n}\n\nfunc NewClient(id string, name string, c net.Conn, oldClient *Client) *Client {\n\tclient := &Client{\n\t\tclientID:  id,\n\t\tloginName: name,\n\t\tconn:      c,\n\t}\n\treturn client\n}\n\nfunc (c *Client) GetClientID() string {\n\treturn c.clientID\n}\n\nfunc (c *Client) GetLoginName() string {\n\treturn c.loginName\n}\n\nfunc (c *Client) GetConn() net.Conn {\n\treturn c.conn\n}\n\nfunc (c *Client) getNextMessageID() uint16 {\n\tc.Lock()\n\tdefer c.Unlock()\n\tc.currentMessageID++\n\tif c.currentMessageID == 0 {\n\t\tc.currentMessageID++\n\t}\n\treturn c.currentMessageID\n}\n\nfunc (c *Client) Publish(dup bool, qos int, topic string, payload []byte) {\n\tc.conn.Write(packPUBLISH(dup, qos, topic, c.getNextMessageID(), payload))\n}\n\nfunc (c *Client) Send(data []byte) {\n\tc.conn.Write(data)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2014 MessageBird B.V.\n\/\/ All rights reserved.\n\/\/\n\/\/ Author: Maurice Nonnekes <maurice@messagebird.com>\n\npackage messagebird\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nconst (\n\tClientVersion = \"2.2.0\"\n\tEndpoint      = \"https:\/\/rest.messagebird.com\"\n)\n\nvar (\n\tErrResponse           = errors.New(\"The MessageBird API returned an error\")\n\tErrUnexpectedResponse = errors.New(\"The MessageBird API is currently unavailable\")\n)\n\ntype Client struct {\n\tAccessKey  string       \/\/ The API access key\n\tHTTPClient *http.Client \/\/ The HTTP client to send requests on\n\tDebugLog   *log.Logger  \/\/ Optional logger for debugging purposes\n}\n\n\/\/ New creates a new MessageBird client object.\nfunc New(AccessKey string) *Client {\n\treturn &Client{AccessKey: AccessKey, HTTPClient: &http.Client{}}\n}\n\nfunc (c *Client) request(v interface{}, path string, params *url.Values) error {\n\turi, err := url.Parse(Endpoint + \"\/\" + path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar request *http.Request\n\tif params != nil {\n\t\tbody := params.Encode()\n\t\tif request, err = http.NewRequest(\"POST\", uri.String(), strings.NewReader(body)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif c.DebugLog != nil {\n\t\t\tif unescapedBody, err := url.QueryUnescape(body); err == nil {\n\t\t\t\tlog.Printf(\"HTTP REQUEST: POST %s %s\", uri.String(), unescapedBody)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"HTTP REQUEST: POST %s %s\", uri.String(), body)\n\t\t\t}\n\t\t}\n\n\t\trequest.Header.Set(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\t} else {\n\t\tif request, err = http.NewRequest(\"GET\", uri.String(), nil); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif c.DebugLog != nil {\n\t\t\tlog.Printf(\"HTTP REQUEST: GET %s\", uri.String())\n\t\t}\n\t}\n\n\trequest.Header.Add(\"Accept\", \"application\/json\")\n\trequest.Header.Add(\"Authorization\", \"AccessKey \"+c.AccessKey)\n\trequest.Header.Add(\"User-Agent\", \"MessageBird\/ApiClient\/\"+ClientVersion+\" Go\/\"+runtime.Version())\n\n\tresponse, err := c.HTTPClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer response.Body.Close()\n\n\tresponseBody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.DebugLog != nil {\n\t\tlog.Printf(\"HTTP RESPONSE: %s\", string(responseBody))\n\t}\n\n\t\/\/ Status code 500 is a server error and means nothing can be done at this\n\t\/\/ point.\n\tif response.StatusCode == 500 {\n\t\treturn ErrUnexpectedResponse\n\t}\n\n\tif err = json.Unmarshal(responseBody, &v); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Status codes 200 and 201 are indicative of being able to convert the\n\t\/\/ response body to the struct that was specified.\n\tif response.StatusCode == 200 || response.StatusCode == 201 {\n\t\treturn nil\n\t}\n\n\t\/\/ Anything else than a 200\/201\/500 should be a JSON error.\n\treturn ErrResponse\n}\n\n\/\/ Balance returns the balance information for the account that is associated\n\/\/ with the access key.\nfunc (c *Client) Balance() (*Balance, error) {\n\tbalance := &Balance{}\n\tif err := c.request(balance, \"balance\", nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn balance, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn balance, nil\n}\n\n\/\/ HLR looks up an existing HLR object for the specified id that was previously\n\/\/ created by the NewHLR function.\nfunc (c *Client) HLR(id string) (*HLR, error) {\n\thlr := &HLR{}\n\tif err := c.request(hlr, \"hlr\/\"+id, nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn hlr, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn hlr, nil\n}\n\n\/\/ NewHLR retrieves the information of an existing HLR.\nfunc (c *Client) NewHLR(msisdn, reference string) (*HLR, error) {\n\tparams := &url.Values{\n\t\t\"msisdn\":    {msisdn},\n\t\t\"reference\": {reference}}\n\n\thlr := &HLR{}\n\tif err := c.request(hlr, \"hlr\", params); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn hlr, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn hlr, nil\n}\n\n\/\/ Message retrieves the information of an existing Message.\nfunc (c *Client) Message(id string) (*Message, error) {\n\tmessage := &Message{}\n\tif err := c.request(message, \"messages\/\"+id, nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn message, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn message, nil\n}\n\n\/\/ NewMessage creates a new message for one or more recipients.\nfunc (c *Client) NewMessage(originator string, recipients []string, body string, msgParams *MessageParams) (*Message, error) {\n\tparams, err := paramsForMessage(msgParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams.Set(\"originator\", originator)\n\tparams.Set(\"body\", body)\n\tparams.Set(\"recipients\", strings.Join(recipients, \",\"))\n\n\tmessage := &Message{}\n\tif err := c.request(message, \"messages\", params); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn message, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn message, nil\n}\n\n\/\/ VoiceMessage retrieves the information of an existing VoiceMessage.\nfunc (c *Client) VoiceMessage(id string) (*VoiceMessage, error) {\n\tmessage := &VoiceMessage{}\n\tif err := c.request(message, \"voicemessages\/\"+id, nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn message, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn message, nil\n}\n\n\/\/ NewVoiceMessage creates a new voice message for one or more recipients.\nfunc (c *Client) NewVoiceMessage(recipients []string, body string, params *VoiceMessageParams) (*VoiceMessage, error) {\n\turlParams := paramsForVoiceMessage(params)\n\turlParams.Set(\"body\", body)\n\turlParams.Set(\"recipients\", strings.Join(recipients, \",\"))\n\n\tmessage := &VoiceMessage{}\n\tif err := c.request(message, \"voicemessages\", urlParams); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn message, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn message, nil\n}\n\n\/\/ OtpGenerate generates a new One-Time-Password for one recipient.\nfunc (c *Client) OtpGenerate(recipient string, params *OtpParams) (*OtpMessage, error) {\n\turlParams := paramsForOtp(params)\n\turlParams.Set(\"recipient\", recipient)\n\n\tmessage := &OtpMessage{}\n\tif err := c.request(message, \"otp\/generate\", urlParams); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn message, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn message, nil\n}\n\n\/\/ OtpVerify verifies the token that was generated with OtpGenerate.\nfunc (c *Client) OtpVerify(recipient string, token string, params *OtpParams) (*OtpMessage, error) {\n\turlParams := paramsForOtp(params)\n\turlParams.Set(\"recipient\", recipient)\n\turlParams.Set(\"token\", token)\n\n\tpath := \"otp\/verify?\" + urlParams.Encode()\n\n\tmessage := &OtpMessage{}\n\tif err := c.request(message, path, nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn message, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn message, nil\n}\n\n\/\/ Lookup performs a new lookup for the specified number.\nfunc (c *Client) Lookup(phoneNumber string, params *LookupParams) (*Lookup, error) {\n\turlParams := paramsForLookup(params)\n\tpath := \"lookup\/\" + phoneNumber + \"?\" + urlParams.Encode()\n\n\tlookup := &Lookup{}\n\tif err := c.request(lookup, path, nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn lookup, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn lookup, nil\n}\n\n\/\/ NewLookupHLR creates a new HLR lookup for the specified number.\nfunc (c *Client) NewLookupHLR(phoneNumber string, params *LookupParams) (*HLR, error) {\n\turlParams := paramsForLookup(params)\n\tpath := \"lookup\/\" + phoneNumber + \"\/hlr\"\n\n\thlr := &HLR{}\n\tif err := c.request(hlr, path, urlParams); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn hlr, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn hlr, nil\n}\n\n\/\/ LookupHLR performs a HLR lookup for the specified number.\nfunc (c *Client) LookupHLR(phoneNumber string, params *LookupParams) (*HLR, error) {\n\turlParams := paramsForLookup(params)\n\tpath := \"lookup\/\" + phoneNumber + \"\/hlr?\" + urlParams.Encode()\n\n\thlr := &HLR{}\n\tif err := c.request(hlr, path, nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn hlr, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn hlr, nil\n}\n<commit_msg>bump version to 2.2.1<commit_after>\/\/\n\/\/ Copyright (c) 2014 MessageBird B.V.\n\/\/ All rights reserved.\n\/\/\n\/\/ Author: Maurice Nonnekes <maurice@messagebird.com>\n\npackage messagebird\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nconst (\n\tClientVersion = \"2.2.1\"\n\tEndpoint      = \"https:\/\/rest.messagebird.com\"\n)\n\nvar (\n\tErrResponse           = errors.New(\"The MessageBird API returned an error\")\n\tErrUnexpectedResponse = errors.New(\"The MessageBird API is currently unavailable\")\n)\n\ntype Client struct {\n\tAccessKey  string       \/\/ The API access key\n\tHTTPClient *http.Client \/\/ The HTTP client to send requests on\n\tDebugLog   *log.Logger  \/\/ Optional logger for debugging purposes\n}\n\n\/\/ New creates a new MessageBird client object.\nfunc New(AccessKey string) *Client {\n\treturn &Client{AccessKey: AccessKey, HTTPClient: &http.Client{}}\n}\n\nfunc (c *Client) request(v interface{}, path string, params *url.Values) error {\n\turi, err := url.Parse(Endpoint + \"\/\" + path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar request *http.Request\n\tif params != nil {\n\t\tbody := params.Encode()\n\t\tif request, err = http.NewRequest(\"POST\", uri.String(), strings.NewReader(body)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif c.DebugLog != nil {\n\t\t\tif unescapedBody, err := url.QueryUnescape(body); err == nil {\n\t\t\t\tlog.Printf(\"HTTP REQUEST: POST %s %s\", uri.String(), unescapedBody)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"HTTP REQUEST: POST %s %s\", uri.String(), body)\n\t\t\t}\n\t\t}\n\n\t\trequest.Header.Set(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\t} else {\n\t\tif request, err = http.NewRequest(\"GET\", uri.String(), nil); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif c.DebugLog != nil {\n\t\t\tlog.Printf(\"HTTP REQUEST: GET %s\", uri.String())\n\t\t}\n\t}\n\n\trequest.Header.Add(\"Accept\", \"application\/json\")\n\trequest.Header.Add(\"Authorization\", \"AccessKey \"+c.AccessKey)\n\trequest.Header.Add(\"User-Agent\", \"MessageBird\/ApiClient\/\"+ClientVersion+\" Go\/\"+runtime.Version())\n\n\tresponse, err := c.HTTPClient.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer response.Body.Close()\n\n\tresponseBody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.DebugLog != nil {\n\t\tlog.Printf(\"HTTP RESPONSE: %s\", string(responseBody))\n\t}\n\n\t\/\/ Status code 500 is a server error and means nothing can be done at this\n\t\/\/ point.\n\tif response.StatusCode == 500 {\n\t\treturn ErrUnexpectedResponse\n\t}\n\n\tif err = json.Unmarshal(responseBody, &v); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Status codes 200 and 201 are indicative of being able to convert the\n\t\/\/ response body to the struct that was specified.\n\tif response.StatusCode == 200 || response.StatusCode == 201 {\n\t\treturn nil\n\t}\n\n\t\/\/ Anything else than a 200\/201\/500 should be a JSON error.\n\treturn ErrResponse\n}\n\n\/\/ Balance returns the balance information for the account that is associated\n\/\/ with the access key.\nfunc (c *Client) Balance() (*Balance, error) {\n\tbalance := &Balance{}\n\tif err := c.request(balance, \"balance\", nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn balance, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn balance, nil\n}\n\n\/\/ HLR looks up an existing HLR object for the specified id that was previously\n\/\/ created by the NewHLR function.\nfunc (c *Client) HLR(id string) (*HLR, error) {\n\thlr := &HLR{}\n\tif err := c.request(hlr, \"hlr\/\"+id, nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn hlr, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn hlr, nil\n}\n\n\/\/ NewHLR retrieves the information of an existing HLR.\nfunc (c *Client) NewHLR(msisdn, reference string) (*HLR, error) {\n\tparams := &url.Values{\n\t\t\"msisdn\":    {msisdn},\n\t\t\"reference\": {reference}}\n\n\thlr := &HLR{}\n\tif err := c.request(hlr, \"hlr\", params); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn hlr, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn hlr, nil\n}\n\n\/\/ Message retrieves the information of an existing Message.\nfunc (c *Client) Message(id string) (*Message, error) {\n\tmessage := &Message{}\n\tif err := c.request(message, \"messages\/\"+id, nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn message, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn message, nil\n}\n\n\/\/ NewMessage creates a new message for one or more recipients.\nfunc (c *Client) NewMessage(originator string, recipients []string, body string, msgParams *MessageParams) (*Message, error) {\n\tparams, err := paramsForMessage(msgParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams.Set(\"originator\", originator)\n\tparams.Set(\"body\", body)\n\tparams.Set(\"recipients\", strings.Join(recipients, \",\"))\n\n\tmessage := &Message{}\n\tif err := c.request(message, \"messages\", params); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn message, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn message, nil\n}\n\n\/\/ VoiceMessage retrieves the information of an existing VoiceMessage.\nfunc (c *Client) VoiceMessage(id string) (*VoiceMessage, error) {\n\tmessage := &VoiceMessage{}\n\tif err := c.request(message, \"voicemessages\/\"+id, nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn message, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn message, nil\n}\n\n\/\/ NewVoiceMessage creates a new voice message for one or more recipients.\nfunc (c *Client) NewVoiceMessage(recipients []string, body string, params *VoiceMessageParams) (*VoiceMessage, error) {\n\turlParams := paramsForVoiceMessage(params)\n\turlParams.Set(\"body\", body)\n\turlParams.Set(\"recipients\", strings.Join(recipients, \",\"))\n\n\tmessage := &VoiceMessage{}\n\tif err := c.request(message, \"voicemessages\", urlParams); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn message, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn message, nil\n}\n\n\/\/ OtpGenerate generates a new One-Time-Password for one recipient.\nfunc (c *Client) OtpGenerate(recipient string, params *OtpParams) (*OtpMessage, error) {\n\turlParams := paramsForOtp(params)\n\turlParams.Set(\"recipient\", recipient)\n\n\tmessage := &OtpMessage{}\n\tif err := c.request(message, \"otp\/generate\", urlParams); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn message, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn message, nil\n}\n\n\/\/ OtpVerify verifies the token that was generated with OtpGenerate.\nfunc (c *Client) OtpVerify(recipient string, token string, params *OtpParams) (*OtpMessage, error) {\n\turlParams := paramsForOtp(params)\n\turlParams.Set(\"recipient\", recipient)\n\turlParams.Set(\"token\", token)\n\n\tpath := \"otp\/verify?\" + urlParams.Encode()\n\n\tmessage := &OtpMessage{}\n\tif err := c.request(message, path, nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn message, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn message, nil\n}\n\n\/\/ Lookup performs a new lookup for the specified number.\nfunc (c *Client) Lookup(phoneNumber string, params *LookupParams) (*Lookup, error) {\n\turlParams := paramsForLookup(params)\n\tpath := \"lookup\/\" + phoneNumber + \"?\" + urlParams.Encode()\n\n\tlookup := &Lookup{}\n\tif err := c.request(lookup, path, nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn lookup, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn lookup, nil\n}\n\n\/\/ NewLookupHLR creates a new HLR lookup for the specified number.\nfunc (c *Client) NewLookupHLR(phoneNumber string, params *LookupParams) (*HLR, error) {\n\turlParams := paramsForLookup(params)\n\tpath := \"lookup\/\" + phoneNumber + \"\/hlr\"\n\n\thlr := &HLR{}\n\tif err := c.request(hlr, path, urlParams); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn hlr, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn hlr, nil\n}\n\n\/\/ LookupHLR performs a HLR lookup for the specified number.\nfunc (c *Client) LookupHLR(phoneNumber string, params *LookupParams) (*HLR, error) {\n\turlParams := paramsForLookup(params)\n\tpath := \"lookup\/\" + phoneNumber + \"\/hlr?\" + urlParams.Encode()\n\n\thlr := &HLR{}\n\tif err := c.request(hlr, path, nil); err != nil {\n\t\tif err == ErrResponse {\n\t\t\treturn hlr, err\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn hlr, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/rpc\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/mdempsky\/gocode\/gbimporter\"\n\t\"github.com\/mdempsky\/gocode\/suggest\"\n)\n\nfunc doClient() {\n\tif *g_debug {\n\t\tstart := time.Now()\n\t\tdefer func() {\n\t\t\telapsed := time.Since(start)\n\t\t\tlog.Printf(\"Elapsed duration: %v\\n\", elapsed)\n\t\t}()\n\t}\n\n\tvar command string\n\tif flag.NArg() > 0 {\n\t\tcommand = flag.Arg(0)\n\t\tswitch command {\n\t\tcase \"autocomplete\", \"exit\":\n\t\t\t\/\/ these are valid commands\n\t\tcase \"close\":\n\t\t\t\/\/ \"close\" is an alias for \"exit\"\n\t\t\tcommand = \"exit\"\n\t\tdefault:\n\t\t\tfmt.Printf(\"gocode: unknown subcommand: %q\\nRun 'gocode -help' for usage.\\n\", command)\n\t\t\tos.Exit(2)\n\t\t}\n\t}\n\n\t\/\/ client\n\tvar client *rpc.Client\n\tif *g_sock != \"none\" {\n\t\taddr := *g_addr\n\t\tif *g_sock == \"unix\" {\n\t\t\taddr = getSocketPath()\n\t\t}\n\n\t\tvar err error\n\t\tclient, err = rpc.Dial(*g_sock, addr)\n\t\tif err != nil {\n\t\t\tif command == \"exit\" {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tif *g_sock == \"unix\" {\n\t\t\t\t_ = os.Remove(addr)\n\t\t\t}\n\t\t\terr = tryStartServer()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Failed to start server: %s\\n\", err)\n\t\t\t}\n\t\t\tclient, err = tryToConnect(*g_sock, addr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Failed to connect to %q: %s\\n\", addr, err)\n\t\t\t}\n\t\t}\n\t\tdefer client.Close()\n\t}\n\n\tswitch command {\n\tcase \"autocomplete\":\n\t\tcmdAutoComplete(client)\n\tcase \"exit\":\n\t\tcmdExit(client)\n\t}\n}\n\nfunc tryStartServer() error {\n\tpath := get_executable_filename()\n\targs := []string{os.Args[0], \"-s\", \"-sock\", *g_sock, \"-addr\", *g_addr}\n\tcwd, _ := os.Getwd()\n\n\tvar err error\n\tstdin, err := os.Open(os.DevNull)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstdout, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstderr, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprocattr := os.ProcAttr{Dir: cwd, Env: os.Environ(), Files: []*os.File{stdin, stdout, stderr}}\n\tp, err := os.StartProcess(path, args, &procattr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn p.Release()\n}\n\nfunc tryToConnect(network, address string) (*rpc.Client, error) {\n\tstart := time.Now()\n\tfor {\n\t\tclient, err := rpc.Dial(network, address)\n\t\tif err != nil && time.Since(start) < time.Second {\n\t\t\tcontinue\n\t\t}\n\t\treturn client, err\n\t}\n}\n\nfunc cmdAutoComplete(c *rpc.Client) {\n\tvar req AutoCompleteRequest\n\treq.Filename, req.Data, req.Cursor = prepareFilenameDataCursor()\n\treq.Context = gbimporter.PackContext(&build.Default)\n\n\tvar res AutoCompleteReply\n\tvar err error\n\tif c == nil {\n\t\ts := Server{}\n\t\terr = s.AutoComplete(&req, &res)\n\t} else {\n\t\terr = c.Call(\"Server.AutoComplete\", &req, &res)\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt := suggest.Formatters[*g_format]\n\tif fmt == nil {\n\t\tfmt = suggest.NiceFormat\n\t}\n\tfmt(os.Stdout, res.Candidates, res.Len)\n}\n\nfunc cmdExit(c *rpc.Client) {\n\tif c == nil {\n\t\treturn\n\t}\n\tvar req ExitRequest\n\tvar res ExitReply\n\tif err := c.Call(\"Server.Exit\", &req, &res); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc prepareFilenameDataCursor() (string, []byte, int) {\n\tvar file []byte\n\tvar err error\n\n\tif *g_input != \"\" {\n\t\tfile, err = ioutil.ReadFile(*g_input)\n\t} else {\n\t\tfile, err = ioutil.ReadAll(os.Stdin)\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfilename := *g_input\n\toffset := \"\"\n\tswitch flag.NArg() {\n\tcase 2:\n\t\toffset = flag.Arg(1)\n\tcase 3:\n\t\tfilename = flag.Arg(1) \/\/ Override default filename\n\t\toffset = flag.Arg(2)\n\t}\n\n\tif filename != \"\" {\n\t\tfilename, _ = filepath.Abs(filename)\n\t}\n\n\tcursor := -1\n\tif offset != \"\" {\n\t\tif offset[0] == 'c' || offset[0] == 'C' {\n\t\t\tcursor, _ = strconv.Atoi(offset[1:])\n\t\t\tcursor = runeToByteOffset(file, cursor)\n\t\t} else {\n\t\t\tcursor, _ = strconv.Atoi(offset)\n\t\t}\n\t}\n\n\treturn filename, file, cursor\n}\n<commit_msg>gocode: speed up client by disabling GC<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/rpc\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"runtime\/debug\"\n\n\t\"github.com\/mdempsky\/gocode\/gbimporter\"\n\t\"github.com\/mdempsky\/gocode\/suggest\"\n)\n\nfunc doClient() {\n\t\/\/ Client is a short-lived program.\n\t\/\/ Disable GC to make it faster\n\tdebug.SetGCPercent(-1)\n\n\tif *g_debug {\n\t\tstart := time.Now()\n\t\tdefer func() {\n\t\t\telapsed := time.Since(start)\n\t\t\tlog.Printf(\"Elapsed duration: %v\\n\", elapsed)\n\t\t}()\n\t}\n\n\tvar command string\n\tif flag.NArg() > 0 {\n\t\tcommand = flag.Arg(0)\n\t\tswitch command {\n\t\tcase \"autocomplete\", \"exit\":\n\t\t\t\/\/ these are valid commands\n\t\tcase \"close\":\n\t\t\t\/\/ \"close\" is an alias for \"exit\"\n\t\t\tcommand = \"exit\"\n\t\tdefault:\n\t\t\tfmt.Printf(\"gocode: unknown subcommand: %q\\nRun 'gocode -help' for usage.\\n\", command)\n\t\t\tos.Exit(2)\n\t\t}\n\t}\n\n\t\/\/ client\n\tvar client *rpc.Client\n\tif *g_sock != \"none\" {\n\t\taddr := *g_addr\n\t\tif *g_sock == \"unix\" {\n\t\t\taddr = getSocketPath()\n\t\t}\n\n\t\tvar err error\n\t\tclient, err = rpc.Dial(*g_sock, addr)\n\t\tif err != nil {\n\t\t\tif command == \"exit\" {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tif *g_sock == \"unix\" {\n\t\t\t\t_ = os.Remove(addr)\n\t\t\t}\n\t\t\terr = tryStartServer()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Failed to start server: %s\\n\", err)\n\t\t\t}\n\t\t\tclient, err = tryToConnect(*g_sock, addr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Failed to connect to %q: %s\\n\", addr, err)\n\t\t\t}\n\t\t}\n\t\tdefer client.Close()\n\t}\n\n\tswitch command {\n\tcase \"autocomplete\":\n\t\tcmdAutoComplete(client)\n\tcase \"exit\":\n\t\tcmdExit(client)\n\t}\n}\n\nfunc tryStartServer() error {\n\tpath := get_executable_filename()\n\targs := []string{os.Args[0], \"-s\", \"-sock\", *g_sock, \"-addr\", *g_addr}\n\tcwd, _ := os.Getwd()\n\n\tvar err error\n\tstdin, err := os.Open(os.DevNull)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstdout, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstderr, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprocattr := os.ProcAttr{Dir: cwd, Env: os.Environ(), Files: []*os.File{stdin, stdout, stderr}}\n\tp, err := os.StartProcess(path, args, &procattr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn p.Release()\n}\n\nfunc tryToConnect(network, address string) (*rpc.Client, error) {\n\tstart := time.Now()\n\tfor {\n\t\tclient, err := rpc.Dial(network, address)\n\t\tif err != nil && time.Since(start) < time.Second {\n\t\t\tcontinue\n\t\t}\n\t\treturn client, err\n\t}\n}\n\nfunc cmdAutoComplete(c *rpc.Client) {\n\tvar req AutoCompleteRequest\n\treq.Filename, req.Data, req.Cursor = prepareFilenameDataCursor()\n\treq.Context = gbimporter.PackContext(&build.Default)\n\n\tvar res AutoCompleteReply\n\tvar err error\n\tif c == nil {\n\t\ts := Server{}\n\t\terr = s.AutoComplete(&req, &res)\n\t} else {\n\t\terr = c.Call(\"Server.AutoComplete\", &req, &res)\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt := suggest.Formatters[*g_format]\n\tif fmt == nil {\n\t\tfmt = suggest.NiceFormat\n\t}\n\tfmt(os.Stdout, res.Candidates, res.Len)\n}\n\nfunc cmdExit(c *rpc.Client) {\n\tif c == nil {\n\t\treturn\n\t}\n\tvar req ExitRequest\n\tvar res ExitReply\n\tif err := c.Call(\"Server.Exit\", &req, &res); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc prepareFilenameDataCursor() (string, []byte, int) {\n\tvar file []byte\n\tvar err error\n\n\tif *g_input != \"\" {\n\t\tfile, err = ioutil.ReadFile(*g_input)\n\t} else {\n\t\tfile, err = ioutil.ReadAll(os.Stdin)\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfilename := *g_input\n\toffset := \"\"\n\tswitch flag.NArg() {\n\tcase 2:\n\t\toffset = flag.Arg(1)\n\tcase 3:\n\t\tfilename = flag.Arg(1) \/\/ Override default filename\n\t\toffset = flag.Arg(2)\n\t}\n\n\tif filename != \"\" {\n\t\tfilename, _ = filepath.Abs(filename)\n\t}\n\n\tcursor := -1\n\tif offset != \"\" {\n\t\tif offset[0] == 'c' || offset[0] == 'C' {\n\t\t\tcursor, _ = strconv.Atoi(offset[1:])\n\t\t\tcursor = runeToByteOffset(file, cursor)\n\t\t} else {\n\t\t\tcursor, _ = strconv.Atoi(offset)\n\t\t}\n\t}\n\n\treturn filename, file, cursor\n}\n<|endoftext|>"}
{"text":"<commit_before>package atlas \/\/ import \"github.com\/keltia\/ripe-atlas\"\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/keltia\/proxy\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ NewClient is the first function to call.\n\/\/ Yes, it does take multiple config\n\/\/ and the last one wins.\nfunc NewClient(cfgs ...Config) (*Client, error) {\n\tc := &Client{}\n\tfor _, cfg := range cfgs {\n\t\tc.config = cfg\n\t}\n\n\t\/\/ This holds the global options\n\tc.opts = make(map[string]string)\n\n\t\/\/ If no log output is specified, use the default one\n\tif c.config.Log == nil {\n\t\tc.log = log.New(os.Stderr, \"\", log.LstdFlags|log.LUTC)\n\t} else {\n\t\tc.log = c.config.Log\n\t}\n\n\t\/\/ Set log levels\n\tif c.config.Verbose == true {\n\t\tc.level = 1\n\t}\n\n\tif c.config.Level > 2 {\n\t\tc.level = 2\n\t}\n\n\t\/\/ Ensure this is not empty\n\tif c.config.endpoint == \"\" {\n\t\tc.config.endpoint = apiEndpoint\n\t}\n\tc.verbose(\"c.config=%#v\", c.config)\n\n\t\/\/ Create and save the http.Client\n\treturn c.addHTTPClient()\n}\n\n\/\/ HasAPIKey returns whether an API key is stored\nfunc (c *Client) HasAPIKey() (string, bool) {\n\tif c.config.APIKey == \"\" {\n\t\treturn \"\", false\n\t}\n\treturn c.config.APIKey, true\n}\n\n\/\/ call is s shortcut\nfunc (c *Client) call(req *http.Request) (*http.Response, error) {\n\tc.verbose(\"Full URL:\\n%v\", req.URL)\n\n\tmyurl, _ := url.Parse(apiEndpoint)\n\treq.Header.Set(\"Host\", myurl.Host)\n\treq.Header.Set(\"User-Agent\", fmt.Sprintf(\"ripe-atlas\/%s\", ourVersion))\n\n\treturn c.client.Do(req)\n}\n\nfunc (c *Client) addHTTPClient() (*Client, error) {\n\t_, transport := proxy.SetupTransport(apiEndpoint)\n\tif transport == nil {\n\t\treturn c, errors.New(\"addhttpclient\")\n\t}\n\tc.client = &http.Client{Transport: transport, Timeout: 20 * time.Second}\n\treturn c, nil\n}\n\n\/\/ SetOption sets a global option\nfunc (c *Client) SetOption(name, value string) *Client {\n\tif value != \"\" {\n\t\tc.opts[name] = value\n\t}\n\treturn c\n}\n\n\/\/ GetVersion returns the API wrapper version\nfunc GetVersion() string {\n\treturn ourVersion\n}\n<commit_msg>Pass NewClient3() and NewClient4().<commit_after>package atlas \/\/ import \"github.com\/keltia\/ripe-atlas\"\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/keltia\/proxy\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ NewClient is the first function to call.\n\/\/ Yes, it does take multiple config\n\/\/ and the last one wins.\nfunc NewClient(cfgs ...Config) (*Client, error) {\n\tc := &Client{}\n\tfor _, cfg := range cfgs {\n\t\tc.config = cfg\n\t}\n\n\t\/\/ This holds the global options\n\tc.opts = make(map[string]string)\n\n\t\/\/ If no log output is specified, use the default one\n\tif c.config.Log == nil {\n\t\tc.log = log.New(os.Stderr, \"\", log.LstdFlags|log.LUTC)\n\t} else {\n\t\tc.log = c.config.Log\n\t}\n\n\t\/\/ Set log levels\n\tif c.config.Verbose == true {\n\t\tc.level = 1\n\t}\n\n\tif c.config.Level != 0 {\n\t\tc.level = c.config.Level\n\t}\n\n\t\/\/ Final check\n\tif c.config.Level > 2 {\n\t\tc.level = 2\n\t}\n\n\t\/\/ Ensure this is not empty\n\tif c.config.endpoint == \"\" {\n\t\tc.config.endpoint = apiEndpoint\n\t}\n\tc.verbose(\"c.config=%#v\", c.config)\n\n\t\/\/ Create and save the http.Client\n\treturn c.addHTTPClient()\n}\n\n\/\/ HasAPIKey returns whether an API key is stored\nfunc (c *Client) HasAPIKey() (string, bool) {\n\tif c.config.APIKey == \"\" {\n\t\treturn \"\", false\n\t}\n\treturn c.config.APIKey, true\n}\n\n\/\/ call is s shortcut\nfunc (c *Client) call(req *http.Request) (*http.Response, error) {\n\tc.verbose(\"Full URL:\\n%v\", req.URL)\n\n\tmyurl, _ := url.Parse(apiEndpoint)\n\treq.Header.Set(\"Host\", myurl.Host)\n\treq.Header.Set(\"User-Agent\", fmt.Sprintf(\"ripe-atlas\/%s\", ourVersion))\n\n\treturn c.client.Do(req)\n}\n\nfunc (c *Client) addHTTPClient() (*Client, error) {\n\t_, transport := proxy.SetupTransport(apiEndpoint)\n\tif transport == nil {\n\t\treturn c, errors.New(\"addhttpclient\")\n\t}\n\tc.client = &http.Client{Transport: transport, Timeout: 20 * time.Second}\n\treturn c, nil\n}\n\n\/\/ SetOption sets a global option\nfunc (c *Client) SetOption(name, value string) *Client {\n\tif value != \"\" {\n\t\tc.opts[name] = value\n\t}\n\treturn c\n}\n\n\/\/ GetVersion returns the API wrapper version\nfunc GetVersion() string {\n\treturn ourVersion\n}\n<|endoftext|>"}
{"text":"<commit_before>package GoMM\n\nimport (\n\t\"errors\"\n\t\"github.com\/hashicorp\/memberlist\"\n\t\"log\"\n\t\"sort\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype Client struct {\n\tmemberTracker *memberlist.Memberlist \/\/ Underlying tracker to\n\n\tpendingMembersLock sync.Mutex\n\tpendingMembers     map[string]Node \/\/ Members that are online, but not active\n\tActiveMembersLock  sync.Mutex\n\tActiveMembers      map[string]Node \/\/ Members that are online and active, mapped by the memberlist.Node.Name\n\tName               string          \/\/ Unique name of the Client\n\tnode               Node            \/\/ Used for TCP communications\n\n\tmessenger Messenger\n\tlistener  Listener\n\n\tbarrierChannel chan string \/\/ The channel that handles barrier message, will be the name of the node that sent the barrier\n\t\/\/ Channel for recieve broadcast messages\n\tBroadcastChannel chan Message\n}\n\nfunc (c Client) NumMembers() int {\n\treturn c.memberTracker.NumMembers()\n}\n\nfunc (c *Client) NumActiveMembers() int {\n\tc.ActiveMembersLock.Lock()\n\tnum := len(c.ActiveMembers)\n\tc.ActiveMembersLock.Unlock()\n\treturn num\n}\n\n\/\/ Cause a node to join another memberlist group. This function removes this\n\/\/ node from the active list. Further more, this should only be called\n\/\/ when a node is alone in it's undelying memberlist. Therefore, a group\n\/\/ of nodes cannot merge with another group, but the sub group must all join\n\/\/ individually. Should this be blocking until the node is made active?\nfunc (c *Client) Join(address string) {\n\tc.memberTracker.Join([]string{address})\n\tc.updateActiveMemberList([]Node{})\n\treturn\n}\n\nfunc (c *Client) JoinAddr() string {\n\treturn c.node.GetMemberlistStringAddr()\n}\n\nfunc (c Client) HandleMessage(msg Message) {\n\tif msg.Type == activateMsg || msg.Type == broadcastMsg || msg.Type == barrierMsg {\n\t\tc.continueMessageBroadcast(msg) \/\/ continues to broadcast the message\n\t}\n\n\tswitch msg.Type {\n\tcase activateMsg:\n\t\tc.handleActivateMessage(msg)\n\t\tbreak\n\tcase barrierMsg:\n\t\tc.barrierChannel <- msg.StringData[0] \/\/ Pass on the name, will be handled on the calling thread\n\t\tbreak\n\tcase broadcastMsg:\n\t\tc.BroadcastChannel <- msg\n\t\tbreak\n\tdefault:\n\t\tlog.Println(\"[ERROR] Unknown message type\")\n\t}\n}\n\nfunc (c *Client) handleActivateMessage(msg Message) {\n\n\tactiveNodes, err := decodeActivateMsg(msg)\n\tif err != nil {\n\t\tlog.Println(\"[ERROR] Received malformed activate message\")\n\t\treturn\n\t}\n\tc.updateActiveMemberList(activeNodes)\n\tlog.Println(\"[DEBUG]\", c.Name, \"IsActive\", c.IsActive(), \"total active nodes: \"+strconv.Itoa(len(activeNodes)))\n}\n\n\/\/ Handles messages that must be broadcast\nfunc (c *Client) continueMessageBroadcast(msg Message) {\n\t\/\/ Send to children nodes if they exit\n\tid := c.GetId()\n\tc.ActiveMembersLock.Lock()\n\ttotalNodes := len(c.ActiveMembers)\n\tc.ActiveMembersLock.Unlock()\n\tleft, right := c.getChildren(id, totalNodes)\n\n\t\/\/ Send the message to the children nodes if they exist\n\tif left != -1 {\n\t\tc.sendMsg(msg, left)\n\t}\n\n\tif right != -1 {\n\t\tc.sendMsg(msg, right)\n\t}\n\n}\n\n\/\/ Returns the children in a binary tree for the nodes. Returns\n\/\/ -1 for invalid nodes\nfunc (c *Client) getChildren(id, totalNodes int) (int, int) {\n\tif totalNodes == 0 {\n\t\t\/\/ invalid tree\n\t\treturn -1, -1\n\t}\n\n\tleft := 2*id + 1\n\tright := 2 * (id + 1)\n\n\tif left >= totalNodes {\n\t\tleft = -1\n\t}\n\n\tif right >= totalNodes {\n\t\tright = -1\n\t}\n\treturn left, right\n}\n\nfunc (c *Client) Start() error {\n\t\/\/ Start event processing\n\tc.listener = NewListener(c)\n\tgo c.listener.Listen(c.messenger)\n\n\tvar config *memberlist.Config = memberlist.DefaultLocalConfig()\n\tconfig.BindPort = c.node.MemberlistPort\n\tconfig.BindAddr = c.node.Addr.String()\n\tconfig.Name = c.Name\n\tconfig.AdvertisePort = c.node.MemberlistPort\n\tconfig.Events = c\n\n\tlist, err := memberlist.Create(config)\n\tif err != nil {\n\t\tlog.Println(\"[ERROR] Failed to create member list for\", c.Name, \"Error: \", err.Error())\n\t}\n\tlog.Println(\"[DEBUG] Started memberlist for\", c.Name)\n\tc.memberTracker = list\n\n\tlog.Println(\"[DEBUG] Started Client\", c.Name)\n\n\treturn nil\n}\n\nfunc (c *Client) Close() {\n\tc.memberTracker.Leave(time.Millisecond * 1)\n\tlog.Println(\"[DEBUG]\", c.Name, \"left memberTracker\")\n\tc.listener.Stop()\n\t\/\/ Not totally sure how closing channels works TODO\n\tclose(c.barrierChannel)\n\tlog.Println(\"[DEBUG]\", c.Name, \"shut down\")\n}\n\n\/\/ Wait until the Client is active\nfunc (c *Client) WaitActive() {\n\tfor {\n\t\tif c.IsActive() == true {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Millisecond * 10)\n\t}\n}\n\n\/\/ Allows members currently waiting to become active to become active,\n\/\/ this method blocks and requires that all current active members\n\/\/ have also called this method.\nfunc (c *Client) UpdateActiveMembers() int {\n\t\/\/ Need to ensure all active members have decided to do this\n\tc.Barrier()\n\tc.activatePendingMembers()\n\t\/\/ Need to send go ahead message to new members to be made active\n\treturn c.NumActiveMembers()\n}\n\nfunc (c *Client) updateActiveMemberList(members []Node) {\n\n\tc.ActiveMembersLock.Lock()\n\n\t\/\/ Delete everything in the map, can't just make a new one, otherwise\n\t\/\/ the references can be broken across threads\n\tfor k := range c.ActiveMembers {\n\t\tdelete(c.ActiveMembers, k)\n\t}\n\n\tfor i := range members {\n\t\tc.ActiveMembers[members[i].Name] = members[i]\n\t}\n\n\tlog.Println(\"[DEBUG] Updateing active member list with:\", c.ActiveMembers)\n\n\tc.ActiveMembersLock.Unlock()\n\n}\n\n\/\/ Determine if the given Client is in the active pool\nfunc (c *Client) IsActive() bool {\n\tc.ActiveMembersLock.Lock()\n\t_, ok := c.ActiveMembers[c.Name]\n\tc.ActiveMembersLock.Unlock()\n\treturn ok\n}\n\n\/\/ Barrier that blacks for all active nodes\nfunc (c *Client) Barrier() {\n\tif !c.IsActive() {\n\t\tpanic(\"Client is not active!\")\n\t}\n\tif c.NumActiveMembers() == 1 {\n\t\t\/\/ This is the only member so can return instantly\n\t\treturn\n\t}\n\n\t\/\/ Need to broadcast the barrier message\n\tmsg := createBarrierMsg(c.Name)\n\n\tlog.Println(\"[DEBUG] Broadcasting barrier from\", c.Name)\n\tc.broadCastMsg(msg)\n\n\t\/\/ Wait for each node to respond\n\t\/\/Get messages from channel\n\n\tresponded := make(map[string]bool)\nPollingLoop:\n\tfor {\n\t\tselect {\n\t\tcase name := <-c.barrierChannel:\n\t\t\tresponded[name] = true\n\t\t\tlog.Println(\"[DEBUG]\", c.Name, \"Received barrier from\", name, len(responded), \"of\", c.NumActiveMembers()-1)\n\t\tdefault:\n\t\t\tif len(responded) == c.NumActiveMembers()-1 {\n\t\t\t\tlog.Println(\"[DEBUG] Barrier completed by\", c.Name)\n\t\t\t\tbreak PollingLoop \/\/ everyone is at the barrier\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Send message to all nodes\n\/\/ TODO implement a tree rather than naive send to all\nfunc (c *Client) Broadcast(stringData []string, floatData []float64) {\n\tmsg := CreateBroadcastMsg(stringData, floatData)\n\tmsg.Origin = c.GetId()\n\tc.broadCastMsg(msg)\n}\n\n\/\/ Sends a message to a node with the supplied id\nfunc (c *Client) sendMsg(msg Message, targetId int) error {\n\ttarget, err := c.ResolveId(targetId)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmsg.Target = target\n\terr = c.messenger.Send(msg)\n\n\treturn err\n}\n\n\/\/ Resolve the id to a client address. The id is currently based on\n\/\/ the sorted string order of the nodes address.\nfunc (c *Client) ResolveId(id int) (string, error) {\n\t\/\/ Check valid id\n\tif id < 0 || id > len(c.ActiveMembers)-1 {\n\t\treturn \"\", errors.New(\"Id out of bounds\")\n\t}\n\tmemberAddresses := c.getSortedMemberAddresses()\n\n\treturn memberAddresses[id], nil\n}\n\nfunc (c *Client) GetAddrId(addr string) (int, error) {\n\tmemberAddresses := c.getSortedMemberAddresses()\n\n\tfor i := 0; i < len(memberAddresses); i++ {\n\t\tif addr == memberAddresses[i] {\n\t\t\treturn i, nil\n\t\t}\n\t}\n\n\treturn -1, errors.New(\"Address not found\")\n}\n\nfunc (c *Client) GetId() int {\n\tid, _ := c.GetAddrId(c.node.GetStringAddr())\n\treturn id\n}\n\nfunc (c *Client) getSortedMemberAddresses() []string {\n\tc.ActiveMembersLock.Lock()\n\tdefer c.ActiveMembersLock.Unlock()\n\n\t\/\/ Generate a list of addresses\n\tmemberAddresses := make([]string, len(c.ActiveMembers))\n\ti := 0\n\tfor _, v := range c.ActiveMembers {\n\t\tmemberAddresses[i] = v.GetStringAddr()\n\t\ti++\n\t}\n\n\tsort.Strings(memberAddresses)\n\n\treturn memberAddresses\n}\n\nfunc (c *Client) broadCastMsg(msg Message) {\n\t\/\/ Send it to the root node for propogation\n\tc.sendMsg(msg, 0)\n}\n\nfunc (c Client) NotifyJoin(n *memberlist.Node) {\n\tnew_node := Node{\n\t\tName: n.Name,\n\t\tAddr: n.Addr,\n\t\tPort: int(n.Port) + 100, \/\/ Add 100 for the port offset\n\t}\n\n\tif n.Name == c.Name {\n\t\t\/\/ The initial self notification\n\t\tc.ActiveMembersLock.Lock()\n\t\tc.ActiveMembers[c.Name] = new_node\n\t\tc.ActiveMembersLock.Unlock()\n\t\treturn\n\t}\n\n\tc.pendingMembersLock.Lock()\n\tc.pendingMembers[n.Name] = new_node\n\tc.pendingMembersLock.Unlock()\n}\n\nfunc (c Client) NotifyLeave(n *memberlist.Node) {\n\tlog.Println(\"[DEBUG]\", n.Name, \"left\")\n\tc.ActiveMembersLock.Lock()\n\t\/\/ Delete the node from active members\n\tdelete(c.ActiveMembers, n.Name)\n\tc.ActiveMembersLock.Unlock()\n\n\t\/\/ Delete the node from pending members\n\tc.pendingMembersLock.Lock()\n\tdelete(c.pendingMembers, n.Name)\n\tc.pendingMembersLock.Unlock()\n}\n\nfunc (c Client) NotifyUpdate(n *memberlist.Node) {\n\n}\n<commit_msg>Added shutdown call to client close to properly shutdown memberlist. Also removed closing of recv channel so the client can be started again.<commit_after>package GoMM\n\nimport (\n\t\"errors\"\n\t\"github.com\/hashicorp\/memberlist\"\n\t\"log\"\n\t\"sort\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype Client struct {\n\tmemberTracker *memberlist.Memberlist \/\/ Underlying tracker to\n\n\tpendingMembersLock sync.Mutex\n\tpendingMembers     map[string]Node \/\/ Members that are online, but not active\n\tActiveMembersLock  sync.Mutex\n\tActiveMembers      map[string]Node \/\/ Members that are online and active, mapped by the memberlist.Node.Name\n\tName               string          \/\/ Unique name of the Client\n\tnode               Node            \/\/ Used for TCP communications\n\n\tmessenger Messenger\n\tlistener  Listener\n\n\tbarrierChannel chan string \/\/ The channel that handles barrier message, will be the name of the node that sent the barrier\n\t\/\/ Channel for recieve broadcast messages\n\tBroadcastChannel chan Message\n}\n\nfunc (c Client) NumMembers() int {\n\treturn c.memberTracker.NumMembers()\n}\n\nfunc (c *Client) NumActiveMembers() int {\n\tc.ActiveMembersLock.Lock()\n\tnum := len(c.ActiveMembers)\n\tc.ActiveMembersLock.Unlock()\n\treturn num\n}\n\n\/\/ Cause a node to join another memberlist group. This function removes this\n\/\/ node from the active list. Further more, this should only be called\n\/\/ when a node is alone in it's undelying memberlist. Therefore, a group\n\/\/ of nodes cannot merge with another group, but the sub group must all join\n\/\/ individually. Should this be blocking until the node is made active?\nfunc (c *Client) Join(address string) {\n\tc.memberTracker.Join([]string{address})\n\tc.updateActiveMemberList([]Node{})\n\treturn\n}\n\nfunc (c *Client) JoinAddr() string {\n\treturn c.node.GetMemberlistStringAddr()\n}\n\nfunc (c Client) HandleMessage(msg Message) {\n\tif msg.Type == activateMsg || msg.Type == broadcastMsg || msg.Type == barrierMsg {\n\t\tc.continueMessageBroadcast(msg) \/\/ continues to broadcast the message\n\t}\n\n\tswitch msg.Type {\n\tcase activateMsg:\n\t\tc.handleActivateMessage(msg)\n\t\tbreak\n\tcase barrierMsg:\n\t\tc.barrierChannel <- msg.StringData[0] \/\/ Pass on the name, will be handled on the calling thread\n\t\tbreak\n\tcase broadcastMsg:\n\t\tc.BroadcastChannel <- msg\n\t\tbreak\n\tdefault:\n\t\tlog.Println(\"[ERROR] Unknown message type\")\n\t}\n}\n\nfunc (c *Client) handleActivateMessage(msg Message) {\n\n\tactiveNodes, err := decodeActivateMsg(msg)\n\tif err != nil {\n\t\tlog.Println(\"[ERROR] Received malformed activate message\")\n\t\treturn\n\t}\n\tc.updateActiveMemberList(activeNodes)\n\tlog.Println(\"[DEBUG]\", c.Name, \"IsActive\", c.IsActive(), \"total active nodes: \"+strconv.Itoa(len(activeNodes)))\n}\n\n\/\/ Handles messages that must be broadcast\nfunc (c *Client) continueMessageBroadcast(msg Message) {\n\t\/\/ Send to children nodes if they exit\n\tid := c.GetId()\n\tc.ActiveMembersLock.Lock()\n\ttotalNodes := len(c.ActiveMembers)\n\tc.ActiveMembersLock.Unlock()\n\tleft, right := c.getChildren(id, totalNodes)\n\n\t\/\/ Send the message to the children nodes if they exist\n\tif left != -1 {\n\t\tc.sendMsg(msg, left)\n\t}\n\n\tif right != -1 {\n\t\tc.sendMsg(msg, right)\n\t}\n\n}\n\n\/\/ Returns the children in a binary tree for the nodes. Returns\n\/\/ -1 for invalid nodes\nfunc (c *Client) getChildren(id, totalNodes int) (int, int) {\n\tif totalNodes == 0 {\n\t\t\/\/ invalid tree\n\t\treturn -1, -1\n\t}\n\n\tleft := 2*id + 1\n\tright := 2 * (id + 1)\n\n\tif left >= totalNodes {\n\t\tleft = -1\n\t}\n\n\tif right >= totalNodes {\n\t\tright = -1\n\t}\n\treturn left, right\n}\n\nfunc (c *Client) Start() error {\n\t\/\/ Start event processing\n\tc.listener = NewListener(c)\n\tgo c.listener.Listen(c.messenger)\n\n\tvar config *memberlist.Config = memberlist.DefaultLocalConfig()\n\tconfig.BindPort = c.node.MemberlistPort\n\tconfig.BindAddr = c.node.Addr.String()\n\tconfig.Name = c.Name\n\tconfig.AdvertisePort = c.node.MemberlistPort\n\tconfig.Events = c\n\n\tlist, err := memberlist.Create(config)\n\tif err != nil {\n\t\tlog.Println(\"[ERROR] Failed to create member list for\", c.Name, \"Error: \", err.Error())\n\t}\n\tlog.Println(\"[DEBUG] Started memberlist for\", c.Name)\n\tc.memberTracker = list\n\n\tlog.Println(\"[DEBUG] Started Client\", c.Name)\n\n\treturn nil\n}\n\nfunc (c *Client) Close() {\n\tc.memberTracker.Leave(time.Millisecond * 500)\n\tc.memberTracker.Shutdown()\n\tlog.Println(\"[DEBUG]\", c.Name, \"left memberTracker\")\n\tc.listener.Stop()\n\t\/\/ Not totally sure how closing channels works TODO\n\t\/\/ close(c.barrierChannel)\n\tlog.Println(\"[DEBUG]\", c.Name, \"shut down\")\n}\n\n\/\/ Wait until the Client is active\nfunc (c *Client) WaitActive() {\n\tfor {\n\t\tif c.IsActive() == true {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Millisecond * 10)\n\t}\n}\n\n\/\/ Allows members currently waiting to become active to become active,\n\/\/ this method blocks and requires that all current active members\n\/\/ have also called this method.\nfunc (c *Client) UpdateActiveMembers() int {\n\t\/\/ Need to ensure all active members have decided to do this\n\tc.Barrier()\n\tc.activatePendingMembers()\n\t\/\/ Need to send go ahead message to new members to be made active\n\treturn c.NumActiveMembers()\n}\n\nfunc (c *Client) updateActiveMemberList(members []Node) {\n\n\tc.ActiveMembersLock.Lock()\n\n\t\/\/ Delete everything in the map, can't just make a new one, otherwise\n\t\/\/ the references can be broken across threads\n\tfor k := range c.ActiveMembers {\n\t\tdelete(c.ActiveMembers, k)\n\t}\n\n\tfor i := range members {\n\t\tc.ActiveMembers[members[i].Name] = members[i]\n\t}\n\n\tlog.Println(\"[DEBUG] Updateing active member list with:\", c.ActiveMembers)\n\n\tc.ActiveMembersLock.Unlock()\n\n}\n\n\/\/ Determine if the given Client is in the active pool\nfunc (c *Client) IsActive() bool {\n\tc.ActiveMembersLock.Lock()\n\t_, ok := c.ActiveMembers[c.Name]\n\tc.ActiveMembersLock.Unlock()\n\treturn ok\n}\n\n\/\/ Barrier that blacks for all active nodes\nfunc (c *Client) Barrier() {\n\tif !c.IsActive() {\n\t\tpanic(\"Client is not active!\")\n\t}\n\tif c.NumActiveMembers() == 1 {\n\t\t\/\/ This is the only member so can return instantly\n\t\treturn\n\t}\n\n\t\/\/ Need to broadcast the barrier message\n\tmsg := createBarrierMsg(c.Name)\n\n\tlog.Println(\"[DEBUG] Broadcasting barrier from\", c.Name)\n\tc.broadCastMsg(msg)\n\n\t\/\/ Wait for each node to respond\n\t\/\/Get messages from channel\n\n\tresponded := make(map[string]bool)\nPollingLoop:\n\tfor {\n\t\tselect {\n\t\tcase name := <-c.barrierChannel:\n\t\t\tresponded[name] = true\n\t\t\tlog.Println(\"[DEBUG]\", c.Name, \"Received barrier from\", name, len(responded), \"of\", c.NumActiveMembers()-1)\n\t\tdefault:\n\t\t\tif len(responded) == c.NumActiveMembers()-1 {\n\t\t\t\tlog.Println(\"[DEBUG] Barrier completed by\", c.Name)\n\t\t\t\tbreak PollingLoop \/\/ everyone is at the barrier\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Send message to all nodes\n\/\/ TODO implement a tree rather than naive send to all\nfunc (c *Client) Broadcast(stringData []string, floatData []float64) {\n\tmsg := CreateBroadcastMsg(stringData, floatData)\n\tmsg.Origin = c.GetId()\n\tc.broadCastMsg(msg)\n}\n\n\/\/ Sends a message to a node with the supplied id\nfunc (c *Client) sendMsg(msg Message, targetId int) error {\n\ttarget, err := c.ResolveId(targetId)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmsg.Target = target\n\terr = c.messenger.Send(msg)\n\n\treturn err\n}\n\n\/\/ Resolve the id to a client address. The id is currently based on\n\/\/ the sorted string order of the nodes address.\nfunc (c *Client) ResolveId(id int) (string, error) {\n\t\/\/ Check valid id\n\tif id < 0 || id > len(c.ActiveMembers)-1 {\n\t\treturn \"\", errors.New(\"Id out of bounds\")\n\t}\n\tmemberAddresses := c.getSortedMemberAddresses()\n\n\treturn memberAddresses[id], nil\n}\n\nfunc (c *Client) GetAddrId(addr string) (int, error) {\n\tmemberAddresses := c.getSortedMemberAddresses()\n\n\tfor i := 0; i < len(memberAddresses); i++ {\n\t\tif addr == memberAddresses[i] {\n\t\t\treturn i, nil\n\t\t}\n\t}\n\n\treturn -1, errors.New(\"Address not found\")\n}\n\nfunc (c *Client) GetId() int {\n\tid, _ := c.GetAddrId(c.node.GetStringAddr())\n\treturn id\n}\n\nfunc (c *Client) getSortedMemberAddresses() []string {\n\tc.ActiveMembersLock.Lock()\n\tdefer c.ActiveMembersLock.Unlock()\n\n\t\/\/ Generate a list of addresses\n\tmemberAddresses := make([]string, len(c.ActiveMembers))\n\ti := 0\n\tfor _, v := range c.ActiveMembers {\n\t\tmemberAddresses[i] = v.GetStringAddr()\n\t\ti++\n\t}\n\n\tsort.Strings(memberAddresses)\n\n\treturn memberAddresses\n}\n\nfunc (c *Client) broadCastMsg(msg Message) {\n\t\/\/ Send it to the root node for propogation\n\tc.sendMsg(msg, 0)\n}\n\nfunc (c Client) NotifyJoin(n *memberlist.Node) {\n\tnew_node := Node{\n\t\tName: n.Name,\n\t\tAddr: n.Addr,\n\t\tPort: int(n.Port) + 100, \/\/ Add 100 for the port offset\n\t}\n\n\tif n.Name == c.Name {\n\t\t\/\/ The initial self notification\n\t\tc.ActiveMembersLock.Lock()\n\t\tc.ActiveMembers[c.Name] = new_node\n\t\tc.ActiveMembersLock.Unlock()\n\t\treturn\n\t}\n\n\tc.pendingMembersLock.Lock()\n\tc.pendingMembers[n.Name] = new_node\n\tc.pendingMembersLock.Unlock()\n}\n\nfunc (c Client) NotifyLeave(n *memberlist.Node) {\n\tlog.Println(\"[DEBUG]\", c.Name, \"sees\", n.Name, \"left\")\n\tc.ActiveMembersLock.Lock()\n\t\/\/ Delete the node from active members\n\tdelete(c.ActiveMembers, n.Name)\n\tc.ActiveMembersLock.Unlock()\n\n\t\/\/ Delete the node from pending members\n\tc.pendingMembersLock.Lock()\n\tdelete(c.pendingMembers, n.Name)\n\tc.pendingMembersLock.Unlock()\n}\n\nfunc (c Client) NotifyUpdate(n *memberlist.Node) {\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package soap\n\nimport (\n\t\"encoding\/xml\"\n\t\"net\/http\"\n\t\"time\"\n\n\tsoap_http \"github.com\/Bridgevine\/soap\/http\"\n)\n\n\/\/ Request represents a SOAP request.\ntype Request struct {\n\tEnv         Envelope\n\tHTTPHeaders http.Header\n\tCreatedAt   time.Time\n\tSentAt      time.Time\n}\n\n\/\/ NewRequest TODO.\nfunc NewRequest(action string, env Envelope) *Request {\n\treturn &Request{\n\t\tEnv:         env,\n\t\tHTTPHeaders: getHTTPHeaders(env.version(), action),\n\t\tCreatedAt:   time.Now(),\n\t}\n}\n\n\/\/ Response represents a SOAP response.\ntype Response struct {\n\tEnv        Envelope\n\tRequest    *Request\n\tReceivedAt time.Time\n\tURL        string \/\/ URL that sent the response.\n\tEndpoint   string \/\/ An endpoint called by request.\n\tMethod     string \/\/ A HTTP method used to contact the endpoint.\n\tStatusCode int    \/\/ HTTP status code received\n}\n\n\/\/ Client represents a SOAP client that will be used\n\/\/ to send requests and process responses.\ntype Client struct {\n\t\/\/ The URL of the endpoint to which the requests will be sent.\n\turl string\n\n\t\/\/ If different than nil, the HTTP Client adapter that\n\t\/\/ will be used to send the request.\n\thttpClient soap_http.ClientAdapter\n}\n\n\/\/ Do sends a SOAP request.\nfunc (c *Client) Do(req *Request) (*Response, error) {\n\tpayload, err := xml.Marshal(req.Env)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thttpReq := soap_http.NewRequest(\"POST\", c.url, payload)\n\thttpReq.Header = req.HTTPHeaders\n\thttpClient := c.httpClient\n\tif httpClient == nil {\n\t\thttpClient = soap_http.NewClientAdapter()\n\t}\n\n\treq.SentAt = time.Now()\n\n\thttpRes, err := httpClient.Do(httpReq)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenv, err := decodeEnvelope(req.Env.version(), httpRes.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := Response{\n\t\tEnv:        env,\n\t\tRequest:    req,\n\t\tReceivedAt: time.Now(),\n\t\tURL:        c.url,\n\t\tMethod:     httpReq.Method,\n\t\tStatusCode: httpRes.StatusCode,\n\t}\n\n\treturn &resp, nil\n}\n\n\/\/ Option represents a configuration function for a SOAP client.\n\/\/ An option will configure or set up internal details of a SOAP client.\ntype Option func(*Client)\n\n\/\/ SetHTTPClient returns a configuration function to configure\n\/\/ the HTTP Client that will be used to send the requests.\nfunc SetHTTPClient(httpClient soap_http.ClientAdapter) Option {\n\treturn func(c *Client) {\n\t\tc.httpClient = httpClient\n\t}\n}\n\n\/\/ NewClient creates a new SOAP client and set its initial state.\n\/\/ The url parameter represents the SOAP Service URL.\nfunc NewClient(url string, opts ...Option) (*Client, error) {\n\tc := &Client{\n\t\turl: url,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(c)\n\t}\n\n\treturn c, nil\n}\n<commit_msg>expaned response to included payload, when an error happens the response body can be placed into payload for logging<commit_after>package soap\n\nimport (\n\t\"encoding\/xml\"\n\t\"net\/http\"\n\t\"time\"\n\n\tsoap_http \"github.com\/Bridgevine\/soap\/http\"\n)\n\n\/\/ Request represents a SOAP request.\ntype Request struct {\n\tEnv         Envelope\n\tHTTPHeaders http.Header\n\tCreatedAt   time.Time\n\tSentAt      time.Time\n}\n\n\/\/ NewRequest TODO.\nfunc NewRequest(action string, env Envelope) *Request {\n\treturn &Request{\n\t\tEnv:         env,\n\t\tHTTPHeaders: getHTTPHeaders(env.version(), action),\n\t\tCreatedAt:   time.Now(),\n\t}\n}\n\n\/\/ Response represents a SOAP response.\ntype Response struct {\n\tEnv        Envelope\n\tRequest    *Request\n\tReceivedAt time.Time\n\tURL        string \/\/ URL that sent the response.\n\tEndpoint   string \/\/ An endpoint called by request.\n\tMethod     string \/\/ A HTTP method used to contact the endpoint.\n\tStatusCode int    \/\/ HTTP status code received\n\tPayload    string \/\/ used when there is an error to strinify the body response\n}\n\n\/\/ Client represents a SOAP client that will be used\n\/\/ to send requests and process responses.\ntype Client struct {\n\t\/\/ The URL of the endpoint to which the requests will be sent.\n\turl string\n\n\t\/\/ If different than nil, the HTTP Client adapter that\n\t\/\/ will be used to send the request.\n\thttpClient soap_http.ClientAdapter\n}\n\n\/\/ Do sends a SOAP request.\nfunc (c *Client) Do(req *Request) (*Response, error) {\n\tpayload, err := xml.Marshal(req.Env)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thttpReq := soap_http.NewRequest(\"POST\", c.url, payload)\n\thttpReq.Header = req.HTTPHeaders\n\thttpClient := c.httpClient\n\tif httpClient == nil {\n\t\thttpClient = soap_http.NewClientAdapter()\n\t}\n\n\treq.SentAt = time.Now()\n\n\thttpRes, err := httpClient.Do(httpReq)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenv, err := decodeEnvelope(req.Env.version(), httpRes.Body)\n\tif err != nil {\n\t\treturn &Response{\n\t\t\tRequest:    req,\n\t\t\tReceivedAt: time.Now(),\n\t\t\tURL:        c.url,\n\t\t\tMethod:     httpReq.Method,\n\t\t\tStatusCode: httpRes.StatusCode,\n\t\t\tPayload:    string(httpRes.Body),\n\t\t}, err\n\t}\n\n\tresp := Response{\n\t\tEnv:        env,\n\t\tRequest:    req,\n\t\tReceivedAt: time.Now(),\n\t\tURL:        c.url,\n\t\tMethod:     httpReq.Method,\n\t\tStatusCode: httpRes.StatusCode,\n\t}\n\n\treturn &resp, nil\n}\n\n\/\/ Option represents a configuration function for a SOAP client.\n\/\/ An option will configure or set up internal details of a SOAP client.\ntype Option func(*Client)\n\n\/\/ SetHTTPClient returns a configuration function to configure\n\/\/ the HTTP Client that will be used to send the requests.\nfunc SetHTTPClient(httpClient soap_http.ClientAdapter) Option {\n\treturn func(c *Client) {\n\t\tc.httpClient = httpClient\n\t}\n}\n\n\/\/ NewClient creates a new SOAP client and set its initial state.\n\/\/ The url parameter represents the SOAP Service URL.\nfunc NewClient(url string, opts ...Option) (*Client, error) {\n\tc := &Client{\n\t\turl: url,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(c)\n\t}\n\n\treturn c, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package grestclient\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\trt \"reflect\"\n)\n\ntype Client interface {\n\n\t\/\/Headers returns the default headers that will\n\t\/\/be set with every request made with the client.\n\tHeaders() http.Header\n\n\t\/\/SetHeaders sets the default headers that will be sent with\n\t\/\/every request made with this client.\n\tSetHeaders(http.Header)\n\n\t\/\/Query returns the default query to use for all requests\n\tQuery() url.Values\n\n\t\/\/SetQuery sets the default query to use for all requests\n\tSetQuery(url.Values)\n\n\t\/\/SetBaseUrl sets the base url to use for all requests\n\t\/\/If you want to use a different base url then you must\n\t\/\/create a new client with the new base url. Call\n\t\/\/CloneWithNewBaseUrl( url ) to get a clone of this\n\t\/\/client's settings but with a new base url.\n\t\/\/An error should be returned if the url is \"unsupported\",\n\t\/\/whatever that may mean.\n\t\/\/If you wish to use a username\/password combination, set\n\t\/\/the userinfo on the url. It will be used during requests.\n\t\/\/To use one client with credentials and another without,\n\t\/\/use CloneWithNewBaseUrl  and then change the base url.\n\t\/\/Any query parameters added here should be ignored.\n\t\/\/Clients should use the SetQuery method to set default\n\t\/\/query parameters\n\tSetBaseUrl(*url.URL) error\n\n\t\/\/BaseUrl returns the base url being used\n\tBaseUrl() *url.URL\n\n\t\/\/Clones the client with everything the old client had\n\t\/\/Ideally, clones should be independent of the original and can be changed\n\t\/\/without affecting the original and vice versa.\n\t\/\/This implementation, however, shared the http.Client among clones.\n\t\/\/All other 'things' like headers, base url, query, marshalers are separate and\n\t\/\/can be adjusted without affecting the original\/clones.\n\tClone() Client\n\n\t\/\/GetHttpClient returns the current http.Client being used\n\t\/\/If none has been set, this should return http.DefaultClient\n\tGetHttpClient() *http.Client\n\n\t\/\/SetHttpClient sets the http.Client to use during requests\n\t\/\/Use this to customize your http.Client as you wish. If you\n\t\/\/don't set one, the default http.Client will be used.\n\tSetHttpClient(*http.Client)\n\n\t\/\/SetMarshaler sets the marshal function to be used\n\t\/\/to marshal the request bodies for requests\n\t\/\/Doesn't have to mirror the Unmarshaler. Send plain text, get back json\n\t\/\/Default is a json marshaler\n\tSetMarshaler(MarshalerFunc)\n\t\/\/SetUnmarshaler sets the unmarshal function to be used\n\t\/\/to unmarshal the response body for responses\n\t\/\/Doesn't have to mirror the Marshaler. Send XML, get back json\n\t\/\/Default is a json unmarshaler\n\tSetUnmarshaler(UnmarshalerFunc)\n\n\t\/\/AddRequestMutator adds a mutator that the request will be\n\t\/\/passed through before executing the request. All RequestMutators\n\t\/\/are called AFTER the Marshaler is used.\n\t\/\/RequestMutators should be called in the order they were added\n\tAddRequestMutators(...RequestMutator) Client\n\n\t\/\/AddResponseMutator adds a mutator that the response will be\n\t\/\/passed through after the server responds. All ResponseMutators\n\t\/\/are called BEFORE the Unmarshaler is used.\n\t\/\/ResponseMutators should be called in the order they were added\n\tAddResponseMutators(...ResponseMutator) Client\n\n\t\/\/RemoveRequestMutator removes a request mutator\n\tSetRequestMutators(...RequestMutator) Client\n\t\/\/RemoveResponseMutator removes a response mutator\n\tSetResponseMutators(...ResponseMutator) Client\n\n\t\/\/Returns the RequestMutators\n\tRequestMutators() []RequestMutator\n\t\/\/Returns the ResponseMutators\n\tResponseMutators() []ResponseMutator\n\n\t\/\/Get performs a get request with the base url plus the path appended to it. You can send query values and\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tGet(path string, query url.Values, successResult interface{}, errorResult interface{}) (*http.Response, error)\n\n\t\/\/Post performs a post request with the base url plus the path appended to it. You can send query values and\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/With post you can also provide a post body.\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tPost(path string, query url.Values, postBody interface{}, successResult interface{}, errorResult interface{}) (*http.Response, error)\n\n\t\/\/Put performs a put request with the base url plus the path appended to it. You can send query values and\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/With put you can also provide a put body.\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tPut(path string, query url.Values, putBody interface{}, successResult interface{}, errorResult interface{}) (*http.Response, error)\n\n\t\/\/Patch performs a patch request with the base url plus the path appended to it. You can send query values and\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/With patch you can also provide a patch body.\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tPatch(path string, query url.Values, patchBody interface{}, successResult interface{}, errorResult interface{}) (*http.Response, error)\n\n\t\/\/Head performs a head request with the base url plus the path appended to it.\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tHead(path string, successResult interface{}, errorResultg interface{}) (*http.Response, error)\n\n\t\/\/Option performs an option request with the base url plus the path appended to it.\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tOptions(path string, successResult interface{}, errorResult interface{}) (*http.Response, error)\n\n\t\/\/Delete performs an delete request with the base url plus the path appended to it.\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tDelete(path string, query url.Values, successResult interface{}, errorResult interface{}) (*http.Response, error)\n}\n\n\/\/MarshalerFunc takes something and converts it into a\n\/\/io.ReadCloser that can be used for the request body\ntype MarshalerFunc func(v interface{}) (io.ReadCloser, error)\n\n\/\/UnmarshalerFunc takes the response body and converts it into\n\/\/something you can use.\ntype UnmarshalerFunc func(body io.ReadCloser, v interface{}) error\n\n\/\/ByteSliceToReadCloser takes a byte slice and converts it to an\n\/\/io.ReadCloser that can be used as a request\/resonse body\nfunc ByteSliceToReadCloser(b []byte) (io.ReadCloser, error) {\n\tif b == nil {\n\t\treturn nil, errors.New(\"ReadCloserFromByteSlice received a nil byte slice.\")\n\t}\n\n\tbuf := bytes.NewBuffer(b)\n\treturn ioutil.NopCloser(buf), nil\n}\n\n\/\/StringToReadCloser takes a string and converts it to an\n\/\/io.ReadCloser that can be used as a request\/resonse body\nfunc StringToReadCloser(s string) (io.ReadCloser, error) {\n\tbuf := bytes.NewBufferString(s)\n\treturn ioutil.NopCloser(buf), nil\n}\n\n\/\/JsonMarshalerFunc can be used to marshal request bodies\n\/\/into json\nfunc JsonMarshalerFunc(v interface{}) (io.ReadCloser, error) {\n\tb, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbody, err := ByteSliceToReadCloser(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn body, nil\n}\n\n\/\/JsonUnmarshalerFunc can be used to unmarshal response bodies\n\/\/from json\nfunc JsonUnmarshalerFunc(body io.ReadCloser, v interface{}) error {\n\tdefer body.Close()\n\tb, err := ioutil.ReadAll(body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(b, v)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/StringMarshalerFunc can be used to marshal strings into a request.\nfunc StringMarshalerFunc(v interface{}) (io.ReadCloser, error) {\n\tswitch t := v.(type) {\n\tcase fmt.Stringer:\n\t\treturn StringToReadCloser(t.String())\n\tcase string:\n\t\treturn StringToReadCloser(t)\n\t}\n\n\treturn nil, errors.New(\"Did not know how to use the body as text.\")\n}\n\n\/\/StringUnmarshalerFunc can be used to unmarshal strings from a response.\nfunc StringUnmarshalerFunc(body io.ReadCloser, v interface{}) error {\n\tdefer body.Close()\n\n\tif v == nil {\n\t\treturn nil\n\t}\n\n\tb, err := ioutil.ReadAll(body)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch v.(type) {\n\tcase *string:\n\t\telem := rt.ValueOf(v).Elem()\n\n\t\tif elem.CanSet() {\n\t\t\telem.SetString(string(b))\n\t\t\treturn nil\n\t\t}\n\tcase string:\n\t\treturn errors.New(\"You must pass the string by reference: \")\n\t}\n\n\treturn errors.New(\"Did not know how to unmarshal the text coming back.\")\n}\n\n\/\/JsonContentTypeMutator sets the Content-Type of the request to be\n\/\/application\/json\nfunc JsonContentTypeMutator(r *http.Request) error {\n\tr.Header.Add(\"Content-Type\", \"application\/json\")\n\treturn nil\n}\n\n\/\/RequestMutators are called before the request is made but after the marshaler function has been\n\/\/called.\ntype RequestMutator func(*http.Request) error\ntype ResponseMutator func(*http.Response) error\n\n\/\/SetupClientForJson is a convenience method that sets the\n\/\/marshaler and unmarshaler funcs on the client to be the\n\/\/Json funcs in this package. It also sets a request mutator\n\/\/to set the Content-Type to json.\nfunc SetupForJson(c Client) {\n\tc.SetMarshaler(JsonMarshalerFunc)\n\tc.SetUnmarshaler(JsonUnmarshalerFunc)\n\tc.AddRequestMutators(JsonContentTypeMutator)\n}\n<commit_msg>Added documentation<commit_after>package grestclient\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\trt \"reflect\"\n)\n\ntype Client interface {\n\n\t\/\/Headers returns the default headers that will\n\t\/\/be set with every request made with the client.\n\tHeaders() http.Header\n\n\t\/\/SetHeaders sets the default headers that will be sent with\n\t\/\/every request made with this client.\n\tSetHeaders(http.Header)\n\n\t\/\/Query returns the default query to use for all requests\n\tQuery() url.Values\n\n\t\/\/SetQuery sets the default query to use for all requests\n\tSetQuery(url.Values)\n\n\t\/\/SetBaseUrl sets the base url to use for all requests\n\t\/\/If you want to use a different base url then you must\n\t\/\/create a new client with the new base url. Call\n\t\/\/CloneWithNewBaseUrl( url ) to get a clone of this\n\t\/\/client's settings but with a new base url.\n\t\/\/An error should be returned if the url is \"unsupported\",\n\t\/\/whatever that may mean.\n\t\/\/If you wish to use a username\/password combination, set\n\t\/\/the userinfo on the url. It will be used during requests.\n\t\/\/To use one client with credentials and another without,\n\t\/\/use CloneWithNewBaseUrl  and then change the base url.\n\t\/\/Any query parameters added here should be ignored.\n\t\/\/Clients should use the SetQuery method to set default\n\t\/\/query parameters\n\tSetBaseUrl(*url.URL) error\n\n\t\/\/BaseUrl returns the base url being used. This implementation\n\t\/\/allows you to change the base url here directly but other\n\t\/\/implementations might give you a clone so changing it won't affect\n\t\/\/the client. In those cases, use SetBaseUrl to change the url.\n\tBaseUrl() *url.URL\n\n\t\/\/Clones the client with everything the old client had\n\t\/\/Ideally, clones should be independent of the original and can be changed\n\t\/\/without affecting the original and vice versa.\n\t\/\/This implementation, however, shared the http.Client among clones.\n\t\/\/All other 'things' like headers, base url, query, marshalers are separate and\n\t\/\/can be adjusted without affecting the original\/clones.\n\tClone() Client\n\n\t\/\/GetHttpClient returns the current http.Client being used\n\t\/\/If none has been set, this should return http.DefaultClient\n\tGetHttpClient() *http.Client\n\n\t\/\/SetHttpClient sets the http.Client to use during requests\n\t\/\/Use this to customize your http.Client as you wish. If you\n\t\/\/don't set one, the default http.Client will be used.\n\tSetHttpClient(*http.Client)\n\n\t\/\/SetMarshaler sets the marshal function to be used\n\t\/\/to marshal the request bodies for requests\n\t\/\/Doesn't have to mirror the Unmarshaler. Send plain text, get back json\n\t\/\/Default is a json marshaler\n\tSetMarshaler(MarshalerFunc)\n\t\/\/SetUnmarshaler sets the unmarshal function to be used\n\t\/\/to unmarshal the response body for responses\n\t\/\/Doesn't have to mirror the Marshaler. Send XML, get back json\n\t\/\/Default is a json unmarshaler\n\tSetUnmarshaler(UnmarshalerFunc)\n\n\t\/\/AddRequestMutator adds a mutator that the request will be\n\t\/\/passed through before executing the request. All RequestMutators\n\t\/\/are called AFTER the Marshaler is used.\n\t\/\/RequestMutators should be called in the order they were added\n\tAddRequestMutators(...RequestMutator) Client\n\n\t\/\/AddResponseMutator adds a mutator that the response will be\n\t\/\/passed through after the server responds. All ResponseMutators\n\t\/\/are called BEFORE the Unmarshaler is used.\n\t\/\/ResponseMutators should be called in the order they were added\n\tAddResponseMutators(...ResponseMutator) Client\n\n\t\/\/RemoveRequestMutator removes a request mutator\n\tSetRequestMutators(...RequestMutator) Client\n\t\/\/RemoveResponseMutator removes a response mutator\n\tSetResponseMutators(...ResponseMutator) Client\n\n\t\/\/Returns the RequestMutators\n\tRequestMutators() []RequestMutator\n\t\/\/Returns the ResponseMutators\n\tResponseMutators() []ResponseMutator\n\n\t\/\/Get performs a get request with the base url plus the path appended to it. You can send query values and\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tGet(path string, query url.Values, successResult interface{}, errorResult interface{}) (*http.Response, error)\n\n\t\/\/Post performs a post request with the base url plus the path appended to it. You can send query values and\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/With post you can also provide a post body.\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tPost(path string, query url.Values, postBody interface{}, successResult interface{}, errorResult interface{}) (*http.Response, error)\n\n\t\/\/Put performs a put request with the base url plus the path appended to it. You can send query values and\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/With put you can also provide a put body.\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tPut(path string, query url.Values, putBody interface{}, successResult interface{}, errorResult interface{}) (*http.Response, error)\n\n\t\/\/Patch performs a patch request with the base url plus the path appended to it. You can send query values and\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/With patch you can also provide a patch body.\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tPatch(path string, query url.Values, patchBody interface{}, successResult interface{}, errorResult interface{}) (*http.Response, error)\n\n\t\/\/Head performs a head request with the base url plus the path appended to it.\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tHead(path string, successResult interface{}, errorResultg interface{}) (*http.Response, error)\n\n\t\/\/Option performs an option request with the base url plus the path appended to it.\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tOptions(path string, successResult interface{}, errorResult interface{}) (*http.Response, error)\n\n\t\/\/Delete performs an delete request with the base url plus the path appended to it.\n\t\/\/supply a successResult that will be populated if the http response has a return code of 300.\n\t\/\/errorResult is populated if the error code is 400 or more\n\t\/\/Returns the raw http.Response and error similar to Do method of http.Client\n\t\/\/The returned http.Response might be non-nil even though an error was also returned\n\t\/\/depending on where the operation failed.\n\tDelete(path string, query url.Values, successResult interface{}, errorResult interface{}) (*http.Response, error)\n}\n\n\/\/MarshalerFunc takes something and converts it into a\n\/\/io.ReadCloser that can be used for the request body\ntype MarshalerFunc func(v interface{}) (io.ReadCloser, error)\n\n\/\/UnmarshalerFunc takes the response body and converts it into\n\/\/something you can use.\ntype UnmarshalerFunc func(body io.ReadCloser, v interface{}) error\n\n\/\/ByteSliceToReadCloser takes a byte slice and converts it to an\n\/\/io.ReadCloser that can be used as a request\/resonse body\nfunc ByteSliceToReadCloser(b []byte) (io.ReadCloser, error) {\n\tif b == nil {\n\t\treturn nil, errors.New(\"ReadCloserFromByteSlice received a nil byte slice.\")\n\t}\n\n\tbuf := bytes.NewBuffer(b)\n\treturn ioutil.NopCloser(buf), nil\n}\n\n\/\/StringToReadCloser takes a string and converts it to an\n\/\/io.ReadCloser that can be used as a request\/resonse body\nfunc StringToReadCloser(s string) (io.ReadCloser, error) {\n\tbuf := bytes.NewBufferString(s)\n\treturn ioutil.NopCloser(buf), nil\n}\n\n\/\/JsonMarshalerFunc can be used to marshal request bodies\n\/\/into json\nfunc JsonMarshalerFunc(v interface{}) (io.ReadCloser, error) {\n\tb, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbody, err := ByteSliceToReadCloser(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn body, nil\n}\n\n\/\/JsonUnmarshalerFunc can be used to unmarshal response bodies\n\/\/from json\nfunc JsonUnmarshalerFunc(body io.ReadCloser, v interface{}) error {\n\tdefer body.Close()\n\tb, err := ioutil.ReadAll(body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(b, v)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/StringMarshalerFunc can be used to marshal strings into a request.\nfunc StringMarshalerFunc(v interface{}) (io.ReadCloser, error) {\n\tswitch t := v.(type) {\n\tcase fmt.Stringer:\n\t\treturn StringToReadCloser(t.String())\n\tcase string:\n\t\treturn StringToReadCloser(t)\n\t}\n\n\treturn nil, errors.New(\"Did not know how to use the body as text.\")\n}\n\n\/\/StringUnmarshalerFunc can be used to unmarshal strings from a response.\nfunc StringUnmarshalerFunc(body io.ReadCloser, v interface{}) error {\n\tdefer body.Close()\n\n\tif v == nil {\n\t\treturn nil\n\t}\n\n\tb, err := ioutil.ReadAll(body)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch v.(type) {\n\tcase *string:\n\t\telem := rt.ValueOf(v).Elem()\n\n\t\tif elem.CanSet() {\n\t\t\telem.SetString(string(b))\n\t\t\treturn nil\n\t\t}\n\tcase string:\n\t\treturn errors.New(\"You must pass the string by reference: \")\n\t}\n\n\treturn errors.New(\"Did not know how to unmarshal the text coming back.\")\n}\n\n\/\/JsonContentTypeMutator sets the Content-Type of the request to be\n\/\/application\/json\nfunc JsonContentTypeMutator(r *http.Request) error {\n\tr.Header.Add(\"Content-Type\", \"application\/json\")\n\treturn nil\n}\n\n\/\/RequestMutators are called before the request is made but after the marshaler function has been\n\/\/called.\ntype RequestMutator func(*http.Request) error\ntype ResponseMutator func(*http.Response) error\n\n\/\/SetupClientForJson is a convenience method that sets the\n\/\/marshaler and unmarshaler funcs on the client to be the\n\/\/Json funcs in this package. It also sets a request mutator\n\/\/to set the Content-Type to json.\nfunc SetupForJson(c Client) {\n\tc.SetMarshaler(JsonMarshalerFunc)\n\tc.SetUnmarshaler(JsonUnmarshalerFunc)\n\tc.AddRequestMutators(JsonContentTypeMutator)\n}\n<|endoftext|>"}
{"text":"<commit_before>package xbl\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\nconst userAgent = \"SmartGlass\/com.microsoft.smartglass (1610.1205.1554; OS Version 10.1.1 (Build 14B100))\"\n\n\/\/ Client encapsulates the entire Xbox Live API and a set\n\/\/ of credentials to access the API.\n\/\/\n\/\/ A Client is safe for concurrent access.\ntype Client struct {\n\tclient      http.Client\n\tcredentials *credentials\n}\n\n\/\/ Expiry returns the time at which this client's credentials will\n\/\/ no longer be valid and the client should be replaced with a new\n\/\/ one obtained from Login.\nfunc (c *Client) Expiry() time.Time {\n\treturn c.credentials.expiresAt\n}\n\n\/\/ UserID returns the XID user ID of the user who is authenticated with\n\/\/ the API. All requests to the API are performed as this user.\nfunc (c *Client) UserID() string {\n\treturn c.credentials.xid\n}\n\n\/\/ Gamertag returns the gamertag of the user who is authenticated with the API.\nfunc (c *Client) Gamertag() string {\n\treturn c.credentials.gamertag\n}\n\ntype apiVersion int\n\nconst (\n\tvXbox360 apiVersion = 1\n\tvXboxOne apiVersion = 2\n\tvBoth    apiVersion = 3\n)\n\nfunc (c *Client) post(url string, v apiVersion, body interface{}, respBody interface{}) error {\n\tb, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewReader(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"User-Agent\", userAgent)\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\treq.Header.Set(\"Accept\", \"application\/json\")\n\treq.Header.Set(\"Authorization\", c.credentials.authHeader())\n\treq.Header.Set(\"x-xbl-contract-version\", strconv.Itoa(int(v)))\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn json.NewDecoder(resp.Body).Decode(respBody)\n}\n\nfunc (c *Client) get(u string, v apiVersion, respBody interface{}) error {\n\treq, err := http.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"User-Agent\", userAgent)\n\treq.Header.Set(\"Accept\", \"application\/json\")\n\treq.Header.Set(\"Authorization\", c.credentials.authHeader())\n\treq.Header.Set(\"x-xbl-contract-version\", strconv.Itoa(int(v)))\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn json.NewDecoder(resp.Body).Decode(respBody)\n}\n\ntype reqOptions struct {\n\tupdatedSince time.Time\n}\n\n\/\/ Option defines an option for a client method.\ntype Option func(*reqOptions)\n\n\/\/ UpdatedSince will filter results to only results updated since the\n\/\/ provided time.\nfunc UpdatedSince(t time.Time) func(*reqOptions) {\n\treturn func(ro *reqOptions) { ro.updatedSince = t }\n}\n<commit_msg>UpdatedSince returns Option<commit_after>package xbl\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\nconst userAgent = \"SmartGlass\/com.microsoft.smartglass (1610.1205.1554; OS Version 10.1.1 (Build 14B100))\"\n\n\/\/ Client encapsulates the entire Xbox Live API and a set\n\/\/ of credentials to access the API.\n\/\/\n\/\/ A Client is safe for concurrent access.\ntype Client struct {\n\tclient      http.Client\n\tcredentials *credentials\n}\n\n\/\/ Expiry returns the time at which this client's credentials will\n\/\/ no longer be valid and the client should be replaced with a new\n\/\/ one obtained from Login.\nfunc (c *Client) Expiry() time.Time {\n\treturn c.credentials.expiresAt\n}\n\n\/\/ UserID returns the XID user ID of the user who is authenticated with\n\/\/ the API. All requests to the API are performed as this user.\nfunc (c *Client) UserID() string {\n\treturn c.credentials.xid\n}\n\n\/\/ Gamertag returns the gamertag of the user who is authenticated with the API.\nfunc (c *Client) Gamertag() string {\n\treturn c.credentials.gamertag\n}\n\ntype apiVersion int\n\nconst (\n\tvXbox360 apiVersion = 1\n\tvXboxOne apiVersion = 2\n\tvBoth    apiVersion = 3\n)\n\nfunc (c *Client) post(url string, v apiVersion, body interface{}, respBody interface{}) error {\n\tb, err := json.Marshal(body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewReader(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"User-Agent\", userAgent)\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\treq.Header.Set(\"Accept\", \"application\/json\")\n\treq.Header.Set(\"Authorization\", c.credentials.authHeader())\n\treq.Header.Set(\"x-xbl-contract-version\", strconv.Itoa(int(v)))\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn json.NewDecoder(resp.Body).Decode(respBody)\n}\n\nfunc (c *Client) get(u string, v apiVersion, respBody interface{}) error {\n\treq, err := http.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"User-Agent\", userAgent)\n\treq.Header.Set(\"Accept\", \"application\/json\")\n\treq.Header.Set(\"Authorization\", c.credentials.authHeader())\n\treq.Header.Set(\"x-xbl-contract-version\", strconv.Itoa(int(v)))\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn json.NewDecoder(resp.Body).Decode(respBody)\n}\n\ntype reqOptions struct {\n\tupdatedSince time.Time\n}\n\n\/\/ Option defines an option for a client method.\ntype Option func(*reqOptions)\n\n\/\/ UpdatedSince will filter results to only results updated since the\n\/\/ provided time.\nfunc UpdatedSince(t time.Time) Option {\n\treturn func(ro *reqOptions) { ro.updatedSince = t }\n}\n<|endoftext|>"}
{"text":"<commit_before>package getter\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\turlhelper \"github.com\/hashicorp\/terraform\/helper\/url\"\n)\n\n\/\/ Client is a client for downloading things.\n\/\/\n\/\/ Top-level functions such as Get are shortcuts for interacting with a client.\n\/\/ Using a client directly allows more fine-grained control over how downloading\n\/\/ is done, as well as customizing the protocols supported.\ntype Client struct {\n\t\/\/ Src is the source URL to get.\n\t\/\/\n\t\/\/ Dst is the path to save the downloaded thing as. If Dir is set to\n\t\/\/ true, then this should be a directory. If the directory doesn't exist,\n\t\/\/ it will be created for you.\n\tSrc string\n\tDst string\n\n\t\/\/ Dir, if true, tells the Client it is downloading a directory (versus\n\t\/\/ a single file). This distinction is necessary since filenames and\n\t\/\/ directory names follow the same format so disambiguating is impossible\n\t\/\/ without knowing ahead of time.\n\tDir bool\n\n\t\/\/ Getters is the map of protocols supported by this client. Use\n\t\/\/ the global Getters variable for the built-in defaults.\n\tGetters map[string]Getter\n}\n\n\/\/ Get downloads the configured source to the destination.\nfunc (c *Client) Get() error {\n\tforce, src := getForcedGetter(c.Src)\n\n\t\/\/ If there is a subdir component, then we download the root separately\n\t\/\/ and then copy over the proper subdir.\n\tvar realDst string\n\tdst := c.Dst\n\tsrc, subDir := SourceDirSubdir(src)\n\tif subDir != \"\" {\n\t\ttmpDir, err := ioutil.TempDir(\"\", \"tf\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := os.RemoveAll(tmpDir); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer os.RemoveAll(tmpDir)\n\n\t\trealDst = dst\n\t\tdst = tmpDir\n\t}\n\n\tu, err := urlhelper.Parse(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif force == \"\" {\n\t\tforce = u.Scheme\n\t}\n\n\tg, ok := c.Getters[force]\n\tif !ok {\n\t\treturn fmt.Errorf(\n\t\t\t\"download not supported for scheme '%s'\", force)\n\t}\n\n\t\/\/ If we're not downloading a directory, then just download the file\n\t\/\/ and return.\n\tif !c.Dir {\n\t\treturn g.GetFile(dst, u)\n\t}\n\n\t\/\/ We're downloading a directory, which might require a bit more work\n\t\/\/ if we're specifying a subdir.\n\terr = g.Get(dst, u)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"error downloading '%s': %s\", src, err)\n\t\treturn err\n\t}\n\n\t\/\/ If we have a subdir, copy that over\n\tif subDir != \"\" {\n\t\tif err := os.RemoveAll(realDst); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := os.MkdirAll(realDst, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn copyDir(realDst, filepath.Join(dst, subDir), false)\n\t}\n\n\treturn nil\n}\n<commit_msg>add basic checksum<commit_after>package getter\n\nimport (\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\turlhelper \"github.com\/hashicorp\/terraform\/helper\/url\"\n)\n\n\/\/ Client is a client for downloading things.\n\/\/\n\/\/ Top-level functions such as Get are shortcuts for interacting with a client.\n\/\/ Using a client directly allows more fine-grained control over how downloading\n\/\/ is done, as well as customizing the protocols supported.\ntype Client struct {\n\t\/\/ Src is the source URL to get.\n\t\/\/\n\t\/\/ Dst is the path to save the downloaded thing as. If Dir is set to\n\t\/\/ true, then this should be a directory. If the directory doesn't exist,\n\t\/\/ it will be created for you.\n\tSrc string\n\tDst string\n\n\t\/\/ Dir, if true, tells the Client it is downloading a directory (versus\n\t\/\/ a single file). This distinction is necessary since filenames and\n\t\/\/ directory names follow the same format so disambiguating is impossible\n\t\/\/ without knowing ahead of time.\n\tDir bool\n\n\t\/\/ Getters is the map of protocols supported by this client. Use\n\t\/\/ the global Getters variable for the built-in defaults.\n\tGetters map[string]Getter\n}\n\n\/\/ Get downloads the configured source to the destination.\nfunc (c *Client) Get() error {\n\tforce, src := getForcedGetter(c.Src)\n\n\t\/\/ If there is a subdir component, then we download the root separately\n\t\/\/ and then copy over the proper subdir.\n\tvar realDst string\n\tdst := c.Dst\n\tsrc, subDir := SourceDirSubdir(src)\n\tif subDir != \"\" {\n\t\ttmpDir, err := ioutil.TempDir(\"\", \"tf\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := os.RemoveAll(tmpDir); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer os.RemoveAll(tmpDir)\n\n\t\trealDst = dst\n\t\tdst = tmpDir\n\t}\n\n\tu, err := urlhelper.Parse(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif force == \"\" {\n\t\tforce = u.Scheme\n\t}\n\n\tg, ok := c.Getters[force]\n\tif !ok {\n\t\treturn fmt.Errorf(\n\t\t\t\"download not supported for scheme '%s'\", force)\n\t}\n\n\tvar sum string\n\tsumRaw := u.Query()[\"checksum\"]\n\tif len(sumRaw) == 1 {\n\t\tsum = sumRaw[0]\n\t}\n\n\t\/\/ If we're not downloading a directory, then just download the file\n\t\/\/ and return.\n\tif !c.Dir {\n\t\tif sum == \"\" {\n\t\t\treturn g.GetFile(dst, u)\n\t\t}\n\n\t\terr := g.GetFile(dst, u)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn checksum(dst, sum)\n\t}\n\n\t\/\/ We're downloading a directory, which might require a bit more work\n\t\/\/ if we're specifying a subdir.\n\terr = g.Get(dst, u)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"error downloading '%s': %s\", src, err)\n\t\treturn err\n\t}\n\n\t\/\/ If we have a subdir, copy that over\n\tif subDir != \"\" {\n\t\tif err := os.RemoveAll(realDst); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := os.MkdirAll(realDst, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn copyDir(realDst, filepath.Join(dst, subDir), false)\n\t}\n\n\treturn checksum(realDst, sum)\n}\n\n\/\/ checksum is a simple method to compute the SHA256 checksum of a source (file\n\/\/ or dir) and compare it to a given sum.\nfunc checksum(source, sum string) error {\n\tif sum == \"\" {\n\t\treturn nil\n\t}\n\t\/\/ compute and check checksum\n\tlog.Printf(\"[DEBUG] Running checksum on (%s)\", source)\n\thasher := sha256.New()\n\tfile, err := os.Open(source)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to open file for checksum: %s\", err)\n\t}\n\n\tdefer file.Close()\n\tio.Copy(hasher, file)\n\n\tcomputed := hex.EncodeToString(hasher.Sum(nil))\n\tif sum != computed {\n\t\treturn fmt.Errorf(\n\t\t\t\"Checksums did not match.\\nExpected (%s), got (%s)\",\n\t\t\tsum,\n\t\t\tcomputed)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package wireless\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/ Client represents a wireless client\ntype Client struct {\n\tconn *Conn\n}\n\n\/\/ NewClient will create a new client by connecting to the\n\/\/ given interface in WPA\nfunc NewClient(iface string) (c *Client, err error) {\n\tc.conn, err = Dial(iface)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ NewClientFromConn returns a new client from an already established connection\nfunc NewClientFromConn(conn *Conn) (c *Client) {\n\tc.conn = conn\n\treturn\n}\n\n\/\/ Close will close the client connection\nfunc (cl *Client) Close() {\n\tcl.conn.Close()\n}\n\n\/\/ Conn will return the underlying connection\nfunc (cl *Client) Conn() *Conn {\n\treturn cl.conn\n}\n\n\/\/ Subscribe will subscribe to certain events that happen in WPA\nfunc (cl *Client) Subscribe(topics ...string) *Subscription {\n\treturn cl.conn.Subscribe(topics...)\n}\n\n\/\/ Status will return the current state of the WPA\nfunc (cl *Client) Status() (State, error) {\n\tdata, err := cl.conn.SendCommand(CmdStatus)\n\tif err != nil {\n\t\treturn State{}, err\n\t}\n\ts := NewState(data)\n\treturn s, nil\n}\n\n\/\/ Scan will scan for networks and return the APs it finds\nfunc (cl *Client) Scan() (nets []AP, err error) {\n\terr = cl.conn.SendCommandBool(CmdScan)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresults := cl.conn.Subscribe(EventScanResults)\n\tfailed := cl.conn.Subscribe(EventScanFailed)\n\n\tfor {\n\t\tselect {\n\t\tcase <-failed.Next():\n\t\t\terr = ErrScanFailed\n\t\t\treturn\n\t\tcase <-results.Next():\n\t\t\tbreak\n\t\tcase <-time.NewTimer(time.Second * 2).C:\n\t\t\tbreak\n\t\t}\n\t}\n\n\tscanned, err := cl.conn.SendCommand(CmdScanResults)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn parseAP([]byte(scanned))\n}\n\n\/\/ Networks lists the known networks\nfunc (cl *Client) Networks() (nets []Network, err error) {\n\tdata, err := cl.conn.SendCommand(CmdListNetworks)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn parseNetwork([]byte(data))\n}\n\n\/\/ Connect to a new or existing network\nfunc (cl *Client) Connect(net Network) (Network, error) {\n\tnet, err := cl.AddOrUpdateNetwork(net)\n\tif err != nil {\n\t\treturn net, err\n\t}\n\n\tsub := cl.conn.Subscribe(EventNetworkNotFound, EventAuthReject, EventConnected, EventDisconnected, EventAssocReject)\n\tif err := cl.EnableNetwork(net.ID); err != nil {\n\t\treturn net, err\n\t}\n\n\tev := <-sub.Next()\n\n\tswitch ev.Name {\n\tcase EventConnected:\n\t\treturn net, cl.SaveConfig()\n\tcase EventNetworkNotFound:\n\t\treturn net, ErrSSIDNotFound\n\tcase EventAuthReject:\n\t\treturn net, ErrAuthFailed\n\tcase EventDisconnected:\n\t\treturn net, ErrDisconnected\n\tcase EventAssocReject:\n\t\treturn net, ErrAssocRejected\n\t}\n\n\treturn net, errors.New(\"failed to catch event \" + ev.Name)\n}\n\n\/\/ AddOrUpdateNetwork will add or, if the network has IDStr set, update it\nfunc (cl *Client) AddOrUpdateNetwork(net Network) (Network, error) {\n\tif net.IDStr != \"\" {\n\t\tnets, err := cl.Networks()\n\t\tif err != nil {\n\t\t\treturn net, err\n\t\t}\n\n\t\tfor _, n := range nets {\n\t\t\tif n.IDStr == net.IDStr {\n\t\t\t\treturn cl.UpdateNetwork(net)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn cl.AddNetwork(net)\n}\n\n\/\/ UpdateNetwork will update the given network, an error will be thrown\n\/\/ if the network doesn't have IDStr specified\nfunc (cl *Client) UpdateNetwork(net Network) (Network, error) {\n\tif net.IDStr == \"\" {\n\t\treturn net, ErrNoIdentifier\n\t}\n\n\tfor _, cmd := range net.SetCmds() {\n\t\tif err := cl.conn.SendCommandBool(cmd...); err != nil {\n\t\t\treturn net, err\n\t\t}\n\t}\n\n\treturn net, nil\n}\n\n\/\/ AddNetwork will add a new network\nfunc (cl *Client) AddNetwork(net Network) (Network, error) {\n\ti, err := cl.conn.SendCommandInt(CmdAddNetwork)\n\tif err != nil {\n\t\treturn net, err\n\t}\n\n\tnet.ID = i\n\n\tif net.IDStr == \"\" {\n\t\tnet.IDStr = net.SSID\n\t}\n\n\tfor _, cmd := range net.SetCmds() {\n\t\tif err := cl.conn.SendCommandBool(cmd...); err != nil {\n\t\t\treturn net, err\n\t\t}\n\t}\n\n\treturn net, nil\n}\n\n\/\/ RemoveNetwork will RemoveNetwork\nfunc (cl *Client) RemoveNetwork(id int) error {\n\treturn cl.conn.SendCommandBool(CmdRemoveNetwork, strconv.Itoa(id))\n}\n\n\/\/ EnableNetwork will EnableNetwork\nfunc (cl *Client) EnableNetwork(id int) error {\n\treturn cl.conn.SendCommandBool(CmdEnableNetwork + \" \" + strconv.Itoa(id))\n}\n\n\/\/ DisableNetwork will DisableNetwork\nfunc (cl *Client) DisableNetwork(id int) error {\n\treturn cl.conn.SendCommandBool(CmdDisableNetwork + \" \" + strconv.Itoa(id))\n}\n\n\/\/ SaveConfig will SaveConfig\nfunc (cl *Client) SaveConfig() error {\n\treturn cl.conn.SendCommandBool(CmdSaveConfig)\n}\n\n\/\/ LoadConfig will LoadConfig\nfunc (cl *Client) LoadConfig() error {\n\treturn cl.conn.SendCommandBool(CmdReconfigure)\n}\n<commit_msg>fix bug with scanning<commit_after>package wireless\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/ Client represents a wireless client\ntype Client struct {\n\tconn *Conn\n}\n\n\/\/ NewClient will create a new client by connecting to the\n\/\/ given interface in WPA\nfunc NewClient(iface string) (c *Client, err error) {\n\tc = new(Client)\n\tc.conn, err = Dial(iface)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ NewClientFromConn returns a new client from an already established connection\nfunc NewClientFromConn(conn *Conn) (c *Client) {\n\tc.conn = conn\n\treturn\n}\n\n\/\/ Close will close the client connection\nfunc (cl *Client) Close() {\n\tcl.conn.Close()\n}\n\n\/\/ Conn will return the underlying connection\nfunc (cl *Client) Conn() *Conn {\n\treturn cl.conn\n}\n\n\/\/ Subscribe will subscribe to certain events that happen in WPA\nfunc (cl *Client) Subscribe(topics ...string) *Subscription {\n\treturn cl.conn.Subscribe(topics...)\n}\n\n\/\/ Status will return the current state of the WPA\nfunc (cl *Client) Status() (State, error) {\n\tdata, err := cl.conn.SendCommand(CmdStatus)\n\tif err != nil {\n\t\treturn State{}, err\n\t}\n\ts := NewState(data)\n\treturn s, nil\n}\n\n\/\/ Scan will scan for networks and return the APs it finds\nfunc (cl *Client) Scan() (nets []AP, err error) {\n\terr = cl.conn.SendCommandBool(CmdScan)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresults := cl.conn.Subscribe(EventScanResults)\n\tfailed := cl.conn.Subscribe(EventScanFailed)\n\n\tfunc() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-failed.Next():\n\t\t\t\terr = ErrScanFailed\n\t\t\t\treturn\n\t\t\tcase <-results.Next():\n\t\t\t\treturn\n\t\t\tcase <-time.NewTimer(time.Second * 2).C:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tscanned, err := cl.conn.SendCommand(CmdScanResults)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn parseAP([]byte(scanned))\n}\n\n\/\/ Networks lists the known networks\nfunc (cl *Client) Networks() (nets []Network, err error) {\n\tdata, err := cl.conn.SendCommand(CmdListNetworks)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn parseNetwork([]byte(data))\n}\n\n\/\/ Connect to a new or existing network\nfunc (cl *Client) Connect(net Network) (Network, error) {\n\tnet, err := cl.AddOrUpdateNetwork(net)\n\tif err != nil {\n\t\treturn net, err\n\t}\n\n\tsub := cl.conn.Subscribe(EventNetworkNotFound, EventAuthReject, EventConnected, EventDisconnected, EventAssocReject)\n\tif err := cl.EnableNetwork(net.ID); err != nil {\n\t\treturn net, err\n\t}\n\n\tev := <-sub.Next()\n\n\tswitch ev.Name {\n\tcase EventConnected:\n\t\treturn net, cl.SaveConfig()\n\tcase EventNetworkNotFound:\n\t\treturn net, ErrSSIDNotFound\n\tcase EventAuthReject:\n\t\treturn net, ErrAuthFailed\n\tcase EventDisconnected:\n\t\treturn net, ErrDisconnected\n\tcase EventAssocReject:\n\t\treturn net, ErrAssocRejected\n\t}\n\n\treturn net, errors.New(\"failed to catch event \" + ev.Name)\n}\n\n\/\/ AddOrUpdateNetwork will add or, if the network has IDStr set, update it\nfunc (cl *Client) AddOrUpdateNetwork(net Network) (Network, error) {\n\tif net.IDStr != \"\" {\n\t\tnets, err := cl.Networks()\n\t\tif err != nil {\n\t\t\treturn net, err\n\t\t}\n\n\t\tfor _, n := range nets {\n\t\t\tif n.IDStr == net.IDStr {\n\t\t\t\treturn cl.UpdateNetwork(net)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn cl.AddNetwork(net)\n}\n\n\/\/ UpdateNetwork will update the given network, an error will be thrown\n\/\/ if the network doesn't have IDStr specified\nfunc (cl *Client) UpdateNetwork(net Network) (Network, error) {\n\tif net.IDStr == \"\" {\n\t\treturn net, ErrNoIdentifier\n\t}\n\n\tfor _, cmd := range net.SetCmds() {\n\t\tif err := cl.conn.SendCommandBool(cmd...); err != nil {\n\t\t\treturn net, err\n\t\t}\n\t}\n\n\treturn net, nil\n}\n\n\/\/ AddNetwork will add a new network\nfunc (cl *Client) AddNetwork(net Network) (Network, error) {\n\ti, err := cl.conn.SendCommandInt(CmdAddNetwork)\n\tif err != nil {\n\t\treturn net, err\n\t}\n\n\tnet.ID = i\n\n\tif net.IDStr == \"\" {\n\t\tnet.IDStr = net.SSID\n\t}\n\n\tfor _, cmd := range net.SetCmds() {\n\t\tif err := cl.conn.SendCommandBool(cmd...); err != nil {\n\t\t\treturn net, err\n\t\t}\n\t}\n\n\treturn net, nil\n}\n\n\/\/ RemoveNetwork will RemoveNetwork\nfunc (cl *Client) RemoveNetwork(id int) error {\n\treturn cl.conn.SendCommandBool(CmdRemoveNetwork, strconv.Itoa(id))\n}\n\n\/\/ EnableNetwork will EnableNetwork\nfunc (cl *Client) EnableNetwork(id int) error {\n\treturn cl.conn.SendCommandBool(CmdEnableNetwork + \" \" + strconv.Itoa(id))\n}\n\n\/\/ DisableNetwork will DisableNetwork\nfunc (cl *Client) DisableNetwork(id int) error {\n\treturn cl.conn.SendCommandBool(CmdDisableNetwork + \" \" + strconv.Itoa(id))\n}\n\n\/\/ SaveConfig will SaveConfig\nfunc (cl *Client) SaveConfig() error {\n\treturn cl.conn.SendCommandBool(CmdSaveConfig)\n}\n\n\/\/ LoadConfig will LoadConfig\nfunc (cl *Client) LoadConfig() error {\n\treturn cl.conn.SendCommandBool(CmdReconfigure)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\nfunc loop() {\n\tclient := &http.Client{}\n\tfqdn := \"localhost\"\n\n\tresp, err := client.Post(\"http:\/\/localhost:1234\/poll\", \"\", strings.NewReader(fqdn))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\trequest, _ := http.ReadRequest(bufio.NewReader(resp.Body))\n\tid := request.Header.Get(\"id\") \/\/ Needed so they can be linked.\n\tlog.Printf(\"Got request for %s\", request.URL.String())\n\trequest.RequestURI = \"\"\n\n\tscrapeResp, err := client.Do(request)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\tlog.Printf(\"Scraped %s\", request.URL.String())\n\tscrapeResp.Header.Set(\"id\", id)\n\tbuf := &bytes.Buffer{}\n\tscrapeResp.Write(buf)\n\tlog.Println(buf.Len())\n\n\t_, err = client.Post(\"http:\/\/localhost:1234\/push\", \"\", buf)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\tlog.Printf(\"Pushed scrape result for %s\", request.URL.String())\n}\n\nfunc main() {\n\tfor {\n\t\tloop()\n\t}\n}\n<commit_msg>Make client more resilient and performant<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc doScrape(request *http.Request) {\n\tclient := &http.Client{}\n\tid := request.Header.Get(\"id\") \/\/ Needed so they can be linked.\n\n\tscrapeResp, err := client.Do(request)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to scrape %s: %s\", request.URL.String(), err)\n\t\treturn\n\t}\n\tlog.Printf(\"Scraped %s\", request.URL.String())\n\tscrapeResp.Header.Set(\"id\", id)\n\tbuf := &bytes.Buffer{}\n\tscrapeResp.Write(buf)\n\tlog.Println(buf.Len())\n\n\t_, err = client.Post(\"http:\/\/localhost:1234\/push\", \"\", buf)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to push scrape result for %s: %s\", request.URL.String(), err)\n\t\treturn\n\t}\n\tlog.Printf(\"Pushed scrape result for %s\", request.URL.String())\n}\n\nfunc loop() {\n\tclient := &http.Client{}\n\tfqdn := \"localhost\"\n\n\tresp, err := client.Post(\"http:\/\/localhost:1234\/poll\", \"\", strings.NewReader(fqdn))\n\tif err != nil {\n\t\tlog.Printf(\"Error polling: %s\", err)\n\t\ttime.Sleep(time.Second) \/\/ Don't pound the server.\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\trequest, _ := http.ReadRequest(bufio.NewReader(resp.Body))\n\tlog.Printf(\"Got request for %s\", request.URL.String())\n\trequest.RequestURI = \"\"\n\n\tgo doScrape(request)\n}\n\nfunc main() {\n\tfor {\n\t\tloop()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package mongo\n\nimport (\n\t\"errors\"\n\t\"github.com\/gobly\/core\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\t\"runtime\"\n)\n\ntype Client struct {\n\tdb         *mgo.Database\n\tc          *mgo.Collection\n\tsession    *mgo.Session\n\tcollection string\n}\n\nfunc (m *Client) Connect(url string, db string, collection string) error {\n\tsession, err := mgo.Dial(url)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\tm.db = session.DB(db)\n\tm.c = m.db.C(collection)\n\tm.session = session\n\tm.collection = collection\n\n\truntime.SetFinalizer(m, func(m *Client) { m.session.Close() })\n\treturn nil\n}\n\nfunc (m *Client) Insert(v interface{}) error {\n\tobjectId := NewObjectId(v)\n\toid, ok := objectId.Value()\n\tif !ok {\n\t\tobjectId.SetValue(oid)\n\t}\n\terr := m.c.Insert(v)\n\treturn err\n}\n\nfunc (m *Client) Update(v interface{}) error {\n\tobjectId := NewObjectId(v)\n\toid, ok := objectId.Value()\n\tif !ok {\n\t\treturn errors.New(\"Missing objectID\")\n\t}\n\n\treturn m.c.UpdateId(oid, v)\n}\n\nfunc (m *Client) UpdateRawFiltered(f bson.M, q bson.M) error {\n\treturn m.c.Update(f, q)\n}\n\nfunc (m *Client) UpdateRaw(q bson.M) error {\n\treturn m.c.Update(nil, q)\n}\n\nfunc (m *Client) ReadByValueFiltered(f interface{}, v interface{}) error {\n\treturn m.c.Find(v).Select(f).One(v)\n}\n\nfunc (m *Client) ReadByValue(v interface{}) error {\n\treturn m.c.Find(v).One(v)\n}\n\nfunc (m *Client) ReadRaw(q map[string]string, v interface{}) error {\n\treturn m.c.Find(q).One(v)\n}\n\nfunc (m *Client) ReadByID(objectId string, v interface{}) error {\n\tif !bson.IsObjectIdHex(objectId) {\n\t\treturn errors.New(\"Invalid ObjectID format\")\n\t}\n\n\treturn m.c.FindId(bson.ObjectIdHex(objectId)).One(v)\n}\n\nfunc (m *Client) ReadBySlug(slug string, v interface{}) error {\n\tif bson.IsObjectIdHex(slug) {\n\t\treturn m.c.FindId(bson.ObjectIdHex(slug)).One(v)\n\t}\n\n\ts := core.NewSlug(v)\n\ts.SetValue(slug)\n\treturn m.c.Find(v).One(v)\n}\n\nfunc (m *Client) FindAll(v interface{}) error {\n\treturn m.c.Find(nil).All(v)\n}\n\nfunc (m *Client) FindByValue(q interface{}, v interface{}) error {\n\treturn m.c.Find(q).All(v)\n}\n\nfunc (m *Client) FindByValueSorted(q interface{}, v interface{}, fields ...string) error {\n\treturn m.c.Find(q).Sort(fields...).All(v)\n}\n\nfunc (m *Client) FindById(objectId string, v interface{}) error {\n\tif !bson.IsObjectIdHex(objectId) {\n\t\treturn errors.New(\"Invalid ObjectID format\")\n\t}\n\n\treturn m.c.FindId(bson.ObjectIdHex(objectId)).All(v)\n}\n\nfunc (m *Client) FindGroup(q interface{}, groupPipe bson.M, sortPipe bson.M, v interface{}) error {\n\tpipe := []bson.M{\n\t\t{\"$match\": q},\n\t\t{\"$group\": groupPipe},\n\t}\n\n\tif len(sortPipe) > 0 {\n\t\treturn m.c.Pipe(append(pipe, bson.M{\"$sort\": sortPipe})).All(v)\n\t}\n\n\treturn m.c.Pipe(pipe).All(v)\n}\n\nfunc (m *Client) FindRedact(q interface{}, redactPipe bson.M, sortPipe bson.M, v interface{}) error {\n\tpipe := []bson.M{\n\t\t{\"$match\": q},\n\t\t{\"$redact\": bson.M{\n\t\t\t\"$cond\": []interface{}{redactPipe, \"$$KEEP\", \"$$PRUNE\"},\n\t\t}},\n\t}\n\n\tif len(sortPipe) > 0 {\n\t\treturn m.c.Pipe(append(pipe, bson.M{\"$sort\": sortPipe})).All(v)\n\t}\n\n\treturn m.c.Pipe(pipe).All(v)\n}\n\nfunc (m *Client) DeleteById(objectId string) error {\n\tif !bson.IsObjectIdHex(objectId) {\n\t\treturn errors.New(\"Invalid ObjectID format\")\n\t}\n\n\treturn m.c.RemoveId(bson.ObjectIdHex(objectId))\n}\n\nfunc (m *Client) DeleteBySlug(slug string, v interface{}) error {\n\tif bson.IsObjectIdHex(slug) {\n\t\treturn m.c.RemoveId(bson.ObjectIdHex(slug))\n\t}\n\n\ts := core.NewSlug(v)\n\ts.SetValue(slug)\n\treturn m.c.Remove(v)\n}\n\nfunc (m *Client) CreateCollection() error {\n\tcols, err := m.db.CollectionNames()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, collection := range cols {\n\t\tif collection == m.collection {\n\t\t\treturn errors.New(\"Collection already exists\")\n\t\t}\n\t}\n\n\treturn m.c.Create(&mgo.CollectionInfo{})\n}\n\nfunc (m *Client) DropCollection() error {\n\treturn m.c.DropCollection()\n}\n<commit_msg>Use consistent raw queries<commit_after>package mongo\n\nimport (\n\t\"errors\"\n\t\"github.com\/gobly\/core\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\t\"runtime\"\n)\n\ntype Client struct {\n\tdb         *mgo.Database\n\tc          *mgo.Collection\n\tsession    *mgo.Session\n\tcollection string\n}\n\nfunc (m *Client) Connect(url string, db string, collection string) error {\n\tsession, err := mgo.Dial(url)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\tm.db = session.DB(db)\n\tm.c = m.db.C(collection)\n\tm.session = session\n\tm.collection = collection\n\n\truntime.SetFinalizer(m, func(m *Client) { m.session.Close() })\n\treturn nil\n}\n\nfunc (m *Client) Insert(v interface{}) error {\n\tobjectId := NewObjectId(v)\n\toid, ok := objectId.Value()\n\tif !ok {\n\t\tobjectId.SetValue(oid)\n\t}\n\terr := m.c.Insert(v)\n\treturn err\n}\n\nfunc (m *Client) Update(v interface{}) error {\n\tobjectId := NewObjectId(v)\n\toid, ok := objectId.Value()\n\tif !ok {\n\t\treturn errors.New(\"Missing objectID\")\n\t}\n\n\treturn m.c.UpdateId(oid, v)\n}\n\nfunc (m *Client) UpdateRawFiltered(f bson.M, q bson.M) error {\n\treturn m.c.Update(f, q)\n}\n\nfunc (m *Client) UpdateRaw(q bson.M) error {\n\treturn m.c.Update(nil, q)\n}\n\nfunc (m *Client) ReadByValueFiltered(f interface{}, v interface{}) error {\n\treturn m.c.Find(v).Select(f).One(v)\n}\n\nfunc (m *Client) ReadByValue(v interface{}) error {\n\treturn m.c.Find(v).One(v)\n}\n\nfunc (m *Client) ReadRaw(q bson.M, v interface{}) error {\n\treturn m.c.Find(q).One(v)\n}\n\nfunc (m *Client) ReadByID(objectId string, v interface{}) error {\n\tif !bson.IsObjectIdHex(objectId) {\n\t\treturn errors.New(\"Invalid ObjectID format\")\n\t}\n\n\treturn m.c.FindId(bson.ObjectIdHex(objectId)).One(v)\n}\n\nfunc (m *Client) ReadBySlug(slug string, v interface{}) error {\n\tif bson.IsObjectIdHex(slug) {\n\t\treturn m.c.FindId(bson.ObjectIdHex(slug)).One(v)\n\t}\n\n\ts := core.NewSlug(v)\n\ts.SetValue(slug)\n\treturn m.c.Find(v).One(v)\n}\n\nfunc (m *Client) FindAll(v interface{}) error {\n\treturn m.c.Find(nil).All(v)\n}\n\nfunc (m *Client) FindByValue(q interface{}, v interface{}) error {\n\treturn m.c.Find(q).All(v)\n}\n\nfunc (m *Client) FindByValueSorted(q interface{}, v interface{}, fields ...string) error {\n\treturn m.c.Find(q).Sort(fields...).All(v)\n}\n\nfunc (m *Client) FindById(objectId string, v interface{}) error {\n\tif !bson.IsObjectIdHex(objectId) {\n\t\treturn errors.New(\"Invalid ObjectID format\")\n\t}\n\n\treturn m.c.FindId(bson.ObjectIdHex(objectId)).All(v)\n}\n\nfunc (m *Client) FindGroup(q interface{}, groupPipe bson.M, sortPipe bson.M, v interface{}) error {\n\tpipe := []bson.M{\n\t\t{\"$match\": q},\n\t\t{\"$group\": groupPipe},\n\t}\n\n\tif len(sortPipe) > 0 {\n\t\treturn m.c.Pipe(append(pipe, bson.M{\"$sort\": sortPipe})).All(v)\n\t}\n\n\treturn m.c.Pipe(pipe).All(v)\n}\n\nfunc (m *Client) FindRedact(q interface{}, redactPipe bson.M, sortPipe bson.M, v interface{}) error {\n\tpipe := []bson.M{\n\t\t{\"$match\": q},\n\t\t{\"$redact\": bson.M{\n\t\t\t\"$cond\": []interface{}{redactPipe, \"$$KEEP\", \"$$PRUNE\"},\n\t\t}},\n\t}\n\n\tif len(sortPipe) > 0 {\n\t\treturn m.c.Pipe(append(pipe, bson.M{\"$sort\": sortPipe})).All(v)\n\t}\n\n\treturn m.c.Pipe(pipe).All(v)\n}\n\nfunc (m *Client) DeleteById(objectId string) error {\n\tif !bson.IsObjectIdHex(objectId) {\n\t\treturn errors.New(\"Invalid ObjectID format\")\n\t}\n\n\treturn m.c.RemoveId(bson.ObjectIdHex(objectId))\n}\n\nfunc (m *Client) DeleteBySlug(slug string, v interface{}) error {\n\tif bson.IsObjectIdHex(slug) {\n\t\treturn m.c.RemoveId(bson.ObjectIdHex(slug))\n\t}\n\n\ts := core.NewSlug(v)\n\ts.SetValue(slug)\n\treturn m.c.Remove(v)\n}\n\nfunc (m *Client) CreateCollection() error {\n\tcols, err := m.db.CollectionNames()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, collection := range cols {\n\t\tif collection == m.collection {\n\t\t\treturn errors.New(\"Collection already exists\")\n\t\t}\n\t}\n\n\treturn m.c.Create(&mgo.CollectionInfo{})\n}\n\nfunc (m *Client) DropCollection() error {\n\treturn m.c.DropCollection()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Afshin Darian. All rights reserved.\n\/\/ Use of this source code is governed by The MIT License\n\/\/ that can be found in the LICENSE file.\n\npackage sleuth\n\nimport (\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/pborman\/uuid\"\n\t\"github.com\/ursiform\/logger\"\n\t\"github.com\/zeromq\/gyre\"\n)\n\ntype listener struct {\n\t*sync.Mutex\n\thandles map[string]chan *http.Response\n}\n\ntype notifier struct {\n\t*sync.Mutex\n\tnotify chan struct{}\n}\n\n\/\/ Client is the peer on the sleuth network that makes requests and, if a\n\/\/ handler has been provided, responds to peer requests.\ntype Client struct {\n\t\/\/ Timeout is the duration to wait before an outstanding request times out.\n\t\/\/ By default, it is set to 500ms.\n\tTimeout time.Duration\n\n\tadditions *notifier\n\thandler   http.Handler\n\tlistener  *listener\n\tlog       *logger.Logger\n\tnode      *gyre.Gyre\n\n\tdirectory map[string]string   \/\/ map[node-name]service-type\n\tservices  map[string]*workers \/\/ map[service-type]service-workers\n}\n\nfunc (c *Client) add(gid, name, node, service, version string) error {\n\tif gid != group {\n\t\tc.log.Debug(\"sleuth: no group header for %s, client-only\", name)\n\t\treturn nil\n\t}\n\t\/\/ Node and service are required. Version is optional.\n\tif len(node) == 0 || len(service) == 0 {\n\t\treturn newError(errAdd, \"failed to add %s node?=%t, type?=%t\",\n\t\t\tname, len(node) > 0, len(service) > 0)\n\t}\n\t\/\/ Associate the node name with its service in the directory.\n\tc.directory[name] = service\n\t\/\/ Create a service workers collection if necessary.\n\tif c.services[service] == nil {\n\t\tc.services[service] = newWorkers()\n\t}\n\t\/\/ Add peer to the service workers.\n\tp := &peer{name: name, node: node, service: service, version: version}\n\tc.services[service].add(p)\n\t\/\/ If necessary, notify the additions channel that a peer has been added.\n\tif c.additions.notify != nil {\n\t\tc.additions.notify <- struct{}{}\n\t}\n\tc.log.Info(\"sleuth: add %s\/%s %s to %s\", service, version, name, group)\n\treturn nil\n}\n\n\/\/ Returns true if it had to block and false if it returns immediately.\nfunc (c *Client) block(services ...string) bool {\n\t\/\/ Block until the required services are available in the pool.\n\tc.additions.Lock()\n\tdefer c.additions.Unlock()\n\t\/\/ Even though the client may have just checked to see if services exist,\n\t\/\/ the check is performed here in case there was a delay waiting for the\n\t\/\/ additions mutex to become available.\n\tif c.has(services...) {\n\t\treturn false\n\t}\n\tc.log.Blocked(\"sleuth: waiting for client to find services %s\", services)\n\tc.additions.notify = make(chan struct{})\n\tfor range c.additions.notify {\n\t\tif c.has(services...) {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.additions.notify = nil\n\treturn true\n}\n\n\/\/ Close leaves the sleuth network and stops the Gyre node.\nfunc (c *Client) Close() error {\n\tc.log.Info(\"%s leaving %s...\", c.node.Name(), group)\n\tif err := c.node.Leave(group); err != nil {\n\t\treturn newError(errLeave, err.Error())\n\t}\n\tif err := c.node.Stop(); err != nil {\n\t\tc.log.Warn(\"sleuth: %s %s [%d]\",\n\t\t\tc.node.Name(), err.Error(), warnClose)\n\t}\n\treturn nil\n}\n\nfunc (c *Client) dispatch(payload []byte) error {\n\t\/\/ Returned responses (RECV command) and outstanding requests (REPL command)\n\t\/\/ have these headers, respectively: SLEUTH-V0RECV and SLEUTH-V0REPL\n\tgroupLength := len(group)\n\tdispatchLength := 4\n\theaderLength := groupLength + dispatchLength\n\t\/\/ If the message header does not match the group, bail.\n\tif len(payload) < headerLength || string(payload[0:groupLength]) != group {\n\t\treturn newError(errDispatchHeader, \"bad header\")\n\t}\n\taction := string(payload[groupLength : groupLength+dispatchLength])\n\tswitch action {\n\tcase recv:\n\t\treturn c.receive(payload[headerLength:])\n\tcase repl:\n\t\treturn c.reply(payload[headerLength:])\n\tdefault:\n\t\treturn newError(errDispatchAction, \"bad action: %s\", action)\n\t}\n}\n\n\/\/ Do sends an HTTP request to a service and returns and HTTP response. The URL\n\/\/ for requests needs to use the following format:\n\/\/ \tsleuth:\/\/service-name\/requested-path\n\/\/ For example, a request to the path \/bar?baz=qux of a service called\n\/\/ foo-service would have the URL:\n\/\/ \tsleuth:\/\/foo-service\/bar?baz=qux\nfunc (c *Client) Do(req *http.Request) (*http.Response, error) {\n\thandle := uuid.New()\n\tto := req.URL.Host\n\tif req.URL.Scheme != scheme {\n\t\terr := newError(errScheme,\n\t\t\t\"URL scheme must be \\\"%s\\\" in %s\", scheme, req.URL.String())\n\t\treturn nil, err\n\t}\n\tservices, ok := c.services[to]\n\tif !ok {\n\t\treturn nil, newError(errUnknownService, \"%s is an unknown service\", to)\n\t}\n\tp := services.next()\n\treceiver := c.node.UUID()\n\tpayload, err := marshalRequest(receiver, handle, req)\n\tif err != nil {\n\t\treturn nil, err.(*Error).escalate(errRequest)\n\t}\n\tc.log.Debug(\"sleuth: %s %s:\/\/%s@%s%s\",\n\t\treq.Method, scheme, to, p.name, req.URL.String())\n\tif err = c.node.Whisper(p.node, payload); err != nil {\n\t\treturn nil, newError(errReqWhisper, err.Error())\n\t}\n\tlistener := make(chan *http.Response, 1)\n\tc.listen(handle, listener)\n\tresponse := <-listener\n\tif response != nil {\n\t\treturn response, nil\n\t}\n\treturn nil, newError(errTimeout,\n\t\t\"%s {%s}%s timed out\", req.Method, to, req.URL.String())\n}\n\nfunc (c *Client) has(services ...string) bool {\n\t\/\/ Check to see if required services are already registered.\n\tverified := make(map[string]bool)\n\tavailable := 0\n\tfor _, service := range services {\n\t\tverified[service] = false\n\t}\n\ttotal := len(verified)\n\tfor service := range verified {\n\t\tif workers, ok := c.services[service]; ok && workers.available() {\n\t\t\tverified[service] = true\n\t\t\tavailable += 1\n\t\t}\n\t}\n\treturn available == total\n}\n\nfunc (c *Client) listen(handle string, listener chan *http.Response) {\n\tc.listener.Lock()\n\tdefer c.listener.Unlock()\n\tc.listener.handles[handle] = listener\n\tgo c.timeout(handle)\n}\n\nfunc (c *Client) receive(payload []byte) error {\n\thandle, res, err := unmarshalResponse(payload)\n\tif err != nil {\n\t\treturn err.(*Error).escalate(errRECV)\n\t}\n\tc.listener.Lock()\n\tdefer c.listener.Unlock()\n\tif listener, ok := c.listener.handles[handle]; ok {\n\t\tlistener <- res\n\t\tdelete(c.listener.handles, handle)\n\t} else {\n\t\treturn newError(errRECV, \"unknown handle %s\", handle)\n\t}\n\treturn nil\n}\n\nfunc (c *Client) remove(name string) {\n\tif service, ok := c.directory[name]; ok {\n\t\tremaining, _ := c.services[service].remove(name)\n\t\tif remaining == 0 {\n\t\t\tdelete(c.services, service)\n\t\t}\n\t\tdelete(c.directory, name)\n\t\tc.log.Info(\"sleuth: remove %s (%s) from %s\", service, name, group)\n\t}\n}\n\nfunc (c *Client) reply(payload []byte) error {\n\tdest, req, err := unmarshalRequest(payload)\n\tif err != nil {\n\t\treturn err.(*Error).escalate(errREPL)\n\t}\n\tc.handler.ServeHTTP(newWriter(c.node, dest), req)\n\treturn nil\n}\n\nfunc (c *Client) timeout(handle string) {\n\t<-time.After(c.Timeout)\n\tc.listener.Lock()\n\tdefer c.listener.Unlock()\n\tif listener, ok := c.listener.handles[handle]; ok {\n\t\tlistener <- nil\n\t\tdelete(c.listener.handles, handle)\n\t}\n}\n\n\/\/ WaitFor blocks until the required services are available in the pool.\nfunc (c *Client) WaitFor(services ...string) {\n\tif !c.has(services...) {\n\t\tc.block(services...)\n\t}\n}\n\nfunc newClient(node *gyre.Gyre, out *logger.Logger) *Client {\n\treturn &Client{\n\t\tadditions: &notifier{Mutex: new(sync.Mutex)},\n\t\tdirectory: make(map[string]string),\n\t\tlistener: &listener{\n\t\t\tnew(sync.Mutex),\n\t\t\tmake(map[string]chan *http.Response)},\n\t\tlog:      out,\n\t\tnode:     node,\n\t\tTimeout:  time.Millisecond * 500,\n\t\tservices: make(map[string]*workers)}\n}\n<commit_msg>trivial language tweak<commit_after>\/\/ Copyright 2016 Afshin Darian. All rights reserved.\n\/\/ Use of this source code is governed by The MIT License\n\/\/ that can be found in the LICENSE file.\n\npackage sleuth\n\nimport (\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/pborman\/uuid\"\n\t\"github.com\/ursiform\/logger\"\n\t\"github.com\/zeromq\/gyre\"\n)\n\ntype listener struct {\n\t*sync.Mutex\n\thandles map[string]chan *http.Response\n}\n\ntype notifier struct {\n\t*sync.Mutex\n\tnotify chan struct{}\n}\n\n\/\/ Client is the peer on the sleuth network that makes requests and, if a\n\/\/ handler has been provided, responds to peer requests.\ntype Client struct {\n\t\/\/ Timeout is the duration to wait before an outstanding request times out.\n\t\/\/ By default, it is set to 500ms.\n\tTimeout time.Duration\n\n\tadditions *notifier\n\thandler   http.Handler\n\tlistener  *listener\n\tlog       *logger.Logger\n\tnode      *gyre.Gyre\n\n\tdirectory map[string]string   \/\/ map[node-name]service-type\n\tservices  map[string]*workers \/\/ map[service-type]service-workers\n}\n\nfunc (c *Client) add(gid, name, node, service, version string) error {\n\tif gid != group {\n\t\tc.log.Debug(\"sleuth: no group header for %s, client-only\", name)\n\t\treturn nil\n\t}\n\t\/\/ Node and service are required. Version is optional.\n\tif len(node) == 0 || len(service) == 0 {\n\t\treturn newError(errAdd, \"failed to add %s node?=%t, type?=%t\",\n\t\t\tname, len(node) > 0, len(service) > 0)\n\t}\n\t\/\/ Associate the node name with its service in the directory.\n\tc.directory[name] = service\n\t\/\/ Create a service workers collection if necessary.\n\tif c.services[service] == nil {\n\t\tc.services[service] = newWorkers()\n\t}\n\t\/\/ Add peer to the service workers.\n\tp := &peer{name: name, node: node, service: service, version: version}\n\tc.services[service].add(p)\n\t\/\/ If necessary, notify the additions channel that a peer has been added.\n\tif c.additions.notify != nil {\n\t\tc.additions.notify <- struct{}{}\n\t}\n\tc.log.Info(\"sleuth: add %s\/%s %s to %s\", service, version, name, group)\n\treturn nil\n}\n\n\/\/ Returns true if it had to block and false if it returns immediately.\nfunc (c *Client) block(services ...string) bool {\n\t\/\/ Block until the required services are available to the client.\n\tc.additions.Lock()\n\tdefer c.additions.Unlock()\n\t\/\/ Even though the client may have just checked to see if services exist,\n\t\/\/ the check is performed here in case there was a delay waiting for the\n\t\/\/ additions mutex to become available.\n\tif c.has(services...) {\n\t\treturn false\n\t}\n\tc.log.Blocked(\"sleuth: waiting for client to find services %s\", services)\n\tc.additions.notify = make(chan struct{})\n\tfor range c.additions.notify {\n\t\tif c.has(services...) {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.additions.notify = nil\n\treturn true\n}\n\n\/\/ Close leaves the sleuth network and stops the Gyre node.\nfunc (c *Client) Close() error {\n\tc.log.Info(\"%s leaving %s...\", c.node.Name(), group)\n\tif err := c.node.Leave(group); err != nil {\n\t\treturn newError(errLeave, err.Error())\n\t}\n\tif err := c.node.Stop(); err != nil {\n\t\tc.log.Warn(\"sleuth: %s %s [%d]\",\n\t\t\tc.node.Name(), err.Error(), warnClose)\n\t}\n\treturn nil\n}\n\nfunc (c *Client) dispatch(payload []byte) error {\n\t\/\/ Returned responses (RECV command) and outstanding requests (REPL command)\n\t\/\/ have these headers, respectively: SLEUTH-V0RECV and SLEUTH-V0REPL\n\tgroupLength := len(group)\n\tdispatchLength := 4\n\theaderLength := groupLength + dispatchLength\n\t\/\/ If the message header does not match the group, bail.\n\tif len(payload) < headerLength || string(payload[0:groupLength]) != group {\n\t\treturn newError(errDispatchHeader, \"bad header\")\n\t}\n\taction := string(payload[groupLength : groupLength+dispatchLength])\n\tswitch action {\n\tcase recv:\n\t\treturn c.receive(payload[headerLength:])\n\tcase repl:\n\t\treturn c.reply(payload[headerLength:])\n\tdefault:\n\t\treturn newError(errDispatchAction, \"bad action: %s\", action)\n\t}\n}\n\n\/\/ Do sends an HTTP request to a service and returns and HTTP response. The URL\n\/\/ for requests needs to use the following format:\n\/\/ \tsleuth:\/\/service-name\/requested-path\n\/\/ For example, a request to the path \/bar?baz=qux of a service called\n\/\/ foo-service would have the URL:\n\/\/ \tsleuth:\/\/foo-service\/bar?baz=qux\nfunc (c *Client) Do(req *http.Request) (*http.Response, error) {\n\thandle := uuid.New()\n\tto := req.URL.Host\n\tif req.URL.Scheme != scheme {\n\t\terr := newError(errScheme,\n\t\t\t\"URL scheme must be \\\"%s\\\" in %s\", scheme, req.URL.String())\n\t\treturn nil, err\n\t}\n\tservices, ok := c.services[to]\n\tif !ok {\n\t\treturn nil, newError(errUnknownService, \"%s is an unknown service\", to)\n\t}\n\tp := services.next()\n\treceiver := c.node.UUID()\n\tpayload, err := marshalRequest(receiver, handle, req)\n\tif err != nil {\n\t\treturn nil, err.(*Error).escalate(errRequest)\n\t}\n\tc.log.Debug(\"sleuth: %s %s:\/\/%s@%s%s\",\n\t\treq.Method, scheme, to, p.name, req.URL.String())\n\tif err = c.node.Whisper(p.node, payload); err != nil {\n\t\treturn nil, newError(errReqWhisper, err.Error())\n\t}\n\tlistener := make(chan *http.Response, 1)\n\tc.listen(handle, listener)\n\tresponse := <-listener\n\tif response != nil {\n\t\treturn response, nil\n\t}\n\treturn nil, newError(errTimeout,\n\t\t\"%s {%s}%s timed out\", req.Method, to, req.URL.String())\n}\n\nfunc (c *Client) has(services ...string) bool {\n\t\/\/ Check to see if required services are already registered.\n\tverified := make(map[string]bool)\n\tavailable := 0\n\tfor _, service := range services {\n\t\tverified[service] = false\n\t}\n\ttotal := len(verified)\n\tfor service := range verified {\n\t\tif workers, ok := c.services[service]; ok && workers.available() {\n\t\t\tverified[service] = true\n\t\t\tavailable += 1\n\t\t}\n\t}\n\treturn available == total\n}\n\nfunc (c *Client) listen(handle string, listener chan *http.Response) {\n\tc.listener.Lock()\n\tdefer c.listener.Unlock()\n\tc.listener.handles[handle] = listener\n\tgo c.timeout(handle)\n}\n\nfunc (c *Client) receive(payload []byte) error {\n\thandle, res, err := unmarshalResponse(payload)\n\tif err != nil {\n\t\treturn err.(*Error).escalate(errRECV)\n\t}\n\tc.listener.Lock()\n\tdefer c.listener.Unlock()\n\tif listener, ok := c.listener.handles[handle]; ok {\n\t\tlistener <- res\n\t\tdelete(c.listener.handles, handle)\n\t} else {\n\t\treturn newError(errRECV, \"unknown handle %s\", handle)\n\t}\n\treturn nil\n}\n\nfunc (c *Client) remove(name string) {\n\tif service, ok := c.directory[name]; ok {\n\t\tremaining, _ := c.services[service].remove(name)\n\t\tif remaining == 0 {\n\t\t\tdelete(c.services, service)\n\t\t}\n\t\tdelete(c.directory, name)\n\t\tc.log.Info(\"sleuth: remove %s (%s) from %s\", service, name, group)\n\t}\n}\n\nfunc (c *Client) reply(payload []byte) error {\n\tdest, req, err := unmarshalRequest(payload)\n\tif err != nil {\n\t\treturn err.(*Error).escalate(errREPL)\n\t}\n\tc.handler.ServeHTTP(newWriter(c.node, dest), req)\n\treturn nil\n}\n\nfunc (c *Client) timeout(handle string) {\n\t<-time.After(c.Timeout)\n\tc.listener.Lock()\n\tdefer c.listener.Unlock()\n\tif listener, ok := c.listener.handles[handle]; ok {\n\t\tlistener <- nil\n\t\tdelete(c.listener.handles, handle)\n\t}\n}\n\n\/\/ WaitFor blocks until the required services are available to the client.\nfunc (c *Client) WaitFor(services ...string) {\n\tif !c.has(services...) {\n\t\tc.block(services...)\n\t}\n}\n\nfunc newClient(node *gyre.Gyre, out *logger.Logger) *Client {\n\treturn &Client{\n\t\tadditions: &notifier{Mutex: new(sync.Mutex)},\n\t\tdirectory: make(map[string]string),\n\t\tlistener: &listener{\n\t\t\tnew(sync.Mutex),\n\t\t\tmake(map[string]chan *http.Response)},\n\t\tlog:      out,\n\t\tnode:     node,\n\t\tTimeout:  time.Millisecond * 500,\n\t\tservices: make(map[string]*workers)}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package cloudsigma provides an http rest client for CloudSigma's cloud api.\npackage cloudsigma\n\nimport (\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n)\n\n\/\/ Client is the CloudSigma http client.\ntype Client struct{}\n\n\/\/ Args holds the arguments for the http request.\ntype Args struct {\n\tResource     string\n\tHeaders      []Header\n\tVerb         string\n\tObjectId     string\n\tGetReqParams map[string]string\n\tActionName   string\n\tBody         interface{}\n\tRequiresAuth bool\n\tUsername     string\n\tPassword     string\n\tLocation     string\n}\n\n\/\/ Header is a name value pair http header.\ntype Header struct {\n\tName  string\n\tValue string\n}\n\n\/\/ CloudSigmaRequest is a local *http.Request, defined because new methods\n\/\/ cannot be defined for types non-local to the current package.  *http.Request\n\/\/ is embedded in a new type, rather than type-aliased because that results in\n\/\/ an incomplete replica.  Using an anonymous field avoids field references.\ntype CloudSigmaRequest struct {\n\t*http.Request\n}\n\nconst (\n\tBaseUrl         = \"https:\/\/%s\/api\/%s\/\"\n\tApiEndpoint     = \"%s.cloudsigma.com\"\n\tApiVersion      = \"2.0\"\n\tUrlResourceList = \"%s\/\"\n\tUrlResource     = \"%s\/%s\"\n\tUrlAction       = \"%s\/%s\/action\/?do=%s\"\n)\n\n\/\/ NewArgs returns an Args object.\nfunc NewArgs() *Args {\n\ta := Args{}\n\treturn &a\n}\n\n\/\/ NewClient returns a Client object.\nfunc NewClient() *Client {\n\tc := Client{}\n\treturn &c\n}\n\n\/\/ buildBaseUrl returns the url on which all requests are built.\nfunc (c *Client) buildBaseUrl(location string) (string, error) {\n\tif location == \"\" {\n\t\treturn \"\", errors.New(\"Location cannot be empty.\")\n\t}\n\tapiEndpoint := fmt.Sprintf(ApiEndpoint, location)\n\treturn fmt.Sprintf(BaseUrl, apiEndpoint, ApiVersion), nil\n}\n\n\/\/ buildResourceUrl returns the url for a specified resource.\nfunc (c *Client) buildResourceUrl(location string, resource string) (*url.URL, error) {\n\tu, err := c.buildBaseUrl(location)\n\tif err != nil {\n\t\treturn &url.URL{}, err\n\t}\n\tu += resource\n\tif resource != \"\" {\n\t\tu += \"\/\"\n\t}\n\tnewUrl, err := url.Parse(u)\n\tif err != nil {\n\t\treturn &url.URL{}, err\n\t}\n\treturn newUrl, nil\n}\n\n\/\/ AddHeader adds a header to the Headers field of an Args object.\nfunc (a *Args) AddHeader(header Header) {\n\ta.Headers = append(a.Headers, header)\n}\n\n\/\/ AddHeaders add Args.Headers to a CloudSigmaRequest object.\nfunc (r *CloudSigmaRequest) AddHeaders(headers []Header) {\n\tfor _, j := range headers {\n\t\tr.Header.Add(j.Name, j.Value)\n\t}\n}\n\n\/\/ Call builds and sends a request, given Args, and returns the http result.\nfunc (c *Client) Call(args Args) ([]byte, error) {\n\treq, err := c.buildRequest(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := c.sendRequest(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}\n\n\/\/ buildRequest creates a http CloudSigmaRequest with the supplied Args.\nfunc (c *Client) buildRequest(args Args) (*CloudSigmaRequest, error) {\n\tu, err := c.buildResourceUrl(args.Location, args.Resource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Add querystring params.\n\tparams := url.Values{}\n\tfor k, v := range args.GetReqParams {\n\t\tparams.Add(k, v)\n\t}\n\tu.RawQuery = params.Encode()\n\n\t\/\/ Build the json body if required.\n\tbodybuf := bytes.NewBuffer([]byte{})\n\tif args.Body != nil {\n\t\tjsonBody, err := json.Marshal(args.Body)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error marshalling body to json.\")\n\t\t\treturn nil, err\n\t\t}\n\t\tbodybuf = bytes.NewBuffer([]byte(jsonBody))\n\t}\n\n\t\/\/ Build the request.\n\tnewreq, err := http.NewRequest(strings.ToUpper(args.Verb), u.String(), bodybuf)\n\treq := CloudSigmaRequest{Request: newreq}\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Build headers list.\n\t\/\/ TODO: this should be optionally xml - json is default.\n\targs.AddHeader(Header{\"Content-Type\", \"application\/json\"})\n\n\t\/\/ Add auth if required.\n\tif args.RequiresAuth {\n\t\targs.AddHeader(c.GetHttpBasicAuthHeader(args.Username, args.Password))\n\t}\n\n\t\/\/ Add headers to request.\n\treq.AddHeaders(args.Headers)\n\treturn &req, nil\n}\n\n\/\/ sendRequest sends the given http CloudSigmaRequest and returns the result.\nfunc (c *Client) sendRequest(req *CloudSigmaRequest) ([]byte, error) {\n\tclient := http.Client{}\n\tresp, err := client.Do(req.Request)\n\tif err != nil {\n\t\tlog.Println(\"Error in client.Do.\")\n\t\tlog.Println(err)\n\t\treturn []byte{}, err\n\t}\n\tdefer resp.Body.Close()\n\t\/\/ TODO: improve this.\n\tif resp.StatusCode != 200 {\n\t\treturn []byte{}, errors.New(resp.Status)\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Println(\"Error in ioutil.ReadAll.\")\n\t\treturn []byte{}, err\n\t}\n\treturn body, nil\n}\n\n\/\/ GetHttpBasicAuthHeader returns a base 64 encoded auth header,\n\/\/ given a username and password.\nfunc (c *Client) GetHttpBasicAuthHeader(userEmail string, password string) Header {\n\t\/\/ Authorization: Basic base64_encode(useremail:password)\n\theader := \"Authorization\"\n\tvalueFormat := \"Basic %s\"\n\tcredsFormat := \"%s:%s\"\n\tcredsData := []byte(fmt.Sprintf(credsFormat, userEmail, password))\n\tcredsBase64 := base64.StdEncoding.EncodeToString(credsData)\n\tvalue := fmt.Sprintf(valueFormat, credsBase64)\n\treturn Header{header, value}\n}\n<commit_msg>Improved error message.<commit_after>\/\/ Package cloudsigma provides an http rest client for CloudSigma's cloud api.\npackage cloudsigma\n\nimport (\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n)\n\n\/\/ Client is the CloudSigma http client.\ntype Client struct{}\n\n\/\/ Args holds the arguments for the http request.\ntype Args struct {\n\tResource     string\n\tHeaders      []Header\n\tVerb         string\n\tObjectId     string\n\tGetReqParams map[string]string\n\tActionName   string\n\tBody         interface{}\n\tRequiresAuth bool\n\tUsername     string\n\tPassword     string\n\tLocation     string\n}\n\n\/\/ Header is a name value pair http header.\ntype Header struct {\n\tName  string\n\tValue string\n}\n\n\/\/ CloudSigmaRequest is a local *http.Request, defined because new methods\n\/\/ cannot be defined for types non-local to the current package.  *http.Request\n\/\/ is embedded in a new type, rather than type-aliased because that results in\n\/\/ an incomplete replica.  Using an anonymous field avoids field references.\ntype CloudSigmaRequest struct {\n\t*http.Request\n}\n\nconst (\n\tBaseUrl         = \"https:\/\/%s\/api\/%s\/\"\n\tApiEndpoint     = \"%s.cloudsigma.com\"\n\tApiVersion      = \"2.0\"\n\tUrlResourceList = \"%s\/\"\n\tUrlResource     = \"%s\/%s\"\n\tUrlAction       = \"%s\/%s\/action\/?do=%s\"\n)\n\n\/\/ NewArgs returns an Args object.\nfunc NewArgs() *Args {\n\ta := Args{}\n\treturn &a\n}\n\n\/\/ NewClient returns a Client object.\nfunc NewClient() *Client {\n\tc := Client{}\n\treturn &c\n}\n\n\/\/ buildBaseUrl returns the url on which all requests are built.\nfunc (c *Client) buildBaseUrl(location string) (string, error) {\n\tif location == \"\" {\n\t\treturn \"\", errors.New(\"Service location not set.  Use command: set config location\")\n\t}\n\tapiEndpoint := fmt.Sprintf(ApiEndpoint, location)\n\treturn fmt.Sprintf(BaseUrl, apiEndpoint, ApiVersion), nil\n}\n\n\/\/ buildResourceUrl returns the url for a specified resource.\nfunc (c *Client) buildResourceUrl(location string, resource string) (*url.URL, error) {\n\tu, err := c.buildBaseUrl(location)\n\tif err != nil {\n\t\treturn &url.URL{}, err\n\t}\n\tu += resource\n\tif resource != \"\" {\n\t\tu += \"\/\"\n\t}\n\tnewUrl, err := url.Parse(u)\n\tif err != nil {\n\t\treturn &url.URL{}, err\n\t}\n\treturn newUrl, nil\n}\n\n\/\/ AddHeader adds a header to the Headers field of an Args object.\nfunc (a *Args) AddHeader(header Header) {\n\ta.Headers = append(a.Headers, header)\n}\n\n\/\/ AddHeaders add Args.Headers to a CloudSigmaRequest object.\nfunc (r *CloudSigmaRequest) AddHeaders(headers []Header) {\n\tfor _, j := range headers {\n\t\tr.Header.Add(j.Name, j.Value)\n\t}\n}\n\n\/\/ Call builds and sends a request, given Args, and returns the http result.\nfunc (c *Client) Call(args Args) ([]byte, error) {\n\treq, err := c.buildRequest(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := c.sendRequest(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}\n\n\/\/ buildRequest creates a http CloudSigmaRequest with the supplied Args.\nfunc (c *Client) buildRequest(args Args) (*CloudSigmaRequest, error) {\n\tu, err := c.buildResourceUrl(args.Location, args.Resource)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Add querystring params.\n\tparams := url.Values{}\n\tfor k, v := range args.GetReqParams {\n\t\tparams.Add(k, v)\n\t}\n\tu.RawQuery = params.Encode()\n\n\t\/\/ Build the json body if required.\n\tbodybuf := bytes.NewBuffer([]byte{})\n\tif args.Body != nil {\n\t\tjsonBody, err := json.Marshal(args.Body)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error marshalling body to json.\")\n\t\t\treturn nil, err\n\t\t}\n\t\tbodybuf = bytes.NewBuffer([]byte(jsonBody))\n\t}\n\n\t\/\/ Build the request.\n\tnewreq, err := http.NewRequest(strings.ToUpper(args.Verb), u.String(), bodybuf)\n\treq := CloudSigmaRequest{Request: newreq}\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Build headers list.\n\t\/\/ TODO: this should be optionally xml - json is default.\n\targs.AddHeader(Header{\"Content-Type\", \"application\/json\"})\n\n\t\/\/ Add auth if required.\n\tif args.RequiresAuth {\n\t\targs.AddHeader(c.GetHttpBasicAuthHeader(args.Username, args.Password))\n\t}\n\n\t\/\/ Add headers to request.\n\treq.AddHeaders(args.Headers)\n\treturn &req, nil\n}\n\n\/\/ sendRequest sends the given http CloudSigmaRequest and returns the result.\nfunc (c *Client) sendRequest(req *CloudSigmaRequest) ([]byte, error) {\n\tclient := http.Client{}\n\tresp, err := client.Do(req.Request)\n\tif err != nil {\n\t\tlog.Println(\"Error in client.Do.\")\n\t\tlog.Println(err)\n\t\treturn []byte{}, err\n\t}\n\tdefer resp.Body.Close()\n\t\/\/ TODO: improve this.\n\tif resp.StatusCode != 200 {\n\t\treturn []byte{}, errors.New(resp.Status)\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Println(\"Error in ioutil.ReadAll.\")\n\t\treturn []byte{}, err\n\t}\n\treturn body, nil\n}\n\n\/\/ GetHttpBasicAuthHeader returns a base 64 encoded auth header,\n\/\/ given a username and password.\nfunc (c *Client) GetHttpBasicAuthHeader(userEmail string, password string) Header {\n\t\/\/ Authorization: Basic base64_encode(useremail:password)\n\theader := \"Authorization\"\n\tvalueFormat := \"Basic %s\"\n\tcredsFormat := \"%s:%s\"\n\tcredsData := []byte(fmt.Sprintf(credsFormat, userEmail, password))\n\tcredsBase64 := base64.StdEncoding.EncodeToString(credsData)\n\tvalue := fmt.Sprintf(valueFormat, credsBase64)\n\treturn Header{header, value}\n}\n<|endoftext|>"}
{"text":"<commit_before>package throttled\n\nimport (\n\t\"net\/http\"\n\t\"sync\"\n)\n\nvar (\n\t\/\/ DefaultDroppedHandler handles the dropped requests that were denied access because\n\t\/\/ of a throttler. By default, returns a 429 status code with a\n\t\/\/ generic message.\n\tDefaultDroppedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.Error(w, \"rate limit exceeded\", 429)\n\t})\n\n\t\/\/ Error is the function to call when an error occurs on a throttled handler.\n\t\/\/ By default, returns a 500 status code with a generic message.\n\tError = func(w http.ResponseWriter, r *http.Request, err error) {\n\t\thttp.Error(w, \"internal error\", http.StatusInternalServerError)\n\t}\n)\n\n\/\/ The Limiter interface defines the methods required to control access to a\n\/\/ throttled handler.\ntype Limiter interface {\n\tStart()\n\tLimit(http.ResponseWriter, *http.Request) (<-chan bool, error)\n}\n\n\/\/ Custom creates a Throttler using the provided Limiter implementation.\nfunc Custom(l Limiter) *Throttler {\n\treturn &Throttler{\n\t\tlimiter: l,\n\t}\n}\n\n\/\/ A Throttler controls access to HTTP handlers using a Limiter.\ntype Throttler struct {\n\t\/\/ DroppedHandler is called if the request is disallowed. If it is nil,\n\t\/\/ the DefaultDroppedHandler variable is used.\n\tDroppedHandler http.Handler\n\n\tlimiter Limiter\n\t\/\/ The mutex protects the started flag\n\tmu      sync.Mutex\n\tstarted bool\n}\n\n\/\/ Throttle wraps a HTTP handler so that its access is controlled by\n\/\/ the Throttler. It returns the Handler with the throttling logic.\nfunc (t *Throttler) Throttle(h http.Handler) http.Handler {\n\tdroph := t.start()\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tch, err := t.limiter.Limit(w, r)\n\t\tif err != nil {\n\t\t\tError(w, r, err)\n\t\t\treturn\n\t\t}\n\t\tok := <-ch\n\t\tif ok {\n\t\t\th.ServeHTTP(w, r)\n\t\t} else {\n\t\t\tdroph.ServeHTTP(w, r)\n\t\t}\n\t})\n}\n\n\/\/ start starts the throttling and returns the effective dropped handler to\n\/\/ use for requests that were denied access.\nfunc (t *Throttler) start() http.Handler {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\t\/\/ Get the effective dropped handler\n\tdrop := t.DroppedHandler\n\tif drop == nil {\n\t\tdrop = DefaultDroppedHandler\n\t}\n\tif !t.started {\n\t\tt.limiter.Start()\n\t\tt.started = true\n\t}\n\treturn drop\n}\n<commit_msg>doc fix<commit_after>package throttled\n\nimport (\n\t\"net\/http\"\n\t\"sync\"\n)\n\nvar (\n\t\/\/ DefaultDroppedHandler handles the dropped requests that were denied access because\n\t\/\/ of a throttler. By default, returns a 429 status code with a\n\t\/\/ generic message.\n\tDefaultDroppedHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.Error(w, \"limit exceeded\", 429)\n\t})\n\n\t\/\/ Error is the function to call when an error occurs on a throttled handler.\n\t\/\/ By default, returns a 500 status code with a generic message.\n\tError = func(w http.ResponseWriter, r *http.Request, err error) {\n\t\thttp.Error(w, \"internal error\", http.StatusInternalServerError)\n\t}\n)\n\n\/\/ The Limiter interface defines the methods required to control access to a\n\/\/ throttled handler.\ntype Limiter interface {\n\tStart()\n\tLimit(http.ResponseWriter, *http.Request) (<-chan bool, error)\n}\n\n\/\/ Custom creates a Throttler using the provided Limiter implementation.\nfunc Custom(l Limiter) *Throttler {\n\treturn &Throttler{\n\t\tlimiter: l,\n\t}\n}\n\n\/\/ A Throttler controls access to HTTP handlers using a Limiter.\ntype Throttler struct {\n\t\/\/ DroppedHandler is called if the request is disallowed. If it is nil,\n\t\/\/ the DefaultDroppedHandler variable is used.\n\tDroppedHandler http.Handler\n\n\tlimiter Limiter\n\t\/\/ The mutex protects the started flag\n\tmu      sync.Mutex\n\tstarted bool\n}\n\n\/\/ Throttle wraps a HTTP handler so that its access is controlled by\n\/\/ the Throttler. It returns the Handler with the throttling logic.\nfunc (t *Throttler) Throttle(h http.Handler) http.Handler {\n\tdroph := t.start()\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tch, err := t.limiter.Limit(w, r)\n\t\tif err != nil {\n\t\t\tError(w, r, err)\n\t\t\treturn\n\t\t}\n\t\tok := <-ch\n\t\tif ok {\n\t\t\th.ServeHTTP(w, r)\n\t\t} else {\n\t\t\tdroph.ServeHTTP(w, r)\n\t\t}\n\t})\n}\n\n\/\/ start starts the throttling and returns the effective dropped handler to\n\/\/ use for requests that were denied access.\nfunc (t *Throttler) start() http.Handler {\n\tt.mu.Lock()\n\tdefer t.mu.Unlock()\n\t\/\/ Get the effective dropped handler\n\tdrop := t.DroppedHandler\n\tif drop == nil {\n\t\tdrop = DefaultDroppedHandler\n\t}\n\tif !t.started {\n\t\tt.limiter.Start()\n\t\tt.started = true\n\t}\n\treturn drop\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"appengine\"\n\t\"appengine\/datastore\"\n)\n\ntype Link struct {\n\tTitle       string\n\tUrl         string\n\tDescription string `datastore:\",noindex\"` \/\/ Markdown\n\tTags        []string\n\tPosted      time.Time\n\tCreated     time.Time\n\tModified    time.Time\n}\n\nfunc NewLink(title string, url string, desc string, tags []string, when time.Time) *Link {\n\te := new(Link)\n\n\t\/\/ User supplied content\n\te.Title = title\n\te.Url = url\n\te.Description = desc\n\te.Tags = tags\n\te.Posted = when\n\n\t\/\/ Computer generated content\n\te.Created = time.Now()\n\te.Modified = time.Now()\n\n\treturn e\n}\n\nfunc (l *Link) TagString() string {\n\ttags := []string{}\n\tfor _, t := range l.Tags {\n\t\ttags = append(tags, fmt.Sprintf(\"#%s\", t))\n\t}\n\n\treturn strings.Join(tags, \" \")\n}\n\nfunc (e *Link) Save(c appengine.Context) error {\n\tk := datastore.NewKey(c, \"Link\", e.Url, 0, nil)\n\tk2, err := datastore.Put(c, k, e)\n\tif err == nil {\n\t\tc.Infof(\"Wrote %+v\", e)\n\t\tc.Infof(\"Old key: %+v; New Key: %+v\", k, k2)\n\t} else {\n\t\tc.Warningf(\"Error writing entry: %v\", e)\n\t}\n\treturn err\n}\n\nfunc AllLinks(c appengine.Context) (*[]Link, error) {\n\treturn Links(c, -1, true)\n}\n\nfunc Links(c appengine.Context, limit int, recentFirst bool) (*[]Link, error) {\n\tq := datastore.NewQuery(\"Link\").Order(\"-Posted\")\n\n\tif recentFirst {\n\t\tq = q.Order(\"-Datetime\")\n\t} else {\n\t\tq = q.Order(\"Datetime\")\n\t}\n\n\tif limit > 0 {\n\t\tq = q.Limit(limit)\n\t}\n\n\tlinks := new([]Link)\n\t_, err := q.GetAll(c, links)\n\treturn links, err\n}\n<commit_msg>whoops<commit_after>package models\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"appengine\"\n\t\"appengine\/datastore\"\n)\n\ntype Link struct {\n\tTitle       string\n\tUrl         string\n\tDescription string `datastore:\",noindex\"` \/\/ Markdown\n\tTags        []string\n\tPosted      time.Time\n\tCreated     time.Time\n\tModified    time.Time\n}\n\nfunc NewLink(title string, url string, desc string, tags []string, when time.Time) *Link {\n\te := new(Link)\n\n\t\/\/ User supplied content\n\te.Title = title\n\te.Url = url\n\te.Description = desc\n\te.Tags = tags\n\te.Posted = when\n\n\t\/\/ Computer generated content\n\te.Created = time.Now()\n\te.Modified = time.Now()\n\n\treturn e\n}\n\nfunc (l *Link) TagString() string {\n\ttags := []string{}\n\tfor _, t := range l.Tags {\n\t\ttags = append(tags, fmt.Sprintf(\"#%s\", t))\n\t}\n\n\treturn strings.Join(tags, \" \")\n}\n\nfunc (e *Link) Save(c appengine.Context) error {\n\tk := datastore.NewKey(c, \"Link\", e.Url, 0, nil)\n\tk2, err := datastore.Put(c, k, e)\n\tif err == nil {\n\t\tc.Infof(\"Wrote %+v\", e)\n\t\tc.Infof(\"Old key: %+v; New Key: %+v\", k, k2)\n\t} else {\n\t\tc.Warningf(\"Error writing entry: %v\", e)\n\t}\n\treturn err\n}\n\nfunc AllLinks(c appengine.Context) (*[]Link, error) {\n\treturn Links(c, -1, true)\n}\n\nfunc Links(c appengine.Context, limit int, recentFirst bool) (*[]Link, error) {\n\tq := datastore.NewQuery(\"Link\")\n\n\tif recentFirst {\n\t\tq = q.Order(\"-Posted\")\n\t} else {\n\t\tq = q.Order(\"Posted\")\n\t}\n\n\tif limit > 0 {\n\t\tq = q.Limit(limit)\n\t}\n\n\tlinks := new([]Link)\n\t_, err := q.GetAll(c, links)\n\treturn links, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the  specific language governing permissions and\nlimitations under the License.\n*\/\npackage models\n\nimport (\n\t\"fmt\"\n\t\"github.com\/skyrings\/skyring-common\/monitoring\"\n\t\"github.com\/skyrings\/skyring-common\/tools\/uuid\"\n\t\"time\"\n)\n\ntype AddStorageNodeRequest struct {\n\tHostname       string `json:\"hostname\"`\n\tSshFingerprint string `json:\"sshfingerprint\"`\n\tUser           string `json:\"user\"`\n\tPassword       string `json:\"password\"`\n\tSshPort        int    `json:\"sshport\"`\n}\n\ntype AddClusterRequest struct {\n\tName               string              `json:\"name\"`\n\tCompatVersion      string              `json:\"compat_version\"`\n\tType               string              `json:\"type\"`\n\tWorkLoad           string              `json:\"workload\"`\n\tTags               []string            `json:\"tags\"`\n\tOptions            map[string]string   `json:\"options\"`\n\tOpenStackServices  []string            `json:\"openstackservices\"`\n\tNodes              []ClusterNode       `json:\"nodes\"`\n\tNetworks           ClusterNetworks     `json:\"networks\"`\n\tMonitoringPlugins  []monitoring.Plugin `json:\"monitoringplugins\"`\n\tMonitoringInterval int                 `json:\"monitoringinterval\"`\n}\n\ntype ClusterNode struct {\n\tNodeId   string              `json:\"nodeid\"`\n\tNodeType []string            `json:\"nodetype\"`\n\tDevices  []ClusterNodeDevice `json:\"disks\"`\n\tOptions  map[string]string   `json:\"options\"`\n}\n\ntype ClusterNodeDevice struct {\n\tName    string            `json:\"name\"`\n\tFSType  string            `json:\"fstype\"`\n\tOptions map[string]string `json:\"options\"`\n}\n\ntype AddStorageRequest struct {\n\tName             string                  `json:\"name\"`\n\tType             string                  `json:\"type\"`\n\tTags             []string                `json:\"tags\"`\n\tSize             string                  `json:\"size\"`\n\tReplicas         int                     `json:\"replicas\"`\n\tProfile          string                  `json:\"profile\"`\n\tSnapshotsEnabled bool                    `json:\"snapshots_enabled\"`\n\tSnapshotSchedule SnapshotScheduleRequest `json:\"snapshot_schedule\"`\n\tQuotaEnabled     bool                    `json:\"quota_enabled\"`\n\tQuotaParams      map[string]string       `json:\"quota_params\"`\n\tOptions          map[string]string       `json:\"options\"`\n}\n\ntype SnapshotScheduleRequest struct {\n\tRecurrence    string   `json:\"recurrence\"`\n\tInterval      int      `json:\"interval\"`\n\tExecutionTime string   `json:\"execution_time\"`\n\tDays          []string `json:\"days\"`\n\tStartFrom     string   `json:\"start_from\"`\n\tEndBy         string   `json:\"endby\"`\n}\n\ntype Nodes []Node\n\ntype NodeEvent struct {\n\tTimestamp time.Time         `json:\"timestamp\"`\n\tNode      string            `json:\"node\"`\n\tTag       string            `json:\"tag\"`\n\tTags      map[string]string `json:\"tags\"`\n\tMessage   string            `json:\"message\"`\n\tSeverity  string            `json:\"severity\"`\n}\n\ntype Event struct {\n\tEventId   uuid.UUID         `json:\"event_id\"`\n\tClusterId uuid.UUID         `json:\"cluster_id\"`\n\tNodeId    uuid.UUID         `json:\"node_id\"`\n\tTimestamp time.Time         `json:\"timestamp\"`\n\tTag       string            `json:\"tag\"`\n\tTags      map[string]string `json:\"tags\"`\n\tMessage   string            `json:\"message\"`\n\tSeverity  string            `json:\"severity\"`\n}\n\ntype QueryOps struct {\n\tSort     bool\n\tBatch    int\n\tIter     bool\n\tLimit    int\n\tPrefetch float64\n\tSelect   interface{}\n\tSkip     bool\n\tDistinct bool\n}\n\nconst (\n\tDEFAULT_SSH_PORT                = 22\n\tDEFAULT_FS_TYPE                 = \"xfs\"\n\tREQUEST_SIZE_LIMIT              = 1048576\n\tCOLL_NAME_STORAGE               = \"storage\"\n\tCOLL_NAME_NODE_EVENTS           = \"node_events\"\n\tCOLL_NAME_STORAGE_NODES         = \"storage_nodes\"\n\tCOLL_NAME_STORAGE_CLUSTERS      = \"storage_clusters\"\n\tCOLL_NAME_STORAGE_LOGICAL_UNITS = \"storage_logical_units\"\n\tCOLL_NAME_TASKS                 = \"tasks\"\n\tCOLL_NAME_SESSION_STORE         = \"skyring_session_store\"\n\tCOLL_NAME_USER                  = \"skyringusers\"\n\tCOLL_NAME_STORAGE_PROFILE       = \"storage_profile\"\n)\n\ntype Clusters []Cluster\ntype Storages []Storage\n\ntype UnmanagedNode struct {\n\tName            string `json:\"name\"`\n\tSaltFingerprint string `json:\"saltfingerprint\"`\n}\n\ntype UnmanagedNodes []UnmanagedNode\n\ntype ClusterStatus int\n\n\/\/ Status values for the cluster\nconst (\n\tCLUSTER_STATUS_OK = iota\n\tCLUSTER_STATUS_WARN\n\tCLUSTER_STATUS_ERROR\n\tCLUSTER_STATUS_UNKNOWN\n)\n\nvar ClusterStatuses = [...]string{\n\t\"ok\",\n\t\"warning\",\n\t\"error\",\n\t\"unknown\",\n}\n\ntype ClusterState int\n\n\/\/ State values for cluster\nconst (\n\tCLUSTER_STATE_CREATING = iota\n\tCLUSTER_STATE_FAILED\n\tCLUSTER_STATE_ACTIVE\n\tCLUSTER_STATE_UNMANAGED\n)\n\nvar ClusterStates = [...]string{\n\t\"creating\",\n\t\"failed\",\n\t\"active\",\n\t\"unmanaged\",\n}\n\nfunc (s ClusterState) String() string { return ClusterStates[s] }\n\n\/\/ Storage logical unit types\nconst (\n\tCEPH_OSD = 1 + iota\n)\n\nvar StorageLogicalUnitTypes = [...]string{\n\t\"osd\",\n}\n\nconst (\n\tSTATUS_UP   = \"up\"\n\tSTATUS_DOWN = \"down\"\n\tSTATUS_OK   = \"ok\"\n\tSTATUS_WARN = \"warning\"\n\tSTATUS_ERR  = \"error\"\n)\n\nfunc (c ClusterStatus) String() string { return ClusterStatuses[c-1] }\n\ntype AsyncResponse struct {\n\tTaskId uuid.UUID `json:\"taskid\"`\n}\n\nfunc (s Status) String() string {\n\treturn fmt.Sprintf(\"%s %s\", s.Timestamp, s.Message)\n}\n\ntype TaskStatus int\n\nconst (\n\tTASK_STATUS_NONE = iota\n\tTASK_STATUS_SUCCESS\n\tTASK_STATUS_TIMED_OUT\n\tTASK_STATUS_FAILURE\n)\n\nvar TaskStatuses = [...]string{\n\t\"none\",\n\t\"success\",\n\t\"timedout\",\n\t\"failed\",\n}\n\nfunc (t TaskStatus) String() string { return TaskStatuses[t] }\n\ntype DiskType int\n\nconst (\n\tNONE = iota\n\tSAS\n\tSSD\n)\n\nvar DiskTypes = [...]string{\n\t\"none\",\n\t\"sas\",\n\t\"ssd\",\n}\n\nfunc (d DiskType) String() string { return DiskTypes[d] }\n\nconst (\n\tDefaultProfile1 = \"sas\"\n\tDefaultProfile2 = \"ssd\"\n\tDefaultProfile3 = \"general\"\n\tDefaultPriority = 100\n)\n\ntype NodeState int\n\nconst (\n\tNODE_STATE_UNACCEPTED = iota\n\tNODE_STATE_INITIALIZING\n\tNODE_STATE_ACTIVE\n\tNODE_STATE_FAILED\n)\n\nvar NodeStates = [...]string{\n\t\"unaccepted\",\n\t\"initializing\",\n\t\"active\",\n\t\"failed\",\n}\n\nfunc (s NodeState) String() string { return NodeStates[s] }\n<commit_msg>Define constant for maximum no of tasks per page limit<commit_after>\/*Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the  specific language governing permissions and\nlimitations under the License.\n*\/\npackage models\n\nimport (\n\t\"fmt\"\n\t\"github.com\/skyrings\/skyring-common\/monitoring\"\n\t\"github.com\/skyrings\/skyring-common\/tools\/uuid\"\n\t\"time\"\n)\n\ntype AddStorageNodeRequest struct {\n\tHostname       string `json:\"hostname\"`\n\tSshFingerprint string `json:\"sshfingerprint\"`\n\tUser           string `json:\"user\"`\n\tPassword       string `json:\"password\"`\n\tSshPort        int    `json:\"sshport\"`\n}\n\ntype AddClusterRequest struct {\n\tName               string              `json:\"name\"`\n\tCompatVersion      string              `json:\"compat_version\"`\n\tType               string              `json:\"type\"`\n\tWorkLoad           string              `json:\"workload\"`\n\tTags               []string            `json:\"tags\"`\n\tOptions            map[string]string   `json:\"options\"`\n\tOpenStackServices  []string            `json:\"openstackservices\"`\n\tNodes              []ClusterNode       `json:\"nodes\"`\n\tNetworks           ClusterNetworks     `json:\"networks\"`\n\tMonitoringPlugins  []monitoring.Plugin `json:\"monitoringplugins\"`\n\tMonitoringInterval int                 `json:\"monitoringinterval\"`\n}\n\ntype ClusterNode struct {\n\tNodeId   string              `json:\"nodeid\"`\n\tNodeType []string            `json:\"nodetype\"`\n\tDevices  []ClusterNodeDevice `json:\"disks\"`\n\tOptions  map[string]string   `json:\"options\"`\n}\n\ntype ClusterNodeDevice struct {\n\tName    string            `json:\"name\"`\n\tFSType  string            `json:\"fstype\"`\n\tOptions map[string]string `json:\"options\"`\n}\n\ntype AddStorageRequest struct {\n\tName             string                  `json:\"name\"`\n\tType             string                  `json:\"type\"`\n\tTags             []string                `json:\"tags\"`\n\tSize             string                  `json:\"size\"`\n\tReplicas         int                     `json:\"replicas\"`\n\tProfile          string                  `json:\"profile\"`\n\tSnapshotsEnabled bool                    `json:\"snapshots_enabled\"`\n\tSnapshotSchedule SnapshotScheduleRequest `json:\"snapshot_schedule\"`\n\tQuotaEnabled     bool                    `json:\"quota_enabled\"`\n\tQuotaParams      map[string]string       `json:\"quota_params\"`\n\tOptions          map[string]string       `json:\"options\"`\n}\n\ntype SnapshotScheduleRequest struct {\n\tRecurrence    string   `json:\"recurrence\"`\n\tInterval      int      `json:\"interval\"`\n\tExecutionTime string   `json:\"execution_time\"`\n\tDays          []string `json:\"days\"`\n\tStartFrom     string   `json:\"start_from\"`\n\tEndBy         string   `json:\"endby\"`\n}\n\ntype Nodes []Node\n\ntype NodeEvent struct {\n\tTimestamp time.Time         `json:\"timestamp\"`\n\tNode      string            `json:\"node\"`\n\tTag       string            `json:\"tag\"`\n\tTags      map[string]string `json:\"tags\"`\n\tMessage   string            `json:\"message\"`\n\tSeverity  string            `json:\"severity\"`\n}\n\ntype Event struct {\n\tEventId   uuid.UUID         `json:\"event_id\"`\n\tClusterId uuid.UUID         `json:\"cluster_id\"`\n\tNodeId    uuid.UUID         `json:\"node_id\"`\n\tTimestamp time.Time         `json:\"timestamp\"`\n\tTag       string            `json:\"tag\"`\n\tTags      map[string]string `json:\"tags\"`\n\tMessage   string            `json:\"message\"`\n\tSeverity  string            `json:\"severity\"`\n}\n\ntype QueryOps struct {\n\tSort     bool\n\tBatch    int\n\tIter     bool\n\tLimit    int\n\tPrefetch float64\n\tSelect   interface{}\n\tSkip     bool\n\tDistinct bool\n}\n\nconst (\n\tDEFAULT_SSH_PORT   = 22\n\tDEFAULT_FS_TYPE    = \"xfs\"\n\tREQUEST_SIZE_LIMIT = 1048576\n\n\tCOLL_NAME_STORAGE               = \"storage\"\n\tCOLL_NAME_NODE_EVENTS           = \"node_events\"\n\tCOLL_NAME_STORAGE_NODES         = \"storage_nodes\"\n\tCOLL_NAME_STORAGE_CLUSTERS      = \"storage_clusters\"\n\tCOLL_NAME_STORAGE_LOGICAL_UNITS = \"storage_logical_units\"\n\tCOLL_NAME_TASKS                 = \"tasks\"\n\tCOLL_NAME_SESSION_STORE         = \"skyring_session_store\"\n\tCOLL_NAME_USER                  = \"skyringusers\"\n\tCOLL_NAME_STORAGE_PROFILE       = \"storage_profile\"\n\n\tTASKS_PER_PAGE = 100\n)\n\ntype Clusters []Cluster\ntype Storages []Storage\n\ntype UnmanagedNode struct {\n\tName            string `json:\"name\"`\n\tSaltFingerprint string `json:\"saltfingerprint\"`\n}\n\ntype UnmanagedNodes []UnmanagedNode\n\ntype ClusterStatus int\n\n\/\/ Status values for the cluster\nconst (\n\tCLUSTER_STATUS_OK = iota\n\tCLUSTER_STATUS_WARN\n\tCLUSTER_STATUS_ERROR\n\tCLUSTER_STATUS_UNKNOWN\n)\n\nvar ClusterStatuses = [...]string{\n\t\"ok\",\n\t\"warning\",\n\t\"error\",\n\t\"unknown\",\n}\n\ntype ClusterState int\n\n\/\/ State values for cluster\nconst (\n\tCLUSTER_STATE_CREATING = iota\n\tCLUSTER_STATE_FAILED\n\tCLUSTER_STATE_ACTIVE\n\tCLUSTER_STATE_UNMANAGED\n)\n\nvar ClusterStates = [...]string{\n\t\"creating\",\n\t\"failed\",\n\t\"active\",\n\t\"unmanaged\",\n}\n\nfunc (s ClusterState) String() string { return ClusterStates[s] }\n\n\/\/ Storage logical unit types\nconst (\n\tCEPH_OSD = 1 + iota\n)\n\nvar StorageLogicalUnitTypes = [...]string{\n\t\"osd\",\n}\n\nconst (\n\tSTATUS_UP   = \"up\"\n\tSTATUS_DOWN = \"down\"\n\tSTATUS_OK   = \"ok\"\n\tSTATUS_WARN = \"warning\"\n\tSTATUS_ERR  = \"error\"\n)\n\nfunc (c ClusterStatus) String() string { return ClusterStatuses[c-1] }\n\ntype AsyncResponse struct {\n\tTaskId uuid.UUID `json:\"taskid\"`\n}\n\nfunc (s Status) String() string {\n\treturn fmt.Sprintf(\"%s %s\", s.Timestamp, s.Message)\n}\n\ntype TaskStatus int\n\nconst (\n\tTASK_STATUS_NONE = iota\n\tTASK_STATUS_SUCCESS\n\tTASK_STATUS_TIMED_OUT\n\tTASK_STATUS_FAILURE\n)\n\nvar TaskStatuses = [...]string{\n\t\"none\",\n\t\"success\",\n\t\"timedout\",\n\t\"failed\",\n}\n\nfunc (t TaskStatus) String() string { return TaskStatuses[t] }\n\ntype DiskType int\n\nconst (\n\tNONE = iota\n\tSAS\n\tSSD\n)\n\nvar DiskTypes = [...]string{\n\t\"none\",\n\t\"sas\",\n\t\"ssd\",\n}\n\nfunc (d DiskType) String() string { return DiskTypes[d] }\n\nconst (\n\tDefaultProfile1 = \"sas\"\n\tDefaultProfile2 = \"ssd\"\n\tDefaultProfile3 = \"general\"\n\tDefaultPriority = 100\n)\n\ntype NodeState int\n\nconst (\n\tNODE_STATE_UNACCEPTED = iota\n\tNODE_STATE_INITIALIZING\n\tNODE_STATE_ACTIVE\n\tNODE_STATE_FAILED\n)\n\nvar NodeStates = [...]string{\n\t\"unaccepted\",\n\t\"initializing\",\n\t\"active\",\n\t\"failed\",\n}\n\nfunc (s NodeState) String() string { return NodeStates[s] }\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Minio Client (C) 2014, 2015 Minio, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"runtime\"\n\t\"sync\"\n\n\t\"github.com\/minio\/cli\"\n\t\"github.com\/minio\/mc\/pkg\/console\"\n\t\"github.com\/minio\/mc\/pkg\/countlock\"\n\t\"github.com\/minio\/minio\/pkg\/iodine\"\n)\n\n\/\/ doCopy - Copy a singe file from source to destination\nfunc doCopy(sourceURL string, sourceConfig *hostConfig, targetURL string, targetConfig *hostConfig, bar *barSend) error {\n\treader, length, err := getSource(sourceURL, sourceConfig)\n\tif err != nil {\n\t\tif !globalQuietFlag {\n\t\t\tbar.ErrorGet(int64(length))\n\t\t}\n\t\treturn iodine.New(err, nil)\n\t}\n\tdefer reader.Close()\n\n\tvar newReader io.Reader\n\tswitch globalQuietFlag {\n\tcase true:\n\t\tconsole.Infoln(fmt.Sprintf(\"‘%s’ -> ‘%s’\", sourceURL, targetURL))\n\t\tnewReader = reader\n\tdefault:\n\t\t\/\/ set up progress\n\t\tnewReader = bar.NewProxyReader(reader)\n\t}\n\n\terr = putTarget(targetURL, targetConfig, length, newReader)\n\tif err != nil {\n\t\tif !globalQuietFlag {\n\t\t\tbar.ErrorPut(int64(length))\n\t\t}\n\t\treturn iodine.New(err, nil)\n\t}\n\treturn nil\n}\n\n\/\/ args2URLs extracts source and target URLs from command-line args.\nfunc args2URLs(args cli.Args) ([]string, error) {\n\tconfig, err := getMcConfig()\n\tif err != nil {\n\t\treturn nil, iodine.New(err, nil)\n\t}\n\t\/\/ Convert arguments to URLs: expand alias, fix format...\n\tURLs, err := getExpandedURLs(args, config.Aliases)\n\tif err != nil {\n\t\treturn nil, iodine.New(err, nil)\n\t}\n\treturn URLs, nil\n}\n\nfunc doCopyInRoutine(cpurls *cpURLs, bar *barSend, cpQueue chan bool, errCh chan error, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tsrcConfig, err := getHostConfig(cpurls.SourceContent.Name)\n\tif err != nil {\n\t\terrCh <- err\n\t\treturn\n\t}\n\ttgtConfig, err := getHostConfig(cpurls.TargetContent.Name)\n\tif err != nil {\n\t\terrCh <- err\n\t\treturn\n\t}\n\tif err := doCopy(cpurls.SourceContent.Name, srcConfig, cpurls.TargetContent.Name, tgtConfig, bar); err != nil {\n\t\terrCh <- err\n\t}\n\t<-cpQueue \/\/ Signal that this copy routine is done.\n}\n\nfunc doCopyCmd(sourceURLs []string, targetURL string, bar barSend) <-chan error {\n\terrCh := make(chan error)\n\n\tgo func(sourceURLs []string, targetURL string, bar barSend, errCh chan error) {\n\t\tdefer close(errCh)\n\n\t\tvar lock countlock.Locker\n\t\tif !globalQuietFlag {\n\t\t\t\/\/ Keep progress-bar and copy routines in sync.\n\t\t\tlock = countlock.New()\n\t\t\tdefer lock.Close()\n\t\t}\n\n\t\tgo func(sourceURLs []string, targetURL string) {\n\t\t\tfor cpURLs := range prepareCopyURLs(sourceURLs, targetURL) {\n\t\t\t\tif cpURLs.Error != nil {\n\t\t\t\t\t\/\/ no need to print errors here, any error here\n\t\t\t\t\t\/\/ will be printed later during Copy()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif !globalQuietFlag {\n\t\t\t\t\tbar.Extend(cpURLs.SourceContent.Size)\n\t\t\t\t\tlock.Up() \/\/ Let copy routine know that it is catch up.\n\t\t\t\t}\n\t\t\t}\n\t\t}(sourceURLs, targetURL)\n\n\t\t\/\/ Pool limited copy routines in parallel.\n\t\tcpQueue := make(chan bool, intMax(runtime.NumCPU()-1, 1))\n\t\tdefer close(cpQueue)\n\n\t\t\/\/ Wait for all copy routines to complete.\n\t\twg := new(sync.WaitGroup)\n\t\tfor cpURLs := range prepareCopyURLs(sourceURLs, targetURL) {\n\t\t\tif cpURLs.Error != nil {\n\t\t\t\terrCh <- cpURLs.Error\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcpQueue <- true \/\/ Wait for existing pool to drain.\n\t\t\twg.Add(1)\n\t\t\tif !globalQuietFlag {\n\t\t\t\tlock.Down() \/\/ Do not jump ahead of the progress bar builder above.\n\t\t\t}\n\t\t\tgo doCopyInRoutine(cpURLs, &bar, cpQueue, errCh, wg)\n\t\t}\n\t\twg.Wait()\n\t}(sourceURLs, targetURL, bar, errCh)\n\treturn errCh\n}\n\n\/\/ runCopyCmd is bound to sub-command\nfunc runCopyCmd(ctx *cli.Context) {\n\tif len(ctx.Args()) < 2 || ctx.Args().First() == \"help\" {\n\t\tcli.ShowCommandHelpAndExit(ctx, \"cp\", 1) \/\/ last argument is exit code\n\t}\n\n\tif !isMcConfigExist() {\n\t\tconsole.Fatals(ErrorMessage{\n\t\t\tMessage: \"Please run \\\"mc config generate\\\"\",\n\t\t\tError:   iodine.New(errors.New(\"\\\"mc\\\" is not configured\"), nil),\n\t\t})\n\t}\n\n\t\/\/ extract URLs.\n\tURLs, err := args2URLs(ctx.Args())\n\tif err != nil {\n\t\tconsole.Fatals(ErrorMessage{\n\t\t\tMessage: fmt.Sprintf(\"Unknown URL types: ‘%s’\", URLs),\n\t\t\tError:   iodine.New(err, nil),\n\t\t})\n\t}\n\n\t\/\/ Separate source and target. 'cp' can take only one target,\n\t\/\/ but any number of sources, even the recursive URLs mixed in-between.\n\tsourceURLs := URLs[:len(URLs)-1]\n\ttargetURL := URLs[len(URLs)-1] \/\/ Last one is target\n\n\tvar bar barSend\n\t\/\/ set up progress bar\n\tif !globalQuietFlag {\n\t\tbar = newCpBar()\n\t}\n\n\tfor err := range doCopyCmd(sourceURLs, targetURL, bar) {\n\t\tif err != nil {\n\t\t\tconsole.Errors(ErrorMessage{\n\t\t\t\tMessage: \"Failed with\",\n\t\t\t\tError:   iodine.New(err, nil),\n\t\t\t})\n\t\t}\n\t}\n\tif !globalQuietFlag {\n\t\tbar.Finish()\n\t}\n}\n<commit_msg>yield CPU to progress bar builder<commit_after>\/*\n * Minio Client (C) 2014, 2015 Minio, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"runtime\"\n\t\"sync\"\n\n\t\"github.com\/minio\/cli\"\n\t\"github.com\/minio\/mc\/pkg\/console\"\n\t\"github.com\/minio\/mc\/pkg\/countlock\"\n\t\"github.com\/minio\/minio\/pkg\/iodine\"\n)\n\n\/\/ doCopy - Copy a singe file from source to destination\nfunc doCopy(sourceURL string, sourceConfig *hostConfig, targetURL string, targetConfig *hostConfig, bar *barSend) error {\n\treader, length, err := getSource(sourceURL, sourceConfig)\n\tif err != nil {\n\t\tif !globalQuietFlag {\n\t\t\tbar.ErrorGet(int64(length))\n\t\t}\n\t\treturn iodine.New(err, nil)\n\t}\n\tdefer reader.Close()\n\n\tvar newReader io.Reader\n\tswitch globalQuietFlag {\n\tcase true:\n\t\tconsole.Infoln(fmt.Sprintf(\"‘%s’ -> ‘%s’\", sourceURL, targetURL))\n\t\tnewReader = reader\n\tdefault:\n\t\t\/\/ set up progress\n\t\tnewReader = bar.NewProxyReader(reader)\n\t}\n\n\terr = putTarget(targetURL, targetConfig, length, newReader)\n\tif err != nil {\n\t\tif !globalQuietFlag {\n\t\t\tbar.ErrorPut(int64(length))\n\t\t}\n\t\treturn iodine.New(err, nil)\n\t}\n\treturn nil\n}\n\n\/\/ args2URLs extracts source and target URLs from command-line args.\nfunc args2URLs(args cli.Args) ([]string, error) {\n\tconfig, err := getMcConfig()\n\tif err != nil {\n\t\treturn nil, iodine.New(err, nil)\n\t}\n\t\/\/ Convert arguments to URLs: expand alias, fix format...\n\tURLs, err := getExpandedURLs(args, config.Aliases)\n\tif err != nil {\n\t\treturn nil, iodine.New(err, nil)\n\t}\n\treturn URLs, nil\n}\n\nfunc doCopyInRoutine(cpurls *cpURLs, bar *barSend, cpQueue chan bool, errCh chan error, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tsrcConfig, err := getHostConfig(cpurls.SourceContent.Name)\n\tif err != nil {\n\t\terrCh <- err\n\t\treturn\n\t}\n\ttgtConfig, err := getHostConfig(cpurls.TargetContent.Name)\n\tif err != nil {\n\t\terrCh <- err\n\t\treturn\n\t}\n\tif err := doCopy(cpurls.SourceContent.Name, srcConfig, cpurls.TargetContent.Name, tgtConfig, bar); err != nil {\n\t\terrCh <- err\n\t}\n\t<-cpQueue \/\/ Signal that this copy routine is done.\n}\n\nfunc doCopyCmd(sourceURLs []string, targetURL string, bar barSend) <-chan error {\n\terrCh := make(chan error)\n\n\tgo func(sourceURLs []string, targetURL string, bar barSend, errCh chan error) {\n\t\tdefer close(errCh)\n\n\t\tvar lock countlock.Locker\n\t\tif !globalQuietFlag {\n\t\t\t\/\/ Keep progress-bar and copy routines in sync.\n\t\t\tlock = countlock.New()\n\t\t\tdefer lock.Close()\n\t\t}\n\n\t\tgo func(sourceURLs []string, targetURL string) {\n\t\t\tfor cpURLs := range prepareCopyURLs(sourceURLs, targetURL) {\n\t\t\t\tif cpURLs.Error != nil {\n\t\t\t\t\t\/\/ no need to print errors here, any error here\n\t\t\t\t\t\/\/ will be printed later during Copy()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif !globalQuietFlag {\n\t\t\t\t\tbar.Extend(cpURLs.SourceContent.Size)\n\t\t\t\t\tlock.Up() \/\/ Let copy routine know that it is catch up.\n\t\t\t\t}\n\t\t\t}\n\t\t}(sourceURLs, targetURL)\n\n\t\t\/\/ Pool limited copy routines in parallel.\n\t\tcpQueue := make(chan bool, intMax(runtime.NumCPU()-1, 1))\n\t\tdefer close(cpQueue)\n\n\t\t\/\/ Wait for all copy routines to complete.\n\t\twg := new(sync.WaitGroup)\n\t\tfor cpURLs := range prepareCopyURLs(sourceURLs, targetURL) {\n\t\t\tif cpURLs.Error != nil {\n\t\t\t\terrCh <- cpURLs.Error\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\truntime.Gosched() \/\/ Yield more CPU time to progress-bar builder.\n\n\t\t\tcpQueue <- true \/\/ Wait for existing pool to drain.\n\t\t\twg.Add(1)\n\t\t\tif !globalQuietFlag {\n\t\t\t\tlock.Down() \/\/ Do not jump ahead of the progress bar builder above.\n\t\t\t}\n\t\t\tgo doCopyInRoutine(cpURLs, &bar, cpQueue, errCh, wg)\n\t\t}\n\t\twg.Wait()\n\t}(sourceURLs, targetURL, bar, errCh)\n\treturn errCh\n}\n\n\/\/ runCopyCmd is bound to sub-command\nfunc runCopyCmd(ctx *cli.Context) {\n\tif len(ctx.Args()) < 2 || ctx.Args().First() == \"help\" {\n\t\tcli.ShowCommandHelpAndExit(ctx, \"cp\", 1) \/\/ last argument is exit code\n\t}\n\n\tif !isMcConfigExist() {\n\t\tconsole.Fatals(ErrorMessage{\n\t\t\tMessage: \"Please run \\\"mc config generate\\\"\",\n\t\t\tError:   iodine.New(errors.New(\"\\\"mc\\\" is not configured\"), nil),\n\t\t})\n\t}\n\n\t\/\/ extract URLs.\n\tURLs, err := args2URLs(ctx.Args())\n\tif err != nil {\n\t\tconsole.Fatals(ErrorMessage{\n\t\t\tMessage: fmt.Sprintf(\"Unknown URL types: ‘%s’\", URLs),\n\t\t\tError:   iodine.New(err, nil),\n\t\t})\n\t}\n\n\t\/\/ Separate source and target. 'cp' can take only one target,\n\t\/\/ but any number of sources, even the recursive URLs mixed in-between.\n\tsourceURLs := URLs[:len(URLs)-1]\n\ttargetURL := URLs[len(URLs)-1] \/\/ Last one is target\n\n\tvar bar barSend\n\t\/\/ set up progress bar\n\tif !globalQuietFlag {\n\t\tbar = newCpBar()\n\t}\n\n\tfor err := range doCopyCmd(sourceURLs, targetURL, bar) {\n\t\tif err != nil {\n\t\t\tconsole.Errors(ErrorMessage{\n\t\t\t\tMessage: \"Failed with\",\n\t\t\t\tError:   iodine.New(err, nil),\n\t\t\t})\n\t\t}\n\t}\n\tif !globalQuietFlag {\n\t\tbar.Finish()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package parser_test\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/goccy\/go-yaml\/ast\"\n\t\"github.com\/goccy\/go-yaml\/lexer\"\n\t\"github.com\/goccy\/go-yaml\/parser\"\n)\n\nfunc TestParser(t *testing.T) {\n\tsources := []string{\n\t\t\"null\\n\",\n\t\t\"{}\\n\",\n\t\t\"v: hi\\n\",\n\t\t\"v: \\\"true\\\"\\n\",\n\t\t\"v: \\\"false\\\"\\n\",\n\t\t\"v: true\\n\",\n\t\t\"v: false\\n\",\n\t\t\"v: 10\\n\",\n\t\t\"v: -10\\n\",\n\t\t\"v: 42\\n\",\n\t\t\"v: 4294967296\\n\",\n\t\t\"v: \\\"10\\\"\\n\",\n\t\t\"v: 0.1\\n\",\n\t\t\"v: 0.99\\n\",\n\t\t\"v: -0.1\\n\",\n\t\t\"v: .inf\\n\",\n\t\t\"v: -.inf\\n\",\n\t\t\"v: .nan\\n\",\n\t\t\"v: null\\n\",\n\t\t\"v: \\\"\\\"\\n\",\n\t\t\"v:\\n- A\\n- B\\n\",\n\t\t\"a: '-'\\n\",\n\t\t\"123\\n\",\n\t\t\"hello: world\\n\",\n\t\t\"a: null\\n\",\n\t\t\"v:\\n- A\\n- 1\\n- B:\\n  - 2\\n  - 3\\n\",\n\t\t\"a:\\n  b: c\\n\",\n\t\t\"a: {x: 1}\\n\",\n\t\t\"t2: 2018-01-09T10:40:47Z\\nt4: 2098-01-09T10:40:47Z\\n\",\n\t\t\"a: [1, 2]\\n\",\n\t\t\"a: {b: c, d: e}\\n\",\n\t\t\"a: 3s\\n\",\n\t\t\"a: <foo>\\n\",\n\t\t\"a: \\\"1:1\\\"\\n\",\n\t\t\"a: 1.2.3.4\\n\",\n\t\t\"a: \\\"2015-02-24T18:19:39Z\\\"\\n\",\n\t\t\"a: 'b: c'\\n\",\n\t\t\"a: 'Hello #comment'\\n\",\n\t\t\"a: 100.5\\n\",\n\t\t\"a: bogus\\n\",\n\t\t\"a: \\\"\\\\0\\\"\\n\",\n\t\t\"b: 2\\na: 1\\nd: 4\\nc: 3\\nsub:\\n  e: 5\\n\",\n\t\t\"       a       :          b        \\n\",\n\t\t\"a: b # comment\\nb: c\\n\",\n\t\t\"---\\na: b\\n\",\n\t\t\"a: b\\n...\\n\",\n\t\t\"%YAML 1.2\\n---\\n\",\n\t\t\"a: !!binary gIGC\\n\",\n\t\t\"a: !!binary |\\n  \" + strings.Repeat(\"kJCQ\", 17) + \"kJ\\n  CQ\\n\",\n\t\t\"- !tag\\n  a: b\\n  c: d\\n\",\n\t\t\"v:\\n- A\\n- |-\\n  B\\n  C\\n\",\n\t\t\"v:\\n- A\\n- >-\\n  B\\n  C\\n\",\n\t\t\"v: |-\\n  0\\n\",\n\t\t\"v: |-\\n  0\\nx: 0\",\n\t\t`\"a\\n1\\nb\"`,\n\t}\n\tfor _, src := range sources {\n\t\tif _, err := parser.Parse(lexer.Tokenize(src), 0); err != nil {\n\t\t\tt.Fatalf(\"parse error: source [%s]: %+v\", src, err)\n\t\t}\n\t}\n}\n\nfunc TestParseComplicatedDocument(t *testing.T) {\n\ttests := []struct {\n\t\tsource string\n\t\texpect string\n\t}{\n\t\t{\n\t\t\t`\namerican:\n  - Boston Red Sox\n  - Detroit Tigers\n  - New York Yankees\nnational:\n  - New York Mets\n  - Chicago Cubs\n  - Atlanta Braves\n`, `\namerican:\n  - Boston Red Sox\n  - Detroit Tigers\n  - New York Yankees\nnational:\n  - New York Mets\n  - Chicago Cubs\n  - Atlanta Braves\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n  b: c\n  d: e\n  f: g\nh:\n  i: j\n  k:\n    l: m\n    n: o\n  p: q\nr: s\n`, `\na:\n  b: c\n  d: e\n  f: g\nh:\n  i: j\n  k:\n    l: m\n    n: o\n  p: q\nr: s\n`,\n\t\t},\n\t\t{\n\t\t\t`\n- a:\n  - b\n  - c\n- d\n`, `\n- a:\n  - b\n  - c\n- d\n`,\n\t\t},\n\t\t{\n\t\t\t`\n- a\n- b\n- c\n - d\n - e\n- f\n`, `\n- a\n- b\n- c - d - e\n- f\n`,\n\t\t},\n\t\t{\n\t\t\t`\na: 0 - 1\n`,\n\t\t\t`\na: 0 - 1\n`,\n\t\t},\n\t\t{`\n- a:\n   b: c\n   d: e\n- f:\n  g: h\n`,\n\t\t\t`\n- a:\n   b: c\n   d: e\n- f: null\n  g: h\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n b\n c\nd: e\n`, `\na: b c\nd: e\n`,\n\t\t},\n\t\t{\n\t\t\t`\na\nb\nc\n`, `\na b c\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n - b\n - c\n`, `\na:\n - b\n - c\n`,\n\t\t},\n\t\t{\n\t\t\t`\n-     a     :\n      b: c\n`, `\n- a: null\n  b: c\n`,\n\t\t},\n\t\t{\n\t\t\t`\n- a:\n   b\n   c\n   d\n  hoge: fuga\n`, `\n- a: b c d\n  hoge: fuga\n`,\n\t\t},\n\t\t{\n\t\t\t`\n- a # ' \" # - : %\n- b # \" # - : % '\n- c # # - : % ' \"\n- d # - : % ' \" #\n- e # : % ' \" # -\n- f # % ' : # - :\n`,\n\t\t\t`\n- a\n- b\n- c\n- d\n- e\n- f\n`,\n\t\t},\n\t\t{\n\t\t\t`\n# comment\na: # comment\n# comment\n b: c # comment\n # comment\nd: e # comment\n# comment\n`,\n\t\t\t`\na:\n b: c\nd: e\n`,\n\t\t},\n\t\t{\n\t\t\t`\na: b#notcomment\n`,\n\t\t\t`\na: b#notcomment\n`,\n\t\t},\n\t\t{\n\t\t\t`\nanchored: &anchor foo\naliased: *anchor\n`,\n\t\t\t`\nanchored: &anchor foo\naliased: *anchor\n`,\n\t\t},\n\t\t{\n\t\t\t`\n---\n- &CENTER { x: 1, y: 2 }\n- &LEFT { x: 0, y: 2 }\n- &BIG { r: 10 }\n- &SMALL { r: 1 }\n\n# All the following maps are equal:\n\n- # Explicit keys\n  x: 1\n  y: 2\n  r: 10\n  label: center\/big\n\n- # Merge one map\n  << : *CENTER\n  r: 10\n  label: center\/big\n\n- # Merge multiple maps\n  << : [ *CENTER, *BIG ]\n  label: center\/big\n\n- # Override\n  << : [ *BIG, *LEFT, *SMALL ]\n  x: 1\n  label: center\/big\n`,\n\t\t\t`\n---\n- &CENTER {x: 1, y: 2}\n- &LEFT {x: 0, y: 2}\n- &BIG {r: 10}\n- &SMALL {r: 1}\n- x: 1\n  y: 2\n  r: 10\n  label: center\/big\n- <<: *CENTER\n  r: 10\n  label: center\/big\n- <<: [*CENTER, *BIG]\n  label: center\/big\n- <<: [*BIG, *LEFT, *SMALL]\n  x: 1\n  label: center\/big\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n- - b\n- - c\n  - d\n`,\n\t\t\t`\na:\n- - b\n- - c\n  - d\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n  b:\n    c: d\n  e:\n    f: g\n    h: i\nj: k\n`,\n\t\t\t`\na:\n  b:\n    c: d\n  e:\n    f: g\n    h: i\nj: k\n`,\n\t\t},\n\t\t{\n\t\t\t`\n---\na: 1\nb: 2\n...\n---\nc: 3\nd: 4\n...\n`,\n\t\t\t`\n---\na: 1\nb: 2\n...\n---\nc: 3\nd: 4\n...\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n  b: |\n    {\n      [ 1, 2 ]\n    }\n  c: d\n`,\n\t\t\t`\na:\n  b: |\n    {\n      [ 1, 2 ]\n    }\n  c: d\n`,\n\t\t},\n\t\t{\n\t\t\t`\n|\n    hoge\n    fuga\n    piyo`,\n\t\t\t`\n|\n    hoge\n    fuga\n    piyo\n`,\n\t\t},\n\t\t{\n\t\t\t`\na: |\n   bbbbbbb\n\n\n   ccccccc\nd: eeeeeeeeeeeeeeeee\n`,\n\t\t\t`\na: |\n   bbbbbbb\n\n\n   ccccccc\nd: eeeeeeeeeeeeeeeee\n`,\n\t\t},\n\t\t{\n\t\t\t`\na: b    \n  c\n`,\n\t\t\t`\na: b c\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:    \n  b: c\n`,\n\t\t\t`\na:\n  b: c\n`,\n\t\t},\n\t\t{\n\t\t\t`\na: b    \nc: d\n`,\n\t\t\t`\na: b\nc: d\n`,\n\t\t},\n\t\t{\n\t\t\t`\n- ab - cd\n- ef - gh\n`,\n\t\t\t`\n- ab - cd\n- ef - gh\n`,\n\t\t},\n\t\t{\n\t\t\t`\n- 0 - 1\n - 2 - 3\n`,\n\t\t\t`\n- 0 - 1 - 2 - 3\n`,\n\t\t},\n\t\t{\n\t\t\t`\na - b - c: value\n`,\n\t\t\t`\na - b - c: value\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n-\n  b: c\n  d: e\n-\n  f: g\n  h: i\n`,\n\t\t\t`\na:\n- b: c\n  d: e\n- f: g\n  h: i\n`,\n\t\t},\n\t\t{\n\t\t\t`\na: |-\n  value\nb: c\n`,\n\t\t\t`\na: |-\n  value\nb: c\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:  |+\n  value\nb: c\n`,\n\t\t\t`\na: |+\n  value\nb: c\n`,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\ttokens := lexer.Tokenize(test.source)\n\t\tf, err := parser.Parse(tokens, 0)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%+v\", err)\n\t\t}\n\t\tvar v Visitor\n\t\tfor _, doc := range f.Docs {\n\t\t\tast.Walk(&v, doc.Body)\n\t\t}\n\t\texpect := fmt.Sprintf(\"\\n%+v\\n\", f)\n\t\tif test.expect != expect {\n\t\t\ttokens.Dump()\n\t\t\tt.Fatalf(\"unexpected output: [%s] != [%s]\", test.expect, expect)\n\t\t}\n\t}\n}\n\nfunc TestNewLineChar(t *testing.T) {\n\tfor _, f := range []string{\n\t\t\"lf.yml\",\n\t\t\"cr.yml\",\n\t\t\"crlf.yml\",\n\t} {\n\t\tast, err := parser.ParseFile(filepath.Join(\"testdata\", f), 0)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%+v\", err)\n\t\t}\n\t\tactual := fmt.Sprintf(\"%v\\n\", ast)\n\t\texpect := `a: \"a\"\nb: 1\n`\n\t\tif expect != actual {\n\t\t\tt.Fatal(\"unexpected result\")\n\t\t}\n\t}\n}\n\nfunc TestSyntaxError(t *testing.T) {\n\tsources := []string{\n\t\t\"a:\\n- b\\n  c: d\\n  e: f\\n  g: h\",\n\t}\n\tfor _, source := range sources {\n\t\t_, err := parser.ParseBytes([]byte(source), 0)\n\t\tif err == nil {\n\t\t\tt.Fatal(\"cannot catch syntax error\")\n\t\t}\n\t\texpected := `\n[2:3] unexpected key name\n   1 | a:\n>  2 | - b\n   3 |   c: d\n         ^\n   4 |   e: f\n   5 |   g: h`\n\t\tactual := \"\\n\" + err.Error()\n\t\tif expected != actual {\n\t\t\tt.Fatalf(\"expected: [%s] but got [%s]\", expected, actual)\n\t\t}\n\t}\n}\n\nfunc TestComment(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tyaml string\n\t}{\n\t\t{\n\t\t\tname: \"map with comment\",\n\t\t\tyaml: `\n# commentA\na: #commentB\n  # commentC\n  b: c # commentD\n  # commentE\n  d: e # commentF\n  # commentG\n  f: g # commentH\n# commentI\nf: g # commentJ\n# commentK\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"sequence with comment\",\n\t\t\tyaml: `\n# commentA\n- a # commentB\n# commentC\n- b: # commentD\n  # commentE\n  - d # commentF\n  - e # commentG\n# commentH\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"anchor and alias\",\n\t\t\tyaml: `\na: &x b # commentA\nc: *x # commentB\n`,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tf, err := parser.ParseBytes([]byte(test.yaml), parser.ParseComments)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"%+v\", err)\n\t\t\t}\n\t\t\tvar v Visitor\n\t\t\tfor _, doc := range f.Docs {\n\t\t\t\tast.Walk(&v, doc.Body)\n\t\t\t}\n\t\t})\n\t}\n}\n\ntype Visitor struct {\n}\n\nfunc (v *Visitor) Visit(node ast.Node) ast.Visitor {\n\ttk := node.GetToken()\n\ttk.Prev = nil\n\ttk.Next = nil\n\tif comment := node.GetComment(); comment != nil {\n\t\tcomment.Prev = nil\n\t\tcomment.Next = nil\n\t}\n\treturn v\n}\n<commit_msg>Add test case for mapping value delimiter in flow style ( #142 )<commit_after>package parser_test\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/goccy\/go-yaml\/ast\"\n\t\"github.com\/goccy\/go-yaml\/lexer\"\n\t\"github.com\/goccy\/go-yaml\/parser\"\n)\n\nfunc TestParser(t *testing.T) {\n\tsources := []string{\n\t\t\"null\\n\",\n\t\t\"{}\\n\",\n\t\t\"v: hi\\n\",\n\t\t\"v: \\\"true\\\"\\n\",\n\t\t\"v: \\\"false\\\"\\n\",\n\t\t\"v: true\\n\",\n\t\t\"v: false\\n\",\n\t\t\"v: 10\\n\",\n\t\t\"v: -10\\n\",\n\t\t\"v: 42\\n\",\n\t\t\"v: 4294967296\\n\",\n\t\t\"v: \\\"10\\\"\\n\",\n\t\t\"v: 0.1\\n\",\n\t\t\"v: 0.99\\n\",\n\t\t\"v: -0.1\\n\",\n\t\t\"v: .inf\\n\",\n\t\t\"v: -.inf\\n\",\n\t\t\"v: .nan\\n\",\n\t\t\"v: null\\n\",\n\t\t\"v: \\\"\\\"\\n\",\n\t\t\"v:\\n- A\\n- B\\n\",\n\t\t\"a: '-'\\n\",\n\t\t\"123\\n\",\n\t\t\"hello: world\\n\",\n\t\t\"a: null\\n\",\n\t\t\"v:\\n- A\\n- 1\\n- B:\\n  - 2\\n  - 3\\n\",\n\t\t\"a:\\n  b: c\\n\",\n\t\t\"a: {x: 1}\\n\",\n\t\t\"t2: 2018-01-09T10:40:47Z\\nt4: 2098-01-09T10:40:47Z\\n\",\n\t\t\"a: [1, 2]\\n\",\n\t\t\"a: {b: c, d: e}\\n\",\n\t\t\"a: 3s\\n\",\n\t\t\"a: <foo>\\n\",\n\t\t\"a: \\\"1:1\\\"\\n\",\n\t\t\"a: 1.2.3.4\\n\",\n\t\t\"a: \\\"2015-02-24T18:19:39Z\\\"\\n\",\n\t\t\"a: 'b: c'\\n\",\n\t\t\"a: 'Hello #comment'\\n\",\n\t\t\"a: 100.5\\n\",\n\t\t\"a: bogus\\n\",\n\t\t\"a: \\\"\\\\0\\\"\\n\",\n\t\t\"b: 2\\na: 1\\nd: 4\\nc: 3\\nsub:\\n  e: 5\\n\",\n\t\t\"       a       :          b        \\n\",\n\t\t\"a: b # comment\\nb: c\\n\",\n\t\t\"---\\na: b\\n\",\n\t\t\"a: b\\n...\\n\",\n\t\t\"%YAML 1.2\\n---\\n\",\n\t\t\"a: !!binary gIGC\\n\",\n\t\t\"a: !!binary |\\n  \" + strings.Repeat(\"kJCQ\", 17) + \"kJ\\n  CQ\\n\",\n\t\t\"- !tag\\n  a: b\\n  c: d\\n\",\n\t\t\"v:\\n- A\\n- |-\\n  B\\n  C\\n\",\n\t\t\"v:\\n- A\\n- >-\\n  B\\n  C\\n\",\n\t\t\"v: |-\\n  0\\n\",\n\t\t\"v: |-\\n  0\\nx: 0\",\n\t\t`\"a\\n1\\nb\"`,\n\t\t`{\"a\":\"b\"}`,\n\t}\n\tfor _, src := range sources {\n\t\tif _, err := parser.Parse(lexer.Tokenize(src), 0); err != nil {\n\t\t\tt.Fatalf(\"parse error: source [%s]: %+v\", src, err)\n\t\t}\n\t}\n}\n\nfunc TestParseComplicatedDocument(t *testing.T) {\n\ttests := []struct {\n\t\tsource string\n\t\texpect string\n\t}{\n\t\t{\n\t\t\t`\namerican:\n  - Boston Red Sox\n  - Detroit Tigers\n  - New York Yankees\nnational:\n  - New York Mets\n  - Chicago Cubs\n  - Atlanta Braves\n`, `\namerican:\n  - Boston Red Sox\n  - Detroit Tigers\n  - New York Yankees\nnational:\n  - New York Mets\n  - Chicago Cubs\n  - Atlanta Braves\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n  b: c\n  d: e\n  f: g\nh:\n  i: j\n  k:\n    l: m\n    n: o\n  p: q\nr: s\n`, `\na:\n  b: c\n  d: e\n  f: g\nh:\n  i: j\n  k:\n    l: m\n    n: o\n  p: q\nr: s\n`,\n\t\t},\n\t\t{\n\t\t\t`\n- a:\n  - b\n  - c\n- d\n`, `\n- a:\n  - b\n  - c\n- d\n`,\n\t\t},\n\t\t{\n\t\t\t`\n- a\n- b\n- c\n - d\n - e\n- f\n`, `\n- a\n- b\n- c - d - e\n- f\n`,\n\t\t},\n\t\t{\n\t\t\t`\na: 0 - 1\n`,\n\t\t\t`\na: 0 - 1\n`,\n\t\t},\n\t\t{`\n- a:\n   b: c\n   d: e\n- f:\n  g: h\n`,\n\t\t\t`\n- a:\n   b: c\n   d: e\n- f: null\n  g: h\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n b\n c\nd: e\n`, `\na: b c\nd: e\n`,\n\t\t},\n\t\t{\n\t\t\t`\na\nb\nc\n`, `\na b c\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n - b\n - c\n`, `\na:\n - b\n - c\n`,\n\t\t},\n\t\t{\n\t\t\t`\n-     a     :\n      b: c\n`, `\n- a: null\n  b: c\n`,\n\t\t},\n\t\t{\n\t\t\t`\n- a:\n   b\n   c\n   d\n  hoge: fuga\n`, `\n- a: b c d\n  hoge: fuga\n`,\n\t\t},\n\t\t{\n\t\t\t`\n- a # ' \" # - : %\n- b # \" # - : % '\n- c # # - : % ' \"\n- d # - : % ' \" #\n- e # : % ' \" # -\n- f # % ' : # - :\n`,\n\t\t\t`\n- a\n- b\n- c\n- d\n- e\n- f\n`,\n\t\t},\n\t\t{\n\t\t\t`\n# comment\na: # comment\n# comment\n b: c # comment\n # comment\nd: e # comment\n# comment\n`,\n\t\t\t`\na:\n b: c\nd: e\n`,\n\t\t},\n\t\t{\n\t\t\t`\na: b#notcomment\n`,\n\t\t\t`\na: b#notcomment\n`,\n\t\t},\n\t\t{\n\t\t\t`\nanchored: &anchor foo\naliased: *anchor\n`,\n\t\t\t`\nanchored: &anchor foo\naliased: *anchor\n`,\n\t\t},\n\t\t{\n\t\t\t`\n---\n- &CENTER { x: 1, y: 2 }\n- &LEFT { x: 0, y: 2 }\n- &BIG { r: 10 }\n- &SMALL { r: 1 }\n\n# All the following maps are equal:\n\n- # Explicit keys\n  x: 1\n  y: 2\n  r: 10\n  label: center\/big\n\n- # Merge one map\n  << : *CENTER\n  r: 10\n  label: center\/big\n\n- # Merge multiple maps\n  << : [ *CENTER, *BIG ]\n  label: center\/big\n\n- # Override\n  << : [ *BIG, *LEFT, *SMALL ]\n  x: 1\n  label: center\/big\n`,\n\t\t\t`\n---\n- &CENTER {x: 1, y: 2}\n- &LEFT {x: 0, y: 2}\n- &BIG {r: 10}\n- &SMALL {r: 1}\n- x: 1\n  y: 2\n  r: 10\n  label: center\/big\n- <<: *CENTER\n  r: 10\n  label: center\/big\n- <<: [*CENTER, *BIG]\n  label: center\/big\n- <<: [*BIG, *LEFT, *SMALL]\n  x: 1\n  label: center\/big\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n- - b\n- - c\n  - d\n`,\n\t\t\t`\na:\n- - b\n- - c\n  - d\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n  b:\n    c: d\n  e:\n    f: g\n    h: i\nj: k\n`,\n\t\t\t`\na:\n  b:\n    c: d\n  e:\n    f: g\n    h: i\nj: k\n`,\n\t\t},\n\t\t{\n\t\t\t`\n---\na: 1\nb: 2\n...\n---\nc: 3\nd: 4\n...\n`,\n\t\t\t`\n---\na: 1\nb: 2\n...\n---\nc: 3\nd: 4\n...\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n  b: |\n    {\n      [ 1, 2 ]\n    }\n  c: d\n`,\n\t\t\t`\na:\n  b: |\n    {\n      [ 1, 2 ]\n    }\n  c: d\n`,\n\t\t},\n\t\t{\n\t\t\t`\n|\n    hoge\n    fuga\n    piyo`,\n\t\t\t`\n|\n    hoge\n    fuga\n    piyo\n`,\n\t\t},\n\t\t{\n\t\t\t`\na: |\n   bbbbbbb\n\n\n   ccccccc\nd: eeeeeeeeeeeeeeeee\n`,\n\t\t\t`\na: |\n   bbbbbbb\n\n\n   ccccccc\nd: eeeeeeeeeeeeeeeee\n`,\n\t\t},\n\t\t{\n\t\t\t`\na: b    \n  c\n`,\n\t\t\t`\na: b c\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:    \n  b: c\n`,\n\t\t\t`\na:\n  b: c\n`,\n\t\t},\n\t\t{\n\t\t\t`\na: b    \nc: d\n`,\n\t\t\t`\na: b\nc: d\n`,\n\t\t},\n\t\t{\n\t\t\t`\n- ab - cd\n- ef - gh\n`,\n\t\t\t`\n- ab - cd\n- ef - gh\n`,\n\t\t},\n\t\t{\n\t\t\t`\n- 0 - 1\n - 2 - 3\n`,\n\t\t\t`\n- 0 - 1 - 2 - 3\n`,\n\t\t},\n\t\t{\n\t\t\t`\na - b - c: value\n`,\n\t\t\t`\na - b - c: value\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:\n-\n  b: c\n  d: e\n-\n  f: g\n  h: i\n`,\n\t\t\t`\na:\n- b: c\n  d: e\n- f: g\n  h: i\n`,\n\t\t},\n\t\t{\n\t\t\t`\na: |-\n  value\nb: c\n`,\n\t\t\t`\na: |-\n  value\nb: c\n`,\n\t\t},\n\t\t{\n\t\t\t`\na:  |+\n  value\nb: c\n`,\n\t\t\t`\na: |+\n  value\nb: c\n`,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\ttokens := lexer.Tokenize(test.source)\n\t\tf, err := parser.Parse(tokens, 0)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%+v\", err)\n\t\t}\n\t\tvar v Visitor\n\t\tfor _, doc := range f.Docs {\n\t\t\tast.Walk(&v, doc.Body)\n\t\t}\n\t\texpect := fmt.Sprintf(\"\\n%+v\\n\", f)\n\t\tif test.expect != expect {\n\t\t\ttokens.Dump()\n\t\t\tt.Fatalf(\"unexpected output: [%s] != [%s]\", test.expect, expect)\n\t\t}\n\t}\n}\n\nfunc TestNewLineChar(t *testing.T) {\n\tfor _, f := range []string{\n\t\t\"lf.yml\",\n\t\t\"cr.yml\",\n\t\t\"crlf.yml\",\n\t} {\n\t\tast, err := parser.ParseFile(filepath.Join(\"testdata\", f), 0)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%+v\", err)\n\t\t}\n\t\tactual := fmt.Sprintf(\"%v\\n\", ast)\n\t\texpect := `a: \"a\"\nb: 1\n`\n\t\tif expect != actual {\n\t\t\tt.Fatal(\"unexpected result\")\n\t\t}\n\t}\n}\n\nfunc TestSyntaxError(t *testing.T) {\n\tsources := []string{\n\t\t\"a:\\n- b\\n  c: d\\n  e: f\\n  g: h\",\n\t}\n\tfor _, source := range sources {\n\t\t_, err := parser.ParseBytes([]byte(source), 0)\n\t\tif err == nil {\n\t\t\tt.Fatal(\"cannot catch syntax error\")\n\t\t}\n\t\texpected := `\n[2:3] unexpected key name\n   1 | a:\n>  2 | - b\n   3 |   c: d\n         ^\n   4 |   e: f\n   5 |   g: h`\n\t\tactual := \"\\n\" + err.Error()\n\t\tif expected != actual {\n\t\t\tt.Fatalf(\"expected: [%s] but got [%s]\", expected, actual)\n\t\t}\n\t}\n}\n\nfunc TestComment(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tyaml string\n\t}{\n\t\t{\n\t\t\tname: \"map with comment\",\n\t\t\tyaml: `\n# commentA\na: #commentB\n  # commentC\n  b: c # commentD\n  # commentE\n  d: e # commentF\n  # commentG\n  f: g # commentH\n# commentI\nf: g # commentJ\n# commentK\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"sequence with comment\",\n\t\t\tyaml: `\n# commentA\n- a # commentB\n# commentC\n- b: # commentD\n  # commentE\n  - d # commentF\n  - e # commentG\n# commentH\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"anchor and alias\",\n\t\t\tyaml: `\na: &x b # commentA\nc: *x # commentB\n`,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tf, err := parser.ParseBytes([]byte(test.yaml), parser.ParseComments)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"%+v\", err)\n\t\t\t}\n\t\t\tvar v Visitor\n\t\t\tfor _, doc := range f.Docs {\n\t\t\t\tast.Walk(&v, doc.Body)\n\t\t\t}\n\t\t})\n\t}\n}\n\ntype Visitor struct {\n}\n\nfunc (v *Visitor) Visit(node ast.Node) ast.Visitor {\n\ttk := node.GetToken()\n\ttk.Prev = nil\n\ttk.Next = nil\n\tif comment := node.GetComment(); comment != nil {\n\t\tcomment.Prev = nil\n\t\tcomment.Next = nil\n\t}\n\treturn v\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Google Inc. All rights reserved.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to writing, software distributed\n\/\/ under the License is distributed on a \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n\/\/ CONDITIONS OF ANY KIND, either express or implied.\n\/\/\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage parser\n\nimport (\n\t\"go\/build\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n)\n\nfunc must(t *testing.T, err error) {\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nvar fakeCode = `\npackage main\nimport \"fmt\"\nfunc main() {\n\tfmt.Println(\"Hello world!\")\n}\n`\n\nfunc TestParseFromMultipleGopath(t *testing.T) {\n\tgopaths := filepath.SplitList(build.Default.GOPATH)\n\tif len(gopaths) < 2 {\n\t\tt.Skipf(\"No multiple GOPATH (%s) exists, skiping..\", build.Default.GOPATH)\n\t}\n\tgopath := gopaths[len(gopaths)-1]\n\tdir := filepath.Join(gopath, \"src\", \"foo\")\n\tdefer must(t, os.RemoveAll(dir))\n\tmust(t, os.MkdirAll(dir, 0755))\n\tmust(t, ioutil.WriteFile(filepath.Join(dir, \"main.go\"), []byte(fakeCode), 0644))\n\n\tif _, err := ParsePackage(dir); err != nil {\n\t\tt.Fatalf(\"Parse package (%v): %v\", dir, err)\n\t}\n}\n<commit_msg>Fix testcase<commit_after>\/\/ Copyright 2017 Google Inc. All rights reserved.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to writing, software distributed\n\/\/ under the License is distributed on a \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n\/\/ CONDITIONS OF ANY KIND, either express or implied.\n\/\/\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage parser\n\nimport (\n\t\"go\/build\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n)\n\nfunc must(t *testing.T, err error) {\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nvar fakeCode = `\npackage main\nimport \"fmt\"\nfunc main() {\n\tfmt.Println(\"Hello world!\")\n}\n`\n\nfunc TestParseFromMultipleGopath(t *testing.T) {\n\tgopaths := filepath.SplitList(build.Default.GOPATH)\n\tif len(gopaths) < 2 {\n\t\tt.Skipf(\"No multiple GOPATH (%s) exists, skiping..\", build.Default.GOPATH)\n\t}\n\tgopath := gopaths[len(gopaths)-1]\n\tdir := filepath.Join(gopath, \"src\", \"foo\")\n\tdefer func() { must(t, os.RemoveAll(dir)) }()\n\tmust(t, os.MkdirAll(dir, 0755))\n\tmust(t, ioutil.WriteFile(filepath.Join(dir, \"main.go\"), []byte(fakeCode), 0644))\n\n\tif _, err := ParsePackage(dir); err != nil {\n\t\tt.Fatalf(\"Parse package (%v): %v\", dir, err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\"\n\t\"local\/mistify-operator-admin\/db\"\n\t\"net\/mail\"\n\n\t\"code.google.com\/p\/go-uuid\/uuid\"\n)\n\ntype User struct {\n\tID       string            `json:\"id\"`\n\tUsername string            `json:\"username\"`\n\tEmail    string            `json:\"email\"`\n\tMetadata map[string]string `json:\"metadata\"`\n\tProjects []*Project        `json:\"-\"`\n}\n\nfunc (user *User) Validate() error {\n\tif user.ID == \"\" {\n\t\treturn errors.New(\"missing id\")\n\t}\n\tif uuid.Parse(user.ID) == nil {\n\t\treturn errors.New(\"invalid id. must be uuid\")\n\t}\n\tif user.Username == \"\" {\n\t\treturn errors.New(\"missing username\")\n\t}\n\tif user.Email == \"\" {\n\t\treturn errors.New(\"missing email\")\n\t}\n\tif _, err := mail.ParseAddress(user.Email); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (user *User) Save() error {\n\terr := user.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td, err := db.Connect(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Writable CTE for an Upsert\n\t\/\/ See: http:\/\/stackoverflow.com\/a\/8702291\n\t\/\/ And: http:\/\/dba.stackexchange.com\/a\/78535\n\tsql := `\n\tWITH new_values (user_id, username, email, metadata) as (\n\t\tVALUES ($1::uuid, $2, $3, $4::json)\n\t),\n\tupsert as (\n\t\tUPDATE users u SET\n\t\t\tusername = nv.username,\n\t\t\temail = nv.email,\n\t\t\tmetadata = nv.metadata\n\t\tFROM new_values nv\n\t\tWHERE u.user_id = nv.user_id\n\t\tRETURNING nv.user_id\n\t)\n\tINSERT INTO users\n\t\t(user_id, username, email, metadata)\n\tSELECT user_id, username, email, metadata\n\tFROM new_values nv\n\tWHERE NOT EXISTS (SELECT 1 FROM upsert u WHERE nv.user_id = u.user_id)\n\t`\n\tmetadata, err := json.Marshal(user.Metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = d.Exec(sql,\n\t\tuser.ID,\n\t\tuser.Username,\n\t\tuser.Email,\n\t\tstring(metadata),\n\t)\n\treturn err\n}\n\n\/*\nfunc (user *User) Apply(update *User) {\n\tif update.Username != \"\" {\n\t\tuser.Username = update.Username\n\t}\n\tif _, err := mail.ParseAddress(update.Email); err == nil {\n\t\tuser.Email = update.Email\n\t}\n}\n*\/\n\nfunc (user *User) Delete() error {\n\td, err := db.Connect(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsql := \"DELETE FROM users WHERE user_id = $1\"\n\t_, err = d.Exec(sql, user.ID)\n\treturn err\n}\n\nfunc (user *User) Load() error {\n\td, err := db.Connect(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsql := `\n\tSELECT user_id, username, email, metadata\n\tFROM users\n\tWHERE user_id = $1\n\t`\n\trows, err := d.Query(sql, user.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\trows.Next()\n\treturn user.fromRows(rows)\n}\n\nfunc (user *User) fromRows(rows *sql.Rows) error {\n\tvar metadata string\n\terr := rows.Scan(\n\t\t&user.ID,\n\t\t&user.Username,\n\t\t&user.Email,\n\t\t&metadata,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal([]byte(metadata), &user.Metadata)\n}\n\nfunc (user *User) Decode(data io.Reader) error {\n\tif err := json.NewDecoder(data).Decode(user); err != nil {\n\t\treturn err\n\t}\n\tif user.Metadata == nil {\n\t\tuser.Metadata = make(map[string]string)\n\t} else {\n\t\tfor key, value := range user.Metadata {\n\t\t\tif value == \"\" {\n\t\t\t\tdelete(user.Metadata, key)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (user *User) LoadProjects() error {\n\tprojects, err := ProjectsByUser(user.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuser.Projects = projects\n\treturn nil\n}\n\nfunc (user *User) SetProjects(projectIDs []*string) error {\n\terr := SetUserProjects(user.ID, projectIDs)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn user.LoadProjects()\n}\n\nfunc (user *User) AddProject(projectID string) error {\n\terr := AddProjectUser(projectID, user.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn user.LoadProjects()\n}\n\nfunc (user *User) RemoveProject(projectID string) error {\n\terr := RemoveProjectUser(projectID, user.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn user.LoadProjects()\n}\n\nfunc (user *User) NewID() string {\n\tuser.ID = uuid.New()\n\treturn user.ID\n}\n\nfunc NewUser() *User {\n\tuser := &User{\n\t\tID: uuid.New(),\n\t}\n\treturn user\n}\n\nfunc FetchUser(id string) (*User, error) {\n\tuser := &User{\n\t\tID: id,\n\t}\n\terr := user.Load()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}\n\nfunc ListUsers() ([]*User, error) {\n\td, err := db.Connect(nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsql := `\n\tSELECT user_id, username, email, metadata\n\tFROM users\n\tORDER BY user_id asc\n\t`\n\trows, err := d.Query(sql)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn usersFromRows(rows)\n}\n\nfunc usersFromRows(rows *sql.Rows) ([]*User, error) {\n\tdefer rows.Close()\n\tusers := make([]*User, 0, 1)\n\tfor rows.Next() {\n\t\tuser := &User{}\n\t\tif err := user.fromRows(rows); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tusers = append(users, user)\n\t}\n\treturn users, nil\n}\n<commit_msg>MIST-227 Remove no longer used Apply func from User<commit_after>package models\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\"\n\t\"local\/mistify-operator-admin\/db\"\n\t\"net\/mail\"\n\n\t\"code.google.com\/p\/go-uuid\/uuid\"\n)\n\ntype User struct {\n\tID       string            `json:\"id\"`\n\tUsername string            `json:\"username\"`\n\tEmail    string            `json:\"email\"`\n\tMetadata map[string]string `json:\"metadata\"`\n\tProjects []*Project        `json:\"-\"`\n}\n\nfunc (user *User) Validate() error {\n\tif user.ID == \"\" {\n\t\treturn errors.New(\"missing id\")\n\t}\n\tif uuid.Parse(user.ID) == nil {\n\t\treturn errors.New(\"invalid id. must be uuid\")\n\t}\n\tif user.Username == \"\" {\n\t\treturn errors.New(\"missing username\")\n\t}\n\tif user.Email == \"\" {\n\t\treturn errors.New(\"missing email\")\n\t}\n\tif _, err := mail.ParseAddress(user.Email); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (user *User) Save() error {\n\terr := user.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td, err := db.Connect(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Writable CTE for an Upsert\n\t\/\/ See: http:\/\/stackoverflow.com\/a\/8702291\n\t\/\/ And: http:\/\/dba.stackexchange.com\/a\/78535\n\tsql := `\n\tWITH new_values (user_id, username, email, metadata) as (\n\t\tVALUES ($1::uuid, $2, $3, $4::json)\n\t),\n\tupsert as (\n\t\tUPDATE users u SET\n\t\t\tusername = nv.username,\n\t\t\temail = nv.email,\n\t\t\tmetadata = nv.metadata\n\t\tFROM new_values nv\n\t\tWHERE u.user_id = nv.user_id\n\t\tRETURNING nv.user_id\n\t)\n\tINSERT INTO users\n\t\t(user_id, username, email, metadata)\n\tSELECT user_id, username, email, metadata\n\tFROM new_values nv\n\tWHERE NOT EXISTS (SELECT 1 FROM upsert u WHERE nv.user_id = u.user_id)\n\t`\n\tmetadata, err := json.Marshal(user.Metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = d.Exec(sql,\n\t\tuser.ID,\n\t\tuser.Username,\n\t\tuser.Email,\n\t\tstring(metadata),\n\t)\n\treturn err\n}\n\nfunc (user *User) Delete() error {\n\td, err := db.Connect(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsql := \"DELETE FROM users WHERE user_id = $1\"\n\t_, err = d.Exec(sql, user.ID)\n\treturn err\n}\n\nfunc (user *User) Load() error {\n\td, err := db.Connect(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsql := `\n\tSELECT user_id, username, email, metadata\n\tFROM users\n\tWHERE user_id = $1\n\t`\n\trows, err := d.Query(sql, user.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\trows.Next()\n\treturn user.fromRows(rows)\n}\n\nfunc (user *User) fromRows(rows *sql.Rows) error {\n\tvar metadata string\n\terr := rows.Scan(\n\t\t&user.ID,\n\t\t&user.Username,\n\t\t&user.Email,\n\t\t&metadata,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal([]byte(metadata), &user.Metadata)\n}\n\nfunc (user *User) Decode(data io.Reader) error {\n\tif err := json.NewDecoder(data).Decode(user); err != nil {\n\t\treturn err\n\t}\n\tif user.Metadata == nil {\n\t\tuser.Metadata = make(map[string]string)\n\t} else {\n\t\tfor key, value := range user.Metadata {\n\t\t\tif value == \"\" {\n\t\t\t\tdelete(user.Metadata, key)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (user *User) LoadProjects() error {\n\tprojects, err := ProjectsByUser(user.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuser.Projects = projects\n\treturn nil\n}\n\nfunc (user *User) SetProjects(projectIDs []*string) error {\n\terr := SetUserProjects(user.ID, projectIDs)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn user.LoadProjects()\n}\n\nfunc (user *User) AddProject(projectID string) error {\n\terr := AddProjectUser(projectID, user.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn user.LoadProjects()\n}\n\nfunc (user *User) RemoveProject(projectID string) error {\n\terr := RemoveProjectUser(projectID, user.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn user.LoadProjects()\n}\n\nfunc (user *User) NewID() string {\n\tuser.ID = uuid.New()\n\treturn user.ID\n}\n\nfunc NewUser() *User {\n\tuser := &User{\n\t\tID: uuid.New(),\n\t}\n\treturn user\n}\n\nfunc FetchUser(id string) (*User, error) {\n\tuser := &User{\n\t\tID: id,\n\t}\n\terr := user.Load()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn user, nil\n}\n\nfunc ListUsers() ([]*User, error) {\n\td, err := db.Connect(nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsql := `\n\tSELECT user_id, username, email, metadata\n\tFROM users\n\tORDER BY user_id asc\n\t`\n\trows, err := d.Query(sql)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn usersFromRows(rows)\n}\n\nfunc usersFromRows(rows *sql.Rows) ([]*User, error) {\n\tdefer rows.Close()\n\tusers := make([]*User, 0, 1)\n\tfor rows.Next() {\n\t\tuser := &User{}\n\t\tif err := user.fromRows(rows); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tusers = append(users, user)\n\t}\n\treturn users, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package topgun_test\n\nimport (\n\t\"crypto\/tls\"\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"golang.org\/x\/oauth2\"\n\n\t\"code.cloudfoundry.org\/lager\"\n\t\"code.cloudfoundry.org\/lager\/lagertest\"\n\n\tgclient \"code.cloudfoundry.org\/garden\/client\"\n\tgconn \"code.cloudfoundry.org\/garden\/client\/connection\"\n\tsq \"github.com\/Masterminds\/squirrel\"\n\t\"github.com\/concourse\/atc\"\n\t\"github.com\/concourse\/go-concourse\/concourse\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\n\t\"strconv\"\n\t\"testing\"\n)\n\nvar (\n\tdeploymentName, flyTarget string\n\tjobInstances              map[string][]boshInstance\n\n\tdbInstance *boshInstance\n\tdbConn     *sql.DB\n\n\tatcInstance    *boshInstance\n\tatcExternalURL string\n\n\tconcourseReleaseVersion, gardenRuncReleaseVersion string\n\tstemcellVersion                                   string\n\n\tpipelineName string\n\n\ttmpHome string\n\tflyBin  string\n\n\tlogger *lagertest.TestLogger\n\n\tboshLogs *gexec.Session\n)\n\nvar psql = sq.StatementBuilder.PlaceholderFormat(sq.Dollar)\n\nfunc TestTOPGUN(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"TOPGUN Suite\")\n}\n\nvar _ = SynchronizedBeforeSuite(func() []byte {\n\tflyBinPath, err := gexec.Build(\"github.com\/concourse\/fly\")\n\tExpect(err).ToNot(HaveOccurred())\n\n\treturn []byte(flyBinPath)\n}, func(data []byte) {\n\tflyBin = string(data)\n})\n\nvar _ = SynchronizedAfterSuite(func() {\n}, func() {\n\tgexec.CleanupBuildArtifacts()\n})\n\nvar _ = BeforeEach(func() {\n\tSetDefaultEventuallyTimeout(5 * time.Minute)\n\tSetDefaultEventuallyPollingInterval(time.Second)\n\tSetDefaultConsistentlyDuration(time.Minute)\n\tSetDefaultConsistentlyPollingInterval(time.Second)\n\n\tlogger = lagertest.NewTestLogger(\"test\")\n\n\tn, found := os.LookupEnv(\"TOPGUN_NETWORK_OFFSET\")\n\tvar networkOffset int\n\tvar err error\n\n\tif found {\n\t\tnetworkOffset, err = strconv.Atoi(n)\n\t}\n\tExpect(err).NotTo(HaveOccurred())\n\n\tconcourseReleaseVersion = os.Getenv(\"CONCOURSE_RELEASE_VERSION\")\n\tif concourseReleaseVersion == \"\" {\n\t\tconcourseReleaseVersion = \"latest\"\n\t}\n\n\tgardenRuncReleaseVersion = os.Getenv(\"GARDEN_RUNC_RELEASE_VERSION\")\n\tif gardenRuncReleaseVersion == \"\" {\n\t\tgardenRuncReleaseVersion = \"latest\"\n\t}\n\n\tstemcellVersion = os.Getenv(\"STEMCELL_VERSION\")\n\tif stemcellVersion == \"\" {\n\t\tstemcellVersion = \"latest\"\n\t}\n\n\tdeploymentNumber := GinkgoParallelNode() + (networkOffset * 4)\n\n\tdeploymentName = fmt.Sprintf(\"concourse-topgun-%d\", deploymentNumber)\n\tflyTarget = deploymentName\n\n\tbosh(\"delete-deployment\")\n\n\tjobInstances = map[string][]boshInstance{}\n\n\tdbInstance = nil\n\tdbConn = nil\n\tatcInstance = nil\n\tatcExternalURL = \"\"\n})\n\nvar _ = AfterEach(func() {\n\tboshLogs.Signal(os.Interrupt)\n\t<-boshLogs.Exited\n\tboshLogs = nil\n\n\tdeleteAllContainers()\n\n\tbosh(\"delete-deployment\")\n})\n\nfunc StartDeploy(manifest string, operations ...string) *gexec.Session {\n\topFlags := []string{}\n\tfor _, op := range operations {\n\t\topFlags = append(opFlags, fmt.Sprintf(\"-o=%s\", op))\n\t}\n\n\treturn spawnBosh(\n\t\tappend([]string{\n\t\t\t\"deploy\", manifest,\n\t\t\t\"-v\", \"deployment-name=\" + deploymentName,\n\t\t\t\"-v\", \"concourse-release-version=\" + concourseReleaseVersion,\n\t\t\t\"-v\", \"garden-runc-release-version=\" + gardenRuncReleaseVersion,\n\n\t\t\t\/\/ 3363.10 becomes 3363.1 as it's floating point; quotes prevent that\n\t\t\t\"-v\", \"stemcell-version='\" + stemcellVersion + \"'\",\n\t\t}, opFlags...)...,\n\t)\n}\n\nfunc Deploy(manifest string, operations ...string) {\n\twait(StartDeploy(manifest, operations...))\n\n\tjobInstances = loadJobInstances()\n\n\tatcInstance = JobInstance(\"atc\")\n\tatcExternalURL = fmt.Sprintf(\"http:\/\/%s:8080\", atcInstance.IP)\n\n\tdbInstance = JobInstance(\"postgresql\")\n\n\tvar err error\n\tdbConn, err = sql.Open(\"postgres\", fmt.Sprintf(\"postgres:\/\/atc:dummy-password@%s:5432\/atc?sslmode=disable\", dbInstance.IP))\n\tExpect(err).ToNot(HaveOccurred())\n\n\t\/\/ give some time for atc to bootstrap (run migrations, etc)\n\tEventually(func() int {\n\t\tflySession := spawnFly(\"login\", \"-c\", atcExternalURL)\n\t\t<-flySession.Exited\n\t\treturn flySession.ExitCode()\n\t}, 2*time.Minute).Should(Equal(0))\n\n\tboshLogs = spawnBosh(\"logs\", \"-f\")\n}\n\nfunc JobInstance(instance string) *boshInstance {\n\tis := jobInstances[instance]\n\tif len(is) == 0 {\n\t\treturn nil\n\t}\n\n\treturn &is[0]\n}\n\nfunc JobInstances(instance string) []boshInstance {\n\treturn jobInstances[instance]\n}\n\ntype boshInstance struct {\n\tName string\n\tIP   string\n}\n\nvar instanceRow = regexp.MustCompile(`^([^\\s]+)\\s+-\\s+(\\w+)\\s+z1\\s+([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+)\\s*$`)\nvar jobRow = regexp.MustCompile(`^([^\\s]+)\\s+(\\w+)\\s+(\\w+)\\s+-\\s+-\\s*$`)\n\nfunc loadJobInstances() map[string][]boshInstance {\n\tsession := spawnBosh(\"instances\", \"-p\")\n\t<-session.Exited\n\tExpect(session.ExitCode()).To(Equal(0))\n\n\toutput := string(session.Out.Contents())\n\n\tjobInstances := map[string][]boshInstance{}\n\n\tlines := strings.Split(output, \"\\n\")\n\tvar instance boshInstance\n\tfor _, line := range lines {\n\t\tinstanceMatch := instanceRow.FindStringSubmatch(line)\n\t\tif len(instanceMatch) > 0 {\n\t\t\tinstance = boshInstance{\n\t\t\t\tName: instanceMatch[1],\n\t\t\t\tIP:   instanceMatch[3],\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tjobMatch := jobRow.FindStringSubmatch(line)\n\t\tif len(jobMatch) > 0 {\n\t\t\tjobName := jobMatch[3]\n\t\t\tjobInstances[jobName] = append(jobInstances[jobName], instance)\n\t\t}\n\t}\n\n\treturn jobInstances\n}\n\nfunc bosh(argv ...string) {\n\twait(spawnBosh(argv...))\n}\n\nfunc spawnBosh(argv ...string) *gexec.Session {\n\treturn spawn(\"bosh\", append([]string{\"-n\", \"-d\", deploymentName}, argv...)...)\n}\n\nfunc fly(argv ...string) {\n\twait(spawnFly(argv...))\n}\n\nfunc concourseClient() concourse.Client {\n\ttoken, err := getATCToken(atcExternalURL)\n\tExpect(err).NotTo(HaveOccurred())\n\thttpClient := oauthClient(token)\n\treturn concourse.NewClient(atcExternalURL, httpClient)\n}\n\nfunc deleteAllContainers() {\n\tclient := concourseClient()\n\tworkers, err := client.ListWorkers()\n\tExpect(err).NotTo(HaveOccurred())\n\n\tcontainers, err := client.ListContainers(map[string]string{})\n\tExpect(err).NotTo(HaveOccurred())\n\n\tfor _, worker := range workers {\n\t\tconnection := gconn.New(\"tcp\", worker.GardenAddr)\n\t\tgardenClient := gclient.New(connection)\n\t\tfor _, container := range containers {\n\t\t\tif container.WorkerName == worker.Name {\n\t\t\t\terr = gardenClient.Destroy(container.ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(\"failed-to-delete-container\", err, lager.Data{\"handle\": container.ID})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc flyHijackTask(argv ...string) *gexec.Session {\n\tcmd := exec.Command(flyBin, append([]string{\"-t\", flyTarget, \"hijack\"}, argv...)...)\n\thijackIn, err := cmd.StdinPipe()\n\tExpect(err).NotTo(HaveOccurred())\n\n\thijackS, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)\n\tExpect(err).ToNot(HaveOccurred())\n\n\tEventually(func() bool {\n\t\ttaskMatcher := gbytes.Say(\"type: task\")\n\t\tmatched, err := taskMatcher.Match(hijackS)\n\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\tif matched {\n\t\t\tre, err := regexp.Compile(\"([0-9]): .+ type: task\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\ttaskNumber := re.FindStringSubmatch(string(hijackS.Out.Contents()))[1]\n\t\t\tfmt.Fprintln(hijackIn, taskNumber)\n\n\t\t\treturn true\n\t\t}\n\n\t\treturn hijackS.ExitCode() == 0\n\t}).Should(BeTrue())\n\n\treturn hijackS\n}\n\nfunc spawnFly(argv ...string) *gexec.Session {\n\treturn spawn(flyBin, append([]string{\"-t\", flyTarget}, argv...)...)\n}\n\nfunc spawnFlyInteractive(stdin io.Reader, argv ...string) *gexec.Session {\n\treturn spawnInteractive(stdin, flyBin, append([]string{\"-t\", flyTarget}, argv...)...)\n}\n\nfunc run(argc string, argv ...string) {\n\twait(spawn(argc, argv...))\n}\n\nfunc spawn(argc string, argv ...string) *gexec.Session {\n\tBy(\"running: \" + argc + \" \" + strings.Join(argv, \" \"))\n\tcmd := exec.Command(argc, argv...)\n\tsession, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)\n\tExpect(err).ToNot(HaveOccurred())\n\treturn session\n}\n\nfunc spawnInteractive(stdin io.Reader, argc string, argv ...string) *gexec.Session {\n\tBy(\"interactively running: \" + argc + \" \" + strings.Join(argv, \" \"))\n\tcmd := exec.Command(argc, argv...)\n\tcmd.Stdin = stdin\n\tsession, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)\n\tExpect(err).ToNot(HaveOccurred())\n\treturn session\n}\n\nfunc wait(session *gexec.Session) {\n\t<-session.Exited\n\tExpect(session.ExitCode()).To(Equal(0))\n}\n\nfunc getATCToken(atcURL string) (*atc.AuthToken, error) {\n\tresponse, err := http.Get(atcURL + \"\/api\/v1\/teams\/main\/auth\/token\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar token *atc.AuthToken\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(body, &token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn token, nil\n}\n\nfunc oauthClient(atcToken *atc.AuthToken) *http.Client {\n\treturn &http.Client{\n\t\tTransport: &oauth2.Transport{\n\t\t\tSource: oauth2.StaticTokenSource(&oauth2.Token{\n\t\t\t\tTokenType:   atcToken.Type,\n\t\t\t\tAccessToken: atcToken.Value,\n\t\t\t}),\n\t\t\tBase: &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc waitForLandingOrLandedWorker() string {\n\treturn waitForWorkerInState(\"landing\", \"landed\")\n}\n\nfunc waitForRunningWorker() string {\n\treturn waitForWorkerInState(\"running\")\n}\n\nfunc waitForStalledWorker() string {\n\treturn waitForWorkerInState(\"stalled\")\n}\n\nfunc waitForWorkerInState(desiredStates ...string) string {\n\tvar workerName string\n\tEventually(func() string {\n\n\t\tworkers := flyTable(\"workers\")\n\n\t\tfor _, worker := range workers {\n\t\t\tname := worker[\"name\"]\n\t\t\tstate := worker[\"state\"]\n\n\t\t\tanyMatched := false\n\t\t\tfor _, desiredState := range desiredStates {\n\t\t\t\tif state == desiredState {\n\t\t\t\t\tanyMatched = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !anyMatched {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif workerName != \"\" {\n\t\t\t\tFail(\"multiple workers in states: \" + strings.Join(desiredStates, \", \"))\n\t\t\t}\n\n\t\t\tworkerName = name\n\t\t}\n\n\t\treturn workerName\n\t}).ShouldNot(BeEmpty())\n\n\treturn workerName\n}\n\nfunc flyTable(argv ...string) []map[string]string {\n\tsession := spawnFly(append([]string{\"--print-table-headers\"}, argv...)...)\n\t<-session.Exited\n\tExpect(session.ExitCode()).To(Equal(0))\n\n\tresult := []map[string]string{}\n\tvar headers []string\n\n\trows := strings.Split(string(session.Out.Contents()), \"\\n\")\n\tfor i, row := range rows {\n\t\tif i == 0 {\n\t\t\theaders = splitFlyColumns(row)\n\t\t\tcontinue\n\t\t}\n\t\tif row == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = append(result, map[string]string{})\n\t\tcolumns := splitFlyColumns(row)\n\n\t\tExpect(columns).To(HaveLen(len(headers)))\n\n\t\tfor j, header := range headers {\n\t\t\tif header == \"\" || columns[j] == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult[i-1][header] = columns[j]\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc splitFlyColumns(row string) []string {\n\treturn regexp.MustCompile(`\\s{2,}`).Split(strings.TrimSpace(row), -1)\n}\n\nfunc waitForWorkersToBeRunning() {\n\tEventually(func() bool {\n\t\tworkers := flyTable(\"workers\")\n\t\tanyNotRunning := false\n\t\tfor _, worker := range workers {\n\n\t\t\tstate := worker[\"state\"]\n\n\t\t\tif state != \"running\" {\n\t\t\t\tanyNotRunning = true\n\t\t\t}\n\t\t}\n\n\t\treturn anyNotRunning\n\t}).Should(BeFalse())\n}\n\nfunc workersWithContainers() []string {\n\tclient := concourseClient()\n\tcontainers, err := client.ListContainers(map[string]string{})\n\tExpect(err).NotTo(HaveOccurred())\n\n\tusedWorkers := map[string]struct{}{}\n\n\tfor _, container := range containers {\n\t\tusedWorkers[container.WorkerName] = struct{}{}\n\t}\n\n\tvar workerNames []string\n\tfor worker, _ := range usedWorkers {\n\t\tworkerNames = append(workerNames, worker)\n\t}\n\n\treturn workerNames\n}\n\nfunc containersBy(condition, value string) []string {\n\tcontainers := flyTable(\"containers\")\n\n\tvar handles []string\n\tfor _, c := range containers {\n\t\tif c[condition] == value {\n\t\t\thandles = append(handles, c[\"handle\"])\n\t\t}\n\t}\n\n\treturn handles\n}\n\nfunc volumesByResourceType(name string) []string {\n\tvolumes := flyTable(\"volumes\", \"-d\")\n\n\tvar handles []string\n\tfor _, v := range volumes {\n\t\tif v[\"type\"] == \"resource\" && strings.HasPrefix(v[\"identifier\"], \"name:\"+name) {\n\t\t\thandles = append(handles, v[\"handle\"])\n\t\t}\n\t}\n\n\treturn handles\n}\n<commit_msg>fix another capture group<commit_after>package topgun_test\n\nimport (\n\t\"crypto\/tls\"\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"golang.org\/x\/oauth2\"\n\n\t\"code.cloudfoundry.org\/lager\"\n\t\"code.cloudfoundry.org\/lager\/lagertest\"\n\n\tgclient \"code.cloudfoundry.org\/garden\/client\"\n\tgconn \"code.cloudfoundry.org\/garden\/client\/connection\"\n\tsq \"github.com\/Masterminds\/squirrel\"\n\t\"github.com\/concourse\/atc\"\n\t\"github.com\/concourse\/go-concourse\/concourse\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\n\t\"strconv\"\n\t\"testing\"\n)\n\nvar (\n\tdeploymentName, flyTarget string\n\tjobInstances              map[string][]boshInstance\n\n\tdbInstance *boshInstance\n\tdbConn     *sql.DB\n\n\tatcInstance    *boshInstance\n\tatcExternalURL string\n\n\tconcourseReleaseVersion, gardenRuncReleaseVersion string\n\tstemcellVersion                                   string\n\n\tpipelineName string\n\n\ttmpHome string\n\tflyBin  string\n\n\tlogger *lagertest.TestLogger\n\n\tboshLogs *gexec.Session\n)\n\nvar psql = sq.StatementBuilder.PlaceholderFormat(sq.Dollar)\n\nfunc TestTOPGUN(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"TOPGUN Suite\")\n}\n\nvar _ = SynchronizedBeforeSuite(func() []byte {\n\tflyBinPath, err := gexec.Build(\"github.com\/concourse\/fly\")\n\tExpect(err).ToNot(HaveOccurred())\n\n\treturn []byte(flyBinPath)\n}, func(data []byte) {\n\tflyBin = string(data)\n})\n\nvar _ = SynchronizedAfterSuite(func() {\n}, func() {\n\tgexec.CleanupBuildArtifacts()\n})\n\nvar _ = BeforeEach(func() {\n\tSetDefaultEventuallyTimeout(5 * time.Minute)\n\tSetDefaultEventuallyPollingInterval(time.Second)\n\tSetDefaultConsistentlyDuration(time.Minute)\n\tSetDefaultConsistentlyPollingInterval(time.Second)\n\n\tlogger = lagertest.NewTestLogger(\"test\")\n\n\tn, found := os.LookupEnv(\"TOPGUN_NETWORK_OFFSET\")\n\tvar networkOffset int\n\tvar err error\n\n\tif found {\n\t\tnetworkOffset, err = strconv.Atoi(n)\n\t}\n\tExpect(err).NotTo(HaveOccurred())\n\n\tconcourseReleaseVersion = os.Getenv(\"CONCOURSE_RELEASE_VERSION\")\n\tif concourseReleaseVersion == \"\" {\n\t\tconcourseReleaseVersion = \"latest\"\n\t}\n\n\tgardenRuncReleaseVersion = os.Getenv(\"GARDEN_RUNC_RELEASE_VERSION\")\n\tif gardenRuncReleaseVersion == \"\" {\n\t\tgardenRuncReleaseVersion = \"latest\"\n\t}\n\n\tstemcellVersion = os.Getenv(\"STEMCELL_VERSION\")\n\tif stemcellVersion == \"\" {\n\t\tstemcellVersion = \"latest\"\n\t}\n\n\tdeploymentNumber := GinkgoParallelNode() + (networkOffset * 4)\n\n\tdeploymentName = fmt.Sprintf(\"concourse-topgun-%d\", deploymentNumber)\n\tflyTarget = deploymentName\n\n\tbosh(\"delete-deployment\")\n\n\tjobInstances = map[string][]boshInstance{}\n\n\tdbInstance = nil\n\tdbConn = nil\n\tatcInstance = nil\n\tatcExternalURL = \"\"\n})\n\nvar _ = AfterEach(func() {\n\tboshLogs.Signal(os.Interrupt)\n\t<-boshLogs.Exited\n\tboshLogs = nil\n\n\tdeleteAllContainers()\n\n\tbosh(\"delete-deployment\")\n})\n\nfunc StartDeploy(manifest string, operations ...string) *gexec.Session {\n\topFlags := []string{}\n\tfor _, op := range operations {\n\t\topFlags = append(opFlags, fmt.Sprintf(\"-o=%s\", op))\n\t}\n\n\treturn spawnBosh(\n\t\tappend([]string{\n\t\t\t\"deploy\", manifest,\n\t\t\t\"-v\", \"deployment-name=\" + deploymentName,\n\t\t\t\"-v\", \"concourse-release-version=\" + concourseReleaseVersion,\n\t\t\t\"-v\", \"garden-runc-release-version=\" + gardenRuncReleaseVersion,\n\n\t\t\t\/\/ 3363.10 becomes 3363.1 as it's floating point; quotes prevent that\n\t\t\t\"-v\", \"stemcell-version='\" + stemcellVersion + \"'\",\n\t\t}, opFlags...)...,\n\t)\n}\n\nfunc Deploy(manifest string, operations ...string) {\n\twait(StartDeploy(manifest, operations...))\n\n\tjobInstances = loadJobInstances()\n\n\tatcInstance = JobInstance(\"atc\")\n\tatcExternalURL = fmt.Sprintf(\"http:\/\/%s:8080\", atcInstance.IP)\n\n\tdbInstance = JobInstance(\"postgresql\")\n\n\tvar err error\n\tdbConn, err = sql.Open(\"postgres\", fmt.Sprintf(\"postgres:\/\/atc:dummy-password@%s:5432\/atc?sslmode=disable\", dbInstance.IP))\n\tExpect(err).ToNot(HaveOccurred())\n\n\t\/\/ give some time for atc to bootstrap (run migrations, etc)\n\tEventually(func() int {\n\t\tflySession := spawnFly(\"login\", \"-c\", atcExternalURL)\n\t\t<-flySession.Exited\n\t\treturn flySession.ExitCode()\n\t}, 2*time.Minute).Should(Equal(0))\n\n\tboshLogs = spawnBosh(\"logs\", \"-f\")\n}\n\nfunc JobInstance(job string) *boshInstance {\n\tis := jobInstances[job]\n\tif len(is) == 0 {\n\t\treturn nil\n\t}\n\n\treturn &is[0]\n}\n\nfunc JobInstances(instance string) []boshInstance {\n\treturn jobInstances[instance]\n}\n\ntype boshInstance struct {\n\tName string\n\tIP   string\n}\n\nvar instanceRow = regexp.MustCompile(`^([^\\s]+)\\s+-\\s+(\\w+)\\s+z1\\s+([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+)\\s*$`)\nvar jobRow = regexp.MustCompile(`^([^\\s]+)\\s+(\\w+)\\s+(\\w+)\\s+-\\s+-\\s*$`)\n\nfunc loadJobInstances() map[string][]boshInstance {\n\tsession := spawnBosh(\"instances\", \"-p\")\n\t<-session.Exited\n\tExpect(session.ExitCode()).To(Equal(0))\n\n\toutput := string(session.Out.Contents())\n\n\tjobInstances := map[string][]boshInstance{}\n\n\tlines := strings.Split(output, \"\\n\")\n\tvar instance boshInstance\n\tfor _, line := range lines {\n\t\tinstanceMatch := instanceRow.FindStringSubmatch(line)\n\t\tif len(instanceMatch) > 0 {\n\t\t\tinstance = boshInstance{\n\t\t\t\tName: instanceMatch[1],\n\t\t\t\tIP:   instanceMatch[3],\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tjobMatch := jobRow.FindStringSubmatch(line)\n\t\tif len(jobMatch) > 0 {\n\t\t\tjobName := jobMatch[2]\n\t\t\tjobInstances[jobName] = append(jobInstances[jobName], instance)\n\t\t}\n\t}\n\n\treturn jobInstances\n}\n\nfunc bosh(argv ...string) {\n\twait(spawnBosh(argv...))\n}\n\nfunc spawnBosh(argv ...string) *gexec.Session {\n\treturn spawn(\"bosh\", append([]string{\"-n\", \"-d\", deploymentName}, argv...)...)\n}\n\nfunc fly(argv ...string) {\n\twait(spawnFly(argv...))\n}\n\nfunc concourseClient() concourse.Client {\n\ttoken, err := getATCToken(atcExternalURL)\n\tExpect(err).NotTo(HaveOccurred())\n\thttpClient := oauthClient(token)\n\treturn concourse.NewClient(atcExternalURL, httpClient)\n}\n\nfunc deleteAllContainers() {\n\tclient := concourseClient()\n\tworkers, err := client.ListWorkers()\n\tExpect(err).NotTo(HaveOccurred())\n\n\tcontainers, err := client.ListContainers(map[string]string{})\n\tExpect(err).NotTo(HaveOccurred())\n\n\tfor _, worker := range workers {\n\t\tconnection := gconn.New(\"tcp\", worker.GardenAddr)\n\t\tgardenClient := gclient.New(connection)\n\t\tfor _, container := range containers {\n\t\t\tif container.WorkerName == worker.Name {\n\t\t\t\terr = gardenClient.Destroy(container.ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(\"failed-to-delete-container\", err, lager.Data{\"handle\": container.ID})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc flyHijackTask(argv ...string) *gexec.Session {\n\tcmd := exec.Command(flyBin, append([]string{\"-t\", flyTarget, \"hijack\"}, argv...)...)\n\thijackIn, err := cmd.StdinPipe()\n\tExpect(err).NotTo(HaveOccurred())\n\n\thijackS, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)\n\tExpect(err).ToNot(HaveOccurred())\n\n\tEventually(func() bool {\n\t\ttaskMatcher := gbytes.Say(\"type: task\")\n\t\tmatched, err := taskMatcher.Match(hijackS)\n\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\tif matched {\n\t\t\tre, err := regexp.Compile(\"([0-9]): .+ type: task\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\ttaskNumber := re.FindStringSubmatch(string(hijackS.Out.Contents()))[1]\n\t\t\tfmt.Fprintln(hijackIn, taskNumber)\n\n\t\t\treturn true\n\t\t}\n\n\t\treturn hijackS.ExitCode() == 0\n\t}).Should(BeTrue())\n\n\treturn hijackS\n}\n\nfunc spawnFly(argv ...string) *gexec.Session {\n\treturn spawn(flyBin, append([]string{\"-t\", flyTarget}, argv...)...)\n}\n\nfunc spawnFlyInteractive(stdin io.Reader, argv ...string) *gexec.Session {\n\treturn spawnInteractive(stdin, flyBin, append([]string{\"-t\", flyTarget}, argv...)...)\n}\n\nfunc run(argc string, argv ...string) {\n\twait(spawn(argc, argv...))\n}\n\nfunc spawn(argc string, argv ...string) *gexec.Session {\n\tBy(\"running: \" + argc + \" \" + strings.Join(argv, \" \"))\n\tcmd := exec.Command(argc, argv...)\n\tsession, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)\n\tExpect(err).ToNot(HaveOccurred())\n\treturn session\n}\n\nfunc spawnInteractive(stdin io.Reader, argc string, argv ...string) *gexec.Session {\n\tBy(\"interactively running: \" + argc + \" \" + strings.Join(argv, \" \"))\n\tcmd := exec.Command(argc, argv...)\n\tcmd.Stdin = stdin\n\tsession, err := gexec.Start(cmd, GinkgoWriter, GinkgoWriter)\n\tExpect(err).ToNot(HaveOccurred())\n\treturn session\n}\n\nfunc wait(session *gexec.Session) {\n\t<-session.Exited\n\tExpect(session.ExitCode()).To(Equal(0))\n}\n\nfunc getATCToken(atcURL string) (*atc.AuthToken, error) {\n\tresponse, err := http.Get(atcURL + \"\/api\/v1\/teams\/main\/auth\/token\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar token *atc.AuthToken\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(body, &token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn token, nil\n}\n\nfunc oauthClient(atcToken *atc.AuthToken) *http.Client {\n\treturn &http.Client{\n\t\tTransport: &oauth2.Transport{\n\t\t\tSource: oauth2.StaticTokenSource(&oauth2.Token{\n\t\t\t\tTokenType:   atcToken.Type,\n\t\t\t\tAccessToken: atcToken.Value,\n\t\t\t}),\n\t\t\tBase: &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc waitForLandingOrLandedWorker() string {\n\treturn waitForWorkerInState(\"landing\", \"landed\")\n}\n\nfunc waitForRunningWorker() string {\n\treturn waitForWorkerInState(\"running\")\n}\n\nfunc waitForStalledWorker() string {\n\treturn waitForWorkerInState(\"stalled\")\n}\n\nfunc waitForWorkerInState(desiredStates ...string) string {\n\tvar workerName string\n\tEventually(func() string {\n\n\t\tworkers := flyTable(\"workers\")\n\n\t\tfor _, worker := range workers {\n\t\t\tname := worker[\"name\"]\n\t\t\tstate := worker[\"state\"]\n\n\t\t\tanyMatched := false\n\t\t\tfor _, desiredState := range desiredStates {\n\t\t\t\tif state == desiredState {\n\t\t\t\t\tanyMatched = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !anyMatched {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif workerName != \"\" {\n\t\t\t\tFail(\"multiple workers in states: \" + strings.Join(desiredStates, \", \"))\n\t\t\t}\n\n\t\t\tworkerName = name\n\t\t}\n\n\t\treturn workerName\n\t}).ShouldNot(BeEmpty())\n\n\treturn workerName\n}\n\nfunc flyTable(argv ...string) []map[string]string {\n\tsession := spawnFly(append([]string{\"--print-table-headers\"}, argv...)...)\n\t<-session.Exited\n\tExpect(session.ExitCode()).To(Equal(0))\n\n\tresult := []map[string]string{}\n\tvar headers []string\n\n\trows := strings.Split(string(session.Out.Contents()), \"\\n\")\n\tfor i, row := range rows {\n\t\tif i == 0 {\n\t\t\theaders = splitFlyColumns(row)\n\t\t\tcontinue\n\t\t}\n\t\tif row == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = append(result, map[string]string{})\n\t\tcolumns := splitFlyColumns(row)\n\n\t\tExpect(columns).To(HaveLen(len(headers)))\n\n\t\tfor j, header := range headers {\n\t\t\tif header == \"\" || columns[j] == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult[i-1][header] = columns[j]\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc splitFlyColumns(row string) []string {\n\treturn regexp.MustCompile(`\\s{2,}`).Split(strings.TrimSpace(row), -1)\n}\n\nfunc waitForWorkersToBeRunning() {\n\tEventually(func() bool {\n\t\tworkers := flyTable(\"workers\")\n\t\tanyNotRunning := false\n\t\tfor _, worker := range workers {\n\n\t\t\tstate := worker[\"state\"]\n\n\t\t\tif state != \"running\" {\n\t\t\t\tanyNotRunning = true\n\t\t\t}\n\t\t}\n\n\t\treturn anyNotRunning\n\t}).Should(BeFalse())\n}\n\nfunc workersWithContainers() []string {\n\tclient := concourseClient()\n\tcontainers, err := client.ListContainers(map[string]string{})\n\tExpect(err).NotTo(HaveOccurred())\n\n\tusedWorkers := map[string]struct{}{}\n\n\tfor _, container := range containers {\n\t\tusedWorkers[container.WorkerName] = struct{}{}\n\t}\n\n\tvar workerNames []string\n\tfor worker, _ := range usedWorkers {\n\t\tworkerNames = append(workerNames, worker)\n\t}\n\n\treturn workerNames\n}\n\nfunc containersBy(condition, value string) []string {\n\tcontainers := flyTable(\"containers\")\n\n\tvar handles []string\n\tfor _, c := range containers {\n\t\tif c[condition] == value {\n\t\t\thandles = append(handles, c[\"handle\"])\n\t\t}\n\t}\n\n\treturn handles\n}\n\nfunc volumesByResourceType(name string) []string {\n\tvolumes := flyTable(\"volumes\", \"-d\")\n\n\tvar handles []string\n\tfor _, v := range volumes {\n\t\tif v[\"type\"] == \"resource\" && strings.HasPrefix(v[\"identifier\"], \"name:\"+name) {\n\t\t\thandles = append(handles, v[\"handle\"])\n\t\t}\n\t}\n\n\treturn handles\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"github.com\/cloudfoundry\/cli\/plugin\"\n\t\/\/\"github.com\/cloudfoundry\/cli\/plugin\/models\"\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\/\/\"reflect\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar ENDPOINTS = [3]string{\"https:\/\/api.ng.bluemix.net\", \"https:\/\/api.au-syd.bluemix.net\", \"https:\/\/api.eu-gb.bluemix.net\"}\n\n\/*\n*\tThis is the struct implementing the interface defined by the core CLI. It can\n*\tbe found at  \"github.com\/cloudfoundry\/cli\/plugin\/plugin.go\"\n*\n *\/\ntype BCSyncPlugin struct{}\n\ntype CloudantCreds struct {\n\tusername string\n\tpassword string\n\turl      string\n\tcookie   string\n}\n\n\/*\n*\tThis function must be implemented by any plugin because it is part of the\n*\tplugin interface defined by the core CLI.\n*\n*\tRun(....) is the entry point when the core CLI is invoking a command defined\n*\tby a plugin. The first parameter, plugin.CliConnection, is a struct that can\n*\tbe used to invoke cli commands. The second paramter, args, is a slice of\n*\tstrings. args[0] will be the name of the command, and will be followed by\n*\tany additional arguments a cli user typed in.\n*\n*\tAny error handling should be handled with the plugin itself (this means printing\n*\tuser facing errors). The CLI will exit 0 if the plugin exits 0 and will exit\n*\t1 should the plugin exits nonzero.\n *\/\nfunc (c *BCSyncPlugin) Run(cliConnection plugin.CliConnection, args []string) {\n\tvar appName string\n\tif len(args) > 1 {\n\t\tappName = args[1]\n\t} else {\n\t\tappName = getAppName(cliConnection)\n\t}\n\tvar httpClient = &http.Client{}\n\tcloudantAccounts, err := getCloudantAccounts(cliConnection, httpClient, appName)\n\tif err != nil {\n\t\treturn\n\t}\n\tdeleteCookies(httpClient, cloudantAccounts)\n}\n\n\/*\nfunc initialPrompt() (string, string){\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"\\nWhich app's databases would you like to sync?\")\n\tappName, _ := reader.ReadString('\\n')\n\tappName = strings.TrimRight(appName, \"\\n\")\n\n}\n*\/\n\nfunc getAppName(cliConnection plugin.CliConnection) string {\n\treader := bufio.NewReader(os.Stdin)\n\tapps_list, _ := cliConnection.GetApps()\n\tfmt.Println(\"\\nCurrent apps:\\n\")\n\tfor i := 0; i < len(apps_list); i++ {\n\t\tfmt.Println(apps_list[i].Name)\n\t}\n\tfmt.Println(\"\\nWhich app's databases would you like to sync?\")\n\tappName, _ := reader.ReadString('\\n')\n\tappName = strings.TrimRight(appName, \"\\n\")\n\tfmt.Println(\"\\n\")\n\treturn appName\n}\n\nfunc deleteCookies(httpClient *http.Client, cloudantAccounts [3]CloudantCreds) {\n\tfor i := 0; i < len(cloudantAccounts); i++ {\n\t\tcred := cloudantAccounts[i]\n\t\turl := \"http:\/\/\" + cred.username + \".cloudant.com\/_session\"\n\t\tbody := \"name=\" + cred.username + \"&password=\" + cred.password\n\t\treq, err := http.NewRequest(\"POST\", url, bytes.NewBufferString(body))\n\t\treq.Header.Set(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\t\treq.Header.Set(\"Cookie\", cred.cookie)\n\t\tresp, err := httpClient.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\t\/\/Just for debugging purposes\n\t\tfmt.Println(\"response Status:\", resp.Status)\n\t\tfmt.Println(\"response Headers:\", resp.Header)\n\t\trespBody, _ := ioutil.ReadAll(resp.Body)\n\t\tfmt.Println(\"response Body:\", string(respBody))\n\t\tresp.Body.Close()\n\t}\n}\n\nfunc getCloudantAccounts(cliConnection plugin.CliConnection, httpClient *http.Client, appName string) ([3]CloudantCreds, error) {\n\tvar cloudantAccounts [3]CloudantCreds\n\tfor i := 0; i < len(ENDPOINTS); i++ {\n\t\tcliConnection.CliCommand(\"api\", ENDPOINTS[i])\n\t\tcliConnection.CliCommand(\"login\")\n\t\tcred, err := getCreds(cliConnection, appName)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tfmt.Println(\"Make sure that you are giving is a valid app IN ALL REGIONS and try again\")\n\t\t\treturn cloudantAccounts, err\n\t\t}\n\t\tcred.cookie = getCookie(cred, httpClient)\n\t\tcloudantAccounts[i] = cred\n\t}\n\treturn cloudantAccounts, nil\n}\n\nfunc getCreds(cliConnection plugin.CliConnection, appName string) (CloudantCreds, error) {\n\tvar creds CloudantCreds\n\tenv, err := cliConnection.CliCommandWithoutTerminalOutput(\"env\", appName)\n\tif err != nil {\n\t\treturn creds, err\n\t}\n\tfor i := 0; i < len(env); i++ {\n\t\tif strings.Index(env[i], \"cloudantNoSQLDB\") != -1 {\n\t\t\tuser_reg, _ := regexp.Compile(\"\\\"username\\\": \\\"([\\x00-\\x7F]+)\\\"\")\n\t\t\tpass_reg, _ := regexp.Compile(\"\\\"password\\\": \\\"([\\x00-\\x7F]+)\\\"\")\n\t\t\turl_reg, _ := regexp.Compile(\"\\\"url\\\": \\\"([\\x00-\\x7F]+)\\\"\")\n\t\t\tcreds.username = strings.Split(user_reg.FindString(env[i]), \"\\\"\")[3]\n\t\t\tcreds.password = strings.Split(pass_reg.FindString(env[i]), \"\\\"\")[3]\n\t\t\tcreds.url = strings.Split(url_reg.FindString(env[i]), \"\\\"\")[3]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn creds, nil\n}\n\nfunc getCookie(cred CloudantCreds, httpClient *http.Client) string {\n\turl := \"http:\/\/\" + cred.username + \".cloudant.com\/_session\"\n\treqBody := \"name=\" + cred.username + \"&password=\" + cred.password\n\tfmt.Println(reqBody)\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBufferString(reqBody))\n\treq.Header.Set(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t\/\/Just for debugging purposes\n\tfmt.Println(\"response Status:\", resp.Status)\n\tfmt.Println(\"response Headers:\", resp.Header)\n\trespBody, _ := ioutil.ReadAll(resp.Body)\n\tfmt.Println(\"response Body:\", string(respBody))\n\tresp.Body.Close()\n\tcookie := resp.Header.Get(\"Set-Cookie\")\n\treturn cookie\n}\n\n\/*\n\/\/Did not need to look for the service in this manner since the service credentials are with the app and not the service itself\n\/\/plus, the app only had user definied environment variables associated with it in the GetAppModel.\nfunc getCloudantServices(cliConnection plugin.CliConnection, app plugin_models.GetAppModel) plugin_models.GetService_Model {\n\tvar cloudantService plugin_models.GetService_Model\n\tservices := app.Services\n\tfor i := 0; i < len(services); i++ {\n\t\ts, _ := cliConnection.GetService(services[i].Name)\n\t\tif s.ServiceOffering.Name == \"cloudantNoSQLDB\" {\n\t\t\tfmt.Println(s.Name)\n\t\t\tfmt.Println(reflect.TypeOf(s))\n\t\t\tcloudantService = s\n\t\t\tbreak\n\t\t}\n\t}\n\treturn cloudantService\n}\n*\/\n\n\/*\n*\tThis function must be implemented as part of the\tplugin interface\n*\tdefined by the core CLI.\n*\n*\tGetMetadata() returns a PluginMetadata struct. The first field, Name,\n*\tdetermines the name of the plugin which should generally be without spaces.\n*\tIf there are spaces in the name a user will need to properly quote the name\n*\tduring uninstall otherwise the name will be treated as seperate arguments.\n*\tThe second value is a slice of Command structs. Our slice only contains one\n*\tCommand Struct, but could contain any number of them. The first field Name\n*\tdefines the command `cf basic-plugin-command` once installed into the CLI. The\n*\tsecond field, HelpText, is used by the core CLI to display help information\n*\tto the user in the core commands `cf help`, `cf`, or `cf -h`.\n *\/\nfunc (c *BCSyncPlugin) GetMetadata() plugin.PluginMetadata {\n\treturn plugin.PluginMetadata{\n\t\tName: \"bluemix-cloudant-sync\",\n\t\tVersion: plugin.VersionType{\n\t\t\tMajor: 1,\n\t\t\tMinor: 0,\n\t\t\tBuild: 0,\n\t\t},\n\t\tMinCliVersion: plugin.VersionType{\n\t\t\tMajor: 6,\n\t\t\tMinor: 7,\n\t\t\tBuild: 0,\n\t\t},\n\t\tCommands: []plugin.Command{\n\t\t\tplugin.Command{\n\t\t\t\tName:     \"sync-app-dbs\",\n\t\t\t\tHelpText: \"synchronizes Cloudant databases for multi-regional apps\",\n\n\t\t\t\t\/\/ UsageDetails is optional\n\t\t\t\t\/\/ It is used to show help of usage of each command\n\t\t\t\tUsageDetails: plugin.Usage{\n\t\t\t\t\tUsage: \"sync-app-dbs\\n   cf sync-app-dbs\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\n\/*\n* Unlike most Go programs, the `Main()` function will not be used to run all of the\n* commands provided in your plugin. Main will be used to initialize the plugin\n* process, as well as any dependencies you might require for your\n* plugin.\n *\/\nfunc main() {\n\t\/\/ Any initialization for your plugin can be handled here\n\t\/\/\n\t\/\/ Note: to run the plugin.Start method, we pass in a pointer to the struct\n\t\/\/ implementing the interface defined at \"github.com\/cloudfoundry\/cli\/plugin\/plugin.go\"\n\t\/\/\n\t\/\/ Note: The plugin's main() method is invoked at install time to collect\n\t\/\/ metadata. The plugin will exit 0 and the Run([]string) method will not be\n\t\/\/ invoked.\n\tplugin.Start(new(BCSyncPlugin))\n\t\/\/ Plugin code should be written in the Run([]string) method,\n\t\/\/ ensuring the plugin environment is bootstrapped.\n}\n<commit_msg>modifies permissions for databases<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"github.com\/cloudfoundry\/cli\/plugin\"\n\t\/\/\"github.com\/cloudfoundry\/cli\/plugin\/models\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\/\/\"reflect\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar ENDPOINTS = []string{\"https:\/\/api.ng.bluemix.net\", \"https:\/\/api.au-syd.bluemix.net\", \"https:\/\/api.eu-gb.bluemix.net\"}\n\n\/*\n*\tThis is the struct implementing the interface defined by the core CLI. It can\n*\tbe found at  \"github.com\/cloudfoundry\/cli\/plugin\/plugin.go\"\n*\n *\/\ntype BCSyncPlugin struct{}\n\ntype CloudantCreds struct {\n\tusername string\n\tpassword string\n\turl      string\n\tcookie   string\n}\n\n\/*\n*\tThis function must be implemented by any plugin because it is part of the\n*\tplugin interface defined by the core CLI.\n*\n*\tRun(....) is the entry point when the core CLI is invoking a command defined\n*\tby a plugin. The first parameter, plugin.CliConnection, is a struct that can\n*\tbe used to invoke cli commands. The second paramter, args, is a slice of\n*\tstrings. args[0] will be the name of the command, and will be followed by\n*\tany additional arguments a cli user typed in.\n*\n*\tAny error handling should be handled with the plugin itself (this means printing\n*\tuser facing errors). The CLI will exit 0 if the plugin exits 0 and will exit\n*\t1 should the plugin exits nonzero.\n *\/\nfunc (c *BCSyncPlugin) Run(cliConnection plugin.CliConnection, args []string) {\n\tif args[0] == \"sync-app-dbs\" {\n\t\tvar appName string\n\t\tif len(args) > 1 {\n\t\t\tappName = args[1]\n\t\t} else {\n\t\t\tappName = getAppName(cliConnection)\n\t\t}\n\t\tvar httpClient = &http.Client{}\n\t\tcloudantAccounts, err := getCloudantAccounts(cliConnection, httpClient, appName)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdb := getDatabase(httpClient, cloudantAccounts[0])\n\t\t\/\/createReplicatorDatabases(httpClient, cloudantAccounts)\n\t\tshareDatabases(db, httpClient, cloudantAccounts)\n\t\tdeleteCookies(httpClient, cloudantAccounts)\n\t}\n}\n\n\/*\nfunc initialPrompt() (string, string){\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"\\nWhich app's databases would you like to sync?\")\n\tappName, _ := reader.ReadString('\\n')\n\tappName = strings.TrimRight(appName, \"\\n\")\n\n}\n*\/\n\nfunc createReplicatorDatabases(httpClient *http.Client, cloudantAccounts []CloudantCreds) {\n\tfor i := 0; i < len(cloudantAccounts); i++ {\n\t\tcred := cloudantAccounts[i]\n\t\turl := \"http:\/\/\" + cred.username + \".cloudant.com\/_replicator\"\n\t\treq, _ := http.NewRequest(\"POST\", url, bytes.NewBufferString(\"\"))\n\t\treq.Header.Set(\"Cookie\", cred.cookie)\n\t\tresp, _ := httpClient.Do(req)\n\t\tfmt.Println(\"response Status:\", resp.Status)\n\t\tfmt.Println(\"response Headers:\", resp.Header)\n\t\trespBody, _ := ioutil.ReadAll(resp.Body)\n\t\tfmt.Println(\"response Body:\", string(respBody))\n\t\tresp.Body.Close()\n\t}\n}\n\nfunc shareDatabases(db string, httpClient *http.Client, cloudantAccounts []CloudantCreds) {\n\tfor i := 0; i < len(cloudantAccounts); i++ {\n\t\tcred := cloudantAccounts[i]\n\t\turl := \"http:\/\/\" + cred.username + \".cloudant.com\/_api\/v2\/db\/\" + db + \"\/_security\"\n\t\treq, _ := http.NewRequest(\"GET\", url, bytes.NewBufferString(\"\"))\n\t\treq.Header.Set(\"Cookie\", cred.cookie)\n\t\tfmt.Println(\"\\nRetrieving permissions\")\n\t\tresp, _ := httpClient.Do(req)\n\t\tfmt.Println(\"response Status:\", resp.Status)\n\t\tfmt.Println(\"response Headers:\", resp.Header)\n\t\trespBody, _ := ioutil.ReadAll(resp.Body)\n\t\tfmt.Println(\"response Body:\", string(respBody))\n\t\tperms := string(respBody)\n\t\tresp.Body.Close()\n\t\tvar parsed map[string]interface{}\n\t\tjson.Unmarshal([]byte(perms), &parsed)\n\t\tfor j := 0; j < len(cloudantAccounts); j++ {\n\t\t\tif i != j {\n\t\t\t\ttemp_parsed := parsed[\"cloudant\"].(map[string]interface{})\n\t\t\t\ttemp_parsed[cloudantAccounts[j].username] = []string{\"_reader\", \"_replicator\"}\n\t\t\t\tparsed[\"cloudant\"] = map[string]interface{}(temp_parsed)\n\t\t\t}\n\t\t}\n\t\tbd, _ := json.MarshalIndent(parsed, \" \", \"  \")\n\t\tbody := string(bd)\n\t\tsharereq, _ := http.NewRequest(\"PUT\", url, bytes.NewBufferString(body))\n\t\tsharereq.Header.Set(\"Cookie\", cred.cookie)\n\t\tsharereq.Header.Set(\"Content-Type\", \"application\/json\")\n\t\tfmt.Println(\"\\nSending new permissions\")\n\t\tshareresp, _ := httpClient.Do(sharereq)\n\t\tfmt.Println(\"response Status:\", shareresp.Status)\n\t\tfmt.Println(\"response Headers:\", shareresp.Header)\n\t\tsharerespBody, _ := ioutil.ReadAll(shareresp.Body)\n\t\tfmt.Println(\"response Body:\", string(sharerespBody))\n\t\tresp.Body.Close()\n\t}\n}\n\nfunc getDatabase(httpClient *http.Client, cred CloudantCreds) string {\n\treader := bufio.NewReader(os.Stdin)\n\tdbs := getAllDatabases(httpClient, cred)\n\tfmt.Println(\"Current databases:\")\n\tfor i := 0; i < len(dbs); i++ {\n\t\tfmt.Println(dbs[i])\n\t}\n\tfmt.Println(\"\\nWhich database would you like to replicate?\")\n\tdb, _ := reader.ReadString('\\n')\n\tdb = strings.TrimRight(db, \"\\n\")\n\tfmt.Println()\n\treturn db\n}\n\nfunc getAllDatabases(httpClient *http.Client, cred CloudantCreds) []string {\n\turl := \"http:\/\/\" + cred.username + \".cloudant.com\/_all_dbs\"\n\treq, _ := http.NewRequest(\"GET\", url, bytes.NewBufferString(\"\"))\n\treq.Header.Set(\"Cookie\", cred.cookie)\n\tfmt.Println(\"\\nGetting database list\")\n\tresp, _ := httpClient.Do(req)\n\t\/\/Just for debugging purposes\n\tfmt.Println(\"response Status:\", resp.Status)\n\tfmt.Println(\"response Headers:\", resp.Header)\n\trespBody, _ := ioutil.ReadAll(resp.Body)\n\tfmt.Println(\"response Body:\", string(respBody))\n\tdbsStr := string(respBody)\n\tdbsStr = strings.Replace(dbsStr, \",\", \" \", -1)\n\tdbsStr = strings.Replace(dbsStr, \"\\\"\", \"\", -1)\n\tdbsStr = strings.Replace(dbsStr, \"[\", \"\", 1)\n\tdbsStr = strings.Replace(dbsStr, \"]\", \"\", 1)\n\tdbs := strings.Fields(dbsStr)\n\tresp.Body.Close()\n\treturn dbs\n}\n\nfunc getAppName(cliConnection plugin.CliConnection) string {\n\treader := bufio.NewReader(os.Stdin)\n\tapps_list, _ := cliConnection.GetApps()\n\tfmt.Println(\"\\nCurrent apps:\\n\")\n\tfor i := 0; i < len(apps_list); i++ {\n\t\tfmt.Println(apps_list[i].Name)\n\t}\n\tfmt.Println(\"\\nWhich app's databases would you like to sync?\")\n\tappName, _ := reader.ReadString('\\n')\n\tappName = strings.TrimRight(appName, \"\\n\")\n\tfmt.Println(\"\\n\")\n\treturn appName\n}\n\nfunc deleteCookies(httpClient *http.Client, cloudantAccounts []CloudantCreds) {\n\tfor i := 0; i < len(cloudantAccounts); i++ {\n\t\tcred := cloudantAccounts[i]\n\t\turl := \"http:\/\/\" + cred.username + \".cloudant.com\/_session\"\n\t\tbody := \"name=\" + cred.username + \"&password=\" + cred.password\n\t\treq, err := http.NewRequest(\"POST\", url, bytes.NewBufferString(body))\n\t\treq.Header.Set(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\t\treq.Header.Set(\"Cookie\", cred.cookie)\n\t\tfmt.Println(\"\\nDeleting Cookie\")\n\t\tresp, err := httpClient.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t\t\/\/Just for debugging purposes\n\t\tfmt.Println(\"response Status:\", resp.Status)\n\t\tfmt.Println(\"response Headers:\", resp.Header)\n\t\trespBody, _ := ioutil.ReadAll(resp.Body)\n\t\tfmt.Println(\"response Body:\", string(respBody))\n\t\tresp.Body.Close()\n\t}\n}\n\nfunc getCloudantAccounts(cliConnection plugin.CliConnection, httpClient *http.Client, appName string) ([]CloudantCreds, error) {\n\tcloudantAccounts := make([]CloudantCreds, len(ENDPOINTS))\n\tfor i := 0; i < len(ENDPOINTS); i++ {\n\t\tcliConnection.CliCommand(\"api\", ENDPOINTS[i])\n\t\tcliConnection.CliCommand(\"login\")\n\t\tcred, err := getCreds(cliConnection, appName)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tfmt.Println(\"Make sure that you are giving is a valid app IN ALL REGIONS and try again\")\n\t\t\treturn cloudantAccounts, err\n\t\t}\n\t\tcred.cookie = getCookie(cred, httpClient)\n\t\tcloudantAccounts[i] = cred\n\t}\n\treturn cloudantAccounts, nil\n}\n\nfunc getCreds(cliConnection plugin.CliConnection, appName string) (CloudantCreds, error) {\n\tvar creds CloudantCreds\n\tenv, err := cliConnection.CliCommandWithoutTerminalOutput(\"env\", appName)\n\tif err != nil {\n\t\treturn creds, err\n\t}\n\tfor i := 0; i < len(env); i++ {\n\t\tif strings.Index(env[i], \"cloudantNoSQLDB\") != -1 {\n\t\t\tuser_reg, _ := regexp.Compile(\"\\\"username\\\": \\\"([\\x00-\\x7F]+)\\\"\")\n\t\t\tpass_reg, _ := regexp.Compile(\"\\\"password\\\": \\\"([\\x00-\\x7F]+)\\\"\")\n\t\t\turl_reg, _ := regexp.Compile(\"\\\"url\\\": \\\"([\\x00-\\x7F]+)\\\"\")\n\t\t\tcreds.username = strings.Split(user_reg.FindString(env[i]), \"\\\"\")[3]\n\t\t\tcreds.password = strings.Split(pass_reg.FindString(env[i]), \"\\\"\")[3]\n\t\t\tcreds.url = strings.Split(url_reg.FindString(env[i]), \"\\\"\")[3]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn creds, nil\n}\n\nfunc getCookie(cred CloudantCreds, httpClient *http.Client) string {\n\turl := \"http:\/\/\" + cred.username + \".cloudant.com\/_session\"\n\treqBody := \"name=\" + cred.username + \"&password=\" + cred.password\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBufferString(reqBody))\n\treq.Header.Set(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\tfmt.Println(\"\\nGetting cookie\")\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t\/\/Just for debugging purposes\n\tfmt.Println(\"response Status:\", resp.Status)\n\tfmt.Println(\"response Headers:\", resp.Header)\n\trespBody, _ := ioutil.ReadAll(resp.Body)\n\tfmt.Println(\"response Body:\", string(respBody))\n\tcookie := resp.Header.Get(\"Set-Cookie\")\n\tresp.Body.Close()\n\treturn cookie\n}\n\n\/*\n\/\/Did not need to look for the service in this manner since the service credentials are with the app and not the service itself\n\/\/plus, the app only had user definied environment variables associated with it in the GetAppModel.\nfunc getCloudantServices(cliConnection plugin.CliConnection, app plugin_models.GetAppModel) plugin_models.GetService_Model {\n\tvar cloudantService plugin_models.GetService_Model\n\tservices := app.Services\n\tfor i := 0; i < len(services); i++ {\n\t\ts, _ := cliConnection.GetService(services[i].Name)\n\t\tif s.ServiceOffering.Name == \"cloudantNoSQLDB\" {\n\t\t\tfmt.Println(s.Name)\n\t\t\tfmt.Println(reflect.TypeOf(s))\n\t\t\tcloudantService = s\n\t\t\tbreak\n\t\t}\n\t}\n\treturn cloudantService\n}\n*\/\n\n\/*\n*\tThis function must be implemented as part of the\tplugin interface\n*\tdefined by the core CLI.\n*\n*\tGetMetadata() returns a PluginMetadata struct. The first field, Name,\n*\tdetermines the name of the plugin which should generally be without spaces.\n*\tIf there are spaces in the name a user will need to properly quote the name\n*\tduring uninstall otherwise the name will be treated as seperate arguments.\n*\tThe second value is a slice of Command structs. Our slice only contains one\n*\tCommand Struct, but could contain any number of them. The first field Name\n*\tdefines the command `cf basic-plugin-command` once installed into the CLI. The\n*\tsecond field, HelpText, is used by the core CLI to display help information\n*\tto the user in the core commands `cf help`, `cf`, or `cf -h`.\n *\/\nfunc (c *BCSyncPlugin) GetMetadata() plugin.PluginMetadata {\n\treturn plugin.PluginMetadata{\n\t\tName: \"bluemix-cloudant-sync\",\n\t\tVersion: plugin.VersionType{\n\t\t\tMajor: 1,\n\t\t\tMinor: 0,\n\t\t\tBuild: 0,\n\t\t},\n\t\tMinCliVersion: plugin.VersionType{\n\t\t\tMajor: 6,\n\t\t\tMinor: 7,\n\t\t\tBuild: 0,\n\t\t},\n\t\tCommands: []plugin.Command{\n\t\t\tplugin.Command{\n\t\t\t\tName:     \"sync-app-dbs\",\n\t\t\t\tHelpText: \"synchronizes Cloudant databases for multi-regional apps\",\n\n\t\t\t\t\/\/ UsageDetails is optional\n\t\t\t\t\/\/ It is used to show help of usage of each command\n\t\t\t\tUsageDetails: plugin.Usage{\n\t\t\t\t\tUsage: \"sync-app-dbs\\n   cf sync-app-dbs\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\n\/*\n* Unlike most Go programs, the `Main()` function will not be used to run all of the\n* commands provided in your plugin. Main will be used to initialize the plugin\n* process, as well as any dependencies you might require for your\n* plugin.\n *\/\nfunc main() {\n\t\/\/ Any initialization for your plugin can be handled here\n\t\/\/\n\t\/\/ Note: to run the plugin.Start method, we pass in a pointer to the struct\n\t\/\/ implementing the interface defined at \"github.com\/cloudfoundry\/cli\/plugin\/plugin.go\"\n\t\/\/\n\t\/\/ Note: The plugin's main() method is invoked at install time to collect\n\t\/\/ metadata. The plugin will exit 0 and the Run([]string) method will not be\n\t\/\/ invoked.\n\tplugin.Start(new(BCSyncPlugin))\n\t\/\/ Plugin code should be written in the Run([]string) method,\n\t\/\/ ensuring the plugin environment is bootstrapped.\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/jessevdk\/go-flags\"\n)\n\ntype Option struct {\n\tDelimiter string `short:\"d\" long:\"delimiter\" default:\"\"`\n\tUseRegexp bool   `short:\"r\" long:\"regexp\"    default:\"false\"`\n\tCount     int    `short:\"c\" long:\"count\"     default:\"-1\"`\n\tMargin    string `short:\"m\" long:\"margin\"    default:\"1:1\"`\n\tJustify   string `short:\"j\" long:\"justify\"   default:\"l\"`\n\tIsHelp    bool   `short:\"h\" long:\"help\"      default:\"false\"`\n\tIsVersion bool   `          long:\"version\"   default:\"false\"`\n\tFiles     []string\n}\n\nfunc ParseOption(args []string) (*Option, error) {\n\topt := &Option{}\n\tfiles, err := flags.ParseArgs(opt, args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\topt.Files = files\n\treturn opt, nil\n}\n<commit_msg>Switch from go-flags to flag<commit_after>package main\n\nimport (\n\t\"flag\"\n)\n\ntype Option struct {\n\tDelimiter string\n\tUseRegexp bool\n\tCount     int\n\tMargin    string\n\tJustify   string\n\tIsHelp    bool\n\tIsVersion bool\n\tFiles     []string\n}\n\nfunc ParseOption(args []string) (*Option, error) {\n\topt := &Option{}\n\n\tf := flag.NewFlagSet(\"alita\", flag.ContinueOnError)\n\tf.StringVar(&opt.Delimiter, \"d\", \"\", \"\")\n\tf.StringVar(&opt.Delimiter, \"delimiter\", \"\", \"\")\n\tf.BoolVar(&opt.UseRegexp, \"r\", false, \"\")\n\tf.BoolVar(&opt.UseRegexp, \"regexp\", false, \"\")\n\tf.IntVar(&opt.Count, \"c\", 0, \"\")\n\tf.IntVar(&opt.Count, \"count\", 0, \"\")\n\tf.StringVar(&opt.Margin, \"m\", \"\", \"\")\n\tf.StringVar(&opt.Margin, \"margin\", \"\", \"\")\n\tf.StringVar(&opt.Justify, \"j\", \"\", \"\")\n\tf.StringVar(&opt.Justify, \"justify\", \"\", \"\")\n\tf.BoolVar(&opt.IsHelp, \"h\", false, \"\")\n\tf.BoolVar(&opt.IsHelp, \"help\", false, \"\")\n\tf.BoolVar(&opt.IsVersion, \"version\", false, \"\")\n\n\tif err := f.Parse(args); err != nil {\n\t\treturn nil, err\n\t}\n\topt.Files = f.Args()\n\treturn opt, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package terraform\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestDiffTransformer_nilDiff(t *testing.T) {\n\tg := Graph{Path: RootModulePath}\n\ttf := &DiffTransformer{}\n\tif err := tf.Transform(&g); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tif len(g.Vertices()) > 0 {\n\t\tt.Fatal(\"graph should be empty\")\n\t}\n}\n\nfunc TestDiffTransformer(t *testing.T) {\n\tg := Graph{Path: RootModulePath}\n\ttf := &DiffTransformer{\n\t\tModule: testModule(t, \"transform-diff-basic\"),\n\t\tDiff: &Diff{\n\t\t\tModules: []*ModuleDiff{\n\t\t\t\t&ModuleDiff{\n\t\t\t\t\tPath: []string{\"root\"},\n\t\t\t\t\tResources: map[string]*InstanceDiff{\n\t\t\t\t\t\t\"aws_instance.foo\": &InstanceDiff{\n\t\t\t\t\t\t\tAttributes: map[string]*ResourceAttrDiff{\n\t\t\t\t\t\t\t\t\"name\": &ResourceAttrDiff{\n\t\t\t\t\t\t\t\t\tOld: \"\",\n\t\t\t\t\t\t\t\t\tNew: \"foo\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tif err := tf.Transform(&g); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tactual := strings.TrimSpace(g.String())\n\texpected := strings.TrimSpace(testTransformDiffBasicStr)\n\tif actual != expected {\n\t\tt.Fatalf(\"bad:\\n\\n%s\", actual)\n\t}\n\n\tv := g.Vertices()[0].(*NodeApplyableResource)\n\tif v.Config == nil {\n\t\tt.Fatal(\"no config\")\n\t}\n}\n\nconst testTransformDiffBasicStr = `\naws_instance.foo\n`\n<commit_msg>terraform: remove diff transformer test that no longer happens<commit_after>package terraform\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestDiffTransformer_nilDiff(t *testing.T) {\n\tg := Graph{Path: RootModulePath}\n\ttf := &DiffTransformer{}\n\tif err := tf.Transform(&g); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tif len(g.Vertices()) > 0 {\n\t\tt.Fatal(\"graph should be empty\")\n\t}\n}\n\nfunc TestDiffTransformer(t *testing.T) {\n\tg := Graph{Path: RootModulePath}\n\ttf := &DiffTransformer{\n\t\tModule: testModule(t, \"transform-diff-basic\"),\n\t\tDiff: &Diff{\n\t\t\tModules: []*ModuleDiff{\n\t\t\t\t&ModuleDiff{\n\t\t\t\t\tPath: []string{\"root\"},\n\t\t\t\t\tResources: map[string]*InstanceDiff{\n\t\t\t\t\t\t\"aws_instance.foo\": &InstanceDiff{\n\t\t\t\t\t\t\tAttributes: map[string]*ResourceAttrDiff{\n\t\t\t\t\t\t\t\t\"name\": &ResourceAttrDiff{\n\t\t\t\t\t\t\t\t\tOld: \"\",\n\t\t\t\t\t\t\t\t\tNew: \"foo\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tif err := tf.Transform(&g); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\n\tactual := strings.TrimSpace(g.String())\n\texpected := strings.TrimSpace(testTransformDiffBasicStr)\n\tif actual != expected {\n\t\tt.Fatalf(\"bad:\\n\\n%s\", actual)\n\t}\n}\n\nconst testTransformDiffBasicStr = `\naws_instance.foo\n`\n<|endoftext|>"}
{"text":"<commit_before>package globals\n\nimport (\n\t\"context\"\n\n\t\"github.com\/keybase\/client\/go\/chat\/types\"\n\t\"github.com\/keybase\/client\/go\/libkb\"\n\t\"github.com\/keybase\/client\/go\/protocol\/chat1\"\n\t\"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n\t\"github.com\/keybase\/go-framed-msgpack-rpc\/rpc\"\n)\n\ntype keyfinderKey int\ntype identifyNotifierKey int\ntype chatTrace int\ntype identifyModeKey int\ntype upakfinderKey int\ntype rateLimitKey int\ntype nameInfoOverride int\ntype localizerCancelableKeyTyp int\ntype messageSkipsKeyTyp int\ntype unboxModeKeyTyp int\ntype emojiHarvesterKeyTyp int\n\nvar kfKey keyfinderKey\nvar inKey identifyNotifierKey\nvar chatTraceKey chatTrace\nvar identModeKey identifyModeKey\nvar upKey upakfinderKey\nvar rlKey rateLimitKey\nvar nameInfoOverrideKey nameInfoOverride\nvar localizerCancelableKey localizerCancelableKeyTyp\nvar messageSkipsKey messageSkipsKeyTyp\nvar unboxModeKey unboxModeKeyTyp\nvar emojiHarvesterKey emojiHarvesterKeyTyp\n\ntype identModeData struct {\n\tmode   keybase1.TLFIdentifyBehavior\n\tbreaks *[]keybase1.TLFIdentifyFailure\n}\n\nfunc CtxKeyFinder(ctx context.Context, g *Context) types.KeyFinder {\n\tvar kf types.KeyFinder\n\tvar ok bool\n\tval := ctx.Value(kfKey)\n\tif kf, ok = val.(types.KeyFinder); ok {\n\t\treturn kf\n\t}\n\treturn g.CtxFactory.NewKeyFinder()\n}\n\nfunc CtxUPAKFinder(ctx context.Context, g *Context) types.UPAKFinder {\n\tvar up types.UPAKFinder\n\tvar ok bool\n\tval := ctx.Value(upKey)\n\tif up, ok = val.(types.UPAKFinder); ok {\n\t\treturn up\n\t}\n\treturn g.CtxFactory.NewUPAKFinder()\n}\n\nfunc CtxIdentifyMode(ctx context.Context) (ib keybase1.TLFIdentifyBehavior, breaks *[]keybase1.TLFIdentifyFailure, ok bool) {\n\tvar imd identModeData\n\tval := ctx.Value(identModeKey)\n\tif imd, ok = val.(identModeData); ok {\n\t\treturn imd.mode, imd.breaks, ok\n\t}\n\treturn keybase1.TLFIdentifyBehavior_CHAT_CLI, nil, false\n}\n\nfunc CtxAddIdentifyMode(ctx context.Context, mode keybase1.TLFIdentifyBehavior,\n\tbreaks *[]keybase1.TLFIdentifyFailure) context.Context {\n\tif mode == keybase1.TLFIdentifyBehavior_UNSET {\n\t\tmode = keybase1.TLFIdentifyBehavior_CHAT_CLI\n\t}\n\treturn context.WithValue(ctx, identModeKey, identModeData{mode: mode, breaks: breaks})\n}\n\nfunc CtxIdentifyNotifier(ctx context.Context) types.IdentifyNotifier {\n\tvar in types.IdentifyNotifier\n\tvar ok bool\n\tval := ctx.Value(inKey)\n\tif in, ok = val.(types.IdentifyNotifier); ok {\n\t\treturn in\n\t}\n\treturn nil\n}\n\nfunc CtxModifyIdentifyNotifier(ctx context.Context, notifier types.IdentifyNotifier) context.Context {\n\treturn context.WithValue(ctx, inKey, notifier)\n}\n\nfunc CtxAddRateLimit(ctx context.Context, rl []chat1.RateLimit) {\n\tval := ctx.Value(rlKey)\n\tif existingRL, ok := val.(map[string]chat1.RateLimit); ok {\n\t\tfor _, r := range rl {\n\t\t\texistingRL[r.Name] = r\n\t\t}\n\t}\n}\n\nfunc CtxRateLimits(ctx context.Context) (res []chat1.RateLimit) {\n\tval := ctx.Value(rlKey)\n\tif existingRL, ok := val.(map[string]chat1.RateLimit); ok {\n\t\tfor _, rl := range existingRL {\n\t\t\tres = append(res, rl)\n\t\t}\n\t}\n\treturn res\n}\n\nfunc CtxAddMessageCacheSkips(ctx context.Context, convID chat1.ConversationID, msgs []chat1.MessageUnboxed) {\n\tval := ctx.Value(messageSkipsKey)\n\tif existingSkips, ok := val.(map[chat1.ConvIDStr]MessageCacheSkip); ok {\n\t\texistingSkips[convID.ConvIDStr()] = MessageCacheSkip{\n\t\t\tConvID: convID,\n\t\t\tMsgs:   append(existingSkips[convID.ConvIDStr()].Msgs, msgs...),\n\t\t}\n\t}\n}\n\ntype MessageCacheSkip struct {\n\tConvID chat1.ConversationID\n\tMsgs   []chat1.MessageUnboxed\n}\n\nfunc CtxMessageCacheSkips(ctx context.Context) (res []MessageCacheSkip) {\n\tval := ctx.Value(messageSkipsKey)\n\tif existingSkips, ok := val.(map[chat1.ConvIDStr]MessageCacheSkip); ok {\n\t\tfor _, skips := range existingSkips {\n\t\t\tres = append(res, skips)\n\t\t}\n\t}\n\treturn res\n}\n\nfunc CtxModifyUnboxMode(ctx context.Context, unboxMode types.UnboxMode) context.Context {\n\treturn context.WithValue(ctx, unboxModeKey, unboxMode)\n}\n\nfunc CtxUnboxMode(ctx context.Context) types.UnboxMode {\n\tval := ctx.Value(unboxModeKey)\n\tif unboxMode, ok := val.(types.UnboxMode); ok {\n\t\treturn unboxMode\n\t}\n\treturn types.UnboxModeFull\n}\n\nfunc CtxOverrideNameInfoSource(ctx context.Context) (types.NameInfoSource, bool) {\n\tval := ctx.Value(nameInfoOverrideKey)\n\tif ni, ok := val.(types.NameInfoSource); ok {\n\t\treturn ni, true\n\t}\n\treturn nil, false\n}\n\nfunc CtxAddOverrideNameInfoSource(ctx context.Context, ni types.NameInfoSource) context.Context {\n\treturn context.WithValue(ctx, nameInfoOverrideKey, ni)\n}\n\nfunc CtxTrace(ctx context.Context) (string, bool) {\n\tvar trace string\n\tvar ok bool\n\tval := ctx.Value(chatTraceKey)\n\tif trace, ok = val.(string); ok {\n\t\treturn trace, true\n\t}\n\treturn \"\", false\n}\n\nfunc CtxAddLogTags(ctx context.Context, g *Context) context.Context {\n\n\t\/\/ Add trace context value\n\ttrace := libkb.RandStringB64(3)\n\tctx = context.WithValue(ctx, chatTraceKey, trace)\n\n\t\/\/ Add log tags\n\tctx = libkb.WithLogTagWithValue(ctx, \"chat-trace\", trace)\n\n\trpcTags := make(map[string]interface{})\n\trpcTags[\"user-agent\"] = libkb.UserAgent\n\trpcTags[\"platform\"] = libkb.GetPlatformString()\n\trpcTags[\"apptype\"] = g.GetAppType()\n\tctx = rpc.AddRpcTagsToContext(ctx, rpcTags)\n\n\treturn ctx\n}\n\nfunc IsLocalizerCancelableCtx(ctx context.Context) bool {\n\tval := ctx.Value(localizerCancelableKey)\n\tif bval, ok := val.(bool); ok && bval {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc CtxAddLocalizerCancelable(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, localizerCancelableKey, true)\n}\n\nfunc CtxRemoveLocalizerCancelable(ctx context.Context) context.Context {\n\tif IsLocalizerCancelableCtx(ctx) {\n\t\treturn context.WithValue(ctx, localizerCancelableKey, false)\n\t}\n\treturn ctx\n}\n\nfunc IsEmojiHarvesterCtx(ctx context.Context) bool {\n\tval := ctx.Value(emojiHarvesterKey)\n\tif bval, ok := val.(bool); ok && bval {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc CtxMakeEmojiHarvester(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, emojiHarvesterKey, true)\n}\n\nfunc ChatCtx(ctx context.Context, g *Context, mode keybase1.TLFIdentifyBehavior,\n\tbreaks *[]keybase1.TLFIdentifyFailure, notifier types.IdentifyNotifier) context.Context {\n\tif breaks == nil {\n\t\tbreaks = new([]keybase1.TLFIdentifyFailure)\n\t}\n\tres := ctx\n\tif _, _, ok := CtxIdentifyMode(res); !ok {\n\t\tres = CtxAddIdentifyMode(res, mode, breaks)\n\t}\n\tval := res.Value(kfKey)\n\tif _, ok := val.(types.KeyFinder); !ok {\n\t\tres = context.WithValue(res, kfKey, g.CtxFactory.NewKeyFinder())\n\t}\n\tval = res.Value(inKey)\n\tif _, ok := val.(types.IdentifyNotifier); !ok {\n\t\tres = context.WithValue(res, inKey, notifier)\n\t}\n\tval = res.Value(upKey)\n\tif _, ok := val.(types.UPAKFinder); !ok {\n\t\tres = context.WithValue(res, upKey, g.CtxFactory.NewUPAKFinder())\n\t}\n\tval = res.Value(rlKey)\n\tif _, ok := val.(map[string]chat1.RateLimit); !ok {\n\t\tres = context.WithValue(res, rlKey, make(map[string]chat1.RateLimit))\n\t}\n\tval = res.Value(messageSkipsKey)\n\tif _, ok := val.(map[chat1.ConvIDStr]MessageCacheSkip); !ok {\n\t\tres = context.WithValue(res, messageSkipsKey, make(map[chat1.ConvIDStr]MessageCacheSkip))\n\t}\n\tval = res.Value(unboxModeKey)\n\tif _, ok := val.(types.UnboxMode); !ok {\n\t\tres = context.WithValue(res, unboxModeKey, types.UnboxModeFull)\n\t}\n\tif _, ok := CtxTrace(res); !ok {\n\t\tres = CtxAddLogTags(res, g)\n\t}\n\treturn res\n}\n\nfunc BackgroundChatCtx(sourceCtx context.Context, g *Context) context.Context {\n\n\trctx := libkb.CopyTagsToBackground(sourceCtx)\n\n\tin := CtxIdentifyNotifier(sourceCtx)\n\tif ident, breaks, ok := CtxIdentifyMode(sourceCtx); ok {\n\t\trctx = ChatCtx(rctx, g, ident, breaks, in)\n\t}\n\n\t\/\/ Overwrite trace tag\n\tif tr, ok := sourceCtx.Value(chatTraceKey).(string); ok {\n\t\trctx = context.WithValue(rctx, chatTraceKey, tr)\n\t}\n\n\tif ni, ok := CtxOverrideNameInfoSource(sourceCtx); ok {\n\t\trctx = CtxAddOverrideNameInfoSource(rctx, ni)\n\t}\n\trctx = context.WithValue(rctx, kfKey, CtxKeyFinder(sourceCtx, g))\n\trctx = context.WithValue(rctx, upKey, CtxUPAKFinder(sourceCtx, g))\n\trctx = context.WithValue(rctx, inKey, in)\n\trctx = libkb.WithLogTag(rctx, \"CHTBKG\")\n\tif IsLocalizerCancelableCtx(sourceCtx) {\n\t\trctx = CtxAddLocalizerCancelable(rctx)\n\t}\n\tif IsEmojiHarvesterCtx(sourceCtx) {\n\t\trctx = CtxMakeEmojiHarvester(rctx)\n\t}\n\treturn rctx\n}\n<commit_msg>prevent concurrent writes to ctx maps (#23634)<commit_after>package globals\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"github.com\/keybase\/client\/go\/chat\/types\"\n\t\"github.com\/keybase\/client\/go\/libkb\"\n\t\"github.com\/keybase\/client\/go\/protocol\/chat1\"\n\t\"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n\t\"github.com\/keybase\/go-framed-msgpack-rpc\/rpc\"\n)\n\ntype keyfinderKey int\ntype identifyNotifierKey int\ntype chatTrace int\ntype identifyModeKey int\ntype upakfinderKey int\ntype rateLimitKey int\ntype nameInfoOverride int\ntype localizerCancelableKeyTyp int\ntype messageSkipsKeyTyp int\ntype unboxModeKeyTyp int\ntype emojiHarvesterKeyTyp int\ntype ctxMutexKeyTyp int\n\nvar kfKey keyfinderKey\nvar inKey identifyNotifierKey\nvar chatTraceKey chatTrace\nvar identModeKey identifyModeKey\nvar upKey upakfinderKey\nvar rlKey rateLimitKey\nvar nameInfoOverrideKey nameInfoOverride\nvar localizerCancelableKey localizerCancelableKeyTyp\nvar messageSkipsKey messageSkipsKeyTyp\nvar unboxModeKey unboxModeKeyTyp\nvar emojiHarvesterKey emojiHarvesterKeyTyp\nvar ctxMutexKey ctxMutexKeyTyp\n\ntype identModeData struct {\n\tmode   keybase1.TLFIdentifyBehavior\n\tbreaks *[]keybase1.TLFIdentifyFailure\n}\n\nfunc CtxKeyFinder(ctx context.Context, g *Context) types.KeyFinder {\n\tvar kf types.KeyFinder\n\tvar ok bool\n\tval := ctx.Value(kfKey)\n\tif kf, ok = val.(types.KeyFinder); ok {\n\t\treturn kf\n\t}\n\treturn g.CtxFactory.NewKeyFinder()\n}\n\nfunc CtxUPAKFinder(ctx context.Context, g *Context) types.UPAKFinder {\n\tvar up types.UPAKFinder\n\tvar ok bool\n\tval := ctx.Value(upKey)\n\tif up, ok = val.(types.UPAKFinder); ok {\n\t\treturn up\n\t}\n\treturn g.CtxFactory.NewUPAKFinder()\n}\n\nfunc CtxIdentifyMode(ctx context.Context) (ib keybase1.TLFIdentifyBehavior, breaks *[]keybase1.TLFIdentifyFailure, ok bool) {\n\tvar imd identModeData\n\tval := ctx.Value(identModeKey)\n\tif imd, ok = val.(identModeData); ok {\n\t\treturn imd.mode, imd.breaks, ok\n\t}\n\treturn keybase1.TLFIdentifyBehavior_CHAT_CLI, nil, false\n}\n\nfunc CtxAddIdentifyMode(ctx context.Context, mode keybase1.TLFIdentifyBehavior,\n\tbreaks *[]keybase1.TLFIdentifyFailure) context.Context {\n\tif mode == keybase1.TLFIdentifyBehavior_UNSET {\n\t\tmode = keybase1.TLFIdentifyBehavior_CHAT_CLI\n\t}\n\treturn context.WithValue(ctx, identModeKey, identModeData{mode: mode, breaks: breaks})\n}\n\nfunc CtxIdentifyNotifier(ctx context.Context) types.IdentifyNotifier {\n\tvar in types.IdentifyNotifier\n\tvar ok bool\n\tval := ctx.Value(inKey)\n\tif in, ok = val.(types.IdentifyNotifier); ok {\n\t\treturn in\n\t}\n\treturn nil\n}\n\nfunc CtxModifyIdentifyNotifier(ctx context.Context, notifier types.IdentifyNotifier) context.Context {\n\treturn context.WithValue(ctx, inKey, notifier)\n}\n\nfunc CtxAddRateLimit(ctx context.Context, rl []chat1.RateLimit) {\n\tval := ctx.Value(ctxMutexKey)\n\tif l, ok := val.(sync.RWMutex); ok {\n\t\tl.Lock()\n\t\tdefer l.Unlock()\n\t\tval = ctx.Value(rlKey)\n\t\tif existingRL, ok := val.(map[string]chat1.RateLimit); ok {\n\t\t\tfor _, r := range rl {\n\t\t\t\texistingRL[r.Name] = r\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc CtxRateLimits(ctx context.Context) (res []chat1.RateLimit) {\n\tval := ctx.Value(ctxMutexKey)\n\tif l, ok := val.(sync.RWMutex); ok {\n\t\tl.RLock()\n\t\tdefer l.RUnlock()\n\t\tval = ctx.Value(rlKey)\n\t\tif existingRL, ok := val.(map[string]chat1.RateLimit); ok {\n\t\t\tfor _, rl := range existingRL {\n\t\t\t\tres = append(res, rl)\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}\n\nfunc CtxAddMessageCacheSkips(ctx context.Context, convID chat1.ConversationID, msgs []chat1.MessageUnboxed) {\n\tval := ctx.Value(ctxMutexKey)\n\tif l, ok := val.(sync.RWMutex); ok {\n\t\tl.Lock()\n\t\tdefer l.Unlock()\n\t\tval = ctx.Value(messageSkipsKey)\n\t\tif existingSkips, ok := val.(map[chat1.ConvIDStr]MessageCacheSkip); ok {\n\t\t\texistingSkips[convID.ConvIDStr()] = MessageCacheSkip{\n\t\t\t\tConvID: convID,\n\t\t\t\tMsgs:   append(existingSkips[convID.ConvIDStr()].Msgs, msgs...),\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype MessageCacheSkip struct {\n\tConvID chat1.ConversationID\n\tMsgs   []chat1.MessageUnboxed\n}\n\nfunc CtxMessageCacheSkips(ctx context.Context) (res []MessageCacheSkip) {\n\tval := ctx.Value(ctxMutexKey)\n\tif l, ok := val.(sync.RWMutex); ok {\n\t\tl.RLock()\n\t\tdefer l.RUnlock()\n\t\tval = ctx.Value(messageSkipsKey)\n\t\tif existingSkips, ok := val.(map[chat1.ConvIDStr]MessageCacheSkip); ok {\n\t\t\tfor _, skips := range existingSkips {\n\t\t\t\tres = append(res, skips)\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}\n\nfunc CtxModifyUnboxMode(ctx context.Context, unboxMode types.UnboxMode) context.Context {\n\treturn context.WithValue(ctx, unboxModeKey, unboxMode)\n}\n\nfunc CtxUnboxMode(ctx context.Context) types.UnboxMode {\n\tval := ctx.Value(unboxModeKey)\n\tif unboxMode, ok := val.(types.UnboxMode); ok {\n\t\treturn unboxMode\n\t}\n\treturn types.UnboxModeFull\n}\n\nfunc CtxOverrideNameInfoSource(ctx context.Context) (types.NameInfoSource, bool) {\n\tval := ctx.Value(nameInfoOverrideKey)\n\tif ni, ok := val.(types.NameInfoSource); ok {\n\t\treturn ni, true\n\t}\n\treturn nil, false\n}\n\nfunc CtxAddOverrideNameInfoSource(ctx context.Context, ni types.NameInfoSource) context.Context {\n\treturn context.WithValue(ctx, nameInfoOverrideKey, ni)\n}\n\nfunc CtxTrace(ctx context.Context) (string, bool) {\n\tvar trace string\n\tvar ok bool\n\tval := ctx.Value(chatTraceKey)\n\tif trace, ok = val.(string); ok {\n\t\treturn trace, true\n\t}\n\treturn \"\", false\n}\n\nfunc CtxAddLogTags(ctx context.Context, g *Context) context.Context {\n\n\t\/\/ Add trace context value\n\ttrace := libkb.RandStringB64(3)\n\tctx = context.WithValue(ctx, chatTraceKey, trace)\n\n\t\/\/ Add log tags\n\tctx = libkb.WithLogTagWithValue(ctx, \"chat-trace\", trace)\n\n\trpcTags := make(map[string]interface{})\n\trpcTags[\"user-agent\"] = libkb.UserAgent\n\trpcTags[\"platform\"] = libkb.GetPlatformString()\n\trpcTags[\"apptype\"] = g.GetAppType()\n\tctx = rpc.AddRpcTagsToContext(ctx, rpcTags)\n\n\treturn ctx\n}\n\nfunc IsLocalizerCancelableCtx(ctx context.Context) bool {\n\tval := ctx.Value(localizerCancelableKey)\n\tif bval, ok := val.(bool); ok && bval {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc CtxAddLocalizerCancelable(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, localizerCancelableKey, true)\n}\n\nfunc CtxRemoveLocalizerCancelable(ctx context.Context) context.Context {\n\tif IsLocalizerCancelableCtx(ctx) {\n\t\treturn context.WithValue(ctx, localizerCancelableKey, false)\n\t}\n\treturn ctx\n}\n\nfunc IsEmojiHarvesterCtx(ctx context.Context) bool {\n\tval := ctx.Value(emojiHarvesterKey)\n\tif bval, ok := val.(bool); ok && bval {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc CtxMakeEmojiHarvester(ctx context.Context) context.Context {\n\treturn context.WithValue(ctx, emojiHarvesterKey, true)\n}\n\nfunc ChatCtx(ctx context.Context, g *Context, mode keybase1.TLFIdentifyBehavior,\n\tbreaks *[]keybase1.TLFIdentifyFailure, notifier types.IdentifyNotifier) context.Context {\n\tif breaks == nil {\n\t\tbreaks = new([]keybase1.TLFIdentifyFailure)\n\t}\n\tres := ctx\n\tif _, _, ok := CtxIdentifyMode(res); !ok {\n\t\tres = CtxAddIdentifyMode(res, mode, breaks)\n\t}\n\tval := res.Value(kfKey)\n\tif _, ok := val.(types.KeyFinder); !ok {\n\t\tres = context.WithValue(res, kfKey, g.CtxFactory.NewKeyFinder())\n\t}\n\tval = res.Value(inKey)\n\tif _, ok := val.(types.IdentifyNotifier); !ok {\n\t\tres = context.WithValue(res, inKey, notifier)\n\t}\n\tval = res.Value(upKey)\n\tif _, ok := val.(types.UPAKFinder); !ok {\n\t\tres = context.WithValue(res, upKey, g.CtxFactory.NewUPAKFinder())\n\t}\n\tval = res.Value(ctxMutexKey)\n\tif _, ok := val.(sync.RWMutex); !ok {\n\t\tres = context.WithValue(res, ctxMutexKey, sync.RWMutex{})\n\t}\n\tval = res.Value(rlKey)\n\tif _, ok := val.(map[string]chat1.RateLimit); !ok {\n\t\tres = context.WithValue(res, rlKey, make(map[string]chat1.RateLimit))\n\t}\n\tval = res.Value(messageSkipsKey)\n\tif _, ok := val.(map[chat1.ConvIDStr]MessageCacheSkip); !ok {\n\t\tres = context.WithValue(res, messageSkipsKey, make(map[chat1.ConvIDStr]MessageCacheSkip))\n\t}\n\tval = res.Value(unboxModeKey)\n\tif _, ok := val.(types.UnboxMode); !ok {\n\t\tres = context.WithValue(res, unboxModeKey, types.UnboxModeFull)\n\t}\n\tif _, ok := CtxTrace(res); !ok {\n\t\tres = CtxAddLogTags(res, g)\n\t}\n\treturn res\n}\n\nfunc BackgroundChatCtx(sourceCtx context.Context, g *Context) context.Context {\n\n\trctx := libkb.CopyTagsToBackground(sourceCtx)\n\n\tin := CtxIdentifyNotifier(sourceCtx)\n\tif ident, breaks, ok := CtxIdentifyMode(sourceCtx); ok {\n\t\trctx = ChatCtx(rctx, g, ident, breaks, in)\n\t}\n\n\t\/\/ Overwrite trace tag\n\tif tr, ok := sourceCtx.Value(chatTraceKey).(string); ok {\n\t\trctx = context.WithValue(rctx, chatTraceKey, tr)\n\t}\n\n\tif ni, ok := CtxOverrideNameInfoSource(sourceCtx); ok {\n\t\trctx = CtxAddOverrideNameInfoSource(rctx, ni)\n\t}\n\trctx = context.WithValue(rctx, kfKey, CtxKeyFinder(sourceCtx, g))\n\trctx = context.WithValue(rctx, upKey, CtxUPAKFinder(sourceCtx, g))\n\trctx = context.WithValue(rctx, inKey, in)\n\trctx = libkb.WithLogTag(rctx, \"CHTBKG\")\n\tif IsLocalizerCancelableCtx(sourceCtx) {\n\t\trctx = CtxAddLocalizerCancelable(rctx)\n\t}\n\tif IsEmojiHarvesterCtx(sourceCtx) {\n\t\trctx = CtxMakeEmojiHarvester(rctx)\n\t}\n\treturn rctx\n}\n<|endoftext|>"}
{"text":"<commit_before>package objectserver\n\nimport (\n\t\"bufio\"\n\t\"encoding\/binary\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"time\"\n)\n\nvar RepUnmountedError = fmt.Errorf(\"Device unmounted\")\nvar repDialer = (&net.Dialer{Timeout: 5 * time.Second, KeepAlive: 30 * time.Second}).Dial\n\nconst repITimeout = time.Minute * 10\nconst repOTimeout = time.Minute\n\ntype BeginReplicationRequest struct {\n\tDevice     string\n\tPartition  string\n\tNeedHashes bool\n}\n\ntype BeginReplicationResponse struct {\n\tHashes map[string]string\n}\n\ntype SyncFileRequest struct {\n\tPath   string\n\tXattrs string\n\tSize   int64\n}\n\ntype SyncFileResponse struct {\n\tExists      bool\n\tNewerExists bool\n\tGoAhead     bool\n\tMsg         string\n}\n\ntype FileUploadResponse struct {\n\tSuccess bool\n\tMsg     string\n}\n\ntype RepConn struct {\n\trw           *bufio.ReadWriter\n\tc            net.Conn\n\tDisconnected bool\n}\n\nfunc (r *RepConn) SendMessage(v interface{}) error {\n\tr.c.SetDeadline(time.Now().Add(repOTimeout))\n\tjsoned, err := json.Marshal(v)\n\tif err != nil {\n\t\tr.Close()\n\t\treturn err\n\t}\n\tif err := binary.Write(r.rw, binary.BigEndian, uint32(len(jsoned))); err != nil {\n\t\tr.Close()\n\t\treturn err\n\t}\n\tif _, err := r.rw.Write(jsoned); err != nil {\n\t\tr.Close()\n\t\treturn err\n\t}\n\tif err := r.rw.Flush(); err != nil {\n\t\tr.Close()\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (r *RepConn) RecvMessage(v interface{}) (err error) {\n\tr.c.SetDeadline(time.Now().Add(repITimeout))\n\tvar length uint32\n\tif err = binary.Read(r.rw, binary.BigEndian, &length); err != nil {\n\t\tr.Close()\n\t\treturn\n\t}\n\tdata := make([]byte, length)\n\tif _, err = r.rw.Read(data); err != nil {\n\t\tr.Close()\n\t\treturn\n\t}\n\tif err = json.Unmarshal(data, v); err != nil {\n\t\tr.Close()\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (r *RepConn) Write(data []byte) (l int, err error) {\n\tr.c.SetDeadline(time.Now().Add(repOTimeout))\n\tif l, err = r.rw.Write(data); err != nil {\n\t\tr.Close()\n\t}\n\treturn\n}\n\nfunc (r *RepConn) Flush() (err error) {\n\tr.c.SetDeadline(time.Now().Add(repOTimeout))\n\tif err = r.rw.Flush(); err != nil {\n\t\tr.Close()\n\t}\n\treturn\n}\n\nfunc (r *RepConn) Read(data []byte) (l int, err error) {\n\tr.c.SetDeadline(time.Now().Add(repITimeout))\n\tif l, err = r.rw.Read(data); err != nil {\n\t\tr.Close()\n\t}\n\treturn\n}\n\nfunc (r *RepConn) Close() {\n\tr.Disconnected = true\n\tr.c.Close()\n}\n\nfunc NewRepConn(ip string, port int, device string, partition string) (*RepConn, error) {\n\turl := fmt.Sprintf(\"http:\/\/%s:%d\/%s\/%s\", ip, port, device, partition)\n\treq, err := http.NewRequest(\"REPCONN\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconn, err := repDialer(\"tcp\", req.URL.Host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thc := httputil.NewClientConn(conn, nil)\n\tresp, err := hc.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode\/100 != 2 {\n\t\treturn nil, RepUnmountedError\n\t}\n\tnewc, _ := hc.Hijack()\n\treturn &RepConn{rw: bufio.NewReadWriter(bufio.NewReader(newc), bufio.NewWriter(newc)), c: newc}, nil\n}\n<commit_msg>go: replicator fix<commit_after>package objectserver\n\nimport (\n\t\"bufio\"\n\t\"encoding\/binary\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"time\"\n)\n\nvar RepUnmountedError = fmt.Errorf(\"Device unmounted\")\nvar repDialer = (&net.Dialer{Timeout: 5 * time.Second, KeepAlive: 30 * time.Second}).Dial\n\nconst repITimeout = time.Minute * 10\nconst repOTimeout = time.Minute\n\ntype BeginReplicationRequest struct {\n\tDevice     string\n\tPartition  string\n\tNeedHashes bool\n}\n\ntype BeginReplicationResponse struct {\n\tHashes map[string]string\n}\n\ntype SyncFileRequest struct {\n\tPath   string\n\tXattrs string\n\tSize   int64\n}\n\ntype SyncFileResponse struct {\n\tExists      bool\n\tNewerExists bool\n\tGoAhead     bool\n\tMsg         string\n}\n\ntype FileUploadResponse struct {\n\tSuccess bool\n\tMsg     string\n}\n\ntype RepConn struct {\n\trw           *bufio.ReadWriter\n\tc            net.Conn\n\tDisconnected bool\n}\n\nfunc (r *RepConn) SendMessage(v interface{}) error {\n\tr.c.SetDeadline(time.Now().Add(repOTimeout))\n\tjsoned, err := json.Marshal(v)\n\tif err != nil {\n\t\tr.Close()\n\t\treturn err\n\t}\n\tif err := binary.Write(r.rw, binary.BigEndian, uint32(len(jsoned))); err != nil {\n\t\tr.Close()\n\t\treturn err\n\t}\n\tif _, err := r.rw.Write(jsoned); err != nil {\n\t\tr.Close()\n\t\treturn err\n\t}\n\tif err := r.rw.Flush(); err != nil {\n\t\tr.Close()\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (r *RepConn) RecvMessage(v interface{}) (err error) {\n\tr.c.SetDeadline(time.Now().Add(repITimeout))\n\tvar length uint32\n\tif err = binary.Read(r.rw, binary.BigEndian, &length); err != nil {\n\t\tr.Close()\n\t\treturn\n\t}\n\tdata := make([]byte, length)\n\tif _, err = io.ReadFull(r.rw, data); err != nil {\n\t\tr.Close()\n\t\treturn\n\t}\n\tif err = json.Unmarshal(data, v); err != nil {\n\t\tr.Close()\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (r *RepConn) Write(data []byte) (l int, err error) {\n\tr.c.SetDeadline(time.Now().Add(repOTimeout))\n\tif l, err = r.rw.Write(data); err != nil {\n\t\tr.Close()\n\t}\n\treturn\n}\n\nfunc (r *RepConn) Flush() (err error) {\n\tr.c.SetDeadline(time.Now().Add(repOTimeout))\n\tif err = r.rw.Flush(); err != nil {\n\t\tr.Close()\n\t}\n\treturn\n}\n\nfunc (r *RepConn) Read(data []byte) (l int, err error) {\n\tr.c.SetDeadline(time.Now().Add(repITimeout))\n\tif l, err = io.ReadFull(r.rw, data); err != nil {\n\t\tr.Close()\n\t}\n\treturn\n}\n\nfunc (r *RepConn) Close() {\n\tr.Disconnected = true\n\tr.c.Close()\n}\n\nfunc NewRepConn(ip string, port int, device string, partition string) (*RepConn, error) {\n\turl := fmt.Sprintf(\"http:\/\/%s:%d\/%s\/%s\", ip, port, device, partition)\n\treq, err := http.NewRequest(\"REPCONN\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconn, err := repDialer(\"tcp\", req.URL.Host)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thc := httputil.NewClientConn(conn, nil)\n\tresp, err := hc.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode\/100 != 2 {\n\t\treturn nil, RepUnmountedError\n\t}\n\tnewc, _ := hc.Hijack()\n\treturn &RepConn{rw: bufio.NewReadWriter(bufio.NewReader(newc), bufio.NewWriter(newc)), c: newc}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com\/gin-gonic\/gin\"\n\t\"golang.org\/x\/text\/language\"\n)\n\n\/\/ DefineLang uses gin context's attached configuration,\n\/\/ the Accept-Language header eventual cookie to\n\/\/ set the lang that should be used in that gin context.\nfunc DefineLang(c *gin.Context) {\n\ttags, _ \/*weights*\/, err := language.ParseAcceptLanguage(c.Request.Header.Get(\"Accept-Language\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ TODO: get lang preference from cookie if it exists\n\t\/\/ and push it in front of tags array\n\n\tconfigInterface, exists := c.Get(\"config\")\n\tif !exists {\n\t\tlog.Fatalln(\"config can't be found in gin context\")\n\t}\n\n\tconf, ok := configInterface.(Config)\n\tif !ok {\n\t\tlog.Fatalln(\"config incorrect format\")\n\t}\n\n\t\/\/ get most appropriate lang and its index in configuration\n\tlang, langIndex := getMostAppropriateLanguage(tags, &conf)\n\n\tc.Set(\"lang\", lang)\n\tc.Set(\"langIndex\", langIndex)\n\n\tc.Next()\n}\n\nfunc getMostAppropriateLanguage(langTags []language.Tag, conf *Config) (availableLang string, index int) {\n\n\tbestMatchWithoutVariant := -1\n\n\tfor _, tag := range langTags {\n\t\ttagStr := tag.String()\n\t\t\/\/ en-GB -> en\n\t\twithoutVariant := strings.Split(tagStr, \"-\")[0]\n\n\t\tfor index, availableLang = range conf.Lang {\n\t\t\tif availableLang == tagStr {\n\t\t\t\treturn\n\t\t\t} else if bestMatchWithoutVariant == -1 && availableLang == withoutVariant {\n\t\t\t\tbestMatchWithoutVariant = index\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ in case we found a match without variant\n\tif bestMatchWithoutVariant > -1 {\n\t\tavailableLang = conf.Lang[bestMatchWithoutVariant]\n\t\tindex = bestMatchWithoutVariant\n\t\treturn\n\t}\n\n\t\/\/ otherwise use first language in config...\n\tavailableLang = conf.Lang[0]\n\tindex = 0\n\treturn\n}\n<commit_msg>get lang from context<commit_after>package main\n\nimport (\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com\/gin-gonic\/gin\"\n\t\"golang.org\/x\/text\/language\"\n)\n\n\/\/ DefineLang uses gin context's attached configuration,\n\/\/ the Accept-Language header eventual cookie to\n\/\/ set the lang that should be used in that gin context.\nfunc DefineLang(c *gin.Context) {\n\ttags, _ \/*weights*\/, err := language.ParseAcceptLanguage(c.Request.Header.Get(\"Accept-Language\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ TODO: get lang preference from cookie if it exists\n\t\/\/ and push it in front of tags array\n\n\tconfigInterface, exists := c.Get(\"config\")\n\tif !exists {\n\t\tlog.Fatalln(\"config can't be found in gin context\")\n\t}\n\n\tconf, ok := configInterface.(Config)\n\tif !ok {\n\t\tlog.Fatalln(\"config incorrect format\")\n\t}\n\n\t\/\/ get most appropriate lang and its index in configuration\n\tlang, langIndex := getMostAppropriateLanguage(tags, &conf)\n\n\tc.Set(\"lang\", lang)\n\tc.Set(\"langIndex\", langIndex)\n\n\tc.Next()\n}\n\nfunc getLangForContext(c *gin.Context) string {\n\tlang, exists := c.Get(\"lang\")\n\tif !exists {\n\t\treturn \"\"\n\t}\n\treturn lang.(string)\n}\n\nfunc getLangIndexForContext(c *gin.Context) int {\n\tlangIndex, exists := c.Get(\"langIndex\")\n\tif !exists {\n\t\treturn -1\n\t}\n\treturn langIndex.(int)\n}\n\nfunc getMostAppropriateLanguage(langTags []language.Tag, conf *Config) (availableLang string, index int) {\n\n\tbestMatchWithoutVariant := -1\n\n\tfor _, tag := range langTags {\n\t\ttagStr := tag.String()\n\t\t\/\/ en-GB -> en\n\t\twithoutVariant := strings.Split(tagStr, \"-\")[0]\n\n\t\tfor index, availableLang = range conf.Lang {\n\t\t\tif availableLang == tagStr {\n\t\t\t\treturn\n\t\t\t} else if bestMatchWithoutVariant == -1 && availableLang == withoutVariant {\n\t\t\t\tbestMatchWithoutVariant = index\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ in case we found a match without variant\n\tif bestMatchWithoutVariant > -1 {\n\t\tavailableLang = conf.Lang[bestMatchWithoutVariant]\n\t\tindex = bestMatchWithoutVariant\n\t\treturn\n\t}\n\n\t\/\/ otherwise use first language in config...\n\tavailableLang = conf.Lang[0]\n\tindex = 0\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 Google Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage stats\n\nimport (\n\t\"expvar\"\n\t\"testing\"\n)\n\nfunc TestHistogram(t *testing.T) {\n\tclear()\n\th := NewHistogram(\"hist1\", \"desc1\", []int64{1, 5})\n\tfor i := 0; i < 10; i++ {\n\t\th.Add(int64(i))\n\t}\n\twant := `{\"1\": 2, \"5\": 6, \"inf\": 10, \"Count\": 10, \"Total\": 45}`\n\tif h.String() != want {\n\t\tt.Errorf(\"got %v, want %v\", h.String(), want)\n\t}\n\tcounts := h.Counts()\n\tcounts[\"Count\"] = h.Count()\n\tcounts[\"Total\"] = h.Total()\n\tfor k, want := range map[string]int64{\n\t\t\"1\":     2,\n\t\t\"5\":     4,\n\t\t\"inf\":   4,\n\t\t\"Count\": 10,\n\t\t\"Total\": 45,\n\t} {\n\t\tif got := counts[k]; got != want {\n\t\t\tt.Errorf(\"histogram counts [%v]: got %d, want %d\", k, got, want)\n\t\t}\n\t}\n\tif got, want := h.CountLabel(), \"Count\"; got != want {\n\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t}\n\tif got, want := h.TotalLabel(), \"Total\"; got != want {\n\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t}\n}\n\nfunc TestGenericHistogram(t *testing.T) {\n\tclear()\n\th := NewGenericHistogram(\n\t\t\"histgen\",\n\t\t\"generic histogram\",\n\t\t[]int64{1, 5},\n\t\t[]string{\"one\", \"five\", \"max\"},\n\t\t\"count\",\n\t\t\"total\",\n\t)\n\twant := `{\"one\": 0, \"five\": 0, \"max\": 0, \"count\": 0, \"total\": 0}`\n\tif got := h.String(); got != want {\n\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t}\n}\n\nfunc TestHistogramHook(t *testing.T) {\n\tvar gotname string\n\tvar gotv *Histogram\n\tclear()\n\tRegister(func(name string, v expvar.Var) {\n\t\tgotname = name\n\t\tgotv = v.(*Histogram)\n\t})\n\n\tname := \"hist2\"\n\tv := NewHistogram(name, \"\", []int64{1})\n\tif gotname != name {\n\t\tt.Errorf(\"got %v; want %v\", gotname, name)\n\t}\n\tif gotv != v {\n\t\tt.Errorf(\"got %#v, want %#v\", gotv, v)\n\t}\n}\n<commit_msg>use \"help\" uniformly as suggested in PR review<commit_after>\/*\nCopyright 2017 Google Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage stats\n\nimport (\n\t\"expvar\"\n\t\"testing\"\n)\n\nfunc TestHistogram(t *testing.T) {\n\tclear()\n\th := NewHistogram(\"hist1\", \"help\", []int64{1, 5})\n\tfor i := 0; i < 10; i++ {\n\t\th.Add(int64(i))\n\t}\n\twant := `{\"1\": 2, \"5\": 6, \"inf\": 10, \"Count\": 10, \"Total\": 45}`\n\tif h.String() != want {\n\t\tt.Errorf(\"got %v, want %v\", h.String(), want)\n\t}\n\tcounts := h.Counts()\n\tcounts[\"Count\"] = h.Count()\n\tcounts[\"Total\"] = h.Total()\n\tfor k, want := range map[string]int64{\n\t\t\"1\":     2,\n\t\t\"5\":     4,\n\t\t\"inf\":   4,\n\t\t\"Count\": 10,\n\t\t\"Total\": 45,\n\t} {\n\t\tif got := counts[k]; got != want {\n\t\t\tt.Errorf(\"histogram counts [%v]: got %d, want %d\", k, got, want)\n\t\t}\n\t}\n\tif got, want := h.CountLabel(), \"Count\"; got != want {\n\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t}\n\tif got, want := h.TotalLabel(), \"Total\"; got != want {\n\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t}\n}\n\nfunc TestGenericHistogram(t *testing.T) {\n\tclear()\n\th := NewGenericHistogram(\n\t\t\"histgen\",\n\t\t\"help\",\n\t\t[]int64{1, 5},\n\t\t[]string{\"one\", \"five\", \"max\"},\n\t\t\"count\",\n\t\t\"total\",\n\t)\n\twant := `{\"one\": 0, \"five\": 0, \"max\": 0, \"count\": 0, \"total\": 0}`\n\tif got := h.String(); got != want {\n\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t}\n}\n\nfunc TestHistogramHook(t *testing.T) {\n\tvar gotname string\n\tvar gotv *Histogram\n\tclear()\n\tRegister(func(name string, v expvar.Var) {\n\t\tgotname = name\n\t\tgotv = v.(*Histogram)\n\t})\n\n\tname := \"hist2\"\n\tv := NewHistogram(name, \"help\", []int64{1})\n\tif gotname != name {\n\t\tt.Errorf(\"got %v; want %v\", gotname, name)\n\t}\n\tif gotv != v {\n\t\tt.Errorf(\"got %#v, want %#v\", gotv, v)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012, Google Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage topotools\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/youtube\/vitess\/go\/trace\"\n\t\"github.com\/youtube\/vitess\/go\/vt\/concurrency\"\n\t\"github.com\/youtube\/vitess\/go\/vt\/logutil\"\n\t\"github.com\/youtube\/vitess\/go\/vt\/topo\"\n\t\"golang.org\/x\/net\/context\"\n\n\tpb \"github.com\/youtube\/vitess\/go\/vt\/proto\/topodata\"\n)\n\nvar _ = flag.Bool(\"lock_srvshard\", false, \"Unused\")\n\n\/\/ RebuildShard updates the SrvShard objects and underlying serving graph.\n\/\/\n\/\/ Re-read from TopologyServer to make sure we are using the side\n\/\/ effects of all actions.\n\/\/\n\/\/ This function will start each cell over from the beginning on ErrBadVersion,\n\/\/ so it doesn't need a lock on the shard.\nfunc RebuildShard(ctx context.Context, log logutil.Logger, ts topo.Server, keyspace, shard string, cells []string, lockTimeout time.Duration) (*topo.ShardInfo, error) {\n\tlog.Infof(\"RebuildShard %v\/%v\", keyspace, shard)\n\n\tspan := trace.NewSpanFromContext(ctx)\n\tspan.StartLocal(\"topotools.RebuildShard\")\n\tdefer span.Finish()\n\tctx = trace.NewContext(ctx, span)\n\n\t\/\/ read the existing shard info. It has to exist.\n\tshardInfo, err := ts.GetShard(ctx, keyspace, shard)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ rebuild all cells in parallel\n\twg := sync.WaitGroup{}\n\trec := concurrency.AllErrorRecorder{}\n\tfor _, cell := range shardInfo.Cells {\n\t\t\/\/ skip this cell if we shouldn't rebuild it\n\t\tif !topo.InCellList(cell, cells) {\n\t\t\tcontinue\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func(cell string) {\n\t\t\tdefer wg.Done()\n\t\t\trec.RecordError(rebuildCellSrvShard(ctx, log, ts, shardInfo, cell))\n\t\t}(cell)\n\t}\n\twg.Wait()\n\n\treturn shardInfo, rec.Error()\n}\n\n\/\/ rebuildCellSrvShard computes and writes the serving graph data to a\n\/\/ single cell\nfunc rebuildCellSrvShard(ctx context.Context, log logutil.Logger, ts topo.Server, si *topo.ShardInfo, cell string) (err error) {\n\tlog.Infof(\"rebuildCellSrvShard %v\/%v in cell %v\", si.Keyspace(), si.ShardName(), cell)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t\/\/ Read existing EndPoints node versions, so we know if any\n\t\t\/\/ changes sneak in after we read the tablets.\n\t\tversions, err := getEndPointsVersions(ctx, ts, cell, si.Keyspace(), si.ShardName())\n\n\t\t\/\/ Get all tablets in this cell\/shard.\n\t\ttablets, err := topo.GetTabletMapForShardByCell(ctx, ts, si.Keyspace(), si.ShardName(), []string{cell})\n\t\tif err != nil {\n\t\t\tif err != topo.ErrPartialResult {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.Warningf(\"Got ErrPartialResult from topo.GetTabletMapForShardByCell(%v), some tablets may not be added properly to serving graph\", cell)\n\t\t}\n\n\t\t\/\/ Build up the serving graph from scratch.\n\t\tserving := make(map[topo.TabletType]*pb.EndPoints)\n\t\tfor _, tablet := range tablets {\n\t\t\tif !tablet.IsInReplicationGraph() {\n\t\t\t\t\/\/ only valid case is a scrapped master in the\n\t\t\t\t\/\/ catastrophic reparent case\n\t\t\t\tlog.Warningf(\"Tablet %v should not be in the replication graph, please investigate (it is being ignored in the rebuild)\", tablet.Alias)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ Only add serving types.\n\t\t\tif !tablet.IsInServingGraph() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ Check the Keyspace and Shard for the tablet are right.\n\t\t\tif tablet.Keyspace != si.Keyspace() || tablet.Shard != si.ShardName() {\n\t\t\t\treturn fmt.Errorf(\"CRITICAL: tablet %v is in replication graph for shard %v\/%v but belongs to shard %v:%v\", tablet.Alias, si.Keyspace(), si.ShardName(), tablet.Keyspace, tablet.Shard)\n\t\t\t}\n\n\t\t\t\/\/ Add the tablet to the list.\n\t\t\tendpoints, ok := serving[tablet.Type]\n\t\t\tif !ok {\n\t\t\t\tendpoints = topo.NewEndPoints()\n\t\t\t\tserving[tablet.Type] = endpoints\n\t\t\t}\n\t\t\tentry, err := tablet.EndPoint()\n\t\t\tif err != nil {\n\t\t\t\tlog.Warningf(\"EndPointForTablet failed for tablet %v: %v\", tablet.Alias, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tendpoints.Entries = append(endpoints.Entries, entry)\n\t\t}\n\n\t\twg := sync.WaitGroup{}\n\t\tfatalErrs := concurrency.AllErrorRecorder{}\n\t\tretryErrs := concurrency.AllErrorRecorder{}\n\n\t\t\/\/ Write nodes that should exist.\n\t\tfor tabletType, endpoints := range serving {\n\t\t\twg.Add(1)\n\t\t\tgo func(tabletType topo.TabletType, endpoints *pb.EndPoints) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tlog.Infof(\"saving serving graph for cell %v shard %v\/%v tabletType %v\", cell, si.Keyspace(), si.ShardName(), tabletType)\n\n\t\t\t\tversion, ok := versions[tabletType]\n\t\t\t\tif !ok {\n\t\t\t\t\t\/\/ This type didn't exist when we first checked.\n\t\t\t\t\t\/\/ Try to create, but only if it still doesn't exist.\n\t\t\t\t\tif err := ts.CreateEndPoints(ctx, cell, si.Keyspace(), si.ShardName(), tabletType, endpoints); err != nil {\n\t\t\t\t\t\tlog.Warningf(\"CreateEndPoints(%v, %v, %v) failed during rebuild: %v\", cell, si, tabletType, err)\n\t\t\t\t\t\tswitch err {\n\t\t\t\t\t\tcase topo.ErrNodeExists:\n\t\t\t\t\t\t\tretryErrs.RecordError(err)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfatalErrs.RecordError(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t\/\/ Update only if the version matches.\n\t\t\t\tif err := ts.UpdateEndPoints(ctx, cell, si.Keyspace(), si.ShardName(), tabletType, endpoints, version); err != nil {\n\t\t\t\t\tlog.Warningf(\"UpdateEndPoints(%v, %v, %v) failed during rebuild: %v\", cell, si, tabletType, err)\n\t\t\t\t\tswitch err {\n\t\t\t\t\tcase topo.ErrBadVersion, topo.ErrNoNode:\n\t\t\t\t\t\tretryErrs.RecordError(err)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tfatalErrs.RecordError(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}(tabletType, endpoints)\n\t\t}\n\n\t\t\/\/ Delete nodes that shouldn't exist.\n\t\tfor tabletType, version := range versions {\n\t\t\tif _, ok := serving[tabletType]; !ok {\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func(tabletType topo.TabletType, version int64) {\n\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\tlog.Infof(\"removing stale db type from serving graph: %v\", tabletType)\n\t\t\t\t\tif err := ts.DeleteEndPoints(ctx, cell, si.Keyspace(), si.ShardName(), tabletType, version); err != nil && err != topo.ErrNoNode {\n\t\t\t\t\t\tlog.Warningf(\"DeleteEndPoints(%v, %v, %v) failed during rebuild: %v\", cell, si, tabletType, err)\n\t\t\t\t\t\tswitch err {\n\t\t\t\t\t\tcase topo.ErrNoNode:\n\t\t\t\t\t\t\t\/\/ Someone else deleted it, which is fine.\n\t\t\t\t\t\tcase topo.ErrBadVersion:\n\t\t\t\t\t\t\tretryErrs.RecordError(err)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfatalErrs.RecordError(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}(tabletType, version)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Update srvShard object\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tlog.Infof(\"updating shard serving graph in cell %v for %v\/%v\", cell, si.Keyspace(), si.ShardName())\n\t\t\tif err := UpdateSrvShard(ctx, ts, cell, si); err != nil {\n\t\t\t\tfatalErrs.RecordError(err)\n\t\t\t\tlog.Warningf(\"writing serving data in cell %v for %v\/%v failed: %v\", cell, si.Keyspace(), si.ShardName(), err)\n\t\t\t}\n\t\t}()\n\n\t\twg.Wait()\n\n\t\t\/\/ If there are any fatal errors, give up.\n\t\tif fatalErrs.HasErrors() {\n\t\t\treturn fatalErrs.Error()\n\t\t}\n\t\t\/\/ If there are any retry errors, try again.\n\t\tif retryErrs.HasErrors() {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Otherwise, success!\n\t\treturn nil\n\t}\n}\n\nfunc getEndPointsVersions(ctx context.Context, ts topo.Server, cell, keyspace, shard string) (map[topo.TabletType]int64, error) {\n\t\/\/ Get all existing tablet types.\n\ttabletTypes, err := ts.GetSrvTabletTypesPerShard(ctx, cell, keyspace, shard)\n\tif err != nil {\n\t\tif err == topo.ErrNoNode {\n\t\t\t\/\/ This just means there aren't any EndPoints lists yet.\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\n\t\/\/ Get node versions.\n\twg := sync.WaitGroup{}\n\terrs := concurrency.AllErrorRecorder{}\n\tversions := make(map[topo.TabletType]int64)\n\tmu := sync.Mutex{}\n\n\tfor _, tabletType := range tabletTypes {\n\t\twg.Add(1)\n\t\tgo func(tabletType topo.TabletType) {\n\t\t\tdefer wg.Done()\n\n\t\t\t_, version, err := ts.GetEndPoints(ctx, cell, keyspace, shard, tabletType)\n\t\t\tif err != nil && err != topo.ErrNoNode {\n\t\t\t\terrs.RecordError(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmu.Lock()\n\t\t\tversions[tabletType] = version\n\t\t\tmu.Unlock()\n\t\t}(tabletType)\n\t}\n\n\twg.Wait()\n\treturn versions, errs.Error()\n}\n\nfunc updateEndpoint(ctx context.Context, ts topo.Server, cell, keyspace, shard string, tabletType topo.TabletType, endpoint *pb.EndPoint) error {\n\treturn retryUpdateEndpoints(ctx, ts, cell, keyspace, shard, tabletType, true, \/* create *\/\n\t\tfunc(endpoints *pb.EndPoints) bool {\n\t\t\t\/\/ Look for an existing entry to update.\n\t\t\tfor i := range endpoints.Entries {\n\t\t\t\tif endpoints.Entries[i].Uid == endpoint.Uid {\n\t\t\t\t\tif topo.EndPointEquality(endpoints.Entries[i], endpoint) {\n\t\t\t\t\t\t\/\/ The entry already exists and is the same.\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Update an existing entry.\n\t\t\t\t\tendpoints.Entries[i] = endpoint\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ The entry doesn't exist, so add it.\n\t\t\tendpoints.Entries = append(endpoints.Entries, endpoint)\n\t\t\treturn true\n\t\t})\n}\n\nfunc removeEndpoint(ctx context.Context, ts topo.Server, cell, keyspace, shard string, tabletType topo.TabletType, tabletUID uint32) error {\n\terr := retryUpdateEndpoints(ctx, ts, cell, keyspace, shard, tabletType, false, \/* create *\/\n\t\tfunc(endpoints *pb.EndPoints) bool {\n\t\t\t\/\/ Make a new list, excluding the given UID.\n\t\t\tentries := make([]*pb.EndPoint, 0, len(endpoints.Entries))\n\t\t\tfor _, ep := range endpoints.Entries {\n\t\t\t\tif ep.Uid != tabletUID {\n\t\t\t\t\tentries = append(entries, ep)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(entries) == len(endpoints.Entries) {\n\t\t\t\t\/\/ Nothing was removed. Don't bother updating.\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t\/\/ Do the update.\n\t\t\tendpoints.Entries = entries\n\t\t\treturn true\n\t\t})\n\n\tif err == topo.ErrNoNode {\n\t\t\/\/ Our goal is to remove one endpoint. If the list is empty, we're fine.\n\t\terr = nil\n\t}\n\treturn err\n}\n\nfunc retryUpdateEndpoints(ctx context.Context, ts topo.Server, cell, keyspace, shard string, tabletType topo.TabletType, create bool, updateFunc func(*pb.EndPoints) bool) error {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t\/\/ Get or create EndPoints list.\n\t\tendpoints, version, err := ts.GetEndPoints(ctx, cell, keyspace, shard, tabletType)\n\t\tif err == topo.ErrNoNode && create {\n\t\t\t\/\/ Create instead of updating.\n\t\t\tendpoints = &pb.EndPoints{}\n\t\t\tif !updateFunc(endpoints) {\n\t\t\t\t\/\/ Nothing changed.\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\terr = ts.CreateEndPoints(ctx, cell, keyspace, shard, tabletType, endpoints)\n\t\t\tif err == topo.ErrNodeExists {\n\t\t\t\t\/\/ Someone else beat us to it. Try again.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ We got an existing EndPoints list. Try to update.\n\t\tif !updateFunc(endpoints) {\n\t\t\t\/\/ Nothing changed.\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ If there's nothing left, we should delete the list entirely.\n\t\tif len(endpoints.Entries) == 0 {\n\t\t\terr = ts.DeleteEndPoints(ctx, cell, keyspace, shard, tabletType, version)\n\t\t\tswitch err {\n\t\t\tcase topo.ErrNoNode:\n\t\t\t\t\/\/ Someone beat us to it, which is fine.\n\t\t\t\treturn nil\n\t\t\tcase topo.ErrBadVersion:\n\t\t\t\t\/\/ Someone else updated the list. Try again.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\terr = ts.UpdateEndPoints(ctx, cell, keyspace, shard, tabletType, endpoints, version)\n\t\tif err == topo.ErrBadVersion || (err == topo.ErrNoNode && create) {\n\t\t\t\/\/ Someone else updated or deleted the list in the meantime. Try again.\n\t\t\tcontinue\n\t\t}\n\t\treturn err\n\t}\n}\n\n\/\/ UpdateTabletEndpoints fixes up any entries in the serving graph that relate\n\/\/ to a given tablet.\nfunc UpdateTabletEndpoints(ctx context.Context, ts topo.Server, tablet *topo.Tablet) (err error) {\n\tsrvTypes, err := ts.GetSrvTabletTypesPerShard(ctx, tablet.Alias.Cell, tablet.Keyspace, tablet.Shard)\n\tif err != nil {\n\t\tif err != topo.ErrNoNode {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ It's fine if there are no existing types.\n\t\tsrvTypes = nil\n\t}\n\n\twg := sync.WaitGroup{}\n\terrs := concurrency.AllErrorRecorder{}\n\n\t\/\/ Update the list that the tablet is supposed to be in (if any).\n\tif tablet.IsInServingGraph() {\n\t\tendpoint, err := tablet.EndPoint()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\terrs.RecordError(\n\t\t\t\tupdateEndpoint(ctx, ts, tablet.Alias.Cell, tablet.Keyspace, tablet.Shard,\n\t\t\t\t\ttablet.Type, endpoint))\n\t\t}()\n\t}\n\n\t\/\/ Remove it from any other lists it isn't supposed to be in.\n\tfor _, srvType := range srvTypes {\n\t\tif srvType != tablet.Type {\n\t\t\twg.Add(1)\n\t\t\tgo func(tabletType topo.TabletType) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\terrs.RecordError(\n\t\t\t\t\tremoveEndpoint(ctx, ts, tablet.Alias.Cell, tablet.Keyspace, tablet.Shard,\n\t\t\t\t\t\ttabletType, tablet.Alias.Uid))\n\t\t\t}(srvType)\n\t\t}\n\t}\n\n\twg.Wait()\n\treturn errs.Error()\n}\n\n\/\/ UpdateSrvShard creates the SrvShard object based on the global ShardInfo,\n\/\/ and writes it to the given cell.\nfunc UpdateSrvShard(ctx context.Context, ts topo.Server, cell string, si *topo.ShardInfo) error {\n\tsrvShard := &topo.SrvShard{\n\t\tName:       si.ShardName(),\n\t\tKeyRange:   si.KeyRange,\n\t\tMasterCell: si.MasterAlias.Cell,\n\t}\n\treturn ts.UpdateSrvShard(ctx, cell, si.Keyspace(), si.ShardName(), srvShard)\n}\n\n\/\/ UpdateAllSrvShards calls UpdateSrvShard for all cells concurrently.\nfunc UpdateAllSrvShards(ctx context.Context, ts topo.Server, si *topo.ShardInfo) error {\n\twg := sync.WaitGroup{}\n\terrs := concurrency.AllErrorRecorder{}\n\n\tfor _, cell := range si.Cells {\n\t\twg.Add(1)\n\t\tgo func(cell string) {\n\t\t\terrs.RecordError(UpdateSrvShard(ctx, ts, cell, si))\n\t\t\twg.Done()\n\t\t}(cell)\n\t}\n\twg.Wait()\n\treturn errs.Error()\n}\n<commit_msg>Remove unused -lock_srvshard flag.<commit_after>\/\/ Copyright 2012, Google Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage topotools\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/youtube\/vitess\/go\/trace\"\n\t\"github.com\/youtube\/vitess\/go\/vt\/concurrency\"\n\t\"github.com\/youtube\/vitess\/go\/vt\/logutil\"\n\t\"github.com\/youtube\/vitess\/go\/vt\/topo\"\n\t\"golang.org\/x\/net\/context\"\n\n\tpb \"github.com\/youtube\/vitess\/go\/vt\/proto\/topodata\"\n)\n\n\/\/ RebuildShard updates the SrvShard objects and underlying serving graph.\n\/\/\n\/\/ Re-read from TopologyServer to make sure we are using the side\n\/\/ effects of all actions.\n\/\/\n\/\/ This function will start each cell over from the beginning on ErrBadVersion,\n\/\/ so it doesn't need a lock on the shard.\nfunc RebuildShard(ctx context.Context, log logutil.Logger, ts topo.Server, keyspace, shard string, cells []string, lockTimeout time.Duration) (*topo.ShardInfo, error) {\n\tlog.Infof(\"RebuildShard %v\/%v\", keyspace, shard)\n\n\tspan := trace.NewSpanFromContext(ctx)\n\tspan.StartLocal(\"topotools.RebuildShard\")\n\tdefer span.Finish()\n\tctx = trace.NewContext(ctx, span)\n\n\t\/\/ read the existing shard info. It has to exist.\n\tshardInfo, err := ts.GetShard(ctx, keyspace, shard)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ rebuild all cells in parallel\n\twg := sync.WaitGroup{}\n\trec := concurrency.AllErrorRecorder{}\n\tfor _, cell := range shardInfo.Cells {\n\t\t\/\/ skip this cell if we shouldn't rebuild it\n\t\tif !topo.InCellList(cell, cells) {\n\t\t\tcontinue\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func(cell string) {\n\t\t\tdefer wg.Done()\n\t\t\trec.RecordError(rebuildCellSrvShard(ctx, log, ts, shardInfo, cell))\n\t\t}(cell)\n\t}\n\twg.Wait()\n\n\treturn shardInfo, rec.Error()\n}\n\n\/\/ rebuildCellSrvShard computes and writes the serving graph data to a\n\/\/ single cell\nfunc rebuildCellSrvShard(ctx context.Context, log logutil.Logger, ts topo.Server, si *topo.ShardInfo, cell string) (err error) {\n\tlog.Infof(\"rebuildCellSrvShard %v\/%v in cell %v\", si.Keyspace(), si.ShardName(), cell)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t\/\/ Read existing EndPoints node versions, so we know if any\n\t\t\/\/ changes sneak in after we read the tablets.\n\t\tversions, err := getEndPointsVersions(ctx, ts, cell, si.Keyspace(), si.ShardName())\n\n\t\t\/\/ Get all tablets in this cell\/shard.\n\t\ttablets, err := topo.GetTabletMapForShardByCell(ctx, ts, si.Keyspace(), si.ShardName(), []string{cell})\n\t\tif err != nil {\n\t\t\tif err != topo.ErrPartialResult {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.Warningf(\"Got ErrPartialResult from topo.GetTabletMapForShardByCell(%v), some tablets may not be added properly to serving graph\", cell)\n\t\t}\n\n\t\t\/\/ Build up the serving graph from scratch.\n\t\tserving := make(map[topo.TabletType]*pb.EndPoints)\n\t\tfor _, tablet := range tablets {\n\t\t\tif !tablet.IsInReplicationGraph() {\n\t\t\t\t\/\/ only valid case is a scrapped master in the\n\t\t\t\t\/\/ catastrophic reparent case\n\t\t\t\tlog.Warningf(\"Tablet %v should not be in the replication graph, please investigate (it is being ignored in the rebuild)\", tablet.Alias)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ Only add serving types.\n\t\t\tif !tablet.IsInServingGraph() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ Check the Keyspace and Shard for the tablet are right.\n\t\t\tif tablet.Keyspace != si.Keyspace() || tablet.Shard != si.ShardName() {\n\t\t\t\treturn fmt.Errorf(\"CRITICAL: tablet %v is in replication graph for shard %v\/%v but belongs to shard %v:%v\", tablet.Alias, si.Keyspace(), si.ShardName(), tablet.Keyspace, tablet.Shard)\n\t\t\t}\n\n\t\t\t\/\/ Add the tablet to the list.\n\t\t\tendpoints, ok := serving[tablet.Type]\n\t\t\tif !ok {\n\t\t\t\tendpoints = topo.NewEndPoints()\n\t\t\t\tserving[tablet.Type] = endpoints\n\t\t\t}\n\t\t\tentry, err := tablet.EndPoint()\n\t\t\tif err != nil {\n\t\t\t\tlog.Warningf(\"EndPointForTablet failed for tablet %v: %v\", tablet.Alias, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tendpoints.Entries = append(endpoints.Entries, entry)\n\t\t}\n\n\t\twg := sync.WaitGroup{}\n\t\tfatalErrs := concurrency.AllErrorRecorder{}\n\t\tretryErrs := concurrency.AllErrorRecorder{}\n\n\t\t\/\/ Write nodes that should exist.\n\t\tfor tabletType, endpoints := range serving {\n\t\t\twg.Add(1)\n\t\t\tgo func(tabletType topo.TabletType, endpoints *pb.EndPoints) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tlog.Infof(\"saving serving graph for cell %v shard %v\/%v tabletType %v\", cell, si.Keyspace(), si.ShardName(), tabletType)\n\n\t\t\t\tversion, ok := versions[tabletType]\n\t\t\t\tif !ok {\n\t\t\t\t\t\/\/ This type didn't exist when we first checked.\n\t\t\t\t\t\/\/ Try to create, but only if it still doesn't exist.\n\t\t\t\t\tif err := ts.CreateEndPoints(ctx, cell, si.Keyspace(), si.ShardName(), tabletType, endpoints); err != nil {\n\t\t\t\t\t\tlog.Warningf(\"CreateEndPoints(%v, %v, %v) failed during rebuild: %v\", cell, si, tabletType, err)\n\t\t\t\t\t\tswitch err {\n\t\t\t\t\t\tcase topo.ErrNodeExists:\n\t\t\t\t\t\t\tretryErrs.RecordError(err)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfatalErrs.RecordError(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t\/\/ Update only if the version matches.\n\t\t\t\tif err := ts.UpdateEndPoints(ctx, cell, si.Keyspace(), si.ShardName(), tabletType, endpoints, version); err != nil {\n\t\t\t\t\tlog.Warningf(\"UpdateEndPoints(%v, %v, %v) failed during rebuild: %v\", cell, si, tabletType, err)\n\t\t\t\t\tswitch err {\n\t\t\t\t\tcase topo.ErrBadVersion, topo.ErrNoNode:\n\t\t\t\t\t\tretryErrs.RecordError(err)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tfatalErrs.RecordError(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}(tabletType, endpoints)\n\t\t}\n\n\t\t\/\/ Delete nodes that shouldn't exist.\n\t\tfor tabletType, version := range versions {\n\t\t\tif _, ok := serving[tabletType]; !ok {\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func(tabletType topo.TabletType, version int64) {\n\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\tlog.Infof(\"removing stale db type from serving graph: %v\", tabletType)\n\t\t\t\t\tif err := ts.DeleteEndPoints(ctx, cell, si.Keyspace(), si.ShardName(), tabletType, version); err != nil && err != topo.ErrNoNode {\n\t\t\t\t\t\tlog.Warningf(\"DeleteEndPoints(%v, %v, %v) failed during rebuild: %v\", cell, si, tabletType, err)\n\t\t\t\t\t\tswitch err {\n\t\t\t\t\t\tcase topo.ErrNoNode:\n\t\t\t\t\t\t\t\/\/ Someone else deleted it, which is fine.\n\t\t\t\t\t\tcase topo.ErrBadVersion:\n\t\t\t\t\t\t\tretryErrs.RecordError(err)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfatalErrs.RecordError(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}(tabletType, version)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Update srvShard object\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tlog.Infof(\"updating shard serving graph in cell %v for %v\/%v\", cell, si.Keyspace(), si.ShardName())\n\t\t\tif err := UpdateSrvShard(ctx, ts, cell, si); err != nil {\n\t\t\t\tfatalErrs.RecordError(err)\n\t\t\t\tlog.Warningf(\"writing serving data in cell %v for %v\/%v failed: %v\", cell, si.Keyspace(), si.ShardName(), err)\n\t\t\t}\n\t\t}()\n\n\t\twg.Wait()\n\n\t\t\/\/ If there are any fatal errors, give up.\n\t\tif fatalErrs.HasErrors() {\n\t\t\treturn fatalErrs.Error()\n\t\t}\n\t\t\/\/ If there are any retry errors, try again.\n\t\tif retryErrs.HasErrors() {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Otherwise, success!\n\t\treturn nil\n\t}\n}\n\nfunc getEndPointsVersions(ctx context.Context, ts topo.Server, cell, keyspace, shard string) (map[topo.TabletType]int64, error) {\n\t\/\/ Get all existing tablet types.\n\ttabletTypes, err := ts.GetSrvTabletTypesPerShard(ctx, cell, keyspace, shard)\n\tif err != nil {\n\t\tif err == topo.ErrNoNode {\n\t\t\t\/\/ This just means there aren't any EndPoints lists yet.\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\n\t\/\/ Get node versions.\n\twg := sync.WaitGroup{}\n\terrs := concurrency.AllErrorRecorder{}\n\tversions := make(map[topo.TabletType]int64)\n\tmu := sync.Mutex{}\n\n\tfor _, tabletType := range tabletTypes {\n\t\twg.Add(1)\n\t\tgo func(tabletType topo.TabletType) {\n\t\t\tdefer wg.Done()\n\n\t\t\t_, version, err := ts.GetEndPoints(ctx, cell, keyspace, shard, tabletType)\n\t\t\tif err != nil && err != topo.ErrNoNode {\n\t\t\t\terrs.RecordError(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmu.Lock()\n\t\t\tversions[tabletType] = version\n\t\t\tmu.Unlock()\n\t\t}(tabletType)\n\t}\n\n\twg.Wait()\n\treturn versions, errs.Error()\n}\n\nfunc updateEndpoint(ctx context.Context, ts topo.Server, cell, keyspace, shard string, tabletType topo.TabletType, endpoint *pb.EndPoint) error {\n\treturn retryUpdateEndpoints(ctx, ts, cell, keyspace, shard, tabletType, true, \/* create *\/\n\t\tfunc(endpoints *pb.EndPoints) bool {\n\t\t\t\/\/ Look for an existing entry to update.\n\t\t\tfor i := range endpoints.Entries {\n\t\t\t\tif endpoints.Entries[i].Uid == endpoint.Uid {\n\t\t\t\t\tif topo.EndPointEquality(endpoints.Entries[i], endpoint) {\n\t\t\t\t\t\t\/\/ The entry already exists and is the same.\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\t\/\/ Update an existing entry.\n\t\t\t\t\tendpoints.Entries[i] = endpoint\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ The entry doesn't exist, so add it.\n\t\t\tendpoints.Entries = append(endpoints.Entries, endpoint)\n\t\t\treturn true\n\t\t})\n}\n\nfunc removeEndpoint(ctx context.Context, ts topo.Server, cell, keyspace, shard string, tabletType topo.TabletType, tabletUID uint32) error {\n\terr := retryUpdateEndpoints(ctx, ts, cell, keyspace, shard, tabletType, false, \/* create *\/\n\t\tfunc(endpoints *pb.EndPoints) bool {\n\t\t\t\/\/ Make a new list, excluding the given UID.\n\t\t\tentries := make([]*pb.EndPoint, 0, len(endpoints.Entries))\n\t\t\tfor _, ep := range endpoints.Entries {\n\t\t\t\tif ep.Uid != tabletUID {\n\t\t\t\t\tentries = append(entries, ep)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(entries) == len(endpoints.Entries) {\n\t\t\t\t\/\/ Nothing was removed. Don't bother updating.\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t\/\/ Do the update.\n\t\t\tendpoints.Entries = entries\n\t\t\treturn true\n\t\t})\n\n\tif err == topo.ErrNoNode {\n\t\t\/\/ Our goal is to remove one endpoint. If the list is empty, we're fine.\n\t\terr = nil\n\t}\n\treturn err\n}\n\nfunc retryUpdateEndpoints(ctx context.Context, ts topo.Server, cell, keyspace, shard string, tabletType topo.TabletType, create bool, updateFunc func(*pb.EndPoints) bool) error {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\t\/\/ Get or create EndPoints list.\n\t\tendpoints, version, err := ts.GetEndPoints(ctx, cell, keyspace, shard, tabletType)\n\t\tif err == topo.ErrNoNode && create {\n\t\t\t\/\/ Create instead of updating.\n\t\t\tendpoints = &pb.EndPoints{}\n\t\t\tif !updateFunc(endpoints) {\n\t\t\t\t\/\/ Nothing changed.\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\terr = ts.CreateEndPoints(ctx, cell, keyspace, shard, tabletType, endpoints)\n\t\t\tif err == topo.ErrNodeExists {\n\t\t\t\t\/\/ Someone else beat us to it. Try again.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ We got an existing EndPoints list. Try to update.\n\t\tif !updateFunc(endpoints) {\n\t\t\t\/\/ Nothing changed.\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ If there's nothing left, we should delete the list entirely.\n\t\tif len(endpoints.Entries) == 0 {\n\t\t\terr = ts.DeleteEndPoints(ctx, cell, keyspace, shard, tabletType, version)\n\t\t\tswitch err {\n\t\t\tcase topo.ErrNoNode:\n\t\t\t\t\/\/ Someone beat us to it, which is fine.\n\t\t\t\treturn nil\n\t\t\tcase topo.ErrBadVersion:\n\t\t\t\t\/\/ Someone else updated the list. Try again.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\terr = ts.UpdateEndPoints(ctx, cell, keyspace, shard, tabletType, endpoints, version)\n\t\tif err == topo.ErrBadVersion || (err == topo.ErrNoNode && create) {\n\t\t\t\/\/ Someone else updated or deleted the list in the meantime. Try again.\n\t\t\tcontinue\n\t\t}\n\t\treturn err\n\t}\n}\n\n\/\/ UpdateTabletEndpoints fixes up any entries in the serving graph that relate\n\/\/ to a given tablet.\nfunc UpdateTabletEndpoints(ctx context.Context, ts topo.Server, tablet *topo.Tablet) (err error) {\n\tsrvTypes, err := ts.GetSrvTabletTypesPerShard(ctx, tablet.Alias.Cell, tablet.Keyspace, tablet.Shard)\n\tif err != nil {\n\t\tif err != topo.ErrNoNode {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ It's fine if there are no existing types.\n\t\tsrvTypes = nil\n\t}\n\n\twg := sync.WaitGroup{}\n\terrs := concurrency.AllErrorRecorder{}\n\n\t\/\/ Update the list that the tablet is supposed to be in (if any).\n\tif tablet.IsInServingGraph() {\n\t\tendpoint, err := tablet.EndPoint()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\terrs.RecordError(\n\t\t\t\tupdateEndpoint(ctx, ts, tablet.Alias.Cell, tablet.Keyspace, tablet.Shard,\n\t\t\t\t\ttablet.Type, endpoint))\n\t\t}()\n\t}\n\n\t\/\/ Remove it from any other lists it isn't supposed to be in.\n\tfor _, srvType := range srvTypes {\n\t\tif srvType != tablet.Type {\n\t\t\twg.Add(1)\n\t\t\tgo func(tabletType topo.TabletType) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\terrs.RecordError(\n\t\t\t\t\tremoveEndpoint(ctx, ts, tablet.Alias.Cell, tablet.Keyspace, tablet.Shard,\n\t\t\t\t\t\ttabletType, tablet.Alias.Uid))\n\t\t\t}(srvType)\n\t\t}\n\t}\n\n\twg.Wait()\n\treturn errs.Error()\n}\n\n\/\/ UpdateSrvShard creates the SrvShard object based on the global ShardInfo,\n\/\/ and writes it to the given cell.\nfunc UpdateSrvShard(ctx context.Context, ts topo.Server, cell string, si *topo.ShardInfo) error {\n\tsrvShard := &topo.SrvShard{\n\t\tName:       si.ShardName(),\n\t\tKeyRange:   si.KeyRange,\n\t\tMasterCell: si.MasterAlias.Cell,\n\t}\n\treturn ts.UpdateSrvShard(ctx, cell, si.Keyspace(), si.ShardName(), srvShard)\n}\n\n\/\/ UpdateAllSrvShards calls UpdateSrvShard for all cells concurrently.\nfunc UpdateAllSrvShards(ctx context.Context, ts topo.Server, si *topo.ShardInfo) error {\n\twg := sync.WaitGroup{}\n\terrs := concurrency.AllErrorRecorder{}\n\n\tfor _, cell := range si.Cells {\n\t\twg.Add(1)\n\t\tgo func(cell string) {\n\t\t\terrs.RecordError(UpdateSrvShard(ctx, ts, cell, si))\n\t\t\twg.Done()\n\t\t}(cell)\n\t}\n\twg.Wait()\n\treturn errs.Error()\n}\n<|endoftext|>"}
{"text":"<commit_before>package measurements_test\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\n\t\"github.com\/vito\/gordon\/warden\"\n)\n\nvar _ = Describe(\"The Warden server\", func() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\tDescribe(\"streaming output from a chatty job\", func() {\n\t\tvar handle string\n\n\t\tBeforeEach(func() {\n\t\t\tres, err := client.Create()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\thandle = res.GetHandle()\n\t\t})\n\n\t\tstreamCounts := []int{0}\n\n\t\tfor i := 1; i <= 128; i *= 2 {\n\t\t\tstreamCounts = append(streamCounts, i)\n\t\t}\n\n\t\tfor _, streams := range streamCounts {\n\t\t\tContext(fmt.Sprintf(\"with %d streams\", streams), func() {\n\t\t\t\tvar started time.Time\n\t\t\t\tvar receivedBytes uint64\n\n\t\t\t\tnumToSpawn := streams\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\treceivedBytes = 0\n\t\t\t\t\tstarted = time.Now()\n\n\t\t\t\t\tspawned := make(chan bool)\n\n\t\t\t\t\tfor j := 0; j < numToSpawn; j++ {\n\t\t\t\t\t\tgo func() {\n\t\t\t\t\t\t\t_, results, err := client.Run(\n\t\t\t\t\t\t\t\thandle,\n\t\t\t\t\t\t\t\t\"cat \/dev\/zero\",\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\t\tgo func(results <-chan *warden.ProcessPayload) {\n\t\t\t\t\t\t\t\tfor {\n\t\t\t\t\t\t\t\t\tres, ok := <-results\n\t\t\t\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tatomic.AddUint64(&receivedBytes, uint64(len(res.GetData())))\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}(results)\n\n\t\t\t\t\t\t\tspawned <- true\n\t\t\t\t\t\t}()\n\t\t\t\t\t}\n\n\t\t\t\t\tfor j := 0; j < numToSpawn; j++ {\n\t\t\t\t\t\t<-spawned\n\t\t\t\t\t}\n\t\t\t\t})\n\n\t\t\t\tAfterEach(func() {\n\t\t\t\t\t_, err := client.Destroy(handle)\n\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t})\n\n\t\t\t\tMeasure(\"it should not adversely affect the rest of the API\", func(b Benchmarker) {\n\t\t\t\t\tvar newHandle string\n\n\t\t\t\t\tb.Time(\"creating another container\", func() {\n\t\t\t\t\t\tres, err := client.Create()\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\tnewHandle = res.GetHandle()\n\t\t\t\t\t})\n\n\t\t\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\t\t\tb.Time(\"getting container info (10x)\", func() {\n\t\t\t\t\t\t\t_, err := client.Info(newHandle)\n\t\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\n\t\t\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\t\t\tb.Time(\"running a job (10x)\", func() {\n\t\t\t\t\t\t\t_, stream, err := client.Run(newHandle, \"ls\")\n\t\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\t\tfor _ = range stream {\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\n\t\t\t\t\tb.Time(\"destroying the container\", func() {\n\t\t\t\t\t\t_, err := client.Destroy(newHandle)\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\t})\n\n\t\t\t\t\tb.RecordValue(\n\t\t\t\t\t\t\"received rate (bytes\/second)\",\n\t\t\t\t\t\tfloat64(receivedBytes)\/float64(time.Since(started)\/time.Second),\n\t\t\t\t\t)\n\n\t\t\t\t\tfmt.Println(\"total time:\", time.Since(started))\n\t\t\t\t}, 5)\n\t\t\t})\n\t\t}\n\t})\n})\n<commit_msg>Set and get atomic integer atomically.<commit_after>package measurements_test\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\n\t\"github.com\/vito\/gordon\/warden\"\n)\n\nvar _ = Describe(\"The Warden server\", func() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\tDescribe(\"streaming output from a chatty job\", func() {\n\t\tvar handle string\n\n\t\tBeforeEach(func() {\n\t\t\tres, err := client.Create()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\thandle = res.GetHandle()\n\t\t})\n\n\t\tstreamCounts := []int{0}\n\n\t\tfor i := 1; i <= 128; i *= 2 {\n\t\t\tstreamCounts = append(streamCounts, i)\n\t\t}\n\n\t\tfor _, streams := range streamCounts {\n\t\t\tContext(fmt.Sprintf(\"with %d streams\", streams), func() {\n\t\t\t\tvar started time.Time\n\t\t\t\tvar receivedBytes uint64\n\n\t\t\t\tnumToSpawn := streams\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tatomic.StoreUint64(&receivedBytes, 0) \n\t\t\t\t\tstarted = time.Now()\n\n\t\t\t\t\tspawned := make(chan bool)\n\n\t\t\t\t\tfor j := 0; j < numToSpawn; j++ {\n\t\t\t\t\t\tgo func() {\n\t\t\t\t\t\t\tdefer GinkgoRecover()\n\t\t\t\t\t\t\t_, results, err := client.Run(\n\t\t\t\t\t\t\t\thandle,\n\t\t\t\t\t\t\t\t\"cat \/dev\/zero\",\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\t\tgo func(results <-chan *warden.ProcessPayload) {\n\t\t\t\t\t\t\t\tfor {\n\t\t\t\t\t\t\t\t\tres, ok := <-results\n\t\t\t\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tatomic.AddUint64(&receivedBytes, uint64(len(res.GetData())))\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}(results)\n\n\t\t\t\t\t\t\tspawned <- true\n\t\t\t\t\t\t}()\n\t\t\t\t\t}\n\n\t\t\t\t\tfor j := 0; j < numToSpawn; j++ {\n\t\t\t\t\t\t<-spawned\n\t\t\t\t\t}\n\t\t\t\t})\n\n\t\t\t\tAfterEach(func() {\n\t\t\t\t\t_, err := client.Destroy(handle)\n\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t})\n\n\t\t\t\tMeasure(\"it should not adversely affect the rest of the API\", func(b Benchmarker) {\n\t\t\t\t\tvar newHandle string\n\n\t\t\t\t\tb.Time(\"creating another container\", func() {\n\t\t\t\t\t\tres, err := client.Create()\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\tnewHandle = res.GetHandle()\n\t\t\t\t\t})\n\n\t\t\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\t\t\tb.Time(\"getting container info (10x)\", func() {\n\t\t\t\t\t\t\t_, err := client.Info(newHandle)\n\t\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\n\t\t\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\t\t\tb.Time(\"running a job (10x)\", func() {\n\t\t\t\t\t\t\t_, stream, err := client.Run(newHandle, \"ls\")\n\t\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\t\tfor _ = range stream {\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\n\t\t\t\t\tb.Time(\"destroying the container\", func() {\n\t\t\t\t\t\t_, err := client.Destroy(newHandle)\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\t})\n\n\t\t\t\t\tb.RecordValue(\n\t\t\t\t\t\t\"received rate (bytes\/second)\",\n\t\t\t\t\t\tfloat64(atomic.LoadUint64(&receivedBytes))\/float64(time.Since(started)\/time.Second),\n\t\t\t\t\t)\n\n\t\t\t\t\tfmt.Println(\"total time:\", time.Since(started))\n\t\t\t\t}, 5)\n\t\t\t})\n\t\t}\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2016 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\npackage mqtt\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/TheThingsNetwork\/ttn\/utils\/random\"\n\t\"github.com\/apex\/log\"\n\tMQTT \"github.com\/eclipse\/paho.mqtt.golang\"\n)\n\nconst QoS = 0x00\n\n\/\/ Client connects to the MQTT server and can publish\/subscribe on uplink, downlink and activations from devices\ntype Client interface {\n\tConnect() error\n\tDisconnect()\n\n\tIsConnected() bool\n\n\t\/\/ Uplink pub\/sub\n\tPublishUplink(payload UplinkMessage) Token\n\tSubscribeDeviceUplink(appID string, devID string, handler UplinkHandler) Token\n\tSubscribeAppUplink(appID string, handler UplinkHandler) Token\n\tSubscribeUplink(handler UplinkHandler) Token\n\tUnsubscribeDeviceUplink(appID string, devID string) Token\n\tUnsubscribeAppUplink(appID string) Token\n\tUnsubscribeUplink() Token\n\n\t\/\/ Downlink pub\/sub\n\tPublishDownlink(payload DownlinkMessage) Token\n\tSubscribeDeviceDownlink(appID string, devID string, handler DownlinkHandler) Token\n\tSubscribeAppDownlink(appID string, handler DownlinkHandler) Token\n\tSubscribeDownlink(handler DownlinkHandler) Token\n\tUnsubscribeDeviceDownlink(appID string, devID string) Token\n\tUnsubscribeAppDownlink(appID string) Token\n\tUnsubscribeDownlink() Token\n\n\t\/\/ Activation pub\/sub\n\tPublishActivation(payload Activation) Token\n\tSubscribeDeviceActivations(appID string, devID string, handler ActivationHandler) Token\n\tSubscribeAppActivations(appID string, handler ActivationHandler) Token\n\tSubscribeActivations(handler ActivationHandler) Token\n\tUnsubscribeDeviceActivations(appID string, devID string) Token\n\tUnsubscribeAppActivations(appID string) Token\n\tUnsubscribeActivations() Token\n}\n\n\/\/ Token is returned on asyncronous functions\ntype Token interface {\n\t\/\/ Wait for the function to finish\n\tWait() bool\n\t\/\/ Wait for the function to finish or return false after a certain time\n\tWaitTimeout(time.Duration) bool\n\t\/\/ The error associated with the result of the function (nil if everything okay)\n\tError() error\n}\n\ntype simpleToken struct {\n\terr error\n}\n\n\/\/ Wait always returns true\nfunc (t *simpleToken) Wait() bool {\n\treturn true\n}\n\n\/\/ WaitTimeout always returns true\nfunc (t *simpleToken) WaitTimeout(_ time.Duration) bool {\n\treturn true\n}\n\n\/\/ Error contains the error if present\nfunc (t *simpleToken) Error() error {\n\treturn t.err\n}\n\n\/\/ UplinkHandler is called for uplink messages\ntype UplinkHandler func(client Client, appID string, devID string, req UplinkMessage)\n\n\/\/ DownlinkHandler is called for downlink messages\ntype DownlinkHandler func(client Client, appID string, devID string, req DownlinkMessage)\n\n\/\/ ActivationHandler is called for activations\ntype ActivationHandler func(client Client, appID string, devID string, req Activation)\n\n\/\/ DefaultClient is the default MQTT client for The Things Network\ntype DefaultClient struct {\n\tmqtt          MQTT.Client\n\tctx           log.Interface\n\tsubscriptions map[string]MQTT.MessageHandler\n}\n\n\/\/ NewClient creates a new DefaultClient\nfunc NewClient(ctx log.Interface, id, username, password string, brokers ...string) Client {\n\tmqttOpts := MQTT.NewClientOptions()\n\n\tfor _, broker := range brokers {\n\t\tmqttOpts.AddBroker(broker)\n\t}\n\n\tmqttOpts.SetClientID(fmt.Sprintf(\"%s-%s\", id, random.String(16)))\n\tmqttOpts.SetUsername(username)\n\tmqttOpts.SetPassword(password)\n\n\t\/\/ TODO: Some tuning of these values probably won't hurt:\n\tmqttOpts.SetKeepAlive(30 * time.Second)\n\tmqttOpts.SetPingTimeout(10 * time.Second)\n\n\tmqttOpts.SetCleanSession(true)\n\n\tmqttOpts.SetDefaultPublishHandler(func(client MQTT.Client, msg MQTT.Message) {\n\t\tctx.WithField(\"message\", msg).Warn(\"Received unhandled message\")\n\t})\n\n\tvar reconnecting bool\n\n\tmqttOpts.SetConnectionLostHandler(func(client MQTT.Client, err error) {\n\t\tctx.WithError(err).Warn(\"Disconnected, reconnecting...\")\n\t\treconnecting = true\n\t})\n\n\tttnClient := &DefaultClient{\n\t\tctx:           ctx,\n\t\tsubscriptions: make(map[string]MQTT.MessageHandler),\n\t}\n\n\tmqttOpts.SetOnConnectHandler(func(client MQTT.Client) {\n\t\tctx.Info(\"Connected to MQTT\")\n\t\tif reconnecting {\n\t\t\tfor topic, handler := range ttnClient.subscriptions {\n\t\t\t\tctx.Infof(\"Re-subscribing to %s\", topic)\n\t\t\t\tttnClient.subscribe(topic, handler)\n\t\t\t}\n\t\t\treconnecting = false\n\t\t}\n\t})\n\n\tttnClient.mqtt = MQTT.NewClient(mqttOpts)\n\n\treturn ttnClient\n}\n\nvar (\n\t\/\/ ConnectRetries says how many times the client should retry a failed connection\n\tConnectRetries = 10\n\t\/\/ ConnectRetryDelay says how long the client should wait between retries\n\tConnectRetryDelay = time.Second\n)\n\n\/\/ Connect to the MQTT broker. It will retry for ConnectRetries times with a delay of ConnectRetryDelay between retries\nfunc (c *DefaultClient) Connect() error {\n\tif c.mqtt.IsConnected() {\n\t\treturn nil\n\t}\n\tvar err error\n\tfor retries := 0; retries < ConnectRetries; retries++ {\n\t\tc.ctx.Debug(\"Connecting to MQTT...\")\n\t\ttoken := c.mqtt.Connect()\n\t\ttoken.Wait()\n\t\terr = token.Error()\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\t<-time.After(ConnectRetryDelay)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not connect: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc (c *DefaultClient) subscribe(topic string, handler MQTT.MessageHandler) Token {\n\tc.subscriptions[topic] = handler\n\treturn c.mqtt.Subscribe(topic, QoS, handler)\n}\n\nfunc (c *DefaultClient) unsubscribe(topic string) Token {\n\tdelete(c.subscriptions, topic)\n\treturn c.mqtt.Unsubscribe(topic)\n}\n\n\/\/ Disconnect from the MQTT broker\nfunc (c *DefaultClient) Disconnect() {\n\tif !c.mqtt.IsConnected() {\n\t\treturn\n\t}\n\tc.ctx.Debug(\"Disconnecting from MQTT\")\n\tc.mqtt.Disconnect(25)\n}\n\n\/\/ IsConnected returns true if there is a connection to the MQTT broker\nfunc (c *DefaultClient) IsConnected() bool {\n\treturn c.mqtt.IsConnected()\n}\n\n\/\/ PublishUplink publishes an uplink message to the MQTT broker\nfunc (c *DefaultClient) PublishUplink(dataUp UplinkMessage) Token {\n\ttopic := DeviceTopic{dataUp.AppID, dataUp.DevID, Uplink}\n\tdataUp.AppID = \"\"\n\tdataUp.DevID = \"\"\n\tmsg, err := json.Marshal(dataUp)\n\tif err != nil {\n\t\treturn &simpleToken{fmt.Errorf(\"Unable to marshal the message payload\")}\n\t}\n\treturn c.mqtt.Publish(topic.String(), QoS, false, msg)\n}\n\n\/\/ SubscribeDeviceUplink subscribes to all uplink messages for the given application and device\nfunc (c *DefaultClient) SubscribeDeviceUplink(appID string, devID string, handler UplinkHandler) Token {\n\ttopic := DeviceTopic{appID, devID, Uplink}\n\treturn c.subscribe(topic.String(), func(mqtt MQTT.Client, msg MQTT.Message) {\n\t\t\/\/ Determine the actual topic\n\t\ttopic, err := ParseDeviceTopic(msg.Topic())\n\t\tif err != nil {\n\t\t\tc.ctx.WithField(\"topic\", msg.Topic()).WithError(err).Warn(\"Received message on invalid uplink topic\")\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Unmarshal the payload\n\t\tdataUp := &UplinkMessage{}\n\t\terr = json.Unmarshal(msg.Payload(), dataUp)\n\t\tdataUp.AppID = topic.AppID\n\t\tdataUp.DevID = topic.DevID\n\n\t\tif err != nil {\n\t\t\tc.ctx.WithError(err).Warn(\"Could not unmarshal uplink\")\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Call the uplink handler\n\t\thandler(c, topic.AppID, topic.DevID, *dataUp)\n\t})\n}\n\n\/\/ SubscribeAppUplink subscribes to all uplink messages for the given application\nfunc (c *DefaultClient) SubscribeAppUplink(appID string, handler UplinkHandler) Token {\n\treturn c.SubscribeDeviceUplink(appID, \"\", handler)\n}\n\n\/\/ SubscribeUplink subscribes to all uplink messages that the current user has access to\nfunc (c *DefaultClient) SubscribeUplink(handler UplinkHandler) Token {\n\treturn c.SubscribeDeviceUplink(\"\", \"\", handler)\n}\n\n\/\/ UnsubscribeDeviceUplink unsubscribes from the uplink messages for the given application and device\nfunc (c *DefaultClient) UnsubscribeDeviceUplink(appID string, devID string) Token {\n\ttopic := DeviceTopic{appID, devID, Uplink}\n\treturn c.unsubscribe(topic.String())\n}\n\n\/\/ UnsubscribeAppUplink unsubscribes from the uplink messages for the given application\nfunc (c *DefaultClient) UnsubscribeAppUplink(appID string) Token {\n\treturn c.UnsubscribeDeviceUplink(appID, \"\")\n}\n\n\/\/ UnsubscribeUplink unsubscribes from the uplink messages that the current user has access to\nfunc (c *DefaultClient) UnsubscribeUplink() Token {\n\treturn c.UnsubscribeDeviceUplink(\"\", \"\")\n}\n\n\/\/ PublishDownlink publishes a downlink message\nfunc (c *DefaultClient) PublishDownlink(dataDown DownlinkMessage) Token {\n\ttopic := DeviceTopic{dataDown.AppID, dataDown.DevID, Downlink}\n\tdataDown.AppID = \"\"\n\tdataDown.DevID = \"\"\n\tmsg, err := json.Marshal(dataDown)\n\tif err != nil {\n\t\treturn &simpleToken{fmt.Errorf(\"Unable to marshal the message payload\")}\n\t}\n\treturn c.mqtt.Publish(topic.String(), QoS, false, msg)\n}\n\n\/\/ SubscribeDeviceDownlink subscribes to all downlink messages for the given application and device\nfunc (c *DefaultClient) SubscribeDeviceDownlink(appID string, devID string, handler DownlinkHandler) Token {\n\ttopic := DeviceTopic{appID, devID, Downlink}\n\treturn c.subscribe(topic.String(), func(mqtt MQTT.Client, msg MQTT.Message) {\n\t\t\/\/ Determine the actual topic\n\t\ttopic, err := ParseDeviceTopic(msg.Topic())\n\t\tif err != nil {\n\t\t\tc.ctx.WithField(\"topic\", msg.Topic()).WithError(err).Warn(\"Received message on invalid Downlink topic\")\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Unmarshal the payload\n\t\tdataDown := &DownlinkMessage{}\n\t\terr = json.Unmarshal(msg.Payload(), dataDown)\n\t\tif err != nil {\n\t\t\tc.ctx.WithError(err).Warn(\"Could not unmarshal Downlink\")\n\t\t\treturn\n\t\t}\n\t\tdataDown.AppID = topic.AppID\n\t\tdataDown.DevID = topic.DevID\n\n\t\t\/\/ Call the Downlink handler\n\t\thandler(c, topic.AppID, topic.DevID, *dataDown)\n\t})\n}\n\n\/\/ SubscribeAppDownlink subscribes to all downlink messages for the given application\nfunc (c *DefaultClient) SubscribeAppDownlink(appID string, handler DownlinkHandler) Token {\n\treturn c.SubscribeDeviceDownlink(appID, \"\", handler)\n}\n\n\/\/ SubscribeDownlink subscribes to all downlink messages that the current user has access to\nfunc (c *DefaultClient) SubscribeDownlink(handler DownlinkHandler) Token {\n\treturn c.SubscribeDeviceDownlink(\"\", \"\", handler)\n}\n\n\/\/ UnsubscribeDeviceDownlink unsubscribes from the downlink messages for the given application and device\nfunc (c *DefaultClient) UnsubscribeDeviceDownlink(appID string, devID string) Token {\n\ttopic := DeviceTopic{appID, devID, Downlink}\n\treturn c.unsubscribe(topic.String())\n}\n\n\/\/ UnsubscribeAppDownlink unsubscribes from the downlink messages for the given application\nfunc (c *DefaultClient) UnsubscribeAppDownlink(appID string) Token {\n\treturn c.UnsubscribeDeviceDownlink(appID, \"\")\n}\n\n\/\/ UnsubscribeDownlink unsubscribes from the downlink messages that the current user has access to\nfunc (c *DefaultClient) UnsubscribeDownlink() Token {\n\treturn c.UnsubscribeDeviceDownlink(\"\", \"\")\n}\n\n\/\/ PublishActivation publishes an activation\nfunc (c *DefaultClient) PublishActivation(activation Activation) Token {\n\ttopic := DeviceTopic{activation.AppID, activation.DevID, Activations}\n\tactivation.AppID = \"\"\n\tactivation.DevID = \"\"\n\tmsg, err := json.Marshal(activation)\n\tif err != nil {\n\t\treturn &simpleToken{fmt.Errorf(\"Unable to marshal the message payload\")}\n\t}\n\treturn c.mqtt.Publish(topic.String(), QoS, false, msg)\n}\n\n\/\/ SubscribeDeviceActivations subscribes to all activations for the given application and device\nfunc (c *DefaultClient) SubscribeDeviceActivations(appID string, devID string, handler ActivationHandler) Token {\n\ttopic := DeviceTopic{appID, devID, Activations}\n\treturn c.subscribe(topic.String(), func(mqtt MQTT.Client, msg MQTT.Message) {\n\t\t\/\/ Determine the actual topic\n\t\ttopic, err := ParseDeviceTopic(msg.Topic())\n\t\tif err != nil {\n\t\t\tc.ctx.WithField(\"topic\", msg.Topic()).WithError(err).Warn(\"Received message on invalid Activations topic\")\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Unmarshal the payload\n\t\tactivation := &Activation{}\n\t\terr = json.Unmarshal(msg.Payload(), activation)\n\t\tif err != nil {\n\t\t\tc.ctx.WithError(err).Warn(\"Could not unmarshal Activation\")\n\t\t\treturn\n\t\t}\n\t\tactivation.AppID = topic.AppID\n\t\tactivation.DevID = topic.DevID\n\n\t\t\/\/ Call the Activation handler\n\t\thandler(c, topic.AppID, topic.DevID, *activation)\n\t})\n}\n\n\/\/ SubscribeAppActivations subscribes to all activations for the given application\nfunc (c *DefaultClient) SubscribeAppActivations(appID string, handler ActivationHandler) Token {\n\treturn c.SubscribeDeviceActivations(appID, \"\", handler)\n}\n\n\/\/ SubscribeActivations subscribes to all activations that the current user has access to\nfunc (c *DefaultClient) SubscribeActivations(handler ActivationHandler) Token {\n\treturn c.SubscribeDeviceActivations(\"\", \"\", handler)\n}\n\n\/\/ UnsubscribeDeviceActivations unsubscribes from the activations for the given application and device\nfunc (c *DefaultClient) UnsubscribeDeviceActivations(appID string, devID string) Token {\n\ttopic := DeviceTopic{appID, devID, Activations}\n\treturn c.unsubscribe(topic.String())\n}\n\n\/\/ UnsubscribeAppActivations unsubscribes from the activations for the given application\nfunc (c *DefaultClient) UnsubscribeAppActivations(appID string) Token {\n\treturn c.UnsubscribeDeviceActivations(appID, \"\")\n}\n\n\/\/ UnsubscribeActivations unsubscribes from the activations that the current user has access to\nfunc (c *DefaultClient) UnsubscribeActivations() Token {\n\treturn c.UnsubscribeDeviceActivations(\"\", \"\")\n}\n<commit_msg>Don't wait more than 1 second in MQTT connection attempt<commit_after>\/\/ Copyright © 2016 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\npackage mqtt\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/TheThingsNetwork\/ttn\/utils\/random\"\n\t\"github.com\/apex\/log\"\n\tMQTT \"github.com\/eclipse\/paho.mqtt.golang\"\n)\n\nconst QoS = 0x00\n\n\/\/ Client connects to the MQTT server and can publish\/subscribe on uplink, downlink and activations from devices\ntype Client interface {\n\tConnect() error\n\tDisconnect()\n\n\tIsConnected() bool\n\n\t\/\/ Uplink pub\/sub\n\tPublishUplink(payload UplinkMessage) Token\n\tSubscribeDeviceUplink(appID string, devID string, handler UplinkHandler) Token\n\tSubscribeAppUplink(appID string, handler UplinkHandler) Token\n\tSubscribeUplink(handler UplinkHandler) Token\n\tUnsubscribeDeviceUplink(appID string, devID string) Token\n\tUnsubscribeAppUplink(appID string) Token\n\tUnsubscribeUplink() Token\n\n\t\/\/ Downlink pub\/sub\n\tPublishDownlink(payload DownlinkMessage) Token\n\tSubscribeDeviceDownlink(appID string, devID string, handler DownlinkHandler) Token\n\tSubscribeAppDownlink(appID string, handler DownlinkHandler) Token\n\tSubscribeDownlink(handler DownlinkHandler) Token\n\tUnsubscribeDeviceDownlink(appID string, devID string) Token\n\tUnsubscribeAppDownlink(appID string) Token\n\tUnsubscribeDownlink() Token\n\n\t\/\/ Activation pub\/sub\n\tPublishActivation(payload Activation) Token\n\tSubscribeDeviceActivations(appID string, devID string, handler ActivationHandler) Token\n\tSubscribeAppActivations(appID string, handler ActivationHandler) Token\n\tSubscribeActivations(handler ActivationHandler) Token\n\tUnsubscribeDeviceActivations(appID string, devID string) Token\n\tUnsubscribeAppActivations(appID string) Token\n\tUnsubscribeActivations() Token\n}\n\n\/\/ Token is returned on asyncronous functions\ntype Token interface {\n\t\/\/ Wait for the function to finish\n\tWait() bool\n\t\/\/ Wait for the function to finish or return false after a certain time\n\tWaitTimeout(time.Duration) bool\n\t\/\/ The error associated with the result of the function (nil if everything okay)\n\tError() error\n}\n\ntype simpleToken struct {\n\terr error\n}\n\n\/\/ Wait always returns true\nfunc (t *simpleToken) Wait() bool {\n\treturn true\n}\n\n\/\/ WaitTimeout always returns true\nfunc (t *simpleToken) WaitTimeout(_ time.Duration) bool {\n\treturn true\n}\n\n\/\/ Error contains the error if present\nfunc (t *simpleToken) Error() error {\n\treturn t.err\n}\n\n\/\/ UplinkHandler is called for uplink messages\ntype UplinkHandler func(client Client, appID string, devID string, req UplinkMessage)\n\n\/\/ DownlinkHandler is called for downlink messages\ntype DownlinkHandler func(client Client, appID string, devID string, req DownlinkMessage)\n\n\/\/ ActivationHandler is called for activations\ntype ActivationHandler func(client Client, appID string, devID string, req Activation)\n\n\/\/ DefaultClient is the default MQTT client for The Things Network\ntype DefaultClient struct {\n\tmqtt          MQTT.Client\n\tctx           log.Interface\n\tsubscriptions map[string]MQTT.MessageHandler\n}\n\n\/\/ NewClient creates a new DefaultClient\nfunc NewClient(ctx log.Interface, id, username, password string, brokers ...string) Client {\n\tmqttOpts := MQTT.NewClientOptions()\n\n\tfor _, broker := range brokers {\n\t\tmqttOpts.AddBroker(broker)\n\t}\n\n\tmqttOpts.SetClientID(fmt.Sprintf(\"%s-%s\", id, random.String(16)))\n\tmqttOpts.SetUsername(username)\n\tmqttOpts.SetPassword(password)\n\n\t\/\/ TODO: Some tuning of these values probably won't hurt:\n\tmqttOpts.SetKeepAlive(30 * time.Second)\n\tmqttOpts.SetPingTimeout(10 * time.Second)\n\n\tmqttOpts.SetCleanSession(true)\n\n\tmqttOpts.SetDefaultPublishHandler(func(client MQTT.Client, msg MQTT.Message) {\n\t\tctx.WithField(\"message\", msg).Warn(\"Received unhandled message\")\n\t})\n\n\tvar reconnecting bool\n\n\tmqttOpts.SetConnectionLostHandler(func(client MQTT.Client, err error) {\n\t\tctx.WithError(err).Warn(\"Disconnected, reconnecting...\")\n\t\treconnecting = true\n\t})\n\n\tttnClient := &DefaultClient{\n\t\tctx:           ctx,\n\t\tsubscriptions: make(map[string]MQTT.MessageHandler),\n\t}\n\n\tmqttOpts.SetOnConnectHandler(func(client MQTT.Client) {\n\t\tctx.Info(\"Connected to MQTT\")\n\t\tif reconnecting {\n\t\t\tfor topic, handler := range ttnClient.subscriptions {\n\t\t\t\tctx.Infof(\"Re-subscribing to %s\", topic)\n\t\t\t\tttnClient.subscribe(topic, handler)\n\t\t\t}\n\t\t\treconnecting = false\n\t\t}\n\t})\n\n\tttnClient.mqtt = MQTT.NewClient(mqttOpts)\n\n\treturn ttnClient\n}\n\nvar (\n\t\/\/ ConnectRetries says how many times the client should retry a failed connection\n\tConnectRetries = 10\n\t\/\/ ConnectRetryDelay says how long the client should wait between retries\n\tConnectRetryDelay = time.Second\n)\n\n\/\/ Connect to the MQTT broker. It will retry for ConnectRetries times with a delay of ConnectRetryDelay between retries\nfunc (c *DefaultClient) Connect() error {\n\tif c.mqtt.IsConnected() {\n\t\treturn nil\n\t}\n\tvar err error\n\tfor retries := 0; retries < ConnectRetries; retries++ {\n\t\ttoken := c.mqtt.Connect()\n\t\tfinished := token.WaitTimeout(1 * time.Second)\n\t\terr = token.Error()\n\t\tif finished && err == nil {\n\t\t\tbreak\n\t\t}\n\t\tc.ctx.WithError(err).Warn(\"Could not connect to MQTT Broker. Retrying...\")\n\t\t<-time.After(ConnectRetryDelay)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not connect to MQTT Broker: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc (c *DefaultClient) subscribe(topic string, handler MQTT.MessageHandler) Token {\n\tc.subscriptions[topic] = handler\n\treturn c.mqtt.Subscribe(topic, QoS, handler)\n}\n\nfunc (c *DefaultClient) unsubscribe(topic string) Token {\n\tdelete(c.subscriptions, topic)\n\treturn c.mqtt.Unsubscribe(topic)\n}\n\n\/\/ Disconnect from the MQTT broker\nfunc (c *DefaultClient) Disconnect() {\n\tif !c.mqtt.IsConnected() {\n\t\treturn\n\t}\n\tc.ctx.Debug(\"Disconnecting from MQTT\")\n\tc.mqtt.Disconnect(25)\n}\n\n\/\/ IsConnected returns true if there is a connection to the MQTT broker\nfunc (c *DefaultClient) IsConnected() bool {\n\treturn c.mqtt.IsConnected()\n}\n\n\/\/ PublishUplink publishes an uplink message to the MQTT broker\nfunc (c *DefaultClient) PublishUplink(dataUp UplinkMessage) Token {\n\ttopic := DeviceTopic{dataUp.AppID, dataUp.DevID, Uplink}\n\tdataUp.AppID = \"\"\n\tdataUp.DevID = \"\"\n\tmsg, err := json.Marshal(dataUp)\n\tif err != nil {\n\t\treturn &simpleToken{fmt.Errorf(\"Unable to marshal the message payload\")}\n\t}\n\treturn c.mqtt.Publish(topic.String(), QoS, false, msg)\n}\n\n\/\/ SubscribeDeviceUplink subscribes to all uplink messages for the given application and device\nfunc (c *DefaultClient) SubscribeDeviceUplink(appID string, devID string, handler UplinkHandler) Token {\n\ttopic := DeviceTopic{appID, devID, Uplink}\n\treturn c.subscribe(topic.String(), func(mqtt MQTT.Client, msg MQTT.Message) {\n\t\t\/\/ Determine the actual topic\n\t\ttopic, err := ParseDeviceTopic(msg.Topic())\n\t\tif err != nil {\n\t\t\tc.ctx.WithField(\"topic\", msg.Topic()).WithError(err).Warn(\"Received message on invalid uplink topic\")\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Unmarshal the payload\n\t\tdataUp := &UplinkMessage{}\n\t\terr = json.Unmarshal(msg.Payload(), dataUp)\n\t\tdataUp.AppID = topic.AppID\n\t\tdataUp.DevID = topic.DevID\n\n\t\tif err != nil {\n\t\t\tc.ctx.WithError(err).Warn(\"Could not unmarshal uplink\")\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Call the uplink handler\n\t\thandler(c, topic.AppID, topic.DevID, *dataUp)\n\t})\n}\n\n\/\/ SubscribeAppUplink subscribes to all uplink messages for the given application\nfunc (c *DefaultClient) SubscribeAppUplink(appID string, handler UplinkHandler) Token {\n\treturn c.SubscribeDeviceUplink(appID, \"\", handler)\n}\n\n\/\/ SubscribeUplink subscribes to all uplink messages that the current user has access to\nfunc (c *DefaultClient) SubscribeUplink(handler UplinkHandler) Token {\n\treturn c.SubscribeDeviceUplink(\"\", \"\", handler)\n}\n\n\/\/ UnsubscribeDeviceUplink unsubscribes from the uplink messages for the given application and device\nfunc (c *DefaultClient) UnsubscribeDeviceUplink(appID string, devID string) Token {\n\ttopic := DeviceTopic{appID, devID, Uplink}\n\treturn c.unsubscribe(topic.String())\n}\n\n\/\/ UnsubscribeAppUplink unsubscribes from the uplink messages for the given application\nfunc (c *DefaultClient) UnsubscribeAppUplink(appID string) Token {\n\treturn c.UnsubscribeDeviceUplink(appID, \"\")\n}\n\n\/\/ UnsubscribeUplink unsubscribes from the uplink messages that the current user has access to\nfunc (c *DefaultClient) UnsubscribeUplink() Token {\n\treturn c.UnsubscribeDeviceUplink(\"\", \"\")\n}\n\n\/\/ PublishDownlink publishes a downlink message\nfunc (c *DefaultClient) PublishDownlink(dataDown DownlinkMessage) Token {\n\ttopic := DeviceTopic{dataDown.AppID, dataDown.DevID, Downlink}\n\tdataDown.AppID = \"\"\n\tdataDown.DevID = \"\"\n\tmsg, err := json.Marshal(dataDown)\n\tif err != nil {\n\t\treturn &simpleToken{fmt.Errorf(\"Unable to marshal the message payload\")}\n\t}\n\treturn c.mqtt.Publish(topic.String(), QoS, false, msg)\n}\n\n\/\/ SubscribeDeviceDownlink subscribes to all downlink messages for the given application and device\nfunc (c *DefaultClient) SubscribeDeviceDownlink(appID string, devID string, handler DownlinkHandler) Token {\n\ttopic := DeviceTopic{appID, devID, Downlink}\n\treturn c.subscribe(topic.String(), func(mqtt MQTT.Client, msg MQTT.Message) {\n\t\t\/\/ Determine the actual topic\n\t\ttopic, err := ParseDeviceTopic(msg.Topic())\n\t\tif err != nil {\n\t\t\tc.ctx.WithField(\"topic\", msg.Topic()).WithError(err).Warn(\"Received message on invalid Downlink topic\")\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Unmarshal the payload\n\t\tdataDown := &DownlinkMessage{}\n\t\terr = json.Unmarshal(msg.Payload(), dataDown)\n\t\tif err != nil {\n\t\t\tc.ctx.WithError(err).Warn(\"Could not unmarshal Downlink\")\n\t\t\treturn\n\t\t}\n\t\tdataDown.AppID = topic.AppID\n\t\tdataDown.DevID = topic.DevID\n\n\t\t\/\/ Call the Downlink handler\n\t\thandler(c, topic.AppID, topic.DevID, *dataDown)\n\t})\n}\n\n\/\/ SubscribeAppDownlink subscribes to all downlink messages for the given application\nfunc (c *DefaultClient) SubscribeAppDownlink(appID string, handler DownlinkHandler) Token {\n\treturn c.SubscribeDeviceDownlink(appID, \"\", handler)\n}\n\n\/\/ SubscribeDownlink subscribes to all downlink messages that the current user has access to\nfunc (c *DefaultClient) SubscribeDownlink(handler DownlinkHandler) Token {\n\treturn c.SubscribeDeviceDownlink(\"\", \"\", handler)\n}\n\n\/\/ UnsubscribeDeviceDownlink unsubscribes from the downlink messages for the given application and device\nfunc (c *DefaultClient) UnsubscribeDeviceDownlink(appID string, devID string) Token {\n\ttopic := DeviceTopic{appID, devID, Downlink}\n\treturn c.unsubscribe(topic.String())\n}\n\n\/\/ UnsubscribeAppDownlink unsubscribes from the downlink messages for the given application\nfunc (c *DefaultClient) UnsubscribeAppDownlink(appID string) Token {\n\treturn c.UnsubscribeDeviceDownlink(appID, \"\")\n}\n\n\/\/ UnsubscribeDownlink unsubscribes from the downlink messages that the current user has access to\nfunc (c *DefaultClient) UnsubscribeDownlink() Token {\n\treturn c.UnsubscribeDeviceDownlink(\"\", \"\")\n}\n\n\/\/ PublishActivation publishes an activation\nfunc (c *DefaultClient) PublishActivation(activation Activation) Token {\n\ttopic := DeviceTopic{activation.AppID, activation.DevID, Activations}\n\tactivation.AppID = \"\"\n\tactivation.DevID = \"\"\n\tmsg, err := json.Marshal(activation)\n\tif err != nil {\n\t\treturn &simpleToken{fmt.Errorf(\"Unable to marshal the message payload\")}\n\t}\n\treturn c.mqtt.Publish(topic.String(), QoS, false, msg)\n}\n\n\/\/ SubscribeDeviceActivations subscribes to all activations for the given application and device\nfunc (c *DefaultClient) SubscribeDeviceActivations(appID string, devID string, handler ActivationHandler) Token {\n\ttopic := DeviceTopic{appID, devID, Activations}\n\treturn c.subscribe(topic.String(), func(mqtt MQTT.Client, msg MQTT.Message) {\n\t\t\/\/ Determine the actual topic\n\t\ttopic, err := ParseDeviceTopic(msg.Topic())\n\t\tif err != nil {\n\t\t\tc.ctx.WithField(\"topic\", msg.Topic()).WithError(err).Warn(\"Received message on invalid Activations topic\")\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Unmarshal the payload\n\t\tactivation := &Activation{}\n\t\terr = json.Unmarshal(msg.Payload(), activation)\n\t\tif err != nil {\n\t\t\tc.ctx.WithError(err).Warn(\"Could not unmarshal Activation\")\n\t\t\treturn\n\t\t}\n\t\tactivation.AppID = topic.AppID\n\t\tactivation.DevID = topic.DevID\n\n\t\t\/\/ Call the Activation handler\n\t\thandler(c, topic.AppID, topic.DevID, *activation)\n\t})\n}\n\n\/\/ SubscribeAppActivations subscribes to all activations for the given application\nfunc (c *DefaultClient) SubscribeAppActivations(appID string, handler ActivationHandler) Token {\n\treturn c.SubscribeDeviceActivations(appID, \"\", handler)\n}\n\n\/\/ SubscribeActivations subscribes to all activations that the current user has access to\nfunc (c *DefaultClient) SubscribeActivations(handler ActivationHandler) Token {\n\treturn c.SubscribeDeviceActivations(\"\", \"\", handler)\n}\n\n\/\/ UnsubscribeDeviceActivations unsubscribes from the activations for the given application and device\nfunc (c *DefaultClient) UnsubscribeDeviceActivations(appID string, devID string) Token {\n\ttopic := DeviceTopic{appID, devID, Activations}\n\treturn c.unsubscribe(topic.String())\n}\n\n\/\/ UnsubscribeAppActivations unsubscribes from the activations for the given application\nfunc (c *DefaultClient) UnsubscribeAppActivations(appID string) Token {\n\treturn c.UnsubscribeDeviceActivations(appID, \"\")\n}\n\n\/\/ UnsubscribeActivations unsubscribes from the activations that the current user has access to\nfunc (c *DefaultClient) UnsubscribeActivations() Token {\n\treturn c.UnsubscribeDeviceActivations(\"\", \"\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ config.go\n\/\/\n\/\/ This file implements the configuration part for when you need the API\n\/\/ key to modify things in the Atlas configuration and manage measurements.\n\npackage atlas\n\nimport (\n\n)\n\nconst (\n\tapiEndpoint = \"https:\/\/atlas.ripe.net\/api\/v2\/\"\n)\n<commit_msg>Fix file name in comment.<commit_after>\/\/ common.go\n\/\/\n\/\/ This file implements the configuration part for when you need the API\n\/\/ key to modify things in the Atlas configuration and manage measurements.\n\npackage atlas\n\nimport (\n\n)\n\nconst (\n\tapiEndpoint = \"https:\/\/atlas.ripe.net\/api\/v2\/\"\n)\n<|endoftext|>"}
{"text":"<commit_before>package selenium\n\nimport (\n\t\"log\"\n)\n\nvar debugFlag = false\n\nfunc setDebug(debug bool) {\n\tdebugFlag = debug\n}\n\nfunc debugLog(format string, args ...interface{}) {\n\tif !debugFlag {\n\t\treturn\n\t}\n\tlog.Printf(format+\"\\n\", args...)\n}\n<commit_msg>Fix debug accessibility<commit_after>package selenium\n\nimport (\n\t\"log\"\n)\n\nvar debugFlag = false\n\nfunc SetDebug(debug bool) {\n\tdebugFlag = debug\n}\n\nfunc debugLog(format string, args ...interface{}) {\n\tif !debugFlag {\n\t\treturn\n\t}\n\tlog.Printf(format+\"\\n\", args...)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ common.go\n\/\/\n\/\/ This file implements the configuration part for when you need the API\n\/\/ key to modify things in the Atlas configuration and manage measurements.\n\npackage atlas\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\nconst (\n\tapiEndpoint = \"https:\/\/atlas.ripe.net\/api\/v2\"\n)\n\n\/\/ getPageNum returns the value of the page= parameter\nfunc getPageNum(url string) (page string) {\n\tre := regexp.MustCompile(`page=(\\d+)`)\n\tif m := re.FindStringSubmatch(url); len(m) >= 1 {\n\t\treturn m[1]\n\t}\n\treturn \"\"\n}\n\n\/\/ AddQueryParameters adds query parameters to the URL.\nfunc AddQueryParameters(baseURL string, queryParams map[string]string) string {\n\tif len(queryParams) == 0 {\n\t\treturn baseURL\n\t}\n\tbaseURL += \"?\"\n\tparams := url.Values{}\n\tfor key, value := range queryParams {\n\t\tparams.Add(key, value)\n\t}\n\treturn baseURL + params.Encode()\n}\n\n\/\/ addAPIKey insert the key into options if needed\nfunc (c *Client) addAPIKey(opts map[string]string) map[string]string {\n\tkey, ok := c.HasAPIKey()\n\t\/\/ Insert key\n\tif ok {\n\t\topts[\"key\"] = key\n\t}\n\treturn opts\n}\n\n\/\/ prepareRequest insert all pre-defined stuff\nfunc (c *Client) prepareRequest(method, what string, opts map[string]string) (req *http.Request) {\n\tvar endPoint string\n\n\t\/\/ This is a hack to fetch direct urls for results\n\tif method == \"FETCH\" {\n\t\tendPoint = what\n\t\tmethod = \"GET\"\n\t} else {\n\t\tif c.config.endpoint != \"\" {\n\t\t\tendPoint = fmt.Sprintf(\"%s\/%s\", c.config.endpoint, what)\n\t\t}\n\t}\n\n\tc.mergeGlobalOptions(opts)\n\tc.debug(\"Options:\\n%v\", opts)\n\tbaseURL := AddQueryParameters(endPoint, opts)\n\n\treq, err := http.NewRequest(method, baseURL, nil)\n\tif err != nil {\n\t\tc.log.Printf(\"error parsing %s: %v\", baseURL, err)\n\t\treturn &http.Request{}\n\t}\n\n\tc.debug(\"req.url=%s\", baseURL)\n\t\/\/ We need these when we POST\n\tif method == \"POST\" {\n\t\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\t\treq.Header.Set(\"Accept\", \"application\/json\")\n\t}\n\n\treturn\n}\n\n\/\/ client.handleAPIResponse check status code & return undecoded APIError\nfunc (c *Client) handleAPIResponse(r *http.Response) ([]byte, error) {\n\tif r == nil {\n\t\treturn []byte{}, fmt.Errorf(\"error: r is nil\")\n\t}\n\n\t\/\/ Everything is fine\n\tif r.StatusCode == http.StatusOK || r.StatusCode == 0 {\n\t\treturn []byte{}, nil\n\t}\n\n\t\/\/ Everything is fine too (200-2xx)\n\tif r.StatusCode >= http.StatusOK && r.StatusCode < http.StatusMultipleChoices {\n\t\treturn []byte{}, nil\n\t}\n\n\t\/\/ Check this condition (3xx are handled directly)\n\tif r.StatusCode >= http.StatusMultipleChoices && r.StatusCode < http.StatusBadRequest {\n\t\treturn []byte{}, nil\n\t}\n\n\t\/\/ Everything else is an error\n\tbody, err := ioutil.ReadAll(r.Body)\n\tdefer r.Body.Close()\n\n\tif err != nil {\n\t\treturn body, errors.Wrap(err, \"read body\")\n\t}\n\n\tvar e APIError\n\n\terr = json.Unmarshal(body, &e)\n\tif err != nil {\n\t\treturn body, errors.Wrapf(err, \"decoding error raw=%v\", body)\n\t}\n\n\treturn body, e\n}\n\nfunc (c *Client) mergeGlobalOptions(opts map[string]string) {\n\tfor k, v := range c.opts {\n\t\topts[k] = v\n\t}\n}\n<commit_msg>Create decodeAPIError to extract interesting stuff from API.<commit_after>\/\/ common.go\n\/\/\n\/\/ This file implements the configuration part for when you need the API\n\/\/ key to modify things in the Atlas configuration and manage measurements.\n\npackage atlas\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\nconst (\n\tapiEndpoint = \"https:\/\/atlas.ripe.net\/api\/v2\"\n)\n\n\/\/ getPageNum returns the value of the page= parameter\nfunc getPageNum(url string) (page string) {\n\tre := regexp.MustCompile(`page=(\\d+)`)\n\tif m := re.FindStringSubmatch(url); len(m) >= 1 {\n\t\treturn m[1]\n\t}\n\treturn \"\"\n}\n\n\/\/ AddQueryParameters adds query parameters to the URL.\nfunc AddQueryParameters(baseURL string, queryParams map[string]string) string {\n\tif len(queryParams) == 0 {\n\t\treturn baseURL\n\t}\n\tbaseURL += \"?\"\n\tparams := url.Values{}\n\tfor key, value := range queryParams {\n\t\tparams.Add(key, value)\n\t}\n\treturn baseURL + params.Encode()\n}\n\n\/\/ addAPIKey insert the key into options if needed\nfunc (c *Client) addAPIKey(opts map[string]string) map[string]string {\n\tkey, ok := c.HasAPIKey()\n\t\/\/ Insert key\n\tif ok {\n\t\topts[\"key\"] = key\n\t}\n\treturn opts\n}\n\n\/\/ prepareRequest insert all pre-defined stuff\nfunc (c *Client) prepareRequest(method, what string, opts map[string]string) (req *http.Request) {\n\tvar endPoint string\n\n\t\/\/ This is a hack to fetch direct urls for results\n\tif method == \"FETCH\" {\n\t\tendPoint = what\n\t\tmethod = \"GET\"\n\t} else {\n\t\tif c.config.endpoint != \"\" {\n\t\t\tendPoint = fmt.Sprintf(\"%s\/%s\", c.config.endpoint, what)\n\t\t}\n\t}\n\n\tc.mergeGlobalOptions(opts)\n\tc.debug(\"Options:\\n%v\", opts)\n\tbaseURL := AddQueryParameters(endPoint, opts)\n\n\treq, err := http.NewRequest(method, baseURL, nil)\n\tif err != nil {\n\t\tc.log.Printf(\"error parsing %s: %v\", baseURL, err)\n\t\treturn &http.Request{}\n\t}\n\n\tc.debug(\"req.url=%s\", baseURL)\n\t\/\/ We need these when we POST\n\tif method == \"POST\" {\n\t\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\t\treq.Header.Set(\"Accept\", \"application\/json\")\n\t}\n\n\treturn\n}\n\n\/\/ decodeAPIError does the deserialisation\nfunc decodeAPIError(body []byte) (*APIError, error) {\n\tvar e APIError\n\n\terr := json.Unmarshal(body, &e)\n\treturn &e, err\n}\n\n\/\/ client.handleAPIResponse check status code & return undecoded APIError\nfunc (c *Client) handleAPIResponse(r *http.Response) ([]byte, error) {\n\tif r == nil {\n\t\treturn []byte{}, fmt.Errorf(\"error: r is nil\")\n\t}\n\n\t\/\/ Everything is fine\n\tif r.StatusCode == http.StatusOK || r.StatusCode == 0 {\n\t\treturn []byte{}, nil\n\t}\n\n\t\/\/ Everything is fine too (200-2xx)\n\tif r.StatusCode >= http.StatusOK && r.StatusCode < http.StatusMultipleChoices {\n\t\treturn []byte{}, nil\n\t}\n\n\t\/\/ Check this condition (3xx are handled directly)\n\tif r.StatusCode >= http.StatusMultipleChoices && r.StatusCode < http.StatusBadRequest {\n\t\treturn []byte{}, nil\n\t}\n\n\t\/\/ Everything else is an error\n\tbody, err := ioutil.ReadAll(r.Body)\n\tdefer r.Body.Close()\n\n\tif err != nil {\n\t\treturn body, errors.Wrap(err, \"read body\")\n\t}\n\n\tvar e APIError\n\n\terr = json.Unmarshal(body, &e)\n\tif err != nil {\n\t\treturn body, errors.Wrapf(err, \"decoding error raw=%v\", body)\n\t}\n\n\treturn body, e\n}\n\nfunc (c *Client) mergeGlobalOptions(opts map[string]string) {\n\tfor k, v := range c.opts {\n\t\topts[k] = v\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage addresser\n\nimport (\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/juju\/names\"\n\n\t\"github.com\/juju\/juju\/api\/base\"\n\t\"github.com\/juju\/juju\/api\/common\"\n\t\"github.com\/juju\/juju\/api\/watcher\"\n\t\"github.com\/juju\/juju\/apiserver\/params\"\n)\n\nconst addresserFacade = \"Addresser\"\n\n\/\/ API provides access to the InstancePoller API facade.\ntype API struct {\n\t*common.EnvironWatcher\n\n\tfacade base.FacadeCaller\n}\n\n\/\/ NewAPI creates a new client-side Addresser facade.\nfunc NewAPI(caller base.APICaller) *API {\n\tif caller == nil {\n\t\tpanic(\"caller is nil\")\n\t}\n\tfacadeCaller := base.NewFacadeCaller(caller, addresserFacade)\n\treturn &API{\n\t\tEnvironWatcher: common.NewEnvironWatcher(facadeCaller),\n\t\tfacade:         facadeCaller,\n\t}\n}\n\n\/\/ IPAddress provides access to methods of a state.IPAddress through the\n\/\/ facade.\nfunc (api *API) IPAddress(tag names.IPAddressTag) (*IPAddress, error) {\n\tlife, err := common.Life(api.facade, tag)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treturn &IPAddress{api.facade, tag, life}, nil\n}\n\nvar newEntityWatcher = watcher.NewEntityWatcher\n\n\/\/ WatchIPAddresses returns a EntityWatcher for observing the\n\/\/ tags of IP addresses with changes in life cycle.\n\/\/ The initial event will contain the tags of any IP addresses\n\/\/ which are no longer Alive.\nfunc (api *API) WatchIPAddresses() (watcher.EntityWatcher, error) {\n\tvar result params.EntityWatchResult\n\terr := api.facade.FacadeCall(\"WatchIPAddresses\", nil, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif result.Error != nil {\n\t\treturn nil, result.Error\n\t}\n\tw := newEntityWatcher(api.facade.RawAPICaller(), result)\n\treturn w, nil\n}\n<commit_msg>Added TODO for later change to bulk requests.<commit_after>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage addresser\n\nimport (\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/juju\/names\"\n\n\t\"github.com\/juju\/juju\/api\/base\"\n\t\"github.com\/juju\/juju\/api\/common\"\n\t\"github.com\/juju\/juju\/api\/watcher\"\n\t\"github.com\/juju\/juju\/apiserver\/params\"\n)\n\nconst addresserFacade = \"Addresser\"\n\n\/\/ API provides access to the InstancePoller API facade.\ntype API struct {\n\t*common.EnvironWatcher\n\n\tfacade base.FacadeCaller\n}\n\n\/\/ NewAPI creates a new client-side Addresser facade.\nfunc NewAPI(caller base.APICaller) *API {\n\tif caller == nil {\n\t\tpanic(\"caller is nil\")\n\t}\n\tfacadeCaller := base.NewFacadeCaller(caller, addresserFacade)\n\treturn &API{\n\t\tEnvironWatcher: common.NewEnvironWatcher(facadeCaller),\n\t\tfacade:         facadeCaller,\n\t}\n}\n\n\/\/ IPAddress provides access to methods of a state.IPAddress through the\n\/\/ facade.\nfunc (api *API) IPAddress(tag names.IPAddressTag) (*IPAddress, error) {\n\t\/\/ TODO(mue) Change approach to use bulk requests for retrieval\n\t\/\/ and later removal.\n\tlife, err := common.Life(api.facade, tag)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treturn &IPAddress{api.facade, tag, life}, nil\n}\n\nvar newEntityWatcher = watcher.NewEntityWatcher\n\n\/\/ WatchIPAddresses returns a EntityWatcher for observing the\n\/\/ tags of IP addresses with changes in life cycle.\n\/\/ The initial event will contain the tags of any IP addresses\n\/\/ which are no longer Alive.\nfunc (api *API) WatchIPAddresses() (watcher.EntityWatcher, error) {\n\tvar result params.EntityWatchResult\n\terr := api.facade.FacadeCall(\"WatchIPAddresses\", nil, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif result.Error != nil {\n\t\treturn nil, result.Error\n\t}\n\tw := newEntityWatcher(api.facade.RawAPICaller(), result)\n\treturn w, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Circonus, Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage api\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nvar (\n\ttestOutlierReport = OutlierReport{\n\t\tCID:              \"\/outlier_report\/1234\",\n\t\tCreated:          1483033102,\n\t\tCreatedBy:        \"\/user\/1234\",\n\t\tLastModified:     1483033102,\n\t\tLastModifiedBy:   \"\/user\/1234\",\n\t\tConfig:           \"\",\n\t\tMetricClusterCID: \"\/metric_cluster\/1234\",\n\t\tTags:             []string{\"cat:tag\"},\n\t\tTitle:            \"foo bar\",\n\t}\n)\n\nfunc testOutlierReportServer() *httptest.Server {\n\tf := func(w http.ResponseWriter, r *http.Request) {\n\t\tpath := r.URL.Path\n\t\tif path == \"\/outlier_report\/1234\" {\n\t\t\tswitch r.Method {\n\t\t\tcase \"GET\":\n\t\t\t\tret, err := json.Marshal(testOutlierReport)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tw.WriteHeader(200)\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\t\tfmt.Fprintln(w, string(ret))\n\t\t\tcase \"PUT\":\n\t\t\t\tdefer r.Body.Close()\n\t\t\t\tb, err := ioutil.ReadAll(r.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tw.WriteHeader(200)\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\t\tfmt.Fprintln(w, string(b))\n\t\t\tcase \"DELETE\":\n\t\t\t\tw.WriteHeader(200)\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tdefault:\n\t\t\t\tw.WriteHeader(404)\n\t\t\t\tfmt.Fprintln(w, fmt.Sprintf(\"not found: %s %s\", r.Method, path))\n\t\t\t}\n\t\t} else if path == \"\/outlier_report\" {\n\t\t\tswitch r.Method {\n\t\t\tcase \"GET\":\n\t\t\t\tc := []OutlierReport{testOutlierReport}\n\t\t\t\tret, err := json.Marshal(c)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tw.WriteHeader(200)\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\t\tfmt.Fprintln(w, string(ret))\n\t\t\tcase \"POST\":\n\t\t\t\tdefer r.Body.Close()\n\t\t\t\t_, err := ioutil.ReadAll(r.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tret, err := json.Marshal(testOutlierReport)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tw.WriteHeader(200)\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\t\tfmt.Fprintln(w, string(ret))\n\t\t\tdefault:\n\t\t\t\tw.WriteHeader(404)\n\t\t\t\tfmt.Fprintln(w, fmt.Sprintf(\"not found: %s %s\", r.Method, path))\n\t\t\t}\n\t\t} else {\n\t\t\tw.WriteHeader(404)\n\t\t\tfmt.Fprintln(w, fmt.Sprintf(\"not found: %s %s\", r.Method, path))\n\t\t}\n\t}\n\n\treturn httptest.NewServer(http.HandlerFunc(f))\n}\n\nfunc TestFetchOutlierReport(t *testing.T) {\n\tserver := testOutlierReportServer()\n\tdefer server.Close()\n\n\tac := &Config{\n\t\tTokenKey: \"abc123\",\n\t\tTokenApp: \"test\",\n\t\tURL:      server.URL,\n\t}\n\tapih, err := NewAPI(ac)\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, got '%v'\", err)\n\t}\n\n\tt.Log(\"without CID\")\n\t{\n\t\tcid := \"\"\n\t\texpectedError := errors.New(\"Invalid outlier report CID [none]\")\n\t\t_, err := apih.FetchOutlierReport(CIDType(&cid))\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"Expected error\")\n\t\t}\n\t\tif err.Error() != expectedError.Error() {\n\t\t\tt.Fatalf(\"Expected %+v got '%+v'\", expectedError, err)\n\t\t}\n\t}\n\n\tt.Log(\"with valid CID\")\n\t{\n\t\tcid := \"\/outlier_report\/1234\"\n\t\treport, err := apih.FetchOutlierReport(CIDType(&cid))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t\t}\n\n\t\tactualType := reflect.TypeOf(report)\n\t\texpectedType := \"*api.OutlierReport\"\n\t\tif actualType.String() != expectedType {\n\t\t\tt.Fatalf(\"Expected %s, got %s\", expectedType, actualType.String())\n\t\t}\n\n\t\tif report.CID != testOutlierReport.CID {\n\t\t\tt.Fatalf(\"CIDs do not match: %+v != %+v\\n\", report, testOutlierReport)\n\t\t}\n\t}\n\n\tt.Log(\"with invalid CID\")\n\t{\n\t\tcid := \"\/invalid\"\n\t\texpectedError := errors.New(\"Invalid outlier report CID [\/invalid]\")\n\t\t_, err := apih.FetchOutlierReport(CIDType(&cid))\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"Expected error\")\n\t\t}\n\t\tif err.Error() != expectedError.Error() {\n\t\t\tt.Fatalf(\"Expected %+v got '%+v'\", expectedError, err)\n\t\t}\n\t}\n}\n\nfunc TestFetchOutlierReports(t *testing.T) {\n\tserver := testOutlierReportServer()\n\tdefer server.Close()\n\n\tac := &Config{\n\t\tTokenKey: \"abc123\",\n\t\tTokenApp: \"test\",\n\t\tURL:      server.URL,\n\t}\n\tapih, err := NewAPI(ac)\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, got '%v'\", err)\n\t}\n\n\treports, err := apih.FetchOutlierReports()\n\tif err != nil {\n\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t}\n\n\tactualType := reflect.TypeOf(reports)\n\texpectedType := \"*[]api.OutlierReport\"\n\tif actualType.String() != expectedType {\n\t\tt.Fatalf(\"Expected %s, got %s\", expectedType, actualType.String())\n\t}\n\n}\n\nfunc TestCreateOutlierReport(t *testing.T) {\n\tserver := testOutlierReportServer()\n\tdefer server.Close()\n\n\tvar apih *API\n\n\tac := &Config{\n\t\tTokenKey: \"abc123\",\n\t\tTokenApp: \"test\",\n\t\tURL:      server.URL,\n\t}\n\tapih, err := NewAPI(ac)\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, got '%v'\", err)\n\t}\n\n\treport, err := apih.CreateOutlierReport(&testOutlierReport)\n\tif err != nil {\n\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t}\n\n\tactualType := reflect.TypeOf(report)\n\texpectedType := \"*api.OutlierReport\"\n\tif actualType.String() != expectedType {\n\t\tt.Fatalf(\"Expected %s, got %s\", expectedType, actualType.String())\n\t}\n}\n\nfunc TestUpdateOutlierReport(t *testing.T) {\n\tserver := testOutlierReportServer()\n\tdefer server.Close()\n\n\tvar apih *API\n\n\tac := &Config{\n\t\tTokenKey: \"abc123\",\n\t\tTokenApp: \"test\",\n\t\tURL:      server.URL,\n\t}\n\tapih, err := NewAPI(ac)\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, got '%v'\", err)\n\t}\n\n\tt.Log(\"valid OutlierReport\")\n\t{\n\t\treport, err := apih.UpdateOutlierReport(&testOutlierReport)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t\t}\n\n\t\tactualType := reflect.TypeOf(report)\n\t\texpectedType := \"*api.OutlierReport\"\n\t\tif actualType.String() != expectedType {\n\t\t\tt.Fatalf(\"Expected %s, got %s\", expectedType, actualType.String())\n\t\t}\n\t}\n\n\tt.Log(\"Test with invalid CID\")\n\t{\n\t\texpectedError := errors.New(\"Invalid outlier report CID [\/invalid]\")\n\t\tx := &OutlierReport{CID: \"\/invalid\"}\n\t\t_, err := apih.UpdateOutlierReport(x)\n\t\tif err == nil {\n\t\t\tt.Fatal(\"Expected an error\")\n\t\t}\n\t\tif err.Error() != expectedError.Error() {\n\t\t\tt.Fatalf(\"Expected %+v got '%+v'\", expectedError, err)\n\t\t}\n\t}\n}\n\nfunc TestDeleteOutlierReport(t *testing.T) {\n\tserver := testOutlierReportServer()\n\tdefer server.Close()\n\n\tvar apih *API\n\n\tac := &Config{\n\t\tTokenKey: \"abc123\",\n\t\tTokenApp: \"test\",\n\t\tURL:      server.URL,\n\t}\n\tapih, err := NewAPI(ac)\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, got '%v'\", err)\n\t}\n\n\tt.Log(\"valid OutlierReport\")\n\t{\n\t\t_, err := apih.DeleteOutlierReport(&testOutlierReport)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t\t}\n\t}\n\n\tt.Log(\"Test with invalid CID\")\n\t{\n\t\texpectedError := errors.New(\"Invalid outlier report CID [\/invalid]\")\n\t\tx := &OutlierReport{CID: \"\/invalid\"}\n\t\t_, err := apih.UpdateOutlierReport(x)\n\t\tif err == nil {\n\t\t\tt.Fatal(\"Expected an error\")\n\t\t}\n\t\tif err.Error() != expectedError.Error() {\n\t\t\tt.Fatalf(\"Expected %+v got '%+v'\", expectedError, err)\n\t\t}\n\t}\n}\n<commit_msg>add: search test coverage<commit_after>\/\/ Copyright 2016 Circonus, Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage api\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nvar (\n\ttestOutlierReport = OutlierReport{\n\t\tCID:              \"\/outlier_report\/1234\",\n\t\tCreated:          1483033102,\n\t\tCreatedBy:        \"\/user\/1234\",\n\t\tLastModified:     1483033102,\n\t\tLastModifiedBy:   \"\/user\/1234\",\n\t\tConfig:           \"\",\n\t\tMetricClusterCID: \"\/metric_cluster\/1234\",\n\t\tTags:             []string{\"cat:tag\"},\n\t\tTitle:            \"foo bar\",\n\t}\n)\n\nfunc testOutlierReportServer() *httptest.Server {\n\tf := func(w http.ResponseWriter, r *http.Request) {\n\t\tpath := r.URL.Path\n\t\tif path == \"\/outlier_report\/1234\" {\n\t\t\tswitch r.Method {\n\t\t\tcase \"GET\":\n\t\t\t\tret, err := json.Marshal(testOutlierReport)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tw.WriteHeader(200)\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\t\tfmt.Fprintln(w, string(ret))\n\t\t\tcase \"PUT\":\n\t\t\t\tdefer r.Body.Close()\n\t\t\t\tb, err := ioutil.ReadAll(r.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tw.WriteHeader(200)\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\t\tfmt.Fprintln(w, string(b))\n\t\t\tcase \"DELETE\":\n\t\t\t\tw.WriteHeader(200)\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tdefault:\n\t\t\t\tw.WriteHeader(404)\n\t\t\t\tfmt.Fprintln(w, fmt.Sprintf(\"not found: %s %s\", r.Method, path))\n\t\t\t}\n\t\t} else if path == \"\/outlier_report\" {\n\t\t\tswitch r.Method {\n\t\t\tcase \"GET\":\n\t\t\t\treqURL := r.URL.String()\n\t\t\t\tvar c []OutlierReport\n\t\t\t\tif reqURL == \"\/outlier_report?search=requests+per+second\" {\n\t\t\t\t\tc = []OutlierReport{testOutlierReport}\n\t\t\t\t} else if reqURL == \"\/outlier_report?f_tags_has=service%3Aweb\" {\n\t\t\t\t\tc = []OutlierReport{testOutlierReport}\n\t\t\t\t} else if reqURL == \"\/outlier_report?f_tags_has=service%3Aweb&search=requests+per+second\" {\n\t\t\t\t\tc = []OutlierReport{testOutlierReport}\n\t\t\t\t} else if reqURL == \"\/outlier_report\" {\n\t\t\t\t\tc = []OutlierReport{testOutlierReport}\n\t\t\t\t} else {\n\t\t\t\t\tc = []OutlierReport{}\n\t\t\t\t}\n\t\t\t\tif len(c) > 0 {\n\t\t\t\t\tret, err := json.Marshal(c)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t\tw.WriteHeader(200)\n\t\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\t\t\tfmt.Fprintln(w, string(ret))\n\t\t\t\t} else {\n\t\t\t\t\tw.WriteHeader(404)\n\t\t\t\t\tfmt.Fprintln(w, fmt.Sprintf(\"not found: %s %s\", r.Method, reqURL))\n\t\t\t\t}\n\t\t\tcase \"POST\":\n\t\t\t\tdefer r.Body.Close()\n\t\t\t\t_, err := ioutil.ReadAll(r.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tret, err := json.Marshal(testOutlierReport)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tw.WriteHeader(200)\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\t\tfmt.Fprintln(w, string(ret))\n\t\t\tdefault:\n\t\t\t\tw.WriteHeader(404)\n\t\t\t\tfmt.Fprintln(w, fmt.Sprintf(\"not found: %s %s\", r.Method, path))\n\t\t\t}\n\t\t} else {\n\t\t\tw.WriteHeader(404)\n\t\t\tfmt.Fprintln(w, fmt.Sprintf(\"not found: %s %s\", r.Method, path))\n\t\t}\n\t}\n\n\treturn httptest.NewServer(http.HandlerFunc(f))\n}\n\nfunc TestFetchOutlierReport(t *testing.T) {\n\tserver := testOutlierReportServer()\n\tdefer server.Close()\n\n\tac := &Config{\n\t\tTokenKey: \"abc123\",\n\t\tTokenApp: \"test\",\n\t\tURL:      server.URL,\n\t}\n\tapih, err := NewAPI(ac)\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, got '%v'\", err)\n\t}\n\n\tt.Log(\"without CID\")\n\t{\n\t\tcid := \"\"\n\t\texpectedError := errors.New(\"Invalid outlier report CID [none]\")\n\t\t_, err := apih.FetchOutlierReport(CIDType(&cid))\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"Expected error\")\n\t\t}\n\t\tif err.Error() != expectedError.Error() {\n\t\t\tt.Fatalf(\"Expected %+v got '%+v'\", expectedError, err)\n\t\t}\n\t}\n\n\tt.Log(\"with valid CID\")\n\t{\n\t\tcid := \"\/outlier_report\/1234\"\n\t\treport, err := apih.FetchOutlierReport(CIDType(&cid))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t\t}\n\n\t\tactualType := reflect.TypeOf(report)\n\t\texpectedType := \"*api.OutlierReport\"\n\t\tif actualType.String() != expectedType {\n\t\t\tt.Fatalf(\"Expected %s, got %s\", expectedType, actualType.String())\n\t\t}\n\n\t\tif report.CID != testOutlierReport.CID {\n\t\t\tt.Fatalf(\"CIDs do not match: %+v != %+v\\n\", report, testOutlierReport)\n\t\t}\n\t}\n\n\tt.Log(\"with invalid CID\")\n\t{\n\t\tcid := \"\/invalid\"\n\t\texpectedError := errors.New(\"Invalid outlier report CID [\/invalid]\")\n\t\t_, err := apih.FetchOutlierReport(CIDType(&cid))\n\t\tif err == nil {\n\t\t\tt.Fatalf(\"Expected error\")\n\t\t}\n\t\tif err.Error() != expectedError.Error() {\n\t\t\tt.Fatalf(\"Expected %+v got '%+v'\", expectedError, err)\n\t\t}\n\t}\n}\n\nfunc TestFetchOutlierReports(t *testing.T) {\n\tserver := testOutlierReportServer()\n\tdefer server.Close()\n\n\tac := &Config{\n\t\tTokenKey: \"abc123\",\n\t\tTokenApp: \"test\",\n\t\tURL:      server.URL,\n\t}\n\tapih, err := NewAPI(ac)\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, got '%v'\", err)\n\t}\n\n\treports, err := apih.FetchOutlierReports()\n\tif err != nil {\n\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t}\n\n\tactualType := reflect.TypeOf(reports)\n\texpectedType := \"*[]api.OutlierReport\"\n\tif actualType.String() != expectedType {\n\t\tt.Fatalf(\"Expected %s, got %s\", expectedType, actualType.String())\n\t}\n\n}\n\nfunc TestCreateOutlierReport(t *testing.T) {\n\tserver := testOutlierReportServer()\n\tdefer server.Close()\n\n\tvar apih *API\n\n\tac := &Config{\n\t\tTokenKey: \"abc123\",\n\t\tTokenApp: \"test\",\n\t\tURL:      server.URL,\n\t}\n\tapih, err := NewAPI(ac)\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, got '%v'\", err)\n\t}\n\n\treport, err := apih.CreateOutlierReport(&testOutlierReport)\n\tif err != nil {\n\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t}\n\n\tactualType := reflect.TypeOf(report)\n\texpectedType := \"*api.OutlierReport\"\n\tif actualType.String() != expectedType {\n\t\tt.Fatalf(\"Expected %s, got %s\", expectedType, actualType.String())\n\t}\n}\n\nfunc TestUpdateOutlierReport(t *testing.T) {\n\tserver := testOutlierReportServer()\n\tdefer server.Close()\n\n\tvar apih *API\n\n\tac := &Config{\n\t\tTokenKey: \"abc123\",\n\t\tTokenApp: \"test\",\n\t\tURL:      server.URL,\n\t}\n\tapih, err := NewAPI(ac)\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, got '%v'\", err)\n\t}\n\n\tt.Log(\"valid OutlierReport\")\n\t{\n\t\treport, err := apih.UpdateOutlierReport(&testOutlierReport)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t\t}\n\n\t\tactualType := reflect.TypeOf(report)\n\t\texpectedType := \"*api.OutlierReport\"\n\t\tif actualType.String() != expectedType {\n\t\t\tt.Fatalf(\"Expected %s, got %s\", expectedType, actualType.String())\n\t\t}\n\t}\n\n\tt.Log(\"Test with invalid CID\")\n\t{\n\t\texpectedError := errors.New(\"Invalid outlier report CID [\/invalid]\")\n\t\tx := &OutlierReport{CID: \"\/invalid\"}\n\t\t_, err := apih.UpdateOutlierReport(x)\n\t\tif err == nil {\n\t\t\tt.Fatal(\"Expected an error\")\n\t\t}\n\t\tif err.Error() != expectedError.Error() {\n\t\t\tt.Fatalf(\"Expected %+v got '%+v'\", expectedError, err)\n\t\t}\n\t}\n}\n\nfunc TestDeleteOutlierReport(t *testing.T) {\n\tserver := testOutlierReportServer()\n\tdefer server.Close()\n\n\tvar apih *API\n\n\tac := &Config{\n\t\tTokenKey: \"abc123\",\n\t\tTokenApp: \"test\",\n\t\tURL:      server.URL,\n\t}\n\tapih, err := NewAPI(ac)\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, got '%v'\", err)\n\t}\n\n\tt.Log(\"valid OutlierReport\")\n\t{\n\t\t_, err := apih.DeleteOutlierReport(&testOutlierReport)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t\t}\n\t}\n\n\tt.Log(\"Test with invalid CID\")\n\t{\n\t\texpectedError := errors.New(\"Invalid outlier report CID [\/invalid]\")\n\t\tx := &OutlierReport{CID: \"\/invalid\"}\n\t\t_, err := apih.UpdateOutlierReport(x)\n\t\tif err == nil {\n\t\t\tt.Fatal(\"Expected an error\")\n\t\t}\n\t\tif err.Error() != expectedError.Error() {\n\t\t\tt.Fatalf(\"Expected %+v got '%+v'\", expectedError, err)\n\t\t}\n\t}\n}\n\nfunc TestSearchOutlierReports(t *testing.T) {\n\tserver := testOutlierReportServer()\n\tdefer server.Close()\n\n\tvar apih *API\n\n\tac := &Config{\n\t\tTokenKey: \"abc123\",\n\t\tTokenApp: \"test\",\n\t\tURL:      server.URL,\n\t}\n\tapih, err := NewAPI(ac)\n\tif err != nil {\n\t\tt.Errorf(\"Expected no error, got '%v'\", err)\n\t}\n\n\tsearch := SearchQueryType(\"requests per second\")\n\tfilter := SearchFilterType(map[string][]string{\"f_tags_has\": []string{\"service:web\"}})\n\n\tt.Log(\"no search, no filter\")\n\t{\n\t\treports, err := apih.SearchOutlierReports(nil, nil)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t\t}\n\n\t\tactualType := reflect.TypeOf(reports)\n\t\texpectedType := \"*[]api.OutlierReport\"\n\t\tif actualType.String() != expectedType {\n\t\t\tt.Fatalf(\"Expected %s, got %s\", expectedType, actualType.String())\n\t\t}\n\t}\n\n\tt.Log(\"search, no filter\")\n\t{\n\t\treports, err := apih.SearchOutlierReports(&search, nil)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t\t}\n\n\t\tactualType := reflect.TypeOf(reports)\n\t\texpectedType := \"*[]api.OutlierReport\"\n\t\tif actualType.String() != expectedType {\n\t\t\tt.Fatalf(\"Expected %s, got %s\", expectedType, actualType.String())\n\t\t}\n\t}\n\n\tt.Log(\"no search, filter\")\n\t{\n\t\treports, err := apih.SearchOutlierReports(nil, &filter)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t\t}\n\n\t\tactualType := reflect.TypeOf(reports)\n\t\texpectedType := \"*[]api.OutlierReport\"\n\t\tif actualType.String() != expectedType {\n\t\t\tt.Fatalf(\"Expected %s, got %s\", expectedType, actualType.String())\n\t\t}\n\t}\n\n\tt.Log(\"search, filter\")\n\t{\n\t\treports, err := apih.SearchOutlierReports(&search, &filter)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected no error, got '%v'\", err)\n\t\t}\n\n\t\tactualType := reflect.TypeOf(reports)\n\t\texpectedType := \"*[]api.OutlierReport\"\n\t\tif actualType.String() != expectedType {\n\t\t\tt.Fatalf(\"Expected %s, got %s\", expectedType, actualType.String())\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package version\n\n\/\/ Version of Functions\nvar Version = \"0.3.164\"\n<commit_msg>functions: 0.3.165 release [skip ci]<commit_after>package version\n\n\/\/ Version of Functions\nvar Version = \"0.3.165\"\n<|endoftext|>"}
{"text":"<commit_before>package version\n\n\/\/ Version of Functions\nvar Version = \"0.3.460\"\n<commit_msg>fnserver: 0.3.461 release [skip ci]<commit_after>package version\n\n\/\/ Version of Functions\nvar Version = \"0.3.461\"\n<|endoftext|>"}
{"text":"<commit_before>package godingtalk\n\nimport (\n\t\"testing\"\n)\n\nfunc TestEncryption(t *testing.T) {\n\tstr, err := c.Encrypt(\"Hello\")\n    if err!=nil {\n        t.Error(err)\n    } else {\n        t.Log(str)\n    }\n}\n<commit_msg>fixed test case<commit_after>package godingtalk\n\nimport (\n\t\"testing\"\n)\n\nfunc TestEncryption(t *testing.T) {\n\tstr, err := c.Encrypt(\"Hello\")\n    if err!=nil {\n        t.Log(err)\n    } else {\n        t.Log(str)\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"io\/ioutil\"\n\t\"strings\"\n\n\t\"github.com\/drone\/drone\/shared\/build\/log\"\n)\n\ntype SshConfigFileSection struct {\n\tHost         string\n\tForwardAgent string\n\tUser         string\n\tHostName     string\n\tPort         string\n}\n\n\/\/ parseSshConfigFileSection parses a section from the ~\/.ssh\/config file\nfunc parseSshConfigFileSection(content string) *SshConfigFileSection {\n\tsection := &SshConfigFileSection{}\n\n\tfor n, line := range strings.Split(content, \"\\n\") {\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif n == 0 {\n\t\t\tsection.Host = line\n\t\t} else if strings.HasPrefix(line, \"ForwardAgent\") {\n\t\t\tsection.ForwardAgent = strings.TrimSpace(strings.TrimPrefix(line, \"ForwardAgent\"))\n\t\t} else if strings.HasPrefix(line, \"User\") {\n\t\t\tsection.User = strings.TrimSpace(strings.TrimPrefix(line, \"User\"))\n\t\t} else if strings.HasPrefix(line, \"HostName\") {\n\t\t\tsection.HostName = strings.TrimSpace(strings.TrimPrefix(line, \"HostName\"))\n\t\t} else if strings.HasPrefix(line, \"Port\") {\n\t\t\tsection.Port = strings.TrimSpace(strings.TrimPrefix(line, \"Port\"))\n\t\t}\n\t}\n\tlog.Debugf(\"parsed ssh config file section: %s\", section.Host)\n\treturn section\n}\n\n\/\/ parseSshConfigFile parses the ~\/.ssh\/config file and build a list of section\nfunc parseSshConfigFile(path string) (map[string]*SshConfigFileSection, error) {\n\tlog.Debugf(\"parsing ssh config file: %s\", path)\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsections := make(map[string]*SshConfigFileSection)\n\tfor _, split := range strings.Split(string(content), \"Host \") {\n\t\tsplit = strings.TrimSpace(split)\n\t\tif split == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tsection := parseSshConfigFileSection(split)\n\t\tsections[section.Host] = section\n\t}\n\n\treturn sections, nil\n}\n<commit_msg>use logrus<commit_after>package main\n\nimport (\n\t\"io\/ioutil\"\n\t\"strings\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\ntype SshConfigFileSection struct {\n\tHost         string\n\tForwardAgent string\n\tUser         string\n\tHostName     string\n\tPort         string\n}\n\n\/\/ parseSshConfigFileSection parses a section from the ~\/.ssh\/config file\nfunc parseSshConfigFileSection(content string) *SshConfigFileSection {\n\tsection := &SshConfigFileSection{}\n\n\tfor n, line := range strings.Split(content, \"\\n\") {\n\t\tline = strings.TrimSpace(line)\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif n == 0 {\n\t\t\tsection.Host = line\n\t\t} else if strings.HasPrefix(line, \"ForwardAgent\") {\n\t\t\tsection.ForwardAgent = strings.TrimSpace(strings.TrimPrefix(line, \"ForwardAgent\"))\n\t\t} else if strings.HasPrefix(line, \"User\") {\n\t\t\tsection.User = strings.TrimSpace(strings.TrimPrefix(line, \"User\"))\n\t\t} else if strings.HasPrefix(line, \"HostName\") {\n\t\t\tsection.HostName = strings.TrimSpace(strings.TrimPrefix(line, \"HostName\"))\n\t\t} else if strings.HasPrefix(line, \"Port\") {\n\t\t\tsection.Port = strings.TrimSpace(strings.TrimPrefix(line, \"Port\"))\n\t\t}\n\t}\n\tlog.Debugf(\"parsed ssh config file section: %s\", section.Host)\n\treturn section\n}\n\n\/\/ parseSshConfigFile parses the ~\/.ssh\/config file and build a list of section\nfunc parseSshConfigFile(path string) (map[string]*SshConfigFileSection, error) {\n\tlog.Debugf(\"parsing ssh config file: %s\", path)\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsections := make(map[string]*SshConfigFileSection)\n\tfor _, split := range strings.Split(string(content), \"Host \") {\n\t\tsplit = strings.TrimSpace(split)\n\t\tif split == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tsection := parseSshConfigFileSection(split)\n\t\tsections[section.Host] = section\n\t}\n\n\treturn sections, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n)\n\ntype Config struct {\n\tTrelloUser       string   `json:\"trello_user\"`\n\tTrelloKey        string   `json:\"trello_key\"`\n\tTrelloToken      string   `json:\"trello_token\"`\n\tBoardName        string   `json:\"board_name\"`\n\tStartListName    string   `json:\"start_list_name\"`\n\tFinishedListName string   `json:\"finished_list_name\"`\n\tNotifyChannel    string   `json:\"notify_channel\"`\n\tInfoChannel      string   `json:\"info_channel\"`\n\tReportDays       int      `json:\"report_days\"`\n\tReportLists      []string `json:\"report_lists\"`\n\tSlackToken       string   `json:\"slack_token\"`\n\tListenURL        string   `json:\"listen_url\"`\n\tPort             string   `json:\"port\"`\n}\n\nfunc LoadConfig(filename string) Config {\n\n\tvar config Config\n\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tfmt.Printf(\"Error reading config file: %v\\n\", err)\n\t}\n\n\tjson.Unmarshal(file, &config)\n\n\treturn config\n}\n<commit_msg>Update config system<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n)\n\ntype Config struct {\n\tTrelloUser  string `json:\"trello_user\"`\n\tTrelloKey   string `json:\"trello_key\"`\n\tTrelloToken string `json:\"trello_token\"`\n\tSlackToken  string `json:\"slack_token\"`\n\tListenURL   string `json:\"listen_url\"`\n\tPort        string `json:\"port\"`\n}\n\ntype BoardConfig struct {\n\tBoardName         string       `json:\"board_name\"`\n\tNotifyChannelName string       `json:\"notify_channel_name\"`\n\tListConfigs       []ListConfig `json:\"list_configs\"`\n}\n\ntype ListConfig struct {\n\tListName        string `json:\"list_name\"`\n\tOnAction        string `json:\"on_action\"`\n\tMessageTemplate string `json:\"message_template\"`\n}\n\nfunc LoadConfig(filename string) Config {\n\n\tvar config Config\n\n\tfile, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tfmt.Printf(\"Error reading config file: %v\\n\", err)\n\t}\n\n\tjson.Unmarshal(file, &config)\n\n\treturn config\n}\n<|endoftext|>"}
{"text":"<commit_before>package cfg\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"launchpad.net\/goyaml\"\n)\n\nfunc LoadConfig(configPath string, configStruct interface{}) error {\n\tbytes, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbytes, err = substitute(bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = goyaml.Unmarshal(bytes, configStruct); err != nil {\n\t\treturn err\n\t}\n\n\tif err = validate(configStruct); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\ntype templateData struct {\n\tEnv map[string]string\n}\n\nfunc substitute(in []byte) ([]byte, error) {\n\tt, err := template.New(\"config\").Parse(string(in))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata := &templateData{\n\t\tEnv: make(map[string]string),\n\t}\n\n\tvalues := os.Environ()\n\tfor _, val := range values {\n\t\tkeyval := strings.SplitN(val, \"=\", 2)\n\t\tif len(keyval) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tdata.Env[keyval[0]] = keyval[1]\n\t}\n\n\tbuffer := &bytes.Buffer{}\n\tif err = t.Execute(buffer, data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buffer.Bytes(), nil\n}\n\nfunc validate(configStruct interface{}) error {\n\treturn validateStruct(\n\t\treflect.TypeOf(configStruct).Elem(),\n\t\treflect.ValueOf(configStruct).Elem())\n}\n\nfunc validateStruct(typ reflect.Type, val reflect.Value) error {\n\tfor idx := 0; idx < val.NumField(); idx++ {\n\t\tfield := typ.Field(idx)\n\t\tif field.Type.Kind() == reflect.Struct {\n\t\t\tif err := validateStruct(val.Field(idx).Type(), val.Field(idx)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else if field.Type.Kind() == reflect.Bool || TypeIsNumeric(field.Type.Kind()) { \/\/ no way to tell if boolean field was provided or not\n\t\t\tcontinue\n\t\t} else {\n\t\t\tif field.Tag.Get(\"config\") != \"optional\" {\n\t\t\t\tif val.Field(idx).Len() == 0 {\n\t\t\t\t\treturn errors.New(\n\t\t\t\t\t\tfmt.Sprintf(\"Missing required config field: %v\", field.Name))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nvar NumericTypes = []reflect.Kind{reflect.Int,\n\treflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,\n\treflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,\n\treflect.Float32, reflect.Float64}\n\nfunc TypeIsNumeric(typ reflect.Kind) bool {\n\tfor _, numericType := range NumericTypes {\n\t\tif typ == numericType {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>Update goyaml dependency: it moved<commit_after>package cfg\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/go-yaml\/yaml\"\n)\n\nfunc LoadConfig(configPath string, configStruct interface{}) error {\n\tbytes, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbytes, err = substitute(bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = yaml.Unmarshal(bytes, configStruct); err != nil {\n\t\treturn err\n\t}\n\n\tif err = validate(configStruct); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\ntype templateData struct {\n\tEnv map[string]string\n}\n\nfunc substitute(in []byte) ([]byte, error) {\n\tt, err := template.New(\"config\").Parse(string(in))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata := &templateData{\n\t\tEnv: make(map[string]string),\n\t}\n\n\tvalues := os.Environ()\n\tfor _, val := range values {\n\t\tkeyval := strings.SplitN(val, \"=\", 2)\n\t\tif len(keyval) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tdata.Env[keyval[0]] = keyval[1]\n\t}\n\n\tbuffer := &bytes.Buffer{}\n\tif err = t.Execute(buffer, data); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buffer.Bytes(), nil\n}\n\nfunc validate(configStruct interface{}) error {\n\treturn validateStruct(\n\t\treflect.TypeOf(configStruct).Elem(),\n\t\treflect.ValueOf(configStruct).Elem())\n}\n\nfunc validateStruct(typ reflect.Type, val reflect.Value) error {\n\tfor idx := 0; idx < val.NumField(); idx++ {\n\t\tfield := typ.Field(idx)\n\t\tif field.Type.Kind() == reflect.Struct {\n\t\t\tif err := validateStruct(val.Field(idx).Type(), val.Field(idx)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else if field.Type.Kind() == reflect.Bool || TypeIsNumeric(field.Type.Kind()) { \/\/ no way to tell if boolean field was provided or not\n\t\t\tcontinue\n\t\t} else {\n\t\t\tif field.Tag.Get(\"config\") != \"optional\" {\n\t\t\t\tif val.Field(idx).Len() == 0 {\n\t\t\t\t\treturn errors.New(\n\t\t\t\t\t\tfmt.Sprintf(\"Missing required config field: %v\", field.Name))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nvar NumericTypes = []reflect.Kind{reflect.Int,\n\treflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,\n\treflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,\n\treflect.Float32, reflect.Float64}\n\nfunc TypeIsNumeric(typ reflect.Kind) bool {\n\tfor _, numericType := range NumericTypes {\n\t\tif typ == numericType {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package runc\n\nimport (\n\t\"encoding\/json\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/inconshreveable\/log15\"\n\t\"github.com\/polydawn\/gosh\"\n\t\"go.polydawn.net\/meep\"\n\n\t\"go.polydawn.net\/repeatr\/api\/def\"\n\t\"go.polydawn.net\/repeatr\/core\/assets\"\n\t\"go.polydawn.net\/repeatr\/core\/executor\"\n\t\"go.polydawn.net\/repeatr\/core\/executor\/basicjob\"\n\t\"go.polydawn.net\/repeatr\/core\/executor\/cradle\"\n\t\"go.polydawn.net\/repeatr\/core\/executor\/util\"\n\t\"go.polydawn.net\/repeatr\/lib\/flak\"\n\t\"go.polydawn.net\/repeatr\/lib\/streamer\"\n)\n\n\/\/ interface assertion\nvar _ executor.Executor = &Executor{}\n\ntype Executor struct {\n\tworkspacePath string\n}\n\nfunc (e *Executor) Configure(workspacePath string) {\n\te.workspacePath = workspacePath\n}\n\nfunc (e *Executor) Start(f def.Formula, id executor.JobID, stdin io.Reader, log log15.Logger) executor.Job {\n\t\/\/ TODO this function sig and its interface are long overdue for an aggressive refactor.\n\t\/\/ - `journal` is Rong.  The streams mux should be accessible after this function's scope!\n\t\/\/   - either that or it's time to get cracking on saving the stream mux as an output\n\t\/\/ - `journal` should still be a thing, but it should be a logger.\n\t\/\/ - All these other values should move along in a `Job` struct\n\t\/\/   - `BasicJob` sorta started, but is drunk:\n\t\/\/      - if we're gonna have that, it's incomplete on the inputs\n\t\/\/      - for some reason it mixes in responsibility for waiting for some of the ouputs\n\t\/\/      - that use of channels and public fields is stupidly indefensive\n\t\/\/   - The current `Job` interface is in the wrong package\n\t\/\/ - almost all of the scopes in these functions is wrong\n\t\/\/   - they should be realigned until they actually assist the defers and cleanups\n\t\/\/     - e.g. withErrorCapture, withJobWorkPath, withFilesystems, etc\n\n\t\/\/ Fill in default config for anything still blank.\n\tf = *cradle.ApplyDefaults(&f)\n\n\tjob := basicjob.New(id)\n\tjobReady := make(chan struct{})\n\n\tgo func() {\n\t\t\/\/ Run the formula in a temporary directory\n\t\tflak.WithDir(func(dir string) {\n\n\t\t\t\/\/ spool our output to a muxed stream\n\t\t\tvar strm streamer.Mux\n\t\t\tstrm = streamer.CborFileMux(filepath.Join(dir, \"log\"))\n\t\t\toutS := strm.Appender(1)\n\t\t\terrS := strm.Appender(2)\n\t\t\tjob.Streams = strm\n\t\t\tdefer func() {\n\t\t\t\t\/\/ Regardless of how the job ends (or even if it fails the remaining setup), output streams must be terminated.\n\t\t\t\toutS.Close()\n\t\t\t\terrS.Close()\n\t\t\t}()\n\n\t\t\t\/\/ Job is ready to stream process output\n\t\t\tclose(jobReady)\n\n\t\t\tjob.Result = e.Run(f, job, dir, stdin, outS, errS, log)\n\t\t}, e.workspacePath, \"job\", string(job.Id()))\n\n\t\t\/\/ Directory is clean; job complete\n\t\tclose(job.WaitChan)\n\t}()\n\n\t<-jobReady\n\treturn job\n}\n\n\/\/ Executes a job, catching any panics.\nfunc (e *Executor) Run(f def.Formula, j executor.Job, d string, stdin io.Reader, outS, errS io.WriteCloser, journal log15.Logger) executor.JobResult {\n\tr := executor.JobResult{\n\t\tID:       j.Id(),\n\t\tExitCode: -1,\n\t}\n\n\tr.Error = meep.RecoverPanics(func() {\n\t\te.Execute(f, j, d, &r, stdin, outS, errS, journal)\n\t})\n\treturn r\n}\n\n\/\/ Execute a formula in a specified directory. MAY PANIC.\nfunc (e *Executor) Execute(formula def.Formula, job executor.Job, jobPath string, result *executor.JobResult, stdin io.Reader, stdout, stderr io.WriteCloser, journal log15.Logger) {\n\trootfsPath := filepath.Join(jobPath, \"rootfs\")\n\n\t\/\/ Prepare inputs\n\ttransmat := util.DefaultTransmat()\n\tinputArenas := util.ProvisionInputs(transmat, formula.Inputs, journal)\n\tutil.ProvisionOutputs(formula.Outputs, rootfsPath, journal)\n\n\t\/\/ Assemble filesystem\n\tassembly := util.AssembleFilesystem(\n\t\tutil.BestAssembler(),\n\t\trootfsPath,\n\t\tformula.Inputs,\n\t\tinputArenas,\n\t\tformula.Action.Escapes.Mounts,\n\t\tjournal,\n\t)\n\tdefer assembly.Teardown()\n\tif formula.Action.Cradle == nil || *(formula.Action.Cradle) == true {\n\t\tcradle.MakeCradle(rootfsPath, formula)\n\t}\n\n\t\/\/ Emit config for runc.\n\truncConfigJsonPath := filepath.Join(jobPath, \"config.json\")\n\tcfg := EmitRuncConfigStruct(formula, job, rootfsPath, stdin != nil)\n\tbuf, err := json.Marshal(cfg)\n\tif err != nil {\n\t\tpanic(executor.UnknownError.Wrap(err))\n\t}\n\tioutil.WriteFile(runcConfigJsonPath, buf, 0600)\n\n\t\/\/ Routing logs through a fifo appears to work, but we're going to use a file as a buffer anyway:\n\t\/\/  in the event of nasty breakdowns, it's preferable that the runc log remain readable even if repeatr was the process to end first.\n\tlogPath := filepath.Join(jobPath, \"runc-debug.log\")\n\n\t\/\/ Get handle to invokable runc plugin.\n\truncPath := filepath.Join(assets.Get(\"runc\"), \"runc\")\n\n\t\/\/ Prepare command to exec\n\targs := []string{\n\t\t\"--root\", filepath.Join(e.workspacePath, \"shared\"), \/\/ a tmpfs would be appropriate\n\t\t\"--log\", logPath,\n\t\t\"--log-format\", \"json\",\n\t\t\"run\",\n\t\t\"--bundle\", jobPath,\n\t\tstring(job.Id()),\n\t}\n\tcmd := exec.Command(runcPath, args...)\n\tcmd.Stdin = stdin\n\tcmd.Stdout = stdout\n\tcmd.Stderr = stderr\n\n\t\/\/ launch execution.\n\t\/\/ transform gosh's typed errors to repeatr's hierarchical errors.\n\t\/\/ this is... not untroubled code: since we're invoking a helper that's then\n\t\/\/  proxying the exec even further, most errors are fatal (the mapping here is\n\t\/\/   very different than in e.g. chroot executor, and provides much less meaning).\n\tstartedExec := time.Now()\n\tjournal.Info(\"Beginning execution!\")\n\tvar proc gosh.Proc\n\tmeep.Try(func() {\n\t\tproc = gosh.ExecProcCmd(cmd)\n\t}, meep.TryPlan{\n\t\t{ByType: gosh.NoSuchCommandError{}, Handler: func(err error) {\n\t\t\tpanic(executor.ConfigError.New(\"runc binary is missing\"))\n\t\t}},\n\t\t{ByType: gosh.NoArgumentsError{}, Handler: func(err error) {\n\t\t\tpanic(executor.UnknownError.Wrap(err))\n\t\t}},\n\t\t{ByType: gosh.NoSuchCwdError{}, Handler: func(err error) {\n\t\t\tpanic(executor.UnknownError.Wrap(err))\n\t\t}},\n\t\t{ByType: gosh.ProcMonitorError{}, Handler: func(err error) {\n\t\t\tpanic(executor.TaskExecError.Wrap(err))\n\t\t}},\n\t\t{CatchAny: true, Handler: func(err error) {\n\t\t\tpanic(executor.UnknownError.Wrap(err))\n\t\t}},\n\t})\n\n\tvar runcLog io.ReadCloser\n\truncLog, err = os.OpenFile(logPath, os.O_CREATE|os.O_RDONLY, 0644)\n\t\/\/ note this open races child; doesn't matter.\n\tif err != nil {\n\t\tpanic(executor.TaskExecError.New(\"failed to tail runc log: %s\", err))\n\t}\n\t\/\/ swaddle the file in userland-interruptable reader;\n\t\/\/  obviously we don't want to stop watching the logs when we hit the end of the still-growing file.\n\truncLog = streamer.NewTailReader(runcLog)\n\n\t\/\/ Proxy runc's logs out in realtime; also, detect errors and exit statuses from the stream.\n\tvar realError error\n\tvar someError bool \/\/ see the \"NOTE WELL\" section below -.-\n\tvar tailerDone sync.WaitGroup\n\ttailerDone.Add(1)\n\tgo func() {\n\t\tdefer tailerDone.Done()\n\t\tdec := json.NewDecoder(runcLog)\n\t\tfor {\n\t\t\t\/\/ Parse log lines.\n\t\t\tvar logMsg map[string]string\n\t\t\terr := dec.Decode(&logMsg)\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tpanic(executor.TaskExecError.New(\"unparsable log from runc: %s\", err))\n\t\t\t}\n\t\t\t\/\/ remap\n\t\t\tif _, ok := logMsg[\"msg\"]; !ok {\n\t\t\t\tlogMsg[\"msg\"] = \"\"\n\t\t\t}\n\t\t\tctx := log15.Ctx{}\n\t\t\tfor k, v := range logMsg {\n\t\t\t\tif k == \"msg\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tctx[\"runc-\"+k] = v\n\t\t\t}\n\n\t\t\t\/\/fmt.Printf(\"\\n\\n---\\n%s\\n---\\n\\n\", logMsg[\"msg\"])\n\n\t\t\t\/\/ Attempt to filter and normalize errors.\n\t\t\t\/\/ We want to be clear in representing which category of errors are coming up:\n\t\t\t\/\/\n\t\t\t\/\/  - Type 1.a: Exit codes of the contained user process.\n\t\t\t\/\/    - These aren't errors that we raise as such: they're just an int code to report.\n\t\t\t\/\/  - Type 1.b: Errors from invalid user configuration (e.g. no such executable, which prevents the process from ever starting) (we expect these to be reproducible!).\n\t\t\t\/\/    - These kinds of errors should be mapped onto clear types themselves: we want a \"NoSuchCwdError\", not just a string vomit.\n\t\t\t\/\/  - Type 2: Errors from runc being unable to function (e.g. maybe your kernel doesn't support cgroups, or other bizarre and serious issue?), where hopefully we can advise the user of this in a clear fashion.\n\t\t\t\/\/  - Type 3: Runc crashing in an unrecognized way (which should result in either patches to our recognizers, or bugs filed upstream to runc).\n\t\t\t\/\/\n\t\t\t\/\/ This is HARD.\n\t\t\t\/\/\n\t\t\t\/\/ NOTE WELL: we cannot guarantee to capture all semantic runc failure modes.\n\t\t\t\/\/  Errors may slip through with exit status 1: there are still many fail states\n\t\t\t\/\/  which runc does not log with sufficient consistency or a sufficiently separate\n\t\t\t\/\/  control channel for us to be able to reliably disambiguate them from stderr\n\t\t\t\/\/  output of a successfully executing job!\n\t\t\t\/\/\n\t\t\t\/\/ We have whitelisted recognizers for what we can, but oddities may remain.\n\t\t\tfor _, tr := range []struct {\n\t\t\t\tprefix, suffix string\n\t\t\t\terr            error\n\t\t\t}{\n\t\t\t\t{\"container_linux.go:262: starting container process caused \\\"exec: \\\\\\\"\", \": executable file not found in $PATH\\\"\\n\",\n\t\t\t\t\texecutor.NoSuchCommandError.New(\"command %q not found\", formula.Action.Entrypoint[0])},\n\t\t\t\t{\"container_linux.go:262: starting container process caused \\\"exec: \\\\\\\"\", \": no such file or directory\\\"\\n\",\n\t\t\t\t\texecutor.NoSuchCommandError.New(\"command %q not found\", formula.Action.Entrypoint[0])},\n\t\t\t\t{\"container_linux.go:262: starting container process caused \\\"chdir to cwd (\\\\\\\"\", \"\\\\\\\") set in config.json failed: not a directory\\\"\\n\",\n\t\t\t\t\texecutor.NoSuchCwdError.New(\"cannot set cwd to %q: no such file or directory\", formula.Action.Cwd)},\n\t\t\t\t{\"container_linux.go:262: starting container process caused \\\"chdir to cwd (\\\\\\\"\", \"\\\\\\\") set in config.json failed: no such file or directory\\\"\\n\",\n\t\t\t\t\texecutor.NoSuchCwdError.New(\"cannot set cwd to %q: no such file or directory\", formula.Action.Cwd)},\n\t\t\t\t\/\/ Note: Some other errors were previously raised in the pattern of `executor.TaskExecError.New(\"runc cannot operate in this environment!\")`,\n\t\t\t\t\/\/ but none of these are currently here because we cachebusted our known error strings when upgrading runc.\n\t\t\t} {\n\t\t\t\tif !strings.HasPrefix(logMsg[\"msg\"], tr.prefix) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif !strings.HasSuffix(logMsg[\"msg\"], tr.suffix) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trealError = tr.err\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ Log again.\n\t\t\t\/\/ The level of alarm we raise depends:\n\t\t\t\/\/  - With runc, everything we hear is at least a warning;\n\t\t\t\/\/  - If we recognized it above, it's no more than a warning;\n\t\t\t\/\/  - If we *didn't* recognize and handle it explicitly, and\n\t\t\t\/\/    we can see a clear indication it's fatal, then log big and red.\n\t\t\tif realError == nil && ctx[\"runc-level\"] == \"error\" {\n\t\t\t\tjournal.Error(logMsg[\"msg\"], ctx)\n\t\t\t\tsomeError = true\n\t\t\t} else {\n\t\t\t\tjournal.Warn(logMsg[\"msg\"], ctx)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ Wait for the job to complete.\n\tresult.ExitCode = proc.GetExitCode()\n\tjournal.Info(\"Execution done!\",\n\t\t\"elapsed\", time.Now().Sub(startedExec).Seconds(),\n\t)\n\t\/\/ Tell the log tailer to drain as soon as the proc exits.\n\truncLog.Close()\n\t\/\/ Wait for the tailer routine to drain & exit (this sync guards the err vars).\n\ttailerDone.Wait()\n\n\t\/\/ If we had a CnC error (rather than the real subprocess exit code):\n\t\/\/  - reset code to -1 because the runc exit code wasn't really from the job command\n\t\/\/  - finally, raise the error\n\t\/\/ FIXME we WISH we could zero the output buffers because runc pushes duplicate error messages\n\t\/\/  down a channel that's indistinguishable from the application stderr... but that's tricky for several reasons:\n\t\/\/  - we support streaming them out, right?\n\t\/\/  - that means we'd have to have been blocking them already; we can't zero retroactively.\n\t\/\/  - there's no \"all clear\" signal available from runc that would let us know we're clear to start flushing the stream if we blocked it.\n\t\/\/  - So, we're unable to pass the executor compat tests until patches to runc clean up this behavior.\n\tif someError && realError == nil {\n\t\trealError = executor.UnknownError.New(\"runc errored in an unrecognized fashion\")\n\t}\n\tif realError != nil {\n\t\tresult.ExitCode = -1\n\t\tpanic(realError)\n\t}\n\n\t\/\/ Save outputs\n\tresult.Outputs = util.PreserveOutputs(transmat, formula.Outputs, rootfsPath, journal)\n}\n<commit_msg>Enable runc debug logging.<commit_after>package runc\n\nimport (\n\t\"encoding\/json\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/inconshreveable\/log15\"\n\t\"github.com\/polydawn\/gosh\"\n\t\"go.polydawn.net\/meep\"\n\n\t\"go.polydawn.net\/repeatr\/api\/def\"\n\t\"go.polydawn.net\/repeatr\/core\/assets\"\n\t\"go.polydawn.net\/repeatr\/core\/executor\"\n\t\"go.polydawn.net\/repeatr\/core\/executor\/basicjob\"\n\t\"go.polydawn.net\/repeatr\/core\/executor\/cradle\"\n\t\"go.polydawn.net\/repeatr\/core\/executor\/util\"\n\t\"go.polydawn.net\/repeatr\/lib\/flak\"\n\t\"go.polydawn.net\/repeatr\/lib\/streamer\"\n)\n\n\/\/ interface assertion\nvar _ executor.Executor = &Executor{}\n\ntype Executor struct {\n\tworkspacePath string\n}\n\nfunc (e *Executor) Configure(workspacePath string) {\n\te.workspacePath = workspacePath\n}\n\nfunc (e *Executor) Start(f def.Formula, id executor.JobID, stdin io.Reader, log log15.Logger) executor.Job {\n\t\/\/ TODO this function sig and its interface are long overdue for an aggressive refactor.\n\t\/\/ - `journal` is Rong.  The streams mux should be accessible after this function's scope!\n\t\/\/   - either that or it's time to get cracking on saving the stream mux as an output\n\t\/\/ - `journal` should still be a thing, but it should be a logger.\n\t\/\/ - All these other values should move along in a `Job` struct\n\t\/\/   - `BasicJob` sorta started, but is drunk:\n\t\/\/      - if we're gonna have that, it's incomplete on the inputs\n\t\/\/      - for some reason it mixes in responsibility for waiting for some of the ouputs\n\t\/\/      - that use of channels and public fields is stupidly indefensive\n\t\/\/   - The current `Job` interface is in the wrong package\n\t\/\/ - almost all of the scopes in these functions is wrong\n\t\/\/   - they should be realigned until they actually assist the defers and cleanups\n\t\/\/     - e.g. withErrorCapture, withJobWorkPath, withFilesystems, etc\n\n\t\/\/ Fill in default config for anything still blank.\n\tf = *cradle.ApplyDefaults(&f)\n\n\tjob := basicjob.New(id)\n\tjobReady := make(chan struct{})\n\n\tgo func() {\n\t\t\/\/ Run the formula in a temporary directory\n\t\tflak.WithDir(func(dir string) {\n\n\t\t\t\/\/ spool our output to a muxed stream\n\t\t\tvar strm streamer.Mux\n\t\t\tstrm = streamer.CborFileMux(filepath.Join(dir, \"log\"))\n\t\t\toutS := strm.Appender(1)\n\t\t\terrS := strm.Appender(2)\n\t\t\tjob.Streams = strm\n\t\t\tdefer func() {\n\t\t\t\t\/\/ Regardless of how the job ends (or even if it fails the remaining setup), output streams must be terminated.\n\t\t\t\toutS.Close()\n\t\t\t\terrS.Close()\n\t\t\t}()\n\n\t\t\t\/\/ Job is ready to stream process output\n\t\t\tclose(jobReady)\n\n\t\t\tjob.Result = e.Run(f, job, dir, stdin, outS, errS, log)\n\t\t}, e.workspacePath, \"job\", string(job.Id()))\n\n\t\t\/\/ Directory is clean; job complete\n\t\tclose(job.WaitChan)\n\t}()\n\n\t<-jobReady\n\treturn job\n}\n\n\/\/ Executes a job, catching any panics.\nfunc (e *Executor) Run(f def.Formula, j executor.Job, d string, stdin io.Reader, outS, errS io.WriteCloser, journal log15.Logger) executor.JobResult {\n\tr := executor.JobResult{\n\t\tID:       j.Id(),\n\t\tExitCode: -1,\n\t}\n\n\tr.Error = meep.RecoverPanics(func() {\n\t\te.Execute(f, j, d, &r, stdin, outS, errS, journal)\n\t})\n\treturn r\n}\n\n\/\/ Execute a formula in a specified directory. MAY PANIC.\nfunc (e *Executor) Execute(formula def.Formula, job executor.Job, jobPath string, result *executor.JobResult, stdin io.Reader, stdout, stderr io.WriteCloser, journal log15.Logger) {\n\trootfsPath := filepath.Join(jobPath, \"rootfs\")\n\n\t\/\/ Prepare inputs\n\ttransmat := util.DefaultTransmat()\n\tinputArenas := util.ProvisionInputs(transmat, formula.Inputs, journal)\n\tutil.ProvisionOutputs(formula.Outputs, rootfsPath, journal)\n\n\t\/\/ Assemble filesystem\n\tassembly := util.AssembleFilesystem(\n\t\tutil.BestAssembler(),\n\t\trootfsPath,\n\t\tformula.Inputs,\n\t\tinputArenas,\n\t\tformula.Action.Escapes.Mounts,\n\t\tjournal,\n\t)\n\tdefer assembly.Teardown()\n\tif formula.Action.Cradle == nil || *(formula.Action.Cradle) == true {\n\t\tcradle.MakeCradle(rootfsPath, formula)\n\t}\n\n\t\/\/ Emit config for runc.\n\truncConfigJsonPath := filepath.Join(jobPath, \"config.json\")\n\tcfg := EmitRuncConfigStruct(formula, job, rootfsPath, stdin != nil)\n\tbuf, err := json.Marshal(cfg)\n\tif err != nil {\n\t\tpanic(executor.UnknownError.Wrap(err))\n\t}\n\tioutil.WriteFile(runcConfigJsonPath, buf, 0600)\n\n\t\/\/ Routing logs through a fifo appears to work, but we're going to use a file as a buffer anyway:\n\t\/\/  in the event of nasty breakdowns, it's preferable that the runc log remain readable even if repeatr was the process to end first.\n\tlogPath := filepath.Join(jobPath, \"runc-debug.log\")\n\n\t\/\/ Get handle to invokable runc plugin.\n\truncPath := filepath.Join(assets.Get(\"runc\"), \"runc\")\n\n\t\/\/ Prepare command to exec\n\targs := []string{\n\t\t\"--root\", filepath.Join(e.workspacePath, \"shared\"), \/\/ a tmpfs would be appropriate\n\t\t\"--debug\",\n\t\t\"--log\", logPath,\n\t\t\"--log-format\", \"json\",\n\t\t\"run\",\n\t\t\"--bundle\", jobPath,\n\t\tstring(job.Id()),\n\t}\n\tcmd := exec.Command(runcPath, args...)\n\tcmd.Stdin = stdin\n\tcmd.Stdout = stdout\n\tcmd.Stderr = stderr\n\n\t\/\/ launch execution.\n\t\/\/ transform gosh's typed errors to repeatr's hierarchical errors.\n\t\/\/ this is... not untroubled code: since we're invoking a helper that's then\n\t\/\/  proxying the exec even further, most errors are fatal (the mapping here is\n\t\/\/   very different than in e.g. chroot executor, and provides much less meaning).\n\tstartedExec := time.Now()\n\tjournal.Info(\"Beginning execution!\")\n\tvar proc gosh.Proc\n\tmeep.Try(func() {\n\t\tproc = gosh.ExecProcCmd(cmd)\n\t}, meep.TryPlan{\n\t\t{ByType: gosh.NoSuchCommandError{}, Handler: func(err error) {\n\t\t\tpanic(executor.ConfigError.New(\"runc binary is missing\"))\n\t\t}},\n\t\t{ByType: gosh.NoArgumentsError{}, Handler: func(err error) {\n\t\t\tpanic(executor.UnknownError.Wrap(err))\n\t\t}},\n\t\t{ByType: gosh.NoSuchCwdError{}, Handler: func(err error) {\n\t\t\tpanic(executor.UnknownError.Wrap(err))\n\t\t}},\n\t\t{ByType: gosh.ProcMonitorError{}, Handler: func(err error) {\n\t\t\tpanic(executor.TaskExecError.Wrap(err))\n\t\t}},\n\t\t{CatchAny: true, Handler: func(err error) {\n\t\t\tpanic(executor.UnknownError.Wrap(err))\n\t\t}},\n\t})\n\n\tvar runcLog io.ReadCloser\n\truncLog, err = os.OpenFile(logPath, os.O_CREATE|os.O_RDONLY, 0644)\n\t\/\/ note this open races child; doesn't matter.\n\tif err != nil {\n\t\tpanic(executor.TaskExecError.New(\"failed to tail runc log: %s\", err))\n\t}\n\t\/\/ swaddle the file in userland-interruptable reader;\n\t\/\/  obviously we don't want to stop watching the logs when we hit the end of the still-growing file.\n\truncLog = streamer.NewTailReader(runcLog)\n\n\t\/\/ Proxy runc's logs out in realtime; also, detect errors and exit statuses from the stream.\n\tvar realError error\n\tvar someError bool \/\/ see the \"NOTE WELL\" section below -.-\n\tvar tailerDone sync.WaitGroup\n\ttailerDone.Add(1)\n\tgo func() {\n\t\tdefer tailerDone.Done()\n\t\tdec := json.NewDecoder(runcLog)\n\t\tfor {\n\t\t\t\/\/ Parse log lines.\n\t\t\tvar logMsg map[string]interface{}\n\t\t\terr := dec.Decode(&logMsg)\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tpanic(executor.TaskExecError.New(\"unparsable log from runc: %s\", err))\n\t\t\t}\n\t\t\t\/\/ remap\n\t\t\tif _, ok := logMsg[\"msg\"]; !ok {\n\t\t\t\tlogMsg[\"msg\"] = \"\"\n\t\t\t}\n\t\t\tctx := log15.Ctx{}\n\t\t\tfor k, v := range logMsg {\n\t\t\t\tif k == \"msg\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tctx[\"runc-\"+k] = v\n\t\t\t}\n\n\t\t\t\/\/fmt.Printf(\"\\n\\n---\\n%s\\n---\\n\\n\", logMsg[\"msg\"])\n\n\t\t\t\/\/ Attempt to filter and normalize errors.\n\t\t\t\/\/ We want to be clear in representing which category of errors are coming up:\n\t\t\t\/\/\n\t\t\t\/\/  - Type 1.a: Exit codes of the contained user process.\n\t\t\t\/\/    - These aren't errors that we raise as such: they're just an int code to report.\n\t\t\t\/\/  - Type 1.b: Errors from invalid user configuration (e.g. no such executable, which prevents the process from ever starting) (we expect these to be reproducible!).\n\t\t\t\/\/    - These kinds of errors should be mapped onto clear types themselves: we want a \"NoSuchCwdError\", not just a string vomit.\n\t\t\t\/\/  - Type 2: Errors from runc being unable to function (e.g. maybe your kernel doesn't support cgroups, or other bizarre and serious issue?), where hopefully we can advise the user of this in a clear fashion.\n\t\t\t\/\/  - Type 3: Runc crashing in an unrecognized way (which should result in either patches to our recognizers, or bugs filed upstream to runc).\n\t\t\t\/\/\n\t\t\t\/\/ This is HARD.\n\t\t\t\/\/\n\t\t\t\/\/ NOTE WELL: we cannot guarantee to capture all semantic runc failure modes.\n\t\t\t\/\/  Errors may slip through with exit status 1: there are still many fail states\n\t\t\t\/\/  which runc does not log with sufficient consistency or a sufficiently separate\n\t\t\t\/\/  control channel for us to be able to reliably disambiguate them from stderr\n\t\t\t\/\/  output of a successfully executing job!\n\t\t\t\/\/\n\t\t\t\/\/ We have whitelisted recognizers for what we can, but oddities may remain.\n\t\t\tfor _, tr := range []struct {\n\t\t\t\tprefix, suffix string\n\t\t\t\terr            error\n\t\t\t}{\n\t\t\t\t{\"container_linux.go:262: starting container process caused \\\"exec: \\\\\\\"\", \": executable file not found in $PATH\\\"\\n\",\n\t\t\t\t\texecutor.NoSuchCommandError.New(\"command %q not found\", formula.Action.Entrypoint[0])},\n\t\t\t\t{\"container_linux.go:262: starting container process caused \\\"exec: \\\\\\\"\", \": no such file or directory\\\"\\n\",\n\t\t\t\t\texecutor.NoSuchCommandError.New(\"command %q not found\", formula.Action.Entrypoint[0])},\n\t\t\t\t{\"container_linux.go:262: starting container process caused \\\"chdir to cwd (\\\\\\\"\", \"\\\\\\\") set in config.json failed: not a directory\\\"\\n\",\n\t\t\t\t\texecutor.NoSuchCwdError.New(\"cannot set cwd to %q: no such file or directory\", formula.Action.Cwd)},\n\t\t\t\t{\"container_linux.go:262: starting container process caused \\\"chdir to cwd (\\\\\\\"\", \"\\\\\\\") set in config.json failed: no such file or directory\\\"\\n\",\n\t\t\t\t\texecutor.NoSuchCwdError.New(\"cannot set cwd to %q: no such file or directory\", formula.Action.Cwd)},\n\t\t\t\t\/\/ Note: Some other errors were previously raised in the pattern of `executor.TaskExecError.New(\"runc cannot operate in this environment!\")`,\n\t\t\t\t\/\/ but none of these are currently here because we cachebusted our known error strings when upgrading runc.\n\t\t\t} {\n\t\t\t\tif !strings.HasPrefix(logMsg[\"msg\"].(string), tr.prefix) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif !strings.HasSuffix(logMsg[\"msg\"].(string), tr.suffix) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trealError = tr.err\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ Log again.\n\t\t\t\/\/ The level of alarm we raise depends:\n\t\t\t\/\/  - If it's clearly flagged debug level, accept that;\n\t\t\t\/\/  - If we recognized it above, it's no more than a warning;\n\t\t\t\/\/  - If we *didn't* recognize and handle it explicitly, and\n\t\t\t\/\/    we can see a clear indication it's fatal, then log big and red.\n\t\t\tswitch ctx[\"runc-level\"] {\n\t\t\tcase \"debug\":\n\t\t\t\tjournal.Debug(logMsg[\"msg\"].(string), ctx)\n\t\t\tdefault:\n\t\t\t\tfallthrough\n\t\t\tcase \"error\":\n\t\t\t\tif realError == nil {\n\t\t\t\t\tjournal.Error(logMsg[\"msg\"].(string), ctx)\n\t\t\t\t\tsomeError = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tfallthrough\n\t\t\tcase \"warning\":\n\t\t\t\tjournal.Warn(logMsg[\"msg\"].(string), ctx)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ Wait for the job to complete.\n\tresult.ExitCode = proc.GetExitCode()\n\tjournal.Info(\"Execution done!\",\n\t\t\"elapsed\", time.Now().Sub(startedExec).Seconds(),\n\t)\n\t\/\/ Tell the log tailer to drain as soon as the proc exits.\n\truncLog.Close()\n\t\/\/ Wait for the tailer routine to drain & exit (this sync guards the err vars).\n\ttailerDone.Wait()\n\n\t\/\/ If we had a CnC error (rather than the real subprocess exit code):\n\t\/\/  - reset code to -1 because the runc exit code wasn't really from the job command\n\t\/\/  - finally, raise the error\n\t\/\/ FIXME we WISH we could zero the output buffers because runc pushes duplicate error messages\n\t\/\/  down a channel that's indistinguishable from the application stderr... but that's tricky for several reasons:\n\t\/\/  - we support streaming them out, right?\n\t\/\/  - that means we'd have to have been blocking them already; we can't zero retroactively.\n\t\/\/  - there's no \"all clear\" signal available from runc that would let us know we're clear to start flushing the stream if we blocked it.\n\t\/\/  - So, we're unable to pass the executor compat tests until patches to runc clean up this behavior.\n\tif someError && realError == nil {\n\t\trealError = executor.UnknownError.New(\"runc errored in an unrecognized fashion\")\n\t}\n\tif realError != nil {\n\t\tresult.ExitCode = -1\n\t\tpanic(realError)\n\t}\n\n\t\/\/ Save outputs\n\tresult.Outputs = util.PreserveOutputs(transmat, formula.Outputs, rootfsPath, journal)\n}\n<|endoftext|>"}
{"text":"<commit_before>package makex\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"sourcegraph.com\/sourcegraph\/rwvfs\"\n)\n\ntype Config struct {\n\tFS           FileSystem\n\tParallelJobs int\n\tVerbose      bool\n\tDryRun       bool\n}\n\nvar Default = Config{\n\tParallelJobs: 1,\n}\n\nfunc (c *Config) fs() FileSystem {\n\tif c.FS != nil {\n\t\treturn c.FS\n\t}\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tdir = \".\"\n\t}\n\treturn NewFileSystem(rwvfs.OS(dir))\n}\n\nfunc (c *Config) pathExists(path string) (bool, error) {\n\t_, err := c.fs().Stat(path)\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t} else if err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}\n\nfunc (c *Config) modTime(path string) (time.Time, error) {\n\ts, err := c.fs().Stat(path)\n\treturn s.ModTime(), err\n}\n\n\/\/ Flags adds makex command-line flags to an existing flag.FlagSet (or the\n\/\/ global FlagSet if fs is nil).\nfunc Flags(fs *flag.FlagSet, conf *Config, prefix string) {\n\tif fs == nil {\n\t\tfs = flag.CommandLine\n\t}\n\tfs.BoolVar(&conf.DryRun, prefix+\"n\", false, \"dry run (don't actually run any commands)\")\n\tfs.IntVar(&conf.ParallelJobs, prefix+\"j\", runtime.GOMAXPROCS(0), \"number of jobs to run in parallel\")\n\tfs.BoolVar(&conf.Verbose, prefix+\"v\", false, \"verbose\")\n}\n<commit_msg>nil check<commit_after>package makex\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"sourcegraph.com\/sourcegraph\/rwvfs\"\n)\n\ntype Config struct {\n\tFS           FileSystem\n\tParallelJobs int\n\tVerbose      bool\n\tDryRun       bool\n}\n\nvar Default = Config{\n\tParallelJobs: 1,\n}\n\nfunc (c *Config) fs() FileSystem {\n\tif c.FS != nil {\n\t\treturn c.FS\n\t}\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tdir = \".\"\n\t}\n\treturn NewFileSystem(rwvfs.OS(dir))\n}\n\nfunc (c *Config) pathExists(path string) (bool, error) {\n\t_, err := c.fs().Stat(path)\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t} else if err != nil {\n\t\treturn false, err\n\t}\n\treturn true, nil\n}\n\nfunc (c *Config) modTime(path string) (time.Time, error) {\n\ts, err := c.fs().Stat(path)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\treturn s.ModTime(), nil\n}\n\n\/\/ Flags adds makex command-line flags to an existing flag.FlagSet (or the\n\/\/ global FlagSet if fs is nil).\nfunc Flags(fs *flag.FlagSet, conf *Config, prefix string) {\n\tif fs == nil {\n\t\tfs = flag.CommandLine\n\t}\n\tfs.BoolVar(&conf.DryRun, prefix+\"n\", false, \"dry run (don't actually run any commands)\")\n\tfs.IntVar(&conf.ParallelJobs, prefix+\"j\", runtime.GOMAXPROCS(0), \"number of jobs to run in parallel\")\n\tfs.BoolVar(&conf.Verbose, prefix+\"v\", false, \"verbose\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package scroll\n\nimport (\n\t\"context\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\tetcd \"github.com\/coreos\/etcd\/clientv3\"\n\t\"github.com\/mailgun\/holster\"\n\t\"github.com\/mailgun\/scroll\/vulcand\"\n\t\"github.com\/pkg\/errors\"\n\t\"google.golang.org\/grpc\/grpclog\"\n)\n\nconst (\n\t\/\/ Suggested result set limit for APIs that may return many entries (e.g. paging).\n\tDefaultLimit = 100\n\n\t\/\/ Suggested max allowed result set limit for APIs that may return many entries (e.g. paging).\n\tMaxLimit = 10000\n\n\t\/\/ Suggested max allowed amount of entries that batch APIs can accept (e.g. batch uploads).\n\tMaxBatchSize = 1000\n\n\tdefaultHTTPReadTimeout  = 10 * time.Second\n\tdefaultHTTPWriteTimeout = 60 * time.Second\n\tdefaultHTTPIdleTimeout  = 60 * time.Second\n\tlocalInsecureEndpoint   = \"http:\/\/127.0.0.1:2379\"\n\tlocalSecureEndpoint     = \"https:\/\/127.0.0.1:2379\"\n\tdefaultRegistrationTTL  = 30 * time.Second\n\tdefaultNamespace        = \"\/vulcand\"\n\tpathToCertAuthority     = \"\/etc\/mailgun\/certs\/ca.pem\"\n)\n\nfunc applyDefaults(cfg *AppConfig) error {\n\tvar envEndpoint, envUser, envPass, envDebug, endpoint, tlsCertFile, tlsKeyFile string\n\n\tfor k, v := range map[string]*string{\n\t\t\"ETCD3_ENDPOINT\": &envEndpoint,\n\t\t\"ETCD3_USER\":     &envUser,\n\t\t\"ETCD3_PASSWORD\": &envPass,\n\t\t\"ETCD3_DEBUG\":    &envDebug,\n\t\t\"ETCD3_TLS_CERT\": &tlsCertFile,\n\t\t\"ETCD3_TLS_KEY\":  &tlsKeyFile,\n\t} {\n\t\t*v = os.Getenv(k)\n\t}\n\n\tholster.SetDefault(&cfg.HTTP.ReadTimeout, defaultHTTPReadTimeout)\n\tholster.SetDefault(&cfg.HTTP.WriteTimeout, defaultHTTPWriteTimeout)\n\tholster.SetDefault(&cfg.HTTP.IdleTimeout, defaultHTTPIdleTimeout)\n\n\tholster.SetDefault(&cfg.Vulcand, &vulcand.Config{})\n\tholster.SetDefault(&cfg.Vulcand.TTL, defaultRegistrationTTL)\n\tholster.SetDefault(&cfg.Vulcand.Etcd, &etcd.Config{})\n\n\tholster.SetDefault(&endpoint, envEndpoint, localInsecureEndpoint)\n\tholster.SetDefault(&cfg.Vulcand.Etcd.Endpoints, []string{endpoint})\n\n\tholster.SetDefault(&cfg.Vulcand.Namespace, defaultNamespace)\n\tholster.SetDefault(&cfg.Vulcand.Etcd.Username, envUser)\n\tholster.SetDefault(&cfg.Vulcand.Etcd.Password, envPass)\n\n\tif envDebug != \"\" {\n\t\tgrpclog.SetLoggerV2(grpclog.NewLoggerV2WithVerbosity(os.Stderr, os.Stderr, os.Stderr, 4))\n\t}\n\n\tif cfg.Vulcand.Etcd.Username == \"\" {\n\t\treturn nil\n\t}\n\n\tif cfg.Vulcand.Etcd.Password == \"\" {\n\t\treturn fmt.Errorf(\"etcd username provided but password is empty\")\n\t}\n\n\t\/\/ If 'user' and 'pass' supplied assume skip verify TLS config\n\tholster.SetDefault(&cfg.Vulcand.Etcd.TLS, &tls.Config{InsecureSkipVerify: true})\n\n\t\/\/ If the CA file exists use that\n\tif _, err := os.Stat(pathToCertAuthority); err == nil {\n\t\tvar rpool *x509.CertPool = nil\n\t\tif pemBytes, err := ioutil.ReadFile(pathToCertAuthority); err == nil {\n\t\t\trpool = x509.NewCertPool()\n\t\t\trpool.AppendCertsFromPEM(pemBytes)\n\t\t} else {\n\t\t\treturn errors.Errorf(\"while loading cert CA file '%s': %s\", pathToCertAuthority, err)\n\t\t}\n\t\tcfg.Vulcand.Etcd.TLS.RootCAs = rpool\n\t\tcfg.Vulcand.Etcd.TLS.InsecureSkipVerify = false\n\t}\n\n\tif tlsCertFile != \"\" && tlsKeyFile != \"\" {\n\t\ttlsCert, err := tls.LoadX509KeyPair(tlsCertFile, tlsKeyFile)\n\t\tif err != nil {\n\t\t\treturn errors.Errorf(\"while loading cert '%s' and key file '%s': %s\",\n\t\t\t\ttlsCertFile, tlsKeyFile, err)\n\t\t}\n\t\tcfg.Vulcand.Etcd.TLS.Certificates = []tls.Certificate{tlsCert}\n\t}\n\n\t\/\/ If we provided the default endpoint, make it a secure endpoint\n\tif cfg.Vulcand.Etcd.Endpoints[0] == localInsecureEndpoint {\n\t\tcfg.Vulcand.Etcd.Endpoints[0] = localSecureEndpoint\n\t}\n\n\t\/\/ Ensure the endpoint is https:\/\/\n\tif !strings.HasPrefix(cfg.Vulcand.Etcd.Endpoints[0], \"https:\/\/\") {\n\t\treturn fmt.Errorf(\"when connecting to etcd via TLS with credentials \" +\n\t\t\t\"endpoint must begin with https:\/\/\")\n\t}\n\n\treturn nil\n}\n\nfunc fetchEtcdConfig(cfg *AppConfig) error {\n\tif cfg.Vulcand == nil || cfg.Vulcand.Etcd == nil {\n\t\treturn errors.New(\"a valid etcd.Config{} and vulcand.Config{} config is required\")\n\t}\n\n\tclient, err := etcd.New(*cfg.Vulcand.Etcd)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create etcd client for config retrieval, cfg=%v\", *cfg.Vulcand.Etcd)\n\t}\n\tctx, cancelFunc := context.WithCancel(context.Background())\n\tdefer cancelFunc()\n\n\tkey := fmt.Sprintf(\"\/mailgun\/configs\/%s\", cfg.Name)\n\tresp, err := client.Get(ctx, key)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"while retrieving key '%s'\", key)\n\t}\n\n\tif len(resp.Kvs) == 0 {\n\t\treturn errors.Errorf(\"config not found while retrieving '%s'\", key)\n\t}\n\n\tjsonCfg := JSONConfig{}\n\tif err := json.Unmarshal(resp.Kvs[0].Value, &jsonCfg); err != nil {\n\t\treturn errors.Wrap(err, \"while parsing json from etcd config\")\n\t}\n\n\t\/\/ Map the json config to our vulcand config\n\tcfg.Vulcand.Namespace = jsonCfg.VulcandNamespace\n\tcfg.PublicAPIHost = jsonCfg.PublicAPIHost\n\tcfg.PublicAPIURL = jsonCfg.PublicAPIURL\n\tcfg.ProtectedAPIHost = jsonCfg.ProtectedAPIHost\n\tcfg.ProtectedAPIURL = jsonCfg.ProtectedAPIURL\n\n\treturn nil\n}\n<commit_msg>perfer ETCD3_CA over default ca location<commit_after>package scroll\n\nimport (\n\t\"context\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\tetcd \"github.com\/coreos\/etcd\/clientv3\"\n\t\"github.com\/mailgun\/holster\"\n\t\"github.com\/mailgun\/scroll\/vulcand\"\n\t\"github.com\/pkg\/errors\"\n\t\"google.golang.org\/grpc\/grpclog\"\n)\n\nconst (\n\t\/\/ Suggested result set limit for APIs that may return many entries (e.g. paging).\n\tDefaultLimit = 100\n\n\t\/\/ Suggested max allowed result set limit for APIs that may return many entries (e.g. paging).\n\tMaxLimit = 10000\n\n\t\/\/ Suggested max allowed amount of entries that batch APIs can accept (e.g. batch uploads).\n\tMaxBatchSize = 1000\n\n\tdefaultHTTPReadTimeout  = 10 * time.Second\n\tdefaultHTTPWriteTimeout = 60 * time.Second\n\tdefaultHTTPIdleTimeout  = 60 * time.Second\n\tlocalInsecureEndpoint   = \"http:\/\/127.0.0.1:2379\"\n\tlocalSecureEndpoint     = \"https:\/\/127.0.0.1:2379\"\n\tdefaultRegistrationTTL  = 30 * time.Second\n\tdefaultNamespace        = \"\/vulcand\"\n\tpathToCertAuthority     = \"\/etc\/mailgun\/ssl\/localhost\/ca.pem\"\n)\n\nfunc applyDefaults(cfg *AppConfig) error {\n\tvar envEndpoint, envUser, envPass, envDebug, endpoint,\n\t\ttlsCertFile, tlsKeyFile, tlsCaCertFile string\n\n\tfor k, v := range map[string]*string{\n\t\t\"ETCD3_ENDPOINT\": &envEndpoint,\n\t\t\"ETCD3_USER\":     &envUser,\n\t\t\"ETCD3_PASSWORD\": &envPass,\n\t\t\"ETCD3_DEBUG\":    &envDebug,\n\t\t\"ETCD3_TLS_CERT\": &tlsCertFile,\n\t\t\"ETCD3_TLS_KEY\":  &tlsKeyFile,\n\t\t\"ETCD3_CA\":       &tlsCaCertFile,\n\t} {\n\t\t*v = os.Getenv(k)\n\t}\n\n\tholster.SetDefault(&cfg.HTTP.ReadTimeout, defaultHTTPReadTimeout)\n\tholster.SetDefault(&cfg.HTTP.WriteTimeout, defaultHTTPWriteTimeout)\n\tholster.SetDefault(&cfg.HTTP.IdleTimeout, defaultHTTPIdleTimeout)\n\n\tholster.SetDefault(&cfg.Vulcand, &vulcand.Config{})\n\tholster.SetDefault(&cfg.Vulcand.TTL, defaultRegistrationTTL)\n\tholster.SetDefault(&cfg.Vulcand.Etcd, &etcd.Config{})\n\n\tholster.SetDefault(&endpoint, envEndpoint, localInsecureEndpoint)\n\tholster.SetDefault(&cfg.Vulcand.Etcd.Endpoints, []string{endpoint})\n\n\tholster.SetDefault(&cfg.Vulcand.Namespace, defaultNamespace)\n\tholster.SetDefault(&cfg.Vulcand.Etcd.Username, envUser)\n\tholster.SetDefault(&cfg.Vulcand.Etcd.Password, envPass)\n\n\tif envDebug != \"\" {\n\t\tgrpclog.SetLoggerV2(grpclog.NewLoggerV2WithVerbosity(os.Stderr, os.Stderr, os.Stderr, 4))\n\t}\n\n\tif cfg.Vulcand.Etcd.Username == \"\" {\n\t\treturn nil\n\t}\n\n\tif cfg.Vulcand.Etcd.Password == \"\" {\n\t\treturn fmt.Errorf(\"etcd username provided but password is empty\")\n\t}\n\n\t\/\/ If 'user' and 'pass' supplied assume skip verify TLS config\n\tholster.SetDefault(&cfg.Vulcand.Etcd.TLS, &tls.Config{InsecureSkipVerify: true})\n\tholster.SetDefault(&tlsCaCertFile, pathToCertAuthority)\n\n\t\/\/ If the CA file exists use that\n\tif _, err := os.Stat(tlsCaCertFile); err == nil {\n\t\tvar rpool *x509.CertPool = nil\n\t\tif pemBytes, err := ioutil.ReadFile(tlsCaCertFile); err == nil {\n\t\t\trpool = x509.NewCertPool()\n\t\t\trpool.AppendCertsFromPEM(pemBytes)\n\t\t} else {\n\t\t\treturn errors.Errorf(\"while loading cert CA file '%s': %s\", tlsCaCertFile, err)\n\t\t}\n\t\tcfg.Vulcand.Etcd.TLS.RootCAs = rpool\n\t\tcfg.Vulcand.Etcd.TLS.InsecureSkipVerify = false\n\t}\n\n\tif tlsCertFile != \"\" && tlsKeyFile != \"\" {\n\t\ttlsCert, err := tls.LoadX509KeyPair(tlsCertFile, tlsKeyFile)\n\t\tif err != nil {\n\t\t\treturn errors.Errorf(\"while loading cert '%s' and key file '%s': %s\",\n\t\t\t\ttlsCertFile, tlsKeyFile, err)\n\t\t}\n\t\tcfg.Vulcand.Etcd.TLS.Certificates = []tls.Certificate{tlsCert}\n\t}\n\n\t\/\/ If we provided the default endpoint, make it a secure endpoint\n\tif cfg.Vulcand.Etcd.Endpoints[0] == localInsecureEndpoint {\n\t\tcfg.Vulcand.Etcd.Endpoints[0] = localSecureEndpoint\n\t}\n\n\t\/\/ Ensure the endpoint is https:\/\/\n\tif !strings.HasPrefix(cfg.Vulcand.Etcd.Endpoints[0], \"https:\/\/\") {\n\t\treturn fmt.Errorf(\"when connecting to etcd via TLS with credentials \" +\n\t\t\t\"endpoint must begin with https:\/\/\")\n\t}\n\n\treturn nil\n}\n\nfunc fetchEtcdConfig(cfg *AppConfig) error {\n\tif cfg.Vulcand == nil || cfg.Vulcand.Etcd == nil {\n\t\treturn errors.New(\"a valid etcd.Config{} and vulcand.Config{} config is required\")\n\t}\n\n\tclient, err := etcd.New(*cfg.Vulcand.Etcd)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create etcd client for config retrieval, cfg=%v\", *cfg.Vulcand.Etcd)\n\t}\n\tctx, cancelFunc := context.WithCancel(context.Background())\n\tdefer cancelFunc()\n\n\tkey := fmt.Sprintf(\"\/mailgun\/configs\/%s\", cfg.Name)\n\tresp, err := client.Get(ctx, key)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"while retrieving key '%s'\", key)\n\t}\n\n\tif len(resp.Kvs) == 0 {\n\t\treturn errors.Errorf(\"config not found while retrieving '%s'\", key)\n\t}\n\n\tjsonCfg := JSONConfig{}\n\tif err := json.Unmarshal(resp.Kvs[0].Value, &jsonCfg); err != nil {\n\t\treturn errors.Wrap(err, \"while parsing json from etcd config\")\n\t}\n\n\t\/\/ Map the json config to our vulcand config\n\tcfg.Vulcand.Namespace = jsonCfg.VulcandNamespace\n\tcfg.PublicAPIHost = jsonCfg.PublicAPIHost\n\tcfg.PublicAPIURL = jsonCfg.PublicAPIURL\n\tcfg.ProtectedAPIHost = jsonCfg.ProtectedAPIHost\n\tcfg.ProtectedAPIURL = jsonCfg.ProtectedAPIURL\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"gopkg.in\/yaml.v2\"\n)\n\ntype ConfigNamespace struct {\n\tOrganization string \/\/ optional additional namespace for orgs.\n\tNamespace    string \/\/ usually project name.\n}\n\ntype Config interface {\n\tLoad(src string, dst interface{}) error\n}\n\nconst UserBase string = \"~\/.config\/\"\nconst EtcDir string = \"\/etc\/\"\n\n\/\/ Load expands the provided src path using config.ExpandUser, then reads\n\/\/ the file and unmarshals into dst using go-yaml.\nfunc Load(src string, dst interface{}) (err error) {\n\tdstv := reflect.ValueOf(dst)\n\n\tif dstv.Kind() != reflect.Ptr {\n\t\terr = errors.New(\"config: not a pointer.\")\n\t} else if dstv.IsNil() {\n\t\terr = fmt.Errorf(\"nil %s.\", reflect.TypeOf(dstv).String())\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpath, err := ExpandUser(src)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = yaml.Unmarshal(data, &dst)\n\treturn\n}\n\nfunc ExpandUser(path string) (exPath string, err error) {\n\t\/\/ Acts kind of like os.path.expanduser in Python, except only supports\n\t\/\/ expanding \"~\/\" or \"$HOME\"\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdir := usr.HomeDir\n\n\tif path[:2] == \"~\/\" {\n\t\texPath = strings.Replace(path, \"~\/\", dir, 1)\n\t} else if path[:5] == \"$HOME\" {\n\t\texPath = strings.Replace(path, \"$HOME\", dir, 1)\n\t} else {\n\t\terr = errors.New(\"No expandable path provided.\")\n\t}\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\texPath, err = filepath.Abs(filepath.Clean(exPath))\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn\n}\n\n\/\/ Returns path to config, chosen by hierarchy and checked for existence:\n\/\/ 1. User config (~\/.config\/podhub\/canary\/config.yaml)\n\/\/ 2. System config (\/etc\/podhub\/canary\/config.yaml)\nfunc (c ConfigNamespace) Path() (path string, err error) {\n\tsystemPath, _ := c.systemPath()\n\tif _, err := os.Stat(systemPath); err == nil {\n\t\tpath, _ = c.systemPath()\n\t}\n\n\tuserPath, _ := c.userPath()\n\tif _, err := os.Stat(userPath); err == nil {\n\t\tpath, _ = c.userPath()\n\t}\n\treturn\n}\n\nfunc (c ConfigNamespace) systemPath() (path string, err error) {\n\tpath = filepath.Join(EtcDir, c.Organization, c.Namespace, \"config.yaml\")\n\treturn\n}\n\nfunc (c ConfigNamespace) userPath() (path string, err error) {\n\tuserBase, err := ExpandUser(UserBase)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpath = filepath.Join(userBase, c.Organization, c.Namespace, \"config.yaml\")\n\treturn\n}\n\nfunc (c ConfigNamespace) Load(dst interface{}) (err error) {\n\tcfgPath, err := c.Path()\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = Load(cfgPath, dst)\n\treturn\n}\n<commit_msg>fix path expansion<commit_after>package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"gopkg.in\/yaml.v2\"\n)\n\ntype ConfigNamespace struct {\n\tOrganization string \/\/ optional additional namespace for orgs.\n\tNamespace    string \/\/ usually project name.\n}\n\ntype Config interface {\n\tLoad(src string, dst interface{}) error\n}\n\nconst UserBase string = \"~\/.config\/\"\nconst EtcDir string = \"\/etc\/\"\n\n\/\/ Load expands the provided src path using config.ExpandUser, then reads\n\/\/ the file and unmarshals into dst using go-yaml.\nfunc Load(src string, dst interface{}) (err error) {\n\tdstv := reflect.ValueOf(dst)\n\n\tif dstv.Kind() != reflect.Ptr {\n\t\terr = errors.New(\"config: not a pointer.\")\n\t} else if dstv.IsNil() {\n\t\terr = fmt.Errorf(\"nil %s.\", reflect.TypeOf(dstv).String())\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpath, err := ExpandUser(src)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = yaml.Unmarshal(data, &dst)\n\treturn\n}\n\nfunc ExpandUser(path string) (exPath string, err error) {\n\t\/\/ Acts kind of like os.path.expanduser in Python, except only supports\n\t\/\/ expanding \"~\/\" or \"$HOME\"\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdir := fmt.Sprintf(\"%s\/\", usr.HomeDir)\n\n\texPath = strings.Replace(path, \"~\/\", dir, 1)\n\texPath = strings.Replace(exPath, \"$HOME\", dir, 1)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\texPath, err = filepath.Abs(filepath.Clean(exPath))\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn\n}\n\n\/\/ Returns path to config, chosen by hierarchy and checked for existence:\n\/\/ 1. User config (~\/.config\/podhub\/canary\/config.yaml)\n\/\/ 2. System config (\/etc\/podhub\/canary\/config.yaml)\nfunc (c ConfigNamespace) Path() (path string, err error) {\n\tsystemPath, _ := c.systemPath()\n\tif _, err := os.Stat(systemPath); err == nil {\n\t\tpath, _ = c.systemPath()\n\t}\n\n\tuserPath, _ := c.userPath()\n\tif _, err := os.Stat(userPath); err == nil {\n\t\tpath, _ = c.userPath()\n\t}\n\treturn\n}\n\nfunc (c ConfigNamespace) systemPath() (path string, err error) {\n\tpath = filepath.Join(EtcDir, c.Organization, c.Namespace, \"config.yaml\")\n\treturn\n}\n\nfunc (c ConfigNamespace) userPath() (path string, err error) {\n\tuserBase, err := ExpandUser(UserBase)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpath = filepath.Join(userBase, c.Organization, c.Namespace, \"config.yaml\")\n\treturn\n}\n\nfunc (c ConfigNamespace) Load(dst interface{}) (err error) {\n\tcfgPath, err := c.Path()\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = Load(cfgPath, dst)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package gobbs\n\nimport (\n\t\"encoding\/xml\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\n\t\"github.com\/liangguangchuan\/gobbs\/lib\"\n)\n\nvar (\n\t\/\/基础配置文件\n\tBConf *Conf\n\t\/\/项目访问路径\n\tAppPath string\n\t\/\/运行模式 dev prod\n\tRunMode string\n\t\/\/项目目录\n\tWorkPath string\n\t\/\/支持 view 层解析格式\n\tTplExt = []string{\"tpl\", \"html\", \"htm\"}\n)\n\n\/\/配置构造体\ntype Conf struct {\n\tHost      string            `xml:\"server_host\"` \/\/运行域名\n\tPort      int64             `xml:\"server_port\"` \/\/运行端口\n\tAppName   string            `xml:\"app_name\"`    \/\/项目名称\n\tRunMode   string            `xml:\"run_mode\"`    \/\/运行模块\n\tTplPATH   string            `xml:\"tpl_path\"`    \/\/模板路径\n\tTplExt    string            `xml:\"tpl_ext\"`     \/\/模板后缀\n\tStaticDir map[string]string `xml:\"static_dir\"`  \/\/静态文件目录\n\tDb        confDB            `xml:\"db\"`          \/\/db 数据\n}\n\n\/\/web 配置 主要用来配置 静态文件目录\ntype WebConfig struct {\n}\n\n\/\/db配置 可能直接使用第三方orm\ntype confDB struct {\n\tHost     string \/\/请求地址\n\tPort     int64  \/\/端口\n\tUsername string \/\/登录用户\n\tUserpass string \/\/登录密码\n\tDatebase string \/\/请求数据库\n\tTablePre string \/\/表前缀\n}\n\n\/\/配置初始化\nfunc init() {\n\t\/\/创建  Conf\n\tBConf = newConf()\n\tvar err error\n\t\/\/获取当前运行的 路径 如果获取失败抛出错误\n\tif AppPath, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/获取工作目录\n\tWorkPath, err = os.Getwd()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/拼接 conf 路径\n\tconfPath := filepath.Join(WorkPath, \"conf\", \"conf.xml\")\n\t\/\/如果项目目录拼接conf\/conf.xml 不存在对应文件\n\tif !lib.FileExists(confPath) {\n\t\tconfPath = filepath.Join(AppPath, \"conf\", \"conf.xml\")\n\t\t\/\/ 根据运行文件目录拼接conf\/conf.xml 不存在对应文件\n\t\tif !lib.FileExists(confPath) {\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/读取文件并赋值 conf\n\tif err = parseConfig(confPath); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/tpl 配置 后缀检查\n\tif TplExtCheck(BConf.TplExt) == false {\n\t\tlog.Fatal(\"`tpl_ext` can only be html,htm,tpl\")\n\t}\n\t\/\/如果当前运行为 develop 输出对应的 conf配置\n\tif BConf.RunMode == DEV {\n\t\tlog.Println(BConf)\n\t}\n}\n\n\/\/生产conf\nfunc newConf() *Conf {\n\treturn &Conf{\n\t\tHost:      \"127.0.0.1\",\n\t\tPort:      8080,\n\t\tAppName:   \"xiaochuan\",\n\t\tRunMode:   DEV,\n\t\tTplPATH:   \"view\",\n\t\tTplExt:    \"tpl\",\n\t\tStaticDir: map[string]string{\"public\": \"public\"},\n\t\tDb:        confDB{},\n\t}\n}\n\n\/\/解析 conf.xml\nfunc parseConfig(confPath string) error {\n\t\/\/文件读取\n\tfileData, err := ioutil.ReadFile(confPath)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/xml 解析到对应构造体\n\terr = xml.Unmarshal(fileData, BConf)\n\n\treturn err\n}\n\n\/\/模板后缀检查\nfunc TplExtCheck(ext string) bool {\n\n\tfor _, v := range TplExt {\n\n\t\tif ext == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\nfunc (c *Conf) getConf(key string) interface{} {\n\tval := reflect.ValueOf(c)\n\tv := val.Elem().FieldByName(key)\n\t\/\/如果存在对应的字段\n\tif v.IsValid() {\n\t\treturn v.Interface()\n\t} else {\n\t\treturn nil\n\t}\n\n}\n<commit_msg>static file pro<commit_after>package gobbs\n\nimport (\n\t\"encoding\/xml\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\n\t\"github.com\/liangguangchuan\/gobbs\/lib\"\n)\n\nvar (\n\t\/\/基础配置文件\n\tBConf *Conf\n\t\/\/项目访问路径\n\tAppPath string\n\t\/\/运行模式 dev prod\n\tRunMode string\n\t\/\/项目目录\n\tWorkPath string\n\t\/\/支持 view 层解析格式\n\tTplExt = []string{\"tpl\", \"html\", \"htm\"}\n)\n\n\/\/配置构造体\ntype Conf struct {\n\tHost      string            `xml:\"server_host\"` \/\/运行域名\n\tPort      int64             `xml:\"server_port\"` \/\/运行端口\n\tAppName   string            `xml:\"app_name\"`    \/\/项目名称\n\tRunMode   string            `xml:\"run_mode\"`    \/\/运行模块\n\tTplPATH   string            `xml:\"tpl_path\"`    \/\/模板路径\n\tTplExt    string            `xml:\"tpl_ext\"`     \/\/模板后缀\n\tStaticDir map[string]string `xml:\"static_dir\"`  \/\/静态文件目录\n\tDb        confDB            `xml:\"db\"`          \/\/db 数据\n}\n\n\/\/db配置 可能直接使用第三方orm\ntype confDB struct {\n\tHost     string \/\/请求地址\n\tPort     int64  \/\/端口\n\tUsername string \/\/登录用户\n\tUserpass string \/\/登录密码\n\tDatebase string \/\/请求数据库\n\tTablePre string \/\/表前缀\n}\n\n\/\/配置初始化\nfunc init() {\n\t\/\/创建  Conf\n\tBConf = newConf()\n\tvar err error\n\t\/\/获取当前运行的 路径 如果获取失败抛出错误\n\tif AppPath, err = filepath.Abs(filepath.Dir(os.Args[0])); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/获取工作目录\n\tWorkPath, err = os.Getwd()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/拼接 conf 路径\n\tconfPath := filepath.Join(WorkPath, \"conf\", \"conf.xml\")\n\t\/\/如果项目目录拼接conf\/conf.xml 不存在对应文件\n\tif !lib.FileExists(confPath) {\n\t\tconfPath = filepath.Join(AppPath, \"conf\", \"conf.xml\")\n\t\t\/\/ 根据运行文件目录拼接conf\/conf.xml 不存在对应文件\n\t\tif !lib.FileExists(confPath) {\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/读取文件并赋值 conf\n\tif err = parseConfig(confPath); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/tpl 配置 后缀检查\n\tif TplExtCheck(BConf.TplExt) == false {\n\t\tlog.Fatal(\"`tpl_ext` can only be html,htm,tpl\")\n\t}\n\t\/\/如果当前运行为 develop 输出对应的 conf配置\n\tif BConf.RunMode == DEV {\n\t\tlog.Println(BConf)\n\t}\n}\n\n\/\/生产conf\nfunc newConf() *Conf {\n\treturn &Conf{\n\t\tHost:      \"127.0.0.1\",\n\t\tPort:      8080,\n\t\tAppName:   \"xiaochuan\",\n\t\tRunMode:   DEV,\n\t\tTplPATH:   \"view\",\n\t\tTplExt:    \"tpl\",\n\t\tStaticDir: map[string]string{\"public\": \"public\"},\n\t\tDb:        confDB{},\n\t}\n}\n\n\/\/解析 conf.xml\nfunc parseConfig(confPath string) error {\n\t\/\/文件读取\n\tfileData, err := ioutil.ReadFile(confPath)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/xml 解析到对应构造体\n\terr = xml.Unmarshal(fileData, BConf)\n\n\treturn err\n}\n\n\/\/模板后缀检查\nfunc TplExtCheck(ext string) bool {\n\n\tfor _, v := range TplExt {\n\n\t\tif ext == v {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\nfunc (c *Conf) getConf(key string) interface{} {\n\tval := reflect.ValueOf(c)\n\tv := val.Elem().FieldByName(key)\n\t\/\/如果存在对应的字段\n\tif v.IsValid() {\n\t\treturn v.Interface()\n\t} else {\n\t\treturn nil\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n    \"encoding\/json\"\n    \"io\/ioutil\"\n)\n\ntype Config struct {\n    Nick        string\n    Host        string\n    RealName    string\n    Networks    []string\n    Servers     map[string] []string\n    Channels    map[string] []string\n    Passwords   map[string] string\n    Plugins     []string\n    Ignore      []string\n    Logpath     string\n}\n\nfunc ReadConfig(path string) (Config, error) {\n    var config Config\n    \n    data, err := ioutil.ReadFile(path)\n    if err != nil {\n        return config, err\n    }\n\n    err = json.Unmarshal(data, &config)\n    if err != nil {\n        return config, err\n    }\n\n    return config, nil\n}\n<commit_msg>Expose username and realname to configuration and make use of it in irc.Dial()<commit_after>package config\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n)\n\ntype Config struct {\n\tNick      string\n\tHost      string\n\tRealName  string\n\tUser      string\n\tNetworks  []string\n\tServers   map[string][]string\n\tChannels  map[string][]string\n\tPasswords map[string]string\n\tPlugins   []string\n\tIgnore    []string\n\tLogpath   string\n}\n\nfunc ReadConfig(path string) (Config, error) {\n\tvar config Config\n\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\terr = json.Unmarshal(data, &config)\n\tif err != nil {\n\t\treturn config, err\n\t}\n\n\treturn config, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package gitmedia\n\nimport (\n\t\"os\"\n\t\"strings\"\n)\n\ntype Configuration struct {\n\tgitConfig map[string]string\n\tremotes   []string\n}\n\nvar Config = &Configuration{}\n\nfunc (c *Configuration) Endpoint() string {\n\tif url, ok := c.GitConfig(\"media.url\"); ok {\n\t\treturn url\n\t}\n\n\treturn c.RemoteEndpoint(\"origin\")\n}\n\nfunc (c *Configuration) RemoteEndpoint(remote string) string {\n\tif url, ok := c.GitConfig(\"remote.\" + remote + \".media\"); ok {\n\t\treturn url\n\t}\n\n\tif url, ok := c.GitConfig(\"remote.\" + remote + \".url\"); ok {\n\t\treturn url + \".git\/info\/media\"\n\t}\n\n\treturn \"\"\n}\n\nfunc (c *Configuration) Remotes() []string {\n\tif c.remotes == nil {\n\t\tc.loadGitConfig()\n\t}\n\treturn c.remotes\n}\n\nfunc (c *Configuration) GitConfig(key string) (string, bool) {\n\tif c.gitConfig == nil {\n\t\tc.loadGitConfig()\n\t}\n\tvalue, ok := c.gitConfig[key]\n\treturn value, ok\n}\n\nfunc (c *Configuration) SetConfig(key, value string) {\n\tif c.gitConfig == nil {\n\t\tc.loadGitConfig()\n\t}\n\tc.gitConfig[key] = value\n}\n\ntype AltConfig struct {\n\tRemote map[string]*struct {\n\t\tMedia string\n\t}\n\n\tMedia struct {\n\t\tUrl string\n\t}\n}\n\nfunc (c *Configuration) loadGitConfig() {\n\tuniqRemotes := make(map[string]bool)\n\n\tc.gitConfig = make(map[string]string)\n\n\tvar output string\n\toutput = SimpleExec(\"git\", \"config\", \"-l\")\n\toutput += \"\\n\"\n\toutput += SimpleExec(\"git\", \"config\", \"-l\", \"-f\", \".gitconfig\")\n\n\tlines := strings.Split(output, \"\\n\")\n\tfor _, line := range lines {\n\t\tpieces := strings.SplitN(line, \"=\", 2)\n\t\tif len(pieces) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tkey := pieces[0]\n\t\tc.gitConfig[key] = pieces[1]\n\n\t\tkeyParts := strings.Split(key, \".\")\n\t\tif len(keyParts) > 1 && keyParts[0] == \"remote\" {\n\t\t\tremote := keyParts[1]\n\t\t\tuniqRemotes[remote] = remote == \"origin\"\n\t\t}\n\t}\n\n\tc.remotes = make([]string, 0, len(uniqRemotes))\n\tfor remote, isOrigin := range uniqRemotes {\n\t\tif isOrigin {\n\t\t\tcontinue\n\t\t}\n\t\tc.remotes = append(c.remotes, remote)\n\t}\n}\n\nfunc configFileExists(filename string) bool {\n\tif _, err := os.Stat(filename); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}\n<commit_msg>Handle repos that end with and without \".git\"<commit_after>package gitmedia\n\nimport (\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n)\n\ntype Configuration struct {\n\tgitConfig map[string]string\n\tremotes   []string\n}\n\nvar Config = &Configuration{}\n\nfunc (c *Configuration) Endpoint() string {\n\tif url, ok := c.GitConfig(\"media.url\"); ok {\n\t\treturn url\n\t}\n\n\treturn c.RemoteEndpoint(\"origin\")\n}\n\nfunc (c *Configuration) RemoteEndpoint(remote string) string {\n\tif url, ok := c.GitConfig(\"remote.\" + remote + \".media\"); ok {\n\t\treturn url\n\t}\n\n\tif url, ok := c.GitConfig(\"remote.\" + remote + \".url\"); ok {\n\t\tif path.Ext(url) == \".git\" {\n\t\t\treturn url + \"\/info\/media\"\n\t\t}\n\t\treturn url + \".git\/info\/media\"\n\t}\n\n\treturn \"\"\n}\n\nfunc (c *Configuration) Remotes() []string {\n\tif c.remotes == nil {\n\t\tc.loadGitConfig()\n\t}\n\treturn c.remotes\n}\n\nfunc (c *Configuration) GitConfig(key string) (string, bool) {\n\tif c.gitConfig == nil {\n\t\tc.loadGitConfig()\n\t}\n\tvalue, ok := c.gitConfig[key]\n\treturn value, ok\n}\n\nfunc (c *Configuration) SetConfig(key, value string) {\n\tif c.gitConfig == nil {\n\t\tc.loadGitConfig()\n\t}\n\tc.gitConfig[key] = value\n}\n\ntype AltConfig struct {\n\tRemote map[string]*struct {\n\t\tMedia string\n\t}\n\n\tMedia struct {\n\t\tUrl string\n\t}\n}\n\nfunc (c *Configuration) loadGitConfig() {\n\tuniqRemotes := make(map[string]bool)\n\n\tc.gitConfig = make(map[string]string)\n\n\tvar output string\n\toutput = SimpleExec(\"git\", \"config\", \"-l\")\n\toutput += \"\\n\"\n\toutput += SimpleExec(\"git\", \"config\", \"-l\", \"-f\", \".gitconfig\")\n\n\tlines := strings.Split(output, \"\\n\")\n\tfor _, line := range lines {\n\t\tpieces := strings.SplitN(line, \"=\", 2)\n\t\tif len(pieces) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tkey := pieces[0]\n\t\tc.gitConfig[key] = pieces[1]\n\n\t\tkeyParts := strings.Split(key, \".\")\n\t\tif len(keyParts) > 1 && keyParts[0] == \"remote\" {\n\t\t\tremote := keyParts[1]\n\t\t\tuniqRemotes[remote] = remote == \"origin\"\n\t\t}\n\t}\n\n\tc.remotes = make([]string, 0, len(uniqRemotes))\n\tfor remote, isOrigin := range uniqRemotes {\n\t\tif isOrigin {\n\t\t\tcontinue\n\t\t}\n\t\tc.remotes = append(c.remotes, remote)\n\t}\n}\n\nfunc configFileExists(filename string) bool {\n\tif _, err := os.Stat(filename); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package controllers\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/takonews\/takonews-api\/app\/models\"\n\t\"github.com\/takonews\/takonews-api\/db\"\n)\n\n\/\/ ArticleIndex show articles\n\/\/ Available Query Parameters\n\/\/ * sort\n\/\/ * fields\n\/\/ * filter\nfunc ArticleIndex(c *gin.Context) {\n\t\/\/ parameters\n\tvar sort []string\n\tvar fields []string\n\tvar startDate time.Time\n\tvar endDate time.Time\n\tvar title string\n\n\tsort = strings.Split(c.Query(\"sort\"), \",\")\n\tfields = strings.Split(c.Query(\"fields\"), \",\")\n\tloc, err := time.LoadLocation(\"Asia\/Tokyo\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tnow := time.Now().In(loc)\n\tif c.Query(\"start-date\") == \"\" { \/\/ default: today:00:00:00\n\t\tstartDate = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)\n\t} else {\n\t\tstartDate, err = time.Parse(\"2006-01-02\", c.Query(\"start-date\"))\n\t\tstartDate = startDate.Add(-9 * time.Hour).In(loc)\n\t}\n\tif c.Query(\"end-date\") == \"\" { \/\/ default: tomorrow:00:00:00\n\t\tendDate = time.Date(now.Year(), now.Month(), now.Day(), 24, 0, 0, 0, loc)\n\t} else {\n\t\tendDate, err = time.Parse(\"2006-01-02\", c.Query(\"end-date\"))\n\t\tendDate = endDate.Add((-9 + 24) * time.Hour).In(loc)\n\t}\n\ttitle = c.Query(\"title\")\n\n\t\/*\n\t\tDB processing\n\t*\/\n\tarticles := []models.Article{}\n\tsql := db.DB\n\n\t\/\/ filter\n\tsql = sql.Where(\"published_at BETWEEN ? AND ?\", startDate, endDate)\n\tsql = sql.Where(\"title LIKE ?\", \"%\"+title+\"%\")\n\n\t\/\/ sort\n\tsql, err = OrderArticles(sql, sort...)\n\n\tif err != nil {\n\t\tc.Status(http.StatusBadRequest)\n\t\terrorResp := ErrorResponse{Message: \"wrong sort param\"}\n\t\tencoder := json.NewEncoder(c.Writer)\n\t\terr = encoder.Encode(errorResp)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ find\n\tsql.Find(&articles)\n\tfmt.Println(articles)\n\t\/*\n\t\tselect output field\n\t*\/\n\tresults := SelectArticles(&articles, fields...)\n\n\t\/\/ set header\n\tc.Writer.Header().Set(\"Link\", \"<page=3>; rel=\\\"next\\\", <page=1>; rel=\\\"prev\\\", <page=5>; rel=\\\"last\\\"\")\n\tc.Status(http.StatusOK)\n\n\t\/\/ write response\n\tb, err := json.MarshalIndent(results, \"\", \" \")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = c.Writer.WriteString(string(b))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ ArticleShow show article details\nfunc ArticleShow(c *gin.Context) {\n\t\/\/ params\n\t\/\/ articlesID := c.Param(\"articles_id\")\n\tarticles := []models.Article{}\n\tdb.DB.Find(&articles).Order(\"created_at desc\")\n\n\t\/\/ set header\n\tc.Writer.Header().Set(\"Link\", \"<page=3>; rel=\\\"next\\\", <page=1>; rel=\\\"prev\\\", <page=5>; rel=\\\"last\\\"\")\n\tc.Status(http.StatusOK)\n\n\t\/\/ write response\n\tencoder := json.NewEncoder(c.Writer)\n\terr := encoder.Encode(articles)\n\tif err != nil {\n\t\tc.Status(http.StatusBadRequest)\n\t\terrorResp := ErrorResponse{Message: \"wrong sort param\"}\n\t\tencoder := json.NewEncoder(c.Writer)\n\t\terr = encoder.Encode(errorResp)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\n\/\/ SelectArticles extends gorm.DB.Select function\nfunc SelectArticles(articles *[]models.Article, fields ...string) (results []map[string]interface{}) {\n\tfor _, v := range *articles {\n\t\tif len(fields) > 1 || (len(fields) == 1 && fields[0] != \"\") {\n\t\t\tresults = append(results, (&v).SelectFields(fields...))\n\t\t} else {\n\t\t\tresults = append(results, (&v).SelectFields(\n\t\t\t\t\"id\",\n\t\t\t\t\"title\",\n\t\t\t\t\"news_site_id\",\n\t\t\t\t\"published_at\",\n\t\t\t\t\"url\",\n\t\t\t))\n\t\t}\n\t}\n\n\treturn results\n}\n\n\/\/ OrderArticles extends gorm.DB.Order function\nfunc OrderArticles(db *gorm.DB, sorts ...string) (*gorm.DB, error) {\n\tvar dbRet = db\n\tvar err error\n\n\tfor i, v := range sorts {\n\t\tif v == \"\" {\n\t\t\tif i == 0 { \/\/ \/articles \/articles?sort= \/articles?sort=,hoge\n\t\t\t\tdbRet = dbRet.Order(\"published_at desc\")\n\t\t\t} else { \/\/ \/articles?sort=hoge,\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else if string(v[0]) == \"-\" { \/\/ sort=-hoge\n\t\t\tdbRet = dbRet.Order(v[1:] + \" desc\")\n\t\t} else { \/\/ sort=hoge\n\t\t\tdbRet = dbRet.Order(v + \" asc\")\n\t\t}\n\t}\n\n\treturn dbRet, nil\n}\n<commit_msg>Update api.go<commit_after>package controllers\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/takonews\/takonews-api\/app\/models\"\n\t\"github.com\/takonews\/takonews-api\/db\"\n)\n\n\/\/ ArticleIndex show articles\n\/\/ Available Query Parameters\n\/\/ * sort\n\/\/ * fields\n\/\/ * filter\nfunc ArticleIndex(c *gin.Context) {\n\t\/\/ parameters\n\tvar sort []string\n\tvar fields []string\n\tvar startDate time.Time\n\tvar endDate time.Time\n\tvar title string\n\n\tsort = strings.Split(c.Query(\"sort\"), \",\")\n\tfields = strings.Split(c.Query(\"fields\"), \",\")\n\tloc, err := time.LoadLocation(\"Asia\/Tokyo\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tnow := time.Now().In(loc)\n\tif c.Query(\"start-date\") == \"\" { \/\/ default: today:00:00:00\n\t\tstartDate = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)\n\t} else {\n\t\tstartDate, err = time.Parse(\"2006-01-02\", c.Query(\"start-date\"))\n\t\tstartDate = startDate.Add(-9 * time.Hour).In(loc)\n\t}\n\tif c.Query(\"end-date\") == \"\" { \/\/ default: tomorrow:00:00:00\n\t\tendDate = time.Date(now.Year(), now.Month(), now.Day(), 24, 0, 0, 0, loc)\n\t} else {\n\t\tendDate, err = time.Parse(\"2006-01-02\", c.Query(\"end-date\"))\n\t\tendDate = endDate.Add((-9 + 24) * time.Hour).In(loc)\n\t}\n\ttitle = c.Query(\"title\")\n\n\t\/*\n\t\tDB processing\n\t*\/\n\tarticles := []models.Article{}\n\tsql := db.DB\n\n\t\/\/ filter\n\tsql = sql.Where(\"published_at BETWEEN ? AND ?\", startDate, endDate)\n\tsql = sql.Where(\"title LIKE ?\", \"%\"+title+\"%\")\n\n\t\/\/ sort\n\tsql, err = OrderArticles(sql, sort...)\n\n\tif err != nil {\n\t\tc.Status(http.StatusBadRequest)\n\t\terrorResp := ErrorResponse{Message: \"wrong sort param\"}\n\t\tencoder := json.NewEncoder(c.Writer)\n\t\terr = encoder.Encode(errorResp)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ find\n\tsql.Find(&articles)\n\n\t\/*\n\t\tselect output field\n\t*\/\n\tresults := SelectArticles(&articles, fields...)\n\n\t\/\/ set header\n\tc.Writer.Header().Set(\"Link\", \"<page=3>; rel=\\\"next\\\", <page=1>; rel=\\\"prev\\\", <page=5>; rel=\\\"last\\\"\")\n\tc.Status(http.StatusOK)\n\n\t\/\/ write response\n\tb, err := json.MarshalIndent(results, \"\", \" \")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = c.Writer.WriteString(string(b))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ ArticleShow show article details\nfunc ArticleShow(c *gin.Context) {\n\t\/\/ params\n\t\/\/ articlesID := c.Param(\"articles_id\")\n\tarticles := []models.Article{}\n\tdb.DB.Find(&articles).Order(\"created_at desc\")\n\n\t\/\/ set header\n\tc.Writer.Header().Set(\"Link\", \"<page=3>; rel=\\\"next\\\", <page=1>; rel=\\\"prev\\\", <page=5>; rel=\\\"last\\\"\")\n\tc.Status(http.StatusOK)\n\n\t\/\/ write response\n\tencoder := json.NewEncoder(c.Writer)\n\terr := encoder.Encode(articles)\n\tif err != nil {\n\t\tc.Status(http.StatusBadRequest)\n\t\terrorResp := ErrorResponse{Message: \"wrong sort param\"}\n\t\tencoder := json.NewEncoder(c.Writer)\n\t\terr = encoder.Encode(errorResp)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\n\/\/ SelectArticles extends gorm.DB.Select function\nfunc SelectArticles(articles *[]models.Article, fields ...string) (results []map[string]interface{}) {\n\tfor _, v := range *articles {\n\t\tif len(fields) > 1 || (len(fields) == 1 && fields[0] != \"\") {\n\t\t\tresults = append(results, (&v).SelectFields(fields...))\n\t\t} else {\n\t\t\tresults = append(results, (&v).SelectFields(\n\t\t\t\t\"id\",\n\t\t\t\t\"title\",\n\t\t\t\t\"news_site_id\",\n\t\t\t\t\"published_at\",\n\t\t\t\t\"url\",\n\t\t\t))\n\t\t}\n\t}\n\n\treturn results\n}\n\n\/\/ OrderArticles extends gorm.DB.Order function\nfunc OrderArticles(db *gorm.DB, sorts ...string) (*gorm.DB, error) {\n\tvar dbRet = db\n\tvar err error\n\n\tfor i, v := range sorts {\n\t\tif v == \"\" {\n\t\t\tif i == 0 { \/\/ \/articles \/articles?sort= \/articles?sort=,hoge\n\t\t\t\tdbRet = dbRet.Order(\"published_at desc\")\n\t\t\t} else { \/\/ \/articles?sort=hoge,\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else if string(v[0]) == \"-\" { \/\/ sort=-hoge\n\t\t\tdbRet = dbRet.Order(v[1:] + \" desc\")\n\t\t} else { \/\/ sort=hoge\n\t\t\tdbRet = dbRet.Order(v + \" asc\")\n\t\t}\n\t}\n\n\treturn dbRet, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package controllers\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/gojp\/nihongo\/app\/models\"\n\t\"github.com\/gojp\/nihongo\/app\/routes\"\n\t\"github.com\/jgraham909\/revmgo\"\n\t\"github.com\/mattbaird\/elastigo\/api\"\n\t\"github.com\/mattbaird\/elastigo\/core\"\n\t\"github.com\/robfig\/revel\"\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\t\"log\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype App struct {\n\t*revel.Controller\n\trevmgo.MongoController\n}\n\ntype Gloss struct {\n\tEnglish string\n\tTags    []string\n\tRelated []string\n\tCommon  bool\n}\n\ntype Highlight struct {\n\tFurigana string\n\tJapanese string\n\tRomaji   string\n\tEnglish  []string\n}\n\ntype Word struct {\n\tRomaji   string\n\tCommon   bool\n\tDialects []string\n\tFields   []string\n\tGlosses  []Gloss\n\tEnglish  []string\n\tFurigana string\n\tJapanese string\n\tTags     []string\n\tPos      []string\n}\n\nfunc highlight(query string, word Word) Word {\n\tre := regexp.MustCompile(query)\n\tqueryHighlighted := \"<strong>\" + query + \"<\/strong>\"\n\tword.Japanese = re.ReplaceAllString(word.Japanese, queryHighlighted)\n\tfor i, e := range word.English {\n\t\te = re.ReplaceAllString(e, queryHighlighted)\n\t\tword.English[i] = e\n\t}\n\treturn word\n}\n\nfunc search(query string) []Word {\n\tfmt.Println(\"Searching for... \", query)\n\tapi.Domain = \"localhost\"\n\tsearchJson := fmt.Sprintf(`{\"query\": {\"multi_match\": {\"query\": \"%s\", \"fields\": [\"japanese\", \"furigana\", \"romaji\", \"english\"]}}, \"highlight\": {\"fields\": {\"furigana\": {}, \"japanese\": {}, \"romaji\": {}, \"english\": {}}}}`, query)\n\tout, err := core.SearchRequest(true, \"edict\", \"entry\", searchJson, \"\", 0)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\thits := [][]byte{}\n\tfor _, hit := range out.Hits.Hits {\n\t\thits = append(hits, hit.Source)\n\t}\n\n\twordList := []Word{}\n\tfor _, hit := range hits {\n\t\tw := Word{}\n\t\terr := json.Unmarshal(hit, &w)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\twordList = append(wordList, highlight(query, w))\n\t}\n\treturn wordList\n}\n\nfunc (a App) Search(query string) revel.Result {\n\tif len(query) == 0 {\n\t\treturn a.Redirect(routes.App.Index())\n\t}\n\twordList := search(query)\n\treturn a.Render(wordList)\n}\n\nfunc (c App) Details(query string) revel.Result {\n\tif len(query) == 0 {\n\t\treturn c.Redirect(routes.App.Index())\n\t}\n\tif strings.Contains(query, \" \") {\n\t\treturn c.Redirect(routes.App.Details(strings.Replace(query, \" \", \"-\", -1)))\n\t}\n\tquery = strings.Replace(query, \"-\", \" \", -1)\n\twordList := search(query)\n\tpageTitle := query + \" in Japanese\"\n\n\t\/\/ log this call in mongo\n\tcollection := c.MongoSession.DB(\"greenbook\").C(\"hits\")\n\t_, err := collection.Upsert(bson.M{\"term\": query}, bson.M{\"$inc\": bson.M{\"count\": 1}})\n\tif err != nil {\n\t\t\/\/ mongo failed to log, but who cares\n\t}\n\n\tindex := mgo.Index{\n\t\tKey:        []string{\"count\"},\n\t\tUnique:     false,\n\t\tDropDups:   false,\n\t\tBackground: true,\n\t\tSparse:     true,\n\t}\n\tcollection.EnsureIndex(index)\n\n\treturn c.Render(wordList, query, pageTitle)\n}\n\nfunc (c App) SearchGet() revel.Result {\n\tif query, ok := c.Params.Values[\"q\"]; ok && len(query) > 0 {\n\t\treturn c.Redirect(routes.App.Details(query[0]))\n\t}\n\treturn c.Redirect(routes.App.Index())\n}\n\nfunc (c App) About() revel.Result {\n\treturn c.Render()\n}\n\nfunc (c App) Index() revel.Result {\n\n\t\/\/ get the popular searches\n\tcollection := c.MongoSession.DB(\"greenbook\").C(\"hits\")\n\tq := collection.Find(nil).Sort(\"-count\")\n\n\ttermList := []models.SearchTerm{}\n\titer := q.Limit(10).Iter()\n\titer.All(&termList)\n\n\treturn c.Render(termList)\n}\n<commit_msg>redefine highlight function to be a method that takes a pointer to a Word<commit_after>package controllers\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/gojp\/nihongo\/app\/models\"\n\t\"github.com\/gojp\/nihongo\/app\/routes\"\n\t\"github.com\/jgraham909\/revmgo\"\n\t\"github.com\/mattbaird\/elastigo\/api\"\n\t\"github.com\/mattbaird\/elastigo\/core\"\n\t\"github.com\/robfig\/revel\"\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\t\"log\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype App struct {\n\t*revel.Controller\n\trevmgo.MongoController\n}\n\ntype Gloss struct {\n\tEnglish string\n\tTags    []string\n\tRelated []string\n\tCommon  bool\n}\n\ntype Highlight struct {\n\tFurigana string\n\tJapanese string\n\tRomaji   string\n\tEnglish  []string\n}\n\ntype Word struct {\n\tRomaji   string\n\tCommon   bool\n\tDialects []string\n\tFields   []string\n\tGlosses  []Gloss\n\tEnglish  []string\n\tFurigana string\n\tJapanese string\n\tTags     []string\n\tPos      []string\n}\n\nfunc (w *Word) highlightQuery(query string) {\n\tre := regexp.MustCompile(query)\n\tqueryHighlighted := \"<strong>\" + query + \"<\/strong>\"\n\tw.Japanese = re.ReplaceAllString(w.Japanese, queryHighlighted)\n\tfor i, e := range w.English {\n\t\te = re.ReplaceAllString(e, queryHighlighted)\n\t\tw.English[i] = e\n\t}\n}\n\nfunc search(query string) []Word {\n\tfmt.Println(\"Searching for... \", query)\n\tapi.Domain = \"localhost\"\n\tsearchJson := fmt.Sprintf(`{\"query\": {\"multi_match\": {\"query\": \"%s\", \"fields\": [\"japanese\", \"furigana\", \"romaji\", \"english\"]}}, \"highlight\": {\"fields\": {\"furigana\": {}, \"japanese\": {}, \"romaji\": {}, \"english\": {}}}}`, query)\n\tout, err := core.SearchRequest(true, \"edict\", \"entry\", searchJson, \"\", 0)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\thits := [][]byte{}\n\tfor _, hit := range out.Hits.Hits {\n\t\thits = append(hits, hit.Source)\n\t}\n\n\twordList := []Word{}\n\tfor _, hit := range hits {\n\t\tw := Word{}\n\t\terr := json.Unmarshal(hit, &w)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\tw.highlightQuery(query)\n\t\twordList = append(wordList, w)\n\t}\n\treturn wordList\n}\n\nfunc (a App) Search(query string) revel.Result {\n\tif len(query) == 0 {\n\t\treturn a.Redirect(routes.App.Index())\n\t}\n\twordList := search(query)\n\treturn a.Render(wordList)\n}\n\nfunc (c App) Details(query string) revel.Result {\n\tif len(query) == 0 {\n\t\treturn c.Redirect(routes.App.Index())\n\t}\n\tif strings.Contains(query, \" \") {\n\t\treturn c.Redirect(routes.App.Details(strings.Replace(query, \" \", \"-\", -1)))\n\t}\n\tquery = strings.Replace(query, \"-\", \" \", -1)\n\twordList := search(query)\n\tpageTitle := query + \" in Japanese\"\n\n\t\/\/ log this call in mongo\n\tcollection := c.MongoSession.DB(\"greenbook\").C(\"hits\")\n\t_, err := collection.Upsert(bson.M{\"term\": query}, bson.M{\"$inc\": bson.M{\"count\": 1}})\n\tif err != nil {\n\t\t\/\/ mongo failed to log, but who cares\n\t}\n\n\tindex := mgo.Index{\n\t\tKey:        []string{\"count\"},\n\t\tUnique:     false,\n\t\tDropDups:   false,\n\t\tBackground: true,\n\t\tSparse:     true,\n\t}\n\tcollection.EnsureIndex(index)\n\n\treturn c.Render(wordList, query, pageTitle)\n}\n\nfunc (c App) SearchGet() revel.Result {\n\tif query, ok := c.Params.Values[\"q\"]; ok && len(query) > 0 {\n\t\treturn c.Redirect(routes.App.Details(query[0]))\n\t}\n\treturn c.Redirect(routes.App.Index())\n}\n\nfunc (c App) About() revel.Result {\n\treturn c.Render()\n}\n\nfunc (c App) Index() revel.Result {\n\n\t\/\/ get the popular searches\n\tcollection := c.MongoSession.DB(\"greenbook\").C(\"hits\")\n\tq := collection.Find(nil).Sort(\"-count\")\n\n\ttermList := []models.SearchTerm{}\n\titer := q.Limit(10).Iter()\n\titer.All(&termList)\n\n\treturn c.Render(termList)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\tconsulapi \"github.com\/hashicorp\/consul\/api\"\n\t\"time\"\n)\n\ntype ConsulClient struct {\n\tclient *consulapi.Client\n}\n\nfunc NewConsulClient() (ConsulClient, error) {\n\tclient, err := consulapi.NewClient(consulapi.DefaultConfig())\n\tif err != nil {\n\t\treturn ConsulClient{}, err\n\t}\n\treturn ConsulClient{client: client}, nil\n}\n\ntype ConsulAgent struct {\n\tagent *consulapi.Agent\n}\n\nfunc (r *ConsulClient) NewConsulAgent() ConsulAgent {\n\tagent := r.client.Agent()\n\treturn ConsulAgent{agent: agent}\n}\n\ntype Member struct {\n\tName string\n\tIP   string\n\tPort uint16\n}\n\ntype Members []Member\n\nfunc buildMember(name string, ip string, port uint16) Member {\n\treturn Member{Name: name, IP: ip, Port: port}\n}\n\nfunc (r *ConsulAgent) members() Members {\n\tlist := Members{}\n\tuse_wan := false\n\tmembers, _ := r.agent.Members(use_wan)\n\tfor _, member := range members {\n\t\tlist = append(list, buildMember(member.Name, member.Addr, member.Port))\n\t}\n\treturn list\n}\n\nfunc buildService(id string, name string, port int, ip string) consulapi.AgentServiceRegistration {\n\treturn consulapi.AgentServiceRegistration{ID: id, Name: name, Port: port, Address: ip}\n}\n\nfunc (r *ConsulAgent) registerService(id string, name string, port int, ip string) error {\n\tsrv := buildService(id, name, port, ip)\n\tif err := r.agent.ServiceRegister(&srv); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (r *ConsulAgent) deregisterService(id string) error {\n\tif err := r.agent.ServiceDeregister(id); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (r *ConsulAgent) services() (map[string]*consulapi.AgentService, error) {\n\tif services, err := r.agent.Services(); err != nil {\n\t\treturn services, err\n\t} else {\n\t\treturn services, nil\n\t}\n}\n\nfunc main() {\n\tclient, _ := NewConsulClient()\n\tagent := client.NewConsulAgent()\n\n\tfmt.Println(agent.members())\n\tfmt.Println(agent.services())\n\n\tagent.registerService(\"docker_id_here\", \"srv-search\", 1234, \"127.0.0.1\")\n\ttime.Sleep(20 * time.Second)\n\n\tagent.deregisterService(\"docker_id_here\")\n}\n<commit_msg>if code style<commit_after>package main\n\nimport (\n\t\"fmt\"\n\tconsulapi \"github.com\/hashicorp\/consul\/api\"\n\t\"time\"\n)\n\ntype ConsulClient struct {\n\tclient *consulapi.Client\n}\n\nfunc NewConsulClient() (ConsulClient, error) {\n\tclient, err := consulapi.NewClient(consulapi.DefaultConfig())\n\tif err != nil {\n\t\treturn ConsulClient{}, err\n\t}\n\treturn ConsulClient{client: client}, nil\n}\n\ntype ConsulAgent struct {\n\tagent *consulapi.Agent\n}\n\nfunc (r *ConsulClient) NewConsulAgent() ConsulAgent {\n\tagent := r.client.Agent()\n\treturn ConsulAgent{agent: agent}\n}\n\ntype Member struct {\n\tName string\n\tIP   string\n\tPort uint16\n}\n\ntype Members []Member\n\nfunc buildMember(name string, ip string, port uint16) Member {\n\treturn Member{Name: name, IP: ip, Port: port}\n}\n\nfunc (r *ConsulAgent) members() Members {\n\tlist := Members{}\n\tuse_wan := false\n\tmembers, _ := r.agent.Members(use_wan)\n\tfor _, member := range members {\n\t\tlist = append(list, buildMember(member.Name, member.Addr, member.Port))\n\t}\n\treturn list\n}\n\nfunc buildService(id string, name string, port int, ip string) consulapi.AgentServiceRegistration {\n\treturn consulapi.AgentServiceRegistration{ID: id, Name: name, Port: port, Address: ip}\n}\n\nfunc (r *ConsulAgent) registerService(id string, name string, port int, ip string) error {\n\tsrv := buildService(id, name, port, ip)\n\tif err := r.agent.ServiceRegister(&srv); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (r *ConsulAgent) deregisterService(id string) error {\n\tif err := r.agent.ServiceDeregister(id); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (r *ConsulAgent) services() (map[string]*consulapi.AgentService, error) {\n\tservices, err := r.agent.Services()\n\tif err != nil {\n\t\treturn services, err\n\t}\n\treturn services, nil\n}\n\nfunc main() {\n\tclient, _ := NewConsulClient()\n\tagent := client.NewConsulAgent()\n\n\tfmt.Println(agent.members())\n\tfmt.Println(agent.services())\n\n\tagent.registerService(\"docker_id_here\", \"srv-search\", 1234, \"127.0.0.1\")\n\ttime.Sleep(20 * time.Second)\n\n\tagent.deregisterService(\"docker_id_here\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package cuckoo\n\nimport (\n\t\"bytes\"\n\t\"hash\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"sync\"\n\n\t\"github.com\/spaolacci\/murmur3\"\n)\n\nconst (\n\tdefaultBucketSize        = 4\n\tdefaultTotalBuckets      = 250000\n\tdefaultMaxKicks          = 500\n\tdefaultFaultPositiveRate = 3\n\tseed                     = 59053\n)\n\n\/\/ emptyFingerprint represents an empty fingerprint\nvar emptyFingerprint []byte\n\n\/\/ fingerprint of the item\ntype fingerprint []byte\n\n\/\/ bucket with b fingerprints per bucket\ntype bucket []fingerprint\n\n\/\/ Filter is the cuckoo-filter\ntype Filter struct {\n\tcount             uint64\n\tbuckets           []bucket\n\tfalsePositiveRate float64\n\tbucketSize        uint64\n\ttotalBuckets      uint64\n\tfingerprintSize   int\n\thash              hash.Hash64\n\tmaxKicks          int\n\n\t\/\/ protects above fields\n\tmu *sync.RWMutex\n}\n\n\/\/ calculateFingerprintSize calculates the fingerprint size from\n\/\/ e - false positive percent and b - bucket size\nfunc calculateFingerprintSizeInBytes(e float64, b uint64) int {\n\treturn int(math.Ceil((math.Log(float64(100)\/e) + math.Log(2*float64(b))) \/ 8))\n}\n\n\/\/ hashOf returns the 64-bit hash\nfunc hashOf(x []byte, hash hash.Hash64) uint64 {\n\thash.Reset()\n\thash.Write(x)\n\treturn hash.Sum64()\n}\n\n\/\/ fingerprintOf returns the fingerprint of x with size using hash\nfunc fingerprintOf(x []byte, fpSize int, hash hash.Hash64) (fp fingerprint, fph uint64) {\n\thash.Reset()\n\thash.Write(x)\n\tfp = make(fingerprint, fpSize)\n\tcopy(fp, hash.Sum(nil))\n\treturn fp, hashOf(fp, hash)\n}\n\n\/\/ indicesOf returns the indices of item x using given hash\nfunc indicesOf(x []byte, fph, totalBuckets uint64, hash hash.Hash64) (i1, i2 uint64) {\n\thash.Reset()\n\thash.Write(x)\n\ti1 = hash.Sum64() % totalBuckets\n\ti2 = (i1 ^ fph) % totalBuckets\n\treturn i1, i2\n}\n\n\/\/ initBuckets initialises the buckets\nfunc initBuckets(totalBuckets uint64, bucketSize int) []bucket {\n\tbuckets := make([]bucket, totalBuckets, totalBuckets)\n\tfor i := range buckets {\n\t\tbuckets[i] = make([]fingerprint, bucketSize, bucketSize)\n\t}\n\n\treturn buckets\n}\n\n\/\/ StdFilter returns Standard Cuckoo-Filter\nfunc StdFilter() *Filter {\n\treturn &Filter{\n\t\tbuckets:           initBuckets(defaultTotalBuckets, defaultBucketSize),\n\t\tfalsePositiveRate: defaultFaultPositiveRate,\n\t\tbucketSize:        defaultBucketSize,\n\t\ttotalBuckets:      defaultTotalBuckets,\n\t\tfingerprintSize:   calculateFingerprintSizeInBytes(defaultFaultPositiveRate, defaultBucketSize),\n\t\thash:              murmur3.New64WithSeed(seed),\n\t\tmaxKicks:          defaultMaxKicks,\n\t\tmu:                &sync.RWMutex{},\n\t}\n}\n\n\/\/ deleteFrom deletes fingerprint from bucket if exists\nfunc deleteFrom(b bucket, fp fingerprint) bool {\n\tfor i := range b {\n\t\tif !bytes.Equal(b[i], fp) {\n\t\t\tcontinue\n\t\t}\n\n\t\tb[i] = emptyFingerprint\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ containsIn returns if the given fingerprint exists in bucket\nfunc containsIn(b bucket, fp fingerprint) bool {\n\tfor i := range b {\n\t\tif bytes.Equal(b[i], fp) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ addToBucket will add fp to the bucket i in filter\nfunc addToBucket(b bucket, fp fingerprint) bool {\n\tfor j := range b {\n\t\tif !bytes.Equal(b[j], emptyFingerprint) {\n\t\t\tcontinue\n\t\t}\n\n\t\tb[j] = fp\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ replaceItem replaces fingerprint from i and returns the alternate index for kicked fingerprint\nfunc replaceItem(f *Filter, i uint64, fp fingerprint) (j uint64, rfp fingerprint) {\n\tk := rand.Intn(len(f.buckets[i]))\n\trfp = f.buckets[i][k]\n\tf.buckets[i][k] = fp\n\trfph := hashOf(rfp, f.hash)\n\tj = (i ^ rfph) % f.totalBuckets\n\treturn j, rfp\n}\n\n\/\/ insert inserts the item into filter\nfunc insert(f *Filter, x []byte) (ok bool) {\n\tfp, fph := fingerprintOf(x, f.fingerprintSize, f.hash)\n\ti1, i2 := indicesOf(x, fph, f.totalBuckets, f.hash)\n\n\tdefer func() {\n\t\tif ok {\n\t\t\tf.count++\n\t\t}\n\t}()\n\n\tif addToBucket(f.buckets[i1], fp) || addToBucket(f.buckets[i2], fp) {\n\t\treturn true\n\t}\n\n\tis := []uint64{i1, i2}\n\ti1 = is[rand.Intn(len(is))]\n\tfor k := 0; k < f.maxKicks; k++ {\n\t\ti1, fp = replaceItem(f, i1, fp)\n\t\tif addToBucket(f.buckets[i1], fp) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ exists checks if the item x existence in filter\nfunc exists(f *Filter, x []byte) bool {\n\tfp, fph := fingerprintOf(x, f.fingerprintSize, f.hash)\n\ti1, i2 := indicesOf(x, fph, f.totalBuckets, f.hash)\n\n\tif containsIn(f.buckets[i1], fp) || containsIn(f.buckets[i2], fp) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ deleteItem deletes item if present from the filter\nfunc deleteItem(f *Filter, x []byte) (ok bool) {\n\tfp, fph := fingerprintOf(x, f.fingerprintSize, f.hash)\n\ti1, i2 := indicesOf(x, fph, f.totalBuckets, f.hash)\n\n\tdefer func() {\n\t\tif ok {\n\t\t\tf.count--\n\t\t}\n\t}()\n\n\tif deleteFrom(f.buckets[i1], fp) || deleteFrom(f.buckets[i2], fp) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ Insert inserts the item to the filter\n\/\/ returns error of filter is full\nfunc (f *Filter) Insert(x []byte) bool {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\treturn insert(f, x)\n}\n\n\/\/ InsertUnique inserts only unique items\nfunc (f *Filter) InsertUnique(x []byte) bool {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\treturn exists(f, x) || insert(f, x)\n}\n\n\/\/ Lookup says if the given items exists in filter\nfunc (f *Filter) Lookup(x []byte) bool {\n\tf.mu.RLock()\n\tdefer f.mu.RUnlock()\n\n\treturn exists(f, x)\n}\n\n\/\/ Delete deletes the item from the filter\nfunc (f *Filter) Delete(x []byte) bool {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\treturn deleteItem(f, x)\n}\n\n\/\/ Count returns total inserted items into filter\nfunc (f *Filter) Count() uint64 {\n\tf.mu.RLock()\n\tdefer f.mu.RUnlock()\n\n\treturn f.count\n}\n<commit_msg>rename exists to lookup<commit_after>package cuckoo\n\nimport (\n\t\"bytes\"\n\t\"hash\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"sync\"\n\n\t\"github.com\/spaolacci\/murmur3\"\n)\n\nconst (\n\tdefaultBucketSize        = 4\n\tdefaultTotalBuckets      = 250000\n\tdefaultMaxKicks          = 500\n\tdefaultFaultPositiveRate = 3\n\tseed                     = 59053\n)\n\n\/\/ emptyFingerprint represents an empty fingerprint\nvar emptyFingerprint []byte\n\n\/\/ fingerprint of the item\ntype fingerprint []byte\n\n\/\/ bucket with b fingerprints per bucket\ntype bucket []fingerprint\n\n\/\/ Filter is the cuckoo-filter\ntype Filter struct {\n\tcount             uint64\n\tbuckets           []bucket\n\tfalsePositiveRate float64\n\tbucketSize        uint64\n\ttotalBuckets      uint64\n\tfingerprintSize   int\n\thash              hash.Hash64\n\tmaxKicks          int\n\n\t\/\/ protects above fields\n\tmu *sync.RWMutex\n}\n\n\/\/ calculateFingerprintSize calculates the fingerprint size from\n\/\/ e - false positive percent and b - bucket size\nfunc calculateFingerprintSizeInBytes(e float64, b uint64) int {\n\treturn int(math.Ceil((math.Log(float64(100)\/e) + math.Log(2*float64(b))) \/ 8))\n}\n\n\/\/ hashOf returns the 64-bit hash\nfunc hashOf(x []byte, hash hash.Hash64) uint64 {\n\thash.Reset()\n\thash.Write(x)\n\treturn hash.Sum64()\n}\n\n\/\/ fingerprintOf returns the fingerprint of x with size using hash\nfunc fingerprintOf(x []byte, fpSize int, hash hash.Hash64) (fp fingerprint, fph uint64) {\n\thash.Reset()\n\thash.Write(x)\n\tfp = make(fingerprint, fpSize)\n\tcopy(fp, hash.Sum(nil))\n\treturn fp, hashOf(fp, hash)\n}\n\n\/\/ indicesOf returns the indices of item x using given hash\nfunc indicesOf(x []byte, fph, totalBuckets uint64, hash hash.Hash64) (i1, i2 uint64) {\n\thash.Reset()\n\thash.Write(x)\n\ti1 = hash.Sum64() % totalBuckets\n\ti2 = (i1 ^ fph) % totalBuckets\n\treturn i1, i2\n}\n\n\/\/ initBuckets initialises the buckets\nfunc initBuckets(totalBuckets uint64, bucketSize int) []bucket {\n\tbuckets := make([]bucket, totalBuckets, totalBuckets)\n\tfor i := range buckets {\n\t\tbuckets[i] = make([]fingerprint, bucketSize, bucketSize)\n\t}\n\n\treturn buckets\n}\n\n\/\/ StdFilter returns Standard Cuckoo-Filter\nfunc StdFilter() *Filter {\n\treturn &Filter{\n\t\tbuckets:           initBuckets(defaultTotalBuckets, defaultBucketSize),\n\t\tfalsePositiveRate: defaultFaultPositiveRate,\n\t\tbucketSize:        defaultBucketSize,\n\t\ttotalBuckets:      defaultTotalBuckets,\n\t\tfingerprintSize:   calculateFingerprintSizeInBytes(defaultFaultPositiveRate, defaultBucketSize),\n\t\thash:              murmur3.New64WithSeed(seed),\n\t\tmaxKicks:          defaultMaxKicks,\n\t\tmu:                &sync.RWMutex{},\n\t}\n}\n\n\/\/ deleteFrom deletes fingerprint from bucket if exists\nfunc deleteFrom(b bucket, fp fingerprint) bool {\n\tfor i := range b {\n\t\tif !bytes.Equal(b[i], fp) {\n\t\t\tcontinue\n\t\t}\n\n\t\tb[i] = emptyFingerprint\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ containsIn returns if the given fingerprint exists in bucket\nfunc containsIn(b bucket, fp fingerprint) bool {\n\tfor i := range b {\n\t\tif bytes.Equal(b[i], fp) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ addToBucket will add fp to the bucket i in filter\nfunc addToBucket(b bucket, fp fingerprint) bool {\n\tfor j := range b {\n\t\tif !bytes.Equal(b[j], emptyFingerprint) {\n\t\t\tcontinue\n\t\t}\n\n\t\tb[j] = fp\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ replaceItem replaces fingerprint from i and returns the alternate index for kicked fingerprint\nfunc replaceItem(f *Filter, i uint64, fp fingerprint) (j uint64, rfp fingerprint) {\n\tk := rand.Intn(len(f.buckets[i]))\n\trfp = f.buckets[i][k]\n\tf.buckets[i][k] = fp\n\trfph := hashOf(rfp, f.hash)\n\tj = (i ^ rfph) % f.totalBuckets\n\treturn j, rfp\n}\n\n\/\/ insert inserts the item into filter\nfunc insert(f *Filter, x []byte) (ok bool) {\n\tfp, fph := fingerprintOf(x, f.fingerprintSize, f.hash)\n\ti1, i2 := indicesOf(x, fph, f.totalBuckets, f.hash)\n\n\tdefer func() {\n\t\tif ok {\n\t\t\tf.count++\n\t\t}\n\t}()\n\n\tif addToBucket(f.buckets[i1], fp) || addToBucket(f.buckets[i2], fp) {\n\t\treturn true\n\t}\n\n\tis := []uint64{i1, i2}\n\ti1 = is[rand.Intn(len(is))]\n\tfor k := 0; k < f.maxKicks; k++ {\n\t\ti1, fp = replaceItem(f, i1, fp)\n\t\tif addToBucket(f.buckets[i1], fp) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ lookup checks if the item x existence in filter\nfunc lookup(f *Filter, x []byte) bool {\n\tfp, fph := fingerprintOf(x, f.fingerprintSize, f.hash)\n\ti1, i2 := indicesOf(x, fph, f.totalBuckets, f.hash)\n\n\tif containsIn(f.buckets[i1], fp) || containsIn(f.buckets[i2], fp) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ deleteItem deletes item if present from the filter\nfunc deleteItem(f *Filter, x []byte) (ok bool) {\n\tfp, fph := fingerprintOf(x, f.fingerprintSize, f.hash)\n\ti1, i2 := indicesOf(x, fph, f.totalBuckets, f.hash)\n\n\tdefer func() {\n\t\tif ok {\n\t\t\tf.count--\n\t\t}\n\t}()\n\n\tif deleteFrom(f.buckets[i1], fp) || deleteFrom(f.buckets[i2], fp) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ Insert inserts the item to the filter\n\/\/ returns error of filter is full\nfunc (f *Filter) Insert(x []byte) bool {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\treturn insert(f, x)\n}\n\n\/\/ InsertUnique inserts only unique items\nfunc (f *Filter) InsertUnique(x []byte) bool {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\treturn lookup(f, x) || insert(f, x)\n}\n\n\/\/ Lookup says if the given item exists in filter\nfunc (f *Filter) Lookup(x []byte) bool {\n\tf.mu.RLock()\n\tdefer f.mu.RUnlock()\n\n\treturn lookup(f, x)\n}\n\n\/\/ Delete deletes the item from the filter\nfunc (f *Filter) Delete(x []byte) bool {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\treturn deleteItem(f, x)\n}\n\n\/\/ Count returns total inserted items into filter\nfunc (f *Filter) Count() uint64 {\n\tf.mu.RLock()\n\tdefer f.mu.RUnlock()\n\n\treturn f.count\n}\n<|endoftext|>"}
{"text":"<commit_before>package gorethink\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"reflect\"\n\t\"sync\"\n\n\t\"github.com\/dancannon\/gorethink\/encoding\"\n\tp \"github.com\/dancannon\/gorethink\/ql2\"\n)\n\nvar (\n\terrCursorClosed = errors.New(\"connection closed, cannot read cursor\")\n)\n\nfunc newCursor(conn *Connection, cursorType string, token int64, term *Term, opts map[string]interface{}) *Cursor {\n\tif cursorType == \"\" {\n\t\tcursorType = \"Cursor\"\n\t}\n\n\tcursor := &Cursor{\n\t\tconn:       conn,\n\t\ttoken:      token,\n\t\tcursorType: cursorType,\n\t\tterm:       term,\n\t\topts:       opts,\n\t}\n\n\treturn cursor\n}\n\n\/\/ Cursor is the result of a query. Its cursor starts before the first row\n\/\/ of the result set. A Cursor is not thread safe and should only be accessed\n\/\/ by a single goroutine at any given time. Use Next to advance through the\n\/\/ rows:\n\/\/\n\/\/     cursor, err := query.Run(session)\n\/\/     ...\n\/\/     defer cursor.Close()\n\/\/\n\/\/     var response interface{}\n\/\/     for cursor.Next(&response) {\n\/\/         ...\n\/\/     }\n\/\/     err = cursor.Err() \/\/ get any error encountered during iteration\n\/\/     ...\ntype Cursor struct {\n\treleaseConn func() error\n\n\tconn       *Connection\n\ttoken      int64\n\tcursorType string\n\tterm       *Term\n\topts       map[string]interface{}\n\n\tmu        sync.RWMutex\n\tlastErr   error\n\tfetching  bool\n\tclosed    bool\n\tfinished  bool\n\tisAtom    bool\n\tbuffer    queue\n\tresponses queue\n\tprofile   interface{}\n}\n\n\/\/ Profile returns the information returned from the query profiler.\nfunc (c *Cursor) Profile() interface{} {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\treturn c.profile\n}\n\n\/\/ Type returns the cursor type (by default \"Cursor\")\nfunc (c *Cursor) Type() string {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\treturn c.cursorType\n}\n\n\/\/ Err returns nil if no errors happened during iteration, or the actual\n\/\/ error otherwise.\nfunc (c *Cursor) Err() error {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\treturn c.lastErr\n}\n\n\/\/ Close closes the cursor, preventing further enumeration. If the end is\n\/\/ encountered, the cursor is closed automatically. Close is idempotent.\nfunc (c *Cursor) Close() error {\n\tvar err error\n\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\t\/\/ If cursor is already closed return immediately\n\tclosed := c.closed\n\tif closed {\n\t\treturn nil\n\t}\n\n\t\/\/ Get connection and check its valid, don't need to lock as this is only\n\t\/\/ set when the cursor is created\n\tconn := c.conn\n\tif conn == nil {\n\t\treturn nil\n\t}\n\tif conn.Conn == nil {\n\t\treturn nil\n\t}\n\n\t\/\/ Stop any unfinished queries\n\tif !c.finished {\n\t\tq := Query{\n\t\t\tType:  p.Query_STOP,\n\t\t\tToken: c.token,\n\t\t\tOpts: map[string]interface{}{\n\t\t\t\t\"noreply\": true,\n\t\t\t},\n\t\t}\n\n\t\t_, _, err = conn.Query(q)\n\t}\n\n\tif c.releaseConn != nil {\n\t\tif err := c.releaseConn(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tc.closed = true\n\tc.conn = nil\n\tc.buffer.elems = nil\n\tc.responses.elems = nil\n\n\treturn err\n}\n\n\/\/ Next retrieves the next document from the result set, blocking if necessary.\n\/\/ This method will also automatically retrieve another batch of documents from\n\/\/ the server when the current one is exhausted, or before that in background\n\/\/ if possible.\n\/\/\n\/\/ Next returns true if a document was successfully unmarshalled onto result,\n\/\/ and false at the end of the result set or if an error happened.\n\/\/ When Next returns false, the Err method should be called to verify if\n\/\/ there was an error during iteration.\n\/\/\n\/\/ Also note that you are able to reuse the same variable multiple times as\n\/\/ `Next` zeroes the value before scanning in the result.\nfunc (c *Cursor) Next(dest interface{}) bool {\n\tc.mu.Lock()\n\tif c.closed {\n\t\tc.mu.Unlock()\n\t\treturn false\n\t}\n\n\thasMore, err := c.loadNextLocked(dest)\n\tif c.handleErrorLocked(err) != nil {\n\t\tc.mu.Unlock()\n\t\tc.Close()\n\t\treturn false\n\t}\n\tc.mu.Unlock()\n\n\tif !hasMore {\n\t\tc.Close()\n\t}\n\n\treturn hasMore\n}\n\nfunc (c *Cursor) loadNextLocked(dest interface{}) (bool, error) {\n\tfor {\n\t\tif c.lastErr != nil {\n\t\t\treturn false, c.lastErr\n\t\t}\n\n\t\t\/\/ Check if response is closed\/finished\n\t\tif c.buffer.Len() == 0 && c.responses.Len() == 0 && c.closed {\n\t\t\treturn false, errCursorClosed\n\t\t}\n\n\t\tif c.buffer.Len() == 0 && c.responses.Len() == 0 && !c.finished {\n\t\t\tc.mu.Unlock()\n\t\t\terr := c.fetchMore()\n\t\t\tc.mu.Lock()\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\n\t\tif c.buffer.Len() == 0 && c.responses.Len() == 0 && c.finished {\n\t\t\treturn false, nil\n\t\t}\n\n\t\tif c.buffer.Len() == 0 && c.responses.Len() > 0 {\n\t\t\tif response, ok := c.responses.Pop().(json.RawMessage); ok {\n\t\t\t\tvar value interface{}\n\t\t\t\tdecoder := json.NewDecoder(bytes.NewBuffer(response))\n\t\t\t\tif c.conn.opts.UseJSONNumber {\n\t\t\t\t\tdecoder.UseNumber()\n\t\t\t\t}\n\t\t\t\terr := decoder.Decode(&value)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\n\t\t\t\tvalue, err = recursivelyConvertPseudotype(value, c.opts)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\n\t\t\t\t\/\/ If response is an ATOM then try and convert to an array\n\t\t\t\tif data, ok := value.([]interface{}); ok && c.isAtom {\n\t\t\t\t\tfor _, v := range data {\n\t\t\t\t\t\tc.buffer.Push(v)\n\t\t\t\t\t}\n\t\t\t\t} else if value == nil {\n\t\t\t\t\tc.buffer.Push(nil)\n\t\t\t\t} else {\n\t\t\t\t\tc.buffer.Push(value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif c.buffer.Len() > 0 {\n\t\t\tdata := c.buffer.Pop()\n\n\t\t\terr := encoding.Decode(dest, data)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\treturn true, nil\n\t\t}\n\t}\n}\n\n\/\/ All retrieves all documents from the result set into the provided slice\n\/\/ and closes the cursor.\n\/\/\n\/\/ The result argument must necessarily be the address for a slice. The slice\n\/\/ may be nil or previously allocated.\n\/\/\n\/\/ Also note that you are able to reuse the same variable multiple times as\n\/\/ `All` zeroes the value before scanning in the result. It also attempts\n\/\/ to reuse the existing slice without allocating any more space by either\n\/\/ resizing or returning a selection of the slice if necessary.\nfunc (c *Cursor) All(result interface{}) error {\n\tresultv := reflect.ValueOf(result)\n\tif resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Slice {\n\t\tpanic(\"result argument must be a slice address\")\n\t}\n\tslicev := resultv.Elem()\n\tslicev = slicev.Slice(0, slicev.Cap())\n\telemt := slicev.Type().Elem()\n\ti := 0\n\tfor {\n\t\tif slicev.Len() == i {\n\t\t\telemp := reflect.New(elemt)\n\t\t\tif !c.Next(elemp.Interface()) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tslicev = reflect.Append(slicev, elemp.Elem())\n\t\t\tslicev = slicev.Slice(0, slicev.Cap())\n\t\t} else {\n\t\t\tif !c.Next(slicev.Index(i).Addr().Interface()) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ti++\n\t}\n\tresultv.Elem().Set(slicev.Slice(0, i))\n\n\tif err := c.Err(); err != nil {\n\t\tc.Close()\n\t\treturn err\n\t}\n\n\tif err := c.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ One retrieves a single document from the result set into the provided\n\/\/ slice and closes the cursor.\n\/\/\n\/\/ Also note that you are able to reuse the same variable multiple times as\n\/\/ `One` zeroes the value before scanning in the result.\nfunc (c *Cursor) One(result interface{}) error {\n\tif c.IsNil() {\n\t\tc.Close()\n\t\treturn ErrEmptyResult\n\t}\n\n\thasResult := c.Next(result)\n\n\tif err := c.Err(); err != nil {\n\t\tc.Close()\n\t\treturn err\n\t}\n\n\tif err := c.Close(); err != nil {\n\t\treturn err\n\t}\n\n\tif !hasResult {\n\t\treturn ErrEmptyResult\n\t}\n\n\treturn nil\n}\n\n\/\/ Listen listens for rows from the database and sends the result onto the given\n\/\/ channel. The type that the row is scanned into is determined by the element\n\/\/ type of the channel.\n\/\/\n\/\/ Also note that this function returns immediately.\n\/\/\n\/\/     cursor, err := r.Expr([]int{1,2,3}).Run(session)\n\/\/     if err != nil {\n\/\/         panic(err)\n\/\/     }\n\/\/\n\/\/     ch := make(chan int)\n\/\/     cursor.Listen(ch)\n\/\/     <- ch \/\/ 1\n\/\/     <- ch \/\/ 2\n\/\/     <- ch \/\/ 3\nfunc (c *Cursor) Listen(channel interface{}) {\n\tgo func() {\n\t\tchannelv := reflect.ValueOf(channel)\n\t\tif channelv.Kind() != reflect.Chan {\n\t\t\tpanic(\"input argument must be a channel\")\n\t\t}\n\t\telemt := channelv.Type().Elem()\n\t\tfor {\n\t\t\telemp := reflect.New(elemt)\n\t\t\tif !c.Next(elemp.Interface()) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tchannelv.Send(elemp.Elem())\n\t\t}\n\n\t\tc.Close()\n\t\tchannelv.Close()\n\t}()\n}\n\n\/\/ IsNil tests if the current row is nil.\nfunc (c *Cursor) IsNil() bool {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\tif c.buffer.Len() > 0 {\n\t\tbufferedItem := c.buffer.Peek()\n\t\tif bufferedItem == nil {\n\t\t\treturn true\n\t\t}\n\n\t\treturn false\n\t}\n\n\tif c.responses.Len() > 0 {\n\t\tresponse := c.responses.Peek()\n\t\tif response == nil {\n\t\t\treturn true\n\t\t}\n\n\t\tif response, ok := response.(json.RawMessage); ok {\n\t\t\tif string(response) == \"null\" {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ fetchMore fetches more rows from the database.\n\/\/\n\/\/ If wait is true then it will wait for the database to reply otherwise it\n\/\/ will return after sending the continue query.\nfunc (c *Cursor) fetchMore() error {\n\tvar err error\n\n\tc.mu.Lock()\n\tfetching := c.fetching\n\tclosed := c.closed\n\n\tif !fetching {\n\t\tc.fetching = true\n\t\tc.mu.Unlock()\n\n\t\tif closed {\n\t\t\treturn errCursorClosed\n\t\t}\n\n\t\tq := Query{\n\t\t\tType:  p.Query_CONTINUE,\n\t\t\tToken: c.token,\n\t\t}\n\n\t\t_, _, err = c.conn.Query(q)\n\t} else {\n\t\tc.mu.Unlock()\n\t}\n\n\treturn err\n}\n\n\/\/ handleError sets the value of lastErr to err if lastErr is not yet set.\nfunc (c *Cursor) handleError(err error) error {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\treturn c.handleErrorLocked(err)\n}\n\nfunc (c *Cursor) handleErrorLocked(err error) error {\n\tif c.lastErr == nil {\n\t\tc.lastErr = err\n\t}\n\n\treturn c.lastErr\n}\n\n\/\/ extend adds the result of a continue query to the cursor.\nfunc (c *Cursor) extend(response *Response) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.extendLocked(response)\n}\n\nfunc (c *Cursor) extendLocked(response *Response) {\n\tfor _, response := range response.Responses {\n\t\tc.responses.Push(response)\n\t}\n\n\tc.finished = response.Type != p.Response_SUCCESS_PARTIAL\n\tc.fetching = false\n\tc.isAtom = response.Type == p.Response_SUCCESS_ATOM\n\n\tputResponse(response)\n}\n\n\/\/ Queue structure used for storing responses\n\ntype queue struct {\n\telems               []interface{}\n\tnelems, popi, pushi int\n}\n\nfunc (q *queue) Len() int {\n\tif len(q.elems) == 0 {\n\t\treturn 0\n\t}\n\n\treturn q.nelems\n}\nfunc (q *queue) Push(elem interface{}) {\n\tif q.nelems == len(q.elems) {\n\t\tq.expand()\n\t}\n\tq.elems[q.pushi] = elem\n\tq.nelems++\n\tq.pushi = (q.pushi + 1) % len(q.elems)\n}\nfunc (q *queue) Pop() (elem interface{}) {\n\tif q.nelems == 0 {\n\t\treturn nil\n\t}\n\telem = q.elems[q.popi]\n\tq.elems[q.popi] = nil \/\/ Help GC.\n\tq.nelems--\n\tq.popi = (q.popi + 1) % len(q.elems)\n\treturn elem\n}\nfunc (q *queue) Peek() (elem interface{}) {\n\tif q.nelems == 0 {\n\t\treturn nil\n\t}\n\treturn q.elems[q.popi]\n}\nfunc (q *queue) expand() {\n\tcurcap := len(q.elems)\n\tvar newcap int\n\tif curcap == 0 {\n\t\tnewcap = 8\n\t} else if curcap < 1024 {\n\t\tnewcap = curcap * 2\n\t} else {\n\t\tnewcap = curcap + (curcap \/ 4)\n\t}\n\telems := make([]interface{}, newcap)\n\tif q.popi == 0 {\n\t\tcopy(elems, q.elems)\n\t\tq.pushi = curcap\n\t} else {\n\t\tnewpopi := newcap - (curcap - q.popi)\n\t\tcopy(elems, q.elems[:q.popi])\n\t\tcopy(elems[newpopi:], q.elems[q.popi:])\n\t\tq.popi = newpopi\n\t}\n\tfor i := range q.elems {\n\t\tq.elems[i] = nil \/\/ Help GC.\n\t}\n\tq.elems = elems\n}\n<commit_msg>Remove panicking queue data structure<commit_after>package gorethink\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"reflect\"\n\t\"sync\"\n\n\t\"github.com\/dancannon\/gorethink\/encoding\"\n\tp \"github.com\/dancannon\/gorethink\/ql2\"\n)\n\nvar (\n\terrCursorClosed = errors.New(\"connection closed, cannot read cursor\")\n)\n\nfunc newCursor(conn *Connection, cursorType string, token int64, term *Term, opts map[string]interface{}) *Cursor {\n\tif cursorType == \"\" {\n\t\tcursorType = \"Cursor\"\n\t}\n\n\tcursor := &Cursor{\n\t\tconn:       conn,\n\t\ttoken:      token,\n\t\tcursorType: cursorType,\n\t\tterm:       term,\n\t\topts:       opts,\n\t\tbuffer:     make([]interface{}, 0),\n\t\tresponses:  make([]json.RawMessage, 0),\n\t}\n\n\treturn cursor\n}\n\n\/\/ Cursor is the result of a query. Its cursor starts before the first row\n\/\/ of the result set. A Cursor is not thread safe and should only be accessed\n\/\/ by a single goroutine at any given time. Use Next to advance through the\n\/\/ rows:\n\/\/\n\/\/     cursor, err := query.Run(session)\n\/\/     ...\n\/\/     defer cursor.Close()\n\/\/\n\/\/     var response interface{}\n\/\/     for cursor.Next(&response) {\n\/\/         ...\n\/\/     }\n\/\/     err = cursor.Err() \/\/ get any error encountered during iteration\n\/\/     ...\ntype Cursor struct {\n\treleaseConn func() error\n\n\tconn       *Connection\n\ttoken      int64\n\tcursorType string\n\tterm       *Term\n\topts       map[string]interface{}\n\n\tmu        sync.RWMutex\n\tlastErr   error\n\tfetching  bool\n\tclosed    bool\n\tfinished  bool\n\tisAtom    bool\n\tbuffer    []interface{}\n\tresponses []json.RawMessage\n\tprofile   interface{}\n}\n\n\/\/ Profile returns the information returned from the query profiler.\nfunc (c *Cursor) Profile() interface{} {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\treturn c.profile\n}\n\n\/\/ Type returns the cursor type (by default \"Cursor\")\nfunc (c *Cursor) Type() string {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\treturn c.cursorType\n}\n\n\/\/ Err returns nil if no errors happened during iteration, or the actual\n\/\/ error otherwise.\nfunc (c *Cursor) Err() error {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\treturn c.lastErr\n}\n\n\/\/ Close closes the cursor, preventing further enumeration. If the end is\n\/\/ encountered, the cursor is closed automatically. Close is idempotent.\nfunc (c *Cursor) Close() error {\n\tvar err error\n\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\t\/\/ If cursor is already closed return immediately\n\tclosed := c.closed\n\tif closed {\n\t\treturn nil\n\t}\n\n\t\/\/ Get connection and check its valid, don't need to lock as this is only\n\t\/\/ set when the cursor is created\n\tconn := c.conn\n\tif conn == nil {\n\t\treturn nil\n\t}\n\tif conn.Conn == nil {\n\t\treturn nil\n\t}\n\n\t\/\/ Stop any unfinished queries\n\tif !c.finished {\n\t\tq := Query{\n\t\t\tType:  p.Query_STOP,\n\t\t\tToken: c.token,\n\t\t\tOpts: map[string]interface{}{\n\t\t\t\t\"noreply\": true,\n\t\t\t},\n\t\t}\n\n\t\t_, _, err = conn.Query(q)\n\t}\n\n\tif c.releaseConn != nil {\n\t\tif err := c.releaseConn(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tc.closed = true\n\tc.conn = nil\n\tc.buffer = nil\n\tc.responses = nil\n\n\treturn err\n}\n\n\/\/ Next retrieves the next document from the result set, blocking if necessary.\n\/\/ This method will also automatically retrieve another batch of documents from\n\/\/ the server when the current one is exhausted, or before that in background\n\/\/ if possible.\n\/\/\n\/\/ Next returns true if a document was successfully unmarshalled onto result,\n\/\/ and false at the end of the result set or if an error happened.\n\/\/ When Next returns false, the Err method should be called to verify if\n\/\/ there was an error during iteration.\n\/\/\n\/\/ Also note that you are able to reuse the same variable multiple times as\n\/\/ `Next` zeroes the value before scanning in the result.\nfunc (c *Cursor) Next(dest interface{}) bool {\n\tc.mu.Lock()\n\tif c.closed {\n\t\tc.mu.Unlock()\n\t\treturn false\n\t}\n\n\thasMore, err := c.loadNextLocked(dest)\n\tif c.handleErrorLocked(err) != nil {\n\t\tc.mu.Unlock()\n\t\tc.Close()\n\t\treturn false\n\t}\n\tc.mu.Unlock()\n\n\tif !hasMore {\n\t\tc.Close()\n\t}\n\n\treturn hasMore\n}\n\nfunc (c *Cursor) loadNextLocked(dest interface{}) (bool, error) {\n\tfor {\n\t\tif c.lastErr != nil {\n\t\t\treturn false, c.lastErr\n\t\t}\n\n\t\t\/\/ Check if response is closed\/finished\n\t\tif len(c.buffer) == 0 && len(c.responses) == 0 && c.closed {\n\t\t\treturn false, errCursorClosed\n\t\t}\n\n\t\tif len(c.buffer) == 0 && len(c.responses) == 0 && !c.finished {\n\t\t\tc.mu.Unlock()\n\t\t\terr := c.fetchMore()\n\t\t\tc.mu.Lock()\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\n\t\tif len(c.buffer) == 0 && len(c.responses) == 0 && c.finished {\n\t\t\treturn false, nil\n\t\t}\n\n\t\tif len(c.buffer) == 0 && len(c.responses) > 0 {\n\t\t\tvar response json.RawMessage\n\t\t\tresponse, c.responses = c.responses[len(c.responses)-1], c.responses[:len(c.responses)-1]\n\n\t\t\tvar value interface{}\n\t\t\tdecoder := json.NewDecoder(bytes.NewBuffer(response))\n\t\t\tif c.conn.opts.UseJSONNumber {\n\t\t\t\tdecoder.UseNumber()\n\t\t\t}\n\t\t\terr := decoder.Decode(&value)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tvalue, err = recursivelyConvertPseudotype(value, c.opts)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\t\/\/ If response is an ATOM then try and convert to an array\n\t\t\tif data, ok := value.([]interface{}); ok && c.isAtom {\n\t\t\t\tfor _, v := range data {\n\t\t\t\t\tc.buffer = append(c.buffer, v)\n\t\t\t\t}\n\t\t\t} else if value == nil {\n\t\t\t\tc.buffer = append(c.buffer, nil)\n\t\t\t} else {\n\t\t\t\tc.buffer = append(c.buffer, value)\n\t\t\t}\n\t\t}\n\n\t\tif len(c.buffer) > 0 {\n\t\t\tvar data interface{}\n\t\t\tdata, c.buffer = c.buffer[len(c.buffer)-1], c.buffer[:len(c.buffer)-1]\n\n\t\t\terr := encoding.Decode(dest, data)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\treturn true, nil\n\t\t}\n\t}\n}\n\n\/\/ All retrieves all documents from the result set into the provided slice\n\/\/ and closes the cursor.\n\/\/\n\/\/ The result argument must necessarily be the address for a slice. The slice\n\/\/ may be nil or previously allocated.\n\/\/\n\/\/ Also note that you are able to reuse the same variable multiple times as\n\/\/ `All` zeroes the value before scanning in the result. It also attempts\n\/\/ to reuse the existing slice without allocating any more space by either\n\/\/ resizing or returning a selection of the slice if necessary.\nfunc (c *Cursor) All(result interface{}) error {\n\tresultv := reflect.ValueOf(result)\n\tif resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Slice {\n\t\tpanic(\"result argument must be a slice address\")\n\t}\n\tslicev := resultv.Elem()\n\tslicev = slicev.Slice(0, slicev.Cap())\n\telemt := slicev.Type().Elem()\n\ti := 0\n\tfor {\n\t\tif slicev.Len() == i {\n\t\t\telemp := reflect.New(elemt)\n\t\t\tif !c.Next(elemp.Interface()) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tslicev = reflect.Append(slicev, elemp.Elem())\n\t\t\tslicev = slicev.Slice(0, slicev.Cap())\n\t\t} else {\n\t\t\tif !c.Next(slicev.Index(i).Addr().Interface()) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\ti++\n\t}\n\tresultv.Elem().Set(slicev.Slice(0, i))\n\n\tif err := c.Err(); err != nil {\n\t\tc.Close()\n\t\treturn err\n\t}\n\n\tif err := c.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ One retrieves a single document from the result set into the provided\n\/\/ slice and closes the cursor.\n\/\/\n\/\/ Also note that you are able to reuse the same variable multiple times as\n\/\/ `One` zeroes the value before scanning in the result.\nfunc (c *Cursor) One(result interface{}) error {\n\tif c.IsNil() {\n\t\tc.Close()\n\t\treturn ErrEmptyResult\n\t}\n\n\thasResult := c.Next(result)\n\n\tif err := c.Err(); err != nil {\n\t\tc.Close()\n\t\treturn err\n\t}\n\n\tif err := c.Close(); err != nil {\n\t\treturn err\n\t}\n\n\tif !hasResult {\n\t\treturn ErrEmptyResult\n\t}\n\n\treturn nil\n}\n\n\/\/ Listen listens for rows from the database and sends the result onto the given\n\/\/ channel. The type that the row is scanned into is determined by the element\n\/\/ type of the channel.\n\/\/\n\/\/ Also note that this function returns immediately.\n\/\/\n\/\/     cursor, err := r.Expr([]int{1,2,3}).Run(session)\n\/\/     if err != nil {\n\/\/         panic(err)\n\/\/     }\n\/\/\n\/\/     ch := make(chan int)\n\/\/     cursor.Listen(ch)\n\/\/     <- ch \/\/ 1\n\/\/     <- ch \/\/ 2\n\/\/     <- ch \/\/ 3\nfunc (c *Cursor) Listen(channel interface{}) {\n\tgo func() {\n\t\tchannelv := reflect.ValueOf(channel)\n\t\tif channelv.Kind() != reflect.Chan {\n\t\t\tpanic(\"input argument must be a channel\")\n\t\t}\n\t\telemt := channelv.Type().Elem()\n\t\tfor {\n\t\t\telemp := reflect.New(elemt)\n\t\t\tif !c.Next(elemp.Interface()) {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tchannelv.Send(elemp.Elem())\n\t\t}\n\n\t\tc.Close()\n\t\tchannelv.Close()\n\t}()\n}\n\n\/\/ IsNil tests if the current row is nil.\nfunc (c *Cursor) IsNil() bool {\n\tc.mu.RLock()\n\tdefer c.mu.RUnlock()\n\n\tif len(c.buffer) > 0 {\n\t\tbufferedItem := c.buffer[len(c.buffer)-1]\n\t\tif bufferedItem == nil {\n\t\t\treturn true\n\t\t}\n\n\t\treturn false\n\t}\n\n\tif len(c.responses) > 0 {\n\t\tresponse := c.responses[len(c.responses)-1]\n\t\tif response == nil {\n\t\t\treturn true\n\t\t}\n\n\t\tif string(response) == \"null\" {\n\t\t\treturn true\n\t\t}\n\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ fetchMore fetches more rows from the database.\n\/\/\n\/\/ If wait is true then it will wait for the database to reply otherwise it\n\/\/ will return after sending the continue query.\nfunc (c *Cursor) fetchMore() error {\n\tvar err error\n\n\tc.mu.Lock()\n\tfetching := c.fetching\n\tclosed := c.closed\n\n\tif !fetching {\n\t\tc.fetching = true\n\t\tc.mu.Unlock()\n\n\t\tif closed {\n\t\t\treturn errCursorClosed\n\t\t}\n\n\t\tq := Query{\n\t\t\tType:  p.Query_CONTINUE,\n\t\t\tToken: c.token,\n\t\t}\n\n\t\t_, _, err = c.conn.Query(q)\n\t} else {\n\t\tc.mu.Unlock()\n\t}\n\n\treturn err\n}\n\n\/\/ handleError sets the value of lastErr to err if lastErr is not yet set.\nfunc (c *Cursor) handleError(err error) error {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\treturn c.handleErrorLocked(err)\n}\n\nfunc (c *Cursor) handleErrorLocked(err error) error {\n\tif c.lastErr == nil {\n\t\tc.lastErr = err\n\t}\n\n\treturn c.lastErr\n}\n\n\/\/ extend adds the result of a continue query to the cursor.\nfunc (c *Cursor) extend(response *Response) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\tc.extendLocked(response)\n}\n\nfunc (c *Cursor) extendLocked(response *Response) {\n\tfor _, response := range response.Responses {\n\t\tc.responses = append(c.responses, response)\n\t}\n\n\tc.finished = response.Type != p.Response_SUCCESS_PARTIAL\n\tc.fetching = false\n\tc.isAtom = response.Type == p.Response_SUCCESS_ATOM\n\n\tputResponse(response)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nPackage daemon 0.8.7 for use with Go (golang) services.\n\nPackage daemon provides primitives for daemonization of golang services.\nThis package is not provide implementation of user daemon,\naccordingly must have root rights to install\/remove service.\nIn the current implementation is only supported Linux and Mac Os X daemon.\n\nExample:\n\n\t\/\/ Example of a daemon with echo service\n\tpackage main\n\n\timport (\n\t\t\"fmt\"\n\t\t\"log\"\n\t\t\"net\"\n\t\t\"os\"\n\t\t\"os\/signal\"\n\t\t\"syscall\"\n\n\t\t\"github.com\/takama\/daemon\"\n\t)\n\n\tconst (\n\n\t\t\/\/ name of the service\n\t\tname        = \"myservice\"\n\t\tdescription = \"My Echo Service\"\n\n\t\t\/\/ port which daemon should be listen\n\t\tport = \":9977\"\n\t)\n\n  \/\/ dependencies that are NOT required by the service, but might be used\n  var dependencies = []string{\"dummy.service\"}\n\n\tvar stdlog, errlog *log.Logger\n\n\t\/\/ Service has embedded daemon\n\ttype Service struct {\n\t\tdaemon.Daemon\n\t}\n\n\t\/\/ Manage by daemon commands or run the daemon\n\tfunc (service *Service) Manage() (string, error) {\n\n\t\tusage := \"Usage: myservice install | remove | start | stop | status\"\n\n\t\t\/\/ if received any kind of command, do it\n\t\tif len(os.Args) > 1 {\n\t\t\tcommand := os.Args[1]\n\t\t\tswitch command {\n\t\t\tcase \"install\":\n\t\t\t\treturn service.Install()\n\t\t\tcase \"remove\":\n\t\t\t\treturn service.Remove()\n\t\t\tcase \"start\":\n\t\t\t\treturn service.Start()\n\t\t\tcase \"stop\":\n\t\t\t\treturn service.Stop()\n\t\t\tcase \"status\":\n\t\t\t\treturn service.Status()\n\t\t\tdefault:\n\t\t\t\treturn usage, nil\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Do something, call your goroutines, etc\n\n\t\t\/\/ Set up channel on which to send signal notifications.\n\t\t\/\/ We must use a buffered channel or risk missing the signal\n\t\t\/\/ if we're not ready to receive when the signal is sent.\n\t\tinterrupt := make(chan os.Signal, 1)\n\t\tsignal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM)\n\n\t\t\/\/ Set up listener for defined host and port\n\t\tlistener, err := net.Listen(\"tcp\", port)\n\t\tif err != nil {\n\t\t\treturn \"Possibly was a problem with the port binding\", err\n\t\t}\n\n\t\t\/\/ set up channel on which to send accepted connections\n\t\tlisten := make(chan net.Conn, 100)\n\t\tgo acceptConnection(listener, listen)\n\n\t\t\/\/ loop work cycle with accept connections or interrupt\n\t\t\/\/ by system signal\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase conn := <-listen:\n\t\t\t\tgo handleClient(conn)\n\t\t\tcase killSignal := <-interrupt:\n\t\t\t\tstdlog.Println(\"Got signal:\", killSignal)\n\t\t\t\tstdlog.Println(\"Stoping listening on \", listener.Addr())\n\t\t\t\tlistener.Close()\n\t\t\t\tif killSignal == os.Interrupt {\n\t\t\t\t\treturn \"Daemon was interrupted by system signal\", nil\n\t\t\t\t}\n\t\t\t\treturn \"Daemon was killed\", nil\n\t\t\t}\n\t\t}\n\n\t\t\/\/ never happen, but need to complete code\n\t\treturn usage, nil\n\t}\n\n\t\/\/ Accept a client connection and collect it in a channel\n\tfunc acceptConnection(listener net.Listener, listen chan<- net.Conn) {\n\t\tfor {\n\t\t\tconn, err := listener.Accept()\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlisten <- conn\n\t\t}\n\t}\n\n\tfunc handleClient(client net.Conn) {\n\t\tfor {\n\t\t\tbuf := make([]byte, 4096)\n\t\t\tnumbytes, err := client.Read(buf)\n\t\t\tif numbytes == 0 || err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tclient.Write(buf[:numbytes])\n\t\t}\n\t}\n\n\tfunc init() {\n\t\tstdlog = log.New(os.Stdout, \"\", log.Ldate|log.Ltime)\n\t\terrlog = log.New(os.Stderr, \"\", log.Ldate|log.Ltime)\n\t}\n\n\tfunc main() {\n\t\tsrv, err := daemon.New(name, description, dependencies...)\n\t\tif err != nil {\n\t\t\terrlog.Println(\"Error: \", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tservice := &Service{srv}\n\t\tstatus, err := service.Manage()\n\t\tif err != nil {\n\t\t\terrlog.Println(status, \"\\nError: \", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Println(status)\n\t}\n\nGo daemon\n*\/\npackage daemon\n\nimport \"strings\"\n\n\/\/ Daemon interface has a standard set of methods\/commands\ntype Daemon interface {\n\n\t\/\/ Install the service into the system\n\tInstall(args ...string) (string, error)\n\n\t\/\/ Remove the service and all corresponding files from the system\n\tRemove() (string, error)\n\n\t\/\/ Start the service\n\tStart() (string, error)\n\n\t\/\/ Stop the service\n\tStop() (string, error)\n\n\t\/\/ Status - check the service status\n\tStatus() (string, error)\n}\n\n\/\/ New - Create a new daemon\n\/\/\n\/\/ name: name of the service\n\/\/\n\/\/ description: any explanation, what is the service, its purpose\nfunc New(name, description string, dependencies ...string) (Daemon, error) {\n\treturn newDaemon(strings.Join(strings.Fields(name), \"_\"), description, dependencies)\n}\n\n\/\/ ExecPath tries to get executable path\nfunc ExecPath() (string, error) {\n\treturn execPath()\n}\n<commit_msg>Bumped version number to 0.9.0<commit_after>\/\/ Copyright 2016 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nPackage daemon 0.9.0 for use with Go (golang) services.\n\nPackage daemon provides primitives for daemonization of golang services.\nThis package is not provide implementation of user daemon,\naccordingly must have root rights to install\/remove service.\nIn the current implementation is only supported Linux and Mac Os X daemon.\n\nExample:\n\n\t\/\/ Example of a daemon with echo service\n\tpackage main\n\n\timport (\n\t\t\"fmt\"\n\t\t\"log\"\n\t\t\"net\"\n\t\t\"os\"\n\t\t\"os\/signal\"\n\t\t\"syscall\"\n\n\t\t\"github.com\/takama\/daemon\"\n\t)\n\n\tconst (\n\n\t\t\/\/ name of the service\n\t\tname        = \"myservice\"\n\t\tdescription = \"My Echo Service\"\n\n\t\t\/\/ port which daemon should be listen\n\t\tport = \":9977\"\n\t)\n\n  \/\/ dependencies that are NOT required by the service, but might be used\n  var dependencies = []string{\"dummy.service\"}\n\n\tvar stdlog, errlog *log.Logger\n\n\t\/\/ Service has embedded daemon\n\ttype Service struct {\n\t\tdaemon.Daemon\n\t}\n\n\t\/\/ Manage by daemon commands or run the daemon\n\tfunc (service *Service) Manage() (string, error) {\n\n\t\tusage := \"Usage: myservice install | remove | start | stop | status\"\n\n\t\t\/\/ if received any kind of command, do it\n\t\tif len(os.Args) > 1 {\n\t\t\tcommand := os.Args[1]\n\t\t\tswitch command {\n\t\t\tcase \"install\":\n\t\t\t\treturn service.Install()\n\t\t\tcase \"remove\":\n\t\t\t\treturn service.Remove()\n\t\t\tcase \"start\":\n\t\t\t\treturn service.Start()\n\t\t\tcase \"stop\":\n\t\t\t\treturn service.Stop()\n\t\t\tcase \"status\":\n\t\t\t\treturn service.Status()\n\t\t\tdefault:\n\t\t\t\treturn usage, nil\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Do something, call your goroutines, etc\n\n\t\t\/\/ Set up channel on which to send signal notifications.\n\t\t\/\/ We must use a buffered channel or risk missing the signal\n\t\t\/\/ if we're not ready to receive when the signal is sent.\n\t\tinterrupt := make(chan os.Signal, 1)\n\t\tsignal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM)\n\n\t\t\/\/ Set up listener for defined host and port\n\t\tlistener, err := net.Listen(\"tcp\", port)\n\t\tif err != nil {\n\t\t\treturn \"Possibly was a problem with the port binding\", err\n\t\t}\n\n\t\t\/\/ set up channel on which to send accepted connections\n\t\tlisten := make(chan net.Conn, 100)\n\t\tgo acceptConnection(listener, listen)\n\n\t\t\/\/ loop work cycle with accept connections or interrupt\n\t\t\/\/ by system signal\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase conn := <-listen:\n\t\t\t\tgo handleClient(conn)\n\t\t\tcase killSignal := <-interrupt:\n\t\t\t\tstdlog.Println(\"Got signal:\", killSignal)\n\t\t\t\tstdlog.Println(\"Stoping listening on \", listener.Addr())\n\t\t\t\tlistener.Close()\n\t\t\t\tif killSignal == os.Interrupt {\n\t\t\t\t\treturn \"Daemon was interrupted by system signal\", nil\n\t\t\t\t}\n\t\t\t\treturn \"Daemon was killed\", nil\n\t\t\t}\n\t\t}\n\n\t\t\/\/ never happen, but need to complete code\n\t\treturn usage, nil\n\t}\n\n\t\/\/ Accept a client connection and collect it in a channel\n\tfunc acceptConnection(listener net.Listener, listen chan<- net.Conn) {\n\t\tfor {\n\t\t\tconn, err := listener.Accept()\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlisten <- conn\n\t\t}\n\t}\n\n\tfunc handleClient(client net.Conn) {\n\t\tfor {\n\t\t\tbuf := make([]byte, 4096)\n\t\t\tnumbytes, err := client.Read(buf)\n\t\t\tif numbytes == 0 || err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tclient.Write(buf[:numbytes])\n\t\t}\n\t}\n\n\tfunc init() {\n\t\tstdlog = log.New(os.Stdout, \"\", log.Ldate|log.Ltime)\n\t\terrlog = log.New(os.Stderr, \"\", log.Ldate|log.Ltime)\n\t}\n\n\tfunc main() {\n\t\tsrv, err := daemon.New(name, description, dependencies...)\n\t\tif err != nil {\n\t\t\terrlog.Println(\"Error: \", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tservice := &Service{srv}\n\t\tstatus, err := service.Manage()\n\t\tif err != nil {\n\t\t\terrlog.Println(status, \"\\nError: \", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Println(status)\n\t}\n\nGo daemon\n*\/\npackage daemon\n\nimport \"strings\"\n\n\/\/ Daemon interface has a standard set of methods\/commands\ntype Daemon interface {\n\n\t\/\/ Install the service into the system\n\tInstall(args ...string) (string, error)\n\n\t\/\/ Remove the service and all corresponding files from the system\n\tRemove() (string, error)\n\n\t\/\/ Start the service\n\tStart() (string, error)\n\n\t\/\/ Stop the service\n\tStop() (string, error)\n\n\t\/\/ Status - check the service status\n\tStatus() (string, error)\n}\n\n\/\/ New - Create a new daemon\n\/\/\n\/\/ name: name of the service\n\/\/\n\/\/ description: any explanation, what is the service, its purpose\nfunc New(name, description string, dependencies ...string) (Daemon, error) {\n\treturn newDaemon(strings.Join(strings.Fields(name), \"_\"), description, dependencies)\n}\n\n\/\/ ExecPath tries to get executable path\nfunc ExecPath() (string, error) {\n\treturn execPath()\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Added another TODO<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport \"tour\/pic\"\n\nfunc Pic(dx, dy int) [][]uint8 {\n\tp := make([][]uint8, dy)\n\tfor i := range p {\n\t\tp[i] = make([]uint8, dx)\n\t}\n\n\tfor y := range p {\n\t\tfor x, row := range p[y] {\n\t\t\trow[x] = uint8(x * y)\n\t\t}\n\t}\n\n\treturn p\n}\n\nfunc main() {\n\tpic.Show(Pic)\n}\n<commit_msg>go-tour: Fixing wrong solution for slices exercise. Fixes issue 50<commit_after>\/\/ Copyright 2012 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport \"tour\/pic\"\n\nfunc Pic(dx, dy int) [][]uint8 {\n\tp := make([][]uint8, dy)\n\tfor i := range p {\n\t\tp[i] = make([]uint8, dx)\n\t}\n\n\tfor y, row := range p {\n\t\tfor x := range row {\n\t\t\trow[x] = uint8(x * y)\n\t\t}\n\t}\n\n\treturn p\n}\n\nfunc main() {\n\tpic.Show(Pic)\n}\n<|endoftext|>"}
{"text":"<commit_before>package xhttp\n\nimport (\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/atdiar\/goroutine\/execution\"\n\t\"github.com\/atdiar\/sac\"\n)\n\n\/\/ ServeMux holds the multiplexing logic of incoming http requests.\n\/\/ It wraps around a net\/http multiplexer.\n\/\/ It facilitates the registration of request handlers.\ntype ServeMux struct {\n\tcatchAll HandlerLinker\n\thandlers map[string]verbsHandler\n\ttimeout  time.Duration\n\t*http.ServeMux\n\tpool *sync.Pool\n}\n\ntype option func(*ServeMux)\n\n\/\/ ChangeMux returns a configuration option for the ServeMux constructor\n\/\/ which enables the choice of an alternate Muxer.\nfunc ChangeMux(mux *http.ServeMux) func(*ServeMux) {\n\treturn func(i *ServeMux) {\n\t\ti.ServeMux = mux\n\t}\n}\n\n\/\/ NewServeMux creates a new multiplexer which holds the request servicing logic.\n\/\/ The mux used by default is http.DefaultServeMux.\n\/\/ That can be changed by using the ChangeMux configuration option.\nfunc NewServeMux(options ...option) ServeMux {\n\tsm := ServeMux{}\n\tsm.ServeMux = http.DefaultServeMux\n\tsm.handlers = make(map[string]verbsHandler)\n\tsm.pool = sac.Pool()\n\n\t\/\/ The below applies the options if any were passed.\n\tfor _, opt := range options {\n\t\topt(&sm)\n\t}\n\treturn sm\n}\n\n\/\/ ServeHTTP is the request-servicing function for an object of type ServeMux.\nfunc (sm ServeMux) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Let's get the pattern first.\n\t_, pattern := sm.ServeMux.Handler(req)\n\n\t\/\/ Let's check whether a handler has been registered for this pattern.\n\tif vh, ok := sm.handlers[pattern]; ok {\n\n\t\t\/\/ Let's extract the http Method and apply the handler if it exists.\n\t\tmethod := strings.ToUpper(req.Method)\n\t\tswitch method {\n\t\tcase \"GET\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.get.ServeHTTP(ctx, w, req)\n\t\tcase \"POST\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.post.ServeHTTP(ctx, w, req)\n\t\tcase \"PUT\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.put.ServeHTTP(ctx, w, req)\n\t\tcase \"PATCH\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.patch.ServeHTTP(ctx, w, req)\n\t\tcase \"DELETE\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.delete.ServeHTTP(ctx, w, req)\n\t\tcase \"HEAD\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.head.ServeHTTP(ctx, w, req)\n\t\tcase \"OPTIONS\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.options.ServeHTTP(ctx, w, req)\n\t\tcase \"CONNECT\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.connect.ServeHTTP(ctx, w, req)\n\t\tcase \"TRACE\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.trace.ServeHTTP(ctx, w, req)\n\t\tdefault:\n\t\t\thttp.Error(w, http.StatusText(405), 405)\n\t\t}\n\t} else {\n\t\thttp.Error(w, http.StatusText(405), 405)\n\t}\n}\n\n\/\/ verbsHandler defines the request handling that is attached to each http\n\/\/ verb.\ntype verbsHandler struct {\n\tget     transformationHandler\n\tpost    transformationHandler\n\tput     transformationHandler\n\tpatch   transformationHandler\n\tdelete  transformationHandler\n\thead    transformationHandler\n\toptions transformationHandler\n\tconnect transformationHandler\n\ttrace   transformationHandler\n}\n\nfunc (vh *verbsHandler) prepend(h HandlerLinker) {\n\tvh.get.prepend(h)\n\tvh.post.prepend(h)\n\tvh.put.prepend(h)\n\tvh.patch.prepend(h)\n\tvh.delete.prepend(h)\n\tvh.head.prepend(h)\n\tvh.options.prepend(h)\n\tvh.connect.prepend(h)\n\tvh.trace.prepend(h)\n}\n\n\/\/ transformationHandler is defined per pattern and per verb.\n\/\/ This format allows for the modification of a handler. For instance, it is\n\/\/ used to prepend catchall request handlers more easily.\n\/\/ It implements the Handler interface.\ntype transformationHandler struct {\n\tinput   Handler\n\tHandler \/\/ output\n}\n\nfunc (t *transformationHandler) register(h Handler) {\n\tt.input = h\n\tt.Handler = h\n}\n\nfunc (t *transformationHandler) prepend(h HandlerLinker) {\n\tif h != nil && t.input != nil {\n\t\tt.Handler = h.CallNext(t.input)\n\t} else {\n\t\tpanic(\"Nil handlers can't be linked together.\")\n\t}\n}\n\n\/\/ HANDLER REGISTRATION\n\n\/\/ GET registers the request Handler for the servicing of http GET requests.\nfunc (sm *ServeMux) GET(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, sm)\n\t}\n\n\troutehandler.get.register(h)\n\troutehandler.get.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ POST registers the request Handler for the servicing of http POST requests.\nfunc (sm *ServeMux) POST(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, sm)\n\t}\n\n\troutehandler.post.register(h)\n\troutehandler.post.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ PUT registers the request Handler for the servicing of http PUT requests.\nfunc (sm *ServeMux) PUT(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.put.register(h)\n\troutehandler.put.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ PATCH registers the request Handler for the servicing of http PATCH requests.\nfunc (sm *ServeMux) PATCH(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.patch.register(h)\n\troutehandler.patch.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ DELETE registers the request Handler for the servicing of http DELETE requests.\nfunc (sm *ServeMux) DELETE(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.delete.register(h)\n\troutehandler.delete.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ HEAD registers the request Handler for the servicing of http HEAD requests.\nfunc (sm *ServeMux) HEAD(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.head.register(h)\n\troutehandler.head.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ OPTIONS registers the request Handler for the servicing of http OPTIONS requests.\nfunc (sm *ServeMux) OPTIONS(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.options.register(h)\n\troutehandler.options.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ CONNECT registers the request Handler for the servicing of http CONNECT requests.\nfunc (sm *ServeMux) CONNECT(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.connect.register(h)\n\troutehandler.connect.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ TRACE registers the request Handler for the servicing of http TRACE requests.\nfunc (sm *ServeMux) TRACE(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.trace.register(h)\n\troutehandler.trace.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ USE registers linkable request Handlers (i.e. implementing HandlerLinker)\n\/\/ which shall be servicing any path, regardless of the request method.\nfunc (sm *ServeMux) USE(handlers ...HandlerLinker) {\n\tsm.catchAll = Link(handlers...)\n\tfor method, vh := range sm.handlers {\n\t\tvh.prepend(sm.catchAll)\n\t\tsm.handlers[method] = vh\n\t}\n}\n\n\/\/ Link is a function that is used to create a chain of Handlers when provided\n\/\/ with linkable Handlers (they must implement HandlerLinker).\n\/\/ It returns the first link of the chain.\nfunc Link(handlers ...HandlerLinker) HandlerLinker {\n\tl := len(handlers)\n\n\tif l == 0 {\n\t\treturn nil\n\t}\n\n\tif l > 1 {\n\t\t\/\/ Starting from the penultimate element, we link the handlers using the\n\t\t\/\/ CallNext registration method.\n\t\tfor i := range handlers[:l-2] {\n\t\t\th := handlers[l-2-i].CallNext(handlers[l-1-i])\n\t\t\thandlers[l-2-i] = h\n\t\t}\n\t}\n\treturn handlers[0]\n}\n<commit_msg>Modify ServeHTTP to handle a third-party having registered a handler.<commit_after>package xhttp\n\nimport (\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/atdiar\/goroutine\/execution\"\n\t\"github.com\/atdiar\/sac\"\n)\n\n\/\/ ServeMux holds the multiplexing logic of incoming http requests.\n\/\/ It wraps around a net\/http multiplexer.\n\/\/ It facilitates the registration of request handlers.\ntype ServeMux struct {\n\tcatchAll HandlerLinker\n\thandlers map[string]verbsHandler\n\ttimeout  time.Duration\n\t*http.ServeMux\n\tpool *sync.Pool\n}\n\ntype option func(*ServeMux)\n\n\/\/ ChangeMux returns a configuration option for the ServeMux constructor\n\/\/ which enables the choice of an alternate Muxer.\nfunc ChangeMux(mux *http.ServeMux) func(*ServeMux) {\n\treturn func(i *ServeMux) {\n\t\ti.ServeMux = mux\n\t}\n}\n\n\/\/ NewServeMux creates a new multiplexer which holds the request servicing logic.\n\/\/ The mux used by default is http.DefaultServeMux.\n\/\/ That can be changed by using the ChangeMux configuration option.\nfunc NewServeMux(options ...option) ServeMux {\n\tsm := ServeMux{}\n\tsm.ServeMux = http.DefaultServeMux\n\tsm.handlers = make(map[string]verbsHandler)\n\tsm.pool = sac.Pool()\n\n\t\/\/ The below applies the options if any were passed.\n\tfor _, opt := range options {\n\t\topt(&sm)\n\t}\n\treturn sm\n}\n\n\/\/ ServeHTTP is the request-servicing function for an object of type ServeMux.\nfunc (sm ServeMux) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\t\/\/ Let's get the pattern first.\n\t_, pattern := sm.ServeMux.Handler(req)\n\n\t\/\/ Let's check whether a handler has been registered for this pattern.\n\tif vh, ok := sm.handlers[pattern]; ok {\n\n\t\t\/\/ Let's extract the http Method and apply the handler if it exists.\n\t\tmethod := strings.ToUpper(req.Method)\n\t\tswitch method {\n\t\tcase \"GET\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.get.ServeHTTP(ctx, w, req)\n\t\tcase \"POST\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.post.ServeHTTP(ctx, w, req)\n\t\tcase \"PUT\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.put.ServeHTTP(ctx, w, req)\n\t\tcase \"PATCH\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.patch.ServeHTTP(ctx, w, req)\n\t\tcase \"DELETE\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.delete.ServeHTTP(ctx, w, req)\n\t\tcase \"HEAD\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.head.ServeHTTP(ctx, w, req)\n\t\tcase \"OPTIONS\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.options.ServeHTTP(ctx, w, req)\n\t\tcase \"CONNECT\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.connect.ServeHTTP(ctx, w, req)\n\t\tcase \"TRACE\":\n\t\t\tS := sac.New(sm.pool)\n\t\t\tctx := execution.NewContext(S)\n\t\t\tif sm.timeout != 0 {\n\t\t\t\tctx = ctx.CancelAfter(execution.Timeout(sm.timeout))\n\t\t\t}\n\t\t\tdefer ctx.Cancel()\n\t\t\tvh.trace.ServeHTTP(ctx, w, req)\n\t\tdefault:\n\t\t\thttp.Error(w, http.StatusText(405), 405)\n\t\t}\n\t} else {\n\t\t\/\/ If nothing was registered by any other entity, h will default to\n\t\t\/\/ a page not found handler (404)\n\t\th, _ := sm.ServeMux.Handler(req)\n\t\th.ServeHTTP(w, req)\n\t}\n}\n\n\/\/ verbsHandler defines the request handling that is attached to each http\n\/\/ verb.\ntype verbsHandler struct {\n\tget     transformationHandler\n\tpost    transformationHandler\n\tput     transformationHandler\n\tpatch   transformationHandler\n\tdelete  transformationHandler\n\thead    transformationHandler\n\toptions transformationHandler\n\tconnect transformationHandler\n\ttrace   transformationHandler\n}\n\nfunc (vh *verbsHandler) prepend(h HandlerLinker) {\n\tvh.get.prepend(h)\n\tvh.post.prepend(h)\n\tvh.put.prepend(h)\n\tvh.patch.prepend(h)\n\tvh.delete.prepend(h)\n\tvh.head.prepend(h)\n\tvh.options.prepend(h)\n\tvh.connect.prepend(h)\n\tvh.trace.prepend(h)\n}\n\n\/\/ transformationHandler is defined per pattern and per verb.\n\/\/ This format allows for the modification of a handler. For instance, it is\n\/\/ used to prepend catchall request handlers more easily.\n\/\/ It implements the Handler interface.\ntype transformationHandler struct {\n\tinput   Handler\n\tHandler \/\/ output\n}\n\nfunc (t *transformationHandler) register(h Handler) {\n\tt.input = h\n\tt.Handler = h\n}\n\nfunc (t *transformationHandler) prepend(h HandlerLinker) {\n\tif h != nil && t.input != nil {\n\t\tt.Handler = h.CallNext(t.input)\n\t} else {\n\t\tpanic(\"Nil handlers can't be linked together.\")\n\t}\n}\n\n\/\/ HANDLER REGISTRATION\n\n\/\/ GET registers the request Handler for the servicing of http GET requests.\nfunc (sm *ServeMux) GET(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, sm)\n\t}\n\n\troutehandler.get.register(h)\n\troutehandler.get.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ POST registers the request Handler for the servicing of http POST requests.\nfunc (sm *ServeMux) POST(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, sm)\n\t}\n\n\troutehandler.post.register(h)\n\troutehandler.post.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ PUT registers the request Handler for the servicing of http PUT requests.\nfunc (sm *ServeMux) PUT(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.put.register(h)\n\troutehandler.put.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ PATCH registers the request Handler for the servicing of http PATCH requests.\nfunc (sm *ServeMux) PATCH(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.patch.register(h)\n\troutehandler.patch.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ DELETE registers the request Handler for the servicing of http DELETE requests.\nfunc (sm *ServeMux) DELETE(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.delete.register(h)\n\troutehandler.delete.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ HEAD registers the request Handler for the servicing of http HEAD requests.\nfunc (sm *ServeMux) HEAD(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.head.register(h)\n\troutehandler.head.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ OPTIONS registers the request Handler for the servicing of http OPTIONS requests.\nfunc (sm *ServeMux) OPTIONS(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.options.register(h)\n\troutehandler.options.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ CONNECT registers the request Handler for the servicing of http CONNECT requests.\nfunc (sm *ServeMux) CONNECT(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.connect.register(h)\n\troutehandler.connect.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ TRACE registers the request Handler for the servicing of http TRACE requests.\nfunc (sm *ServeMux) TRACE(pattern string, h Handler) {\n\n\tif h == nil {\n\t\tpanic(\"ERROR: Handler should not be nil.\")\n\t}\n\n\troutehandler, ok := sm.handlers[pattern]\n\tif !ok {\n\t\tsm.ServeMux.Handle(pattern, *sm)\n\t}\n\n\troutehandler.trace.register(h)\n\troutehandler.trace.prepend(sm.catchAll)\n\tsm.handlers[pattern] = routehandler\n\n}\n\n\/\/ USE registers linkable request Handlers (i.e. implementing HandlerLinker)\n\/\/ which shall be servicing any path, regardless of the request method.\nfunc (sm *ServeMux) USE(handlers ...HandlerLinker) {\n\tsm.catchAll = Link(handlers...)\n\tfor method, vh := range sm.handlers {\n\t\tvh.prepend(sm.catchAll)\n\t\tsm.handlers[method] = vh\n\t}\n}\n\n\/\/ Link is a function that is used to create a chain of Handlers when provided\n\/\/ with linkable Handlers (they must implement HandlerLinker).\n\/\/ It returns the first link of the chain.\nfunc Link(handlers ...HandlerLinker) HandlerLinker {\n\tl := len(handlers)\n\n\tif l == 0 {\n\t\treturn nil\n\t}\n\n\tif l > 1 {\n\t\t\/\/ Starting from the penultimate element, we link the handlers using the\n\t\t\/\/ CallNext registration method.\n\t\tfor i := range handlers[:l-2] {\n\t\t\th := handlers[l-2-i].CallNext(handlers[l-1-i])\n\t\t\thandlers[l-2-i] = h\n\t\t}\n\t}\n\treturn handlers[0]\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n\n\nCopyright 2015 Intel Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage mysql\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\n\t\"github.com\/intelsdi-x\/pulse\/control\/plugin\"\n\t\"github.com\/intelsdi-x\/pulse\/control\/plugin\/cpolicy\"\n\t\"github.com\/intelsdi-x\/pulse\/core\/ctypes\"\n\n\t\"database\/sql\"\n\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\nconst (\n\tname       = \"mysql\"\n\tversion    = 3\n\tpluginType = plugin.PublisherPluginType\n)\n\ntype mysqlPublisher struct {\n}\n\nfunc NewMySQLPublisher() *mysqlPublisher {\n\treturn &mysqlPublisher{}\n}\n\n\/\/ Publish sends data to a MySQL server\nfunc (s *mysqlPublisher) Publish(contentType string, content []byte, config map[string]ctypes.ConfigValue) error {\n\tlogger := log.New()\n\tlogger.Println(\"Publishing started\")\n\tvar metrics []plugin.PluginMetricType\n\n\tswitch contentType {\n\tcase plugin.PulseGOBContentType:\n\t\tdec := gob.NewDecoder(bytes.NewBuffer(content))\n\t\tif err := dec.Decode(&metrics); err != nil {\n\t\t\tlogger.Printf(\"Error decoding: error=%v content=%v\", err, content)\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\tlogger.Printf(\"Error unknown content type '%v'\", contentType)\n\t\treturn errors.New(fmt.Sprintf(\"Unknown content type '%s'\", contentType))\n\t}\n\n\tlogger.Printf(\"publishing %v to %v\", metrics, config)\n\n\t\/\/ Open connection and ping to make sure it works\n\tusername := config[\"username\"].(ctypes.ConfigValueStr).Value\n\tpassword := config[\"password\"].(ctypes.ConfigValueStr).Value\n\tdatabase := config[\"database\"].(ctypes.ConfigValueStr).Value\n\ttableName := config[\"tablename\"].(ctypes.ConfigValueStr).Value\n\ttableColumns := \"(timestamp VARCHAR(200), source_column VARCHAR(200), key_column VARCHAR(200), value_column VARCHAR(200))\"\n\tdb, err := sql.Open(\"mysql\", username+\":\"+password+\"@\/\"+database)\n\tdefer db.Close()\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Create the table if it's not already there\n\t_, err = db.Exec(\"CREATE TABLE IF NOT EXISTS\" + \" \" + tableName + \" \" + tableColumns)\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\t\/\/ Put the values into the database with the current time\n\ttableValues := \"VALUES( ?, ?, ?, ? )\"\n\tinsert, err := db.Prepare(\"INSERT INTO\" + \" \" + tableName + \" \" + tableValues)\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\tvar key, value string\n\tfor _, m := range metrics {\n\t\tkey = sliceToString(m.Namespace())\n\t\tvalue, err = interfaceToString(m.Data())\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"Error: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\t_, err := insert.Exec(m.Timestamp(), m.Source(), key, value)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc Meta() *plugin.PluginMeta {\n\treturn plugin.NewPluginMeta(name, version, pluginType, []string{plugin.PulseGOBContentType}, []string{plugin.PulseGOBContentType})\n}\n\nfunc (f *mysqlPublisher) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) {\n\tcp := cpolicy.New()\n\tconfig := cpolicy.NewPolicyNode()\n\n\tusername, err := cpolicy.NewStringRule(\"username\", true, \"root\")\n\thandleErr(err)\n\tusername.Description = \"Username to login to the MySQL server\"\n\n\tpassword, err := cpolicy.NewStringRule(\"password\", true, \"root\")\n\thandleErr(err)\n\tpassword.Description = \"Password to login to the MySQL server\"\n\n\tdatabase, err := cpolicy.NewStringRule(\"database\", true, \"PULSE_TEST\")\n\thandleErr(err)\n\tdatabase.Description = \"The MySQL database that data will be pushed to\"\n\n\ttableName, err := cpolicy.NewStringRule(\"tablename\", true, \"info\")\n\thandleErr(err)\n\ttableName.Description = \"The MySQL table within the database where information will be stored\"\n\n\tconfig.Add(username, password, database, tableName)\n\n\tcp.Add([]string{\"\"}, config)\n\treturn cp, nil\n}\n\nfunc handleErr(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc sliceToString(slice []string) string {\n\treturn strings.Join(slice, \", \")\n}\n\n\/\/ Supported types: []string, []int, int, string\nfunc interfaceToString(face interface{}) (string, error) {\n\tvar (\n\t\tret string\n\t\terr error\n\t)\n\tswitch val := face.(type) {\n\tcase []string:\n\t\tret = sliceToString(val)\n\tcase []int:\n\t\tlength := len(val)\n\t\tif length == 0 {\n\t\t\treturn ret, err\n\t\t}\n\t\tret = strconv.Itoa(val[0])\n\t\tif length == 1 {\n\t\t\treturn ret, err\n\t\t}\n\t\tfor i := 1; i < length; i++ {\n\t\t\tret += \", \"\n\t\t\tret += strconv.Itoa(val[i])\n\t\t}\n\tcase int:\n\t\tret = strconv.Itoa(val)\n\tcase string:\n\t\tret = val\n\tdefault:\n\t\terr = errors.New(\"unsupported type\")\n\t}\n\treturn ret, err\n}\n<commit_msg>Update version to 4<commit_after>\/*\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n\n\nCopyright 2015 Intel Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage mysql\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\n\t\"github.com\/intelsdi-x\/pulse\/control\/plugin\"\n\t\"github.com\/intelsdi-x\/pulse\/control\/plugin\/cpolicy\"\n\t\"github.com\/intelsdi-x\/pulse\/core\/ctypes\"\n\n\t\"database\/sql\"\n\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\nconst (\n\tname       = \"mysql\"\n\tversion    = 4\n\tpluginType = plugin.PublisherPluginType\n)\n\ntype mysqlPublisher struct {\n}\n\nfunc NewMySQLPublisher() *mysqlPublisher {\n\treturn &mysqlPublisher{}\n}\n\n\/\/ Publish sends data to a MySQL server\nfunc (s *mysqlPublisher) Publish(contentType string, content []byte, config map[string]ctypes.ConfigValue) error {\n\tlogger := log.New()\n\tlogger.Println(\"Publishing started\")\n\tvar metrics []plugin.PluginMetricType\n\n\tswitch contentType {\n\tcase plugin.PulseGOBContentType:\n\t\tdec := gob.NewDecoder(bytes.NewBuffer(content))\n\t\tif err := dec.Decode(&metrics); err != nil {\n\t\t\tlogger.Printf(\"Error decoding: error=%v content=%v\", err, content)\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\tlogger.Printf(\"Error unknown content type '%v'\", contentType)\n\t\treturn errors.New(fmt.Sprintf(\"Unknown content type '%s'\", contentType))\n\t}\n\n\tlogger.Printf(\"publishing %v to %v\", metrics, config)\n\n\t\/\/ Open connection and ping to make sure it works\n\tusername := config[\"username\"].(ctypes.ConfigValueStr).Value\n\tpassword := config[\"password\"].(ctypes.ConfigValueStr).Value\n\tdatabase := config[\"database\"].(ctypes.ConfigValueStr).Value\n\ttableName := config[\"tablename\"].(ctypes.ConfigValueStr).Value\n\ttableColumns := \"(timestamp VARCHAR(200), source_column VARCHAR(200), key_column VARCHAR(200), value_column VARCHAR(200))\"\n\tdb, err := sql.Open(\"mysql\", username+\":\"+password+\"@\/\"+database)\n\tdefer db.Close()\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Create the table if it's not already there\n\t_, err = db.Exec(\"CREATE TABLE IF NOT EXISTS\" + \" \" + tableName + \" \" + tableColumns)\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\t\/\/ Put the values into the database with the current time\n\ttableValues := \"VALUES( ?, ?, ?, ? )\"\n\tinsert, err := db.Prepare(\"INSERT INTO\" + \" \" + tableName + \" \" + tableValues)\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\tvar key, value string\n\tfor _, m := range metrics {\n\t\tkey = sliceToString(m.Namespace())\n\t\tvalue, err = interfaceToString(m.Data())\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"Error: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\t_, err := insert.Exec(m.Timestamp(), m.Source(), key, value)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc Meta() *plugin.PluginMeta {\n\treturn plugin.NewPluginMeta(name, version, pluginType, []string{plugin.PulseGOBContentType}, []string{plugin.PulseGOBContentType})\n}\n\nfunc (f *mysqlPublisher) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) {\n\tcp := cpolicy.New()\n\tconfig := cpolicy.NewPolicyNode()\n\n\tusername, err := cpolicy.NewStringRule(\"username\", true, \"root\")\n\thandleErr(err)\n\tusername.Description = \"Username to login to the MySQL server\"\n\n\tpassword, err := cpolicy.NewStringRule(\"password\", true, \"root\")\n\thandleErr(err)\n\tpassword.Description = \"Password to login to the MySQL server\"\n\n\tdatabase, err := cpolicy.NewStringRule(\"database\", true, \"PULSE_TEST\")\n\thandleErr(err)\n\tdatabase.Description = \"The MySQL database that data will be pushed to\"\n\n\ttableName, err := cpolicy.NewStringRule(\"tablename\", true, \"info\")\n\thandleErr(err)\n\ttableName.Description = \"The MySQL table within the database where information will be stored\"\n\n\tconfig.Add(username, password, database, tableName)\n\n\tcp.Add([]string{\"\"}, config)\n\treturn cp, nil\n}\n\nfunc handleErr(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc sliceToString(slice []string) string {\n\treturn strings.Join(slice, \", \")\n}\n\n\/\/ Supported types: []string, []int, int, string\nfunc interfaceToString(face interface{}) (string, error) {\n\tvar (\n\t\tret string\n\t\terr error\n\t)\n\tswitch val := face.(type) {\n\tcase []string:\n\t\tret = sliceToString(val)\n\tcase []int:\n\t\tlength := len(val)\n\t\tif length == 0 {\n\t\t\treturn ret, err\n\t\t}\n\t\tret = strconv.Itoa(val[0])\n\t\tif length == 1 {\n\t\t\treturn ret, err\n\t\t}\n\t\tfor i := 1; i < length; i++ {\n\t\t\tret += \", \"\n\t\t\tret += strconv.Itoa(val[i])\n\t\t}\n\tcase int:\n\t\tret = strconv.Itoa(val)\n\tcase string:\n\t\tret = val\n\tdefault:\n\t\terr = errors.New(\"unsupported type\")\n\t}\n\treturn ret, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package mysql\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\n\t\"github.com\/intelsdi-x\/pulse\/control\/plugin\"\n\t\"github.com\/intelsdi-x\/pulse\/control\/plugin\/cpolicy\"\n\t\"github.com\/intelsdi-x\/pulse\/core\/ctypes\"\n\n\t\"database\/sql\"\n\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\nconst (\n\tname       = \"mysql\"\n\tversion    = 1\n\tpluginType = plugin.PublisherPluginType\n)\n\ntype mysqlPublisher struct {\n}\n\nfunc NewMySQLPublisher() *mysqlPublisher {\n\treturn &mysqlPublisher{}\n}\n\n\/\/ Publish sends data to a MySQL server\nfunc (s *mysqlPublisher) Publish(contentType string, content []byte, config map[string]ctypes.ConfigValue) error {\n\tlogger := log.New()\n\tlogger.Println(\"Publishing started\")\n\tvar metrics []plugin.PluginMetricType\n\n\tswitch contentType {\n\tcase plugin.PulseGOBContentType:\n\t\tdec := gob.NewDecoder(bytes.NewBuffer(content))\n\t\tif err := dec.Decode(&metrics); err != nil {\n\t\t\tlogger.Printf(\"Error decoding: error=%v content=%v\", err, content)\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\tlogger.Printf(\"Error unknown content type '%v'\", contentType)\n\t\treturn errors.New(fmt.Sprintf(\"Unknown content type '%s'\", contentType))\n\t}\n\n\tlogger.Printf(\"publishing %v to %v\", metrics, config)\n\n\t\/\/ Open connection and ping to make sure it works\n\tusername := config[\"username\"].(ctypes.ConfigValueStr).Value\n\tpassword := config[\"password\"].(ctypes.ConfigValueStr).Value\n\tdatabase := config[\"database\"].(ctypes.ConfigValueStr).Value\n\ttableName := config[\"table name\"].(ctypes.ConfigValueStr).Value\n\ttableColumns := \"(time_posted VARCHAR(200), key_column VARCHAR(200), value_column VARCHAR(200))\"\n\tdb, err := sql.Open(\"mysql\", username+\":\"+password+\"@\/\"+database)\n\tdefer db.Close()\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Create the table if it's not already there\n\t_, err = db.Exec(\"CREATE TABLE IF NOT EXISTS\" + \" \" + tableName + \" \" + tableColumns)\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Put the values into the database with the current time\n\ttableValues := \"VALUES( ?, ?, ? )\"\n\tinsert, err := db.Prepare(\"INSERT INTO\" + \" \" + tableName + \" \" + tableValues)\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\tnowTime := time.Now()\n\tvar key, value string\n\tfor _, m := range metrics {\n\t\tkey = sliceToString(m.Namespace())\n\t\tvalue, err = interfaceToString(m.Data())\n\t\tif err == nil {\n\t\t\t_, err := insert.Exec(nowTime, key, value)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t\tlogger.Printf(\"Error: %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Printf(\"Error: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc Meta() *plugin.PluginMeta {\n\treturn plugin.NewPluginMeta(name, version, pluginType, []string{plugin.PulseGOBContentType}, []string{plugin.PulseGOBContentType})\n}\n\nfunc (f *mysqlPublisher) GetConfigPolicy() cpolicy.ConfigPolicy {\n\tcp := cpolicy.New()\n\tconfig := cpolicy.NewPolicyNode()\n\n\tusername, err := cpolicy.NewStringRule(\"username\", true, \"root\")\n\thandleErr(err)\n\tusername.Description = \"Username to login to the MySQL server\"\n\n\tpassword, err := cpolicy.NewStringRule(\"password\", true, \"root\")\n\thandleErr(err)\n\tpassword.Description = \"Password to login to the MySQL server\"\n\n\tdatabase, err := cpolicy.NewStringRule(\"database\", true, \"PULSE_TEST\")\n\thandleErr(err)\n\tdatabase.Description = \"The MySQL database that data will be pushed to\"\n\n\ttableName, err := cpolicy.NewStringRule(\"tablename\", true, \"info\")\n\thandleErr(err)\n\ttableName.Description = \"The MySQL table within the database where information will be stored\"\n\n\tconfig.Add(username, password, database, tableName)\n\n\tcp.Add([]string{\"\"}, config)\n\treturn *cp\n}\n\nfunc handleErr(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc sliceToString(slice []string) string {\n\treturn strings.Join(slice, \", \")\n}\n\n\/\/ Supported types: []string, []int, int, string\nfunc interfaceToString(face interface{}) (string, error) {\n\tvar (\n\t\tret string\n\t\terr error\n\t)\n\tswitch val := face.(type) {\n\tcase []string:\n\t\tret = sliceToString(val)\n\tcase []int:\n\t\tlength := len(val)\n\t\tif length == 0 {\n\t\t\treturn ret, err\n\t\t}\n\t\tret = strconv.Itoa(val[0])\n\t\tif length == 1 {\n\t\t\treturn ret, err\n\t\t}\n\t\tfor i := 1; i < length; i++ {\n\t\t\tret += \", \"\n\t\t\tret += strconv.Itoa(val[i])\n\t\t}\n\tcase int:\n\t\tret = strconv.Itoa(val)\n\tcase string:\n\t\tret = val\n\tdefault:\n\t\terr = errors.New(\"unsupported type\")\n\t}\n\treturn ret, err\n}\n<commit_msg>Update with code fixes from go vet and add source and timestamp from metric<commit_after>package mysql\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\n\t\"github.com\/intelsdi-x\/pulse\/control\/plugin\"\n\t\"github.com\/intelsdi-x\/pulse\/control\/plugin\/cpolicy\"\n\t\"github.com\/intelsdi-x\/pulse\/core\/ctypes\"\n\n\t\"database\/sql\"\n\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\nconst (\n\tname       = \"mysql\"\n\tversion    = 1\n\tpluginType = plugin.PublisherPluginType\n)\n\ntype mysqlPublisher struct {\n}\n\nfunc NewMySQLPublisher() *mysqlPublisher {\n\treturn &mysqlPublisher{}\n}\n\n\/\/ Publish sends data to a MySQL server\nfunc (s *mysqlPublisher) Publish(contentType string, content []byte, config map[string]ctypes.ConfigValue) error {\n\tlogger := log.New()\n\tlogger.Println(\"Publishing started\")\n\tvar metrics []plugin.PluginMetricType\n\n\tswitch contentType {\n\tcase plugin.PulseGOBContentType:\n\t\tdec := gob.NewDecoder(bytes.NewBuffer(content))\n\t\tif err := dec.Decode(&metrics); err != nil {\n\t\t\tlogger.Printf(\"Error decoding: error=%v content=%v\", err, content)\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\tlogger.Printf(\"Error unknown content type '%v'\", contentType)\n\t\treturn errors.New(fmt.Sprintf(\"Unknown content type '%s'\", contentType))\n\t}\n\n\tlogger.Printf(\"publishing %v to %v\", metrics, config)\n\n\t\/\/ Open connection and ping to make sure it works\n\tusername := config[\"username\"].(ctypes.ConfigValueStr).Value\n\tpassword := config[\"password\"].(ctypes.ConfigValueStr).Value\n\tdatabase := config[\"database\"].(ctypes.ConfigValueStr).Value\n\ttableName := config[\"tablename\"].(ctypes.ConfigValueStr).Value\n\ttableColumns := \"(timestamp VARCHAR(200), source_column VARCHAR(200), key_column VARCHAR(200), value_column VARCHAR(200))\"\n\tdb, err := sql.Open(\"mysql\", username+\":\"+password+\"@\/\"+database)\n\tdefer db.Close()\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Create the table if it's not already there\n\t_, err = db.Exec(\"CREATE TABLE IF NOT EXISTS\" + \" \" + tableName + \" \" + tableColumns)\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Put the values into the database with the current time\n\ttableValues := \"VALUES( ?, ?, ?, ? )\"\n\tinsert, err := db.Prepare(\"INSERT INTO\" + \" \" + tableName + \" \" + tableValues)\n\tif err != nil {\n\t\tlogger.Printf(\"Error: %v\", err)\n\t\treturn err\n\t}\n\tnowTime := time.Now()\n\tvar key, value string\n\tfor _, m := range metrics {\n\t\tkey = sliceToString(m.Namespace())\n\t\tvalue, err = interfaceToString(m.Data())\n\t\tif err == nil {\n\t\t\t_, err := insert.Exec(m.Timestamp(), m.Source(), key, value)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.Printf(\"Error: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc Meta() *plugin.PluginMeta {\n\treturn plugin.NewPluginMeta(name, version, pluginType, []string{plugin.PulseGOBContentType}, []string{plugin.PulseGOBContentType})\n}\n\nfunc (f *mysqlPublisher) GetConfigPolicy() cpolicy.ConfigPolicy {\n\tcp := cpolicy.New()\n\tconfig := cpolicy.NewPolicyNode()\n\n\tusername, err := cpolicy.NewStringRule(\"username\", true, \"root\")\n\thandleErr(err)\n\tusername.Description = \"Username to login to the MySQL server\"\n\n\tpassword, err := cpolicy.NewStringRule(\"password\", true, \"root\")\n\thandleErr(err)\n\tpassword.Description = \"Password to login to the MySQL server\"\n\n\tdatabase, err := cpolicy.NewStringRule(\"database\", true, \"PULSE_TEST\")\n\thandleErr(err)\n\tdatabase.Description = \"The MySQL database that data will be pushed to\"\n\n\ttableName, err := cpolicy.NewStringRule(\"tablename\", true, \"info\")\n\thandleErr(err)\n\ttableName.Description = \"The MySQL table within the database where information will be stored\"\n\n\tconfig.Add(username, password, database, tableName)\n\n\tcp.Add([]string{\"\"}, config)\n\treturn *cp\n}\n\nfunc handleErr(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc sliceToString(slice []string) string {\n\treturn strings.Join(slice, \", \")\n}\n\n\/\/ Supported types: []string, []int, int, string\nfunc interfaceToString(face interface{}) (string, error) {\n\tvar (\n\t\tret string\n\t\terr error\n\t)\n\tswitch val := face.(type) {\n\tcase []string:\n\t\tret = sliceToString(val)\n\tcase []int:\n\t\tlength := len(val)\n\t\tif length == 0 {\n\t\t\treturn ret, err\n\t\t}\n\t\tret = strconv.Itoa(val[0])\n\t\tif length == 1 {\n\t\t\treturn ret, err\n\t\t}\n\t\tfor i := 1; i < length; i++ {\n\t\t\tret += \", \"\n\t\t\tret += strconv.Itoa(val[i])\n\t\t}\n\tcase int:\n\t\tret = strconv.Itoa(val)\n\tcase string:\n\t\tret = val\n\tdefault:\n\t\terr = errors.New(\"unsupported type\")\n\t}\n\treturn ret, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package weatherdata\n\nimport (\n\t\"encoding\/xml\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n)\n\nvar (\n\tcacheFile  = fmt.Sprintf(\"%swoozyforecast.xml\", os.TempDir())\n\tdateFormat = \"2006-01-02T15:04:05\"\n)\n\ntype weatherCredit struct {\n\tURL  string `xml:\"url,attr\"`\n\tText string `xml:\"text,attr\"`\n}\n\ntype customTime struct {\n\ttime.Time\n}\n\ntype customTimeAttr struct {\n\ttime.Time\n}\n\ntype sun struct {\n\tRise customTimeAttr `xml:\"rise,attr\"`\n\tSet  customTimeAttr `xml:\"set,attr\"`\n}\n\ntype weatherLocation struct {\n\tName     string `xml:\"name\"`\n\tType     string `xml:\"type\"`\n\tCountry  string `xml:\"country\"`\n\tTimezone struct {\n\t\tID        string `xml:\"id,attr\"`\n\t\tUTCOffset string `xml:\"utcoffsetMinutes,attr\"`\n\t} `xml:\"timezone\"`\n}\n\n\/\/ WeatherMeta contains metadata about the forecast\ntype WeatherMeta struct {\n\tLastUpdate customTime `xml:\"lastupdate\"`\n\tNextUpdate customTime `xml:\"nextupdate\"`\n}\n\n\/\/ WeatherForecast contains actual forecast\ntype WeatherForecast struct {\n\tFrom     customTimeAttr `xml:\"from,attr\"`\n\tTo       customTimeAttr `xml:\"to,attr\"`\n\tPeriod   int            `xml:\"period,attr\"`\n\tPressure struct {\n\t\tUnit  string  `xml:\"unit,attr\"`\n\t\tValue float32 `xml:\"value,attr\"`\n\t} `xml:\"pressure\"`\n\tPrecipitation struct {\n\t\tValue float32 `xml:\"value,attr\"`\n\t\tMin   float32 `xml:\"minvalue,attr\"`\n\t\tMax   float32 `xml:\"maxvalue,attr\"`\n\t} `xml:\"precipitation\"`\n\tSymbol struct {\n\t\tName   string `xml:\"name,attr\"`\n\t\tNumber int    `xml:\"number,attr\"`\n\t} `xml:\"symbol\"`\n\tTemperature struct {\n\t\tUnit  string `xml:\"unit,attr\"`\n\t\tValue int    `xml:\"value,attr\"`\n\t} `xml:\"temperature\"`\n\tWindDirection struct {\n\t\tDeg  float32 `xml:\"deg,attr\"`\n\t\tCode string  `xml:\"code,attr\"`\n\t\tName string  `xml:\"name,attr\"`\n\t} `xml:\"windDirection\"`\n\tWindSpeed struct {\n\t\tMps  float32 `xml:\"mps,attr\"`\n\t\tName string  `xml:\"name,attr\"`\n\t} `xml:\"windSpeed\"`\n}\n\n\/\/ WeatherData contains actual weather data\ntype WeatherData struct {\n\tCredit   weatherCredit     `xml:\"credit>link\"`\n\tLocation weatherLocation   `xml:\"location\"`\n\tMeta     WeatherMeta       `xml:\"meta\"`\n\tSun      sun               `xml:\"sun\"`\n\tForecast []WeatherForecast `xml:\"forecast>tabular>time\"`\n}\n\nfunc (c *customTime) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tloc, _ := time.LoadLocation(\"Local\")\n\tparse, err := time.ParseInLocation(dateFormat, v, loc)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*c = customTime{parse}\n\treturn nil\n}\n\nfunc (ca *customTimeAttr) UnmarshalXMLAttr(attr xml.Attr) error {\n\tloc, _ := time.LoadLocation(\"Local\")\n\tparse, err := time.ParseInLocation(dateFormat, attr.Value, loc)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*ca = customTimeAttr{parse}\n\treturn nil\n}\n\n\/\/ PeriodName returns period as text\nfunc (wf WeatherForecast) PeriodName() string {\n\tvar retStr string\n\tswitch {\n\tcase wf.Period == 0:\n\t\tretStr = \"Night:   \"\n\tcase wf.Period == 1:\n\t\tretStr = \"Morning: \"\n\tcase wf.Period == 2:\n\t\tretStr = \"Day:     \"\n\tcase wf.Period == 3:\n\t\tretStr = \"Evening: \"\n\t}\n\treturn retStr\n}\n\n\/\/ HoursSinceUpdate returns hours since last update\nfunc (wm WeatherMeta) HoursSinceUpdate() float64 {\n\tt := time.Unix(0, wm.LastUpdate.Local().UnixNano())\n\telapsed := time.Since(t)\n\treturn elapsed.Hours()\n}\n\n\/\/ HoursToNextUpdate returns hours until next update\nfunc (wm WeatherMeta) HoursToNextUpdate() float64 {\n\tt := time.Unix(0, wm.NextUpdate.Local().UnixNano())\n\telapsed := t.Sub(time.Now())\n\treturn elapsed.Hours()\n}\n\n\/\/ SunHours represents number of hours sun is up\nfunc (wd WeatherData) SunHours() float64 {\n\tt := time.Unix(0, wd.Sun.Set.Local().UnixNano())\n\telapsed := t.Sub(time.Unix(0, wd.Sun.Rise.Local().UnixNano()))\n\treturn elapsed.Hours()\n}\n\nfunc yrURL(place string) string {\n\treturn fmt.Sprintf(\"http:\/\/www.yr.no\/place\/%s\/forecast.xml\", place)\n}\n\nfunc weatherDataCache(cc bool, assumeValid bool) (wd WeatherData, valid bool) {\n\tif cc == true {\n\t\tfmt.Println(\"Clearing cache\")\n\t\tos.Remove(cacheFile)\n\t\treturn wd, false\n\t}\n\txmlFile, err := os.Open(cacheFile)\n\n\tif err != nil {\n\t\treturn wd, false\n\t}\n\n\tdefer xmlFile.Close()\n\tXMLdata, _ := ioutil.ReadAll(xmlFile)\n\txml.Unmarshal(XMLdata, &wd)\n\n\t\/\/ Check if forecast is still valid\n\tif wd.Meta.NextUpdate.Before(time.Now()) == true && assumeValid == false {\n\t\tos.Remove(cacheFile)\n\t\treturn WeatherData{}, false\n\t}\n\treturn wd, true\n}\n\nfunc fillWeatherDataCache(place string) (err error) {\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", yrURL(place), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"User-Agent\", \"woozy, https:\/\/github.com\/gummiboll\/woozy\")\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn errors.New(\"Failed to load forecast from yr.no\")\n\t}\n\n\tdefer resp.Body.Close()\n\tout, err := os.Create(cacheFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\tio.Copy(out, resp.Body)\n\treturn nil\n}\n\n\/\/ LoadWeatherData loads xml from yr and returns a struct\nfunc LoadWeatherData(place string, cc bool) (wd WeatherData, err error) {\n\twd, valid := weatherDataCache(cc, false)\n\tif valid != true {\n\t\terr := fillWeatherDataCache(place)\n\t\tif err != nil {\n\t\t\treturn wd, err\n\t\t}\n\t\twd, valid := weatherDataCache(false, true)\n\t\tif valid != true {\n\t\t\treturn wd, errors.New(\"Failed to load forecast\")\n\t\t}\n\t\treturn wd, nil\n\t}\n\treturn wd, nil\n}\n<commit_msg>Adds a timeout to the yr.no-request<commit_after>package weatherdata\n\nimport (\n\t\"encoding\/xml\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n)\n\nvar (\n\tcacheFile  = fmt.Sprintf(\"%swoozyforecast.xml\", os.TempDir())\n\tdateFormat = \"2006-01-02T15:04:05\"\n)\n\ntype weatherCredit struct {\n\tURL  string `xml:\"url,attr\"`\n\tText string `xml:\"text,attr\"`\n}\n\ntype customTime struct {\n\ttime.Time\n}\n\ntype customTimeAttr struct {\n\ttime.Time\n}\n\ntype sun struct {\n\tRise customTimeAttr `xml:\"rise,attr\"`\n\tSet  customTimeAttr `xml:\"set,attr\"`\n}\n\ntype weatherLocation struct {\n\tName     string `xml:\"name\"`\n\tType     string `xml:\"type\"`\n\tCountry  string `xml:\"country\"`\n\tTimezone struct {\n\t\tID        string `xml:\"id,attr\"`\n\t\tUTCOffset string `xml:\"utcoffsetMinutes,attr\"`\n\t} `xml:\"timezone\"`\n}\n\n\/\/ WeatherMeta contains metadata about the forecast\ntype WeatherMeta struct {\n\tLastUpdate customTime `xml:\"lastupdate\"`\n\tNextUpdate customTime `xml:\"nextupdate\"`\n}\n\n\/\/ WeatherForecast contains actual forecast\ntype WeatherForecast struct {\n\tFrom     customTimeAttr `xml:\"from,attr\"`\n\tTo       customTimeAttr `xml:\"to,attr\"`\n\tPeriod   int            `xml:\"period,attr\"`\n\tPressure struct {\n\t\tUnit  string  `xml:\"unit,attr\"`\n\t\tValue float32 `xml:\"value,attr\"`\n\t} `xml:\"pressure\"`\n\tPrecipitation struct {\n\t\tValue float32 `xml:\"value,attr\"`\n\t\tMin   float32 `xml:\"minvalue,attr\"`\n\t\tMax   float32 `xml:\"maxvalue,attr\"`\n\t} `xml:\"precipitation\"`\n\tSymbol struct {\n\t\tName   string `xml:\"name,attr\"`\n\t\tNumber int    `xml:\"number,attr\"`\n\t} `xml:\"symbol\"`\n\tTemperature struct {\n\t\tUnit  string `xml:\"unit,attr\"`\n\t\tValue int    `xml:\"value,attr\"`\n\t} `xml:\"temperature\"`\n\tWindDirection struct {\n\t\tDeg  float32 `xml:\"deg,attr\"`\n\t\tCode string  `xml:\"code,attr\"`\n\t\tName string  `xml:\"name,attr\"`\n\t} `xml:\"windDirection\"`\n\tWindSpeed struct {\n\t\tMps  float32 `xml:\"mps,attr\"`\n\t\tName string  `xml:\"name,attr\"`\n\t} `xml:\"windSpeed\"`\n}\n\n\/\/ WeatherData contains actual weather data\ntype WeatherData struct {\n\tCredit   weatherCredit     `xml:\"credit>link\"`\n\tLocation weatherLocation   `xml:\"location\"`\n\tMeta     WeatherMeta       `xml:\"meta\"`\n\tSun      sun               `xml:\"sun\"`\n\tForecast []WeatherForecast `xml:\"forecast>tabular>time\"`\n}\n\nfunc (c *customTime) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\td.DecodeElement(&v, &start)\n\tloc, _ := time.LoadLocation(\"Local\")\n\tparse, err := time.ParseInLocation(dateFormat, v, loc)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*c = customTime{parse}\n\treturn nil\n}\n\nfunc (ca *customTimeAttr) UnmarshalXMLAttr(attr xml.Attr) error {\n\tloc, _ := time.LoadLocation(\"Local\")\n\tparse, err := time.ParseInLocation(dateFormat, attr.Value, loc)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*ca = customTimeAttr{parse}\n\treturn nil\n}\n\n\/\/ PeriodName returns period as text\nfunc (wf WeatherForecast) PeriodName() string {\n\tvar retStr string\n\tswitch {\n\tcase wf.Period == 0:\n\t\tretStr = \"Night:   \"\n\tcase wf.Period == 1:\n\t\tretStr = \"Morning: \"\n\tcase wf.Period == 2:\n\t\tretStr = \"Day:     \"\n\tcase wf.Period == 3:\n\t\tretStr = \"Evening: \"\n\t}\n\treturn retStr\n}\n\n\/\/ HoursSinceUpdate returns hours since last update\nfunc (wm WeatherMeta) HoursSinceUpdate() float64 {\n\tt := time.Unix(0, wm.LastUpdate.Local().UnixNano())\n\telapsed := time.Since(t)\n\treturn elapsed.Hours()\n}\n\n\/\/ HoursToNextUpdate returns hours until next update\nfunc (wm WeatherMeta) HoursToNextUpdate() float64 {\n\tt := time.Unix(0, wm.NextUpdate.Local().UnixNano())\n\telapsed := t.Sub(time.Now())\n\treturn elapsed.Hours()\n}\n\n\/\/ SunHours represents number of hours sun is up\nfunc (wd WeatherData) SunHours() float64 {\n\tt := time.Unix(0, wd.Sun.Set.Local().UnixNano())\n\telapsed := t.Sub(time.Unix(0, wd.Sun.Rise.Local().UnixNano()))\n\treturn elapsed.Hours()\n}\n\nfunc yrURL(place string) string {\n\treturn fmt.Sprintf(\"http:\/\/www.yr.no\/place\/%s\/forecast.xml\", place)\n}\n\nfunc weatherDataCache(cc bool, assumeValid bool) (wd WeatherData, valid bool) {\n\tif cc == true {\n\t\tfmt.Println(\"Clearing cache\")\n\t\tos.Remove(cacheFile)\n\t\treturn wd, false\n\t}\n\txmlFile, err := os.Open(cacheFile)\n\n\tif err != nil {\n\t\treturn wd, false\n\t}\n\n\tdefer xmlFile.Close()\n\tXMLdata, _ := ioutil.ReadAll(xmlFile)\n\txml.Unmarshal(XMLdata, &wd)\n\n\t\/\/ Check if forecast is still valid\n\tif wd.Meta.NextUpdate.Before(time.Now()) == true && assumeValid == false {\n\t\tos.Remove(cacheFile)\n\t\treturn WeatherData{}, false\n\t}\n\treturn wd, true\n}\n\nfunc fillWeatherDataCache(place string) (err error) {\n\tclient := &http.Client{\n\t\tTimeout: 20 * time.Second,\n\t}\n\treq, err := http.NewRequest(\"GET\", yrURL(place), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"User-Agent\", \"woozy, https:\/\/github.com\/gummiboll\/woozy\")\n\tresp, err := client.Do(req)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn errors.New(\"Failed to load forecast from yr.no\")\n\t}\n\n\tdefer resp.Body.Close()\n\tout, err := os.Create(cacheFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\tio.Copy(out, resp.Body)\n\treturn nil\n}\n\n\/\/ LoadWeatherData loads xml from yr and returns a struct\nfunc LoadWeatherData(place string, cc bool) (wd WeatherData, err error) {\n\twd, valid := weatherDataCache(cc, false)\n\tif valid != true {\n\t\terr := fillWeatherDataCache(place)\n\t\tif err != nil {\n\t\t\treturn wd, err\n\t\t}\n\t\twd, valid := weatherDataCache(false, true)\n\t\tif valid != true {\n\t\t\treturn wd, errors.New(\"Failed to load forecast\")\n\t\t}\n\t\treturn wd, nil\n\t}\n\treturn wd, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package plugins\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Jeffail\/gabs\"\n\t\"github.com\/Seklfreak\/Robyul2\/helpers\"\n\t\"github.com\/bwmarrin\/discordgo\"\n)\n\nconst (\n\tstreamableApiBaseUrl = \"https:\/\/api.streamable.com\/%s\"\n)\n\ntype Streamable struct{}\n\nfunc (s *Streamable) Commands() []string {\n\treturn []string{\n\t\t\"streamable\",\n\t}\n}\n\nfunc (s *Streamable) Init(session *discordgo.Session) {\n\n}\n\nfunc (s *Streamable) Action(command string, content string, msg *discordgo.Message, session *discordgo.Session) { \/\/ [p]streamable [<link>] or attachment\n\tvar err error\n\n\tsession.ChannelTyping(msg.ChannelID)\n\n\tif len(content) <= 0 && len(msg.Attachments) <= 0 {\n\t\t_, err := session.ChannelMessageSend(msg.ChannelID, helpers.GetText(\"bot.arguments.invalid\"))\n\t\thelpers.Relax(err)\n\t\treturn\n\t}\n\n\tsourceUrl := content\n\tif len(msg.Attachments) > 0 {\n\t\tsourceUrl = msg.Attachments[0].URL\n\t}\n\n\tcreateStreamableEndpoint := fmt.Sprintf(streamableApiBaseUrl, fmt.Sprintf(\"import?url=%s\", url.QueryEscape(sourceUrl)))\n\trequest, err := http.NewRequest(\"GET\", createStreamableEndpoint, nil)\n\trequest.Header.Add(\"user-agent\", helpers.DEFAULT_UA)\n\trequest.SetBasicAuth(helpers.GetConfig().Path(\"streamable.username\").Data().(string),\n\t\thelpers.GetConfig().Path(\"streamable.password\").Data().(string))\n\thelpers.Relax(err)\n\tresponse, err := httpClient.Do(request)\n\thelpers.Relax(err)\n\tdefer response.Body.Close()\n\tbuf := bytes.NewBuffer(nil)\n\t_, err = io.Copy(buf, response.Body)\n\thelpers.Relax(err)\n\n\tjsonResult, err := gabs.ParseJSON(buf.Bytes())\n\n\tif err != nil || jsonResult.ExistsP(\"status\") == false || jsonResult.Path(\"status\").Data().(float64) >= 3 {\n\t\t_, err = session.ChannelMessageSend(msg.ChannelID,\n\t\t\tfmt.Sprintf(\"<@%s> Something went wrong while creating your streamable. <:blobscream:317043778823389184>\",\n\t\t\t\tmsg.Author.ID))\n\t\thelpers.Relax(err)\n\t\treturn\n\t}\n\n\tsession.ChannelMessageSend(msg.ChannelID, \"Your streamable is processing, this may take a while. <:blobsleeping:317047101534109696>\")\n\tsession.ChannelTyping(msg.ChannelID)\n\n\tstreamableShortcode := jsonResult.Path(\"shortcode\").Data().(string)\n\tstreamableUrl := \"\"\nCheckStreamableStatusLoop:\n\tfor {\n\t\tstatusStreamableEndpoint := fmt.Sprintf(streamableApiBaseUrl, fmt.Sprintf(\"videos\/%s\", streamableShortcode))\n\t\tresult := helpers.GetJSON(statusStreamableEndpoint)\n\n\t\tswitch result.Path(\"status\").Data().(float64) {\n\t\tcase 0:\n\t\tcase 1:\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t\tsession.ChannelTyping(msg.ChannelID)\n\t\t\tcontinue CheckStreamableStatusLoop\n\t\tcase 2:\n\t\t\tstreamableUrl = result.Path(\"url\").Data().(string)\n\t\t\tif !strings.Contains(streamableUrl, \":\/\/\") {\n\t\t\t\tstreamableUrl = \"https:\/\/\" + streamableUrl\n\t\t\t}\n\t\t\tbreak CheckStreamableStatusLoop\n\t\tdefault:\n\t\t\t_, err = session.ChannelMessageSend(msg.ChannelID,\n\t\t\t\tfmt.Sprintf(\"<@%s> Something went wrong while creating your streamable. <:blobscream:317043778823389184>\",\n\t\t\t\t\tmsg.Author.ID))\n\t\t\thelpers.Relax(err)\n\t\t\treturn\n\t\t\treturn\n\t\t}\n\t}\n\n\t_, err = session.ChannelMessageSend(msg.ChannelID, fmt.Sprintf(\"<@%s> Your streamable is done: %s .\", msg.Author.ID, streamableUrl))\n\thelpers.Relax(err)\n}\n<commit_msg>[streamable] handles 429 error<commit_after>package plugins\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Jeffail\/gabs\"\n\t\"github.com\/Seklfreak\/Robyul2\/helpers\"\n\t\"github.com\/bwmarrin\/discordgo\"\n)\n\nconst (\n\tstreamableApiBaseUrl = \"https:\/\/api.streamable.com\/%s\"\n)\n\ntype Streamable struct{}\n\nfunc (s *Streamable) Commands() []string {\n\treturn []string{\n\t\t\"streamable\",\n\t}\n}\n\nfunc (s *Streamable) Init(session *discordgo.Session) {\n\n}\n\nfunc (s *Streamable) Action(command string, content string, msg *discordgo.Message, session *discordgo.Session) { \/\/ [p]streamable [<link>] or attachment\n\tvar err error\n\n\tsession.ChannelTyping(msg.ChannelID)\n\n\tif len(content) <= 0 && len(msg.Attachments) <= 0 {\n\t\t_, err := session.ChannelMessageSend(msg.ChannelID, helpers.GetText(\"bot.arguments.invalid\"))\n\t\thelpers.Relax(err)\n\t\treturn\n\t}\n\n\tsourceUrl := content\n\tif len(msg.Attachments) > 0 {\n\t\tsourceUrl = msg.Attachments[0].URL\n\t}\n\n\tcreateStreamableEndpoint := fmt.Sprintf(streamableApiBaseUrl, fmt.Sprintf(\"import?url=%s\", url.QueryEscape(sourceUrl)))\n\trequest, err := http.NewRequest(\"GET\", createStreamableEndpoint, nil)\n\trequest.Header.Add(\"user-agent\", helpers.DEFAULT_UA)\n\trequest.SetBasicAuth(helpers.GetConfig().Path(\"streamable.username\").Data().(string),\n\t\thelpers.GetConfig().Path(\"streamable.password\").Data().(string))\n\thelpers.Relax(err)\n\tresponse, err := httpClient.Do(request)\n\thelpers.Relax(err)\n\tdefer response.Body.Close()\n\tbuf := bytes.NewBuffer(nil)\n\t_, err = io.Copy(buf, response.Body)\n\thelpers.Relax(err)\n\n\tjsonResult, err := gabs.ParseJSON(buf.Bytes())\n\n\tif err != nil || jsonResult.ExistsP(\"status\") == false || jsonResult.Path(\"status\").Data().(float64) >= 3 {\n\t\t_, err = session.ChannelMessageSend(msg.ChannelID,\n\t\t\tfmt.Sprintf(\"<@%s> Something went wrong while creating your streamable. <:blobscream:317043778823389184>\",\n\t\t\t\tmsg.Author.ID))\n\t\thelpers.Relax(err)\n\t\treturn\n\t}\n\n\tsession.ChannelMessageSend(msg.ChannelID, \"Your streamable is processing, this may take a while. <:blobsleeping:317047101534109696>\")\n\tsession.ChannelTyping(msg.ChannelID)\n\n\tstreamableShortcode := jsonResult.Path(\"shortcode\").Data().(string)\n\tstreamableUrl := \"\"\nCheckStreamableStatusLoop:\n\tfor {\n\t\tstatusStreamableEndpoint := fmt.Sprintf(streamableApiBaseUrl, fmt.Sprintf(\"videos\/%s\", streamableShortcode))\n\t\tresult, err := gabs.ParseJSON(helpers.NetGet(statusStreamableEndpoint))\n\t\tif err != nil {\n\t\t\tif strings.Contains(err.Error(), \"Expected status 200; Got 429\") {\n\t\t\t\t_, err = session.ChannelMessageSend(msg.ChannelID,\n\t\t\t\t\tfmt.Sprintf(\"<@%s> Too many requests, please try again later. <:blobscream:317043778823389184>\",\n\t\t\t\t\t\tmsg.Author.ID))\n\t\t\t\thelpers.Relax(err)\n\t\t\t} else {\n\t\t\t\thelpers.Relax(err)\n\t\t\t}\n\t\t}\n\n\t\tswitch result.Path(\"status\").Data().(float64) {\n\t\tcase 0:\n\t\tcase 1:\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t\tsession.ChannelTyping(msg.ChannelID)\n\t\t\tcontinue CheckStreamableStatusLoop\n\t\tcase 2:\n\t\t\tstreamableUrl = result.Path(\"url\").Data().(string)\n\t\t\tif !strings.Contains(streamableUrl, \":\/\/\") {\n\t\t\t\tstreamableUrl = \"https:\/\/\" + streamableUrl\n\t\t\t}\n\t\t\tbreak CheckStreamableStatusLoop\n\t\tdefault:\n\t\t\t_, err = session.ChannelMessageSend(msg.ChannelID,\n\t\t\t\tfmt.Sprintf(\"<@%s> Something went wrong while creating your streamable. <:blobscream:317043778823389184>\",\n\t\t\t\t\tmsg.Author.ID))\n\t\t\thelpers.Relax(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t_, err = session.ChannelMessageSend(msg.ChannelID, fmt.Sprintf(\"<@%s> Your streamable is done: %s .\", msg.Author.ID, streamableUrl))\n\thelpers.Relax(err)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 The Gitea Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage validation\n\nimport (\n\t\"net\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"code.gitea.io\/gitea\/modules\/setting\"\n)\n\nvar loopbackIPBlocks []*net.IPNet\n\nvar externalTrackerRegex = regexp.MustCompile(`({?)(?:user|repo|index)+?(}?)`)\n\nfunc init() {\n\tfor _, cidr := range []string{\n\t\t\"127.0.0.0\/8\", \/\/ IPv4 loopback\n\t\t\"::1\/128\",     \/\/ IPv6 loopback\n\t} {\n\t\tif _, block, err := net.ParseCIDR(cidr); err == nil {\n\t\t\tloopbackIPBlocks = append(loopbackIPBlocks, block)\n\t\t}\n\t}\n}\n\nfunc isLoopbackIP(ip string) bool {\n\tpip := net.ParseIP(ip)\n\tif pip == nil {\n\t\treturn false\n\t}\n\tfor _, block := range loopbackIPBlocks {\n\t\tif block.Contains(pip) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ IsValidURL checks if URL is valid\nfunc IsValidURL(uri string) bool {\n\tif u, err := url.ParseRequestURI(uri); err != nil ||\n\t\t(u.Scheme != \"http\" && u.Scheme != \"https\") ||\n\t\t!validPort(portOnly(u.Host)) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ IsValidSiteURL checks if URL is valid\nfunc IsValidSiteURL(uri string) bool {\n\tu, err := url.ParseRequestURI(uri)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif !validPort(portOnly(u.Host)) {\n\t\treturn false\n\t}\n\n\tfor _, scheme := range setting.Service.ValidSiteURLSchemes {\n\t\tif scheme == u.Scheme {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ IsAPIURL checks if URL is current Gitea instance API URL\nfunc IsAPIURL(uri string) bool {\n\treturn strings.HasPrefix(strings.ToLower(uri), strings.ToLower(setting.AppURL+\"api\"))\n}\n\n\/\/ IsValidExternalURL checks if URL is valid external URL\nfunc IsValidExternalURL(uri string) bool {\n\tif !IsValidURL(uri) || IsAPIURL(uri) {\n\t\treturn false\n\t}\n\n\tu, err := url.ParseRequestURI(uri)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\t\/\/ Currently check only if not loopback IP is provided to keep compatibility\n\tif isLoopbackIP(u.Hostname()) || strings.ToLower(u.Hostname()) == \"localhost\" {\n\t\treturn false\n\t}\n\n\t\/\/ TODO: Later it should be added to allow local network IP addresses\n\t\/\/       only if allowed by special setting\n\n\treturn true\n}\n\n\/\/ IsValidExternalTrackerURLFormat checks if URL matches required syntax for external trackers\nfunc IsValidExternalTrackerURLFormat(uri string) bool {\n\tif !IsValidExternalURL(uri) {\n\t\treturn false\n\t}\n\n\t\/\/ check for typoed variables like \/{index\/ or \/[repo}\n\tfor _, match := range externalTrackerRegex.FindAllStringSubmatch(uri, -1) {\n\t\tif (match[1] == \"{\" || match[2] == \"}\") && (match[1] != \"{\" || match[2] != \"}\") {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n<commit_msg>use IsLoopback (#19477)<commit_after>\/\/ Copyright 2018 The Gitea Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage validation\n\nimport (\n\t\"net\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"code.gitea.io\/gitea\/modules\/setting\"\n)\n\nvar externalTrackerRegex = regexp.MustCompile(`({?)(?:user|repo|index)+?(}?)`)\n\nfunc isLoopbackIP(ip string) bool {\n\treturn net.ParseIP(ip).IsLoopback()\n}\n\n\/\/ IsValidURL checks if URL is valid\nfunc IsValidURL(uri string) bool {\n\tif u, err := url.ParseRequestURI(uri); err != nil ||\n\t\t(u.Scheme != \"http\" && u.Scheme != \"https\") ||\n\t\t!validPort(portOnly(u.Host)) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ IsValidSiteURL checks if URL is valid\nfunc IsValidSiteURL(uri string) bool {\n\tu, err := url.ParseRequestURI(uri)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif !validPort(portOnly(u.Host)) {\n\t\treturn false\n\t}\n\n\tfor _, scheme := range setting.Service.ValidSiteURLSchemes {\n\t\tif scheme == u.Scheme {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ IsAPIURL checks if URL is current Gitea instance API URL\nfunc IsAPIURL(uri string) bool {\n\treturn strings.HasPrefix(strings.ToLower(uri), strings.ToLower(setting.AppURL+\"api\"))\n}\n\n\/\/ IsValidExternalURL checks if URL is valid external URL\nfunc IsValidExternalURL(uri string) bool {\n\tif !IsValidURL(uri) || IsAPIURL(uri) {\n\t\treturn false\n\t}\n\n\tu, err := url.ParseRequestURI(uri)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\t\/\/ Currently check only if not loopback IP is provided to keep compatibility\n\tif isLoopbackIP(u.Hostname()) || strings.ToLower(u.Hostname()) == \"localhost\" {\n\t\treturn false\n\t}\n\n\t\/\/ TODO: Later it should be added to allow local network IP addresses\n\t\/\/       only if allowed by special setting\n\n\treturn true\n}\n\n\/\/ IsValidExternalTrackerURLFormat checks if URL matches required syntax for external trackers\nfunc IsValidExternalTrackerURLFormat(uri string) bool {\n\tif !IsValidExternalURL(uri) {\n\t\treturn false\n\t}\n\n\t\/\/ check for typoed variables like \/{index\/ or \/[repo}\n\tfor _, match := range externalTrackerRegex.FindAllStringSubmatch(uri, -1) {\n\t\tif (match[1] == \"{\" || match[2] == \"}\") && (match[1] != \"{\" || match[2] != \"}\") {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2014 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage framework\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n)\n\nfunc EtcdUpgrade(target_storage, target_version string) error {\n\tswitch TestContext.Provider {\n\tcase \"gce\":\n\t\treturn etcdUpgradeGCE(target_storage, target_version)\n\tdefault:\n\t\treturn fmt.Errorf(\"EtcdUpgrade() is not implemented for provider %s\", TestContext.Provider)\n\t}\n}\n\nfunc IngressUpgrade(isUpgrade bool) error {\n\tswitch TestContext.Provider {\n\tcase \"gce\":\n\t\treturn ingressUpgradeGCE(isUpgrade)\n\tdefault:\n\t\treturn fmt.Errorf(\"IngressUpgrade() is not implemented for provider %s\", TestContext.Provider)\n\t}\n}\n\nfunc MasterUpgrade(v string) error {\n\tswitch TestContext.Provider {\n\tcase \"gce\":\n\t\treturn masterUpgradeGCE(v, false)\n\tcase \"gke\":\n\t\treturn masterUpgradeGKE(v)\n\tcase \"kubernetes-anywhere\":\n\t\treturn masterUpgradeKubernetesAnywhere(v)\n\tdefault:\n\t\treturn fmt.Errorf(\"MasterUpgrade() is not implemented for provider %s\", TestContext.Provider)\n\t}\n}\n\nfunc etcdUpgradeGCE(target_storage, target_version string) error {\n\tenv := append(\n\t\tos.Environ(),\n\t\t\"TEST_ETCD_VERSION=\"+target_version,\n\t\t\"STORAGE_BACKEND=\"+target_storage,\n\t\t\"TEST_ETCD_IMAGE=3.2.18-0\")\n\n\t_, _, err := RunCmdEnv(env, gceUpgradeScript(), \"-l\", \"-M\")\n\treturn err\n}\n\nfunc ingressUpgradeGCE(isUpgrade bool) error {\n\tvar command string\n\tif isUpgrade {\n\t\t\/\/ User specified image to upgrade to.\n\t\ttargetImage := TestContext.IngressUpgradeImage\n\t\tif targetImage != \"\" {\n\t\t\tcommand = fmt.Sprintf(\"sudo sed -i -re 's|(image:)(.*)|\\\\1 %s|' \/etc\/kubernetes\/manifests\/glbc.manifest\", targetImage)\n\t\t} else {\n\t\t\t\/\/ Upgrade to latest HEAD image.\n\t\t\tcommand = \"sudo sed -i -re 's\/(image:)(.*)\/\\\\1 gcr.io\\\\\/k8s-ingress-image-push\\\\\/ingress-gce-e2e-glbc-amd64:master\/' \/etc\/kubernetes\/manifests\/glbc.manifest\"\n\t\t}\n\t} else {\n\t\t\/\/ Downgrade to latest release image.\n\t\tcommand = \"sudo sed -i -re 's\/(image:)(.*)\/\\\\1 k8s.gcr.io\\\\\/ingress-gce-glbc-amd64:v1.1.1\/' \/etc\/kubernetes\/manifests\/glbc.manifest\"\n\t}\n\t\/\/ Kubelet should restart glbc automatically.\n\tsshResult, err := NodeExec(GetMasterHost(), command)\n\tLogSSHResult(sshResult)\n\treturn err\n}\n\n\/\/ TODO(mrhohn): Remove this function when kube-proxy is run as a DaemonSet by default.\nfunc MasterUpgradeGCEWithKubeProxyDaemonSet(v string, enableKubeProxyDaemonSet bool) error {\n\treturn masterUpgradeGCE(v, enableKubeProxyDaemonSet)\n}\n\n\/\/ TODO(mrhohn): Remove 'enableKubeProxyDaemonSet' when kube-proxy is run as a DaemonSet by default.\nfunc masterUpgradeGCE(rawV string, enableKubeProxyDaemonSet bool) error {\n\tenv := append(os.Environ(), fmt.Sprintf(\"KUBE_PROXY_DAEMONSET=%v\", enableKubeProxyDaemonSet))\n\t\/\/ TODO: Remove these variables when they're no longer needed for downgrades.\n\tif TestContext.EtcdUpgradeVersion != \"\" && TestContext.EtcdUpgradeStorage != \"\" {\n\t\tenv = append(env,\n\t\t\t\"TEST_ETCD_VERSION=\"+TestContext.EtcdUpgradeVersion,\n\t\t\t\"STORAGE_BACKEND=\"+TestContext.EtcdUpgradeStorage,\n\t\t\t\"TEST_ETCD_IMAGE=3.2.18-0\")\n\t} else {\n\t\t\/\/ In e2e tests, we skip the confirmation prompt about\n\t\t\/\/ implicit etcd upgrades to simulate the user entering \"y\".\n\t\tenv = append(env, \"TEST_ALLOW_IMPLICIT_ETCD_UPGRADE=true\")\n\t}\n\n\tv := \"v\" + rawV\n\t_, _, err := RunCmdEnv(env, gceUpgradeScript(), \"-M\", v)\n\treturn err\n}\n\nfunc locationParamGKE() string {\n\tif TestContext.CloudConfig.MultiMaster {\n\t\t\/\/ GKE Regional Clusters are being tested.\n\t\treturn fmt.Sprintf(\"--region=%s\", TestContext.CloudConfig.Region)\n\t}\n\treturn fmt.Sprintf(\"--zone=%s\", TestContext.CloudConfig.Zone)\n}\n\nfunc appendContainerCommandGroupIfNeeded(args []string) []string {\n\tif TestContext.CloudConfig.Region != \"\" {\n\t\t\/\/ TODO(wojtek-t): Get rid of it once Regional Clusters go to GA.\n\t\treturn append([]string{\"beta\"}, args...)\n\t}\n\treturn args\n}\n\nfunc masterUpgradeGKE(v string) error {\n\tLogf(\"Upgrading master to %q\", v)\n\targs := []string{\n\t\t\"container\",\n\t\t\"clusters\",\n\t\tfmt.Sprintf(\"--project=%s\", TestContext.CloudConfig.ProjectID),\n\t\tlocationParamGKE(),\n\t\t\"upgrade\",\n\t\tTestContext.CloudConfig.Cluster,\n\t\t\"--master\",\n\t\tfmt.Sprintf(\"--cluster-version=%s\", v),\n\t\t\"--quiet\",\n\t}\n\t_, _, err := RunCmd(\"gcloud\", appendContainerCommandGroupIfNeeded(args)...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twaitForSSHTunnels()\n\n\treturn nil\n}\n\nfunc masterUpgradeKubernetesAnywhere(v string) error {\n\tLogf(\"Upgrading master to %q\", v)\n\n\tkaPath := TestContext.KubernetesAnywherePath\n\toriginalConfigPath := filepath.Join(kaPath, \".config\")\n\tbackupConfigPath := filepath.Join(kaPath, \".config.bak\")\n\tupdatedConfigPath := filepath.Join(kaPath, fmt.Sprintf(\".config-%s\", v))\n\n\t\/\/ modify config with specified k8s version\n\tif _, _, err := RunCmd(\"sed\",\n\t\t\"-i.bak\", \/\/ writes original to .config.bak\n\t\tfmt.Sprintf(`s\/kubernetes_version=.*$\/kubernetes_version=%q\/`, v),\n\t\toriginalConfigPath); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\t\/\/ revert .config.bak to .config\n\t\tif err := os.Rename(backupConfigPath, originalConfigPath); err != nil {\n\t\t\tLogf(\"Could not rename %s back to %s\", backupConfigPath, originalConfigPath)\n\t\t}\n\t}()\n\n\t\/\/ invoke ka upgrade\n\tif _, _, err := RunCmd(\"make\", \"-C\", TestContext.KubernetesAnywherePath,\n\t\t\"WAIT_FOR_KUBECONFIG=y\", \"upgrade-master\"); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ move .config to .config.<version>\n\tif err := os.Rename(originalConfigPath, updatedConfigPath); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc NodeUpgrade(f *Framework, v string, img string) error {\n\t\/\/ Perform the upgrade.\n\tvar err error\n\tswitch TestContext.Provider {\n\tcase \"gce\":\n\t\terr = nodeUpgradeGCE(v, img, false)\n\tcase \"gke\":\n\t\terr = nodeUpgradeGKE(v, img)\n\tdefault:\n\t\terr = fmt.Errorf(\"NodeUpgrade() is not implemented for provider %s\", TestContext.Provider)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Wait for it to complete and validate nodes are healthy.\n\t\/\/\n\t\/\/ TODO(ihmccreery) We shouldn't have to wait for nodes to be ready in\n\t\/\/ GKE; the operation shouldn't return until they all are.\n\tLogf(\"Waiting up to %v for all nodes to be ready after the upgrade\", RestartNodeReadyAgainTimeout)\n\tif _, err := CheckNodesReady(f.ClientSet, TestContext.CloudConfig.NumNodes, RestartNodeReadyAgainTimeout); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ TODO(mrhohn): Remove this function when kube-proxy is run as a DaemonSet by default.\nfunc NodeUpgradeGCEWithKubeProxyDaemonSet(f *Framework, v string, img string, enableKubeProxyDaemonSet bool) error {\n\t\/\/ Perform the upgrade.\n\tif err := nodeUpgradeGCE(v, img, enableKubeProxyDaemonSet); err != nil {\n\t\treturn err\n\t}\n\t\/\/ Wait for it to complete and validate nodes are healthy.\n\tLogf(\"Waiting up to %v for all nodes to be ready after the upgrade\", RestartNodeReadyAgainTimeout)\n\tif _, err := CheckNodesReady(f.ClientSet, TestContext.CloudConfig.NumNodes, RestartNodeReadyAgainTimeout); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ TODO(mrhohn): Remove 'enableKubeProxyDaemonSet' when kube-proxy is run as a DaemonSet by default.\nfunc nodeUpgradeGCE(rawV, img string, enableKubeProxyDaemonSet bool) error {\n\tv := \"v\" + rawV\n\tenv := append(os.Environ(), fmt.Sprintf(\"KUBE_PROXY_DAEMONSET=%v\", enableKubeProxyDaemonSet))\n\tif img != \"\" {\n\t\tenv = append(env, \"KUBE_NODE_OS_DISTRIBUTION=\"+img)\n\t\t_, _, err := RunCmdEnv(env, gceUpgradeScript(), \"-N\", \"-o\", v)\n\t\treturn err\n\t}\n\t_, _, err := RunCmdEnv(env, gceUpgradeScript(), \"-N\", v)\n\treturn err\n}\n\nfunc nodeUpgradeGKE(v string, img string) error {\n\tLogf(\"Upgrading nodes to version %q and image %q\", v, img)\n\targs := []string{\n\t\t\"container\",\n\t\t\"clusters\",\n\t\tfmt.Sprintf(\"--project=%s\", TestContext.CloudConfig.ProjectID),\n\t\tlocationParamGKE(),\n\t\t\"upgrade\",\n\t\tTestContext.CloudConfig.Cluster,\n\t\tfmt.Sprintf(\"--cluster-version=%s\", v),\n\t\t\"--quiet\",\n\t}\n\tif len(img) > 0 {\n\t\targs = append(args, fmt.Sprintf(\"--image-type=%s\", img))\n\t}\n\t_, _, err := RunCmd(\"gcloud\", appendContainerCommandGroupIfNeeded(args)...)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twaitForSSHTunnels()\n\n\treturn nil\n}\n\n\/\/ MigTemplate (GCE-only) returns the name of the MIG template that the\n\/\/ nodes of the cluster use.\nfunc MigTemplate() (string, error) {\n\tvar errLast error\n\tvar templ string\n\tkey := \"instanceTemplate\"\n\tif wait.Poll(Poll, SingleCallTimeout, func() (bool, error) {\n\t\t\/\/ TODO(mikedanese): make this hit the compute API directly instead of\n\t\t\/\/ shelling out to gcloud.\n\t\t\/\/ An `instance-groups managed describe` call outputs what we want to stdout.\n\t\toutput, _, err := retryCmd(\"gcloud\", \"compute\", \"instance-groups\", \"managed\",\n\t\t\tfmt.Sprintf(\"--project=%s\", TestContext.CloudConfig.ProjectID),\n\t\t\t\"describe\",\n\t\t\tfmt.Sprintf(\"--zone=%s\", TestContext.CloudConfig.Zone),\n\t\t\tTestContext.CloudConfig.NodeInstanceGroup)\n\t\tif err != nil {\n\t\t\terrLast = fmt.Errorf(\"gcloud compute instance-groups managed describe call failed with err: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\n\t\t\/\/ The 'describe' call probably succeeded; parse the output and try to\n\t\t\/\/ find the line that looks like \"instanceTemplate: url\/to\/<templ>\" and\n\t\t\/\/ return <templ>.\n\t\tif val := ParseKVLines(output, key); len(val) > 0 {\n\t\t\turl := strings.Split(val, \"\/\")\n\t\t\ttempl = url[len(url)-1]\n\t\t\tLogf(\"MIG group %s using template: %s\", TestContext.CloudConfig.NodeInstanceGroup, templ)\n\t\t\treturn true, nil\n\t\t}\n\t\terrLast = fmt.Errorf(\"couldn't find %s in output to get MIG template. Output: %s\", key, output)\n\t\treturn false, nil\n\t}) != nil {\n\t\treturn \"\", fmt.Errorf(\"MigTemplate() failed with last error: %v\", errLast)\n\t}\n\treturn templ, nil\n}\n\nfunc gceUpgradeScript() string {\n\tif len(TestContext.GCEUpgradeScript) == 0 {\n\t\treturn path.Join(TestContext.RepoRoot, \"cluster\/gce\/upgrade.sh\")\n\t}\n\treturn TestContext.GCEUpgradeScript\n}\n\nfunc waitForSSHTunnels() {\n\tLogf(\"Waiting for SSH tunnels to establish\")\n\tRunKubectl(\"run\", \"ssh-tunnel-test\",\n\t\t\"--image=busybox\",\n\t\t\"--restart=Never\",\n\t\t\"--command\", \"--\",\n\t\t\"echo\", \"Hello\")\n\tdefer RunKubectl(\"delete\", \"pod\", \"ssh-tunnel-test\")\n\n\t\/\/ allow up to a minute for new ssh tunnels to establish\n\twait.PollImmediate(5*time.Second, time.Minute, func() (bool, error) {\n\t\t_, err := RunKubectl(\"logs\", \"ssh-tunnel-test\")\n\t\treturn err == nil, nil\n\t})\n}\n<commit_msg>Fix GKE Regional Clusters upgrade tests<commit_after>\/*\nCopyright 2014 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage framework\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n)\n\nfunc EtcdUpgrade(target_storage, target_version string) error {\n\tswitch TestContext.Provider {\n\tcase \"gce\":\n\t\treturn etcdUpgradeGCE(target_storage, target_version)\n\tdefault:\n\t\treturn fmt.Errorf(\"EtcdUpgrade() is not implemented for provider %s\", TestContext.Provider)\n\t}\n}\n\nfunc IngressUpgrade(isUpgrade bool) error {\n\tswitch TestContext.Provider {\n\tcase \"gce\":\n\t\treturn ingressUpgradeGCE(isUpgrade)\n\tdefault:\n\t\treturn fmt.Errorf(\"IngressUpgrade() is not implemented for provider %s\", TestContext.Provider)\n\t}\n}\n\nfunc MasterUpgrade(v string) error {\n\tswitch TestContext.Provider {\n\tcase \"gce\":\n\t\treturn masterUpgradeGCE(v, false)\n\tcase \"gke\":\n\t\treturn masterUpgradeGKE(v)\n\tcase \"kubernetes-anywhere\":\n\t\treturn masterUpgradeKubernetesAnywhere(v)\n\tdefault:\n\t\treturn fmt.Errorf(\"MasterUpgrade() is not implemented for provider %s\", TestContext.Provider)\n\t}\n}\n\nfunc etcdUpgradeGCE(target_storage, target_version string) error {\n\tenv := append(\n\t\tos.Environ(),\n\t\t\"TEST_ETCD_VERSION=\"+target_version,\n\t\t\"STORAGE_BACKEND=\"+target_storage,\n\t\t\"TEST_ETCD_IMAGE=3.2.18-0\")\n\n\t_, _, err := RunCmdEnv(env, gceUpgradeScript(), \"-l\", \"-M\")\n\treturn err\n}\n\nfunc ingressUpgradeGCE(isUpgrade bool) error {\n\tvar command string\n\tif isUpgrade {\n\t\t\/\/ User specified image to upgrade to.\n\t\ttargetImage := TestContext.IngressUpgradeImage\n\t\tif targetImage != \"\" {\n\t\t\tcommand = fmt.Sprintf(\"sudo sed -i -re 's|(image:)(.*)|\\\\1 %s|' \/etc\/kubernetes\/manifests\/glbc.manifest\", targetImage)\n\t\t} else {\n\t\t\t\/\/ Upgrade to latest HEAD image.\n\t\t\tcommand = \"sudo sed -i -re 's\/(image:)(.*)\/\\\\1 gcr.io\\\\\/k8s-ingress-image-push\\\\\/ingress-gce-e2e-glbc-amd64:master\/' \/etc\/kubernetes\/manifests\/glbc.manifest\"\n\t\t}\n\t} else {\n\t\t\/\/ Downgrade to latest release image.\n\t\tcommand = \"sudo sed -i -re 's\/(image:)(.*)\/\\\\1 k8s.gcr.io\\\\\/ingress-gce-glbc-amd64:v1.1.1\/' \/etc\/kubernetes\/manifests\/glbc.manifest\"\n\t}\n\t\/\/ Kubelet should restart glbc automatically.\n\tsshResult, err := NodeExec(GetMasterHost(), command)\n\tLogSSHResult(sshResult)\n\treturn err\n}\n\n\/\/ TODO(mrhohn): Remove this function when kube-proxy is run as a DaemonSet by default.\nfunc MasterUpgradeGCEWithKubeProxyDaemonSet(v string, enableKubeProxyDaemonSet bool) error {\n\treturn masterUpgradeGCE(v, enableKubeProxyDaemonSet)\n}\n\n\/\/ TODO(mrhohn): Remove 'enableKubeProxyDaemonSet' when kube-proxy is run as a DaemonSet by default.\nfunc masterUpgradeGCE(rawV string, enableKubeProxyDaemonSet bool) error {\n\tenv := append(os.Environ(), fmt.Sprintf(\"KUBE_PROXY_DAEMONSET=%v\", enableKubeProxyDaemonSet))\n\t\/\/ TODO: Remove these variables when they're no longer needed for downgrades.\n\tif TestContext.EtcdUpgradeVersion != \"\" && TestContext.EtcdUpgradeStorage != \"\" {\n\t\tenv = append(env,\n\t\t\t\"TEST_ETCD_VERSION=\"+TestContext.EtcdUpgradeVersion,\n\t\t\t\"STORAGE_BACKEND=\"+TestContext.EtcdUpgradeStorage,\n\t\t\t\"TEST_ETCD_IMAGE=3.2.18-0\")\n\t} else {\n\t\t\/\/ In e2e tests, we skip the confirmation prompt about\n\t\t\/\/ implicit etcd upgrades to simulate the user entering \"y\".\n\t\tenv = append(env, \"TEST_ALLOW_IMPLICIT_ETCD_UPGRADE=true\")\n\t}\n\n\tv := \"v\" + rawV\n\t_, _, err := RunCmdEnv(env, gceUpgradeScript(), \"-M\", v)\n\treturn err\n}\n\nfunc locationParamGKE() string {\n\tif TestContext.CloudConfig.MultiMaster {\n\t\t\/\/ GKE Regional Clusters are being tested.\n\t\treturn fmt.Sprintf(\"--region=%s\", TestContext.CloudConfig.Region)\n\t}\n\treturn fmt.Sprintf(\"--zone=%s\", TestContext.CloudConfig.Zone)\n}\n\nfunc appendContainerCommandGroupIfNeeded(args []string) []string {\n\tif TestContext.CloudConfig.Region != \"\" {\n\t\t\/\/ TODO(wojtek-t): Get rid of it once Regional Clusters go to GA.\n\t\treturn append([]string{\"beta\"}, args...)\n\t}\n\treturn args\n}\n\nfunc masterUpgradeGKE(v string) error {\n\tLogf(\"Upgrading master to %q\", v)\n\targs := []string{\n\t\t\"container\",\n\t\t\"clusters\",\n\t\tfmt.Sprintf(\"--project=%s\", TestContext.CloudConfig.ProjectID),\n\t\tlocationParamGKE(),\n\t\t\"upgrade\",\n\t\tTestContext.CloudConfig.Cluster,\n\t\t\"--master\",\n\t\tfmt.Sprintf(\"--cluster-version=%s\", v),\n\t\t\"--quiet\",\n\t}\n\t_, _, err := RunCmd(\"gcloud\", appendContainerCommandGroupIfNeeded(args)...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twaitForSSHTunnels()\n\n\treturn nil\n}\n\nfunc masterUpgradeKubernetesAnywhere(v string) error {\n\tLogf(\"Upgrading master to %q\", v)\n\n\tkaPath := TestContext.KubernetesAnywherePath\n\toriginalConfigPath := filepath.Join(kaPath, \".config\")\n\tbackupConfigPath := filepath.Join(kaPath, \".config.bak\")\n\tupdatedConfigPath := filepath.Join(kaPath, fmt.Sprintf(\".config-%s\", v))\n\n\t\/\/ modify config with specified k8s version\n\tif _, _, err := RunCmd(\"sed\",\n\t\t\"-i.bak\", \/\/ writes original to .config.bak\n\t\tfmt.Sprintf(`s\/kubernetes_version=.*$\/kubernetes_version=%q\/`, v),\n\t\toriginalConfigPath); err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\t\/\/ revert .config.bak to .config\n\t\tif err := os.Rename(backupConfigPath, originalConfigPath); err != nil {\n\t\t\tLogf(\"Could not rename %s back to %s\", backupConfigPath, originalConfigPath)\n\t\t}\n\t}()\n\n\t\/\/ invoke ka upgrade\n\tif _, _, err := RunCmd(\"make\", \"-C\", TestContext.KubernetesAnywherePath,\n\t\t\"WAIT_FOR_KUBECONFIG=y\", \"upgrade-master\"); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ move .config to .config.<version>\n\tif err := os.Rename(originalConfigPath, updatedConfigPath); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc NodeUpgrade(f *Framework, v string, img string) error {\n\t\/\/ Perform the upgrade.\n\tvar err error\n\tswitch TestContext.Provider {\n\tcase \"gce\":\n\t\terr = nodeUpgradeGCE(v, img, false)\n\tcase \"gke\":\n\t\terr = nodeUpgradeGKE(v, img)\n\tdefault:\n\t\terr = fmt.Errorf(\"NodeUpgrade() is not implemented for provider %s\", TestContext.Provider)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn waitForNodesReadyAfterUpgrade(f)\n}\n\n\/\/ TODO(mrhohn): Remove this function when kube-proxy is run as a DaemonSet by default.\nfunc NodeUpgradeGCEWithKubeProxyDaemonSet(f *Framework, v string, img string, enableKubeProxyDaemonSet bool) error {\n\t\/\/ Perform the upgrade.\n\tif err := nodeUpgradeGCE(v, img, enableKubeProxyDaemonSet); err != nil {\n\t\treturn err\n\t}\n\treturn waitForNodesReadyAfterUpgrade(f)\n}\n\nfunc waitForNodesReadyAfterUpgrade(f *Framework) error {\n\t\/\/ Wait for it to complete and validate nodes are healthy.\n\t\/\/\n\t\/\/ TODO(ihmccreery) We shouldn't have to wait for nodes to be ready in\n\t\/\/ GKE; the operation shouldn't return until they all are.\n\tnumNodes, err := NumberOfRegisteredNodes(f.ClientSet)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't detect number of nodes\")\n\t}\n\tLogf(\"Waiting up to %v for all %d nodes to be ready after the upgrade\", RestartNodeReadyAgainTimeout, numNodes)\n\tif _, err := CheckNodesReady(f.ClientSet, numNodes, RestartNodeReadyAgainTimeout); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ TODO(mrhohn): Remove 'enableKubeProxyDaemonSet' when kube-proxy is run as a DaemonSet by default.\nfunc nodeUpgradeGCE(rawV, img string, enableKubeProxyDaemonSet bool) error {\n\tv := \"v\" + rawV\n\tenv := append(os.Environ(), fmt.Sprintf(\"KUBE_PROXY_DAEMONSET=%v\", enableKubeProxyDaemonSet))\n\tif img != \"\" {\n\t\tenv = append(env, \"KUBE_NODE_OS_DISTRIBUTION=\"+img)\n\t\t_, _, err := RunCmdEnv(env, gceUpgradeScript(), \"-N\", \"-o\", v)\n\t\treturn err\n\t}\n\t_, _, err := RunCmdEnv(env, gceUpgradeScript(), \"-N\", v)\n\treturn err\n}\n\nfunc nodeUpgradeGKE(v string, img string) error {\n\tLogf(\"Upgrading nodes to version %q and image %q\", v, img)\n\targs := []string{\n\t\t\"container\",\n\t\t\"clusters\",\n\t\tfmt.Sprintf(\"--project=%s\", TestContext.CloudConfig.ProjectID),\n\t\tlocationParamGKE(),\n\t\t\"upgrade\",\n\t\tTestContext.CloudConfig.Cluster,\n\t\tfmt.Sprintf(\"--cluster-version=%s\", v),\n\t\t\"--quiet\",\n\t}\n\tif len(img) > 0 {\n\t\targs = append(args, fmt.Sprintf(\"--image-type=%s\", img))\n\t}\n\t_, _, err := RunCmd(\"gcloud\", appendContainerCommandGroupIfNeeded(args)...)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twaitForSSHTunnels()\n\n\treturn nil\n}\n\n\/\/ MigTemplate (GCE-only) returns the name of the MIG template that the\n\/\/ nodes of the cluster use.\nfunc MigTemplate() (string, error) {\n\tvar errLast error\n\tvar templ string\n\tkey := \"instanceTemplate\"\n\tif wait.Poll(Poll, SingleCallTimeout, func() (bool, error) {\n\t\t\/\/ TODO(mikedanese): make this hit the compute API directly instead of\n\t\t\/\/ shelling out to gcloud.\n\t\t\/\/ An `instance-groups managed describe` call outputs what we want to stdout.\n\t\toutput, _, err := retryCmd(\"gcloud\", \"compute\", \"instance-groups\", \"managed\",\n\t\t\tfmt.Sprintf(\"--project=%s\", TestContext.CloudConfig.ProjectID),\n\t\t\t\"describe\",\n\t\t\tfmt.Sprintf(\"--zone=%s\", TestContext.CloudConfig.Zone),\n\t\t\tTestContext.CloudConfig.NodeInstanceGroup)\n\t\tif err != nil {\n\t\t\terrLast = fmt.Errorf(\"gcloud compute instance-groups managed describe call failed with err: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\n\t\t\/\/ The 'describe' call probably succeeded; parse the output and try to\n\t\t\/\/ find the line that looks like \"instanceTemplate: url\/to\/<templ>\" and\n\t\t\/\/ return <templ>.\n\t\tif val := ParseKVLines(output, key); len(val) > 0 {\n\t\t\turl := strings.Split(val, \"\/\")\n\t\t\ttempl = url[len(url)-1]\n\t\t\tLogf(\"MIG group %s using template: %s\", TestContext.CloudConfig.NodeInstanceGroup, templ)\n\t\t\treturn true, nil\n\t\t}\n\t\terrLast = fmt.Errorf(\"couldn't find %s in output to get MIG template. Output: %s\", key, output)\n\t\treturn false, nil\n\t}) != nil {\n\t\treturn \"\", fmt.Errorf(\"MigTemplate() failed with last error: %v\", errLast)\n\t}\n\treturn templ, nil\n}\n\nfunc gceUpgradeScript() string {\n\tif len(TestContext.GCEUpgradeScript) == 0 {\n\t\treturn path.Join(TestContext.RepoRoot, \"cluster\/gce\/upgrade.sh\")\n\t}\n\treturn TestContext.GCEUpgradeScript\n}\n\nfunc waitForSSHTunnels() {\n\tLogf(\"Waiting for SSH tunnels to establish\")\n\tRunKubectl(\"run\", \"ssh-tunnel-test\",\n\t\t\"--image=busybox\",\n\t\t\"--restart=Never\",\n\t\t\"--command\", \"--\",\n\t\t\"echo\", \"Hello\")\n\tdefer RunKubectl(\"delete\", \"pod\", \"ssh-tunnel-test\")\n\n\t\/\/ allow up to a minute for new ssh tunnels to establish\n\twait.PollImmediate(5*time.Second, time.Minute, func() (bool, error) {\n\t\t_, err := RunKubectl(\"logs\", \"ssh-tunnel-test\")\n\t\treturn err == nil, nil\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/foize\/go.sgr\"\n\t\"github.com\/howeyc\/fsnotify\"\n\t\"go\/build\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n)\n\nvar (\n\twd string \/\/ working directory\n\n\tpkg *build.Package\n\n\tmonAngo *exec.Cmd \/\/ command builds ango on file change (uses gomon)\n\n\t\/\/ watcher on the ango binary\n\twatcher *fsnotify.Watcher\n\n\t\/\/ closed on stop\n\tstopCh = make(chan bool)\n\tstopWg sync.WaitGroup\n)\n\ntype CheckWriter struct {\n\twr     io.Writer\n\tfilter string\n\taction func()\n}\n\nfunc (c *CheckWriter) Write(b []byte) (n int, err error) {\n\tn, err = c.wr.Write(b)\n\tif strings.Contains(string(b), c.filter) {\n\t\tc.action()\n\t}\n\treturn n, err\n}\nfunc main() {\n\tvar err error\n\tfmt.Println(\"Starting ango dev tool.\")\n\n\twd, err = os.Getwd()\n\tif err != nil {\n\t\tfmt.Printf(\"Error getting wd: %s\\n\", err)\n\t\tstop(1)\n\t\tselect {}\n\t}\n\n\tpkg, err = build.ImportDir(wd, 0)\n\tif err != nil {\n\t\tfmt.Printf(\"Error loading package: %s\\n\", err)\n\t\tstop(1)\n\t\tselect {}\n\t}\n\n\tif pkg.Name != \"main\" || !pkg.IsCommand() || filepath.Base(wd) != \"ango\" {\n\t\tfmt.Println(\"Is tool executed from the right directory? (github.com\/GeertJohan\/ango or a fork)?\")\n\t\tfmt.Printf(\"Current package (%s) is invalid.\\n\", pkg.Name)\n\t\tstop(1)\n\t\tselect {}\n\t}\n\n\tgo rerunExample()\n\n\tgo rerunAngo()\n\n\tgo watchExampleAngo()\n\n\tsigChan := make(chan os.Signal)\n\tsignal.Notify(sigChan, os.Kill, os.Interrupt)\n\tsig := <-sigChan\n\tsignal.Stop(sigChan)\n\n\tfmt.Printf(\"Received %s, closing...\\n\", sig)\n\tif sig == os.Interrupt {\n\t\tstop(0)\n\t} else {\n\t\tstop(1)\n\t}\n\tselect {}\n}\n\nfunc stop(exitCode int) {\n\tgo func() {\n\t\t\/\/ synced stop\n\t\tclose(stopCh)\n\t\tstopWg.Wait()\n\n\t\t\/\/ os.Exit(..)\n\t\tos.Exit(exitCode)\n\t}()\n}\n\nfunc rerunExample() {\n\tstopWg.Add(1)\n\tdefer stopWg.Done()\n\n\tcmdRerun := exec.Command(\"rerun\", filepath.Join(pkg.ImportPath, \"example\"))\n\tcmdRerun.Stdin = os.Stdin\n\tcmdRerun.Stdout = sgr.NewColorWriter(os.Stdout, sgr.FgYellow, false)\n\tcmdRerun.Stderr = sgr.NewColorWriter(os.Stderr, sgr.FgYellow, false)\n\terr := cmdRerun.Start()\n\tif err != nil {\n\t\tfmt.Printf(\"Error running rerun example: %s\\n\", err)\n\t\tstop(1)\n\t\treturn\n\t}\n\t<-stopCh\n\tif cmdRerun.Process != nil {\n\t\tcmdRerun.Process.Signal(os.Interrupt)\n\t}\n\terr = cmdRerun.Wait()\n\tif err != nil && err.Error() != \"exit status 2\" {\n\t\tfmt.Printf(\"Error stopping rerun example: %s\\n\", err)\n\t\treturn\n\t}\n}\n\nfunc rerunAngo() {\n\tstopWg.Add(1)\n\tdefer stopWg.Done()\n\n\tcmdRerun := exec.Command(\"rerun\", \"-build-only\", pkg.ImportPath)\n\tcmdRerun.Stdin = os.Stdin\n\tcw := &CheckWriter{\n\t\twr:     os.Stderr,\n\t\tfilter: \"build passed\",\n\t\taction: func() {\n\t\t\tangoExample()\n\t\t},\n\t}\n\tcmdRerun.Stdout = sgr.NewColorWriter(os.Stdout, sgr.FgCyan, false)\n\tcmdRerun.Stderr = sgr.NewColorWriter(cw, sgr.FgCyan, false)\n\terr := cmdRerun.Start()\n\tif err != nil {\n\t\tfmt.Printf(\"Error running rerun ango build: %s\\n\", err)\n\t\tstop(1)\n\t\treturn\n\t}\n\t<-stopCh\n\tif cmdRerun.Process != nil {\n\t\tcmdRerun.Process.Signal(os.Interrupt)\n\t}\n\terr = cmdRerun.Wait()\n\tif err != nil && err.Error() != \"exit status 2\" {\n\t\tfmt.Printf(\"Error stopping rerun ango build: %s\\n\", err)\n\t\treturn\n\t}\n}\n\nfunc watchExampleAngo() {\n\tstopWg.Add(1)\n\tdefer stopWg.Done()\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting watcher: %s\\n\", err)\n\t\tstop(1)\n\t\treturn\n\t}\n\tdefer watcher.Close()\n\t<-stopCh\n}\n\nfunc angoExample() {\n\tstopWg.Add(1)\n\tdefer stopWg.Done()\n\tfmt.Println(\"Running ango tool for example\/chatService.ango\")\n\tcmdAngoExample := exec.Command(filepath.Join(wd, \"ango\"), \"--verbose\", \"-i\", \"example\/chatService.ango\", \"--js\", \"example\/http-files\", \"--force-overwrite\") \/\/ \"--go\", \"example\",\n\tcmdAngoExample.Stdin = os.Stdin\n\tcmdAngoExample.Stdout = sgr.NewColorWriter(os.Stdout, sgr.FgBlue, false)\n\tcmdAngoExample.Stderr = sgr.NewColorWriter(os.Stderr, sgr.FgBlue, false)\n\terr := cmdAngoExample.Run()\n\tif err != nil {\n\t\tfmt.Printf(\"Error running ango tool: %s\\n\", err)\n\t}\n}\n<commit_msg>Add example .ango file watcher<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/foize\/go.sgr\"\n\t\"github.com\/howeyc\/fsnotify\"\n\t\"go\/build\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n)\n\nvar (\n\twd string \/\/ working directory\n\n\tpkg *build.Package\n\n\tmonAngo *exec.Cmd \/\/ command builds ango on file change (uses gomon)\n\n\t\/\/ watcher on the ango binary\n\twatcher *fsnotify.Watcher\n\n\t\/\/ closed on stop\n\tstopCh = make(chan bool)\n\tstopWg sync.WaitGroup\n)\n\nconst exampleAngoFile = \"example\/chatService.ango\"\n\ntype CheckWriter struct {\n\twr     io.Writer\n\tfilter string\n\taction func()\n}\n\nfunc (c *CheckWriter) Write(b []byte) (n int, err error) {\n\tn, err = c.wr.Write(b)\n\tif strings.Contains(string(b), c.filter) {\n\t\tc.action()\n\t}\n\treturn n, err\n}\nfunc main() {\n\tvar err error\n\tfmt.Println(\"Starting ango dev tool.\")\n\n\twd, err = os.Getwd()\n\tif err != nil {\n\t\tfmt.Printf(\"Error getting wd: %s\\n\", err)\n\t\tstop(1)\n\t\tselect {}\n\t}\n\n\tpkg, err = build.ImportDir(wd, 0)\n\tif err != nil {\n\t\tfmt.Printf(\"Error loading package: %s\\n\", err)\n\t\tstop(1)\n\t\tselect {}\n\t}\n\n\tif pkg.Name != \"main\" || !pkg.IsCommand() || filepath.Base(wd) != \"ango\" {\n\t\tfmt.Println(\"Is tool executed from the right directory? (github.com\/GeertJohan\/ango or a fork)?\")\n\t\tfmt.Printf(\"Current package (%s) is invalid.\\n\", pkg.Name)\n\t\tstop(1)\n\t\tselect {}\n\t}\n\n\tgo rerunExample()\n\n\tgo rerunAngo()\n\n\tgo watchExampleAngo()\n\n\tsigChan := make(chan os.Signal)\n\tsignal.Notify(sigChan, os.Kill, os.Interrupt)\n\tsig := <-sigChan\n\tsignal.Stop(sigChan)\n\n\tfmt.Printf(\"Received %s, closing...\\n\", sig)\n\tif sig == os.Interrupt {\n\t\tstop(0)\n\t} else {\n\t\tstop(1)\n\t}\n\tselect {}\n}\n\nfunc stop(exitCode int) {\n\tgo func() {\n\t\t\/\/ synced stop\n\t\tclose(stopCh)\n\t\tstopWg.Wait()\n\n\t\t\/\/ os.Exit(..)\n\t\tos.Exit(exitCode)\n\t}()\n}\n\nfunc rerunExample() {\n\tstopWg.Add(1)\n\tdefer stopWg.Done()\n\n\tcmdRerun := exec.Command(\"rerun\", filepath.Join(pkg.ImportPath, \"example\"))\n\tcmdRerun.Stdin = os.Stdin\n\tcmdRerun.Stdout = sgr.NewColorWriter(os.Stdout, sgr.FgYellow, false)\n\tcmdRerun.Stderr = sgr.NewColorWriter(os.Stderr, sgr.FgYellow, false)\n\terr := cmdRerun.Start()\n\tif err != nil {\n\t\tfmt.Printf(\"Error running rerun example: %s\\n\", err)\n\t\tstop(1)\n\t\treturn\n\t}\n\t<-stopCh\n\tif cmdRerun.Process != nil {\n\t\tcmdRerun.Process.Signal(os.Interrupt)\n\t}\n\terr = cmdRerun.Wait()\n\tif err != nil && err.Error() != \"exit status 2\" {\n\t\tfmt.Printf(\"Error stopping rerun example: %s\\n\", err)\n\t\treturn\n\t}\n}\n\nfunc rerunAngo() {\n\tstopWg.Add(1)\n\tdefer stopWg.Done()\n\n\tcmdRerun := exec.Command(\"rerun\", \"-build-only\", pkg.ImportPath)\n\tcmdRerun.Stdin = os.Stdin\n\tcw := &CheckWriter{\n\t\twr:     os.Stderr,\n\t\tfilter: \"build passed\",\n\t\taction: func() {\n\t\t\tangoExample()\n\t\t},\n\t}\n\tcmdRerun.Stdout = sgr.NewColorWriter(os.Stdout, sgr.FgCyan, false)\n\tcmdRerun.Stderr = sgr.NewColorWriter(cw, sgr.FgCyan, false)\n\terr := cmdRerun.Start()\n\tif err != nil {\n\t\tfmt.Printf(\"Error running rerun ango build: %s\\n\", err)\n\t\tstop(1)\n\t\treturn\n\t}\n\t<-stopCh\n\tif cmdRerun.Process != nil {\n\t\tcmdRerun.Process.Signal(os.Interrupt)\n\t}\n\terr = cmdRerun.Wait()\n\tif err != nil && err.Error() != \"exit status 2\" {\n\t\tfmt.Printf(\"Error stopping rerun ango build: %s\\n\", err)\n\t\treturn\n\t}\n}\n\nfunc watchExampleAngo() {\n\tstopWg.Add(1)\n\tdefer stopWg.Done()\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting watcher: %s\\n\", err)\n\t\tstop(1)\n\t\treturn\n\t}\n\terr = watcher.WatchFlags(exampleAngoFile, fsnotify.FSN_MODIFY)\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting watch on example ango file: %s\\n\", err)\n\t\tstop(1)\n\t\treturn\n\t}\n\tdefer watcher.Close()\n\tfor {\n\t\tselect {\n\t\tcase <-stopCh:\n\t\t\treturn\n\t\tcase <-watcher.Event:\n\t\t\tangoExample()\n\t\tcase err := <-watcher.Error:\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Error watching example ango file: %s\\n\", err)\n\t\t\t\tstop(1)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc angoExample() {\n\tstopWg.Add(1)\n\tdefer stopWg.Done()\n\tfmt.Println(\"Running ango tool for example\/chatService.ango\")\n\tcmdAngoExample := exec.Command(filepath.Join(wd, \"ango\"), \"--verbose\", \"-i\", exampleAngoFile, \"--js\", \"example\/http-files\", \"--force-overwrite\") \/\/ \"--go\", \"example\",\n\tcmdAngoExample.Stdin = os.Stdin\n\tcmdAngoExample.Stdout = sgr.NewColorWriter(os.Stdout, sgr.FgBlue, false)\n\tcmdAngoExample.Stderr = sgr.NewColorWriter(os.Stderr, sgr.FgBlue, false)\n\terr := cmdAngoExample.Run()\n\tif err != nil {\n\t\tfmt.Printf(\"Error running ango tool: %s\\n\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014-2015 The Notify Authors. All rights reserved.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\npackage notify\n\nimport \"sync\"\n\n\/\/ nonrecursiveTree TODO(rjeczalik)\ntype nonrecursiveTree struct {\n\trw   sync.RWMutex \/\/ protects root\n\troot root\n\tw    watcher\n\tc    chan EventInfo\n\trec  chan EventInfo\n}\n\n\/\/ newNonrecursiveTree TODO(rjeczalik)\nfunc newNonrecursiveTree(w watcher, c, rec chan EventInfo) *nonrecursiveTree {\n\tif rec == nil {\n\t\trec = make(chan EventInfo, buffer)\n\t}\n\tt := &nonrecursiveTree{\n\t\troot: root{nd: newnode(\"\")},\n\t\tw:    w,\n\t\tc:    c,\n\t\trec:  rec,\n\t}\n\tgo t.dispatch(c)\n\tgo t.internal(rec)\n\treturn t\n}\n\n\/\/ dispatch TODO(rjeczalik)\nfunc (t *nonrecursiveTree) dispatch(c <-chan EventInfo) {\n\tfor ei := range c {\n\t\tdbgprintf(\"dispatching %v on %q\", ei.Event(), ei.Path())\n\t\tgo func(ei EventInfo) {\n\t\t\tvar nd node\n\t\t\tvar isrec bool\n\t\t\tdir, base := split(ei.Path())\n\t\t\tfn := func(it node, isbase bool) error {\n\t\t\t\tisrec = isrec || it.Watch.IsRecursive()\n\t\t\t\tif isbase {\n\t\t\t\t\tnd = it\n\t\t\t\t} else {\n\t\t\t\t\tit.Watch.Dispatch(ei, recursive)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tt.rw.RLock()\n\t\t\t\/\/ Notify recursive watchpoints found on the path.\n\t\t\tif err := t.root.WalkPath(dir, fn); err != nil {\n\t\t\t\tdbgprint(\"dispatch did not reach leaf:\", err)\n\t\t\t\tt.rw.RUnlock()\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ Notify parent watchpoint.\n\t\t\tnd.Watch.Dispatch(ei, 0)\n\t\t\tisrec = isrec || nd.Watch.IsRecursive()\n\t\t\t\/\/ If leaf watchpoint exists, notify it.\n\t\t\tif nd, ok := nd.Child[base]; ok {\n\t\t\t\tisrec = isrec || nd.Watch.IsRecursive()\n\t\t\t\tnd.Watch.Dispatch(ei, 0)\n\t\t\t}\n\t\t\tt.rw.RUnlock()\n\t\t\t\/\/ If the event describes newly leaf directory created within\n\t\t\tif !isrec || ei.Event() != Create {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif ok, err := ei.(isDirer).isDir(); !ok || err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tt.rec <- ei\n\t\t}(ei)\n\t}\n}\n\n\/\/ internal TODO(rjeczalik)\nfunc (t *nonrecursiveTree) internal(rec <-chan EventInfo) {\n\tfor ei := range rec {\n\t\tvar nd node\n\t\tvar eset = internal\n\t\tt.rw.Lock()\n\t\tt.root.WalkPath(ei.Path(), func(it node, _ bool) error {\n\t\t\tif e := it.Watch[t.rec]; e != 0 && e > eset {\n\t\t\t\teset = e\n\t\t\t}\n\t\t\tnd = it\n\t\t\treturn nil\n\t\t})\n\t\tif eset == internal {\n\t\t\tt.rw.Unlock()\n\t\t\tcontinue\n\t\t}\n\t\terr := nd.Add(ei.Path()).AddDir(t.recFunc(eset))\n\t\tt.rw.Unlock()\n\t\tif err != nil {\n\t\t\tdbgprintf(\"internal(%p) error: %v\", rec, err)\n\t\t}\n\t}\n}\n\n\/\/ watchAdd TODO(rjeczalik)\nfunc (t *nonrecursiveTree) watchAdd(nd node, c chan<- EventInfo, e Event) eventDiff {\n\tif e&recursive != 0 {\n\t\tdiff := nd.Watch.Add(t.rec, e|Create|omit)\n\t\tnd.Watch.Add(c, e)\n\t\treturn diff\n\t}\n\treturn nd.Watch.Add(c, e)\n}\n\n\/\/ watchDelMin TODO(rjeczalik)\nfunc (t *nonrecursiveTree) watchDelMin(min Event, nd node, c chan<- EventInfo, e Event) eventDiff {\n\told, ok := nd.Watch[t.rec]\n\tif ok {\n\t\tnd.Watch[t.rec] = min\n\t}\n\tdiff := nd.Watch.Del(c, e)\n\tif ok {\n\t\tswitch old &^= diff[0] &^ diff[1]; {\n\t\tcase old|internal == internal:\n\t\t\tdelete(nd.Watch, t.rec)\n\t\t\tif set, ok := nd.Watch[nil]; ok && len(nd.Watch) == 1 && set == 0 {\n\t\t\t\tdelete(nd.Watch, nil)\n\t\t\t}\n\t\tdefault:\n\t\t\tnd.Watch.Add(t.rec, old|Create)\n\t\t\tswitch {\n\t\t\tcase diff == none:\n\t\t\tcase diff[1]|Create == diff[0]:\n\t\t\t\tdiff = none\n\t\t\tdefault:\n\t\t\t\tdiff[1] |= Create\n\t\t\t}\n\t\t}\n\t}\n\treturn diff\n}\n\n\/\/ watchDel TODO(rjeczalik)\nfunc (t *nonrecursiveTree) watchDel(nd node, c chan<- EventInfo, e Event) eventDiff {\n\treturn t.watchDelMin(0, nd, c, e)\n}\n\n\/\/ Watch TODO(rjeczalik)\nfunc (t *nonrecursiveTree) Watch(path string, c chan<- EventInfo, events ...Event) error {\n\tif c == nil {\n\t\tpanic(\"notify: Watch using nil channel\")\n\t}\n\t\/\/ Expanding with empty event set is a nop.\n\tif len(events) == 0 {\n\t\treturn nil\n\t}\n\tpath, isrec, err := cleanpath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\teset := joinevents(events)\n\tt.rw.Lock()\n\tdefer t.rw.Unlock()\n\tnd := t.root.Add(path)\n\tif isrec {\n\t\treturn t.watchrec(nd, c, eset|recursive)\n\t}\n\treturn t.watch(nd, c, eset)\n}\n\nfunc (t *nonrecursiveTree) watch(nd node, c chan<- EventInfo, e Event) (err error) {\n\tdiff := nd.Watch.Add(c, e)\n\tswitch {\n\tcase diff == none:\n\t\treturn nil\n\tcase diff[1] == 0:\n\t\t\/\/ TODO(rjeczalik): cleanup this panic after implementation is stable\n\t\tpanic(\"eset is empty: \" + nd.Name)\n\tcase diff[0] == 0:\n\t\terr = t.w.Watch(nd.Name, diff[1])\n\tdefault:\n\t\terr = t.w.Rewatch(nd.Name, diff[0], diff[1])\n\t}\n\tif err != nil {\n\t\tnd.Watch.Del(c, diff.Event())\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (t *nonrecursiveTree) recFunc(e Event) walkFunc {\n\treturn func(nd node) error {\n\t\tswitch diff := nd.Watch.Add(t.rec, e|omit|Create); {\n\t\tcase diff == none:\n\t\tcase diff[1] == 0:\n\t\t\t\/\/ TODO(rjeczalik): cleanup this panic after implementation is stable\n\t\t\tpanic(\"eset is empty: \" + nd.Name)\n\t\tcase diff[0] == 0:\n\t\t\tt.w.Watch(nd.Name, diff[1])\n\t\tdefault:\n\t\t\tt.w.Rewatch(nd.Name, diff[0], diff[1])\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc (t *nonrecursiveTree) watchrec(nd node, c chan<- EventInfo, e Event) error {\n\tvar traverse func(walkFunc) error\n\t\/\/ Non-recursive tree listens on Create event for every recursive\n\t\/\/ watchpoint in order to automagically set a watch for every\n\t\/\/ created directory.\n\tswitch diff := nd.Watch.dryAdd(t.rec, e|Create); {\n\tcase diff == none:\n\t\tt.watchAdd(nd, c, e)\n\t\tnd.Watch.Add(t.rec, e|omit|Create)\n\t\treturn nil\n\tcase diff[1] == 0:\n\t\t\/\/ TODO(rjeczalik): cleanup this panic after implementation is stable\n\t\tpanic(\"eset is empty: \" + nd.Name)\n\tcase diff[0] == 0:\n\t\t\/\/ TODO(rjeczalik): BFS into directories and skip subtree as soon as first\n\t\t\/\/ recursive watchpoint is encountered.\n\t\ttraverse = nd.AddDir\n\tdefault:\n\t\ttraverse = nd.Walk\n\t}\n\t\/\/ TODO(rjeczalik): account every path that failed to be (re)watched\n\t\/\/ and retry.\n\tif err := traverse(t.recFunc(e)); err != nil {\n\t\treturn err\n\t}\n\tt.watchAdd(nd, c, e)\n\treturn nil\n}\n\ntype walkWatchpointFunc func(Event, node) error\n\nfunc (t *nonrecursiveTree) walkWatchpoint(nd node, fn walkWatchpointFunc) error {\n\ttype minode struct {\n\t\tmin Event\n\t\tnd  node\n\t}\n\tmnd := minode{nd: nd}\n\tstack := []minode{mnd}\nTraverse:\n\tfor n := len(stack); n != 0; n = len(stack) {\n\t\tmnd, stack = stack[n-1], stack[:n-1]\n\t\t\/\/ There must be no recursive watchpoints if the node has no watchpoints\n\t\t\/\/ itself (every node in subtree rooted at recursive watchpoints must\n\t\t\/\/ have at least nil (total) and t.rec watchpoints).\n\t\tif len(mnd.nd.Watch) != 0 {\n\t\t\tswitch err := fn(mnd.min, mnd.nd); err {\n\t\t\tcase nil:\n\t\t\tcase errSkip:\n\t\t\t\tcontinue Traverse\n\t\t\tdefault:\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tfor _, nd := range mnd.nd.Child {\n\t\t\tstack = append(stack, minode{mnd.nd.Watch[t.rec], nd})\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Stop TODO(rjeczalik)\nfunc (t *nonrecursiveTree) Stop(c chan<- EventInfo) {\n\tfn := func(min Event, nd node) error {\n\t\t\/\/ TODO(rjeczalik): aggregate watcher errors and retry; in worst case\n\t\t\/\/ forward to the user.\n\t\tswitch diff := t.watchDelMin(min, nd, c, all); {\n\t\tcase diff == none:\n\t\t\treturn nil\n\t\tcase diff[1] == 0:\n\t\t\tt.w.Unwatch(nd.Name)\n\t\tdefault:\n\t\t\tt.w.Rewatch(nd.Name, diff[0], diff[1])\n\t\t}\n\t\treturn nil\n\t}\n\tt.rw.Lock()\n\terr := t.walkWatchpoint(t.root.nd, fn) \/\/ TODO(rjeczalik): store max root per c\n\tt.rw.Unlock()\n\tdbgprintf(\"Stop(%p) error: %v\\n\", c, err)\n}\n\n\/\/ Close TODO(rjeczalik)\nfunc (t *nonrecursiveTree) Close() error {\n\terr := t.w.Close()\n\tclose(t.c)\n\treturn err\n}\n<commit_msg>Handle errors that could be produced in recFunc closure (fixes #76)<commit_after>\/\/ Copyright (c) 2014-2015 The Notify Authors. All rights reserved.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\npackage notify\n\nimport \"sync\"\n\n\/\/ nonrecursiveTree TODO(rjeczalik)\ntype nonrecursiveTree struct {\n\trw   sync.RWMutex \/\/ protects root\n\troot root\n\tw    watcher\n\tc    chan EventInfo\n\trec  chan EventInfo\n}\n\n\/\/ newNonrecursiveTree TODO(rjeczalik)\nfunc newNonrecursiveTree(w watcher, c, rec chan EventInfo) *nonrecursiveTree {\n\tif rec == nil {\n\t\trec = make(chan EventInfo, buffer)\n\t}\n\tt := &nonrecursiveTree{\n\t\troot: root{nd: newnode(\"\")},\n\t\tw:    w,\n\t\tc:    c,\n\t\trec:  rec,\n\t}\n\tgo t.dispatch(c)\n\tgo t.internal(rec)\n\treturn t\n}\n\n\/\/ dispatch TODO(rjeczalik)\nfunc (t *nonrecursiveTree) dispatch(c <-chan EventInfo) {\n\tfor ei := range c {\n\t\tdbgprintf(\"dispatching %v on %q\", ei.Event(), ei.Path())\n\t\tgo func(ei EventInfo) {\n\t\t\tvar nd node\n\t\t\tvar isrec bool\n\t\t\tdir, base := split(ei.Path())\n\t\t\tfn := func(it node, isbase bool) error {\n\t\t\t\tisrec = isrec || it.Watch.IsRecursive()\n\t\t\t\tif isbase {\n\t\t\t\t\tnd = it\n\t\t\t\t} else {\n\t\t\t\t\tit.Watch.Dispatch(ei, recursive)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tt.rw.RLock()\n\t\t\t\/\/ Notify recursive watchpoints found on the path.\n\t\t\tif err := t.root.WalkPath(dir, fn); err != nil {\n\t\t\t\tdbgprint(\"dispatch did not reach leaf:\", err)\n\t\t\t\tt.rw.RUnlock()\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ Notify parent watchpoint.\n\t\t\tnd.Watch.Dispatch(ei, 0)\n\t\t\tisrec = isrec || nd.Watch.IsRecursive()\n\t\t\t\/\/ If leaf watchpoint exists, notify it.\n\t\t\tif nd, ok := nd.Child[base]; ok {\n\t\t\t\tisrec = isrec || nd.Watch.IsRecursive()\n\t\t\t\tnd.Watch.Dispatch(ei, 0)\n\t\t\t}\n\t\t\tt.rw.RUnlock()\n\t\t\t\/\/ If the event describes newly leaf directory created within\n\t\t\tif !isrec || ei.Event() != Create {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif ok, err := ei.(isDirer).isDir(); !ok || err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tt.rec <- ei\n\t\t}(ei)\n\t}\n}\n\n\/\/ internal TODO(rjeczalik)\nfunc (t *nonrecursiveTree) internal(rec <-chan EventInfo) {\n\tfor ei := range rec {\n\t\tvar nd node\n\t\tvar eset = internal\n\t\tt.rw.Lock()\n\t\tt.root.WalkPath(ei.Path(), func(it node, _ bool) error {\n\t\t\tif e := it.Watch[t.rec]; e != 0 && e > eset {\n\t\t\t\teset = e\n\t\t\t}\n\t\t\tnd = it\n\t\t\treturn nil\n\t\t})\n\t\tif eset == internal {\n\t\t\tt.rw.Unlock()\n\t\t\tcontinue\n\t\t}\n\t\terr := nd.Add(ei.Path()).AddDir(t.recFunc(eset))\n\t\tt.rw.Unlock()\n\t\tif err != nil {\n\t\t\tdbgprintf(\"internal(%p) error: %v\", rec, err)\n\t\t}\n\t}\n}\n\n\/\/ watchAdd TODO(rjeczalik)\nfunc (t *nonrecursiveTree) watchAdd(nd node, c chan<- EventInfo, e Event) eventDiff {\n\tif e&recursive != 0 {\n\t\tdiff := nd.Watch.Add(t.rec, e|Create|omit)\n\t\tnd.Watch.Add(c, e)\n\t\treturn diff\n\t}\n\treturn nd.Watch.Add(c, e)\n}\n\n\/\/ watchDelMin TODO(rjeczalik)\nfunc (t *nonrecursiveTree) watchDelMin(min Event, nd node, c chan<- EventInfo, e Event) eventDiff {\n\told, ok := nd.Watch[t.rec]\n\tif ok {\n\t\tnd.Watch[t.rec] = min\n\t}\n\tdiff := nd.Watch.Del(c, e)\n\tif ok {\n\t\tswitch old &^= diff[0] &^ diff[1]; {\n\t\tcase old|internal == internal:\n\t\t\tdelete(nd.Watch, t.rec)\n\t\t\tif set, ok := nd.Watch[nil]; ok && len(nd.Watch) == 1 && set == 0 {\n\t\t\t\tdelete(nd.Watch, nil)\n\t\t\t}\n\t\tdefault:\n\t\t\tnd.Watch.Add(t.rec, old|Create)\n\t\t\tswitch {\n\t\t\tcase diff == none:\n\t\t\tcase diff[1]|Create == diff[0]:\n\t\t\t\tdiff = none\n\t\t\tdefault:\n\t\t\t\tdiff[1] |= Create\n\t\t\t}\n\t\t}\n\t}\n\treturn diff\n}\n\n\/\/ watchDel TODO(rjeczalik)\nfunc (t *nonrecursiveTree) watchDel(nd node, c chan<- EventInfo, e Event) eventDiff {\n\treturn t.watchDelMin(0, nd, c, e)\n}\n\n\/\/ Watch TODO(rjeczalik)\nfunc (t *nonrecursiveTree) Watch(path string, c chan<- EventInfo, events ...Event) error {\n\tif c == nil {\n\t\tpanic(\"notify: Watch using nil channel\")\n\t}\n\t\/\/ Expanding with empty event set is a nop.\n\tif len(events) == 0 {\n\t\treturn nil\n\t}\n\tpath, isrec, err := cleanpath(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\teset := joinevents(events)\n\tt.rw.Lock()\n\tdefer t.rw.Unlock()\n\tnd := t.root.Add(path)\n\tif isrec {\n\t\treturn t.watchrec(nd, c, eset|recursive)\n\t}\n\treturn t.watch(nd, c, eset)\n}\n\nfunc (t *nonrecursiveTree) watch(nd node, c chan<- EventInfo, e Event) (err error) {\n\tdiff := nd.Watch.Add(c, e)\n\tswitch {\n\tcase diff == none:\n\t\treturn nil\n\tcase diff[1] == 0:\n\t\t\/\/ TODO(rjeczalik): cleanup this panic after implementation is stable\n\t\tpanic(\"eset is empty: \" + nd.Name)\n\tcase diff[0] == 0:\n\t\terr = t.w.Watch(nd.Name, diff[1])\n\tdefault:\n\t\terr = t.w.Rewatch(nd.Name, diff[0], diff[1])\n\t}\n\tif err != nil {\n\t\tnd.Watch.Del(c, diff.Event())\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (t *nonrecursiveTree) recFunc(e Event) walkFunc {\n\treturn func(nd node) (err error) {\n\t\tswitch diff := nd.Watch.Add(t.rec, e|omit|Create); {\n\t\tcase diff == none:\n\t\tcase diff[1] == 0:\n\t\t\t\/\/ TODO(rjeczalik): cleanup this panic after implementation is stable\n\t\t\tpanic(\"eset is empty: \" + nd.Name)\n\t\tcase diff[0] == 0:\n\t\t\terr = t.w.Watch(nd.Name, diff[1])\n\t\tdefault:\n\t\t\terr = t.w.Rewatch(nd.Name, diff[0], diff[1])\n\t\t}\n\t\treturn\n\t}\n}\n\nfunc (t *nonrecursiveTree) watchrec(nd node, c chan<- EventInfo, e Event) error {\n\tvar traverse func(walkFunc) error\n\t\/\/ Non-recursive tree listens on Create event for every recursive\n\t\/\/ watchpoint in order to automagically set a watch for every\n\t\/\/ created directory.\n\tswitch diff := nd.Watch.dryAdd(t.rec, e|Create); {\n\tcase diff == none:\n\t\tt.watchAdd(nd, c, e)\n\t\tnd.Watch.Add(t.rec, e|omit|Create)\n\t\treturn nil\n\tcase diff[1] == 0:\n\t\t\/\/ TODO(rjeczalik): cleanup this panic after implementation is stable\n\t\tpanic(\"eset is empty: \" + nd.Name)\n\tcase diff[0] == 0:\n\t\t\/\/ TODO(rjeczalik): BFS into directories and skip subtree as soon as first\n\t\t\/\/ recursive watchpoint is encountered.\n\t\ttraverse = nd.AddDir\n\tdefault:\n\t\ttraverse = nd.Walk\n\t}\n\t\/\/ TODO(rjeczalik): account every path that failed to be (re)watched\n\t\/\/ and retry.\n\tif err := traverse(t.recFunc(e)); err != nil {\n\t\treturn err\n\t}\n\tt.watchAdd(nd, c, e)\n\treturn nil\n}\n\ntype walkWatchpointFunc func(Event, node) error\n\nfunc (t *nonrecursiveTree) walkWatchpoint(nd node, fn walkWatchpointFunc) error {\n\ttype minode struct {\n\t\tmin Event\n\t\tnd  node\n\t}\n\tmnd := minode{nd: nd}\n\tstack := []minode{mnd}\nTraverse:\n\tfor n := len(stack); n != 0; n = len(stack) {\n\t\tmnd, stack = stack[n-1], stack[:n-1]\n\t\t\/\/ There must be no recursive watchpoints if the node has no watchpoints\n\t\t\/\/ itself (every node in subtree rooted at recursive watchpoints must\n\t\t\/\/ have at least nil (total) and t.rec watchpoints).\n\t\tif len(mnd.nd.Watch) != 0 {\n\t\t\tswitch err := fn(mnd.min, mnd.nd); err {\n\t\t\tcase nil:\n\t\t\tcase errSkip:\n\t\t\t\tcontinue Traverse\n\t\t\tdefault:\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tfor _, nd := range mnd.nd.Child {\n\t\t\tstack = append(stack, minode{mnd.nd.Watch[t.rec], nd})\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Stop TODO(rjeczalik)\nfunc (t *nonrecursiveTree) Stop(c chan<- EventInfo) {\n\tfn := func(min Event, nd node) error {\n\t\t\/\/ TODO(rjeczalik): aggregate watcher errors and retry; in worst case\n\t\t\/\/ forward to the user.\n\t\tswitch diff := t.watchDelMin(min, nd, c, all); {\n\t\tcase diff == none:\n\t\t\treturn nil\n\t\tcase diff[1] == 0:\n\t\t\tt.w.Unwatch(nd.Name)\n\t\tdefault:\n\t\t\tt.w.Rewatch(nd.Name, diff[0], diff[1])\n\t\t}\n\t\treturn nil\n\t}\n\tt.rw.Lock()\n\terr := t.walkWatchpoint(t.root.nd, fn) \/\/ TODO(rjeczalik): store max root per c\n\tt.rw.Unlock()\n\tdbgprintf(\"Stop(%p) error: %v\\n\", c, err)\n}\n\n\/\/ Close TODO(rjeczalik)\nfunc (t *nonrecursiveTree) Close() error {\n\terr := t.w.Close()\n\tclose(t.c)\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage mungers\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\tgithubapi \"github.com\/google\/go-github\/github\"\n\t\"k8s.io\/contrib\/mungegithub\/github\"\n)\n\n\/\/ xref k8s.io\/test-infra\/prow\/cmd\/deck\/jobs.go\ntype prowJob struct {\n\tType    string `json:\"type\"`\n\tRepo    string `json:\"repo\"`\n\tRefs    string `json:\"refs\"`\n\tState   string `json:\"state\"`\n\tContext string `json:\"context\"`\n}\n\n\/\/ getSuccessfulBatchJobs reads test results from Prow and returns\n\/\/ all batch jobs that succeeded for the current repo.\nfunc getSuccessfulBatchJobs(repo, url string) ([]prowJob, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tallJobs := []prowJob{}\n\terr = json.Unmarshal(body, &allJobs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tjobs := []prowJob{}\n\tfor _, job := range allJobs {\n\t\tif job.Repo == repo && job.Type == \"batch\" && job.State == \"success\" {\n\t\t\tjobs = append(jobs, job)\n\t\t}\n\t}\n\treturn jobs, nil\n}\n\ntype batchPull struct {\n\tNumber int\n\tSha    string\n}\n\n\/\/ Batch represents a specific merge state:\n\/\/ a base branch and SHA, and the SHAs of each PR merged into it.\ntype Batch struct {\n\tBaseName string\n\tBaseSha  string\n\tPulls    []batchPull\n}\n\nfunc (b *Batch) String() string {\n\tout := b.BaseName + \":\" + b.BaseSha\n\tfor _, pull := range b.Pulls {\n\t\tout += \",\" + strconv.Itoa(pull.Number) + \":\" + pull.Sha\n\t}\n\treturn out\n}\n\n\/\/ batchRefToBatch parses a string into a Batch.\n\/\/ The input is a comma-separated list of colon-separated ref\/sha pairs,\n\/\/ like \"master:abcdef0,123:f00d,456:f00f\".\nfunc batchRefToBatch(batchRef string) (Batch, error) {\n\tbatch := Batch{}\n\tfor i, ref := range strings.Split(batchRef, \",\") {\n\t\tparts := strings.Split(ref, \":\")\n\t\tif len(parts) != 2 {\n\t\t\treturn Batch{}, errors.New(\"bad batchref: \" + batchRef)\n\t\t}\n\t\tif i == 0 {\n\t\t\tbatch.BaseName = parts[0]\n\t\t\tbatch.BaseSha = parts[1]\n\t\t} else {\n\t\t\tnum, err := strconv.ParseInt(parts[0], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn Batch{}, fmt.Errorf(\"bad batchref: %s (%v)\", batchRef, err)\n\t\t\t}\n\t\t\tbatch.Pulls = append(batch.Pulls, batchPull{int(num), parts[1]})\n\t\t}\n\t}\n\treturn batch, nil\n}\n\n\/\/ getCompleteBatches returns a list of Batches that passed all\n\/\/ required tests.\nfunc (sq *SubmitQueue) getCompleteBatches(jobs []prowJob) []Batch {\n\t\/\/ for each batch specifier, a set of successful contexts\n\tbatchContexts := make(map[string]map[string]interface{})\n\tfor _, job := range jobs {\n\t\tif batchContexts[job.Refs] == nil {\n\t\t\tbatchContexts[job.Refs] = make(map[string]interface{})\n\t\t}\n\t\tbatchContexts[job.Refs][job.Context] = nil\n\t}\n\tbatches := []Batch{}\n\tfor batchRef, contexts := range batchContexts {\n\t\tmatch := true\n\t\t\/\/ Did this succeed in all the contexts we want?\n\t\tfor _, ctx := range sq.RequiredStatusContexts {\n\t\t\tif _, ok := contexts[ctx]; !ok {\n\t\t\t\tmatch = false\n\t\t\t}\n\t\t}\n\t\tfor _, ctx := range sq.RequiredRetestContexts {\n\t\t\tif _, ok := contexts[ctx]; !ok {\n\t\t\t\tmatch = false\n\t\t\t}\n\t\t}\n\t\tif match {\n\t\t\tbatch, err := batchRefToBatch(batchRef)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbatches = append(batches, batch)\n\t\t}\n\t}\n\treturn batches\n}\n\n\/\/ batchIntersectsQueue returns whether at least one PR in the batch is queued.\nfunc (sq *SubmitQueue) batchIntersectsQueue(batch Batch) bool {\n\tsq.Lock()\n\tdefer sq.Unlock()\n\tfor _, pull := range batch.Pulls {\n\t\tif _, ok := sq.githubE2EQueue[pull.Number]; ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ matchesCommit determines if the batch can be merged given some commits.\n\/\/ That is, does it contain exactly:\n\/\/ 1) the batch's BaseSha\n\/\/ 2) (optional) merge commits for PRs in the batch\n\/\/ 3) any merged PRs in the batch are sequential from the beginning\n\/\/ The return value is the number of PRs already merged, and any errors.\nfunc (b *Batch) matchesCommits(commits []*githubapi.RepositoryCommit) (int, error) {\n\tif len(commits) == 0 {\n\t\treturn 0, errors.New(\"no commits\")\n\t}\n\n\tshaToPR := make(map[string]int)\n\n\tfor _, pull := range b.Pulls {\n\t\tshaToPR[pull.Sha] = pull.Number\n\t}\n\n\tmatchedPRs := []int{}\n\n\t\/\/ convert the list of commits into a DAG for easy following\n\tdag := make(map[string]*githubapi.RepositoryCommit)\n\tfor _, commit := range commits {\n\t\tdag[*commit.SHA] = commit\n\t}\n\n\tref := *commits[0].SHA\n\tfor {\n\t\tif ref == b.BaseSha {\n\t\t\tbreak \/\/ found the base ref (condition #1)\n\t\t}\n\t\tcommit, ok := dag[ref]\n\t\tif !ok {\n\t\t\treturn 0, errors.New(\"ran out of commits (missing ref \" + ref + \")\")\n\t\t}\n\t\tif len(commit.Parents) == 2 && commit.Message != nil &&\n\t\t\tstrings.HasPrefix(*commit.Message, \"Merge\") {\n\t\t\t\/\/ looks like a merge commit!\n\n\t\t\t\/\/ first parent is the normal branch\n\t\t\tref = *commit.Parents[0].SHA\n\t\t\t\/\/ second parent is the PR\n\t\t\tpr, ok := shaToPR[*commit.Parents[1].SHA]\n\t\t\tif !ok {\n\t\t\t\treturn 0, errors.New(\"Merge of something not in batch\")\n\t\t\t}\n\t\t\tmatchedPRs = append(matchedPRs, pr)\n\t\t} else {\n\t\t\treturn 0, errors.New(\"Unknown non-merge commit \" + ref)\n\t\t}\n\t}\n\n\t\/\/ Now, ensure that the merged PRs are ordered correctly.\n\tfor i, pr := range matchedPRs {\n\t\tif b.Pulls[len(matchedPRs)-1-i].Number != pr {\n\t\t\treturn 0, errors.New(\"Batch PRs merged out-of-order\")\n\t\t}\n\t}\n\treturn len(matchedPRs), nil\n}\n\n\/\/ batchIsApplicable returns whether a successful batch result can be used--\n\/\/ 1) some of the batch is still unmerged and in the queue.\n\/\/ 2) the recent commits are the batch head ref or merges of batch PRs.\n\/\/ 3) all unmerged PRs in the batch are still in the queue.\n\/\/ The return value is the number of PRs already merged, and any errors.\nfunc (sq *SubmitQueue) batchIsApplicable(batch Batch) (int, error) {\n\t\/\/ batch must intersect the queue\n\tif !sq.batchIntersectsQueue(batch) {\n\t\treturn 0, errors.New(\"batch has no PRs in Queue\")\n\t}\n\tcommits, err := sq.githubConfig.GetBranchCommits(batch.BaseName, 100)\n\tif err != nil {\n\t\tglog.Errorf(\"Error getting commits for batchIsApplicable: %v\", err)\n\t\treturn 0, errors.New(\"failed to get branch commits: \" + err.Error())\n\t}\n\treturn batch.matchesCommits(commits)\n}\n\nfunc (sq *SubmitQueue) handleGithubE2EBatchMerge() {\n\trepo := sq.githubConfig.Org + \"\/\" + sq.githubConfig.Project\n\tfor range time.Tick(1 * time.Minute) {\n\t\tjobs, err := getSuccessfulBatchJobs(repo, sq.BatchURL)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Error reading batch jobs from Prow URL %v\", sq.BatchURL)\n\t\t\tcontinue\n\t\t}\n\t\tbatches := sq.getCompleteBatches(jobs)\n\t\tbatchErrors := make(map[string]string)\n\t\tfor _, batch := range batches {\n\t\t\t_, err := sq.batchIsApplicable(batch)\n\t\t\tif err != nil {\n\t\t\t\tbatchErrors[batch.String()] = err.Error()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsq.doBatchMerge(batch)\n\t\t}\n\t\tsq.batchStatus.Error = batchErrors\n\t}\n}\n\n\/\/ doBatchMerge iteratively merges PRs in the batch if possible.\n\/\/ If you modify this, consider modifying doGithubE2EAndMerge too.\nfunc (sq *SubmitQueue) doBatchMerge(batch Batch) {\n\tsq.mergeLock.Lock()\n\tdefer sq.mergeLock.Unlock()\n\n\t\/\/ Test again inside the merge lock, in case some other merge snuck in.\n\tmatch, err := sq.batchIsApplicable(batch)\n\tif err != nil {\n\t\tglog.Errorf(\"unexpected! batchIsApplicable failed after success %v\", err)\n\t\treturn\n\t}\n\tif !sq.e2eStable(true) {\n\t\treturn\n\t}\n\tprs := []*github.MungeObject{}\n\t\/\/ Check entire batch's preconditions first.\n\tfor _, pull := range batch.Pulls[match:] {\n\t\tobj, err := sq.githubConfig.GetObject(pull.Number)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"error getting object for pr #%d: %v\", pull.Number, err)\n\t\t\treturn\n\t\t}\n\t\tif sha, _, ok := obj.GetHeadAndBase(); !ok {\n\t\t\tglog.Errorf(\"error getting pr #%d sha\", pull.Number, err)\n\t\t\treturn\n\t\t} else if sha != pull.Sha {\n\t\t\tglog.Errorf(\"error: batch PR #%d HEAD changed: %s instead of %s\",\n\t\t\t\tsha, pull.Sha)\n\t\t\treturn\n\t\t}\n\t\tif !sq.validForMergeExt(obj, false) {\n\t\t\treturn\n\t\t}\n\t\tprs = append(prs, obj)\n\t}\n\t\/\/ then merge each\n\tfor _, pr := range prs {\n\t\terr := sq.mergePullRequest(pr, mergedBatch)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tatomic.AddInt32(&sq.batchMerges, 1)\n\t}\n}\n<commit_msg>log an explanation line when batch merging, for clarity<commit_after>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage mungers\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\tgithubapi \"github.com\/google\/go-github\/github\"\n\t\"k8s.io\/contrib\/mungegithub\/github\"\n)\n\n\/\/ xref k8s.io\/test-infra\/prow\/cmd\/deck\/jobs.go\ntype prowJob struct {\n\tType    string `json:\"type\"`\n\tRepo    string `json:\"repo\"`\n\tRefs    string `json:\"refs\"`\n\tState   string `json:\"state\"`\n\tContext string `json:\"context\"`\n}\n\n\/\/ getSuccessfulBatchJobs reads test results from Prow and returns\n\/\/ all batch jobs that succeeded for the current repo.\nfunc getSuccessfulBatchJobs(repo, url string) ([]prowJob, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\n\tallJobs := []prowJob{}\n\terr = json.Unmarshal(body, &allJobs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tjobs := []prowJob{}\n\tfor _, job := range allJobs {\n\t\tif job.Repo == repo && job.Type == \"batch\" && job.State == \"success\" {\n\t\t\tjobs = append(jobs, job)\n\t\t}\n\t}\n\treturn jobs, nil\n}\n\ntype batchPull struct {\n\tNumber int\n\tSha    string\n}\n\n\/\/ Batch represents a specific merge state:\n\/\/ a base branch and SHA, and the SHAs of each PR merged into it.\ntype Batch struct {\n\tBaseName string\n\tBaseSha  string\n\tPulls    []batchPull\n}\n\nfunc (b *Batch) String() string {\n\tout := b.BaseName + \":\" + b.BaseSha\n\tfor _, pull := range b.Pulls {\n\t\tout += \",\" + strconv.Itoa(pull.Number) + \":\" + pull.Sha\n\t}\n\treturn out\n}\n\n\/\/ batchRefToBatch parses a string into a Batch.\n\/\/ The input is a comma-separated list of colon-separated ref\/sha pairs,\n\/\/ like \"master:abcdef0,123:f00d,456:f00f\".\nfunc batchRefToBatch(batchRef string) (Batch, error) {\n\tbatch := Batch{}\n\tfor i, ref := range strings.Split(batchRef, \",\") {\n\t\tparts := strings.Split(ref, \":\")\n\t\tif len(parts) != 2 {\n\t\t\treturn Batch{}, errors.New(\"bad batchref: \" + batchRef)\n\t\t}\n\t\tif i == 0 {\n\t\t\tbatch.BaseName = parts[0]\n\t\t\tbatch.BaseSha = parts[1]\n\t\t} else {\n\t\t\tnum, err := strconv.ParseInt(parts[0], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn Batch{}, fmt.Errorf(\"bad batchref: %s (%v)\", batchRef, err)\n\t\t\t}\n\t\t\tbatch.Pulls = append(batch.Pulls, batchPull{int(num), parts[1]})\n\t\t}\n\t}\n\treturn batch, nil\n}\n\n\/\/ getCompleteBatches returns a list of Batches that passed all\n\/\/ required tests.\nfunc (sq *SubmitQueue) getCompleteBatches(jobs []prowJob) []Batch {\n\t\/\/ for each batch specifier, a set of successful contexts\n\tbatchContexts := make(map[string]map[string]interface{})\n\tfor _, job := range jobs {\n\t\tif batchContexts[job.Refs] == nil {\n\t\t\tbatchContexts[job.Refs] = make(map[string]interface{})\n\t\t}\n\t\tbatchContexts[job.Refs][job.Context] = nil\n\t}\n\tbatches := []Batch{}\n\tfor batchRef, contexts := range batchContexts {\n\t\tmatch := true\n\t\t\/\/ Did this succeed in all the contexts we want?\n\t\tfor _, ctx := range sq.RequiredStatusContexts {\n\t\t\tif _, ok := contexts[ctx]; !ok {\n\t\t\t\tmatch = false\n\t\t\t}\n\t\t}\n\t\tfor _, ctx := range sq.RequiredRetestContexts {\n\t\t\tif _, ok := contexts[ctx]; !ok {\n\t\t\t\tmatch = false\n\t\t\t}\n\t\t}\n\t\tif match {\n\t\t\tbatch, err := batchRefToBatch(batchRef)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbatches = append(batches, batch)\n\t\t}\n\t}\n\treturn batches\n}\n\n\/\/ batchIntersectsQueue returns whether at least one PR in the batch is queued.\nfunc (sq *SubmitQueue) batchIntersectsQueue(batch Batch) bool {\n\tsq.Lock()\n\tdefer sq.Unlock()\n\tfor _, pull := range batch.Pulls {\n\t\tif _, ok := sq.githubE2EQueue[pull.Number]; ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ matchesCommit determines if the batch can be merged given some commits.\n\/\/ That is, does it contain exactly:\n\/\/ 1) the batch's BaseSha\n\/\/ 2) (optional) merge commits for PRs in the batch\n\/\/ 3) any merged PRs in the batch are sequential from the beginning\n\/\/ The return value is the number of PRs already merged, and any errors.\nfunc (b *Batch) matchesCommits(commits []*githubapi.RepositoryCommit) (int, error) {\n\tif len(commits) == 0 {\n\t\treturn 0, errors.New(\"no commits\")\n\t}\n\n\tshaToPR := make(map[string]int)\n\n\tfor _, pull := range b.Pulls {\n\t\tshaToPR[pull.Sha] = pull.Number\n\t}\n\n\tmatchedPRs := []int{}\n\n\t\/\/ convert the list of commits into a DAG for easy following\n\tdag := make(map[string]*githubapi.RepositoryCommit)\n\tfor _, commit := range commits {\n\t\tdag[*commit.SHA] = commit\n\t}\n\n\tref := *commits[0].SHA\n\tfor {\n\t\tif ref == b.BaseSha {\n\t\t\tbreak \/\/ found the base ref (condition #1)\n\t\t}\n\t\tcommit, ok := dag[ref]\n\t\tif !ok {\n\t\t\treturn 0, errors.New(\"ran out of commits (missing ref \" + ref + \")\")\n\t\t}\n\t\tif len(commit.Parents) == 2 && commit.Message != nil &&\n\t\t\tstrings.HasPrefix(*commit.Message, \"Merge\") {\n\t\t\t\/\/ looks like a merge commit!\n\n\t\t\t\/\/ first parent is the normal branch\n\t\t\tref = *commit.Parents[0].SHA\n\t\t\t\/\/ second parent is the PR\n\t\t\tpr, ok := shaToPR[*commit.Parents[1].SHA]\n\t\t\tif !ok {\n\t\t\t\treturn 0, errors.New(\"Merge of something not in batch\")\n\t\t\t}\n\t\t\tmatchedPRs = append(matchedPRs, pr)\n\t\t} else {\n\t\t\treturn 0, errors.New(\"Unknown non-merge commit \" + ref)\n\t\t}\n\t}\n\n\t\/\/ Now, ensure that the merged PRs are ordered correctly.\n\tfor i, pr := range matchedPRs {\n\t\tif b.Pulls[len(matchedPRs)-1-i].Number != pr {\n\t\t\treturn 0, errors.New(\"Batch PRs merged out-of-order\")\n\t\t}\n\t}\n\treturn len(matchedPRs), nil\n}\n\n\/\/ batchIsApplicable returns whether a successful batch result can be used--\n\/\/ 1) some of the batch is still unmerged and in the queue.\n\/\/ 2) the recent commits are the batch head ref or merges of batch PRs.\n\/\/ 3) all unmerged PRs in the batch are still in the queue.\n\/\/ The return value is the number of PRs already merged, and any errors.\nfunc (sq *SubmitQueue) batchIsApplicable(batch Batch) (int, error) {\n\t\/\/ batch must intersect the queue\n\tif !sq.batchIntersectsQueue(batch) {\n\t\treturn 0, errors.New(\"batch has no PRs in Queue\")\n\t}\n\tcommits, err := sq.githubConfig.GetBranchCommits(batch.BaseName, 100)\n\tif err != nil {\n\t\tglog.Errorf(\"Error getting commits for batchIsApplicable: %v\", err)\n\t\treturn 0, errors.New(\"failed to get branch commits: \" + err.Error())\n\t}\n\treturn batch.matchesCommits(commits)\n}\n\nfunc (sq *SubmitQueue) handleGithubE2EBatchMerge() {\n\trepo := sq.githubConfig.Org + \"\/\" + sq.githubConfig.Project\n\tfor range time.Tick(1 * time.Minute) {\n\t\tjobs, err := getSuccessfulBatchJobs(repo, sq.BatchURL)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Error reading batch jobs from Prow URL %v\", sq.BatchURL)\n\t\t\tcontinue\n\t\t}\n\t\tbatches := sq.getCompleteBatches(jobs)\n\t\tbatchErrors := make(map[string]string)\n\t\tfor _, batch := range batches {\n\t\t\t_, err := sq.batchIsApplicable(batch)\n\t\t\tif err != nil {\n\t\t\t\tbatchErrors[batch.String()] = err.Error()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsq.doBatchMerge(batch)\n\t\t}\n\t\tsq.batchStatus.Error = batchErrors\n\t}\n}\n\n\/\/ doBatchMerge iteratively merges PRs in the batch if possible.\n\/\/ If you modify this, consider modifying doGithubE2EAndMerge too.\nfunc (sq *SubmitQueue) doBatchMerge(batch Batch) {\n\tsq.mergeLock.Lock()\n\tdefer sq.mergeLock.Unlock()\n\n\t\/\/ Test again inside the merge lock, in case some other merge snuck in.\n\tmatch, err := sq.batchIsApplicable(batch)\n\tif err != nil {\n\t\tglog.Errorf(\"unexpected! batchIsApplicable failed after success %v\", err)\n\t\treturn\n\t}\n\tif !sq.e2eStable(true) {\n\t\treturn\n\t}\n\n\tglog.Infof(\"merging batch: %s\", batch)\n\tprs := []*github.MungeObject{}\n\t\/\/ Check entire batch's preconditions first.\n\tfor _, pull := range batch.Pulls[match:] {\n\t\tobj, err := sq.githubConfig.GetObject(pull.Number)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"error getting object for pr #%d: %v\", pull.Number, err)\n\t\t\treturn\n\t\t}\n\t\tif sha, _, ok := obj.GetHeadAndBase(); !ok {\n\t\t\tglog.Errorf(\"error getting pr #%d sha\", pull.Number, err)\n\t\t\treturn\n\t\t} else if sha != pull.Sha {\n\t\t\tglog.Errorf(\"error: batch PR #%d HEAD changed: %s instead of %s\",\n\t\t\t\tsha, pull.Sha)\n\t\t\treturn\n\t\t}\n\t\tif !sq.validForMergeExt(obj, false) {\n\t\t\treturn\n\t\t}\n\t\tprs = append(prs, obj)\n\t}\n\t\/\/ then merge each\n\tfor _, pr := range prs {\n\t\terr := sq.mergePullRequest(pr, mergedBatch)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tatomic.AddInt32(&sq.batchMerges, 1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>add: wmi\/system builtin collector<commit_after><|endoftext|>"}
{"text":"<commit_before>package brew\n\nimport (\n\t\"bytes\"\n\t\"log\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/goreleaser\/goreleaser\/clients\"\n\t\"github.com\/goreleaser\/goreleaser\/context\"\n\t\"github.com\/goreleaser\/goreleaser\/sha256sum\"\n)\n\nconst formulae = `class {{ .Name }} < Formula\n  desc \"{{ .Desc }}\"\n  homepage \"{{ .Homepage }}\"\n  url \"https:\/\/github.com\/{{ .Repo }}\/releases\/download\/{{ .Tag }}\/{{ .File }}.{{ .Format }}\"\n  version \"{{ .Tag }}\"\n  sha256 \"{{ .SHA256 }}\"\n\n  def install\n    bin.install \"{{ .BinaryName }}\"\n  end\n\n  {{- if .Caveats }}\n\n  def caveats\n    \"{{ .Caveats }}\"\n  end\n  {{- end }}\nend\n`\n\ntype templateData struct {\n\tName, Desc, Homepage, Repo, Tag, BinaryName, Caveats, File, Format, SHA256 string\n}\n\n\/\/ Pipe for brew deployment\ntype Pipe struct{}\n\n\/\/ Description of the pipe\nfunc (Pipe) Description() string {\n\treturn \"Creating homebrew formulae...\"\n}\n\n\/\/ Run the pipe\nfunc (Pipe) Run(ctx *context.Context) error {\n\tif ctx.Config.Brew.Repo == \"\" {\n\t\treturn nil\n\t}\n\tclient := clients.GitHub(*ctx.Token)\n\tpath := filepath.Join(\n\t\tctx.Config.Brew.Folder, ctx.Config.Build.BinaryName+\".rb\",\n\t)\n\n\tlog.Println(\"Updating\", path, \"on\", ctx.Config.Brew.Repo, \"...\")\n\tout, err := buildFormulae(ctx, client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toptions := &github.RepositoryContentFileOptions{\n\t\tCommitter: &github.CommitAuthor{\n\t\t\tName:  github.String(\"goreleaserbot\"),\n\t\t\tEmail: github.String(\"bot@goreleaser\"),\n\t\t},\n\t\tContent: out.Bytes(),\n\t\tMessage: github.String(\n\t\t\tctx.Config.Build.BinaryName + \" version \" + ctx.Git.CurrentTag,\n\t\t),\n\t}\n\n\towner := ctx.BrewRepo.Owner\n\trepo := ctx.BrewRepo.Name\n\tfile, _, res, err := client.Repositories.GetContents(\n\t\towner, repo, path, &github.RepositoryContentGetOptions{},\n\t)\n\tif err != nil && res.StatusCode == 404 {\n\t\t_, _, err = client.Repositories.CreateFile(owner, repo, path, options)\n\t\treturn err\n\t}\n\toptions.SHA = file.SHA\n\t_, _, err = client.Repositories.UpdateFile(owner, repo, path, options)\n\treturn err\n}\n\nfunc buildFormulae(ctx *context.Context, client *github.Client) (bytes.Buffer, error) {\n\tdata, err := dataFor(ctx, client)\n\tif err != nil {\n\t\treturn bytes.Buffer{}, err\n\t}\n\treturn doBuildFormulae(data)\n}\n\nfunc doBuildFormulae(data templateData) (bytes.Buffer, error) {\n\tvar out bytes.Buffer\n\ttmpl, err := template.New(data.BinaryName).Parse(formulae)\n\tif err != nil {\n\t\treturn out, err\n\t}\n\terr = tmpl.Execute(&out, data)\n\treturn out, err\n}\n\nfunc dataFor(ctx *context.Context, client *github.Client) (result templateData, err error) {\n\tvar homepage string\n\tvar description string\n\trep, _, err := client.Repositories.Get(ctx.ReleaseRepo.Owner, ctx.ReleaseRepo.Name)\n\tif err != nil {\n\t\treturn\n\t}\n\tfile := ctx.Archives[\"darwinamd64\"]\n\tsum, err := sha256sum.For(\"dist\/\" + file + \".\" + ctx.Config.Archive.Format)\n\tif err != nil {\n\t\treturn\n\t}\n\tif rep.Homepage != nil && *rep.Homepage != \"\" {\n\t\thomepage = *rep.Homepage\n\t} else {\n\t\thomepage = *rep.HTMLURL\n\t}\n\tif rep.Description == nil {\n\t\tdescription = \"TODO\"\n\t} else {\n\t\tdescription = *rep.Description\n\t}\n\treturn templateData{\n\t\tName:       formulaNameFor(ctx.Config.Build.BinaryName),\n\t\tDesc:       description,\n\t\tHomepage:   homepage,\n\t\tRepo:       ctx.Config.Release.Repo,\n\t\tTag:        ctx.Git.CurrentTag,\n\t\tBinaryName: ctx.Config.Build.BinaryName,\n\t\tCaveats:    ctx.Config.Brew.Caveats,\n\t\tFile:       file,\n\t\tFormat:     ctx.Config.Archive.Format,\n\t\tSHA256:     sum,\n\t}, err\n}\n\nfunc formulaNameFor(name string) string {\n\tname = strings.Replace(name, \"-\", \" \", -1)\n\tname = strings.Replace(name, \"_\", \" \", -1)\n\treturn strings.Replace(strings.Title(name), \" \", \"\", -1)\n}\n<commit_msg>fail brew pipe if there is no darwin_amd64 build<commit_after>package brew\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"log\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/goreleaser\/goreleaser\/clients\"\n\t\"github.com\/goreleaser\/goreleaser\/context\"\n\t\"github.com\/goreleaser\/goreleaser\/sha256sum\"\n)\n\n\/\/ ErrNoDarwin64Build when there is no build for darwin_amd64 (goos doesn't\n\/\/ contain darwin and\/or goarch doesn't contain amd64)\nvar ErrNoDarwin64Build = errors.New(\"brew tap requires a darwin amd64 build\")\n\nconst formulae = `class {{ .Name }} < Formula\n  desc \"{{ .Desc }}\"\n  homepage \"{{ .Homepage }}\"\n  url \"https:\/\/github.com\/{{ .Repo }}\/releases\/download\/{{ .Tag }}\/{{ .File }}.{{ .Format }}\"\n  version \"{{ .Tag }}\"\n  sha256 \"{{ .SHA256 }}\"\n\n  def install\n    bin.install \"{{ .BinaryName }}\"\n  end\n\n  {{- if .Caveats }}\n\n  def caveats\n    \"{{ .Caveats }}\"\n  end\n  {{- end }}\nend\n`\n\ntype templateData struct {\n\tName, Desc, Homepage, Repo, Tag, BinaryName, Caveats, File, Format, SHA256 string\n}\n\n\/\/ Pipe for brew deployment\ntype Pipe struct{}\n\n\/\/ Description of the pipe\nfunc (Pipe) Description() string {\n\treturn \"Creating homebrew formulae...\"\n}\n\n\/\/ Run the pipe\nfunc (Pipe) Run(ctx *context.Context) error {\n\tif ctx.Config.Brew.Repo == \"\" {\n\t\treturn nil\n\t}\n\tclient := clients.GitHub(*ctx.Token)\n\tpath := filepath.Join(\n\t\tctx.Config.Brew.Folder, ctx.Config.Build.BinaryName+\".rb\",\n\t)\n\n\tlog.Println(\"Updating\", path, \"on\", ctx.Config.Brew.Repo, \"...\")\n\tout, err := buildFormulae(ctx, client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\toptions := &github.RepositoryContentFileOptions{\n\t\tCommitter: &github.CommitAuthor{\n\t\t\tName:  github.String(\"goreleaserbot\"),\n\t\t\tEmail: github.String(\"bot@goreleaser\"),\n\t\t},\n\t\tContent: out.Bytes(),\n\t\tMessage: github.String(\n\t\t\tctx.Config.Build.BinaryName + \" version \" + ctx.Git.CurrentTag,\n\t\t),\n\t}\n\n\towner := ctx.BrewRepo.Owner\n\trepo := ctx.BrewRepo.Name\n\tfile, _, res, err := client.Repositories.GetContents(\n\t\towner, repo, path, &github.RepositoryContentGetOptions{},\n\t)\n\tif err != nil && res.StatusCode == 404 {\n\t\t_, _, err = client.Repositories.CreateFile(owner, repo, path, options)\n\t\treturn err\n\t}\n\toptions.SHA = file.SHA\n\t_, _, err = client.Repositories.UpdateFile(owner, repo, path, options)\n\treturn err\n}\n\nfunc buildFormulae(ctx *context.Context, client *github.Client) (bytes.Buffer, error) {\n\tdata, err := dataFor(ctx, client)\n\tif err != nil {\n\t\treturn bytes.Buffer{}, err\n\t}\n\treturn doBuildFormulae(data)\n}\n\nfunc doBuildFormulae(data templateData) (bytes.Buffer, error) {\n\tvar out bytes.Buffer\n\ttmpl, err := template.New(data.BinaryName).Parse(formulae)\n\tif err != nil {\n\t\treturn out, err\n\t}\n\terr = tmpl.Execute(&out, data)\n\treturn out, err\n}\n\nfunc dataFor(ctx *context.Context, client *github.Client) (result templateData, err error) {\n\tvar homepage string\n\tvar description string\n\trep, _, err := client.Repositories.Get(ctx.ReleaseRepo.Owner, ctx.ReleaseRepo.Name)\n\tif err != nil {\n\t\treturn\n\t}\n\tfile := ctx.Archives[\"darwinamd64\"]\n\tif file == \"\" {\n\t\treturn result, ErrNoDarwin64Build\n\t}\n\tsum, err := sha256sum.For(\"dist\/\" + file + \".\" + ctx.Config.Archive.Format)\n\tif err != nil {\n\t\treturn\n\t}\n\tif rep.Homepage != nil && *rep.Homepage != \"\" {\n\t\thomepage = *rep.Homepage\n\t} else {\n\t\thomepage = *rep.HTMLURL\n\t}\n\tif rep.Description == nil {\n\t\tdescription = \"TODO\"\n\t} else {\n\t\tdescription = *rep.Description\n\t}\n\treturn templateData{\n\t\tName:       formulaNameFor(ctx.Config.Build.BinaryName),\n\t\tDesc:       description,\n\t\tHomepage:   homepage,\n\t\tRepo:       ctx.Config.Release.Repo,\n\t\tTag:        ctx.Git.CurrentTag,\n\t\tBinaryName: ctx.Config.Build.BinaryName,\n\t\tCaveats:    ctx.Config.Brew.Caveats,\n\t\tFile:       file,\n\t\tFormat:     ctx.Config.Archive.Format,\n\t\tSHA256:     sum,\n\t}, err\n}\n\nfunc formulaNameFor(name string) string {\n\tname = strings.Replace(name, \"-\", \" \", -1)\n\tname = strings.Replace(name, \"_\", \" \", -1)\n\treturn strings.Replace(strings.Title(name), \" \", \"\", -1)\n}\n<|endoftext|>"}
{"text":"<commit_before>package apps\n\nimport (\n\t\"encoding\/json\"\n\t\"io\"\n\t\"net\/url\"\n\t\"path\"\n\t\"regexp\"\n\n\t\"github.com\/cozy\/cozy-stack\/pkg\/couchdb\"\n\t\"github.com\/cozy\/cozy-stack\/pkg\/vfs\"\n)\n\nvar slugReg = regexp.MustCompile(`^[A-Za-z0-9\\-]+$`)\n\n\/\/ Installer is used to install or update applications.\ntype Installer struct {\n\tfetcher Fetcher\n\tctx     vfs.Context\n\n\tman  *Manifest\n\tsrc  *url.URL\n\tslug string\n\n\terr  error\n\terrc chan error\n\tmanc chan *Manifest\n}\n\n\/\/ InstallerOptions provides the slug name of the application along with the\n\/\/ source URL.\ntype InstallerOptions struct {\n\tSlug      string\n\tSourceURL string\n}\n\n\/\/ Fetcher interface should be implemented by the underlying transport\n\/\/ used to fetch the application data.\ntype Fetcher interface {\n\t\/\/ FetchManifest should returns an io.ReadCloser to read the\n\t\/\/ manifest data\n\tFetchManifest(src *url.URL) (io.ReadCloser, error)\n\t\/\/ Fetch should download the application and install it in the given\n\t\/\/ directory.\n\tFetch(src *url.URL, appDir string) error\n}\n\n\/\/ NewInstaller creates a new Installer\nfunc NewInstaller(ctx vfs.Context, opts *InstallerOptions) (*Installer, error) {\n\tslug := opts.Slug\n\tif slug == \"\" || !slugReg.MatchString(slug) {\n\t\treturn nil, ErrInvalidSlugName\n\t}\n\n\tman, err := GetBySlug(ctx, slug)\n\tif err != nil && !couchdb.IsNotFoundError(err) {\n\t\treturn nil, err\n\t}\n\n\tvar src *url.URL\n\tif opts.SourceURL != \"\" {\n\t\tsrc, err = url.Parse(opts.SourceURL)\n\t} else if man != nil {\n\t\tsrc, err = url.Parse(man.Source)\n\t} else {\n\t\terr = ErrNotSupportedSource\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar fetcher Fetcher\n\tswitch src.Scheme {\n\tcase \"git\":\n\t\tfetcher = newGitFetcher(ctx)\n\tdefault:\n\t\treturn nil, ErrNotSupportedSource\n\t}\n\n\tinst := &Installer{\n\t\tfetcher: fetcher,\n\t\tctx:     ctx,\n\t\tsrc:     src,\n\t\tslug:    slug,\n\t\tman:     man,\n\t\terrc:    make(chan error),\n\t\tmanc:    make(chan *Manifest, 1),\n\t}\n\n\treturn inst, nil\n}\n\n\/\/ InstallOrUpdate will install the application linked to the installer. If the\n\/\/ application is already installed, it will try to upgrade it. It will report\n\/\/ its progress or error (see Poll method).\nfunc (i *Installer) InstallOrUpdate() {\n\tdefer i.endOfProc()\n\n\tif i.man == nil {\n\t\ti.man, i.err = i.install()\n\t\treturn\n\t}\n\n\tstate := i.man.State\n\tif state != Ready && state != Errored {\n\t\ti.man, i.err = nil, ErrBadState\n\t\treturn\n\t}\n\n\ti.man, i.err = i.update()\n\treturn\n}\n\nfunc (i *Installer) endOfProc() {\n\tman, err := i.man, i.err\n\tif man == nil || err == ErrBadState {\n\t\ti.errc <- err\n\t\treturn\n\t}\n\tif err != nil {\n\t\tman.State = Errored\n\t\tman.Error = err.Error()\n\t\tupdateManifest(i.ctx, man)\n\t\ti.errc <- err\n\t\treturn\n\t}\n\tman.State = Ready\n\tupdateManifest(i.ctx, man)\n\ti.manc <- i.man\n}\n\nfunc (i *Installer) install() (*Manifest, error) {\n\tman := &Manifest{}\n\tif err := i.ReadManifest(Installing, &man); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := createManifest(i.ctx, man); err != nil {\n\t\treturn nil, err\n\t}\n\n\ti.manc <- man\n\n\tappdir := i.appDir()\n\tif _, err := vfs.MkdirAll(i.ctx, appdir, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := i.fetcher.Fetch(i.src, appdir); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn man, nil\n}\n\nfunc (i *Installer) update() (*Manifest, error) {\n\tman := i.man\n\tversion := man.Version\n\n\tif err := i.ReadManifest(Upgrading, &man); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif man.Version == version {\n\t\treturn man, nil\n\t}\n\n\tif err := updateManifest(i.ctx, man); err != nil {\n\t\treturn nil, err\n\t}\n\n\ti.manc <- man\n\n\tappdir := i.appDir()\n\tif err := i.fetcher.Fetch(i.src, appdir); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn man, nil\n}\n\n\/\/ ReadManifest will fetch the manifest and read its JSON content into the\n\/\/ passed manifest pointer.\n\/\/\n\/\/ The State field of the manifest will be set to the specified state.\nfunc (i *Installer) ReadManifest(state State, man **Manifest) error {\n\tr, err := i.fetcher.FetchManifest(i.src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\n\terr = json.NewDecoder(io.LimitReader(r, ManifestMaxSize)).Decode(man)\n\tif err != nil {\n\t\treturn ErrBadManifest\n\t}\n\n\t(*man).Slug = i.slug\n\t(*man).Source = i.src.String()\n\t(*man).State = state\n\treturn nil\n}\n\nfunc (i *Installer) appDir() string {\n\treturn path.Join(vfs.AppsDirName, i.slug)\n}\n\n\/\/ Poll should be used to monitor the progress of the Installer.\nfunc (i *Installer) Poll() (man *Manifest, done bool, err error) {\n\tselect {\n\tcase man = <-i.manc:\n\t\tdone = man.State == Ready\n\t\treturn\n\tcase err = <-i.errc:\n\t\treturn\n\t}\n}\n\nfunc updateManifest(db couchdb.Database, man *Manifest) error {\n\treturn couchdb.UpdateDoc(db, man)\n}\n\nfunc createManifest(db couchdb.Database, man *Manifest) error {\n\treturn couchdb.CreateNamedDoc(db, man)\n}\n<commit_msg>Return the fetched manifest even if an error occur while upgrading\/installing<commit_after>package apps\n\nimport (\n\t\"encoding\/json\"\n\t\"io\"\n\t\"net\/url\"\n\t\"path\"\n\t\"regexp\"\n\n\t\"github.com\/cozy\/cozy-stack\/pkg\/couchdb\"\n\t\"github.com\/cozy\/cozy-stack\/pkg\/vfs\"\n)\n\nvar slugReg = regexp.MustCompile(`^[A-Za-z0-9\\-]+$`)\n\n\/\/ Installer is used to install or update applications.\ntype Installer struct {\n\tfetcher Fetcher\n\tctx     vfs.Context\n\n\tman  *Manifest\n\tsrc  *url.URL\n\tslug string\n\n\terr  error\n\terrc chan error\n\tmanc chan *Manifest\n}\n\n\/\/ InstallerOptions provides the slug name of the application along with the\n\/\/ source URL.\ntype InstallerOptions struct {\n\tSlug      string\n\tSourceURL string\n}\n\n\/\/ Fetcher interface should be implemented by the underlying transport\n\/\/ used to fetch the application data.\ntype Fetcher interface {\n\t\/\/ FetchManifest should returns an io.ReadCloser to read the\n\t\/\/ manifest data\n\tFetchManifest(src *url.URL) (io.ReadCloser, error)\n\t\/\/ Fetch should download the application and install it in the given\n\t\/\/ directory.\n\tFetch(src *url.URL, appDir string) error\n}\n\n\/\/ NewInstaller creates a new Installer\nfunc NewInstaller(ctx vfs.Context, opts *InstallerOptions) (*Installer, error) {\n\tslug := opts.Slug\n\tif slug == \"\" || !slugReg.MatchString(slug) {\n\t\treturn nil, ErrInvalidSlugName\n\t}\n\n\tman, err := GetBySlug(ctx, slug)\n\tif err != nil && !couchdb.IsNotFoundError(err) {\n\t\treturn nil, err\n\t}\n\n\tvar src *url.URL\n\tif opts.SourceURL != \"\" {\n\t\tsrc, err = url.Parse(opts.SourceURL)\n\t} else if man != nil {\n\t\tsrc, err = url.Parse(man.Source)\n\t} else {\n\t\terr = ErrNotSupportedSource\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar fetcher Fetcher\n\tswitch src.Scheme {\n\tcase \"git\":\n\t\tfetcher = newGitFetcher(ctx)\n\tdefault:\n\t\treturn nil, ErrNotSupportedSource\n\t}\n\n\tinst := &Installer{\n\t\tfetcher: fetcher,\n\t\tctx:     ctx,\n\t\tsrc:     src,\n\t\tslug:    slug,\n\t\tman:     man,\n\t\terrc:    make(chan error),\n\t\tmanc:    make(chan *Manifest, 1),\n\t}\n\n\treturn inst, nil\n}\n\n\/\/ InstallOrUpdate will install the application linked to the installer. If the\n\/\/ application is already installed, it will try to upgrade it. It will report\n\/\/ its progress or error (see Poll method).\nfunc (i *Installer) InstallOrUpdate() {\n\tdefer i.endOfProc()\n\n\tif i.man == nil {\n\t\ti.man, i.err = i.install()\n\t\treturn\n\t}\n\n\tstate := i.man.State\n\tif state != Ready && state != Errored {\n\t\ti.man, i.err = nil, ErrBadState\n\t\treturn\n\t}\n\n\ti.man, i.err = i.update()\n\treturn\n}\n\nfunc (i *Installer) endOfProc() {\n\tman, err := i.man, i.err\n\tif man == nil || err == ErrBadState {\n\t\ti.errc <- err\n\t\treturn\n\t}\n\tif err != nil {\n\t\tman.State = Errored\n\t\tman.Error = err.Error()\n\t\tupdateManifest(i.ctx, man)\n\t\ti.errc <- err\n\t\treturn\n\t}\n\tman.State = Ready\n\tupdateManifest(i.ctx, man)\n\ti.manc <- i.man\n}\n\n\/\/ install will perform the installation of an application. It returns the\n\/\/ freshly fetched manifest from the source along with a possible error in case\n\/\/ the installation went wrong.\n\/\/\n\/\/ Note that the fetched manifest is returned even if an error occured while\n\/\/ upgrading.\nfunc (i *Installer) install() (*Manifest, error) {\n\tman := &Manifest{}\n\tif err := i.ReadManifest(Installing, &man); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := createManifest(i.ctx, man); err != nil {\n\t\treturn man, err\n\t}\n\n\ti.manc <- man\n\n\tappdir := i.appDir()\n\tif _, err := vfs.MkdirAll(i.ctx, appdir, nil); err != nil {\n\t\treturn man, err\n\t}\n\n\tif err := i.fetcher.Fetch(i.src, appdir); err != nil {\n\t\treturn man, err\n\t}\n\n\treturn man, nil\n}\n\n\/\/ update will perform the update of an already installed application. It\n\/\/ returns the freshly fetched manifest from the source along with a possible\n\/\/ error in case the update went wrong.\n\/\/\n\/\/ Note that the fetched manifest is returned even if an error occured while\n\/\/ upgrading.\nfunc (i *Installer) update() (*Manifest, error) {\n\tman := i.man\n\tversion := man.Version\n\n\tif err := i.ReadManifest(Upgrading, &man); err != nil {\n\t\treturn man, err\n\t}\n\n\tif man.Version == version {\n\t\treturn man, nil\n\t}\n\n\tif err := updateManifest(i.ctx, man); err != nil {\n\t\treturn man, err\n\t}\n\n\ti.manc <- man\n\n\tappdir := i.appDir()\n\tif err := i.fetcher.Fetch(i.src, appdir); err != nil {\n\t\treturn man, err\n\t}\n\n\treturn man, nil\n}\n\n\/\/ ReadManifest will fetch the manifest and read its JSON content into the\n\/\/ passed manifest pointer.\n\/\/\n\/\/ The State field of the manifest will be set to the specified state.\nfunc (i *Installer) ReadManifest(state State, man **Manifest) error {\n\tr, err := i.fetcher.FetchManifest(i.src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\n\terr = json.NewDecoder(io.LimitReader(r, ManifestMaxSize)).Decode(man)\n\tif err != nil {\n\t\treturn ErrBadManifest\n\t}\n\n\t(*man).Slug = i.slug\n\t(*man).Source = i.src.String()\n\t(*man).State = state\n\treturn nil\n}\n\nfunc (i *Installer) appDir() string {\n\treturn path.Join(vfs.AppsDirName, i.slug)\n}\n\n\/\/ Poll should be used to monitor the progress of the Installer.\nfunc (i *Installer) Poll() (man *Manifest, done bool, err error) {\n\tselect {\n\tcase man = <-i.manc:\n\t\tdone = man.State == Ready\n\t\treturn\n\tcase err = <-i.errc:\n\t\treturn\n\t}\n}\n\nfunc updateManifest(db couchdb.Database, man *Manifest) error {\n\treturn couchdb.UpdateDoc(db, man)\n}\n\nfunc createManifest(db couchdb.Database, man *Manifest) error {\n\treturn couchdb.CreateNamedDoc(db, man)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package tree benchmarks\n\/\/ All benchmarks where down on a 13inch macbook pro with a 2.5 GHz Intel Core i5 processor and 8gb of memory\n\/\/ BenchmarkTreeToArr1000-4        2000000000               0.00 ns\/op\n\/\/ BenchmarkTreeToArr10000-4       2000000000               0.01 ns\/op\n\/\/ BenchmarkTreeToArr100000-4      1000000000               0.26 ns\/op\n\/\/ BenchmarkTreeToArr1000000-4            1        3997007417 ns\/op\n\/\/ BenchmarkEdgeCount1000-4        2000000000               0.00 ns\/op\n\/\/ BenchmarkEdgeCount10000-4       2000000000               0.01 ns\/op\n\/\/ BenchmarkEdgeCount100000-4      2000000000               0.15 ns\/op\n\/\/ BenchmarkEdgeCount1000000-4            1        3882999625 ns\/op\n\/\/ BenchmarkRootShift1000-4        2000000000               0.00 ns\/op\n\/\/ BenchmarkRootShift10000-4       1000000000               0.02 ns\/op\n\/\/ BenchmarkRootShift100000-4      2000000000               0.21 ns\/op\n\/\/ BenchmarkRootShift1000000-4            1        7592046369 ns\/op\n\/\/ BenchmarkNewTree1000-4          2000000000               0.00 ns\/op\n\/\/ BenchmarkNewTree10000-4         2000000000               0.01 ns\/op\n\/\/ BenchmarkNewTree100000-4        2000000000               0.09 ns\/op\n\/\/ BenchmarkNewTree1000000-4              1        3040027533 ns\/op\npackage tree\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ Node is a fudemental part of what makes a tree a tree. Many Nodes creates a tree\ntype Node struct {\n\tLeft  *Node\n\tRight *Node\n\tData  int\n}\n\n\/\/ Tree basic tree structure.. Root is of type Node,\ntype Tree struct {\n\tRoot      *Node\n\tTotal     int\n\tNodeCount int\n}\n\nvar (\n\t\/\/ ErrPositiveIntegers reports that only positive intergers may be added to the tree\n\tErrPositiveIntegers = fmt.Errorf(\"only postive integers may be added\")\n\t\/\/ ErrNodeNotFound reports that a Node wasn't found\n\tErrNodeNotFound = fmt.Errorf(\"Node not found\")\n)\n\n\/\/ NewTree ...\nfunc NewTree() *Tree {\n\treturn new(Tree)\n}\n\n\/\/ FindNode ...\nfunc (t *Tree) FindNode(data int) (err error) {\n\tnewNode := Node{\n\t\tData: data,\n\t}\n\tif t.Root != nil {\n\t\tif t.findNode(t.Root, newNode) != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn ErrNodeNotFound\n}\n\nfunc (t *Tree) findNode(search *Node, target Node) *Node {\n\tvar returnNode *Node\n\tif search == nil {\n\t\treturn returnNode\n\t}\n\tif search.Data == target.Data {\n\t\treturn search\n\t}\n\treturnNode = t.findNode(search.Left, target)\n\tif returnNode == nil {\n\t\treturnNode = t.findNode(search.Right, target)\n\t}\n\treturn returnNode\n}\n\n\/\/ Add appends a new node to a branch in a balanced manner\nfunc (t *Tree) Add(data int) (err error) {\n\tt.Total += data\n\tt.NodeCount++\n\tif data < 0 {\n\t\treturn ErrPositiveIntegers\n\t}\n\tNodeToAdd := Node{\n\t\tData: data,\n\t}\n\tif t.Root == nil {\n\t\tt.Root = new(Node)\n\t}\n\tif t.Root.Data == 0 {\n\t\tt.Root = &NodeToAdd\n\t\treturn\n\t}\n\tt.add(t.Root, NodeToAdd)\n\treturn\n}\n\nfunc (t *Tree) add(oldNode *Node, newNode Node) {\n\tif newNode.Data < oldNode.Data {\n\t\tif oldNode.Left == nil {\n\t\t\toldNode.Left = &newNode\n\t\t} else {\n\t\t\tt.add(oldNode.Left, newNode)\n\t\t}\n\t} else if newNode.Data > oldNode.Data {\n\t\tif oldNode.Right == nil {\n\t\t\toldNode.Right = &newNode\n\t\t} else {\n\t\t\tt.add(oldNode.Right, newNode)\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ InOrderTraversal prints out the values in order\nfunc (t *Tree) InOrderTraversal() {\n\tif t.Root != nil {\n\t\tcurrentNode := t.Root\n\t\tif currentNode.Left == nil && currentNode.Right == nil {\n\t\t\tfmt.Println(currentNode.Data)\n\t\t} else {\n\t\t\tt.inOrderTraversal(currentNode)\n\t\t}\n\t}\n\treturn\n}\n\nfunc (t *Tree) inOrderTraversal(n *Node) {\n\tif n.Left != nil {\n\t\tt.inOrderTraversal(n.Left)\n\t}\n\tfmt.Println(n.Data)\n\tif n.Right != nil {\n\t\tt.inOrderTraversal(n.Right)\n\t}\n\treturn\n}\n\n\/\/ Traversal prints out the values by branch side, left, right, ect...\nfunc (t *Tree) Traversal() {\n\tif t.Root != nil {\n\t\tcurrentNode := t.Root\n\t\tif currentNode.Left == nil && currentNode.Right == nil {\n\t\t\tfmt.Println(currentNode.Data)\n\t\t} else {\n\t\t\tt.traversal(currentNode)\n\t\t}\n\t}\n\treturn\n}\n\nfunc (t *Tree) traversal(n *Node) {\n\tfmt.Println(n.Data)\n\tif n.Left != nil {\n\t\tt.traversal(n.Left)\n\t}\n\tif n.Right != nil {\n\t\tt.traversal(n.Right)\n\t}\n\treturn\n}\n\n\/\/ Sum added up all the values stored in the Nodes.. It is a redundant function because total value is kept as a Tree\n\/\/ value\nfunc (t *Tree) Sum() (total int) {\n\tvar wg sync.WaitGroup\n\tc := make(chan int, 100)\n\tif t.Root != nil {\n\t\tcurrentNode := t.Root\n\t\tif currentNode.Left == nil && currentNode.Right == nil {\n\t\t\treturn 1\n\t\t}\n\t\twg.Add(1)\n\t\tt.sum(currentNode, c, &wg)\n\t}\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(c)\n\t}()\n\tfor n := range c {\n\t\ttotal += n\n\t}\n\treturn total\n}\n\nfunc (t *Tree) sum(n *Node, counter chan int, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tif n.Left != nil {\n\t\twg.Add(1)\n\t\tgo t.sum(n.Left, counter, wg)\n\t}\n\tcounter <- n.Data\n\tif n.Right != nil {\n\t\twg.Add(1)\n\t\tgo t.sum(n.Right, counter, wg)\n\t}\n\treturn\n}\n\n\/\/ CountEdges returns the number of edges the tree contains\nfunc (t *Tree) CountEdges() (edges int) {\n\tvar wg sync.WaitGroup\n\tc := make(chan int, 100)\n\tif t.Root != nil {\n\t\tcurrentNode := t.Root\n\t\tif currentNode.Left == nil && currentNode.Right == nil {\n\t\t\treturn 1\n\t\t}\n\t\twg.Add(1)\n\t\tt.countEdges(currentNode, c, &wg)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(c)\n\t}()\n\tfor n := range c {\n\t\tedges += n\n\t}\n\treturn edges\n}\n\nfunc (t *Tree) countEdges(n *Node, counter chan int, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tif n.Left != nil {\n\t\twg.Add(1)\n\t\tgo t.countEdges(n.Left, counter, wg)\n\t}\n\tcounter <- 1\n\tif n.Right != nil {\n\t\twg.Add(1)\n\t\tgo t.countEdges(n.Right, counter, wg)\n\t}\n\treturn\n}\n\n\/\/ GenerateRandomTree uses time (time.Now().Unix()) to create enthorpy for a source of random numbers to append to the Tree\nfunc (t *Tree) GenerateRandomTree(numberOfNodesToCreate int) (err error) {\n\tif numberOfNodesToCreate < 0 {\n\t\treturn ErrPositiveIntegers\n\t}\n\tu := time.Now()\n\tsource := rand.NewSource(u.Unix())\n\tr := rand.New(source)\n\tarr := r.Perm(numberOfNodesToCreate)\n\tfor _, a := range arr {\n\t\tt.Add(a)\n\t}\n\treturn\n}\n\n\/\/ GetRootData returns the data stored at the root, however this does not return the root Node\nfunc (t *Tree) GetRootData() int {\n\treturn t.Root.Data\n}\n\n\/\/ GetTreeTotal returns the sum of the collecitve nodes on the Tree\nfunc (t *Tree) GetTreeTotal() int {\n\treturn t.Total\n}\n\n\/\/ TreeToArray converts to the into an int slice\nfunc (t *Tree) TreeToArray() []int {\n\tvar wg sync.WaitGroup\n\tc := make(chan int, 100)\n\tarr := make([]int, 0, t.NodeCount)\n\tif t.Root != nil {\n\t\tcurrentNode := t.Root\n\t\tif currentNode.Left == nil && currentNode.Right == nil {\n\t\t\treturn []int{currentNode.Data}\n\t\t}\n\t\twg.Add(1)\n\t\tt.traversalGetVals(currentNode, c, &wg)\n\t}\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(c)\n\t}()\n\tfor n := range c {\n\t\tarr = append(arr, n)\n\t}\n\treturn arr\n}\n\nfunc (t *Tree) traversalGetVals(n *Node, c chan int, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tif n.Left != nil {\n\t\tc <- n.Left.Data\n\t\twg.Add(1)\n\t\tgo t.traversalGetVals(n.Left, c, wg)\n\t}\n\tif n.Right != nil {\n\t\tc <- n.Right.Data\n\t\twg.Add(1)\n\t\tgo t.traversalGetVals(n.Right, c, wg)\n\t}\n\treturn\n}\n\n\/\/ ShiftRoot rebuilds the tree with a new root\nfunc (t *Tree) ShiftRoot(newRoot int) {\n\tarr := t.TreeToArray()\n\tn := Tree{}\n\tn.Add(newRoot)\n\tfor _, i := range arr {\n\t\tn.Add(i)\n\t}\n\t*t = n\n}\n\n\/\/ PrintTree uses json.MarshalIndent() to print the Tree in an organized fashion, which can then be analysized as a JSON\n\/\/ object\nfunc (t *Tree) PrintTree() {\n\tb, err := json.MarshalIndent(t, \"\", \" \")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(string(b))\n}\n<commit_msg>overview<commit_after>\/\/ Package tree implements a basic balanced binary tree\npackage tree\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ Node is a fudemental part of what makes a tree a tree. Many Nodes creates a tree\ntype Node struct {\n\tLeft  *Node\n\tRight *Node\n\tData  int\n}\n\n\/\/ Tree basic tree structure.. Root is of type Node,\ntype Tree struct {\n\tRoot      *Node\n\tTotal     int\n\tNodeCount int\n}\n\nvar (\n\t\/*\n\t\tAll benchmarks where down on a 13inch macbook pro with a 2.5 GHz Intel Core i5 processor and 8gb of memory\n\t\tBenchmarkTreeToArr1000-4        2000000000               0.00 ns\/op\n\t\tBenchmarkTreeToArr10000-4       2000000000               0.01 ns\/op\n\t\tBenchmarkTreeToArr100000-4      1000000000               0.26 ns\/op\n\t\tBenchmarkTreeToArr1000000-4            1        3997007417 ns\/op\n\t\tBenchmarkEdgeCount1000-4        2000000000               0.00 ns\/op\n\t\tBenchmarkEdgeCount10000-4       2000000000               0.01 ns\/op\n\t\tBenchmarkEdgeCount100000-4      2000000000               0.15 ns\/op\n\t\tBenchmarkEdgeCount1000000-4            1        3882999625 ns\/op\n\t\tBenchmarkRootShift1000-4        2000000000               0.00 ns\/op\n\t\tBenchmarkRootShift10000-4       1000000000               0.02 ns\/op\n\t\tBenchmarkRootShift100000-4      2000000000               0.21 ns\/op\n\t\tBenchmarkRootShift1000000-4            1        7592046369 ns\/op\n\t\tBenchmarkNewTree1000-4          2000000000               0.00 ns\/op\n\t\tBenchmarkNewTree10000-4         2000000000               0.01 ns\/op\n\t\tBenchmarkNewTree100000-4        2000000000               0.09 ns\/op\n\t\tBenchmarkNewTree1000000-4              1        3040027533 ns\/op\n\t*\/\n\n\t\/\/ ErrPositiveIntegers reports that only positive intergers may be added to the tree\n\tErrPositiveIntegers = fmt.Errorf(\"only postive integers may be added\")\n\t\/\/ ErrNodeNotFound reports that a Node wasn't found\n\tErrNodeNotFound = fmt.Errorf(\"Node not found\")\n)\n\n\/\/ NewTree ...\nfunc NewTree() *Tree {\n\treturn new(Tree)\n}\n\n\/\/ FindNode ...\nfunc (t *Tree) FindNode(data int) (err error) {\n\tnewNode := Node{\n\t\tData: data,\n\t}\n\tif t.Root != nil {\n\t\tif t.findNode(t.Root, newNode) != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn ErrNodeNotFound\n}\n\nfunc (t *Tree) findNode(search *Node, target Node) *Node {\n\tvar returnNode *Node\n\tif search == nil {\n\t\treturn returnNode\n\t}\n\tif search.Data == target.Data {\n\t\treturn search\n\t}\n\treturnNode = t.findNode(search.Left, target)\n\tif returnNode == nil {\n\t\treturnNode = t.findNode(search.Right, target)\n\t}\n\treturn returnNode\n}\n\n\/\/ Add appends a new node to a branch in a balanced manner\nfunc (t *Tree) Add(data int) (err error) {\n\tt.Total += data\n\tt.NodeCount++\n\tif data < 0 {\n\t\treturn ErrPositiveIntegers\n\t}\n\tNodeToAdd := Node{\n\t\tData: data,\n\t}\n\tif t.Root == nil {\n\t\tt.Root = new(Node)\n\t}\n\tif t.Root.Data == 0 {\n\t\tt.Root = &NodeToAdd\n\t\treturn\n\t}\n\tt.add(t.Root, NodeToAdd)\n\treturn\n}\n\nfunc (t *Tree) add(oldNode *Node, newNode Node) {\n\tif newNode.Data < oldNode.Data {\n\t\tif oldNode.Left == nil {\n\t\t\toldNode.Left = &newNode\n\t\t} else {\n\t\t\tt.add(oldNode.Left, newNode)\n\t\t}\n\t} else if newNode.Data > oldNode.Data {\n\t\tif oldNode.Right == nil {\n\t\t\toldNode.Right = &newNode\n\t\t} else {\n\t\t\tt.add(oldNode.Right, newNode)\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ InOrderTraversal prints out the values in order\nfunc (t *Tree) InOrderTraversal() {\n\tif t.Root != nil {\n\t\tcurrentNode := t.Root\n\t\tif currentNode.Left == nil && currentNode.Right == nil {\n\t\t\tfmt.Println(currentNode.Data)\n\t\t} else {\n\t\t\tt.inOrderTraversal(currentNode)\n\t\t}\n\t}\n\treturn\n}\n\nfunc (t *Tree) inOrderTraversal(n *Node) {\n\tif n.Left != nil {\n\t\tt.inOrderTraversal(n.Left)\n\t}\n\tfmt.Println(n.Data)\n\tif n.Right != nil {\n\t\tt.inOrderTraversal(n.Right)\n\t}\n\treturn\n}\n\n\/\/ Traversal prints out the values by branch side, left, right, ect...\nfunc (t *Tree) Traversal() {\n\tif t.Root != nil {\n\t\tcurrentNode := t.Root\n\t\tif currentNode.Left == nil && currentNode.Right == nil {\n\t\t\tfmt.Println(currentNode.Data)\n\t\t} else {\n\t\t\tt.traversal(currentNode)\n\t\t}\n\t}\n\treturn\n}\n\nfunc (t *Tree) traversal(n *Node) {\n\tfmt.Println(n.Data)\n\tif n.Left != nil {\n\t\tt.traversal(n.Left)\n\t}\n\tif n.Right != nil {\n\t\tt.traversal(n.Right)\n\t}\n\treturn\n}\n\n\/\/ Sum added up all the values stored in the Nodes.. It is a redundant function because total value is kept as a Tree\n\/\/ value\nfunc (t *Tree) Sum() (total int) {\n\tvar wg sync.WaitGroup\n\tc := make(chan int, 100)\n\tif t.Root != nil {\n\t\tcurrentNode := t.Root\n\t\tif currentNode.Left == nil && currentNode.Right == nil {\n\t\t\treturn 1\n\t\t}\n\t\twg.Add(1)\n\t\tt.sum(currentNode, c, &wg)\n\t}\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(c)\n\t}()\n\tfor n := range c {\n\t\ttotal += n\n\t}\n\treturn total\n}\n\nfunc (t *Tree) sum(n *Node, counter chan int, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tif n.Left != nil {\n\t\twg.Add(1)\n\t\tgo t.sum(n.Left, counter, wg)\n\t}\n\tcounter <- n.Data\n\tif n.Right != nil {\n\t\twg.Add(1)\n\t\tgo t.sum(n.Right, counter, wg)\n\t}\n\treturn\n}\n\n\/\/ CountEdges returns the number of edges the tree contains\nfunc (t *Tree) CountEdges() (edges int) {\n\tvar wg sync.WaitGroup\n\tc := make(chan int, 100)\n\tif t.Root != nil {\n\t\tcurrentNode := t.Root\n\t\tif currentNode.Left == nil && currentNode.Right == nil {\n\t\t\treturn 1\n\t\t}\n\t\twg.Add(1)\n\t\tt.countEdges(currentNode, c, &wg)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(c)\n\t}()\n\tfor n := range c {\n\t\tedges += n\n\t}\n\treturn edges\n}\n\nfunc (t *Tree) countEdges(n *Node, counter chan int, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tif n.Left != nil {\n\t\twg.Add(1)\n\t\tgo t.countEdges(n.Left, counter, wg)\n\t}\n\tcounter <- 1\n\tif n.Right != nil {\n\t\twg.Add(1)\n\t\tgo t.countEdges(n.Right, counter, wg)\n\t}\n\treturn\n}\n\n\/\/ GenerateRandomTree uses time (time.Now().Unix()) to create enthorpy for a source of random numbers to append to the Tree\nfunc (t *Tree) GenerateRandomTree(numberOfNodesToCreate int) (err error) {\n\tif numberOfNodesToCreate < 0 {\n\t\treturn ErrPositiveIntegers\n\t}\n\tu := time.Now()\n\tsource := rand.NewSource(u.Unix())\n\tr := rand.New(source)\n\tarr := r.Perm(numberOfNodesToCreate)\n\tfor _, a := range arr {\n\t\tt.Add(a)\n\t}\n\treturn\n}\n\n\/\/ GetRootData returns the data stored at the root, however this does not return the root Node\nfunc (t *Tree) GetRootData() int {\n\treturn t.Root.Data\n}\n\n\/\/ GetTreeTotal returns the sum of the collecitve nodes on the Tree\nfunc (t *Tree) GetTreeTotal() int {\n\treturn t.Total\n}\n\n\/\/ TreeToArray converts to the into an int slice\nfunc (t *Tree) TreeToArray() []int {\n\tvar wg sync.WaitGroup\n\tc := make(chan int, 100)\n\tarr := make([]int, 0, t.NodeCount)\n\tif t.Root != nil {\n\t\tcurrentNode := t.Root\n\t\tif currentNode.Left == nil && currentNode.Right == nil {\n\t\t\treturn []int{currentNode.Data}\n\t\t}\n\t\twg.Add(1)\n\t\tt.traversalGetVals(currentNode, c, &wg)\n\t}\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(c)\n\t}()\n\tfor n := range c {\n\t\tarr = append(arr, n)\n\t}\n\treturn arr\n}\n\nfunc (t *Tree) traversalGetVals(n *Node, c chan int, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tif n.Left != nil {\n\t\tc <- n.Left.Data\n\t\twg.Add(1)\n\t\tgo t.traversalGetVals(n.Left, c, wg)\n\t}\n\tif n.Right != nil {\n\t\tc <- n.Right.Data\n\t\twg.Add(1)\n\t\tgo t.traversalGetVals(n.Right, c, wg)\n\t}\n\treturn\n}\n\n\/\/ ShiftRoot rebuilds the tree with a new root\nfunc (t *Tree) ShiftRoot(newRoot int) {\n\tarr := t.TreeToArray()\n\tn := Tree{}\n\tn.Add(newRoot)\n\tfor _, i := range arr {\n\t\tn.Add(i)\n\t}\n\t*t = n\n}\n\n\/\/ PrintTree uses json.MarshalIndent() to print the Tree in an organized fashion, which can then be analysized as a JSON\n\/\/ object\nfunc (t *Tree) PrintTree() {\n\tb, err := json.MarshalIndent(t, \"\", \" \")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(string(b))\n}\n<|endoftext|>"}
{"text":"<commit_before>package tree\n\nimport (\n\t\"container\/list\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/Masterminds\/glide\/dependency\"\n\t\"github.com\/Masterminds\/glide\/msg\"\n\tgpath \"github.com\/Masterminds\/glide\/path\"\n\t\"github.com\/Masterminds\/glide\/util\"\n)\n\n\/\/ Display displays a tree view of the given project.\n\/\/\n\/\/ FIXME: The output formatting could use some TLC.\nfunc Display(b *util.BuildCtxt, basedir, myName string, level int, core bool, l *list.List) {\n\tdeps := walkDeps(b, basedir, myName)\n\tfor _, name := range deps {\n\t\tfound := findPkg(b, name, basedir)\n\t\tif found.Loc == dependency.LocUnknown {\n\t\t\tm := \"glide get \" + found.Name\n\t\t\tmsg.Puts(\"\\t%s\\t(%s)\", found.Name, m)\n\t\t\tcontinue\n\t\t}\n\t\tif !core && found.Loc == dependency.LocGoroot || found.Loc == dependency.LocCgo {\n\t\t\tcontinue\n\t\t}\n\t\tmsg.Print(strings.Repeat(\"|\\t\", level-1) + \"|-- \")\n\n\t\tf := findInList(found.Name, l)\n\t\tif f == true {\n\t\t\tmsg.Puts(\"(Recursion) %s   (%s)\", found.Name, found.Path)\n\t\t} else {\n\t\t\t\/\/ Every branch in the tree is a copy to handle all the branches\n\t\t\tcl := copyList(l)\n\t\t\tcl.PushBack(found.Name)\n\t\t\tmsg.Puts(\"%s   (%s)\", found.Name, found.Path)\n\t\t\tDisplay(b, found.Path, found.Name, level+1, core, cl)\n\t\t}\n\t}\n}\n\nfunc walkDeps(b *util.BuildCtxt, base, myName string) []string {\n\texternalDeps := []string{}\n\tfilepath.Walk(base, func(path string, fi os.FileInfo, err error) error {\n\t\tif !dependency.IsSrcDir(fi) {\n\t\t\tif fi.IsDir() {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tvar imps []string\n\t\tpkg, err := b.ImportDir(path, 0)\n\t\tif err != nil && strings.HasPrefix(err.Error(), \"found packages \") {\n\t\t\t\/\/ If we got here it's because a package and multiple packages\n\t\t\t\/\/ declared. This is often because of an example with a package\n\t\t\t\/\/ or main but +build ignore as a build tag. In that case we\n\t\t\t\/\/ try to brute force the packages with a slower scan.\n\t\t\timps, _, err = dependency.IterativeScan(path)\n\t\t\tif err != nil {\n\t\t\t\tmsg.Err(\"Error walking dependencies for %s: %s\", path, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else if err != nil {\n\t\t\tif !strings.HasPrefix(err.Error(), \"no buildable Go source\") {\n\t\t\t\tmsg.Warn(\"Error: %s (%s)\", err, path)\n\t\t\t\t\/\/ Not sure if we should return here.\n\t\t\t\t\/\/return err\n\t\t\t}\n\t\t} else {\n\t\t\timps = pkg.Imports\n\t\t}\n\n\t\tif pkg.Goroot {\n\t\t\treturn nil\n\t\t}\n\n\t\tfor _, imp := range imps {\n\t\t\t\/\/if strings.HasPrefix(imp, myName) {\n\t\t\t\/\/\/\/Info(\"Skipping %s because it is a subpackage of %s\", imp, myName)\n\t\t\t\/\/continue\n\t\t\t\/\/}\n\t\t\tif imp == myName {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\texternalDeps = append(externalDeps, imp)\n\t\t}\n\n\t\treturn nil\n\t})\n\treturn externalDeps\n}\n\nfunc findPkg(b *util.BuildCtxt, name, cwd string) *dependency.PkgInfo {\n\tvar fi os.FileInfo\n\tvar err error\n\tvar p string\n\n\tinfo := &dependency.PkgInfo{\n\t\tName: name,\n\t}\n\n\tif strings.HasPrefix(name, \".\/\") || strings.HasPrefix(name, \"..\/\") {\n\t\tinfo.Loc = dependency.LocRelative\n\t\treturn info\n\t}\n\n\t\/\/ Recurse backward to scan other vendor\/ directories\n\t\/\/ If the cwd isn't an absolute path walking upwards looking for vendor\/\n\t\/\/ folders can get into an infinate loop.\n\tabs, err := filepath.Abs(cwd)\n\tif err != nil {\n\t\tabs = cwd\n\t}\n\tif abs != \".\" {\n\t\t\/\/ Previously there was a check on the loop that wd := \"\/\". The path\n\t\t\/\/ \"\/\" is a POSIX path so this fails on Windows. Now the check is to\n\t\t\/\/ make sure the same wd isn't seen twice. When the same wd happens\n\t\t\/\/ more than once it's the beginning of looping on the same location\n\t\t\/\/ which is the top level.\n\t\tpwd := \"\"\n\t\tfor wd := abs; wd != pwd; wd = filepath.Dir(wd) {\n\t\t\tpwd = wd\n\n\t\t\t\/\/ Don't look for packages outside the GOPATH\n\t\t\t\/\/ Note, the GOPATH may or may not end with the path separator.\n\t\t\t\/\/ The output of filepath.Dir does not the the path separator on the\n\t\t\t\/\/ end so we need to test both.\n\t\t\tif wd == b.GOPATH || wd+string(os.PathSeparator) == b.GOPATH {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tp = filepath.Join(wd, \"vendor\", name)\n\t\t\tif fi, err = os.Stat(p); err == nil && (fi.IsDir() || gpath.IsLink(fi)) {\n\t\t\t\tinfo.Path = p\n\t\t\t\tinfo.Loc = dependency.LocVendor\n\t\t\t\tinfo.Vendored = true\n\t\t\t\treturn info\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Check $GOPATH\n\tfor _, r := range strings.Split(b.GOPATH, \":\") {\n\t\tp = filepath.Join(r, \"src\", name)\n\t\tif fi, err = os.Stat(p); err == nil && (fi.IsDir() || gpath.IsLink(fi)) {\n\t\t\tinfo.Path = p\n\t\t\tinfo.Loc = dependency.LocGopath\n\t\t\treturn info\n\t\t}\n\t}\n\n\t\/\/ Check $GOROOT\n\tfor _, r := range strings.Split(b.GOROOT, \":\") {\n\t\tp = filepath.Join(r, \"src\", name)\n\t\tif fi, err = os.Stat(p); err == nil && (fi.IsDir() || gpath.IsLink(fi)) {\n\t\t\tinfo.Path = p\n\t\t\tinfo.Loc = dependency.LocGoroot\n\t\t\treturn info\n\t\t}\n\t}\n\n\t\/\/ If this is \"C\", we're dealing with cgo\n\tif name == \"C\" {\n\t\tinfo.Loc = dependency.LocCgo\n\t} else if name == \"appengine\" || name == \"appengine_internal\" ||\n\t\tstrings.HasPrefix(name, \"appengine\/\") ||\n\t\tstrings.HasPrefix(name, \"appengine_internal\/\") {\n\t\t\/\/ Appengine is a special case when it comes to Go builds. It is a local\n\t\t\/\/ looking package only available within appengine. It's a special case\n\t\t\/\/ where Google products are playing with each other.\n\t\t\/\/ https:\/\/blog.golang.org\/the-app-engine-sdk-and-workspaces-gopath\n\t\tinfo.Loc = dependency.LocAppengine\n\t} else if name == \"context\" || name == \"net\/http\/httptrace\" {\n\t\t\/\/ context and net\/http\/httptrace are packages being added to\n\t\t\/\/ the Go 1.7 standard library. Some packages, such as golang.org\/x\/net\n\t\t\/\/ are importing it with build flags in files for go1.7. Need to detect\n\t\t\/\/ this and handle it.\n\t\tinfo.Loc = dependency.LocGoroot\n\t}\n\n\treturn info\n}\n\n\/\/ copyList copies an existing list to a new list.\nfunc copyList(l *list.List) *list.List {\n\tn := list.New()\n\tfor e := l.Front(); e != nil; e = e.Next() {\n\t\tn.PushBack(e.Value.(string))\n\t}\n\treturn n\n}\n\n\/\/ findInList searches a list haystack for a string needle.\nfunc findInList(n string, l *list.List) bool {\n\tfor e := l.Front(); e != nil; e = e.Next() {\n\t\tif e.Value.(string) == n {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n<commit_msg>Fixes panic while running tree command.<commit_after>package tree\n\nimport (\n\t\"container\/list\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/Masterminds\/glide\/dependency\"\n\t\"github.com\/Masterminds\/glide\/msg\"\n\tgpath \"github.com\/Masterminds\/glide\/path\"\n\t\"github.com\/Masterminds\/glide\/util\"\n)\n\n\/\/ Display displays a tree view of the given project.\n\/\/\n\/\/ FIXME: The output formatting could use some TLC.\nfunc Display(b *util.BuildCtxt, basedir, myName string, level int, core bool, l *list.List) {\n\tdeps := walkDeps(b, basedir, myName)\n\tfor _, name := range deps {\n\t\tfound := findPkg(b, name, basedir)\n\t\tif found.Loc == dependency.LocUnknown {\n\t\t\tm := \"glide get \" + found.Name\n\t\t\tmsg.Puts(\"\\t%s\\t(%s)\", found.Name, m)\n\t\t\tcontinue\n\t\t}\n\t\tif !core && found.Loc == dependency.LocGoroot || found.Loc == dependency.LocCgo {\n\t\t\tcontinue\n\t\t}\n\t\tmsg.Print(strings.Repeat(\"|\\t\", level-1) + \"|-- \")\n\n\t\tf := findInList(found.Name, l)\n\t\tif f == true {\n\t\t\tmsg.Puts(\"(Recursion) %s   (%s)\", found.Name, found.Path)\n\t\t} else {\n\t\t\t\/\/ Every branch in the tree is a copy to handle all the branches\n\t\t\tcl := copyList(l)\n\t\t\tcl.PushBack(found.Name)\n\t\t\tmsg.Puts(\"%s   (%s)\", found.Name, found.Path)\n\t\t\tDisplay(b, found.Path, found.Name, level+1, core, cl)\n\t\t}\n\t}\n}\n\nfunc walkDeps(b *util.BuildCtxt, base, myName string) []string {\n\texternalDeps := []string{}\n\tfilepath.Walk(base, func(path string, fi os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !dependency.IsSrcDir(fi) {\n\t\t\tif fi.IsDir() {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\tvar imps []string\n\t\tpkg, err := b.ImportDir(path, 0)\n\t\tif err != nil && strings.HasPrefix(err.Error(), \"found packages \") {\n\t\t\t\/\/ If we got here it's because a package and multiple packages\n\t\t\t\/\/ declared. This is often because of an example with a package\n\t\t\t\/\/ or main but +build ignore as a build tag. In that case we\n\t\t\t\/\/ try to brute force the packages with a slower scan.\n\t\t\timps, _, err = dependency.IterativeScan(path)\n\t\t\tif err != nil {\n\t\t\t\tmsg.Err(\"Error walking dependencies for %s: %s\", path, err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else if err != nil {\n\t\t\tif !strings.HasPrefix(err.Error(), \"no buildable Go source\") {\n\t\t\t\tmsg.Warn(\"Error: %s (%s)\", err, path)\n\t\t\t\t\/\/ Not sure if we should return here.\n\t\t\t\t\/\/return err\n\t\t\t}\n\t\t} else {\n\t\t\timps = pkg.Imports\n\t\t}\n\n\t\tif pkg.Goroot {\n\t\t\treturn nil\n\t\t}\n\n\t\tfor _, imp := range imps {\n\t\t\t\/\/if strings.HasPrefix(imp, myName) {\n\t\t\t\/\/\/\/Info(\"Skipping %s because it is a subpackage of %s\", imp, myName)\n\t\t\t\/\/continue\n\t\t\t\/\/}\n\t\t\tif imp == myName {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\texternalDeps = append(externalDeps, imp)\n\t\t}\n\n\t\treturn nil\n\t})\n\treturn externalDeps\n}\n\nfunc findPkg(b *util.BuildCtxt, name, cwd string) *dependency.PkgInfo {\n\tvar fi os.FileInfo\n\tvar err error\n\tvar p string\n\n\tinfo := &dependency.PkgInfo{\n\t\tName: name,\n\t}\n\n\tif strings.HasPrefix(name, \".\/\") || strings.HasPrefix(name, \"..\/\") {\n\t\tinfo.Loc = dependency.LocRelative\n\t\treturn info\n\t}\n\n\t\/\/ Recurse backward to scan other vendor\/ directories\n\t\/\/ If the cwd isn't an absolute path walking upwards looking for vendor\/\n\t\/\/ folders can get into an infinate loop.\n\tabs, err := filepath.Abs(cwd)\n\tif err != nil {\n\t\tabs = cwd\n\t}\n\tif abs != \".\" {\n\t\t\/\/ Previously there was a check on the loop that wd := \"\/\". The path\n\t\t\/\/ \"\/\" is a POSIX path so this fails on Windows. Now the check is to\n\t\t\/\/ make sure the same wd isn't seen twice. When the same wd happens\n\t\t\/\/ more than once it's the beginning of looping on the same location\n\t\t\/\/ which is the top level.\n\t\tpwd := \"\"\n\t\tfor wd := abs; wd != pwd; wd = filepath.Dir(wd) {\n\t\t\tpwd = wd\n\n\t\t\t\/\/ Don't look for packages outside the GOPATH\n\t\t\t\/\/ Note, the GOPATH may or may not end with the path separator.\n\t\t\t\/\/ The output of filepath.Dir does not the the path separator on the\n\t\t\t\/\/ end so we need to test both.\n\t\t\tif wd == b.GOPATH || wd+string(os.PathSeparator) == b.GOPATH {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tp = filepath.Join(wd, \"vendor\", name)\n\t\t\tif fi, err = os.Stat(p); err == nil && (fi.IsDir() || gpath.IsLink(fi)) {\n\t\t\t\tinfo.Path = p\n\t\t\t\tinfo.Loc = dependency.LocVendor\n\t\t\t\tinfo.Vendored = true\n\t\t\t\treturn info\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Check $GOPATH\n\tfor _, r := range strings.Split(b.GOPATH, \":\") {\n\t\tp = filepath.Join(r, \"src\", name)\n\t\tif fi, err = os.Stat(p); err == nil && (fi.IsDir() || gpath.IsLink(fi)) {\n\t\t\tinfo.Path = p\n\t\t\tinfo.Loc = dependency.LocGopath\n\t\t\treturn info\n\t\t}\n\t}\n\n\t\/\/ Check $GOROOT\n\tfor _, r := range strings.Split(b.GOROOT, \":\") {\n\t\tp = filepath.Join(r, \"src\", name)\n\t\tif fi, err = os.Stat(p); err == nil && (fi.IsDir() || gpath.IsLink(fi)) {\n\t\t\tinfo.Path = p\n\t\t\tinfo.Loc = dependency.LocGoroot\n\t\t\treturn info\n\t\t}\n\t}\n\n\t\/\/ If this is \"C\", we're dealing with cgo\n\tif name == \"C\" {\n\t\tinfo.Loc = dependency.LocCgo\n\t} else if name == \"appengine\" || name == \"appengine_internal\" ||\n\t\tstrings.HasPrefix(name, \"appengine\/\") ||\n\t\tstrings.HasPrefix(name, \"appengine_internal\/\") {\n\t\t\/\/ Appengine is a special case when it comes to Go builds. It is a local\n\t\t\/\/ looking package only available within appengine. It's a special case\n\t\t\/\/ where Google products are playing with each other.\n\t\t\/\/ https:\/\/blog.golang.org\/the-app-engine-sdk-and-workspaces-gopath\n\t\tinfo.Loc = dependency.LocAppengine\n\t} else if name == \"context\" || name == \"net\/http\/httptrace\" {\n\t\t\/\/ context and net\/http\/httptrace are packages being added to\n\t\t\/\/ the Go 1.7 standard library. Some packages, such as golang.org\/x\/net\n\t\t\/\/ are importing it with build flags in files for go1.7. Need to detect\n\t\t\/\/ this and handle it.\n\t\tinfo.Loc = dependency.LocGoroot\n\t}\n\n\treturn info\n}\n\n\/\/ copyList copies an existing list to a new list.\nfunc copyList(l *list.List) *list.List {\n\tn := list.New()\n\tfor e := l.Front(); e != nil; e = e.Next() {\n\t\tn.PushBack(e.Value.(string))\n\t}\n\treturn n\n}\n\n\/\/ findInList searches a list haystack for a string needle.\nfunc findInList(n string, l *list.List) bool {\n\tfor e := l.Front(); e != nil; e = e.Next() {\n\t\tif e.Value.(string) == n {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Matthew Holt and The Caddy Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build gofuzz\n\/\/ +build gofuzz_libfuzzer\n\npackage caddyfile\n\nimport (\n\t\"bytes\"\n)\n\nfunc FuzzParseCaddyfile(data []byte) (score int) {\n\tsb, err := Parse(\"Caddyfile\", bytes.NewReader(data))\n\tif err != nil {\n\t\t\/\/ if both an error is received and some ServerBlocks,\n\t\t\/\/ then the parse was able to parse partially. Mark this\n\t\t\/\/ result as interesting to push the fuzzer further through the parser.\n\t\tif sb != nil && len(sb) > 0 {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\t}\n\treturn 1\n}\n<commit_msg>v2: fuzz: update function signature of caddyfile.Parse (#3160)<commit_after>\/\/ Copyright 2015 Matthew Holt and The Caddy Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build gofuzz\n\/\/ +build gofuzz_libfuzzer\n\npackage caddyfile\n\nfunc FuzzParseCaddyfile(data []byte) (score int) {\n\tsb, err := Parse(\"Caddyfile\", data)\n\tif err != nil {\n\t\t\/\/ if both an error is received and some ServerBlocks,\n\t\t\/\/ then the parse was able to parse partially. Mark this\n\t\t\/\/ result as interesting to push the fuzzer further through the parser.\n\t\tif sb != nil && len(sb) > 0 {\n\t\t\treturn 1\n\t\t}\n\t\treturn 0\n\t}\n\treturn 1\n}\n<|endoftext|>"}
{"text":"<commit_before>package detect\n\nimport (\n\t\"encoding\/binary\"\n\t\"net\"\n\t\"strconv\"\n\n\t\"github.com\/mesos\/mesos-go\/detector\"\n\tmesos \"github.com\/mesos\/mesos-go\/mesosproto\"\n\n\t\"github.com\/mesosphere\/mesos-dns\/logging\"\n)\n\nvar (\n\t_ detector.MasterChanged = (*Masters)(nil)\n\t_ detector.AllMasters    = (*Masters)(nil)\n)\n\n\/\/ Masters detects changes of leader and\/or master elections\n\/\/ and sends these changes to a channel.\ntype Masters struct {\n\t\/\/ current masters list,\n\t\/\/ 1st item represents the leader,\n\t\/\/ the rest remaining masters\n\tmasters []string\n\n\t\/\/ the channel leader\/master changes are being sent to\n\tchanged chan<- []string\n}\n\n\/\/ NewMasters returns a new Masters detector with the given initial masters\n\/\/ and the given changed channel to which master changes will be sent to.\n\/\/ Initially the leader is unknown which is represented by\n\/\/ setting the first item of the sent masters slice to be empty.\nfunc NewMasters(masters []string, changed chan<- []string) *Masters {\n\treturn &Masters{\n\t\tmasters: append([]string{\"\"}, masters...),\n\t\tchanged: changed,\n\t}\n}\n\n\/\/ OnMasterChanged sets the given MasterInfo as the current leader\n\/\/ leaving the remaining masters unchanged and emits the current masters state.\n\/\/ It implements the detector.MasterChanged interface.\nfunc (ms *Masters) OnMasterChanged(leader *mesos.MasterInfo) {\n\tlogging.VeryVerbose.Println(\"Updated leader: \", leader)\n\n\tif leader == nil {\n\t\tlogging.Error.Println(\"No master available in Zookeeper.\")\n\t\treturn\n\t}\n\n\tms.masters = ordered(masterHostPort(leader), ms.masters[1:])\n\temit(ms.changed, ms.masters)\n}\n\n\/\/ UpdatedMasters sets the given slice of MasterInfo as the current remaining masters\n\/\/ leaving the current leader unchanged and emits the current masters state.\n\/\/ It implements the detector.AllMasters interface.\nfunc (ms *Masters) UpdatedMasters(infos []*mesos.MasterInfo) {\n\tlogging.VeryVerbose.Println(\"Updated masters: \", infos)\n\n\tif infos == nil {\n\t\tlogging.Error.Println(\"No masters available in Zookeeper.\")\n\t\treturn\n\t}\n\n\tmasters := make([]string, 0, len(infos))\n\tfor _, info := range infos {\n\t\tif validMasterInfo(info) {\n\t\t\tmasters = append(masters, masterHostPort(info))\n\t\t}\n\t}\n\n\tif len(masters) == 0 {\n\t\tlogging.Error.Println(\"No valid masters available in Zookeeper.\")\n\t\treturn\n\t}\n\n\tms.masters = ordered(ms.masters[0], masters)\n\temit(ms.changed, ms.masters)\n}\n\nfunc emit(ch chan<- []string, s []string) {\n\tch <- append(make([]string, 0, len(s)), s...)\n}\n\n\/\/ ordered returns a slice of masters with the given leader in the first position\nfunc ordered(leader string, masters []string) []string {\n\tms := append(make([]string, 0, len(masters)+1), leader)\n\tfor _, m := range masters {\n\t\tif m != leader {\n\t\t\tms = append(ms, m)\n\t\t}\n\t}\n\treturn ms\n}\n\nfunc validMasterInfo(info *mesos.MasterInfo) bool {\n\treturn info.GetHostname() != \"\" || info.GetIp() != 0\n}\n\nfunc masterHostPort(info *mesos.MasterInfo) string {\n\t\/\/ unpack IPv4\n\toctets := make([]byte, net.IPv4len)\n\tbinary.LittleEndian.PutUint32(octets, info.GetIp())\n\t\/\/ we're using an octet slice of len IPv4len, thus no need to convert with To4()\n\tipv4 := net.IP(octets)\n\n\treturn net.JoinHostPort(ipv4.String(), masterPort(info))\n}\n\nfunc masterPort(info *mesos.MasterInfo) string {\n\treturn strconv.FormatUint(uint64(info.GetPort()), 10)\n}\n<commit_msg>detect: add TODO for refactoring towards Address.ip<commit_after>package detect\n\nimport (\n\t\"encoding\/binary\"\n\t\"net\"\n\t\"strconv\"\n\n\t\"github.com\/mesos\/mesos-go\/detector\"\n\tmesos \"github.com\/mesos\/mesos-go\/mesosproto\"\n\n\t\"github.com\/mesosphere\/mesos-dns\/logging\"\n)\n\nvar (\n\t_ detector.MasterChanged = (*Masters)(nil)\n\t_ detector.AllMasters    = (*Masters)(nil)\n)\n\n\/\/ Masters detects changes of leader and\/or master elections\n\/\/ and sends these changes to a channel.\ntype Masters struct {\n\t\/\/ current masters list,\n\t\/\/ 1st item represents the leader,\n\t\/\/ the rest remaining masters\n\tmasters []string\n\n\t\/\/ the channel leader\/master changes are being sent to\n\tchanged chan<- []string\n}\n\n\/\/ NewMasters returns a new Masters detector with the given initial masters\n\/\/ and the given changed channel to which master changes will be sent to.\n\/\/ Initially the leader is unknown which is represented by\n\/\/ setting the first item of the sent masters slice to be empty.\nfunc NewMasters(masters []string, changed chan<- []string) *Masters {\n\treturn &Masters{\n\t\tmasters: append([]string{\"\"}, masters...),\n\t\tchanged: changed,\n\t}\n}\n\n\/\/ OnMasterChanged sets the given MasterInfo as the current leader\n\/\/ leaving the remaining masters unchanged and emits the current masters state.\n\/\/ It implements the detector.MasterChanged interface.\nfunc (ms *Masters) OnMasterChanged(leader *mesos.MasterInfo) {\n\tlogging.VeryVerbose.Println(\"Updated leader: \", leader)\n\n\tif leader == nil {\n\t\tlogging.Error.Println(\"No master available in Zookeeper.\")\n\t\treturn\n\t}\n\n\tms.masters = ordered(masterHostPort(leader), ms.masters[1:])\n\temit(ms.changed, ms.masters)\n}\n\n\/\/ UpdatedMasters sets the given slice of MasterInfo as the current remaining masters\n\/\/ leaving the current leader unchanged and emits the current masters state.\n\/\/ It implements the detector.AllMasters interface.\nfunc (ms *Masters) UpdatedMasters(infos []*mesos.MasterInfo) {\n\tlogging.VeryVerbose.Println(\"Updated masters: \", infos)\n\n\tif infos == nil {\n\t\tlogging.Error.Println(\"No masters available in Zookeeper.\")\n\t\treturn\n\t}\n\n\tmasters := make([]string, 0, len(infos))\n\tfor _, info := range infos {\n\t\tif validMasterInfo(info) {\n\t\t\tmasters = append(masters, masterHostPort(info))\n\t\t}\n\t}\n\n\tif len(masters) == 0 {\n\t\tlogging.Error.Println(\"No valid masters available in Zookeeper.\")\n\t\treturn\n\t}\n\n\tms.masters = ordered(ms.masters[0], masters)\n\temit(ms.changed, ms.masters)\n}\n\nfunc emit(ch chan<- []string, s []string) {\n\tch <- append(make([]string, 0, len(s)), s...)\n}\n\n\/\/ ordered returns a slice of masters with the given leader in the first position\nfunc ordered(leader string, masters []string) []string {\n\tms := append(make([]string, 0, len(masters)+1), leader)\n\tfor _, m := range masters {\n\t\tif m != leader {\n\t\t\tms = append(ms, m)\n\t\t}\n\t}\n\treturn ms\n}\n\nfunc validMasterInfo(info *mesos.MasterInfo) bool {\n\treturn info.GetHostname() != \"\" || info.GetIp() != 0\n}\n\nfunc masterHostPort(info *mesos.MasterInfo) string {\n\t\/\/ unpack IPv4\n\toctets := make([]byte, net.IPv4len)\n\t\/\/ TODO(sur): refactor to use the Address.ip string field once available\n\tbinary.LittleEndian.PutUint32(octets, info.GetIp())\n\t\/\/ we're using an octet slice of len IPv4len, thus no need to convert with To4()\n\tipv4 := net.IP(octets)\n\n\treturn net.JoinHostPort(ipv4.String(), masterPort(info))\n}\n\nfunc masterPort(info *mesos.MasterInfo) string {\n\treturn strconv.FormatUint(uint64(info.GetPort()), 10)\n}\n<|endoftext|>"}
{"text":"<commit_before>package handlers\n\nimport (\n\t\"crypto\/rsa\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/JustinBeckwith\/go-yelp\/yelp\"\n\t\"github.com\/dgrijalva\/jwt-go\"\n\t\"github.com\/rs\/cors\"\n\n\t\"github.com\/justinas\/alice\"\n\n\t\"github.com\/gorilla\/context\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/gorilla\/sessions\"\n\t\"github.com\/gorilla\/websocket\"\n\t\"github.com\/markbates\/goth\"\n\t\"github.com\/markbates\/goth\/gothic\"\n\t\"github.com\/markbates\/goth\/providers\/twitter\"\n)\n\nvar (\n\tverifyKey *rsa.PublicKey\n\tsignKey   *rsa.PrivateKey\n)\n\nconst (\n\tprivKeyPath    = \"keys\/app.rsa\"     \/\/ openssl genrsa -out app.rsa keysize\n\tpubKeyPath     = \"keys\/app.rsa.pub\" \/\/ openssl rsa -in app.rsa -pubout > app.rsa.pub\n\tclientURL      = \"http:\/\/localhost:8080\"\n\tuserContextKey = \"userid\"\n)\n\nvar upgrader = websocket.Upgrader{\n\tReadBufferSize:  1024,\n\tWriteBufferSize: 1024,\n\tCheckOrigin: func(r *http.Request) bool {\n\t\treturn true\n\t},\n}\n\n\/\/ read the key files before starting http handlers\nfunc init() {\n\tsignBytes, err := ioutil.ReadFile(privKeyPath)\n\tfatal(err)\n\n\tsignKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n\tfatal(err)\n\n\tverifyBytes, err := ioutil.ReadFile(pubKeyPath)\n\tfatal(err)\n\n\tverifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n\n}\n\nfunc fatal(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\ntype httpError struct {\n\tstatus int\n}\n\nfunc (e httpError) Error() string {\n\treturn http.StatusText(e.status)\n}\n\nfunc abortWithStatus(w http.ResponseWriter, status int) {\n\tabortWithError(w, httpError{status})\n}\n\nfunc abortWithError(w http.ResponseWriter, err error) {\n\tif httpError, ok := err.(httpError); ok {\n\t\thttp.Error(w, httpError.Error(), httpError.status)\n\t\treturn\n\t}\n\t\/\/ maybe catch other errors such as \"no rows found\"\n\tlog.Println(err)\n\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n}\n\nvar (\n\tdb = initDB()\n\th  = initHub()\n)\n\n\/\/ grabs user ID from context\nfunc getUserID(r *http.Request) string {\n\tif userID := context.Get(r, userContextKey); userID != nil {\n\t\treturn userID.(string)\n\t}\n\treturn \"\"\n}\n\nfunc authenticate(w http.ResponseWriter, r *http.Request) error {\n\tauth := \"\"\n\theader := r.Header.Get(\"Authorization\")\n\tif header == \"\" {\n\t\t\/\/ try the query string\n\t\tauth = r.URL.Query().Get(\"jwt-token\")\n\t} else {\n\t\tparts := strings.Split(header, \"Bearer\")\n\t\tif len(parts) < 2 {\n\t\t\treturn nil\n\t\t}\n\t\tauth = strings.Trim(parts[1], \" \")\n\t}\n\tif auth == \"\" {\n\t\treturn nil\n\t}\n\tt, err := jwt.Parse(auth, func(token *jwt.Token) (interface{}, error) {\n\t\treturn verifyKey, nil\n\t})\n\tif err != nil {\n\t\t\/\/check if timeout etc\n\t\tlog.Println(\"JWTERROR\", err)\n\t\t\/\/ if a timeout throw a 401, so we can prompt re-login\n\t\treturn httpError{http.StatusUnauthorized}\n\t}\n\tif t.Valid {\n\t\tcontext.Set(r, userContextKey, t.Claims[\"userid\"])\n\t} else {\n\t\tfmt.Println(\"NOTVALID\")\n\t}\n\treturn nil\n}\n\n\/\/ authentication middleware: decodes JWT token\nfunc authenticator(next http.Handler) http.Handler {\n\t\/\/ token will either be in header or query string (e.g. sockets)\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif err := authenticate(w, r); err != nil {\n\t\t\tabortWithError(w, err)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n\/\/ Run runs the application.\nfunc Run(host string) {\n\n\ttwitterKey := os.Getenv(\"TWITTER_KEY\")\n\ttwitterSecret := os.Getenv(\"TWITTER_SECRET\")\n\n\tgoth.UseProviders(\n\t\ttwitter.New(twitterKey, twitterSecret,\n\t\t\t\"http:\/\/localhost:4000\/auth\/callback\/?provider=twitter\",\n\t\t),\n\t)\n\tgothic.Store = sessions.NewCookieStore([]byte(os.Getenv(\"SECRET_KEY\")))\n\n\tcors := cors.New(cors.Options{\n\t\tAllowedOrigins:   []string{\"*\"},\n\t\tAllowedHeaders:   []string{\"*\"},\n\t\tAllowCredentials: true,\n\t\tDebug:            false,\n\t})\n\n\tauthOptions := &yelp.AuthOptions{\n\t\tConsumerKey:       os.Getenv(\"YELP_CONSUMER_KEY\"),\n\t\tConsumerSecret:    os.Getenv(\"YELP_CONSUMER_SECRET\"),\n\t\tAccessToken:       os.Getenv(\"YELP_ACCESS_TOKEN\"),\n\t\tAccessTokenSecret: os.Getenv(\"YELP_ACCESS_TOKEN_SECRET\"),\n\t}\n\n\trouter := mux.NewRouter()\n\n\trouter.HandleFunc(\"\/search\/\", func(w http.ResponseWriter, r *http.Request) {\n\n\t\tlocation := r.URL.Query().Get(\"location\")\n\t\tif location == \"\" {\n\t\t\tabortWithStatus(w, http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tsearchOptions := yelp.SearchOptions{\n\t\t\tLocationOptions: &yelp.LocationOptions{\n\t\t\t\tLocation: location,\n\t\t\t},\n\t\t\tGeneralOptions: &yelp.GeneralOptions{\n\t\t\t\tCategoryFilter: \"bars\",\n\t\t\t},\n\t\t}\n\n\t\tclient := yelp.New(authOptions, nil)\n\t\tresult, err := client.DoSearch(searchOptions)\n\t\tif err != nil {\n\t\t\tabortWithError(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tbars := make([]Bar, len(result.Businesses))\n\t\tuserID := getUserID(r)\n\n\t\tfor i, biz := range result.Businesses {\n\t\t\tbars[i] = Bar{\n\t\t\t\tbiz.ID,\n\t\t\t\tbiz.ImageURL,\n\t\t\t\tbiz.Name,\n\t\t\t\tbiz.SnippetText,\n\t\t\t\tdb.getTotal(biz.ID),\n\t\t\t\tdb.isGoing(biz.ID, userID),\n\t\t\t}\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tjson.NewEncoder(w).Encode(bars)\n\t})\n\n\trouter.HandleFunc(\"\/ws\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tws, err := upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\tabortWithError(w, err)\n\t\t\treturn\n\t\t}\n\t\tcn := &conn{\n\t\t\tsend:   make(chan *Message),\n\t\t\tws:     ws,\n\t\t\tuserID: getUserID(r),\n\t\t\th:      h}\n\t\th.register <- cn\n\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(2)\n\t\tgo cn.write(&wg)\n\t\tgo cn.read(&wg)\n\t\twg.Wait()\n\t})\n\n\tauth := router.PathPrefix(\"\/auth\").Subrouter()\n\n\t\/\/ redirects to provider\n\tauth.HandleFunc(\"\/redirect\/\", gothic.BeginAuthHandler)\n\n\t\/\/ oauth provider callback\n\tauth.HandleFunc(\"\/callback\/\", func(w http.ResponseWriter, r *http.Request) {\n\n\t\tcreds, err := gothic.CompleteUserAuth(w, r)\n\t\tif err != nil {\n\t\t\tabortWithError(w, err)\n\t\t\treturn\n\t\t}\n\t\texpires := time.Now().Add(time.Hour * 24)\n\t\tuserID := fmt.Sprintf(\"%s:%s\", creds.Provider, creds.UserID)\n\n\t\ttoken := jwt.New(jwt.SigningMethodRS256)\n\t\ttoken.Claims[\"userid\"] = userID\n\t\ttoken.Claims[\"exp\"] = expires.Unix()\n\t\ttokenStr, err := token.SignedString(signKey)\n\t\tif err != nil {\n\t\t\tabortWithError(w, err)\n\t\t\treturn\n\t\t}\n\t\t\/\/ the client can now just read the token from the query string\n\t\turl := fmt.Sprintf(\"%s?jwt-token=%s\", clientURL, tokenStr)\n\t\thttp.Redirect(w, r, url, http.StatusTemporaryRedirect)\n\t})\n\n\t\/\/ kickoff the connection hub\n\n\tgo h.run()\n\n\tchain := alice.New(cors.Handler, authenticator).Then(router)\n\n\tif err := http.ListenAndServe(host, chain); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}\n<commit_msg>Refactoring<commit_after>package handlers\n\nimport (\n\t\"crypto\/rsa\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/JustinBeckwith\/go-yelp\/yelp\"\n\t\"github.com\/dgrijalva\/jwt-go\"\n\t\"github.com\/rs\/cors\"\n\n\t\"github.com\/justinas\/alice\"\n\n\t\"github.com\/gorilla\/context\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/gorilla\/sessions\"\n\t\"github.com\/gorilla\/websocket\"\n\t\"github.com\/markbates\/goth\"\n\t\"github.com\/markbates\/goth\/gothic\"\n\t\"github.com\/markbates\/goth\/providers\/twitter\"\n)\n\nvar (\n\tverifyKey   *rsa.PublicKey\n\tsignKey     *rsa.PrivateKey\n\tauthOptions *yelp.AuthOptions\n)\n\nvar (\n\tdb = initDB()\n\th  = initHub()\n)\n\nconst (\n\tprivKeyPath    = \"keys\/app.rsa\"     \/\/ openssl genrsa -out app.rsa keysize\n\tpubKeyPath     = \"keys\/app.rsa.pub\" \/\/ openssl rsa -in app.rsa -pubout > app.rsa.pub\n\tclientURL      = \"http:\/\/localhost:8080\"\n\tuserContextKey = \"userid\"\n)\n\nvar upgrader = websocket.Upgrader{\n\tReadBufferSize:  1024,\n\tWriteBufferSize: 1024,\n\tCheckOrigin: func(r *http.Request) bool {\n\t\treturn true\n\t},\n}\n\n\/\/ read the key files before starting http handlers\nfunc init() {\n\tsignBytes, err := ioutil.ReadFile(privKeyPath)\n\tfatal(err)\n\n\tsignKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)\n\tfatal(err)\n\n\tverifyBytes, err := ioutil.ReadFile(pubKeyPath)\n\tfatal(err)\n\n\tverifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)\n\n\tauthOptions = &yelp.AuthOptions{\n\t\tConsumerKey:       os.Getenv(\"YELP_CONSUMER_KEY\"),\n\t\tConsumerSecret:    os.Getenv(\"YELP_CONSUMER_SECRET\"),\n\t\tAccessToken:       os.Getenv(\"YELP_ACCESS_TOKEN\"),\n\t\tAccessTokenSecret: os.Getenv(\"YELP_ACCESS_TOKEN_SECRET\"),\n\t}\n\n\ttwitterKey := os.Getenv(\"TWITTER_KEY\")\n\ttwitterSecret := os.Getenv(\"TWITTER_SECRET\")\n\n\tgoth.UseProviders(\n\t\ttwitter.New(twitterKey, twitterSecret,\n\t\t\t\"http:\/\/localhost:4000\/auth\/callback\/?provider=twitter\",\n\t\t),\n\t)\n\n\tgothic.Store = sessions.NewCookieStore([]byte(os.Getenv(\"SECRET_KEY\")))\n}\n\nfunc fatal(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\ntype httpError struct {\n\tstatus int\n}\n\nfunc (e httpError) Error() string {\n\treturn http.StatusText(e.status)\n}\n\nfunc newHTTPError(status int) error {\n\treturn httpError{status}\n}\n\nfunc renderJSON(w http.ResponseWriter, status int, payload interface{}) error {\n\tw.WriteHeader(status)\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\treturn json.NewEncoder(w).Encode(payload)\n}\n\nfunc handleError(w http.ResponseWriter, err error) {\n\tif httpError, ok := err.(httpError); ok {\n\t\thttp.Error(w, httpError.Error(), httpError.status)\n\t\treturn\n\t}\n\t\/\/ maybe catch other errors such as \"no rows found\"\n\tlog.Println(err)\n\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n}\n\n\/\/ grabs user ID from context\nfunc getUserID(r *http.Request) string {\n\tif userID := context.Get(r, userContextKey); userID != nil {\n\t\treturn userID.(string)\n\t}\n\treturn \"\"\n}\n\nfunc authenticate(w http.ResponseWriter, r *http.Request) error {\n\tauth := \"\"\n\theader := r.Header.Get(\"Authorization\")\n\tif header == \"\" {\n\t\t\/\/ try the query string\n\t\tauth = r.URL.Query().Get(\"jwt-token\")\n\t} else {\n\t\tparts := strings.Split(header, \"Bearer\")\n\t\tif len(parts) < 2 {\n\t\t\treturn nil\n\t\t}\n\t\tauth = strings.Trim(parts[1], \" \")\n\t}\n\tif auth == \"\" {\n\t\treturn nil\n\t}\n\tt, err := jwt.Parse(auth, func(token *jwt.Token) (interface{}, error) {\n\t\treturn verifyKey, nil\n\t})\n\tif err != nil {\n\t\t\/\/check if timeout etc\n\t\tlog.Println(\"JWTERROR\", err)\n\t\t\/\/ if a timeout throw a 401, so we can prompt re-login\n\t\treturn newHTTPError(http.StatusUnauthorized)\n\t}\n\tif t.Valid {\n\t\tcontext.Set(r, userContextKey, t.Claims[\"userid\"])\n\t} else {\n\t\tfmt.Println(\"NOTVALID\")\n\t}\n\treturn nil\n}\n\ntype handlerFunc func(http.ResponseWriter, *http.Request) error\n\ntype handler struct {\n\tH handlerFunc\n}\n\nfunc (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif err := authenticate(w, r); err != nil {\n\t\thandleError(w, err)\n\t\treturn\n\t}\n\tif err := h.H(w, r); err != nil {\n\t\thandleError(w, err)\n\t}\n}\n\nfunc newHandler(h handlerFunc) http.Handler {\n\treturn handler{h}\n}\n\nfunc socket(w http.ResponseWriter, r *http.Request) error {\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcn := &conn{\n\t\tsend:   make(chan *Message),\n\t\tws:     ws,\n\t\tuserID: getUserID(r),\n\t\th:      h}\n\th.register <- cn\n\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\tgo cn.write(&wg)\n\tgo cn.read(&wg)\n\twg.Wait()\n\treturn nil\n\n}\n\nfunc authCallback(w http.ResponseWriter, r *http.Request) error {\n\tcreds, err := gothic.CompleteUserAuth(w, r)\n\tif err != nil {\n\t\treturn err\n\t}\n\texpires := time.Now().Add(time.Hour * 24)\n\tuserID := fmt.Sprintf(\"%s:%s\", creds.Provider, creds.UserID)\n\n\ttoken := jwt.New(jwt.SigningMethodRS256)\n\ttoken.Claims[\"userid\"] = userID\n\ttoken.Claims[\"exp\"] = expires.Unix()\n\ttokenStr, err := token.SignedString(signKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ the client can now just read the token from the query string\n\turl := fmt.Sprintf(\"%s?jwt-token=%s\", clientURL, tokenStr)\n\thttp.Redirect(w, r, url, http.StatusTemporaryRedirect)\n\treturn nil\n}\n\nfunc searchLocation(w http.ResponseWriter, r *http.Request) error {\n\tlocation := r.URL.Query().Get(\"location\")\n\tif location == \"\" {\n\t\treturn newHTTPError(http.StatusBadRequest)\n\t}\n\n\tsearchOptions := yelp.SearchOptions{\n\t\tLocationOptions: &yelp.LocationOptions{\n\t\t\tLocation: location,\n\t\t},\n\t\tGeneralOptions: &yelp.GeneralOptions{\n\t\t\tCategoryFilter: \"bars\",\n\t\t},\n\t}\n\n\tclient := yelp.New(authOptions, nil)\n\tresult, err := client.DoSearch(searchOptions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbars := make([]Bar, len(result.Businesses))\n\tuserID := getUserID(r)\n\n\tfor i, biz := range result.Businesses {\n\t\tbars[i] = Bar{\n\t\t\tbiz.ID,\n\t\t\tbiz.ImageURL,\n\t\t\tbiz.Name,\n\t\t\tbiz.SnippetText,\n\t\t\tdb.getTotal(biz.ID),\n\t\t\tdb.isGoing(biz.ID, userID),\n\t\t}\n\t}\n\treturn renderJSON(w, http.StatusOK, bars)\n}\n\n\/\/ Run runs the application.\nfunc Run(host string) {\n\n\tcors := cors.New(cors.Options{\n\t\tAllowedOrigins:   []string{\"*\"},\n\t\tAllowedHeaders:   []string{\"*\"},\n\t\tAllowCredentials: true,\n\t\tDebug:            false,\n\t})\n\n\trouter := mux.NewRouter()\n\n\trouter.Handle(\"\/search\/\", newHandler(searchLocation)).Methods(\"GET\")\n\trouter.Handle(\"\/ws\/\", newHandler(socket)).Methods(\"GET\")\n\n\tauth := router.PathPrefix(\"\/auth\").Subrouter()\n\n\t\/\/ oauth provider callback\n\tauth.Handle(\"\/callback\/\", newHandler(authCallback))\n\n\t\/\/ redirects to provider\n\tauth.HandleFunc(\"\/redirect\/\", gothic.BeginAuthHandler)\n\n\t\/\/ kickoff the connection hub\n\n\tgo h.run()\n\n\tchain := alice.New(cors.Handler).Then(router)\n\n\tif err := http.ListenAndServe(host, chain); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package elog\r\n\r\nimport (\r\n\t\"bytes\"\r\n\t\"errors\"\r\n\t\"fmt\"\r\n\t\"os\"\r\n\t\"runtime\"\r\n\t\"sync\"\r\n\t\"time\"\r\n)\r\n\r\nconst (\r\n\tlf          byte = 0x0A \/\/ 换行\r\n\tspace       byte = 0x20 \/\/ 空格\r\n\tcoreFormat       = \"[%s] %v\"\r\n\ttimeLayout       = \"2006-01-02 15:04:05.999\"\r\n\tcallerDepth      = 3\r\n)\r\n\r\nvar (\r\n\tbufPool = &sync.Pool{\r\n\t\tNew: func() interface{} {\r\n\t\t\treturn &bytes.Buffer{}\r\n\t\t},\r\n\t}\r\n\r\n\tmsgPool = &sync.Pool{\r\n\t\tNew: func() interface{} {\r\n\t\t\treturn &logMessage{}\r\n\t\t},\r\n\t}\r\n\r\n\terrLineNo = errors.New(\"ELog: get lineno encounter a error.\")\r\n)\r\n\r\nfunc (e *ELog) baseLog(lvl LogLevel, msg string) {\r\n\tif e.cfg.LogLevel > lvl {\r\n\t\treturn \/\/ 屏蔽打印\r\n\t}\r\n\tlogMsg := msgPool.Get().(*logMessage)\r\n\r\n\tlogMsg.msg = msg\r\n\tlogMsg.lvl = lvl\r\n\tline, err := getLineNo()\r\n\tif err != nil {\r\n\t\tfmt.Fprintln(os.Stderr, \"Get line number encounter a error.\")\r\n\t}\r\n\tlogMsg.lineNo = line\r\n\r\n\te.waitWrite.Wait()\r\n\te.logChan <- logMsg\r\n}\r\n\r\nfunc (e *ELog) Debug(format string, params ...interface{}) {\r\n\te.baseLog(DebugLvl, fmt.Sprintf(format, params...))\r\n}\r\n\r\nfunc (e *ELog) Info(format string, params ...interface{}) {\r\n\te.baseLog(InfoLvl, fmt.Sprintf(format, params...))\r\n}\r\n\r\nfunc (e *ELog) Warn(format string, params ...interface{}) {\r\n\te.baseLog(WarnLvl, fmt.Sprintf(format, params...))\r\n}\r\n\r\nfunc (e *ELog) Error(format string, params ...interface{}) {\r\n\te.baseLog(ErrorLvl, fmt.Sprintf(format, params...))\r\n}\r\n\r\n\/\/ Panic由调用者处理\r\nfunc (e *ELog) Panic(format string, params ...interface{}) {\r\n\te.baseLog(PanicLvl, fmt.Sprintf(format, params...))\r\n}\r\n\r\n\/\/ 这里会退出程序,调用os.Exit()\r\nfunc (e *ELog) Fatal(format string, params ...interface{}) {\r\n\te.baseLog(FatalLvl, fmt.Sprintf(format, params...))\r\n}\r\n\r\n\/\/ core func\r\nfunc (e *ELog) log(logMsg *logMessage) {\r\n\tvar buffer *bytes.Buffer\r\n\tbuffer = bufPool.Get().(*bytes.Buffer)\r\n\tbuffer.Reset() \/\/ 不能保证buffer是否被GC\r\n\tdefer bufPool.Put(buffer)\r\n\r\n\te.logger.Lock()\r\n\tdefer e.logger.Unlock()\r\n\r\n\t\/\/ 前缀\r\n\tbuffer.WriteString(e.logPrefix(logMsg.lvl))\r\n\tbuffer.WriteByte(space)\r\n\r\n\t\/\/ 行号\r\n\tif e.cfg.ShowLineNumber {\r\n\t\tbuffer.WriteString(logMsg.lineNo)\r\n\t\tbuffer.WriteByte(space)\r\n\t}\r\n\r\n\t\/\/ 日志信息\r\n\tbuffer.WriteString(logMsg.msg)\r\n\tbuffer.WriteByte(lf)\r\n\r\n\t\/\/ 写入文件\r\n\te.logger.f.Write(buffer.Bytes())\r\n\r\n\t\/\/ 写入标注输出\r\n\tif e.cfg.EnabledStdout {\r\n\t\te.stdout.Write(buffer.Bytes())\r\n\t}\r\n}\r\n\r\nfunc (e *ELog) logPrefix(lvl LogLevel) string {\r\n\tnow := time.Now()\r\n\tprefix := \"\"\r\n\r\n\tif len(e.cfg.TimeLayout) <= 0 {\r\n\t\tprefix = fmt.Sprintf(coreFormat, lvl.String(), now.Format(timeLayout))\r\n\t} else {\r\n\t\tprefix = fmt.Sprintf(coreFormat, lvl.String(), now.Format(e.cfg.TimeLayout))\r\n\t}\r\n\r\n\treturn prefix\r\n}\r\n\r\n\/\/ 失败返回空字符串\r\nfunc getLineNo() (string, error) {\r\n\t_, filePath, lineNo, ok := runtime.Caller(callerDepth)\r\n\tif !ok {\r\n\t\treturn \"\", errLineNo\r\n\t}\r\n\r\n\treturn fmt.Sprintf(\"%s:%d.\", filePath, lineNo), nil\r\n}\r\n<commit_msg>avoid panic main channel.<commit_after>package elog\r\n\r\nimport (\r\n\t\"bytes\"\r\n\t\"errors\"\r\n\t\"fmt\"\r\n\t\"log\"\r\n\t\"os\"\r\n\t\"runtime\"\r\n\t\"sync\"\r\n\t\"time\"\r\n)\r\n\r\nconst (\r\n\tlf          byte = 0x0A \/\/ 换行\r\n\tspace       byte = 0x20 \/\/ 空格\r\n\tcoreFormat       = \"[%s] %v\"\r\n\ttimeLayout       = \"2006-01-02 15:04:05.999\"\r\n\tcallerDepth      = 3\r\n)\r\n\r\nvar (\r\n\tbufPool = &sync.Pool{\r\n\t\tNew: func() interface{} {\r\n\t\t\treturn &bytes.Buffer{}\r\n\t\t},\r\n\t}\r\n\r\n\tmsgPool = &sync.Pool{\r\n\t\tNew: func() interface{} {\r\n\t\t\treturn &logMessage{}\r\n\t\t},\r\n\t}\r\n\r\n\terrLineNo = errors.New(\"ELog: get lineno encounter a error.\")\r\n)\r\n\r\nfunc (e *ELog) baseLog(lvl LogLevel, msg string) {\r\n\tif e.cfg.LogLevel > lvl {\r\n\t\treturn \/\/ 屏蔽打印\r\n\t}\r\n\tlogMsg := msgPool.Get().(*logMessage)\r\n\r\n\tlogMsg.msg = msg\r\n\tlogMsg.lvl = lvl\r\n\tline, err := getLineNo()\r\n\tif err != nil {\r\n\t\tfmt.Fprintln(os.Stderr, \"Get line number encounter a error.\")\r\n\t}\r\n\tlogMsg.lineNo = line\r\n\r\n\te.waitWrite.Wait()\r\n\te.logChan <- logMsg\r\n}\r\n\r\nfunc (e *ELog) Debug(format string, params ...interface{}) {\r\n\te.baseLog(DebugLvl, fmt.Sprintf(format, params...))\r\n}\r\n\r\nfunc (e *ELog) Info(format string, params ...interface{}) {\r\n\te.baseLog(InfoLvl, fmt.Sprintf(format, params...))\r\n}\r\n\r\nfunc (e *ELog) Warn(format string, params ...interface{}) {\r\n\te.baseLog(WarnLvl, fmt.Sprintf(format, params...))\r\n}\r\n\r\nfunc (e *ELog) Error(format string, params ...interface{}) {\r\n\te.baseLog(ErrorLvl, fmt.Sprintf(format, params...))\r\n}\r\n\r\n\/\/ Panic由调用者处理\r\nfunc (e *ELog) Panic(format string, params ...interface{}) {\r\n\te.baseLog(PanicLvl, fmt.Sprintf(format, params...))\r\n}\r\n\r\n\/\/ 这里会退出程序,调用os.Exit()\r\nfunc (e *ELog) Fatal(format string, params ...interface{}) {\r\n\te.baseLog(FatalLvl, fmt.Sprintf(format, params...))\r\n}\r\n\r\n\/\/ core func\r\nfunc (e *ELog) log(logMsg *logMessage) {\r\n\tdefer func() {\r\n\t\tif err := recover(); err != nil {\r\n\t\t\t\/\/ avoid panic main channel.\r\n\t\t\tlog.Printf(\"Recover from a error.Error(%v)\\n\", err)\r\n\t\t}\r\n\t}()\r\n\r\n\tvar buffer *bytes.Buffer\r\n\tbuffer = bufPool.Get().(*bytes.Buffer)\r\n\tbuffer.Reset() \/\/ 不能保证buffer是否被GC\r\n\tdefer bufPool.Put(buffer)\r\n\r\n\te.logger.Lock()\r\n\tdefer e.logger.Unlock()\r\n\r\n\t\/\/ 前缀\r\n\tbuffer.WriteString(e.logPrefix(logMsg.lvl))\r\n\tbuffer.WriteByte(space)\r\n\r\n\t\/\/ 行号\r\n\tif e.cfg.ShowLineNumber {\r\n\t\tbuffer.WriteString(logMsg.lineNo)\r\n\t\tbuffer.WriteByte(space)\r\n\t}\r\n\r\n\t\/\/ 日志信息\r\n\tbuffer.WriteString(logMsg.msg)\r\n\tbuffer.WriteByte(lf)\r\n\r\n\t\/\/ 写入文件\r\n\te.logger.f.Write(buffer.Bytes())\r\n\r\n\t\/\/ 写入标注输出\r\n\tif e.cfg.EnabledStdout {\r\n\t\te.stdout.Write(buffer.Bytes())\r\n\t}\r\n}\r\n\r\nfunc (e *ELog) logPrefix(lvl LogLevel) string {\r\n\tnow := time.Now()\r\n\tprefix := \"\"\r\n\r\n\tif len(e.cfg.TimeLayout) <= 0 {\r\n\t\tprefix = fmt.Sprintf(coreFormat, lvl.String(), now.Format(timeLayout))\r\n\t} else {\r\n\t\tprefix = fmt.Sprintf(coreFormat, lvl.String(), now.Format(e.cfg.TimeLayout))\r\n\t}\r\n\r\n\treturn prefix\r\n}\r\n\r\n\/\/ 失败返回空字符串\r\nfunc getLineNo() (string, error) {\r\n\t_, filePath, lineNo, ok := runtime.Caller(callerDepth)\r\n\tif !ok {\r\n\t\treturn \"\", errLineNo\r\n\t}\r\n\r\n\treturn fmt.Sprintf(\"%s:%d.\", filePath, lineNo), nil\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>package storage\n\nimport (\n\t\"encoding\/binary\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/boltdb\/bolt\"\n\n\t\"github.com\/anacrolix\/torrent\/metainfo\"\n)\n\nvar (\n\tvalue = []byte{}\n)\n\ntype boltPieceCompletion struct {\n\tdb *bolt.DB\n}\n\nfunc NewBoltPieceCompletion(dir string) (ret PieceCompletion, err error) {\n\tp := filepath.Join(dir, \".torrent.bolt.db\")\n\tdb, err := bolt.Open(p, 0660, &bolt.Options{\n\t\tTimeout: time.Second,\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\tret = &boltPieceCompletion{db}\n\treturn\n}\n\nfunc (me *boltPieceCompletion) Get(pk metainfo.PieceKey) (ret bool, err error) {\n\terr = me.db.View(func(tx *bolt.Tx) error {\n\t\tc := tx.Bucket(completed)\n\t\tif c == nil {\n\t\t\treturn nil\n\t\t}\n\t\tih := c.Bucket(pk.InfoHash[:])\n\t\tif ih == nil {\n\t\t\treturn nil\n\t\t}\n\t\tvar key [4]byte\n\t\tbinary.BigEndian.PutUint32(key[:], uint32(pk.Index))\n\t\tret = ih.Get(key[:]) != nil\n\t\treturn nil\n\t})\n\treturn\n}\n\nfunc (me *boltPieceCompletion) Set(pk metainfo.PieceKey, b bool) error {\n\treturn me.db.Update(func(tx *bolt.Tx) error {\n\t\tc, err := tx.CreateBucketIfNotExists(completed)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tih, err := c.CreateBucketIfNotExists(pk.InfoHash[:])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar key [4]byte\n\t\tbinary.BigEndian.PutUint32(key[:], uint32(pk.Index))\n\t\tif b {\n\t\t\treturn ih.Put(key[:], value)\n\t\t} else {\n\t\t\treturn ih.Delete(key[:])\n\t\t}\n\t})\n}\n\nfunc (me *boltPieceCompletion) Close() error {\n\treturn me.db.Close()\n}\n<commit_msg>Make bolt completion DB directory if necessary<commit_after>package storage\n\nimport (\n\t\"encoding\/binary\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/boltdb\/bolt\"\n\n\t\"github.com\/anacrolix\/torrent\/metainfo\"\n)\n\nvar (\n\tvalue = []byte{}\n)\n\ntype boltPieceCompletion struct {\n\tdb *bolt.DB\n}\n\nfunc NewBoltPieceCompletion(dir string) (ret PieceCompletion, err error) {\n\tos.MkdirAll(dir, 0770)\n\tp := filepath.Join(dir, \".torrent.bolt.db\")\n\tdb, err := bolt.Open(p, 0660, &bolt.Options{\n\t\tTimeout: time.Second,\n\t})\n\tif err != nil {\n\t\treturn\n\t}\n\tret = &boltPieceCompletion{db}\n\treturn\n}\n\nfunc (me *boltPieceCompletion) Get(pk metainfo.PieceKey) (ret bool, err error) {\n\terr = me.db.View(func(tx *bolt.Tx) error {\n\t\tc := tx.Bucket(completed)\n\t\tif c == nil {\n\t\t\treturn nil\n\t\t}\n\t\tih := c.Bucket(pk.InfoHash[:])\n\t\tif ih == nil {\n\t\t\treturn nil\n\t\t}\n\t\tvar key [4]byte\n\t\tbinary.BigEndian.PutUint32(key[:], uint32(pk.Index))\n\t\tret = ih.Get(key[:]) != nil\n\t\treturn nil\n\t})\n\treturn\n}\n\nfunc (me *boltPieceCompletion) Set(pk metainfo.PieceKey, b bool) error {\n\treturn me.db.Update(func(tx *bolt.Tx) error {\n\t\tc, err := tx.CreateBucketIfNotExists(completed)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tih, err := c.CreateBucketIfNotExists(pk.InfoHash[:])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar key [4]byte\n\t\tbinary.BigEndian.PutUint32(key[:], uint32(pk.Index))\n\t\tif b {\n\t\t\treturn ih.Put(key[:], value)\n\t\t} else {\n\t\t\treturn ih.Delete(key[:])\n\t\t}\n\t})\n}\n\nfunc (me *boltPieceCompletion) Close() error {\n\treturn me.db.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>package common\n\nimport (\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/webx-top\/com\"\n\t\"github.com\/webx-top\/db\"\n\t\"github.com\/webx-top\/db\/lib\/factory\"\n\t\"github.com\/webx-top\/db\/mysql\"\n)\n\nfunc SQLLineParser(exec func(string) error, lastSQLs ...*string) func(string) error {\n\tvar sqlStr string\n\treturn func(line string) error {\n\t\tif strings.HasPrefix(line, `--`) {\n\t\t\treturn nil\n\t\t}\n\t\tline = strings.TrimRight(line, \"\\r \")\n\t\tif strings.HasPrefix(line, `\/*`) && strings.HasSuffix(line, `*\/;`) {\n\t\t\treturn nil\n\t\t}\n\t\tsqlStr += line\n\t\tif strings.HasSuffix(line, `;`) {\n\t\t\tdefer func() {\n\t\t\t\tsqlStr = ``\n\t\t\t}()\n\t\t\t\/\/println(sqlStr)\n\t\t\tif sqlStr == `;` {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn exec(sqlStr)\n\t\t}\n\t\tsqlStr += \"\\n\"\n\t\treturn nil\n\t}\n}\n\nfunc ParseSQL(sqlFile string, isFile bool, installer func(string) error) (err error) {\n\tinstallFunction := SQLLineParser(installer)\n\tif isFile {\n\t\treturn com.SeekFileLines(sqlFile, installFunction)\n\t}\n\tsqlContent := sqlFile\n\tfor _, line := range strings.Split(sqlContent, \"\\n\") {\n\t\terr = installFunction(line)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ ReplacePrefix 替换前缀数据\nfunc ReplacePrefix(m factory.Model, field string, oldPrefix string, newPrefix string) error {\n\toldPrefix = com.AddSlashes(oldPrefix, '_', '%')\n\tvalue := db.Raw(\"REPLACE(`\"+field+\"`, ?, ?)\", oldPrefix, newPrefix)\n\treturn m.SetField(nil, field, value, field, db.Like(oldPrefix+`%`))\n}\n\nvar (\n\tsqlCharsetRegexp     = regexp.MustCompile(`(?i) (CHARACTER SET |CHARSET=)utf8mb4 `)\n\tsqlCollateRegexp     = regexp.MustCompile(`(?i) (COLLATE[= ])utf8mb4_general_ci`)\n\tsqlCreateTableRegexp = regexp.MustCompile(`(?i)^CREATE TABLE `)\n\tmysqlNetworkRegexp   = regexp.MustCompile(`^[\/]{2,}`)\n)\n\n\/\/ ReplaceCharset 替换DDL语句中的字符集\nfunc ReplaceCharset(sqlStr string, charset string, checkCreateDDL ...bool) string {\n\tif charset == `utf8mb4` {\n\t\treturn sqlStr\n\t}\n\tif len(checkCreateDDL) > 0 && checkCreateDDL[0] {\n\t\tif !sqlCreateTableRegexp.MatchString(sqlStr) {\n\t\t\treturn sqlStr\n\t\t}\n\t}\n\tsqlStr = sqlCharsetRegexp.ReplaceAllString(sqlStr, ` ${1}`+charset+` `)\n\tsqlStr = sqlCollateRegexp.ReplaceAllString(sqlStr, ` ${1}`+charset+`_general_ci`)\n\treturn sqlStr\n}\n\nfunc ParseMysqlConnectionURL(settings *mysql.ConnectionURL) {\n\tif strings.HasPrefix(settings.Host, `unix:`) {\n\t\tsettings.Socket = strings.TrimPrefix(settings.Host, `unix:`)\n\t\tsettings.Socket = mysqlNetworkRegexp.ReplaceAllString(settings.Socket, `\/`)\n\t\tsettings.Host = ``\n\t}\n}\n<commit_msg>update<commit_after>package common\n\nimport (\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/webx-top\/com\"\n\t\"github.com\/webx-top\/db\"\n\t\"github.com\/webx-top\/db\/lib\/factory\"\n\t\"github.com\/webx-top\/db\/mysql\"\n)\n\nfunc SQLLineParser(exec func(string) error) func(string) error {\n\tvar sqlStr string\n\treturn func(line string) error {\n\t\tif strings.HasPrefix(line, `--`) {\n\t\t\treturn nil\n\t\t}\n\t\tline = strings.TrimRight(line, \"\\r \")\n\t\tif strings.HasPrefix(line, `\/*`) && strings.HasSuffix(line, `*\/;`) {\n\t\t\treturn nil\n\t\t}\n\t\tsqlStr += line\n\t\tif strings.HasSuffix(line, `;`) {\n\t\t\tdefer func() {\n\t\t\t\tsqlStr = ``\n\t\t\t}()\n\t\t\t\/\/println(sqlStr)\n\t\t\tif sqlStr == `;` {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn exec(sqlStr)\n\t\t}\n\t\tsqlStr += \"\\n\"\n\t\treturn nil\n\t}\n}\n\nfunc ParseSQL(sqlFile string, isFile bool, installer func(string) error) (err error) {\n\tinstallFunction := SQLLineParser(installer)\n\tif isFile {\n\t\treturn com.SeekFileLines(sqlFile, installFunction)\n\t}\n\tsqlContent := sqlFile\n\tfor _, line := range strings.Split(sqlContent, \"\\n\") {\n\t\terr = installFunction(line)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ ReplacePrefix 替换前缀数据\nfunc ReplacePrefix(m factory.Model, field string, oldPrefix string, newPrefix string) error {\n\toldPrefix = com.AddSlashes(oldPrefix, '_', '%')\n\tvalue := db.Raw(\"REPLACE(`\"+field+\"`, ?, ?)\", oldPrefix, newPrefix)\n\treturn m.SetField(nil, field, value, field, db.Like(oldPrefix+`%`))\n}\n\nvar (\n\tsqlCharsetRegexp     = regexp.MustCompile(`(?i) (CHARACTER SET |CHARSET=)utf8mb4 `)\n\tsqlCollateRegexp     = regexp.MustCompile(`(?i) (COLLATE[= ])utf8mb4_general_ci`)\n\tsqlCreateTableRegexp = regexp.MustCompile(`(?i)^CREATE TABLE `)\n\tmysqlNetworkRegexp   = regexp.MustCompile(`^[\/]{2,}`)\n)\n\n\/\/ ReplaceCharset 替换DDL语句中的字符集\nfunc ReplaceCharset(sqlStr string, charset string, checkCreateDDL ...bool) string {\n\tif charset == `utf8mb4` {\n\t\treturn sqlStr\n\t}\n\tif len(checkCreateDDL) > 0 && checkCreateDDL[0] {\n\t\tif !sqlCreateTableRegexp.MatchString(sqlStr) {\n\t\t\treturn sqlStr\n\t\t}\n\t}\n\tsqlStr = sqlCharsetRegexp.ReplaceAllString(sqlStr, ` ${1}`+charset+` `)\n\tsqlStr = sqlCollateRegexp.ReplaceAllString(sqlStr, ` ${1}`+charset+`_general_ci`)\n\treturn sqlStr\n}\n\nfunc ParseMysqlConnectionURL(settings *mysql.ConnectionURL) {\n\tif strings.HasPrefix(settings.Host, `unix:`) {\n\t\tsettings.Socket = strings.TrimPrefix(settings.Host, `unix:`)\n\t\tsettings.Socket = mysqlNetworkRegexp.ReplaceAllString(settings.Socket, `\/`)\n\t\tsettings.Host = ``\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build integration\n\npackage riak\n\nimport (\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestCreateNodeWithOptionsAndStart(t *testing.T) {\n\to := &testListenerOpts{\n\t\ttest: t,\n\t\thost: \"127.0.0.1\",\n\t\tport: 13340,\n\t}\n\ttl := newTestListener(o)\n\ttl.start()\n\tdefer tl.stop()\n\n\tcount := uint16(16)\n\topts := &NodeOptions{\n\t\tRemoteAddress:       tl.addr,\n\t\tMinConnections:      count,\n\t\tMaxConnections:      count,\n\t\tIdleTimeout:         thirtySeconds,\n\t\tConnectTimeout:      thirtySeconds,\n\t\tRequestTimeout:      thirtySeconds,\n\t\tHealthCheckInterval: time.Millisecond * 500,\n\t\tHealthCheckBuilder:  &PingCommandBuilder{},\n\t}\n\tnode, err := NewNode(opts)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\tif node == nil {\n\t\tt.Fatal(\"expected non-nil node\")\n\t}\n\tif node.addr.Port != int(tl.port) {\n\t\tt.Errorf(\"expected port %d, got: %d\", tl.port, node.addr.Port)\n\t}\n\tif node.addr.Zone != \"\" {\n\t\tt.Errorf(\"expected empty zone, got: %s\", string(node.addr.Zone))\n\t}\n\tif expected, actual := opts.MinConnections, node.cm.minConnections; expected != actual {\n\t\tt.Errorf(\"expected %v, got: %v\", expected, actual)\n\t}\n\tif expected, actual := opts.MaxConnections, node.cm.maxConnections; expected != actual {\n\t\tt.Errorf(\"expected %v, got: %v\", expected, actual)\n\t}\n\tif expected, actual := opts.IdleTimeout, node.cm.idleTimeout; expected != actual {\n\t\tt.Errorf(\"expected %v, got: %v\", expected, actual)\n\t}\n\tif err := node.start(); err != nil {\n\t\tt.Error(err)\n\t}\n\tvar f = func(v interface{}) (bool, bool) {\n\t\tconn := v.(*connection)\n\t\tif conn == nil {\n\t\t\tt.Error(\"got unexpected nil value\")\n\t\t\treturn true, false\n\t\t}\n\t\tif expected, actual := int(tl.port), conn.addr.Port; expected != actual {\n\t\t\tt.Errorf(\"expected %d, got: %d\", expected, actual)\n\t\t}\n\t\tif conn.addr.Zone != \"\" {\n\t\t\tt.Errorf(\"expected empty zone, got: %s\", string(conn.addr.Zone))\n\t\t}\n\t\tif conn.healthCheck != nil {\n\t\t\tt.Error(\"expected nil conn.healthCheck\")\n\t\t}\n\t\tif expected, actual := conn.connectTimeout, opts.ConnectTimeout; expected != actual {\n\t\t\tt.Errorf(\"expected %v, got: %v\", expected, actual)\n\t\t}\n\t\tif expected, actual := conn.requestTimeout, opts.RequestTimeout; expected != actual {\n\t\t\tt.Errorf(\"expected %v, got: %v\", expected, actual)\n\t\t}\n\t\treturn false, true\n\t}\n\tif err := node.cm.q.iterate(f); err != nil {\n\t\tt.Error(err)\n\t}\n\tif err := node.stop(); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestRecoverViaDefaultPingHealthCheck(t *testing.T) {\n\tconnects := 0\n\tvar onConn = func(c net.Conn) bool {\n\t\tconnects++\n\t\tif connects == 1 {\n\t\t\tc.Close()\n\t\t} else {\n\t\t\treadWritePingResp(t, c, true)\n\t\t}\n\t\treturn true\n\t}\n\to := &testListenerOpts{\n\t\ttest:   t,\n\t\thost:   \"127.0.0.1\",\n\t\tport:   13337,\n\t\tonConn: onConn,\n\t}\n\ttl := newTestListener(o)\n\ttl.start()\n\tdefer tl.stop()\n\n\tdoneChan := make(chan struct{})\n\tstateChan := make(chan state)\n\n\tgo func() {\n\t\topts := &NodeOptions{\n\t\t\tRemoteAddress:       tl.addr,\n\t\t\tMinConnections:      0,\n\t\t\tHealthCheckInterval: 50 * time.Millisecond,\n\t\t}\n\t\tnode, err := NewNode(opts)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\torigSetStateFunc := node.setStateFunc\n\t\tnode.setStateFunc = func(sd *stateData, st state) {\n\t\t\torigSetStateFunc(&node.stateData, st)\n\t\t\tlogDebug(\"[TestRecoverViaDefaultPingHealthCheck]\", \"sending state '%v' down stateChan\", st)\n\t\t\tstateChan <- st\n\t\t}\n\n\t\tnode.start()\n\t\tping := &PingCommand{}\n\t\texecuted, err := node.execute(ping)\n\t\tif executed == false {\n\t\t\tt.Fatal(\"expected ping to be executed\")\n\t\t}\n\t\tif err == nil {\n\t\t\tt.Fatal(\"expected non-nil error\")\n\t\t}\n\t\tlogDebug(\"[TestRecoverViaDefaultPingHealthCheck]\", \"waiting to stop node\")\n\t\t<-doneChan\n\t\tlogDebug(\"[TestRecoverViaDefaultPingHealthCheck]\", \"stopping node\")\n\t\tnode.stop()\n\t}()\n\n\tcheckStatesFunc := func(states []state) {\n\t\tfor i := 0; i < len(states); i++ {\n\t\t\tnodeState := <-stateChan\n\t\t\tif expected, actual := states[i], nodeState; expected != actual {\n\t\t\t\tt.Errorf(\"expected %v, got %v\", expected, actual)\n\t\t\t} else {\n\t\t\t\tlogDebug(\"[TestRecoverViaDefaultPingHealthCheck]\", \"saw state %d\", nodeState)\n\t\t\t}\n\t\t}\n\t}\n\n\texpectedStates := []state{\n\t\tnodeRunning, nodeHealthChecking, nodeRunning,\n\t}\n\n\tcheckStatesFunc(expectedStates)\n\n\tclose(doneChan)\n\n\texpectedStates = []state{\n\t\tnodeShuttingDown, nodeShutdown,\n\t}\n\n\tcheckStatesFunc(expectedStates)\n\n\tclose(stateChan)\n}\n\nfunc TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck(t *testing.T) {\n\to := &testListenerOpts{\n\t\ttest: t,\n\t\thost: \"127.0.0.1\",\n\t\tport: 13338,\n\t}\n\ttl := newTestListener(o)\n\tdefer tl.stop()\n\n\tstateChan := make(chan state)\n\trecoveredChan := make(chan struct{})\n\n\tvar node *Node\n\topts := &NodeOptions{\n\t\tConnectTimeout: 125 * time.Millisecond,\n\t\tRemoteAddress:  tl.addr,\n\t}\n\tvar err error\n\tnode, err = NewNode(opts)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\torigSetStateFunc := node.setStateFunc\n\n\tgo func() {\n\t\tnode.setStateFunc = func(sd *stateData, st state) {\n\t\t\torigSetStateFunc(&node.stateData, st)\n\t\t\tlogDebug(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck]\", \"sending state '%v' down stateChan\", st)\n\t\t\tstateChan <- st\n\t\t}\n\t\tnode.start()\n\n\t\tpc := &PingCommand{}\n\t\tnode.execute(pc)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-recoveredChan:\n\t\t\t\tbreak\n\t\t\tcase <-time.After(time.Second):\n\t\t\t\tlogDebug(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck]\", \"waiting for recovery...\")\n\t\t\t\tpc := &PingCommand{}\n\t\t\t\tnode.execute(pc)\n\t\t\t}\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tlistenerStarted := false\n\t\tnodeIsRunningCount := 0\n\t\tfor {\n\t\t\tif nodeState, ok := <-stateChan; ok {\n\t\t\t\tlogDebug(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck]\", \"nodeState: '%v'\", nodeState)\n\t\t\t\tif node.isCurrentState(nodeRunning) {\n\t\t\t\t\tnodeIsRunningCount++\n\t\t\t\t}\n\t\t\t\tif nodeIsRunningCount == 2 {\n\t\t\t\t\t\/\/ This is the second time node has entered nodeRunning state, so it must have recovered via the health check\n\t\t\t\t\tlogDebug(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck]\", \"SUCCESS node recovered via health check\")\n\t\t\t\t\tclose(recoveredChan)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif !listenerStarted && node.isCurrentState(nodeHealthChecking) {\n\t\t\t\t\tlogDebug(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck]\", \"STARTING LISTENER\")\n\t\t\t\t\ttl.start()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tt.Error(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck] stateChan closed before recovering via health check\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-recoveredChan:\n\t\tlogDebug(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck]\", \"recovered\")\n\t\tnode.setStateFunc = origSetStateFunc\n\t\tnode.stop()\n\t\tclose(stateChan)\n\tcase <-time.After(5 * time.Second):\n\t\tt.Error(\"test timed out\")\n\t}\n}\n<commit_msg>Give test a bit more time<commit_after>\/\/ +build integration\n\npackage riak\n\nimport (\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestCreateNodeWithOptionsAndStart(t *testing.T) {\n\to := &testListenerOpts{\n\t\ttest: t,\n\t\thost: \"127.0.0.1\",\n\t\tport: 13340,\n\t}\n\ttl := newTestListener(o)\n\ttl.start()\n\tdefer tl.stop()\n\n\tcount := uint16(16)\n\topts := &NodeOptions{\n\t\tRemoteAddress:       tl.addr,\n\t\tMinConnections:      count,\n\t\tMaxConnections:      count,\n\t\tIdleTimeout:         thirtySeconds,\n\t\tConnectTimeout:      thirtySeconds,\n\t\tRequestTimeout:      thirtySeconds,\n\t\tHealthCheckInterval: time.Millisecond * 500,\n\t\tHealthCheckBuilder:  &PingCommandBuilder{},\n\t}\n\tnode, err := NewNode(opts)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\tif node == nil {\n\t\tt.Fatal(\"expected non-nil node\")\n\t}\n\tif node.addr.Port != int(tl.port) {\n\t\tt.Errorf(\"expected port %d, got: %d\", tl.port, node.addr.Port)\n\t}\n\tif node.addr.Zone != \"\" {\n\t\tt.Errorf(\"expected empty zone, got: %s\", string(node.addr.Zone))\n\t}\n\tif expected, actual := opts.MinConnections, node.cm.minConnections; expected != actual {\n\t\tt.Errorf(\"expected %v, got: %v\", expected, actual)\n\t}\n\tif expected, actual := opts.MaxConnections, node.cm.maxConnections; expected != actual {\n\t\tt.Errorf(\"expected %v, got: %v\", expected, actual)\n\t}\n\tif expected, actual := opts.IdleTimeout, node.cm.idleTimeout; expected != actual {\n\t\tt.Errorf(\"expected %v, got: %v\", expected, actual)\n\t}\n\tif err := node.start(); err != nil {\n\t\tt.Error(err)\n\t}\n\tvar f = func(v interface{}) (bool, bool) {\n\t\tconn := v.(*connection)\n\t\tif conn == nil {\n\t\t\tt.Error(\"got unexpected nil value\")\n\t\t\treturn true, false\n\t\t}\n\t\tif expected, actual := int(tl.port), conn.addr.Port; expected != actual {\n\t\t\tt.Errorf(\"expected %d, got: %d\", expected, actual)\n\t\t}\n\t\tif conn.addr.Zone != \"\" {\n\t\t\tt.Errorf(\"expected empty zone, got: %s\", string(conn.addr.Zone))\n\t\t}\n\t\tif conn.healthCheck != nil {\n\t\t\tt.Error(\"expected nil conn.healthCheck\")\n\t\t}\n\t\tif expected, actual := conn.connectTimeout, opts.ConnectTimeout; expected != actual {\n\t\t\tt.Errorf(\"expected %v, got: %v\", expected, actual)\n\t\t}\n\t\tif expected, actual := conn.requestTimeout, opts.RequestTimeout; expected != actual {\n\t\t\tt.Errorf(\"expected %v, got: %v\", expected, actual)\n\t\t}\n\t\treturn false, true\n\t}\n\tif err := node.cm.q.iterate(f); err != nil {\n\t\tt.Error(err)\n\t}\n\tif err := node.stop(); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestRecoverViaDefaultPingHealthCheck(t *testing.T) {\n\tconnects := 0\n\tvar onConn = func(c net.Conn) bool {\n\t\tconnects++\n\t\tif connects == 1 {\n\t\t\tc.Close()\n\t\t} else {\n\t\t\treadWritePingResp(t, c, true)\n\t\t}\n\t\treturn true\n\t}\n\to := &testListenerOpts{\n\t\ttest:   t,\n\t\thost:   \"127.0.0.1\",\n\t\tport:   13337,\n\t\tonConn: onConn,\n\t}\n\ttl := newTestListener(o)\n\ttl.start()\n\tdefer tl.stop()\n\n\tdoneChan := make(chan struct{})\n\tstateChan := make(chan state)\n\n\tgo func() {\n\t\topts := &NodeOptions{\n\t\t\tRemoteAddress:       tl.addr,\n\t\t\tMinConnections:      0,\n\t\t\tHealthCheckInterval: 50 * time.Millisecond,\n\t\t}\n\t\tnode, err := NewNode(opts)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\torigSetStateFunc := node.setStateFunc\n\t\tnode.setStateFunc = func(sd *stateData, st state) {\n\t\t\torigSetStateFunc(&node.stateData, st)\n\t\t\tlogDebug(\"[TestRecoverViaDefaultPingHealthCheck]\", \"sending state '%v' down stateChan\", st)\n\t\t\tstateChan <- st\n\t\t}\n\n\t\tnode.start()\n\t\tping := &PingCommand{}\n\t\texecuted, err := node.execute(ping)\n\t\tif executed == false {\n\t\t\tt.Fatal(\"expected ping to be executed\")\n\t\t}\n\t\tif err == nil {\n\t\t\tt.Fatal(\"expected non-nil error\")\n\t\t}\n\t\tlogDebug(\"[TestRecoverViaDefaultPingHealthCheck]\", \"waiting to stop node\")\n\t\t<-doneChan\n\t\tlogDebug(\"[TestRecoverViaDefaultPingHealthCheck]\", \"stopping node\")\n\t\tnode.stop()\n\t}()\n\n\tcheckStatesFunc := func(states []state) {\n\t\tfor i := 0; i < len(states); i++ {\n\t\t\tnodeState := <-stateChan\n\t\t\tif expected, actual := states[i], nodeState; expected != actual {\n\t\t\t\tt.Errorf(\"expected %v, got %v\", expected, actual)\n\t\t\t} else {\n\t\t\t\tlogDebug(\"[TestRecoverViaDefaultPingHealthCheck]\", \"saw state %d\", nodeState)\n\t\t\t}\n\t\t}\n\t}\n\n\texpectedStates := []state{\n\t\tnodeRunning, nodeHealthChecking, nodeRunning,\n\t}\n\n\tcheckStatesFunc(expectedStates)\n\n\tclose(doneChan)\n\n\texpectedStates = []state{\n\t\tnodeShuttingDown, nodeShutdown,\n\t}\n\n\tcheckStatesFunc(expectedStates)\n\n\tclose(stateChan)\n}\n\nfunc TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck(t *testing.T) {\n\to := &testListenerOpts{\n\t\ttest: t,\n\t\thost: \"127.0.0.1\",\n\t\tport: 13338,\n\t}\n\ttl := newTestListener(o)\n\tdefer tl.stop()\n\n\tstateChan := make(chan state)\n\trecoveredChan := make(chan struct{})\n\n\tvar node *Node\n\topts := &NodeOptions{\n\t\tConnectTimeout: 125 * time.Millisecond,\n\t\tRemoteAddress:  tl.addr,\n\t}\n\tvar err error\n\tnode, err = NewNode(opts)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\torigSetStateFunc := node.setStateFunc\n\n\tgo func() {\n\t\tnode.setStateFunc = func(sd *stateData, st state) {\n\t\t\torigSetStateFunc(&node.stateData, st)\n\t\t\tlogDebug(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck]\", \"sending state '%v' down stateChan\", st)\n\t\t\tstateChan <- st\n\t\t}\n\t\tnode.start()\n\n\t\tpc := &PingCommand{}\n\t\tnode.execute(pc)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-recoveredChan:\n\t\t\t\tbreak\n\t\t\tcase <-time.After(time.Second):\n\t\t\t\tlogDebug(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck]\", \"waiting for recovery...\")\n\t\t\t\tpc := &PingCommand{}\n\t\t\t\tnode.execute(pc)\n\t\t\t}\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tlistenerStarted := false\n\t\tnodeIsRunningCount := 0\n\t\tfor {\n\t\t\tif nodeState, ok := <-stateChan; ok {\n\t\t\t\tlogDebug(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck]\", \"nodeState: '%v'\", nodeState)\n\t\t\t\tif node.isCurrentState(nodeRunning) {\n\t\t\t\t\tnodeIsRunningCount++\n\t\t\t\t}\n\t\t\t\tif nodeIsRunningCount == 2 {\n\t\t\t\t\t\/\/ This is the second time node has entered nodeRunning state, so it must have recovered via the health check\n\t\t\t\t\tlogDebug(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck]\", \"SUCCESS node recovered via health check\")\n\t\t\t\t\tclose(recoveredChan)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif !listenerStarted && node.isCurrentState(nodeHealthChecking) {\n\t\t\t\t\tlogDebug(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck]\", \"STARTING LISTENER\")\n\t\t\t\t\ttl.start()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tt.Error(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck] stateChan closed before recovering via health check\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-recoveredChan:\n\t\tlogDebug(\"[TestRecoverAfterConnectionComesUpViaDefaultPingHealthCheck]\", \"recovered\")\n\t\tnode.setStateFunc = origSetStateFunc\n\t\tnode.stop()\n\t\tclose(stateChan)\n\tcase <-time.After(10 * time.Second):\n\t\tt.Error(\"test timed out\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Vector Creations Ltd\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage routing\n\nimport (\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/auth\/storage\/accounts\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/auth\/storage\/devices\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/producers\"\n\t\"github.com\/matrix-org\/dendrite\/common\"\n\t\"github.com\/matrix-org\/dendrite\/common\/config\"\n\t\"github.com\/matrix-org\/dendrite\/roomserver\/api\"\n\t\"github.com\/matrix-org\/gomatrixserverlib\"\n\t\"github.com\/matrix-org\/util\"\n)\n\nconst (\n\tpathPrefixV2Keys       = \"\/_matrix\/key\/v2\"\n\tpathPrefixV1Federation = \"\/_matrix\/federation\/v1\"\n)\n\n\/\/ Setup registers HTTP handlers with the given ServeMux.\nfunc Setup(\n\tapiMux *mux.Router,\n\tcfg config.Dendrite,\n\tquery api.RoomserverQueryAPI,\n\taliasAPI api.RoomserverAliasAPI,\n\tproducer *producers.RoomserverProducer,\n\tkeys gomatrixserverlib.KeyRing,\n\tfederation *gomatrixserverlib.FederationClient,\n\taccountDB *accounts.Database,\n\tdeviceDB *devices.Database,\n) {\n\tv2keysmux := apiMux.PathPrefix(pathPrefixV2Keys).Subrouter()\n\tv1fedmux := apiMux.PathPrefix(pathPrefixV1Federation).Subrouter()\n\n\tlocalKeys := common.MakeExternalAPI(\"localkeys\", func(req *http.Request) util.JSONResponse {\n\t\treturn LocalKeys(cfg)\n\t})\n\n\t\/\/ Ignore the {keyID} argument as we only have a single server key so we always\n\t\/\/ return that key.\n\t\/\/ Even if we had more than one server key, we would probably still ignore the\n\t\/\/ {keyID} argument and always return a response containing all of the keys.\n\tv2keysmux.Handle(\"\/server\/{keyID}\", localKeys).Methods(http.MethodGet)\n\tv2keysmux.Handle(\"\/server\/\", localKeys).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/send\/{txnID}\/\", common.MakeFedAPI(\n\t\t\"federation_send\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn Send(\n\t\t\t\thttpReq, request, gomatrixserverlib.TransactionID(vars[\"txnID\"]),\n\t\t\t\tcfg, query, producer, keys, federation,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodPut, http.MethodOptions)\n\n\tv1fedmux.Handle(\"\/invite\/{roomID}\/{eventID}\", common.MakeFedAPI(\n\t\t\"federation_invite\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn Invite(\n\t\t\t\thttpReq, request, vars[\"roomID\"], vars[\"eventID\"],\n\t\t\t\tcfg, producer, keys,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodPut, http.MethodOptions)\n\n\tv1fedmux.Handle(\"\/3pid\/onbind\", common.MakeExternalAPI(\"3pid_onbind\",\n\t\tfunc(req *http.Request) util.JSONResponse {\n\t\t\treturn CreateInvitesFrom3PIDInvites(req, query, cfg, producer, federation, accountDB)\n\t\t},\n\t)).Methods(http.MethodPost, http.MethodOptions)\n\n\tv1fedmux.Handle(\"\/exchange_third_party_invite\/{roomID}\", common.MakeFedAPI(\n\t\t\"exchange_third_party_invite\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn ExchangeThirdPartyInvite(\n\t\t\t\thttpReq, request, vars[\"roomID\"], query, cfg, federation, producer,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodPut, http.MethodOptions)\n\n\tv1fedmux.Handle(\"\/event\/{eventID}\", common.MakeFedAPI(\n\t\t\"federation_get_event\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn GetEvent(\n\t\t\t\thttpReq.Context(), request, query, vars[\"eventID\"],\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/state\/{roomID}\", common.MakeFedAPI(\n\t\t\"federation_get_event_auth\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn GetState(\n\t\t\t\thttpReq.Context(), request, cfg, query, time.Now(),\n\t\t\t\tkeys, vars[\"roomID\"],\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/state_ids\/{roomID}\", common.MakeFedAPI(\n\t\t\"federation_get_event_auth\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn GetStateIDs(\n\t\t\t\thttpReq.Context(), request, cfg, query, time.Now(),\n\t\t\t\tkeys, vars[\"roomID\"],\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/query\/directory\/\", common.MakeFedAPI(\n\t\t\"federation_query_room_alias\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\treturn RoomAliasToID(\n\t\t\t\thttpReq, federation, cfg, aliasAPI,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/query\/profile\", common.MakeFedAPI(\n\t\t\"federation_query_profile\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\treturn GetProfile(\n\t\t\t\thttpReq, accountDB, cfg,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/query\/user_devices\/{userID}\", common.MakeFedAPI(\n\t\t\"federation_query_user_devices\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn GetUserDevices(\n\t\t\t\thttpReq, deviceDB, vars[\"userID\"],\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/make_join\/{roomID}\/{userID}\", common.MakeFedAPI(\n\t\t\"federation_make_join\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\troomID := vars[\"roomID\"]\n\t\t\tuserID := vars[\"userID\"]\n\t\t\treturn MakeJoin(\n\t\t\t\thttpReq, request, cfg, query, roomID, userID,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/send_join\/{roomID}\/{userID}\", common.MakeFedAPI(\n\t\t\"federation_send_join\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\troomID := vars[\"roomID\"]\n\t\t\tuserID := vars[\"userID\"]\n\t\t\treturn SendJoin(\n\t\t\t\thttpReq.Context(), httpReq, request, cfg, query, producer, keys, roomID, userID,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodPut)\n\n\tv1fedmux.Handle(\"\/make_leave\/{roomID}\/{userID}\", common.MakeFedAPI(\n\t\t\"federation_make_leave\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\troomID := vars[\"roomID\"]\n\t\t\tuserID := vars[\"userID\"]\n\t\t\treturn MakeLeave(\n\t\t\t\thttpReq, request, cfg, query, roomID, userID,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/send_leave\/{roomID}\/{userID}\", common.MakeFedAPI(\n\t\t\"federation_send_leave\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\troomID := vars[\"roomID\"]\n\t\t\tuserID := vars[\"userID\"]\n\t\t\treturn SendLeave(\n\t\t\t\thttpReq, request, cfg, producer, keys, roomID, userID,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodPut)\n\n\tv1fedmux.Handle(\"\/version\", common.MakeExternalAPI(\n\t\t\"federation_version\",\n\t\tfunc(httpReq *http.Request) util.JSONResponse {\n\t\t\treturn Version()\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"get_missing_events\/{roomID}\", common.MakeFedAPI(\n\t\t\"federation_get_missing_events\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn GetMissingEvents(httpReq, request, query, vars[\"roomID\"])\n\t\t},\n\t)).Methods(http.MethodGet)\n}\n<commit_msg>Correct user\/devices path (#557)<commit_after>\/\/ Copyright 2017 Vector Creations Ltd\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage routing\n\nimport (\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/auth\/storage\/accounts\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/auth\/storage\/devices\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/producers\"\n\t\"github.com\/matrix-org\/dendrite\/common\"\n\t\"github.com\/matrix-org\/dendrite\/common\/config\"\n\t\"github.com\/matrix-org\/dendrite\/roomserver\/api\"\n\t\"github.com\/matrix-org\/gomatrixserverlib\"\n\t\"github.com\/matrix-org\/util\"\n)\n\nconst (\n\tpathPrefixV2Keys       = \"\/_matrix\/key\/v2\"\n\tpathPrefixV1Federation = \"\/_matrix\/federation\/v1\"\n)\n\n\/\/ Setup registers HTTP handlers with the given ServeMux.\nfunc Setup(\n\tapiMux *mux.Router,\n\tcfg config.Dendrite,\n\tquery api.RoomserverQueryAPI,\n\taliasAPI api.RoomserverAliasAPI,\n\tproducer *producers.RoomserverProducer,\n\tkeys gomatrixserverlib.KeyRing,\n\tfederation *gomatrixserverlib.FederationClient,\n\taccountDB *accounts.Database,\n\tdeviceDB *devices.Database,\n) {\n\tv2keysmux := apiMux.PathPrefix(pathPrefixV2Keys).Subrouter()\n\tv1fedmux := apiMux.PathPrefix(pathPrefixV1Federation).Subrouter()\n\n\tlocalKeys := common.MakeExternalAPI(\"localkeys\", func(req *http.Request) util.JSONResponse {\n\t\treturn LocalKeys(cfg)\n\t})\n\n\t\/\/ Ignore the {keyID} argument as we only have a single server key so we always\n\t\/\/ return that key.\n\t\/\/ Even if we had more than one server key, we would probably still ignore the\n\t\/\/ {keyID} argument and always return a response containing all of the keys.\n\tv2keysmux.Handle(\"\/server\/{keyID}\", localKeys).Methods(http.MethodGet)\n\tv2keysmux.Handle(\"\/server\/\", localKeys).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/send\/{txnID}\/\", common.MakeFedAPI(\n\t\t\"federation_send\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn Send(\n\t\t\t\thttpReq, request, gomatrixserverlib.TransactionID(vars[\"txnID\"]),\n\t\t\t\tcfg, query, producer, keys, federation,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodPut, http.MethodOptions)\n\n\tv1fedmux.Handle(\"\/invite\/{roomID}\/{eventID}\", common.MakeFedAPI(\n\t\t\"federation_invite\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn Invite(\n\t\t\t\thttpReq, request, vars[\"roomID\"], vars[\"eventID\"],\n\t\t\t\tcfg, producer, keys,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodPut, http.MethodOptions)\n\n\tv1fedmux.Handle(\"\/3pid\/onbind\", common.MakeExternalAPI(\"3pid_onbind\",\n\t\tfunc(req *http.Request) util.JSONResponse {\n\t\t\treturn CreateInvitesFrom3PIDInvites(req, query, cfg, producer, federation, accountDB)\n\t\t},\n\t)).Methods(http.MethodPost, http.MethodOptions)\n\n\tv1fedmux.Handle(\"\/exchange_third_party_invite\/{roomID}\", common.MakeFedAPI(\n\t\t\"exchange_third_party_invite\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn ExchangeThirdPartyInvite(\n\t\t\t\thttpReq, request, vars[\"roomID\"], query, cfg, federation, producer,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodPut, http.MethodOptions)\n\n\tv1fedmux.Handle(\"\/event\/{eventID}\", common.MakeFedAPI(\n\t\t\"federation_get_event\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn GetEvent(\n\t\t\t\thttpReq.Context(), request, query, vars[\"eventID\"],\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/state\/{roomID}\", common.MakeFedAPI(\n\t\t\"federation_get_event_auth\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn GetState(\n\t\t\t\thttpReq.Context(), request, cfg, query, time.Now(),\n\t\t\t\tkeys, vars[\"roomID\"],\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/state_ids\/{roomID}\", common.MakeFedAPI(\n\t\t\"federation_get_event_auth\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn GetStateIDs(\n\t\t\t\thttpReq.Context(), request, cfg, query, time.Now(),\n\t\t\t\tkeys, vars[\"roomID\"],\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/query\/directory\/\", common.MakeFedAPI(\n\t\t\"federation_query_room_alias\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\treturn RoomAliasToID(\n\t\t\t\thttpReq, federation, cfg, aliasAPI,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/query\/profile\", common.MakeFedAPI(\n\t\t\"federation_query_profile\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\treturn GetProfile(\n\t\t\t\thttpReq, accountDB, cfg,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/user\/devices\/{userID}\", common.MakeFedAPI(\n\t\t\"federation_user_devices\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn GetUserDevices(\n\t\t\t\thttpReq, deviceDB, vars[\"userID\"],\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/make_join\/{roomID}\/{userID}\", common.MakeFedAPI(\n\t\t\"federation_make_join\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\troomID := vars[\"roomID\"]\n\t\t\tuserID := vars[\"userID\"]\n\t\t\treturn MakeJoin(\n\t\t\t\thttpReq, request, cfg, query, roomID, userID,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/send_join\/{roomID}\/{userID}\", common.MakeFedAPI(\n\t\t\"federation_send_join\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\troomID := vars[\"roomID\"]\n\t\t\tuserID := vars[\"userID\"]\n\t\t\treturn SendJoin(\n\t\t\t\thttpReq.Context(), httpReq, request, cfg, query, producer, keys, roomID, userID,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodPut)\n\n\tv1fedmux.Handle(\"\/make_leave\/{roomID}\/{userID}\", common.MakeFedAPI(\n\t\t\"federation_make_leave\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\troomID := vars[\"roomID\"]\n\t\t\tuserID := vars[\"userID\"]\n\t\t\treturn MakeLeave(\n\t\t\t\thttpReq, request, cfg, query, roomID, userID,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"\/send_leave\/{roomID}\/{userID}\", common.MakeFedAPI(\n\t\t\"federation_send_leave\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\troomID := vars[\"roomID\"]\n\t\t\tuserID := vars[\"userID\"]\n\t\t\treturn SendLeave(\n\t\t\t\thttpReq, request, cfg, producer, keys, roomID, userID,\n\t\t\t)\n\t\t},\n\t)).Methods(http.MethodPut)\n\n\tv1fedmux.Handle(\"\/version\", common.MakeExternalAPI(\n\t\t\"federation_version\",\n\t\tfunc(httpReq *http.Request) util.JSONResponse {\n\t\t\treturn Version()\n\t\t},\n\t)).Methods(http.MethodGet)\n\n\tv1fedmux.Handle(\"get_missing_events\/{roomID}\", common.MakeFedAPI(\n\t\t\"federation_get_missing_events\", cfg.Matrix.ServerName, keys,\n\t\tfunc(httpReq *http.Request, request *gomatrixserverlib.FederationRequest) util.JSONResponse {\n\t\t\tvars := mux.Vars(httpReq)\n\t\t\treturn GetMissingEvents(httpReq, request, query, vars[\"roomID\"])\n\t\t},\n\t)).Methods(http.MethodGet)\n}\n<|endoftext|>"}
{"text":"<commit_before>package v1\n\nimport (\n\t\"database\/sql\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"git.zxq.co\/ripple\/rippleapi\/common\"\n\t\"git.zxq.co\/ripple\/rippleapi\/limit\"\n)\n\ntype rankRequestsStatusResponse struct {\n\tcommon.ResponseBase\n\tQueueSize       int        `json:\"queue_size\"`\n\tMaxPerUser      int        `json:\"max_per_user\"`\n\tSubmitted       int        `json:\"submitted\"`\n\tSubmittedByUser *int       `json:\"submitted_by_user,omitempty\"`\n\tCanSubmit       *bool      `json:\"can_submit,omitempty\"`\n\tNextExpiration  *time.Time `json:\"next_expiration\"`\n}\n\n\/\/ BeatmapRankRequestsStatusGET gets the current status for beatmap ranking requests.\nfunc BeatmapRankRequestsStatusGET(md common.MethodData) common.CodeMessager {\n\tc := common.GetConf()\n\trows, err := md.DB.Query(\"SELECT userid, time FROM rank_requests WHERE time > ? ORDER BY id ASC LIMIT \"+strconv.Itoa(c.RankQueueSize), time.Now().Add(-time.Hour*24).Unix())\n\tif err != nil {\n\t\tmd.Err(err)\n\t\treturn Err500\n\t}\n\tvar r rankRequestsStatusResponse\n\t\/\/ if it's not auth-free access and we have got ReadConfidential, we can\n\t\/\/ know if this user can submit beatmaps or not.\n\thasConfid := md.ID() != 0 && md.User.TokenPrivileges&common.PrivilegeReadConfidential > 0\n\tif hasConfid {\n\t\tr.SubmittedByUser = new(int)\n\t}\n\tisFirst := true\n\tfor rows.Next() {\n\t\tvar (\n\t\t\tuser      int\n\t\t\ttimestamp common.UnixTimestamp\n\t\t)\n\t\terr := rows.Scan(&user, &timestamp)\n\t\tif err != nil {\n\t\t\tmd.Err(err)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ if the user submitted this rank request, increase the number of\n\t\t\/\/ rank requests submitted by this user\n\t\tif user == md.ID() && r.SubmittedByUser != nil {\n\t\t\t(*r.SubmittedByUser)++\n\t\t}\n\t\t\/\/ also, if this is the first result, it means it will be the next to\n\t\t\/\/ expire.\n\t\tif isFirst {\n\t\t\tx := time.Time(timestamp)\n\t\t\tr.NextExpiration = &x\n\t\t\tisFirst = false\n\t\t}\n\t\tr.Submitted++\n\t}\n\tr.QueueSize = c.RankQueueSize\n\tr.MaxPerUser = c.BeatmapRequestsPerUser\n\tif hasConfid {\n\t\tx := r.Submitted < r.QueueSize && *r.SubmittedByUser < r.MaxPerUser\n\t\tr.CanSubmit = &x\n\t}\n\tr.Code = 200\n\treturn r\n}\n\ntype submitRequestData struct {\n\tID    int `json:\"id\"`\n\tSetID int `json:\"set_id\"`\n}\n\n\/\/ BeatmapRankRequestsSubmitPOST submits a new beatmap for ranking approval.\nfunc BeatmapRankRequestsSubmitPOST(md common.MethodData) common.CodeMessager {\n\tvar d submitRequestData\n\terr := md.RequestData.Unmarshal(&d)\n\tif err != nil {\n\t\treturn ErrBadJSON\n\t}\n\t\/\/ check json data is present\n\tif d.ID == 0 && d.SetID == 0 {\n\t\treturn ErrMissingField(\"id|set_id\")\n\t}\n\n\t\/\/ you've been rate limited\n\tif !limit.NonBlockingRequest(\"rankrequest:u:\"+strconv.Itoa(md.ID()), 5) {\n\t\treturn common.SimpleResponse(429, \"You may only try to request 5 beatmaps per minute.\")\n\t}\n\tif !limit.NonBlockingRequest(\"rankrequest:ip:\"+md.C.ClientIP(), 8) {\n\t\treturn common.SimpleResponse(429, \"You may only try to request 8 beatmaps per minute from the same IP.\")\n\t}\n\n\t\/\/ find out from BeatmapRankRequestsStatusGET if we can submit beatmaps.\n\tstatusRaw := BeatmapRankRequestsStatusGET(md)\n\tstatus, ok := statusRaw.(rankRequestsStatusResponse)\n\tif !ok {\n\t\t\/\/ if it's not a rankRequestsStatusResponse, it means it's an error\n\t\treturn statusRaw\n\t}\n\tif !*status.CanSubmit {\n\t\treturn common.SimpleResponse(403, \"It's not possible to do a rank request at this time.\")\n\t}\n\n\tw := common.\n\t\tWhere(\"beatmap_id = ?\", strconv.Itoa(d.ID)).Or().\n\t\tWhere(\"beatmapset_id = ?\", strconv.Itoa(d.SetID))\n\n\tvar ranked int\n\terr = md.DB.QueryRow(\"SELECT ranked FROM beatmaps \"+w.Clause+\" LIMIT 1\", w.Params...).Scan(&ranked)\n\tif ranked >= 2 {\n\t\treturn common.SimpleResponse(406, \"That beatmap is already ranked.\")\n\t}\n\n\tswitch err {\n\tcase nil:\n\t\t\/\/ move on\n\tcase sql.ErrNoRows:\n\t\tif d.SetID != 0 {\n\t\t\tmd.R.Publish(\"lets:beatmap_updates:sets\", strconv.Itoa(d.SetID))\n\t\t} else {\n\t\t\tmd.R.Publish(\"lets:beatmap_updates:single\", strconv.Itoa(d.ID))\n\t\t}\n\tdefault:\n\t\tmd.Err(err)\n\t\treturn Err500\n\t}\n\n\t\/\/ type and value of beatmap rank request\n\tt := \"b\"\n\tv := d.ID\n\tif d.SetID != 0 {\n\t\tt = \"s\"\n\t\tv = d.SetID\n\t}\n\terr = md.DB.QueryRow(\"SELECT 1 FROM rank_requests WHERE bid = ? AND type = ? AND time > ?\",\n\t\tv, t, time.Now().Add(-time.Hour*24).Unix()).Scan(new(int))\n\n\t\/\/ error handling\n\tswitch err {\n\tcase sql.ErrNoRows:\n\t\tbreak\n\tcase nil:\n\t\t\/\/ we're returning a success because if the request was already sent in the past 24\n\t\t\/\/ hours, it's as if the user submitted it.\n\t\treturn BeatmapRankRequestsStatusGET(md)\n\tdefault:\n\t\tmd.Err(err)\n\t\treturn Err500\n\t}\n\n\t_, err = md.DB.Exec(\n\t\t\"INSERT INTO rank_requests (userid, bid, type, time, blacklisted) VALUES (?, ?, ?, ?, 0)\",\n\t\tmd.ID(), v, t, time.Now().Unix())\n\tif err != nil {\n\t\tmd.Err(err)\n\t\treturn Err500\n\t}\n\n\treturn BeatmapRankRequestsStatusGET(md)\n}\n<commit_msg>Use JSON instead of GLI ZINGONI<commit_after>package v1\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"git.zxq.co\/ripple\/rippleapi\/common\"\n\t\"git.zxq.co\/ripple\/rippleapi\/limit\"\n)\n\ntype rankRequestsStatusResponse struct {\n\tcommon.ResponseBase\n\tQueueSize       int        `json:\"queue_size\"`\n\tMaxPerUser      int        `json:\"max_per_user\"`\n\tSubmitted       int        `json:\"submitted\"`\n\tSubmittedByUser *int       `json:\"submitted_by_user,omitempty\"`\n\tCanSubmit       *bool      `json:\"can_submit,omitempty\"`\n\tNextExpiration  *time.Time `json:\"next_expiration\"`\n}\n\n\/\/ BeatmapRankRequestsStatusGET gets the current status for beatmap ranking requests.\nfunc BeatmapRankRequestsStatusGET(md common.MethodData) common.CodeMessager {\n\tc := common.GetConf()\n\trows, err := md.DB.Query(\"SELECT userid, time FROM rank_requests WHERE time > ? ORDER BY id ASC LIMIT \"+strconv.Itoa(c.RankQueueSize), time.Now().Add(-time.Hour*24).Unix())\n\tif err != nil {\n\t\tmd.Err(err)\n\t\treturn Err500\n\t}\n\tvar r rankRequestsStatusResponse\n\t\/\/ if it's not auth-free access and we have got ReadConfidential, we can\n\t\/\/ know if this user can submit beatmaps or not.\n\thasConfid := md.ID() != 0 && md.User.TokenPrivileges&common.PrivilegeReadConfidential > 0\n\tif hasConfid {\n\t\tr.SubmittedByUser = new(int)\n\t}\n\tisFirst := true\n\tfor rows.Next() {\n\t\tvar (\n\t\t\tuser      int\n\t\t\ttimestamp common.UnixTimestamp\n\t\t)\n\t\terr := rows.Scan(&user, &timestamp)\n\t\tif err != nil {\n\t\t\tmd.Err(err)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ if the user submitted this rank request, increase the number of\n\t\t\/\/ rank requests submitted by this user\n\t\tif user == md.ID() && r.SubmittedByUser != nil {\n\t\t\t(*r.SubmittedByUser)++\n\t\t}\n\t\t\/\/ also, if this is the first result, it means it will be the next to\n\t\t\/\/ expire.\n\t\tif isFirst {\n\t\t\tx := time.Time(timestamp)\n\t\t\tr.NextExpiration = &x\n\t\t\tisFirst = false\n\t\t}\n\t\tr.Submitted++\n\t}\n\tr.QueueSize = c.RankQueueSize\n\tr.MaxPerUser = c.BeatmapRequestsPerUser\n\tif hasConfid {\n\t\tx := r.Submitted < r.QueueSize && *r.SubmittedByUser < r.MaxPerUser\n\t\tr.CanSubmit = &x\n\t}\n\tr.Code = 200\n\treturn r\n}\n\ntype submitRequestData struct {\n\tID    int `json:\"id\"`\n\tSetID int `json:\"set_id\"`\n}\n\n\/\/ BeatmapRankRequestsSubmitPOST submits a new beatmap for ranking approval.\nfunc BeatmapRankRequestsSubmitPOST(md common.MethodData) common.CodeMessager {\n\tvar d submitRequestData\n\terr := md.RequestData.Unmarshal(&d)\n\tif err != nil {\n\t\treturn ErrBadJSON\n\t}\n\t\/\/ check json data is present\n\tif d.ID == 0 && d.SetID == 0 {\n\t\treturn ErrMissingField(\"id|set_id\")\n\t}\n\n\t\/\/ you've been rate limited\n\tif !limit.NonBlockingRequest(\"rankrequest:u:\"+strconv.Itoa(md.ID()), 5) {\n\t\treturn common.SimpleResponse(429, \"You may only try to request 5 beatmaps per minute.\")\n\t}\n\tif !limit.NonBlockingRequest(\"rankrequest:ip:\"+md.C.ClientIP(), 8) {\n\t\treturn common.SimpleResponse(429, \"You may only try to request 8 beatmaps per minute from the same IP.\")\n\t}\n\n\t\/\/ find out from BeatmapRankRequestsStatusGET if we can submit beatmaps.\n\tstatusRaw := BeatmapRankRequestsStatusGET(md)\n\tstatus, ok := statusRaw.(rankRequestsStatusResponse)\n\tif !ok {\n\t\t\/\/ if it's not a rankRequestsStatusResponse, it means it's an error\n\t\treturn statusRaw\n\t}\n\tif !*status.CanSubmit {\n\t\treturn common.SimpleResponse(403, \"It's not possible to do a rank request at this time.\")\n\t}\n\n\tw := common.\n\t\tWhere(\"beatmap_id = ?\", strconv.Itoa(d.ID)).Or().\n\t\tWhere(\"beatmapset_id = ?\", strconv.Itoa(d.SetID))\n\n\tvar ranked int\n\terr = md.DB.QueryRow(\"SELECT ranked FROM beatmaps \"+w.Clause+\" LIMIT 1\", w.Params...).Scan(&ranked)\n\tif ranked >= 2 {\n\t\treturn common.SimpleResponse(406, \"That beatmap is already ranked.\")\n\t}\n\n\tswitch err {\n\tcase nil:\n\t\t\/\/ move on\n\tcase sql.ErrNoRows:\n\t\tdata, _ := json.Marshal(d)\n\t\tmd.R.Publish(\"lets:beatmap_updates\", string(data))\n\tdefault:\n\t\tmd.Err(err)\n\t\treturn Err500\n\t}\n\n\t\/\/ type and value of beatmap rank request\n\tt := \"b\"\n\tv := d.ID\n\tif d.SetID != 0 {\n\t\tt = \"s\"\n\t\tv = d.SetID\n\t}\n\terr = md.DB.QueryRow(\"SELECT 1 FROM rank_requests WHERE bid = ? AND type = ? AND time > ?\",\n\t\tv, t, time.Now().Add(-time.Hour*24).Unix()).Scan(new(int))\n\n\t\/\/ error handling\n\tswitch err {\n\tcase sql.ErrNoRows:\n\t\tbreak\n\tcase nil:\n\t\t\/\/ we're returning a success because if the request was already sent in the past 24\n\t\t\/\/ hours, it's as if the user submitted it.\n\t\treturn BeatmapRankRequestsStatusGET(md)\n\tdefault:\n\t\tmd.Err(err)\n\t\treturn Err500\n\t}\n\n\t_, err = md.DB.Exec(\n\t\t\"INSERT INTO rank_requests (userid, bid, type, time, blacklisted) VALUES (?, ?, ?, ?, 0)\",\n\t\tmd.ID(), v, t, time.Now().Unix())\n\tif err != nil {\n\t\tmd.Err(err)\n\t\treturn Err500\n\t}\n\n\treturn BeatmapRankRequestsStatusGET(md)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"sort\"\n\n\t\"image\"\n\t\"image\/draw\"\n\t\"image\/png\"\n)\n\ntype Size struct {\n\tx, y int\n}\n\nfunc (a Size) Equal(b Size) bool {\n\treturn a.x == b.x && a.y == b.y\n}\n\nfunc (a Size) Larger(b Size) bool {\n\treturn b.x < a.x && b.y < a.y\n}\n\nfunc (a Size) Smaller(b Size) bool {\n\treturn !a.Larger(b)\n}\n\ntype sprite struct {\n\tname string\n\timg  image.Image\n\trect image.Rectangle\n\tarea int\n\tsize Size\n}\n\ntype ByArea []sprite\n\nfunc (a ByArea) Len() int           { return len(a) }\nfunc (a ByArea) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a ByArea) Less(i, j int) bool { return a[i].area < a[j].area }\n\ntype Node struct {\n\tchild [2]*Node\n\trect  image.Rectangle\n\timg   *sprite\n}\n\nfunc (n *Node) size() Size {\n\treturn Size{n.rect.Dx(), n.rect.Dy()}\n}\n\nfunc (n *Node) print() {\n\tfmt.Println(n)\n\tif n.child[0] != nil {\n\t\tn.child[0].print()\n\t}\n\tif n.child[1] != nil {\n\t\tn.child[1].print()\n\t}\n}\n\nfunc (n *Node) insert(img *sprite) bool {\n\t\/\/ there is already an image in this node\n\tif n.img != nil {\n\t\tfmt.Println(\"already contains an image\")\n\t\treturn false\n\t}\n\n\t\/\/ try to insert into either of the nodes children\n\tif n.child[0] != nil {\n\t\tfmt.Println(\"has a 0 child\")\n\t\tin := n.child[0].insert(img)\n\n\t\tif in {\n\t\t\treturn true\n\t\t} else {\n\t\t\tfmt.Println(\"has a 1 child\")\n\t\t\treturn n.child[1].insert(img)\n\t\t}\n\t}\n\n\tif n.rect.Dx() < img.size.x || n.rect.Dy() < img.size.y {\n\t\tfmt.Println(\"space too small\")\n\t\treturn false\n\t}\n\n\tif n.rect.Dx() == img.size.x && n.rect.Dy() == img.size.y {\n\t\tfmt.Println(\"prefect fit\")\n\t\tn.img = img\n\t\treturn true\n\t}\n\n\tif n.rect.Dx() >= img.size.x && n.rect.Dy() >= img.size.y {\n\t\tfmt.Println(\"Split\")\n\t\tn.split(img)\n\t}\n\n\treturn n.insert(img)\n\n}\n\nfunc (n *Node) split(img *sprite) {\n\tvar tl0 image.Point\n\tvar br0 image.Point\n\n\tvar tl1 image.Point\n\tvar br1 image.Point\n\n\tdx := n.size().x - img.size.x\n\tdy := n.size().y - img.size.y\n\n\trc := n.rect\n\n\ttl0 = rc.Min\n\tbr1 = rc.Max\n\n\tif dx > dy {\n\t\tfmt.Println(\"split on x\")\n\t\tbr0 = image.Point{rc.Min.X + img.size.x, rc.Dy()}\n\t\ttl1 = image.Point{rc.Min.X + img.size.x - 1, rc.Min.Y}\n\t} else {\n\t\tfmt.Println(\"split on y\")\n\t\tbr0 = image.Point{rc.Dx(), rc.Min.Y + img.size.y}\n\t\ttl1 = image.Point{rc.Min.X, rc.Min.Y + img.size.y - 1}\n\t}\n\n\trect0 := image.Rectangle{tl0, br0}\n\tn.child[0] = &Node{rect: rect0}\n\n\trect1 := image.Rectangle{tl1, br1}\n\tn.child[1] = &Node{rect: rect1}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\targs := flag.Args()\n\n\tinputDir := args[0]\n\n\tfiles, _ := ioutil.ReadDir(inputDir)\n\tsprites := make([]sprite, len(files))\n\n\ttotalX := 0\n\ttotalY := 0\n\n\tfor i := range sprites {\n\t\ts := readSprite(inputDir, files[i].Name())\n\t\tsprites[i] = s\n\t\ttotalX += s.size.x\n\t\ttotalY += s.size.y\n\t}\n\n\t\/\/ we want to place the largest sprite first\n\tsort.Sort(sort.Reverse(ByArea(sprites)))\n\n\t\/\/ the final image\n\tdst := image.NewRGBA(image.Rect(0, 0, 2048, 2048))\n\n\tn := Node{rect: image.Rect(0, 0, 1024, 1024)}\n\n\tfor i := range sprites {\n\t\ts := &sprites[i]\n\t\tfmt.Printf(\"inserting %s\\n\", s.name)\n\t\tn.insert(s)\n\t\tdraw.Draw(dst, s.rect, s.img, image.ZP, draw.Src)\n\t}\n\n\tn.print()\n\n\twriter, err := os.Create(\"test.png\")\n\terr = png.Encode(writer, dst)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc readSprite(dir, name string) (s sprite) {\n\tpath := path.Join(dir, name)\n\treader, err := os.Open(path)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer reader.Close()\n\n\timg, err := png.Decode(reader)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ts.name = name\n\ts.img = img\n\ts.rect = img.Bounds()\n\ts.size = Size{s.rect.Dx(), s.rect.Dy()}\n\ts.area = s.size.x * s.size.y\n\treturn\n}\n<commit_msg>Return fitting rectangle from insert<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"sort\"\n\n\t\"image\"\n\t\"image\/draw\"\n\t\"image\/png\"\n)\n\ntype Size struct {\n\tx, y int\n}\n\nfunc (a Size) Equal(b Size) bool {\n\treturn a.x == b.x && a.y == b.y\n}\n\nfunc (a Size) Larger(b Size) bool {\n\treturn b.x < a.x && b.y < a.y\n}\n\nfunc (a Size) Smaller(b Size) bool {\n\treturn !a.Larger(b)\n}\n\ntype sprite struct {\n\tname string\n\timg  image.Image\n\trect image.Rectangle\n\tarea int\n\tsize Size\n}\n\ntype ByArea []sprite\n\nfunc (a ByArea) Len() int           { return len(a) }\nfunc (a ByArea) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a ByArea) Less(i, j int) bool { return a[i].area < a[j].area }\n\ntype Node struct {\n\tchild [2]*Node\n\trect  image.Rectangle\n\timg   *sprite\n}\n\nfunc (n *Node) size() Size {\n\treturn Size{n.rect.Dx(), n.rect.Dy()}\n}\n\nfunc (n *Node) print() {\n\tfmt.Println(n)\n\tif n.child[0] != nil {\n\t\tn.child[0].print()\n\t}\n\tif n.child[1] != nil {\n\t\tn.child[1].print()\n\t}\n}\n\nfunc (n *Node) insert(img *sprite) (*image.Rectangle, error) {\n\t\/\/ there is already an image in this node\n\tif n.img != nil {\n\t\tfmt.Println(\"already contains an image\")\n\t\treturn nil, errors.New(\"already contains an image\")\n\t}\n\n\t\/\/ try to insert into either of the nodes children\n\tif n.child[0] != nil {\n\t\tfmt.Println(\"has a 0 child\")\n\t\trc, err := n.child[0].insert(img)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"has a 1 child\")\n\t\t\treturn n.child[1].insert(img)\n\t\t} else {\n\t\t\treturn rc, nil\n\t\t}\n\t}\n\n\tif n.rect.Dx() < img.size.x || n.rect.Dy() < img.size.y {\n\t\tfmt.Println(\"space too small\")\n\t\treturn nil, errors.New(\"space too small\")\n\t}\n\n\tif n.rect.Dx() == img.size.x && n.rect.Dy() == img.size.y {\n\t\tfmt.Println(\"prefect fit\")\n\t\tn.img = img\n\t\treturn &n.rect, nil\n\t}\n\n\tif n.rect.Dx() >= img.size.x && n.rect.Dy() >= img.size.y {\n\t\tfmt.Println(\"Split\")\n\t\tn.split(img)\n\t}\n\n\treturn n.insert(img)\n\n}\n\nfunc (n *Node) split(img *sprite) {\n\tvar tl0 image.Point\n\tvar br0 image.Point\n\n\tvar tl1 image.Point\n\tvar br1 image.Point\n\n\tdx := n.size().x - img.size.x\n\tdy := n.size().y - img.size.y\n\n\trc := n.rect\n\n\ttl0 = rc.Min\n\tbr1 = rc.Max\n\n\tif dx > dy {\n\t\tfmt.Println(\"split on x\")\n\t\tbr0 = image.Point{rc.Min.X + img.size.x, rc.Dy()}\n\t\ttl1 = image.Point{rc.Min.X + img.size.x - 1, rc.Min.Y}\n\t} else {\n\t\tfmt.Println(\"split on y\")\n\t\tbr0 = image.Point{rc.Dx(), rc.Min.Y + img.size.y}\n\t\ttl1 = image.Point{rc.Min.X, rc.Min.Y + img.size.y - 1}\n\t}\n\n\trect0 := image.Rectangle{tl0, br0}\n\tn.child[0] = &Node{rect: rect0}\n\n\trect1 := image.Rectangle{tl1, br1}\n\tn.child[1] = &Node{rect: rect1}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\targs := flag.Args()\n\n\tinputDir := args[0]\n\n\tfiles, _ := ioutil.ReadDir(inputDir)\n\tsprites := make([]sprite, len(files))\n\n\ttotalX := 0\n\ttotalY := 0\n\n\tfor i := range sprites {\n\t\ts := readSprite(inputDir, files[i].Name())\n\t\tsprites[i] = s\n\t\ttotalX += s.size.x\n\t\ttotalY += s.size.y\n\t}\n\n\t\/\/ we want to place the largest sprite first\n\tsort.Sort(sort.Reverse(ByArea(sprites)))\n\n\t\/\/ the final image\n\tdst := image.NewRGBA(image.Rect(0, 0, 2048, 2048))\n\n\tn := Node{rect: image.Rect(0, 0, 1024, 1024)}\n\n\tfor i := range sprites {\n\t\ts := &sprites[i]\n\t\tfmt.Printf(\"inserting %s\\n\", s.name)\n\t\tn.insert(s)\n\t\tdraw.Draw(dst, s.rect, s.img, image.ZP, draw.Src)\n\t}\n\n\tn.print()\n\n\twriter, err := os.Create(\"test.png\")\n\terr = png.Encode(writer, dst)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc readSprite(dir, name string) (s sprite) {\n\tpath := path.Join(dir, name)\n\treader, err := os.Open(path)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer reader.Close()\n\n\timg, err := png.Decode(reader)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ts.name = name\n\ts.img = img\n\ts.rect = img.Bounds()\n\ts.size = Size{s.rect.Dx(), s.rect.Dy()}\n\ts.area = s.size.x * s.size.y\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package handlers\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"google.golang.org\/appengine\"\n\t\"google.golang.org\/appengine\/log\"\n\t\"google.golang.org\/appengine\/user\"\n\n\t\"github.com\/icco\/natnatnat\/models\"\n\t\"github.com\/pilu\/traffic\"\n)\n\ntype ImportStruct struct {\n\tId       int\n\tDatetime time.Time\n\tText     string\n\tTitle    string\n}\n\nfunc ImportTumbleHandler(w traffic.ResponseWriter, r *traffic.Request) {\n\tc := appengine.NewContext(r.Request)\n\tu := user.Current(c)\n\tif u == nil {\n\t\turl, _ := user.LoginURL(c, \"\/post\/new\")\n\t\thttp.Redirect(w, r.Request, url, 302)\n\t\treturn\n\t} else {\n\t\tlog.Infof(c, \"Logged in as: %s\", u.String())\n\t}\n\n\tif u != nil && !user.IsAdmin(c) {\n\t\thttp.Error(w, errors.New(\"Not a valid user.\").Error(), 403)\n\t\treturn\n\t} else {\n\t\tfile, err := ioutil.ReadFile(\"tumbledata.json\")\n\t\tif err != nil {\n\t\t\te := fmt.Sprintf(\"File error: %v\", err)\n\t\t\thttp.Error(w, e, 500)\n\t\t\treturn\n\t\t}\n\n\t\tvar data []ImportStruct\n\t\tjson.Unmarshal(file, &data)\n\t\tlog.Debugf(\"Loaded: %v\", data)\n\n\t\tw.WriteText(\"Finished.\")\n\t}\n}\n<commit_msg>fix imports<commit_after>package handlers\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"google.golang.org\/appengine\"\n\t\"google.golang.org\/appengine\/log\"\n\t\"google.golang.org\/appengine\/user\"\n\n\t\"github.com\/icco\/natnatnat\/models\"\n\t\"github.com\/pilu\/traffic\"\n)\n\ntype ImportStruct struct {\n\tId       int\n\tDatetime time.Time\n\tText     string\n\tTitle    string\n}\n\nfunc ImportTumbleHandler(w traffic.ResponseWriter, r *traffic.Request) {\n\tc := appengine.NewContext(r.Request)\n\tu := user.Current(c)\n\tmd := models.Markdown(\"test\")\n\tif u == nil {\n\t\turl, _ := user.LoginURL(c, \"\/post\/new\")\n\t\thttp.Redirect(w, r.Request, url, 302)\n\t\treturn\n\t} else {\n\t\tlog.Infof(c, \"Logged in as: %s\", u.String())\n\t}\n\n\tif u != nil && !user.IsAdmin(c) {\n\t\thttp.Error(w, errors.New(\"Not a valid user.\").Error(), 403)\n\t\treturn\n\t} else {\n\t\tfile, err := ioutil.ReadFile(\"tumbledata.json\")\n\t\tif err != nil {\n\t\t\te := fmt.Sprintf(\"File error: %v\", err)\n\t\t\thttp.Error(w, e, 500)\n\t\t\treturn\n\t\t}\n\n\t\tvar data []ImportStruct\n\t\tjson.Unmarshal(file, &data)\n\t\tlog.Debugf(\"Loaded: %v\", data)\n\n\t\tw.WriteText(\"Finished.\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/lakeformation\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/validation\"\n)\n\nfunc resourceAwsLakeFormationResource() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsLakeFormationResourceRegister,\n\t\tRead:   resourceAwsLakeFormationResourceDescribe,\n\t\tDelete: resourceAwsLakeFormationResourceDeregister,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"resource_arn\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tRequired:     true,\n\t\t\t\tForceNew:     true,\n\t\t\t\tValidateFunc: validation.NoZeroValues,\n\t\t\t},\n\t\t\t\"role_arn\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tOptional:     true,\n\t\t\t\tComputed:     true,\n\t\t\t\tForceNew:     true,\n\t\t\t\tValidateFunc: validation.NoZeroValues,\n\t\t\t},\n\t\t\t\"use_service_linked_role\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"last_modified\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceAwsLakeFormationResourceRegister(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).lakeformationconn\n\tresourceArn := d.Get(\"resource_arn\").(string)\n\tuseServiceLinkedRole := d.Get(\"use_service_linked_role\").(bool)\n\n\tinput := &lakeformation.RegisterResourceInput{\n\t\tResourceArn:          aws.String(resourceArn),\n\t\tUseServiceLinkedRole: aws.Bool(useServiceLinkedRole),\n\t}\n\tif v, ok := d.GetOk(\"role_arn\"); ok {\n\t\tinput.RoleArn = aws.String(v.(string))\n\t}\n\n\t_, err := conn.RegisterResource(input)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error registering LakeFormation Resource: %s\", err)\n\t}\n\n\td.SetId(fmt.Sprintf(\"lakeformation:resource:%s\", resourceArn))\n\n\treturn resourceAwsLakeFormationResourceDescribe(d, meta)\n}\n\nfunc resourceAwsLakeFormationResourceDescribe(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).lakeformationconn\n\tresourceArn := d.Get(\"resource_arn\").(string)\n\n\tinput := &lakeformation.DescribeResourceInput{\n\t\tResourceArn: aws.String(resourceArn),\n\t}\n\n\tout, err := conn.DescribeResource(input)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error reading LakeFormation Resource: %s\", err)\n\t}\n\n\td.Set(\"resource_arn\", resourceArn)\n\td.Set(\"role_arn\", out.ResourceInfo.RoleArn)\n\tif out.ResourceInfo.LastModified != nil {\n\t\td.Set(\"last_modified\", out.ResourceInfo.LastModified.Format(time.RFC3339))\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsLakeFormationResourceDeregister(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).lakeformationconn\n\tresourceArn := d.Get(\"resource_arn\").(string)\n\n\tinput := &lakeformation.DeregisterResourceInput{\n\t\tResourceArn: aws.String(resourceArn),\n\t}\n\n\t_, err := conn.DeregisterResource(input)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deregistering LakeFormation Resource: %s\", err)\n\t}\n\n\treturn nil\n}\n<commit_msg>Better validations<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/lakeformation\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n)\n\nfunc resourceAwsLakeFormationResource() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsLakeFormationResourceRegister,\n\t\tRead:   resourceAwsLakeFormationResourceDescribe,\n\t\tDelete: resourceAwsLakeFormationResourceDeregister,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"resource_arn\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tRequired:     true,\n\t\t\t\tForceNew:     true,\n\t\t\t\tValidateFunc: validateArn,\n\t\t\t},\n\t\t\t\"role_arn\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tOptional:     true,\n\t\t\t\tComputed:     true,\n\t\t\t\tForceNew:     true,\n\t\t\t\tValidateFunc: validateArn,\n\t\t\t},\n\t\t\t\"use_service_linked_role\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"last_modified\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceAwsLakeFormationResourceRegister(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).lakeformationconn\n\tresourceArn := d.Get(\"resource_arn\").(string)\n\tuseServiceLinkedRole := d.Get(\"use_service_linked_role\").(bool)\n\n\tinput := &lakeformation.RegisterResourceInput{\n\t\tResourceArn:          aws.String(resourceArn),\n\t\tUseServiceLinkedRole: aws.Bool(useServiceLinkedRole),\n\t}\n\tif v, ok := d.GetOk(\"role_arn\"); ok {\n\t\tinput.RoleArn = aws.String(v.(string))\n\t}\n\n\t_, err := conn.RegisterResource(input)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error registering LakeFormation Resource: %s\", err)\n\t}\n\n\td.SetId(fmt.Sprintf(\"lakeformation:resource:%s\", resourceArn))\n\n\treturn resourceAwsLakeFormationResourceDescribe(d, meta)\n}\n\nfunc resourceAwsLakeFormationResourceDescribe(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).lakeformationconn\n\tresourceArn := d.Get(\"resource_arn\").(string)\n\n\tinput := &lakeformation.DescribeResourceInput{\n\t\tResourceArn: aws.String(resourceArn),\n\t}\n\n\tout, err := conn.DescribeResource(input)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error reading LakeFormation Resource: %s\", err)\n\t}\n\n\td.Set(\"resource_arn\", resourceArn)\n\td.Set(\"role_arn\", out.ResourceInfo.RoleArn)\n\tif out.ResourceInfo.LastModified != nil {\n\t\td.Set(\"last_modified\", out.ResourceInfo.LastModified.Format(time.RFC3339))\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsLakeFormationResourceDeregister(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).lakeformationconn\n\tresourceArn := d.Get(\"resource_arn\").(string)\n\n\tinput := &lakeformation.DeregisterResourceInput{\n\t\tResourceArn: aws.String(resourceArn),\n\t}\n\n\t_, err := conn.DeregisterResource(input)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deregistering LakeFormation Resource: %s\", err)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage unicode\n\n\/\/ Bit masks for each code point under U+0100, for fast lookup.\nconst (\n\tpC     = 1 << iota \/\/ a control character.\n\tpP                 \/\/ a punctuation character.\n\tpN                 \/\/ a numeral.\n\tpS                 \/\/ a symbolic character.\n\tpZ                 \/\/ a spacing character.\n\tpLu                \/\/ an upper-case letter.\n\tpLl                \/\/ a lower-case letter.\n\tpp                 \/\/ a printable character according to Go's definition.\n\tpg     = pp | pZ   \/\/ a graphical character according to the Unicode definition.\n\tpLo    = pLl | pLu \/\/ a letter that is neither upper nor lower case.\n\tpLmask = pLo\n)\n\n\/\/ GraphicRanges defines the set of graphic characters according to Unicode.\nvar GraphicRanges = []*RangeTable{\n\tL, M, N, P, S, Zs,\n}\n\n\/\/ PrintRanges defines the set of printable characters according to Go.\n\/\/ ASCII space, U+0020, is handled separately.\nvar PrintRanges = []*RangeTable{\n\tL, M, N, P, S,\n}\n\n\/\/ IsGraphic reports whether the rune is defined as a Graphic by Unicode.\n\/\/ Such characters include letters, marks, numbers, punctuation, symbols, and\n\/\/ spaces, from categories L, M, N, P, S, Zs.\nfunc IsGraphic(r rune) bool {\n\t\/\/ We convert to uint32 to avoid the extra test for negative,\n\t\/\/ and in the index we convert to uint8 to avoid the range check.\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&pg != 0\n\t}\n\treturn In(r, GraphicRanges...)\n}\n\n\/\/ IsPrint reports whether the rune is defined as printable by Go. Such\n\/\/ characters include letters, marks, numbers, punctuation, symbols, and the\n\/\/ ASCII space character, from categories L, M, N, P, S and the ASCII space\n\/\/ character.  This categorization is the same as IsGraphic except that the\n\/\/ only spacing character is ASCII space, U+0020.\nfunc IsPrint(r rune) bool {\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&pp != 0\n\t}\n\treturn In(r, PrintRanges...)\n}\n\n\/\/ IsOneOf reports whether the rune is a member of one of the ranges.\n\/\/ The function \"In\" provides a nicer signature and should be used in preference to IsOneOf.\nfunc IsOneOf(ranges []*RangeTable, r rune) bool {\n\tfor _, inside := range ranges {\n\t\tif Is(inside, r) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ In reports whether the rune is a member of one of the ranges.\nfunc In(r rune, ranges ...*RangeTable) bool {\n\tfor _, inside := range ranges {\n\t\tif Is(inside, r) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ IsControl reports whether the rune is a control character.\n\/\/ The C (Other) Unicode category includes more code points\n\/\/ such as surrogates; use Is(C, r) to test for them.\nfunc IsControl(r rune) bool {\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&pC != 0\n\t}\n\t\/\/ All control characters are < Latin1Max.\n\treturn false\n}\n\n\/\/ IsLetter reports whether the rune is a letter (category L).\nfunc IsLetter(r rune) bool {\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&(pLmask) != 0\n\t}\n\treturn isExcludingLatin(Letter, r)\n}\n\n\/\/ IsMark reports whether the rune is a mark character (category M).\nfunc IsMark(r rune) bool {\n\t\/\/ There are no mark characters in Latin-1.\n\treturn isExcludingLatin(Mark, r)\n}\n\n\/\/ IsNumber reports whether the rune is a number (category N).\nfunc IsNumber(r rune) bool {\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&pN != 0\n\t}\n\treturn isExcludingLatin(Number, r)\n}\n\n\/\/ IsPunct reports whether the rune is a Unicode punctuation character\n\/\/ (category P).\nfunc IsPunct(r rune) bool {\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&pP != 0\n\t}\n\treturn Is(Punct, r)\n}\n\n\/\/ IsSpace reports whether the rune is a space character as defined\n\/\/ by Unicode's White Space property; in the Latin-1 space\n\/\/ this is\n\/\/\t'\\t', '\\n', '\\v', '\\f', '\\r', ' ', U+0085 (NEL), U+00A0 (NBSP).\n\/\/ Other definitions of spacing characters are set by category\n\/\/ Z and property Pattern_White_Space.\nfunc IsSpace(r rune) bool {\n\t\/\/ This property isn't the same as Z; special-case it.\n\tif uint32(r) <= MaxLatin1 {\n\t\tswitch r {\n\t\tcase '\\t', '\\n', '\\v', '\\f', '\\r', ' ', 0x85, 0xA0:\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\treturn isExcludingLatin(White_Space, r)\n}\n\n\/\/ IsSymbol reports whether the rune is a symbolic character.\nfunc IsSymbol(r rune) bool {\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&pS != 0\n\t}\n\treturn isExcludingLatin(Symbol, r)\n}\n<commit_msg>unicode: Fixed an out of date comment (MaxLatin1, not Latin1Max).<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage unicode\n\n\/\/ Bit masks for each code point under U+0100, for fast lookup.\nconst (\n\tpC     = 1 << iota \/\/ a control character.\n\tpP                 \/\/ a punctuation character.\n\tpN                 \/\/ a numeral.\n\tpS                 \/\/ a symbolic character.\n\tpZ                 \/\/ a spacing character.\n\tpLu                \/\/ an upper-case letter.\n\tpLl                \/\/ a lower-case letter.\n\tpp                 \/\/ a printable character according to Go's definition.\n\tpg     = pp | pZ   \/\/ a graphical character according to the Unicode definition.\n\tpLo    = pLl | pLu \/\/ a letter that is neither upper nor lower case.\n\tpLmask = pLo\n)\n\n\/\/ GraphicRanges defines the set of graphic characters according to Unicode.\nvar GraphicRanges = []*RangeTable{\n\tL, M, N, P, S, Zs,\n}\n\n\/\/ PrintRanges defines the set of printable characters according to Go.\n\/\/ ASCII space, U+0020, is handled separately.\nvar PrintRanges = []*RangeTable{\n\tL, M, N, P, S,\n}\n\n\/\/ IsGraphic reports whether the rune is defined as a Graphic by Unicode.\n\/\/ Such characters include letters, marks, numbers, punctuation, symbols, and\n\/\/ spaces, from categories L, M, N, P, S, Zs.\nfunc IsGraphic(r rune) bool {\n\t\/\/ We convert to uint32 to avoid the extra test for negative,\n\t\/\/ and in the index we convert to uint8 to avoid the range check.\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&pg != 0\n\t}\n\treturn In(r, GraphicRanges...)\n}\n\n\/\/ IsPrint reports whether the rune is defined as printable by Go. Such\n\/\/ characters include letters, marks, numbers, punctuation, symbols, and the\n\/\/ ASCII space character, from categories L, M, N, P, S and the ASCII space\n\/\/ character.  This categorization is the same as IsGraphic except that the\n\/\/ only spacing character is ASCII space, U+0020.\nfunc IsPrint(r rune) bool {\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&pp != 0\n\t}\n\treturn In(r, PrintRanges...)\n}\n\n\/\/ IsOneOf reports whether the rune is a member of one of the ranges.\n\/\/ The function \"In\" provides a nicer signature and should be used in preference to IsOneOf.\nfunc IsOneOf(ranges []*RangeTable, r rune) bool {\n\tfor _, inside := range ranges {\n\t\tif Is(inside, r) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ In reports whether the rune is a member of one of the ranges.\nfunc In(r rune, ranges ...*RangeTable) bool {\n\tfor _, inside := range ranges {\n\t\tif Is(inside, r) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ IsControl reports whether the rune is a control character.\n\/\/ The C (Other) Unicode category includes more code points\n\/\/ such as surrogates; use Is(C, r) to test for them.\nfunc IsControl(r rune) bool {\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&pC != 0\n\t}\n\t\/\/ All control characters are < MaxLatin1.\n\treturn false\n}\n\n\/\/ IsLetter reports whether the rune is a letter (category L).\nfunc IsLetter(r rune) bool {\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&(pLmask) != 0\n\t}\n\treturn isExcludingLatin(Letter, r)\n}\n\n\/\/ IsMark reports whether the rune is a mark character (category M).\nfunc IsMark(r rune) bool {\n\t\/\/ There are no mark characters in Latin-1.\n\treturn isExcludingLatin(Mark, r)\n}\n\n\/\/ IsNumber reports whether the rune is a number (category N).\nfunc IsNumber(r rune) bool {\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&pN != 0\n\t}\n\treturn isExcludingLatin(Number, r)\n}\n\n\/\/ IsPunct reports whether the rune is a Unicode punctuation character\n\/\/ (category P).\nfunc IsPunct(r rune) bool {\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&pP != 0\n\t}\n\treturn Is(Punct, r)\n}\n\n\/\/ IsSpace reports whether the rune is a space character as defined\n\/\/ by Unicode's White Space property; in the Latin-1 space\n\/\/ this is\n\/\/\t'\\t', '\\n', '\\v', '\\f', '\\r', ' ', U+0085 (NEL), U+00A0 (NBSP).\n\/\/ Other definitions of spacing characters are set by category\n\/\/ Z and property Pattern_White_Space.\nfunc IsSpace(r rune) bool {\n\t\/\/ This property isn't the same as Z; special-case it.\n\tif uint32(r) <= MaxLatin1 {\n\t\tswitch r {\n\t\tcase '\\t', '\\n', '\\v', '\\f', '\\r', ' ', 0x85, 0xA0:\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\treturn isExcludingLatin(White_Space, r)\n}\n\n\/\/ IsSymbol reports whether the rune is a symbolic character.\nfunc IsSymbol(r rune) bool {\n\tif uint32(r) <= MaxLatin1 {\n\t\treturn properties[uint8(r)]&pS != 0\n\t}\n\treturn isExcludingLatin(Symbol, r)\n}\n<|endoftext|>"}
{"text":"<commit_before>package resolver\n\ntype MemStorage struct {\n\tTable    map[string]string\n}\n\nfunc NewMemStorage() *MemStorage {\n    return &MemStorage{Table: make(map[string]string)}\n}\n\nfunc (this *MemStorage) Get(key string) string {\n\treturn this.Table[key]\n}\n\nfunc (this *MemStorage) Set(key string, value string) {\n\tthis.Table[key] = value\n}\n\nfunc (this *MemStorage) List() []string {\n\tvar keys []string\n\n\tfor k := range this.Table {\n\t\tkeys = append(keys, k)\n\t}\n\n\treturn keys\n}\n<commit_msg>oops. forgot formatting<commit_after>package resolver\n\ntype MemStorage struct {\n\tTable map[string]string\n}\n\nfunc NewMemStorage() *MemStorage {\n\treturn &MemStorage{Table: make(map[string]string)}\n}\n\nfunc (this *MemStorage) Get(key string) string {\n\treturn this.Table[key]\n}\n\nfunc (this *MemStorage) Set(key string, value string) {\n\tthis.Table[key] = value\n}\n\nfunc (this *MemStorage) List() []string {\n\tvar keys []string\n\n\tfor k := range this.Table {\n\t\tkeys = append(keys, k)\n\t}\n\n\treturn keys\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Prometheus Authors\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage discovery\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/common\/log\"\n\t\"github.com\/prometheus\/common\/model\"\n\t\"golang.org\/x\/net\/context\"\n\t\"gopkg.in\/fsnotify.v1\"\n\t\"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/prometheus\/prometheus\/config\"\n)\n\nconst fileSDFilepathLabel = model.MetaLabelPrefix + \"filepath\"\n\n\/\/ FileDiscovery provides service discovery functionality based\n\/\/ on files that contain target groups in JSON or YAML format. Refreshing\n\/\/ happens using file watches and periodic refreshes.\ntype FileDiscovery struct {\n\tpaths    []string\n\twatcher  *fsnotify.Watcher\n\tinterval time.Duration\n\n\t\/\/ lastRefresh stores which files were found during the last refresh\n\t\/\/ and how many target groups they contained.\n\t\/\/ This is used to detect deleted target groups.\n\tlastRefresh map[string]int\n}\n\n\/\/ NewFileDiscovery returns a new file discovery for the given paths.\nfunc NewFileDiscovery(conf *config.FileSDConfig) *FileDiscovery {\n\treturn &FileDiscovery{\n\t\tpaths:    conf.Files,\n\t\tinterval: time.Duration(conf.RefreshInterval),\n\t}\n}\n\n\/\/ listFiles returns a list of all files that match the configured patterns.\nfunc (fd *FileDiscovery) listFiles() []string {\n\tvar paths []string\n\tfor _, p := range fd.paths {\n\t\tfiles, err := filepath.Glob(p)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error expanding glob %q: %s\", p, err)\n\t\t\tcontinue\n\t\t}\n\t\tpaths = append(paths, files...)\n\t}\n\treturn paths\n}\n\n\/\/ watchFiles sets watches on all full paths or directories that were configured for\n\/\/ this file discovery.\nfunc (fd *FileDiscovery) watchFiles() {\n\tif fd.watcher == nil {\n\t\tpanic(\"no watcher configured\")\n\t}\n\tfor _, p := range fd.paths {\n\t\tif idx := strings.LastIndex(p, \"\/\"); idx > -1 {\n\t\t\tp = p[:idx]\n\t\t} else {\n\t\t\tp = \".\/\"\n\t\t}\n\t\tif err := fd.watcher.Add(p); err != nil {\n\t\t\tlog.Errorf(\"Error adding file watch for %q: %s\", p, err)\n\t\t}\n\t}\n}\n\n\/\/ Run implements the TargetProvider interface.\nfunc (fd *FileDiscovery) Run(ctx context.Context, ch chan<- []*config.TargetGroup) {\n\tdefer close(ch)\n\tdefer fd.stop()\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.Errorf(\"Error creating file watcher: %s\", err)\n\t\treturn\n\t}\n\tfd.watcher = watcher\n\n\tfd.refresh(ch)\n\n\tticker := time.NewTicker(fd.interval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\t\/\/ Stopping has priority over refreshing. Thus we wrap the actual select\n\t\t\/\/ clause to always catch done signals.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\n\t\t\tcase event := <-fd.watcher.Events:\n\t\t\t\t\/\/ fsnotify sometimes sends a bunch of events without name or operation.\n\t\t\t\t\/\/ It's unclear what they are and why they are sent - filter them out.\n\t\t\t\tif len(event.Name) == 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t\/\/ Everything but a chmod requires rereading.\n\t\t\t\tif event.Op^fsnotify.Chmod == 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t\/\/ Changes to a file can spawn various sequences of events with\n\t\t\t\t\/\/ different combinations of operations. For all practical purposes\n\t\t\t\t\/\/ this is inaccurate.\n\t\t\t\t\/\/ The most reliable solution is to reload everything if anything happens.\n\t\t\t\tfd.refresh(ch)\n\n\t\t\tcase <-ticker.C:\n\t\t\t\t\/\/ Setting a new watch after an update might fail. Make sure we don't lose\n\t\t\t\t\/\/ those files forever.\n\t\t\t\tfd.refresh(ch)\n\n\t\t\tcase err := <-fd.watcher.Errors:\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Error on file watch: %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ stop shuts down the file watcher.\nfunc (fd *FileDiscovery) stop() {\n\tlog.Debugf(\"Stopping file discovery for %s...\", fd.paths)\n\n\tdone := make(chan struct{})\n\tdefer close(done)\n\n\t\/\/ Closing the watcher will deadlock unless all events and errors are drained.\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-fd.watcher.Errors:\n\t\t\tcase <-fd.watcher.Events:\n\t\t\t\t\/\/ Drain all events and errors.\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\tif err := fd.watcher.Close(); err != nil {\n\t\tlog.Errorf(\"Error closing file watcher for %s: %s\", fd.paths, err)\n\t}\n\n\tlog.Debugf(\"File discovery for %s stopped.\", fd.paths)\n}\n\n\/\/ refresh reads all files matching the discovery's patterns and sends the respective\n\/\/ updated target groups through the channel.\nfunc (fd *FileDiscovery) refresh(ch chan<- []*config.TargetGroup) {\n\tref := map[string]int{}\n\tfor _, p := range fd.listFiles() {\n\t\ttgroups, err := readFile(p)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error reading file %q: %s\", p, err)\n\t\t\t\/\/ Prevent deletion down below.\n\t\t\tref[p] = fd.lastRefresh[p]\n\t\t\tcontinue\n\t\t}\n\t\tch <- tgroups\n\n\t\tref[p] = len(tgroups)\n\t}\n\t\/\/ Send empty updates for sources that disappeared.\n\tfor f, n := range fd.lastRefresh {\n\t\tm, ok := ref[f]\n\t\tif !ok || n > m {\n\t\t\tfor i := m; i < n; i++ {\n\t\t\t\tch <- []*config.TargetGroup{\n\t\t\t\t\t{Source: fileSource(f, i)},\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfd.lastRefresh = ref\n\n\tfd.watchFiles()\n}\n\n\/\/ fileSource returns a source ID for the i-th target group in the file.\nfunc fileSource(filename string, i int) string {\n\treturn fmt.Sprintf(\"%s:%d\", filename, i)\n}\n\n\/\/ readFile reads a JSON or YAML list of targets groups from the file, depending on its\n\/\/ file extension. It returns full configuration target groups.\nfunc readFile(filename string) ([]*config.TargetGroup, error) {\n\tcontent, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar targetGroups []*config.TargetGroup\n\n\tswitch ext := filepath.Ext(filename); strings.ToLower(ext) {\n\tcase \".json\":\n\t\tif err := json.Unmarshal(content, &targetGroups); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase \".yml\", \".yaml\":\n\t\tif err := yaml.Unmarshal(content, &targetGroups); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault:\n\t\tpanic(fmt.Errorf(\"retrieval.FileDiscovery.readFile: unhandled file extension %q\", ext))\n\t}\n\n\tfor i, tg := range targetGroups {\n\t\ttg.Source = fileSource(filename, i)\n\t\tif tg.Labels == nil {\n\t\t\ttg.Labels = model.LabelSet{}\n\t\t}\n\t\ttg.Labels[fileSDFilepathLabel] = model.LabelValue(filename)\n\t}\n\treturn targetGroups, nil\n}\n<commit_msg>Add File-SD metrics (#2103)<commit_after>\/\/ Copyright 2015 The Prometheus Authors\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage discovery\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/prometheus\/common\/log\"\n\t\"github.com\/prometheus\/common\/model\"\n\t\"golang.org\/x\/net\/context\"\n\t\"gopkg.in\/fsnotify.v1\"\n\t\"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/prometheus\/prometheus\/config\"\n)\n\nconst fileSDFilepathLabel = model.MetaLabelPrefix + \"filepath\"\n\nvar (\n\tfileSDScanDuration = prometheus.NewSummary(\n\t\tprometheus.SummaryOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"sd_file_scan_duration_seconds\",\n\t\t\tHelp:      \"The duration of the File-SD scan in seconds.\",\n\t\t})\n\tfileSDReadErrorsCount = prometheus.NewCounter(\n\t\tprometheus.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"sd_file_read_errors_total\",\n\t\t\tHelp:      \"The number of File-SD read errors.\",\n\t\t})\n)\n\nfunc init() {\n\tprometheus.MustRegister(fileSDScanDuration)\n\tprometheus.MustRegister(fileSDReadErrorsCount)\n}\n\n\/\/ FileDiscovery provides service discovery functionality based\n\/\/ on files that contain target groups in JSON or YAML format. Refreshing\n\/\/ happens using file watches and periodic refreshes.\ntype FileDiscovery struct {\n\tpaths    []string\n\twatcher  *fsnotify.Watcher\n\tinterval time.Duration\n\n\t\/\/ lastRefresh stores which files were found during the last refresh\n\t\/\/ and how many target groups they contained.\n\t\/\/ This is used to detect deleted target groups.\n\tlastRefresh map[string]int\n}\n\n\/\/ NewFileDiscovery returns a new file discovery for the given paths.\nfunc NewFileDiscovery(conf *config.FileSDConfig) *FileDiscovery {\n\treturn &FileDiscovery{\n\t\tpaths:    conf.Files,\n\t\tinterval: time.Duration(conf.RefreshInterval),\n\t}\n}\n\n\/\/ listFiles returns a list of all files that match the configured patterns.\nfunc (fd *FileDiscovery) listFiles() []string {\n\tvar paths []string\n\tfor _, p := range fd.paths {\n\t\tfiles, err := filepath.Glob(p)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error expanding glob %q: %s\", p, err)\n\t\t\tcontinue\n\t\t}\n\t\tpaths = append(paths, files...)\n\t}\n\treturn paths\n}\n\n\/\/ watchFiles sets watches on all full paths or directories that were configured for\n\/\/ this file discovery.\nfunc (fd *FileDiscovery) watchFiles() {\n\tif fd.watcher == nil {\n\t\tpanic(\"no watcher configured\")\n\t}\n\tfor _, p := range fd.paths {\n\t\tif idx := strings.LastIndex(p, \"\/\"); idx > -1 {\n\t\t\tp = p[:idx]\n\t\t} else {\n\t\t\tp = \".\/\"\n\t\t}\n\t\tif err := fd.watcher.Add(p); err != nil {\n\t\t\tlog.Errorf(\"Error adding file watch for %q: %s\", p, err)\n\t\t}\n\t}\n}\n\n\/\/ Run implements the TargetProvider interface.\nfunc (fd *FileDiscovery) Run(ctx context.Context, ch chan<- []*config.TargetGroup) {\n\tdefer close(ch)\n\tdefer fd.stop()\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.Errorf(\"Error creating file watcher: %s\", err)\n\t\treturn\n\t}\n\tfd.watcher = watcher\n\n\tfd.refresh(ch)\n\n\tticker := time.NewTicker(fd.interval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\t\/\/ Stopping has priority over refreshing. Thus we wrap the actual select\n\t\t\/\/ clause to always catch done signals.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\n\t\t\tcase event := <-fd.watcher.Events:\n\t\t\t\t\/\/ fsnotify sometimes sends a bunch of events without name or operation.\n\t\t\t\t\/\/ It's unclear what they are and why they are sent - filter them out.\n\t\t\t\tif len(event.Name) == 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t\/\/ Everything but a chmod requires rereading.\n\t\t\t\tif event.Op^fsnotify.Chmod == 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t\/\/ Changes to a file can spawn various sequences of events with\n\t\t\t\t\/\/ different combinations of operations. For all practical purposes\n\t\t\t\t\/\/ this is inaccurate.\n\t\t\t\t\/\/ The most reliable solution is to reload everything if anything happens.\n\t\t\t\tfd.refresh(ch)\n\n\t\t\tcase <-ticker.C:\n\t\t\t\t\/\/ Setting a new watch after an update might fail. Make sure we don't lose\n\t\t\t\t\/\/ those files forever.\n\t\t\t\tfd.refresh(ch)\n\n\t\t\tcase err := <-fd.watcher.Errors:\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Error on file watch: %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ stop shuts down the file watcher.\nfunc (fd *FileDiscovery) stop() {\n\tlog.Debugf(\"Stopping file discovery for %s...\", fd.paths)\n\n\tdone := make(chan struct{})\n\tdefer close(done)\n\n\t\/\/ Closing the watcher will deadlock unless all events and errors are drained.\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-fd.watcher.Errors:\n\t\t\tcase <-fd.watcher.Events:\n\t\t\t\t\/\/ Drain all events and errors.\n\t\t\tcase <-done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\tif err := fd.watcher.Close(); err != nil {\n\t\tlog.Errorf(\"Error closing file watcher for %s: %s\", fd.paths, err)\n\t}\n\n\tlog.Debugf(\"File discovery for %s stopped.\", fd.paths)\n}\n\n\/\/ refresh reads all files matching the discovery's patterns and sends the respective\n\/\/ updated target groups through the channel.\nfunc (fd *FileDiscovery) refresh(ch chan<- []*config.TargetGroup) {\n\tt0 := time.Now()\n\tdefer func() {\n\t\tfileSDScanDuration.Observe(time.Since(t0).Seconds())\n\t}()\n\n\tref := map[string]int{}\n\tfor _, p := range fd.listFiles() {\n\t\ttgroups, err := readFile(p)\n\t\tif err != nil {\n\t\t\tfileSDReadErrorsCount.Inc()\n\t\t\tlog.Errorf(\"Error reading file %q: %s\", p, err)\n\t\t\t\/\/ Prevent deletion down below.\n\t\t\tref[p] = fd.lastRefresh[p]\n\t\t\tcontinue\n\t\t}\n\t\tch <- tgroups\n\n\t\tref[p] = len(tgroups)\n\t}\n\t\/\/ Send empty updates for sources that disappeared.\n\tfor f, n := range fd.lastRefresh {\n\t\tm, ok := ref[f]\n\t\tif !ok || n > m {\n\t\t\tfor i := m; i < n; i++ {\n\t\t\t\tch <- []*config.TargetGroup{\n\t\t\t\t\t{Source: fileSource(f, i)},\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfd.lastRefresh = ref\n\n\tfd.watchFiles()\n}\n\n\/\/ fileSource returns a source ID for the i-th target group in the file.\nfunc fileSource(filename string, i int) string {\n\treturn fmt.Sprintf(\"%s:%d\", filename, i)\n}\n\n\/\/ readFile reads a JSON or YAML list of targets groups from the file, depending on its\n\/\/ file extension. It returns full configuration target groups.\nfunc readFile(filename string) ([]*config.TargetGroup, error) {\n\tcontent, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar targetGroups []*config.TargetGroup\n\n\tswitch ext := filepath.Ext(filename); strings.ToLower(ext) {\n\tcase \".json\":\n\t\tif err := json.Unmarshal(content, &targetGroups); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase \".yml\", \".yaml\":\n\t\tif err := yaml.Unmarshal(content, &targetGroups); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tdefault:\n\t\tpanic(fmt.Errorf(\"retrieval.FileDiscovery.readFile: unhandled file extension %q\", ext))\n\t}\n\n\tfor i, tg := range targetGroups {\n\t\ttg.Source = fileSource(filename, i)\n\t\tif tg.Labels == nil {\n\t\t\ttg.Labels = model.LabelSet{}\n\t\t}\n\t\ttg.Labels[fileSDFilepathLabel] = model.LabelValue(filename)\n\t}\n\treturn targetGroups, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package lucene42\n\nimport (\n\t\"github.com\/balzaczyy\/golucene\/core\/store\"\n\t\"testing\"\n)\n\nfunc TestReadFieldInfos(t *testing.T) {\n\tpath := \"..\/..\/search\/testdata\/osx\/belfrysample\"\n\td, err := store.OpenFSDirectory(path)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tctx := store.NewIOContextBool(false)\n\tcd, err := store.NewCompoundFileDirectory(d, \"_0.cfs\", ctx, false)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tfis, err := Lucene42FieldInfosReader(cd, \"_0\", store.IO_CONTEXT_READONCE)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !fis.HasNorms || fis.HasDocValues {\n\t\tt.Errorf(\"hasNorms must be true and hasDocValues must be false, but found %v\", fis)\n\t}\n}\n<commit_msg>fix unit test for codec\/lucene42<commit_after>package lucene42\n\nimport (\n\t\"github.com\/balzaczyy\/golucene\/core\/store\"\n\t\"testing\"\n)\n\nfunc TestReadFieldInfos(t *testing.T) {\n\tpath := \"..\/..\/search\/testdata\/osx\/belfrysample\"\n\td, err := store.OpenFSDirectory(path)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tctx := store.NewIOContextBool(false)\n\tcd, err := store.NewCompoundFileDirectory(d, \"_0.cfs\", ctx, false)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tfis, err := Lucene42FieldInfosReader(cd, \"_0\", \"\", store.IO_CONTEXT_READONCE)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif !fis.HasNorms || fis.HasDocValues {\n\t\tt.Errorf(\"hasNorms must be true and hasDocValues must be false, but found %v\", fis)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2014 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cache\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/sets\"\n)\n\n\/\/ ThreadSafeStore is an interface that allows concurrent indexed\n\/\/ access to a storage backend.  It is like Indexer but does not\n\/\/ (necessarily) know how to extract the Store key from a given\n\/\/ object.\n\/\/\n\/\/ TL;DR caveats: you must not modify anything returned by Get or List as it will break\n\/\/ the indexing feature in addition to not being thread safe.\n\/\/\n\/\/ The guarantees of thread safety provided by List\/Get are only valid if the caller\n\/\/ treats returned items as read-only. For example, a pointer inserted in the store\n\/\/ through `Add` will be returned as is by `Get`. Multiple clients might invoke `Get`\n\/\/ on the same key and modify the pointer in a non-thread-safe way. Also note that\n\/\/ modifying objects stored by the indexers (if any) will *not* automatically lead\n\/\/ to a re-index. So it's not a good idea to directly modify the objects returned by\n\/\/ Get\/List, in general.\ntype ThreadSafeStore interface {\n\tAdd(key string, obj interface{})\n\tUpdate(key string, obj interface{})\n\tDelete(key string)\n\tGet(key string) (item interface{}, exists bool)\n\tList() []interface{}\n\tListKeys() []string\n\tReplace(map[string]interface{}, string)\n\tIndex(indexName string, obj interface{}) ([]interface{}, error)\n\tIndexKeys(indexName, indexedValue string) ([]string, error)\n\tListIndexFuncValues(name string) []string\n\tByIndex(indexName, indexedValue string) ([]interface{}, error)\n\tGetIndexers() Indexers\n\n\t\/\/ AddIndexers adds more indexers to this store.  If you call this after you already have data\n\t\/\/ in the store, the results are undefined.\n\tAddIndexers(newIndexers Indexers) error\n\t\/\/ Resync is a no-op and is deprecated\n\tResync() error\n}\n\n\/\/ storeIndex implements the indexing functionality for Store interface\ntype storeIndex struct {\n\t\/\/ indexers maps a name to an IndexFunc\n\tindexers Indexers\n\t\/\/ indices maps a name to an Index\n\tindices Indices\n}\n\nfunc (i *storeIndex) reset() {\n\ti.indices = Indices{}\n}\n\nfunc (i *storeIndex) getKeysFromIndex(indexName string, obj interface{}) (sets.String, error) {\n\tindexFunc := i.indexers[indexName]\n\tif indexFunc == nil {\n\t\treturn nil, fmt.Errorf(\"Index with name %s does not exist\", indexName)\n\t}\n\n\tindexedValues, err := indexFunc(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tindex := i.indices[indexName]\n\n\tvar storeKeySet sets.String\n\tif len(indexedValues) == 1 {\n\t\t\/\/ In majority of cases, there is exactly one value matching.\n\t\t\/\/ Optimize the most common path - deduping is not needed here.\n\t\tstoreKeySet = index[indexedValues[0]]\n\t} else {\n\t\t\/\/ Need to de-dupe the return list.\n\t\t\/\/ Since multiple keys are allowed, this can happen.\n\t\tstoreKeySet = sets.String{}\n\t\tfor _, indexedValue := range indexedValues {\n\t\t\tfor key := range index[indexedValue] {\n\t\t\t\tstoreKeySet.Insert(key)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn storeKeySet, nil\n}\n\nfunc (i *storeIndex) getKeysByIndex(indexName, indexedValue string) (sets.String, error) {\n\tindexFunc := i.indexers[indexName]\n\tif indexFunc == nil {\n\t\treturn nil, fmt.Errorf(\"Index with name %s does not exist\", indexName)\n\t}\n\n\tindex := i.indices[indexName]\n\treturn index[indexedValue], nil\n}\n\nfunc (i *storeIndex) getIndexValues(indexName string) []string {\n\tindex := i.indices[indexName]\n\tnames := make([]string, 0, len(index))\n\tfor key := range index {\n\t\tnames = append(names, key)\n\t}\n\treturn names\n}\n\nfunc (i *storeIndex) addIndexers(newIndexers Indexers) error {\n\toldKeys := sets.StringKeySet(i.indexers)\n\tnewKeys := sets.StringKeySet(newIndexers)\n\n\tif oldKeys.HasAny(newKeys.List()...) {\n\t\treturn fmt.Errorf(\"indexer conflict: %v\", oldKeys.Intersection(newKeys))\n\t}\n\n\tfor k, v := range newIndexers {\n\t\ti.indexers[k] = v\n\t}\n\treturn nil\n}\n\n\/\/ threadSafeMap implements ThreadSafeStore\ntype threadSafeMap struct {\n\tlock  sync.RWMutex\n\titems map[string]interface{}\n\n\t\/\/ index implements the indexing functionality\n\tindex *storeIndex\n}\n\nfunc (c *threadSafeMap) Add(key string, obj interface{}) {\n\tc.Update(key, obj)\n}\n\nfunc (c *threadSafeMap) Update(key string, obj interface{}) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\toldObject := c.items[key]\n\tc.items[key] = obj\n\tc.index.updateIndices(oldObject, obj, key)\n}\n\nfunc (c *threadSafeMap) Delete(key string) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tif obj, exists := c.items[key]; exists {\n\t\tc.index.updateIndices(obj, nil, key)\n\t\tdelete(c.items, key)\n\t}\n}\n\nfunc (c *threadSafeMap) Get(key string) (item interface{}, exists bool) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\titem, exists = c.items[key]\n\treturn item, exists\n}\n\nfunc (c *threadSafeMap) List() []interface{} {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\tlist := make([]interface{}, 0, len(c.items))\n\tfor _, item := range c.items {\n\t\tlist = append(list, item)\n\t}\n\treturn list\n}\n\n\/\/ ListKeys returns a list of all the keys of the objects currently\n\/\/ in the threadSafeMap.\nfunc (c *threadSafeMap) ListKeys() []string {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\tlist := make([]string, 0, len(c.items))\n\tfor key := range c.items {\n\t\tlist = append(list, key)\n\t}\n\treturn list\n}\n\nfunc (c *threadSafeMap) Replace(items map[string]interface{}, resourceVersion string) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.items = items\n\n\t\/\/ rebuild any index\n\tc.index.reset()\n\tfor key, item := range c.items {\n\t\tc.index.updateIndices(nil, item, key)\n\t}\n}\n\n\/\/ Index returns a list of items that match the given object on the index function.\n\/\/ Index is thread-safe so long as you treat all items as immutable.\nfunc (c *threadSafeMap) Index(indexName string, obj interface{}) ([]interface{}, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\tstoreKeySet, err := c.index.getKeysFromIndex(indexName, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlist := make([]interface{}, 0, storeKeySet.Len())\n\tfor storeKey := range storeKeySet {\n\t\tlist = append(list, c.items[storeKey])\n\t}\n\treturn list, nil\n}\n\n\/\/ ByIndex returns a list of the items whose indexed values in the given index include the given indexed value\nfunc (c *threadSafeMap) ByIndex(indexName, indexedValue string) ([]interface{}, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\tset, err := c.index.getKeysByIndex(indexName, indexedValue)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlist := make([]interface{}, 0, set.Len())\n\tfor key := range set {\n\t\tlist = append(list, c.items[key])\n\t}\n\n\treturn list, nil\n}\n\n\/\/ IndexKeys returns a list of the Store keys of the objects whose indexed values in the given index include the given indexed value.\n\/\/ IndexKeys is thread-safe so long as you treat all items as immutable.\nfunc (c *threadSafeMap) IndexKeys(indexName, indexedValue string) ([]string, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\tset, err := c.index.getKeysByIndex(indexName, indexedValue)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn set.List(), nil\n}\n\nfunc (c *threadSafeMap) ListIndexFuncValues(indexName string) []string {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\treturn c.index.getIndexValues(indexName)\n}\n\nfunc (c *threadSafeMap) GetIndexers() Indexers {\n\treturn c.index.indexers\n}\n\nfunc (c *threadSafeMap) AddIndexers(newIndexers Indexers) error {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif len(c.items) > 0 {\n\t\treturn fmt.Errorf(\"cannot add indexers to running index\")\n\t}\n\n\treturn c.index.addIndexers(newIndexers)\n}\n\n\/\/ updateIndices modifies the objects location in the managed indexes:\n\/\/ - for create you must provide only the newObj\n\/\/ - for update you must provide both the oldObj and the newObj\n\/\/ - for delete you must provide only the oldObj\n\/\/ updateIndices must be called from a function that already has a lock on the cache\nfunc (i *storeIndex) updateIndices(oldObj interface{}, newObj interface{}, key string) {\n\tvar oldIndexValues, indexValues []string\n\tvar err error\n\tfor name, indexFunc := range i.indexers {\n\t\tif oldObj != nil {\n\t\t\toldIndexValues, err = indexFunc(oldObj)\n\t\t} else {\n\t\t\toldIndexValues = oldIndexValues[:0]\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"unable to calculate an index entry for key %q on index %q: %v\", key, name, err))\n\t\t}\n\n\t\tif newObj != nil {\n\t\t\tindexValues, err = indexFunc(newObj)\n\t\t} else {\n\t\t\tindexValues = indexValues[:0]\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"unable to calculate an index entry for key %q on index %q: %v\", key, name, err))\n\t\t}\n\n\t\tindex := i.indices[name]\n\t\tif index == nil {\n\t\t\tindex = Index{}\n\t\t\ti.indices[name] = index\n\t\t}\n\n\t\tif len(indexValues) == 1 && len(oldIndexValues) == 1 && indexValues[0] == oldIndexValues[0] {\n\t\t\t\/\/ We optimize for the most common case where indexFunc returns a single value which has not been changed\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, value := range oldIndexValues {\n\t\t\ti.deleteKeyFromIndex(key, value, index)\n\t\t}\n\t\tfor _, value := range indexValues {\n\t\t\ti.addKeyToIndex(key, value, index)\n\t\t}\n\t}\n}\n\nfunc (i *storeIndex) addKeyToIndex(key, indexValue string, index Index) {\n\tset := index[indexValue]\n\tif set == nil {\n\t\tset = sets.String{}\n\t\tindex[indexValue] = set\n\t}\n\tset.Insert(key)\n}\n\nfunc (i *storeIndex) deleteKeyFromIndex(key, indexValue string, index Index) {\n\tset := index[indexValue]\n\tif set == nil {\n\t\treturn\n\t}\n\tset.Delete(key)\n\t\/\/ If we don't delete the set when zero, indices with high cardinality\n\t\/\/ short lived resources can cause memory to increase over time from\n\t\/\/ unused empty sets. See `kubernetes\/kubernetes\/issues\/84959`.\n\tif len(set) == 0 {\n\t\tdelete(index, indexValue)\n\t}\n}\n\nfunc (c *threadSafeMap) Resync() error {\n\t\/\/ Nothing to do\n\treturn nil\n}\n\n\/\/ NewThreadSafeStore creates a new instance of ThreadSafeStore.\nfunc NewThreadSafeStore(indexers Indexers, indices Indices) ThreadSafeStore {\n\treturn &threadSafeMap{\n\t\titems: map[string]interface{}{},\n\t\tindex: &storeIndex{\n\t\t\tindexers: indexers,\n\t\t\tindices:  indices,\n\t\t},\n\t}\n}\n<commit_msg>Minor cleanup of thread safe store<commit_after>\/*\nCopyright 2014 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cache\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/sets\"\n)\n\n\/\/ ThreadSafeStore is an interface that allows concurrent indexed\n\/\/ access to a storage backend.  It is like Indexer but does not\n\/\/ (necessarily) know how to extract the Store key from a given\n\/\/ object.\n\/\/\n\/\/ TL;DR caveats: you must not modify anything returned by Get or List as it will break\n\/\/ the indexing feature in addition to not being thread safe.\n\/\/\n\/\/ The guarantees of thread safety provided by List\/Get are only valid if the caller\n\/\/ treats returned items as read-only. For example, a pointer inserted in the store\n\/\/ through `Add` will be returned as is by `Get`. Multiple clients might invoke `Get`\n\/\/ on the same key and modify the pointer in a non-thread-safe way. Also note that\n\/\/ modifying objects stored by the indexers (if any) will *not* automatically lead\n\/\/ to a re-index. So it's not a good idea to directly modify the objects returned by\n\/\/ Get\/List, in general.\ntype ThreadSafeStore interface {\n\tAdd(key string, obj interface{})\n\tUpdate(key string, obj interface{})\n\tDelete(key string)\n\tGet(key string) (item interface{}, exists bool)\n\tList() []interface{}\n\tListKeys() []string\n\tReplace(map[string]interface{}, string)\n\tIndex(indexName string, obj interface{}) ([]interface{}, error)\n\tIndexKeys(indexName, indexedValue string) ([]string, error)\n\tListIndexFuncValues(name string) []string\n\tByIndex(indexName, indexedValue string) ([]interface{}, error)\n\tGetIndexers() Indexers\n\n\t\/\/ AddIndexers adds more indexers to this store.  If you call this after you already have data\n\t\/\/ in the store, the results are undefined.\n\tAddIndexers(newIndexers Indexers) error\n\t\/\/ Resync is a no-op and is deprecated\n\tResync() error\n}\n\n\/\/ storeIndex implements the indexing functionality for Store interface\ntype storeIndex struct {\n\t\/\/ indexers maps a name to an IndexFunc\n\tindexers Indexers\n\t\/\/ indices maps a name to an Index\n\tindices Indices\n}\n\nfunc (i *storeIndex) reset() {\n\ti.indices = Indices{}\n}\n\nfunc (i *storeIndex) getKeysFromIndex(indexName string, obj interface{}) (sets.String, error) {\n\tindexFunc := i.indexers[indexName]\n\tif indexFunc == nil {\n\t\treturn nil, fmt.Errorf(\"Index with name %s does not exist\", indexName)\n\t}\n\n\tindexedValues, err := indexFunc(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tindex := i.indices[indexName]\n\n\tvar storeKeySet sets.String\n\tif len(indexedValues) == 1 {\n\t\t\/\/ In majority of cases, there is exactly one value matching.\n\t\t\/\/ Optimize the most common path - deduping is not needed here.\n\t\tstoreKeySet = index[indexedValues[0]]\n\t} else {\n\t\t\/\/ Need to de-dupe the return list.\n\t\t\/\/ Since multiple keys are allowed, this can happen.\n\t\tstoreKeySet = sets.String{}\n\t\tfor _, indexedValue := range indexedValues {\n\t\t\tfor key := range index[indexedValue] {\n\t\t\t\tstoreKeySet.Insert(key)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn storeKeySet, nil\n}\n\nfunc (i *storeIndex) getKeysByIndex(indexName, indexedValue string) (sets.String, error) {\n\tindexFunc := i.indexers[indexName]\n\tif indexFunc == nil {\n\t\treturn nil, fmt.Errorf(\"Index with name %s does not exist\", indexName)\n\t}\n\n\tindex := i.indices[indexName]\n\treturn index[indexedValue], nil\n}\n\nfunc (i *storeIndex) getIndexValues(indexName string) []string {\n\tindex := i.indices[indexName]\n\tnames := make([]string, 0, len(index))\n\tfor key := range index {\n\t\tnames = append(names, key)\n\t}\n\treturn names\n}\n\nfunc (i *storeIndex) addIndexers(newIndexers Indexers) error {\n\toldKeys := sets.StringKeySet(i.indexers)\n\tnewKeys := sets.StringKeySet(newIndexers)\n\n\tif oldKeys.HasAny(newKeys.List()...) {\n\t\treturn fmt.Errorf(\"indexer conflict: %v\", oldKeys.Intersection(newKeys))\n\t}\n\n\tfor k, v := range newIndexers {\n\t\ti.indexers[k] = v\n\t}\n\treturn nil\n}\n\n\/\/ updateIndices modifies the objects location in the managed indexes:\n\/\/ - for create you must provide only the newObj\n\/\/ - for update you must provide both the oldObj and the newObj\n\/\/ - for delete you must provide only the oldObj\n\/\/ updateIndices must be called from a function that already has a lock on the cache\nfunc (i *storeIndex) updateIndices(oldObj interface{}, newObj interface{}, key string) {\n\tvar oldIndexValues, indexValues []string\n\tvar err error\n\tfor name, indexFunc := range i.indexers {\n\t\tif oldObj != nil {\n\t\t\toldIndexValues, err = indexFunc(oldObj)\n\t\t} else {\n\t\t\toldIndexValues = oldIndexValues[:0]\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"unable to calculate an index entry for key %q on index %q: %v\", key, name, err))\n\t\t}\n\n\t\tif newObj != nil {\n\t\t\tindexValues, err = indexFunc(newObj)\n\t\t} else {\n\t\t\tindexValues = indexValues[:0]\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"unable to calculate an index entry for key %q on index %q: %v\", key, name, err))\n\t\t}\n\n\t\tindex := i.indices[name]\n\t\tif index == nil {\n\t\t\tindex = Index{}\n\t\t\ti.indices[name] = index\n\t\t}\n\n\t\tif len(indexValues) == 1 && len(oldIndexValues) == 1 && indexValues[0] == oldIndexValues[0] {\n\t\t\t\/\/ We optimize for the most common case where indexFunc returns a single value which has not been changed\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, value := range oldIndexValues {\n\t\t\ti.deleteKeyFromIndex(key, value, index)\n\t\t}\n\t\tfor _, value := range indexValues {\n\t\t\ti.addKeyToIndex(key, value, index)\n\t\t}\n\t}\n}\n\nfunc (i *storeIndex) addKeyToIndex(key, indexValue string, index Index) {\n\tset := index[indexValue]\n\tif set == nil {\n\t\tset = sets.String{}\n\t\tindex[indexValue] = set\n\t}\n\tset.Insert(key)\n}\n\nfunc (i *storeIndex) deleteKeyFromIndex(key, indexValue string, index Index) {\n\tset := index[indexValue]\n\tif set == nil {\n\t\treturn\n\t}\n\tset.Delete(key)\n\t\/\/ If we don't delete the set when zero, indices with high cardinality\n\t\/\/ short lived resources can cause memory to increase over time from\n\t\/\/ unused empty sets. See `kubernetes\/kubernetes\/issues\/84959`.\n\tif len(set) == 0 {\n\t\tdelete(index, indexValue)\n\t}\n}\n\n\/\/ threadSafeMap implements ThreadSafeStore\ntype threadSafeMap struct {\n\tlock  sync.RWMutex\n\titems map[string]interface{}\n\n\t\/\/ index implements the indexing functionality\n\tindex *storeIndex\n}\n\nfunc (c *threadSafeMap) Add(key string, obj interface{}) {\n\tc.Update(key, obj)\n}\n\nfunc (c *threadSafeMap) Update(key string, obj interface{}) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\toldObject := c.items[key]\n\tc.items[key] = obj\n\tc.index.updateIndices(oldObject, obj, key)\n}\n\nfunc (c *threadSafeMap) Delete(key string) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tif obj, exists := c.items[key]; exists {\n\t\tc.index.updateIndices(obj, nil, key)\n\t\tdelete(c.items, key)\n\t}\n}\n\nfunc (c *threadSafeMap) Get(key string) (item interface{}, exists bool) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\titem, exists = c.items[key]\n\treturn item, exists\n}\n\nfunc (c *threadSafeMap) List() []interface{} {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\tlist := make([]interface{}, 0, len(c.items))\n\tfor _, item := range c.items {\n\t\tlist = append(list, item)\n\t}\n\treturn list\n}\n\n\/\/ ListKeys returns a list of all the keys of the objects currently\n\/\/ in the threadSafeMap.\nfunc (c *threadSafeMap) ListKeys() []string {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\tlist := make([]string, 0, len(c.items))\n\tfor key := range c.items {\n\t\tlist = append(list, key)\n\t}\n\treturn list\n}\n\nfunc (c *threadSafeMap) Replace(items map[string]interface{}, resourceVersion string) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\tc.items = items\n\n\t\/\/ rebuild any index\n\tc.index.reset()\n\tfor key, item := range c.items {\n\t\tc.index.updateIndices(nil, item, key)\n\t}\n}\n\n\/\/ Index returns a list of items that match the given object on the index function.\n\/\/ Index is thread-safe so long as you treat all items as immutable.\nfunc (c *threadSafeMap) Index(indexName string, obj interface{}) ([]interface{}, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\tstoreKeySet, err := c.index.getKeysFromIndex(indexName, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlist := make([]interface{}, 0, storeKeySet.Len())\n\tfor storeKey := range storeKeySet {\n\t\tlist = append(list, c.items[storeKey])\n\t}\n\treturn list, nil\n}\n\n\/\/ ByIndex returns a list of the items whose indexed values in the given index include the given indexed value\nfunc (c *threadSafeMap) ByIndex(indexName, indexedValue string) ([]interface{}, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\tset, err := c.index.getKeysByIndex(indexName, indexedValue)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlist := make([]interface{}, 0, set.Len())\n\tfor key := range set {\n\t\tlist = append(list, c.items[key])\n\t}\n\n\treturn list, nil\n}\n\n\/\/ IndexKeys returns a list of the Store keys of the objects whose indexed values in the given index include the given indexed value.\n\/\/ IndexKeys is thread-safe so long as you treat all items as immutable.\nfunc (c *threadSafeMap) IndexKeys(indexName, indexedValue string) ([]string, error) {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\tset, err := c.index.getKeysByIndex(indexName, indexedValue)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn set.List(), nil\n}\n\nfunc (c *threadSafeMap) ListIndexFuncValues(indexName string) []string {\n\tc.lock.RLock()\n\tdefer c.lock.RUnlock()\n\n\treturn c.index.getIndexValues(indexName)\n}\n\nfunc (c *threadSafeMap) GetIndexers() Indexers {\n\treturn c.index.indexers\n}\n\nfunc (c *threadSafeMap) AddIndexers(newIndexers Indexers) error {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif len(c.items) > 0 {\n\t\treturn fmt.Errorf(\"cannot add indexers to running index\")\n\t}\n\n\treturn c.index.addIndexers(newIndexers)\n}\n\nfunc (c *threadSafeMap) Resync() error {\n\t\/\/ Nothing to do\n\treturn nil\n}\n\n\/\/ NewThreadSafeStore creates a new instance of ThreadSafeStore.\nfunc NewThreadSafeStore(indexers Indexers, indices Indices) ThreadSafeStore {\n\treturn &threadSafeMap{\n\t\titems: map[string]interface{}{},\n\t\tindex: &storeIndex{\n\t\t\tindexers: indexers,\n\t\t\tindices:  indices,\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package middlewares\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\n\t\"github.com\/cozy\/cozy-stack\/pkg\/logger\"\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/labstack\/echo\/middleware\"\n)\n\ntype (\n\t\/\/ RecoverConfig defines the config for Recover middleware.\n\tRecoverConfig struct {\n\t\t\/\/ Skipper defines a function to skip middleware.\n\t\tSkipper middleware.Skipper\n\n\t\t\/\/ Size of the stack to be printed.\n\t\t\/\/ Optional. Default value 4KB.\n\t\tStackSize int `json:\"stack_size\"`\n\t}\n)\n\nvar (\n\t\/\/ DefaultRecoverConfig is the default Recover middleware config.\n\tDefaultRecoverConfig = RecoverConfig{\n\t\tSkipper:   middleware.DefaultSkipper,\n\t\tStackSize: 4 << 10, \/\/ 4 KB\n\t}\n)\n\n\/\/ Recover returns a middleware which recovers from panics anywhere in the chain\n\/\/ and handles the control to the centralized HTTPErrorHandler.\nfunc Recover() echo.MiddlewareFunc {\n\treturn RecoverWithConfig(DefaultRecoverConfig)\n}\n\n\/\/ RecoverWithConfig returns a Recover middleware with config.\n\/\/ See: `Recover()`.\nfunc RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc {\n\t\/\/ Defaults\n\tif config.Skipper == nil {\n\t\tconfig.Skipper = DefaultRecoverConfig.Skipper\n\t}\n\tif config.StackSize == 0 {\n\t\tconfig.StackSize = DefaultRecoverConfig.StackSize\n\t}\n\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tif config.Skipper(c) {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tvar err error\n\t\t\t\t\tswitch r := r.(type) {\n\t\t\t\t\tcase error:\n\t\t\t\t\t\terr = r\n\t\t\t\t\tdefault:\n\t\t\t\t\t\terr = fmt.Errorf(\"%v\", r)\n\t\t\t\t\t}\n\t\t\t\t\tstack := make([]byte, config.StackSize)\n\t\t\t\t\tlength := runtime.Stack(stack, false)\n\t\t\t\t\tlog := logger.WithDomain(c.Request().Host).WithField(\"panic\", true)\n\t\t\t\t\tlog.Errorf(\"PANIC RECOVER %s: %s\", err.Error(), stack[:length])\n\t\t\t\t\tc.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\t\t\treturn next(c)\n\t\t}\n\t}\n}\n<commit_msg>Simplify defaults<commit_after>package middlewares\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\n\t\"github.com\/cozy\/cozy-stack\/pkg\/logger\"\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/labstack\/echo\/middleware\"\n)\n\ntype (\n\t\/\/ RecoverConfig defines the config for Recover middleware.\n\tRecoverConfig struct {\n\t\t\/\/ Skipper defines a function to skip middleware.\n\t\tSkipper middleware.Skipper\n\n\t\t\/\/ Size of the stack to be printed.\n\t\t\/\/ Optional. Default value 4KB.\n\t\tStackSize int `json:\"stack_size\"`\n\t}\n)\n\n\/\/ RecoverWithConfig returns a Recover middleware with config.\n\/\/ See: `Recover()`.\nfunc RecoverWithConfig(config RecoverConfig) echo.MiddlewareFunc {\n\t\/\/ Defaults\n\tif config.Skipper == nil {\n\t\tconfig.Skipper = middleware.DefaultSkipper\n\t}\n\tif config.StackSize == 0 {\n\t\tconfig.StackSize = 4 << 10 \/\/ 4 KB\n\t}\n\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tif config.Skipper(c) {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tvar err error\n\t\t\t\t\tswitch r := r.(type) {\n\t\t\t\t\tcase error:\n\t\t\t\t\t\terr = r\n\t\t\t\t\tdefault:\n\t\t\t\t\t\terr = fmt.Errorf(\"%v\", r)\n\t\t\t\t\t}\n\t\t\t\t\tstack := make([]byte, config.StackSize)\n\t\t\t\t\tlength := runtime.Stack(stack, false)\n\t\t\t\t\tlog := logger.WithDomain(c.Request().Host).WithField(\"panic\", true)\n\t\t\t\t\tlog.Errorf(\"PANIC RECOVER %s: %s\", err.Error(), stack[:length])\n\t\t\t\t\tc.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\t\t\treturn next(c)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package version\n\nimport (\n\t\"math\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/gin-gonic\/gin\"\n)\n\nfunc New(c *gin.Context) (string, error) {\n\theader := c.Request.Header[\"Accept\"][0]\n\theader = strings.Join(strings.Fields(header), \"\")\n\tvar ver string\n\n\t\/\/ header version\n\tif strings.Contains(header, \"version=\") {\n\t\tver = strings.Split(strings.SplitAfter(header, \"version=\")[1], \";\")[0]\n\t}\n\n\t\/\/ query v\n\tv := c.Query(\"v\")\n\tif v != \"\" {\n\t\tver = v\n\t}\n\n\tif ver == \"\" {\n\t\treturn \"-1\", nil\n\t}\n\n\t_, err := strconv.Atoi(strings.Join(strings.Split(ver, \".\"), \"\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn ver, nil\n}\n\nfunc Range(left string, op string, right string) bool {\n\tswitch op {\n\tcase \"<\":\n\t\treturn (compare(left, right) == -1)\n\tcase \"<=\":\n\t\treturn (compare(left, right) <= 0)\n\tcase \">\":\n\t\treturn (compare(left, right) == 1)\n\tcase \">=\":\n\t\treturn (compare(left, right) >= 0)\n\tcase \"==\":\n\t\treturn (compare(left, right) == 0)\n\t}\n\treturn false\n}\n\nfunc compare(left string, right string) int {\n\t\/\/ l > r : 1\n\t\/\/ l == r : 0\n\t\/\/ l < r : -1\n\tif left == \"-1\" {\n\t\treturn 1\n\t} else if right == \"-1\" {\n\t\treturn -1\n\t}\n\n\tlArr := strings.Split(left, \".\")\n\trArr := strings.Split(right, \".\")\n\tlItems := len(lArr)\n\trItems := len(rArr)\n\tmin := int(math.Min(float64(lItems), float64(rItems)))\n\tfor i := 0; i < min; i++ {\n\t\tl, _ := strconv.Atoi(lArr[i])\n\t\tr, _ := strconv.Atoi(rArr[i])\n\t\tif l != r {\n\t\t\tif l > r {\n\t\t\t\treturn 1\n\t\t\t}\n\t\t\treturn -1\n\t\t}\n\t}\n\tif lItems == rItems {\n\t\treturn 0\n\t}\n\tif lItems < rItems {\n\t\treturn 1\n\t}\n\n\treturn -1\n}\n<commit_msg>Remove unnecessary comments in version.go<commit_after>package version\n\nimport (\n\t\"math\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/gin-gonic\/gin\"\n)\n\nfunc New(c *gin.Context) (string, error) {\n\theader := c.Request.Header[\"Accept\"][0]\n\theader = strings.Join(strings.Fields(header), \"\")\n\tvar ver string\n\n\tif strings.Contains(header, \"version=\") {\n\t\tver = strings.Split(strings.SplitAfter(header, \"version=\")[1], \";\")[0]\n\t}\n\n\tv := c.Query(\"v\")\n\tif v != \"\" {\n\t\tver = v\n\t}\n\n\tif ver == \"\" {\n\t\treturn \"-1\", nil\n\t}\n\n\t_, err := strconv.Atoi(strings.Join(strings.Split(ver, \".\"), \"\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn ver, nil\n}\n\nfunc Range(left string, op string, right string) bool {\n\tswitch op {\n\tcase \"<\":\n\t\treturn (compare(left, right) == -1)\n\tcase \"<=\":\n\t\treturn (compare(left, right) <= 0)\n\tcase \">\":\n\t\treturn (compare(left, right) == 1)\n\tcase \">=\":\n\t\treturn (compare(left, right) >= 0)\n\tcase \"==\":\n\t\treturn (compare(left, right) == 0)\n\t}\n\treturn false\n}\n\nfunc compare(left string, right string) int {\n\t\/\/ l > r : 1\n\t\/\/ l == r : 0\n\t\/\/ l < r : -1\n\tif left == \"-1\" {\n\t\treturn 1\n\t} else if right == \"-1\" {\n\t\treturn -1\n\t}\n\n\tlArr := strings.Split(left, \".\")\n\trArr := strings.Split(right, \".\")\n\tlItems := len(lArr)\n\trItems := len(rArr)\n\tmin := int(math.Min(float64(lItems), float64(rItems)))\n\tfor i := 0; i < min; i++ {\n\t\tl, _ := strconv.Atoi(lArr[i])\n\t\tr, _ := strconv.Atoi(rArr[i])\n\t\tif l != r {\n\t\t\tif l > r {\n\t\t\t\treturn 1\n\t\t\t}\n\t\t\treturn -1\n\t\t}\n\t}\n\tif lItems == rItems {\n\t\treturn 0\n\t}\n\tif lItems < rItems {\n\t\treturn 1\n\t}\n\n\treturn -1\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>code tidy<commit_after><|endoftext|>"}
{"text":"<commit_before>package toml\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"reflect\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar e = fmt.Errorf\n\n\/\/ Primitive is a TOML value that hasn't been decoded into a Go value.\n\/\/ When using the various `Decode*` functions, the type `Primitive` may\n\/\/ be given to any value, and its decoding will be delayed.\n\/\/\n\/\/ A `Primitive` value can be decoded using the `PrimitiveDecode` function.\n\/\/\n\/\/ The underlying representation of a `Primitive` value is subject to change.\n\/\/ Do not rely on it.\n\/\/\n\/\/ N.B. Primitive values are still parsed, so using them will only avoid\n\/\/ the overhead of reflection. They can be useful when you don't know the\n\/\/ exact type of TOML data until run time.\ntype Primitive interface{}\n\n\/\/ PrimitiveDecode is just like the other `Decode*` functions, except it\n\/\/ decodes a TOML value that has already been parsed. Valid primitive values\n\/\/ can *only* be obtained from values filled by the decoder functions,\n\/\/ including `PrimitiveDecode`. (i.e., `v` may contain more `Primitive`\n\/\/ values.)\n\/\/\n\/\/ Meta data for primitive values is included in the meta data returned by\n\/\/ the `Decode*` functions.\nfunc PrimitiveDecode(primValue Primitive, v interface{}) error {\n\treturn unify(primValue, rvalue(v))\n}\n\n\/\/ Decode will decode the contents of `data` in TOML format into a pointer\n\/\/ `v`.\n\/\/\n\/\/ TOML hashes correspond to Go structs or maps. (Dealer's choice. They can be\n\/\/ used interchangeably.)\n\/\/\n\/\/ TOML datetimes correspond to Go `time.Time` values.\n\/\/\n\/\/ All other TOML types (float, string, int, bool and array) correspond\n\/\/ to the obvious Go types.\n\/\/\n\/\/ TOML keys can map to either keys in a Go map or field names in a Go\n\/\/ struct. The special `toml` struct tag may be used to map TOML keys to\n\/\/ struct fields that don't match the key name exactly. (See the example.)\n\/\/ A case insensitive match to struct names will be tried if an exact match\n\/\/ can't be found.\n\/\/\n\/\/ The mapping between TOML values and Go values is loose. That is, there\n\/\/ may exist TOML values that cannot be placed into your representation, and\n\/\/ there may be parts of your representation that do not correspond to\n\/\/ TOML values.\n\/\/\n\/\/ This decoder will not handle cyclic types. If a cyclic type is passed,\n\/\/ `Decode` will not terminate.\nfunc Decode(data string, v interface{}) (MetaData, error) {\n\tp, err := parse(data)\n\tif err != nil {\n\t\treturn MetaData{}, err\n\t}\n\treturn MetaData{p.mapping, p.types, p.ordered}, unify(p.mapping, rvalue(v))\n}\n\n\/\/ DecodeFile is just like Decode, except it will automatically read the\n\/\/ contents of the file at `fpath` and decode it for you.\nfunc DecodeFile(fpath string, v interface{}) (MetaData, error) {\n\tbs, err := ioutil.ReadFile(fpath)\n\tif err != nil {\n\t\treturn MetaData{}, err\n\t}\n\treturn Decode(string(bs), v)\n}\n\n\/\/ DecodeReader is just like Decode, except it will consume all bytes\n\/\/ from the reader and decode it for you.\nfunc DecodeReader(r io.Reader, v interface{}) (MetaData, error) {\n\tbs, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn MetaData{}, err\n\t}\n\treturn Decode(string(bs), v)\n}\n\n\/\/ unify performs a sort of type unification based on the structure of `rv`,\n\/\/ which is the client representation.\n\/\/\n\/\/ Any type mismatch produces an error. Finding a type that we don't know\n\/\/ how to handle produces an unsupported type error.\nfunc unify(data interface{}, rv reflect.Value) error {\n\t\/\/ Special case. Look for a `Primitive` value.\n\tif rv.Type() == reflect.TypeOf((*Primitive)(nil)).Elem() {\n\t\treturn unifyAnything(data, rv)\n\t}\n\n\t\/\/ Special case. Go's `time.Time` is a struct, which we don't want\n\t\/\/ to confuse with a user struct.\n\tif rv.Type().AssignableTo(rvalue(time.Time{}).Type()) {\n\t\treturn unifyDatetime(data, rv)\n\t}\n\n\tk := rv.Kind()\n\n\t\/\/ laziness\n\tif k >= reflect.Int && k <= reflect.Uint64 {\n\t\treturn unifyInt(data, rv)\n\t}\n\tswitch k {\n\tcase reflect.Struct:\n\t\treturn unifyStruct(data, rv)\n\tcase reflect.Map:\n\t\treturn unifyMap(data, rv)\n\tcase reflect.Slice:\n\t\treturn unifySlice(data, rv)\n\tcase reflect.String:\n\t\treturn unifyString(data, rv)\n\tcase reflect.Bool:\n\t\treturn unifyBool(data, rv)\n\tcase reflect.Interface:\n\t\t\/\/ we only support empty interfaces.\n\t\tif rv.NumMethod() > 0 {\n\t\t\te(\"Unsupported type '%s'.\", rv.Kind())\n\t\t}\n\t\treturn unifyAnything(data, rv)\n\tcase reflect.Float32:\n\t\tfallthrough\n\tcase reflect.Float64:\n\t\treturn unifyFloat64(data, rv)\n\t}\n\treturn e(\"Unsupported type '%s'.\", rv.Kind())\n}\n\nfunc unifyStruct(mapping interface{}, rv reflect.Value) error {\n\ttmap, ok := mapping.(map[string]interface{})\n\tif !ok {\n\t\treturn mismatch(rv, \"map\", mapping)\n\t}\n\n\trt := rv.Type()\n\tfor i := 0; i < rt.NumField(); i++ {\n\t\t\/\/ A little tricky. We want to use the special `toml` name in the\n\t\t\/\/ struct tag if it exists. In particular, we need to make sure that\n\t\t\/\/ this struct field is in the current map before trying to unify it.\n\t\tsft := rt.Field(i)\n\t\tkname := sft.Tag.Get(\"toml\")\n\t\tif len(kname) == 0 {\n\t\t\tkname = sft.Name\n\t\t}\n\t\tif datum, ok := insensitiveGet(tmap, kname); ok {\n\t\t\tsf := indirect(rv.Field(i))\n\n\t\t\t\/\/ Don't try to mess with unexported types and other such things.\n\t\t\tif sf.CanSet() {\n\t\t\t\tif err := unify(datum, sf); err != nil {\n\t\t\t\t\treturn e(\"Type mismatch for '%s.%s': %s\",\n\t\t\t\t\t\trt.String(), sft.Name, err)\n\t\t\t\t}\n\t\t\t} else if len(sft.Tag.Get(\"toml\")) > 0 {\n\t\t\t\t\/\/ Bad user! No soup for you!\n\t\t\t\treturn e(\"Field '%s.%s' is unexported, and therefore cannot \"+\n\t\t\t\t\t\"be loaded with reflection.\", rt.String(), sft.Name)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc unifyMap(mapping interface{}, rv reflect.Value) error {\n\ttmap, ok := mapping.(map[string]interface{})\n\tif !ok {\n\t\treturn badtype(\"map\", mapping)\n\t}\n\tif rv.IsNil() {\n\t\trv.Set(reflect.MakeMap(rv.Type()))\n\t}\n\tfor k, v := range tmap {\n\t\trvkey := indirect(reflect.New(rv.Type().Key()))\n\t\trvval := indirect(reflect.New(rv.Type().Elem()))\n\t\tif err := unify(v, rvval); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trvkey.SetString(k)\n\t\trv.SetMapIndex(rvkey, rvval)\n\t}\n\treturn nil\n}\n\nfunc unifySlice(data interface{}, rv reflect.Value) error {\n\tslice, ok := data.([]interface{})\n\tif !ok {\n\t\treturn badtype(\"slice\", data)\n\t}\n\tif rv.IsNil() {\n\t\trv.Set(reflect.MakeSlice(rv.Type(), len(slice), len(slice)))\n\t}\n\tfor i, v := range slice {\n\t\tsliceval := indirect(rv.Index(i))\n\t\tif err := unify(v, sliceval); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc unifyDatetime(data interface{}, rv reflect.Value) error {\n\tif _, ok := data.(time.Time); ok {\n\t\trv.Set(reflect.ValueOf(data))\n\t\treturn nil\n\t}\n\treturn badtype(\"time.Time\", data)\n}\n\nfunc unifyString(data interface{}, rv reflect.Value) error {\n\tif s, ok := data.(string); ok {\n\t\trv.SetString(s)\n\t\treturn nil\n\t}\n\treturn badtype(\"string\", data)\n}\n\nfunc unifyFloat64(data interface{}, rv reflect.Value) error {\n\tif num, ok := data.(float64); ok {\n\t\tswitch rv.Kind() {\n\t\tcase reflect.Float32:\n\t\t\tfallthrough\n\t\tcase reflect.Float64:\n\t\t\trv.SetFloat(num)\n\t\tdefault:\n\t\t\tpanic(\"bug\")\n\t\t}\n\t\treturn nil\n\t}\n\treturn badtype(\"float\", data)\n}\n\nfunc unifyInt(data interface{}, rv reflect.Value) error {\n\tif num, ok := data.(int64); ok {\n\t\tswitch rv.Kind() {\n\t\tcase reflect.Int:\n\t\t\tfallthrough\n\t\tcase reflect.Int8:\n\t\t\tfallthrough\n\t\tcase reflect.Int16:\n\t\t\tfallthrough\n\t\tcase reflect.Int32:\n\t\t\tfallthrough\n\t\tcase reflect.Int64:\n\t\t\trv.SetInt(int64(num))\n\t\tcase reflect.Uint:\n\t\t\tfallthrough\n\t\tcase reflect.Uint8:\n\t\t\tfallthrough\n\t\tcase reflect.Uint16:\n\t\t\tfallthrough\n\t\tcase reflect.Uint32:\n\t\t\tfallthrough\n\t\tcase reflect.Uint64:\n\t\t\trv.SetUint(uint64(num))\n\t\tdefault:\n\t\t\tpanic(\"bug\")\n\t\t}\n\t\treturn nil\n\t}\n\treturn badtype(\"integer\", data)\n}\n\nfunc unifyBool(data interface{}, rv reflect.Value) error {\n\tif b, ok := data.(bool); ok {\n\t\trv.SetBool(b)\n\t\treturn nil\n\t}\n\treturn badtype(\"integer\", data)\n}\n\nfunc unifyAnything(data interface{}, rv reflect.Value) error {\n\t\/\/ too awesome to fail\n\trv.Set(reflect.ValueOf(data))\n\treturn nil\n}\n\n\/\/ rvalue returns a reflect.Value of `v`. All pointers are resolved.\nfunc rvalue(v interface{}) reflect.Value {\n\treturn indirect(reflect.ValueOf(v))\n}\n\n\/\/ indirect returns the value pointed to by a pointer.\n\/\/ Pointers are followed until the value is not a pointer.\n\/\/ New values are allocated for each nil pointer.\nfunc indirect(v reflect.Value) reflect.Value {\n\tif v.Kind() != reflect.Ptr {\n\t\treturn v\n\t}\n\tif v.IsNil() {\n\t\tv.Set(reflect.New(v.Type().Elem()))\n\t}\n\treturn indirect(reflect.Indirect(v))\n}\n\nfunc tstring(rv reflect.Value) string {\n\treturn rv.Type().String()\n}\n\nfunc badtype(expected string, data interface{}) error {\n\treturn e(\"Expected %s but found '%T'.\", expected, data)\n}\n\nfunc mismatch(user reflect.Value, expected string, data interface{}) error {\n\treturn e(\"Type mismatch for %s. Expected %s but found '%T'.\",\n\t\ttstring(user), expected, data)\n}\n\nfunc insensitiveGet(\n\ttmap map[string]interface{}, kname string) (interface{}, bool) {\n\n\tif datum, ok := tmap[kname]; ok {\n\t\treturn datum, true\n\t}\n\tfor k, v := range tmap {\n\t\tif strings.EqualFold(kname, k) {\n\t\t\treturn v, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\n\/\/ MetaData allows access to meta information about TOML data that may not\n\/\/ be inferrable via reflection. In particular, whether a key has been defined\n\/\/ and the TOML type of a key.\n\/\/\n\/\/ (XXX: If TOML gets NULL values, that information will be added here too.)\ntype MetaData struct {\n\tmapping map[string]interface{}\n\ttypes   map[string]tomlType\n\tkeys    []Key\n}\n\n\/\/ IsDefined returns true if the key given exists in the TOML data. The key\n\/\/ should be specified hierarchially. e.g.,\n\/\/\n\/\/\t\/\/ access the TOML key 'a.b.c'\n\/\/\tIsDefined(\"a\", \"b\", \"c\")\n\/\/\n\/\/ IsDefined will return false if an empty key given. Keys are case sensitive.\nfunc (md MetaData) IsDefined(key ...string) bool {\n\tvar hashOrVal interface{}\n\tvar hash map[string]interface{}\n\tvar ok bool\n\n\tif len(key) == 0 {\n\t\treturn false\n\t}\n\n\thashOrVal = md.mapping\n\tfor _, k := range key {\n\t\tif hash, ok = hashOrVal.(map[string]interface{}); !ok {\n\t\t\treturn false\n\t\t}\n\t\tif hashOrVal, ok = hash[k]; !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Type returns a string representation of the type of the key specified.\n\/\/\n\/\/ Type will return the empty string if given an empty key or a key that\n\/\/ does not exist. Keys are case sensitive.\nfunc (md MetaData) Type(key ...string) string {\n\tfullkey := strings.Join(key, \".\")\n\tif typ, ok := md.types[fullkey]; ok {\n\t\treturn typ.typeString()\n\t}\n\treturn \"\"\n}\n\n\/\/ Key is the type of any TOML key, including key groups. Use (MetaData).Keys\n\/\/ to get values of this type.\ntype Key []string\n\nfunc (k Key) String() string {\n\treturn strings.Join(k, \".\")\n}\n\nfunc (k Key) add(piece string) Key {\n\tnewKey := make(Key, len(k))\n\tcopy(newKey, k)\n\treturn append(newKey, piece)\n}\n\n\/\/ Keys returns a slice of every key in the TOML data, including key groups.\n\/\/ Each key is itself a slice, where the first element is the top of the\n\/\/ hierarchy and the last is the most specific.\n\/\/\n\/\/ The list will have the same order as the keys appeared in the TOML data.\n\/\/\n\/\/ All keys returned are non-empty.\nfunc (md MetaData) Keys() []Key {\n\treturn md.keys\n}\n\nfunc allKeys(m map[string]interface{}, context Key) []Key {\n\tkeys := make([]Key, 0, len(m))\n\tfor k, v := range m {\n\t\tkeys = append(keys, context.add(k))\n\t\tif t, ok := v.(map[string]interface{}); ok {\n\t\t\tkeys = append(keys, allKeys(t, context.add(k))...)\n\t\t}\n\t}\n\treturn keys\n}\n<commit_msg>Close issue #6.<commit_after>package toml\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"reflect\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar e = fmt.Errorf\n\n\/\/ Primitive is a TOML value that hasn't been decoded into a Go value.\n\/\/ When using the various `Decode*` functions, the type `Primitive` may\n\/\/ be given to any value, and its decoding will be delayed.\n\/\/\n\/\/ A `Primitive` value can be decoded using the `PrimitiveDecode` function.\n\/\/\n\/\/ The underlying representation of a `Primitive` value is subject to change.\n\/\/ Do not rely on it.\n\/\/\n\/\/ N.B. Primitive values are still parsed, so using them will only avoid\n\/\/ the overhead of reflection. They can be useful when you don't know the\n\/\/ exact type of TOML data until run time.\ntype Primitive interface{}\n\n\/\/ PrimitiveDecode is just like the other `Decode*` functions, except it\n\/\/ decodes a TOML value that has already been parsed. Valid primitive values\n\/\/ can *only* be obtained from values filled by the decoder functions,\n\/\/ including `PrimitiveDecode`. (i.e., `v` may contain more `Primitive`\n\/\/ values.)\n\/\/\n\/\/ Meta data for primitive values is included in the meta data returned by\n\/\/ the `Decode*` functions.\nfunc PrimitiveDecode(primValue Primitive, v interface{}) error {\n\treturn unify(primValue, rvalue(v))\n}\n\n\/\/ Decode will decode the contents of `data` in TOML format into a pointer\n\/\/ `v`.\n\/\/\n\/\/ TOML hashes correspond to Go structs or maps. (Dealer's choice. They can be\n\/\/ used interchangeably.)\n\/\/\n\/\/ TOML datetimes correspond to Go `time.Time` values.\n\/\/\n\/\/ All other TOML types (float, string, int, bool and array) correspond\n\/\/ to the obvious Go types.\n\/\/\n\/\/ TOML keys can map to either keys in a Go map or field names in a Go\n\/\/ struct. The special `toml` struct tag may be used to map TOML keys to\n\/\/ struct fields that don't match the key name exactly. (See the example.)\n\/\/ A case insensitive match to struct names will be tried if an exact match\n\/\/ can't be found.\n\/\/\n\/\/ The mapping between TOML values and Go values is loose. That is, there\n\/\/ may exist TOML values that cannot be placed into your representation, and\n\/\/ there may be parts of your representation that do not correspond to\n\/\/ TOML values.\n\/\/\n\/\/ This decoder will not handle cyclic types. If a cyclic type is passed,\n\/\/ `Decode` will not terminate.\nfunc Decode(data string, v interface{}) (MetaData, error) {\n\tp, err := parse(data)\n\tif err != nil {\n\t\treturn MetaData{}, err\n\t}\n\treturn MetaData{p.mapping, p.types, p.ordered}, unify(p.mapping, rvalue(v))\n}\n\n\/\/ DecodeFile is just like Decode, except it will automatically read the\n\/\/ contents of the file at `fpath` and decode it for you.\nfunc DecodeFile(fpath string, v interface{}) (MetaData, error) {\n\tbs, err := ioutil.ReadFile(fpath)\n\tif err != nil {\n\t\treturn MetaData{}, err\n\t}\n\treturn Decode(string(bs), v)\n}\n\n\/\/ DecodeReader is just like Decode, except it will consume all bytes\n\/\/ from the reader and decode it for you.\nfunc DecodeReader(r io.Reader, v interface{}) (MetaData, error) {\n\tbs, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn MetaData{}, err\n\t}\n\treturn Decode(string(bs), v)\n}\n\n\/\/ unify performs a sort of type unification based on the structure of `rv`,\n\/\/ which is the client representation.\n\/\/\n\/\/ Any type mismatch produces an error. Finding a type that we don't know\n\/\/ how to handle produces an unsupported type error.\nfunc unify(data interface{}, rv reflect.Value) error {\n\t\/\/ Special case. Look for a `Primitive` value.\n\tif rv.Type() == reflect.TypeOf((*Primitive)(nil)).Elem() {\n\t\treturn unifyAnything(data, rv)\n\t}\n\n\t\/\/ Special case. Go's `time.Time` is a struct, which we don't want\n\t\/\/ to confuse with a user struct.\n\tif rv.Type().AssignableTo(rvalue(time.Time{}).Type()) {\n\t\treturn unifyDatetime(data, rv)\n\t}\n\n\tk := rv.Kind()\n\n\t\/\/ laziness\n\tif k >= reflect.Int && k <= reflect.Uint64 {\n\t\treturn unifyInt(data, rv)\n\t}\n\tswitch k {\n\tcase reflect.Struct:\n\t\treturn unifyStruct(data, rv)\n\tcase reflect.Map:\n\t\treturn unifyMap(data, rv)\n\tcase reflect.Slice:\n\t\treturn unifySlice(data, rv)\n\tcase reflect.String:\n\t\treturn unifyString(data, rv)\n\tcase reflect.Bool:\n\t\treturn unifyBool(data, rv)\n\tcase reflect.Interface:\n\t\t\/\/ we only support empty interfaces.\n\t\tif rv.NumMethod() > 0 {\n\t\t\treturn e(\"Unsupported type '%s'.\", rv.Kind())\n\t\t}\n\t\treturn unifyAnything(data, rv)\n\tcase reflect.Float32:\n\t\tfallthrough\n\tcase reflect.Float64:\n\t\treturn unifyFloat64(data, rv)\n\t}\n\treturn e(\"Unsupported type '%s'.\", rv.Kind())\n}\n\nfunc unifyStruct(mapping interface{}, rv reflect.Value) error {\n\ttmap, ok := mapping.(map[string]interface{})\n\tif !ok {\n\t\treturn mismatch(rv, \"map\", mapping)\n\t}\n\n\trt := rv.Type()\n\tfor i := 0; i < rt.NumField(); i++ {\n\t\t\/\/ A little tricky. We want to use the special `toml` name in the\n\t\t\/\/ struct tag if it exists. In particular, we need to make sure that\n\t\t\/\/ this struct field is in the current map before trying to unify it.\n\t\tsft := rt.Field(i)\n\t\tkname := sft.Tag.Get(\"toml\")\n\t\tif len(kname) == 0 {\n\t\t\tkname = sft.Name\n\t\t}\n\t\tif datum, ok := insensitiveGet(tmap, kname); ok {\n\t\t\tsf := indirect(rv.Field(i))\n\n\t\t\t\/\/ Don't try to mess with unexported types and other such things.\n\t\t\tif sf.CanSet() {\n\t\t\t\tif err := unify(datum, sf); err != nil {\n\t\t\t\t\treturn e(\"Type mismatch for '%s.%s': %s\",\n\t\t\t\t\t\trt.String(), sft.Name, err)\n\t\t\t\t}\n\t\t\t} else if len(sft.Tag.Get(\"toml\")) > 0 {\n\t\t\t\t\/\/ Bad user! No soup for you!\n\t\t\t\treturn e(\"Field '%s.%s' is unexported, and therefore cannot \"+\n\t\t\t\t\t\"be loaded with reflection.\", rt.String(), sft.Name)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc unifyMap(mapping interface{}, rv reflect.Value) error {\n\ttmap, ok := mapping.(map[string]interface{})\n\tif !ok {\n\t\treturn badtype(\"map\", mapping)\n\t}\n\tif rv.IsNil() {\n\t\trv.Set(reflect.MakeMap(rv.Type()))\n\t}\n\tfor k, v := range tmap {\n\t\trvkey := indirect(reflect.New(rv.Type().Key()))\n\t\trvval := indirect(reflect.New(rv.Type().Elem()))\n\t\tif err := unify(v, rvval); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trvkey.SetString(k)\n\t\trv.SetMapIndex(rvkey, rvval)\n\t}\n\treturn nil\n}\n\nfunc unifySlice(data interface{}, rv reflect.Value) error {\n\tslice, ok := data.([]interface{})\n\tif !ok {\n\t\treturn badtype(\"slice\", data)\n\t}\n\tif rv.IsNil() {\n\t\trv.Set(reflect.MakeSlice(rv.Type(), len(slice), len(slice)))\n\t}\n\tfor i, v := range slice {\n\t\tsliceval := indirect(rv.Index(i))\n\t\tif err := unify(v, sliceval); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc unifyDatetime(data interface{}, rv reflect.Value) error {\n\tif _, ok := data.(time.Time); ok {\n\t\trv.Set(reflect.ValueOf(data))\n\t\treturn nil\n\t}\n\treturn badtype(\"time.Time\", data)\n}\n\nfunc unifyString(data interface{}, rv reflect.Value) error {\n\tif s, ok := data.(string); ok {\n\t\trv.SetString(s)\n\t\treturn nil\n\t}\n\treturn badtype(\"string\", data)\n}\n\nfunc unifyFloat64(data interface{}, rv reflect.Value) error {\n\tif num, ok := data.(float64); ok {\n\t\tswitch rv.Kind() {\n\t\tcase reflect.Float32:\n\t\t\tfallthrough\n\t\tcase reflect.Float64:\n\t\t\trv.SetFloat(num)\n\t\tdefault:\n\t\t\tpanic(\"bug\")\n\t\t}\n\t\treturn nil\n\t}\n\treturn badtype(\"float\", data)\n}\n\nfunc unifyInt(data interface{}, rv reflect.Value) error {\n\tif num, ok := data.(int64); ok {\n\t\tswitch rv.Kind() {\n\t\tcase reflect.Int:\n\t\t\tfallthrough\n\t\tcase reflect.Int8:\n\t\t\tfallthrough\n\t\tcase reflect.Int16:\n\t\t\tfallthrough\n\t\tcase reflect.Int32:\n\t\t\tfallthrough\n\t\tcase reflect.Int64:\n\t\t\trv.SetInt(int64(num))\n\t\tcase reflect.Uint:\n\t\t\tfallthrough\n\t\tcase reflect.Uint8:\n\t\t\tfallthrough\n\t\tcase reflect.Uint16:\n\t\t\tfallthrough\n\t\tcase reflect.Uint32:\n\t\t\tfallthrough\n\t\tcase reflect.Uint64:\n\t\t\trv.SetUint(uint64(num))\n\t\tdefault:\n\t\t\tpanic(\"bug\")\n\t\t}\n\t\treturn nil\n\t}\n\treturn badtype(\"integer\", data)\n}\n\nfunc unifyBool(data interface{}, rv reflect.Value) error {\n\tif b, ok := data.(bool); ok {\n\t\trv.SetBool(b)\n\t\treturn nil\n\t}\n\treturn badtype(\"integer\", data)\n}\n\nfunc unifyAnything(data interface{}, rv reflect.Value) error {\n\t\/\/ too awesome to fail\n\trv.Set(reflect.ValueOf(data))\n\treturn nil\n}\n\n\/\/ rvalue returns a reflect.Value of `v`. All pointers are resolved.\nfunc rvalue(v interface{}) reflect.Value {\n\treturn indirect(reflect.ValueOf(v))\n}\n\n\/\/ indirect returns the value pointed to by a pointer.\n\/\/ Pointers are followed until the value is not a pointer.\n\/\/ New values are allocated for each nil pointer.\nfunc indirect(v reflect.Value) reflect.Value {\n\tif v.Kind() != reflect.Ptr {\n\t\treturn v\n\t}\n\tif v.IsNil() {\n\t\tv.Set(reflect.New(v.Type().Elem()))\n\t}\n\treturn indirect(reflect.Indirect(v))\n}\n\nfunc tstring(rv reflect.Value) string {\n\treturn rv.Type().String()\n}\n\nfunc badtype(expected string, data interface{}) error {\n\treturn e(\"Expected %s but found '%T'.\", expected, data)\n}\n\nfunc mismatch(user reflect.Value, expected string, data interface{}) error {\n\treturn e(\"Type mismatch for %s. Expected %s but found '%T'.\",\n\t\ttstring(user), expected, data)\n}\n\nfunc insensitiveGet(\n\ttmap map[string]interface{}, kname string) (interface{}, bool) {\n\n\tif datum, ok := tmap[kname]; ok {\n\t\treturn datum, true\n\t}\n\tfor k, v := range tmap {\n\t\tif strings.EqualFold(kname, k) {\n\t\t\treturn v, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\n\/\/ MetaData allows access to meta information about TOML data that may not\n\/\/ be inferrable via reflection. In particular, whether a key has been defined\n\/\/ and the TOML type of a key.\n\/\/\n\/\/ (XXX: If TOML gets NULL values, that information will be added here too.)\ntype MetaData struct {\n\tmapping map[string]interface{}\n\ttypes   map[string]tomlType\n\tkeys    []Key\n}\n\n\/\/ IsDefined returns true if the key given exists in the TOML data. The key\n\/\/ should be specified hierarchially. e.g.,\n\/\/\n\/\/\t\/\/ access the TOML key 'a.b.c'\n\/\/\tIsDefined(\"a\", \"b\", \"c\")\n\/\/\n\/\/ IsDefined will return false if an empty key given. Keys are case sensitive.\nfunc (md MetaData) IsDefined(key ...string) bool {\n\tvar hashOrVal interface{}\n\tvar hash map[string]interface{}\n\tvar ok bool\n\n\tif len(key) == 0 {\n\t\treturn false\n\t}\n\n\thashOrVal = md.mapping\n\tfor _, k := range key {\n\t\tif hash, ok = hashOrVal.(map[string]interface{}); !ok {\n\t\t\treturn false\n\t\t}\n\t\tif hashOrVal, ok = hash[k]; !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Type returns a string representation of the type of the key specified.\n\/\/\n\/\/ Type will return the empty string if given an empty key or a key that\n\/\/ does not exist. Keys are case sensitive.\nfunc (md MetaData) Type(key ...string) string {\n\tfullkey := strings.Join(key, \".\")\n\tif typ, ok := md.types[fullkey]; ok {\n\t\treturn typ.typeString()\n\t}\n\treturn \"\"\n}\n\n\/\/ Key is the type of any TOML key, including key groups. Use (MetaData).Keys\n\/\/ to get values of this type.\ntype Key []string\n\nfunc (k Key) String() string {\n\treturn strings.Join(k, \".\")\n}\n\nfunc (k Key) add(piece string) Key {\n\tnewKey := make(Key, len(k))\n\tcopy(newKey, k)\n\treturn append(newKey, piece)\n}\n\n\/\/ Keys returns a slice of every key in the TOML data, including key groups.\n\/\/ Each key is itself a slice, where the first element is the top of the\n\/\/ hierarchy and the last is the most specific.\n\/\/\n\/\/ The list will have the same order as the keys appeared in the TOML data.\n\/\/\n\/\/ All keys returned are non-empty.\nfunc (md MetaData) Keys() []Key {\n\treturn md.keys\n}\n\nfunc allKeys(m map[string]interface{}, context Key) []Key {\n\tkeys := make([]Key, 0, len(m))\n\tfor k, v := range m {\n\t\tkeys = append(keys, context.add(k))\n\t\tif t, ok := v.(map[string]interface{}); ok {\n\t\t\tkeys = append(keys, allKeys(t, context.add(k))...)\n\t\t}\n\t}\n\treturn keys\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ package Commands defines and implements command-line commands and flags\n\/\/ used by devopsdays-cli. Commands and flags are implemented using Cobra.\npackage commands\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/devopsdays\/devopsdays-cli\/helpers\/paths\"\n\t\"github.com\/dimiro1\/banner\"\n\t\"github.com\/mattn\/go-colorable\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n)\n\nvar myBanner = `\n\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|d|e|v|o|p|s|d|a|y|s|-|c|l|i|\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n`\n\n\/\/ webdir is the path to the source files for the Hugo website\nvar webdir = paths.GetWebdir()\n\n\/\/ const webdir = \"\/Users\/mattstratton\/src\/devopsdays-web\"\n\nvar cfgFile string\n\n\/\/ Debug means should we run in debug mode. Duh.\nvar Debug bool\n\n\/\/ City is the city we will be using - obtained via local flag\nvar City string\n\n\/\/ Year is the year we will be using - obtained via local flag\nvar Year string\n\n\/\/ All is used by a flag on Show commands to represent showing all of a thing\nvar All bool\n\n\/\/ RootCmd represents the base command when called without any subcommands\nvar RootCmd = &cobra.Command{\n\tUse:   \"devopsdays-cli\",\n\tShort: \"Run maintenance tasks for the devopsdays.org website\",\n\tLong: `\nCommand-line utilities for the devopsdays.org website\nbuilt with love by mattstratton in Go.\n\nComplete documentation is available at https:\/\/github.com\/devopsdays\/devopsdays-cli`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tmainPrompt()\n\t},\n}\n\n\/\/ Execute adds all child commands to the root command sets flags appropriately.\n\/\/ This is called by main.main(). It only needs to happen once to the rootCmd.\nfunc Execute() {\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\nfunc init() {\n\tcobra.OnInitialize(initConfig)\n\tisEnabled := true\n\tisColorEnabled := true\n\tbanner.Init(colorable.NewColorableStdout(), isEnabled, isColorEnabled, bytes.NewBufferString(myBanner))\n\n\tRootCmd.PersistentFlags().BoolVarP(&Debug, \"debug\", \"d\", false, \"enable debug mode\")\n\n}\n\n\/\/ initConfig reads in config file and ENV variables if set.\nfunc initConfig() {\n\tif cfgFile != \"\" { \/\/ enable ability to specify config file via flag\n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\n\tviper.SetConfigName(\".devopsdays-cli\") \/\/ name of config file (without extension)\n\tviper.AddConfigPath(\"$HOME\")           \/\/ adding home directory as first search path\n\tviper.AutomaticEnv()                   \/\/ read in environment variables that match\n\n\t\/\/ If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n}\n<commit_msg>Fix godoc for commands package<commit_after>\/\/ package commands defines and implements command-line commands and flags\n\/\/ used by devopsdays-cli. Commands and flags are implemented using Cobra.\npackage commands\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/devopsdays\/devopsdays-cli\/helpers\/paths\"\n\t\"github.com\/dimiro1\/banner\"\n\t\"github.com\/mattn\/go-colorable\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n)\n\nvar myBanner = `\n\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|d|e|v|o|p|s|d|a|y|s|-|c|l|i|\n+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n`\n\n\/\/ webdir is the path to the source files for the Hugo website\nvar webdir = paths.GetWebdir()\n\n\/\/ const webdir = \"\/Users\/mattstratton\/src\/devopsdays-web\"\n\nvar cfgFile string\n\n\/\/ Debug means should we run in debug mode. Duh.\nvar Debug bool\n\n\/\/ City is the city we will be using - obtained via local flag\nvar City string\n\n\/\/ Year is the year we will be using - obtained via local flag\nvar Year string\n\n\/\/ All is used by a flag on Show commands to represent showing all of a thing\nvar All bool\n\n\/\/ RootCmd represents the base command when called without any subcommands\nvar RootCmd = &cobra.Command{\n\tUse:   \"devopsdays-cli\",\n\tShort: \"Run maintenance tasks for the devopsdays.org website\",\n\tLong: `\nCommand-line utilities for the devopsdays.org website\nbuilt with love by mattstratton in Go.\n\nComplete documentation is available at https:\/\/github.com\/devopsdays\/devopsdays-cli`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tmainPrompt()\n\t},\n}\n\n\/\/ Execute adds all child commands to the root command sets flags appropriately.\n\/\/ This is called by main.main(). It only needs to happen once to the rootCmd.\nfunc Execute() {\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\nfunc init() {\n\tcobra.OnInitialize(initConfig)\n\tisEnabled := true\n\tisColorEnabled := true\n\tbanner.Init(colorable.NewColorableStdout(), isEnabled, isColorEnabled, bytes.NewBufferString(myBanner))\n\n\tRootCmd.PersistentFlags().BoolVarP(&Debug, \"debug\", \"d\", false, \"enable debug mode\")\n\n}\n\n\/\/ initConfig reads in config file and ENV variables if set.\nfunc initConfig() {\n\tif cfgFile != \"\" { \/\/ enable ability to specify config file via flag\n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\n\tviper.SetConfigName(\".devopsdays-cli\") \/\/ name of config file (without extension)\n\tviper.AddConfigPath(\"$HOME\")           \/\/ adding home directory as first search path\n\tviper.AutomaticEnv()                   \/\/ read in environment variables that match\n\n\t\/\/ If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\t\"container\/list\"\n\tjs \"encoding\/json\"\n\n\t\"github.com\/kurrik\/oauth1a\"\n\t\"github.com\/codingneo\/twittergo\"\n\t\"github.com\/kurrik\/json\"\n\t\"github.com\/robfig\/cron\"\n\t\/\/\"github.com\/PuerkitoBio\/goquery\"\n\t\"github.com\/advancedlogic\/GoOse\"\n\t\"github.com\/codingneo\/tweetsbot\/ranking\"\n)\n\n\nfunc LoadCredentials() (client *twittergo.Client, err error) {\n\tcredentials, err := ioutil.ReadFile(\"CREDENTIALS\")\n\tif err != nil {\n\t\treturn\n\t}\n\tlines := strings.Split(string(credentials), \"\\n\")\n\tconfig := &oauth1a.ClientConfig{\n\t\tConsumerKey:    lines[0],\n\t\tConsumerSecret: lines[1],\n\t}\n\tuser := oauth1a.NewAuthorizedConfig(lines[2], lines[3])\n\tclient = twittergo.NewClient(config, user, \"stream.twitter.com\")\n\treturn\n}\n\ntype Args struct {\n\tTrack string\n\tLang string\n}\n\nfunc parseArgs() *Args {\n\ta := &Args{}\n\tflag.StringVar(&a.Track, \"track\", \"Data Science,Big Data\", \"Keyword to look up\")\n\tflag.StringVar(&a.Lang, \"lang\", \"en\", \"Language to look up\")\n\tflag.Parse()\n\treturn a\n}\n\ntype streamConn struct {\n\tclient   *http.Client\n\tresp     *http.Response\n\turl      *url.URL\n\tstale    bool\n\tclosed   bool\n\tmu       sync.Mutex\n\t\/\/ wait time before trying to reconnect, this will be\n\t\/\/ exponentially moved up until reaching maxWait, when\n\t\/\/ it will exit\n\twait    int\n\tmaxWait int\n\tconnect func() (*http.Response, error)\n}\n\nfunc NewStreamConn(max int) streamConn {\n\treturn streamConn{wait: 1, maxWait: max}\n}\n\nfunc (conn *streamConn) Close() {\n\t\/\/ Just mark the connection as stale, and let the connect() handler close after a read\n\tconn.mu.Lock()\n\tdefer conn.mu.Unlock()\n\tconn.stale = true\n\tconn.closed = true\n\tif conn.resp != nil {\n\t\tconn.resp.Body.Close()\n\t}\n}\n\nfunc (conn *streamConn) isStale() bool {\n\tconn.mu.Lock()\n\tr := conn.stale\n\tconn.mu.Unlock()\n\treturn r\n}\n\nfunc readStream(client *twittergo.Client, sc streamConn, path string, query url.Values, \n\t\t\t\tresp *twittergo.APIResponse, handler func([]byte), done chan bool) {\n\n\tvar reader *bufio.Reader\n\treader = bufio.NewReader(resp.Body)\n\n\tfor {\n\t\t\/\/we've been closed\n\t\tif sc.isStale() {\n\t\t\tsc.Close()\n\t\t\tfmt.Println(\"Connection closed, shutting down \")\n\t\t\tbreak\n\t\t}\n\n\t\tline, err := reader.ReadBytes('\\n')\n\n\t\tif err != nil {\n\t\t\tif sc.isStale() {\n\t\t\t\tfmt.Println(\"conn stale, continue\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttime.Sleep(time.Second * time.Duration(sc.wait))\n\t\t\t\/\/try reconnecting, but exponentially back off until MaxWait is reached then exit?\n\t\t\tresp, err := Connect(client, path, query)\n\t\t\tif err != nil || resp == nil {\n\t\t\t\tfmt.Println(\" Could not reconnect to source? sleeping and will retry \")\n\t\t\t\tif sc.wait < sc.maxWait {\n\t\t\t\t\tsc.wait = sc.wait * 2\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"exiting, max wait reached\")\n\t\t\t\t\tdone <- true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif resp.StatusCode != 200 {\n\t\t\t\tfmt.Printf(\"resp.StatusCode = %d\", resp.StatusCode)\n\t\t\t\tif sc.wait < sc.maxWait {\n\t\t\t\t\tsc.wait = sc.wait * 2\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treader = bufio.NewReader(resp.Body)\n\t\t\tcontinue\n\t\t} else if sc.wait != 1 {\n\t\t\tsc.wait = 1\n\t\t}\n\t\tline = bytes.TrimSpace(line)\n\t\tfmt.Println(\"Received a line \")\n\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\thandler(line)\n\t}\n}\n\nfunc Connect(client *twittergo.Client, path string, query url.Values) (resp *twittergo.APIResponse, err error) {\n\tvar (\n\t\treq \t*http.Request\n\t)\n\n\turl := fmt.Sprintf(\"%v?%v\", path, query.Encode())\n\treq, err = http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Could not parse request: %v\\n\", err)\n\t\treturn\n\t}\n\tresp, err = client.SendRequest(req)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Could not send request: %v\\n\", err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"resp.StatusCode=%d\\n\", resp.StatusCode)\n\treturn\n}\n\nfunc filterStream(client *twittergo.Client, path string, query url.Values) (err error) {\n\tvar (\n\t\tresp    *twittergo.APIResponse\n\t)\n\n\tsc := NewStreamConn(300)\n\n\tresp, err = Connect(client, path, query)\n\n\tdone := make(chan bool)\n\tstream := make(chan []byte, 1000)\n\tgo func() {\n\t\ttopList := list.New()\n\n\t\t\/\/Cron job to store toplist per hour\n\t\tc := cron.New()\n\t\tc.AddFunc(\"0 * * * * *\", \n\t\t\tfunc() { \n\t\t\t\tfmt.Println(\"cron cron cron cron ............................\")\n\t\t\t\tfilename := \".\/data\/toplist-\" + \n\t\t\t\t\t\t\t\t\t\ttime.Now().Local().Format(\"2006-01-02\") +\n\t\t\t\t\t\t\t\t\t\t\".json\"\n\n\t\t\t\toutput := make(map[string]interface{})\n\t\t\t\toutput[\"articles\"] = make([]ranking.Item, 0)\n\n\t\t\t\tf, err := os.OpenFile(filename, os.O_RDWR, 0666)\n\t\t\t\tif (err != nil) {\n\t\t\t\t\tfmt.Println(\"[Cron] File not exist\")\n\t\t\t\t\tf, err = os.Create(filename)\n\t\t\t\t\tif (err != nil) {\n\t\t\t\t\t\tfmt.Println(\"[Cron] File creation error\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttlist := make([]ranking.Item, 0)\n\t\t\t\tfor e := topList.Front(); e != nil; e = e.Next() {\n\t\t\t\t\tfmt.Println(\"[Cron] Write url into file\")\n\t\t\t\t\t\/\/f.WriteString(e.Value.(ranking.Item).Url)\n\t\t\t\t\t\/\/f.WriteString(\"\\n\")\n\t\t\t\t\ttlist = append(tlist, e.Value.(ranking.Item))\n\t\t\t\t}\n\t\t\t\toutput[\"articles\"] = tlist\n\n\t\t\t\tjsonstr, _ := js.Marshal(output)\n\t\t\t\tf.WriteString(string(jsonstr))\n\t\t\t\tf.Sync()\n\t\t\t\tf.Close()\n\t\t\t})\n\t\tc.Start()\n\t\tfmt.Println(\"cron job start\")\n\n\t\tg := goose.New()\n\t\tfor data := range stream {\n\t\t\tfmt.Println(string(data))\n\t\t\ttweet := &twittergo.Tweet{}\n\t\t\terr := json.Unmarshal(data, tweet)\n\t\t\tif (err == nil) {\n\t\t\t\tfmt.Printf(\"ID:                   %v\\n\", tweet.Id())\n\t\t\t\tfmt.Printf(\"User:                 %v\\n\", tweet.User().ScreenName())\n\t\t\t\tfmt.Printf(\"Tweet:                %v\\n\", tweet.Text())\n\t\t\t\t\n\t\t\t\trs := tweet.RetweetStatus()\n\t\t\t\tvote := 0\n\t\t\t\tif (rs != nil) {\n\t\t\t\t\tfmt.Printf(\"retweet_count:        %d\\n\", rs.RetweetCount())\n\t\t\t\t\tfmt.Printf(\"favorite_count:        %d\\n\", rs.FavoriteCount())\n\t\t\t\t\tvote += int(rs.RetweetCount()+rs.FavoriteCount())\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\te := tweet.Entities()\n\t\t\t\tif (e != nil) {\n\t\t\t\t\tfmt.Printf(\"url:        %v\\n\", e.FirstUrl().ExpandedUrl())\n\n\t\t\t\t\t\/\/ Form top item\n\t\t\t\t\tif (e.FirstUrl().ExpandedUrl()!=\"\") {\n\t\t\t\t\t\titem := ranking.Item{}\n\t\t\t\t\t\titem.Vote = vote\n\t\t\t\t\t\titem.Url = e.FirstUrl().ExpandedUrl()\n\n\t\t\t\t\t\t\/\/ article extraction\n\t\t\t\t\t\t\/\/doc, err := goquery.NewDocument(item.Url)\n\t\t\t\t\t\tarticle := g.ExtractFromUrl(item.Url)\n\n\t\t\t\t\t\tfmt.Println(\"title\", article.Title)\n    \t\t\t\tfmt.Println(\"description\", article.MetaDescription)\n    \t\t\t\tfmt.Println(\"top image\", article.TopImage)\n\n    \t\t\t\tif (article.Title != \"\") && \n    \t\t\t\t\t (article.MetaDescription != \"\")) {\n\t\t\t\t\t\t\titem.Title = article.Title\n    \t\t\t\t\titem.Description = article.MetaDescription\n    \t\t\t\t\titem.Image = article.TopImage\n\n    \t\t\t\t\tranking.Insert(topList, item)\n    \t\t\t\t}\n\n\t\t\t\t\t\t\/\/if err == nil {\n\t\t\t\t\t\t\/\/\titem.Title = doc.Find(\"title\").Text()\n\t\t\t\t\t\t\/\/\tfmt.Printf(\"title:        %v\\n\", item.Title)\n\t\t\t\t\t\t\/\/\tranking.Insert(topList, item)\n\t\t\t\t\t\t\/\/}\n\n\t\t\t\t\t\tfmt.Println(\"**********************************\")\n\t\t\t\t\t\tfor e := topList.Front(); e != nil; e = e.Next() {\n\t\t\t\t\t\t\tfmt.Printf(\"%d: %v\\n\",e.Value.(ranking.Item).Vote, e.Value.(ranking.Item).Url)\n\t\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\treadStream(client, sc, path, query, resp, func(line []byte) {\n\t\tstream <- line}, done)\n\n\n\treturn\n}\n\nfunc main() {\n\tvar (\n\t\terr    error\n\t\targs   *Args\n\t\tclient *twittergo.Client\n\t)\n\n\targs = parseArgs()\n\tif client, err = LoadCredentials(); err != nil {\n\t\tfmt.Printf(\"Could not parse CREDENTIALS file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tfmt.Println(args.Track)\n\tquery := url.Values{}\n\tquery.Set(\"track\", args.Track)\n\tquery.Set(\"lang\", args.Lang)\n\n\tfmt.Println(\"Printing everything about data science:\")\n\tfmt.Printf(\"=========================================================\\n\")\n\tif err = filterStream(client, \"\/1.1\/statuses\/filter.json\", query); err != nil {\n\t\tfmt.Println(\"Error: %v\\n\", err)\n\t}\n\tfmt.Printf(\"\\n\\n\")\n\n}\n<commit_msg>Bug fix<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\t\"container\/list\"\n\tjs \"encoding\/json\"\n\n\t\"github.com\/kurrik\/oauth1a\"\n\t\"github.com\/codingneo\/twittergo\"\n\t\"github.com\/kurrik\/json\"\n\t\"github.com\/robfig\/cron\"\n\t\/\/\"github.com\/PuerkitoBio\/goquery\"\n\t\"github.com\/advancedlogic\/GoOse\"\n\t\"github.com\/codingneo\/tweetsbot\/ranking\"\n)\n\n\nfunc LoadCredentials() (client *twittergo.Client, err error) {\n\tcredentials, err := ioutil.ReadFile(\"CREDENTIALS\")\n\tif err != nil {\n\t\treturn\n\t}\n\tlines := strings.Split(string(credentials), \"\\n\")\n\tconfig := &oauth1a.ClientConfig{\n\t\tConsumerKey:    lines[0],\n\t\tConsumerSecret: lines[1],\n\t}\n\tuser := oauth1a.NewAuthorizedConfig(lines[2], lines[3])\n\tclient = twittergo.NewClient(config, user, \"stream.twitter.com\")\n\treturn\n}\n\ntype Args struct {\n\tTrack string\n\tLang string\n}\n\nfunc parseArgs() *Args {\n\ta := &Args{}\n\tflag.StringVar(&a.Track, \"track\", \"Data Science,Big Data\", \"Keyword to look up\")\n\tflag.StringVar(&a.Lang, \"lang\", \"en\", \"Language to look up\")\n\tflag.Parse()\n\treturn a\n}\n\ntype streamConn struct {\n\tclient   *http.Client\n\tresp     *http.Response\n\turl      *url.URL\n\tstale    bool\n\tclosed   bool\n\tmu       sync.Mutex\n\t\/\/ wait time before trying to reconnect, this will be\n\t\/\/ exponentially moved up until reaching maxWait, when\n\t\/\/ it will exit\n\twait    int\n\tmaxWait int\n\tconnect func() (*http.Response, error)\n}\n\nfunc NewStreamConn(max int) streamConn {\n\treturn streamConn{wait: 1, maxWait: max}\n}\n\nfunc (conn *streamConn) Close() {\n\t\/\/ Just mark the connection as stale, and let the connect() handler close after a read\n\tconn.mu.Lock()\n\tdefer conn.mu.Unlock()\n\tconn.stale = true\n\tconn.closed = true\n\tif conn.resp != nil {\n\t\tconn.resp.Body.Close()\n\t}\n}\n\nfunc (conn *streamConn) isStale() bool {\n\tconn.mu.Lock()\n\tr := conn.stale\n\tconn.mu.Unlock()\n\treturn r\n}\n\nfunc readStream(client *twittergo.Client, sc streamConn, path string, query url.Values, \n\t\t\t\tresp *twittergo.APIResponse, handler func([]byte), done chan bool) {\n\n\tvar reader *bufio.Reader\n\treader = bufio.NewReader(resp.Body)\n\n\tfor {\n\t\t\/\/we've been closed\n\t\tif sc.isStale() {\n\t\t\tsc.Close()\n\t\t\tfmt.Println(\"Connection closed, shutting down \")\n\t\t\tbreak\n\t\t}\n\n\t\tline, err := reader.ReadBytes('\\n')\n\n\t\tif err != nil {\n\t\t\tif sc.isStale() {\n\t\t\t\tfmt.Println(\"conn stale, continue\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttime.Sleep(time.Second * time.Duration(sc.wait))\n\t\t\t\/\/try reconnecting, but exponentially back off until MaxWait is reached then exit?\n\t\t\tresp, err := Connect(client, path, query)\n\t\t\tif err != nil || resp == nil {\n\t\t\t\tfmt.Println(\" Could not reconnect to source? sleeping and will retry \")\n\t\t\t\tif sc.wait < sc.maxWait {\n\t\t\t\t\tsc.wait = sc.wait * 2\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"exiting, max wait reached\")\n\t\t\t\t\tdone <- true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif resp.StatusCode != 200 {\n\t\t\t\tfmt.Printf(\"resp.StatusCode = %d\", resp.StatusCode)\n\t\t\t\tif sc.wait < sc.maxWait {\n\t\t\t\t\tsc.wait = sc.wait * 2\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treader = bufio.NewReader(resp.Body)\n\t\t\tcontinue\n\t\t} else if sc.wait != 1 {\n\t\t\tsc.wait = 1\n\t\t}\n\t\tline = bytes.TrimSpace(line)\n\t\tfmt.Println(\"Received a line \")\n\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\thandler(line)\n\t}\n}\n\nfunc Connect(client *twittergo.Client, path string, query url.Values) (resp *twittergo.APIResponse, err error) {\n\tvar (\n\t\treq \t*http.Request\n\t)\n\n\turl := fmt.Sprintf(\"%v?%v\", path, query.Encode())\n\treq, err = http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Could not parse request: %v\\n\", err)\n\t\treturn\n\t}\n\tresp, err = client.SendRequest(req)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Could not send request: %v\\n\", err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"resp.StatusCode=%d\\n\", resp.StatusCode)\n\treturn\n}\n\nfunc filterStream(client *twittergo.Client, path string, query url.Values) (err error) {\n\tvar (\n\t\tresp    *twittergo.APIResponse\n\t)\n\n\tsc := NewStreamConn(300)\n\n\tresp, err = Connect(client, path, query)\n\n\tdone := make(chan bool)\n\tstream := make(chan []byte, 1000)\n\tgo func() {\n\t\ttopList := list.New()\n\n\t\t\/\/Cron job to store toplist per hour\n\t\tc := cron.New()\n\t\tc.AddFunc(\"0 * * * * *\", \n\t\t\tfunc() { \n\t\t\t\tfmt.Println(\"cron cron cron cron ............................\")\n\t\t\t\tfilename := \".\/data\/toplist-\" + \n\t\t\t\t\t\t\t\t\t\ttime.Now().Local().Format(\"2006-01-02\") +\n\t\t\t\t\t\t\t\t\t\t\".json\"\n\n\t\t\t\toutput := make(map[string]interface{})\n\t\t\t\toutput[\"articles\"] = make([]ranking.Item, 0)\n\n\t\t\t\tf, err := os.OpenFile(filename, os.O_RDWR, 0666)\n\t\t\t\tif (err != nil) {\n\t\t\t\t\tfmt.Println(\"[Cron] File not exist\")\n\t\t\t\t\tf, err = os.Create(filename)\n\t\t\t\t\tif (err != nil) {\n\t\t\t\t\t\tfmt.Println(\"[Cron] File creation error\")\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttlist := make([]ranking.Item, 0)\n\t\t\t\tfor e := topList.Front(); e != nil; e = e.Next() {\n\t\t\t\t\tfmt.Println(\"[Cron] Write url into file\")\n\t\t\t\t\t\/\/f.WriteString(e.Value.(ranking.Item).Url)\n\t\t\t\t\t\/\/f.WriteString(\"\\n\")\n\t\t\t\t\ttlist = append(tlist, e.Value.(ranking.Item))\n\t\t\t\t}\n\t\t\t\toutput[\"articles\"] = tlist\n\n\t\t\t\tjsonstr, _ := js.Marshal(output)\n\t\t\t\tf.WriteString(string(jsonstr))\n\t\t\t\tf.Sync()\n\t\t\t\tf.Close()\n\t\t\t})\n\t\tc.Start()\n\t\tfmt.Println(\"cron job start\")\n\n\t\tg := goose.New()\n\t\tfor data := range stream {\n\t\t\tfmt.Println(string(data))\n\t\t\ttweet := &twittergo.Tweet{}\n\t\t\terr := json.Unmarshal(data, tweet)\n\t\t\tif (err == nil) {\n\t\t\t\tfmt.Printf(\"ID:                   %v\\n\", tweet.Id())\n\t\t\t\tfmt.Printf(\"User:                 %v\\n\", tweet.User().ScreenName())\n\t\t\t\tfmt.Printf(\"Tweet:                %v\\n\", tweet.Text())\n\t\t\t\t\n\t\t\t\trs := tweet.RetweetStatus()\n\t\t\t\tvote := 0\n\t\t\t\tif (rs != nil) {\n\t\t\t\t\tfmt.Printf(\"retweet_count:        %d\\n\", rs.RetweetCount())\n\t\t\t\t\tfmt.Printf(\"favorite_count:        %d\\n\", rs.FavoriteCount())\n\t\t\t\t\tvote += int(rs.RetweetCount()+rs.FavoriteCount())\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\te := tweet.Entities()\n\t\t\t\tif (e != nil) {\n\t\t\t\t\tfmt.Printf(\"url:        %v\\n\", e.FirstUrl().ExpandedUrl())\n\n\t\t\t\t\t\/\/ Form top item\n\t\t\t\t\tif (e.FirstUrl().ExpandedUrl()!=\"\") {\n\t\t\t\t\t\titem := ranking.Item{}\n\t\t\t\t\t\titem.Vote = vote\n\t\t\t\t\t\titem.Url = e.FirstUrl().ExpandedUrl()\n\n\t\t\t\t\t\t\/\/ article extraction\n\t\t\t\t\t\t\/\/doc, err := goquery.NewDocument(item.Url)\n\t\t\t\t\t\tarticle := g.ExtractFromUrl(item.Url)\n\n\t\t\t\t\t\tfmt.Println(\"title\", article.Title)\n    \t\t\t\tfmt.Println(\"description\", article.MetaDescription)\n    \t\t\t\tfmt.Println(\"top image\", article.TopImage)\n\n    \t\t\t\tif (article.Title != \"\") && \n    \t\t\t\t\t (article.MetaDescription != \"\") {\n\t\t\t\t\t\t\titem.Title = article.Title\n    \t\t\t\t\titem.Description = article.MetaDescription\n    \t\t\t\t\titem.Image = article.TopImage\n\n    \t\t\t\t\tranking.Insert(topList, item)\n    \t\t\t\t}\n\n\t\t\t\t\t\t\/\/if err == nil {\n\t\t\t\t\t\t\/\/\titem.Title = doc.Find(\"title\").Text()\n\t\t\t\t\t\t\/\/\tfmt.Printf(\"title:        %v\\n\", item.Title)\n\t\t\t\t\t\t\/\/\tranking.Insert(topList, item)\n\t\t\t\t\t\t\/\/}\n\n\t\t\t\t\t\tfmt.Println(\"**********************************\")\n\t\t\t\t\t\tfor e := topList.Front(); e != nil; e = e.Next() {\n\t\t\t\t\t\t\tfmt.Printf(\"%d: %v\\n\",e.Value.(ranking.Item).Vote, e.Value.(ranking.Item).Url)\n\t\t\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\treadStream(client, sc, path, query, resp, func(line []byte) {\n\t\tstream <- line}, done)\n\n\n\treturn\n}\n\nfunc main() {\n\tvar (\n\t\terr    error\n\t\targs   *Args\n\t\tclient *twittergo.Client\n\t)\n\n\targs = parseArgs()\n\tif client, err = LoadCredentials(); err != nil {\n\t\tfmt.Printf(\"Could not parse CREDENTIALS file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tfmt.Println(args.Track)\n\tquery := url.Values{}\n\tquery.Set(\"track\", args.Track)\n\tquery.Set(\"lang\", args.Lang)\n\n\tfmt.Println(\"Printing everything about data science:\")\n\tfmt.Printf(\"=========================================================\\n\")\n\tif err = filterStream(client, \"\/1.1\/statuses\/filter.json\", query); err != nil {\n\t\tfmt.Println(\"Error: %v\\n\", err)\n\t}\n\tfmt.Printf(\"\\n\\n\")\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"sort\"\n\n\t\"image\"\n\t\"image\/draw\"\n\t\"image\/png\"\n)\n\ntype Size struct {\n\tx, y int\n}\n\ntype sprite struct {\n\tname string\n\timg  image.Image\n\trect image.Rectangle\n\tarea int\n\tsize Size\n}\n\ntype ByArea []sprite\n\nfunc (a ByArea) Len() int           { return len(a) }\nfunc (a ByArea) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a ByArea) Less(i, j int) bool { return a[i].area < a[j].area }\n\nfunc main() {\n\tflag.Parse()\n\n\targs := flag.Args()\n\n\tinputDir := args[0]\n\n\tfiles, _ := ioutil.ReadDir(inputDir)\n\tsprites := make([]sprite, len(files))\n\n\ttotalX := 0\n\ttotalY := 0\n\n\tfor i := range sprites {\n\t\ts := readSprite(inputDir, files[i].Name())\n\t\tsprites[i] = s\n\t\ttotalX += s.size.x\n\t\ttotalY += s.size.y\n\t}\n\n\t\/\/ we want to place the largest sprite first\n\tsort.Sort(sort.Reverse(ByArea(sprites)))\n\n\t\/\/ the final image\n\tdst := image.NewRGBA(image.Rect(0, 0, 1024, 1024))\n\n\tfor i := range sprites {\n\t\ts := &sprites[i]\n\t\tdraw.Draw(dst, s.rect, s.img, image.ZP, draw.Src)\n\t}\n\n\twriter, err := os.Create(\"test.png\")\n\terr = png.Encode(writer, dst)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc readSprite(dir, name string) (s sprite) {\n\tpath := path.Join(dir, name)\n\treader, err := os.Open(path)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer reader.Close()\n\n\timg, err := png.Decode(reader)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ts.name = name\n\ts.img = img\n\ts.rect = img.Bounds()\n\ts.size = Size{s.rect.Dx(), s.rect.Dy()}\n\ts.area = s.size.x * s.size.y\n\treturn\n}\n<commit_msg>Broken packer tree<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"sort\"\n\n\t\"image\"\n\t\"image\/draw\"\n\t\"image\/png\"\n)\n\ntype Size struct {\n\tx, y int\n}\n\nfunc (a Size) Equal(b Size) bool {\n\treturn a.x == b.x && a.y == b.y\n}\n\nfunc (a Size) Larger(b Size) bool {\n\treturn b.x < a.x && b.y < a.y\n}\n\nfunc (a Size) Smaller(b Size) bool {\n\treturn !a.Larger(b)\n}\n\ntype sprite struct {\n\tname string\n\timg  image.Image\n\trect image.Rectangle\n\tarea int\n\tsize Size\n}\n\ntype ByArea []sprite\n\nfunc (a ByArea) Len() int           { return len(a) }\nfunc (a ByArea) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a ByArea) Less(i, j int) bool { return a[i].area < a[j].area }\n\ntype Node struct {\n\tchild [2]*Node\n\trect  image.Rectangle\n\timg   *sprite\n}\n\nfunc (n *Node) size() Size {\n\treturn Size{n.rect.Dx(), n.rect.Dy()}\n}\n\nfunc (n *Node) print() {\n\tfmt.Println(n)\n\tif n.child[0] != nil {\n\t\tn.child[0].print()\n\t}\n\tif n.child[1] != nil {\n\t\tn.child[1].print()\n\t}\n}\n\nfunc (n *Node) insert(img *sprite) bool {\n\t\/\/ there is already an image in this node\n\tif n.img != nil {\n\t\tfmt.Println(\"already contains an image\")\n\t\treturn false\n\t}\n\n\t\/\/ try to insert into either of the nodes children\n\tif n.child[0] != nil {\n\t\tfmt.Println(\"has a 0 child\")\n\t\tin := n.child[0].insert(img)\n\n\t\tif in {\n\t\t\treturn true\n\t\t} else {\n\t\t\tfmt.Println(\"has a 1 child\")\n\t\t\treturn n.child[1].insert(img)\n\t\t}\n\t}\n\n\tif n.rect.Dx() < img.size.x || n.rect.Dy() < img.size.y {\n\t\tfmt.Println(\"space too small\")\n\t\treturn false\n\t}\n\n\tif n.rect.Dx() == img.size.x && n.rect.Dy() == img.size.y {\n\t\tfmt.Println(\"prefect fit\")\n\t\tn.img = img\n\t\treturn true\n\t}\n\n\tif n.rect.Dx() >= img.size.x && n.rect.Dy() >= img.size.y {\n\t\tfmt.Println(\"Split\")\n\t\tn.split(img)\n\t}\n\n\treturn n.insert(img)\n\n}\n\nfunc (n *Node) split(img *sprite) {\n\tvar tl0 image.Point\n\tvar br0 image.Point\n\n\tvar tl1 image.Point\n\tvar br1 image.Point\n\n\tdx := n.size().x - img.size.x\n\tdy := n.size().y - img.size.y\n\n\trc := n.rect\n\n\ttl0 = rc.Min\n\tbr1 = rc.Max\n\n\tif dx > dy {\n\t\tfmt.Println(\"split on x\")\n\t\tbr0 = image.Point{rc.Min.X + img.size.x, rc.Dy()}\n\t\ttl1 = image.Point{rc.Min.X + img.size.x - 1, rc.Min.Y}\n\t} else {\n\t\tfmt.Println(\"split on y\")\n\t\tbr0 = image.Point{rc.Dx(), rc.Min.Y + img.size.y}\n\t\ttl1 = image.Point{rc.Min.X, rc.Min.Y + img.size.y - 1}\n\t}\n\n\trect0 := image.Rectangle{tl0, br0}\n\tn.child[0] = &Node{rect: rect0}\n\n\trect1 := image.Rectangle{tl1, br1}\n\tn.child[1] = &Node{rect: rect1}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\targs := flag.Args()\n\n\tinputDir := args[0]\n\n\tfiles, _ := ioutil.ReadDir(inputDir)\n\tsprites := make([]sprite, len(files))\n\n\ttotalX := 0\n\ttotalY := 0\n\n\tfor i := range sprites {\n\t\ts := readSprite(inputDir, files[i].Name())\n\t\tsprites[i] = s\n\t\ttotalX += s.size.x\n\t\ttotalY += s.size.y\n\t}\n\n\t\/\/ we want to place the largest sprite first\n\tsort.Sort(sort.Reverse(ByArea(sprites)))\n\n\t\/\/ the final image\n\tdst := image.NewRGBA(image.Rect(0, 0, 2048, 2048))\n\n\tn := Node{rect: image.Rect(0, 0, 1024, 1024)}\n\n\tfor i := range sprites {\n\t\ts := &sprites[i]\n\t\tfmt.Printf(\"inserting %s\\n\", s.name)\n\t\tn.insert(s)\n\t\tdraw.Draw(dst, s.rect, s.img, image.ZP, draw.Src)\n\t}\n\n\tn.print()\n\n\twriter, err := os.Create(\"test.png\")\n\terr = png.Encode(writer, dst)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc readSprite(dir, name string) (s sprite) {\n\tpath := path.Join(dir, name)\n\treader, err := os.Open(path)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer reader.Close()\n\n\timg, err := png.Decode(reader)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ts.name = name\n\ts.img = img\n\ts.rect = img.Bounds()\n\ts.size = Size{s.rect.Dx(), s.rect.Dy()}\n\ts.area = s.size.x * s.size.y\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package heartbeater\n\nimport (\n\t\"errors\"\n\t\"math\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry\/storeadapter\"\n\t\"github.com\/pivotal-golang\/clock\"\n\t\"github.com\/pivotal-golang\/lager\"\n)\n\nvar (\n\tErrLockFailed       = errors.New(\"failed to compare and swap\")\n\tErrStoreUnavailable = errors.New(\"failed to connect to etcd\")\n)\n\ntype Heartbeater struct {\n\tclient   storeadapter.StoreAdapter\n\tkey      string\n\tvalue    string\n\tinterval time.Duration\n\tlogger   lager.Logger\n\n\tclock clock.Clock\n}\n\nfunc New(\n\tetcdClient storeadapter.StoreAdapter,\n\tclock clock.Clock,\n\theartbeatKey string,\n\theartbeatValue string,\n\theartbeatInterval time.Duration,\n\tlogger lager.Logger,\n) Heartbeater {\n\treturn Heartbeater{\n\t\tclient:   etcdClient,\n\t\tclock:    clock,\n\t\tkey:      heartbeatKey,\n\t\tvalue:    heartbeatValue,\n\t\tinterval: heartbeatInterval,\n\t\tlogger:   logger,\n\t}\n}\n\nfunc (h Heartbeater) Run(signals <-chan os.Signal, ready chan<- struct{}) error {\n\tlogger := h.logger.Session(\"heartbeat\", lager.Data{\"key\": h.key, \"value\": h.value})\n\n\tttl := uint64(math.Ceil((h.interval * 2).Seconds()))\n\n\tnode := storeadapter.StoreNode{\n\t\tKey:   h.key,\n\t\tValue: []byte(h.value),\n\t\tTTL:   ttl,\n\t}\n\n\tif h.acquireHeartbeat(logger, node, ttl, signals) {\n\t\tclose(ready)\n\n\t\treturn h.maintainHeartbeat(logger, node, ttl, signals)\n\t}\n\n\treturn nil\n}\n\nfunc (h Heartbeater) acquireHeartbeat(logger lager.Logger, node storeadapter.StoreNode, ttl uint64, signals <-chan os.Signal) bool {\n\tlogger.Info(\"starting\")\n\n\terr := h.client.CompareAndSwap(node, node)\n\tif err != nil {\n\t\tvar stopWatch chan<- bool\n\t\tvar watchEvents <-chan storeadapter.WatchEvent\n\t\tvar watchErrors <-chan error\n\n\t\twatchEvents, stopWatch, watchErrors = h.client.Watch(h.key)\n\t\tdefer close(stopWatch)\n\n\t\tintervalTimer := h.clock.NewTimer(0)\n\t\tdefer intervalTimer.Stop()\n\n\tWATCH:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-watchEvents:\n\t\t\t\tif !(event.Type == storeadapter.DeleteEvent || event.Type == storeadapter.ExpireEvent) {\n\t\t\t\t\tcontinue WATCH\n\t\t\t\t}\n\t\t\tcase <-intervalTimer.C():\n\t\t\tcase <-watchErrors:\n\t\t\t\twatchEvents, stopWatch, watchErrors = h.client.Watch(h.key)\n\t\t\t\tcontinue WATCH\n\t\t\tcase <-signals:\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\terr := h.client.Create(node)\n\t\t\tif err == nil {\n\t\t\t\tlogger.Info(\"created-node\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tintervalTimer.Reset(h.interval)\n\t\t}\n\t}\n\n\tlogger.Info(\"started\")\n\treturn true\n}\n\nfunc (h Heartbeater) maintainHeartbeat(logger lager.Logger, node storeadapter.StoreNode, ttl uint64, signals <-chan os.Signal) error {\n\tvar connectionTimer clock.Timer\n\tvar connectionTimeout <-chan time.Time\n\n\tintervalTimer := h.clock.NewTimer(h.interval)\n\tdefer intervalTimer.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase sig := <-signals:\n\t\t\tlogger.Info(\"received-shutdown-signal\")\n\t\t\tswitch sig {\n\t\t\tcase os.Kill:\n\t\t\t\treturn nil\n\t\t\tdefault:\n\t\t\t\th.client.CompareAndDelete(node)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\tcase <-connectionTimeout:\n\t\t\tlogger.Info(\"connection-timed-out\")\n\t\t\treturn ErrStoreUnavailable\n\n\t\tcase <-intervalTimer.C():\n\t\t\terr := h.client.CompareAndSwap(node, node)\n\t\t\tswitch err {\n\t\t\tcase storeadapter.ErrorTimeout:\n\t\t\t\tlogger.Error(\"store-timeout\", err)\n\t\t\t\tif connectionTimeout == nil {\n\t\t\t\t\tconnectionTimer = h.clock.NewTimer(time.Duration(ttl) * time.Second)\n\t\t\t\t\tconnectionTimeout = connectionTimer.C()\n\t\t\t\t}\n\t\t\tcase storeadapter.ErrorKeyNotFound:\n\t\t\t\terr = h.client.Create(node)\n\t\t\t\tif err != nil && connectionTimeout == nil {\n\t\t\t\t\tconnectionTimer = h.clock.NewTimer(time.Duration(ttl) * time.Second)\n\t\t\t\t\tconnectionTimeout = connectionTimer.C()\n\t\t\t\t}\n\t\t\tcase nil:\n\t\t\t\tif connectionTimeout != nil {\n\t\t\t\t\tconnectionTimer.Stop()\n\t\t\t\t\tconnectionTimeout = nil\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlogger.Error(\"compare-and-swap-failed\", err)\n\t\t\t\treturn ErrLockFailed\n\t\t\t}\n\t\t\tintervalTimer.Reset(h.interval)\n\t\t}\n\t}\n}\n<commit_msg>Add debug logging to heartbeater [#89826352]<commit_after>package heartbeater\n\nimport (\n\t\"errors\"\n\t\"math\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry\/storeadapter\"\n\t\"github.com\/pivotal-golang\/clock\"\n\t\"github.com\/pivotal-golang\/lager\"\n)\n\nvar (\n\tErrLockFailed       = errors.New(\"failed to compare and swap\")\n\tErrStoreUnavailable = errors.New(\"failed to connect to etcd\")\n)\n\ntype Heartbeater struct {\n\tclient storeadapter.StoreAdapter\n\tkey    string\n\tvalue  string\n\n\tkeyCreateRetryInterval time.Duration\n\tkeyHeartbeatInterval   time.Duration\n\tkeyTTL                 uint64\n\tclock                  clock.Clock\n\n\tlogger lager.Logger\n}\n\nfunc New(\n\tetcdClient storeadapter.StoreAdapter,\n\tclock clock.Clock,\n\theartbeatKey string,\n\theartbeatValue string,\n\theartbeatInterval time.Duration,\n\tlogger lager.Logger,\n) Heartbeater {\n\treturn Heartbeater{\n\t\tclient: etcdClient,\n\t\tkey:    heartbeatKey,\n\t\tvalue:  heartbeatValue,\n\n\t\tkeyCreateRetryInterval: heartbeatInterval,\n\t\tkeyHeartbeatInterval:   heartbeatInterval,\n\t\tkeyTTL:                 uint64(math.Ceil((heartbeatInterval * 2).Seconds())),\n\t\tclock:                  clock,\n\n\t\tlogger: logger,\n\t}\n}\n\nfunc (h Heartbeater) Run(signals <-chan os.Signal, ready chan<- struct{}) error {\n\tlogger := h.logger.Session(\"heartbeat\", lager.Data{\"key\": h.key, \"value\": h.value})\n\n\tnode := storeadapter.StoreNode{\n\t\tKey:   h.key,\n\t\tValue: []byte(h.value),\n\t\tTTL:   h.keyTTL,\n\t}\n\n\tif h.acquireHeartbeat(logger, node, signals) {\n\t\tclose(ready)\n\n\t\treturn h.maintainHeartbeat(logger, node, signals)\n\t}\n\n\treturn nil\n}\n\nfunc (h Heartbeater) acquireHeartbeat(logger lager.Logger, node storeadapter.StoreNode, signals <-chan os.Signal) bool {\n\tlogger.Info(\"starting\")\n\n\terr := h.client.CompareAndSwap(node, node)\n\tif err != nil {\n\t\tvar stopWatch chan<- bool\n\t\tvar watchEvents <-chan storeadapter.WatchEvent\n\t\tvar watchErrors <-chan error\n\n\t\twatchEvents, stopWatch, watchErrors = h.client.Watch(h.key)\n\t\tdefer close(stopWatch)\n\n\t\tintervalTimer := h.clock.NewTimer(0)\n\t\tdefer intervalTimer.Stop()\n\n\tWATCH:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-watchEvents:\n\t\t\t\tif !(event.Type == storeadapter.DeleteEvent || event.Type == storeadapter.ExpireEvent) {\n\t\t\t\t\tcontinue WATCH\n\t\t\t\t}\n\t\t\tcase <-intervalTimer.C():\n\t\t\tcase <-watchErrors:\n\t\t\t\twatchEvents, stopWatch, watchErrors = h.client.Watch(h.key)\n\t\t\t\tcontinue WATCH\n\t\t\tcase <-signals:\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\terr := h.client.Create(node)\n\t\t\tif err == nil {\n\t\t\t\tlogger.Info(\"created-node\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tintervalTimer.Reset(h.keyCreateRetryInterval)\n\t\t}\n\t}\n\n\tlogger.Info(\"started\")\n\treturn true\n}\n\nfunc (h Heartbeater) maintainHeartbeat(logger lager.Logger, node storeadapter.StoreNode, signals <-chan os.Signal) error {\n\tvar connectionTimer clock.Timer\n\tvar connectionTimeout <-chan time.Time\n\n\tintervalTimer := h.clock.NewTimer(h.keyHeartbeatInterval)\n\tdefer intervalTimer.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase sig := <-signals:\n\t\t\tlogger.Info(\"received-shutdown-signal\")\n\t\t\tswitch sig {\n\t\t\tcase os.Kill:\n\t\t\t\treturn nil\n\t\t\tdefault:\n\t\t\t\th.client.CompareAndDelete(node)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\tcase <-connectionTimeout:\n\t\t\tlogger.Info(\"connection-timed-out\")\n\t\t\treturn ErrStoreUnavailable\n\n\t\tcase <-intervalTimer.C():\n\t\t\tlogger.Debug(\"compare-and-swapping\")\n\t\t\terr := h.client.CompareAndSwap(node, node)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(\"failed-compare-and-swapping\", err)\n\t\t\t} else {\n\t\t\t\tlogger.Debug(\"succeeded-compare-and-swapping\")\n\t\t\t}\n\t\t\tswitch err {\n\t\t\tcase storeadapter.ErrorTimeout:\n\t\t\t\tif connectionTimeout == nil {\n\t\t\t\t\tconnectionTimer = h.clock.NewTimer(time.Duration(h.keyTTL) * time.Second)\n\t\t\t\t\tconnectionTimeout = connectionTimer.C()\n\t\t\t\t}\n\t\t\tcase storeadapter.ErrorKeyNotFound:\n\t\t\t\tlogger.Debug(\"re-creating-node\")\n\t\t\t\terr = h.client.Create(node)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(\"failed-re-creating-node\", err)\n\t\t\t\t} else {\n\t\t\t\t\tlogger.Debug(\"succeeded-re-creating-node\")\n\t\t\t\t}\n\t\t\t\tif err != nil && connectionTimeout == nil {\n\t\t\t\t\tconnectionTimer = h.clock.NewTimer(time.Duration(h.keyTTL) * time.Second)\n\t\t\t\t\tconnectionTimeout = connectionTimer.C()\n\t\t\t\t}\n\t\t\tcase nil:\n\t\t\t\tif connectionTimeout != nil {\n\t\t\t\t\tconnectionTimer.Stop()\n\t\t\t\t\tconnectionTimeout = nil\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn ErrLockFailed\n\t\t\t}\n\t\t\tintervalTimer.Reset(h.keyHeartbeatInterval)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ 7 february 2014\npackage main\n\nimport (\n\t\"fmt\"\n\t\"syscall\"\n\t\"unsafe\"\n)\n\n\/\/ MessageBox button types.\nconst (\n\t_MB_ABORTRETRYIGNORE = 0x00000002\n\t_MB_CANCELTRYCONTINUE = 0x00000006\n\t_MB_HELP = 0x00004000\n\t_MB_OK = 0x00000000\n\t_MB_OKCANCEL = 0x00000001\n\t_MB_RETRYCANCEL = 0x00000005\n\t_MB_YESNO = 0x00000004\n\t_MB_YESNOCANCEL = 0x00000003\n)\n\n\/\/ MessageBox icon types.\nconst (\n\t_MB_ICONEXCLAMATION = 0x00000030\n\t_MB_ICONWARNING = 0x00000030\n\t_MB_ICONINFORMATION = 0x00000040\n\t_MB_ICONASTERISK = 0x00000040\n\t_MB_ICONQUESTION = 0x00000020\n\t_MB_ICONSTOP = 0x00000010\n\t_MB_ICONERROR = 0x00000010\n\t_MB_ICONHAND = 0x00000010\n)\n\n\/\/ MessageBox default button types.\nconst (\n\t_MB_DEFBUTTON1 = 0x00000000\n\t_MB_DEFBUTTON2 = 0x00000100\n\t_MB_DEFBUTTON3 = 0x00000200\n\t_MB_DEFBUTTON4 = 0x00000300\n)\n\n\/\/ MessageBox modality types.\nconst (\n\t_MB_APPLMODAL = 0x00000000\n\t_MB_SYSTEMMODAL = 0x00001000\n\t_MB_TASKMODAL = 0x00002000\n)\n\n\/\/ MessageBox miscellaneous types.\nconst (\n\t_MB_DEFAULT_DESKTOP_ONLY = 0x00020000\n\t_MB_RIGHT = 0x00080000\n\t_MB_RTLREADING = 0x00100000\n\t_MB_SETFOREGROUND = 0x00010000\n\t_MB_TOPMOST = 0x00040000\n\t_MB_SERVICE_NOTIFICATION = 0x00200000\n)\n\n\/\/ MessageBox return values.\nconst (\n\t_IDABORT = 3\n\t_IDCANCEL = 2\n\t_IDCONTINUE = 11\n\t_IDIGNORE = 5\n\t_IDNO = 7\n\t_IDOK = 1\n\t_IDRETRY = 4\n\t_IDTRYAGAIN = 10\n\t_IDYES = 6\n)\n\nvar (\n\t_messageBox = user32.NewProc(\"MessageBoxW\")\n)\n\nfunc msgBox(lpText string, lpCaption string, uType uint32) (result int) {\n\tr1, _, err := _messageBox.Call(\n\t\tuintptr(_NULL),\n\t\tuintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(lpText))),\n\t\tuintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(lpCaption))),\n\t\tuintptr(uType))\n\tif r1 == 0 {\t\t\/\/ failure\n\t\tpanic(fmt.Sprintf(\"error displaying message box to user: %v\\nstyle: 0x%08X\\ntitle: %q\\ntext:\\n%s\", err, uType, lpCaption, lpText))\n\t}\n\treturn int(r1)\n}\n\n\/\/ MsgBox displays an informational message box to the user with just an OK button.\nfunc MsgBox(title string, textfmt string, args ...interface{}) {\n\t\/\/ TODO add an icon?\n\tmsgBox(fmt.Sprintf(textfmt, args...), title, _MB_OK)\n}\n\n\/\/ MsgBoxError displays a message box to the user with just an OK button and an icon indicating an error.\nfunc MsgBoxError(title string, textfmt string, args ...interface{}) {\n\t\/\/ TODO add an icon?\n\tmsgBox(fmt.Sprintf(textfmt, args...), title, _MB_OK | _MB_ERROR)\n}\n<commit_msg>Fixed a build error in the previous commit.<commit_after>\/\/ 7 february 2014\npackage main\n\nimport (\n\t\"fmt\"\n\t\"syscall\"\n\t\"unsafe\"\n)\n\n\/\/ MessageBox button types.\nconst (\n\t_MB_ABORTRETRYIGNORE = 0x00000002\n\t_MB_CANCELTRYCONTINUE = 0x00000006\n\t_MB_HELP = 0x00004000\n\t_MB_OK = 0x00000000\n\t_MB_OKCANCEL = 0x00000001\n\t_MB_RETRYCANCEL = 0x00000005\n\t_MB_YESNO = 0x00000004\n\t_MB_YESNOCANCEL = 0x00000003\n)\n\n\/\/ MessageBox icon types.\nconst (\n\t_MB_ICONEXCLAMATION = 0x00000030\n\t_MB_ICONWARNING = 0x00000030\n\t_MB_ICONINFORMATION = 0x00000040\n\t_MB_ICONASTERISK = 0x00000040\n\t_MB_ICONQUESTION = 0x00000020\n\t_MB_ICONSTOP = 0x00000010\n\t_MB_ICONERROR = 0x00000010\n\t_MB_ICONHAND = 0x00000010\n)\n\n\/\/ MessageBox default button types.\nconst (\n\t_MB_DEFBUTTON1 = 0x00000000\n\t_MB_DEFBUTTON2 = 0x00000100\n\t_MB_DEFBUTTON3 = 0x00000200\n\t_MB_DEFBUTTON4 = 0x00000300\n)\n\n\/\/ MessageBox modality types.\nconst (\n\t_MB_APPLMODAL = 0x00000000\n\t_MB_SYSTEMMODAL = 0x00001000\n\t_MB_TASKMODAL = 0x00002000\n)\n\n\/\/ MessageBox miscellaneous types.\nconst (\n\t_MB_DEFAULT_DESKTOP_ONLY = 0x00020000\n\t_MB_RIGHT = 0x00080000\n\t_MB_RTLREADING = 0x00100000\n\t_MB_SETFOREGROUND = 0x00010000\n\t_MB_TOPMOST = 0x00040000\n\t_MB_SERVICE_NOTIFICATION = 0x00200000\n)\n\n\/\/ MessageBox return values.\nconst (\n\t_IDABORT = 3\n\t_IDCANCEL = 2\n\t_IDCONTINUE = 11\n\t_IDIGNORE = 5\n\t_IDNO = 7\n\t_IDOK = 1\n\t_IDRETRY = 4\n\t_IDTRYAGAIN = 10\n\t_IDYES = 6\n)\n\nvar (\n\t_messageBox = user32.NewProc(\"MessageBoxW\")\n)\n\nfunc msgBox(lpText string, lpCaption string, uType uint32) (result int) {\n\tr1, _, err := _messageBox.Call(\n\t\tuintptr(_NULL),\n\t\tuintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(lpText))),\n\t\tuintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(lpCaption))),\n\t\tuintptr(uType))\n\tif r1 == 0 {\t\t\/\/ failure\n\t\tpanic(fmt.Sprintf(\"error displaying message box to user: %v\\nstyle: 0x%08X\\ntitle: %q\\ntext:\\n%s\", err, uType, lpCaption, lpText))\n\t}\n\treturn int(r1)\n}\n\n\/\/ MsgBox displays an informational message box to the user with just an OK button.\nfunc MsgBox(title string, textfmt string, args ...interface{}) {\n\t\/\/ TODO add an icon?\n\tmsgBox(fmt.Sprintf(textfmt, args...), title, _MB_OK)\n}\n\n\/\/ MsgBoxError displays a message box to the user with just an OK button and an icon indicating an error.\nfunc MsgBoxError(title string, textfmt string, args ...interface{}) {\n\t\/\/ TODO add an icon?\n\tmsgBox(fmt.Sprintf(textfmt, args...), title, _MB_OK | _MB_ICONERROR)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"os\"\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\t\"strings\"\n\t\"strconv\"\n\t\"text\/template\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"google.golang.org\/api\/appengine\/v1beta4\"\n\t\"google.golang.org\/api\/storage\/v1\"\n)\n\nfunc resourceAppengine() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAppengineCreate,\n\t\tRead:   resourceAppengineRead,\n\t\tDelete: resourceAppengineDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"moduleName\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"version\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"gstorageBucket\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"gstorageKey\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"scaling\": &schema.Schema{\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"minIdleInstances\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeInt,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tDefault:  \"1\",\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"maxIdleInstances\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeInt,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tDefault: \"3\",\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"minPendingLatency\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tDefault: \"Automatic\",\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"maxPendingLatency\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tDefault: \"Automatic\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"topicName\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"servingStatus\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nvar (\n\tremoteBase = \"https:\/\/storage.googleapis.com\/\"\n)\n\n\nfunc urlHandlers() ([]*appengine.UrlMap) {\n\thandlers := make([]*appengine.UrlMap, 0)\n\t\thandlers = append(handlers, &appengine.UrlMap{\n\t\t\tSecurityLevel: \"SECURE_OPTIONAL\",\n\t\t\tLogin: \"LOGIN_OPTIONAL\",\n\t\t\tUrlRegex:\"\/\", \n\t\t\tScript:&appengine.ScriptHandler{\n\t\t\t\tScriptPath:\"unused\",\n\t\t\t},\n\t\t})\n\t\thandlers = append(handlers, &appengine.UrlMap{\n\t\t\tSecurityLevel: \"SECURE_OPTIONAL\",\n\t\t\tLogin: \"LOGIN_OPTIONAL\",\n\t\t\tUrlRegex:\"\/.*\/\", \n\t\t\tScript:&appengine.ScriptHandler{\n\t\t\t\tScriptPath:\"unused\",\n\t\t\t},\n\t\t})\n\t\thandlers = append(handlers, &appengine.UrlMap{\n\t\t\tSecurityLevel: \"SECURE_OPTIONAL\",\n\t\t\tLogin: \"LOGIN_OPTIONAL\",\n\t\t\tUrlRegex:\"\/_ah\/.*\", \n\t\t\tScript:&appengine.ScriptHandler{\n\t\t\t\tScriptPath:\"unused\",\n\t\t\t},\n\t\t})\n\t\thandlers = append(handlers, &appengine.UrlMap{\n\t\t\tSecurityLevel: \"SECURE_OPTIONAL\",\n\t\t\tLogin: \"LOGIN_OPTIONAL\",\n\t\t\tUrlRegex:\"\/endpoint\", \n\t\t\tScript:&appengine.ScriptHandler{\n\t\t\t\tScriptPath:\"unused\",\n\t\t\t},\n\t\t})\n\t\t\n\t\treturn handlers\n}\n\n\n\/\/ known issues with this function:\n\/\/   assumes \"\/\" is delimiter in gstorage and forces that to be last char in key\n\/\/   only searches first page, if more then 1k files to load, will only grab first 1k\nfunc generateFileList(d *schema.ResourceData, config *Config) (map[string]appengine.FileInfo, error) {\n\tlistService := storage.NewObjectsService(config.clientStorage)\n\tbucket := d.Get(\"gstorageBucket\").(string)\n\tlistCall := listService.List(bucket)\n\tkey := d.Get(\"gstorageKey\").(string)\n\tlastChar := key[len(key)-1:]\n\tif lastChar != \"\/\" {\n\t\tkey = key + \"\/\"\n\t}\n\tlistCall = listCall.Prefix(key)\n\tobjs, err := listCall.Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\n\tfiles := make(map[string]appengine.FileInfo)\n\tfor _, obj := range objs.Items {\n\t\tonDiskName := strings.Replace(obj.Name, key, \"\", 1)  \/\/ trims key from file name\n\t\tinCloudURL := remoteBase + bucket + \"\/\" + obj.Name\n\t\tfiles[onDiskName] = appengine.FileInfo{SourceUrl:inCloudURL} \n\t}\n\t\n\treturn files, nil\n}\n\nfunc renderAppengineXML(d  *schema.ResourceData, config *Config) (error) {\n\ttype AppengineXmlData struct {\n\t\tProject\t\t\tstring\n\t\tSourceVersion\tstring\n\t\tModule\t\t\tstring\n\t\tTopicName\t\tstring\n\t}\n\t\n\taxd := AppengineXmlData{\n\t\tProject: config.Project,\n\t\tSourceVersion: d.Get(\"version\").(string),\n\t\tModule: d.Get(\"moduleName\").(string),\n\t\tTopicName: d.Get(\"topicName\").(string),\n\t}\n\t\n\ttempl, err := template.New(\"appengine-web.xml.template\").Parse(axdTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\taxdRendered, err := os.Create(\"appengine-web.xml\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer axdRendered.Close()\n\terr = templ.Execute(axdRendered, axd)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\treturn nil\n}\n\nfunc pushAppengineXmlToCloud(d *schema.ResourceData, config *Config) (error) {\n\tkey := d.Get(\"gstorageKey\").(string)\n\tlastChar := key[len(key)-1:]\n\tif lastChar != \"\/\" {\n\t\tkey = key + \"\/\"\n\t}\n\tkey = key + \"WEB-INF\/appengine-web.xml\"\n\tobject := &storage.Object{Name: key}\n    file, err := os.Open(\"appengine-web.xml\")\n    if err != nil {\n    \tfmt.Errorf(\"Error opening %q: %v\", \"appengine.xml\", err)\n    }\n\tobjectService := storage.NewObjectsService(config.clientStorage)\n\t_, err = objectService.Insert(d.Get(\"gstorageBucket\").(string), object).Media(file).Do()\n    if err != nil {\n        fmt.Errorf(\"Objects.Insert failed: %v\", err)\n    }\n\n\treturn nil\n}\n\nfunc renderAppengineXMLToCloud(d *schema.ResourceData, config *Config) (error) {\n\terr := renderAppengineXML(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\terr = pushAppengineXmlToCloud(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\treturn nil\n}\n\nfunc validateLatency(latency string) (string, error) {\n\tlastChar := latency[len(latency)-1:]\n\tif lastChar != \"s\" {\n\t\treturn \"\", fmt.Errorf(\"latency values must be between 1 and 15 seconds in the form: 3s\")\n\t}\n\tlatency_i, err := strconv.Atoi(latency[:len(latency)-1])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif latency_i < 1 || latency_i > 15 {\n\t\treturn \"\", fmt.Errorf(\"latency values must be between 1 and 15 seconds in the form: 3s\")\n\t}\n\t\n\treturn latency, nil\n}\n\nfunc resourceAppengineCreate(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\n\tscaling_raw := d.Get(\"scaling\").([]interface{})\n\tif len(scaling_raw) > 1 {\n\t\treturn fmt.Errorf(\"User supplied more then one scaling setting.  This is wrong\")\n\t}\n\t\n\t\n\tscale := scaling_raw[0].(map[string]interface{})\n\tminPendingLatency, err := validateLatency(scale[\"minPendingLatency\"].(string))\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\tmaxPendingLatency, err := validateLatency(scale[\"maxPendingLatency\"].(string))\n\tif err != nil {\n\t\treturn err\n\t}\n\tautomaticScaling := &appengine.AutomaticScaling{\n\t\tMinIdleInstances: int64(scale[\"minIdleInstances\"].(int)),\n\t\tMaxIdleInstances: int64(scale[\"maxIdleInstances\"].(int)),\n\t\tMinPendingLatency: minPendingLatency,\n\t\tMaxPendingLatency: maxPendingLatency,\n\t}\n\t\n\terr = renderAppengineXMLToCloud(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\t\n\tfiles, err := generateFileList(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdeployment := &appengine.Deployment{Files:files}\n\t\n\thandlers := urlHandlers()\n\t\n\tinbound_services := make([]string, 1)\n\tinbound_services[0] = \"INBOUND_SERVICE_WARMUP\"\n\t\n\t\/\/  Version object for this module \n\tversion := &appengine.Version{\n\t\tAutomaticScaling: automaticScaling, \n\t\tDeployment:deployment, \n\t\tHandlers: handlers, \n\t\tId: d.Get(\"version\").(string), \n\t\tRuntime: \"java7\",\n\t\t\/\/InstanceClass: \"F2\",  this is exploding.  not sure why\n\t\tInboundServices: inbound_services,\n\t\tThreadsafe: true,\n\t}\n\t\n\t\/\/  create the application\n\tmoduleVersionService := appengine.NewAppsModulesVersionsService(config.clientAppengine)\n\tcreateCall := moduleVersionService.Create(config.Project, d.Get(\"moduleName\").(string), version)\n\toperation, err := createCall.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\terr = operationWait(operation, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\treturn resourceAppengineRead(d, meta)\n}\n\nfunc operationWait(operation *appengine.Operation, config *Config) (error) {\n\t\/\/  wait for the creation to complete\n\toperationService := appengine.NewAppsOperationsService(config.clientAppengine)\n\toperationGet := operationService.Get(config.Project, strings.Replace(operation.Name, \"apps\/\"+config.Project+\"\/operations\/\", \"\", 1))\n\tcarryon := true\n\tfor carryon {\n\t\toperation, err := operationGet.Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcarryon = !operation.Done\n\t\ttime.Sleep(10*time.Second)\n\t}\n\t\n\t\/\/   if it failed, explode\n\tif operation.Error != nil {\n\t\tlog.Printf(\"[DEBUG] status list from bad operation: %q\", operation.Error.Details)\n\t\treturn fmt.Errorf(operation.Error.Message)\n\t}\n\t\n\treturn nil\n}\n\nfunc resourceAppengineRead(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tmoduleVersionService := appengine.NewAppsModulesVersionsService(config.clientAppengine)\n\tgetCall := moduleVersionService.Get(config.Project, d.Get(\"moduleName\").(string), d.Get(\"version\").(string))\n\tversion, err := getCall.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.SetId(version.Name)\n\td.Set(\"servingStatus\", version.ServingStatus)\n\treturn nil\n}\n\nfunc resourceAppengineDelete(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tmoduleVersionService := appengine.NewAppsModulesVersionsService(config.clientAppengine)\n\tdeleteCall := moduleVersionService.Delete(config.Project, d.Get(\"moduleName\").(string), d.Get(\"version\").(string))\n\toperation, err := deleteCall.Do()\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"Cannot delete the final version of a service (module)\") {\n\t\t\tmoduleService := appengine.NewAppsModulesService(config.clientAppengine)\n\t\t\tmoduleDelete := moduleService.Delete(config.Project, d.Get(\"moduleName\").(string))\n\t\t\toperation, err = moduleDelete.Do()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t\n\t\t\terr = operationWait(operation, config)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\t\t\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\terr = operationWait(operation, config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\td.SetId(\"\")\n\treturn nil\n}\n<commit_msg>add env variables to appengine deploy<commit_after>package main\n\nimport (\n\t\"os\"\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\t\"strings\"\n\t\"strconv\"\n\t\"text\/template\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"google.golang.org\/api\/appengine\/v1beta4\"\n\t\"google.golang.org\/api\/storage\/v1\"\n)\n\nfunc resourceAppengine() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAppengineCreate,\n\t\tRead:   resourceAppengineRead,\n\t\tDelete: resourceAppengineDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"moduleName\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"version\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"gstorageBucket\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"gstorageKey\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"scaling\": &schema.Schema{\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"minIdleInstances\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeInt,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tDefault:  \"1\",\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"maxIdleInstances\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeInt,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tDefault: \"3\",\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"minPendingLatency\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tDefault: \"Automatic\",\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"maxPendingLatency\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tDefault: \"Automatic\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"topicName\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"servingStatus\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nvar (\n\tremoteBase = \"https:\/\/storage.googleapis.com\/\"\n)\n\n\nfunc urlHandlers() ([]*appengine.UrlMap) {\n\thandlers := make([]*appengine.UrlMap, 0)\n\t\thandlers = append(handlers, &appengine.UrlMap{\n\t\t\tSecurityLevel: \"SECURE_OPTIONAL\",\n\t\t\tLogin: \"LOGIN_OPTIONAL\",\n\t\t\tUrlRegex:\"\/\", \n\t\t\tScript:&appengine.ScriptHandler{\n\t\t\t\tScriptPath:\"unused\",\n\t\t\t},\n\t\t})\n\t\thandlers = append(handlers, &appengine.UrlMap{\n\t\t\tSecurityLevel: \"SECURE_OPTIONAL\",\n\t\t\tLogin: \"LOGIN_OPTIONAL\",\n\t\t\tUrlRegex:\"\/.*\/\", \n\t\t\tScript:&appengine.ScriptHandler{\n\t\t\t\tScriptPath:\"unused\",\n\t\t\t},\n\t\t})\n\t\thandlers = append(handlers, &appengine.UrlMap{\n\t\t\tSecurityLevel: \"SECURE_OPTIONAL\",\n\t\t\tLogin: \"LOGIN_OPTIONAL\",\n\t\t\tUrlRegex:\"\/_ah\/.*\", \n\t\t\tScript:&appengine.ScriptHandler{\n\t\t\t\tScriptPath:\"unused\",\n\t\t\t},\n\t\t})\n\t\thandlers = append(handlers, &appengine.UrlMap{\n\t\t\tSecurityLevel: \"SECURE_OPTIONAL\",\n\t\t\tLogin: \"LOGIN_OPTIONAL\",\n\t\t\tUrlRegex:\"\/endpoint\", \n\t\t\tScript:&appengine.ScriptHandler{\n\t\t\t\tScriptPath:\"unused\",\n\t\t\t},\n\t\t})\n\t\t\n\t\treturn handlers\n}\n\n\n\/\/ known issues with this function:\n\/\/   assumes \"\/\" is delimiter in gstorage and forces that to be last char in key\n\/\/   only searches first page, if more then 1k files to load, will only grab first 1k\nfunc generateFileList(d *schema.ResourceData, config *Config) (map[string]appengine.FileInfo, error) {\n\tlistService := storage.NewObjectsService(config.clientStorage)\n\tbucket := d.Get(\"gstorageBucket\").(string)\n\tlistCall := listService.List(bucket)\n\tkey := d.Get(\"gstorageKey\").(string)\n\tlastChar := key[len(key)-1:]\n\tif lastChar != \"\/\" {\n\t\tkey = key + \"\/\"\n\t}\n\tlistCall = listCall.Prefix(key)\n\tobjs, err := listCall.Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\n\tfiles := make(map[string]appengine.FileInfo)\n\tfor _, obj := range objs.Items {\n\t\tonDiskName := strings.Replace(obj.Name, key, \"\", 1)  \/\/ trims key from file name\n\t\tinCloudURL := remoteBase + bucket + \"\/\" + obj.Name\n\t\tfiles[onDiskName] = appengine.FileInfo{SourceUrl:inCloudURL} \n\t}\n\t\n\treturn files, nil\n}\n\nfunc renderAppengineXML(d  *schema.ResourceData, config *Config) (error) {\n\ttype AppengineXmlData struct {\n\t\tProject\t\t\tstring\n\t\tSourceVersion\tstring\n\t\tModule\t\t\tstring\n\t\tTopicName\t\tstring\n\t}\n\t\n\taxd := AppengineXmlData{\n\t\tProject: config.Project,\n\t\tSourceVersion: d.Get(\"version\").(string),\n\t\tModule: d.Get(\"moduleName\").(string),\n\t\tTopicName: d.Get(\"topicName\").(string),\n\t}\n\t\n\ttempl, err := template.New(\"appengine-web.xml.template\").Parse(axdTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\taxdRendered, err := os.Create(\"appengine-web.xml\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer axdRendered.Close()\n\terr = templ.Execute(axdRendered, axd)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\treturn nil\n}\n\nfunc pushAppengineXmlToCloud(d *schema.ResourceData, config *Config) (error) {\n\tkey := d.Get(\"gstorageKey\").(string)\n\tlastChar := key[len(key)-1:]\n\tif lastChar != \"\/\" {\n\t\tkey = key + \"\/\"\n\t}\n\tkey = key + \"WEB-INF\/appengine-web.xml\"\n\tobject := &storage.Object{Name: key}\n    file, err := os.Open(\"appengine-web.xml\")\n    if err != nil {\n    \tfmt.Errorf(\"Error opening %q: %v\", \"appengine.xml\", err)\n    }\n\tobjectService := storage.NewObjectsService(config.clientStorage)\n\t_, err = objectService.Insert(d.Get(\"gstorageBucket\").(string), object).Media(file).Do()\n    if err != nil {\n        fmt.Errorf(\"Objects.Insert failed: %v\", err)\n    }\n\n\treturn nil\n}\n\nfunc renderAppengineXMLToCloud(d *schema.ResourceData, config *Config) (error) {\n\terr := renderAppengineXML(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\terr = pushAppengineXmlToCloud(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\treturn nil\n}\n\nfunc validateLatency(latency string) (string, error) {\n\tlastChar := latency[len(latency)-1:]\n\tif lastChar != \"s\" {\n\t\treturn \"\", fmt.Errorf(\"latency values must be between 1 and 15 seconds in the form: 3s\")\n\t}\n\tlatency_i, err := strconv.Atoi(latency[:len(latency)-1])\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif latency_i < 1 || latency_i > 15 {\n\t\treturn \"\", fmt.Errorf(\"latency values must be between 1 and 15 seconds in the form: 3s\")\n\t}\n\t\n\treturn latency, nil\n}\n\nfunc resourceAppengineCreate(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\n\tscaling_raw := d.Get(\"scaling\").([]interface{})\n\tif len(scaling_raw) > 1 {\n\t\treturn fmt.Errorf(\"User supplied more then one scaling setting.  This is wrong\")\n\t}\n\t\n\t\n\tscale := scaling_raw[0].(map[string]interface{})\n\tminPendingLatency, err := validateLatency(scale[\"minPendingLatency\"].(string))\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\tmaxPendingLatency, err := validateLatency(scale[\"maxPendingLatency\"].(string))\n\tif err != nil {\n\t\treturn err\n\t}\n\tautomaticScaling := &appengine.AutomaticScaling{\n\t\tMinIdleInstances: int64(scale[\"minIdleInstances\"].(int)),\n\t\tMaxIdleInstances: int64(scale[\"maxIdleInstances\"].(int)),\n\t\tMinPendingLatency: minPendingLatency,\n\t\tMaxPendingLatency: maxPendingLatency,\n\t}\n\t\n\terr = renderAppengineXMLToCloud(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\t\n\tfiles, err := generateFileList(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdeployment := &appengine.Deployment{Files:files}\n\t\n\thandlers := urlHandlers()\n\t\n\tinbound_services := make([]string, 1)\n\tinbound_services[0] = \"INBOUND_SERVICE_WARMUP\"\n\t\n\tenv_vars := make(map[string]string,2)\n\tenv_vars[\"OUTPUTPUBSUB\"] = d.Get(\"topicName\").(string)\n\tenv_vars[\"RETURNMESSAGEIDS\"] = \"true\"\n\t\n\t\/\/  Version object for this module \n\tversion := &appengine.Version{\n\t\tAutomaticScaling: automaticScaling, \n\t\tDeployment:deployment, \n\t\tHandlers: handlers, \n\t\tId: d.Get(\"version\").(string), \n\t\tRuntime: \"java7\",\n\t\t\/\/InstanceClass: \"F2\",  this is exploding.  not sure why\n\t\tInboundServices: inbound_services,\n\t\tEnvVariables: env_vars,\n\t\tThreadsafe: true,\n\t}\n\t\n\t\/\/  create the application\n\tmoduleVersionService := appengine.NewAppsModulesVersionsService(config.clientAppengine)\n\tcreateCall := moduleVersionService.Create(config.Project, d.Get(\"moduleName\").(string), version)\n\toperation, err := createCall.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\terr = operationWait(operation, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\treturn resourceAppengineRead(d, meta)\n}\n\nfunc operationWait(operation *appengine.Operation, config *Config) (error) {\n\t\/\/  wait for the creation to complete\n\toperationService := appengine.NewAppsOperationsService(config.clientAppengine)\n\toperationGet := operationService.Get(config.Project, strings.Replace(operation.Name, \"apps\/\"+config.Project+\"\/operations\/\", \"\", 1))\n\tcarryon := true\n\tfor carryon {\n\t\toperation, err := operationGet.Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcarryon = !operation.Done\n\t\ttime.Sleep(10*time.Second)\n\t}\n\t\n\t\/\/   if it failed, explode\n\tif operation.Error != nil {\n\t\tlog.Printf(\"[DEBUG] status list from bad operation: %q\", operation.Error.Details)\n\t\treturn fmt.Errorf(operation.Error.Message)\n\t}\n\t\n\treturn nil\n}\n\nfunc resourceAppengineRead(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tmoduleVersionService := appengine.NewAppsModulesVersionsService(config.clientAppengine)\n\tgetCall := moduleVersionService.Get(config.Project, d.Get(\"moduleName\").(string), d.Get(\"version\").(string))\n\tversion, err := getCall.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.SetId(version.Name)\n\td.Set(\"servingStatus\", version.ServingStatus)\n\treturn nil\n}\n\nfunc resourceAppengineDelete(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tmoduleVersionService := appengine.NewAppsModulesVersionsService(config.clientAppengine)\n\tdeleteCall := moduleVersionService.Delete(config.Project, d.Get(\"moduleName\").(string), d.Get(\"version\").(string))\n\toperation, err := deleteCall.Do()\n\tif err != nil {\n\t\tif strings.Contains(err.Error(), \"Cannot delete the final version of a service (module)\") {\n\t\t\tmoduleService := appengine.NewAppsModulesService(config.clientAppengine)\n\t\t\tmoduleDelete := moduleService.Delete(config.Project, d.Get(\"moduleName\").(string))\n\t\t\toperation, err = moduleDelete.Do()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t\n\t\t\terr = operationWait(operation, config)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\t\t\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\terr = operationWait(operation, config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\td.SetId(\"\")\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package web_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\/\/ . \"github.com\/sclevine\/agouti\/matchers\"\n\n\t\"github.com\/concourse\/atc\"\n)\n\nvar _ = Describe(\"Viewing resources\", func() {\n\tDescribe(\"a broken resource\", func() {\n\t\tvar brokenResource atc.Resource\n\n\t\tBeforeEach(func() {\n\t\t\t_, _, _, err := team.CreateOrUpdatePipelineConfig(pipelineName, \"0\", atc.Config{\n\t\t\t\tResources: []atc.ResourceConfig{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"broken-resource\",\n\t\t\t\t\t\tType: \"git\",\n\t\t\t\t\t\tSource: atc.Source{\n\t\t\t\t\t\t\t\"branch\": \"master\",\n\t\t\t\t\t\t\t\"uri\":    \"i r not reall?\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tCheckEvery: \"\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t_, err = team.UnpausePipeline(pipelineName)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\tvar found bool\n\t\t\tbrokenResource, found, err = team.Resource(pipelineName, \"broken-resource\")\n\t\t\tExpect(found).To(BeTrue())\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t})\n\n\t\tIt(\"correctly displays logs\", func() {\n\t\t\turl := atcRoute(fmt.Sprintf(\"\/teams\/%s\/pipelines\/%s\/resources\/%s\", teamName, pipelineName, brokenResource.Name))\n\n\t\t\tcounter := 0\n\t\t\tfor {\n\t\t\t\tExpect(page.Navigate(url)).To(Succeed())\n\t\t\t\tif counter == 120 {\n\t\t\t\t\tFail(\"Unable to locate resource log information.\")\n\t\t\t\t}\n\n\t\t\t\tif visible, _ := page.Find(\".resource-check-status .header i.errored\").Visible(); visible {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcounter++\n\t\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t\t}\n\n\t\t\tEventually(page.Find(\"pre\").Text).Should(ContainSubstring(\"failed: exit status\"))\n\t\t})\n\t})\n})\n<commit_msg>fix invalid config<commit_after>package web_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\/\/ . \"github.com\/sclevine\/agouti\/matchers\"\n\n\t\"github.com\/concourse\/atc\"\n)\n\nvar _ = Describe(\"Viewing resources\", func() {\n\tDescribe(\"a broken resource\", func() {\n\t\tvar brokenResource atc.Resource\n\n\t\tBeforeEach(func() {\n\t\t\t_, _, _, err := team.CreateOrUpdatePipelineConfig(pipelineName, \"0\", atc.Config{\n\t\t\t\tResources: []atc.ResourceConfig{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"broken-resource\",\n\t\t\t\t\t\tType: \"git\",\n\t\t\t\t\t\tSource: atc.Source{\n\t\t\t\t\t\t\t\"branch\": \"master\",\n\t\t\t\t\t\t\t\"uri\":    \"i r not reall?\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tCheckEvery: \"\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tJobs: atc.JobConfigs{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"broken-resource-user\",\n\t\t\t\t\t\tPlan: atc.PlanSequence{\n\t\t\t\t\t\t\t{Get: \"broken-resource\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t_, err = team.UnpausePipeline(pipelineName)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\tvar found bool\n\t\t\tbrokenResource, found, err = team.Resource(pipelineName, \"broken-resource\")\n\t\t\tExpect(found).To(BeTrue())\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t})\n\n\t\tIt(\"correctly displays logs\", func() {\n\t\t\turl := atcRoute(fmt.Sprintf(\"\/teams\/%s\/pipelines\/%s\/resources\/%s\", teamName, pipelineName, brokenResource.Name))\n\n\t\t\tcounter := 0\n\t\t\tfor {\n\t\t\t\tExpect(page.Navigate(url)).To(Succeed())\n\t\t\t\tif counter == 120 {\n\t\t\t\t\tFail(\"Unable to locate resource log information.\")\n\t\t\t\t}\n\n\t\t\t\tif visible, _ := page.Find(\".resource-check-status .header i.errored\").Visible(); visible {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcounter++\n\t\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t\t}\n\n\t\t\tEventually(page.Find(\"pre\").Text).Should(ContainSubstring(\"failed: exit status\"))\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>more Commuting Engineer<commit_after><|endoftext|>"}
{"text":"<commit_before>package scanner\n\nimport (\n\t\"fmt\"\n)\n\nfunc compare(left *FileSystem, right *FileSystem, verbose bool) bool {\n\tif len(left.InodeTable) != len(right.InodeTable) {\n\t\tfmt.Printf(\"left vs. right: %d vs %d inodes\\n\",\n\t\t\tlen(left.InodeTable), len(right.InodeTable))\n\t\treturn false\n\t}\n\treturn true\n}\n<commit_msg>Add embryonic scanner.compareDirectories() function.<commit_after>package scanner\n\nimport (\n\t\"fmt\"\n)\n\nfunc compare(left *FileSystem, right *FileSystem, verbose bool) bool {\n\tif len(left.InodeTable) != len(right.InodeTable) {\n\t\tfmt.Printf(\"left vs. right: %d vs. %d inodes\\n\",\n\t\t\tlen(left.InodeTable), len(right.InodeTable))\n\t\treturn false\n\t}\n\treturn compareDirectories(&left.Directory, &right.Directory, verbose)\n}\n\nfunc compareDirectories(left *Directory, right *Directory, verbose bool) bool {\n\tif left.name != right.name {\n\t\tfmt.Printf(\"left vs. right: %s vs. %s\\n\", left.name, right.name)\n\t\treturn false\n\t}\n\tif len(left.FileList) != len(right.FileList) {\n\t\tfmt.Printf(\"left vs. right: %d vs. %d files\\n\",\n\t\t\tlen(left.FileList), len(right.FileList))\n\t\treturn false\n\t}\n\tif len(left.DirectoryList) != len(right.DirectoryList) {\n\t\tfmt.Printf(\"left vs. right: %d vs. %d subdirs\\n\",\n\t\t\tlen(left.DirectoryList), len(right.DirectoryList))\n\t\treturn false\n\t}\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage mesh\n\nimport (\n\t\"flag\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\tbinversion \"istio.io\/istio\/operator\/version\"\n\t\"istio.io\/pkg\/log\"\n\t\"istio.io\/pkg\/version\"\n)\n\nconst (\n\tsetFlagHelpStr = `Override an IstioOperator value, e.g. to choose a profile\n(--set profile=demo), enable or disable components (--set components.policy.enabled=true), or override Istio\nsettings (--set values.grafana.enabled=true). See documentation for more info:\nhttps:\/\/istio.io\/docs\/reference\/config\/istio.operator.v1alpha1\/#IstioOperatorSpec`\n\t\/\/ ChartsFlagHelpStr is the command line description for --charts\n\tChartsFlagHelpStr = `Specify a path to a directory of charts and profiles\n(e.g. ~\/Downloads\/istio-1.6.0\/install\/kubernetes\/operator)\nor release tar URL (e.g. https:\/\/github.com\/istio\/istio\/releases\/download\/1.6.0\/istio-1.6.0-linux-amd64.tar.gz).\n`\n\trevisionFlagHelpStr         = `Target control plane revision for the command.`\n\tskipConfirmationFlagHelpStr = `skipConfirmation determines whether the user is prompted for confirmation.\nIf set to true, the user is not prompted and a Yes response is assumed in all cases.`\n\tfilenameFlagHelpStr = `Path to file containing IstioOperator custom resource\nThis flag can be specified multiple times to overlay multiple files. Multiple files are overlaid in left to right order.`\n\tinstallationCompleteStr = `Installation complete`\n)\n\ntype rootArgs struct {\n\t\/\/ Dry run performs all steps except actually applying the manifests or creating output dirs\/files.\n\tdryRun bool\n}\n\nfunc addFlags(cmd *cobra.Command, rootArgs *rootArgs) {\n\tcmd.PersistentFlags().BoolVarP(&rootArgs.dryRun, \"dry-run\", \"\",\n\t\tfalse, \"Console\/log output only, make no changes.\")\n}\n\n\/\/ GetRootCmd returns the root of the cobra command-tree.\nfunc GetRootCmd(args []string) *cobra.Command {\n\trootCmd := &cobra.Command{\n\t\tUse:          \"mesh\",\n\t\tShort:        \"Command line Istio install utility.\",\n\t\tSilenceUsage: true,\n\t\tLong: \"This command uses the Istio operator code to generate templates, query configurations and perform \" +\n\t\t\t\"utility operations.\",\n\t}\n\trootCmd.SetArgs(args)\n\trootCmd.PersistentFlags().AddGoFlagSet(flag.CommandLine)\n\n\trootCmd.AddCommand(ManifestCmd(log.DefaultOptions()))\n\trootCmd.AddCommand(ProfileCmd())\n\trootCmd.AddCommand(OperatorCmd())\n\trootCmd.AddCommand(version.CobraCommand())\n\trootCmd.AddCommand(UpgradeCmd())\n\n\tversion.Info.Version = binversion.OperatorVersionString\n\n\treturn rootCmd\n}\n<commit_msg>Update path of charts and profile (#24202)<commit_after>\/\/ Copyright 2019 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage mesh\n\nimport (\n\t\"flag\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\tbinversion \"istio.io\/istio\/operator\/version\"\n\t\"istio.io\/pkg\/log\"\n\t\"istio.io\/pkg\/version\"\n)\n\nconst (\n\tsetFlagHelpStr = `Override an IstioOperator value, e.g. to choose a profile\n(--set profile=demo), enable or disable components (--set components.policy.enabled=true), or override Istio\nsettings (--set values.grafana.enabled=true). See documentation for more info:\nhttps:\/\/istio.io\/docs\/reference\/config\/istio.operator.v1alpha1\/#IstioOperatorSpec`\n\t\/\/ ChartsFlagHelpStr is the command line description for --charts\n\tChartsFlagHelpStr = `Specify a path to a directory of charts and profiles\n(e.g. ~\/Downloads\/istio-1.6.0\/manifests)\nor release tar URL (e.g. https:\/\/github.com\/istio\/istio\/releases\/download\/1.6.0\/istio-1.6.0-linux-amd64.tar.gz).\n`\n\trevisionFlagHelpStr         = `Target control plane revision for the command.`\n\tskipConfirmationFlagHelpStr = `skipConfirmation determines whether the user is prompted for confirmation.\nIf set to true, the user is not prompted and a Yes response is assumed in all cases.`\n\tfilenameFlagHelpStr = `Path to file containing IstioOperator custom resource\nThis flag can be specified multiple times to overlay multiple files. Multiple files are overlaid in left to right order.`\n\tinstallationCompleteStr = `Installation complete`\n)\n\ntype rootArgs struct {\n\t\/\/ Dry run performs all steps except actually applying the manifests or creating output dirs\/files.\n\tdryRun bool\n}\n\nfunc addFlags(cmd *cobra.Command, rootArgs *rootArgs) {\n\tcmd.PersistentFlags().BoolVarP(&rootArgs.dryRun, \"dry-run\", \"\",\n\t\tfalse, \"Console\/log output only, make no changes.\")\n}\n\n\/\/ GetRootCmd returns the root of the cobra command-tree.\nfunc GetRootCmd(args []string) *cobra.Command {\n\trootCmd := &cobra.Command{\n\t\tUse:          \"mesh\",\n\t\tShort:        \"Command line Istio install utility.\",\n\t\tSilenceUsage: true,\n\t\tLong: \"This command uses the Istio operator code to generate templates, query configurations and perform \" +\n\t\t\t\"utility operations.\",\n\t}\n\trootCmd.SetArgs(args)\n\trootCmd.PersistentFlags().AddGoFlagSet(flag.CommandLine)\n\n\trootCmd.AddCommand(ManifestCmd(log.DefaultOptions()))\n\trootCmd.AddCommand(ProfileCmd())\n\trootCmd.AddCommand(OperatorCmd())\n\trootCmd.AddCommand(version.CobraCommand())\n\trootCmd.AddCommand(UpgradeCmd())\n\n\tversion.Info.Version = binversion.OperatorVersionString\n\n\treturn rootCmd\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"..\/nsq\"\n\t\"..\/util\/notify\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n)\n\nvar notifyChannelChan = make(chan interface{})\nvar notifyTopicChan = make(chan interface{})\nvar lookupPeers = make([]*nsq.LookupPeer, 0)\n\nfunc LookupRouter(lookupHosts []string) {\n\tfor _, host := range lookupHosts {\n\t\ttcpAddr, err := net.ResolveTCPAddr(\"tcp\", host)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"LOOKUP: could not resolve TCP address for %s\", host)\n\t\t}\n\t\tlookupPeer := nsq.NewLookupPeer(tcpAddr)\n\t\tlookupPeers = append(lookupPeers, lookupPeer)\n\t}\n\n\tnotify.Observe(\"new_channel\", notifyChannelChan)\n\tnotify.Observe(\"new_topic\", notifyTopicChan)\n\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(10 * time.Second):\n\t\t\t\/\/ send a heartbeat and read a response (read detects closed conns)\n\t\t\tfor _, lookupPeer := range lookupPeers {\n\t\t\t\tlog.Printf(\"LOOKUP: sending heartbeat to %s\", lookupPeer.String())\n\t\t\t\tif !lookupPeer.IsConnected() {\n\t\t\t\t\terr := lookupPeer.Connect()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Printf(\"LOOKUP: failed to connect to %s\", lookupPeer.String())\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tlookupPeer.Version(nsq.LookupProtocolV1Magic)\n\t\t\t\t}\n\t\t\t\terr := lookupPeer.WriteCommand(lookupPeer.Ping())\n\t\t\t\tif err != nil {\n\t\t\t\t\tlookupPeer.Close()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t_, err = lookupPeer.ReadResponse()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlookupPeer.Close()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\tcase newChannel := <-notifyChannelChan:\n\t\t\tchannel := newChannel.(*Channel)\n\t\t\tlog.Printf(\"LOOKUP: new channel %s\", channel.name)\n\t\tcase newTopic := <-notifyTopicChan:\n\t\t\ttopic := newTopic.(*Topic)\n\t\t\tlog.Printf(\"LOOKUP: new topic %s\", topic.name)\n\t\t\tfor _, lookupPeer := range lookupPeers {\n\t\t\t\tif !lookupPeer.IsConnected() {\n\t\t\t\t\terr := lookupPeer.Connect()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Printf(\"LOOKUP: failed to connect to %s\", lookupPeer.String())\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tlookupPeer.Version(nsq.LookupProtocolV1Magic)\n\t\t\t\t}\n\t\t\t\terr := lookupPeer.WriteCommand(lookupPeer.Announce(topic.name, *bindAddress, *tcpPort))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"LOOKUP: error announcing to %s... closing\", lookupPeer.String())\n\t\t\t\t\tlookupPeer.Close()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t_, err = lookupPeer.ReadResponse()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlookupPeer.Close()\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>DRY up the outbound req\/resp from nsqd -> nsqlookupd<commit_after>package main\n\nimport (\n\t\"..\/nsq\"\n\t\"..\/util\/notify\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n)\n\nvar notifyChannelChan = make(chan interface{})\nvar notifyTopicChan = make(chan interface{})\nvar lookupPeers = make([]*nsq.LookupPeer, 0)\n\nfunc LookupRouter(lookupHosts []string) {\n\tfor _, host := range lookupHosts {\n\t\ttcpAddr, err := net.ResolveTCPAddr(\"tcp\", host)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"LOOKUP: could not resolve TCP address for %s\", host)\n\t\t}\n\t\tlookupPeer := nsq.NewLookupPeer(tcpAddr)\n\t\tlookupPeers = append(lookupPeers, lookupPeer)\n\t}\n\n\tnotify.Observe(\"new_channel\", notifyChannelChan)\n\tnotify.Observe(\"new_topic\", notifyTopicChan)\n\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(10 * time.Second):\n\t\t\t\/\/ send a heartbeat and read a response (read detects closed conns)\n\t\t\tfor _, lookupPeer := range lookupPeers {\n\t\t\t\tlog.Printf(\"LOOKUP: sending heartbeat to %s\", lookupPeer.String())\n\t\t\t\tlookupCommand(lookupPeer, lookupPeer.Ping())\n\t\t\t}\n\t\tcase newChannel := <-notifyChannelChan:\n\t\t\tchannel := newChannel.(*Channel)\n\t\t\tlog.Printf(\"LOOKUP: new channel %s\", channel.name)\n\t\t\t\/\/ TODO: notify all nsds that a new channel exists\n\t\tcase newTopic := <-notifyTopicChan:\n\t\t\t\/\/ notify all nsds that a new topic exists\n\t\t\ttopic := newTopic.(*Topic)\n\t\t\tlog.Printf(\"LOOKUP: new topic %s\", topic.name)\n\t\t\tfor _, lookupPeer := range lookupPeers {\n\t\t\t\tlookupCommand(lookupPeer, lookupPeer.Announce(topic.name, *bindAddress, *tcpPort))\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc lookupCommand(peer *nsq.LookupPeer, cmd *nsq.ProtocolCommand) ([]byte, error) {\n\tif !peer.IsConnected() {\n\t\terr := peer.Connect()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"LOOKUP: failed to connect to %s\", peer.String())\n\t\t\treturn nil, err\n\t\t}\n\t\tpeer.Version(nsq.LookupProtocolV1Magic)\n\t}\n\terr := peer.WriteCommand(cmd)\n\tif err != nil {\n\t\tpeer.Close()\n\t\treturn nil, err\n\t}\n\tresp, err := peer.ReadResponse()\n\tif err != nil {\n\t\tpeer.Close()\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package appstore\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestHandleError(t *testing.T) {\n\tvar expected, actual error\n\n\t\/\/ status 0\n\texpected = nil\n\tactual = HandleError(0)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21000\n\texpected = errors.New(\"The App Store could not read the JSON object you provided.\")\n\tactual = HandleError(21000)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21002\n\texpected = errors.New(\"The data in the receipt-data property was malformed or missing.\")\n\tactual = HandleError(21002)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21003\n\texpected = errors.New(\"The receipt could not be authenticated.\")\n\tactual = HandleError(21003)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21004\n\texpected = errors.New(\"The shared secret you provided does not match the shared secret on file for your account.\")\n\tactual = HandleError(21004)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21005\n\texpected = errors.New(\"The receipt server is not currently available.\")\n\tactual = HandleError(21005)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21007\n\texpected = errors.New(\"This receipt is from the test environment, but it was sent to the production environment for verification. Send it to the test environment instead.\")\n\tactual = HandleError(21007)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21008\n\texpected = errors.New(\"This receipt is from the production environment, but it was sent to the test environment for verification. Send it to the production environment instead.\")\n\tactual = HandleError(21008)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21010\n\texpected = errors.New(\"This receipt could not be authorized. Treat this the same as if a purchase was never made.\")\n\tactual = HandleError(21010)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21100 - 21199\n\texpected = errors.New(\"Internal data access error.\")\n\tactual = HandleError(21155)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status unknown\n\texpected = errors.New(\"An unknown error occurred\")\n\tactual = HandleError(100)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n}\n\nfunc TestNew(t *testing.T) {\n\texpected := Client{\n\t\tProductionURL: ProductionURL,\n\t\tSandboxURL:    SandboxURL,\n\t\tTimeOut:       time.Second * 5,\n\t}\n\n\tactual := New()\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n}\n\nfunc TestNewWithEnvironment(t *testing.T) {\n\texpected := Client{\n\t\tProductionURL: ProductionURL,\n\t\tTimeOut:       time.Second * 5,\n\t\tSandboxURL:    SandboxURL,\n\t}\n\n\tos.Setenv(\"IAP_ENVIRONMENT\", \"production\")\n\tactual := New()\n\tos.Clearenv()\n\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n}\n\nfunc TestNewWithConfig(t *testing.T) {\n\tconfig := Config{\n\t\tTimeOut: time.Second * 2,\n\t}\n\n\texpected := Client{\n\t\tProductionURL: ProductionURL,\n\t\tSandboxURL:    SandboxURL,\n\t\tTimeOut:       time.Second * 2,\n\t}\n\n\tactual := NewWithConfig(config)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n}\n\nfunc TestNewWithConfigTimeout(t *testing.T) {\n\tconfig := Config{}\n\n\texpected := Client{\n\t\tProductionURL: ProductionURL,\n\t\tSandboxURL:    SandboxURL,\n\t\tTimeOut:       time.Second * 5,\n\t}\n\n\tactual := NewWithConfig(config)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n}\n\nfunc TestVerifyTimeout(t *testing.T) {\n\tclient := New()\n\tclient.TimeOut = time.Millisecond\n\n\treq := IAPRequest{\n\t\tReceiptData: \"dummy data\",\n\t}\n\tresult := &IAPResponse{}\n\terr := client.Verify(req, result)\n\tif err == nil {\n\t\tt.Errorf(\"error should be occurred because of timeout\")\n\t}\n}\n\nfunc TestVerifyBadURL(t *testing.T) {\n\tclient := New()\n\tclient.ProductionURL = \"127.0.0.1\"\n\n\treq := IAPRequest{\n\t\tReceiptData: \"dummy data\",\n\t}\n\tresult := &IAPResponse{}\n\terr := client.Verify(req, result)\n\tif err == nil {\n\t\tt.Errorf(\"error should be occurred because the server is not real\")\n\t}\n}\n\nfunc TestVerifyBadPayload(t *testing.T) {\n\ts := httptest.NewServer(serverWithResponse(`{\"status\": 21002}`))\n\tdefer s.Close()\n\n\tclient := New()\n\tclient.ProductionURL = s.URL\n\texpected := &IAPResponse{\n\t\tStatus: 21002,\n\t}\n\treq := IAPRequest{\n\t\tReceiptData: \"dummy data\",\n\t}\n\tresult := &IAPResponse{}\n\n\terr := client.Verify(req, result)\n\tif err != nil {\n\t\tt.Errorf(\"got error %s\", err)\n\t}\n\tif !reflect.DeepEqual(result, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", result, expected)\n\t}\n}\n\nfunc TestVerifyBadResponse(t *testing.T) {\n\ts := httptest.NewServer(serverWithResponse(`qwerty!@#$%^`))\n\tdefer s.Close()\n\n\tclient := New()\n\tclient.ProductionURL = s.URL\n\treq := IAPRequest{\n\t\tReceiptData: \"dummy data\",\n\t}\n\tresult := &IAPResponse{}\n\n\terr := client.Verify(req, result)\n\tif err == nil {\n\t\tt.Errorf(\"expected an error because Verify could not unmarshal server response\")\n\t}\n}\n\nfunc TestVerifySandboxReceipt(t *testing.T) {\n\ts := httptest.NewServer(serverWithResponse(`{\"status\": 21007}`))\n\tdefer s.Close()\n\n\tsandboxServ := httptest.NewServer(serverWithResponse(`{\"status\": 0}`))\n\tdefer sandboxServ.Close()\n\n\tclient := New()\n\tclient.ProductionURL = s.URL\n\tclient.TimeOut = time.Second * 100\n\tclient.SandboxURL = sandboxServ.URL\n\n\texpected := &IAPResponse{\n\t\tStatus: 0,\n\t}\n\treq := IAPRequest{\n\t\tReceiptData: \"dummy data\",\n\t}\n\tresult := &IAPResponse{}\n\n\terr := client.Verify(req, result)\n\tif err != nil {\n\t\tt.Errorf(\"got error %s\", err)\n\t}\n\tif !reflect.DeepEqual(result, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", result, expected)\n\t}\n}\n\nfunc TestVerifySandboxReceiptFailure(t *testing.T) {\n\ts := httptest.NewServer(serverWithResponse(`{\"status\": 21007}`))\n\tdefer s.Close()\n\n\tclient := New()\n\tclient.ProductionURL = s.URL\n\tclient.TimeOut = time.Second * 100\n\tclient.SandboxURL = \"localhost\"\n\n\treq := IAPRequest{\n\t\tReceiptData: \"dummy data\",\n\t}\n\tresult := &IAPResponse{}\n\n\terr := client.Verify(req, result)\n\tif err == nil {\n\t\tt.Errorf(\"expected error to be not nil since the sandbox is not responding\")\n\t}\n}\n\nfunc TestCannotReadBody(t *testing.T) {\n\tclient := New()\n\ttestResponse := http.Response{Body: ioutil.NopCloser(errReader(0))}\n\n\tif client.parseResponse(&testResponse, IAPResponse{}, http.Client{}, IAPRequest{}) == nil {\n\t\tt.Errorf(\"expected redirectToSandbox to fail to read the body\")\n\t}\n}\n\nfunc TestCannotUnmarshalBody(t *testing.T) {\n\tclient := New()\n\ttestResponse := http.Response{Body: ioutil.NopCloser(strings.NewReader(`{\"status\": true}`))}\n\n\tif client.parseResponse(&testResponse, StatusResponse{}, http.Client{}, IAPRequest{}) == nil {\n\t\tt.Errorf(\"expected redirectToSandbox to fail to unmarshal the data\")\n\t}\n}\n\ntype errReader int\n\nfunc (errReader) Read(p []byte) (n int, err error) {\n\treturn 0, errors.New(\"test error\")\n}\n\nfunc serverWithResponse(response string) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif \"POST\" == r.Method {\n\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tw.Write([]byte(response))\n\t\t\treturn\n\t\t} else {\n\t\t\tw.Write([]byte(`unsupported request`))\n\t\t}\n\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t})\n}\n<commit_msg>Correct tests<commit_after>package appstore\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestHandleError(t *testing.T) {\n\tvar expected, actual error\n\n\t\/\/ status 0\n\texpected = nil\n\tactual = HandleError(0)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21000\n\texpected = errors.New(\"The App Store could not read the JSON object you provided.\")\n\tactual = HandleError(21000)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21002\n\texpected = errors.New(\"The data in the receipt-data property was malformed or missing.\")\n\tactual = HandleError(21002)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21003\n\texpected = errors.New(\"The receipt could not be authenticated.\")\n\tactual = HandleError(21003)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21004\n\texpected = errors.New(\"The shared secret you provided does not match the shared secret on file for your account.\")\n\tactual = HandleError(21004)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21005\n\texpected = errors.New(\"The receipt server is not currently available.\")\n\tactual = HandleError(21005)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21007\n\texpected = errors.New(\"This receipt is from the test environment, but it was sent to the production environment for verification. Send it to the test environment instead.\")\n\tactual = HandleError(21007)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21008\n\texpected = errors.New(\"This receipt is from the production environment, but it was sent to the test environment for verification. Send it to the production environment instead.\")\n\tactual = HandleError(21008)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21010\n\texpected = errors.New(\"This receipt could not be authorized. Treat this the same as if a purchase was never made.\")\n\tactual = HandleError(21010)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status 21100 - 21199\n\texpected = errors.New(\"Internal data access error.\")\n\tactual = HandleError(21155)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n\n\t\/\/ status unknown\n\texpected = errors.New(\"An unknown error occurred\")\n\tactual = HandleError(100)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n}\n\nfunc TestNew(t *testing.T) {\n\texpected := Client{\n\t\tProductionURL: ProductionURL,\n\t\tSandboxURL:    SandboxURL,\n\t\tTimeOut:       time.Second * 5,\n\t}\n\n\tactual := New()\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n}\n\nfunc TestNewWithEnvironment(t *testing.T) {\n\texpected := Client{\n\t\tProductionURL: ProductionURL,\n\t\tTimeOut:       time.Second * 5,\n\t\tSandboxURL:    SandboxURL,\n\t}\n\n\tos.Setenv(\"IAP_ENVIRONMENT\", \"production\")\n\tactual := New()\n\tos.Clearenv()\n\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n}\n\nfunc TestNewWithConfig(t *testing.T) {\n\tconfig := Config{\n\t\tTimeOut: time.Second * 2,\n\t}\n\n\texpected := Client{\n\t\tProductionURL: ProductionURL,\n\t\tSandboxURL:    SandboxURL,\n\t\tTimeOut:       time.Second * 2,\n\t}\n\n\tactual := NewWithConfig(config)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n}\n\nfunc TestNewWithConfigTimeout(t *testing.T) {\n\tconfig := Config{}\n\n\texpected := Client{\n\t\tProductionURL: ProductionURL,\n\t\tSandboxURL:    SandboxURL,\n\t\tTimeOut:       time.Second * 5,\n\t}\n\n\tactual := NewWithConfig(config)\n\tif !reflect.DeepEqual(actual, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", actual, expected)\n\t}\n}\n\nfunc TestVerifyTimeout(t *testing.T) {\n\tclient := New()\n\tclient.TimeOut = time.Millisecond\n\n\treq := IAPRequest{\n\t\tReceiptData: \"dummy data\",\n\t}\n\tresult := &IAPResponse{}\n\terr := client.Verify(req, result)\n\tif err == nil {\n\t\tt.Errorf(\"error should be occurred because of timeout\")\n\t}\n}\n\nfunc TestVerifyBadURL(t *testing.T) {\n\tclient := New()\n\tclient.ProductionURL = \"127.0.0.1\"\n\n\treq := IAPRequest{\n\t\tReceiptData: \"dummy data\",\n\t}\n\tresult := &IAPResponse{}\n\terr := client.Verify(req, result)\n\tif err == nil {\n\t\tt.Errorf(\"error should be occurred because the server is not real\")\n\t}\n}\n\nfunc TestVerifyBadPayload(t *testing.T) {\n\ts := httptest.NewServer(serverWithResponse(http.StatusBadRequest, `{\"status\": 21002}`))\n\tdefer s.Close()\n\n\tclient := New()\n\tclient.ProductionURL = s.URL\n\texpected := &IAPResponse{\n\t\tStatus: 21002,\n\t}\n\treq := IAPRequest{\n\t\tReceiptData: \"dummy data\",\n\t}\n\tresult := &IAPResponse{}\n\n\terr := client.Verify(req, result)\n\tif err != nil {\n\t\tt.Errorf(\"got error %s\", err)\n\t}\n\tif !reflect.DeepEqual(result, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", result, expected)\n\t}\n}\n\nfunc TestVerifyBadResponse(t *testing.T) {\n\ts := httptest.NewServer(serverWithResponse(http.StatusInternalServerError, `qwerty!@#$%^`))\n\tdefer s.Close()\n\n\tclient := New()\n\tclient.ProductionURL = s.URL\n\treq := IAPRequest{\n\t\tReceiptData: \"dummy data\",\n\t}\n\tresult := &IAPResponse{}\n\n\terr := client.Verify(req, result)\n\tif err == nil {\n\t\tt.Errorf(\"expected an error because Verify could not unmarshal server response\")\n\t}\n}\n\nfunc TestVerifySandboxReceipt(t *testing.T) {\n\ts := httptest.NewServer(serverWithResponse(http.StatusOK, `{\"status\": 21007}`))\n\tdefer s.Close()\n\n\tsandboxServ := httptest.NewServer(serverWithResponse(http.StatusOK, `{\"status\": 0}`))\n\tdefer sandboxServ.Close()\n\n\tclient := New()\n\tclient.ProductionURL = s.URL\n\tclient.TimeOut = time.Second * 100\n\tclient.SandboxURL = sandboxServ.URL\n\n\texpected := &IAPResponse{\n\t\tStatus: 0,\n\t}\n\treq := IAPRequest{\n\t\tReceiptData: \"dummy data\",\n\t}\n\tresult := &IAPResponse{}\n\n\terr := client.Verify(req, result)\n\tif err != nil {\n\t\tt.Errorf(\"got error %s\", err)\n\t}\n\tif !reflect.DeepEqual(result, expected) {\n\t\tt.Errorf(\"got %v\\nwant %v\", result, expected)\n\t}\n}\n\nfunc TestVerifySandboxReceiptFailure(t *testing.T) {\n\ts := httptest.NewServer(serverWithResponse(http.StatusOK, `{\"status\": 21007}`))\n\tdefer s.Close()\n\n\tclient := New()\n\tclient.ProductionURL = s.URL\n\tclient.TimeOut = time.Second * 100\n\tclient.SandboxURL = \"localhost\"\n\n\treq := IAPRequest{\n\t\tReceiptData: \"dummy data\",\n\t}\n\tresult := &IAPResponse{}\n\n\terr := client.Verify(req, result)\n\tif err == nil {\n\t\tt.Errorf(\"expected error to be not nil since the sandbox is not responding\")\n\t}\n}\n\nfunc TestCannotReadBody(t *testing.T) {\n\tclient := New()\n\ttestResponse := http.Response{Body: ioutil.NopCloser(errReader(0))}\n\n\tif client.parseResponse(&testResponse, IAPResponse{}, http.Client{}, IAPRequest{}) == nil {\n\t\tt.Errorf(\"expected redirectToSandbox to fail to read the body\")\n\t}\n}\n\nfunc TestCannotUnmarshalBody(t *testing.T) {\n\tclient := New()\n\ttestResponse := http.Response{Body: ioutil.NopCloser(strings.NewReader(`{\"status\": true}`))}\n\n\tif client.parseResponse(&testResponse, StatusResponse{}, http.Client{}, IAPRequest{}) == nil {\n\t\tt.Errorf(\"expected redirectToSandbox to fail to unmarshal the data\")\n\t}\n}\n\ntype errReader int\n\nfunc (errReader) Read(p []byte) (n int, err error) {\n\treturn 0, errors.New(\"test error\")\n}\n\nfunc serverWithResponse(statusCode int, response string) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif \"POST\" == r.Method {\n\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tw.Write([]byte(response))\n\t\t\treturn\n\t\t} else {\n\t\t\tw.Write([]byte(`unsupported request`))\n\t\t}\n\n\t\tw.WriteHeader(statusCode)\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright ©2014 The Gonum Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage distuv\n\nimport (\n\t\"math\"\n\t\"math\/cmplx\"\n\n\t\"golang.org\/x\/exp\/rand\"\n)\n\n\/\/ Weibull distribution. Valid range for x is [0,+∞).\ntype Weibull struct {\n\t\/\/ Shape parameter of the distribution. A value of 1 represents\n\t\/\/ the exponential distribution. A value of 2 represents the\n\t\/\/ Rayleigh distribution. Valid range is (0,+∞).\n\tK float64\n\t\/\/ Scale parameter of the distribution. Valid range is (0,+∞).\n\tLambda float64\n\t\/\/ Source of random numbers\n\tSrc rand.Source\n}\n\n\/\/ CDF computes the value of the cumulative density function at x.\nfunc (w Weibull) CDF(x float64) float64 {\n\tif x < 0 {\n\t\treturn 0\n\t}\n\treturn 1 - cmplx.Abs(cmplx.Exp(w.LogCDF(x)))\n}\n\n\/\/ Entropy returns the entropy of the distribution.\nfunc (w Weibull) Entropy() float64 {\n\treturn eulerGamma*(1-1\/w.K) + math.Log(w.Lambda\/w.K) + 1\n}\n\n\/\/ ExKurtosis returns the excess kurtosis of the distribution.\nfunc (w Weibull) ExKurtosis() float64 {\n\treturn (-6*w.gammaIPow(1, 4) + 12*w.gammaIPow(1, 2)*math.Gamma(1+2\/w.K) - 3*w.gammaIPow(2, 2) - 4*math.Gamma(1+1\/w.K)*math.Gamma(1+3\/w.K) + math.Gamma(1+4\/w.K)) \/ math.Pow(math.Gamma(1+2\/w.K)-w.gammaIPow(1, 2), 2)\n}\n\n\/\/ gammIPow is a shortcut for computing the gamma function to a power.\nfunc (w Weibull) gammaIPow(i, pow float64) float64 {\n\treturn math.Pow(math.Gamma(1+i\/w.K), pow)\n}\n\n\/\/ LogCDF computes the value of the log of the cumulative density function at x.\nfunc (w Weibull) LogCDF(x float64) complex128 {\n\tif x < 0 {\n\t\treturn 0\n\t}\n\treturn cmplx.Log(-1) + complex(-math.Pow(x\/w.Lambda, w.K), 0)\n}\n\n\/\/ LogProb computes the natural logarithm of the value of the probability\n\/\/ density function at x. Zero is returned if x is less than zero.\n\/\/\n\/\/ Special cases occur when x == 0, and the result depends on the shape\n\/\/ parameter as follows:\n\/\/  If 0 < K < 1, LogProb returns +Inf.\n\/\/  If K == 1, LogProb returns 0.\n\/\/  If K > 1, LogProb returns -Inf.\nfunc (w Weibull) LogProb(x float64) float64 {\n\tif x < 0 {\n\t\treturn 0\n\t}\n\treturn math.Log(w.K) - math.Log(w.Lambda) + (w.K-1)*(math.Log(x)-math.Log(w.Lambda)) - math.Pow(x\/w.Lambda, w.K)\n}\n\n\/\/ LogSurvival returns the log of the survival function (complementary CDF) at x.\nfunc (w Weibull) LogSurvival(x float64) float64 {\n\tif x < 0 {\n\t\treturn 0\n\t}\n\treturn -math.Pow(x\/w.Lambda, w.K)\n}\n\n\/\/ Mean returns the mean of the probability distribution.\nfunc (w Weibull) Mean() float64 {\n\treturn w.Lambda * math.Gamma(1+1\/w.K)\n}\n\n\/\/ Median returns the median of the normal distribution.\nfunc (w Weibull) Median() float64 {\n\treturn w.Lambda * math.Pow(ln2, 1\/w.K)\n}\n\n\/\/ Mode returns the mode of the normal distribution.\n\/\/\n\/\/ The mode is NaN in the special case where the K (shape) parameter\n\/\/ is less than 1.\nfunc (w Weibull) Mode() float64 {\n\tif w.K > 1 {\n\t\treturn w.Lambda * math.Pow((w.K-1)\/w.K, 1\/w.K)\n\t} else if w.K == 1 {\n\t\treturn 0\n\t} else {\n\t\treturn math.NaN()\n\t}\n}\n\n\/\/ NumParameters returns the number of parameters in the distribution.\nfunc (Weibull) NumParameters() int {\n\treturn 2\n}\n\n\/\/ Prob computes the value of the probability density function at x.\nfunc (w Weibull) Prob(x float64) float64 {\n\tif x < 0 {\n\t\treturn 0\n\t}\n\treturn math.Exp(w.LogProb(x))\n}\n\n\/\/ Quantile returns the inverse of the cumulative probability distribution.\nfunc (w Weibull) Quantile(p float64) float64 {\n\tif p < 0 || p > 1 {\n\t\tpanic(badPercentile)\n\t}\n\treturn w.Lambda * math.Pow(-math.Log(1-p), 1\/w.K)\n}\n\n\/\/ Rand returns a random sample drawn from the distribution.\nfunc (w Weibull) Rand() float64 {\n\tvar rnd float64\n\tif w.Src == nil {\n\t\trnd = rand.Float64()\n\t} else {\n\t\trnd = rand.New(w.Src).Float64()\n\t}\n\treturn w.Quantile(rnd)\n}\n\n\/\/ Score returns the score function with respect to the parameters of the\n\/\/ distribution at the input location x. The score function is the derivative\n\/\/ of the log-likelihood at x with respect to the parameters\n\/\/  (∂\/∂θ) log(p(x;θ))\n\/\/ If deriv is non-nil, len(deriv) must equal the number of parameters otherwise\n\/\/ Score will panic, and the derivative is stored in-place into deriv. If deriv\n\/\/ is nil a new slice will be allocated and returned.\n\/\/\n\/\/ The order is [∂LogProb \/ ∂K, ∂LogProb \/ ∂λ].\n\/\/\n\/\/ For more information, see https:\/\/en.wikipedia.org\/wiki\/Score_%28statistics%29.\n\/\/\n\/\/ Special cases:\n\/\/  Score(0) = [NaN, NaN]\nfunc (w Weibull) Score(deriv []float64, x float64) []float64 {\n\tif deriv == nil {\n\t\tderiv = make([]float64, w.NumParameters())\n\t}\n\tif len(deriv) != w.NumParameters() {\n\t\tpanic(badLength)\n\t}\n\tif x > 0 {\n\t\tderiv[0] = 1\/w.K + math.Log(x) - math.Log(w.Lambda) - (math.Log(x)-math.Log(w.Lambda))*math.Pow(x\/w.Lambda, w.K)\n\t\tderiv[1] = (w.K * (math.Pow(x\/w.Lambda, w.K) - 1)) \/ w.Lambda\n\t\treturn deriv\n\t}\n\tif x < 0 {\n\t\tderiv[0] = 0\n\t\tderiv[1] = 0\n\t\treturn deriv\n\t}\n\tderiv[0] = math.NaN()\n\tderiv[0] = math.NaN()\n\treturn deriv\n}\n\n\/\/ ScoreInput returns the score function with respect to the input of the\n\/\/ distribution at the input location specified by x. The score function is the\n\/\/ derivative of the log-likelihood\n\/\/  (d\/dx) log(p(x)) .\n\/\/\n\/\/ Special cases:\n\/\/  ScoreInput(0) = NaN\nfunc (w Weibull) ScoreInput(x float64) float64 {\n\tif x > 0 {\n\t\treturn (-w.K*math.Pow(x\/w.Lambda, w.K) + w.K - 1) \/ x\n\t}\n\tif x < 0 {\n\t\treturn 0\n\t}\n\treturn math.NaN()\n}\n\n\/\/ Skewness returns the skewness of the distribution.\nfunc (w Weibull) Skewness() float64 {\n\tstdDev := w.StdDev()\n\tfirstGamma, firstGammaSign := math.Lgamma(1 + 3\/w.K)\n\tlogFirst := firstGamma + 3*(math.Log(w.Lambda)-math.Log(stdDev))\n\tlogSecond := math.Log(3) + math.Log(w.Mean()) + 2*math.Log(stdDev) - 3*math.Log(stdDev)\n\tlogThird := 3 * (math.Log(w.Mean()) - math.Log(stdDev))\n\treturn float64(firstGammaSign)*math.Exp(logFirst) - math.Exp(logSecond) - math.Exp(logThird)\n}\n\n\/\/ StdDev returns the standard deviation of the probability distribution.\nfunc (w Weibull) StdDev() float64 {\n\treturn math.Sqrt(w.Variance())\n}\n\n\/\/ Survival returns the survival function (complementary CDF) at x.\nfunc (w Weibull) Survival(x float64) float64 {\n\treturn math.Exp(w.LogSurvival(x))\n}\n\n\/\/ setParameters modifies the parameters of the distribution.\nfunc (w *Weibull) setParameters(p []Parameter) {\n\tif len(p) != w.NumParameters() {\n\t\tpanic(\"weibull: incorrect number of parameters to set\")\n\t}\n\tif p[0].Name != \"K\" {\n\t\tpanic(\"weibull: \" + panicNameMismatch)\n\t}\n\tif p[1].Name != \"λ\" {\n\t\tpanic(\"weibull: \" + panicNameMismatch)\n\t}\n\tw.K = p[0].Value\n\tw.Lambda = p[1].Value\n}\n\n\/\/ Variance returns the variance of the probability distribution.\nfunc (w Weibull) Variance() float64 {\n\treturn math.Pow(w.Lambda, 2) * (math.Gamma(1+2\/w.K) - w.gammaIPow(1, 2))\n}\n\n\/\/ parameters returns the parameters of the distribution.\nfunc (w Weibull) parameters(p []Parameter) []Parameter {\n\tnParam := w.NumParameters()\n\tif p == nil {\n\t\tp = make([]Parameter, nParam)\n\t} else if len(p) != nParam {\n\t\tpanic(\"weibull: improper parameter length\")\n\t}\n\tp[0].Name = \"K\"\n\tp[0].Value = w.K\n\tp[1].Name = \"λ\"\n\tp[1].Value = w.Lambda\n\treturn p\n\n}\n<commit_msg>stat\/distuv: fix duplicated assignment<commit_after>\/\/ Copyright ©2014 The Gonum Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage distuv\n\nimport (\n\t\"math\"\n\t\"math\/cmplx\"\n\n\t\"golang.org\/x\/exp\/rand\"\n)\n\n\/\/ Weibull distribution. Valid range for x is [0,+∞).\ntype Weibull struct {\n\t\/\/ Shape parameter of the distribution. A value of 1 represents\n\t\/\/ the exponential distribution. A value of 2 represents the\n\t\/\/ Rayleigh distribution. Valid range is (0,+∞).\n\tK float64\n\t\/\/ Scale parameter of the distribution. Valid range is (0,+∞).\n\tLambda float64\n\t\/\/ Source of random numbers\n\tSrc rand.Source\n}\n\n\/\/ CDF computes the value of the cumulative density function at x.\nfunc (w Weibull) CDF(x float64) float64 {\n\tif x < 0 {\n\t\treturn 0\n\t}\n\treturn 1 - cmplx.Abs(cmplx.Exp(w.LogCDF(x)))\n}\n\n\/\/ Entropy returns the entropy of the distribution.\nfunc (w Weibull) Entropy() float64 {\n\treturn eulerGamma*(1-1\/w.K) + math.Log(w.Lambda\/w.K) + 1\n}\n\n\/\/ ExKurtosis returns the excess kurtosis of the distribution.\nfunc (w Weibull) ExKurtosis() float64 {\n\treturn (-6*w.gammaIPow(1, 4) + 12*w.gammaIPow(1, 2)*math.Gamma(1+2\/w.K) - 3*w.gammaIPow(2, 2) - 4*math.Gamma(1+1\/w.K)*math.Gamma(1+3\/w.K) + math.Gamma(1+4\/w.K)) \/ math.Pow(math.Gamma(1+2\/w.K)-w.gammaIPow(1, 2), 2)\n}\n\n\/\/ gammIPow is a shortcut for computing the gamma function to a power.\nfunc (w Weibull) gammaIPow(i, pow float64) float64 {\n\treturn math.Pow(math.Gamma(1+i\/w.K), pow)\n}\n\n\/\/ LogCDF computes the value of the log of the cumulative density function at x.\nfunc (w Weibull) LogCDF(x float64) complex128 {\n\tif x < 0 {\n\t\treturn 0\n\t}\n\treturn cmplx.Log(-1) + complex(-math.Pow(x\/w.Lambda, w.K), 0)\n}\n\n\/\/ LogProb computes the natural logarithm of the value of the probability\n\/\/ density function at x. Zero is returned if x is less than zero.\n\/\/\n\/\/ Special cases occur when x == 0, and the result depends on the shape\n\/\/ parameter as follows:\n\/\/  If 0 < K < 1, LogProb returns +Inf.\n\/\/  If K == 1, LogProb returns 0.\n\/\/  If K > 1, LogProb returns -Inf.\nfunc (w Weibull) LogProb(x float64) float64 {\n\tif x < 0 {\n\t\treturn 0\n\t}\n\treturn math.Log(w.K) - math.Log(w.Lambda) + (w.K-1)*(math.Log(x)-math.Log(w.Lambda)) - math.Pow(x\/w.Lambda, w.K)\n}\n\n\/\/ LogSurvival returns the log of the survival function (complementary CDF) at x.\nfunc (w Weibull) LogSurvival(x float64) float64 {\n\tif x < 0 {\n\t\treturn 0\n\t}\n\treturn -math.Pow(x\/w.Lambda, w.K)\n}\n\n\/\/ Mean returns the mean of the probability distribution.\nfunc (w Weibull) Mean() float64 {\n\treturn w.Lambda * math.Gamma(1+1\/w.K)\n}\n\n\/\/ Median returns the median of the normal distribution.\nfunc (w Weibull) Median() float64 {\n\treturn w.Lambda * math.Pow(ln2, 1\/w.K)\n}\n\n\/\/ Mode returns the mode of the normal distribution.\n\/\/\n\/\/ The mode is NaN in the special case where the K (shape) parameter\n\/\/ is less than 1.\nfunc (w Weibull) Mode() float64 {\n\tif w.K > 1 {\n\t\treturn w.Lambda * math.Pow((w.K-1)\/w.K, 1\/w.K)\n\t} else if w.K == 1 {\n\t\treturn 0\n\t} else {\n\t\treturn math.NaN()\n\t}\n}\n\n\/\/ NumParameters returns the number of parameters in the distribution.\nfunc (Weibull) NumParameters() int {\n\treturn 2\n}\n\n\/\/ Prob computes the value of the probability density function at x.\nfunc (w Weibull) Prob(x float64) float64 {\n\tif x < 0 {\n\t\treturn 0\n\t}\n\treturn math.Exp(w.LogProb(x))\n}\n\n\/\/ Quantile returns the inverse of the cumulative probability distribution.\nfunc (w Weibull) Quantile(p float64) float64 {\n\tif p < 0 || p > 1 {\n\t\tpanic(badPercentile)\n\t}\n\treturn w.Lambda * math.Pow(-math.Log(1-p), 1\/w.K)\n}\n\n\/\/ Rand returns a random sample drawn from the distribution.\nfunc (w Weibull) Rand() float64 {\n\tvar rnd float64\n\tif w.Src == nil {\n\t\trnd = rand.Float64()\n\t} else {\n\t\trnd = rand.New(w.Src).Float64()\n\t}\n\treturn w.Quantile(rnd)\n}\n\n\/\/ Score returns the score function with respect to the parameters of the\n\/\/ distribution at the input location x. The score function is the derivative\n\/\/ of the log-likelihood at x with respect to the parameters\n\/\/  (∂\/∂θ) log(p(x;θ))\n\/\/ If deriv is non-nil, len(deriv) must equal the number of parameters otherwise\n\/\/ Score will panic, and the derivative is stored in-place into deriv. If deriv\n\/\/ is nil a new slice will be allocated and returned.\n\/\/\n\/\/ The order is [∂LogProb \/ ∂K, ∂LogProb \/ ∂λ].\n\/\/\n\/\/ For more information, see https:\/\/en.wikipedia.org\/wiki\/Score_%28statistics%29.\n\/\/\n\/\/ Special cases:\n\/\/  Score(0) = [NaN, NaN]\nfunc (w Weibull) Score(deriv []float64, x float64) []float64 {\n\tif deriv == nil {\n\t\tderiv = make([]float64, w.NumParameters())\n\t}\n\tif len(deriv) != w.NumParameters() {\n\t\tpanic(badLength)\n\t}\n\tif x > 0 {\n\t\tderiv[0] = 1\/w.K + math.Log(x) - math.Log(w.Lambda) - (math.Log(x)-math.Log(w.Lambda))*math.Pow(x\/w.Lambda, w.K)\n\t\tderiv[1] = (w.K * (math.Pow(x\/w.Lambda, w.K) - 1)) \/ w.Lambda\n\t\treturn deriv\n\t}\n\tif x < 0 {\n\t\tderiv[0] = 0\n\t\tderiv[1] = 0\n\t\treturn deriv\n\t}\n\tderiv[0] = math.NaN()\n\tderiv[1] = math.NaN()\n\treturn deriv\n}\n\n\/\/ ScoreInput returns the score function with respect to the input of the\n\/\/ distribution at the input location specified by x. The score function is the\n\/\/ derivative of the log-likelihood\n\/\/  (d\/dx) log(p(x)) .\n\/\/\n\/\/ Special cases:\n\/\/  ScoreInput(0) = NaN\nfunc (w Weibull) ScoreInput(x float64) float64 {\n\tif x > 0 {\n\t\treturn (-w.K*math.Pow(x\/w.Lambda, w.K) + w.K - 1) \/ x\n\t}\n\tif x < 0 {\n\t\treturn 0\n\t}\n\treturn math.NaN()\n}\n\n\/\/ Skewness returns the skewness of the distribution.\nfunc (w Weibull) Skewness() float64 {\n\tstdDev := w.StdDev()\n\tfirstGamma, firstGammaSign := math.Lgamma(1 + 3\/w.K)\n\tlogFirst := firstGamma + 3*(math.Log(w.Lambda)-math.Log(stdDev))\n\tlogSecond := math.Log(3) + math.Log(w.Mean()) + 2*math.Log(stdDev) - 3*math.Log(stdDev)\n\tlogThird := 3 * (math.Log(w.Mean()) - math.Log(stdDev))\n\treturn float64(firstGammaSign)*math.Exp(logFirst) - math.Exp(logSecond) - math.Exp(logThird)\n}\n\n\/\/ StdDev returns the standard deviation of the probability distribution.\nfunc (w Weibull) StdDev() float64 {\n\treturn math.Sqrt(w.Variance())\n}\n\n\/\/ Survival returns the survival function (complementary CDF) at x.\nfunc (w Weibull) Survival(x float64) float64 {\n\treturn math.Exp(w.LogSurvival(x))\n}\n\n\/\/ setParameters modifies the parameters of the distribution.\nfunc (w *Weibull) setParameters(p []Parameter) {\n\tif len(p) != w.NumParameters() {\n\t\tpanic(\"weibull: incorrect number of parameters to set\")\n\t}\n\tif p[0].Name != \"K\" {\n\t\tpanic(\"weibull: \" + panicNameMismatch)\n\t}\n\tif p[1].Name != \"λ\" {\n\t\tpanic(\"weibull: \" + panicNameMismatch)\n\t}\n\tw.K = p[0].Value\n\tw.Lambda = p[1].Value\n}\n\n\/\/ Variance returns the variance of the probability distribution.\nfunc (w Weibull) Variance() float64 {\n\treturn math.Pow(w.Lambda, 2) * (math.Gamma(1+2\/w.K) - w.gammaIPow(1, 2))\n}\n\n\/\/ parameters returns the parameters of the distribution.\nfunc (w Weibull) parameters(p []Parameter) []Parameter {\n\tnParam := w.NumParameters()\n\tif p == nil {\n\t\tp = make([]Parameter, nParam)\n\t} else if len(p) != nParam {\n\t\tpanic(\"weibull: improper parameter length\")\n\t}\n\tp[0].Name = \"K\"\n\tp[0].Value = w.K\n\tp[1].Name = \"λ\"\n\tp[1].Value = w.Lambda\n\treturn p\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\n\t\"github.com\/containernetworking\/cni\/pkg\/skel\"\n\t\"github.com\/containernetworking\/cni\/pkg\/version\"\n\t\"github.com\/containernetworking\/plugins\/pkg\/ip\"\n\t\"github.com\/containernetworking\/plugins\/pkg\/ns\"\n\t\"github.com\/vishvananda\/netlink\"\n\n\t\"github.com\/openvswitch\/ovn-kubernetes\/go-controller\/pkg\/kube\"\n\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n)\n\nconst defaultVethMTU = 1400\n\nfunc renameLink(curName, newName string) error {\n\tlink, err := netlink.LinkByName(curName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := netlink.LinkSetDown(link); err != nil {\n\t\treturn err\n\t}\n\tif err := netlink.LinkSetName(link, newName); err != nil {\n\t\treturn err\n\t}\n\tif err := netlink.LinkSetUp(link); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc setupInterface(netns ns.NetNS, containerID, ifName, macAddress, ipAddress, gatewayIP string) (string, error) {\n\tvar hostIfaceName string\n\n\terr := netns.Do(func(hostNS ns.NetNS) error {\n\t\t\/\/ create the veth pair in the container and move host end into host netns\n\t\thostVeth, containerVeth, err := ip.SetupVeth(ifName, defaultVethMTU, hostNS)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcontIfaceName := containerVeth.Name\n\n\t\tlink, err := netlink.LinkByName(contIfaceName)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to lookup %s: %v\", contIfaceName, err)\n\t\t}\n\n\t\thwAddr, err := net.ParseMAC(macAddress)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse mac address for %s: %v\", contIfaceName, err)\n\t\t}\n\t\terr = netlink.LinkSetHardwareAddr(link, hwAddr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to add mac address %s to %s: %v\", macAddress, contIfaceName, err)\n\t\t}\n\n\t\taddr, err := netlink.ParseAddr(ipAddress)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = netlink.AddrAdd(link, addr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to add IP addr %s to %s: %v\", ipAddress, contIfaceName, err)\n\t\t}\n\n\t\tgw := net.ParseIP(gatewayIP)\n\t\tif gw == nil {\n\t\t\treturn fmt.Errorf(\"parse ip of gateway failed\")\n\t\t}\n\t\terr = ip.AddRoute(nil, gw, link)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\thostIfaceName = hostVeth.Name\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t\/\/ rename the host end of veth pair\n\tnewHostIfaceName := containerID[:15]\n\tif err := renameLink(hostIfaceName, newHostIfaceName); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to rename %s to %s: %v\", hostIfaceName, newHostIfaceName, err)\n\t}\n\n\treturn newHostIfaceName, nil\n}\n\nfunc argString2Map(args string) (map[string]string, error) {\n\targsMap := make(map[string]string)\n\n\tpairs := strings.Split(args, \";\")\n\tfor _, pair := range pairs {\n\t\tkv := strings.Split(pair, \"=\")\n\t\tif len(kv) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"ARGS: invalid pair %q\", pair)\n\t\t}\n\t\tkeyString := kv[0]\n\t\tvalueString := kv[1]\n\t\targsMap[keyString] = valueString\n\t}\n\n\treturn argsMap, nil\n}\n\nfunc cmdAdd(args *skel.CmdArgs) error {\n\targsMap, err := argString2Map(args.Args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnamespace := argsMap[\"K8S_POD_NAMESPACE\"]\n\tpodName := argsMap[\"K8S_POD_NAME\"]\n\tif namespace == \"\" || podName == \"\" {\n\t\treturn fmt.Errorf(\"required CNI variable missing\")\n\t}\n\n\tovsArgs := []string{\n\t\t\"--if-exists\", \"get\", \"Open_vSwitch\",\n\t\t\".\", \"external_ids:k8s-api-server\",\n\t}\n\tout, err := exec.Command(\"ovs-vsctl\", ovsArgs...).CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get K8S_API_SERVER\")\n\t}\n\tk8sAPIServer := strings.Trim(strings.TrimSpace(string(out)), \"\\\"\")\n\tif !strings.HasPrefix(k8sAPIServer, \"http\") {\n\t\tk8sAPIServer = fmt.Sprintf(\"http:\/\/%s\", k8sAPIServer)\n\t}\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(k8sAPIServer, \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tkubecli := &kube.Kube{KClient: clientset}\n\n\t\/\/ Get the IP address and MAC address from the API server.\n\t\/\/ Wait for a maximum of 3 seconds with a retry every 0.1 second.\n\tvar annotation map[string]string\n\tfor cnt := 0; cnt < 30; cnt++ {\n\t\tannotation, err = kubecli.GetAnnotationsOnPod(namespace, podName)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := annotation[\"ovn\"]; ok {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif annotation == nil {\n\t\treturn fmt.Errorf(\"failed to get pod annotation\")\n\t}\n\n\tovnAnnotation, ok := annotation[\"ovn\"]\n\tif !ok {\n\t\treturn fmt.Errorf(\"failed to get annotation of ovn\")\n\t}\n\n\tvar ovnAnnotatedMap map[string]string\n\terr = json.Unmarshal([]byte(ovnAnnotation), &ovnAnnotatedMap)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unmarshal ovn annotation failed\")\n\t}\n\n\tipAddress := ovnAnnotatedMap[\"ip_address\"]\n\tmacAddress := ovnAnnotatedMap[\"mac_address\"]\n\tgatewayIP := ovnAnnotatedMap[\"gateway_ip\"]\n\n\tif ipAddress == \"\" || macAddress == \"\" || gatewayIP == \"\" {\n\t\treturn fmt.Errorf(\"failed in pod annotation key extract\")\n\t}\n\n\tnetns, err := ns.GetNS(args.Netns)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open netns %q: %v\", args.Netns, err)\n\t}\n\tdefer netns.Close()\n\n\tvethOutside, err := setupInterface(netns, args.ContainerID, args.IfName, macAddress, ipAddress, gatewayIP)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tifaceID := fmt.Sprintf(\"%s_%s\", namespace, podName)\n\n\tovsArgs = []string{\n\t\t\"add-port\", \"br-int\", vethOutside, \"--\", \"set\",\n\t\t\"interface\", vethOutside,\n\t\tfmt.Sprintf(\"external_ids:attached_mac=%s\", macAddress),\n\t\tfmt.Sprintf(\"external_ids:iface-id=%s\", ifaceID),\n\t\tfmt.Sprintf(\"external_ids:ip_address=%s\", ipAddress),\n\t}\n\tout, err = exec.Command(\"ovs-vsctl\", ovsArgs...).CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failure in plugging pod interface: %v\\n  %q\", err, string(out))\n\t}\n\n\t\/\/ TODO: conform with cni specification\n\tresult := fmt.Sprintf(\"{\\\"ip_address\\\":\\\"%s\\\", \\\"mac_address\\\":\\\"%s\\\", \\\"gateway_ip\\\": \\\"%s\\\"}\", ipAddress, macAddress, gatewayIP)\n\t_, err = os.Stdout.Write([]byte(result))\n\n\treturn err\n}\n\nfunc cmdDel(args *skel.CmdArgs) error {\n\tifaceName := args.ContainerID[:15]\n\tovsArgs := []string{\n\t\t\"del-port\", \"br-int\", ifaceName,\n\t}\n\tout, err := exec.Command(\"ovs-vsctl\", ovsArgs...).CombinedOutput()\n\tif err != nil && !strings.Contains(string(out), \"no port named\") {\n\t\t\/\/ DEL should be idempotent; don't return an error just log it\n\t\tlogrus.Warningf(\"failed to delete OVS port %s: %v\\n  %q\", ifaceName, err, string(out))\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\tskel.PluginMain(cmdAdd, cmdDel, version.All)\n}\n<commit_msg>go-overlay: conform to CNI spec when returning the ADD result<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\n\t\"github.com\/containernetworking\/cni\/pkg\/skel\"\n\t\"github.com\/containernetworking\/cni\/pkg\/types\"\n\t\"github.com\/containernetworking\/cni\/pkg\/types\/current\"\n\t\"github.com\/containernetworking\/cni\/pkg\/version\"\n\t\"github.com\/containernetworking\/plugins\/pkg\/ip\"\n\t\"github.com\/containernetworking\/plugins\/pkg\/ns\"\n\t\"github.com\/vishvananda\/netlink\"\n\n\t\"github.com\/openvswitch\/ovn-kubernetes\/go-controller\/pkg\/kube\"\n\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n)\n\nconst defaultVethMTU = 1400\n\nfunc renameLink(curName, newName string) error {\n\tlink, err := netlink.LinkByName(curName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := netlink.LinkSetDown(link); err != nil {\n\t\treturn err\n\t}\n\tif err := netlink.LinkSetName(link, newName); err != nil {\n\t\treturn err\n\t}\n\tif err := netlink.LinkSetUp(link); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc setupInterface(netns ns.NetNS, containerID, ifName, macAddress, ipAddress, gatewayIP string) (*current.Interface, *current.Interface, error) {\n\thostIface := &current.Interface{}\n\tcontIface := &current.Interface{}\n\n\tvar oldHostVethName string\n\terr := netns.Do(func(hostNS ns.NetNS) error {\n\t\t\/\/ create the veth pair in the container and move host end into host netns\n\t\thostVeth, containerVeth, err := ip.SetupVeth(ifName, defaultVethMTU, hostNS)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thostIface.Mac = hostVeth.HardwareAddr.String()\n\t\tcontIface.Name = containerVeth.Name\n\n\t\tlink, err := netlink.LinkByName(contIface.Name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to lookup %s: %v\", contIface.Name, err)\n\t\t}\n\n\t\thwAddr, err := net.ParseMAC(macAddress)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to parse mac address for %s: %v\", contIface.Name, err)\n\t\t}\n\t\terr = netlink.LinkSetHardwareAddr(link, hwAddr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to add mac address %s to %s: %v\", macAddress, contIface.Name, err)\n\t\t}\n\t\tcontIface.Mac = macAddress\n\t\tcontIface.Sandbox = netns.Path()\n\n\t\taddr, err := netlink.ParseAddr(ipAddress)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = netlink.AddrAdd(link, addr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to add IP addr %s to %s: %v\", ipAddress, contIface.Name, err)\n\t\t}\n\n\t\tgw := net.ParseIP(gatewayIP)\n\t\tif gw == nil {\n\t\t\treturn fmt.Errorf(\"parse ip of gateway failed\")\n\t\t}\n\t\terr = ip.AddRoute(nil, gw, link)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\toldHostVethName = hostVeth.Name\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ rename the host end of veth pair\n\thostIface.Name = containerID[:15]\n\tif err := renameLink(oldHostVethName, hostIface.Name); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to rename %s to %s: %v\", oldHostVethName, hostIface.Name, err)\n\t}\n\n\treturn hostIface, contIface, nil\n}\n\nfunc argString2Map(args string) (map[string]string, error) {\n\targsMap := make(map[string]string)\n\n\tpairs := strings.Split(args, \";\")\n\tfor _, pair := range pairs {\n\t\tkv := strings.Split(pair, \"=\")\n\t\tif len(kv) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"ARGS: invalid pair %q\", pair)\n\t\t}\n\t\tkeyString := kv[0]\n\t\tvalueString := kv[1]\n\t\targsMap[keyString] = valueString\n\t}\n\n\treturn argsMap, nil\n}\n\nfunc cmdAdd(args *skel.CmdArgs) error {\n\tconf := &types.NetConf{}\n\tif err := json.Unmarshal(args.StdinData, conf); err != nil {\n\t\treturn fmt.Errorf(\"failed to load netconf: %v\", err)\n\t}\n\n\targsMap, err := argString2Map(args.Args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnamespace := argsMap[\"K8S_POD_NAMESPACE\"]\n\tpodName := argsMap[\"K8S_POD_NAME\"]\n\tif namespace == \"\" || podName == \"\" {\n\t\treturn fmt.Errorf(\"required CNI variable missing\")\n\t}\n\n\tovsArgs := []string{\n\t\t\"--if-exists\", \"get\", \"Open_vSwitch\",\n\t\t\".\", \"external_ids:k8s-api-server\",\n\t}\n\tout, err := exec.Command(\"ovs-vsctl\", ovsArgs...).CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get K8S_API_SERVER\")\n\t}\n\tk8sAPIServer := strings.Trim(strings.TrimSpace(string(out)), \"\\\"\")\n\tif !strings.HasPrefix(k8sAPIServer, \"http\") {\n\t\tk8sAPIServer = fmt.Sprintf(\"http:\/\/%s\", k8sAPIServer)\n\t}\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(k8sAPIServer, \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tkubecli := &kube.Kube{KClient: clientset}\n\n\t\/\/ Get the IP address and MAC address from the API server.\n\t\/\/ Wait for a maximum of 3 seconds with a retry every 0.1 second.\n\tvar annotation map[string]string\n\tfor cnt := 0; cnt < 30; cnt++ {\n\t\tannotation, err = kubecli.GetAnnotationsOnPod(namespace, podName)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := annotation[\"ovn\"]; ok {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif annotation == nil {\n\t\treturn fmt.Errorf(\"failed to get pod annotation\")\n\t}\n\n\tovnAnnotation, ok := annotation[\"ovn\"]\n\tif !ok {\n\t\treturn fmt.Errorf(\"failed to get annotation of ovn\")\n\t}\n\n\tvar ovnAnnotatedMap map[string]string\n\terr = json.Unmarshal([]byte(ovnAnnotation), &ovnAnnotatedMap)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unmarshal ovn annotation failed\")\n\t}\n\n\tipAddress := ovnAnnotatedMap[\"ip_address\"]\n\tmacAddress := ovnAnnotatedMap[\"mac_address\"]\n\tgatewayIP := ovnAnnotatedMap[\"gateway_ip\"]\n\n\tif ipAddress == \"\" || macAddress == \"\" || gatewayIP == \"\" {\n\t\treturn fmt.Errorf(\"failed in pod annotation key extract\")\n\t}\n\n\tnetns, err := ns.GetNS(args.Netns)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open netns %q: %v\", args.Netns, err)\n\t}\n\tdefer netns.Close()\n\n\thostIface, contIface, err := setupInterface(netns, args.ContainerID, args.IfName, macAddress, ipAddress, gatewayIP)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tifaceID := fmt.Sprintf(\"%s_%s\", namespace, podName)\n\n\tovsArgs = []string{\n\t\t\"add-port\", \"br-int\", hostIface.Name, \"--\", \"set\",\n\t\t\"interface\", hostIface.Name,\n\t\tfmt.Sprintf(\"external_ids:attached_mac=%s\", macAddress),\n\t\tfmt.Sprintf(\"external_ids:iface-id=%s\", ifaceID),\n\t\tfmt.Sprintf(\"external_ids:ip_address=%s\", ipAddress),\n\t}\n\tout, err = exec.Command(\"ovs-vsctl\", ovsArgs...).CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failure in plugging pod interface: %v\\n  %q\", err, string(out))\n\t}\n\n\t\/\/ Build the result structure to pass back to the runtime\n\taddr, addrNet, err := net.ParseCIDR(ipAddress)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse IP address %q: %v\", ipAddress, err)\n\t}\n\tipVersion := \"6\"\n\tif addr.To4() != nil {\n\t\tipVersion = \"4\"\n\t}\n\tresult := &current.Result{\n\t\tInterfaces: []*current.Interface{hostIface, contIface},\n\t\tIPs: []*current.IPConfig{\n\t\t\t{\n\t\t\t\tVersion:   ipVersion,\n\t\t\t\tInterface: current.Int(1),\n\t\t\t\tAddress:   net.IPNet{IP: addr, Mask: addrNet.Mask},\n\t\t\t\tGateway:   net.ParseIP(gatewayIP),\n\t\t\t},\n\t\t},\n\t}\n\n\treturn types.PrintResult(result, conf.CNIVersion)\n}\n\nfunc cmdDel(args *skel.CmdArgs) error {\n\tifaceName := args.ContainerID[:15]\n\tovsArgs := []string{\n\t\t\"del-port\", \"br-int\", ifaceName,\n\t}\n\tout, err := exec.Command(\"ovs-vsctl\", ovsArgs...).CombinedOutput()\n\tif err != nil && !strings.Contains(string(out), \"no port named\") {\n\t\t\/\/ DEL should be idempotent; don't return an error just log it\n\t\tlogrus.Warningf(\"failed to delete OVS port %s: %v\\n  %q\", ifaceName, err, string(out))\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\tskel.PluginMain(cmdAdd, cmdDel, version.All)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright IBM Corp. 2017 All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\t\t http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage sw\n\nimport (\n\t\"crypto\/ecdsa\"\n\t\"crypto\/elliptic\"\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"crypto\/x509\"\n\t\"math\/big\"\n\t\"testing\"\n\n\t\"github.com\/hyperledger\/fabric\/bccsp\/utils\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestSignECDSABadParameter(t *testing.T) {\n\t\/\/ Generate a key\n\tlowLevelKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tassert.NoError(t, err)\n\n\t\/\/ Induce an error on the underlying ecdsa algorithm\n\tmsg := []byte(\"hello world\")\n\toldN := lowLevelKey.Params().N\n\tdefer func() { lowLevelKey.Params().N = oldN }()\n\tlowLevelKey.Params().N = big.NewInt(0)\n\t_, err = signECDSA(lowLevelKey, msg, nil)\n\tassert.Error(t, err)\n\tassert.Contains(t, err.Error(), \"zero parameter\")\n}\n\nfunc TestVerifyECDSA(t *testing.T) {\n\tt.Parallel()\n\n\t\/\/ Generate a key\n\tlowLevelKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tassert.NoError(t, err)\n\n\tmsg := []byte(\"hello world\")\n\tsigma, err := signECDSA(lowLevelKey, msg, nil)\n\tassert.NoError(t, err)\n\n\tvalid, err := verifyECDSA(&lowLevelKey.PublicKey, sigma, msg, nil)\n\tassert.NoError(t, err)\n\tassert.True(t, valid)\n\n\t_, err = verifyECDSA(&lowLevelKey.PublicKey, nil, msg, nil)\n\tassert.Error(t, err)\n\tassert.Contains(t, err.Error(), \"Failed unmashalling signature [\")\n\n\tR, S, err := utils.UnmarshalECDSASignature(sigma)\n\tassert.NoError(t, err)\n\tS.Add(utils.GetCurveHalfOrdersAt(elliptic.P256()), big.NewInt(1))\n\tsigmaWrongS, err := utils.MarshalECDSASignature(R, S)\n\tassert.NoError(t, err)\n\t_, err = verifyECDSA(&lowLevelKey.PublicKey, sigmaWrongS, msg, nil)\n\tassert.Error(t, err)\n\tassert.Contains(t, err.Error(), \"Invalid S. Must be smaller than half the order [\")\n}\n\nfunc TestEcdsaSignerSign(t *testing.T) {\n\tt.Parallel()\n\n\tsigner := &ecdsaSigner{}\n\tverifierPrivateKey := &ecdsaPrivateKeyVerifier{}\n\tverifierPublicKey := &ecdsaPublicKeyKeyVerifier{}\n\n\t\/\/ Generate a key\n\tlowLevelKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tassert.NoError(t, err)\n\tk := &ecdsaPrivateKey{lowLevelKey}\n\tpk, err := k.PublicKey()\n\tassert.NoError(t, err)\n\n\t\/\/ Sign\n\tmsg := []byte(\"Hello World\")\n\tsigma, err := signer.Sign(k, msg, nil)\n\tassert.NoError(t, err)\n\tassert.NotNil(t, sigma)\n\n\t\/\/ Verify\n\tvalid, err := verifyECDSA(&lowLevelKey.PublicKey, sigma, msg, nil)\n\tassert.NoError(t, err)\n\tassert.True(t, valid)\n\n\tvalid, err = verifierPrivateKey.Verify(k, sigma, msg, nil)\n\tassert.NoError(t, err)\n\tassert.True(t, valid)\n\n\tvalid, err = verifierPublicKey.Verify(pk, sigma, msg, nil)\n\tassert.NoError(t, err)\n\tassert.True(t, valid)\n}\n\nfunc TestEcdsaPrivateKey(t *testing.T) {\n\tt.Parallel()\n\n\tlowLevelKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tassert.NoError(t, err)\n\tk := &ecdsaPrivateKey{lowLevelKey}\n\n\tassert.False(t, k.Symmetric())\n\tassert.True(t, k.Private())\n\n\t_, err = k.Bytes()\n\tassert.Error(t, err)\n\tassert.Contains(t, err.Error(), \"Not supported.\")\n\n\tk.privKey = nil\n\tski := k.SKI()\n\tassert.Nil(t, ski)\n\n\tk.privKey = lowLevelKey\n\tski = k.SKI()\n\traw := elliptic.Marshal(k.privKey.Curve, k.privKey.PublicKey.X, k.privKey.PublicKey.Y)\n\thash := sha256.New()\n\thash.Write(raw)\n\tski2 := hash.Sum(nil)\n\tassert.Equal(t, ski2, ski, \"SKI is not computed in the right way.\")\n\n\tpk, err := k.PublicKey()\n\tassert.NoError(t, err)\n\tassert.NotNil(t, pk)\n\tecdsaPK, ok := pk.(*ecdsaPublicKey)\n\tassert.True(t, ok)\n\tassert.Equal(t, &lowLevelKey.PublicKey, ecdsaPK.pubKey)\n}\n\nfunc TestEcdsaPublicKey(t *testing.T) {\n\tt.Parallel()\n\n\tlowLevelKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tassert.NoError(t, err)\n\tk := &ecdsaPublicKey{&lowLevelKey.PublicKey}\n\n\tassert.False(t, k.Symmetric())\n\tassert.False(t, k.Private())\n\n\tk.pubKey = nil\n\tski := k.SKI()\n\tassert.Nil(t, ski)\n\n\tk.pubKey = &lowLevelKey.PublicKey\n\tski = k.SKI()\n\traw := elliptic.Marshal(k.pubKey.Curve, k.pubKey.X, k.pubKey.Y)\n\thash := sha256.New()\n\thash.Write(raw)\n\tski2 := hash.Sum(nil)\n\tassert.Equal(t, ski, ski2, \"SKI is not computed in the right way.\")\n\n\tpk, err := k.PublicKey()\n\tassert.NoError(t, err)\n\tassert.Equal(t, k, pk)\n\n\tbytes, err := k.Bytes()\n\tassert.NoError(t, err)\n\tbytes2, err := x509.MarshalPKIXPublicKey(k.pubKey)\n\tassert.NoError(t, err)\n\tassert.Equal(t, bytes2, bytes, \"bytes are not computed in the right way.\")\n\n\tinvalidCurve := &elliptic.CurveParams{Name: \"P-Invalid\"}\n\tinvalidCurve.BitSize = 1024\n\tk.pubKey = &ecdsa.PublicKey{Curve: invalidCurve, X: big.NewInt(1), Y: big.NewInt(1)}\n\t_, err = k.Bytes()\n\tassert.Error(t, err)\n\tassert.Contains(t, err.Error(), \"Failed marshalling key [\")\n}\n<commit_msg>Stop modifying curve held in crypto package var<commit_after>\/*\nCopyright IBM Corp. 2017 All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\t\t http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage sw\n\nimport (\n\t\"crypto\/ecdsa\"\n\t\"crypto\/elliptic\"\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"crypto\/x509\"\n\t\"math\/big\"\n\t\"testing\"\n\n\t\"github.com\/hyperledger\/fabric\/bccsp\/utils\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestSignECDSABadParameter(t *testing.T) {\n\t\/\/ Generate a key\n\tlowLevelKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tassert.NoError(t, err)\n\n\t\/\/ Induce an error on the underlying ecdsa algorithm\n\tcurve := *elliptic.P256().Params()\n\tcurve.N = big.NewInt(0)\n\tlowLevelKey.Curve = &curve\n\n\t_, err = signECDSA(lowLevelKey, []byte(\"hello world\"), nil)\n\tassert.Error(t, err)\n\tassert.Contains(t, err.Error(), \"zero parameter\")\n}\n\nfunc TestVerifyECDSA(t *testing.T) {\n\tt.Parallel()\n\n\t\/\/ Generate a key\n\tlowLevelKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tassert.NoError(t, err)\n\n\tmsg := []byte(\"hello world\")\n\tsigma, err := signECDSA(lowLevelKey, msg, nil)\n\tassert.NoError(t, err)\n\n\tvalid, err := verifyECDSA(&lowLevelKey.PublicKey, sigma, msg, nil)\n\tassert.NoError(t, err)\n\tassert.True(t, valid)\n\n\t_, err = verifyECDSA(&lowLevelKey.PublicKey, nil, msg, nil)\n\tassert.Error(t, err)\n\tassert.Contains(t, err.Error(), \"Failed unmashalling signature [\")\n\n\tR, S, err := utils.UnmarshalECDSASignature(sigma)\n\tassert.NoError(t, err)\n\tS.Add(utils.GetCurveHalfOrdersAt(elliptic.P256()), big.NewInt(1))\n\tsigmaWrongS, err := utils.MarshalECDSASignature(R, S)\n\tassert.NoError(t, err)\n\t_, err = verifyECDSA(&lowLevelKey.PublicKey, sigmaWrongS, msg, nil)\n\tassert.Error(t, err)\n\tassert.Contains(t, err.Error(), \"Invalid S. Must be smaller than half the order [\")\n}\n\nfunc TestEcdsaSignerSign(t *testing.T) {\n\tt.Parallel()\n\n\tsigner := &ecdsaSigner{}\n\tverifierPrivateKey := &ecdsaPrivateKeyVerifier{}\n\tverifierPublicKey := &ecdsaPublicKeyKeyVerifier{}\n\n\t\/\/ Generate a key\n\tlowLevelKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tassert.NoError(t, err)\n\tk := &ecdsaPrivateKey{lowLevelKey}\n\tpk, err := k.PublicKey()\n\tassert.NoError(t, err)\n\n\t\/\/ Sign\n\tmsg := []byte(\"Hello World\")\n\tsigma, err := signer.Sign(k, msg, nil)\n\tassert.NoError(t, err)\n\tassert.NotNil(t, sigma)\n\n\t\/\/ Verify\n\tvalid, err := verifyECDSA(&lowLevelKey.PublicKey, sigma, msg, nil)\n\tassert.NoError(t, err)\n\tassert.True(t, valid)\n\n\tvalid, err = verifierPrivateKey.Verify(k, sigma, msg, nil)\n\tassert.NoError(t, err)\n\tassert.True(t, valid)\n\n\tvalid, err = verifierPublicKey.Verify(pk, sigma, msg, nil)\n\tassert.NoError(t, err)\n\tassert.True(t, valid)\n}\n\nfunc TestEcdsaPrivateKey(t *testing.T) {\n\tt.Parallel()\n\n\tlowLevelKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tassert.NoError(t, err)\n\tk := &ecdsaPrivateKey{lowLevelKey}\n\n\tassert.False(t, k.Symmetric())\n\tassert.True(t, k.Private())\n\n\t_, err = k.Bytes()\n\tassert.Error(t, err)\n\tassert.Contains(t, err.Error(), \"Not supported.\")\n\n\tk.privKey = nil\n\tski := k.SKI()\n\tassert.Nil(t, ski)\n\n\tk.privKey = lowLevelKey\n\tski = k.SKI()\n\traw := elliptic.Marshal(k.privKey.Curve, k.privKey.PublicKey.X, k.privKey.PublicKey.Y)\n\thash := sha256.New()\n\thash.Write(raw)\n\tski2 := hash.Sum(nil)\n\tassert.Equal(t, ski2, ski, \"SKI is not computed in the right way.\")\n\n\tpk, err := k.PublicKey()\n\tassert.NoError(t, err)\n\tassert.NotNil(t, pk)\n\tecdsaPK, ok := pk.(*ecdsaPublicKey)\n\tassert.True(t, ok)\n\tassert.Equal(t, &lowLevelKey.PublicKey, ecdsaPK.pubKey)\n}\n\nfunc TestEcdsaPublicKey(t *testing.T) {\n\tt.Parallel()\n\n\tlowLevelKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tassert.NoError(t, err)\n\tk := &ecdsaPublicKey{&lowLevelKey.PublicKey}\n\n\tassert.False(t, k.Symmetric())\n\tassert.False(t, k.Private())\n\n\tk.pubKey = nil\n\tski := k.SKI()\n\tassert.Nil(t, ski)\n\n\tk.pubKey = &lowLevelKey.PublicKey\n\tski = k.SKI()\n\traw := elliptic.Marshal(k.pubKey.Curve, k.pubKey.X, k.pubKey.Y)\n\thash := sha256.New()\n\thash.Write(raw)\n\tski2 := hash.Sum(nil)\n\tassert.Equal(t, ski, ski2, \"SKI is not computed in the right way.\")\n\n\tpk, err := k.PublicKey()\n\tassert.NoError(t, err)\n\tassert.Equal(t, k, pk)\n\n\tbytes, err := k.Bytes()\n\tassert.NoError(t, err)\n\tbytes2, err := x509.MarshalPKIXPublicKey(k.pubKey)\n\tassert.NoError(t, err)\n\tassert.Equal(t, bytes2, bytes, \"bytes are not computed in the right way.\")\n\n\tinvalidCurve := &elliptic.CurveParams{Name: \"P-Invalid\"}\n\tinvalidCurve.BitSize = 1024\n\tk.pubKey = &ecdsa.PublicKey{Curve: invalidCurve, X: big.NewInt(1), Y: big.NewInt(1)}\n\t_, err = k.Bytes()\n\tassert.Error(t, err)\n\tassert.Contains(t, err.Error(), \"Failed marshalling key [\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package router\n\nimport (\n\t\"sync\/atomic\"\n\n\t\"github.com\/AsynkronIT\/protoactor-go\/actor\"\n)\n\ntype roundRobinGroupRouter struct {\n\tGroupRouter\n}\n\ntype roundRobinPoolRouter struct {\n\tPoolRouter\n}\n\ntype roundRobinState struct {\n\tindex   int32\n\troutees *actor.PIDSet\n\tvalues  []actor.PID\n}\n\nfunc (state *roundRobinState) SetRoutees(routees *actor.PIDSet) {\n\tstate.routees = routees\n\tstate.values = routees.Values()\n}\n\nfunc (state *roundRobinState) GetRoutees() *actor.PIDSet {\n\treturn state.routees\n}\n\nfunc (state *roundRobinState) RouteMessage(message interface{}, sender *actor.PID) {\n\tpid := roundRobinRoutee(&state.index, state.values)\n\tpid.Request(message, sender)\n}\n\nfunc NewRoundRobinPool(size int) *actor.Props {\n\treturn actor.FromSpawnFunc(spawner(&roundRobinPoolRouter{PoolRouter{PoolSize: size}}))\n}\n\nfunc NewRoundRobinGroup(routees ...*actor.PID) *actor.Props {\n\treturn actor.FromSpawnFunc(spawner(&roundRobinGroupRouter{GroupRouter{Routees: actor.NewPIDSet(routees...)}}))\n}\n\nfunc (config *roundRobinPoolRouter) CreateRouterState() Interface {\n\treturn &roundRobinState{}\n}\n\nfunc (config *roundRobinGroupRouter) CreateRouterState() Interface {\n\treturn &roundRobinState{}\n}\n\nfunc roundRobinRoutee(index *int32, routees []actor.PID) actor.PID {\n\ti := int(atomic.AddInt32(index, 1))\n\tmod := len(routees)\n\troutee := routees[i%mod]\n\treturn routee\n}\n<commit_msg>fix roundrobin_router when access the maximum of int32 will produce a minus index value which will cause panic<commit_after>package router\n\nimport (\n\t\"sync\/atomic\"\n\n\t\"github.com\/AsynkronIT\/protoactor-go\/actor\"\n)\n\ntype roundRobinGroupRouter struct {\n\tGroupRouter\n}\n\ntype roundRobinPoolRouter struct {\n\tPoolRouter\n}\n\ntype roundRobinState struct {\n\tindex   int32\n\troutees *actor.PIDSet\n\tvalues  []actor.PID\n}\n\nfunc (state *roundRobinState) SetRoutees(routees *actor.PIDSet) {\n\tstate.routees = routees\n\tstate.values = routees.Values()\n}\n\nfunc (state *roundRobinState) GetRoutees() *actor.PIDSet {\n\treturn state.routees\n}\n\nfunc (state *roundRobinState) RouteMessage(message interface{}, sender *actor.PID) {\n\tpid := roundRobinRoutee(&state.index, state.values)\n\tpid.Request(message, sender)\n}\n\nfunc NewRoundRobinPool(size int) *actor.Props {\n\treturn actor.FromSpawnFunc(spawner(&roundRobinPoolRouter{PoolRouter{PoolSize: size}}))\n}\n\nfunc NewRoundRobinGroup(routees ...*actor.PID) *actor.Props {\n\treturn actor.FromSpawnFunc(spawner(&roundRobinGroupRouter{GroupRouter{Routees: actor.NewPIDSet(routees...)}}))\n}\n\nfunc (config *roundRobinPoolRouter) CreateRouterState() Interface {\n\treturn &roundRobinState{}\n}\n\nfunc (config *roundRobinGroupRouter) CreateRouterState() Interface {\n\treturn &roundRobinState{}\n}\n\nfunc roundRobinRoutee(index *int32, routees []actor.PID) actor.PID {\n\ti := int(atomic.AddInt32(index, 1))\n\tif i < 0 {\n\t\t*index = 0\n\t\ti = 0\n\t}\n\tmod := len(routees)\n\troutee := routees[i%mod]\n\treturn routee\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/mozmark\/OneCRL-Tools\/oneCRL\"\t\n\t\"github.com\/mozmark\/OneCRL-Tools\/config\"\t\n)\n\ntype revocations struct {\n\tbyIssuerSerialNumber map[string][]string\n\tbySubjectPubKeyHash map[string][]string\n}\n\nfunc (r *revocations) LoadRecord(record oneCRL.Record) {\n\t\/\/ if there's no issuer name, assume we're revoking by Subject \/ PubKeyHash\n\t\/\/ otherwise it's issuer \/ serial\n\tif 0 == len(record.IssuerName) {\n\t\tif nil == r.bySubjectPubKeyHash {\n\t\t\tr.bySubjectPubKeyHash = make(map[string][]string)\n\t\t}\n\t\tif nil == r.bySubjectPubKeyHash[record.Subject]{\n\t\t\tpubKeyHashes := make([]string, 1)\n\t\t\tpubKeyHashes[0] = record.PubKeyHash\n\t\t\tr.bySubjectPubKeyHash[record.Subject] = pubKeyHashes\n\t\t} else {\n\t\t\tr.bySubjectPubKeyHash[record.Subject] = append(r.bySubjectPubKeyHash[record.Subject], record.PubKeyHash)\n\t\t}\n\t} else {\n\t\tif nil == r.byIssuerSerialNumber {\n\t\t\tr.byIssuerSerialNumber= make(map[string][]string)\n\t\t}\n\t\tif nil == r.byIssuerSerialNumber[record.IssuerName]{\n\t\t\tserials := make([]string, 1)\n\t\t\tserials[0] = record.SerialNumber\n\t\t\tr.byIssuerSerialNumber[record.IssuerName] = serials\n\t\t} else {\n\t\t\tr.byIssuerSerialNumber[record.IssuerName] = append(r.byIssuerSerialNumber[record.IssuerName], record.SerialNumber)\n\t\t}\n\t}\n}\n\nfunc main() {\n\tconfig.DefineFlags()\n\tflag.Parse()\n\n\trev := new (revocations)\n\t\n\tconfig := config.GetConfig()\n\n\turl := config.GetRecordURL()\n\n\terr := oneCRL.LoadJSONFromURL(url, rev)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor issuer, serials := range rev.byIssuerSerialNumber {\n\t\tfmt.Printf(\"%s\\n\", issuer)\n\t\tfor _, serial := range serials {\n\t\t\tfmt.Printf(\" %s\\n\", serial)\n\t\t}\n\t}\n\tfor subject, pubKeyHashes := range rev.bySubjectPubKeyHash {\n\t\tfmt.Printf(\"%s\\n\", subject)\n\t\tfor _, pubKeyHash := range pubKeyHashes {\n\t\t\tfmt.Printf(\"\\t%s\\n\", pubKeyHash)\n\t\t}\n\t}\n}\n<commit_msg>Issue #43 - oneCRL2RevocationsTxt fails with \"multiple-value config.GetRecordURL() in single-value context\"<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/mozmark\/OneCRL-Tools\/oneCRL\"\t\n\t\"github.com\/mozmark\/OneCRL-Tools\/config\"\t\n)\n\ntype revocations struct {\n\tbyIssuerSerialNumber map[string][]string\n\tbySubjectPubKeyHash map[string][]string\n}\n\nfunc (r *revocations) LoadRecord(record oneCRL.Record) {\n\t\/\/ if there's no issuer name, assume we're revoking by Subject \/ PubKeyHash\n\t\/\/ otherwise it's issuer \/ serial\n\tif 0 == len(record.IssuerName) {\n\t\tif nil == r.bySubjectPubKeyHash {\n\t\t\tr.bySubjectPubKeyHash = make(map[string][]string)\n\t\t}\n\t\tif nil == r.bySubjectPubKeyHash[record.Subject]{\n\t\t\tpubKeyHashes := make([]string, 1)\n\t\t\tpubKeyHashes[0] = record.PubKeyHash\n\t\t\tr.bySubjectPubKeyHash[record.Subject] = pubKeyHashes\n\t\t} else {\n\t\t\tr.bySubjectPubKeyHash[record.Subject] = append(r.bySubjectPubKeyHash[record.Subject], record.PubKeyHash)\n\t\t}\n\t} else {\n\t\tif nil == r.byIssuerSerialNumber {\n\t\t\tr.byIssuerSerialNumber= make(map[string][]string)\n\t\t}\n\t\tif nil == r.byIssuerSerialNumber[record.IssuerName]{\n\t\t\tserials := make([]string, 1)\n\t\t\tserials[0] = record.SerialNumber\n\t\t\tr.byIssuerSerialNumber[record.IssuerName] = serials\n\t\t} else {\n\t\t\tr.byIssuerSerialNumber[record.IssuerName] = append(r.byIssuerSerialNumber[record.IssuerName], record.SerialNumber)\n\t\t}\n\t}\n}\n\nfunc main() {\n\tconfig.DefineFlags()\n\tflag.Parse()\n\n\trev := new (revocations)\n\t\n\tconfig := config.GetConfig()\n\n\terr, url := config.GetRecordURL()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = oneCRL.LoadJSONFromURL(url, rev)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor issuer, serials := range rev.byIssuerSerialNumber {\n\t\tfmt.Printf(\"%s\\n\", issuer)\n\t\tfor _, serial := range serials {\n\t\t\tfmt.Printf(\" %s\\n\", serial)\n\t\t}\n\t}\n\tfor subject, pubKeyHashes := range rev.bySubjectPubKeyHash {\n\t\tfmt.Printf(\"%s\\n\", subject)\n\t\tfor _, pubKeyHash := range pubKeyHashes {\n\t\t\tfmt.Printf(\"\\t%s\\n\", pubKeyHash)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Fission Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage canaryconfigmgr\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\tpromClient \"github.com\/prometheus\/client_golang\/api\/prometheus\"\n\t\"github.com\/prometheus\/common\/model\"\n\t\"go.uber.org\/zap\"\n\t\"golang.org\/x\/net\/context\"\n)\n\ntype PrometheusApiClient struct {\n\tlogger *zap.Logger\n\tclient promClient.QueryAPI\n}\n\nfunc MakePrometheusClient(logger *zap.Logger, prometheusSvc string) (*PrometheusApiClient, error) {\n\tpromApiConfig := promClient.Config{\n\t\tAddress: prometheusSvc,\n\t}\n\n\tpromApiClient, err := promClient.New(promApiConfig)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error creating prometheus api client for svc: %s\", prometheusSvc)\n\t}\n\n\tapiQueryClient := promClient.NewQueryAPI(promApiClient)\n\n\t\/\/ By default, the prometheus client library doesn't test server connectivity when creating\n\t\/\/ prometheus client. As a workaround, here we send out a test query string to ensure that\n\t\/\/ prometheus server is running.\n\tfor i := 0; i < 15; i++ {\n\t\t_, err = apiQueryClient.Query(context.Background(), \"http_requests_total\", time.Now())\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error sending test query to prometheus server\")\n\t}\n\n\tlogger.Info(\"successfully made prometheus client with service\", zap.String(\"service\", prometheusSvc))\n\treturn &PrometheusApiClient{\n\t\tlogger: logger.Named(\"prometheus_api_client\"),\n\t\tclient: apiQueryClient,\n\t}, nil\n}\n\nfunc (promApiClient *PrometheusApiClient) GetFunctionFailurePercentage(path, method, funcName, funcNs string, window string) (float64, error) {\n\t\/\/ first get a total count of requests to this url in a time window\n\treqs, err := promApiClient.GetRequestsToFuncInWindow(path, method, funcName, funcNs, window)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif reqs <= 0 {\n\t\treturn -1, fmt.Errorf(\"no requests to this url %v and method %v in the window: %v\", path, method, window)\n\t}\n\n\t\/\/ next, get a total count of errored out requests to this function in the same window\n\tfailedReqs, err := promApiClient.GetTotalFailedRequestsToFuncInWindow(funcName, funcNs, path, method, window)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ calculate the failure percentage of the function\n\tfailurePercentForFunc := (failedReqs \/ reqs) * 100\n\n\treturn failurePercentForFunc, nil\n}\n\nfunc (promApiClient *PrometheusApiClient) GetRequestsToFuncInWindow(path string, method string, funcName string, funcNs string, window string) (float64, error) {\n\tqueryString := fmt.Sprintf(\"fission_function_calls_total{path=\\\"%s\\\",method=\\\"%s\\\",name=\\\"%s\\\",namespace=\\\"%s\\\"}[%v]\", path, method, funcName, funcNs, window)\n\n\treqs, err := promApiClient.executeQuery(queryString)\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"error executing query: %s\", queryString)\n\t}\n\n\tqueryString = fmt.Sprintf(\"fission_function_calls_total{path=\\\"%s\\\",method=\\\"%s\\\",name=\\\"%s\\\",namespace=\\\"%s\\\"} offset %v\", path, method, funcName, funcNs, window)\n\n\treqsInPrevWindow, err := promApiClient.executeQuery(queryString)\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"error executing query: %s\", queryString)\n\t}\n\n\treqsInCurrentWindow := reqs - reqsInPrevWindow\n\tpromApiClient.logger.Info(\"function requests\",\n\t\tzap.Float64(\"requests\", reqs),\n\t\tzap.Float64(\"requests_in_previous_window\", reqsInPrevWindow),\n\t\tzap.Float64(\"requests_in_current_window\", reqsInCurrentWindow),\n\t\tzap.String(\"function\", funcName))\n\n\treturn reqsInCurrentWindow, nil\n}\n\nfunc (promApiClient *PrometheusApiClient) GetTotalFailedRequestsToFuncInWindow(funcName string, funcNs string, path string, method string, window string) (float64, error) {\n\tqueryString := fmt.Sprintf(\"fission_function_errors_total{name=\\\"%s\\\",namespace=\\\"%s\\\",path=\\\"%s\\\", method=\\\"%s\\\"}[%v]\", funcName, funcNs, path, method, window)\n\n\tfailedRequests, err := promApiClient.executeQuery(queryString)\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"error executing query: %s\", queryString)\n\t}\n\n\tqueryString = fmt.Sprintf(\"fission_function_errors_total{name=\\\"%s\\\",namespace=\\\"%s\\\",path=\\\"%s\\\", method=\\\"%s\\\"} offset %v\", funcName, funcNs, path, method, window)\n\n\tfailedReqsInPrevWindow, err := promApiClient.executeQuery(queryString)\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"error executing query: %s\", queryString)\n\t}\n\n\tfailedReqsInCurrentWindow := failedRequests - failedReqsInPrevWindow\n\tpromApiClient.logger.Info(\"function requests\",\n\t\tzap.Float64(\"failed_requests\", failedRequests),\n\t\tzap.Float64(\"failed_requests_in_previous_window\", failedReqsInPrevWindow),\n\t\tzap.Float64(\"failed_requests_in_current_window\", failedReqsInCurrentWindow),\n\t\tzap.String(\"function\", funcName))\n\n\treturn failedReqsInCurrentWindow, nil\n}\n\nfunc (promApiClient *PrometheusApiClient) executeQuery(queryString string) (float64, error) {\n\tval, err := promApiClient.client.Query(context.Background(), queryString, time.Now())\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"error querying prometheus\")\n\t}\n\n\tswitch {\n\tcase val.Type() == model.ValScalar:\n\t\tscalarVal := val.(*model.Scalar)\n\t\treturn float64(scalarVal.Value), nil\n\n\tcase val.Type() == model.ValVector:\n\t\tvectorVal := val.(model.Vector)\n\t\ttotal := float64(0)\n\t\tfor _, elem := range vectorVal {\n\t\t\ttotal = total + float64(elem.Value)\n\t\t}\n\t\treturn total, nil\n\n\tcase val.Type() == model.ValMatrix:\n\t\tmatrixVal := val.(model.Matrix)\n\t\ttotal := float64(0)\n\t\tfor _, elem := range matrixVal {\n\t\t\ttotal += float64(elem.Values[len(elem.Values)-1].Value)\n\t\t}\n\t\treturn total, nil\n\n\tdefault:\n\t\tpromApiClient.logger.Info(\"return value type of prometheus query was unrecognized\",\n\t\t\tzap.Any(\"type\", val.Type()))\n\t\treturn 0, nil\n\t}\n}\n<commit_msg>Remove prometheus server connectivity test during controller initialization (#1179)<commit_after>\/*\nCopyright 2016 The Fission Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage canaryconfigmgr\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\tpromClient \"github.com\/prometheus\/client_golang\/api\/prometheus\"\n\t\"github.com\/prometheus\/common\/model\"\n\t\"go.uber.org\/zap\"\n\t\"golang.org\/x\/net\/context\"\n)\n\ntype PrometheusApiClient struct {\n\tlogger *zap.Logger\n\tclient promClient.QueryAPI\n}\n\nfunc MakePrometheusClient(logger *zap.Logger, prometheusSvc string) (*PrometheusApiClient, error) {\n\tpromApiConfig := promClient.Config{\n\t\tAddress: prometheusSvc,\n\t}\n\n\tpromApiClient, err := promClient.New(promApiConfig)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error creating prometheus api client for svc: %s\", prometheusSvc)\n\t}\n\n\tapiQueryClient := promClient.NewQueryAPI(promApiClient)\n\n\treturn &PrometheusApiClient{\n\t\tlogger: logger.Named(\"prometheus_api_client\"),\n\t\tclient: apiQueryClient,\n\t}, nil\n}\n\nfunc (promApiClient *PrometheusApiClient) GetFunctionFailurePercentage(path, method, funcName, funcNs string, window string) (float64, error) {\n\t\/\/ first get a total count of requests to this url in a time window\n\treqs, err := promApiClient.GetRequestsToFuncInWindow(path, method, funcName, funcNs, window)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif reqs <= 0 {\n\t\treturn -1, fmt.Errorf(\"no requests to this url %v and method %v in the window: %v\", path, method, window)\n\t}\n\n\t\/\/ next, get a total count of errored out requests to this function in the same window\n\tfailedReqs, err := promApiClient.GetTotalFailedRequestsToFuncInWindow(funcName, funcNs, path, method, window)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ calculate the failure percentage of the function\n\tfailurePercentForFunc := (failedReqs \/ reqs) * 100\n\n\treturn failurePercentForFunc, nil\n}\n\nfunc (promApiClient *PrometheusApiClient) GetRequestsToFuncInWindow(path string, method string, funcName string, funcNs string, window string) (float64, error) {\n\tqueryString := fmt.Sprintf(\"fission_function_calls_total{path=\\\"%s\\\",method=\\\"%s\\\",name=\\\"%s\\\",namespace=\\\"%s\\\"}[%v]\", path, method, funcName, funcNs, window)\n\n\treqs, err := promApiClient.executeQuery(queryString)\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"error executing query: %s\", queryString)\n\t}\n\n\tqueryString = fmt.Sprintf(\"fission_function_calls_total{path=\\\"%s\\\",method=\\\"%s\\\",name=\\\"%s\\\",namespace=\\\"%s\\\"} offset %v\", path, method, funcName, funcNs, window)\n\n\treqsInPrevWindow, err := promApiClient.executeQuery(queryString)\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"error executing query: %s\", queryString)\n\t}\n\n\treqsInCurrentWindow := reqs - reqsInPrevWindow\n\tpromApiClient.logger.Info(\"function requests\",\n\t\tzap.Float64(\"requests\", reqs),\n\t\tzap.Float64(\"requests_in_previous_window\", reqsInPrevWindow),\n\t\tzap.Float64(\"requests_in_current_window\", reqsInCurrentWindow),\n\t\tzap.String(\"function\", funcName))\n\n\treturn reqsInCurrentWindow, nil\n}\n\nfunc (promApiClient *PrometheusApiClient) GetTotalFailedRequestsToFuncInWindow(funcName string, funcNs string, path string, method string, window string) (float64, error) {\n\tqueryString := fmt.Sprintf(\"fission_function_errors_total{name=\\\"%s\\\",namespace=\\\"%s\\\",path=\\\"%s\\\", method=\\\"%s\\\"}[%v]\", funcName, funcNs, path, method, window)\n\n\tfailedRequests, err := promApiClient.executeQuery(queryString)\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"error executing query: %s\", queryString)\n\t}\n\n\tqueryString = fmt.Sprintf(\"fission_function_errors_total{name=\\\"%s\\\",namespace=\\\"%s\\\",path=\\\"%s\\\", method=\\\"%s\\\"} offset %v\", funcName, funcNs, path, method, window)\n\n\tfailedReqsInPrevWindow, err := promApiClient.executeQuery(queryString)\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"error executing query: %s\", queryString)\n\t}\n\n\tfailedReqsInCurrentWindow := failedRequests - failedReqsInPrevWindow\n\tpromApiClient.logger.Info(\"function requests\",\n\t\tzap.Float64(\"failed_requests\", failedRequests),\n\t\tzap.Float64(\"failed_requests_in_previous_window\", failedReqsInPrevWindow),\n\t\tzap.Float64(\"failed_requests_in_current_window\", failedReqsInCurrentWindow),\n\t\tzap.String(\"function\", funcName))\n\n\treturn failedReqsInCurrentWindow, nil\n}\n\nfunc (promApiClient *PrometheusApiClient) executeQuery(queryString string) (float64, error) {\n\tval, err := promApiClient.client.Query(context.Background(), queryString, time.Now())\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"error querying prometheus\")\n\t}\n\n\tswitch {\n\tcase val.Type() == model.ValScalar:\n\t\tscalarVal := val.(*model.Scalar)\n\t\treturn float64(scalarVal.Value), nil\n\n\tcase val.Type() == model.ValVector:\n\t\tvectorVal := val.(model.Vector)\n\t\ttotal := float64(0)\n\t\tfor _, elem := range vectorVal {\n\t\t\ttotal = total + float64(elem.Value)\n\t\t}\n\t\treturn total, nil\n\n\tcase val.Type() == model.ValMatrix:\n\t\tmatrixVal := val.(model.Matrix)\n\t\ttotal := float64(0)\n\t\tfor _, elem := range matrixVal {\n\t\t\ttotal += float64(elem.Values[len(elem.Values)-1].Value)\n\t\t}\n\t\treturn total, nil\n\n\tdefault:\n\t\tpromApiClient.logger.Info(\"return value type of prometheus query was unrecognized\",\n\t\t\tzap.Any(\"type\", val.Type()))\n\t\treturn 0, nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package user\n\nimport (\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"gopkg.in\/DATA-DOG\/go-sqlmock.v1\"\n\t\"testing\"\n\n\t\"github.com\/eirka\/eirka-libs\/db\"\n\t\"github.com\/eirka\/eirka-libs\/validate\"\n)\n\nfunc TestProtect(t *testing.T) {\n\n\tvar err error\n\n\tSecret = \"secret\"\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\trows := sqlmock.NewRows([]string{\"role\"}).AddRow(1)\n\n\tmock.ExpectQuery(`SELECT COALESCE`).WillReturnRows(rows)\n\n\tgin.SetMode(gin.ReleaseMode)\n\n\trouter := gin.New()\n\n\trouter.Use(validate.ValidateParams())\n\trouter.Use(Auth(true))\n\trouter.Use(Protect())\n\n\trouter.GET(\"\/important\", func(c *gin.Context) {\n\t\tc.String(200, \"OK\")\n\t\treturn\n\t})\n\n\tfirst := performRequest(router, \"GET\", \"\/important\")\n\n\tassert.Equal(t, first.Code, 401, \"HTTP request code should match\")\n\n\tuser := DefaultUser()\n\tuser.SetId(2)\n\tuser.SetAuthenticated()\n\n\tuser.hash, err = HashPassword(\"testpassword\")\n\tif assert.NoError(t, err, \"An error was not expected\") {\n\t\tassert.NotNil(t, user.hash, \"password should be returned\")\n\t}\n\n\tassert.True(t, user.ComparePassword(\"testpassword\"), \"Password should validate\")\n\n\ttoken, err := user.CreateToken()\n\tif assert.NoError(t, err, \"An error was not expected\") {\n\t\tassert.NotEmpty(t, token, \"token should be returned\")\n\t}\n\n\tsecond := performJwtHeaderRequest(router, \"GET\", \"\/important\", token)\n\n}\n<commit_msg>add protect middleware test<commit_after>package user\n\nimport (\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"gopkg.in\/DATA-DOG\/go-sqlmock.v1\"\n\t\"testing\"\n\n\t\"github.com\/eirka\/eirka-libs\/db\"\n\t\"github.com\/eirka\/eirka-libs\/validate\"\n)\n\nfunc TestProtect(t *testing.T) {\n\n\tvar err error\n\n\tSecret = \"secret\"\n\n\tmock, err := db.NewTestDb()\n\tassert.NoError(t, err, \"An error was not expected\")\n\n\trows := sqlmock.NewRows([]string{\"role\"}).AddRow(1)\n\n\tmock.ExpectQuery(`SELECT COALESCE`).WillReturnRows(rows)\n\n\tgin.SetMode(gin.ReleaseMode)\n\n\trouter := gin.New()\n\n\trouter.Use(validate.ValidateParams())\n\trouter.Use(Auth(true))\n\trouter.Use(Protect())\n\n\trouter.GET(\"\/important\", func(c *gin.Context) {\n\t\tc.String(200, \"OK\")\n\t\treturn\n\t})\n\n\tfirst := performRequest(router, \"GET\", \"\/important\")\n\n\tassert.Equal(t, first.Code, 401, \"HTTP request code should match\")\n\n\tuser := DefaultUser()\n\tuser.SetId(2)\n\tuser.SetAuthenticated()\n\n\tuser.hash, err = HashPassword(\"testpassword\")\n\tif assert.NoError(t, err, \"An error was not expected\") {\n\t\tassert.NotNil(t, user.hash, \"password should be returned\")\n\t}\n\n\tassert.True(t, user.ComparePassword(\"testpassword\"), \"Password should validate\")\n\n\ttoken, err := user.CreateToken()\n\tif assert.NoError(t, err, \"An error was not expected\") {\n\t\tassert.NotEmpty(t, token, \"token should be returned\")\n\t}\n\n\tsecond := performJwtHeaderRequest(router, \"GET\", \"\/important\", token)\n\n\tassert.Equal(t, second.Code, 200, \"HTTP request code should match\")\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package challenges_test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\/**\n * Definition for singly-linked list.\n * type ListNode struct {\n *     Val int\n *     Next *ListNode\n * }\n *\/\n\ntype ListNode struct {\n\tVal  int\n\tNext *ListNode\n}\n\n\/\/ moving the current node value to the next value and pointing next to next, the \"GC\" will clean up the object\nfunc deleteNode(node *ListNode) {\n\tif node != nil && node.Next != nil {\n\t\tnode.Val = node.Next.Val\n\t\tnode.Next = node.Next.Next\n\t}\n}\n\nfunc removeNthFromEnd(head *ListNode, n int) *ListNode {\n\n\tlen := 1\n\td := head\n\tfor d != nil && d.Next != nil {\n\t\tlen++\n\t\td = d.Next\n\t}\n\n\tif n > len {\n\t\treturn head\n\t}\n\n\tremoveThis := head\n\tmoveRight := len - n\n\t\/\/ going from left to right N spaces\n\tfor i := 1; i <= moveRight; i++ {\n\t\tremoveThis = removeThis.Next\n\t}\n\n\t\/\/ 1->2->3->4->5: if n == 2; 5-2 == 3\n\tif removeThis != nil && removeThis.Next == nil {\n\t\treturn nil\n\t}\n\n\t\/\/fmt.Printf(\"Removing node pos[%d] on len[%d]: %v\\n\", moveRight, len, removeThis)\n\tdeleteNode(removeThis)\n\treturn head\n\n}\n\nfunc Test_deleteNode(t *testing.T) {\n\ttype args struct {\n\t\tnode *ListNode\n\t}\n\n\tn := &ListNode{4, &ListNode{5, &ListNode{1, &ListNode{9, nil}}}}\n\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t}{\n\t\t{\"delete\", args{n.Next}},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tdeleteNode(tt.args.node)\n\t\t})\n\t}\n}\n\nfunc Test_removeNthFromEnd(t *testing.T) {\n\ttype args struct {\n\t\thead *ListNode\n\t\tn    int\n\t}\n\n\tn := &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, &ListNode{5, nil}}}}}\n\n\tn2 := &ListNode{1, nil}\n\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant *ListNode\n\t}{\n\t\t\/\/ TODO: Add test cases.\n\t\t{\"remove\", args{head: n, n: 2}, n},\n\t\t{\"remove\", args{head: n2, n: 1}, nil},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := removeNthFromEnd(tt.args.head, tt.args.n); !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Errorf(\"removeNthFromEnd() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}\n<commit_msg>fixed remove from the end.<commit_after>package challenges_test\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/davecgh\/go-spew\/spew\"\n)\n\n\/**\n * Definition for singly-linked list.\n * type ListNode struct {\n *     Val int\n *     Next *ListNode\n * }\n *\/\n\ntype ListNode struct {\n\tVal  int\n\tNext *ListNode\n}\n\n\/\/ moving the current node value to the next value and pointing next to next, the \"GC\" will clean up the object\nfunc deleteNode(node *ListNode) {\n\tif node != nil && node.Next != nil {\n\t\tnode.Val = node.Next.Val\n\t\tnode.Next = node.Next.Next\n\t}\n}\n\nfunc removeNthFromEnd(head *ListNode, n int) *ListNode {\n\n\tlen := 1\n\td := head\n\tfor d != nil && d.Next != nil {\n\t\tlen++\n\t\td = d.Next\n\t}\n\n\tif n > len {\n\t\treturn head\n\t}\n\n\tremoveThis := head\n\tmoveRight := len - n\n\tfmt.Printf(\"Len: %d Moving Right: %d\\n\", len, moveRight)\n\t\/\/ going from left to right N spaces\n\tfor i := 1; i <= moveRight; i++ {\n\t\tremoveThis = removeThis.Next\n\t}\n\t\/\/ deleteting the end (need to back up one)\n\tif removeThis != nil && removeThis.Next == nil && removeThis != head {\n\t\tremoveThis = head\n\t\tmoveRight := len - n - 1\n\t\tfor i := 1; i <= moveRight; i++ {\n\t\t\tremoveThis = removeThis.Next\n\t\t}\n\t\tremoveThis.Next = nil\n\t\treturn head\n\t}\n\n\t\/\/ 1->2->3->4->5: if n == 2; 5-2 == 3\n\tif removeThis != nil && removeThis.Next == nil && removeThis == head {\n\t\treturn nil\n\t}\n\n\t\/\/fmt.Printf(\"Removing node pos[%d] on len[%d]: %v\\n\", moveRight, len, removeThis)\n\tdeleteNode(removeThis)\n\treturn head\n\n}\n\nfunc Test_removeNthFromEnd(t *testing.T) {\n\ttype args struct {\n\t\thead *ListNode\n\t\tn    int\n\t}\n\n\tn1 := &ListNode{1, &ListNode{2, &ListNode{3, &ListNode{4, &ListNode{5, nil}}}}}\n\tn2 := &ListNode{1, nil}\n\tn3 := &ListNode{1, &ListNode{2, nil}}\n\tn4 := &ListNode{1, &ListNode{2, &ListNode{3, nil}}}\n\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant *ListNode\n\t}{\n\t\t{\"remove\", args{head: n1, n: 2}, n1},\n\t\t{\"remove\", args{head: n2, n: 1}, nil},\n\t\t{\"remove\", args{head: n3, n: 1}, n3},\n\t\t{\"remove\", args{head: n4, n: 1}, n4},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif got := removeNthFromEnd(tt.args.head, tt.args.n); !reflect.DeepEqual(got, tt.want) {\n\t\t\t\tt.Errorf(\"removeNthFromEnd() = %v, want %v\", got, tt.want)\n\t\t\t} else {\n\t\t\t\tt.Log(spew.Sprintf(\"OK: %v\\n\", tt.want))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc Test_deleteNode(t *testing.T) {\n\ttype args struct {\n\t\tnode *ListNode\n\t}\n\n\tn := &ListNode{4, &ListNode{5, &ListNode{1, &ListNode{9, nil}}}}\n\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t}{\n\t\t{\"delete\", args{n.Next}},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tdeleteNode(tt.args.node)\n\t\t})\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package peco\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/mattn\/go-runewidth\"\n\t\"github.com\/nsf\/termbox-go\"\n)\n\nfunc TestActionNames(t *testing.T) {\n\t\/\/ These names MUST exist\n\tnames := []string{\n\t\t\"peco.ForwardChar\",\n\t\t\"peco.BackwardChar\",\n\t\t\"peco.ForwardWord\",\n\t\t\"peco.BackwardWord\",\n\t\t\"peco.BeginningOfLine\",\n\t\t\"peco.EndOfLine\",\n\t\t\"peco.EndOfFile\",\n\t\t\"peco.DeleteForwardChar\",\n\t\t\"peco.DeleteBackwardChar\",\n\t\t\"peco.DeleteForwardWord\",\n\t\t\"peco.DeleteBackwardWord\",\n\t\t\"peco.KillEndOfLine\",\n\t\t\"peco.DeleteAll\",\n\t\t\"peco.SelectPreviousPage\",\n\t\t\"peco.SelectNextPage\",\n\t\t\"peco.SelectPrevious\",\n\t\t\"peco.SelectNext\",\n\t\t\"peco.ToggleSelection\",\n\t\t\"peco.ToggleSelectionAndSelectNext\",\n\t\t\"peco.RotateMatcher\",\n\t\t\"peco.Finish\",\n\t\t\"peco.Cancel\",\n\t}\n\tfor _, name := range names {\n\t\tif _, ok := nameToActions[name]; !ok {\n\t\t\tt.Errorf(\"Action %s should exist, but it does not\", name)\n\t\t}\n\t}\n}\n\nfunc expectCaretPos(t *testing.T, c interface {\n\tCaretPos() int\n}, expect int) bool {\n\tif c.CaretPos() != expect {\n\t\tt.Errorf(\"Expected caret position %d, got %d\", expect, c.CaretPos())\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc expectQueryString(t *testing.T, c interface {\n\tQueryString() string\n}, expect string) bool {\n\tif c.QueryString() != expect {\n\t\tt.Errorf(\"Expected '%s', got '%s'\", expect, c.QueryString())\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc TestDoDeleteForwardChar(t *testing.T) {\n\tctx := NewCtx(nil)\n\tinput := ctx.NewInput()\n\n\tctx.SetQuery([]rune(\"Hello, World!\"))\n\tctx.SetCaretPos(5)\n\tdoDeleteForwardChar(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hello World!\")\n\texpectCaretPos(t, ctx, 5)\n\n\tctx.SetCaretPos(runewidth.StringWidth(ctx.QueryString()))\n\tdoDeleteForwardChar(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hello World!\")\n\texpectCaretPos(t, ctx, runewidth.StringWidth(ctx.QueryString()))\n\n\tctx.SetCaretPos(0)\n\tdoDeleteForwardChar(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"ello World!\")\n\texpectCaretPos(t, ctx, 0)\n}\n\nfunc TestDoDeleteForwardWord(t *testing.T) {\n\tctx := NewCtx(nil)\n\tinput := ctx.NewInput()\n\n\tctx.SetQuery([]rune(\"Hello, World!\"))\n\tctx.SetCaretPos(5)\n\tdoDeleteForwardWord(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hello World!\")\n\texpectCaretPos(t, ctx, 5)\n\n\tctx.SetCaretPos(runewidth.StringWidth(ctx.QueryString()))\n\tdoDeleteForwardWord(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hello World!\")\n\texpectCaretPos(t, ctx, runewidth.StringWidth(ctx.QueryString()))\n\n\tctx.SetCaretPos(0)\n\tdoDeleteForwardWord(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \" World!\")\n\texpectCaretPos(t, ctx, 0)\n\n\tctx.SetCaretPos(1)\n\tdoDeleteForwardWord(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \" \")\n}\n\nfunc TestDoDeleteBackwardChar(t *testing.T) {\n\tctx := NewCtx(nil)\n\tinput := ctx.NewInput()\n\n\tctx.SetQuery([]rune(\"Hello, World!\"))\n\tctx.SetCaretPos(5)\n\tdoDeleteBackwardChar(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hell, World!\")\n\texpectCaretPos(t, ctx, 4)\n\n\tctx.SetCaretPos(runewidth.StringWidth(ctx.QueryString()))\n\tdoDeleteBackwardChar(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hell, World\")\n\texpectCaretPos(t, ctx, runewidth.StringWidth(ctx.QueryString()))\n\n\tctx.SetCaretPos(0)\n\tdoDeleteBackwardChar(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hell, World\")\n\texpectCaretPos(t, ctx, 0)\n}\n\nfunc TestDoDeleteBackwardWord(t *testing.T) {\n\tctx := NewCtx(nil)\n\tinput := ctx.NewInput()\n\n\t\/\/ In case of an overflow (bug)\n\tctx.SetQuery([]rune(\"foo\"))\n\tctx.SetCaretPos(5)\n\tdoDeleteBackwardWord(input, termbox.Event{})\n\n\t\/\/ https:\/\/github.com\/peco\/peco\/pull\/184#issuecomment-54026739\n\n\t\/\/ Case 1. \" foo<caret>\" -> \" \"\n\tctx.SetQuery([]rune(\" foo\"))\n\tctx.SetCaretPos(4)\n\tdoDeleteBackwardWord(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \" \")\n\texpectCaretPos(t, ctx, 1)\n\n\t\/\/ Case 2. \"foo bar<caret>\" -> \"foo \"\n\tctx.SetQuery([]rune(\"foo bar\"))\n\tctx.SetCaretPos(7)\n\tdoDeleteBackwardWord(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"foo \")\n\texpectCaretPos(t, ctx, 4)\n}\n<commit_msg>Add small test<commit_after>package peco\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/mattn\/go-runewidth\"\n\t\"github.com\/nsf\/termbox-go\"\n)\n\nfunc TestActionFunc(t *testing.T) {\n\tcalled := 0\n\taf := ActionFunc(func(_ *Input, _ termbox.Event) {\n\t\tcalled++\n\t})\n\taf.Execute(nil, termbox.Event{})\n\tif called != 1 {\n\t\tt.Errorf(\"Expected ActionFunc to be called once, but it got called %d times\", called)\n\t}\n}\n\nfunc TestActionNames(t *testing.T) {\n\t\/\/ These names MUST exist\n\tnames := []string{\n\t\t\"peco.ForwardChar\",\n\t\t\"peco.BackwardChar\",\n\t\t\"peco.ForwardWord\",\n\t\t\"peco.BackwardWord\",\n\t\t\"peco.BeginningOfLine\",\n\t\t\"peco.EndOfLine\",\n\t\t\"peco.EndOfFile\",\n\t\t\"peco.DeleteForwardChar\",\n\t\t\"peco.DeleteBackwardChar\",\n\t\t\"peco.DeleteForwardWord\",\n\t\t\"peco.DeleteBackwardWord\",\n\t\t\"peco.KillEndOfLine\",\n\t\t\"peco.DeleteAll\",\n\t\t\"peco.SelectPreviousPage\",\n\t\t\"peco.SelectNextPage\",\n\t\t\"peco.SelectPrevious\",\n\t\t\"peco.SelectNext\",\n\t\t\"peco.ToggleSelection\",\n\t\t\"peco.ToggleSelectionAndSelectNext\",\n\t\t\"peco.RotateMatcher\",\n\t\t\"peco.Finish\",\n\t\t\"peco.Cancel\",\n\t}\n\tfor _, name := range names {\n\t\tif _, ok := nameToActions[name]; !ok {\n\t\t\tt.Errorf(\"Action %s should exist, but it does not\", name)\n\t\t}\n\t}\n}\n\nfunc expectCaretPos(t *testing.T, c interface {\n\tCaretPos() int\n}, expect int) bool {\n\tif c.CaretPos() != expect {\n\t\tt.Errorf(\"Expected caret position %d, got %d\", expect, c.CaretPos())\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc expectQueryString(t *testing.T, c interface {\n\tQueryString() string\n}, expect string) bool {\n\tif c.QueryString() != expect {\n\t\tt.Errorf(\"Expected '%s', got '%s'\", expect, c.QueryString())\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc TestDoDeleteForwardChar(t *testing.T) {\n\tctx := NewCtx(nil)\n\tinput := ctx.NewInput()\n\n\tctx.SetQuery([]rune(\"Hello, World!\"))\n\tctx.SetCaretPos(5)\n\tdoDeleteForwardChar(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hello World!\")\n\texpectCaretPos(t, ctx, 5)\n\n\tctx.SetCaretPos(runewidth.StringWidth(ctx.QueryString()))\n\tdoDeleteForwardChar(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hello World!\")\n\texpectCaretPos(t, ctx, runewidth.StringWidth(ctx.QueryString()))\n\n\tctx.SetCaretPos(0)\n\tdoDeleteForwardChar(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"ello World!\")\n\texpectCaretPos(t, ctx, 0)\n}\n\nfunc TestDoDeleteForwardWord(t *testing.T) {\n\tctx := NewCtx(nil)\n\tinput := ctx.NewInput()\n\n\tctx.SetQuery([]rune(\"Hello, World!\"))\n\tctx.SetCaretPos(5)\n\tdoDeleteForwardWord(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hello World!\")\n\texpectCaretPos(t, ctx, 5)\n\n\tctx.SetCaretPos(runewidth.StringWidth(ctx.QueryString()))\n\tdoDeleteForwardWord(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hello World!\")\n\texpectCaretPos(t, ctx, runewidth.StringWidth(ctx.QueryString()))\n\n\tctx.SetCaretPos(0)\n\tdoDeleteForwardWord(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \" World!\")\n\texpectCaretPos(t, ctx, 0)\n\n\tctx.SetCaretPos(1)\n\tdoDeleteForwardWord(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \" \")\n}\n\nfunc TestDoDeleteBackwardChar(t *testing.T) {\n\tctx := NewCtx(nil)\n\tinput := ctx.NewInput()\n\n\tctx.SetQuery([]rune(\"Hello, World!\"))\n\tctx.SetCaretPos(5)\n\tdoDeleteBackwardChar(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hell, World!\")\n\texpectCaretPos(t, ctx, 4)\n\n\tctx.SetCaretPos(runewidth.StringWidth(ctx.QueryString()))\n\tdoDeleteBackwardChar(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hell, World\")\n\texpectCaretPos(t, ctx, runewidth.StringWidth(ctx.QueryString()))\n\n\tctx.SetCaretPos(0)\n\tdoDeleteBackwardChar(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"Hell, World\")\n\texpectCaretPos(t, ctx, 0)\n}\n\nfunc TestDoDeleteBackwardWord(t *testing.T) {\n\tctx := NewCtx(nil)\n\tinput := ctx.NewInput()\n\n\t\/\/ In case of an overflow (bug)\n\tctx.SetQuery([]rune(\"foo\"))\n\tctx.SetCaretPos(5)\n\tdoDeleteBackwardWord(input, termbox.Event{})\n\n\t\/\/ https:\/\/github.com\/peco\/peco\/pull\/184#issuecomment-54026739\n\n\t\/\/ Case 1. \" foo<caret>\" -> \" \"\n\tctx.SetQuery([]rune(\" foo\"))\n\tctx.SetCaretPos(4)\n\tdoDeleteBackwardWord(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \" \")\n\texpectCaretPos(t, ctx, 1)\n\n\t\/\/ Case 2. \"foo bar<caret>\" -> \"foo \"\n\tctx.SetQuery([]rune(\"foo bar\"))\n\tctx.SetCaretPos(7)\n\tdoDeleteBackwardWord(input, termbox.Event{})\n\n\texpectQueryString(t, ctx, \"foo \")\n\texpectCaretPos(t, ctx, 4)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/  Copyright (c) 2013 Couchbase, Inc.\n\npackage builtin\n\nimport \"time\"\nimport \"fmt\"\n\nimport \"github.com\/prataprc\/monster\/common\"\n\nvar _ = fmt.Sprintf(\"dummy\")\n\n\/\/ Uuid returns a unique value based on current nanosecond timestamp.\nfunc Uuid(scope common.Scope, args ...interface{}) interface{} {\n\tuuid := time.Now().UnixNano()\n\treturn uuid\n}\n<commit_msg>monster: generate cryptographic random number.<commit_after>\/\/  Copyright (c) 2013 Couchbase, Inc.\n\npackage builtin\n\nimport \"fmt\"\nimport \"bytes\"\nimport \"strconv\"\nimport \"io\"\nimport \"encoding\/binary\"\nimport \"math\/rand\"\nimport crypt \"crypto\/rand\"\n\nimport \"github.com\/prataprc\/monster\/common\"\n\nvar _ = fmt.Sprintf(\"dummy\")\n\ntype UUID []byte\n\nfunc init() {\n\tseed := newUUID().Uint64()\n\trand.Seed(int64(seed))\n}\n\n\/\/ Uuid returns a unique value based on current nanosecond timestamp.\nfunc Uuid(scope common.Scope, args ...interface{}) interface{} {\n\treturn newUUID().Uint64()\n}\n\nfunc newUUID() UUID {\n\tuuid := make([]byte, 8)\n\tif n, err := io.ReadFull(crypt.Reader, uuid); err != nil {\n\t\tpanic(\"crypt.Reader errored out\")\n\t} else if n != len(uuid) {\n\t\tpanic(\"crypt.Reader failed\")\n\t}\n\treturn UUID(uuid)\n}\n\nfunc (u UUID) Uint64() uint64 {\n\treturn binary.LittleEndian.Uint64(([]byte)(u))\n}\n\nfunc (u UUID) Str() string {\n\tvar buf bytes.Buffer\n\tfor i := 0; i < len(u); i++ {\n\t\tif i > 0 {\n\t\t\tbuf.WriteString(\":\")\n\t\t}\n\t\tbuf.WriteString(strconv.FormatUint(uint64(u[i]), 16))\n\t}\n\treturn buf.String()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage gce\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"k8s.io\/contrib\/cluster-autoscaler\/cloudprovider\"\n\tkube_api \"k8s.io\/kubernetes\/pkg\/api\"\n)\n\n\/\/ GceCloudProvider implements CloudProvider interface.\ntype GceCloudProvider struct {\n\tgceManager *GceManager\n\tmigs       []*Mig\n}\n\n\/\/ BuildGceCloudProvider builds CloudProvider implementation for GCE.\nfunc BuildGceCloudProvider(gceManager *GceManager, specs []string) (*GceCloudProvider, error) {\n\tgce := &GceCloudProvider{\n\t\tgceManager: gceManager,\n\t\tmigs:       make([]*Mig, 0),\n\t}\n\tfor _, spec := range specs {\n\t\tif err := gce.addNodeGroup(spec); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn gce, nil\n}\n\n\/\/ addNodeGroup adds node group defined in string spec. Format:\n\/\/ minNodes:maxNodes:migUrl\nfunc (gce *GceCloudProvider) addNodeGroup(spec string) error {\n\tmig, err := buildMig(spec, gce.gceManager)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgce.migs = append(gce.migs, mig)\n\tgce.gceManager.RegisterMig(mig)\n\treturn nil\n}\n\n\/\/ Name returns name of the cloud provider.\nfunc (gce *GceCloudProvider) Name() string {\n\treturn \"gce\"\n}\n\n\/\/ NodeGroups returns all node groups configured for this cloud provider.\nfunc (gce *GceCloudProvider) NodeGroups() []cloudprovider.NodeGroup {\n\tresult := make([]cloudprovider.NodeGroup, 0, len(gce.migs))\n\tfor _, mig := range gce.migs {\n\t\tresult = append(result, mig)\n\t}\n\treturn result\n}\n\n\/\/ NodeGroupForNode returns the node group for the given node.\nfunc (gce *GceCloudProvider) NodeGroupForNode(node *kube_api.Node) (cloudprovider.NodeGroup, error) {\n\tref, err := GceRefFromProviderId(node.Spec.ProviderID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmig, err := gce.gceManager.GetMigForInstance(ref)\n\treturn mig, err\n}\n\n\/\/ GceRef contains s reference to some entity in GCE\/GKE world.\ntype GceRef struct {\n\tProject string\n\tZone    string\n\tName    string\n}\n\n\/\/ GceRefFromProviderId creates InstanceConfig object\n\/\/ from provider id which must be in format:\n\/\/ gce:\/\/<project-id>\/<zone>\/<name>\n\/\/ TODO(piosz): add better check whether the id is correct\nfunc GceRefFromProviderId(id string) (*GceRef, error) {\n\tsplitted := strings.Split(id[6:], \"\/\")\n\tif len(splitted) != 3 {\n\t\treturn nil, fmt.Errorf(\"Wrong id: expected format gce:\/\/<project-id>\/<zone>\/<name>, got %v\", id)\n\t}\n\treturn &GceRef{\n\t\tProject: splitted[0],\n\t\tZone:    splitted[1],\n\t\tName:    splitted[2],\n\t}, nil\n}\n\n\/\/ Mig implements NodeGroup interfrace.\ntype Mig struct {\n\tGceRef\n\n\tgceManager *GceManager\n\n\tminSize int\n\tmaxSize int\n}\n\n\/\/ MaxSize returns maximum size of the node group.\nfunc (mig *Mig) MaxSize() int {\n\treturn mig.maxSize\n}\n\n\/\/ MinSize returns minimum size of the node group.\nfunc (mig *Mig) MinSize() int {\n\treturn mig.minSize\n}\n\n\/\/ TargetSize returns the current TARGET size of the node group. It is possible that the\n\/\/ number is different from the number of nodes registered in Kuberentes.\nfunc (mig *Mig) TargetSize() (int, error) {\n\tsize, err := mig.gceManager.GetMigSize(mig)\n\treturn int(size), err\n}\n\n\/\/ IncreaseSize increases Mig size\nfunc (mig *Mig) IncreaseSize(delta int) error {\n\tif delta <= 0 {\n\t\treturn fmt.Errorf(\"size increase must be positive\")\n\t}\n\tsize, err := mig.gceManager.GetMigSize(mig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif int(size)+delta > mig.MaxSize() {\n\t\treturn fmt.Errorf(\"size increase too large - desired:%d max:%d\", int(size)+delta, mig.MaxSize())\n\t}\n\treturn mig.gceManager.SetMigSize(mig, size+int64(delta))\n}\n\n\/\/ Belongs returns true if the given node belongs to the NodeGroup.\nfunc (mig *Mig) Belongs(node *kube_api.Node) (bool, error) {\n\tref, err := GceRefFromProviderId(node.Spec.ProviderID)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\ttargetMig, err := mig.gceManager.GetMigForInstance(ref)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif targetMig == nil {\n\t\treturn false, fmt.Errorf(\"%s doesn't belong to a known mig\", node.Name)\n\t}\n\tif targetMig.Id() != mig.Id() {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}\n\n\/\/ DeleteNodes deletes the nodes from the group.\nfunc (mig *Mig) DeleteNodes(nodes []*kube_api.Node) error {\n\tsize, err := mig.gceManager.GetMigSize(mig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif int(size) <= mig.MinSize() {\n\t\treturn fmt.Errorf(\"min size reached, nodes will not be deleted\")\n\t}\n\trefs := make([]*GceRef, 0, len(nodes))\n\tfor _, node := range nodes {\n\n\t\tbelongs, err := mig.Belongs(node)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif belongs {\n\t\t\treturn fmt.Errorf(\"%s belong to a different mig than %s\", node.Name, mig.Id())\n\t\t}\n\t\tgceref, err := GceRefFromProviderId(node.Spec.ProviderID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trefs = append(refs, gceref)\n\t}\n\treturn mig.gceManager.DeleteInstances(refs)\n}\n\n\/\/ Id returns mig url.\nfunc (mig *Mig) Id() string {\n\treturn GenerateMigUrl(mig.Project, mig.Zone, mig.Name)\n}\n\n\/\/ Debug returns a debug string for the Mig.\nfunc (mig *Mig) Debug() string {\n\treturn fmt.Sprintf(\"%s (%d:%d)\", mig.Id(), mig.MinSize(), mig.MaxSize())\n}\n\nfunc buildMig(value string, gceManager *GceManager) (*Mig, error) {\n\ttokens := strings.SplitN(value, \":\", 3)\n\tif len(tokens) != 3 {\n\t\treturn nil, fmt.Errorf(\"wrong nodes configuration: %s\", value)\n\t}\n\n\tmig := Mig{\n\t\tgceManager: gceManager,\n\t}\n\tif size, err := strconv.Atoi(tokens[0]); err == nil {\n\t\tif size <= 0 {\n\t\t\treturn nil, fmt.Errorf(\"min size must be >= 1\")\n\t\t}\n\t\tmig.minSize = size\n\t} else {\n\t\treturn nil, fmt.Errorf(\"failed to set min size: %s, expected integer\", tokens[0])\n\t}\n\n\tif size, err := strconv.Atoi(tokens[1]); err == nil {\n\t\tif size < mig.minSize {\n\t\t\treturn nil, fmt.Errorf(\"max size must be greater or equal to min size\")\n\t\t}\n\t\tmig.maxSize = size\n\t} else {\n\t\treturn nil, fmt.Errorf(\"failed to set max size: %s, expected integer\", tokens[1])\n\t}\n\n\tvar err error\n\tif mig.Project, mig.Zone, mig.Name, err = ParseMigUrl(tokens[2]); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse mig url: %s got error: %v\", tokens[2], err)\n\t}\n\treturn &mig, nil\n}\n<commit_msg>Cluster-autoscaler: fix belongs check in gce cloud provider<commit_after>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage gce\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"k8s.io\/contrib\/cluster-autoscaler\/cloudprovider\"\n\tkube_api \"k8s.io\/kubernetes\/pkg\/api\"\n)\n\n\/\/ GceCloudProvider implements CloudProvider interface.\ntype GceCloudProvider struct {\n\tgceManager *GceManager\n\tmigs       []*Mig\n}\n\n\/\/ BuildGceCloudProvider builds CloudProvider implementation for GCE.\nfunc BuildGceCloudProvider(gceManager *GceManager, specs []string) (*GceCloudProvider, error) {\n\tgce := &GceCloudProvider{\n\t\tgceManager: gceManager,\n\t\tmigs:       make([]*Mig, 0),\n\t}\n\tfor _, spec := range specs {\n\t\tif err := gce.addNodeGroup(spec); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn gce, nil\n}\n\n\/\/ addNodeGroup adds node group defined in string spec. Format:\n\/\/ minNodes:maxNodes:migUrl\nfunc (gce *GceCloudProvider) addNodeGroup(spec string) error {\n\tmig, err := buildMig(spec, gce.gceManager)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgce.migs = append(gce.migs, mig)\n\tgce.gceManager.RegisterMig(mig)\n\treturn nil\n}\n\n\/\/ Name returns name of the cloud provider.\nfunc (gce *GceCloudProvider) Name() string {\n\treturn \"gce\"\n}\n\n\/\/ NodeGroups returns all node groups configured for this cloud provider.\nfunc (gce *GceCloudProvider) NodeGroups() []cloudprovider.NodeGroup {\n\tresult := make([]cloudprovider.NodeGroup, 0, len(gce.migs))\n\tfor _, mig := range gce.migs {\n\t\tresult = append(result, mig)\n\t}\n\treturn result\n}\n\n\/\/ NodeGroupForNode returns the node group for the given node.\nfunc (gce *GceCloudProvider) NodeGroupForNode(node *kube_api.Node) (cloudprovider.NodeGroup, error) {\n\tref, err := GceRefFromProviderId(node.Spec.ProviderID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmig, err := gce.gceManager.GetMigForInstance(ref)\n\treturn mig, err\n}\n\n\/\/ GceRef contains s reference to some entity in GCE\/GKE world.\ntype GceRef struct {\n\tProject string\n\tZone    string\n\tName    string\n}\n\n\/\/ GceRefFromProviderId creates InstanceConfig object\n\/\/ from provider id which must be in format:\n\/\/ gce:\/\/<project-id>\/<zone>\/<name>\n\/\/ TODO(piosz): add better check whether the id is correct\nfunc GceRefFromProviderId(id string) (*GceRef, error) {\n\tsplitted := strings.Split(id[6:], \"\/\")\n\tif len(splitted) != 3 {\n\t\treturn nil, fmt.Errorf(\"Wrong id: expected format gce:\/\/<project-id>\/<zone>\/<name>, got %v\", id)\n\t}\n\treturn &GceRef{\n\t\tProject: splitted[0],\n\t\tZone:    splitted[1],\n\t\tName:    splitted[2],\n\t}, nil\n}\n\n\/\/ Mig implements NodeGroup interfrace.\ntype Mig struct {\n\tGceRef\n\n\tgceManager *GceManager\n\n\tminSize int\n\tmaxSize int\n}\n\n\/\/ MaxSize returns maximum size of the node group.\nfunc (mig *Mig) MaxSize() int {\n\treturn mig.maxSize\n}\n\n\/\/ MinSize returns minimum size of the node group.\nfunc (mig *Mig) MinSize() int {\n\treturn mig.minSize\n}\n\n\/\/ TargetSize returns the current TARGET size of the node group. It is possible that the\n\/\/ number is different from the number of nodes registered in Kuberentes.\nfunc (mig *Mig) TargetSize() (int, error) {\n\tsize, err := mig.gceManager.GetMigSize(mig)\n\treturn int(size), err\n}\n\n\/\/ IncreaseSize increases Mig size\nfunc (mig *Mig) IncreaseSize(delta int) error {\n\tif delta <= 0 {\n\t\treturn fmt.Errorf(\"size increase must be positive\")\n\t}\n\tsize, err := mig.gceManager.GetMigSize(mig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif int(size)+delta > mig.MaxSize() {\n\t\treturn fmt.Errorf(\"size increase too large - desired:%d max:%d\", int(size)+delta, mig.MaxSize())\n\t}\n\treturn mig.gceManager.SetMigSize(mig, size+int64(delta))\n}\n\n\/\/ Belongs returns true if the given node belongs to the NodeGroup.\nfunc (mig *Mig) Belongs(node *kube_api.Node) (bool, error) {\n\tref, err := GceRefFromProviderId(node.Spec.ProviderID)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\ttargetMig, err := mig.gceManager.GetMigForInstance(ref)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif targetMig == nil {\n\t\treturn false, fmt.Errorf(\"%s doesn't belong to a known mig\", node.Name)\n\t}\n\tif targetMig.Id() != mig.Id() {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}\n\n\/\/ DeleteNodes deletes the nodes from the group.\nfunc (mig *Mig) DeleteNodes(nodes []*kube_api.Node) error {\n\tsize, err := mig.gceManager.GetMigSize(mig)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif int(size) <= mig.MinSize() {\n\t\treturn fmt.Errorf(\"min size reached, nodes will not be deleted\")\n\t}\n\trefs := make([]*GceRef, 0, len(nodes))\n\tfor _, node := range nodes {\n\n\t\tbelongs, err := mig.Belongs(node)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !belongs {\n\t\t\treturn fmt.Errorf(\"%s belong to a different mig than %s\", node.Name, mig.Id())\n\t\t}\n\t\tgceref, err := GceRefFromProviderId(node.Spec.ProviderID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trefs = append(refs, gceref)\n\t}\n\treturn mig.gceManager.DeleteInstances(refs)\n}\n\n\/\/ Id returns mig url.\nfunc (mig *Mig) Id() string {\n\treturn GenerateMigUrl(mig.Project, mig.Zone, mig.Name)\n}\n\n\/\/ Debug returns a debug string for the Mig.\nfunc (mig *Mig) Debug() string {\n\treturn fmt.Sprintf(\"%s (%d:%d)\", mig.Id(), mig.MinSize(), mig.MaxSize())\n}\n\nfunc buildMig(value string, gceManager *GceManager) (*Mig, error) {\n\ttokens := strings.SplitN(value, \":\", 3)\n\tif len(tokens) != 3 {\n\t\treturn nil, fmt.Errorf(\"wrong nodes configuration: %s\", value)\n\t}\n\n\tmig := Mig{\n\t\tgceManager: gceManager,\n\t}\n\tif size, err := strconv.Atoi(tokens[0]); err == nil {\n\t\tif size <= 0 {\n\t\t\treturn nil, fmt.Errorf(\"min size must be >= 1\")\n\t\t}\n\t\tmig.minSize = size\n\t} else {\n\t\treturn nil, fmt.Errorf(\"failed to set min size: %s, expected integer\", tokens[0])\n\t}\n\n\tif size, err := strconv.Atoi(tokens[1]); err == nil {\n\t\tif size < mig.minSize {\n\t\t\treturn nil, fmt.Errorf(\"max size must be greater or equal to min size\")\n\t\t}\n\t\tmig.maxSize = size\n\t} else {\n\t\treturn nil, fmt.Errorf(\"failed to set max size: %s, expected integer\", tokens[1])\n\t}\n\n\tvar err error\n\tif mig.Project, mig.Zone, mig.Name, err = ParseMigUrl(tokens[2]); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse mig url: %s got error: %v\", tokens[2], err)\n\t}\n\treturn &mig, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 WALLIX\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage commands\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/wallix\/awless\/cloud\"\n\t\"github.com\/wallix\/awless\/config\"\n\t\"github.com\/wallix\/awless\/console\"\n\t\"github.com\/wallix\/awless\/graph\"\n\t\"github.com\/wallix\/awless\/logger\"\n\t\"github.com\/wallix\/awless\/sync\"\n)\n\nvar (\n\tlistAllSiblingsFlag          bool\n\tnoAliasFlag                  bool\n\tshowPropertiesValuesOnlyFlag []string\n)\n\nfunc init() {\n\tRootCmd.AddCommand(showCmd)\n\tshowCmd.Flags().BoolVar(&listAllSiblingsFlag, \"siblings\", false, \"List all the resource's siblings\")\n\tshowCmd.Flags().BoolVar(&noAliasFlag, \"no-alias\", false, \"Disable the resolution of ID to alias\")\n\tshowCmd.Flags().StringSliceVar(&showPropertiesValuesOnlyFlag, \"values-for\", []string{}, \"Output values only for given properties keys\")\n}\n\nvar showCmd = &cobra.Command{\n\tUse:   \"show REFERENCE\",\n\tShort: \"Show a resource and its interrelations given a REFERENCE: id or name\",\n\tExample: `  awless show i-8d43b21b            # show an instance via its ref\n  awless show AIDAJ3Z24GOKHTZO4OIX6 # show a user via its ref\n  awless show jsmith                # show a user via its ref,\n  awless show @jsmith               # forcing search by name`,\n\tPersistentPreRun:  applyHooks(initLoggerHook, initAwlessEnvHook, initCloudServicesHook, initSyncerHook, firstInstallDoneHook),\n\tPersistentPostRun: applyHooks(verifyNewVersionHook, onVersionUpgrade),\n\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tif len(args) < 1 {\n\t\t\treturn errors.New(\"REFERENCE required. See examples.\")\n\t\t}\n\n\t\tref := args[0]\n\t\tnotFound := fmt.Sprintf(\"resource with reference '%s' not found\", deprefix(ref))\n\n\t\tvar resource *graph.Resource\n\t\tvar gph *graph.Graph\n\n\t\tresource, gph = findResourceInLocalGraphs(ref)\n\n\t\tif resource == nil && localGlobalFlag {\n\t\t\tlogger.Info(notFound)\n\t\t\treturn nil\n\t\t} else if resource == nil {\n\t\t\trunFullSync()\n\n\t\t\tif resource, gph = findResourceInLocalGraphs(ref); resource == nil {\n\t\t\t\tlogger.Info(notFound)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tif !localGlobalFlag && config.GetAutosync() {\n\t\t\tsrv, err := cloud.GetServiceForType(resource.Type())\n\t\t\texitOn(err)\n\t\t\tlogger.Verbosef(\"syncing service for %s type\", resource.Type())\n\t\t\tif _, err = sync.DefaultSyncer.Sync(srv); err != nil {\n\t\t\t\tlogger.Verbose(err)\n\t\t\t}\n\t\t\tresource, gph = findResourceInLocalGraphs(ref)\n\t\t}\n\n\t\tif resource != nil {\n\t\t\tif len(showPropertiesValuesOnlyFlag) > 0 {\n\t\t\t\tshowResourceValuesOnlyFor(resource, showPropertiesValuesOnlyFlag)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tshowResource(resource, gph)\n\t\t}\n\n\t\treturn nil\n\t},\n}\n\nfunc showResourceValuesOnlyFor(resource *graph.Resource, propKeys []string) {\n\tvar normalized []string\n\tfor _, p := range propKeys {\n\t\tnormalized = append(normalized, strings.ToLower(strings.Replace(p, \" \", \"\", -1)))\n\t}\n\n\tvaluesForKeys := map[string]string{}\n\tisIncluded := func(s string) (bool, string) {\n\t\tfor _, n := range normalized {\n\t\t\tif n == strings.ToLower(s) {\n\t\t\t\treturn true, n\n\t\t\t}\n\t\t}\n\t\treturn false, \"\"\n\t}\n\tfor k, v := range resource.Properties {\n\t\tif ok, p := isIncluded(k); ok {\n\t\t\tvaluesForKeys[p] = fmt.Sprint(v)\n\t\t}\n\t}\n\n\tvar values []string\n\tfor _, n := range normalized {\n\t\tif v, ok := valuesForKeys[n]; ok {\n\t\t\tvalues = append(values, v)\n\t\t}\n\t}\n\n\tfmt.Println(strings.Join(values, \",\"))\n}\n\nfunc showResource(resource *graph.Resource, gph *graph.Graph) {\n\tdisplayer, err := console.BuildOptions(\n\t\tconsole.WithHeaders(console.DefaultsColumnDefinitions[resource.Type()]),\n\t\tconsole.WithFormat(listingFormat),\n\t\tconsole.WithMaxWidth(console.GetTerminalWidth()),\n\t).SetSource(resource).Build()\n\texitOn(err)\n\n\texitOn(displayer.Print(os.Stdout))\n\n\tvar parents []*graph.Resource\n\terr = gph.Accept(&graph.ParentsVisitor{From: resource, Each: graph.VisitorCollectFunc(&parents)})\n\texitOn(err)\n\n\tvar parentsW bytes.Buffer\n\tvar count int\n\tfor i := len(parents) - 1; i >= 0; i-- {\n\t\tif count == 0 {\n\t\t\tfmt.Fprintf(&parentsW, \"%s\\n\", printResourceRef(parents[i]))\n\t\t} else {\n\t\t\tfmt.Fprintf(&parentsW, \"%s↳ %s\\n\", strings.Repeat(\"\\t\", count), printResourceRef(parents[i]))\n\t\t}\n\t\tcount++\n\t}\n\n\tvar childrenW bytes.Buffer\n\tvar hasChildren bool\n\tprintWithTabs := func(r *graph.Resource, distance int) error {\n\t\tvar tabs bytes.Buffer\n\t\ttabs.WriteString(strings.Repeat(\"\\t\", count))\n\t\tfor i := 0; i < distance; i++ {\n\t\t\ttabs.WriteByte('\\t')\n\t\t}\n\n\t\tdisplay := r.String()\n\t\tif r.Same(resource) {\n\t\t\tdisplay = renderGreenFn(printResourceRef(resource))\n\t\t} else {\n\t\t\thasChildren = true\n\t\t}\n\t\tfmt.Fprintf(&childrenW, \"%s↳ %s\\n\", tabs.String(), display)\n\t\treturn nil\n\t}\n\terr = gph.Accept(&graph.ChildrenVisitor{From: resource, Each: printWithTabs, IncludeFrom: true})\n\texitOn(err)\n\n\tif len(parents) > 0 || hasChildren {\n\t\tfmt.Println(renderCyanBoldFn(\"\\n# Relations:\"))\n\t\tfmt.Printf(parentsW.String())\n\t\tfmt.Printf(childrenW.String())\n\t}\n\n\tappliedOn, err := gph.ListResourcesAppliedOn(resource)\n\texitOn(err)\n\tprintResourceList(renderCyanBoldFn(\"Applied on\"), appliedOn)\n\n\tdependingOn, err := gph.ListResourcesDependingOn(resource)\n\texitOn(err)\n\tprintResourceList(renderCyanBoldFn(\"Depending on\"), dependingOn)\n\n\tvar siblings []*graph.Resource\n\terr = gph.Accept(&graph.SiblingsVisitor{From: resource, Each: graph.VisitorCollectFunc(&siblings)})\n\texitOn(err)\n\tprintResourceList(renderCyanBoldFn(\"Siblings\"), siblings, \"display all with flag --siblings\")\n}\n\nfunc runFullSync() {\n\tif !config.GetAutosync() {\n\t\tlogger.Info(\"autosync disabled\")\n\t\treturn\n\t}\n\n\tlogger.Infof(\"cannot find resource in existing data synced locally\")\n\tlogger.Infof(\"running sync for current region '%s'\", config.GetAWSRegion())\n\n\tvar services []cloud.Service\n\tfor _, srv := range cloud.ServiceRegistry {\n\t\tservices = append(services, srv)\n\t}\n\n\tif _, err := sync.DefaultSyncer.Sync(services...); err != nil {\n\t\tlogger.Verbose(err)\n\t}\n}\n\nfunc findResourceInLocalGraphs(ref string) (*graph.Resource, *graph.Graph) {\n\tg, resources := resolveResourceFromRef(ref)\n\tswitch len(resources) {\n\tcase 0:\n\t\treturn nil, nil\n\tcase 1:\n\t\treturn resources[0], g\n\tdefault:\n\t\tlogger.Infof(\"%d resources found with name '%s'. Show a specific resource with:\", len(resources), deprefix(ref))\n\t\tfor _, res := range resources {\n\t\t\tvar buf bytes.Buffer\n\t\t\tbuf.WriteString(fmt.Sprintf(\"\\t`awless show %s` to show the %s\", res.Id(), res.Type()))\n\t\t\tif state, ok := res.Properties[\"State\"].(string); ok {\n\t\t\t\tbuf.WriteString(fmt.Sprintf(\" (state: '%s')\", state))\n\t\t\t}\n\t\t\tlogger.Infof(buf.String())\n\t\t}\n\n\t\tos.Exit(0)\n\t}\n\n\treturn nil, nil\n}\n\nfunc resolveResourceFromRef(ref string) (*graph.Graph, []*graph.Resource) {\n\tg, err := sync.LoadAllLocalGraphs()\n\texitOn(err)\n\n\tname := deprefix(ref)\n\tbyName := &graph.ByProperty{Key: \"Name\", Value: name}\n\n\tif strings.HasPrefix(ref, \"@\") {\n\t\tlogger.Verbosef(\"prefixed with @: forcing research by name '%s'\", name)\n\t\trs, err := g.ResolveResources(byName)\n\t\texitOn(err)\n\t\treturn g, rs\n\t} else {\n\t\trs, err := g.ResolveResources(&graph.ById{Id: name})\n\t\texitOn(err)\n\n\t\tif len(rs) > 0 {\n\t\t\treturn g, rs\n\t\t} else {\n\t\t\trs, err := g.ResolveResources(\n\t\t\t\tbyName,\n\t\t\t\t&graph.ByProperty{Key: \"Arn\", Value: name},\n\t\t\t)\n\t\t\texitOn(err)\n\n\t\t\treturn g, rs\n\t\t}\n\t}\n}\n\nfunc deprefix(s string) string {\n\treturn strings.TrimPrefix(s, \"@\")\n}\n\nfunc printResourceList(title string, list []*graph.Resource, shortenListMsg ...string) {\n\tsort.Sort(byTypeAndString{list})\n\tall := graph.Resources(list).Map(func(r *graph.Resource) string { return printResourceRef(r) })\n\tcount := len(all)\n\tmax := 3\n\tif count > 0 {\n\t\tif !listAllSiblingsFlag && len(shortenListMsg) > 0 && count > max {\n\t\t\tfmt.Printf(\"\\n%s: %s, ... (%s)\\n\", title, strings.Join(all[0:max], \", \"), shortenListMsg[0])\n\t\t} else {\n\t\t\tfmt.Printf(\"\\n%s: %s\\n\", title, strings.Join(all, \", \"))\n\t\t}\n\t}\n}\n\nfunc printResourceRef(r *graph.Resource) string {\n\tif noAliasFlag {\n\t\treturn r.Format(\"%i[%t]\")\n\t}\n\treturn r.Format(\"%n[%t]\")\n}\n\ntype byTypeAndString struct {\n\tres []*graph.Resource\n}\n\nfunc (b byTypeAndString) Len() int { return len(b.res) }\nfunc (b byTypeAndString) Swap(i, j int) {\n\tb.res[i], b.res[j] = b.res[j], b.res[i]\n}\nfunc (b byTypeAndString) Less(i, j int) bool {\n\tif b.res[i].Type() != b.res[j].Type() {\n\t\treturn b.res[i].Type() < b.res[j].Type()\n\t}\n\treturn b.res[i].String() <= b.res[j].String()\n}\n<commit_msg>Fix display of children with --no-alias flag<commit_after>\/*\nCopyright 2017 WALLIX\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage commands\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/wallix\/awless\/cloud\"\n\t\"github.com\/wallix\/awless\/config\"\n\t\"github.com\/wallix\/awless\/console\"\n\t\"github.com\/wallix\/awless\/graph\"\n\t\"github.com\/wallix\/awless\/logger\"\n\t\"github.com\/wallix\/awless\/sync\"\n)\n\nvar (\n\tlistAllSiblingsFlag          bool\n\tnoAliasFlag                  bool\n\tshowPropertiesValuesOnlyFlag []string\n)\n\nfunc init() {\n\tRootCmd.AddCommand(showCmd)\n\tshowCmd.Flags().BoolVar(&listAllSiblingsFlag, \"siblings\", false, \"List all the resource's siblings\")\n\tshowCmd.Flags().BoolVar(&noAliasFlag, \"no-alias\", false, \"Disable the resolution of ID to alias\")\n\tshowCmd.Flags().StringSliceVar(&showPropertiesValuesOnlyFlag, \"values-for\", []string{}, \"Output values only for given properties keys\")\n}\n\nvar showCmd = &cobra.Command{\n\tUse:   \"show REFERENCE\",\n\tShort: \"Show a resource and its interrelations given a REFERENCE: id or name\",\n\tExample: `  awless show i-8d43b21b            # show an instance via its ref\n  awless show AIDAJ3Z24GOKHTZO4OIX6 # show a user via its ref\n  awless show jsmith                # show a user via its ref,\n  awless show @jsmith               # forcing search by name`,\n\tPersistentPreRun:  applyHooks(initLoggerHook, initAwlessEnvHook, initCloudServicesHook, initSyncerHook, firstInstallDoneHook),\n\tPersistentPostRun: applyHooks(verifyNewVersionHook, onVersionUpgrade),\n\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tif len(args) < 1 {\n\t\t\treturn errors.New(\"REFERENCE required. See examples.\")\n\t\t}\n\n\t\tref := args[0]\n\t\tnotFound := fmt.Sprintf(\"resource with reference '%s' not found\", deprefix(ref))\n\n\t\tvar resource *graph.Resource\n\t\tvar gph *graph.Graph\n\n\t\tresource, gph = findResourceInLocalGraphs(ref)\n\n\t\tif resource == nil && localGlobalFlag {\n\t\t\tlogger.Info(notFound)\n\t\t\treturn nil\n\t\t} else if resource == nil {\n\t\t\trunFullSync()\n\n\t\t\tif resource, gph = findResourceInLocalGraphs(ref); resource == nil {\n\t\t\t\tlogger.Info(notFound)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tif !localGlobalFlag && config.GetAutosync() {\n\t\t\tsrv, err := cloud.GetServiceForType(resource.Type())\n\t\t\texitOn(err)\n\t\t\tlogger.Verbosef(\"syncing service for %s type\", resource.Type())\n\t\t\tif _, err = sync.DefaultSyncer.Sync(srv); err != nil {\n\t\t\t\tlogger.Verbose(err)\n\t\t\t}\n\t\t\tresource, gph = findResourceInLocalGraphs(ref)\n\t\t}\n\n\t\tif resource != nil {\n\t\t\tif len(showPropertiesValuesOnlyFlag) > 0 {\n\t\t\t\tshowResourceValuesOnlyFor(resource, showPropertiesValuesOnlyFlag)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tshowResource(resource, gph)\n\t\t}\n\n\t\treturn nil\n\t},\n}\n\nfunc showResourceValuesOnlyFor(resource *graph.Resource, propKeys []string) {\n\tvar normalized []string\n\tfor _, p := range propKeys {\n\t\tnormalized = append(normalized, strings.ToLower(strings.Replace(p, \" \", \"\", -1)))\n\t}\n\n\tvaluesForKeys := map[string]string{}\n\tisIncluded := func(s string) (bool, string) {\n\t\tfor _, n := range normalized {\n\t\t\tif n == strings.ToLower(s) {\n\t\t\t\treturn true, n\n\t\t\t}\n\t\t}\n\t\treturn false, \"\"\n\t}\n\tfor k, v := range resource.Properties {\n\t\tif ok, p := isIncluded(k); ok {\n\t\t\tvaluesForKeys[p] = fmt.Sprint(v)\n\t\t}\n\t}\n\n\tvar values []string\n\tfor _, n := range normalized {\n\t\tif v, ok := valuesForKeys[n]; ok {\n\t\t\tvalues = append(values, v)\n\t\t}\n\t}\n\n\tfmt.Println(strings.Join(values, \",\"))\n}\n\nfunc showResource(resource *graph.Resource, gph *graph.Graph) {\n\tdisplayer, err := console.BuildOptions(\n\t\tconsole.WithHeaders(console.DefaultsColumnDefinitions[resource.Type()]),\n\t\tconsole.WithFormat(listingFormat),\n\t\tconsole.WithMaxWidth(console.GetTerminalWidth()),\n\t).SetSource(resource).Build()\n\texitOn(err)\n\n\texitOn(displayer.Print(os.Stdout))\n\n\tvar parents []*graph.Resource\n\terr = gph.Accept(&graph.ParentsVisitor{From: resource, Each: graph.VisitorCollectFunc(&parents)})\n\texitOn(err)\n\n\tvar parentsW bytes.Buffer\n\tvar count int\n\tfor i := len(parents) - 1; i >= 0; i-- {\n\t\tif count == 0 {\n\t\t\tfmt.Fprintf(&parentsW, \"%s\\n\", printResourceRef(parents[i]))\n\t\t} else {\n\t\t\tfmt.Fprintf(&parentsW, \"%s↳ %s\\n\", strings.Repeat(\"\\t\", count), printResourceRef(parents[i]))\n\t\t}\n\t\tcount++\n\t}\n\n\tvar childrenW bytes.Buffer\n\tvar hasChildren bool\n\tprintWithTabs := func(r *graph.Resource, distance int) error {\n\t\tvar tabs bytes.Buffer\n\t\ttabs.WriteString(strings.Repeat(\"\\t\", count))\n\t\tfor i := 0; i < distance; i++ {\n\t\t\ttabs.WriteByte('\\t')\n\t\t}\n\n\t\tdisplay := printResourceRef(r)\n\t\tif r.Same(resource) {\n\t\t\tdisplay = renderGreenFn(printResourceRef(resource))\n\t\t} else {\n\t\t\thasChildren = true\n\t\t}\n\t\tfmt.Fprintf(&childrenW, \"%s↳ %s\\n\", tabs.String(), display)\n\t\treturn nil\n\t}\n\terr = gph.Accept(&graph.ChildrenVisitor{From: resource, Each: printWithTabs, IncludeFrom: true})\n\texitOn(err)\n\n\tif len(parents) > 0 || hasChildren {\n\t\tfmt.Println(renderCyanBoldFn(\"\\n# Relations:\"))\n\t\tfmt.Printf(parentsW.String())\n\t\tfmt.Printf(childrenW.String())\n\t}\n\n\tappliedOn, err := gph.ListResourcesAppliedOn(resource)\n\texitOn(err)\n\tprintResourceList(renderCyanBoldFn(\"Applied on\"), appliedOn)\n\n\tdependingOn, err := gph.ListResourcesDependingOn(resource)\n\texitOn(err)\n\tprintResourceList(renderCyanBoldFn(\"Depending on\"), dependingOn)\n\n\tvar siblings []*graph.Resource\n\terr = gph.Accept(&graph.SiblingsVisitor{From: resource, Each: graph.VisitorCollectFunc(&siblings)})\n\texitOn(err)\n\tprintResourceList(renderCyanBoldFn(\"Siblings\"), siblings, \"display all with flag --siblings\")\n}\n\nfunc runFullSync() {\n\tif !config.GetAutosync() {\n\t\tlogger.Info(\"autosync disabled\")\n\t\treturn\n\t}\n\n\tlogger.Infof(\"cannot find resource in existing data synced locally\")\n\tlogger.Infof(\"running sync for current region '%s'\", config.GetAWSRegion())\n\n\tvar services []cloud.Service\n\tfor _, srv := range cloud.ServiceRegistry {\n\t\tservices = append(services, srv)\n\t}\n\n\tif _, err := sync.DefaultSyncer.Sync(services...); err != nil {\n\t\tlogger.Verbose(err)\n\t}\n}\n\nfunc findResourceInLocalGraphs(ref string) (*graph.Resource, *graph.Graph) {\n\tg, resources := resolveResourceFromRef(ref)\n\tswitch len(resources) {\n\tcase 0:\n\t\treturn nil, nil\n\tcase 1:\n\t\treturn resources[0], g\n\tdefault:\n\t\tlogger.Infof(\"%d resources found with name '%s'. Show a specific resource with:\", len(resources), deprefix(ref))\n\t\tfor _, res := range resources {\n\t\t\tvar buf bytes.Buffer\n\t\t\tbuf.WriteString(fmt.Sprintf(\"\\t`awless show %s` to show the %s\", res.Id(), res.Type()))\n\t\t\tif state, ok := res.Properties[\"State\"].(string); ok {\n\t\t\t\tbuf.WriteString(fmt.Sprintf(\" (state: '%s')\", state))\n\t\t\t}\n\t\t\tlogger.Infof(buf.String())\n\t\t}\n\n\t\tos.Exit(0)\n\t}\n\n\treturn nil, nil\n}\n\nfunc resolveResourceFromRef(ref string) (*graph.Graph, []*graph.Resource) {\n\tg, err := sync.LoadAllLocalGraphs()\n\texitOn(err)\n\n\tname := deprefix(ref)\n\tbyName := &graph.ByProperty{Key: \"Name\", Value: name}\n\n\tif strings.HasPrefix(ref, \"@\") {\n\t\tlogger.Verbosef(\"prefixed with @: forcing research by name '%s'\", name)\n\t\trs, err := g.ResolveResources(byName)\n\t\texitOn(err)\n\t\treturn g, rs\n\t} else {\n\t\trs, err := g.ResolveResources(&graph.ById{Id: name})\n\t\texitOn(err)\n\n\t\tif len(rs) > 0 {\n\t\t\treturn g, rs\n\t\t} else {\n\t\t\trs, err := g.ResolveResources(\n\t\t\t\tbyName,\n\t\t\t\t&graph.ByProperty{Key: \"Arn\", Value: name},\n\t\t\t)\n\t\t\texitOn(err)\n\n\t\t\treturn g, rs\n\t\t}\n\t}\n}\n\nfunc deprefix(s string) string {\n\treturn strings.TrimPrefix(s, \"@\")\n}\n\nfunc printResourceList(title string, list []*graph.Resource, shortenListMsg ...string) {\n\tsort.Sort(byTypeAndString{list})\n\tall := graph.Resources(list).Map(func(r *graph.Resource) string { return printResourceRef(r) })\n\tcount := len(all)\n\tmax := 3\n\tif count > 0 {\n\t\tif !listAllSiblingsFlag && len(shortenListMsg) > 0 && count > max {\n\t\t\tfmt.Printf(\"\\n%s: %s, ... (%s)\\n\", title, strings.Join(all[0:max], \", \"), shortenListMsg[0])\n\t\t} else {\n\t\t\tfmt.Printf(\"\\n%s: %s\\n\", title, strings.Join(all, \", \"))\n\t\t}\n\t}\n}\n\nfunc printResourceRef(r *graph.Resource) string {\n\tif noAliasFlag {\n\t\treturn r.Format(\"%i[%t]\")\n\t}\n\treturn r.Format(\"%n[%t]\")\n}\n\ntype byTypeAndString struct {\n\tres []*graph.Resource\n}\n\nfunc (b byTypeAndString) Len() int { return len(b.res) }\nfunc (b byTypeAndString) Swap(i, j int) {\n\tb.res[i], b.res[j] = b.res[j], b.res[i]\n}\nfunc (b byTypeAndString) Less(i, j int) bool {\n\tif b.res[i].Type() != b.res[j].Type() {\n\t\treturn b.res[i].Type() < b.res[j].Type()\n\t}\n\treturn b.res[i].String() <= b.res[j].String()\n}\n<|endoftext|>"}
{"text":"<commit_before>package txtdirect\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tbasezone        = \"_redirect\"\n\tdefaultSub      = \"www\"\n\tdefaultProtocol = \"https\"\n)\n\ntype record struct {\n\tVersion string\n\tTo      string\n\tCode    int\n\tType    string\n\tVcs     string\n}\n\n\/\/ Config contains the middleware's configuration\ntype Config struct {\n\tEnable   []string\n\tRedirect string\n}\n\nfunc (r *record) Parse(str string) error {\n\ts := strings.Split(str, \";\")\n\tfor _, l := range s {\n\t\tswitch {\n\t\tcase strings.HasPrefix(l, \"v=\"):\n\t\t\tl = strings.TrimPrefix(l, \"v=\")\n\t\t\tr.Version = l\n\t\t\tif r.Version != \"txtv0\" {\n\t\t\t\treturn fmt.Errorf(\"unhandled version '%s'\", r.Version)\n\t\t\t}\n\t\t\tlog.Print(\"WARN: txtv0 is not suitable for production\")\n\n\t\tcase strings.HasPrefix(l, \"to=\"):\n\t\t\tl = strings.TrimPrefix(l, \"to=\")\n\t\t\tr.To = l\n\n\t\tcase strings.HasPrefix(l, \"code=\"):\n\t\t\tl = strings.TrimPrefix(l, \"code=\")\n\t\t\ti, err := strconv.Atoi(l)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not parse status code: %s\", err)\n\t\t\t}\n\t\t\tr.Code = i\n\n\t\tcase strings.HasPrefix(l, \"type=\"):\n\t\t\tl = strings.TrimPrefix(l, \"type=\")\n\t\t\tr.Type = l\n\n\t\tcase strings.HasPrefix(l, \"vcs=\"):\n\t\t\tl = strings.TrimPrefix(l, \"vcs=\")\n\t\t\tr.Vcs = l\n\n\t\tdefault:\n\t\t\tif r.To != \"\" {\n\t\t\t\treturn fmt.Errorf(\"multiple values without keys\")\n\t\t\t}\n\t\t\tr.To = l\n\t\t}\n\t}\n\n\tif r.Code == 0 {\n\t\tr.Code = 301\n\t}\n\n\tif r.Vcs == \"\" {\n\t\tr.Vcs = \"git\"\n\t}\n\n\tif r.Type == \"\" {\n\t\tr.Type = \"host\"\n\t}\n\n\treturn nil\n}\n\nfunc getBaseTarget(rec record) (string, int) {\n\treturn rec.To, rec.Code\n}\n\nfunc getRecord(host, path string) (record, error) {\n\tzone := strings.Join([]string{basezone, host}, \".\")\n\ts, err := net.LookupTXT(zone)\n\tif err != nil {\n\t\treturn record{}, fmt.Errorf(\"could not get TXT record: %s\", err)\n\t}\n\n\trec := record{}\n\tif err = rec.Parse(s[0]); err != nil {\n\t\treturn rec, fmt.Errorf(\"could not parse record: %s\", err)\n\t}\n\n\tif rec.To == \"\" {\n\t\ts := []string{defaultProtocol, \":\/\/\", defaultSub, \".\", host}\n\t\trec.To = strings.Join(s, \"\")\n\t}\n\n\treturn rec, nil\n}\n\nfunc contains(array []string, word string) bool {\n\tfor _, w := range array {\n\t\tif w == word {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Redirect the request depending on the redirect record found\nfunc Redirect(w http.ResponseWriter, r *http.Request, c Config) error {\n\thost := r.Host\n\tpath := r.URL.Path\n\n\trec, err := getRecord(host, path)\n\tif err != nil {\n\t\tif strings.HasSuffix(err.Error(), \"no such host\") {\n\t\t\ts := []string{defaultProtocol, \":\/\/\", defaultSub, \".\", host}\n\t\t\thttp.Redirect(w, r, strings.Join(s, \"\"), 301)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tif !contains(c.Enable, rec.Type) {\n\t\treturn fmt.Errorf(\"option disabled\")\n\t}\n\n\tif rec.Type == \"host\" {\n\t\tto, code := getBaseTarget(rec)\n\t\thttp.Redirect(w, r, to, code)\n\t\treturn nil\n\t}\n\n\tif rec.Type == \"gometa\" {\n\t\treturn gometa(w, rec, host, path)\n\t}\n\n\treturn fmt.Errorf(\"record type %s unsupported\", rec.Type)\n}\n<commit_msg>Make 404 the default behavior when www is disabled<commit_after>package txtdirect\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tbasezone        = \"_redirect\"\n\tdefaultSub      = \"www\"\n\tdefaultProtocol = \"https\"\n)\n\ntype record struct {\n\tVersion string\n\tTo      string\n\tCode    int\n\tType    string\n\tVcs     string\n}\n\n\/\/ Config contains the middleware's configuration\ntype Config struct {\n\tEnable   []string\n\tRedirect string\n}\n\nfunc (r *record) Parse(str string) error {\n\ts := strings.Split(str, \";\")\n\tfor _, l := range s {\n\t\tswitch {\n\t\tcase strings.HasPrefix(l, \"v=\"):\n\t\t\tl = strings.TrimPrefix(l, \"v=\")\n\t\t\tr.Version = l\n\t\t\tif r.Version != \"txtv0\" {\n\t\t\t\treturn fmt.Errorf(\"unhandled version '%s'\", r.Version)\n\t\t\t}\n\t\t\tlog.Print(\"WARN: txtv0 is not suitable for production\")\n\n\t\tcase strings.HasPrefix(l, \"to=\"):\n\t\t\tl = strings.TrimPrefix(l, \"to=\")\n\t\t\tr.To = l\n\n\t\tcase strings.HasPrefix(l, \"code=\"):\n\t\t\tl = strings.TrimPrefix(l, \"code=\")\n\t\t\ti, err := strconv.Atoi(l)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not parse status code: %s\", err)\n\t\t\t}\n\t\t\tr.Code = i\n\n\t\tcase strings.HasPrefix(l, \"type=\"):\n\t\t\tl = strings.TrimPrefix(l, \"type=\")\n\t\t\tr.Type = l\n\n\t\tcase strings.HasPrefix(l, \"vcs=\"):\n\t\t\tl = strings.TrimPrefix(l, \"vcs=\")\n\t\t\tr.Vcs = l\n\n\t\tdefault:\n\t\t\tif r.To != \"\" {\n\t\t\t\treturn fmt.Errorf(\"multiple values without keys\")\n\t\t\t}\n\t\t\tr.To = l\n\t\t}\n\t}\n\n\tif r.Code == 0 {\n\t\tr.Code = 301\n\t}\n\n\tif r.Vcs == \"\" {\n\t\tr.Vcs = \"git\"\n\t}\n\n\tif r.Type == \"\" {\n\t\tr.Type = \"host\"\n\t}\n\n\treturn nil\n}\n\nfunc getBaseTarget(rec record) (string, int) {\n\treturn rec.To, rec.Code\n}\n\nfunc getRecord(host, path string) (record, error) {\n\tzone := strings.Join([]string{basezone, host}, \".\")\n\ts, err := net.LookupTXT(zone)\n\tif err != nil {\n\t\treturn record{}, fmt.Errorf(\"could not get TXT record: %s\", err)\n\t}\n\n\trec := record{}\n\tif err = rec.Parse(s[0]); err != nil {\n\t\treturn rec, fmt.Errorf(\"could not parse record: %s\", err)\n\t}\n\n\tif rec.To == \"\" {\n\t\ts := []string{defaultProtocol, \":\/\/\", defaultSub, \".\", host}\n\t\trec.To = strings.Join(s, \"\")\n\t}\n\n\treturn rec, nil\n}\n\nfunc contains(array []string, word string) bool {\n\tfor _, w := range array {\n\t\tif w == word {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Redirect the request depending on the redirect record found\nfunc Redirect(w http.ResponseWriter, r *http.Request, c Config) error {\n\thost := r.Host\n\tpath := r.URL.Path\n\n\trec, err := getRecord(host, path)\n\tif err != nil {\n\t\tif strings.HasSuffix(err.Error(), \"no such host\") {\n\t\t\tif contains(c.Enable, \"www\") {\n\t\t\t\ts := []string{defaultProtocol, \":\/\/\", defaultSub, \".\", host}\n\t\t\t\thttp.Redirect(w, r, strings.Join(s, \"\"), 301)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\tif !contains(c.Enable, rec.Type) {\n\t\treturn fmt.Errorf(\"option disabled\")\n\t}\n\n\tif rec.Type == \"host\" {\n\t\tto, code := getBaseTarget(rec)\n\t\thttp.Redirect(w, r, to, code)\n\t\treturn nil\n\t}\n\n\tif rec.Type == \"gometa\" {\n\t\treturn gometa(w, rec, host, path)\n\t}\n\n\treturn fmt.Errorf(\"record type %s unsupported\", rec.Type)\n}\n<|endoftext|>"}
{"text":"<commit_before>package ais\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ Packet represents one line of AIS data\ntype Packet struct {\n\tTalker     string\n\tPacketType string\n\tFragCount  int\n\tFragNo     int\n\tSeqId      string\n\tChannel    string\n\tPayload    string\n\tFillBits   int\n}\n\nvar (\n\tErrEmptyPacket         = errors.New(\"empty packet\")\n\tErrInvalidPacketPrefix = errors.New(\"invalid prefix\")\n\tErrMissingChecksum     = errors.New(\"missing checksum\")\n\tErrIncorrectChecksum   = errors.New(\"incorrect checksum\")\n\tErrInvalidPacket       = errors.New(\"invalid packet\")\n)\n\n\/\/ ParsePacket parses one line of AIS data\nfunc ParsePacket(rawPacket string) (*Packet, error) {\n\tl := len(rawPacket)\n\tif l == 0 {\n\t\treturn nil, ErrEmptyPacket\n\t}\n\n\tif rawPacket[0] != '!' {\n\t\treturn nil, ErrInvalidPacketPrefix\n\t}\n\n\tchecksum, err := readChecksum(rawPacket)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinnerMessage := rawPacket[1 : l-3]\n\tcalculatedChecksum := calculateChecksum(innerMessage)\n\tif checksum != calculatedChecksum {\n\t\treturn nil, ErrIncorrectChecksum\n\t}\n\n\tparts := strings.Split(innerMessage, \",\")\n\n\tfragCount, err := toInt(parts[1])\n\tif err != nil {\n\t\treturn nil, ErrInvalidPacket\n\t}\n\tfragNo, err := toInt(parts[2])\n\tif err != nil {\n\t\treturn nil, ErrInvalidPacket\n\t}\n\tfillBits, err := toInt(parts[6])\n\tif err != nil {\n\t\treturn nil, ErrInvalidPacket\n\t}\n\treturn &Packet{\n\t\tTalker:     parts[0][0:2],\n\t\tPacketType: parts[0][2:],\n\t\tFragCount:  fragCount,\n\t\tFragNo:     fragNo,\n\t\tSeqId:      parts[3],\n\t\tChannel:    parts[4],\n\t\tPayload:    parts[5],\n\t\tFillBits:   fillBits,\n\t}, nil\n}\n\nfunc readChecksum(rawPacket string) (byte, error) {\n\tl := len(rawPacket)\n\tif rawPacket[l-3] != '*' {\n\t\treturn 0, ErrMissingChecksum\n\t}\n\tchecksumN := rawPacket[l-2:]\n\tchecksum, err := strconv.ParseUint(checksumN, 16, 8)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn byte(checksum), nil\n}\n\nfunc calculateChecksum(s string) uint8 {\n\tvar checksum int32\n\tfor _, r := range s {\n\t\tchecksum ^= r\n\t}\n\treturn uint8(checksum)\n}\n\nfunc toInt(s string) (int, error) {\n\treturn strconv.Atoi(s)\n}\n<commit_msg>Remove panic<commit_after>package ais\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ Packet represents one line of AIS data\ntype Packet struct {\n\tTalker     string\n\tPacketType string\n\tFragCount  int\n\tFragNo     int\n\tSeqId      string\n\tChannel    string\n\tPayload    string\n\tFillBits   int\n}\n\nvar (\n\tErrEmptyPacket         = errors.New(\"empty packet\")\n\tErrInvalidPacketPrefix = errors.New(\"invalid prefix\")\n\tErrMissingChecksum     = errors.New(\"missing checksum\")\n\tErrIncorrectChecksum   = errors.New(\"incorrect checksum\")\n\tErrInvalidPacket       = errors.New(\"invalid packet\")\n)\n\n\/\/ ParsePacket parses one line of AIS data\nfunc ParsePacket(rawPacket string) (*Packet, error) {\n\tl := len(rawPacket)\n\tif l == 0 {\n\t\treturn nil, ErrEmptyPacket\n\t}\n\n\tif rawPacket[0] != '!' {\n\t\treturn nil, ErrInvalidPacketPrefix\n\t}\n\n\tchecksum, err := readChecksum(rawPacket)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinnerMessage := rawPacket[1 : l-3]\n\tcalculatedChecksum := calculateChecksum(innerMessage)\n\tif checksum != calculatedChecksum {\n\t\treturn nil, ErrIncorrectChecksum\n\t}\n\n\tparts := strings.Split(innerMessage, \",\")\n\n\tfragCount, err := toInt(parts[1])\n\tif err != nil {\n\t\treturn nil, ErrInvalidPacket\n\t}\n\tfragNo, err := toInt(parts[2])\n\tif err != nil {\n\t\treturn nil, ErrInvalidPacket\n\t}\n\tfillBits, err := toInt(parts[6])\n\tif err != nil {\n\t\treturn nil, ErrInvalidPacket\n\t}\n\treturn &Packet{\n\t\tTalker:     parts[0][0:2],\n\t\tPacketType: parts[0][2:],\n\t\tFragCount:  fragCount,\n\t\tFragNo:     fragNo,\n\t\tSeqId:      parts[3],\n\t\tChannel:    parts[4],\n\t\tPayload:    parts[5],\n\t\tFillBits:   fillBits,\n\t}, nil\n}\n\nfunc readChecksum(rawPacket string) (byte, error) {\n\tl := len(rawPacket)\n\tif rawPacket[l-3] != '*' {\n\t\treturn 0, ErrMissingChecksum\n\t}\n\tchecksumN := rawPacket[l-2:]\n\tchecksum, err := strconv.ParseUint(checksumN, 16, 8)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn byte(checksum), nil\n}\n\nfunc calculateChecksum(s string) uint8 {\n\tvar checksum int32\n\tfor _, r := range s {\n\t\tchecksum ^= r\n\t}\n\treturn uint8(checksum)\n}\n\nfunc toInt(s string) (int, error) {\n\treturn strconv.Atoi(s)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage subnets_test\n\nimport (\n\t\"errors\"\n\n\tgc \"gopkg.in\/check.v1\"\n\n\t\"github.com\/juju\/juju\/api\/base\"\n\tapitesting \"github.com\/juju\/juju\/api\/base\/testing\"\n\t\"github.com\/juju\/juju\/api\/subnets\"\n\t\"github.com\/juju\/juju\/apiserver\/params\"\n\tcoretesting \"github.com\/juju\/juju\/testing\"\n\t\"github.com\/juju\/names\"\n)\n\n\/\/ SubnetsSuite tests the client side subnets API\ntype SubnetsSuite struct {\n\tcoretesting.BaseSuite\n\n\tcalled    int\n\tapiCaller base.APICaller\n\tapi       *subnets.API\n}\n\nvar _ = gc.Suite(&SubnetsSuite{})\n\nfunc (s *SubnetsSuite) init(c *gc.C, args *apitesting.CheckArgs, err error) {\n\ts.called = 0\n\ts.apiCaller = apitesting.CheckingAPICaller(c, args, &s.called, err)\n\ts.api = subnets.NewAPI(s.apiCaller)\n\tc.Check(s.api, gc.NotNil)\n\tc.Check(s.called, gc.Equals, 0)\n}\n\n\/\/ TestNewAPISuccess checks that a new subnets API is created when passed a non-nil caller\nfunc (s *SubnetsSuite) TestNewAPISuccess(c *gc.C) {\n\tvar called int\n\tapiCaller := apitesting.CheckingAPICaller(c, nil, &called, nil)\n\tapi := subnets.NewAPI(apiCaller)\n\tc.Check(api, gc.NotNil)\n\tc.Check(called, gc.Equals, 0)\n}\n\n\/\/ TestNewAPIWithNilCaller checks that a new subnets API is not created when passed a nil caller\nfunc (s *SubnetsSuite) TestNewAPIWithNilCaller(c *gc.C) {\n\tpanicFunc := func() { subnets.NewAPI(nil) }\n\tc.Assert(panicFunc, gc.PanicMatches, \"caller is nil\")\n}\n\nfunc makeAddSubnetsArgs(cidr, providerId, space string, zones []string) apitesting.CheckArgs {\n\tspaceTag := names.NewSpaceTag(space).String()\n\tsubnetTag := names.NewSubnetTag(cidr).String()\n\n\texpectArgs := params.AddSubnetsParams{\n\t\tSubnets: []params.AddSubnetParams{\n\t\t\t{\n\t\t\t\tSpaceTag:         spaceTag,\n\t\t\t\tSubnetTag:        subnetTag,\n\t\t\t\tSubnetProviderId: providerId,\n\t\t\t\tZones:            zones,\n\t\t\t}}}\n\n\texpectResults := params.ErrorResults{}\n\n\targs := apitesting.CheckArgs{\n\t\tFacade:  \"Subnets\",\n\t\tMethod:  \"AddSubnets\",\n\t\tArgs:    expectArgs,\n\t\tResults: expectResults,\n\t}\n\n\treturn args\n}\n\nfunc makeCreateSubnetsArgs(cidr, space string, zones []string, isPublic bool) apitesting.CheckArgs {\n\tspaceTag := names.NewSpaceTag(space).String()\n\tsubnetTag := names.NewSubnetTag(cidr).String()\n\n\texpectArgs := params.CreateSubnetsParams{\n\t\tSubnets: []params.CreateSubnetParams{\n\t\t\t{\n\t\t\t\tSpaceTag:  spaceTag,\n\t\t\t\tSubnetTag: subnetTag,\n\t\t\t\tZones:     zones,\n\t\t\t\tIsPublic:  isPublic,\n\t\t\t}}}\n\n\texpectResults := params.ErrorResults{}\n\n\targs := apitesting.CheckArgs{\n\t\tFacade:  \"Subnets\",\n\t\tMethod:  \"CreateSubnets\",\n\t\tArgs:    expectArgs,\n\t\tResults: expectResults,\n\t}\n\n\treturn args\n}\n\nfunc (s *SpacesSuite) TestAddSubnet(c *gc.C) {\n\tcidr := \"1.1.1.0\/24\"\n\tproviderId := \"foo\"\n\tspace := \"bar\"\n\tzones := []string{\"foo\", \"bar\"}\n\targs := makeAddSubnetsArgs(cidr, providerId, space, zones)\n\ts.init(c, &args, nil)\n\tresults, err := s.api.AddSubnet(cidr, providerId, space, zones)\n\tc.Assert(s.called, gc.Equals, 1)\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(results, gc.DeepEquals, args.Results)\n}\n\nfunc (s *SpacesSuite) TestAddSubnetFails(c *gc.C) {\n\tcidr := \"1.1.1.0\/24\"\n\tproviderId := \"foo\"\n\tspace := \"bar\"\n\tzones := []string{\"foo\", \"bar\"}\n\targs := makeAddSubnetsArgs(cidr, providerId, space, zones)\n\ts.init(c, &args, errors.New(\"bang\"))\n\tresults, err := s.api.AddSubnet(cidr, providerId, space, zones)\n\tc.Check(s.called, gc.Equals, 1)\n\tc.Assert(err, gc.ErrorMatches, \"bang\")\n\tc.Assert(results, gc.DeepEquals, args.Results)\n}\n\nfunc (s *SpacesSuite) TestCreateSubnet(c *gc.C) {\n\tcidr := \"1.1.1.0\/24\"\n\tspace := \"bar\"\n\tzones := []string{\"foo\", \"bar\"}\n\tisPublic := true\n\targs := makeCreateSubnetsArgs(cidr, space, zones, isPublic)\n\ts.init(c, &args, nil)\n\tresults, err := s.api.CreateSubnet(cidr, space, zones, isPublic)\n\tc.Assert(s.called, gc.Equals, 1)\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(results, gc.DeepEquals, args.Results)\n}\n\nfunc (s *SpacesSuite) TestCreateSubnetFails(c *gc.C) {\n\tcidr := \"1.1.1.0\/24\"\n\tisPublic := true\n\tspace := \"bar\"\n\tzones := []string{\"foo\", \"bar\"}\n\targs := makeCreateSubnetsArgs(cidr, space, zones, isPublic)\n\ts.init(c, &args, errors.New(\"bang\"))\n\tresults, err := s.api.CreateSubnet(cidr, space, zones, isPublic)\n\tc.Check(s.called, gc.Equals, 1)\n\tc.Assert(err, gc.ErrorMatches, \"bang\")\n\tc.Assert(results, gc.DeepEquals, args.Results)\n}\n<commit_msg>Test ListSubnets<commit_after>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage subnets_test\n\nimport (\n\t\"errors\"\n\n\tgc \"gopkg.in\/check.v1\"\n\n\t\"github.com\/juju\/juju\/api\/base\"\n\tapitesting \"github.com\/juju\/juju\/api\/base\/testing\"\n\t\"github.com\/juju\/juju\/api\/subnets\"\n\t\"github.com\/juju\/juju\/apiserver\/params\"\n\tcoretesting \"github.com\/juju\/juju\/testing\"\n\t\"github.com\/juju\/names\"\n)\n\n\/\/ SubnetsSuite tests the client side subnets API\ntype SubnetsSuite struct {\n\tcoretesting.BaseSuite\n\n\tcalled    int\n\tapiCaller base.APICaller\n\tapi       *subnets.API\n}\n\nvar _ = gc.Suite(&SubnetsSuite{})\n\nfunc (s *SubnetsSuite) init(c *gc.C, args *apitesting.CheckArgs, err error) {\n\ts.called = 0\n\ts.apiCaller = apitesting.CheckingAPICaller(c, args, &s.called, err)\n\ts.api = subnets.NewAPI(s.apiCaller)\n\tc.Check(s.api, gc.NotNil)\n\tc.Check(s.called, gc.Equals, 0)\n}\n\n\/\/ TestNewAPISuccess checks that a new subnets API is created when passed a non-nil caller\nfunc (s *SubnetsSuite) TestNewAPISuccess(c *gc.C) {\n\tvar called int\n\tapiCaller := apitesting.CheckingAPICaller(c, nil, &called, nil)\n\tapi := subnets.NewAPI(apiCaller)\n\tc.Check(api, gc.NotNil)\n\tc.Check(called, gc.Equals, 0)\n}\n\n\/\/ TestNewAPIWithNilCaller checks that a new subnets API is not created when passed a nil caller\nfunc (s *SubnetsSuite) TestNewAPIWithNilCaller(c *gc.C) {\n\tpanicFunc := func() { subnets.NewAPI(nil) }\n\tc.Assert(panicFunc, gc.PanicMatches, \"caller is nil\")\n}\n\nfunc makeAddSubnetsArgs(cidr, providerId, space string, zones []string) apitesting.CheckArgs {\n\tspaceTag := names.NewSpaceTag(space).String()\n\tsubnetTag := names.NewSubnetTag(cidr).String()\n\n\texpectArgs := params.AddSubnetsParams{\n\t\tSubnets: []params.AddSubnetParams{\n\t\t\t{\n\t\t\t\tSpaceTag:         spaceTag,\n\t\t\t\tSubnetTag:        subnetTag,\n\t\t\t\tSubnetProviderId: providerId,\n\t\t\t\tZones:            zones,\n\t\t\t}}}\n\n\texpectResults := params.ErrorResults{}\n\n\targs := apitesting.CheckArgs{\n\t\tFacade:  \"Subnets\",\n\t\tMethod:  \"AddSubnets\",\n\t\tArgs:    expectArgs,\n\t\tResults: expectResults,\n\t}\n\n\treturn args\n}\n\nfunc makeCreateSubnetsArgs(cidr, space string, zones []string, isPublic bool) apitesting.CheckArgs {\n\tspaceTag := names.NewSpaceTag(space).String()\n\tsubnetTag := names.NewSubnetTag(cidr).String()\n\n\texpectArgs := params.CreateSubnetsParams{\n\t\tSubnets: []params.CreateSubnetParams{\n\t\t\t{\n\t\t\t\tSpaceTag:  spaceTag,\n\t\t\t\tSubnetTag: subnetTag,\n\t\t\t\tZones:     zones,\n\t\t\t\tIsPublic:  isPublic,\n\t\t\t}}}\n\n\texpectResults := params.ErrorResults{}\n\n\targs := apitesting.CheckArgs{\n\t\tFacade:  \"Subnets\",\n\t\tMethod:  \"CreateSubnets\",\n\t\tArgs:    expectArgs,\n\t\tResults: expectResults,\n\t}\n\n\treturn args\n}\n\nfunc makeListSubnetsArgs(space names.SpaceTag, zone string) apitesting.CheckArgs {\n\texpectResults := params.ListSubnetsResults{}\n\texpectArgs := params.ListSubnetsParams{\n\t\tFilters: []params.ListSubnetsFilterParamsParams{\n\t\t\t{\n\t\t\t\tSpaceTag: space,\n\t\t\t\tZone:     zone,\n\t\t\t}}}\n\targs := apitesting.CheckArgs{\n\t\tFacade:  \"Subnets\",\n\t\tMethod:  \"ListSubnets\",\n\t\tResults: expectResults,\n\t\tArgs:    expectArgs,\n\t}\n\treturn args\n}\n\nfunc (s *SubnetsSuite) TestAddSubnet(c *gc.C) {\n\tcidr := \"1.1.1.0\/24\"\n\tproviderId := \"foo\"\n\tspace := \"bar\"\n\tzones := []string{\"foo\", \"bar\"}\n\targs := makeAddSubnetsArgs(cidr, providerId, space, zones)\n\ts.init(c, &args, nil)\n\tresults, err := s.api.AddSubnet(cidr, providerId, space, zones)\n\tc.Assert(s.called, gc.Equals, 1)\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(results, gc.DeepEquals, args.Results)\n}\n\nfunc (s *SubnetsSuite) TestAddSubnetFails(c *gc.C) {\n\tcidr := \"1.1.1.0\/24\"\n\tproviderId := \"foo\"\n\tspace := \"bar\"\n\tzones := []string{\"foo\", \"bar\"}\n\targs := makeAddSubnetsArgs(cidr, providerId, space, zones)\n\ts.init(c, &args, errors.New(\"bang\"))\n\tresults, err := s.api.AddSubnet(cidr, providerId, space, zones)\n\tc.Check(s.called, gc.Equals, 1)\n\tc.Assert(err, gc.ErrorMatches, \"bang\")\n\tc.Assert(results, gc.DeepEquals, args.Results)\n}\n\nfunc (s *SubnetsSuite) TestCreateSubnet(c *gc.C) {\n\tcidr := \"1.1.1.0\/24\"\n\tspace := \"bar\"\n\tzones := []string{\"foo\", \"bar\"}\n\tisPublic := true\n\targs := makeCreateSubnetsArgs(cidr, space, zones, isPublic)\n\ts.init(c, &args, nil)\n\tresults, err := s.api.CreateSubnet(cidr, space, zones, isPublic)\n\tc.Assert(s.called, gc.Equals, 1)\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(results, gc.DeepEquals, args.Results)\n}\n\nfunc (s *SubnetsSuite) TestCreateSubnetFails(c *gc.C) {\n\tcidr := \"1.1.1.0\/24\"\n\tisPublic := true\n\tspace := \"bar\"\n\tzones := []string{\"foo\", \"bar\"}\n\targs := makeCreateSubnetsArgs(cidr, space, zones, isPublic)\n\ts.init(c, &args, errors.New(\"bang\"))\n\tresults, err := s.api.CreateSubnet(cidr, space, zones, isPublic)\n\tc.Check(s.called, gc.Equals, 1)\n\tc.Assert(err, gc.ErrorMatches, \"bang\")\n\tc.Assert(results, gc.DeepEquals, args.Results)\n}\n\nfunc (s *SubnetsSuite) TestListSubnets(c *gc.C) {\n\tspace := names.SpaceTag(\"foo\")\n\tzone := \"bar\"\n\targs := makeListSubnetsArgs(space, zone)\n\ts.init(c, &args, nil)\n\tresults, err := s.api.ListSubnets(space, zone)\n\tc.Assert(s.called, gc.Equals, 1)\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(results, gc.DeepEquals, expectResults)\n}\n\nfunc (s *SubnetsSuite) TestListSubnetsFails(c *gc.C) {\n\tspace := names.SpaceTag(\"foo\")\n\tzone := \"bar\"\n\targs := makeListSubnetsArgs(space, zone)\n\ts.init(c, &args, errors.New(\"bang\"))\n\tresults, err := s.api.ListSubnets(space, zone)\n\tc.Assert(s.called, gc.Equals, 1)\n\tc.Assert(err, gc.ErrorMatches, \"bang\")\n\tc.Assert(results, gc.DeepEquals, args.Results)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ 7 february 2014\n\npackage ui\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nvar (\n\t_messageBox = user32.NewProc(\"MessageBoxW\")\n)\n\nfunc _msgBox(parent *Window, primarytext string, secondarytext string, uType uint32) (result chan int) {\n\t\/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/aa511267.aspx says \"Use task dialogs whenever appropriate to achieve a consistent look and layout. Task dialogs require Windows Vista® or later, so they aren't suitable for earlier versions of Windows. If you must use a message box, separate the main instruction from the supplemental instruction with two line breaks.\"\n\ttext := primarytext\n\tif secondarytext != \"\" {\n\t\ttext += \"\\n\\n\" + secondarytext\n\t}\n\tptext := toUTF16(text)\n\tptitle := toUTF16(os.Args[0])\n\tparenthwnd := _HWND(_NULL)\n\tif parent != dialogWindow {\n\t\tparenthwnd = parent.sysData.hwnd\n\t\tuType |= _MB_APPLMODAL \/\/ only for this window\n\t} else {\n\t\tuType |= _MB_TASKMODAL \/\/ make modal to every window in the program (they're all windows of the uitask, which is a single thread)\n\t}\n\tretchan := make(chan int)\n\tgo func() {\n\t\tret := make(chan uiret)\n\t\tdefer close(ret)\n\t\tuitask <- &uimsg{\n\t\t\tcall: _messageBox,\n\t\t\tp: []uintptr{\n\t\t\t\tuintptr(parenthwnd),\n\t\t\t\tutf16ToArg(ptext),\n\t\t\t\tutf16ToArg(ptitle),\n\t\t\t\tuintptr(uType),\n\t\t\t},\n\t\t\tret: ret,\n\t\t}\n\t\tr := <-ret\n\t\tif r.ret == 0 { \/\/ failure\n\t\t\tpanic(fmt.Sprintf(\"error displaying message box to user: %v\\nstyle: 0x%08X\\ntitle: %q\\ntext:\\n%s\", r.err, uType, os.Args[0], text))\n\t\t}\n\t\tretchan <- int(r.ret)\n\t}()\n\treturn retchan\n}\n\nfunc (w *Window) msgBox(primarytext string, secondarytext string) (done chan struct{}) {\n\tdone = make(chan struct{})\n\tgo func() {\n\t\t<-_msgBox(w, primarytext, secondarytext, _MB_OK)\n\t\tdone <- struct{}{}\n\t}()\n\treturn done\n}\n\nfunc (w *Window) msgBoxError(primarytext string, secondarytext string) (done chan struct{}) {\n\tdone = make(chan struct{})\n\tgo func() {\n\t\t<-_msgBox(w, primarytext, secondarytext, _MB_OK|_MB_ICONERROR)\n\t\tdone <- struct{}{}\n\t}()\n\treturn done\n}\n<commit_msg>Disabled MsgBox() on Windows for the time being; I'm going to restructure uitask to avoid needing to deal with channels and it's the only thing using uimsg now.<commit_after>\/\/ 7 february 2014\n\npackage ui\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nvar (\n\t_messageBox = user32.NewProc(\"MessageBoxW\")\n)\n\nfunc _msgBox(parent *Window, primarytext string, secondarytext string, uType uint32) (result chan int) {\n\t\/\/ http:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/aa511267.aspx says \"Use task dialogs whenever appropriate to achieve a consistent look and layout. Task dialogs require Windows Vista® or later, so they aren't suitable for earlier versions of Windows. If you must use a message box, separate the main instruction from the supplemental instruction with two line breaks.\"\n\ttext := primarytext\n\tif secondarytext != \"\" {\n\t\ttext += \"\\n\\n\" + secondarytext\n\t}\n\tptext := toUTF16(text)\n\tptitle := toUTF16(os.Args[0])\n\tparenthwnd := _HWND(_NULL)\n\tif parent != dialogWindow {\n\t\tparenthwnd = parent.sysData.hwnd\n\t\tuType |= _MB_APPLMODAL \/\/ only for this window\n\t} else {\n\t\tuType |= _MB_TASKMODAL \/\/ make modal to every window in the program (they're all windows of the uitask, which is a single thread)\n\t}\n\tretchan := make(chan int)\n\tgo func() {\n\t\tret := make(chan uiret)\n\t\tdefer close(ret)\n\/* TODO\n\t\tuitask <- &uimsg{\n\t\t\tcall: _messageBox,\n\t\t\tp: []uintptr{\n\t\t\t\tuintptr(parenthwnd),\n\t\t\t\tutf16ToArg(ptext),\n\t\t\t\tutf16ToArg(ptitle),\n\t\t\t\tuintptr(uType),\n\t\t\t},\n\t\t\tret: ret,\n\t\t}\n*\/\n\t\tr := <-ret\n\t\tif r.ret == 0 { \/\/ failure\n\t\t\tpanic(fmt.Sprintf(\"error displaying message box to user: %v\\nstyle: 0x%08X\\ntitle: %q\\ntext:\\n%s\", r.err, uType, os.Args[0], text))\n\t\t}\n\t\tretchan <- int(r.ret)\n\t}()\n\treturn retchan\n}\n\nfunc (w *Window) msgBox(primarytext string, secondarytext string) (done chan struct{}) {\n\tdone = make(chan struct{})\n\tgo func() {\n\t\t<-_msgBox(w, primarytext, secondarytext, _MB_OK)\n\t\tdone <- struct{}{}\n\t}()\n\treturn done\n}\n\nfunc (w *Window) msgBoxError(primarytext string, secondarytext string) (done chan struct{}) {\n\tdone = make(chan struct{})\n\tgo func() {\n\t\t<-_msgBox(w, primarytext, secondarytext, _MB_OK|_MB_ICONERROR)\n\t\tdone <- struct{}{}\n\t}()\n\treturn done\n}\n<|endoftext|>"}
{"text":"<commit_before>package system\n\nimport (\n\t\"log\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Integration: \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype Shell struct {\n\tcoverage       bool\n\tgobin          string\n\treportsPath    string\n\tdefaultTimeout string\n}\n\nfunc NewShell(gobin, reportsPath string, coverage bool, defaultTimeout string) *Shell {\n\treturn &Shell{\n\t\tcoverage:       coverage,\n\t\tgobin:          gobin,\n\t\treportsPath:    reportsPath,\n\t\tdefaultTimeout: defaultTimeout,\n\t}\n}\n\nfunc (self *Shell) GoTest(directory, packageName string, arguments []string) (output string, err error) {\n\treportFilename := strings.Replace(packageName, \"\/\", \"-\", -1)\n\treportPath := filepath.Join(self.reportsPath, reportFilename)\n\treportData := reportPath + \".txt\"\n\treportHTML := reportPath + \".html\"\n\n\tgoconvey := findGoConvey(directory, self.gobin, packageName).Execute()\n\tcompilation := compile(directory, self.gobin).Execute()\n\twithCoverage := runWithCoverage(compilation, goconvey, self.coverage, reportData, directory, self.gobin, self.defaultTimeout, arguments).Execute()\n\tfinal := runWithoutCoverage(compilation, withCoverage, goconvey, directory, self.gobin, self.defaultTimeout, arguments).Execute()\n\tgo generateReports(final, self.coverage, directory, self.gobin, reportData, reportHTML).Execute()\n\n\treturn final.Output, final.Error\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Functional Core:\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc findGoConvey(directory, gobin, packageName string) Command {\n\treturn NewCommand(directory, gobin, \"list\", \"-f\", \"'{{.TestImports}}'\", packageName)\n}\n\nfunc compile(directory, gobin string) Command {\n\treturn NewCommand(directory, gobin, \"test\", \"-i\")\n}\n\nfunc runWithCoverage(compile, goconvey Command, coverage bool, reportPath, directory, gobin, defaultTimeout string, customArguments []string) Command {\n\tif compile.Error != nil {\n\t\treturn compile\n\t}\n\n\tif !coverage {\n\t\treturn compile\n\t}\n\n\targuments := []string{\"test\", \"-v\", \"-coverprofile=\" + reportPath}\n\n\tcustomArgsText := strings.Join(customArguments, \"\\t\")\n\tif !strings.Contains(customArgsText, \"-covermode=\") {\n\t\targuments = append(arguments, \"-covermode=set\")\n\t}\n\n\tif !strings.Contains(customArgsText, \"-timeout=\") {\n\t\targuments = append(arguments, \"-timeout=\"+defaultTimeout)\n\t}\n\n\tif strings.Contains(goconvey.Output, goconveyDSLImport) {\n\t\targuments = append(arguments, \"-json\")\n\t}\n\n\targuments = append(arguments, customArguments...)\n\n\treturn NewCommand(directory, gobin, arguments...)\n}\n\nfunc runWithoutCoverage(compile, withCoverage, goconvey Command, directory, gobin, defaultTimeout string, customArguments []string) Command {\n\tif compile.Error != nil {\n\t\treturn compile\n\t}\n\n\tif coverageStatementRE.MatchString(withCoverage.Output) {\n\t\treturn withCoverage\n\t}\n\n\tlog.Printf(\"Coverage output: %v\", withCoverage.Output)\n\n\tlog.Print(\"Run without coverage\")\n\n\targuments := []string{\"test\", \"-v\"}\n\tcustomArgsText := strings.Join(customArguments, \"\\t\")\n\tif !strings.Contains(customArgsText, \"-timeout=\") {\n\t\targuments = append(arguments, \"-timeout=\"+defaultTimeout)\n\t}\n\n\tif strings.Contains(goconvey.Output, goconveyDSLImport) {\n\t\targuments = append(arguments, \"-json\")\n\t}\n\targuments = append(arguments, customArguments...)\n\treturn NewCommand(directory, gobin, arguments...)\n}\n\nfunc generateReports(previous Command, coverage bool, directory, gobin, reportData, reportHTML string) Command {\n\tif previous.Error != nil {\n\t\treturn previous\n\t}\n\n\tif !coverage {\n\t\treturn previous\n\t}\n\n\treturn NewCommand(directory, gobin, \"tool\", \"cover\", \"-html=\"+reportData, \"-o\", reportHTML)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Imperative Shell: \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype Command struct {\n\tdirectory  string\n\texecutable string\n\targuments  []string\n\n\tOutput string\n\tError  error\n}\n\nfunc NewCommand(directory, executable string, arguments ...string) Command {\n\treturn Command{\n\t\tdirectory:  directory,\n\t\texecutable: executable,\n\t\targuments:  arguments,\n\t}\n}\n\nfunc (this Command) Execute() Command {\n\tif len(this.executable) == 0 {\n\t\treturn this\n\t}\n\n\tif len(this.Output) > 0 || this.Error != nil {\n\t\treturn this\n\t}\n\n\tcommand := exec.Command(this.executable, this.arguments...)\n\tcommand.Dir = this.directory\n\tvar rawOutput []byte\n\trawOutput, this.Error = command.CombinedOutput()\n\tthis.Output = string(rawOutput)\n\treturn this\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst goconveyDSLImport = \"github.com\/smartystreets\/goconvey\/convey \" \/\/ note the trailing space: we don't want to target packages nested in the \/convey package.\nvar coverageStatementRE = regexp.MustCompile(`(?m)^coverage: \\d+\\.\\d% of statements(.*)$|^panic: test timed out after `)\n<commit_msg>Added error checks along with hints about source of error<commit_after>package system\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Integration: \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype Shell struct {\n\tcoverage       bool\n\tgobin          string\n\treportsPath    string\n\tdefaultTimeout string\n}\n\nfunc NewShell(gobin, reportsPath string, coverage bool, defaultTimeout string) *Shell {\n\treturn &Shell{\n\t\tcoverage:       coverage,\n\t\tgobin:          gobin,\n\t\treportsPath:    reportsPath,\n\t\tdefaultTimeout: defaultTimeout,\n\t}\n}\n\nfunc (self *Shell) GoTest(directory, packageName string, arguments []string) (output string, err error) {\n\treportFilename := strings.Replace(packageName, \"\/\", \"-\", -1)\n\treportPath := filepath.Join(self.reportsPath, reportFilename)\n\treportData := reportPath + \".txt\"\n\treportHTML := reportPath + \".html\"\n\n\tgoconvey := findGoConvey(directory, self.gobin, packageName).Execute()\n\tif goconvey.Error != nil {\n\t\treturn fmt.Sprintf(\"Is your source in $GOPATH or using symbolic links?\\n%s\",\n\t\t\tgoconvey.Output), goconvey.Error\n\t}\n\tcompilation := compile(directory, self.gobin).Execute()\n\twithCoverage := runWithCoverage(compilation, goconvey, self.coverage, reportData, directory, self.gobin, self.defaultTimeout, arguments).Execute()\n\tif withCoverage.Error != nil {\n\t\treturn withCoverage.Output, withCoverage.Error\n\t}\n\tfinal := runWithoutCoverage(compilation, withCoverage, goconvey, directory, self.gobin, self.defaultTimeout, arguments).Execute()\n\tgo generateReports(final, self.coverage, directory, self.gobin, reportData, reportHTML).Execute()\n\n\treturn final.Output, final.Error\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Functional Core:\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc findGoConvey(directory, gobin, packageName string) Command {\n\treturn NewCommand(directory, gobin, \"list\", \"-f\", \"'{{.TestImports}}'\", packageName)\n}\n\nfunc compile(directory, gobin string) Command {\n\treturn NewCommand(directory, gobin, \"test\", \"-i\")\n}\n\nfunc runWithCoverage(compile, goconvey Command, coverage bool, reportPath, directory, gobin, defaultTimeout string, customArguments []string) Command {\n\tif compile.Error != nil {\n\t\treturn compile\n\t}\n\n\tif !coverage {\n\t\treturn compile\n\t}\n\n\targuments := []string{\"test\", \"-v\", \"-coverprofile=\" + reportPath}\n\n\tcustomArgsText := strings.Join(customArguments, \"\\t\")\n\tif !strings.Contains(customArgsText, \"-covermode=\") {\n\t\targuments = append(arguments, \"-covermode=set\")\n\t}\n\n\tif !strings.Contains(customArgsText, \"-timeout=\") {\n\t\targuments = append(arguments, \"-timeout=\"+defaultTimeout)\n\t}\n\n\tif strings.Contains(goconvey.Output, goconveyDSLImport) {\n\t\targuments = append(arguments, \"-json\")\n\t}\n\n\targuments = append(arguments, customArguments...)\n\n\treturn NewCommand(directory, gobin, arguments...)\n}\n\nfunc runWithoutCoverage(compile, withCoverage, goconvey Command, directory, gobin, defaultTimeout string, customArguments []string) Command {\n\tif compile.Error != nil {\n\t\treturn compile\n\t}\n\n\tif coverageStatementRE.MatchString(withCoverage.Output) {\n\t\treturn withCoverage\n\t}\n\n\tlog.Printf(\"Coverage output: %v\", withCoverage.Output)\n\n\tlog.Print(\"Run without coverage\")\n\n\targuments := []string{\"test\", \"-v\"}\n\tcustomArgsText := strings.Join(customArguments, \"\\t\")\n\tif !strings.Contains(customArgsText, \"-timeout=\") {\n\t\targuments = append(arguments, \"-timeout=\"+defaultTimeout)\n\t}\n\n\tif strings.Contains(goconvey.Output, goconveyDSLImport) {\n\t\targuments = append(arguments, \"-json\")\n\t}\n\targuments = append(arguments, customArguments...)\n\treturn NewCommand(directory, gobin, arguments...)\n}\n\nfunc generateReports(previous Command, coverage bool, directory, gobin, reportData, reportHTML string) Command {\n\tif previous.Error != nil {\n\t\treturn previous\n\t}\n\n\tif !coverage {\n\t\treturn previous\n\t}\n\n\treturn NewCommand(directory, gobin, \"tool\", \"cover\", \"-html=\"+reportData, \"-o\", reportHTML)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Imperative Shell: \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype Command struct {\n\tdirectory  string\n\texecutable string\n\targuments  []string\n\n\tOutput string\n\tError  error\n}\n\nfunc NewCommand(directory, executable string, arguments ...string) Command {\n\treturn Command{\n\t\tdirectory:  directory,\n\t\texecutable: executable,\n\t\targuments:  arguments,\n\t}\n}\n\nfunc (this Command) Execute() Command {\n\tif len(this.executable) == 0 {\n\t\treturn this\n\t}\n\n\tif len(this.Output) > 0 || this.Error != nil {\n\t\treturn this\n\t}\n\n\tcommand := exec.Command(this.executable, this.arguments...)\n\tcommand.Dir = this.directory\n\tvar rawOutput []byte\n\trawOutput, this.Error = command.CombinedOutput()\n\tthis.Output = string(rawOutput)\n\treturn this\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst goconveyDSLImport = \"github.com\/smartystreets\/goconvey\/convey \" \/\/ note the trailing space: we don't want to target packages nested in the \/convey package.\nvar coverageStatementRE = regexp.MustCompile(`(?m)^coverage: \\d+\\.\\d% of statements(.*)$|^panic: test timed out after `)\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>helper: Escape test name in TF_LOG_PATH_MASK<commit_after><|endoftext|>"}
{"text":"<commit_before>package openstack\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/rackspace\/gophercloud\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/compute\/v2\/extensions\/secgroups\"\n)\n\nfunc resourceComputeSecGroupV2() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceComputeSecGroupV2Create,\n\t\tRead:   resourceComputeSecGroupV2Read,\n\t\tUpdate: resourceComputeSecGroupV2Update,\n\t\tDelete: resourceComputeSecGroupV2Delete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"region\": &schema.Schema{\n\t\t\t\tType:        schema.TypeString,\n\t\t\t\tRequired:    true,\n\t\t\t\tForceNew:    true,\n\t\t\t\tDefaultFunc: envDefaultFunc(\"OS_REGION_NAME\"),\n\t\t\t},\n\t\t\t\"name\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: false,\n\t\t\t},\n\t\t\t\"description\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: false,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceComputeSecGroupV2Create(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\tcomputeClient, err := openstack.NewComputeV2(config.osClient, gophercloud.EndpointOpts{\n\t\tRegion: d.Get(\"region\").(string),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack compute client: %s\", err)\n\t}\n\n\tcreateOpts := secgroups.CreateOpts{\n\t\tName:        d.Get(\"name\").(string),\n\t\tDescription: d.Get(\"description\").(string),\n\t}\n\n\tsg, err := secgroups.Create(computeClient, createOpts).Extract()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack security group: %s\", err)\n\t}\n\n\td.SetId(sg.ID)\n\n\treturn resourceComputeSecGroupV2Read(d, meta)\n}\n\nfunc resourceComputeSecGroupV2Read(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\tcomputeClient, err := openstack.NewComputeV2(config.osClient, gophercloud.EndpointOpts{\n\t\tRegion: d.Get(\"region\").(string),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack compute client: %s\", err)\n\t}\n\n\tsg, err := secgroups.Get(computeClient, d.Id()).Extract()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error retrieving OpenStack security group: %s\", err)\n\t}\n\n\td.Set(\"region\", d.Get(\"region\").(string))\n\td.Set(\"name\", sg.Name)\n\td.Set(\"description\", sg.Description)\n\n\treturn nil\n}\n\nfunc resourceComputeSecGroupV2Update(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\tcomputeClient, err := openstack.NewComputeV2(config.osClient, gophercloud.EndpointOpts{\n\t\tRegion: d.Get(\"region\").(string),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack compute client: %s\", err)\n\t}\n\n\tupdateOpts := secgroups.UpdateOpts{\n\t\tName:        d.Get(\"name\").(string),\n\t\tDescription: d.Get(\"description\").(string),\n\t}\n\n\tlog.Printf(\"[DEBUG] Updating Security Group (%s) with options: %+v\", d.Id(), updateOpts)\n\n\t_, err = secgroups.Update(computeClient, d.Id(), updateOpts).Extract()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error updating OpenStack security group (%s): %s\", d.Id(), err)\n\t}\n\n\treturn resourceComputeSecGroupV2Read(d, meta)\n}\n\nfunc resourceComputeSecGroupV2Delete(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\tcomputeClient, err := openstack.NewComputeV2(config.osClient, gophercloud.EndpointOpts{\n\t\tRegion: d.Get(\"region\").(string),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack compute client: %s\", err)\n\t}\n\n\terr = secgroups.Delete(computeClient, d.Id()).ExtractErr()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting OpenStack security group: %s\", err)\n\t}\n\td.SetId(\"\")\n\treturn nil\n}\n<commit_msg>add security group rules ops to security groups file<commit_after>package openstack\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/hashcode\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/rackspace\/gophercloud\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/compute\/v2\/extensions\/secgroups\"\n)\n\nfunc resourceComputeSecGroupV2() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceComputeSecGroupV2Create,\n\t\tRead:   resourceComputeSecGroupV2Read,\n\t\tUpdate: resourceComputeSecGroupV2Update,\n\t\tDelete: resourceComputeSecGroupV2Delete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"region\": &schema.Schema{\n\t\t\t\tType:        schema.TypeString,\n\t\t\t\tRequired:    true,\n\t\t\t\tForceNew:    true,\n\t\t\t\tDefaultFunc: envDefaultFunc(\"OS_REGION_NAME\"),\n\t\t\t},\n\t\t\t\"name\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: false,\n\t\t\t},\n\t\t\t\"description\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: false,\n\t\t\t},\n\t\t\t\"rules\": &schema.Schema{\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"from_port\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeInt,\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\tForceNew: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"to_port\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeInt,\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\tForceNew: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"ip_protocol\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\tForceNew: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"cidr\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tForceNew: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"from_group_id\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tForceNew: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSet: resourceSecGroupRuleHash,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceComputeSecGroupV2Create(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\tcomputeClient, err := openstack.NewComputeV2(config.osClient, gophercloud.EndpointOpts{\n\t\tRegion: d.Get(\"region\").(string),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack compute client: %s\", err)\n\t}\n\n\tcreateOpts := secgroups.CreateOpts{\n\t\tName:        d.Get(\"name\").(string),\n\t\tDescription: d.Get(\"description\").(string),\n\t}\n\n\tsg, err := secgroups.Create(computeClient, createOpts).Extract()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack security group: %s\", err)\n\t}\n\n\td.SetId(sg.ID)\n\n\tcreateRuleOptsList := resourceSecGroupRulesV2(d)\n\tfor _, createRuleOpts := range createRuleOptsList {\n\t\t_, err := secgroups.CreateRule(computeClient, createRuleOpts).Extract()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error creating OpenStack security group rule: %s\", err)\n\t\t}\n\t}\n\n\treturn resourceComputeSecGroupV2Read(d, meta)\n}\n\nfunc resourceComputeSecGroupV2Read(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\tcomputeClient, err := openstack.NewComputeV2(config.osClient, gophercloud.EndpointOpts{\n\t\tRegion: d.Get(\"region\").(string),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack compute client: %s\", err)\n\t}\n\n\tsg, err := secgroups.Get(computeClient, d.Id()).Extract()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error retrieving OpenStack security group: %s\", err)\n\t}\n\n\td.Set(\"region\", d.Get(\"region\").(string))\n\td.Set(\"name\", sg.Name)\n\td.Set(\"description\", sg.Description)\n\td.Set(\"rules\", sg.Rules)\n\n\treturn nil\n}\n\nfunc resourceComputeSecGroupV2Update(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\tcomputeClient, err := openstack.NewComputeV2(config.osClient, gophercloud.EndpointOpts{\n\t\tRegion: d.Get(\"region\").(string),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack compute client: %s\", err)\n\t}\n\n\tupdateOpts := secgroups.UpdateOpts{\n\t\tName:        d.Get(\"name\").(string),\n\t\tDescription: d.Get(\"description\").(string),\n\t}\n\n\tlog.Printf(\"[DEBUG] Updating Security Group (%s) with options: %+v\", d.Id(), updateOpts)\n\n\t_, err = secgroups.Update(computeClient, d.Id(), updateOpts).Extract()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error updating OpenStack security group (%s): %s\", d.Id(), err)\n\t}\n\n\tif d.HasChange(\"rules\") {\n\t\toldSGRaw, newSGRaw := d.GetChange(\"rules\")\n\t\toldSGRSet, newSGRSet := oldSGRaw.(*schema.Set), newSGRaw.(*schema.Set)\n\t\tsecgrouprulesToAdd := newSGRSet.Difference(oldSGRSet)\n\t\tsecgrouprulesToRemove := oldSGRSet.Difference(newSGRSet)\n\n\t\tlog.Printf(\"[DEBUG] Security group rules to add: %v\", secgrouprulesToAdd)\n\n\t\tlog.Printf(\"[DEBUG] Security groups to remove: %v\", secgrouprulesToRemove)\n\n\t\tfor _, rawRule := range secgrouprulesToAdd.List() {\n\t\t\tcreateRuleOpts := resourceSecGroupRuleV2(d, rawRule)\n\t\t\trule, err := secgroups.CreateRule(computeClient, createRuleOpts).Extract()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error adding rule to OpenStack security group (%s): %s\", d.Id(), err)\n\t\t\t}\n\t\t\tlog.Printf(\"[DEBUG] Added rule (%s) to OpenStack security group (%s) \", rule.ID, d.Id())\n\t\t}\n\n\t\tfor _, r := range secgrouprulesToRemove.List() {\n\t\t\trule := r.(secgroups.Rule)\n\t\t\terr := secgroups.DeleteRule(computeClient, \"\").ExtractErr()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error removing rule (%s) from OpenStack security group (%s): %s\", rule.ID, d.Id(), err)\n\t\t\t}\n\t\t\tlog.Printf(\"[DEBUG] Removed rule (%s) from OpenStack security group (%s)\", rule.ID, d.Id())\n\t\t}\n\t}\n\n\treturn resourceComputeSecGroupV2Read(d, meta)\n}\n\nfunc resourceComputeSecGroupV2Delete(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\tcomputeClient, err := openstack.NewComputeV2(config.osClient, gophercloud.EndpointOpts{\n\t\tRegion: d.Get(\"region\").(string),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating OpenStack compute client: %s\", err)\n\t}\n\n\terr = secgroups.Delete(computeClient, d.Id()).ExtractErr()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting OpenStack security group: %s\", err)\n\t}\n\td.SetId(\"\")\n\treturn nil\n}\n\nfunc resourceSecGroupRuleHash(v interface{}) int {\n\tvar buf bytes.Buffer\n\tm := v.(map[string]interface{})\n\tbuf.WriteString(fmt.Sprintf(\"%d-\", m[\"from_port\"].(int)))\n\tbuf.WriteString(fmt.Sprintf(\"%d-\", m[\"to_port\"].(int)))\n\tbuf.WriteString(fmt.Sprintf(\"%s-\", m[\"ip_protocol\"].(string)))\n\tbuf.WriteString(fmt.Sprintf(\"%s-\", m[\"cidr\"].(string)))\n\tbuf.WriteString(fmt.Sprintf(\"%s-\", m[\"from_group_id\"].(string)))\n\n\treturn hashcode.String(buf.String())\n}\n\nfunc resourceSecGroupRulesV2(d *schema.ResourceData) []secgroups.CreateRuleOpts {\n\trawRules := (d.Get(\"rules\")).(*schema.Set)\n\tcreateRuleOptsList := make([]secgroups.CreateRuleOpts, rawRules.Len())\n\tfor i, raw := range rawRules.List() {\n\t\trawMap := raw.(map[string]interface{})\n\t\tcreateRuleOptsList[i] = secgroups.CreateRuleOpts{\n\t\t\tParentGroupID: d.Id(),\n\t\t\tFromPort:      rawMap[\"from_port\"].(int),\n\t\t\tToPort:        rawMap[\"to_port\"].(int),\n\t\t\tIPProtocol:    rawMap[\"ip_protocol\"].(string),\n\t\t\tCIDR:          rawMap[\"cidr\"].(string),\n\t\t\tFromGroupID:   rawMap[\"from_group_id\"].(string),\n\t\t}\n\t}\n\treturn createRuleOptsList\n}\n\nfunc resourceSecGroupRuleV2(d *schema.ResourceData, raw interface{}) secgroups.CreateRuleOpts {\n\trawMap := raw.(map[string]interface{})\n\tcreateRuleOpts := secgroups.CreateRuleOpts{\n\t\tParentGroupID: d.Id(),\n\t\tFromPort:      rawMap[\"from_port\"].(int),\n\t\tToPort:        rawMap[\"to_port\"].(int),\n\t\tIPProtocol:    rawMap[\"ip_protocol\"].(string),\n\t\tCIDR:          rawMap[\"cidr\"].(string),\n\t\tFromGroupID:   rawMap[\"from_group_id\"].(string),\n\t}\n\n\treturn createRuleOpts\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport(\n  \"fmt\"\n  \"io\"\n  \"io\/ioutil\"\n  \"crypto\/sha1\"\n  \"os\"\n  \"os\/exec\"\n  \"path\/filepath\"\n  \"bytes\"\n  \"runtime\"\n  \"strings\"\n  \"github.com\/kr\/s3\/s3util\"\n  \"github.com\/jessevdk\/go-flags\"\n)\n\nconst VERSION = \"0.2.0\"\n\nconst(\n  ERR_WRONG_USAGE    = 2\n  ERR_NO_CREDENTIALS = 3\n  ERR_NO_BUNDLE      = 4\n  ERR_BUNDLE_EXISTS  = 5\n  ERR_NO_GEMLOCK     = 6\n)\n\nvar options struct {\n  Prefix    string `long:\"prefix\"     description:\"Custom archive filename (default: current dir)\"`\n  Path      string `long:\"path\"       description:\"Path to directory with .bundle (default: current)\"`\n  AccessKey string `long:\"access-key\" description:\"S3 Access key\"`\n  SecretKey string `long:\"secret-key\" description:\"S3 Secret key\"`\n  Bucket    string `long:\"bucket\"     description:\"S3 Bucket name\"`\n}\n\nfunc terminate(message string, exit_code int) {\n  fmt.Fprintln(os.Stderr, message)\n  os.Exit(exit_code)\n}\n\nfunc terminateWithError(err error, exit_code int) {\n  fmt.Fprintln(os.Stderr, err)\n  os.Exit(exit_code)\n}\n\nfunc fileExists(path string) bool {\n  _, err := os.Stat(path)\n  return err == nil\n}\n\nfunc open(s string) (io.ReadCloser, error) {\n  if isURL(s) {\n    return s3util.Open(s, nil)\n  }\n  return os.Open(s)\n}\n\nfunc create(s string) (io.WriteCloser, error) {\n  if isURL(s) {\n    return s3util.Create(s, nil, nil)\n  }\n  return os.Create(s)\n}\n\nfunc isURL(s string) bool {\n  return strings.HasPrefix(s, \"http:\/\/\") || strings.HasPrefix(s, \"https:\/\/\")\n}\n\nfunc s3url(filename string) string {\n  format := \"https:\/\/s3.amazonaws.com\/%s\/%s\"\n  url := fmt.Sprintf(format, options.Bucket, filename)\n\n  return url\n}\n\nfunc sh(command string) (string, error) {\n  var output bytes.Buffer\n \n  cmd := exec.Command(\"bash\", \"-c\", command)\n \n  cmd.Stdout = &output\n  cmd.Stderr = &output\n \n  err := cmd.Run()\n  return output.String(), err\n}\n\nfunc calculateChecksum(buffer string) string {\n  h := sha1.New()\n  io.WriteString(h, buffer)\n  return fmt.Sprintf(\"%x\", h.Sum(nil))\n}\n\nfunc transferArchive(file string, url string) {\n  s3util.DefaultConfig.AccessKey = options.AccessKey\n  s3util.DefaultConfig.SecretKey = options.SecretKey\n\n  r, err := open(file)\n  if err != nil {\n    terminateWithError(err, 1)\n  }\n\n  w, err := create(url)\n  if err != nil {\n    terminateWithError(err, 1)\n  }\n\n  _, err = io.Copy(w, r)\n  if err != nil {\n    terminateWithError(err, 1)\n  }\n\n  err = w.Close()\n  if err != nil {\n    terminateWithError(err, 1)\n  }\n}\n\nfunc extractArchive(filename string, path string) bool {\n  cmd_mkdir   := fmt.Sprintf(\"cd %s && mkdir .bundle\", path)\n  cmd_move    := fmt.Sprintf(\"mv %s %s\/.bundle\/bundle_cache.tar.gz\", filename, path)\n  cmd_extract := fmt.Sprintf(\"cd %s\/.bundle && tar -xzf .\/bundle_cache.tar.gz\", path)\n  cmd_remove  := fmt.Sprintf(\"rm %s\/.bundle\/bundle_cache.tar.gz\", path)\n\n  if _, err := sh(cmd_mkdir) ; err != nil {\n    fmt.Println(\"Bundle directory '.bundle' already exists\")\n    return false\n  }\n\n  if _, err := sh(cmd_move) ; err != nil {\n    fmt.Println(\"Unable to move file\")\n    return false\n  }\n\n  if out, err := sh(cmd_extract) ; err != nil {\n    fmt.Println(\"Unable to extract:\", out)\n    return false\n  }\n\n  if _, err := sh(cmd_remove) ; err != nil {\n    fmt.Println(\"Unable to remove archive\")\n    return false\n  }\n\n  return true\n}\n\nfunc envDefined(name string) bool {\n  result := os.Getenv(name)\n  return len(result) > 0\n}\n\nfunc checkS3Credentials() {\n  if len(options.AccessKey) == 0 { \n    terminate(\"Please provide S3 access key\", ERR_NO_CREDENTIALS) \n  }\n  \n  if len(options.SecretKey) == 0 { \n    terminate(\"Please provide S3 secret key\", ERR_NO_CREDENTIALS) \n  }\n  \n  if len(options.Bucket) == 0 { \n    terminate(\"Please provide S3 bucket name\", ERR_NO_CREDENTIALS) \n  }\n}\n\nfunc printUsage() {\n  terminate(\"Usage: bundle_cache [download|upload]\", ERR_WRONG_USAGE)\n}\n\nfunc upload(bundle_path string, archive_path string, archive_url string) {\n  if envDefined(\"BUNDLE_CACHE_DOWNLOAD\") {\n    if os.Getenv(\"BUNDLE_CACHE_DOWNLOAD\") == \"ok\" {\n      fmt.Println(\"Bundle cache downloaded. Skipping upload\")\n      return\n    }\n  }\n\n  if !fileExists(bundle_path) {\n    terminate(\"Bundle path does not exist\", ERR_NO_BUNDLE)\n  }\n\n  fmt.Println(\"Archiving...\")\n  cmd := fmt.Sprintf(\"cd %s && tar -czf %s .\", bundle_path, archive_path)\n  if _, err := sh(cmd); err != nil {\n    terminate(\"Failed to make archive.\", 1)\n  }\n\n  fmt.Println(\"Transferring...\")\n  transferArchive(archive_path, archive_url)\n\n  os.Exit(0)\n}\n\nfunc download(path string, bundle_path string, archive_path string, archive_url string) {\n  if fileExists(bundle_path) {\n    terminate(\"Bundle path already exists\", ERR_BUNDLE_EXISTS)\n  }\n\n  fmt.Println(\"Downloading...\", archive_url)\n  transferArchive(archive_url, archive_path)\n\n  fmt.Println(\"Extracting...\")\n  extractArchive(archive_path, path)\n\n  \/* Set download result veriable *\/\n  err := os.Setenv(\"BUNDLE_CACHE_DOWNLOAD\", \"ok\")\n  if err != nil {\n    fmt.Println(\"Failed to set BUNDLE_CACHE_DOWNLOAD variable\")\n  }\n\n  os.Exit(0)\n}\n\nfunc main() {\n  new_args, err := flags.ParseArgs(&options, os.Args)\n\n  if err != nil {\n    fmt.Println(err)\n    os.Exit(ERR_WRONG_USAGE)\n  }\n\n  if len(options.AccessKey) == 0 && envDefined(\"S3_ACCESS_KEY\") {\n    options.AccessKey = os.Getenv(\"S3_ACCESS_KEY\")\n  }\n\n  if len(options.SecretKey) == 0 && envDefined(\"S3_SECRET_KEY\") {\n    options.SecretKey = os.Getenv(\"S3_SECRET_KEY\")\n  }\n\n  if len(options.Bucket) == 0 && envDefined(\"S3_BUCKET\") {\n    options.Bucket = os.Getenv(\"S3_BUCKET\")\n  }\n\n  args := new_args[1:]\n\n  if len(args) != 1 {\n    printUsage()\n  }\n\n  action := args[0]\n\n  checkS3Credentials()\n\n  if len(options.Path) == 0 {\n    options.Path, _ = os.Getwd()\n  }\n\n  if len(options.Prefix) == 0 {\n    options.Prefix = filepath.Base(options.Path)\n  }\n\n  bundle_path   := fmt.Sprintf(\"%s\/.bundle\", options.Path)\n  lockfile_path := fmt.Sprintf(\"%s\/Gemfile.lock\", options.Path)\n\n  if !fileExists(lockfile_path) {\n    message := fmt.Sprintf(\"%s does not exist\", lockfile_path)\n    terminate(message, ERR_NO_GEMLOCK)\n  }\n\n  lockfile, err := ioutil.ReadFile(lockfile_path)\n  if err != nil {\n    terminate(\"Unable to read Gemfile.lock\", 1)\n  }\n\n  checksum     := calculateChecksum(string(lockfile))\n  archive_name := fmt.Sprintf(\"%s_%s_%s.tar.gz\", options.Prefix, checksum, runtime.GOARCH)\n  archive_path := fmt.Sprintf(\"\/tmp\/%s\", archive_name)\n  archive_url  := s3url(archive_name)\n\n  if fileExists(archive_path) {\n    if os.Remove(archive_path) != nil {\n      terminate(\"Failed to remove existing archive\", 1)\n    }\n  }\n\n  if action == \"upload\" || action == \"up\" {\n    upload(bundle_path, archive_path, archive_url)\n  }\n\n  if action == \"download\" || action == \"down\" {\n    download(options.Path, bundle_path, archive_path, archive_url)\n  }\n\n  fmt.Println(\"Invalid command:\", action)\n  printUsage()\n}\n<commit_msg>Setup cache checks via .bundle_cache file<commit_after>package main\n\nimport(\n  \"fmt\"\n  \"io\"\n  \"io\/ioutil\"\n  \"crypto\/sha1\"\n  \"os\"\n  \"os\/exec\"\n  \"path\/filepath\"\n  \"bytes\"\n  \"runtime\"\n  \"strings\"\n  \"github.com\/kr\/s3\/s3util\"\n  \"github.com\/jessevdk\/go-flags\"\n)\n\nconst VERSION = \"0.2.0\"\n\nconst(\n  ERR_WRONG_USAGE    = 2\n  ERR_NO_CREDENTIALS = 3\n  ERR_NO_BUNDLE      = 4\n  ERR_BUNDLE_EXISTS  = 5\n  ERR_NO_GEMLOCK     = 6\n)\n\nvar options struct {\n  Prefix    string `long:\"prefix\"     description:\"Custom archive filename (default: current dir)\"`\n  Path      string `long:\"path\"       description:\"Path to directory with .bundle (default: current)\"`\n  AccessKey string `long:\"access-key\" description:\"S3 Access key\"`\n  SecretKey string `long:\"secret-key\" description:\"S3 Secret key\"`\n  Bucket    string `long:\"bucket\"     description:\"S3 Bucket name\"`\n}\n\nfunc terminate(message string, exit_code int) {\n  fmt.Fprintln(os.Stderr, message)\n  os.Exit(exit_code)\n}\n\nfunc terminateWithError(err error, exit_code int) {\n  fmt.Fprintln(os.Stderr, err)\n  os.Exit(exit_code)\n}\n\nfunc fileExists(path string) bool {\n  _, err := os.Stat(path)\n  return err == nil\n}\n\nfunc open(s string) (io.ReadCloser, error) {\n  if isURL(s) {\n    return s3util.Open(s, nil)\n  }\n  return os.Open(s)\n}\n\nfunc create(s string) (io.WriteCloser, error) {\n  if isURL(s) {\n    return s3util.Create(s, nil, nil)\n  }\n  return os.Create(s)\n}\n\nfunc isURL(s string) bool {\n  return strings.HasPrefix(s, \"http:\/\/\") || strings.HasPrefix(s, \"https:\/\/\")\n}\n\nfunc s3url(filename string) string {\n  format := \"https:\/\/s3.amazonaws.com\/%s\/%s\"\n  url := fmt.Sprintf(format, options.Bucket, filename)\n\n  return url\n}\n\nfunc sh(command string) (string, error) {\n  var output bytes.Buffer\n \n  cmd := exec.Command(\"bash\", \"-c\", command)\n \n  cmd.Stdout = &output\n  cmd.Stderr = &output\n \n  err := cmd.Run()\n  return output.String(), err\n}\n\nfunc calculateChecksum(buffer string) string {\n  h := sha1.New()\n  io.WriteString(h, buffer)\n  return fmt.Sprintf(\"%x\", h.Sum(nil))\n}\n\nfunc transferArchive(file string, url string) {\n  s3util.DefaultConfig.AccessKey = options.AccessKey\n  s3util.DefaultConfig.SecretKey = options.SecretKey\n\n  r, err := open(file)\n  if err != nil {\n    terminateWithError(err, 1)\n  }\n\n  w, err := create(url)\n  if err != nil {\n    terminateWithError(err, 1)\n  }\n\n  _, err = io.Copy(w, r)\n  if err != nil {\n    terminateWithError(err, 1)\n  }\n\n  err = w.Close()\n  if err != nil {\n    terminateWithError(err, 1)\n  }\n}\n\nfunc extractArchive(filename string, path string) bool {\n  cmd_mkdir   := fmt.Sprintf(\"cd %s && mkdir .bundle\", path)\n  cmd_move    := fmt.Sprintf(\"mv %s %s\/.bundle\/bundle_cache.tar.gz\", filename, path)\n  cmd_extract := fmt.Sprintf(\"cd %s\/.bundle && tar -xzf .\/bundle_cache.tar.gz\", path)\n  cmd_remove  := fmt.Sprintf(\"rm %s\/.bundle\/bundle_cache.tar.gz\", path)\n\n  if _, err := sh(cmd_mkdir) ; err != nil {\n    fmt.Println(\"Bundle directory '.bundle' already exists\")\n    return false\n  }\n\n  if _, err := sh(cmd_move) ; err != nil {\n    fmt.Println(\"Unable to move file\")\n    return false\n  }\n\n  if out, err := sh(cmd_extract) ; err != nil {\n    fmt.Println(\"Unable to extract:\", out)\n    return false\n  }\n\n  if _, err := sh(cmd_remove) ; err != nil {\n    fmt.Println(\"Unable to remove archive\")\n    return false\n  }\n\n  return true\n}\n\nfunc envDefined(name string) bool {\n  result := os.Getenv(name)\n  return len(result) > 0\n}\n\nfunc checkS3Credentials() {\n  if len(options.AccessKey) == 0 { \n    terminate(\"Please provide S3 access key\", ERR_NO_CREDENTIALS) \n  }\n  \n  if len(options.SecretKey) == 0 { \n    terminate(\"Please provide S3 secret key\", ERR_NO_CREDENTIALS) \n  }\n  \n  if len(options.Bucket) == 0 { \n    terminate(\"Please provide S3 bucket name\", ERR_NO_CREDENTIALS) \n  }\n}\n\nfunc printUsage() {\n  terminate(\"Usage: bundle_cache [download|upload]\", ERR_WRONG_USAGE)\n}\n\nfunc upload(bundle_path string, archive_path string, archive_url string) {\n  cache_file := fmt.Sprintf(\"%s\/.bundle_cache\", options.Path)\n\n  if fileExists(cache_file) {\n    fmt.Println(\"Your bundle is cached. Skipping...\")\n    os.Exit(0)\n  }\n\n  if !fileExists(bundle_path) {\n    terminate(\"Bundle path does not exist\", ERR_NO_BUNDLE)\n  }\n\n  fmt.Println(\"Archiving...\")\n  cmd := fmt.Sprintf(\"cd %s && tar -czf %s .\", bundle_path, archive_path)\n  if _, err := sh(cmd); err != nil {\n    terminate(\"Failed to make archive.\", 1)\n  }\n\n  fmt.Println(\"Transferring...\")\n  transferArchive(archive_path, archive_url)\n\n  os.Exit(0)\n}\n\nfunc download(path string, bundle_path string, archive_path string, archive_url string) {\n  if fileExists(bundle_path) {\n    terminate(\"Bundle path already exists\", ERR_BUNDLE_EXISTS)\n  }\n\n  fmt.Println(\"Downloading...\", archive_url)\n  transferArchive(archive_url, archive_path)\n\n  fmt.Println(\"Extracting...\")\n  extractArchive(archive_path, path)\n\n  \/* Create a temp file in path to indicate that bundle was cached *\/\n  cache_file := fmt.Sprintf(\"%s\/.bundle_cache\", options.Path)\n  \n  if !fileExists(cache_file) {\n    sh(fmt.Sprintf(\"touch %s\", cache_file))\n  }\n\n  os.Exit(0)\n}\n\nfunc main() {\n  new_args, err := flags.ParseArgs(&options, os.Args)\n\n  if err != nil {\n    fmt.Println(err)\n    os.Exit(ERR_WRONG_USAGE)\n  }\n\n  if len(options.AccessKey) == 0 && envDefined(\"S3_ACCESS_KEY\") {\n    options.AccessKey = os.Getenv(\"S3_ACCESS_KEY\")\n  }\n\n  if len(options.SecretKey) == 0 && envDefined(\"S3_SECRET_KEY\") {\n    options.SecretKey = os.Getenv(\"S3_SECRET_KEY\")\n  }\n\n  if len(options.Bucket) == 0 && envDefined(\"S3_BUCKET\") {\n    options.Bucket = os.Getenv(\"S3_BUCKET\")\n  }\n\n  args := new_args[1:]\n\n  if len(args) != 1 {\n    printUsage()\n  }\n\n  action := args[0]\n\n  checkS3Credentials()\n\n  if len(options.Path) == 0 {\n    options.Path, _ = os.Getwd()\n  }\n\n  if len(options.Prefix) == 0 {\n    options.Prefix = filepath.Base(options.Path)\n  }\n\n  bundle_path   := fmt.Sprintf(\"%s\/.bundle\", options.Path)\n  lockfile_path := fmt.Sprintf(\"%s\/Gemfile.lock\", options.Path)\n\n  if !fileExists(lockfile_path) {\n    message := fmt.Sprintf(\"%s does not exist\", lockfile_path)\n    terminate(message, ERR_NO_GEMLOCK)\n  }\n\n  lockfile, err := ioutil.ReadFile(lockfile_path)\n  if err != nil {\n    terminate(\"Unable to read Gemfile.lock\", 1)\n  }\n\n  checksum     := calculateChecksum(string(lockfile))\n  archive_name := fmt.Sprintf(\"%s_%s_%s.tar.gz\", options.Prefix, checksum, runtime.GOARCH)\n  archive_path := fmt.Sprintf(\"\/tmp\/%s\", archive_name)\n  archive_url  := s3url(archive_name)\n\n  if fileExists(archive_path) {\n    if os.Remove(archive_path) != nil {\n      terminate(\"Failed to remove existing archive\", 1)\n    }\n  }\n\n  if action == \"upload\" || action == \"up\" {\n    upload(bundle_path, archive_path, archive_url)\n  }\n\n  if action == \"download\" || action == \"down\" {\n    download(options.Path, bundle_path, archive_path, archive_url)\n  }\n\n  fmt.Println(\"Invalid command:\", action)\n  printUsage()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage common\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/common\/model\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/klog\"\n\t\"k8s.io\/kubernetes\/pkg\/master\/ports\"\n\tschedulermetric \"k8s.io\/kubernetes\/pkg\/scheduler\/metrics\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/measurement\"\n\tmeasurementutil \"k8s.io\/perf-tests\/clusterloader2\/pkg\/measurement\/util\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/util\"\n)\n\nconst (\n\tschedulerLatencyMetricName = \"SchedulingMetrics\"\n\n\te2eSchedulingDurationMetricName           = model.LabelValue(schedulermetric.SchedulerSubsystem + \"_e2e_scheduling_duration_seconds_bucket\")\n\tschedulingAlgorithmDurationMetricName     = model.LabelValue(schedulermetric.SchedulerSubsystem + \"_scheduling_algorithm_duration_seconds_bucket\")\n\tframeworkExtensionPointDurationMetricName = model.LabelValue(schedulermetric.SchedulerSubsystem + \"_framework_extension_point_duration_seconds_bucket\")\n\tpreemptionEvaluationMetricName            = model.LabelValue(schedulermetric.SchedulerSubsystem + \"_scheduling_algorithm_preemption_evaluation_seconds_bucket\")\n\n\tsingleRestCallTimeout = 5 * time.Minute\n)\n\nvar (\n\textentionsPoints = []string{\n\t\t\"PreFilter\",\n\t\t\"Filter\",\n\t\t\"PreScore\",\n\t\t\"Score\",\n\t\t\"PreBind\",\n\t\t\"Bind\",\n\t\t\"PostBind\",\n\t\t\"Reserve\",\n\t\t\"Unreserve\",\n\t\t\"Permit\",\n\t}\n)\n\nfunc init() {\n\tif err := measurement.Register(schedulerLatencyMetricName, createSchedulerLatencyMeasurement); err != nil {\n\t\tklog.Fatalf(\"Cannot register %s: %v\", schedulerLatencyMetricName, err)\n\t}\n}\n\nfunc createSchedulerLatencyMeasurement() measurement.Measurement {\n\treturn &schedulerLatencyMeasurement{}\n}\n\ntype schedulerLatencyMeasurement struct {\n\tinitialLatency schedulerLatencyMetrics\n}\n\ntype schedulerLatencyMetrics struct {\n\te2eSchedulingDurationHist           *measurementutil.Histogram\n\tschedulingAlgorithmDurationHist     *measurementutil.Histogram\n\tpreemptionEvaluationHist            *measurementutil.Histogram\n\tframeworkExtensionPointDurationHist map[string]*measurementutil.Histogram\n}\n\n\/\/ Execute supports two actions:\n\/\/ - reset - Resets latency data on api scheduler side.\n\/\/ - gather - Gathers and prints current scheduler latency data.\nfunc (s *schedulerLatencyMeasurement) Execute(config *measurement.Config) ([]measurement.Summary, error) {\n\tSSHToMasterSupported := config.ClusterFramework.GetClusterConfig().SSHToMasterSupported\n\n\tc := config.ClusterFramework.GetClientSets().GetClient()\n\tnodes, err := c.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar masterRegistered = false\n\tfor _, node := range nodes.Items {\n\t\tif util.LegacyIsMasterNode(&node) {\n\t\t\tmasterRegistered = true\n\t\t}\n\t}\n\n\tprovider, err := util.GetStringOrDefault(config.Params, \"provider\", config.ClusterFramework.GetClusterConfig().Provider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !SSHToMasterSupported && !masterRegistered {\n\t\tklog.Infof(\"unable to fetch scheduler metrics for provider: %s\", provider)\n\t\treturn nil, nil\n\t}\n\n\taction, err := util.GetString(config.Params, \"action\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmasterIP, err := util.GetStringOrDefault(config.Params, \"masterIP\", config.ClusterFramework.GetClusterConfig().GetMasterIP())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmasterName, err := util.GetStringOrDefault(config.Params, \"masterName\", config.ClusterFramework.GetClusterConfig().MasterName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch action {\n\tcase \"reset\":\n\t\tklog.Infof(\"%s: start collecting latency initial metrics in scheduler...\", s)\n\t\treturn nil, s.getSchedulingInitialLatency(config.ClusterFramework.GetClientSets().GetClient(), masterIP, provider, masterName, masterRegistered)\n\tcase \"start\":\n\t\tklog.Infof(\"%s: start collecting latency metrics in scheduler...\", s)\n\t\treturn nil, s.getSchedulingInitialLatency(config.ClusterFramework.GetClientSets().GetClient(), masterIP, provider, masterName, masterRegistered)\n\tcase \"gather\":\n\t\tklog.Infof(\"%s: gathering latency metrics in scheduler...\", s)\n\t\treturn s.getSchedulingLatency(config.ClusterFramework.GetClientSets().GetClient(), masterIP, provider, masterName, masterRegistered)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown action %v\", action)\n\t}\n}\n\n\/\/ Dispose cleans up after the measurement.\nfunc (*schedulerLatencyMeasurement) Dispose() {}\n\n\/\/ String returns string representation of this measurement.\nfunc (*schedulerLatencyMeasurement) String() string {\n\treturn schedulerLatencyMetricName\n}\n\n\/\/ Helper function to substract two histograms\nfunc histogramSub(finalHist, initialHist *measurementutil.Histogram) *measurementutil.Histogram {\n\tfor k := range finalHist.Buckets {\n\t\tfinalHist.Buckets[k] = finalHist.Buckets[k] - initialHist.Buckets[k]\n\t}\n\treturn finalHist\n}\n\nfunc (m *schedulerLatencyMetrics) substract(sub schedulerLatencyMetrics) {\n\tif sub.preemptionEvaluationHist != nil {\n\t\tm.preemptionEvaluationHist = histogramSub(m.preemptionEvaluationHist, sub.preemptionEvaluationHist)\n\t}\n\tif sub.schedulingAlgorithmDurationHist != nil {\n\t\tm.schedulingAlgorithmDurationHist = histogramSub(m.schedulingAlgorithmDurationHist, sub.schedulingAlgorithmDurationHist)\n\t}\n\tif sub.e2eSchedulingDurationHist != nil {\n\t\tm.e2eSchedulingDurationHist = histogramSub(m.e2eSchedulingDurationHist, sub.e2eSchedulingDurationHist)\n\t}\n\tfor _, ep := range extentionsPoints {\n\t\tif sub.frameworkExtensionPointDurationHist[ep] != nil {\n\t\t\tm.frameworkExtensionPointDurationHist[ep] = histogramSub(m.frameworkExtensionPointDurationHist[ep], sub.frameworkExtensionPointDurationHist[ep])\n\t\t}\n\t}\n}\n\nfunc (s *schedulerLatencyMeasurement) setQuantiles(metrics schedulerLatencyMetrics) (schedulingMetrics, error) {\n\tresult := schedulingMetrics{\n\t\tFrameworkExtensionPointDuration: make(map[string]*measurementutil.LatencyMetric),\n\t}\n\tfor _, ePoint := range extentionsPoints {\n\t\tresult.FrameworkExtensionPointDuration[ePoint] = &measurementutil.LatencyMetric{}\n\t}\n\n\tif err := s.setQuantileFromHistogram(&result.E2eSchedulingLatency, metrics.e2eSchedulingDurationHist); err != nil {\n\t\treturn result, err\n\t}\n\tif err := s.setQuantileFromHistogram(&result.SchedulingLatency, metrics.schedulingAlgorithmDurationHist); err != nil {\n\t\treturn result, err\n\t}\n\n\tfor _, ePoint := range extentionsPoints {\n\t\tif err := s.setQuantileFromHistogram(result.FrameworkExtensionPointDuration[ePoint], metrics.frameworkExtensionPointDurationHist[ePoint]); err != nil {\n\t\t\treturn result, err\n\t\t}\n\t}\n\n\tif err := s.setQuantileFromHistogram(&result.PreemptionEvaluationLatency, metrics.preemptionEvaluationHist); err != nil {\n\t\treturn result, err\n\t}\n\treturn result, nil\n}\n\n\/\/ Retrieves scheduler latency metrics.\nfunc (s *schedulerLatencyMeasurement) getSchedulingLatency(c clientset.Interface, host, provider, masterName string, masterRegistered bool) ([]measurement.Summary, error) {\n\tschedulerMetrics, err := s.getSchedulingMetrics(c, host, provider, masterName, masterRegistered)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tschedulerMetrics.substract(s.initialLatency)\n\tresult, err := s.setQuantiles(schedulerMetrics)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent, err := util.PrettyPrintJSON(result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsummary := measurement.CreateSummary(schedulerLatencyMetricName, \"json\", content)\n\treturn []measurement.Summary{summary}, nil\n}\n\n\/\/ Retrieves initial values of scheduler latency metrics\nfunc (s *schedulerLatencyMeasurement) getSchedulingInitialLatency(c clientset.Interface, host, provider, masterName string, masterRegistered bool) error {\n\tvar err error\n\ts.initialLatency, err = s.getSchedulingMetrics(c, host, provider, masterName, masterRegistered)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Get scheduler latency metrics\nfunc (s *schedulerLatencyMeasurement) getSchedulingMetrics(c clientset.Interface, host, provider, masterName string, masterRegistered bool) (schedulerLatencyMetrics, error) {\n\te2eSchedulingDurationHist := measurementutil.NewHistogram(nil)\n\tschedulingAlgorithmDurationHist := measurementutil.NewHistogram(nil)\n\tpreemptionEvaluationHist := measurementutil.NewHistogram(nil)\n\tframeworkExtensionPointDurationHist := make(map[string]*measurementutil.Histogram)\n\tlatencyMetrics := schedulerLatencyMetrics{\n\t\te2eSchedulingDurationHist,\n\t\tschedulingAlgorithmDurationHist,\n\t\tpreemptionEvaluationHist,\n\t\tframeworkExtensionPointDurationHist}\n\n\tfor _, ePoint := range extentionsPoints {\n\t\tframeworkExtensionPointDurationHist[ePoint] = measurementutil.NewHistogram(nil)\n\t}\n\n\tdata, err := s.sendRequestToScheduler(c, \"GET\", host, provider, masterName, masterRegistered)\n\tif err != nil {\n\t\treturn latencyMetrics, err\n\t}\n\tsamples, err := measurementutil.ExtractMetricSamples(data)\n\tif err != nil {\n\t\treturn latencyMetrics, err\n\t}\n\n\tfor _, sample := range samples {\n\t\tswitch sample.Metric[model.MetricNameLabel] {\n\t\tcase e2eSchedulingDurationMetricName:\n\t\t\tmeasurementutil.ConvertSampleToHistogram(sample, e2eSchedulingDurationHist)\n\t\tcase schedulingAlgorithmDurationMetricName:\n\t\t\tmeasurementutil.ConvertSampleToHistogram(sample, schedulingAlgorithmDurationHist)\n\t\tcase frameworkExtensionPointDurationMetricName:\n\t\t\tePoint := string(sample.Metric[\"extension_point\"])\n\t\t\tif _, exists := frameworkExtensionPointDurationHist[ePoint]; exists {\n\t\t\t\tmeasurementutil.ConvertSampleToHistogram(sample, frameworkExtensionPointDurationHist[ePoint])\n\t\t\t}\n\t\tcase preemptionEvaluationMetricName:\n\t\t\tmeasurementutil.ConvertSampleToHistogram(sample, preemptionEvaluationHist)\n\t\t}\n\t}\n\treturn latencyMetrics, nil\n}\n\n\/\/ Set quantile of LatencyMetric from Histogram\nfunc (s *schedulerLatencyMeasurement) setQuantileFromHistogram(metric *measurementutil.LatencyMetric, hist *measurementutil.Histogram) error {\n\tquantiles := []float64{0.5, 0.9, 0.99}\n\tfor _, quantile := range quantiles {\n\t\thistQuantile, err := hist.Quantile(quantile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ NaN is returned only when there are less than two buckets.\n\t\t\/\/ In which case all quantiles are NaN and all latency metrics are untouched.\n\t\tif !math.IsNaN(histQuantile) {\n\t\t\tmetric.SetQuantile(quantile, time.Duration(int64(histQuantile*float64(time.Second))))\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Sends request to kube scheduler metrics\nfunc (s *schedulerLatencyMeasurement) sendRequestToScheduler(c clientset.Interface, op, host, provider, masterName string, masterRegistered bool) (string, error) {\n\topUpper := strings.ToUpper(op)\n\tif opUpper != \"GET\" && opUpper != \"DELETE\" {\n\t\treturn \"\", fmt.Errorf(\"unknown REST request\")\n\t}\n\n\tvar responseText string\n\tif masterRegistered {\n\t\tctx, cancel := context.WithTimeout(context.Background(), singleRestCallTimeout)\n\t\tdefer cancel()\n\n\t\tbody, err := c.CoreV1().RESTClient().Verb(opUpper).\n\t\t\tNamespace(metav1.NamespaceSystem).\n\t\t\tResource(\"pods\").\n\t\t\tName(fmt.Sprintf(\"kube-scheduler-%v:%v\", masterName, ports.InsecureSchedulerPort)).\n\t\t\tSubResource(\"proxy\").\n\t\t\tSuffix(\"metrics\").\n\t\t\tDo(ctx).Raw()\n\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Send request to scheduler failed with err: %v\", err)\n\t\t\treturn \"\", err\n\t\t}\n\t\tresponseText = string(body)\n\t} else {\n\t\tcmd := \"curl -X \" + opUpper + \" http:\/\/localhost:10251\/metrics\"\n\t\tsshResult, err := measurementutil.SSH(cmd, host+\":22\", provider)\n\t\tif err != nil || sshResult.Code != 0 {\n\t\t\treturn \"\", fmt.Errorf(\"unexpected error (code: %d) in ssh connection to master: %#v\", sshResult.Code, err)\n\t\t}\n\t\tresponseText = sshResult.Stdout\n\t}\n\treturn responseText, nil\n}\n\ntype schedulingMetrics struct {\n\tFrameworkExtensionPointDuration map[string]*measurementutil.LatencyMetric `json:\"frameworkExtensionPointDuration\"`\n\tPreemptionEvaluationLatency     measurementutil.LatencyMetric             `json:\"preemptionEvaluationLatency\"`\n\tE2eSchedulingLatency            measurementutil.LatencyMetric             `json:\"e2eSchedulingLatency\"`\n\n\t\/\/ To track scheduling latency without binding, this allows to easier present the ceiling of the scheduler throughput.\n\tSchedulingLatency measurementutil.LatencyMetric `json:\"schedulingLatency\"`\n}\n<commit_msg>address review comments: put function name in comments<commit_after>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage common\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/common\/model\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/klog\"\n\t\"k8s.io\/kubernetes\/pkg\/master\/ports\"\n\tschedulermetric \"k8s.io\/kubernetes\/pkg\/scheduler\/metrics\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/measurement\"\n\tmeasurementutil \"k8s.io\/perf-tests\/clusterloader2\/pkg\/measurement\/util\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/util\"\n)\n\nconst (\n\tschedulerLatencyMetricName = \"SchedulingMetrics\"\n\n\te2eSchedulingDurationMetricName           = model.LabelValue(schedulermetric.SchedulerSubsystem + \"_e2e_scheduling_duration_seconds_bucket\")\n\tschedulingAlgorithmDurationMetricName     = model.LabelValue(schedulermetric.SchedulerSubsystem + \"_scheduling_algorithm_duration_seconds_bucket\")\n\tframeworkExtensionPointDurationMetricName = model.LabelValue(schedulermetric.SchedulerSubsystem + \"_framework_extension_point_duration_seconds_bucket\")\n\tpreemptionEvaluationMetricName            = model.LabelValue(schedulermetric.SchedulerSubsystem + \"_scheduling_algorithm_preemption_evaluation_seconds_bucket\")\n\n\tsingleRestCallTimeout = 5 * time.Minute\n)\n\nvar (\n\textentionsPoints = []string{\n\t\t\"PreFilter\",\n\t\t\"Filter\",\n\t\t\"PreScore\",\n\t\t\"Score\",\n\t\t\"PreBind\",\n\t\t\"Bind\",\n\t\t\"PostBind\",\n\t\t\"Reserve\",\n\t\t\"Unreserve\",\n\t\t\"Permit\",\n\t}\n)\n\nfunc init() {\n\tif err := measurement.Register(schedulerLatencyMetricName, createSchedulerLatencyMeasurement); err != nil {\n\t\tklog.Fatalf(\"Cannot register %s: %v\", schedulerLatencyMetricName, err)\n\t}\n}\n\nfunc createSchedulerLatencyMeasurement() measurement.Measurement {\n\treturn &schedulerLatencyMeasurement{}\n}\n\ntype schedulerLatencyMeasurement struct {\n\tinitialLatency schedulerLatencyMetrics\n}\n\ntype schedulerLatencyMetrics struct {\n\te2eSchedulingDurationHist           *measurementutil.Histogram\n\tschedulingAlgorithmDurationHist     *measurementutil.Histogram\n\tpreemptionEvaluationHist            *measurementutil.Histogram\n\tframeworkExtensionPointDurationHist map[string]*measurementutil.Histogram\n}\n\n\/\/ Execute supports two actions:\n\/\/ - reset - Resets latency data on api scheduler side.\n\/\/ - gather - Gathers and prints current scheduler latency data.\nfunc (s *schedulerLatencyMeasurement) Execute(config *measurement.Config) ([]measurement.Summary, error) {\n\tSSHToMasterSupported := config.ClusterFramework.GetClusterConfig().SSHToMasterSupported\n\n\tc := config.ClusterFramework.GetClientSets().GetClient()\n\tnodes, err := c.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar masterRegistered = false\n\tfor _, node := range nodes.Items {\n\t\tif util.LegacyIsMasterNode(&node) {\n\t\t\tmasterRegistered = true\n\t\t}\n\t}\n\n\tprovider, err := util.GetStringOrDefault(config.Params, \"provider\", config.ClusterFramework.GetClusterConfig().Provider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !SSHToMasterSupported && !masterRegistered {\n\t\tklog.Infof(\"unable to fetch scheduler metrics for provider: %s\", provider)\n\t\treturn nil, nil\n\t}\n\n\taction, err := util.GetString(config.Params, \"action\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmasterIP, err := util.GetStringOrDefault(config.Params, \"masterIP\", config.ClusterFramework.GetClusterConfig().GetMasterIP())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmasterName, err := util.GetStringOrDefault(config.Params, \"masterName\", config.ClusterFramework.GetClusterConfig().MasterName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch action {\n\tcase \"reset\":\n\t\tklog.Infof(\"%s: start collecting latency initial metrics in scheduler...\", s)\n\t\treturn nil, s.getSchedulingInitialLatency(config.ClusterFramework.GetClientSets().GetClient(), masterIP, provider, masterName, masterRegistered)\n\tcase \"start\":\n\t\tklog.Infof(\"%s: start collecting latency metrics in scheduler...\", s)\n\t\treturn nil, s.getSchedulingInitialLatency(config.ClusterFramework.GetClientSets().GetClient(), masterIP, provider, masterName, masterRegistered)\n\tcase \"gather\":\n\t\tklog.Infof(\"%s: gathering latency metrics in scheduler...\", s)\n\t\treturn s.getSchedulingLatency(config.ClusterFramework.GetClientSets().GetClient(), masterIP, provider, masterName, masterRegistered)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown action %v\", action)\n\t}\n}\n\n\/\/ Dispose cleans up after the measurement.\nfunc (*schedulerLatencyMeasurement) Dispose() {}\n\n\/\/ String returns string representation of this measurement.\nfunc (*schedulerLatencyMeasurement) String() string {\n\treturn schedulerLatencyMetricName\n}\n\n\/\/ histogramSub is a helper function to substract two histograms\nfunc histogramSub(finalHist, initialHist *measurementutil.Histogram) *measurementutil.Histogram {\n\tfor k := range finalHist.Buckets {\n\t\tfinalHist.Buckets[k] = finalHist.Buckets[k] - initialHist.Buckets[k]\n\t}\n\treturn finalHist\n}\n\nfunc (m *schedulerLatencyMetrics) substract(sub schedulerLatencyMetrics) {\n\tif sub.preemptionEvaluationHist != nil {\n\t\tm.preemptionEvaluationHist = histogramSub(m.preemptionEvaluationHist, sub.preemptionEvaluationHist)\n\t}\n\tif sub.schedulingAlgorithmDurationHist != nil {\n\t\tm.schedulingAlgorithmDurationHist = histogramSub(m.schedulingAlgorithmDurationHist, sub.schedulingAlgorithmDurationHist)\n\t}\n\tif sub.e2eSchedulingDurationHist != nil {\n\t\tm.e2eSchedulingDurationHist = histogramSub(m.e2eSchedulingDurationHist, sub.e2eSchedulingDurationHist)\n\t}\n\tfor _, ep := range extentionsPoints {\n\t\tif sub.frameworkExtensionPointDurationHist[ep] != nil {\n\t\t\tm.frameworkExtensionPointDurationHist[ep] = histogramSub(m.frameworkExtensionPointDurationHist[ep], sub.frameworkExtensionPointDurationHist[ep])\n\t\t}\n\t}\n}\n\nfunc (s *schedulerLatencyMeasurement) setQuantiles(metrics schedulerLatencyMetrics) (schedulingMetrics, error) {\n\tresult := schedulingMetrics{\n\t\tFrameworkExtensionPointDuration: make(map[string]*measurementutil.LatencyMetric),\n\t}\n\tfor _, ePoint := range extentionsPoints {\n\t\tresult.FrameworkExtensionPointDuration[ePoint] = &measurementutil.LatencyMetric{}\n\t}\n\n\tif err := s.setQuantileFromHistogram(&result.E2eSchedulingLatency, metrics.e2eSchedulingDurationHist); err != nil {\n\t\treturn result, err\n\t}\n\tif err := s.setQuantileFromHistogram(&result.SchedulingLatency, metrics.schedulingAlgorithmDurationHist); err != nil {\n\t\treturn result, err\n\t}\n\n\tfor _, ePoint := range extentionsPoints {\n\t\tif err := s.setQuantileFromHistogram(result.FrameworkExtensionPointDuration[ePoint], metrics.frameworkExtensionPointDurationHist[ePoint]); err != nil {\n\t\t\treturn result, err\n\t\t}\n\t}\n\n\tif err := s.setQuantileFromHistogram(&result.PreemptionEvaluationLatency, metrics.preemptionEvaluationHist); err != nil {\n\t\treturn result, err\n\t}\n\treturn result, nil\n}\n\n\/\/ getSchedulingLatency retrieves scheduler latency metrics.\nfunc (s *schedulerLatencyMeasurement) getSchedulingLatency(c clientset.Interface, host, provider, masterName string, masterRegistered bool) ([]measurement.Summary, error) {\n\tschedulerMetrics, err := s.getSchedulingMetrics(c, host, provider, masterName, masterRegistered)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tschedulerMetrics.substract(s.initialLatency)\n\tresult, err := s.setQuantiles(schedulerMetrics)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontent, err := util.PrettyPrintJSON(result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsummary := measurement.CreateSummary(schedulerLatencyMetricName, \"json\", content)\n\treturn []measurement.Summary{summary}, nil\n}\n\n\/\/ getSchedulingInitialLatency retrieves initial values of scheduler latency metrics\nfunc (s *schedulerLatencyMeasurement) getSchedulingInitialLatency(c clientset.Interface, host, provider, masterName string, masterRegistered bool) error {\n\tvar err error\n\ts.initialLatency, err = s.getSchedulingMetrics(c, host, provider, masterName, masterRegistered)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ getSchedulingMetrics gets scheduler latency metrics\nfunc (s *schedulerLatencyMeasurement) getSchedulingMetrics(c clientset.Interface, host, provider, masterName string, masterRegistered bool) (schedulerLatencyMetrics, error) {\n\te2eSchedulingDurationHist := measurementutil.NewHistogram(nil)\n\tschedulingAlgorithmDurationHist := measurementutil.NewHistogram(nil)\n\tpreemptionEvaluationHist := measurementutil.NewHistogram(nil)\n\tframeworkExtensionPointDurationHist := make(map[string]*measurementutil.Histogram)\n\tlatencyMetrics := schedulerLatencyMetrics{\n\t\te2eSchedulingDurationHist,\n\t\tschedulingAlgorithmDurationHist,\n\t\tpreemptionEvaluationHist,\n\t\tframeworkExtensionPointDurationHist}\n\n\tfor _, ePoint := range extentionsPoints {\n\t\tframeworkExtensionPointDurationHist[ePoint] = measurementutil.NewHistogram(nil)\n\t}\n\n\tdata, err := s.sendRequestToScheduler(c, \"GET\", host, provider, masterName, masterRegistered)\n\tif err != nil {\n\t\treturn latencyMetrics, err\n\t}\n\tsamples, err := measurementutil.ExtractMetricSamples(data)\n\tif err != nil {\n\t\treturn latencyMetrics, err\n\t}\n\n\tfor _, sample := range samples {\n\t\tswitch sample.Metric[model.MetricNameLabel] {\n\t\tcase e2eSchedulingDurationMetricName:\n\t\t\tmeasurementutil.ConvertSampleToHistogram(sample, e2eSchedulingDurationHist)\n\t\tcase schedulingAlgorithmDurationMetricName:\n\t\t\tmeasurementutil.ConvertSampleToHistogram(sample, schedulingAlgorithmDurationHist)\n\t\tcase frameworkExtensionPointDurationMetricName:\n\t\t\tePoint := string(sample.Metric[\"extension_point\"])\n\t\t\tif _, exists := frameworkExtensionPointDurationHist[ePoint]; exists {\n\t\t\t\tmeasurementutil.ConvertSampleToHistogram(sample, frameworkExtensionPointDurationHist[ePoint])\n\t\t\t}\n\t\tcase preemptionEvaluationMetricName:\n\t\t\tmeasurementutil.ConvertSampleToHistogram(sample, preemptionEvaluationHist)\n\t\t}\n\t}\n\treturn latencyMetrics, nil\n}\n\n\/\/ setQuantileFromHistogram sets quantile of LatencyMetric from Histogram\nfunc (s *schedulerLatencyMeasurement) setQuantileFromHistogram(metric *measurementutil.LatencyMetric, hist *measurementutil.Histogram) error {\n\tquantiles := []float64{0.5, 0.9, 0.99}\n\tfor _, quantile := range quantiles {\n\t\thistQuantile, err := hist.Quantile(quantile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ NaN is returned only when there are less than two buckets.\n\t\t\/\/ In which case all quantiles are NaN and all latency metrics are untouched.\n\t\tif !math.IsNaN(histQuantile) {\n\t\t\tmetric.SetQuantile(quantile, time.Duration(int64(histQuantile*float64(time.Second))))\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ sendRequestToScheduler sends request to kube scheduler metrics\nfunc (s *schedulerLatencyMeasurement) sendRequestToScheduler(c clientset.Interface, op, host, provider, masterName string, masterRegistered bool) (string, error) {\n\topUpper := strings.ToUpper(op)\n\tif opUpper != \"GET\" && opUpper != \"DELETE\" {\n\t\treturn \"\", fmt.Errorf(\"unknown REST request\")\n\t}\n\n\tvar responseText string\n\tif masterRegistered {\n\t\tctx, cancel := context.WithTimeout(context.Background(), singleRestCallTimeout)\n\t\tdefer cancel()\n\n\t\tbody, err := c.CoreV1().RESTClient().Verb(opUpper).\n\t\t\tNamespace(metav1.NamespaceSystem).\n\t\t\tResource(\"pods\").\n\t\t\tName(fmt.Sprintf(\"kube-scheduler-%v:%v\", masterName, ports.InsecureSchedulerPort)).\n\t\t\tSubResource(\"proxy\").\n\t\t\tSuffix(\"metrics\").\n\t\t\tDo(ctx).Raw()\n\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"Send request to scheduler failed with err: %v\", err)\n\t\t\treturn \"\", err\n\t\t}\n\t\tresponseText = string(body)\n\t} else {\n\t\tcmd := \"curl -X \" + opUpper + \" http:\/\/localhost:10251\/metrics\"\n\t\tsshResult, err := measurementutil.SSH(cmd, host+\":22\", provider)\n\t\tif err != nil || sshResult.Code != 0 {\n\t\t\treturn \"\", fmt.Errorf(\"unexpected error (code: %d) in ssh connection to master: %#v\", sshResult.Code, err)\n\t\t}\n\t\tresponseText = sshResult.Stdout\n\t}\n\treturn responseText, nil\n}\n\ntype schedulingMetrics struct {\n\tFrameworkExtensionPointDuration map[string]*measurementutil.LatencyMetric `json:\"frameworkExtensionPointDuration\"`\n\tPreemptionEvaluationLatency     measurementutil.LatencyMetric             `json:\"preemptionEvaluationLatency\"`\n\tE2eSchedulingLatency            measurementutil.LatencyMetric             `json:\"e2eSchedulingLatency\"`\n\n\t\/\/ To track scheduling latency without binding, this allows to easier present the ceiling of the scheduler throughput.\n\tSchedulingLatency measurementutil.LatencyMetric `json:\"schedulingLatency\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Doctl Authors All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage commands\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/digitalocean\/doctl\"\n\t\"github.com\/digitalocean\/doctl\/commands\/displayers\"\n\t\"github.com\/digitalocean\/doctl\/do\"\n\t\"github.com\/digitalocean\/godo\"\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ Tags creates the tag commands hierarchy.\nfunc Tags() *Command {\n\tcmd := &Command{\n\t\tCommand: &cobra.Command{\n\t\t\tUse:   \"tag\",\n\t\t\tShort: \"tag commands\",\n\t\t\tLong:  \"tag is used to access tag commands\",\n\t\t},\n\t}\n\n\tCmdBuilder(cmd, RunCmdTagCreate, \"create <tag-name>\", \"create tag\", Writer)\n\n\tCmdBuilder(cmd, RunCmdTagGet, \"get <tag-name>\", \"get tag\", Writer,\n\t\tdisplayerType(&displayers.Tag{}))\n\n\tCmdBuilder(cmd, RunCmdTagList, \"list\", \"list tags\", Writer,\n\t\taliasOpt(\"ls\"), displayerType(&displayers.Tag{}))\n\n\tcmdRunTagDelete := CmdBuilder(cmd, RunCmdTagDelete, \"delete <tag-name>...\", \"delete tags\", Writer)\n\tAddBoolFlag(cmdRunTagDelete, doctl.ArgForce, doctl.ArgShortForce, false, \"Force tag delete\")\n\n\treturn cmd\n}\n\n\/\/ RunCmdTagCreate runs tag create.\nfunc RunCmdTagCreate(c *CmdConfig) error {\n\tif len(c.Args) != 1 {\n\t\treturn doctl.NewMissingArgsErr(c.NS)\n\t}\n\n\tname := c.Args[0]\n\tts := c.Tags()\n\n\ttcr := &godo.TagCreateRequest{Name: name}\n\tt, err := ts.Create(tcr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Display(&displayers.Tag{Tags: do.Tags{*t}})\n}\n\n\/\/ RunCmdTagGet runs tag get.\nfunc RunCmdTagGet(c *CmdConfig) error {\n\tif len(c.Args) != 1 {\n\t\treturn doctl.NewMissingArgsErr(c.NS)\n\t}\n\n\tname := c.Args[0]\n\tts := c.Tags()\n\tt, err := ts.Get(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Display(&displayers.Tag{Tags: do.Tags{*t}})\n}\n\n\/\/ RunCmdTagList runs tag list.\nfunc RunCmdTagList(c *CmdConfig) error {\n\tts := c.Tags()\n\ttags, err := ts.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Display(&displayers.Tag{Tags: tags})\n}\n\n\/\/ RunCmdTagDelete runs tag delete.\nfunc RunCmdTagDelete(c *CmdConfig) error {\n\tif len(c.Args) < 1 {\n\t\treturn doctl.NewMissingArgsErr(c.NS)\n\t}\n\n\tforce, err := c.Doit.GetBool(c.NS, doctl.ArgForce)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif force || AskForConfirm(\"delete tag(s)\") == nil {\n\t\tfor id := range c.Args {\n\t\t\tname := c.Args[id]\n\t\t\tts := c.Tags()\n\t\t\tif err := ts.Delete(name); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"operation aborted\")\n\t}\n\n\treturn nil\n}\n<commit_msg>Add extended documentation for tag command<commit_after>\/*\nCopyright 2018 The Doctl Authors All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage commands\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/digitalocean\/doctl\"\n\t\"github.com\/digitalocean\/doctl\/commands\/displayers\"\n\t\"github.com\/digitalocean\/doctl\/do\"\n\t\"github.com\/digitalocean\/godo\"\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ Tags creates the tag commands hierarchy.\nfunc Tags() *Command {\n\tcmd := &Command{\n\t\tCommand: &cobra.Command{\n\t\t\tUse:   \"tag\",\n\t\t\tShort: \"Provides commands that manage tags\",\n\t\t\tLong:  `The sub-commands of 'doctl compute tag' manage the tags on your account.\n\t\t\t\nA tag is a label that can be applied to a resource (currently Droplets, Images, \nVolumes, Volume Snapshots, and Database clusters) in order to better organize or \nfacilitate the lookups and actions on it.\nTags have two attributes: a user defined name attribute and an embedded \nresources attribute with information about resources that have been tagged.`,\n\t\t},\n\t}\n\n\tCmdBuilderWithDocs(cmd, RunCmdTagCreate, \"create <tag-name>\", \"create tag\", `Use this command to create a new tag on your account.`, Writer)\n\n\tCmdBuilderWithDocs(cmd, RunCmdTagGet, \"get <tag-name>\", \"get tag\", `Use this command to retrieve a tag, see how many resources are using the tag, and the last item tagged with the current tag.`,Writer,\n\t\tdisplayerType(&displayers.Tag{}))\n\n\tCmdBuilderWithDocs(cmd, RunCmdTagList, \"list\", \"list tags\", `Use this command to retrieve a list of all tags on your account.`, Writer,\n\t\taliasOpt(\"ls\"), displayerType(&displayers.Tag{}))\n\n\tcmdRunTagDelete := CmdBuilderWithDocs(cmd, RunCmdTagDelete, \"delete <tag-name>...\", \"delete tags\", `Use this command to delete a tag.\n\nDeleting a tag also untags all the resources that have previously been tagged by the tag.`, Writer)\n\tAddBoolFlag(cmdRunTagDelete, doctl.ArgForce, doctl.ArgShortForce, false, \"Force tag delete\")\n\n\treturn cmd\n}\n\n\/\/ RunCmdTagCreate runs tag create.\nfunc RunCmdTagCreate(c *CmdConfig) error {\n\tif len(c.Args) != 1 {\n\t\treturn doctl.NewMissingArgsErr(c.NS)\n\t}\n\n\tname := c.Args[0]\n\tts := c.Tags()\n\n\ttcr := &godo.TagCreateRequest{Name: name}\n\tt, err := ts.Create(tcr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Display(&displayers.Tag{Tags: do.Tags{*t}})\n}\n\n\/\/ RunCmdTagGet runs tag get.\nfunc RunCmdTagGet(c *CmdConfig) error {\n\tif len(c.Args) != 1 {\n\t\treturn doctl.NewMissingArgsErr(c.NS)\n\t}\n\n\tname := c.Args[0]\n\tts := c.Tags()\n\tt, err := ts.Get(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Display(&displayers.Tag{Tags: do.Tags{*t}})\n}\n\n\/\/ RunCmdTagList runs tag list.\nfunc RunCmdTagList(c *CmdConfig) error {\n\tts := c.Tags()\n\ttags, err := ts.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.Display(&displayers.Tag{Tags: tags})\n}\n\n\/\/ RunCmdTagDelete runs tag delete.\nfunc RunCmdTagDelete(c *CmdConfig) error {\n\tif len(c.Args) < 1 {\n\t\treturn doctl.NewMissingArgsErr(c.NS)\n\t}\n\n\tforce, err := c.Doit.GetBool(c.NS, doctl.ArgForce)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif force || AskForConfirm(\"delete tag(s)\") == nil {\n\t\tfor id := range c.Args {\n\t\t\tname := c.Args[id]\n\t\t\tts := c.Tags()\n\t\t\tif err := ts.Delete(name); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"operation aborted\")\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package override\n\nimport (\n\t\"net\"\n\t\"testing\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc ipsEqual(in []net.IP, vals ...string) bool {\n\tif len(in) != len(vals) {\n\t\treturn false\n\t}\n\n\tfor i, ip := range in {\n\t\tif !ip.Equal(net.ParseIP(vals[i])) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc TestOverride(t *testing.T) {\n\tConvey(\"override should work\", t, func() {\n\t\tips := ParseIPs(\"127.0.0.1\", \"127.0.0.2\")\n\t\tSo(ipsEqual(ips, \"127.0.0.1\", \"127.0.0.2\"), ShouldBeTrue)\n\n\t\tlist := map[string][]net.IP{\n\t\t\t\"example.com\": ips,\n\t\t}\n\n\t\to := New(list)\n\t\tSo(o, ShouldNotBeNil)\n\n\t\tv, ok := o.Override(\"www.example.com\")\n\t\tSo(ok, ShouldBeFalse)\n\t\tSo(v, ShouldBeNil)\n\n\t\tv, ok = o.Override(\"example.com\")\n\t\tSo(ok, ShouldBeTrue)\n\t\tSo(ipsEqual(v, \"127.0.0.1\", \"127.0.0.2\"), ShouldBeTrue)\n\t})\n}\n<commit_msg>fix broken test<commit_after>package override\n\nimport (\n\t\"net\"\n\t\"testing\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc ipsEqual(in []net.IP, vals ...string) bool {\n\tif len(in) != len(vals) {\n\t\treturn false\n\t}\n\n\tfor i, ip := range in {\n\t\tif !ip.Equal(net.ParseIP(vals[i])) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc TestOverride(t *testing.T) {\n\tConvey(\"override should work\", t, func() {\n\t\tips := ParseIPs(\"127.0.0.1\", \"127.0.0.2\")\n\t\tSo(ipsEqual(ips, \"127.0.0.1\", \"127.0.0.2\"), ShouldBeTrue)\n\n\t\tlist := map[string][]net.IP{\n\t\t\t\"example.com\": ips,\n\t\t}\n\n\t\to := New(list)\n\t\tSo(o, ShouldNotBeNil)\n\n\t\tv := o.Override(\"www.example.com\")\n\t\tSo(v, ShouldBeNil)\n\n\t\tv = o.Override(\"example.com\")\n\t\tSo(ipsEqual(v, \"127.0.0.1\", \"127.0.0.2\"), ShouldBeTrue)\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package admin\n\nimport (\n\t\"net\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/rakyll\/statik\/fs\"\n\n\t_ \"github.com\/influxdb\/influxdb\/statik\"\n)\n\ntype HttpServer struct {\n\tport     string\n\tlistener net.Listener\n\tclosed   bool\n}\n\n\/\/ port should be a string that looks like \":8083\" or whatever port to serve on.\nfunc NewHttpServer(port string) *HttpServer {\n\treturn &HttpServer{port: port, closed: true}\n}\n\nfunc (s *HttpServer) ListenAndServe() {\n\tif s.port == \"\" {\n\t\treturn\n\t}\n\n\ts.closed = false\n\tvar err error\n\ts.listener, _ = net.Listen(\"tcp\", s.port)\n\n\tstatikFS, _ := fs.New()\n\n\terr = http.Serve(s.listener, http.FileServer(statikFS))\n\tif !strings.Contains(err.Error(), \"closed\") {\n\t\tpanic(err)\n\t}\n}\n\nfunc (s *HttpServer) Close() {\n\tif s.closed {\n\t\treturn\n\t}\n\n\ts.closed = true\n\ts.listener.Close()\n}\n<commit_msg>Stop setting up the listener on an error.<commit_after>package admin\n\nimport (\n\t\"net\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/rakyll\/statik\/fs\"\n\n\t_ \"github.com\/influxdb\/influxdb\/statik\"\n)\n\ntype HttpServer struct {\n\tport     string\n\tlistener net.Listener\n\tclosed   bool\n}\n\n\/\/ port should be a string that looks like \":8083\" or whatever port to serve on.\nfunc NewHttpServer(port string) *HttpServer {\n\treturn &HttpServer{port: port, closed: true}\n}\n\nfunc (s *HttpServer) ListenAndServe() {\n\tif s.port == \"\" {\n\t\treturn\n\t}\n\n\ts.closed = false\n\tvar err error\n\ts.listener, _ = net.Listen(\"tcp\", s.port)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tstatikFS, _ := fs.New()\n\n\terr = http.Serve(s.listener, http.FileServer(statikFS))\n\tif !strings.Contains(err.Error(), \"closed\") {\n\t\tpanic(err)\n\t}\n}\n\nfunc (s *HttpServer) Close() {\n\tif s.closed {\n\t\treturn\n\t}\n\n\ts.closed = true\n\ts.listener.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 Google Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage banner\n\nimport (\n\t\"net\/http\"\n\t\"testing\"\n)\n\nfunc TestIsHTMLRequest(t *testing.T) {\n\ttestCases := []struct {\n\t\treq  *http.Request\n\t\twant bool\n\t}{\n\t\t{\n\t\t\treq:  &http.Request{},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\treq: &http.Request{\n\t\t\t\tMethod: http.MethodPost,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Accept\": []string{\"text\/html\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\treq: &http.Request{\n\t\t\t\tMethod: http.MethodGet,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Accept\": []string{\"application\/json\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\treq: &http.Request{\n\t\t\t\tMethod: http.MethodGet,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Accept\": []string{\"text\/xhtml\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\treq: &http.Request{\n\t\t\t\tMethod: http.MethodGet,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Accept\": []string{\"text\/html\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t}\n\n\tfor _, testCase := range testCases {\n\t\tif got, want := isHTMLRequest(testCase.req), testCase.want; got != want {\n\t\t\tt.Errorf(\"isHTMLRequest(%+v): got %v, want %v\", testCase.req, got, want)\n\t\t}\n\t}\n}\n\nfunc TestIsHTMLResponse(t *testing.T) {\n\ttestCases := []struct {\n\t\tresp *http.Response\n\t\twant bool\n\t}{\n\t\t{\n\t\t\tresp: &http.Response{},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tresp: &http.Response{\n\t\t\t\tStatusCode: http.StatusNotFound,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Content-Type\": []string{\"text\/html\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tresp: &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Content-Type\": []string{\"application\/json\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tresp: &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Content-Type\": []string{\"text\/xhtml\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tresp: &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Content-Type\": []string{\"text\/html\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t}\n\n\tfor _, testCase := range testCases {\n\t\tif got, want := isHTMLResponse(testCase.resp), testCase.want; got != want {\n\t\t\tt.Errorf(\"isHTMLResponse(%+v): got %v, want %v\", testCase.resp, got, want)\n\t\t}\n\t}\n}\n<commit_msg>Add a unit test for the isAlreadyFramed method<commit_after>\/*\nCopyright 2019 Google Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage banner\n\nimport (\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"testing\"\n)\n\nfunc TestIsHTMLRequest(t *testing.T) {\n\ttestCases := []struct {\n\t\treq  *http.Request\n\t\twant bool\n\t}{\n\t\t{\n\t\t\treq:  &http.Request{},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\treq: &http.Request{\n\t\t\t\tMethod: http.MethodPost,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Accept\": []string{\"text\/html\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\treq: &http.Request{\n\t\t\t\tMethod: http.MethodGet,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Accept\": []string{\"application\/json\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\treq: &http.Request{\n\t\t\t\tMethod: http.MethodGet,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Accept\": []string{\"text\/xhtml\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\treq: &http.Request{\n\t\t\t\tMethod: http.MethodGet,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Accept\": []string{\"text\/html\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t}\n\n\tfor _, testCase := range testCases {\n\t\tif got, want := isHTMLRequest(testCase.req), testCase.want; got != want {\n\t\t\tt.Errorf(\"isHTMLRequest(%+v): got %v, want %v\", testCase.req, got, want)\n\t\t}\n\t}\n}\n\nfunc TestIsHTMLResponse(t *testing.T) {\n\ttestCases := []struct {\n\t\tresp *http.Response\n\t\twant bool\n\t}{\n\t\t{\n\t\t\tresp: &http.Response{},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tresp: &http.Response{\n\t\t\t\tStatusCode: http.StatusNotFound,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Content-Type\": []string{\"text\/html\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tresp: &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Content-Type\": []string{\"application\/json\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tresp: &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Content-Type\": []string{\"text\/xhtml\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tresp: &http.Response{\n\t\t\t\tStatusCode: http.StatusOK,\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Content-Type\": []string{\"text\/html\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t}\n\n\tfor _, testCase := range testCases {\n\t\tif got, want := isHTMLResponse(testCase.resp), testCase.want; got != want {\n\t\t\tt.Errorf(\"isHTMLResponse(%+v): got %v, want %v\", testCase.resp, got, want)\n\t\t}\n\t}\n}\n\nfunc TestIsAlreadyFramed(t *testing.T) {\n\ttestCases := []struct {\n\t\treq  *http.Request\n\t\twant bool\n\t}{\n\t\t{\n\t\t\treq:  &http.Request{},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\treq: &http.Request{\n\t\t\t\tHost: \"example.com\",\n\t\t\t\tURL: &url.URL{\n\t\t\t\t\tPath: \"\/some\/example\/path\",\n\t\t\t\t},\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Referer\": []string{\"https:\/\/example.com\/some\/other\/path\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\treq: &http.Request{\n\t\t\t\tHost: \"example.com\",\n\t\t\t\tURL: &url.URL{\n\t\t\t\t\tPath: \"\/some\/example\/path\",\n\t\t\t\t},\n\t\t\t\tHeader: http.Header{\n\t\t\t\t\t\"Referer\": []string{\"https:\/\/example.com\/some\/example\/path\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: true,\n\t\t},\n\t}\n\n\tfor _, testCase := range testCases {\n\t\tif got, want := isAlreadyFramed(testCase.req), testCase.want; got != want {\n\t\t\tt.Errorf(\"isAlreadyFramed(%+v): got %v, want %v\", testCase.req, got, want)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package kami\n\nimport (\n\t\"golang.org\/x\/net\/context\"\n)\n\ntype key int\n\nconst (\n\tparamsKey key = iota\n\tpanicKey\n)\n\n\/\/ Param returns a request URL parameter, or a blank string if it doesn't exist.\n\/\/ For example, with the path \/v2\/papers\/:page\n\/\/ use kami.Param(ctx, \"page\") to access the :page variable.\nfunc Param(ctx context.Context, name string) string {\n\tparams, ok := ctx.Value(paramsKey).(map[string]string)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn params[name]\n}\n\n\/\/ Exception gets the \"v\" in panic(v). The panic details.\n\/\/ Only PanicHandler will receive a context you can use this with.\nfunc Exception(ctx context.Context) interface{} {\n\treturn ctx.Value(panicKey)\n}\n\nfunc newContextWithParams(ctx context.Context, params map[string]string) context.Context {\n\treturn context.WithValue(ctx, paramsKey, params)\n}\n\nfunc mergeParams(ctx context.Context, params map[string]string) context.Context {\n\tcurrent, _ := ctx.Value(paramsKey).(map[string]string)\n\tif current == nil {\n\t\treturn context.WithValue(ctx, paramsKey, params)\n\t}\n\n\tfor k, v := range params {\n\t\tcurrent[k] = v\n\t}\n\treturn ctx\n}\n\nfunc newContextWithException(ctx context.Context, exception interface{}) context.Context {\n\treturn context.WithValue(ctx, panicKey, exception)\n}\n<commit_msg>add the SetParameters method<commit_after>package kami\n\nimport (\n\t\"golang.org\/x\/net\/context\"\n)\n\ntype key int\n\nconst (\n\tparamsKey key = iota\n\tpanicKey\n)\n\n\/\/ Param returns a request URL parameter, or a blank string if it doesn't exist.\n\/\/ For example, with the path \/v2\/papers\/:page\n\/\/ use kami.Param(ctx, \"page\") to access the :page variable.\nfunc Param(ctx context.Context, name string) string {\n\tparams, ok := ctx.Value(paramsKey).(map[string]string)\n\tif !ok {\n\t\treturn \"\"\n\t}\n\treturn params[name]\n}\n\n\/\/ SetParameter will set the value of a path parameter in a given context.\nfunc SetParameter(ctx context.Context, name string, value string) context.Context {\n\tparams, ok := ctx.Value(paramsKey).(map[string]string)\n\tif !ok {\n\t\tparams = make(map[string]string)\n\t}\n\tparams[name] = value\n\treturn context.WithValue(ctx, paramsKey, params)\n}\n\n\/\/ Exception gets the \"v\" in panic(v). The panic details.\n\/\/ Only PanicHandler will receive a context you can use this with.\nfunc Exception(ctx context.Context) interface{} {\n\treturn ctx.Value(panicKey)\n}\n\nfunc newContextWithParams(ctx context.Context, params map[string]string) context.Context {\n\treturn context.WithValue(ctx, paramsKey, params)\n}\n\nfunc mergeParams(ctx context.Context, params map[string]string) context.Context {\n\tcurrent, _ := ctx.Value(paramsKey).(map[string]string)\n\tif current == nil {\n\t\treturn context.WithValue(ctx, paramsKey, params)\n\t}\n\n\tfor k, v := range params {\n\t\tcurrent[k] = v\n\t}\n\treturn ctx\n}\n\nfunc newContextWithException(ctx context.Context, exception interface{}) context.Context {\n\treturn context.WithValue(ctx, panicKey, exception)\n}\n<|endoftext|>"}
{"text":"<commit_before>package api_test\n\nimport (\n\t\"cf\"\n\t. \"cf\/api\"\n\t\"cf\/configuration\"\n\t\"cf\/net\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"strings\"\n\t\"testhelpers\"\n\t\"testing\"\n)\n\nfunc TestCreate(t *testing.T) {\n\tendpoint, status := testhelpers.CreateCheckableEndpoint(\n\t\t\"POST\",\n\t\t\"\/v2\/service_auth_tokens\",\n\t\ttesthelpers.RequestBodyMatcher(`{\"label\":\"a label\",\"provider\":\"a provider\",\"token\":\"a token\"}`),\n\t\ttesthelpers.TestResponse{Status: http.StatusCreated},\n\t)\n\n\tts, repo := createServiceAuthTokenRepo(endpoint)\n\tdefer ts.Close()\n\n\tapiResponse := repo.Create(cf.ServiceAuthToken{Label: \"a label\", Provider: \"a provider\", Token: \"a token\"})\n\n\tassert.True(t, status.Called())\n\tassert.True(t, apiResponse.IsSuccessful())\n}\n\nvar findAllServiceAuthTokensEndpoint, findAllStatus = testhelpers.CreateCheckableEndpoint(\n\t\"GET\",\n\t\"\/v2\/service_auth_tokens\",\n\tnil,\n\ttesthelpers.TestResponse{Status: http.StatusOK, Body: `\n{\n  \"resources\": [\n    {\n      \"metadata\": {\n        \"guid\": \"mysql-core-guid\"\n      },\n      \"entity\": {\n        \"label\": \"mysql\",\n        \"provider\": \"mysql-core\",\n        \"token\": \"mysql-token-guid\"\n      }\n    },\n    {\n      \"metadata\": {\n        \"guid\": \"postgres-core-guid\"\n      },\n      \"entity\": {\n        \"label\": \"postgres\",\n        \"provider\": \"postgres-core\"\n      }\n    }\n  ]\n}`},\n)\n\nfunc TestFindAll(t *testing.T) {\n\tfindAllStatus.Reset()\n\tts, repo := createServiceAuthTokenRepo(findAllServiceAuthTokensEndpoint)\n\tdefer ts.Close()\n\n\tauthTokens, apiResponse := repo.FindAll()\n\tassert.True(t, findAllStatus.Called())\n\tassert.True(t, apiResponse.IsSuccessful())\n\n\tassert.Equal(t, len(authTokens), 2)\n\n\tassert.Equal(t, authTokens[0].Label, \"mysql\")\n\tassert.Equal(t, authTokens[0].Provider, \"mysql-core\")\n\tassert.Equal(t, authTokens[0].Guid, \"mysql-core-guid\")\n\n\tassert.Equal(t, authTokens[1].Label, \"postgres\")\n\tassert.Equal(t, authTokens[1].Provider, \"postgres-core\")\n\tassert.Equal(t, authTokens[1].Guid, \"postgres-core-guid\")\n}\n\nfunc createServiceAuthTokenRepo(endpoint http.HandlerFunc) (ts *httptest.Server, repo ServiceAuthTokenRepository) {\n\tts = httptest.NewTLSServer(endpoint)\n\n\tconfig := &configuration.Configuration{\n\t\tTarget:      ts.URL,\n\t\tAccessToken: \"BEARER my_access_token\",\n\t}\n\tgateway := net.NewCloudControllerGateway()\n\n\trepo = NewCloudControllerServiceAuthTokenRepository(config, gateway)\n\treturn\n}\n\nvar updateServiceAuthTokenEndpoint, updateStatus = testhelpers.CreateCheckableEndpoint(\n\t\"PUT\",\n\t\"\/v2\/service_auth_tokens\/mysql-core-guid\",\n\ttesthelpers.RequestBodyMatcher(`{\"token\":\"a value\"}`),\n\ttesthelpers.TestResponse{Status: http.StatusCreated},\n)\n\nvar servicesEndpoints = http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\tif strings.Contains(request.Method, \"PUT\") {\n\t\tupdateServiceAuthTokenEndpoint(writer, request)\n\t} else {\n\t\tfindAllServiceAuthTokensEndpoint(writer, request)\n\t}\n})\n\nfunc TestServiceAuthUpdate(t *testing.T) {\n\tupdateStatus.Reset()\n\tfindAllStatus.Reset()\n\n\tts := httptest.NewTLSServer(servicesEndpoints)\n\tdefer ts.Close()\n\n\tconfig := &configuration.Configuration{\n\t\tTarget:      ts.URL,\n\t\tAccessToken: \"BEARER my_access_token\",\n\t}\n\tgateway := net.NewCloudControllerGateway()\n\n\trepo := NewCloudControllerServiceAuthTokenRepository(config, gateway)\n\tapiResponse := repo.Update(cf.ServiceAuthToken{\n\t\tLabel:    \"mysql\",\n\t\tProvider: \"mysql-core\",\n\t\tToken:    \"a value\",\n\t})\n\n\tassert.True(t, findAllStatus.Called())\n\tassert.True(t, updateStatus.Called())\n\tassert.True(t, apiResponse.IsSuccessful())\n}\n<commit_msg>Updated service auth repository tests<commit_after>package api_test\n\nimport (\n\t\"cf\"\n\t. \"cf\/api\"\n\t\"cf\/configuration\"\n\t\"cf\/net\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"strings\"\n\t\"testhelpers\"\n\t\"testing\"\n)\n\nfunc TestCreate(t *testing.T) {\n\tendpoint, status := testhelpers.CreateCheckableEndpoint(\n\t\t\"POST\",\n\t\t\"\/v2\/service_auth_tokens\",\n\t\ttesthelpers.RequestBodyMatcher(`{\"label\":\"a label\",\"provider\":\"a provider\",\"token\":\"a token\"}`),\n\t\ttesthelpers.TestResponse{Status: http.StatusCreated},\n\t)\n\n\tts, repo := createServiceAuthTokenRepo(endpoint)\n\tdefer ts.Close()\n\n\tapiResponse := repo.Create(cf.ServiceAuthToken{Label: \"a label\", Provider: \"a provider\", Token: \"a token\"})\n\n\tassert.True(t, status.Called())\n\tassert.True(t, apiResponse.IsSuccessful())\n}\n\nvar findAllServiceAuthTokensEndpoint, findAllStatus = testhelpers.CreateCheckableEndpoint(\n\t\"GET\",\n\t\"\/v2\/service_auth_tokens\",\n\tnil,\n\ttesthelpers.TestResponse{Status: http.StatusOK, Body: `\n{\n  \"resources\": [\n    {\n      \"metadata\": {\n        \"guid\": \"mysql-core-guid\"\n      },\n      \"entity\": {\n        \"label\": \"mysql\",\n        \"provider\": \"mysql-core\",\n        \"token\": \"mysql-token-guid\"\n      }\n    },\n    {\n      \"metadata\": {\n        \"guid\": \"postgres-core-guid\"\n      },\n      \"entity\": {\n        \"label\": \"postgres\",\n        \"provider\": \"postgres-core\"\n      }\n    }\n  ]\n}`},\n)\n\nfunc TestFindAll(t *testing.T) {\n\tfindAllStatus.Reset()\n\tts, repo := createServiceAuthTokenRepo(findAllServiceAuthTokensEndpoint)\n\tdefer ts.Close()\n\n\tauthTokens, apiResponse := repo.FindAll()\n\tassert.True(t, findAllStatus.Called())\n\tassert.True(t, apiResponse.IsSuccessful())\n\n\tassert.Equal(t, len(authTokens), 2)\n\n\tassert.Equal(t, authTokens[0].Label, \"mysql\")\n\tassert.Equal(t, authTokens[0].Provider, \"mysql-core\")\n\tassert.Equal(t, authTokens[0].Guid, \"mysql-core-guid\")\n\n\tassert.Equal(t, authTokens[1].Label, \"postgres\")\n\tassert.Equal(t, authTokens[1].Provider, \"postgres-core\")\n\tassert.Equal(t, authTokens[1].Guid, \"postgres-core-guid\")\n}\n\nvar updateServiceAuthTokenEndpoint, updateStatus = testhelpers.CreateCheckableEndpoint(\n\t\"PUT\",\n\t\"\/v2\/service_auth_tokens\/mysql-core-guid\",\n\ttesthelpers.RequestBodyMatcher(`{\"token\":\"a value\"}`),\n\ttesthelpers.TestResponse{Status: http.StatusCreated},\n)\n\nfunc TestServiceAuthUpdate(t *testing.T) {\n\tservicesEndpoints := http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\tif strings.Contains(request.Method, \"PUT\") {\n\t\t\tupdateServiceAuthTokenEndpoint(writer, request)\n\t\t} else {\n\t\t\tfindAllServiceAuthTokensEndpoint(writer, request)\n\t\t}\n\t})\n\tupdateStatus.Reset()\n\tfindAllStatus.Reset()\n\n\tts, repo := createServiceAuthTokenRepo(servicesEndpoints)\n\tdefer ts.Close()\n\n\tapiResponse := repo.Update(cf.ServiceAuthToken{\n\t\tLabel:    \"mysql\",\n\t\tProvider: \"mysql-core\",\n\t\tToken:    \"a value\",\n\t})\n\n\tassert.True(t, findAllStatus.Called())\n\tassert.True(t, updateStatus.Called())\n\tassert.True(t, apiResponse.IsSuccessful())\n}\n\nfunc createServiceAuthTokenRepo(endpoint http.HandlerFunc) (ts *httptest.Server, repo ServiceAuthTokenRepository) {\n\tts = httptest.NewTLSServer(endpoint)\n\n\tconfig := &configuration.Configuration{\n\t\tTarget:      ts.URL,\n\t\tAccessToken: \"BEARER my_access_token\",\n\t}\n\tgateway := net.NewCloudControllerGateway()\n\n\trepo = NewCloudControllerServiceAuthTokenRepository(config, gateway)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package deploy\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/remind101\/deploy\/Godeps\/_workspace\/src\/github.com\/codegangsta\/cli\"\n\t\"github.com\/remind101\/deploy\/Godeps\/_workspace\/src\/github.com\/github\/hub\/git\"\n\thub \"github.com\/remind101\/deploy\/Godeps\/_workspace\/src\/github.com\/github\/hub\/github\"\n\t\"github.com\/remind101\/deploy\/Godeps\/_workspace\/src\/github.com\/google\/go-github\/github\"\n)\n\nconst (\n\tName  = \"deploy\"\n\tUsage = \"A command for creating GitHub deployments\"\n)\n\nconst DefaultRef = \"master\"\n\nfunc init() {\n\tcli.AppHelpTemplate = `USAGE:\n   # Deploy the master branch of remind101\/acme-inc to staging\n   {{.Name}} -env=staging -ref=master remind101\/acme-inc\n\n   # Deploy HEAD of the current branch to staging\n   {{.Name}} -env=staging remind101\/acme-inc\n\n   # Deploy the current GitHub repo to staging\n   {{.Name}} -env=staging\n{{if .Flags}}\nOPTIONS:\n   {{range .Flags}}{{.}}\n   {{end}}{{end}}\n`\n}\n\nvar flags = []cli.Flag{\n\tcli.StringFlag{\n\t\tName:  \"ref, branch, commit, tag\",\n\t\tValue: \"\",\n\t\tUsage: \"The git ref to deploy. Can be a git commit, branch or tag.\",\n\t},\n\tcli.StringFlag{\n\t\tName:  \"env, e\",\n\t\tValue: \"\",\n\t\tUsage: \"The environment to deploy to.\",\n\t},\n\tcli.BoolFlag{\n\t\tName:  \"force, f\",\n\t\tUsage: \"Ignore failed tests.\",\n\t},\n}\n\n\/\/ NewApp returns a new cli.App for the deploy command.\nfunc NewApp() *cli.App {\n\tapp := cli.NewApp()\n\tapp.Version = \"0.0.1\"\n\tapp.Name = Name\n\tapp.Usage = Usage\n\tapp.Flags = flags\n\tapp.Action = func(c *cli.Context) {\n\t\tif err := RunDeploy(c); err != nil {\n\t\t\tmsg := err.Error()\n\t\t\tif err, ok := err.(*github.ErrorResponse); ok {\n\t\t\t\tmsg = err.Message\n\t\t\t}\n\n\t\t\tfmt.Println(msg)\n\t\t\tos.Exit(-1)\n\t\t}\n\t}\n\n\treturn app\n}\n\n\/\/ RunDeploy performs a deploy.\nfunc RunDeploy(c *cli.Context) error {\n\tw := c.App.Writer\n\n\th, err := hub.CurrentConfig().PromptForHost(\"github.com\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient, err := newGitHubClient(h)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnwo, err := Repo(c.Args())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\towner, repo, err := SplitRepo(nwo)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Invalid GitHub repo: %s\", nwo)\n\t}\n\n\tr, err := newDeploymentRequest(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(w, \"Creating deployment request of %s@%s to %s... \", nwo, *r.Ref, *r.Environment)\n\n\td, _, err := client.Repositories.CreateDeployment(owner, repo, r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tch := make(chan *github.DeploymentStatus)\n\n\tgo func() {\n\t\tfor {\n\t\t\tstatuses, _, err := client.Repositories.ListDeploymentStatuses(owner, repo, *d.ID, nil)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif len(statuses) != 0 {\n\t\t\t\tch <- &statuses[0]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\ttimeout := time.Duration(20)\n\tselect {\n\tcase <-time.After(timeout * time.Second):\n\t\treturn fmt.Errorf(\"No deployment started after waiting %d seconds\\n\", timeout)\n\tcase status := <-ch:\n\t\tvar url string\n\t\tif status.TargetURL != nil {\n\t\t\turl = *status.TargetURL\n\t\t}\n\n\t\tfmt.Fprintf(w, \"%s\\n\", url)\n\t}\n\n\treturn nil\n}\n\nfunc newDeploymentRequest(c *cli.Context) (*github.DeploymentRequest, error) {\n\tref := c.String(\"ref\")\n\tif ref == \"\" {\n\t\tr, err := git.Ref(\"HEAD\")\n\t\tif err == nil {\n\t\t\tref = r\n\t\t} else {\n\t\t\tref = DefaultRef\n\t\t}\n\t}\n\n\tenv := c.String(\"env\")\n\tif env == \"\" {\n\t\treturn nil, fmt.Errorf(\"-env flag is required\")\n\t}\n\n\tvar contexts *[]string\n\tif c.Bool(\"force\") {\n\t\ts := []string{}\n\t\tcontexts = &s\n\t}\n\n\treturn &github.DeploymentRequest{\n\t\tRef:              github.String(ref),\n\t\tTask:             github.String(\"deploy\"),\n\t\tAutoMerge:        github.Bool(false),\n\t\tEnvironment:      github.String(env),\n\t\tRequiredContexts: contexts,\n\t\t\/\/ TODO Description:\n\t}, nil\n}\n\n\/\/ Repo will determine the correct GitHub repo to deploy to, based on a set of\n\/\/ arguments.\nfunc Repo(arguments []string) (string, error) {\n\tif len(arguments) != 0 {\n\t\treturn arguments[0], nil\n\t}\n\n\tremotes, err := hub.Remotes()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trepo := GitHubRepo(remotes)\n\tif repo == \"\" {\n\t\treturn repo, errors.New(\"no GitHub repo found in .git\/config\")\n\t}\n\n\treturn repo, nil\n}\n\n\/\/ A regular expression that can convert a URL.Path into a GitHub repo name.\nvar remoteRegex = regexp.MustCompile(`^\/(.*)\\.git$`)\n\n\/\/ GitHubRepo, given a list of git remotes, will determine what the GitHub repo\n\/\/ is.\nfunc GitHubRepo(remotes []hub.Remote) string {\n\t\/\/ We only want to look at the `origin` remote.\n\tremote := findRemote(\"origin\", remotes)\n\tif remote == nil {\n\t\treturn \"\"\n\t}\n\n\t\/\/ Remotes that are not pointed at a GitHub repo are not valid.\n\tif remote.URL.Host != \"github.com\" {\n\t\treturn \"\"\n\t}\n\n\t\/\/ Convert `\/remind101\/acme-inc.git` => `remind101\/acme-inc`.\n\treturn remoteRegex.ReplaceAllString(remote.URL.Path, \"$1\")\n}\n\nfunc findRemote(name string, remotes []hub.Remote) *hub.Remote {\n\tfor _, r := range remotes {\n\t\tif r.Name == name {\n\t\t\treturn &r\n\t\t}\n\t}\n\n\treturn nil\n}\n\nvar errInvalidRepo = errors.New(\"invalid repo\")\n\n\/\/ SplitRepo splits a repo string in the form remind101\/acme-inc into it's owner\n\/\/ and repo components.\nfunc SplitRepo(nwo string) (owner string, repo string, err error) {\n\tparts := strings.Split(nwo, \"\/\")\n\n\tif len(parts) != 2 {\n\t\terr = errInvalidRepo\n\t\treturn\n\t}\n\n\towner = parts[0]\n\trepo = parts[1]\n\n\treturn\n}\n<commit_msg>Wait for deployment to complete.<commit_after>package deploy\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/remind101\/deploy\/Godeps\/_workspace\/src\/github.com\/codegangsta\/cli\"\n\t\"github.com\/remind101\/deploy\/Godeps\/_workspace\/src\/github.com\/github\/hub\/git\"\n\thub \"github.com\/remind101\/deploy\/Godeps\/_workspace\/src\/github.com\/github\/hub\/github\"\n\t\"github.com\/remind101\/deploy\/Godeps\/_workspace\/src\/github.com\/google\/go-github\/github\"\n)\n\nconst (\n\tName  = \"deploy\"\n\tUsage = \"A command for creating GitHub deployments\"\n)\n\nconst DefaultRef = \"master\"\n\nfunc init() {\n\tcli.AppHelpTemplate = `USAGE:\n   # Deploy the master branch of remind101\/acme-inc to staging\n   {{.Name}} -env=staging -ref=master remind101\/acme-inc\n\n   # Deploy HEAD of the current branch to staging\n   {{.Name}} -env=staging remind101\/acme-inc\n\n   # Deploy the current GitHub repo to staging\n   {{.Name}} -env=staging\n{{if .Flags}}\nOPTIONS:\n   {{range .Flags}}{{.}}\n   {{end}}{{end}}\n`\n}\n\nvar flags = []cli.Flag{\n\tcli.StringFlag{\n\t\tName:  \"ref, branch, commit, tag\",\n\t\tValue: \"\",\n\t\tUsage: \"The git ref to deploy. Can be a git commit, branch or tag.\",\n\t},\n\tcli.StringFlag{\n\t\tName:  \"env, e\",\n\t\tValue: \"\",\n\t\tUsage: \"The environment to deploy to.\",\n\t},\n\tcli.BoolFlag{\n\t\tName:  \"force, f\",\n\t\tUsage: \"Ignore failed tests.\",\n\t},\n}\n\n\/\/ NewApp returns a new cli.App for the deploy command.\nfunc NewApp() *cli.App {\n\tapp := cli.NewApp()\n\tapp.Version = \"0.0.1\"\n\tapp.Name = Name\n\tapp.Usage = Usage\n\tapp.Flags = flags\n\tapp.Action = func(c *cli.Context) {\n\t\tif err := RunDeploy(c); err != nil {\n\t\t\tmsg := err.Error()\n\t\t\tif err, ok := err.(*github.ErrorResponse); ok {\n\t\t\t\tmsg = err.Message\n\t\t\t}\n\n\t\t\tfmt.Println(msg)\n\t\t\tos.Exit(-1)\n\t\t}\n\t}\n\n\treturn app\n}\n\n\/\/ RunDeploy performs a deploy.\nfunc RunDeploy(c *cli.Context) error {\n\tw := c.App.Writer\n\n\th, err := hub.CurrentConfig().PromptForHost(\"github.com\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient, err := newGitHubClient(h)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnwo, err := Repo(c.Args())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\towner, repo, err := SplitRepo(nwo)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Invalid GitHub repo: %s\", nwo)\n\t}\n\n\tr, err := newDeploymentRequest(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Fprintf(w, \"Creating deployment request of %s@%s to %s... \", nwo, *r.Ref, *r.Environment)\n\n\td, _, err := client.Repositories.CreateDeployment(owner, repo, r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tch := make(chan *github.DeploymentStatus)\n\n\tgo func() {\n\t\tfor {\n\t\t\tstatuses, _, err := client.Repositories.ListDeploymentStatuses(owner, repo, *d.ID, nil)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcompleted := CompletedStatus(statuses)\n\t\t\tif completed != nil {\n\t\t\t\tch <- completed\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\tstatus := <-ch\n\n\tvar url string\n\tif status.TargetURL != nil {\n\t\turl = *status.TargetURL\n\t}\n\n\tstate := \"unkown\"\n\tif status.State != nil {\n\t\tstate = *status.State\n\t}\n\n\tfmt.Fprintf(w, \"%s: %s\\n\", state, url)\n\n\treturn nil\n}\n\nfunc newDeploymentRequest(c *cli.Context) (*github.DeploymentRequest, error) {\n\tref := c.String(\"ref\")\n\tif ref == \"\" {\n\t\tr, err := git.Ref(\"HEAD\")\n\t\tif err == nil {\n\t\t\tref = r\n\t\t} else {\n\t\t\tref = DefaultRef\n\t\t}\n\t}\n\n\tenv := c.String(\"env\")\n\tif env == \"\" {\n\t\treturn nil, fmt.Errorf(\"-env flag is required\")\n\t}\n\n\tvar contexts *[]string\n\tif c.Bool(\"force\") {\n\t\ts := []string{}\n\t\tcontexts = &s\n\t}\n\n\treturn &github.DeploymentRequest{\n\t\tRef:              github.String(ref),\n\t\tTask:             github.String(\"deploy\"),\n\t\tAutoMerge:        github.Bool(false),\n\t\tEnvironment:      github.String(env),\n\t\tRequiredContexts: contexts,\n\t\t\/\/ TODO Description:\n\t}, nil\n}\n\nvar completedStatuses = []string{\"success\", \"error\", \"failure\"}\n\n\/\/ CompletedStatus takes a slice of github.DeploymentStatus and returns the\n\/\/ first \"completed\" status. nil is returned if there are no completed\n\/\/ deployment states.\nfunc CompletedStatus(statuses []github.DeploymentStatus) *github.DeploymentStatus {\n\tfor _, ds := range statuses {\n\t\tfor _, s := range completedStatuses {\n\t\t\tif ds.State != nil && *ds.State == s {\n\t\t\t\treturn &ds\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Repo will determine the correct GitHub repo to deploy to, based on a set of\n\/\/ arguments.\nfunc Repo(arguments []string) (string, error) {\n\tif len(arguments) != 0 {\n\t\treturn arguments[0], nil\n\t}\n\n\tremotes, err := hub.Remotes()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trepo := GitHubRepo(remotes)\n\tif repo == \"\" {\n\t\treturn repo, errors.New(\"no GitHub repo found in .git\/config\")\n\t}\n\n\treturn repo, nil\n}\n\n\/\/ A regular expression that can convert a URL.Path into a GitHub repo name.\nvar remoteRegex = regexp.MustCompile(`^\/(.*)\\.git$`)\n\n\/\/ GitHubRepo, given a list of git remotes, will determine what the GitHub repo\n\/\/ is.\nfunc GitHubRepo(remotes []hub.Remote) string {\n\t\/\/ We only want to look at the `origin` remote.\n\tremote := findRemote(\"origin\", remotes)\n\tif remote == nil {\n\t\treturn \"\"\n\t}\n\n\t\/\/ Remotes that are not pointed at a GitHub repo are not valid.\n\tif remote.URL.Host != \"github.com\" {\n\t\treturn \"\"\n\t}\n\n\t\/\/ Convert `\/remind101\/acme-inc.git` => `remind101\/acme-inc`.\n\treturn remoteRegex.ReplaceAllString(remote.URL.Path, \"$1\")\n}\n\nfunc findRemote(name string, remotes []hub.Remote) *hub.Remote {\n\tfor _, r := range remotes {\n\t\tif r.Name == name {\n\t\t\treturn &r\n\t\t}\n\t}\n\n\treturn nil\n}\n\nvar errInvalidRepo = errors.New(\"invalid repo\")\n\n\/\/ SplitRepo splits a repo string in the form remind101\/acme-inc into it's owner\n\/\/ and repo components.\nfunc SplitRepo(nwo string) (owner string, repo string, err error) {\n\tparts := strings.Split(nwo, \"\/\")\n\n\tif len(parts) != 2 {\n\t\terr = errInvalidRepo\n\t\treturn\n\t}\n\n\towner = parts[0]\n\trepo = parts[1]\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package applications_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/helper\/resource\"\n\n\t\"github.com\/hashicorp\/terraform-provider-azuread\/internal\/acceptance\"\n\t\"github.com\/hashicorp\/terraform-provider-azuread\/internal\/acceptance\/check\"\n)\n\ntype ApplicationDataSource struct{}\n\nfunc TestAccApplicationDataSource_byObjectId(t *testing.T) {\n\tdata := acceptance.BuildTestData(t, \"data.azuread_application\", \"test\")\n\tr := ApplicationDataSource{}\n\n\tdata.DataSourceTest(t, []resource.TestStep{\n\t\t{\n\t\t\tConfig: r.objectId(data),\n\t\t\tCheck:  r.testCheck(data),\n\t\t},\n\t})\n}\n\nfunc TestAccApplicationDataSource_byApplicationId(t *testing.T) {\n\tdata := acceptance.BuildTestData(t, \"data.azuread_application\", \"test\")\n\tr := ApplicationDataSource{}\n\n\tdata.DataSourceTest(t, []resource.TestStep{\n\t\t{\n\t\t\tConfig: r.applicationId(data),\n\t\t\tCheck:  r.testCheck(data),\n\t\t},\n\t})\n}\n\nfunc TestAccApplicationDataSource_byDisplayName(t *testing.T) {\n\tdata := acceptance.BuildTestData(t, \"data.azuread_application\", \"test\")\n\tr := ApplicationDataSource{}\n\n\tdata.DataSourceTest(t, []resource.TestStep{\n\t\t{\n\t\t\tConfig: r.displayName(data),\n\t\t\tCheck:  r.testCheck(data),\n\t\t},\n\t})\n}\n\nfunc (ApplicationDataSource) testCheck(data acceptance.TestData) resource.TestCheckFunc {\n\treturn resource.ComposeTestCheckFunc(\n\t\tcheck.That(data.ResourceName).Key(\"application_id\").IsUuid(),\n\t\tcheck.That(data.ResourceName).Key(\"object_id\").IsUuid(),\n\t\tcheck.That(data.ResourceName).Key(\"api.0.oauth2_permission_scopes.#\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"app_roles.#\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"app_role_ids.%\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"display_name\").HasValue(fmt.Sprintf(\"acctest-APP-complete-%d\", data.RandomInteger)),\n\t\tcheck.That(data.ResourceName).Key(\"group_membership_claims.#\").HasValue(\"1\"),\n\t\tcheck.That(data.ResourceName).Key(\"group_membership_claims.0\").HasValue(\"All\"),\n\t\tcheck.That(data.ResourceName).Key(\"identifier_uris.#\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"oauth2_permission_scope_ids.%\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"optional_claims.#\").HasValue(\"1\"),\n\t\tcheck.That(data.ResourceName).Key(\"optional_claims.0.access_token.#\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"optional_claims.0.id_token.#\").HasValue(\"1\"),\n\t\tcheck.That(data.ResourceName).Key(\"required_resource_access.#\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"sign_in_audience\").HasValue(\"AzureADandPersonalMicrosoftAccount\"),\n\t\tcheck.That(data.ResourceName).Key(\"web.0.homepage_url\").HasValue(fmt.Sprintf(\"https:\/\/app.hashitown-%d.com\/\", data.RandomInteger)),\n\t\tcheck.That(data.ResourceName).Key(\"web.0.logout_url\").HasValue(fmt.Sprintf(\"https:\/\/app.hashitown-%[1]d.com\/logout\", data.RandomInteger)),\n\t\tcheck.That(data.ResourceName).Key(\"web.0.redirect_uris.#\").HasValue(\"2\"),\n\t)\n}\n\nfunc (ApplicationDataSource) objectId(data acceptance.TestData) string {\n\treturn fmt.Sprintf(`\n%[1]s\n\ndata \"azuread_application\" \"test\" {\n  object_id = azuread_application.test.object_id\n}\n`, ApplicationResource{}.complete(data))\n}\n\nfunc (ApplicationDataSource) applicationId(data acceptance.TestData) string {\n\treturn fmt.Sprintf(`\n%[1]s\n\ndata \"azuread_application\" \"test\" {\n  application_id = upper(azuread_application.test.application_id)\n}\n`, ApplicationResource{}.complete(data))\n}\n\nfunc (ApplicationDataSource) displayName(data acceptance.TestData) string {\n\treturn fmt.Sprintf(`\n%[1]s\n\ndata \"azuread_application\" \"test\" {\n  display_name = upper(azuread_application.test.display_name)\n}\n`, ApplicationResource{}.complete(data))\n}\n<commit_msg>Fix application data source test<commit_after>package applications_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/helper\/resource\"\n\n\t\"github.com\/hashicorp\/terraform-provider-azuread\/internal\/acceptance\"\n\t\"github.com\/hashicorp\/terraform-provider-azuread\/internal\/acceptance\/check\"\n)\n\ntype ApplicationDataSource struct{}\n\nfunc TestAccApplicationDataSource_byObjectId(t *testing.T) {\n\tdata := acceptance.BuildTestData(t, \"data.azuread_application\", \"test\")\n\tr := ApplicationDataSource{}\n\n\tdata.DataSourceTest(t, []resource.TestStep{\n\t\t{\n\t\t\tConfig: r.objectId(data),\n\t\t\tCheck:  r.testCheck(data),\n\t\t},\n\t})\n}\n\nfunc TestAccApplicationDataSource_byApplicationId(t *testing.T) {\n\tdata := acceptance.BuildTestData(t, \"data.azuread_application\", \"test\")\n\tr := ApplicationDataSource{}\n\n\tdata.DataSourceTest(t, []resource.TestStep{\n\t\t{\n\t\t\tConfig: r.applicationId(data),\n\t\t\tCheck:  r.testCheck(data),\n\t\t},\n\t})\n}\n\nfunc TestAccApplicationDataSource_byDisplayName(t *testing.T) {\n\tdata := acceptance.BuildTestData(t, \"data.azuread_application\", \"test\")\n\tr := ApplicationDataSource{}\n\n\tdata.DataSourceTest(t, []resource.TestStep{\n\t\t{\n\t\t\tConfig: r.displayName(data),\n\t\t\tCheck:  r.testCheck(data),\n\t\t},\n\t})\n}\n\nfunc (ApplicationDataSource) testCheck(data acceptance.TestData) resource.TestCheckFunc {\n\treturn resource.ComposeTestCheckFunc(\n\t\tcheck.That(data.ResourceName).Key(\"application_id\").IsUuid(),\n\t\tcheck.That(data.ResourceName).Key(\"object_id\").IsUuid(),\n\t\tcheck.That(data.ResourceName).Key(\"api.0.oauth2_permission_scopes.#\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"app_roles.#\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"app_role_ids.%\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"display_name\").HasValue(fmt.Sprintf(\"acctest-APP-complete-%d\", data.RandomInteger)),\n\t\tcheck.That(data.ResourceName).Key(\"group_membership_claims.#\").HasValue(\"1\"),\n\t\tcheck.That(data.ResourceName).Key(\"group_membership_claims.0\").HasValue(\"All\"),\n\t\tcheck.That(data.ResourceName).Key(\"identifier_uris.#\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"oauth2_permission_scope_ids.%\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"optional_claims.#\").HasValue(\"1\"),\n\t\tcheck.That(data.ResourceName).Key(\"optional_claims.0.access_token.#\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"optional_claims.0.id_token.#\").HasValue(\"1\"),\n\t\tcheck.That(data.ResourceName).Key(\"required_resource_access.#\").HasValue(\"2\"),\n\t\tcheck.That(data.ResourceName).Key(\"sign_in_audience\").HasValue(\"AzureADandPersonalMicrosoftAccount\"),\n\t\tcheck.That(data.ResourceName).Key(\"web.0.homepage_url\").HasValue(fmt.Sprintf(\"https:\/\/app.hashitown-%d.com\/\", data.RandomInteger)),\n\t\tcheck.That(data.ResourceName).Key(\"web.0.logout_url\").HasValue(fmt.Sprintf(\"https:\/\/app.hashitown-%[1]d.com\/logout\", data.RandomInteger)),\n\t\tcheck.That(data.ResourceName).Key(\"web.0.redirect_uris.#\").HasValue(\"3\"),\n\t)\n}\n\nfunc (ApplicationDataSource) objectId(data acceptance.TestData) string {\n\treturn fmt.Sprintf(`\n%[1]s\n\ndata \"azuread_application\" \"test\" {\n  object_id = azuread_application.test.object_id\n}\n`, ApplicationResource{}.complete(data))\n}\n\nfunc (ApplicationDataSource) applicationId(data acceptance.TestData) string {\n\treturn fmt.Sprintf(`\n%[1]s\n\ndata \"azuread_application\" \"test\" {\n  application_id = upper(azuread_application.test.application_id)\n}\n`, ApplicationResource{}.complete(data))\n}\n\nfunc (ApplicationDataSource) displayName(data acceptance.TestData) string {\n\treturn fmt.Sprintf(`\n%[1]s\n\ndata \"azuread_application\" \"test\" {\n  display_name = upper(azuread_application.test.display_name)\n}\n`, ApplicationResource{}.complete(data))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017, 2019, Oracle and\/or its affiliates. All rights reserved.\n\npackage oci\n\nimport (\n\t\"log\"\n)\n\nconst Version = \"3.77.0\"\n\nfunc PrintVersion() {\n\tlog.Printf(\"[INFO] terraform-provider-oci %s\\n\", Version)\n}\n<commit_msg>Update version to 3.78.0 due to adding a new fix.<commit_after>\/\/ Copyright (c) 2017, 2019, Oracle and\/or its affiliates. All rights reserved.\n\npackage oci\n\nimport (\n\t\"log\"\n)\n\nconst Version = \"3.78.0\"\n\nfunc PrintVersion() {\n\tlog.Printf(\"[INFO] terraform-provider-oci %s\\n\", Version)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 ~ 2018 AlexStocks(https:\/\/github.com\/AlexStocks).\n\/\/ All rights reserved.  Use of this source code is\n\/\/ governed by Apache License 2.0.\n\n\/\/ Package gxerrgroup implements an actor-runner with deterministic teardown. It is\n\/\/ somewhat similar to package errgroup, except it does not require actor\n\/\/ goroutines to understand context semantics. This makes it suitable for use in\n\/\/ more circumstances; for example, goroutines which are handling connections\n\/\/ from net.Listeners, or scanning input from a closable io.Reader.\n\/\/\n\/\/ refers to github.com\/oklog\/run\npackage gxerrgroup\n\nimport (\n\t\"github.com\/AlexStocks\/goext\/runtime\"\n\t\"time\"\n)\n\n\/\/ Group collects actors (functions) and runs them concurrently.\n\/\/ When one actor (function) returns, all actors are interrupted.\n\/\/ The zero value of a Group is useful.\ntype Group struct {\n\tactors []actor\n\tpool   *gxruntime.Pool\n}\n\ntype actor struct {\n\texecute   func() error\n\tinterrupt func(error)\n}\n\n\/\/ NewGroup initialize a Group instance which will create a goroutine pool.\n\/\/ idleTimeout is a goroutine's max idle time interval.\nfunc NewGroup(idleTimeout time.Duration) *Group {\n\treturn &Group{\n\t\tactors: make([]actor, 0, 16),\n\t\tpool:   gxruntime.NewGoroutinePool(idleTimeout),\n\t}\n}\n\nfunc (g *Group) Close() {\n\tg.pool.Close()\n}\n\n\/\/ Add an actor (function) to the group. Each actor must be pre-emptable by an\n\/\/ interrupt function. That is, if interrupt is invoked, execute should return.\n\/\/ Also, it must be safe to call interrupt even after execute has returned.\n\/\/\n\/\/ The first actor (function) to return interrupts all running actors.\n\/\/ The error is passed to the interrupt functions, and is returned by Run.\nfunc (g *Group) Add(execute func() error, interrupt func(error)) {\n\tg.actors = append(g.actors, actor{execute, interrupt})\n}\n\n\/\/ Run all actors (functions) concurrently.\n\/\/ When the first actor returns, all others are interrupted.\n\/\/ Run only returns when all actors have exited.\n\/\/ Run returns the error returned by the first exiting actor.\nfunc (g *Group) Run() error {\n\tif len(g.actors) == 0 {\n\t\treturn nil\n\t}\n\n\t\/\/ Run each actor.\n\terrors := make(chan error, len(g.actors))\n\tfor idx := range g.actors {\n\t\ti := idx\n\t\ta := g.actors[i]\n\t\tg.pool.Go(func() {\n\t\t\terrors <- a.execute()\n\t\t})\n\t\t\/\/go func(a actor) {\n\t\t\/\/\tfmt.Printf(\"a:%+v\\n\", a)\n\t\t\/\/\terrors <- a.execute()\n\t\t\/\/}(a)\n\t}\n\n\t\/\/ Wait for the first actor to stop.\n\terr := <-errors\n\n\t\/\/ Signal all actors to stop.\n\tfor _, a := range g.actors {\n\t\ta.interrupt(err)\n\t}\n\n\t\/\/ Wait for all actors to stop.\n\tfor i := 1; i < cap(errors); i++ {\n\t\t<-errors\n\t}\n\n\t\/\/ Return the original error.\n\treturn err\n}\n<commit_msg>Mod: import package format<commit_after>\/\/ Copyright 2016 ~ 2018 AlexStocks(https:\/\/github.com\/AlexStocks).\n\/\/ All rights reserved.  Use of this source code is\n\/\/ governed by Apache License 2.0.\n\n\/\/ Package gxerrgroup implements an actor-runner with deterministic teardown. It is\n\/\/ somewhat similar to package errgroup, except it does not require actor\n\/\/ goroutines to understand context semantics. This makes it suitable for use in\n\/\/ more circumstances; for example, goroutines which are handling connections\n\/\/ from net.Listeners, or scanning input from a closable io.Reader.\n\/\/\n\/\/ refers to github.com\/oklog\/run\npackage gxerrgroup\n\nimport (\n\t\"time\"\n)\n\nimport (\n\t\"github.com\/AlexStocks\/goext\/runtime\"\n)\n\n\/\/ Group collects actors (functions) and runs them concurrently.\n\/\/ When one actor (function) returns, all actors are interrupted.\n\/\/ The zero value of a Group is useful.\ntype Group struct {\n\tactors []actor\n\tpool   *gxruntime.Pool\n}\n\ntype actor struct {\n\texecute   func() error\n\tinterrupt func(error)\n}\n\n\/\/ NewGroup initialize a Group instance which will create a goroutine pool.\n\/\/ idleTimeout is a goroutine's max idle time interval.\nfunc NewGroup(idleTimeout time.Duration) *Group {\n\treturn &Group{\n\t\tactors: make([]actor, 0, 16),\n\t\tpool:   gxruntime.NewGoroutinePool(idleTimeout),\n\t}\n}\n\nfunc (g *Group) Close() {\n\tg.pool.Close()\n}\n\n\/\/ Add an actor (function) to the group. Each actor must be pre-emptable by an\n\/\/ interrupt function. That is, if interrupt is invoked, execute should return.\n\/\/ Also, it must be safe to call interrupt even after execute has returned.\n\/\/\n\/\/ The first actor (function) to return interrupts all running actors.\n\/\/ The error is passed to the interrupt functions, and is returned by Run.\nfunc (g *Group) Add(execute func() error, interrupt func(error)) {\n\tg.actors = append(g.actors, actor{execute, interrupt})\n}\n\n\/\/ Run all actors (functions) concurrently.\n\/\/ When the first actor returns, all others are interrupted.\n\/\/ Run only returns when all actors have exited.\n\/\/ Run returns the error returned by the first exiting actor.\nfunc (g *Group) Run() error {\n\tif len(g.actors) == 0 {\n\t\treturn nil\n\t}\n\n\t\/\/ Run each actor.\n\terrors := make(chan error, len(g.actors))\n\tfor idx := range g.actors {\n\t\ti := idx\n\t\ta := g.actors[i]\n\t\tg.pool.Go(func() {\n\t\t\terrors <- a.execute()\n\t\t})\n\t\t\/\/go func(a actor) {\n\t\t\/\/\tfmt.Printf(\"a:%+v\\n\", a)\n\t\t\/\/\terrors <- a.execute()\n\t\t\/\/}(a)\n\t}\n\n\t\/\/ Wait for the first actor to stop.\n\terr := <-errors\n\n\t\/\/ Signal all actors to stop.\n\tfor _, a := range g.actors {\n\t\ta.interrupt(err)\n\t}\n\n\t\/\/ Wait for all actors to stop.\n\tfor i := 1; i < cap(errors); i++ {\n\t\t<-errors\n\t}\n\n\t\/\/ Return the original error.\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package record\n\n\/\/ \/CdsXSnhGV0TQ9B3VZ9IneNK4vk+K9k+\n\nimport (\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"github.com\/revel\/revel\"\n\t\"io\/ioutil\"\n\t\"replay\/app\/models\/history\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar platformURLs map[string]string = map[string]string{\n\t\"NA1\":  \"http:\/\/spectator.na.lol.riotgames.com:80\",\n\t\"OC1\":  \"http:\/\/spectator.oc1.lol.riotgames.com:80\",\n\t\"EUN1\": \"http:\/\/spectator.eu.lol.riotgames.com:8088\",\n\t\"EUW1\": \"http:\/\/spectator.euw1.lol.riotgames.com:80\",\n}\n\nvar version string \/\/ Version functions in getters.go\nvar recording map[string]map[string]string = make(map[string]map[string]string)\n\nfunc writeRecording(region, gameId, key string, value []byte) {\n\tcurrentRecording := recording[region+\":\"+gameId]\n\tcurrentRecording[key] = base64.URLEncoding.EncodeToString(value)\n\trecording[region+\":\"+gameId] = currentRecording\n}\n\nfunc writeString(region, gameId, key string, value string) {\n\tcurrentRecording := recording[region+\":\"+gameId]\n\tcurrentRecording[key] = value\n\trecording[region+\":\"+gameId] = currentRecording\n}\n\nfunc existsRecording(region, gameId, key string) bool {\n\tif _, exists := recording[region+\":\"+gameId][key]; exists {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc writeLastChunkInfo(region, gameId string,\n\tfirstChunk, firstKeyFrame int, chunk ChunkInfo) {\n\n\twriteChunk := ChunkInfo{\n\t\tNextChunk:       firstChunk,\n\t\tCurrentChunk:    firstChunk,\n\t\tNextUpdate:      3000,\n\t\tStartGameChunk:  chunk.StartGameChunk,\n\t\tCurrentKeyFrame: firstKeyFrame,\n\t\tEndGameChunk:    chunk.CurrentChunk,\n\t\tAvailableSince:  0,\n\t\tDuration:        3000,\n\t\tEndStartupChunk: chunk.EndStartupChunk,\n\t}\n\n\tresult, err := json.Marshal(writeChunk)\n\tif err != nil {\n\t\tpanic(\"Error while encoding first chunk data json?!??!??\")\n\t}\n\n\twriteRecording(region, gameId, \"firstChunkData\", result)\n\n\twriteChunk.NextChunk = chunk.CurrentChunk\n\twriteChunk.CurrentChunk = chunk.CurrentChunk\n\twriteChunk.CurrentKeyFrame = chunk.CurrentKeyFrame\n\n\tresult, err = json.Marshal(writeChunk)\n\tif err != nil {\n\t\tpanic(\"Error while encoding last chunk data json?!??!??\")\n\t}\n\n\twriteRecording(region, gameId, \"lastChunkData\", result)\n\twriteString(region, gameId, \"firstChunkNumber\", strconv.Itoa(firstChunk))\n}\n\nfunc saveRecording(region, gameId string) {\n\tsavePath := revel.BasePath + \"\/replays\/\" + region + \"-\" + gameId\n\n\tresult, err := json.Marshal(recording[region+\":\"+gameId])\n\tif err != nil {\n\t\tpanic(\"Error while encoding recording json?!?!?!?\")\n\t}\n\n\terr = ioutil.WriteFile(savePath, result, 0644)\n\tif err != nil {\n\t\trevel.ERROR.Println(\"Error saving recording!\")\n\t}\n}\n\nfunc recordMetadata(region, gameId string) {\n\tmetadata := getMetadata(region, gameId)\n\n\tfor {\n\t\tchunk := getLastChunkInfo(region, gameId)\n\t\tif chunk.CurrentChunk > metadata.StartupChunk {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Duration(chunk.NextUpdate)*time.Millisecond +\n\t\t\ttime.Second)\n\t}\n\n\tmetadata = getMetadata(region, gameId)\n\n\t\/\/ Get the startup frames\n\tfor i := 1; i <= metadata.StartupChunk+1; i++ {\n\t\t\/\/ revel.INFO.Println(\"Getting startup chunk:\", i)\n\t\tfor {\n\t\t\tchunk := getLastChunkInfo(region, gameId)\n\t\t\tif i > chunk.CurrentChunk {\n\t\t\t\ttime.Sleep(time.Duration(chunk.NextUpdate)*time.Millisecond +\n\t\t\t\t\ttime.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgetChunkFrame(region, gameId, strconv.Itoa(i))\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc recordFrames(region, gameId string) {\n\tfirstChunk := 0\n\tfirstKeyFrame := 0\n\tlastChunk := 0\n\tlastKeyFrame := 0\n\n\tfor {\n\t\tchunk := getLastChunkInfo(region, gameId)\n\n\t\tif firstChunk == 0 {\n\t\t\tif chunk.CurrentChunk > chunk.StartGameChunk {\n\t\t\t\tfirstChunk = chunk.CurrentChunk\n\t\t\t} else {\n\t\t\t\tfirstChunk = chunk.StartGameChunk\n\t\t\t}\n\n\t\t\tif chunk.CurrentKeyFrame > 0 {\n\t\t\t\tfirstKeyFrame = chunk.CurrentKeyFrame\n\t\t\t} else {\n\t\t\t\tfirstKeyFrame = 1\n\t\t\t}\n\n\t\t\tlastChunk = chunk.CurrentChunk\n\t\t\tlastKeyFrame = chunk.CurrentKeyFrame\n\t\t}\n\n\t\tif chunk.CurrentChunk > lastChunk {\n\t\t\tfor i := lastChunk + 1; i <= chunk.CurrentChunk; i++ {\n\t\t\t\tgetChunkFrame(region, gameId, strconv.Itoa(i))\n\t\t\t}\n\t\t}\n\n\t\tif chunk.NextChunk < chunk.CurrentChunk && chunk.NextChunk > 0 {\n\t\t\tgetChunkFrame(region, gameId, strconv.Itoa(chunk.NextChunk))\n\t\t}\n\n\t\tif chunk.CurrentKeyFrame > lastKeyFrame {\n\t\t\tfor i := lastKeyFrame + 1; i <= chunk.CurrentKeyFrame; i++ {\n\t\t\t\tgetKeyFrame(region, gameId, strconv.Itoa(chunk.CurrentKeyFrame))\n\t\t\t}\n\t\t}\n\n\t\twriteLastChunkInfo(region, gameId, firstChunk, firstKeyFrame, chunk)\n\t\tsaveRecording(region, gameId)\n\n\t\tlastChunk = chunk.CurrentChunk\n\t\tlastKeyFrame = chunk.CurrentKeyFrame\n\n\t\tif chunk.EndGameChunk == chunk.CurrentChunk {\n\t\t\treturn\n\t\t}\n\n\t\ttime.Sleep(time.Duration(chunk.NextUpdate)*time.Millisecond +\n\t\t\ttime.Second)\n\t}\n}\n\nfunc asyncRecord(region, gameId, encryptionKey string) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\trevel.ERROR.Println(\"Error while recording game ID: \" + gameId)\n\t\t\trevel.ERROR.Println(r)\n\t\t\tdelete(recording, region+\":\"+gameId)\n\t\t}\n\t}()\n\n\twriteRecording(region, gameId, \"encryptionKey\", []byte(encryptionKey))\n\n\turl := platformURLs[region]\n\tUpdateVersion(url)\n\n\trevel.INFO.Println(\"Now recording: \" + region + \":\" + gameId)\n\trevel.INFO.Println(gameId + \"'s Encryption Key: \" + encryptionKey)\n\n\trecordMetadata(region, gameId)\n\trecordFrames(region, gameId)\n\n\trevel.INFO.Println(\"Recording complete for: \" + region + \":\" + gameId)\n\tdelete(recording, region+\":\"+gameId)\n}\n\nfunc Record(region, gameId, encryptionKey string) bool {\n\tif _, ok := recording[region+\":\"+gameId]; ok {\n\t\treturn false\n\t} else {\n\t\trecording[region+\":\"+gameId] = make(map[string]string)\n\t}\n\n\thistory.StoreGame(region, gameId, encryptionKey)\n\n\tgo asyncRecord(region, gameId, encryptionKey)\n\treturn true\n}\n<commit_msg>Fixed not recording first chunk\/frame<commit_after>package record\n\n\/\/ \/CdsXSnhGV0TQ9B3VZ9IneNK4vk+K9k+\n\nimport (\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"github.com\/revel\/revel\"\n\t\"io\/ioutil\"\n\t\"replay\/app\/models\/history\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar platformURLs map[string]string = map[string]string{\n\t\"NA1\":  \"http:\/\/spectator.na.lol.riotgames.com:80\",\n\t\"OC1\":  \"http:\/\/spectator.oc1.lol.riotgames.com:80\",\n\t\"EUN1\": \"http:\/\/spectator.eu.lol.riotgames.com:8088\",\n\t\"EUW1\": \"http:\/\/spectator.euw1.lol.riotgames.com:80\",\n}\n\nvar version string \/\/ Version functions in getters.go\nvar recording map[string]map[string]string = make(map[string]map[string]string)\n\nfunc writeRecording(region, gameId, key string, value []byte) {\n\tcurrentRecording := recording[region+\":\"+gameId]\n\tcurrentRecording[key] = base64.URLEncoding.EncodeToString(value)\n\trecording[region+\":\"+gameId] = currentRecording\n}\n\nfunc writeString(region, gameId, key string, value string) {\n\tcurrentRecording := recording[region+\":\"+gameId]\n\tcurrentRecording[key] = value\n\trecording[region+\":\"+gameId] = currentRecording\n}\n\nfunc existsRecording(region, gameId, key string) bool {\n\tif _, exists := recording[region+\":\"+gameId][key]; exists {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc writeLastChunkInfo(region, gameId string,\n\tfirstChunk, firstKeyFrame int, chunk ChunkInfo) {\n\n\twriteChunk := ChunkInfo{\n\t\tNextChunk:       firstChunk,\n\t\tCurrentChunk:    firstChunk,\n\t\tNextUpdate:      3000,\n\t\tStartGameChunk:  chunk.StartGameChunk,\n\t\tCurrentKeyFrame: firstKeyFrame,\n\t\tEndGameChunk:    chunk.CurrentChunk,\n\t\tAvailableSince:  0,\n\t\tDuration:        3000,\n\t\tEndStartupChunk: chunk.EndStartupChunk,\n\t}\n\n\tresult, err := json.Marshal(writeChunk)\n\tif err != nil {\n\t\tpanic(\"Error while encoding first chunk data json?!??!??\")\n\t}\n\n\twriteRecording(region, gameId, \"firstChunkData\", result)\n\n\twriteChunk.NextChunk = chunk.CurrentChunk\n\twriteChunk.CurrentChunk = chunk.CurrentChunk\n\twriteChunk.CurrentKeyFrame = chunk.CurrentKeyFrame\n\n\tresult, err = json.Marshal(writeChunk)\n\tif err != nil {\n\t\tpanic(\"Error while encoding last chunk data json?!??!??\")\n\t}\n\n\twriteRecording(region, gameId, \"lastChunkData\", result)\n\twriteString(region, gameId, \"firstChunkNumber\", strconv.Itoa(firstChunk))\n}\n\nfunc saveRecording(region, gameId string) {\n\tsavePath := revel.BasePath + \"\/replays\/\" + region + \"-\" + gameId\n\n\tresult, err := json.Marshal(recording[region+\":\"+gameId])\n\tif err != nil {\n\t\tpanic(\"Error while encoding recording json?!?!?!?\")\n\t}\n\n\terr = ioutil.WriteFile(savePath, result, 0644)\n\tif err != nil {\n\t\trevel.ERROR.Println(\"Error saving recording!\")\n\t}\n}\n\nfunc recordMetadata(region, gameId string) {\n\tmetadata := getMetadata(region, gameId)\n\n\tfor {\n\t\tchunk := getLastChunkInfo(region, gameId)\n\t\tif chunk.CurrentChunk > metadata.StartupChunk {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Duration(chunk.NextUpdate)*time.Millisecond +\n\t\t\ttime.Second)\n\t}\n\n\tmetadata = getMetadata(region, gameId)\n\n\t\/\/ Get the startup frames\n\tfor i := 1; i <= metadata.StartupChunk+1; i++ {\n\t\t\/\/ revel.INFO.Println(\"Getting startup chunk:\", i)\n\t\tfor {\n\t\t\tchunk := getLastChunkInfo(region, gameId)\n\t\t\tif i > chunk.CurrentChunk {\n\t\t\t\ttime.Sleep(time.Duration(chunk.NextUpdate)*time.Millisecond +\n\t\t\t\t\ttime.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgetChunkFrame(region, gameId, strconv.Itoa(i))\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc recordFrames(region, gameId string) {\n\tfirstChunk := 0\n\tfirstKeyFrame := 0\n\tlastChunk := 0\n\tlastKeyFrame := 0\n\n\tfor {\n\t\tchunk := getLastChunkInfo(region, gameId)\n\n\t\tif firstChunk == 0 {\n\t\t\tif chunk.CurrentChunk > chunk.StartGameChunk {\n\t\t\t\tfirstChunk = chunk.CurrentChunk\n\t\t\t} else {\n\t\t\t\tfirstChunk = chunk.StartGameChunk\n\t\t\t}\n\n\t\t\tif chunk.CurrentKeyFrame > 0 {\n\t\t\t\tfirstKeyFrame = chunk.CurrentKeyFrame\n\t\t\t} else {\n\t\t\t\tfirstKeyFrame = 1\n\t\t\t}\n\n\t\t\tlastChunk = chunk.CurrentChunk\n\t\t\tlastKeyFrame = chunk.CurrentKeyFrame\n\n\t\t\tgetChunkFrame(region, gameId, chunk.CurrentChunk)\n\t\t\tgetKeyFrame(region, gameId, chunk.CurrentKeyFrame)\n\t\t}\n\n\t\tif chunk.CurrentChunk > lastChunk {\n\t\t\tfor i := lastChunk + 1; i <= chunk.CurrentChunk; i++ {\n\t\t\t\tgetChunkFrame(region, gameId, strconv.Itoa(i))\n\t\t\t}\n\t\t}\n\n\t\tif chunk.NextChunk < chunk.CurrentChunk && chunk.NextChunk > 0 {\n\t\t\tgetChunkFrame(region, gameId, strconv.Itoa(chunk.NextChunk))\n\t\t}\n\n\t\tif chunk.CurrentKeyFrame > lastKeyFrame {\n\t\t\tfor i := lastKeyFrame + 1; i <= chunk.CurrentKeyFrame; i++ {\n\t\t\t\tgetKeyFrame(region, gameId, strconv.Itoa(chunk.CurrentKeyFrame))\n\t\t\t}\n\t\t}\n\n\t\twriteLastChunkInfo(region, gameId, firstChunk, firstKeyFrame, chunk)\n\t\tsaveRecording(region, gameId)\n\n\t\tlastChunk = chunk.CurrentChunk\n\t\tlastKeyFrame = chunk.CurrentKeyFrame\n\n\t\tif chunk.EndGameChunk == chunk.CurrentChunk {\n\t\t\treturn\n\t\t}\n\n\t\ttime.Sleep(time.Duration(chunk.NextUpdate)*time.Millisecond +\n\t\t\ttime.Second)\n\t}\n}\n\nfunc asyncRecord(region, gameId, encryptionKey string) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\trevel.ERROR.Println(\"Error while recording game ID: \" + gameId)\n\t\t\trevel.ERROR.Println(r)\n\t\t\tdelete(recording, region+\":\"+gameId)\n\t\t}\n\t}()\n\n\twriteRecording(region, gameId, \"encryptionKey\", []byte(encryptionKey))\n\n\turl := platformURLs[region]\n\tUpdateVersion(url)\n\n\trevel.INFO.Println(\"Now recording: \" + region + \":\" + gameId)\n\trevel.INFO.Println(gameId + \"'s Encryption Key: \" + encryptionKey)\n\n\trecordMetadata(region, gameId)\n\trecordFrames(region, gameId)\n\n\trevel.INFO.Println(\"Recording complete for: \" + region + \":\" + gameId)\n\tdelete(recording, region+\":\"+gameId)\n}\n\nfunc Record(region, gameId, encryptionKey string) bool {\n\tif _, ok := recording[region+\":\"+gameId]; ok {\n\t\treturn false\n\t} else {\n\t\trecording[region+\":\"+gameId] = make(map[string]string)\n\t}\n\n\thistory.StoreGame(region, gameId, encryptionKey)\n\n\tgo asyncRecord(region, gameId, encryptionKey)\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nPackage encrypt implement a backend that encrypt\/decrypt on the fly (using nacl\/secretbox [1])\nand store blobs in the \"dest\" backend.\n\nLinks\n\n\t[1] godoc.org\/code.google.com\/p\/go.crypto\/nacl\/secretbox\n\n*\/\npackage encrypt\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"errors\"\n\t\"expvar\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"sync\"\n\n\t\"github.com\/tsileo\/blobstash\/backend\"\n\n\t\"github.com\/dchest\/blake2b\"\n\n\t\"github.com\/golang\/snappy\"\n\t\"golang.org\/x\/crypto\/nacl\/secretbox\"\n)\n\nvar (\n\tbytesUploaded   = expvar.NewMap(\"encrypt-bytes-uploaded\")\n\tbytesDownloaded = expvar.NewMap(\"encrypt-bytes-downloaded\")\n\tblobsUploaded   = expvar.NewMap(\"encrypt-blobs-uploaded\")\n\tblobsDownloaded = expvar.NewMap(\"encrypt-blobs-downloaded\")\n)\n\nvar headerSize = 86\n\nfunc GenerateNonce(nonce *[24]byte) (err error) {\n\t_, err = io.ReadFull(rand.Reader, nonce[:])\n\treturn\n}\n\ntype EncryptBackend struct {\n\tdest backend.BlobHandler\n\t\/\/ index map the plain text hash to encrypted hash\n\tindex map[string]string\n\n\t\/\/ holds the encryption key\n\tkey *[32]byte\n\n\tsync.Mutex\n}\n\n\/\/ New return a backend that encrypt\/decrypt blobs on the fly,\n\/\/ blobs are compressed with snappy before encryption with nacl\/secretbox.\n\/\/ At startup it scan encrypted blobs to discover the plain hash (the hash of the plain-text\/unencrypted data).\n\/\/ Blobs are stored in the following format:\n\/\/\n\/\/ #blobstash\/secretbox\\n\n\/\/ [plain hash]\\n\n\/\/ [encrypted data]\n\/\/\nfunc New(keyPath string, dest backend.BlobHandler) *EncryptBackend {\n\tlog.Printf(\"EncryptBackend: starting with dest %v\", dest.String())\n\tif err := LoadKey(keyPath); err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Printf(\"EncryptBackend: loaded key at %v\", keyPath)\n\tb := &EncryptBackend{dest: dest, index: make(map[string]string), key: &Key}\n\tlog.Printf(\"EncryptBackend: backend id => %v\", b.String())\n\tlog.Println(\"EncryptBackend: scanning blobs to discover plain-text blobs hashes\")\n\tblobsCnt := 0\n\t\/\/ Scan the blobs to discover the plain text blob hashes and build the in-memory index\n\thashes := make(chan string)\n\terrs := make(chan error)\n\tgo func() {\n\t\terrs <- b.dest.Enumerate(hashes)\n\t}()\n\tfor hash := range hashes {\n\t\tscanner := b.scanner(hash)\n\t\tplainHash, err := scanHash(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t\t\/\/return errors.New(fmt.Sprintf(\"Error reading plain hash from %v, %v\", hash, err))\n\t\t}\n\t\tb.index[plainHash] = hash\n\t\tblobsCnt++\n\t}\n\tif err := <-errs; err != nil {\n\t\tif err == backend.ErrWriteOnly {\n\t\t\tlog.Printf(\"EncryptBackend: no scan in write-only mode\")\n\t\t} else {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tlog.Printf(\"EncryptBackend: %v blobs successfully scanned\", blobsCnt)\n\treturn b\n}\n\nfunc (backend *EncryptBackend) String() string {\n\treturn fmt.Sprintf(\"encrypt-%v\", backend.dest.String())\n}\n\nfunc (b *EncryptBackend) Put(hash string, rawData []byte) (err error) {\n\t\/\/ #blobstash\/secretbox\\n\n\t\/\/ data hash\\n\n\t\/\/ data\n\tvar nonce [24]byte\n\t\/\/out := make([]byte, len(data) + secretbox.Overhead + 24 + headerSize)\n\tif err := GenerateNonce(&nonce); err != nil {\n\t\treturn err\n\t}\n\t\/\/ First we compress the data with snappy\n\tdata := snappy.Encode(nil, rawData)\n\n\tvar out bytes.Buffer\n\tout.WriteString(\"#blobstash\/secretbox\\n\")\n\tout.WriteString(fmt.Sprintf(\"%v\\n\", hash))\n\tencData := make([]byte, len(data)+secretbox.Overhead)\n\tsecretbox.Seal(encData[0:0], data, &nonce, b.key)\n\tout.Write(nonce[:])\n\tout.Write(encData)\n\tencHash := fmt.Sprintf(\"%x\", blake2b.Sum256(out.Bytes()))\n\tb.dest.Put(encHash, out.Bytes())\n\tb.Lock()\n\tb.index[hash] = encHash\n\tdefer b.Unlock()\n\tblobsUploaded.Add(b.dest.String(), 1)\n\tbytesUploaded.Add(b.dest.String(), int64(len(out.Bytes())))\n\treturn\n}\n\nfunc (b *EncryptBackend) Delete(hash string) error {\n\tif err := b.dest.Delete(b.index[hash]); err != nil {\n\t\treturn err\n\t}\n\tdelete(b.index, hash)\n\treturn nil\n}\n\nfunc (b *EncryptBackend) Exists(hash string) (bool, error) {\n\tb.Lock()\n\tdefer b.Unlock()\n\t_, exists := b.index[hash]\n\treturn exists, nil\n}\n\nfunc (b *EncryptBackend) Done() error {\n\treturn nil\n}\n\nfunc (b *EncryptBackend) scanner(hash string) *bufio.Scanner {\n\tenc, err := b.dest.Get(hash)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tbuf := bytes.NewBuffer(enc)\n\treturn bufio.NewScanner(buf)\n}\n\nfunc scanHash(scanner *bufio.Scanner) (hash string, err error) {\n\tif !scanner.Scan() {\n\t\treturn \"\", errors.New(\"No line to read\")\n\t}\n\tif scanner.Text() != \"#blobstash\/secretbox\" {\n\t\treturn \"\", errors.New(\"bad header\")\n\t}\n\tif !scanner.Scan() {\n\t\treturn \"\", errors.New(\"ref not found\")\n\t}\n\treturn scanner.Text(), nil\n}\n\nfunc (b *EncryptBackend) Get(hash string) (data []byte, err error) {\n\tref, _ := b.index[hash]\n\tenc, err := b.dest.Get(ref)\n\tif err != nil {\n\t\treturn data, err\n\t}\n\tbox := enc[headerSize:]\n\tvar nonce [24]byte\n\tencData := make([]byte, len(box)-24)\n\tcopy(nonce[:], box[:24])\n\tcopy(encData[:], box[24:])\n\tout := make([]byte, len(box)-24)\n\tout, success := secretbox.Open(nil, encData, &nonce, b.key)\n\tif !success {\n\t\treturn data, fmt.Errorf(\"failed to decrypt blob %v\/%v\", hash, ref)\n\t}\n\t\/\/ Decode snappy data\n\tdata, err = snappy.Decode(nil, out)\n\tif err != nil {\n\t\treturn data, fmt.Errorf(\"failed to decode blob %v\/%v\", hash, ref)\n\t}\n\tblobsDownloaded.Add(b.dest.String(), 1)\n\tbytesDownloaded.Add(b.dest.String(), int64(len(enc)))\n\treturn\n}\n\nfunc (b *EncryptBackend) Enumerate(blobs chan<- string) error {\n\tdefer close(blobs)\n\tfor plainHash, _ := range b.index {\n\t\tblobs <- plainHash\n\t}\n\treturn nil\n}\n\nfunc (b *EncryptBackend) Close() {\n\tb.dest.Close()\n}\n<commit_msg>backend: added Config struct for Encrypt backend<commit_after>\/*\n\nPackage encrypt implement a backend that encrypt\/decrypt on the fly (using nacl\/secretbox [1])\nand store blobs in the \"dest\" backend.\n\nLinks\n\n\t[1] godoc.org\/code.google.com\/p\/go.crypto\/nacl\/secretbox\n\n*\/\npackage encrypt\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"errors\"\n\t\"expvar\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"sync\"\n\n\t\"github.com\/tsileo\/blobstash\/backend\"\n\n\t\"github.com\/dchest\/blake2b\"\n\n\t\"github.com\/golang\/snappy\"\n\t\"golang.org\/x\/crypto\/nacl\/secretbox\"\n)\n\nvar (\n\tbytesUploaded   = expvar.NewMap(\"encrypt-bytes-uploaded\")\n\tbytesDownloaded = expvar.NewMap(\"encrypt-bytes-downloaded\")\n\tblobsUploaded   = expvar.NewMap(\"encrypt-blobs-uploaded\")\n\tblobsDownloaded = expvar.NewMap(\"encrypt-blobs-downloaded\")\n)\n\nvar headerSize = 86\n\nfunc GenerateNonce(nonce *[24]byte) (err error) {\n\t_, err = io.ReadFull(rand.Reader, nonce[:])\n\treturn\n}\n\ntype Config struct {\n\tKeyPath     string         `structs:\"key_path,omitempty\"`\n\tDestBackend backend.Config `structs:\"backend,omitempty\"`\n}\n\nfunc (c *Config) Backend() string {\n\treturn \"encrypt\"\n}\n\nfunc (c *Config) Config() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"backend-type\": c.Backend(),\n\t\t\"backend-args\": c.Map(),\n\t}\n}\n\nfunc (c *Config) Map() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"key-path\": c.KeyPath,\n\t\t\"dest\":     c.DestBackend.Config(),\n\t}\n}\n\ntype EncryptBackend struct {\n\tdest backend.BlobHandler\n\t\/\/ index map the plain text hash to encrypted hash\n\tindex map[string]string\n\n\t\/\/ holds the encryption key\n\tkey *[32]byte\n\n\tsync.Mutex\n}\n\n\/\/ New return a backend that encrypt\/decrypt blobs on the fly,\n\/\/ blobs are compressed with snappy before encryption with nacl\/secretbox.\n\/\/ At startup it scan encrypted blobs to discover the plain hash (the hash of the plain-text\/unencrypted data).\n\/\/ Blobs are stored in the following format:\n\/\/\n\/\/ #blobstash\/secretbox\\n\n\/\/ [plain hash]\\n\n\/\/ [encrypted data]\n\/\/\nfunc New(keyPath string, dest backend.BlobHandler) *EncryptBackend {\n\tlog.Printf(\"EncryptBackend: starting with dest %v\", dest.String())\n\tif err := LoadKey(keyPath); err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Printf(\"EncryptBackend: loaded key at %v\", keyPath)\n\tb := &EncryptBackend{dest: dest, index: make(map[string]string), key: &Key}\n\tlog.Printf(\"EncryptBackend: backend id => %v\", b.String())\n\tlog.Println(\"EncryptBackend: scanning blobs to discover plain-text blobs hashes\")\n\tblobsCnt := 0\n\t\/\/ Scan the blobs to discover the plain text blob hashes and build the in-memory index\n\thashes := make(chan string)\n\terrs := make(chan error)\n\tgo func() {\n\t\terrs <- b.dest.Enumerate(hashes)\n\t}()\n\tfor hash := range hashes {\n\t\tscanner := b.scanner(hash)\n\t\tplainHash, err := scanHash(scanner)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t\t\/\/return errors.New(fmt.Sprintf(\"Error reading plain hash from %v, %v\", hash, err))\n\t\t}\n\t\tb.index[plainHash] = hash\n\t\tblobsCnt++\n\t}\n\tif err := <-errs; err != nil {\n\t\tif err == backend.ErrWriteOnly {\n\t\t\tlog.Printf(\"EncryptBackend: no scan in write-only mode\")\n\t\t} else {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tlog.Printf(\"EncryptBackend: %v blobs successfully scanned\", blobsCnt)\n\treturn b\n}\n\nfunc (backend *EncryptBackend) String() string {\n\treturn fmt.Sprintf(\"encrypt-%v\", backend.dest.String())\n}\n\nfunc (b *EncryptBackend) Put(hash string, rawData []byte) (err error) {\n\t\/\/ #blobstash\/secretbox\\n\n\t\/\/ data hash\\n\n\t\/\/ data\n\tvar nonce [24]byte\n\t\/\/out := make([]byte, len(data) + secretbox.Overhead + 24 + headerSize)\n\tif err := GenerateNonce(&nonce); err != nil {\n\t\treturn err\n\t}\n\t\/\/ First we compress the data with snappy\n\tdata := snappy.Encode(nil, rawData)\n\n\tvar out bytes.Buffer\n\tout.WriteString(\"#blobstash\/secretbox\\n\")\n\tout.WriteString(fmt.Sprintf(\"%v\\n\", hash))\n\tencData := make([]byte, len(data)+secretbox.Overhead)\n\tsecretbox.Seal(encData[0:0], data, &nonce, b.key)\n\tout.Write(nonce[:])\n\tout.Write(encData)\n\tencHash := fmt.Sprintf(\"%x\", blake2b.Sum256(out.Bytes()))\n\tb.dest.Put(encHash, out.Bytes())\n\tb.Lock()\n\tb.index[hash] = encHash\n\tdefer b.Unlock()\n\tblobsUploaded.Add(b.dest.String(), 1)\n\tbytesUploaded.Add(b.dest.String(), int64(len(out.Bytes())))\n\treturn\n}\n\nfunc (b *EncryptBackend) Delete(hash string) error {\n\tif err := b.dest.Delete(b.index[hash]); err != nil {\n\t\treturn err\n\t}\n\tdelete(b.index, hash)\n\treturn nil\n}\n\nfunc (b *EncryptBackend) Exists(hash string) (bool, error) {\n\tb.Lock()\n\tdefer b.Unlock()\n\t_, exists := b.index[hash]\n\treturn exists, nil\n}\n\nfunc (b *EncryptBackend) Done() error {\n\treturn nil\n}\n\nfunc (b *EncryptBackend) scanner(hash string) *bufio.Scanner {\n\tenc, err := b.dest.Get(hash)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tbuf := bytes.NewBuffer(enc)\n\treturn bufio.NewScanner(buf)\n}\n\nfunc scanHash(scanner *bufio.Scanner) (hash string, err error) {\n\tif !scanner.Scan() {\n\t\treturn \"\", errors.New(\"No line to read\")\n\t}\n\tif scanner.Text() != \"#blobstash\/secretbox\" {\n\t\treturn \"\", errors.New(\"bad header\")\n\t}\n\tif !scanner.Scan() {\n\t\treturn \"\", errors.New(\"ref not found\")\n\t}\n\treturn scanner.Text(), nil\n}\n\nfunc (b *EncryptBackend) Get(hash string) (data []byte, err error) {\n\tref, _ := b.index[hash]\n\tenc, err := b.dest.Get(ref)\n\tif err != nil {\n\t\treturn data, err\n\t}\n\tbox := enc[headerSize:]\n\tvar nonce [24]byte\n\tencData := make([]byte, len(box)-24)\n\tcopy(nonce[:], box[:24])\n\tcopy(encData[:], box[24:])\n\tout := make([]byte, len(box)-24)\n\tout, success := secretbox.Open(nil, encData, &nonce, b.key)\n\tif !success {\n\t\treturn data, fmt.Errorf(\"failed to decrypt blob %v\/%v\", hash, ref)\n\t}\n\t\/\/ Decode snappy data\n\tdata, err = snappy.Decode(nil, out)\n\tif err != nil {\n\t\treturn data, fmt.Errorf(\"failed to decode blob %v\/%v\", hash, ref)\n\t}\n\tblobsDownloaded.Add(b.dest.String(), 1)\n\tbytesDownloaded.Add(b.dest.String(), int64(len(enc)))\n\treturn\n}\n\nfunc (b *EncryptBackend) Enumerate(blobs chan<- string) error {\n\tdefer close(blobs)\n\tfor plainHash, _ := range b.index {\n\t\tblobs <- plainHash\n\t}\n\treturn nil\n}\n\nfunc (b *EncryptBackend) Close() {\n\tb.dest.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package lzw implements the Lempel-Ziv-Welch compressed data format,\n\/\/ described in T. A. Welch, ``A Technique for High-Performance Data\n\/\/ Compression'', Computer, 17(6) (June 1984), pp 8-19.\n\/\/\n\/\/ In particular, it implements LZW as used by the GIF, TIFF and PDF file\n\/\/ formats, which means variable-width codes up to 12 bits and the first\n\/\/ two non-literal codes are a clear code and an EOF code.\npackage lzw\n\n\/\/ TODO(nigeltao): check that TIFF and PDF use LZW in the same way as GIF,\n\/\/ modulo LSB\/MSB packing order.\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\n\/\/ Order specifies the bit ordering in an LZW data stream.\ntype Order int\n\nconst (\n\t\/\/ LSB means Least Significant Bits first, as used in the GIF file format.\n\tLSB Order = iota\n\t\/\/ MSB means Most Significant Bits first, as used in the TIFF and PDF\n\t\/\/ file formats.\n\tMSB\n)\n\nconst (\n\tmaxWidth           = 12\n\tdecoderInvalidCode = 0xffff\n\tflushBuffer        = 1 << maxWidth\n)\n\n\/\/ decoder is the state from which the readXxx method converts a byte\n\/\/ stream into a code stream.\ntype decoder struct {\n\tr        io.ByteReader\n\tbits     uint32\n\tnBits    uint\n\twidth    uint\n\tread     func(*decoder) (uint16, error) \/\/ readLSB or readMSB\n\tlitWidth int                            \/\/ width in bits of literal codes\n\terr      error\n\n\t\/\/ The first 1<<litWidth codes are literal codes.\n\t\/\/ The next two codes mean clear and EOF.\n\t\/\/ Other valid codes are in the range [lo, hi] where lo := clear + 2,\n\t\/\/ with the upper bound incrementing on each code seen.\n\t\/\/ overflow is the code at which hi overflows the code width.\n\t\/\/ last is the most recently seen code, or decoderInvalidCode.\n\tclear, eof, hi, overflow, last uint16\n\n\t\/\/ Each code c in [lo, hi] expands to two or more bytes. For c != hi:\n\t\/\/   suffix[c] is the last of these bytes.\n\t\/\/   prefix[c] is the code for all but the last byte.\n\t\/\/   This code can either be a literal code or another code in [lo, c).\n\t\/\/ The c == hi case is a special case.\n\tsuffix [1 << maxWidth]uint8\n\tprefix [1 << maxWidth]uint16\n\n\t\/\/ output is the temporary output buffer.\n\t\/\/ Literal codes are accumulated from the start of the buffer.\n\t\/\/ Non-literal codes decode to a sequence of suffixes that are first\n\t\/\/ written right-to-left from the end of the buffer before being copied\n\t\/\/ to the start of the buffer.\n\t\/\/ It is flushed when it contains >= 1<<maxWidth bytes,\n\t\/\/ so that there is always room to decode an entire code.\n\toutput [2 * 1 << maxWidth]byte\n\to      int    \/\/ write index into output\n\ttoRead []byte \/\/ bytes to return from Read\n}\n\n\/\/ readLSB returns the next code for \"Least Significant Bits first\" data.\nfunc (d *decoder) readLSB() (uint16, error) {\n\tfor d.nBits < d.width {\n\t\tx, err := d.r.ReadByte()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\td.bits |= uint32(x) << d.nBits\n\t\td.nBits += 8\n\t}\n\tcode := uint16(d.bits & (1<<d.width - 1))\n\td.bits >>= d.width\n\td.nBits -= d.width\n\treturn code, nil\n}\n\n\/\/ readMSB returns the next code for \"Most Significant Bits first\" data.\nfunc (d *decoder) readMSB() (uint16, error) {\n\tfor d.nBits < d.width {\n\t\tx, err := d.r.ReadByte()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\td.bits |= uint32(x) << (24 - d.nBits)\n\t\td.nBits += 8\n\t}\n\tcode := uint16(d.bits >> (32 - d.width))\n\td.bits <<= d.width\n\td.nBits -= d.width\n\treturn code, nil\n}\n\nfunc (d *decoder) Read(b []byte) (int, error) {\n\tfor {\n\t\tif len(d.toRead) > 0 {\n\t\t\tn := copy(b, d.toRead)\n\t\t\td.toRead = d.toRead[n:]\n\t\t\treturn n, nil\n\t\t}\n\t\tif d.err != nil {\n\t\t\treturn 0, d.err\n\t\t}\n\t\td.decode()\n\t}\n}\n\n\/\/ decode decompresses bytes from r and leaves them in d.toRead.\n\/\/ read specifies how to decode bytes into codes.\n\/\/ litWidth is the width in bits of literal codes.\nfunc (d *decoder) decode() {\n\t\/\/ Loop over the code stream, converting codes into decompressed bytes.\n\tfor {\n\t\tcode, err := d.read(d)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\terr = io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\td.err = err\n\t\t\treturn\n\t\t}\n\t\tswitch {\n\t\tcase code < d.clear:\n\t\t\t\/\/ We have a literal code.\n\t\t\td.output[d.o] = uint8(code)\n\t\t\td.o++\n\t\t\tif d.last != decoderInvalidCode {\n\t\t\t\t\/\/ Save what the hi code expands to.\n\t\t\t\td.suffix[d.hi] = uint8(code)\n\t\t\t\td.prefix[d.hi] = d.last\n\t\t\t}\n\t\tcase code == d.clear:\n\t\t\td.width = 1 + uint(d.litWidth)\n\t\t\td.hi = d.eof\n\t\t\td.overflow = 1 << d.width\n\t\t\td.last = decoderInvalidCode\n\t\t\tcontinue\n\t\tcase code == d.eof:\n\t\t\td.flush()\n\t\t\td.err = io.EOF\n\t\t\treturn\n\t\tcase code <= d.hi:\n\t\t\tc, i := code, len(d.output)-1\n\t\t\tif code == d.hi {\n\t\t\t\t\/\/ code == hi is a special case which expands to the last expansion\n\t\t\t\t\/\/ followed by the head of the last expansion. To find the head, we walk\n\t\t\t\t\/\/ the prefix chain until we find a literal code.\n\t\t\t\tc = d.last\n\t\t\t\tfor c >= d.clear {\n\t\t\t\t\tc = d.prefix[c]\n\t\t\t\t}\n\t\t\t\td.output[i] = uint8(c)\n\t\t\t\ti--\n\t\t\t\tc = d.last\n\t\t\t}\n\t\t\t\/\/ Copy the suffix chain into output and then write that to w.\n\t\t\tfor c >= d.clear {\n\t\t\t\td.output[i] = d.suffix[c]\n\t\t\t\ti--\n\t\t\t\tc = d.prefix[c]\n\t\t\t}\n\t\t\td.output[i] = uint8(c)\n\t\t\td.o += copy(d.output[d.o:], d.output[i:])\n\t\t\tif d.last != decoderInvalidCode {\n\t\t\t\t\/\/ Save what the hi code expands to.\n\t\t\t\td.suffix[d.hi] = uint8(c)\n\t\t\t\td.prefix[d.hi] = d.last\n\t\t\t}\n\t\tdefault:\n\t\t\td.err = errors.New(\"lzw: invalid code\")\n\t\t\treturn\n\t\t}\n\t\td.last, d.hi = code, d.hi+1\n\t\tif d.hi >= d.overflow {\n\t\t\tif d.width == maxWidth {\n\t\t\t\td.last = decoderInvalidCode\n\t\t\t} else {\n\t\t\t\td.width++\n\t\t\t\td.overflow <<= 1\n\t\t\t}\n\t\t}\n\t\tif d.o >= flushBuffer {\n\t\t\td.flush()\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (d *decoder) flush() {\n\td.toRead = d.output[:d.o]\n\td.o = 0\n}\n\nvar errClosed = errors.New(\"compress\/lzw: reader\/writer is closed\")\n\nfunc (d *decoder) Close() error {\n\td.err = errClosed \/\/ in case any Reads come along\n\treturn nil\n}\n\n\/\/ NewReader creates a new io.ReadCloser.\n\/\/ Reads from the returned io.ReadCloser read and decompress data from r.\n\/\/ It is the caller's responsibility to call Close on the ReadCloser when\n\/\/ finished reading.\n\/\/ The number of bits to use for literal codes, litWidth, must be in the\n\/\/ range [2,8] and is typically 8.\nfunc NewReader(r io.Reader, order Order, litWidth int) io.ReadCloser {\n\td := new(decoder)\n\tswitch order {\n\tcase LSB:\n\t\td.read = (*decoder).readLSB\n\tcase MSB:\n\t\td.read = (*decoder).readMSB\n\tdefault:\n\t\td.err = errors.New(\"lzw: unknown order\")\n\t\treturn d\n\t}\n\tif litWidth < 2 || 8 < litWidth {\n\t\td.err = fmt.Errorf(\"lzw: litWidth %d out of range\", litWidth)\n\t\treturn d\n\t}\n\tif br, ok := r.(io.ByteReader); ok {\n\t\td.r = br\n\t} else {\n\t\td.r = bufio.NewReader(r)\n\t}\n\td.litWidth = litWidth\n\td.width = 1 + uint(litWidth)\n\td.clear = uint16(1) << uint(litWidth)\n\td.eof, d.hi = d.clear+1, d.clear+1\n\td.overflow = uint16(1) << d.width\n\td.last = decoderInvalidCode\n\n\treturn d\n}\n<commit_msg>compress\/lzw: add commentary that TIFF's LZW differs from the standard algorithm.<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package lzw implements the Lempel-Ziv-Welch compressed data format,\n\/\/ described in T. A. Welch, ``A Technique for High-Performance Data\n\/\/ Compression'', Computer, 17(6) (June 1984), pp 8-19.\n\/\/\n\/\/ In particular, it implements LZW as used by the GIF and PDF file\n\/\/ formats, which means variable-width codes up to 12 bits and the first\n\/\/ two non-literal codes are a clear code and an EOF code.\n\/\/\n\/\/ The TIFF file format uses a similar but incompatible version of the LZW\n\/\/ algorithm. See the code.google.com\/p\/go.image\/tiff\/lzw package for an\n\/\/ implementation.\npackage lzw\n\n\/\/ TODO(nigeltao): check that PDF uses LZW in the same way as GIF,\n\/\/ modulo LSB\/MSB packing order.\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\n\/\/ Order specifies the bit ordering in an LZW data stream.\ntype Order int\n\nconst (\n\t\/\/ LSB means Least Significant Bits first, as used in the GIF file format.\n\tLSB Order = iota\n\t\/\/ MSB means Most Significant Bits first, as used in the TIFF and PDF\n\t\/\/ file formats.\n\tMSB\n)\n\nconst (\n\tmaxWidth           = 12\n\tdecoderInvalidCode = 0xffff\n\tflushBuffer        = 1 << maxWidth\n)\n\n\/\/ decoder is the state from which the readXxx method converts a byte\n\/\/ stream into a code stream.\ntype decoder struct {\n\tr        io.ByteReader\n\tbits     uint32\n\tnBits    uint\n\twidth    uint\n\tread     func(*decoder) (uint16, error) \/\/ readLSB or readMSB\n\tlitWidth int                            \/\/ width in bits of literal codes\n\terr      error\n\n\t\/\/ The first 1<<litWidth codes are literal codes.\n\t\/\/ The next two codes mean clear and EOF.\n\t\/\/ Other valid codes are in the range [lo, hi] where lo := clear + 2,\n\t\/\/ with the upper bound incrementing on each code seen.\n\t\/\/ overflow is the code at which hi overflows the code width.\n\t\/\/ last is the most recently seen code, or decoderInvalidCode.\n\tclear, eof, hi, overflow, last uint16\n\n\t\/\/ Each code c in [lo, hi] expands to two or more bytes. For c != hi:\n\t\/\/   suffix[c] is the last of these bytes.\n\t\/\/   prefix[c] is the code for all but the last byte.\n\t\/\/   This code can either be a literal code or another code in [lo, c).\n\t\/\/ The c == hi case is a special case.\n\tsuffix [1 << maxWidth]uint8\n\tprefix [1 << maxWidth]uint16\n\n\t\/\/ output is the temporary output buffer.\n\t\/\/ Literal codes are accumulated from the start of the buffer.\n\t\/\/ Non-literal codes decode to a sequence of suffixes that are first\n\t\/\/ written right-to-left from the end of the buffer before being copied\n\t\/\/ to the start of the buffer.\n\t\/\/ It is flushed when it contains >= 1<<maxWidth bytes,\n\t\/\/ so that there is always room to decode an entire code.\n\toutput [2 * 1 << maxWidth]byte\n\to      int    \/\/ write index into output\n\ttoRead []byte \/\/ bytes to return from Read\n}\n\n\/\/ readLSB returns the next code for \"Least Significant Bits first\" data.\nfunc (d *decoder) readLSB() (uint16, error) {\n\tfor d.nBits < d.width {\n\t\tx, err := d.r.ReadByte()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\td.bits |= uint32(x) << d.nBits\n\t\td.nBits += 8\n\t}\n\tcode := uint16(d.bits & (1<<d.width - 1))\n\td.bits >>= d.width\n\td.nBits -= d.width\n\treturn code, nil\n}\n\n\/\/ readMSB returns the next code for \"Most Significant Bits first\" data.\nfunc (d *decoder) readMSB() (uint16, error) {\n\tfor d.nBits < d.width {\n\t\tx, err := d.r.ReadByte()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\td.bits |= uint32(x) << (24 - d.nBits)\n\t\td.nBits += 8\n\t}\n\tcode := uint16(d.bits >> (32 - d.width))\n\td.bits <<= d.width\n\td.nBits -= d.width\n\treturn code, nil\n}\n\nfunc (d *decoder) Read(b []byte) (int, error) {\n\tfor {\n\t\tif len(d.toRead) > 0 {\n\t\t\tn := copy(b, d.toRead)\n\t\t\td.toRead = d.toRead[n:]\n\t\t\treturn n, nil\n\t\t}\n\t\tif d.err != nil {\n\t\t\treturn 0, d.err\n\t\t}\n\t\td.decode()\n\t}\n}\n\n\/\/ decode decompresses bytes from r and leaves them in d.toRead.\n\/\/ read specifies how to decode bytes into codes.\n\/\/ litWidth is the width in bits of literal codes.\nfunc (d *decoder) decode() {\n\t\/\/ Loop over the code stream, converting codes into decompressed bytes.\n\tfor {\n\t\tcode, err := d.read(d)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\terr = io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\td.err = err\n\t\t\treturn\n\t\t}\n\t\tswitch {\n\t\tcase code < d.clear:\n\t\t\t\/\/ We have a literal code.\n\t\t\td.output[d.o] = uint8(code)\n\t\t\td.o++\n\t\t\tif d.last != decoderInvalidCode {\n\t\t\t\t\/\/ Save what the hi code expands to.\n\t\t\t\td.suffix[d.hi] = uint8(code)\n\t\t\t\td.prefix[d.hi] = d.last\n\t\t\t}\n\t\tcase code == d.clear:\n\t\t\td.width = 1 + uint(d.litWidth)\n\t\t\td.hi = d.eof\n\t\t\td.overflow = 1 << d.width\n\t\t\td.last = decoderInvalidCode\n\t\t\tcontinue\n\t\tcase code == d.eof:\n\t\t\td.flush()\n\t\t\td.err = io.EOF\n\t\t\treturn\n\t\tcase code <= d.hi:\n\t\t\tc, i := code, len(d.output)-1\n\t\t\tif code == d.hi {\n\t\t\t\t\/\/ code == hi is a special case which expands to the last expansion\n\t\t\t\t\/\/ followed by the head of the last expansion. To find the head, we walk\n\t\t\t\t\/\/ the prefix chain until we find a literal code.\n\t\t\t\tc = d.last\n\t\t\t\tfor c >= d.clear {\n\t\t\t\t\tc = d.prefix[c]\n\t\t\t\t}\n\t\t\t\td.output[i] = uint8(c)\n\t\t\t\ti--\n\t\t\t\tc = d.last\n\t\t\t}\n\t\t\t\/\/ Copy the suffix chain into output and then write that to w.\n\t\t\tfor c >= d.clear {\n\t\t\t\td.output[i] = d.suffix[c]\n\t\t\t\ti--\n\t\t\t\tc = d.prefix[c]\n\t\t\t}\n\t\t\td.output[i] = uint8(c)\n\t\t\td.o += copy(d.output[d.o:], d.output[i:])\n\t\t\tif d.last != decoderInvalidCode {\n\t\t\t\t\/\/ Save what the hi code expands to.\n\t\t\t\td.suffix[d.hi] = uint8(c)\n\t\t\t\td.prefix[d.hi] = d.last\n\t\t\t}\n\t\tdefault:\n\t\t\td.err = errors.New(\"lzw: invalid code\")\n\t\t\treturn\n\t\t}\n\t\td.last, d.hi = code, d.hi+1\n\t\tif d.hi >= d.overflow {\n\t\t\tif d.width == maxWidth {\n\t\t\t\td.last = decoderInvalidCode\n\t\t\t} else {\n\t\t\t\td.width++\n\t\t\t\td.overflow <<= 1\n\t\t\t}\n\t\t}\n\t\tif d.o >= flushBuffer {\n\t\t\td.flush()\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (d *decoder) flush() {\n\td.toRead = d.output[:d.o]\n\td.o = 0\n}\n\nvar errClosed = errors.New(\"compress\/lzw: reader\/writer is closed\")\n\nfunc (d *decoder) Close() error {\n\td.err = errClosed \/\/ in case any Reads come along\n\treturn nil\n}\n\n\/\/ NewReader creates a new io.ReadCloser.\n\/\/ Reads from the returned io.ReadCloser read and decompress data from r.\n\/\/ It is the caller's responsibility to call Close on the ReadCloser when\n\/\/ finished reading.\n\/\/ The number of bits to use for literal codes, litWidth, must be in the\n\/\/ range [2,8] and is typically 8.\nfunc NewReader(r io.Reader, order Order, litWidth int) io.ReadCloser {\n\td := new(decoder)\n\tswitch order {\n\tcase LSB:\n\t\td.read = (*decoder).readLSB\n\tcase MSB:\n\t\td.read = (*decoder).readMSB\n\tdefault:\n\t\td.err = errors.New(\"lzw: unknown order\")\n\t\treturn d\n\t}\n\tif litWidth < 2 || 8 < litWidth {\n\t\td.err = fmt.Errorf(\"lzw: litWidth %d out of range\", litWidth)\n\t\treturn d\n\t}\n\tif br, ok := r.(io.ByteReader); ok {\n\t\td.r = br\n\t} else {\n\t\td.r = bufio.NewReader(r)\n\t}\n\td.litWidth = litWidth\n\td.width = 1 + uint(litWidth)\n\td.clear = uint16(1) << uint(litWidth)\n\td.eof, d.hi = d.clear+1, d.clear+1\n\td.overflow = uint16(1) << d.width\n\td.last = decoderInvalidCode\n\n\treturn d\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>add interactive service constructor<commit_after><|endoftext|>"}
{"text":"<commit_before>package calculator\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\n\/\/ in organises input value for Calc\ntype in struct {\n\tinput float64\n\top    string\n}\n\n\/\/ Test organises values for tests\ntype Test struct {\n\tname        string\n\tin          in\n\tout         float64\n\tshouldError bool\n}\n\n\/\/ TestCalcAdd tests the behavior of Calc with Add operation\nfunc TestCalcAdd(t *testing.T) {\n\tvar tests = []Test{\n\t\tTest{\n\t\t\tname: \"first input\",\n\t\t\tin:   in{input: 5, op: \"+\"},\n\t\t\tout:  5,\n\t\t},\n\t\tTest{\n\t\t\tname: \"second input\",\n\t\t\tin:   in{input: 10, op: \"+\"},\n\t\t\tout:  15,\n\t\t},\n\t\tTest{\n\t\t\tname: \"third input\",\n\t\t\tin:   in{input: 35, op: \"+\"},\n\t\t\tout:  50,\n\t\t},\n\t}\n\tc := &Calculator{}\n\tvar result float64\n\tfor _, test := range tests {\n\n\t\tresult = c.Do(test.in.input, test.in.op)\n\t\t\/\/if test.out != result {\n\t\t\/\/\tt.Errorf(fmt.Sprintf(\"%s: %v\", test.name, test.in))\n\t\t\/\/}\n\t\t\/\/ Assertion with assert package\n\t\tassert.Equal(\n\t\t\tt,\n\t\t\ttest.out,\n\t\t\tresult,\n\t\t\tfmt.Sprintf(\"%s: %v\", test.name, test.in),\n\t\t)\n\t}\n}\n\n\/\/ TestCalcMultipleOps tests the behavior of Calc with multiple operations\nfunc TestCalcMultipleOps(t *testing.T) {\n\tvar tests = []Test{\n\t\tTest{\n\t\t\tname: \"first input for addition\",\n\t\t\tin:   in{input: 10, op: \"+\"},\n\t\t\tout:  10,\n\t\t},\n\t\tTest{\n\t\t\tname: \"second input for multiplication\",\n\t\t\tin:   in{input: 5, op: \"*\"},\n\t\t\tout:  50,\n\t\t},\n\t\tTest{\n\t\t\tname: \"third input for subtraction\",\n\t\t\tin:   in{input: 30, op: \"-\"},\n\t\t\tout:  20,\n\t\t},\n\t\tTest{\n\t\t\tname: \"fourth input for subtraction\",\n\t\t\tin:   in{input: 4, op: \"\/\"},\n\t\t\tout:  5,\n\t\t},\n\t}\n\tc := &Calculator{}\n\tfor _, test := range tests {\n\t\t\/\/ Assertion with assert package\n\t\tassert.Equal(\n\t\t\tt,\n\t\t\ttest.out,\n\t\t\tc.Do(test.in.input, test.in.op),\n\t\t\tfmt.Sprintf(\"%s: %v\", test.name, test.in),\n\t\t)\n\t}\n}\n\n\/\/ TestCalcMultipleOpsWithSubTest tests the behavior of Calc with multiple operations\n\/\/ with sub-level tests\nfunc TestCalcMultipleOpsWithSubTest(t *testing.T) {\n\tvar tests = []Test{\n\t\tTest{\n\t\t\tname: \"first input for addition\",\n\t\t\tin:   in{input: 10, op: \"+\"},\n\t\t\tout:  10,\n\t\t},\n\t\tTest{\n\t\t\tname: \"second input for multiplication\",\n\t\t\tin:   in{input: 5, op: \"*\"},\n\t\t\tout:  50,\n\t\t},\n\t\tTest{\n\t\t\tname: \"third input for subtraction\",\n\t\t\tin:   in{input: 30, op: \"-\"},\n\t\t\tout:  20,\n\t\t},\n\t\tTest{\n\t\t\tname: \"fourth input for subtraction\",\n\t\t\tin:   in{input: 4, op: \"\/\"},\n\t\t\tout:  5,\n\t\t},\n\t}\n\tc := &Calculator{}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\ttest.out,\n\t\t\t\tc.Do(test.in.input, test.in.op),\n\t\t\t\tfmt.Sprintf(\"%s: %v\", test.name, test.in),\n\t\t\t)\n\t\t})\n\t}\n}\n\n\/\/\/\/ BenchmarkCalc benchmarks Calc\n\/\/func BenchmarkCalc(b *testing.B) {\n\/\/\ttest := Test{\n\/\/\t\tin:  in{input: 5, op: \"+\"},\n\/\/\t\tout: 5,\n\/\/\t}\n\/\/\tfor i := 0; i < b.N; i++ {\n\/\/\t\tc := &Calculator{}\n\/\/\t\tc.Do(test.in.input, test.in.op)\n\/\/\t}\n\/\/}\n\/\/\n\/\/\/\/ BenchmarkCalcMultipleOpsWithSubTest benchmarks with sub-level benchmark\n\/\/func BenchmarkCalcMultipleOpsWithSubTest(b *testing.B) {\n\/\/\tvar tests = []Test{\n\/\/\t\tTest{\n\/\/\t\t\tname: \"input for addition\",\n\/\/\t\t\tin:   in{input: 10, op: \"+\"},\n\/\/\t\t\tout:  10,\n\/\/\t\t},\n\/\/\t\tTest{\n\/\/\t\t\tname: \"input for multiplication\",\n\/\/\t\t\tin:   in{input: 5, op: \"*\"},\n\/\/\t\t\tout:  50,\n\/\/\t\t},\n\/\/\t\tTest{\n\/\/\t\t\tname: \"input for subtraction\",\n\/\/\t\t\tin:   in{input: 30, op: \"-\"},\n\/\/\t\t\tout:  20,\n\/\/\t\t},\n\/\/\t\tTest{\n\/\/\t\t\tname: \"third input for subtraction\",\n\/\/\t\t\tin:   in{input: 4, op: \"\/\"},\n\/\/\t\t\tout:  5,\n\/\/\t\t},\n\/\/\t}\n\/\/\tfor _, test := range tests {\n\/\/\t\tb.Run(test.name, func(b *testing.B) {\n\/\/\t\t\tfor i := 0; i < b.N; i++ {\n\/\/\t\t\t\tc := &Calculator{}\n\/\/\t\t\t\tc.Do(test.in.input, test.in.op)\n\/\/\t\t\t}\n\/\/\t\t})\n\/\/\t}\n\/\/}\n<commit_msg>Modifications in test examples<commit_after>package calculator\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\n\/\/ in organises input value for Calc\ntype in struct {\n\tinput float64\n\top    string\n}\n\n\/\/ Test organises values for tests\ntype Test struct {\n\tname        string\n\tin          in\n\tout         float64\n\tshouldError bool\n}\n\n\/\/ TestCalcAdd tests the behavior of Calc with Add operation\nfunc TestCalcAdd(t *testing.T) {\n\tvar tests = []Test{\n\t\tTest{\n\t\t\tname: \"first input\",\n\t\t\tin:   in{input: 5, op: \"+\"},\n\t\t\tout:  5,\n\t\t},\n\t\tTest{\n\t\t\tname: \"second input\",\n\t\t\tin:   in{input: 10, op: \"+\"},\n\t\t\tout:  15,\n\t\t},\n\t\tTest{\n\t\t\tname: \"third input\",\n\t\t\tin:   in{input: 35, op: \"+\"},\n\t\t\tout:  50,\n\t\t},\n\t}\n\tc := &Calculator{}\n\tvar result float64\n\tfor _, test := range tests {\n\n\t\tresult = c.Do(test.in.input, test.in.op)\n\t\t\/\/if test.out != result {\n\t\t\/\/\tt.Errorf(fmt.Sprintf(\"%s: %v\", test.name, test.in))\n\t\t\/\/}\n\t\t\/\/ Assertion with assert package\n\t\tassert.Equal(\n\t\t\tt,\n\t\t\ttest.out,\n\t\t\tresult,\n\t\t\tfmt.Sprintf(\"%s: %v\", test.name, test.in),\n\t\t)\n\t}\n}\n\n\/\/ TestCalcMultipleOps tests the behavior of Calc with multiple operations\nfunc TestCalcMultipleOps(t *testing.T) {\n\tvar tests = []Test{\n\t\tTest{\n\t\t\tname: \"first input for addition\",\n\t\t\tin:   in{input: 10, op: \"+\"},\n\t\t\tout:  10,\n\t\t},\n\t\tTest{\n\t\t\tname: \"second input for multiplication\",\n\t\t\tin:   in{input: 5, op: \"*\"},\n\t\t\tout:  50,\n\t\t},\n\t\tTest{\n\t\t\tname: \"third input for subtraction\",\n\t\t\tin:   in{input: 30, op: \"-\"},\n\t\t\tout:  20,\n\t\t},\n\t\tTest{\n\t\t\tname: \"fourth input for subtraction\",\n\t\t\tin:   in{input: 4, op: \"\/\"},\n\t\t\tout:  5,\n\t\t},\n\t}\n\tc := &Calculator{}\n\tfor _, test := range tests {\n\t\t\/\/ Assertion with assert package\n\t\tassert.Equal(\n\t\t\tt,\n\t\t\ttest.out,\n\t\t\tc.Do(test.in.input, test.in.op),\n\t\t\tfmt.Sprintf(\"%s: %v\", test.name, test.in),\n\t\t)\n\t}\n}\n\n\/\/ TestCalcMultipleOpsWithSubTest tests the behavior of Calc with multiple operations\n\/\/ with sub-level tests\nfunc TestCalcMultipleOpsWithSubTest(t *testing.T) {\n\tvar tests = []Test{\n\t\tTest{\n\t\t\tname: \"first input for addition\",\n\t\t\tin:   in{input: 10, op: \"+\"},\n\t\t\tout:  10,\n\t\t},\n\t\tTest{\n\t\t\tname: \"second input for multiplication\",\n\t\t\tin:   in{input: 5, op: \"*\"},\n\t\t\tout:  50,\n\t\t},\n\t\tTest{\n\t\t\tname: \"third input for subtraction\",\n\t\t\tin:   in{input: 30, op: \"-\"},\n\t\t\tout:  20,\n\t\t},\n\t\tTest{\n\t\t\tname: \"fourth input for subtraction\",\n\t\t\tin:   in{input: 4, op: \"\/\"},\n\t\t\tout:  5,\n\t\t},\n\t}\n\tc := &Calculator{}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\ttest.out,\n\t\t\t\tc.Do(test.in.input, test.in.op),\n\t\t\t\tfmt.Sprintf(\"%s: %v\", test.name, test.in),\n\t\t\t)\n\t\t})\n\t}\n}\n\n\/\/ BenchmarkCalc benchmarks Calc\nfunc BenchmarkCalc(b *testing.B) {\n\ttest := Test{\n\t\tin:  in{input: 5, op: \"+\"},\n\t\tout: 5,\n\t}\n\tfor i := 0; i < b.N; i++ {\n\t\tc := &Calculator{}\n\t\tc.Do(test.in.input, test.in.op)\n\t}\n}\n\n\/\/ BenchmarkCalcMultipleOpsWithSubTest benchmarks with sub-level benchmark\nfunc BenchmarkCalcMultipleOpsWithSubTest(b *testing.B) {\n\tvar tests = []Test{\n\t\tTest{\n\t\t\tname: \"input for addition\",\n\t\t\tin:   in{input: 10, op: \"+\"},\n\t\t\tout:  10,\n\t\t},\n\t\tTest{\n\t\t\tname: \"input for multiplication\",\n\t\t\tin:   in{input: 5, op: \"*\"},\n\t\t\tout:  50,\n\t\t},\n\t\tTest{\n\t\t\tname: \"input for subtraction\",\n\t\t\tin:   in{input: 30, op: \"-\"},\n\t\t\tout:  20,\n\t\t},\n\t\tTest{\n\t\t\tname: \"third input for subtraction\",\n\t\t\tin:   in{input: 4, op: \"\/\"},\n\t\t\tout:  5,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tb.Run(test.name, func(b *testing.B) {\n\t\t\tfor i := 0; i < b.N; i++ {\n\t\t\t\tc := &Calculator{}\n\t\t\t\tc.Do(test.in.input, test.in.op)\n\t\t\t}\n\t\t})\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package u5 provides a single utility to fetch the importers of a GoPackage via godoc.org API.\npackage u5\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n)\n\n\/\/ GoPackage represents a Go package.\ntype GoPackage struct {\n\tPath     string \/\/ Import path of the package.\n\tSynopsis string \/\/ Synopsis of the package.\n}\n\n\/\/ Importers contains the list of Go packages that import a given Go package.\ntype Importers struct {\n\tResults []GoPackage\n}\n\n\/\/ GetGodocOrgImporters fetches the importers of Go package with specified importPath via godoc.org API.\nfunc GetGodocOrgImporters(importPath string) (*Importers, error) {\n\tresp, err := http.Get(\"http:\/\/api.godoc.org\/importers\/\" + importPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"non-200 status code: %v\", resp.StatusCode)\n\t}\n\tvar importers Importers\n\terr = json.NewDecoder(resp.Body).Decode(&importers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &importers, nil\n}\n<commit_msg>u5: Add UserAgent variable.<commit_after>\/\/ Package u5 provides a single utility to fetch the importers of a GoPackage via godoc.org API.\npackage u5\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n)\n\n\/\/ GoPackage represents a Go package.\ntype GoPackage struct {\n\tPath     string \/\/ Import path of the package.\n\tSynopsis string \/\/ Synopsis of the package.\n}\n\n\/\/ Importers contains the list of Go packages that import a given Go package.\ntype Importers struct {\n\tResults []GoPackage\n}\n\n\/\/ UserAgent is used for outbound requests to godoc.org API, if set to non-empty value.\nvar UserAgent string\n\n\/\/ GetGodocOrgImporters fetches the importers of Go package with specified importPath via godoc.org API.\nfunc GetGodocOrgImporters(importPath string) (*Importers, error) {\n\treq, err := http.NewRequest(\"GET\", \"http:\/\/api.godoc.org\/importers\/\"+importPath, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif UserAgent != \"\" {\n\t\treq.Header.Set(\"User-Agent\", UserAgent)\n\t}\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"non-200 status code: %v\", resp.StatusCode)\n\t}\n\tvar importers Importers\n\terr = json.NewDecoder(resp.Body).Decode(&importers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &importers, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2022 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage concurrentddltest\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/pingcap\/tidb\/kv\"\n\t\"github.com\/pingcap\/tidb\/meta\"\n\t\"github.com\/pingcap\/tidb\/testkit\"\n\t\"github.com\/pingcap\/tidb\/util\"\n\t\"github.com\/stretchr\/testify\/require\"\n\t\"go.uber.org\/atomic\"\n)\n\nfunc TestConcurrentDDLSwitch(t *testing.T) {\n\tstore := testkit.CreateMockStore(t)\n\n\ttype table struct {\n\t\tcolumnIdx int\n\t\tindexIdx  int\n\t}\n\n\tvar tables []*table\n\ttblCount := 20\n\tfor i := 0; i < tblCount; i++ {\n\t\ttables = append(tables, &table{1, 0})\n\t}\n\n\ttk := testkit.NewTestKit(t, store)\n\ttk.MustExec(\"use test\")\n\ttk.MustExec(\"set global tidb_enable_metadata_lock=0\")\n\ttk.MustExec(\"set @@global.tidb_ddl_reorg_worker_cnt=1\")\n\ttk.MustExec(\"set @@global.tidb_ddl_reorg_batch_size=32\")\n\n\tfor i := range tables {\n\t\ttk.MustExec(fmt.Sprintf(\"create table t%d (col0 int) partition by range columns (col0) (\"+\n\t\t\t\"partition p1 values less than (100), \"+\n\t\t\t\"partition p2 values less than (300), \"+\n\t\t\t\"partition p3 values less than (500), \"+\n\t\t\t\"partition p4 values less than (700), \"+\n\t\t\t\"partition p5 values less than (1000), \"+\n\t\t\t\"partition p6 values less than maxvalue);\",\n\t\t\ti))\n\t\tfor j := 0; j < 1000; j++ {\n\t\t\ttk.MustExec(fmt.Sprintf(\"insert into t%d values (%d)\", i, j))\n\t\t}\n\t}\n\n\tddls := make([]string, 0, tblCount)\n\tddlCount := 100\n\tfor i := 0; i < ddlCount; i++ {\n\t\ttblIdx := rand.Intn(tblCount)\n\t\tif rand.Intn(2) == 0 {\n\t\t\tddls = append(ddls, fmt.Sprintf(\"alter table t%d add index idx%d (col0)\", tblIdx, tables[tblIdx].indexIdx))\n\t\t\ttables[tblIdx].indexIdx++\n\t\t} else {\n\t\t\tddls = append(ddls, fmt.Sprintf(\"alter table t%d add column col%d int\", tblIdx, tables[tblIdx].columnIdx))\n\t\t\ttables[tblIdx].columnIdx++\n\t\t}\n\t}\n\n\tc := atomic.NewInt32(0)\n\tch := make(chan struct{})\n\tgo func() {\n\t\tvar wg util.WaitGroupWrapper\n\t\tfor i := range ddls {\n\t\t\twg.Add(1)\n\t\t\tgo func(idx int) {\n\t\t\t\ttk := testkit.NewTestKit(t, store)\n\t\t\t\ttk.MustExec(\"use test\")\n\t\t\t\ttk.MustExec(ddls[idx])\n\t\t\t\tc.Add(1)\n\t\t\t\twg.Done()\n\t\t\t}(i)\n\t\t}\n\t\twg.Wait()\n\t\tch <- struct{}{}\n\t}()\n\n\tticker := time.NewTicker(time.Second)\n\tcount := 0\n\tdone := false\n\tfor !done {\n\t\tselect {\n\t\tcase <-ch:\n\t\t\tdone = true\n\t\tcase <-ticker.C:\n\t\t\tvar b bool\n\t\t\tvar err error\n\t\t\terr = kv.RunInNewTxn(kv.WithInternalSourceType(context.Background(), kv.InternalTxnDDL), store, false, func(ctx context.Context, txn kv.Transaction) error {\n\t\t\t\tb, err = meta.NewMeta(txn).IsConcurrentDDL()\n\t\t\t\treturn err\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\t\t\trs, err := testkit.NewTestKit(t, store).Exec(fmt.Sprintf(\"set @@global.tidb_enable_concurrent_ddl=%t\", !b))\n\t\t\tif rs != nil {\n\t\t\t\trequire.NoError(t, rs.Close())\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\tcount++\n\t\t\t\tif b {\n\t\t\t\t\ttk := testkit.NewTestKit(t, store)\n\t\t\t\t\ttk.MustQuery(\"select count(*) from mysql.tidb_ddl_job\").Check(testkit.Rows(\"0\"))\n\t\t\t\t\ttk.MustQuery(\"select count(*) from mysql.tidb_ddl_reorg\").Check(testkit.Rows(\"0\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\trequire.Equal(t, int32(ddlCount), c.Load())\n\trequire.Greater(t, count, 0)\n\n\ttk = testkit.NewTestKit(t, store)\n\ttk.MustExec(\"use test\")\n\tfor i, tbl := range tables {\n\t\ttk.MustQuery(fmt.Sprintf(\"select count(*) from information_schema.columns where TABLE_SCHEMA = 'test' and TABLE_NAME = 't%d'\", i)).Check(testkit.Rows(fmt.Sprintf(\"%d\", tbl.columnIdx)))\n\t\ttk.MustExec(fmt.Sprintf(\"admin check table t%d\", i))\n\t\tfor j := 0; j < tbl.indexIdx; j++ {\n\t\t\ttk.MustExec(fmt.Sprintf(\"admin check index t%d idx%d\", i, j))\n\t\t}\n\t}\n}\n<commit_msg>test: remove partition in `TestConcurrentDDLSwitch` (#37962)<commit_after>\/\/ Copyright 2022 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage concurrentddltest\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/pingcap\/tidb\/kv\"\n\t\"github.com\/pingcap\/tidb\/meta\"\n\t\"github.com\/pingcap\/tidb\/testkit\"\n\t\"github.com\/pingcap\/tidb\/util\"\n\t\"github.com\/stretchr\/testify\/require\"\n\t\"go.uber.org\/atomic\"\n)\n\nfunc TestConcurrentDDLSwitch(t *testing.T) {\n\tstore := testkit.CreateMockStore(t)\n\n\ttype table struct {\n\t\tcolumnIdx int\n\t\tindexIdx  int\n\t}\n\n\tvar tables []*table\n\ttblCount := 20\n\tfor i := 0; i < tblCount; i++ {\n\t\ttables = append(tables, &table{1, 0})\n\t}\n\n\ttk := testkit.NewTestKit(t, store)\n\ttk.MustExec(\"use test\")\n\ttk.MustExec(\"set global tidb_enable_metadata_lock=0\")\n\ttk.MustExec(\"set @@global.tidb_ddl_reorg_worker_cnt=1\")\n\ttk.MustExec(\"set @@global.tidb_ddl_reorg_batch_size=32\")\n\n\tfor i := range tables {\n\t\ttk.MustExec(fmt.Sprintf(\"create table t%d (col0 int)\", i))\n\t\tfor j := 0; j < 1000; j++ {\n\t\t\ttk.MustExec(fmt.Sprintf(\"insert into t%d values (%d)\", i, j))\n\t\t}\n\t}\n\n\tddls := make([]string, 0, tblCount)\n\tddlCount := 100\n\tfor i := 0; i < ddlCount; i++ {\n\t\ttblIdx := rand.Intn(tblCount)\n\t\tif rand.Intn(2) == 0 {\n\t\t\tddls = append(ddls, fmt.Sprintf(\"alter table t%d add index idx%d (col0)\", tblIdx, tables[tblIdx].indexIdx))\n\t\t\ttables[tblIdx].indexIdx++\n\t\t} else {\n\t\t\tddls = append(ddls, fmt.Sprintf(\"alter table t%d add column col%d int\", tblIdx, tables[tblIdx].columnIdx))\n\t\t\ttables[tblIdx].columnIdx++\n\t\t}\n\t}\n\n\tc := atomic.NewInt32(0)\n\tch := make(chan struct{})\n\tgo func() {\n\t\tvar wg util.WaitGroupWrapper\n\t\tfor i := range ddls {\n\t\t\twg.Add(1)\n\t\t\tgo func(idx int) {\n\t\t\t\ttk := testkit.NewTestKit(t, store)\n\t\t\t\ttk.MustExec(\"use test\")\n\t\t\t\ttk.MustExec(ddls[idx])\n\t\t\t\tc.Add(1)\n\t\t\t\twg.Done()\n\t\t\t}(i)\n\t\t}\n\t\twg.Wait()\n\t\tch <- struct{}{}\n\t}()\n\n\tticker := time.NewTicker(time.Second)\n\tcount := 0\n\tdone := false\n\tfor !done {\n\t\tselect {\n\t\tcase <-ch:\n\t\t\tdone = true\n\t\tcase <-ticker.C:\n\t\t\tvar b bool\n\t\t\tvar err error\n\t\t\terr = kv.RunInNewTxn(kv.WithInternalSourceType(context.Background(), kv.InternalTxnDDL), store, false, func(ctx context.Context, txn kv.Transaction) error {\n\t\t\t\tb, err = meta.NewMeta(txn).IsConcurrentDDL()\n\t\t\t\treturn err\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\t\t\trs, err := testkit.NewTestKit(t, store).Exec(fmt.Sprintf(\"set @@global.tidb_enable_concurrent_ddl=%t\", !b))\n\t\t\tif rs != nil {\n\t\t\t\trequire.NoError(t, rs.Close())\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\tcount++\n\t\t\t\tif b {\n\t\t\t\t\ttk := testkit.NewTestKit(t, store)\n\t\t\t\t\ttk.MustQuery(\"select count(*) from mysql.tidb_ddl_job\").Check(testkit.Rows(\"0\"))\n\t\t\t\t\ttk.MustQuery(\"select count(*) from mysql.tidb_ddl_reorg\").Check(testkit.Rows(\"0\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\trequire.Equal(t, int32(ddlCount), c.Load())\n\trequire.Greater(t, count, 0)\n\n\ttk = testkit.NewTestKit(t, store)\n\ttk.MustExec(\"use test\")\n\tfor i, tbl := range tables {\n\t\ttk.MustQuery(fmt.Sprintf(\"select count(*) from information_schema.columns where TABLE_SCHEMA = 'test' and TABLE_NAME = 't%d'\", i)).Check(testkit.Rows(fmt.Sprintf(\"%d\", tbl.columnIdx)))\n\t\ttk.MustExec(fmt.Sprintf(\"admin check table t%d\", i))\n\t\tfor j := 0; j < tbl.indexIdx; j++ {\n\t\t\ttk.MustExec(fmt.Sprintf(\"admin check index t%d idx%d\", i, j))\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package connmgr\n\nimport (\n\t\"math\/rand\"\n\t\"sync\"\n\t\"testing\"\n\n\tinet \"github.com\/libp2p\/go-libp2p-net\"\n)\n\nfunc randomConns(tb testing.TB) (c [5000]inet.Conn) {\n\tfor i, _ := range c {\n\t\tc[i] = randConn(tb, nil)\n\t}\n\treturn c\n}\n\nfunc BenchmarkLockContention(b *testing.B) {\n\tconns := randomConns(b)\n\tcm := NewConnManager(1000, 1000, 0)\n\tnot := cm.Notifee()\n\n\tkill := make(chan struct{})\n\tvar wg sync.WaitGroup\n\n\tfor i := 0; i < 16; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-kill:\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t\t_ = cm.GetTagInfo(conns[rand.Intn(3000)].RemotePeer())\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\trc := conns[rand.Intn(3000)]\n\t\tnot.Connected(nil, rc)\n\t\tcm.TagPeer(rc.RemotePeer(), \"tag\", 100)\n\t\tcm.UntagPeer(rc.RemotePeer(), \"tag\")\n\t\tnot.Disconnected(nil, rc)\n\t}\n\tclose(kill)\n\twg.Wait()\n}\n<commit_msg>fix bench_test to use TagPeer in parallel goroutines<commit_after>package connmgr\n\nimport (\n\t\"math\/rand\"\n\t\"sync\"\n\t\"testing\"\n\n\tinet \"github.com\/libp2p\/go-libp2p-net\"\n)\n\nfunc randomConns(tb testing.TB) (c [5000]inet.Conn) {\n\tfor i, _ := range c {\n\t\tc[i] = randConn(tb, nil)\n\t}\n\treturn c\n}\n\nfunc BenchmarkLockContention(b *testing.B) {\n\tconns := randomConns(b)\n\tcm := NewConnManager(1000, 1000, 0)\n\tnot := cm.Notifee()\n\n\tkill := make(chan struct{})\n\tvar wg sync.WaitGroup\n\n\tfor i := 0; i < 16; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-kill:\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t\tcm.TagPeer(conns[rand.Intn(len(conns))].RemotePeer(), \"another-tag\", 1)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\trc := conns[rand.Intn(len(conns))]\n\t\tnot.Connected(nil, rc)\n\t\tcm.TagPeer(rc.RemotePeer(), \"tag\", 100)\n\t\tcm.UntagPeer(rc.RemotePeer(), \"tag\")\n\t\tnot.Disconnected(nil, rc)\n\t}\n\tclose(kill)\n\twg.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019, OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage prometheus\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\/promhttp\"\n\n\t\"go.opentelemetry.io\/otel\/api\/core\"\n\t\"go.opentelemetry.io\/otel\/api\/global\"\n\texport \"go.opentelemetry.io\/otel\/sdk\/export\/metric\"\n\t\"go.opentelemetry.io\/otel\/sdk\/export\/metric\/aggregator\"\n\tsdkmetric \"go.opentelemetry.io\/otel\/sdk\/metric\"\n\t\"go.opentelemetry.io\/otel\/sdk\/metric\/batcher\/defaultkeys\"\n\t\"go.opentelemetry.io\/otel\/sdk\/metric\/controller\/push\"\n\t\"go.opentelemetry.io\/otel\/sdk\/metric\/selector\/simple\"\n)\n\n\/\/ Exporter is an implementation of metric.Exporter that sends metrics to\n\/\/ Prometheus.\ntype Exporter struct {\n\thandler http.Handler\n\n\tregisterer prometheus.Registerer\n\tgatherer   prometheus.Gatherer\n\n\tsnapshot export.CheckpointSet\n\tonError  func(error)\n\n\tdefaultSummaryQuantiles []float64\n}\n\nvar _ export.Exporter = &Exporter{}\nvar _ http.Handler = &Exporter{}\n\n\/\/ Config is a set of configs for the tally reporter.\ntype Config struct {\n\t\/\/ Registry is the prometheus registry that will be used as the default Registerer and\n\t\/\/ Gatherer if these are not specified.\n\t\/\/\n\t\/\/ If not set a new empty Registry is created.\n\tRegistry *prometheus.Registry\n\n\t\/\/ Registerer is the prometheus registerer to register\n\t\/\/ metrics with.\n\t\/\/\n\t\/\/ If not specified the Registry will be used as default.\n\tRegisterer prometheus.Registerer\n\n\t\/\/ Gatherer is the prometheus gatherer to gather\n\t\/\/ metrics with.\n\t\/\/\n\t\/\/ If not specified the Registry will be used as default.\n\tGatherer prometheus.Gatherer\n\n\t\/\/ DefaultSummaryQuantiles is the default summary quantiles\n\t\/\/ to use. Use nil to specify the system-default summary quantiles.\n\tDefaultSummaryQuantiles []float64\n\n\t\/\/ OnError is a function that handle errors that may occur while exporting metrics.\n\t\/\/ TODO: This should be refactored or even removed once we have a better error handling mechanism.\n\tOnError func(error)\n}\n\n\/\/ NewRawExporter returns a new prometheus exporter for prometheus metrics\n\/\/ for use in a pipeline.\nfunc NewRawExporter(config Config) (*Exporter, error) {\n\tif config.Registry == nil {\n\t\tconfig.Registry = prometheus.NewRegistry()\n\t}\n\n\tif config.Registerer == nil {\n\t\tconfig.Registerer = config.Registry\n\t}\n\n\tif config.Gatherer == nil {\n\t\tconfig.Gatherer = config.Registry\n\t}\n\n\tif config.OnError == nil {\n\t\tconfig.OnError = func(err error) {\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t}\n\n\te := &Exporter{\n\t\thandler:                 promhttp.HandlerFor(config.Gatherer, promhttp.HandlerOpts{}),\n\t\tregisterer:              config.Registerer,\n\t\tgatherer:                config.Gatherer,\n\t\tdefaultSummaryQuantiles: config.DefaultSummaryQuantiles,\n\t\tonError:                 config.OnError,\n\t}\n\n\tc := newCollector(e)\n\tif err := config.Registerer.Register(c); err != nil {\n\t\tconfig.OnError(fmt.Errorf(\"cannot register the collector: %w\", err))\n\t}\n\n\treturn e, nil\n}\n\n\/\/ InstallNewPipeline instantiates a NewExportPipeline and registers it globally.\n\/\/ Typically called as:\n\/\/ pipeline, hf, err := prometheus.InstallNewPipeline(prometheus.Config{...})\n\/\/ if err != nil {\n\/\/ \t...\n\/\/ }\n\/\/ http.HandleFunc(\"\/metrics\", hf)\n\/\/ defer pipeline.Stop()\n\/\/ ... Done\nfunc InstallNewPipeline(config Config) (*push.Controller, http.HandlerFunc, error) {\n\tcontroller, hf, err := NewExportPipeline(config)\n\tif err != nil {\n\t\treturn controller, hf, err\n\t}\n\tglobal.SetMeterProvider(controller)\n\treturn controller, hf, err\n}\n\n\/\/ NewExportPipeline sets up a complete export pipeline with the recommended setup,\n\/\/ chaining a NewRawExporter into the recommended selectors and batchers.\nfunc NewExportPipeline(config Config) (*push.Controller, http.HandlerFunc, error) {\n\tselector := simple.NewWithExactMeasure()\n\texporter, err := NewRawExporter(config)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Prometheus needs to use a stateful batcher since counters (and histogram since they are a collection of Counters)\n\t\/\/ are cumulative (i.e., monotonically increasing values) and should not be resetted after each export.\n\t\/\/\n\t\/\/ Prometheus uses this approach to be resilient to scrape failures.\n\t\/\/ If a Prometheus server tries to scrape metrics from a host and fails for some reason,\n\t\/\/ it could try again on the next scrape and no data would be lost, only resolution.\n\t\/\/\n\t\/\/ Gauges (or LastValues) and Summaries are an exception to this and have different behaviors.\n\tbatcher := defaultkeys.New(selector, sdkmetric.NewDefaultLabelEncoder(), true)\n\tpusher := push.New(batcher, exporter, time.Second)\n\tpusher.Start()\n\n\treturn pusher, exporter.ServeHTTP, nil\n}\n\n\/\/ Export exports the provide metric record to prometheus.\nfunc (e *Exporter) Export(_ context.Context, checkpointSet export.CheckpointSet) error {\n\te.snapshot = checkpointSet\n\treturn nil\n}\n\n\/\/ collector implements prometheus.Collector interface.\ntype collector struct {\n\texp *Exporter\n}\n\nvar _ prometheus.Collector = (*collector)(nil)\n\nfunc newCollector(exporter *Exporter) *collector {\n\treturn &collector{\n\t\texp: exporter,\n\t}\n}\n\nfunc (c *collector) Describe(ch chan<- *prometheus.Desc) {\n\tif c.exp.snapshot == nil {\n\t\treturn\n\t}\n\n\tc.exp.snapshot.ForEach(func(record export.Record) {\n\t\tch <- c.toDesc(&record)\n\t})\n}\n\n\/\/ Collect exports the last calculated CheckpointSet.\n\/\/\n\/\/ Collect is invoked whenever prometheus.Gatherer is also invoked.\n\/\/ For example, when the HTTP endpoint is invoked by Prometheus.\nfunc (c *collector) Collect(ch chan<- prometheus.Metric) {\n\tif c.exp.snapshot == nil {\n\t\treturn\n\t}\n\n\tc.exp.snapshot.ForEach(func(record export.Record) {\n\t\tagg := record.Aggregator()\n\t\tnumberKind := record.Descriptor().NumberKind()\n\t\tlabels := labelValues(record.Labels())\n\t\tdesc := c.toDesc(&record)\n\n\t\t\/\/ TODO: implement histogram export when the histogram aggregation is done.\n\t\t\/\/  https:\/\/github.com\/open-telemetry\/opentelemetry-go\/issues\/317\n\n\t\tif dist, ok := agg.(aggregator.Distribution); ok {\n\t\t\t\/\/ TODO: summaries values are never being resetted.\n\t\t\t\/\/  As measures are recorded, new records starts to have less impact on these summaries.\n\t\t\t\/\/  We should implement an solution that is similar to the Prometheus Clients\n\t\t\t\/\/  using a rolling window for summaries could be a solution.\n\t\t\t\/\/\n\t\t\t\/\/  References:\n\t\t\t\/\/ \thttps:\/\/www.robustperception.io\/how-does-a-prometheus-summary-work\n\t\t\t\/\/  https:\/\/github.com\/prometheus\/client_golang\/blob\/fa4aa9000d2863904891d193dea354d23f3d712a\/prometheus\/summary.go#L135\n\t\t\tc.exportSummary(ch, dist, numberKind, desc, labels)\n\t\t} else if sum, ok := agg.(aggregator.Sum); ok {\n\t\t\tc.exportCounter(ch, sum, numberKind, desc, labels)\n\t\t} else if gauge, ok := agg.(aggregator.LastValue); ok {\n\t\t\tc.exportGauge(ch, gauge, numberKind, desc, labels)\n\t\t}\n\t})\n}\n\nfunc (c *collector) exportGauge(ch chan<- prometheus.Metric, gauge aggregator.LastValue, kind core.NumberKind, desc *prometheus.Desc, labels []string) {\n\tlastValue, _, err := gauge.LastValue()\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tm, err := prometheus.NewConstMetric(desc, prometheus.GaugeValue, lastValue.CoerceToFloat64(kind), labels...)\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tch <- m\n}\n\nfunc (c *collector) exportCounter(ch chan<- prometheus.Metric, sum aggregator.Sum, kind core.NumberKind, desc *prometheus.Desc, labels []string) {\n\tv, err := sum.Sum()\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tm, err := prometheus.NewConstMetric(desc, prometheus.CounterValue, v.CoerceToFloat64(kind), labels...)\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tch <- m\n}\n\nfunc (c *collector) exportSummary(ch chan<- prometheus.Metric, dist aggregator.Distribution, kind core.NumberKind, desc *prometheus.Desc, labels []string) {\n\tcount, err := dist.Count()\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tvar sum core.Number\n\tsum, err = dist.Sum()\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tquantiles := make(map[float64]float64)\n\tfor _, quantile := range c.exp.defaultSummaryQuantiles {\n\t\tq, _ := dist.Quantile(quantile)\n\t\tquantiles[quantile] = q.CoerceToFloat64(kind)\n\t}\n\n\tm, err := prometheus.NewConstSummary(desc, uint64(count), sum.CoerceToFloat64(kind), quantiles, labels...)\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tch <- m\n}\n\nfunc (c *collector) toDesc(metric *export.Record) *prometheus.Desc {\n\tdesc := metric.Descriptor()\n\tlabels := labelsKeys(metric.Labels())\n\treturn prometheus.NewDesc(sanitize(desc.Name()), desc.Description(), labels, nil)\n}\n\nfunc (e *Exporter) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\te.handler.ServeHTTP(w, r)\n}\n\nfunc labelsKeys(labels export.Labels) []string {\n\tkeys := make([]string, 0, labels.Len())\n\tfor _, kv := range labels.Ordered() {\n\t\tkeys = append(keys, sanitize(string(kv.Key)))\n\t}\n\treturn keys\n}\n\nfunc labelValues(labels export.Labels) []string {\n\t\/\/ TODO(paivagustavo): parse the labels.Encoded() instead of calling `Emit()` directly\n\t\/\/  this would avoid unnecessary allocations.\n\tvalues := make([]string, 0, labels.Len())\n\tfor _, label := range labels.Ordered() {\n\t\tvalues = append(values, label.Value.Emit())\n\t}\n\treturn values\n}\n<commit_msg>exporter\/metric\/prometheus: fix incorrect code format comments for InstallNewPipeline (#482)<commit_after>\/\/ Copyright 2019, OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage prometheus\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\/promhttp\"\n\n\t\"go.opentelemetry.io\/otel\/api\/core\"\n\t\"go.opentelemetry.io\/otel\/api\/global\"\n\texport \"go.opentelemetry.io\/otel\/sdk\/export\/metric\"\n\t\"go.opentelemetry.io\/otel\/sdk\/export\/metric\/aggregator\"\n\tsdkmetric \"go.opentelemetry.io\/otel\/sdk\/metric\"\n\t\"go.opentelemetry.io\/otel\/sdk\/metric\/batcher\/defaultkeys\"\n\t\"go.opentelemetry.io\/otel\/sdk\/metric\/controller\/push\"\n\t\"go.opentelemetry.io\/otel\/sdk\/metric\/selector\/simple\"\n)\n\n\/\/ Exporter is an implementation of metric.Exporter that sends metrics to\n\/\/ Prometheus.\ntype Exporter struct {\n\thandler http.Handler\n\n\tregisterer prometheus.Registerer\n\tgatherer   prometheus.Gatherer\n\n\tsnapshot export.CheckpointSet\n\tonError  func(error)\n\n\tdefaultSummaryQuantiles []float64\n}\n\nvar _ export.Exporter = &Exporter{}\nvar _ http.Handler = &Exporter{}\n\n\/\/ Config is a set of configs for the tally reporter.\ntype Config struct {\n\t\/\/ Registry is the prometheus registry that will be used as the default Registerer and\n\t\/\/ Gatherer if these are not specified.\n\t\/\/\n\t\/\/ If not set a new empty Registry is created.\n\tRegistry *prometheus.Registry\n\n\t\/\/ Registerer is the prometheus registerer to register\n\t\/\/ metrics with.\n\t\/\/\n\t\/\/ If not specified the Registry will be used as default.\n\tRegisterer prometheus.Registerer\n\n\t\/\/ Gatherer is the prometheus gatherer to gather\n\t\/\/ metrics with.\n\t\/\/\n\t\/\/ If not specified the Registry will be used as default.\n\tGatherer prometheus.Gatherer\n\n\t\/\/ DefaultSummaryQuantiles is the default summary quantiles\n\t\/\/ to use. Use nil to specify the system-default summary quantiles.\n\tDefaultSummaryQuantiles []float64\n\n\t\/\/ OnError is a function that handle errors that may occur while exporting metrics.\n\t\/\/ TODO: This should be refactored or even removed once we have a better error handling mechanism.\n\tOnError func(error)\n}\n\n\/\/ NewRawExporter returns a new prometheus exporter for prometheus metrics\n\/\/ for use in a pipeline.\nfunc NewRawExporter(config Config) (*Exporter, error) {\n\tif config.Registry == nil {\n\t\tconfig.Registry = prometheus.NewRegistry()\n\t}\n\n\tif config.Registerer == nil {\n\t\tconfig.Registerer = config.Registry\n\t}\n\n\tif config.Gatherer == nil {\n\t\tconfig.Gatherer = config.Registry\n\t}\n\n\tif config.OnError == nil {\n\t\tconfig.OnError = func(err error) {\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t}\n\n\te := &Exporter{\n\t\thandler:                 promhttp.HandlerFor(config.Gatherer, promhttp.HandlerOpts{}),\n\t\tregisterer:              config.Registerer,\n\t\tgatherer:                config.Gatherer,\n\t\tdefaultSummaryQuantiles: config.DefaultSummaryQuantiles,\n\t\tonError:                 config.OnError,\n\t}\n\n\tc := newCollector(e)\n\tif err := config.Registerer.Register(c); err != nil {\n\t\tconfig.OnError(fmt.Errorf(\"cannot register the collector: %w\", err))\n\t}\n\n\treturn e, nil\n}\n\n\/\/ InstallNewPipeline instantiates a NewExportPipeline and registers it globally.\n\/\/ Typically called as:\n\/\/\n\/\/ \tpipeline, hf, err := prometheus.InstallNewPipeline(prometheus.Config{...})\n\/\/\n\/\/ \tif err != nil {\n\/\/ \t\t...\n\/\/ \t}\n\/\/ \thttp.HandleFunc(\"\/metrics\", hf)\n\/\/ \tdefer pipeline.Stop()\n\/\/ \t... Done\nfunc InstallNewPipeline(config Config) (*push.Controller, http.HandlerFunc, error) {\n\tcontroller, hf, err := NewExportPipeline(config)\n\tif err != nil {\n\t\treturn controller, hf, err\n\t}\n\tglobal.SetMeterProvider(controller)\n\treturn controller, hf, err\n}\n\n\/\/ NewExportPipeline sets up a complete export pipeline with the recommended setup,\n\/\/ chaining a NewRawExporter into the recommended selectors and batchers.\nfunc NewExportPipeline(config Config) (*push.Controller, http.HandlerFunc, error) {\n\tselector := simple.NewWithExactMeasure()\n\texporter, err := NewRawExporter(config)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Prometheus needs to use a stateful batcher since counters (and histogram since they are a collection of Counters)\n\t\/\/ are cumulative (i.e., monotonically increasing values) and should not be resetted after each export.\n\t\/\/\n\t\/\/ Prometheus uses this approach to be resilient to scrape failures.\n\t\/\/ If a Prometheus server tries to scrape metrics from a host and fails for some reason,\n\t\/\/ it could try again on the next scrape and no data would be lost, only resolution.\n\t\/\/\n\t\/\/ Gauges (or LastValues) and Summaries are an exception to this and have different behaviors.\n\tbatcher := defaultkeys.New(selector, sdkmetric.NewDefaultLabelEncoder(), true)\n\tpusher := push.New(batcher, exporter, time.Second)\n\tpusher.Start()\n\n\treturn pusher, exporter.ServeHTTP, nil\n}\n\n\/\/ Export exports the provide metric record to prometheus.\nfunc (e *Exporter) Export(_ context.Context, checkpointSet export.CheckpointSet) error {\n\te.snapshot = checkpointSet\n\treturn nil\n}\n\n\/\/ collector implements prometheus.Collector interface.\ntype collector struct {\n\texp *Exporter\n}\n\nvar _ prometheus.Collector = (*collector)(nil)\n\nfunc newCollector(exporter *Exporter) *collector {\n\treturn &collector{\n\t\texp: exporter,\n\t}\n}\n\nfunc (c *collector) Describe(ch chan<- *prometheus.Desc) {\n\tif c.exp.snapshot == nil {\n\t\treturn\n\t}\n\n\tc.exp.snapshot.ForEach(func(record export.Record) {\n\t\tch <- c.toDesc(&record)\n\t})\n}\n\n\/\/ Collect exports the last calculated CheckpointSet.\n\/\/\n\/\/ Collect is invoked whenever prometheus.Gatherer is also invoked.\n\/\/ For example, when the HTTP endpoint is invoked by Prometheus.\nfunc (c *collector) Collect(ch chan<- prometheus.Metric) {\n\tif c.exp.snapshot == nil {\n\t\treturn\n\t}\n\n\tc.exp.snapshot.ForEach(func(record export.Record) {\n\t\tagg := record.Aggregator()\n\t\tnumberKind := record.Descriptor().NumberKind()\n\t\tlabels := labelValues(record.Labels())\n\t\tdesc := c.toDesc(&record)\n\n\t\t\/\/ TODO: implement histogram export when the histogram aggregation is done.\n\t\t\/\/  https:\/\/github.com\/open-telemetry\/opentelemetry-go\/issues\/317\n\n\t\tif dist, ok := agg.(aggregator.Distribution); ok {\n\t\t\t\/\/ TODO: summaries values are never being resetted.\n\t\t\t\/\/  As measures are recorded, new records starts to have less impact on these summaries.\n\t\t\t\/\/  We should implement an solution that is similar to the Prometheus Clients\n\t\t\t\/\/  using a rolling window for summaries could be a solution.\n\t\t\t\/\/\n\t\t\t\/\/  References:\n\t\t\t\/\/ \thttps:\/\/www.robustperception.io\/how-does-a-prometheus-summary-work\n\t\t\t\/\/  https:\/\/github.com\/prometheus\/client_golang\/blob\/fa4aa9000d2863904891d193dea354d23f3d712a\/prometheus\/summary.go#L135\n\t\t\tc.exportSummary(ch, dist, numberKind, desc, labels)\n\t\t} else if sum, ok := agg.(aggregator.Sum); ok {\n\t\t\tc.exportCounter(ch, sum, numberKind, desc, labels)\n\t\t} else if gauge, ok := agg.(aggregator.LastValue); ok {\n\t\t\tc.exportGauge(ch, gauge, numberKind, desc, labels)\n\t\t}\n\t})\n}\n\nfunc (c *collector) exportGauge(ch chan<- prometheus.Metric, gauge aggregator.LastValue, kind core.NumberKind, desc *prometheus.Desc, labels []string) {\n\tlastValue, _, err := gauge.LastValue()\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tm, err := prometheus.NewConstMetric(desc, prometheus.GaugeValue, lastValue.CoerceToFloat64(kind), labels...)\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tch <- m\n}\n\nfunc (c *collector) exportCounter(ch chan<- prometheus.Metric, sum aggregator.Sum, kind core.NumberKind, desc *prometheus.Desc, labels []string) {\n\tv, err := sum.Sum()\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tm, err := prometheus.NewConstMetric(desc, prometheus.CounterValue, v.CoerceToFloat64(kind), labels...)\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tch <- m\n}\n\nfunc (c *collector) exportSummary(ch chan<- prometheus.Metric, dist aggregator.Distribution, kind core.NumberKind, desc *prometheus.Desc, labels []string) {\n\tcount, err := dist.Count()\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tvar sum core.Number\n\tsum, err = dist.Sum()\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tquantiles := make(map[float64]float64)\n\tfor _, quantile := range c.exp.defaultSummaryQuantiles {\n\t\tq, _ := dist.Quantile(quantile)\n\t\tquantiles[quantile] = q.CoerceToFloat64(kind)\n\t}\n\n\tm, err := prometheus.NewConstSummary(desc, uint64(count), sum.CoerceToFloat64(kind), quantiles, labels...)\n\tif err != nil {\n\t\tc.exp.onError(err)\n\t\treturn\n\t}\n\n\tch <- m\n}\n\nfunc (c *collector) toDesc(metric *export.Record) *prometheus.Desc {\n\tdesc := metric.Descriptor()\n\tlabels := labelsKeys(metric.Labels())\n\treturn prometheus.NewDesc(sanitize(desc.Name()), desc.Description(), labels, nil)\n}\n\nfunc (e *Exporter) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\te.handler.ServeHTTP(w, r)\n}\n\nfunc labelsKeys(labels export.Labels) []string {\n\tkeys := make([]string, 0, labels.Len())\n\tfor _, kv := range labels.Ordered() {\n\t\tkeys = append(keys, sanitize(string(kv.Key)))\n\t}\n\treturn keys\n}\n\nfunc labelValues(labels export.Labels) []string {\n\t\/\/ TODO(paivagustavo): parse the labels.Encoded() instead of calling `Emit()` directly\n\t\/\/  this would avoid unnecessary allocations.\n\tvalues := make([]string, 0, labels.Len())\n\tfor _, label := range labels.Ordered() {\n\t\tvalues = append(values, label.Value.Emit())\n\t}\n\treturn values\n}\n<|endoftext|>"}
{"text":"<commit_before>package google\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/hashicorp\/go-retryablehttp\"\n\t\"github.com\/pkg\/errors\"\n)\n\nfunc buildClient() *retryablehttp.Client {\n\thttpClient := retryablehttp.NewClient()\n\n\t\/\/ Stop debug logger\n\thttpClient.Logger = nil\n\thttpClient.RetryMax = 1\n\thttpClient.RetryWaitMin = 30 * time.Second\n\thttpClient.RetryWaitMax = 2 * time.Minute\n\n\treturn httpClient\n}\n\nfunc buildRequest(langFrom, langTo, inputText string) (*retryablehttp.Request, error) {\n\tvar URL *url.URL\n\tURL, err := url.Parse(\"https:\/\/translate.googleapis.com\/translate_a\/single\")\n\n\tparameters := url.Values{}\n\tparameters.Add(\"client\", \"gtx\") \/\/ Google translate extension\n\tparameters.Add(\"dt\", \"t\")       \/\/ Translate text\n\tparameters.Add(\"hl\", \"en\")      \/\/ Interface language\n\tparameters.Add(\"sl\", langFrom)  \/\/ Source language or \"auto\"\n\tparameters.Add(\"tl\", langTo)    \/\/ Target language\n\tparameters.Add(\"ie\", \"UTF-8\")   \/\/ Input encoding\n\tparameters.Add(\"oe\", \"UTF-8\")   \/\/ Output encoding\n\tparameters.Add(\"q\", inputText)  \/\/ Source text\n\n\tURL.RawQuery = parameters.Encode()\n\n\tr, err := retryablehttp.NewRequest(\"GET\", URL.String(), nil)\n\tif err != nil {\n\t\treturn r, errors.Wrap(err, \"Failed to create request\")\n\t}\n\n\treturn r, err\n}\n\nfunc (q *batchTranslator) translateBatch(items []inputObject) {\n\tq.lastBatch = time.Now()\n\n\t\/\/log.Debug(\"Items:\", spew.Sdump(items))\n\n\tlog.Infof(\"processing %d items\", len(items))\n\n\tif len(items) < 1 {\n\t\tlog.Debug(\"nothing to do\")\n\t\treturn\n\t}\n\n\t\/\/ TODO: Add support for different language pairs\n\terr := q.translateItems(items)\n\tif err != nil {\n\t\t\/\/ Send error to all items\n\t\tfor _, i := range items {\n\t\t\ti.outChan <- returnObject{\n\t\t\t\ttext: \"\",\n\t\t\t\terr:  err,\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (q *batchTranslator) translateItems(items []inputObject) error {\n\t\/\/ Join every input separated by newline\n\tvar reqText string\n\tfor _, i := range items {\n\t\treqText += i.req.Text + \"\\n\"\n\t}\n\n\tr, err := buildRequest(items[0].req.From, items[0].req.To, reqText)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := q.client.Do(r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\n\t\treturn errors.Wrapf(err, \"Failed to do request (%s delay)\", q.batchDelay)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tif contents, err := ioutil.ReadAll(resp.Body); err == nil {\n\t\t\treturn fmt.Errorf(\"%s - %s\", resp.Status, contents)\n\t\t}\n\n\t\treturn fmt.Errorf(\"%s\", resp.Status)\n\t}\n\n\tcontents, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to read response body\")\n\t}\n\n\tresponse, err := decodeResponse(string(contents))\n\tif err != nil {\n\t\tlog.Error(\"Unknown response: %q\", string(contents))\n\t\treturn errors.Wrap(err, \"Failed to decode response json\")\n\t}\n\n\tif len(items) != len(response) {\n\t\tlog.Fatal(\"Response pairs doesn't match input\", spew.Sdump(response), spew.Sdump(items))\n\t}\n\n\tfor i, pair := range response {\n\t\tif strings.TrimSpace(pair.input) != strings.TrimSpace(items[i].req.Text) {\n\t\t\titems[i].outChan <- returnObject{\n\t\t\t\ttext: pair.input,\n\t\t\t\terr:  fmt.Errorf(\"mismatched input text! %q != %q\", items[i].req.Text, pair.input),\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\titems[i].outChan <- returnObject{\n\t\t\ttext: pair.output,\n\t\t\terr:  nil,\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>Fix mising format<commit_after>package google\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/hashicorp\/go-retryablehttp\"\n\t\"github.com\/pkg\/errors\"\n)\n\nfunc buildClient() *retryablehttp.Client {\n\thttpClient := retryablehttp.NewClient()\n\n\t\/\/ Stop debug logger\n\thttpClient.Logger = nil\n\thttpClient.RetryMax = 1\n\thttpClient.RetryWaitMin = 30 * time.Second\n\thttpClient.RetryWaitMax = 2 * time.Minute\n\n\treturn httpClient\n}\n\nfunc buildRequest(langFrom, langTo, inputText string) (*retryablehttp.Request, error) {\n\tvar URL *url.URL\n\tURL, err := url.Parse(\"https:\/\/translate.googleapis.com\/translate_a\/single\")\n\n\tparameters := url.Values{}\n\tparameters.Add(\"client\", \"gtx\") \/\/ Google translate extension\n\tparameters.Add(\"dt\", \"t\")       \/\/ Translate text\n\tparameters.Add(\"hl\", \"en\")      \/\/ Interface language\n\tparameters.Add(\"sl\", langFrom)  \/\/ Source language or \"auto\"\n\tparameters.Add(\"tl\", langTo)    \/\/ Target language\n\tparameters.Add(\"ie\", \"UTF-8\")   \/\/ Input encoding\n\tparameters.Add(\"oe\", \"UTF-8\")   \/\/ Output encoding\n\tparameters.Add(\"q\", inputText)  \/\/ Source text\n\n\tURL.RawQuery = parameters.Encode()\n\n\tr, err := retryablehttp.NewRequest(\"GET\", URL.String(), nil)\n\tif err != nil {\n\t\treturn r, errors.Wrap(err, \"Failed to create request\")\n\t}\n\n\treturn r, err\n}\n\nfunc (q *batchTranslator) translateBatch(items []inputObject) {\n\tq.lastBatch = time.Now()\n\n\t\/\/log.Debug(\"Items:\", spew.Sdump(items))\n\n\tlog.Infof(\"processing %d items\", len(items))\n\n\tif len(items) < 1 {\n\t\tlog.Debug(\"nothing to do\")\n\t\treturn\n\t}\n\n\t\/\/ TODO: Add support for different language pairs\n\terr := q.translateItems(items)\n\tif err != nil {\n\t\t\/\/ Send error to all items\n\t\tfor _, i := range items {\n\t\t\ti.outChan <- returnObject{\n\t\t\t\ttext: \"\",\n\t\t\t\terr:  err,\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (q *batchTranslator) translateItems(items []inputObject) error {\n\t\/\/ Join every input separated by newline\n\tvar reqText string\n\tfor _, i := range items {\n\t\treqText += i.req.Text + \"\\n\"\n\t}\n\n\tr, err := buildRequest(items[0].req.From, items[0].req.To, reqText)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := q.client.Do(r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\n\t\treturn errors.Wrapf(err, \"Failed to do request (%s delay)\", q.batchDelay)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\tif contents, err := ioutil.ReadAll(resp.Body); err == nil {\n\t\t\treturn fmt.Errorf(\"%s - %s\", resp.Status, contents)\n\t\t}\n\n\t\treturn fmt.Errorf(\"%s\", resp.Status)\n\t}\n\n\tcontents, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Failed to read response body\")\n\t}\n\n\tresponse, err := decodeResponse(string(contents))\n\tif err != nil {\n\t\tlog.Errorf(\"Unknown response: %q\", string(contents))\n\t\treturn errors.Wrap(err, \"Failed to decode response json\")\n\t}\n\n\tif len(items) != len(response) {\n\t\tlog.Fatal(\"Response pairs doesn't match input\", spew.Sdump(response), spew.Sdump(items))\n\t}\n\n\tfor i, pair := range response {\n\t\tif strings.TrimSpace(pair.input) != strings.TrimSpace(items[i].req.Text) {\n\t\t\titems[i].outChan <- returnObject{\n\t\t\t\ttext: pair.input,\n\t\t\t\terr:  fmt.Errorf(\"mismatched input text! %q != %q\", items[i].req.Text, pair.input),\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\titems[i].outChan <- returnObject{\n\t\t\ttext: pair.output,\n\t\t\terr:  nil,\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2014 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage predicates\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/client\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/labels\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/plugin\/pkg\/scheduler\/algorithm\"\n)\n\ntype NodeInfo interface {\n\tGetNodeInfo(nodeID string) (*api.Node, error)\n}\n\ntype StaticNodeInfo struct {\n\t*api.NodeList\n}\n\nfunc (nodes StaticNodeInfo) GetNodeInfo(nodeID string) (*api.Node, error) {\n\tfor ix := range nodes.Items {\n\t\tif nodes.Items[ix].Name == nodeID {\n\t\t\treturn &nodes.Items[ix], nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"failed to find node: %s, %#v\", nodeID, nodes)\n}\n\ntype ClientNodeInfo struct {\n\t*client.Client\n}\n\nfunc (nodes ClientNodeInfo) GetNodeInfo(nodeID string) (*api.Node, error) {\n\treturn nodes.Nodes().Get(nodeID)\n}\n\nfunc isVolumeConflict(volume api.Volume, pod *api.Pod) bool {\n\tif volume.GCEPersistentDisk != nil {\n\t\tdisk := volume.GCEPersistentDisk\n\n\t\tmanifest := &(pod.Spec)\n\t\tfor ix := range manifest.Volumes {\n\t\t\tif manifest.Volumes[ix].GCEPersistentDisk != nil &&\n\t\t\t\tmanifest.Volumes[ix].GCEPersistentDisk.PDName == disk.PDName &&\n\t\t\t\t!(manifest.Volumes[ix].GCEPersistentDisk.ReadOnly && disk.ReadOnly) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\tif volume.AWSElasticBlockStore != nil {\n\t\tvolumeID := volume.AWSElasticBlockStore.VolumeID\n\n\t\tmanifest := &(pod.Spec)\n\t\tfor ix := range manifest.Volumes {\n\t\t\tif manifest.Volumes[ix].AWSElasticBlockStore != nil &&\n\t\t\t\tmanifest.Volumes[ix].AWSElasticBlockStore.VolumeID == volumeID {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ NoDiskConflict evaluates if a pod can fit due to the volumes it requests, and those that\n\/\/ are already mounted. Some times of volumes are mounted onto node machines.  For now, these mounts\n\/\/ are exclusive so if there is already a volume mounted on that node, another pod can't schedule\n\/\/ there. This is GCE specific for now.\n\/\/ TODO: migrate this into some per-volume specific code?\nfunc NoDiskConflict(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\tmanifest := &(pod.Spec)\n\tfor ix := range manifest.Volumes {\n\t\tfor podIx := range existingPods {\n\t\t\tif isVolumeConflict(manifest.Volumes[ix], existingPods[podIx]) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn true, nil\n}\n\ntype ResourceFit struct {\n\tinfo NodeInfo\n}\n\ntype resourceRequest struct {\n\tmilliCPU int64\n\tmemory   int64\n}\n\nfunc getResourceRequest(pod *api.Pod) resourceRequest {\n\tresult := resourceRequest{}\n\tfor ix := range pod.Spec.Containers {\n\t\tlimits := pod.Spec.Containers[ix].Resources.Limits\n\t\tresult.memory += limits.Memory().Value()\n\t\tresult.milliCPU += limits.Cpu().MilliValue()\n\t}\n\treturn result\n}\n\nfunc CheckPodsExceedingCapacity(pods []*api.Pod, capacity api.ResourceList) (fitting []*api.Pod, notFitting []*api.Pod) {\n\ttotalMilliCPU := capacity.Cpu().MilliValue()\n\ttotalMemory := capacity.Memory().Value()\n\tmilliCPURequested := int64(0)\n\tmemoryRequested := int64(0)\n\tfor _, pod := range pods {\n\t\tpodRequest := getResourceRequest(pod)\n\t\tfitsCPU := totalMilliCPU == 0 || (totalMilliCPU-milliCPURequested) >= podRequest.milliCPU\n\t\tfitsMemory := totalMemory == 0 || (totalMemory-memoryRequested) >= podRequest.memory\n\t\tif !fitsCPU || !fitsMemory {\n\t\t\t\/\/ the pod doesn't fit\n\t\t\tnotFitting = append(notFitting, pod)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ the pod fits\n\t\tmilliCPURequested += podRequest.milliCPU\n\t\tmemoryRequested += podRequest.memory\n\t\tfitting = append(fitting, pod)\n\t}\n\treturn\n}\n\n\/\/ PodFitsResources calculates fit based on requested, rather than used resources\nfunc (r *ResourceFit) PodFitsResources(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\tpodRequest := getResourceRequest(pod)\n\tinfo, err := r.info.GetNodeInfo(node)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif podRequest.milliCPU == 0 && podRequest.memory == 0 {\n\t\treturn int64(len(existingPods)) < info.Status.Capacity.Pods().Value(), nil\n\t}\n\tpods := []*api.Pod{}\n\tcopy(pods, existingPods)\n\tpods = append(existingPods, pod)\n\t_, exceeding := CheckPodsExceedingCapacity(pods, info.Status.Capacity)\n\tif len(exceeding) > 0 || int64(len(pods)) > info.Status.Capacity.Pods().Value() {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}\n\nfunc NewResourceFitPredicate(info NodeInfo) algorithm.FitPredicate {\n\tfit := &ResourceFit{\n\t\tinfo: info,\n\t}\n\treturn fit.PodFitsResources\n}\n\nfunc NewSelectorMatchPredicate(info NodeInfo) algorithm.FitPredicate {\n\tselector := &NodeSelector{\n\t\tinfo: info,\n\t}\n\treturn selector.PodSelectorMatches\n}\n\nfunc PodMatchesNodeLabels(pod *api.Pod, node *api.Node) bool {\n\tif len(pod.Spec.NodeSelector) == 0 {\n\t\treturn true\n\t}\n\tselector := labels.SelectorFromSet(pod.Spec.NodeSelector)\n\treturn selector.Matches(labels.Set(node.Labels))\n}\n\ntype NodeSelector struct {\n\tinfo NodeInfo\n}\n\nfunc (n *NodeSelector) PodSelectorMatches(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\tminion, err := n.info.GetNodeInfo(node)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn PodMatchesNodeLabels(pod, minion), nil\n}\n\nfunc PodFitsHost(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\tif len(pod.Spec.NodeName) == 0 {\n\t\treturn true, nil\n\t}\n\treturn pod.Spec.NodeName == node, nil\n}\n\ntype NodeLabelChecker struct {\n\tinfo     NodeInfo\n\tlabels   []string\n\tpresence bool\n}\n\nfunc NewNodeLabelPredicate(info NodeInfo, labels []string, presence bool) algorithm.FitPredicate {\n\tlabelChecker := &NodeLabelChecker{\n\t\tinfo:     info,\n\t\tlabels:   labels,\n\t\tpresence: presence,\n\t}\n\treturn labelChecker.CheckNodeLabelPresence\n}\n\n\/\/ CheckNodeLabelPresence checks whether all of the specified labels exists on a minion or not, regardless of their value\n\/\/ If \"presence\" is false, then returns false if any of the requested labels matches any of the minion's labels,\n\/\/ otherwise returns true.\n\/\/ If \"presence\" is true, then returns false if any of the requested labels does not match any of the minion's labels,\n\/\/ otherwise returns true.\n\/\/\n\/\/ Consider the cases where the minions are placed in regions\/zones\/racks and these are identified by labels\n\/\/ In some cases, it is required that only minions that are part of ANY of the defined regions\/zones\/racks be selected\n\/\/\n\/\/ Alternately, eliminating minions that have a certain label, regardless of value, is also useful\n\/\/ A minion may have a label with \"retiring\" as key and the date as the value\n\/\/ and it may be desirable to avoid scheduling new pods on this minion\nfunc (n *NodeLabelChecker) CheckNodeLabelPresence(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\tvar exists bool\n\tminion, err := n.info.GetNodeInfo(node)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tminionLabels := labels.Set(minion.Labels)\n\tfor _, label := range n.labels {\n\t\texists = minionLabels.Has(label)\n\t\tif (exists && !n.presence) || (!exists && n.presence) {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}\n\ntype ServiceAffinity struct {\n\tpodLister     algorithm.PodLister\n\tserviceLister algorithm.ServiceLister\n\tnodeInfo      NodeInfo\n\tlabels        []string\n}\n\nfunc NewServiceAffinityPredicate(podLister algorithm.PodLister, serviceLister algorithm.ServiceLister, nodeInfo NodeInfo, labels []string) algorithm.FitPredicate {\n\taffinity := &ServiceAffinity{\n\t\tpodLister:     podLister,\n\t\tserviceLister: serviceLister,\n\t\tnodeInfo:      nodeInfo,\n\t\tlabels:        labels,\n\t}\n\treturn affinity.CheckServiceAffinity\n}\n\n\/\/ CheckServiceAffinity ensures that only the minions that match the specified labels are considered for scheduling.\n\/\/ The set of labels to be considered are provided to the struct (ServiceAffinity).\n\/\/ The pod is checked for the labels and any missing labels are then checked in the minion\n\/\/ that hosts the service pods (peers) for the given pod.\n\/\/\n\/\/ We add an implicit selector requiring some particular value V for label L to a pod, if:\n\/\/ - L is listed in the ServiceAffinity object that is passed into the function\n\/\/ - the pod does not have any NodeSelector for L\n\/\/ - some other pod from the same service is already scheduled onto a minion that has value V for label L\nfunc (s *ServiceAffinity) CheckServiceAffinity(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\tvar affinitySelector labels.Selector\n\n\t\/\/ check if the pod being scheduled has the affinity labels specified in its NodeSelector\n\taffinityLabels := map[string]string{}\n\tnodeSelector := labels.Set(pod.Spec.NodeSelector)\n\tlabelsExist := true\n\tfor _, l := range s.labels {\n\t\tif nodeSelector.Has(l) {\n\t\t\taffinityLabels[l] = nodeSelector.Get(l)\n\t\t} else {\n\t\t\t\/\/ the current pod does not specify all the labels, look in the existing service pods\n\t\t\tlabelsExist = false\n\t\t}\n\t}\n\n\t\/\/ skip looking at other pods in the service if the current pod defines all the required affinity labels\n\tif !labelsExist {\n\t\tservices, err := s.serviceLister.GetPodServices(pod)\n\t\tif err == nil {\n\t\t\t\/\/ just use the first service and get the other pods within the service\n\t\t\t\/\/ TODO: a separate predicate can be created that tries to handle all services for the pod\n\t\t\tselector := labels.SelectorFromSet(services[0].Spec.Selector)\n\t\t\tservicePods, err := s.podLister.List(selector)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\t\/\/ consider only the pods that belong to the same namespace\n\t\t\tnsServicePods := []*api.Pod{}\n\t\t\tfor _, nsPod := range servicePods {\n\t\t\t\tif nsPod.Namespace == pod.Namespace {\n\t\t\t\t\tnsServicePods = append(nsServicePods, nsPod)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(nsServicePods) > 0 {\n\t\t\t\t\/\/ consider any service pod and fetch the minion its hosted on\n\t\t\t\totherMinion, err := s.nodeInfo.GetNodeInfo(nsServicePods[0].Spec.NodeName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tfor _, l := range s.labels {\n\t\t\t\t\t\/\/ If the pod being scheduled has the label value specified, do not override it\n\t\t\t\t\tif _, exists := affinityLabels[l]; exists {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif labels.Set(otherMinion.Labels).Has(l) {\n\t\t\t\t\t\taffinityLabels[l] = labels.Set(otherMinion.Labels).Get(l)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ if there are no existing pods in the service, consider all minions\n\tif len(affinityLabels) == 0 {\n\t\taffinitySelector = labels.Everything()\n\t} else {\n\t\taffinitySelector = labels.Set(affinityLabels).AsSelector()\n\t}\n\n\tminion, err := s.nodeInfo.GetNodeInfo(node)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ check if the minion matches the selector\n\treturn affinitySelector.Matches(labels.Set(minion.Labels)), nil\n}\n\nfunc PodFitsPorts(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\texistingPorts := getUsedPorts(existingPods...)\n\twantPorts := getUsedPorts(pod)\n\tfor wport := range wantPorts {\n\t\tif wport == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif existingPorts[wport] {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}\n\nfunc getUsedPorts(pods ...*api.Pod) map[int]bool {\n\tports := make(map[int]bool)\n\tfor _, pod := range pods {\n\t\tfor _, container := range pod.Spec.Containers {\n\t\t\tfor _, podPort := range container.Ports {\n\t\t\t\tports[podPort.HostPort] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn ports\n}\n\nfunc filterNonRunningPods(pods []*api.Pod) []*api.Pod {\n\tif len(pods) == 0 {\n\t\treturn pods\n\t}\n\tresult := []*api.Pod{}\n\tfor _, pod := range pods {\n\t\tif pod.Status.Phase == api.PodSucceeded || pod.Status.Phase == api.PodFailed {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, pod)\n\t}\n\treturn result\n}\n\n\/\/ MapPodsToMachines obtains a list of pods and pivots that list into a map where the keys are host names\n\/\/ and the values are the list of pods running on that host.\nfunc MapPodsToMachines(lister algorithm.PodLister) (map[string][]*api.Pod, error) {\n\tmachineToPods := map[string][]*api.Pod{}\n\t\/\/ TODO: perform more targeted query...\n\tpods, err := lister.List(labels.Everything())\n\tif err != nil {\n\t\treturn map[string][]*api.Pod{}, err\n\t}\n\tpods = filterNonRunningPods(pods)\n\tfor _, scheduledPod := range pods {\n\t\thost := scheduledPod.Spec.NodeName\n\t\tmachineToPods[host] = append(machineToPods[host], scheduledPod)\n\t}\n\treturn machineToPods, nil\n}\n<commit_msg>Add more logging to scheduler predicates to help debugging max_pods e2e test flakyness<commit_after>\/*\nCopyright 2014 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage predicates\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/client\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/labels\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/plugin\/pkg\/scheduler\/algorithm\"\n\n\t\"github.com\/golang\/glog\"\n)\n\ntype NodeInfo interface {\n\tGetNodeInfo(nodeID string) (*api.Node, error)\n}\n\ntype StaticNodeInfo struct {\n\t*api.NodeList\n}\n\nfunc (nodes StaticNodeInfo) GetNodeInfo(nodeID string) (*api.Node, error) {\n\tfor ix := range nodes.Items {\n\t\tif nodes.Items[ix].Name == nodeID {\n\t\t\treturn &nodes.Items[ix], nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"failed to find node: %s, %#v\", nodeID, nodes)\n}\n\ntype ClientNodeInfo struct {\n\t*client.Client\n}\n\nfunc (nodes ClientNodeInfo) GetNodeInfo(nodeID string) (*api.Node, error) {\n\treturn nodes.Nodes().Get(nodeID)\n}\n\nfunc isVolumeConflict(volume api.Volume, pod *api.Pod) bool {\n\tif volume.GCEPersistentDisk != nil {\n\t\tdisk := volume.GCEPersistentDisk\n\n\t\tmanifest := &(pod.Spec)\n\t\tfor ix := range manifest.Volumes {\n\t\t\tif manifest.Volumes[ix].GCEPersistentDisk != nil &&\n\t\t\t\tmanifest.Volumes[ix].GCEPersistentDisk.PDName == disk.PDName &&\n\t\t\t\t!(manifest.Volumes[ix].GCEPersistentDisk.ReadOnly && disk.ReadOnly) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\tif volume.AWSElasticBlockStore != nil {\n\t\tvolumeID := volume.AWSElasticBlockStore.VolumeID\n\n\t\tmanifest := &(pod.Spec)\n\t\tfor ix := range manifest.Volumes {\n\t\t\tif manifest.Volumes[ix].AWSElasticBlockStore != nil &&\n\t\t\t\tmanifest.Volumes[ix].AWSElasticBlockStore.VolumeID == volumeID {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ NoDiskConflict evaluates if a pod can fit due to the volumes it requests, and those that\n\/\/ are already mounted. Some times of volumes are mounted onto node machines.  For now, these mounts\n\/\/ are exclusive so if there is already a volume mounted on that node, another pod can't schedule\n\/\/ there. This is GCE specific for now.\n\/\/ TODO: migrate this into some per-volume specific code?\nfunc NoDiskConflict(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\tmanifest := &(pod.Spec)\n\tfor ix := range manifest.Volumes {\n\t\tfor podIx := range existingPods {\n\t\t\tif isVolumeConflict(manifest.Volumes[ix], existingPods[podIx]) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn true, nil\n}\n\ntype ResourceFit struct {\n\tinfo NodeInfo\n}\n\ntype resourceRequest struct {\n\tmilliCPU int64\n\tmemory   int64\n}\n\nfunc getResourceRequest(pod *api.Pod) resourceRequest {\n\tresult := resourceRequest{}\n\tfor ix := range pod.Spec.Containers {\n\t\tlimits := pod.Spec.Containers[ix].Resources.Limits\n\t\tresult.memory += limits.Memory().Value()\n\t\tresult.milliCPU += limits.Cpu().MilliValue()\n\t}\n\treturn result\n}\n\nfunc CheckPodsExceedingCapacity(pods []*api.Pod, capacity api.ResourceList) (fitting []*api.Pod, notFitting []*api.Pod) {\n\ttotalMilliCPU := capacity.Cpu().MilliValue()\n\ttotalMemory := capacity.Memory().Value()\n\tmilliCPURequested := int64(0)\n\tmemoryRequested := int64(0)\n\tfor _, pod := range pods {\n\t\tpodRequest := getResourceRequest(pod)\n\t\tfitsCPU := totalMilliCPU == 0 || (totalMilliCPU-milliCPURequested) >= podRequest.milliCPU\n\t\tfitsMemory := totalMemory == 0 || (totalMemory-memoryRequested) >= podRequest.memory\n\t\tif !fitsCPU || !fitsMemory {\n\t\t\t\/\/ the pod doesn't fit\n\t\t\tnotFitting = append(notFitting, pod)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ the pod fits\n\t\tmilliCPURequested += podRequest.milliCPU\n\t\tmemoryRequested += podRequest.memory\n\t\tfitting = append(fitting, pod)\n\t}\n\treturn\n}\n\n\/\/ PodFitsResources calculates fit based on requested, rather than used resources\nfunc (r *ResourceFit) PodFitsResources(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\tpodRequest := getResourceRequest(pod)\n\tinfo, err := r.info.GetNodeInfo(node)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif podRequest.milliCPU == 0 && podRequest.memory == 0 {\n\t\treturn int64(len(existingPods)) < info.Status.Capacity.Pods().Value(), nil\n\t}\n\tpods := []*api.Pod{}\n\tcopy(pods, existingPods)\n\tpods = append(existingPods, pod)\n\t_, exceeding := CheckPodsExceedingCapacity(pods, info.Status.Capacity)\n\tif len(exceeding) > 0 || int64(len(pods)) > info.Status.Capacity.Pods().Value() {\n\t\tglog.V(4).Infof(\"Cannot schedule Pod %v, because Node %v is full, running %v out of %v Pods.\", pod, node, len(pods)-1, info.Status.Capacity.Pods().Value())\n\t\treturn false, nil\n\t}\n\tglog.V(4).Infof(\"Schedule Pod %v on Node %v is allowed, Node is running only %v out of %v Pods.\", pod, node, len(pods)-1, info.Status.Capacity.Pods().Value())\n\treturn true, nil\n}\n\nfunc NewResourceFitPredicate(info NodeInfo) algorithm.FitPredicate {\n\tfit := &ResourceFit{\n\t\tinfo: info,\n\t}\n\treturn fit.PodFitsResources\n}\n\nfunc NewSelectorMatchPredicate(info NodeInfo) algorithm.FitPredicate {\n\tselector := &NodeSelector{\n\t\tinfo: info,\n\t}\n\treturn selector.PodSelectorMatches\n}\n\nfunc PodMatchesNodeLabels(pod *api.Pod, node *api.Node) bool {\n\tif len(pod.Spec.NodeSelector) == 0 {\n\t\treturn true\n\t}\n\tselector := labels.SelectorFromSet(pod.Spec.NodeSelector)\n\treturn selector.Matches(labels.Set(node.Labels))\n}\n\ntype NodeSelector struct {\n\tinfo NodeInfo\n}\n\nfunc (n *NodeSelector) PodSelectorMatches(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\tminion, err := n.info.GetNodeInfo(node)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn PodMatchesNodeLabels(pod, minion), nil\n}\n\nfunc PodFitsHost(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\tif len(pod.Spec.NodeName) == 0 {\n\t\treturn true, nil\n\t}\n\treturn pod.Spec.NodeName == node, nil\n}\n\ntype NodeLabelChecker struct {\n\tinfo     NodeInfo\n\tlabels   []string\n\tpresence bool\n}\n\nfunc NewNodeLabelPredicate(info NodeInfo, labels []string, presence bool) algorithm.FitPredicate {\n\tlabelChecker := &NodeLabelChecker{\n\t\tinfo:     info,\n\t\tlabels:   labels,\n\t\tpresence: presence,\n\t}\n\treturn labelChecker.CheckNodeLabelPresence\n}\n\n\/\/ CheckNodeLabelPresence checks whether all of the specified labels exists on a minion or not, regardless of their value\n\/\/ If \"presence\" is false, then returns false if any of the requested labels matches any of the minion's labels,\n\/\/ otherwise returns true.\n\/\/ If \"presence\" is true, then returns false if any of the requested labels does not match any of the minion's labels,\n\/\/ otherwise returns true.\n\/\/\n\/\/ Consider the cases where the minions are placed in regions\/zones\/racks and these are identified by labels\n\/\/ In some cases, it is required that only minions that are part of ANY of the defined regions\/zones\/racks be selected\n\/\/\n\/\/ Alternately, eliminating minions that have a certain label, regardless of value, is also useful\n\/\/ A minion may have a label with \"retiring\" as key and the date as the value\n\/\/ and it may be desirable to avoid scheduling new pods on this minion\nfunc (n *NodeLabelChecker) CheckNodeLabelPresence(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\tvar exists bool\n\tminion, err := n.info.GetNodeInfo(node)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tminionLabels := labels.Set(minion.Labels)\n\tfor _, label := range n.labels {\n\t\texists = minionLabels.Has(label)\n\t\tif (exists && !n.presence) || (!exists && n.presence) {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}\n\ntype ServiceAffinity struct {\n\tpodLister     algorithm.PodLister\n\tserviceLister algorithm.ServiceLister\n\tnodeInfo      NodeInfo\n\tlabels        []string\n}\n\nfunc NewServiceAffinityPredicate(podLister algorithm.PodLister, serviceLister algorithm.ServiceLister, nodeInfo NodeInfo, labels []string) algorithm.FitPredicate {\n\taffinity := &ServiceAffinity{\n\t\tpodLister:     podLister,\n\t\tserviceLister: serviceLister,\n\t\tnodeInfo:      nodeInfo,\n\t\tlabels:        labels,\n\t}\n\treturn affinity.CheckServiceAffinity\n}\n\n\/\/ CheckServiceAffinity ensures that only the minions that match the specified labels are considered for scheduling.\n\/\/ The set of labels to be considered are provided to the struct (ServiceAffinity).\n\/\/ The pod is checked for the labels and any missing labels are then checked in the minion\n\/\/ that hosts the service pods (peers) for the given pod.\n\/\/\n\/\/ We add an implicit selector requiring some particular value V for label L to a pod, if:\n\/\/ - L is listed in the ServiceAffinity object that is passed into the function\n\/\/ - the pod does not have any NodeSelector for L\n\/\/ - some other pod from the same service is already scheduled onto a minion that has value V for label L\nfunc (s *ServiceAffinity) CheckServiceAffinity(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\tvar affinitySelector labels.Selector\n\n\t\/\/ check if the pod being scheduled has the affinity labels specified in its NodeSelector\n\taffinityLabels := map[string]string{}\n\tnodeSelector := labels.Set(pod.Spec.NodeSelector)\n\tlabelsExist := true\n\tfor _, l := range s.labels {\n\t\tif nodeSelector.Has(l) {\n\t\t\taffinityLabels[l] = nodeSelector.Get(l)\n\t\t} else {\n\t\t\t\/\/ the current pod does not specify all the labels, look in the existing service pods\n\t\t\tlabelsExist = false\n\t\t}\n\t}\n\n\t\/\/ skip looking at other pods in the service if the current pod defines all the required affinity labels\n\tif !labelsExist {\n\t\tservices, err := s.serviceLister.GetPodServices(pod)\n\t\tif err == nil {\n\t\t\t\/\/ just use the first service and get the other pods within the service\n\t\t\t\/\/ TODO: a separate predicate can be created that tries to handle all services for the pod\n\t\t\tselector := labels.SelectorFromSet(services[0].Spec.Selector)\n\t\t\tservicePods, err := s.podLister.List(selector)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\t\/\/ consider only the pods that belong to the same namespace\n\t\t\tnsServicePods := []*api.Pod{}\n\t\t\tfor _, nsPod := range servicePods {\n\t\t\t\tif nsPod.Namespace == pod.Namespace {\n\t\t\t\t\tnsServicePods = append(nsServicePods, nsPod)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(nsServicePods) > 0 {\n\t\t\t\t\/\/ consider any service pod and fetch the minion its hosted on\n\t\t\t\totherMinion, err := s.nodeInfo.GetNodeInfo(nsServicePods[0].Spec.NodeName)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn false, err\n\t\t\t\t}\n\t\t\t\tfor _, l := range s.labels {\n\t\t\t\t\t\/\/ If the pod being scheduled has the label value specified, do not override it\n\t\t\t\t\tif _, exists := affinityLabels[l]; exists {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif labels.Set(otherMinion.Labels).Has(l) {\n\t\t\t\t\t\taffinityLabels[l] = labels.Set(otherMinion.Labels).Get(l)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ if there are no existing pods in the service, consider all minions\n\tif len(affinityLabels) == 0 {\n\t\taffinitySelector = labels.Everything()\n\t} else {\n\t\taffinitySelector = labels.Set(affinityLabels).AsSelector()\n\t}\n\n\tminion, err := s.nodeInfo.GetNodeInfo(node)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ check if the minion matches the selector\n\treturn affinitySelector.Matches(labels.Set(minion.Labels)), nil\n}\n\nfunc PodFitsPorts(pod *api.Pod, existingPods []*api.Pod, node string) (bool, error) {\n\texistingPorts := getUsedPorts(existingPods...)\n\twantPorts := getUsedPorts(pod)\n\tfor wport := range wantPorts {\n\t\tif wport == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif existingPorts[wport] {\n\t\t\treturn false, nil\n\t\t}\n\t}\n\treturn true, nil\n}\n\nfunc getUsedPorts(pods ...*api.Pod) map[int]bool {\n\tports := make(map[int]bool)\n\tfor _, pod := range pods {\n\t\tfor _, container := range pod.Spec.Containers {\n\t\t\tfor _, podPort := range container.Ports {\n\t\t\t\tports[podPort.HostPort] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn ports\n}\n\nfunc filterNonRunningPods(pods []*api.Pod) []*api.Pod {\n\tif len(pods) == 0 {\n\t\treturn pods\n\t}\n\tresult := []*api.Pod{}\n\tfor _, pod := range pods {\n\t\tif pod.Status.Phase == api.PodSucceeded || pod.Status.Phase == api.PodFailed {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, pod)\n\t}\n\treturn result\n}\n\n\/\/ MapPodsToMachines obtains a list of pods and pivots that list into a map where the keys are host names\n\/\/ and the values are the list of pods running on that host.\nfunc MapPodsToMachines(lister algorithm.PodLister) (map[string][]*api.Pod, error) {\n\tmachineToPods := map[string][]*api.Pod{}\n\t\/\/ TODO: perform more targeted query...\n\tpods, err := lister.List(labels.Everything())\n\tif err != nil {\n\t\treturn map[string][]*api.Pod{}, err\n\t}\n\tpods = filterNonRunningPods(pods)\n\tfor _, scheduledPod := range pods {\n\t\thost := scheduledPod.Spec.NodeName\n\t\tmachineToPods[host] = append(machineToPods[host], scheduledPod)\n\t}\n\treturn machineToPods, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package filesystem_test\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/naoty\/todo\/repository\/filesystem\"\n\t\"github.com\/naoty\/todo\/todo\"\n)\n\nfunc TestGet(t *testing.T) {\n\ttestcases := []struct {\n\t\tinput  int\n\t\toutput *todo.Todo\n\t\terr    error\n\t}{\n\t\t{1, &todo.Todo{ID: 1, Title: \"dummy\", State: todo.Undone}, nil},\n\t\t{2, &todo.Todo{ID: 2, Title: \"dummy\", State: todo.Done}, nil},\n\t\t{3, &todo.Todo{ID: 3, Title: \"dummy\", State: todo.Waiting}, nil},\n\t\t{1000, nil, filesystem.ErrTODONotFound},\n\t}\n\n\trepo, err := filesystem.New(\".\/testdata\/todos\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to initialize repository: %v\", err)\n\t}\n\n\tfor _, testcase := range testcases {\n\t\tname := fmt.Sprintf(\"ID:%d\", testcase.input)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\ttd, err := repo.Get(testcase.input)\n\n\t\t\tif err != nil {\n\t\t\t\tif !errors.Is(err, testcase.err) {\n\t\t\t\t\tt.Errorf(\"got: %v, want: %v\", err, testcase.err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !td.Equal(testcase.output) {\n\t\t\t\tt.Errorf(\"got: %+v, want: %+v\", td, testcase.output)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestList(t *testing.T) {\n\trepo, err := filesystem.New(\".\/testdata\/todos\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to initialize repository: %v\", err)\n\t}\n\n\ttodos, err := repo.List()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to list todos\")\n\t}\n\n\tids := make([]int, 3)\n\tfor i, td := range todos {\n\t\tids[i] = td.ID\n\t}\n\n\twant := []int{2, 1, 3}\n\tif !reflect.DeepEqual(ids, want) {\n\t\tt.Errorf(\"got: %v, want: %v\", ids, want)\n\t}\n}\n\nfunc TestAdd(t *testing.T) {\n\trepo, err := filesystem.New(\".\/testdata\/sandbox\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to initialize repository: %v\", err)\n\t}\n\n\tt.Cleanup(func() {\n\t\terr := os.RemoveAll(\".\/testdata\/sandbox\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to cleanup sandbox: %v\", err)\n\t\t}\n\t})\n\n\tparent := 0\n\terr = repo.Add(\"dummy\", &parent)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to add a TODO\")\n\t}\n\n\ttd, err := repo.Get(1)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get a new TODO\")\n\t}\n\n\tif td.Title != \"dummy\" {\n\t\tt.Errorf(\"got: %s, want: dummy\", td.Title)\n\t}\n\n\tif td.State != todo.Undone {\n\t\tt.Errorf(\"got: %s, want: %s\", td.State, todo.Undone)\n\t}\n\n\tif td.Body != \"\" {\n\t\tt.Errorf(\"got: %s, want: ''\", td.Body)\n\t}\n}\n\nfunc TestUpdate(t *testing.T) {\n\trepo, err := filesystem.New(\".\/testdata\/sandbox\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to initialize repository: %v\", err)\n\t}\n\n\tt.Cleanup(func() {\n\t\terr := os.RemoveAll(\".\/testdata\/sandbox\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to cleanup sandbox: %v\", err)\n\t\t}\n\t})\n\n\tparent := 0\n\terr = repo.Add(\"dummy\", &parent)\n\tif err != nil {\n\t\tt.Fatal(\"failed to add a TODO\")\n\t}\n\n\ttd, err := repo.Get(1)\n\tif err != nil {\n\t\tt.Fatal(\"failed to get a new TODO\")\n\t}\n\n\ttd.State = todo.Done\n\terr = repo.Update(td)\n\tif err != nil {\n\t\tt.Fatal(\"failed to update a TODO\")\n\t}\n\n\ttd, err = repo.Get(1)\n\tif err != nil {\n\t\tt.Fatal(\"failed to get a new TODO\")\n\t}\n\n\tif td.State != todo.Done {\n\t\tt.Errorf(\"got: %s, want: %s\", td.State, todo.Done)\n\t}\n}\n<commit_msg>Add a test for (*FileSystem).Delete()<commit_after>package filesystem_test\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/naoty\/todo\/repository\/filesystem\"\n\t\"github.com\/naoty\/todo\/todo\"\n)\n\nfunc TestGet(t *testing.T) {\n\ttestcases := []struct {\n\t\tinput  int\n\t\toutput *todo.Todo\n\t\terr    error\n\t}{\n\t\t{1, &todo.Todo{ID: 1, Title: \"dummy\", State: todo.Undone}, nil},\n\t\t{2, &todo.Todo{ID: 2, Title: \"dummy\", State: todo.Done}, nil},\n\t\t{3, &todo.Todo{ID: 3, Title: \"dummy\", State: todo.Waiting}, nil},\n\t\t{1000, nil, filesystem.ErrTODONotFound},\n\t}\n\n\trepo, err := filesystem.New(\".\/testdata\/todos\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to initialize repository: %v\", err)\n\t}\n\n\tfor _, testcase := range testcases {\n\t\tname := fmt.Sprintf(\"ID:%d\", testcase.input)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\ttd, err := repo.Get(testcase.input)\n\n\t\t\tif err != nil {\n\t\t\t\tif !errors.Is(err, testcase.err) {\n\t\t\t\t\tt.Errorf(\"got: %v, want: %v\", err, testcase.err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !td.Equal(testcase.output) {\n\t\t\t\tt.Errorf(\"got: %+v, want: %+v\", td, testcase.output)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestList(t *testing.T) {\n\trepo, err := filesystem.New(\".\/testdata\/todos\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to initialize repository: %v\", err)\n\t}\n\n\ttodos, err := repo.List()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to list todos\")\n\t}\n\n\tids := make([]int, 3)\n\tfor i, td := range todos {\n\t\tids[i] = td.ID\n\t}\n\n\twant := []int{2, 1, 3}\n\tif !reflect.DeepEqual(ids, want) {\n\t\tt.Errorf(\"got: %v, want: %v\", ids, want)\n\t}\n}\n\nfunc TestAdd(t *testing.T) {\n\trepo, err := filesystem.New(\".\/testdata\/sandbox\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to initialize repository: %v\", err)\n\t}\n\n\tt.Cleanup(func() {\n\t\terr := os.RemoveAll(\".\/testdata\/sandbox\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to cleanup sandbox: %v\", err)\n\t\t}\n\t})\n\n\tparent := 0\n\terr = repo.Add(\"dummy\", &parent)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to add a TODO\")\n\t}\n\n\ttd, err := repo.Get(1)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get a new TODO\")\n\t}\n\n\tif td.Title != \"dummy\" {\n\t\tt.Errorf(\"got: %s, want: dummy\", td.Title)\n\t}\n\n\tif td.State != todo.Undone {\n\t\tt.Errorf(\"got: %s, want: %s\", td.State, todo.Undone)\n\t}\n\n\tif td.Body != \"\" {\n\t\tt.Errorf(\"got: %s, want: ''\", td.Body)\n\t}\n}\n\nfunc TestUpdate(t *testing.T) {\n\trepo, err := filesystem.New(\".\/testdata\/sandbox\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to initialize repository: %v\", err)\n\t}\n\n\tt.Cleanup(func() {\n\t\terr := os.RemoveAll(\".\/testdata\/sandbox\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to cleanup sandbox: %v\", err)\n\t\t}\n\t})\n\n\tparent := 0\n\terr = repo.Add(\"dummy\", &parent)\n\tif err != nil {\n\t\tt.Fatal(\"failed to add a TODO\")\n\t}\n\n\ttd, err := repo.Get(1)\n\tif err != nil {\n\t\tt.Fatal(\"failed to get a new TODO\")\n\t}\n\n\ttd.State = todo.Done\n\terr = repo.Update(td)\n\tif err != nil {\n\t\tt.Fatal(\"failed to update a TODO\")\n\t}\n\n\ttd, err = repo.Get(1)\n\tif err != nil {\n\t\tt.Fatal(\"failed to get a new TODO\")\n\t}\n\n\tif td.State != todo.Done {\n\t\tt.Errorf(\"got: %s, want: %s\", td.State, todo.Done)\n\t}\n}\n\nfunc TestDelete(t *testing.T) {\n\trepo, err := filesystem.New(\".\/testdata\/sandbox\")\n\tif err != nil {\n\t\tt.Fatalf(\"failed to initialize repository: %v\", err)\n\t}\n\n\tt.Cleanup(func() {\n\t\terr := os.RemoveAll(\".\/testdata\/sandbox\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"failed to cleanup sandbox: %v\", err)\n\t\t}\n\t})\n\n\tparent := 0\n\terr = repo.Add(\"dummy\", &parent)\n\tif err != nil {\n\t\tt.Fatal(\"failed to add a TODO\")\n\t}\n\n\terr = repo.Delete(1)\n\tif err != nil {\n\t\tt.Fatal(\"failed to delete a TODO\")\n\t}\n\n\tif _, err := os.Stat(\".\/testdata\/sandbox\/1.md\"); os.IsExist(err) {\n\t\tt.Error(\"1.md is not deleted\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package analyze\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/bazelbuild\/buildtools\/edit\"\n\t\"github.com\/bazelbuild\/rules_typescript\/ts_auto_deps\/workspace\"\n\t\"github.com\/golang\/protobuf\/proto\"\n\n\tappb \"github.com\/bazelbuild\/buildtools\/build_proto\"\n)\n\n\/\/ pkgCacheEntry represents a set of loaded rules and a mapping from alias\n\/\/ to rules from a package.\ntype pkgCacheEntry struct {\n\t\/\/ rules is all rules in a package.\n\trules []*appb.Rule\n\t\/\/ aliases is a map from an alias label to the actual rule of the alias.\n\taliases map[string]*appb.Rule\n}\n\n\/\/ QueryBasedTargetLoader uses Bazel query to load targets from BUILD files.\ntype QueryBasedTargetLoader struct {\n\tworkdir     string\n\tbazelBinary string\n\n\t\/\/ pkgCache is a mapping from a package to all of the rules in said\n\t\/\/ package along with a map from aliases to actual rules.\n\t\/\/\n\t\/\/ Keys are of the form of \"<visibility>|<package>\" where visibility\n\t\/\/ is the package that rules in package must be visible to and package\n\t\/\/ is the actual package that has been loaded and cached.\n\t\/\/\n\t\/\/ Since a new target loader is constructed for each directory being\n\t\/\/ analyzed in the \"-recursive\" case, these caches will be garbage\n\t\/\/ collected between directories.\n\tpkgCache map[string]*pkgCacheEntry\n\t\/\/ labelCache is a mapping from a label to its loaded rule.\n\tlabelCache map[string]*appb.Rule\n\n\t\/\/ queryCount is the total number of queries executed by the target loader.\n\tqueryCount int\n}\n\n\/\/ NewQueryBasedTargetLoader constructs a new QueryBasedTargetLoader rooted\n\/\/ in workdir.\nfunc NewQueryBasedTargetLoader(workdir, bazelBinary string) *QueryBasedTargetLoader {\n\treturn &QueryBasedTargetLoader{\n\t\tworkdir:     workdir,\n\t\tbazelBinary: bazelBinary,\n\n\t\tpkgCache:   make(map[string]*pkgCacheEntry),\n\t\tlabelCache: make(map[string]*appb.Rule),\n\t}\n}\n\n\/\/ LoadLabels uses Bazel query to load targets associated with labels from BUILD\n\/\/ files.\nfunc (q *QueryBasedTargetLoader) LoadLabels(pkg string, labels []string) (map[string]*appb.Rule, error) {\n\tvar labelCacheMisses []string\n\tfor _, label := range labels {\n\t\tif _, ok := q.labelCache[labelCacheKey(pkg, label)]; !ok {\n\t\t\tlabelCacheMisses = append(labelCacheMisses, label)\n\t\t}\n\t}\n\tif len(labelCacheMisses) > 0 {\n\t\tvar queries []string\n\t\tif pkg == \"\" {\n\t\t\tqueries = labelCacheMisses\n\t\t} else {\n\t\t\tfor _, label := range labelCacheMisses {\n\t\t\t\tqueries = append(queries, fmt.Sprintf(\"visible(%s:*, %s)\", pkg, label))\n\t\t\t}\n\t\t}\n\t\tr, err := q.batchQuery(queries)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, target := range r.GetTarget() {\n\t\t\tlabel, err := q.ruleLabel(target)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tq.labelCache[labelCacheKey(pkg, label)] = target.GetRule()\n\t\t}\n\t\tfor _, label := range labelCacheMisses {\n\t\t\tkey := labelCacheKey(pkg, label)\n\t\t\tif _, ok := q.labelCache[key]; !ok {\n\t\t\t\t\/\/ Set to nil so the result exists in the cache and is not\n\t\t\t\t\/\/ loaded again. If the nil is not added at the appropriate\n\t\t\t\t\/\/ cache key, LoadLabels will attempt to load it again when\n\t\t\t\t\/\/ next requested instead of getting a cache hit.\n\t\t\t\tq.labelCache[key] = nil\n\t\t\t}\n\t\t}\n\t}\n\tlabelToRule := make(map[string]*appb.Rule)\n\tfor _, label := range labels {\n\t\tlabelToRule[label] = q.labelCache[labelCacheKey(pkg, label)]\n\t}\n\treturn labelToRule, nil\n}\n\nfunc labelCacheKey(currentPkg, label string) string {\n\treturn currentPkg + \"^\" + label\n}\n\n\/\/ LoadImportPaths uses Bazel Query to load targets associated with import\n\/\/ paths from BUILD files.\nfunc (q *QueryBasedTargetLoader) LoadImportPaths(ctx context.Context, currentPkg, workspaceRoot string, paths []string) (map[string]*appb.Rule, error) {\n\tdebugf(\"loading imports visible to %q relative to %q: %q\", currentPkg, workspaceRoot, paths)\n\tresults := make(map[string]*appb.Rule)\n\n\taddedPaths := make(map[string]bool)\n\tvar possiblePaths []string\n\tfor _, path := range paths {\n\t\tif strings.HasPrefix(path, \"goog:\") {\n\t\t\t\/\/ 'goog:' imports are resolved using an sstable.\n\t\t\tresults[path] = nil\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.HasPrefix(path, \"@\") {\n\t\t\tif _, ok := addedPaths[path]; !ok {\n\t\t\t\taddedPaths[path] = true\n\n\t\t\t\t\/\/ If the path has a suffix of \".ngfactory\" or \".ngsummary\", it might\n\t\t\t\t\/\/ be an Angular AOT generated file. We can infer the target as we\n\t\t\t\t\/\/ infer its corresponding ngmodule target by simply stripping the\n\t\t\t\t\/\/ \".ngfactory\" \/ \".ngsummary\" suffix\n\t\t\t\tpath = strings.TrimSuffix(strings.TrimSuffix(path, \".ngsummary\"), \".ngfactory\")\n\t\t\t\tpath = strings.TrimPrefix(path, workspace.Name()+\"\/\")\n\n\t\t\t\tpossiblePaths = append(possiblePaths, pathWithExtensions(path)...)\n\t\t\t\tpossiblePaths = append(possiblePaths, pathWithExtensions(filepath.Join(path, \"index\"))...)\n\t\t\t}\n\t\t}\n\t}\n\n\tr, err := q.batchQuery(possiblePaths)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar sourceFileLabels, generators []string\n\tgeneratorsToFiles := make(map[string][]*appb.GeneratedFile)\n\tfor _, target := range r.GetTarget() {\n\t\tlabel, err := q.fileLabel(target)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch target.GetType() {\n\t\tcase appb.Target_GENERATED_FILE:\n\t\t\tfile := target.GetGeneratedFile()\n\t\t\tgenerator := file.GetGeneratingRule()\n\n\t\t\tgenerators = append(generators, generator)\n\t\t\tgeneratorsToFiles[generator] = append(generatorsToFiles[generator], file)\n\t\tcase appb.Target_SOURCE_FILE:\n\t\t\tsourceFileLabels = append(sourceFileLabels, label)\n\t\t}\n\t}\n\n\tlabelToRule := make(map[string]*appb.Rule)\n\tfor len(generators) > 0 {\n\t\tgeneratorToRule, err := q.LoadLabels(currentPkg, generators)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar newGenerators []string\n\t\tfor label, rule := range generatorToRule {\n\t\t\t_, _, target := edit.ParseLabel(label)\n\t\t\tif generator := stringAttribute(rule, \"generator_name\"); generator != \"\" && generator != target {\n\t\t\t\t\/\/ Located rule is also a generated rule. Look for the rule\n\t\t\t\t\/\/ that generates it.\n\t\t\t\t_, pkg, _ := edit.ParseLabel(label)\n\t\t\t\tnewLabel := \"\/\/\" + pkg + \":\" + generator\n\t\t\t\tnewGenerators = append(newGenerators, newLabel)\n\t\t\t\tgeneratorsToFiles[newLabel] = generatorsToFiles[label]\n\t\t\t} else {\n\t\t\t\tfor _, generated := range generatorsToFiles[label] {\n\t\t\t\t\tlabelToRule[generated.GetName()] = rule\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgenerators = newGenerators\n\t}\n\n\tsourceLabelToRule, err := q.loadRulesIncludingSourceFiles(workspaceRoot, sourceFileLabels)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor label, rule := range sourceLabelToRule {\n\t\tlabelToRule[label] = rule\n\t}\n\n\tfor label, rule := range labelToRule {\n\t\t_, pkg, file := edit.ParseLabel(label)\n\t\t\/\/ Trim \"\/index\" suffixes that were added to path in the queries above.\n\t\tpathWithoutExtension := strings.TrimSuffix(filepath.Join(pkg, stripTSExtension(file)), string(filepath.Separator)+\"index\")\n\t\tfor _, path := range paths {\n\t\t\tif pathWithoutExtension == strings.TrimSuffix(path, string(filepath.Separator)+\"index\") {\n\t\t\t\tresults[path] = rule\n\t\t\t} else if pathWithoutExtension == strings.TrimSuffix(path, \".ngsummary\") {\n\t\t\t\tresults[path] = rule\n\t\t\t} else if pathWithoutExtension == strings.TrimSuffix(path, \".ngfactory\") {\n\t\t\t\tresults[path] = rule\n\t\t\t}\n\t\t}\n\t}\n\n\treturn results, nil\n}\n\nfunc (q *QueryBasedTargetLoader) ruleLabel(target *appb.Target) (string, error) {\n\tif t := target.GetType(); t != appb.Target_RULE {\n\t\treturn \"\", fmt.Errorf(\"target contains object of type %q instead of type %q\", t, appb.Target_RULE)\n\t}\n\treturn target.GetRule().GetName(), nil\n}\n\nfunc (q *QueryBasedTargetLoader) fileLabel(target *appb.Target) (string, error) {\n\tswitch t := target.GetType(); t {\n\tcase appb.Target_GENERATED_FILE:\n\t\treturn target.GetGeneratedFile().GetName(), nil\n\tcase appb.Target_SOURCE_FILE:\n\t\treturn target.GetSourceFile().GetName(), nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"target contains object of type %q instead of type %q or %q\", t, appb.Target_SOURCE_FILE, appb.Target_GENERATED_FILE)\n\t}\n}\n\n\/\/ loadRuleIncludingSourceFiles loads all rules which include labels in\n\/\/ sourceFileLabels, Returns a map from source file label to the rule which\n\/\/ includes it.\nfunc (q *QueryBasedTargetLoader) loadRulesIncludingSourceFiles(workspaceRoot string, sourceFileLabels []string) (map[string]*appb.Rule, error) {\n\tpkgToLabels := make(map[string][]string)\n\tqueries := make([]string, 0, len(sourceFileLabels))\n\tfor _, label := range sourceFileLabels {\n\t\t_, pkg, file := edit.ParseLabel(label)\n\t\tpkgToLabels[pkg] = append(pkgToLabels[pkg], label)\n\t\t\/\/ Query for all targets in the package which use file.\n\t\tqueries = append(queries, fmt.Sprintf(\"attr('srcs', %s, \/\/%s:*)\", file, pkg))\n\t}\n\tr, err := q.batchQuery(queries)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlabelToRule := make(map[string]*appb.Rule)\n\tfor _, target := range r.GetTarget() {\n\t\tlabel, err := q.ruleLabel(target)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trule := target.GetRule()\n\t\t_, pkg, _ := edit.ParseLabel(label)\n\t\tlabels := pkgToLabels[pkg]\n\t\tfor _, src := range listAttribute(rule, \"srcs\") {\n\t\t\tfor _, l := range labels {\n\t\t\t\tif src == l {\n\t\t\t\t\tlabelToRule[l] = rule\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn labelToRule, nil\n}\n\n\/\/ batchQuery runs a set of queries with a single call to Bazel query and the\n\/\/ '--keep_going' flag.\nfunc (q *QueryBasedTargetLoader) batchQuery(queries []string) (*appb.QueryResult, error) {\n\t\/\/ Join all of the queries with a '+' character according to Bazel's\n\t\/\/ syntax for running multiple queries.\n\treturn q.query(\"--keep_going\", strings.Join(queries, \"+\"))\n}\n\nfunc (q *QueryBasedTargetLoader) query(args ...string) (*appb.QueryResult, error) {\n\tn := len(args)\n\tif n < 1 {\n\t\treturn nil, fmt.Errorf(\"expected at least one argument\")\n\t}\n\tquery := args[n-1]\n\tif query == \"\" {\n\t\t\/\/ An empty query was provided so return an empty result without\n\t\t\/\/ making a call to Bazel.\n\t\treturn &appb.QueryResult{}, nil\n\t}\n\tvar stdout, stderr bytes.Buffer\n\targs = append([]string{\"query\", \"--output=proto\"}, args...)\n\tq.queryCount++\n\tdebugf(\"executing query #%d in %q: %s %s %q\", q.queryCount, q.workdir, q.bazelBinary, strings.Join(args[:len(args)-1], \" \"), query)\n\tcmd := exec.Command(q.bazelBinary, args...)\n\tcmd.Dir = q.workdir\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\tstartTime := time.Now()\n\tif err := cmd.Run(); err != nil {\n\t\t\/\/ Exit status 3 is a direct result of one or more queries in a set of\n\t\t\/\/ queries not returning a result while running with the '--keep_going'\n\t\t\/\/ flag. Since one query failing to return a result does not hinder the\n\t\t\/\/ other queries from returning a result, ignore these errors.\n\t\tif err.Error() != \"exit status 3\" {\n\t\t\t\/\/ The error provided as a result is less useful than the contents of\n\t\t\t\/\/ stderr for debugging.\n\t\t\treturn nil, fmt.Errorf(stderr.String())\n\t\t}\n\t}\n\tdebugf(\"query #%d took %v\", q.queryCount, time.Since(startTime))\n\tvar result appb.QueryResult\n\tif err := proto.Unmarshal(stdout.Bytes(), &result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}\n\n\/\/ dedupeLabels returns a new set of labels with no duplicates.\nfunc dedupeLabels(labels []string) []string {\n\taddedLabels := make(map[string]bool)\n\tvar uniqueLabels []string\n\tfor _, label := range labels {\n\t\tif _, added := addedLabels[label]; !added {\n\t\t\taddedLabels[label] = true\n\t\t\tuniqueLabels = append(uniqueLabels, label)\n\t\t}\n\t}\n\treturn uniqueLabels\n}\n\n\/\/ isTazeManagedRuleClass checks if a class is a ts_auto_deps-managed rule class.\nfunc isTazeManagedRuleClass(class string) bool {\n\tfor _, c := range []string{\n\t\t\"ts_library\",\n\t\t\/\/ TODO(alexeagle): Add ts_declaration once it can be determined\n\t\t\/\/ if they are unused.\n\t\t\"ng_module\",\n\t\t\"js_library\",\n\t} {\n\t\tif c == class {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ typeScriptRules returns all TypeScript rules in rules.\nfunc typeScriptRules(rules []*appb.Rule) []*appb.Rule {\n\tvar tsRules []*appb.Rule\n\tfor _, rule := range rules {\n\t\tfor _, supportedRuleClass := range []string{\n\t\t\t\"ts_library\",\n\t\t\t\"ts_declaration\",\n\t\t\t\"ng_module\",\n\t\t} {\n\t\t\tif rule.GetRuleClass() == supportedRuleClass {\n\t\t\t\ttsRules = append(tsRules, rule)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn tsRules\n}\n\n\/\/ resolveAgainstModuleRoot resolves imported against moduleRoot and moduleName.\nfunc resolveAgainstModuleRoot(label, moduleRoot, moduleName, imported string) string {\n\tif moduleRoot == \"\" && moduleName == \"\" {\n\t\treturn imported\n\t}\n\ttrim := strings.TrimPrefix(imported, moduleName)\n\tif trim == imported {\n\t\treturn imported\n\t}\n\t_, pkg, _ := edit.ParseLabel(label)\n\treturn filepath.Join(pkg, moduleRoot, trim)\n}\n\n\/\/ parsePackageName parses and returns the scope and package of imported. For\n\/\/ example, \"@foo\/bar\" would have a scope of \"@foo\" and a package of \"bar\".\nfunc parsePackageName(imported string) (string, string) {\n\tfirstSlash := strings.Index(imported, \"\/\")\n\tif firstSlash == -1 {\n\t\treturn imported, \"\"\n\t}\n\tafterSlash := imported[firstSlash+1:]\n\tif secondSlash := strings.Index(afterSlash, \"\/\"); secondSlash > -1 {\n\t\treturn imported[:firstSlash], afterSlash[:secondSlash]\n\t}\n\treturn imported[:firstSlash], afterSlash\n}\n<commit_msg>No external change<commit_after>package analyze\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/bazelbuild\/buildtools\/edit\"\n\t\"github.com\/bazelbuild\/rules_typescript\/ts_auto_deps\/workspace\"\n\t\"github.com\/golang\/protobuf\/proto\"\n\n\tappb \"github.com\/bazelbuild\/buildtools\/build_proto\"\n)\n\n\/\/ pkgCacheEntry represents a set of loaded rules and a mapping from alias\n\/\/ to rules from a package.\ntype pkgCacheEntry struct {\n\t\/\/ rules is all rules in a package.\n\trules []*appb.Rule\n\t\/\/ aliases is a map from an alias label to the actual rule of the alias.\n\taliases map[string]*appb.Rule\n}\n\n\/\/ QueryBasedTargetLoader uses Bazel query to load targets from BUILD files.\ntype QueryBasedTargetLoader struct {\n\tworkdir     string\n\tbazelBinary string\n\n\t\/\/ pkgCache is a mapping from a package to all of the rules in said\n\t\/\/ package along with a map from aliases to actual rules.\n\t\/\/\n\t\/\/ Keys are of the form of \"<visibility>|<package>\" where visibility\n\t\/\/ is the package that rules in package must be visible to and package\n\t\/\/ is the actual package that has been loaded and cached.\n\t\/\/\n\t\/\/ Since a new target loader is constructed for each directory being\n\t\/\/ analyzed in the \"-recursive\" case, these caches will be garbage\n\t\/\/ collected between directories.\n\tpkgCache map[string]*pkgCacheEntry\n\t\/\/ labelCache is a mapping from a label to its loaded rule.\n\tlabelCache map[string]*appb.Rule\n\n\t\/\/ queryCount is the total number of queries executed by the target loader.\n\tqueryCount int\n}\n\n\/\/ NewQueryBasedTargetLoader constructs a new QueryBasedTargetLoader rooted\n\/\/ in workdir.\nfunc NewQueryBasedTargetLoader(workdir, bazelBinary string) *QueryBasedTargetLoader {\n\treturn &QueryBasedTargetLoader{\n\t\tworkdir:     workdir,\n\t\tbazelBinary: bazelBinary,\n\n\t\tpkgCache:   make(map[string]*pkgCacheEntry),\n\t\tlabelCache: make(map[string]*appb.Rule),\n\t}\n}\n\n\/\/ LoadLabels uses Bazel query to load targets associated with labels from BUILD\n\/\/ files.\nfunc (q *QueryBasedTargetLoader) LoadLabels(pkg string, labels []string) (map[string]*appb.Rule, error) {\n\tvar labelCacheMisses []string\n\tfor _, label := range labels {\n\t\tif _, ok := q.labelCache[labelCacheKey(pkg, label)]; !ok {\n\t\t\tlabelCacheMisses = append(labelCacheMisses, label)\n\t\t}\n\t}\n\tif len(labelCacheMisses) > 0 {\n\t\tvar queries []string\n\t\tif pkg == \"\" {\n\t\t\tqueries = labelCacheMisses\n\t\t} else {\n\t\t\tfor _, label := range labelCacheMisses {\n\t\t\t\tqueries = append(queries, fmt.Sprintf(\"visible(%s:*, %s)\", pkg, label))\n\t\t\t}\n\t\t}\n\t\tr, err := q.batchQuery(queries)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, target := range r.GetTarget() {\n\t\t\tlabel, err := q.ruleLabel(target)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tq.labelCache[labelCacheKey(pkg, label)] = target.GetRule()\n\t\t}\n\t\tfor _, label := range labelCacheMisses {\n\t\t\tkey := labelCacheKey(pkg, label)\n\t\t\tif _, ok := q.labelCache[key]; !ok {\n\t\t\t\t\/\/ Set to nil so the result exists in the cache and is not\n\t\t\t\t\/\/ loaded again. If the nil is not added at the appropriate\n\t\t\t\t\/\/ cache key, LoadLabels will attempt to load it again when\n\t\t\t\t\/\/ next requested instead of getting a cache hit.\n\t\t\t\tq.labelCache[key] = nil\n\t\t\t}\n\t\t}\n\t}\n\tlabelToRule := make(map[string]*appb.Rule)\n\tfor _, label := range labels {\n\t\tlabelToRule[label] = q.labelCache[labelCacheKey(pkg, label)]\n\t}\n\treturn labelToRule, nil\n}\n\nfunc labelCacheKey(currentPkg, label string) string {\n\treturn currentPkg + \"^\" + label\n}\n\n\/\/ LoadImportPaths uses Bazel Query to load targets associated with import\n\/\/ paths from BUILD files.\nfunc (q *QueryBasedTargetLoader) LoadImportPaths(ctx context.Context, currentPkg, workspaceRoot string, paths []string) (map[string]*appb.Rule, error) {\n\tdebugf(\"loading imports visible to %q relative to %q: %q\", currentPkg, workspaceRoot, paths)\n\tresults := make(map[string]*appb.Rule)\n\n\taddedPaths := make(map[string]bool)\n\tvar possiblePaths []string\n\tfor _, path := range paths {\n\t\tif strings.HasPrefix(path, \"goog:\") {\n\t\t\t\/\/ 'goog:' imports are resolved using an sstable.\n\t\t\tresults[path] = nil\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.HasPrefix(path, \"@\") {\n\t\t\tif _, ok := addedPaths[path]; !ok {\n\t\t\t\taddedPaths[path] = true\n\n\t\t\t\t\/\/ If the path has a suffix of \".ngfactory\" or \".ngsummary\", it might\n\t\t\t\t\/\/ be an Angular AOT generated file. We can infer the target as we\n\t\t\t\t\/\/ infer its corresponding ngmodule target by simply stripping the\n\t\t\t\t\/\/ \".ngfactory\" \/ \".ngsummary\" suffix\n\t\t\t\tpath = strings.TrimSuffix(strings.TrimSuffix(path, \".ngsummary\"), \".ngfactory\")\n\t\t\t\tpath = strings.TrimPrefix(path, workspace.Name()+\"\/\")\n\n\t\t\t\tpossiblePaths = append(possiblePaths, pathWithExtensions(path)...)\n\t\t\t\tpossiblePaths = append(possiblePaths, pathWithExtensions(filepath.Join(path, \"index\"))...)\n\t\t\t}\n\t\t}\n\t}\n\n\tr, err := q.batchQuery(possiblePaths)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar sourceFileLabels, generators []string\n\tgeneratorsToFiles := make(map[string][]*appb.GeneratedFile)\n\tfor _, target := range r.GetTarget() {\n\t\tlabel, err := q.fileLabel(target)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch target.GetType() {\n\t\tcase appb.Target_GENERATED_FILE:\n\t\t\tfile := target.GetGeneratedFile()\n\t\t\tgenerator := file.GetGeneratingRule()\n\n\t\t\tgenerators = append(generators, generator)\n\t\t\tgeneratorsToFiles[generator] = append(generatorsToFiles[generator], file)\n\t\tcase appb.Target_SOURCE_FILE:\n\t\t\tsourceFileLabels = append(sourceFileLabels, label)\n\t\t}\n\t}\n\n\tlabelToRule := make(map[string]*appb.Rule)\n\tfor len(generators) > 0 {\n\t\tgeneratorToRule, err := q.LoadLabels(currentPkg, generators)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar newGenerators []string\n\t\tfor label, rule := range generatorToRule {\n\t\t\t_, _, target := edit.ParseLabel(label)\n\n\t\t\tif generator := stringAttribute(rule, \"generator_name\"); generator != \"\" && generator != target {\n\t\t\t\t\/\/ Located rule is also a generated rule. Look for the rule\n\t\t\t\t\/\/ that generates it.\n\t\t\t\t_, pkg, _ := edit.ParseLabel(label)\n\t\t\t\tnewLabel := \"\/\/\" + pkg + \":\" + generator\n\t\t\t\tnewGenerators = append(newGenerators, newLabel)\n\t\t\t\tgeneratorsToFiles[newLabel] = generatorsToFiles[label]\n\t\t\t} else {\n\t\t\t\tfor _, generated := range generatorsToFiles[label] {\n\t\t\t\t\tlabelToRule[generated.GetName()] = rule\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgenerators = newGenerators\n\t}\n\n\tsourceLabelToRule, err := q.loadRulesIncludingSourceFiles(workspaceRoot, sourceFileLabels)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor label, rule := range sourceLabelToRule {\n\t\tlabelToRule[label] = rule\n\t}\n\n\tfor label, rule := range labelToRule {\n\t\t_, pkg, file := edit.ParseLabel(label)\n\t\t\/\/ Trim \"\/index\" suffixes that were added to path in the queries above.\n\t\tpathWithoutExtension := strings.TrimSuffix(filepath.Join(pkg, stripTSExtension(file)), string(filepath.Separator)+\"index\")\n\t\tfor _, path := range paths {\n\t\t\tif pathWithoutExtension == strings.TrimSuffix(path, string(filepath.Separator)+\"index\") {\n\t\t\t\tresults[path] = rule\n\t\t\t} else if pathWithoutExtension == strings.TrimSuffix(path, \".ngsummary\") {\n\t\t\t\tresults[path] = rule\n\t\t\t} else if pathWithoutExtension == strings.TrimSuffix(path, \".ngfactory\") {\n\t\t\t\tresults[path] = rule\n\t\t\t}\n\t\t}\n\t}\n\n\treturn results, nil\n}\n\nfunc (q *QueryBasedTargetLoader) ruleLabel(target *appb.Target) (string, error) {\n\tif t := target.GetType(); t != appb.Target_RULE {\n\t\treturn \"\", fmt.Errorf(\"target contains object of type %q instead of type %q\", t, appb.Target_RULE)\n\t}\n\treturn target.GetRule().GetName(), nil\n}\n\nfunc (q *QueryBasedTargetLoader) fileLabel(target *appb.Target) (string, error) {\n\tswitch t := target.GetType(); t {\n\tcase appb.Target_GENERATED_FILE:\n\t\treturn target.GetGeneratedFile().GetName(), nil\n\tcase appb.Target_SOURCE_FILE:\n\t\treturn target.GetSourceFile().GetName(), nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"target contains object of type %q instead of type %q or %q\", t, appb.Target_SOURCE_FILE, appb.Target_GENERATED_FILE)\n\t}\n}\n\n\/\/ loadRuleIncludingSourceFiles loads all rules which include labels in\n\/\/ sourceFileLabels, Returns a map from source file label to the rule which\n\/\/ includes it.\nfunc (q *QueryBasedTargetLoader) loadRulesIncludingSourceFiles(workspaceRoot string, sourceFileLabels []string) (map[string]*appb.Rule, error) {\n\tpkgToLabels := make(map[string][]string)\n\tqueries := make([]string, 0, len(sourceFileLabels))\n\tfor _, label := range sourceFileLabels {\n\t\t_, pkg, file := edit.ParseLabel(label)\n\t\tpkgToLabels[pkg] = append(pkgToLabels[pkg], label)\n\t\t\/\/ Query for all targets in the package which use file.\n\t\tqueries = append(queries, fmt.Sprintf(\"attr('srcs', %s, \/\/%s:*)\", file, pkg))\n\t}\n\tr, err := q.batchQuery(queries)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlabelToRule := make(map[string]*appb.Rule)\n\tfor _, target := range r.GetTarget() {\n\t\tlabel, err := q.ruleLabel(target)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trule := target.GetRule()\n\t\t_, pkg, _ := edit.ParseLabel(label)\n\t\tlabels := pkgToLabels[pkg]\n\t\tfor _, src := range listAttribute(rule, \"srcs\") {\n\t\t\tfor _, l := range labels {\n\t\t\t\tif src == l {\n\t\t\t\t\tlabelToRule[l] = rule\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn labelToRule, nil\n}\n\n\/\/ batchQuery runs a set of queries with a single call to Bazel query and the\n\/\/ '--keep_going' flag.\nfunc (q *QueryBasedTargetLoader) batchQuery(queries []string) (*appb.QueryResult, error) {\n\t\/\/ Join all of the queries with a '+' character according to Bazel's\n\t\/\/ syntax for running multiple queries.\n\treturn q.query(\"--keep_going\", strings.Join(queries, \"+\"))\n}\n\nfunc (q *QueryBasedTargetLoader) query(args ...string) (*appb.QueryResult, error) {\n\tn := len(args)\n\tif n < 1 {\n\t\treturn nil, fmt.Errorf(\"expected at least one argument\")\n\t}\n\tquery := args[n-1]\n\tif query == \"\" {\n\t\t\/\/ An empty query was provided so return an empty result without\n\t\t\/\/ making a call to Bazel.\n\t\treturn &appb.QueryResult{}, nil\n\t}\n\tvar stdout, stderr bytes.Buffer\n\targs = append([]string{\"query\", \"--output=proto\"}, args...)\n\tq.queryCount++\n\tdebugf(\"executing query #%d in %q: %s %s %q\", q.queryCount, q.workdir, q.bazelBinary, strings.Join(args[:len(args)-1], \" \"), query)\n\tcmd := exec.Command(q.bazelBinary, args...)\n\tcmd.Dir = q.workdir\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\tstartTime := time.Now()\n\tif err := cmd.Run(); err != nil {\n\t\t\/\/ Exit status 3 is a direct result of one or more queries in a set of\n\t\t\/\/ queries not returning a result while running with the '--keep_going'\n\t\t\/\/ flag. Since one query failing to return a result does not hinder the\n\t\t\/\/ other queries from returning a result, ignore these errors.\n\t\tif err.Error() != \"exit status 3\" {\n\t\t\t\/\/ The error provided as a result is less useful than the contents of\n\t\t\t\/\/ stderr for debugging.\n\t\t\treturn nil, fmt.Errorf(stderr.String())\n\t\t}\n\t}\n\tdebugf(\"query #%d took %v\", q.queryCount, time.Since(startTime))\n\tvar result appb.QueryResult\n\tif err := proto.Unmarshal(stdout.Bytes(), &result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}\n\n\/\/ dedupeLabels returns a new set of labels with no duplicates.\nfunc dedupeLabels(labels []string) []string {\n\taddedLabels := make(map[string]bool)\n\tvar uniqueLabels []string\n\tfor _, label := range labels {\n\t\tif _, added := addedLabels[label]; !added {\n\t\t\taddedLabels[label] = true\n\t\t\tuniqueLabels = append(uniqueLabels, label)\n\t\t}\n\t}\n\treturn uniqueLabels\n}\n\n\/\/ isTazeManagedRuleClass checks if a class is a ts_auto_deps-managed rule class.\nfunc isTazeManagedRuleClass(class string) bool {\n\tfor _, c := range []string{\n\t\t\"ts_library\",\n\t\t\/\/ TODO(alexeagle): Add ts_declaration once it can be determined\n\t\t\/\/ if they are unused.\n\t\t\"ng_module\",\n\t\t\"js_library\",\n\t} {\n\t\tif c == class {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ typeScriptRules returns all TypeScript rules in rules.\nfunc typeScriptRules(rules []*appb.Rule) []*appb.Rule {\n\tvar tsRules []*appb.Rule\n\tfor _, rule := range rules {\n\t\tfor _, supportedRuleClass := range []string{\n\t\t\t\"ts_library\",\n\t\t\t\"ts_declaration\",\n\t\t\t\"ng_module\",\n\t\t} {\n\t\t\tif rule.GetRuleClass() == supportedRuleClass {\n\t\t\t\ttsRules = append(tsRules, rule)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn tsRules\n}\n\n\/\/ resolveAgainstModuleRoot resolves imported against moduleRoot and moduleName.\nfunc resolveAgainstModuleRoot(label, moduleRoot, moduleName, imported string) string {\n\tif moduleRoot == \"\" && moduleName == \"\" {\n\t\treturn imported\n\t}\n\ttrim := strings.TrimPrefix(imported, moduleName)\n\tif trim == imported {\n\t\treturn imported\n\t}\n\t_, pkg, _ := edit.ParseLabel(label)\n\treturn filepath.Join(pkg, moduleRoot, trim)\n}\n\n\/\/ parsePackageName parses and returns the scope and package of imported. For\n\/\/ example, \"@foo\/bar\" would have a scope of \"@foo\" and a package of \"bar\".\nfunc parsePackageName(imported string) (string, string) {\n\tfirstSlash := strings.Index(imported, \"\/\")\n\tif firstSlash == -1 {\n\t\treturn imported, \"\"\n\t}\n\tafterSlash := imported[firstSlash+1:]\n\tif secondSlash := strings.Index(afterSlash, \"\/\"); secondSlash > -1 {\n\t\treturn imported[:firstSlash], afterSlash[:secondSlash]\n\t}\n\treturn imported[:firstSlash], afterSlash\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\/\/\"fmt\"\n\t\"delay\"\n\t\"sync\/atomic\"\n\n\t\"nrf5\/ppipwm\"\n)\n\nconst (\n\tpwmNum  = 24\n\tstepRPM = 1 << 5\n\tminRPM  = 420\n\tmaxRPM  = minRPM + (pwmNum-1)*stepRPM\n\tdivP    = 8\n\tdivI    = 64\n\tdivD    = 16\n)\n\ntype fan struct {\n\trpmToPWM  [pwmNum]byte\n\ttargetRPM int\n\tsum       int\n\tlastE     int\n}\n\nfunc (f *fan) TargetRPM() int {\n\treturn atomic.LoadInt(&f.targetRPM)\n}\n\nfunc (f *fan) SetTargetRPM(rpm int) {\n\tatomic.StoreInt(&f.targetRPM, rpm)\n}\n\nfunc (f *fan) NextE(e, maxSum int) (sum, diff int) {\n\tsum = f.sum + e\n\tif sum > maxSum {\n\t\tsum = maxSum\n\t} else if sum < -maxSum {\n\t\tsum = -maxSum\n\t}\n\tf.sum = sum\n\tdiff = e - f.lastE\n\tf.lastE = e\n\treturn sum, diff\n}\n\nfunc (f *fan) ResetE() {\n\tf.sum = 0\n\tf.lastE = 0\n}\n\nfunc (f *fan) ModelPWM(rpm int) int {\n\tr := rpm - minRPM\n\tn := r \/ stepRPM\n\tm := r & (stepRPM - 1)\n\tif n < 0 {\n\t\treturn 0\n\t}\n\tif n >= len(f.rpmToPWM)-1 {\n\t\treturn int(f.rpmToPWM[len(f.rpmToPWM)-1])\n\t}\n\ta := int(f.rpmToPWM[n])\n\tb := int(f.rpmToPWM[n+1])\n\treturn ((stepRPM-m)*a + m*b) \/ stepRPM\n}\n\nfunc (f *fan) SetModelPWM(n, pwm int) {\n\tf.rpmToPWM[n] = byte(pwm)\n}\n\nfunc (f *fan) FixModel(trouble bool) bool {\n\tif trouble {\n\t\t\/\/ TODO: If trouble analyze rpmToPWM to detect broken fan.\n\n\t\treturn false\n\t}\n\t\/\/ Fix single gaps in rpmToPWM.\n\tfor i, pwm := range f.rpmToPWM {\n\t\tif pwm != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tswitch {\n\t\tcase i == 0:\n\t\t\tpwm = f.rpmToPWM[i+1]\n\t\tcase i == pwmNum-1:\n\t\t\tpwm = f.rpmToPWM[i-1]\n\t\tdefault:\n\t\t\tpwm = byte((int(f.rpmToPWM[i-1]) + int(f.rpmToPWM[i+1])) \/ 2)\n\t\t}\n\t\tif pwm == 0 {\n\t\t\treturn false\n\t\t}\n\t\tf.rpmToPWM[i] = pwm\n\t}\n\treturn true\n}\n\ntype FanControl struct {\n\tpwm  *ppipwm.Toggle\n\ttach *Tachometer\n\tfans [2]fan\n\tmaxI int\n}\n\nfunc NewFanControl(pwm *ppipwm.Toggle, tach *Tachometer) *FanControl {\n\tfc := new(FanControl)\n\tfc.pwm = pwm\n\tfc.tach = tach\n\treturn fc\n}\n\nfunc (fc *FanControl) MaxRPM() int {\n\treturn maxRPM\n}\n\nfunc (fc *FanControl) TargetRPM(n int) int {\n\treturn fc.fans[n].TargetRPM()\n}\n\nfunc (fc *FanControl) SetTargetRPM(n, rpm int) {\n\tfan := &fc.fans[n]\n\tif fan.TargetRPM() < 0 {\n\t\treturn \/\/ Disabled.\n\t}\n\tif rpm < 0 {\n\t\trpm = 0\n\t} else if rpm > maxRPM {\n\t\trpm = maxRPM\n\t}\n\tfan.SetTargetRPM(rpm)\n}\n\nfunc (fc *FanControl) RPM(n int) int {\n\treturn fc.tach.RPM(n)\n}\n\nfunc (fc *FanControl) TachISR() {\n\tn := fc.tach.ISR()\n\tfan := &fc.fans[n]\n\ttargetRPM := fan.TargetRPM()\n\tif targetRPM < 0 {\n\t\treturn\n\t}\n\tdc := 0\n\tif targetRPM >= minRPM {\n\t\tmodelPWM := fan.ModelPWM(targetRPM)\n\t\trpm := fc.RPM(n)\n\t\te := targetRPM - rpm\n\t\tsum, diff := fan.NextE(e, fc.maxI)\n\t\tdc = modelPWM + e\/divP + sum\/divI + diff\/divD\n\t} else {\n\t\tfan.ResetE()\n\t}\n\tfc.pwm.SetInv(n, dc)\n}\n\nfunc (fc *FanControl) Identify() {\n\tfor n := range fc.fans {\n\t\tfan := &fc.fans[n]\n\t\tfan.SetTargetRPM(-1) \/\/ Prevent useing PWM by TachISR.\n\t\tfc.pwm.SetInv(n, 0)\n\t\tfor i := range fan.rpmToPWM {\n\t\t\tfan.rpmToPWM[i] = 0\n\t\t}\n\t}\n\tmaxPWM := fc.pwm.Max()*3\/4\n\tif maxPWM > 255 {\n\t\tpanic(\"maxPWM>255\")\n\t}\n\ttodo := uint(1<<uint(len(fc.fans)) - 1)\n\tfor pwm := 33; pwm <= maxPWM && todo != 0; pwm++ {\n\t\tatomic.StoreInt(&fc.maxI, pwm-maxPWM) \/\/ Progress\n\t\tfc.pwm.SetManyInv(todo, pwm, pwm, pwm)\n\t\tdelay.Millisec(500)\n\t\tfor n := range fc.fans {\n\t\t\tfanMask := uint(1 << uint(n))\n\t\t\tif todo&fanMask == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trpm := fc.RPM(n)\n\t\t\tm := (rpm - minRPM + stepRPM - 1) \/ stepRPM\n\t\t\t\/\/fmt.Printf(\"%d: %d %d\\n\", n, pwm, rpm)\n\t\t\tswitch {\n\t\t\tcase m >= pwmNum:\n\t\t\t\ttodo &^= 1 << uint(n)\n\t\t\t\tfc.pwm.SetInv(n, 0)\n\t\t\tcase m >= 0:\n\t\t\t\tfc.fans[n].SetModelPWM(m, pwm)\n\t\t\t}\n\t\t}\n\t}\n\tfc.pwm.SetManyInv(todo, 0, 0, 0)\n\tfc.maxI = maxPWM * divI \/ 2\n\tfor n := range fc.fans {\n\t\tfan := &fc.fans[n]\n\t\tif fan.FixModel(todo&1<<uint(n) != 0) {\n\t\t\tfan.SetTargetRPM(0) \/\/ Enable fan if OK.\n\t\t}\n\t}\n}\n\nfunc (fc *FanControl) IdentProgress() int {\n\tprogress := atomic.LoadInt(&fc.maxI)\n\tif progress >= 0 {\n\t\treturn 0\n\t}\n\treturn -progress\n}\n<commit_msg>examples\/core51822\/ventilation: Temporary disable P and D component in controller.<commit_after>package main\n\nimport (\n\t\/\/\"fmt\"\n\t\"delay\"\n\t\"sync\/atomic\"\n\n\t\"nrf5\/ppipwm\"\n)\n\nconst (\n\tpwmNum  = 24\n\tstepRPM = 1 << 5\n\tminRPM  = 420\n\tmaxRPM  = minRPM + (pwmNum-1)*stepRPM\n\tdivP    = 8\n\tdivI    = 64\n\tdivD    = 16\n)\n\ntype fan struct {\n\trpmToPWM  [pwmNum]byte\n\ttargetRPM int\n\tsum       int\n\tlastE     int\n}\n\nfunc (f *fan) TargetRPM() int {\n\treturn atomic.LoadInt(&f.targetRPM)\n}\n\nfunc (f *fan) SetTargetRPM(rpm int) {\n\tatomic.StoreInt(&f.targetRPM, rpm)\n}\n\nfunc (f *fan) NextE(e, maxSum int) (sum, diff int) {\n\tsum = f.sum + e\n\tif sum > maxSum {\n\t\tsum = maxSum\n\t} else if sum < -maxSum {\n\t\tsum = -maxSum\n\t}\n\tf.sum = sum\n\tdiff = e - f.lastE\n\tf.lastE = e\n\treturn sum, diff\n}\n\nfunc (f *fan) ResetE() {\n\tf.sum = 0\n\tf.lastE = 0\n}\n\nfunc (f *fan) ModelPWM(rpm int) int {\n\tr := rpm - minRPM\n\tn := r \/ stepRPM\n\tm := r & (stepRPM - 1)\n\tif n < 0 {\n\t\treturn 0\n\t}\n\tif n >= len(f.rpmToPWM)-1 {\n\t\treturn int(f.rpmToPWM[len(f.rpmToPWM)-1])\n\t}\n\ta := int(f.rpmToPWM[n])\n\tb := int(f.rpmToPWM[n+1])\n\treturn ((stepRPM-m)*a + m*b) \/ stepRPM\n}\n\nfunc (f *fan) SetModelPWM(n, pwm int) {\n\tf.rpmToPWM[n] = byte(pwm)\n}\n\nfunc (f *fan) FixModel(trouble bool) bool {\n\tif trouble {\n\t\t\/\/ TODO: If trouble analyze rpmToPWM to detect broken fan.\n\n\t\treturn false\n\t}\n\t\/\/ Fix single gaps in rpmToPWM.\n\tfor i, pwm := range f.rpmToPWM {\n\t\tif pwm != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tswitch {\n\t\tcase i == 0:\n\t\t\tpwm = f.rpmToPWM[i+1]\n\t\tcase i == pwmNum-1:\n\t\t\tpwm = f.rpmToPWM[i-1]\n\t\tdefault:\n\t\t\tpwm = byte((int(f.rpmToPWM[i-1]) + int(f.rpmToPWM[i+1])) \/ 2)\n\t\t}\n\t\tif pwm == 0 {\n\t\t\treturn false\n\t\t}\n\t\tf.rpmToPWM[i] = pwm\n\t}\n\treturn true\n}\n\ntype FanControl struct {\n\tpwm  *ppipwm.Toggle\n\ttach *Tachometer\n\tfans [2]fan\n\tmaxI int\n}\n\nfunc NewFanControl(pwm *ppipwm.Toggle, tach *Tachometer) *FanControl {\n\tfc := new(FanControl)\n\tfc.pwm = pwm\n\tfc.tach = tach\n\treturn fc\n}\n\nfunc (fc *FanControl) MaxRPM() int {\n\treturn maxRPM\n}\n\nfunc (fc *FanControl) TargetRPM(n int) int {\n\treturn fc.fans[n].TargetRPM()\n}\n\nfunc (fc *FanControl) SetTargetRPM(n, rpm int) {\n\tfan := &fc.fans[n]\n\tif fan.TargetRPM() < 0 {\n\t\treturn \/\/ Disabled.\n\t}\n\tif rpm < 0 {\n\t\trpm = 0\n\t} else if rpm > maxRPM {\n\t\trpm = maxRPM\n\t}\n\tfan.SetTargetRPM(rpm)\n}\n\nfunc (fc *FanControl) RPM(n int) int {\n\treturn fc.tach.RPM(n)\n}\n\nfunc (fc *FanControl) TachISR() {\n\tn := fc.tach.ISR()\n\tfan := &fc.fans[n]\n\ttargetRPM := fan.TargetRPM()\n\tif targetRPM < 0 {\n\t\treturn\n\t}\n\tdc := 0\n\tif targetRPM >= minRPM {\n\t\tmodelPWM := fan.ModelPWM(targetRPM)\n\t\trpm := fc.RPM(n)\n\t\te := targetRPM - rpm\n\t\tsum, diff := fan.NextE(e, fc.maxI)\n\t\tdc = modelPWM + 0*e\/divP + sum\/divI + 0*diff\/divD\n\t} else {\n\t\tfan.ResetE()\n\t}\n\tfc.pwm.SetInv(n, dc)\n}\n\nfunc (fc *FanControl) Identify() {\n\tfor n := range fc.fans {\n\t\tfan := &fc.fans[n]\n\t\tfan.SetTargetRPM(-1) \/\/ Prevent useing PWM by TachISR.\n\t\tfc.pwm.SetInv(n, 0)\n\t\tfor i := range fan.rpmToPWM {\n\t\t\tfan.rpmToPWM[i] = 0\n\t\t}\n\t}\n\tmaxPWM := fc.pwm.Max() * 3 \/ 4\n\tif maxPWM > 255 {\n\t\tpanic(\"maxPWM>255\")\n\t}\n\ttodo := uint(1<<uint(len(fc.fans)) - 1)\n\tfor pwm := 33; pwm <= maxPWM && todo != 0; pwm++ {\n\t\tatomic.StoreInt(&fc.maxI, pwm-maxPWM) \/\/ Progress\n\t\tfc.pwm.SetManyInv(todo, pwm, pwm, pwm)\n\t\tdelay.Millisec(500)\n\t\tfor n := range fc.fans {\n\t\t\tfanMask := uint(1 << uint(n))\n\t\t\tif todo&fanMask == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trpm := fc.RPM(n)\n\t\t\tm := (rpm - minRPM + stepRPM - 1) \/ stepRPM\n\t\t\t\/\/fmt.Printf(\"%d: %d %d\\n\", n, pwm, rpm)\n\t\t\tswitch {\n\t\t\tcase m >= pwmNum:\n\t\t\t\ttodo &^= 1 << uint(n)\n\t\t\t\tfc.pwm.SetInv(n, 0)\n\t\t\tcase m >= 0:\n\t\t\t\tfc.fans[n].SetModelPWM(m, pwm)\n\t\t\t}\n\t\t}\n\t}\n\tfc.pwm.SetManyInv(todo, 0, 0, 0)\n\tfc.maxI = maxPWM * divI \/ 2\n\tfor n := range fc.fans {\n\t\tfan := &fc.fans[n]\n\t\tif fan.FixModel(todo&1<<uint(n) != 0) {\n\t\t\tfan.SetTargetRPM(0) \/\/ Enable fan if OK.\n\t\t}\n\t}\n}\n\nfunc (fc *FanControl) IdentProgress() int {\n\tprogress := atomic.LoadInt(&fc.maxI)\n\tif progress >= 0 {\n\t\treturn 0\n\t}\n\treturn -progress\n}\n<|endoftext|>"}
{"text":"<commit_before>package resource\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/weaveworks\/flux\/resource\"\n)\n\n\/\/ Load takes paths to directories or files, and creates an object set\n\/\/ based on the file(s) therein. Resources are named according to the\n\/\/ file content, rather than the file name of directory structure.\nfunc Load(base string, paths []string) (map[string]resource.Resource, error) {\n\tobjs := map[string]resource.Resource{}\n\tcharts, err := newChartTracker(base)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"walking %q for chartdirs\", base)\n\t}\n\tfor _, root := range paths {\n\t\terr := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"walking %q for yamels\", path)\n\t\t\t}\n\n\t\t\tif charts.isDirChart(path) {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\n\t\t\tif charts.isPathInChart(path) {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif !info.IsDir() && filepath.Ext(path) == \".yaml\" || filepath.Ext(path) == \".yml\" {\n\t\t\t\tbytes, err := ioutil.ReadFile(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"unable to read file at %q\", path)\n\t\t\t\t}\n\t\t\t\tsource, err := filepath.Rel(base, path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"path to scan %q is not under base %q\", path, base)\n\t\t\t\t}\n\t\t\t\tdocsInFile, err := ParseMultidoc(bytes, source)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfor id, obj := range docsInFile {\n\t\t\t\t\tif alreadyDefined, ok := objs[id]; ok {\n\t\t\t\t\t\treturn fmt.Errorf(`duplicate definition of '%s' (in %s and %s)`, id, alreadyDefined.Source(), source)\n\t\t\t\t\t}\n\t\t\t\t\tobjs[id] = obj\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn objs, err\n\t\t}\n\t}\n\n\treturn objs, nil\n}\n\ntype chartTracker map[string]bool\n\nfunc newChartTracker(root string) (chartTracker, error) {\n\tvar chartdirs = make(map[string]bool)\n\terr := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"walking %q for charts\", path)\n\t\t}\n\n\t\tif info.IsDir() && looksLikeChart(path) {\n\t\t\tchartdirs[path] = true\n\t\t\treturn filepath.SkipDir\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn chartTracker(chartdirs), nil\n}\n\nfunc (c chartTracker) isDirChart(path string) bool {\n\treturn c[path]\n}\n\nfunc (c chartTracker) isPathInChart(path string) bool {\n\tp := path\n\troot := fmt.Sprintf(\"%c\", filepath.Separator)\n\tfor p != root {\n\t\tif c[p] {\n\t\t\treturn true\n\t\t}\n\t\tp = filepath.Dir(p)\n\t}\n\treturn false\n}\n\n\/\/ looksLikeChart returns `true` if the path `dir` (assumed to be a\n\/\/ directory) looks like it contains a Helm chart, rather than\n\/\/ manifest files.\nfunc looksLikeChart(dir string) bool {\n\t\/\/ These are the two mandatory parts of a chart. If they both\n\t\/\/ exist, chances are it's a chart. See\n\t\/\/ https:\/\/github.com\/kubernetes\/helm\/blob\/master\/docs\/charts.md#the-chart-file-structure\n\tchartpath := filepath.Join(dir, \"Chart.yaml\")\n\tvaluespath := filepath.Join(dir, \"values.yaml\")\n\tif _, err := os.Stat(chartpath); err != nil && os.IsNotExist(err) {\n\t\treturn false\n\t}\n\tif _, err := os.Stat(valuespath); err != nil && os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ ParseMultidoc takes a dump of config (a multidoc YAML) and\n\/\/ constructs an object set from the resources represented therein.\nfunc ParseMultidoc(multidoc []byte, source string) (map[string]resource.Resource, error) {\n\tobjs := map[string]resource.Resource{}\n\tchunks := bufio.NewScanner(bytes.NewReader(multidoc))\n\tinitialBuffer := make([]byte, 4096)     \/\/ Matches startBufSize in bufio\/scan.go\n\tchunks.Buffer(initialBuffer, 1024*1024) \/\/ Allow growth to 1MB\n\tchunks.Split(splitYAMLDocument)\n\n\tvar obj resource.Resource\n\tvar err error\n\tfor chunks.Scan() {\n\t\t\/\/ It's not guaranteed that the return value of Bytes() will not be mutated later:\n\t\t\/\/ https:\/\/golang.org\/pkg\/bufio\/#Scanner.Bytes\n\t\t\/\/ But we will be snaffling it away, so make a copy.\n\t\tbytes := chunks.Bytes()\n\t\tbytes2 := make([]byte, len(bytes), cap(bytes))\n\t\tcopy(bytes2, bytes)\n\t\tif obj, err = unmarshalObject(source, bytes2); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"parsing YAML doc from %q\", source)\n\t\t}\n\t\tif obj == nil {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Lists must be treated specially, since it's the\n\t\t\/\/ contained resources we are after.\n\t\tif list, ok := obj.(*List); ok {\n\t\t\tfor _, item := range list.Items {\n\t\t\t\tobjs[item.ResourceID().String()] = item\n\t\t\t}\n\t\t} else {\n\t\t\tobjs[obj.ResourceID().String()] = obj\n\t\t}\n\t}\n\n\tif err := chunks.Err(); err != nil {\n\t\treturn objs, errors.Wrapf(err, \"scanning multidoc from %q\", source)\n\t}\n\treturn objs, nil\n}\n\n\/\/ ---\n\/\/ Taken directly from https:\/\/github.com\/kubernetes\/apimachinery\/blob\/master\/pkg\/util\/yaml\/decoder.go.\n\nconst yamlSeparator = \"\\n---\"\n\n\/\/ splitYAMLDocument is a bufio.SplitFunc for splitting YAML streams into individual documents.\nfunc splitYAMLDocument(data []byte, atEOF bool) (advance int, token []byte, err error) {\n\tif atEOF && len(data) == 0 {\n\t\treturn 0, nil, nil\n\t}\n\tsep := len([]byte(yamlSeparator))\n\tif i := bytes.Index(data, []byte(yamlSeparator)); i >= 0 {\n\t\t\/\/ We have a potential document terminator\n\t\ti += sep\n\t\tafter := data[i:]\n\t\tif len(after) == 0 {\n\t\t\t\/\/ we can't read any more characters\n\t\t\tif atEOF {\n\t\t\t\treturn len(data), data[:len(data)-sep], nil\n\t\t\t}\n\t\t\treturn 0, nil, nil\n\t\t}\n\t\tif j := bytes.IndexByte(after, '\\n'); j >= 0 {\n\t\t\treturn i + j + 1, data[0 : i-sep], nil\n\t\t}\n\t\treturn 0, nil, nil\n\t}\n\t\/\/ If we're at EOF, we have a final, non-terminated line. Return it.\n\tif atEOF {\n\t\treturn len(data), data, nil\n\t}\n\t\/\/ Request more data.\n\treturn 0, nil, nil\n}\n\n\/\/ ---\n<commit_msg>Check if git path exists before walking the dir<commit_after>package resource\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/weaveworks\/flux\/resource\"\n)\n\n\/\/ Load takes paths to directories or files, and creates an object set\n\/\/ based on the file(s) therein. Resources are named according to the\n\/\/ file content, rather than the file name of directory structure.\nfunc Load(base string, paths []string) (map[string]resource.Resource, error) {\n\tif _, err := os.Stat(base); os.IsNotExist(err) {\n\t\treturn nil, fmt.Errorf(\"git path %q not found\", base)\n\t}\n\tobjs := map[string]resource.Resource{}\n\tcharts, err := newChartTracker(base)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"walking %q for chartdirs\", base)\n\t}\n\tfor _, root := range paths {\n\t\terr := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrapf(err, \"walking %q for yamels\", path)\n\t\t\t}\n\n\t\t\tif charts.isDirChart(path) {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\n\t\t\tif charts.isPathInChart(path) {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif !info.IsDir() && filepath.Ext(path) == \".yaml\" || filepath.Ext(path) == \".yml\" {\n\t\t\t\tbytes, err := ioutil.ReadFile(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"unable to read file at %q\", path)\n\t\t\t\t}\n\t\t\t\tsource, err := filepath.Rel(base, path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrapf(err, \"path to scan %q is not under base %q\", path, base)\n\t\t\t\t}\n\t\t\t\tdocsInFile, err := ParseMultidoc(bytes, source)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfor id, obj := range docsInFile {\n\t\t\t\t\tif alreadyDefined, ok := objs[id]; ok {\n\t\t\t\t\t\treturn fmt.Errorf(`duplicate definition of '%s' (in %s and %s)`, id, alreadyDefined.Source(), source)\n\t\t\t\t\t}\n\t\t\t\t\tobjs[id] = obj\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn objs, err\n\t\t}\n\t}\n\n\treturn objs, nil\n}\n\ntype chartTracker map[string]bool\n\nfunc newChartTracker(root string) (chartTracker, error) {\n\tvar chartdirs = make(map[string]bool)\n\terr := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"walking %q for charts\", path)\n\t\t}\n\n\t\tif info.IsDir() && looksLikeChart(path) {\n\t\t\tchartdirs[path] = true\n\t\t\treturn filepath.SkipDir\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn chartTracker(chartdirs), nil\n}\n\nfunc (c chartTracker) isDirChart(path string) bool {\n\treturn c[path]\n}\n\nfunc (c chartTracker) isPathInChart(path string) bool {\n\tp := path\n\troot := fmt.Sprintf(\"%c\", filepath.Separator)\n\tfor p != root {\n\t\tif c[p] {\n\t\t\treturn true\n\t\t}\n\t\tp = filepath.Dir(p)\n\t}\n\treturn false\n}\n\n\/\/ looksLikeChart returns `true` if the path `dir` (assumed to be a\n\/\/ directory) looks like it contains a Helm chart, rather than\n\/\/ manifest files.\nfunc looksLikeChart(dir string) bool {\n\t\/\/ These are the two mandatory parts of a chart. If they both\n\t\/\/ exist, chances are it's a chart. See\n\t\/\/ https:\/\/github.com\/kubernetes\/helm\/blob\/master\/docs\/charts.md#the-chart-file-structure\n\tchartpath := filepath.Join(dir, \"Chart.yaml\")\n\tvaluespath := filepath.Join(dir, \"values.yaml\")\n\tif _, err := os.Stat(chartpath); err != nil && os.IsNotExist(err) {\n\t\treturn false\n\t}\n\tif _, err := os.Stat(valuespath); err != nil && os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ ParseMultidoc takes a dump of config (a multidoc YAML) and\n\/\/ constructs an object set from the resources represented therein.\nfunc ParseMultidoc(multidoc []byte, source string) (map[string]resource.Resource, error) {\n\tobjs := map[string]resource.Resource{}\n\tchunks := bufio.NewScanner(bytes.NewReader(multidoc))\n\tinitialBuffer := make([]byte, 4096)     \/\/ Matches startBufSize in bufio\/scan.go\n\tchunks.Buffer(initialBuffer, 1024*1024) \/\/ Allow growth to 1MB\n\tchunks.Split(splitYAMLDocument)\n\n\tvar obj resource.Resource\n\tvar err error\n\tfor chunks.Scan() {\n\t\t\/\/ It's not guaranteed that the return value of Bytes() will not be mutated later:\n\t\t\/\/ https:\/\/golang.org\/pkg\/bufio\/#Scanner.Bytes\n\t\t\/\/ But we will be snaffling it away, so make a copy.\n\t\tbytes := chunks.Bytes()\n\t\tbytes2 := make([]byte, len(bytes), cap(bytes))\n\t\tcopy(bytes2, bytes)\n\t\tif obj, err = unmarshalObject(source, bytes2); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"parsing YAML doc from %q\", source)\n\t\t}\n\t\tif obj == nil {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Lists must be treated specially, since it's the\n\t\t\/\/ contained resources we are after.\n\t\tif list, ok := obj.(*List); ok {\n\t\t\tfor _, item := range list.Items {\n\t\t\t\tobjs[item.ResourceID().String()] = item\n\t\t\t}\n\t\t} else {\n\t\t\tobjs[obj.ResourceID().String()] = obj\n\t\t}\n\t}\n\n\tif err := chunks.Err(); err != nil {\n\t\treturn objs, errors.Wrapf(err, \"scanning multidoc from %q\", source)\n\t}\n\treturn objs, nil\n}\n\n\/\/ ---\n\/\/ Taken directly from https:\/\/github.com\/kubernetes\/apimachinery\/blob\/master\/pkg\/util\/yaml\/decoder.go.\n\nconst yamlSeparator = \"\\n---\"\n\n\/\/ splitYAMLDocument is a bufio.SplitFunc for splitting YAML streams into individual documents.\nfunc splitYAMLDocument(data []byte, atEOF bool) (advance int, token []byte, err error) {\n\tif atEOF && len(data) == 0 {\n\t\treturn 0, nil, nil\n\t}\n\tsep := len([]byte(yamlSeparator))\n\tif i := bytes.Index(data, []byte(yamlSeparator)); i >= 0 {\n\t\t\/\/ We have a potential document terminator\n\t\ti += sep\n\t\tafter := data[i:]\n\t\tif len(after) == 0 {\n\t\t\t\/\/ we can't read any more characters\n\t\t\tif atEOF {\n\t\t\t\treturn len(data), data[:len(data)-sep], nil\n\t\t\t}\n\t\t\treturn 0, nil, nil\n\t\t}\n\t\tif j := bytes.IndexByte(after, '\\n'); j >= 0 {\n\t\t\treturn i + j + 1, data[0 : i-sep], nil\n\t\t}\n\t\treturn 0, nil, nil\n\t}\n\t\/\/ If we're at EOF, we have a final, non-terminated line. Return it.\n\tif atEOF {\n\t\treturn len(data), data, nil\n\t}\n\t\/\/ Request more data.\n\treturn 0, nil, nil\n}\n\n\/\/ ---\n<|endoftext|>"}
{"text":"<commit_before>package kickass\n\nimport (\n\t\"strconv\"\n\n\t\"gopkg.in\/xmlpath.v2\"\n)\n\n\/\/ XPATH\nvar (\n\txpathTorrentResults = xmlpath.MustCompile(\"\/\/tr[contains(@id, 'torrent_')]\")\n\txpathTorrentName    = xmlpath.MustCompile(\".\/\/a[@class=\\\"cellMainLink\\\"]\")\n\txpathTorrentURL     = xmlpath.MustCompile(\".\/\/a[contains(@title,'Download torrent file')]\/@href\")\n\txpathMagnetURL      = xmlpath.MustCompile(\".\/\/a[contains(@title,'Torrent magnet link')]\/@href\")\n\txpathSeed           = xmlpath.MustCompile(\".\/\/td[5]\")\n\txpathLeech          = xmlpath.MustCompile(\".\/\/td[6]\")\n\txpathAge            = xmlpath.MustCompile(\".\/\/td[4]\")\n\txpathSize           = xmlpath.MustCompile(\".\/\/td[2]\")\n\txpathFileCount      = xmlpath.MustCompile(\".\/\/td[3]\")\n\txpathVerify         = xmlpath.MustCompile(\".\/\/a[contains(@class,'iverify')]\")\n\txpathUser           = xmlpath.MustCompile(\".\/\/a[contains(@href, '\/user\/')]\")\n)\n\n\/\/ Default parse function, to be overwritten during the tests\nvar parseFunc = parseResult\n\nfunc parseResult(root *xmlpath.Node) ([]*Torrent, error) {\n\ttorrents := []*Torrent{}\n\titer := xpathTorrentResults.Iter(root)\n\tfor iter.Next() {\n\t\tname, ok := xpathTorrentName.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\ttorrentURL, ok := xpathTorrentURL.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\tmagnet, ok := xpathMagnetURL.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\tverify := xpathVerify.Exists(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\n\t\tseedStr, ok := xpathSeed.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\tseed, err := strconv.Atoi(seedStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tleechStr, ok := xpathLeech.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\tleech, err := strconv.Atoi(leechStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tage, ok := xpathAge.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\tfileCountStr, ok := xpathFileCount.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\tfileCount, err := strconv.Atoi(fileCountStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsize, ok := xpathSize.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\n\t\tuser, ok := xpathUser.String(iter.Node())\n\t\tif !ok {\n\t\t\t\/\/ The user name is not always present\n\t\t\tuser = \"\"\n\t\t}\n\n\t\tt := &Torrent{\n\t\t\tName:       name,\n\t\t\tTorrentURL: torrentURL,\n\t\t\tMagnetURL:  magnet,\n\t\t\tSeed:       seed,\n\t\t\tLeech:      leech,\n\t\t\tAge:        age,\n\t\t\tFileCount:  fileCount,\n\t\t\tSize:       size,\n\t\t\tVerified:   verify,\n\t\t\tUser:       user,\n\t\t}\n\n\t\ttorrents = append(torrents, t)\n\t}\n\n\treturn torrents, nil\n}\n<commit_msg>Don't parse the web page if there is no results<commit_after>package kickass\n\nimport (\n\t\"strconv\"\n\n\t\"gopkg.in\/xmlpath.v2\"\n)\n\n\/\/ XPATH\nvar (\n\txpathNoResult       = xmlpath.MustCompile(\"\/\/text()[contains(.,'did not match any documents')]\")\n\txpathTorrentResults = xmlpath.MustCompile(\"\/\/tr[contains(@id, 'torrent_')]\")\n\txpathTorrentName    = xmlpath.MustCompile(\".\/\/a[@class=\\\"cellMainLink\\\"]\")\n\txpathTorrentURL     = xmlpath.MustCompile(\".\/\/a[contains(@title,'Download torrent file')]\/@href\")\n\txpathMagnetURL      = xmlpath.MustCompile(\".\/\/a[contains(@title,'Torrent magnet link')]\/@href\")\n\txpathSeed           = xmlpath.MustCompile(\".\/\/td[5]\")\n\txpathLeech          = xmlpath.MustCompile(\".\/\/td[6]\")\n\txpathAge            = xmlpath.MustCompile(\".\/\/td[4]\")\n\txpathSize           = xmlpath.MustCompile(\".\/\/td[2]\")\n\txpathFileCount      = xmlpath.MustCompile(\".\/\/td[3]\")\n\txpathVerify         = xmlpath.MustCompile(\".\/\/a[contains(@class,'iverify')]\")\n\txpathUser           = xmlpath.MustCompile(\".\/\/a[contains(@href, '\/user\/')]\")\n)\n\n\/\/ Default parse function, to be overwritten during the tests\nvar parseFunc = parseResult\n\nfunc parseResult(root *xmlpath.Node) ([]*Torrent, error) {\n\ttorrents := []*Torrent{}\n\n\t\/\/ Don't go further if there is no results\n\tif xpathNoResult.Exists(root) {\n\t\treturn torrents, nil\n\t}\n\n\titer := xpathTorrentResults.Iter(root)\n\tfor iter.Next() {\n\t\tname, ok := xpathTorrentName.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\ttorrentURL, ok := xpathTorrentURL.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\tmagnet, ok := xpathMagnetURL.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\tverify := xpathVerify.Exists(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\n\t\tseedStr, ok := xpathSeed.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\tseed, err := strconv.Atoi(seedStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tleechStr, ok := xpathLeech.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\tleech, err := strconv.Atoi(leechStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tage, ok := xpathAge.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\tfileCountStr, ok := xpathFileCount.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\t\tfileCount, err := strconv.Atoi(fileCountStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsize, ok := xpathSize.String(iter.Node())\n\t\tif !ok {\n\t\t\treturn nil, ErrUnexpectedContent\n\t\t}\n\n\t\tuser, ok := xpathUser.String(iter.Node())\n\t\tif !ok {\n\t\t\t\/\/ The user name is not always present\n\t\t\tuser = \"\"\n\t\t}\n\n\t\tt := &Torrent{\n\t\t\tName:       name,\n\t\t\tTorrentURL: torrentURL,\n\t\t\tMagnetURL:  magnet,\n\t\t\tSeed:       seed,\n\t\t\tLeech:      leech,\n\t\t\tAge:        age,\n\t\t\tFileCount:  fileCount,\n\t\t\tSize:       size,\n\t\t\tVerified:   verify,\n\t\t\tUser:       user,\n\t\t}\n\n\t\ttorrents = append(torrents, t)\n\t}\n\n\treturn torrents, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017, Oracle and\/or its affiliates. All rights reserved.\n\npackage provider\n\nimport (\n\t\"log\"\n)\n\nconst Version = \"3.1.0\"\n\nfunc PrintVersion() {\n\tlog.Printf(\"[INFO] terraform-provider-oci %s\\n\", Version)\n}\n<commit_msg>Update version to 3.1.1<commit_after>\/\/ Copyright (c) 2017, Oracle and\/or its affiliates. All rights reserved.\n\npackage provider\n\nimport (\n\t\"log\"\n)\n\nconst Version = \"3.1.1\"\n\nfunc PrintVersion() {\n\tlog.Printf(\"[INFO] terraform-provider-oci %s\\n\", Version)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage http\n\nimport (\n\t. \"github.com\/jacobsa\/ogletest\"\n\t\"testing\"\n)\n\nfunc TestRetry(t *testing.T) { RunTests(t) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype RetryingConnTest struct {\n}\n\nfunc init() { RegisterTestSuite(&RetryingConnTest{}) }\n\nfunc (t *RetryingConnTest) SetUp(i *TestInfo) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *RetryingConnTest) DoesFoo() {\n\tExpectEq(\"TODO\", \"\")\n}\n<commit_msg>Added test names.<commit_after>\/\/ Copyright 2012 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage http\n\nimport (\n\t. \"github.com\/jacobsa\/ogletest\"\n\t\"testing\"\n)\n\nfunc TestRetry(t *testing.T) { RunTests(t) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype RetryingConnTest struct {\n}\n\nfunc init() { RegisterTestSuite(&RetryingConnTest{}) }\n\nfunc (t *RetryingConnTest) SetUp(i *TestInfo) {\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *RetryingConnTest) CallsWrapped() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *RetryingConnTest) WrappedReturnsWrongErrorType() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *RetryingConnTest) WrappedReturnsWrongOpErrorType() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *RetryingConnTest) WrappedReturnsUnknownErrno() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *RetryingConnTest) RetriesForBrokenPipe() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *RetryingConnTest) WrappedFailsOnThirdCall() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *RetryingConnTest) WrappedSucceedsOnThirdCall() {\n\tExpectEq(\"TODO\", \"\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package kafka\n\nimport (\n\tl \"log\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/funkygao\/gafka\/cmd\/kateway\/meta\"\n\t\"github.com\/funkygao\/gafka\/ctx\"\n\t\"github.com\/funkygao\/golib\/color\"\n\tlog \"github.com\/funkygao\/log4go\"\n)\n\ntype pubStore struct {\n\tshutdownCh chan struct{}\n\n\tmaxRetries int\n\twg         *sync.WaitGroup\n\thostname   string \/\/ used as kafka client id\n\tdryRun     bool\n\n\tpubPools        map[string]*pubPool \/\/ key is cluster, each cluster maintains a conn pool\n\tpubPoolsCapcity int\n\tpubPoolsLock    sync.RWMutex\n\tidleTimeout     time.Duration\n\n\tjobPools     map[string]*jobPool \/\/ key is cluster\n\tjobPoolsLock sync.RWMutex\n\n\t\/\/ to avoid too frequent refresh\n\t\/\/ TODO refresh by cluster: current implementation will refresh zone\n\tlastRefreshedAt time.Time\n}\n\nfunc NewPubStore(poolCapcity int, maxRetries int, idleTimeout time.Duration,\n\twg *sync.WaitGroup, debug bool, dryRun bool) *pubStore {\n\tif debug {\n\t\tsarama.Logger = l.New(os.Stdout, color.Green(\"[Sarama]\"),\n\t\t\tl.LstdFlags|l.Lshortfile)\n\t}\n\n\treturn &pubStore{\n\t\thostname:        ctx.Hostname(),\n\t\tmaxRetries:      maxRetries,\n\t\tidleTimeout:     idleTimeout,\n\t\tpubPoolsCapcity: poolCapcity,\n\t\tpubPools:        make(map[string]*pubPool),\n\t\tjobPools:        make(map[string]*jobPool),\n\t\twg:              wg,\n\t\tdryRun:          dryRun,\n\t\tshutdownCh:      make(chan struct{}),\n\t}\n}\n\nfunc (this *pubStore) Name() string {\n\treturn \"kafka\"\n}\n\nfunc (this *pubStore) Start() (err error) {\n\tthis.wg.Add(1)\n\tdefer this.wg.Done()\n\n\t\/\/ warmup: create pools according the current kafka topology\n\tfor _, cluster := range meta.Default.ClusterNames() {\n\t\tthis.pubPools[cluster] = newPubPool(this, cluster,\n\t\t\tmeta.Default.BrokerList(cluster), this.pubPoolsCapcity)\n\t}\n\n\tthis.refreshJobPoolNodes()\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-meta.Default.RefreshEvent():\n\t\t\t\tthis.doRefresh()\n\n\t\t\tcase <-this.shutdownCh:\n\t\t\t\tlog.Trace(\"pub store[%s] stopped\", this.Name())\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn\n}\n\nfunc (this *pubStore) Stop() {\n\tthis.pubPoolsLock.Lock()\n\tdefer this.pubPoolsLock.Unlock()\n\n\t\/\/ close all kafka connections\n\tfor _, pool := range this.pubPools {\n\t\tpool.Close()\n\t}\n\n\tclose(this.shutdownCh)\n}\n\nfunc (this *pubStore) refreshJobPoolNodes() {\n\tif disqueAddrs, err := meta.Default.KatewayDisqueAddrs(); err == nil {\n\t\tlog.Debug(\"disques: %+v\", disqueAddrs)\n\n\t\tfor cluster, addrs := range disqueAddrs {\n\t\t\tif _, present := this.jobPools[cluster]; !present {\n\t\t\t\t\/\/ found a new cluster of disque\n\t\t\t\tthis.jobPools[cluster] = newJobPool(addrs)\n\t\t\t\tif e := this.jobPools[cluster].RefreshNodes(); e != nil {\n\t\t\t\t\tlog.Error(\"dique refresh nodes: %v\", e)\n\n\t\t\t\t\t\/\/ unload this problemetic cluster\n\t\t\t\t\tdelete(this.jobPools, cluster)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.jobPools[cluster].RefreshNodes()\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\/\/ just log, still using the current pools\n\t\tlog.Error(\"disque addrs fetch: %v\", err)\n\t}\n}\n\nfunc (this *pubStore) doRefresh() {\n\t\/\/ TODO the lock is too big, should consider cluster level refresh\n\tthis.pubPoolsLock.Lock()\n\tdefer this.pubPoolsLock.Unlock()\n\tthis.jobPoolsLock.Lock()\n\tdefer this.jobPoolsLock.Unlock()\n\n\tif time.Since(this.lastRefreshedAt) <= time.Second*5 {\n\t\tlog.Warn(\"ignored too frequent refresh: %s\", time.Since(this.lastRefreshedAt))\n\t\treturn\n\t}\n\n\t\/\/ job pools\n\tthis.refreshJobPoolNodes()\n\n\t\/\/ pub pool\n\tactiveClusters := make(map[string]struct{})\n\tfor _, cluster := range meta.Default.ClusterNames() {\n\t\tactiveClusters[cluster] = struct{}{}\n\t\tif _, present := this.pubPools[cluster]; !present {\n\t\t\t\/\/ found a new cluster\n\t\t\tthis.pubPools[cluster] = newPubPool(this, cluster,\n\t\t\t\tmeta.Default.BrokerList(cluster), this.pubPoolsCapcity)\n\t\t} else {\n\t\t\tthis.pubPools[cluster].RefreshBrokerList(meta.Default.BrokerList(cluster))\n\t\t}\n\t}\n\n\t\/\/ shutdown the dead clusters\n\tfor cluster, pool := range this.pubPools {\n\t\tif _, present := activeClusters[cluster]; !present {\n\t\t\t\/\/ this cluster is dead or removed forever\n\t\t\tpool.Close()\n\t\t\tdelete(this.pubPools, cluster)\n\t\t}\n\t}\n\n\tthis.lastRefreshedAt = time.Now()\n}\n<commit_msg>fix typo<commit_after>package kafka\n\nimport (\n\tl \"log\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/funkygao\/gafka\/cmd\/kateway\/meta\"\n\t\"github.com\/funkygao\/gafka\/ctx\"\n\t\"github.com\/funkygao\/golib\/color\"\n\tlog \"github.com\/funkygao\/log4go\"\n)\n\ntype pubStore struct {\n\tshutdownCh chan struct{}\n\n\tmaxRetries int\n\twg         *sync.WaitGroup\n\thostname   string \/\/ used as kafka client id\n\tdryRun     bool\n\n\tpubPools        map[string]*pubPool \/\/ key is cluster, each cluster maintains a conn pool\n\tpubPoolsCapcity int\n\tpubPoolsLock    sync.RWMutex\n\tidleTimeout     time.Duration\n\n\tjobPools     map[string]*jobPool \/\/ key is cluster\n\tjobPoolsLock sync.RWMutex\n\n\t\/\/ to avoid too frequent refresh\n\t\/\/ TODO refresh by cluster: current implementation will refresh zone\n\tlastRefreshedAt time.Time\n}\n\nfunc NewPubStore(poolCapcity int, maxRetries int, idleTimeout time.Duration,\n\twg *sync.WaitGroup, debug bool, dryRun bool) *pubStore {\n\tif debug {\n\t\tsarama.Logger = l.New(os.Stdout, color.Green(\"[Sarama]\"),\n\t\t\tl.LstdFlags|l.Lshortfile)\n\t}\n\n\treturn &pubStore{\n\t\thostname:        ctx.Hostname(),\n\t\tmaxRetries:      maxRetries,\n\t\tidleTimeout:     idleTimeout,\n\t\tpubPoolsCapcity: poolCapcity,\n\t\tpubPools:        make(map[string]*pubPool),\n\t\tjobPools:        make(map[string]*jobPool),\n\t\twg:              wg,\n\t\tdryRun:          dryRun,\n\t\tshutdownCh:      make(chan struct{}),\n\t}\n}\n\nfunc (this *pubStore) Name() string {\n\treturn \"kafka\"\n}\n\nfunc (this *pubStore) Start() (err error) {\n\tthis.wg.Add(1)\n\tdefer this.wg.Done()\n\n\t\/\/ warmup: create pools according the current kafka topology\n\tfor _, cluster := range meta.Default.ClusterNames() {\n\t\tthis.pubPools[cluster] = newPubPool(this, cluster,\n\t\t\tmeta.Default.BrokerList(cluster), this.pubPoolsCapcity)\n\t}\n\n\tthis.refreshJobPoolNodes()\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-meta.Default.RefreshEvent():\n\t\t\t\tthis.doRefresh()\n\n\t\t\tcase <-this.shutdownCh:\n\t\t\t\tlog.Trace(\"pub store[%s] stopped\", this.Name())\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn\n}\n\nfunc (this *pubStore) Stop() {\n\tthis.pubPoolsLock.Lock()\n\tdefer this.pubPoolsLock.Unlock()\n\n\t\/\/ close all kafka connections\n\tfor _, pool := range this.pubPools {\n\t\tpool.Close()\n\t}\n\n\tclose(this.shutdownCh)\n}\n\nfunc (this *pubStore) refreshJobPoolNodes() {\n\tif disqueAddrs, err := meta.Default.KatewayDisqueAddrs(); err == nil {\n\t\tlog.Debug(\"disques: %+v\", disqueAddrs)\n\n\t\tfor cluster, addrs := range disqueAddrs {\n\t\t\tif _, present := this.jobPools[cluster]; !present {\n\t\t\t\t\/\/ found a new cluster of disque\n\t\t\t\tthis.jobPools[cluster] = newJobPool(addrs)\n\t\t\t\tif e := this.jobPools[cluster].RefreshNodes(); e != nil {\n\t\t\t\t\tlog.Error(\"disque[%s] refresh nodes: %v\", cluster, e)\n\n\t\t\t\t\t\/\/ unload this problemetic cluster\n\t\t\t\t\tdelete(this.jobPools, cluster)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.jobPools[cluster].RefreshNodes()\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\/\/ just log, still using the current pools\n\t\tlog.Error(\"disque addrs fetch: %v\", err)\n\t}\n}\n\nfunc (this *pubStore) doRefresh() {\n\t\/\/ TODO the lock is too big, should consider cluster level refresh\n\tthis.pubPoolsLock.Lock()\n\tdefer this.pubPoolsLock.Unlock()\n\tthis.jobPoolsLock.Lock()\n\tdefer this.jobPoolsLock.Unlock()\n\n\tif time.Since(this.lastRefreshedAt) <= time.Second*5 {\n\t\tlog.Warn(\"ignored too frequent refresh: %s\", time.Since(this.lastRefreshedAt))\n\t\treturn\n\t}\n\n\t\/\/ job pools\n\tthis.refreshJobPoolNodes()\n\n\t\/\/ pub pool\n\tactiveClusters := make(map[string]struct{})\n\tfor _, cluster := range meta.Default.ClusterNames() {\n\t\tactiveClusters[cluster] = struct{}{}\n\t\tif _, present := this.pubPools[cluster]; !present {\n\t\t\t\/\/ found a new cluster\n\t\t\tthis.pubPools[cluster] = newPubPool(this, cluster,\n\t\t\t\tmeta.Default.BrokerList(cluster), this.pubPoolsCapcity)\n\t\t} else {\n\t\t\tthis.pubPools[cluster].RefreshBrokerList(meta.Default.BrokerList(cluster))\n\t\t}\n\t}\n\n\t\/\/ shutdown the dead clusters\n\tfor cluster, pool := range this.pubPools {\n\t\tif _, present := activeClusters[cluster]; !present {\n\t\t\t\/\/ this cluster is dead or removed forever\n\t\t\tpool.Close()\n\t\t\tdelete(this.pubPools, cluster)\n\t\t}\n\t}\n\n\tthis.lastRefreshedAt = time.Now()\n}\n<|endoftext|>"}
{"text":"<commit_before>package forge\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\n\t\"github.com\/brettlangdon\/forge\/token\"\n)\n\ntype Parser struct {\n\tsettings    *Section\n\tscanner     *Scanner\n\tcur_tok     token.Token\n\tcur_section *Section\n\tprevious    []*Section\n}\n\nfunc NewParser(reader io.Reader) *Parser {\n\tsettings := NewSection()\n\treturn &Parser{\n\t\tscanner:     NewScanner(reader),\n\t\tsettings:    settings,\n\t\tcur_section: settings,\n\t\tprevious:    make([]*Section, 0),\n\t}\n}\n\nfunc (this *Parser) syntaxError(msg string) error {\n\tmsg = fmt.Sprintf(\n\t\t\"Syntax error line <%d> column <%d>: %s\",\n\t\tthis.cur_tok.Line,\n\t\tthis.cur_tok.Column,\n\t\tmsg,\n\t)\n\treturn errors.New(msg)\n}\n\nfunc (this *Parser) readToken() token.Token {\n\tthis.cur_tok = this.scanner.NextToken()\n\treturn this.cur_tok\n}\n\nfunc (this *Parser) parseReference(starting_section *Section, period bool) (Value, error) {\n\tname := \"\"\n\tif period == false {\n\t\tname = this.cur_tok.Literal\n\t}\n\tfor {\n\t\tthis.readToken()\n\t\tif this.cur_tok.ID == token.PERIOD && period == false {\n\t\t\tperiod = true\n\t\t} else if period && this.cur_tok.ID == token.IDENTIFIER {\n\t\t\tif len(name) > 0 {\n\t\t\t\tname += \".\"\n\t\t\t}\n\t\t\tname += this.cur_tok.Literal\n\t\t\tperiod = false\n\t\t} else if this.cur_tok.ID == token.SEMICOLON {\n\t\t\tbreak\n\t\t} else {\n\t\t\tmsg := fmt.Sprintf(\"expected ';' instead found '%s'\", this.cur_tok.Literal)\n\t\t\treturn nil, this.syntaxError(msg)\n\t\t}\n\t}\n\tif len(name) == 0 {\n\t\treturn nil, this.syntaxError(\n\t\t\tfmt.Sprintf(\"expected IDENTIFIER instead found %s\", this.cur_tok.Literal),\n\t\t)\n\t}\n\n\tif period {\n\t\treturn nil, this.syntaxError(fmt.Sprintf(\"expected IDENTIFIER after PERIOD\"))\n\t}\n\n\tvalue, err := starting_section.Resolve(name)\n\tif err != nil {\n\t\terr = errors.New(\"Reference error, \" + err.Error())\n\t}\n\treturn value, nil\n}\n\nfunc (this *Parser) parseSetting(name string) error {\n\tvar value Value\n\tthis.readToken()\n\n\tread_next := true\n\tswitch this.cur_tok.ID {\n\tcase token.STRING:\n\t\tvalue = NewString(this.cur_tok.Literal)\n\tcase token.BOOLEAN:\n\t\tbool_val, err := strconv.ParseBool(this.cur_tok.Literal)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tvalue = NewBoolean(bool_val)\n\tcase token.NULL:\n\t\tvalue = NewNull()\n\tcase token.INTEGER:\n\t\tint_val, err := strconv.ParseInt(this.cur_tok.Literal, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue = NewInteger(int_val)\n\tcase token.FLOAT:\n\t\tfloat_val, err := strconv.ParseFloat(this.cur_tok.Literal, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue = NewFloat(float_val)\n\tcase token.PERIOD:\n\t\treference, err := this.parseReference(this.cur_section, true)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue = reference\n\t\tread_next = false\n\tcase token.IDENTIFIER:\n\t\treference, err := this.parseReference(this.settings, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue = reference\n\t\tread_next = false\n\tdefault:\n\t\treturn this.syntaxError(\n\t\t\tfmt.Sprintf(\"expected STRING, INTEGER, FLOAT, BOOLEAN or IDENTIFIER, instead found %s\", this.cur_tok.ID),\n\t\t)\n\t}\n\n\tif read_next {\n\t\tthis.readToken()\n\t}\n\tif this.cur_tok.ID != token.SEMICOLON {\n\t\tmsg := fmt.Sprintf(\"expected ';' instead found '%s'\", this.cur_tok.Literal)\n\t\treturn this.syntaxError(msg)\n\t}\n\tthis.readToken()\n\n\tthis.cur_section.Set(name, value)\n\treturn nil\n}\n\nfunc (this *Parser) parseInclude() error {\n\tif this.cur_tok.ID != token.STRING {\n\t\tmsg := fmt.Sprintf(\"expected STRING instead found '%s'\", this.cur_tok.ID)\n\t\treturn this.syntaxError(msg)\n\t}\n\tpattern := this.cur_tok.Literal\n\n\tthis.readToken()\n\tif this.cur_tok.ID != token.SEMICOLON {\n\t\tmsg := fmt.Sprintf(\"expected ';' instead found '%s'\", this.cur_tok.Literal)\n\t\treturn this.syntaxError(msg)\n\t}\n\n\tfilenames, err := filepath.Glob(pattern)\n\tif err != nil {\n\t\treturn err\n\t}\n\told_scanner := this.scanner\n\tfor _, filename := range filenames {\n\t\treader, err := os.Open(filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ this.cur_section.AddInclude(filename)\n\t\tthis.scanner = NewScanner(reader)\n\t\tthis.parse()\n\t}\n\tthis.scanner = old_scanner\n\tthis.readToken()\n\treturn nil\n}\n\nfunc (this *Parser) parseSection(name string) error {\n\tsection := this.cur_section.AddSection(name)\n\tthis.previous = append(this.previous, this.cur_section)\n\tthis.cur_section = section\n\treturn nil\n}\n\nfunc (this *Parser) endSection() error {\n\tif len(this.previous) == 0 {\n\t\treturn this.syntaxError(\"unexpected section end '}'\")\n\t}\n\n\tp_len := len(this.previous)\n\tprevious := this.previous[p_len-1]\n\tthis.previous = this.previous[0 : p_len-1]\n\tthis.cur_section = previous\n\treturn nil\n}\n\nfunc (this *Parser) GetSettings() *Section {\n\treturn this.settings\n}\n\nfunc (this *Parser) parse() error {\n\tthis.readToken()\n\tfor {\n\t\tif this.cur_tok.ID == token.EOF {\n\t\t\tbreak\n\t\t}\n\t\ttok := this.cur_tok\n\t\tthis.readToken()\n\t\tswitch tok.ID {\n\t\tcase token.COMMENT:\n\t\t\t\/\/ this.cur_section.AddComment(tok.Literal)\n\t\tcase token.INCLUDE:\n\t\t\tthis.parseInclude()\n\t\tcase token.IDENTIFIER:\n\t\t\tif this.cur_tok.ID == token.LBRACKET {\n\t\t\t\terr := this.parseSection(tok.Literal)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tthis.readToken()\n\t\t\t} else if this.cur_tok.ID == token.EQUAL {\n\t\t\t\terr := this.parseSetting(tok.Literal)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\tcase token.RBRACKET:\n\t\t\terr := this.endSection()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\treturn this.syntaxError(fmt.Sprintf(\"unexpected token %s\", tok))\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (this *Parser) Parse() error {\n\terr := this.parse()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(this.previous) > 0 {\n\t\treturn this.syntaxError(\"expected end of section, instead found EOF\")\n\t}\n\n\treturn nil\n}\n<commit_msg>remove underscore names in parser<commit_after>package forge\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\n\t\"github.com\/brettlangdon\/forge\/token\"\n)\n\ntype Parser struct {\n\tsettings   *Section\n\tscanner    *Scanner\n\tcurTok     token.Token\n\tcurSection *Section\n\tprevious   []*Section\n}\n\nfunc NewParser(reader io.Reader) *Parser {\n\tsettings := NewSection()\n\treturn &Parser{\n\t\tscanner:    NewScanner(reader),\n\t\tsettings:   settings,\n\t\tcurSection: settings,\n\t\tprevious:   make([]*Section, 0),\n\t}\n}\n\nfunc (this *Parser) syntaxError(msg string) error {\n\tmsg = fmt.Sprintf(\n\t\t\"Syntax error line <%d> column <%d>: %s\",\n\t\tthis.curTok.Line,\n\t\tthis.curTok.Column,\n\t\tmsg,\n\t)\n\treturn errors.New(msg)\n}\n\nfunc (this *Parser) readToken() token.Token {\n\tthis.curTok = this.scanner.NextToken()\n\treturn this.curTok\n}\n\nfunc (this *Parser) parseReference(startingSection *Section, period bool) (Value, error) {\n\tname := \"\"\n\tif period == false {\n\t\tname = this.curTok.Literal\n\t}\n\tfor {\n\t\tthis.readToken()\n\t\tif this.curTok.ID == token.PERIOD && period == false {\n\t\t\tperiod = true\n\t\t} else if period && this.curTok.ID == token.IDENTIFIER {\n\t\t\tif len(name) > 0 {\n\t\t\t\tname += \".\"\n\t\t\t}\n\t\t\tname += this.curTok.Literal\n\t\t\tperiod = false\n\t\t} else if this.curTok.ID == token.SEMICOLON {\n\t\t\tbreak\n\t\t} else {\n\t\t\tmsg := fmt.Sprintf(\"expected ';' instead found '%s'\", this.curTok.Literal)\n\t\t\treturn nil, this.syntaxError(msg)\n\t\t}\n\t}\n\tif len(name) == 0 {\n\t\treturn nil, this.syntaxError(\n\t\t\tfmt.Sprintf(\"expected IDENTIFIER instead found %s\", this.curTok.Literal),\n\t\t)\n\t}\n\n\tif period {\n\t\treturn nil, this.syntaxError(fmt.Sprintf(\"expected IDENTIFIER after PERIOD\"))\n\t}\n\n\tvalue, err := startingSection.Resolve(name)\n\tif err != nil {\n\t\terr = errors.New(\"Reference error, \" + err.Error())\n\t}\n\treturn value, nil\n}\n\nfunc (this *Parser) parseSetting(name string) error {\n\tvar value Value\n\tthis.readToken()\n\n\tread_next := true\n\tswitch this.curTok.ID {\n\tcase token.STRING:\n\t\tvalue = NewString(this.curTok.Literal)\n\tcase token.BOOLEAN:\n\t\tboolVal, err := strconv.ParseBool(this.curTok.Literal)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tvalue = NewBoolean(boolVal)\n\tcase token.NULL:\n\t\tvalue = NewNull()\n\tcase token.INTEGER:\n\t\tintVal, err := strconv.ParseInt(this.curTok.Literal, 10, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue = NewInteger(intVal)\n\tcase token.FLOAT:\n\t\tfloatVal, err := strconv.ParseFloat(this.curTok.Literal, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue = NewFloat(floatVal)\n\tcase token.PERIOD:\n\t\treference, err := this.parseReference(this.curSection, true)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue = reference\n\t\tread_next = false\n\tcase token.IDENTIFIER:\n\t\treference, err := this.parseReference(this.settings, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvalue = reference\n\t\tread_next = false\n\tdefault:\n\t\treturn this.syntaxError(\n\t\t\tfmt.Sprintf(\"expected STRING, INTEGER, FLOAT, BOOLEAN or IDENTIFIER, instead found %s\", this.curTok.ID),\n\t\t)\n\t}\n\n\tif read_next {\n\t\tthis.readToken()\n\t}\n\tif this.curTok.ID != token.SEMICOLON {\n\t\tmsg := fmt.Sprintf(\"expected ';' instead found '%s'\", this.curTok.Literal)\n\t\treturn this.syntaxError(msg)\n\t}\n\tthis.readToken()\n\n\tthis.curSection.Set(name, value)\n\treturn nil\n}\n\nfunc (this *Parser) parseInclude() error {\n\tif this.curTok.ID != token.STRING {\n\t\tmsg := fmt.Sprintf(\"expected STRING instead found '%s'\", this.curTok.ID)\n\t\treturn this.syntaxError(msg)\n\t}\n\tpattern := this.curTok.Literal\n\n\tthis.readToken()\n\tif this.curTok.ID != token.SEMICOLON {\n\t\tmsg := fmt.Sprintf(\"expected ';' instead found '%s'\", this.curTok.Literal)\n\t\treturn this.syntaxError(msg)\n\t}\n\n\tfilenames, err := filepath.Glob(pattern)\n\tif err != nil {\n\t\treturn err\n\t}\n\toldScanner := this.scanner\n\tfor _, filename := range filenames {\n\t\treader, err := os.Open(filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ this.curSection.AddInclude(filename)\n\t\tthis.scanner = NewScanner(reader)\n\t\tthis.parse()\n\t}\n\tthis.scanner = oldScanner\n\tthis.readToken()\n\treturn nil\n}\n\nfunc (this *Parser) parseSection(name string) error {\n\tsection := this.curSection.AddSection(name)\n\tthis.previous = append(this.previous, this.curSection)\n\tthis.curSection = section\n\treturn nil\n}\n\nfunc (this *Parser) endSection() error {\n\tif len(this.previous) == 0 {\n\t\treturn this.syntaxError(\"unexpected section end '}'\")\n\t}\n\n\tpLen := len(this.previous)\n\tprevious := this.previous[pLen-1]\n\tthis.previous = this.previous[0 : pLen-1]\n\tthis.curSection = previous\n\treturn nil\n}\n\nfunc (this *Parser) GetSettings() *Section {\n\treturn this.settings\n}\n\nfunc (this *Parser) parse() error {\n\tthis.readToken()\n\tfor {\n\t\tif this.curTok.ID == token.EOF {\n\t\t\tbreak\n\t\t}\n\t\ttok := this.curTok\n\t\tthis.readToken()\n\t\tswitch tok.ID {\n\t\tcase token.COMMENT:\n\t\t\t\/\/ this.curSection.AddComment(tok.Literal)\n\t\tcase token.INCLUDE:\n\t\t\tthis.parseInclude()\n\t\tcase token.IDENTIFIER:\n\t\t\tif this.curTok.ID == token.LBRACKET {\n\t\t\t\terr := this.parseSection(tok.Literal)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tthis.readToken()\n\t\t\t} else if this.curTok.ID == token.EQUAL {\n\t\t\t\terr := this.parseSetting(tok.Literal)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\tcase token.RBRACKET:\n\t\t\terr := this.endSection()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\treturn this.syntaxError(fmt.Sprintf(\"unexpected token %s\", tok))\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (this *Parser) Parse() error {\n\terr := this.parse()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(this.previous) > 0 {\n\t\treturn this.syntaxError(\"expected end of section, instead found EOF\")\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage lsp\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"golang.org\/x\/tools\/internal\/lsp\/protocol\"\n\t\"golang.org\/x\/tools\/internal\/lsp\/source\"\n\t\"golang.org\/x\/tools\/internal\/span\"\n\t\"golang.org\/x\/tools\/internal\/telemetry\/log\"\n\t\"golang.org\/x\/tools\/internal\/telemetry\/tag\"\n)\n\nfunc (s *Server) completion(ctx context.Context, params *protocol.CompletionParams) (*protocol.CompletionList, error) {\n\turi := span.NewURI(params.TextDocument.URI)\n\tview, err := s.session.ViewOf(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsnapshot := view.Snapshot()\n\toptions := view.Options()\n\tfh, err := snapshot.GetFile(ctx, uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar candidates []source.CompletionItem\n\tvar surrounding *source.Selection\n\tswitch fh.Identity().Kind {\n\tcase source.Go:\n\t\toptions.Completion.FullDocumentation = options.HoverKind == source.FullDocumentation\n\t\tcandidates, surrounding, err = source.Completion(ctx, snapshot, fh, params.Position, options.Completion)\n\tcase source.Mod:\n\t\tcandidates, surrounding = nil, nil\n\t}\n\n\tif err != nil {\n\t\tlog.Print(ctx, \"no completions found\", tag.Of(\"At\", params.Position), tag.Of(\"Failure\", err))\n\t}\n\tif candidates == nil {\n\t\treturn &protocol.CompletionList{\n\t\t\tItems: []protocol.CompletionItem{},\n\t\t}, nil\n\t}\n\t\/\/ We might need to adjust the position to account for the prefix.\n\trng, err := surrounding.Range()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Sort the candidates by score, then label, since that is not supported by LSP yet.\n\tsort.SliceStable(candidates, func(i, j int) bool {\n\t\tif candidates[i].Score != candidates[j].Score {\n\t\t\treturn candidates[i].Score > candidates[j].Score\n\t\t}\n\t\treturn candidates[i].Label < candidates[j].Label\n\t})\n\n\t\/\/ When using deep completions\/fuzzy matching, report results as incomplete so\n\t\/\/ client fetches updated completions after every key stroke.\n\tincompleteResults := options.Completion.Deep || options.Completion.FuzzyMatching\n\n\titems := toProtocolCompletionItems(candidates, rng, options)\n\n\tif incompleteResults && len(items) > 1 {\n\t\tfor i := range items[1:] {\n\t\t\t\/\/ Give all the candidaites the same filterText to trick VSCode\n\t\t\t\/\/ into not reordering our candidates. All the candidates will\n\t\t\t\/\/ appear to be equally good matches, so VSCode's fuzzy\n\t\t\t\/\/ matching\/ranking just maintains the natural \"sortText\"\n\t\t\t\/\/ ordering. We can only do this in tandem with\n\t\t\t\/\/ \"incompleteResults\" since otherwise client side filtering is\n\t\t\t\/\/ important.\n\t\t\titems[i].FilterText = items[0].FilterText\n\t\t}\n\t}\n\n\treturn &protocol.CompletionList{\n\t\tIsIncomplete: incompleteResults,\n\t\tItems:        items,\n\t}, nil\n}\n\nfunc toProtocolCompletionItems(candidates []source.CompletionItem, rng protocol.Range, options source.Options) []protocol.CompletionItem {\n\tvar (\n\t\titems                  = make([]protocol.CompletionItem, 0, len(candidates))\n\t\tnumDeepCompletionsSeen int\n\t)\n\tfor i, candidate := range candidates {\n\t\t\/\/ Limit the number of deep completions to not overwhelm the user in cases\n\t\t\/\/ with dozens of deep completion matches.\n\t\tif candidate.Depth > 0 {\n\t\t\tif !options.Completion.Deep {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif numDeepCompletionsSeen >= source.MaxDeepCompletions {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnumDeepCompletionsSeen++\n\t\t}\n\t\tinsertText := candidate.InsertText\n\t\tif options.InsertTextFormat == protocol.SnippetTextFormat {\n\t\t\tinsertText = candidate.Snippet()\n\t\t}\n\n\t\t\/\/ This can happen if the client has snippets disabled but the\n\t\t\/\/ candidate only supports snippet insertion.\n\t\tif insertText == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\titem := protocol.CompletionItem{\n\t\t\tLabel:  candidate.Label,\n\t\t\tDetail: candidate.Detail,\n\t\t\tKind:   candidate.Kind,\n\t\t\tTextEdit: &protocol.TextEdit{\n\t\t\t\tNewText: insertText,\n\t\t\t\tRange:   rng,\n\t\t\t},\n\t\t\tInsertTextFormat:    options.InsertTextFormat,\n\t\t\tAdditionalTextEdits: candidate.AdditionalTextEdits,\n\t\t\t\/\/ This is a hack so that the client sorts completion results in the order\n\t\t\t\/\/ according to their score. This can be removed upon the resolution of\n\t\t\t\/\/ https:\/\/github.com\/Microsoft\/language-server-protocol\/issues\/348.\n\t\t\tSortText: fmt.Sprintf(\"%05d\", i),\n\n\t\t\t\/\/ Trim address operator (VSCode doesn't like weird characters\n\t\t\t\/\/ in filterText).\n\t\t\tFilterText: strings.TrimLeft(candidate.InsertText, \"&\"),\n\n\t\t\tPreselect:     i == 0,\n\t\t\tDocumentation: candidate.Documentation,\n\t\t}\n\t\t\/\/ Trigger signature help for any function or method completion.\n\t\t\/\/ This is helpful even if a function does not have parameters,\n\t\t\/\/ since we show return types as well.\n\t\tswitch item.Kind {\n\t\tcase protocol.FunctionCompletion, protocol.MethodCompletion:\n\t\t\titem.Command = &protocol.Command{\n\t\t\t\tCommand: \"editor.action.triggerParameterHints\",\n\t\t\t}\n\t\t}\n\t\titems = append(items, item)\n\t}\n\treturn items\n}\n<commit_msg>internal\/lsp: fix completion ordering workaround<commit_after>\/\/ Copyright 2018 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage lsp\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"golang.org\/x\/tools\/internal\/lsp\/protocol\"\n\t\"golang.org\/x\/tools\/internal\/lsp\/source\"\n\t\"golang.org\/x\/tools\/internal\/span\"\n\t\"golang.org\/x\/tools\/internal\/telemetry\/log\"\n\t\"golang.org\/x\/tools\/internal\/telemetry\/tag\"\n)\n\nfunc (s *Server) completion(ctx context.Context, params *protocol.CompletionParams) (*protocol.CompletionList, error) {\n\turi := span.NewURI(params.TextDocument.URI)\n\tview, err := s.session.ViewOf(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsnapshot := view.Snapshot()\n\toptions := view.Options()\n\tfh, err := snapshot.GetFile(ctx, uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar candidates []source.CompletionItem\n\tvar surrounding *source.Selection\n\tswitch fh.Identity().Kind {\n\tcase source.Go:\n\t\toptions.Completion.FullDocumentation = options.HoverKind == source.FullDocumentation\n\t\tcandidates, surrounding, err = source.Completion(ctx, snapshot, fh, params.Position, options.Completion)\n\tcase source.Mod:\n\t\tcandidates, surrounding = nil, nil\n\t}\n\n\tif err != nil {\n\t\tlog.Print(ctx, \"no completions found\", tag.Of(\"At\", params.Position), tag.Of(\"Failure\", err))\n\t}\n\tif candidates == nil {\n\t\treturn &protocol.CompletionList{\n\t\t\tItems: []protocol.CompletionItem{},\n\t\t}, nil\n\t}\n\t\/\/ We might need to adjust the position to account for the prefix.\n\trng, err := surrounding.Range()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Sort the candidates by score, then label, since that is not supported by LSP yet.\n\tsort.SliceStable(candidates, func(i, j int) bool {\n\t\tif candidates[i].Score != candidates[j].Score {\n\t\t\treturn candidates[i].Score > candidates[j].Score\n\t\t}\n\t\treturn candidates[i].Label < candidates[j].Label\n\t})\n\n\t\/\/ When using deep completions\/fuzzy matching, report results as incomplete so\n\t\/\/ client fetches updated completions after every key stroke.\n\tincompleteResults := options.Completion.Deep || options.Completion.FuzzyMatching\n\n\titems := toProtocolCompletionItems(candidates, rng, options)\n\n\tif incompleteResults {\n\t\tfor i := 1; i < len(items); i++ {\n\t\t\t\/\/ Give all the candidates the same filterText to trick VSCode\n\t\t\t\/\/ into not reordering our candidates. All the candidates will\n\t\t\t\/\/ appear to be equally good matches, so VSCode's fuzzy\n\t\t\t\/\/ matching\/ranking just maintains the natural \"sortText\"\n\t\t\t\/\/ ordering. We can only do this in tandem with\n\t\t\t\/\/ \"incompleteResults\" since otherwise client side filtering is\n\t\t\t\/\/ important.\n\t\t\titems[i].FilterText = items[0].FilterText\n\t\t}\n\t}\n\n\treturn &protocol.CompletionList{\n\t\tIsIncomplete: incompleteResults,\n\t\tItems:        items,\n\t}, nil\n}\n\nfunc toProtocolCompletionItems(candidates []source.CompletionItem, rng protocol.Range, options source.Options) []protocol.CompletionItem {\n\tvar (\n\t\titems                  = make([]protocol.CompletionItem, 0, len(candidates))\n\t\tnumDeepCompletionsSeen int\n\t)\n\tfor i, candidate := range candidates {\n\t\t\/\/ Limit the number of deep completions to not overwhelm the user in cases\n\t\t\/\/ with dozens of deep completion matches.\n\t\tif candidate.Depth > 0 {\n\t\t\tif !options.Completion.Deep {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif numDeepCompletionsSeen >= source.MaxDeepCompletions {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tnumDeepCompletionsSeen++\n\t\t}\n\t\tinsertText := candidate.InsertText\n\t\tif options.InsertTextFormat == protocol.SnippetTextFormat {\n\t\t\tinsertText = candidate.Snippet()\n\t\t}\n\n\t\t\/\/ This can happen if the client has snippets disabled but the\n\t\t\/\/ candidate only supports snippet insertion.\n\t\tif insertText == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\titem := protocol.CompletionItem{\n\t\t\tLabel:  candidate.Label,\n\t\t\tDetail: candidate.Detail,\n\t\t\tKind:   candidate.Kind,\n\t\t\tTextEdit: &protocol.TextEdit{\n\t\t\t\tNewText: insertText,\n\t\t\t\tRange:   rng,\n\t\t\t},\n\t\t\tInsertTextFormat:    options.InsertTextFormat,\n\t\t\tAdditionalTextEdits: candidate.AdditionalTextEdits,\n\t\t\t\/\/ This is a hack so that the client sorts completion results in the order\n\t\t\t\/\/ according to their score. This can be removed upon the resolution of\n\t\t\t\/\/ https:\/\/github.com\/Microsoft\/language-server-protocol\/issues\/348.\n\t\t\tSortText: fmt.Sprintf(\"%05d\", i),\n\n\t\t\t\/\/ Trim address operator (VSCode doesn't like weird characters\n\t\t\t\/\/ in filterText).\n\t\t\tFilterText: strings.TrimLeft(candidate.InsertText, \"&\"),\n\n\t\t\tPreselect:     i == 0,\n\t\t\tDocumentation: candidate.Documentation,\n\t\t}\n\t\t\/\/ Trigger signature help for any function or method completion.\n\t\t\/\/ This is helpful even if a function does not have parameters,\n\t\t\/\/ since we show return types as well.\n\t\tswitch item.Kind {\n\t\tcase protocol.FunctionCompletion, protocol.MethodCompletion:\n\t\t\titem.Command = &protocol.Command{\n\t\t\t\tCommand: \"editor.action.triggerParameterHints\",\n\t\t\t}\n\t\t}\n\t\titems = append(items, item)\n\t}\n\treturn items\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage template\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ Error describes a problem encountered during template Escaping.\ntype Error struct {\n\t\/\/ ErrorCode describes the kind of error.\n\tErrorCode ErrorCode\n\t\/\/ Name is the name of the template in which the error was encountered.\n\tName string\n\t\/\/ Line is the line number of the error in the template source or 0.\n\tLine int\n\t\/\/ Description is a human-readable description of the problem.\n\tDescription string\n}\n\n\/\/ ErrorCode is a code for a kind of error.\ntype ErrorCode int\n\n\/\/ We define codes for each error that manifests while escaping templates, but\n\/\/ escaped templates may also fail at runtime.\n\/\/\n\/\/ Output: \"ZgotmplZ\"\n\/\/ Example:\n\/\/   <img src=\"{{.X}}\">\n\/\/   where {{.X}} evaluates to `javascript:...`\n\/\/ Discussion:\n\/\/   \"ZgotmplZ\" is a special value that indicates that unsafe content reached a\n\/\/   CSS or URL context at runtime. The output of the example will be\n\/\/     <img src=\"#ZgotmplZ\">\n\/\/   If the data comes from a trusted source, use content types to exempt it\n\/\/   from filtering: URL(`javascript:...`).\nconst (\n\t\/\/ OK indicates the lack of an error.\n\tOK ErrorCode = iota\n\n\t\/\/ ErrAmbigContext: \"... appears in an ambiguous URL context\"\n\t\/\/ Example:\n\t\/\/   <a href=\"\n\t\/\/      {{if .C}}\n\t\/\/        \/path\/\n\t\/\/      {{else}}\n\t\/\/        \/search?q=\n\t\/\/      {{end}}\n\t\/\/      {{.X}}\n\t\/\/   \">\n\t\/\/ Discussion:\n\t\/\/   {{.X}} is in an ambiguous URL context since, depending on {{.C}},\n\t\/\/  it may be either a URL suffix or a query parameter.\n\t\/\/   Moving {{.X}} into the condition removes the ambiguity:\n\t\/\/   <a href=\"{{if .C}}\/path\/{{.X}}{{else}}\/search?q={{.X}}\">\n\tErrAmbigContext\n\n\t\/\/ ErrBadHTML: \"expected space, attr name, or end of tag, but got ...\",\n\t\/\/   \"... in unquoted attr\", \"... in attribute name\"\n\t\/\/ Example:\n\t\/\/   <a href = \/search?q=foo>\n\t\/\/   <href=foo>\n\t\/\/   <form na<e=...>\n\t\/\/   <option selected<\n\t\/\/ Discussion:\n\t\/\/   This is often due to a typo in an HTML element, but some runes\n\t\/\/   are banned in tag names, attribute names, and unquoted attribute\n\t\/\/   values because they can tickle parser ambiguities.\n\t\/\/   Quoting all attributes is the best policy.\n\tErrBadHTML\n\n\t\/\/ ErrBranchEnd: \"{{if}} branches end in different contexts\"\n\t\/\/ Example:\n\t\/\/   {{if .C}}<a href=\"{{end}}{{.X}}\n\t\/\/ Discussion:\n\t\/\/   Package html\/template statically examines each path through an\n\t\/\/   {{if}}, {{range}}, or {{with}} to escape any following pipelines.\n\t\/\/   The example is ambiguous since {{.X}} might be an HTML text node,\n\t\/\/   or a URL prefix in an HTML attribute. The context of {{.X}} is\n\t\/\/   used to figure out how to escape it, but that context depends on\n\t\/\/   the run-time value of {{.C}} which is not statically known.\n\t\/\/\n\t\/\/   The problem is usually something like missing quotes or angle\n\t\/\/   brackets, or can be avoided by refactoring to put the two contexts\n\t\/\/   into different branches of an if, range or with. If the problem\n\t\/\/   is in a {{range}} over a collection that should never be empty,\n\t\/\/   adding a dummy {{else}} can help.\n\tErrBranchEnd\n\n\t\/\/ ErrEndContext: \"... ends in a non-text context: ...\"\n\t\/\/ Examples:\n\t\/\/   <div\n\t\/\/   <div title=\"no close quote>\n\t\/\/   <script>f()\n\t\/\/ Discussion:\n\t\/\/   Executed templates should produce a DocumentFragment of HTML.\n\t\/\/   Templates that end without closing tags will trigger this error.\n\t\/\/   Templates that should not be used in an HTML context or that\n\t\/\/   produce incomplete Fragments should not be executed directly.\n\t\/\/\n\t\/\/   {{define \"main\"}} <script>{{template \"helper\"}}<\/script> {{end}}\n\t\/\/   {{define \"helper\"}} document.write(' <div title=\" ') {{end}}\n\t\/\/\n\t\/\/   \"helper\" does not produce a valid document fragment, so should\n\t\/\/   not be Executed directly.\n\tErrEndContext\n\n\t\/\/ ErrNoSuchTemplate: \"no such template ...\"\n\t\/\/ Examples:\n\t\/\/   {{define \"main\"}}<div {{template \"attrs\"}}>{{end}}\n\t\/\/   {{define \"attrs\"}}href=\"{{.URL}}\"{{end}}\n\t\/\/ Discussion:\n\t\/\/   Package html\/template looks through template calls to compute the\n\t\/\/   context.\n\t\/\/   Here the {{.URL}} in \"attrs\" must be treated as a URL when called\n\t\/\/   from \"main\", but you will get this error if \"attrs\" is not defined\n\t\/\/   when \"main\" is parsed.\n\tErrNoSuchTemplate\n\n\t\/\/ ErrOutputContext: \"cannot compute output context for template ...\"\n\t\/\/ Examples:\n\t\/\/   {{define \"t\"}}{{if .T}}{{template \"t\" .T}}{{end}}{{.H}}\",{{end}}\n\t\/\/ Discussion:\n\t\/\/   A recursive template does not end in the same context in which it\n\t\/\/   starts, and a reliable output context cannot be computed.\n\t\/\/   Look for typos in the named template.\n\t\/\/   If the template should not be called in the named start context,\n\t\/\/   look for calls to that template in unexpected contexts.\n\t\/\/   Maybe refactor recursive templates to not be recursive.\n\tErrOutputContext\n\n\t\/\/ ErrPartialCharset: \"unfinished JS regexp charset in ...\"\n\t\/\/ Example:\n\t\/\/     <script>var pattern = \/foo[{{.Chars}}]\/<\/script>\n\t\/\/ Discussion:\n\t\/\/   Package html\/template does not support interpolation into regular\n\t\/\/   expression literal character sets.\n\tErrPartialCharset\n\n\t\/\/ ErrPartialEscape: \"unfinished escape sequence in ...\"\n\t\/\/ Example:\n\t\/\/   <script>alert(\"\\{{.X}}\")<\/script>\n\t\/\/ Discussion:\n\t\/\/   Package html\/template does not support actions following a\n\t\/\/   backslash.\n\t\/\/   This is usually an error and there are better solutions; for\n\t\/\/   example\n\t\/\/     <script>alert(\"{{.X}}\")<\/script>\n\t\/\/   should work, and if {{.X}} is a partial escape sequence such as\n\t\/\/   \"xA0\", mark the whole sequence as safe content: JSStr(`\\xA0`)\n\tErrPartialEscape\n\n\t\/\/ ErrRangeLoopReentry: \"on range loop re-entry: ...\"\n\t\/\/ Example:\n\t\/\/   <script>var x = [{{range .}}'{{.}},{{end}}]<\/script>\n\t\/\/ Discussion:\n\t\/\/   If an iteration through a range would cause it to end in a\n\t\/\/   different context than an earlier pass, there is no single context.\n\t\/\/   In the example, there is missing a quote, so it is not clear\n\t\/\/   whether {{.}} is meant to be inside a JS string or in a JS value\n\t\/\/   context.  The second iteration would produce something like\n\t\/\/\n\t\/\/     <script>var x = ['firstValue,'secondValue]<\/script>\n\tErrRangeLoopReentry\n\n\t\/\/ ErrSlashAmbig: '\/' could start a division or regexp.\n\t\/\/ Example:\n\t\/\/   <script>\n\t\/\/     {{if .C}}var x = 1{{end}}\n\t\/\/     \/-{{.N}}\/i.test(x) ? doThis : doThat();\n\t\/\/   <\/script>\n\t\/\/ Discussion:\n\t\/\/   The example above could produce `var x = 1\/-2\/i.test(s)...`\n\t\/\/   in which the first '\/' is a mathematical division operator or it\n\t\/\/   could produce `\/-2\/i.test(s)` in which the first '\/' starts a\n\t\/\/   regexp literal.\n\t\/\/   Look for missing semicolons inside branches, and maybe add\n\t\/\/   parentheses to make it clear which interpretation you intend.\n\tErrSlashAmbig\n)\n\nfunc (e *Error) Error() string {\n\tif e == nil {\n\t\treturn \"html\/template: Unknown Error\"\n\t} else if e.Line != 0 {\n\t\treturn fmt.Sprintf(\"html\/template:%s:%d: %s\", e.Name, e.Line, e.Description)\n\t} else if e.Name != \"\" {\n\t\treturn fmt.Sprintf(\"html\/template:%s: %s\", e.Name, e.Description)\n\t}\n\treturn \"html\/template: \" + e.Description\n}\n\n\/\/ errorf creates an error given a format string f and args.\n\/\/ The template Name still needs to be supplied.\nfunc errorf(k ErrorCode, line int, f string, args ...interface{}) *Error {\n\treturn &Error{k, \"\", line, fmt.Sprintf(f, args...)}\n}\n<commit_msg>Revert nil error check change since we handle signals properly now<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage template\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ Error describes a problem encountered during template Escaping.\ntype Error struct {\n\t\/\/ ErrorCode describes the kind of error.\n\tErrorCode ErrorCode\n\t\/\/ Name is the name of the template in which the error was encountered.\n\tName string\n\t\/\/ Line is the line number of the error in the template source or 0.\n\tLine int\n\t\/\/ Description is a human-readable description of the problem.\n\tDescription string\n}\n\n\/\/ ErrorCode is a code for a kind of error.\ntype ErrorCode int\n\n\/\/ We define codes for each error that manifests while escaping templates, but\n\/\/ escaped templates may also fail at runtime.\n\/\/\n\/\/ Output: \"ZgotmplZ\"\n\/\/ Example:\n\/\/   <img src=\"{{.X}}\">\n\/\/   where {{.X}} evaluates to `javascript:...`\n\/\/ Discussion:\n\/\/   \"ZgotmplZ\" is a special value that indicates that unsafe content reached a\n\/\/   CSS or URL context at runtime. The output of the example will be\n\/\/     <img src=\"#ZgotmplZ\">\n\/\/   If the data comes from a trusted source, use content types to exempt it\n\/\/   from filtering: URL(`javascript:...`).\nconst (\n\t\/\/ OK indicates the lack of an error.\n\tOK ErrorCode = iota\n\n\t\/\/ ErrAmbigContext: \"... appears in an ambiguous URL context\"\n\t\/\/ Example:\n\t\/\/   <a href=\"\n\t\/\/      {{if .C}}\n\t\/\/        \/path\/\n\t\/\/      {{else}}\n\t\/\/        \/search?q=\n\t\/\/      {{end}}\n\t\/\/      {{.X}}\n\t\/\/   \">\n\t\/\/ Discussion:\n\t\/\/   {{.X}} is in an ambiguous URL context since, depending on {{.C}},\n\t\/\/  it may be either a URL suffix or a query parameter.\n\t\/\/   Moving {{.X}} into the condition removes the ambiguity:\n\t\/\/   <a href=\"{{if .C}}\/path\/{{.X}}{{else}}\/search?q={{.X}}\">\n\tErrAmbigContext\n\n\t\/\/ ErrBadHTML: \"expected space, attr name, or end of tag, but got ...\",\n\t\/\/   \"... in unquoted attr\", \"... in attribute name\"\n\t\/\/ Example:\n\t\/\/   <a href = \/search?q=foo>\n\t\/\/   <href=foo>\n\t\/\/   <form na<e=...>\n\t\/\/   <option selected<\n\t\/\/ Discussion:\n\t\/\/   This is often due to a typo in an HTML element, but some runes\n\t\/\/   are banned in tag names, attribute names, and unquoted attribute\n\t\/\/   values because they can tickle parser ambiguities.\n\t\/\/   Quoting all attributes is the best policy.\n\tErrBadHTML\n\n\t\/\/ ErrBranchEnd: \"{{if}} branches end in different contexts\"\n\t\/\/ Example:\n\t\/\/   {{if .C}}<a href=\"{{end}}{{.X}}\n\t\/\/ Discussion:\n\t\/\/   Package html\/template statically examines each path through an\n\t\/\/   {{if}}, {{range}}, or {{with}} to escape any following pipelines.\n\t\/\/   The example is ambiguous since {{.X}} might be an HTML text node,\n\t\/\/   or a URL prefix in an HTML attribute. The context of {{.X}} is\n\t\/\/   used to figure out how to escape it, but that context depends on\n\t\/\/   the run-time value of {{.C}} which is not statically known.\n\t\/\/\n\t\/\/   The problem is usually something like missing quotes or angle\n\t\/\/   brackets, or can be avoided by refactoring to put the two contexts\n\t\/\/   into different branches of an if, range or with. If the problem\n\t\/\/   is in a {{range}} over a collection that should never be empty,\n\t\/\/   adding a dummy {{else}} can help.\n\tErrBranchEnd\n\n\t\/\/ ErrEndContext: \"... ends in a non-text context: ...\"\n\t\/\/ Examples:\n\t\/\/   <div\n\t\/\/   <div title=\"no close quote>\n\t\/\/   <script>f()\n\t\/\/ Discussion:\n\t\/\/   Executed templates should produce a DocumentFragment of HTML.\n\t\/\/   Templates that end without closing tags will trigger this error.\n\t\/\/   Templates that should not be used in an HTML context or that\n\t\/\/   produce incomplete Fragments should not be executed directly.\n\t\/\/\n\t\/\/   {{define \"main\"}} <script>{{template \"helper\"}}<\/script> {{end}}\n\t\/\/   {{define \"helper\"}} document.write(' <div title=\" ') {{end}}\n\t\/\/\n\t\/\/   \"helper\" does not produce a valid document fragment, so should\n\t\/\/   not be Executed directly.\n\tErrEndContext\n\n\t\/\/ ErrNoSuchTemplate: \"no such template ...\"\n\t\/\/ Examples:\n\t\/\/   {{define \"main\"}}<div {{template \"attrs\"}}>{{end}}\n\t\/\/   {{define \"attrs\"}}href=\"{{.URL}}\"{{end}}\n\t\/\/ Discussion:\n\t\/\/   Package html\/template looks through template calls to compute the\n\t\/\/   context.\n\t\/\/   Here the {{.URL}} in \"attrs\" must be treated as a URL when called\n\t\/\/   from \"main\", but you will get this error if \"attrs\" is not defined\n\t\/\/   when \"main\" is parsed.\n\tErrNoSuchTemplate\n\n\t\/\/ ErrOutputContext: \"cannot compute output context for template ...\"\n\t\/\/ Examples:\n\t\/\/   {{define \"t\"}}{{if .T}}{{template \"t\" .T}}{{end}}{{.H}}\",{{end}}\n\t\/\/ Discussion:\n\t\/\/   A recursive template does not end in the same context in which it\n\t\/\/   starts, and a reliable output context cannot be computed.\n\t\/\/   Look for typos in the named template.\n\t\/\/   If the template should not be called in the named start context,\n\t\/\/   look for calls to that template in unexpected contexts.\n\t\/\/   Maybe refactor recursive templates to not be recursive.\n\tErrOutputContext\n\n\t\/\/ ErrPartialCharset: \"unfinished JS regexp charset in ...\"\n\t\/\/ Example:\n\t\/\/     <script>var pattern = \/foo[{{.Chars}}]\/<\/script>\n\t\/\/ Discussion:\n\t\/\/   Package html\/template does not support interpolation into regular\n\t\/\/   expression literal character sets.\n\tErrPartialCharset\n\n\t\/\/ ErrPartialEscape: \"unfinished escape sequence in ...\"\n\t\/\/ Example:\n\t\/\/   <script>alert(\"\\{{.X}}\")<\/script>\n\t\/\/ Discussion:\n\t\/\/   Package html\/template does not support actions following a\n\t\/\/   backslash.\n\t\/\/   This is usually an error and there are better solutions; for\n\t\/\/   example\n\t\/\/     <script>alert(\"{{.X}}\")<\/script>\n\t\/\/   should work, and if {{.X}} is a partial escape sequence such as\n\t\/\/   \"xA0\", mark the whole sequence as safe content: JSStr(`\\xA0`)\n\tErrPartialEscape\n\n\t\/\/ ErrRangeLoopReentry: \"on range loop re-entry: ...\"\n\t\/\/ Example:\n\t\/\/   <script>var x = [{{range .}}'{{.}},{{end}}]<\/script>\n\t\/\/ Discussion:\n\t\/\/   If an iteration through a range would cause it to end in a\n\t\/\/   different context than an earlier pass, there is no single context.\n\t\/\/   In the example, there is missing a quote, so it is not clear\n\t\/\/   whether {{.}} is meant to be inside a JS string or in a JS value\n\t\/\/   context.  The second iteration would produce something like\n\t\/\/\n\t\/\/     <script>var x = ['firstValue,'secondValue]<\/script>\n\tErrRangeLoopReentry\n\n\t\/\/ ErrSlashAmbig: '\/' could start a division or regexp.\n\t\/\/ Example:\n\t\/\/   <script>\n\t\/\/     {{if .C}}var x = 1{{end}}\n\t\/\/     \/-{{.N}}\/i.test(x) ? doThis : doThat();\n\t\/\/   <\/script>\n\t\/\/ Discussion:\n\t\/\/   The example above could produce `var x = 1\/-2\/i.test(s)...`\n\t\/\/   in which the first '\/' is a mathematical division operator or it\n\t\/\/   could produce `\/-2\/i.test(s)` in which the first '\/' starts a\n\t\/\/   regexp literal.\n\t\/\/   Look for missing semicolons inside branches, and maybe add\n\t\/\/   parentheses to make it clear which interpretation you intend.\n\tErrSlashAmbig\n)\n\nfunc (e *Error) Error() string {\n\tif e.Line != 0 {\n\t\treturn fmt.Sprintf(\"html\/template:%s:%d: %s\", e.Name, e.Line, e.Description)\n\t} else if e.Name != \"\" {\n\t\treturn fmt.Sprintf(\"html\/template:%s: %s\", e.Name, e.Description)\n\t}\n\treturn \"html\/template: \" + e.Description\n}\n\n\/\/ errorf creates an error given a format string f and args.\n\/\/ The template Name still needs to be supplied.\nfunc errorf(k ErrorCode, line int, f string, args ...interface{}) *Error {\n\treturn &Error{k, \"\", line, fmt.Sprintf(f, args...)}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016-2019 terraform-provider-sakuracloud authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage sakuracloud\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/httpclient\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/sacloud\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/sacloud\/fake\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/sacloud\/trace\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/utils\/builder\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/utils\/setup\"\n)\n\nconst (\n\ttraceHTTP = \"http\"\n\ttraceAPI  = \"api\"\n)\n\nconst uaEnvVar = \"SAKURACLOUD_APPEND_USER_AGENT\"\n\nvar (\n\tfakeModeOnce                    sync.Once\n\tv2ClientOnce                    sync.Once\n\tdeletionWaiterTimeout           = 30 * time.Minute\n\tdeletionWaiterPollingInterval   = 5 * time.Second\n\tdatabaseWaitAfterCreateDuration = 1 * time.Minute\n)\n\n\/\/ Config type of SakuraCloud Config\ntype Config struct {\n\tAccessToken         string\n\tAccessTokenSecret   string\n\tZone                string\n\tZones               []string\n\tTraceMode           string\n\tFakeMode            string\n\tFakeStorePath       string\n\tAcceptLanguage      string\n\tAPIRootURL          string\n\tRetryMax            int\n\tRetryInterval       int\n\tAPIRequestTimeout   int\n\tAPIRequestRateLimit int\n\n\tterraformVersion string\n\tinitOnce         sync.Once\n}\n\n\/\/ APIClient for SakuraCloud API\ntype APIClient struct {\n\tsacloud.APICaller\n\tdefaultZone                     string\n\tzones                           []string\n\tdeletionWaiterTimeout           time.Duration\n\tdeletionWaiterPollingInterval   time.Duration\n\tdatabaseWaitAfterCreateDuration time.Duration\n}\n\n\/\/ NewClient returns new API Client for SakuraCloud\nfunc (c *Config) NewClient() *APIClient {\n\n\ttfUserAgent := httpclient.TerraformUserAgent(c.terraformVersion)\n\tproviderUserAgent := fmt.Sprintf(\"%s\/v%s\", \"terraform-provider-sakuracloud\", Version)\n\tua := fmt.Sprintf(\"%s %s\", tfUserAgent, providerUserAgent)\n\tif add := os.Getenv(uaEnvVar); add != \"\" {\n\t\tua += \" \" + add\n\t\tlog.Printf(\"[DEBUG] Using modified User-Agent: %s\", ua)\n\t}\n\n\thttpClient := &http.Client{\n\t\tTimeout:   time.Duration(c.APIRequestTimeout) * time.Second,\n\t\tTransport: &sacloud.RateLimitRoundTripper{RateLimitPerSec: c.APIRequestRateLimit},\n\t}\n\tcaller := &sacloud.Client{\n\t\tAccessToken:       c.AccessToken,\n\t\tAccessTokenSecret: c.AccessTokenSecret,\n\t\tUserAgent:         ua,\n\t\tAcceptLanguage:    c.AcceptLanguage,\n\t\tRetryMax:          c.RetryMax,\n\t\tRetryInterval:     time.Duration(c.RetryInterval) * time.Second,\n\t\tHTTPClient:        httpClient,\n\t}\n\tsacloud.DefaultStatePollingTimeout = 72 * time.Hour\n\n\tif c.TraceMode != \"\" {\n\t\tenableAPITrace := true\n\t\tenableHTTPTrace := true\n\n\t\tmode := strings.ToLower(c.TraceMode)\n\t\tswitch mode {\n\t\tcase traceAPI:\n\t\t\tenableHTTPTrace = false\n\t\tcase traceHTTP:\n\t\t\tenableAPITrace = false\n\t\t}\n\n\t\tif enableAPITrace {\n\t\t\tv2ClientOnce.Do(func() {\n\t\t\t\ttrace.AddClientFactoryHooks()\n\t\t\t})\n\t\t}\n\t\tif enableHTTPTrace {\n\t\t\tcaller.HTTPClient.Transport = &sacloud.TracingRoundTripper{\n\t\t\t\tTransport: caller.HTTPClient.Transport,\n\t\t\t}\n\t\t}\n\t}\n\n\tif c.FakeMode != \"\" {\n\t\tif c.FakeStorePath != \"\" {\n\t\t\tfake.DataStore = fake.NewJSONFileStore(c.FakeStorePath)\n\t\t}\n\t\tfakeModeOnce.Do(func() {\n\t\t\tfake.SwitchFactoryFuncToFake()\n\t\t})\n\n\t\t\/\/ TODO パラメータ化\n\t\tdeletionWaiterTimeout = 10 * time.Second\n\t\tdefaultInterval := 10 * time.Millisecond\n\t\tdeletionWaiterPollingInterval = defaultInterval\n\t\tdatabaseWaitAfterCreateDuration = defaultInterval\n\n\t\t\/\/ update default polling intervals: libsacloud\/sacloud\n\t\tsacloud.DefaultStatePollingInterval = defaultInterval\n\t\tsacloud.APIDefaultRetryInterval = defaultInterval\n\t\t\/\/ update default polling intervals: libsacloud\/utils\/setup\n\t\tsetup.DefaultDeleteWaitInterval = defaultInterval\n\t\tsetup.DefaultProvisioningWaitInterval = defaultInterval\n\t\tsetup.DefaultPollingInterval = defaultInterval\n\t\t\/\/ update default polling intervals: libsacloud\/utils\/builder\n\t\tbuilder.DefaultNICUpdateWaitDuration = defaultInterval\n\t}\n\n\tzones := c.Zones\n\tif len(zones) == 0 {\n\t\tzones = defaultZones\n\t}\n\tif c.APIRootURL != \"\" {\n\t\tif strings.HasSuffix(c.APIRootURL, \"\/\") {\n\t\t\tc.APIRootURL = strings.TrimRight(c.APIRootURL, \"\/\")\n\t\t}\n\t\tsacloud.SakuraCloudAPIRoot = c.APIRootURL\n\t}\n\n\treturn &APIClient{\n\t\tAPICaller:                       caller,\n\t\tdefaultZone:                     c.Zone,\n\t\tzones:                           zones,\n\t\tdeletionWaiterTimeout:           deletionWaiterTimeout,\n\t\tdeletionWaiterPollingInterval:   deletionWaiterPollingInterval,\n\t\tdatabaseWaitAfterCreateDuration: databaseWaitAfterCreateDuration,\n\t}\n}\n<commit_msg>lint: structcheck<commit_after>\/\/ Copyright 2016-2019 terraform-provider-sakuracloud authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage sakuracloud\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/httpclient\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/sacloud\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/sacloud\/fake\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/sacloud\/trace\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/utils\/builder\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/utils\/setup\"\n)\n\nconst (\n\ttraceHTTP = \"http\"\n\ttraceAPI  = \"api\"\n)\n\nconst uaEnvVar = \"SAKURACLOUD_APPEND_USER_AGENT\"\n\nvar (\n\tfakeModeOnce                    sync.Once\n\tv2ClientOnce                    sync.Once\n\tdeletionWaiterTimeout           = 30 * time.Minute\n\tdeletionWaiterPollingInterval   = 5 * time.Second\n\tdatabaseWaitAfterCreateDuration = 1 * time.Minute\n)\n\n\/\/ Config type of SakuraCloud Config\ntype Config struct {\n\tAccessToken         string\n\tAccessTokenSecret   string\n\tZone                string\n\tZones               []string\n\tTraceMode           string\n\tFakeMode            string\n\tFakeStorePath       string\n\tAcceptLanguage      string\n\tAPIRootURL          string\n\tRetryMax            int\n\tRetryInterval       int\n\tAPIRequestTimeout   int\n\tAPIRequestRateLimit int\n\n\tterraformVersion string\n}\n\n\/\/ APIClient for SakuraCloud API\ntype APIClient struct {\n\tsacloud.APICaller\n\tdefaultZone                     string\n\tzones                           []string\n\tdeletionWaiterTimeout           time.Duration\n\tdeletionWaiterPollingInterval   time.Duration\n\tdatabaseWaitAfterCreateDuration time.Duration\n}\n\n\/\/ NewClient returns new API Client for SakuraCloud\nfunc (c *Config) NewClient() *APIClient {\n\n\ttfUserAgent := httpclient.TerraformUserAgent(c.terraformVersion)\n\tproviderUserAgent := fmt.Sprintf(\"%s\/v%s\", \"terraform-provider-sakuracloud\", Version)\n\tua := fmt.Sprintf(\"%s %s\", tfUserAgent, providerUserAgent)\n\tif add := os.Getenv(uaEnvVar); add != \"\" {\n\t\tua += \" \" + add\n\t\tlog.Printf(\"[DEBUG] Using modified User-Agent: %s\", ua)\n\t}\n\n\thttpClient := &http.Client{\n\t\tTimeout:   time.Duration(c.APIRequestTimeout) * time.Second,\n\t\tTransport: &sacloud.RateLimitRoundTripper{RateLimitPerSec: c.APIRequestRateLimit},\n\t}\n\tcaller := &sacloud.Client{\n\t\tAccessToken:       c.AccessToken,\n\t\tAccessTokenSecret: c.AccessTokenSecret,\n\t\tUserAgent:         ua,\n\t\tAcceptLanguage:    c.AcceptLanguage,\n\t\tRetryMax:          c.RetryMax,\n\t\tRetryInterval:     time.Duration(c.RetryInterval) * time.Second,\n\t\tHTTPClient:        httpClient,\n\t}\n\tsacloud.DefaultStatePollingTimeout = 72 * time.Hour\n\n\tif c.TraceMode != \"\" {\n\t\tenableAPITrace := true\n\t\tenableHTTPTrace := true\n\n\t\tmode := strings.ToLower(c.TraceMode)\n\t\tswitch mode {\n\t\tcase traceAPI:\n\t\t\tenableHTTPTrace = false\n\t\tcase traceHTTP:\n\t\t\tenableAPITrace = false\n\t\t}\n\n\t\tif enableAPITrace {\n\t\t\tv2ClientOnce.Do(func() {\n\t\t\t\ttrace.AddClientFactoryHooks()\n\t\t\t})\n\t\t}\n\t\tif enableHTTPTrace {\n\t\t\tcaller.HTTPClient.Transport = &sacloud.TracingRoundTripper{\n\t\t\t\tTransport: caller.HTTPClient.Transport,\n\t\t\t}\n\t\t}\n\t}\n\n\tif c.FakeMode != \"\" {\n\t\tif c.FakeStorePath != \"\" {\n\t\t\tfake.DataStore = fake.NewJSONFileStore(c.FakeStorePath)\n\t\t}\n\t\tfakeModeOnce.Do(func() {\n\t\t\tfake.SwitchFactoryFuncToFake()\n\t\t})\n\n\t\t\/\/ TODO パラメータ化\n\t\tdeletionWaiterTimeout = 10 * time.Second\n\t\tdefaultInterval := 10 * time.Millisecond\n\t\tdeletionWaiterPollingInterval = defaultInterval\n\t\tdatabaseWaitAfterCreateDuration = defaultInterval\n\n\t\t\/\/ update default polling intervals: libsacloud\/sacloud\n\t\tsacloud.DefaultStatePollingInterval = defaultInterval\n\t\tsacloud.APIDefaultRetryInterval = defaultInterval\n\t\t\/\/ update default polling intervals: libsacloud\/utils\/setup\n\t\tsetup.DefaultDeleteWaitInterval = defaultInterval\n\t\tsetup.DefaultProvisioningWaitInterval = defaultInterval\n\t\tsetup.DefaultPollingInterval = defaultInterval\n\t\t\/\/ update default polling intervals: libsacloud\/utils\/builder\n\t\tbuilder.DefaultNICUpdateWaitDuration = defaultInterval\n\t}\n\n\tzones := c.Zones\n\tif len(zones) == 0 {\n\t\tzones = defaultZones\n\t}\n\tif c.APIRootURL != \"\" {\n\t\tif strings.HasSuffix(c.APIRootURL, \"\/\") {\n\t\t\tc.APIRootURL = strings.TrimRight(c.APIRootURL, \"\/\")\n\t\t}\n\t\tsacloud.SakuraCloudAPIRoot = c.APIRootURL\n\t}\n\n\treturn &APIClient{\n\t\tAPICaller:                       caller,\n\t\tdefaultZone:                     c.Zone,\n\t\tzones:                           zones,\n\t\tdeletionWaiterTimeout:           deletionWaiterTimeout,\n\t\tdeletionWaiterPollingInterval:   deletionWaiterPollingInterval,\n\t\tdatabaseWaitAfterCreateDuration: databaseWaitAfterCreateDuration,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright The Helm Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage chartutil\n\nimport (\n\t\"archive\/tar\"\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/golang\/protobuf\/ptypes\/any\"\n\n\t\"k8s.io\/helm\/pkg\/ignore\"\n\t\"k8s.io\/helm\/pkg\/proto\/hapi\/chart\"\n\t\"k8s.io\/helm\/pkg\/sympath\"\n)\n\n\/\/ Load takes a string name, tries to resolve it to a file or directory, and then loads it.\n\/\/\n\/\/ This is the preferred way to load a chart. It will discover the chart encoding\n\/\/ and hand off to the appropriate chart reader.\n\/\/\n\/\/ If a .helmignore file is present, the directory loader will skip loading any files\n\/\/ matching it. But .helmignore is not evaluated when reading out of an archive.\nfunc Load(name string) (*chart.Chart, error) {\n\tname = filepath.FromSlash(name)\n\tfi, err := os.Stat(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif fi.IsDir() {\n\t\tif validChart, err := IsChartDir(name); !validChart {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn LoadDir(name)\n\t}\n\treturn LoadFile(name)\n}\n\n\/\/ BufferedFile represents an archive file buffered for later processing.\ntype BufferedFile struct {\n\tName string\n\tData []byte\n}\n\nvar drivePathPattern = regexp.MustCompile(`^[a-zA-Z]:\/`)\n\n\/\/ loadArchiveFiles loads files out of an archive\nfunc loadArchiveFiles(in io.Reader) ([]*BufferedFile, error) {\n\tunzipped, err := gzip.NewReader(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer unzipped.Close()\n\n\tfiles := []*BufferedFile{}\n\ttr := tar.NewReader(unzipped)\n\tfor {\n\t\tb := bytes.NewBuffer(nil)\n\t\thd, err := tr.Next()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif hd.FileInfo().IsDir() {\n\t\t\t\/\/ Use this instead of hd.Typeflag because we don't have to do any\n\t\t\t\/\/ inference chasing.\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Archive could contain \\ if generated on Windows\n\t\tdelimiter := \"\/\"\n\t\tif strings.ContainsRune(hd.Name, '\\\\') {\n\t\t\tdelimiter = \"\\\\\"\n\t\t}\n\n\t\tparts := strings.Split(hd.Name, delimiter)\n\t\tn := strings.Join(parts[1:], delimiter)\n\n\t\t\/\/ Normalize the path to the \/ delimiter\n\t\tn = strings.Replace(n, delimiter, \"\/\", -1)\n\n\t\tif path.IsAbs(n) {\n\t\t\treturn nil, errors.New(\"chart illegally contains absolute paths\")\n\t\t}\n\n\t\tn = path.Clean(n)\n\t\tif n == \".\" {\n\t\t\t\/\/ In this case, the original path was relative when it should have been absolute.\n\t\t\treturn nil, errors.New(\"chart illegally contains empty path\")\n\t\t}\n\t\tif strings.HasPrefix(n, \"..\") {\n\t\t\treturn nil, errors.New(\"chart illegally references parent directory\")\n\t\t}\n\n\t\t\/\/ In some particularly arcane acts of path creativity, it is possible to intermix\n\t\t\/\/ UNIX and Windows style paths in such a way that you produce a result of the form\n\t\t\/\/ c:\/foo even after all the built-in absolute path checks. So we explicitly check\n\t\t\/\/ for this condition.\n\t\tif drivePathPattern.MatchString(n) {\n\t\t\treturn nil, errors.New(\"chart contains illegally named files\")\n\t\t}\n\n\t\tif parts[0] == \"Chart.yaml\" {\n\t\t\treturn nil, errors.New(\"chart yaml not in base directory\")\n\t\t}\n\n\t\tif _, err := io.Copy(b, tr); err != nil {\n\t\t\treturn files, err\n\t\t}\n\n\t\tfiles = append(files, &BufferedFile{Name: n, Data: b.Bytes()})\n\t\tb.Reset()\n\t}\n\n\tif len(files) == 0 {\n\t\treturn nil, errors.New(\"no files in chart archive\")\n\t}\n\treturn files, nil\n}\n\n\/\/ LoadArchive loads from a reader containing a compressed tar archive.\nfunc LoadArchive(in io.Reader) (*chart.Chart, error) {\n\tfiles, err := loadArchiveFiles(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn LoadFiles(files)\n}\n\n\/\/ LoadFiles loads from in-memory files.\nfunc LoadFiles(files []*BufferedFile) (*chart.Chart, error) {\n\tc := &chart.Chart{}\n\tsubcharts := map[string][]*BufferedFile{}\n\n\tfor _, f := range files {\n\t\tif f.Name == \"Chart.yaml\" {\n\t\t\tm, err := UnmarshalChartfile(f.Data)\n\t\t\tif err != nil {\n\t\t\t\treturn c, err\n\t\t\t}\n\t\t\tc.Metadata = m\n\t\t} else if f.Name == \"values.toml\" {\n\t\t\treturn c, errors.New(\"values.toml is illegal as of 2.0.0-alpha.2\")\n\t\t} else if f.Name == \"values.yaml\" {\n\t\t\tc.Values = &chart.Config{Raw: string(f.Data)}\n\t\t} else if strings.HasPrefix(f.Name, \"templates\/\") {\n\t\t\tc.Templates = append(c.Templates, &chart.Template{Name: f.Name, Data: f.Data})\n\t\t} else if strings.HasPrefix(f.Name, \"charts\/\") {\n\t\t\tif filepath.Ext(f.Name) == \".prov\" {\n\t\t\t\tc.Files = append(c.Files, &any.Any{TypeUrl: f.Name, Value: f.Data})\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcname := strings.TrimPrefix(f.Name, \"charts\/\")\n\t\t\tif strings.IndexAny(cname, \"._\") == 0 {\n\t\t\t\t\/\/ Ignore charts\/ that start with . or _.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tparts := strings.SplitN(cname, \"\/\", 2)\n\t\t\tscname := parts[0]\n\t\t\tsubcharts[scname] = append(subcharts[scname], &BufferedFile{Name: cname, Data: f.Data})\n\t\t} else {\n\t\t\tc.Files = append(c.Files, &any.Any{TypeUrl: f.Name, Value: f.Data})\n\t\t}\n\t}\n\n\t\/\/ Ensure that we got a Chart.yaml file\n\tif c.Metadata == nil {\n\t\treturn c, errors.New(\"chart metadata (Chart.yaml) missing\")\n\t}\n\tif c.Metadata.Name == \"\" {\n\t\treturn c, errors.New(\"invalid chart (Chart.yaml): name must not be empty\")\n\t}\n\n\tfor n, files := range subcharts {\n\t\tvar sc *chart.Chart\n\t\tvar err error\n\t\tif strings.IndexAny(n, \"_.\") == 0 {\n\t\t\tcontinue\n\t\t} else if filepath.Ext(n) == \".tgz\" {\n\t\t\tfile := files[0]\n\t\t\tif file.Name != n {\n\t\t\t\treturn c, fmt.Errorf(\"error unpacking tar in %s: expected %s, got %s\", c.Metadata.Name, n, file.Name)\n\t\t\t}\n\t\t\t\/\/ Untar the chart and add to c.Dependencies\n\t\t\tb := bytes.NewBuffer(file.Data)\n\t\t\tsc, err = LoadArchive(b)\n\t\t} else {\n\t\t\t\/\/ We have to trim the prefix off of every file, and ignore any file\n\t\t\t\/\/ that is in charts\/, but isn't actually a chart.\n\t\t\tbuff := make([]*BufferedFile, 0, len(files))\n\t\t\tfor _, f := range files {\n\t\t\t\tparts := strings.SplitN(f.Name, \"\/\", 2)\n\t\t\t\tif len(parts) < 2 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tf.Name = parts[1]\n\t\t\t\tbuff = append(buff, f)\n\t\t\t}\n\t\t\tsc, err = LoadFiles(buff)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn c, fmt.Errorf(\"error unpacking %s in %s: %s\", n, c.Metadata.Name, err)\n\t\t}\n\n\t\tc.Dependencies = append(c.Dependencies, sc)\n\t}\n\n\treturn c, nil\n}\n\n\/\/ LoadFile loads from an archive file.\nfunc LoadFile(name string) (*chart.Chart, error) {\n\tif fi, err := os.Stat(name); err != nil {\n\t\treturn nil, err\n\t} else if fi.IsDir() {\n\t\treturn nil, errors.New(\"cannot load a directory\")\n\t}\n\n\traw, err := os.Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer raw.Close()\n\n\treturn LoadArchive(raw)\n}\n\n\/\/ LoadDir loads from a directory.\n\/\/\n\/\/ This loads charts only from directories.\nfunc LoadDir(dir string) (*chart.Chart, error) {\n\ttopdir, err := filepath.Abs(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Just used for errors.\n\tc := &chart.Chart{}\n\n\trules := ignore.Empty()\n\tifile := filepath.Join(topdir, ignore.HelmIgnore)\n\tif _, err := os.Stat(ifile); err == nil {\n\t\tr, err := ignore.ParseFile(ifile)\n\t\tif err != nil {\n\t\t\treturn c, err\n\t\t}\n\t\trules = r\n\t}\n\trules.AddDefaults()\n\n\tfiles := []*BufferedFile{}\n\ttopdir += string(filepath.Separator)\n\n\twalk := func(name string, fi os.FileInfo, err error) error {\n\t\tn := strings.TrimPrefix(name, topdir)\n\t\tif n == \"\" {\n\t\t\t\/\/ No need to process top level. Avoid bug with helmignore .* matching\n\t\t\t\/\/ empty names. See issue 1779.\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ Normalize to \/ since it will also work on Windows\n\t\tn = filepath.ToSlash(n)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif fi.IsDir() {\n\t\t\t\/\/ Directory-based ignore rules should involve skipping the entire\n\t\t\t\/\/ contents of that directory.\n\t\t\tif rules.Ignore(n, fi) {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ If a .helmignore file matches, skip this file.\n\t\tif rules.Ignore(n, fi) {\n\t\t\treturn nil\n\t\t}\n\n\t\tdata, err := ioutil.ReadFile(name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading %s: %s\", n, err)\n\t\t}\n\n\t\tfiles = append(files, &BufferedFile{Name: n, Data: data})\n\t\treturn nil\n\t}\n\tif err = sympath.Walk(topdir, walk); err != nil {\n\t\treturn c, err\n\t}\n\n\treturn LoadFiles(files)\n}\n<commit_msg>fix: ignore pax header \"file\"s in chart validation<commit_after>\/*\nCopyright The Helm Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage chartutil\n\nimport (\n\t\"archive\/tar\"\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/golang\/protobuf\/ptypes\/any\"\n\n\t\"k8s.io\/helm\/pkg\/ignore\"\n\t\"k8s.io\/helm\/pkg\/proto\/hapi\/chart\"\n\t\"k8s.io\/helm\/pkg\/sympath\"\n)\n\n\/\/ Load takes a string name, tries to resolve it to a file or directory, and then loads it.\n\/\/\n\/\/ This is the preferred way to load a chart. It will discover the chart encoding\n\/\/ and hand off to the appropriate chart reader.\n\/\/\n\/\/ If a .helmignore file is present, the directory loader will skip loading any files\n\/\/ matching it. But .helmignore is not evaluated when reading out of an archive.\nfunc Load(name string) (*chart.Chart, error) {\n\tname = filepath.FromSlash(name)\n\tfi, err := os.Stat(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif fi.IsDir() {\n\t\tif validChart, err := IsChartDir(name); !validChart {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn LoadDir(name)\n\t}\n\treturn LoadFile(name)\n}\n\n\/\/ BufferedFile represents an archive file buffered for later processing.\ntype BufferedFile struct {\n\tName string\n\tData []byte\n}\n\nvar drivePathPattern = regexp.MustCompile(`^[a-zA-Z]:\/`)\n\n\/\/ loadArchiveFiles loads files out of an archive\nfunc loadArchiveFiles(in io.Reader) ([]*BufferedFile, error) {\n\tunzipped, err := gzip.NewReader(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer unzipped.Close()\n\n\tfiles := []*BufferedFile{}\n\ttr := tar.NewReader(unzipped)\n\tfor {\n\t\tb := bytes.NewBuffer(nil)\n\t\thd, err := tr.Next()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif hd.FileInfo().IsDir() {\n\t\t\t\/\/ Use this instead of hd.Typeflag because we don't have to do any\n\t\t\t\/\/ inference chasing.\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch hd.Typeflag {\n\t\t\/\/ We don't want to process these extension header files.\n\t\tcase tar.TypeXGlobalHeader, tar.TypeXHeader:\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Archive could contain \\ if generated on Windows\n\t\tdelimiter := \"\/\"\n\t\tif strings.ContainsRune(hd.Name, '\\\\') {\n\t\t\tdelimiter = \"\\\\\"\n\t\t}\n\n\t\tparts := strings.Split(hd.Name, delimiter)\n\t\tn := strings.Join(parts[1:], delimiter)\n\n\t\t\/\/ Normalize the path to the \/ delimiter\n\t\tn = strings.Replace(n, delimiter, \"\/\", -1)\n\n\t\tif path.IsAbs(n) {\n\t\t\treturn nil, errors.New(\"chart illegally contains absolute paths\")\n\t\t}\n\n\t\tn = path.Clean(n)\n\t\tif n == \".\" {\n\t\t\t\/\/ In this case, the original path was relative when it should have been absolute.\n\t\t\treturn nil, errors.New(\"chart illegally contains empty path\")\n\t\t}\n\t\tif strings.HasPrefix(n, \"..\") {\n\t\t\treturn nil, errors.New(\"chart illegally references parent directory\")\n\t\t}\n\n\t\t\/\/ In some particularly arcane acts of path creativity, it is possible to intermix\n\t\t\/\/ UNIX and Windows style paths in such a way that you produce a result of the form\n\t\t\/\/ c:\/foo even after all the built-in absolute path checks. So we explicitly check\n\t\t\/\/ for this condition.\n\t\tif drivePathPattern.MatchString(n) {\n\t\t\treturn nil, errors.New(\"chart contains illegally named files\")\n\t\t}\n\n\t\tif parts[0] == \"Chart.yaml\" {\n\t\t\treturn nil, errors.New(\"chart yaml not in base directory\")\n\t\t}\n\n\t\tif _, err := io.Copy(b, tr); err != nil {\n\t\t\treturn files, err\n\t\t}\n\n\t\tfiles = append(files, &BufferedFile{Name: n, Data: b.Bytes()})\n\t\tb.Reset()\n\t}\n\n\tif len(files) == 0 {\n\t\treturn nil, errors.New(\"no files in chart archive\")\n\t}\n\treturn files, nil\n}\n\n\/\/ LoadArchive loads from a reader containing a compressed tar archive.\nfunc LoadArchive(in io.Reader) (*chart.Chart, error) {\n\tfiles, err := loadArchiveFiles(in)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn LoadFiles(files)\n}\n\n\/\/ LoadFiles loads from in-memory files.\nfunc LoadFiles(files []*BufferedFile) (*chart.Chart, error) {\n\tc := &chart.Chart{}\n\tsubcharts := map[string][]*BufferedFile{}\n\n\tfor _, f := range files {\n\t\tif f.Name == \"Chart.yaml\" {\n\t\t\tm, err := UnmarshalChartfile(f.Data)\n\t\t\tif err != nil {\n\t\t\t\treturn c, err\n\t\t\t}\n\t\t\tc.Metadata = m\n\t\t} else if f.Name == \"values.toml\" {\n\t\t\treturn c, errors.New(\"values.toml is illegal as of 2.0.0-alpha.2\")\n\t\t} else if f.Name == \"values.yaml\" {\n\t\t\tc.Values = &chart.Config{Raw: string(f.Data)}\n\t\t} else if strings.HasPrefix(f.Name, \"templates\/\") {\n\t\t\tc.Templates = append(c.Templates, &chart.Template{Name: f.Name, Data: f.Data})\n\t\t} else if strings.HasPrefix(f.Name, \"charts\/\") {\n\t\t\tif filepath.Ext(f.Name) == \".prov\" {\n\t\t\t\tc.Files = append(c.Files, &any.Any{TypeUrl: f.Name, Value: f.Data})\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcname := strings.TrimPrefix(f.Name, \"charts\/\")\n\t\t\tif strings.IndexAny(cname, \"._\") == 0 {\n\t\t\t\t\/\/ Ignore charts\/ that start with . or _.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tparts := strings.SplitN(cname, \"\/\", 2)\n\t\t\tscname := parts[0]\n\t\t\tsubcharts[scname] = append(subcharts[scname], &BufferedFile{Name: cname, Data: f.Data})\n\t\t} else {\n\t\t\tc.Files = append(c.Files, &any.Any{TypeUrl: f.Name, Value: f.Data})\n\t\t}\n\t}\n\n\t\/\/ Ensure that we got a Chart.yaml file\n\tif c.Metadata == nil {\n\t\treturn c, errors.New(\"chart metadata (Chart.yaml) missing\")\n\t}\n\tif c.Metadata.Name == \"\" {\n\t\treturn c, errors.New(\"invalid chart (Chart.yaml): name must not be empty\")\n\t}\n\n\tfor n, files := range subcharts {\n\t\tvar sc *chart.Chart\n\t\tvar err error\n\t\tif strings.IndexAny(n, \"_.\") == 0 {\n\t\t\tcontinue\n\t\t} else if filepath.Ext(n) == \".tgz\" {\n\t\t\tfile := files[0]\n\t\t\tif file.Name != n {\n\t\t\t\treturn c, fmt.Errorf(\"error unpacking tar in %s: expected %s, got %s\", c.Metadata.Name, n, file.Name)\n\t\t\t}\n\t\t\t\/\/ Untar the chart and add to c.Dependencies\n\t\t\tb := bytes.NewBuffer(file.Data)\n\t\t\tsc, err = LoadArchive(b)\n\t\t} else {\n\t\t\t\/\/ We have to trim the prefix off of every file, and ignore any file\n\t\t\t\/\/ that is in charts\/, but isn't actually a chart.\n\t\t\tbuff := make([]*BufferedFile, 0, len(files))\n\t\t\tfor _, f := range files {\n\t\t\t\tparts := strings.SplitN(f.Name, \"\/\", 2)\n\t\t\t\tif len(parts) < 2 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tf.Name = parts[1]\n\t\t\t\tbuff = append(buff, f)\n\t\t\t}\n\t\t\tsc, err = LoadFiles(buff)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn c, fmt.Errorf(\"error unpacking %s in %s: %s\", n, c.Metadata.Name, err)\n\t\t}\n\n\t\tc.Dependencies = append(c.Dependencies, sc)\n\t}\n\n\treturn c, nil\n}\n\n\/\/ LoadFile loads from an archive file.\nfunc LoadFile(name string) (*chart.Chart, error) {\n\tif fi, err := os.Stat(name); err != nil {\n\t\treturn nil, err\n\t} else if fi.IsDir() {\n\t\treturn nil, errors.New(\"cannot load a directory\")\n\t}\n\n\traw, err := os.Open(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer raw.Close()\n\n\treturn LoadArchive(raw)\n}\n\n\/\/ LoadDir loads from a directory.\n\/\/\n\/\/ This loads charts only from directories.\nfunc LoadDir(dir string) (*chart.Chart, error) {\n\ttopdir, err := filepath.Abs(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Just used for errors.\n\tc := &chart.Chart{}\n\n\trules := ignore.Empty()\n\tifile := filepath.Join(topdir, ignore.HelmIgnore)\n\tif _, err := os.Stat(ifile); err == nil {\n\t\tr, err := ignore.ParseFile(ifile)\n\t\tif err != nil {\n\t\t\treturn c, err\n\t\t}\n\t\trules = r\n\t}\n\trules.AddDefaults()\n\n\tfiles := []*BufferedFile{}\n\ttopdir += string(filepath.Separator)\n\n\twalk := func(name string, fi os.FileInfo, err error) error {\n\t\tn := strings.TrimPrefix(name, topdir)\n\t\tif n == \"\" {\n\t\t\t\/\/ No need to process top level. Avoid bug with helmignore .* matching\n\t\t\t\/\/ empty names. See issue 1779.\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ Normalize to \/ since it will also work on Windows\n\t\tn = filepath.ToSlash(n)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif fi.IsDir() {\n\t\t\t\/\/ Directory-based ignore rules should involve skipping the entire\n\t\t\t\/\/ contents of that directory.\n\t\t\tif rules.Ignore(n, fi) {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ If a .helmignore file matches, skip this file.\n\t\tif rules.Ignore(n, fi) {\n\t\t\treturn nil\n\t\t}\n\n\t\tdata, err := ioutil.ReadFile(name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading %s: %s\", n, err)\n\t\t}\n\n\t\tfiles = append(files, &BufferedFile{Name: n, Data: data})\n\t\treturn nil\n\t}\n\tif err = sympath.Walk(topdir, walk); err != nil {\n\t\treturn c, err\n\t}\n\n\treturn LoadFiles(files)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ The httptest package provides utilities for HTTP testing.\npackage httptest\n\nimport (\n\t\"bytes\"\n\t\"http\"\n\t\"os\"\n)\n\n\/\/ ResponseRecorder is an implementation of http.ResponseWriter that\n\/\/ records its mutations for later inspection in tests.\ntype ResponseRecorder struct {\n\tCode      int           \/\/ the HTTP response code from WriteHeader\n\tHeaderMap http.Header   \/\/ the HTTP response headers\n\tBody      *bytes.Buffer \/\/ if non-nil, the bytes.Buffer to append written data to\n\tFlushed   bool\n}\n\n\/\/ NewRecorder returns an initialized ResponseRecorder.\nfunc NewRecorder() *ResponseRecorder {\n\treturn &ResponseRecorder{\n\t\tHeaderMap: make(http.Header),\n\t\tBody:      new(bytes.Buffer),\n\t}\n}\n\n\/\/ DefaultRemoteAddr is the default remote address to return in RemoteAddr if\n\/\/ an explicit DefaultRemoteAddr isn't set on ResponseRecorder.\nconst DefaultRemoteAddr = \"1.2.3.4\"\n\n\/\/ Header returns the response headers.\nfunc (rw *ResponseRecorder) Header() http.Header {\n\treturn rw.HeaderMap\n}\n\n\/\/ Write always succeeds and writes to rw.Body, if not nil.\nfunc (rw *ResponseRecorder) Write(buf []byte) (int, os.Error) {\n\tif rw.Body != nil {\n\t\trw.Body.Write(buf)\n\t}\n\treturn len(buf), nil\n}\n\n\/\/ WriteHeader sets rw.Code.\nfunc (rw *ResponseRecorder) WriteHeader(code int) {\n\trw.Code = code\n}\n\n\/\/ Flush sets rw.Flushed to true.\nfunc (rw *ResponseRecorder) Flush() {\n\trw.Flushed = true\n}\n<commit_msg>httptest: default the Recorder status code to 200 on a Write<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ The httptest package provides utilities for HTTP testing.\npackage httptest\n\nimport (\n\t\"bytes\"\n\t\"http\"\n\t\"os\"\n)\n\n\/\/ ResponseRecorder is an implementation of http.ResponseWriter that\n\/\/ records its mutations for later inspection in tests.\ntype ResponseRecorder struct {\n\tCode      int           \/\/ the HTTP response code from WriteHeader\n\tHeaderMap http.Header   \/\/ the HTTP response headers\n\tBody      *bytes.Buffer \/\/ if non-nil, the bytes.Buffer to append written data to\n\tFlushed   bool\n}\n\n\/\/ NewRecorder returns an initialized ResponseRecorder.\nfunc NewRecorder() *ResponseRecorder {\n\treturn &ResponseRecorder{\n\t\tHeaderMap: make(http.Header),\n\t\tBody:      new(bytes.Buffer),\n\t}\n}\n\n\/\/ DefaultRemoteAddr is the default remote address to return in RemoteAddr if\n\/\/ an explicit DefaultRemoteAddr isn't set on ResponseRecorder.\nconst DefaultRemoteAddr = \"1.2.3.4\"\n\n\/\/ Header returns the response headers.\nfunc (rw *ResponseRecorder) Header() http.Header {\n\treturn rw.HeaderMap\n}\n\n\/\/ Write always succeeds and writes to rw.Body, if not nil.\nfunc (rw *ResponseRecorder) Write(buf []byte) (int, os.Error) {\n\tif rw.Body != nil {\n\t\trw.Body.Write(buf)\n\t}\n\tif rw.Code == 0 {\n\t\trw.Code = http.StatusOK\n\t}\n\treturn len(buf), nil\n}\n\n\/\/ WriteHeader sets rw.Code.\nfunc (rw *ResponseRecorder) WriteHeader(code int) {\n\trw.Code = code\n}\n\n\/\/ Flush sets rw.Flushed to true.\nfunc (rw *ResponseRecorder) Flush() {\n\trw.Flushed = true\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage master\n\nimport (\n\t\"crypto\/x509\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n\n\tkubeadmapi \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/apis\/extensions\"\n\tclientset \"k8s.io\/kubernetes\/pkg\/client\/clientset_generated\/internalclientset\"\n\tcertutil \"k8s.io\/kubernetes\/pkg\/util\/cert\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/wait\"\n)\n\ntype kubeDiscovery struct {\n\tDeployment *extensions.Deployment\n\tSecret     *api.Secret\n}\n\nconst (\n\tkubeDiscoveryName       = \"kube-discovery\"\n\tkubeDiscoverySecretName = \"clusterinfo\"\n)\n\nfunc encodeKubeDiscoverySecretData(s *kubeadmapi.KubeadmConfig, caCert *x509.Certificate) map[string][]byte {\n\tvar (\n\t\tdata         = map[string][]byte{}\n\t\tendpointList = []string{}\n\t\ttokenMap     = map[string]string{}\n\t)\n\n\tfor _, addr := range s.InitFlags.API.AdvertiseAddrs {\n\t\tendpointList = append(endpointList, fmt.Sprintf(\"https:\/\/%s:443\", addr.String()))\n\t}\n\n\ttokenMap[s.Secrets.TokenID] = hex.EncodeToString(s.Secrets.Token)\n\n\tdata[\"endpoint-list.json\"], _ = json.Marshal(endpointList)\n\tdata[\"token-map.json\"], _ = json.Marshal(tokenMap)\n\tdata[\"ca.pem\"] = certutil.EncodeCertPEM(caCert)\n\n\treturn data\n}\n\nfunc newKubeDiscoveryPodSpec(s *kubeadmapi.KubeadmConfig) api.PodSpec {\n\treturn api.PodSpec{\n\t\t\/\/ We have to use host network namespace, as `HostPort`\/`HostIP` are Docker's\n\t\t\/\/ buisness and CNI support isn't quite there yet (except for kubenet)\n\t\t\/\/ (see https:\/\/github.com\/kubernetes\/kubernetes\/issues\/31307)\n\t\t\/\/ TODO update this when #31307 is resolved\n\t\tSecurityContext: &api.PodSecurityContext{HostNetwork: true},\n\t\tContainers: []api.Container{{\n\t\t\tName:    kubeDiscoveryName,\n\t\t\tImage:   s.EnvParams[\"discovery_image\"],\n\t\t\tCommand: []string{\"\/usr\/local\/bin\/kube-discovery\"},\n\t\t\tVolumeMounts: []api.VolumeMount{{\n\t\t\t\tName:      kubeDiscoverySecretName,\n\t\t\t\tMountPath: \"\/tmp\/secret\", \/\/ TODO use a shared constant\n\t\t\t\tReadOnly:  true,\n\t\t\t}},\n\t\t\tPorts: []api.ContainerPort{\n\t\t\t\t\/\/ TODO when CNI issue (#31307) is resolved, we should consider adding\n\t\t\t\t\/\/ `HostIP: s.API.AdvertiseAddrs[0]`, if there is only one address`\n\t\t\t\t{Name: \"http\", ContainerPort: 9898, HostPort: 9898},\n\t\t\t},\n\t\t}},\n\t\tVolumes: []api.Volume{{\n\t\t\tName: kubeDiscoverySecretName,\n\t\t\tVolumeSource: api.VolumeSource{\n\t\t\t\tSecret: &api.SecretVolumeSource{SecretName: kubeDiscoverySecretName},\n\t\t\t}},\n\t\t},\n\t}\n}\n\nfunc newKubeDiscovery(s *kubeadmapi.KubeadmConfig, caCert *x509.Certificate) kubeDiscovery {\n\tkd := kubeDiscovery{\n\t\tDeployment: NewDeployment(kubeDiscoveryName, 1, newKubeDiscoveryPodSpec(s)),\n\t\tSecret: &api.Secret{\n\t\t\tObjectMeta: api.ObjectMeta{Name: kubeDiscoverySecretName},\n\t\t\tType:       api.SecretTypeOpaque,\n\t\t\tData:       encodeKubeDiscoverySecretData(s, caCert),\n\t\t},\n\t}\n\n\tSetMasterTaintTolerations(&kd.Deployment.Spec.Template.ObjectMeta)\n\tSetMasterNodeAffinity(&kd.Deployment.Spec.Template.ObjectMeta)\n\n\treturn kd\n}\n\nfunc CreateDiscoveryDeploymentAndSecret(s *kubeadmapi.KubeadmConfig, client *clientset.Clientset, caCert *x509.Certificate) error {\n\tkd := newKubeDiscovery(s, caCert)\n\n\tif _, err := client.Extensions().Deployments(api.NamespaceSystem).Create(kd.Deployment); err != nil {\n\t\treturn fmt.Errorf(\"<master\/discovery> failed to create %q deployment [%s]\", kubeDiscoveryName, err)\n\t}\n\tif _, err := client.Secrets(api.NamespaceSystem).Create(kd.Secret); err != nil {\n\t\treturn fmt.Errorf(\"<master\/discovery> failed to create %q secret [%s]\", kubeDiscoverySecretName, err)\n\t}\n\n\tfmt.Println(\"<master\/discovery> created essential addon: kube-discovery, waiting for it to become ready\")\n\n\tstart := time.Now()\n\twait.PollInfinite(apiCallRetryInterval, func() (bool, error) {\n\t\td, err := client.Extensions().Deployments(api.NamespaceSystem).Get(kubeDiscoveryName)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif d.Status.AvailableReplicas < 1 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tfmt.Printf(\"<master\/discovery> kube-discovery is ready after %f seconds\\n\", time.Since(start).Seconds())\n\n\treturn nil\n}\n<commit_msg>Fix boostrap token encoding bug during master init<commit_after>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage master\n\nimport (\n\t\"crypto\/x509\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n\n\tkubeadmapi \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/apis\/extensions\"\n\tclientset \"k8s.io\/kubernetes\/pkg\/client\/clientset_generated\/internalclientset\"\n\tcertutil \"k8s.io\/kubernetes\/pkg\/util\/cert\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/wait\"\n)\n\ntype kubeDiscovery struct {\n\tDeployment *extensions.Deployment\n\tSecret     *api.Secret\n}\n\nconst (\n\tkubeDiscoveryName       = \"kube-discovery\"\n\tkubeDiscoverySecretName = \"clusterinfo\"\n)\n\nfunc encodeKubeDiscoverySecretData(s *kubeadmapi.KubeadmConfig, caCert *x509.Certificate) map[string][]byte {\n\tvar (\n\t\tdata         = map[string][]byte{}\n\t\tendpointList = []string{}\n\t\ttokenMap     = map[string]string{}\n\t)\n\n\tfor _, addr := range s.InitFlags.API.AdvertiseAddrs {\n\t\tendpointList = append(endpointList, fmt.Sprintf(\"https:\/\/%s:443\", addr.String()))\n\t}\n\n\ttokenMap[s.Secrets.TokenID] = s.Secrets.BearerToken\n\n\tdata[\"endpoint-list.json\"], _ = json.Marshal(endpointList)\n\tdata[\"token-map.json\"], _ = json.Marshal(tokenMap)\n\tdata[\"ca.pem\"] = certutil.EncodeCertPEM(caCert)\n\n\treturn data\n}\n\nfunc newKubeDiscoveryPodSpec(s *kubeadmapi.KubeadmConfig) api.PodSpec {\n\treturn api.PodSpec{\n\t\t\/\/ We have to use host network namespace, as `HostPort`\/`HostIP` are Docker's\n\t\t\/\/ buisness and CNI support isn't quite there yet (except for kubenet)\n\t\t\/\/ (see https:\/\/github.com\/kubernetes\/kubernetes\/issues\/31307)\n\t\t\/\/ TODO update this when #31307 is resolved\n\t\tSecurityContext: &api.PodSecurityContext{HostNetwork: true},\n\t\tContainers: []api.Container{{\n\t\t\tName:    kubeDiscoveryName,\n\t\t\tImage:   s.EnvParams[\"discovery_image\"],\n\t\t\tCommand: []string{\"\/usr\/local\/bin\/kube-discovery\"},\n\t\t\tVolumeMounts: []api.VolumeMount{{\n\t\t\t\tName:      kubeDiscoverySecretName,\n\t\t\t\tMountPath: \"\/tmp\/secret\", \/\/ TODO use a shared constant\n\t\t\t\tReadOnly:  true,\n\t\t\t}},\n\t\t\tPorts: []api.ContainerPort{\n\t\t\t\t\/\/ TODO when CNI issue (#31307) is resolved, we should consider adding\n\t\t\t\t\/\/ `HostIP: s.API.AdvertiseAddrs[0]`, if there is only one address`\n\t\t\t\t{Name: \"http\", ContainerPort: 9898, HostPort: 9898},\n\t\t\t},\n\t\t}},\n\t\tVolumes: []api.Volume{{\n\t\t\tName: kubeDiscoverySecretName,\n\t\t\tVolumeSource: api.VolumeSource{\n\t\t\t\tSecret: &api.SecretVolumeSource{SecretName: kubeDiscoverySecretName},\n\t\t\t}},\n\t\t},\n\t}\n}\n\nfunc newKubeDiscovery(s *kubeadmapi.KubeadmConfig, caCert *x509.Certificate) kubeDiscovery {\n\tkd := kubeDiscovery{\n\t\tDeployment: NewDeployment(kubeDiscoveryName, 1, newKubeDiscoveryPodSpec(s)),\n\t\tSecret: &api.Secret{\n\t\t\tObjectMeta: api.ObjectMeta{Name: kubeDiscoverySecretName},\n\t\t\tType:       api.SecretTypeOpaque,\n\t\t\tData:       encodeKubeDiscoverySecretData(s, caCert),\n\t\t},\n\t}\n\n\tSetMasterTaintTolerations(&kd.Deployment.Spec.Template.ObjectMeta)\n\tSetMasterNodeAffinity(&kd.Deployment.Spec.Template.ObjectMeta)\n\n\treturn kd\n}\n\nfunc CreateDiscoveryDeploymentAndSecret(s *kubeadmapi.KubeadmConfig, client *clientset.Clientset, caCert *x509.Certificate) error {\n\tkd := newKubeDiscovery(s, caCert)\n\n\tif _, err := client.Extensions().Deployments(api.NamespaceSystem).Create(kd.Deployment); err != nil {\n\t\treturn fmt.Errorf(\"<master\/discovery> failed to create %q deployment [%s]\", kubeDiscoveryName, err)\n\t}\n\tif _, err := client.Secrets(api.NamespaceSystem).Create(kd.Secret); err != nil {\n\t\treturn fmt.Errorf(\"<master\/discovery> failed to create %q secret [%s]\", kubeDiscoverySecretName, err)\n\t}\n\n\tfmt.Println(\"<master\/discovery> created essential addon: kube-discovery, waiting for it to become ready\")\n\n\tstart := time.Now()\n\twait.PollInfinite(apiCallRetryInterval, func() (bool, error) {\n\t\td, err := client.Extensions().Deployments(api.NamespaceSystem).Get(kubeDiscoveryName)\n\t\tif err != nil {\n\t\t\treturn false, nil\n\t\t}\n\t\tif d.Status.AvailableReplicas < 1 {\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n\tfmt.Printf(\"<master\/discovery> kube-discovery is ready after %f seconds\\n\", time.Since(start).Seconds())\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package jwthelper\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n)\n\n\/\/ Parser is used to parse JWT token string.\ntype Parser struct {\n\tkey    interface{}\n\tparser jwt.Parser\n}\n\n\/\/ ParserOption represents the option for parsing JWT token string.\n\/\/ Use option helper functions to set options:\n\/\/ e.g. ParserUseJSONNumber()\ntype ParserOption struct {\n\tf func(p *Parser)\n}\n\nvar (\n\t\/\/ ErrInvalidParser represents the error of invalid parser.\n\tErrInvalidParser = fmt.Errorf(\"invalid parser\")\n\t\/\/ ErrParseClaims represents the error of failed to parse claims.\n\tErrParseClaims = fmt.Errorf(\"failed to parse claims\")\n\t\/\/ ErrInvalidToken represents the error of invalid token.\n\tErrInvalidToken = fmt.Errorf(\"invalid token\")\n)\n\n\/\/ ParserUseJSONNumber returns the option for using JSON number.\n\/\/ It causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.\n\/\/ After calling Parser.Parse(), the type of number stored in the map[string]interface{} is:\n\/\/ * float64: flag is false.\n\/\/ * json.Number: flag is true.\n\/\/ See https:\/\/godoc.org\/encoding\/json#Decoder.UseNumber\nfunc ParserUseJSONNumber(flag bool) ParserOption {\n\treturn ParserOption{func(p *Parser) {\n\t\tp.parser.UseJSONNumber = flag\n\t}}\n}\n\n\/\/ NewRSASHAParser news a parser with RSASHA alg.\n\/\/\n\/\/     Params:\n\/\/         key: RSA public PEM key.\n\/\/         options: variadic options returned by option helper functions.\n\/\/                  e.g. ParserUseJSONNumber.\nfunc NewRSASHAParser(key []byte, options ...ParserOption) *Parser {\n\tp := &Parser{\n\t\tnil,\n\t\tjwt.Parser{\n\t\t\t\/\/ UseJSONNumber will call encoding\/json.Decoder.UseNumber().\n\t\t\t\/\/ It causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.\n\t\t\t\/\/ See https:\/\/godoc.org\/encoding\/json#Decoder.UseNumber\n\t\t\tUseJSONNumber: true,\n\t\t\t\/\/ If populated, only these methods will be considered valid\n\t\t\t\/\/ See https:\/\/godoc.org\/github.com\/dgrijalva\/jwt-go#Parser\n\t\t\tValidMethods: []string{\n\t\t\t\tjwt.SigningMethodRS256.Alg(),\n\t\t\t\tjwt.SigningMethodRS384.Alg(),\n\t\t\t\tjwt.SigningMethodRS512.Alg(),\n\t\t\t},\n\t\t},\n\t}\n\n\t\/\/ Override customized options.\n\tfor _, op := range options {\n\t\top.f(p)\n\t}\n\n\tpublicKey, err := jwt.ParseRSAPublicKeyFromPEM(key)\n\tif err != nil {\n\t\treturn &Parser{}\n\t}\n\n\tp.key = publicKey\n\treturn p\n}\n\n\/\/ NewRSASHAParserFromPEMFile news a parser with RSASHA alg from the RSA public PEM file.\n\/\/\n\/\/     Params:\n\/\/         key: RSA public PEM file path.\n\/\/         options: variadic options returned by option helper functions.\n\/\/                  e.g. ParserUseJSONNumber.\nfunc NewRSASHAParserFromPEMFile(publicPEM string, options ...ParserOption) *Parser {\n\tkey, err := ReadKey(publicPEM)\n\tif err != nil {\n\t\treturn &Parser{}\n\t}\n\n\treturn NewRSASHAParser(key, options...)\n}\n\n\/\/ Valid validates the parser.\nfunc (p *Parser) Valid() bool {\n\tif p.key == nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ Parse parses the signed string and returns the map which stores claims.\n\/\/\n\/\/     Params:\n\/\/         tokenString: token string to be parsed.\n\/\/     Return:\n\/\/         map stores claims.\n\/\/     comments:\n\/\/         by default, ParserUseJSONNumber option is true.\n\/\/         all numbers will be parsed to json.Number type.\n\/\/         Use Number.Int64(), Number.Float64(), Number.String() according to your need.\n\/\/         You may get float64 type if set ParserUseJSONNumber option to false when new a parser.\nfunc (p *Parser) Parse(tokenString string) (map[string]interface{}, error) {\n\tm := map[string]interface{}{}\n\n\tif !p.Valid() {\n\t\treturn m, ErrInvalidParser\n\t}\n\n\ttoken, err := p.parser.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {\n\t\treturn p.key, nil\n\t})\n\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\tclaims, ok := token.Claims.(jwt.MapClaims)\n\tif !ok {\n\t\treturn m, ErrParseClaims\n\t}\n\n\tif !token.Valid {\n\t\treturn m, ErrInvalidToken\n\t}\n\n\treturn claims, nil\n}\n<commit_msg>Add ParseClaims() to parse claims but not verify the signature<commit_after>package jwthelper\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n)\n\n\/\/ Parser is used to parse JWT token string.\ntype Parser struct {\n\tkey    interface{}\n\tparser jwt.Parser\n}\n\n\/\/ ParserOption represents the option for parsing JWT token string.\n\/\/ Use option helper functions to set options:\n\/\/ e.g. ParserUseJSONNumber()\ntype ParserOption struct {\n\tf func(p *Parser)\n}\n\nvar (\n\t\/\/ ErrInvalidParser represents the error of invalid parser.\n\tErrInvalidParser = fmt.Errorf(\"invalid parser\")\n\t\/\/ ErrParseClaims represents the error of failed to parse claims.\n\tErrParseClaims = fmt.Errorf(\"failed to parse claims\")\n\t\/\/ ErrInvalidToken represents the error of invalid token.\n\tErrInvalidToken   = fmt.Errorf(\"invalid token\")\n\tErrInvalidPartNum = fmt.Errorf(\"invalid number of JWT part\")\n)\n\n\/\/ ParserUseJSONNumber returns the option for using JSON number.\n\/\/ It causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.\n\/\/ After calling Parser.Parse(), the type of number stored in the map[string]interface{} is:\n\/\/ * float64: flag is false.\n\/\/ * json.Number: flag is true.\n\/\/ See https:\/\/godoc.org\/encoding\/json#Decoder.UseNumber\nfunc ParserUseJSONNumber(flag bool) ParserOption {\n\treturn ParserOption{func(p *Parser) {\n\t\tp.parser.UseJSONNumber = flag\n\t}}\n}\n\n\/\/ NewRSASHAParser news a parser with RSASHA alg.\n\/\/\n\/\/     Params:\n\/\/         key: RSA public PEM key.\n\/\/         options: variadic options returned by option helper functions.\n\/\/                  e.g. ParserUseJSONNumber.\nfunc NewRSASHAParser(key []byte, options ...ParserOption) *Parser {\n\tp := &Parser{\n\t\tnil,\n\t\tjwt.Parser{\n\t\t\t\/\/ UseJSONNumber will call encoding\/json.Decoder.UseNumber().\n\t\t\t\/\/ It causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.\n\t\t\t\/\/ See https:\/\/godoc.org\/encoding\/json#Decoder.UseNumber\n\t\t\tUseJSONNumber: true,\n\t\t\t\/\/ If populated, only these methods will be considered valid\n\t\t\t\/\/ See https:\/\/godoc.org\/github.com\/dgrijalva\/jwt-go#Parser\n\t\t\tValidMethods: []string{\n\t\t\t\tjwt.SigningMethodRS256.Alg(),\n\t\t\t\tjwt.SigningMethodRS384.Alg(),\n\t\t\t\tjwt.SigningMethodRS512.Alg(),\n\t\t\t},\n\t\t},\n\t}\n\n\t\/\/ Override customized options.\n\tfor _, op := range options {\n\t\top.f(p)\n\t}\n\n\tpublicKey, err := jwt.ParseRSAPublicKeyFromPEM(key)\n\tif err != nil {\n\t\treturn &Parser{}\n\t}\n\n\tp.key = publicKey\n\treturn p\n}\n\n\/\/ NewRSASHAParserFromPEMFile news a parser with RSASHA alg from the RSA public PEM file.\n\/\/\n\/\/     Params:\n\/\/         key: RSA public PEM file path.\n\/\/         options: variadic options returned by option helper functions.\n\/\/                  e.g. ParserUseJSONNumber.\nfunc NewRSASHAParserFromPEMFile(publicPEM string, options ...ParserOption) *Parser {\n\tkey, err := ReadKey(publicPEM)\n\tif err != nil {\n\t\treturn &Parser{}\n\t}\n\n\treturn NewRSASHAParser(key, options...)\n}\n\n\/\/ Valid validates the parser.\nfunc (p *Parser) Valid() bool {\n\tif p.key == nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ Parse parses the signed string and returns the map which stores claims.\n\/\/\n\/\/     Params:\n\/\/         tokenString: token string to be parsed.\n\/\/     Return:\n\/\/         map stores claims.\n\/\/     comments:\n\/\/         by default, ParserUseJSONNumber option is true.\n\/\/         all numbers will be parsed to json.Number type.\n\/\/         Use Number.Int64(), Number.Float64(), Number.String() according to your need.\n\/\/         You may get float64 type if set ParserUseJSONNumber option to false when new a parser.\nfunc (p *Parser) Parse(tokenString string) (map[string]interface{}, error) {\n\tm := map[string]interface{}{}\n\n\tif !p.Valid() {\n\t\treturn m, ErrInvalidParser\n\t}\n\n\ttoken, err := p.parser.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {\n\t\treturn p.key, nil\n\t})\n\n\tif err != nil {\n\t\treturn m, err\n\t}\n\n\tclaims, ok := token.Claims.(jwt.MapClaims)\n\tif !ok {\n\t\treturn m, ErrParseClaims\n\t}\n\n\tif !token.Valid {\n\t\treturn m, ErrInvalidToken\n\t}\n\n\treturn claims, nil\n}\n\nfunc ParseClaims(tokenString string) (map[string]interface{}, error) {\n\tparts := strings.Split(tokenString, \".\")\n\tif len(parts) != 3 {\n\t\treturn nil, ErrInvalidPartNum\n\t}\n\n\tbuf, err := jwt.DecodeSegment(parts[1])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm := map[string]interface{}{}\n\tdec := json.NewDecoder(bytes.NewBuffer(buf))\n\tif err = dec.Decode(&m); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn m, nil\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>update words<commit_after><|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"text\/template\"\n\n\t\"github.com\/Masterminds\/sprig\"\n\t\"github.com\/kubernetes\/helm\/pkg\/kube\"\n)\n\n\/\/ Installer installs tiller into Kubernetes\n\/\/\n\/\/ See InstallYAML.\ntype Installer struct {\n\n\t\/\/ Metadata holds any global metadata attributes for the resources\n\tMetadata map[string]interface{}\n\n\t\/\/ Tiller specific metadata\n\tTiller map[string]interface{}\n}\n\n\/\/ NewInstaller creates a new Installer\nfunc NewInstaller() *Installer {\n\treturn &Installer{\n\t\tMetadata: map[string]interface{}{},\n\t\tTiller:   map[string]interface{}{},\n\t}\n}\n\n\/\/ Install uses kubernetes client to install tiller\n\/\/\n\/\/ Returns the string output received from the operation, and an error if the\n\/\/ command failed.\nfunc (i *Installer) Install(verbose bool) error {\n\n\tvar b bytes.Buffer\n\terr := template.Must(template.New(\"manifest\").Funcs(sprig.TxtFuncMap()).\n\t\tParse(InstallYAML)).\n\t\tExecute(&b, i)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif verbose {\n\t\tfmt.Println(b.String())\n\t}\n\n\treturn kube.New(nil).Create(\"helm\", &b)\n}\n\n\/\/ InstallYAML is the installation YAML for DM.\nconst InstallYAML = `\n---{{$namespace := default \"helm\" .Tiller.Namespace}}\napiVersion: v1\nkind: Namespace\nmetadata:\n  labels:\n    app: helm\n    name: helm-namespace\n  name: {{$namespace}}\n---\napiVersion: v1\nkind: ReplicationController\nmetadata:\n  labels:\n    app: helm\n    name: tiller\n  name: tiller-rc\n  namespace: {{$namespace}}\nspec:\n  replicas: 1\n  selector:\n    app: helm\n    name: tiller\n  template:\n    metadata:\n      labels:\n        app: helm\n        name: tiller\n    spec:\n      containers:\n      - env:\n          - name: DEFAULT_NAMESPACE\n            valueFrom:\n              fieldRef:\n                fieldPath: metadata.namespace\n        image: {{default \"gcr.io\/kubernetes-helm\/tiller:canary\" .Tiller.Image}}\n        name: tiller\n        ports:\n        - containerPort: 8080\n          name: tiller\n        imagePullPolicy: Always\n---\n`\n<commit_msg>fix(tiller): use correct port in rc spec<commit_after>package client\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"text\/template\"\n\n\t\"github.com\/Masterminds\/sprig\"\n\t\"github.com\/kubernetes\/helm\/pkg\/kube\"\n)\n\n\/\/ Installer installs tiller into Kubernetes\n\/\/\n\/\/ See InstallYAML.\ntype Installer struct {\n\n\t\/\/ Metadata holds any global metadata attributes for the resources\n\tMetadata map[string]interface{}\n\n\t\/\/ Tiller specific metadata\n\tTiller map[string]interface{}\n}\n\n\/\/ NewInstaller creates a new Installer\nfunc NewInstaller() *Installer {\n\treturn &Installer{\n\t\tMetadata: map[string]interface{}{},\n\t\tTiller:   map[string]interface{}{},\n\t}\n}\n\n\/\/ Install uses kubernetes client to install tiller\n\/\/\n\/\/ Returns the string output received from the operation, and an error if the\n\/\/ command failed.\nfunc (i *Installer) Install(verbose bool) error {\n\n\tvar b bytes.Buffer\n\terr := template.Must(template.New(\"manifest\").Funcs(sprig.TxtFuncMap()).\n\t\tParse(InstallYAML)).\n\t\tExecute(&b, i)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif verbose {\n\t\tfmt.Println(b.String())\n\t}\n\n\treturn kube.New(nil).Create(\"helm\", &b)\n}\n\n\/\/ InstallYAML is the installation YAML for DM.\nconst InstallYAML = `\n---{{$namespace := default \"helm\" .Tiller.Namespace}}\napiVersion: v1\nkind: Namespace\nmetadata:\n  labels:\n    app: helm\n    name: helm-namespace\n  name: {{$namespace}}\n---\napiVersion: v1\nkind: ReplicationController\nmetadata:\n  labels:\n    app: helm\n    name: tiller\n  name: tiller-rc\n  namespace: {{$namespace}}\nspec:\n  replicas: 1\n  selector:\n    app: helm\n    name: tiller\n  template:\n    metadata:\n      labels:\n        app: helm\n        name: tiller\n    spec:\n      containers:\n      - env:\n          - name: DEFAULT_NAMESPACE\n            valueFrom:\n              fieldRef:\n                fieldPath: metadata.namespace\n        image: {{default \"gcr.io\/kubernetes-helm\/tiller:canary\" .Tiller.Image}}\n        name: tiller\n        ports:\n        - containerPort: 44134\n          name: tiller\n        imagePullPolicy: Always\n---\n`\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage httputil\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ One of the copies, say from b to r2, could be avoided by using a more\n\/\/ elaborate trick where the other copy is made during Request\/Response.Write.\n\/\/ This would complicate things too much, given that these functions are for\n\/\/ debugging only.\nfunc drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error) {\n\tvar buf bytes.Buffer\n\tif _, err = buf.ReadFrom(b); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err = b.Close(); err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn ioutil.NopCloser(&buf), ioutil.NopCloser(bytes.NewBuffer(buf.Bytes())), nil\n}\n\n\/\/ dumpConn is a net.Conn which writes to Writer and reads from Reader\ntype dumpConn struct {\n\tio.Writer\n\tio.Reader\n}\n\nfunc (c *dumpConn) Close() error                       { return nil }\nfunc (c *dumpConn) LocalAddr() net.Addr                { return nil }\nfunc (c *dumpConn) RemoteAddr() net.Addr               { return nil }\nfunc (c *dumpConn) SetDeadline(t time.Time) error      { return nil }\nfunc (c *dumpConn) SetReadDeadline(t time.Time) error  { return nil }\nfunc (c *dumpConn) SetWriteDeadline(t time.Time) error { return nil }\n\n\/\/ DumpRequestOut is like DumpRequest but includes\n\/\/ headers that the standard http.Transport adds,\n\/\/ such as User-Agent.\nfunc DumpRequestOut(req *http.Request, body bool) ([]byte, error) {\n\tsave := req.Body\n\tif !body || req.Body == nil {\n\t\treq.Body = nil\n\t} else {\n\t\tvar err error\n\t\tsave, req.Body, err = drainBody(req.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Since we're using the actual Transport code to write the request,\n\t\/\/ switch to http so the Transport doesn't try to do an SSL\n\t\/\/ negotiation with our dumpConn and its bytes.Buffer & pipe.\n\t\/\/ The wire format for https and http are the same, anyway.\n\treqSend := req\n\tif req.URL.Scheme == \"https\" {\n\t\treqSend = new(http.Request)\n\t\t*reqSend = *req\n\t\treqSend.URL = new(url.URL)\n\t\t*reqSend.URL = *req.URL\n\t\treqSend.URL.Scheme = \"http\"\n\t}\n\n\t\/\/ Use the actual Transport code to record what we would send\n\t\/\/ on the wire, but not using TCP.  Use a Transport with a\n\t\/\/ customer dialer that returns a fake net.Conn that waits\n\t\/\/ for the full input (and recording it), and then responds\n\t\/\/ with a dummy response.\n\tvar buf bytes.Buffer \/\/ records the output\n\tpr, pw := io.Pipe()\n\tdr := &delegateReader{c: make(chan io.Reader)}\n\t\/\/ Wait for the request before replying with a dummy response:\n\tgo func() {\n\t\thttp.ReadRequest(bufio.NewReader(pr))\n\t\tdr.c <- strings.NewReader(\"HTTP\/1.1 204 No Content\\r\\n\\r\\n\")\n\t}()\n\n\tt := &http.Transport{\n\t\tDial: func(net, addr string) (net.Conn, error) {\n\t\t\treturn &dumpConn{io.MultiWriter(pw, &buf), dr}, nil\n\t\t},\n\t}\n\n\t_, err := t.RoundTrip(reqSend)\n\n\treq.Body = save\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}\n\n\/\/ delegateReader is a reader that delegates to another reader,\n\/\/ once it arrives on a channel.\ntype delegateReader struct {\n\tc chan io.Reader\n\tr io.Reader \/\/ nil until received from c\n}\n\nfunc (r *delegateReader) Read(p []byte) (int, error) {\n\tif r.r == nil {\n\t\tr.r = <-r.c\n\t}\n\treturn r.r.Read(p)\n}\n\n\/\/ Return value if nonempty, def otherwise.\nfunc valueOrDefault(value, def string) string {\n\tif value != \"\" {\n\t\treturn value\n\t}\n\treturn def\n}\n\nvar reqWriteExcludeHeaderDump = map[string]bool{\n\t\"Host\":              true, \/\/ not in Header map anyway\n\t\"Content-Length\":    true,\n\t\"Transfer-Encoding\": true,\n\t\"Trailer\":           true,\n}\n\n\/\/ dumpAsReceived writes req to w in the form as it was received, or\n\/\/ at least as accurately as possible from the information retained in\n\/\/ the request.\nfunc dumpAsReceived(req *http.Request, w io.Writer) error {\n\treturn nil\n}\n\n\/\/ DumpRequest returns the as-received wire representation of req,\n\/\/ optionally including the request body, for debugging.\n\/\/ DumpRequest is semantically a no-op, but in order to\n\/\/ dump the body, it reads the body data into memory and\n\/\/ changes req.Body to refer to the in-memory copy.\n\/\/ The documentation for http.Request.Write details which fields\n\/\/ of req are used.\nfunc DumpRequest(req *http.Request, body bool) (dump []byte, err error) {\n\tsave := req.Body\n\tif !body || req.Body == nil {\n\t\treq.Body = nil\n\t} else {\n\t\tsave, req.Body, err = drainBody(req.Body)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tvar b bytes.Buffer\n\n\tfmt.Fprintf(&b, \"%s %s HTTP\/%d.%d\\r\\n\", valueOrDefault(req.Method, \"GET\"),\n\t\treq.URL.RequestURI(), req.ProtoMajor, req.ProtoMinor)\n\n\thost := req.Host\n\tif host == \"\" && req.URL != nil {\n\t\thost = req.URL.Host\n\t}\n\tif host != \"\" {\n\t\tfmt.Fprintf(&b, \"Host: %s\\r\\n\", host)\n\t}\n\n\tchunked := len(req.TransferEncoding) > 0 && req.TransferEncoding[0] == \"chunked\"\n\tif len(req.TransferEncoding) > 0 {\n\t\tfmt.Fprintf(&b, \"Transfer-Encoding: %s\\r\\n\", strings.Join(req.TransferEncoding, \",\"))\n\t}\n\tif req.Close {\n\t\tfmt.Fprintf(&b, \"Connection: close\\r\\n\")\n\t}\n\n\terr = req.Header.WriteSubset(&b, reqWriteExcludeHeaderDump)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tio.WriteString(&b, \"\\r\\n\")\n\n\tif req.Body != nil {\n\t\tvar dest io.Writer = &b\n\t\tif chunked {\n\t\t\tdest = NewChunkedWriter(dest)\n\t\t}\n\t\t_, err = io.Copy(dest, req.Body)\n\t\tif chunked {\n\t\t\tdest.(io.Closer).Close()\n\t\t\tio.WriteString(&b, \"\\r\\n\")\n\t\t}\n\t}\n\n\treq.Body = save\n\tif err != nil {\n\t\treturn\n\t}\n\tdump = b.Bytes()\n\treturn\n}\n\n\/\/ DumpResponse is like DumpRequest but dumps a response.\nfunc DumpResponse(resp *http.Response, body bool) (dump []byte, err error) {\n\tvar b bytes.Buffer\n\tsave := resp.Body\n\tsavecl := resp.ContentLength\n\tif !body || resp.Body == nil {\n\t\tresp.Body = nil\n\t\tresp.ContentLength = 0\n\t} else {\n\t\tsave, resp.Body, err = drainBody(resp.Body)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\terr = resp.Write(&b)\n\tresp.Body = save\n\tresp.ContentLength = savecl\n\tif err != nil {\n\t\treturn\n\t}\n\tdump = b.Bytes()\n\treturn\n}\n<commit_msg>net\/http\/httputil: fix typo in comment.<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage httputil\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ One of the copies, say from b to r2, could be avoided by using a more\n\/\/ elaborate trick where the other copy is made during Request\/Response.Write.\n\/\/ This would complicate things too much, given that these functions are for\n\/\/ debugging only.\nfunc drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error) {\n\tvar buf bytes.Buffer\n\tif _, err = buf.ReadFrom(b); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif err = b.Close(); err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn ioutil.NopCloser(&buf), ioutil.NopCloser(bytes.NewBuffer(buf.Bytes())), nil\n}\n\n\/\/ dumpConn is a net.Conn which writes to Writer and reads from Reader\ntype dumpConn struct {\n\tio.Writer\n\tio.Reader\n}\n\nfunc (c *dumpConn) Close() error                       { return nil }\nfunc (c *dumpConn) LocalAddr() net.Addr                { return nil }\nfunc (c *dumpConn) RemoteAddr() net.Addr               { return nil }\nfunc (c *dumpConn) SetDeadline(t time.Time) error      { return nil }\nfunc (c *dumpConn) SetReadDeadline(t time.Time) error  { return nil }\nfunc (c *dumpConn) SetWriteDeadline(t time.Time) error { return nil }\n\n\/\/ DumpRequestOut is like DumpRequest but includes\n\/\/ headers that the standard http.Transport adds,\n\/\/ such as User-Agent.\nfunc DumpRequestOut(req *http.Request, body bool) ([]byte, error) {\n\tsave := req.Body\n\tif !body || req.Body == nil {\n\t\treq.Body = nil\n\t} else {\n\t\tvar err error\n\t\tsave, req.Body, err = drainBody(req.Body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Since we're using the actual Transport code to write the request,\n\t\/\/ switch to http so the Transport doesn't try to do an SSL\n\t\/\/ negotiation with our dumpConn and its bytes.Buffer & pipe.\n\t\/\/ The wire format for https and http are the same, anyway.\n\treqSend := req\n\tif req.URL.Scheme == \"https\" {\n\t\treqSend = new(http.Request)\n\t\t*reqSend = *req\n\t\treqSend.URL = new(url.URL)\n\t\t*reqSend.URL = *req.URL\n\t\treqSend.URL.Scheme = \"http\"\n\t}\n\n\t\/\/ Use the actual Transport code to record what we would send\n\t\/\/ on the wire, but not using TCP.  Use a Transport with a\n\t\/\/ custom dialer that returns a fake net.Conn that waits\n\t\/\/ for the full input (and recording it), and then responds\n\t\/\/ with a dummy response.\n\tvar buf bytes.Buffer \/\/ records the output\n\tpr, pw := io.Pipe()\n\tdr := &delegateReader{c: make(chan io.Reader)}\n\t\/\/ Wait for the request before replying with a dummy response:\n\tgo func() {\n\t\thttp.ReadRequest(bufio.NewReader(pr))\n\t\tdr.c <- strings.NewReader(\"HTTP\/1.1 204 No Content\\r\\n\\r\\n\")\n\t}()\n\n\tt := &http.Transport{\n\t\tDial: func(net, addr string) (net.Conn, error) {\n\t\t\treturn &dumpConn{io.MultiWriter(pw, &buf), dr}, nil\n\t\t},\n\t}\n\n\t_, err := t.RoundTrip(reqSend)\n\n\treq.Body = save\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}\n\n\/\/ delegateReader is a reader that delegates to another reader,\n\/\/ once it arrives on a channel.\ntype delegateReader struct {\n\tc chan io.Reader\n\tr io.Reader \/\/ nil until received from c\n}\n\nfunc (r *delegateReader) Read(p []byte) (int, error) {\n\tif r.r == nil {\n\t\tr.r = <-r.c\n\t}\n\treturn r.r.Read(p)\n}\n\n\/\/ Return value if nonempty, def otherwise.\nfunc valueOrDefault(value, def string) string {\n\tif value != \"\" {\n\t\treturn value\n\t}\n\treturn def\n}\n\nvar reqWriteExcludeHeaderDump = map[string]bool{\n\t\"Host\":              true, \/\/ not in Header map anyway\n\t\"Content-Length\":    true,\n\t\"Transfer-Encoding\": true,\n\t\"Trailer\":           true,\n}\n\n\/\/ dumpAsReceived writes req to w in the form as it was received, or\n\/\/ at least as accurately as possible from the information retained in\n\/\/ the request.\nfunc dumpAsReceived(req *http.Request, w io.Writer) error {\n\treturn nil\n}\n\n\/\/ DumpRequest returns the as-received wire representation of req,\n\/\/ optionally including the request body, for debugging.\n\/\/ DumpRequest is semantically a no-op, but in order to\n\/\/ dump the body, it reads the body data into memory and\n\/\/ changes req.Body to refer to the in-memory copy.\n\/\/ The documentation for http.Request.Write details which fields\n\/\/ of req are used.\nfunc DumpRequest(req *http.Request, body bool) (dump []byte, err error) {\n\tsave := req.Body\n\tif !body || req.Body == nil {\n\t\treq.Body = nil\n\t} else {\n\t\tsave, req.Body, err = drainBody(req.Body)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tvar b bytes.Buffer\n\n\tfmt.Fprintf(&b, \"%s %s HTTP\/%d.%d\\r\\n\", valueOrDefault(req.Method, \"GET\"),\n\t\treq.URL.RequestURI(), req.ProtoMajor, req.ProtoMinor)\n\n\thost := req.Host\n\tif host == \"\" && req.URL != nil {\n\t\thost = req.URL.Host\n\t}\n\tif host != \"\" {\n\t\tfmt.Fprintf(&b, \"Host: %s\\r\\n\", host)\n\t}\n\n\tchunked := len(req.TransferEncoding) > 0 && req.TransferEncoding[0] == \"chunked\"\n\tif len(req.TransferEncoding) > 0 {\n\t\tfmt.Fprintf(&b, \"Transfer-Encoding: %s\\r\\n\", strings.Join(req.TransferEncoding, \",\"))\n\t}\n\tif req.Close {\n\t\tfmt.Fprintf(&b, \"Connection: close\\r\\n\")\n\t}\n\n\terr = req.Header.WriteSubset(&b, reqWriteExcludeHeaderDump)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tio.WriteString(&b, \"\\r\\n\")\n\n\tif req.Body != nil {\n\t\tvar dest io.Writer = &b\n\t\tif chunked {\n\t\t\tdest = NewChunkedWriter(dest)\n\t\t}\n\t\t_, err = io.Copy(dest, req.Body)\n\t\tif chunked {\n\t\t\tdest.(io.Closer).Close()\n\t\t\tio.WriteString(&b, \"\\r\\n\")\n\t\t}\n\t}\n\n\treq.Body = save\n\tif err != nil {\n\t\treturn\n\t}\n\tdump = b.Bytes()\n\treturn\n}\n\n\/\/ DumpResponse is like DumpRequest but dumps a response.\nfunc DumpResponse(resp *http.Response, body bool) (dump []byte, err error) {\n\tvar b bytes.Buffer\n\tsave := resp.Body\n\tsavecl := resp.ContentLength\n\tif !body || resp.Body == nil {\n\t\tresp.Body = nil\n\t\tresp.ContentLength = 0\n\t} else {\n\t\tsave, resp.Body, err = drainBody(resp.Body)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\terr = resp.Write(&b)\n\tresp.Body = save\n\tresp.ContentLength = savecl\n\tif err != nil {\n\t\treturn\n\t}\n\tdump = b.Bytes()\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Implements the Google omaha protocol.\n\n   Omaha is a request\/response protocol using XML. Requests are made by\n   clients and responses are given by the Omaha server.\n   http:\/\/code.google.com\/p\/omaha\/wiki\/ServerProtocol\n*\/\npackage omaha\n\nimport (\n\t\"encoding\/xml\"\n)\n\ntype Request struct {\n\tXMLName        xml.Name `xml:\"request\" datastore:\"-\"`\n\tOs             Os       `xml:\"os\"`\n\tApps           []*App   `xml:\"app\"`\n\tProtocol       string   `xml:\"protocol,attr\"`\n\tVersion        string   `xml:\"version,attr,omitempty\"`\n\tIsMachine      string   `xml:\"ismachine,attr,omitempty\"`\n\tSessionId      string   `xml:\"sessionid,attr,omitempty\"`\n\tUserId         string   `xml:\"userid,attr,omitempty\"`\n\tInstallSource  string   `xml:\"installsource,attr,omitempty\"`\n\tTestSource     string   `xml:\"testsource,attr,omitempty\"`\n\tRequestId      string   `xml:\"requestid,attr,omitempty\"`\n\tUpdaterVersion string   `xml:\"updaterversion,attr,omitempty\"`\n}\n\nfunc NewRequest(version string, platform string, sp string, arch string) *Request {\n\tr := new(Request)\n\tr.Protocol = \"3.0\"\n\tr.Os = Os{Version: version, Platform: platform, Sp: sp, Arch: arch}\n\treturn r\n}\n\nfunc (r *Request) AddApp(id string, version string) *App {\n\ta := NewApp(id)\n\ta.Version = version\n\tr.Apps = append(r.Apps, a)\n\treturn a\n}\n\n\/* Response\n *\/\ntype Response struct {\n\tXMLName  xml.Name `xml:\"response\" datastore:\"-\"`\n\tDayStart DayStart `xml:\"daystart\"`\n\tApps     []*App   `xml:\"app\"`\n\tProtocol string   `xml:\"protocol,attr\"`\n\tServer   string   `xml:\"server,attr\"`\n}\n\nfunc NewResponse(server string) *Response {\n\tr := &Response{Server: server, Protocol: \"3.0\"}\n\tr.DayStart.ElapsedSeconds = \"0\"\n\treturn r\n}\n\ntype DayStart struct {\n\tElapsedSeconds string `xml:\"elapsed_seconds,attr\"`\n}\n\nfunc (r *Response) AddApp(id string) *App {\n\ta := NewApp(id)\n\tr.Apps = append(r.Apps, a)\n\treturn a\n}\n\ntype App struct {\n\tXMLName     xml.Name     `xml:\"app\" datastore\"-\"`\n\tPing        *Ping        `xml:\"ping\"`\n\tUpdateCheck *UpdateCheck `xml:\"updatecheck\"`\n\tEvents      []*Event     `xml:\"event\"`\n\tId          string       `xml:\"appid,attr,omitempty\"`\n\tVersion     string       `xml:\"version,attr,omitempty\"`\n\tNextVersion string       `xml:\"nextversion,attr,omitempty\"`\n\tLang        string       `xml:\"lang,attr,omitempty\"`\n\tClient      string       `xml:\"client,attr,omitempty\"`\n\tInstallAge  string       `xml:\"installage,attr,omitempty\"`\n\tTrack       string       `xml:\"track,attr,omitempty\"`\n\tFromTrack   string       `xml:\"from_track,attr,omitempty\"`\n\tStatus      string       `xml:\"status,attr,omitempty\"`\n}\n\nfunc NewApp(id string) *App {\n\ta := &App{Id: id}\n\treturn a\n}\n\nfunc (a *App) AddUpdateCheck() *UpdateCheck {\n\ta.UpdateCheck = new(UpdateCheck)\n\treturn a.UpdateCheck\n}\n\nfunc (a *App) AddPing() *Ping {\n\ta.Ping = new(Ping)\n\treturn a.Ping\n}\n\nfunc (a *App) AddEvent() *Event {\n\tevent := new(Event)\n\ta.Events = append(a.Events, event)\n\treturn event\n}\n\ntype UpdateCheck struct {\n\tXMLName             xml.Name  `xml:\"updatecheck\" datastore:\"-\"`\n\tUrls                *Urls     `xml:\"urls\"`\n\tManifest            *Manifest `xml:\"manifest\"`\n\tTargetVersionPrefix string    `xml:\"targetversionprefix,attr,omitempty\"`\n\tStatus              string    `xml:\"status,attr,omitempty\"`\n}\n\nfunc (u *UpdateCheck) AddUrl(codebase string) *Url {\n\tif u.Urls == nil {\n\t\tu.Urls = new(Urls)\n\t}\n\turl := new(Url)\n\turl.CodeBase = codebase\n\tu.Urls.Urls = append(u.Urls.Urls, *url)\n\treturn url\n}\n\nfunc (u *UpdateCheck) AddManifest(version string) *Manifest {\n\tu.Manifest = &Manifest{Version: version}\n\treturn u.Manifest\n}\n\ntype Ping struct {\n\tXMLName        xml.Name `xml:\"ping\" datastore:\"-\"`\n\tLastReportDays string   `xml:\"r,attr,omitempty\"`\n\tStatus         string   `xml:\"status,attr,omitempty\"`\n}\n\ntype Os struct {\n\tXMLName  xml.Name `xml:\"os\" datastore:\"-\"`\n\tPlatform string   `xml:\"platform,attr,omitempty\"`\n\tVersion  string   `xml:\"version,attr,omitempty\"`\n\tSp       string   `xml:\"sp,attr,omitempty\"`\n\tArch     string   `xml:\"arch,attr,omitempty\"`\n}\n\nfunc NewOs(platform string, version string, sp string, arch string) *Os {\n\to := &Os{Version: version, Platform: platform, Sp: sp, Arch: arch}\n\treturn o\n}\n\ntype Event struct {\n\tXMLName         xml.Name `xml:\"event\" datastore:\"-\"`\n\tType            string   `xml:\"eventtype,attr,omitempty\"`\n\tResult          string   `xml:\"eventresult,attr,omitempty\"`\n\tPreviousVersion string   `xml:\"previousversion,attr,omitempty\"`\n}\n\ntype Urls struct {\n\tXMLName xml.Name `xml:\"urls\" datastore:\"-\"`\n\tUrls    []Url    `xml:\"url\"`\n}\n\ntype Url struct {\n\tXMLName  xml.Name `xml:\"url\" datastore:\"-\"`\n\tCodeBase string   `xml:\"codebase,attr\"`\n}\n\ntype Manifest struct {\n\tXMLName  xml.Name `xml:\"manifest\" datastore:\"-\"`\n\tPackages Packages `xml:\"packages\"`\n\tActions  Actions  `xml:\"actions\"`\n\tVersion  string   `xml:\"version,attr\"`\n}\n\ntype Packages struct {\n\tXMLName  xml.Name  `xml:\"packages\" datastore:\"-\"`\n\tPackages []Package `xml:\"package\"`\n}\n\ntype Package struct {\n\tXMLName  xml.Name `xml:\"package\" datastore:\"-\"`\n\tHash     string   `xml:\"hash,attr\"`\n\tName     string   `xml:\"name,attr\"`\n\tSize     string   `xml:\"size,attr\"`\n\tRequired bool     `xml:\"required,attr\"`\n}\n\nfunc (m *Manifest) AddPackage(hash string, name string, size string, required bool) *Package {\n\tp := &Package{Hash: hash, Name: name, Size: size, Required: required}\n\tm.Packages.Packages = append(m.Packages.Packages, *p)\n\treturn p\n}\n\ntype Actions struct {\n\tXMLName xml.Name  `xml:\"actions\" datastore:\"-\"`\n\tActions []*Action `xml:\"action\"`\n}\n\ntype Action struct {\n\tXMLName xml.Name `xml:\"action\" datastore:\"-\"`\n\tEvent   string   `xml:\"event,attr\"`\n\n\t\/\/ Extensions added by update_engine\n\tChromeOSVersion       string `xml:\"ChromeOSVersion,attr\"`\n\tSha256                string `xml:\"sha256,attr\"`\n\tNeedsAdmin            bool   `xml:\"needsadmin,attr\"`\n\tIsDelta               bool   `xml:\"IsDelta,attr\"`\n\tDisablePayloadBackoff bool   `xml:\"DisablePayloadBackoff,attr,omitempty\"`\n\tMetadataSignatureRsa  string `xml:\"MetadataSignatureRsa,attr,omitempty\"`\n\tMetadataSize          string `xml:\"MetadataSize,attr,omitempty\"`\n\tDeadline              string `xml:\"deadline,attr,omitempty\"`\n}\n\nfunc (m *Manifest) AddAction(event string) *Action {\n\ta := &Action{Event: event}\n\tm.Actions.Actions = append(m.Actions.Actions, a)\n\treturn a\n}\n\nvar EventTypes = map[int]string{\n\t0:   \"unknown\",\n\t1:   \"download complete\",\n\t2:   \"install complete\",\n\t3:   \"update complete\",\n\t4:   \"uninstall\",\n\t5:   \"download started\",\n\t6:   \"install started\",\n\t9:   \"new application install started\",\n\t10:  \"setup started\",\n\t11:  \"setup finished\",\n\t12:  \"update application started\",\n\t13:  \"update download started\",\n\t14:  \"update download finished\",\n\t15:  \"update installer started\",\n\t16:  \"setup update begin\",\n\t17:  \"setup update complete\",\n\t20:  \"register product complete\",\n\t30:  \"OEM install first check\",\n\t40:  \"app-specific command started\",\n\t41:  \"app-specific command ended\",\n\t100: \"setup failure\",\n\t102: \"COM server failure\",\n\t103: \"setup update failure\",\n}\n\nvar EventResults = map[int]string{\n\t0:  \"error\",\n\t1:  \"success\",\n\t2:  \"success reboot\",\n\t3:  \"success restart browser\",\n\t4:  \"cancelled\",\n\t5:  \"error installer MSI\",\n\t6:  \"error installer other\",\n\t7:  \"noupdate\",\n\t8:  \"error installer system\",\n\t9:  \"update deferred\",\n\t10: \"handoff error\",\n}\n<commit_msg>chore(omaha): group the update engine extensions together<commit_after>\/*\n   Implements the Google omaha protocol.\n\n   Omaha is a request\/response protocol using XML. Requests are made by\n   clients and responses are given by the Omaha server.\n   http:\/\/code.google.com\/p\/omaha\/wiki\/ServerProtocol\n*\/\npackage omaha\n\nimport (\n\t\"encoding\/xml\"\n)\n\ntype Request struct {\n\tXMLName        xml.Name `xml:\"request\" datastore:\"-\"`\n\tOs             Os       `xml:\"os\"`\n\tApps           []*App   `xml:\"app\"`\n\tProtocol       string   `xml:\"protocol,attr\"`\n\tVersion        string   `xml:\"version,attr,omitempty\"`\n\tIsMachine      string   `xml:\"ismachine,attr,omitempty\"`\n\tSessionId      string   `xml:\"sessionid,attr,omitempty\"`\n\tUserId         string   `xml:\"userid,attr,omitempty\"`\n\tInstallSource  string   `xml:\"installsource,attr,omitempty\"`\n\tTestSource     string   `xml:\"testsource,attr,omitempty\"`\n\tRequestId      string   `xml:\"requestid,attr,omitempty\"`\n\tUpdaterVersion string   `xml:\"updaterversion,attr,omitempty\"`\n}\n\nfunc NewRequest(version string, platform string, sp string, arch string) *Request {\n\tr := new(Request)\n\tr.Protocol = \"3.0\"\n\tr.Os = Os{Version: version, Platform: platform, Sp: sp, Arch: arch}\n\treturn r\n}\n\nfunc (r *Request) AddApp(id string, version string) *App {\n\ta := NewApp(id)\n\ta.Version = version\n\tr.Apps = append(r.Apps, a)\n\treturn a\n}\n\n\/* Response\n *\/\ntype Response struct {\n\tXMLName  xml.Name `xml:\"response\" datastore:\"-\"`\n\tDayStart DayStart `xml:\"daystart\"`\n\tApps     []*App   `xml:\"app\"`\n\tProtocol string   `xml:\"protocol,attr\"`\n\tServer   string   `xml:\"server,attr\"`\n}\n\nfunc NewResponse(server string) *Response {\n\tr := &Response{Server: server, Protocol: \"3.0\"}\n\tr.DayStart.ElapsedSeconds = \"0\"\n\treturn r\n}\n\ntype DayStart struct {\n\tElapsedSeconds string `xml:\"elapsed_seconds,attr\"`\n}\n\nfunc (r *Response) AddApp(id string) *App {\n\ta := NewApp(id)\n\tr.Apps = append(r.Apps, a)\n\treturn a\n}\n\ntype App struct {\n\tXMLName     xml.Name     `xml:\"app\" datastore\"-\"`\n\tPing        *Ping        `xml:\"ping\"`\n\tUpdateCheck *UpdateCheck `xml:\"updatecheck\"`\n\tEvents      []*Event     `xml:\"event\"`\n\tId          string       `xml:\"appid,attr,omitempty\"`\n\tVersion     string       `xml:\"version,attr,omitempty\"`\n\tNextVersion string       `xml:\"nextversion,attr,omitempty\"`\n\tLang        string       `xml:\"lang,attr,omitempty\"`\n\tClient      string       `xml:\"client,attr,omitempty\"`\n\tInstallAge  string       `xml:\"installage,attr,omitempty\"`\n\tStatus      string       `xml:\"status,attr,omitempty\"`\n\n\t\/\/ update engine extensions\n\tTrack       string       `xml:\"track,attr,omitempty\"`\n\tFromTrack   string       `xml:\"from_track,attr,omitempty\"`\n}\n\nfunc NewApp(id string) *App {\n\ta := &App{Id: id}\n\treturn a\n}\n\nfunc (a *App) AddUpdateCheck() *UpdateCheck {\n\ta.UpdateCheck = new(UpdateCheck)\n\treturn a.UpdateCheck\n}\n\nfunc (a *App) AddPing() *Ping {\n\ta.Ping = new(Ping)\n\treturn a.Ping\n}\n\nfunc (a *App) AddEvent() *Event {\n\tevent := new(Event)\n\ta.Events = append(a.Events, event)\n\treturn event\n}\n\ntype UpdateCheck struct {\n\tXMLName             xml.Name  `xml:\"updatecheck\" datastore:\"-\"`\n\tUrls                *Urls     `xml:\"urls\"`\n\tManifest            *Manifest `xml:\"manifest\"`\n\tTargetVersionPrefix string    `xml:\"targetversionprefix,attr,omitempty\"`\n\tStatus              string    `xml:\"status,attr,omitempty\"`\n}\n\nfunc (u *UpdateCheck) AddUrl(codebase string) *Url {\n\tif u.Urls == nil {\n\t\tu.Urls = new(Urls)\n\t}\n\turl := new(Url)\n\turl.CodeBase = codebase\n\tu.Urls.Urls = append(u.Urls.Urls, *url)\n\treturn url\n}\n\nfunc (u *UpdateCheck) AddManifest(version string) *Manifest {\n\tu.Manifest = &Manifest{Version: version}\n\treturn u.Manifest\n}\n\ntype Ping struct {\n\tXMLName        xml.Name `xml:\"ping\" datastore:\"-\"`\n\tLastReportDays string   `xml:\"r,attr,omitempty\"`\n\tStatus         string   `xml:\"status,attr,omitempty\"`\n}\n\ntype Os struct {\n\tXMLName  xml.Name `xml:\"os\" datastore:\"-\"`\n\tPlatform string   `xml:\"platform,attr,omitempty\"`\n\tVersion  string   `xml:\"version,attr,omitempty\"`\n\tSp       string   `xml:\"sp,attr,omitempty\"`\n\tArch     string   `xml:\"arch,attr,omitempty\"`\n}\n\nfunc NewOs(platform string, version string, sp string, arch string) *Os {\n\to := &Os{Version: version, Platform: platform, Sp: sp, Arch: arch}\n\treturn o\n}\n\ntype Event struct {\n\tXMLName         xml.Name `xml:\"event\" datastore:\"-\"`\n\tType            string   `xml:\"eventtype,attr,omitempty\"`\n\tResult          string   `xml:\"eventresult,attr,omitempty\"`\n\tPreviousVersion string   `xml:\"previousversion,attr,omitempty\"`\n}\n\ntype Urls struct {\n\tXMLName xml.Name `xml:\"urls\" datastore:\"-\"`\n\tUrls    []Url    `xml:\"url\"`\n}\n\ntype Url struct {\n\tXMLName  xml.Name `xml:\"url\" datastore:\"-\"`\n\tCodeBase string   `xml:\"codebase,attr\"`\n}\n\ntype Manifest struct {\n\tXMLName  xml.Name `xml:\"manifest\" datastore:\"-\"`\n\tPackages Packages `xml:\"packages\"`\n\tActions  Actions  `xml:\"actions\"`\n\tVersion  string   `xml:\"version,attr\"`\n}\n\ntype Packages struct {\n\tXMLName  xml.Name  `xml:\"packages\" datastore:\"-\"`\n\tPackages []Package `xml:\"package\"`\n}\n\ntype Package struct {\n\tXMLName  xml.Name `xml:\"package\" datastore:\"-\"`\n\tHash     string   `xml:\"hash,attr\"`\n\tName     string   `xml:\"name,attr\"`\n\tSize     string   `xml:\"size,attr\"`\n\tRequired bool     `xml:\"required,attr\"`\n}\n\nfunc (m *Manifest) AddPackage(hash string, name string, size string, required bool) *Package {\n\tp := &Package{Hash: hash, Name: name, Size: size, Required: required}\n\tm.Packages.Packages = append(m.Packages.Packages, *p)\n\treturn p\n}\n\ntype Actions struct {\n\tXMLName xml.Name  `xml:\"actions\" datastore:\"-\"`\n\tActions []*Action `xml:\"action\"`\n}\n\ntype Action struct {\n\tXMLName xml.Name `xml:\"action\" datastore:\"-\"`\n\tEvent   string   `xml:\"event,attr\"`\n\n\t\/\/ Extensions added by update_engine\n\tChromeOSVersion       string `xml:\"ChromeOSVersion,attr\"`\n\tSha256                string `xml:\"sha256,attr\"`\n\tNeedsAdmin            bool   `xml:\"needsadmin,attr\"`\n\tIsDelta               bool   `xml:\"IsDelta,attr\"`\n\tDisablePayloadBackoff bool   `xml:\"DisablePayloadBackoff,attr,omitempty\"`\n\tMetadataSignatureRsa  string `xml:\"MetadataSignatureRsa,attr,omitempty\"`\n\tMetadataSize          string `xml:\"MetadataSize,attr,omitempty\"`\n\tDeadline              string `xml:\"deadline,attr,omitempty\"`\n}\n\nfunc (m *Manifest) AddAction(event string) *Action {\n\ta := &Action{Event: event}\n\tm.Actions.Actions = append(m.Actions.Actions, a)\n\treturn a\n}\n\nvar EventTypes = map[int]string{\n\t0:   \"unknown\",\n\t1:   \"download complete\",\n\t2:   \"install complete\",\n\t3:   \"update complete\",\n\t4:   \"uninstall\",\n\t5:   \"download started\",\n\t6:   \"install started\",\n\t9:   \"new application install started\",\n\t10:  \"setup started\",\n\t11:  \"setup finished\",\n\t12:  \"update application started\",\n\t13:  \"update download started\",\n\t14:  \"update download finished\",\n\t15:  \"update installer started\",\n\t16:  \"setup update begin\",\n\t17:  \"setup update complete\",\n\t20:  \"register product complete\",\n\t30:  \"OEM install first check\",\n\t40:  \"app-specific command started\",\n\t41:  \"app-specific command ended\",\n\t100: \"setup failure\",\n\t102: \"COM server failure\",\n\t103: \"setup update failure\",\n}\n\nvar EventResults = map[int]string{\n\t0:  \"error\",\n\t1:  \"success\",\n\t2:  \"success reboot\",\n\t3:  \"success restart browser\",\n\t4:  \"cancelled\",\n\t5:  \"error installer MSI\",\n\t6:  \"error installer other\",\n\t7:  \"noupdate\",\n\t8:  \"error installer system\",\n\t9:  \"update deferred\",\n\t10: \"handoff error\",\n}\n<|endoftext|>"}
{"text":"<commit_before>package goose\n\nimport (\n\t\"code.google.com\/p\/go.net\/html\"\n\t\"github.com\/PuerkitoBio\/goquery\"\n)\n\ntype parser struct{}\n\nfunc NewParser() *parser {\n\treturn &parser{}\n}\n\nfunc (this *parser) dropTag(selection *goquery.Selection) {\n\tselection.Each(func(i int, s *goquery.Selection) {\n\t\tnode := s.Get(0)\n\t\tnode.Data = s.Text()\n\t\tnode.Type = html.TextNode\n\t})\n}\n\nfunc (this *parser) indexOfAttribute(selection *goquery.Selection, attr string) int {\n\tnode := selection.Get(0)\n\tfor i, a := range node.Attr {\n\t\tif a.Key == attr {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (this *parser) delAttr(selection *goquery.Selection, attr string) {\n\tidx := this.indexOfAttribute(selection, attr)\n\tif idx > -1 {\n\t\tnode := selection.Get(0)\n\t\tnode.Attr = append(node.Attr[:idx], node.Attr[idx+1:]...)\n\t}\n}\n\nfunc (this *parser) getElementsByTags(div *goquery.Selection, tags []string) *goquery.Selection {\n\tselection := new(goquery.Selection)\n\tfor _, tag := range tags {\n\t\tselections := div.Find(tag)\n\t\tif selections != nil {\n\t\t\tselection = selection.Union(selections)\n\t\t}\n\t}\n\treturn selection\n}\n\nfunc (this *parser) clear(selection *goquery.Selection) {\n\tselection.Nodes = make([]*html.Node, 0)\n}\n\nfunc (this *parser) removeNode(selection *goquery.Selection) {\n\tif selection != nil {\n\t\tnode := selection.Get(0)\n\t\tif node != nil && node.Parent != nil {\n\t\t\tnode.Parent.RemoveChild(node)\n\t\t}\n\t}\n}\n\nfunc (this *parser) name(selector string, selection *goquery.Selection) string {\n\tvalue, exists := selection.Attr(selector)\n\tif exists {\n\t\treturn value\n\t}\n\treturn \"\"\n}\n\nfunc (this *parser) setAttr(selection *goquery.Selection, attr string, value string) {\n\tnode := selection.Get(0)\n\n\tfor _, a := range node.Attr {\n\t\tif a.Key == attr {\n\t\t\ta.Val = value\n\t\t\treturn\n\t\t}\n\t}\n\tattrs := make([]html.Attribute, len(node.Attr)+1)\n\tfor i, a := range node.Attr {\n\t\tattrs[i+1] = a\n\t}\n\tnewAttr := new(html.Attribute)\n\tnewAttr.Key = attr\n\tnewAttr.Val = value\n\tattrs[0] = *newAttr\n\tnode.Attr = attrs\n}\n<commit_msg>Fixed setAttr<commit_after>package goose\n\nimport (\n\t\"code.google.com\/p\/go.net\/html\"\n\t\"github.com\/PuerkitoBio\/goquery\"\n)\n\ntype parser struct{}\n\nfunc NewParser() *parser {\n\treturn &parser{}\n}\n\nfunc (this *parser) dropTag(selection *goquery.Selection) {\n\tselection.Each(func(i int, s *goquery.Selection) {\n\t\tnode := s.Get(0)\n\t\tnode.Data = s.Text()\n\t\tnode.Type = html.TextNode\n\t})\n}\n\nfunc (this *parser) indexOfAttribute(selection *goquery.Selection, attr string) int {\n\tnode := selection.Get(0)\n\tfor i, a := range node.Attr {\n\t\tif a.Key == attr {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (this *parser) delAttr(selection *goquery.Selection, attr string) {\n\tidx := this.indexOfAttribute(selection, attr)\n\tif idx > -1 {\n\t\tnode := selection.Get(0)\n\t\tnode.Attr = append(node.Attr[:idx], node.Attr[idx+1:]...)\n\t}\n}\n\nfunc (this *parser) getElementsByTags(div *goquery.Selection, tags []string) *goquery.Selection {\n\tselection := new(goquery.Selection)\n\tfor _, tag := range tags {\n\t\tselections := div.Find(tag)\n\t\tif selections != nil {\n\t\t\tselection = selection.Union(selections)\n\t\t}\n\t}\n\treturn selection\n}\n\nfunc (this *parser) clear(selection *goquery.Selection) {\n\tselection.Nodes = make([]*html.Node, 0)\n}\n\nfunc (this *parser) removeNode(selection *goquery.Selection) {\n\tif selection != nil {\n\t\tnode := selection.Get(0)\n\t\tif node != nil && node.Parent != nil {\n\t\t\tnode.Parent.RemoveChild(node)\n\t\t}\n\t}\n}\n\nfunc (this *parser) name(selector string, selection *goquery.Selection) string {\n\tvalue, exists := selection.Attr(selector)\n\tif exists {\n\t\treturn value\n\t}\n\treturn \"\"\n}\n\nfunc (this *parser) setAttr(selection *goquery.Selection, attr string, value string) {\n\tnode := selection.Get(0)\n\tattrs := make([]html.Attribute, 0)\n\tfor _, a := range node.Attr {\n\t\tif a.Key != attr {\n\t\t\tnewAttr := new(html.Attribute)\n\t\t\tnewAttr.Key = a.Key\n\t\t\tnewAttr.Val = a.Val\n\t\t\tattrs = append(attrs, *newAttr)\n\t\t}\n\t}\n\tnewAttr := new(html.Attribute)\n\tnewAttr.Key = attr\n\tnewAttr.Val = value\n\tattrs = append(attrs, *newAttr)\n\tnode.Attr = attrs\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage http_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t. \"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"strconv\"\n\t\"testing\"\n)\n\nvar sniffTests = []struct {\n\tdesc        string\n\tdata        []byte\n\tcontentType string\n}{\n\t\/\/ Some nonsense.\n\t{\"Empty\", []byte{}, \"text\/plain; charset=utf-8\"},\n\t{\"Binary\", []byte{1, 2, 3}, \"application\/octet-stream\"},\n\n\t{\"HTML document #1\", []byte(`<HtMl><bOdY>blah blah blah<\/body><\/html>`), \"text\/html; charset=utf-8\"},\n\t{\"HTML document #2\", []byte(`<HTML><\/HTML>`), \"text\/html; charset=utf-8\"},\n\t{\"HTML document #3 (leading whitespace)\", []byte(`   <!DOCTYPE HTML>...`), \"text\/html; charset=utf-8\"},\n\t{\"HTML document #4 (leading CRLF)\", []byte(\"\\r\\n<html>...\"), \"text\/html; charset=utf-8\"},\n\n\t{\"Plain text\", []byte(`This is not HTML. It has ☃ though.`), \"text\/plain; charset=utf-8\"},\n\n\t{\"XML\", []byte(\"\\n<?xml!\"), \"text\/xml; charset=utf-8\"},\n\n\t\/\/ Image types.\n\t{\"GIF 87a\", []byte(`GIF87a`), \"image\/gif\"},\n\t{\"GIF 89a\", []byte(`GIF89a...`), \"image\/gif\"},\n\n\t\/\/ TODO(dsymonds): Re-enable this when the spec is sorted w.r.t. MP4.\n\t\/\/{\"MP4 video\", []byte(\"\\x00\\x00\\x00\\x18ftypmp42\\x00\\x00\\x00\\x00mp42isom<\\x06t\\xbfmdat\"), \"video\/mp4\"},\n\t\/\/{\"MP4 audio\", []byte(\"\\x00\\x00\\x00\\x20ftypM4A \\x00\\x00\\x00\\x00M4A mp42isom\\x00\\x00\\x00\\x00\"), \"audio\/mp4\"},\n}\n\nfunc TestDetectContentType(t *testing.T) {\n\tfor _, tt := range sniffTests {\n\t\tct := DetectContentType(tt.data)\n\t\tif ct != tt.contentType {\n\t\t\tt.Errorf(\"%v: DetectContentType = %q, want %q\", tt.desc, ct, tt.contentType)\n\t\t}\n\t}\n}\n\nfunc TestServerContentType(t *testing.T) {\n\tts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {\n\t\ti, _ := strconv.Atoi(r.FormValue(\"i\"))\n\t\ttt := sniffTests[i]\n\t\tn, err := w.Write(tt.data)\n\t\tif n != len(tt.data) || err != nil {\n\t\t\tlog.Fatalf(\"%v: Write(%q) = %v, %v want %d, nil\", tt.desc, tt.data, n, err, len(tt.data))\n\t\t}\n\t}))\n\tdefer ts.Close()\n\n\tfor i, tt := range sniffTests {\n\t\tresp, err := Get(ts.URL + \"\/?i=\" + strconv.Itoa(i))\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%v: %v\", tt.desc, err)\n\t\t\tcontinue\n\t\t}\n\t\tif ct := resp.Header.Get(\"Content-Type\"); ct != tt.contentType {\n\t\t\tt.Errorf(\"%v: Content-Type = %q, want %q\", tt.desc, ct, tt.contentType)\n\t\t}\n\t\tdata, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%v: reading body: %v\", tt.desc, err)\n\t\t} else if !bytes.Equal(data, tt.data) {\n\t\t\tt.Errorf(\"%v: data is %q, want %q\", tt.desc, data, tt.data)\n\t\t}\n\t\tresp.Body.Close()\n\t}\n}\n\nfunc TestContentTypeWithCopy(t *testing.T) {\n\tconst (\n\t\tinput    = \"\\n<html>\\n\\t<head>\\n\"\n\t\texpected = \"text\/html; charset=utf-8\"\n\t)\n\n\tts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {\n\t\t\/\/ Use io.Copy from a bytes.Buffer to trigger ReadFrom.\n\t\tbuf := bytes.NewBuffer([]byte(input))\n\t\tn, err := io.Copy(w, buf)\n\t\tif int(n) != len(input) || err != nil {\n\t\t\tt.Fatalf(\"io.Copy(w, %q) = %v, %v want %d, nil\", input, n, err, len(input))\n\t\t}\n\t}))\n\tdefer ts.Close()\n\n\tresp, err := Get(ts.URL)\n\tif err != nil {\n\t\tt.Fatalf(\"Get: %v\", err)\n\t}\n\tif ct := resp.Header.Get(\"Content-Type\"); ct != expected {\n\t\tt.Errorf(\"Content-Type = %q, want %q\", ct, expected)\n\t}\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Errorf(\"reading body: %v\", err)\n\t} else if !bytes.Equal(data, []byte(input)) {\n\t\tt.Errorf(\"data is %q, want %q\", data, input)\n\t}\n\tresp.Body.Close()\n}\n<commit_msg>net\/http: use t.Errorf from alternate goroutine in test.<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage http_test\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t. \"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"strconv\"\n\t\"testing\"\n)\n\nvar sniffTests = []struct {\n\tdesc        string\n\tdata        []byte\n\tcontentType string\n}{\n\t\/\/ Some nonsense.\n\t{\"Empty\", []byte{}, \"text\/plain; charset=utf-8\"},\n\t{\"Binary\", []byte{1, 2, 3}, \"application\/octet-stream\"},\n\n\t{\"HTML document #1\", []byte(`<HtMl><bOdY>blah blah blah<\/body><\/html>`), \"text\/html; charset=utf-8\"},\n\t{\"HTML document #2\", []byte(`<HTML><\/HTML>`), \"text\/html; charset=utf-8\"},\n\t{\"HTML document #3 (leading whitespace)\", []byte(`   <!DOCTYPE HTML>...`), \"text\/html; charset=utf-8\"},\n\t{\"HTML document #4 (leading CRLF)\", []byte(\"\\r\\n<html>...\"), \"text\/html; charset=utf-8\"},\n\n\t{\"Plain text\", []byte(`This is not HTML. It has ☃ though.`), \"text\/plain; charset=utf-8\"},\n\n\t{\"XML\", []byte(\"\\n<?xml!\"), \"text\/xml; charset=utf-8\"},\n\n\t\/\/ Image types.\n\t{\"GIF 87a\", []byte(`GIF87a`), \"image\/gif\"},\n\t{\"GIF 89a\", []byte(`GIF89a...`), \"image\/gif\"},\n\n\t\/\/ TODO(dsymonds): Re-enable this when the spec is sorted w.r.t. MP4.\n\t\/\/{\"MP4 video\", []byte(\"\\x00\\x00\\x00\\x18ftypmp42\\x00\\x00\\x00\\x00mp42isom<\\x06t\\xbfmdat\"), \"video\/mp4\"},\n\t\/\/{\"MP4 audio\", []byte(\"\\x00\\x00\\x00\\x20ftypM4A \\x00\\x00\\x00\\x00M4A mp42isom\\x00\\x00\\x00\\x00\"), \"audio\/mp4\"},\n}\n\nfunc TestDetectContentType(t *testing.T) {\n\tfor _, tt := range sniffTests {\n\t\tct := DetectContentType(tt.data)\n\t\tif ct != tt.contentType {\n\t\t\tt.Errorf(\"%v: DetectContentType = %q, want %q\", tt.desc, ct, tt.contentType)\n\t\t}\n\t}\n}\n\nfunc TestServerContentType(t *testing.T) {\n\tts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {\n\t\ti, _ := strconv.Atoi(r.FormValue(\"i\"))\n\t\ttt := sniffTests[i]\n\t\tn, err := w.Write(tt.data)\n\t\tif n != len(tt.data) || err != nil {\n\t\t\tlog.Fatalf(\"%v: Write(%q) = %v, %v want %d, nil\", tt.desc, tt.data, n, err, len(tt.data))\n\t\t}\n\t}))\n\tdefer ts.Close()\n\n\tfor i, tt := range sniffTests {\n\t\tresp, err := Get(ts.URL + \"\/?i=\" + strconv.Itoa(i))\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%v: %v\", tt.desc, err)\n\t\t\tcontinue\n\t\t}\n\t\tif ct := resp.Header.Get(\"Content-Type\"); ct != tt.contentType {\n\t\t\tt.Errorf(\"%v: Content-Type = %q, want %q\", tt.desc, ct, tt.contentType)\n\t\t}\n\t\tdata, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%v: reading body: %v\", tt.desc, err)\n\t\t} else if !bytes.Equal(data, tt.data) {\n\t\t\tt.Errorf(\"%v: data is %q, want %q\", tt.desc, data, tt.data)\n\t\t}\n\t\tresp.Body.Close()\n\t}\n}\n\nfunc TestContentTypeWithCopy(t *testing.T) {\n\tconst (\n\t\tinput    = \"\\n<html>\\n\\t<head>\\n\"\n\t\texpected = \"text\/html; charset=utf-8\"\n\t)\n\n\tts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {\n\t\t\/\/ Use io.Copy from a bytes.Buffer to trigger ReadFrom.\n\t\tbuf := bytes.NewBuffer([]byte(input))\n\t\tn, err := io.Copy(w, buf)\n\t\tif int(n) != len(input) || err != nil {\n\t\t\tt.Errorf(\"io.Copy(w, %q) = %v, %v want %d, nil\", input, n, err, len(input))\n\t\t}\n\t}))\n\tdefer ts.Close()\n\n\tresp, err := Get(ts.URL)\n\tif err != nil {\n\t\tt.Fatalf(\"Get: %v\", err)\n\t}\n\tif ct := resp.Header.Get(\"Content-Type\"); ct != expected {\n\t\tt.Errorf(\"Content-Type = %q, want %q\", ct, expected)\n\t}\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tt.Errorf(\"reading body: %v\", err)\n\t} else if !bytes.Equal(data, []byte(input)) {\n\t\tt.Errorf(\"data is %q, want %q\", data, input)\n\t}\n\tresp.Body.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage client\n\nimport (\n\t\"bytes\"\n\t\"text\/template\"\n\n\t\"github.com\/Masterminds\/sprig\"\n\t\"github.com\/kubernetes\/helm\/pkg\/format\"\n\t\"github.com\/kubernetes\/helm\/pkg\/kubectl\"\n)\n\n\/\/ Installer is capable of installing DM into Kubernetes.\n\/\/\n\/\/ See InstallYAML.\ntype Installer struct {\n\t\/\/ TODO: At some point we could transform these from maps to structs.\n\n\t\/\/ Expandybird params are used to render the expandybird manifest.\n\tExpandybird map[string]interface{}\n\t\/\/ Resourcifier params are used to render the resourcifier manifest.\n\tResourcifier map[string]interface{}\n\t\/\/ Manager params are used to render the manager manifest.\n\tManager map[string]interface{}\n}\n\n\/\/ NewInstaller creates a new Installer.\nfunc NewInstaller() *Installer {\n\treturn &Installer{\n\t\tExpandybird:  map[string]interface{}{},\n\t\tResourcifier: map[string]interface{}{},\n\t\tManager:      map[string]interface{}{},\n\t}\n}\n\n\/\/ Install uses kubectl to install the base DM.\n\/\/\n\/\/ Returns the string output received from the operation, and an error if the\n\/\/ command failed.\nfunc (i *Installer) Install(runner kubectl.Runner) (string, error) {\n\tb, err := i.expand()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\to, err := runner.Create(b)\n\treturn string(o), err\n}\n\nfunc (i *Installer) expand() ([]byte, error) {\n\tvar b bytes.Buffer\n\tt := template.Must(template.New(\"manifest\").Funcs(sprig.TxtFuncMap()).Parse(InstallYAML))\n\terr := t.Execute(&b, i)\n\treturn b.Bytes(), err\n}\n\n\/\/ IsInstalled checks whether DM has been installed.\nfunc IsInstalled(runner kubectl.Runner) bool {\n\t\/\/ Basically, we test \"all-or-nothing\" here: if this returns without error\n\t\/\/ we know that we have both the namespace and the manager API server.\n\tout, err := runner.GetByKind(\"rc\", \"manager-rc\", \"helm\")\n\tif err != nil {\n\t\tformat.Err(\"Installation not found: %s %s\", out, err)\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ InstallYAML is the installation YAML for DM.\nconst InstallYAML = `\n######################################################################\n# Copyright 2015 The Kubernetes Authors All rights reserved.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n######################################################################\n\n---\napiVersion: v1\nkind: Namespace\nmetadata:\n  labels:\n    app: helm\n    name: helm-namespace\n  name: helm\n---\napiVersion: v1\nkind: Service\nmetadata:\n  labels:\n    app: helm\n    name: expandybird-service\n  name: expandybird-service\n  namespace: helm\nspec:\n  ports:\n  - name: expandybird\n    port: 8081\n    targetPort: 8080\n  selector:\n    app: helm\n    name: expandybird\n---\napiVersion: v1\nkind: ReplicationController\nmetadata:\n  labels:\n    app: helm\n    name: expandybird-rc\n  name: expandybird-rc\n  namespace: helm\nspec:\n  replicas: 2\n  selector:\n    app: helm\n    name: expandybird\n  template:\n    metadata:\n      labels:\n        app: helm\n        name: expandybird\n    spec:\n      containers:\n      - env: []\n        image: {{default \"gcr.io\/kubernetes-helm\/expandybird:v1.2.1\" .Expandybird.Image}}\n        name: expandybird\n        ports:\n        - containerPort: 8080\n          name: expandybird\n---\napiVersion: v1\nkind: Service\nmetadata:\n  labels:\n    app: helm\n    name: resourcifier-service\n  name: resourcifier-service\n  namespace: helm\nspec:\n  ports:\n  - name: resourcifier\n    port: 8082\n    targetPort: 8080\n  selector:\n    app: helm\n    name: resourcifier\n---\napiVersion: v1\nkind: ReplicationController\nmetadata:\n  labels:\n    app: helm\n    name: resourcifier-rc\n  name: resourcifier-rc\n  namespace: helm\nspec:\n  replicas: 2\n  selector:\n    app: helm\n    name: resourcifier\n  template:\n    metadata:\n      labels:\n        app: helm\n        name: resourcifier\n    spec:\n      containers:\n      - env: []\n        image: {{ default \"gcr.io\/kubernetes-helm\/resourcifier:v1.2.1\" .Resourcifier.Image }}\n        name: resourcifier\n        ports:\n        - containerPort: 8080\n          name: resourcifier\n---\napiVersion: v1\nkind: Service\nmetadata:\n  labels:\n    app: helm\n    name: manager-service\n  name: manager-service\n  namespace: helm\nspec:\n  ports:\n  - name: manager\n    port: 8080\n    targetPort: 8080\n  selector:\n    app: helm\n    name: manager\n---\napiVersion: v1\nkind: ReplicationController\nmetadata:\n  labels:\n    app: helm\n    name: manager-rc\n  name: manager-rc\n  namespace: helm\nspec:\n  replicas: 1\n  selector:\n    app: helm\n    name: manager\n  template:\n    metadata:\n      labels:\n        app: helm\n        name: manager\n    spec:\n      containers:\n      - env: []\n        image: {{ default \"gcr.io\/kubernetes-helm\/manager:v1.2.1\" .Manager.Image }}\n        name: manager\n        ports:\n        - containerPort: 8080\n          name: manager\n`\n<commit_msg>Change server image default tag from v1.2.1 to latest<commit_after>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage client\n\nimport (\n\t\"bytes\"\n\t\"text\/template\"\n\n\t\"github.com\/Masterminds\/sprig\"\n\t\"github.com\/kubernetes\/helm\/pkg\/format\"\n\t\"github.com\/kubernetes\/helm\/pkg\/kubectl\"\n)\n\n\/\/ Installer is capable of installing DM into Kubernetes.\n\/\/\n\/\/ See InstallYAML.\ntype Installer struct {\n\t\/\/ TODO: At some point we could transform these from maps to structs.\n\n\t\/\/ Expandybird params are used to render the expandybird manifest.\n\tExpandybird map[string]interface{}\n\t\/\/ Resourcifier params are used to render the resourcifier manifest.\n\tResourcifier map[string]interface{}\n\t\/\/ Manager params are used to render the manager manifest.\n\tManager map[string]interface{}\n}\n\n\/\/ NewInstaller creates a new Installer.\nfunc NewInstaller() *Installer {\n\treturn &Installer{\n\t\tExpandybird:  map[string]interface{}{},\n\t\tResourcifier: map[string]interface{}{},\n\t\tManager:      map[string]interface{}{},\n\t}\n}\n\n\/\/ Install uses kubectl to install the base DM.\n\/\/\n\/\/ Returns the string output received from the operation, and an error if the\n\/\/ command failed.\nfunc (i *Installer) Install(runner kubectl.Runner) (string, error) {\n\tb, err := i.expand()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\to, err := runner.Create(b)\n\treturn string(o), err\n}\n\nfunc (i *Installer) expand() ([]byte, error) {\n\tvar b bytes.Buffer\n\tt := template.Must(template.New(\"manifest\").Funcs(sprig.TxtFuncMap()).Parse(InstallYAML))\n\terr := t.Execute(&b, i)\n\treturn b.Bytes(), err\n}\n\n\/\/ IsInstalled checks whether DM has been installed.\nfunc IsInstalled(runner kubectl.Runner) bool {\n\t\/\/ Basically, we test \"all-or-nothing\" here: if this returns without error\n\t\/\/ we know that we have both the namespace and the manager API server.\n\tout, err := runner.GetByKind(\"rc\", \"manager-rc\", \"helm\")\n\tif err != nil {\n\t\tformat.Err(\"Installation not found: %s %s\", out, err)\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ InstallYAML is the installation YAML for DM.\nconst InstallYAML = `\n######################################################################\n# Copyright 2015 The Kubernetes Authors All rights reserved.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n######################################################################\n\n---\napiVersion: v1\nkind: Namespace\nmetadata:\n  labels:\n    app: helm\n    name: helm-namespace\n  name: helm\n---\napiVersion: v1\nkind: Service\nmetadata:\n  labels:\n    app: helm\n    name: expandybird-service\n  name: expandybird-service\n  namespace: helm\nspec:\n  ports:\n  - name: expandybird\n    port: 8081\n    targetPort: 8080\n  selector:\n    app: helm\n    name: expandybird\n---\napiVersion: v1\nkind: ReplicationController\nmetadata:\n  labels:\n    app: helm\n    name: expandybird-rc\n  name: expandybird-rc\n  namespace: helm\nspec:\n  replicas: 2\n  selector:\n    app: helm\n    name: expandybird\n  template:\n    metadata:\n      labels:\n        app: helm\n        name: expandybird\n    spec:\n      containers:\n      - env: []\n        image: {{default \"gcr.io\/kubernetes-helm\/expandybird:latest\" .Expandybird.Image}}\n        name: expandybird\n        ports:\n        - containerPort: 8080\n          name: expandybird\n---\napiVersion: v1\nkind: Service\nmetadata:\n  labels:\n    app: helm\n    name: resourcifier-service\n  name: resourcifier-service\n  namespace: helm\nspec:\n  ports:\n  - name: resourcifier\n    port: 8082\n    targetPort: 8080\n  selector:\n    app: helm\n    name: resourcifier\n---\napiVersion: v1\nkind: ReplicationController\nmetadata:\n  labels:\n    app: helm\n    name: resourcifier-rc\n  name: resourcifier-rc\n  namespace: helm\nspec:\n  replicas: 2\n  selector:\n    app: helm\n    name: resourcifier\n  template:\n    metadata:\n      labels:\n        app: helm\n        name: resourcifier\n    spec:\n      containers:\n      - env: []\n        image: {{ default \"gcr.io\/kubernetes-helm\/resourcifier:latest\" .Resourcifier.Image }}\n        name: resourcifier\n        ports:\n        - containerPort: 8080\n          name: resourcifier\n---\napiVersion: v1\nkind: Service\nmetadata:\n  labels:\n    app: helm\n    name: manager-service\n  name: manager-service\n  namespace: helm\nspec:\n  ports:\n  - name: manager\n    port: 8080\n    targetPort: 8080\n  selector:\n    app: helm\n    name: manager\n---\napiVersion: v1\nkind: ReplicationController\nmetadata:\n  labels:\n    app: helm\n    name: manager-rc\n  name: manager-rc\n  namespace: helm\nspec:\n  replicas: 1\n  selector:\n    app: helm\n    name: manager\n  template:\n    metadata:\n      labels:\n        app: helm\n        name: manager\n    spec:\n      containers:\n      - env: []\n        image: {{ default \"gcr.io\/kubernetes-helm\/manager:latest\" .Manager.Image }}\n        name: manager\n        ports:\n        - containerPort: 8080\n          name: manager\n`\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\n\tboardgame-util is a comprehensive CLI tool to help administer projects\n\tbuilt with boardgame. All of its substantive functionality is implemented\n\tin sub-libraries in lib\/, which can be used directly if necessary.\n\n\tThe canonical help documentation is provided by `boardgame-util help`.\n\n*\/\npackage main\n\nimport (\n\t\"os\"\n\t\"strings\"\n)\n\nfunc main() {\n\tmainImpl(os.Args)\n}\n\nfunc mainImpl(args []string) {\n\tb := &BoardgameUtil{}\n\n\tsetupParents(b, nil, nil)\n\n\tdefer b.Cleanup()\n\n\tcmd := b.WritCommand()\n\n\tpath, positional, err := cmd.Decode(args[1:])\n\n\tif err != nil {\n\t\tpath.Last().ExitHelp(err)\n\t}\n\n\tsubcommandObj := selectSubcommandObject(b, strings.Split(path.String(), \" \"))\n\n\tif subcommandObj == nil {\n\t\tpanic(\"BUG: one of the subcommands didn't enumerate all subcommands\")\n\t}\n\n\tsubcommandObj.Run(path, positional)\n\n}\n<commit_msg>BoardgameUtil.Cleanup is called now when program is canceled via sigterm, so when you Ctrl-C the serve command it deletes the temp dir. Part of #655.<commit_after>\/*\n\n\tboardgame-util is a comprehensive CLI tool to help administer projects\n\tbuilt with boardgame. All of its substantive functionality is implemented\n\tin sub-libraries in lib\/, which can be used directly if necessary.\n\n\tThe canonical help documentation is provided by `boardgame-util help`.\n\n*\/\npackage main\n\nimport (\n\t\"os\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nfunc main() {\n\tmainImpl(os.Args)\n}\n\nfunc mainImpl(args []string) {\n\tb := &BoardgameUtil{}\n\n\tsetupParents(b, nil, nil)\n\n\tdefer b.Cleanup()\n\n\t\/\/Make sure that even if we get exited early we still clean up.\n\tc := make(chan os.Signal, 1)\n\n\tsignal.Notify(c, os.Interrupt)\n\tsignal.Notify(c, syscall.SIGTERM)\n\n\tgo func() {\n\t\t<-c\n\t\tb.Cleanup()\n\t\tos.Exit(1)\n\t}()\n\n\tcmd := b.WritCommand()\n\n\tpath, positional, err := cmd.Decode(args[1:])\n\n\tif err != nil {\n\t\tpath.Last().ExitHelp(err)\n\t}\n\n\tsubcommandObj := selectSubcommandObject(b, strings.Split(path.String(), \" \"))\n\n\tif subcommandObj == nil {\n\t\tpanic(\"BUG: one of the subcommands didn't enumerate all subcommands\")\n\t}\n\n\tsubcommandObj.Run(path, positional)\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage generators\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"k8s.io\/gengo\/args\"\n\t\"k8s.io\/gengo\/generator\"\n\t\"k8s.io\/gengo\/namer\"\n\t\"k8s.io\/gengo\/types\"\n\n\t\"k8s.io\/code-generator\/cmd\/client-gen\/generators\/util\"\n\tclientgentypes \"k8s.io\/code-generator\/cmd\/client-gen\/types\"\n\n\t\"github.com\/golang\/glog\"\n)\n\n\/\/ NameSystems returns the name system used by the generators in this package.\nfunc NameSystems() namer.NameSystems {\n\tpluralExceptions := map[string]string{\n\t\t\"Endpoints\": \"Endpoints\",\n\t}\n\treturn namer.NameSystems{\n\t\t\"public\":             namer.NewPublicNamer(0),\n\t\t\"private\":            namer.NewPrivateNamer(0),\n\t\t\"raw\":                namer.NewRawNamer(\"\", nil),\n\t\t\"publicPlural\":       namer.NewPublicPluralNamer(pluralExceptions),\n\t\t\"allLowercasePlural\": namer.NewAllLowercasePluralNamer(pluralExceptions),\n\t\t\"lowercaseSingular\":  &lowercaseSingularNamer{},\n\t}\n}\n\n\/\/ lowercaseSingularNamer implements Namer\ntype lowercaseSingularNamer struct{}\n\n\/\/ Name returns t's name in all lowercase.\nfunc (n *lowercaseSingularNamer) Name(t *types.Type) string {\n\treturn strings.ToLower(t.Name.Name)\n}\n\n\/\/ DefaultNameSystem returns the default name system for ordering the types to be\n\/\/ processed by the generators in this package.\nfunc DefaultNameSystem() string {\n\treturn \"public\"\n}\n\n\/\/ generatedBy returns information about the arguments used to invoke\n\/\/ lister-gen.\nfunc generatedBy() string {\n\treturn fmt.Sprintf(\"\\n\/\/ This file was automatically generated by lister-gen\\n\\n\")\n}\n\n\/\/ Packages makes the client package definition.\nfunc Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages {\n\tboilerplate, err := arguments.LoadGoBoilerplate()\n\tif err != nil {\n\t\tglog.Fatalf(\"Failed loading boilerplate: %v\", err)\n\t}\n\n\tboilerplate = append(boilerplate, []byte(generatedBy())...)\n\n\tvar packageList generator.Packages\n\tfor _, inputDir := range arguments.InputDirs {\n\t\tp := context.Universe.Package(inputDir)\n\n\t\tobjectMeta, internal, err := objectMetaForPackage(p)\n\t\tif err != nil {\n\t\t\tglog.Fatal(err)\n\t\t}\n\t\tif objectMeta == nil {\n\t\t\t\/\/ no types in this package had genclient\n\t\t\tcontinue\n\t\t}\n\n\t\tvar gv clientgentypes.GroupVersion\n\t\tvar internalGVPkg string\n\n\t\tif internal {\n\t\t\tlastSlash := strings.LastIndex(p.Path, \"\/\")\n\t\t\tif lastSlash == -1 {\n\t\t\t\tglog.Fatalf(\"error constructing internal group version for package %q\", p.Path)\n\t\t\t}\n\t\t\tgv.Group = clientgentypes.Group(p.Path[lastSlash+1:])\n\t\t\tinternalGVPkg = p.Path\n\t\t} else {\n\t\t\tparts := strings.Split(p.Path, \"\/\")\n\t\t\tgv.Group = clientgentypes.Group(parts[len(parts)-2])\n\t\t\tgv.Version = clientgentypes.Version(parts[len(parts)-1])\n\n\t\t\tinternalGVPkg = strings.Join(parts[0:len(parts)-1], \"\/\")\n\t\t}\n\n\t\t\/\/ If there's a comment of the form \"\/\/ +groupName=somegroup\" or\n\t\t\/\/ \"\/\/ +groupName=somegroup.foo.bar.io\", use the first field (somegroup) as the name of the\n\t\t\/\/ group when generating.\n\t\tif override := types.ExtractCommentTags(\"+\", p.DocComments)[\"groupName\"]; override != nil {\n\t\t\tgv.Group = clientgentypes.Group(strings.SplitN(override[0], \".\", 2)[0])\n\t\t}\n\n\t\tvar typesToGenerate []*types.Type\n\t\tfor _, t := range p.Types {\n\t\t\ttags := util.MustParseClientGenTags(t.SecondClosestCommentLines)\n\t\t\tif !tags.GenerateClient || !tags.HasVerb(\"list\") || !tags.HasVerb(\"get\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttypesToGenerate = append(typesToGenerate, t)\n\t\t}\n\t\tif len(typesToGenerate) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\torderer := namer.Orderer{Namer: namer.NewPrivateNamer(0)}\n\t\ttypesToGenerate = orderer.OrderTypes(typesToGenerate)\n\n\t\tpackagePath := filepath.Join(arguments.OutputPackagePath, strings.ToLower(gv.Group.NonEmpty()), strings.ToLower(gv.Version.NonEmpty()))\n\t\tpackageList = append(packageList, &generator.DefaultPackage{\n\t\t\tPackageName: strings.ToLower(gv.Version.NonEmpty()),\n\t\t\tPackagePath: packagePath,\n\t\t\tHeaderText:  boilerplate,\n\t\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\t\tgenerators = append(generators, &expansionGenerator{\n\t\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\t\tOptionalName: \"expansion_generated\",\n\t\t\t\t\t},\n\t\t\t\t\tpackagePath: filepath.Join(arguments.OutputBase, packagePath),\n\t\t\t\t\ttypes:       typesToGenerate,\n\t\t\t\t})\n\n\t\t\t\tfor _, t := range typesToGenerate {\n\t\t\t\t\tgenerators = append(generators, &listerGenerator{\n\t\t\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\t\t\tOptionalName: strings.ToLower(t.Name.Name),\n\t\t\t\t\t\t},\n\t\t\t\t\t\toutputPackage:  arguments.OutputPackagePath,\n\t\t\t\t\t\tgroupVersion:   gv,\n\t\t\t\t\t\tinternalGVPkg:  internalGVPkg,\n\t\t\t\t\t\ttypeToGenerate: t,\n\t\t\t\t\t\timports:        generator.NewImportTracker(),\n\t\t\t\t\t\tobjectMeta:     objectMeta,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\treturn generators\n\t\t\t},\n\t\t\tFilterFunc: func(c *generator.Context, t *types.Type) bool {\n\t\t\t\ttags := util.MustParseClientGenTags(t.SecondClosestCommentLines)\n\t\t\t\treturn tags.GenerateClient && tags.HasVerb(\"list\") && tags.HasVerb(\"get\")\n\t\t\t},\n\t\t})\n\t}\n\n\treturn packageList\n}\n\n\/\/ objectMetaForPackage returns the type of ObjectMeta used by package p.\nfunc objectMetaForPackage(p *types.Package) (*types.Type, bool, error) {\n\tgeneratingForPackage := false\n\tfor _, t := range p.Types {\n\t\t\/\/ filter out types which dont have genclient.\n\t\tif !util.MustParseClientGenTags(t.SecondClosestCommentLines).GenerateClient {\n\t\t\tcontinue\n\t\t}\n\t\tgeneratingForPackage = true\n\t\tfor _, member := range t.Members {\n\t\t\tif member.Name == \"ObjectMeta\" {\n\t\t\t\treturn member.Type, isInternal(member), nil\n\t\t\t}\n\t\t}\n\t}\n\tif generatingForPackage {\n\t\treturn nil, false, fmt.Errorf(\"unable to find ObjectMeta for any types in package %s\", p.Path)\n\t}\n\treturn nil, false, nil\n}\n\n\/\/ isInternal returns true if the tags for a member do not contain a json tag\nfunc isInternal(m types.Member) bool {\n\treturn !strings.Contains(m.Tags, \"json\")\n}\n\n\/\/ listerGenerator produces a file of listers for a given GroupVersion and\n\/\/ type.\ntype listerGenerator struct {\n\tgenerator.DefaultGen\n\toutputPackage  string\n\tgroupVersion   clientgentypes.GroupVersion\n\tinternalGVPkg  string\n\ttypeToGenerate *types.Type\n\timports        namer.ImportTracker\n\tobjectMeta     *types.Type\n}\n\nvar _ generator.Generator = &listerGenerator{}\n\nfunc (g *listerGenerator) Filter(c *generator.Context, t *types.Type) bool {\n\treturn t == g.typeToGenerate\n}\n\nfunc (g *listerGenerator) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}\n\nfunc (g *listerGenerator) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.imports.ImportLines()...)\n\timports = append(imports, \"k8s.io\/apimachinery\/pkg\/api\/errors\")\n\timports = append(imports, \"k8s.io\/apimachinery\/pkg\/labels\")\n\t\/\/ for Indexer\n\timports = append(imports, \"k8s.io\/client-go\/tools\/cache\")\n\treturn\n}\n\nfunc (g *listerGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\n\tglog.V(5).Infof(\"processing type %v\", t)\n\tm := map[string]interface{}{\n\t\t\"Resource\":   c.Universe.Function(types.Name{Package: t.Name.Package, Name: \"Resource\"}),\n\t\t\"type\":       t,\n\t\t\"objectMeta\": g.objectMeta,\n\t}\n\n\ttags, err := util.ParseClientGenTags(t.SecondClosestCommentLines)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif tags.NonNamespaced {\n\t\tsw.Do(typeListerInterface_NonNamespaced, m)\n\t} else {\n\t\tsw.Do(typeListerInterface, m)\n\t}\n\n\tsw.Do(typeListerStruct, m)\n\tsw.Do(typeListerConstructor, m)\n\tsw.Do(typeLister_List, m)\n\n\tif tags.NonNamespaced {\n\t\tsw.Do(typeLister_NonNamespacedGet, m)\n\t\treturn sw.Error()\n\t}\n\n\tsw.Do(typeLister_NamespaceLister, m)\n\tsw.Do(namespaceListerInterface, m)\n\tsw.Do(namespaceListerStruct, m)\n\tsw.Do(namespaceLister_List, m)\n\tsw.Do(namespaceLister_Get, m)\n\n\treturn sw.Error()\n}\n\nvar typeListerInterface = `\n\/\/ $.type|public$Lister helps list $.type|publicPlural$.\ntype $.type|public$Lister interface {\n\t\/\/ List lists all $.type|publicPlural$ in the indexer.\n\tList(selector labels.Selector) (ret []*$.type|raw$, err error)\n\t\/\/ $.type|publicPlural$ returns an object that can list and get $.type|publicPlural$.\n\t$.type|publicPlural$(namespace string) $.type|public$NamespaceLister\n\t$.type|public$ListerExpansion\n}\n`\n\nvar typeListerInterface_NonNamespaced = `\n\/\/ $.type|public$Lister helps list $.type|publicPlural$.\ntype $.type|public$Lister interface {\n\t\/\/ List lists all $.type|publicPlural$ in the indexer.\n\tList(selector labels.Selector) (ret []*$.type|raw$, err error)\n\t\/\/ Get retrieves the $.type|public$ from the index for a given name.\n\tGet(name string) (*$.type|raw$, error)\n\t$.type|public$ListerExpansion\n}\n`\n\nvar typeListerStruct = `\n\/\/ $.type|private$Lister implements the $.type|public$Lister interface.\ntype $.type|private$Lister struct {\n\tindexer cache.Indexer\n}\n`\n\nvar typeListerConstructor = `\n\/\/ New$.type|public$Lister returns a new $.type|public$Lister.\nfunc New$.type|public$Lister(indexer cache.Indexer) $.type|public$Lister {\n\treturn &$.type|private$Lister{indexer: indexer}\n}\n`\n\nvar typeLister_List = `\n\/\/ List lists all $.type|publicPlural$ in the indexer.\nfunc (s *$.type|private$Lister) List(selector labels.Selector) (ret []*$.type|raw$, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*$.type|raw$))\n\t})\n\treturn ret, err\n}\n`\n\nvar typeLister_NamespaceLister = `\n\/\/ $.type|publicPlural$ returns an object that can list and get $.type|publicPlural$.\nfunc (s *$.type|private$Lister) $.type|publicPlural$(namespace string) $.type|public$NamespaceLister {\n\treturn $.type|private$NamespaceLister{indexer: s.indexer, namespace: namespace}\n}\n`\n\nvar typeLister_NonNamespacedGet = `\n\/\/ Get retrieves the $.type|public$ from the index for a given name.\nfunc (s *$.type|private$Lister) Get(name string) (*$.type|raw$, error) {\n  key := &$.type|raw${ObjectMeta: $.objectMeta|raw${Name: name}}\n  obj, exists, err := s.indexer.Get(key)\n  if err != nil {\n    return nil, err\n  }\n  if !exists {\n    return nil, errors.NewNotFound($.Resource|raw$(\"$.type|lowercaseSingular$\"), name)\n  }\n  return obj.(*$.type|raw$), nil\n}\n`\n\nvar namespaceListerInterface = `\n\/\/ $.type|public$NamespaceLister helps list and get $.type|publicPlural$.\ntype $.type|public$NamespaceLister interface {\n\t\/\/ List lists all $.type|publicPlural$ in the indexer for a given namespace.\n\tList(selector labels.Selector) (ret []*$.type|raw$, err error)\n\t\/\/ Get retrieves the $.type|public$ from the indexer for a given namespace and name.\n\tGet(name string) (*$.type|raw$, error)\n\t$.type|public$NamespaceListerExpansion\n}\n`\n\nvar namespaceListerStruct = `\n\/\/ $.type|private$NamespaceLister implements the $.type|public$NamespaceLister\n\/\/ interface.\ntype $.type|private$NamespaceLister struct {\n\tindexer cache.Indexer\n\tnamespace string\n}\n`\n\nvar namespaceLister_List = `\n\/\/ List lists all $.type|publicPlural$ in the indexer for a given namespace.\nfunc (s $.type|private$NamespaceLister) List(selector labels.Selector) (ret []*$.type|raw$, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*$.type|raw$))\n\t})\n\treturn ret, err\n}\n`\n\nvar namespaceLister_Get = `\n\/\/ Get retrieves the $.type|public$ from the indexer for a given namespace and name.\nfunc (s $.type|private$NamespaceLister) Get(name string) (*$.type|raw$, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"\/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound($.Resource|raw$(\"$.type|lowercaseSingular$\"), name)\n\t}\n\treturn obj.(*$.type|raw$), nil\n}\n`\n<commit_msg>Use GetByKey() in typeLister_NonNamespacedGet<commit_after>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage generators\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"k8s.io\/gengo\/args\"\n\t\"k8s.io\/gengo\/generator\"\n\t\"k8s.io\/gengo\/namer\"\n\t\"k8s.io\/gengo\/types\"\n\n\t\"k8s.io\/code-generator\/cmd\/client-gen\/generators\/util\"\n\tclientgentypes \"k8s.io\/code-generator\/cmd\/client-gen\/types\"\n\n\t\"github.com\/golang\/glog\"\n)\n\n\/\/ NameSystems returns the name system used by the generators in this package.\nfunc NameSystems() namer.NameSystems {\n\tpluralExceptions := map[string]string{\n\t\t\"Endpoints\": \"Endpoints\",\n\t}\n\treturn namer.NameSystems{\n\t\t\"public\":             namer.NewPublicNamer(0),\n\t\t\"private\":            namer.NewPrivateNamer(0),\n\t\t\"raw\":                namer.NewRawNamer(\"\", nil),\n\t\t\"publicPlural\":       namer.NewPublicPluralNamer(pluralExceptions),\n\t\t\"allLowercasePlural\": namer.NewAllLowercasePluralNamer(pluralExceptions),\n\t\t\"lowercaseSingular\":  &lowercaseSingularNamer{},\n\t}\n}\n\n\/\/ lowercaseSingularNamer implements Namer\ntype lowercaseSingularNamer struct{}\n\n\/\/ Name returns t's name in all lowercase.\nfunc (n *lowercaseSingularNamer) Name(t *types.Type) string {\n\treturn strings.ToLower(t.Name.Name)\n}\n\n\/\/ DefaultNameSystem returns the default name system for ordering the types to be\n\/\/ processed by the generators in this package.\nfunc DefaultNameSystem() string {\n\treturn \"public\"\n}\n\n\/\/ generatedBy returns information about the arguments used to invoke\n\/\/ lister-gen.\nfunc generatedBy() string {\n\treturn fmt.Sprintf(\"\\n\/\/ This file was automatically generated by lister-gen\\n\\n\")\n}\n\n\/\/ Packages makes the client package definition.\nfunc Packages(context *generator.Context, arguments *args.GeneratorArgs) generator.Packages {\n\tboilerplate, err := arguments.LoadGoBoilerplate()\n\tif err != nil {\n\t\tglog.Fatalf(\"Failed loading boilerplate: %v\", err)\n\t}\n\n\tboilerplate = append(boilerplate, []byte(generatedBy())...)\n\n\tvar packageList generator.Packages\n\tfor _, inputDir := range arguments.InputDirs {\n\t\tp := context.Universe.Package(inputDir)\n\n\t\tobjectMeta, internal, err := objectMetaForPackage(p)\n\t\tif err != nil {\n\t\t\tglog.Fatal(err)\n\t\t}\n\t\tif objectMeta == nil {\n\t\t\t\/\/ no types in this package had genclient\n\t\t\tcontinue\n\t\t}\n\n\t\tvar gv clientgentypes.GroupVersion\n\t\tvar internalGVPkg string\n\n\t\tif internal {\n\t\t\tlastSlash := strings.LastIndex(p.Path, \"\/\")\n\t\t\tif lastSlash == -1 {\n\t\t\t\tglog.Fatalf(\"error constructing internal group version for package %q\", p.Path)\n\t\t\t}\n\t\t\tgv.Group = clientgentypes.Group(p.Path[lastSlash+1:])\n\t\t\tinternalGVPkg = p.Path\n\t\t} else {\n\t\t\tparts := strings.Split(p.Path, \"\/\")\n\t\t\tgv.Group = clientgentypes.Group(parts[len(parts)-2])\n\t\t\tgv.Version = clientgentypes.Version(parts[len(parts)-1])\n\n\t\t\tinternalGVPkg = strings.Join(parts[0:len(parts)-1], \"\/\")\n\t\t}\n\n\t\t\/\/ If there's a comment of the form \"\/\/ +groupName=somegroup\" or\n\t\t\/\/ \"\/\/ +groupName=somegroup.foo.bar.io\", use the first field (somegroup) as the name of the\n\t\t\/\/ group when generating.\n\t\tif override := types.ExtractCommentTags(\"+\", p.DocComments)[\"groupName\"]; override != nil {\n\t\t\tgv.Group = clientgentypes.Group(strings.SplitN(override[0], \".\", 2)[0])\n\t\t}\n\n\t\tvar typesToGenerate []*types.Type\n\t\tfor _, t := range p.Types {\n\t\t\ttags := util.MustParseClientGenTags(t.SecondClosestCommentLines)\n\t\t\tif !tags.GenerateClient || !tags.HasVerb(\"list\") || !tags.HasVerb(\"get\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttypesToGenerate = append(typesToGenerate, t)\n\t\t}\n\t\tif len(typesToGenerate) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\torderer := namer.Orderer{Namer: namer.NewPrivateNamer(0)}\n\t\ttypesToGenerate = orderer.OrderTypes(typesToGenerate)\n\n\t\tpackagePath := filepath.Join(arguments.OutputPackagePath, strings.ToLower(gv.Group.NonEmpty()), strings.ToLower(gv.Version.NonEmpty()))\n\t\tpackageList = append(packageList, &generator.DefaultPackage{\n\t\t\tPackageName: strings.ToLower(gv.Version.NonEmpty()),\n\t\t\tPackagePath: packagePath,\n\t\t\tHeaderText:  boilerplate,\n\t\t\tGeneratorFunc: func(c *generator.Context) (generators []generator.Generator) {\n\t\t\t\tgenerators = append(generators, &expansionGenerator{\n\t\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\t\tOptionalName: \"expansion_generated\",\n\t\t\t\t\t},\n\t\t\t\t\tpackagePath: filepath.Join(arguments.OutputBase, packagePath),\n\t\t\t\t\ttypes:       typesToGenerate,\n\t\t\t\t})\n\n\t\t\t\tfor _, t := range typesToGenerate {\n\t\t\t\t\tgenerators = append(generators, &listerGenerator{\n\t\t\t\t\t\tDefaultGen: generator.DefaultGen{\n\t\t\t\t\t\t\tOptionalName: strings.ToLower(t.Name.Name),\n\t\t\t\t\t\t},\n\t\t\t\t\t\toutputPackage:  arguments.OutputPackagePath,\n\t\t\t\t\t\tgroupVersion:   gv,\n\t\t\t\t\t\tinternalGVPkg:  internalGVPkg,\n\t\t\t\t\t\ttypeToGenerate: t,\n\t\t\t\t\t\timports:        generator.NewImportTracker(),\n\t\t\t\t\t\tobjectMeta:     objectMeta,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t\treturn generators\n\t\t\t},\n\t\t\tFilterFunc: func(c *generator.Context, t *types.Type) bool {\n\t\t\t\ttags := util.MustParseClientGenTags(t.SecondClosestCommentLines)\n\t\t\t\treturn tags.GenerateClient && tags.HasVerb(\"list\") && tags.HasVerb(\"get\")\n\t\t\t},\n\t\t})\n\t}\n\n\treturn packageList\n}\n\n\/\/ objectMetaForPackage returns the type of ObjectMeta used by package p.\nfunc objectMetaForPackage(p *types.Package) (*types.Type, bool, error) {\n\tgeneratingForPackage := false\n\tfor _, t := range p.Types {\n\t\t\/\/ filter out types which dont have genclient.\n\t\tif !util.MustParseClientGenTags(t.SecondClosestCommentLines).GenerateClient {\n\t\t\tcontinue\n\t\t}\n\t\tgeneratingForPackage = true\n\t\tfor _, member := range t.Members {\n\t\t\tif member.Name == \"ObjectMeta\" {\n\t\t\t\treturn member.Type, isInternal(member), nil\n\t\t\t}\n\t\t}\n\t}\n\tif generatingForPackage {\n\t\treturn nil, false, fmt.Errorf(\"unable to find ObjectMeta for any types in package %s\", p.Path)\n\t}\n\treturn nil, false, nil\n}\n\n\/\/ isInternal returns true if the tags for a member do not contain a json tag\nfunc isInternal(m types.Member) bool {\n\treturn !strings.Contains(m.Tags, \"json\")\n}\n\n\/\/ listerGenerator produces a file of listers for a given GroupVersion and\n\/\/ type.\ntype listerGenerator struct {\n\tgenerator.DefaultGen\n\toutputPackage  string\n\tgroupVersion   clientgentypes.GroupVersion\n\tinternalGVPkg  string\n\ttypeToGenerate *types.Type\n\timports        namer.ImportTracker\n\tobjectMeta     *types.Type\n}\n\nvar _ generator.Generator = &listerGenerator{}\n\nfunc (g *listerGenerator) Filter(c *generator.Context, t *types.Type) bool {\n\treturn t == g.typeToGenerate\n}\n\nfunc (g *listerGenerator) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}\n\nfunc (g *listerGenerator) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.imports.ImportLines()...)\n\timports = append(imports, \"k8s.io\/apimachinery\/pkg\/api\/errors\")\n\timports = append(imports, \"k8s.io\/apimachinery\/pkg\/labels\")\n\t\/\/ for Indexer\n\timports = append(imports, \"k8s.io\/client-go\/tools\/cache\")\n\treturn\n}\n\nfunc (g *listerGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"$\", \"$\")\n\n\tglog.V(5).Infof(\"processing type %v\", t)\n\tm := map[string]interface{}{\n\t\t\"Resource\":   c.Universe.Function(types.Name{Package: t.Name.Package, Name: \"Resource\"}),\n\t\t\"type\":       t,\n\t\t\"objectMeta\": g.objectMeta,\n\t}\n\n\ttags, err := util.ParseClientGenTags(t.SecondClosestCommentLines)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif tags.NonNamespaced {\n\t\tsw.Do(typeListerInterface_NonNamespaced, m)\n\t} else {\n\t\tsw.Do(typeListerInterface, m)\n\t}\n\n\tsw.Do(typeListerStruct, m)\n\tsw.Do(typeListerConstructor, m)\n\tsw.Do(typeLister_List, m)\n\n\tif tags.NonNamespaced {\n\t\tsw.Do(typeLister_NonNamespacedGet, m)\n\t\treturn sw.Error()\n\t}\n\n\tsw.Do(typeLister_NamespaceLister, m)\n\tsw.Do(namespaceListerInterface, m)\n\tsw.Do(namespaceListerStruct, m)\n\tsw.Do(namespaceLister_List, m)\n\tsw.Do(namespaceLister_Get, m)\n\n\treturn sw.Error()\n}\n\nvar typeListerInterface = `\n\/\/ $.type|public$Lister helps list $.type|publicPlural$.\ntype $.type|public$Lister interface {\n\t\/\/ List lists all $.type|publicPlural$ in the indexer.\n\tList(selector labels.Selector) (ret []*$.type|raw$, err error)\n\t\/\/ $.type|publicPlural$ returns an object that can list and get $.type|publicPlural$.\n\t$.type|publicPlural$(namespace string) $.type|public$NamespaceLister\n\t$.type|public$ListerExpansion\n}\n`\n\nvar typeListerInterface_NonNamespaced = `\n\/\/ $.type|public$Lister helps list $.type|publicPlural$.\ntype $.type|public$Lister interface {\n\t\/\/ List lists all $.type|publicPlural$ in the indexer.\n\tList(selector labels.Selector) (ret []*$.type|raw$, err error)\n\t\/\/ Get retrieves the $.type|public$ from the index for a given name.\n\tGet(name string) (*$.type|raw$, error)\n\t$.type|public$ListerExpansion\n}\n`\n\nvar typeListerStruct = `\n\/\/ $.type|private$Lister implements the $.type|public$Lister interface.\ntype $.type|private$Lister struct {\n\tindexer cache.Indexer\n}\n`\n\nvar typeListerConstructor = `\n\/\/ New$.type|public$Lister returns a new $.type|public$Lister.\nfunc New$.type|public$Lister(indexer cache.Indexer) $.type|public$Lister {\n\treturn &$.type|private$Lister{indexer: indexer}\n}\n`\n\nvar typeLister_List = `\n\/\/ List lists all $.type|publicPlural$ in the indexer.\nfunc (s *$.type|private$Lister) List(selector labels.Selector) (ret []*$.type|raw$, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*$.type|raw$))\n\t})\n\treturn ret, err\n}\n`\n\nvar typeLister_NamespaceLister = `\n\/\/ $.type|publicPlural$ returns an object that can list and get $.type|publicPlural$.\nfunc (s *$.type|private$Lister) $.type|publicPlural$(namespace string) $.type|public$NamespaceLister {\n\treturn $.type|private$NamespaceLister{indexer: s.indexer, namespace: namespace}\n}\n`\n\nvar typeLister_NonNamespacedGet = `\n\/\/ Get retrieves the $.type|public$ from the index for a given name.\nfunc (s *$.type|private$Lister) Get(name string) (*$.type|raw$, error) {\n  obj, exists, err := s.indexer.GetByKey(name)\n  if err != nil {\n    return nil, err\n  }\n  if !exists {\n    return nil, errors.NewNotFound($.Resource|raw$(\"$.type|lowercaseSingular$\"), name)\n  }\n  return obj.(*$.type|raw$), nil\n}\n`\n\nvar namespaceListerInterface = `\n\/\/ $.type|public$NamespaceLister helps list and get $.type|publicPlural$.\ntype $.type|public$NamespaceLister interface {\n\t\/\/ List lists all $.type|publicPlural$ in the indexer for a given namespace.\n\tList(selector labels.Selector) (ret []*$.type|raw$, err error)\n\t\/\/ Get retrieves the $.type|public$ from the indexer for a given namespace and name.\n\tGet(name string) (*$.type|raw$, error)\n\t$.type|public$NamespaceListerExpansion\n}\n`\n\nvar namespaceListerStruct = `\n\/\/ $.type|private$NamespaceLister implements the $.type|public$NamespaceLister\n\/\/ interface.\ntype $.type|private$NamespaceLister struct {\n\tindexer cache.Indexer\n\tnamespace string\n}\n`\n\nvar namespaceLister_List = `\n\/\/ List lists all $.type|publicPlural$ in the indexer for a given namespace.\nfunc (s $.type|private$NamespaceLister) List(selector labels.Selector) (ret []*$.type|raw$, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*$.type|raw$))\n\t})\n\treturn ret, err\n}\n`\n\nvar namespaceLister_Get = `\n\/\/ Get retrieves the $.type|public$ from the indexer for a given namespace and name.\nfunc (s $.type|private$NamespaceLister) Get(name string) (*$.type|raw$, error) {\n\tobj, exists, err := s.indexer.GetByKey(s.namespace + \"\/\" + name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !exists {\n\t\treturn nil, errors.NewNotFound($.Resource|raw$(\"$.type|lowercaseSingular$\"), name)\n\t}\n\treturn obj.(*$.type|raw$), nil\n}\n`\n<|endoftext|>"}
{"text":"<commit_before>package jsonez\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\/*\n * JSON types\n *\/\nconst (\n\tJSON_BOOL = iota\n\tJSON_NULL\n\tJSON_INT\n\tJSON_DOUBLE\n\tJSON_STRING\n\tJSON_ARRAY\n\tJSON_OBJECT\n)\n\nvar errorOffset int = -1\n\n\/*\n * GoJSON structure\n *\/\ntype GoJSON struct {\n\t\/**\n\t * Pointers to walk array\/object chains\n\t *\/\n\tnext, prev *GoJSON\n\n\t\/**\n\t * Child item of the current object\n\t *\/\n\tchild *GoJSON\n\n\t\/** JSON type *\/\n\tJsontype int\n\n\t\/**\n\t * Valstr will be set when\n\t *type is JSON_STRING\n\t *\/\n\tValstr string\n\n\t\/**\n\t * Valint will be set when type\n\t * is JSON_INT\n\t *\/\n\tValint int\n\n\t\/**\n\t * valuenum will be set when\n\t * type is JSON_DOUBLE\n\t *\/\n\tValdouble float64\n\n\t\/**\n\t * Valbool will be set when\n\t * type is JSON_BOOL\n\t *\/\n\tValbool bool\n\n\t\/**\n\t * JSON Key\n\t *\/\n\tKey string\n}\n\n\/**\n * Functions related to parsing a JSON string\n *\/\n\n\/**\n * nextToken finds the next token\n *\/\nfunc nextToken(input []byte) []byte {\n\tfor i, c := range input {\n\t\tif unicode.IsSpace(rune(c)) || c == '\\'' {\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn input[i:]\n\t\t}\n\t}\n\n\treturn []byte{}\n}\n\n\/**\n * Function to parse a string\n *\/\nfunc parseString(cur *GoJSON, input []byte) ([]byte, error) {\n\tvar offset int\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Byte slice is empty\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tif input[0] != '\"' {\n\t\terrorStr := fmt.Sprintf(\"%s: Not a valid string in input %s\", funcName(), string(input))\n\t\treturn nil, errors.New(errorStr)\n\t}\n\n\tfor i := range input {\n\t\tif i > 0 && input[i] == '\"' {\n\t\t\tbreak\n\t\t} else {\n\t\t\toffset++\n\t\t}\n\t}\n\n\tcur.Jsontype = JSON_STRING\n\tcur.Valstr = strings.Trim(string(input[1:offset]), \" \")\n\n\treturn input[offset+1:], nil\n}\n\n\/**\n * Function to parse a number\n *\/\nfunc parseNumber(cur *GoJSON, input []byte) ([]byte, error) {\n\tvar n, sign, scale float64\n\tvar subscale, signsubscale, offset int\n\tvar isDouble bool = false\n\n\tsign = 1\n\tsubscale = 0\n\tsignsubscale = 1\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Byte slice is empty\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tif input[offset] == '-' {\n\t\tsign = -1\n\t\toffset++\n\t}\n\n\tif unicode.IsDigit(rune(input[offset])) == false {\n\t\terrorStr := fmt.Sprintf(\"%s: Not a valid number in input %s\", funcName(), string(input))\n\t\treturn nil, errors.New(errorStr)\n\t}\n\n\tfor {\n\t\tif input[offset] == '0' {\n\t\t\toffset++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor {\n\t\tif unicode.IsDigit(rune(input[offset])) == true {\n\t\t\tn = (n * 10.0) + float64(input[offset]-'0')\n\t\t\toffset++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif input[offset] == '.' && unicode.IsDigit(rune(input[offset+1])) == true {\n\t\toffset++\n\t\tisDouble = true\n\n\t\tfor {\n\t\t\tif unicode.IsDigit(rune(input[offset])) == true {\n\t\t\t\tn = (n * 10.0) + float64(input[offset]-'0')\n\t\t\t\toffset++\n\t\t\t\tscale--\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif input[offset] == 'e' || input[offset] == 'E' {\n\t\toffset++\n\t\tisDouble = true\n\n\t\tif input[offset] == '-' {\n\t\t\tsignsubscale = -1\n\t\t}\n\t\toffset++\n\n\t\tfor {\n\t\t\tif unicode.IsDigit(rune(input[offset])) == true {\n\t\t\t\tsubscale = (subscale * 10) + int(input[offset]-'0')\n\t\t\t\toffset++\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tn = sign * n * math.Pow(10.0, scale+float64(subscale)*float64(signsubscale))\n\n\tif isDouble == true {\n\t\tcur.Valdouble = n\n\t\tcur.Jsontype = JSON_DOUBLE\n\t} else {\n\t\tcur.Valint = int(n)\n\t\tcur.Jsontype = JSON_INT\n\t}\n\n\treturn input[offset:], nil\n}\n\n\/**\n * Function to parse an array\n *\/\nfunc parseArray(cur *GoJSON, input []byte) ([]byte, error) {\n\tvar child, sibling *GoJSON\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Byte slice is empty\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tif input[0] != '[' {\n\t\terrorStr := fmt.Sprintf(\"%s: Not a valid array in input %s\", funcName(), string(input))\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tcur.Jsontype = JSON_ARRAY\n\tinput = nextToken(input[1:])\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Could not find any valid JSON\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\t\/*\n\t * Check if the array is empty\n\t *\/\n\tif input[0] == ']' {\n\t\treturn input[1:], nil\n\t}\n\n\t\/*\n\t * Allocate memory for the child to\n\t * continue processing\n\t *\/\n\tcur.child = new(GoJSON)\n\tchild = cur.child\n\tinput, err := parseValue(child, nextToken(input))\n\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tinput = nextToken(input)\n\n\tif len(input) == 0 {\n\t\treturn []byte{}, nil\n\t}\n\n\t\/*\n\t * Continue processing the array and add the\n\t * child entries to this parent GoJSON object\n\t *\/\n\tfor {\n\t\tif input[0] == ',' {\n\t\t\tsibling = new(GoJSON)\n\t\t\tchild.next = sibling\n\t\t\tsibling.prev = child\n\t\t\tchild = sibling\n\n\t\t\tinput, err = parseValue(child, nextToken(input[1:]))\n\n\t\t\tif err != nil {\n\t\t\t\treturn []byte{}, err\n\t\t\t}\n\n\t\t\tinput = nextToken(input)\n\n\t\t\tif len(input) == 0 {\n\t\t\t\treturn []byte{}, nil\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif input[0] == ']' {\n\t\treturn input[1:], nil\n\t} else {\n\t\terrorStr := fmt.Sprintf(\"%s: Incomplete\/Malformed array in input %s\", funcName(), string(input))\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n}\n\n\/**\n * Function to parse an object\n *\/\nfunc parseObject(cur *GoJSON, input []byte) ([]byte, error) {\n\tvar child, sibling *GoJSON\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Byte slice is empty\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tif input[0] != '{' {\n\t\terrorStr := fmt.Sprintf(\"%s: Not a valid object\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tcur.Jsontype = JSON_OBJECT\n\tinput = nextToken(input[1:])\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Could not find any valid JSON in input %s\", funcName(), string(input))\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\t\/*\n\t * Check if the object is empty\n\t *\/\n\tif input[0] == '}' {\n\t\treturn input[1:], nil\n\t}\n\n\t\/*\n\t * Allocate memory for the child to\n\t * continue processing\n\t *\/\n\tcur.child = new(GoJSON)\n\tchild = cur.child\n\tinput, err := parseString(child, nextToken(input))\n\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tchild.Key = child.Valstr\n\tchild.Valstr = \"\"\n\n\t\/*\n\t * Fetch the location of ':' after the object key\n\t *\/\n\tinput = nextToken(input)\n\tif len(input) == 0 {\n\t\treturn []byte{}, nil\n\t}\n\n\tif input[0] != ':' {\n\t\terrorStr := fmt.Sprintf(\"%s: Malformed object in input %s\", funcName(), string(input))\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tinput, err = parseValue(child, nextToken(input[1:]))\n\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tif input[0] != ',' {\n\t\tinput = nextToken(input)\n\n\t\tif len(input) == 0 {\n\t\t\treturn []byte{}, nil\n\t\t}\n\t}\n\n\t\/*\n\t * Continue processing the object and add the\n\t * child entries to this parent GoJSON object\n\t *\/\n\tfor {\n\t\tif input[0] == ',' {\n\t\t\tsibling = new(GoJSON)\n\t\t\tchild.next = sibling\n\t\t\tsibling.prev = child\n\t\t\tchild = sibling\n\n\t\t\tinput, err = parseString(child, nextToken(input[1:]))\n\n\t\t\tif err != nil {\n\t\t\t\treturn []byte{}, err\n\t\t\t}\n\n\t\t\tchild.Key = child.Valstr\n\t\t\tchild.Valstr = \"\"\n\n\t\t\t\/*\n\t\t\t * Fetch the location of ':' after the object key\n\t\t\t *\/\n\t\t\tinput = nextToken(input)\n\t\t\tif len(input) == 0 {\n\t\t\t\treturn []byte{}, nil\n\t\t\t}\n\n\t\t\tif input[0] != ':' {\n\t\t\t\terrorStr := fmt.Sprintf(\"%s: Malformed object in input %s\", funcName(), string(input))\n\t\t\t\treturn []byte{}, errors.New(errorStr)\n\t\t\t}\n\n\t\t\tinput, err = parseValue(child, nextToken(input[1:]))\n\n\t\t\tif err != nil {\n\t\t\t\treturn []byte{}, err\n\t\t\t}\n\n\t\t\tif input[0] != ',' {\n\t\t\t\tinput = nextToken(input)\n\n\t\t\t\tif len(input) == 0 {\n\t\t\t\t\treturn []byte{}, nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif input[0] == '}' {\n\t\treturn input[1:], nil\n\t} else {\n\t\terrorStr := fmt.Sprintf(\"%s: Incomplete\/Malformed object in input %s\", funcName(), string(input))\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n}\n\n\/**\n * Function to parse the current token\n *\/\nfunc parseValue(cur *GoJSON, input []byte) ([]byte, error) {\n\tinput = nextToken(input)\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Byte slice is empty\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tif strings.Compare(string(input[:4]), \"null\") == 0 {\n\t\tcur.Jsontype = JSON_NULL\n\t\treturn input[4:], nil\n\t}\n\n\tif strings.Compare(string(input[:5]), \"false\") == 0 {\n\t\tcur.Jsontype = JSON_BOOL\n\t\tcur.Valbool = false\n\t\treturn input[5:], nil\n\t}\n\n\tif strings.Compare(string(input[:4]), \"true\") == 0 {\n\t\tcur.Jsontype = JSON_BOOL\n\t\tcur.Valbool = true\n\t\treturn input[4:], nil\n\t}\n\n\tif input[0] >= '0' && input[0] <= '9' {\n\t\treturn parseNumber(cur, input)\n\t}\n\n\tswitch input[0] {\n\tcase '\"':\n\t\treturn parseString(cur, input)\n\n\tcase '-':\n\t\treturn parseNumber(cur, input)\n\n\tcase '[':\n\t\treturn parseArray(cur, input)\n\n\tcase '{':\n\t\treturn parseObject(cur, input)\n\n\t}\n\n\terrorStr := fmt.Sprintf(\"%s: Parsing Error\", funcName())\n\treturn []byte{}, errors.New(errorStr)\n}\n\n\/*\n * Function to begin processing the string input\n * as a byte sequence\n *\/\nfunc GoJSONParse(input []byte) (*GoJSON, error) {\n\tvar g *GoJSON\n\n\tg = new(GoJSON)\n\n\tinput = nextToken(input)\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Could not find any valid JSON in input %s\", funcName(), string(input))\n\t\treturn nil, errors.New(errorStr)\n\t}\n\n\t_, err := parseValue(g, input)\n\n\tif err != nil {\n\t\terrorStr := fmt.Sprintf(\"%s: JSON Parse failed with error %s \", funcName(), err)\n\t\treturn nil, errors.New(errorStr)\n\t}\n\n\treturn g, nil\n}\n<commit_msg>Changes next, prev and child pointers to be exposed externally.<commit_after>package jsonez\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\/*\n * JSON types\n *\/\nconst (\n\tJSON_BOOL = iota\n\tJSON_NULL\n\tJSON_INT\n\tJSON_DOUBLE\n\tJSON_STRING\n\tJSON_ARRAY\n\tJSON_OBJECT\n)\n\nvar errorOffset int = -1\n\n\/*\n * GoJSON structure\n *\/\ntype GoJSON struct {\n\t\/**\n\t * Pointers to walk array\/object chains\n\t *\/\n\tNext, Prev *GoJSON\n\n\t\/**\n\t * Child item of the current object\n\t *\/\n\tChild *GoJSON\n\n\t\/** JSON type *\/\n\tJsontype int\n\n\t\/**\n\t * Valstr will be set when\n\t *type is JSON_STRING\n\t *\/\n\tValstr string\n\n\t\/**\n\t * Valint will be set when type\n\t * is JSON_INT\n\t *\/\n\tValint int\n\n\t\/**\n\t * valuenum will be set when\n\t * type is JSON_DOUBLE\n\t *\/\n\tValdouble float64\n\n\t\/**\n\t * Valbool will be set when\n\t * type is JSON_BOOL\n\t *\/\n\tValbool bool\n\n\t\/**\n\t * JSON Key\n\t *\/\n\tKey string\n}\n\n\/**\n * Functions related to parsing a JSON string\n *\/\n\n\/**\n * nextToken finds the next token\n *\/\nfunc nextToken(input []byte) []byte {\n\tfor i, c := range input {\n\t\tif unicode.IsSpace(rune(c)) || c == '\\'' {\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn input[i:]\n\t\t}\n\t}\n\n\treturn []byte{}\n}\n\n\/**\n * Function to parse a string\n *\/\nfunc parseString(cur *GoJSON, input []byte) ([]byte, error) {\n\tvar offset int\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Byte slice is empty\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tif input[0] != '\"' {\n\t\terrorStr := fmt.Sprintf(\"%s: Not a valid string in input %s\", funcName(), string(input))\n\t\treturn nil, errors.New(errorStr)\n\t}\n\n\tfor i := range input {\n\t\tif i > 0 && input[i] == '\"' {\n\t\t\tbreak\n\t\t} else {\n\t\t\toffset++\n\t\t}\n\t}\n\n\tcur.Jsontype = JSON_STRING\n\tcur.Valstr = strings.Trim(string(input[1:offset]), \" \")\n\n\treturn input[offset+1:], nil\n}\n\n\/**\n * Function to parse a number\n *\/\nfunc parseNumber(cur *GoJSON, input []byte) ([]byte, error) {\n\tvar n, sign, scale float64\n\tvar subscale, signsubscale, offset int\n\tvar isDouble bool = false\n\n\tsign = 1\n\tsubscale = 0\n\tsignsubscale = 1\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Byte slice is empty\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tif input[offset] == '-' {\n\t\tsign = -1\n\t\toffset++\n\t}\n\n\tif unicode.IsDigit(rune(input[offset])) == false {\n\t\terrorStr := fmt.Sprintf(\"%s: Not a valid number in input %s\", funcName(), string(input))\n\t\treturn nil, errors.New(errorStr)\n\t}\n\n\tfor {\n\t\tif input[offset] == '0' {\n\t\t\toffset++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor {\n\t\tif unicode.IsDigit(rune(input[offset])) == true {\n\t\t\tn = (n * 10.0) + float64(input[offset]-'0')\n\t\t\toffset++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif input[offset] == '.' && unicode.IsDigit(rune(input[offset+1])) == true {\n\t\toffset++\n\t\tisDouble = true\n\n\t\tfor {\n\t\t\tif unicode.IsDigit(rune(input[offset])) == true {\n\t\t\t\tn = (n * 10.0) + float64(input[offset]-'0')\n\t\t\t\toffset++\n\t\t\t\tscale--\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif input[offset] == 'e' || input[offset] == 'E' {\n\t\toffset++\n\t\tisDouble = true\n\n\t\tif input[offset] == '-' {\n\t\t\tsignsubscale = -1\n\t\t}\n\t\toffset++\n\n\t\tfor {\n\t\t\tif unicode.IsDigit(rune(input[offset])) == true {\n\t\t\t\tsubscale = (subscale * 10) + int(input[offset]-'0')\n\t\t\t\toffset++\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tn = sign * n * math.Pow(10.0, scale+float64(subscale)*float64(signsubscale))\n\n\tif isDouble == true {\n\t\tcur.Valdouble = n\n\t\tcur.Jsontype = JSON_DOUBLE\n\t} else {\n\t\tcur.Valint = int(n)\n\t\tcur.Jsontype = JSON_INT\n\t}\n\n\treturn input[offset:], nil\n}\n\n\/**\n * Function to parse an array\n *\/\nfunc parseArray(cur *GoJSON, input []byte) ([]byte, error) {\n\tvar child, sibling *GoJSON\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Byte slice is empty\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tif input[0] != '[' {\n\t\terrorStr := fmt.Sprintf(\"%s: Not a valid array in input %s\", funcName(), string(input))\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tcur.Jsontype = JSON_ARRAY\n\tinput = nextToken(input[1:])\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Could not find any valid JSON\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\t\/*\n\t * Check if the array is empty\n\t *\/\n\tif input[0] == ']' {\n\t\treturn input[1:], nil\n\t}\n\n\t\/*\n\t * Allocate memory for the child to\n\t * continue processing\n\t *\/\n\tcur.child = new(GoJSON)\n\tchild = cur.child\n\tinput, err := parseValue(child, nextToken(input))\n\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tinput = nextToken(input)\n\n\tif len(input) == 0 {\n\t\treturn []byte{}, nil\n\t}\n\n\t\/*\n\t * Continue processing the array and add the\n\t * child entries to this parent GoJSON object\n\t *\/\n\tfor {\n\t\tif input[0] == ',' {\n\t\t\tsibling = new(GoJSON)\n\t\t\tchild.next = sibling\n\t\t\tsibling.prev = child\n\t\t\tchild = sibling\n\n\t\t\tinput, err = parseValue(child, nextToken(input[1:]))\n\n\t\t\tif err != nil {\n\t\t\t\treturn []byte{}, err\n\t\t\t}\n\n\t\t\tinput = nextToken(input)\n\n\t\t\tif len(input) == 0 {\n\t\t\t\treturn []byte{}, nil\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif input[0] == ']' {\n\t\treturn input[1:], nil\n\t} else {\n\t\terrorStr := fmt.Sprintf(\"%s: Incomplete\/Malformed array in input %s\", funcName(), string(input))\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n}\n\n\/**\n * Function to parse an object\n *\/\nfunc parseObject(cur *GoJSON, input []byte) ([]byte, error) {\n\tvar child, sibling *GoJSON\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Byte slice is empty\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tif input[0] != '{' {\n\t\terrorStr := fmt.Sprintf(\"%s: Not a valid object\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tcur.Jsontype = JSON_OBJECT\n\tinput = nextToken(input[1:])\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Could not find any valid JSON in input %s\", funcName(), string(input))\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\t\/*\n\t * Check if the object is empty\n\t *\/\n\tif input[0] == '}' {\n\t\treturn input[1:], nil\n\t}\n\n\t\/*\n\t * Allocate memory for the child to\n\t * continue processing\n\t *\/\n\tcur.child = new(GoJSON)\n\tchild = cur.child\n\tinput, err := parseString(child, nextToken(input))\n\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tchild.Key = child.Valstr\n\tchild.Valstr = \"\"\n\n\t\/*\n\t * Fetch the location of ':' after the object key\n\t *\/\n\tinput = nextToken(input)\n\tif len(input) == 0 {\n\t\treturn []byte{}, nil\n\t}\n\n\tif input[0] != ':' {\n\t\terrorStr := fmt.Sprintf(\"%s: Malformed object in input %s\", funcName(), string(input))\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tinput, err = parseValue(child, nextToken(input[1:]))\n\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\tif input[0] != ',' {\n\t\tinput = nextToken(input)\n\n\t\tif len(input) == 0 {\n\t\t\treturn []byte{}, nil\n\t\t}\n\t}\n\n\t\/*\n\t * Continue processing the object and add the\n\t * child entries to this parent GoJSON object\n\t *\/\n\tfor {\n\t\tif input[0] == ',' {\n\t\t\tsibling = new(GoJSON)\n\t\t\tchild.next = sibling\n\t\t\tsibling.prev = child\n\t\t\tchild = sibling\n\n\t\t\tinput, err = parseString(child, nextToken(input[1:]))\n\n\t\t\tif err != nil {\n\t\t\t\treturn []byte{}, err\n\t\t\t}\n\n\t\t\tchild.Key = child.Valstr\n\t\t\tchild.Valstr = \"\"\n\n\t\t\t\/*\n\t\t\t * Fetch the location of ':' after the object key\n\t\t\t *\/\n\t\t\tinput = nextToken(input)\n\t\t\tif len(input) == 0 {\n\t\t\t\treturn []byte{}, nil\n\t\t\t}\n\n\t\t\tif input[0] != ':' {\n\t\t\t\terrorStr := fmt.Sprintf(\"%s: Malformed object in input %s\", funcName(), string(input))\n\t\t\t\treturn []byte{}, errors.New(errorStr)\n\t\t\t}\n\n\t\t\tinput, err = parseValue(child, nextToken(input[1:]))\n\n\t\t\tif err != nil {\n\t\t\t\treturn []byte{}, err\n\t\t\t}\n\n\t\t\tif input[0] != ',' {\n\t\t\t\tinput = nextToken(input)\n\n\t\t\t\tif len(input) == 0 {\n\t\t\t\t\treturn []byte{}, nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif input[0] == '}' {\n\t\treturn input[1:], nil\n\t} else {\n\t\terrorStr := fmt.Sprintf(\"%s: Incomplete\/Malformed object in input %s\", funcName(), string(input))\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n}\n\n\/**\n * Function to parse the current token\n *\/\nfunc parseValue(cur *GoJSON, input []byte) ([]byte, error) {\n\tinput = nextToken(input)\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Byte slice is empty\", funcName())\n\t\treturn []byte{}, errors.New(errorStr)\n\t}\n\n\tif strings.Compare(string(input[:4]), \"null\") == 0 {\n\t\tcur.Jsontype = JSON_NULL\n\t\treturn input[4:], nil\n\t}\n\n\tif strings.Compare(string(input[:5]), \"false\") == 0 {\n\t\tcur.Jsontype = JSON_BOOL\n\t\tcur.Valbool = false\n\t\treturn input[5:], nil\n\t}\n\n\tif strings.Compare(string(input[:4]), \"true\") == 0 {\n\t\tcur.Jsontype = JSON_BOOL\n\t\tcur.Valbool = true\n\t\treturn input[4:], nil\n\t}\n\n\tif input[0] >= '0' && input[0] <= '9' {\n\t\treturn parseNumber(cur, input)\n\t}\n\n\tswitch input[0] {\n\tcase '\"':\n\t\treturn parseString(cur, input)\n\n\tcase '-':\n\t\treturn parseNumber(cur, input)\n\n\tcase '[':\n\t\treturn parseArray(cur, input)\n\n\tcase '{':\n\t\treturn parseObject(cur, input)\n\n\t}\n\n\terrorStr := fmt.Sprintf(\"%s: Parsing Error\", funcName())\n\treturn []byte{}, errors.New(errorStr)\n}\n\n\/*\n * Function to begin processing the string input\n * as a byte sequence\n *\/\nfunc GoJSONParse(input []byte) (*GoJSON, error) {\n\tvar g *GoJSON\n\n\tg = new(GoJSON)\n\n\tinput = nextToken(input)\n\n\tif len(input) == 0 {\n\t\terrorStr := fmt.Sprintf(\"%s: Could not find any valid JSON in input %s\", funcName(), string(input))\n\t\treturn nil, errors.New(errorStr)\n\t}\n\n\t_, err := parseValue(g, input)\n\n\tif err != nil {\n\t\terrorStr := fmt.Sprintf(\"%s: JSON Parse failed with error %s \", funcName(), err)\n\t\treturn nil, errors.New(errorStr)\n\t}\n\n\treturn g, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\npackage runtime_test\n\nimport \"testing\"\n\nconst N = 20\n\nfunc BenchmarkAppend(b *testing.B) {\n\tb.StopTimer()\n\tx := make([]int, 0, N)\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tx = x[0:0]\n\t\tfor j := 0; j < N; j++ {\n\t\t\tx = append(x, j)\n\t\t}\n\t}\n}\n\nfunc BenchmarkAppendSpecialCase(b *testing.B) {\n\tb.StopTimer()\n\tx := make([]int, 0, N)\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tx = x[0:0]\n\t\tfor j := 0; j < N; j++ {\n\t\t\tif len(x) < cap(x) {\n\t\t\t\tx = x[:len(x)+1]\n\t\t\t\tx[len(x)-1] = j\n\t\t\t} else {\n\t\t\t\tx = append(x, j)\n\t\t\t}\n\t\t}\n\t}\n}\n\nvar x = make([]int, 0, 10)\n\nfunc f() int {\n\tx[:1][0] = 3\n\treturn 2\n}\n\nfunc TestSideEffectOrder(t *testing.T) {\n\tx = append(x, 1, f())\n\tif x[0] != 1 || x[1] != 2 {\n\t\tt.Error(\"append failed: \", x[0], x[1])\n\t}\n}\n<commit_msg>runtime: make TestSideEffectOrder work twice<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\npackage runtime_test\n\nimport \"testing\"\n\nconst N = 20\n\nfunc BenchmarkAppend(b *testing.B) {\n\tb.StopTimer()\n\tx := make([]int, 0, N)\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tx = x[0:0]\n\t\tfor j := 0; j < N; j++ {\n\t\t\tx = append(x, j)\n\t\t}\n\t}\n}\n\nfunc BenchmarkAppendSpecialCase(b *testing.B) {\n\tb.StopTimer()\n\tx := make([]int, 0, N)\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tx = x[0:0]\n\t\tfor j := 0; j < N; j++ {\n\t\t\tif len(x) < cap(x) {\n\t\t\t\tx = x[:len(x)+1]\n\t\t\t\tx[len(x)-1] = j\n\t\t\t} else {\n\t\t\t\tx = append(x, j)\n\t\t\t}\n\t\t}\n\t}\n}\n\nvar x []int\n\nfunc f() int {\n\tx[:1][0] = 3\n\treturn 2\n}\n\nfunc TestSideEffectOrder(t *testing.T) {\n\tx = make([]int, 0, 10)\n\tx = append(x, 1, f())\n\tif x[0] != 1 || x[1] != 2 {\n\t\tt.Error(\"append failed: \", x[0], x[1])\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package deploy\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\tyaml \"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/ViBiOh\/auth\/pkg\/auth\"\n\t\"github.com\/ViBiOh\/auth\/pkg\/model\"\n\t\"github.com\/ViBiOh\/dashboard\/pkg\/commons\"\n\t\"github.com\/ViBiOh\/dashboard\/pkg\/docker\"\n\t\"github.com\/ViBiOh\/httputils\/pkg\/httperror\"\n\t\"github.com\/ViBiOh\/httputils\/pkg\/httpjson\"\n\t\"github.com\/ViBiOh\/httputils\/pkg\/request\"\n\t\"github.com\/ViBiOh\/httputils\/pkg\/rollbar\"\n\t\"github.com\/ViBiOh\/httputils\/pkg\/tools\"\n\t\"github.com\/ViBiOh\/mailer\/pkg\/client\"\n\t\"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/api\/types\/filters\"\n\topentracing \"github.com\/opentracing\/opentracing-go\"\n)\n\nconst (\n\t\/\/ DeployTimeout indicates delay for application to deploy before rollback\n\tDeployTimeout = 3 * time.Minute\n\n\tdefaultCPUShares = 128\n\tminMemory        = 16777216\n\tmaxMemory        = 805306368\n\tcolonSeparator   = `:`\n\tdeploySuffix     = `_deploy`\n)\n\n\/\/ App stores informations\ntype App struct {\n\ttasks         sync.Map\n\tdockerApp     *docker.App\n\tauthApp       *auth.App\n\tnetwork       string\n\ttag           string\n\tcontainerUser string\n\tappURL        string\n\tnotification  string\n\tmailerApp     *client.App\n}\n\n\/\/ NewApp creates new App from Flags' config\nfunc NewApp(config map[string]*string, authApp *auth.App, dockerApp *docker.App, mailerApp *client.App) *App {\n\treturn &App{\n\t\ttasks:         sync.Map{},\n\t\tdockerApp:     dockerApp,\n\t\tauthApp:       authApp,\n\t\tmailerApp:     mailerApp,\n\t\tnetwork:       strings.TrimSpace(*config[`network`]),\n\t\ttag:           strings.TrimSpace(*config[`tag`]),\n\t\tcontainerUser: strings.TrimSpace(*config[`containerUser`]),\n\t\tappURL:        strings.TrimSpace(*config[`appURL`]),\n\t\tnotification:  strings.TrimSpace(*config[`notification`]),\n\t}\n}\n\n\/\/ Flags adds flags for given prefix\nfunc Flags(prefix string) map[string]*string {\n\treturn map[string]*string{\n\t\t`network`:       flag.String(tools.ToCamel(fmt.Sprintf(`%sNetwork`, prefix)), `traefik`, `[deploy] Default Network`),\n\t\t`tag`:           flag.String(tools.ToCamel(fmt.Sprintf(`%sTag`, prefix)), `latest`, `[deploy] Default image tag)`),\n\t\t`containerUser`: flag.String(tools.ToCamel(fmt.Sprintf(`%sContainerUser`, prefix)), `1000`, `[deploy] Default container user`),\n\t\t`appURL`:        flag.String(tools.ToCamel(fmt.Sprintf(`%sAppURL`, prefix)), `https:\/\/dashboard.vibioh.fr`, `[deploy] Application web URL`),\n\t\t`notification`:  flag.String(tools.ToCamel(fmt.Sprintf(`%sNotification`, prefix)), `onError`, `[deploy] Send email notification when deploy ends (possibles values ares \"never\", \"onError\", \"all\")`),\n\t}\n}\n\n\/\/ CanBeGracefullyClosed indicates if application can terminate safely\nfunc (a *App) CanBeGracefullyClosed() (canBe bool) {\n\tcanBe = true\n\n\ta.tasks.Range(func(_ interface{}, value interface{}) bool {\n\t\tcanBe = !value.(bool)\n\t\treturn canBe\n\t})\n\n\treturn\n}\n\nfunc (a *App) pullImage(ctx context.Context, image string) error {\n\tif !strings.Contains(image, colonSeparator) {\n\t\timage = fmt.Sprintf(`%s%slatest`, image, colonSeparator)\n\t}\n\n\tpull, err := a.dockerApp.Docker.ImagePull(ctx, image, types.ImagePullOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(`Error while pulling image: %v`, err)\n\t}\n\n\t_, err = request.ReadBody(pull)\n\treturn err\n}\n\nfunc (a *App) cleanContainers(ctx context.Context, containers []types.Container) error {\n\tfor _, container := range containers {\n\t\tif _, err := a.dockerApp.GracefulStopContainer(ctx, container.ID, time.Minute); err != nil {\n\t\t\trollbar.LogError(`Error while stopping container %s: %v`, container.Names, err)\n\t\t}\n\t}\n\n\tfor _, container := range containers {\n\t\tif _, err := a.dockerApp.RmContainer(ctx, container.ID, nil, false); err != nil {\n\t\t\treturn fmt.Errorf(`Error while deleting container %s: %v`, container.Names, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (a *App) renameDeployedContainers(ctx context.Context, services map[string]*deployedService) error {\n\tfor _, service := range services {\n\t\tif err := a.dockerApp.Docker.ContainerRename(ctx, service.ContainerID, getFinalName(service.FullName)); err != nil {\n\t\t\treturn fmt.Errorf(`Error while renaming container %s: %v`, service.Name, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (a *App) deleteServices(ctx context.Context, appName string, services map[string]*deployedService, user *model.User) {\n\tfor _, service := range services {\n\t\tinfos, err := a.dockerApp.InspectContainer(ctx, service.ContainerID)\n\t\tif err != nil {\n\t\t\trollbar.LogError(`[%s] [%s] Error while inspecting service %s: %v`, user.Username, appName, service.Name, err)\n\t\t} else {\n\t\t\tif _, err := a.dockerApp.StopContainer(ctx, service.ContainerID, infos); err != nil {\n\t\t\t\trollbar.LogError(`[%s] [%s] Error while stopping service %s: %v`, user.Username, appName, service.Name, err)\n\t\t\t}\n\n\t\t\tif _, err := a.dockerApp.RmContainer(ctx, service.ContainerID, infos, true); err != nil {\n\t\t\t\trollbar.LogError(`[%s] [%s] Error while deleting service %s: %v`, user.Username, appName, service.Name, err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (a *App) startServices(ctx context.Context, services map[string]*deployedService) error {\n\tfor _, service := range services {\n\t\tif _, err := a.dockerApp.StartContainer(ctx, service.ContainerID, nil); err != nil {\n\t\t\treturn fmt.Errorf(`Error while starting service %s: %v`, service.Name, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (a *App) inspectServices(ctx context.Context, services map[string]*deployedService, user *model.User, appName string) []*types.ContainerJSON {\n\tcontainers := make([]*types.ContainerJSON, 0, len(services))\n\n\tfor _, service := range services {\n\t\tinfos, err := a.dockerApp.InspectContainer(ctx, service.ContainerID)\n\t\tif err != nil {\n\t\t\trollbar.LogError(`[%s] [%s] Error while inspecting container %s: %v`, user.Username, appName, service.Name, err)\n\t\t} else {\n\t\t\tcontainers = append(containers, infos)\n\t\t}\n\t}\n\n\treturn containers\n}\n\nfunc (a *App) areContainersHealthy(ctx context.Context, user *model.User, appName string, services map[string]*deployedService) bool {\n\tcontainersServices := a.inspectServices(ctx, services, user, appName)\n\tcontainersIdsWithHealthcheck := commons.GetContainersIDs(commons.FilterContainers(containersServices, hasHealthcheck))\n\n\tif len(containersIdsWithHealthcheck) == 0 {\n\t\treturn true\n\t}\n\n\tfor _, id := range containersIdsWithHealthcheck {\n\t\tif service := findServiceByContainerID(services, id); service != nil {\n\t\t\tservice.State = `unhealthy`\n\t\t}\n\t}\n\n\tfiltersArgs := filters.NewArgs()\n\thealthyStatusFilters(&filtersArgs, containersIdsWithHealthcheck)\n\n\ttimeoutCtx, cancel := context.WithTimeout(ctx, DeployTimeout)\n\tdefer cancel()\n\n\tmessages, errors := a.dockerApp.Docker.Events(timeoutCtx, types.EventsOptions{Filters: filtersArgs})\n\thealthyContainers := make(map[string]bool, len(containersIdsWithHealthcheck))\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn false\n\t\tcase message := <-messages:\n\t\t\tif service := findServiceByContainerID(services, message.ID); service != nil {\n\t\t\t\tservice.State = `healthy`\n\t\t\t}\n\n\t\t\thealthyContainers[message.ID] = true\n\t\t\tif len(healthyContainers) == len(containersIdsWithHealthcheck) {\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase err := <-errors:\n\t\t\trollbar.LogError(`[%s] [%s] Error while reading healthy events: %v`, user.Username, appName, err)\n\t\t\treturn false\n\t\t}\n\t}\n}\n\nfunc (a *App) finishDeploy(ctx context.Context, user *model.User, appName string, services map[string]*deployedService, oldContainers []types.Container, requestParams url.Values) {\n\tspan := opentracing.SpanFromContext(ctx)\n\tspan.SetTag(`app`, appName)\n\tspan.SetTag(`services_count`, len(services))\n\tdefer func() {\n\t\tdefer a.tasks.Delete(appName)\n\t\tdefer span.Finish()\n\t}()\n\n\tsuccess := a.areContainersHealthy(ctx, user, appName, services)\n\ta.captureServicesOutput(ctx, user, appName, services)\n\n\tif success {\n\t\tif err := a.cleanContainers(ctx, oldContainers); err != nil {\n\t\t\trollbar.LogError(`[%s] [%s] Error while cleaning old containers: %v`, user.Username, appName, err)\n\t\t}\n\n\t\tif err := a.renameDeployedContainers(ctx, services); err != nil {\n\t\t\trollbar.LogError(`[%s] [%s] Error while renaming deployed containers: %v`, user.Username, appName, err)\n\t\t}\n\t} else {\n\t\trollbar.LogWarning(`[%s] [%s] Failed to deploy: %v`, user.Username, appName, errHealthCheckFailed)\n\t\ta.deleteServices(ctx, appName, services, user)\n\t}\n\n\tif !success {\n\t\tfor _, service := range services {\n\t\t\tlog.Printf(\"[%s] [%s] Logs output for %s: \\n%s\\n\", user.Username, appName, service.Name, strings.Join(service.Logs, \"\\n\"))\n\t\t\tlog.Printf(\"[%s] [%s] Health output for %s: \\n%s\\n\", user.Username, appName, service.Name, strings.Join(service.HealthLogs, \"\\n\"))\n\t\t}\n\t}\n\n\tif err := a.sendEmailNotification(ctx, user, appName, services, success); err != nil {\n\t\trollbar.LogError(`[%s] [%s] Error while sending email notification: %s`, user.Username, appName, err)\n\t}\n\n\tif err := a.sendRollbarNotification(ctx, user, requestParams); err != nil {\n\t\trollbar.LogError(`[%s] [%s] Error while sending rollbar notification: %s`, user.Username, appName, err)\n\t}\n}\n\nfunc (a *App) createContainer(ctx context.Context, user *model.User, appName string, serviceName string, service *dockerComposeService) (*deployedService, error) {\n\timagePulled := false\n\n\tif a.tag != `` {\n\t\timageOverride := fmt.Sprintf(`%s%s%s`, service.Image, colonSeparator, a.tag)\n\t\tif err := a.pullImage(ctx, imageOverride); err == nil {\n\t\t\tservice.Image = imageOverride\n\t\t\timagePulled = true\n\t\t}\n\t}\n\n\tif !imagePulled {\n\t\tif err := a.pullImage(ctx, service.Image); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tserviceFullName := getServiceFullName(appName, serviceName)\n\n\tconfig, err := a.getConfig(service, user, appName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(`Error while getting config: %v`, err)\n\t}\n\n\tcreatedContainer, err := a.dockerApp.Docker.ContainerCreate(ctx, config, a.getHostConfig(service, user), a.getNetworkConfig(serviceName, service), serviceFullName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(`Error while creating service %s: %v`, serviceName, err)\n\t}\n\n\treturn &deployedService{\n\t\tName:        serviceName,\n\t\tFullName:    serviceFullName,\n\t\tContainerID: createdContainer.ID,\n\t\tImageName:   service.Image,\n\t}, nil\n}\n\nfunc (a *App) parseCompose(ctx context.Context, user *model.User, appName string, composeFile []byte) (map[string]*deployedService, error) {\n\tcomposeFile = bytes.Replace(composeFile, []byte(`$$`), []byte(`$`), -1)\n\n\tcompose := dockerCompose{}\n\tif err := yaml.Unmarshal(composeFile, &compose); err != nil {\n\t\treturn nil, fmt.Errorf(`[%s] [%s] Error while unmarshalling compose file: %v`, user.Username, appName, err)\n\t}\n\n\tnewServices := make(map[string]*deployedService)\n\tfor serviceName, service := range compose.Services {\n\t\tif deployedService, err := a.createContainer(ctx, user, appName, serviceName, &service); err != nil {\n\t\t\tbreak\n\t\t} else {\n\t\t\tnewServices[serviceName] = deployedService\n\t\t}\n\t}\n\n\treturn newServices, nil\n}\n\nfunc composeFailed(w http.ResponseWriter, user *model.User, appName string, err error) {\n\thttperror.InternalServerError(w, fmt.Errorf(`[%s] [%s] Failed to deploy: %v`, user.Username, appName, err))\n}\n\nfunc (a *App) composeHandler(w http.ResponseWriter, r *http.Request, user *model.User) {\n\tif r.Method != http.MethodPost {\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tappName, composeFile, err := checkParams(r, user)\n\tif err != nil {\n\t\thttperror.BadRequest(w, err)\n\t\treturn\n\t}\n\n\tctx := r.Context()\n\n\toldContainers, err := a.checkRights(ctx, user, appName)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusForbidden)\n\t\treturn\n\t}\n\n\tnewServices, err := a.parseCompose(ctx, user, appName, composeFile)\n\tif err != nil {\n\t\tcomposeFailed(w, user, appName, err)\n\t\treturn\n\t}\n\n\tif err = a.checkTasks(user, appName); err != nil {\n\t\tcomposeFailed(w, user, appName, err)\n\t\treturn\n\t}\n\n\tif err == nil {\n\t\terr = a.startServices(ctx, newServices)\n\t}\n\n\tif err != nil {\n\t\tcomposeFailed(w, user, appName, err)\n\t\treturn\n\t}\n\n\tctx = context.Background()\n\tparentSpanContext := opentracing.SpanFromContext(r.Context()).Context()\n\t_, ctx = opentracing.StartSpanFromContext(ctx, `Deploy`, opentracing.FollowsFrom(parentSpanContext))\n\n\tgo a.finishDeploy(ctx, user, appName, newServices, oldContainers, r.URL.Query())\n\n\tif err := httpjson.ResponseArrayJSON(w, http.StatusOK, newServices, httpjson.IsPretty(r.URL.RawQuery)); err != nil {\n\t\thttperror.InternalServerError(w, err)\n\t}\n}\n\n\/\/ Handler for request. Should be use with net\/http\nfunc (a *App) Handler() http.Handler {\n\treturn a.authApp.Handler(a.composeHandler)\n}\n<commit_msg>Restoring clean of deploy failed on success<commit_after>package deploy\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\tyaml \"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/ViBiOh\/auth\/pkg\/auth\"\n\t\"github.com\/ViBiOh\/auth\/pkg\/model\"\n\t\"github.com\/ViBiOh\/dashboard\/pkg\/commons\"\n\t\"github.com\/ViBiOh\/dashboard\/pkg\/docker\"\n\t\"github.com\/ViBiOh\/httputils\/pkg\/httperror\"\n\t\"github.com\/ViBiOh\/httputils\/pkg\/httpjson\"\n\t\"github.com\/ViBiOh\/httputils\/pkg\/request\"\n\t\"github.com\/ViBiOh\/httputils\/pkg\/rollbar\"\n\t\"github.com\/ViBiOh\/httputils\/pkg\/tools\"\n\t\"github.com\/ViBiOh\/mailer\/pkg\/client\"\n\t\"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/api\/types\/filters\"\n\topentracing \"github.com\/opentracing\/opentracing-go\"\n)\n\nconst (\n\t\/\/ DeployTimeout indicates delay for application to deploy before rollback\n\tDeployTimeout = 3 * time.Minute\n\n\tdefaultCPUShares = 128\n\tminMemory        = 16777216\n\tmaxMemory        = 805306368\n\tcolonSeparator   = `:`\n\tdeploySuffix     = `_deploy`\n)\n\n\/\/ App stores informations\ntype App struct {\n\ttasks         sync.Map\n\tdockerApp     *docker.App\n\tauthApp       *auth.App\n\tnetwork       string\n\ttag           string\n\tcontainerUser string\n\tappURL        string\n\tnotification  string\n\tmailerApp     *client.App\n}\n\n\/\/ NewApp creates new App from Flags' config\nfunc NewApp(config map[string]*string, authApp *auth.App, dockerApp *docker.App, mailerApp *client.App) *App {\n\treturn &App{\n\t\ttasks:         sync.Map{},\n\t\tdockerApp:     dockerApp,\n\t\tauthApp:       authApp,\n\t\tmailerApp:     mailerApp,\n\t\tnetwork:       strings.TrimSpace(*config[`network`]),\n\t\ttag:           strings.TrimSpace(*config[`tag`]),\n\t\tcontainerUser: strings.TrimSpace(*config[`containerUser`]),\n\t\tappURL:        strings.TrimSpace(*config[`appURL`]),\n\t\tnotification:  strings.TrimSpace(*config[`notification`]),\n\t}\n}\n\n\/\/ Flags adds flags for given prefix\nfunc Flags(prefix string) map[string]*string {\n\treturn map[string]*string{\n\t\t`network`:       flag.String(tools.ToCamel(fmt.Sprintf(`%sNetwork`, prefix)), `traefik`, `[deploy] Default Network`),\n\t\t`tag`:           flag.String(tools.ToCamel(fmt.Sprintf(`%sTag`, prefix)), `latest`, `[deploy] Default image tag)`),\n\t\t`containerUser`: flag.String(tools.ToCamel(fmt.Sprintf(`%sContainerUser`, prefix)), `1000`, `[deploy] Default container user`),\n\t\t`appURL`:        flag.String(tools.ToCamel(fmt.Sprintf(`%sAppURL`, prefix)), `https:\/\/dashboard.vibioh.fr`, `[deploy] Application web URL`),\n\t\t`notification`:  flag.String(tools.ToCamel(fmt.Sprintf(`%sNotification`, prefix)), `onError`, `[deploy] Send email notification when deploy ends (possibles values ares \"never\", \"onError\", \"all\")`),\n\t}\n}\n\n\/\/ CanBeGracefullyClosed indicates if application can terminate safely\nfunc (a *App) CanBeGracefullyClosed() (canBe bool) {\n\tcanBe = true\n\n\ta.tasks.Range(func(_ interface{}, value interface{}) bool {\n\t\tcanBe = !value.(bool)\n\t\treturn canBe\n\t})\n\n\treturn\n}\n\nfunc (a *App) pullImage(ctx context.Context, image string) error {\n\tif !strings.Contains(image, colonSeparator) {\n\t\timage = fmt.Sprintf(`%s%slatest`, image, colonSeparator)\n\t}\n\n\tpull, err := a.dockerApp.Docker.ImagePull(ctx, image, types.ImagePullOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(`Error while pulling image: %v`, err)\n\t}\n\n\t_, err = request.ReadBody(pull)\n\treturn err\n}\n\nfunc (a *App) cleanContainers(ctx context.Context, containers []types.Container) error {\n\tfor _, container := range containers {\n\t\tif _, err := a.dockerApp.GracefulStopContainer(ctx, container.ID, time.Minute); err != nil {\n\t\t\trollbar.LogError(`Error while stopping container %s: %v`, container.Names, err)\n\t\t}\n\t}\n\n\tfor _, container := range containers {\n\t\tif _, err := a.dockerApp.RmContainer(ctx, container.ID, nil, false); err != nil {\n\t\t\treturn fmt.Errorf(`Error while deleting container %s: %v`, container.Names, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (a *App) renameDeployedContainers(ctx context.Context, services map[string]*deployedService) error {\n\tfor _, service := range services {\n\t\tif err := a.dockerApp.Docker.ContainerRename(ctx, service.ContainerID, getFinalName(service.FullName)); err != nil {\n\t\t\treturn fmt.Errorf(`Error while renaming container %s: %v`, service.Name, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (a *App) deleteServices(ctx context.Context, appName string, services map[string]*deployedService, user *model.User) {\n\tfor _, service := range services {\n\t\tinfos, err := a.dockerApp.InspectContainer(ctx, service.ContainerID)\n\t\tif err != nil {\n\t\t\trollbar.LogError(`[%s] [%s] Error while inspecting service %s: %v`, user.Username, appName, service.Name, err)\n\t\t} else {\n\t\t\tif _, err := a.dockerApp.StopContainer(ctx, service.ContainerID, infos); err != nil {\n\t\t\t\trollbar.LogError(`[%s] [%s] Error while stopping service %s: %v`, user.Username, appName, service.Name, err)\n\t\t\t}\n\n\t\t\tif _, err := a.dockerApp.RmContainer(ctx, service.ContainerID, infos, true); err != nil {\n\t\t\t\trollbar.LogError(`[%s] [%s] Error while deleting service %s: %v`, user.Username, appName, service.Name, err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (a *App) startServices(ctx context.Context, services map[string]*deployedService) error {\n\tfor _, service := range services {\n\t\tif _, err := a.dockerApp.StartContainer(ctx, service.ContainerID, nil); err != nil {\n\t\t\treturn fmt.Errorf(`Error while starting service %s: %v`, service.Name, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (a *App) inspectServices(ctx context.Context, services map[string]*deployedService, user *model.User, appName string) []*types.ContainerJSON {\n\tcontainers := make([]*types.ContainerJSON, 0, len(services))\n\n\tfor _, service := range services {\n\t\tinfos, err := a.dockerApp.InspectContainer(ctx, service.ContainerID)\n\t\tif err != nil {\n\t\t\trollbar.LogError(`[%s] [%s] Error while inspecting container %s: %v`, user.Username, appName, service.Name, err)\n\t\t} else {\n\t\t\tcontainers = append(containers, infos)\n\t\t}\n\t}\n\n\treturn containers\n}\n\nfunc (a *App) areContainersHealthy(ctx context.Context, user *model.User, appName string, services map[string]*deployedService) bool {\n\tcontainersServices := a.inspectServices(ctx, services, user, appName)\n\tcontainersIdsWithHealthcheck := commons.GetContainersIDs(commons.FilterContainers(containersServices, hasHealthcheck))\n\n\tif len(containersIdsWithHealthcheck) == 0 {\n\t\treturn true\n\t}\n\n\tfor _, id := range containersIdsWithHealthcheck {\n\t\tif service := findServiceByContainerID(services, id); service != nil {\n\t\t\tservice.State = `unhealthy`\n\t\t}\n\t}\n\n\tfiltersArgs := filters.NewArgs()\n\thealthyStatusFilters(&filtersArgs, containersIdsWithHealthcheck)\n\n\ttimeoutCtx, cancel := context.WithTimeout(ctx, DeployTimeout)\n\tdefer cancel()\n\n\tmessages, errors := a.dockerApp.Docker.Events(timeoutCtx, types.EventsOptions{Filters: filtersArgs})\n\thealthyContainers := make(map[string]bool, len(containersIdsWithHealthcheck))\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn false\n\t\tcase message := <-messages:\n\t\t\tif service := findServiceByContainerID(services, message.ID); service != nil {\n\t\t\t\tservice.State = `healthy`\n\t\t\t}\n\n\t\t\thealthyContainers[message.ID] = true\n\t\t\tif len(healthyContainers) == len(containersIdsWithHealthcheck) {\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase err := <-errors:\n\t\t\trollbar.LogError(`[%s] [%s] Error while reading healthy events: %v`, user.Username, appName, err)\n\t\t\treturn false\n\t\t}\n\t}\n}\n\nfunc (a *App) finishDeploy(ctx context.Context, user *model.User, appName string, services map[string]*deployedService, oldContainers []types.Container, requestParams url.Values) {\n\tspan := opentracing.SpanFromContext(ctx)\n\tspan.SetTag(`app`, appName)\n\tspan.SetTag(`services_count`, len(services))\n\tdefer func() {\n\t\tdefer a.tasks.Delete(appName)\n\t\tdefer span.Finish()\n\t}()\n\n\tsuccess := a.areContainersHealthy(ctx, user, appName, services)\n\ta.captureServicesOutput(ctx, user, appName, services)\n\n\tif success {\n\t\tif err := a.cleanContainers(ctx, oldContainers); err != nil {\n\t\t\trollbar.LogError(`[%s] [%s] Error while cleaning old containers: %v`, user.Username, appName, err)\n\t\t}\n\n\t\tif err := a.renameDeployedContainers(ctx, services); err != nil {\n\t\t\trollbar.LogError(`[%s] [%s] Error while renaming deployed containers: %v`, user.Username, appName, err)\n\t\t}\n\t} else {\n\t\trollbar.LogWarning(`[%s] [%s] Failed to deploy: %v`, user.Username, appName, errHealthCheckFailed)\n\t\ta.deleteServices(ctx, appName, services, user)\n\t}\n\n\tif !success {\n\t\tfor _, service := range services {\n\t\t\tlog.Printf(\"[%s] [%s] Logs output for %s: \\n%s\\n\", user.Username, appName, service.Name, strings.Join(service.Logs, \"\\n\"))\n\t\t\tlog.Printf(\"[%s] [%s] Health output for %s: \\n%s\\n\", user.Username, appName, service.Name, strings.Join(service.HealthLogs, \"\\n\"))\n\t\t}\n\t}\n\n\tif err := a.sendEmailNotification(ctx, user, appName, services, success); err != nil {\n\t\trollbar.LogError(`[%s] [%s] Error while sending email notification: %s`, user.Username, appName, err)\n\t}\n\n\tif err := a.sendRollbarNotification(ctx, user, requestParams); err != nil {\n\t\trollbar.LogError(`[%s] [%s] Error while sending rollbar notification: %s`, user.Username, appName, err)\n\t}\n}\n\nfunc (a *App) createContainer(ctx context.Context, user *model.User, appName string, serviceName string, service *dockerComposeService) (*deployedService, error) {\n\timagePulled := false\n\n\tif a.tag != `` {\n\t\timageOverride := fmt.Sprintf(`%s%s%s`, service.Image, colonSeparator, a.tag)\n\t\tif err := a.pullImage(ctx, imageOverride); err == nil {\n\t\t\tservice.Image = imageOverride\n\t\t\timagePulled = true\n\t\t}\n\t}\n\n\tif !imagePulled {\n\t\tif err := a.pullImage(ctx, service.Image); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tserviceFullName := getServiceFullName(appName, serviceName)\n\n\tconfig, err := a.getConfig(service, user, appName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(`Error while getting config: %v`, err)\n\t}\n\n\tcreatedContainer, err := a.dockerApp.Docker.ContainerCreate(ctx, config, a.getHostConfig(service, user), a.getNetworkConfig(serviceName, service), serviceFullName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(`Error while creating service %s: %v`, serviceName, err)\n\t}\n\n\treturn &deployedService{\n\t\tName:        serviceName,\n\t\tFullName:    serviceFullName,\n\t\tContainerID: createdContainer.ID,\n\t\tImageName:   service.Image,\n\t}, nil\n}\n\nfunc (a *App) parseCompose(ctx context.Context, user *model.User, appName string, composeFile []byte) (map[string]*deployedService, error) {\n\tcomposeFile = bytes.Replace(composeFile, []byte(`$$`), []byte(`$`), -1)\n\n\tcompose := dockerCompose{}\n\tif err := yaml.Unmarshal(composeFile, &compose); err != nil {\n\t\treturn nil, fmt.Errorf(`[%s] [%s] Error while unmarshalling compose file: %v`, user.Username, appName, err)\n\t}\n\n\tnewServices := make(map[string]*deployedService)\n\tfor serviceName, service := range compose.Services {\n\t\tif deployedService, err := a.createContainer(ctx, user, appName, serviceName, &service); err != nil {\n\t\t\tbreak\n\t\t} else {\n\t\t\tnewServices[serviceName] = deployedService\n\t\t}\n\t}\n\n\treturn newServices, nil\n}\n\nfunc composeFailed(w http.ResponseWriter, user *model.User, appName string, err error) {\n\thttperror.InternalServerError(w, fmt.Errorf(`[%s] [%s] Failed to deploy: %v`, user.Username, appName, err))\n}\n\nfunc (a *App) composeHandler(w http.ResponseWriter, r *http.Request, user *model.User) {\n\tif r.Method != http.MethodPost {\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tappName, composeFile, err := checkParams(r, user)\n\tif err != nil {\n\t\thttperror.BadRequest(w, err)\n\t\treturn\n\t}\n\n\tctx := r.Context()\n\n\toldContainers, err := a.checkRights(ctx, user, appName)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusForbidden)\n\t\treturn\n\t}\n\n\tnewServices, err := a.parseCompose(ctx, user, appName, composeFile)\n\tif err != nil {\n\t\tcomposeFailed(w, user, appName, err)\n\t\treturn\n\t}\n\n\tif err = a.checkTasks(user, appName); err != nil {\n\t\tcomposeFailed(w, user, appName, err)\n\t\treturn\n\t}\n\n\tif err == nil {\n\t\terr = a.startServices(ctx, newServices)\n\t}\n\n\tctx = context.Background()\n\tparentSpanContext := opentracing.SpanFromContext(r.Context()).Context()\n\t_, ctx = opentracing.StartSpanFromContext(ctx, `Deploy`, opentracing.FollowsFrom(parentSpanContext))\n\n\tgo a.finishDeploy(ctx, user, appName, newServices, oldContainers, r.URL.Query())\n\n\tif err != nil {\n\t\tcomposeFailed(w, user, appName, err)\n\t\treturn\n\t}\n\n\tif err := httpjson.ResponseArrayJSON(w, http.StatusOK, newServices, httpjson.IsPretty(r.URL.RawQuery)); err != nil {\n\t\thttperror.InternalServerError(w, err)\n\t}\n}\n\n\/\/ Handler for request. Should be use with net\/http\nfunc (a *App) Handler() http.Handler {\n\treturn a.authApp.Handler(a.composeHandler)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package quick implements utility functions to help with black box testing.\npackage quick\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"reflect\"\n\t\"strings\"\n)\n\nvar defaultMaxCount *int = flag.Int(\"quickchecks\", 100, \"The default number of iterations for each check\")\n\n\/\/ A Generator can generate random values of its own type.\ntype Generator interface {\n\t\/\/ Generate returns a random instance of the type on which it is a\n\t\/\/ method using the size as a size hint.\n\tGenerate(rand *rand.Rand, size int) reflect.Value\n}\n\n\/\/ randFloat32 generates a random float taking the full range of a float32.\nfunc randFloat32(rand *rand.Rand) float32 {\n\tf := rand.Float64() * math.MaxFloat32\n\tif rand.Int()&1 == 1 {\n\t\tf = -f\n\t}\n\treturn float32(f)\n}\n\n\/\/ randFloat64 generates a random float taking the full range of a float64.\nfunc randFloat64(rand *rand.Rand) float64 {\n\tf := rand.Float64() * math.MaxFloat64\n\tif rand.Int()&1 == 1 {\n\t\tf = -f\n\t}\n\treturn f\n}\n\n\/\/ randInt64 returns a random integer taking half the range of an int64.\nfunc randInt64(rand *rand.Rand) int64 { return rand.Int63() - 1<<62 }\n\n\/\/ complexSize is the maximum length of arbitrary values that contain other\n\/\/ values.\nconst complexSize = 50\n\n\/\/ Value returns an arbitrary value of the given type.\n\/\/ If the type implements the Generator interface, that will be used.\n\/\/ Note: To create arbitrary values for structs, all the fields must be exported.\nfunc Value(t reflect.Type, rand *rand.Rand) (value reflect.Value, ok bool) {\n\tif m, ok := reflect.Zero(t).Interface().(Generator); ok {\n\t\treturn m.Generate(rand, complexSize), true\n\t}\n\n\tv := reflect.New(t).Elem()\n\tswitch concrete := t; concrete.Kind() {\n\tcase reflect.Bool:\n\t\tv.SetBool(rand.Int()&1 == 0)\n\tcase reflect.Float32:\n\t\tv.SetFloat(float64(randFloat32(rand)))\n\tcase reflect.Float64:\n\t\tv.SetFloat(randFloat64(rand))\n\tcase reflect.Complex64:\n\t\tv.SetComplex(complex(float64(randFloat32(rand)), float64(randFloat32(rand))))\n\tcase reflect.Complex128:\n\t\tv.SetComplex(complex(randFloat64(rand), randFloat64(rand)))\n\tcase reflect.Int16:\n\t\tv.SetInt(randInt64(rand))\n\tcase reflect.Int32:\n\t\tv.SetInt(randInt64(rand))\n\tcase reflect.Int64:\n\t\tv.SetInt(randInt64(rand))\n\tcase reflect.Int8:\n\t\tv.SetInt(randInt64(rand))\n\tcase reflect.Int:\n\t\tv.SetInt(randInt64(rand))\n\tcase reflect.Uint16:\n\t\tv.SetUint(uint64(randInt64(rand)))\n\tcase reflect.Uint32:\n\t\tv.SetUint(uint64(randInt64(rand)))\n\tcase reflect.Uint64:\n\t\tv.SetUint(uint64(randInt64(rand)))\n\tcase reflect.Uint8:\n\t\tv.SetUint(uint64(randInt64(rand)))\n\tcase reflect.Uint:\n\t\tv.SetUint(uint64(randInt64(rand)))\n\tcase reflect.Uintptr:\n\t\tv.SetUint(uint64(randInt64(rand)))\n\tcase reflect.Map:\n\t\tnumElems := rand.Intn(complexSize)\n\t\tv.Set(reflect.MakeMap(concrete))\n\t\tfor i := 0; i < numElems; i++ {\n\t\t\tkey, ok1 := Value(concrete.Key(), rand)\n\t\t\tvalue, ok2 := Value(concrete.Elem(), rand)\n\t\t\tif !ok1 || !ok2 {\n\t\t\t\treturn reflect.Value{}, false\n\t\t\t}\n\t\t\tv.SetMapIndex(key, value)\n\t\t}\n\tcase reflect.Ptr:\n\t\telem, ok := Value(concrete.Elem(), rand)\n\t\tif !ok {\n\t\t\treturn reflect.Value{}, false\n\t\t}\n\t\tv.Set(reflect.New(concrete.Elem()))\n\t\tv.Elem().Set(elem)\n\tcase reflect.Slice:\n\t\tnumElems := rand.Intn(complexSize)\n\t\tv.Set(reflect.MakeSlice(concrete, numElems, numElems))\n\t\tfor i := 0; i < numElems; i++ {\n\t\t\telem, ok := Value(concrete.Elem(), rand)\n\t\t\tif !ok {\n\t\t\t\treturn reflect.Value{}, false\n\t\t\t}\n\t\t\tv.Index(i).Set(elem)\n\t\t}\n\tcase reflect.String:\n\t\tnumChars := rand.Intn(complexSize)\n\t\tcodePoints := make([]rune, numChars)\n\t\tfor i := 0; i < numChars; i++ {\n\t\t\tcodePoints[i] = rune(rand.Intn(0x10ffff))\n\t\t}\n\t\tv.SetString(string(codePoints))\n\tcase reflect.Struct:\n\t\tfor i := 0; i < v.NumField(); i++ {\n\t\t\telem, ok := Value(concrete.Field(i).Type, rand)\n\t\t\tif !ok {\n\t\t\t\treturn reflect.Value{}, false\n\t\t\t}\n\t\t\tv.Field(i).Set(elem)\n\t\t}\n\tdefault:\n\t\treturn reflect.Value{}, false\n\t}\n\n\treturn v, true\n}\n\n\/\/ A Config structure contains options for running a test.\ntype Config struct {\n\t\/\/ MaxCount sets the maximum number of iterations. If zero,\n\t\/\/ MaxCountScale is used.\n\tMaxCount int\n\t\/\/ MaxCountScale is a non-negative scale factor applied to the default\n\t\/\/ maximum. If zero, the default is unchanged.\n\tMaxCountScale float64\n\t\/\/ If non-nil, rand is a source of random numbers. Otherwise a default\n\t\/\/ pseudo-random source will be used.\n\tRand *rand.Rand\n\t\/\/ If non-nil, the Values function generates a slice of arbitrary\n\t\/\/ reflect.Values that are congruent with the arguments to the function\n\t\/\/ being tested. Otherwise, the top-level Values function is used\n\t\/\/ to generate them.\n\tValues func([]reflect.Value, *rand.Rand)\n}\n\nvar defaultConfig Config\n\n\/\/ getRand returns the *rand.Rand to use for a given Config.\nfunc (c *Config) getRand() *rand.Rand {\n\tif c.Rand == nil {\n\t\treturn rand.New(rand.NewSource(0))\n\t}\n\treturn c.Rand\n}\n\n\/\/ getMaxCount returns the maximum number of iterations to run for a given\n\/\/ Config.\nfunc (c *Config) getMaxCount() (maxCount int) {\n\tmaxCount = c.MaxCount\n\tif maxCount == 0 {\n\t\tif c.MaxCountScale != 0 {\n\t\t\tmaxCount = int(c.MaxCountScale * float64(*defaultMaxCount))\n\t\t} else {\n\t\t\tmaxCount = *defaultMaxCount\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ A SetupError is the result of an error in the way that check is being\n\/\/ used, independent of the functions being tested.\ntype SetupError string\n\nfunc (s SetupError) Error() string { return string(s) }\n\n\/\/ A CheckError is the result of Check finding an error.\ntype CheckError struct {\n\tCount int\n\tIn    []interface{}\n}\n\nfunc (s *CheckError) Error() string {\n\treturn fmt.Sprintf(\"#%d: failed on input %s\", s.Count, toString(s.In))\n}\n\n\/\/ A CheckEqualError is the result CheckEqual finding an error.\ntype CheckEqualError struct {\n\tCheckError\n\tOut1 []interface{}\n\tOut2 []interface{}\n}\n\nfunc (s *CheckEqualError) Error() string {\n\treturn fmt.Sprintf(\"#%d: failed on input %s. Output 1: %s. Output 2: %s\", s.Count, toString(s.In), toString(s.Out1), toString(s.Out2))\n}\n\n\/\/ Check looks for an input to f, any function that returns bool,\n\/\/ such that f returns false.  It calls f repeatedly, with arbitrary\n\/\/ values for each argument.  If f returns false on a given input,\n\/\/ Check returns that input as a *CheckError.\n\/\/ For example:\n\/\/\n\/\/ \tfunc TestOddMultipleOfThree(t *testing.T) {\n\/\/ \t\tf := func(x int) bool {\n\/\/ \t\t\ty := OddMultipleOfThree(x)\n\/\/ \t\t\treturn y%2 == 1 && y%3 == 0\n\/\/ \t\t}\n\/\/ \t\tif err := quick.Check(f, nil); err != nil {\n\/\/ \t\t\tt.Error(err)\n\/\/ \t\t}\n\/\/ \t}\nfunc Check(function interface{}, config *Config) (err error) {\n\tif config == nil {\n\t\tconfig = &defaultConfig\n\t}\n\n\tf, fType, ok := functionAndType(function)\n\tif !ok {\n\t\terr = SetupError(\"argument is not a function\")\n\t\treturn\n\t}\n\n\tif fType.NumOut() != 1 {\n\t\terr = SetupError(\"function returns more than one value.\")\n\t\treturn\n\t}\n\tif fType.Out(0).Kind() != reflect.Bool {\n\t\terr = SetupError(\"function does not return a bool\")\n\t\treturn\n\t}\n\n\targuments := make([]reflect.Value, fType.NumIn())\n\trand := config.getRand()\n\tmaxCount := config.getMaxCount()\n\n\tfor i := 0; i < maxCount; i++ {\n\t\terr = arbitraryValues(arguments, fType, config, rand)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !f.Call(arguments)[0].Bool() {\n\t\t\terr = &CheckError{i + 1, toInterfaces(arguments)}\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ CheckEqual looks for an input on which f and g return different results.\n\/\/ It calls f and g repeatedly with arbitrary values for each argument.\n\/\/ If f and g return different answers, CheckEqual returns a *CheckEqualError\n\/\/ describing the input and the outputs.\nfunc CheckEqual(f, g interface{}, config *Config) (err error) {\n\tif config == nil {\n\t\tconfig = &defaultConfig\n\t}\n\n\tx, xType, ok := functionAndType(f)\n\tif !ok {\n\t\terr = SetupError(\"f is not a function\")\n\t\treturn\n\t}\n\ty, yType, ok := functionAndType(g)\n\tif !ok {\n\t\terr = SetupError(\"g is not a function\")\n\t\treturn\n\t}\n\n\tif xType != yType {\n\t\terr = SetupError(\"functions have different types\")\n\t\treturn\n\t}\n\n\targuments := make([]reflect.Value, xType.NumIn())\n\trand := config.getRand()\n\tmaxCount := config.getMaxCount()\n\n\tfor i := 0; i < maxCount; i++ {\n\t\terr = arbitraryValues(arguments, xType, config, rand)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\txOut := toInterfaces(x.Call(arguments))\n\t\tyOut := toInterfaces(y.Call(arguments))\n\n\t\tif !reflect.DeepEqual(xOut, yOut) {\n\t\t\terr = &CheckEqualError{CheckError{i + 1, toInterfaces(arguments)}, xOut, yOut}\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ arbitraryValues writes Values to args such that args contains Values\n\/\/ suitable for calling f.\nfunc arbitraryValues(args []reflect.Value, f reflect.Type, config *Config, rand *rand.Rand) (err error) {\n\tif config.Values != nil {\n\t\tconfig.Values(args, rand)\n\t\treturn\n\t}\n\n\tfor j := 0; j < len(args); j++ {\n\t\tvar ok bool\n\t\targs[j], ok = Value(f.In(j), rand)\n\t\tif !ok {\n\t\t\terr = SetupError(fmt.Sprintf(\"cannot create arbitrary value of type %s for argument %d\", f.In(j), j))\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc functionAndType(f interface{}) (v reflect.Value, t reflect.Type, ok bool) {\n\tv = reflect.ValueOf(f)\n\tok = v.Kind() == reflect.Func\n\tif !ok {\n\t\treturn\n\t}\n\tt = v.Type()\n\treturn\n}\n\nfunc toInterfaces(values []reflect.Value) []interface{} {\n\tret := make([]interface{}, len(values))\n\tfor i, v := range values {\n\t\tret[i] = v.Interface()\n\t}\n\treturn ret\n}\n\nfunc toString(interfaces []interface{}) string {\n\ts := make([]string, len(interfaces))\n\tfor i, v := range interfaces {\n\t\ts[i] = fmt.Sprintf(\"%#v\", v)\n\t}\n\treturn strings.Join(s, \", \")\n}\n<commit_msg>testing\/quick: brought Check parameter name in line with function doc<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package quick implements utility functions to help with black box testing.\npackage quick\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"reflect\"\n\t\"strings\"\n)\n\nvar defaultMaxCount *int = flag.Int(\"quickchecks\", 100, \"The default number of iterations for each check\")\n\n\/\/ A Generator can generate random values of its own type.\ntype Generator interface {\n\t\/\/ Generate returns a random instance of the type on which it is a\n\t\/\/ method using the size as a size hint.\n\tGenerate(rand *rand.Rand, size int) reflect.Value\n}\n\n\/\/ randFloat32 generates a random float taking the full range of a float32.\nfunc randFloat32(rand *rand.Rand) float32 {\n\tf := rand.Float64() * math.MaxFloat32\n\tif rand.Int()&1 == 1 {\n\t\tf = -f\n\t}\n\treturn float32(f)\n}\n\n\/\/ randFloat64 generates a random float taking the full range of a float64.\nfunc randFloat64(rand *rand.Rand) float64 {\n\tf := rand.Float64() * math.MaxFloat64\n\tif rand.Int()&1 == 1 {\n\t\tf = -f\n\t}\n\treturn f\n}\n\n\/\/ randInt64 returns a random integer taking half the range of an int64.\nfunc randInt64(rand *rand.Rand) int64 { return rand.Int63() - 1<<62 }\n\n\/\/ complexSize is the maximum length of arbitrary values that contain other\n\/\/ values.\nconst complexSize = 50\n\n\/\/ Value returns an arbitrary value of the given type.\n\/\/ If the type implements the Generator interface, that will be used.\n\/\/ Note: To create arbitrary values for structs, all the fields must be exported.\nfunc Value(t reflect.Type, rand *rand.Rand) (value reflect.Value, ok bool) {\n\tif m, ok := reflect.Zero(t).Interface().(Generator); ok {\n\t\treturn m.Generate(rand, complexSize), true\n\t}\n\n\tv := reflect.New(t).Elem()\n\tswitch concrete := t; concrete.Kind() {\n\tcase reflect.Bool:\n\t\tv.SetBool(rand.Int()&1 == 0)\n\tcase reflect.Float32:\n\t\tv.SetFloat(float64(randFloat32(rand)))\n\tcase reflect.Float64:\n\t\tv.SetFloat(randFloat64(rand))\n\tcase reflect.Complex64:\n\t\tv.SetComplex(complex(float64(randFloat32(rand)), float64(randFloat32(rand))))\n\tcase reflect.Complex128:\n\t\tv.SetComplex(complex(randFloat64(rand), randFloat64(rand)))\n\tcase reflect.Int16:\n\t\tv.SetInt(randInt64(rand))\n\tcase reflect.Int32:\n\t\tv.SetInt(randInt64(rand))\n\tcase reflect.Int64:\n\t\tv.SetInt(randInt64(rand))\n\tcase reflect.Int8:\n\t\tv.SetInt(randInt64(rand))\n\tcase reflect.Int:\n\t\tv.SetInt(randInt64(rand))\n\tcase reflect.Uint16:\n\t\tv.SetUint(uint64(randInt64(rand)))\n\tcase reflect.Uint32:\n\t\tv.SetUint(uint64(randInt64(rand)))\n\tcase reflect.Uint64:\n\t\tv.SetUint(uint64(randInt64(rand)))\n\tcase reflect.Uint8:\n\t\tv.SetUint(uint64(randInt64(rand)))\n\tcase reflect.Uint:\n\t\tv.SetUint(uint64(randInt64(rand)))\n\tcase reflect.Uintptr:\n\t\tv.SetUint(uint64(randInt64(rand)))\n\tcase reflect.Map:\n\t\tnumElems := rand.Intn(complexSize)\n\t\tv.Set(reflect.MakeMap(concrete))\n\t\tfor i := 0; i < numElems; i++ {\n\t\t\tkey, ok1 := Value(concrete.Key(), rand)\n\t\t\tvalue, ok2 := Value(concrete.Elem(), rand)\n\t\t\tif !ok1 || !ok2 {\n\t\t\t\treturn reflect.Value{}, false\n\t\t\t}\n\t\t\tv.SetMapIndex(key, value)\n\t\t}\n\tcase reflect.Ptr:\n\t\telem, ok := Value(concrete.Elem(), rand)\n\t\tif !ok {\n\t\t\treturn reflect.Value{}, false\n\t\t}\n\t\tv.Set(reflect.New(concrete.Elem()))\n\t\tv.Elem().Set(elem)\n\tcase reflect.Slice:\n\t\tnumElems := rand.Intn(complexSize)\n\t\tv.Set(reflect.MakeSlice(concrete, numElems, numElems))\n\t\tfor i := 0; i < numElems; i++ {\n\t\t\telem, ok := Value(concrete.Elem(), rand)\n\t\t\tif !ok {\n\t\t\t\treturn reflect.Value{}, false\n\t\t\t}\n\t\t\tv.Index(i).Set(elem)\n\t\t}\n\tcase reflect.String:\n\t\tnumChars := rand.Intn(complexSize)\n\t\tcodePoints := make([]rune, numChars)\n\t\tfor i := 0; i < numChars; i++ {\n\t\t\tcodePoints[i] = rune(rand.Intn(0x10ffff))\n\t\t}\n\t\tv.SetString(string(codePoints))\n\tcase reflect.Struct:\n\t\tfor i := 0; i < v.NumField(); i++ {\n\t\t\telem, ok := Value(concrete.Field(i).Type, rand)\n\t\t\tif !ok {\n\t\t\t\treturn reflect.Value{}, false\n\t\t\t}\n\t\t\tv.Field(i).Set(elem)\n\t\t}\n\tdefault:\n\t\treturn reflect.Value{}, false\n\t}\n\n\treturn v, true\n}\n\n\/\/ A Config structure contains options for running a test.\ntype Config struct {\n\t\/\/ MaxCount sets the maximum number of iterations. If zero,\n\t\/\/ MaxCountScale is used.\n\tMaxCount int\n\t\/\/ MaxCountScale is a non-negative scale factor applied to the default\n\t\/\/ maximum. If zero, the default is unchanged.\n\tMaxCountScale float64\n\t\/\/ If non-nil, rand is a source of random numbers. Otherwise a default\n\t\/\/ pseudo-random source will be used.\n\tRand *rand.Rand\n\t\/\/ If non-nil, the Values function generates a slice of arbitrary\n\t\/\/ reflect.Values that are congruent with the arguments to the function\n\t\/\/ being tested. Otherwise, the top-level Values function is used\n\t\/\/ to generate them.\n\tValues func([]reflect.Value, *rand.Rand)\n}\n\nvar defaultConfig Config\n\n\/\/ getRand returns the *rand.Rand to use for a given Config.\nfunc (c *Config) getRand() *rand.Rand {\n\tif c.Rand == nil {\n\t\treturn rand.New(rand.NewSource(0))\n\t}\n\treturn c.Rand\n}\n\n\/\/ getMaxCount returns the maximum number of iterations to run for a given\n\/\/ Config.\nfunc (c *Config) getMaxCount() (maxCount int) {\n\tmaxCount = c.MaxCount\n\tif maxCount == 0 {\n\t\tif c.MaxCountScale != 0 {\n\t\t\tmaxCount = int(c.MaxCountScale * float64(*defaultMaxCount))\n\t\t} else {\n\t\t\tmaxCount = *defaultMaxCount\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ A SetupError is the result of an error in the way that check is being\n\/\/ used, independent of the functions being tested.\ntype SetupError string\n\nfunc (s SetupError) Error() string { return string(s) }\n\n\/\/ A CheckError is the result of Check finding an error.\ntype CheckError struct {\n\tCount int\n\tIn    []interface{}\n}\n\nfunc (s *CheckError) Error() string {\n\treturn fmt.Sprintf(\"#%d: failed on input %s\", s.Count, toString(s.In))\n}\n\n\/\/ A CheckEqualError is the result CheckEqual finding an error.\ntype CheckEqualError struct {\n\tCheckError\n\tOut1 []interface{}\n\tOut2 []interface{}\n}\n\nfunc (s *CheckEqualError) Error() string {\n\treturn fmt.Sprintf(\"#%d: failed on input %s. Output 1: %s. Output 2: %s\", s.Count, toString(s.In), toString(s.Out1), toString(s.Out2))\n}\n\n\/\/ Check looks for an input to f, any function that returns bool,\n\/\/ such that f returns false.  It calls f repeatedly, with arbitrary\n\/\/ values for each argument.  If f returns false on a given input,\n\/\/ Check returns that input as a *CheckError.\n\/\/ For example:\n\/\/\n\/\/ \tfunc TestOddMultipleOfThree(t *testing.T) {\n\/\/ \t\tf := func(x int) bool {\n\/\/ \t\t\ty := OddMultipleOfThree(x)\n\/\/ \t\t\treturn y%2 == 1 && y%3 == 0\n\/\/ \t\t}\n\/\/ \t\tif err := quick.Check(f, nil); err != nil {\n\/\/ \t\t\tt.Error(err)\n\/\/ \t\t}\n\/\/ \t}\nfunc Check(f interface{}, config *Config) (err error) {\n\tif config == nil {\n\t\tconfig = &defaultConfig\n\t}\n\n\tfVal, fType, ok := functionAndType(f)\n\tif !ok {\n\t\terr = SetupError(\"argument is not a function\")\n\t\treturn\n\t}\n\n\tif fType.NumOut() != 1 {\n\t\terr = SetupError(\"function returns more than one value.\")\n\t\treturn\n\t}\n\tif fType.Out(0).Kind() != reflect.Bool {\n\t\terr = SetupError(\"function does not return a bool\")\n\t\treturn\n\t}\n\n\targuments := make([]reflect.Value, fType.NumIn())\n\trand := config.getRand()\n\tmaxCount := config.getMaxCount()\n\n\tfor i := 0; i < maxCount; i++ {\n\t\terr = arbitraryValues(arguments, fType, config, rand)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !fVal.Call(arguments)[0].Bool() {\n\t\t\terr = &CheckError{i + 1, toInterfaces(arguments)}\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ CheckEqual looks for an input on which f and g return different results.\n\/\/ It calls f and g repeatedly with arbitrary values for each argument.\n\/\/ If f and g return different answers, CheckEqual returns a *CheckEqualError\n\/\/ describing the input and the outputs.\nfunc CheckEqual(f, g interface{}, config *Config) (err error) {\n\tif config == nil {\n\t\tconfig = &defaultConfig\n\t}\n\n\tx, xType, ok := functionAndType(f)\n\tif !ok {\n\t\terr = SetupError(\"f is not a function\")\n\t\treturn\n\t}\n\ty, yType, ok := functionAndType(g)\n\tif !ok {\n\t\terr = SetupError(\"g is not a function\")\n\t\treturn\n\t}\n\n\tif xType != yType {\n\t\terr = SetupError(\"functions have different types\")\n\t\treturn\n\t}\n\n\targuments := make([]reflect.Value, xType.NumIn())\n\trand := config.getRand()\n\tmaxCount := config.getMaxCount()\n\n\tfor i := 0; i < maxCount; i++ {\n\t\terr = arbitraryValues(arguments, xType, config, rand)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\txOut := toInterfaces(x.Call(arguments))\n\t\tyOut := toInterfaces(y.Call(arguments))\n\n\t\tif !reflect.DeepEqual(xOut, yOut) {\n\t\t\terr = &CheckEqualError{CheckError{i + 1, toInterfaces(arguments)}, xOut, yOut}\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ arbitraryValues writes Values to args such that args contains Values\n\/\/ suitable for calling f.\nfunc arbitraryValues(args []reflect.Value, f reflect.Type, config *Config, rand *rand.Rand) (err error) {\n\tif config.Values != nil {\n\t\tconfig.Values(args, rand)\n\t\treturn\n\t}\n\n\tfor j := 0; j < len(args); j++ {\n\t\tvar ok bool\n\t\targs[j], ok = Value(f.In(j), rand)\n\t\tif !ok {\n\t\t\terr = SetupError(fmt.Sprintf(\"cannot create arbitrary value of type %s for argument %d\", f.In(j), j))\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc functionAndType(f interface{}) (v reflect.Value, t reflect.Type, ok bool) {\n\tv = reflect.ValueOf(f)\n\tok = v.Kind() == reflect.Func\n\tif !ok {\n\t\treturn\n\t}\n\tt = v.Type()\n\treturn\n}\n\nfunc toInterfaces(values []reflect.Value) []interface{} {\n\tret := make([]interface{}, len(values))\n\tfor i, v := range values {\n\t\tret[i] = v.Interface()\n\t}\n\treturn ret\n}\n\nfunc toString(interfaces []interface{}) string {\n\ts := make([]string, len(interfaces))\n\tfor i, v := range interfaces {\n\t\ts[i] = fmt.Sprintf(\"%#v\", v)\n\t}\n\treturn strings.Join(s, \", \")\n}\n<|endoftext|>"}
{"text":"<commit_before>package envoy\n\nimport (\n\t\"fmt\"\n\t\"kourier\/pkg\/config\"\n\t\"os\"\n\n\t\"github.com\/envoyproxy\/go-control-plane\/pkg\/conversion\"\n\t\"github.com\/envoyproxy\/go-control-plane\/pkg\/wellknown\"\n\n\tv2 \"github.com\/envoyproxy\/go-control-plane\/envoy\/api\/v2\"\n\tauth \"github.com\/envoyproxy\/go-control-plane\/envoy\/api\/v2\/auth\"\n\tcore \"github.com\/envoyproxy\/go-control-plane\/envoy\/api\/v2\/core\"\n\tlistener \"github.com\/envoyproxy\/go-control-plane\/envoy\/api\/v2\/listener\"\n\thttpconnmanagerv2 \"github.com\/envoyproxy\/go-control-plane\/envoy\/config\/filter\/network\/http_connection_manager\/v2\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\tkubeclient \"k8s.io\/client-go\/kubernetes\"\n)\n\nconst (\n\tenvCertsSecretNamespace = \"CERTS_SECRET_NAMESPACE\"\n\tenvCertsSecretName      = \"CERTS_SECRET_NAME\"\n\tcertFieldInSecret       = \"tls.crt\"\n\tkeyFieldInSecret        = \"tls.key\"\n)\n\nfunc newExternalEnvoyListener(https bool,\n\tmanager *httpconnmanagerv2.HttpConnectionManager,\n\tkubeClient kubeclient.Interface) (*v2.Listener, error) {\n\n\tif https {\n\t\treturn envoyHTTPSListener(manager, kubeClient, config.HttpsPortExternal)\n\t} else {\n\t\treturn envoyHTTPListener(manager, config.HttpPortExternal)\n\t}\n}\n\nfunc newInternalEnvoyListener(manager *httpconnmanagerv2.HttpConnectionManager) (*v2.Listener, error) {\n\treturn envoyHTTPListener(manager, config.HttpPortInternal)\n}\n\nfunc envoyHTTPListener(manager *httpconnmanagerv2.HttpConnectionManager, port uint32) (*v2.Listener, error) {\n\tfilters, err := createFilters(manager)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvoyListener := &v2.Listener{\n\t\tName:    fmt.Sprintf(\"listener_%d\", port),\n\t\tAddress: createAddress(port),\n\t\tFilterChains: []*listener.FilterChain{\n\t\t\t{\n\t\t\t\tFilters: filters,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn envoyListener, nil\n}\n\nfunc envoyHTTPSListener(manager *httpconnmanagerv2.HttpConnectionManager,\n\tkubeClient kubeclient.Interface,\n\tport uint32) (*v2.Listener, error) {\n\n\tsecret, err := kubeClient.CoreV1().Secrets(os.Getenv(envCertsSecretNamespace)).Get(\n\t\tos.Getenv(envCertsSecretName), metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcertificateChain := string(secret.Data[certFieldInSecret])\n\tprivateKey := string(secret.Data[keyFieldInSecret])\n\n\tfilters, err := createFilters(manager)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvoyListener := v2.Listener{\n\t\tName:    fmt.Sprintf(\"listener_%d\", port),\n\t\tAddress: createAddress(port),\n\t\tFilterChains: []*listener.FilterChain{\n\t\t\t{\n\t\t\t\tTlsContext: createTLSContext(certificateChain, privateKey),\n\t\t\t\tFilters:    filters,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn &envoyListener, nil\n}\n\nfunc createAddress(port uint32) *core.Address {\n\treturn &core.Address{\n\t\tAddress: &core.Address_SocketAddress{\n\t\t\tSocketAddress: &core.SocketAddress{\n\t\t\t\tProtocol: core.SocketAddress_TCP,\n\t\t\t\tAddress:  \"0.0.0.0\",\n\t\t\t\tPortSpecifier: &core.SocketAddress_PortValue{\n\t\t\t\t\tPortValue: port,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc createFilters(manager *httpconnmanagerv2.HttpConnectionManager) ([]*listener.Filter, error) {\n\tpbst, err := conversion.MessageToStruct(manager)\n\tif err != nil {\n\t\treturn []*listener.Filter{}, err\n\t}\n\n\tfilters := []*listener.Filter{\n\t\t{\n\t\t\tName:       wellknown.HTTPConnectionManager,\n\t\t\tConfigType: &listener.Filter_Config{Config: pbst},\n\t\t},\n\t}\n\n\treturn filters, nil\n}\n\nfunc createTLSContext(certificate string, privateKey string) *auth.DownstreamTlsContext {\n\treturn &auth.DownstreamTlsContext{\n\t\tCommonTlsContext: &auth.CommonTlsContext{\n\t\t\tTlsCertificates: []*auth.TlsCertificate{\n\t\t\t\t{\n\t\t\t\t\tCertificateChain: &core.DataSource{\n\t\t\t\t\t\tSpecifier: &core.DataSource_InlineBytes{InlineBytes: []byte(certificate)},\n\t\t\t\t\t},\n\t\t\t\t\tPrivateKey: &core.DataSource{\n\t\t\t\t\t\tSpecifier: &core.DataSource_InlineBytes{InlineBytes: []byte(privateKey)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n<commit_msg>Use typedConfig for httpManager to avoid deprecation message<commit_after>package envoy\n\nimport (\n\t\"fmt\"\n\t\"kourier\/pkg\/config\"\n\t\"os\"\n\n\t\"github.com\/golang\/protobuf\/ptypes\"\n\n\t\"github.com\/envoyproxy\/go-control-plane\/pkg\/wellknown\"\n\n\tv2 \"github.com\/envoyproxy\/go-control-plane\/envoy\/api\/v2\"\n\tauth \"github.com\/envoyproxy\/go-control-plane\/envoy\/api\/v2\/auth\"\n\tcore \"github.com\/envoyproxy\/go-control-plane\/envoy\/api\/v2\/core\"\n\tlistener \"github.com\/envoyproxy\/go-control-plane\/envoy\/api\/v2\/listener\"\n\thttpconnmanagerv2 \"github.com\/envoyproxy\/go-control-plane\/envoy\/config\/filter\/network\/http_connection_manager\/v2\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\tkubeclient \"k8s.io\/client-go\/kubernetes\"\n)\n\nconst (\n\tenvCertsSecretNamespace = \"CERTS_SECRET_NAMESPACE\"\n\tenvCertsSecretName      = \"CERTS_SECRET_NAME\"\n\tcertFieldInSecret       = \"tls.crt\"\n\tkeyFieldInSecret        = \"tls.key\"\n)\n\nfunc newExternalEnvoyListener(https bool,\n\tmanager *httpconnmanagerv2.HttpConnectionManager,\n\tkubeClient kubeclient.Interface) (*v2.Listener, error) {\n\n\tif https {\n\t\treturn envoyHTTPSListener(manager, kubeClient, config.HttpsPortExternal)\n\t} else {\n\t\treturn envoyHTTPListener(manager, config.HttpPortExternal)\n\t}\n}\n\nfunc newInternalEnvoyListener(manager *httpconnmanagerv2.HttpConnectionManager) (*v2.Listener, error) {\n\treturn envoyHTTPListener(manager, config.HttpPortInternal)\n}\n\nfunc envoyHTTPListener(manager *httpconnmanagerv2.HttpConnectionManager, port uint32) (*v2.Listener, error) {\n\tfilters, err := createFilters(manager)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvoyListener := &v2.Listener{\n\t\tName:    fmt.Sprintf(\"listener_%d\", port),\n\t\tAddress: createAddress(port),\n\t\tFilterChains: []*listener.FilterChain{\n\t\t\t{\n\t\t\t\tFilters: filters,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn envoyListener, nil\n}\n\nfunc envoyHTTPSListener(manager *httpconnmanagerv2.HttpConnectionManager,\n\tkubeClient kubeclient.Interface,\n\tport uint32) (*v2.Listener, error) {\n\n\tsecret, err := kubeClient.CoreV1().Secrets(os.Getenv(envCertsSecretNamespace)).Get(\n\t\tos.Getenv(envCertsSecretName), metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcertificateChain := string(secret.Data[certFieldInSecret])\n\tprivateKey := string(secret.Data[keyFieldInSecret])\n\n\tfilters, err := createFilters(manager)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvoyListener := v2.Listener{\n\t\tName:    fmt.Sprintf(\"listener_%d\", port),\n\t\tAddress: createAddress(port),\n\t\tFilterChains: []*listener.FilterChain{\n\t\t\t{\n\t\t\t\tTlsContext: createTLSContext(certificateChain, privateKey),\n\t\t\t\tFilters:    filters,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn &envoyListener, nil\n}\n\nfunc createAddress(port uint32) *core.Address {\n\treturn &core.Address{\n\t\tAddress: &core.Address_SocketAddress{\n\t\t\tSocketAddress: &core.SocketAddress{\n\t\t\t\tProtocol: core.SocketAddress_TCP,\n\t\t\t\tAddress:  \"0.0.0.0\",\n\t\t\t\tPortSpecifier: &core.SocketAddress_PortValue{\n\t\t\t\t\tPortValue: port,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc createFilters(manager *httpconnmanagerv2.HttpConnectionManager) ([]*listener.Filter, error) {\n\tmanagerAny, err := ptypes.MarshalAny(manager)\n\tif err != nil {\n\t\treturn []*listener.Filter{}, err\n\t}\n\n\tfilters := []*listener.Filter{\n\t\t{\n\t\t\tName:       wellknown.HTTPConnectionManager,\n\t\t\tConfigType: &listener.Filter_TypedConfig{TypedConfig: managerAny},\n\t\t},\n\t}\n\n\treturn filters, nil\n}\n\nfunc createTLSContext(certificate string, privateKey string) *auth.DownstreamTlsContext {\n\treturn &auth.DownstreamTlsContext{\n\t\tCommonTlsContext: &auth.CommonTlsContext{\n\t\t\tTlsCertificates: []*auth.TlsCertificate{\n\t\t\t\t{\n\t\t\t\t\tCertificateChain: &core.DataSource{\n\t\t\t\t\t\tSpecifier: &core.DataSource_InlineBytes{InlineBytes: []byte(certificate)},\n\t\t\t\t\t},\n\t\t\t\t\tPrivateKey: &core.DataSource{\n\t\t\t\t\t\tSpecifier: &core.DataSource_InlineBytes{InlineBytes: []byte(privateKey)},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package executor\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\/\/ Local provisioning is responsible for providing the execution environment\n\/\/ on local machine via exec.Command.\n\/\/ It runs command as current user.\ntype Local struct {\n}\n\n\/\/ NewLocal returns a Local instance.\nfunc NewLocal() Local {\n\treturn Local{}\n}\n\n\/\/ Execute runs the command given as input.\n\/\/ Returned Task is able to stop & monitor the provisioned process.\nfunc (l Local) Execute(command string) (Task, error) {\n\tlog.Debug(\"Starting \", command)\n\n\tcmd := exec.Command(\"sh\", \"-c\", command)\n\n\t\/\/ It is important to set additional Process Group ID for parent process and his children\n\t\/\/ to have ability to kill all the children processes.\n\tcmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}\n\n\t\/\/ Setting Buffer as io.Writer for Command output.\n\t\/\/ TODO: Write to temporary files instead of keeping in memory.\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Debug(\"Started with PID \", cmd.Process.Pid)\n\n\t\/\/ Wait Err channel is for gethering error potential error messages from cmd.Wait function.\n\twaitErrChannel := make(chan error, 1)\n\t\/\/ Wait End channel is for checking the status of the Wait. If this channel is closed,\n\t\/\/ it means that the wait is completed (either with error or not)\n\t\/\/ This channel will not be used for passing any message.\n\twaitEndChannel := make(chan struct{})\n\n\t\/\/ Wait for local task in goroutine.\n\tgo func() {\n\t\t\/\/ Wait for task completion.\n\t\t\/\/ NOTE: Wait() returns an error. We grab the process state in any case\n\t\t\/\/ (success or failure) below, so the error object matters less in the\n\t\t\/\/ status handling for now.\n\t\tif err := cmd.Wait(); err != nil {\n\t\t\tif _, ok := err.(*exec.ExitError); !ok {\n\t\t\t\t\/\/ In case of NON Exit Errors we are not sure if task does\n\t\t\t\t\/\/ terminate so return error.\n\t\t\t\tlog.Error(\"Waiting for task failed. \", err)\n\t\t\t\twaitErrChannel <- err\n\n\t\t\t\tclose(waitErrChannel)\n\t\t\t\tclose(waitEndChannel)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tlog.Debug(\n\t\t\t\"Ended \", strings.Join(cmd.Args, \" \"),\n\t\t\t\" with output in file: \", stdout.String(),\n\t\t\t\" with err output in file: \", stderr.String(),\n\t\t\t\" with status code: \",\n\t\t\t(cmd.ProcessState.Sys().(syscall.WaitStatus)).ExitStatus())\n\n\t\twaitErrChannel <- nil\n\n\t\tclose(waitErrChannel)\n\t\tclose(waitEndChannel)\n\t}()\n\n\treturn newlocalTask(cmd, &stdout, &stderr, waitErrChannel, waitEndChannel), nil\n}\n\nconst killTimeout = 5 * time.Second\n\n\/\/ localTask implements Task interface.\ntype localTask struct {\n\twaitMutex      sync.Mutex\n\tcmdHandler     *exec.Cmd\n\tstdout         *bytes.Buffer\n\tstderr         *bytes.Buffer\n\twaitErrChannel chan error\n\twaitEndChannel chan struct{}\n\tkillTimeout    time.Duration\n}\n\n\/\/ newlocalTask returns a localTask instance.\nfunc newlocalTask(cmdHandler *exec.Cmd, stdout *bytes.Buffer,\n\tstderr *bytes.Buffer, waitErrChannel chan error, waitEndChannel chan struct{}) *localTask {\n\tt := &localTask{\n\t\tcmdHandler:     cmdHandler,\n\t\tstdout:         stdout,\n\t\tstderr:         stderr,\n\t\twaitErrChannel: waitErrChannel,\n\t\twaitEndChannel: waitEndChannel,\n\t\tkillTimeout:    killTimeout,\n\t}\n\treturn t\n}\n\n\/\/ isTerminated checks if waitEndChannel is closed. If it is closed, it means\n\/\/ that wait ends, task is in terminated state and ProcessState is not nil.\n\/\/ ProcessState contains information about an exited process,\n\/\/ available after call to Wait or Run.\nfunc (task *localTask) isTerminated() bool {\n\tselect {\n\tcase <-task.waitEndChannel:\n\t\t\/\/ If waitEndChannel is closed then task is terminated.\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc (task *localTask) getPid() int {\n\treturn task.cmdHandler.Process.Pid\n}\n\nfunc (task *localTask) createStatus() *Status {\n\tif !task.isTerminated() {\n\t\treturn nil\n\t}\n\n\treturn &Status{\n\t\t(task.cmdHandler.ProcessState.Sys().(syscall.WaitStatus)).ExitStatus(),\n\t\ttask.stdout.String(),\n\t\ttask.stderr.String(),\n\t}\n}\n\nfunc (task *localTask) killTask(sig syscall.Signal) error {\n\t\/\/ We signal the entire process group.\n\t\/\/ The kill syscall interprets a negated PID N as the process group N belongs to.\n\tlog.Debug(\"Sending \", sig, \" to PID \", -task.getPid())\n\treturn syscall.Kill(-task.getPid(), sig)\n}\n\n\/\/ Stop terminates the local task.\nfunc (task *localTask) Stop() error {\n\tif task.isTerminated() {\n\t\treturn nil\n\t}\n\n\t\/\/ Sending SIGKILL signal to local task.\n\t\/\/ TODO: Add PID namespace to handle orphan tasks properly.\n\terr := task.killTask(syscall.SIGKILL)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\n\t\/\/ Checking if kill was succesful.\n\tisTerminated, taskErr := task.Wait(killTimeout)\n\tif taskErr != nil {\n\t\tlog.Error(taskErr.Error())\n\t\treturn taskErr\n\t}\n\n\tif !isTerminated {\n\t\treturn errors.New(\"Cannot kill -9 task\")\n\t}\n\n\t\/\/ No error, task terminated.\n\treturn nil\n}\n\n\/\/ Status returns a state of the task. If task is terminated it returns the Status as a\n\/\/ second item in tuple. Otherwise returns nil.\nfunc (task *localTask) Status() (TaskState, *Status) {\n\tif !task.isTerminated() {\n\t\treturn RUNNING, nil\n\t}\n\n\treturn TERMINATED, task.createStatus()\n}\n\n\/\/ Wait waits for the command to finish with the given timeout time.\n\/\/ In case of timeout == 0 there is no timeout for that.\n\/\/ It returns true if task is terminated.\nfunc (task *localTask) Wait(timeout time.Duration) (bool, error) {\n\tif task.isTerminated() {\n\t\treturn true, nil\n\t}\n\n\tvar timeoutChannel <-chan time.Time\n\tif timeout != 0 {\n\t\t\/\/ In case of wait with timeout set the timeout channel.\n\t\ttimeoutChannel = time.After(timeout)\n\t}\n\n\tselect {\n\tcase err, ok := <-task.waitErrChannel:\n\t\tif err != nil && ok {\n\t\t\t\/\/ If channel is not closed and there is error return false and error.\n\t\t\treturn false, err\n\t\t}\n\n\t\t\/\/ If channel is closed or there is no error return true and nil.\n\t\treturn true, nil\n\tcase <-timeoutChannel:\n\t\t\/\/ If timeout time exceeded return false and nil.\n\t\treturn false, nil\n\t}\n}\n<commit_msg>Issues addressed.<commit_after>package executor\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\/\/ Local provisioning is responsible for providing the execution environment\n\/\/ on local machine via exec.Command.\n\/\/ It runs command as current user.\ntype Local struct {\n}\n\n\/\/ NewLocal returns a Local instance.\nfunc NewLocal() Local {\n\treturn Local{}\n}\n\n\/\/ Execute runs the command given as input.\n\/\/ Returned Task is able to stop & monitor the provisioned process.\nfunc (l Local) Execute(command string) (Task, error) {\n\tlog.Debug(\"Starting \", command)\n\n\tcmd := exec.Command(\"sh\", \"-c\", command)\n\n\t\/\/ It is important to set additional Process Group ID for parent process and his children\n\t\/\/ to have ability to kill all the children processes.\n\tcmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}\n\n\t\/\/ Setting Buffer as io.Writer for Command output.\n\t\/\/ TODO: Write to temporary files instead of keeping in memory.\n\tvar stdout bytes.Buffer\n\tvar stderr bytes.Buffer\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Debug(\"Started with PID \", cmd.Process.Pid)\n\n\t\/\/ Wait Err channel is for gethering error potential error messages from cmd.Wait function.\n\twaitErrChannel := make(chan error, 1)\n\t\/\/ Wait End channel is for checking the status of the Wait. If this channel is closed,\n\t\/\/ it means that the wait is completed (either with error or not)\n\t\/\/ This channel will not be used for passing any message.\n\twaitEndChannel := make(chan struct{})\n\n\t\/\/ Wait for local task in goroutine.\n\tgo func() {\n\t\tdefer close(waitErrChannel)\n\t\tdefer close(waitEndChannel)\n\n\t\t\/\/ Wait for task completion.\n\t\t\/\/ NOTE: Wait() returns an error. We grab the process state in any case\n\t\t\/\/ (success or failure) below, so the error object matters less in the\n\t\t\/\/ status handling for now.\n\t\tif err := cmd.Wait(); err != nil {\n\t\t\tif _, ok := err.(*exec.ExitError); !ok {\n\t\t\t\t\/\/ In case of NON Exit Errors we are not sure if task does\n\t\t\t\t\/\/ terminate so return error.\n\t\t\t\tlog.Error(\"Waiting for task failed. \", err)\n\t\t\t\twaitErrChannel <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tlog.Debug(\n\t\t\t\"Ended \", strings.Join(cmd.Args, \" \"),\n\t\t\t\" with output in file: \", stdout.String(),\n\t\t\t\" with err output in file: \", stderr.String(),\n\t\t\t\" with status code: \",\n\t\t\t(cmd.ProcessState.Sys().(syscall.WaitStatus)).ExitStatus())\n\t}()\n\n\treturn newlocalTask(cmd, &stdout, &stderr, waitErrChannel, waitEndChannel), nil\n}\n\nconst killTimeout = 5 * time.Second\n\n\/\/ localTask implements Task interface.\ntype localTask struct {\n\twaitMutex      sync.Mutex\n\tcmdHandler     *exec.Cmd\n\tstdout         *bytes.Buffer\n\tstderr         *bytes.Buffer\n\twaitErrChannel chan error\n\twaitEndChannel chan struct{}\n\tkillTimeout    time.Duration\n}\n\n\/\/ newlocalTask returns a localTask instance.\nfunc newlocalTask(cmdHandler *exec.Cmd, stdout *bytes.Buffer,\n\tstderr *bytes.Buffer, waitErrChannel chan error, waitEndChannel chan struct{}) *localTask {\n\tt := &localTask{\n\t\tcmdHandler:     cmdHandler,\n\t\tstdout:         stdout,\n\t\tstderr:         stderr,\n\t\twaitErrChannel: waitErrChannel,\n\t\twaitEndChannel: waitEndChannel,\n\t\tkillTimeout:    killTimeout,\n\t}\n\treturn t\n}\n\n\/\/ isTerminated checks if waitEndChannel is closed. If it is closed, it means\n\/\/ that wait ended and task is in terminated state.\n\/\/ NOTE: If it's true then ProcessState is not nil. ProcessState contains information\n\/\/ about an exited process available after call to Wait or Run.\nfunc (task *localTask) isTerminated() bool {\n\tselect {\n\tcase <-task.waitEndChannel:\n\t\t\/\/ If waitEndChannel is closed then task is terminated.\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc (task *localTask) getPid() int {\n\treturn task.cmdHandler.Process.Pid\n}\n\nfunc (task *localTask) createStatus() *Status {\n\tif !task.isTerminated() {\n\t\treturn nil\n\t}\n\n\treturn &Status{\n\t\t(task.cmdHandler.ProcessState.Sys().(syscall.WaitStatus)).ExitStatus(),\n\t\ttask.stdout.String(),\n\t\ttask.stderr.String(),\n\t}\n}\n\nfunc (task *localTask) killTask(sig syscall.Signal) error {\n\t\/\/ We signal the entire process group.\n\t\/\/ The kill syscall interprets a negated PID N as the process group N belongs to.\n\tlog.Debug(\"Sending \", sig, \" to PID \", -task.getPid())\n\treturn syscall.Kill(-task.getPid(), sig)\n}\n\n\/\/ Stop terminates the local task.\nfunc (task *localTask) Stop() error {\n\tif task.isTerminated() {\n\t\treturn nil\n\t}\n\n\t\/\/ Sending SIGKILL signal to local task.\n\t\/\/ TODO: Add PID namespace to handle orphan tasks properly.\n\terr := task.killTask(syscall.SIGKILL)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\n\t\/\/ Checking if kill was succesful.\n\tisTerminated, taskErr := task.Wait(killTimeout)\n\tif taskErr != nil {\n\t\tlog.Error(taskErr.Error())\n\t\treturn taskErr\n\t}\n\n\tif !isTerminated {\n\t\treturn errors.New(\"Cannot kill -9 task\")\n\t}\n\n\t\/\/ No error, task terminated.\n\treturn nil\n}\n\n\/\/ Status returns a state of the task. If task is terminated it returns the Status as a\n\/\/ second item in tuple. Otherwise returns nil.\nfunc (task *localTask) Status() (TaskState, *Status) {\n\tif !task.isTerminated() {\n\t\treturn RUNNING, nil\n\t}\n\n\treturn TERMINATED, task.createStatus()\n}\n\n\/\/ Wait waits for the command to finish with the given timeout time.\n\/\/ In case of timeout == 0 there is no timeout for that.\n\/\/ It returns true if task is terminated.\nfunc (task *localTask) Wait(timeout time.Duration) (bool, error) {\n\tif task.isTerminated() {\n\t\treturn true, nil\n\t}\n\n\tvar timeoutChannel <-chan time.Time\n\tif timeout != 0 {\n\t\t\/\/ In case of wait with timeout set the timeout channel.\n\t\ttimeoutChannel = time.After(timeout)\n\t}\n\n\tselect {\n\tcase err, ok := <-task.waitErrChannel:\n\t\tif err != nil && ok {\n\t\t\t\/\/ If channel is not closed and there is error return false and error.\n\t\t\treturn false, err\n\t\t}\n\n\t\t\/\/ If channel is closed or there is no error return true and nil.\n\t\treturn true, nil\n\tcase <-timeoutChannel:\n\t\t\/\/ If timeout time exceeded return false and nil.\n\t\treturn false, nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2021 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage notes\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"k8s.io\/release\/pkg\/notes\/options\"\n\n\t\"github.com\/cheggaaa\/pb\/v3\"\n\t\"github.com\/go-git\/go-git\/v5\"\n\t\"github.com\/go-git\/go-git\/v5\/plumbing\"\n\tgitobject \"github.com\/go-git\/go-git\/v5\/plumbing\/object\"\n\t\"github.com\/nozzle\/throttler\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\ntype commitPrPair struct {\n\tCommit *gitobject.Commit\n\tPrNum  int\n}\n\ntype releaseNotesAggregator struct {\n\treleaseNotes *ReleaseNotes\n\tsync.RWMutex\n}\n\nfunc (g *Gatherer) ListReleaseNotesV2() (*ReleaseNotes, error) {\n\t\/\/ left parent of Git commits is always the main branch parent\n\tpairs, err := g.listLeftParentCommits(g.options)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"listing offline commits\")\n\t}\n\n\t\/\/ load map providers specified in options\n\tmapProviders := []MapProvider{}\n\tfor _, initString := range g.options.MapProviderStrings {\n\t\tprovider, err := NewProviderFromInitString(initString)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"while getting release notes map providers\")\n\t\t}\n\t\tmapProviders = append(mapProviders, provider)\n\t}\n\n\tt := throttler.New(maxParallelRequests, len(pairs))\n\n\taggregator := releaseNotesAggregator{\n\t\treleaseNotes: NewReleaseNotes(),\n\t}\n\n\tpairsCount := len(pairs)\n\tlogrus.Infof(\"processing release notes for %d commits\", pairsCount)\n\tbar := pb.Full.Start(pairsCount)\n\n\tfor _, pair := range pairs {\n\t\tnoteMaps := []*ReleaseNotesMap{}\n\n\t\tfor _, provider := range mapProviders {\n\t\t\tnoteMaps, err = provider.GetMapsForPR(pair.PrNum)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Errorf(\"[ignored] pr: %d err: %v\", pair.PrNum, err)\n\t\t\t\tnoteMaps = []*ReleaseNotesMap{}\n\t\t\t}\n\t\t}\n\n\t\tgo func() {\n\t\t\treleaseNote, err := g.buildReleaseNote(pair)\n\t\t\tif err == nil && releaseNote != nil {\n\t\t\t\tfor _, noteMap := range noteMaps {\n\t\t\t\t\tif err := releaseNote.ApplyMap(noteMap); err != nil {\n\t\t\t\t\t\tlogrus.Errorf(\"[ignored] pr: %d err: %v\", pair.PrNum, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\taggregator.Lock()\n\t\t\t\taggregator.releaseNotes.Set(pair.PrNum, releaseNote)\n\t\t\t\taggregator.Unlock()\n\t\t\t} else if err != nil {\n\t\t\t\tlogrus.Errorf(\"sha: %s pr: %d err: %v\", pair.Commit.Hash.String(), pair.PrNum, err)\n\t\t\t}\n\t\t\tbar.Increment()\n\t\t\tt.Done(nil)\n\t\t}()\n\n\t\tif t.Throttle() > 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif err := t.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tbar.Finish()\n\n\treturn aggregator.releaseNotes, nil\n}\n\nfunc (g *Gatherer) buildReleaseNote(pair *commitPrPair) (*ReleaseNote, error) {\n\tpr, _, err := g.client.GetPullRequest(g.context, g.options.GithubOrg, g.options.GithubRepo, pair.PrNum)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprBody := pr.GetBody()\n\n\ttext, err := noteTextFromString(prBody)\n\tif err != nil {\n\t\tlogrus.Debugf(\"sha: %s pr: %d err: %v\", pair.Commit.Hash.String(), pair.PrNum, err)\n\t\treturn nil, nil\n\t}\n\n\tdocumentation := DocumentationFromString(prBody)\n\n\tauthor := pr.GetUser().GetLogin()\n\tauthorURL := pr.GetUser().GetHTMLURL()\n\tprURL := pr.GetHTMLURL()\n\tisFeature := hasString(labelsWithPrefix(pr, \"kind\"), \"feature\")\n\tnoteSuffix := prettifySIGList(labelsWithPrefix(pr, \"sig\"))\n\n\tisDuplicateSIG := false\n\tif len(labelsWithPrefix(pr, \"sig\")) > 1 {\n\t\tisDuplicateSIG = true\n\t}\n\n\tisDuplicateKind := false\n\tif len(labelsWithPrefix(pr, \"kind\")) > 1 {\n\t\tisDuplicateKind = true\n\t}\n\n\t\/\/ TODO(wilsonehusin): extract \/ follow original in ReleasenoteFromCommit\n\tindented := strings.ReplaceAll(text, \"\\n\", \"\\n  \")\n\tmarkdown := fmt.Sprintf(\"%s ([#%d](%s), [@%s](%s))\",\n\t\tindented, pr.GetNumber(), prURL, author, authorURL)\n\n\tif noteSuffix != \"\" {\n\t\tmarkdown = fmt.Sprintf(\"%s [%s]\", markdown, noteSuffix)\n\t}\n\n\t\/\/ Uppercase the first character of the markdown to make it look uniform\n\tmarkdown = strings.ToUpper(string(markdown[0])) + markdown[1:]\n\n\treturn &ReleaseNote{\n\t\tCommit:         pair.Commit.Hash.String(),\n\t\tText:           text,\n\t\tMarkdown:       markdown,\n\t\tDocumentation:  documentation,\n\t\tAuthor:         author,\n\t\tAuthorURL:      authorURL,\n\t\tPrURL:          prURL,\n\t\tPrNumber:       pr.GetNumber(),\n\t\tSIGs:           labelsWithPrefix(pr, \"sig\"),\n\t\tKinds:          labelsWithPrefix(pr, \"kind\"),\n\t\tAreas:          labelsWithPrefix(pr, \"area\"),\n\t\tFeature:        isFeature,\n\t\tDuplicate:      isDuplicateSIG,\n\t\tDuplicateKind:  isDuplicateKind,\n\t\tActionRequired: labelExactMatch(pr, \"release-note-action-required\"),\n\t\tDoNotPublish:   labelExactMatch(pr, \"release-note-none\"),\n\t}, nil\n}\n\nfunc (g *Gatherer) listLeftParentCommits(opts *options.Options) ([]*commitPrPair, error) {\n\tlocalRepository, err := git.PlainOpen(opts.RepoPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ opts.StartSHA points to a tag (e.g. 1.20.0) which is on a release branch (e.g. release-1.20)\n\t\/\/ this means traveling through commit history from opts.EndSHA will never reach opts.StartSHA\n\n\t\/\/ the stopping point to be set should be the last shared commit between release branch and primary (master) branch\n\t\/\/ usually, following the left \/ first parents, it would be\n\t\/\/ * tag: v1.20.0, some merge commit\n\t\/\/ |\n\t\/\/ * Anago GCB release commit (begin branch out of release-1.20)\n\t\/\/ |\n\t\/\/ * last shared commit\n\n\t\/\/ this means the stopping point is 2 commits behind the tag pointed by opts.StartSHA\n\n\tstopHash := plumbing.NewHash(opts.StartSHA)\n\tfor i := 0; i < 2; i++ {\n\t\tcommitObject, err := localRepository.CommitObject(stopHash)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"finding last shared commit\")\n\t\t}\n\t\tstopHash = commitObject.ParentHashes[0]\n\t}\n\n\tlogrus.Infof(\"will stop at %s\", stopHash)\n\n\tcurrentTagHash := plumbing.NewHash(opts.EndSHA)\n\n\tpairs := []*commitPrPair{}\n\thashPointer := currentTagHash\n\tfor hashPointer != stopHash {\n\t\thashString := hashPointer.String()\n\n\t\t\/\/ Find and collect commit objects\n\t\tcommitPointer, err := localRepository.CommitObject(hashPointer)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"finding CommitObject\")\n\t\t}\n\n\t\t\/\/ Find and collect PR number from commit message\n\t\tprNums, err := prsNumForCommitFromMessage(commitPointer.Message)\n\t\tif err == errNoPRIDFoundInCommitMessage {\n\t\t\tlogrus.Debugf(\"sha: %s prs: []\", hashString)\n\n\t\t\t\/\/ Advance pointer based on left parent\n\t\t\thashPointer = commitPointer.ParentHashes[0]\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\tlogrus.Warnf(\"sha: %s err: %s (silenced)\", hashString, err.Error())\n\n\t\t\t\/\/ Advance pointer based on left parent\n\t\t\thashPointer = commitPointer.ParentHashes[0]\n\t\t\tcontinue\n\t\t}\n\t\tlogrus.Debugf(\"sha: %s prs: %v\", hashString, prNums)\n\n\t\t\/\/ Only taking the first one, assuming they are merged by Prow\n\t\tpairs = append(pairs, &commitPrPair{Commit: commitPointer, PrNum: prNums[0]})\n\n\t\t\/\/ Advance pointer based on left parent\n\t\thashPointer = commitPointer.ParentHashes[0]\n\t}\n\n\treturn pairs, nil\n}\n<commit_msg>Apply MatchesExcludeFilter on PR (v1 parity)<commit_after>\/*\nCopyright 2021 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage notes\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"k8s.io\/release\/pkg\/notes\/options\"\n\n\t\"github.com\/cheggaaa\/pb\/v3\"\n\t\"github.com\/go-git\/go-git\/v5\"\n\t\"github.com\/go-git\/go-git\/v5\/plumbing\"\n\tgitobject \"github.com\/go-git\/go-git\/v5\/plumbing\/object\"\n\t\"github.com\/nozzle\/throttler\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\ntype commitPrPair struct {\n\tCommit *gitobject.Commit\n\tPrNum  int\n}\n\ntype releaseNotesAggregator struct {\n\treleaseNotes *ReleaseNotes\n\tsync.RWMutex\n}\n\nfunc (g *Gatherer) ListReleaseNotesV2() (*ReleaseNotes, error) {\n\t\/\/ left parent of Git commits is always the main branch parent\n\tpairs, err := g.listLeftParentCommits(g.options)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"listing offline commits\")\n\t}\n\n\t\/\/ load map providers specified in options\n\tmapProviders := []MapProvider{}\n\tfor _, initString := range g.options.MapProviderStrings {\n\t\tprovider, err := NewProviderFromInitString(initString)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"while getting release notes map providers\")\n\t\t}\n\t\tmapProviders = append(mapProviders, provider)\n\t}\n\n\tt := throttler.New(maxParallelRequests, len(pairs))\n\n\taggregator := releaseNotesAggregator{\n\t\treleaseNotes: NewReleaseNotes(),\n\t}\n\n\tpairsCount := len(pairs)\n\tlogrus.Infof(\"processing release notes for %d commits\", pairsCount)\n\tbar := pb.New(pairsCount).SetWriter(os.Stdout).Start()\n\n\tfor _, pair := range pairs {\n\t\tgo func(pair *commitPrPair) {\n\t\t\tnoteMaps := []*ReleaseNotesMap{}\n\t\t\tfor _, provider := range mapProviders {\n\t\t\t\tnoteMaps, err = provider.GetMapsForPR(pair.PrNum)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\t\t\"pr\": pair.PrNum,\n\t\t\t\t\t}).Errorf(\"ignore err: %v\", err)\n\t\t\t\t\tnoteMaps = []*ReleaseNotesMap{}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treleaseNote, err := g.buildReleaseNote(pair)\n\t\t\tif err == nil {\n\t\t\t\tif releaseNote != nil {\n\t\t\t\t\tfor _, noteMap := range noteMaps {\n\t\t\t\t\t\tif err := releaseNote.ApplyMap(noteMap); err != nil {\n\t\t\t\t\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\t\t\t\t\"pr\": pair.PrNum,\n\t\t\t\t\t\t\t}).Errorf(\"ignore err: %v\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\t\t\"pr\":   pair.PrNum,\n\t\t\t\t\t\t\"note\": releaseNote.Text,\n\t\t\t\t\t}).Debugf(\"finalized release note\")\n\t\t\t\t\taggregator.Lock()\n\t\t\t\t\taggregator.releaseNotes.Set(pair.PrNum, releaseNote)\n\t\t\t\t\taggregator.Unlock()\n\t\t\t\t} else {\n\t\t\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\t\t\"pr\": pair.PrNum,\n\t\t\t\t\t}).Debugf(\"skip: empty release note\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\t\"sha\": pair.Commit.Hash.String(),\n\t\t\t\t\t\"pr\":  pair.PrNum,\n\t\t\t\t}).Errorf(\"err: %v\", err)\n\t\t\t}\n\t\t\tbar.Increment()\n\t\t\tt.Done(nil)\n\t\t}(pair)\n\n\t\tif t.Throttle() > 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif err := t.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tbar.Finish()\n\n\treturn aggregator.releaseNotes, nil\n}\n\nfunc (g *Gatherer) buildReleaseNote(pair *commitPrPair) (*ReleaseNote, error) {\n\tpr, _, err := g.client.GetPullRequest(g.context, g.options.GithubOrg, g.options.GithubRepo, pair.PrNum)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tprBody := pr.GetBody()\n\n\tif MatchesExcludeFilter(prBody) {\n\t\treturn nil, nil\n\t}\n\n\ttext, err := noteTextFromString(prBody)\n\tif err != nil {\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"sha\": pair.Commit.Hash.String(),\n\t\t\t\"pr\":  pair.PrNum,\n\t\t}).Debugf(\"ignore err: %v\", err)\n\t\treturn nil, nil\n\t}\n\n\tdocumentation := DocumentationFromString(prBody)\n\n\tauthor := pr.GetUser().GetLogin()\n\tauthorURL := pr.GetUser().GetHTMLURL()\n\tprURL := pr.GetHTMLURL()\n\tisFeature := hasString(labelsWithPrefix(pr, \"kind\"), \"feature\")\n\tnoteSuffix := prettifySIGList(labelsWithPrefix(pr, \"sig\"))\n\n\tisDuplicateSIG := false\n\tif len(labelsWithPrefix(pr, \"sig\")) > 1 {\n\t\tisDuplicateSIG = true\n\t}\n\n\tisDuplicateKind := false\n\tif len(labelsWithPrefix(pr, \"kind\")) > 1 {\n\t\tisDuplicateKind = true\n\t}\n\n\t\/\/ TODO(wilsonehusin): extract \/ follow original in ReleasenoteFromCommit\n\tindented := strings.ReplaceAll(text, \"\\n\", \"\\n  \")\n\tmarkdown := fmt.Sprintf(\"%s ([#%d](%s), [@%s](%s))\",\n\t\tindented, pr.GetNumber(), prURL, author, authorURL)\n\n\tif noteSuffix != \"\" {\n\t\tmarkdown = fmt.Sprintf(\"%s [%s]\", markdown, noteSuffix)\n\t}\n\n\t\/\/ Uppercase the first character of the markdown to make it look uniform\n\tmarkdown = strings.ToUpper(string(markdown[0])) + markdown[1:]\n\n\treturn &ReleaseNote{\n\t\tCommit:         pair.Commit.Hash.String(),\n\t\tText:           text,\n\t\tMarkdown:       markdown,\n\t\tDocumentation:  documentation,\n\t\tAuthor:         author,\n\t\tAuthorURL:      authorURL,\n\t\tPrURL:          prURL,\n\t\tPrNumber:       pr.GetNumber(),\n\t\tSIGs:           labelsWithPrefix(pr, \"sig\"),\n\t\tKinds:          labelsWithPrefix(pr, \"kind\"),\n\t\tAreas:          labelsWithPrefix(pr, \"area\"),\n\t\tFeature:        isFeature,\n\t\tDuplicate:      isDuplicateSIG,\n\t\tDuplicateKind:  isDuplicateKind,\n\t\tActionRequired: labelExactMatch(pr, \"release-note-action-required\"),\n\t\tDoNotPublish:   labelExactMatch(pr, \"release-note-none\"),\n\t}, nil\n}\n\nfunc (g *Gatherer) listLeftParentCommits(opts *options.Options) ([]*commitPrPair, error) {\n\tlocalRepository, err := git.PlainOpen(opts.RepoPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ opts.StartSHA points to a tag (e.g. 1.20.0) which is on a release branch (e.g. release-1.20)\n\t\/\/ this means traveling through commit history from opts.EndSHA will never reach opts.StartSHA\n\n\t\/\/ the stopping point to be set should be the last shared commit between release branch and primary (master) branch\n\t\/\/ usually, following the left \/ first parents, it would be\n\t\/\/ * tag: v1.20.0, some merge commit\n\t\/\/ |\n\t\/\/ * Anago GCB release commit (begin branch out of release-1.20)\n\t\/\/ |\n\t\/\/ * last shared commit\n\n\t\/\/ this means the stopping point is 2 commits behind the tag pointed by opts.StartSHA\n\n\tstopHash := plumbing.NewHash(opts.StartSHA)\n\tfor i := 0; i < 2; i++ {\n\t\tcommitObject, err := localRepository.CommitObject(stopHash)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"finding last shared commit\")\n\t\t}\n\t\tstopHash = commitObject.ParentHashes[0]\n\t}\n\n\tlogrus.Infof(\"will stop at %s\", stopHash)\n\n\tcurrentTagHash := plumbing.NewHash(opts.EndSHA)\n\n\tpairs := []*commitPrPair{}\n\thashPointer := currentTagHash\n\tfor hashPointer != stopHash {\n\t\thashString := hashPointer.String()\n\n\t\t\/\/ Find and collect commit objects\n\t\tcommitPointer, err := localRepository.CommitObject(hashPointer)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"finding CommitObject\")\n\t\t}\n\n\t\t\/\/ Find and collect PR number from commit message\n\t\tprNums, err := prsNumForCommitFromMessage(commitPointer.Message)\n\t\tif err == errNoPRIDFoundInCommitMessage {\n\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\"sha\": hashString,\n\t\t\t}).Debug(\"no associated PR found\")\n\n\t\t\t\/\/ Advance pointer based on left parent\n\t\t\thashPointer = commitPointer.ParentHashes[0]\n\t\t\tcontinue\n\t\t}\n\t\tif err != nil {\n\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\"sha\": hashString,\n\t\t\t}).Warnf(\"ignore err: %v\", err)\n\n\t\t\t\/\/ Advance pointer based on left parent\n\t\t\thashPointer = commitPointer.ParentHashes[0]\n\t\t\tcontinue\n\t\t}\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"sha\": hashString,\n\t\t\t\"prs\": prNums,\n\t\t}).Debug(\"found PR from commit\")\n\n\t\t\/\/ Only taking the first one, assuming they are merged by Prow\n\t\tpairs = append(pairs, &commitPrPair{Commit: commitPointer, PrNum: prNums[0]})\n\n\t\t\/\/ Advance pointer based on left parent\n\t\thashPointer = commitPointer.ParentHashes[0]\n\t}\n\n\treturn pairs, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/emembrives\/dispotrains\/dispotrains.webapp\/src\/storage\"\n\n\t\"github.com\/eknkc\/dateformat\"\n\t\"github.com\/gorilla\/mux\"\n\tmgo \"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\nconst (\n\tmongoDbHost = \"localhost\"\n)\n\nvar (\n\tsession = createSessionOrDie()\n)\n\ntype Line struct {\n\tNetwork      string\n\tID           string\n\tGoodStations []*storage.Station\n\tBadStations  []*storage.Station\n\tLastUpdate   time.Time\n}\n\ntype LineSlice []Line\n\ntype DisplayStation struct {\n\tName         string\n\tDisplayName  string\n\tCity         string\n\tPosition     storage.Coordinates\n\tOsmID        string\n\tElevators    []*LocElevator\n\tLastUpdate   time.Time\n\tBadElevators int\n}\n\ntype LocElevator storage.Elevator\n\ntype dataStatus struct {\n\tElevator   string\n\tState      string\n\tLastupdate time.Time\n}\n\nfunc (e *LocElevator) LocalStatusDate() string {\n\treturn dateformat.FormatLocale(e.Status.LastUpdate, \"ddd D MMM à HH:MM\", dateformat.French)\n}\n\nfunc createSessionOrDie() *mgo.Session {\n\tsession, err := mgo.Dial(mongoDbHost)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn session\n}\n\n\/\/ VoronoiHandler sends historical data for the Voronoi map.\nfunc VoronoiHandler(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Add(\"Access-Control-Allow-Methods\", \"GET\")\n\tw.Header().Add(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\tcStatistics := session.DB(\"dispotrains\").C(\"statistics\")\n\n\tvar stats []bson.M = make([]bson.M, 0)\n\tif err := cStatistics.Find(nil).All(&stats); err != nil {\n\t\tlog.Println(err)\n\t}\n\tvar jsonData []bson.M = make([]bson.M, 0)\n\tfor _, stat := range stats {\n\t\tdelete(stat, \"_id\")\n\t\tjsonData = append(jsonData, stat)\n\t}\n\tif err := json.NewEncoder(w).Encode(&jsonData); err != nil {\n\t\tlog.Println(err)\n\t}\n}\n\nfunc GetLinesHandler(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Add(\"Access-Control-Allow-Methods\", \"GET\")\n\tw.Header().Add(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\tw.Header().Set(\"Cache-control\", \"public, max-age=86400\")\n\n\tc := session.DB(\"dispotrains\").C(\"lines\")\n\tvar lines = make(LineSlice, 0)\n\tif err := c.Find(nil).Sort(\"network\", \"id\").All(&lines); err != nil {\n\t\tlog.Println(err)\n\t}\n\tjson.NewEncoder(w).Encode(&lines)\n}\n\nfunc GetStationsHandler(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Add(\"Access-Control-Allow-Methods\", \"GET\")\n\tw.Header().Add(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\tc := session.DB(\"dispotrains\").C(\"stations\")\n\tvar stations []bson.M\n\tif err := c.Find(nil).All(&stations); err != nil {\n\t\tlog.Println(err)\n\t}\n\tvar jsonStations []bson.M\n\tfor _, station := range stations {\n\t\tdelete(station, \"_id\")\n\t\tjsonStations = append(jsonStations, station)\n\t}\n\tjson.NewEncoder(w).Encode(&jsonStations)\n}\n\nfunc CacheRequest(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Cache-control\", \"public, max-age=259200\")\n\t\th.ServeHTTP(w, r)\n\t})\n}\n\nfunc main() {\n\tdefer session.Close()\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"\/app\/GetLines\/\", GetLinesHandler)\n\tr.HandleFunc(\"\/app\/GetStations\/\", GetStationsHandler)\n\tr.HandleFunc(\"\/app\/AllStats\/\", VoronoiHandler)\n\tr.PathPrefix(\"\/static\/\").Handler(CacheRequest(http.StripPrefix(\"\/static\/\", http.FileServer(http.Dir(\"static\")))))\n\tr.PathPrefix(\"\/\").Handler(CacheRequest(http.FileServer(http.Dir(\"dist\"))))\n\thttp.Handle(\"\/\", r)\n\tlog.Fatal(http.ListenAndServe(\"0.0.0.0:9000\", nil))\n}\n<commit_msg>Fix server name<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/emembrives\/dispotrains\/dispotrains.webapp\/src\/storage\"\n\n\t\"github.com\/eknkc\/dateformat\"\n\t\"github.com\/gorilla\/mux\"\n\tmgo \"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\nconst (\n\tmongoDbHost = \"db\"\n)\n\nvar (\n\tsession = createSessionOrDie()\n)\n\ntype Line struct {\n\tNetwork      string\n\tID           string\n\tGoodStations []*storage.Station\n\tBadStations  []*storage.Station\n\tLastUpdate   time.Time\n}\n\ntype LineSlice []Line\n\ntype DisplayStation struct {\n\tName         string\n\tDisplayName  string\n\tCity         string\n\tPosition     storage.Coordinates\n\tOsmID        string\n\tElevators    []*LocElevator\n\tLastUpdate   time.Time\n\tBadElevators int\n}\n\ntype LocElevator storage.Elevator\n\ntype dataStatus struct {\n\tElevator   string\n\tState      string\n\tLastupdate time.Time\n}\n\nfunc (e *LocElevator) LocalStatusDate() string {\n\treturn dateformat.FormatLocale(e.Status.LastUpdate, \"ddd D MMM à HH:MM\", dateformat.French)\n}\n\nfunc createSessionOrDie() *mgo.Session {\n\tsession, err := mgo.Dial(mongoDbHost)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn session\n}\n\n\/\/ VoronoiHandler sends historical data for the Voronoi map.\nfunc VoronoiHandler(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Add(\"Access-Control-Allow-Methods\", \"GET\")\n\tw.Header().Add(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\tcStatistics := session.DB(\"dispotrains\").C(\"statistics\")\n\n\tvar stats []bson.M = make([]bson.M, 0)\n\tif err := cStatistics.Find(nil).All(&stats); err != nil {\n\t\tlog.Println(err)\n\t}\n\tvar jsonData []bson.M = make([]bson.M, 0)\n\tfor _, stat := range stats {\n\t\tdelete(stat, \"_id\")\n\t\tjsonData = append(jsonData, stat)\n\t}\n\tif err := json.NewEncoder(w).Encode(&jsonData); err != nil {\n\t\tlog.Println(err)\n\t}\n}\n\nfunc GetLinesHandler(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Add(\"Access-Control-Allow-Methods\", \"GET\")\n\tw.Header().Add(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\tw.Header().Set(\"Cache-control\", \"public, max-age=86400\")\n\n\tc := session.DB(\"dispotrains\").C(\"lines\")\n\tvar lines = make(LineSlice, 0)\n\tif err := c.Find(nil).Sort(\"network\", \"id\").All(&lines); err != nil {\n\t\tlog.Println(err)\n\t}\n\tjson.NewEncoder(w).Encode(&lines)\n}\n\nfunc GetStationsHandler(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Add(\"Access-Control-Allow-Methods\", \"GET\")\n\tw.Header().Add(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\n\tc := session.DB(\"dispotrains\").C(\"stations\")\n\tvar stations []bson.M\n\tif err := c.Find(nil).All(&stations); err != nil {\n\t\tlog.Println(err)\n\t}\n\tvar jsonStations []bson.M\n\tfor _, station := range stations {\n\t\tdelete(station, \"_id\")\n\t\tjsonStations = append(jsonStations, station)\n\t}\n\tjson.NewEncoder(w).Encode(&jsonStations)\n}\n\nfunc CacheRequest(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Cache-control\", \"public, max-age=259200\")\n\t\th.ServeHTTP(w, r)\n\t})\n}\n\nfunc main() {\n\tdefer session.Close()\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"\/app\/GetLines\/\", GetLinesHandler)\n\tr.HandleFunc(\"\/app\/GetStations\/\", GetStationsHandler)\n\tr.HandleFunc(\"\/app\/AllStats\/\", VoronoiHandler)\n\tr.PathPrefix(\"\/static\/\").Handler(CacheRequest(http.StripPrefix(\"\/static\/\", http.FileServer(http.Dir(\"static\")))))\n\tr.PathPrefix(\"\/\").Handler(CacheRequest(http.FileServer(http.Dir(\"dist\"))))\n\thttp.Handle(\"\/\", r)\n\tlog.Fatal(http.ListenAndServe(\"0.0.0.0:9000\", nil))\n}\n<|endoftext|>"}
{"text":"<commit_before>package cache\n\nimport \"gopkg.in\/src-d\/go-git.v4\/plumbing\"\n\nconst (\n\tinitialQueueSize = 20\n\tMaxSize          = 10 * MiByte\n)\n\ntype ObjectFIFO struct {\n\tobjects map[plumbing.Hash]plumbing.EncodedObject\n\torder   *queue\n\n\tmaxSize    int64\n\tactualSize int64\n}\n\n\/\/ NewObjectFIFO returns an Object cache that keeps the newest objects that fit\n\/\/ into the specific memory size\nfunc NewObjectFIFO(size int64) *ObjectFIFO {\n\treturn &ObjectFIFO{\n\t\tobjects: make(map[plumbing.Hash]plumbing.EncodedObject),\n\t\torder:   newQueue(initialQueueSize),\n\t\tmaxSize: size,\n\t}\n}\n\n\/\/ Add adds a new object to the cache. If the object size is greater than the\n\/\/ cache size, the object is not added.\nfunc (c *ObjectFIFO) Add(o plumbing.EncodedObject) {\n\t\/\/ if the size of the object is bigger or equal than the cache size,\n\t\/\/ skip it\n\tif o.Size() >= c.maxSize {\n\t\treturn\n\t}\n\n\t\/\/ if the object is into the cache, do not add it again\n\tif _, ok := c.objects[o.Hash()]; ok {\n\t\treturn\n\t}\n\n\t\/\/ delete the oldest object if cache is full\n\tif c.actualSize >= c.maxSize {\n\t\th := c.order.Pop()\n\t\to := c.objects[h]\n\t\tif o != nil {\n\t\t\tc.actualSize -= o.Size()\n\t\t\tdelete(c.objects, h)\n\t\t}\n\t}\n\n\tc.objects[o.Hash()] = o\n\tc.order.Push(o.Hash())\n\tc.actualSize += o.Size()\n}\n\n\/\/ Get returns an object by his hash. If the object is not into the cache, it\n\/\/ returns nil\nfunc (c *ObjectFIFO) Get(k plumbing.Hash) plumbing.EncodedObject {\n\treturn c.objects[k]\n}\n\n\/\/ Clear the content of this cache object\nfunc (c *ObjectFIFO) Clear() {\n\tc.objects = make(map[plumbing.Hash]plumbing.EncodedObject)\n\tc.order = newQueue(initialQueueSize)\n\tc.actualSize = 0\n}\n<commit_msg>Fix typos in cache pkg (#235)<commit_after>package cache\n\nimport \"gopkg.in\/src-d\/go-git.v4\/plumbing\"\n\nconst (\n\tinitialQueueSize = 20\n\tMaxSize          = 10 * MiByte\n)\n\ntype ObjectFIFO struct {\n\tobjects map[plumbing.Hash]plumbing.EncodedObject\n\torder   *queue\n\n\tmaxSize    int64\n\tactualSize int64\n}\n\n\/\/ NewObjectFIFO returns an Object cache that keeps the newest objects that fit\n\/\/ into the specific memory size\nfunc NewObjectFIFO(size int64) *ObjectFIFO {\n\treturn &ObjectFIFO{\n\t\tobjects: make(map[plumbing.Hash]plumbing.EncodedObject),\n\t\torder:   newQueue(initialQueueSize),\n\t\tmaxSize: size,\n\t}\n}\n\n\/\/ Add adds a new object to the cache. If the object size is greater than the\n\/\/ cache size, the object is not added.\nfunc (c *ObjectFIFO) Add(o plumbing.EncodedObject) {\n\t\/\/ if the size of the object is bigger or equal than the cache size,\n\t\/\/ skip it\n\tif o.Size() >= c.maxSize {\n\t\treturn\n\t}\n\n\t\/\/ if the object is into the cache, do not add it again\n\tif _, ok := c.objects[o.Hash()]; ok {\n\t\treturn\n\t}\n\n\t\/\/ delete the oldest object if cache is full\n\tif c.actualSize >= c.maxSize {\n\t\th := c.order.Pop()\n\t\to := c.objects[h]\n\t\tif o != nil {\n\t\t\tc.actualSize -= o.Size()\n\t\t\tdelete(c.objects, h)\n\t\t}\n\t}\n\n\tc.objects[o.Hash()] = o\n\tc.order.Push(o.Hash())\n\tc.actualSize += o.Size()\n}\n\n\/\/ Get returns an object by his hash. If the object is not found in the cache, it\n\/\/ returns nil\nfunc (c *ObjectFIFO) Get(k plumbing.Hash) plumbing.EncodedObject {\n\treturn c.objects[k]\n}\n\n\/\/ Clear the content of this object cache\nfunc (c *ObjectFIFO) Clear() {\n\tc.objects = make(map[plumbing.Hash]plumbing.EncodedObject)\n\tc.order = newQueue(initialQueueSize)\n\tc.actualSize = 0\n}\n<|endoftext|>"}
{"text":"<commit_before>package venuelib\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/howeyc\/gopass\"\n\t\"github.com\/kward\/venue\/codes\"\n)\n\n\/\/ venueError defines the status of a Venue call.\ntype venueError struct {\n\tcode codes.Code\n\tdesc string\n}\n\nfunc (e *venueError) Error() string {\n\treturn fmt.Sprintf(\"venue error: %s: %s\", e.code, e.desc)\n}\n\n\/\/ Code returns the error code for `err` if it was produced by Venue.\n\/\/ Otherwise, it returns codes.Unknown.\nfunc Code(err error) codes.Code {\n\tif err == nil {\n\t\treturn codes.OK\n\t}\n\tif e, ok := err.(*venueError); ok {\n\t\treturn e.code\n\t}\n\treturn codes.Unknown\n}\n\n\/\/ ErrorDesc returns the error description of `err` if it was produced by Venue.\n\/\/ Otherwise, it returns err.Error(), or an empty string when `err` is nil.\nfunc ErrorDesc(err error) string {\n\tif err == nil {\n\t\treturn \"\"\n\t}\n\tif e, ok := err.(*venueError); ok {\n\t\treturn e.desc\n\t}\n\treturn err.Error()\n}\n\n\/\/ Errorf returns an error containing an error code and a description.\n\/\/ Errorf returns nil if `c` is OK.\nfunc Errorf(c codes.Code, format string, a ...interface{}) error {\n\tif c == codes.OK {\n\t\treturn nil\n\t}\n\treturn &venueError{\n\t\tcode: c,\n\t\tdesc: fmt.Sprintf(format, a...),\n\t}\n}\n\n\/\/ GetPasswd requests the user for a masked password.\nfunc GetPasswd() string {\n\tfmt.Printf(\"Password: \")\n\tp, err := gopass.GetPasswdMasked()\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\treturn string(p)\n}\n\n\/\/ ToInt converts a string to an int.\nfunc ToInt(s string) int {\n\tvar i int\n\t_, err := fmt.Fscanf(bytes.NewBufferString(s), \"%d\", &i)\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn i\n}\n\n\/\/ FnName returns the calling function name, e.g. \"SomeFunction()\". This is\n\/\/ useful for logging the function name with glog.\nfunc FnName() string {\n\tpc := make([]uintptr, 10) \/\/ At least 1 entry needed.\n\truntime.Callers(2, pc)\n\tname := runtime.FuncForPC(pc[0]).Name()\n\treturn name[strings.LastIndex(name, \".\")+1:] + \"()\"\n}\n<commit_msg>added package comment<commit_after>\/\/ Package venuelib provides utility functions.\npackage venuelib\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/howeyc\/gopass\"\n\t\"github.com\/kward\/venue\/codes\"\n)\n\n\/\/ venueError defines the status of a Venue call.\ntype venueError struct {\n\tcode codes.Code\n\tdesc string\n}\n\nfunc (e *venueError) Error() string {\n\treturn fmt.Sprintf(\"venue error: %s: %s\", e.code, e.desc)\n}\n\n\/\/ Code returns the error code for `err` if it was produced by Venue.\n\/\/ Otherwise, it returns codes.Unknown.\nfunc Code(err error) codes.Code {\n\tif err == nil {\n\t\treturn codes.OK\n\t}\n\tif e, ok := err.(*venueError); ok {\n\t\treturn e.code\n\t}\n\treturn codes.Unknown\n}\n\n\/\/ ErrorDesc returns the error description of `err` if it was produced by Venue.\n\/\/ Otherwise, it returns err.Error(), or an empty string when `err` is nil.\nfunc ErrorDesc(err error) string {\n\tif err == nil {\n\t\treturn \"\"\n\t}\n\tif e, ok := err.(*venueError); ok {\n\t\treturn e.desc\n\t}\n\treturn err.Error()\n}\n\n\/\/ Errorf returns an error containing an error code and a description.\n\/\/ Errorf returns nil if `c` is OK.\nfunc Errorf(c codes.Code, format string, a ...interface{}) error {\n\tif c == codes.OK {\n\t\treturn nil\n\t}\n\treturn &venueError{\n\t\tcode: c,\n\t\tdesc: fmt.Sprintf(format, a...),\n\t}\n}\n\n\/\/ GetPasswd requests the user for a masked password.\nfunc GetPasswd() string {\n\tfmt.Printf(\"Password: \")\n\tp, err := gopass.GetPasswdMasked()\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\treturn string(p)\n}\n\n\/\/ ToInt converts a string to an int.\nfunc ToInt(s string) int {\n\tvar i int\n\t_, err := fmt.Fscanf(bytes.NewBufferString(s), \"%d\", &i)\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn i\n}\n\n\/\/ FnName returns the calling function name, e.g. \"SomeFunction()\". This is\n\/\/ useful for logging the function name with glog.\nfunc FnName() string {\n\tpc := make([]uintptr, 10) \/\/ At least 1 entry needed.\n\truntime.Callers(2, pc)\n\tname := runtime.FuncForPC(pc[0]).Name()\n\treturn name[strings.LastIndex(name, \".\")+1:] + \"()\"\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Patrice FERLET\n\/\/ Ue of this source code is governed by MIT-style\n\/\/ license that can be found in the LICENSE file\npackage verbalexpressions\n\nimport (\n\t\"log\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ VerbalExpression structure to create expression\ntype VerbalExpression struct {\n\texpression string\n\tanycase    bool\n\toneline    bool\n\tsuffixes   string\n\tprefixes   string\n}\n\n\/\/ quote is an alias to regexp.QuoteMeta\nfunc quote(s string) string {\n\treturn regexp.QuoteMeta(s)\n}\n\n\/\/ utility function to return only strings\nfunc tostring(i interface{}) string {\n\tvar r string\n\tswitch x := i.(type) {\n\tcase string:\n\t\tr = x\n\tcase int64:\n\t\tr = strconv.FormatInt(x, 64)\n\tcase uint:\n\t\tr = strconv.FormatUint(uint64(x), 64)\n\tcase int:\n\t\tr = strconv.FormatInt(int64(x), 32)\n\tdefault:\n\t\tlog.Panicf(\"Could not convert %v %t\", x, x)\n\t}\n\treturn r\n}\n\n\/\/ Instanciate a new VerbalExpression. You should use this method to\n\/\/ initalize some internal var.\n\/\/ Example:\n\/\/\t\tv := verbalexpression.New().Find(\"foo\")\nfunc New() *VerbalExpression {\n\tr := new(VerbalExpression)\n\tr.anycase, r.oneline = false, true\n\treturn r\n}\n\n\/\/ add method, append expresions to the internal string that will be parsed\nfunc (v *VerbalExpression) add(s string) *VerbalExpression {\n\tv.expression += s\n\treturn v\n}\n\n\/\/ Start to capture something, stop with EndCapture()\nfunc (v *VerbalExpression) BeginCapture() *VerbalExpression {\n\tv.suffixes += \")\"\n\treturn v.add(\"(\")\n}\n\n\/\/ Stop capturing expresions parts\nfunc (v *VerbalExpression) EndCapture() *VerbalExpression {\n\tv.suffixes = strings.Replace(v.suffixes, \")\", \"\", 1)\n\treturn v.add(\")\")\n}\n\n\/\/ Anything will match any char\nfunc (v *VerbalExpression) Anything() *VerbalExpression {\n\treturn v.add(`(?:.*)`)\n}\n\n\/\/ AnythingBut will match anything excpeting the given string.\n\/\/ Example:\n\/\/\t\ts := \"This is a simple test\"\n\/\/\t\tv := verbalexpressions.New().AnythingBut(\"ie\").RegExp().FindAllString(s, -1)\n\/\/\t\t[Th s  s a s mple t st]\nfunc (v *VerbalExpression) AnythingBut(s string) *VerbalExpression {\n\treturn v.add(`(?:[^` + quote(s) + `]*)`)\n}\n\n\/\/ EndOfLine tells verbalexpressions to match a end of line.\n\/\/ Warning, to check multiple line, you must use SearchOneLine(true)\nfunc (v *VerbalExpression) EndOfLine() *VerbalExpression {\n\tv.suffixes += \"$\"\n\treturn v\n}\n\n\/\/ Maybe will search string zero on more times\nfunc (v *VerbalExpression) Maybe(s string) *VerbalExpression {\n\treturn v.add(`(?:` + quote(s) + `)?`)\n}\n\n\/\/ StartOfLine seeks the begining of a line. As EndOfLine you should use\n\/\/ SearchOneLine(true) to test multiple lines\nfunc (v *VerbalExpression) StartOfLine() *VerbalExpression {\n\tv.prefixes += `^`\n\treturn v\n}\n\n\/\/ Find seeks string. The string MUST be there (unlike Maybe() method)\nfunc (v *VerbalExpression) Find(s string) *VerbalExpression {\n\treturn v.add(`(?:` + quote(s) + `)`)\n}\n\n\/\/ Alias to Find()\nfunc (v *VerbalExpression) Then(s string) *VerbalExpression {\n\treturn v.Find(s)\n}\n\n\/\/ Any accepts caracters to be matched\n\/\/ Example:\n\/\/\t\ts := \"foo1 foo5 foobar\"\n\/\/\t\tv := New().Find(\"foo\").Any(\"1234567890\").Regex().FindAllString(s, -1)\n\/\/\t\t[foo1 foo5]\nfunc (v *VerbalExpression) Any(s string) *VerbalExpression {\n\treturn v.add(`(?:[` + quote(s) + `])`)\n}\n\n\/\/AnyOf is an alias to Any\nfunc (v *VerbalExpression) AnyOf(s string) *VerbalExpression {\n\treturn v.Any(s)\n}\n\n\/\/ LineBreak to find \"\\n\" or \"\\r\\n\"\nfunc (v *VerbalExpression) LineBreak() *VerbalExpression {\n\treturn v.add(`(?:(?:\\n)|(?:\\r\\n))`)\n}\n\n\/\/ Alias to LineBreak\nfunc (v *VerbalExpression) Br() *VerbalExpression {\n\treturn v.LineBreak()\n}\n\n\/\/ Range accepts an even number of arguments. Each pair of values defines start and end of range.\n\/\/ Think like this: Range(from, to [, from, to ...])\n\/\/ Example:\n\/\/\t\ts := \"This 1 is 55 a TEST\"\n\/\/\t\tv := verbalexpressions.New().Range(\"a\",\"z\",0,9)\nfunc (v *VerbalExpression) Range(args ...interface{}) *VerbalExpression {\n\tif len(args)%2 != 0 {\n\t\tlog.Panicf(\"Range: not even args number\")\n\t}\n\n\tparts := make([]string, 3)\n\tapp := \"\"\n\tfor i := 0; i < len(args); i++ {\n\t\tapp += tostring(args[i])\n\t\tif i%2 != 0 {\n\t\t\tparts = append(parts, quote(app))\n\t\t\tapp = \"\"\n\t\t} else {\n\t\t\tapp += \"-\"\n\t\t}\n\t}\n\treturn v.add(\"[\" + strings.Join(parts, \"\") + \"]\")\n}\n\n\/\/ Tab fetch tabulation char (\\t)\nfunc (v *VerbalExpression) Tab() *VerbalExpression {\n\treturn v.add(`\\t+`)\n}\n\n\/\/ Word matches any word (containing alpha char)\nfunc (v *VerbalExpression) Word() *VerbalExpression {\n\treturn v.add(`\\w+`)\n}\n\n\/\/ Or, as the word is meaning...\nfunc (v *VerbalExpression) Or() *VerbalExpression {\n\tv.prefixes += \"(?:\"\n\tv.suffixes = \")\" + v.suffixes\n\treturn v.add(\")|(?:\")\n}\n\n\/\/ WithAnyCase ask verbalexpressions to match with or without case sensitivity\nfunc (v *VerbalExpression) WithAnyCase(sensitive bool) *VerbalExpression {\n\tv.anycase = sensitive\n\treturn v\n}\n\n\/\/ SearchOneLine deactivate \"multiline\" mode if true\n\/\/ Default is false\nfunc (v *VerbalExpression) SearchOneLine(oneline bool) *VerbalExpression {\n\tv.oneline = !oneline\n\treturn v\n}\n\n\/\/ Regex return the regular expression to use to test on string.\nfunc (v *VerbalExpression) Regex() *regexp.Regexp {\n\tmodifier := \"\"\n\tif v.anycase {\n\t\tmodifier += \"i\"\n\t}\n\n\tif v.oneline {\n\t\tmodifier += \"m\"\n\t}\n\tif len(modifier) > 0 {\n\t\tmodifier = \"(?\" + modifier + \")\"\n\t}\n\n\treturn regexp.MustCompile(modifier + v.prefixes + v.expression + v.suffixes)\n}\n\n\/* proxy and helpers to regexp.Regexp functions *\/\n\n\/\/ Test return true if verbalexpressions matches something in string \"s\"\nfunc (v *VerbalExpression) Test(s string) bool {\n\treturn v.Regex().Match([]byte(s))\n}\n\n\/\/ Replace alias to regexp.ReplaceAllString. It replace the found expression from\n\/\/ string src by string dst\nfunc (v *VerbalExpression) Replace(src string, dst string) string {\n\treturn v.Regex().ReplaceAllString(src, dst)\n}\n\n\/\/ Returns a slice of results from captures. If you didn't apply BeginCapture() and EnCapture(), the slices\n\/\/ will return slice of []string where []string is length 1, and 0 index is the global capture\n\/\/ Example:\n\/\/\t\ts:=\"This should get barsystem and whatever...\"\n\/\/\t\t\/\/ get \"bar\" followed by a word\n\/\/\t\tv := verbalexpressions.New().Anything().\n\/\/\t\t\t\tBeginCatpure().\n\/\/\t\t\t\tFind(\"bar\").Word().\n\/\/\t\t\t\tEndCapture()\n\/\/\n\/\/\t\tres := v.Captures(s)\n\/\/\t\tfmt.Println(res)\n\/\/\t\t[[\"This should get barsystem\", \"barsystem\"]]\n\/\/\n\/\/ So, to range results, you can do:\n\/\/\t\tfor _, captures := range res {\n\/\/\t\t\tfmt.Println(captures[1])\n\/\/\t\t}\n\/\/ Actualy, 1 matches first group, you can use several captures.\nfunc (v *VerbalExpression) Captures(s string) [][]string {\n\treturn v.Regex().FindAllStringSubmatch(s, -1)\n}\n<commit_msg>Reimplement modifiers<commit_after>\/\/ Copyright 2013 Patrice FERLET\n\/\/ Ue of this source code is governed by MIT-style\n\/\/ license that can be found in the LICENSE file\npackage verbalexpressions\n\nimport (\n\t\"log\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ VerbalExpression structure to create expression\ntype VerbalExpression struct {\n\texpression string\n\tsuffixes   string\n\tprefixes   string\n\tmodifiers  string\n}\n\n\/\/ quote is an alias to regexp.QuoteMeta\nfunc quote(s string) string {\n\treturn regexp.QuoteMeta(s)\n}\n\n\/\/ utility function to return only strings\nfunc tostring(i interface{}) string {\n\tvar r string\n\tswitch x := i.(type) {\n\tcase string:\n\t\tr = x\n\tcase int64:\n\t\tr = strconv.FormatInt(x, 64)\n\tcase uint:\n\t\tr = strconv.FormatUint(uint64(x), 64)\n\tcase int:\n\t\tr = strconv.FormatInt(int64(x), 32)\n\tdefault:\n\t\tlog.Panicf(\"Could not convert %v %t\", x, x)\n\t}\n\treturn r\n}\n\n\/\/ Instanciate a new VerbalExpression. You should use this method to\n\/\/ initalize some internal var.\n\/\/ Example:\n\/\/\t\tv := verbalexpression.New().Find(\"foo\")\nfunc New() *VerbalExpression {\n\tr := new(VerbalExpression)\n\tr.modifiers = \"m\"\n\treturn r\n}\n\n\/\/ append a modifier\nfunc (v *VerbalExpression) addmodifier(m string) *VerbalExpression {\n\tif !strings.Contains(v.modifiers, m) {\n\t\tv.modifiers += \"m\"\n\t}\n\treturn v\n}\n\n\/\/ remove a modifier\nfunc (v *VerbalExpression) removemodifier(m string) *VerbalExpression {\n\tv.modifiers = strings.Replace(v.modifiers, m, \"\", -1)\n\treturn v\n}\n\n\/\/ add method, append expresions to the internal string that will be parsed\nfunc (v *VerbalExpression) add(s string) *VerbalExpression {\n\tv.expression += s\n\treturn v\n}\n\n\/\/ Start to capture something, stop with EndCapture()\nfunc (v *VerbalExpression) BeginCapture() *VerbalExpression {\n\tv.suffixes += \")\"\n\treturn v.add(\"(\")\n}\n\n\/\/ Stop capturing expresions parts\nfunc (v *VerbalExpression) EndCapture() *VerbalExpression {\n\tv.suffixes = strings.Replace(v.suffixes, \")\", \"\", 1)\n\treturn v.add(\")\")\n}\n\n\/\/ Anything will match any char\nfunc (v *VerbalExpression) Anything() *VerbalExpression {\n\treturn v.add(`(?:.*)`)\n}\n\n\/\/ AnythingBut will match anything excpeting the given string.\n\/\/ Example:\n\/\/\t\ts := \"This is a simple test\"\n\/\/\t\tv := verbalexpressions.New().AnythingBut(\"ie\").RegExp().FindAllString(s, -1)\n\/\/\t\t[Th s  s a s mple t st]\nfunc (v *VerbalExpression) AnythingBut(s string) *VerbalExpression {\n\treturn v.add(`(?:[^` + quote(s) + `]*)`)\n}\n\n\/\/ EndOfLine tells verbalexpressions to match a end of line.\n\/\/ Warning, to check multiple line, you must use SearchOneLine(true)\nfunc (v *VerbalExpression) EndOfLine() *VerbalExpression {\n\tv.suffixes += \"$\"\n\treturn v\n}\n\n\/\/ Maybe will search string zero on more times\nfunc (v *VerbalExpression) Maybe(s string) *VerbalExpression {\n\treturn v.add(`(?:` + quote(s) + `)?`)\n}\n\n\/\/ StartOfLine seeks the begining of a line. As EndOfLine you should use\n\/\/ SearchOneLine(true) to test multiple lines\nfunc (v *VerbalExpression) StartOfLine() *VerbalExpression {\n\tv.prefixes += `^`\n\treturn v\n}\n\n\/\/ Find seeks string. The string MUST be there (unlike Maybe() method)\nfunc (v *VerbalExpression) Find(s string) *VerbalExpression {\n\treturn v.add(`(?:` + quote(s) + `)`)\n}\n\n\/\/ Alias to Find()\nfunc (v *VerbalExpression) Then(s string) *VerbalExpression {\n\treturn v.Find(s)\n}\n\n\/\/ Any accepts caracters to be matched\n\/\/ Example:\n\/\/\t\ts := \"foo1 foo5 foobar\"\n\/\/\t\tv := New().Find(\"foo\").Any(\"1234567890\").Regex().FindAllString(s, -1)\n\/\/\t\t[foo1 foo5]\nfunc (v *VerbalExpression) Any(s string) *VerbalExpression {\n\treturn v.add(`(?:[` + quote(s) + `])`)\n}\n\n\/\/AnyOf is an alias to Any\nfunc (v *VerbalExpression) AnyOf(s string) *VerbalExpression {\n\treturn v.Any(s)\n}\n\n\/\/ LineBreak to find \"\\n\" or \"\\r\\n\"\nfunc (v *VerbalExpression) LineBreak() *VerbalExpression {\n\treturn v.add(`(?:(?:\\n)|(?:\\r\\n))`)\n}\n\n\/\/ Alias to LineBreak\nfunc (v *VerbalExpression) Br() *VerbalExpression {\n\treturn v.LineBreak()\n}\n\n\/\/ Range accepts an even number of arguments. Each pair of values defines start and end of range.\n\/\/ Think like this: Range(from, to [, from, to ...])\n\/\/ Example:\n\/\/\t\ts := \"This 1 is 55 a TEST\"\n\/\/\t\tv := verbalexpressions.New().Range(\"a\",\"z\",0,9)\nfunc (v *VerbalExpression) Range(args ...interface{}) *VerbalExpression {\n\tif len(args)%2 != 0 {\n\t\tlog.Panicf(\"Range: not even args number\")\n\t}\n\n\tparts := make([]string, 3)\n\tapp := \"\"\n\tfor i := 0; i < len(args); i++ {\n\t\tapp += tostring(args[i])\n\t\tif i%2 != 0 {\n\t\t\tparts = append(parts, quote(app))\n\t\t\tapp = \"\"\n\t\t} else {\n\t\t\tapp += \"-\"\n\t\t}\n\t}\n\treturn v.add(\"[\" + strings.Join(parts, \"\") + \"]\")\n}\n\n\/\/ Tab fetch tabulation char (\\t)\nfunc (v *VerbalExpression) Tab() *VerbalExpression {\n\treturn v.add(`\\t+`)\n}\n\n\/\/ Word matches any word (containing alpha char)\nfunc (v *VerbalExpression) Word() *VerbalExpression {\n\treturn v.add(`\\w+`)\n}\n\n\/\/ Or, chains a alternate expression\n\/\/ Example:\n\/\/\t\tv := Verbalexpression.New().\n\/\/\t\t\t\tFind(\"foobarbaz\").\n\/\/\t\t\t\tOr().\n\/\/\t\t\t\tFind(\"footestbaz\")\nfunc (v *VerbalExpression) Or() *VerbalExpression {\n\tv.prefixes += \"(?:\"\n\tv.suffixes = \")\" + v.suffixes\n\treturn v.add(\")|(?:\")\n}\n\n\/\/ WithAnyCase ask verbalexpressions to match with or without case sensitivity\nfunc (v *VerbalExpression) WithAnyCase(sensitive bool) *VerbalExpression {\n\treturn v.addmodifier(\"i\")\n}\n\n\/\/ SearchOneLine deactivate \"multiline\" mode if true\n\/\/ Default is false\nfunc (v *VerbalExpression) SearchOneLine(oneline bool) *VerbalExpression {\n\tif oneline {\n\t\treturn v.removemodifier(\"m\")\n\t} else {\n\t\treturn v.addmodifier(\"m\")\n\t}\n}\n\n\/\/ Regex return the regular expression to use to test on string.\nfunc (v *VerbalExpression) Regex() *regexp.Regexp {\n\tmodifier := \"\"\n\tif len(v.modifiers) > 0 {\n\t\tmodifier = \"(?\" + v.modifiers + \")\"\n\t}\n\n\treturn regexp.MustCompile(modifier + v.prefixes + v.expression + v.suffixes)\n}\n\n\/* proxy and helpers to regexp.Regexp functions *\/\n\n\/\/ Test return true if verbalexpressions matches something in string \"s\"\nfunc (v *VerbalExpression) Test(s string) bool {\n\treturn v.Regex().Match([]byte(s))\n}\n\n\/\/ Replace alias to regexp.ReplaceAllString. It replace the found expression from\n\/\/ string src by string dst\nfunc (v *VerbalExpression) Replace(src string, dst string) string {\n\treturn v.Regex().ReplaceAllString(src, dst)\n}\n\n\/\/ Returns a slice of results from captures. If you didn't apply BeginCapture() and EnCapture(), the slices\n\/\/ will return slice of []string where []string is length 1, and 0 index is the global capture\n\/\/ Example:\n\/\/\t\ts:=\"This should get barsystem and whatever...\"\n\/\/\t\t\/\/ get \"bar\" followed by a word\n\/\/\t\tv := verbalexpressions.New().Anything().\n\/\/\t\t\t\tBeginCatpure().\n\/\/\t\t\t\tFind(\"bar\").Word().\n\/\/\t\t\t\tEndCapture()\n\/\/\n\/\/\t\tres := v.Captures(s)\n\/\/\t\tfmt.Println(res)\n\/\/\t\t[[\"This should get barsystem\", \"barsystem\"]]\n\/\/\n\/\/ So, to range results, you can do:\n\/\/\t\tfor _, captures := range res {\n\/\/\t\t\tfmt.Println(captures[1])\n\/\/\t\t}\n\/\/ Actualy, 1 matches first group, you can use several captures.\nfunc (v *VerbalExpression) Captures(s string) [][]string {\n\treturn v.Regex().FindAllStringSubmatch(s, -1)\n}\n<|endoftext|>"}
{"text":"<commit_before>package federationapi\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto\/ed25519\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/matrix-org\/dendrite\/federationapi\/api\"\n\t\"github.com\/matrix-org\/dendrite\/federationapi\/routing\"\n\t\"github.com\/matrix-org\/dendrite\/internal\/caching\"\n\t\"github.com\/matrix-org\/dendrite\/setup\/base\"\n\t\"github.com\/matrix-org\/dendrite\/setup\/config\"\n\t\"github.com\/matrix-org\/gomatrixserverlib\"\n)\n\ntype server struct {\n\tname      gomatrixserverlib.ServerName        \/\/ server name\n\tvalidity  time.Duration                       \/\/ key validity duration from now\n\tconfig    *config.FederationAPI               \/\/ skeleton config, from TestMain\n\tfedclient *gomatrixserverlib.FederationClient \/\/ uses MockRoundTripper\n\tcache     *caching.Caches                     \/\/ server-specific cache\n\tapi       api.FederationInternalAPI           \/\/ server-specific server key API\n}\n\nfunc (s *server) renew() {\n\t\/\/ This updates the validity period to be an hour in the\n\t\/\/ future, which is particularly useful in server A and\n\t\/\/ server C's cases which have validity either as now or\n\t\/\/ in the past.\n\ts.validity = time.Hour\n\ts.config.Matrix.KeyValidityPeriod = s.validity\n}\n\nvar (\n\tserverKeyID = gomatrixserverlib.KeyID(\"ed25519:auto\")\n\tserverA     = &server{name: \"a.com\", validity: time.Duration(0)} \/\/ expires now\n\tserverB     = &server{name: \"b.com\", validity: time.Hour}        \/\/ expires in an hour\n\tserverC     = &server{name: \"c.com\", validity: -time.Hour}       \/\/ expired an hour ago\n)\n\nvar servers = map[string]*server{\n\t\"a.com\": serverA,\n\t\"b.com\": serverB,\n\t\"c.com\": serverC,\n}\n\nfunc TestMain(m *testing.M) {\n\t\/\/ Set up the server key API for each \"server\" that we\n\t\/\/ will use in our tests.\n\tfor _, s := range servers {\n\t\t\/\/ Generate a new key.\n\t\t_, testPriv, err := ed25519.GenerateKey(nil)\n\t\tif err != nil {\n\t\t\tpanic(\"can't generate identity key: \" + err.Error())\n\t\t}\n\n\t\t\/\/ Create a new cache but don't enable prometheus!\n\t\ts.cache, err = caching.NewInMemoryLRUCache(false)\n\t\tif err != nil {\n\t\t\tpanic(\"can't create cache: \" + err.Error())\n\t\t}\n\n\t\t\/\/ Create a temporary directory for JetStream.\n\t\td, err := ioutil.TempDir(\".\/\", \"jetstream*\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer os.RemoveAll(d)\n\n\t\t\/\/ Draw up just enough Dendrite config for the server key\n\t\t\/\/ API to work.\n\t\tcfg := &config.Dendrite{}\n\t\tcfg.Defaults(true)\n\t\tcfg.Global.ServerName = gomatrixserverlib.ServerName(s.name)\n\t\tcfg.Global.PrivateKey = testPriv\n\t\tcfg.Global.JetStream.InMemory = true\n\t\tcfg.Global.JetStream.TopicPrefix = string(s.name[:1])\n\t\tcfg.Global.JetStream.StoragePath = config.Path(d)\n\t\tcfg.Global.KeyID = serverKeyID\n\t\tcfg.Global.KeyValidityPeriod = s.validity\n\t\tcfg.FederationAPI.Database.ConnectionString = config.DataSource(\"file::memory:\")\n\t\ts.config = &cfg.FederationAPI\n\n\t\t\/\/ Create a transport which redirects federation requests to\n\t\t\/\/ the mock round tripper. Since we're not *really* listening for\n\t\t\/\/ federation requests then this will return the key instead.\n\t\ttransport := &http.Transport{}\n\t\ttransport.RegisterProtocol(\"matrix\", &MockRoundTripper{})\n\n\t\t\/\/ Create the federation client.\n\t\ts.fedclient = gomatrixserverlib.NewFederationClient(\n\t\t\ts.config.Matrix.ServerName, serverKeyID, testPriv,\n\t\t\tgomatrixserverlib.WithTransport(transport),\n\t\t)\n\n\t\t\/\/ Finally, build the server key APIs.\n\t\tsbase := base.NewBaseDendrite(cfg, \"Monolith\", base.DisableMetrics)\n\t\ts.api = NewInternalAPI(sbase, s.fedclient, nil, s.cache, nil, true)\n\t}\n\n\t\/\/ Now that we have built our server key APIs, start the\n\t\/\/ rest of the tests.\n\tos.Exit(m.Run())\n}\n\ntype MockRoundTripper struct{}\n\nfunc (m *MockRoundTripper) RoundTrip(req *http.Request) (res *http.Response, err error) {\n\t\/\/ Check if the request is looking for keys from a server that\n\t\/\/ we know about in the test. The only reason this should go wrong\n\t\/\/ is if the test is broken.\n\ts, ok := servers[req.Host]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"server not known: %s\", req.Host)\n\t}\n\n\t\/\/ We're intercepting \/matrix\/key\/v2\/server requests here, so check\n\t\/\/ that the URL supplied in the request is for that.\n\tif req.URL.Path != \"\/_matrix\/key\/v2\/server\" {\n\t\treturn nil, fmt.Errorf(\"unexpected request path: %s\", req.URL.Path)\n\t}\n\n\t\/\/ Get the keys and JSON-ify them.\n\tkeys := routing.LocalKeys(s.config)\n\tbody, err := json.MarshalIndent(keys.JSON, \"\", \"  \")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ And respond.\n\tres = &http.Response{\n\t\tStatusCode: 200,\n\t\tBody:       ioutil.NopCloser(bytes.NewReader(body)),\n\t}\n\treturn\n}\n\nfunc TestServersRequestOwnKeys(t *testing.T) {\n\t\/\/ Each server will request its own keys. There's no reason\n\t\/\/ for this to fail as each server should know its own keys.\n\n\tfor name, s := range servers {\n\t\treq := gomatrixserverlib.PublicKeyLookupRequest{\n\t\t\tServerName: s.name,\n\t\t\tKeyID:      serverKeyID,\n\t\t}\n\t\tres, err := s.api.FetchKeys(\n\t\t\tcontext.Background(),\n\t\t\tmap[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp{\n\t\t\t\treq: gomatrixserverlib.AsTimestamp(time.Now()),\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"server could not fetch own key: %s\", err)\n\t\t}\n\t\tif _, ok := res[req]; !ok {\n\t\t\tt.Fatalf(\"server didn't return its own key in the results\")\n\t\t}\n\t\tt.Logf(\"%s's key expires at %s\\n\", name, res[req].ValidUntilTS.Time())\n\t}\n}\n\nfunc TestCachingBehaviour(t *testing.T) {\n\t\/\/ Server A will request Server B's key, which has a validity\n\t\/\/ period of an hour from now. We should retrieve the key and\n\t\/\/ it should make it into the cache automatically.\n\n\treq := gomatrixserverlib.PublicKeyLookupRequest{\n\t\tServerName: serverB.name,\n\t\tKeyID:      serverKeyID,\n\t}\n\tts := gomatrixserverlib.AsTimestamp(time.Now())\n\n\tres, err := serverA.api.FetchKeys(\n\t\tcontext.Background(),\n\t\tmap[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp{\n\t\t\treq: ts,\n\t\t},\n\t)\n\tif err != nil {\n\t\tt.Fatalf(\"server A failed to retrieve server B key: %s\", err)\n\t}\n\tif len(res) != 1 {\n\t\tt.Fatalf(\"server B should have returned one key but instead returned %d keys\", len(res))\n\t}\n\tif _, ok := res[req]; !ok {\n\t\tt.Fatalf(\"server B isn't included in the key fetch response\")\n\t}\n\n\t\/\/ At this point, if the previous key request was a success,\n\t\/\/ then the cache should now contain the key. Check if that's\n\t\/\/ the case - if it isn't then there's something wrong with\n\t\/\/ the cache implementation or we failed to get the key.\n\n\tcres, ok := serverA.cache.GetServerKey(req, ts)\n\tif !ok {\n\t\tt.Fatalf(\"server B key should be in cache but isn't\")\n\t}\n\tif !reflect.DeepEqual(cres, res[req]) {\n\t\tt.Fatalf(\"the cached result from server B wasn't what server B gave us\")\n\t}\n\n\t\/\/ If we ask the cache for the same key but this time for an event\n\t\/\/ that happened in +30 minutes. Since the validity period is for\n\t\/\/ another hour, then we should get a response back from the cache.\n\n\t_, ok = serverA.cache.GetServerKey(\n\t\treq,\n\t\tgomatrixserverlib.AsTimestamp(time.Now().Add(time.Minute*30)),\n\t)\n\tif !ok {\n\t\tt.Fatalf(\"server B key isn't in cache when it should be (+30 minutes)\")\n\t}\n\n\t\/\/ If we ask the cache for the same key but this time for an event\n\t\/\/ that happened in +90 minutes then we should expect to get no\n\t\/\/ cache result. This is because the cache shouldn't return a result\n\t\/\/ that is obviously past the validity of the event.\n\n\t_, ok = serverA.cache.GetServerKey(\n\t\treq,\n\t\tgomatrixserverlib.AsTimestamp(time.Now().Add(time.Minute*90)),\n\t)\n\tif ok {\n\t\tt.Fatalf(\"server B key is in cache when it shouldn't be (+90 minutes)\")\n\t}\n}\n\nfunc TestRenewalBehaviour(t *testing.T) {\n\t\/\/ Server A will request Server C's key but their validity period\n\t\/\/ is an hour in the past. We'll retrieve the key as, even though it's\n\t\/\/ past its validity, it will be able to verify past events.\n\n\treq := gomatrixserverlib.PublicKeyLookupRequest{\n\t\tServerName: serverC.name,\n\t\tKeyID:      serverKeyID,\n\t}\n\n\tres, err := serverA.api.FetchKeys(\n\t\tcontext.Background(),\n\t\tmap[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp{\n\t\t\treq: gomatrixserverlib.AsTimestamp(time.Now()),\n\t\t},\n\t)\n\tif err != nil {\n\t\tt.Fatalf(\"server A failed to retrieve server C key: %s\", err)\n\t}\n\tif len(res) != 1 {\n\t\tt.Fatalf(\"server C should have returned one key but instead returned %d keys\", len(res))\n\t}\n\tif _, ok := res[req]; !ok {\n\t\tt.Fatalf(\"server C isn't included in the key fetch response\")\n\t}\n\n\t\/\/ If we ask the cache for the server key for an event that happened\n\t\/\/ 90 minutes ago then we should get a cache result, as the key hadn't\n\t\/\/ passed its validity by that point. The fact that the key is now in\n\t\/\/ the cache is, in itself, proof that we successfully retrieved the\n\t\/\/ key before.\n\n\toldcached, ok := serverA.cache.GetServerKey(\n\t\treq,\n\t\tgomatrixserverlib.AsTimestamp(time.Now().Add(-time.Minute*90)),\n\t)\n\tif !ok {\n\t\tt.Fatalf(\"server C key isn't in cache when it should be (-90 minutes)\")\n\t}\n\n\t\/\/ If we now ask the cache for the same key but this time for an event\n\t\/\/ that only happened 30 minutes ago then we shouldn't get a cached\n\t\/\/ result, as the event happened after the key validity expired. This\n\t\/\/ is really just for sanity checking.\n\n\t_, ok = serverA.cache.GetServerKey(\n\t\treq,\n\t\tgomatrixserverlib.AsTimestamp(time.Now().Add(-time.Minute*30)),\n\t)\n\tif ok {\n\t\tt.Fatalf(\"server B key is in cache when it shouldn't be (-30 minutes)\")\n\t}\n\n\t\/\/ We're now going to kick server C into renewing its key. Since we're\n\t\/\/ happy at this point that the key that we already have is from the past\n\t\/\/ then repeating a key fetch should cause us to try and renew the key.\n\t\/\/ If so, then the new key will end up in our cache.\n\n\tserverC.renew()\n\n\tres, err = serverA.api.FetchKeys(\n\t\tcontext.Background(),\n\t\tmap[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp{\n\t\t\treq: gomatrixserverlib.AsTimestamp(time.Now()),\n\t\t},\n\t)\n\tif err != nil {\n\t\tt.Fatalf(\"server A failed to retrieve server C key: %s\", err)\n\t}\n\tif len(res) != 1 {\n\t\tt.Fatalf(\"server C should have returned one key but instead returned %d keys\", len(res))\n\t}\n\tif _, ok = res[req]; !ok {\n\t\tt.Fatalf(\"server C isn't included in the key fetch response\")\n\t}\n\n\t\/\/ We're now going to ask the cache what the new key validity is. If\n\t\/\/ it is still the same as the previous validity then we've failed to\n\t\/\/ retrieve the renewed key. If it's newer then we've successfully got\n\t\/\/ the renewed key.\n\n\tnewcached, ok := serverA.cache.GetServerKey(\n\t\treq,\n\t\tgomatrixserverlib.AsTimestamp(time.Now().Add(-time.Minute*30)),\n\t)\n\tif !ok {\n\t\tt.Fatalf(\"server B key isn't in cache when it shouldn't be (post-renewal)\")\n\t}\n\tif oldcached.ValidUntilTS >= newcached.ValidUntilTS {\n\t\tt.Fatalf(\"the server B key should have been renewed but wasn't\")\n\t}\n\tt.Log(res)\n}\n<commit_msg>Allow defers to run in `TestMain` in federation API tests<commit_after>package federationapi\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"crypto\/ed25519\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/matrix-org\/dendrite\/federationapi\/api\"\n\t\"github.com\/matrix-org\/dendrite\/federationapi\/routing\"\n\t\"github.com\/matrix-org\/dendrite\/internal\/caching\"\n\t\"github.com\/matrix-org\/dendrite\/setup\/base\"\n\t\"github.com\/matrix-org\/dendrite\/setup\/config\"\n\t\"github.com\/matrix-org\/gomatrixserverlib\"\n)\n\ntype server struct {\n\tname      gomatrixserverlib.ServerName        \/\/ server name\n\tvalidity  time.Duration                       \/\/ key validity duration from now\n\tconfig    *config.FederationAPI               \/\/ skeleton config, from TestMain\n\tfedclient *gomatrixserverlib.FederationClient \/\/ uses MockRoundTripper\n\tcache     *caching.Caches                     \/\/ server-specific cache\n\tapi       api.FederationInternalAPI           \/\/ server-specific server key API\n}\n\nfunc (s *server) renew() {\n\t\/\/ This updates the validity period to be an hour in the\n\t\/\/ future, which is particularly useful in server A and\n\t\/\/ server C's cases which have validity either as now or\n\t\/\/ in the past.\n\ts.validity = time.Hour\n\ts.config.Matrix.KeyValidityPeriod = s.validity\n}\n\nvar (\n\tserverKeyID = gomatrixserverlib.KeyID(\"ed25519:auto\")\n\tserverA     = &server{name: \"a.com\", validity: time.Duration(0)} \/\/ expires now\n\tserverB     = &server{name: \"b.com\", validity: time.Hour}        \/\/ expires in an hour\n\tserverC     = &server{name: \"c.com\", validity: -time.Hour}       \/\/ expired an hour ago\n)\n\nvar servers = map[string]*server{\n\t\"a.com\": serverA,\n\t\"b.com\": serverB,\n\t\"c.com\": serverC,\n}\n\nfunc TestMain(m *testing.M) {\n\t\/\/ Set up the server key API for each \"server\" that we\n\t\/\/ will use in our tests.\n\tos.Exit(func() int {\n\t\tfor _, s := range servers {\n\t\t\t\/\/ Generate a new key.\n\t\t\t_, testPriv, err := ed25519.GenerateKey(nil)\n\t\t\tif err != nil {\n\t\t\t\tpanic(\"can't generate identity key: \" + err.Error())\n\t\t\t}\n\n\t\t\t\/\/ Create a new cache but don't enable prometheus!\n\t\t\ts.cache, err = caching.NewInMemoryLRUCache(false)\n\t\t\tif err != nil {\n\t\t\t\tpanic(\"can't create cache: \" + err.Error())\n\t\t\t}\n\n\t\t\t\/\/ Create a temporary directory for JetStream.\n\t\t\td, err := ioutil.TempDir(\".\/\", \"jetstream*\")\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tdefer os.RemoveAll(d)\n\n\t\t\t\/\/ Draw up just enough Dendrite config for the server key\n\t\t\t\/\/ API to work.\n\t\t\tcfg := &config.Dendrite{}\n\t\t\tcfg.Defaults(true)\n\t\t\tcfg.Global.ServerName = gomatrixserverlib.ServerName(s.name)\n\t\t\tcfg.Global.PrivateKey = testPriv\n\t\t\tcfg.Global.JetStream.InMemory = true\n\t\t\tcfg.Global.JetStream.TopicPrefix = string(s.name[:1])\n\t\t\tcfg.Global.JetStream.StoragePath = config.Path(d)\n\t\t\tcfg.Global.KeyID = serverKeyID\n\t\t\tcfg.Global.KeyValidityPeriod = s.validity\n\t\t\tcfg.FederationAPI.Database.ConnectionString = config.DataSource(\"file::memory:\")\n\t\t\ts.config = &cfg.FederationAPI\n\n\t\t\t\/\/ Create a transport which redirects federation requests to\n\t\t\t\/\/ the mock round tripper. Since we're not *really* listening for\n\t\t\t\/\/ federation requests then this will return the key instead.\n\t\t\ttransport := &http.Transport{}\n\t\t\ttransport.RegisterProtocol(\"matrix\", &MockRoundTripper{})\n\n\t\t\t\/\/ Create the federation client.\n\t\t\ts.fedclient = gomatrixserverlib.NewFederationClient(\n\t\t\t\ts.config.Matrix.ServerName, serverKeyID, testPriv,\n\t\t\t\tgomatrixserverlib.WithTransport(transport),\n\t\t\t)\n\n\t\t\t\/\/ Finally, build the server key APIs.\n\t\t\tsbase := base.NewBaseDendrite(cfg, \"Monolith\", base.DisableMetrics)\n\t\t\ts.api = NewInternalAPI(sbase, s.fedclient, nil, s.cache, nil, true)\n\t\t}\n\n\t\t\/\/ Now that we have built our server key APIs, start the\n\t\t\/\/ rest of the tests.\n\t\treturn m.Run()\n\t}())\n}\n\ntype MockRoundTripper struct{}\n\nfunc (m *MockRoundTripper) RoundTrip(req *http.Request) (res *http.Response, err error) {\n\t\/\/ Check if the request is looking for keys from a server that\n\t\/\/ we know about in the test. The only reason this should go wrong\n\t\/\/ is if the test is broken.\n\ts, ok := servers[req.Host]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"server not known: %s\", req.Host)\n\t}\n\n\t\/\/ We're intercepting \/matrix\/key\/v2\/server requests here, so check\n\t\/\/ that the URL supplied in the request is for that.\n\tif req.URL.Path != \"\/_matrix\/key\/v2\/server\" {\n\t\treturn nil, fmt.Errorf(\"unexpected request path: %s\", req.URL.Path)\n\t}\n\n\t\/\/ Get the keys and JSON-ify them.\n\tkeys := routing.LocalKeys(s.config)\n\tbody, err := json.MarshalIndent(keys.JSON, \"\", \"  \")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ And respond.\n\tres = &http.Response{\n\t\tStatusCode: 200,\n\t\tBody:       ioutil.NopCloser(bytes.NewReader(body)),\n\t}\n\treturn\n}\n\nfunc TestServersRequestOwnKeys(t *testing.T) {\n\t\/\/ Each server will request its own keys. There's no reason\n\t\/\/ for this to fail as each server should know its own keys.\n\n\tfor name, s := range servers {\n\t\treq := gomatrixserverlib.PublicKeyLookupRequest{\n\t\t\tServerName: s.name,\n\t\t\tKeyID:      serverKeyID,\n\t\t}\n\t\tres, err := s.api.FetchKeys(\n\t\t\tcontext.Background(),\n\t\t\tmap[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp{\n\t\t\t\treq: gomatrixserverlib.AsTimestamp(time.Now()),\n\t\t\t},\n\t\t)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"server could not fetch own key: %s\", err)\n\t\t}\n\t\tif _, ok := res[req]; !ok {\n\t\t\tt.Fatalf(\"server didn't return its own key in the results\")\n\t\t}\n\t\tt.Logf(\"%s's key expires at %s\\n\", name, res[req].ValidUntilTS.Time())\n\t}\n}\n\nfunc TestCachingBehaviour(t *testing.T) {\n\t\/\/ Server A will request Server B's key, which has a validity\n\t\/\/ period of an hour from now. We should retrieve the key and\n\t\/\/ it should make it into the cache automatically.\n\n\treq := gomatrixserverlib.PublicKeyLookupRequest{\n\t\tServerName: serverB.name,\n\t\tKeyID:      serverKeyID,\n\t}\n\tts := gomatrixserverlib.AsTimestamp(time.Now())\n\n\tres, err := serverA.api.FetchKeys(\n\t\tcontext.Background(),\n\t\tmap[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp{\n\t\t\treq: ts,\n\t\t},\n\t)\n\tif err != nil {\n\t\tt.Fatalf(\"server A failed to retrieve server B key: %s\", err)\n\t}\n\tif len(res) != 1 {\n\t\tt.Fatalf(\"server B should have returned one key but instead returned %d keys\", len(res))\n\t}\n\tif _, ok := res[req]; !ok {\n\t\tt.Fatalf(\"server B isn't included in the key fetch response\")\n\t}\n\n\t\/\/ At this point, if the previous key request was a success,\n\t\/\/ then the cache should now contain the key. Check if that's\n\t\/\/ the case - if it isn't then there's something wrong with\n\t\/\/ the cache implementation or we failed to get the key.\n\n\tcres, ok := serverA.cache.GetServerKey(req, ts)\n\tif !ok {\n\t\tt.Fatalf(\"server B key should be in cache but isn't\")\n\t}\n\tif !reflect.DeepEqual(cres, res[req]) {\n\t\tt.Fatalf(\"the cached result from server B wasn't what server B gave us\")\n\t}\n\n\t\/\/ If we ask the cache for the same key but this time for an event\n\t\/\/ that happened in +30 minutes. Since the validity period is for\n\t\/\/ another hour, then we should get a response back from the cache.\n\n\t_, ok = serverA.cache.GetServerKey(\n\t\treq,\n\t\tgomatrixserverlib.AsTimestamp(time.Now().Add(time.Minute*30)),\n\t)\n\tif !ok {\n\t\tt.Fatalf(\"server B key isn't in cache when it should be (+30 minutes)\")\n\t}\n\n\t\/\/ If we ask the cache for the same key but this time for an event\n\t\/\/ that happened in +90 minutes then we should expect to get no\n\t\/\/ cache result. This is because the cache shouldn't return a result\n\t\/\/ that is obviously past the validity of the event.\n\n\t_, ok = serverA.cache.GetServerKey(\n\t\treq,\n\t\tgomatrixserverlib.AsTimestamp(time.Now().Add(time.Minute*90)),\n\t)\n\tif ok {\n\t\tt.Fatalf(\"server B key is in cache when it shouldn't be (+90 minutes)\")\n\t}\n}\n\nfunc TestRenewalBehaviour(t *testing.T) {\n\t\/\/ Server A will request Server C's key but their validity period\n\t\/\/ is an hour in the past. We'll retrieve the key as, even though it's\n\t\/\/ past its validity, it will be able to verify past events.\n\n\treq := gomatrixserverlib.PublicKeyLookupRequest{\n\t\tServerName: serverC.name,\n\t\tKeyID:      serverKeyID,\n\t}\n\n\tres, err := serverA.api.FetchKeys(\n\t\tcontext.Background(),\n\t\tmap[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp{\n\t\t\treq: gomatrixserverlib.AsTimestamp(time.Now()),\n\t\t},\n\t)\n\tif err != nil {\n\t\tt.Fatalf(\"server A failed to retrieve server C key: %s\", err)\n\t}\n\tif len(res) != 1 {\n\t\tt.Fatalf(\"server C should have returned one key but instead returned %d keys\", len(res))\n\t}\n\tif _, ok := res[req]; !ok {\n\t\tt.Fatalf(\"server C isn't included in the key fetch response\")\n\t}\n\n\t\/\/ If we ask the cache for the server key for an event that happened\n\t\/\/ 90 minutes ago then we should get a cache result, as the key hadn't\n\t\/\/ passed its validity by that point. The fact that the key is now in\n\t\/\/ the cache is, in itself, proof that we successfully retrieved the\n\t\/\/ key before.\n\n\toldcached, ok := serverA.cache.GetServerKey(\n\t\treq,\n\t\tgomatrixserverlib.AsTimestamp(time.Now().Add(-time.Minute*90)),\n\t)\n\tif !ok {\n\t\tt.Fatalf(\"server C key isn't in cache when it should be (-90 minutes)\")\n\t}\n\n\t\/\/ If we now ask the cache for the same key but this time for an event\n\t\/\/ that only happened 30 minutes ago then we shouldn't get a cached\n\t\/\/ result, as the event happened after the key validity expired. This\n\t\/\/ is really just for sanity checking.\n\n\t_, ok = serverA.cache.GetServerKey(\n\t\treq,\n\t\tgomatrixserverlib.AsTimestamp(time.Now().Add(-time.Minute*30)),\n\t)\n\tif ok {\n\t\tt.Fatalf(\"server B key is in cache when it shouldn't be (-30 minutes)\")\n\t}\n\n\t\/\/ We're now going to kick server C into renewing its key. Since we're\n\t\/\/ happy at this point that the key that we already have is from the past\n\t\/\/ then repeating a key fetch should cause us to try and renew the key.\n\t\/\/ If so, then the new key will end up in our cache.\n\n\tserverC.renew()\n\n\tres, err = serverA.api.FetchKeys(\n\t\tcontext.Background(),\n\t\tmap[gomatrixserverlib.PublicKeyLookupRequest]gomatrixserverlib.Timestamp{\n\t\t\treq: gomatrixserverlib.AsTimestamp(time.Now()),\n\t\t},\n\t)\n\tif err != nil {\n\t\tt.Fatalf(\"server A failed to retrieve server C key: %s\", err)\n\t}\n\tif len(res) != 1 {\n\t\tt.Fatalf(\"server C should have returned one key but instead returned %d keys\", len(res))\n\t}\n\tif _, ok = res[req]; !ok {\n\t\tt.Fatalf(\"server C isn't included in the key fetch response\")\n\t}\n\n\t\/\/ We're now going to ask the cache what the new key validity is. If\n\t\/\/ it is still the same as the previous validity then we've failed to\n\t\/\/ retrieve the renewed key. If it's newer then we've successfully got\n\t\/\/ the renewed key.\n\n\tnewcached, ok := serverA.cache.GetServerKey(\n\t\treq,\n\t\tgomatrixserverlib.AsTimestamp(time.Now().Add(-time.Minute*30)),\n\t)\n\tif !ok {\n\t\tt.Fatalf(\"server B key isn't in cache when it shouldn't be (post-renewal)\")\n\t}\n\tif oldcached.ValidUntilTS >= newcached.ValidUntilTS {\n\t\tt.Fatalf(\"the server B key should have been renewed but wasn't\")\n\t}\n\tt.Log(res)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gopkg.in\/urfave\/cli.v1\"\n)\n\nfunc TestCommands_requirements(t *testing.T) {\n\tvar cs, subcs []cli.Command\n\tfor _, c := range Commands {\n\t\tif len(c.Subcommands) == 0 {\n\t\t\tcs = append(cs, c)\n\t\t} else {\n\t\t\tfor _, sc := range c.Subcommands {\n\t\t\t\tcs = append(cs, sc)\n\t\t\t}\n\t\t\tsubcs = append(subcs, c)\n\t\t}\n\t}\n\tfor _, c := range cs {\n\t\tif !strings.HasPrefix(c.Description, \"\\n    \") {\n\t\t\tt.Errorf(\"%s: cli.Command.Description should start with '\\\\n    ', got:\\n%s\", c.Name, c.Description)\n\t\t}\n\t\tif !strings.HasSuffix(c.Description, \"\\n\") {\n\t\t\tt.Errorf(\"%s: cli.Command.Description should end with '\\\\n', got:\\n%s\", c.Name, c.Description)\n\t\t}\n\t\tif len(c.Flags) > 0 && c.ArgsUsage == \"\" {\n\t\t\tt.Errorf(\"%s: cli.Command.ArgsUsage should not be empty. Describe flag options.\", c.Name)\n\t\t}\n\t}\n\tfor _, sc := range subcs {\n\t\tif sc.Description == \"\" {\n\t\t\tt.Errorf(\"%s: cli.Command.Description should not be empty\", sc.Name)\n\t\t}\n\t}\n}\n<commit_msg>Remove Description convention tests<commit_after>package main\n\nimport (\n\t\"testing\"\n\n\tcli \"gopkg.in\/urfave\/cli.v1\"\n)\n\nfunc TestCommands_requirements(t *testing.T) {\n\tvar cs, subcs []cli.Command\n\tfor _, c := range Commands {\n\t\tif len(c.Subcommands) == 0 {\n\t\t\tcs = append(cs, c)\n\t\t} else {\n\t\t\tfor _, sc := range c.Subcommands {\n\t\t\t\tcs = append(cs, sc)\n\t\t\t}\n\t\t\tsubcs = append(subcs, c)\n\t\t}\n\t}\n\tfor _, c := range cs {\n\t\tif len(c.Flags) > 0 && c.ArgsUsage == \"\" {\n\t\t\tt.Errorf(\"%s: cli.Command.ArgsUsage should not be empty. Describe flag options.\", c.Name)\n\t\t}\n\t}\n\tfor _, sc := range subcs {\n\t\tif sc.Description == \"\" {\n\t\t\tt.Errorf(\"%s: cli.Command.Description should not be empty\", sc.Name)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package system\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\thttpd \"github.com\/rqlite\/rqlite\/http\"\n\t\"github.com\/rqlite\/rqlite\/store\"\n)\n\n\/\/ Node represents a node under test.\ntype Node struct {\n\tAPIAddr  string\n\tRaftAddr string\n\tDir      string\n\tStore    *store.Store\n\tService  *httpd.Service\n}\n\n\/\/ SameAs returns true if this node is the same as node o.\nfunc (n *Node) SameAs(o *Node) bool {\n\treturn n.RaftAddr == o.RaftAddr\n}\n\n\/\/ Deprovision shuts down and removes all resources associated with the node.\nfunc (n *Node) Deprovision() {\n\tn.Store.Close(false)\n\tn.Service.Close()\n\tos.RemoveAll(n.Dir)\n}\n\n\/\/ WaitForLeader blocks for up to 10 seconds until the node detects a leader.\nfunc (n *Node) WaitForLeader() (string, error) {\n\treturn n.Store.WaitForLeader(10 * time.Second)\n}\n\n\/\/ Execute executes a single statement against the node.\nfunc (n *Node) Execute(stmt string) (string, error) {\n\treturn n.ExecuteMulti([]string{stmt})\n}\n\n\/\/ ExecuteMulti executes multiple statements against the node.\nfunc (n *Node) ExecuteMulti(stmts []string) (string, error) {\n\tj, err := json.Marshal(stmts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn n.postExecute(string(j))\n}\n\n\/\/ Query runs a single query against the node.\nfunc (n *Node) Query(stmt string) (string, error) {\n\tv, _ := url.Parse(\"http:\/\/\" + n.APIAddr + \"\/db\/query\")\n\tv.RawQuery = url.Values{\"q\": []string{stmt}}.Encode()\n\n\tresp, err := http.Get(v.String())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}\n\n\/\/ Join instructs this node to join the leader.\nfunc (n *Node) Join(leader *Node) error {\n\tresp, err := DoJoinRequest(leader.APIAddr, n.RaftAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"failed to join, leader returned: %s\", resp.Status)\n\t}\n\tdefer resp.Body.Close()\n\treturn nil\n}\n\n\/\/ Status returns the status and diagnostic output for node.\nfunc (n *Node) Status() (string, error) {\n\tv, _ := url.Parse(\"http:\/\/\" + n.APIAddr + \"\/status\")\n\n\tresp, err := http.Get(v.String())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}\n\n\/\/ Expvar returns the expvar output for node.\nfunc (n *Node) Expvar() (string, error) {\n\tv, _ := url.Parse(\"http:\/\/\" + n.APIAddr + \"\/debug\/vars\")\n\n\tresp, err := http.Get(v.String())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}\n\n\/\/ ConfirmRedirect confirms that the node responds with a redirect to the given host.\nfunc (n *Node) ConfirmRedirect(host string) bool {\n\tv, _ := url.Parse(\"http:\/\/\" + n.APIAddr + \"\/db\/query\")\n\tv.RawQuery = url.Values{\"q\": []string{`SELECT * FROM foo`}}.Encode()\n\n\tresp, err := http.Get(v.String())\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer resp.Body.Close()\n\tfmt.Println(resp.StatusCode)\n\tif resp.StatusCode != http.StatusMovedPermanently {\n\t\treturn false\n\t}\n\tif resp.Header.Get(\"location\") != host {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc (n *Node) postExecute(stmt string) (string, error) {\n\tresp, err := http.Post(\"http:\/\/\"+n.APIAddr+\"\/db\/execute\", \"application\/json\", strings.NewReader(stmt))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}\n\n\/\/ Cluster represents a cluster of nodes.\ntype Cluster []*Node\n\n\/\/ Leader returns the leader node of a cluster.\nfunc (c Cluster) Leader() (*Node, error) {\n\tl, err := c[0].WaitForLeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.FindNodeByRaftAddr(l)\n}\n\n\/\/ WaitForNewLeader waits for the leader to change from the node passed in.\nfunc (c Cluster) WaitForNewLeader(old *Node) (*Node, error) {\n\ttimer := time.NewTimer(30 * time.Second)\n\tdefer timer.Stop()\n\tticker := time.NewTicker(100 * time.Millisecond)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-timer.C:\n\t\t\treturn nil, fmt.Errorf(\"timed out waiting for new leader\")\n\t\tcase <-ticker.C:\n\t\t\tl, err := c.Leader()\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !l.SameAs(old) {\n\t\t\t\treturn l, nil\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Followers returns the slice of nodes in the cluster that are followers.\nfunc (c Cluster) Followers() ([]*Node, error) {\n\tn, err := c[0].WaitForLeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tleader, err := c.FindNodeByRaftAddr(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar followers []*Node\n\tfor _, n := range c {\n\t\tif n != leader {\n\t\t\tfollowers = append(followers, n)\n\t\t}\n\t}\n\treturn followers, nil\n}\n\n\/\/ RemoveNode removes the given node from the list of nodes representing\n\/\/ a cluster.\nfunc (c Cluster) RemoveNode(node *Node) {\n\tfor i, n := range c {\n\t\tif n.RaftAddr == node.RaftAddr {\n\t\t\tc = append(c[:i], c[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ FindNodeByRaftAddr returns the node with the given Raft address.\nfunc (c Cluster) FindNodeByRaftAddr(addr string) (*Node, error) {\n\tfor _, n := range c {\n\t\tif n.RaftAddr == addr {\n\t\t\treturn n, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"node not found\")\n}\n\n\/\/ Deprovision deprovisions every node in the cluster.\nfunc (c Cluster) Deprovision() {\n\tfor _, n := range c {\n\t\tn.Deprovision()\n\t}\n}\n\n\/\/ Remove tells the cluster at n to remove the node at addr. Assumes n is the leader.\nfunc Remove(n *Node, addr string) error {\n\tb, err := json.Marshal(map[string]string{\"addr\": addr})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Attempt to remove node from leader.\n\tresp, err := http.Post(\"http:\/\/\"+n.APIAddr+\"\/remove\", \"application-type\/json\", bytes.NewReader(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"failed to remove node, leader returned: %s\", resp.Status)\n\t}\n\tdefer resp.Body.Close()\n\treturn nil\n}\n\n\/\/ DoJoinRequest sends a join request to nodeAddr, for raftAddr.\nfunc DoJoinRequest(nodeAddr, raftAddr string) (*http.Response, error) {\n\tb, err := json.Marshal(map[string]string{\"addr\": raftAddr})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := http.Post(\"http:\/\/\"+nodeAddr+\"\/join\", \"application-type\/json\", bytes.NewReader(b))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}\n\nfunc mustNewNode(enableSingle bool) *Node {\n\tnode := &Node{\n\t\tDir: mustTempDir(),\n\t}\n\n\tdbConf := store.NewDBConfig(\"\", false)\n\tnode.Store = store.New(&store.StoreConfig{\n\t\tDBConf: dbConf,\n\t\tDir:    node.Dir,\n\t\tTn:     mustMockTransport(\"localhost:0\"),\n\t})\n\tif err := node.Store.Open(enableSingle); err != nil {\n\t\tnode.Deprovision()\n\t\tpanic(fmt.Sprintf(\"failed to open store: %s\", err.Error()))\n\t}\n\tnode.RaftAddr = node.Store.Addr().String()\n\n\tnode.Service = httpd.New(\"localhost:0\", node.Store, nil)\n\tif err := node.Service.Start(); err != nil {\n\t\tnode.Deprovision()\n\t\tpanic(fmt.Sprintf(\"failed to start HTTP server: %s\", err.Error()))\n\t}\n\tnode.APIAddr = node.Service.Addr().String()\n\n\treturn node\n}\n\nfunc mustNewLeaderNode() *Node {\n\tnode := mustNewNode(true)\n\tif _, err := node.WaitForLeader(); err != nil {\n\t\tnode.Deprovision()\n\t\tpanic(\"node never became leader\")\n\t}\n\treturn node\n}\n\ntype mockTransport struct {\n\tln net.Listener\n}\n\nfunc mustMockTransport(addr string) *mockTransport {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tpanic(\"failed to create new transport\")\n\t}\n\treturn &mockTransport{ln}\n}\n\nfunc (m *mockTransport) Dial(addr string, timeout time.Duration) (net.Conn, error) {\n\treturn net.DialTimeout(\"tcp\", addr, timeout)\n}\n\nfunc (m *mockTransport) Accept() (net.Conn, error) { return m.ln.Accept() }\n\nfunc (m *mockTransport) Close() error { return m.ln.Close() }\n\nfunc (m *mockTransport) Addr() net.Addr { return m.ln.Addr() }\n\nfunc mustTempDir() string {\n\tvar err error\n\tpath, err := ioutil.TempDir(\"\", \"rqlilte-system-test-\")\n\tif err != nil {\n\t\tpanic(\"failed to create temp dir\")\n\t}\n\treturn path\n}\n\nfunc isJSON(s string) bool {\n\tvar js map[string]interface{}\n\treturn json.Unmarshal([]byte(s), &js) == nil\n}\n<commit_msg>Enable expvar endpoint for testing<commit_after>package system\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\thttpd \"github.com\/rqlite\/rqlite\/http\"\n\t\"github.com\/rqlite\/rqlite\/store\"\n)\n\n\/\/ Node represents a node under test.\ntype Node struct {\n\tAPIAddr  string\n\tRaftAddr string\n\tDir      string\n\tStore    *store.Store\n\tService  *httpd.Service\n}\n\n\/\/ SameAs returns true if this node is the same as node o.\nfunc (n *Node) SameAs(o *Node) bool {\n\treturn n.RaftAddr == o.RaftAddr\n}\n\n\/\/ Deprovision shuts down and removes all resources associated with the node.\nfunc (n *Node) Deprovision() {\n\tn.Store.Close(false)\n\tn.Service.Close()\n\tos.RemoveAll(n.Dir)\n}\n\n\/\/ WaitForLeader blocks for up to 10 seconds until the node detects a leader.\nfunc (n *Node) WaitForLeader() (string, error) {\n\treturn n.Store.WaitForLeader(10 * time.Second)\n}\n\n\/\/ Execute executes a single statement against the node.\nfunc (n *Node) Execute(stmt string) (string, error) {\n\treturn n.ExecuteMulti([]string{stmt})\n}\n\n\/\/ ExecuteMulti executes multiple statements against the node.\nfunc (n *Node) ExecuteMulti(stmts []string) (string, error) {\n\tj, err := json.Marshal(stmts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn n.postExecute(string(j))\n}\n\n\/\/ Query runs a single query against the node.\nfunc (n *Node) Query(stmt string) (string, error) {\n\tv, _ := url.Parse(\"http:\/\/\" + n.APIAddr + \"\/db\/query\")\n\tv.RawQuery = url.Values{\"q\": []string{stmt}}.Encode()\n\n\tresp, err := http.Get(v.String())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}\n\n\/\/ Join instructs this node to join the leader.\nfunc (n *Node) Join(leader *Node) error {\n\tresp, err := DoJoinRequest(leader.APIAddr, n.RaftAddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"failed to join, leader returned: %s\", resp.Status)\n\t}\n\tdefer resp.Body.Close()\n\treturn nil\n}\n\n\/\/ Status returns the status and diagnostic output for node.\nfunc (n *Node) Status() (string, error) {\n\tv, _ := url.Parse(\"http:\/\/\" + n.APIAddr + \"\/status\")\n\n\tresp, err := http.Get(v.String())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn \"\", fmt.Errorf(\"status endpoint returned: %s\", resp.Status)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}\n\n\/\/ Expvar returns the expvar output for node.\nfunc (n *Node) Expvar() (string, error) {\n\tv, _ := url.Parse(\"http:\/\/\" + n.APIAddr + \"\/debug\/vars\")\n\n\tresp, err := http.Get(v.String())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn \"\", fmt.Errorf(\"expvar endpoint returned: %s\", resp.Status)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}\n\n\/\/ ConfirmRedirect confirms that the node responds with a redirect to the given host.\nfunc (n *Node) ConfirmRedirect(host string) bool {\n\tv, _ := url.Parse(\"http:\/\/\" + n.APIAddr + \"\/db\/query\")\n\tv.RawQuery = url.Values{\"q\": []string{`SELECT * FROM foo`}}.Encode()\n\n\tresp, err := http.Get(v.String())\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer resp.Body.Close()\n\tfmt.Println(resp.StatusCode)\n\tif resp.StatusCode != http.StatusMovedPermanently {\n\t\treturn false\n\t}\n\tif resp.Header.Get(\"location\") != host {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc (n *Node) postExecute(stmt string) (string, error) {\n\tresp, err := http.Post(\"http:\/\/\"+n.APIAddr+\"\/db\/execute\", \"application\/json\", strings.NewReader(stmt))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body), nil\n}\n\n\/\/ Cluster represents a cluster of nodes.\ntype Cluster []*Node\n\n\/\/ Leader returns the leader node of a cluster.\nfunc (c Cluster) Leader() (*Node, error) {\n\tl, err := c[0].WaitForLeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.FindNodeByRaftAddr(l)\n}\n\n\/\/ WaitForNewLeader waits for the leader to change from the node passed in.\nfunc (c Cluster) WaitForNewLeader(old *Node) (*Node, error) {\n\ttimer := time.NewTimer(30 * time.Second)\n\tdefer timer.Stop()\n\tticker := time.NewTicker(100 * time.Millisecond)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-timer.C:\n\t\t\treturn nil, fmt.Errorf(\"timed out waiting for new leader\")\n\t\tcase <-ticker.C:\n\t\t\tl, err := c.Leader()\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !l.SameAs(old) {\n\t\t\t\treturn l, nil\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Followers returns the slice of nodes in the cluster that are followers.\nfunc (c Cluster) Followers() ([]*Node, error) {\n\tn, err := c[0].WaitForLeader()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tleader, err := c.FindNodeByRaftAddr(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar followers []*Node\n\tfor _, n := range c {\n\t\tif n != leader {\n\t\t\tfollowers = append(followers, n)\n\t\t}\n\t}\n\treturn followers, nil\n}\n\n\/\/ RemoveNode removes the given node from the list of nodes representing\n\/\/ a cluster.\nfunc (c Cluster) RemoveNode(node *Node) {\n\tfor i, n := range c {\n\t\tif n.RaftAddr == node.RaftAddr {\n\t\t\tc = append(c[:i], c[i+1:]...)\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ FindNodeByRaftAddr returns the node with the given Raft address.\nfunc (c Cluster) FindNodeByRaftAddr(addr string) (*Node, error) {\n\tfor _, n := range c {\n\t\tif n.RaftAddr == addr {\n\t\t\treturn n, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"node not found\")\n}\n\n\/\/ Deprovision deprovisions every node in the cluster.\nfunc (c Cluster) Deprovision() {\n\tfor _, n := range c {\n\t\tn.Deprovision()\n\t}\n}\n\n\/\/ Remove tells the cluster at n to remove the node at addr. Assumes n is the leader.\nfunc Remove(n *Node, addr string) error {\n\tb, err := json.Marshal(map[string]string{\"addr\": addr})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Attempt to remove node from leader.\n\tresp, err := http.Post(\"http:\/\/\"+n.APIAddr+\"\/remove\", \"application-type\/json\", bytes.NewReader(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"failed to remove node, leader returned: %s\", resp.Status)\n\t}\n\tdefer resp.Body.Close()\n\treturn nil\n}\n\n\/\/ DoJoinRequest sends a join request to nodeAddr, for raftAddr.\nfunc DoJoinRequest(nodeAddr, raftAddr string) (*http.Response, error) {\n\tb, err := json.Marshal(map[string]string{\"addr\": raftAddr})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := http.Post(\"http:\/\/\"+nodeAddr+\"\/join\", \"application-type\/json\", bytes.NewReader(b))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}\n\nfunc mustNewNode(enableSingle bool) *Node {\n\tnode := &Node{\n\t\tDir: mustTempDir(),\n\t}\n\n\tdbConf := store.NewDBConfig(\"\", false)\n\tnode.Store = store.New(&store.StoreConfig{\n\t\tDBConf: dbConf,\n\t\tDir:    node.Dir,\n\t\tTn:     mustMockTransport(\"localhost:0\"),\n\t})\n\tif err := node.Store.Open(enableSingle); err != nil {\n\t\tnode.Deprovision()\n\t\tpanic(fmt.Sprintf(\"failed to open store: %s\", err.Error()))\n\t}\n\tnode.RaftAddr = node.Store.Addr().String()\n\n\tnode.Service = httpd.New(\"localhost:0\", node.Store, nil)\n\tnode.Service.Expvar = true\n\tif err := node.Service.Start(); err != nil {\n\t\tnode.Deprovision()\n\t\tpanic(fmt.Sprintf(\"failed to start HTTP server: %s\", err.Error()))\n\t}\n\tnode.APIAddr = node.Service.Addr().String()\n\n\treturn node\n}\n\nfunc mustNewLeaderNode() *Node {\n\tnode := mustNewNode(true)\n\tif _, err := node.WaitForLeader(); err != nil {\n\t\tnode.Deprovision()\n\t\tpanic(\"node never became leader\")\n\t}\n\treturn node\n}\n\ntype mockTransport struct {\n\tln net.Listener\n}\n\nfunc mustMockTransport(addr string) *mockTransport {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tpanic(\"failed to create new transport\")\n\t}\n\treturn &mockTransport{ln}\n}\n\nfunc (m *mockTransport) Dial(addr string, timeout time.Duration) (net.Conn, error) {\n\treturn net.DialTimeout(\"tcp\", addr, timeout)\n}\n\nfunc (m *mockTransport) Accept() (net.Conn, error) { return m.ln.Accept() }\n\nfunc (m *mockTransport) Close() error { return m.ln.Close() }\n\nfunc (m *mockTransport) Addr() net.Addr { return m.ln.Addr() }\n\nfunc mustTempDir() string {\n\tvar err error\n\tpath, err := ioutil.TempDir(\"\", \"rqlilte-system-test-\")\n\tif err != nil {\n\t\tpanic(\"failed to create temp dir\")\n\t}\n\treturn path\n}\n\nfunc isJSON(s string) bool {\n\tvar js map[string]interface{}\n\treturn json.Unmarshal([]byte(s), &js) == nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package bot\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/bwmarrin\/discordgo\"\n\t\"go.uber.org\/zap\"\n)\n\ntype EmojiRole struct {\n\tEmojiId string `yaml:\"emojiId\"`\n\tRoleId  string `yaml:\"roleId\"`\n}\n\ntype DiscordEmojiRoleGroup struct {\n\tMessageTitle string      `yaml:\"messageTitle\"`\n\tMessageBody  string      `yaml:\"messageBody\"`\n\tRoles        []EmojiRole `yaml:\"roles\"`\n}\n\ntype DiscordRoleCfg struct {\n\tChannelId       string                  `yaml:\"channelId\"`\n\tEmojiRoleGroups []DiscordEmojiRoleGroup `yaml:\"emojiRoles\"`\n}\n\nfunc (d *DiscordAPI) StartRoleHandlers() {\n\td.listRoles()\n\td.clearRoleChannel()\n\td.createRoleMessages()\n\td.discord.AddHandler(d.roleAssignmentHandler)\n\tLogger.Info(\"Role assignment handler started\")\n}\n\nfunc (d DiscordAPI) roleAssignmentHandler(s *discordgo.Session, event *discordgo.MessageReactionAdd) {\n\n\t\/\/ skip if the event was from the bot\/app\n\tif event.UserID == d.Config.ClientId {\n\t\treturn\n\t}\n\n\t\/\/ only handle if the message is one we have configured\n\tif roles, ok := d.assignmentMsgs[event.MessageID]; ok {\n\n\t\t\/\/ Unicode emojis use the unicode character (name) as the id. Others use the name and integer as the id.\n\t\temojiId := event.Emoji.Name\n\t\tif event.Emoji.ID != \"\" {\n\t\t\temojiId = fmt.Sprintf(\":%s:%s\", event.Emoji.Name, event.Emoji.ID)\n\t\t}\n\n\t\tif roleId, ok := roles[emojiId]; ok {\n\t\t\t\/\/ get the user from the server\/guild\n\t\t\tmember, err := d.discord.GuildMember(d.Config.GuildId, event.UserID)\n\t\t\tif err != nil {\n\t\t\t\tLogger.Error(\"Unable to get member\", zap.Error(err))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tuserHadRole := false\n\t\t\t\/\/ if the member has the mapped role, remove it\n\t\t\tfor _, id := range member.Roles {\n\t\t\t\tif id == roleId {\n\t\t\t\t\td.removeRoleFromUser(event.UserID, roleId)\n\t\t\t\t\tuserHadRole = true \/\/ true, even if an attempt was made and failed\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ if the member does not have the mapped role, add it\n\t\t\tif !userHadRole {\n\t\t\t\td.addRoleToUser(event.UserID, roleId)\n\t\t\t}\n\n\t\t\t\/\/ DM the user the confirmation\n\t\t\trole, err := d.FindGuildRole(roleId)\n\t\t\tif err != nil {\n\t\t\t\tLogger.Error(\"Unable to find role\", zap.Error(err))\n\t\t\t}\n\t\t\tif userHadRole {\n\t\t\t\td.SendDM(event.UserID, fmt.Sprintf(\"The %s role has been removed\", role.Name))\n\t\t\t} else {\n\t\t\t\td.SendDM(event.UserID, fmt.Sprintf(\"You now have the %s role!\", role.Name))\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/ remove the users reaction. If the add\/remove failed, they can click it again to re-trigger\n\t\terr := d.discord.MessageReactionRemove(\n\t\t\tevent.ChannelID,\n\t\t\tevent.MessageID,\n\t\t\temojiId,\n\t\t\tevent.UserID,\n\t\t)\n\n\t\tif err != nil {\n\t\t\tLogger.Error(\"could not remove reaction from message\",\n\t\t\t\tzap.String(\"user\", event.UserID),\n\t\t\t\tzap.String(\"emoji\", emojiId),\n\t\t\t\tzap.Error(err))\n\t\t}\n\t}\n\n}\n\n\/\/ removes all messages entered by this bot in the channel. Uses the ClientID of the bot\/app\nfunc (d *DiscordAPI) clearRoleChannel() {\n\tchannelId := d.Config.RoleCfg.ChannelId\n\n\tmessages, err := d.discord.ChannelMessages(channelId, 50, \"\", \"\", \"\")\n\tif err != nil {\n\t\tLogger.Error(\"Unable to access channel messages\", zap.String(\"channelId\", channelId), zap.Error(err))\n\t\treturn\n\t}\n\tfor _, message := range messages {\n\t\tif message.Author.ID == d.Config.ClientId {\n\t\t\terr := d.discord.ChannelMessageDelete(channelId, message.ID)\n\t\t\tif err == nil {\n\t\t\t\tLogger.Info(\"Removed bot message\", zap.String(\"messageId\", message.ID))\n\t\t\t} else {\n\t\t\t\tLogger.Error(\"Unable to remove message\", zap.String(\"messageId\", message.ID), zap.Error(err))\n\t\t\t}\n\n\t\t}\n\t}\n}\n\n\/\/ creates messages in the channel and adds the emojis\nfunc (d *DiscordAPI) createRoleMessages() {\n\td.assignmentMsgs = make(map[string]map[string]string)\n\tfor _, group := range d.Config.RoleCfg.EmojiRoleGroups {\n\t\tmessageEmbed := discordgo.MessageEmbed{\n\t\t\tTitle:       group.MessageTitle,\n\t\t\tDescription: group.MessageBody,\n\t\t\tColor:       15581239,\n\t\t}\n\t\t\/\/ create the message\n\t\tmessage, err := d.discord.ChannelMessageSendEmbed(d.Config.RoleCfg.ChannelId, &messageEmbed)\n\t\tif err != nil {\n\t\t\tLogger.Error(\"Unable to create message\", zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\tLogger.Info(\"Added role message\", zap.String(\"message\", group.MessageTitle), zap.String(\"messageId\", message.ID))\n\n\t\t\/\/ add the emojis\n\t\temojiRoles := make(map[string]string)\n\t\tfor _, role := range group.Roles {\n\t\t\temojiRoles[role.EmojiId] = role.RoleId\n\t\t\terr := d.discord.MessageReactionAdd(d.Config.RoleCfg.ChannelId, message.ID, role.EmojiId)\n\t\t\tif err != nil {\n\t\t\t\tLogger.Error(\"Unable to add emoji to message\",\n\t\t\t\t\tzap.String(\"emojiId\", role.EmojiId),\n\t\t\t\t\tzap.String(\"messageId\", message.ID),\n\t\t\t\t\tzap.Error(err),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\td.assignmentMsgs[message.ID] = emojiRoles\n\t}\n}\n\nfunc (d DiscordAPI) addRoleToUser(userId string, roleId string) {\n\terr := d.discord.GuildMemberRoleAdd(d.Config.GuildId, userId, roleId)\n\tif err != nil {\n\t\tLogger.Error(\"could not add role\",\n\t\t\tzap.String(\"userId\", userId),\n\t\t\tzap.String(\"roleId\", roleId),\n\t\t\tzap.Error(err))\n\t} else {\n\t\tLogger.Info(\"added role to user\",\n\t\t\tzap.String(\"userId\", userId),\n\t\t\tzap.String(\"roleId\", roleId),\n\t\t)\n\t}\n}\n\nfunc (d DiscordAPI) removeRoleFromUser(userId string, roleId string) {\n\terr := d.discord.GuildMemberRoleRemove(d.Config.GuildId, userId, roleId)\n\tif err != nil {\n\t\tLogger.Error(\"could not remove role\", zap.Error(err))\n\t} else {\n\t\tLogger.Info(\"removed role from user\",\n\t\t\tzap.String(\"userId\", userId),\n\t\t\tzap.String(\"roleId\", roleId),\n\t\t)\n\t}\n}\nfunc (d *DiscordAPI) listRoles() {\n\troles, err := d.discord.GuildRoles(d.Config.GuildId)\n\n\tif err != nil {\n\t\tLogger.Error(\"Could not get roles\", zap.Error(err))\n\t\treturn\n\t}\n\n\tfor i, role := range roles {\n\t\tLogger.Info(fmt.Sprintf(\"Role %d\", i), zap.Any(\"role\", role))\n\t}\n}\n<commit_msg>Refactoring role assignment for reusability<commit_after>package bot\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/bwmarrin\/discordgo\"\n\t\"go.uber.org\/zap\"\n)\n\ntype EmojiRole struct {\n\tEmojiId string `yaml:\"emojiId\"`\n\tRoleId  string `yaml:\"roleId\"`\n}\n\ntype DiscordEmojiRoleGroup struct {\n\tMessageTitle string      `yaml:\"messageTitle\"`\n\tMessageBody  string      `yaml:\"messageBody\"`\n\tRoles        []EmojiRole `yaml:\"roles\"`\n}\n\ntype DiscordRoleCfg struct {\n\tChannelId       string                  `yaml:\"channelId\"`\n\tEmojiRoleGroups []DiscordEmojiRoleGroup `yaml:\"emojiRoles\"`\n}\n\nfunc (d *DiscordAPI) StartRoleHandlers() {\n\td.listRoles()\n\td.clearRoleChannel()\n\td.createRoleMessages()\n\td.discord.AddHandler(d.roleAssignmentHandler)\n\tLogger.Info(\"Role assignment handler started\")\n}\n\nfunc (d DiscordAPI) roleAssignmentHandler(s *discordgo.Session, event *discordgo.MessageReactionAdd) {\n\n\t\/\/ skip if the event was from the bot\/app\n\tif event.UserID == d.Config.ClientId {\n\t\treturn\n\t}\n\n\t\/\/ only handle if the message is one we have configured\n\tif roles, ok := d.assignmentMsgs[event.MessageID]; ok {\n\n\t\t\/\/ Unicode emojis use the unicode character (name) as the id. Others use the name and integer as the id.\n\t\temojiId := event.Emoji.Name\n\t\tif event.Emoji.ID != \"\" {\n\t\t\temojiId = fmt.Sprintf(\":%s:%s\", event.Emoji.Name, event.Emoji.ID)\n\t\t}\n\n\t\tif roleId, ok := roles[emojiId]; ok {\n\t\t\td.assignRoleToUser(event.UserID, roleId)\n\t\t}\n\n\t\t\/\/ remove the users reaction. If the add\/remove failed, they can click it again to re-trigger\n\t\terr := d.discord.MessageReactionRemove(\n\t\t\tevent.ChannelID,\n\t\t\tevent.MessageID,\n\t\t\temojiId,\n\t\t\tevent.UserID,\n\t\t)\n\n\t\tif err != nil {\n\t\t\tLogger.Error(\"could not remove reaction from message\",\n\t\t\t\tzap.String(\"user\", event.UserID),\n\t\t\t\tzap.String(\"emoji\", emojiId),\n\t\t\t\tzap.Error(err))\n\t\t}\n\t}\n\n}\n\nfunc (d *DiscordAPI) assignRoleToUser(userID, roleID string ) {\n\t\/\/ get the user from the server\/guild\n\tmember, err := d.discord.GuildMember(d.Config.GuildId, userID)\n\tif err != nil {\n\t\tLogger.Error(\"Unable to get member\", zap.Error(err))\n\t\treturn\n\t}\n\n\tuserHadRole := false\n\t\/\/ if the member has the mapped role, remove it\n\tfor _, id := range member.Roles {\n\t\tif id == roleID {\n\t\t\td.removeRoleFromUser(userID, roleID)\n\t\t\tuserHadRole = true \/\/ true, even if an attempt was made and failed\n\t\t}\n\t}\n\n\t\/\/ if the member does not have the mapped role, add it\n\tif !userHadRole {\n\t\td.addRoleToUser(userID, roleID)\n\t}\n\n\t\/\/ DM the user the confirmation\n\trole, err := d.FindGuildRole(roleID)\n\tif err != nil {\n\t\tLogger.Error(\"Unable to find role\", zap.Error(err))\n\t}\n\tif userHadRole {\n\t\td.SendDM(userID, fmt.Sprintf(\"The %s role has been removed\", role.Name))\n\t} else {\n\t\td.SendDM(userID, fmt.Sprintf(\"You now have the %s role!\", role.Name))\n\t}\n}\n\n\/\/ removes all messages entered by this bot in the channel. Uses the ClientID of the bot\/app\nfunc (d *DiscordAPI) clearRoleChannel() {\n\tchannelId := d.Config.RoleCfg.ChannelId\n\n\tmessages, err := d.discord.ChannelMessages(channelId, 50, \"\", \"\", \"\")\n\tif err != nil {\n\t\tLogger.Error(\"Unable to access channel messages\", zap.String(\"channelId\", channelId), zap.Error(err))\n\t\treturn\n\t}\n\tfor _, message := range messages {\n\t\tif message.Author.ID == d.Config.ClientId {\n\t\t\terr := d.discord.ChannelMessageDelete(channelId, message.ID)\n\t\t\tif err == nil {\n\t\t\t\tLogger.Info(\"Removed bot message\", zap.String(\"messageId\", message.ID))\n\t\t\t} else {\n\t\t\t\tLogger.Error(\"Unable to remove message\", zap.String(\"messageId\", message.ID), zap.Error(err))\n\t\t\t}\n\n\t\t}\n\t}\n}\n\n\/\/ creates messages in the channel and adds the emojis\nfunc (d *DiscordAPI) createRoleMessages() {\n\td.assignmentMsgs = make(map[string]map[string]string)\n\tfor _, group := range d.Config.RoleCfg.EmojiRoleGroups {\n\t\tmessageEmbed := discordgo.MessageEmbed{\n\t\t\tTitle:       group.MessageTitle,\n\t\t\tDescription: group.MessageBody,\n\t\t\tColor:       15581239,\n\t\t}\n\t\t\/\/ create the message\n\t\tmessage, err := d.discord.ChannelMessageSendEmbed(d.Config.RoleCfg.ChannelId, &messageEmbed)\n\t\tif err != nil {\n\t\t\tLogger.Error(\"Unable to create message\", zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\tLogger.Info(\"Added role message\", zap.String(\"message\", group.MessageTitle), zap.String(\"messageId\", message.ID))\n\n\t\t\/\/ add the emojis\n\t\temojiRoles := make(map[string]string)\n\t\tfor _, role := range group.Roles {\n\t\t\temojiRoles[role.EmojiId] = role.RoleId\n\t\t\terr := d.discord.MessageReactionAdd(d.Config.RoleCfg.ChannelId, message.ID, role.EmojiId)\n\t\t\tif err != nil {\n\t\t\t\tLogger.Error(\"Unable to add emoji to message\",\n\t\t\t\t\tzap.String(\"emojiId\", role.EmojiId),\n\t\t\t\t\tzap.String(\"messageId\", message.ID),\n\t\t\t\t\tzap.Error(err),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\td.assignmentMsgs[message.ID] = emojiRoles\n\t}\n}\n\nfunc (d DiscordAPI) addRoleToUser(userId string, roleId string) {\n\terr := d.discord.GuildMemberRoleAdd(d.Config.GuildId, userId, roleId)\n\tif err != nil {\n\t\tLogger.Error(\"could not add role\",\n\t\t\tzap.String(\"userId\", userId),\n\t\t\tzap.String(\"roleId\", roleId),\n\t\t\tzap.Error(err))\n\t} else {\n\t\tLogger.Info(\"added role to user\",\n\t\t\tzap.String(\"userId\", userId),\n\t\t\tzap.String(\"roleId\", roleId),\n\t\t)\n\t}\n}\n\nfunc (d DiscordAPI) removeRoleFromUser(userId string, roleId string) {\n\terr := d.discord.GuildMemberRoleRemove(d.Config.GuildId, userId, roleId)\n\tif err != nil {\n\t\tLogger.Error(\"could not remove role\", zap.Error(err))\n\t} else {\n\t\tLogger.Info(\"removed role from user\",\n\t\t\tzap.String(\"userId\", userId),\n\t\t\tzap.String(\"roleId\", roleId),\n\t\t)\n\t}\n}\nfunc (d *DiscordAPI) listRoles() {\n\troles, err := d.discord.GuildRoles(d.Config.GuildId)\n\n\tif err != nil {\n\t\tLogger.Error(\"Could not get roles\", zap.Error(err))\n\t\treturn\n\t}\n\n\tfor i, role := range roles {\n\t\tLogger.Info(fmt.Sprintf(\"Role %d\", i), zap.Any(\"role\", role))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package common\n\nimport (\n\t\"encoding\/base64\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"strings\"\n)\n\nfunc IsExist(filename string) bool {\n\t_, err := os.Stat(filename)\n\treturn err == nil\n}\n\nfunc MapReduce(map1, map2 map[string]interface{}) map[string]interface{} {\n\tfor ia, va := range map1 {\n\t\tswitch value := va.(type) {\n\t\tcase string:\n\t\t\tif value != \"\" && map2[ia] == \"\" {\n\t\t\t\tmap2[ia] = value\n\t\t\t}\n\t\tcase []string:\n\t\t\tmap2Value := reflect.ValueOf(map2[ia])\n\t\t\tif len(value) > 0 && map2Value.Len() == 0 {\n\t\t\t\tmap2[ia] = value\n\t\t\t}\n\t\tcase bool:\n\t\t\tmap2Value := reflect.ValueOf(map2[ia])\n\t\t\tif value == true && map2Value.Bool() == false {\n\t\t\t\tmap2[ia] = value\n\t\t\t}\n\t\t}\n\t}\n\n\treturn map2\n}\n\nfunc StructToMap(val interface{}) (mapVal map[string]interface{}, ok bool) {\n\tstructVal := reflect.Indirect(reflect.ValueOf(val))\n\ttyp := structVal.Type()\n\n\tmapVal = make(map[string]interface{})\n\n\tfor i := 0; i < typ.NumField(); i++ {\n\t\tfield := structVal.Field(i)\n\n\t\tif field.CanSet() {\n\t\t\tmapVal[typ.Field(i).Name] = field.Interface()\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc MapToStruct(mapVal map[string]interface{}, val interface{}) (ok bool) {\n\tstructVal := reflect.Indirect(reflect.ValueOf(val))\n\tfor name, elem := range mapVal {\n\t\tstructVal.FieldByName(name).Set(reflect.ValueOf(elem))\n\t}\n\n\treturn\n}\n\nfunc GetFullPath(path string) (fullPath string) {\n\tusr, _ := user.Current()\n\tfullPath = strings.Replace(path, \"~\", usr.HomeDir, 1)\n\tfullPath, _ = filepath.Abs(fullPath)\n\treturn fullPath\n}\n\nfunc GetMaxLength(list []string) (MaxLength int) {\n\tMaxLength = 0\n\tfor _, elem := range list {\n\t\tif MaxLength < len(elem) {\n\t\t\tMaxLength = len(elem)\n\t\t}\n\t}\n\treturn\n}\n\nfunc GetFilesBase64(list []string) (result string, err error) {\n\tvar data []byte\n\tfor _, path := range list {\n\n\t\tfullPath := GetFullPath(path)\n\n\t\t\/\/ open file\n\t\tfile, err := os.Open(fullPath)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tdefer file.Close()\n\n\t\tfile_data, err := ioutil.ReadAll(file)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tdata = append(data, file_data...)\n\t}\n\n\tresult = base64.StdEncoding.EncodeToString(data)\n\treturn result, err\n}\n<commit_msg>rcfile add newline<commit_after>package common\n\nimport (\n\t\"encoding\/base64\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"strings\"\n)\n\nfunc IsExist(filename string) bool {\n\t_, err := os.Stat(filename)\n\treturn err == nil\n}\n\nfunc MapReduce(map1, map2 map[string]interface{}) map[string]interface{} {\n\tfor ia, va := range map1 {\n\t\tswitch value := va.(type) {\n\t\tcase string:\n\t\t\tif value != \"\" && map2[ia] == \"\" {\n\t\t\t\tmap2[ia] = value\n\t\t\t}\n\t\tcase []string:\n\t\t\tmap2Value := reflect.ValueOf(map2[ia])\n\t\t\tif len(value) > 0 && map2Value.Len() == 0 {\n\t\t\t\tmap2[ia] = value\n\t\t\t}\n\t\tcase bool:\n\t\t\tmap2Value := reflect.ValueOf(map2[ia])\n\t\t\tif value == true && map2Value.Bool() == false {\n\t\t\t\tmap2[ia] = value\n\t\t\t}\n\t\t}\n\t}\n\n\treturn map2\n}\n\nfunc StructToMap(val interface{}) (mapVal map[string]interface{}, ok bool) {\n\tstructVal := reflect.Indirect(reflect.ValueOf(val))\n\ttyp := structVal.Type()\n\n\tmapVal = make(map[string]interface{})\n\n\tfor i := 0; i < typ.NumField(); i++ {\n\t\tfield := structVal.Field(i)\n\n\t\tif field.CanSet() {\n\t\t\tmapVal[typ.Field(i).Name] = field.Interface()\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc MapToStruct(mapVal map[string]interface{}, val interface{}) (ok bool) {\n\tstructVal := reflect.Indirect(reflect.ValueOf(val))\n\tfor name, elem := range mapVal {\n\t\tstructVal.FieldByName(name).Set(reflect.ValueOf(elem))\n\t}\n\n\treturn\n}\n\nfunc GetFullPath(path string) (fullPath string) {\n\tusr, _ := user.Current()\n\tfullPath = strings.Replace(path, \"~\", usr.HomeDir, 1)\n\tfullPath, _ = filepath.Abs(fullPath)\n\treturn fullPath\n}\n\nfunc GetMaxLength(list []string) (MaxLength int) {\n\tMaxLength = 0\n\tfor _, elem := range list {\n\t\tif MaxLength < len(elem) {\n\t\t\tMaxLength = len(elem)\n\t\t}\n\t}\n\treturn\n}\n\nfunc GetFilesBase64(list []string) (result string, err error) {\n\tvar data []byte\n\tfor _, path := range list {\n\n\t\tfullPath := GetFullPath(path)\n\n\t\t\/\/ open file\n\t\tfile, err := os.Open(fullPath)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tdefer file.Close()\n\n\t\tfile_data, err := ioutil.ReadAll(file)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tdata = append(data, file_data...)\n\t\tdata = append(data, '\\n')\n\t}\n\n\tresult = base64.StdEncoding.EncodeToString(data)\n\treturn result, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\t@author Robert\n*\/\n\npackage common\n\nimport (\n\t\"errors\"\n\t\"math\/rand\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strings\"\n\t\"unsafe\"\n)\n\nvar (\n\tletterAndNumberRunes = []rune(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\")\n\n\t\/\/ email validation regular expression\n\temailRegEx = regexp.MustCompile(`^[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,4}$`)\n)\n\n\/\/ IsEmailAddress returns true if str seems to be an email address\nfunc IsEmailAddress(str string) bool {\n\treturn emailRegEx.MatchString(str)\n}\n\n\/\/ UpdateStructFields() errors\nvar (\n\tErrNotStruct = errors.New(\"Destination must by struct or a pointer to struct\")\n)\n\n\/\/ UpdateStructFromMap can be used to update the fields of a structure by sending\n\/\/ the new field values in a map, wherer the key is the field name as in the struct\n\/\/ and the value is the new value that will be set.\n\/\/\n\/\/ Only those values in the map will be evaluated and updated.\n\/\/ Parameter destination must be a pointer, otherwise changes won't be reflected.\nfunc UpdateStructFromMap(destination interface{}, source map[string]interface{}) (err error) {\n\n\t\/\/ to avoid panic, type of 'destination' must be a struct or a pointer\n\tif reflect.TypeOf(destination).Kind() == reflect.Struct || reflect.TypeOf(destination).Kind() == reflect.Ptr {\n\t\tif ps := reflect.ValueOf(destination); ps.IsValid() {\n\t\t\ts := ps.Elem()\n\n\t\t\tif s.Kind() == reflect.Struct {\n\t\t\t\tfor k, v := range source {\n\t\t\t\t\t\/\/ retrieve field from struct\n\t\t\t\t\tif field := s.FieldByName(k); field.IsValid() {\n\n\t\t\t\t\t\tif field.CanSet() {\n\n\t\t\t\t\t\t\t\/\/ set field value based on the type\n\t\t\t\t\t\t\t\/\/ note: not all types are supported, so test and add as needed\n\t\t\t\t\t\t\tswitch field.Kind() {\n\n\t\t\t\t\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t\t\t\t\t\tfield.SetInt(v.(int64))\n\t\t\t\t\t\t\tcase reflect.String:\n\t\t\t\t\t\t\t\tfield.SetString(v.(string))\n\t\t\t\t\t\t\tcase reflect.Bool:\n\t\t\t\t\t\t\t\tfield.SetBool(v.(bool))\n\t\t\t\t\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\t\t\t\t\tfield.SetFloat(v.(float64))\n\t\t\t\t\t\t\tcase reflect.Ptr:\n\t\t\t\t\t\t\t\tfield.SetPointer(v.(unsafe.Pointer))\n\t\t\t\t\t\t\tcase reflect.Complex64, reflect.Complex128:\n\t\t\t\t\t\t\t\tfield.SetComplex(v.(complex128))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = ErrNotStruct\n\t\t\t}\n\t\t}\n\t} else {\n\t\terr = ErrNotStruct\n\t}\n\n\treturn\n}\n\n\/\/ Random generates a random number between min and max.\n\/\/ Keep in mind that random seed must be initialized before. Example:\n\/\/ \t\trand.Seed(time.Now().Unix())\nfunc Random(min, max int) int {\n\treturn rand.Intn(max-min) + min\n}\n\n\/\/ RandomString generates a random string of the specified length.\n\/\/ Keep in mind that random seed must be initialized before. Example:\n\/\/ \t\trand.Seed(time.Now().Unix())\nfunc RandomString(n int) string {\n\tb := make([]rune, n)\n\tfor i := range b {\n\t\tb[i] = letterAndNumberRunes[rand.Intn(len(letterAndNumberRunes))]\n\t}\n\treturn string(b)\n}\n\n\/\/ MaskString creates a mask with `maskChar` for the indicated string `s`.\n\/\/ If noMaskLeft and noMaskRight equals -1, then all the string is masked.\nfunc MaskString(s string, noMaskLeft, noMaskRight int, maskChar string) (masked string) {\n\n\t\/\/ return all masked string if applies\n\tif len(s) <= noMaskLeft+noMaskRight || (noMaskLeft == -1 && noMaskRight == -1) {\n\t\tmasked = strings.Repeat(maskChar, len(s))\n\t\treturn\n\t}\n\n\tif noMaskLeft == -1 {\n\t\tnoMaskLeft = 0\n\t}\n\n\tif noMaskRight == -1 {\n\t\tnoMaskRight = 0\n\t}\n\n\tsLen := len(s)\n\n\tleftStr := s[:noMaskLeft]\n\trightStr := s[sLen-noMaskRight:]\n\tmiddle := strings.Repeat(maskChar, sLen-len(leftStr)-len(rightStr))\n\n\tmasked = leftStr + middle + rightStr\n\treturn\n}\n\n\/\/ FindInStringArray searches for the indicated element 'elem' in array 'a'\nfunc FindInStringArray(elem string, a []string) (e string, found bool) {\n\tfor i := range a {\n\t\tif a[i] == elem {\n\t\t\treturn elem, true\n\t\t}\n\t}\n\n\treturn \"\", false\n}\n\n\/\/ FindInIntgArray searches for the indicated element 'elem' in array 'a'\nfunc FindInIntgArray(elem int64, a []int64) (e int64, found bool) {\n\tfor i := range a {\n\t\tif a[i] == elem {\n\t\t\treturn elem, true\n\t\t}\n\t}\n\n\treturn 0, false\n}\n\n\/\/ GetNonNullFields returns an array with all the fields that\n\/\/ aren't nil in the structure's instance\nfunc GetNonNullFields(i interface{}, tagName string) (fields []string) {\n\n\tvar e reflect.Value\n\tv := reflect.ValueOf(i)\n\n\tif v.Kind() == reflect.Struct {\n\t\te = v\n\t} else if v.Kind() == reflect.Ptr {\n\t\te = v.Elem()\n\t} else {\n\t\t\/\/ non applicable\n\t\treturn\n\t}\n\n\tfor f := 0; f < e.NumField(); f++ {\n\t\tprocess := false\n\t\tfieldInstance := e.Type().Field(f)\n\t\tfieldKind := e.Type().Kind()\n\n\t\t\/\/ skip structs and pointers to structs\n\t\tswitch fieldKind {\n\t\tcase reflect.Ptr:\n\t\t\tif e.Field(f).Elem().Kind() != reflect.Struct {\n\t\t\t\tprocess = true\n\t\t\t}\n\t\tdefault:\n\t\t\tprocess = true\n\t\t}\n\n\t\tif process {\n\t\t\tif !e.Field(f).IsNil() {\n\t\t\t\tif tagName != \"\" {\n\t\t\t\t\tif jsonTag := fieldInstance.Tag.Get(tagName); jsonTag != \"\" && jsonTag != \"-\" {\n\t\t\t\t\t\tfieldName := strings.Split(jsonTag, \",\")[0]\n\t\t\t\t\t\tfields = append(fields, fieldName)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfields = append(fields, fieldInstance.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n<commit_msg>use random source for number generation<commit_after>\/*\n\t@author Robert\n*\/\n\npackage common\n\nimport (\n\t\"errors\"\n\t\"math\/rand\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\t\"unsafe\"\n)\n\nvar (\n\tletterAndNumberRunes = []rune(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\")\n\n\t\/\/ email validation regular expression\n\temailRegEx = regexp.MustCompile(`^[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,4}$`)\n\n\trandomGenerator = rand.New(rand.NewSource(time.Now().Unix()))\n)\n\n\/\/ IsEmailAddress returns true if str seems to be an email address\nfunc IsEmailAddress(str string) bool {\n\treturn emailRegEx.MatchString(str)\n}\n\n\/\/ UpdateStructFields() errors\nvar (\n\tErrNotStruct = errors.New(\"Destination must by struct or a pointer to struct\")\n)\n\n\/\/ UpdateStructFromMap can be used to update the fields of a structure by sending\n\/\/ the new field values in a map, wherer the key is the field name as in the struct\n\/\/ and the value is the new value that will be set.\n\/\/\n\/\/ Only those values in the map will be evaluated and updated.\n\/\/ Parameter destination must be a pointer, otherwise changes won't be reflected.\nfunc UpdateStructFromMap(destination interface{}, source map[string]interface{}) (err error) {\n\n\t\/\/ to avoid panic, type of 'destination' must be a struct or a pointer\n\tif reflect.TypeOf(destination).Kind() == reflect.Struct || reflect.TypeOf(destination).Kind() == reflect.Ptr {\n\t\tif ps := reflect.ValueOf(destination); ps.IsValid() {\n\t\t\ts := ps.Elem()\n\n\t\t\tif s.Kind() == reflect.Struct {\n\t\t\t\tfor k, v := range source {\n\t\t\t\t\t\/\/ retrieve field from struct\n\t\t\t\t\tif field := s.FieldByName(k); field.IsValid() {\n\n\t\t\t\t\t\tif field.CanSet() {\n\n\t\t\t\t\t\t\t\/\/ set field value based on the type\n\t\t\t\t\t\t\t\/\/ note: not all types are supported, so test and add as needed\n\t\t\t\t\t\t\tswitch field.Kind() {\n\n\t\t\t\t\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t\t\t\t\t\tfield.SetInt(v.(int64))\n\t\t\t\t\t\t\tcase reflect.String:\n\t\t\t\t\t\t\t\tfield.SetString(v.(string))\n\t\t\t\t\t\t\tcase reflect.Bool:\n\t\t\t\t\t\t\t\tfield.SetBool(v.(bool))\n\t\t\t\t\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\t\t\t\t\tfield.SetFloat(v.(float64))\n\t\t\t\t\t\t\tcase reflect.Ptr:\n\t\t\t\t\t\t\t\tfield.SetPointer(v.(unsafe.Pointer))\n\t\t\t\t\t\t\tcase reflect.Complex64, reflect.Complex128:\n\t\t\t\t\t\t\t\tfield.SetComplex(v.(complex128))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = ErrNotStruct\n\t\t\t}\n\t\t}\n\t} else {\n\t\terr = ErrNotStruct\n\t}\n\n\treturn\n}\n\n\/\/ Random generates a random number between min and max.\n\/\/ Keep in mind that random seed must be initialized before. Example:\n\/\/ \t\trand.Seed(time.Now().Unix())\nfunc Random(min, max int) int {\n\treturn rand.Intn(max-min) + min\n}\n\n\/\/ RandomString generates a random string of the specified length.\n\/\/ Keep in mind that random seed must be initialized before. Example:\n\/\/ \t\trand.Seed(time.Now().Unix())\nfunc RandomString(n int) string {\n\tb := make([]rune, n)\n\tfor i := range b {\n\t\tb[i] = letterAndNumberRunes[rand.Intn(len(letterAndNumberRunes))]\n\t}\n\treturn string(b)\n}\n\n\/\/ MaskString creates a mask with `maskChar` for the indicated string `s`.\n\/\/ If noMaskLeft and noMaskRight equals -1, then all the string is masked.\nfunc MaskString(s string, noMaskLeft, noMaskRight int, maskChar string) (masked string) {\n\n\t\/\/ return all masked string if applies\n\tif len(s) <= noMaskLeft+noMaskRight || (noMaskLeft == -1 && noMaskRight == -1) {\n\t\tmasked = strings.Repeat(maskChar, len(s))\n\t\treturn\n\t}\n\n\tif noMaskLeft == -1 {\n\t\tnoMaskLeft = 0\n\t}\n\n\tif noMaskRight == -1 {\n\t\tnoMaskRight = 0\n\t}\n\n\tsLen := len(s)\n\n\tleftStr := s[:noMaskLeft]\n\trightStr := s[sLen-noMaskRight:]\n\tmiddle := strings.Repeat(maskChar, sLen-len(leftStr)-len(rightStr))\n\n\tmasked = leftStr + middle + rightStr\n\treturn\n}\n\n\/\/ FindInStringArray searches for the indicated element 'elem' in array 'a'\nfunc FindInStringArray(elem string, a []string) (e string, found bool) {\n\tfor i := range a {\n\t\tif a[i] == elem {\n\t\t\treturn elem, true\n\t\t}\n\t}\n\n\treturn \"\", false\n}\n\n\/\/ FindInIntgArray searches for the indicated element 'elem' in array 'a'\nfunc FindInIntgArray(elem int64, a []int64) (e int64, found bool) {\n\tfor i := range a {\n\t\tif a[i] == elem {\n\t\t\treturn elem, true\n\t\t}\n\t}\n\n\treturn 0, false\n}\n\n\/\/ GetNonNullFields returns an array with all the fields that\n\/\/ aren't nil in the structure's instance\nfunc GetNonNullFields(i interface{}, tagName string) (fields []string) {\n\n\tvar e reflect.Value\n\tv := reflect.ValueOf(i)\n\n\tif v.Kind() == reflect.Struct {\n\t\te = v\n\t} else if v.Kind() == reflect.Ptr {\n\t\te = v.Elem()\n\t} else {\n\t\t\/\/ non applicable\n\t\treturn\n\t}\n\n\tfor f := 0; f < e.NumField(); f++ {\n\t\tprocess := false\n\t\tfieldInstance := e.Type().Field(f)\n\t\tfieldKind := e.Type().Kind()\n\n\t\t\/\/ skip structs and pointers to structs\n\t\tswitch fieldKind {\n\t\tcase reflect.Ptr:\n\t\t\tif e.Field(f).Elem().Kind() != reflect.Struct {\n\t\t\t\tprocess = true\n\t\t\t}\n\t\tdefault:\n\t\t\tprocess = true\n\t\t}\n\n\t\tif process {\n\t\t\tif !e.Field(f).IsNil() {\n\t\t\t\tif tagName != \"\" {\n\t\t\t\t\tif jsonTag := fieldInstance.Tag.Get(tagName); jsonTag != \"\" && jsonTag != \"-\" {\n\t\t\t\t\t\tfieldName := strings.Split(jsonTag, \",\")[0]\n\t\t\t\t\t\tfields = append(fields, fieldName)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfields = append(fields, fieldInstance.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package again\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"reflect\"\n)\n\nfunc jsonToJson(r io.Reader, w io.Writer) {\n\tturnBothCranks(\n\t\tNewJsonDecoder(r),\n\t\tNewJsonEncoder(w),\n\t)\n}\n\nfunc turnBothCranks(tokenSrc TokenSrc, tokenSink TokenSink) error {\n\tvar tok Token\n\tvar srcDone, sinkDone bool\n\tvar err error\n\tfor {\n\t\tsrcDone, err = tokenSrc.Step(&tok)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsinkDone, err = tokenSink.Step(&tok)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif srcDone {\n\t\t\tif sinkDone {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"src at end of item but sink expects more\")\n\t\t}\n\t}\n}\n\n\/*\n\tFill with address of primitive (or []byte), or the magic const tokens\n\tfor beginning and ending of maps and arrays.\n\n\tDecoder implementations are encouraged to use `util.DecodeBag` to contain\n\tprimitives during decode, then return the address of the relevant\n\tprimitive field from the `DecodeBag` as a `Token`.  This avoids repeated\n\tpointer allocations.\n*\/\ntype Token interface{}\n\nconst (\n\tToken_MapOpen  = '{'\n\tToken_MapClose = '}'\n\tToken_ArrOpen  = '['\n\tToken_ArrClose = ']'\n)\n\ntype TokenSrc interface {\n\tStep(fillme *Token) (done bool, err error)\n\tReset()\n}\n\ntype TokenSink interface {\n\tStep(consume *Token) (done bool, err error)\n\tReset()\n}\n\n\/\/\n\/\/ Constructors\n\/\/\n\nfunc NewJsonDecoder(r io.Reader \/* optional *JsonSchemaNotes *\/) TokenSrc  { return nil }\nfunc NewJsonEncoder(w io.Writer \/* optional *JsonSchemaNotes *\/) TokenSink { return nil }\n\nfunc NewVarTokenizer(v interface{} \/* TODO visitmagicks *\/) TokenSrc { return nil }\nfunc NewVarReceiver(v interface{} \/* TODO visitmagicks *\/) TokenSink { return nil }\n\ntype varReceiver struct {\n\tstep func(*Token)\n\tdone bool\n\terr  error\n}\n\n\/\/ used at initialization to figure out the first step given the type of var\n\/\/\nfunc (vr *varReceiver) stepFor(v interface{}) func(*Token) {\n\tswitch v.(type) {\n\tcase *interface{}:\n\t\treturn vr.step_AcceptAny \/\/ pick between a literal, and `map[string]interface{}` and `[]interface{}` based on the next token to come in.\n\tcase *string, *[]byte:\n\t\treturn vr.step_AcceptLiteral\n\tcase *int, *int8, *int16, *int32, *int64:\n\t\treturn vr.step_AcceptLiteral\n\tcase *uint, *uint8, *uint16, *uint32, *uint64:\n\t\treturn vr.step_AcceptLiteral\n\tdefault:\n\t\t\/\/ TODO mustAddressable check goes here.\n\t\tif reflect.TypeOf(v).Kind() == reflect.Interface {\n\t\t\t\/\/ special path because we can recycle the decoder machines, if they implement resettable.\n\t\t}\n\t\t\/\/ any other concrete type or particular interface:\n\t\t\/\/  must have its own visit func defined.\n\t\t\/\/  we don't know if it expects to be a map, lit, arr, etc until it takes over.\n\t\t\/\/  (the rest of our functions here are the exception: they're half inlined here -- TODO maybe don't be like that; this lookup only makes sense for top level wtf-is-this'es)\n\t\tpanic(\"TODO mappersuite lookup\")\n\t}\n}\n\nfunc (vr *varReceiver) step_AcceptAny(tok *Token) {\n\t\/\/ If it's a special state, start an object.\n\t\/\/  (Or, blow up if its a special state that's silly).\n\tswitch *tok {\n\tcase Token_MapOpen:\n\t\tvar v map[string]interface{} \/\/ FIXME this should still be being pushed into top ref\n\t\tstep := vr.stepFor(v)        \/\/ Get the step.\n\t\tstep(tok)                    \/\/ Call it (with the same token, so it can consume it); it will set the next `vr.step`.\n\t\treturn\n\tcase Token_ArrOpen:\n\t\tvar v []interface{}   \/\/ FIXME this should still be being pushed into top ref\n\t\tstep := vr.stepFor(v) \/\/ Get the step.\n\t\tstep(tok)             \/\/ Call it (with the same token, so it can consume it); it will set the next `vr.step`.\n\t\treturn\n\tcase Token_MapClose:\n\t\tpanic(\"unexpected mapClose; expected start of value\")\n\tcase Token_ArrClose:\n\t\tpanic(\"unexpected arrClose; expected start of value\")\n\t}\n\t\/\/ If it wasn't the start of composite, check for a literal of understood kind.\n\tvr.step_AcceptLiteral(tok)\n}\n\nfunc (vr *varReceiver) step_AcceptLiteral(tok *Token) {\n\tacceptLiteral(nil \/* ???*\/, tok)\n}\n\nfunc acceptLiteral(v interface{}, tok *Token) {\n\tswitch v2 := v.(type) {\n\tcase *string:\n\t\t*v2 = (*tok).(string)\n\tcase *[]byte:\n\t\t\/\/ FIXME again, need the top ref to push into\n\tcase *int, *int8, *int16, *int32, *int64:\n\t\t\/\/ FIXME again, need the top ref to push into\n\tcase *uint, *uint8, *uint16, *uint32, *uint64:\n\t\t\/\/ FIXME again, need the top ref to push into\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unexpected literal token of unknown type %T\", *tok))\n\t}\n}\n\n\/*\n\tSuppose we have the following var to unmarshal into:\n\n\t\tvar thingy SomeType\n\n\tWhere SomeType is defined as:\n\n\t\ttype SomeType struct {\n\t\t\tAnInt int\n\t\t\tSomething interface{}\n\t\t}\n\n\tThe flow of a VarReciever working on this will be something like the following:\n\n\t\t- Begin handling a var of type `SomeType`.\n\t\t- Look up the hander for that type info.\n\t\t- The handler is accepts the val ref, and returns a step function.\n\t\t- The step function is called with the token.\n\t\t- [Much work ensues.]\n\t\t- If the step function returns done, we return entirely;\n\t\t  otherwise we hang onto the next stepFunc, and return.\n\n\tThe flow of the specific handler for SomeType will look like this:\n\n\t\t- Expect a MapOpen token.\n\t\t- Expect a MapKey token.  Return a step func expecting that matching value.\n\t\t  - When called with the next token, this step func grabs the ref\n\t\t    of the struct field matching the name we were primed with...\n\t\t  - And calls dispatch on the whole thing.\n\t\t  - (Generally this func looks like it needs {fillingName string, rest},\n\t\t    so it can tell what value grab the ref to fill, and decide whether\n\t\t\tto return \"expect all done\" step.)\n\t\t- At any point, it may receive MapClose, which will jump to a check\n\t\t  that all fields are either noted as filled (requires sidebar) or\n\t\t  are tagged as omitEmpty.\n*\/\n\n\/\/ Returns an atlas so we can use this to build the contin-passing machine without bothering you.\nfunc HandleMe(vreal interface{}) (\n\tvmediate interface{},\n\tatl *Atlas,\n\tafter func(), \/* closure, already has vreal and vmediate refs *\/\n) {\n\treturn nil, nil, nil\n}\n\ntype Atlas struct{}\n\ntype atlasDecoderMachine struct {\n\tval      reflect.Value \/\/ We're filling this.\n\tatl      *Atlas        \/\/ Our directions.\n\tstep     func(*Token)  \/\/ The next step.\n\tkey      string        \/\/ The key consumed by the prev `step_AcceptKey`.\n\tkeysDone []string      \/\/ List of keys we've completed already (repeats aren't wanted).\n}\n\nfunc NewAtlasDecoderMachine(into reflect.Value, atl *Atlas) *atlasDecoderMachine {\n\t\/\/ TODO this return type should prob have some interface that covers it sufficiently.\n\tdm := &atlasDecoderMachine{\n\t\tatl: atl,\n\t}\n\tdm.Reset(into)\n\treturn dm\n}\n\nfunc (dm *atlasDecoderMachine) Reset(into reflect.Value) {\n\tdm.val = into\n\tdm.step = dm.step_Initial\n\tdm.key = \"\"\n\tdm.keysDone = dm.keysDone[0:0]\n}\n\nfunc (dm *atlasDecoderMachine) step_Initial(tok *Token) {\n\tswitch *tok {\n\tcase Token_MapOpen:\n\t\t\/\/ Great.  Consumed.\n\t\tdm.step = dm.step_AcceptKey\n\tcase Token_ArrOpen:\n\t\tpanic(\"unexpected arrOpen; expected start of struct\")\n\tcase Token_MapClose:\n\t\tpanic(\"unexpected mapClose; expected start of struct\")\n\tcase Token_ArrClose:\n\t\tpanic(\"unexpected arrClose; expected start of struct\")\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unexpected literal of type %T; expected start of struct\", *tok))\n\t}\n}\n\nfunc (dm *atlasDecoderMachine) step_AcceptKey(tok *Token) {\n\tswitch *tok {\n\tcase Token_MapOpen:\n\t\tpanic(\"unexpected mapOpen; expected map key\")\n\tcase Token_ArrOpen:\n\t\tpanic(\"unexpected arrOpen; expected map key\")\n\tcase Token_MapClose:\n\t\tdm.handleEnd()\n\tcase Token_ArrClose:\n\t\tpanic(\"unexpected arrClose; expected map key\")\n\t}\n\tswitch k := (*tok).(type) {\n\tcase *string:\n\t\tdm.key = *k\n\t\tdm.mustAcceptKey(*k)\n\t\t\/\/dm.step = dm.step_AcceptValue\n\t\t\/\/ actually we might wanna just push up our plea now --\n\t\t\/\/  this saves us from having to see and forward the token at all,\n\t\t\/\/  and makes the pattern of fab-var-filler, ret step func(token) consistent.\n\t\t\/\/  if you *really* wanted to implement a breakout for known prims, you could still do that branch here.\n\t\t\/\/  HANG ON, nope: keep it in the value step and keep the tok passdown.\n\t\t\/\/   do it for parity with arrays, which must have that step\n\t\t\/\/   and accept that token during it so they can check for end there.\n\t\t\/*\n\t\t\tdriver.Fill(\n\t\t\t\ttok, \/\/ still meant for next person and the real step is to come; we just had to figure out types, here.\n\t\t\t\tdm.Addr(dm.key),\n\t\t\t\tdm.step_postValue(), \/\/ driver returns to us after the value is done by calling this.\n\t\t\t\t    \/\/ may actually be that we stash that stepfunc, and give driver more general self pointer and Resume func in interface.\n\t\t\t)\n\t\t*\/\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unexpected literal of type %T; expected start of struct\", *tok))\n\t}\n}\nfunc (dm *atlasDecoderMachine) mustAcceptKey(k string) {\n\tfor _, x := range dm.keysDone {\n\t\tif x == k {\n\t\t\tpanic(fmt.Errorf(\"repeated key %q\", k))\n\t\t}\n\t}\n\tdm.keysDone = append(dm.keysDone, k)\n}\nfunc (dm *atlasDecoderMachine) addr(k string) interface{} {\n\t_ = dm.atl\n\treturn nil \/\/ TODO\n\t\/\/ n.b. this is one of the spots where i can't decide if &thing or reflect.Value is better\n\t\/\/ but either way we may want to define a `Slot` type alias to make it readable\n}\n\nfunc (dm *atlasDecoderMachine) step_AcceptValue(tok *Token) {\n}\n\nfunc (dm *atlasDecoderMachine) handleEnd() {\n\t\/\/ TODO check for all filled, etc.  then set terminal states.\n}\n<commit_msg>Factor apart the wildcard machines.<commit_after>package again\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"reflect\"\n)\n\nfunc jsonToJson(r io.Reader, w io.Writer) {\n\tturnBothCranks(\n\t\tNewJsonDecoder(r),\n\t\tNewJsonEncoder(w),\n\t)\n}\n\nfunc turnBothCranks(tokenSrc TokenSrc, tokenSink TokenSink) error {\n\tvar tok Token\n\tvar srcDone, sinkDone bool\n\tvar err error\n\tfor {\n\t\tsrcDone, err = tokenSrc.Step(&tok)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsinkDone, err = tokenSink.Step(&tok)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif srcDone {\n\t\t\tif sinkDone {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"src at end of item but sink expects more\")\n\t\t}\n\t}\n}\n\n\/*\n\tFill with address of primitive (or []byte), or the magic const tokens\n\tfor beginning and ending of maps and arrays.\n\n\tDecoder implementations are encouraged to use `util.DecodeBag` to contain\n\tprimitives during decode, then return the address of the relevant\n\tprimitive field from the `DecodeBag` as a `Token`.  This avoids repeated\n\tpointer allocations.\n*\/\ntype Token interface{}\n\nconst (\n\tToken_MapOpen  = '{'\n\tToken_MapClose = '}'\n\tToken_ArrOpen  = '['\n\tToken_ArrClose = ']'\n)\n\ntype TokenSrc interface {\n\tStep(fillme *Token) (done bool, err error)\n\tReset()\n}\n\ntype TokenSink interface {\n\tStep(consume *Token) (done bool, err error)\n\tReset()\n}\n\n\/\/\n\/\/ Constructors\n\/\/\n\nfunc NewJsonDecoder(r io.Reader \/* optional *JsonSchemaNotes *\/) TokenSrc  { return nil }\nfunc NewJsonEncoder(w io.Writer \/* optional *JsonSchemaNotes *\/) TokenSink { return nil }\n\nfunc NewVarTokenizer(v interface{} \/* TODO visitmagicks *\/) TokenSrc { return nil }\nfunc NewVarReceiver(v interface{} \/* TODO visitmagicks *\/) TokenSink { return nil }\n\ntype varReceiver struct {\n\tstep func(*Token) (done bool, err error)\n\tdone bool\n\terr  error\n}\n\n\/\/ used at initialization to figure out the first step given the type of var\n\/\/\nfunc (vr *varReceiver) stepFor(v interface{}) func(*Token) (done bool, err error) {\n\tswitch v.(type) {\n\t\/\/ For total wildcards:\n\t\/\/  Return a machine that will pick between a literal or `map[string]interface{}`\n\t\/\/  or `[]interface{}` based on the next token.\n\tcase *interface{}:\n\t\treturn wildcardStep(v)\n\t\/\/ For single literals:\n\t\/\/  we have a single machine that handles all these.\n\tcase *string, *[]byte,\n\t\t*int, *int8, *int16, *int32, *int64,\n\t\t*uint, *uint8, *uint16, *uint32, *uint64:\n\t\tdec := &literalDecoderMachine{}\n\t\tdec.Reset(v)\n\t\treturn dec.Step\n\t\/\/ Anything that has real type info:\n\t\/\/  ... Plaaaay ball!\n\tdefault:\n\t\t\/\/ TODO mustAddressable check goes here.\n\t\tif reflect.TypeOf(v).Kind() == reflect.Interface {\n\t\t\t\/\/ special path because we can recycle the decoder machines, if they implement resettable.\n\t\t}\n\t\t\/\/ any other concrete type or particular interface:\n\t\t\/\/  must have its own visit func defined.\n\t\t\/\/  we don't know if it expects to be a map, lit, arr, etc until it takes over.\n\t\t\/\/  (the rest of our functions here are the exception: they're half inlined here -- TODO maybe don't be like that; this lookup only makes sense for top level wtf-is-this'es)\n\t\tpanic(\"TODO mappersuite lookup\")\n\t}\n}\n\nfunc wildcardStep(target interface{}) func(*Token) (bool, error) {\n\treturn func(tok *Token) (done bool, err error) {\n\t\t\/\/ If it's a special state, start an object.\n\t\t\/\/  (Or, blow up if its a special state that's silly).\n\t\tswitch *tok {\n\t\tcase Token_MapOpen:\n\t\t\t\/\/ Fill in our wildcard ref with a blank map,\n\t\t\t\/\/  and make a new machine for it; hand off everything.\n\t\t\ttarget = make(map[string]interface{})\n\t\t\tdec := &wildcardMapDecoderMachine{}\n\t\t\tdec.Reset(target)\n\t\t\treturn dec.Step(tok)\n\t\tcase Token_ArrOpen:\n\t\t\t\/\/ TODO same as maps, but with a machine for arrays\n\t\t\tpanic(\"NYI\")\n\t\tcase Token_MapClose:\n\t\t\treturn true, fmt.Errorf(\"unexpected mapClose; expected start of value\")\n\t\tcase Token_ArrClose:\n\t\t\treturn true, fmt.Errorf(\"unexpected arrClose; expected start of value\")\n\t\tdefault:\n\t\t\t\/\/ If it wasn't the start of composite, shell out to the machine for literals.\n\t\t\tdec := &literalDecoderMachine{}\n\t\t\tdec.Reset(target)\n\t\t\treturn dec.Step(tok)\n\t\t}\n\t}\n}\n\ntype wildcardMapDecoderMachine struct {\n\ttarget map[string]interface{}\n\tstep   func(*Token) (done bool, err error)\n\tkey    string \/\/ The key consumed by the prev `step_AcceptKey`.\n}\n\nfunc (dm *wildcardMapDecoderMachine) Reset(target interface{}) {\n\tdm.target = target.(map[string]interface{})\n\tdm.step = dm.step_Initial\n\tdm.key = \"\"\n}\n\nfunc (dm *wildcardMapDecoderMachine) Step(tok *Token) (done bool, err error) {\n\treturn dm.step(tok)\n}\n\nfunc (dm *wildcardMapDecoderMachine) step_Initial(tok *Token) (done bool, err error) {\n\t\/\/ If it's a special state, start an object.\n\t\/\/  (Or, blow up if its a special state that's silly).\n\tswitch *tok {\n\tcase Token_MapOpen:\n\t\t\/\/ Great.  Consumed.\n\t\tdm.step = dm.step_AcceptKey\n\t\treturn false, nil\n\tcase Token_ArrOpen:\n\t\treturn true, fmt.Errorf(\"unexpected arrOpen; expected start of map\")\n\tcase Token_MapClose:\n\t\treturn true, fmt.Errorf(\"unexpected mapClose; expected start of map\")\n\tcase Token_ArrClose:\n\t\treturn true, fmt.Errorf(\"unexpected arrClose; expected start of map\")\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unexpected literal of type %T; expected start of map\", *tok))\n\t}\n}\nfunc (dm *wildcardMapDecoderMachine) step_AcceptKey(tok *Token) (done bool, err error) {\n\tswitch *tok {\n\tcase Token_MapOpen:\n\t\treturn true, fmt.Errorf(\"unexpected mapOpen; expected map key\")\n\tcase Token_ArrOpen:\n\t\treturn true, fmt.Errorf(\"unexpected arrOpen; expected map key\")\n\tcase Token_MapClose:\n\t\t\/\/ no special checks for ends of wildcard map; no such thing as incomplete.\n\t\treturn true, nil\n\tcase Token_ArrClose:\n\t\treturn true, fmt.Errorf(\"unexpected arrClose; expected map key\")\n\t}\n\tswitch k := (*tok).(type) {\n\tcase *string:\n\t\tif err = dm.mustAcceptKey(*k); err != nil {\n\t\t\treturn true, err\n\t\t}\n\t\tdm.key = *k\n\t\tdm.step = dm.step_AcceptValue\n\t\treturn false, nil\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unexpected literal of type %T; expected start of struct\", *tok))\n\t}\n}\nfunc (dm *wildcardMapDecoderMachine) mustAcceptKey(k string) error {\n\tif _, exists := dm.target[k]; exists {\n\t\treturn fmt.Errorf(\"repeated key %q\", k)\n\t}\n\treturn nil\n}\n\nfunc (dm *wildcardMapDecoderMachine) step_AcceptValue(tok *Token) (done bool, err error) {\n\t\/*\n\t\tdriver.Fill(\n\t\t\ttok, \/\/ still meant for next person and the real step is to come; we just had to figure out types, here.\n\t\t\tdm.Addr(dm.key),\n\t\t\tdm.step_postValue(), \/\/ driver returns to us after the value is done by calling this.\n\t\t\t    \/\/ may actually be that we stash that stepfunc, and give driver more general self pointer and Resume func in interface.\n\t\t)\n\t*\/\n\treturn false, nil \/\/ TODO\n}\n\ntype literalDecoderMachine struct {\n\ttarget interface{}\n}\n\nfunc (dm *literalDecoderMachine) Reset(target interface{}) {\n\tdm.target = target\n}\n\nfunc (dm *literalDecoderMachine) Step(tok *Token) (done bool, err error) {\n\tvar ok bool\n\tswitch v2 := dm.target.(type) {\n\tcase *string:\n\t\t*v2, ok = (*tok).(string)\n\tcase *[]byte:\n\t\tpanic(\"TODO\")\n\tcase *int, *int8, *int16, *int32, *int64:\n\t\tpanic(\"TODO\")\n\tcase *uint, *uint8, *uint16, *uint32, *uint64:\n\t\tpanic(\"TODO\")\n\tdefault:\n\t\tpanic(fmt.Errorf(\"cannot unmarshall into unhandled type %T\", dm.target))\n\t}\n\tif ok {\n\t\treturn true, nil\n\t}\n\treturn true, fmt.Errorf(\"unexpected token of type %T, expected literal of type %T\", *tok, dm.target)\n}\n\n\/*\n\tSuppose we have the following var to unmarshal into:\n\n\t\tvar thingy SomeType\n\n\tWhere SomeType is defined as:\n\n\t\ttype SomeType struct {\n\t\t\tAnInt int\n\t\t\tSomething interface{}\n\t\t}\n\n\tThe flow of a VarReciever working on this will be something like the following:\n\n\t\t- Begin handling a var of type `SomeType`.\n\t\t- Look up the hander for that type info.\n\t\t- The handler is accepts the val ref, and returns a step function.\n\t\t- The step function is called with the token.\n\t\t- [Much work ensues.]\n\t\t- If the step function returns done, we return entirely;\n\t\t  otherwise we hang onto the next stepFunc, and return.\n\n\tThe flow of the specific handler for SomeType will look like this:\n\n\t\t- Expect a MapOpen token.\n\t\t- Expect a MapKey token.  Return a step func expecting that matching value.\n\t\t  - When called with the next token, this step func grabs the ref\n\t\t    of the struct field matching the name we were primed with...\n\t\t  - And calls dispatch on the whole thing.\n\t\t  - (Generally this func looks like it needs {fillingName string, rest},\n\t\t    so it can tell what value grab the ref to fill, and decide whether\n\t\t\tto return \"expect all done\" step.)\n\t\t- At any point, it may receive MapClose, which will jump to a check\n\t\t  that all fields are either noted as filled (requires sidebar) or\n\t\t  are tagged as omitEmpty.\n*\/\n\n\/\/ Returns an atlas so we can use this to build the contin-passing machine without bothering you.\nfunc HandleMe(vreal interface{}) (\n\tvmediate interface{},\n\tatl *Atlas,\n\tafter func(), \/* closure, already has vreal and vmediate refs *\/\n) {\n\treturn nil, nil, nil\n}\n\ntype Atlas struct{}\n\ntype atlasDecoderMachine struct {\n\tval      reflect.Value \/\/ We're filling this.\n\tatl      *Atlas        \/\/ Our directions.\n\tstep     func(*Token)  \/\/ The next step.\n\tkey      string        \/\/ The key consumed by the prev `step_AcceptKey`.\n\tkeysDone []string      \/\/ List of keys we've completed already (repeats aren't wanted).\n}\n\nfunc NewAtlasDecoderMachine(into reflect.Value, atl *Atlas) *atlasDecoderMachine {\n\t\/\/ TODO this return type should prob have some interface that covers it sufficiently.\n\tdm := &atlasDecoderMachine{\n\t\tatl: atl,\n\t}\n\tdm.Reset(into)\n\treturn dm\n}\n\nfunc (dm *atlasDecoderMachine) Reset(into reflect.Value) {\n\tdm.val = into\n\tdm.step = dm.step_Initial\n\tdm.key = \"\"\n\tdm.keysDone = dm.keysDone[0:0]\n}\n\nfunc (dm *atlasDecoderMachine) step_Initial(tok *Token) {\n\tswitch *tok {\n\tcase Token_MapOpen:\n\t\t\/\/ Great.  Consumed.\n\t\tdm.step = dm.step_AcceptKey\n\tcase Token_ArrOpen:\n\t\tpanic(\"unexpected arrOpen; expected start of struct\")\n\tcase Token_MapClose:\n\t\tpanic(\"unexpected mapClose; expected start of struct\")\n\tcase Token_ArrClose:\n\t\tpanic(\"unexpected arrClose; expected start of struct\")\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unexpected literal of type %T; expected start of struct\", *tok))\n\t}\n}\n\nfunc (dm *atlasDecoderMachine) step_AcceptKey(tok *Token) {\n\tswitch *tok {\n\tcase Token_MapOpen:\n\t\tpanic(\"unexpected mapOpen; expected map key\")\n\tcase Token_ArrOpen:\n\t\tpanic(\"unexpected arrOpen; expected map key\")\n\tcase Token_MapClose:\n\t\tdm.handleEnd()\n\tcase Token_ArrClose:\n\t\tpanic(\"unexpected arrClose; expected map key\")\n\t}\n\tswitch k := (*tok).(type) {\n\tcase *string:\n\t\tdm.key = *k\n\t\tdm.mustAcceptKey(*k)\n\t\t\/\/dm.step = dm.step_AcceptValue\n\t\t\/\/ actually we might wanna just push up our plea now --\n\t\t\/\/  this saves us from having to see and forward the token at all,\n\t\t\/\/  and makes the pattern of fab-var-filler, ret step func(token) consistent.\n\t\t\/\/  if you *really* wanted to implement a breakout for known prims, you could still do that branch here.\n\t\t\/\/  HANG ON, nope: keep it in the value step and keep the tok passdown.\n\t\t\/\/   do it for parity with arrays, which must have that step\n\t\t\/\/   and accept that token during it so they can check for end there.\n\t\t\/*\n\t\t\tdriver.Fill(\n\t\t\t\ttok, \/\/ still meant for next person and the real step is to come; we just had to figure out types, here.\n\t\t\t\tdm.Addr(dm.key),\n\t\t\t\tdm.step_postValue(), \/\/ driver returns to us after the value is done by calling this.\n\t\t\t\t    \/\/ may actually be that we stash that stepfunc, and give driver more general self pointer and Resume func in interface.\n\t\t\t)\n\t\t*\/\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unexpected literal of type %T; expected start of struct\", *tok))\n\t}\n}\nfunc (dm *atlasDecoderMachine) mustAcceptKey(k string) {\n\tfor _, x := range dm.keysDone {\n\t\tif x == k {\n\t\t\tpanic(fmt.Errorf(\"repeated key %q\", k))\n\t\t}\n\t}\n\tdm.keysDone = append(dm.keysDone, k)\n}\nfunc (dm *atlasDecoderMachine) addr(k string) interface{} {\n\t_ = dm.atl\n\treturn nil \/\/ TODO\n\t\/\/ n.b. this is one of the spots where i can't decide if &thing or reflect.Value is better\n\t\/\/ but either way we may want to define a `Slot` type alias to make it readable\n}\n\nfunc (dm *atlasDecoderMachine) step_AcceptValue(tok *Token) {\n}\n\nfunc (dm *atlasDecoderMachine) handleEnd() {\n\t\/\/ TODO check for all filled, etc.  then set terminal states.\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package agent provides hooks programs can register to retrieve\n\/\/ diagnostics data by using gops.\npackage agent\n\nimport (\n\t\"fmt\"\n\t\"hello\/gops\/agent\/signal\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"runtime\"\n)\n\nfunc init() {\n\tsock := fmt.Sprintf(\"\/tmp\/gops%d.sock\", os.Getpid())\n\tl, err := net.Listen(\"unix\", sock)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ TODO(jbd): cleanup the socket on shutdown.\n\tgo func() {\n\t\tbuf := make([]byte, 1)\n\t\tfor {\n\t\t\tfd, err := l.Accept()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"gops: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, err := fd.Read(buf); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"gops: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := handle(fd, buf); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"gops: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfd.Close()\n\t\t}\n\t}()\n}\n\nfunc handle(conn net.Conn, msg []byte) error {\n\tswitch msg[0] {\n\tcase signal.Stack:\n\t\tbuf := make([]byte, 1<<16)\n\t\tn := runtime.Stack(buf, true)\n\t\t_, err := conn.Write(buf[:n])\n\t\treturn err\n\tcase signal.GC:\n\t\truntime.GC()\n\t\t_, err := conn.Write([]byte(\"ok\"))\n\t\treturn err\n\tcase signal.MemStats:\n\t\tvar s runtime.MemStats\n\t\truntime.ReadMemStats(&s)\n\t\tfmt.Fprintf(conn, \"alloc: %v\\n\", s.Alloc)\n\t\tfmt.Fprintf(conn, \"total-alloc: %v\\n\", s.TotalAlloc)\n\t\tfmt.Fprintf(conn, \"sys: %v\\n\", s.Sys)\n\t\tfmt.Fprintf(conn, \"lookups: %v\\n\", s.Lookups)\n\t\tfmt.Fprintf(conn, \"mallocs: %v\\n\", s.Mallocs)\n\t\tfmt.Fprintf(conn, \"frees: %v\\n\", s.Frees)\n\t\tfmt.Fprintf(conn, \"heap-alloc: %v\\n\", s.HeapAlloc)\n\t\tfmt.Fprintf(conn, \"heap-sys: %v\\n\", s.HeapSys)\n\t\tfmt.Fprintf(conn, \"heap-idle: %v\\n\", s.HeapIdle)\n\t\tfmt.Fprintf(conn, \"heap-in-use: %v\\n\", s.HeapInuse)\n\t\tfmt.Fprintf(conn, \"heap-released: %v\\n\", s.HeapReleased)\n\t\tfmt.Fprintf(conn, \"heap-objects: %v\\n\", s.HeapObjects)\n\t\tfmt.Fprintf(conn, \"stack-in-use: %v\\n\", s.StackInuse)\n\t\tfmt.Fprintf(conn, \"stack-sys: %v\\n\", s.StackSys)\n\t\tfmt.Fprintf(conn, \"next-gc: %v\\n\", s.NextGC)\n\t\tfmt.Fprintf(conn, \"last-gc: %v ns ago\\n\", s.LastGC)\n\t\tfmt.Fprintf(conn, \"gc-pause: %v ns\\n\", s.PauseTotalNs)\n\t\tfmt.Fprintf(conn, \"num-gc: %v\\n\", s.NumGC)\n\t\tfmt.Fprintf(conn, \"enable-gc: %v\\n\", s.EnableGC)\n\t\tfmt.Fprintf(conn, \"debug-gc: %v\\n\", s.DebugGC)\n\tcase signal.Version:\n\t\tfmt.Fprintf(conn, \"%v\\n\", runtime.Version())\n\n\t}\n\treturn nil\n}\n<commit_msg>cleanup socket on shutdown<commit_after>\/\/ Copyright 2016 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package agent provides hooks programs can register to retrieve\n\/\/ diagnostics data by using gops.\npackage agent\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\tgosignal \"os\/signal\"\n\t\"runtime\"\n\n\t\"hello\/gops\/agent\/signal\"\n)\n\nfunc init() {\n\tsock := fmt.Sprintf(\"\/tmp\/gops%d.sock\", os.Getpid())\n\tl, err := net.Listen(\"unix\", sock)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tc := make(chan os.Signal, 1)\n\tgosignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\t\/\/ cleanup the socket on shutdown.\n\t\t<-c\n\t\tos.Remove(sock)\n\t\tos.Exit(1)\n\t}()\n\n\tgo func() {\n\t\tbuf := make([]byte, 1)\n\t\tfor {\n\t\t\tfd, err := l.Accept()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"gops: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, err := fd.Read(buf); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"gops: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := handle(fd, buf); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"gops: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfd.Close()\n\t\t}\n\t}()\n}\n\nfunc handle(conn net.Conn, msg []byte) error {\n\tswitch msg[0] {\n\tcase signal.Stack:\n\t\tbuf := make([]byte, 1<<16)\n\t\tn := runtime.Stack(buf, true)\n\t\t_, err := conn.Write(buf[:n])\n\t\treturn err\n\tcase signal.GC:\n\t\truntime.GC()\n\t\t_, err := conn.Write([]byte(\"ok\"))\n\t\treturn err\n\tcase signal.MemStats:\n\t\tvar s runtime.MemStats\n\t\truntime.ReadMemStats(&s)\n\t\tfmt.Fprintf(conn, \"alloc: %v\\n\", s.Alloc)\n\t\tfmt.Fprintf(conn, \"total-alloc: %v\\n\", s.TotalAlloc)\n\t\tfmt.Fprintf(conn, \"sys: %v\\n\", s.Sys)\n\t\tfmt.Fprintf(conn, \"lookups: %v\\n\", s.Lookups)\n\t\tfmt.Fprintf(conn, \"mallocs: %v\\n\", s.Mallocs)\n\t\tfmt.Fprintf(conn, \"frees: %v\\n\", s.Frees)\n\t\tfmt.Fprintf(conn, \"heap-alloc: %v\\n\", s.HeapAlloc)\n\t\tfmt.Fprintf(conn, \"heap-sys: %v\\n\", s.HeapSys)\n\t\tfmt.Fprintf(conn, \"heap-idle: %v\\n\", s.HeapIdle)\n\t\tfmt.Fprintf(conn, \"heap-in-use: %v\\n\", s.HeapInuse)\n\t\tfmt.Fprintf(conn, \"heap-released: %v\\n\", s.HeapReleased)\n\t\tfmt.Fprintf(conn, \"heap-objects: %v\\n\", s.HeapObjects)\n\t\tfmt.Fprintf(conn, \"stack-in-use: %v\\n\", s.StackInuse)\n\t\tfmt.Fprintf(conn, \"stack-sys: %v\\n\", s.StackSys)\n\t\tfmt.Fprintf(conn, \"next-gc: %v\\n\", s.NextGC)\n\t\tfmt.Fprintf(conn, \"last-gc: %v ns ago\\n\", s.LastGC)\n\t\tfmt.Fprintf(conn, \"gc-pause: %v ns\\n\", s.PauseTotalNs)\n\t\tfmt.Fprintf(conn, \"num-gc: %v\\n\", s.NumGC)\n\t\tfmt.Fprintf(conn, \"enable-gc: %v\\n\", s.EnableGC)\n\t\tfmt.Fprintf(conn, \"debug-gc: %v\\n\", s.DebugGC)\n\tcase signal.Version:\n\t\tfmt.Fprintf(conn, \"%v\\n\", runtime.Version())\n\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package baggageclaimcmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/clock\"\n\t\"code.cloudfoundry.org\/lager\"\n\t\"github.com\/concourse\/baggageclaim\/api\"\n\t\"github.com\/concourse\/baggageclaim\/reaper\"\n\t\"github.com\/concourse\/baggageclaim\/uidgid\"\n\t\"github.com\/concourse\/baggageclaim\/volume\"\n\t\"github.com\/concourse\/baggageclaim\/volume\/driver\"\n\t\"github.com\/tedsuo\/ifrit\"\n\t\"github.com\/tedsuo\/ifrit\/grouper\"\n\t\"github.com\/tedsuo\/ifrit\/http_server\"\n\t\"github.com\/tedsuo\/ifrit\/sigmon\"\n\t\"github.com\/xoebus\/zest\"\n)\n\ntype BaggageclaimCommand struct {\n\tLogger LagerFlag\n\n\tBindIP   IPFlag `long:\"bind-ip\"   default:\"127.0.0.1\" description:\"IP address on which to listen for API traffic.\"`\n\tBindPort uint16 `long:\"bind-port\" default:\"7788\"      description:\"Port on which to listen for API traffic.\"`\n\n\tVolumesDir DirFlag `long:\"volumes\" required:\"true\" description:\"Directory in which to place volume data.\"`\n\n\tDriver   string `long:\"driver\" default:\"naive\" choice:\"naive\" choice:\"btrfs\" description:\"Driver to use for managing volumes.\"`\n\tBtrfsBin string `long:\"btrfs-bin\" default:\"btrfs\" description:\"Path to btrfs binary\"`\n\tMkfsBin  string `long:\"mkfs-bin\" default:\"mkfs.btrfs\" description:\"Path to mkfs.btrfs binary\"`\n\n\tReapInterval time.Duration `long:\"reap-interval\" default:\"10s\" description:\"Interval on which to reap expired volumes.\"`\n\n\tMetrics struct {\n\t\tYellerAPIKey      string `long:\"yeller-api-key\"     description:\"Yeller API key. If specified, all errors logged will be emitted.\"`\n\t\tYellerEnvironment string `long:\"yeller-environment\" description:\"Environment to tag on all Yeller events emitted.\"`\n\t} `group:\"Metrics & Diagnostics\"`\n}\n\nfunc (cmd *BaggageclaimCommand) Execute(args []string) error {\n\trunner, err := cmd.Runner(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn <-ifrit.Invoke(sigmon.New(runner)).Wait()\n}\n\nfunc (cmd *BaggageclaimCommand) Runner(args []string) (ifrit.Runner, error) {\n\tlogger, _ := cmd.constructLogger()\n\n\tlistenAddr := fmt.Sprintf(\"%s:%d\", cmd.BindIP.IP(), cmd.BindPort)\n\n\tvar volumeDriver volume.Driver\n\n\tif cmd.Driver == \"btrfs\" {\n\t\tvolumeDriver = driver.NewBtrFSDriver(\n\t\t\tlogger.Session(\"driver\"),\n\t\t\tstring(cmd.VolumesDir),\n\t\t\tcmd.BtrfsBin,\n\t\t)\n\t} else {\n\t\tvolumeDriver = &driver.NaiveDriver{}\n\t}\n\n\tvar namespacer uidgid.Namespacer\n\n\tmaxUID, maxUIDErr := uidgid.DefaultUIDMap.MaxValid()\n\tmaxGID, maxGIDErr := uidgid.DefaultGIDMap.MaxValid()\n\n\tif runtime.GOOS == \"linux\" && maxUIDErr == nil && maxGIDErr == nil {\n\t\tmaxId := uidgid.Min(maxUID, maxGID)\n\t\tTranslator := uidgid.NewTranslator(maxId)\n\n\t\tnamespacer = &uidgid.UidNamespacer{\n\t\t\tTranslator: Translator,\n\t\t\tLogger:     logger.Session(\"uid-namespacer\"),\n\t\t}\n\t} else {\n\t\tnamespacer = uidgid.NoopNamespacer{}\n\t}\n\n\tlocker := volume.NewLockManager()\n\n\tfilesystem, err := volume.NewFilesystem(volumeDriver, string(cmd.VolumesDir))\n\tif err != nil {\n\t\tlogger.Fatal(\"failed-to-initialize-filesystem\", err)\n\t}\n\n\tvolumeRepo := volume.NewRepository(\n\t\tlogger.Session(\"repository\"),\n\t\tfilesystem,\n\t\tlocker,\n\t)\n\n\tstrategerizer := volume.NewStrategerizer(namespacer)\n\n\tapiHandler, err := api.NewHandler(\n\t\tlogger.Session(\"api\"),\n\t\tstrategerizer,\n\t\tnamespacer,\n\t\tvolumeRepo,\n\t)\n\tif err != nil {\n\t\tlogger.Fatal(\"failed-to-create-handler\", err)\n\t}\n\n\tclock := clock.NewClock()\n\n\tmorbidReality := reaper.NewReaper(clock, volumeRepo)\n\n\tmembers := []grouper.Member{\n\t\t{\"api\", http_server.New(listenAddr, apiHandler)},\n\t\t{\"reaper\", reaper.NewRunner(logger, clock, cmd.ReapInterval, morbidReality.Reap)},\n\t}\n\n\treturn onReady(grouper.NewParallel(os.Interrupt, members), func() {\n\t\tlogger.Info(\"listening\", lager.Data{\n\t\t\t\"addr\": listenAddr,\n\t\t})\n\t}), nil\n}\n\nfunc (cmd *BaggageclaimCommand) constructLogger() (lager.Logger, *lager.ReconfigurableSink) {\n\tlogger, reconfigurableSink := cmd.Logger.Logger(\"baggageclaim\")\n\n\tif cmd.Metrics.YellerAPIKey != \"\" {\n\t\tyellerSink := zest.NewYellerSink(cmd.Metrics.YellerAPIKey, cmd.Metrics.YellerEnvironment)\n\t\tlogger.RegisterSink(yellerSink)\n\t}\n\n\treturn logger, reconfigurableSink\n}\n\nfunc onReady(runner ifrit.Runner, cb func()) ifrit.Runner {\n\treturn ifrit.RunFunc(func(signals <-chan os.Signal, ready chan<- struct{}) error {\n\t\tprocess := ifrit.Background(runner)\n\n\t\tsubExited := process.Wait()\n\t\tsubReady := process.Ready()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-subReady:\n\t\t\t\tcb()\n\t\t\t\tsubReady = nil\n\t\t\tcase err := <-subExited:\n\t\t\t\treturn err\n\t\t\tcase sig := <-signals:\n\t\t\t\tprocess.Signal(sig)\n\t\t\t}\n\t\t}\n\t})\n}\n<commit_msg>use .Path<commit_after>package baggageclaimcmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/clock\"\n\t\"code.cloudfoundry.org\/lager\"\n\t\"github.com\/concourse\/baggageclaim\/api\"\n\t\"github.com\/concourse\/baggageclaim\/reaper\"\n\t\"github.com\/concourse\/baggageclaim\/uidgid\"\n\t\"github.com\/concourse\/baggageclaim\/volume\"\n\t\"github.com\/concourse\/baggageclaim\/volume\/driver\"\n\t\"github.com\/tedsuo\/ifrit\"\n\t\"github.com\/tedsuo\/ifrit\/grouper\"\n\t\"github.com\/tedsuo\/ifrit\/http_server\"\n\t\"github.com\/tedsuo\/ifrit\/sigmon\"\n\t\"github.com\/xoebus\/zest\"\n)\n\ntype BaggageclaimCommand struct {\n\tLogger LagerFlag\n\n\tBindIP   IPFlag `long:\"bind-ip\"   default:\"127.0.0.1\" description:\"IP address on which to listen for API traffic.\"`\n\tBindPort uint16 `long:\"bind-port\" default:\"7788\"      description:\"Port on which to listen for API traffic.\"`\n\n\tVolumesDir DirFlag `long:\"volumes\" required:\"true\" description:\"Directory in which to place volume data.\"`\n\n\tDriver   string `long:\"driver\" default:\"naive\" choice:\"naive\" choice:\"btrfs\" description:\"Driver to use for managing volumes.\"`\n\tBtrfsBin string `long:\"btrfs-bin\" default:\"btrfs\" description:\"Path to btrfs binary\"`\n\tMkfsBin  string `long:\"mkfs-bin\" default:\"mkfs.btrfs\" description:\"Path to mkfs.btrfs binary\"`\n\n\tReapInterval time.Duration `long:\"reap-interval\" default:\"10s\" description:\"Interval on which to reap expired volumes.\"`\n\n\tMetrics struct {\n\t\tYellerAPIKey      string `long:\"yeller-api-key\"     description:\"Yeller API key. If specified, all errors logged will be emitted.\"`\n\t\tYellerEnvironment string `long:\"yeller-environment\" description:\"Environment to tag on all Yeller events emitted.\"`\n\t} `group:\"Metrics & Diagnostics\"`\n}\n\nfunc (cmd *BaggageclaimCommand) Execute(args []string) error {\n\trunner, err := cmd.Runner(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn <-ifrit.Invoke(sigmon.New(runner)).Wait()\n}\n\nfunc (cmd *BaggageclaimCommand) Runner(args []string) (ifrit.Runner, error) {\n\tlogger, _ := cmd.constructLogger()\n\n\tlistenAddr := fmt.Sprintf(\"%s:%d\", cmd.BindIP.IP(), cmd.BindPort)\n\n\tvar volumeDriver volume.Driver\n\n\tif cmd.Driver == \"btrfs\" {\n\t\tvolumeDriver = driver.NewBtrFSDriver(\n\t\t\tlogger.Session(\"driver\"),\n\t\t\tstring(cmd.VolumesDir),\n\t\t\tcmd.BtrfsBin,\n\t\t)\n\t} else {\n\t\tvolumeDriver = &driver.NaiveDriver{}\n\t}\n\n\tvar namespacer uidgid.Namespacer\n\n\tmaxUID, maxUIDErr := uidgid.DefaultUIDMap.MaxValid()\n\tmaxGID, maxGIDErr := uidgid.DefaultGIDMap.MaxValid()\n\n\tif runtime.GOOS == \"linux\" && maxUIDErr == nil && maxGIDErr == nil {\n\t\tmaxId := uidgid.Min(maxUID, maxGID)\n\t\tTranslator := uidgid.NewTranslator(maxId)\n\n\t\tnamespacer = &uidgid.UidNamespacer{\n\t\t\tTranslator: Translator,\n\t\t\tLogger:     logger.Session(\"uid-namespacer\"),\n\t\t}\n\t} else {\n\t\tnamespacer = uidgid.NoopNamespacer{}\n\t}\n\n\tlocker := volume.NewLockManager()\n\n\tfilesystem, err := volume.NewFilesystem(volumeDriver, cmd.VolumesDir.Path())\n\tif err != nil {\n\t\tlogger.Fatal(\"failed-to-initialize-filesystem\", err)\n\t}\n\n\tvolumeRepo := volume.NewRepository(\n\t\tlogger.Session(\"repository\"),\n\t\tfilesystem,\n\t\tlocker,\n\t)\n\n\tstrategerizer := volume.NewStrategerizer(namespacer)\n\n\tapiHandler, err := api.NewHandler(\n\t\tlogger.Session(\"api\"),\n\t\tstrategerizer,\n\t\tnamespacer,\n\t\tvolumeRepo,\n\t)\n\tif err != nil {\n\t\tlogger.Fatal(\"failed-to-create-handler\", err)\n\t}\n\n\tclock := clock.NewClock()\n\n\tmorbidReality := reaper.NewReaper(clock, volumeRepo)\n\n\tmembers := []grouper.Member{\n\t\t{\"api\", http_server.New(listenAddr, apiHandler)},\n\t\t{\"reaper\", reaper.NewRunner(logger, clock, cmd.ReapInterval, morbidReality.Reap)},\n\t}\n\n\treturn onReady(grouper.NewParallel(os.Interrupt, members), func() {\n\t\tlogger.Info(\"listening\", lager.Data{\n\t\t\t\"addr\": listenAddr,\n\t\t})\n\t}), nil\n}\n\nfunc (cmd *BaggageclaimCommand) constructLogger() (lager.Logger, *lager.ReconfigurableSink) {\n\tlogger, reconfigurableSink := cmd.Logger.Logger(\"baggageclaim\")\n\n\tif cmd.Metrics.YellerAPIKey != \"\" {\n\t\tyellerSink := zest.NewYellerSink(cmd.Metrics.YellerAPIKey, cmd.Metrics.YellerEnvironment)\n\t\tlogger.RegisterSink(yellerSink)\n\t}\n\n\treturn logger, reconfigurableSink\n}\n\nfunc onReady(runner ifrit.Runner, cb func()) ifrit.Runner {\n\treturn ifrit.RunFunc(func(signals <-chan os.Signal, ready chan<- struct{}) error {\n\t\tprocess := ifrit.Background(runner)\n\n\t\tsubExited := process.Wait()\n\t\tsubReady := process.Ready()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-subReady:\n\t\t\t\tcb()\n\t\t\t\tsubReady = nil\n\t\t\tcase err := <-subExited:\n\t\t\t\treturn err\n\t\t\tcase sig := <-signals:\n\t\t\t\tprocess.Signal(sig)\n\t\t\t}\n\t\t}\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 The Walk Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage walk\n\ntype TableViewColumnList struct {\n\ttv    *TableView\n\titems []*TableViewColumn\n}\n\nfunc newTableViewColumnList(tv *TableView) *TableViewColumnList {\n\treturn &TableViewColumnList{tv: tv}\n}\n\n\/\/ Add adds a TableViewColumn to the end of the list.\nfunc (l *TableViewColumnList) Add(item *TableViewColumn) error {\n\treturn l.Insert(len(l.items), item)\n}\n\n\/\/ At returns the TableViewColumn as the specified index.\n\/\/\n\/\/ Bounds are not checked.\nfunc (l *TableViewColumnList) At(index int) *TableViewColumn {\n\treturn l.items[index]\n}\n\nfunc (l *TableViewColumnList) atInListView(index int) *TableViewColumn {\n\tvar idx int\n\n\tfor _, item := range l.items {\n\t\tif item.visible {\n\t\t\tif idx == index {\n\t\t\t\treturn item\n\t\t\t}\n\n\t\t\tidx++\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Clear removes all TableViewColumns from the list.\nfunc (l *TableViewColumnList) Clear() error {\n\tfor _ = range l.items {\n\t\tif err := l.RemoveAt(0); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Index returns the index of the specified TableViewColumn or -1 if it is not\n\/\/ found.\nfunc (l *TableViewColumnList) Index(item *TableViewColumn) int {\n\tfor i, lvi := range l.items {\n\t\tif lvi == item {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}\n\n\/\/ Contains returns whether the specified TableViewColumn is found in the list.\nfunc (l *TableViewColumnList) Contains(item *TableViewColumn) bool {\n\treturn l.Index(item) > -1\n}\n\n\/\/ Insert inserts TableViewColumn item at position index.\n\/\/\n\/\/ A TableViewColumn cannot be contained in multiple TableViewColumnLists at the\n\/\/ same time.\nfunc (l *TableViewColumnList) Insert(index int, item *TableViewColumn) error {\n\tif item.tv != nil {\n\t\treturn newError(\"duplicate insert\")\n\t}\n\n\titem.tv = l.tv\n\n\tif err := item.create(); err != nil {\n\t\titem.tv = nil\n\t\treturn err\n\t}\n\n\tl.items = append(l.items, nil)\n\tcopy(l.items[index+1:], l.items[index:])\n\tl.items[index] = item\n\n\treturn nil\n}\n\n\/\/ Len returns the number of TableViewColumns in  the list.\nfunc (l *TableViewColumnList) Len() int {\n\treturn len(l.items)\n}\n\n\/\/ Remove removes the specified TableViewColumn from the list.\nfunc (l *TableViewColumnList) Remove(item *TableViewColumn) error {\n\tindex := l.Index(item)\n\tif index == -1 {\n\t\treturn nil\n\t}\n\n\treturn l.RemoveAt(index)\n}\n\n\/\/ RemoveAt removes the TableViewColumn at position index.\nfunc (l *TableViewColumnList) RemoveAt(index int) error {\n\ttvc := l.items[index]\n\n\tif err := tvc.destroy(); err != nil {\n\t\treturn err\n\t}\n\n\ttvc.tv = nil\n\n\tl.items = append(l.items[:index], l.items[index+1:]...)\n\n\treturn nil\n}\n\nfunc (l *TableViewColumnList) unsetColumnsTV() {\n\tfor _, tvc := range l.items {\n\t\ttvc.tv = nil\n\t}\n}\n<commit_msg>TableViewColumnList: In Insert, only call item.create if the column is visible<commit_after>\/\/ Copyright 2013 The Walk Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage walk\n\ntype TableViewColumnList struct {\n\ttv    *TableView\n\titems []*TableViewColumn\n}\n\nfunc newTableViewColumnList(tv *TableView) *TableViewColumnList {\n\treturn &TableViewColumnList{tv: tv}\n}\n\n\/\/ Add adds a TableViewColumn to the end of the list.\nfunc (l *TableViewColumnList) Add(item *TableViewColumn) error {\n\treturn l.Insert(len(l.items), item)\n}\n\n\/\/ At returns the TableViewColumn as the specified index.\n\/\/\n\/\/ Bounds are not checked.\nfunc (l *TableViewColumnList) At(index int) *TableViewColumn {\n\treturn l.items[index]\n}\n\nfunc (l *TableViewColumnList) atInListView(index int) *TableViewColumn {\n\tvar idx int\n\n\tfor _, item := range l.items {\n\t\tif item.visible {\n\t\t\tif idx == index {\n\t\t\t\treturn item\n\t\t\t}\n\n\t\t\tidx++\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Clear removes all TableViewColumns from the list.\nfunc (l *TableViewColumnList) Clear() error {\n\tfor _ = range l.items {\n\t\tif err := l.RemoveAt(0); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Index returns the index of the specified TableViewColumn or -1 if it is not\n\/\/ found.\nfunc (l *TableViewColumnList) Index(item *TableViewColumn) int {\n\tfor i, lvi := range l.items {\n\t\tif lvi == item {\n\t\t\treturn i\n\t\t}\n\t}\n\n\treturn -1\n}\n\n\/\/ Contains returns whether the specified TableViewColumn is found in the list.\nfunc (l *TableViewColumnList) Contains(item *TableViewColumn) bool {\n\treturn l.Index(item) > -1\n}\n\n\/\/ Insert inserts TableViewColumn item at position index.\n\/\/\n\/\/ A TableViewColumn cannot be contained in multiple TableViewColumnLists at the\n\/\/ same time.\nfunc (l *TableViewColumnList) Insert(index int, item *TableViewColumn) error {\n\tif item.tv != nil {\n\t\treturn newError(\"duplicate insert\")\n\t}\n\n\titem.tv = l.tv\n\n\tif item.visible {\n\t\tif err := item.create(); err != nil {\n\t\t\titem.tv = nil\n\t\t\treturn err\n\t\t}\n\t}\n\n\tl.items = append(l.items, nil)\n\tcopy(l.items[index+1:], l.items[index:])\n\tl.items[index] = item\n\n\treturn nil\n}\n\n\/\/ Len returns the number of TableViewColumns in  the list.\nfunc (l *TableViewColumnList) Len() int {\n\treturn len(l.items)\n}\n\n\/\/ Remove removes the specified TableViewColumn from the list.\nfunc (l *TableViewColumnList) Remove(item *TableViewColumn) error {\n\tindex := l.Index(item)\n\tif index == -1 {\n\t\treturn nil\n\t}\n\n\treturn l.RemoveAt(index)\n}\n\n\/\/ RemoveAt removes the TableViewColumn at position index.\nfunc (l *TableViewColumnList) RemoveAt(index int) error {\n\ttvc := l.items[index]\n\n\tif err := tvc.destroy(); err != nil {\n\t\treturn err\n\t}\n\n\ttvc.tv = nil\n\n\tl.items = append(l.items[:index], l.items[index+1:]...)\n\n\treturn nil\n}\n\nfunc (l *TableViewColumnList) unsetColumnsTV() {\n\tfor _, tvc := range l.items {\n\t\ttvc.tv = nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gothumb\n\nimport (\n\t\"github.com\/rwcarlsen\/goexif\/exif\"\n\t\"io\"\n)\n\nfunc Orientation(reader io.Reader) (orientation int, err error) {\n\torientation = 1\n\n\tinfo, err := exif.Decode(reader)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\torientTag, err := info.Get(exif.Orientation)\n\n\tif err != nil {\n\t\treturn 1, nil\n\t}\n\n\torientation = int(orientTag.Int(0))\n\n\treturn\n}\n<commit_msg>copiles with updated dependencies again<commit_after>package gothumb\n\nimport (\n\t\"github.com\/rwcarlsen\/goexif\/exif\"\n\t\"io\"\n)\n\nfunc Orientation(reader io.Reader) (orientation int, err error) {\n\torientation = 1\n\n\tinfo, err := exif.Decode(reader)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\torientTag, err := info.Get(exif.Orientation)\n\n\tif err != nil {\n\t\treturn 1, nil\n\t}\n\n\torientation, err = orientTag.Int(0)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage net\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc newLocalListener(t *testing.T) Listener {\n\tln, err := Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tln, err = Listen(\"tcp6\", \"[::1]:0\")\n\t}\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn ln\n}\n\nfunc TestDialTimeout(t *testing.T) {\n\torigBacklog := listenerBacklog\n\tdefer func() {\n\t\tlistenerBacklog = origBacklog\n\t}()\n\tlistenerBacklog = 1\n\n\tln := newLocalListener(t)\n\tdefer ln.Close()\n\n\terrc := make(chan error)\n\n\tnumConns := listenerBacklog + 100\n\n\t\/\/ TODO(bradfitz): It's hard to test this in a portable\n\t\/\/ way. This is unfortunate, but works for now.\n\tswitch runtime.GOOS {\n\tcase \"linux\":\n\t\t\/\/ The kernel will start accepting TCP connections before userspace\n\t\t\/\/ gets a chance to not accept them, so fire off a bunch to fill up\n\t\t\/\/ the kernel's backlog.  Then we test we get a failure after that.\n\t\tfor i := 0; i < numConns; i++ {\n\t\t\tgo func() {\n\t\t\t\t_, err := DialTimeout(\"tcp\", ln.Addr().String(), 200*time.Millisecond)\n\t\t\t\terrc <- err\n\t\t\t}()\n\t\t}\n\tcase \"darwin\", \"windows\":\n\t\t\/\/ At least OS X 10.7 seems to accept any number of\n\t\t\/\/ connections, ignoring listen's backlog, so resort\n\t\t\/\/ to connecting to a hopefully-dead 127\/8 address.\n\t\t\/\/ Same for windows.\n\t\t\/\/\n\t\t\/\/ Use an IANA reserved port (49151) instead of 80, because\n\t\t\/\/ on our 386 builder, this Dial succeeds, connecting\n\t\t\/\/ to an IIS web server somewhere.  The data center\n\t\t\/\/ or VM or firewall must be stealing the TCP connection.\n\t\t\/\/\n\t\t\/\/ IANA Service Name and Transport Protocol Port Number Registry\n\t\t\/\/ <http:\/\/www.iana.org\/assignments\/service-names-port-numbers\/service-names-port-numbers.xml>\n\t\tgo func() {\n\t\t\tc, err := DialTimeout(\"tcp\", \"127.0.71.111:49151\", 200*time.Millisecond)\n\t\t\tif err == nil {\n\t\t\t\terr = fmt.Errorf(\"unexpected: connected to %s!\", c.RemoteAddr())\n\t\t\t\tc.Close()\n\t\t\t}\n\t\t\terrc <- err\n\t\t}()\n\tdefault:\n\t\t\/\/ TODO(bradfitz):\n\t\t\/\/ OpenBSD may have a reject route to 127\/8 except 127.0.0.1\/32\n\t\t\/\/ by default. FreeBSD likely works, but is untested.\n\t\t\/\/ TODO(rsc):\n\t\t\/\/ The timeout never happens on Windows.  Why?  Issue 3016.\n\t\tt.Skipf(\"skipping test on %q; untested.\", runtime.GOOS)\n\t}\n\n\tconnected := 0\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(15 * time.Second):\n\t\t\tt.Fatal(\"too slow\")\n\t\tcase err := <-errc:\n\t\t\tif err == nil {\n\t\t\t\tconnected++\n\t\t\t\tif connected == numConns {\n\t\t\t\t\tt.Fatal(\"all connections connected; expected some to time out\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tterr, ok := err.(timeout)\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Fatalf(\"got error %q; want error with timeout interface\", err)\n\t\t\t\t}\n\t\t\t\tif !terr.Timeout() {\n\t\t\t\t\tt.Fatalf(\"got error %q; not a timeout\", err)\n\t\t\t\t}\n\t\t\t\t\/\/ Pass. We saw a timeout error.\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestSelfConnect(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\t\/\/ TODO(brainman): do not know why it hangs.\n\t\tt.Skip(\"skipping known-broken test on windows\")\n\t}\n\t\/\/ Test that Dial does not honor self-connects.\n\t\/\/ See the comment in DialTCP.\n\n\t\/\/ Find a port that would be used as a local address.\n\tl, err := Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tc, err := Dial(\"tcp\", l.Addr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\taddr := c.LocalAddr().String()\n\tc.Close()\n\tl.Close()\n\n\t\/\/ Try to connect to that address repeatedly.\n\tn := 100000\n\tif testing.Short() {\n\t\tn = 1000\n\t}\n\tswitch runtime.GOOS {\n\tcase \"darwin\", \"dragonfly\", \"freebsd\", \"netbsd\", \"openbsd\", \"plan9\", \"windows\":\n\t\t\/\/ Non-Linux systems take a long time to figure\n\t\t\/\/ out that there is nothing listening on localhost.\n\t\tn = 100\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tc, err := Dial(\"tcp\", addr)\n\t\tif err == nil {\n\t\t\tc.Close()\n\t\t\tt.Errorf(\"#%d: Dial %q succeeded\", i, addr)\n\t\t}\n\t}\n}\n\nvar runErrorTest = flag.Bool(\"run_error_test\", false, \"let TestDialError check for dns errors\")\n\ntype DialErrorTest struct {\n\tNet     string\n\tRaddr   string\n\tPattern string\n}\n\nvar dialErrorTests = []DialErrorTest{\n\t{\n\t\t\"datakit\", \"mh\/astro\/r70\",\n\t\t\"dial datakit mh\/astro\/r70: unknown network datakit\",\n\t},\n\t{\n\t\t\"tcp\", \"127.0.0.1:☺\",\n\t\t\"dial tcp 127.0.0.1:☺: unknown port tcp\/☺\",\n\t},\n\t{\n\t\t\"tcp\", \"no-such-name.google.com.:80\",\n\t\t\"dial tcp no-such-name.google.com.:80: lookup no-such-name.google.com.( on .*)?: no (.*)\",\n\t},\n\t{\n\t\t\"tcp\", \"no-such-name.no-such-top-level-domain.:80\",\n\t\t\"dial tcp no-such-name.no-such-top-level-domain.:80: lookup no-such-name.no-such-top-level-domain.( on .*)?: no (.*)\",\n\t},\n\t{\n\t\t\"tcp\", \"no-such-name:80\",\n\t\t`dial tcp no-such-name:80: lookup no-such-name\\.(.*\\.)?( on .*)?: no (.*)`,\n\t},\n\t{\n\t\t\"tcp\", \"mh\/astro\/r70:http\",\n\t\t\"dial tcp mh\/astro\/r70:http: lookup mh\/astro\/r70: invalid domain name\",\n\t},\n\t{\n\t\t\"unix\", \"\/etc\/file-not-found\",\n\t\t\"dial unix \/etc\/file-not-found: no such file or directory\",\n\t},\n\t{\n\t\t\"unix\", \"\/etc\/\",\n\t\t\"dial unix \/etc\/: (permission denied|socket operation on non-socket|connection refused)\",\n\t},\n\t{\n\t\t\"unixpacket\", \"\/etc\/file-not-found\",\n\t\t\"dial unixpacket \/etc\/file-not-found: no such file or directory\",\n\t},\n\t{\n\t\t\"unixpacket\", \"\/etc\/\",\n\t\t\"dial unixpacket \/etc\/: (permission denied|socket operation on non-socket|connection refused)\",\n\t},\n}\n\nvar duplicateErrorPattern = `dial (.*) dial (.*)`\n\nfunc TestDialError(t *testing.T) {\n\tif !*runErrorTest {\n\t\tt.Logf(\"test disabled; use -run_error_test to enable\")\n\t\treturn\n\t}\n\tfor i, tt := range dialErrorTests {\n\t\tc, err := Dial(tt.Net, tt.Raddr)\n\t\tif c != nil {\n\t\t\tc.Close()\n\t\t}\n\t\tif err == nil {\n\t\t\tt.Errorf(\"#%d: nil error, want match for %#q\", i, tt.Pattern)\n\t\t\tcontinue\n\t\t}\n\t\ts := err.Error()\n\t\tmatch, _ := regexp.MatchString(tt.Pattern, s)\n\t\tif !match {\n\t\t\tt.Errorf(\"#%d: %q, want match for %#q\", i, s, tt.Pattern)\n\t\t}\n\t\tmatch, _ = regexp.MatchString(duplicateErrorPattern, s)\n\t\tif match {\n\t\t\tt.Errorf(\"#%d: %q, duplicate error return from Dial\", i, s)\n\t\t}\n\t}\n}\n\nvar invalidDialAndListenArgTests = []struct {\n\tnet  string\n\taddr string\n\terr  error\n}{\n\t{\"foo\", \"bar\", &OpError{Op: \"dial\", Net: \"foo\", Addr: nil, Err: UnknownNetworkError(\"foo\")}},\n\t{\"baz\", \"\", &OpError{Op: \"listen\", Net: \"baz\", Addr: nil, Err: UnknownNetworkError(\"baz\")}},\n\t{\"tcp\", \"\", &OpError{Op: \"dial\", Net: \"tcp\", Addr: nil, Err: errMissingAddress}},\n}\n\nfunc TestInvalidDialAndListenArgs(t *testing.T) {\n\tfor _, tt := range invalidDialAndListenArgTests {\n\t\tvar err error\n\t\tswitch tt.err.(*OpError).Op {\n\t\tcase \"dial\":\n\t\t\t_, err = Dial(tt.net, tt.addr)\n\t\tcase \"listen\":\n\t\t\t_, err = Listen(tt.net, tt.addr)\n\t\t}\n\t\tif !reflect.DeepEqual(tt.err, err) {\n\t\t\tt.Fatalf(\"got %#v; expected %#v\", err, tt.err)\n\t\t}\n\t}\n}\n\nfunc TestDialTimeoutFDLeak(t *testing.T) {\n\tif runtime.GOOS != \"linux\" {\n\t\t\/\/ TODO(bradfitz): test on other platforms\n\t\tt.Skipf(\"skipping test on %q\", runtime.GOOS)\n\t}\n\n\tln := newLocalListener(t)\n\tdefer ln.Close()\n\n\ttype connErr struct {\n\t\tconn Conn\n\t\terr  error\n\t}\n\tdials := listenerBacklog + 100\n\t\/\/ used to be listenerBacklog + 5, but was found to be unreliable, issue 4384.\n\tmaxGoodConnect := listenerBacklog + runtime.NumCPU()*10\n\tresc := make(chan connErr)\n\tfor i := 0; i < dials; i++ {\n\t\tgo func() {\n\t\t\tconn, err := DialTimeout(\"tcp\", ln.Addr().String(), 500*time.Millisecond)\n\t\t\tresc <- connErr{conn, err}\n\t\t}()\n\t}\n\n\tvar firstErr string\n\tvar ngood int\n\tvar toClose []io.Closer\n\tfor i := 0; i < dials; i++ {\n\t\tce := <-resc\n\t\tif ce.err == nil {\n\t\t\tngood++\n\t\t\tif ngood > maxGoodConnect {\n\t\t\t\tt.Errorf(\"%d good connects; expected at most %d\", ngood, maxGoodConnect)\n\t\t\t}\n\t\t\ttoClose = append(toClose, ce.conn)\n\t\t\tcontinue\n\t\t}\n\t\terr := ce.err\n\t\tif firstErr == \"\" {\n\t\t\tfirstErr = err.Error()\n\t\t} else if err.Error() != firstErr {\n\t\t\tt.Fatalf(\"inconsistent error messages: first was %q, then later %q\", firstErr, err)\n\t\t}\n\t}\n\tfor _, c := range toClose {\n\t\tc.Close()\n\t}\n\tfor i := 0; i < 100; i++ {\n\t\tif got := numFD(); got < dials {\n\t\t\t\/\/ Test passes.\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\tif got := numFD(); got >= dials {\n\t\tt.Errorf(\"num fds after %d timeouts = %d; want <%d\", dials, got, dials)\n\t}\n}\n\nfunc numFD() int {\n\tif runtime.GOOS == \"linux\" {\n\t\tf, err := os.Open(\"\/proc\/self\/fd\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer f.Close()\n\t\tnames, err := f.Readdirnames(0)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn len(names)\n\t}\n\t\/\/ All tests using this should be skipped anyway, but:\n\tpanic(\"numFDs not implemented on \" + runtime.GOOS)\n}\n\nvar testPoller = flag.Bool(\"poller\", false, \"platform supports runtime-integrated poller\")\n\n\/\/ Assert that a failed Dial attempt does not leak\n\/\/ runtime.PollDesc structures\nfunc TestDialFailPDLeak(t *testing.T) {\n\tif !*testPoller {\n\t\tt.Skip(\"test disabled; use -poller to enable\")\n\t}\n\n\tconst loops = 10\n\tconst count = 20000\n\tvar old runtime.MemStats \/\/ used by sysdelta\n\truntime.ReadMemStats(&old)\n\tsysdelta := func() uint64 {\n\t\tvar new runtime.MemStats\n\t\truntime.ReadMemStats(&new)\n\t\tdelta := old.Sys - new.Sys\n\t\told = new\n\t\treturn delta\n\t}\n\td := &Dialer{Timeout: time.Nanosecond} \/\/ don't bother TCP with handshaking\n\tfailcount := 0\n\tfor i := 0; i < loops; i++ {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tconn, err := d.Dial(\"tcp\", \"127.0.0.1:1\")\n\t\t\tif err == nil {\n\t\t\t\tt.Error(\"dial should not succeed\")\n\t\t\t\tconn.Close()\n\t\t\t\tt.FailNow()\n\t\t\t}\n\t\t}\n\t\tif delta := sysdelta(); delta > 0 {\n\t\t\tfailcount++\n\t\t}\n\t\t\/\/ there are always some allocations on the first loop\n\t\tif failcount > 3 {\n\t\t\tt.Error(\"detected possible memory leak in runtime\")\n\t\t\tt.FailNow()\n\t\t}\n\t}\n}\n\nfunc TestDialer(t *testing.T) {\n\tln, err := Listen(\"tcp4\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatalf(\"Listen failed: %v\", err)\n\t}\n\tdefer ln.Close()\n\tch := make(chan error, 1)\n\tgo func() {\n\t\tc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tch <- fmt.Errorf(\"Accept failed: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer c.Close()\n\t\tch <- nil\n\t}()\n\n\tladdr, err := ResolveTCPAddr(\"tcp4\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatalf(\"ResolveTCPAddr failed: %v\", err)\n\t}\n\td := &Dialer{LocalAddr: laddr}\n\tc, err := d.Dial(\"tcp4\", ln.Addr().String())\n\tif err != nil {\n\t\tt.Fatalf(\"Dial failed: %v\", err)\n\t}\n\tdefer c.Close()\n\tc.Read(make([]byte, 1))\n\terr = <-ch\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n<commit_msg>net: allow TestDialFailPDLeak run in long-mode test<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage net\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc newLocalListener(t *testing.T) Listener {\n\tln, err := Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tln, err = Listen(\"tcp6\", \"[::1]:0\")\n\t}\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn ln\n}\n\nfunc TestDialTimeout(t *testing.T) {\n\torigBacklog := listenerBacklog\n\tdefer func() {\n\t\tlistenerBacklog = origBacklog\n\t}()\n\tlistenerBacklog = 1\n\n\tln := newLocalListener(t)\n\tdefer ln.Close()\n\n\terrc := make(chan error)\n\n\tnumConns := listenerBacklog + 100\n\n\t\/\/ TODO(bradfitz): It's hard to test this in a portable\n\t\/\/ way. This is unfortunate, but works for now.\n\tswitch runtime.GOOS {\n\tcase \"linux\":\n\t\t\/\/ The kernel will start accepting TCP connections before userspace\n\t\t\/\/ gets a chance to not accept them, so fire off a bunch to fill up\n\t\t\/\/ the kernel's backlog.  Then we test we get a failure after that.\n\t\tfor i := 0; i < numConns; i++ {\n\t\t\tgo func() {\n\t\t\t\t_, err := DialTimeout(\"tcp\", ln.Addr().String(), 200*time.Millisecond)\n\t\t\t\terrc <- err\n\t\t\t}()\n\t\t}\n\tcase \"darwin\", \"windows\":\n\t\t\/\/ At least OS X 10.7 seems to accept any number of\n\t\t\/\/ connections, ignoring listen's backlog, so resort\n\t\t\/\/ to connecting to a hopefully-dead 127\/8 address.\n\t\t\/\/ Same for windows.\n\t\t\/\/\n\t\t\/\/ Use an IANA reserved port (49151) instead of 80, because\n\t\t\/\/ on our 386 builder, this Dial succeeds, connecting\n\t\t\/\/ to an IIS web server somewhere.  The data center\n\t\t\/\/ or VM or firewall must be stealing the TCP connection.\n\t\t\/\/\n\t\t\/\/ IANA Service Name and Transport Protocol Port Number Registry\n\t\t\/\/ <http:\/\/www.iana.org\/assignments\/service-names-port-numbers\/service-names-port-numbers.xml>\n\t\tgo func() {\n\t\t\tc, err := DialTimeout(\"tcp\", \"127.0.71.111:49151\", 200*time.Millisecond)\n\t\t\tif err == nil {\n\t\t\t\terr = fmt.Errorf(\"unexpected: connected to %s!\", c.RemoteAddr())\n\t\t\t\tc.Close()\n\t\t\t}\n\t\t\terrc <- err\n\t\t}()\n\tdefault:\n\t\t\/\/ TODO(bradfitz):\n\t\t\/\/ OpenBSD may have a reject route to 127\/8 except 127.0.0.1\/32\n\t\t\/\/ by default. FreeBSD likely works, but is untested.\n\t\t\/\/ TODO(rsc):\n\t\t\/\/ The timeout never happens on Windows.  Why?  Issue 3016.\n\t\tt.Skipf(\"skipping test on %q; untested.\", runtime.GOOS)\n\t}\n\n\tconnected := 0\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(15 * time.Second):\n\t\t\tt.Fatal(\"too slow\")\n\t\tcase err := <-errc:\n\t\t\tif err == nil {\n\t\t\t\tconnected++\n\t\t\t\tif connected == numConns {\n\t\t\t\t\tt.Fatal(\"all connections connected; expected some to time out\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tterr, ok := err.(timeout)\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Fatalf(\"got error %q; want error with timeout interface\", err)\n\t\t\t\t}\n\t\t\t\tif !terr.Timeout() {\n\t\t\t\t\tt.Fatalf(\"got error %q; not a timeout\", err)\n\t\t\t\t}\n\t\t\t\t\/\/ Pass. We saw a timeout error.\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestSelfConnect(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\t\/\/ TODO(brainman): do not know why it hangs.\n\t\tt.Skip(\"skipping known-broken test on windows\")\n\t}\n\t\/\/ Test that Dial does not honor self-connects.\n\t\/\/ See the comment in DialTCP.\n\n\t\/\/ Find a port that would be used as a local address.\n\tl, err := Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tc, err := Dial(\"tcp\", l.Addr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\taddr := c.LocalAddr().String()\n\tc.Close()\n\tl.Close()\n\n\t\/\/ Try to connect to that address repeatedly.\n\tn := 100000\n\tif testing.Short() {\n\t\tn = 1000\n\t}\n\tswitch runtime.GOOS {\n\tcase \"darwin\", \"dragonfly\", \"freebsd\", \"netbsd\", \"openbsd\", \"plan9\", \"windows\":\n\t\t\/\/ Non-Linux systems take a long time to figure\n\t\t\/\/ out that there is nothing listening on localhost.\n\t\tn = 100\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tc, err := Dial(\"tcp\", addr)\n\t\tif err == nil {\n\t\t\tc.Close()\n\t\t\tt.Errorf(\"#%d: Dial %q succeeded\", i, addr)\n\t\t}\n\t}\n}\n\nvar runErrorTest = flag.Bool(\"run_error_test\", false, \"let TestDialError check for dns errors\")\n\ntype DialErrorTest struct {\n\tNet     string\n\tRaddr   string\n\tPattern string\n}\n\nvar dialErrorTests = []DialErrorTest{\n\t{\n\t\t\"datakit\", \"mh\/astro\/r70\",\n\t\t\"dial datakit mh\/astro\/r70: unknown network datakit\",\n\t},\n\t{\n\t\t\"tcp\", \"127.0.0.1:☺\",\n\t\t\"dial tcp 127.0.0.1:☺: unknown port tcp\/☺\",\n\t},\n\t{\n\t\t\"tcp\", \"no-such-name.google.com.:80\",\n\t\t\"dial tcp no-such-name.google.com.:80: lookup no-such-name.google.com.( on .*)?: no (.*)\",\n\t},\n\t{\n\t\t\"tcp\", \"no-such-name.no-such-top-level-domain.:80\",\n\t\t\"dial tcp no-such-name.no-such-top-level-domain.:80: lookup no-such-name.no-such-top-level-domain.( on .*)?: no (.*)\",\n\t},\n\t{\n\t\t\"tcp\", \"no-such-name:80\",\n\t\t`dial tcp no-such-name:80: lookup no-such-name\\.(.*\\.)?( on .*)?: no (.*)`,\n\t},\n\t{\n\t\t\"tcp\", \"mh\/astro\/r70:http\",\n\t\t\"dial tcp mh\/astro\/r70:http: lookup mh\/astro\/r70: invalid domain name\",\n\t},\n\t{\n\t\t\"unix\", \"\/etc\/file-not-found\",\n\t\t\"dial unix \/etc\/file-not-found: no such file or directory\",\n\t},\n\t{\n\t\t\"unix\", \"\/etc\/\",\n\t\t\"dial unix \/etc\/: (permission denied|socket operation on non-socket|connection refused)\",\n\t},\n\t{\n\t\t\"unixpacket\", \"\/etc\/file-not-found\",\n\t\t\"dial unixpacket \/etc\/file-not-found: no such file or directory\",\n\t},\n\t{\n\t\t\"unixpacket\", \"\/etc\/\",\n\t\t\"dial unixpacket \/etc\/: (permission denied|socket operation on non-socket|connection refused)\",\n\t},\n}\n\nvar duplicateErrorPattern = `dial (.*) dial (.*)`\n\nfunc TestDialError(t *testing.T) {\n\tif !*runErrorTest {\n\t\tt.Logf(\"test disabled; use -run_error_test to enable\")\n\t\treturn\n\t}\n\tfor i, tt := range dialErrorTests {\n\t\tc, err := Dial(tt.Net, tt.Raddr)\n\t\tif c != nil {\n\t\t\tc.Close()\n\t\t}\n\t\tif err == nil {\n\t\t\tt.Errorf(\"#%d: nil error, want match for %#q\", i, tt.Pattern)\n\t\t\tcontinue\n\t\t}\n\t\ts := err.Error()\n\t\tmatch, _ := regexp.MatchString(tt.Pattern, s)\n\t\tif !match {\n\t\t\tt.Errorf(\"#%d: %q, want match for %#q\", i, s, tt.Pattern)\n\t\t}\n\t\tmatch, _ = regexp.MatchString(duplicateErrorPattern, s)\n\t\tif match {\n\t\t\tt.Errorf(\"#%d: %q, duplicate error return from Dial\", i, s)\n\t\t}\n\t}\n}\n\nvar invalidDialAndListenArgTests = []struct {\n\tnet  string\n\taddr string\n\terr  error\n}{\n\t{\"foo\", \"bar\", &OpError{Op: \"dial\", Net: \"foo\", Addr: nil, Err: UnknownNetworkError(\"foo\")}},\n\t{\"baz\", \"\", &OpError{Op: \"listen\", Net: \"baz\", Addr: nil, Err: UnknownNetworkError(\"baz\")}},\n\t{\"tcp\", \"\", &OpError{Op: \"dial\", Net: \"tcp\", Addr: nil, Err: errMissingAddress}},\n}\n\nfunc TestInvalidDialAndListenArgs(t *testing.T) {\n\tfor _, tt := range invalidDialAndListenArgTests {\n\t\tvar err error\n\t\tswitch tt.err.(*OpError).Op {\n\t\tcase \"dial\":\n\t\t\t_, err = Dial(tt.net, tt.addr)\n\t\tcase \"listen\":\n\t\t\t_, err = Listen(tt.net, tt.addr)\n\t\t}\n\t\tif !reflect.DeepEqual(tt.err, err) {\n\t\t\tt.Fatalf(\"got %#v; expected %#v\", err, tt.err)\n\t\t}\n\t}\n}\n\nfunc TestDialTimeoutFDLeak(t *testing.T) {\n\tif runtime.GOOS != \"linux\" {\n\t\t\/\/ TODO(bradfitz): test on other platforms\n\t\tt.Skipf(\"skipping test on %q\", runtime.GOOS)\n\t}\n\n\tln := newLocalListener(t)\n\tdefer ln.Close()\n\n\ttype connErr struct {\n\t\tconn Conn\n\t\terr  error\n\t}\n\tdials := listenerBacklog + 100\n\t\/\/ used to be listenerBacklog + 5, but was found to be unreliable, issue 4384.\n\tmaxGoodConnect := listenerBacklog + runtime.NumCPU()*10\n\tresc := make(chan connErr)\n\tfor i := 0; i < dials; i++ {\n\t\tgo func() {\n\t\t\tconn, err := DialTimeout(\"tcp\", ln.Addr().String(), 500*time.Millisecond)\n\t\t\tresc <- connErr{conn, err}\n\t\t}()\n\t}\n\n\tvar firstErr string\n\tvar ngood int\n\tvar toClose []io.Closer\n\tfor i := 0; i < dials; i++ {\n\t\tce := <-resc\n\t\tif ce.err == nil {\n\t\t\tngood++\n\t\t\tif ngood > maxGoodConnect {\n\t\t\t\tt.Errorf(\"%d good connects; expected at most %d\", ngood, maxGoodConnect)\n\t\t\t}\n\t\t\ttoClose = append(toClose, ce.conn)\n\t\t\tcontinue\n\t\t}\n\t\terr := ce.err\n\t\tif firstErr == \"\" {\n\t\t\tfirstErr = err.Error()\n\t\t} else if err.Error() != firstErr {\n\t\t\tt.Fatalf(\"inconsistent error messages: first was %q, then later %q\", firstErr, err)\n\t\t}\n\t}\n\tfor _, c := range toClose {\n\t\tc.Close()\n\t}\n\tfor i := 0; i < 100; i++ {\n\t\tif got := numFD(); got < dials {\n\t\t\t\/\/ Test passes.\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(10 * time.Millisecond)\n\t}\n\tif got := numFD(); got >= dials {\n\t\tt.Errorf(\"num fds after %d timeouts = %d; want <%d\", dials, got, dials)\n\t}\n}\n\nfunc numFD() int {\n\tif runtime.GOOS == \"linux\" {\n\t\tf, err := os.Open(\"\/proc\/self\/fd\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer f.Close()\n\t\tnames, err := f.Readdirnames(0)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn len(names)\n\t}\n\t\/\/ All tests using this should be skipped anyway, but:\n\tpanic(\"numFDs not implemented on \" + runtime.GOOS)\n}\n\n\/\/ Assert that a failed Dial attempt does not leak\n\/\/ runtime.PollDesc structures\nfunc TestDialFailPDLeak(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"skipping test in short mode\")\n\t}\n\n\tconst loops = 10\n\tconst count = 20000\n\tvar old runtime.MemStats \/\/ used by sysdelta\n\truntime.ReadMemStats(&old)\n\tsysdelta := func() uint64 {\n\t\tvar new runtime.MemStats\n\t\truntime.ReadMemStats(&new)\n\t\tdelta := old.Sys - new.Sys\n\t\told = new\n\t\treturn delta\n\t}\n\td := &Dialer{Timeout: time.Nanosecond} \/\/ don't bother TCP with handshaking\n\tfailcount := 0\n\tfor i := 0; i < loops; i++ {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tconn, err := d.Dial(\"tcp\", \"127.0.0.1:1\")\n\t\t\tif err == nil {\n\t\t\t\tt.Error(\"dial should not succeed\")\n\t\t\t\tconn.Close()\n\t\t\t\tt.FailNow()\n\t\t\t}\n\t\t}\n\t\tif delta := sysdelta(); delta > 0 {\n\t\t\tfailcount++\n\t\t}\n\t\t\/\/ there are always some allocations on the first loop\n\t\tif failcount > 3 {\n\t\t\tt.Error(\"detected possible memory leak in runtime\")\n\t\t\tt.FailNow()\n\t\t}\n\t}\n}\n\nfunc TestDialer(t *testing.T) {\n\tln, err := Listen(\"tcp4\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatalf(\"Listen failed: %v\", err)\n\t}\n\tdefer ln.Close()\n\tch := make(chan error, 1)\n\tgo func() {\n\t\tc, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tch <- fmt.Errorf(\"Accept failed: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer c.Close()\n\t\tch <- nil\n\t}()\n\n\tladdr, err := ResolveTCPAddr(\"tcp4\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatalf(\"ResolveTCPAddr failed: %v\", err)\n\t}\n\td := &Dialer{LocalAddr: laddr}\n\tc, err := d.Dial(\"tcp4\", ln.Addr().String())\n\tif err != nil {\n\t\tt.Fatalf(\"Dial failed: %v\", err)\n\t}\n\tdefer c.Close()\n\tc.Read(make([]byte, 1))\n\terr = <-ch\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\n\tPackage unsafe contains operations that step around the type safety of Go programs.\n*\/\npackage unsafe\n\n\/\/ ArbitraryType is here for the purposes of documentation only and is not actually\n\/\/ part of the unsafe package.  It represents the type of an arbitrary Go expression.\ntype ArbitraryType int\n\n\/\/ Pointer represents a pointer to an arbitrary type.  There are three special operations\n\/\/ available for type Pointer that are not available for other types.\n\/\/\t1) A pointer value of any type can be converted to a Pointer.\n\/\/\t2) A Pointer can be converted to a pointer value of any type.\n\/\/\t3) A uintptr can be converted to a Pointer.\n\/\/\t4) A Pointer can be converted to a uintptr.\n\/\/ Pointer therefore allows a program to defeat the type system and read and write\n\/\/ arbitrary memory. It should be used with extreme care.\ntype Pointer *ArbitraryType\n\n\/\/ Sizeof returns the size in bytes occupied by the value v.  The size is that of the\n\/\/ \"top level\" of the value only.  For instance, if v is a slice, it returns the size of\n\/\/ the slice descriptor, not the size of the memory referenced by the slice.\nfunc Sizeof(v ArbitraryType) uintptr\n\n\/\/ Offsetof returns the offset within the struct of the field represented by v,\n\/\/ which must be of the form struct_value.field.  In other words, it returns the\n\/\/ number of bytes between the start of the struct and the start of the field.\nfunc Offsetof(v ArbitraryType) uintptr\n\n\/\/ Alignof returns the alignment of the value v.  It is the maximum value m such\n\/\/ that the address of a variable with the type of v will always always be zero mod m.\n\/\/ If v is of the form obj.f, it returns the alignment of field f within struct object obj.\nfunc Alignof(v ArbitraryType) uintptr\n\n\/\/ Typeof returns the type of an interface value, a runtime.Type.\nfunc Typeof(i interface{}) (typ interface{})\n\n\/\/ Reflect unpacks an interface value into its type and the address of a copy of the\n\/\/ internal value.\nfunc Reflect(i interface{}) (typ interface{}, addr Pointer)\n\n\/\/ Unreflect inverts Reflect: Given a type and a pointer to a value, it returns an\n\/\/ empty interface value with contents the type and the value (not the pointer to\n\/\/ the value).  The typ is assumed to contain a pointer to a runtime type; the type\n\/\/ information in the interface{} is ignored, so that, for example, both\n\/\/ *reflect.structType and *runtime.StructType can be passed for typ.\nfunc Unreflect(typ interface{}, addr Pointer) (ret interface{})\n\n\/\/ New allocates and returns a pointer to memory for a new value of the given type.\n\/\/ The typ is assumed to hold a pointer to a runtime type.\n\/\/ Callers should use reflect.New or reflect.Zero instead of invoking unsafe.New directly.\nfunc New(typ interface{}) Pointer\n\n\/\/ NewArray allocates and returns a pointer to an array of n elements of the given type.\n\/\/ The typ is assumed to hold a pointer to a runtime type.\n\/\/ Callers should use reflect.MakeSlice instead of invoking unsafe.NewArray directly.\nfunc NewArray(typ interface{}, n int) Pointer\n<commit_msg>unsafe: Alignof and Offsetof now use the same style<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\n\tPackage unsafe contains operations that step around the type safety of Go programs.\n*\/\npackage unsafe\n\n\/\/ ArbitraryType is here for the purposes of documentation only and is not actually\n\/\/ part of the unsafe package.  It represents the type of an arbitrary Go expression.\ntype ArbitraryType int\n\n\/\/ Pointer represents a pointer to an arbitrary type.  There are three special operations\n\/\/ available for type Pointer that are not available for other types.\n\/\/\t1) A pointer value of any type can be converted to a Pointer.\n\/\/\t2) A Pointer can be converted to a pointer value of any type.\n\/\/\t3) A uintptr can be converted to a Pointer.\n\/\/\t4) A Pointer can be converted to a uintptr.\n\/\/ Pointer therefore allows a program to defeat the type system and read and write\n\/\/ arbitrary memory. It should be used with extreme care.\ntype Pointer *ArbitraryType\n\n\/\/ Sizeof returns the size in bytes occupied by the value v.  The size is that of the\n\/\/ \"top level\" of the value only.  For instance, if v is a slice, it returns the size of\n\/\/ the slice descriptor, not the size of the memory referenced by the slice.\nfunc Sizeof(v ArbitraryType) uintptr\n\n\/\/ Offsetof returns the offset within the struct of the field represented by v,\n\/\/ which must be of the form structValue.field.  In other words, it returns the\n\/\/ number of bytes between the start of the struct and the start of the field.\nfunc Offsetof(v ArbitraryType) uintptr\n\n\/\/ Alignof returns the alignment of the value v.  It is the maximum value m such\n\/\/ that the address of a variable with the type of v will always always be zero mod m.\n\/\/ If v is of the form structValue.field, it returns the alignment of field f within struct object obj.\nfunc Alignof(v ArbitraryType) uintptr\n\n\/\/ Typeof returns the type of an interface value, a runtime.Type.\nfunc Typeof(i interface{}) (typ interface{})\n\n\/\/ Reflect unpacks an interface value into its type and the address of a copy of the\n\/\/ internal value.\nfunc Reflect(i interface{}) (typ interface{}, addr Pointer)\n\n\/\/ Unreflect inverts Reflect: Given a type and a pointer to a value, it returns an\n\/\/ empty interface value with contents the type and the value (not the pointer to\n\/\/ the value).  The typ is assumed to contain a pointer to a runtime type; the type\n\/\/ information in the interface{} is ignored, so that, for example, both\n\/\/ *reflect.structType and *runtime.StructType can be passed for typ.\nfunc Unreflect(typ interface{}, addr Pointer) (ret interface{})\n\n\/\/ New allocates and returns a pointer to memory for a new value of the given type.\n\/\/ The typ is assumed to hold a pointer to a runtime type.\n\/\/ Callers should use reflect.New or reflect.Zero instead of invoking unsafe.New directly.\nfunc New(typ interface{}) Pointer\n\n\/\/ NewArray allocates and returns a pointer to an array of n elements of the given type.\n\/\/ The typ is assumed to hold a pointer to a runtime type.\n\/\/ Callers should use reflect.MakeSlice instead of invoking unsafe.NewArray directly.\nfunc NewArray(typ interface{}, n int) Pointer\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage xml\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\/\/ Stripped down Atom feed data structures.\n\nfunc TestUnmarshalFeed(t *testing.T) {\n\tvar f Feed\n\tif err := Unmarshal(StringReader(rssFeedString), &f); err != nil {\n\t\tt.Fatalf(\"Unmarshal: %s\", err)\n\t}\n\tif !reflect.DeepEqual(f, rssFeed) {\n\t\tt.Fatalf(\"have %#v\\nwant %#v\", f, rssFeed)\n\t}\n}\n\n\/\/ hget http:\/\/codereview.appspot.com\/rss\/mine\/rsc\nconst rssFeedString = `\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<feed xmlns=\"http:\/\/www.w3.org\/2005\/Atom\" xml:lang=\"en-us\"><title>Code Review - My issues<\/title><link href=\"http:\/\/codereview.appspot.com\/\" rel=\"alternate\"><\/link><li-nk href=\"http:\/\/codereview.appspot.com\/rss\/mine\/rsc\" rel=\"self\"><\/li-nk><id>http:\/\/codereview.appspot.com\/<\/id><updated>2009-10-04T01:35:58+00:00<\/updated><author><name>rietveld&lt;&gt;<\/name><\/author><entry><title>rietveld: an attempt at pubsubhubbub\n<\/title><link hre-f=\"http:\/\/codereview.appspot.com\/126085\" rel=\"alternate\"><\/link><updated>2009-10-04T01:35:58+00:00<\/updated><author><name>email-address-removed<\/name><\/author><id>urn:md5:134d9179c41f806be79b3a5f7877d19a<\/id><summary type=\"html\">\n  An attempt at adding pubsubhubbub support to Rietveld.\nhttp:\/\/code.google.com\/p\/pubsubhubbub\nhttp:\/\/code.google.com\/p\/rietveld\/issues\/detail?id=155\n\nThe server side of the protocol is trivial:\n  1. add a &amp;lt;link rel=&amp;quot;hub&amp;quot; href=&amp;quot;hub-server&amp;quot;&amp;gt; tag to all\n     feeds that will be pubsubhubbubbed.\n  2. every time one of those feeds changes, tell the hub\n     with a simple POST request.\n\nI have tested this by adding debug prints to a local hub\nserver and checking that the server got the right publish\nrequests.\n\nI can&amp;#39;t quite get the server to work, but I think the bug\nis not in my code.  I think that the server expects to be\nable to grab the feed and see the feed&amp;#39;s actual URL in\nthe link rel=&amp;quot;self&amp;quot;, but the default value for that drops\nthe :port from the URL, and I cannot for the life of me\nfigure out how to get the Atom generator deep inside\ndjango not to do that, or even where it is doing that,\nor even what code is running to generate the Atom feed.\n(I thought I knew but I added some assert False statements\nand it kept running!)\n\nIgnoring that particular problem, I would appreciate\nfeedback on the right way to get the two values at\nthe top of feeds.py marked NOTE(rsc).\n\n\n<\/summary><\/entry><entry><title>rietveld: correct tab handling\n<\/title><link href=\"http:\/\/codereview.appspot.com\/124106\" rel=\"alternate\"><\/link><updated>2009-10-03T23:02:17+00:00<\/updated><author><name>email-address-removed<\/name><\/author><id>urn:md5:0a2a4f19bb815101f0ba2904aed7c35a<\/id><summary type=\"html\">\n  This fixes the buggy tab rendering that can be seen at\nhttp:\/\/codereview.appspot.com\/116075\/diff\/1\/2\n\nThe fundamental problem was that the tab code was\nnot being told what column the text began in, so it\ndidn&amp;#39;t know where to put the tab stops.  Another problem\nwas that some of the code assumed that string byte\noffsets were the same as column offsets, which is only\ntrue if there are no tabs.\n\nIn the process of fixing this, I cleaned up the arguments\nto Fold and ExpandTabs and renamed them Break and\n_ExpandTabs so that I could be sure that I found all the\ncall sites.  I also wanted to verify that ExpandTabs was\nnot being used from outside intra_region_diff.py.\n\n\n<\/summary><\/entry><\/feed> \t   `\n\ntype Feed struct {\n\tXMLName Name \"http:\/\/www.w3.org\/2005\/Atom feed\"\n\tTitle   string\n\tId      string\n\tLink    []Link\n\tUpdated Time\n\tAuthor  Person\n\tEntry   []Entry\n}\n\ntype Entry struct {\n\tTitle   string\n\tId      string\n\tLink    []Link\n\tUpdated Time\n\tAuthor  Person\n\tSummary Text\n}\n\ntype Link struct {\n\tRel  string \"attr\"\n\tHref string \"attr\"\n}\n\ntype Person struct {\n\tName     string\n\tURI      string\n\tEmail    string\n\tInnerXML string \"innerxml\"\n}\n\ntype Text struct {\n\tType string \"attr\"\n\tBody string \"chardata\"\n}\n\ntype Time string\n\nvar rssFeed = Feed{\n\tXMLName: Name{\"http:\/\/www.w3.org\/2005\/Atom\", \"feed\"},\n\tTitle:   \"Code Review - My issues\",\n\tLink: []Link{\n\t\t{Rel: \"alternate\", Href: \"http:\/\/codereview.appspot.com\/\"},\n\t\t{Rel: \"self\", Href: \"http:\/\/codereview.appspot.com\/rss\/mine\/rsc\"},\n\t},\n\tId:      \"http:\/\/codereview.appspot.com\/\",\n\tUpdated: \"2009-10-04T01:35:58+00:00\",\n\tAuthor: Person{\n\t\tName:     \"rietveld<>\",\n\t\tInnerXML: \"<name>rietveld&lt;&gt;<\/name>\",\n\t},\n\tEntry: []Entry{\n\t\t{\n\t\t\tTitle: \"rietveld: an attempt at pubsubhubbub\\n\",\n\t\t\tLink: []Link{\n\t\t\t\t{Rel: \"alternate\", Href: \"http:\/\/codereview.appspot.com\/126085\"},\n\t\t\t},\n\t\t\tUpdated: \"2009-10-04T01:35:58+00:00\",\n\t\t\tAuthor: Person{\n\t\t\t\tName:     \"email-address-removed\",\n\t\t\t\tInnerXML: \"<name>email-address-removed<\/name>\",\n\t\t\t},\n\t\t\tId: \"urn:md5:134d9179c41f806be79b3a5f7877d19a\",\n\t\t\tSummary: Text{\n\t\t\t\tType: \"html\",\n\t\t\t\tBody: `\n  An attempt at adding pubsubhubbub support to Rietveld.\nhttp:\/\/code.google.com\/p\/pubsubhubbub\nhttp:\/\/code.google.com\/p\/rietveld\/issues\/detail?id=155\n\nThe server side of the protocol is trivial:\n  1. add a &lt;link rel=&quot;hub&quot; href=&quot;hub-server&quot;&gt; tag to all\n     feeds that will be pubsubhubbubbed.\n  2. every time one of those feeds changes, tell the hub\n     with a simple POST request.\n\nI have tested this by adding debug prints to a local hub\nserver and checking that the server got the right publish\nrequests.\n\nI can&#39;t quite get the server to work, but I think the bug\nis not in my code.  I think that the server expects to be\nable to grab the feed and see the feed&#39;s actual URL in\nthe link rel=&quot;self&quot;, but the default value for that drops\nthe :port from the URL, and I cannot for the life of me\nfigure out how to get the Atom generator deep inside\ndjango not to do that, or even where it is doing that,\nor even what code is running to generate the Atom feed.\n(I thought I knew but I added some assert False statements\nand it kept running!)\n\nIgnoring that particular problem, I would appreciate\nfeedback on the right way to get the two values at\nthe top of feeds.py marked NOTE(rsc).\n\n\n`,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tTitle: \"rietveld: correct tab handling\\n\",\n\t\t\tLink: []Link{\n\t\t\t\t{Rel: \"alternate\", Href: \"http:\/\/codereview.appspot.com\/124106\"},\n\t\t\t},\n\t\t\tUpdated: \"2009-10-03T23:02:17+00:00\",\n\t\t\tAuthor: Person{\n\t\t\t\tName:     \"email-address-removed\",\n\t\t\t\tInnerXML: \"<name>email-address-removed<\/name>\",\n\t\t\t},\n\t\t\tId: \"urn:md5:0a2a4f19bb815101f0ba2904aed7c35a\",\n\t\t\tSummary: Text{\n\t\t\t\tType: \"html\",\n\t\t\t\tBody: `\n  This fixes the buggy tab rendering that can be seen at\nhttp:\/\/codereview.appspot.com\/116075\/diff\/1\/2\n\nThe fundamental problem was that the tab code was\nnot being told what column the text began in, so it\ndidn&#39;t know where to put the tab stops.  Another problem\nwas that some of the code assumed that string byte\noffsets were the same as column offsets, which is only\ntrue if there are no tabs.\n\nIn the process of fixing this, I cleaned up the arguments\nto Fold and ExpandTabs and renamed them Break and\n_ExpandTabs so that I could be sure that I found all the\ncall sites.  I also wanted to verify that ExpandTabs was\nnot being used from outside intra_region_diff.py.\n\n\n`,\n\t\t\t},\n\t\t},\n\t},\n}\n\ntype FieldNameTest struct {\n\tin, out string\n}\n\nvar FieldNameTests = []FieldNameTest{\n\t{\"Profile-Image\", \"profileimage\"},\n\t{\"_score\", \"score\"},\n}\n\nfunc TestFieldName(t *testing.T) {\n\tfor _, tt := range FieldNameTests {\n\t\ta := fieldName(tt.in)\n\t\tif a != tt.out {\n\t\t\tt.Fatalf(\"have %#v\\nwant %#v\\n\\n\", a, tt.out)\n\t\t}\n\t}\n}\n\nconst pathTestString = `\n<result>\n    <before>1<\/before>\n    <items>\n        <item1>\n            <value>A<\/value>\n        <\/item1>\n        <item2>\n            <value>B<\/value>\n        <\/item2>\n        <Item1>\n            <Value>C<\/Value>\n            <Value>D<\/Value>\n        <\/Item1>\n    <\/items>\n    <after>2<\/after>\n<\/result>\n`\n\ntype PathTestItem struct {\n\tValue string\n}\n\ntype PathTestA struct {\n\tItems         []PathTestItem \">item1\"\n\tBefore, After string\n}\n\ntype PathTestB struct {\n\tOther         []PathTestItem \"items>Item1\"\n\tBefore, After string\n}\n\ntype PathTestC struct {\n\tValues1       []string \"items>item1>value\"\n\tValues2       []string \"items>item2>value\"\n\tBefore, After string\n}\n\ntype PathTestSet struct {\n\tItem1 []PathTestItem\n}\n\ntype PathTestD struct {\n\tOther         PathTestSet \"items>\"\n\tBefore, After string\n}\n\nvar pathTests = []interface{}{\n\t&PathTestA{Items: []PathTestItem{{\"A\"}, {\"D\"}}, Before: \"1\", After: \"2\"},\n\t&PathTestB{Other: []PathTestItem{{\"A\"}, {\"D\"}}, Before: \"1\", After: \"2\"},\n\t&PathTestC{Values1: []string{\"A\", \"C\", \"D\"}, Values2: []string{\"B\"}, Before: \"1\", After: \"2\"},\n\t&PathTestD{Other: PathTestSet{Item1: []PathTestItem{{\"A\"}, {\"D\"}}}, Before: \"1\", After: \"2\"},\n}\n\nfunc TestUnmarshalPaths(t *testing.T) {\n\tfor _, pt := range pathTests {\n\t\tp := reflect.MakeZero(reflect.NewValue(pt).Type()).(*reflect.PtrValue)\n\t\tp.PointTo(reflect.MakeZero(p.Type().(*reflect.PtrType).Elem()))\n\t\tv := p.Interface()\n\t\tif err := Unmarshal(StringReader(pathTestString), v); err != nil {\n\t\t\tt.Fatalf(\"Unmarshal: %s\", err)\n\t\t}\n\t\tif !reflect.DeepEqual(v, pt) {\n\t\t\tt.Fatalf(\"have %#v\\nwant %#v\", v, pt)\n\t\t}\n\t}\n}\n\ntype BadPathTestA struct {\n\tFirst  string \"items>item1\"\n\tOther  string \"items>item2\"\n\tSecond string \"items>\"\n}\n\ntype BadPathTestB struct {\n\tOther  string \"items>item2>value\"\n\tFirst  string \"items>item1\"\n\tSecond string \"items>item1>value\"\n}\n\nvar badPathTests = []struct {\n\tv, e interface{}\n}{\n\t{&BadPathTestA{}, &TagPathError{reflect.Typeof(BadPathTestA{}), \"First\", \"items>item1\", \"Second\", \"items>\"}},\n\t{&BadPathTestB{}, &TagPathError{reflect.Typeof(BadPathTestB{}), \"First\", \"items>item1\", \"Second\", \"items>item1>value\"}},\n}\n\nfunc TestUnmarshalBadPaths(t *testing.T) {\n\tfor _, tt := range badPathTests {\n\t\terr := Unmarshal(StringReader(pathTestString), tt.v)\n\t\tif !reflect.DeepEqual(err, tt.e) {\n\t\t\tt.Fatalf(\"Unmarshal with %#v didn't fail properly: %#v\", tt.v, err)\n\t\t}\n\t}\n}\n<commit_msg>xml: fix typo in test.<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage xml\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n\/\/ Stripped down Atom feed data structures.\n\nfunc TestUnmarshalFeed(t *testing.T) {\n\tvar f Feed\n\tif err := Unmarshal(StringReader(atomFeedString), &f); err != nil {\n\t\tt.Fatalf(\"Unmarshal: %s\", err)\n\t}\n\tif !reflect.DeepEqual(f, atomFeed) {\n\t\tt.Fatalf(\"have %#v\\nwant %#v\", f, atomFeed)\n\t}\n}\n\n\/\/ hget http:\/\/codereview.appspot.com\/rss\/mine\/rsc\nconst atomFeedString = `\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<feed xmlns=\"http:\/\/www.w3.org\/2005\/Atom\" xml:lang=\"en-us\"><title>Code Review - My issues<\/title><link href=\"http:\/\/codereview.appspot.com\/\" rel=\"alternate\"><\/link><li-nk href=\"http:\/\/codereview.appspot.com\/rss\/mine\/rsc\" rel=\"self\"><\/li-nk><id>http:\/\/codereview.appspot.com\/<\/id><updated>2009-10-04T01:35:58+00:00<\/updated><author><name>rietveld&lt;&gt;<\/name><\/author><entry><title>rietveld: an attempt at pubsubhubbub\n<\/title><link hre-f=\"http:\/\/codereview.appspot.com\/126085\" rel=\"alternate\"><\/link><updated>2009-10-04T01:35:58+00:00<\/updated><author><name>email-address-removed<\/name><\/author><id>urn:md5:134d9179c41f806be79b3a5f7877d19a<\/id><summary type=\"html\">\n  An attempt at adding pubsubhubbub support to Rietveld.\nhttp:\/\/code.google.com\/p\/pubsubhubbub\nhttp:\/\/code.google.com\/p\/rietveld\/issues\/detail?id=155\n\nThe server side of the protocol is trivial:\n  1. add a &amp;lt;link rel=&amp;quot;hub&amp;quot; href=&amp;quot;hub-server&amp;quot;&amp;gt; tag to all\n     feeds that will be pubsubhubbubbed.\n  2. every time one of those feeds changes, tell the hub\n     with a simple POST request.\n\nI have tested this by adding debug prints to a local hub\nserver and checking that the server got the right publish\nrequests.\n\nI can&amp;#39;t quite get the server to work, but I think the bug\nis not in my code.  I think that the server expects to be\nable to grab the feed and see the feed&amp;#39;s actual URL in\nthe link rel=&amp;quot;self&amp;quot;, but the default value for that drops\nthe :port from the URL, and I cannot for the life of me\nfigure out how to get the Atom generator deep inside\ndjango not to do that, or even where it is doing that,\nor even what code is running to generate the Atom feed.\n(I thought I knew but I added some assert False statements\nand it kept running!)\n\nIgnoring that particular problem, I would appreciate\nfeedback on the right way to get the two values at\nthe top of feeds.py marked NOTE(rsc).\n\n\n<\/summary><\/entry><entry><title>rietveld: correct tab handling\n<\/title><link href=\"http:\/\/codereview.appspot.com\/124106\" rel=\"alternate\"><\/link><updated>2009-10-03T23:02:17+00:00<\/updated><author><name>email-address-removed<\/name><\/author><id>urn:md5:0a2a4f19bb815101f0ba2904aed7c35a<\/id><summary type=\"html\">\n  This fixes the buggy tab rendering that can be seen at\nhttp:\/\/codereview.appspot.com\/116075\/diff\/1\/2\n\nThe fundamental problem was that the tab code was\nnot being told what column the text began in, so it\ndidn&amp;#39;t know where to put the tab stops.  Another problem\nwas that some of the code assumed that string byte\noffsets were the same as column offsets, which is only\ntrue if there are no tabs.\n\nIn the process of fixing this, I cleaned up the arguments\nto Fold and ExpandTabs and renamed them Break and\n_ExpandTabs so that I could be sure that I found all the\ncall sites.  I also wanted to verify that ExpandTabs was\nnot being used from outside intra_region_diff.py.\n\n\n<\/summary><\/entry><\/feed> \t   `\n\ntype Feed struct {\n\tXMLName Name \"http:\/\/www.w3.org\/2005\/Atom feed\"\n\tTitle   string\n\tId      string\n\tLink    []Link\n\tUpdated Time\n\tAuthor  Person\n\tEntry   []Entry\n}\n\ntype Entry struct {\n\tTitle   string\n\tId      string\n\tLink    []Link\n\tUpdated Time\n\tAuthor  Person\n\tSummary Text\n}\n\ntype Link struct {\n\tRel  string \"attr\"\n\tHref string \"attr\"\n}\n\ntype Person struct {\n\tName     string\n\tURI      string\n\tEmail    string\n\tInnerXML string \"innerxml\"\n}\n\ntype Text struct {\n\tType string \"attr\"\n\tBody string \"chardata\"\n}\n\ntype Time string\n\nvar atomFeed = Feed{\n\tXMLName: Name{\"http:\/\/www.w3.org\/2005\/Atom\", \"feed\"},\n\tTitle:   \"Code Review - My issues\",\n\tLink: []Link{\n\t\t{Rel: \"alternate\", Href: \"http:\/\/codereview.appspot.com\/\"},\n\t\t{Rel: \"self\", Href: \"http:\/\/codereview.appspot.com\/rss\/mine\/rsc\"},\n\t},\n\tId:      \"http:\/\/codereview.appspot.com\/\",\n\tUpdated: \"2009-10-04T01:35:58+00:00\",\n\tAuthor: Person{\n\t\tName:     \"rietveld<>\",\n\t\tInnerXML: \"<name>rietveld&lt;&gt;<\/name>\",\n\t},\n\tEntry: []Entry{\n\t\t{\n\t\t\tTitle: \"rietveld: an attempt at pubsubhubbub\\n\",\n\t\t\tLink: []Link{\n\t\t\t\t{Rel: \"alternate\", Href: \"http:\/\/codereview.appspot.com\/126085\"},\n\t\t\t},\n\t\t\tUpdated: \"2009-10-04T01:35:58+00:00\",\n\t\t\tAuthor: Person{\n\t\t\t\tName:     \"email-address-removed\",\n\t\t\t\tInnerXML: \"<name>email-address-removed<\/name>\",\n\t\t\t},\n\t\t\tId: \"urn:md5:134d9179c41f806be79b3a5f7877d19a\",\n\t\t\tSummary: Text{\n\t\t\t\tType: \"html\",\n\t\t\t\tBody: `\n  An attempt at adding pubsubhubbub support to Rietveld.\nhttp:\/\/code.google.com\/p\/pubsubhubbub\nhttp:\/\/code.google.com\/p\/rietveld\/issues\/detail?id=155\n\nThe server side of the protocol is trivial:\n  1. add a &lt;link rel=&quot;hub&quot; href=&quot;hub-server&quot;&gt; tag to all\n     feeds that will be pubsubhubbubbed.\n  2. every time one of those feeds changes, tell the hub\n     with a simple POST request.\n\nI have tested this by adding debug prints to a local hub\nserver and checking that the server got the right publish\nrequests.\n\nI can&#39;t quite get the server to work, but I think the bug\nis not in my code.  I think that the server expects to be\nable to grab the feed and see the feed&#39;s actual URL in\nthe link rel=&quot;self&quot;, but the default value for that drops\nthe :port from the URL, and I cannot for the life of me\nfigure out how to get the Atom generator deep inside\ndjango not to do that, or even where it is doing that,\nor even what code is running to generate the Atom feed.\n(I thought I knew but I added some assert False statements\nand it kept running!)\n\nIgnoring that particular problem, I would appreciate\nfeedback on the right way to get the two values at\nthe top of feeds.py marked NOTE(rsc).\n\n\n`,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tTitle: \"rietveld: correct tab handling\\n\",\n\t\t\tLink: []Link{\n\t\t\t\t{Rel: \"alternate\", Href: \"http:\/\/codereview.appspot.com\/124106\"},\n\t\t\t},\n\t\t\tUpdated: \"2009-10-03T23:02:17+00:00\",\n\t\t\tAuthor: Person{\n\t\t\t\tName:     \"email-address-removed\",\n\t\t\t\tInnerXML: \"<name>email-address-removed<\/name>\",\n\t\t\t},\n\t\t\tId: \"urn:md5:0a2a4f19bb815101f0ba2904aed7c35a\",\n\t\t\tSummary: Text{\n\t\t\t\tType: \"html\",\n\t\t\t\tBody: `\n  This fixes the buggy tab rendering that can be seen at\nhttp:\/\/codereview.appspot.com\/116075\/diff\/1\/2\n\nThe fundamental problem was that the tab code was\nnot being told what column the text began in, so it\ndidn&#39;t know where to put the tab stops.  Another problem\nwas that some of the code assumed that string byte\noffsets were the same as column offsets, which is only\ntrue if there are no tabs.\n\nIn the process of fixing this, I cleaned up the arguments\nto Fold and ExpandTabs and renamed them Break and\n_ExpandTabs so that I could be sure that I found all the\ncall sites.  I also wanted to verify that ExpandTabs was\nnot being used from outside intra_region_diff.py.\n\n\n`,\n\t\t\t},\n\t\t},\n\t},\n}\n\ntype FieldNameTest struct {\n\tin, out string\n}\n\nvar FieldNameTests = []FieldNameTest{\n\t{\"Profile-Image\", \"profileimage\"},\n\t{\"_score\", \"score\"},\n}\n\nfunc TestFieldName(t *testing.T) {\n\tfor _, tt := range FieldNameTests {\n\t\ta := fieldName(tt.in)\n\t\tif a != tt.out {\n\t\t\tt.Fatalf(\"have %#v\\nwant %#v\\n\\n\", a, tt.out)\n\t\t}\n\t}\n}\n\nconst pathTestString = `\n<result>\n    <before>1<\/before>\n    <items>\n        <item1>\n            <value>A<\/value>\n        <\/item1>\n        <item2>\n            <value>B<\/value>\n        <\/item2>\n        <Item1>\n            <Value>C<\/Value>\n            <Value>D<\/Value>\n        <\/Item1>\n    <\/items>\n    <after>2<\/after>\n<\/result>\n`\n\ntype PathTestItem struct {\n\tValue string\n}\n\ntype PathTestA struct {\n\tItems         []PathTestItem \">item1\"\n\tBefore, After string\n}\n\ntype PathTestB struct {\n\tOther         []PathTestItem \"items>Item1\"\n\tBefore, After string\n}\n\ntype PathTestC struct {\n\tValues1       []string \"items>item1>value\"\n\tValues2       []string \"items>item2>value\"\n\tBefore, After string\n}\n\ntype PathTestSet struct {\n\tItem1 []PathTestItem\n}\n\ntype PathTestD struct {\n\tOther         PathTestSet \"items>\"\n\tBefore, After string\n}\n\nvar pathTests = []interface{}{\n\t&PathTestA{Items: []PathTestItem{{\"A\"}, {\"D\"}}, Before: \"1\", After: \"2\"},\n\t&PathTestB{Other: []PathTestItem{{\"A\"}, {\"D\"}}, Before: \"1\", After: \"2\"},\n\t&PathTestC{Values1: []string{\"A\", \"C\", \"D\"}, Values2: []string{\"B\"}, Before: \"1\", After: \"2\"},\n\t&PathTestD{Other: PathTestSet{Item1: []PathTestItem{{\"A\"}, {\"D\"}}}, Before: \"1\", After: \"2\"},\n}\n\nfunc TestUnmarshalPaths(t *testing.T) {\n\tfor _, pt := range pathTests {\n\t\tp := reflect.MakeZero(reflect.NewValue(pt).Type()).(*reflect.PtrValue)\n\t\tp.PointTo(reflect.MakeZero(p.Type().(*reflect.PtrType).Elem()))\n\t\tv := p.Interface()\n\t\tif err := Unmarshal(StringReader(pathTestString), v); err != nil {\n\t\t\tt.Fatalf(\"Unmarshal: %s\", err)\n\t\t}\n\t\tif !reflect.DeepEqual(v, pt) {\n\t\t\tt.Fatalf(\"have %#v\\nwant %#v\", v, pt)\n\t\t}\n\t}\n}\n\ntype BadPathTestA struct {\n\tFirst  string \"items>item1\"\n\tOther  string \"items>item2\"\n\tSecond string \"items>\"\n}\n\ntype BadPathTestB struct {\n\tOther  string \"items>item2>value\"\n\tFirst  string \"items>item1\"\n\tSecond string \"items>item1>value\"\n}\n\nvar badPathTests = []struct {\n\tv, e interface{}\n}{\n\t{&BadPathTestA{}, &TagPathError{reflect.Typeof(BadPathTestA{}), \"First\", \"items>item1\", \"Second\", \"items>\"}},\n\t{&BadPathTestB{}, &TagPathError{reflect.Typeof(BadPathTestB{}), \"First\", \"items>item1\", \"Second\", \"items>item1>value\"}},\n}\n\nfunc TestUnmarshalBadPaths(t *testing.T) {\n\tfor _, tt := range badPathTests {\n\t\terr := Unmarshal(StringReader(pathTestString), tt.v)\n\t\tif !reflect.DeepEqual(err, tt.e) {\n\t\t\tt.Fatalf(\"Unmarshal with %#v didn't fail properly: %#v\", tt.v, err)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package brokers\n\nimport (\n\t\"github.com\/kafkactl\/api\/client\"\n)\n\ntype BrokerAdd struct{}\n\nfunc Add(api client.APIClient, in *BrokerAdd) error {}\n<commit_msg>brokers: Add minor error fix (imports & return)<commit_after>package brokers\n\nimport (\n\t\"github.com\/eddyzags\/kafkactl\/api\/client\"\n)\n\ntype BrokerAdd struct{}\n\nfunc Add(api client.APIClient, in *BrokerAdd) error {\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Force apt-get to use IPv4<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage oglematchers_test\n\nimport (\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/ogletest\"\n\t\"errors\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype allOfFakeMatcher struct {\n\tdesc string\n\tres  MatchResult\n\terr  error\n}\n\nfunc (m *allOfFakeMatcher) Matches(c interface{}) (MatchResult, error) {\n\treturn m.res, m.err\n}\n\nfunc (m *allOfFakeMatcher) Description() string {\n\treturn m.desc\n}\n\ntype AllOfTest struct {\n}\n\nfunc init() { RegisterTestSuite(&AllOfTest{}) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *AllOfTest) DescriptionWithEmptySet() {\n\tm := AllOf()\n\tExpectEq(\"is anything\", m.Description())\n}\n\nfunc (t *AllOfTest) DescriptionWithOneMatcher() {\n\tm := AllOf(&allOfFakeMatcher{\"taco\", MATCH_FALSE, nil})\n\tExpectEq(\"taco\", m.Description())\n}\n\nfunc (t *AllOfTest) DescriptionWithMultipleMatchers() {\n\tm := AllOf(\n\t\t&allOfFakeMatcher{\"taco\", MATCH_FALSE, nil},\n\t\t&allOfFakeMatcher{\"burrito\", MATCH_FALSE, nil},\n\t\t&allOfFakeMatcher{\"enchilada\", MATCH_FALSE, nil})\n\n\tExpectEq(\"taco, and burrito, and enchilada\", m.Description())\n}\n\nfunc (t *AllOfTest) EmptySet() {\n\tm := AllOf()\n\tres, err := m.Matches(17)\n\n\tExpectEq(MATCH_TRUE, res)\n\tExpectEq(nil, err)\n}\n\nfunc (t *AllOfTest) OneMatcherSaysUndefinedAndSomeSayFalse() {\n\tm := AllOf(\n\t\t&allOfFakeMatcher{\"\", MATCH_FALSE, errors.New(\"\")},\n\t\t&allOfFakeMatcher{\"\", MATCH_UNDEFINED, errors.New(\"taco\")},\n\t\t&allOfFakeMatcher{\"\", MATCH_FALSE, errors.New(\"\")},\n\t\t&allOfFakeMatcher{\"\", MATCH_TRUE, nil})\n\n\tres, err := m.Matches(17)\n\n\tExpectEq(MATCH_UNDEFINED, res)\n\tExpectThat(err, Error(Equals(\"taco\")))\n}\n\nfunc (t *AllOfTest) OneMatcherSaysFalseAndOthersSayTrue() {\n\tm := AllOf(\n\t\t&allOfFakeMatcher{\"\", MATCH_TRUE, nil},\n\t\t&allOfFakeMatcher{\"\", MATCH_FALSE, errors.New(\"taco\")},\n\t\t&allOfFakeMatcher{\"\", MATCH_TRUE, nil})\n\n\tres, err := m.Matches(17)\n\n\tExpectEq(MATCH_FALSE, res)\n\tExpectThat(err, Error(Equals(\"taco\")))\n}\n\nfunc (t *AllOfTest) AllMatchersSayTrue() {\n\tm := AllOf(\n\t\t&allOfFakeMatcher{\"\", MATCH_TRUE, nil},\n\t\t&allOfFakeMatcher{\"\", MATCH_TRUE, nil},\n\t\t&allOfFakeMatcher{\"\", MATCH_TRUE, nil})\n\n\tres, err := m.Matches(17)\n\n\tExpectEq(MATCH_TRUE, res)\n\tExpectEq(nil, err)\n}\n<commit_msg>Fixed up all_of_test.go for #20.<commit_after>\/\/ Copyright 2011 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage oglematchers_test\n\nimport (\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/ogletest\"\n\t\"errors\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype allOfFakeMatcher struct {\n\tdesc string\n\tres  bool\n\terr  error\n}\n\nfunc (m *allOfFakeMatcher) Matches(c interface{}) (bool, error) {\n\treturn m.res, m.err\n}\n\nfunc (m *allOfFakeMatcher) Description() string {\n\treturn m.desc\n}\n\ntype AllOfTest struct {\n}\n\nfunc init() { RegisterTestSuite(&AllOfTest{}) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *AllOfTest) DescriptionWithEmptySet() {\n\tm := AllOf()\n\tExpectEq(\"is anything\", m.Description())\n}\n\nfunc (t *AllOfTest) DescriptionWithOneMatcher() {\n\tm := AllOf(&allOfFakeMatcher{\"taco\", false, errors.New(\"\")})\n\tExpectEq(\"taco\", m.Description())\n}\n\nfunc (t *AllOfTest) DescriptionWithMultipleMatchers() {\n\tm := AllOf(\n\t\t&allOfFakeMatcher{\"taco\", false, errors.New(\"\")},\n\t\t&allOfFakeMatcher{\"burrito\", false, errors.New(\"\")},\n\t\t&allOfFakeMatcher{\"enchilada\", false, errors.New(\"\")})\n\n\tExpectEq(\"taco, and burrito, and enchilada\", m.Description())\n}\n\nfunc (t *AllOfTest) EmptySet() {\n\tm := AllOf()\n\tres, err := m.Matches(17)\n\n\tExpectTrue(res)\n\tExpectFalse(isFatal(err))\n\tExpectThat(err, Error(Equals(\"\")))\n}\n\nfunc (t *AllOfTest) OneMatcherReturnsFatalErrorAndSomeOthersFail() {\n\tm := AllOf(\n\t\t&allOfFakeMatcher{\"\", false, errors.New(\"\")},\n\t\t&allOfFakeMatcher{\"\", false, NewFatalError(\"taco\")},\n\t\t&allOfFakeMatcher{\"\", false, errors.New(\"\")},\n\t\t&allOfFakeMatcher{\"\", true, nil})\n\n\tres, err := m.Matches(17)\n\n\tExpectFalse(res)\n\tExpectTrue(isFatal(err))\n\tExpectThat(err, Error(Equals(\"taco\")))\n}\n\nfunc (t *AllOfTest) OneMatcherReturnsNonFatalAndOthersSayTrue() {\n\tm := AllOf(\n\t\t&allOfFakeMatcher{\"\", true, nil},\n\t\t&allOfFakeMatcher{\"\", false, errors.New(\"taco\")},\n\t\t&allOfFakeMatcher{\"\", true, nil})\n\n\tres, err := m.Matches(17)\n\n\tExpectFalse(res)\n\tExpectTrue(isFatal(err))\n\tExpectThat(err, Error(Equals(\"taco\")))\n}\n\nfunc (t *AllOfTest) AllMatchersSayTrue() {\n\tm := AllOf(\n\t\t&allOfFakeMatcher{\"\", true, nil},\n\t\t&allOfFakeMatcher{\"\", true, nil},\n\t\t&allOfFakeMatcher{\"\", true, nil})\n\n\tres, err := m.Matches(17)\n\n\tExpectTrue(res)\n\tExpectEq(nil, err)\n}\n<|endoftext|>"}
{"text":"<commit_before>package collaboration\n\nimport (\n\t\"fmt\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"math\/rand\"\n\tapimodels \"socialapi\/models\"\n\t\"socialapi\/rest\"\n\t\"socialapi\/workers\/collaboration\/models\"\n\t\"socialapi\/workers\/common\/runner\"\n\t\"testing\"\n\t\"time\"\n\n\t\"socialapi\/workers\/collaboration\"\n\t\"socialapi\/workers\/helper\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\nvar (\n\tAccountOldId = bson.NewObjectId()\n)\n\nfunc TestCollaborationPing(t *testing.T) {\n\tr := runner.New(\"collaboration-tests\")\n\terr := r.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer r.Close()\n\n\tmodelhelper.Initialize(r.Conf.Mongo)\n\tdefer modelhelper.Close()\n\n\tredisConn := helper.MustInitRedisConn(r.Conf)\n\tdefer redisConn.Close()\n\n\tredis := helper.MustGetRedisConn()\n\n\thandler := New(r.Log, redisConn, r.Conf, r.Kite)\n\n\tConvey(\"while pinging collaboration\", t, func() {\n\t\t\/\/ owner\n\t\towner := apimodels.NewAccount()\n\t\towner.OldId = AccountOldId.Hex()\n\t\towner, err := rest.CreateAccount(owner)\n\t\tSo(err, ShouldBeNil)\n\t\tSo(owner, ShouldNotBeNil)\n\n\t\townerSession, err := apimodels.FetchOrCreateSession(owner.Nick)\n\t\tSo(err, ShouldBeNil)\n\t\tSo(ownerSession, ShouldNotBeNil)\n\n\t\trand.Seed(time.Now().UnixNano())\n\n\t\treq := &models.Ping{\n\t\t\tAccountId: 1,\n\t\t\tFileId:    fmt.Sprintf(\"%d\", rand.Int63()),\n\t\t}\n\n\t\tConvey(\"while testing Ping\", func() {\n\t\t\tConvey(\"reponse should be success with valid ping\", func() {\n\t\t\t\terr := handler.Ping(req)\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(\"reponse should be success with invalid FileId\", func() {\n\t\t\t\treq.FileId = \"\"\n\t\t\t\terr := handler.Ping(req)\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(\"reponse should be success with invalid AccountId\", func() {\n\t\t\t\treq.AccountId = 0\n\t\t\t\terr := handler.Ping(req)\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(\"reponse should be success with invalid session\", func() {\n\t\t\t\treq := req\n\t\t\t\t\/\/ prepare an invalid session here\n\t\t\t\treq.CreatedAt = time.Now().UTC()\n\t\t\t\terr := redis.Setex(\n\t\t\t\t\tPrepareFileKey(req.FileId),\n\t\t\t\t\tcollaboration.ExpireSessionKeyDuration, \/\/ expire the key after this period\n\t\t\t\t\treq.CreatedAt.Add(-terminateSessionDuration),\n\t\t\t\t)\n\n\t\t\t\terr = handler.Ping(req)\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(\"after sleep time\", func() {\n\t\t\t\treq := req\n\n\t\t\t\tConvey(\"expired session should get invalidSessoin\", func() {\n\t\t\t\t\tst := sleepTime\n\t\t\t\t\tsleepTime = time.Millisecond * 110\n\n\t\t\t\t\ttsd := terminateSessionDuration\n\t\t\t\t\tterminateSessionDuration = 100\n\n\t\t\t\t\t\/\/ set durations back to the original value\n\t\t\t\t\tdefer func() {\n\t\t\t\t\t\tsleepTime = st\n\t\t\t\t\t\tterminateSessionDuration = tsd\n\t\t\t\t\t}()\n\n\t\t\t\t\treq.CreatedAt = time.Now().UTC()\n\t\t\t\t\t\/\/ prepare a valid key\n\t\t\t\t\terr := redis.Setex(\n\t\t\t\t\t\tPrepareFileKey(req.FileId),\n\t\t\t\t\t\tterminateSessionDuration, \/\/ expire the key after this period\n\t\t\t\t\t\treq.CreatedAt.Unix(),     \/\/ value - unix time\n\t\t\t\t\t)\n\n\t\t\t\t\t\/\/ while sleeping here, redis key should be removed\n\t\t\t\t\t\/\/ and we can understand that the Collab session is expired\n\t\t\t\t\ttime.Sleep(sleepTime)\n\n\t\t\t\t\treq := req\n\t\t\t\t\terr = handler.wait(req)\n\t\t\t\t\tSo(err, ShouldEqual, errSessionInvalid)\n\t\t\t\t})\n\n\t\t\t\tConvey(\"deadlined session should get errDeadlineReached\", func() {\n\t\t\t\t\tst := sleepTime\n\t\t\t\t\tsleepTime = time.Millisecond * 110\n\n\t\t\t\t\tdd := deadLineDuration\n\t\t\t\t\tdeadLineDuration = 100\n\n\t\t\t\t\t\/\/ set durations back to the original value\n\t\t\t\t\tdefer func() {\n\t\t\t\t\t\tsleepTime = st\n\t\t\t\t\t\tdeadLineDuration = dd\n\t\t\t\t\t}()\n\n\t\t\t\t\treq := req\n\t\t\t\t\terr := handler.wait(req)\n\t\t\t\t\tSo(err, ShouldEqual, errDeadlineReached)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"while testing checkIfKeyIsValid\", func() {\n\n\t\t\treq := req\n\t\t\treq.CreatedAt = time.Now().UTC()\n\n\t\t\t\/\/ prepare a valid key\n\t\t\terr := redis.Setex(\n\t\t\t\tPrepareFileKey(req.FileId),\n\t\t\t\tcollaboration.ExpireSessionKeyDuration, \/\/ expire the key after this period\n\t\t\t\treq.CreatedAt.Unix(),                   \/\/ value - unix time\n\t\t\t)\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tConvey(\"valid key should return nil\", func() {\n\t\t\t\terr := handler.checkIfKeyIsValid(req)\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(\"invalid key should return errSessionInvalid\", func() {\n\t\t\t\treq := req\n\t\t\t\t\/\/ override fileId\n\t\t\t\treq.FileId = fmt.Sprintf(\"%d\", rand.Int63())\n\t\t\t\terr := handler.checkIfKeyIsValid(req)\n\t\t\t\tSo(err, ShouldEqual, errSessionInvalid)\n\t\t\t})\n\n\t\t\tConvey(\"invalid (non-timestamp) value should return errSessionInvalid\", func() {\n\t\t\t\treq := req\n\t\t\t\treq.CreatedAt = time.Now().UTC()\n\t\t\t\terr := redis.Setex(\n\t\t\t\t\tPrepareFileKey(req.FileId),\n\t\t\t\t\tcollaboration.ExpireSessionKeyDuration, \/\/ expire the key after this period\n\t\t\t\t\t\"req.CreatedAt.Unix()\",                 \/\/ replace timestamp with unix time\n\t\t\t\t)\n\n\t\t\t\terr = handler.checkIfKeyIsValid(req)\n\t\t\t\tSo(err, ShouldEqual, errSessionInvalid)\n\t\t\t})\n\n\t\t\tConvey(\"old ping time should return errSessionInvalid\", func() {\n\t\t\t\treq := req\n\t\t\t\treq.CreatedAt = time.Now().UTC()\n\t\t\t\terr := redis.Setex(\n\t\t\t\t\tPrepareFileKey(req.FileId),\n\t\t\t\t\tcollaboration.ExpireSessionKeyDuration, \/\/ expire the key after this period\n\t\t\t\t\treq.CreatedAt.Add(-terminateSessionDuration),\n\t\t\t\t)\n\n\t\t\t\terr = handler.checkIfKeyIsValid(req)\n\t\t\t\tSo(err, ShouldEqual, errSessionInvalid)\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"while testing drive operations\", func() {\n\t\t\treq := req\n\t\t\treq.CreatedAt = time.Now().UTC()\n\t\t\tConvey(\"should be able to create the file\", func() {\n\t\t\t\tf, err := handler.createFile()\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\treq.FileId = f.Id\n\t\t\t\tConvey(\"should be able to get the created file\", func() {\n\t\t\t\t\tf2, err := handler.getFile(f.Id)\n\t\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\t\tSo(f2, ShouldNotBeNil)\n\t\t\t\t\tConvey(\"should be able to delete the created file\", func() {\n\t\t\t\t\t\terr = handler.deleteFile(req.FileId)\n\t\t\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\t\t\tConvey(\"should not be able to get the deleted file\", func() {\n\t\t\t\t\t\t\tf2, err = handler.getFile(f.Id)\n\t\t\t\t\t\t\tSo(err, ShouldNotBeNil)\n\t\t\t\t\t\t\tSo(f2, ShouldBeNil)\n\t\t\t\t\t\t})\n\t\t\t\t\t\tConvey(\"deleting the deleted file should not give error\", func() {\n\t\t\t\t\t\t\terr = handler.deleteFile(req.FileId)\n\t\t\t\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n}\n<commit_msg>Socialapi: added better test cases for ping system<commit_after>package collaboration\n\nimport (\n\t\"fmt\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"math\/rand\"\n\tapimodels \"socialapi\/models\"\n\t\"socialapi\/rest\"\n\t\"socialapi\/workers\/collaboration\/models\"\n\t\"socialapi\/workers\/common\/runner\"\n\t\"strconv\"\n\t\"testing\"\n\t\"time\"\n\n\t\"socialapi\/workers\/collaboration\"\n\t\"socialapi\/workers\/helper\"\n\n\t\"github.com\/koding\/redis\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\nvar (\n\tAccountOldId = bson.NewObjectId()\n)\n\nfunc TestCollaboration(t *testing.T) {\n\tr := runner.New(\"collaboration-tests\")\n\terr := r.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer r.Close()\n\n\tmodelhelper.Initialize(r.Conf.Mongo)\n\tdefer modelhelper.Close()\n\n\tredisConn := helper.MustInitRedisConn(r.Conf)\n\tdefer redisConn.Close()\n\n\tredis := helper.MustGetRedisConn()\n\n\thandler := New(r.Log, redisConn, r.Conf, r.Kite)\n\n\tConvey(\"while pinging collaboration\", t, func() {\n\t\t\/\/ owner\n\t\towner := apimodels.NewAccount()\n\t\towner.OldId = AccountOldId.Hex()\n\t\towner, err := rest.CreateAccount(owner)\n\t\tSo(err, ShouldBeNil)\n\t\tSo(owner, ShouldNotBeNil)\n\n\t\townerSession, err := apimodels.FetchOrCreateSession(owner.Nick)\n\t\tSo(err, ShouldBeNil)\n\t\tSo(ownerSession, ShouldNotBeNil)\n\n\t\trand.Seed(time.Now().UnixNano())\n\n\t\treq := &models.Ping{\n\t\t\tAccountId: 1,\n\t\t\tFileId:    fmt.Sprintf(\"%d\", rand.Int63()),\n\t\t}\n\n\t\tConvey(\"while testing Ping\", func() {\n\t\t\tConvey(\"reponse should be success with valid ping\", func() {\n\t\t\t\terr := handler.Ping(req)\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(\"reponse should be success with invalid FileId\", func() {\n\t\t\t\treq.FileId = \"\"\n\t\t\t\terr := handler.Ping(req)\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(\"reponse should be success with invalid AccountId\", func() {\n\t\t\t\treq.AccountId = 0\n\t\t\t\terr := handler.Ping(req)\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(\"reponse should be success with invalid session\", func() {\n\t\t\t\treq := req\n\t\t\t\t\/\/ prepare an invalid session here\n\t\t\t\treq.CreatedAt = time.Now().UTC()\n\t\t\t\terr := redis.Setex(\n\t\t\t\t\tPrepareFileKey(req.FileId),\n\t\t\t\t\tcollaboration.ExpireSessionKeyDuration, \/\/ expire the key after this period\n\t\t\t\t\treq.CreatedAt.Add(-terminateSessionDuration),\n\t\t\t\t)\n\n\t\t\t\terr = handler.Ping(req)\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(\"after sleep time\", func() {\n\t\t\t\treq := req\n\n\t\t\t\tConvey(\"expired session should get invalidSessoin\", func() {\n\t\t\t\t\tst := sleepTime\n\t\t\t\t\tsleepTime = time.Millisecond * 110\n\n\t\t\t\t\ttsd := terminateSessionDuration\n\t\t\t\t\tterminateSessionDuration = 100\n\n\t\t\t\t\t\/\/ set durations back to the original value\n\t\t\t\t\tdefer func() {\n\t\t\t\t\t\tsleepTime = st\n\t\t\t\t\t\tterminateSessionDuration = tsd\n\t\t\t\t\t}()\n\n\t\t\t\t\treq.CreatedAt = time.Now().UTC()\n\t\t\t\t\t\/\/ prepare a valid key\n\t\t\t\t\terr := redis.Setex(\n\t\t\t\t\t\tPrepareFileKey(req.FileId),\n\t\t\t\t\t\tterminateSessionDuration, \/\/ expire the key after this period\n\t\t\t\t\t\treq.CreatedAt.Unix(),     \/\/ value - unix time\n\t\t\t\t\t)\n\n\t\t\t\t\t\/\/ while sleeping here, redis key should be removed\n\t\t\t\t\t\/\/ and we can understand that the Collab session is expired\n\t\t\t\t\ttime.Sleep(sleepTime)\n\n\t\t\t\t\treq := req\n\t\t\t\t\terr = handler.wait(req)\n\t\t\t\t\tSo(err, ShouldEqual, errSessionInvalid)\n\t\t\t\t})\n\n\t\t\t\tConvey(\"deadlined session should get errDeadlineReached\", func() {\n\t\t\t\t\tst := sleepTime\n\t\t\t\t\tsleepTime = time.Millisecond * 110\n\n\t\t\t\t\tdd := deadLineDuration\n\t\t\t\t\tdeadLineDuration = 100\n\n\t\t\t\t\t\/\/ set durations back to the original value\n\t\t\t\t\tdefer func() {\n\t\t\t\t\t\tsleepTime = st\n\t\t\t\t\t\tdeadLineDuration = dd\n\t\t\t\t\t}()\n\n\t\t\t\t\treq := req\n\t\t\t\t\terr := handler.wait(req)\n\t\t\t\t\tSo(err, ShouldEqual, errDeadlineReached)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"while testing checkIfKeyIsValid\", func() {\n\n\t\t\treq := req\n\t\t\treq.CreatedAt = time.Now().UTC()\n\n\t\t\t\/\/ prepare a valid key\n\t\t\terr := redis.Setex(\n\t\t\t\tPrepareFileKey(req.FileId),\n\t\t\t\tcollaboration.ExpireSessionKeyDuration, \/\/ expire the key after this period\n\t\t\t\treq.CreatedAt.Unix(),                   \/\/ value - unix time\n\t\t\t)\n\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tConvey(\"valid key should return nil\", func() {\n\t\t\t\terr := handler.checkIfKeyIsValid(req)\n\t\t\t\tSo(err, ShouldBeNil)\n\t\t\t})\n\n\t\t\tConvey(\"invalid key should return errSessionInvalid\", func() {\n\t\t\t\treq := req\n\t\t\t\t\/\/ override fileId\n\t\t\t\treq.FileId = fmt.Sprintf(\"%d\", rand.Int63())\n\t\t\t\terr := handler.checkIfKeyIsValid(req)\n\t\t\t\tSo(err, ShouldEqual, errSessionInvalid)\n\t\t\t})\n\n\t\t\tConvey(\"invalid (non-timestamp) value should return errSessionInvalid\", func() {\n\t\t\t\treq := req\n\t\t\t\treq.CreatedAt = time.Now().UTC()\n\t\t\t\terr := redis.Setex(\n\t\t\t\t\tPrepareFileKey(req.FileId),\n\t\t\t\t\tcollaboration.ExpireSessionKeyDuration, \/\/ expire the key after this period\n\t\t\t\t\t\"req.CreatedAt.Unix()\",                 \/\/ replace timestamp with unix time\n\t\t\t\t)\n\n\t\t\t\terr = handler.checkIfKeyIsValid(req)\n\t\t\t\tSo(err, ShouldEqual, errSessionInvalid)\n\t\t\t})\n\n\t\t\tConvey(\"old ping time should return errSessionInvalid\", func() {\n\t\t\t\treq := req\n\t\t\t\treq.CreatedAt = time.Now().UTC()\n\t\t\t\terr := redis.Setex(\n\t\t\t\t\tPrepareFileKey(req.FileId),\n\t\t\t\t\tcollaboration.ExpireSessionKeyDuration, \/\/ expire the key after this period\n\t\t\t\t\treq.CreatedAt.Add(-terminateSessionDuration).Unix(),\n\t\t\t\t)\n\n\t\t\t\terr = handler.checkIfKeyIsValid(req)\n\t\t\t\tSo(err, ShouldEqual, errSessionInvalid)\n\t\t\t})\n\n\t\t\tConvey(\"previous ping time is in safe area\", func() {\n\t\t\t\treq := req\n\t\t\t\ttestPingTimes(req, -1, redis, handler, nil)\n\t\t\t})\n\n\t\t\tConvey(\"0 ping time is in safe area\", func() {\n\t\t\t\treq := req\n\t\t\t\ttestPingTimes(req, 0, redis, handler, nil)\n\t\t\t})\n\n\t\t\tConvey(\"2 ping time is in safe area\", func() {\n\t\t\t\treq := req\n\t\t\t\ttestPingTimes(req, 2, redis, handler, nil)\n\t\t\t})\n\n\t\t\tConvey(\"3 ping time is in safe area\", func() {\n\t\t\t\treq := req\n\t\t\t\ttestPingTimes(req, 3, redis, handler, nil)\n\t\t\t})\n\n\t\t\tConvey(\"4 ping time is not in safe area - because we already reverted the time \", func() {\n\t\t\t\treq := req\n\t\t\t\ttestPingTimes(req, 4, redis, handler, errSessionInvalid)\n\t\t\t})\n\n\t\t\tConvey(\"5 ping time is not in safe area \", func() {\n\t\t\t\treq := req\n\t\t\t\ttestPingTimes(req, 5, redis, handler, errSessionInvalid)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc testPingTimes(\n\treq *models.Ping,\n\tpingCount int,\n\tredis *redis.RedisSession,\n\thandler *Controller,\n\texpectedErr error,\n) {\n\treq.FileId = req.FileId + strconv.Itoa(pingCount)\n\treq.CreatedAt = time.\n\t\tNow().\n\t\tUTC().\n\t\tAdd(-pingDuration * time.Duration(pingCount))\n\n\terr := redis.Setex(\n\t\tPrepareFileKey(req.FileId),\n\t\tcollaboration.ExpireSessionKeyDuration, \/\/ expire the key after this period\n\t\treq.CreatedAt.Unix(),\n\t)\n\n\terr = handler.checkIfKeyIsValid(req)\n\tSo(err, ShouldEqual, expectedErr)\n}\n<|endoftext|>"}
{"text":"<commit_before>package algoliaconnector\n\nimport (\n\t\"socialapi\/models\"\n\t\"strconv\"\n)\n\n\/\/ ChannelCreated handles the channel create events, for now only handles the\n\/\/ channels that are topic channels,\nfunc (f *Controller) ChannelCreated(data *models.Channel) error {\n\tif data.TypeConstant != models.Channel_TYPE_TOPIC {\n\t\treturn nil\n\t}\n\n\treturn f.insert(IndexTopics, map[string]interface{}{\n\t\t\"objectID\": strconv.FormatInt(data.Id, 10),\n\t\t\"name\":     data.Name,\n\t\t\"purpose\":  data.Purpose,\n\t})\n}\n\n\/\/ ChannelUpdated handles the channel update events, for now only handles the\n\/\/ channels that are topic channels, we can link channels together in any point\n\/\/ of time, after linking, leaf channel is removed from search engine. But it is\n\/\/ still searchable via its root channel, because we are adding it as synonym to\n\/\/ the root of it\nfunc (f *Controller) ChannelUpdated(data *models.Channel) error {\n\tif data.TypeConstant != models.Channel_TYPE_LINKED_TOPIC {\n\t\tf.log.Debug(\"unsuported channel for topic update type: %s id: %d\", data.TypeConstant, data.Id)\n\t\treturn nil\n\t}\n\n\treturn f.delete(IndexTopics, strconv.FormatInt(data.Id, 10))\n}\n<commit_msg>Socialapi: added main group initial channel id into all channels for security<commit_after>package algoliaconnector\n\nimport (\n\t\"socialapi\/models\"\n\t\"strconv\"\n)\n\n\/\/ ChannelCreated handles the channel create events, for now only handles the\n\/\/ channels that are topic channels,\nfunc (f *Controller) ChannelCreated(data *models.Channel) error {\n\tif data.TypeConstant != models.Channel_TYPE_TOPIC {\n\t\treturn nil\n\t}\n\n\t\/\/ add public group channel id into tags for security\n\tpublicChannel := models.NewChannel()\n\terr := publicChannel.FetchPublicChannel(data.GroupName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn f.insert(IndexTopics, map[string]interface{}{\n\t\t\"objectID\": strconv.FormatInt(data.Id, 10),\n\t\t\"name\":     data.Name,\n\t\t\"purpose\":  data.Purpose,\n\t\t\"_tags\":    []string{strconv.FormatInt(publicChannel.Id, 10)},\n\t})\n}\n\n\/\/ ChannelUpdated handles the channel update events, for now only handles the\n\/\/ channels that are topic channels, we can link channels together in any point\n\/\/ of time, after linking, leaf channel is removed from search engine. But it is\n\/\/ still searchable via its root channel, because we are adding it as synonym to\n\/\/ the root of it\nfunc (f *Controller) ChannelUpdated(data *models.Channel) error {\n\tif data.TypeConstant != models.Channel_TYPE_LINKED_TOPIC {\n\t\tf.log.Debug(\"unsuported channel for topic update type: %s id: %d\", data.TypeConstant, data.Id)\n\t\treturn nil\n\t}\n\n\treturn f.delete(IndexTopics, strconv.FormatInt(data.Id, 10))\n}\n<|endoftext|>"}
{"text":"<commit_before>package webhook\n\nimport (\n\t\"net\/http\"\n\t\"socialapi\/config\"\n\t\"socialapi\/workers\/common\/mux\"\n\t\"socialapi\/workers\/integration\/webhook\"\n\t\"testing\"\n\n\t\"github.com\/koding\/logging\"\n\t\"github.com\/koding\/runner\"\n\t\"github.com\/rcrowley\/go-tigertonic\/mocking\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc newRequest(body, channelName string) *webhook.WebhookRequest {\n\treturn &webhook.WebhookRequest{\n\t\tBody:        body,\n\t\tChannelName: channelName,\n\t}\n}\n\nfunc TestWebhookListen(t *testing.T) {\n\tr := runner.New(\"test\")\n\tif err := r.Init(); err != nil {\n\t\tt.Fatalf(\"something went wrong: %s\", err)\n\t}\n\tr.Log.SetLevel(logging.CRITICAL)\n\n\tdefer r.Close()\n\tconfig.MustRead(r.Conf.Path)\n\tmc := mux.NewConfig(\"testing\", \"\", \"\")\n\tm := mux.New(mc, r.Log)\n\n\th := webhook.NewHandler(r.Log)\n\th.AddHandlers(m)\n\n\tConvey(\"while testing incoming webhook\", t, func() {\n\n\t\tConvey(\"users should not be able to send any message when they don't have valid token\", func() {\n\t\t\ttoken := \"123123\"\n\t\t\ts, _, _, err := h.Push(\n\t\t\t\tmocking.URL(m, \"POST\", \"\/webhook\/push\/\"+token),\n\t\t\t\tmocking.Header(nil),\n\t\t\t\tnewRequest(\"hey\", \"testingchannel\"),\n\t\t\t)\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t\tSo(s, ShouldEqual, http.StatusNotFound)\n\n\t\t\ttoken = \"\"\n\t\t\ts, _, _, err = h.Push(\n\t\t\t\tmocking.URL(m, \"POST\", \"\/webhook\/push\/\"+token),\n\t\t\t\tmocking.Header(nil),\n\t\t\t\tnewRequest(\"hey\", \"testingchannel\"),\n\t\t\t)\n\t\t\tSo(err.Error(), ShouldEqual, ErrTokenNotSet.Error())\n\t\t\tSo(s, ShouldEqual, http.StatusBadRequest)\n\t\t})\n\n\t\tConvey(\"users should not be able to send any message when their request does not include body or channel name\", func() {\n\n\t\t\ttoken := \"123123\"\n\t\t\ts, _, _, err := h.Push(\n\t\t\t\tmocking.URL(m, \"POST\", \"\/webhook\/push\/\"+token),\n\t\t\t\tmocking.Header(nil),\n\t\t\t\tnewRequest(\"\", \"testingchannel\"),\n\t\t\t)\n\t\t\tSo(err.Error(), ShouldEqual, ErrBodyNotSet.Error())\n\t\t\tSo(s, ShouldEqual, http.StatusBadRequest)\n\t\t})\n\n\t\tConvey(\"users should be able to send message when token is valid\", nil)\n\n\t})\n}\n<commit_msg>webhook: add channel validation test<commit_after>package webhook\n\nimport (\n\t\"net\/http\"\n\t\"socialapi\/config\"\n\t\"socialapi\/workers\/common\/mux\"\n\t\"socialapi\/workers\/integration\/webhook\"\n\t\"testing\"\n\n\t\"github.com\/koding\/logging\"\n\t\"github.com\/koding\/runner\"\n\t\"github.com\/rcrowley\/go-tigertonic\/mocking\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc newRequest(body, channelName string) *webhook.WebhookRequest {\n\treturn &webhook.WebhookRequest{\n\t\tBody:        body,\n\t\tChannelName: channelName,\n\t}\n}\n\nfunc TestWebhookListen(t *testing.T) {\n\tr := runner.New(\"test\")\n\tif err := r.Init(); err != nil {\n\t\tt.Fatalf(\"something went wrong: %s\", err)\n\t}\n\tr.Log.SetLevel(logging.CRITICAL)\n\n\tdefer r.Close()\n\tconfig.MustRead(r.Conf.Path)\n\tmc := mux.NewConfig(\"testing\", \"\", \"\")\n\tm := mux.New(mc, r.Log)\n\n\th := webhook.NewHandler(r.Log)\n\th.AddHandlers(m)\n\n\tConvey(\"while testing incoming webhook\", t, func() {\n\n\t\tConvey(\"users should not be able to send any message when they don't have valid token\", func() {\n\t\t\ttoken := \"123123\"\n\t\t\ts, _, _, err := h.Push(\n\t\t\t\tmocking.URL(m, \"POST\", \"\/webhook\/push\/\"+token),\n\t\t\t\tmocking.Header(nil),\n\t\t\t\tnewRequest(\"hey\", \"testingchannel\"),\n\t\t\t)\n\t\t\tSo(err, ShouldNotBeNil)\n\t\t\tSo(s, ShouldEqual, http.StatusNotFound)\n\n\t\t\ttoken = \"\"\n\t\t\ts, _, _, err = h.Push(\n\t\t\t\tmocking.URL(m, \"POST\", \"\/webhook\/push\/\"+token),\n\t\t\t\tmocking.Header(nil),\n\t\t\t\tnewRequest(\"hey\", \"testingchannel\"),\n\t\t\t)\n\t\t\tSo(err.Error(), ShouldEqual, ErrTokenNotSet.Error())\n\t\t\tSo(s, ShouldEqual, http.StatusBadRequest)\n\t\t})\n\n\t\tConvey(\"users should not be able to send any message when their request does not include body or channel name\", func() {\n\n\t\t\ttoken := \"123123\"\n\t\t\ts, _, _, err := h.Push(\n\t\t\t\tmocking.URL(m, \"POST\", \"\/webhook\/push\/\"+token),\n\t\t\t\tmocking.Header(nil),\n\t\t\t\tnewRequest(\"\", \"testingchannel\"),\n\t\t\t)\n\t\t\tSo(err.Error(), ShouldEqual, ErrBodyNotSet.Error())\n\t\t\tSo(s, ShouldEqual, http.StatusBadRequest)\n\n\t\t\ts, _, _, err = h.Push(\n\t\t\t\tmocking.URL(m, \"POST\", \"\/webhook\/push\/\"+token),\n\t\t\t\tmocking.Header(nil),\n\t\t\t\tnewRequest(\"hey\", \"\"),\n\t\t\t)\n\t\t\tSo(err.Error(), ShouldEqual, ErrChannelNotSet.Error())\n\t\t\tSo(s, ShouldEqual, http.StatusBadRequest)\n\t\t})\n\n\t\tConvey(\"users should be able to send message when token is valid\", nil)\n\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage runtime\n\nimport \"unsafe\"\n\n\/\/ Solaris runtime-integrated network poller.\n\/\/\n\/\/ Solaris uses event ports for scalable network I\/O. Event\n\/\/ ports are level-triggered, unlike epoll and kqueue which\n\/\/ can be configured in both level-triggered and edge-triggered\n\/\/ mode. Level triggering means we have to keep track of a few things\n\/\/ ourselves. After we receive an event for a file descriptor,\n\/\/ it's our responsibility to ask again to be notified for future\n\/\/ events for that descriptor. When doing this we must keep track of\n\/\/ what kind of events the goroutines are currently interested in,\n\/\/ for example a fd may be open both for reading and writing.\n\/\/\n\/\/ A description of the high level operation of this code\n\/\/ follows. Networking code will get a file descriptor by some means\n\/\/ and will register it with the netpolling mechanism by a code path\n\/\/ that eventually calls runtime·netpollopen. runtime·netpollopen\n\/\/ calls port_associate with an empty event set. That means that we\n\/\/ will not receive any events at this point. The association needs\n\/\/ to be done at this early point because we need to process the I\/O\n\/\/ readiness notification at some point in the future. If I\/O becomes\n\/\/ ready when nobody is listening, when we finally care about it,\n\/\/ nobody will tell us anymore.\n\/\/\n\/\/ Beside calling runtime·netpollopen, the networking code paths\n\/\/ will call runtime·netpollarm each time goroutines are interested\n\/\/ in doing network I\/O. Because now we know what kind of I\/O we\n\/\/ are interested in (reading\/writing), we can call port_associate\n\/\/ passing the correct type of event set (POLLIN\/POLLOUT). As we made\n\/\/ sure to have already associated the file descriptor with the port,\n\/\/ when we now call port_associate, we will unblock the main poller\n\/\/ loop (in runtime·netpoll) right away if the socket is actually\n\/\/ ready for I\/O.\n\/\/\n\/\/ The main poller loop runs in its own thread waiting for events\n\/\/ using port_getn. When an event happens, it will tell the scheduler\n\/\/ about it using runtime·netpollready. Besides doing this, it must\n\/\/ also re-associate the events that were not part of this current\n\/\/ notification with the file descriptor. Failing to do this would\n\/\/ mean each notification will prevent concurrent code using the\n\/\/ same file descriptor in parallel.\n\/\/\n\/\/ The logic dealing with re-associations is encapsulated in\n\/\/ runtime·netpollupdate. This function takes care to associate the\n\/\/ descriptor only with the subset of events that were previously\n\/\/ part of the association, except the one that just happened. We\n\/\/ can't re-associate with that right away, because event ports\n\/\/ are level triggered so it would cause a busy loop. Instead, that\n\/\/ association is effected only by the runtime·netpollarm code path,\n\/\/ when Go code actually asks for I\/O.\n\/\/\n\/\/ The open and arming mechanisms are serialized using the lock\n\/\/ inside PollDesc. This is required because the netpoll loop runs\n\/\/ asynchronously in respect to other Go code and by the time we get\n\/\/ to call port_associate to update the association in the loop, the\n\/\/ file descriptor might have been closed and reopened already. The\n\/\/ lock allows runtime·netpollupdate to be called synchronously from\n\/\/ the loop thread while preventing other threads operating to the\n\/\/ same PollDesc, so once we unblock in the main loop, until we loop\n\/\/ again we know for sure we are always talking about the same file\n\/\/ descriptor and can safely access the data we want (the event set).\n\n\/\/go:cgo_import_dynamic libc_port_create port_create \"libc.so\"\n\/\/go:cgo_import_dynamic libc_port_associate port_associate \"libc.so\"\n\/\/go:cgo_import_dynamic libc_port_dissociate port_dissociate \"libc.so\"\n\/\/go:cgo_import_dynamic libc_port_getn port_getn \"libc.so\"\n\n\/\/go:linkname libc_port_create libc_port_create\n\/\/go:linkname libc_port_associate libc_port_associate\n\/\/go:linkname libc_port_dissociate libc_port_dissociate\n\/\/go:linkname libc_port_getn libc_port_getn\n\nvar (\n\tlibc_port_create,\n\tlibc_port_associate,\n\tlibc_port_dissociate,\n\tlibc_port_getn libcFunc\n)\n\nfunc errno() int32 {\n\treturn *getg().m.perrno\n}\n\nfunc fcntl(fd, cmd int32, arg uintptr) int32 {\n\treturn int32(sysvicall3(&libc_fcntl, uintptr(fd), uintptr(cmd), arg))\n}\n\nfunc port_create() int32 {\n\treturn int32(sysvicall0(&libc_port_create))\n}\n\nfunc port_associate(port, source int32, object uintptr, events uint32, user uintptr) int32 {\n\treturn int32(sysvicall5(&libc_port_associate, uintptr(port), uintptr(source), object, uintptr(events), user))\n}\n\nfunc port_dissociate(port, source int32, object uintptr) int32 {\n\treturn int32(sysvicall3(&libc_port_dissociate, uintptr(port), uintptr(source), object))\n}\n\nfunc port_getn(port int32, evs *portevent, max uint32, nget *uint32, timeout *timespec) int32 {\n\treturn int32(sysvicall5(&libc_port_getn, uintptr(port), uintptr(unsafe.Pointer(evs)), uintptr(max), uintptr(unsafe.Pointer(nget)), uintptr(unsafe.Pointer(timeout))))\n}\n\nvar portfd int32 = -1\n\nfunc netpollinit() {\n\tportfd = port_create()\n\tif portfd >= 0 {\n\t\tfcntl(portfd, _F_SETFD, _FD_CLOEXEC)\n\t\treturn\n\t}\n\n\tprint(\"runtime: port_create failed (errno=\", errno(), \")\\n\")\n\tthrow(\"runtime: netpollinit failed\")\n}\n\nfunc netpolldescriptor() uintptr {\n\treturn uintptr(portfd)\n}\n\nfunc netpollopen(fd uintptr, pd *pollDesc) int32 {\n\tlock(&pd.lock)\n\t\/\/ We don't register for any specific type of events yet, that's\n\t\/\/ netpollarm's job. We merely ensure we call port_associate before\n\t\/\/ asynchronous connect\/accept completes, so when we actually want\n\t\/\/ to do any I\/O, the call to port_associate (from netpollarm,\n\t\/\/ with the interested event set) will unblock port_getn right away\n\t\/\/ because of the I\/O readiness notification.\n\tpd.user = 0\n\tr := port_associate(portfd, _PORT_SOURCE_FD, fd, 0, uintptr(unsafe.Pointer(pd)))\n\tunlock(&pd.lock)\n\treturn r\n}\n\nfunc netpollclose(fd uintptr) int32 {\n\treturn port_dissociate(portfd, _PORT_SOURCE_FD, fd)\n}\n\n\/\/ Updates the association with a new set of interested events. After\n\/\/ this call, port_getn will return one and only one event for that\n\/\/ particular descriptor, so this function needs to be called again.\nfunc netpollupdate(pd *pollDesc, set, clear uint32) {\n\tif pd.closing {\n\t\treturn\n\t}\n\n\told := pd.user\n\tevents := (old & ^clear) | set\n\tif old == events {\n\t\treturn\n\t}\n\n\tif events != 0 && port_associate(portfd, _PORT_SOURCE_FD, pd.fd, events, uintptr(unsafe.Pointer(pd))) != 0 {\n\t\tprint(\"runtime: port_associate failed (errno=\", errno(), \")\\n\")\n\t\tthrow(\"runtime: netpollupdate failed\")\n\t}\n\tpd.user = events\n}\n\n\/\/ subscribe the fd to the port such that port_getn will return one event.\nfunc netpollarm(pd *pollDesc, mode int) {\n\tlock(&pd.lock)\n\tswitch mode {\n\tcase 'r':\n\t\tnetpollupdate(pd, _POLLIN, 0)\n\tcase 'w':\n\t\tnetpollupdate(pd, _POLLOUT, 0)\n\tdefault:\n\t\tthrow(\"runtime: bad mode\")\n\t}\n\tunlock(&pd.lock)\n}\n\n\/\/ polls for ready network connections\n\/\/ returns list of goroutines that become runnable\nfunc netpoll(block bool) gList {\n\tif portfd == -1 {\n\t\treturn gList{}\n\t}\n\n\tvar wait *timespec\n\tvar zero timespec\n\tif !block {\n\t\twait = &zero\n\t}\n\n\tvar events [128]portevent\nretry:\n\tvar n uint32 = 1\n\tif port_getn(portfd, &events[0], uint32(len(events)), &n, wait) < 0 {\n\t\tif e := errno(); e != _EINTR {\n\t\t\tprint(\"runtime: port_getn on fd \", portfd, \" failed (errno=\", e, \")\\n\")\n\t\t\tthrow(\"runtime: netpoll failed\")\n\t\t}\n\t\tgoto retry\n\t}\n\n\tvar toRun gList\n\tfor i := 0; i < int(n); i++ {\n\t\tev := &events[i]\n\n\t\tif ev.portev_events == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tpd := (*pollDesc)(unsafe.Pointer(ev.portev_user))\n\n\t\tvar mode, clear int32\n\t\tif (ev.portev_events & (_POLLIN | _POLLHUP | _POLLERR)) != 0 {\n\t\t\tmode += 'r'\n\t\t\tclear |= _POLLIN\n\t\t}\n\t\tif (ev.portev_events & (_POLLOUT | _POLLHUP | _POLLERR)) != 0 {\n\t\t\tmode += 'w'\n\t\t\tclear |= _POLLOUT\n\t\t}\n\t\t\/\/ To effect edge-triggered events, we need to be sure to\n\t\t\/\/ update our association with whatever events were not\n\t\t\/\/ set with the event. For example if we are registered\n\t\t\/\/ for POLLIN|POLLOUT, and we get POLLIN, besides waking\n\t\t\/\/ the goroutine interested in POLLIN we have to not forget\n\t\t\/\/ about the one interested in POLLOUT.\n\t\tif clear != 0 {\n\t\t\tlock(&pd.lock)\n\t\t\tnetpollupdate(pd, 0, uint32(clear))\n\t\t\tunlock(&pd.lock)\n\t\t}\n\n\t\tif mode != 0 {\n\t\t\tpd.everr = false\n\t\t\tif ev.portev_events == _POLLERR {\n\t\t\t\tpd.everr = true\n\t\t\t}\n\t\t\tnetpollready(&toRun, pd, mode)\n\t\t}\n\t}\n\n\tif block && toRun.empty() {\n\t\tgoto retry\n\t}\n\treturn toRun\n}\n<commit_msg>runtime: disable event scanning error reporting on solaris<commit_after>\/\/ Copyright 2014 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage runtime\n\nimport \"unsafe\"\n\n\/\/ Solaris runtime-integrated network poller.\n\/\/\n\/\/ Solaris uses event ports for scalable network I\/O. Event\n\/\/ ports are level-triggered, unlike epoll and kqueue which\n\/\/ can be configured in both level-triggered and edge-triggered\n\/\/ mode. Level triggering means we have to keep track of a few things\n\/\/ ourselves. After we receive an event for a file descriptor,\n\/\/ it's our responsibility to ask again to be notified for future\n\/\/ events for that descriptor. When doing this we must keep track of\n\/\/ what kind of events the goroutines are currently interested in,\n\/\/ for example a fd may be open both for reading and writing.\n\/\/\n\/\/ A description of the high level operation of this code\n\/\/ follows. Networking code will get a file descriptor by some means\n\/\/ and will register it with the netpolling mechanism by a code path\n\/\/ that eventually calls runtime·netpollopen. runtime·netpollopen\n\/\/ calls port_associate with an empty event set. That means that we\n\/\/ will not receive any events at this point. The association needs\n\/\/ to be done at this early point because we need to process the I\/O\n\/\/ readiness notification at some point in the future. If I\/O becomes\n\/\/ ready when nobody is listening, when we finally care about it,\n\/\/ nobody will tell us anymore.\n\/\/\n\/\/ Beside calling runtime·netpollopen, the networking code paths\n\/\/ will call runtime·netpollarm each time goroutines are interested\n\/\/ in doing network I\/O. Because now we know what kind of I\/O we\n\/\/ are interested in (reading\/writing), we can call port_associate\n\/\/ passing the correct type of event set (POLLIN\/POLLOUT). As we made\n\/\/ sure to have already associated the file descriptor with the port,\n\/\/ when we now call port_associate, we will unblock the main poller\n\/\/ loop (in runtime·netpoll) right away if the socket is actually\n\/\/ ready for I\/O.\n\/\/\n\/\/ The main poller loop runs in its own thread waiting for events\n\/\/ using port_getn. When an event happens, it will tell the scheduler\n\/\/ about it using runtime·netpollready. Besides doing this, it must\n\/\/ also re-associate the events that were not part of this current\n\/\/ notification with the file descriptor. Failing to do this would\n\/\/ mean each notification will prevent concurrent code using the\n\/\/ same file descriptor in parallel.\n\/\/\n\/\/ The logic dealing with re-associations is encapsulated in\n\/\/ runtime·netpollupdate. This function takes care to associate the\n\/\/ descriptor only with the subset of events that were previously\n\/\/ part of the association, except the one that just happened. We\n\/\/ can't re-associate with that right away, because event ports\n\/\/ are level triggered so it would cause a busy loop. Instead, that\n\/\/ association is effected only by the runtime·netpollarm code path,\n\/\/ when Go code actually asks for I\/O.\n\/\/\n\/\/ The open and arming mechanisms are serialized using the lock\n\/\/ inside PollDesc. This is required because the netpoll loop runs\n\/\/ asynchronously in respect to other Go code and by the time we get\n\/\/ to call port_associate to update the association in the loop, the\n\/\/ file descriptor might have been closed and reopened already. The\n\/\/ lock allows runtime·netpollupdate to be called synchronously from\n\/\/ the loop thread while preventing other threads operating to the\n\/\/ same PollDesc, so once we unblock in the main loop, until we loop\n\/\/ again we know for sure we are always talking about the same file\n\/\/ descriptor and can safely access the data we want (the event set).\n\n\/\/go:cgo_import_dynamic libc_port_create port_create \"libc.so\"\n\/\/go:cgo_import_dynamic libc_port_associate port_associate \"libc.so\"\n\/\/go:cgo_import_dynamic libc_port_dissociate port_dissociate \"libc.so\"\n\/\/go:cgo_import_dynamic libc_port_getn port_getn \"libc.so\"\n\n\/\/go:linkname libc_port_create libc_port_create\n\/\/go:linkname libc_port_associate libc_port_associate\n\/\/go:linkname libc_port_dissociate libc_port_dissociate\n\/\/go:linkname libc_port_getn libc_port_getn\n\nvar (\n\tlibc_port_create,\n\tlibc_port_associate,\n\tlibc_port_dissociate,\n\tlibc_port_getn libcFunc\n)\n\nfunc errno() int32 {\n\treturn *getg().m.perrno\n}\n\nfunc fcntl(fd, cmd int32, arg uintptr) int32 {\n\treturn int32(sysvicall3(&libc_fcntl, uintptr(fd), uintptr(cmd), arg))\n}\n\nfunc port_create() int32 {\n\treturn int32(sysvicall0(&libc_port_create))\n}\n\nfunc port_associate(port, source int32, object uintptr, events uint32, user uintptr) int32 {\n\treturn int32(sysvicall5(&libc_port_associate, uintptr(port), uintptr(source), object, uintptr(events), user))\n}\n\nfunc port_dissociate(port, source int32, object uintptr) int32 {\n\treturn int32(sysvicall3(&libc_port_dissociate, uintptr(port), uintptr(source), object))\n}\n\nfunc port_getn(port int32, evs *portevent, max uint32, nget *uint32, timeout *timespec) int32 {\n\treturn int32(sysvicall5(&libc_port_getn, uintptr(port), uintptr(unsafe.Pointer(evs)), uintptr(max), uintptr(unsafe.Pointer(nget)), uintptr(unsafe.Pointer(timeout))))\n}\n\nvar portfd int32 = -1\n\nfunc netpollinit() {\n\tportfd = port_create()\n\tif portfd >= 0 {\n\t\tfcntl(portfd, _F_SETFD, _FD_CLOEXEC)\n\t\treturn\n\t}\n\n\tprint(\"runtime: port_create failed (errno=\", errno(), \")\\n\")\n\tthrow(\"runtime: netpollinit failed\")\n}\n\nfunc netpolldescriptor() uintptr {\n\treturn uintptr(portfd)\n}\n\nfunc netpollopen(fd uintptr, pd *pollDesc) int32 {\n\tlock(&pd.lock)\n\t\/\/ We don't register for any specific type of events yet, that's\n\t\/\/ netpollarm's job. We merely ensure we call port_associate before\n\t\/\/ asynchronous connect\/accept completes, so when we actually want\n\t\/\/ to do any I\/O, the call to port_associate (from netpollarm,\n\t\/\/ with the interested event set) will unblock port_getn right away\n\t\/\/ because of the I\/O readiness notification.\n\tpd.user = 0\n\tr := port_associate(portfd, _PORT_SOURCE_FD, fd, 0, uintptr(unsafe.Pointer(pd)))\n\tunlock(&pd.lock)\n\treturn r\n}\n\nfunc netpollclose(fd uintptr) int32 {\n\treturn port_dissociate(portfd, _PORT_SOURCE_FD, fd)\n}\n\n\/\/ Updates the association with a new set of interested events. After\n\/\/ this call, port_getn will return one and only one event for that\n\/\/ particular descriptor, so this function needs to be called again.\nfunc netpollupdate(pd *pollDesc, set, clear uint32) {\n\tif pd.closing {\n\t\treturn\n\t}\n\n\told := pd.user\n\tevents := (old & ^clear) | set\n\tif old == events {\n\t\treturn\n\t}\n\n\tif events != 0 && port_associate(portfd, _PORT_SOURCE_FD, pd.fd, events, uintptr(unsafe.Pointer(pd))) != 0 {\n\t\tprint(\"runtime: port_associate failed (errno=\", errno(), \")\\n\")\n\t\tthrow(\"runtime: netpollupdate failed\")\n\t}\n\tpd.user = events\n}\n\n\/\/ subscribe the fd to the port such that port_getn will return one event.\nfunc netpollarm(pd *pollDesc, mode int) {\n\tlock(&pd.lock)\n\tswitch mode {\n\tcase 'r':\n\t\tnetpollupdate(pd, _POLLIN, 0)\n\tcase 'w':\n\t\tnetpollupdate(pd, _POLLOUT, 0)\n\tdefault:\n\t\tthrow(\"runtime: bad mode\")\n\t}\n\tunlock(&pd.lock)\n}\n\n\/\/ polls for ready network connections\n\/\/ returns list of goroutines that become runnable\nfunc netpoll(block bool) gList {\n\tif portfd == -1 {\n\t\treturn gList{}\n\t}\n\n\tvar wait *timespec\n\tvar zero timespec\n\tif !block {\n\t\twait = &zero\n\t}\n\n\tvar events [128]portevent\nretry:\n\tvar n uint32 = 1\n\tif port_getn(portfd, &events[0], uint32(len(events)), &n, wait) < 0 {\n\t\tif e := errno(); e != _EINTR {\n\t\t\tprint(\"runtime: port_getn on fd \", portfd, \" failed (errno=\", e, \")\\n\")\n\t\t\tthrow(\"runtime: netpoll failed\")\n\t\t}\n\t\tgoto retry\n\t}\n\n\tvar toRun gList\n\tfor i := 0; i < int(n); i++ {\n\t\tev := &events[i]\n\n\t\tif ev.portev_events == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tpd := (*pollDesc)(unsafe.Pointer(ev.portev_user))\n\n\t\tvar mode, clear int32\n\t\tif (ev.portev_events & (_POLLIN | _POLLHUP | _POLLERR)) != 0 {\n\t\t\tmode += 'r'\n\t\t\tclear |= _POLLIN\n\t\t}\n\t\tif (ev.portev_events & (_POLLOUT | _POLLHUP | _POLLERR)) != 0 {\n\t\t\tmode += 'w'\n\t\t\tclear |= _POLLOUT\n\t\t}\n\t\t\/\/ To effect edge-triggered events, we need to be sure to\n\t\t\/\/ update our association with whatever events were not\n\t\t\/\/ set with the event. For example if we are registered\n\t\t\/\/ for POLLIN|POLLOUT, and we get POLLIN, besides waking\n\t\t\/\/ the goroutine interested in POLLIN we have to not forget\n\t\t\/\/ about the one interested in POLLOUT.\n\t\tif clear != 0 {\n\t\t\tlock(&pd.lock)\n\t\t\tnetpollupdate(pd, 0, uint32(clear))\n\t\t\tunlock(&pd.lock)\n\t\t}\n\n\t\tif mode != 0 {\n\t\t\t\/\/ TODO(mikio): Consider implementing event\n\t\t\t\/\/ scanning error reporting once we are sure\n\t\t\t\/\/ about the event port on SmartOS.\n\t\t\t\/\/\n\t\t\t\/\/ See golang.org\/x\/issue\/30840.\n\t\t\tnetpollready(&toRun, pd, mode)\n\t\t}\n\t}\n\n\tif block && toRun.empty() {\n\t\tgoto retry\n\t}\n\treturn toRun\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build linux\n\/\/ +build 386 amd64 arm arm64 ppc64 ppc64le\n\npackage runtime_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\t_ \"unsafe\"\n)\n\n\/\/ These tests are a little risky because they overwrite the vdsoClockgettimeSym value.\n\/\/ It's normally initialized at startup and remains unchanged after that.\n\n\/\/go:linkname vdsoClockgettimeSym runtime.vdsoClockgettimeSym\nvar vdsoClockgettimeSym uintptr\n\nfunc TestClockVDSOAndFallbackPaths(t *testing.T) {\n\t\/\/ Check that we can call walltime() and nanotime() with and without their (1st) fast-paths.\n\t\/\/ This just checks that fast and fallback paths can be called, rather than testing their\n\t\/\/ results.\n\t\/\/\n\t\/\/ Call them indirectly via time.Now(), so we don't need auxiliary .s files to allow us to\n\t\/\/ use go:linkname to refer to the functions directly.\n\n\tsave := vdsoClockgettimeSym\n\tif save == 0 {\n\t\tt.Log(\"vdsoClockgettime symbol not found; fallback path will be used by default\")\n\t}\n\n\t\/\/ Call with fast-path enabled (if vDSO symbol found at startup)\n\ttime.Now()\n\n\t\/\/ Call with fast-path disabled\n\tvdsoClockgettimeSym = 0\n\ttime.Now()\n\tvdsoClockgettimeSym = save\n}\n\nfunc BenchmarkClockVDSOAndFallbackPaths(b *testing.B) {\n\trun := func(b *testing.B) {\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t\/\/ Call via time.Now() - see comment in test above.\n\t\t\ttime.Now()\n\t\t}\n\t}\n\n\tsave := vdsoClockgettimeSym\n\tb.Run(\"vDSO\", run)\n\tvdsoClockgettimeSym = 0\n\tb.Run(\"Fallback\", run)\n\tvdsoClockgettimeSym = save\n}\n\nfunc BenchmarkTimeNow(b *testing.B) {\n\tfor i := 0; i < b.N; i++ {\n\t\ttime.Now()\n\t}\n}\n<commit_msg>runtime: remove VDSO fallback test and benchmarks<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage samples\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/timeutil\"\n\t\"github.com\/jacobsa\/fuse\"\n\t\"github.com\/jacobsa\/ogletest\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ A struct that implements common behavior needed by tests in the samples\/\n\/\/ directory. Use it as an embedded field in your test fixture, calling its\n\/\/ SetUp method from your SetUp method after setting the FileSystem field.\ntype SampleTest struct {\n\t\/\/ The file system under test and the configuration with which it should be\n\t\/\/ mounted. These must be set by the user of this type before calling SetUp;\n\t\/\/ all the other fields below are set by SetUp itself.\n\tFileSystem  fuse.FileSystem\n\tMountConfig fuse.MountConfig\n\n\t\/\/ A context object that can be used for long-running operations.\n\tCtx context.Context\n\n\t\/\/ A clock with a fixed initial time. The test's set up method may use this\n\t\/\/ to wire the file system with a clock, if desired.\n\tClock timeutil.SimulatedClock\n\n\t\/\/ The directory at which the file system is mounted.\n\tDir string\n\n\t\/\/ Anothing non-nil in this slice will be closed by TearDown. The test will\n\t\/\/ fail if closing fails.\n\tToClose []io.Closer\n\n\tmfs *fuse.MountedFileSystem\n}\n\n\/\/ Mount t.FileSystem and initialize the other exported fields of the struct.\n\/\/ Panics on error.\n\/\/\n\/\/ REQUIRES: t.FileSystem has been set.\nfunc (t *SampleTest) SetUp(ti *ogletest.TestInfo) {\n\terr := t.initialize(t.FileSystem, &t.MountConfig)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Like SetUp, but doens't panic.\nfunc (t *SampleTest) initialize(\n\tfs fuse.FileSystem,\n\tconfig *fuse.MountConfig) (err error) {\n\t\/\/ Initialize the context.\n\tt.Ctx = context.Background()\n\n\t\/\/ Initialize the clock.\n\tt.Clock.SetTime(time.Date(2012, 8, 15, 22, 56, 0, 0, time.Local))\n\n\t\/\/ Set up a temporary directory.\n\tt.Dir, err = ioutil.TempDir(\"\", \"sample_test\")\n\tif err != nil {\n\t\terr = fmt.Errorf(\"TempDir: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Mount the file system.\n\tt.mfs, err = fuse.Mount(t.Dir, fs, config)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Mount: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Wait for it to be read.\n\terr = t.mfs.WaitForReady(t.Ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"WaitForReady: %v\", err)\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ Unmount the file system and clean up. Panics on error.\nfunc (t *SampleTest) TearDown() {\n\terr := t.destroy()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Like TearDown, but doesn't panic.\nfunc (t *SampleTest) destroy() (err error) {\n\t\/\/ Close what is necessary.\n\tfor _, c := range t.ToClose {\n\t\tif c == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\togletest.ExpectEq(nil, c.Close())\n\t}\n\n\t\/\/ Was the file system mounted?\n\tif t.mfs == nil {\n\t\treturn\n\t}\n\n\t\/\/ Unmount the file system. Try again on \"resource busy\" errors.\n\tdelay := 10 * time.Millisecond\n\tfor {\n\t\terr = t.mfs.Unmount()\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif strings.Contains(err.Error(), \"resource busy\") {\n\t\t\tlog.Println(\"Resource busy error while unmounting; trying again\")\n\t\t\ttime.Sleep(delay)\n\t\t\tdelay = time.Duration(1.3 * float64(delay))\n\t\t\tcontinue\n\t\t}\n\n\t\terr = fmt.Errorf(\"MountedFileSystem.Unmount: %v\", err)\n\t\treturn\n\t}\n\n\tif err = t.mfs.Join(t.Ctx); err != nil {\n\t\terr = fmt.Errorf(\"MountedFileSystem.Join: %v\", err)\n\t\treturn\n\t}\n\n\treturn\n}\n<commit_msg>Fixed a comment.<commit_after>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage samples\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/timeutil\"\n\t\"github.com\/jacobsa\/fuse\"\n\t\"github.com\/jacobsa\/ogletest\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ A struct that implements common behavior needed by tests in the samples\/\n\/\/ directory. Use it as an embedded field in your test fixture, calling its\n\/\/ SetUp method from your SetUp method after setting the FileSystem field.\ntype SampleTest struct {\n\t\/\/ The file system under test and the configuration with which it should be\n\t\/\/ mounted. These must be set by the user of this type before calling SetUp;\n\t\/\/ all the other fields below are set by SetUp itself.\n\tFileSystem  fuse.FileSystem\n\tMountConfig fuse.MountConfig\n\n\t\/\/ A context object that can be used for long-running operations.\n\tCtx context.Context\n\n\t\/\/ A clock with a fixed initial time. The test's set up method may use this\n\t\/\/ to wire the file system with a clock, if desired.\n\tClock timeutil.SimulatedClock\n\n\t\/\/ The directory at which the file system is mounted.\n\tDir string\n\n\t\/\/ Anothing non-nil in this slice will be closed by TearDown. The test will\n\t\/\/ fail if closing fails.\n\tToClose []io.Closer\n\n\tmfs *fuse.MountedFileSystem\n}\n\n\/\/ Mount t.FileSystem and initialize the other exported fields of the struct.\n\/\/ Panics on error.\n\/\/\n\/\/ REQUIRES: t.FileSystem has been set.\nfunc (t *SampleTest) SetUp(ti *ogletest.TestInfo) {\n\terr := t.initialize(t.FileSystem, &t.MountConfig)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Like SetUp, but doens't panic.\nfunc (t *SampleTest) initialize(\n\tfs fuse.FileSystem,\n\tconfig *fuse.MountConfig) (err error) {\n\t\/\/ Initialize the context.\n\tt.Ctx = context.Background()\n\n\t\/\/ Initialize the clock.\n\tt.Clock.SetTime(time.Date(2012, 8, 15, 22, 56, 0, 0, time.Local))\n\n\t\/\/ Set up a temporary directory.\n\tt.Dir, err = ioutil.TempDir(\"\", \"sample_test\")\n\tif err != nil {\n\t\terr = fmt.Errorf(\"TempDir: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Mount the file system.\n\tt.mfs, err = fuse.Mount(t.Dir, fs, config)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Mount: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Wait for it to be ready.\n\terr = t.mfs.WaitForReady(t.Ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"WaitForReady: %v\", err)\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ Unmount the file system and clean up. Panics on error.\nfunc (t *SampleTest) TearDown() {\n\terr := t.destroy()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Like TearDown, but doesn't panic.\nfunc (t *SampleTest) destroy() (err error) {\n\t\/\/ Close what is necessary.\n\tfor _, c := range t.ToClose {\n\t\tif c == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\togletest.ExpectEq(nil, c.Close())\n\t}\n\n\t\/\/ Was the file system mounted?\n\tif t.mfs == nil {\n\t\treturn\n\t}\n\n\t\/\/ Unmount the file system. Try again on \"resource busy\" errors.\n\tdelay := 10 * time.Millisecond\n\tfor {\n\t\terr = t.mfs.Unmount()\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif strings.Contains(err.Error(), \"resource busy\") {\n\t\t\tlog.Println(\"Resource busy error while unmounting; trying again\")\n\t\t\ttime.Sleep(delay)\n\t\t\tdelay = time.Duration(1.3 * float64(delay))\n\t\t\tcontinue\n\t\t}\n\n\t\terr = fmt.Errorf(\"MountedFileSystem.Unmount: %v\", err)\n\t\treturn\n\t}\n\n\tif err = t.mfs.Join(t.Ctx); err != nil {\n\t\terr = fmt.Errorf(\"MountedFileSystem.Join: %v\", err)\n\t\treturn\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 by the contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/kubernetes-sigs\/aws-iam-authenticator\/pkg\/config\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n)\n\nvar cfgFile string\n\nvar rootCmd = &cobra.Command{\n\tUse:   \"aws-iam-authenticator\",\n\tShort: \"A tool to authenticate to Kubernetes using AWS IAM credentials\",\n}\n\nfunc main() {\n\tExecute()\n}\n\n\/\/ Execute the CLI entrypoint\nfunc Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc init() {\n\tlogrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})\n\tcobra.OnInitialize(initConfig)\n\trootCmd.PersistentFlags().StringVarP(&cfgFile, \"config\", \"c\", \"\", \"Load configuration from `filename`\")\n\n\trootCmd.PersistentFlags().StringP(\n\t\t\"cluster-id\",\n\t\t\"i\",\n\t\t\"\",\n\t\t\"Specify the cluster `ID`, a unique-per-cluster identifier for your aws-iam-authenticator installation.\",\n\t)\n\tviper.BindPFlag(\"clusterID\", rootCmd.PersistentFlags().Lookup(\"cluster-id\"))\n\tviper.BindEnv(\"clusterID\", \"KUBERNETES_AWS_AUTHENTICATOR_CLUSTER_ID\")\n}\n\nfunc initConfig() {\n\tif cfgFile == \"\" {\n\t\treturn\n\t}\n\tviper.SetConfigFile(cfgFile)\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tfmt.Printf(\"Can't read configuration file %q: %v\\n\", cfgFile, err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc getConfig() (config.Config, error) {\n\tconfig := config.Config{\n\t\tClusterID:                         viper.GetString(\"clusterID\"),\n\t\tServerEC2DescribeInstancesRoleARN: viper.GetString(\"server.ec2DescribeInstancesRoleARN\"),\n\t\tLocalhostPort:                     viper.GetInt(\"server.port\"),\n\t\tGenerateKubeconfigPath:            viper.GetString(\"server.generateKubeconfig\"),\n\t\tKubeconfigPregenerated:            viper.GetBool(\"server.kubeconfigPregenerated\"),\n\t\tStateDir:                          viper.GetString(\"server.stateDir\"),\n\t}\n\tif err := viper.UnmarshalKey(\"server.mapRoles\", &config.RoleMappings); err != nil {\n\t\treturn config, fmt.Errorf(\"invalid server role mappings: %v\", err)\n\t}\n\tif err := viper.UnmarshalKey(\"server.mapUsers\", &config.UserMappings); err != nil {\n\t\tlogrus.WithError(err).Fatal(\"invalid server user mappings\")\n\t}\n\tif err := viper.UnmarshalKey(\"server.mapAccounts\", &config.AutoMappedAWSAccounts); err != nil {\n\t\tlogrus.WithError(err).Fatal(\"invalid server account mappings\")\n\t}\n\n\tif config.ClusterID == \"\" {\n\t\treturn config, errors.New(\"cluster ID cannot be empty\")\n\t}\n\n\treturn config, nil\n}\n<commit_msg>Add --log-format server flag to configure output format<commit_after>\/*\nCopyright 2017 by the contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/kubernetes-sigs\/aws-iam-authenticator\/pkg\/config\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n)\n\nvar cfgFile string\n\nvar rootCmd = &cobra.Command{\n\tUse:   \"aws-iam-authenticator\",\n\tShort: \"A tool to authenticate to Kubernetes using AWS IAM credentials\",\n}\n\nfunc main() {\n\tExecute()\n}\n\n\/\/ Execute the CLI entrypoint\nfunc Execute() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc init() {\n\tcobra.OnInitialize(initConfig)\n\trootCmd.PersistentFlags().StringVarP(&cfgFile, \"config\", \"c\", \"\", \"Load configuration from `filename`\")\n\n\trootCmd.PersistentFlags().StringP(\"log-format\", \"l\", \"text\", \"Specify log format to use when logging to stderr [text or json]\")\n\n\trootCmd.PersistentFlags().StringP(\n\t\t\"cluster-id\",\n\t\t\"i\",\n\t\t\"\",\n\t\t\"Specify the cluster `ID`, a unique-per-cluster identifier for your aws-iam-authenticator installation.\",\n\t)\n\tviper.BindPFlag(\"clusterID\", rootCmd.PersistentFlags().Lookup(\"cluster-id\"))\n\tviper.BindEnv(\"clusterID\", \"KUBERNETES_AWS_AUTHENTICATOR_CLUSTER_ID\")\n}\n\nfunc initConfig() {\n\tlogrus.SetFormatter(getLogFormatter())\n\tif cfgFile == \"\" {\n\t\treturn\n\t}\n\tviper.SetConfigFile(cfgFile)\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tfmt.Printf(\"Can't read configuration file %q: %v\\n\", cfgFile, err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc getConfig() (config.Config, error) {\n\tconfig := config.Config{\n\t\tClusterID:                         viper.GetString(\"clusterID\"),\n\t\tServerEC2DescribeInstancesRoleARN: viper.GetString(\"server.ec2DescribeInstancesRoleARN\"),\n\t\tLocalhostPort:                     viper.GetInt(\"server.port\"),\n\t\tGenerateKubeconfigPath:            viper.GetString(\"server.generateKubeconfig\"),\n\t\tKubeconfigPregenerated:            viper.GetBool(\"server.kubeconfigPregenerated\"),\n\t\tStateDir:                          viper.GetString(\"server.stateDir\"),\n\t}\n\tif err := viper.UnmarshalKey(\"server.mapRoles\", &config.RoleMappings); err != nil {\n\t\treturn config, fmt.Errorf(\"invalid server role mappings: %v\", err)\n\t}\n\tif err := viper.UnmarshalKey(\"server.mapUsers\", &config.UserMappings); err != nil {\n\t\tlogrus.WithError(err).Fatal(\"invalid server user mappings\")\n\t}\n\tif err := viper.UnmarshalKey(\"server.mapAccounts\", &config.AutoMappedAWSAccounts); err != nil {\n\t\tlogrus.WithError(err).Fatal(\"invalid server account mappings\")\n\t}\n\n\tif config.ClusterID == \"\" {\n\t\treturn config, errors.New(\"cluster ID cannot be empty\")\n\t}\n\n\treturn config, nil\n}\n\nfunc getLogFormatter() logrus.Formatter {\n\tformat, _ := rootCmd.PersistentFlags().GetString(\"log-format\")\n\n\tif format == \"json\" {\n\t\treturn &logrus.JSONFormatter{}\n\t} else if format != \"text\" {\n\t\tlogrus.Warnf(\"Unknown log format specified (%s), will use default text formatter instead.\", format)\n\t}\n\n\treturn &logrus.TextFormatter{FullTimestamp: true}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gateway\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/funkygao\/httprouter\"\n\tlog \"github.com\/funkygao\/log4go\"\n)\n\ntype webServer struct {\n\tgw *Gateway\n\n\tname       string\n\tmaxClients int\n\n\trouter *httprouter.Router\n\n\thttpListener net.Listener\n\thttpServer   *http.Server\n\n\thttpsListener net.Listener\n\thttpsServer   *http.Server\n\n\twaitExitFunc    waitExitFunc\n\tconnStateFunc   connStateFunc\n\tonConnNewFunc   onConnNewFunc\n\tonConnCloseFunc onConnCloseFunc\n\n\tonStop        func()\n\tmu            sync.Mutex\n\twaiterStarted bool\n\n\t\/\/ FIXME if http\/https listener both enabled, must able to tell them apart\n\tactiveConnN int32\n\n\t\/\/ TODO channel performance is frustrating, no better than mutex\/map use ring buffer\n\tstateIdleCh, stateRemoveCh, stateActiveCh chan net.Conn\n\n\tclosed chan struct{}\n}\n\nfunc newWebServer(name string, httpAddr, httpsAddr string, maxClients int,\n\tgw *Gateway) *webServer {\n\tconst initialConnBuckets = 200\n\tthis := &webServer{\n\t\tname:          name,\n\t\tgw:            gw,\n\t\tmaxClients:    maxClients,\n\t\tstateActiveCh: make(chan net.Conn, initialConnBuckets),\n\t\tstateIdleCh:   make(chan net.Conn, initialConnBuckets),\n\t\tstateRemoveCh: make(chan net.Conn, initialConnBuckets),\n\t\trouter:        httprouter.New(),\n\t\tclosed:        make(chan struct{}),\n\t}\n\n\tif Options.EnableHttpPanicRecover {\n\t\tthis.router.PanicHandler = func(w http.ResponseWriter, r *http.Request, err interface{}) {\n\t\t\tlog.Error(\"PANIC %s %s(%s) %s %s: %+v\", this.name, r.RemoteAddr, getHttpRemoteIp(r), r.Method, r.RequestURI, err)\n\n\t\t\twriteServerError(w, http.StatusText(http.StatusInternalServerError))\n\t\t}\n\t}\n\n\tif httpAddr != \"\" {\n\t\tthis.httpServer = &http.Server{\n\t\t\tAddr:           httpAddr,\n\t\t\tHandler:        this.router,\n\t\t\tReadTimeout:    Options.HttpReadTimeout,\n\t\t\tWriteTimeout:   Options.HttpWriteTimeout,\n\t\t\tMaxHeaderBytes: Options.HttpHeaderMaxBytes,\n\t\t}\n\t}\n\n\tif httpsAddr != \"\" {\n\t\tthis.httpsServer = &http.Server{\n\t\t\tAddr:           httpsAddr,\n\t\t\tHandler:        this.router,\n\t\t\tReadTimeout:    Options.HttpReadTimeout,\n\t\t\tWriteTimeout:   Options.HttpWriteTimeout,\n\t\t\tMaxHeaderBytes: Options.HttpHeaderMaxBytes,\n\t\t}\n\t}\n\n\treturn this\n}\n\nfunc (this *webServer) Router() *httprouter.Router {\n\treturn this.router\n}\n\nfunc (this *webServer) Start() {\n\tif this.waitExitFunc == nil {\n\t\tthis.waitExitFunc = this.defaultWaitExit\n\t}\n\tif this.connStateFunc == nil {\n\t\tthis.connStateFunc = this.defaultConnStateMachine\n\n\t\tgo this.manageIdleConns()\n\t}\n\n\tif this.httpsServer != nil {\n\t\tthis.httpsServer.ConnState = this.connStateFunc\n\t\tthis.startServer(true)\n\t}\n\n\tif this.httpServer != nil {\n\t\tthis.httpServer.ConnState = this.connStateFunc\n\t\tthis.startServer(false)\n\t}\n\n}\n\nfunc (this *webServer) startServer(https bool) {\n\tvar err error\n\twaitListenerUp := make(chan struct{})\n\tgo func() {\n\t\tif Options.CpuAffinity {\n\t\t\truntime.LockOSThread()\n\t\t}\n\n\t\tvar (\n\t\t\tretryDelay         time.Duration\n\t\t\ttheListener        net.Listener\n\t\t\twaitListenerUpOnce sync.Once\n\t\t)\n\t\tfor {\n\t\t\tif https {\n\t\t\t\tthis.httpsListener, err = net.Listen(\"tcp\", this.httpsServer.Addr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif strings.HasSuffix(err.Error(), \"address already in use\") {\n\t\t\t\t\t\t\/\/ non-retriable error encountered\n\t\t\t\t\t\tpanic(fmt.Errorf(\"%s listener: %v\", this.name, err))\n\t\t\t\t\t}\n\n\t\t\t\t\tif retryDelay == 0 {\n\t\t\t\t\t\tretryDelay = 50 * time.Millisecond\n\t\t\t\t\t} else {\n\t\t\t\t\t\tretryDelay = 2 * retryDelay\n\t\t\t\t\t}\n\t\t\t\t\tif maxDelay := time.Second; retryDelay > maxDelay {\n\t\t\t\t\t\tretryDelay = maxDelay\n\t\t\t\t\t}\n\t\t\t\t\tlog.Error(\"%s listener %v, retry in %v\", this.name, err, retryDelay)\n\t\t\t\t\ttime.Sleep(retryDelay)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\ttheListener, err = setupHttpsListener(this.httpsListener, this.gw.certFile, this.gw.keyFile)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttheListener, err = net.Listen(\"tcp\", this.httpServer.Addr)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\tif retryDelay == 0 {\n\t\t\t\t\tretryDelay = 50 * time.Millisecond\n\t\t\t\t} else {\n\t\t\t\t\tretryDelay = 2 * retryDelay\n\t\t\t\t}\n\t\t\t\tif maxDelay := time.Second; retryDelay > maxDelay {\n\t\t\t\t\tretryDelay = maxDelay\n\t\t\t\t}\n\t\t\t\tlog.Error(\"%s listener %v, retry in %v\", this.name, err, retryDelay)\n\t\t\t\ttime.Sleep(retryDelay)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttheListener = LimitListener(this.name, this.gw, theListener, this.maxClients)\n\t\t\twaitListenerUpOnce.Do(func() {\n\t\t\t\tclose(waitListenerUp)\n\t\t\t})\n\n\t\t\t\/\/ on non-temporary err, net\/http will close the listener\n\t\t\tif https {\n\t\t\t\tthis.mu.Lock()\n\t\t\t\tthis.httpsListener = theListener\n\t\t\t\tthis.mu.Unlock()\n\n\t\t\t\terr = this.httpsServer.Serve(theListener)\n\t\t\t} else {\n\t\t\t\tthis.mu.Lock()\n\t\t\t\tthis.httpListener = theListener\n\t\t\t\tthis.mu.Unlock()\n\n\t\t\t\terr = this.httpServer.Serve(theListener)\n\t\t\t}\n\n\t\t\tselect {\n\t\t\tcase <-this.gw.shutdownCh:\n\t\t\t\treturn\n\n\t\t\tdefault:\n\t\t\t\tlog.Error(\"%s server: %v\", this.name, err)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ wait for the listener up\n\t<-waitListenerUp\n\n\tthis.mu.Lock()\n\tif !this.waiterStarted {\n\t\tthis.waiterStarted = true\n\n\t\tthis.gw.wg.Add(1)\n\t\tgo this.waitExitFunc(this.gw.shutdownCh)\n\t}\n\tthis.mu.Unlock()\n\n\tif https {\n\t\tlog.Info(\"%s https server ready on %s\", this.name, this.httpsServer.Addr)\n\t} else {\n\t\tlog.Info(\"%s http server ready on %s\", this.name, this.httpServer.Addr)\n\t}\n}\n\nfunc (this *webServer) defaultConnStateMachine(c net.Conn, cs http.ConnState) {\n\tswitch cs {\n\tcase http.StateNew:\n\t\tatomic.AddInt32(&this.activeConnN, 1)\n\n\t\tif this.onConnNewFunc != nil {\n\t\t\tthis.onConnNewFunc(c)\n\t\t}\n\n\tcase http.StateIdle:\n\t\tthis.stateIdleCh <- c\n\n\tcase http.StateActive:\n\t\tthis.stateActiveCh <- c\n\n\tcase http.StateClosed, http.StateHijacked:\n\t\tatomic.AddInt32(&this.activeConnN, -1)\n\t\tthis.stateRemoveCh <- c\n\n\t\tif this.onConnCloseFunc != nil {\n\t\t\tthis.onConnCloseFunc(c)\n\t\t}\n\t}\n}\n\nfunc (this *webServer) manageIdleConns() {\n\tvar (\n\t\tidleConns     = make(map[net.Conn]struct{}, 200)\n\t\tc             net.Conn\n\t\twaitNextRound = make(chan struct{}, 10)\n\t)\n\tdefer close(waitNextRound)\n\n\tlog.Debug(\"%s is managing idle connections\", this.name)\n\n\tfor {\n\t\tselect {\n\t\tcase <-this.gw.shutdownCh:\n\t\t\tif len(idleConns) == 0 {\n\t\t\t\t\/\/ happy ending\n\t\t\t\tlog.Debug(\"%s closed all idle conns\", this.name)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tt := time.Now().Add(time.Millisecond * 100)\n\t\t\tfor conn := range idleConns {\n\t\t\t\tif conn == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tlog.Debug(\"%s closing %s\", this.name, conn.RemoteAddr())\n\t\t\t\tconn.SetDeadline(t)\n\t\t\t}\n\n\t\t\t\/\/ wait for next loop\n\t\t\twaitNextRound <- struct{}{}\n\n\t\tcase <-waitNextRound:\n\t\t\tif len(idleConns) == 0 {\n\t\t\t\tlog.Debug(\"%s closed all idle conns\", this.name)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tt := time.Now().Add(time.Millisecond * 100)\n\t\t\tfor conn := range idleConns {\n\t\t\t\tif conn == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tlog.Debug(\"%s closing %s\", this.name, conn.RemoteAddr())\n\t\t\t\tconn.SetDeadline(t)\n\t\t\t}\n\n\t\t\t\/\/ wait for next loop\n\t\t\twaitNextRound <- struct{}{}\n\n\t\tcase c = <-this.stateActiveCh:\n\t\t\tdelete(idleConns, c)\n\n\t\tcase c = <-this.stateIdleCh:\n\t\t\tidleConns[c] = struct{}{}\n\n\t\tcase c = <-this.stateRemoveCh:\n\t\t\tdelete(idleConns, c)\n\t\t}\n\t}\n}\n\nfunc (this *webServer) defaultWaitExit(exit <-chan struct{}) {\n\tlog.Debug(\"%s enter default wait exit\", this.name)\n\n\t<-exit\n\n\tvar err error\n\tif this.httpServer != nil {\n\t\t\/\/ HTTP response will have \"Connection: close\"\n\t\tthis.httpServer.SetKeepAlivesEnabled(false)\n\n\t\t\/\/ avoid new connections\n\t\tthis.mu.Lock()\n\t\tif this.httpListener != nil {\n\t\t\terr = this.httpListener.Close()\n\t\t}\n\t\tthis.mu.Unlock()\n\n\t\tif err != nil {\n\t\t\tlog.Error(\"%s on %s: %+v\", this.name, this.httpServer.Addr, err)\n\t\t}\n\n\t\tlog.Trace(\"%s on %s listener closed\", this.name, this.httpServer.Addr)\n\t}\n\n\tif this.httpsServer != nil {\n\t\t\/\/ HTTP response will have \"Connection: close\"\n\t\tthis.httpsServer.SetKeepAlivesEnabled(false)\n\n\t\t\/\/ avoid new connections\n\t\tthis.mu.Lock()\n\t\tif this.httpsListener != nil {\n\t\t\terr = this.httpsListener.Close()\n\t\t}\n\t\tthis.mu.Unlock()\n\n\t\tif err != nil {\n\t\t\tlog.Error(\"%s on %s: %+v\", this.name, this.httpsServer.Addr, err)\n\t\t}\n\n\t\tlog.Trace(\"%s on %s listener closed\", this.name, this.httpsServer.Addr)\n\t}\n\n\t\/\/ wait for all established http\/https conns close\n\twaitStart := time.Now()\n\tvar prompt sync.Once\n\tfor {\n\t\tactiveConnN := atomic.LoadInt32(&this.activeConnN)\n\t\tif activeConnN == 0 {\n\t\t\t\/\/ good luck, all connections finished\n\t\t\tbreak\n\t\t}\n\n\t\tprompt.Do(func() {\n\t\t\tlog.Trace(\"%s waiting for %d clients shutdown...\", this.name, activeConnN)\n\t\t})\n\n\t\t\/\/ timeout mechanism\n\t\tif time.Since(waitStart) > Options.SubTimeout+time.Second {\n\t\t\tlog.Warn(\"%s still left %d conns after %s, forced to shutdown\",\n\t\t\t\tthis.name, activeConnN, Options.SubTimeout)\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(time.Millisecond * 50)\n\t}\n\tlog.Trace(\"%s all connections finished\", this.name)\n\n\tif this.httpsServer != nil {\n\t\tthis.httpsServer.ConnState = nil\n\t}\n\tif this.httpServer != nil {\n\t\tthis.httpServer.ConnState = nil\n\t}\n\n\t\/\/ TODO close will lead to race condition\n\t\/\/close(this.stateActiveCh)\n\t\/\/close(this.stateIdleCh)\n\t\/\/close(this.stateRemoveCh)\n\n\tif this.onStop != nil {\n\t\tthis.onStop()\n\t}\n\n\tthis.gw.wg.Done()\n\tclose(this.closed)\n}\n\nfunc (this *webServer) Closed() <-chan struct{} {\n\treturn this.closed\n}\n\nfunc (this *webServer) notFoundHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Error(\"%s: not found %s\", this.name, r.RequestURI)\n\n\twriteNotFound(w)\n}\n<commit_msg>log the request method in 404 handler<commit_after>package gateway\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/funkygao\/httprouter\"\n\tlog \"github.com\/funkygao\/log4go\"\n)\n\ntype webServer struct {\n\tgw *Gateway\n\n\tname       string\n\tmaxClients int\n\n\trouter *httprouter.Router\n\n\thttpListener net.Listener\n\thttpServer   *http.Server\n\n\thttpsListener net.Listener\n\thttpsServer   *http.Server\n\n\twaitExitFunc    waitExitFunc\n\tconnStateFunc   connStateFunc\n\tonConnNewFunc   onConnNewFunc\n\tonConnCloseFunc onConnCloseFunc\n\n\tonStop        func()\n\tmu            sync.Mutex\n\twaiterStarted bool\n\n\t\/\/ FIXME if http\/https listener both enabled, must able to tell them apart\n\tactiveConnN int32\n\n\t\/\/ TODO channel performance is frustrating, no better than mutex\/map use ring buffer\n\tstateIdleCh, stateRemoveCh, stateActiveCh chan net.Conn\n\n\tclosed chan struct{}\n}\n\nfunc newWebServer(name string, httpAddr, httpsAddr string, maxClients int,\n\tgw *Gateway) *webServer {\n\tconst initialConnBuckets = 200\n\tthis := &webServer{\n\t\tname:          name,\n\t\tgw:            gw,\n\t\tmaxClients:    maxClients,\n\t\tstateActiveCh: make(chan net.Conn, initialConnBuckets),\n\t\tstateIdleCh:   make(chan net.Conn, initialConnBuckets),\n\t\tstateRemoveCh: make(chan net.Conn, initialConnBuckets),\n\t\trouter:        httprouter.New(),\n\t\tclosed:        make(chan struct{}),\n\t}\n\n\tif Options.EnableHttpPanicRecover {\n\t\tthis.router.PanicHandler = func(w http.ResponseWriter, r *http.Request, err interface{}) {\n\t\t\tlog.Error(\"PANIC %s %s(%s) %s %s: %+v\", this.name, r.RemoteAddr, getHttpRemoteIp(r), r.Method, r.RequestURI, err)\n\n\t\t\twriteServerError(w, http.StatusText(http.StatusInternalServerError))\n\t\t}\n\t}\n\n\tif httpAddr != \"\" {\n\t\tthis.httpServer = &http.Server{\n\t\t\tAddr:           httpAddr,\n\t\t\tHandler:        this.router,\n\t\t\tReadTimeout:    Options.HttpReadTimeout,\n\t\t\tWriteTimeout:   Options.HttpWriteTimeout,\n\t\t\tMaxHeaderBytes: Options.HttpHeaderMaxBytes,\n\t\t}\n\t}\n\n\tif httpsAddr != \"\" {\n\t\tthis.httpsServer = &http.Server{\n\t\t\tAddr:           httpsAddr,\n\t\t\tHandler:        this.router,\n\t\t\tReadTimeout:    Options.HttpReadTimeout,\n\t\t\tWriteTimeout:   Options.HttpWriteTimeout,\n\t\t\tMaxHeaderBytes: Options.HttpHeaderMaxBytes,\n\t\t}\n\t}\n\n\treturn this\n}\n\nfunc (this *webServer) Router() *httprouter.Router {\n\treturn this.router\n}\n\nfunc (this *webServer) Start() {\n\tif this.waitExitFunc == nil {\n\t\tthis.waitExitFunc = this.defaultWaitExit\n\t}\n\tif this.connStateFunc == nil {\n\t\tthis.connStateFunc = this.defaultConnStateMachine\n\n\t\tgo this.manageIdleConns()\n\t}\n\n\tif this.httpsServer != nil {\n\t\tthis.httpsServer.ConnState = this.connStateFunc\n\t\tthis.startServer(true)\n\t}\n\n\tif this.httpServer != nil {\n\t\tthis.httpServer.ConnState = this.connStateFunc\n\t\tthis.startServer(false)\n\t}\n\n}\n\nfunc (this *webServer) startServer(https bool) {\n\tvar err error\n\twaitListenerUp := make(chan struct{})\n\tgo func() {\n\t\tif Options.CpuAffinity {\n\t\t\truntime.LockOSThread()\n\t\t}\n\n\t\tvar (\n\t\t\tretryDelay         time.Duration\n\t\t\ttheListener        net.Listener\n\t\t\twaitListenerUpOnce sync.Once\n\t\t)\n\t\tfor {\n\t\t\tif https {\n\t\t\t\tthis.httpsListener, err = net.Listen(\"tcp\", this.httpsServer.Addr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif strings.HasSuffix(err.Error(), \"address already in use\") {\n\t\t\t\t\t\t\/\/ non-retriable error encountered\n\t\t\t\t\t\tpanic(fmt.Errorf(\"%s listener: %v\", this.name, err))\n\t\t\t\t\t}\n\n\t\t\t\t\tif retryDelay == 0 {\n\t\t\t\t\t\tretryDelay = 50 * time.Millisecond\n\t\t\t\t\t} else {\n\t\t\t\t\t\tretryDelay = 2 * retryDelay\n\t\t\t\t\t}\n\t\t\t\t\tif maxDelay := time.Second; retryDelay > maxDelay {\n\t\t\t\t\t\tretryDelay = maxDelay\n\t\t\t\t\t}\n\t\t\t\t\tlog.Error(\"%s listener %v, retry in %v\", this.name, err, retryDelay)\n\t\t\t\t\ttime.Sleep(retryDelay)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\ttheListener, err = setupHttpsListener(this.httpsListener, this.gw.certFile, this.gw.keyFile)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttheListener, err = net.Listen(\"tcp\", this.httpServer.Addr)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\tif retryDelay == 0 {\n\t\t\t\t\tretryDelay = 50 * time.Millisecond\n\t\t\t\t} else {\n\t\t\t\t\tretryDelay = 2 * retryDelay\n\t\t\t\t}\n\t\t\t\tif maxDelay := time.Second; retryDelay > maxDelay {\n\t\t\t\t\tretryDelay = maxDelay\n\t\t\t\t}\n\t\t\t\tlog.Error(\"%s listener %v, retry in %v\", this.name, err, retryDelay)\n\t\t\t\ttime.Sleep(retryDelay)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttheListener = LimitListener(this.name, this.gw, theListener, this.maxClients)\n\t\t\twaitListenerUpOnce.Do(func() {\n\t\t\t\tclose(waitListenerUp)\n\t\t\t})\n\n\t\t\t\/\/ on non-temporary err, net\/http will close the listener\n\t\t\tif https {\n\t\t\t\tthis.mu.Lock()\n\t\t\t\tthis.httpsListener = theListener\n\t\t\t\tthis.mu.Unlock()\n\n\t\t\t\terr = this.httpsServer.Serve(theListener)\n\t\t\t} else {\n\t\t\t\tthis.mu.Lock()\n\t\t\t\tthis.httpListener = theListener\n\t\t\t\tthis.mu.Unlock()\n\n\t\t\t\terr = this.httpServer.Serve(theListener)\n\t\t\t}\n\n\t\t\tselect {\n\t\t\tcase <-this.gw.shutdownCh:\n\t\t\t\treturn\n\n\t\t\tdefault:\n\t\t\t\tlog.Error(\"%s server: %v\", this.name, err)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ wait for the listener up\n\t<-waitListenerUp\n\n\tthis.mu.Lock()\n\tif !this.waiterStarted {\n\t\tthis.waiterStarted = true\n\n\t\tthis.gw.wg.Add(1)\n\t\tgo this.waitExitFunc(this.gw.shutdownCh)\n\t}\n\tthis.mu.Unlock()\n\n\tif https {\n\t\tlog.Info(\"%s https server ready on %s\", this.name, this.httpsServer.Addr)\n\t} else {\n\t\tlog.Info(\"%s http server ready on %s\", this.name, this.httpServer.Addr)\n\t}\n}\n\nfunc (this *webServer) defaultConnStateMachine(c net.Conn, cs http.ConnState) {\n\tswitch cs {\n\tcase http.StateNew:\n\t\tatomic.AddInt32(&this.activeConnN, 1)\n\n\t\tif this.onConnNewFunc != nil {\n\t\t\tthis.onConnNewFunc(c)\n\t\t}\n\n\tcase http.StateIdle:\n\t\tthis.stateIdleCh <- c\n\n\tcase http.StateActive:\n\t\tthis.stateActiveCh <- c\n\n\tcase http.StateClosed, http.StateHijacked:\n\t\tatomic.AddInt32(&this.activeConnN, -1)\n\t\tthis.stateRemoveCh <- c\n\n\t\tif this.onConnCloseFunc != nil {\n\t\t\tthis.onConnCloseFunc(c)\n\t\t}\n\t}\n}\n\nfunc (this *webServer) manageIdleConns() {\n\tvar (\n\t\tidleConns     = make(map[net.Conn]struct{}, 200)\n\t\tc             net.Conn\n\t\twaitNextRound = make(chan struct{}, 10)\n\t)\n\tdefer close(waitNextRound)\n\n\tlog.Debug(\"%s is managing idle connections\", this.name)\n\n\tfor {\n\t\tselect {\n\t\tcase <-this.gw.shutdownCh:\n\t\t\tif len(idleConns) == 0 {\n\t\t\t\t\/\/ happy ending\n\t\t\t\tlog.Debug(\"%s closed all idle conns\", this.name)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tt := time.Now().Add(time.Millisecond * 100)\n\t\t\tfor conn := range idleConns {\n\t\t\t\tif conn == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tlog.Debug(\"%s closing %s\", this.name, conn.RemoteAddr())\n\t\t\t\tconn.SetDeadline(t)\n\t\t\t}\n\n\t\t\t\/\/ wait for next loop\n\t\t\twaitNextRound <- struct{}{}\n\n\t\tcase <-waitNextRound:\n\t\t\tif len(idleConns) == 0 {\n\t\t\t\tlog.Debug(\"%s closed all idle conns\", this.name)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tt := time.Now().Add(time.Millisecond * 100)\n\t\t\tfor conn := range idleConns {\n\t\t\t\tif conn == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tlog.Debug(\"%s closing %s\", this.name, conn.RemoteAddr())\n\t\t\t\tconn.SetDeadline(t)\n\t\t\t}\n\n\t\t\t\/\/ wait for next loop\n\t\t\twaitNextRound <- struct{}{}\n\n\t\tcase c = <-this.stateActiveCh:\n\t\t\tdelete(idleConns, c)\n\n\t\tcase c = <-this.stateIdleCh:\n\t\t\tidleConns[c] = struct{}{}\n\n\t\tcase c = <-this.stateRemoveCh:\n\t\t\tdelete(idleConns, c)\n\t\t}\n\t}\n}\n\nfunc (this *webServer) defaultWaitExit(exit <-chan struct{}) {\n\tlog.Debug(\"%s enter default wait exit\", this.name)\n\n\t<-exit\n\n\tvar err error\n\tif this.httpServer != nil {\n\t\t\/\/ HTTP response will have \"Connection: close\"\n\t\tthis.httpServer.SetKeepAlivesEnabled(false)\n\n\t\t\/\/ avoid new connections\n\t\tthis.mu.Lock()\n\t\tif this.httpListener != nil {\n\t\t\terr = this.httpListener.Close()\n\t\t}\n\t\tthis.mu.Unlock()\n\n\t\tif err != nil {\n\t\t\tlog.Error(\"%s on %s: %+v\", this.name, this.httpServer.Addr, err)\n\t\t}\n\n\t\tlog.Trace(\"%s on %s listener closed\", this.name, this.httpServer.Addr)\n\t}\n\n\tif this.httpsServer != nil {\n\t\t\/\/ HTTP response will have \"Connection: close\"\n\t\tthis.httpsServer.SetKeepAlivesEnabled(false)\n\n\t\t\/\/ avoid new connections\n\t\tthis.mu.Lock()\n\t\tif this.httpsListener != nil {\n\t\t\terr = this.httpsListener.Close()\n\t\t}\n\t\tthis.mu.Unlock()\n\n\t\tif err != nil {\n\t\t\tlog.Error(\"%s on %s: %+v\", this.name, this.httpsServer.Addr, err)\n\t\t}\n\n\t\tlog.Trace(\"%s on %s listener closed\", this.name, this.httpsServer.Addr)\n\t}\n\n\t\/\/ wait for all established http\/https conns close\n\twaitStart := time.Now()\n\tvar prompt sync.Once\n\tfor {\n\t\tactiveConnN := atomic.LoadInt32(&this.activeConnN)\n\t\tif activeConnN == 0 {\n\t\t\t\/\/ good luck, all connections finished\n\t\t\tbreak\n\t\t}\n\n\t\tprompt.Do(func() {\n\t\t\tlog.Trace(\"%s waiting for %d clients shutdown...\", this.name, activeConnN)\n\t\t})\n\n\t\t\/\/ timeout mechanism\n\t\tif time.Since(waitStart) > Options.SubTimeout+time.Second {\n\t\t\tlog.Warn(\"%s still left %d conns after %s, forced to shutdown\",\n\t\t\t\tthis.name, activeConnN, Options.SubTimeout)\n\t\t\tbreak\n\t\t}\n\n\t\ttime.Sleep(time.Millisecond * 50)\n\t}\n\tlog.Trace(\"%s all connections finished\", this.name)\n\n\tif this.httpsServer != nil {\n\t\tthis.httpsServer.ConnState = nil\n\t}\n\tif this.httpServer != nil {\n\t\tthis.httpServer.ConnState = nil\n\t}\n\n\t\/\/ TODO close will lead to race condition\n\t\/\/close(this.stateActiveCh)\n\t\/\/close(this.stateIdleCh)\n\t\/\/close(this.stateRemoveCh)\n\n\tif this.onStop != nil {\n\t\tthis.onStop()\n\t}\n\n\tthis.gw.wg.Done()\n\tclose(this.closed)\n}\n\nfunc (this *webServer) Closed() <-chan struct{} {\n\treturn this.closed\n}\n\nfunc (this *webServer) notFoundHandler(w http.ResponseWriter, r *http.Request) {\n\tlog.Error(\"%s: not found %s %s\", this.name, r.Method, r.RequestURI)\n\n\twriteNotFound(w)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright The OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage trace_test\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"go.opentelemetry.io\/otel\/attribute\"\n\tsdktrace \"go.opentelemetry.io\/otel\/sdk\/trace\"\n\t\"go.opentelemetry.io\/otel\/trace\"\n)\n\nfunc BenchmarkStartEndSpan(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark StartEndSpan\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.End()\n\t\t}\n\t})\n}\n\nfunc BenchmarkSpanWithAttributes_4(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark Start With 4 Attributes\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.SetAttributes(\n\t\t\t\tattribute.Bool(\"key1\", false),\n\t\t\t\tattribute.String(\"key2\", \"hello\"),\n\t\t\t\tattribute.Float64(\"key4\", 123.456),\n\t\t\t)\n\t\t\tspan.End()\n\t\t}\n\t})\n}\n\nfunc BenchmarkSpanWithAttributes_8(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark Start With 8 Attributes\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.SetAttributes(\n\t\t\t\tattribute.Bool(\"key1\", false),\n\t\t\t\tattribute.String(\"key2\", \"hello\"),\n\t\t\t\tattribute.Float64(\"key4\", 123.456),\n\t\t\t\tattribute.Bool(\"key21\", false),\n\t\t\t\tattribute.String(\"key22\", \"hello\"),\n\t\t\t\tattribute.Float64(\"key24\", 123.456),\n\t\t\t)\n\t\t\tspan.End()\n\t\t}\n\t})\n}\n\nfunc BenchmarkSpanWithAttributes_all(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark Start With all Attribute types\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.SetAttributes(\n\t\t\t\tattribute.Bool(\"key1\", false),\n\t\t\t\tattribute.String(\"key2\", \"hello\"),\n\t\t\t\tattribute.Int64(\"key3\", 123),\n\t\t\t\tattribute.Float64(\"key7\", 123.456),\n\t\t\t\tattribute.Int(\"key9\", 123),\n\t\t\t)\n\t\t\tspan.End()\n\t\t}\n\t})\n}\n\nfunc BenchmarkSpanWithAttributes_all_2x(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark Start With all Attributes types twice\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.SetAttributes(\n\t\t\t\tattribute.Bool(\"key1\", false),\n\t\t\t\tattribute.String(\"key2\", \"hello\"),\n\t\t\t\tattribute.Int64(\"key3\", 123),\n\t\t\t\tattribute.Float64(\"key7\", 123.456),\n\t\t\t\tattribute.Int(\"key10\", 123),\n\t\t\t\tattribute.Bool(\"key21\", false),\n\t\t\t\tattribute.String(\"key22\", \"hello\"),\n\t\t\t\tattribute.Int64(\"key23\", 123),\n\t\t\t\tattribute.Float64(\"key27\", 123.456),\n\t\t\t\tattribute.Int(\"key210\", 123),\n\t\t\t)\n\t\t\tspan.End()\n\t\t}\n\t})\n}\n\nfunc BenchmarkTraceID_DotString(b *testing.B) {\n\tt, _ := trace.TraceIDFromHex(\"0000000000000001000000000000002a\")\n\tsc := trace.NewSpanContext(trace.SpanContextConfig{TraceID: t})\n\n\twant := \"0000000000000001000000000000002a\"\n\tfor i := 0; i < b.N; i++ {\n\t\tif got := sc.TraceID().String(); got != want {\n\t\t\tb.Fatalf(\"got = %q want = %q\", got, want)\n\t\t}\n\t}\n}\n\nfunc BenchmarkSpanID_DotString(b *testing.B) {\n\tsc := trace.NewSpanContext(trace.SpanContextConfig{SpanID: trace.SpanID{1}})\n\twant := \"0100000000000000\"\n\tfor i := 0; i < b.N; i++ {\n\t\tif got := sc.SpanID().String(); got != want {\n\t\t\tb.Fatalf(\"got = %q want = %q\", got, want)\n\t\t}\n\t}\n}\n\nfunc traceBenchmark(b *testing.B, name string, fn func(*testing.B, trace.Tracer)) {\n\tb.Run(\"AlwaysSample\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfn(b, tracer(b, name, sdktrace.AlwaysSample()))\n\t})\n\tb.Run(\"NeverSample\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfn(b, tracer(b, name, sdktrace.NeverSample()))\n\t})\n}\n\nfunc tracer(b *testing.B, name string, sampler sdktrace.Sampler) trace.Tracer {\n\ttp := sdktrace.NewTracerProvider(sdktrace.WithSampler(sampler))\n\treturn tp.Tracer(name)\n}\n<commit_msg>Added Benchmarks around events (#2405)<commit_after>\/\/ Copyright The OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage trace_test\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"go.opentelemetry.io\/otel\/attribute\"\n\tsdktrace \"go.opentelemetry.io\/otel\/sdk\/trace\"\n\t\"go.opentelemetry.io\/otel\/trace\"\n)\n\nfunc BenchmarkStartEndSpan(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark StartEndSpan\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.End()\n\t\t}\n\t})\n}\n\nfunc BenchmarkSpanWithAttributes_4(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark Start With 4 Attributes\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.SetAttributes(\n\t\t\t\tattribute.Bool(\"key1\", false),\n\t\t\t\tattribute.String(\"key2\", \"hello\"),\n\t\t\t\tattribute.Int64(\"key3\", 123),\n\t\t\t\tattribute.Float64(\"key4\", 123.456),\n\t\t\t)\n\t\t\tspan.End()\n\t\t}\n\t})\n}\n\nfunc BenchmarkSpanWithAttributes_8(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark Start With 8 Attributes\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.SetAttributes(\n\t\t\t\tattribute.Bool(\"key1\", false),\n\t\t\t\tattribute.String(\"key2\", \"hello\"),\n\t\t\t\tattribute.Int64(\"key3\", 123),\n\t\t\t\tattribute.Float64(\"key4\", 123.456),\n\t\t\t\tattribute.Bool(\"key21\", false),\n\t\t\t\tattribute.String(\"key22\", \"hello\"),\n\t\t\t\tattribute.Int64(\"key23\", 123),\n\t\t\t\tattribute.Float64(\"key24\", 123.456),\n\t\t\t)\n\t\t\tspan.End()\n\t\t}\n\t})\n}\n\nfunc BenchmarkSpanWithAttributes_all(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark Start With all Attribute types\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.SetAttributes(\n\t\t\t\tattribute.Bool(\"key1\", false),\n\t\t\t\tattribute.String(\"key2\", \"hello\"),\n\t\t\t\tattribute.Int64(\"key3\", 123),\n\t\t\t\tattribute.Float64(\"key7\", 123.456),\n\t\t\t\tattribute.Int(\"key9\", 123),\n\t\t\t)\n\t\t\tspan.End()\n\t\t}\n\t})\n}\n\nfunc BenchmarkSpanWithAttributes_all_2x(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark Start With all Attributes types twice\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.SetAttributes(\n\t\t\t\tattribute.Bool(\"key1\", false),\n\t\t\t\tattribute.String(\"key2\", \"hello\"),\n\t\t\t\tattribute.Int64(\"key3\", 123),\n\t\t\t\tattribute.Float64(\"key7\", 123.456),\n\t\t\t\tattribute.Int(\"key10\", 123),\n\t\t\t\tattribute.Bool(\"key21\", false),\n\t\t\t\tattribute.String(\"key22\", \"hello\"),\n\t\t\t\tattribute.Int64(\"key23\", 123),\n\t\t\t\tattribute.Float64(\"key27\", 123.456),\n\t\t\t\tattribute.Int(\"key210\", 123),\n\t\t\t)\n\t\t\tspan.End()\n\t\t}\n\t})\n}\n\nfunc BenchmarkSpanWithEvents_4(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark Start With 4 Events\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.AddEvent(\"event1\")\n\t\t\tspan.AddEvent(\"event2\")\n\t\t\tspan.AddEvent(\"event3\")\n\t\t\tspan.AddEvent(\"event4\")\n\t\t\tspan.End()\n\t\t}\n\t})\n}\n\nfunc BenchmarkSpanWithEvents_8(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark Start With 4 Events\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.AddEvent(\"event1\")\n\t\t\tspan.AddEvent(\"event2\")\n\t\t\tspan.AddEvent(\"event3\")\n\t\t\tspan.AddEvent(\"event4\")\n\t\t\tspan.AddEvent(\"event5\")\n\t\t\tspan.AddEvent(\"event6\")\n\t\t\tspan.AddEvent(\"event7\")\n\t\t\tspan.AddEvent(\"event8\")\n\t\t\tspan.End()\n\t\t}\n\t})\n}\n\nfunc BenchmarkSpanWithEvents_WithStackTrace(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark Start With 4 Attributes\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.AddEvent(\"event1\", trace.WithStackTrace(true))\n\t\t\tspan.End()\n\t\t}\n\t})\n}\nfunc BenchmarkSpanWithEvents_WithTimestamp(b *testing.B) {\n\ttraceBenchmark(b, \"Benchmark Start With 4 Attributes\", func(b *testing.B, t trace.Tracer) {\n\t\tctx := context.Background()\n\t\tb.ResetTimer()\n\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\t_, span := t.Start(ctx, \"\/foo\")\n\t\t\tspan.AddEvent(\"event1\", trace.WithTimestamp(time.Unix(0, 0)))\n\t\t\tspan.End()\n\t\t}\n\t})\n}\n\nfunc BenchmarkTraceID_DotString(b *testing.B) {\n\tt, _ := trace.TraceIDFromHex(\"0000000000000001000000000000002a\")\n\tsc := trace.NewSpanContext(trace.SpanContextConfig{TraceID: t})\n\n\twant := \"0000000000000001000000000000002a\"\n\tfor i := 0; i < b.N; i++ {\n\t\tif got := sc.TraceID().String(); got != want {\n\t\t\tb.Fatalf(\"got = %q want = %q\", got, want)\n\t\t}\n\t}\n}\n\nfunc BenchmarkSpanID_DotString(b *testing.B) {\n\tsc := trace.NewSpanContext(trace.SpanContextConfig{SpanID: trace.SpanID{1}})\n\twant := \"0100000000000000\"\n\tfor i := 0; i < b.N; i++ {\n\t\tif got := sc.SpanID().String(); got != want {\n\t\t\tb.Fatalf(\"got = %q want = %q\", got, want)\n\t\t}\n\t}\n}\n\nfunc traceBenchmark(b *testing.B, name string, fn func(*testing.B, trace.Tracer)) {\n\tb.Run(\"AlwaysSample\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfn(b, tracer(b, name, sdktrace.AlwaysSample()))\n\t})\n\tb.Run(\"NeverSample\", func(b *testing.B) {\n\t\tb.ReportAllocs()\n\t\tfn(b, tracer(b, name, sdktrace.NeverSample()))\n\t})\n}\n\nfunc tracer(b *testing.B, name string, sampler sdktrace.Sampler) trace.Tracer {\n\ttp := sdktrace.NewTracerProvider(sdktrace.WithSampler(sampler))\n\treturn tp.Tracer(name)\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"encoding\/json\"\n\t\"time\"\n)\n\nconst (\n\tUNIT_BYTES = \"bytes\"\n\tUNIT_BYTES_PER_SECOND = \"bytes\/second\"\n\tUNIT_BITS = \"bits\"\n\tUNIT_BITS_PER_SECOND = \"bits\/second\"\n\tUNIT_SECONDS = \"seconds\"\n\tUNIT_COUNT = \"count\"\n\tUNIT_COUNT_PER_SECOND = \"count\/second\"\n\tUNIT_PERCENT = \"percent\"\n)\n\ntype Metric struct {\n\tName      string\n\tValue     float64\n\tUnit      string\n\tTimestamp time.Time\n\tMetadata  map[string]string\n}\n\n\/\/ Add metadata values to the metric if they do not already exist.\nfunc (m *Metric) Underlay(metadata map[string]string) {\n\tif m.Metadata == nil {\n\t\tm.Metadata = make(map[string]string, len(metadata))\n\t}\n\tfor key, value := range metadata {\n\t\tif _, ok := m.Metadata[key]; !ok {\n\t\t\tm.Metadata[key] = value\n\t\t}\n\t}\n}\n\n\/\/ A collection of metric values.\ntype Metrics struct {\n\tmetrics []*Metric\n}\n\nfunc (m *Metrics) MarshalJSON() ([]byte, error) {\n\tval, err := json.Marshal(m.metrics)\n\treturn val, err\n}\n\nfunc (m *Metrics) UnmarshalJSON(raw []byte) error {\n\terr := json.Unmarshal(raw, &m.metrics)\n\treturn err\n}\n\n\/\/ Add a single metric to the collection.\nfunc (m *Metrics) Add(name string, value float64, unit string, timestamp time.Time, metadata map[string]string) {\n\tm.metrics = append(m.metrics, &Metric{name, value, unit, timestamp, metadata})\n}\n\n\/\/ Append other metrics to this metrics struct.\nfunc (m *Metrics) Append(metrics Metrics) {\n\tm.metrics = append(m.metrics, metrics.metrics...)\n}\n\n\/\/ Retrieve the metrics as an array.\nfunc (m *Metrics) Items() []*Metric {\n\treturn m.metrics\n}\n\n<commit_msg>Add more units.<commit_after>package api\n\nimport (\n\t\"encoding\/json\"\n\t\"time\"\n)\n\nconst (\n\tUNIT_BYTES = \"bytes\"\n\tUNIT_KILOBYTES = \"kilobytes\"\n\tUNIT_MEGABYTES = \"megabytes\"\n\tUNIT_GIGABYTES = \"gigabytes\"\n\tUNIT_TERABYTES = \"terabytes\"\n\tUNIT_BYTES_PER_SECOND = \"bytes\/second\"\n\tUNIT_KILOBYTES_PER_SECOND = \"kilobytes\/second\"\n\tUNIT_MEGABYTES_PER_SECOND = \"megabytes\/second\"\n\tUNIT_GIGABYTES_PER_SECOND = \"gigabytes\/second\"\n\tUNIT_TERABYTES_PER_SECOND = \"terabytes\/second\"\n\tUNIT_BITS = \"bits\"\n\tUNIT_KILOBITS = \"kilobits\"\n\tUNIT_MEGABITS = \"megabits\"\n\tUNIT_GIGABITS = \"gigabits\"\n\tUNIT_TERABITS = \"terabits\"\n\tUNIT_BITS_PER_SECOND = \"bits\/second\"\n\tUNIT_KILOBITS_PER_SECOND = \"kilobits\/second\"\n\tUNIT_MEGABITS_PER_SECOND = \"megabits\/second\"\n\tUNIT_GIGABITS_PER_SECOND = \"gigabits\/second\"\n\tUNIT_TERABITS_PER_SECOND = \"terabits\/second\"\n\tUNIT_SECONDS = \"seconds\"\n\tUNIT_PERCENT = \"percent\"\n\tUNIT_COUNT = \"count\"\n\tUNIT_COUNT_PER_SECOND = \"count\/second\"\n)\n\ntype Metric struct {\n\tName      string\n\tValue     float64\n\tUnit      string\n\tTimestamp time.Time\n\tMetadata  map[string]string\n}\n\n\/\/ Add metadata values to the metric if they do not already exist.\nfunc (m *Metric) Underlay(metadata map[string]string) {\n\tif m.Metadata == nil {\n\t\tm.Metadata = make(map[string]string, len(metadata))\n\t}\n\tfor key, value := range metadata {\n\t\tif _, ok := m.Metadata[key]; !ok {\n\t\t\tm.Metadata[key] = value\n\t\t}\n\t}\n}\n\n\/\/ A collection of metric values.\ntype Metrics struct {\n\tmetrics []*Metric\n}\n\nfunc (m *Metrics) MarshalJSON() ([]byte, error) {\n\tval, err := json.Marshal(m.metrics)\n\treturn val, err\n}\n\nfunc (m *Metrics) UnmarshalJSON(raw []byte) error {\n\terr := json.Unmarshal(raw, &m.metrics)\n\treturn err\n}\n\n\/\/ Add a single metric to the collection.\nfunc (m *Metrics) Add(name string, value float64, unit string, timestamp time.Time, metadata map[string]string) {\n\tm.metrics = append(m.metrics, &Metric{name, value, unit, timestamp, metadata})\n}\n\n\/\/ Append other metrics to this metrics struct.\nfunc (m *Metrics) Append(metrics Metrics) {\n\tm.metrics = append(m.metrics, metrics.metrics...)\n}\n\n\/\/ Retrieve the metrics as an array.\nfunc (m *Metrics) Items() []*Metric {\n\treturn m.metrics\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 trivago GmbH\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage producer\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"github.com\/trivago\/gollum\/core\"\n\t\"github.com\/trivago\/gollum\/core\/log\"\n\t\"github.com\/trivago\/gollum\/shared\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\ntype spoolFile struct {\n\tfile        *os.File\n\tbatch       core.MessageBatch\n\tassembly    core.WriterAssembly\n\tfileCreated time.Time\n\tstreamName  string\n\tprod        *Spooling\n\tsource      core.MessageSource\n}\n\nconst maxSpoolFileNumber = 99999999 \/\/ maximum file number defined by %08d -> 8 digits\nconst spoolFileFormatString = \"%s\/%08d.spl\"\n\nfunc newSpoolFile(prod *Spooling, streamName string, source core.MessageSource) *spoolFile {\n\tspool := &spoolFile{\n\t\tfile:        nil,\n\t\tbatch:       core.NewMessageBatch(prod.batchMaxCount),\n\t\tassembly:    core.NewWriterAssembly(nil, prod.Drop, prod.GetFormatter()),\n\t\tfileCreated: time.Now(),\n\t\tstreamName:  streamName,\n\t\tprod:        prod,\n\t\tsource:      source,\n\t}\n\n\tshared.Metric.New(spoolingMetricName + streamName)\n\tshared.Metric.New(spooledMetricName + streamName)\n\tgo spool.read()\n\treturn spool\n}\n\nfunc (spool *spoolFile) flush() {\n\tspool.batch.Flush(spool.assembly.Write)\n}\n\nfunc (spool *spoolFile) close() {\n\tspool.batch.Flush(spool.assembly.Flush)\n\tspool.batch.WaitForFlush(spool.prod.GetShutdownTimeout())\n\tspool.file.Close()\n}\n\nfunc (spool *spoolFile) getFileNumbering(path string) (min int, max int) {\n\tmin, max = maxSpoolFileNumber+1, 0\n\tfiles, _ := ioutil.ReadDir(path)\n\tfor _, file := range files {\n\t\tbase := filepath.Base(file.Name())\n\t\tnumber, _ := shared.Btoi([]byte(base)) \/\/ Because we need leading zero support\n\t\tmin = shared.MinI(min, int(number))\n\t\tmax = shared.MaxI(max, int(number))\n\t}\n\treturn min, max\n}\n\nfunc (spool *spoolFile) openOrRotate() bool {\n\tfileSize := int64(0)\n\tif spool.file != nil {\n\t\tfileInfo, _ := spool.file.Stat()\n\t\tfileSize = fileInfo.Size()\n\t}\n\n\tif spool.file == nil || fileSize >= spool.prod.maxFileSize || time.Since(spool.fileCreated) > spool.prod.maxFileAge {\n\t\tpath := spool.prod.path + \"\/\" + spool.streamName\n\t\t_, maxSuffix := spool.getFileNumbering(path)\n\n\t\t\/\/ Reopen spooling file\n\t\tvar err error\n\t\toldFile := spool.file\n\t\tspoolFileName := fmt.Sprintf(spoolFileFormatString, path, maxSuffix+1)\n\t\tspool.file, err = os.OpenFile(spoolFileName, os.O_WRONLY|os.O_CREATE, 0600)\n\n\t\t\/\/ Close current file\n\t\tif oldFile != nil {\n\t\t\tspool.batch.WaitForFlush(time.Duration(0))\n\t\t\toldFile.Close()\n\t\t}\n\n\t\tspool.assembly.SetWriter(spool.file)\n\t\tspool.fileCreated = time.Now()\n\t\tif err != nil {\n\t\t\tLog.Error.Print(\"Spooling: \", err)\n\t\t\treturn false \/\/ ### return, could not open file ###\n\t\t}\n\t\tLog.Debug.Print(\"Spooler opened \", spoolFileName, \" for writing\")\n\t}\n\n\treturn true\n}\n\nfunc (spool *spoolFile) read() {\n\tspool.prod.AddWorker()\n\tdefer spool.prod.WorkerDone()\n\n\tpath := spool.prod.path + \"\/\" + spool.streamName\n\n\tfor spool.prod.IsActive() {\n\t\tminSuffix, _ := spool.getFileNumbering(path)\n\n\t\tspoolFileName := fmt.Sprintf(spoolFileFormatString, path, minSuffix)\n\t\tif minSuffix == 0 || minSuffix > maxSpoolFileNumber || (spool.file != nil && spool.file.Name() == spoolFileName) {\n\t\t\tif minSuffix > maxSpoolFileNumber {\n\t\t\t\tLog.Debug.Print(\"Spool read sleeps (no file)\")\n\t\t\t} else {\n\t\t\t\tLog.Debug.Printf(\"Spool read waits for %s\", spoolFileName)\n\t\t\t}\n\t\t\ttime.Sleep(spool.prod.maxFileAge \/ 2)\n\t\t\tcontinue \/\/ ### continue, try again ###\n\t\t}\n\n\t\tfile, err := os.OpenFile(spoolFileName, os.O_RDONLY, 0600)\n\t\tif err != nil {\n\t\t\tLog.Error.Print(\"Spool read open error \", err)\n\t\t\tcontinue \/\/ ### continue, try again ###\n\t\t}\n\n\t\tLog.Debug.Print(\"Spooler opened \", spoolFileName, \" for reading\")\n\t\treader := bufio.NewReader(file)\n\t\tfor {\n\t\t\t\/\/ Only spool back if target is not busy\n\t\t\tif spool.source != nil && spool.source.IsBlocked() {\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\tcontinue \/\/ ### contine, busy source ###\n\t\t\t}\n\n\t\t\t\/\/ Read one line (might require multiple reads)\n\t\t\tbuffer, isPartial, err := reader.ReadLine()\n\t\t\tfor isPartial && err == nil {\n\t\t\t\tvar appendix []byte\n\t\t\t\tappendix, isPartial, err = reader.ReadLine()\n\t\t\t\tbuffer = append(buffer, appendix...)\n\t\t\t}\n\t\t\t\/\/ Any error cancels the loop\n\t\t\tif err != nil {\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\tLog.Error.Print(\"Spool read error: \", err)\n\t\t\t\t}\n\t\t\t\tbreak \/\/ ### break, read error or EOF ###\n\t\t\t}\n\t\t\t\/\/ Deserialize from string\n\t\t\tmsg, err := core.DeserializeMessage(string(buffer))\n\t\t\tif err != nil {\n\t\t\t\tLog.Error.Print(\"Spool file read: \", err)\n\t\t\t} else {\n\t\t\t\tspool.prod.routeToOrigin(msg)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Close and remove file\n\t\tLog.Debug.Print(\"Spooler removes \", spoolFileName)\n\t\tfile.Close()\n\t\tos.Remove(spoolFileName)\n\t}\n}\n<commit_msg>[fix] Inner spooling loop exit condition<commit_after>\/\/ Copyright 2015 trivago GmbH\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage producer\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"github.com\/trivago\/gollum\/core\"\n\t\"github.com\/trivago\/gollum\/core\/log\"\n\t\"github.com\/trivago\/gollum\/shared\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\ntype spoolFile struct {\n\tfile        *os.File\n\tbatch       core.MessageBatch\n\tassembly    core.WriterAssembly\n\tfileCreated time.Time\n\tstreamName  string\n\tprod        *Spooling\n\tsource      core.MessageSource\n}\n\nconst maxSpoolFileNumber = 99999999 \/\/ maximum file number defined by %08d -> 8 digits\nconst spoolFileFormatString = \"%s\/%08d.spl\"\n\nfunc newSpoolFile(prod *Spooling, streamName string, source core.MessageSource) *spoolFile {\n\tspool := &spoolFile{\n\t\tfile:        nil,\n\t\tbatch:       core.NewMessageBatch(prod.batchMaxCount),\n\t\tassembly:    core.NewWriterAssembly(nil, prod.Drop, prod.GetFormatter()),\n\t\tfileCreated: time.Now(),\n\t\tstreamName:  streamName,\n\t\tprod:        prod,\n\t\tsource:      source,\n\t}\n\n\tshared.Metric.New(spoolingMetricName + streamName)\n\tshared.Metric.New(spooledMetricName + streamName)\n\tgo spool.read()\n\treturn spool\n}\n\nfunc (spool *spoolFile) flush() {\n\tspool.batch.Flush(spool.assembly.Write)\n}\n\nfunc (spool *spoolFile) close() {\n\tspool.batch.Flush(spool.assembly.Flush)\n\tspool.batch.WaitForFlush(spool.prod.GetShutdownTimeout())\n\tspool.file.Close()\n}\n\nfunc (spool *spoolFile) getFileNumbering(path string) (min int, max int) {\n\tmin, max = maxSpoolFileNumber+1, 0\n\tfiles, _ := ioutil.ReadDir(path)\n\tfor _, file := range files {\n\t\tbase := filepath.Base(file.Name())\n\t\tnumber, _ := shared.Btoi([]byte(base)) \/\/ Because we need leading zero support\n\t\tmin = shared.MinI(min, int(number))\n\t\tmax = shared.MaxI(max, int(number))\n\t}\n\treturn min, max\n}\n\nfunc (spool *spoolFile) openOrRotate() bool {\n\tfileSize := int64(0)\n\tif spool.file != nil {\n\t\tfileInfo, _ := spool.file.Stat()\n\t\tfileSize = fileInfo.Size()\n\t}\n\n\tif spool.file == nil || fileSize >= spool.prod.maxFileSize || time.Since(spool.fileCreated) > spool.prod.maxFileAge {\n\t\tpath := spool.prod.path + \"\/\" + spool.streamName\n\t\t_, maxSuffix := spool.getFileNumbering(path)\n\n\t\t\/\/ Reopen spooling file\n\t\tvar err error\n\t\toldFile := spool.file\n\t\tspoolFileName := fmt.Sprintf(spoolFileFormatString, path, maxSuffix+1)\n\t\tspool.file, err = os.OpenFile(spoolFileName, os.O_WRONLY|os.O_CREATE, 0600)\n\n\t\t\/\/ Close current file\n\t\tif oldFile != nil {\n\t\t\tspool.batch.WaitForFlush(time.Duration(0))\n\t\t\toldFile.Close()\n\t\t}\n\n\t\tspool.assembly.SetWriter(spool.file)\n\t\tspool.fileCreated = time.Now()\n\t\tif err != nil {\n\t\t\tLog.Error.Print(\"Spooling: \", err)\n\t\t\treturn false \/\/ ### return, could not open file ###\n\t\t}\n\t\tLog.Debug.Print(\"Spooler opened \", spoolFileName, \" for writing\")\n\t}\n\n\treturn true\n}\n\nfunc (spool *spoolFile) read() {\n\tspool.prod.AddWorker()\n\tdefer spool.prod.WorkerDone()\n\n\tpath := spool.prod.path + \"\/\" + spool.streamName\n\n\tfor spool.prod.IsActive() {\n\t\tminSuffix, _ := spool.getFileNumbering(path)\n\n\t\tspoolFileName := fmt.Sprintf(spoolFileFormatString, path, minSuffix)\n\t\tif minSuffix == 0 || minSuffix > maxSpoolFileNumber || (spool.file != nil && spool.file.Name() == spoolFileName) {\n\t\t\tif minSuffix > maxSpoolFileNumber {\n\t\t\t\tLog.Debug.Print(\"Spool read sleeps (no file)\")\n\t\t\t} else {\n\t\t\t\tLog.Debug.Printf(\"Spool read waits for %s\", spoolFileName)\n\t\t\t}\n\t\t\ttime.Sleep(spool.prod.maxFileAge \/ 2)\n\t\t\tcontinue \/\/ ### continue, try again ###\n\t\t}\n\n\t\tfile, err := os.OpenFile(spoolFileName, os.O_RDONLY, 0600)\n\t\tif err != nil {\n\t\t\tLog.Error.Print(\"Spool read open error \", err)\n\t\t\tcontinue \/\/ ### continue, try again ###\n\t\t}\n\n\t\tLog.Debug.Print(\"Spooler opened \", spoolFileName, \" for reading\")\n\t\treader := bufio.NewReader(file)\n\n\t\tfor spool.prod.IsActive() {\n\t\t\t\/\/ Only spool back if target is not busy\n\t\t\tif spool.source != nil && spool.source.IsBlocked() {\n\t\t\t\tLog.Debug.Print(\"Spool read sleeps on inactive source\")\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\tcontinue \/\/ ### contine, busy source ###\n\t\t\t}\n\n\t\t\t\/\/ Read one line (might require multiple reads)\n\t\t\tbuffer, isPartial, err := reader.ReadLine()\n\t\t\tfor isPartial && err == nil {\n\t\t\t\tvar appendix []byte\n\t\t\t\tappendix, isPartial, err = reader.ReadLine()\n\t\t\t\tbuffer = append(buffer, appendix...)\n\t\t\t}\n\t\t\t\/\/ Any error cancels the loop\n\t\t\tif err != nil {\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\tLog.Error.Print(\"Spool read error: \", err)\n\t\t\t\t}\n\t\t\t\tbreak \/\/ ### break, read error or EOF ###\n\t\t\t}\n\t\t\t\/\/ Deserialize from string\n\t\t\tmsg, err := core.DeserializeMessage(string(buffer))\n\t\t\tif err != nil {\n\t\t\t\tLog.Error.Print(\"Spool file read: \", err)\n\t\t\t} else {\n\t\t\t\tspool.prod.routeToOrigin(msg)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Close and remove file\n\t\tLog.Debug.Print(\"Spooler removes \", spoolFileName)\n\t\tfile.Close()\n\t\tos.Remove(spoolFileName)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package janus\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/etcinit\/speedbump\"\n\t\"github.com\/hellofresh\/ginger-middleware\/mongodb\"\n\t\"github.com\/urfave\/negroni\"\n\t\"gopkg.in\/alexcesaro\/statsd.v2\"\n\t\"gopkg.in\/redis.v3\"\n)\n\nvar APILoader = APIDefinitionLoader{}\n\ntype APIManager struct {\n\tproxyRegister *ProxyRegister\n\tredisClient   *redis.Client\n\taccessor      *mongodb.DatabaseAccessor\n}\n\n\/\/ NewAPIManager creates a new instance of the api manager\nfunc NewAPIManager(router Router, redisClient *redis.Client, accessor *mongodb.DatabaseAccessor, statsdClient *statsd.Client) *APIManager {\n\tproxyRegister := &ProxyRegister{Router: router, statsdClient: statsdClient}\n\treturn &APIManager{proxyRegister, redisClient, accessor}\n}\n\n\/\/ Load loads all api specs from a datasource\nfunc (m *APIManager) Load() {\n\toauthManager := &OAuthManager{m.redisClient}\n\n\toAuthServers := m.getOAuthServers()\n\tgo m.LoadOAuthServers(oAuthServers, oauthManager)\n\n\tspecs := m.getAPISpecs()\n\tgo m.LoadApps(specs, oauthManager)\n}\n\n\/\/ LoadApps load application middleware\nfunc (m *APIManager) LoadApps(apiSpecs []*APISpec, oauthManager *OAuthManager) {\n\tlog.Debug(\"Loading API configurations\")\n\n\tfor _, referenceSpec := range apiSpecs {\n\t\tvar skip bool\n\n\t\t\/\/Validates the proxy\n\t\tskip = validateProxy(referenceSpec.Proxy)\n\t\tif false == referenceSpec.Active {\n\t\t\tlog.Debug(\"API is not active, skiping...\")\n\t\t\tskip = false\n\t\t}\n\n\t\tif skip {\n\t\t\thasher := speedbump.PerSecondHasher{}\n\t\t\tlimit := referenceSpec.RateLimit.Limit\n\t\t\tlimiter := speedbump.NewLimiter(m.redisClient, hasher, limit)\n\n\t\t\tmw := &Middleware{referenceSpec}\n\t\t\tvar beforeHandlers = []negroni.HandlerFunc{\n\t\t\t\tCreateMiddleware(&RateLimitMiddleware{mw, limiter, hasher, limit}),\n\t\t\t\tCreateMiddleware(&CorsMiddleware{mw}),\n\t\t\t}\n\n\t\t\tif referenceSpec.UseOauth2 {\n\t\t\t\tbeforeHandlers = append(beforeHandlers, CreateMiddleware(&Oauth2KeyExists{mw, oauthManager}))\n\t\t\t}\n\n\t\t\tm.proxyRegister.Register(referenceSpec.Proxy, beforeHandlers, nil)\n\t\t\tlog.Debug(\"Proxy registered\")\n\t\t} else {\n\t\t\tlog.Error(\"Listen path is empty, skipping...\")\n\t\t}\n\t}\n}\n\n\/\/ LoadOAuthServers loads and register the oauth servers\nfunc (m *APIManager) LoadOAuthServers(oauthServers []*OAuthSpec, oauthManager *OAuthManager) {\n\tlog.Debug(\"Loading OAuth servers configurations\")\n\n\tvar beforeHandlers []negroni.HandlerFunc\n\tvar handlers []negroni.HandlerFunc\n\toauthRegister := &OAuthRegister{}\n\n\tfor _, oauthServer := range oauthServers {\n\t\tbeforeHandlers = append(beforeHandlers, CreateMiddleware(&Oauth2Secret{oauthServer}))\n\t\thandlers = append(handlers, CreateMiddleware(&OAuthMiddleware{oauthManager, oauthServer}))\n\t\toauthServer.OAuthManager = &OAuthManager{m.redisClient}\n\t\tproxies := oauthRegister.GetProxiesForServer(oauthServer.OAuth)\n\t\tm.proxyRegister.RegisterMany(proxies, beforeHandlers, handlers)\n\t}\n\n\tlog.Debug(\"Done loading OAuth servers configurations\")\n}\n\n\/\/getAPISpecs Load application specs from datasource\nfunc (m *APIManager) getAPISpecs() []*APISpec {\n\tlog.Debug(\"Using App Configuration from Mongo DB\")\n\treturn APILoader.LoadDefinitionsFromDatastore(m.accessor.Session)\n}\n\n\/\/getOAuthServers Load oauth servers from datasource\nfunc (m *APIManager) getOAuthServers() []*OAuthSpec {\n\tlog.Debug(\"Using Oauth servers configuration from Mongo DB\")\n\treturn APILoader.LoadOauthServersFromDatastore(m.accessor.Session)\n}\n<commit_msg>Rename middlewares in api manager<commit_after>package janus\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/etcinit\/speedbump\"\n\t\"github.com\/hellofresh\/ginger-middleware\/mongodb\"\n\t\"github.com\/urfave\/negroni\"\n\t\"gopkg.in\/alexcesaro\/statsd.v2\"\n\t\"gopkg.in\/redis.v3\"\n)\n\nvar APILoader = APIDefinitionLoader{}\n\ntype APIManager struct {\n\tproxyRegister *ProxyRegister\n\tredisClient   *redis.Client\n\taccessor      *mongodb.DatabaseAccessor\n}\n\n\/\/ NewAPIManager creates a new instance of the api manager\nfunc NewAPIManager(router Router, redisClient *redis.Client, accessor *mongodb.DatabaseAccessor, statsdClient *statsd.Client) *APIManager {\n\tproxyRegister := &ProxyRegister{Router: router, statsdClient: statsdClient}\n\treturn &APIManager{proxyRegister, redisClient, accessor}\n}\n\n\/\/ Load loads all api specs from a datasource\nfunc (m *APIManager) Load() {\n\toauthManager := &OAuthManager{m.redisClient}\n\n\toAuthServers := m.getOAuthServers()\n\tgo m.LoadOAuthServers(oAuthServers, oauthManager)\n\n\tspecs := m.getAPISpecs()\n\tgo m.LoadApps(specs, oauthManager)\n}\n\n\/\/ LoadApps load application middleware\nfunc (m *APIManager) LoadApps(apiSpecs []*APISpec, oauthManager *OAuthManager) {\n\tlog.Debug(\"Loading API configurations\")\n\n\tfor _, referenceSpec := range apiSpecs {\n\t\tvar skip bool\n\n\t\t\/\/Validates the proxy\n\t\tskip = validateProxy(referenceSpec.Proxy)\n\t\tif false == referenceSpec.Active {\n\t\t\tlog.Debug(\"API is not active, skiping...\")\n\t\t\tskip = false\n\t\t}\n\n\t\tif skip {\n\t\t\thasher := speedbump.PerSecondHasher{}\n\t\t\tlimit := referenceSpec.RateLimit.Limit\n\t\t\tlimiter := speedbump.NewLimiter(m.redisClient, hasher, limit)\n\n\t\t\tmw := &Middleware{referenceSpec}\n\t\t\tvar beforeHandlers = []negroni.HandlerFunc{\n\t\t\t\tCreateMiddleware(&RateLimitMiddleware{mw, limiter, hasher, limit}),\n\t\t\t\tCreateMiddleware(&CorsMiddleware{mw}),\n\t\t\t}\n\n\t\t\tif referenceSpec.UseOauth2 {\n\t\t\t\tbeforeHandlers = append(beforeHandlers, CreateMiddleware(&Oauth2KeyExistsMiddleware{mw, oauthManager}))\n\t\t\t}\n\n\t\t\tm.proxyRegister.Register(referenceSpec.Proxy, beforeHandlers, nil)\n\t\t\tlog.Debug(\"Proxy registered\")\n\t\t} else {\n\t\t\tlog.Error(\"Listen path is empty, skipping...\")\n\t\t}\n\t}\n}\n\n\/\/ LoadOAuthServers loads and register the oauth servers\nfunc (m *APIManager) LoadOAuthServers(oauthServers []*OAuthSpec, oauthManager *OAuthManager) {\n\tlog.Debug(\"Loading OAuth servers configurations\")\n\n\tvar beforeHandlers []negroni.HandlerFunc\n\tvar handlers []negroni.HandlerFunc\n\toauthRegister := &OAuthRegister{}\n\n\tfor _, oauthServer := range oauthServers {\n\t\tbeforeHandlers = append(beforeHandlers, CreateMiddleware(&Oauth2SecretMiddleware{oauthServer}))\n\t\thandlers = append(handlers, CreateMiddleware(&OAuthMiddleware{oauthManager, oauthServer}))\n\t\toauthServer.OAuthManager = &OAuthManager{m.redisClient}\n\t\tproxies := oauthRegister.GetProxiesForServer(oauthServer.OAuth)\n\t\tm.proxyRegister.RegisterMany(proxies, beforeHandlers, handlers)\n\t}\n\n\tlog.Debug(\"Done loading OAuth servers configurations\")\n}\n\n\/\/getAPISpecs Load application specs from datasource\nfunc (m *APIManager) getAPISpecs() []*APISpec {\n\tlog.Debug(\"Using App Configuration from Mongo DB\")\n\treturn APILoader.LoadDefinitionsFromDatastore(m.accessor.Session)\n}\n\n\/\/getOAuthServers Load oauth servers from datasource\nfunc (m *APIManager) getOAuthServers() []*OAuthSpec {\n\tlog.Debug(\"Using Oauth servers configuration from Mongo DB\")\n\treturn APILoader.LoadOauthServersFromDatastore(m.accessor.Session)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ISO\/IEC 2000 APL Required Character Set\n\/\/ see also \/usr\/share\/X11\/xkb\/symbols\/apl\npackage main\n\nimport \"fmt\"\n\nvar charmap = map[rune]string{\n\t'⍺': \"alpha\",\n\t'↓': \"down arrow\",\n\t'←': \"left arrow\",\n\t'→': \"right arrow\",\n\t'↑': \"up arrow\",\n\t'-': \"bar\",\n\t' ': \"blank\",\n\t'{': \"left brace\",\n\t'}': \"right brace\",\n\t'[': \"left bracket\",\n\t']': \"right bracket\",\n\t'∨': \"down caret\",\n\t'⍱': \"down caret tilde\",\n\t'<': \"left caret\",\n\t'>': \"right caret\",\n\t'∧': \"up caret\",\n\t'⍲': \"up caret tilde\",\n\t'○': \"circle\",\n\t'⍉': \"circle backslash\",\n\t'⊖': \"circle bar\",\n\t'⍟': \"circle star\",\n\t'⌽': \"circle stile\",\n\t':': \"colon\",\n\t',': \"comma\",\n\t'⍪': \"comma bar\",\n\t'∇': \"del\",\n\t'⍒': \"del stile\",\n\t'⍫': \"del tilde\",\n\t'∆': \"delta\",\n\t'⍋': \"delta stile\",\n\t'⍙': \"delta underbar\",\n\t'¨': \"diaeresis\",\n\t'⋄': \"diamond\",\n\t'÷': \"divide\",\n\t'$': \"dollar sign\",\n\t'.': \"dot\",\n\t'∊': \"epsion\",\n\t'=': \"equal\",\n\t'≥': \"greater-than or equal\",\n\t'⍳': \"iota\",\n\t'∘': \"jot\",\n\t'≤': \"less-than or equal\",\n\t'×': \"miltiply\",\n\t'≠': \"not equal\",\n\t'¯': \"overbar\",\n\t'(': \"left parenthesis\",\n\t')': \"right parenthesis\",\n\t'+': \"plus\",\n\t'⎕': \"quad\",\n\t'⌹': \"quad divide\",\n\t'?': \"query\",\n\t'⍤': \"diaeresis jot\",\n\t'\\'': \"quote\",\n\t'!': \"quote dot\",\n\t'⍞': \"quate quad\",\n\t'⍴': \"rho\",\n\t';': \"semicolon\",\n\t'∪': \"down shoe\",\n\t'⊂': \"left shoe\",\n\t'⊃': \"right shoe\",\n\t'∩': \"up shoe\",\n\t'⍝': \"up shoe jot\",\n\t'\/': \"slash\",\n\t'\\\\': \"back slash\",\n\t'⌿': \"slash bar\",\n\t'⍀': \"back slash bar\",\n\t'*': \"star\",\n\t'|': \"stile\",\n\t'⌊': \"down stile\",\n\t'⌈': \"up stile\",\n\t'⊥': \"up tack\",\n\t'⍎': \"up tack jot\",\n\t'⊢': \"right tack\",\n\t'⊣': \"left tack\",\n\t'⊤': \"down tack\",\n\t'⍕': \"down tack jot\",\n\t'~': \"tilde\",\n\t'_': \"underbar\",\n\t'⍨': \"diaeresis tilde\",\n\t'⍵': \"omega\",\n\t'≡': \"equal underbar\",\n}\n\nfunc scan(chars string) {\n\tfor _, c := range chars {\n\t\tif name, ok := charmap[c]; ok {\n\t\t\tfmt.Println(string(c), name)\n\t\t} else {\n\t\t\tfmt.Println(string(c), \"... missing\")\n\t\t}\n\t}\n}\n\nfunc main() {\n\tscan(\"⋄⌶⍫⍒⍋⌽⍉⊖⍟⍱⍲!⌹?⍵⍷⍴⍨↑↓⍸⍥⍣⍞⍬⍺⌈⌊_∇∆⍤'⌷≡≢⊣⍕⊂⊃∩∪⊥⊤|⍪⍙⍠\")\n\tscan(\"⋄¨¯<≤=≥>≠∨∧×÷?⍵∊⍴~↑↓⍳○*←→⍺⌈⌊_∇∆∘'⎕⍎⍕⊢⍎⊂⊃∩∪⊥⊤|⍝⍀⌿\")\n}\n<commit_msg>gofmt<commit_after>\/\/ ISO\/IEC 2000 APL Required Character Set\n\/\/ see also \/usr\/share\/X11\/xkb\/symbols\/apl\npackage main\n\nimport \"fmt\"\n\nvar charmap = map[rune]string{\n\t'⍺':  \"alpha\",\n\t'↓':  \"down arrow\",\n\t'←':  \"left arrow\",\n\t'→':  \"right arrow\",\n\t'↑':  \"up arrow\",\n\t'-':  \"bar\",\n\t' ':  \"blank\",\n\t'{':  \"left brace\",\n\t'}':  \"right brace\",\n\t'[':  \"left bracket\",\n\t']':  \"right bracket\",\n\t'∨':  \"down caret\",\n\t'⍱':  \"down caret tilde\",\n\t'<':  \"left caret\",\n\t'>':  \"right caret\",\n\t'∧':  \"up caret\",\n\t'⍲':  \"up caret tilde\",\n\t'○':  \"circle\",\n\t'⍉':  \"circle backslash\",\n\t'⊖':  \"circle bar\",\n\t'⍟':  \"circle star\",\n\t'⌽':  \"circle stile\",\n\t':':  \"colon\",\n\t',':  \"comma\",\n\t'⍪':  \"comma bar\",\n\t'∇':  \"del\",\n\t'⍒':  \"del stile\",\n\t'⍫':  \"del tilde\",\n\t'∆':  \"delta\",\n\t'⍋':  \"delta stile\",\n\t'⍙':  \"delta underbar\",\n\t'¨':  \"diaeresis\",\n\t'⋄':  \"diamond\",\n\t'÷':  \"divide\",\n\t'$':  \"dollar sign\",\n\t'.':  \"dot\",\n\t'∊':  \"epsion\",\n\t'=':  \"equal\",\n\t'≥':  \"greater-than or equal\",\n\t'⍳':  \"iota\",\n\t'∘':  \"jot\",\n\t'≤':  \"less-than or equal\",\n\t'×':  \"miltiply\",\n\t'≠':  \"not equal\",\n\t'¯':  \"overbar\",\n\t'(':  \"left parenthesis\",\n\t')':  \"right parenthesis\",\n\t'+':  \"plus\",\n\t'⎕':  \"quad\",\n\t'⌹':  \"quad divide\",\n\t'?':  \"query\",\n\t'⍤':  \"diaeresis jot\",\n\t'\\'': \"quote\",\n\t'!':  \"quote dot\",\n\t'⍞':  \"quate quad\",\n\t'⍴':  \"rho\",\n\t';':  \"semicolon\",\n\t'∪':  \"down shoe\",\n\t'⊂':  \"left shoe\",\n\t'⊃':  \"right shoe\",\n\t'∩':  \"up shoe\",\n\t'⍝':  \"up shoe jot\",\n\t'\/':  \"slash\",\n\t'\\\\': \"back slash\",\n\t'⌿':  \"slash bar\",\n\t'⍀':  \"back slash bar\",\n\t'*':  \"star\",\n\t'|':  \"stile\",\n\t'⌊':  \"down stile\",\n\t'⌈':  \"up stile\",\n\t'⊥':  \"up tack\",\n\t'⍎':  \"up tack jot\",\n\t'⊢':  \"right tack\",\n\t'⊣':  \"left tack\",\n\t'⊤':  \"down tack\",\n\t'⍕':  \"down tack jot\",\n\t'~':  \"tilde\",\n\t'_':  \"underbar\",\n\t'⍨':  \"diaeresis tilde\",\n\t'⍵':  \"omega\",\n\t'≡':  \"equal underbar\",\n}\n\nfunc scan(chars string) {\n\tfor _, c := range chars {\n\t\tif name, ok := charmap[c]; ok {\n\t\t\tfmt.Println(string(c), name)\n\t\t} else {\n\t\t\tfmt.Println(string(c), \"... missing\")\n\t\t}\n\t}\n}\n\nfunc main() {\n\tscan(\"⋄⌶⍫⍒⍋⌽⍉⊖⍟⍱⍲!⌹?⍵⍷⍴⍨↑↓⍸⍥⍣⍞⍬⍺⌈⌊_∇∆⍤'⌷≡≢⊣⍕⊂⊃∩∪⊥⊤|⍪⍙⍠\")\n\tscan(\"⋄¨¯<≤=≥>≠∨∧×÷?⍵∊⍴~↑↓⍳○*←→⍺⌈⌊_∇∆∘'⎕⍎⍕⊢⍎⊂⊃∩∪⊥⊤|⍝⍀⌿\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build !race\n\npackage command\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/hashicorp\/vault\/vault\/diagnose\"\n\t\"github.com\/mitchellh\/cli\"\n)\n\nfunc testOperatorDiagnoseCommand(tb testing.TB) *OperatorDiagnoseCommand {\n\ttb.Helper()\n\n\tui := cli.NewMockUi()\n\treturn &OperatorDiagnoseCommand{\n\t\tdiagnose: diagnose.New(ioutil.Discard),\n\t\tBaseCommand: &BaseCommand{\n\t\t\tUI: ui,\n\t\t},\n\t\tskipEndEnd: true,\n\t}\n}\n\nfunc TestOperatorDiagnoseCommand_Run(t *testing.T) {\n\tt.Parallel()\n\tcases := []struct {\n\t\tname     string\n\t\targs     []string\n\t\texpected []*diagnose.Result\n\t}{\n\t\t{\n\t\t\t\"diagnose_ok\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/config_diagnose_ok.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:   \"operating system\",\n\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"open file limits\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"disk usage\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\n\t\t\t\t{\n\t\t\t\t\tName:   \"parse-config\",\n\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:   \"init-listeners\",\n\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-listeners\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"check-listener-tls\",\n\t\t\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\t\t\tWarnings: []string{\n\t\t\t\t\t\t\t\t\"TLS is disabled in a Listener config stanza.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:   \"storage\",\n\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-storage-backend\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-storage-tls-consul\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-consul-direct-access-storage\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"diagnose_invalid_storage\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/nostore_config.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:    \"storage\",\n\t\t\t\t\tStatus:  diagnose.ErrorStatus,\n\t\t\t\t\tMessage: \"no storage stanza found in config\",\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-storage-backend\",\n\t\t\t\t\t\t\tStatus: diagnose.ErrorStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"diagnose_listener_config_ok\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/tls_config_ok.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:   \"init-listeners\",\n\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-listeners\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"check-listener-tls\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"diagnose_invalid_https_storage\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/config_bad_https_storage.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:   \"storage\",\n\t\t\t\t\tStatus: diagnose.ErrorStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-storage-backend\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:    \"test-storage-tls-consul\",\n\t\t\t\t\t\t\tStatus:  diagnose.ErrorStatus,\n\t\t\t\t\t\t\tMessage: \"expired\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-consul-direct-access-storage\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"diagnose_invalid_https_hastorage\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/config_diagnose_hastorage_bad_https.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:   \"storage\",\n\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-storage-backend\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-storage-tls-consul\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-consul-direct-access-storage\",\n\t\t\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\t\t\tWarnings: []string{\n\t\t\t\t\t\t\t\t\"consul storage does not connect to local agent, but directly to server\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:   \"setup-ha-storage\",\n\t\t\t\t\tStatus: diagnose.ErrorStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-ha-storage-backend\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-consul-direct-access-storage\",\n\t\t\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\t\t\tWarnings: []string{\n\t\t\t\t\t\t\t\t\"consul storage does not connect to local agent, but directly to server\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:    \"test-ha-storage-tls-consul\",\n\t\t\t\t\t\t\tStatus:  diagnose.ErrorStatus,\n\t\t\t\t\t\t\tMessage: \"x509: certificate has expired or is not yet valid\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:   \"find-cluster-addr\",\n\t\t\t\t\tStatus: diagnose.ErrorStatus,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"diagnose_invalid_https_sr\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/diagnose_bad_https_consul_sr.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:   \"service-discovery\",\n\t\t\t\t\tStatus: diagnose.ErrorStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:    \"test-serviceregistration-tls-consul\",\n\t\t\t\t\t\t\tStatus:  diagnose.ErrorStatus,\n\t\t\t\t\t\t\tMessage: \"failed to verify certificate: x509: certificate has expired or is not yet valid\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-consul-direct-access-service-discovery\",\n\t\t\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\t\t\tWarnings: []string{\n\t\t\t\t\t\t\t\tdiagnose.DirAccessErr,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"diagnose_direct_storage_access\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/diagnose_ok_storage_direct_access.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:   \"storage\",\n\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-storage-backend\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-storage-tls-consul\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-consul-direct-access-storage\",\n\t\t\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\t\t\tWarnings: []string{\n\t\t\t\t\t\t\t\tdiagnose.DirAccessErr,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tt.Run(\"validations\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tfor _, tc := range cases {\n\t\t\ttc := tc\n\t\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t\tt.Parallel()\n\t\t\t\tclient, closer := testVaultServer(t)\n\t\t\t\tdefer closer()\n\n\t\t\t\tcmd := testOperatorDiagnoseCommand(t)\n\t\t\t\tcmd.client = client\n\n\t\t\t\tcmd.Run(tc.args)\n\t\t\t\tresult := cmd.diagnose.Finalize(context.Background())\n\n\t\t\t\tif err := compareResults(tc.expected, result.Children); err != nil {\n\t\t\t\t\tt.Fatalf(\"Did not find expected test results: %v\", err)\n\t\t\t\t\tt.Fatal(result.String())\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})\n}\n\nfunc compareResults(expected []*diagnose.Result, actual []*diagnose.Result) error {\n\tfor _, exp := range expected {\n\t\tfound := false\n\t\t\/\/ Check them all so we don't have to be order specific\n\t\tfor _, act := range actual {\n\t\t\tif exp.Name == act.Name {\n\t\t\t\tfound = true\n\t\t\t\tif err := compareResult(exp, act); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\treturn fmt.Errorf(\"could not find expected test result: %s\", exp.Name)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc compareResult(exp *diagnose.Result, act *diagnose.Result) error {\n\tif exp.Name != act.Name {\n\t\treturn fmt.Errorf(\"names mismatch: %s vs %s\", exp.Name, act.Name)\n\t}\n\tif exp.Status != act.Status {\n\t\tif act.Status != diagnose.OkStatus {\n\t\t\treturn fmt.Errorf(\"section %s, status mismatch: %s vs %s, got error %s\", exp.Name, exp.Status, act.Status, act.Message)\n\n\t\t}\n\t\treturn fmt.Errorf(\"section %s, status mismatch: %s vs %s\", exp.Name, exp.Status, act.Status)\n\t}\n\tif exp.Message != \"\" && exp.Message != act.Message && !strings.Contains(act.Message, exp.Message) {\n\t\treturn fmt.Errorf(\"section %s, message not found: %s in %s\", exp.Name, exp.Message, act.Message)\n\t}\n\tif len(exp.Warnings) != len(act.Warnings) {\n\t\treturn fmt.Errorf(\"section %s, warning count mismatch: %d vs %d\", exp.Name, len(exp.Warnings), len(act.Warnings))\n\t}\n\tfor j := range exp.Warnings {\n\t\tif !strings.Contains(act.Warnings[j], exp.Warnings[j]) {\n\t\t\treturn fmt.Errorf(\"section %s, warning message not found: %s in %s\", exp.Name, exp.Warnings[j], act.Warnings[j])\n\t\t}\n\t}\n\tif len(exp.Children) > len(act.Children) {\n\t\terrStrings := []string{}\n\t\tfor _, c := range act.Children {\n\t\t\terrStrings = append(errStrings, fmt.Sprintf(\"%+v\", c))\n\t\t}\n\t\treturn fmt.Errorf(strings.Join(errStrings, \",\"))\n\t}\n\n\tif len(exp.Children) > 0 {\n\t\treturn compareResults(exp.Children, act.Children)\n\t}\n\n\tif len(exp.Children) > 0 {\n\t\treturn compareResults(exp.Children, act.Children)\n\t}\n\treturn nil\n}\n<commit_msg>Remove duplicate children test (#11751)<commit_after>\/\/ +build !race\n\npackage command\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/hashicorp\/vault\/vault\/diagnose\"\n\t\"github.com\/mitchellh\/cli\"\n)\n\nfunc testOperatorDiagnoseCommand(tb testing.TB) *OperatorDiagnoseCommand {\n\ttb.Helper()\n\n\tui := cli.NewMockUi()\n\treturn &OperatorDiagnoseCommand{\n\t\tdiagnose: diagnose.New(ioutil.Discard),\n\t\tBaseCommand: &BaseCommand{\n\t\t\tUI: ui,\n\t\t},\n\t\tskipEndEnd: true,\n\t}\n}\n\nfunc TestOperatorDiagnoseCommand_Run(t *testing.T) {\n\tt.Parallel()\n\tcases := []struct {\n\t\tname     string\n\t\targs     []string\n\t\texpected []*diagnose.Result\n\t}{\n\t\t{\n\t\t\t\"diagnose_ok\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/config_diagnose_ok.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:   \"operating system\",\n\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"open file limits\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"disk usage\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\n\t\t\t\t{\n\t\t\t\t\tName:   \"parse-config\",\n\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:   \"init-listeners\",\n\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-listeners\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"check-listener-tls\",\n\t\t\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\t\t\tWarnings: []string{\n\t\t\t\t\t\t\t\t\"TLS is disabled in a Listener config stanza.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:   \"storage\",\n\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-storage-backend\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-storage-tls-consul\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-consul-direct-access-storage\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"diagnose_invalid_storage\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/nostore_config.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:    \"storage\",\n\t\t\t\t\tStatus:  diagnose.ErrorStatus,\n\t\t\t\t\tMessage: \"no storage stanza found in config\",\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-storage-backend\",\n\t\t\t\t\t\t\tStatus: diagnose.ErrorStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"diagnose_listener_config_ok\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/tls_config_ok.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:   \"init-listeners\",\n\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-listeners\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"check-listener-tls\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"diagnose_invalid_https_storage\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/config_bad_https_storage.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:   \"storage\",\n\t\t\t\t\tStatus: diagnose.ErrorStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-storage-backend\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:    \"test-storage-tls-consul\",\n\t\t\t\t\t\t\tStatus:  diagnose.ErrorStatus,\n\t\t\t\t\t\t\tMessage: \"expired\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-consul-direct-access-storage\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"diagnose_invalid_https_hastorage\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/config_diagnose_hastorage_bad_https.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:   \"storage\",\n\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-storage-backend\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-storage-tls-consul\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-consul-direct-access-storage\",\n\t\t\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\t\t\tWarnings: []string{\n\t\t\t\t\t\t\t\t\"consul storage does not connect to local agent, but directly to server\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:   \"setup-ha-storage\",\n\t\t\t\t\tStatus: diagnose.ErrorStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-ha-storage-backend\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-consul-direct-access-storage\",\n\t\t\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\t\t\tWarnings: []string{\n\t\t\t\t\t\t\t\t\"consul storage does not connect to local agent, but directly to server\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:    \"test-ha-storage-tls-consul\",\n\t\t\t\t\t\t\tStatus:  diagnose.ErrorStatus,\n\t\t\t\t\t\t\tMessage: \"x509: certificate has expired or is not yet valid\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:   \"find-cluster-addr\",\n\t\t\t\t\tStatus: diagnose.ErrorStatus,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"diagnose_invalid_https_sr\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/diagnose_bad_https_consul_sr.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:   \"service-discovery\",\n\t\t\t\t\tStatus: diagnose.ErrorStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:    \"test-serviceregistration-tls-consul\",\n\t\t\t\t\t\t\tStatus:  diagnose.ErrorStatus,\n\t\t\t\t\t\t\tMessage: \"failed to verify certificate: x509: certificate has expired or is not yet valid\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-consul-direct-access-service-discovery\",\n\t\t\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\t\t\tWarnings: []string{\n\t\t\t\t\t\t\t\tdiagnose.DirAccessErr,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\"diagnose_direct_storage_access\",\n\t\t\t[]string{\n\t\t\t\t\"-config\", \".\/server\/test-fixtures\/diagnose_ok_storage_direct_access.hcl\",\n\t\t\t},\n\t\t\t[]*diagnose.Result{\n\t\t\t\t{\n\t\t\t\t\tName:   \"storage\",\n\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\tChildren: []*diagnose.Result{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"create-storage-backend\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-storage-tls-consul\",\n\t\t\t\t\t\t\tStatus: diagnose.OkStatus,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:   \"test-consul-direct-access-storage\",\n\t\t\t\t\t\t\tStatus: diagnose.WarningStatus,\n\t\t\t\t\t\t\tWarnings: []string{\n\t\t\t\t\t\t\t\tdiagnose.DirAccessErr,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tt.Run(\"validations\", func(t *testing.T) {\n\t\tt.Parallel()\n\n\t\tfor _, tc := range cases {\n\t\t\ttc := tc\n\t\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t\tt.Parallel()\n\t\t\t\tclient, closer := testVaultServer(t)\n\t\t\t\tdefer closer()\n\n\t\t\t\tcmd := testOperatorDiagnoseCommand(t)\n\t\t\t\tcmd.client = client\n\n\t\t\t\tcmd.Run(tc.args)\n\t\t\t\tresult := cmd.diagnose.Finalize(context.Background())\n\n\t\t\t\tif err := compareResults(tc.expected, result.Children); err != nil {\n\t\t\t\t\tt.Fatalf(\"Did not find expected test results: %v\", err)\n\t\t\t\t\tt.Fatal(result.String())\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})\n}\n\nfunc compareResults(expected []*diagnose.Result, actual []*diagnose.Result) error {\n\tfor _, exp := range expected {\n\t\tfound := false\n\t\t\/\/ Check them all so we don't have to be order specific\n\t\tfor _, act := range actual {\n\t\t\tif exp.Name == act.Name {\n\t\t\t\tfound = true\n\t\t\t\tif err := compareResult(exp, act); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\treturn fmt.Errorf(\"could not find expected test result: %s\", exp.Name)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc compareResult(exp *diagnose.Result, act *diagnose.Result) error {\n\tif exp.Name != act.Name {\n\t\treturn fmt.Errorf(\"names mismatch: %s vs %s\", exp.Name, act.Name)\n\t}\n\tif exp.Status != act.Status {\n\t\tif act.Status != diagnose.OkStatus {\n\t\t\treturn fmt.Errorf(\"section %s, status mismatch: %s vs %s, got error %s\", exp.Name, exp.Status, act.Status, act.Message)\n\n\t\t}\n\t\treturn fmt.Errorf(\"section %s, status mismatch: %s vs %s\", exp.Name, exp.Status, act.Status)\n\t}\n\tif exp.Message != \"\" && exp.Message != act.Message && !strings.Contains(act.Message, exp.Message) {\n\t\treturn fmt.Errorf(\"section %s, message not found: %s in %s\", exp.Name, exp.Message, act.Message)\n\t}\n\tif len(exp.Warnings) != len(act.Warnings) {\n\t\treturn fmt.Errorf(\"section %s, warning count mismatch: %d vs %d\", exp.Name, len(exp.Warnings), len(act.Warnings))\n\t}\n\tfor j := range exp.Warnings {\n\t\tif !strings.Contains(act.Warnings[j], exp.Warnings[j]) {\n\t\t\treturn fmt.Errorf(\"section %s, warning message not found: %s in %s\", exp.Name, exp.Warnings[j], act.Warnings[j])\n\t\t}\n\t}\n\tif len(exp.Children) > len(act.Children) {\n\t\terrStrings := []string{}\n\t\tfor _, c := range act.Children {\n\t\t\terrStrings = append(errStrings, fmt.Sprintf(\"%+v\", c))\n\t\t}\n\t\treturn fmt.Errorf(strings.Join(errStrings, \",\"))\n\t}\n\n\tif len(exp.Children) > 0 {\n\t\treturn compareResults(exp.Children, act.Children)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package awskms\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha1\"\n\t\"encoding\/gob\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/kms\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/sts\"\n\t\"github.com\/dcoker\/biscuit\/keymanager\"\n\t\"github.com\/dcoker\/biscuit\/shared\"\n\t\"github.com\/dcoker\/biscuit\/store\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\ntype kmsGrantsCreate struct {\n\tname,\n\tgranteePrincipal,\n\tretiringPrincipal,\n\tfilename   *string\n\toperations *[]string\n\tallNames   *bool\n}\n\n\/\/ NewKmsGrantsCreate constructs the command to create a grant.\nfunc NewKmsGrantsCreate(c *kingpin.CmdClause) shared.Command {\n\tparams := &kmsGrantsCreate{}\n\tparams.name = c.Arg(\"name\", \"Name of the secret to grant access to.\").Required().String()\n\tparams.allNames = c.Flag(\"all-names\", \"If set, the grant allows the grantee to decrypt any values encrypted under \"+\n\t\t\"the keys that the named secret is encrypted with.\").Default(\"false\").Bool()\n\tparams.granteePrincipal = c.Flag(\"grantee-principal\", \"The ARN that will be granted \"+\n\t\t\"additional privileges.\").Short('g').PlaceHolder(\"ARN\").Required().String()\n\tparams.retiringPrincipal = c.Flag(\"retiring-principal\", \"The ARN that can retire the \"+\n\t\t\"grant.\").Short('e').PlaceHolder(\"ARN\").String()\n\tparams.operations = operationsFlag(c)\n\tparams.filename = shared.FilenameFlag(c)\n\treturn params\n}\n\ntype grantsCreatedOutput struct {\n\tName string\n\t\/\/ Alias -> Region -> Grant\n\tAliases map[string]map[string]grantDetails\n}\n\ntype grantDetails struct {\n\tGrantID,\n\tGrantToken string\n}\n\n\/\/ Run runs the command.\nfunc (w *kmsGrantsCreate) Run() error {\n\tdatabase := store.NewFileStore(*w.filename)\n\tvalues, err := database.Get(*w.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvalues = values.FilterByKeyManager(keymanager.KmsLabel)\n\n\taliases, err := resolveValuesToAliasesAndRegions(values)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgranteeArn, retireeArn, err := resolveGranteeArns(*w.granteePrincipal, *w.retiringPrincipal)\n\n\t\/\/ The template from which grants in each region are created.\n\tcreateGrantInput := kms.CreateGrantInput{\n\t\tOperations:       aws.StringSlice(*w.operations),\n\t\tGranteePrincipal: &granteeArn,\n\t}\n\tif !*w.allNames {\n\t\tcreateGrantInput.Constraints = &kms.GrantConstraints{\n\t\t\tEncryptionContextSubset: map[string]*string{\"SecretName\": w.name},\n\t\t}\n\t}\n\tif len(retireeArn) > 0 {\n\t\tcreateGrantInput.RetiringPrincipal = &retireeArn\n\t}\n\n\tgrantName, err := computeGrantName(createGrantInput)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcreateGrantInput.Name = aws.String(grantName)\n\n\toutput := grantsCreatedOutput{\n\t\tName:    grantName,\n\t\tAliases: make(map[string]map[string]grantDetails),\n\t}\n\tfor alias, regionList := range aliases {\n\t\tmrk, err := NewMultiRegionKey(alias, regionList, \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresults, err := mrk.AddGrant(createGrantInput)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tregionToGrantDetails := make(map[string]grantDetails)\n\t\tfor region, grant := range results {\n\t\t\tregionToGrantDetails[region] = grantDetails{\n\t\t\t\tGrantID:    *grant.GrantId,\n\t\t\t\tGrantToken: *grant.GrantToken}\n\t\t}\n\t\toutput.Aliases[alias] = regionToGrantDetails\n\t}\n\tfmt.Print(shared.MustYaml(output))\n\treturn nil\n}\n\nfunc computeGrantName(input kms.CreateGrantInput) (string, error) {\n\tcallerIdentity, err := sts.New(session.New()).GetCallerIdentity(nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar buf bytes.Buffer\n\tgob.Register(kms.CreateGrantInput{})\n\tencoder := gob.NewEncoder(&buf)\n\tif err := encoder.Encode([]interface{}{input, callerIdentity.Arn}); err != nil {\n\t\tpanic(err)\n\t}\n\thashed := sha1.Sum(buf.Bytes())\n\treturn GrantPrefix + hex.EncodeToString(hashed[:])[:10], nil\n}\n\nfunc resolveValuesToAliasesAndRegions(values store.ValueList) (map[string][]string, error) {\n\t\/\/ The KeyID field may refer to a key\/ or alias\/ ARN. We need to resolve the alias for any key\/ ARN\n\t\/\/ so that we can act on them across multiple regions. This loop resolves key\/ ARNs into their appropriate\n\t\/\/ aliases, and maintains a list of regions for each alias.\n\taliases := make(map[string][]string)\n\tfor _, v := range values {\n\t\tarn, err := keymanager.NewARN(v.KeyID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif arn.IsKmsAlias() {\n\t\t\taliases[\"alias\/\"+arn.Resource] = append(aliases[\"alias\/\"+arn.Resource], arn.Region)\n\t\t} else if arn.IsKmsKey() {\n\t\t\tregion := arn.Region\n\t\t\tclient := kmsHelper{kms.New(session.New(&aws.Config{Region: &region}))}\n\t\t\talias, err := client.GetAliasByKeyID(arn.Resource)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%s: Unable to find an alias for this key: %s\\n\", v.KeyID, err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\taliases[alias] = append(aliases[alias], arn.Region)\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn aliases, nil\n}\n\nfunc resolveGranteeArns(granteePrincipal, retiringPrincipal string) (string, string, error) {\n\tstsClient := sts.New(session.New(&aws.Config{}))\n\tcallerIdentity, err := stsClient.GetCallerIdentity(nil)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tgranteeArn := cleanArn(*callerIdentity.Account, granteePrincipal)\n\tif len(granteeArn) == 0 {\n\t\treturn \"\", \"\", errors.New(\"grantee ARN must not be empty string\")\n\t}\n\tretireeArn := cleanArn(*callerIdentity.Account, retiringPrincipal)\n\treturn granteeArn, retireeArn, nil\n}\n<commit_msg>Minor formatting fix to kmsgrantcreate.<commit_after>package awskms\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha1\"\n\t\"encoding\/gob\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/kms\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/sts\"\n\t\"github.com\/dcoker\/biscuit\/keymanager\"\n\t\"github.com\/dcoker\/biscuit\/shared\"\n\t\"github.com\/dcoker\/biscuit\/store\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\ntype kmsGrantsCreate struct {\n\tname,\n\tgranteePrincipal,\n\tretiringPrincipal,\n\tfilename *string\n\toperations *[]string\n\tallNames   *bool\n}\n\n\/\/ NewKmsGrantsCreate constructs the command to create a grant.\nfunc NewKmsGrantsCreate(c *kingpin.CmdClause) shared.Command {\n\tparams := &kmsGrantsCreate{}\n\tparams.name = c.Arg(\"name\", \"Name of the secret to grant access to.\").Required().String()\n\tparams.allNames = c.Flag(\"all-names\", \"If set, the grant allows the grantee to decrypt any values encrypted under \"+\n\t\t\"the keys that the named secret is encrypted with.\").Default(\"false\").Bool()\n\tparams.granteePrincipal = c.Flag(\"grantee-principal\", \"The ARN that will be granted \"+\n\t\t\"additional privileges.\").Short('g').PlaceHolder(\"ARN\").Required().String()\n\tparams.retiringPrincipal = c.Flag(\"retiring-principal\", \"The ARN that can retire the \"+\n\t\t\"grant.\").Short('e').PlaceHolder(\"ARN\").String()\n\tparams.operations = operationsFlag(c)\n\tparams.filename = shared.FilenameFlag(c)\n\treturn params\n}\n\ntype grantsCreatedOutput struct {\n\tName string\n\t\/\/ Alias -> Region -> Grant\n\tAliases map[string]map[string]grantDetails\n}\n\ntype grantDetails struct {\n\tGrantID,\n\tGrantToken string\n}\n\n\/\/ Run runs the command.\nfunc (w *kmsGrantsCreate) Run() error {\n\tdatabase := store.NewFileStore(*w.filename)\n\tvalues, err := database.Get(*w.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvalues = values.FilterByKeyManager(keymanager.KmsLabel)\n\n\taliases, err := resolveValuesToAliasesAndRegions(values)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgranteeArn, retireeArn, err := resolveGranteeArns(*w.granteePrincipal, *w.retiringPrincipal)\n\n\t\/\/ The template from which grants in each region are created.\n\tcreateGrantInput := kms.CreateGrantInput{\n\t\tOperations:       aws.StringSlice(*w.operations),\n\t\tGranteePrincipal: &granteeArn,\n\t}\n\tif !*w.allNames {\n\t\tcreateGrantInput.Constraints = &kms.GrantConstraints{\n\t\t\tEncryptionContextSubset: map[string]*string{\"SecretName\": w.name},\n\t\t}\n\t}\n\tif len(retireeArn) > 0 {\n\t\tcreateGrantInput.RetiringPrincipal = &retireeArn\n\t}\n\n\tgrantName, err := computeGrantName(createGrantInput)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcreateGrantInput.Name = aws.String(grantName)\n\n\toutput := grantsCreatedOutput{\n\t\tName:    grantName,\n\t\tAliases: make(map[string]map[string]grantDetails),\n\t}\n\tfor alias, regionList := range aliases {\n\t\tmrk, err := NewMultiRegionKey(alias, regionList, \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresults, err := mrk.AddGrant(createGrantInput)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tregionToGrantDetails := make(map[string]grantDetails)\n\t\tfor region, grant := range results {\n\t\t\tregionToGrantDetails[region] = grantDetails{\n\t\t\t\tGrantID:    *grant.GrantId,\n\t\t\t\tGrantToken: *grant.GrantToken}\n\t\t}\n\t\toutput.Aliases[alias] = regionToGrantDetails\n\t}\n\tfmt.Print(shared.MustYaml(output))\n\treturn nil\n}\n\nfunc computeGrantName(input kms.CreateGrantInput) (string, error) {\n\tcallerIdentity, err := sts.New(session.New()).GetCallerIdentity(nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar buf bytes.Buffer\n\tgob.Register(kms.CreateGrantInput{})\n\tencoder := gob.NewEncoder(&buf)\n\tif err := encoder.Encode([]interface{}{input, callerIdentity.Arn}); err != nil {\n\t\tpanic(err)\n\t}\n\thashed := sha1.Sum(buf.Bytes())\n\treturn GrantPrefix + hex.EncodeToString(hashed[:])[:10], nil\n}\n\nfunc resolveValuesToAliasesAndRegions(values store.ValueList) (map[string][]string, error) {\n\t\/\/ The KeyID field may refer to a key\/ or alias\/ ARN. We need to resolve the alias for any key\/ ARN\n\t\/\/ so that we can act on them across multiple regions. This loop resolves key\/ ARNs into their appropriate\n\t\/\/ aliases, and maintains a list of regions for each alias.\n\taliases := make(map[string][]string)\n\tfor _, v := range values {\n\t\tarn, err := keymanager.NewARN(v.KeyID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif arn.IsKmsAlias() {\n\t\t\taliases[\"alias\/\"+arn.Resource] = append(aliases[\"alias\/\"+arn.Resource], arn.Region)\n\t\t} else if arn.IsKmsKey() {\n\t\t\tregion := arn.Region\n\t\t\tclient := kmsHelper{kms.New(session.New(&aws.Config{Region: &region}))}\n\t\t\talias, err := client.GetAliasByKeyID(arn.Resource)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"%s: Unable to find an alias for this key: %s\\n\", v.KeyID, err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\taliases[alias] = append(aliases[alias], arn.Region)\n\t\t} else {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn aliases, nil\n}\n\nfunc resolveGranteeArns(granteePrincipal, retiringPrincipal string) (string, string, error) {\n\tstsClient := sts.New(session.New(&aws.Config{}))\n\tcallerIdentity, err := stsClient.GetCallerIdentity(nil)\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tgranteeArn := cleanArn(*callerIdentity.Account, granteePrincipal)\n\tif len(granteeArn) == 0 {\n\t\treturn \"\", \"\", errors.New(\"grantee ARN must not be empty string\")\n\t}\n\tretireeArn := cleanArn(*callerIdentity.Account, retiringPrincipal)\n\treturn granteeArn, retireeArn, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\nfunc init() {\n\thttp.HandleFunc(\"\/compile\", compile)\n}\n\nfunc compile(w http.ResponseWriter, r *http.Request) {\n\tif err := passThru(w, r); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintln(w, \"Compile server error.\")\n\t}\n}\n\nfunc passThru(w io.Writer, req *http.Request) error {\n\tlog.Debug(\"passThru()\")\n\n\tdefer req.Body.Close()\n\n\tjsonReader, err := makeBodyJson(req.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"make body json error: %v\", err)\n\t\treturn err\n\t}\n\n\tr, err := http.Post(s.sandbox.URL, req.Header.Get(\"Content-type\"), jsonReader)\n\tif err != nil {\n\t\tlog.Errorf(\"making POST request: %v\", err)\n\t\treturn err\n\t}\n\tdefer r.Body.Close()\n\tif _, err := io.Copy(w, r.Body); err != nil {\n\t\tlog.Errorf(\"copying response Body: %v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc makeBodyJson(httpBody io.Reader) (io.Reader, error) {\n\t\/\/ io.Reader -> []byte\n\thttpBodyByte, err := ioutil.ReadAll(httpBody)\n\tif err != nil {\n\t\tlog.Errorf(\"body read error: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ []byte -> url.Values\n\tv, err := url.ParseQuery(string(httpBodyByte))\n\tif err != nil {\n\t\tlog.Errorf(\"query parse error: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ make json\n\tjson, err := json.Marshal(map[string]string{\"Body\": v.Get(\"body\")})\n\tif err != nil {\n\t\tlog.Errorf(\"json marshal error: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ convert byte json -> io.Reader\n\treturn bytes.NewReader(json), nil\n}\n<commit_msg>rename Json -> JSON<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\nfunc init() {\n\thttp.HandleFunc(\"\/compile\", compile)\n}\n\nfunc compile(w http.ResponseWriter, r *http.Request) {\n\tif err := passThru(w, r); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintln(w, \"Compile server error.\")\n\t}\n}\n\nfunc passThru(w io.Writer, req *http.Request) error {\n\tlog.Debug(\"passThru()\")\n\n\tdefer req.Body.Close()\n\n\tjsonReader, err := makeBodyJSON(req.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"make body json error: %v\", err)\n\t\treturn err\n\t}\n\n\tr, err := http.Post(s.sandbox.URL, req.Header.Get(\"Content-type\"), jsonReader)\n\tif err != nil {\n\t\tlog.Errorf(\"making POST request: %v\", err)\n\t\treturn err\n\t}\n\tdefer r.Body.Close()\n\tif _, err := io.Copy(w, r.Body); err != nil {\n\t\tlog.Errorf(\"copying response Body: %v\", err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc makeBodyJSON(httpBody io.Reader) (io.Reader, error) {\n\t\/\/ io.Reader -> []byte\n\thttpBodyByte, err := ioutil.ReadAll(httpBody)\n\tif err != nil {\n\t\tlog.Errorf(\"body read error: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ []byte -> url.Values\n\tv, err := url.ParseQuery(string(httpBodyByte))\n\tif err != nil {\n\t\tlog.Errorf(\"query parse error: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ make json\n\tjson, err := json.Marshal(map[string]string{\"Body\": v.Get(\"body\")})\n\tif err != nil {\n\t\tlog.Errorf(\"json marshal error: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ convert byte json -> io.Reader\n\treturn bytes.NewReader(json), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package astilectron\n\nimport (\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/asticode\/go-astilog\"\n\t\"github.com\/asticode\/go-astitools\/context\"\n\t\"github.com\/asticode\/go-astitools\/exec\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ Versions\nconst (\n\tDefaultAcceptTCPTimeout = 30 * time.Second\n\tVersionAstilectron      = \"0.29.0\"\n\tVersionElectron         = \"1.8.1\"\n)\n\n\/\/ Misc vars\nvar (\n\tvalidOSes = map[string]bool{\n\t\t\"darwin\":  true,\n\t\t\"linux\":   true,\n\t\t\"windows\": true,\n\t}\n)\n\n\/\/ App event names\nconst (\n\tEventNameAppClose         = \"app.close\"\n\tEventNameAppCmdQuit       = \"app.cmd.quit\" \/\/ Sends an event to Electron to properly quit the app\n\tEventNameAppCmdStop       = \"app.cmd.stop\" \/\/ Cancel the context which results in exiting abruptly Electron's app\n\tEventNameAppCrash         = \"app.crash\"\n\tEventNameAppErrorAccept   = \"app.error.accept\"\n\tEventNameAppEventReady    = \"app.event.ready\"\n\tEventNameAppNoAccept      = \"app.no.accept\"\n\tEventNameAppTooManyAccept = \"app.too.many.accept\"\n)\n\n\/\/ Astilectron represents an object capable of interacting with Astilectron\ntype Astilectron struct {\n\tcanceller    *asticontext.Canceller\n\tchannelQuit  chan bool\n\tcloseOnce    sync.Once\n\tdispatcher   *dispatcher\n\tdisplayPool  *displayPool\n\tdock         *Dock\n\texecuter     Executer\n\tidentifier   *identifier\n\tlistener     net.Listener\n\toptions      Options\n\tpaths        *Paths\n\tprovisioner  Provisioner\n\treader       *reader\n\tstderrWriter *astiexec.StdWriter\n\tstdoutWriter *astiexec.StdWriter\n\tsupported    *Supported\n\twriter       *writer\n}\n\n\/\/ Options represents Astilectron options\ntype Options struct {\n\tAcceptTCPTimeout   time.Duration\n\tAppName            string\n\tAppIconDarwinPath  string \/\/ Darwin systems requires a specific .icns file\n\tAppIconDefaultPath string\n\tBaseDirectoryPath  string\n\tDataDirectoryPath  string\n\tElectronSwitches   []string\n\tSingleInstance     bool\n}\n\n\/\/ Supported represents Astilectron supported features\ntype Supported struct {\n\tNotification *bool `json:\"notification\"`\n}\n\n\/\/ New creates a new Astilectron instance\nfunc New(o Options) (a *Astilectron, err error) {\n\t\/\/ Validate the OS\n\tif !IsValidOS(runtime.GOOS) {\n\t\terr = errors.Wrapf(err, \"OS %s is invalid\", runtime.GOOS)\n\t\treturn\n\t}\n\n\t\/\/ Init\n\ta = &Astilectron{\n\t\tcanceller:   asticontext.NewCanceller(),\n\t\tchannelQuit: make(chan bool),\n\t\tdispatcher:  newDispatcher(),\n\t\tdisplayPool: newDisplayPool(),\n\t\texecuter:    DefaultExecuter,\n\t\tidentifier:  newIdentifier(),\n\t\toptions:     o,\n\t\tprovisioner: DefaultProvisioner,\n\t}\n\n\t\/\/ Set paths\n\tif a.paths, err = newPaths(runtime.GOOS, runtime.GOARCH, o); err != nil {\n\t\terr = errors.Wrap(err, \"creating new paths failed\")\n\t\treturn\n\t}\n\n\t\/\/ Add default listeners\n\ta.On(EventNameAppCmdStop, func(e Event) (deleteListener bool) {\n\t\ta.Stop()\n\t\treturn\n\t})\n\ta.On(EventNameDisplayEventAdded, func(e Event) (deleteListener bool) {\n\t\ta.displayPool.update(e.Displays)\n\t\treturn\n\t})\n\ta.On(EventNameDisplayEventMetricsChanged, func(e Event) (deleteListener bool) {\n\t\ta.displayPool.update(e.Displays)\n\t\treturn\n\t})\n\ta.On(EventNameDisplayEventRemoved, func(e Event) (deleteListener bool) {\n\t\ta.displayPool.update(e.Displays)\n\t\treturn\n\t})\n\treturn\n}\n\n\/\/ IsValidOS validates the OS\nfunc IsValidOS(os string) (ok bool) {\n\t_, ok = validOSes[os]\n\treturn\n}\n\n\/\/ SetProvisioner sets the provisioner\nfunc (a *Astilectron) SetProvisioner(p Provisioner) *Astilectron {\n\ta.provisioner = p\n\treturn a\n}\n\n\/\/ SetExecuter sets the executer\nfunc (a *Astilectron) SetExecuter(e Executer) *Astilectron {\n\ta.executer = e\n\treturn a\n}\n\n\/\/ On implements the Listenable interface\nfunc (a *Astilectron) On(eventName string, l Listener) {\n\ta.dispatcher.addListener(targetIDApp, eventName, l)\n}\n\n\/\/ Start starts Astilectron\nfunc (a *Astilectron) Start() (err error) {\n\t\/\/ Log\n\tastilog.Debug(\"Starting...\")\n\n\t\/\/ Provision\n\tif err = a.provision(); err != nil {\n\t\treturn errors.Wrap(err, \"provisioning failed\")\n\t}\n\n\t\/\/ Unfortunately communicating with Electron through stdin\/stdout doesn't work on Windows so all communications\n\t\/\/ will be done through TCP\n\tif err = a.listenTCP(); err != nil {\n\t\treturn errors.Wrap(err, \"listening failed\")\n\t}\n\n\t\/\/ Execute\n\tif err = a.execute(); err != nil {\n\t\terr = errors.Wrap(err, \"executing failed\")\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/ provision provisions Astilectron\nfunc (a *Astilectron) provision() error {\n\tastilog.Debug(\"Provisioning...\")\n\tvar ctx, _ = a.canceller.NewContext()\n\treturn a.provisioner.Provision(ctx, a.options.AppName, runtime.GOOS, runtime.GOARCH, *a.paths)\n}\n\n\/\/ listenTCP listens to the first TCP connection coming its way (this should be Astilectron)\nfunc (a *Astilectron) listenTCP() (err error) {\n\t\/\/ Log\n\tastilog.Debug(\"Listening...\")\n\n\t\/\/ Listen\n\tif a.listener, err = net.Listen(\"tcp\", \"127.0.0.1:\"); err != nil {\n\t\treturn errors.Wrap(err, \"tcp net.Listen failed\")\n\t}\n\n\t\/\/ Check a connection has been accepted quickly enough\n\tvar chanAccepted = make(chan bool)\n\tgo a.watchNoAccept(a.options.AcceptTCPTimeout, chanAccepted)\n\n\t\/\/ Accept connections\n\tgo a.acceptTCP(chanAccepted)\n\treturn\n}\n\n\/\/ watchNoAccept checks whether a TCP connection is accepted quickly enough\nfunc (a *Astilectron) watchNoAccept(timeout time.Duration, chanAccepted chan bool) {\n\t\/\/check timeout\n\tif timeout == 0 {\n\t\ttimeout = DefaultAcceptTCPTimeout\n\t}\n\tvar t = time.NewTimer(timeout)\n\tdefer t.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-chanAccepted:\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\tastilog.Errorf(\"No TCP connection has been accepted in the past %s\", timeout)\n\t\t\ta.dispatcher.dispatch(Event{Name: EventNameAppNoAccept, TargetID: targetIDApp})\n\t\t\ta.dispatcher.dispatch(Event{Name: EventNameAppCmdStop, TargetID: targetIDApp})\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ watchAcceptTCP accepts TCP connections\nfunc (a *Astilectron) acceptTCP(chanAccepted chan bool) {\n\tfor i := 0; i <= 1; i++ {\n\t\t\/\/ Accept\n\t\tvar conn net.Conn\n\t\tvar err error\n\t\tif conn, err = a.listener.Accept(); err != nil {\n\t\t\tastilog.Errorf(\"%s while TCP accepting\", err)\n\t\t\ta.dispatcher.dispatch(Event{Name: EventNameAppErrorAccept, TargetID: targetIDApp})\n\t\t\ta.dispatcher.dispatch(Event{Name: EventNameAppCmdStop, TargetID: targetIDApp})\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ We only accept the first connection which should be Astilectron, close the next one and stop\n\t\t\/\/ the app\n\t\tif i > 0 {\n\t\t\tastilog.Errorf(\"Too many TCP connections\")\n\t\t\ta.dispatcher.dispatch(Event{Name: EventNameAppTooManyAccept, TargetID: targetIDApp})\n\t\t\ta.dispatcher.dispatch(Event{Name: EventNameAppCmdStop, TargetID: targetIDApp})\n\t\t\tconn.Close()\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Let the timer know a connection has been accepted\n\t\tchanAccepted <- true\n\n\t\t\/\/ Create reader and writer\n\t\ta.writer = newWriter(conn)\n\t\tctx, _ := a.canceller.NewContext()\n\t\ta.reader = newReader(ctx, a.dispatcher, conn)\n\t\tgo a.reader.read()\n\t}\n}\n\n\/\/ execute executes Astilectron in Electron\nfunc (a *Astilectron) execute() (err error) {\n\t\/\/ Log\n\tastilog.Debug(\"Executing...\")\n\n\t\/\/ Create command\n\tvar ctx, _ = a.canceller.NewContext()\n\tvar singleInstance string\n\tif a.options.SingleInstance == true {\n\t\tsingleInstance = \"true\"\n\t} else {\n\t\tsingleInstance = \"false\"\n\t}\n\tvar cmd = exec.CommandContext(ctx, a.paths.AppExecutable(), append([]string{a.paths.AstilectronApplication(), a.listener.Addr().String(), singleInstance}, a.options.ElectronSwitches...)...)\n\ta.stderrWriter = astiexec.NewStdWriter(func(i []byte) { astilog.Debugf(\"Stderr says: %s\", i) })\n\ta.stdoutWriter = astiexec.NewStdWriter(func(i []byte) { astilog.Debugf(\"Stdout says: %s\", i) })\n\tcmd.Stderr = a.stderrWriter\n\tcmd.Stdout = a.stdoutWriter\n\n\t\/\/ Execute command\n\tif err = a.executeCmd(cmd); err != nil {\n\t\treturn errors.Wrap(err, \"executing cmd failed\")\n\t}\n\treturn\n}\n\n\/\/ executeCmd executes the command\nfunc (a *Astilectron) executeCmd(cmd *exec.Cmd) (err error) {\n\tvar e = synchronousFunc(a.canceller, a, func() {\n\t\terr = a.executer(a, cmd)\n\t}, EventNameAppEventReady)\n\n\t\/\/ Update display pool\n\tif e.Displays != nil {\n\t\ta.displayPool.update(e.Displays)\n\t}\n\n\t\/\/ Create dock\n\ta.dock = newDock(a.canceller, a.dispatcher, a.identifier, a.writer)\n\n\t\/\/ Update supported features\n\ta.supported = e.Supported\n\treturn\n}\n\n\/\/ watchCmd watches the cmd execution\nfunc (a *Astilectron) watchCmd(cmd *exec.Cmd) {\n\t\/\/ Wait\n\tcmd.Wait()\n\n\t\/\/ Check the canceller to check whether it was a crash\n\tif !a.canceller.Cancelled() {\n\t\tastilog.Debug(\"App has crashed\")\n\t\ta.dispatcher.dispatch(Event{Name: EventNameAppCrash, TargetID: targetIDApp})\n\t} else {\n\t\tastilog.Debug(\"App has closed\")\n\t\ta.dispatcher.dispatch(Event{Name: EventNameAppClose, TargetID: targetIDApp})\n\t}\n\ta.dispatcher.dispatch(Event{Name: EventNameAppCmdStop, TargetID: targetIDApp})\n}\n\n\/\/ Close closes Astilectron properly\nfunc (a *Astilectron) Close() {\n\tastilog.Debug(\"Closing...\")\n\ta.canceller.Cancel()\n\tif a.listener != nil {\n\t\ta.listener.Close()\n\t}\n\tif a.reader != nil {\n\t\ta.reader.close()\n\t}\n\tif a.stderrWriter != nil {\n\t\ta.stderrWriter.Close()\n\t}\n\tif a.stdoutWriter != nil {\n\t\ta.stdoutWriter.Close()\n\t}\n\tif a.writer != nil {\n\t\ta.writer.close()\n\t}\n}\n\n\/\/ HandleSignals handles signals\nfunc (a *Astilectron) HandleSignals() {\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, syscall.SIGABRT, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)\n\tgo func() {\n\t\tfor sig := range ch {\n\t\t\tastilog.Debugf(\"Received signal %s\", sig)\n\t\t\ta.Stop()\n\t\t}\n\t}()\n}\n\n\/\/ Stop orders Astilectron to stop\nfunc (a *Astilectron) Stop() {\n\tastilog.Debug(\"Stopping...\")\n\ta.canceller.Cancel()\n\ta.closeOnce.Do(func() {\n\t\tclose(a.channelQuit)\n\t})\n}\n\n\/\/ Wait is a blocking pattern\nfunc (a *Astilectron) Wait() {\n\t<-a.channelQuit\n}\n\n\/\/ Quit quits the app\nfunc (a *Astilectron) Quit() error {\n\treturn a.writer.write(Event{Name: EventNameAppCmdQuit})\n}\n\n\/\/ Paths returns the paths\nfunc (a *Astilectron) Paths() Paths {\n\treturn *a.paths\n}\n\n\/\/ Displays returns the displays\nfunc (a *Astilectron) Displays() []*Display {\n\treturn a.displayPool.all()\n}\n\n\/\/ Dock returns the dock\nfunc (a *Astilectron) Dock() *Dock {\n\treturn a.dock\n}\n\n\/\/ PrimaryDisplay returns the primary display\nfunc (a *Astilectron) PrimaryDisplay() *Display {\n\treturn a.displayPool.primary()\n}\n\n\/\/ NewMenu creates a new app menu\nfunc (a *Astilectron) NewMenu(i []*MenuItemOptions) *Menu {\n\treturn newMenu(nil, targetIDApp, i, a.canceller, a.dispatcher, a.identifier, a.writer)\n}\n\n\/\/ NewWindow creates a new window\nfunc (a *Astilectron) NewWindow(url string, o *WindowOptions) (*Window, error) {\n\treturn newWindow(a.options, a.Paths(), url, o, a.canceller, a.dispatcher, a.identifier, a.writer)\n}\n\n\/\/ NewWindowInDisplay creates a new window in a specific display\n\/\/ This overrides the center attribute\nfunc (a *Astilectron) NewWindowInDisplay(d *Display, url string, o *WindowOptions) (*Window, error) {\n\tif o.X != nil {\n\t\t*o.X += d.Bounds().X\n\t} else {\n\t\to.X = PtrInt(d.Bounds().X)\n\t}\n\tif o.Y != nil {\n\t\t*o.Y += d.Bounds().Y\n\t} else {\n\t\to.Y = PtrInt(d.Bounds().Y)\n\t}\n\treturn newWindow(a.options, a.Paths(), url, o, a.canceller, a.dispatcher, a.identifier, a.writer)\n}\n\n\/\/ NewTray creates a new tray\nfunc (a *Astilectron) NewTray(o *TrayOptions) *Tray {\n\treturn newTray(o, a.canceller, a.dispatcher, a.identifier, a.writer)\n}\n\n\/\/ NewNotification creates a new notification\nfunc (a *Astilectron) NewNotification(o *NotificationOptions) *Notification {\n\treturn newNotification(o, a.supported != nil && a.supported.Notification != nil && *a.supported.Notification, a.canceller, a.dispatcher, a.identifier, a.writer)\n}\n<commit_msg>Bumped Electron version to 4.0.1<commit_after>package astilectron\n\nimport (\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/asticode\/go-astilog\"\n\t\"github.com\/asticode\/go-astitools\/context\"\n\t\"github.com\/asticode\/go-astitools\/exec\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ Versions\nconst (\n\tDefaultAcceptTCPTimeout = 30 * time.Second\n\tVersionAstilectron      = \"0.29.0\"\n\tVersionElectron         = \"4.0.1\"\n)\n\n\/\/ Misc vars\nvar (\n\tvalidOSes = map[string]bool{\n\t\t\"darwin\":  true,\n\t\t\"linux\":   true,\n\t\t\"windows\": true,\n\t}\n)\n\n\/\/ App event names\nconst (\n\tEventNameAppClose         = \"app.close\"\n\tEventNameAppCmdQuit       = \"app.cmd.quit\" \/\/ Sends an event to Electron to properly quit the app\n\tEventNameAppCmdStop       = \"app.cmd.stop\" \/\/ Cancel the context which results in exiting abruptly Electron's app\n\tEventNameAppCrash         = \"app.crash\"\n\tEventNameAppErrorAccept   = \"app.error.accept\"\n\tEventNameAppEventReady    = \"app.event.ready\"\n\tEventNameAppNoAccept      = \"app.no.accept\"\n\tEventNameAppTooManyAccept = \"app.too.many.accept\"\n)\n\n\/\/ Astilectron represents an object capable of interacting with Astilectron\ntype Astilectron struct {\n\tcanceller    *asticontext.Canceller\n\tchannelQuit  chan bool\n\tcloseOnce    sync.Once\n\tdispatcher   *dispatcher\n\tdisplayPool  *displayPool\n\tdock         *Dock\n\texecuter     Executer\n\tidentifier   *identifier\n\tlistener     net.Listener\n\toptions      Options\n\tpaths        *Paths\n\tprovisioner  Provisioner\n\treader       *reader\n\tstderrWriter *astiexec.StdWriter\n\tstdoutWriter *astiexec.StdWriter\n\tsupported    *Supported\n\twriter       *writer\n}\n\n\/\/ Options represents Astilectron options\ntype Options struct {\n\tAcceptTCPTimeout   time.Duration\n\tAppName            string\n\tAppIconDarwinPath  string \/\/ Darwin systems requires a specific .icns file\n\tAppIconDefaultPath string\n\tBaseDirectoryPath  string\n\tDataDirectoryPath  string\n\tElectronSwitches   []string\n\tSingleInstance     bool\n}\n\n\/\/ Supported represents Astilectron supported features\ntype Supported struct {\n\tNotification *bool `json:\"notification\"`\n}\n\n\/\/ New creates a new Astilectron instance\nfunc New(o Options) (a *Astilectron, err error) {\n\t\/\/ Validate the OS\n\tif !IsValidOS(runtime.GOOS) {\n\t\terr = errors.Wrapf(err, \"OS %s is invalid\", runtime.GOOS)\n\t\treturn\n\t}\n\n\t\/\/ Init\n\ta = &Astilectron{\n\t\tcanceller:   asticontext.NewCanceller(),\n\t\tchannelQuit: make(chan bool),\n\t\tdispatcher:  newDispatcher(),\n\t\tdisplayPool: newDisplayPool(),\n\t\texecuter:    DefaultExecuter,\n\t\tidentifier:  newIdentifier(),\n\t\toptions:     o,\n\t\tprovisioner: DefaultProvisioner,\n\t}\n\n\t\/\/ Set paths\n\tif a.paths, err = newPaths(runtime.GOOS, runtime.GOARCH, o); err != nil {\n\t\terr = errors.Wrap(err, \"creating new paths failed\")\n\t\treturn\n\t}\n\n\t\/\/ Add default listeners\n\ta.On(EventNameAppCmdStop, func(e Event) (deleteListener bool) {\n\t\ta.Stop()\n\t\treturn\n\t})\n\ta.On(EventNameDisplayEventAdded, func(e Event) (deleteListener bool) {\n\t\ta.displayPool.update(e.Displays)\n\t\treturn\n\t})\n\ta.On(EventNameDisplayEventMetricsChanged, func(e Event) (deleteListener bool) {\n\t\ta.displayPool.update(e.Displays)\n\t\treturn\n\t})\n\ta.On(EventNameDisplayEventRemoved, func(e Event) (deleteListener bool) {\n\t\ta.displayPool.update(e.Displays)\n\t\treturn\n\t})\n\treturn\n}\n\n\/\/ IsValidOS validates the OS\nfunc IsValidOS(os string) (ok bool) {\n\t_, ok = validOSes[os]\n\treturn\n}\n\n\/\/ SetProvisioner sets the provisioner\nfunc (a *Astilectron) SetProvisioner(p Provisioner) *Astilectron {\n\ta.provisioner = p\n\treturn a\n}\n\n\/\/ SetExecuter sets the executer\nfunc (a *Astilectron) SetExecuter(e Executer) *Astilectron {\n\ta.executer = e\n\treturn a\n}\n\n\/\/ On implements the Listenable interface\nfunc (a *Astilectron) On(eventName string, l Listener) {\n\ta.dispatcher.addListener(targetIDApp, eventName, l)\n}\n\n\/\/ Start starts Astilectron\nfunc (a *Astilectron) Start() (err error) {\n\t\/\/ Log\n\tastilog.Debug(\"Starting...\")\n\n\t\/\/ Provision\n\tif err = a.provision(); err != nil {\n\t\treturn errors.Wrap(err, \"provisioning failed\")\n\t}\n\n\t\/\/ Unfortunately communicating with Electron through stdin\/stdout doesn't work on Windows so all communications\n\t\/\/ will be done through TCP\n\tif err = a.listenTCP(); err != nil {\n\t\treturn errors.Wrap(err, \"listening failed\")\n\t}\n\n\t\/\/ Execute\n\tif err = a.execute(); err != nil {\n\t\terr = errors.Wrap(err, \"executing failed\")\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/ provision provisions Astilectron\nfunc (a *Astilectron) provision() error {\n\tastilog.Debug(\"Provisioning...\")\n\tvar ctx, _ = a.canceller.NewContext()\n\treturn a.provisioner.Provision(ctx, a.options.AppName, runtime.GOOS, runtime.GOARCH, *a.paths)\n}\n\n\/\/ listenTCP listens to the first TCP connection coming its way (this should be Astilectron)\nfunc (a *Astilectron) listenTCP() (err error) {\n\t\/\/ Log\n\tastilog.Debug(\"Listening...\")\n\n\t\/\/ Listen\n\tif a.listener, err = net.Listen(\"tcp\", \"127.0.0.1:\"); err != nil {\n\t\treturn errors.Wrap(err, \"tcp net.Listen failed\")\n\t}\n\n\t\/\/ Check a connection has been accepted quickly enough\n\tvar chanAccepted = make(chan bool)\n\tgo a.watchNoAccept(a.options.AcceptTCPTimeout, chanAccepted)\n\n\t\/\/ Accept connections\n\tgo a.acceptTCP(chanAccepted)\n\treturn\n}\n\n\/\/ watchNoAccept checks whether a TCP connection is accepted quickly enough\nfunc (a *Astilectron) watchNoAccept(timeout time.Duration, chanAccepted chan bool) {\n\t\/\/check timeout\n\tif timeout == 0 {\n\t\ttimeout = DefaultAcceptTCPTimeout\n\t}\n\tvar t = time.NewTimer(timeout)\n\tdefer t.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-chanAccepted:\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\tastilog.Errorf(\"No TCP connection has been accepted in the past %s\", timeout)\n\t\t\ta.dispatcher.dispatch(Event{Name: EventNameAppNoAccept, TargetID: targetIDApp})\n\t\t\ta.dispatcher.dispatch(Event{Name: EventNameAppCmdStop, TargetID: targetIDApp})\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ watchAcceptTCP accepts TCP connections\nfunc (a *Astilectron) acceptTCP(chanAccepted chan bool) {\n\tfor i := 0; i <= 1; i++ {\n\t\t\/\/ Accept\n\t\tvar conn net.Conn\n\t\tvar err error\n\t\tif conn, err = a.listener.Accept(); err != nil {\n\t\t\tastilog.Errorf(\"%s while TCP accepting\", err)\n\t\t\ta.dispatcher.dispatch(Event{Name: EventNameAppErrorAccept, TargetID: targetIDApp})\n\t\t\ta.dispatcher.dispatch(Event{Name: EventNameAppCmdStop, TargetID: targetIDApp})\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ We only accept the first connection which should be Astilectron, close the next one and stop\n\t\t\/\/ the app\n\t\tif i > 0 {\n\t\t\tastilog.Errorf(\"Too many TCP connections\")\n\t\t\ta.dispatcher.dispatch(Event{Name: EventNameAppTooManyAccept, TargetID: targetIDApp})\n\t\t\ta.dispatcher.dispatch(Event{Name: EventNameAppCmdStop, TargetID: targetIDApp})\n\t\t\tconn.Close()\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Let the timer know a connection has been accepted\n\t\tchanAccepted <- true\n\n\t\t\/\/ Create reader and writer\n\t\ta.writer = newWriter(conn)\n\t\tctx, _ := a.canceller.NewContext()\n\t\ta.reader = newReader(ctx, a.dispatcher, conn)\n\t\tgo a.reader.read()\n\t}\n}\n\n\/\/ execute executes Astilectron in Electron\nfunc (a *Astilectron) execute() (err error) {\n\t\/\/ Log\n\tastilog.Debug(\"Executing...\")\n\n\t\/\/ Create command\n\tvar ctx, _ = a.canceller.NewContext()\n\tvar singleInstance string\n\tif a.options.SingleInstance == true {\n\t\tsingleInstance = \"true\"\n\t} else {\n\t\tsingleInstance = \"false\"\n\t}\n\tvar cmd = exec.CommandContext(ctx, a.paths.AppExecutable(), append([]string{a.paths.AstilectronApplication(), a.listener.Addr().String(), singleInstance}, a.options.ElectronSwitches...)...)\n\ta.stderrWriter = astiexec.NewStdWriter(func(i []byte) { astilog.Debugf(\"Stderr says: %s\", i) })\n\ta.stdoutWriter = astiexec.NewStdWriter(func(i []byte) { astilog.Debugf(\"Stdout says: %s\", i) })\n\tcmd.Stderr = a.stderrWriter\n\tcmd.Stdout = a.stdoutWriter\n\n\t\/\/ Execute command\n\tif err = a.executeCmd(cmd); err != nil {\n\t\treturn errors.Wrap(err, \"executing cmd failed\")\n\t}\n\treturn\n}\n\n\/\/ executeCmd executes the command\nfunc (a *Astilectron) executeCmd(cmd *exec.Cmd) (err error) {\n\tvar e = synchronousFunc(a.canceller, a, func() {\n\t\terr = a.executer(a, cmd)\n\t}, EventNameAppEventReady)\n\n\t\/\/ Update display pool\n\tif e.Displays != nil {\n\t\ta.displayPool.update(e.Displays)\n\t}\n\n\t\/\/ Create dock\n\ta.dock = newDock(a.canceller, a.dispatcher, a.identifier, a.writer)\n\n\t\/\/ Update supported features\n\ta.supported = e.Supported\n\treturn\n}\n\n\/\/ watchCmd watches the cmd execution\nfunc (a *Astilectron) watchCmd(cmd *exec.Cmd) {\n\t\/\/ Wait\n\tcmd.Wait()\n\n\t\/\/ Check the canceller to check whether it was a crash\n\tif !a.canceller.Cancelled() {\n\t\tastilog.Debug(\"App has crashed\")\n\t\ta.dispatcher.dispatch(Event{Name: EventNameAppCrash, TargetID: targetIDApp})\n\t} else {\n\t\tastilog.Debug(\"App has closed\")\n\t\ta.dispatcher.dispatch(Event{Name: EventNameAppClose, TargetID: targetIDApp})\n\t}\n\ta.dispatcher.dispatch(Event{Name: EventNameAppCmdStop, TargetID: targetIDApp})\n}\n\n\/\/ Close closes Astilectron properly\nfunc (a *Astilectron) Close() {\n\tastilog.Debug(\"Closing...\")\n\ta.canceller.Cancel()\n\tif a.listener != nil {\n\t\ta.listener.Close()\n\t}\n\tif a.reader != nil {\n\t\ta.reader.close()\n\t}\n\tif a.stderrWriter != nil {\n\t\ta.stderrWriter.Close()\n\t}\n\tif a.stdoutWriter != nil {\n\t\ta.stdoutWriter.Close()\n\t}\n\tif a.writer != nil {\n\t\ta.writer.close()\n\t}\n}\n\n\/\/ HandleSignals handles signals\nfunc (a *Astilectron) HandleSignals() {\n\tch := make(chan os.Signal, 1)\n\tsignal.Notify(ch, syscall.SIGABRT, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)\n\tgo func() {\n\t\tfor sig := range ch {\n\t\t\tastilog.Debugf(\"Received signal %s\", sig)\n\t\t\ta.Stop()\n\t\t}\n\t}()\n}\n\n\/\/ Stop orders Astilectron to stop\nfunc (a *Astilectron) Stop() {\n\tastilog.Debug(\"Stopping...\")\n\ta.canceller.Cancel()\n\ta.closeOnce.Do(func() {\n\t\tclose(a.channelQuit)\n\t})\n}\n\n\/\/ Wait is a blocking pattern\nfunc (a *Astilectron) Wait() {\n\t<-a.channelQuit\n}\n\n\/\/ Quit quits the app\nfunc (a *Astilectron) Quit() error {\n\treturn a.writer.write(Event{Name: EventNameAppCmdQuit})\n}\n\n\/\/ Paths returns the paths\nfunc (a *Astilectron) Paths() Paths {\n\treturn *a.paths\n}\n\n\/\/ Displays returns the displays\nfunc (a *Astilectron) Displays() []*Display {\n\treturn a.displayPool.all()\n}\n\n\/\/ Dock returns the dock\nfunc (a *Astilectron) Dock() *Dock {\n\treturn a.dock\n}\n\n\/\/ PrimaryDisplay returns the primary display\nfunc (a *Astilectron) PrimaryDisplay() *Display {\n\treturn a.displayPool.primary()\n}\n\n\/\/ NewMenu creates a new app menu\nfunc (a *Astilectron) NewMenu(i []*MenuItemOptions) *Menu {\n\treturn newMenu(nil, targetIDApp, i, a.canceller, a.dispatcher, a.identifier, a.writer)\n}\n\n\/\/ NewWindow creates a new window\nfunc (a *Astilectron) NewWindow(url string, o *WindowOptions) (*Window, error) {\n\treturn newWindow(a.options, a.Paths(), url, o, a.canceller, a.dispatcher, a.identifier, a.writer)\n}\n\n\/\/ NewWindowInDisplay creates a new window in a specific display\n\/\/ This overrides the center attribute\nfunc (a *Astilectron) NewWindowInDisplay(d *Display, url string, o *WindowOptions) (*Window, error) {\n\tif o.X != nil {\n\t\t*o.X += d.Bounds().X\n\t} else {\n\t\to.X = PtrInt(d.Bounds().X)\n\t}\n\tif o.Y != nil {\n\t\t*o.Y += d.Bounds().Y\n\t} else {\n\t\to.Y = PtrInt(d.Bounds().Y)\n\t}\n\treturn newWindow(a.options, a.Paths(), url, o, a.canceller, a.dispatcher, a.identifier, a.writer)\n}\n\n\/\/ NewTray creates a new tray\nfunc (a *Astilectron) NewTray(o *TrayOptions) *Tray {\n\treturn newTray(o, a.canceller, a.dispatcher, a.identifier, a.writer)\n}\n\n\/\/ NewNotification creates a new notification\nfunc (a *Astilectron) NewNotification(o *NotificationOptions) *Notification {\n\treturn newNotification(o, a.supported != nil && a.supported.Notification != nil && *a.supported.Notification, a.canceller, a.dispatcher, a.identifier, a.writer)\n}\n<|endoftext|>"}
{"text":"<commit_before>package cdsclient\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"regexp\"\n\t\"runtime\/pprof\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/ovh\/cds\/cli\"\n\t\"github.com\/ovh\/cds\/sdk\/telemetry\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n\n\t\"github.com\/ovh\/cds\/sdk\"\n)\n\nconst (\n\t\/\/ RequestedIfModifiedSinceHeader is used as HTTP header\n\tRequestedIfModifiedSinceHeader = \"If-Modified-Since\"\n\t\/\/ ResponseAPITimeHeader is used as HTTP header\n\tResponseAPITimeHeader = \"X-Api-Time\"\n\t\/\/ ResponseAPINanosecondsTimeHeader is used as HTTP header\n\tResponseAPINanosecondsTimeHeader = \"X-Api-Nanoseconds-Time\"\n\t\/\/ ResponseEtagHeader is used as HTTP header\n\tResponseEtagHeader = \"Etag\"\n\t\/\/ ResponseProcessTimeHeader is used as HTTP header\n\tResponseProcessTimeHeader = \"X-Api-Process-Time\"\n)\n\n\/\/ RequestModifier is used to modify behavior of Request and Steam functions\ntype RequestModifier func(req *http.Request)\n\n\/\/ HTTPClient is a interface for HTTPClient mock\ntype HTTPClient interface {\n\tDo(*http.Request) (*http.Response, error)\n}\n\n\/\/ SetHeader modify headers of http.Request\nfunc SetHeader(key, value string) RequestModifier {\n\treturn func(req *http.Request) {\n\t\treq.Header.Set(key, value)\n\t}\n}\n\n\/\/ WithQueryParameter add query parameters to your http.Request\nfunc WithQueryParameter(key, value string) RequestModifier {\n\treturn func(req *http.Request) {\n\t\tq := req.URL.Query()\n\t\tq.Set(key, value)\n\t\treq.URL.RawQuery = q.Encode()\n\t}\n}\n\n\/\/ PostJSON post the *in* struct as json. If set, it unmarshalls the response to *out*\nfunc (c *client) PostJSON(ctx context.Context, path string, in interface{}, out interface{}, mods ...RequestModifier) (int, error) {\n\t_, _, code, err := c.RequestJSON(ctx, http.MethodPost, path, in, out, mods...)\n\treturn code, err\n}\n\n\/\/ PostJSON ut the *in* struct as json. If set, it unmarshalls the response to *out*\nfunc (c *client) PutJSON(ctx context.Context, path string, in interface{}, out interface{}, mods ...RequestModifier) (int, error) {\n\t_, _, code, err := c.RequestJSON(ctx, http.MethodPut, path, in, out, mods...)\n\treturn code, err\n}\n\n\/\/ GetJSON get the requested path If set, it unmarshalls the response to *out*\nfunc (c *client) GetJSON(ctx context.Context, path string, out interface{}, mods ...RequestModifier) (int, error) {\n\t_, _, code, err := c.RequestJSON(ctx, http.MethodGet, path, nil, out, mods...)\n\treturn code, err\n}\n\n\/\/ GetJSONWithHeaders get the requested path If set, it unmarshalls the response to *out* and return response headers\nfunc (c *client) GetJSONWithHeaders(path string, out interface{}, mods ...RequestModifier) (http.Header, int, error) {\n\t_, header, code, err := c.RequestJSON(context.Background(), http.MethodGet, path, nil, out, mods...)\n\treturn header, code, err\n}\n\n\/\/ DeleteJSON deletes the requested path If set, it unmarshalls the response to *out*\nfunc (c *client) DeleteJSON(ctx context.Context, path string, out interface{}, mods ...RequestModifier) (int, error) {\n\t_, _, code, err := c.RequestJSON(ctx, http.MethodDelete, path, nil, out, mods...)\n\treturn code, err\n}\n\n\/\/ RequestJSON does a request with the *in* struct as json. If set, it unmarshalls the response to *out*\nfunc (c *client) RequestJSON(ctx context.Context, method, path string, in interface{}, out interface{}, mods ...RequestModifier) ([]byte, http.Header, int, error) {\n\tvar b = []byte{}\n\tvar err error\n\n\tif in != nil {\n\t\tb, err = json.Marshal(in)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, sdk.WithStack(err)\n\t\t}\n\t}\n\n\tvar body io.Reader\n\tif len(b) > 0 {\n\t\tbody = bytes.NewBuffer(b)\n\t}\n\n\tres, header, code, err := c.Request(ctx, method, path, body, mods...)\n\tif err != nil {\n\t\treturn nil, nil, code, sdk.WithStack(err)\n\t}\n\n\tif code >= 400 {\n\t\tif err := sdk.DecodeError(res); err != nil {\n\t\t\treturn res, nil, code, err\n\t\t}\n\t\treturn res, nil, code, sdk.WithStack(fmt.Errorf(\"HTTP %d\", code))\n\t}\n\n\tif code == 204 {\n\t\treturn res, header, code, nil\n\t}\n\n\tif out != nil {\n\t\tif err := json.Unmarshal(res, out); err != nil {\n\t\t\treturn res, nil, code, sdk.WithStack(err)\n\t\t}\n\t}\n\n\treturn res, header, code, nil\n}\n\n\/\/ Request executes an authentificated HTTP request on $path given $method and $args\nfunc (c *client) Request(ctx context.Context, method string, path string, body io.Reader, mods ...RequestModifier) ([]byte, http.Header, int, error) {\n\trespBody, respHeader, code, err := c.Stream(ctx, method, path, body, false, mods...)\n\tif err != nil {\n\t\treturn nil, nil, 0, sdk.WithStack(err)\n\t}\n\tdefer func() {\n\t\t\/\/ Drain and close the body to let the Transport reuse the connection\n\t\t_, _ = io.Copy(ioutil.Discard, respBody)\n\t\t_ = respBody.Close()\n\t}()\n\n\tvar bodyBtes []byte\n\tbodyBtes, err = ioutil.ReadAll(respBody)\n\tif err != nil {\n\t\treturn nil, nil, code, sdk.WithStack(err)\n\t}\n\n\tif c.config.Verbose {\n\t\tif len(bodyBtes) > 0 {\n\t\t\tlog.Printf(\"Response Body: %s\\n\", bodyBtes)\n\t\t}\n\t}\n\n\tif code >= 400 {\n\t\tif err := sdk.DecodeError(bodyBtes); err != nil {\n\t\t\treturn bodyBtes, nil, code, sdk.WithStack(err)\n\t\t}\n\t\treturn bodyBtes, nil, code, sdk.WithStack(fmt.Errorf(\"HTTP %d\", code))\n\t}\n\n\treturn bodyBtes, respHeader, code, nil\n}\n\n\/\/ signin route pattern\n\nvar signinRouteRegexp = regexp.MustCompile(`\\\/auth\\\/consumer\\\/.*\\\/signin`)\n\nfunc extractBodyErrorFromResponse(r *http.Response) error {\n\tbody, _ := ioutil.ReadAll(r.Body)\n\tr.Body.Close() \/\/ nolint\n\tif err := sdk.DecodeError(body); err != nil {\n\t\treturn sdk.WithStack(err)\n\t}\n\treturn sdk.WithStack(fmt.Errorf(\"HTTP %d\", r.StatusCode))\n}\n\n\/\/ Stream makes an authenticated http request and return io.ReadCloser\nfunc (c *client) Stream(ctx context.Context, method string, path string, body io.Reader, noTimeout bool, mods ...RequestModifier) (io.ReadCloser, http.Header, int, error) {\n\t\/\/ Checks that current session_token is still valid\n\t\/\/ If not, challenge a new one against the authenticationToken\n\tvar checkToken = !strings.Contains(path, \"\/auth\/consumer\/builtin\/signin\") &&\n\t\t!strings.Contains(path, \"\/auth\/consumer\/local\/signin\") &&\n\t\t!strings.Contains(path, \"\/auth\/consumer\/local\/signup\") &&\n\t\t!strings.Contains(path, \"\/auth\/consumer\/local\/verify\") &&\n\t\t!strings.Contains(path, \"\/auth\/consumer\/worker\/signin\")\n\n\tif checkToken && !c.config.HasValidSessionToken() && c.config.BuitinConsumerAuthenticationToken != \"\" {\n\t\tif c.config.Verbose {\n\t\t\tlog.Printf(\"session token invalid: (%s). Relogin...\\n\", c.config.SessionToken)\n\t\t}\n\t\tresp, err := c.AuthConsumerSignin(sdk.ConsumerBuiltin, sdk.AuthConsumerSigninRequest{\"token\": c.config.BuitinConsumerAuthenticationToken})\n\t\tif err != nil {\n\t\t\treturn nil, nil, -1, sdk.WithStack(err)\n\t\t}\n\t\tif c.config.Verbose {\n\t\t\tlog.Println(\"jwt: \", sdk.StringFirstN(resp.Token, 12))\n\t\t}\n\t\tc.config.SessionToken = resp.Token\n\t}\n\n\tlabels := pprof.Labels(\"path\", path, \"method\", method)\n\tctx = pprof.WithLabels(ctx, labels)\n\tpprof.SetGoroutineLabels(ctx)\n\n\t\/\/ In case where the given reader is not a ReadSeeker we should store the body in ram to retry http request\n\tvar bodyBytes []byte\n\tvar err error\n\tif _, ok := body.(io.ReadSeeker); !ok && body != nil {\n\t\tbodyBytes, err = ioutil.ReadAll(body)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, sdk.WithStack(err)\n\t\t}\n\t}\n\n\tvar url string\n\tif strings.HasPrefix(path, \"http\") {\n\t\turl = path\n\t} else {\n\t\turl = c.config.Host + path\n\t}\n\n\tvar savederror error\n\tfor i := 0; i <= c.config.Retry; i++ {\n\t\tvar req *http.Request\n\t\tvar requestError error\n\t\tif rs, ok := body.(io.ReadSeeker); ok {\n\t\t\tif _, err := rs.Seek(0, 0); err != nil {\n\t\t\t\treturn nil, nil, 0, sdk.WrapError(err, \"request failed after %d retries\", i)\n\t\t\t}\n\t\t\treq, requestError = http.NewRequest(method, url, body)\n\t\t} else {\n\t\t\treq, requestError = http.NewRequest(method, url, bytes.NewBuffer(bodyBytes))\n\t\t}\n\t\tif requestError != nil {\n\t\t\tsavederror = sdk.WithStack(requestError)\n\t\t\tcontinue\n\t\t}\n\n\t\treq = req.WithContext(ctx)\n\t\tdate := sdk.FormatDateRFC5322(time.Now())\n\t\treq.Header.Set(\"Date\", date)\n\t\treq.Header.Set(\"X-CDS-RemoteTime\", date)\n\n\t\tif c.config.Verbose {\n\t\t\tlog.Printf(\"Stream > context> %s\\n\", telemetry.DumpContext(ctx))\n\t\t}\n\t\tspanCtx, ok := telemetry.ContextToSpanContext(ctx)\n\t\tif ok {\n\t\t\ttelemetry.DefaultFormat.SpanContextToRequest(spanCtx, req)\n\t\t}\n\n\t\tfor i := range mods {\n\t\t\tif mods[i] != nil {\n\t\t\t\tmods[i](req)\n\t\t\t}\n\t\t}\n\n\t\tif req.Header.Get(\"Content-Type\") == \"\" {\n\t\t\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\t\t}\n\n\t\treq.Header.Set(\"Connection\", \"close\")\n\n\t\t\/\/No auth on signing routes or on url that is not cds configured in config.Host\n\t\tif strings.HasPrefix(url, c.config.Host) && !signinRouteRegexp.MatchString(path) {\n\t\t\tif _, _, err := new(jwt.Parser).ParseUnverified(c.config.SessionToken, &sdk.AuthSessionJWTClaims{}); err == nil {\n\t\t\t\tif c.config.Verbose {\n\t\t\t\t\tlog.Println(\"JWT recognized\")\n\t\t\t\t}\n\t\t\t\tauth := \"Bearer \" + c.config.SessionToken\n\t\t\t\treq.Header.Add(\"Authorization\", auth)\n\t\t\t}\n\t\t}\n\n\t\tif c.config.Verbose {\n\t\t\tlog.Println(cli.Green(\"********REQUEST**********\"))\n\t\t\tdmp, _ := httputil.DumpRequestOut(req, true)\n\t\t\tlog.Printf(\"%s\", string(dmp))\n\t\t\tlog.Println(cli.Green(\"**************************\"))\n\t\t}\n\n\t\tvar errDo error\n\t\tvar resp *http.Response\n\t\tif noTimeout {\n\t\t\tresp, errDo = c.httpSSEClient.Do(req)\n\t\t} else {\n\t\t\tresp, errDo = c.httpClient.Do(req)\n\t\t}\n\t\tif errDo != nil {\n\t\t\tsavederror = sdk.WithStack(errDo)\n\t\t\tcontinue\n\t\t}\n\n\t\tif c.config.Verbose {\n\t\t\tlog.Println(cli.Yellow(\"********RESPONSE**********\"))\n\t\t\tdmp, _ := httputil.DumpResponse(resp, true)\n\t\t\tlog.Printf(\"%s\", string(dmp))\n\t\t\tlog.Println(cli.Yellow(\"**************************\"))\n\t\t}\n\n\t\tif resp.StatusCode == 401 {\n\t\t\tc.config.SessionToken = \"\"\n\t\t}\n\n\t\tif resp.StatusCode == 409 || resp.StatusCode > 500 {\n\t\t\ttime.Sleep(250 * time.Millisecond)\n\t\t\tsavederror = extractBodyErrorFromResponse(resp)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ if no request error by status > 500, check CDS error\n\t\t\/\/ if there is a CDS errors, return it\n\t\tif resp.StatusCode == 500 {\n\t\t\treturn nil, resp.Header, resp.StatusCode, extractBodyErrorFromResponse(resp)\n\t\t}\n\n\t\treturn resp.Body, resp.Header, resp.StatusCode, nil\n\t}\n\n\treturn nil, nil, 0, sdk.WrapError(savederror, \"request failed after %d retries\", c.config.Retry)\n}\n\n\/\/ UploadMultiPart upload multipart\nfunc (c *client) UploadMultiPart(method string, path string, body *bytes.Buffer, mods ...RequestModifier) ([]byte, int, error) {\n\t\/\/ Checks that current session_token is still valid\n\t\/\/ If not, challenge a new one against the authenticationToken\n\tif !c.config.HasValidSessionToken() && c.config.BuitinConsumerAuthenticationToken != \"\" {\n\t\tresp, err := c.AuthConsumerSignin(sdk.ConsumerBuiltin, sdk.AuthConsumerSigninRequest{\"token\": c.config.BuitinConsumerAuthenticationToken})\n\t\tif err != nil {\n\t\t\treturn nil, -1, err\n\t\t}\n\t\tc.config.SessionToken = resp.Token\n\t}\n\n\tvar req *http.Request\n\treq, errRequest := http.NewRequest(method, c.config.Host+path, body)\n\tif errRequest != nil {\n\t\treturn nil, 0, errRequest\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application\/octet-stream\")\n\treq.Header.Set(\"Connection\", \"close\")\n\n\tfor i := range mods {\n\t\tmods[i](req)\n\t}\n\n\t\/\/No auth on signing routes\n\tif !signinRouteRegexp.MatchString(path) {\n\t\tif _, _, err := new(jwt.Parser).ParseUnverified(c.config.SessionToken, &sdk.AuthSessionJWTClaims{}); err == nil {\n\t\t\tif c.config.Verbose {\n\t\t\t\tfmt.Println(\"JWT recognized\")\n\t\t\t}\n\t\t\tauth := \"Bearer \" + c.config.SessionToken\n\t\t\treq.Header.Add(\"Authorization\", auth)\n\t\t}\n\t}\n\n\tresp, err := c.httpSSEClient.Do(req)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif c.config.Verbose {\n\t\tfmt.Printf(\"Response Status: %s\\n\", resp.Status)\n\t\tfmt.Printf(\"Request path: %s\\n\", c.config.Host+path)\n\t\tfmt.Printf(\"Request Headers: %s\\n\", req.Header)\n\t\tfmt.Printf(\"Response Headers: %s\\n\", resp.Header)\n\t}\n\n\tif resp.StatusCode == 401 {\n\t\tc.config.SessionToken = \"\"\n\t}\n\n\tvar respBody []byte\n\trespBody, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, resp.StatusCode, err\n\t}\n\n\tif c.config.Verbose {\n\t\tif len(body.Bytes()) > 0 {\n\t\t\tfmt.Printf(\"Response Body: %s\\n\", body.String())\n\t\t}\n\t}\n\n\treturn respBody, resp.StatusCode, nil\n}\n<commit_msg>fix(sdk): stream should return original error (#5652)<commit_after>package cdsclient\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"regexp\"\n\t\"runtime\/pprof\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/ovh\/cds\/cli\"\n\t\"github.com\/ovh\/cds\/sdk\/telemetry\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n\n\t\"github.com\/ovh\/cds\/sdk\"\n)\n\nconst (\n\t\/\/ RequestedIfModifiedSinceHeader is used as HTTP header\n\tRequestedIfModifiedSinceHeader = \"If-Modified-Since\"\n\t\/\/ ResponseAPITimeHeader is used as HTTP header\n\tResponseAPITimeHeader = \"X-Api-Time\"\n\t\/\/ ResponseAPINanosecondsTimeHeader is used as HTTP header\n\tResponseAPINanosecondsTimeHeader = \"X-Api-Nanoseconds-Time\"\n\t\/\/ ResponseEtagHeader is used as HTTP header\n\tResponseEtagHeader = \"Etag\"\n\t\/\/ ResponseProcessTimeHeader is used as HTTP header\n\tResponseProcessTimeHeader = \"X-Api-Process-Time\"\n)\n\n\/\/ RequestModifier is used to modify behavior of Request and Steam functions\ntype RequestModifier func(req *http.Request)\n\n\/\/ HTTPClient is a interface for HTTPClient mock\ntype HTTPClient interface {\n\tDo(*http.Request) (*http.Response, error)\n}\n\n\/\/ SetHeader modify headers of http.Request\nfunc SetHeader(key, value string) RequestModifier {\n\treturn func(req *http.Request) {\n\t\treq.Header.Set(key, value)\n\t}\n}\n\n\/\/ WithQueryParameter add query parameters to your http.Request\nfunc WithQueryParameter(key, value string) RequestModifier {\n\treturn func(req *http.Request) {\n\t\tq := req.URL.Query()\n\t\tq.Set(key, value)\n\t\treq.URL.RawQuery = q.Encode()\n\t}\n}\n\n\/\/ PostJSON post the *in* struct as json. If set, it unmarshalls the response to *out*\nfunc (c *client) PostJSON(ctx context.Context, path string, in interface{}, out interface{}, mods ...RequestModifier) (int, error) {\n\t_, _, code, err := c.RequestJSON(ctx, http.MethodPost, path, in, out, mods...)\n\treturn code, err\n}\n\n\/\/ PostJSON ut the *in* struct as json. If set, it unmarshalls the response to *out*\nfunc (c *client) PutJSON(ctx context.Context, path string, in interface{}, out interface{}, mods ...RequestModifier) (int, error) {\n\t_, _, code, err := c.RequestJSON(ctx, http.MethodPut, path, in, out, mods...)\n\treturn code, err\n}\n\n\/\/ GetJSON get the requested path If set, it unmarshalls the response to *out*\nfunc (c *client) GetJSON(ctx context.Context, path string, out interface{}, mods ...RequestModifier) (int, error) {\n\t_, _, code, err := c.RequestJSON(ctx, http.MethodGet, path, nil, out, mods...)\n\treturn code, err\n}\n\n\/\/ GetJSONWithHeaders get the requested path If set, it unmarshalls the response to *out* and return response headers\nfunc (c *client) GetJSONWithHeaders(path string, out interface{}, mods ...RequestModifier) (http.Header, int, error) {\n\t_, header, code, err := c.RequestJSON(context.Background(), http.MethodGet, path, nil, out, mods...)\n\treturn header, code, err\n}\n\n\/\/ DeleteJSON deletes the requested path If set, it unmarshalls the response to *out*\nfunc (c *client) DeleteJSON(ctx context.Context, path string, out interface{}, mods ...RequestModifier) (int, error) {\n\t_, _, code, err := c.RequestJSON(ctx, http.MethodDelete, path, nil, out, mods...)\n\treturn code, err\n}\n\n\/\/ RequestJSON does a request with the *in* struct as json. If set, it unmarshalls the response to *out*\nfunc (c *client) RequestJSON(ctx context.Context, method, path string, in interface{}, out interface{}, mods ...RequestModifier) ([]byte, http.Header, int, error) {\n\tvar b = []byte{}\n\tvar err error\n\n\tif in != nil {\n\t\tb, err = json.Marshal(in)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, sdk.WithStack(err)\n\t\t}\n\t}\n\n\tvar body io.Reader\n\tif len(b) > 0 {\n\t\tbody = bytes.NewBuffer(b)\n\t}\n\n\tres, header, code, err := c.Request(ctx, method, path, body, mods...)\n\tif err != nil {\n\t\treturn nil, nil, code, sdk.WithStack(err)\n\t}\n\n\tif code >= 400 {\n\t\tif err := sdk.DecodeError(res); err != nil {\n\t\t\treturn res, nil, code, err\n\t\t}\n\t\treturn res, nil, code, sdk.WithStack(fmt.Errorf(\"HTTP %d\", code))\n\t}\n\n\tif code == 204 {\n\t\treturn res, header, code, nil\n\t}\n\n\tif out != nil {\n\t\tif err := json.Unmarshal(res, out); err != nil {\n\t\t\treturn res, nil, code, sdk.WithStack(err)\n\t\t}\n\t}\n\n\treturn res, header, code, nil\n}\n\n\/\/ Request executes an authentificated HTTP request on $path given $method and $args\nfunc (c *client) Request(ctx context.Context, method string, path string, body io.Reader, mods ...RequestModifier) ([]byte, http.Header, int, error) {\n\trespBody, respHeader, code, err := c.Stream(ctx, method, path, body, false, mods...)\n\tif err != nil {\n\t\treturn nil, nil, 0, sdk.WithStack(err)\n\t}\n\tdefer func() {\n\t\t\/\/ Drain and close the body to let the Transport reuse the connection\n\t\t_, _ = io.Copy(ioutil.Discard, respBody)\n\t\t_ = respBody.Close()\n\t}()\n\n\tvar bodyBtes []byte\n\tbodyBtes, err = ioutil.ReadAll(respBody)\n\tif err != nil {\n\t\treturn nil, nil, code, sdk.WithStack(err)\n\t}\n\n\tif c.config.Verbose {\n\t\tif len(bodyBtes) > 0 {\n\t\t\tlog.Printf(\"Response Body: %s\\n\", bodyBtes)\n\t\t}\n\t}\n\n\tif code >= 400 {\n\t\tif err := sdk.DecodeError(bodyBtes); err != nil {\n\t\t\treturn bodyBtes, nil, code, sdk.WithStack(err)\n\t\t}\n\t\treturn bodyBtes, nil, code, sdk.WithStack(fmt.Errorf(\"HTTP %d\", code))\n\t}\n\n\treturn bodyBtes, respHeader, code, nil\n}\n\n\/\/ signin route pattern\n\nvar signinRouteRegexp = regexp.MustCompile(`\\\/auth\\\/consumer\\\/.*\\\/signin`)\n\nfunc extractBodyErrorFromResponse(r *http.Response) error {\n\tbody, _ := ioutil.ReadAll(r.Body)\n\tr.Body.Close() \/\/ nolint\n\tif err := sdk.DecodeError(body); err != nil {\n\t\treturn sdk.WithStack(err)\n\t}\n\treturn sdk.WithStack(fmt.Errorf(\"HTTP %d\", r.StatusCode))\n}\n\n\/\/ Stream makes an authenticated http request and return io.ReadCloser\nfunc (c *client) Stream(ctx context.Context, method string, path string, body io.Reader, noTimeout bool, mods ...RequestModifier) (io.ReadCloser, http.Header, int, error) {\n\t\/\/ Checks that current session_token is still valid\n\t\/\/ If not, challenge a new one against the authenticationToken\n\tvar checkToken = !strings.Contains(path, \"\/auth\/consumer\/builtin\/signin\") &&\n\t\t!strings.Contains(path, \"\/auth\/consumer\/local\/signin\") &&\n\t\t!strings.Contains(path, \"\/auth\/consumer\/local\/signup\") &&\n\t\t!strings.Contains(path, \"\/auth\/consumer\/local\/verify\") &&\n\t\t!strings.Contains(path, \"\/auth\/consumer\/worker\/signin\")\n\n\tif checkToken && !c.config.HasValidSessionToken() && c.config.BuitinConsumerAuthenticationToken != \"\" {\n\t\tif c.config.Verbose {\n\t\t\tlog.Printf(\"session token invalid: (%s). Relogin...\\n\", c.config.SessionToken)\n\t\t}\n\t\tresp, err := c.AuthConsumerSignin(sdk.ConsumerBuiltin, sdk.AuthConsumerSigninRequest{\"token\": c.config.BuitinConsumerAuthenticationToken})\n\t\tif err != nil {\n\t\t\treturn nil, nil, -1, sdk.WithStack(err)\n\t\t}\n\t\tif c.config.Verbose {\n\t\t\tlog.Println(\"jwt: \", sdk.StringFirstN(resp.Token, 12))\n\t\t}\n\t\tc.config.SessionToken = resp.Token\n\t}\n\n\tlabels := pprof.Labels(\"path\", path, \"method\", method)\n\tctx = pprof.WithLabels(ctx, labels)\n\tpprof.SetGoroutineLabels(ctx)\n\n\t\/\/ In case where the given reader is not a ReadSeeker we should store the body in ram to retry http request\n\tvar bodyBytes []byte\n\tvar err error\n\tif _, ok := body.(io.ReadSeeker); !ok && body != nil {\n\t\tbodyBytes, err = ioutil.ReadAll(body)\n\t\tif err != nil {\n\t\t\treturn nil, nil, 0, sdk.WithStack(err)\n\t\t}\n\t}\n\n\tvar url string\n\tif strings.HasPrefix(path, \"http\") {\n\t\turl = path\n\t} else {\n\t\turl = c.config.Host + path\n\t}\n\n\tvar savederror error\n\tfor i := 0; i <= c.config.Retry; i++ {\n\t\tvar req *http.Request\n\t\tvar requestError error\n\t\tif rs, ok := body.(io.ReadSeeker); ok {\n\t\t\tif _, err := rs.Seek(0, 0); err != nil {\n\t\t\t\treturn nil, nil, 0, sdk.WrapError(savederror, \"request failed after %d retries: %v\", i, err)\n\t\t\t}\n\t\t\treq, requestError = http.NewRequest(method, url, body)\n\t\t} else {\n\t\t\treq, requestError = http.NewRequest(method, url, bytes.NewBuffer(bodyBytes))\n\t\t}\n\t\tif requestError != nil {\n\t\t\tsavederror = sdk.WithStack(requestError)\n\t\t\tcontinue\n\t\t}\n\n\t\treq = req.WithContext(ctx)\n\t\tdate := sdk.FormatDateRFC5322(time.Now())\n\t\treq.Header.Set(\"Date\", date)\n\t\treq.Header.Set(\"X-CDS-RemoteTime\", date)\n\n\t\tif c.config.Verbose {\n\t\t\tlog.Printf(\"Stream > context> %s\\n\", telemetry.DumpContext(ctx))\n\t\t}\n\t\tspanCtx, ok := telemetry.ContextToSpanContext(ctx)\n\t\tif ok {\n\t\t\ttelemetry.DefaultFormat.SpanContextToRequest(spanCtx, req)\n\t\t}\n\n\t\tfor i := range mods {\n\t\t\tif mods[i] != nil {\n\t\t\t\tmods[i](req)\n\t\t\t}\n\t\t}\n\n\t\tif req.Header.Get(\"Content-Type\") == \"\" {\n\t\t\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\t\t}\n\n\t\treq.Header.Set(\"Connection\", \"close\")\n\n\t\t\/\/No auth on signing routes or on url that is not cds configured in config.Host\n\t\tif strings.HasPrefix(url, c.config.Host) && !signinRouteRegexp.MatchString(path) {\n\t\t\tif _, _, err := new(jwt.Parser).ParseUnverified(c.config.SessionToken, &sdk.AuthSessionJWTClaims{}); err == nil {\n\t\t\t\tif c.config.Verbose {\n\t\t\t\t\tlog.Println(\"JWT recognized\")\n\t\t\t\t}\n\t\t\t\tauth := \"Bearer \" + c.config.SessionToken\n\t\t\t\treq.Header.Add(\"Authorization\", auth)\n\t\t\t}\n\t\t}\n\n\t\tif c.config.Verbose {\n\t\t\tlog.Println(cli.Green(\"********REQUEST**********\"))\n\t\t\tdmp, _ := httputil.DumpRequestOut(req, true)\n\t\t\tlog.Printf(\"%s\", string(dmp))\n\t\t\tlog.Println(cli.Green(\"**************************\"))\n\t\t}\n\n\t\tvar errDo error\n\t\tvar resp *http.Response\n\t\tif noTimeout {\n\t\t\tresp, errDo = c.httpSSEClient.Do(req)\n\t\t} else {\n\t\t\tresp, errDo = c.httpClient.Do(req)\n\t\t}\n\t\tif errDo != nil {\n\t\t\tsavederror = sdk.WithStack(errDo)\n\t\t\tcontinue\n\t\t}\n\n\t\tif c.config.Verbose {\n\t\t\tlog.Println(cli.Yellow(\"********RESPONSE**********\"))\n\t\t\tdmp, _ := httputil.DumpResponse(resp, true)\n\t\t\tlog.Printf(\"%s\", string(dmp))\n\t\t\tlog.Println(cli.Yellow(\"**************************\"))\n\t\t}\n\n\t\tif resp.StatusCode == 401 {\n\t\t\tc.config.SessionToken = \"\"\n\t\t}\n\n\t\tif resp.StatusCode == 409 || resp.StatusCode > 500 {\n\t\t\ttime.Sleep(250 * time.Millisecond)\n\t\t\tsavederror = extractBodyErrorFromResponse(resp)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ if no request error by status > 500, check CDS error\n\t\t\/\/ if there is a CDS errors, return it\n\t\tif resp.StatusCode == 500 {\n\t\t\treturn nil, resp.Header, resp.StatusCode, extractBodyErrorFromResponse(resp)\n\t\t}\n\n\t\treturn resp.Body, resp.Header, resp.StatusCode, nil\n\t}\n\n\treturn nil, nil, 0, sdk.WrapError(savederror, \"request failed after %d retries\", c.config.Retry)\n}\n\n\/\/ UploadMultiPart upload multipart\nfunc (c *client) UploadMultiPart(method string, path string, body *bytes.Buffer, mods ...RequestModifier) ([]byte, int, error) {\n\t\/\/ Checks that current session_token is still valid\n\t\/\/ If not, challenge a new one against the authenticationToken\n\tif !c.config.HasValidSessionToken() && c.config.BuitinConsumerAuthenticationToken != \"\" {\n\t\tresp, err := c.AuthConsumerSignin(sdk.ConsumerBuiltin, sdk.AuthConsumerSigninRequest{\"token\": c.config.BuitinConsumerAuthenticationToken})\n\t\tif err != nil {\n\t\t\treturn nil, -1, err\n\t\t}\n\t\tc.config.SessionToken = resp.Token\n\t}\n\n\tvar req *http.Request\n\treq, errRequest := http.NewRequest(method, c.config.Host+path, body)\n\tif errRequest != nil {\n\t\treturn nil, 0, errRequest\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application\/octet-stream\")\n\treq.Header.Set(\"Connection\", \"close\")\n\n\tfor i := range mods {\n\t\tmods[i](req)\n\t}\n\n\t\/\/No auth on signing routes\n\tif !signinRouteRegexp.MatchString(path) {\n\t\tif _, _, err := new(jwt.Parser).ParseUnverified(c.config.SessionToken, &sdk.AuthSessionJWTClaims{}); err == nil {\n\t\t\tif c.config.Verbose {\n\t\t\t\tfmt.Println(\"JWT recognized\")\n\t\t\t}\n\t\t\tauth := \"Bearer \" + c.config.SessionToken\n\t\t\treq.Header.Add(\"Authorization\", auth)\n\t\t}\n\t}\n\n\tresp, err := c.httpSSEClient.Do(req)\n\tif err != nil {\n\t\treturn nil, 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif c.config.Verbose {\n\t\tfmt.Printf(\"Response Status: %s\\n\", resp.Status)\n\t\tfmt.Printf(\"Request path: %s\\n\", c.config.Host+path)\n\t\tfmt.Printf(\"Request Headers: %s\\n\", req.Header)\n\t\tfmt.Printf(\"Response Headers: %s\\n\", resp.Header)\n\t}\n\n\tif resp.StatusCode == 401 {\n\t\tc.config.SessionToken = \"\"\n\t}\n\n\tvar respBody []byte\n\trespBody, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, resp.StatusCode, err\n\t}\n\n\tif c.config.Verbose {\n\t\tif len(body.Bytes()) > 0 {\n\t\t\tfmt.Printf(\"Response Body: %s\\n\", body.String())\n\t\t}\n\t}\n\n\treturn respBody, resp.StatusCode, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package aws provides core functionality for making requests to AWS services.\npackage aws\n\n\/\/ SDKName is the name of this AWS SDK\nconst SDKName = \"aws-sdk-go\"\n\n\/\/ SDKVersion is the version of this SDK\nconst SDKVersion = \"0.7.2\"\n<commit_msg>Tag release v0.7.3<commit_after>\/\/ Package aws provides core functionality for making requests to AWS services.\npackage aws\n\n\/\/ SDKName is the name of this AWS SDK\nconst SDKName = \"aws-sdk-go\"\n\n\/\/ SDKVersion is the version of this SDK\nconst SDKVersion = \"0.7.3\"\n<|endoftext|>"}
{"text":"<commit_before>package azure\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n)\n\n\/\/ String returns a pointer to the input string. This is useful when initializing\n\/\/ structures.\nfunc String(input string) *string {\n\treturn &input\n}\n\n\/\/ isSuccessCode returns true for 200-range numbers which usually denote\n\/\/ that an HTTP request was successful\nfunc isSuccessCode(statusCode int) bool {\n\tif statusCode >= http.StatusOK && statusCode < http.StatusMultipleChoices {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ unmarshalFlattenPropertiesAndClose returns a map[string]interface{} with the\n\/\/ \"properties\" key flattened for use with mapstructure. It closes the Body reader of\n\/\/ the http.Response passed in.\nfunc unmarshalFlattenPropertiesAndClose(response *http.Response) (map[string]interface{}, error) {\n\treturn unmarshalNested(response, \"properties\")\n}\n\n\/\/ unmarshalFlattenErrorAndClose returns a map[string]interface{} with the\n\/\/ \"error\" key flattened for use with mapstructure. It closes the Body reader of\n\/\/ the http.Response passed in.\nfunc unmarshalFlattenErrorAndClose(response *http.Response) (map[string]interface{}, error) {\n\treturn unmarshalNested(response, \"error\")\n}\n\nfunc unmarshalNested(response *http.Response, key string) (map[string]interface{}, error) {\n\tdefer response.Body.Close()\n\n\tvar unmarshalled map[string]interface{}\n\tdecoder := json.NewDecoder(response.Body)\n\n\terr := decoder.Decode(&unmarshalled)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif properties, hasProperties := unmarshalled[key]; hasProperties {\n\t\tif propertiesMap, ok := properties.(map[string]interface{}); ok {\n\t\t\tfor k, v := range propertiesMap {\n\t\t\t\tunmarshalled[k] = v\n\t\t\t}\n\n\t\t\tdelete(propertiesMap, key)\n\t\t}\n\t}\n\n\treturn unmarshalled, nil\n\n}\n<commit_msg>Add wrappers for obtaining primitive pointers<commit_after>package azure\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n)\n\n\/\/ String returns a pointer to the input string. This is useful when initializing\n\/\/ structures.\nfunc String(input string) *string {\n\treturn &input\n}\n\n\/\/ Int32 returns a pointer to the input int32. This is useful when initializing\n\/\/ structures.\nfunc Int32(input int32) *int32 {\n\treturn &input\n}\n\n\/\/ Int64 returns a pointer to the input int64. This is useful when initializing\n\/\/ structures.\nfunc Int64(input int64) *int64 {\n\treturn &input\n}\n\n\/\/ Bool returns a pointer to the input bool. This is useful when initializing\n\/\/ structures.\nfunc Bool(input bool) *bool {\n\treturn &input\n}\n\n\/\/ isSuccessCode returns true for 200-range numbers which usually denote\n\/\/ that an HTTP request was successful\nfunc isSuccessCode(statusCode int) bool {\n\tif statusCode >= http.StatusOK && statusCode < http.StatusMultipleChoices {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ unmarshalFlattenPropertiesAndClose returns a map[string]interface{} with the\n\/\/ \"properties\" key flattened for use with mapstructure. It closes the Body reader of\n\/\/ the http.Response passed in.\nfunc unmarshalFlattenPropertiesAndClose(response *http.Response) (map[string]interface{}, error) {\n\treturn unmarshalNested(response, \"properties\")\n}\n\n\/\/ unmarshalFlattenErrorAndClose returns a map[string]interface{} with the\n\/\/ \"error\" key flattened for use with mapstructure. It closes the Body reader of\n\/\/ the http.Response passed in.\nfunc unmarshalFlattenErrorAndClose(response *http.Response) (map[string]interface{}, error) {\n\treturn unmarshalNested(response, \"error\")\n}\n\nfunc unmarshalNested(response *http.Response, key string) (map[string]interface{}, error) {\n\tdefer response.Body.Close()\n\n\tvar unmarshalled map[string]interface{}\n\tdecoder := json.NewDecoder(response.Body)\n\n\terr := decoder.Decode(&unmarshalled)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif properties, hasProperties := unmarshalled[key]; hasProperties {\n\t\tif propertiesMap, ok := properties.(map[string]interface{}); ok {\n\t\t\tfor k, v := range propertiesMap {\n\t\t\t\tunmarshalled[k] = v\n\t\t\t}\n\n\t\t\tdelete(propertiesMap, key)\n\t\t}\n\t}\n\n\treturn unmarshalled, nil\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\ntype basicEditor struct {\n\tpos int\n\tbuf []rune\n}\n\n\/\/ move moves the position.\n\/\/ Given invalid position, move sets the position at the end of the buffer.\nfunc (e *basicEditor) move(to int) {\n\tswitch {\n\tcase to >= len(e.buf):\n\t\te.pos = len(e.buf)\n\tcase to <= 0:\n\t\te.pos = 0\n\tdefault:\n\t\te.pos = to\n\t}\n}\n<commit_msg>Update the comment of e.move<commit_after>package main\n\ntype basicEditor struct {\n\tpos int\n\tbuf []rune\n}\n\n\/\/ move moves the position.\n\/\/ Given a invalid position, move sets the position at the end of the buffer.\n\/\/ Valid positions are in range [0, len(e.buf)].\nfunc (e *basicEditor) move(to int) {\n\tswitch {\n\tcase to >= len(e.buf):\n\t\te.pos = len(e.buf)\n\tcase to <= 0:\n\t\te.pos = 0\n\tdefault:\n\t\te.pos = to\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/oxtoacart\/framed\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime\/pprof\"\n\t\"sync\"\n)\n\nconst (\n\tserverAddr = \"127.0.0.1:10081\"\n)\n\nvar (\n\tmode = flag.String(\"mode\", \"server\", \"Mode (server or client)\")\n\twg   sync.WaitGroup\n)\n\nfunc main() {\n\truntime.GOMAXPROCS(1)\n\tflag.Parse()\n\tfile, err := os.Create(fmt.Sprintf(\"\/tmp\/framed_profile_%s\", *mode))\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to create CPU profile file: %s\", err)\n\t}\n\tpprof.StartCPUProfile(file)\n\tdefer pprof.StopCPUProfile()\n\tif *mode == \"client\" {\n\t\tclient()\n\t} else {\n\t\tserver()\n\t}\n}\n\nfunc server() {\n\tlog.Printf(\"Starting server at %s\", serverAddr)\n\tif listener, err := net.Listen(\"tcp\", serverAddr); err != nil {\n\t\tlog.Fatalf(\"Unable to listen: %s\", err)\n\t} else {\n\t\tfor {\n\t\t\tif conn, err := listener.Accept(); err != nil {\n\t\t\t\tlog.Printf(\"Unable to accept: %s\", err)\n\t\t\t} else {\n\t\t\t\tf := framed.NewFramed(conn)\n\t\t\t\tgo func() {\n\t\t\t\t\tif frame, err := f.ReadInitial(); err != nil {\n\t\t\t\t\t\tlog.Printf(\"Unable to read initial frame: %s\", frame)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor {\n\t\t\t\t\t\t\tif err := frame.CopyTo(conn); err != nil {\n\t\t\t\t\t\t\t\tpprof.StopCPUProfile()\n\t\t\t\t\t\t\t\tlog.Fatalf(\"Unable to copy: %s\", err)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tif frame, err = frame.Next(); err != nil {\n\t\t\t\t\t\t\t\t\tlog.Fatalf(\"Unable to read next frame\")\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}()\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc client() {\n\tfor i := 0; i < 1; i++ {\n\t\twg.Add(1)\n\t\tgo doClient()\n\t}\n\twg.Wait()\n}\n\nfunc doClient() {\n\tlog.Printf(\"Starting client connection to server at %s\", serverAddr)\n\theader := []byte{}\n\tdata := []byte(\"Hell World\")\n\tif conn, err := net.Dial(\"tcp\", serverAddr); err != nil {\n\t\tlog.Fatalf(\"Unable to dial server: %s\", err)\n\t} else {\n\t\tf := framed.NewFramed(conn)\n\t\t\/\/ Read\n\t\tgo io.Copy(ioutil.Discard, conn)\n\n\t\t\/\/ Write\n\t\tfor {\n\t\t\tif err := f.WriteFrame(header, data); err != nil {\n\t\t\t\tlog.Fatalf(\"Unable to write frame: %s\", err)\n\t\t\t}\n\t\t}\n\t}\n\twg.Done()\n}\n<commit_msg>Added ability to run without framing<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/oxtoacart\/framed\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime\/pprof\"\n\t\"sync\"\n)\n\nconst (\n\tserverAddr = \"127.0.0.1:10081\"\n)\n\nvar (\n\tmode        = flag.String(\"mode\", \"server\", \"Mode (server or client)\")\n\tshouldFrame = flag.Bool(\"framed\", false, \"Whether or not run in framed mode\")\n\twg          sync.WaitGroup\n)\n\nfunc main() {\n\truntime.GOMAXPROCS(1)\n\tflag.Parse()\n\tfile, err := os.Create(fmt.Sprintf(\"\/tmp\/framed_profile_%s\", *mode))\n\tif err != nil {\n\t\tlog.Fatal(\"Unable to create CPU profile file: %s\", err)\n\t}\n\tpprof.StartCPUProfile(file)\n\tdefer pprof.StopCPUProfile()\n\tif *mode == \"client\" {\n\t\tclient()\n\t} else {\n\t\tserver()\n\t}\n}\n\nfunc server() {\n\tlog.Printf(\"Starting server at %s\", serverAddr)\n\tif listener, err := net.Listen(\"tcp\", serverAddr); err != nil {\n\t\tlog.Fatalf(\"Unable to listen: %s\", err)\n\t} else {\n\t\tfor {\n\t\t\tif conn, err := listener.Accept(); err != nil {\n\t\t\t\tlog.Printf(\"Unable to accept: %s\", err)\n\t\t\t} else {\n\t\t\t\tif *shouldFrame {\n\t\t\t\t\tf := framed.NewFramed(conn)\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tif frame, err := f.ReadInitial(); err != nil {\n\t\t\t\t\t\t\tlog.Printf(\"Unable to read initial frame: %s\", frame)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfor {\n\t\t\t\t\t\t\t\tif err := frame.CopyTo(conn); err != nil {\n\t\t\t\t\t\t\t\t\tpprof.StopCPUProfile()\n\t\t\t\t\t\t\t\t\tlog.Fatalf(\"Unable to copy: %s\", err)\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif frame, err = frame.Next(); err != nil {\n\t\t\t\t\t\t\t\t\t\tlog.Fatalf(\"Unable to read next frame\")\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}()\n\t\t\t\t} else {\n\t\t\t\t\tgo io.Copy(conn, conn)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc client() {\n\tfor i := 0; i < 1; i++ {\n\t\twg.Add(1)\n\t\tgo doClient()\n\t}\n\twg.Wait()\n}\n\nfunc doClient() {\n\tlog.Printf(\"Starting client connection to server at %s\", serverAddr)\n\theader := []byte{}\n\tdata := []byte(\"Hell World\")\n\tif conn, err := net.Dial(\"tcp\", serverAddr); err != nil {\n\t\tlog.Fatalf(\"Unable to dial server: %s\", err)\n\t} else {\n\t\tf := framed.NewFramed(conn)\n\t\t\/\/ Read\n\t\tgo io.Copy(ioutil.Discard, conn)\n\n\t\t\/\/ Write\n\t\tfor {\n\t\t\tif err := f.WriteFrame(header, data); err != nil {\n\t\t\t\tlog.Fatalf(\"Unable to write frame: %s\", err)\n\t\t\t}\n\t\t}\n\t}\n\twg.Done()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Jeff Foley. All rights reserved.\n\/\/ Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n\npackage sources\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/OWASP\/Amass\/amass\/core\"\n\t\"github.com\/OWASP\/Amass\/amass\/utils\"\n)\n\n\/\/ VirusTotal is the Service that handles access to the VirusTotal data source.\ntype VirusTotal struct {\n\tcore.BaseService\n\n\tAPI        *core.APIKey\n\tSourceType string\n\n\thaveAPIKey bool\n}\n\n\/\/ NewVirusTotal returns he object initialized, but not yet started.\nfunc NewVirusTotal(config *core.Config, bus *core.EventBus) *VirusTotal {\n\tv := &VirusTotal{\n\t\tSourceType: core.API,\n\t\thaveAPIKey: true,\n\t}\n\n\tv.BaseService = *core.NewBaseService(v, \"VirusTotal\", config, bus)\n\treturn v\n}\n\n\/\/ OnStart implements the Service interface\nfunc (v *VirusTotal) OnStart() error {\n\tv.BaseService.OnStart()\n\n\tv.API = v.Config().GetAPIKey(v.String())\n\tif v.API == nil || v.API.Key == \"\" {\n\t\tv.haveAPIKey = false\n\t\tv.Config().Log.Printf(\"%s: API key data was not provided\", v.String())\n\t}\n\n\tgo v.processRequests()\n\treturn nil\n}\n\nfunc (v *VirusTotal) processRequests() {\n\tfor {\n\t\tselect {\n\t\tcase <-v.Quit():\n\t\t\treturn\n\t\tcase req := <-v.RequestChan():\n\t\t\tif v.Config().IsDomainInScope(req.Domain) {\n\t\t\t\tif v.haveAPIKey {\n\t\t\t\t\tv.apiQuery(req.Domain)\n\t\t\t\t} else {\n\t\t\t\t\tv.regularQuery(req.Domain)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (v *VirusTotal) apiQuery(domain string) {\n\turl := v.apiURL(domain)\n\theaders := map[string]string{\"Content-Type\": \"application\/json\"}\n\tpage, err := utils.RequestWebPage(url, nil, headers, \"\", \"\")\n\tif err != nil {\n\t\tv.Config().Log.Printf(\"%s: %s: %v\", v.String(), url, err)\n\t\treturn\n\t}\n\n\t\/\/ Extract the subdomain names from the results\n\tvar m struct {\n\t\tResponseCode int      `json:\"response_code\"`\n\t\tMessage      string   `json:\"verbose_msg\"`\n\t\tSubdomains   []string `json:\"subdomains\"`\n\t\tResolutions  []struct {\n\t\t\tIP string `json:\"ip_address\"`\n\t\t} `json:\"resolutions\"`\n\t}\n\tif err := json.Unmarshal([]byte(page), &m); err != nil {\n\t\treturn\n\t}\n\n\tif m.ResponseCode != 1 {\n\t\tv.Config().Log.Printf(\"%s: %s: Response code %d: %s\", v.String(), url, m.ResponseCode, m.Message)\n\t\treturn\n\t}\n\n\tv.SetActive()\n\tre := v.Config().DomainRegex(domain)\n\tfor _, sub := range m.Subdomains {\n\t\ts := strings.ToLower(sub)\n\n\t\tif !re.MatchString(s) {\n\t\t\tcontinue\n\t\t}\n\n\t\tv.Bus().Publish(core.NewNameTopic, &core.Request{\n\t\t\tName:   s,\n\t\t\tDomain: domain,\n\t\t\tTag:    v.SourceType,\n\t\t\tSource: v.String(),\n\t\t})\n\t}\n\n\tfor _, res := range m.Resolutions {\n\t\tv.Bus().Publish(core.NewNameTopic, &core.Request{\n\t\t\tAddress: res.IP,\n\t\t\tDomain:  domain,\n\t\t\tTag:     v.SourceType,\n\t\t\tSource:  v.String(),\n\t\t})\n\t}\n}\n\nfunc (v *VirusTotal) apiURL(domain string) string {\n\tu, _ := url.Parse(\"https:\/\/www.virustotal.com\/vtapi\/v2\/domain\/report\")\n\tu.RawQuery = url.Values{\"apikey\": {v.API.Key}, \"domain\": {domain}}.Encode()\n\n\treturn u.String()\n}\n\nfunc (v *VirusTotal) regularQuery(domain string) {\n\turl := v.getURL(domain)\n\theaders := map[string]string{\"Content-Type\": \"application\/json\"}\n\tpage, err := utils.RequestWebPage(url, nil, headers, \"\", \"\")\n\tif err != nil {\n\t\tv.Config().Log.Printf(\"%s: %s: %v\", v.String(), url, err)\n\t\treturn\n\t}\n\n\t\/\/ Extract the subdomain names from the results\n\tvar m struct {\n\t\tData []struct {\n\t\t\tID   string `json:\"id\"`\n\t\t\tType string `json:\"type\"`\n\t\t} `json:\"data\"`\n\t}\n\tif err := json.Unmarshal([]byte(page), &m); err != nil {\n\t\treturn\n\t}\n\n\tv.SetActive()\n\tre := v.Config().DomainRegex(domain)\n\tfor _, data := range m.Data {\n\t\tif data.Type != \"domain\" || !re.MatchString(data.ID) {\n\t\t\tcontinue\n\t\t}\n\n\t\tv.Bus().Publish(core.NewNameTopic, &core.Request{\n\t\t\tName:   data.ID,\n\t\t\tDomain: domain,\n\t\t\tTag:    v.SourceType,\n\t\t\tSource: v.String(),\n\t\t})\n\t}\n}\n\nfunc (v *VirusTotal) getURL(domain string) string {\n\tformat := \"https:\/\/www.virustotal.com\/ui\/domains\/%s\/subdomains?limit=40\"\n\n\treturn fmt.Sprintf(format, domain)\n}\n<commit_msg>fixed the ability to publish discovered IP addresses<commit_after>\/\/ Copyright 2017 Jeff Foley. All rights reserved.\n\/\/ Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n\npackage sources\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/OWASP\/Amass\/amass\/core\"\n\t\"github.com\/OWASP\/Amass\/amass\/utils\"\n)\n\n\/\/ VirusTotal is the Service that handles access to the VirusTotal data source.\ntype VirusTotal struct {\n\tcore.BaseService\n\n\tAPI        *core.APIKey\n\tSourceType string\n\n\thaveAPIKey bool\n}\n\n\/\/ NewVirusTotal returns he object initialized, but not yet started.\nfunc NewVirusTotal(config *core.Config, bus *core.EventBus) *VirusTotal {\n\tv := &VirusTotal{\n\t\tSourceType: core.API,\n\t\thaveAPIKey: true,\n\t}\n\n\tv.BaseService = *core.NewBaseService(v, \"VirusTotal\", config, bus)\n\treturn v\n}\n\n\/\/ OnStart implements the Service interface\nfunc (v *VirusTotal) OnStart() error {\n\tv.BaseService.OnStart()\n\n\tv.API = v.Config().GetAPIKey(v.String())\n\tif v.API == nil || v.API.Key == \"\" {\n\t\tv.haveAPIKey = false\n\t\tv.Config().Log.Printf(\"%s: API key data was not provided\", v.String())\n\t}\n\n\tgo v.processRequests()\n\treturn nil\n}\n\nfunc (v *VirusTotal) processRequests() {\n\tfor {\n\t\tselect {\n\t\tcase <-v.Quit():\n\t\t\treturn\n\t\tcase req := <-v.RequestChan():\n\t\t\tif v.Config().IsDomainInScope(req.Domain) {\n\t\t\t\tif v.haveAPIKey {\n\t\t\t\t\tv.apiQuery(req.Domain)\n\t\t\t\t} else {\n\t\t\t\t\tv.regularQuery(req.Domain)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (v *VirusTotal) apiQuery(domain string) {\n\turl := v.apiURL(domain)\n\theaders := map[string]string{\"Content-Type\": \"application\/json\"}\n\tpage, err := utils.RequestWebPage(url, nil, headers, \"\", \"\")\n\tif err != nil {\n\t\tv.Config().Log.Printf(\"%s: %s: %v\", v.String(), url, err)\n\t\treturn\n\t}\n\n\t\/\/ Extract the subdomain names from the results\n\tvar m struct {\n\t\tResponseCode int      `json:\"response_code\"`\n\t\tMessage      string   `json:\"verbose_msg\"`\n\t\tSubdomains   []string `json:\"subdomains\"`\n\t\tResolutions  []struct {\n\t\t\tIP string `json:\"ip_address\"`\n\t\t} `json:\"resolutions\"`\n\t}\n\tif err := json.Unmarshal([]byte(page), &m); err != nil {\n\t\treturn\n\t}\n\n\tif m.ResponseCode != 1 {\n\t\tv.Config().Log.Printf(\"%s: %s: Response code %d: %s\", v.String(), url, m.ResponseCode, m.Message)\n\t\treturn\n\t}\n\n\tv.SetActive()\n\tre := v.Config().DomainRegex(domain)\n\tfor _, sub := range m.Subdomains {\n\t\ts := strings.ToLower(sub)\n\n\t\tif !re.MatchString(s) {\n\t\t\tcontinue\n\t\t}\n\n\t\tv.Bus().Publish(core.NewNameTopic, &core.Request{\n\t\t\tName:   s,\n\t\t\tDomain: domain,\n\t\t\tTag:    v.SourceType,\n\t\t\tSource: v.String(),\n\t\t})\n\t}\n\n\tfor _, res := range m.Resolutions {\n\t\tv.Bus().Publish(core.NewAddrTopic, &core.Request{\n\t\t\tAddress: res.IP,\n\t\t\tDomain:  domain,\n\t\t\tTag:     v.SourceType,\n\t\t\tSource:  v.String(),\n\t\t})\n\t}\n}\n\nfunc (v *VirusTotal) apiURL(domain string) string {\n\tu, _ := url.Parse(\"https:\/\/www.virustotal.com\/vtapi\/v2\/domain\/report\")\n\tu.RawQuery = url.Values{\"apikey\": {v.API.Key}, \"domain\": {domain}}.Encode()\n\n\treturn u.String()\n}\n\nfunc (v *VirusTotal) regularQuery(domain string) {\n\turl := v.getURL(domain)\n\theaders := map[string]string{\"Content-Type\": \"application\/json\"}\n\tpage, err := utils.RequestWebPage(url, nil, headers, \"\", \"\")\n\tif err != nil {\n\t\tv.Config().Log.Printf(\"%s: %s: %v\", v.String(), url, err)\n\t\treturn\n\t}\n\n\t\/\/ Extract the subdomain names from the results\n\tvar m struct {\n\t\tData []struct {\n\t\t\tID   string `json:\"id\"`\n\t\t\tType string `json:\"type\"`\n\t\t} `json:\"data\"`\n\t}\n\tif err := json.Unmarshal([]byte(page), &m); err != nil {\n\t\treturn\n\t}\n\n\tv.SetActive()\n\tre := v.Config().DomainRegex(domain)\n\tfor _, data := range m.Data {\n\t\tif data.Type != \"domain\" || !re.MatchString(data.ID) {\n\t\t\tcontinue\n\t\t}\n\n\t\tv.Bus().Publish(core.NewNameTopic, &core.Request{\n\t\t\tName:   data.ID,\n\t\t\tDomain: domain,\n\t\t\tTag:    v.SourceType,\n\t\t\tSource: v.String(),\n\t\t})\n\t}\n}\n\nfunc (v *VirusTotal) getURL(domain string) string {\n\tformat := \"https:\/\/www.virustotal.com\/ui\/domains\/%s\/subdomains?limit=40\"\n\n\treturn fmt.Sprintf(format, domain)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015, 2016 Minio, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage minio\n\nimport (\n\t\"bytes\"\n\t\"encoding\/hex\"\n\t\"encoding\/xml\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ Comprehensive put object operation involving multipart resumable uploads.\n\/\/\n\/\/ Following code handles these types of readers.\n\/\/\n\/\/  - *os.File\n\/\/  - *minio.Object\n\/\/  - Any reader which has a method 'ReadAt()'\n\/\/\n\/\/ If we exhaust all the known types, code proceeds to use stream as\n\/\/ is where each part is re-downloaded, checksummed and verified\n\/\/ before upload.\nfunc (c Client) putObjectMultipart(bucketName, objectName string, reader io.Reader, size int64, contentType string, progress io.Reader) (n int64, err error) {\n\tif size > 0 && size > minPartSize {\n\t\t\/\/ Verify if reader is *os.File, then use file system functionalities.\n\t\tif isFile(reader) {\n\t\t\treturn c.putObjectMultipartFromFile(bucketName, objectName, reader.(*os.File), size, contentType, progress)\n\t\t}\n\t\t\/\/ Verify if reader is *minio.Object or io.ReaderAt.\n\t\t\/\/ NOTE: Verification of object is kept for a specific purpose\n\t\t\/\/ while it is going to be duck typed similar to io.ReaderAt.\n\t\t\/\/ It is to indicate that *minio.Object implements io.ReaderAt.\n\t\t\/\/ and such a functionality is used in the subsequent code\n\t\t\/\/ path.\n\t\tif isObject(reader) || isReadAt(reader) {\n\t\t\treturn c.putObjectMultipartFromReadAt(bucketName, objectName, reader.(io.ReaderAt), size, contentType, progress)\n\t\t}\n\t}\n\t\/\/ For any other data size and reader type we do generic multipart\n\t\/\/ approach by staging data in temporary files and uploading them.\n\treturn c.putObjectMultipartStream(bucketName, objectName, reader, size, contentType, progress)\n}\n\n\/\/ putObjectStream uploads files bigger than 5MiB, and also supports\n\/\/ special case where size is unknown i.e '-1'.\nfunc (c Client) putObjectMultipartStream(bucketName, objectName string, reader io.Reader, size int64, contentType string, progress io.Reader) (n int64, err error) {\n\t\/\/ Input validation.\n\tif err := isValidBucketName(bucketName); err != nil {\n\t\treturn 0, err\n\t}\n\tif err := isValidObjectName(objectName); err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ Total data read and written to server. should be equal to 'size' at the end of the call.\n\tvar totalUploadedSize int64\n\n\t\/\/ Complete multipart upload.\n\tvar complMultipartUpload completeMultipartUpload\n\n\t\/\/ A map of all previously uploaded parts.\n\tvar partsInfo = make(map[int]objectPart)\n\n\t\/\/ getUploadID for an object, initiates a new multipart request\n\t\/\/ if it cannot find any previously partially uploaded object.\n\tuploadID, isNew, err := c.getUploadID(bucketName, objectName, contentType)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ If This session is a continuation of a previous session fetch all\n\t\/\/ previously uploaded parts info.\n\tif !isNew {\n\t\t\/\/ Fetch previously uploaded parts and maximum part size.\n\t\tpartsInfo, err = c.listObjectParts(bucketName, objectName, uploadID)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\t\/\/ Calculate the optimal parts info for a given size.\n\ttotalPartsCount, partSize, _, err := optimalPartInfo(size)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ Part number always starts with '1'.\n\tpartNumber := 1\n\n\t\/\/ Initialize a temporary buffer.\n\ttmpBuffer := new(bytes.Buffer)\n\n\tfor partNumber <= totalPartsCount {\n\t\t\/\/ Calculates MD5 and SHA256 sum while copying partSize bytes\n\t\t\/\/ into tmpBuffer.\n\t\tmd5Sum, sha256Sum, prtSize, rErr := c.hashCopyN(tmpBuffer, reader, partSize)\n\t\tif rErr != nil {\n\t\t\tif rErr != io.EOF {\n\t\t\t\treturn 0, rErr\n\t\t\t}\n\t\t}\n\n\t\tvar reader io.Reader\n\t\t\/\/ Update progress reader appropriately to the latest offset\n\t\t\/\/ as we read from the source.\n\t\treader = newHook(tmpBuffer, progress)\n\n\t\t\/\/ Verify if part should be uploaded.\n\t\tif shouldUploadPart(objectPart{\n\t\t\tETag:       hex.EncodeToString(md5Sum),\n\t\t\tPartNumber: partNumber,\n\t\t\tSize:       prtSize,\n\t\t}, partsInfo) {\n\t\t\t\/\/ Proceed to upload the part.\n\t\t\tvar objPart objectPart\n\t\t\tobjPart, err = c.uploadPart(bucketName, objectName, uploadID, reader, partNumber, md5Sum, sha256Sum, prtSize)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Reset the temporary buffer upon any error.\n\t\t\t\ttmpBuffer.Reset()\n\t\t\t\treturn totalUploadedSize, err\n\t\t\t}\n\t\t\t\/\/ Save successfully uploaded part metadata.\n\t\t\tpartsInfo[partNumber] = objPart\n\t\t} else {\n\t\t\t\/\/ Update the progress reader for the skipped part.\n\t\t\tif progress != nil {\n\t\t\t\tif _, err = io.CopyN(ioutil.Discard, progress, prtSize); err != nil {\n\t\t\t\t\treturn totalUploadedSize, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Reset the temporary buffer.\n\t\ttmpBuffer.Reset()\n\n\t\t\/\/ Save successfully uploaded size.\n\t\ttotalUploadedSize += prtSize\n\n\t\t\/\/ For unknown size, Read EOF we break away.\n\t\t\/\/ We do not have to upload till totalPartsCount.\n\t\tif size < 0 && rErr == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Increment part number.\n\t\tpartNumber++\n\t}\n\n\t\/\/ Verify if we uploaded all the data.\n\tif size > 0 {\n\t\tif totalUploadedSize != size {\n\t\t\treturn totalUploadedSize, ErrUnexpectedEOF(totalUploadedSize, size, bucketName, objectName)\n\t\t}\n\t}\n\n\t\/\/ Loop over uploaded parts to save them in a Parts array before completing the multipart request.\n\tfor _, part := range partsInfo {\n\t\tvar complPart completePart\n\t\tcomplPart.ETag = part.ETag\n\t\tcomplPart.PartNumber = part.PartNumber\n\t\tcomplMultipartUpload.Parts = append(complMultipartUpload.Parts, complPart)\n\t}\n\n\tif size > 0 {\n\t\t\/\/ Verify if totalPartsCount is not equal to total list of parts.\n\t\tif totalPartsCount != len(complMultipartUpload.Parts) {\n\t\t\treturn totalUploadedSize, ErrInvalidParts(partNumber, len(complMultipartUpload.Parts))\n\t\t}\n\t}\n\n\t\/\/ Sort all completed parts.\n\tsort.Sort(completedParts(complMultipartUpload.Parts))\n\t_, err = c.completeMultipartUpload(bucketName, objectName, uploadID, complMultipartUpload)\n\tif err != nil {\n\t\treturn totalUploadedSize, err\n\t}\n\n\t\/\/ Return final size.\n\treturn totalUploadedSize, nil\n}\n\n\/\/ initiateMultipartUpload - Initiates a multipart upload and returns an upload ID.\nfunc (c Client) initiateMultipartUpload(bucketName, objectName, contentType string) (initiateMultipartUploadResult, error) {\n\t\/\/ Input validation.\n\tif err := isValidBucketName(bucketName); err != nil {\n\t\treturn initiateMultipartUploadResult{}, err\n\t}\n\tif err := isValidObjectName(objectName); err != nil {\n\t\treturn initiateMultipartUploadResult{}, err\n\t}\n\n\t\/\/ Initialize url queries.\n\turlValues := make(url.Values)\n\turlValues.Set(\"uploads\", \"\")\n\n\tif contentType == \"\" {\n\t\tcontentType = \"application\/octet-stream\"\n\t}\n\n\t\/\/ Set ContentType header.\n\tcustomHeader := make(http.Header)\n\tcustomHeader.Set(\"Content-Type\", contentType)\n\n\treqMetadata := requestMetadata{\n\t\tbucketName:   bucketName,\n\t\tobjectName:   objectName,\n\t\tqueryValues:  urlValues,\n\t\tcustomHeader: customHeader,\n\t}\n\n\t\/\/ Execute POST on an objectName to initiate multipart upload.\n\tresp, err := c.executeMethod(\"POST\", reqMetadata)\n\tdefer closeResponse(resp)\n\tif err != nil {\n\t\treturn initiateMultipartUploadResult{}, err\n\t}\n\tif resp != nil {\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn initiateMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName)\n\t\t}\n\t}\n\t\/\/ Decode xml for new multipart upload.\n\tinitiateMultipartUploadResult := initiateMultipartUploadResult{}\n\terr = xmlDecoder(resp.Body, &initiateMultipartUploadResult)\n\tif err != nil {\n\t\treturn initiateMultipartUploadResult, err\n\t}\n\treturn initiateMultipartUploadResult, nil\n}\n\n\/\/ uploadPart - Uploads a part in a multipart upload.\nfunc (c Client) uploadPart(bucketName, objectName, uploadID string, reader io.Reader, partNumber int, md5Sum, sha256Sum []byte, size int64) (objectPart, error) {\n\t\/\/ Input validation.\n\tif err := isValidBucketName(bucketName); err != nil {\n\t\treturn objectPart{}, err\n\t}\n\tif err := isValidObjectName(objectName); err != nil {\n\t\treturn objectPart{}, err\n\t}\n\tif size > maxPartSize {\n\t\treturn objectPart{}, ErrEntityTooLarge(size, maxPartSize, bucketName, objectName)\n\t}\n\tif size <= -1 {\n\t\treturn objectPart{}, ErrEntityTooSmall(size, bucketName, objectName)\n\t}\n\tif partNumber <= 0 {\n\t\treturn objectPart{}, ErrInvalidArgument(\"Part number cannot be negative or equal to zero.\")\n\t}\n\tif uploadID == \"\" {\n\t\treturn objectPart{}, ErrInvalidArgument(\"UploadID cannot be empty.\")\n\t}\n\n\t\/\/ Get resources properly escaped and lined up before using them in http request.\n\turlValues := make(url.Values)\n\t\/\/ Set part number.\n\turlValues.Set(\"partNumber\", strconv.Itoa(partNumber))\n\t\/\/ Set upload id.\n\turlValues.Set(\"uploadId\", uploadID)\n\n\treqMetadata := requestMetadata{\n\t\tbucketName:         bucketName,\n\t\tobjectName:         objectName,\n\t\tqueryValues:        urlValues,\n\t\tcontentBody:        reader,\n\t\tcontentLength:      size,\n\t\tcontentMD5Bytes:    md5Sum,\n\t\tcontentSHA256Bytes: sha256Sum,\n\t}\n\n\t\/\/ Execute PUT on each part.\n\tresp, err := c.executeMethod(\"PUT\", reqMetadata)\n\tdefer closeResponse(resp)\n\tif err != nil {\n\t\treturn objectPart{}, err\n\t}\n\tif resp != nil {\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn objectPart{}, httpRespToErrorResponse(resp, bucketName, objectName)\n\t\t}\n\t}\n\t\/\/ Once successfully uploaded, return completed part.\n\tobjPart := objectPart{}\n\tobjPart.Size = size\n\tobjPart.PartNumber = partNumber\n\t\/\/ Trim off the odd double quotes from ETag in the beginning and end.\n\tobjPart.ETag = strings.TrimPrefix(resp.Header.Get(\"ETag\"), \"\\\"\")\n\tobjPart.ETag = strings.TrimSuffix(objPart.ETag, \"\\\"\")\n\treturn objPart, nil\n}\n\n\/\/ completeMultipartUpload - Completes a multipart upload by assembling previously uploaded parts.\nfunc (c Client) completeMultipartUpload(bucketName, objectName, uploadID string, complete completeMultipartUpload) (completeMultipartUploadResult, error) {\n\t\/\/ Input validation.\n\tif err := isValidBucketName(bucketName); err != nil {\n\t\treturn completeMultipartUploadResult{}, err\n\t}\n\tif err := isValidObjectName(objectName); err != nil {\n\t\treturn completeMultipartUploadResult{}, err\n\t}\n\n\t\/\/ Initialize url queries.\n\turlValues := make(url.Values)\n\turlValues.Set(\"uploadId\", uploadID)\n\n\t\/\/ Marshal complete multipart body.\n\tcompleteMultipartUploadBytes, err := xml.Marshal(complete)\n\tif err != nil {\n\t\treturn completeMultipartUploadResult{}, err\n\t}\n\n\t\/\/ Instantiate all the complete multipart buffer.\n\tcompleteMultipartUploadBuffer := bytes.NewReader(completeMultipartUploadBytes)\n\treqMetadata := requestMetadata{\n\t\tbucketName:         bucketName,\n\t\tobjectName:         objectName,\n\t\tqueryValues:        urlValues,\n\t\tcontentBody:        completeMultipartUploadBuffer,\n\t\tcontentLength:      int64(len(completeMultipartUploadBytes)),\n\t\tcontentSHA256Bytes: sum256(completeMultipartUploadBytes),\n\t}\n\n\t\/\/ Execute POST to complete multipart upload for an objectName.\n\tresp, err := c.executeMethod(\"POST\", reqMetadata)\n\tdefer closeResponse(resp)\n\tif err != nil {\n\t\treturn completeMultipartUploadResult{}, err\n\t}\n\tif resp != nil {\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn completeMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName)\n\t\t}\n\t}\n\t\/\/ Decode completed multipart upload response on success.\n\tcompleteMultipartUploadResult := completeMultipartUploadResult{}\n\terr = xmlDecoder(resp.Body, &completeMultipartUploadResult)\n\tif err != nil {\n\t\treturn completeMultipartUploadResult, err\n\t}\n\treturn completeMultipartUploadResult, nil\n}\n<commit_msg>CompleteMultipartUpload API may contain error response in resp.Body (#419)<commit_after>\/*\n * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015, 2016 Minio, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage minio\n\nimport (\n\t\"bytes\"\n\t\"encoding\/hex\"\n\t\"encoding\/xml\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ Comprehensive put object operation involving multipart resumable uploads.\n\/\/\n\/\/ Following code handles these types of readers.\n\/\/\n\/\/  - *os.File\n\/\/  - *minio.Object\n\/\/  - Any reader which has a method 'ReadAt()'\n\/\/\n\/\/ If we exhaust all the known types, code proceeds to use stream as\n\/\/ is where each part is re-downloaded, checksummed and verified\n\/\/ before upload.\nfunc (c Client) putObjectMultipart(bucketName, objectName string, reader io.Reader, size int64, contentType string, progress io.Reader) (n int64, err error) {\n\tif size > 0 && size > minPartSize {\n\t\t\/\/ Verify if reader is *os.File, then use file system functionalities.\n\t\tif isFile(reader) {\n\t\t\treturn c.putObjectMultipartFromFile(bucketName, objectName, reader.(*os.File), size, contentType, progress)\n\t\t}\n\t\t\/\/ Verify if reader is *minio.Object or io.ReaderAt.\n\t\t\/\/ NOTE: Verification of object is kept for a specific purpose\n\t\t\/\/ while it is going to be duck typed similar to io.ReaderAt.\n\t\t\/\/ It is to indicate that *minio.Object implements io.ReaderAt.\n\t\t\/\/ and such a functionality is used in the subsequent code\n\t\t\/\/ path.\n\t\tif isObject(reader) || isReadAt(reader) {\n\t\t\treturn c.putObjectMultipartFromReadAt(bucketName, objectName, reader.(io.ReaderAt), size, contentType, progress)\n\t\t}\n\t}\n\t\/\/ For any other data size and reader type we do generic multipart\n\t\/\/ approach by staging data in temporary files and uploading them.\n\treturn c.putObjectMultipartStream(bucketName, objectName, reader, size, contentType, progress)\n}\n\n\/\/ putObjectStream uploads files bigger than 5MiB, and also supports\n\/\/ special case where size is unknown i.e '-1'.\nfunc (c Client) putObjectMultipartStream(bucketName, objectName string, reader io.Reader, size int64, contentType string, progress io.Reader) (n int64, err error) {\n\t\/\/ Input validation.\n\tif err := isValidBucketName(bucketName); err != nil {\n\t\treturn 0, err\n\t}\n\tif err := isValidObjectName(objectName); err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ Total data read and written to server. should be equal to 'size' at the end of the call.\n\tvar totalUploadedSize int64\n\n\t\/\/ Complete multipart upload.\n\tvar complMultipartUpload completeMultipartUpload\n\n\t\/\/ A map of all previously uploaded parts.\n\tvar partsInfo = make(map[int]objectPart)\n\n\t\/\/ getUploadID for an object, initiates a new multipart request\n\t\/\/ if it cannot find any previously partially uploaded object.\n\tuploadID, isNew, err := c.getUploadID(bucketName, objectName, contentType)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ If This session is a continuation of a previous session fetch all\n\t\/\/ previously uploaded parts info.\n\tif !isNew {\n\t\t\/\/ Fetch previously uploaded parts and maximum part size.\n\t\tpartsInfo, err = c.listObjectParts(bucketName, objectName, uploadID)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\t\/\/ Calculate the optimal parts info for a given size.\n\ttotalPartsCount, partSize, _, err := optimalPartInfo(size)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ Part number always starts with '1'.\n\tpartNumber := 1\n\n\t\/\/ Initialize a temporary buffer.\n\ttmpBuffer := new(bytes.Buffer)\n\n\tfor partNumber <= totalPartsCount {\n\t\t\/\/ Calculates MD5 and SHA256 sum while copying partSize bytes\n\t\t\/\/ into tmpBuffer.\n\t\tmd5Sum, sha256Sum, prtSize, rErr := c.hashCopyN(tmpBuffer, reader, partSize)\n\t\tif rErr != nil {\n\t\t\tif rErr != io.EOF {\n\t\t\t\treturn 0, rErr\n\t\t\t}\n\t\t}\n\n\t\tvar reader io.Reader\n\t\t\/\/ Update progress reader appropriately to the latest offset\n\t\t\/\/ as we read from the source.\n\t\treader = newHook(tmpBuffer, progress)\n\n\t\t\/\/ Verify if part should be uploaded.\n\t\tif shouldUploadPart(objectPart{\n\t\t\tETag:       hex.EncodeToString(md5Sum),\n\t\t\tPartNumber: partNumber,\n\t\t\tSize:       prtSize,\n\t\t}, partsInfo) {\n\t\t\t\/\/ Proceed to upload the part.\n\t\t\tvar objPart objectPart\n\t\t\tobjPart, err = c.uploadPart(bucketName, objectName, uploadID, reader, partNumber, md5Sum, sha256Sum, prtSize)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Reset the temporary buffer upon any error.\n\t\t\t\ttmpBuffer.Reset()\n\t\t\t\treturn totalUploadedSize, err\n\t\t\t}\n\t\t\t\/\/ Save successfully uploaded part metadata.\n\t\t\tpartsInfo[partNumber] = objPart\n\t\t} else {\n\t\t\t\/\/ Update the progress reader for the skipped part.\n\t\t\tif progress != nil {\n\t\t\t\tif _, err = io.CopyN(ioutil.Discard, progress, prtSize); err != nil {\n\t\t\t\t\treturn totalUploadedSize, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Reset the temporary buffer.\n\t\ttmpBuffer.Reset()\n\n\t\t\/\/ Save successfully uploaded size.\n\t\ttotalUploadedSize += prtSize\n\n\t\t\/\/ For unknown size, Read EOF we break away.\n\t\t\/\/ We do not have to upload till totalPartsCount.\n\t\tif size < 0 && rErr == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Increment part number.\n\t\tpartNumber++\n\t}\n\n\t\/\/ Verify if we uploaded all the data.\n\tif size > 0 {\n\t\tif totalUploadedSize != size {\n\t\t\treturn totalUploadedSize, ErrUnexpectedEOF(totalUploadedSize, size, bucketName, objectName)\n\t\t}\n\t}\n\n\t\/\/ Loop over uploaded parts to save them in a Parts array before completing the multipart request.\n\tfor _, part := range partsInfo {\n\t\tvar complPart completePart\n\t\tcomplPart.ETag = part.ETag\n\t\tcomplPart.PartNumber = part.PartNumber\n\t\tcomplMultipartUpload.Parts = append(complMultipartUpload.Parts, complPart)\n\t}\n\n\tif size > 0 {\n\t\t\/\/ Verify if totalPartsCount is not equal to total list of parts.\n\t\tif totalPartsCount != len(complMultipartUpload.Parts) {\n\t\t\treturn totalUploadedSize, ErrInvalidParts(partNumber, len(complMultipartUpload.Parts))\n\t\t}\n\t}\n\n\t\/\/ Sort all completed parts.\n\tsort.Sort(completedParts(complMultipartUpload.Parts))\n\t_, err = c.completeMultipartUpload(bucketName, objectName, uploadID, complMultipartUpload)\n\tif err != nil {\n\t\treturn totalUploadedSize, err\n\t}\n\n\t\/\/ Return final size.\n\treturn totalUploadedSize, nil\n}\n\n\/\/ initiateMultipartUpload - Initiates a multipart upload and returns an upload ID.\nfunc (c Client) initiateMultipartUpload(bucketName, objectName, contentType string) (initiateMultipartUploadResult, error) {\n\t\/\/ Input validation.\n\tif err := isValidBucketName(bucketName); err != nil {\n\t\treturn initiateMultipartUploadResult{}, err\n\t}\n\tif err := isValidObjectName(objectName); err != nil {\n\t\treturn initiateMultipartUploadResult{}, err\n\t}\n\n\t\/\/ Initialize url queries.\n\turlValues := make(url.Values)\n\turlValues.Set(\"uploads\", \"\")\n\n\tif contentType == \"\" {\n\t\tcontentType = \"application\/octet-stream\"\n\t}\n\n\t\/\/ Set ContentType header.\n\tcustomHeader := make(http.Header)\n\tcustomHeader.Set(\"Content-Type\", contentType)\n\n\treqMetadata := requestMetadata{\n\t\tbucketName:   bucketName,\n\t\tobjectName:   objectName,\n\t\tqueryValues:  urlValues,\n\t\tcustomHeader: customHeader,\n\t}\n\n\t\/\/ Execute POST on an objectName to initiate multipart upload.\n\tresp, err := c.executeMethod(\"POST\", reqMetadata)\n\tdefer closeResponse(resp)\n\tif err != nil {\n\t\treturn initiateMultipartUploadResult{}, err\n\t}\n\tif resp != nil {\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn initiateMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName)\n\t\t}\n\t}\n\t\/\/ Decode xml for new multipart upload.\n\tinitiateMultipartUploadResult := initiateMultipartUploadResult{}\n\terr = xmlDecoder(resp.Body, &initiateMultipartUploadResult)\n\tif err != nil {\n\t\treturn initiateMultipartUploadResult, err\n\t}\n\treturn initiateMultipartUploadResult, nil\n}\n\n\/\/ uploadPart - Uploads a part in a multipart upload.\nfunc (c Client) uploadPart(bucketName, objectName, uploadID string, reader io.Reader, partNumber int, md5Sum, sha256Sum []byte, size int64) (objectPart, error) {\n\t\/\/ Input validation.\n\tif err := isValidBucketName(bucketName); err != nil {\n\t\treturn objectPart{}, err\n\t}\n\tif err := isValidObjectName(objectName); err != nil {\n\t\treturn objectPart{}, err\n\t}\n\tif size > maxPartSize {\n\t\treturn objectPart{}, ErrEntityTooLarge(size, maxPartSize, bucketName, objectName)\n\t}\n\tif size <= -1 {\n\t\treturn objectPart{}, ErrEntityTooSmall(size, bucketName, objectName)\n\t}\n\tif partNumber <= 0 {\n\t\treturn objectPart{}, ErrInvalidArgument(\"Part number cannot be negative or equal to zero.\")\n\t}\n\tif uploadID == \"\" {\n\t\treturn objectPart{}, ErrInvalidArgument(\"UploadID cannot be empty.\")\n\t}\n\n\t\/\/ Get resources properly escaped and lined up before using them in http request.\n\turlValues := make(url.Values)\n\t\/\/ Set part number.\n\turlValues.Set(\"partNumber\", strconv.Itoa(partNumber))\n\t\/\/ Set upload id.\n\turlValues.Set(\"uploadId\", uploadID)\n\n\treqMetadata := requestMetadata{\n\t\tbucketName:         bucketName,\n\t\tobjectName:         objectName,\n\t\tqueryValues:        urlValues,\n\t\tcontentBody:        reader,\n\t\tcontentLength:      size,\n\t\tcontentMD5Bytes:    md5Sum,\n\t\tcontentSHA256Bytes: sha256Sum,\n\t}\n\n\t\/\/ Execute PUT on each part.\n\tresp, err := c.executeMethod(\"PUT\", reqMetadata)\n\tdefer closeResponse(resp)\n\tif err != nil {\n\t\treturn objectPart{}, err\n\t}\n\tif resp != nil {\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn objectPart{}, httpRespToErrorResponse(resp, bucketName, objectName)\n\t\t}\n\t}\n\t\/\/ Once successfully uploaded, return completed part.\n\tobjPart := objectPart{}\n\tobjPart.Size = size\n\tobjPart.PartNumber = partNumber\n\t\/\/ Trim off the odd double quotes from ETag in the beginning and end.\n\tobjPart.ETag = strings.TrimPrefix(resp.Header.Get(\"ETag\"), \"\\\"\")\n\tobjPart.ETag = strings.TrimSuffix(objPart.ETag, \"\\\"\")\n\treturn objPart, nil\n}\n\n\/\/ completeMultipartUpload - Completes a multipart upload by assembling previously uploaded parts.\nfunc (c Client) completeMultipartUpload(bucketName, objectName, uploadID string, complete completeMultipartUpload) (completeMultipartUploadResult, error) {\n\t\/\/ Input validation.\n\tif err := isValidBucketName(bucketName); err != nil {\n\t\treturn completeMultipartUploadResult{}, err\n\t}\n\tif err := isValidObjectName(objectName); err != nil {\n\t\treturn completeMultipartUploadResult{}, err\n\t}\n\n\t\/\/ Initialize url queries.\n\turlValues := make(url.Values)\n\turlValues.Set(\"uploadId\", uploadID)\n\n\t\/\/ Marshal complete multipart body.\n\tcompleteMultipartUploadBytes, err := xml.Marshal(complete)\n\tif err != nil {\n\t\treturn completeMultipartUploadResult{}, err\n\t}\n\n\t\/\/ Instantiate all the complete multipart buffer.\n\tcompleteMultipartUploadBuffer := bytes.NewReader(completeMultipartUploadBytes)\n\treqMetadata := requestMetadata{\n\t\tbucketName:         bucketName,\n\t\tobjectName:         objectName,\n\t\tqueryValues:        urlValues,\n\t\tcontentBody:        completeMultipartUploadBuffer,\n\t\tcontentLength:      int64(len(completeMultipartUploadBytes)),\n\t\tcontentSHA256Bytes: sum256(completeMultipartUploadBytes),\n\t}\n\n\t\/\/ Execute POST to complete multipart upload for an objectName.\n\tresp, err := c.executeMethod(\"POST\", reqMetadata)\n\tdefer closeResponse(resp)\n\tif err != nil {\n\t\treturn completeMultipartUploadResult{}, err\n\t}\n\tif resp != nil {\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn completeMultipartUploadResult{}, httpRespToErrorResponse(resp, bucketName, objectName)\n\t\t}\n\t}\n\n\t\/\/ Read resp.Body into a []bytes to parse for Error response inside the body\n\tvar b []byte\n\tb, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn completeMultipartUploadResult{}, err\n\t}\n\t\/\/ Decode completed multipart upload response on success.\n\tcompleteMultipartUploadResult := completeMultipartUploadResult{}\n\terr = xmlDecoder(bytes.NewReader(b), &completeMultipartUploadResult)\n\tif err != nil {\n\t\t\/\/ xml parsing failure due to presence an ill-formed xml fragment\n\t\treturn completeMultipartUploadResult, err\n\t} else if completeMultipartUploadResult.Bucket == \"\" {\n\t\t\/\/ xml's Decode method ignores well-formed xml that don't apply to the type of value supplied.\n\t\t\/\/ In this case, it would leave completeMultipartUploadResult with the corresponding zero-values\n\t\t\/\/ of the members.\n\n\t\t\/\/ Decode completed multipart upload response on failure\n\t\tcompleteMultipartUploadErr := ErrorResponse{}\n\t\terr = xmlDecoder(bytes.NewReader(b), &completeMultipartUploadErr)\n\t\tif err != nil {\n\t\t\t\/\/ xml parsing failure due to presence an ill-formed xml fragment\n\t\t\treturn completeMultipartUploadResult, err\n\t\t}\n\t\treturn completeMultipartUploadResult, completeMultipartUploadErr\n\t}\n\treturn completeMultipartUploadResult, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage api_test\n\nimport (\n\t\"fmt\"\n\n\tjc \"github.com\/juju\/testing\/checkers\"\n\tgc \"gopkg.in\/check.v1\"\n\t\"gopkg.in\/juju\/charm.v6-unstable\"\n\n\t\"github.com\/juju\/juju\/api\"\n\tapitesting \"github.com\/juju\/juju\/api\/testing\"\n\t\"github.com\/juju\/juju\/testcharms\"\n)\n\nvar _ = gc.Suite(&clientMacaroonSuite{})\n\n\/\/ clientMacaroonSuite tests that Client endpoints that are\n\/\/ independent of the RPC-based API work with\n\/\/ macaroon authentication.\ntype clientMacaroonSuite struct {\n\tapitesting.MacaroonSuite\n\tclient    *api.Client\n\tcookieJar *apitesting.ClearableCookieJar\n}\n\nfunc (s *clientMacaroonSuite) SetUpTest(c *gc.C) {\n\ts.MacaroonSuite.SetUpTest(c)\n\ts.AddModelUser(c, \"testuser@somewhere\")\n\ts.cookieJar = apitesting.NewClearableCookieJar()\n\ts.DischargerLogin = func() string { return \"testuser@somewhere\" }\n\ts.client = s.OpenAPI(c, nil, s.cookieJar).Client()\n\n\t\/\/ Even though we've logged into the API, we want\n\t\/\/ the tests below to exercise the discharging logic\n\t\/\/ so we clear the cookies.\n\ts.cookieJar.Clear()\n}\n\nfunc (s *clientMacaroonSuite) TearDownTest(c *gc.C) {\n\ts.client.Close()\n\ts.MacaroonSuite.TearDownTest(c)\n}\n\nfunc (s *clientMacaroonSuite) TestAddLocalCharmWithFailedDischarge(c *gc.C) {\n\ts.DischargerLogin = func() string { return \"\" }\n\tcharmArchive := testcharms.Repo.CharmArchive(c.MkDir(), \"dummy\")\n\tcurl := charm.MustParseURL(\n\t\tfmt.Sprintf(\"local:quantal\/%s-%d\", charmArchive.Meta().Name, charmArchive.Revision()),\n\t)\n\tsavedURL, err := s.client.AddLocalCharm(curl, charmArchive)\n\tc.Assert(err, gc.ErrorMatches, `POST https:\/\/.*\/model\/deadbeef-0bad-400d-8000-4b1d0d06f00d\/charms\\?series=quantal: cannot get discharge from \"https:\/\/.*\": third party refused discharge: cannot discharge: login denied by discharger`)\n\tc.Assert(savedURL, gc.IsNil)\n}\n\nfunc (s *clientMacaroonSuite) TestAddLocalCharmSuccess(c *gc.C) {\n\tcharmArchive := testcharms.Repo.CharmArchive(c.MkDir(), \"dummy\")\n\tcurl := charm.MustParseURL(\n\t\tfmt.Sprintf(\"local:quantal\/%s-%d\", charmArchive.Meta().Name, charmArchive.Revision()),\n\t)\n\t\/\/ Upload an archive with its original revision.\n\tsavedURL, err := s.client.AddLocalCharm(curl, charmArchive)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(savedURL.String(), gc.Equals, curl.String())\n}\n\nfunc (s *clientMacaroonSuite) TestAddLocalCharmUnauthorized(c *gc.C) {\n\ts.DischargerLogin = func() string { return \"baduser\" }\n\tcharmArchive := testcharms.Repo.CharmArchive(c.MkDir(), \"dummy\")\n\tcurl := charm.MustParseURL(\n\t\tfmt.Sprintf(\"local:quantal\/%s-%d\", charmArchive.Meta().Name, charmArchive.Revision()),\n\t)\n\t\/\/ Upload an archive with its original revision.\n\t_, err := s.client.AddLocalCharm(curl, charmArchive)\n\tc.Assert(err, gc.ErrorMatches, `POST https:\/\/.*\/model\/deadbeef-0bad-400d-8000-4b1d0d06f00d\/charms\\?series=quantal: invalid entity name or password`)\n}\n<commit_msg>api: Disabled flaky macaroon test TestAddLocalCharmSuccess<commit_after>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage api_test\n\nimport (\n\t\"fmt\"\n\n\tjc \"github.com\/juju\/testing\/checkers\"\n\tgc \"gopkg.in\/check.v1\"\n\t\"gopkg.in\/juju\/charm.v6-unstable\"\n\n\t\"github.com\/juju\/juju\/api\"\n\tapitesting \"github.com\/juju\/juju\/api\/testing\"\n\t\"github.com\/juju\/juju\/testcharms\"\n)\n\nvar _ = gc.Suite(&clientMacaroonSuite{})\n\n\/\/ clientMacaroonSuite tests that Client endpoints that are\n\/\/ independent of the RPC-based API work with\n\/\/ macaroon authentication.\ntype clientMacaroonSuite struct {\n\tapitesting.MacaroonSuite\n\tclient    *api.Client\n\tcookieJar *apitesting.ClearableCookieJar\n}\n\nfunc (s *clientMacaroonSuite) SetUpTest(c *gc.C) {\n\ts.MacaroonSuite.SetUpTest(c)\n\ts.AddModelUser(c, \"testuser@somewhere\")\n\ts.cookieJar = apitesting.NewClearableCookieJar()\n\ts.DischargerLogin = func() string { return \"testuser@somewhere\" }\n\ts.client = s.OpenAPI(c, nil, s.cookieJar).Client()\n\n\t\/\/ Even though we've logged into the API, we want\n\t\/\/ the tests below to exercise the discharging logic\n\t\/\/ so we clear the cookies.\n\ts.cookieJar.Clear()\n}\n\nfunc (s *clientMacaroonSuite) TearDownTest(c *gc.C) {\n\ts.client.Close()\n\ts.MacaroonSuite.TearDownTest(c)\n}\n\nfunc (s *clientMacaroonSuite) TestAddLocalCharmWithFailedDischarge(c *gc.C) {\n\ts.DischargerLogin = func() string { return \"\" }\n\tcharmArchive := testcharms.Repo.CharmArchive(c.MkDir(), \"dummy\")\n\tcurl := charm.MustParseURL(\n\t\tfmt.Sprintf(\"local:quantal\/%s-%d\", charmArchive.Meta().Name, charmArchive.Revision()),\n\t)\n\tsavedURL, err := s.client.AddLocalCharm(curl, charmArchive)\n\tc.Assert(err, gc.ErrorMatches, `POST https:\/\/.*\/model\/deadbeef-0bad-400d-8000-4b1d0d06f00d\/charms\\?series=quantal: cannot get discharge from \"https:\/\/.*\": third party refused discharge: cannot discharge: login denied by discharger`)\n\tc.Assert(savedURL, gc.IsNil)\n}\n\nfunc (s *clientMacaroonSuite) TestAddLocalCharmSuccess(c *gc.C) {\n\tc.Skip(\"dimitern: disabled as flaky - see http:\/\/pad.lv\/1560511 as possible root cause\")\n\n\tcharmArchive := testcharms.Repo.CharmArchive(c.MkDir(), \"dummy\")\n\tcurl := charm.MustParseURL(\n\t\tfmt.Sprintf(\"local:quantal\/%s-%d\", charmArchive.Meta().Name, charmArchive.Revision()),\n\t)\n\t\/\/ Upload an archive with its original revision.\n\tsavedURL, err := s.client.AddLocalCharm(curl, charmArchive)\n\tc.Assert(err, jc.ErrorIsNil)\n\tc.Assert(savedURL.String(), gc.Equals, curl.String())\n}\n\nfunc (s *clientMacaroonSuite) TestAddLocalCharmUnauthorized(c *gc.C) {\n\ts.DischargerLogin = func() string { return \"baduser\" }\n\tcharmArchive := testcharms.Repo.CharmArchive(c.MkDir(), \"dummy\")\n\tcurl := charm.MustParseURL(\n\t\tfmt.Sprintf(\"local:quantal\/%s-%d\", charmArchive.Meta().Name, charmArchive.Revision()),\n\t)\n\t\/\/ Upload an archive with its original revision.\n\t_, err := s.client.AddLocalCharm(curl, charmArchive)\n\tc.Assert(err, gc.ErrorMatches, `POST https:\/\/.*\/model\/deadbeef-0bad-400d-8000-4b1d0d06f00d\/charms\\?series=quantal: invalid entity name or password`)\n}\n<|endoftext|>"}
{"text":"<commit_before>package omxplayer\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/guelfey\/go.dbus\"\n)\n\nconst (\n\tifaceProps     = \"org.freedesktop.DBus.Properties\"\n\tifaceOmxRoot   = ifaceMpris\n\tifaceOmxPlayer = ifaceOmxRoot + \".Player\"\n\n\tcmdQuit                 = ifaceOmxRoot + \".Quit\"\n\tpropCanQuit             = ifaceProps + \".CanQuit\"\n\tpropFullscreen          = ifaceProps + \".Fullscreen\"\n\tpropCanSetFullscreen    = ifaceProps + \".CanSetFullscreen\"\n\tpropCanRaise            = ifaceProps + \".CanRaise\"\n\tpropHasTrackList        = ifaceProps + \".HasTrackList\"\n\tpropIdentity            = ifaceProps + \".Identity\"\n\tpropSupportedUriSchemes = ifaceProps + \".SupportedUriSchemes\"\n\tpropSupportedMimeTypes  = ifaceProps + \".SupportedMimeTypes\"\n\tpropCanGoNext           = ifaceProps + \".CanGoNext\"\n\tpropCanGoPrevious       = ifaceProps + \".CanGoPrevious\"\n\tpropCanSeek             = ifaceProps + \".CanSeek\"\n\tpropCanControl          = ifaceProps + \".CanControl\"\n\tpropCanPlay             = ifaceProps + \".CanPlay\"\n\tpropCanPause            = ifaceProps + \".CanPause\"\n\tcmdNext                 = ifaceOmxPlayer + \".Next\"\n\tcmdPrevious             = ifaceOmxPlayer + \".Previous\"\n\tcmdPause                = ifaceOmxPlayer + \".Pause\"\n\tcmdPlayPause            = ifaceOmxPlayer + \".PlayPause\"\n\tcmdStop                 = ifaceOmxPlayer + \".Stop\"\n\tcmdSeek                 = ifaceOmxPlayer + \".Seek\"\n\tcmdSetPosition          = ifaceOmxPlayer + \".SetPosition\"\n\tpropPlaybackStatus      = ifaceProps + \".PlaybackStatus\"\n\tcmdVolume               = ifaceProps + \".Volume\"\n\tcmdMute                 = ifaceProps + \".Mute\"\n\tcmdUnmute               = ifaceProps + \".Unmute\"\n\tpropPosition            = ifaceProps + \".Position\"\n\tpropAspect              = ifaceProps + \".Aspect\"\n\tpropVideoStreamCount    = ifaceProps + \".VideoStreamCount\"\n\tpropResWidth            = ifaceProps + \".ResWidth\"\n\tpropResHeight           = ifaceProps + \".ResHeight\"\n\tpropDuration            = ifaceProps + \".Duration\"\n\tpropMinimumRate         = ifaceProps + \".MinimumRate\"\n\tpropMaximumRate         = ifaceProps + \".MaximumRate\"\n\tcmdListSubtitles        = ifaceOmxPlayer + \".ListSubtitles\"\n\tcmdHideVideo            = ifaceOmxPlayer + \".HideVideo\"\n\tcmdUnHideVideo          = ifaceOmxPlayer + \".UnHideVideo\"\n\tcmdListAudio            = ifaceOmxPlayer + \".ListAudio\"\n\tcmdListVideo            = ifaceOmxPlayer + \".ListVideo\"\n\tcmdSelectSubtitle       = ifaceOmxPlayer + \".SelectSubtitle\"\n\tcmdSelectAudio          = ifaceOmxPlayer + \".SelectAudio\"\n\tcmdShowSubtitles        = ifaceOmxPlayer + \".ShowSubtitles\"\n\tcmdHideSubtitles        = ifaceOmxPlayer + \".HideSubtitles\"\n\tcmdAction               = ifaceOmxPlayer + \".Action\"\n)\n\ntype Player struct {\n\tbus *dbus.Object\n}\n\nfunc (p *Player) Quit() error {\n\treturn dbusCall(p.bus, cmdQuit)\n}\n\nfunc (p *Player) CanQuit() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanQuit)\n}\n\nfunc (p *Player) Fullscreen() (bool, error) {\n\treturn dbusGetBool(p.bus, propFullscreen)\n}\n\nfunc (p *Player) CanSetFullscreen() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanSetFullscreen)\n}\n\nfunc (p *Player) CanRaise() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanRaise)\n}\n\nfunc (p *Player) HasTrackList() (bool, error) {\n\treturn dbusGetBool(p.bus, propHasTrackList)\n}\n\nfunc (p *Player) Identity() (string, error) {\n\treturn dbusGetString(p.bus, propIdentity)\n}\n\nfunc (p *Player) SupportedUriSchemes() ([]string, error) {\n\treturn dbusGetStringArray(p.bus, propSupportedUriSchemes)\n}\n\nfunc (p *Player) SupportedMimeTypes() ([]string, error) {\n\treturn dbusGetStringArray(p.bus, propSupportedMimeTypes)\n}\n\nfunc (p *Player) CanGoNext() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanGoNext)\n}\n\nfunc (p *Player) CanGoPrevious() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanGoPrevious)\n}\n\nfunc (p *Player) CanSeek() (bool, error) {\n\treturn dbusGetBool(p.bus, cmdSeek)\n}\n\nfunc (p *Player) CanControl() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanControl)\n}\n\nfunc (p *Player) CanPlay() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanPlay)\n}\n\nfunc (p *Player) CanPause() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanPause)\n}\n\nfunc (p *Player) Next() error {\n\treturn dbusCall(p.bus, cmdNext)\n}\n\nfunc (p *Player) Previous() error {\n\treturn dbusCall(p.bus, cmdPrevious)\n}\n\nfunc (p *Player) Pause() error {\n\treturn dbusCall(p.bus, cmdPause)\n}\n\nfunc (p *Player) PlayPause() error {\n\treturn dbusCall(p.bus, cmdPlayPause)\n}\n\nfunc (p *Player) Stop() error {\n\treturn dbusCall(p.bus, cmdStop)\n}\n\nfunc (p *Player) Seek(amount int64) (int64, error) {\n\tlog.WithFields(log.Fields{\n\t\t\"path\":        cmdSeek,\n\t\t\"paramAmount\": amount,\n\t}).Debug(\"omxplayer: dbus call\")\n\tcall := p.bus.Call(cmdSeek, 0, amount)\n\tif call.Err != nil {\n\t\treturn 0, call.Err\n\t}\n\treturn call.Body[0].(int64), nil\n}\n\nfunc (p *Player) SetPosition(path string, position int64) (int64, error) {\n\tlog.WithFields(log.Fields{\n\t\t\"path\":          cmdSetPosition,\n\t\t\"paramPath\":     path,\n\t\t\"paramPosition\": position,\n\t}).Debug(\"omxplayer: dbus call\")\n\tcall := p.bus.Call(cmdSetPosition, 0, path, position)\n\tif call.Err != nil {\n\t\treturn 0, call.Err\n\t}\n\treturn call.Body[0].(int64), nil\n}\n\nfunc (p *Player) PlaybackStatus() (string, error) {\n\treturn dbusGetString(p.bus, propPlaybackStatus)\n}\n\nfunc (p *Player) Volume(volume ...float64) (float64, error) {\n\tlog.WithFields(log.Fields{\n\t\t\"path\":        cmdVolume,\n\t\t\"paramVolume\": volume,\n\t}).Debug(\"omxplayer: dbus call\")\n\tif len(volume) == 0 {\n\t\treturn dbusGetFloat64(p.bus, cmdVolume)\n\t}\n\tcall := p.bus.Call(cmdVolume, 0, volume[0])\n\tif call.Err != nil {\n\t\treturn 0, call.Err\n\t}\n\treturn call.Body[0].(float64), nil\n}\n\nfunc (p *Player) Mute() error {\n\treturn dbusCall(p.bus, cmdMute)\n}\n\nfunc (p *Player) Unmute() error {\n\treturn dbusCall(p.bus, cmdUnmute)\n}\n\nfunc (p *Player) Position() (int64, error) {\n\treturn dbusGetInt64(p.bus, propPosition)\n}\n\nfunc (p *Player) Aspect() (float64, error) {\n\treturn dbusGetFloat64(p.bus, propAspect)\n}\n\nfunc (p *Player) VideoStreamCount() (int64, error) {\n\treturn dbusGetInt64(p.bus, propVideoStreamCount)\n}\n\nfunc (p *Player) ResWidth() (int64, error) {\n\treturn dbusGetInt64(p.bus, propResWidth)\n}\n\nfunc (p *Player) ResHeight() (int64, error) {\n\treturn dbusGetInt64(p.bus, propResHeight)\n}\n\nfunc (p *Player) Duration() (int64, error) {\n\treturn dbusGetInt64(p.bus, propDuration)\n}\n\nfunc (p *Player) MinimumRate() (float64, error) {\n\treturn dbusGetFloat64(p.bus, propMinimumRate)\n}\n\nfunc (p *Player) MaximumRate() (float64, error) {\n\treturn dbusGetFloat64(p.bus, propMaximumRate)\n}\n\nfunc (p *Player) ListSubtitles() ([]string, error) {\n\treturn dbusGetStringArray(p.bus, cmdListSubtitles)\n}\n\nfunc (p *Player) HideVideo() error {\n\treturn dbusCall(p.bus, cmdHideVideo)\n}\n\nfunc (p *Player) UnHideVideo() error {\n\treturn dbusCall(p.bus, cmdUnHideVideo)\n}\n\nfunc (p *Player) ListAudio() ([]string, error) {\n\treturn dbusGetStringArray(p.bus, cmdListAudio)\n}\n\nfunc (p *Player) ListVideo() ([]string, error) {\n\treturn dbusGetStringArray(p.bus, cmdListVideo)\n}\n\nfunc (p *Player) SelectSubtitle(index int32) (bool, error) {\n\tlog.WithFields(log.Fields{\n\t\t\"path\":       cmdSelectSubtitle,\n\t\t\"paramIndex\": index,\n\t}).Debug(\"omxplayer: dbus call\")\n\tcall := p.bus.Call(cmdSelectSubtitle, 0, index)\n\tif call.Err != nil {\n\t\treturn false, call.Err\n\t}\n\treturn call.Body[0].(bool), nil\n}\n\nfunc (p *Player) SelectAudio(index int32) (bool, error) {\n\tlog.WithFields(log.Fields{\n\t\t\"path\":       cmdSelectAudio,\n\t\t\"paramIndex\": index,\n\t}).Debug(\"omxplayer: dbus call\")\n\tcall := p.bus.Call(cmdSelectAudio, 0, index)\n\tif call.Err != nil {\n\t\treturn false, call.Err\n\t}\n\treturn call.Body[0].(bool), nil\n}\n\nfunc (p *Player) ShowSubtitles() error {\n\treturn dbusCall(p.bus, cmdShowSubtitles)\n}\n\nfunc (p *Player) HideSubtitles() error {\n\treturn dbusCall(p.bus, cmdHideSubtitles)\n}\n\nfunc (p *Player) Action(action int32) error {\n\tlog.WithFields(log.Fields{\n\t\t\"path\":        cmdAction,\n\t\t\"paramAction\": action,\n\t}).Debug(\"omxplayer: dbus call\")\n\treturn p.bus.Call(cmdAction, 0, action).Err\n}\n<commit_msg>Add command and connection to Player struct.<commit_after>package omxplayer\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/guelfey\/go.dbus\"\n\t\"os\/exec\"\n)\n\nconst (\n\tifaceProps     = \"org.freedesktop.DBus.Properties\"\n\tifaceOmxRoot   = ifaceMpris\n\tifaceOmxPlayer = ifaceOmxRoot + \".Player\"\n\n\tcmdQuit                 = ifaceOmxRoot + \".Quit\"\n\tpropCanQuit             = ifaceProps + \".CanQuit\"\n\tpropFullscreen          = ifaceProps + \".Fullscreen\"\n\tpropCanSetFullscreen    = ifaceProps + \".CanSetFullscreen\"\n\tpropCanRaise            = ifaceProps + \".CanRaise\"\n\tpropHasTrackList        = ifaceProps + \".HasTrackList\"\n\tpropIdentity            = ifaceProps + \".Identity\"\n\tpropSupportedUriSchemes = ifaceProps + \".SupportedUriSchemes\"\n\tpropSupportedMimeTypes  = ifaceProps + \".SupportedMimeTypes\"\n\tpropCanGoNext           = ifaceProps + \".CanGoNext\"\n\tpropCanGoPrevious       = ifaceProps + \".CanGoPrevious\"\n\tpropCanSeek             = ifaceProps + \".CanSeek\"\n\tpropCanControl          = ifaceProps + \".CanControl\"\n\tpropCanPlay             = ifaceProps + \".CanPlay\"\n\tpropCanPause            = ifaceProps + \".CanPause\"\n\tcmdNext                 = ifaceOmxPlayer + \".Next\"\n\tcmdPrevious             = ifaceOmxPlayer + \".Previous\"\n\tcmdPause                = ifaceOmxPlayer + \".Pause\"\n\tcmdPlayPause            = ifaceOmxPlayer + \".PlayPause\"\n\tcmdStop                 = ifaceOmxPlayer + \".Stop\"\n\tcmdSeek                 = ifaceOmxPlayer + \".Seek\"\n\tcmdSetPosition          = ifaceOmxPlayer + \".SetPosition\"\n\tpropPlaybackStatus      = ifaceProps + \".PlaybackStatus\"\n\tcmdVolume               = ifaceProps + \".Volume\"\n\tcmdMute                 = ifaceProps + \".Mute\"\n\tcmdUnmute               = ifaceProps + \".Unmute\"\n\tpropPosition            = ifaceProps + \".Position\"\n\tpropAspect              = ifaceProps + \".Aspect\"\n\tpropVideoStreamCount    = ifaceProps + \".VideoStreamCount\"\n\tpropResWidth            = ifaceProps + \".ResWidth\"\n\tpropResHeight           = ifaceProps + \".ResHeight\"\n\tpropDuration            = ifaceProps + \".Duration\"\n\tpropMinimumRate         = ifaceProps + \".MinimumRate\"\n\tpropMaximumRate         = ifaceProps + \".MaximumRate\"\n\tcmdListSubtitles        = ifaceOmxPlayer + \".ListSubtitles\"\n\tcmdHideVideo            = ifaceOmxPlayer + \".HideVideo\"\n\tcmdUnHideVideo          = ifaceOmxPlayer + \".UnHideVideo\"\n\tcmdListAudio            = ifaceOmxPlayer + \".ListAudio\"\n\tcmdListVideo            = ifaceOmxPlayer + \".ListVideo\"\n\tcmdSelectSubtitle       = ifaceOmxPlayer + \".SelectSubtitle\"\n\tcmdSelectAudio          = ifaceOmxPlayer + \".SelectAudio\"\n\tcmdShowSubtitles        = ifaceOmxPlayer + \".ShowSubtitles\"\n\tcmdHideSubtitles        = ifaceOmxPlayer + \".HideSubtitles\"\n\tcmdAction               = ifaceOmxPlayer + \".Action\"\n)\n\ntype Player struct {\n\tcommand    *exec.Cmd\n\tconnection *dbus.Conn\n\tbus        *dbus.Object\n}\n\nfunc (p *Player) Quit() error {\n\treturn dbusCall(p.bus, cmdQuit)\n}\n\nfunc (p *Player) CanQuit() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanQuit)\n}\n\nfunc (p *Player) Fullscreen() (bool, error) {\n\treturn dbusGetBool(p.bus, propFullscreen)\n}\n\nfunc (p *Player) CanSetFullscreen() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanSetFullscreen)\n}\n\nfunc (p *Player) CanRaise() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanRaise)\n}\n\nfunc (p *Player) HasTrackList() (bool, error) {\n\treturn dbusGetBool(p.bus, propHasTrackList)\n}\n\nfunc (p *Player) Identity() (string, error) {\n\treturn dbusGetString(p.bus, propIdentity)\n}\n\nfunc (p *Player) SupportedUriSchemes() ([]string, error) {\n\treturn dbusGetStringArray(p.bus, propSupportedUriSchemes)\n}\n\nfunc (p *Player) SupportedMimeTypes() ([]string, error) {\n\treturn dbusGetStringArray(p.bus, propSupportedMimeTypes)\n}\n\nfunc (p *Player) CanGoNext() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanGoNext)\n}\n\nfunc (p *Player) CanGoPrevious() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanGoPrevious)\n}\n\nfunc (p *Player) CanSeek() (bool, error) {\n\treturn dbusGetBool(p.bus, cmdSeek)\n}\n\nfunc (p *Player) CanControl() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanControl)\n}\n\nfunc (p *Player) CanPlay() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanPlay)\n}\n\nfunc (p *Player) CanPause() (bool, error) {\n\treturn dbusGetBool(p.bus, propCanPause)\n}\n\nfunc (p *Player) Next() error {\n\treturn dbusCall(p.bus, cmdNext)\n}\n\nfunc (p *Player) Previous() error {\n\treturn dbusCall(p.bus, cmdPrevious)\n}\n\nfunc (p *Player) Pause() error {\n\treturn dbusCall(p.bus, cmdPause)\n}\n\nfunc (p *Player) PlayPause() error {\n\treturn dbusCall(p.bus, cmdPlayPause)\n}\n\nfunc (p *Player) Stop() error {\n\treturn dbusCall(p.bus, cmdStop)\n}\n\nfunc (p *Player) Seek(amount int64) (int64, error) {\n\tlog.WithFields(log.Fields{\n\t\t\"path\":        cmdSeek,\n\t\t\"paramAmount\": amount,\n\t}).Debug(\"omxplayer: dbus call\")\n\tcall := p.bus.Call(cmdSeek, 0, amount)\n\tif call.Err != nil {\n\t\treturn 0, call.Err\n\t}\n\treturn call.Body[0].(int64), nil\n}\n\nfunc (p *Player) SetPosition(path string, position int64) (int64, error) {\n\tlog.WithFields(log.Fields{\n\t\t\"path\":          cmdSetPosition,\n\t\t\"paramPath\":     path,\n\t\t\"paramPosition\": position,\n\t}).Debug(\"omxplayer: dbus call\")\n\tcall := p.bus.Call(cmdSetPosition, 0, path, position)\n\tif call.Err != nil {\n\t\treturn 0, call.Err\n\t}\n\treturn call.Body[0].(int64), nil\n}\n\nfunc (p *Player) PlaybackStatus() (string, error) {\n\treturn dbusGetString(p.bus, propPlaybackStatus)\n}\n\nfunc (p *Player) Volume(volume ...float64) (float64, error) {\n\tlog.WithFields(log.Fields{\n\t\t\"path\":        cmdVolume,\n\t\t\"paramVolume\": volume,\n\t}).Debug(\"omxplayer: dbus call\")\n\tif len(volume) == 0 {\n\t\treturn dbusGetFloat64(p.bus, cmdVolume)\n\t}\n\tcall := p.bus.Call(cmdVolume, 0, volume[0])\n\tif call.Err != nil {\n\t\treturn 0, call.Err\n\t}\n\treturn call.Body[0].(float64), nil\n}\n\nfunc (p *Player) Mute() error {\n\treturn dbusCall(p.bus, cmdMute)\n}\n\nfunc (p *Player) Unmute() error {\n\treturn dbusCall(p.bus, cmdUnmute)\n}\n\nfunc (p *Player) Position() (int64, error) {\n\treturn dbusGetInt64(p.bus, propPosition)\n}\n\nfunc (p *Player) Aspect() (float64, error) {\n\treturn dbusGetFloat64(p.bus, propAspect)\n}\n\nfunc (p *Player) VideoStreamCount() (int64, error) {\n\treturn dbusGetInt64(p.bus, propVideoStreamCount)\n}\n\nfunc (p *Player) ResWidth() (int64, error) {\n\treturn dbusGetInt64(p.bus, propResWidth)\n}\n\nfunc (p *Player) ResHeight() (int64, error) {\n\treturn dbusGetInt64(p.bus, propResHeight)\n}\n\nfunc (p *Player) Duration() (int64, error) {\n\treturn dbusGetInt64(p.bus, propDuration)\n}\n\nfunc (p *Player) MinimumRate() (float64, error) {\n\treturn dbusGetFloat64(p.bus, propMinimumRate)\n}\n\nfunc (p *Player) MaximumRate() (float64, error) {\n\treturn dbusGetFloat64(p.bus, propMaximumRate)\n}\n\nfunc (p *Player) ListSubtitles() ([]string, error) {\n\treturn dbusGetStringArray(p.bus, cmdListSubtitles)\n}\n\nfunc (p *Player) HideVideo() error {\n\treturn dbusCall(p.bus, cmdHideVideo)\n}\n\nfunc (p *Player) UnHideVideo() error {\n\treturn dbusCall(p.bus, cmdUnHideVideo)\n}\n\nfunc (p *Player) ListAudio() ([]string, error) {\n\treturn dbusGetStringArray(p.bus, cmdListAudio)\n}\n\nfunc (p *Player) ListVideo() ([]string, error) {\n\treturn dbusGetStringArray(p.bus, cmdListVideo)\n}\n\nfunc (p *Player) SelectSubtitle(index int32) (bool, error) {\n\tlog.WithFields(log.Fields{\n\t\t\"path\":       cmdSelectSubtitle,\n\t\t\"paramIndex\": index,\n\t}).Debug(\"omxplayer: dbus call\")\n\tcall := p.bus.Call(cmdSelectSubtitle, 0, index)\n\tif call.Err != nil {\n\t\treturn false, call.Err\n\t}\n\treturn call.Body[0].(bool), nil\n}\n\nfunc (p *Player) SelectAudio(index int32) (bool, error) {\n\tlog.WithFields(log.Fields{\n\t\t\"path\":       cmdSelectAudio,\n\t\t\"paramIndex\": index,\n\t}).Debug(\"omxplayer: dbus call\")\n\tcall := p.bus.Call(cmdSelectAudio, 0, index)\n\tif call.Err != nil {\n\t\treturn false, call.Err\n\t}\n\treturn call.Body[0].(bool), nil\n}\n\nfunc (p *Player) ShowSubtitles() error {\n\treturn dbusCall(p.bus, cmdShowSubtitles)\n}\n\nfunc (p *Player) HideSubtitles() error {\n\treturn dbusCall(p.bus, cmdHideSubtitles)\n}\n\nfunc (p *Player) Action(action int32) error {\n\tlog.WithFields(log.Fields{\n\t\t\"path\":        cmdAction,\n\t\t\"paramAction\": action,\n\t}).Debug(\"omxplayer: dbus call\")\n\treturn p.bus.Call(cmdAction, 0, action).Err\n}\n<|endoftext|>"}
{"text":"<commit_before>package awskms\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\tlog \"github.com\/hashicorp\/go-hclog\"\n\t\"github.com\/hashicorp\/vault\/helper\/logging\"\n)\n\nfunc TestAWSKMSSeal(t *testing.T) {\n\ts := NewSeal(logging.NewVaultLogger(log.Trace))\n\ts.client = &mockAWSKMSSealClient{\n\t\tkeyID: aws.String(awsTestKeyID),\n\t}\n\n\t_, err := s.SetConfig(nil)\n\tif err == nil {\n\t\tt.Fatal(\"expected error when AWSKMSSeal key ID is not provided\")\n\t}\n\n\t\/\/ Set the key\n\tos.Setenv(EnvAWSKMSSealKeyID, awsTestKeyID)\n\t_, err = s.SetConfig(nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestAWSKMSSeal_Lifecycle(t *testing.T) {\n\ts := NewSeal(logging.NewVaultLogger(log.Trace))\n\ts.client = &mockAWSKMSSealClient{\n\t\tkeyID: aws.String(awsTestKeyID),\n\t}\n\n\tos.Setenv(EnvAWSKMSSealKeyID, awsTestKeyID)\n\t_, err := s.SetConfig(nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Test Encrypt and Decrypt calls\n\tinput := []byte(\"foo\")\n\tswi, err := s.Encrypt(context.Background(), input)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err.Error())\n\t}\n\n\tpt, err := s.Decrypt(context.Background(), swi)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err.Error())\n\t}\n\n\tif !reflect.DeepEqual(input, pt) {\n\t\tt.Fatalf(\"expected %s, got %s\", input, pt)\n\t}\n}\n\nfunc TestAWSKMSSeal_custom_endpoint(t *testing.T) {\n\tcustomEndpoint := \"https:\/\/custom.endpoint\"\n\tcustomEndpoint2 := \"https:\/\/custom.endpoint.2\"\n\tendpointENV := \"AWS_KMS_ENDPOINT\"\n\n\t\/\/ unset at end of test\n\tos.Setenv(EnvAWSKMSSealKeyID, awsTestKeyID)\n\tdefer func() {\n\t\tif err := os.Unsetenv(EnvAWSKMSSealKeyID); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tcfg := make(map[string]string)\n\tcfg[\"endpoint\"] = customEndpoint\n\n\ttestCases := []struct {\n\t\tTitle    string\n\t\tEnv      string\n\t\tConfig   map[string]string\n\t\tExpected *string\n\t}{\n\t\t{\n\t\t\t\/\/ Default will have nil for the config endpoint, and be looked up\n\t\t\t\/\/ dynamically by the SDK\n\t\t\tTitle: \"Default\",\n\t\t},\n\t\t{\n\t\t\tTitle:    \"Environment\",\n\t\t\tEnv:      customEndpoint,\n\t\t\tExpected: aws.String(customEndpoint),\n\t\t},\n\t\t{\n\t\t\tTitle:    \"Config\",\n\t\t\tConfig:   cfg,\n\t\t\tExpected: aws.String(customEndpoint),\n\t\t},\n\t\t{\n\t\t\t\/\/ Expect environment to take precedence over configuration\n\t\t\tTitle:    \"Env-Config\",\n\t\t\tEnv:      customEndpoint2,\n\t\t\tConfig:   cfg,\n\t\t\tExpected: aws.String(customEndpoint2),\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.Title, func(t *testing.T) {\n\t\t\ts := NewSeal(logging.NewVaultLogger(log.Trace))\n\n\t\t\ts.client = &mockAWSKMSSealClient{\n\t\t\t\tkeyID: aws.String(awsTestKeyID),\n\t\t\t}\n\n\t\t\tif tc.Env != \"\" {\n\t\t\t\tif err := os.Setenv(endpointENV, tc.Env); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ cfg starts as nil, and takes a test case value if given. If not,\n\t\t\t\/\/ SetConfig is called with nil and creates it's own config\n\t\t\tvar cfg map[string]string\n\t\t\tif tc.Config != nil {\n\t\t\t\tcfg = tc.Config\n\t\t\t}\n\t\t\tif _, err := s.SetConfig(cfg); err != nil {\n\t\t\t\tt.Fatalf(\"error setting config: %s\", err)\n\t\t\t}\n\n\t\t\t\/\/ call getAWSKMSClient() to get the configured client and verify it's\n\t\t\t\/\/ endpoint\n\t\t\tk, err := s.getAWSKMSClient()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tif tc.Expected == nil && k.Config.Endpoint != nil {\n\t\t\t\tt.Fatalf(\"Expected nil endpoint, got: (%s)\", *k.Config.Endpoint)\n\t\t\t}\n\n\t\t\tif tc.Expected != nil {\n\t\t\t\tif k.Config.Endpoint == nil {\n\t\t\t\t\tt.Fatal(\"expected custom endpoint, but config was nil\")\n\t\t\t\t}\n\t\t\t\tif *k.Config.Endpoint != *tc.Expected {\n\t\t\t\t\tt.Fatalf(\"expected custom endpoint (%s), got: (%s)\", *tc.Expected, *k.Config.Endpoint)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ clear endpoint env after each test\n\t\t\tif err := os.Unsetenv(endpointENV); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t})\n\t}\n\n}\n<commit_msg>AWS auto-unseal acceptance test (#5739)<commit_after>package awskms\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\tlog \"github.com\/hashicorp\/go-hclog\"\n\t\"github.com\/hashicorp\/vault\/helper\/logging\"\n)\n\nfunc TestAWSKMSSeal(t *testing.T) {\n\ts := NewSeal(logging.NewVaultLogger(log.Trace))\n\ts.client = &mockAWSKMSSealClient{\n\t\tkeyID: aws.String(awsTestKeyID),\n\t}\n\n\t_, err := s.SetConfig(nil)\n\tif err == nil {\n\t\tt.Fatal(\"expected error when AWSKMSSeal key ID is not provided\")\n\t}\n\n\t\/\/ Set the key\n\tos.Setenv(EnvAWSKMSSealKeyID, awsTestKeyID)\n\t_, err = s.SetConfig(nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestAWSKMSSeal_Lifecycle(t *testing.T) {\n\ts := NewSeal(logging.NewVaultLogger(log.Trace))\n\ts.client = &mockAWSKMSSealClient{\n\t\tkeyID: aws.String(awsTestKeyID),\n\t}\n\tos.Setenv(EnvAWSKMSSealKeyID, awsTestKeyID)\n\ttestEncryptionRoundTrip(t, s)\n}\n\n\/\/ This test executes real calls. The calls themselves should be free,\n\/\/ but the KMS key used is generally not free. AWS charges about $1\/month\n\/\/ per key.\n\/\/\n\/\/ To run this test, the following env variables need to be set:\n\/\/   - VAULT_AWSKMS_SEAL_KEY_ID\n\/\/   - AWS_REGION\n\/\/   - AWS_ACCESS_KEY_ID\n\/\/   - AWS_SECRET_ACCESS_KEY\nfunc TestAccAWSKMSSeal_Lifecycle(t *testing.T) {\n\tif os.Getenv(EnvAWSKMSSealKeyID) == \"\" {\n\t\tt.SkipNow()\n\t}\n\ts := NewSeal(logging.NewVaultLogger(log.Trace))\n\ttestEncryptionRoundTrip(t, s)\n}\n\nfunc testEncryptionRoundTrip(t *testing.T, seal *AWSKMSSeal) {\n\tseal.SetConfig(nil)\n\tinput := []byte(\"foo\")\n\tswi, err := seal.Encrypt(context.Background(), input)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err.Error())\n\t}\n\n\tpt, err := seal.Decrypt(context.Background(), swi)\n\tif err != nil {\n\t\tt.Fatalf(\"err: %s\", err.Error())\n\t}\n\n\tif !reflect.DeepEqual(input, pt) {\n\t\tt.Fatalf(\"expected %s, got %s\", input, pt)\n\t}\n}\n\nfunc TestAWSKMSSeal_custom_endpoint(t *testing.T) {\n\tcustomEndpoint := \"https:\/\/custom.endpoint\"\n\tcustomEndpoint2 := \"https:\/\/custom.endpoint.2\"\n\tendpointENV := \"AWS_KMS_ENDPOINT\"\n\n\t\/\/ unset at end of test\n\tos.Setenv(EnvAWSKMSSealKeyID, awsTestKeyID)\n\tdefer func() {\n\t\tif err := os.Unsetenv(EnvAWSKMSSealKeyID); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\tcfg := make(map[string]string)\n\tcfg[\"endpoint\"] = customEndpoint\n\n\ttestCases := []struct {\n\t\tTitle    string\n\t\tEnv      string\n\t\tConfig   map[string]string\n\t\tExpected *string\n\t}{\n\t\t{\n\t\t\t\/\/ Default will have nil for the config endpoint, and be looked up\n\t\t\t\/\/ dynamically by the SDK\n\t\t\tTitle: \"Default\",\n\t\t},\n\t\t{\n\t\t\tTitle:    \"Environment\",\n\t\t\tEnv:      customEndpoint,\n\t\t\tExpected: aws.String(customEndpoint),\n\t\t},\n\t\t{\n\t\t\tTitle:    \"Config\",\n\t\t\tConfig:   cfg,\n\t\t\tExpected: aws.String(customEndpoint),\n\t\t},\n\t\t{\n\t\t\t\/\/ Expect environment to take precedence over configuration\n\t\t\tTitle:    \"Env-Config\",\n\t\t\tEnv:      customEndpoint2,\n\t\t\tConfig:   cfg,\n\t\t\tExpected: aws.String(customEndpoint2),\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.Title, func(t *testing.T) {\n\t\t\ts := NewSeal(logging.NewVaultLogger(log.Trace))\n\n\t\t\ts.client = &mockAWSKMSSealClient{\n\t\t\t\tkeyID: aws.String(awsTestKeyID),\n\t\t\t}\n\n\t\t\tif tc.Env != \"\" {\n\t\t\t\tif err := os.Setenv(endpointENV, tc.Env); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ cfg starts as nil, and takes a test case value if given. If not,\n\t\t\t\/\/ SetConfig is called with nil and creates it's own config\n\t\t\tvar cfg map[string]string\n\t\t\tif tc.Config != nil {\n\t\t\t\tcfg = tc.Config\n\t\t\t}\n\t\t\tif _, err := s.SetConfig(cfg); err != nil {\n\t\t\t\tt.Fatalf(\"error setting config: %s\", err)\n\t\t\t}\n\n\t\t\t\/\/ call getAWSKMSClient() to get the configured client and verify it's\n\t\t\t\/\/ endpoint\n\t\t\tk, err := s.getAWSKMSClient()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tif tc.Expected == nil && k.Config.Endpoint != nil {\n\t\t\t\tt.Fatalf(\"Expected nil endpoint, got: (%s)\", *k.Config.Endpoint)\n\t\t\t}\n\n\t\t\tif tc.Expected != nil {\n\t\t\t\tif k.Config.Endpoint == nil {\n\t\t\t\t\tt.Fatal(\"expected custom endpoint, but config was nil\")\n\t\t\t\t}\n\t\t\t\tif *k.Config.Endpoint != *tc.Expected {\n\t\t\t\t\tt.Fatalf(\"expected custom endpoint (%s), got: (%s)\", *tc.Expected, *k.Config.Endpoint)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ clear endpoint env after each test\n\t\t\tif err := os.Unsetenv(endpointENV); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t})\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nCopyright (c) 2010 Andrea Fazzi\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and\/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*\/\n\npackage spectrum\n\nimport \"sync\"\n\ntype Keyboard struct {\n\tkeyStates [8]byte\n\tmutex     sync.RWMutex\n}\n\nfunc NewKeyboard() *Keyboard {\n\tk := &Keyboard{}\n\n\t\/\/ Initialize keyStates\n\tvar row uint\n\tfor row = 0; row < 8; row++ {\n\t\tk.SetKeyState(row, 0xff)\n\t}\n\n\treturn k\n}\n\nfunc (keyboard *Keyboard) GetKeyState(row uint) byte {\n\tkeyboard.mutex.RLock()\n\tkeyState := keyboard.keyStates[row]\n\tkeyboard.mutex.RUnlock()\n\treturn keyState\n}\n\nfunc (keyboard *Keyboard) SetKeyState(row uint, state byte) {\n\tkeyboard.mutex.Lock()\n\tkeyboard.keyStates[row] = state\n\tkeyboard.mutex.Unlock()\n}\n\nfunc (keyboard *Keyboard) KeyDown(keySym uint) {\n\tkeyCode, ok := keyCodes[keySym]\n\n\tif ok {\n\t\tkeyboard.mutex.Lock()\n\t\tkeyboard.keyStates[keyCode.row] &= ^(keyCode.mask)\n\t\tkeyboard.mutex.Unlock()\n\t}\n}\n\nfunc (keyboard *Keyboard) KeyUp(keySym uint) {\n\tkeyCode, ok := keyCodes[keySym]\n\n\tif ok {\n\t\tkeyboard.mutex.Lock()\n\t\tkeyboard.keyStates[keyCode.row] |= (keyCode.mask)\n\t\tkeyboard.mutex.Unlock()\n\t}\n}\n\ntype keyCell struct {\n\trow, mask byte\n}\n\nvar keyCodes = map[uint]keyCell{\n\t49: keyCell{row: 3, mask: 0x01}, \/* 1 *\/\n\t50: keyCell{row: 3, mask: 0x02}, \/* 2 *\/\n\t51: keyCell{row: 3, mask: 0x04}, \/* 3 *\/\n\t52: keyCell{row: 3, mask: 0x08}, \/* 4 *\/\n\t53: keyCell{row: 3, mask: 0x10}, \/* 5 *\/\n\t54: keyCell{row: 4, mask: 0x10}, \/* 6 *\/\n\t55: keyCell{row: 4, mask: 0x08}, \/* 7 *\/\n\t56: keyCell{row: 4, mask: 0x04}, \/* 8 *\/\n\t57: keyCell{row: 4, mask: 0x02}, \/* 9 *\/\n\t48: keyCell{row: 4, mask: 0x01}, \/* 0 *\/\n\n\t113: keyCell{row: 2, mask: 0x01}, \/* Q *\/\n\t119: keyCell{row: 2, mask: 0x02}, \/* W *\/\n\t101: keyCell{row: 2, mask: 0x04}, \/* E *\/\n\t114: keyCell{row: 2, mask: 0x08}, \/* R *\/\n\t116: keyCell{row: 2, mask: 0x10}, \/* T *\/\n\t121: keyCell{row: 5, mask: 0x10}, \/* Y *\/\n\t117: keyCell{row: 5, mask: 0x08}, \/* U *\/\n\t105: keyCell{row: 5, mask: 0x04}, \/* I *\/\n\t111: keyCell{row: 5, mask: 0x02}, \/* O *\/\n\t112: keyCell{row: 5, mask: 0x01}, \/* P *\/\n\n\t97:  keyCell{row: 1, mask: 0x01}, \/* A *\/\n\t115: keyCell{row: 1, mask: 0x02}, \/* S *\/\n\t100: keyCell{row: 1, mask: 0x04}, \/* D *\/\n\t102: keyCell{row: 1, mask: 0x08}, \/* F *\/\n\t103: keyCell{row: 1, mask: 0x10}, \/* G *\/\n\t104: keyCell{row: 6, mask: 0x10}, \/* H *\/\n\t106: keyCell{row: 6, mask: 0x08}, \/* J *\/\n\t107: keyCell{row: 6, mask: 0x04}, \/* K *\/\n\t108: keyCell{row: 6, mask: 0x02}, \/* L *\/\n\t13:  keyCell{row: 6, mask: 0x01}, \/* enter *\/\n\n\t304: keyCell{row: 0, mask: 0x01}, \/* caps *\/\n\t122: keyCell{row: 0, mask: 0x02}, \/* Z *\/\n\t120: keyCell{row: 0, mask: 0x04}, \/* X *\/\n\t99:  keyCell{row: 0, mask: 0x08}, \/* C *\/\n\t118: keyCell{row: 0, mask: 0x10}, \/* V *\/\n\t98:  keyCell{row: 7, mask: 0x10}, \/* B *\/\n\t110: keyCell{row: 7, mask: 0x08}, \/* N *\/\n\t109: keyCell{row: 7, mask: 0x04}, \/* M *\/\n\t306: keyCell{row: 7, mask: 0x02}, \/* sym - gah, firefox screws up ctrl+key too *\/\n\t32:  keyCell{row: 7, mask: 0x01} \/* space *\/}\n<commit_msg>Add a final comma in the keysym hash<commit_after>\/*\n\nCopyright (c) 2010 Andrea Fazzi\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and\/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*\/\n\npackage spectrum\n\nimport \"sync\"\n\ntype Keyboard struct {\n\tkeyStates [8]byte\n\tmutex     sync.RWMutex\n}\n\nfunc NewKeyboard() *Keyboard {\n\tk := &Keyboard{}\n\n\t\/\/ Initialize keyStates\n\tvar row uint\n\tfor row = 0; row < 8; row++ {\n\t\tk.SetKeyState(row, 0xff)\n\t}\n\n\treturn k\n}\n\nfunc (keyboard *Keyboard) GetKeyState(row uint) byte {\n\tkeyboard.mutex.RLock()\n\tkeyState := keyboard.keyStates[row]\n\tkeyboard.mutex.RUnlock()\n\treturn keyState\n}\n\nfunc (keyboard *Keyboard) SetKeyState(row uint, state byte) {\n\tkeyboard.mutex.Lock()\n\tkeyboard.keyStates[row] = state\n\tkeyboard.mutex.Unlock()\n}\n\nfunc (keyboard *Keyboard) KeyDown(keySym uint) {\n\tkeyCode, ok := keyCodes[keySym]\n\n\tif ok {\n\t\tkeyboard.mutex.Lock()\n\t\tkeyboard.keyStates[keyCode.row] &= ^(keyCode.mask)\n\t\tkeyboard.mutex.Unlock()\n\t}\n}\n\nfunc (keyboard *Keyboard) KeyUp(keySym uint) {\n\tkeyCode, ok := keyCodes[keySym]\n\n\tif ok {\n\t\tkeyboard.mutex.Lock()\n\t\tkeyboard.keyStates[keyCode.row] |= (keyCode.mask)\n\t\tkeyboard.mutex.Unlock()\n\t}\n}\n\ntype keyCell struct {\n\trow, mask byte\n}\n\nvar keyCodes = map[uint]keyCell{\n\t49: keyCell{row: 3, mask: 0x01}, \/* 1 *\/\n\t50: keyCell{row: 3, mask: 0x02}, \/* 2 *\/\n\t51: keyCell{row: 3, mask: 0x04}, \/* 3 *\/\n\t52: keyCell{row: 3, mask: 0x08}, \/* 4 *\/\n\t53: keyCell{row: 3, mask: 0x10}, \/* 5 *\/\n\t54: keyCell{row: 4, mask: 0x10}, \/* 6 *\/\n\t55: keyCell{row: 4, mask: 0x08}, \/* 7 *\/\n\t56: keyCell{row: 4, mask: 0x04}, \/* 8 *\/\n\t57: keyCell{row: 4, mask: 0x02}, \/* 9 *\/\n\t48: keyCell{row: 4, mask: 0x01}, \/* 0 *\/\n\n\t113: keyCell{row: 2, mask: 0x01}, \/* Q *\/\n\t119: keyCell{row: 2, mask: 0x02}, \/* W *\/\n\t101: keyCell{row: 2, mask: 0x04}, \/* E *\/\n\t114: keyCell{row: 2, mask: 0x08}, \/* R *\/\n\t116: keyCell{row: 2, mask: 0x10}, \/* T *\/\n\t121: keyCell{row: 5, mask: 0x10}, \/* Y *\/\n\t117: keyCell{row: 5, mask: 0x08}, \/* U *\/\n\t105: keyCell{row: 5, mask: 0x04}, \/* I *\/\n\t111: keyCell{row: 5, mask: 0x02}, \/* O *\/\n\t112: keyCell{row: 5, mask: 0x01}, \/* P *\/\n\n\t97:  keyCell{row: 1, mask: 0x01}, \/* A *\/\n\t115: keyCell{row: 1, mask: 0x02}, \/* S *\/\n\t100: keyCell{row: 1, mask: 0x04}, \/* D *\/\n\t102: keyCell{row: 1, mask: 0x08}, \/* F *\/\n\t103: keyCell{row: 1, mask: 0x10}, \/* G *\/\n\t104: keyCell{row: 6, mask: 0x10}, \/* H *\/\n\t106: keyCell{row: 6, mask: 0x08}, \/* J *\/\n\t107: keyCell{row: 6, mask: 0x04}, \/* K *\/\n\t108: keyCell{row: 6, mask: 0x02}, \/* L *\/\n\t13:  keyCell{row: 6, mask: 0x01}, \/* enter *\/\n\n\t304: keyCell{row: 0, mask: 0x01}, \/* caps *\/\n\t122: keyCell{row: 0, mask: 0x02}, \/* Z *\/\n\t120: keyCell{row: 0, mask: 0x04}, \/* X *\/\n\t99:  keyCell{row: 0, mask: 0x08}, \/* C *\/\n\t118: keyCell{row: 0, mask: 0x10}, \/* V *\/\n\t98:  keyCell{row: 7, mask: 0x10}, \/* B *\/\n\t110: keyCell{row: 7, mask: 0x08}, \/* N *\/\n\t109: keyCell{row: 7, mask: 0x04}, \/* M *\/\n\t306: keyCell{row: 7, mask: 0x02}, \/* sym - gah, firefox screws up ctrl+key too *\/\n\t32:  keyCell{row: 7, mask: 0x01},\/* space *\/\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017 Cisco and\/or its affiliates.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at:\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage vppcalls\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n\n\t\"github.com\/ligato\/cn-infra\/logging\"\n\tl2ba \"github.com\/ligato\/vpp-agent\/plugins\/vpp\/binapi\/l2\"\n)\n\n\/\/ FibLogicalReq groups multiple fields so that all of them do\n\/\/ not enumerate in one function call (request, reply\/callback).\ntype FibLogicalReq struct {\n\tIsAdd    bool\n\tMAC      string\n\tBDIdx    uint32\n\tSwIfIdx  uint32\n\tBVI      bool\n\tStatic   bool\n\tcallback func(error)\n}\n\n\/\/ Add implements fib handler.\nfunc (handler *FibVppHandler) Add(mac string, bdID uint32, ifIdx uint32, bvi bool, static bool, callback func(error)) error {\n\thandler.log.Debug(\"Adding L2 FIB table entry, mac: \", mac)\n\n\thandler.requestChan <- &FibLogicalReq{\n\t\tIsAdd:    true,\n\t\tMAC:      mac,\n\t\tBDIdx:    bdID,\n\t\tSwIfIdx:  ifIdx,\n\t\tBVI:      bvi,\n\t\tStatic:   static,\n\t\tcallback: callback,\n\t}\n\treturn nil\n}\n\n\/\/ Delete implements fib handler.\nfunc (handler *FibVppHandler) Delete(mac string, bdID uint32, ifIdx uint32, callback func(error)) error {\n\thandler.log.Debug(\"Removing L2 fib table entry, mac: \", mac)\n\n\thandler.requestChan <- &FibLogicalReq{\n\t\tIsAdd:    false,\n\t\tMAC:      mac,\n\t\tBDIdx:    bdID,\n\t\tSwIfIdx:  ifIdx,\n\t\tcallback: callback,\n\t}\n\treturn nil\n}\n\n\/\/ WatchFIBReplies implements fib handler.\nfunc (handler *FibVppHandler) WatchFIBReplies() {\n\tfor {\n\t\tselect {\n\t\tcase r := <-handler.requestChan:\n\t\t\thandler.log.Debug(\"VPP L2FIB request: \", r)\n\t\t\terr := handler.l2fibAddDel(r.MAC, r.BDIdx, r.SwIfIdx, r.BVI, r.Static, r.IsAdd)\n\t\t\tif err != nil {\n\t\t\t\thandler.log.WithFields(logging.Fields{\"mac\": r.MAC, \"bdIdx\": r.BDIdx}).\n\t\t\t\t\tError(\"Static fib entry add\/delete failed:\", err)\n\t\t\t} else {\n\t\t\t\thandler.log.WithFields(logging.Fields{\"mac\": r.MAC, \"bdIdx\": r.BDIdx}).\n\t\t\t\t\tDebug(\"Static fib entry added\/deleted.\")\n\t\t\t}\n\t\t\tr.callback(err)\n\t\t}\n\t}\n}\n\nfunc (handler *FibVppHandler) l2fibAddDel(macstr string, bdIdx, swIfIdx uint32, bvi, static, isAdd bool) (err error) {\n\tdefer func(t time.Time) {\n\t\thandler.stopwatch.TimeLog(l2ba.L2fibAddDel{}).LogTimeEntry(time.Since(t))\n\t}(time.Now())\n\n\tvar mac []byte\n\tif macstr != \"\" {\n\t\tmac, err = net.ParseMAC(macstr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treq := &l2ba.L2fibAddDel{\n\t\tIsAdd:     boolToUint(isAdd),\n\t\tMac:       mac,\n\t\tBdID:      bdIdx,\n\t\tSwIfIndex: swIfIdx,\n\t\tBviMac:    boolToUint(bvi),\n\t\tStaticMac: boolToUint(static),\n\t}\n\treply := &l2ba.L2fibAddDelReply{}\n\n\tif err := handler.asyncCallsChannel.SendRequest(req).ReceiveReply(reply); err != nil {\n\t\treturn err\n\t} else if reply.Retval != 0 {\n\t\treturn fmt.Errorf(\"%s returned %d\", reply.GetMessageName(), reply.Retval)\n\t}\n\n\treturn nil\n}\n<commit_msg>added ifIdx to log in fib vppcalls<commit_after>\/\/ Copyright (c) 2017 Cisco and\/or its affiliates.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at:\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage vppcalls\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n\n\t\"github.com\/ligato\/cn-infra\/logging\"\n\tl2ba \"github.com\/ligato\/vpp-agent\/plugins\/vpp\/binapi\/l2\"\n)\n\n\/\/ FibLogicalReq groups multiple fields so that all of them do\n\/\/ not enumerate in one function call (request, reply\/callback).\ntype FibLogicalReq struct {\n\tIsAdd    bool\n\tMAC      string\n\tBDIdx    uint32\n\tSwIfIdx  uint32\n\tBVI      bool\n\tStatic   bool\n\tcallback func(error)\n}\n\n\/\/ Add implements fib handler.\nfunc (handler *FibVppHandler) Add(mac string, bdID uint32, ifIdx uint32, bvi bool, static bool, callback func(error)) error {\n\thandler.log.Debug(\"Adding L2 FIB table entry, mac: \", mac)\n\n\thandler.requestChan <- &FibLogicalReq{\n\t\tIsAdd:    true,\n\t\tMAC:      mac,\n\t\tBDIdx:    bdID,\n\t\tSwIfIdx:  ifIdx,\n\t\tBVI:      bvi,\n\t\tStatic:   static,\n\t\tcallback: callback,\n\t}\n\treturn nil\n}\n\n\/\/ Delete implements fib handler.\nfunc (handler *FibVppHandler) Delete(mac string, bdID uint32, ifIdx uint32, callback func(error)) error {\n\thandler.log.Debug(\"Removing L2 fib table entry, mac: \", mac)\n\n\thandler.requestChan <- &FibLogicalReq{\n\t\tIsAdd:    false,\n\t\tMAC:      mac,\n\t\tBDIdx:    bdID,\n\t\tSwIfIdx:  ifIdx,\n\t\tcallback: callback,\n\t}\n\treturn nil\n}\n\n\/\/ WatchFIBReplies implements fib handler.\nfunc (handler *FibVppHandler) WatchFIBReplies() {\n\tfor {\n\t\tselect {\n\t\tcase r := <-handler.requestChan:\n\t\t\thandler.log.Debug(\"VPP L2FIB request: \", r)\n\t\t\terr := handler.l2fibAddDel(r.MAC, r.BDIdx, r.SwIfIdx, r.BVI, r.Static, r.IsAdd)\n\t\t\tif err != nil {\n\t\t\t\thandler.log.WithFields(logging.Fields{\"mac\": r.MAC, \"ifIdx\": r.SwIfIdx, \"bdIdx\": r.BDIdx}).\n\t\t\t\t\tError(\"Static fib entry add\/delete failed:\", err)\n\t\t\t} else {\n\t\t\t\thandler.log.WithFields(logging.Fields{\"mac\": r.MAC, \"ifIdx\": r.SwIfIdx, \"bdIdx\": r.BDIdx}).\n\t\t\t\t\tDebug(\"Static fib entry added\/deleted.\")\n\t\t\t}\n\t\t\tr.callback(err)\n\t\t}\n\t}\n}\n\nfunc (handler *FibVppHandler) l2fibAddDel(macstr string, bdIdx, swIfIdx uint32, bvi, static, isAdd bool) (err error) {\n\tdefer func(t time.Time) {\n\t\thandler.stopwatch.TimeLog(l2ba.L2fibAddDel{}).LogTimeEntry(time.Since(t))\n\t}(time.Now())\n\n\tvar mac []byte\n\tif macstr != \"\" {\n\t\tmac, err = net.ParseMAC(macstr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treq := &l2ba.L2fibAddDel{\n\t\tIsAdd:     boolToUint(isAdd),\n\t\tMac:       mac,\n\t\tBdID:      bdIdx,\n\t\tSwIfIndex: swIfIdx,\n\t\tBviMac:    boolToUint(bvi),\n\t\tStaticMac: boolToUint(static),\n\t}\n\treply := &l2ba.L2fibAddDelReply{}\n\n\tif err := handler.asyncCallsChannel.SendRequest(req).ReceiveReply(reply); err != nil {\n\t\treturn err\n\t} else if reply.Retval != 0 {\n\t\treturn fmt.Errorf(\"%s returned %d\", reply.GetMessageName(), reply.Retval)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package rpm\n\nimport (\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ A PackageFile is an RPM package definition loaded directly from the pacakge\n\/\/ file itself.\ntype PackageFile struct {\n\tLead    Lead\n\tHeaders Headers\n\n\tpath     string\n\tfileSize uint64\n\tfileTime time.Time\n}\n\n\/\/ ReadPackageFile reads a rpm package file from a stream and returns a pointer\n\/\/ to it.\nfunc ReadPackageFile(r io.Reader) (*PackageFile, error) {\n\t\/\/ See: http:\/\/www.rpm.org\/max-rpm\/s1-rpm-file-format-rpm-file-format.html\n\tp := &PackageFile{}\n\n\t\/\/ read the deprecated \"lead\"\n\tlead, err := ReadPackageLead(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp.Lead = *lead\n\n\t\/\/ read signature and header headers\n\toffset := 96\n\tp.Headers = make(Headers, 2)\n\tfor i := 0; i < 2; i++ {\n\t\t\/\/ parse header\n\t\th, err := ReadPackageHeader(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%v (v%d.%d)\", err, lead.VersionMajor, lead.VersionMinor)\n\t\t}\n\n\t\t\/\/ set start and end offsets\n\t\th.Start = offset\n\t\th.End = h.Start + 16 + (16 * h.IndexCount) + h.Length\n\t\toffset = h.End\n\n\t\t\/\/ calculate location of the end of the header by padding to a multiple of 8\n\t\tpad := 8 - int(math.Mod(float64(h.Length), 8))\n\t\tif pad < 8 {\n\t\t\toffset += pad\n\t\t}\n\n\t\t\/\/ append\n\t\tp.Headers[i] = *h\n\t}\n\n\treturn p, nil\n}\n\n\/\/ OpenPackageFile reads a rpm package from the file systems and returns a pointer\n\/\/ to it.\nfunc OpenPackageFile(path string) (*PackageFile, error) {\n\t\/\/ stat file\n\tfi, err := os.Stat(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ open file\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error opening RPM file: %s\", err)\n\t}\n\tdefer f.Close()\n\n\t\/\/ read package content\n\tp, err := ReadPackageFile(f)\n\tif err == nil {\n\t\t\/\/ set file path\n\t\tp.path = path\n\t}\n\n\t\/\/ set file stats\n\tp.fileSize = uint64(fi.Size())\n\tp.fileTime = fi.ModTime()\n\n\treturn p, err\n}\n\n\/\/ OpenPackageFiles reads all rpm packages with the .rpm suffix from the given\n\/\/ directory on the file systems and returns a slice of pointers to the loaded\n\/\/ packages.\nfunc OpenPackageFiles(path string) ([]*PackageFile, error) {\n\t\/\/ read directory\n\tdir, err := ioutil.ReadDir(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ list *.rpm files\n\tfiles := make([]string, 0)\n\tfor _, f := range dir {\n\t\tif strings.HasSuffix(f.Name(), \".rpm\") {\n\t\t\tfiles = append(files, filepath.Join(path, f.Name()))\n\t\t}\n\t}\n\n\t\/\/ read packages\n\tpackages := make([]*PackageFile, len(files))\n\tfor i, f := range files {\n\t\tp, err := OpenPackageFile(f)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpackages[i] = p\n\t}\n\n\treturn packages, nil\n}\n\n\/\/ dependencies translates the given tag values into a slice of package\n\/\/ relationships such as provides, conflicts, obsoletes and requires.\nfunc (c *PackageFile) dependencies(nevrsTagId, flagsTagId, namesTagId, versionsTagId int) Dependencies {\n\t\/\/ TODO: Implement NEVRS tags\n\n\tflgs := c.Headers[1].Indexes.IntsByTag(flagsTagId)\n\tnames := c.Headers[1].Indexes.StringsByTag(namesTagId)\n\tvers := c.Headers[1].Indexes.StringsByTag(versionsTagId)\n\n\tdeps := make(Dependencies, len(names))\n\tfor i := 0; i < len(names); i++ {\n\t\tdeps[i] = NewDependency(int(flgs[i]), names[i], 0, vers[i], \"\")\n\t}\n\n\treturn deps\n}\n\n\/\/ String returns the package identifier in the form\n\/\/ '[name]-[version]-[release].[architecture]'.\nfunc (c *PackageFile) String() string {\n\treturn fmt.Sprintf(\"%s-%s-%s.%s\", c.Name(), c.Version(), c.Release(), c.Architecture())\n}\n\n\/\/ Path returns the path which was given to open a package file if it was opened\n\/\/ with OpenPackageFile.\nfunc (c *PackageFile) Path() string {\n\treturn c.path\n}\n\n\/\/ FileTime returns the time at which the RPM was last modified if known.\nfunc (c *PackageFile) FileTime() time.Time {\n\treturn c.fileTime\n}\n\n\/\/ FileSize returns the size of the package file in bytes.\nfunc (c *PackageFile) FileSize() uint64 {\n\treturn c.fileSize\n}\n\n\/\/ Checksum computes and returns the SHA256 checksum (encoded in hexidecimal) of\n\/\/ the package file.\nfunc (c *PackageFile) Checksum() (string, error) {\n\tif c.Path() == \"\" {\n\t\treturn \"\", fmt.Errorf(\"File not found\")\n\t}\n\n\tif f, err := os.Open(c.Path()); err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\tdefer f.Close()\n\n\t\ts := sha256.New()\n\t\tif _, err := io.Copy(s, f); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\treturn hex.EncodeToString(s.Sum(nil)), nil\n\t}\n}\n\n\/\/ ChecksumType returns \"sha256\"\nfunc (c *PackageFile) ChecksumType() string {\n\treturn \"sha256\"\n}\n\nfunc (c *PackageFile) HeaderStart() uint64 {\n\treturn uint64(c.Headers[1].Start)\n}\n\nfunc (c *PackageFile) HeaderEnd() uint64 {\n\treturn uint64(c.Headers[1].End)\n}\n\n\/\/ For tag definitions, see:\n\/\/ https:\/\/github.com\/rpm-software-management\/rpm\/blob\/master\/lib\/rpmtag.h#L61\n\nfunc (c *PackageFile) Name() string {\n\treturn c.Headers[1].Indexes.StringByTag(1000)\n}\n\nfunc (c *PackageFile) Version() string {\n\treturn c.Headers[1].Indexes.StringByTag(1001)\n}\n\nfunc (c *PackageFile) Release() string {\n\treturn c.Headers[1].Indexes.StringByTag(1002)\n}\n\nfunc (c *PackageFile) Epoch() int {\n\treturn int(c.Headers[1].Indexes.IntByTag(1003))\n}\n\nfunc (c *PackageFile) Requires() Dependencies {\n\treturn c.dependencies(5041, 1048, 1049, 1050)\n}\n\nfunc (c *PackageFile) Provides() Dependencies {\n\treturn c.dependencies(5042, 1112, 1047, 1113)\n}\n\nfunc (c *PackageFile) Conflicts() Dependencies {\n\treturn c.dependencies(5044, 1053, 1054, 1055)\n}\n\nfunc (c *PackageFile) Obsoletes() Dependencies {\n\treturn c.dependencies(5043, 1114, 1090, 1115)\n}\n\nfunc (c *PackageFile) Files() []string {\n\tixs := c.Headers[1].Indexes.IntsByTag(1116)\n\tnames := c.Headers[1].Indexes.StringsByTag(1117)\n\tdirs := c.Headers[1].Indexes.StringsByTag(1118)\n\n\tfiles := make([]string, len(names))\n\tfor i := 0; i < len(names); i++ {\n\t\tfiles[i] = dirs[ixs[i]] + names[i]\n\t}\n\n\treturn files\n}\n\nfunc (c *PackageFile) Summary() string {\n\treturn strings.Join(c.Headers[1].Indexes.StringsByTag(1004), \"\\n\")\n}\n\nfunc (c *PackageFile) Description() string {\n\treturn strings.Join(c.Headers[1].Indexes.StringsByTag(1005), \"\\n\")\n}\n\nfunc (c *PackageFile) BuildTime() time.Time {\n\treturn c.Headers[1].Indexes.TimeByTag(1006)\n}\n\nfunc (c *PackageFile) BuildHost() string {\n\treturn c.Headers[1].Indexes.StringByTag(1007)\n}\n\nfunc (c *PackageFile) InstallTime() time.Time {\n\treturn c.Headers[1].Indexes.TimeByTag(1008)\n}\n\nfunc (c *PackageFile) Size() uint64 {\n\treturn uint64(c.Headers[1].Indexes.IntByTag(1009))\n}\n\nfunc (c *PackageFile) ArchiveSize() uint64 {\n\treturn uint64(c.Headers[1].Indexes.IntByTag(1046))\n}\n\nfunc (c *PackageFile) Distribution() string {\n\treturn c.Headers[1].Indexes.StringByTag(1010)\n}\n\nfunc (c *PackageFile) Vendor() string {\n\treturn c.Headers[1].Indexes.StringByTag(1011)\n}\n\nfunc (c *PackageFile) GIFImage() []byte {\n\treturn c.Headers[1].Indexes.BytesByTag(1012)\n}\n\nfunc (c *PackageFile) XPMImage() []byte {\n\treturn c.Headers[1].Indexes.BytesByTag(1013)\n}\n\nfunc (c *PackageFile) License() string {\n\treturn c.Headers[1].Indexes.StringByTag(1014)\n}\n\nfunc (c *PackageFile) Packager() string {\n\treturn c.Headers[1].Indexes.StringByTag(1015)\n}\n\nfunc (c *PackageFile) Groups() []string {\n\treturn c.Headers[1].Indexes.StringsByTag(1016)\n}\n\nfunc (c *PackageFile) ChangeLog() []string {\n\treturn c.Headers[1].Indexes.StringsByTag(1017)\n}\n\nfunc (c *PackageFile) Source() []string {\n\treturn c.Headers[1].Indexes.StringsByTag(1018)\n}\n\nfunc (c *PackageFile) Patch() []string {\n\treturn c.Headers[1].Indexes.StringsByTag(1019)\n}\n\nfunc (c *PackageFile) URL() string {\n\treturn c.Headers[1].Indexes.StringByTag(1020)\n}\n\nfunc (c *PackageFile) OperatingSystem() string {\n\treturn c.Headers[1].Indexes.StringByTag(1021)\n}\n\nfunc (c *PackageFile) Architecture() string {\n\treturn c.Headers[1].Indexes.StringByTag(1022)\n}\n\nfunc (c *PackageFile) PreInstallScript() string {\n\treturn c.Headers[1].Indexes.StringByTag(1023)\n}\n\nfunc (c *PackageFile) PostInstallScript() string {\n\treturn c.Headers[1].Indexes.StringByTag(1024)\n}\n\nfunc (c *PackageFile) PreUninstallScript() string {\n\treturn c.Headers[1].Indexes.StringByTag(1025)\n}\n\nfunc (c *PackageFile) PostUninstallScript() string {\n\treturn c.Headers[1].Indexes.StringByTag(1026)\n}\n\nfunc (c *PackageFile) OldFilenames() []string {\n\treturn c.Headers[1].Indexes.StringsByTag(1027)\n}\n\nfunc (c *PackageFile) Icon() []byte {\n\treturn c.Headers[1].Indexes.BytesByTag(1043)\n}\n\nfunc (c *PackageFile) SourceRPM() string {\n\treturn c.Headers[1].Indexes.StringByTag(1044)\n}\n\nfunc (c *PackageFile) RPMVersion() string {\n\treturn c.Headers[1].Indexes.StringByTag(1064)\n}\n\nfunc (c *PackageFile) Platform() string {\n\treturn c.Headers[1].Indexes.StringByTag(1132)\n}\n<commit_msg>Fixed PackageFile.ArhciveSize()<commit_after>package rpm\n\nimport (\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ A PackageFile is an RPM package definition loaded directly from the pacakge\n\/\/ file itself.\ntype PackageFile struct {\n\tLead    Lead\n\tHeaders Headers\n\n\tpath     string\n\tfileSize uint64\n\tfileTime time.Time\n}\n\n\/\/ ReadPackageFile reads a rpm package file from a stream and returns a pointer\n\/\/ to it.\nfunc ReadPackageFile(r io.Reader) (*PackageFile, error) {\n\t\/\/ See: http:\/\/www.rpm.org\/max-rpm\/s1-rpm-file-format-rpm-file-format.html\n\tp := &PackageFile{}\n\n\t\/\/ read the deprecated \"lead\"\n\tlead, err := ReadPackageLead(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp.Lead = *lead\n\n\t\/\/ read signature and header headers\n\toffset := 96\n\tp.Headers = make(Headers, 2)\n\tfor i := 0; i < 2; i++ {\n\t\t\/\/ parse header\n\t\th, err := ReadPackageHeader(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%v (v%d.%d)\", err, lead.VersionMajor, lead.VersionMinor)\n\t\t}\n\n\t\t\/\/ set start and end offsets\n\t\th.Start = offset\n\t\th.End = h.Start + 16 + (16 * h.IndexCount) + h.Length\n\t\toffset = h.End\n\n\t\t\/\/ calculate location of the end of the header by padding to a multiple of 8\n\t\tpad := 8 - int(math.Mod(float64(h.Length), 8))\n\t\tif pad < 8 {\n\t\t\toffset += pad\n\t\t}\n\n\t\t\/\/ append\n\t\tp.Headers[i] = *h\n\t}\n\n\treturn p, nil\n}\n\n\/\/ OpenPackageFile reads a rpm package from the file systems and returns a pointer\n\/\/ to it.\nfunc OpenPackageFile(path string) (*PackageFile, error) {\n\t\/\/ stat file\n\tfi, err := os.Stat(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ open file\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error opening RPM file: %s\", err)\n\t}\n\tdefer f.Close()\n\n\t\/\/ read package content\n\tp, err := ReadPackageFile(f)\n\tif err == nil {\n\t\t\/\/ set file path\n\t\tp.path = path\n\t}\n\n\t\/\/ set file stats\n\tp.fileSize = uint64(fi.Size())\n\tp.fileTime = fi.ModTime()\n\n\treturn p, err\n}\n\n\/\/ OpenPackageFiles reads all rpm packages with the .rpm suffix from the given\n\/\/ directory on the file systems and returns a slice of pointers to the loaded\n\/\/ packages.\nfunc OpenPackageFiles(path string) ([]*PackageFile, error) {\n\t\/\/ read directory\n\tdir, err := ioutil.ReadDir(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ list *.rpm files\n\tfiles := make([]string, 0)\n\tfor _, f := range dir {\n\t\tif strings.HasSuffix(f.Name(), \".rpm\") {\n\t\t\tfiles = append(files, filepath.Join(path, f.Name()))\n\t\t}\n\t}\n\n\t\/\/ read packages\n\tpackages := make([]*PackageFile, len(files))\n\tfor i, f := range files {\n\t\tp, err := OpenPackageFile(f)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpackages[i] = p\n\t}\n\n\treturn packages, nil\n}\n\n\/\/ dependencies translates the given tag values into a slice of package\n\/\/ relationships such as provides, conflicts, obsoletes and requires.\nfunc (c *PackageFile) dependencies(nevrsTagId, flagsTagId, namesTagId, versionsTagId int) Dependencies {\n\t\/\/ TODO: Implement NEVRS tags\n\n\tflgs := c.Headers[1].Indexes.IntsByTag(flagsTagId)\n\tnames := c.Headers[1].Indexes.StringsByTag(namesTagId)\n\tvers := c.Headers[1].Indexes.StringsByTag(versionsTagId)\n\n\tdeps := make(Dependencies, len(names))\n\tfor i := 0; i < len(names); i++ {\n\t\tdeps[i] = NewDependency(int(flgs[i]), names[i], 0, vers[i], \"\")\n\t}\n\n\treturn deps\n}\n\n\/\/ String returns the package identifier in the form\n\/\/ '[name]-[version]-[release].[architecture]'.\nfunc (c *PackageFile) String() string {\n\treturn fmt.Sprintf(\"%s-%s-%s.%s\", c.Name(), c.Version(), c.Release(), c.Architecture())\n}\n\n\/\/ Path returns the path which was given to open a package file if it was opened\n\/\/ with OpenPackageFile.\nfunc (c *PackageFile) Path() string {\n\treturn c.path\n}\n\n\/\/ FileTime returns the time at which the RPM was last modified if known.\nfunc (c *PackageFile) FileTime() time.Time {\n\treturn c.fileTime\n}\n\n\/\/ FileSize returns the size of the package file in bytes.\nfunc (c *PackageFile) FileSize() uint64 {\n\treturn c.fileSize\n}\n\n\/\/ Checksum computes and returns the SHA256 checksum (encoded in hexidecimal) of\n\/\/ the package file.\nfunc (c *PackageFile) Checksum() (string, error) {\n\tif c.Path() == \"\" {\n\t\treturn \"\", fmt.Errorf(\"File not found\")\n\t}\n\n\tif f, err := os.Open(c.Path()); err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\tdefer f.Close()\n\n\t\ts := sha256.New()\n\t\tif _, err := io.Copy(s, f); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\treturn hex.EncodeToString(s.Sum(nil)), nil\n\t}\n}\n\n\/\/ ChecksumType returns \"sha256\"\nfunc (c *PackageFile) ChecksumType() string {\n\treturn \"sha256\"\n}\n\nfunc (c *PackageFile) HeaderStart() uint64 {\n\treturn uint64(c.Headers[1].Start)\n}\n\nfunc (c *PackageFile) HeaderEnd() uint64 {\n\treturn uint64(c.Headers[1].End)\n}\n\n\/\/ For tag definitions, see:\n\/\/ https:\/\/github.com\/rpm-software-management\/rpm\/blob\/master\/lib\/rpmtag.h#L61\n\nfunc (c *PackageFile) Name() string {\n\treturn c.Headers[1].Indexes.StringByTag(1000)\n}\n\nfunc (c *PackageFile) Version() string {\n\treturn c.Headers[1].Indexes.StringByTag(1001)\n}\n\nfunc (c *PackageFile) Release() string {\n\treturn c.Headers[1].Indexes.StringByTag(1002)\n}\n\nfunc (c *PackageFile) Epoch() int {\n\treturn int(c.Headers[1].Indexes.IntByTag(1003))\n}\n\nfunc (c *PackageFile) Requires() Dependencies {\n\treturn c.dependencies(5041, 1048, 1049, 1050)\n}\n\nfunc (c *PackageFile) Provides() Dependencies {\n\treturn c.dependencies(5042, 1112, 1047, 1113)\n}\n\nfunc (c *PackageFile) Conflicts() Dependencies {\n\treturn c.dependencies(5044, 1053, 1054, 1055)\n}\n\nfunc (c *PackageFile) Obsoletes() Dependencies {\n\treturn c.dependencies(5043, 1114, 1090, 1115)\n}\n\nfunc (c *PackageFile) Files() []string {\n\tixs := c.Headers[1].Indexes.IntsByTag(1116)\n\tnames := c.Headers[1].Indexes.StringsByTag(1117)\n\tdirs := c.Headers[1].Indexes.StringsByTag(1118)\n\n\tfiles := make([]string, len(names))\n\tfor i := 0; i < len(names); i++ {\n\t\tfiles[i] = dirs[ixs[i]] + names[i]\n\t}\n\n\treturn files\n}\n\nfunc (c *PackageFile) Summary() string {\n\treturn strings.Join(c.Headers[1].Indexes.StringsByTag(1004), \"\\n\")\n}\n\nfunc (c *PackageFile) Description() string {\n\treturn strings.Join(c.Headers[1].Indexes.StringsByTag(1005), \"\\n\")\n}\n\nfunc (c *PackageFile) BuildTime() time.Time {\n\treturn c.Headers[1].Indexes.TimeByTag(1006)\n}\n\nfunc (c *PackageFile) BuildHost() string {\n\treturn c.Headers[1].Indexes.StringByTag(1007)\n}\n\nfunc (c *PackageFile) InstallTime() time.Time {\n\treturn c.Headers[1].Indexes.TimeByTag(1008)\n}\n\n\/\/ Size specifies the disk space consumed by installation of the package.\nfunc (c *PackageFile) Size() uint64 {\n\treturn uint64(c.Headers[1].Indexes.IntByTag(1009))\n}\n\n\/\/ ArchiveSize specifies the size of the archived payload of the package in\n\/\/ bytes.\nfunc (c *PackageFile) ArchiveSize() uint64 {\n\tif i := uint64(c.Headers[0].Indexes.IntByTag(1007)); i > 0 {\n\t\treturn i\n\t}\n\n\treturn uint64(c.Headers[1].Indexes.IntByTag(1046))\n}\n\nfunc (c *PackageFile) Distribution() string {\n\treturn c.Headers[1].Indexes.StringByTag(1010)\n}\n\nfunc (c *PackageFile) Vendor() string {\n\treturn c.Headers[1].Indexes.StringByTag(1011)\n}\n\nfunc (c *PackageFile) GIFImage() []byte {\n\treturn c.Headers[1].Indexes.BytesByTag(1012)\n}\n\nfunc (c *PackageFile) XPMImage() []byte {\n\treturn c.Headers[1].Indexes.BytesByTag(1013)\n}\n\nfunc (c *PackageFile) License() string {\n\treturn c.Headers[1].Indexes.StringByTag(1014)\n}\n\nfunc (c *PackageFile) Packager() string {\n\treturn c.Headers[1].Indexes.StringByTag(1015)\n}\n\nfunc (c *PackageFile) Groups() []string {\n\treturn c.Headers[1].Indexes.StringsByTag(1016)\n}\n\nfunc (c *PackageFile) ChangeLog() []string {\n\treturn c.Headers[1].Indexes.StringsByTag(1017)\n}\n\nfunc (c *PackageFile) Source() []string {\n\treturn c.Headers[1].Indexes.StringsByTag(1018)\n}\n\nfunc (c *PackageFile) Patch() []string {\n\treturn c.Headers[1].Indexes.StringsByTag(1019)\n}\n\nfunc (c *PackageFile) URL() string {\n\treturn c.Headers[1].Indexes.StringByTag(1020)\n}\n\nfunc (c *PackageFile) OperatingSystem() string {\n\treturn c.Headers[1].Indexes.StringByTag(1021)\n}\n\nfunc (c *PackageFile) Architecture() string {\n\treturn c.Headers[1].Indexes.StringByTag(1022)\n}\n\nfunc (c *PackageFile) PreInstallScript() string {\n\treturn c.Headers[1].Indexes.StringByTag(1023)\n}\n\nfunc (c *PackageFile) PostInstallScript() string {\n\treturn c.Headers[1].Indexes.StringByTag(1024)\n}\n\nfunc (c *PackageFile) PreUninstallScript() string {\n\treturn c.Headers[1].Indexes.StringByTag(1025)\n}\n\nfunc (c *PackageFile) PostUninstallScript() string {\n\treturn c.Headers[1].Indexes.StringByTag(1026)\n}\n\nfunc (c *PackageFile) OldFilenames() []string {\n\treturn c.Headers[1].Indexes.StringsByTag(1027)\n}\n\nfunc (c *PackageFile) Icon() []byte {\n\treturn c.Headers[1].Indexes.BytesByTag(1043)\n}\n\nfunc (c *PackageFile) SourceRPM() string {\n\treturn c.Headers[1].Indexes.StringByTag(1044)\n}\n\nfunc (c *PackageFile) RPMVersion() string {\n\treturn c.Headers[1].Indexes.StringByTag(1064)\n}\n\nfunc (c *PackageFile) Platform() string {\n\treturn c.Headers[1].Indexes.StringByTag(1132)\n}\n<|endoftext|>"}
{"text":"<commit_before>package marionette_client\n\ntype Capabilities struct {\n\tBrowserName                   string\n\tBrowserVersion                string\n\tPlatformName                  string\n\tPlatformVersion               string\n\tSpecificationLevel            string\n\tRaisesAccessibilityExceptions bool\n\tRotatable                     bool\n\tAcceptSslCerts                bool\n\tTakesElementScreenshot        bool\n\tTakesScreenshot               bool\n\tProxy                         interface{}\n\tPlatform                      string\n\tXULappId                      string\n\tAppBuildId                    string\n\tDevice                        string\n\tVersion                       string\n\tCommand_id                    uint32\n}\n<commit_msg>fixed Capabilities struct specificationLevel data type for ff 53.0.3<commit_after>package marionette_client\n\ntype Capabilities struct {\n\tBrowserName                   string\n\tBrowserVersion                string\n\tPlatformName                  string\n\tPlatformVersion               string\n\tSpecificationLevel            uint\n\tRaisesAccessibilityExceptions bool\n\tRotatable                     bool\n\tAcceptSslCerts                bool\n\tTakesElementScreenshot        bool\n\tTakesScreenshot               bool\n\tProxy                         interface{}\n\tPlatform                      string\n\tXULappId                      string\n\tAppBuildId                    string\n\tDevice                        string\n\tVersion                       string\n\tCommand_id                    uint32\n}\n\n\/*\n{\"capabilities\":\n  {\n\t\"browserName\":\"firefox\",\n\t\"browserVersion\":\"53.0.3\",\"platformName\":\"linux\",\n\t\"platformVersion\":\"4.8.12-040812-generic\",\n\t\"pageLoadStrategy\":\"normal\",\n\t\"acceptInsecureCerts\":false,\n\t\"timeouts\":{\n\t\t\"implicit\":0,\n\t\t\"pageLoad\":300000,\n\t\t\"script\":30000\n\t},\n\t\"rotatable\":false,\n\t\"specificationLevel\":0,\n\t\"moz:processID\":2004,\n\t\"moz:profile\":\"\/home\/travis\/.mozilla\/firefox\/594k4686.default\",\n\t\"moz:accessibilityChecks\":false\n  }\n}**\/\n<|endoftext|>"}
{"text":"<commit_before>package leaderboard\n\nimport (\n\t\"superstellar\/backend\/pb\"\n\t\"superstellar\/backend\/state\"\n\t\"sort\"\n)\n\nconst LeaderboardLength = 10\n\ntype Leaderboard struct {\n\tranks []Rank\n}\n\nfunc LeaderboardFromSpace(space *state.Space) *Leaderboard{\n\tsize := len(space.Spaceships)\n\tranks := make([]Rank, 0, size)\n\tfor _, stateship := range space.Spaceships {\n\t\t\/\/ TODO: change to MaxHP?\n\t\tranks = append(ranks, Rank{stateship.ID, stateship.HP})\n\t}\n\tsort.Stable(sort.Reverse(SortableByScore(ranks)))\n\treturn &Leaderboard{ranks: ranks}\n}\n\n\/\/ ToProto returns protobuf representation\nfunc (leaderboard *Leaderboard) ToProto() *pb.Leaderboard {\n\tranks := make([]*pb.Rank, 0, len(leaderboard.ranks))\n\tfor _, rank := range leaderboard.ranks {\n\t\tranks = append(ranks, rank.ToProto())\n\t}\n\n\treturn &pb.Leaderboard{Ranks: ranks}\n}\n\n\/\/ ToMessage returns protobuffer Message object with Leaderboard containing ordered Ranks.\nfunc (leaderboard *Leaderboard) ToMessage() *pb.Message {\n\treturn &pb.Message{\n\t\tContent: &pb.Message_Leaderboard{\n\t\t\tLeaderboard: leaderboard.ToProto(),\n\t\t},\n\t}\n}\n<commit_msg>Use MaxHP as Score<commit_after>package leaderboard\n\nimport (\n\t\"superstellar\/backend\/pb\"\n\t\"superstellar\/backend\/state\"\n\t\"sort\"\n)\n\nconst LeaderboardLength = 10\n\ntype Leaderboard struct {\n\tranks []Rank\n}\n\nfunc LeaderboardFromSpace(space *state.Space) *Leaderboard{\n\tsize := len(space.Spaceships)\n\tranks := make([]Rank, 0, size)\n\tfor _, stateship := range space.Spaceships {\n\t\tranks = append(ranks, Rank{stateship.ID, stateship.MaxHP})\n\t}\n\tsort.Stable(sort.Reverse(SortableByScore(ranks)))\n\treturn &Leaderboard{ranks: ranks}\n}\n\n\/\/ ToProto returns protobuf representation\nfunc (leaderboard *Leaderboard) ToProto() *pb.Leaderboard {\n\tranks := make([]*pb.Rank, 0, len(leaderboard.ranks))\n\tfor _, rank := range leaderboard.ranks {\n\t\tranks = append(ranks, rank.ToProto())\n\t}\n\n\treturn &pb.Leaderboard{Ranks: ranks}\n}\n\n\/\/ ToMessage returns protobuffer Message object with Leaderboard containing ordered Ranks.\nfunc (leaderboard *Leaderboard) ToMessage() *pb.Message {\n\treturn &pb.Message{\n\t\tContent: &pb.Message_Leaderboard{\n\t\t\tLeaderboard: leaderboard.ToProto(),\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package sub\n\nimport (\n\t\"github.com\/Symantec\/Dominator\/lib\/filesystem\"\n\t\"github.com\/Symantec\/Dominator\/lib\/hash\"\n\t\"github.com\/Symantec\/Dominator\/lib\/triggers\"\n\t\"github.com\/Symantec\/Dominator\/proto\/common\"\n\t\"github.com\/Symantec\/Dominator\/sub\/scanner\"\n)\n\ntype Configuration struct {\n\tScanSpeedPercent    uint\n\tNetworkSpeedPercent uint\n\tScanExclusionList   []string\n}\n\ntype FetchRequest struct {\n\tServerAddress string\n\tHashes        []hash.Hash\n}\n\ntype FetchResponse common.StatusResponse\n\ntype GetConfigurationRequest struct {\n}\n\ntype GetConfigurationResponse Configuration\n\ntype PollRequest struct {\n\tHaveGeneration uint64\n}\n\ntype PollResponse struct {\n\tNetworkSpeed     uint64\n\tFetchInProgress  bool \/\/ Fetch() and Update() are mutually exclusive.\n\tUpdateInProgress bool\n\tGenerationCount  uint64\n\tFileSystem       *scanner.FileSystem\n}\n\ntype SetConfigurationRequest Configuration\n\ntype SetConfigurationResponse common.StatusResponse\n\ntype Directory struct {\n\tName string\n\tMode filesystem.FileMode\n\tUid  uint32\n\tGid  uint32\n}\n\ntype Hardlink struct {\n\tSource string\n\tTarget string\n}\n\ntype Inode struct {\n\tName string\n\tfilesystem.GenericInode\n}\n\ntype UpdateRequest struct {\n\tPathsToDelete       []string\n\tDirectoriesToMake   []Directory\n\tDirectoriesToChange []Directory\n\tInodesToChange      []Inode\n\tHardlinksToMake     []Hardlink\n\tTriggers            *triggers.Triggers\n}\n\ntype UpdateResponse struct{}\n<commit_msg>Add InodesToMake to UpdateRequest RPC message.<commit_after>package sub\n\nimport (\n\t\"github.com\/Symantec\/Dominator\/lib\/filesystem\"\n\t\"github.com\/Symantec\/Dominator\/lib\/hash\"\n\t\"github.com\/Symantec\/Dominator\/lib\/triggers\"\n\t\"github.com\/Symantec\/Dominator\/proto\/common\"\n\t\"github.com\/Symantec\/Dominator\/sub\/scanner\"\n)\n\ntype Configuration struct {\n\tScanSpeedPercent    uint\n\tNetworkSpeedPercent uint\n\tScanExclusionList   []string\n}\n\ntype FetchRequest struct {\n\tServerAddress string\n\tHashes        []hash.Hash\n}\n\ntype FetchResponse common.StatusResponse\n\ntype GetConfigurationRequest struct {\n}\n\ntype GetConfigurationResponse Configuration\n\ntype PollRequest struct {\n\tHaveGeneration uint64\n}\n\ntype PollResponse struct {\n\tNetworkSpeed     uint64\n\tFetchInProgress  bool \/\/ Fetch() and Update() are mutually exclusive.\n\tUpdateInProgress bool\n\tGenerationCount  uint64\n\tFileSystem       *scanner.FileSystem\n}\n\ntype SetConfigurationRequest Configuration\n\ntype SetConfigurationResponse common.StatusResponse\n\ntype Directory struct {\n\tName string\n\tMode filesystem.FileMode\n\tUid  uint32\n\tGid  uint32\n}\n\ntype Hardlink struct {\n\tSource string\n\tTarget string\n}\n\ntype Inode struct {\n\tName string\n\tfilesystem.GenericInode\n}\n\ntype UpdateRequest struct {\n\tPathsToDelete       []string\n\tDirectoriesToMake   []Directory\n\tDirectoriesToChange []Directory\n\tInodesToChange      []Inode\n\tInodesToMake        []Inode\n\tHardlinksToMake     []Hardlink\n\tTriggers            *triggers.Triggers\n}\n\ntype UpdateResponse struct{}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"code.google.com\/p\/gcfg\"\n\t\"fmt\"\n\t\"os\"\n)\n\ntype Config struct {\n\tWorker struct {\n\t\tDir string\n\t}\n\tSite struct {\n\t\tPort    string\n\t\tIp      string\n\t\tGif_Dir string\n\t}\n\tRedis struct {\n\t\tPort string\n\t\tIp   string\n\t}\n}\n\nvar conf Config\n\nfunc Get() Config {\n\t\/\/ if we loaded it before, return that instead\n\tif conf.Worker.Dir != \"\" {\n\t\treturn conf\n\t}\n\tfmt.Println(os.Getwd())\n\tif err := gcfg.ReadFileInto(&conf, \"config.txt\"); err != nil {\n\t\tpanic(err)\n\t}\n\treturn conf\n}\n<commit_msg>hook up logger<commit_after>package config\n\nimport (\n\t\"code.google.com\/p\/gcfg\"\n\t\"github.com\/Stantheman\/youtube-gif-go\/logger\"\n)\n\ntype Config struct {\n\tWorker struct {\n\t\tDir string\n\t}\n\tSite struct {\n\t\tPort    string\n\t\tIp      string\n\t\tGif_Dir string\n\t}\n\tRedis struct {\n\t\tPort string\n\t\tIp   string\n\t}\n}\n\nvar conf Config\n\nfunc Get() Config {\n\t\/\/ if we loaded it before, return that instead\n\tif conf.Worker.Dir != \"\" {\n\t\treturn conf\n\t}\n\tif err := gcfg.ReadFileInto(&conf, \"config.txt\"); err != nil {\n\t\tpanic(err)\n\t}\n\tlogger.Get().Info(\"Loaded configuration\")\n\treturn conf\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nPackage config contains convenience functions for reading and managing viper configs.\n\nCopyright 2018 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\npackage config\n\nimport (\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/viper\"\n\t\"go.opencensus.io\/stats\"\n\t\"go.opencensus.io\/stats\/view\"\n)\n\nvar (\n\t\/\/ Logrus structured logging setup\n\tlogFields = log.Fields{\n\t\t\"app\":       \"openmatch\",\n\t\t\"component\": \"config\",\n\t}\n\tcfgLog = log.WithFields(logFields)\n\n\t\/\/ Map of the config file keys to environment variable names populated by\n\t\/\/ k8s into pods. Examples of redis-related env vars as written by k8s\n\t\/\/ REDIS_SENTINEL_PORT_6379_TCP=tcp:\/\/10.55.253.195:6379\n\t\/\/ REDIS_SENTINEL_PORT=tcp:\/\/10.55.253.195:6379\n\t\/\/ REDIS_SENTINEL_PORT_6379_TCP_ADDR=10.55.253.195\n\t\/\/ REDIS_SENTINEL_SERVICE_PORT=6379\n\t\/\/ REDIS_SENTINEL_PORT_6379_TCP_PORT=6379\n\t\/\/ REDIS_SENTINEL_PORT_6379_TCP_PROTO=tcp\n\t\/\/ REDIS_SENTINEL_SERVICE_HOST=10.55.253.195\n\t\/\/\n\t\/\/ MMFs are expected to get their configuation from env vars instead\n\t\/\/ of reading the config file.  So, config parameters that are required\n\t\/\/ by MMFs should be populated to env vars.\n\tenvMappings = map[string]string{\n\t\t\"redis.hostname\":         \"REDIS_SERVICE_HOST\",\n\t\t\"redis.port\":             \"REDIS_SERVICE_PORT\",\n\t\t\"redis.pool.maxIdle\":     \"REDIS_POOL_MAXIDLE\",\n\t\t\"redis.pool.maxActive\":   \"REDIS_POOL_MAXACTIVE\",\n\t\t\"redis.pool.idleTimeout\": \"REDIS_POOL_IDLETIMEOUT\",\n\t\t\"api.mmlogic.hostname\":   \"OM_MMLOGICAPI_SERVICE_HOST\",\n\t\t\"api.mmlogic.port\":       \"OM_MMLOGICAPI_SERVICE_PORT\",\n\t}\n\n\t\/\/ Viper config management setup\n\tcfg = viper.New()\n\n\t\/\/ OpenCensus\n\tcfgVarCount = stats.Int64(\"config\/vars_total\", \"Number of config vars read during initialization\", \"1\")\n\t\/\/ CfgVarCountView is the Open Census view for the cfgVarCount measure.\n\tCfgVarCountView = &view.View{\n\t\tName:        \"config\/vars_total\",\n\t\tMeasure:     cfgVarCount,\n\t\tDescription: \"The number of config vars read during initialization\",\n\t\tAggregation: view.Count(),\n\t}\n)\n\n\/\/ Read reads a config file into a viper.Viper instance and associates environment vars defined in\n\/\/ config.envMappings\nfunc Read() (*viper.Viper, error) {\n\n\t\/\/ Viper config management initialization\n\t\/\/ Support either json or yaml file types (json for backwards compatibility\n\t\/\/ with previous versions)\n\tcfg.SetConfigType(\"json\")\n\tcfg.SetConfigType(\"yaml\")\n\tcfg.SetConfigName(\"matchmaker_config\")\n\tcfg.AddConfigPath(\".\")\n\n\t\/\/ Read in config file using Viper\n\terr := cfg.ReadInConfig()\n\tif err != nil {\n\t\tcfgLog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatal(\"Fatal error reading config file\")\n\t}\n\n\t\/\/ Bind this envvars to viper config vars.\n\t\/\/ https:\/\/github.com\/spf13\/viper#working-with-environment-variables\n\t\/\/ One important thing to recognize when working with ENV variables is\n\t\/\/ that the value will be read each time it is accessed. Viper does not\n\t\/\/ fix the value when the BindEnv is called.\n\tfor cfgKey, envVar := range envMappings {\n\t\terr = cfg.BindEnv(cfgKey, envVar)\n\n\t\tif err != nil {\n\t\t\tcfgLog.WithFields(log.Fields{\n\t\t\t\t\"configkey\": cfgKey,\n\t\t\t\t\"envvar\":    envVar,\n\t\t\t\t\"error\":     err.Error(),\n\t\t\t\t\"module\":    \"config\",\n\t\t\t}).Warn(\"Unable to bind environment var as a config variable\")\n\n\t\t} else {\n\t\t\tcfgLog.WithFields(log.Fields{\n\t\t\t\t\"configkey\": cfgKey,\n\t\t\t\t\"envvar\":    envVar,\n\t\t\t\t\"module\":    \"config\",\n\t\t\t}).Info(\"Binding environment var as a config variable\")\n\n\t\t}\n\n\t}\n\n\t\/\/ Look for updates to the config; in Kubernetes, this is implemented using\n\t\/\/ a ConfigMap that is written to the matchmaker_config.yaml file, which is\n\t\/\/ what the Open Match components using Viper monitor for changes.\n\t\/\/ More details about Open Match's use of Kubernetes ConfigMaps at:\n\t\/\/ https:\/\/github.com\/GoogleCloudPlatform\/open-match\/issues\/42\n\tcfg.WatchConfig() \/\/ Watch and re-read config file.\n\treturn cfg, err\n}\n<commit_msg>Add config\/ in the search path for configuration so that PWD\/config can be used as a ConfigMap mount path.<commit_after>\/*\nPackage config contains convenience functions for reading and managing viper configs.\n\nCopyright 2018 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\npackage config\n\nimport (\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/viper\"\n\t\"go.opencensus.io\/stats\"\n\t\"go.opencensus.io\/stats\/view\"\n)\n\nvar (\n\t\/\/ Logrus structured logging setup\n\tlogFields = log.Fields{\n\t\t\"app\":       \"openmatch\",\n\t\t\"component\": \"config\",\n\t}\n\tcfgLog = log.WithFields(logFields)\n\n\t\/\/ Map of the config file keys to environment variable names populated by\n\t\/\/ k8s into pods. Examples of redis-related env vars as written by k8s\n\t\/\/ REDIS_SENTINEL_PORT_6379_TCP=tcp:\/\/10.55.253.195:6379\n\t\/\/ REDIS_SENTINEL_PORT=tcp:\/\/10.55.253.195:6379\n\t\/\/ REDIS_SENTINEL_PORT_6379_TCP_ADDR=10.55.253.195\n\t\/\/ REDIS_SENTINEL_SERVICE_PORT=6379\n\t\/\/ REDIS_SENTINEL_PORT_6379_TCP_PORT=6379\n\t\/\/ REDIS_SENTINEL_PORT_6379_TCP_PROTO=tcp\n\t\/\/ REDIS_SENTINEL_SERVICE_HOST=10.55.253.195\n\t\/\/\n\t\/\/ MMFs are expected to get their configuation from env vars instead\n\t\/\/ of reading the config file.  So, config parameters that are required\n\t\/\/ by MMFs should be populated to env vars.\n\tenvMappings = map[string]string{\n\t\t\"redis.hostname\":         \"REDIS_SERVICE_HOST\",\n\t\t\"redis.port\":             \"REDIS_SERVICE_PORT\",\n\t\t\"redis.pool.maxIdle\":     \"REDIS_POOL_MAXIDLE\",\n\t\t\"redis.pool.maxActive\":   \"REDIS_POOL_MAXACTIVE\",\n\t\t\"redis.pool.idleTimeout\": \"REDIS_POOL_IDLETIMEOUT\",\n\t\t\"api.mmlogic.hostname\":   \"OM_MMLOGICAPI_SERVICE_HOST\",\n\t\t\"api.mmlogic.port\":       \"OM_MMLOGICAPI_SERVICE_PORT\",\n\t}\n\n\t\/\/ Viper config management setup\n\tcfg = viper.New()\n\n\t\/\/ OpenCensus\n\tcfgVarCount = stats.Int64(\"config\/vars_total\", \"Number of config vars read during initialization\", \"1\")\n\t\/\/ CfgVarCountView is the Open Census view for the cfgVarCount measure.\n\tCfgVarCountView = &view.View{\n\t\tName:        \"config\/vars_total\",\n\t\tMeasure:     cfgVarCount,\n\t\tDescription: \"The number of config vars read during initialization\",\n\t\tAggregation: view.Count(),\n\t}\n)\n\n\/\/ Read reads a config file into a viper.Viper instance and associates environment vars defined in\n\/\/ config.envMappings\nfunc Read() (*viper.Viper, error) {\n\n\t\/\/ Viper config management initialization\n\t\/\/ Support either json or yaml file types (json for backwards compatibility\n\t\/\/ with previous versions)\n\tcfg.SetConfigType(\"json\")\n\tcfg.SetConfigType(\"yaml\")\n\tcfg.SetConfigName(\"matchmaker_config\")\n\tcfg.AddConfigPath(\".\")\n\tcfg.AddConfigPath(\"config\")\n\n\t\/\/ Read in config file using Viper\n\terr := cfg.ReadInConfig()\n\tif err != nil {\n\t\tcfgLog.WithFields(log.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatal(\"Fatal error reading config file\")\n\t}\n\n\t\/\/ Bind this envvars to viper config vars.\n\t\/\/ https:\/\/github.com\/spf13\/viper#working-with-environment-variables\n\t\/\/ One important thing to recognize when working with ENV variables is\n\t\/\/ that the value will be read each time it is accessed. Viper does not\n\t\/\/ fix the value when the BindEnv is called.\n\tfor cfgKey, envVar := range envMappings {\n\t\terr = cfg.BindEnv(cfgKey, envVar)\n\n\t\tif err != nil {\n\t\t\tcfgLog.WithFields(log.Fields{\n\t\t\t\t\"configkey\": cfgKey,\n\t\t\t\t\"envvar\":    envVar,\n\t\t\t\t\"error\":     err.Error(),\n\t\t\t\t\"module\":    \"config\",\n\t\t\t}).Warn(\"Unable to bind environment var as a config variable\")\n\n\t\t} else {\n\t\t\tcfgLog.WithFields(log.Fields{\n\t\t\t\t\"configkey\": cfgKey,\n\t\t\t\t\"envvar\":    envVar,\n\t\t\t\t\"module\":    \"config\",\n\t\t\t}).Info(\"Binding environment var as a config variable\")\n\n\t\t}\n\n\t}\n\n\t\/\/ Look for updates to the config; in Kubernetes, this is implemented using\n\t\/\/ a ConfigMap that is written to the matchmaker_config.yaml file, which is\n\t\/\/ what the Open Match components using Viper monitor for changes.\n\t\/\/ More details about Open Match's use of Kubernetes ConfigMaps at:\n\t\/\/ https:\/\/github.com\/GoogleCloudPlatform\/open-match\/issues\/42\n\tcfg.WatchConfig() \/\/ Watch and re-read config file.\n\treturn cfg, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\n\thomedir \"github.com\/mitchellh\/go-homedir\"\n\t\"github.com\/prydonius\/karn\/repo\"\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\nconst (\n\tCONFIG_FILE   = \"~\/.karn.yml\"\n\tFILE_READ_ERR = \"Unable to open karn configuration file. Did you create a ~\/.karn.yml in your\" +\n\t\t\" home directory?\"\n)\n\ntype Dirs map[string]*repo.Identity\n\nfunc GetConfig() (Dirs, error) {\n\tfile, err := homedir.Expand(CONFIG_FILE)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsource, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, errors.New(FILE_READ_ERR)\n\t}\n\n\tdirs := make(Dirs)\n\terr = yaml.Unmarshal(source, dirs)\n\tif err != nil {\n\t\treturn dirs, err\n\t}\n\n\treturn dirs, nil\n}\n\nfunc GetIdentity(path string, dirs Dirs) (*repo.Identity, error) {\n\tfor {\n\t\tfor dir, _ := range dirs {\n\t\t\tverdict, err := regexp.MatchString(path+\"\/?\", dir)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif verdict {\n\t\t\t\treturn dirs[dir], nil\n\t\t\t}\n\t\t}\n\n\t\tpath, _ = filepath.Split(path)\n\t\tlength := len(path)\n\n\t\tif length == 1 {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Remove trailing slash\n\t\tpath = path[:length-1]\n\t}\n\n\treturn nil, nil\n}\n<commit_msg>Rewrite GetIdentity to make it more readable<commit_after>package config\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\n\thomedir \"github.com\/mitchellh\/go-homedir\"\n\t\"github.com\/prydonius\/karn\/repo\"\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\nconst (\n\tCONFIG_FILE   = \"~\/.karn.yml\"\n\tFILE_READ_ERR = \"Unable to open karn configuration file. Did you create a ~\/.karn.yml in your\" +\n\t\t\" home directory?\"\n)\n\ntype Dirs map[string]*repo.Identity\n\nfunc GetConfig() (Dirs, error) {\n\tfile, err := homedir.Expand(CONFIG_FILE)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsource, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, errors.New(FILE_READ_ERR)\n\t}\n\n\tdirs := make(Dirs)\n\terr = yaml.Unmarshal(source, dirs)\n\tif err != nil {\n\t\treturn dirs, err\n\t}\n\n\treturn dirs, nil\n}\n\nfunc GetIdentity(path string, dirs Dirs) (*repo.Identity, error) {\n\tif len(path) == 1 {\n\t\treturn dirs[path], nil\n\t}\n\n\t\/\/ Traverse directory -> id map from config\n\tfor dir, _ := range dirs {\n\t\t\/\/ Expects the path to not have a trailing slash\n\t\tmatch, err := regexp.MatchString(\"^\"+path+\"\/?$\", dir)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif match {\n\t\t\treturn dirs[dir], nil\n\t\t}\n\t}\n\n\t\/\/ No match, try parent directory\n\treturn GetIdentity(filepath.Dir(path), dirs)\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/go-fsnotify\/fsnotify\"\n\n\t\"github.com\/juju\/loggo\"\n\t\"gopkg.in\/alecthomas\/kingpin.v1\"\n)\n\nvar (\n\tconfig   map[string]interface{}\n\tlog      = loggo.GetLogger(\"config\") \/\/ avoid the wrapper as it uses this module and will cause a loop\n\tdataPath = \"\/data\"\n\tlock     = &sync.WaitGroup{}\n)\n\nfunc init() {\n\t\/\/ in snappy, we default to using the snappy data path\n\tsnappDataPath := os.Getenv(\"SNAPP_APP_DATA_PATH\")\n\tif snappDataPath != \"\" {\n\t\tdataPath = snappDataPath\n\t}\n\n\tMustRefresh()\n\n\tif Bool(false, \"dumpConfig\") {\n\t\tspew.Dump(GetAll(false))\n\t}\n\n\tgo func() {\n\n\t\twatcher, err := fsnotify.NewWatcher()\n\t\tif err != nil {\n\t\t\tpanic(\"Failed to create watcher: \" + err.Error())\n\t\t}\n\t\twatcher.Add(dataPath + \"\/etc\/opt\/ninja\")\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase ev := <-watcher.Events:\n\t\t\t\tlog.Infof(\"Config updated: %s\", ev.Name)\n\t\t\t\tMustRefresh()\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tlog.Warningf(\"Config Watcher error: %s\", err)\n\t\t\t}\n\t\t}\n\n\t}()\n}\n\nfunc GetAll(flatten bool) map[string]interface{} {\n\tif flatten {\n\t\treturn config\n\t}\n\treturn unflatten(config)\n}\n\nvar serial string\nvar sphereVersion string\n\nfunc Serial() string {\n\n\tif serial == \"\" {\n\n\t\tif HasString(\"serial\") {\n\t\t\tserial = String(\"serial\")\n\t\t} else {\n\n\t\t\tcmd := exec.Command(\"sphere-serial\", os.Args[1:]...)\n\n\t\t\tvar out bytes.Buffer\n\t\t\tcmd.Stdout = &out\n\n\t\t\terr := cmd.Run()\n\t\t\tif err == nil {\n\t\t\t\tserial = out.String()\n\t\t\t} else {\n\n\t\t\t\tif runtime.GOOS == \"darwin\" {\n\t\t\t\t\tserial = darwinSerial()\n\t\t\t\t} else {\n\t\t\t\t\tlog.Errorf(\"Failed to get sphere serial (sphere-serial must be in the PATH) error:%s\", err)\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn serial\n}\n\nfunc darwinSerial() string {\n\tcmd := exec.Command(\"\/bin\/sh\", \"-c\", \"system_profiler SPHardwareDataType | sed -n 's\/.*Serial Number (system).*: \/OSX\/p'\")\n\tbytes, err := cmd.Output()\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to get darwin serial: %s \", err)\n\t\tpanic(\"No darwin serial\")\n\t}\n\n\treturn string(bytes[0 : len(bytes)-1])\n}\n\nfunc SphereVersion() string {\n\tif sphereVersion == \"\" {\n\t\tif HasString(\"sphere-version\") {\n\n\t\t\tsphereVersion = String(\"sphere-version\")\n\n\t\t} else {\n\n\t\t\tcmd := exec.Command(\"sphere-version\", os.Args[1:]...)\n\n\t\t\tvar out bytes.Buffer\n\t\t\tcmd.Stdout = &out\n\n\t\t\terr := cmd.Run()\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed to get sphere version (sphere-version must be in the PATH) error:%s\", err)\n\t\t\t\tsphereVersion = \"[unknown]\"\n\t\t\t} else {\n\t\t\t\tsphereVersion = strings.TrimSpace(out.String())\n\t\t\t}\n\t\t}\n\n\t}\n\treturn sphereVersion\n}\n\nfunc IsPaired() bool {\n\treturn \/*HasString(\"sphereNetworkKey\") && *\/ HasString(\"token\") && HasString(\"userId\")\n}\n\nfunc NoCloud() bool {\n\treturn Bool(false, \"noCloud\")\n}\n\nfunc String(def string, path ...string) string {\n\tval := get(path...)\n\tif val == nil {\n\t\treturn def\n\t}\n\treturn val.(string)\n}\n\n\/\/ MustString returns the string property at the path\nfunc MustString(path ...string) string {\n\treturn mustGet(path...).(string)\n}\n\n\/\/ Duration returns the string property at the path, as a time.Duration\nfunc Duration(def time.Duration, path ...string) time.Duration {\n\ts := String(hey, path...)\n\tif s == hey {\n\t\treturn def\n\t}\n\td, err := time.ParseDuration(s)\n\tif err != nil {\n\t\tlog.Infof(\"Failed to parse duration '%s': %s\", s, err)\n\t\treturn def\n\t}\n\treturn d\n}\n\n\/\/ MustDuration returns the string property at the path, as a time.Duration\nfunc MustDuration(path ...string) time.Duration {\n\ts := MustString(path...)\n\td, err := time.ParseDuration(s)\n\tif err != nil {\n\t\tlog.Infof(\"Failed to parse duration '%s': %s\", s, err)\n\t}\n\treturn d\n}\n\n\/\/ MustStringArray returns the string array property at the path\nfunc MustStringArray(path ...string) []string {\n\ta := mustGet(path...).([]interface{})\n\tb := make([]string, len(a))\n\tfor i := range a {\n\t\tb[i] = a[i].(string)\n\t}\n\treturn b\n}\n\n\/\/ Int returns the integer property at the path, with a default\nfunc Int(def int, path ...string) int {\n\tval := get(path...)\n\tif val == nil {\n\t\treturn def\n\t}\n\treturn int(val.(float64))\n}\n\n\/\/ MustInt returns the string property at the path\nfunc MustInt(path ...string) int {\n\treturn int(mustGet(path...).(float64))\n}\n\n\/\/ Float returns the float property at the path, with a default\nfunc Float(def float64, path ...string) float64 {\n\tval := get(path...)\n\tif val == nil {\n\t\treturn def\n\t}\n\treturn val.(float64)\n}\n\nfunc MustFloat(path ...string) float64 {\n\treturn mustGet(path...).(float64)\n}\n\n\/\/ Bool returns the boolean property at the path, with a default\nfunc Bool(def bool, path ...string) bool {\n\tval := get(path...)\n\tif val == nil {\n\t\treturn def\n\t}\n\treturn val.(bool)\n}\n\n\/\/ MustBool returns the boolean property at the path\nfunc MustBool(path ...string) bool {\n\treturn mustGet(path...).(bool)\n}\n\nvar hey = \"what's up buddy?\"\n\nfunc HasString(path ...string) bool {\n\tlock.Wait()\n\n\tval, ok := config[strings.Join(path, \".\")]\n\tif !ok {\n\t\treturn false\n\t}\n\n\t_, ok = val.(string)\n\treturn ok\n}\n\nfunc mustGet(path ...string) interface{} {\n\tlock.Wait()\n\n\tval, ok := config[strings.Join(path, \".\")]\n\tif !ok {\n\t\tlog.Errorf(\"expected value for %v but found nothing\", path)\n\t\tpanic(fmt.Errorf(\"expected value for %v but found nothing\", path))\n\t}\n\treturn val\n}\n\nfunc get(path ...string) interface{} {\n\tlock.Wait()\n\n\tval, ok := config[strings.Join(path, \".\")]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn val\n}\n\nfunc MustRefresh() {\n\tlock.Wait()\n\tlock.Add(1)\n\tdefer lock.Done()\n\n\tflat := make(map[string]interface{})\n\n\t\/\/ cli overrides\n\taddArgs(flat)\n\n\t\/\/ load environments (no value args) from cli args\n\tenvironments := []string{}\n\tfor name, value := range flat {\n\t\tif value == nil {\n\t\t\tenvironments = append(environments, name)\n\t\t} else {\n\t\t\tif ok, boolValue := value.(bool); ok {\n\t\t\t\tif boolValue {\n\t\t\t\t\tenvironments = append(environments, name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ env vars (if starting with \"sphere_\")\n\taddEnv(flat)\n\n\t\/\/ If there aren't any environments set via cli, see if any were set in env var\n\tif len(environments) == 0 {\n\t\tif v, ok := flat[\"env\"]; ok {\n\t\t\tenvironments = append(environments, strings.Split(v.(string), \",\")...)\n\t\t}\n\t}\n\n\tenvironments = append(environments, \"default\")\n\n\tflat[\"env\"] = environments\n\n\tlog.Infof(\"Environments: %s\", strings.Join(environments, \", \"))\n\n\tuserHome := getUserHome()\n\n\t\/\/ anything that can be parsed as a number, is a number\n\tparseNumbers(flat)\n\n\tinstallDir := \"\/opt\/ninjablocks\"\n\tif val, ok := flat[\"installDirectory\"]; ok {\n\t\tinstallDir = val.(string)\n\t}\n\n\tif _, err := os.Stat(installDir); err != nil {\n\t\t\/\/ check for installation in snappy, apply different default path\n\t\tsnappAppPath := os.Getenv(\"SNAPP_APP_PATH\")\n\t\tif snappAppPath != \"\" {\n\t\t\tinstallDir = snappAppPath\n\t\t}\n\t}\n\n\tflat[\"installDirectory\"] = installDir\n\n\tif _, err := os.Stat(installDir); err != nil {\n\t\tlog.Warningf(\"Couldn't load sphere install directory. Override with env var sphere_installDirectory. error:%s\", err)\n\t}\n\n\t\/\/ User overrides (json)\n\taddFile(dataPath+\"\/config.json\", flat)\n\n\tfiles, _ := ioutil.ReadDir(dataPath + \"\/etc\/opt\/ninja\")\n\tfor _, f := range files {\n\t\tif strings.HasSuffix(f.Name(), \".json\") {\n\t\t\taddFile(dataPath+\"\/etc\/opt\/ninja\/\"+f.Name(), flat)\n\t\t}\n\t}\n\n\t\/\/ home directory environment(s) config\n\tfor i := len(environments) - 1; i >= 0; i-- {\n\t\taddFile(filepath.Join(userHome, \".sphere\", environments[i]+\".json\"), flat)\n\t}\n\n\t\/\/ current directory environment(s) config\n\tfor i := len(environments) - 1; i >= 0; i-- {\n\t\taddFile(filepath.Join(\".\", \"config\", environments[i]+\".json\"), flat)\n\t}\n\n\t\/\/ common environment(s) config\n\tfor i := len(environments) - 1; i >= 0; i-- {\n\t\taddFile(filepath.Join(installDir, \"config\", environments[i]+\".json\"), flat)\n\t}\n\n\t\/\/log.Debugf(\"Loaded config: %v\", flat)\n\n\tconfig = flat\n\n\tif nc, ok := config[\"noCloud\"]; ok {\n\t\tif nc.(bool) {\n\t\t\tconfig[\"userId\"] = \"nouser\"\n\t\t\tconfig[\"token\"] = \"notoken\"\n\t\t\tconfig[\"sphereNetworkKey\"] = \"nonetworkkey\"\n\t\t\tconfig[\"siteId\"] = \"nomesh\" + Serial()\n\t\t\tconfig[\"masterNodeId\"] = Serial()\n\t\t}\n\t}\n\n}\n\nfunc addEnv(config map[string]interface{}) {\n\tprefix := \"sphere_\"\n\tfor _, v := range os.Environ() {\n\n\t\tre := regexp.MustCompile(\"([^=]*)=(.*)\")\n\t\tsplit := re.FindStringSubmatch(v)\n\t\tif split != nil {\n\t\t\tname, value := split[1], split[2]\n\n\t\t\tif strings.HasPrefix(name, prefix) {\n\t\t\t\tname = strings.TrimPrefix(name, prefix)\n\t\t\t\tname = strings.Replace(name, \"_\", \".\", -1)\n\n\t\t\t\tif _, ok := config[name]; !ok {\n\t\t\t\t\tconfig[name] = value\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc addArgs(config map[string]interface{}) {\n\n\tparser := kingpin.Tokenize(os.Args[1:]).Tokens\n\n\tfor token, parser := parser.Peek(), parser.Next(); token.Type != kingpin.TokenEOL; token, parser = parser.Peek(), parser.Next() {\n\n\t\tif token.IsFlag() {\n\t\t\tvar value interface{}\n\t\t\tname := token.Value\n\n\t\t\tnext := parser.Peek()\n\t\t\tif next.Type == kingpin.TokenArg {\n\t\t\t\tif next.Value == \"false\" {\n\t\t\t\t\tvalue = false\n\t\t\t\t} else if next.Value == \"true\" {\n\t\t\t\t\tvalue = true\n\t\t\t\t} else {\n\t\t\t\t\tvalue = next.Value\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvalue = true\n\t\t\t\t\/\/ It's an environment indicator... like --cloud-production\n\t\t\t}\n\n\t\t\tconfig[name] = value\n\t\t}\n\n\t}\n\n}\n\nfunc addFile(path string, config map[string]interface{}) error {\n\t\/\/log.Debugf(\"Loading config file: %s\", path)\n\n\tfile, e := ioutil.ReadFile(path)\n\tif e != nil {\n\t\treturn fmt.Errorf(\"Failed to load file: %s error: %s\", path, e)\n\t}\n\n\tcontent := make(map[string]interface{})\n\te = json.Unmarshal(file, &content)\n\tif e != nil {\n\t\treturn fmt.Errorf(\"Failed to read file: %s error: %s\", path, e)\n\t}\n\n\t\/\/spew.Dump(path, content)\n\n\tflatten(content, nil, config)\n\treturn nil\n}\n\nfunc flatten(input interface{}, lpath []string, flattened map[string]interface{}) {\n\tif lpath == nil {\n\t\tlpath = []string{}\n\t}\n\n\tif reflect.ValueOf(input).Kind() == reflect.Map {\n\t\tfor rkey, value := range input.(map[string]interface{}) {\n\t\t\tflatten(value, append(lpath, rkey), flattened)\n\t\t}\n\t} else {\n\t\tif _, ok := flattened[strings.Join(lpath, \".\")]; !ok {\n\t\t\tflattened[strings.Join(lpath, \".\")] = input\n\t\t}\n\t}\n}\n\nfunc unflatten(flat map[string]interface{}) map[string]interface{} {\n\tout := make(map[string]interface{})\n\tobj := out\n\n\tfor key, val := range flat {\n\n\t\tobj = out\n\t\tkeys := strings.Split(key, \".\")\n\n\t\tfor i, k := range keys {\n\t\t\tif i == len(keys)-1 {\n\t\t\t\tobj[k] = val\n\t\t\t} else {\n\t\t\t\tnext, ok := obj[k]\n\t\t\t\tif !ok {\n\t\t\t\t\tnext = make(map[string]interface{})\n\t\t\t\t}\n\t\t\t\tobj[k] = next\n\t\t\t\tobj = next.(map[string]interface{})\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn out\n}\n\nfunc parseNumbers(config map[string]interface{}) {\n\tfor name, val := range config {\n\t\tstringVal, ok := val.(string)\n\t\tif ok {\n\t\t\tfloatVal, err := strconv.ParseFloat(stringVal, 64)\n\t\t\tif err == nil {\n\t\t\t\tconfig[name] = floatVal\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc getUserHome() string {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn \"\/root\"\n\t}\n\treturn usr.HomeDir\n}\n\nfunc IsSlave() bool {\n\tmasterNodeId := String(\"\", \"masterNodeId\")\n\tserial := Serial()\n\treturn masterNodeId != \"\" && serial != masterNodeId\n}\n\nfunc IsMaster() bool {\n\tmasterNodeId := String(\"\", \"masterNodeId\")\n\tserial := Serial()\n\treturn masterNodeId != \"\" && serial == masterNodeId\n}\n<commit_msg>fix up configuration override order so that the following are used in order:<commit_after>package config\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/go-fsnotify\/fsnotify\"\n\n\t\"github.com\/juju\/loggo\"\n\t\"gopkg.in\/alecthomas\/kingpin.v1\"\n)\n\nvar (\n\tconfig   map[string]interface{}\n\tlog      = loggo.GetLogger(\"config\") \/\/ avoid the wrapper as it uses this module and will cause a loop\n\tdataPath = \"\/data\"\n\tlock     = &sync.WaitGroup{}\n)\n\nfunc init() {\n\t\/\/ in snappy, we default to using the snappy data path\n\tsnappDataPath := os.Getenv(\"SNAPP_APP_DATA_PATH\")\n\tif snappDataPath != \"\" {\n\t\tdataPath = snappDataPath\n\t}\n\n\tMustRefresh()\n\n\tif Bool(false, \"dumpConfig\") {\n\t\tspew.Dump(GetAll(false))\n\t}\n\n\tgo func() {\n\n\t\twatcher, err := fsnotify.NewWatcher()\n\t\tif err != nil {\n\t\t\tpanic(\"Failed to create watcher: \" + err.Error())\n\t\t}\n\t\twatcher.Add(dataPath + \"\/etc\/opt\/ninja\")\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase ev := <-watcher.Events:\n\t\t\t\tlog.Infof(\"Config updated: %s\", ev.Name)\n\t\t\t\tMustRefresh()\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tlog.Warningf(\"Config Watcher error: %s\", err)\n\t\t\t}\n\t\t}\n\n\t}()\n}\n\nfunc GetAll(flatten bool) map[string]interface{} {\n\tif flatten {\n\t\treturn config\n\t}\n\treturn unflatten(config)\n}\n\nvar serial string\nvar sphereVersion string\n\nfunc Serial() string {\n\n\tif serial == \"\" {\n\n\t\tif HasString(\"serial\") {\n\t\t\tserial = String(\"serial\")\n\t\t} else {\n\n\t\t\tcmd := exec.Command(\"sphere-serial\", os.Args[1:]...)\n\n\t\t\tvar out bytes.Buffer\n\t\t\tcmd.Stdout = &out\n\n\t\t\terr := cmd.Run()\n\t\t\tif err == nil {\n\t\t\t\tserial = out.String()\n\t\t\t} else {\n\n\t\t\t\tif runtime.GOOS == \"darwin\" {\n\t\t\t\t\tserial = darwinSerial()\n\t\t\t\t} else {\n\t\t\t\t\tlog.Errorf(\"Failed to get sphere serial (sphere-serial must be in the PATH) error:%s\", err)\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\treturn serial\n}\n\nfunc darwinSerial() string {\n\tcmd := exec.Command(\"\/bin\/sh\", \"-c\", \"system_profiler SPHardwareDataType | sed -n 's\/.*Serial Number (system).*: \/OSX\/p'\")\n\tbytes, err := cmd.Output()\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to get darwin serial: %s \", err)\n\t\tpanic(\"No darwin serial\")\n\t}\n\n\treturn string(bytes[0 : len(bytes)-1])\n}\n\nfunc SphereVersion() string {\n\tif sphereVersion == \"\" {\n\t\tif HasString(\"sphere-version\") {\n\n\t\t\tsphereVersion = String(\"sphere-version\")\n\n\t\t} else {\n\n\t\t\tcmd := exec.Command(\"sphere-version\", os.Args[1:]...)\n\n\t\t\tvar out bytes.Buffer\n\t\t\tcmd.Stdout = &out\n\n\t\t\terr := cmd.Run()\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed to get sphere version (sphere-version must be in the PATH) error:%s\", err)\n\t\t\t\tsphereVersion = \"[unknown]\"\n\t\t\t} else {\n\t\t\t\tsphereVersion = strings.TrimSpace(out.String())\n\t\t\t}\n\t\t}\n\n\t}\n\treturn sphereVersion\n}\n\nfunc IsPaired() bool {\n\treturn \/*HasString(\"sphereNetworkKey\") && *\/ HasString(\"token\") && HasString(\"userId\")\n}\n\nfunc NoCloud() bool {\n\treturn Bool(false, \"noCloud\")\n}\n\nfunc String(def string, path ...string) string {\n\tval := get(path...)\n\tif val == nil {\n\t\treturn def\n\t}\n\treturn val.(string)\n}\n\n\/\/ MustString returns the string property at the path\nfunc MustString(path ...string) string {\n\treturn mustGet(path...).(string)\n}\n\n\/\/ Duration returns the string property at the path, as a time.Duration\nfunc Duration(def time.Duration, path ...string) time.Duration {\n\ts := String(hey, path...)\n\tif s == hey {\n\t\treturn def\n\t}\n\td, err := time.ParseDuration(s)\n\tif err != nil {\n\t\tlog.Infof(\"Failed to parse duration '%s': %s\", s, err)\n\t\treturn def\n\t}\n\treturn d\n}\n\n\/\/ MustDuration returns the string property at the path, as a time.Duration\nfunc MustDuration(path ...string) time.Duration {\n\ts := MustString(path...)\n\td, err := time.ParseDuration(s)\n\tif err != nil {\n\t\tlog.Infof(\"Failed to parse duration '%s': %s\", s, err)\n\t}\n\treturn d\n}\n\n\/\/ MustStringArray returns the string array property at the path\nfunc MustStringArray(path ...string) []string {\n\ta := mustGet(path...).([]interface{})\n\tb := make([]string, len(a))\n\tfor i := range a {\n\t\tb[i] = a[i].(string)\n\t}\n\treturn b\n}\n\n\/\/ Int returns the integer property at the path, with a default\nfunc Int(def int, path ...string) int {\n\tval := get(path...)\n\tif val == nil {\n\t\treturn def\n\t}\n\treturn int(val.(float64))\n}\n\n\/\/ MustInt returns the string property at the path\nfunc MustInt(path ...string) int {\n\treturn int(mustGet(path...).(float64))\n}\n\n\/\/ Float returns the float property at the path, with a default\nfunc Float(def float64, path ...string) float64 {\n\tval := get(path...)\n\tif val == nil {\n\t\treturn def\n\t}\n\treturn val.(float64)\n}\n\nfunc MustFloat(path ...string) float64 {\n\treturn mustGet(path...).(float64)\n}\n\n\/\/ Bool returns the boolean property at the path, with a default\nfunc Bool(def bool, path ...string) bool {\n\tval := get(path...)\n\tif val == nil {\n\t\treturn def\n\t}\n\treturn val.(bool)\n}\n\n\/\/ MustBool returns the boolean property at the path\nfunc MustBool(path ...string) bool {\n\treturn mustGet(path...).(bool)\n}\n\nvar hey = \"what's up buddy?\"\n\nfunc HasString(path ...string) bool {\n\tlock.Wait()\n\n\tval, ok := config[strings.Join(path, \".\")]\n\tif !ok {\n\t\treturn false\n\t}\n\n\t_, ok = val.(string)\n\treturn ok\n}\n\nfunc mustGet(path ...string) interface{} {\n\tlock.Wait()\n\n\tval, ok := config[strings.Join(path, \".\")]\n\tif !ok {\n\t\tlog.Errorf(\"expected value for %v but found nothing\", path)\n\t\tpanic(fmt.Errorf(\"expected value for %v but found nothing\", path))\n\t}\n\treturn val\n}\n\nfunc get(path ...string) interface{} {\n\tlock.Wait()\n\n\tval, ok := config[strings.Join(path, \".\")]\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn val\n}\n\nfunc MustRefresh() {\n\tlock.Wait()\n\tlock.Add(1)\n\tdefer lock.Done()\n\n\tflat := make(map[string]interface{})\n\n\t\/\/ cli overrides\n\taddArgs(flat)\n\n\t\/\/ env vars (if starting with \"sphere_\")\n\taddEnv(flat)\n\n\t\/\/ initialise the list\n\tenvironments := []string{\"default\"}\n\n\t\/\/ add environments read from the env variable\n\tif v, ok := flat[\"env\"]; ok {\n\t\tenvironments = append(environments, strings.Split(v.(string), \",\")...)\n\t}\n\n\t\/\/ then add any found in cli arguments\n\tfor name, value := range flat {\n\t\tif value == nil {\n\t\t\tenvironments = append(environments, name)\n\t\t} else {\n\t\t\tif ok, boolValue := value.(bool); ok {\n\t\t\t\tif boolValue {\n\t\t\t\t\tenvironments = append(environments, name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tflat[\"env\"] = environments\n\n\tlog.Infof(\"Environments: %s\", strings.Join(environments, \", \"))\n\n\tuserHome := getUserHome()\n\n\t\/\/ anything that can be parsed as a number, is a number\n\tparseNumbers(flat)\n\n\tinstallDir := \"\/opt\/ninjablocks\"\n\tif val, ok := flat[\"installDirectory\"]; ok {\n\t\tinstallDir = val.(string)\n\t}\n\n\tif _, err := os.Stat(installDir); err != nil {\n\t\t\/\/ check for installation in snappy, apply different default path\n\t\tsnappAppPath := os.Getenv(\"SNAPP_APP_PATH\")\n\t\tif snappAppPath != \"\" {\n\t\t\tinstallDir = snappAppPath\n\t\t}\n\t}\n\n\tflat[\"installDirectory\"] = installDir\n\n\tif _, err := os.Stat(installDir); err != nil {\n\t\tlog.Warningf(\"Couldn't load sphere install directory. Override with env var sphere_installDirectory. error:%s\", err)\n\t}\n\n\t\/\/ User overrides (json)\n\taddFile(dataPath+\"\/config.json\", flat)\n\n\tfiles, _ := ioutil.ReadDir(dataPath + \"\/etc\/opt\/ninja\")\n\tfor _, f := range files {\n\t\tif strings.HasSuffix(f.Name(), \".json\") {\n\t\t\taddFile(dataPath+\"\/etc\/opt\/ninja\/\"+f.Name(), flat)\n\t\t}\n\t}\n\n\t\/\/ home directory environment(s) config\n\tfor i := len(environments) - 1; i >= 0; i-- {\n\t\taddFile(filepath.Join(userHome, \".sphere\", environments[i]+\".json\"), flat)\n\t}\n\n\t\/\/ current directory environment(s) config\n\tfor i := len(environments) - 1; i >= 0; i-- {\n\t\taddFile(filepath.Join(\".\", \"config\", environments[i]+\".json\"), flat)\n\t}\n\n\t\/\/ common environment(s) config\n\tfor i := len(environments) - 1; i >= 0; i-- {\n\t\taddFile(filepath.Join(installDir, \"config\", environments[i]+\".json\"), flat)\n\t}\n\n\t\/\/log.Debugf(\"Loaded config: %v\", flat)\n\n\tconfig = flat\n\n\tif nc, ok := config[\"noCloud\"]; ok {\n\t\tif nc.(bool) {\n\t\t\tconfig[\"userId\"] = \"nouser\"\n\t\t\tconfig[\"token\"] = \"notoken\"\n\t\t\tconfig[\"sphereNetworkKey\"] = \"nonetworkkey\"\n\t\t\tconfig[\"siteId\"] = \"nomesh\" + Serial()\n\t\t\tconfig[\"masterNodeId\"] = Serial()\n\t\t}\n\t}\n\n}\n\nfunc addEnv(config map[string]interface{}) {\n\tprefix := \"sphere_\"\n\tfor _, v := range os.Environ() {\n\n\t\tre := regexp.MustCompile(\"([^=]*)=(.*)\")\n\t\tsplit := re.FindStringSubmatch(v)\n\t\tif split != nil {\n\t\t\tname, value := split[1], split[2]\n\n\t\t\tif strings.HasPrefix(name, prefix) {\n\t\t\t\tname = strings.TrimPrefix(name, prefix)\n\t\t\t\tname = strings.Replace(name, \"_\", \".\", -1)\n\n\t\t\t\tif _, ok := config[name]; !ok {\n\t\t\t\t\tconfig[name] = value\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc addArgs(config map[string]interface{}) {\n\n\tparser := kingpin.Tokenize(os.Args[1:]).Tokens\n\n\tfor token, parser := parser.Peek(), parser.Next(); token.Type != kingpin.TokenEOL; token, parser = parser.Peek(), parser.Next() {\n\n\t\tif token.IsFlag() {\n\t\t\tvar value interface{}\n\t\t\tname := token.Value\n\n\t\t\tnext := parser.Peek()\n\t\t\tif next.Type == kingpin.TokenArg {\n\t\t\t\tif next.Value == \"false\" {\n\t\t\t\t\tvalue = false\n\t\t\t\t} else if next.Value == \"true\" {\n\t\t\t\t\tvalue = true\n\t\t\t\t} else {\n\t\t\t\t\tvalue = next.Value\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvalue = true\n\t\t\t\t\/\/ It's an environment indicator... like --cloud-production\n\t\t\t}\n\n\t\t\tconfig[name] = value\n\t\t}\n\n\t}\n\n}\n\nfunc addFile(path string, config map[string]interface{}) error {\n\t\/\/log.Debugf(\"Loading config file: %s\", path)\n\n\tfile, e := ioutil.ReadFile(path)\n\tif e != nil {\n\t\treturn fmt.Errorf(\"Failed to load file: %s error: %s\", path, e)\n\t}\n\n\tcontent := make(map[string]interface{})\n\te = json.Unmarshal(file, &content)\n\tif e != nil {\n\t\treturn fmt.Errorf(\"Failed to read file: %s error: %s\", path, e)\n\t}\n\n\t\/\/spew.Dump(path, content)\n\n\tflatten(content, nil, config)\n\treturn nil\n}\n\nfunc flatten(input interface{}, lpath []string, flattened map[string]interface{}) {\n\tif lpath == nil {\n\t\tlpath = []string{}\n\t}\n\n\tif reflect.ValueOf(input).Kind() == reflect.Map {\n\t\tfor rkey, value := range input.(map[string]interface{}) {\n\t\t\tflatten(value, append(lpath, rkey), flattened)\n\t\t}\n\t} else {\n\t\tif _, ok := flattened[strings.Join(lpath, \".\")]; !ok {\n\t\t\tflattened[strings.Join(lpath, \".\")] = input\n\t\t}\n\t}\n}\n\nfunc unflatten(flat map[string]interface{}) map[string]interface{} {\n\tout := make(map[string]interface{})\n\tobj := out\n\n\tfor key, val := range flat {\n\n\t\tobj = out\n\t\tkeys := strings.Split(key, \".\")\n\n\t\tfor i, k := range keys {\n\t\t\tif i == len(keys)-1 {\n\t\t\t\tobj[k] = val\n\t\t\t} else {\n\t\t\t\tnext, ok := obj[k]\n\t\t\t\tif !ok {\n\t\t\t\t\tnext = make(map[string]interface{})\n\t\t\t\t}\n\t\t\t\tobj[k] = next\n\t\t\t\tobj = next.(map[string]interface{})\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn out\n}\n\nfunc parseNumbers(config map[string]interface{}) {\n\tfor name, val := range config {\n\t\tstringVal, ok := val.(string)\n\t\tif ok {\n\t\t\tfloatVal, err := strconv.ParseFloat(stringVal, 64)\n\t\t\tif err == nil {\n\t\t\t\tconfig[name] = floatVal\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc getUserHome() string {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn \"\/root\"\n\t}\n\treturn usr.HomeDir\n}\n\nfunc IsSlave() bool {\n\tmasterNodeId := String(\"\", \"masterNodeId\")\n\tserial := Serial()\n\treturn masterNodeId != \"\" && serial != masterNodeId\n}\n\nfunc IsMaster() bool {\n\tmasterNodeId := String(\"\", \"masterNodeId\")\n\tserial := Serial()\n\treturn masterNodeId != \"\" && serial == masterNodeId\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"time\"\n\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\n\/\/ S3CloudStorageConfig stores the configuration of an S3 API proxy backend.\ntype S3CloudStorageConfig struct {\n\tEndpoint        string `yaml:\"endpoint\"`\n\tBucket          string `yaml:\"bucket\"`\n\tPrefix          string `yaml:\"prefix\"`\n\tAccessKeyID     string `yaml:\"access_key_id\"`\n\tSecretAccessKey string `yaml:\"secret_access_key\"`\n\tDisableSSL      bool   `yaml:\"disable_ssl\"`\n\tIAMRoleEndpoint string `yaml:\"iam_role_endpoint\"`\n\tRegion          string `yaml:\"region\"`\n}\n\n\/\/ GoogleCloudStorageConfig stores the configuration of a GCS proxy backend.\ntype GoogleCloudStorageConfig struct {\n\tBucket                string `yaml:\"bucket\"`\n\tUseDefaultCredentials bool   `yaml:\"use_default_credentials\"`\n\tJSONCredentialsFile   string `yaml:\"json_credentials_file\"`\n}\n\n\/\/ HTTPBackendConfig stores the configuration for a HTTP proxy backend.\ntype HTTPBackendConfig struct {\n\tBaseURL string `yaml:\"url\"`\n}\n\n\/\/ Config holds the top-level configuration for bazel-remote.\ntype Config struct {\n\tHost                    string                    `yaml:\"host\"`\n\tPort                    int                       `yaml:\"port\"`\n\tGRPCPort                int                       `yaml:\"grpc_port\"`\n\tProfileHost             string                    `yaml:\"profile_host\"`\n\tProfilePort             int                       `yaml:\"profile_port\"`\n\tDir                     string                    `yaml:\"dir\"`\n\tMaxSize                 int                       `yaml:\"max_size\"`\n\tHtpasswdFile            string                    `yaml:\"htpasswd_file\"`\n\tTLSCertFile             string                    `yaml:\"tls_cert_file\"`\n\tTLSKeyFile              string                    `yaml:\"tls_key_file\"`\n\tS3CloudStorage          *S3CloudStorageConfig     `yaml:\"s3_proxy\"`\n\tGoogleCloudStorage      *GoogleCloudStorageConfig `yaml:\"gcs_proxy\"`\n\tHTTPBackend             *HTTPBackendConfig        `yaml:\"http_proxy\"`\n\tIdleTimeout             time.Duration             `yaml:\"idle_timeout\"`\n\tDisableHTTPACValidation bool                      `yaml:\"disable_http_ac_validation\"`\n\tDisableGRPCACDepsCheck  bool                      `yaml:\"disable_grpc_ac_deps_check\"`\n}\n\n\/\/ New ...\nfunc New(dir string, maxSize int, host string, port int, grpcPort int,\n\tprofileHost string, profilePort int, htpasswdFile string,\n\ttlsCertFile string, tlsKeyFile string, idleTimeout time.Duration,\n\ts3 *S3CloudStorageConfig, disableHTTPACValidation bool,\n\tdisableGRPCACDepsCheck bool) (*Config, error) {\n\tc := Config{\n\t\tHost:                    host,\n\t\tPort:                    port,\n\t\tGRPCPort:                grpcPort,\n\t\tProfileHost:             profileHost,\n\t\tProfilePort:             profilePort,\n\t\tDir:                     dir,\n\t\tMaxSize:                 maxSize,\n\t\tHtpasswdFile:            htpasswdFile,\n\t\tTLSCertFile:             tlsCertFile,\n\t\tTLSKeyFile:              tlsKeyFile,\n\t\tS3CloudStorage:          s3,\n\t\tGoogleCloudStorage:      nil,\n\t\tHTTPBackend:             nil,\n\t\tIdleTimeout:             idleTimeout,\n\t\tDisableHTTPACValidation: disableHTTPACValidation,\n\t\tDisableGRPCACDepsCheck:  disableGRPCACDepsCheck,\n\t}\n\n\terr := validateConfig(&c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}\n\n\/\/ NewFromYamlFile ...\nfunc NewFromYamlFile(path string) (*Config, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to open config file '%s': %v\", path, err)\n\t}\n\tdefer file.Close()\n\n\tdata, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to read config file '%s': %v\", path, err)\n\t}\n\n\treturn newFromYaml(data)\n}\n\nfunc newFromYaml(data []byte) (*Config, error) {\n\tc := Config{}\n\terr := yaml.Unmarshal(data, &c)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to parse YAML config: %v\", err)\n\t}\n\n\terr = validateConfig(&c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}\n\nfunc validateConfig(c *Config) error {\n\tif c.Dir == \"\" {\n\t\treturn errors.New(\"The 'dir' flag\/key is required\")\n\t}\n\n\tif c.MaxSize <= 0 {\n\t\treturn errors.New(\"The 'max_size' flag\/key must be set to a value > 0\")\n\t}\n\n\tif c.Port == 0 {\n\t\treturn errors.New(\"A valid 'port' flag\/key must be specified\")\n\t}\n\n\tif c.GRPCPort < 0 {\n\t\treturn errors.New(\"The 'grpc_port' flag\/key must be 0 (disabled) or a positive integer\")\n\t}\n\n\tif (c.TLSCertFile != \"\" && c.TLSKeyFile == \"\") || (c.TLSCertFile == \"\" && c.TLSKeyFile != \"\") {\n\t\treturn errors.New(\"When enabling TLS one must specify both \" +\n\t\t\t\"'tls_key_file' and 'tls_cert_file'\")\n\t}\n\n\tif c.GoogleCloudStorage != nil && c.HTTPBackend != nil && c.S3CloudStorage != nil {\n\t\treturn errors.New(\"One can specify at most one proxying backend\")\n\t}\n\n\tif c.GoogleCloudStorage != nil {\n\t\tif c.GoogleCloudStorage.Bucket == \"\" {\n\t\t\treturn errors.New(\"The 'bucket' field is required for 'gcs_proxy'\")\n\t\t}\n\t}\n\n\tif c.HTTPBackend != nil {\n\t\tif c.HTTPBackend.BaseURL == \"\" {\n\t\t\treturn errors.New(\"The 'url' field is required for 'http_proxy'\")\n\t\t}\n\t}\n\n\tif c.S3CloudStorage != nil {\n\t\tif c.S3CloudStorage.AccessKeyID != \"\" && c.S3CloudStorage.IAMRoleEndpoint != \"\" {\n\t\t\treturn errors.New(\"Expected either 's3.access_key_id' or 's3.iam_role_endpoint', found both\")\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>config: add non-stub comments for New and NewFromYamlFile<commit_after>package config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"time\"\n\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\n\/\/ S3CloudStorageConfig stores the configuration of an S3 API proxy backend.\ntype S3CloudStorageConfig struct {\n\tEndpoint        string `yaml:\"endpoint\"`\n\tBucket          string `yaml:\"bucket\"`\n\tPrefix          string `yaml:\"prefix\"`\n\tAccessKeyID     string `yaml:\"access_key_id\"`\n\tSecretAccessKey string `yaml:\"secret_access_key\"`\n\tDisableSSL      bool   `yaml:\"disable_ssl\"`\n\tIAMRoleEndpoint string `yaml:\"iam_role_endpoint\"`\n\tRegion          string `yaml:\"region\"`\n}\n\n\/\/ GoogleCloudStorageConfig stores the configuration of a GCS proxy backend.\ntype GoogleCloudStorageConfig struct {\n\tBucket                string `yaml:\"bucket\"`\n\tUseDefaultCredentials bool   `yaml:\"use_default_credentials\"`\n\tJSONCredentialsFile   string `yaml:\"json_credentials_file\"`\n}\n\n\/\/ HTTPBackendConfig stores the configuration for a HTTP proxy backend.\ntype HTTPBackendConfig struct {\n\tBaseURL string `yaml:\"url\"`\n}\n\n\/\/ Config holds the top-level configuration for bazel-remote.\ntype Config struct {\n\tHost                    string                    `yaml:\"host\"`\n\tPort                    int                       `yaml:\"port\"`\n\tGRPCPort                int                       `yaml:\"grpc_port\"`\n\tProfileHost             string                    `yaml:\"profile_host\"`\n\tProfilePort             int                       `yaml:\"profile_port\"`\n\tDir                     string                    `yaml:\"dir\"`\n\tMaxSize                 int                       `yaml:\"max_size\"`\n\tHtpasswdFile            string                    `yaml:\"htpasswd_file\"`\n\tTLSCertFile             string                    `yaml:\"tls_cert_file\"`\n\tTLSKeyFile              string                    `yaml:\"tls_key_file\"`\n\tS3CloudStorage          *S3CloudStorageConfig     `yaml:\"s3_proxy\"`\n\tGoogleCloudStorage      *GoogleCloudStorageConfig `yaml:\"gcs_proxy\"`\n\tHTTPBackend             *HTTPBackendConfig        `yaml:\"http_proxy\"`\n\tIdleTimeout             time.Duration             `yaml:\"idle_timeout\"`\n\tDisableHTTPACValidation bool                      `yaml:\"disable_http_ac_validation\"`\n\tDisableGRPCACDepsCheck  bool                      `yaml:\"disable_grpc_ac_deps_check\"`\n}\n\n\/\/ New returns a validated Config with the specified values, and an error\n\/\/ if there were any problems with the validation.\nfunc New(dir string, maxSize int, host string, port int, grpcPort int,\n\tprofileHost string, profilePort int, htpasswdFile string,\n\ttlsCertFile string, tlsKeyFile string, idleTimeout time.Duration,\n\ts3 *S3CloudStorageConfig, disableHTTPACValidation bool,\n\tdisableGRPCACDepsCheck bool) (*Config, error) {\n\tc := Config{\n\t\tHost:                    host,\n\t\tPort:                    port,\n\t\tGRPCPort:                grpcPort,\n\t\tProfileHost:             profileHost,\n\t\tProfilePort:             profilePort,\n\t\tDir:                     dir,\n\t\tMaxSize:                 maxSize,\n\t\tHtpasswdFile:            htpasswdFile,\n\t\tTLSCertFile:             tlsCertFile,\n\t\tTLSKeyFile:              tlsKeyFile,\n\t\tS3CloudStorage:          s3,\n\t\tGoogleCloudStorage:      nil,\n\t\tHTTPBackend:             nil,\n\t\tIdleTimeout:             idleTimeout,\n\t\tDisableHTTPACValidation: disableHTTPACValidation,\n\t\tDisableGRPCACDepsCheck:  disableGRPCACDepsCheck,\n\t}\n\n\terr := validateConfig(&c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}\n\n\/\/ NewFromYamlFile reads configuration settings from a YAML file then returns\n\/\/ a validated Config with those settings, and an error if there were any\n\/\/ problems.\nfunc NewFromYamlFile(path string) (*Config, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to open config file '%s': %v\", path, err)\n\t}\n\tdefer file.Close()\n\n\tdata, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to read config file '%s': %v\", path, err)\n\t}\n\n\treturn newFromYaml(data)\n}\n\nfunc newFromYaml(data []byte) (*Config, error) {\n\tc := Config{}\n\terr := yaml.Unmarshal(data, &c)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to parse YAML config: %v\", err)\n\t}\n\n\terr = validateConfig(&c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}\n\nfunc validateConfig(c *Config) error {\n\tif c.Dir == \"\" {\n\t\treturn errors.New(\"The 'dir' flag\/key is required\")\n\t}\n\n\tif c.MaxSize <= 0 {\n\t\treturn errors.New(\"The 'max_size' flag\/key must be set to a value > 0\")\n\t}\n\n\tif c.Port == 0 {\n\t\treturn errors.New(\"A valid 'port' flag\/key must be specified\")\n\t}\n\n\tif c.GRPCPort < 0 {\n\t\treturn errors.New(\"The 'grpc_port' flag\/key must be 0 (disabled) or a positive integer\")\n\t}\n\n\tif (c.TLSCertFile != \"\" && c.TLSKeyFile == \"\") || (c.TLSCertFile == \"\" && c.TLSKeyFile != \"\") {\n\t\treturn errors.New(\"When enabling TLS one must specify both \" +\n\t\t\t\"'tls_key_file' and 'tls_cert_file'\")\n\t}\n\n\tif c.GoogleCloudStorage != nil && c.HTTPBackend != nil && c.S3CloudStorage != nil {\n\t\treturn errors.New(\"One can specify at most one proxying backend\")\n\t}\n\n\tif c.GoogleCloudStorage != nil {\n\t\tif c.GoogleCloudStorage.Bucket == \"\" {\n\t\t\treturn errors.New(\"The 'bucket' field is required for 'gcs_proxy'\")\n\t\t}\n\t}\n\n\tif c.HTTPBackend != nil {\n\t\tif c.HTTPBackend.BaseURL == \"\" {\n\t\t\treturn errors.New(\"The 'url' field is required for 'http_proxy'\")\n\t\t}\n\t}\n\n\tif c.S3CloudStorage != nil {\n\t\tif c.S3CloudStorage.AccessKeyID != \"\" && c.S3CloudStorage.IAMRoleEndpoint != \"\" {\n\t\t\treturn errors.New(\"Expected either 's3.access_key_id' or 's3.iam_role_endpoint', found both\")\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package inbloom\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"hash\"\n\t\"hash\/fnv\"\n\t\"math\"\n)\n\n\/\/ProbabilisticSet represents an abstraction of a Probabilistic\ntype ProbabilisticSet interface {\n\tAdd(obj *[]byte) error\n\tTest(obj *[]byte) (bool, error)\n}\n\n\/\/BloomFilter is a space-efficient probabilistic data structure, conceived by Burton Howard Bloom in 1970, that is used to test whether an element is a member of a set.\ntype BloomFilter struct {\n\tvector         []byte\n\tbaseHashFn     hash.Hash64\n\tnumberOfHashes uint64\n}\n\n\/\/Add an object to the set\nfunc (filter BloomFilter) Add(obj *[]byte) error {\n\n\thashValues, err := filter.getHashVector(obj)\n\n\tfor i := 0; i < len(hashValues); i++ {\n\t\thashVal := hashValues[i]\n\t\tfilter.vector[hashVal] = 1\n\t}\n\treturn err\n}\n\nfunc (filter *BloomFilter) getHashVector(obj *[]byte) ([]uint64, error) {\n\n\tdefer filter.baseHashFn.Reset()\n\n\tif filter == nil {\n\t\tfmt.Println(\"filter is null\")\n\t}\n\n\tif filter.baseHashFn == nil {\n\t\tfmt.Println(\"hash function is null\")\n\t}\n\t_, e1 := filter.baseHashFn.Write(*obj)\n\n\tif e1 != nil {\n\t\tempty := make([]uint64, 0)\n\t\treturn empty, errors.New(\"failed to add object to filter\")\n\t}\n\n\tseed1 := filter.baseHashFn.Sum64()\n\t\/\/ simulate output of two hash functions that will serve as base hashes for simulating the output of n hash functions\n\tupperBits := seed1 >> 32 << 32\n\tlowerBits := seed1 >> 32 << 32\n\thashValues := make([]uint64, filter.numberOfHashes)\n\tfor i := uint64(0); i < filter.numberOfHashes; i++ {\n\n\t\th := (upperBits + lowerBits*i) % filter.numberOfHashes\n\t\thashValues[i] = h\n\t}\n\n\treturn hashValues, nil\n}\n\n\/\/Test if an element is in the set\nfunc (filter BloomFilter) Test(obj *[]byte) (bool, error) {\n\n\thashVales, e := filter.getHashVector(obj)\n\n\tfor i := 0; i < len(hashVales); i++ {\n\t\thashVal := hashVales[i]\n\t\tif filter.vector[hashVal] == 0 {\n\t\t\treturn false, e\n\t\t}\n\t}\n\n\treturn true, e\n}\n\n\/\/NewFilter creates a new BloomFilter. p is the error rate\n\/\/and n is the estimated number of elements that will be handled by the filter\nfunc NewFilter(p float64, n int64) ProbabilisticSet {\n\n\t\/*\n\t\tGiven:\n\n\t\tn: how many items you expect to have in your filter (e.g. 216,553)\n\t\tp: your acceptable false positive rate {0..1} (e.g. 0.01 → 1%)\n\t\twe want to calculate:\n\n\t\tm: the number of bits needed in the bloom filter\n\t\tk: the number of hash functions we should apply\n\t\tThe formulas:\n\n\t\tm = -n*ln(p) \/ (ln(2)^2) the number of bits\n\t\tk = m\/n * ln(2) the number of hash functions\n\n\t*\/\n\n\tm := -float64(n) * math.Log(p) \/ math.Pow(math.Ln2, 2)\n\tk := uint64(m \/ float64(n) * math.Ln2)\n\n\treturn BloomFilter{vector: make([]byte, int64(m), int64(m)),\n\t\tbaseHashFn:     fnv.New64(),\n\t\tnumberOfHashes: k}\n}\n<commit_msg>fixed bug in hashing function, and cleaned up some code leftovers<commit_after>package inbloom\n\nimport (\n\t\"errors\"\n\t\"hash\"\n\t\"hash\/fnv\"\n\t\"math\"\n)\n\n\/\/ProbabilisticSet represents an abstraction of a Probabilistic\ntype ProbabilisticSet interface {\n\tAdd(obj *[]byte) error\n\tTest(obj *[]byte) (bool, error)\n}\n\n\/\/BloomFilter is a space-efficient probabilistic data structure, conceived by Burton Howard Bloom in 1970, that is used to test whether an element is a member of a set.\ntype BloomFilter struct {\n\tvector         []byte\n\tbaseHashFn     hash.Hash64\n\tnumberOfHashes uint64\n}\n\n\/\/Add an object to the set\nfunc (filter BloomFilter) Add(obj *[]byte) error {\n\n\thashValues, err := filter.getHashVector(obj)\n\n\tfor i := 0; i < len(hashValues); i++ {\n\t\thashVal := hashValues[i]\n\t\tfilter.vector[hashVal] = 1\n\t}\n\treturn err\n}\n\nfunc (filter *BloomFilter) getHashVector(obj *[]byte) ([]uint64, error) {\n\n\tdefer filter.baseHashFn.Reset()\n\n\t_, e1 := filter.baseHashFn.Write(*obj)\n\n\tif e1 != nil {\n\t\tempty := make([]uint64, 0)\n\t\treturn empty, errors.New(\"failed to add object to filter\")\n\t}\n\n\t\/\/ simulate output of two hash functions that will serve as base hashes for simulating the output of n hash functions\n\t\/\/ based on https:\/\/www.eecs.harvard.edu\/~michaelm\/postscripts\/rsa2008.pdf\n\n\t\/\/ instead of generating 2 hash values we optimize and generate only 1 and splitting it's value\n\t\/\/ into 2 distinct values simulating the values of two separate hash functions\n\tseed1 := filter.baseHashFn.Sum64()\n\n\tupperBits := seed1 >> 32 << 32\n\tlowerBits := seed1 >> 32 << 32\n\thashValues := make([]uint64, filter.numberOfHashes)\n\n\tfor i := uint64(0); i < filter.numberOfHashes; i++ {\n\n\t\th := (upperBits + lowerBits*i + uint64(math.Pow(float64(i), 2))) % filter.numberOfHashes\n\t\thashValues[i] = h\n\t}\n\n\treturn hashValues, nil\n}\n\n\/\/Test if an element is in the set\nfunc (filter BloomFilter) Test(obj *[]byte) (bool, error) {\n\n\thashVales, e := filter.getHashVector(obj)\n\n\tfor i := 0; i < len(hashVales); i++ {\n\t\thashVal := hashVales[i]\n\t\tif filter.vector[hashVal] == 0 {\n\t\t\treturn false, e\n\t\t}\n\t}\n\n\treturn true, e\n}\n\n\/\/NewFilter creates a new BloomFilter. p is the error rate\n\/\/and n is the estimated number of elements that will be handled by the filter\nfunc NewFilter(p float64, n int64) ProbabilisticSet {\n\n\t\/*\n\t\tGiven:\n\n\t\tn: how many items you expect to have in your filter (e.g. 216,553)\n\t\tp: your acceptable false positive rate {0..1} (e.g. 0.01 → 1%)\n\t\twe want to calculate:\n\n\t\tm: the number of bits needed in the bloom filter\n\t\tk: the number of hash functions we should apply\n\t\tThe formulas:\n\n\t\tm = -n*ln(p) \/ (ln(2)^2) the number of bits\n\t\tk = m\/n * ln(2) the number of hash functions\n\n\t*\/\n\n\tm := -float64(n) * math.Log(p) \/ math.Pow(math.Ln2, 2)\n\tk := uint64(m \/ float64(n) * math.Ln2)\n\n\treturn BloomFilter{vector: make([]byte, int64(m), int64(m)),\n\t\tbaseHashFn:     fnv.New64(),\n\t\tnumberOfHashes: k}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016-2019 Granitic. All rights reserved.\n\/\/ Use of this source code is governed by an Apache 2.0 license that can be found in the LICENSE file at the root of this project.\n\n\/*\nPackage config provides functionality for working with configuration files and command line arguments to a Granitic application.\n\nGrantic uses JSON files to store component definitions (declarations of, and relationships between, components to\nrun in the IoC container) and configuration (variables used by IoC components that may vary between environments and settings\nfor Grantic's built-in facilities). A definition of the use and syntax of these files are outside of the scope of a GoDoc page,\nbut are described in detail at https:\/\/granitic.io\/ref\/component-definition-files and https:\/\/granitic.io\/ref\/configuration-files\n\nThis package defines functionality for loading a JSON file (from a filesystem or via HTTP) and merging multiple files into\na single view. This is a key concept in Granitic.\n\nGiven a folder of configuration files called conf:\n\tconf\/x.json\n\tconf\/sub\/a.json\n\tconf\/sub\/b.json\n\nstarting a Grantic application with:\n\n\t-c http:\/\/example.com\/base.json,conf,http:\/\/example.com\/myinstance.json\n\nThe following will take place. Firstly the files would be expanded into a flat list of paths\/URIs\n\n\thttp:\/\/example.com\/base.json\n\tconf\/sub\/a.json\n\tconf\/sub\/b.json\n\tconf\/x.json\n\thttp:\/\/example.com\/myinstance.json\n\nThe the files will be merged together from left, using the the first file as a base. In this example,  http:\/\/example.com\/base.json\nand conf\/sub\/a.json will be merged together, then result of that merge will be merged with conf\/sub\/b.json and so on.\n\nFor named fields (in a JSON object\/map), the process of merging is fairly obvious. When merging files A and B, a field that\nis defined in both files will have the value of the field used in file B in the merged output. For example,\n\n\ta.json\n\n\t{\n\t\t\"database\": {\n\t\t\t\"host\": \"localhost\",\n\t\t\t\"port\": 3306,\n\t\t\t\"flags\": [\"a\", \"b\", \"c\"]\n\t\t}\n\t}\n\nand\n\n\tb.json\n\n\t{\n\t\t\"database\": {\n\t\t\t\"host\": \"remotehost\",\n\t\t\t\"flags\": [\"d\"]\n\t\t}\n\t}\n\nwoud merge to:\n\n\t{\n\t\t\"database\": {\n\t\t\t\"host\": \"remotehost\",\n\t\t\t\"port\": 3306,\n\t\t\t\"flags\": [\"d\"]\n\t\t}\n\t}\n\nThe merging of configuration files occurs exactly above, but when component definition files are merged, arrays are joined, not overwritten.\nFor example:\n\n\t{ \"methods\": [\"GET\"] }\n\nmerged with;\n\n\t{ \"methods\": [\"POST\"] }\n\nwould result in:\n\n\t{ \"methods\": [\"GET\", \"POST\"] }\n\nAnother core concept used by the types in this package is a config path. This is the absolute path to field in the\neventual merged configuration file with a dot-delimited notation. E.g \"database.host\".\n*\/\npackage config\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/graniticio\/granitic\/v2\/logging\"\n\t\"reflect\"\n\t\"strings\"\n)\n\n\/\/ JSONPathSeparator is the character used to delimit paths to config values.\nconst JSONPathSeparator string = \".\"\n\n\/\/ Used by code that needs to know what type of JSON data structure resides at a particular path\n\/\/ before operating on it.\nconst (\n\tUnset       = -2\n\tJSONUnknown = -1\n\tJSONString  = 1\n\tJSONArray   = 2\n\tJSONMap     = 3\n\tJSONBool    = 4\n)\n\n\/\/ MissingPathError indicates that the a problem was caused by there being no value at the supplied\n\/\/ config path\ntype MissingPathError struct {\n\tmessage string\n}\n\nfunc (mp MissingPathError) Error() string {\n\treturn mp.message\n}\n\n\/\/ A Accessor provides access to a merged view of configuration files during the initialisation and\n\/\/ configuration of the Granitic IoC container.\ntype Accessor struct {\n\t\/\/ The merged JSON configuration in object form.\n\tJSONData map[string]interface{}\n\n\t\/\/ Logger used by Granitic framework components. Automatically injected.\n\tFrameworkLogger logging.Logger\n}\n\n\/\/ Flush removes internal references to the (potentially very large) merged JSON data so the associated\n\/\/ memory can be recovered during the next garbage collection.\nfunc (ac *Accessor) Flush() {\n\tac.JSONData = nil\n}\n\n\/\/ PathExists check to see whether the supplied dot-delimited path exists in the configuration and points to a non-null JSON value.\nfunc (ac *Accessor) PathExists(path string) bool {\n\tvalue := ac.Value(path)\n\n\treturn value != nil\n}\n\n\/\/ Value returns the JSON value at the supplied path or nil if the path does not exist of points to a null JSON value.\nfunc (ac *Accessor) Value(path string) interface{} {\n\n\tsplitPath := strings.Split(path, JSONPathSeparator)\n\n\treturn ac.configVal(splitPath, ac.JSONData)\n\n}\n\n\/\/ ObjectVal returns a map representing a JSON object or nil if the path does not exist of points to a null JSON value. An error\n\/\/ is returned if the value cannot be interpreted as a JSON object.\nfunc (ac *Accessor) ObjectVal(path string) (map[string]interface{}, error) {\n\n\tvalue := ac.Value(path)\n\n\tif value == nil {\n\t\treturn nil, nil\n\t} else if v, found := value.(map[string]interface{}); found {\n\t\treturn v, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unable to convert the value at %s to a JSON map\/object\", path)\n\n}\n\n\/\/ StringVal returns the string value of the JSON string at the supplied path. Does not convert other types to\n\/\/ a string, so will return an error if the value is not a JSON string.\nfunc (ac *Accessor) StringVal(path string) (string, error) {\n\n\tv := ac.Value(path)\n\n\tif v == nil {\n\t\treturn \"\", errors.New(\"No string value found at \" + path)\n\t}\n\n\ts, found := v.(string)\n\n\tif found {\n\t\treturn s, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"Value at %s is %q and cannot be converted to a string\", path, v)\n\n}\n\n\/\/ IntVal returns the int value of the JSON number at the supplied path. JSON numbers\n\/\/ are internally represented by Go as a float64, so no error will be returned, but data might be lost\n\/\/ if the JSON number does not actually represent an int. An error will be returned if the value is not a JSON number\n\/\/ or cannot be converted to an int.\nfunc (ac *Accessor) IntVal(path string) (int, error) {\n\n\tv := ac.Value(path)\n\n\tif v == nil {\n\t\treturn 0, errors.New(\"No such path \" + path)\n\t} else if f, found := v.(float64); found {\n\t\treturn int(f), nil\n\t}\n\n\treturn 0, fmt.Errorf(\"alue at %s is %q and cannot be converted to an int\", path, v)\n\n}\n\n\/\/ Float64Val returns the float64 value of the JSON number at the supplied path. An error will be returned if the value is not a JSON number.\nfunc (ac *Accessor) Float64Val(path string) (float64, error) {\n\n\tv := ac.Value(path)\n\n\tif v == nil {\n\t\treturn 0, errors.New(\"No such path \" + path)\n\t} else if f, found := v.(float64); found {\n\t\treturn f, nil\n\t}\n\n\treturn 0, fmt.Errorf(\"value at %s is %q and cannot be converted to a float64\", path, v)\n}\n\n\/\/ Array returns the value of an array of JSON obects at the supplied path. Caution should be used when calling this method\n\/\/ as behaviour is undefined for JSON arrays of JSON types other than object.\nfunc (ac *Accessor) Array(path string) ([]interface{}, error) {\n\n\tvalue := ac.Value(path)\n\n\tif value == nil {\n\t\treturn nil, nil\n\t} else if v, found := value.([]interface{}); found {\n\t\treturn v, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unable to convert the value at %s to a JSON array\", path)\n\n}\n\n\/\/ BoolVal returns the bool value of the JSON bool at the supplied path. An error will be returned if the value is not a JSON bool.\n\/\/ Note this method only suports the JSON definition of bools (true, false) not the Go definition (true, false, 1, 0 etc).\nfunc (ac *Accessor) BoolVal(path string) (bool, error) {\n\n\tv := ac.Value(path)\n\n\tif v == nil {\n\t\treturn false, errors.New(\"No such path \" + path)\n\t}\n\n\tif b, found := v.(bool); found {\n\t\treturn b, nil\n\t}\n\n\treturn false, fmt.Errorf(\"Value at %s is %q and cannot be converted to a bool\", path, v)\n\n}\n\n\/\/ JSONType determines the apparent JSONType of the supplied Go interface.\nfunc JSONType(value interface{}) int {\n\n\tswitch value.(type) {\n\tcase string:\n\t\treturn JSONString\n\tcase map[string]interface{}:\n\t\treturn JSONMap\n\tcase bool:\n\t\treturn JSONBool\n\tcase []interface{}:\n\t\treturn JSONArray\n\tdefault:\n\t\treturn JSONUnknown\n\t}\n}\n\nfunc (ac *Accessor) configVal(path []string, jsonMap map[string]interface{}) interface{} {\n\n\tvar result interface{}\n\tresult = jsonMap[path[0]]\n\n\tif result == nil {\n\t\treturn nil\n\t}\n\n\tif len(path) == 1 {\n\t\treturn result\n\t}\n\n\tremainPath := path[1:len(path)]\n\treturn ac.configVal(remainPath, result.(map[string]interface{}))\n}\n\n\/\/ SetField takes a target Go interface and uses the data a the supplied path to populated the named field on the\n\/\/ target. The target must be a pointer to a struct. The field must be a string, bool, int, float63, string[interface{}] map\n\/\/ or a slice of one of those types. An eror will be returned if the target field, is missing, not settable or incompatible\n\/\/ with the JSON value at the supplied path.\nfunc (ac *Accessor) SetField(fieldName string, path string, target interface{}) error {\n\n\tif !ac.PathExists(path) {\n\t\treturn MissingPathError{message: \"No value found at \" + path}\n\t}\n\n\ttargetReflect := reflect.ValueOf(target).Elem()\n\ttargetField := targetReflect.FieldByName(fieldName)\n\n\tk := targetField.Type().Kind()\n\n\tswitch k {\n\tcase reflect.String:\n\t\ts, _ := ac.StringVal(path)\n\t\ttargetField.SetString(s)\n\tcase reflect.Bool:\n\t\tb, _ := ac.BoolVal(path)\n\t\ttargetField.SetBool(b)\n\tcase reflect.Int:\n\t\ti, _ := ac.IntVal(path)\n\t\ttargetField.SetInt(int64(i))\n\tcase reflect.Float64:\n\t\tf, _ := ac.Float64Val(path)\n\t\ttargetField.SetFloat(f)\n\tcase reflect.Map:\n\n\t\tif v, err := ac.ObjectVal(path); err == nil {\n\t\t\tif err = ac.populateMapField(targetField, v); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\tcase reflect.Slice:\n\t\tac.populateSlice(targetField, path, target)\n\n\tdefault:\n\t\tm := fmt.Sprintf(\"Unable to use value at path %s as target field %s is not a suppported type (%s)\", path, fieldName, k)\n\t\tac.FrameworkLogger.LogErrorf(m)\n\n\t\treturn errors.New(m)\n\t}\n\n\treturn nil\n}\n\nfunc (ac *Accessor) populateSlice(targetField reflect.Value, path string, target interface{}) {\n\n\tv := ac.Value(path)\n\n\tdata, _ := json.Marshal(v)\n\n\tvt := targetField.Type()\n\tnt := reflect.New(vt)\n\n\tjTarget := nt.Interface()\n\tjson.Unmarshal(data, &jTarget)\n\n\tvr := reflect.ValueOf(jTarget)\n\ttargetField.Set(vr.Elem())\n\n}\n\nfunc (ac *Accessor) populateMapField(targetField reflect.Value, contents map[string]interface{}) error {\n\tvar err error\n\n\tm := reflect.MakeMap(targetField.Type())\n\ttargetField.Set(m)\n\n\tfor k, v := range contents {\n\n\t\tkeyVal := reflect.ValueOf(k)\n\t\tvVal := reflect.ValueOf(v)\n\n\t\tif vVal.Kind() == reflect.Slice {\n\t\t\tvVal, err = ac.arrayVal(vVal)\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tm.SetMapIndex(keyVal, vVal)\n\n\t}\n\n\treturn nil\n}\n\nfunc (ac *Accessor) arrayVal(a reflect.Value) (reflect.Value, error) {\n\n\tv := a.Interface().([]interface{})\n\tl := len(v)\n\n\tif l == 0 {\n\n\t\treturn reflect.Zero(reflect.TypeOf(ac)), errors.New(\"cannot use an empty array as a value in a Map\")\n\n\t}\n\n\tvar s reflect.Value\n\n\tswitch t := v[0].(type) {\n\tcase string:\n\t\ts = reflect.MakeSlice(reflect.TypeOf([]string{}), 0, 0)\n\tdefault:\n\t\tm := fmt.Sprintf(\"Cannot use an array of %T as a value in a Map.\", t)\n\t\treturn reflect.Zero(reflect.TypeOf(ac)), errors.New(m)\n\t}\n\n\tfor _, elem := range v {\n\n\t\ts = reflect.Append(s, reflect.ValueOf(elem))\n\n\t}\n\n\treturn s, nil\n}\n\n\/\/ Populate sets the fields on the supplied target object using the JSON data\n\/\/ at the supplied path. This is achieved using Go's json.Marshal to convert the data\n\/\/ back into text JSON and then json.Unmarshal to unmarshal back into the target.\nfunc (ac *Accessor) Populate(path string, target interface{}) error {\n\texists := ac.PathExists(path)\n\n\tif !exists {\n\t\treturn errors.New(\"No such path: \" + path)\n\t}\n\n\t\/\/Already check if path exists\n\tobject, _ := ac.ObjectVal(path)\n\n\tif data, err := json.Marshal(object); err != nil {\n\t\tm := fmt.Sprintf(\"%T cannot be marshalled to JSON\", object)\n\t\treturn errors.New(m)\n\t} else if json.Unmarshal(data, target); err != nil {\n\t\treturn fmt.Errorf(\"%T cannot be populated with %v to JSON\", object, data)\n\t}\n\n\treturn nil\n\n}\n<commit_msg>Run gofmt.<commit_after>\/\/ Copyright 2016-2019 Granitic. All rights reserved.\n\/\/ Use of this source code is governed by an Apache 2.0 license that can be found in the LICENSE file at the root of this project.\n\n\/*\nPackage config provides functionality for working with configuration files and command line arguments to a Granitic application.\n\nGrantic uses JSON files to store component definitions (declarations of, and relationships between, components to\nrun in the IoC container) and configuration (variables used by IoC components that may vary between environments and settings\nfor Grantic's built-in facilities). A definition of the use and syntax of these files are outside of the scope of a GoDoc page,\nbut are described in detail at https:\/\/granitic.io\/ref\/component-definition-files and https:\/\/granitic.io\/ref\/configuration-files\n\nThis package defines functionality for loading a JSON file (from a filesystem or via HTTP) and merging multiple files into\na single view. This is a key concept in Granitic.\n\nGiven a folder of configuration files called conf:\n\tconf\/x.json\n\tconf\/sub\/a.json\n\tconf\/sub\/b.json\n\nstarting a Grantic application with:\n\n\t-c http:\/\/example.com\/base.json,conf,http:\/\/example.com\/myinstance.json\n\nThe following will take place. Firstly the files would be expanded into a flat list of paths\/URIs\n\n\thttp:\/\/example.com\/base.json\n\tconf\/sub\/a.json\n\tconf\/sub\/b.json\n\tconf\/x.json\n\thttp:\/\/example.com\/myinstance.json\n\nThe the files will be merged together from left, using the the first file as a base. In this example,  http:\/\/example.com\/base.json\nand conf\/sub\/a.json will be merged together, then result of that merge will be merged with conf\/sub\/b.json and so on.\n\nFor named fields (in a JSON object\/map), the process of merging is fairly obvious. When merging files A and B, a field that\nis defined in both files will have the value of the field used in file B in the merged output. For example,\n\n\ta.json\n\n\t{\n\t\t\"database\": {\n\t\t\t\"host\": \"localhost\",\n\t\t\t\"port\": 3306,\n\t\t\t\"flags\": [\"a\", \"b\", \"c\"]\n\t\t}\n\t}\n\nand\n\n\tb.json\n\n\t{\n\t\t\"database\": {\n\t\t\t\"host\": \"remotehost\",\n\t\t\t\"flags\": [\"d\"]\n\t\t}\n\t}\n\nwoud merge to:\n\n\t{\n\t\t\"database\": {\n\t\t\t\"host\": \"remotehost\",\n\t\t\t\"port\": 3306,\n\t\t\t\"flags\": [\"d\"]\n\t\t}\n\t}\n\nThe merging of configuration files occurs exactly above, but when component definition files are merged, arrays are joined, not overwritten.\nFor example:\n\n\t{ \"methods\": [\"GET\"] }\n\nmerged with;\n\n\t{ \"methods\": [\"POST\"] }\n\nwould result in:\n\n\t{ \"methods\": [\"GET\", \"POST\"] }\n\nAnother core concept used by the types in this package is a config path. This is the absolute path to field in the\neventual merged configuration file with a dot-delimited notation. E.g \"database.host\".\n*\/\npackage config\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/graniticio\/granitic\/v2\/logging\"\n\t\"reflect\"\n\t\"strings\"\n)\n\n\/\/ JSONPathSeparator is the character used to delimit paths to config values.\nconst JSONPathSeparator string = \".\"\n\n\/\/ Used by code that needs to know what type of JSON data structure resides at a particular path\n\/\/ before operating on it.\nconst (\n\tUnset       = -2\n\tJSONUnknown = -1\n\tJSONString  = 1\n\tJSONArray   = 2\n\tJSONMap     = 3\n\tJSONBool    = 4\n)\n\n\/\/ MissingPathError indicates that the a problem was caused by there being no value at the supplied\n\/\/ config path\ntype MissingPathError struct {\n\tmessage string\n}\n\nfunc (mp MissingPathError) Error() string {\n\treturn mp.message\n}\n\n\/\/ A Accessor provides access to a merged view of configuration files during the initialisation and\n\/\/ configuration of the Granitic IoC container.\ntype Accessor struct {\n\t\/\/ The merged JSON configuration in object form.\n\tJSONData map[string]interface{}\n\n\t\/\/ Logger used by Granitic framework components. Automatically injected.\n\tFrameworkLogger logging.Logger\n}\n\n\/\/ Flush removes internal references to the (potentially very large) merged JSON data so the associated\n\/\/ memory can be recovered during the next garbage collection.\nfunc (ac *Accessor) Flush() {\n\tac.JSONData = nil\n}\n\n\/\/ PathExists check to see whether the supplied dot-delimited path exists in the configuration and points to a non-null JSON value.\nfunc (ac *Accessor) PathExists(path string) bool {\n\tvalue := ac.Value(path)\n\n\treturn value != nil\n}\n\n\/\/ Value returns the JSON value at the supplied path or nil if the path does not exist of points to a null JSON value.\nfunc (ac *Accessor) Value(path string) interface{} {\n\n\tsplitPath := strings.Split(path, JSONPathSeparator)\n\n\treturn ac.configVal(splitPath, ac.JSONData)\n\n}\n\n\/\/ ObjectVal returns a map representing a JSON object or nil if the path does not exist of points to a null JSON value. An error\n\/\/ is returned if the value cannot be interpreted as a JSON object.\nfunc (ac *Accessor) ObjectVal(path string) (map[string]interface{}, error) {\n\n\tvalue := ac.Value(path)\n\n\tif value == nil {\n\t\treturn nil, nil\n\t} else if v, found := value.(map[string]interface{}); found {\n\t\treturn v, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unable to convert the value at %s to a JSON map\/object\", path)\n\n}\n\n\/\/ StringVal returns the string value of the JSON string at the supplied path. Does not convert other types to\n\/\/ a string, so will return an error if the value is not a JSON string.\nfunc (ac *Accessor) StringVal(path string) (string, error) {\n\n\tv := ac.Value(path)\n\n\tif v == nil {\n\t\treturn \"\", errors.New(\"No string value found at \" + path)\n\t}\n\n\ts, found := v.(string)\n\n\tif found {\n\t\treturn s, nil\n\t}\n\n\treturn \"\", fmt.Errorf(\"Value at %s is %q and cannot be converted to a string\", path, v)\n\n}\n\n\/\/ IntVal returns the int value of the JSON number at the supplied path. JSON numbers\n\/\/ are internally represented by Go as a float64, so no error will be returned, but data might be lost\n\/\/ if the JSON number does not actually represent an int. An error will be returned if the value is not a JSON number\n\/\/ or cannot be converted to an int.\nfunc (ac *Accessor) IntVal(path string) (int, error) {\n\n\tv := ac.Value(path)\n\n\tif v == nil {\n\t\treturn 0, errors.New(\"No such path \" + path)\n\t} else if f, found := v.(float64); found {\n\t\treturn int(f), nil\n\t}\n\n\treturn 0, fmt.Errorf(\"alue at %s is %q and cannot be converted to an int\", path, v)\n\n}\n\n\/\/ Float64Val returns the float64 value of the JSON number at the supplied path. An error will be returned if the value is not a JSON number.\nfunc (ac *Accessor) Float64Val(path string) (float64, error) {\n\n\tv := ac.Value(path)\n\n\tif v == nil {\n\t\treturn 0, errors.New(\"No such path \" + path)\n\t} else if f, found := v.(float64); found {\n\t\treturn f, nil\n\t}\n\n\treturn 0, fmt.Errorf(\"value at %s is %q and cannot be converted to a float64\", path, v)\n}\n\n\/\/ Array returns the value of an array of JSON obects at the supplied path. Caution should be used when calling this method\n\/\/ as behaviour is undefined for JSON arrays of JSON types other than object.\nfunc (ac *Accessor) Array(path string) ([]interface{}, error) {\n\n\tvalue := ac.Value(path)\n\n\tif value == nil {\n\t\treturn nil, nil\n\t} else if v, found := value.([]interface{}); found {\n\t\treturn v, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unable to convert the value at %s to a JSON array\", path)\n\n}\n\n\/\/ BoolVal returns the bool value of the JSON bool at the supplied path. An error will be returned if the value is not a JSON bool.\n\/\/ Note this method only suports the JSON definition of bools (true, false) not the Go definition (true, false, 1, 0 etc).\nfunc (ac *Accessor) BoolVal(path string) (bool, error) {\n\n\tv := ac.Value(path)\n\n\tif v == nil {\n\t\treturn false, errors.New(\"No such path \" + path)\n\t}\n\n\tif b, found := v.(bool); found {\n\t\treturn b, nil\n\t}\n\n\treturn false, fmt.Errorf(\"Value at %s is %q and cannot be converted to a bool\", path, v)\n\n}\n\n\/\/ JSONType determines the apparent JSONType of the supplied Go interface.\nfunc JSONType(value interface{}) int {\n\n\tswitch value.(type) {\n\tcase string:\n\t\treturn JSONString\n\tcase map[string]interface{}:\n\t\treturn JSONMap\n\tcase bool:\n\t\treturn JSONBool\n\tcase []interface{}:\n\t\treturn JSONArray\n\tdefault:\n\t\treturn JSONUnknown\n\t}\n}\n\nfunc (ac *Accessor) configVal(path []string, jsonMap map[string]interface{}) interface{} {\n\n\tvar result interface{}\n\tresult = jsonMap[path[0]]\n\n\tif result == nil {\n\t\treturn nil\n\t}\n\n\tif len(path) == 1 {\n\t\treturn result\n\t}\n\n\tremainPath := path[1:]\n\treturn ac.configVal(remainPath, result.(map[string]interface{}))\n}\n\n\/\/ SetField takes a target Go interface and uses the data a the supplied path to populated the named field on the\n\/\/ target. The target must be a pointer to a struct. The field must be a string, bool, int, float63, string[interface{}] map\n\/\/ or a slice of one of those types. An eror will be returned if the target field, is missing, not settable or incompatible\n\/\/ with the JSON value at the supplied path.\nfunc (ac *Accessor) SetField(fieldName string, path string, target interface{}) error {\n\n\tif !ac.PathExists(path) {\n\t\treturn MissingPathError{message: \"No value found at \" + path}\n\t}\n\n\ttargetReflect := reflect.ValueOf(target).Elem()\n\ttargetField := targetReflect.FieldByName(fieldName)\n\n\tk := targetField.Type().Kind()\n\n\tswitch k {\n\tcase reflect.String:\n\t\ts, _ := ac.StringVal(path)\n\t\ttargetField.SetString(s)\n\tcase reflect.Bool:\n\t\tb, _ := ac.BoolVal(path)\n\t\ttargetField.SetBool(b)\n\tcase reflect.Int:\n\t\ti, _ := ac.IntVal(path)\n\t\ttargetField.SetInt(int64(i))\n\tcase reflect.Float64:\n\t\tf, _ := ac.Float64Val(path)\n\t\ttargetField.SetFloat(f)\n\tcase reflect.Map:\n\n\t\tif v, err := ac.ObjectVal(path); err == nil {\n\t\t\tif err = ac.populateMapField(targetField, v); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\tcase reflect.Slice:\n\t\tac.populateSlice(targetField, path, target)\n\n\tdefault:\n\t\tm := fmt.Sprintf(\"Unable to use value at path %s as target field %s is not a suppported type (%s)\", path, fieldName, k)\n\t\tac.FrameworkLogger.LogErrorf(m)\n\n\t\treturn errors.New(m)\n\t}\n\n\treturn nil\n}\n\nfunc (ac *Accessor) populateSlice(targetField reflect.Value, path string, target interface{}) {\n\n\tv := ac.Value(path)\n\n\tdata, _ := json.Marshal(v)\n\n\tvt := targetField.Type()\n\tnt := reflect.New(vt)\n\n\tjTarget := nt.Interface()\n\tjson.Unmarshal(data, &jTarget)\n\n\tvr := reflect.ValueOf(jTarget)\n\ttargetField.Set(vr.Elem())\n\n}\n\nfunc (ac *Accessor) populateMapField(targetField reflect.Value, contents map[string]interface{}) error {\n\tvar err error\n\n\tm := reflect.MakeMap(targetField.Type())\n\ttargetField.Set(m)\n\n\tfor k, v := range contents {\n\n\t\tkeyVal := reflect.ValueOf(k)\n\t\tvVal := reflect.ValueOf(v)\n\n\t\tif vVal.Kind() == reflect.Slice {\n\t\t\tvVal, err = ac.arrayVal(vVal)\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tm.SetMapIndex(keyVal, vVal)\n\n\t}\n\n\treturn nil\n}\n\nfunc (ac *Accessor) arrayVal(a reflect.Value) (reflect.Value, error) {\n\n\tv := a.Interface().([]interface{})\n\tl := len(v)\n\n\tif l == 0 {\n\n\t\treturn reflect.Zero(reflect.TypeOf(ac)), errors.New(\"cannot use an empty array as a value in a Map\")\n\n\t}\n\n\tvar s reflect.Value\n\n\tswitch t := v[0].(type) {\n\tcase string:\n\t\ts = reflect.MakeSlice(reflect.TypeOf([]string{}), 0, 0)\n\tdefault:\n\t\tm := fmt.Sprintf(\"Cannot use an array of %T as a value in a Map.\", t)\n\t\treturn reflect.Zero(reflect.TypeOf(ac)), errors.New(m)\n\t}\n\n\tfor _, elem := range v {\n\n\t\ts = reflect.Append(s, reflect.ValueOf(elem))\n\n\t}\n\n\treturn s, nil\n}\n\n\/\/ Populate sets the fields on the supplied target object using the JSON data\n\/\/ at the supplied path. This is achieved using Go's json.Marshal to convert the data\n\/\/ back into text JSON and then json.Unmarshal to unmarshal back into the target.\nfunc (ac *Accessor) Populate(path string, target interface{}) error {\n\texists := ac.PathExists(path)\n\n\tif !exists {\n\t\treturn errors.New(\"No such path: \" + path)\n\t}\n\n\t\/\/Already check if path exists\n\tobject, _ := ac.ObjectVal(path)\n\n\tif data, err := json.Marshal(object); err != nil {\n\t\tm := fmt.Sprintf(\"%T cannot be marshalled to JSON\", object)\n\t\treturn errors.New(m)\n\t} else if json.Unmarshal(data, target); err != nil {\n\t\treturn fmt.Errorf(\"%T cannot be populated with %v to JSON\", object, data)\n\t}\n\n\treturn nil\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\/user\"\n\n\tyaml \"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ ClusterName is the name of an ECS Cluster (example: \"mountain\")\ntype ClusterName string\n\n\/\/ FilePath is the path to a yaml file on disk\ntype FilePath string\n\n\/\/ Keys is a map of cluster names\ntype Keys map[ClusterName]FilePath\n\n\/\/ Config represents global application configuration\ntype Config struct {\n\tKeys Keys `yaml:\"keys\"`\n}\n\n\/\/ Storage is a mechanism for storing ECS Commander Config!\ntype Storage interface {\n\tReadKeys() (Keys, error)\n\tSaveKeys(Keys) error\n\tIsModified() bool\n}\n\n\/\/ ReadKeys returns you the existing keys if they exist,\n\/\/ if not, will return a new, blank, Keys struct\nfunc ReadKeys(adapter Storage) (Keys, error) {\n\treturn adapter.ReadKeys()\n}\n\n\/\/ YAMLFile stores config in a YAML file on disk,\n\/\/ this is the default.  It implements the storage\n\/\/ adapter interface.\ntype YAMLFile struct {\n\tpath     string\n\tcontent  []byte\n\tmodified bool\n}\n\n\/\/ GetYAMLConfig gets, or creates, a yaml configuration\n\/\/ file from disk\nfunc GetYAMLConfig() *YAMLFile {\n\tfile := viper.ConfigFileUsed()\n\tconfigFile := NewYAMLFile()\n\tif file != \"\" {\n\t\tconfigFile = ReadYAMLFile(file)\n\t}\n\treturn configFile\n}\n\n\/\/ NewYAMLFile creates a new and empty YAML file\nfunc NewYAMLFile() *YAMLFile {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn &YAMLFile{path: fmt.Sprintf(\"%s\/.ecs-commander.yaml\", usr.HomeDir)}\n}\n\n\/\/ ReadYAMLFile Sets the file to be used for storing config\nfunc ReadYAMLFile(path string) *YAMLFile {\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Tried to read config file from %s, but failed. %v\", content, err))\n\t}\n\tyamlFile := &YAMLFile{path: path, content: content}\n\treturn yamlFile\n}\n\n\/\/ ReadKeys implements a key reader for yaml files\nfunc (yamlFile *YAMLFile) ReadKeys() (Keys, error) {\n\tconfig := &Config{}\n\terr := yaml.Unmarshal(yamlFile.content, &config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn config.Keys, nil\n}\n\n\/\/ SaveKeys implements a key writer for yaml files\nfunc (yamlFile *YAMLFile) SaveKeys(keys Keys) error {\n\tconfig := &Config{}\n\terr := yaml.Unmarshal(yamlFile.content, &config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.Keys = keys\n\tbytes, err := yaml.Marshal(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(yamlFile.path, bytes, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ IsModified implements a modified\nfunc (yamlFile *YAMLFile) IsModified() bool {\n\treturn true\n}\n\n\/\/ GetClusterKey returns the registered key path for a cluster\nfunc GetClusterKey(cluster string) string {\n\tout := fmt.Sprintf(\"~\/%s.pem\", cluster)\n\tallKeys, err := GetYAMLConfig().ReadKeys()\n\tif err != nil {\n\t\treturn out\n\t}\n\tif key, ok := allKeys[ClusterName(cluster)]; ok {\n\t\tout = string(key)\n\t}\n\treturn out\n}\n<commit_msg>Fix bug with empty config<commit_after>package config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\/user\"\n\n\tyaml \"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ ClusterName is the name of an ECS Cluster (example: \"mountain\")\ntype ClusterName string\n\n\/\/ FilePath is the path to a yaml file on disk\ntype FilePath string\n\n\/\/ Keys is a map of cluster names\ntype Keys map[ClusterName]FilePath\n\n\/\/ Config represents global application configuration\ntype Config struct {\n\tKeys Keys `yaml:\"keys\"`\n}\n\n\/\/ Storage is a mechanism for storing ECS Commander Config!\ntype Storage interface {\n\tReadKeys() (Keys, error)\n\tSaveKeys(Keys) error\n\tIsModified() bool\n}\n\n\/\/ ReadKeys returns you the existing keys if they exist,\n\/\/ if not, will return a new, blank, Keys struct\nfunc ReadKeys(adapter Storage) (Keys, error) {\n\treturn adapter.ReadKeys()\n}\n\n\/\/ YAMLFile stores config in a YAML file on disk,\n\/\/ this is the default.  It implements the storage\n\/\/ adapter interface.\ntype YAMLFile struct {\n\tpath     string\n\tcontent  []byte\n\tmodified bool\n}\n\n\/\/ GetYAMLConfig gets, or creates, a yaml configuration\n\/\/ file from disk\nfunc GetYAMLConfig() *YAMLFile {\n\tfile := viper.ConfigFileUsed()\n\tconfigFile := NewYAMLFile()\n\tif file != \"\" {\n\t\tconfigFile = ReadYAMLFile(file)\n\t}\n\treturn configFile\n}\n\n\/\/ NewYAMLFile creates a new and empty YAML file\nfunc NewYAMLFile() *YAMLFile {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn &YAMLFile{path: fmt.Sprintf(\"%s\/.ecs-commander.yaml\", usr.HomeDir)}\n}\n\n\/\/ ReadYAMLFile Sets the file to be used for storing config\nfunc ReadYAMLFile(path string) *YAMLFile {\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Tried to read config file from %s, but failed. %v\", content, err))\n\t}\n\tyamlFile := &YAMLFile{path: path, content: content}\n\treturn yamlFile\n}\n\n\/\/ ReadKeys implements a key reader for yaml files\nfunc (yamlFile *YAMLFile) ReadKeys() (Keys, error) {\n\tconfig := &Config{}\n\terr := yaml.Unmarshal(yamlFile.content, &config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif config.Keys == nil {\n\t\tconfig.Keys = make(Keys)\n\t}\n\treturn config.Keys, nil\n}\n\n\/\/ SaveKeys implements a key writer for yaml files\nfunc (yamlFile *YAMLFile) SaveKeys(keys Keys) error {\n\tconfig := &Config{}\n\terr := yaml.Unmarshal(yamlFile.content, &config)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.Keys = keys\n\tbytes, err := yaml.Marshal(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(yamlFile.path, bytes, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ IsModified implements a modified\nfunc (yamlFile *YAMLFile) IsModified() bool {\n\treturn true\n}\n\n\/\/ GetClusterKey returns the registered key path for a cluster\nfunc GetClusterKey(cluster string) string {\n\tout := fmt.Sprintf(\"~\/%s.pem\", cluster)\n\tallKeys, err := GetYAMLConfig().ReadKeys()\n\tif err != nil {\n\t\treturn out\n\t}\n\tif key, ok := allKeys[ClusterName(cluster)]; ok {\n\t\tout = string(key)\n\t}\n\treturn out\n}\n<|endoftext|>"}
{"text":"<commit_before>package help\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\t\"text\/template\"\n\t\"time\"\n\t\"unicode\/utf8\"\n\n\t\"github.com\/cloudfoundry\/cli\/cf\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/command_registry\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/configuration\/plugin_config\"\n\t. \"github.com\/cloudfoundry\/cli\/cf\/i18n\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/terminal\"\n)\n\ntype appPresenter struct {\n\tName     string\n\tUsage    string\n\tVersion  string\n\tCompiled time.Time\n\tCommands []groupedCommands\n}\n\ntype groupedCommands struct {\n\tName             string\n\tCommandSubGroups [][]cmdPresenter\n}\n\ntype cmdPresenter struct {\n\tName        string\n\tDescription string\n}\n\nfunc ShowHelp(helpTemplate string) {\n\ttranslatedTemplatedHelp := T(strings.Replace(helpTemplate, \"{{\", \"[[\", -1))\n\ttranslatedTemplatedHelp = strings.Replace(translatedTemplatedHelp, \"[[\", \"{{\", -1)\n\n\tshowAppHelp(translatedTemplatedHelp)\n}\n\nfunc showAppHelp(helpTemplate string) {\n\tpresenter := newAppPresenter()\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\\t', 0)\n\tt := template.Must(template.New(\"help\").Parse(helpTemplate))\n\terr := t.Execute(w, presenter)\n\tif err != nil {\n\t\tfmt.Println(\"error\", err)\n\t}\n\tw.Flush()\n}\n\nfunc newAppPresenter() (presenter appPresenter) {\n\tmaxNameLen := command_registry.Commands.MaxCommandNameLength()\n\n\tpresentNonCodegangstaCommand := func(commandName string) (presenter cmdPresenter) {\n\t\tcmd := command_registry.Commands.FindCommand(commandName)\n\t\tpresenter.Name = cmd.MetaData().Name\n\t\tpadding := strings.Repeat(\" \", maxNameLen-utf8.RuneCountInString(presenter.Name))\n\t\tpresenter.Name = presenter.Name + padding\n\t\tpresenter.Description = cmd.MetaData().Description\n\t\treturn\n\t}\n\n\tpresentPluginCommands := func() []cmdPresenter {\n\t\tpluginConfig := plugin_config.NewPluginConfig(func(err error) {\n\t\t\t\/\/fail silently when running help?\n\t\t})\n\n\t\tplugins := pluginConfig.Plugins()\n\t\tvar presenters []cmdPresenter\n\t\tvar pluginPresenter cmdPresenter\n\n\t\tfor _, pluginMetadata := range plugins {\n\t\t\tfor _, cmd := range pluginMetadata.Commands {\n\n\t\t\t\tif cmd.Alias == \"\" {\n\t\t\t\t\tpluginPresenter.Name = cmd.Name\n\t\t\t\t} else {\n\t\t\t\t\tpluginPresenter.Name = cmd.Name + \", \" + cmd.Alias\n\t\t\t\t}\n\n\t\t\t\tpadding := strings.Repeat(\" \", maxNameLen-utf8.RuneCountInString(pluginPresenter.Name))\n\t\t\t\tpluginPresenter.Name = pluginPresenter.Name + padding\n\t\t\t\tpluginPresenter.Description = cmd.HelpText\n\t\t\t\tpresenters = append(presenters, pluginPresenter)\n\t\t\t}\n\t\t}\n\n\t\treturn presenters\n\t}\n\n\tpresenter.Name = os.Args[0]\n\tpresenter.Usage = T(\"A command line tool to interact with Cloud Foundry\")\n\tpresenter.Version = cf.Version + \"-\" + cf.BuiltOnDate\n\tcompiledAtTime, err := time.Parse(\"2006-01-02T03:04:05+00:00\", cf.BuiltOnDate)\n\tif err == nil {\n\t\tpresenter.Compiled = compiledAtTime\n\t} else {\n\t\tpresenter.Compiled = time.Now()\n\t}\n\tpresenter.Commands = []groupedCommands{\n\t\t{\n\t\t\tName: T(\"GETTING STARTED\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"help\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"login\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"logout\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"passwd\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"target\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"api\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"auth\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"APPS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"apps\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"app\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"push\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"scale\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"rename\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"start\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"stop\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"restart\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"restage\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"restart-app-instance\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"events\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"files\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"logs\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"env\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-env\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unset-env\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"stacks\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"stack\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"copy-source\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-app-manifest\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"get-health-check\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-health-check\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"enable-ssh\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"disable-ssh\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"ssh-enabled\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"SERVICES\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"marketplace\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"services\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"service\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-service\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-service\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-service\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"rename-service\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-service-key\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"service-keys\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"service-key\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-service-key\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"bind-service\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unbind-service\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-user-provided-service\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-user-provided-service\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ORGS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"orgs\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"org\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-org\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-org\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"rename-org\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"SPACES\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"spaces\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"space\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-space\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-space\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"rename-space\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"allow-space-ssh\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"disallow-space-ssh\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"space-ssh-allowed\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"DOMAINS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"domains\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-domain\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-domain\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-shared-domain\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-shared-domain\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ROUTES\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"routes\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-route\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"check-route\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"map-route\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unmap-route\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-route\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-orphaned-routes\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"BUILDPACKS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"buildpacks\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-buildpack\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-buildpack\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"rename-buildpack\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-buildpack\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"USER ADMIN\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-user\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-user\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"org-users\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-org-role\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unset-org-role\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"space-users\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-space-role\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unset-space-role\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ORG ADMIN\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"quotas\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-quota\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-quota\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"share-private-domain\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unshare-private-domain\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"SPACE ADMIN\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"space-quotas\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"space-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-space-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-space-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-space-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-space-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unset-space-quota\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"SERVICE ADMIN\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"service-auth-tokens\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-service-auth-token\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-service-auth-token\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-service-auth-token\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"service-brokers\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-service-broker\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-service-broker\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-service-broker\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"rename-service-broker\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"migrate-service-instances\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"purge-service-offering\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"service-access\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"enable-service-access\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"disable-service-access\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"SECURITY GROUP\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"security-groups\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"bind-security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unbind-security-group\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"bind-staging-security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"staging-security-groups\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unbind-staging-security-group\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"bind-running-security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"running-security-groups\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unbind-running-security-group\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ENVIRONMENT VARIABLE GROUPS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"running-environment-variable-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"staging-environment-variable-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-staging-environment-variable-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-running-environment-variable-group\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: T(\"FEATURE FLAGS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"feature-flags\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"feature-flag\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"enable-feature-flag\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"disable-feature-flag\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ADVANCED\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"curl\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"config\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"oauth-token\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ADD\/REMOVE PLUGIN REPOSITORY\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"add-plugin-repo\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"remove-plugin-repo\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"list-plugin-repos\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"repo-plugins\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ADD\/REMOVE PLUGIN\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"plugins\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"install-plugin\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"uninstall-plugin\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"INSTALLED PLUGIN COMMANDS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\tpresentPluginCommands(),\n\t\t\t},\n\t\t},\n\t}\n\n\treturn\n}\n\nfunc (p appPresenter) Title(name string) string {\n\treturn terminal.HeaderColor(name)\n}\n\nfunc (c groupedCommands) SubTitle(name string) string {\n\treturn terminal.HeaderColor(name + \":\")\n}\n<commit_msg>add command ssh to cf help<commit_after>package help\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\t\"text\/template\"\n\t\"time\"\n\t\"unicode\/utf8\"\n\n\t\"github.com\/cloudfoundry\/cli\/cf\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/command_registry\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/configuration\/plugin_config\"\n\t. \"github.com\/cloudfoundry\/cli\/cf\/i18n\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/terminal\"\n)\n\ntype appPresenter struct {\n\tName     string\n\tUsage    string\n\tVersion  string\n\tCompiled time.Time\n\tCommands []groupedCommands\n}\n\ntype groupedCommands struct {\n\tName             string\n\tCommandSubGroups [][]cmdPresenter\n}\n\ntype cmdPresenter struct {\n\tName        string\n\tDescription string\n}\n\nfunc ShowHelp(helpTemplate string) {\n\ttranslatedTemplatedHelp := T(strings.Replace(helpTemplate, \"{{\", \"[[\", -1))\n\ttranslatedTemplatedHelp = strings.Replace(translatedTemplatedHelp, \"[[\", \"{{\", -1)\n\n\tshowAppHelp(translatedTemplatedHelp)\n}\n\nfunc showAppHelp(helpTemplate string) {\n\tpresenter := newAppPresenter()\n\n\tw := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\\t', 0)\n\tt := template.Must(template.New(\"help\").Parse(helpTemplate))\n\terr := t.Execute(w, presenter)\n\tif err != nil {\n\t\tfmt.Println(\"error\", err)\n\t}\n\tw.Flush()\n}\n\nfunc newAppPresenter() (presenter appPresenter) {\n\tmaxNameLen := command_registry.Commands.MaxCommandNameLength()\n\n\tpresentNonCodegangstaCommand := func(commandName string) (presenter cmdPresenter) {\n\t\tcmd := command_registry.Commands.FindCommand(commandName)\n\t\tpresenter.Name = cmd.MetaData().Name\n\t\tpadding := strings.Repeat(\" \", maxNameLen-utf8.RuneCountInString(presenter.Name))\n\t\tpresenter.Name = presenter.Name + padding\n\t\tpresenter.Description = cmd.MetaData().Description\n\t\treturn\n\t}\n\n\tpresentPluginCommands := func() []cmdPresenter {\n\t\tpluginConfig := plugin_config.NewPluginConfig(func(err error) {\n\t\t\t\/\/fail silently when running help?\n\t\t})\n\n\t\tplugins := pluginConfig.Plugins()\n\t\tvar presenters []cmdPresenter\n\t\tvar pluginPresenter cmdPresenter\n\n\t\tfor _, pluginMetadata := range plugins {\n\t\t\tfor _, cmd := range pluginMetadata.Commands {\n\n\t\t\t\tif cmd.Alias == \"\" {\n\t\t\t\t\tpluginPresenter.Name = cmd.Name\n\t\t\t\t} else {\n\t\t\t\t\tpluginPresenter.Name = cmd.Name + \", \" + cmd.Alias\n\t\t\t\t}\n\n\t\t\t\tpadding := strings.Repeat(\" \", maxNameLen-utf8.RuneCountInString(pluginPresenter.Name))\n\t\t\t\tpluginPresenter.Name = pluginPresenter.Name + padding\n\t\t\t\tpluginPresenter.Description = cmd.HelpText\n\t\t\t\tpresenters = append(presenters, pluginPresenter)\n\t\t\t}\n\t\t}\n\n\t\treturn presenters\n\t}\n\n\tpresenter.Name = os.Args[0]\n\tpresenter.Usage = T(\"A command line tool to interact with Cloud Foundry\")\n\tpresenter.Version = cf.Version + \"-\" + cf.BuiltOnDate\n\tcompiledAtTime, err := time.Parse(\"2006-01-02T03:04:05+00:00\", cf.BuiltOnDate)\n\tif err == nil {\n\t\tpresenter.Compiled = compiledAtTime\n\t} else {\n\t\tpresenter.Compiled = time.Now()\n\t}\n\tpresenter.Commands = []groupedCommands{\n\t\t{\n\t\t\tName: T(\"GETTING STARTED\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"help\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"login\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"logout\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"passwd\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"target\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"api\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"auth\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"APPS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"apps\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"app\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"push\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"scale\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"rename\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"start\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"stop\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"restart\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"restage\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"restart-app-instance\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"events\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"files\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"logs\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"env\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-env\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unset-env\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"stacks\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"stack\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"copy-source\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-app-manifest\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"get-health-check\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-health-check\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"enable-ssh\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"disable-ssh\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"ssh-enabled\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"ssh\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"SERVICES\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"marketplace\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"services\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"service\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-service\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-service\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-service\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"rename-service\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-service-key\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"service-keys\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"service-key\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-service-key\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"bind-service\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unbind-service\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-user-provided-service\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-user-provided-service\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ORGS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"orgs\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"org\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-org\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-org\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"rename-org\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"SPACES\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"spaces\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"space\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-space\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-space\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"rename-space\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"allow-space-ssh\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"disallow-space-ssh\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"space-ssh-allowed\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"DOMAINS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"domains\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-domain\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-domain\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-shared-domain\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-shared-domain\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ROUTES\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"routes\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-route\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"check-route\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"map-route\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unmap-route\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-route\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-orphaned-routes\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"BUILDPACKS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"buildpacks\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-buildpack\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-buildpack\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"rename-buildpack\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-buildpack\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"USER ADMIN\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-user\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-user\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"org-users\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-org-role\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unset-org-role\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"space-users\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-space-role\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unset-space-role\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ORG ADMIN\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"quotas\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-quota\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-quota\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"share-private-domain\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unshare-private-domain\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"SPACE ADMIN\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"space-quotas\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"space-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-space-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-space-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-space-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-space-quota\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unset-space-quota\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"SERVICE ADMIN\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"service-auth-tokens\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-service-auth-token\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-service-auth-token\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-service-auth-token\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"service-brokers\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-service-broker\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-service-broker\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-service-broker\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"rename-service-broker\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"migrate-service-instances\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"purge-service-offering\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"service-access\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"enable-service-access\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"disable-service-access\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"SECURITY GROUP\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"security-groups\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"create-security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"update-security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"delete-security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"bind-security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unbind-security-group\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"bind-staging-security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"staging-security-groups\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unbind-staging-security-group\"),\n\t\t\t\t}, {\n\t\t\t\t\tpresentNonCodegangstaCommand(\"bind-running-security-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"running-security-groups\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"unbind-running-security-group\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ENVIRONMENT VARIABLE GROUPS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"running-environment-variable-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"staging-environment-variable-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-staging-environment-variable-group\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"set-running-environment-variable-group\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: T(\"FEATURE FLAGS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"feature-flags\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"feature-flag\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"enable-feature-flag\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"disable-feature-flag\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ADVANCED\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"curl\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"config\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"oauth-token\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ADD\/REMOVE PLUGIN REPOSITORY\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"add-plugin-repo\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"remove-plugin-repo\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"list-plugin-repos\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"repo-plugins\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"ADD\/REMOVE PLUGIN\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\t{\n\t\t\t\t\tpresentNonCodegangstaCommand(\"plugins\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"install-plugin\"),\n\t\t\t\t\tpresentNonCodegangstaCommand(\"uninstall-plugin\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}, {\n\t\t\tName: T(\"INSTALLED PLUGIN COMMANDS\"),\n\t\t\tCommandSubGroups: [][]cmdPresenter{\n\t\t\t\tpresentPluginCommands(),\n\t\t\t},\n\t\t},\n\t}\n\n\treturn\n}\n\nfunc (p appPresenter) Title(name string) string {\n\treturn terminal.HeaderColor(name)\n}\n\nfunc (c groupedCommands) SubTitle(name string) string {\n\treturn terminal.HeaderColor(name + \":\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package board\n\nimport (\n\t\"math\/rand\"\n\t\"time\"\n)\n\n\/\/ Board size\nconst (\n\tX = 4\n\tY = 4\n)\n\n\/\/ Direction\ntype Direction int32\n\n\/\/ Direction\nconst (\n\tLEFT  = iota\n\tUP    = iota\n\tRIGHT = iota\n\tDOWN  = iota\n)\n\nvar (\n\tDIRECTIONS = map[int]int{\n\t\tLEFT:  -1,\n\t\tUP:    -1,\n\t\tRIGHT: 1,\n\t\tDOWN:  1,\n\t}\n)\n\ntype Board struct {\n\tCells [][]int\n\n\tgoal   int\n\tpoints int\n}\n\nfunc New() Board {\n\tboard := Board{\n\t\t\/*\n\t\t   Cells: [Y][X]int {\n\t\t       {0, 3, 0, 0},\n\t\t       {1, 0, 2, 0},\n\t\t       {2, 1, 1, 0},\n\t\t       {0, 6, 5, 0},\n\t\t   },\n\t\t*\/\n\t\tCells:  make2dArray(X, Y),\n\t\tgoal:   2048,\n\t\tpoints: 0,\n\t}\n\n\t\/\/ Seed rng\n\trand.Seed(time.Now().Unix())\n\n\t\/\/ Add two random tiles\n\tboard.AddTile()\n\tboard.AddTile()\n\n\treturn board\n}\n\nfunc make2dArray(x, y int) [][]int {\n\trows := make([][]int, y)\n\n\tfor i, _ := range rows {\n\t\trows[i] = make([]int, x)\n\t}\n\n\treturn rows\n}\n\nfunc (b *Board) emptyRow(n int) []int {\n\trow := make([]int, n)\n\treturn row[0:n]\n}\n\nfunc (b *Board) moveLine(row []int, direction int) []int {\n\tvar empty []int\n\tvar nonEmpty []int\n\tresult := make([]int, len(row))\n\n\tfor i := 0; i < len(row); i++ {\n\t\tif row[i] == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tnonEmpty = append(nonEmpty, row[i])\n\t}\n\n\tempty = b.emptyRow(X - len(nonEmpty))\n\n\t\/\/ Copy merges to result array\n\tif direction == -1 {\n\t\tcopy(result[:], append(nonEmpty, empty...)[0:len(row)])\n\t} else {\n\t\tcopy(result[:], append(empty, nonEmpty...)[0:len(row)])\n\t}\n\n\treturn result\n}\n\n\/\/ Is a given line mergeable\nfunc canMergeLine(row []int) bool {\n\tfor i := 0; i < len(row); i++ {\n\t\t\/\/ Previous\n\t\tif i > 0 && row[i] == row[i-1] {\n\t\t\treturn true\n\t\t}\n\n\t\t\/\/ Next\n\t\tif i+1 < len(row) && row[i] == row[i+1] {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (b *Board) mergeLine(row []int, direction int) []int {\n\tnewRow := make([]int, len(row))\n\tvar start, end, pos, nextpos int\n\n\tif direction == -1 {\n\t\tend = 0\n\t\tstart = len(row) - 1\n\t} else {\n\t\tstart = 0\n\t\tend = len(row) - 1\n\t}\n\n\tpos = start\n\tfor i := 0; i < len(row); i++ {\n\t\tnextpos = pos + direction\n\n\t\t\/\/ Don't merge empty cells\n\t\t\/\/ or already merged cells\n\t\tif row[pos] == 0 || newRow[pos] != 0 {\n\t\t\tpos = nextpos\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Next cell is identical\n\t\tif pos != end && row[pos] == row[nextpos] {\n\t\t\tvar value = row[pos] + 1\n\t\t\tnewRow[pos] = 0\n\t\t\tnewRow[nextpos] = value\n\t\t} else {\n\t\t\tnewRow[pos] = row[pos]\n\t\t}\n\n\t\t\/\/ Update position\n\t\tpos = nextpos\n\t}\n\n\treturn newRow\n}\n\nfunc (b *Board) setRow(y int, row []int) {\n\tfor x := 0; x < X; x++ {\n\t\tb.Cells[y][x] = row[x]\n\t}\n}\n\nfunc (b *Board) getRow(y int) []int {\n\treturn b.Cells[y]\n}\n\nfunc (b *Board) setCol(x int, row []int) {\n\tfor y := 0; y < Y; y++ {\n\t\tb.Cells[y][x] = row[y]\n\t}\n}\n\nfunc (b *Board) getCol(x int) []int {\n\ta := make([]int, Y)\n\n\tfor y := 0; y < Y; y++ {\n\t\ta[y] = b.Cells[y][x]\n\t}\n\n\treturn a\n}\n\nfunc (b *Board) moveRows(d int) {\n\tfor y := 0; y < Y; y++ {\n\t\t\/\/ Get new row by moving and merging previous row\n\t\tvar newRow = b.moveLine(\n\t\t\tb.mergeLine(\n\t\t\t\tb.moveLine(\n\t\t\t\t\tb.getRow(y),\n\t\t\t\t\td,\n\t\t\t\t),\n\t\t\t\td,\n\t\t\t),\n\t\t\td,\n\t\t)\n\n\t\t\/\/ Set new row\n\t\tb.setRow(y, newRow)\n\t}\n}\n\nfunc (b *Board) moveCols(d int) {\n\tfor x := 0; x < X; x++ {\n\t\t\/\/ Get new col by moving and merging previous col\n\t\tvar newCol = b.moveLine(\n\t\t\tb.mergeLine(\n\t\t\t\tb.moveLine(\n\t\t\t\t\tb.getCol(x),\n\t\t\t\t\td,\n\t\t\t\t),\n\t\t\t\td,\n\t\t\t),\n\t\t\td,\n\t\t)\n\n\t\t\/\/ Set new col\n\t\tb.setCol(x, newCol)\n\t}\n}\n\ntype cellLocation struct {\n\tx, y int\n}\n\nfunc (b *Board) emptyCells() []cellLocation {\n\tvar arr []cellLocation\n\n\tfor y := 0; y < Y; y++ {\n\t\tfor x := 0; x < X; x++ {\n\t\t\tif b.Cells[y][x] == 0 {\n\t\t\t\tvar cell = cellLocation{x, y}\n\t\t\t\tarr = append(arr, cell)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn arr\n}\n\nfunc (b *Board) IsFull() bool {\n\treturn len(b.emptyCells()) == 0\n}\n\nfunc (b *Board) AddTile() {\n\tcells := b.emptyCells()\n\tcell := cells[rand.Int()%len(cells)]\n\n\t\/\/ Set cell randomly to 1 or 2\n\t\/\/ b.Cells[cell.y][cell.x] = (rand.Int() % 2) + 1\n\tb.Cells[cell.y][cell.x] = 1\n}\n\nfunc (b *Board) Playable() bool {\n\tif !b.IsFull() {\n\t\treturn true\n\t}\n\n\tfor y := 0; y < Y; y++ {\n\t\tif canMergeLine(b.getRow(y)) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor x := 0; x < X; x++ {\n\t\tif canMergeLine(b.getCol(x)) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (b *Board) Values() []int {\n\tvar arr []int\n\n\tfor y := 0; y < Y; y++ {\n\t\tfor x := 0; x < X; x++ {\n\t\t\tif b.Cells[y][x] != 0 {\n\t\t\t\tarr = append(arr, b.Cells[y][x])\n\t\t\t}\n\t\t}\n\t}\n\treturn arr\n}\n\nfunc copyCells(src [][]int) [][]int {\n\tdst := make2dArray(X, Y)\n\tfor y := 0; y < Y; y++ {\n\t\tfor x := 0; x < X; x++ {\n\t\t\tdst[y][x] = src[y][x]\n\t\t}\n\t}\n\treturn dst\n}\n\nfunc cellsEqual(a, b [][]int) bool {\n\tfor y := 0; y < Y; y++ {\n\t\tfor x := 0; x < X; x++ {\n\t\t\tif a[y][x] != b[y][x] {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Move board in a given direction\nfunc (b *Board) Move(d Direction) {\n\t\/\/ Make a copy of cells pre-moving (so we can see if anything changed)\n\toldCells := copyCells(b.Cells)\n\n\tswitch d {\n\tcase UP:\n\t\tb.moveCols(DIRECTIONS[UP])\n\tcase DOWN:\n\t\tb.moveCols(DIRECTIONS[DOWN])\n\n\tcase LEFT:\n\t\tb.moveRows(DIRECTIONS[LEFT])\n\tcase RIGHT:\n\t\tb.moveRows(DIRECTIONS[RIGHT])\n\t}\n\n\t\/\/ Don't add new tile if nothing in the board has changed\n\tcellsChanged := !cellsEqual(oldCells, b.Cells)\n\n\t\/\/ Add new tile if not empty\n\tif !b.IsFull() && cellsChanged {\n\t\tb.AddTile()\n\t}\n}\n<commit_msg>board: decouple line methods from Board struct to simplify testing<commit_after>package board\n\nimport (\n\t\"math\/rand\"\n\t\"time\"\n)\n\n\/\/ Board size\nconst (\n\tX = 4\n\tY = 4\n)\n\n\/\/ Direction\ntype Direction int32\n\n\/\/ Direction\nconst (\n\tLEFT  = iota\n\tUP    = iota\n\tRIGHT = iota\n\tDOWN  = iota\n)\n\nvar (\n\tDIRECTIONS = map[int]int{\n\t\tLEFT:  -1,\n\t\tUP:    -1,\n\t\tRIGHT: 1,\n\t\tDOWN:  1,\n\t}\n)\n\ntype Board struct {\n\tCells [][]int\n\n\tgoal   int\n\tpoints int\n}\n\nfunc New() Board {\n\tboard := Board{\n\t\t\/*\n\t\t   Cells: [Y][X]int {\n\t\t       {0, 3, 0, 0},\n\t\t       {1, 0, 2, 0},\n\t\t       {2, 1, 1, 0},\n\t\t       {0, 6, 5, 0},\n\t\t   },\n\t\t*\/\n\t\tCells:  make2dArray(X, Y),\n\t\tgoal:   2048,\n\t\tpoints: 0,\n\t}\n\n\t\/\/ Seed rng\n\trand.Seed(time.Now().Unix())\n\n\t\/\/ Add two random tiles\n\tboard.AddTile()\n\tboard.AddTile()\n\n\treturn board\n}\n\nfunc make2dArray(x, y int) [][]int {\n\trows := make([][]int, y)\n\n\tfor i, _ := range rows {\n\t\trows[i] = make([]int, x)\n\t}\n\n\treturn rows\n}\n\nfunc emptyRow(n int) []int {\n\trow := make([]int, n)\n\treturn row[0:n]\n}\n\nfunc moveLine(row []int, direction int) []int {\n\tvar empty []int\n\tvar nonEmpty []int\n\tresult := make([]int, len(row))\n\n\tfor i := 0; i < len(row); i++ {\n\t\tif row[i] == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tnonEmpty = append(nonEmpty, row[i])\n\t}\n\n\tempty = emptyRow(X - len(nonEmpty))\n\n\t\/\/ Copy merges to result array\n\tif direction == -1 {\n\t\tcopy(result[:], append(nonEmpty, empty...)[0:len(row)])\n\t} else {\n\t\tcopy(result[:], append(empty, nonEmpty...)[0:len(row)])\n\t}\n\n\treturn result\n}\n\n\/\/ Is a given line mergeable\nfunc canMergeLine(row []int) bool {\n\tfor i := 0; i < len(row); i++ {\n\t\t\/\/ Previous\n\t\tif i > 0 && row[i] == row[i-1] {\n\t\t\treturn true\n\t\t}\n\n\t\t\/\/ Next\n\t\tif i+1 < len(row) && row[i] == row[i+1] {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc mergeLine(row []int, direction int) []int {\n\tnewRow := make([]int, len(row))\n\tvar start, end, pos, nextpos int\n\n\tif direction == -1 {\n\t\tend = 0\n\t\tstart = len(row) - 1\n\t} else {\n\t\tstart = 0\n\t\tend = len(row) - 1\n\t}\n\n\tpos = start\n\tfor i := 0; i < len(row); i++ {\n\t\tnextpos = pos + direction\n\n\t\t\/\/ Don't merge empty cells\n\t\t\/\/ or already merged cells\n\t\tif row[pos] == 0 || newRow[pos] != 0 {\n\t\t\tpos = nextpos\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Next cell is identical\n\t\tif pos != end && row[pos] == row[nextpos] {\n\t\t\tvar value = row[pos] + 1\n\t\t\tnewRow[pos] = 0\n\t\t\tnewRow[nextpos] = value\n\t\t} else {\n\t\t\tnewRow[pos] = row[pos]\n\t\t}\n\n\t\t\/\/ Update position\n\t\tpos = nextpos\n\t}\n\n\treturn newRow\n}\n\nfunc (b *Board) setRow(y int, row []int) {\n\tfor x := 0; x < X; x++ {\n\t\tb.Cells[y][x] = row[x]\n\t}\n}\n\nfunc (b *Board) getRow(y int) []int {\n\treturn b.Cells[y]\n}\n\nfunc (b *Board) setCol(x int, row []int) {\n\tfor y := 0; y < Y; y++ {\n\t\tb.Cells[y][x] = row[y]\n\t}\n}\n\nfunc (b *Board) getCol(x int) []int {\n\ta := make([]int, Y)\n\n\tfor y := 0; y < Y; y++ {\n\t\ta[y] = b.Cells[y][x]\n\t}\n\n\treturn a\n}\n\nfunc (b *Board) moveRows(d int) {\n\tfor y := 0; y < Y; y++ {\n\t\t\/\/ Get new row by moving and merging previous row\n\t\tvar newRow = moveLine(\n\t\t\tmergeLine(\n\t\t\t\tmoveLine(\n\t\t\t\t\tb.getRow(y),\n\t\t\t\t\td,\n\t\t\t\t),\n\t\t\t\td,\n\t\t\t),\n\t\t\td,\n\t\t)\n\n\t\t\/\/ Set new row\n\t\tb.setRow(y, newRow)\n\t}\n}\n\nfunc (b *Board) moveCols(d int) {\n\tfor x := 0; x < X; x++ {\n\t\t\/\/ Get new col by moving and merging previous col\n\t\tvar newCol = moveLine(\n\t\t\tmergeLine(\n\t\t\t\tmoveLine(\n\t\t\t\t\tb.getCol(x),\n\t\t\t\t\td,\n\t\t\t\t),\n\t\t\t\td,\n\t\t\t),\n\t\t\td,\n\t\t)\n\n\t\t\/\/ Set new col\n\t\tb.setCol(x, newCol)\n\t}\n}\n\ntype cellLocation struct {\n\tx, y int\n}\n\nfunc (b *Board) emptyCells() []cellLocation {\n\tvar arr []cellLocation\n\n\tfor y := 0; y < Y; y++ {\n\t\tfor x := 0; x < X; x++ {\n\t\t\tif b.Cells[y][x] == 0 {\n\t\t\t\tvar cell = cellLocation{x, y}\n\t\t\t\tarr = append(arr, cell)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn arr\n}\n\nfunc (b *Board) IsFull() bool {\n\treturn len(b.emptyCells()) == 0\n}\n\nfunc (b *Board) AddTile() {\n\tcells := b.emptyCells()\n\tcell := cells[rand.Int()%len(cells)]\n\n\t\/\/ Set cell randomly to 1 or 2\n\t\/\/ b.Cells[cell.y][cell.x] = (rand.Int() % 2) + 1\n\tb.Cells[cell.y][cell.x] = 1\n}\n\nfunc (b *Board) Playable() bool {\n\tif !b.IsFull() {\n\t\treturn true\n\t}\n\n\tfor y := 0; y < Y; y++ {\n\t\tif canMergeLine(b.getRow(y)) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor x := 0; x < X; x++ {\n\t\tif canMergeLine(b.getCol(x)) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (b *Board) Values() []int {\n\tvar arr []int\n\n\tfor y := 0; y < Y; y++ {\n\t\tfor x := 0; x < X; x++ {\n\t\t\tif b.Cells[y][x] != 0 {\n\t\t\t\tarr = append(arr, b.Cells[y][x])\n\t\t\t}\n\t\t}\n\t}\n\treturn arr\n}\n\nfunc copyCells(src [][]int) [][]int {\n\tdst := make2dArray(X, Y)\n\tfor y := 0; y < Y; y++ {\n\t\tfor x := 0; x < X; x++ {\n\t\t\tdst[y][x] = src[y][x]\n\t\t}\n\t}\n\treturn dst\n}\n\nfunc cellsEqual(a, b [][]int) bool {\n\tfor y := 0; y < Y; y++ {\n\t\tfor x := 0; x < X; x++ {\n\t\t\tif a[y][x] != b[y][x] {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Move board in a given direction\nfunc (b *Board) Move(d Direction) {\n\t\/\/ Make a copy of cells pre-moving (so we can see if anything changed)\n\toldCells := copyCells(b.Cells)\n\n\tswitch d {\n\tcase UP:\n\t\tb.moveCols(DIRECTIONS[UP])\n\tcase DOWN:\n\t\tb.moveCols(DIRECTIONS[DOWN])\n\n\tcase LEFT:\n\t\tb.moveRows(DIRECTIONS[LEFT])\n\tcase RIGHT:\n\t\tb.moveRows(DIRECTIONS[RIGHT])\n\t}\n\n\t\/\/ Don't add new tile if nothing in the board has changed\n\tcellsChanged := !cellsEqual(oldCells, b.Cells)\n\n\t\/\/ Add new tile if not empty\n\tif !b.IsFull() && cellsChanged {\n\t\tb.AddTile()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\n\tmemory is a storage manager that just keeps the games and storage in\n\tmemory, which means that when the program exits the storage evaporates.\n\tUseful in cases where you don't want a persistent store (e.g. testing or\n\tfast iteration). Implements both boardgame.StorageManager and\n\tboardgame\/server.StorageManager.\n\n*\/\npackage memory\n\nimport (\n\t\"errors\"\n\t\"github.com\/jkomoros\/boardgame\"\n\t\"github.com\/jkomoros\/boardgame\/server\/api\/extendedgame\"\n\t\"github.com\/jkomoros\/boardgame\/server\/api\/listing\"\n\t\"github.com\/jkomoros\/boardgame\/server\/api\/users\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype StorageManager struct {\n\tstates            map[string]map[int]boardgame.StateStorageRecord\n\tmoves             map[string]map[int]*boardgame.MoveStorageRecord\n\tgames             map[string]*boardgame.GameStorageRecord\n\textendedGames     map[string]*extendedgame.StorageRecord\n\tusersById         map[string]*users.StorageRecord\n\tusersByCookie     map[string]*users.StorageRecord\n\tusersForGames     map[string][]string\n\tagentStates       map[string][]byte\n\tstatesLock        sync.RWMutex\n\tmovesLock         sync.RWMutex\n\tgamesLock         sync.RWMutex\n\textendedGamesLock sync.RWMutex\n\tusersLock         sync.RWMutex\n\tusersForGamesLock sync.RWMutex\n\tagentStatesLock   sync.RWMutex\n}\n\nfunc NewStorageManager() *StorageManager {\n\t\/\/InMemoryStorageManager is an extremely simple StorageManager that just keeps\n\t\/\/track of the objects in memory.\n\treturn &StorageManager{\n\t\tstates:        make(map[string]map[int]boardgame.StateStorageRecord),\n\t\tmoves:         make(map[string]map[int]*boardgame.MoveStorageRecord),\n\t\tgames:         make(map[string]*boardgame.GameStorageRecord),\n\t\textendedGames: make(map[string]*extendedgame.StorageRecord),\n\t\tusersById:     make(map[string]*users.StorageRecord),\n\t\tusersByCookie: make(map[string]*users.StorageRecord),\n\t\tusersForGames: make(map[string][]string),\n\t\tagentStates:   make(map[string][]byte),\n\t}\n}\n\nfunc (s *StorageManager) Name() string {\n\treturn \"memory\"\n}\n\nfunc (s *StorageManager) State(gameId string, version int) (boardgame.StateStorageRecord, error) {\n\tif gameId == \"\" {\n\t\treturn nil, errors.New(\"No game provided\")\n\t}\n\n\tif version < 0 {\n\t\treturn nil, errors.New(\"Invalid version\")\n\t}\n\n\ts.statesLock.RLock()\n\n\tversionMap, ok := s.states[gameId]\n\n\ts.statesLock.RUnlock()\n\n\tif !ok {\n\t\treturn nil, errors.New(\"No such game\")\n\t}\n\ts.statesLock.RLock()\n\trecord, ok := versionMap[version]\n\ts.statesLock.RUnlock()\n\n\tif !ok {\n\t\treturn nil, errors.New(\"No such version for that game\")\n\t}\n\n\treturn record, nil\n\n}\n\nfunc (s *StorageManager) Moves(gameId string, fromVersion, toVersion int) ([]*boardgame.MoveStorageRecord, error) {\n\n\t\/\/There's no efficiency boost for fetching multiple moves at once so just wrap around Move()\n\n\tif fromVersion == toVersion {\n\t\tfromVersion = fromVersion - 1\n\t}\n\n\tresult := make([]*boardgame.MoveStorageRecord, toVersion-fromVersion)\n\n\tindex := 0\n\tfor i := fromVersion + 1; i <= toVersion; i++ {\n\t\tmove, err := s.Move(gameId, i)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[index] = move\n\t\tindex++\n\t}\n\treturn result, nil\n}\n\nfunc (s *StorageManager) Move(gameId string, version int) (*boardgame.MoveStorageRecord, error) {\n\tif gameId == \"\" {\n\t\treturn nil, errors.New(\"No game provided\")\n\t}\n\n\tif version < 0 {\n\t\treturn nil, errors.New(\"Invalid version\")\n\t}\n\n\ts.movesLock.RLock()\n\n\tversionMap, ok := s.moves[gameId]\n\n\ts.movesLock.RUnlock()\n\n\tif !ok {\n\t\treturn nil, errors.New(\"No such game\")\n\t}\n\ts.movesLock.RLock()\n\trecord, ok := versionMap[version]\n\ts.movesLock.RUnlock()\n\n\tif !ok {\n\t\treturn nil, errors.New(\"No such version for that game\")\n\t}\n\n\treturn record, nil\n\n}\n\nfunc (s *StorageManager) Game(id string) (*boardgame.GameStorageRecord, error) {\n\n\ts.gamesLock.RLock()\n\trecord := s.games[id]\n\ts.gamesLock.RUnlock()\n\n\tif record == nil {\n\t\treturn nil, errors.New(\"No such game\")\n\t}\n\n\treturn record, nil\n}\n\nfunc (s *StorageManager) SaveGameAndCurrentState(game *boardgame.GameStorageRecord, state boardgame.StateStorageRecord, move *boardgame.MoveStorageRecord) error {\n\tif game == nil {\n\t\treturn errors.New(\"No game provided\")\n\t}\n\n\ts.statesLock.RLock()\n\t_, ok := s.states[game.Id]\n\ts.statesLock.RUnlock()\n\tif !ok {\n\t\ts.statesLock.Lock()\n\t\ts.states[game.Id] = make(map[int]boardgame.StateStorageRecord)\n\t\ts.statesLock.Unlock()\n\t}\n\n\ts.movesLock.RLock()\n\t_, ok = s.moves[game.Id]\n\ts.movesLock.RUnlock()\n\tif !ok {\n\t\ts.movesLock.Lock()\n\t\ts.moves[game.Id] = make(map[int]*boardgame.MoveStorageRecord)\n\t\ts.movesLock.Unlock()\n\t}\n\n\tversion := game.Version\n\n\ts.statesLock.RLock()\n\tversionMap := s.states[game.Id]\n\t_, ok = versionMap[version]\n\ts.statesLock.RUnlock()\n\n\tif ok {\n\t\t\/\/Wait, there was already a version stored there?\n\t\treturn errors.New(\"There was already a version for that game stored\")\n\t}\n\n\ts.movesLock.RLock()\n\tmoveMap := s.moves[game.Id]\n\t_, ok = moveMap[version]\n\ts.movesLock.RUnlock()\n\n\tif ok {\n\t\t\/\/Wait, there was already a version stored there?\n\t\treturn errors.New(\"There was already a version for that game stored\")\n\t}\n\n\ts.extendedGamesLock.RLock()\n\teGame, ok := s.extendedGames[game.Id]\n\ts.extendedGamesLock.RUnlock()\n\tif !ok {\n\t\ts.extendedGamesLock.Lock()\n\t\ts.extendedGames[game.Id] = extendedgame.DefaultStorageRecord()\n\t\ts.extendedGamesLock.Unlock()\n\t} else {\n\t\teGame.LastActivity = time.Now().UnixNano()\n\t}\n\n\ts.statesLock.Lock()\n\tversionMap[version] = state\n\ts.statesLock.Unlock()\n\n\ts.movesLock.Lock()\n\tmoveMap[version] = move\n\ts.movesLock.Unlock()\n\n\ts.gamesLock.Lock()\n\ts.games[game.Id] = game\n\ts.gamesLock.Unlock()\n\n\treturn nil\n}\n\nfunc keyForAgent(gameId string, player boardgame.PlayerIndex) string {\n\treturn gameId + \"-\" + player.String()\n}\n\nfunc (s *StorageManager) AgentState(gameId string, player boardgame.PlayerIndex) ([]byte, error) {\n\n\tkey := keyForAgent(gameId, player)\n\n\ts.agentStatesLock.RLock()\n\tresult := s.agentStates[key]\n\ts.agentStatesLock.RUnlock()\n\n\treturn result, nil\n}\n\nfunc (s *StorageManager) SaveAgentState(gameId string, player boardgame.PlayerIndex, state []byte) error {\n\tkey := keyForAgent(gameId, player)\n\n\ts.agentStatesLock.Lock()\n\ts.agentStates[key] = state\n\ts.agentStatesLock.Unlock()\n\n\treturn nil\n}\n\n\/\/ListGames will return game objects for up to max number of games\nfunc (s *StorageManager) ListGames(max int, list listing.Type, userId string, gameType string) []*extendedgame.CombinedStorageRecord {\n\n\tif (list == listing.ParticipatingActive || list == listing.ParticipatingActive) && userId == \"\" {\n\t\t\/\/If we're filtering to only participating games and there's no userId, then there can't be any games,\n\t\t\/\/because the non-user can't be participating in any games.\n\t\treturn nil\n\t}\n\n\tvar result []*extendedgame.CombinedStorageRecord\n\n\tfor _, game := range s.games {\n\n\t\tif gameType != \"\" {\n\t\t\tif game.Name != gameType {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\teGame := s.extendedGames[game.Id]\n\n\t\tusersForGame := s.UserIdsForGame(game.Id)\n\n\t\thasUser := false\n\t\tnumUsers := 0\n\n\t\tfor _, user := range usersForGame {\n\t\t\tif user != \"\" {\n\t\t\t\tnumUsers++\n\t\t\t}\n\t\t\tif userId != \"\" && user == userId {\n\t\t\t\thasUser = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tnumAgents := 0\n\n\t\tfor _, agent := range game.Agents {\n\t\t\tif agent != \"\" {\n\t\t\t\tnumAgents++\n\t\t\t}\n\t\t}\n\n\t\thasSlots := game.NumPlayers > (numUsers + numAgents)\n\n\t\tswitch list {\n\t\tcase listing.ParticipatingActive:\n\t\t\tif game.Finished || !hasUser {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase listing.ParticipatingFinished:\n\t\t\tif !game.Finished || !hasUser {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase listing.VisibleJoinableActive:\n\t\t\tif game.Finished || hasUser || !eGame.Visible || !eGame.Open || !hasSlots {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase listing.VisibleActive:\n\t\t\tif game.Finished || hasUser || !eGame.Visible || (eGame.Open && hasSlots) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tresult = append(result, &extendedgame.CombinedStorageRecord{\n\t\t\t*game,\n\t\t\t*eGame,\n\t\t})\n\n\t\tif len(result) >= max {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tsort.Slice(result, func(i, j int) bool {\n\t\treturn result[i].LastActivity > result[j].LastActivity\n\t})\n\n\treturn result\n\n}\n\nfunc (s *StorageManager) ExtendedGame(id string) (*extendedgame.StorageRecord, error) {\n\ts.extendedGamesLock.RLock()\n\teGame := s.extendedGames[id]\n\ts.extendedGamesLock.RUnlock()\n\tif eGame == nil {\n\t\treturn nil, errors.New(\"No such extended game\")\n\t}\n\n\treturn eGame, nil\n}\n\nfunc (s *StorageManager) CombinedGame(id string) (*extendedgame.CombinedStorageRecord, error) {\n\ts.extendedGamesLock.RLock()\n\teGame := s.extendedGames[id]\n\ts.extendedGamesLock.RUnlock()\n\tif eGame == nil {\n\t\treturn nil, errors.New(\"No such extended game\")\n\t}\n\n\tgame, err := s.Game(id)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &extendedgame.CombinedStorageRecord{\n\t\t*game,\n\t\t*eGame,\n\t}\n\n\treturn result, nil\n}\n\nfunc (s *StorageManager) UpdateExtendedGame(id string, eGame *extendedgame.StorageRecord) error {\n\ts.extendedGamesLock.Lock()\n\ts.extendedGames[id] = eGame\n\ts.extendedGamesLock.Unlock()\n\treturn nil\n}\n\nfunc (s *StorageManager) UserIdsForGame(gameId string) []string {\n\ts.usersForGamesLock.RLock()\n\tids := s.usersForGames[gameId]\n\ts.usersForGamesLock.RUnlock()\n\n\tif ids == nil {\n\t\tgame, _ := s.Game(gameId)\n\t\tif game == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn make([]string, game.NumPlayers)\n\t}\n\n\treturn ids\n}\n\nfunc (s *StorageManager) SetPlayerForGame(gameId string, playerIndex boardgame.PlayerIndex, userId string) error {\n\tids := s.UserIdsForGame(gameId)\n\n\tif int(playerIndex) < 0 || int(playerIndex) >= len(ids) {\n\t\treturn errors.New(\"PlayerIndex \" + playerIndex.String() + \" is not valid for this game.\")\n\t}\n\n\tif ids[playerIndex] != \"\" {\n\t\treturn errors.New(\"PlayerIndex \" + playerIndex.String() + \" is already taken.\")\n\t}\n\n\tuser := s.GetUserById(userId)\n\n\tif user == nil {\n\t\treturn errors.New(\"That uid does not describe an existing user\")\n\t}\n\n\tids[playerIndex] = userId\n\n\ts.usersForGamesLock.Lock()\n\ts.usersForGames[gameId] = ids\n\ts.usersForGamesLock.Unlock()\n\n\treturn nil\n}\n\n\/\/Store or update all fields\nfunc (s *StorageManager) UpdateUser(user *users.StorageRecord) error {\n\n\ts.usersLock.Lock()\n\ts.usersById[user.Id] = user\n\ts.usersLock.Unlock()\n\n\treturn nil\n\n}\n\nfunc (s *StorageManager) GetUserById(uid string) *users.StorageRecord {\n\ts.usersLock.RLock()\n\tuser := s.usersById[uid]\n\ts.usersLock.RUnlock()\n\n\treturn user\n}\n\nfunc (s *StorageManager) GetUserByCookie(cookie string) *users.StorageRecord {\n\ts.usersLock.RLock()\n\tuser := s.usersByCookie[cookie]\n\ts.usersLock.RUnlock()\n\n\treturn user\n}\n\n\/\/If user is nil, the cookie should be deleted if it exists. If the user\n\/\/does not yet exist, it should be added to the database.\nfunc (s *StorageManager) ConnectCookieToUser(cookie string, user *users.StorageRecord) error {\n\tif user == nil {\n\t\ts.usersLock.Lock()\n\t\tdelete(s.usersByCookie, cookie)\n\t\ts.usersLock.Unlock()\n\t\treturn nil\n\t}\n\n\totherUser := s.GetUserById(user.Id)\n\n\tif otherUser == nil {\n\t\ts.UpdateUser(user)\n\t}\n\n\ts.usersLock.Lock()\n\ts.usersByCookie[cookie] = user\n\ts.usersLock.Unlock()\n\n\treturn nil\n}\n\nfunc (s *StorageManager) Connect(config string) error {\n\treturn nil\n}\n\nfunc (s *StorageManager) Close() {\n\t\/\/Don't need to do anything\n}\n\nfunc (s *StorageManager) CleanUp() {\n\t\/\/Don't need to do\n}\n\nfunc (s *StorageManager) PlayerMoveApplied(game *boardgame.GameStorageRecord) error {\n\t\/\/Don't need to do anything\n\treturn nil\n}\n<commit_msg>Fix a bug in the memory storage layer where on the very first save of a game we saved a nil move record. Only found now because the machinery for #516 exercised it.<commit_after>\/*\n\n\tmemory is a storage manager that just keeps the games and storage in\n\tmemory, which means that when the program exits the storage evaporates.\n\tUseful in cases where you don't want a persistent store (e.g. testing or\n\tfast iteration). Implements both boardgame.StorageManager and\n\tboardgame\/server.StorageManager.\n\n*\/\npackage memory\n\nimport (\n\t\"errors\"\n\t\"github.com\/jkomoros\/boardgame\"\n\t\"github.com\/jkomoros\/boardgame\/server\/api\/extendedgame\"\n\t\"github.com\/jkomoros\/boardgame\/server\/api\/listing\"\n\t\"github.com\/jkomoros\/boardgame\/server\/api\/users\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype StorageManager struct {\n\tstates            map[string]map[int]boardgame.StateStorageRecord\n\tmoves             map[string]map[int]*boardgame.MoveStorageRecord\n\tgames             map[string]*boardgame.GameStorageRecord\n\textendedGames     map[string]*extendedgame.StorageRecord\n\tusersById         map[string]*users.StorageRecord\n\tusersByCookie     map[string]*users.StorageRecord\n\tusersForGames     map[string][]string\n\tagentStates       map[string][]byte\n\tstatesLock        sync.RWMutex\n\tmovesLock         sync.RWMutex\n\tgamesLock         sync.RWMutex\n\textendedGamesLock sync.RWMutex\n\tusersLock         sync.RWMutex\n\tusersForGamesLock sync.RWMutex\n\tagentStatesLock   sync.RWMutex\n}\n\nfunc NewStorageManager() *StorageManager {\n\t\/\/InMemoryStorageManager is an extremely simple StorageManager that just keeps\n\t\/\/track of the objects in memory.\n\treturn &StorageManager{\n\t\tstates:        make(map[string]map[int]boardgame.StateStorageRecord),\n\t\tmoves:         make(map[string]map[int]*boardgame.MoveStorageRecord),\n\t\tgames:         make(map[string]*boardgame.GameStorageRecord),\n\t\textendedGames: make(map[string]*extendedgame.StorageRecord),\n\t\tusersById:     make(map[string]*users.StorageRecord),\n\t\tusersByCookie: make(map[string]*users.StorageRecord),\n\t\tusersForGames: make(map[string][]string),\n\t\tagentStates:   make(map[string][]byte),\n\t}\n}\n\nfunc (s *StorageManager) Name() string {\n\treturn \"memory\"\n}\n\nfunc (s *StorageManager) State(gameId string, version int) (boardgame.StateStorageRecord, error) {\n\tif gameId == \"\" {\n\t\treturn nil, errors.New(\"No game provided\")\n\t}\n\n\tif version < 0 {\n\t\treturn nil, errors.New(\"Invalid version\")\n\t}\n\n\ts.statesLock.RLock()\n\n\tversionMap, ok := s.states[gameId]\n\n\ts.statesLock.RUnlock()\n\n\tif !ok {\n\t\treturn nil, errors.New(\"No such game\")\n\t}\n\ts.statesLock.RLock()\n\trecord, ok := versionMap[version]\n\ts.statesLock.RUnlock()\n\n\tif !ok {\n\t\treturn nil, errors.New(\"No such version for that game\")\n\t}\n\n\treturn record, nil\n\n}\n\nfunc (s *StorageManager) Moves(gameId string, fromVersion, toVersion int) ([]*boardgame.MoveStorageRecord, error) {\n\n\t\/\/There's no efficiency boost for fetching multiple moves at once so just wrap around Move()\n\n\tif fromVersion == toVersion {\n\t\tfromVersion = fromVersion - 1\n\t}\n\n\tresult := make([]*boardgame.MoveStorageRecord, toVersion-fromVersion)\n\n\tindex := 0\n\tfor i := fromVersion + 1; i <= toVersion; i++ {\n\t\tmove, err := s.Move(gameId, i)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresult[index] = move\n\t\tindex++\n\t}\n\treturn result, nil\n}\n\nfunc (s *StorageManager) Move(gameId string, version int) (*boardgame.MoveStorageRecord, error) {\n\tif gameId == \"\" {\n\t\treturn nil, errors.New(\"No game provided\")\n\t}\n\n\tif version < 0 {\n\t\treturn nil, errors.New(\"Invalid version\")\n\t}\n\n\ts.movesLock.RLock()\n\n\tversionMap, ok := s.moves[gameId]\n\n\ts.movesLock.RUnlock()\n\n\tif !ok {\n\t\treturn nil, errors.New(\"No such game\")\n\t}\n\ts.movesLock.RLock()\n\trecord, ok := versionMap[version]\n\ts.movesLock.RUnlock()\n\n\tif !ok {\n\t\treturn nil, errors.New(\"No such version for that game\")\n\t}\n\n\treturn record, nil\n\n}\n\nfunc (s *StorageManager) Game(id string) (*boardgame.GameStorageRecord, error) {\n\n\ts.gamesLock.RLock()\n\trecord := s.games[id]\n\ts.gamesLock.RUnlock()\n\n\tif record == nil {\n\t\treturn nil, errors.New(\"No such game\")\n\t}\n\n\treturn record, nil\n}\n\nfunc (s *StorageManager) SaveGameAndCurrentState(game *boardgame.GameStorageRecord, state boardgame.StateStorageRecord, move *boardgame.MoveStorageRecord) error {\n\tif game == nil {\n\t\treturn errors.New(\"No game provided\")\n\t}\n\n\ts.statesLock.RLock()\n\t_, ok := s.states[game.Id]\n\ts.statesLock.RUnlock()\n\tif !ok {\n\t\ts.statesLock.Lock()\n\t\ts.states[game.Id] = make(map[int]boardgame.StateStorageRecord)\n\t\ts.statesLock.Unlock()\n\t}\n\n\ts.movesLock.RLock()\n\t_, ok = s.moves[game.Id]\n\ts.movesLock.RUnlock()\n\tif !ok {\n\t\ts.movesLock.Lock()\n\t\ts.moves[game.Id] = make(map[int]*boardgame.MoveStorageRecord)\n\t\ts.movesLock.Unlock()\n\t}\n\n\tversion := game.Version\n\n\ts.statesLock.RLock()\n\tversionMap := s.states[game.Id]\n\t_, ok = versionMap[version]\n\ts.statesLock.RUnlock()\n\n\tif ok {\n\t\t\/\/Wait, there was already a version stored there?\n\t\treturn errors.New(\"There was already a version for that game stored\")\n\t}\n\n\ts.movesLock.RLock()\n\tmoveMap := s.moves[game.Id]\n\t_, ok = moveMap[version]\n\ts.movesLock.RUnlock()\n\n\tif ok {\n\t\t\/\/Wait, there was already a version stored there?\n\t\treturn errors.New(\"There was already a version for that game stored\")\n\t}\n\n\ts.extendedGamesLock.RLock()\n\teGame, ok := s.extendedGames[game.Id]\n\ts.extendedGamesLock.RUnlock()\n\tif !ok {\n\t\ts.extendedGamesLock.Lock()\n\t\ts.extendedGames[game.Id] = extendedgame.DefaultStorageRecord()\n\t\ts.extendedGamesLock.Unlock()\n\t} else {\n\t\teGame.LastActivity = time.Now().UnixNano()\n\t}\n\n\ts.statesLock.Lock()\n\tversionMap[version] = state\n\ts.statesLock.Unlock()\n\n\ts.movesLock.Lock()\n\tif move != nil {\n\t\tmoveMap[version] = move\n\t}\n\ts.movesLock.Unlock()\n\n\ts.gamesLock.Lock()\n\ts.games[game.Id] = game\n\ts.gamesLock.Unlock()\n\n\treturn nil\n}\n\nfunc keyForAgent(gameId string, player boardgame.PlayerIndex) string {\n\treturn gameId + \"-\" + player.String()\n}\n\nfunc (s *StorageManager) AgentState(gameId string, player boardgame.PlayerIndex) ([]byte, error) {\n\n\tkey := keyForAgent(gameId, player)\n\n\ts.agentStatesLock.RLock()\n\tresult := s.agentStates[key]\n\ts.agentStatesLock.RUnlock()\n\n\treturn result, nil\n}\n\nfunc (s *StorageManager) SaveAgentState(gameId string, player boardgame.PlayerIndex, state []byte) error {\n\tkey := keyForAgent(gameId, player)\n\n\ts.agentStatesLock.Lock()\n\ts.agentStates[key] = state\n\ts.agentStatesLock.Unlock()\n\n\treturn nil\n}\n\n\/\/ListGames will return game objects for up to max number of games\nfunc (s *StorageManager) ListGames(max int, list listing.Type, userId string, gameType string) []*extendedgame.CombinedStorageRecord {\n\n\tif (list == listing.ParticipatingActive || list == listing.ParticipatingActive) && userId == \"\" {\n\t\t\/\/If we're filtering to only participating games and there's no userId, then there can't be any games,\n\t\t\/\/because the non-user can't be participating in any games.\n\t\treturn nil\n\t}\n\n\tvar result []*extendedgame.CombinedStorageRecord\n\n\tfor _, game := range s.games {\n\n\t\tif gameType != \"\" {\n\t\t\tif game.Name != gameType {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\teGame := s.extendedGames[game.Id]\n\n\t\tusersForGame := s.UserIdsForGame(game.Id)\n\n\t\thasUser := false\n\t\tnumUsers := 0\n\n\t\tfor _, user := range usersForGame {\n\t\t\tif user != \"\" {\n\t\t\t\tnumUsers++\n\t\t\t}\n\t\t\tif userId != \"\" && user == userId {\n\t\t\t\thasUser = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tnumAgents := 0\n\n\t\tfor _, agent := range game.Agents {\n\t\t\tif agent != \"\" {\n\t\t\t\tnumAgents++\n\t\t\t}\n\t\t}\n\n\t\thasSlots := game.NumPlayers > (numUsers + numAgents)\n\n\t\tswitch list {\n\t\tcase listing.ParticipatingActive:\n\t\t\tif game.Finished || !hasUser {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase listing.ParticipatingFinished:\n\t\t\tif !game.Finished || !hasUser {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase listing.VisibleJoinableActive:\n\t\t\tif game.Finished || hasUser || !eGame.Visible || !eGame.Open || !hasSlots {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase listing.VisibleActive:\n\t\t\tif game.Finished || hasUser || !eGame.Visible || (eGame.Open && hasSlots) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tresult = append(result, &extendedgame.CombinedStorageRecord{\n\t\t\t*game,\n\t\t\t*eGame,\n\t\t})\n\n\t\tif len(result) >= max {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tsort.Slice(result, func(i, j int) bool {\n\t\treturn result[i].LastActivity > result[j].LastActivity\n\t})\n\n\treturn result\n\n}\n\nfunc (s *StorageManager) ExtendedGame(id string) (*extendedgame.StorageRecord, error) {\n\ts.extendedGamesLock.RLock()\n\teGame := s.extendedGames[id]\n\ts.extendedGamesLock.RUnlock()\n\tif eGame == nil {\n\t\treturn nil, errors.New(\"No such extended game\")\n\t}\n\n\treturn eGame, nil\n}\n\nfunc (s *StorageManager) CombinedGame(id string) (*extendedgame.CombinedStorageRecord, error) {\n\ts.extendedGamesLock.RLock()\n\teGame := s.extendedGames[id]\n\ts.extendedGamesLock.RUnlock()\n\tif eGame == nil {\n\t\treturn nil, errors.New(\"No such extended game\")\n\t}\n\n\tgame, err := s.Game(id)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := &extendedgame.CombinedStorageRecord{\n\t\t*game,\n\t\t*eGame,\n\t}\n\n\treturn result, nil\n}\n\nfunc (s *StorageManager) UpdateExtendedGame(id string, eGame *extendedgame.StorageRecord) error {\n\ts.extendedGamesLock.Lock()\n\ts.extendedGames[id] = eGame\n\ts.extendedGamesLock.Unlock()\n\treturn nil\n}\n\nfunc (s *StorageManager) UserIdsForGame(gameId string) []string {\n\ts.usersForGamesLock.RLock()\n\tids := s.usersForGames[gameId]\n\ts.usersForGamesLock.RUnlock()\n\n\tif ids == nil {\n\t\tgame, _ := s.Game(gameId)\n\t\tif game == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn make([]string, game.NumPlayers)\n\t}\n\n\treturn ids\n}\n\nfunc (s *StorageManager) SetPlayerForGame(gameId string, playerIndex boardgame.PlayerIndex, userId string) error {\n\tids := s.UserIdsForGame(gameId)\n\n\tif int(playerIndex) < 0 || int(playerIndex) >= len(ids) {\n\t\treturn errors.New(\"PlayerIndex \" + playerIndex.String() + \" is not valid for this game.\")\n\t}\n\n\tif ids[playerIndex] != \"\" {\n\t\treturn errors.New(\"PlayerIndex \" + playerIndex.String() + \" is already taken.\")\n\t}\n\n\tuser := s.GetUserById(userId)\n\n\tif user == nil {\n\t\treturn errors.New(\"That uid does not describe an existing user\")\n\t}\n\n\tids[playerIndex] = userId\n\n\ts.usersForGamesLock.Lock()\n\ts.usersForGames[gameId] = ids\n\ts.usersForGamesLock.Unlock()\n\n\treturn nil\n}\n\n\/\/Store or update all fields\nfunc (s *StorageManager) UpdateUser(user *users.StorageRecord) error {\n\n\ts.usersLock.Lock()\n\ts.usersById[user.Id] = user\n\ts.usersLock.Unlock()\n\n\treturn nil\n\n}\n\nfunc (s *StorageManager) GetUserById(uid string) *users.StorageRecord {\n\ts.usersLock.RLock()\n\tuser := s.usersById[uid]\n\ts.usersLock.RUnlock()\n\n\treturn user\n}\n\nfunc (s *StorageManager) GetUserByCookie(cookie string) *users.StorageRecord {\n\ts.usersLock.RLock()\n\tuser := s.usersByCookie[cookie]\n\ts.usersLock.RUnlock()\n\n\treturn user\n}\n\n\/\/If user is nil, the cookie should be deleted if it exists. If the user\n\/\/does not yet exist, it should be added to the database.\nfunc (s *StorageManager) ConnectCookieToUser(cookie string, user *users.StorageRecord) error {\n\tif user == nil {\n\t\ts.usersLock.Lock()\n\t\tdelete(s.usersByCookie, cookie)\n\t\ts.usersLock.Unlock()\n\t\treturn nil\n\t}\n\n\totherUser := s.GetUserById(user.Id)\n\n\tif otherUser == nil {\n\t\ts.UpdateUser(user)\n\t}\n\n\ts.usersLock.Lock()\n\ts.usersByCookie[cookie] = user\n\ts.usersLock.Unlock()\n\n\treturn nil\n}\n\nfunc (s *StorageManager) Connect(config string) error {\n\treturn nil\n}\n\nfunc (s *StorageManager) Close() {\n\t\/\/Don't need to do anything\n}\n\nfunc (s *StorageManager) CleanUp() {\n\t\/\/Don't need to do\n}\n\nfunc (s *StorageManager) PlayerMoveApplied(game *boardgame.GameStorageRecord) error {\n\t\/\/Don't need to do anything\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package ring_test\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"hash\/fnv\"\n\n\t\"github.com\/gholt\/ring\"\n)\n\n\/\/ This will be an in-depth implementation of using the ring package. We will\n\/\/ be building a distributed object storage system where object names will be\n\/\/ mapped to disks. There will be multiple disks per server, and multiple\n\/\/ servers per zone.\n\n\/\/ First, let's define our BuilderDisk, representing a single disk in the\n\/\/ cluster and is what the ring package will be mapping assignments to.\n\n\/\/ We want all the fields to be private because we don't want users of our new\n\/\/ package to accidentally alter anything. This complicates our code, but\n\/\/ simplifies things for users of our new storage package, and would be a\n\/\/ common use case.\n\ntype BuilderDisk struct {\n\t\/\/ We'll define our specific StorageBuilder later. We need a reference to\n\t\/\/ it in each node so we notify it of changes and to resolve things like\n\t\/\/ tier names.\n\tstorageBuilder *StorageBuilder\n\t\/\/ This is the actual ring.Node the ring.Builder will need to work with,\n\t\/\/ and contains whether the disk is Disabled or not, the Capacity, and the\n\t\/\/ list of indexes that define what tiers (server, zone) the disk is in.\n\tnode ring.Node\n\t\/\/ The ip:port where the disk can be reached.\n\taddr string\n\t\/\/ The name of the disk on the server.\n\tname string\n}\n\n\/\/ Now we map public methods to the fields.\n\nfunc (bd *BuilderDisk) Disabled() bool {\n\treturn bd.node.Disabled\n}\n\nfunc (bd *BuilderDisk) SetDisabled(v bool) {\n\tbd.node.Disabled = v\n}\n\nfunc (bd *BuilderDisk) Capacity() uint32 {\n\treturn bd.node.Capacity\n}\n\nfunc (bd *BuilderDisk) SetCapacity(v uint32) {\n\tbd.node.Capacity = v\n}\n\nfunc (bd *BuilderDisk) Tiers() []string {\n\ttiers := make([]string, len(bd.node.TierIndexes))\n\tfor i, ti := range bd.node.TierIndexes {\n\t\ttiers[i] = bd.storageBuilder.tierIndexToName[ti]\n\t}\n\treturn tiers\n}\n\nfunc (bd *BuilderDisk) SetTier(tier int, name string) {\n\tfor tier >= len(bd.node.TierIndexes) {\n\t\tbd.node.TierIndexes = append(bd.node.TierIndexes, 0)\n\t}\n\tif bd.storageBuilder.tierNameToIndex == nil {\n\t\tbd.storageBuilder.tierNameToIndex = map[string]uint32{}\n\t}\n\tif ti, ok := bd.storageBuilder.tierNameToIndex[name]; ok {\n\t\tbd.node.TierIndexes[tier] = ti\n\t} else {\n\t\tti = uint32(len(bd.storageBuilder.tierIndexToName))\n\t\tbd.storageBuilder.tierIndexToName = append(bd.storageBuilder.tierIndexToName, name)\n\t\tbd.storageBuilder.tierNameToIndex[name] = ti\n\t\tbd.node.TierIndexes[tier] = ti\n\t}\n}\n\nfunc (bd *BuilderDisk) Addr() string {\n\treturn bd.addr\n}\n\nfunc (bd *BuilderDisk) SetAddr(v string) {\n\tbd.addr = v\n}\n\nfunc (bd *BuilderDisk) Name() string {\n\treturn bd.name\n}\n\nfunc (bd *BuilderDisk) SetName(v string) {\n\tbd.name = v\n}\n\n\/\/ We want to be able to persist this information, so we make JSON translators.\n\/\/ Note that this does not set the storageBuilder field; that has to be done by\n\/\/ the StorageBuilder JSON translators.\n\ntype builderDiskJSON struct {\n\t\/\/ ring.Node is serializable on its own.\n\tNode *ring.Node\n\tAddr string\n\tName string\n}\n\nfunc (bd *BuilderDisk) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(&builderDiskJSON{\n\t\tNode: &bd.node,\n\t\tAddr: bd.addr,\n\t\tName: bd.name,\n\t})\n}\n\nfunc (bd *BuilderDisk) UnmarshalJSON(b []byte) error {\n\tvar j builderDiskJSON\n\tif err := json.Unmarshal(b, &j); err != nil {\n\t\treturn err\n\t}\n\tbd.node = *j.Node\n\tbd.addr = j.Addr\n\tbd.name = j.Name\n\treturn nil\n}\n\n\/\/ Now, let's define the StorageBuilder.\n\ntype StorageBuilder struct {\n\t\/\/ This is the actual builder that will do all the reblancing work.\n\tbuilder ring.Builder\n\t\/\/ These are all the disks in the cluster, we have to map them to the\n\t\/\/ ring.Builder's nodes.\n\tdisks []*BuilderDisk\n\t\/\/ These are to give the tiers human readable names, like Server34 and\n\t\/\/ Zone5 or whatever is desired.\n\ttierIndexToName []string\n\ttierNameToIndex map[string]uint32\n}\n\nfunc (sb *StorageBuilder) AddDisk() *BuilderDisk {\n\tbd := &BuilderDisk{storageBuilder: sb}\n\tsb.disks = append(sb.disks, bd)\n\tsb.builder.Nodes = append(sb.builder.Nodes, &bd.node)\n\treturn bd\n}\n\nfunc (sb *StorageBuilder) ChangeReplicaCount(count int) {\n\tsb.builder.ChangeReplicaCount(count)\n}\n\n\/\/ We'll skip removing disks, listing all disks, reading the replica count,\n\/\/ partition count, changing last moved, etc. but those kind of methods would\n\/\/ normally exist. The important point is that any modifications need to keep\n\/\/ the ring.Builder's nodes in sync.\n\n\/\/ We do want to give a useful ring to use, so let's provide that method. We'll\n\/\/ define the StorageRing later, but it will be an immutable copy of the state\n\/\/ of things at the time of StorageRing() call.\n\nfunc (sb *StorageBuilder) StorageRing() *StorageRing {\n\tsb.builder.Rebalance()\n\tstorageRing := &StorageRing{ring: sb.builder.RingDuplicate()}\n\tstorageRing.disks = make([]*StorageDisk, len(sb.disks))\n\tfor i, d := range sb.disks {\n\t\tstorageRing.disks[i] = &StorageDisk{\n\t\t\tstorageRing: storageRing,\n\t\t\tdisabled:    d.node.Disabled,\n\t\t\tcapacity:    d.node.Capacity,\n\t\t\ttierIndexes: d.node.TierIndexes,\n\t\t\taddr:        d.addr,\n\t\t\tname:        d.name,\n\t\t}\n\t}\n\tstorageRing.tierIndexToName = make([]string, len(sb.tierIndexToName))\n\tcopy(storageRing.tierIndexToName, sb.tierIndexToName)\n\treturn storageRing\n}\n\n\/\/ Since we want to be able to persist this information, we'll need to make the\n\/\/ JSON translators for the StorageBuilder.\n\ntype storageBuilderJSON struct {\n\t\/\/ ring.Builder is serializable on its own but we'll want to zero out its\n\t\/\/ nodes when we persist and copy in new node references when loading so we\n\t\/\/ aren't storing duplicate information\n\tBuilder         *ring.Builder\n\tDisks           []*BuilderDisk\n\tTierIndexToName []string\n\t\/\/ No need to store tierNameToIndex; we can rebuild that on load.\n}\n\nfunc (sb *StorageBuilder) MarshalJSON() ([]byte, error) {\n\tsavedBuilderNodes := sb.builder.Nodes\n\tsb.builder.Nodes = nil\n\tb, err := json.Marshal(&storageBuilderJSON{\n\t\tBuilder:         &sb.builder,\n\t\tDisks:           sb.disks,\n\t\tTierIndexToName: sb.tierIndexToName,\n\t})\n\tsb.builder.Nodes = savedBuilderNodes\n\treturn b, err\n}\n\nfunc (sb *StorageBuilder) UnmarshalJSON(b []byte) error {\n\tvar j storageBuilderJSON\n\tif err := json.Unmarshal(b, &j); err != nil {\n\t\treturn err\n\t}\n\tsb.builder = *j.Builder\n\tsb.disks = j.Disks\n\tsb.builder.Nodes = make([]*ring.Node, len(sb.disks))\n\tfor i, bd := range sb.disks {\n\t\tsb.builder.Nodes[i] = &bd.node\n\t}\n\tsb.tierIndexToName = j.TierIndexToName\n\tsb.tierNameToIndex = make(map[string]uint32, len(sb.tierIndexToName))\n\tfor ti, name := range sb.tierIndexToName {\n\t\tsb.tierNameToIndex[name] = uint32(ti)\n\t}\n\treturn nil\n}\n\n\/\/ Now let's define the StorageDisk and StorageRing.\n\/\/ These are completely immutable structs, as you don't want users of the ring\n\/\/ to have to constantly check if things moved, replica counts changed, etc.\n\/\/ Instead, those sort of changes would be propagated by distributing a new\n\/\/ ring.\n\ntype StorageDisk struct {\n\tstorageRing *StorageRing\n\tdisabled    bool\n\tcapacity    uint32\n\ttierIndexes []uint32\n\taddr        string\n\tname        string\n}\n\nfunc (sd *StorageDisk) Disabled() bool {\n\treturn sd.disabled\n}\n\nfunc (sd *StorageDisk) Capacity() uint32 {\n\treturn sd.capacity\n}\n\nfunc (sd *StorageDisk) Tiers() []string {\n\ttiers := make([]string, len(sd.tierIndexes))\n\tfor i, ti := range sd.tierIndexes {\n\t\ttiers[i] = sd.storageRing.tierIndexToName[ti]\n\t}\n\treturn tiers\n}\n\nfunc (sd *StorageDisk) Addr() string {\n\treturn sd.addr\n}\n\nfunc (sd *StorageDisk) Name() string {\n\treturn sd.name\n}\n\ntype StorageRing struct {\n\tring            ring.Ring\n\tdisks           []*StorageDisk\n\ttierIndexToName []string\n}\n\n\/\/ This is the main lookup method. You give it an object name and it gives you\n\/\/ the disks you should store it on.\n\/\/ We're going to use fnv for the hashing here, for convenience, but you'd\n\/\/ probably pick your favorite here, something better like blake2.\n\nfunc (sr *StorageRing) DisksFor(objectName string) []*StorageDisk {\n\thasher := fnv.New64a()\n\thasher.Write([]byte(objectName))\n\tpartition := hasher.Sum64() % uint64(sr.ring.PartitionCount())\n\tdisks := make([]*StorageDisk, sr.ring.ReplicaCount())\n\tfor replica := sr.ring.ReplicaCount() - 1; replica >= 0; replica-- {\n\t\tdisks[replica] = sr.disks[sr.ring[replica][partition]]\n\t}\n\treturn disks\n}\n\n\/\/ You would normally provide the JSON marshaling and unmarshaling methods for\n\/\/ StorageRing and StorageDisk too, but we'll skip those for now.\n\n\/\/ Now let's actually use all this stuff.\n\nfunc Example_storageUseCase() {\n\tsb := &StorageBuilder{}\n\tsb.ChangeReplicaCount(3)\n\t\/\/ We're going to add a bunch of disks, two per server, four servers per\n\t\/\/ zone, and five zones.\n\tserverNumber := 0\n\tfor _, zone := range []string{\"ZoneA\", \"ZoneB\", \"ZoneC\", \"ZoneD\", \"ZoneE\"} {\n\t\tfor i := 0; i < 4; i++ {\n\t\t\tserverNumber++\n\t\t\tfor _, disk := range []string{\"sda1\", \"sdb1\"} {\n\t\t\t\tbd := sb.AddDisk()\n\t\t\t\t\/\/ We're going to vary the capacities for a bit more work on\n\t\t\t\t\/\/ the rebalancer. This would usually represent the amount of\n\t\t\t\t\/\/ space, say, in gigabytes, that each disk has.\n\t\t\t\tbd.SetCapacity(uint32(100 + 100*i))\n\t\t\t\tbd.SetName(disk)\n\t\t\t\tbd.SetAddr(fmt.Sprintf(\"10.1.1.%d\", serverNumber))\n\t\t\t\tbd.SetTier(0, fmt.Sprintf(\"Server%d\", serverNumber))\n\t\t\t\tbd.SetTier(1, zone)\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Let's do a quick test of the JSON marshaling and unmarshaling.\n\t\/\/ We'll marshal the builder, unmarshal it into a new variable and\n\t\/\/ remarshal that, and compare.\n\tvar first []byte\n\tvar err error\n\tif first, err = json.Marshal(sb); err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tsb2 := &StorageBuilder{}\n\tjson.Unmarshal(first, &sb2)\n\tvar second []byte\n\tif second, err = json.Marshal(sb2); err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tif !bytes.Equal(first, second) {\n\t\tfmt.Println(\"not equal\")\n\t}\n\t\/\/ Now let's actually get a useful ring and look up an object.\n\tsr := sb.StorageRing()\n\tobjectName := \"my test object\"\n\tfor replica, disk := range sr.DisksFor(objectName) {\n\t\tfmt.Printf(\"Replica %d of %q is on %s\/%s which is on %s in %s\\n\", replica, objectName, disk.addr, disk.name, disk.Tiers()[0], disk.Tiers()[1])\n\t}\n\t\/\/ Output:\n\t\/\/ Replica 0 of \"my test object\" is on 10.1.1.2\/sda1 which is on Server2 in ZoneA\n\t\/\/ Replica 1 of \"my test object\" is on 10.1.1.20\/sdb1 which is on Server20 in ZoneE\n\t\/\/ Replica 2 of \"my test object\" is on 10.1.1.16\/sda1 which is on Server16 in ZoneD\n}\n<commit_msg>Added the example output as a comment since godoc.org just removed it otherwise<commit_after>package ring_test\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"hash\/fnv\"\n\n\t\"github.com\/gholt\/ring\"\n)\n\n\/\/ This will be an in-depth implementation of using the ring package. We will\n\/\/ be building a distributed object storage system where object names will be\n\/\/ mapped to disks. There will be multiple disks per server, and multiple\n\/\/ servers per zone.\n\n\/\/ First, let's define our BuilderDisk, representing a single disk in the\n\/\/ cluster and is what the ring package will be mapping assignments to.\n\n\/\/ We want all the fields to be private because we don't want users of our new\n\/\/ package to accidentally alter anything. This complicates our code, but\n\/\/ simplifies things for users of our new storage package, and would be a\n\/\/ common use case.\n\ntype BuilderDisk struct {\n\t\/\/ We'll define our specific StorageBuilder later. We need a reference to\n\t\/\/ it in each node so we notify it of changes and to resolve things like\n\t\/\/ tier names.\n\tstorageBuilder *StorageBuilder\n\t\/\/ This is the actual ring.Node the ring.Builder will need to work with,\n\t\/\/ and contains whether the disk is Disabled or not, the Capacity, and the\n\t\/\/ list of indexes that define what tiers (server, zone) the disk is in.\n\tnode ring.Node\n\t\/\/ The ip:port where the disk can be reached.\n\taddr string\n\t\/\/ The name of the disk on the server.\n\tname string\n}\n\n\/\/ Now we map public methods to the fields.\n\nfunc (bd *BuilderDisk) Disabled() bool {\n\treturn bd.node.Disabled\n}\n\nfunc (bd *BuilderDisk) SetDisabled(v bool) {\n\tbd.node.Disabled = v\n}\n\nfunc (bd *BuilderDisk) Capacity() uint32 {\n\treturn bd.node.Capacity\n}\n\nfunc (bd *BuilderDisk) SetCapacity(v uint32) {\n\tbd.node.Capacity = v\n}\n\nfunc (bd *BuilderDisk) Tiers() []string {\n\ttiers := make([]string, len(bd.node.TierIndexes))\n\tfor i, ti := range bd.node.TierIndexes {\n\t\ttiers[i] = bd.storageBuilder.tierIndexToName[ti]\n\t}\n\treturn tiers\n}\n\nfunc (bd *BuilderDisk) SetTier(tier int, name string) {\n\tfor tier >= len(bd.node.TierIndexes) {\n\t\tbd.node.TierIndexes = append(bd.node.TierIndexes, 0)\n\t}\n\tif bd.storageBuilder.tierNameToIndex == nil {\n\t\tbd.storageBuilder.tierNameToIndex = map[string]uint32{}\n\t}\n\tif ti, ok := bd.storageBuilder.tierNameToIndex[name]; ok {\n\t\tbd.node.TierIndexes[tier] = ti\n\t} else {\n\t\tti = uint32(len(bd.storageBuilder.tierIndexToName))\n\t\tbd.storageBuilder.tierIndexToName = append(bd.storageBuilder.tierIndexToName, name)\n\t\tbd.storageBuilder.tierNameToIndex[name] = ti\n\t\tbd.node.TierIndexes[tier] = ti\n\t}\n}\n\nfunc (bd *BuilderDisk) Addr() string {\n\treturn bd.addr\n}\n\nfunc (bd *BuilderDisk) SetAddr(v string) {\n\tbd.addr = v\n}\n\nfunc (bd *BuilderDisk) Name() string {\n\treturn bd.name\n}\n\nfunc (bd *BuilderDisk) SetName(v string) {\n\tbd.name = v\n}\n\n\/\/ We want to be able to persist this information, so we make JSON translators.\n\/\/ Note that this does not set the storageBuilder field; that has to be done by\n\/\/ the StorageBuilder JSON translators.\n\ntype builderDiskJSON struct {\n\t\/\/ ring.Node is serializable on its own.\n\tNode *ring.Node\n\tAddr string\n\tName string\n}\n\nfunc (bd *BuilderDisk) MarshalJSON() ([]byte, error) {\n\treturn json.Marshal(&builderDiskJSON{\n\t\tNode: &bd.node,\n\t\tAddr: bd.addr,\n\t\tName: bd.name,\n\t})\n}\n\nfunc (bd *BuilderDisk) UnmarshalJSON(b []byte) error {\n\tvar j builderDiskJSON\n\tif err := json.Unmarshal(b, &j); err != nil {\n\t\treturn err\n\t}\n\tbd.node = *j.Node\n\tbd.addr = j.Addr\n\tbd.name = j.Name\n\treturn nil\n}\n\n\/\/ Now, let's define the StorageBuilder.\n\ntype StorageBuilder struct {\n\t\/\/ This is the actual builder that will do all the reblancing work.\n\tbuilder ring.Builder\n\t\/\/ These are all the disks in the cluster, we have to map them to the\n\t\/\/ ring.Builder's nodes.\n\tdisks []*BuilderDisk\n\t\/\/ These are to give the tiers human readable names, like Server34 and\n\t\/\/ Zone5 or whatever is desired.\n\ttierIndexToName []string\n\ttierNameToIndex map[string]uint32\n}\n\nfunc (sb *StorageBuilder) AddDisk() *BuilderDisk {\n\tbd := &BuilderDisk{storageBuilder: sb}\n\tsb.disks = append(sb.disks, bd)\n\tsb.builder.Nodes = append(sb.builder.Nodes, &bd.node)\n\treturn bd\n}\n\nfunc (sb *StorageBuilder) ChangeReplicaCount(count int) {\n\tsb.builder.ChangeReplicaCount(count)\n}\n\n\/\/ We'll skip removing disks, listing all disks, reading the replica count,\n\/\/ partition count, changing last moved, etc. but those kind of methods would\n\/\/ normally exist. The important point is that any modifications need to keep\n\/\/ the ring.Builder's nodes in sync.\n\n\/\/ We do want to give a useful ring to use, so let's provide that method. We'll\n\/\/ define the StorageRing later, but it will be an immutable copy of the state\n\/\/ of things at the time of StorageRing() call.\n\nfunc (sb *StorageBuilder) StorageRing() *StorageRing {\n\tsb.builder.Rebalance()\n\tstorageRing := &StorageRing{ring: sb.builder.RingDuplicate()}\n\tstorageRing.disks = make([]*StorageDisk, len(sb.disks))\n\tfor i, d := range sb.disks {\n\t\tstorageRing.disks[i] = &StorageDisk{\n\t\t\tstorageRing: storageRing,\n\t\t\tdisabled:    d.node.Disabled,\n\t\t\tcapacity:    d.node.Capacity,\n\t\t\ttierIndexes: d.node.TierIndexes,\n\t\t\taddr:        d.addr,\n\t\t\tname:        d.name,\n\t\t}\n\t}\n\tstorageRing.tierIndexToName = make([]string, len(sb.tierIndexToName))\n\tcopy(storageRing.tierIndexToName, sb.tierIndexToName)\n\treturn storageRing\n}\n\n\/\/ Since we want to be able to persist this information, we'll need to make the\n\/\/ JSON translators for the StorageBuilder.\n\ntype storageBuilderJSON struct {\n\t\/\/ ring.Builder is serializable on its own but we'll want to zero out its\n\t\/\/ nodes when we persist and copy in new node references when loading so we\n\t\/\/ aren't storing duplicate information\n\tBuilder         *ring.Builder\n\tDisks           []*BuilderDisk\n\tTierIndexToName []string\n\t\/\/ No need to store tierNameToIndex; we can rebuild that on load.\n}\n\nfunc (sb *StorageBuilder) MarshalJSON() ([]byte, error) {\n\tsavedBuilderNodes := sb.builder.Nodes\n\tsb.builder.Nodes = nil\n\tb, err := json.Marshal(&storageBuilderJSON{\n\t\tBuilder:         &sb.builder,\n\t\tDisks:           sb.disks,\n\t\tTierIndexToName: sb.tierIndexToName,\n\t})\n\tsb.builder.Nodes = savedBuilderNodes\n\treturn b, err\n}\n\nfunc (sb *StorageBuilder) UnmarshalJSON(b []byte) error {\n\tvar j storageBuilderJSON\n\tif err := json.Unmarshal(b, &j); err != nil {\n\t\treturn err\n\t}\n\tsb.builder = *j.Builder\n\tsb.disks = j.Disks\n\tsb.builder.Nodes = make([]*ring.Node, len(sb.disks))\n\tfor i, bd := range sb.disks {\n\t\tsb.builder.Nodes[i] = &bd.node\n\t}\n\tsb.tierIndexToName = j.TierIndexToName\n\tsb.tierNameToIndex = make(map[string]uint32, len(sb.tierIndexToName))\n\tfor ti, name := range sb.tierIndexToName {\n\t\tsb.tierNameToIndex[name] = uint32(ti)\n\t}\n\treturn nil\n}\n\n\/\/ Now let's define the StorageDisk and StorageRing.\n\/\/ These are completely immutable structs, as you don't want users of the ring\n\/\/ to have to constantly check if things moved, replica counts changed, etc.\n\/\/ Instead, those sort of changes would be propagated by distributing a new\n\/\/ ring.\n\ntype StorageDisk struct {\n\tstorageRing *StorageRing\n\tdisabled    bool\n\tcapacity    uint32\n\ttierIndexes []uint32\n\taddr        string\n\tname        string\n}\n\nfunc (sd *StorageDisk) Disabled() bool {\n\treturn sd.disabled\n}\n\nfunc (sd *StorageDisk) Capacity() uint32 {\n\treturn sd.capacity\n}\n\nfunc (sd *StorageDisk) Tiers() []string {\n\ttiers := make([]string, len(sd.tierIndexes))\n\tfor i, ti := range sd.tierIndexes {\n\t\ttiers[i] = sd.storageRing.tierIndexToName[ti]\n\t}\n\treturn tiers\n}\n\nfunc (sd *StorageDisk) Addr() string {\n\treturn sd.addr\n}\n\nfunc (sd *StorageDisk) Name() string {\n\treturn sd.name\n}\n\ntype StorageRing struct {\n\tring            ring.Ring\n\tdisks           []*StorageDisk\n\ttierIndexToName []string\n}\n\n\/\/ This is the main lookup method. You give it an object name and it gives you\n\/\/ the disks you should store it on.\n\/\/ We're going to use fnv for the hashing here, for convenience, but you'd\n\/\/ probably pick your favorite here, something better like blake2.\n\nfunc (sr *StorageRing) DisksFor(objectName string) []*StorageDisk {\n\thasher := fnv.New64a()\n\thasher.Write([]byte(objectName))\n\tpartition := hasher.Sum64() % uint64(sr.ring.PartitionCount())\n\tdisks := make([]*StorageDisk, sr.ring.ReplicaCount())\n\tfor replica := sr.ring.ReplicaCount() - 1; replica >= 0; replica-- {\n\t\tdisks[replica] = sr.disks[sr.ring[replica][partition]]\n\t}\n\treturn disks\n}\n\n\/\/ You would normally provide the JSON marshaling and unmarshaling methods for\n\/\/ StorageRing and StorageDisk too, but we'll skip those for now.\n\n\/\/ Now let's actually use all this stuff.\n\nfunc Example_storageUseCase() {\n\tsb := &StorageBuilder{}\n\tsb.ChangeReplicaCount(3)\n\t\/\/ We're going to add a bunch of disks, two per server, four servers per\n\t\/\/ zone, and five zones.\n\tserverNumber := 0\n\tfor _, zone := range []string{\"ZoneA\", \"ZoneB\", \"ZoneC\", \"ZoneD\", \"ZoneE\"} {\n\t\tfor i := 0; i < 4; i++ {\n\t\t\tserverNumber++\n\t\t\tfor _, disk := range []string{\"sda1\", \"sdb1\"} {\n\t\t\t\tbd := sb.AddDisk()\n\t\t\t\t\/\/ We're going to vary the capacities for a bit more work on\n\t\t\t\t\/\/ the rebalancer. This would usually represent the amount of\n\t\t\t\t\/\/ space, say, in gigabytes, that each disk has.\n\t\t\t\tbd.SetCapacity(uint32(100 + 100*i))\n\t\t\t\tbd.SetName(disk)\n\t\t\t\tbd.SetAddr(fmt.Sprintf(\"10.1.1.%d\", serverNumber))\n\t\t\t\tbd.SetTier(0, fmt.Sprintf(\"Server%d\", serverNumber))\n\t\t\t\tbd.SetTier(1, zone)\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Let's do a quick test of the JSON marshaling and unmarshaling.\n\t\/\/ We'll marshal the builder, unmarshal it into a new variable and\n\t\/\/ remarshal that, and compare.\n\tvar first []byte\n\tvar err error\n\tif first, err = json.Marshal(sb); err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tsb2 := &StorageBuilder{}\n\tjson.Unmarshal(first, &sb2)\n\tvar second []byte\n\tif second, err = json.Marshal(sb2); err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tif !bytes.Equal(first, second) {\n\t\tfmt.Println(\"not equal\")\n\t}\n\t\/\/ Now let's actually get a useful ring and look up an object.\n\tsr := sb.StorageRing()\n\tobjectName := \"my test object\"\n\tfor replica, disk := range sr.DisksFor(objectName) {\n\t\tfmt.Printf(\"Replica %d of %q is on %s\/%s which is on %s in %s\\n\", replica, objectName, disk.addr, disk.name, disk.Tiers()[0], disk.Tiers()[1])\n\t}\n\t\/\/ Replica 0 of \"my test object\" is on 10.1.1.2\/sda1 which is on Server2 in ZoneA\n\t\/\/ Replica 1 of \"my test object\" is on 10.1.1.20\/sdb1 which is on Server20 in ZoneE\n\t\/\/ Replica 2 of \"my test object\" is on 10.1.1.16\/sda1 which is on Server16 in ZoneD\n\t\/\/ Output:\n\t\/\/ Replica 0 of \"my test object\" is on 10.1.1.2\/sda1 which is on Server2 in ZoneA\n\t\/\/ Replica 1 of \"my test object\" is on 10.1.1.20\/sdb1 which is on Server20 in ZoneE\n\t\/\/ Replica 2 of \"my test object\" is on 10.1.1.16\/sda1 which is on Server16 in ZoneD\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ DISCLAIMER\n\/\/\n\/\/ Copyright 2020 ArangoDB GmbH, Cologne, Germany\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\n\npackage test\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com\/arangodb\/go-driver\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\n\/\/ Test_Graph_AdvancedCreateV2 will check if graph created have properly set replication factor and write concern\nfunc Test_Graph_AdvancedCreateV2(t *testing.T) {\n\t\/\/ Arrange\n\tctx := context.Background()\n\n\tc := createClientFromEnv(t, true)\n\tv, err := c.Version(nil)\n\trequire.NoError(t, err)\n\n\tskipNoCluster(c, t)\n\n\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"replication\"), nil, t)\n\n\t\/\/ Create\n\tgraphID := db.Name() + \"_graph\"\n\n\toptions, collections := newGraphOpts(db)\n\toptions.ReplicationFactor = 3\n\toptions.WriteConcern = 2\n\n\t_, err = db.CreateGraphV2(ctx, graphID, &options)\n\trequire.NoError(t, err)\n\n\t\/\/ Wait for collections to be created\n\twaitForCollections(t, db, collections)\n\n\tt.Run(\"Ensure all properties are set properly\", func(t *testing.T) {\n\t\tfor _, collName := range collections {\n\t\t\tcollection, err := db.Collection(ctx, collName)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tprop, err := collection.Properties(ctx)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trequire.Equalf(t, 3, prop.NumberOfShards, \"NumberOfShards mismatch for %s\", collName)\n\n\t\t\trequire.Equalf(t, 3, prop.ReplicationFactor, \"ReplicationFactor mismatch for %s\", collName)\n\t\t\tif v.Version.CompareTo(\"3.6\") >= 0 {\n\t\t\t\trequire.Equalf(t, 2, prop.WriteConcern, \"WriteConcern mismatch for %s\", collName)\n\t\t\t}\n\t\t}\n\t})\n}\n\n\/\/ Test_Graph_AdvancedCreateV2_Defaults will check if graph created have properly set replication factor and write concern by default\nfunc Test_Graph_AdvancedCreateV2_Defaults(t *testing.T) {\n\t\/\/ Arrange\n\tctx := context.Background()\n\n\tc := createClientFromEnv(t, true)\n\tv, err := c.Version(nil)\n\trequire.NoError(t, err)\n\n\tskipNoCluster(c, t)\n\n\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\/\/ Create\n\tgraphID := db.Name() + \"_graph\"\n\n\toptions, collections := newGraphOpts(db)\n\n\t_, err = db.CreateGraphV2(ctx, graphID, &options)\n\trequire.NoError(t, err)\n\n\t\/\/ Wait for collections to be created\n\twaitForCollections(t, db, collections)\n\n\tt.Run(\"Ensure all properties are set properly by default\", func(t *testing.T) {\n\t\tfor _, collName := range collections {\n\t\t\tcollection, err := db.Collection(ctx, collName)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tprop, err := collection.Properties(ctx)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trequire.Equalf(t, 1, prop.ReplicationFactor, \"ReplicationFactor mismatch for %s\", collName)\n\t\t\tif v.Version.CompareTo(\"3.6\") >= 0 {\n\t\t\t\trequire.Equalf(t, 1, prop.WriteConcern, \"WriteConcern mismatch for %s\", collName)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestGraphCreationV2(t *testing.T) {\n\t\/\/ Arrange\n\tctx := context.Background()\n\n\tc := createClientFromEnv(t, true)\n\tEnsureVersion(t, ctx, c).CheckVersion(MinimumVersion(\"3.7.0\")).Cluster().Enterprise()\n\n\tt.Run(\"Satellite\", func(t *testing.T) {\n\t\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\t\/\/ Create\n\t\tgraphID := db.Name() + \"_graph\"\n\n\t\toptions, collections := newGraphOpts(db)\n\n\t\toptions.ReplicationFactor = driver.SatelliteGraph\n\t\toptions.IsSmart = false\n\t\toptions.SmartGraphAttribute = \"\"\n\n\t\tg, err := db.CreateGraphV2(ctx, graphID, &options)\n\t\trequire.NoError(t, err)\n\n\t\t\/\/ Wait for collections to be created\n\t\twaitForCollections(t, db, collections)\n\n\t\trequire.True(t, g.IsSatellite())\n\t})\n\n\tt.Run(\"Satellite - list\", func(t *testing.T) {\n\t\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\t\/\/ Create\n\t\tgraphID := db.Name() + \"_graph\"\n\n\t\toptions, collections := newGraphOpts(db)\n\n\t\toptions.ReplicationFactor = driver.SatelliteGraph\n\t\toptions.IsSmart = false\n\t\toptions.SmartGraphAttribute = \"\"\n\n\t\tg, err := db.CreateGraphV2(ctx, graphID, &options)\n\t\trequire.NoError(t, err)\n\n\t\t\/\/ Wait for collections to be created\n\t\twaitForCollections(t, db, collections)\n\n\t\tgraphs, err := db.Graphs(ctx)\n\t\trequire.NoError(t, err)\n\t\trequire.Len(t, graphs, 1)\n\n\t\trequire.Equal(t, g.Name(), graphs[0].Name())\n\t\trequire.True(t, graphs[0].IsSatellite())\n\t})\n\n\tt.Run(\"Standard\", func(t *testing.T) {\n\t\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\t\/\/ Create\n\t\tgraphID := db.Name() + \"_graph\"\n\n\t\toptions, collections := newGraphOpts(db)\n\n\t\tg, err := db.CreateGraphV2(ctx, graphID, &options)\n\t\trequire.NoError(t, err)\n\n\t\t\/\/ Wait for collections to be created\n\t\twaitForCollections(t, db, collections)\n\n\t\trequire.False(t, g.IsSatellite())\n\t})\n\n\tt.Run(\"Standard - list\", func(t *testing.T) {\n\t\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\t\/\/ Create\n\t\tgraphID := db.Name() + \"_graph\"\n\n\t\toptions, collections := newGraphOpts(db)\n\n\t\tg, err := db.CreateGraphV2(ctx, graphID, &options)\n\t\trequire.NoError(t, err)\n\n\t\t\/\/ Wait for collections to be created\n\t\twaitForCollections(t, db, collections)\n\n\t\tgraphs, err := db.Graphs(ctx)\n\t\trequire.NoError(t, err)\n\t\trequire.Len(t, graphs, 1)\n\n\t\trequire.Equal(t, g.Name(), graphs[0].Name())\n\t\trequire.False(t, graphs[0].IsSatellite())\n\t})\n\n\tt.Run(\"Disjoint\", func(t *testing.T) {\n\t\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\t\/\/ Create\n\t\tgraphID := db.Name() + \"_graph\"\n\n\t\toptions, collections := newGraphOpts(db)\n\n\t\toptions.IsDisjoint = true\n\n\t\tg, err := db.CreateGraphV2(ctx, graphID, &options)\n\t\trequire.NoError(t, err)\n\n\t\t\/\/ Wait for collections to be created\n\t\twaitForCollections(t, db, collections)\n\n\t\trequire.True(t, g.IsDisjoint())\n\t})\n\n\tt.Run(\"Disjoint - list\", func(t *testing.T) {\n\t\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\t\/\/ Create\n\t\tgraphID := db.Name() + \"_graph\"\n\n\t\toptions, collections := newGraphOpts(db)\n\n\t\toptions.IsDisjoint = true\n\n\t\tg, err := db.CreateGraphV2(ctx, graphID, &options)\n\t\trequire.NoError(t, err)\n\n\t\t\/\/ Wait for collections to be created\n\t\twaitForCollections(t, db, collections)\n\n\t\tgraphs, err := db.Graphs(ctx)\n\t\trequire.NoError(t, err)\n\t\trequire.Len(t, graphs, 1)\n\n\t\trequire.Equal(t, g.Name(), graphs[0].Name())\n\t\trequire.True(t, graphs[0].IsDisjoint())\n\t})\n}\n\nfunc TestHybridSmartGraphCreationV2(t *testing.T) {\n\tctx := context.Background()\n\n\tc := createClientFromEnv(t, true)\n\tEnsureVersion(t, ctx, c).CheckVersion(MinimumVersion(\"3.9.0\")).Cluster().Enterprise()\n\n\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"hybrid\"), nil, t)\n\n\tname := db.Name() + \"_test_create_hybrid_graph\"\n\tcolName := db.Name() + \"_create_hybrid_edge_col\"\n\tcol1Name := db.Name() + \"_sat_edge_col\"\n\tcol2Name := db.Name() + \"_non_sat_edge_col\"\n\n\toptions := driver.CreateGraphOptions{\n\t\tIsSmart:             true,\n\t\tSmartGraphAttribute: \"test\",\n\t\tReplicationFactor:   2,\n\t\tNumberOfShards:      2,\n\t\tSatellites:          []string{colName, col1Name},\n\t\tEdgeDefinitions: []driver.EdgeDefinition{{\n\t\t\tCollection: colName,\n\t\t\tFrom:       []string{col1Name},\n\t\t\tTo:         []string{col2Name},\n\t\t}},\n\t}\n\tg, err := db.CreateGraphV2(ctx, name, &options)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create graph '%s': %s\", name, describe(err))\n\t}\n\n\tgraphs, err := db.Graphs(ctx)\n\trequire.NoError(t, err)\n\trequire.Len(t, graphs, 1)\n\n\trequire.Equal(t, g.Name(), graphs[0].Name())\n\trequire.True(t, graphs[0].IsSmart())\n\n\tfor _, collName := range []string{colName, col1Name, col2Name} {\n\t\tcollection, err := db.Collection(ctx, collName)\n\t\trequire.NoError(t, err)\n\n\t\tprop, err := collection.Properties(ctx)\n\t\trequire.NoError(t, err)\n\n\t\tif collName == col2Name {\n\t\t\trequire.Equalf(t, 2, prop.ReplicationFactor, \"ReplicationFactor mismatch for %s\", collName)\n\t\t\trequire.Equalf(t, 2, prop.NumberOfShards, \"NumberOfShards mismatch for %s\", collName)\n\t\t} else {\n\t\t\trequire.True(t, prop.IsSatellite())\n\t\t}\n\t}\n}\n<commit_msg>[TG-209] Adjust Graph tests for the latest changes in 3.9 (#360)<commit_after>\/\/\n\/\/ DISCLAIMER\n\/\/\n\/\/ Copyright 2020 ArangoDB GmbH, Cologne, Germany\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\n\npackage test\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com\/arangodb\/go-driver\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\n\/\/ Test_Graph_AdvancedCreateV2 will check if graph created have properly set replication factor and write concern\nfunc Test_Graph_AdvancedCreateV2(t *testing.T) {\n\t\/\/ Arrange\n\tctx := context.Background()\n\n\tc := createClientFromEnv(t, true)\n\tv, err := c.Version(nil)\n\trequire.NoError(t, err)\n\n\tskipNoCluster(c, t)\n\n\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"replication\"), nil, t)\n\n\t\/\/ Create\n\tgraphID := db.Name() + \"_graph\"\n\n\toptions, collections := newGraphOpts(db)\n\toptions.ReplicationFactor = 3\n\toptions.WriteConcern = 2\n\n\t_, err = db.CreateGraphV2(ctx, graphID, &options)\n\trequire.NoError(t, err)\n\n\t\/\/ Wait for collections to be created\n\twaitForCollections(t, db, collections)\n\n\tt.Run(\"Ensure all properties are set properly\", func(t *testing.T) {\n\t\tfor _, collName := range collections {\n\t\t\tcollection, err := db.Collection(ctx, collName)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tprop, err := collection.Properties(ctx)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trequire.Equalf(t, 3, prop.NumberOfShards, \"NumberOfShards mismatch for %s\", collName)\n\n\t\t\trequire.Equalf(t, 3, prop.ReplicationFactor, \"ReplicationFactor mismatch for %s\", collName)\n\t\t\tif v.Version.CompareTo(\"3.6\") >= 0 {\n\t\t\t\trequire.Equalf(t, 2, prop.WriteConcern, \"WriteConcern mismatch for %s\", collName)\n\t\t\t}\n\t\t}\n\t})\n}\n\n\/\/ Test_Graph_AdvancedCreateV2_Defaults will check if graph created have properly set replication factor and write concern by default\nfunc Test_Graph_AdvancedCreateV2_Defaults(t *testing.T) {\n\t\/\/ Arrange\n\tctx := context.Background()\n\n\tc := createClientFromEnv(t, true)\n\tv, err := c.Version(nil)\n\trequire.NoError(t, err)\n\n\tskipNoCluster(c, t)\n\n\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\/\/ Create\n\tgraphID := db.Name() + \"_graph\"\n\n\toptions, collections := newGraphOpts(db)\n\n\t_, err = db.CreateGraphV2(ctx, graphID, &options)\n\trequire.NoError(t, err)\n\n\t\/\/ Wait for collections to be created\n\twaitForCollections(t, db, collections)\n\n\tt.Run(\"Ensure all properties are set properly by default\", func(t *testing.T) {\n\t\tfor _, collName := range collections {\n\t\t\tcollection, err := db.Collection(ctx, collName)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tprop, err := collection.Properties(ctx)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trequire.Equalf(t, 1, prop.ReplicationFactor, \"ReplicationFactor mismatch for %s\", collName)\n\t\t\tif v.Version.CompareTo(\"3.6\") >= 0 {\n\t\t\t\trequire.Equalf(t, 1, prop.WriteConcern, \"WriteConcern mismatch for %s\", collName)\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc TestGraphCreationV2(t *testing.T) {\n\t\/\/ Arrange\n\tctx := context.Background()\n\n\tc := createClientFromEnv(t, true)\n\tEnsureVersion(t, ctx, c).CheckVersion(MinimumVersion(\"3.7.0\")).Cluster().Enterprise()\n\n\tt.Run(\"Satellite\", func(t *testing.T) {\n\t\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\t\/\/ Create\n\t\tgraphID := db.Name() + \"_graph\"\n\n\t\toptions, collections := newGraphOpts(db)\n\n\t\toptions.ReplicationFactor = driver.SatelliteGraph\n\t\toptions.NumberOfShards = 1\n\t\toptions.IsSmart = false\n\t\toptions.SmartGraphAttribute = \"\"\n\n\t\tg, err := db.CreateGraphV2(ctx, graphID, &options)\n\t\trequire.NoError(t, err)\n\n\t\t\/\/ Wait for collections to be created\n\t\twaitForCollections(t, db, collections)\n\n\t\trequire.True(t, g.IsSatellite())\n\t})\n\n\tt.Run(\"Satellite - list\", func(t *testing.T) {\n\t\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\t\/\/ Create\n\t\tgraphID := db.Name() + \"_graph\"\n\n\t\toptions, collections := newGraphOpts(db)\n\n\t\toptions.ReplicationFactor = driver.SatelliteGraph\n\t\toptions.NumberOfShards = 1\n\t\toptions.IsSmart = false\n\t\toptions.SmartGraphAttribute = \"\"\n\n\t\tg, err := db.CreateGraphV2(ctx, graphID, &options)\n\t\trequire.NoError(t, err)\n\n\t\t\/\/ Wait for collections to be created\n\t\twaitForCollections(t, db, collections)\n\n\t\tgraphs, err := db.Graphs(ctx)\n\t\trequire.NoError(t, err)\n\t\trequire.Len(t, graphs, 1)\n\n\t\trequire.Equal(t, g.Name(), graphs[0].Name())\n\t\trequire.True(t, graphs[0].IsSatellite())\n\t})\n\n\tt.Run(\"Standard\", func(t *testing.T) {\n\t\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\t\/\/ Create\n\t\tgraphID := db.Name() + \"_graph\"\n\n\t\toptions, collections := newGraphOpts(db)\n\n\t\tg, err := db.CreateGraphV2(ctx, graphID, &options)\n\t\trequire.NoError(t, err)\n\n\t\t\/\/ Wait for collections to be created\n\t\twaitForCollections(t, db, collections)\n\n\t\trequire.False(t, g.IsSatellite())\n\t})\n\n\tt.Run(\"Standard - list\", func(t *testing.T) {\n\t\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\t\/\/ Create\n\t\tgraphID := db.Name() + \"_graph\"\n\n\t\toptions, collections := newGraphOpts(db)\n\n\t\tg, err := db.CreateGraphV2(ctx, graphID, &options)\n\t\trequire.NoError(t, err)\n\n\t\t\/\/ Wait for collections to be created\n\t\twaitForCollections(t, db, collections)\n\n\t\tgraphs, err := db.Graphs(ctx)\n\t\trequire.NoError(t, err)\n\t\trequire.Len(t, graphs, 1)\n\n\t\trequire.Equal(t, g.Name(), graphs[0].Name())\n\t\trequire.False(t, graphs[0].IsSatellite())\n\t})\n\n\tt.Run(\"Disjoint\", func(t *testing.T) {\n\t\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\t\/\/ Create\n\t\tgraphID := db.Name() + \"_graph\"\n\n\t\toptions, collections := newGraphOpts(db)\n\n\t\toptions.IsDisjoint = true\n\n\t\tg, err := db.CreateGraphV2(ctx, graphID, &options)\n\t\trequire.NoError(t, err)\n\n\t\t\/\/ Wait for collections to be created\n\t\twaitForCollections(t, db, collections)\n\n\t\trequire.True(t, g.IsDisjoint())\n\t})\n\n\tt.Run(\"Disjoint - list\", func(t *testing.T) {\n\t\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"defaults\"), nil, t)\n\n\t\t\/\/ Create\n\t\tgraphID := db.Name() + \"_graph\"\n\n\t\toptions, collections := newGraphOpts(db)\n\n\t\toptions.IsDisjoint = true\n\n\t\tg, err := db.CreateGraphV2(ctx, graphID, &options)\n\t\trequire.NoError(t, err)\n\n\t\t\/\/ Wait for collections to be created\n\t\twaitForCollections(t, db, collections)\n\n\t\tgraphs, err := db.Graphs(ctx)\n\t\trequire.NoError(t, err)\n\t\trequire.Len(t, graphs, 1)\n\n\t\trequire.Equal(t, g.Name(), graphs[0].Name())\n\t\trequire.True(t, graphs[0].IsDisjoint())\n\t})\n}\n\nfunc TestHybridSmartGraphCreationV2(t *testing.T) {\n\tctx := context.Background()\n\n\tc := createClientFromEnv(t, true)\n\tEnsureVersion(t, ctx, c).CheckVersion(MinimumVersion(\"3.9.0\")).Cluster().Enterprise()\n\n\tdb := ensureDatabase(ctx, c, databaseName(\"graph\", \"create\", \"hybrid\"), nil, t)\n\n\tname := db.Name() + \"_test_create_hybrid_graph\"\n\tcolName := db.Name() + \"_create_hybrid_edge_col\"\n\tcol1Name := db.Name() + \"_sat_edge_col\"\n\tcol2Name := db.Name() + \"_non_sat_edge_col\"\n\n\toptions := driver.CreateGraphOptions{\n\t\tIsSmart:             true,\n\t\tSmartGraphAttribute: \"test\",\n\t\tReplicationFactor:   2,\n\t\tNumberOfShards:      2,\n\t\tSatellites:          []string{colName, col1Name},\n\t\tEdgeDefinitions: []driver.EdgeDefinition{{\n\t\t\tCollection: colName,\n\t\t\tFrom:       []string{col1Name},\n\t\t\tTo:         []string{col2Name},\n\t\t}},\n\t}\n\tg, err := db.CreateGraphV2(ctx, name, &options)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create graph '%s': %s\", name, describe(err))\n\t}\n\n\tgraphs, err := db.Graphs(ctx)\n\trequire.NoError(t, err)\n\trequire.Len(t, graphs, 1)\n\n\trequire.Equal(t, g.Name(), graphs[0].Name())\n\trequire.True(t, graphs[0].IsSmart())\n\n\tfor _, collName := range []string{colName, col1Name, col2Name} {\n\t\tcollection, err := db.Collection(ctx, collName)\n\t\trequire.NoError(t, err)\n\n\t\tprop, err := collection.Properties(ctx)\n\t\trequire.NoError(t, err)\n\n\t\tif collName == col2Name {\n\t\t\trequire.Equalf(t, 2, prop.ReplicationFactor, \"ReplicationFactor mismatch for %s\", collName)\n\t\t\trequire.Equalf(t, 2, prop.NumberOfShards, \"NumberOfShards mismatch for %s\", collName)\n\t\t} else {\n\t\t\trequire.True(t, prop.IsSatellite())\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/alecthomas\/template\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar HELM_BIN = \"\/bin\/helm\"\nvar KUBECONFIG = \"\/root\/.kube\/kubeconfig\"\nvar CONFIG = \"\/root\/.kube\/config\"\n\ntype (\n\t\/\/ Config maps the params we need to run Helm\n\tConfig struct {\n\t\tAPIServer     string   `json:\"api_server\"`\n\t\tToken         string   `json:\"token\"`\n\t\tHelmCommand   []string `json:\"helm_command\"`\n\t\tSkipTLSVerify bool     `json:\"tls_skip_verify\"`\n\t\tNamespace     string   `json:\"namespace\"`\n\t\tRelease       string   `json:\"release\"`\n\t\tChart         string   `json:\"chart\"`\n\t\tValues        string   `json:\"values\"`\n\t\tDebug         bool     `json:\"debug\"`\n\t\tDryRun        bool     `json:\"dry_run\"`\n\t\tSecrets       []string `json:\"secrets\"`\n\t\tPrefix        string   `json:\"prefix\"`\n\t}\n\t\/\/ Plugin default\n\tPlugin struct {\n\t\tConfig Config\n\t}\n)\n\nfunc setHelmHelp(p *Plugin) {\n\tp.Config.HelmCommand = []string{\"\"}\n}\nfunc setDeleteEventCommand(p *Plugin) {\n\tupgrade := make([]string, 2)\n\tupgrade[0] = \"delete\"\n\tupgrade[1] = p.Config.Release\n\n\tp.Config.HelmCommand = upgrade\n}\n\nfunc setPushEventCommand(p *Plugin) {\n\tupgrade := make([]string, 2)\n\tupgrade[0] = \"upgrade\"\n\tupgrade[1] = \"--install\"\n\tif p.Config.Release != \"\" {\n\t\tupgrade = append(upgrade, p.Config.Release)\n\t}\n\tupgrade = append(upgrade, p.Config.Chart)\n\tif p.Config.Values != \"\" {\n\t\tupgrade = append(upgrade, \"--set\")\n\t\tupgrade = append(upgrade, p.Config.Values)\n\t}\n\tif p.Config.DryRun {\n\t\tupgrade = append(upgrade, \"--dry-run\")\n\t}\n\tif p.Config.Debug {\n\t\tupgrade = append(upgrade, \"--debug\")\n\t}\n\tp.Config.HelmCommand = upgrade\n\n}\n\nfunc setHelmCommand(p *Plugin) {\n\tbuildEvent := os.Getenv(\"DRONE_BUILD_EVENT\")\n\tswitch buildEvent {\n\tcase \"push\":\n\t\tsetPushEventCommand(p)\n\tcase \"delete\":\n\t\tsetDeleteEventCommand(p)\n\tdefault:\n\t\tsetHelmHelp(p)\n\t}\n\n}\n\n\/\/ Exec default method\nfunc (p *Plugin) Exec() error {\n\tresolveSecrets(p)\n\tif p.Config.APIServer == \"\" {\n\t\treturn fmt.Errorf(\"Error: API Server is needed to deploy.\")\n\t}\n\tif p.Config.Token == \"\" {\n\t\treturn fmt.Errorf(\"Error: Token is needed to deploy.\")\n\t}\n\tinitialiseKubeconfig(&p.Config, KUBECONFIG, CONFIG)\n\n\tif p.Config.Debug {\n\t\tp.debug()\n\t}\n\n\tinit := make([]string, 1)\n\tinit[0] = \"init\"\n\terr := runCommand(init)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error running helm comand: \" + strings.Join(init[:], \" \"))\n\t}\n\n\tsetHelmCommand(p)\n\tif p.Config.Debug {\n\t\tlog.Println(\"helm comand: \" + strings.Join(p.Config.HelmCommand[:], \" \"))\n\t}\n\terr = runCommand(p.Config.HelmCommand)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error running helm comand: \" + strings.Join(p.Config.HelmCommand[:], \" \"))\n\t}\n\treturn nil\n}\n\nfunc initialiseKubeconfig(params *Config, source string, target string) error {\n\tt, _ := template.ParseFiles(source)\n\tf, err := os.Create(target)\n\terr = t.Execute(f, params)\n\tf.Close()\n\treturn err\n}\n\nfunc runCommand(params []string) error {\n\tcmd := new(exec.Cmd)\n\tcmd = exec.Command(HELM_BIN, params...)\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\terr := cmd.Run()\n\treturn err\n}\n\nfunc resolveSecrets(p *Plugin) {\n\tp.Config.Values = resolveEnvVar(p.Config.Values, p.Config.Prefix)\n\tp.Config.APIServer = resolveEnvVar(\"${API_SERVER}\", p.Config.Prefix)\n\tp.Config.Token = resolveEnvVar(\"${TOKEN}\", p.Config.Prefix)\n}\n\n\/\/ getEnvVars will return [${TAG} {TAG} TAG]\nfunc getEnvVars(envvars string) [][]string {\n\tre := regexp.MustCompile(`\\$(\\{?(\\w+)\\}?)\\.?`)\n\textracted := re.FindAllStringSubmatch(envvars, -1)\n\treturn extracted\n}\n\nfunc resolveEnvVar(key string, prefix string) string {\n\tenvvars := getEnvVars(key)\n\treturn replaceEnvvars(envvars, prefix, key)\n}\n\nfunc replaceEnvvars(envvars [][]string, prefix string, s string) string {\n\tfmt.Println(\"--- params passed to replaceEnvvars ----\")\n\tfmt.Println(envvars)\n\tfmt.Println(prefix)\n\tfmt.Println(s)\n\tfmt.Println(\"--------\")\n\tfor _, envvar := range envvars {\n\t\t\/\/ [${TAG} {TAG} TAG]\n\t\tfmt.Println(envvar)\n\t\tenvvarName := envvar[0]\n\t\tenvvarKey := envvar[2]\n\t\tif prefix != \"\" {\n\t\t\tenvvarKey = prefix + \"_\" + envvarKey\n\t\t}\n\t\tenvval := os.Getenv(envvarKey)\n\t\tfmt.Printf(\"Envval %s using key: %s \\n\", envval, envvarKey)\n\t\tfmt.Printf(\"Replacing %s by %s in --%s-- using envvar as %s\\n with value: %s\", envvarName, envval, s, envvarKey, envval)\n\t\tif strings.Contains(s, envvarName) {\n\t\t\ts = strings.Replace(s, envvarName, envval, -1)\n\t\t}\n\t}\n\tfmt.Println(s)\n\treturn s\n}\n\nfunc (p *Plugin) debug() {\n\tfmt.Println(p)\n\t\/\/ debug env vars\n\tfor _, e := range os.Environ() {\n\t\tfmt.Println(\"-Var:--\", e)\n\t}\n\t\/\/ debug plugin obj\n\tfmt.Printf(\"Api server: %s \\n\", p.Config.APIServer)\n\tfmt.Printf(\"Values: %s \\n\", p.Config.Values)\n\tfmt.Printf(\"Values: %s \\n\", p.Config.Secrets)\n\n\tkubeconfig, err := ioutil.ReadFile(KUBECONFIG)\n\tif err == nil {\n\t\tfmt.Println(string(kubeconfig))\n\t}\n\tconfig, err := ioutil.ReadFile(CONFIG)\n\tif err == nil {\n\t\tfmt.Println(string(config))\n\t}\n\n}\n<commit_msg>remove debug statments<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/alecthomas\/template\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar HELM_BIN = \"\/bin\/helm\"\nvar KUBECONFIG = \"\/root\/.kube\/kubeconfig\"\nvar CONFIG = \"\/root\/.kube\/config\"\n\ntype (\n\t\/\/ Config maps the params we need to run Helm\n\tConfig struct {\n\t\tAPIServer     string   `json:\"api_server\"`\n\t\tToken         string   `json:\"token\"`\n\t\tHelmCommand   []string `json:\"helm_command\"`\n\t\tSkipTLSVerify bool     `json:\"tls_skip_verify\"`\n\t\tNamespace     string   `json:\"namespace\"`\n\t\tRelease       string   `json:\"release\"`\n\t\tChart         string   `json:\"chart\"`\n\t\tValues        string   `json:\"values\"`\n\t\tDebug         bool     `json:\"debug\"`\n\t\tDryRun        bool     `json:\"dry_run\"`\n\t\tSecrets       []string `json:\"secrets\"`\n\t\tPrefix        string   `json:\"prefix\"`\n\t}\n\t\/\/ Plugin default\n\tPlugin struct {\n\t\tConfig Config\n\t}\n)\n\nfunc setHelmHelp(p *Plugin) {\n\tp.Config.HelmCommand = []string{\"\"}\n}\nfunc setDeleteEventCommand(p *Plugin) {\n\tupgrade := make([]string, 2)\n\tupgrade[0] = \"delete\"\n\tupgrade[1] = p.Config.Release\n\n\tp.Config.HelmCommand = upgrade\n}\n\nfunc setPushEventCommand(p *Plugin) {\n\tupgrade := make([]string, 2)\n\tupgrade[0] = \"upgrade\"\n\tupgrade[1] = \"--install\"\n\tif p.Config.Release != \"\" {\n\t\tupgrade = append(upgrade, p.Config.Release)\n\t}\n\tupgrade = append(upgrade, p.Config.Chart)\n\tif p.Config.Values != \"\" {\n\t\tupgrade = append(upgrade, \"--set\")\n\t\tupgrade = append(upgrade, p.Config.Values)\n\t}\n\tif p.Config.DryRun {\n\t\tupgrade = append(upgrade, \"--dry-run\")\n\t}\n\tif p.Config.Debug {\n\t\tupgrade = append(upgrade, \"--debug\")\n\t}\n\tp.Config.HelmCommand = upgrade\n\n}\n\nfunc setHelmCommand(p *Plugin) {\n\tbuildEvent := os.Getenv(\"DRONE_BUILD_EVENT\")\n\tswitch buildEvent {\n\tcase \"push\":\n\t\tsetPushEventCommand(p)\n\tcase \"delete\":\n\t\tsetDeleteEventCommand(p)\n\tdefault:\n\t\tsetHelmHelp(p)\n\t}\n\n}\n\n\/\/ Exec default method\nfunc (p *Plugin) Exec() error {\n\tresolveSecrets(p)\n\tif p.Config.APIServer == \"\" {\n\t\treturn fmt.Errorf(\"Error: API Server is needed to deploy.\")\n\t}\n\tif p.Config.Token == \"\" {\n\t\treturn fmt.Errorf(\"Error: Token is needed to deploy.\")\n\t}\n\tinitialiseKubeconfig(&p.Config, KUBECONFIG, CONFIG)\n\n\tif p.Config.Debug {\n\t\tp.debug()\n\t}\n\n\tinit := make([]string, 1)\n\tinit[0] = \"init\"\n\terr := runCommand(init)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error running helm comand: \" + strings.Join(init[:], \" \"))\n\t}\n\n\tsetHelmCommand(p)\n\tif p.Config.Debug {\n\t\tlog.Println(\"helm comand: \" + strings.Join(p.Config.HelmCommand[:], \" \"))\n\t}\n\terr = runCommand(p.Config.HelmCommand)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error running helm comand: \" + strings.Join(p.Config.HelmCommand[:], \" \"))\n\t}\n\treturn nil\n}\n\nfunc initialiseKubeconfig(params *Config, source string, target string) error {\n\tt, _ := template.ParseFiles(source)\n\tf, err := os.Create(target)\n\terr = t.Execute(f, params)\n\tf.Close()\n\treturn err\n}\n\nfunc runCommand(params []string) error {\n\tcmd := new(exec.Cmd)\n\tcmd = exec.Command(HELM_BIN, params...)\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\terr := cmd.Run()\n\treturn err\n}\n\nfunc resolveSecrets(p *Plugin) {\n\tp.Config.Values = resolveEnvVar(p.Config.Values, p.Config.Prefix)\n\tp.Config.APIServer = resolveEnvVar(\"${API_SERVER}\", p.Config.Prefix)\n\tp.Config.Token = resolveEnvVar(\"${TOKEN}\", p.Config.Prefix)\n}\n\n\/\/ getEnvVars will return [${TAG} {TAG} TAG]\nfunc getEnvVars(envvars string) [][]string {\n\tre := regexp.MustCompile(`\\$(\\{?(\\w+)\\}?)\\.?`)\n\textracted := re.FindAllStringSubmatch(envvars, -1)\n\treturn extracted\n}\n\nfunc resolveEnvVar(key string, prefix string) string {\n\tenvvars := getEnvVars(key)\n\treturn replaceEnvvars(envvars, prefix, key)\n}\n\nfunc replaceEnvvars(envvars [][]string, prefix string, s string) string {\n\tfor _, envvar := range envvars {\n\t\t\/\/ [${TAG} {TAG} TAG]\n\t\tenvvarName := envvar[0]\n\t\tenvvarKey := envvar[2]\n\t\tif prefix != \"\" {\n\t\t\tenvvarKey = prefix + \"_\" + envvarKey\n\t\t}\n\t\tenvval := os.Getenv(envvarKey)\n\t\tif strings.Contains(s, envvarName) {\n\t\t\ts = strings.Replace(s, envvarName, envval, -1)\n\t\t}\n\t}\n\treturn s\n}\n\nfunc (p *Plugin) debug() {\n\tfmt.Println(p)\n\t\/\/ debug env vars\n\tfor _, e := range os.Environ() {\n\t\tfmt.Println(\"-Var:--\", e)\n\t}\n\t\/\/ debug plugin obj\n\tfmt.Printf(\"Api server: %s \\n\", p.Config.APIServer)\n\tfmt.Printf(\"Values: %s \\n\", p.Config.Values)\n\tfmt.Printf(\"Values: %s \\n\", p.Config.Secrets)\n\n\tkubeconfig, err := ioutil.ReadFile(KUBECONFIG)\n\tif err == nil {\n\t\tfmt.Println(string(kubeconfig))\n\t}\n\tconfig, err := ioutil.ReadFile(CONFIG)\n\tif err == nil {\n\t\tfmt.Println(string(config))\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\n\tdockerapi \"github.com\/docker\/docker\/api\"\n\tdockerclient \"github.com\/docker\/engine-api\/client\"\n\t\"github.com\/docker\/go-plugins-helpers\/authorization\"\n)\n\nfunc newPlugin(dockerHost, certPath string, tlsVerify bool) (*novolume, error) {\n\tvar transport *http.Transport\n\tif certPath != \"\" {\n\t\ttlsc := &tls.Config{}\n\n\t\tcert, err := tls.LoadX509KeyPair(filepath.Join(certPath, \"cert.pem\"), filepath.Join(certPath, \"key.pem\"))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error loading x509 key pair: %s\", err)\n\t\t}\n\n\t\ttlsc.Certificates = append(tlsc.Certificates, cert)\n\t\ttlsc.InsecureSkipVerify = !tlsVerify\n\t\ttransport = &http.Transport{\n\t\t\tTLSClientConfig: tlsc,\n\t\t}\n\t}\n\n\tclient, err := dockerclient.NewClient(dockerHost, dockerapi.DefaultVersion.String(), transport, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &novolume{client: client}, nil\n}\n\nvar (\n\tstartRegExp = regexp.MustCompile(`\/containers\/(.*)\/start$`)\n)\n\ntype novolume struct {\n\tclient *dockerclient.Client\n}\n\nfunc (p *novolume) AuthZReq(req authorization.Request) authorization.Response {\n\tif req.RequestMethod == \"POST\" && startRegExp.MatchString(req.RequestURI) {\n\t\t\/\/ this is deprecated in docker, remove once hostConfig is dropped to\n\t\t\/\/ being available at start time\n\t\tif req.RequestBody != nil {\n\t\t\ttype vfrom struct {\n\t\t\t\tVolumesFrom []string\n\t\t\t}\n\t\t\tvf := &vfrom{}\n\t\t\tif err := json.NewDecoder(bytes.NewReader(req.RequestBody)).Decode(vf); err != nil {\n\t\t\t\treturn authorization.Response{Err: err.Error()}\n\t\t\t}\n\t\t\tif len(vf.VolumesFrom) > 0 {\n\t\t\t\tgoto noallow\n\t\t\t}\n\t\t}\n\t\tres := startRegExp.FindStringSubmatch(req.RequestURI)\n\t\tif len(res) < 1 {\n\t\t\treturn authorization.Response{Err: \"unable to find container name\"}\n\t\t}\n\t\tcontainer, err := p.client.ContainerInspect(res[1])\n\t\tif err != nil {\n\t\t\treturn authorization.Response{Err: err.Error()}\n\t\t}\n\t\tbindDests := []string{}\n\t\tfor _, m := range container.Mounts {\n\t\t\tif m.Driver != \"\" {\n\t\t\t\tgoto noallow\n\t\t\t}\n\t\t\tbindDests = append(bindDests, m.Destination)\n\t\t}\n\t\timage, _, err := p.client.ImageInspectWithRaw(container.Image, false)\n\t\tif err != nil {\n\t\t\treturn authorization.Response{Err: err.Error()}\n\t\t}\n\t\tif len(bindDests) == 0 && len(image.Config.Volumes) > 0 {\n\t\t\tgoto noallow\n\t\t}\n\t\tif len(image.Config.Volumes) > 0 {\n\t\t\tfor _, bd := range bindDests {\n\t\t\t\tif _, ok := image.Config.Volumes[bd]; !ok {\n\t\t\t\t\tgoto noallow\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(container.HostConfig.VolumesFrom) > 0 {\n\t\t\tgoto noallow\n\t\t}\n\t\t\/\/ TODO(runcom): FROM scratch ?!?!\n\t}\n\treturn authorization.Response{Allow: true}\n\nnoallow:\n\treturn authorization.Response{Msg: \"volumes are not allowed\"}\n}\n\nfunc (p *novolume) AuthZRes(req authorization.Request) authorization.Response {\n\treturn authorization.Response{Allow: true}\n}\n<commit_msg>fix bypass when query string is in request URI<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\n\tdockerapi \"github.com\/docker\/docker\/api\"\n\tdockerclient \"github.com\/docker\/engine-api\/client\"\n\t\"github.com\/docker\/go-plugins-helpers\/authorization\"\n)\n\nfunc newPlugin(dockerHost, certPath string, tlsVerify bool) (*novolume, error) {\n\tvar transport *http.Transport\n\tif certPath != \"\" {\n\t\ttlsc := &tls.Config{}\n\n\t\tcert, err := tls.LoadX509KeyPair(filepath.Join(certPath, \"cert.pem\"), filepath.Join(certPath, \"key.pem\"))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error loading x509 key pair: %s\", err)\n\t\t}\n\n\t\ttlsc.Certificates = append(tlsc.Certificates, cert)\n\t\ttlsc.InsecureSkipVerify = !tlsVerify\n\t\ttransport = &http.Transport{\n\t\t\tTLSClientConfig: tlsc,\n\t\t}\n\t}\n\n\tclient, err := dockerclient.NewClient(dockerHost, dockerapi.DefaultVersion.String(), transport, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &novolume{client: client}, nil\n}\n\nvar (\n\tstartRegExp = regexp.MustCompile(`\/containers\/(.*)\/start`)\n)\n\ntype novolume struct {\n\tclient *dockerclient.Client\n}\n\nfunc (p *novolume) AuthZReq(req authorization.Request) authorization.Response {\n\tif req.RequestMethod == \"POST\" && startRegExp.MatchString(req.RequestURI) {\n\t\t\/\/ this is deprecated in docker, remove once hostConfig is dropped to\n\t\t\/\/ being available at start time\n\t\tif req.RequestBody != nil {\n\t\t\ttype vfrom struct {\n\t\t\t\tVolumesFrom []string\n\t\t\t}\n\t\t\tvf := &vfrom{}\n\t\t\tif err := json.NewDecoder(bytes.NewReader(req.RequestBody)).Decode(vf); err != nil {\n\t\t\t\treturn authorization.Response{Err: err.Error()}\n\t\t\t}\n\t\t\tif len(vf.VolumesFrom) > 0 {\n\t\t\t\tgoto noallow\n\t\t\t}\n\t\t}\n\t\tres := startRegExp.FindStringSubmatch(req.RequestURI)\n\t\tif len(res) < 1 {\n\t\t\treturn authorization.Response{Err: \"unable to find container name\"}\n\t\t}\n\t\tcontainer, err := p.client.ContainerInspect(res[1])\n\t\tif err != nil {\n\t\t\treturn authorization.Response{Err: err.Error()}\n\t\t}\n\t\tbindDests := []string{}\n\t\tfor _, m := range container.Mounts {\n\t\t\tif m.Driver != \"\" {\n\t\t\t\tgoto noallow\n\t\t\t}\n\t\t\tbindDests = append(bindDests, m.Destination)\n\t\t}\n\t\timage, _, err := p.client.ImageInspectWithRaw(container.Image, false)\n\t\tif err != nil {\n\t\t\treturn authorization.Response{Err: err.Error()}\n\t\t}\n\t\tif len(bindDests) == 0 && len(image.Config.Volumes) > 0 {\n\t\t\tgoto noallow\n\t\t}\n\t\tif len(image.Config.Volumes) > 0 {\n\t\t\tfor _, bd := range bindDests {\n\t\t\t\tif _, ok := image.Config.Volumes[bd]; !ok {\n\t\t\t\t\tgoto noallow\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(container.HostConfig.VolumesFrom) > 0 {\n\t\t\tgoto noallow\n\t\t}\n\t\t\/\/ TODO(runcom): FROM scratch ?!?!\n\t}\n\treturn authorization.Response{Allow: true}\n\nnoallow:\n\treturn authorization.Response{Msg: \"volumes are not allowed\"}\n}\n\nfunc (p *novolume) AuthZRes(req authorization.Request) authorization.Response {\n\treturn authorization.Response{Allow: true}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"code.google.com\/p\/goprotobuf\/proto\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/getgauge\/common\"\n\t\"net\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\texecutionScope          = \"execution\"\n\tpluginConnectionTimeout = time.Second * 10\n\tsetupScope              = \"setup\"\n\tpluginConnectionPortEnv = \"plugin_connection_port\"\n)\n\ntype pluginDescriptor struct {\n\tId          string\n\tVersion     string\n\tName        string\n\tDescription string\n\tCommand     struct {\n\t\tWindows []string\n\t\tLinux   []string\n\t\tDarwin  []string\n\t}\n\tScope      []string\n\tpluginPath string\n}\n\ntype pluginHandler struct {\n\tpluginsMap map[string]*plugin\n}\n\ntype plugin struct {\n\tconnection net.Conn\n\tpluginCmd  *exec.Cmd\n\tdescriptor *pluginDescriptor\n}\n\nfunc (plugin *plugin) kill(wg *sync.WaitGroup) error {\n\tdefer wg.Done()\n\tif plugin.isStillRunning() {\n\n\t\texited := make(chan bool, 1)\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tif plugin.isStillRunning() {\n\t\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\t} else {\n\t\t\t\t\texited <- true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tselect {\n\t\tcase done := <-exited:\n\t\t\tif done {\n\t\t\t\tfmt.Println(fmt.Sprintf(\"Plugin [%s] with pid [%d] has exited\", plugin.descriptor.Name, plugin.pluginCmd.Process.Pid))\n\t\t\t}\n\t\tcase <-time.After(pluginConnectionTimeout):\n\t\t\tfmt.Println(fmt.Sprintf(\"Plugin [%s] with pid [%d] did not exit after %.2f seconds. Forcefully killing it.\", plugin.descriptor.Name, plugin.pluginCmd.Process.Pid, pluginConnectionTimeout.Seconds()))\n\t\t\treturn plugin.pluginCmd.Process.Kill()\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (plugin *plugin) isStillRunning() bool {\n\treturn plugin.pluginCmd.ProcessState == nil || !plugin.pluginCmd.ProcessState.Exited()\n}\n\nfunc isPluginInstalled(pluginName, pluginVersion string) bool {\n\tpluginsInstallDir, err := common.GetPluginsInstallDir(pluginName)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tthisPluginDir := path.Join(pluginsInstallDir, pluginName)\n\tif !common.DirExists(thisPluginDir) {\n\t\treturn false\n\t}\n\n\tif pluginVersion != \"\" {\n\t\tpluginJson := path.Join(thisPluginDir, pluginVersion, common.PluginJsonFile)\n\t\tif common.FileExists(pluginJson) {\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\treturn true\n\t}\n}\n\nfunc getPluginJsonPath(pluginName, version string) (string, error) {\n\tif !isPluginInstalled(pluginName, version) {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"%s %s is not installed\", pluginName))\n\t}\n\n\tpluginInstallDir, err := common.GetPluginInstallDir(pluginName, \"\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(pluginInstallDir, common.PluginJsonFile), nil\n}\n\nfunc getPluginDescriptor(pluginId, pluginVersion string) (*pluginDescriptor, error) {\n\tpluginJson, err := getPluginJsonPath(pluginId, pluginVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpluginJsonContents, err := common.ReadFileContents(pluginJson)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar pd pluginDescriptor\n\tif err = json.Unmarshal([]byte(pluginJsonContents), &pd); err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"%s: %s\", pluginJson, err.Error()))\n\t}\n\tpd.pluginPath = filepath.Dir(pluginJson)\n\n\treturn &pd, nil\n}\n\nfunc startPlugin(pd *pluginDescriptor, action string, wait bool) (*exec.Cmd, error) {\n\tcommand := []string{}\n\tswitch runtime.GOOS {\n\tcase \"windows\":\n\t\tcommand = pd.Command.Windows\n\t\tbreak\n\tcase \"darwin\":\n\t\tcommand = pd.Command.Darwin\n\t\tbreak\n\tdefault:\n\t\tcommand = pd.Command.Linux\n\t\tbreak\n\t}\n\n\tpluginConsoleWriter := &pluginConsoleWriter{pluginName: pd.Name}\n\tcmd, err := common.ExecuteCommand(command, pd.pluginPath, pluginConsoleWriter, pluginConsoleWriter)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif wait {\n\t\treturn cmd, cmd.Wait()\n\t} else {\n\t\tgo func() {\n\t\t\tcmd.Wait()\n\t\t}()\n\t}\n\n\treturn cmd, nil\n}\n\nfunc setEnvForPlugin(action string, pd *pluginDescriptor, manifest *manifest, pluginEnvVars map[string]string) error {\n\tpluginEnvVars[fmt.Sprintf(\"%s_action\", pd.Id)] = action\n\tpluginEnvVars[\"test_language\"] = manifest.Language\n\tif err := setEnvironmentProperties(pluginEnvVars); err != nil {\n\t\treturn err\n\t}\n\tif err := setCurrentProjectEnvVariable(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc setEnvironmentProperties(properties map[string]string) error {\n\tfor k, v := range properties {\n\t\tif err := common.SetEnvVariable(k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc addPluginToTheProject(pluginName string, pluginArgs map[string]string, manifest *manifest) error {\n\tpd, err := getPluginDescriptor(pluginName, pluginArgs[\"version\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif isPluginAdded(manifest, pd) {\n\t\treturn errors.New(\"Plugin \" + pd.Name + \" is already added\")\n\t}\n\taction := setupScope\n\tif err := setEnvForPlugin(action, pd, manifest, pluginArgs); err != nil {\n\t\treturn err\n\t}\n\tif _, err := startPlugin(pd, action, true); err != nil {\n\t\treturn err\n\t}\n\tmanifest.Plugins = append(manifest.Plugins, pd.Id)\n\treturn manifest.save()\n}\n\nfunc isPluginAdded(manifest *manifest, descriptor *pluginDescriptor) bool {\n\tfor _, pluginId := range manifest.Plugins {\n\t\tif pluginId == descriptor.Id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc startPluginsForExecution(manifest *manifest) (*pluginHandler, []string) {\n\twarnings := make([]string, 0)\n\thandler := &pluginHandler{}\n\tenvProperties := make(map[string]string)\n\n\tfor _, pluginId := range manifest.Plugins {\n\t\tpd, err := getPluginDescriptor(pluginId, \"\")\n\t\tif err != nil {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"Error starting plugin %s. Failed to get plugin.json. %s\", pluginId, err.Error()))\n\t\t\tcontinue\n\t\t}\n\t\tif isExecutionScopePlugin(pd) {\n\t\t\tgaugeConnectionHandler, err := newGaugeConnectionHandler(0, nil)\n\t\t\tif err != nil {\n\t\t\t\twarnings = append(warnings, err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tenvProperties[pluginConnectionPortEnv] = strconv.Itoa(gaugeConnectionHandler.connectionPortNumber())\n\t\t\tsetEnvForPlugin(executionScope, pd, manifest, envProperties)\n\n\t\t\tpluginCmd, err := startPlugin(pd, executionScope, false)\n\t\t\tif err != nil {\n\t\t\t\twarnings = append(warnings, fmt.Sprintf(\"Error starting plugin %s %s. %s\", pd.Name, pd.Version, err.Error()))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpluginConnection, err := gaugeConnectionHandler.acceptConnection(pluginConnectionTimeout)\n\t\t\tif err != nil {\n\t\t\t\twarnings = append(warnings, fmt.Sprintf(\"Error starting plugin %s %s. Failed to connect to plugin. %s\", pd.Name, pd.Version, err.Error()))\n\t\t\t\tpluginCmd.Process.Kill()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\thandler.addPlugin(pluginId, &plugin{connection: pluginConnection, pluginCmd: pluginCmd, descriptor: pd})\n\t\t}\n\n\t}\n\treturn handler, warnings\n}\n\nfunc isExecutionScopePlugin(pd *pluginDescriptor) bool {\n\tfor _, scope := range pd.Scope {\n\t\tif strings.ToLower(scope) == executionScope {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (handler *pluginHandler) addPlugin(pluginId string, pluginToAdd *plugin) {\n\tif handler.pluginsMap == nil {\n\t\thandler.pluginsMap = make(map[string]*plugin)\n\t}\n\thandler.pluginsMap[pluginId] = pluginToAdd\n}\n\nfunc (handler *pluginHandler) removePlugin(pluginId string) {\n\tdelete(handler.pluginsMap, pluginId)\n}\n\nfunc (handler *pluginHandler) notifyPlugins(message *Message) {\n\tfor id, plugin := range handler.pluginsMap {\n\t\terr := plugin.sendMessage(message)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"[Warinig] Unable to connect to plugin %s %s. %s\\n\", plugin.descriptor.Name, plugin.descriptor.Version, err.Error())\n\t\t\thandler.killPlugin(id)\n\t\t}\n\t}\n}\n\nfunc (handler *pluginHandler) killPlugin(pluginId string) {\n\tplugin := handler.pluginsMap[pluginId]\n\tfmt.Printf(\"Killing Plugin %s %s\\n\", plugin.descriptor.Name, plugin.descriptor.Version)\n\terr := plugin.pluginCmd.Process.Kill()\n\tif err != nil {\n\t\tfmt.Printf(\"[Error] Failed to kill plugin %s %s. %s\\n\", plugin.descriptor.Name, plugin.descriptor.Version, err.Error())\n\t}\n\thandler.removePlugin(pluginId)\n}\n\nfunc (handler *pluginHandler) gracefullyKillPlugins() {\n\tvar wg sync.WaitGroup\n\tfor _, plugin := range handler.pluginsMap {\n\t\twg.Add(1)\n\t\tgo plugin.kill(&wg)\n\t}\n\twg.Wait()\n}\n\nfunc (plugin *plugin) sendMessage(message *Message) error {\n\tmessageId := common.GetUniqueId()\n\tmessage.MessageId = &messageId\n\tmessageBytes, err := proto.Marshal(message)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = write(plugin.connection, messageBytes)\n\tif err != nil {\n\t\treturn errors.New(fmt.Sprintf(\"[Warning] Failed to send message to plugin: %d  %s\", plugin.descriptor.Id, err.Error()))\n\t}\n\treturn nil\n}\n<commit_msg>Fixing warning message<commit_after>package main\n\nimport (\n\t\"code.google.com\/p\/goprotobuf\/proto\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/getgauge\/common\"\n\t\"net\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\texecutionScope          = \"execution\"\n\tpluginConnectionTimeout = time.Second * 10\n\tsetupScope              = \"setup\"\n\tpluginConnectionPortEnv = \"plugin_connection_port\"\n)\n\ntype pluginDescriptor struct {\n\tId          string\n\tVersion     string\n\tName        string\n\tDescription string\n\tCommand     struct {\n\t\tWindows []string\n\t\tLinux   []string\n\t\tDarwin  []string\n\t}\n\tScope      []string\n\tpluginPath string\n}\n\ntype pluginHandler struct {\n\tpluginsMap map[string]*plugin\n}\n\ntype plugin struct {\n\tconnection net.Conn\n\tpluginCmd  *exec.Cmd\n\tdescriptor *pluginDescriptor\n}\n\nfunc (plugin *plugin) kill(wg *sync.WaitGroup) error {\n\tdefer wg.Done()\n\tif plugin.isStillRunning() {\n\n\t\texited := make(chan bool, 1)\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tif plugin.isStillRunning() {\n\t\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\t} else {\n\t\t\t\t\texited <- true\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tselect {\n\t\tcase done := <-exited:\n\t\t\tif done {\n\t\t\t\tfmt.Println(fmt.Sprintf(\"Plugin [%s] with pid [%d] has exited\", plugin.descriptor.Name, plugin.pluginCmd.Process.Pid))\n\t\t\t}\n\t\tcase <-time.After(pluginConnectionTimeout):\n\t\t\tfmt.Println(fmt.Sprintf(\"Plugin [%s] with pid [%d] did not exit after %.2f seconds. Forcefully killing it.\", plugin.descriptor.Name, plugin.pluginCmd.Process.Pid, pluginConnectionTimeout.Seconds()))\n\t\t\treturn plugin.pluginCmd.Process.Kill()\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (plugin *plugin) isStillRunning() bool {\n\treturn plugin.pluginCmd.ProcessState == nil || !plugin.pluginCmd.ProcessState.Exited()\n}\n\nfunc isPluginInstalled(pluginName, pluginVersion string) bool {\n\tpluginsInstallDir, err := common.GetPluginsInstallDir(pluginName)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tthisPluginDir := path.Join(pluginsInstallDir, pluginName)\n\tif !common.DirExists(thisPluginDir) {\n\t\treturn false\n\t}\n\n\tif pluginVersion != \"\" {\n\t\tpluginJson := path.Join(thisPluginDir, pluginVersion, common.PluginJsonFile)\n\t\tif common.FileExists(pluginJson) {\n\t\t\treturn true\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\treturn true\n\t}\n}\n\nfunc getPluginJsonPath(pluginName, version string) (string, error) {\n\tif !isPluginInstalled(pluginName, version) {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"%s %s is not installed\", pluginName, version))\n\t}\n\n\tpluginInstallDir, err := common.GetPluginInstallDir(pluginName, \"\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(pluginInstallDir, common.PluginJsonFile), nil\n}\n\nfunc getPluginDescriptor(pluginId, pluginVersion string) (*pluginDescriptor, error) {\n\tpluginJson, err := getPluginJsonPath(pluginId, pluginVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpluginJsonContents, err := common.ReadFileContents(pluginJson)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar pd pluginDescriptor\n\tif err = json.Unmarshal([]byte(pluginJsonContents), &pd); err != nil {\n\t\treturn nil, errors.New(fmt.Sprintf(\"%s: %s\", pluginJson, err.Error()))\n\t}\n\tpd.pluginPath = filepath.Dir(pluginJson)\n\n\treturn &pd, nil\n}\n\nfunc startPlugin(pd *pluginDescriptor, action string, wait bool) (*exec.Cmd, error) {\n\tcommand := []string{}\n\tswitch runtime.GOOS {\n\tcase \"windows\":\n\t\tcommand = pd.Command.Windows\n\t\tbreak\n\tcase \"darwin\":\n\t\tcommand = pd.Command.Darwin\n\t\tbreak\n\tdefault:\n\t\tcommand = pd.Command.Linux\n\t\tbreak\n\t}\n\n\tpluginConsoleWriter := &pluginConsoleWriter{pluginName: pd.Name}\n\tcmd, err := common.ExecuteCommand(command, pd.pluginPath, pluginConsoleWriter, pluginConsoleWriter)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif wait {\n\t\treturn cmd, cmd.Wait()\n\t} else {\n\t\tgo func() {\n\t\t\tcmd.Wait()\n\t\t}()\n\t}\n\n\treturn cmd, nil\n}\n\nfunc setEnvForPlugin(action string, pd *pluginDescriptor, manifest *manifest, pluginEnvVars map[string]string) error {\n\tpluginEnvVars[fmt.Sprintf(\"%s_action\", pd.Id)] = action\n\tpluginEnvVars[\"test_language\"] = manifest.Language\n\tif err := setEnvironmentProperties(pluginEnvVars); err != nil {\n\t\treturn err\n\t}\n\tif err := setCurrentProjectEnvVariable(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc setEnvironmentProperties(properties map[string]string) error {\n\tfor k, v := range properties {\n\t\tif err := common.SetEnvVariable(k, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc addPluginToTheProject(pluginName string, pluginArgs map[string]string, manifest *manifest) error {\n\tpd, err := getPluginDescriptor(pluginName, pluginArgs[\"version\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif isPluginAdded(manifest, pd) {\n\t\treturn errors.New(\"Plugin \" + pd.Name + \" is already added\")\n\t}\n\taction := setupScope\n\tif err := setEnvForPlugin(action, pd, manifest, pluginArgs); err != nil {\n\t\treturn err\n\t}\n\tif _, err := startPlugin(pd, action, true); err != nil {\n\t\treturn err\n\t}\n\tmanifest.Plugins = append(manifest.Plugins, pd.Id)\n\treturn manifest.save()\n}\n\nfunc isPluginAdded(manifest *manifest, descriptor *pluginDescriptor) bool {\n\tfor _, pluginId := range manifest.Plugins {\n\t\tif pluginId == descriptor.Id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc startPluginsForExecution(manifest *manifest) (*pluginHandler, []string) {\n\twarnings := make([]string, 0)\n\thandler := &pluginHandler{}\n\tenvProperties := make(map[string]string)\n\n\tfor _, pluginId := range manifest.Plugins {\n\t\tpd, err := getPluginDescriptor(pluginId, \"\")\n\t\tif err != nil {\n\t\t\twarnings = append(warnings, fmt.Sprintf(\"Error starting plugin %s. Failed to get plugin.json. %s\", pluginId, err.Error()))\n\t\t\tcontinue\n\t\t}\n\t\tif isExecutionScopePlugin(pd) {\n\t\t\tgaugeConnectionHandler, err := newGaugeConnectionHandler(0, nil)\n\t\t\tif err != nil {\n\t\t\t\twarnings = append(warnings, err.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tenvProperties[pluginConnectionPortEnv] = strconv.Itoa(gaugeConnectionHandler.connectionPortNumber())\n\t\t\tsetEnvForPlugin(executionScope, pd, manifest, envProperties)\n\n\t\t\tpluginCmd, err := startPlugin(pd, executionScope, false)\n\t\t\tif err != nil {\n\t\t\t\twarnings = append(warnings, fmt.Sprintf(\"Error starting plugin %s %s. %s\", pd.Name, pd.Version, err.Error()))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpluginConnection, err := gaugeConnectionHandler.acceptConnection(pluginConnectionTimeout)\n\t\t\tif err != nil {\n\t\t\t\twarnings = append(warnings, fmt.Sprintf(\"Error starting plugin %s %s. Failed to connect to plugin. %s\", pd.Name, pd.Version, err.Error()))\n\t\t\t\tpluginCmd.Process.Kill()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\thandler.addPlugin(pluginId, &plugin{connection: pluginConnection, pluginCmd: pluginCmd, descriptor: pd})\n\t\t}\n\n\t}\n\treturn handler, warnings\n}\n\nfunc isExecutionScopePlugin(pd *pluginDescriptor) bool {\n\tfor _, scope := range pd.Scope {\n\t\tif strings.ToLower(scope) == executionScope {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (handler *pluginHandler) addPlugin(pluginId string, pluginToAdd *plugin) {\n\tif handler.pluginsMap == nil {\n\t\thandler.pluginsMap = make(map[string]*plugin)\n\t}\n\thandler.pluginsMap[pluginId] = pluginToAdd\n}\n\nfunc (handler *pluginHandler) removePlugin(pluginId string) {\n\tdelete(handler.pluginsMap, pluginId)\n}\n\nfunc (handler *pluginHandler) notifyPlugins(message *Message) {\n\tfor id, plugin := range handler.pluginsMap {\n\t\terr := plugin.sendMessage(message)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"[Warinig] Unable to connect to plugin %s %s. %s\\n\", plugin.descriptor.Name, plugin.descriptor.Version, err.Error())\n\t\t\thandler.killPlugin(id)\n\t\t}\n\t}\n}\n\nfunc (handler *pluginHandler) killPlugin(pluginId string) {\n\tplugin := handler.pluginsMap[pluginId]\n\tfmt.Printf(\"Killing Plugin %s %s\\n\", plugin.descriptor.Name, plugin.descriptor.Version)\n\terr := plugin.pluginCmd.Process.Kill()\n\tif err != nil {\n\t\tfmt.Printf(\"[Error] Failed to kill plugin %s %s. %s\\n\", plugin.descriptor.Name, plugin.descriptor.Version, err.Error())\n\t}\n\thandler.removePlugin(pluginId)\n}\n\nfunc (handler *pluginHandler) gracefullyKillPlugins() {\n\tvar wg sync.WaitGroup\n\tfor _, plugin := range handler.pluginsMap {\n\t\twg.Add(1)\n\t\tgo plugin.kill(&wg)\n\t}\n\twg.Wait()\n}\n\nfunc (plugin *plugin) sendMessage(message *Message) error {\n\tmessageId := common.GetUniqueId()\n\tmessage.MessageId = &messageId\n\tmessageBytes, err := proto.Marshal(message)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = write(plugin.connection, messageBytes)\n\tif err != nil {\n\t\treturn errors.New(fmt.Sprintf(\"[Warning] Failed to send message to plugin: %d  %s\", plugin.descriptor.Id, err.Error()))\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n)\n\ntype UbootEnvCommand struct {\n\tEnvCmd string\n}\n\ntype UbootVars map[string]string\n\ntype Runner interface {\n\tRun(string, ...string) *exec.Cmd\n}\n\ntype RealRunner struct{}\n\nvar (\n\trunner Runner\n\tLog    *log.Logger\n)\n\nfunc init() {\n\trunner = RealRunner{}\n\tLog = log.New(os.Stdout, \"MESSAGE:\", log.Ldate|log.Ltime|log.Lshortfile)\n}\n\n\/\/ the real runner for the actual program, actually execs the command\nfunc (r RealRunner) Run(command string, args ...string) *exec.Cmd {\n\treturn exec.Command(command, args...)\n}\n\nfunc (c *UbootEnvCommand) Command(params ...string) (UbootVars, error) {\n\n\tcmd := runner.Run(c.EnvCmd, params...)\n\tcmdReader, err := cmd.StdoutPipe()\n\n\tif err != nil {\n\t\tLog.Println(\"Error creating StdoutPipe:\", err)\n\t\treturn nil, err\n\t}\n\n\tscanner := bufio.NewScanner(cmdReader)\n\n\terr = cmd.Start()\n\tif err != nil {\n\t\tLog.Println(\"There was an error getting or setting U-Boot env\")\n\t\treturn nil, err\n\t}\n\n\tvar env_variables = make(UbootVars)\n\n\tfor scanner.Scan() {\n\t\tLog.Println(\"Have U-Boot variable:\", scanner.Text())\n\t\tsplited_line := strings.Split(scanner.Text(), \"=\")\n\n\t\t\/\/we are having empty line (usually at the end of output)\n\t\tif scanner.Text() == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/we have some malformed data or Warning\/Error\n\t\tif len(splited_line) != 2 {\n\t\t\tLog.Println(\"U-Boot variable malformed or error occured\")\n\t\t\treturn nil, errors.New(\"Invalid U-Boot variable or error: \" + scanner.Text())\n\t\t}\n\n\t\tenv_variables[splited_line[0]] = splited_line[1]\n\t}\n\n\terr = cmd.Wait()\n\tif err != nil {\n\t\tLog.Println(\"U-Boot env command returned non zero status\")\n\t\treturn nil, err\n\t}\n\n\tif len(env_variables) > 0 {\n\t\tLog.Println(\"List of U-Boot variables:\", env_variables)\n\t}\n\n\treturn env_variables, err\n}\n\nfunc GetBootEnv(var_name ...string) (UbootVars, error) {\n\tget_env := UbootEnvCommand{\"fw_printenv\"}\n\treturn get_env.Command(var_name...)\n}\n\nfunc SetBootEnv(var_name string, value string) error {\n\n\tset_env := UbootEnvCommand{\"fw_setenv\"}\n\n\tif _, err := set_env.Command(var_name, value); err != nil {\n\t\tLog.Println(\"Error setting U-Boot variable:\", err)\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>Change name of local function to be not exported from module.<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n)\n\ntype UbootEnvCommand struct {\n\tEnvCmd string\n}\n\ntype UbootVars map[string]string\n\ntype Runner interface {\n\tRun(string, ...string) *exec.Cmd\n}\n\ntype RealRunner struct{}\n\nvar (\n\trunner Runner\n\tLog    *log.Logger\n)\n\nfunc init() {\n\trunner = RealRunner{}\n\tLog = log.New(os.Stdout, \"BOOT_ENV:\", log.Ldate|log.Ltime|log.Lshortfile)\n}\n\n\/\/ the real runner for the actual program, actually execs the command\nfunc (r RealRunner) Run(command string, args ...string) *exec.Cmd {\n\treturn exec.Command(command, args...)\n}\n\nfunc (c *UbootEnvCommand) command(params ...string) (UbootVars, error) {\n\n\tcmd := runner.Run(c.EnvCmd, params...)\n\tcmdReader, err := cmd.StdoutPipe()\n\n\tif err != nil {\n\t\tLog.Println(\"Error creating StdoutPipe:\", err)\n\t\treturn nil, err\n\t}\n\n\tscanner := bufio.NewScanner(cmdReader)\n\n\terr = cmd.Start()\n\tif err != nil {\n\t\tLog.Println(\"There was an error getting or setting U-Boot env\")\n\t\treturn nil, err\n\t}\n\n\tvar env_variables = make(UbootVars)\n\n\tfor scanner.Scan() {\n\t\tLog.Println(\"Have U-Boot variable:\", scanner.Text())\n\t\tsplited_line := strings.Split(scanner.Text(), \"=\")\n\n\t\t\/\/we are having empty line (usually at the end of output)\n\t\tif scanner.Text() == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/we have some malformed data or Warning\/Error\n\t\tif len(splited_line) != 2 {\n\t\t\tLog.Println(\"U-Boot variable malformed or error occured\")\n\t\t\treturn nil, errors.New(\"Invalid U-Boot variable or error: \" + scanner.Text())\n\t\t}\n\n\t\tenv_variables[splited_line[0]] = splited_line[1]\n\t}\n\n\terr = cmd.Wait()\n\tif err != nil {\n\t\tLog.Println(\"U-Boot env command returned non zero status\")\n\t\treturn nil, err\n\t}\n\n\tif len(env_variables) > 0 {\n\t\tLog.Println(\"List of U-Boot variables:\", env_variables)\n\t}\n\n\treturn env_variables, err\n}\n\nfunc GetBootEnv(var_name ...string) (UbootVars, error) {\n\tget_env := UbootEnvCommand{\"fw_printenv\"}\n\treturn get_env.command(var_name...)\n}\n\nfunc SetBootEnv(var_name string, value string) error {\n\n\tset_env := UbootEnvCommand{\"fw_setenv\"}\n\n\tif _, err := set_env.command(var_name, value); err != nil {\n\t\tLog.Println(\"Error setting U-Boot variable:\", err)\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Plan 9 environment variables.\n\npackage syscall\n\nimport (\n\t\"errors\"\n\t\"sync\"\n)\n\nvar (\n\t\/\/ envOnce guards copyenv, which populates env, envi and envs.\n\tenvOnce sync.Once\n\n\t\/\/ envLock guards env, envi and envs.\n\tenvLock sync.RWMutex\n\n\t\/\/ env maps from an environment variable to its value.\n\t\/\/ TODO: remove this? golang.org\/issue\/8849\n\tenv = make(map[string]string)\n\n\t\/\/ envi maps from an environment variable to its index in envs.\n\t\/\/ TODO: remove this? golang.org\/issue\/8849\n\tenvi = make(map[string]int)\n\n\t\/\/ envs contains elements of env in the form \"key=value\".\n\t\/\/ empty strings mean deleted.\n\tenvs []string\n\n\terrZeroLengthKey = errors.New(\"zero length key\")\n\terrShortWrite    = errors.New(\"i\/o count too small\")\n)\n\nfunc readenv(key string) (string, error) {\n\tfd, err := Open(\"\/env\/\"+key, O_RDONLY)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer Close(fd)\n\tl, _ := Seek(fd, 0, 2)\n\tSeek(fd, 0, 0)\n\tbuf := make([]byte, l)\n\tn, err := Read(fd, buf)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif n > 0 && buf[n-1] == 0 {\n\t\tbuf = buf[:n-1]\n\t}\n\treturn string(buf), nil\n}\n\nfunc writeenv(key, value string) error {\n\tfd, err := Create(\"\/env\/\"+key, O_RDWR, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer Close(fd)\n\tb := []byte(value)\n\tn, err := Write(fd, b)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n != len(b) {\n\t\treturn errShortWrite\n\t}\n\treturn nil\n}\n\nfunc copyenv() {\n\tfd, err := Open(\"\/env\", O_RDONLY)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer Close(fd)\n\tfiles, err := readdirnames(fd)\n\tif err != nil {\n\t\treturn\n\t}\n\tenvs = make([]string, len(files))\n\ti := 0\n\tfor _, key := range files {\n\t\tv, err := readenv(key)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tenv[key] = v\n\t\tenvs[i] = key + \"=\" + v\n\t\tenvi[key] = i\n\t\ti++\n\t}\n}\n\nfunc Getenv(key string) (value string, found bool) {\n\tif len(key) == 0 {\n\t\treturn \"\", false\n\t}\n\n\tenvLock.RLock()\n\tdefer envLock.RUnlock()\n\n\tif v, ok := env[key]; ok {\n\t\treturn v, true\n\t}\n\tv, err := readenv(key)\n\tif err != nil {\n\t\treturn \"\", false\n\t}\n\tenv[key] = v\n\tenvs = append(envs, key+\"=\"+v)\n\treturn v, true\n}\n\nfunc Setenv(key, value string) error {\n\tif len(key) == 0 {\n\t\treturn errZeroLengthKey\n\t}\n\n\tenvLock.Lock()\n\tdefer envLock.Unlock()\n\n\terr := writeenv(key, value)\n\tif err != nil {\n\t\treturn err\n\t}\n\tenv[key] = value\n\tenvs = append(envs, key+\"=\"+value)\n\treturn nil\n}\n\nfunc Clearenv() {\n\tenvLock.Lock()\n\tdefer envLock.Unlock()\n\n\tenv = make(map[string]string)\n\tenvi = make(map[string]int)\n\tenvs = []string{}\n\tRawSyscall(SYS_RFORK, RFCENVG, 0, 0)\n}\n\nfunc Unsetenv(key string) error {\n\tif len(key) == 0 {\n\t\treturn errZeroLengthKey\n\t}\n\n\tenvLock.Lock()\n\tdefer envLock.Unlock()\n\n\tRemove(\"\/env\/\" + key)\n\n\tif i, ok := envi[key]; ok {\n\t\tdelete(env, key)\n\t\tdelete(envi, key)\n\t\tenvs[i] = \"\"\n\t}\n\treturn nil\n}\n\nfunc Environ() []string {\n\tenvLock.RLock()\n\tdefer envLock.RUnlock()\n\n\tenvOnce.Do(copyenv)\n\tret := make([]string, 0, len(envs))\n\tfor _, pair := range envs {\n\t\tif pair != \"\" {\n\t\t\tret = append(ret, pair)\n\t\t}\n\t}\n\treturn ret\n}\n<commit_msg>syscall: fix Setenv for plan 9<commit_after>\/\/ Copyright 2011 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Plan 9 environment variables.\n\npackage syscall\n\nimport (\n\t\"errors\"\n\t\"sync\"\n)\n\nvar (\n\t\/\/ envOnce guards copyenv, which populates env, envi and envs.\n\tenvOnce sync.Once\n\n\t\/\/ envLock guards env, envi and envs.\n\tenvLock sync.RWMutex\n\n\t\/\/ env maps from an environment variable to its value.\n\t\/\/ TODO: remove this? golang.org\/issue\/8849\n\tenv = make(map[string]string)\n\n\t\/\/ envi maps from an environment variable to its index in envs.\n\t\/\/ TODO: remove this? golang.org\/issue\/8849\n\tenvi = make(map[string]int)\n\n\t\/\/ envs contains elements of env in the form \"key=value\".\n\t\/\/ empty strings mean deleted.\n\tenvs []string\n\n\terrZeroLengthKey = errors.New(\"zero length key\")\n\terrShortWrite    = errors.New(\"i\/o count too small\")\n)\n\nfunc readenv(key string) (string, error) {\n\tfd, err := Open(\"\/env\/\"+key, O_RDONLY)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer Close(fd)\n\tl, _ := Seek(fd, 0, 2)\n\tSeek(fd, 0, 0)\n\tbuf := make([]byte, l)\n\tn, err := Read(fd, buf)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif n > 0 && buf[n-1] == 0 {\n\t\tbuf = buf[:n-1]\n\t}\n\treturn string(buf), nil\n}\n\nfunc writeenv(key, value string) error {\n\tfd, err := Create(\"\/env\/\"+key, O_RDWR, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer Close(fd)\n\tb := []byte(value)\n\tn, err := Write(fd, b)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n != len(b) {\n\t\treturn errShortWrite\n\t}\n\treturn nil\n}\n\nfunc copyenv() {\n\tfd, err := Open(\"\/env\", O_RDONLY)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer Close(fd)\n\tfiles, err := readdirnames(fd)\n\tif err != nil {\n\t\treturn\n\t}\n\tenvs = make([]string, len(files))\n\ti := 0\n\tfor _, key := range files {\n\t\tv, err := readenv(key)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tenv[key] = v\n\t\tenvs[i] = key + \"=\" + v\n\t\tenvi[key] = i\n\t\ti++\n\t}\n}\n\nfunc Getenv(key string) (value string, found bool) {\n\tif len(key) == 0 {\n\t\treturn \"\", false\n\t}\n\n\tenvLock.RLock()\n\tdefer envLock.RUnlock()\n\n\tif v, ok := env[key]; ok {\n\t\treturn v, true\n\t}\n\tv, err := readenv(key)\n\tif err != nil {\n\t\treturn \"\", false\n\t}\n\tenv[key] = v\n\tenvs = append(envs, key+\"=\"+v)\n\treturn v, true\n}\n\nfunc Setenv(key, value string) error {\n\tif len(key) == 0 {\n\t\treturn errZeroLengthKey\n\t}\n\n\tenvLock.Lock()\n\tdefer envLock.Unlock()\n\n\terr := writeenv(key, value)\n\tif err != nil {\n\t\treturn err\n\t}\n\tenv[key] = value\n\tenvs = append(envs, key+\"=\"+value)\n\tenvi[key] = len(envs) - 1\n\treturn nil\n}\n\nfunc Clearenv() {\n\tenvLock.Lock()\n\tdefer envLock.Unlock()\n\n\tenv = make(map[string]string)\n\tenvi = make(map[string]int)\n\tenvs = []string{}\n\tRawSyscall(SYS_RFORK, RFCENVG, 0, 0)\n}\n\nfunc Unsetenv(key string) error {\n\tif len(key) == 0 {\n\t\treturn errZeroLengthKey\n\t}\n\n\tenvLock.Lock()\n\tdefer envLock.Unlock()\n\n\tRemove(\"\/env\/\" + key)\n\n\tif i, ok := envi[key]; ok {\n\t\tdelete(env, key)\n\t\tdelete(envi, key)\n\t\tenvs[i] = \"\"\n\t}\n\treturn nil\n}\n\nfunc Environ() []string {\n\tenvLock.RLock()\n\tdefer envLock.RUnlock()\n\n\tenvOnce.Do(copyenv)\n\tret := make([]string, 0, len(envs))\n\tfor _, pair := range envs {\n\t\tif pair != \"\" {\n\t\t\tret = append(ret, pair)\n\t\t}\n\t}\n\treturn ret\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\n\t\"google.golang.org\/grpc\"\n\n\t\"github.com\/afg984\/thegame\/server\/go\/thegame\/pb\"\n)\n\nvar listen string\n\nfunc init() {\n\tflag.StringVar(&listen, \"listen\", \":50051\", \"[host]:port to listen to\")\n}\n\ntype server struct {\n\tarena          *Arena\n\tspectatorToken string\n\tadminToken     string\n}\n\nfunc newServer() *server {\n\ts := &server{\n\t\tarena:          NewArena(),\n\t\tspectatorToken: os.Getenv(\"THEGAME_SPECTATOR_TOKEN\"),\n\t\tadminToken:     os.Getenv(\"THEGAME_ADMIN_TOKEN\"),\n\t}\n\tif s.adminToken == \"\" {\n\t\tlog.Println(\"Environment variable THEGAME_ADMIN_TOKEN is not set or empty,\" +\n\t\t\t\" admin command is disabled\")\n\t}\n\treturn s\n}\n\nfunc (s *server) Game(stream pb.TheGame_GameServer) error {\n\tlog.Println(\"New client connected\")\n\tjoin, err := stream.Recv()\n\tif err != nil {\n\t\tlog.Printf(\"join initialization failed: %v\", err)\n\t\treturn err\n\t}\n\telement := s.arena.Join(join.Name)\n\thero := element.Value.(*Hero)\n\tgo func() {\n\t\tupdates := hero.UpdateChan\n\t\tfor gameState := range updates {\n\t\t\terr := stream.Send(gameState)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"cannot send gameState to %v: %v\", hero, err)\n\t\t\t}\n\t\t}\n\t}()\n\tdefer s.arena.Quit(element)\n\tfor {\n\t\tcontrols, err := stream.Recv()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"cannot receive controls from %v: %v\", hero, err)\n\t\t\treturn err\n\t\t}\n\t\ts.arena.controlChan <- HeroControls{\n\t\t\tHero:     hero,\n\t\t\tControls: controls,\n\t\t}\n\t}\n}\n\nfunc (s *server) View(view *pb.ViewRequest, stream pb.TheGame_ViewServer) error {\n\tif s.spectatorToken != view.Token {\n\t\treturn errors.New(\"Invalid token\")\n\t}\n\tch := make(chan *pb.GameState, 16)\n\ts.arena.viewChan <- ch\n\tfor gs := range ch {\n\t\terr := stream.Send(gs)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"cannot send gameState to audience: %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *server) Admin(ctx context.Context, command *pb.Command) (*pb.CommandResponse, error) {\n\tif s.adminToken == \"\" {\n\t\treturn nil, errors.New(\"Admin disabled\")\n\t}\n\tif command.Token != s.adminToken {\n\t\treturn nil, errors.New(\"Invalid token\")\n\t}\n\tif command.Resume {\n\t\t<-s.arena.Command(CommandResume)\n\t} else if command.Pause {\n\t\t<-s.arena.Command(CommandPause)\n\t} else if command.Tick {\n\t\t<-s.arena.Command(CommandTick)\n\t} else if command.GameReset {\n\t\t<-s.arena.Command(CommandReset)\n\t} else if command.WaitForControls {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tif err := ctx.Err(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase <-s.arena.AllControlsReceived():\n\t\t}\n\t}\n\treturn &pb.CommandResponse{}, nil\n}\n\nfunc main() {\n\tflag.Parse()\n\tlis, err := net.Listen(\"tcp\", listen)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\tport := lis.Addr().(*net.TCPAddr).Port\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlog.SetPrefix(fmt.Sprintf(\"[%s:%d] \", hostname, port))\n\n\ts := grpc.NewServer()\n\tgs := newServer()\n\tpb.RegisterTheGameServer(s, gs)\n\tlog.Println(\"listening on\", listen)\n\tgo func() {\n\t\tfor {\n\t\t\tvar line string\n\t\t\t_, err := fmt.Scanln(&line)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"Failed to read line: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tswitch line {\n\t\t\tcase \"p\":\n\t\t\t\tgs.arena.Command(CommandPause)\n\t\t\tcase \"r\":\n\t\t\t\tgs.arena.Command(CommandResume)\n\t\t\tcase \"t\":\n\t\t\t\tgs.arena.Command(CommandTick)\n\t\t\tcase \"reset\":\n\t\t\t\tgs.arena.Command(CommandReset)\n\t\t\tdefault:\n\t\t\t\tfmt.Printf(\"Unknown command: %q\\n\", line)\n\t\t\t}\n\t\t}\n\t}()\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n}\n<commit_msg>fmt -> log<commit_after>package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\n\t\"google.golang.org\/grpc\"\n\n\t\"github.com\/afg984\/thegame\/server\/go\/thegame\/pb\"\n)\n\nvar listen string\n\nfunc init() {\n\tflag.StringVar(&listen, \"listen\", \":50051\", \"[host]:port to listen to\")\n}\n\ntype server struct {\n\tarena          *Arena\n\tspectatorToken string\n\tadminToken     string\n}\n\nfunc newServer() *server {\n\ts := &server{\n\t\tarena:          NewArena(),\n\t\tspectatorToken: os.Getenv(\"THEGAME_SPECTATOR_TOKEN\"),\n\t\tadminToken:     os.Getenv(\"THEGAME_ADMIN_TOKEN\"),\n\t}\n\tif s.adminToken == \"\" {\n\t\tlog.Println(\"Environment variable THEGAME_ADMIN_TOKEN is not set or empty,\" +\n\t\t\t\" admin command is disabled\")\n\t}\n\treturn s\n}\n\nfunc (s *server) Game(stream pb.TheGame_GameServer) error {\n\tlog.Println(\"New client connected\")\n\tjoin, err := stream.Recv()\n\tif err != nil {\n\t\tlog.Printf(\"join initialization failed: %v\", err)\n\t\treturn err\n\t}\n\telement := s.arena.Join(join.Name)\n\thero := element.Value.(*Hero)\n\tgo func() {\n\t\tupdates := hero.UpdateChan\n\t\tfor gameState := range updates {\n\t\t\terr := stream.Send(gameState)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"cannot send gameState to %v: %v\", hero, err)\n\t\t\t}\n\t\t}\n\t}()\n\tdefer s.arena.Quit(element)\n\tfor {\n\t\tcontrols, err := stream.Recv()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"cannot receive controls from %v: %v\", hero, err)\n\t\t\treturn err\n\t\t}\n\t\ts.arena.controlChan <- HeroControls{\n\t\t\tHero:     hero,\n\t\t\tControls: controls,\n\t\t}\n\t}\n}\n\nfunc (s *server) View(view *pb.ViewRequest, stream pb.TheGame_ViewServer) error {\n\tif s.spectatorToken != view.Token {\n\t\treturn errors.New(\"Invalid token\")\n\t}\n\tch := make(chan *pb.GameState, 16)\n\ts.arena.viewChan <- ch\n\tfor gs := range ch {\n\t\terr := stream.Send(gs)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"cannot send gameState to audience: %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *server) Admin(ctx context.Context, command *pb.Command) (*pb.CommandResponse, error) {\n\tif s.adminToken == \"\" {\n\t\treturn nil, errors.New(\"Admin disabled\")\n\t}\n\tif command.Token != s.adminToken {\n\t\treturn nil, errors.New(\"Invalid token\")\n\t}\n\tif command.Resume {\n\t\t<-s.arena.Command(CommandResume)\n\t} else if command.Pause {\n\t\t<-s.arena.Command(CommandPause)\n\t} else if command.Tick {\n\t\t<-s.arena.Command(CommandTick)\n\t} else if command.GameReset {\n\t\t<-s.arena.Command(CommandReset)\n\t} else if command.WaitForControls {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tif err := ctx.Err(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\tcase <-s.arena.AllControlsReceived():\n\t\t}\n\t}\n\treturn &pb.CommandResponse{}, nil\n}\n\nfunc main() {\n\tflag.Parse()\n\tlis, err := net.Listen(\"tcp\", listen)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\", err)\n\t}\n\n\tport := lis.Addr().(*net.TCPAddr).Port\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlog.SetPrefix(fmt.Sprintf(\"[%s:%d] \", hostname, port))\n\n\ts := grpc.NewServer()\n\tgs := newServer()\n\tpb.RegisterTheGameServer(s, gs)\n\tlog.Println(\"listening on\", listen)\n\tgo func() {\n\t\tfor {\n\t\t\tvar line string\n\t\t\t_, err := fmt.Scanln(&line)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Failed to read line: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tswitch line {\n\t\t\tcase \"p\":\n\t\t\t\tgs.arena.Command(CommandPause)\n\t\t\tcase \"r\":\n\t\t\t\tgs.arena.Command(CommandResume)\n\t\t\tcase \"t\":\n\t\t\t\tgs.arena.Command(CommandTick)\n\t\t\tcase \"reset\":\n\t\t\t\tgs.arena.Command(CommandReset)\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"Unknown command: %q\\n\", line)\n\t\t\t}\n\t\t}\n\t}()\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Http provider\npackage http\n\nimport (\n\t\"fmt\"\n\t\"github.com\/pierrre\/imageserver\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n)\n\nvar contentTypeRegexp, _ = regexp.Compile(\"^image\/(.+)$\")\n\n\/\/ Returns image from an http source\n\/\/\n\/\/ If the source is not an url, the string representation of the source will be used to create one.\n\/\/\n\/\/ Returns an error if the http status code is not 200 (OK).\n\/\/\n\/\/ The image type is determined by the \"Content-Type\" header.\ntype HttpProvider struct {\n}\n\nfunc (provider *HttpProvider) Get(source interface{}, parameters imageserver.Parameters) (*imageserver.Image, error) {\n\tsourceUrl, err := provider.getSourceUrl(source)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponse, err := provider.request(sourceUrl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\tif err = provider.checkResponse(response); err != nil {\n\t\treturn nil, err\n\t}\n\timage, err := provider.createImage(response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn image, nil\n}\n\nfunc (provider *HttpProvider) getSourceUrl(source interface{}) (*url.URL, error) {\n\tsourceUrl, ok := source.(*url.URL)\n\tif !ok {\n\t\tvar err error\n\t\tsourceUrl, err = url.ParseRequestURI(fmt.Sprint(source))\n\t\tif err != nil {\n\t\t\treturn nil, imageserver.NewError(\"Invalid source url\")\n\t\t}\n\t}\n\tif sourceUrl.Scheme != \"http\" && sourceUrl.Scheme != \"https\" {\n\t\treturn nil, imageserver.NewError(\"Invalid source scheme\")\n\t}\n\treturn sourceUrl, nil\n}\n\nfunc (provider *HttpProvider) request(sourceUrl *url.URL) (*http.Response, error) {\n\t\/\/TODO optional http client\n\treturn http.Get(sourceUrl.String())\n}\n\nfunc (provider *HttpProvider) checkResponse(response *http.Response) error {\n\tif response.StatusCode != http.StatusOK {\n\t\treturn imageserver.NewError(fmt.Sprintf(\"Error %d while downloading source\", response.StatusCode))\n\t}\n\treturn nil\n}\n\nfunc (provider *HttpProvider) createImage(response *http.Response) (*imageserver.Image, error) {\n\timage := &imageserver.Image{}\n\tprovider.parseType(response, image)\n\tif err := provider.parseData(response, image); err != nil {\n\t\treturn nil, err\n\t}\n\treturn image, nil\n}\n\nfunc (provider *HttpProvider) parseType(response *http.Response, image *imageserver.Image) {\n\tcontentType := response.Header.Get(\"Content-Type\")\n\tif len(contentType) == 0 {\n\t\treturn\n\t}\n\tmatches := contentTypeRegexp.FindStringSubmatch(contentType)\n\tif matches == nil || len(matches) != 2 {\n\t\treturn\n\t}\n\timage.Type = matches[1]\n}\n\nfunc (provider *HttpProvider) parseData(response *http.Response, image *imageserver.Image) error {\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\timage.Data = data\n\treturn nil\n}\n<commit_msg>format code<commit_after>\/\/ Http provider\npackage http\n\nimport (\n\t\"fmt\"\n\t\"github.com\/pierrre\/imageserver\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n)\n\nvar contentTypeRegexp, _ = regexp.Compile(\"^image\/(.+)$\")\n\n\/\/ Returns image from an http source\n\/\/\n\/\/ If the source is not an url, the string representation of the source will be used to create one.\n\/\/\n\/\/ Returns an error if the http status code is not 200 (OK).\n\/\/\n\/\/ The image type is determined by the \"Content-Type\" header.\ntype HttpProvider struct {\n}\n\nfunc (provider *HttpProvider) Get(source interface{}, parameters imageserver.Parameters) (*imageserver.Image, error) {\n\tsourceUrl, err := provider.getSourceUrl(source)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse, err := provider.request(sourceUrl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\n\tif err = provider.checkResponse(response); err != nil {\n\t\treturn nil, err\n\t}\n\n\timage, err := provider.createImage(response)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn image, nil\n}\n\nfunc (provider *HttpProvider) getSourceUrl(source interface{}) (*url.URL, error) {\n\tsourceUrl, ok := source.(*url.URL)\n\tif !ok {\n\t\tvar err error\n\t\tsourceUrl, err = url.ParseRequestURI(fmt.Sprint(source))\n\t\tif err != nil {\n\t\t\treturn nil, imageserver.NewError(\"Invalid source url\")\n\t\t}\n\t}\n\n\tif sourceUrl.Scheme != \"http\" && sourceUrl.Scheme != \"https\" {\n\t\treturn nil, imageserver.NewError(\"Invalid source scheme\")\n\t}\n\n\treturn sourceUrl, nil\n}\n\nfunc (provider *HttpProvider) request(sourceUrl *url.URL) (*http.Response, error) {\n\t\/\/TODO optional http client\n\treturn http.Get(sourceUrl.String())\n}\n\nfunc (provider *HttpProvider) checkResponse(response *http.Response) error {\n\tif response.StatusCode != http.StatusOK {\n\t\treturn imageserver.NewError(fmt.Sprintf(\"Error %d while downloading source\", response.StatusCode))\n\t}\n\treturn nil\n}\n\nfunc (provider *HttpProvider) createImage(response *http.Response) (*imageserver.Image, error) {\n\timage := &imageserver.Image{}\n\n\tprovider.parseType(response, image)\n\n\tif err := provider.parseData(response, image); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn image, nil\n}\n\nfunc (provider *HttpProvider) parseType(response *http.Response, image *imageserver.Image) {\n\tcontentType := response.Header.Get(\"Content-Type\")\n\tif len(contentType) == 0 {\n\t\treturn\n\t}\n\n\tmatches := contentTypeRegexp.FindStringSubmatch(contentType)\n\tif matches == nil || len(matches) != 2 {\n\t\treturn\n\t}\n\n\timage.Type = matches[1]\n}\n\nfunc (provider *HttpProvider) parseData(response *http.Response, image *imageserver.Image) error {\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\timage.Data = data\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package providers\n\nimport (\n\t\"github.com\/hashicorp\/terraform\/configs\/configschema\"\n\t\"github.com\/hashicorp\/terraform\/tfdiags\"\n\t\"github.com\/zclconf\/go-cty\/cty\"\n)\n\n\/\/ Interface represents the set of methods required for a complete resource\n\/\/ provider plugin.\ntype Interface interface {\n\t\/\/ GetSchema returns the complete schema for the provider.\n\tGetSchema() GetSchemaResponse\n\n\t\/\/ ValidateProviderConfig allows the provider to validate the configuration\n\t\/\/ values.\n\tValidateProviderConfig(ValidateProviderConfigRequest) ValidateProviderConfigResponse\n\n\t\/\/ ValidateResourceTypeConfig allows the provider to validate the resource\n\t\/\/ configuration values.\n\tValidateResourceTypeConfig(ValidateResourceTypeConfigRequest) ValidateResourceTypeConfigResponse\n\n\t\/\/ ValidateDataSource allows the provider to validate the data source\n\t\/\/ configuration values.\n\tValidateDataSourceConfig(ValidateDataSourceConfigRequest) ValidateDataSourceConfigResponse\n\n\t\/\/ UpgradeResourceState is called when the state loader encounters an\n\t\/\/ instance state whose schema version is less than the one reported by the\n\t\/\/ currently-used version of the corresponding provider, and the upgraded\n\t\/\/ result is used for any further processing.\n\tUpgradeResourceState(UpgradeResourceStateRequest) UpgradeResourceStateResponse\n\n\t\/\/ Configure configures and initialized the provider.\n\tConfigure(ConfigureRequest) ConfigureResponse\n\n\t\/\/ Stop is called when the provider should halt any in-flight actions.\n\t\/\/\n\t\/\/ Stop should not block waiting for in-flight actions to complete. It\n\t\/\/ should take any action it wants and return immediately acknowledging it\n\t\/\/ has received the stop request. Terraform will not make any further API\n\t\/\/ calls to the provider after Stop is called.\n\t\/\/\n\t\/\/ The error returned, if non-nil, is assumed to mean that signaling the\n\t\/\/ stop somehow failed and that the user should expect potentially waiting\n\t\/\/ a longer period of time.\n\tStop() error\n\n\t\/\/ ReadResource refreshes a resource and returns its current state.\n\tReadResource(ReadResourceRequest) ReadResourceResponse\n\n\t\/\/ PlanResourceChange takes the current state and proposed state of a\n\t\/\/ resource, and returns the planned final state.\n\tPlanResourceChange(PlanResourceChangeRequest) PlanResourceChangeResponse\n\n\t\/\/ ApplyResourceChange takes the planned state for a resource, which may\n\t\/\/ yet contain unknown computed values, and applies the changes returning\n\t\/\/ the final state.\n\tApplyResourceChange(ApplyResourceChangeRequest) ApplyResourceChangeResponse\n\n\t\/\/ ImportResourceState requests that the given resource be imported.\n\tImportResourceState(ImportResourceStateRequest) ImportResourceStateResponse\n\n\t\/\/ ReadDataSource returns the data source's current state.\n\tReadDataSource(ReadDataSourceRequest) ReadDataSourceResponse\n}\n\ntype GetSchemaResponse struct {\n\t\/\/ Provider is the schema for the provider itself.\n\tProvider Schema\n\n\t\/\/ ResourceTypes map the resource type name to that type's schema.\n\tResourceTypes map[string]Schema\n\n\t\/\/ DataSources maps the data source name to that data source's schema.\n\tDataSources map[string]Schema\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\n\/\/ Schema pairs a provider or resource schema with that schema's version.\n\/\/ This is used to be able to upgrade the schema in\ntype Schema struct {\n\tVersion int\n\tBlock   *configschema.Block\n}\n\ntype ValidateProviderConfigRequest struct {\n\t\/\/ Config is the complete configuration value for the provider.\n\tConfig cty.Value\n}\n\ntype ValidateProviderConfigResponse struct {\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype ValidateResourceTypeConfigRequest struct {\n\t\/\/ TypeName is the name of the resource type to validate.\n\tTypeName string\n\n\t\/\/ Config is the configuration value to validate, which may contain unknown\n\t\/\/ values.\n\tConfig cty.Value\n}\n\ntype ValidateResourceTypeConfigResponse struct {\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype ValidateDataSourceConfigRequest struct {\n\t\/\/ TypeName is the name of the data source type to validate.\n\tTypeName string\n\n\t\/\/ Config is the configuration value to validate, which may contain unknown\n\t\/\/ values.\n\tConfig cty.Value\n}\n\ntype ValidateDataSourceConfigResponse struct {\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype UpgradeResourceStateRequest struct {\n\t\/\/ TypeName is the name of the resource type being upgraded\n\tTypeName string\n\n\t\/\/ Version is version of the schema that created the current state.\n\tVersion int\n\n\t\/\/ RawStateJSON and RawStateFlatmap contiain the state that needs to be\n\t\/\/ upgraded to match the current schema version. Because the schema is\n\t\/\/ unknown, this contains only the raw data as stored in the state.\n\t\/\/ RawStateJSON is the current json state encoding.\n\t\/\/ RawStateFlatmap is the legacy flatmap encoding.\n\t\/\/ Only on of these fields may be set for the upgrade request.\n\tRawStateJSON    []byte\n\tRawStateFlatmap map[string]string\n}\n\ntype UpgradeResourceStateResponse struct {\n\t\/\/ UpgradedState is the newly upgraded resource state.\n\tUpgradedState cty.Value\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype ConfigureRequest struct {\n\t\/\/ Config is the complete configuration value for the provider.\n\tConfig cty.Value\n}\n\ntype ConfigureResponse struct {\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype ReadResourceRequest struct {\n\t\/\/ TypeName is the name of the resource type being read.\n\tTypeName string\n\n\t\/\/ PriorState contains the previously saved state value for this resource.\n\tPriorState cty.Value\n}\n\ntype ReadResourceResponse struct {\n\t\/\/ NewState contains the current state of the resource.\n\tNewState cty.Value\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype PlanResourceChangeRequest struct {\n\t\/\/ TypeName is the name of the resource type to plan.\n\tTypeName string\n\n\t\/\/ PriorState is the previously saved state value for this resource.\n\tPriorState cty.Value\n\n\t\/\/ ProposedNewState is the expected state after the new configuration is\n\t\/\/ applied. This is created by directly applying the configuration to the\n\t\/\/ PriorState. The provider is then responsible for applying any further\n\t\/\/ changes required to create the proposed final state.\n\tProposedNewState cty.Value\n\n\t\/\/ Config is the resource configuration, before being merged with the\n\t\/\/ PriorState. Any value not explicitly set in the configuration will be\n\t\/\/ null. Config is supplied for reference, but Provider implementations\n\t\/\/ should prefer the ProposedNewState in most circumstances.\n\tConfig cty.Value\n\n\t\/\/ PriorPrivate is the previously saved private data returned from the\n\t\/\/ provider during the last apply.\n\tPriorPrivate []byte\n}\n\ntype PlanResourceChangeResponse struct {\n\t\/\/ PlannedState is the expected state of the resource once the current\n\t\/\/ configuration is applied.\n\tPlannedState cty.Value\n\n\t\/\/ RequiresReplace is the list of thee attributes that are requiring\n\t\/\/ resource replacement.\n\tRequiresReplace []cty.Path\n\n\t\/\/ PlannedPrivate is an opaque blob that is not interpreted by terraform\n\t\/\/ core. This will be saved and relayed back to the provider during\n\t\/\/ ApplyResourceChange.\n\tPlannedPrivate []byte\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype ApplyResourceChangeRequest struct {\n\t\/\/ TypeName is the name of the resource type being applied.\n\tTypeName string\n\n\t\/\/ PriorState is the current state of resource.\n\tPriorState cty.Value\n\n\t\/\/ Planned state is the state returned from PlanResourceChange, and should\n\t\/\/ represent the new state, minus any remaining computed attributes.\n\tPlannedState cty.Value\n\n\t\/\/ Config is the resource configuration, before being merged with the\n\t\/\/ PriorState. Any value not explicitly set in the configuration will be\n\t\/\/ null. Config is supplied for reference, but Provider implementations\n\t\/\/ should prefer the PlannedState in most circumstances.\n\tConfig cty.Value\n\n\t\/\/ PlannedPrivate is the same value as returned by PlanResourceChange.\n\tPlannedPrivate []byte\n}\n\ntype ApplyResourceChangeResponse struct {\n\t\/\/ NewState is the new complete state after applying the planned change.\n\t\/\/ In the event of an error, NewState should represent the most recent\n\t\/\/ known state of the resource, if it exists.\n\tNewState cty.Value\n\n\t\/\/ Connection is used to return any information provisioners might require\n\t\/\/ to cty.Value\n\tConnection cty.Value\n\n\t\/\/ Private is an opaque blob that will be stored in state along with the\n\t\/\/ resource. It is intended only for interpretation by the provider itself.\n\tPrivate []byte\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype ImportResourceStateRequest struct {\n\t\/\/ TypeName is the name of the resource type to be imported.\n\tTypeName string\n\n\t\/\/ ID is a string with which the provider can identify the resource to be\n\t\/\/ imported.\n\tID string\n}\n\ntype ImportResourceStateResponse struct {\n\t\/\/ ImportedResources contains one or more state values related to the\n\t\/\/ imported resource. It is not required that these be complete, only that\n\t\/\/ there is enough identifying information for the provider to successfully\n\t\/\/ update the states in ReadResource.\n\tImportedResources []ImportedResource\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\n\/\/ ImportedResource represents an object being imported into Terraform with the\n\/\/ help of a provider. An ImportedObject is a RemoteObject that has been read\n\/\/ by the provider's import handler but hasn't yet been committed to state.\ntype ImportedResource struct {\n\t\/\/ ResourceType is the name of the resource type associated with the\n\t\/\/ returned state. It's possible for providers to import multiple related\n\t\/\/ types with a single import request.\n\tResourceType string\n\n\t\/\/ State is the state of the remote object being imported. This may not be\n\t\/\/ complete, but must contain enough information to uniquely identify the\n\t\/\/ resource.\n\tState cty.Value\n\n\t\/\/ Private is an opaque blob that will be stored in state along with the\n\t\/\/ resource. It is intended only for interpretation by the provider itself.\n\tPrivate []byte\n}\n\ntype ReadDataSourceRequest struct {\n\t\/\/ TypeName is the name of the data source type to Read.\n\tTypeName string\n\n\t\/\/ Config is the complete configuration for the requested data source.\n\tConfig cty.Value\n}\n\ntype ReadDataSourceResponse struct {\n\t\/\/ State is the current state of the requested data source.\n\tState cty.Value\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n<commit_msg>removing connection data from the providers<commit_after>package providers\n\nimport (\n\t\"github.com\/hashicorp\/terraform\/configs\/configschema\"\n\t\"github.com\/hashicorp\/terraform\/tfdiags\"\n\t\"github.com\/zclconf\/go-cty\/cty\"\n)\n\n\/\/ Interface represents the set of methods required for a complete resource\n\/\/ provider plugin.\ntype Interface interface {\n\t\/\/ GetSchema returns the complete schema for the provider.\n\tGetSchema() GetSchemaResponse\n\n\t\/\/ ValidateProviderConfig allows the provider to validate the configuration\n\t\/\/ values.\n\tValidateProviderConfig(ValidateProviderConfigRequest) ValidateProviderConfigResponse\n\n\t\/\/ ValidateResourceTypeConfig allows the provider to validate the resource\n\t\/\/ configuration values.\n\tValidateResourceTypeConfig(ValidateResourceTypeConfigRequest) ValidateResourceTypeConfigResponse\n\n\t\/\/ ValidateDataSource allows the provider to validate the data source\n\t\/\/ configuration values.\n\tValidateDataSourceConfig(ValidateDataSourceConfigRequest) ValidateDataSourceConfigResponse\n\n\t\/\/ UpgradeResourceState is called when the state loader encounters an\n\t\/\/ instance state whose schema version is less than the one reported by the\n\t\/\/ currently-used version of the corresponding provider, and the upgraded\n\t\/\/ result is used for any further processing.\n\tUpgradeResourceState(UpgradeResourceStateRequest) UpgradeResourceStateResponse\n\n\t\/\/ Configure configures and initialized the provider.\n\tConfigure(ConfigureRequest) ConfigureResponse\n\n\t\/\/ Stop is called when the provider should halt any in-flight actions.\n\t\/\/\n\t\/\/ Stop should not block waiting for in-flight actions to complete. It\n\t\/\/ should take any action it wants and return immediately acknowledging it\n\t\/\/ has received the stop request. Terraform will not make any further API\n\t\/\/ calls to the provider after Stop is called.\n\t\/\/\n\t\/\/ The error returned, if non-nil, is assumed to mean that signaling the\n\t\/\/ stop somehow failed and that the user should expect potentially waiting\n\t\/\/ a longer period of time.\n\tStop() error\n\n\t\/\/ ReadResource refreshes a resource and returns its current state.\n\tReadResource(ReadResourceRequest) ReadResourceResponse\n\n\t\/\/ PlanResourceChange takes the current state and proposed state of a\n\t\/\/ resource, and returns the planned final state.\n\tPlanResourceChange(PlanResourceChangeRequest) PlanResourceChangeResponse\n\n\t\/\/ ApplyResourceChange takes the planned state for a resource, which may\n\t\/\/ yet contain unknown computed values, and applies the changes returning\n\t\/\/ the final state.\n\tApplyResourceChange(ApplyResourceChangeRequest) ApplyResourceChangeResponse\n\n\t\/\/ ImportResourceState requests that the given resource be imported.\n\tImportResourceState(ImportResourceStateRequest) ImportResourceStateResponse\n\n\t\/\/ ReadDataSource returns the data source's current state.\n\tReadDataSource(ReadDataSourceRequest) ReadDataSourceResponse\n}\n\ntype GetSchemaResponse struct {\n\t\/\/ Provider is the schema for the provider itself.\n\tProvider Schema\n\n\t\/\/ ResourceTypes map the resource type name to that type's schema.\n\tResourceTypes map[string]Schema\n\n\t\/\/ DataSources maps the data source name to that data source's schema.\n\tDataSources map[string]Schema\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\n\/\/ Schema pairs a provider or resource schema with that schema's version.\n\/\/ This is used to be able to upgrade the schema in\ntype Schema struct {\n\tVersion int\n\tBlock   *configschema.Block\n}\n\ntype ValidateProviderConfigRequest struct {\n\t\/\/ Config is the complete configuration value for the provider.\n\tConfig cty.Value\n}\n\ntype ValidateProviderConfigResponse struct {\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype ValidateResourceTypeConfigRequest struct {\n\t\/\/ TypeName is the name of the resource type to validate.\n\tTypeName string\n\n\t\/\/ Config is the configuration value to validate, which may contain unknown\n\t\/\/ values.\n\tConfig cty.Value\n}\n\ntype ValidateResourceTypeConfigResponse struct {\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype ValidateDataSourceConfigRequest struct {\n\t\/\/ TypeName is the name of the data source type to validate.\n\tTypeName string\n\n\t\/\/ Config is the configuration value to validate, which may contain unknown\n\t\/\/ values.\n\tConfig cty.Value\n}\n\ntype ValidateDataSourceConfigResponse struct {\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype UpgradeResourceStateRequest struct {\n\t\/\/ TypeName is the name of the resource type being upgraded\n\tTypeName string\n\n\t\/\/ Version is version of the schema that created the current state.\n\tVersion int\n\n\t\/\/ RawStateJSON and RawStateFlatmap contiain the state that needs to be\n\t\/\/ upgraded to match the current schema version. Because the schema is\n\t\/\/ unknown, this contains only the raw data as stored in the state.\n\t\/\/ RawStateJSON is the current json state encoding.\n\t\/\/ RawStateFlatmap is the legacy flatmap encoding.\n\t\/\/ Only on of these fields may be set for the upgrade request.\n\tRawStateJSON    []byte\n\tRawStateFlatmap map[string]string\n}\n\ntype UpgradeResourceStateResponse struct {\n\t\/\/ UpgradedState is the newly upgraded resource state.\n\tUpgradedState cty.Value\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype ConfigureRequest struct {\n\t\/\/ Config is the complete configuration value for the provider.\n\tConfig cty.Value\n}\n\ntype ConfigureResponse struct {\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype ReadResourceRequest struct {\n\t\/\/ TypeName is the name of the resource type being read.\n\tTypeName string\n\n\t\/\/ PriorState contains the previously saved state value for this resource.\n\tPriorState cty.Value\n}\n\ntype ReadResourceResponse struct {\n\t\/\/ NewState contains the current state of the resource.\n\tNewState cty.Value\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype PlanResourceChangeRequest struct {\n\t\/\/ TypeName is the name of the resource type to plan.\n\tTypeName string\n\n\t\/\/ PriorState is the previously saved state value for this resource.\n\tPriorState cty.Value\n\n\t\/\/ ProposedNewState is the expected state after the new configuration is\n\t\/\/ applied. This is created by directly applying the configuration to the\n\t\/\/ PriorState. The provider is then responsible for applying any further\n\t\/\/ changes required to create the proposed final state.\n\tProposedNewState cty.Value\n\n\t\/\/ Config is the resource configuration, before being merged with the\n\t\/\/ PriorState. Any value not explicitly set in the configuration will be\n\t\/\/ null. Config is supplied for reference, but Provider implementations\n\t\/\/ should prefer the ProposedNewState in most circumstances.\n\tConfig cty.Value\n\n\t\/\/ PriorPrivate is the previously saved private data returned from the\n\t\/\/ provider during the last apply.\n\tPriorPrivate []byte\n}\n\ntype PlanResourceChangeResponse struct {\n\t\/\/ PlannedState is the expected state of the resource once the current\n\t\/\/ configuration is applied.\n\tPlannedState cty.Value\n\n\t\/\/ RequiresReplace is the list of thee attributes that are requiring\n\t\/\/ resource replacement.\n\tRequiresReplace []cty.Path\n\n\t\/\/ PlannedPrivate is an opaque blob that is not interpreted by terraform\n\t\/\/ core. This will be saved and relayed back to the provider during\n\t\/\/ ApplyResourceChange.\n\tPlannedPrivate []byte\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype ApplyResourceChangeRequest struct {\n\t\/\/ TypeName is the name of the resource type being applied.\n\tTypeName string\n\n\t\/\/ PriorState is the current state of resource.\n\tPriorState cty.Value\n\n\t\/\/ Planned state is the state returned from PlanResourceChange, and should\n\t\/\/ represent the new state, minus any remaining computed attributes.\n\tPlannedState cty.Value\n\n\t\/\/ Config is the resource configuration, before being merged with the\n\t\/\/ PriorState. Any value not explicitly set in the configuration will be\n\t\/\/ null. Config is supplied for reference, but Provider implementations\n\t\/\/ should prefer the PlannedState in most circumstances.\n\tConfig cty.Value\n\n\t\/\/ PlannedPrivate is the same value as returned by PlanResourceChange.\n\tPlannedPrivate []byte\n}\n\ntype ApplyResourceChangeResponse struct {\n\t\/\/ NewState is the new complete state after applying the planned change.\n\t\/\/ In the event of an error, NewState should represent the most recent\n\t\/\/ known state of the resource, if it exists.\n\tNewState cty.Value\n\n\t\/\/ Private is an opaque blob that will be stored in state along with the\n\t\/\/ resource. It is intended only for interpretation by the provider itself.\n\tPrivate []byte\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\ntype ImportResourceStateRequest struct {\n\t\/\/ TypeName is the name of the resource type to be imported.\n\tTypeName string\n\n\t\/\/ ID is a string with which the provider can identify the resource to be\n\t\/\/ imported.\n\tID string\n}\n\ntype ImportResourceStateResponse struct {\n\t\/\/ ImportedResources contains one or more state values related to the\n\t\/\/ imported resource. It is not required that these be complete, only that\n\t\/\/ there is enough identifying information for the provider to successfully\n\t\/\/ update the states in ReadResource.\n\tImportedResources []ImportedResource\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n\n\/\/ ImportedResource represents an object being imported into Terraform with the\n\/\/ help of a provider. An ImportedObject is a RemoteObject that has been read\n\/\/ by the provider's import handler but hasn't yet been committed to state.\ntype ImportedResource struct {\n\t\/\/ ResourceType is the name of the resource type associated with the\n\t\/\/ returned state. It's possible for providers to import multiple related\n\t\/\/ types with a single import request.\n\tResourceType string\n\n\t\/\/ State is the state of the remote object being imported. This may not be\n\t\/\/ complete, but must contain enough information to uniquely identify the\n\t\/\/ resource.\n\tState cty.Value\n\n\t\/\/ Private is an opaque blob that will be stored in state along with the\n\t\/\/ resource. It is intended only for interpretation by the provider itself.\n\tPrivate []byte\n}\n\ntype ReadDataSourceRequest struct {\n\t\/\/ TypeName is the name of the data source type to Read.\n\tTypeName string\n\n\t\/\/ Config is the complete configuration for the requested data source.\n\tConfig cty.Value\n}\n\ntype ReadDataSourceResponse struct {\n\t\/\/ State is the current state of the requested data source.\n\tState cty.Value\n\n\t\/\/ Diagnostics contains any warnings or errors from the method call.\n\tDiagnostics tfdiags.Diagnostics\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"errors\"\n\t\"net\/http\"\n\n\tapierr \"github.com\/dpb587\/ssoca\/server\/api\/errors\"\n\t\"github.com\/dpb587\/ssoca\/server\/service\"\n\t\"github.com\/dpb587\/ssoca\/server\/service\/req\"\n\t\"github.com\/sirupsen\/logrus\"\n\n\tuuid \"github.com\/nu7hatch\/gouuid\"\n)\n\ntype apiHandler struct {\n\tauthService service.AuthService\n\tapiService  service.Service\n\thandler     req.RouteHandler\n\tlogger      logrus.FieldLogger\n}\n\nfunc CreateHandler(authService service.AuthService, apiService service.Service, handler req.RouteHandler, logger logrus.FieldLogger) (http.Handler, error) {\n\treturn apiHandler{\n\t\tauthService: authService,\n\t\tapiService:  apiService,\n\t\thandler:     handler,\n\t\tlogger:      logger,\n\t}, nil\n}\n\nfunc (h apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\trequest := req.Request{\n\t\tRawRequest:  r,\n\t\tRawResponse: w,\n\t}\n\n\trequestUUID, err := uuid.NewV4()\n\tif err != nil {\n\t\th.sendGenericErrorResponse(request, apierr.WrapError(err, \"Generating request ID\"))\n\n\t\treturn\n\t}\n\n\trequest.ID = requestUUID.String()\n\trequest.LoggerContext = logrus.Fields{\n\t\t\"server.request.id\":          request.ID,\n\t\t\"server.request.remote_addr\": r.RemoteAddr,\n\t\t\"service.name\":               h.apiService.Name(),\n\t\t\"service.type\":               h.apiService.Type(),\n\t}\n\n\ttoken, err := h.authService.ParseRequestAuth(*r)\n\tif err != nil {\n\t\t\/\/ never allow a token if there was an error\n\t\ttoken = nil\n\n\t\t\/\/ differentiate unauthorized (essentially unauthorized, aka expired) vs forbidden (apparent auth, but invalid)\n\t\tif matchederr, matched := err.(apierr.Error); matched {\n\t\t\tif matchederr.Status == http.StatusUnauthorized {\n\t\t\t\th.getRequestLogger(request).Debug(err)\n\n\t\t\t\terr = nil\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\th.sendGenericErrorResponse(request, apierr.WrapError(err, \"Parsing authentication token\"))\n\n\t\t\treturn\n\t\t}\n\t}\n\n\trequest.AuthToken = token\n\n\tauthz, err := h.apiService.IsAuthorized(*r, request.AuthToken)\n\tif err != nil {\n\t\th.sendGenericErrorResponse(request, apierr.WrapError(apierr.NewError(err, 401, \"\"), \"Checking service authorization\"))\n\n\t\treturn\n\t} else if !authz {\n\t\th.sendErrorResponse(request, apierr.NewError(errors.New(\"Not authorized\"), http.StatusForbidden, \"\"))\n\n\t\treturn\n\t}\n\n\tif token != nil {\n\t\trequest.LoggerContext[\"auth.user_id\"] = token.ID\n\t}\n\n\terr = h.handler.Execute(request)\n\tif err != nil {\n\t\th.sendGenericErrorResponse(request, apierr.WrapError(err, \"Executing handler\"))\n\t}\n\n\th.getRequestLogger(request).Info(\"Finished request\")\n}\n\nfunc (h apiHandler) sendGenericErrorResponse(request req.Request, err error) {\n\th.sendErrorResponse(request, apierr.NewError(err, http.StatusInternalServerError, \"\"))\n}\n\nfunc (h apiHandler) sendErrorResponse(request req.Request, err apierr.Error) {\n\trequest.RawResponse.WriteHeader(err.Status)\n\n\tvar loggerFunc func(args ...interface{})\n\tlogger := h.getRequestLogger(request)\n\n\tif err.Status >= 500 {\n\t\tloggerFunc = logger.Error\n\t} else {\n\t\tloggerFunc = logger.Warn\n\t}\n\n\tloggerFunc(err.Error())\n\n\trequest.WritePayload(map[string]interface{}{\n\t\t\"error\": map[string]interface{}{\n\t\t\t\"status\":  err.Status,\n\t\t\t\"message\": err.PublicError,\n\t\t},\n\t})\n}\n\nfunc (h apiHandler) getRequestLogger(request req.Request) *logrus.Entry {\n\treturn h.logger.WithFields(request.LoggerContext).WithFields(logrus.Fields{\n\t\t\"server.request.method\": request.RawRequest.Method,\n\t\t\"server.request.path\":   request.RawRequest.URL.Path,\n\t})\n}\n<commit_msg>auth: Remove special handling of 401 Unauthorized errors<commit_after>package api\n\nimport (\n\t\"errors\"\n\t\"net\/http\"\n\n\tapierr \"github.com\/dpb587\/ssoca\/server\/api\/errors\"\n\t\"github.com\/dpb587\/ssoca\/server\/service\"\n\t\"github.com\/dpb587\/ssoca\/server\/service\/req\"\n\t\"github.com\/sirupsen\/logrus\"\n\n\tuuid \"github.com\/nu7hatch\/gouuid\"\n)\n\ntype apiHandler struct {\n\tauthService service.AuthService\n\tapiService  service.Service\n\thandler     req.RouteHandler\n\tlogger      logrus.FieldLogger\n}\n\nfunc CreateHandler(authService service.AuthService, apiService service.Service, handler req.RouteHandler, logger logrus.FieldLogger) (http.Handler, error) {\n\treturn apiHandler{\n\t\tauthService: authService,\n\t\tapiService:  apiService,\n\t\thandler:     handler,\n\t\tlogger:      logger,\n\t}, nil\n}\n\nfunc (h apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\trequest := req.Request{\n\t\tRawRequest:  r,\n\t\tRawResponse: w,\n\t}\n\n\trequestUUID, err := uuid.NewV4()\n\tif err != nil {\n\t\th.sendGenericErrorResponse(request, apierr.WrapError(err, \"Generating request ID\"))\n\n\t\treturn\n\t}\n\n\trequest.ID = requestUUID.String()\n\trequest.LoggerContext = logrus.Fields{\n\t\t\"server.request.id\":          request.ID,\n\t\t\"server.request.remote_addr\": r.RemoteAddr,\n\t\t\"service.name\":               h.apiService.Name(),\n\t\t\"service.type\":               h.apiService.Type(),\n\t}\n\n\ttoken, err := h.authService.ParseRequestAuth(*r)\n\tif err != nil {\n\t\th.sendGenericErrorResponse(request, apierr.WrapError(err, \"Parsing authentication token\"))\n\n\t\treturn\n\t}\n\n\trequest.AuthToken = token\n\n\tauthz, err := h.apiService.IsAuthorized(*r, request.AuthToken)\n\tif err != nil {\n\t\th.sendGenericErrorResponse(request, apierr.WrapError(apierr.NewError(err, 401, \"\"), \"Checking service authorization\"))\n\n\t\treturn\n\t} else if !authz {\n\t\th.sendErrorResponse(request, apierr.NewError(errors.New(\"Not authorized\"), http.StatusForbidden, \"\"))\n\n\t\treturn\n\t}\n\n\tif token != nil {\n\t\trequest.LoggerContext[\"auth.user_id\"] = token.ID\n\t}\n\n\terr = h.handler.Execute(request)\n\tif err != nil {\n\t\th.sendGenericErrorResponse(request, apierr.WrapError(err, \"Executing handler\"))\n\t}\n\n\th.getRequestLogger(request).Info(\"Finished request\")\n}\n\nfunc (h apiHandler) sendGenericErrorResponse(request req.Request, err error) {\n\th.sendErrorResponse(request, apierr.NewError(err, http.StatusInternalServerError, \"\"))\n}\n\nfunc (h apiHandler) sendErrorResponse(request req.Request, err apierr.Error) {\n\trequest.RawResponse.WriteHeader(err.Status)\n\n\tvar loggerFunc func(args ...interface{})\n\tlogger := h.getRequestLogger(request)\n\n\tif err.Status >= 500 {\n\t\tloggerFunc = logger.Error\n\t} else {\n\t\tloggerFunc = logger.Warn\n\t}\n\n\tloggerFunc(err.Error())\n\n\trequest.WritePayload(map[string]interface{}{\n\t\t\"error\": map[string]interface{}{\n\t\t\t\"status\":  err.Status,\n\t\t\t\"message\": err.PublicError,\n\t\t},\n\t})\n}\n\nfunc (h apiHandler) getRequestLogger(request req.Request) *logrus.Entry {\n\treturn h.logger.WithFields(request.LoggerContext).WithFields(logrus.Fields{\n\t\t\"server.request.method\": request.RawRequest.Method,\n\t\t\"server.request.path\":   request.RawRequest.URL.Path,\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 tsuru authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage swarm\n\nimport (\n\t\"errors\"\n\t\"math\/rand\"\n\n\t\"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/tsuru\/tsuru\/db\"\n\t\"github.com\/tsuru\/tsuru\/db\/storage\"\n)\n\nvar errNoSwarmNode = errors.New(\"no swarm nodes available\")\n\ntype NodeAddr struct {\n\tDockerAddress string `bson:\"_id\"`\n\tSwarmAddress  string\n}\n\nfunc chooseDBSwarmNode() (*docker.Client, *NodeAddr, error) {\n\tcoll, err := nodeAddrCollection()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tvar addrs []NodeAddr\n\terr = coll.Find(nil).All(&addrs)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif len(addrs) == 0 {\n\t\treturn nil, nil, errNoSwarmNode\n\t}\n\taddr := addrs[rand.Intn(len(addrs))]\n\t\/\/ TODO(cezarsa): try ping. in case of failure, try another node and update\n\t\/\/ swarm node collection\n\tclient, err := newClient(addr.DockerAddress)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn client, &addr, nil\n}\n\nfunc updateDBSwarmNodes(client *docker.Client) error {\n\tnodes, err := client.ListNodes(docker.ListNodesOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar docs []interface{}\n\tfor _, n := range nodes {\n\t\tif n.ManagerStatus == nil {\n\t\t\tcontinue\n\t\t}\n\t\taddr := n.Spec.Annotations.Labels[labelDockerAddr]\n\t\tif addr == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tdocs = append(docs, NodeAddr{\n\t\t\tDockerAddress: addr,\n\t\t\tSwarmAddress:  n.ManagerStatus.Addr,\n\t\t})\n\t}\n\tcoll, err := nodeAddrCollection()\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ TODO(cezarsa): safety and performance, do diff update instead of remove\n\t\/\/ all and add all.\n\t_, err = coll.RemoveAll(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn coll.Insert(docs...)\n}\n\nfunc nodeAddrCollection() (*storage.Collection, error) {\n\tconn, err := db.Conn()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn conn.Collection(\"swarmnodes\"), nil\n}\n<commit_msg>provision\/swarm: fix leak of db connections<commit_after>\/\/ Copyright 2016 tsuru authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage swarm\n\nimport (\n\t\"errors\"\n\t\"math\/rand\"\n\n\t\"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/tsuru\/tsuru\/db\"\n\t\"github.com\/tsuru\/tsuru\/db\/storage\"\n)\n\nvar errNoSwarmNode = errors.New(\"no swarm nodes available\")\n\ntype NodeAddr struct {\n\tDockerAddress string `bson:\"_id\"`\n\tSwarmAddress  string\n}\n\nfunc chooseDBSwarmNode() (*docker.Client, *NodeAddr, error) {\n\tcoll, err := nodeAddrCollection()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tdefer coll.Close()\n\tvar addrs []NodeAddr\n\terr = coll.Find(nil).All(&addrs)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif len(addrs) == 0 {\n\t\treturn nil, nil, errNoSwarmNode\n\t}\n\taddr := addrs[rand.Intn(len(addrs))]\n\t\/\/ TODO(cezarsa): try ping. in case of failure, try another node and update\n\t\/\/ swarm node collection\n\tclient, err := newClient(addr.DockerAddress)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn client, &addr, nil\n}\n\nfunc updateDBSwarmNodes(client *docker.Client) error {\n\tnodes, err := client.ListNodes(docker.ListNodesOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar docs []interface{}\n\tfor _, n := range nodes {\n\t\tif n.ManagerStatus == nil {\n\t\t\tcontinue\n\t\t}\n\t\taddr := n.Spec.Annotations.Labels[labelDockerAddr]\n\t\tif addr == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tdocs = append(docs, NodeAddr{\n\t\t\tDockerAddress: addr,\n\t\t\tSwarmAddress:  n.ManagerStatus.Addr,\n\t\t})\n\t}\n\tcoll, err := nodeAddrCollection()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer coll.Close()\n\t\/\/ TODO(cezarsa): safety and performance, do diff update instead of remove\n\t\/\/ all and add all.\n\t_, err = coll.RemoveAll(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn coll.Insert(docs...)\n}\n\nfunc nodeAddrCollection() (*storage.Collection, error) {\n\tconn, err := db.Conn()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn conn.Collection(\"swarmnodes\"), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\n\tutilerrors \"k8s.io\/apimachinery\/pkg\/util\/errors\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/sets\"\n\t\"k8s.io\/test-infra\/prow\/config\"\n\t\"k8s.io\/test-infra\/prow\/tide\"\n\t\"k8s.io\/test-infra\/prow\/tide\/history\"\n)\n\ntype tidePools struct {\n\tQueries     []string\n\tTideQueries []config.TideQuery\n\tPools       []tide.Pool\n}\n\ntype tideHistory struct {\n\tHistory map[string][]history.Record\n}\n\ntype tideAgent struct {\n\tlog          *logrus.Entry\n\tpath         string\n\tupdatePeriod func() time.Duration\n\n\t\/\/ Config for hiding repos\n\thiddenRepos func() []string\n\thiddenOnly  bool\n\tshowHidden  bool\n\n\ttenantIDs []string\n\tcfg       config.Config\n\n\tsync.Mutex\n\tpools   []tide.Pool\n\thistory map[string][]history.Record\n}\n\nfunc (ta *tideAgent) start() {\n\tstartTimePool := time.Now()\n\tif err := ta.updatePools(); err != nil {\n\t\tta.log.WithError(err).Error(\"Updating pools the first time.\")\n\t}\n\tstartTimeHistory := time.Now()\n\tif err := ta.updateHistory(); err != nil {\n\t\tta.log.WithError(err).Error(\"Updating history the first time.\")\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Until(startTimePool.Add(ta.updatePeriod())))\n\t\t\tstartTimePool = time.Now()\n\t\t\tif err := ta.updatePools(); err != nil {\n\t\t\t\tta.log.WithError(err).Error(\"Updating pools.\")\n\t\t\t}\n\t\t}\n\t}()\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Until(startTimeHistory.Add(ta.updatePeriod())))\n\t\t\tstartTimeHistory = time.Now()\n\t\t\tif err := ta.updateHistory(); err != nil {\n\t\t\t\tta.log.WithError(err).Error(\"Updating history.\")\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc fetchTideData(log *logrus.Entry, path string, data interface{}) error {\n\tvar prevErrs []error\n\tvar err error\n\tbackoff := 5 * time.Second\n\tfor i := 0; i < 4; i++ {\n\t\tvar resp *http.Response\n\t\tif err != nil {\n\t\t\tprevErrs = append(prevErrs, err)\n\t\t\ttime.Sleep(backoff)\n\t\t\tbackoff *= 4\n\t\t}\n\t\tresp, err = http.Get(path)\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tif resp.StatusCode < 200 || resp.StatusCode > 299 {\n\t\t\t\terr = fmt.Errorf(\"response has status code %d\", resp.StatusCode)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err = json.NewDecoder(resp.Body).Decode(data); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/ Either combine previous errors with the returned error, or if we succeeded\n\t\/\/ log once about any errors we saw before succeeding.\n\tprevErr := utilerrors.NewAggregate(prevErrs)\n\tif err != nil {\n\t\treturn utilerrors.NewAggregate([]error{err, prevErr})\n\t}\n\tif prevErr != nil {\n\t\tlog.WithError(prevErr).Infof(\n\t\t\t\"Failed %d retries fetching Tide data before success: %v.\",\n\t\t\tlen(prevErrs),\n\t\t\tprevErr,\n\t\t)\n\t}\n\treturn nil\n}\n\nfunc (ta *tideAgent) updatePools() error {\n\tvar pools []tide.Pool\n\tif err := fetchTideData(ta.log, ta.path, &pools); err != nil {\n\t\treturn err\n\t}\n\tpools = ta.filterPools(pools)\n\n\tta.Lock()\n\tdefer ta.Unlock()\n\tta.pools = pools\n\treturn nil\n}\n\nfunc (ta *tideAgent) updateHistory() error {\n\tpath := strings.TrimSuffix(ta.path, \"\/\") + \"\/history\"\n\tvar history map[string][]history.Record\n\tif err := fetchTideData(ta.log, path, &history); err != nil {\n\t\treturn err\n\t}\n\thistory = ta.filterHistory(history)\n\n\tta.Lock()\n\tdefer ta.Unlock()\n\tta.history = history\n\treturn nil\n}\n\nfunc (ta *tideAgent) matchingIDs(ids []string) bool {\n\treturn len(ids) > 0 && sets.String{}.Insert(ta.tenantIDs...).HasAll(ids...)\n}\n\nfunc (ta *tideAgent) filterPools(pools []tide.Pool) []tide.Pool {\n\tfiltered := make([]tide.Pool, 0, len(pools))\n\tfor _, pool := range pools {\n\t\t\/\/ curIDs are the IDs associated with all PJs in the Pool\n\t\t\/\/ We want to add the ID associated with the OrgRepo for extra protection\n\t\tcurIDs := sets.NewString(pool.TenantIDs...)\n\t\torgRepoID := ta.cfg.GetProwJobDefault(pool.Org+\"\/\"+pool.Repo, \"*\").TenantID\n\t\t\/\/ If the orgrepo is associated with no tenantID OR the default tenantID we ignore it here.\n\t\t\/\/ This prevents already IDd pools from getting the default ID assigned to them when their orgrepo is not associated with an OrgRepo.\n\t\t\/\/ Pools with no tenantID and with default tenantID behave the same, so adding the default ID just causes issues\n\t\tif orgRepoID != \"\" && orgRepoID != config.DefaultTenantID {\n\t\t\tcurIDs.Insert(orgRepoID)\n\t\t}\n\t\tif len(ta.tenantIDs) > 0 && ta.matchingIDs(curIDs.List()) {\n\t\t\t\/\/ Deck has tenantIDs and they match with the pool\n\t\t\tfiltered = append(filtered, pool)\n\t\t} else if len(ta.tenantIDs) == 0 {\n\t\t\t\/\/Deck has no tenantID\n\t\t\tneedsHide := matches(pool.Org+\"\/\"+pool.Repo, ta.hiddenRepos())\n\t\t\tif needsHide && (ta.showHidden || ta.hiddenOnly) {\n\t\t\t\t\/\/ Pool is hidden and Deck is showing hidden\n\t\t\t\tfiltered = append(filtered, pool)\n\t\t\t} else if !needsHide && !ta.hiddenOnly && noTenantIDOrDefaultTenantID(curIDs.List()) {\n\t\t\t\t\/\/ Pool is not hidden and has no tenantID and Deck is not hidden only.\n\t\t\t\tfiltered = append(filtered, pool)\n\t\t\t}\n\t\t}\n\t}\n\treturn filtered\n}\n\nfunc noTenantIDOrDefaultTenantID(ids []string) bool {\n\tfor _, id := range ids {\n\t\tif id != \"\" && id != config.DefaultTenantID {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc recordIDs(records []history.Record) sets.String {\n\tres := sets.String{}\n\tfor _, record := range records {\n\t\tres.Insert(record.TenantIDs...)\n\t}\n\treturn res\n}\n\nfunc (ta *tideAgent) filterHistory(hist map[string][]history.Record) map[string][]history.Record {\n\tfiltered := make(map[string][]history.Record, len(hist))\n\tfor pool, records := range hist {\n\t\torgRepo := strings.Split(pool, \":\")[0]\n\t\tcurIDs := recordIDs(records).Insert()\n\t\torgRepoID := ta.cfg.GetProwJobDefault(orgRepo, \"*\").TenantID\n\t\t\/\/ If the orgrepo is associated with no tenantID OR the default tenantID we ignore it here.\n\t\t\/\/ This prevents already IDd History from getting the default ID assigned to them when their orgrepo is not associated with an OrgRepo.\n\t\t\/\/ History with no tenantID and with default tenantID behave the same, so adding the default ID just causes issues\n\t\tif orgRepoID != \"\" && orgRepoID != config.DefaultTenantID {\n\t\t\tcurIDs.Insert(orgRepoID)\n\t\t}\n\t\tif len(ta.tenantIDs) > 0 && ta.matchingIDs(curIDs.List()) {\n\t\t\t\/\/ Deck has tenantIDs and they match with the History\n\t\t\tfiltered[pool] = records\n\t\t} else if len(ta.tenantIDs) == 0 {\n\t\t\tneedsHide := matches(orgRepo, ta.hiddenRepos())\n\t\t\tif needsHide && (ta.showHidden || ta.hiddenOnly) {\n\t\t\t\tfiltered[pool] = records\n\t\t\t} else if !needsHide && !ta.hiddenOnly && noTenantIDOrDefaultTenantID(curIDs.List()) {\n\t\t\t\tfiltered[pool] = records\n\t\t\t}\n\t\t}\n\t}\n\treturn filtered\n}\n\nfunc (ta *tideAgent) filterQueries(queries []config.TideQuery) []config.TideQuery {\n\tfiltered := make([]config.TideQuery, 0, len(queries))\n\tfor _, qc := range queries {\n\t\tcurIDs := qc.TenantIDs(ta.cfg)\n\t\tneedsHide := false\n\t\tif len(ta.tenantIDs) > 0 && ta.matchingIDs(curIDs) {\n\t\t\t\/\/ Deck has tenantIDs and they match with the Query\n\t\t\tfiltered = append(filtered, qc)\n\t\t} else if len(ta.tenantIDs) == 0 {\n\t\t\tfor _, repo := range qc.Repos {\n\t\t\t\tif matches(repo, ta.hiddenRepos()) {\n\t\t\t\t\tneedsHide = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif needsHide && (ta.showHidden || ta.hiddenOnly) {\n\t\t\t\t\/\/ Query is hidden and Deck is showing hidden\n\t\t\t\tfiltered = append(filtered, qc)\n\t\t\t} else if !needsHide && !ta.hiddenOnly && noTenantIDOrDefaultTenantID(curIDs) {\n\t\t\t\t\/\/ Query is not hidden and has no tenantID and Deck is not hidden only.\n\t\t\t\tfiltered = append(filtered, qc)\n\t\t\t}\n\t\t}\n\t}\n\treturn filtered\n}\n\n\/\/ matches returns whether the provided repo intersects\n\/\/ with repos. repo has always the \"org\/repo\" format but\n\/\/ repos can include both orgs and repos.\nfunc matches(repo string, repos []string) bool {\n\torg := strings.Split(repo, \"\/\")[0]\n\tfor _, r := range repos {\n\t\tif r == repo || r == org {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>Fix indenting on if statements<commit_after>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\n\tutilerrors \"k8s.io\/apimachinery\/pkg\/util\/errors\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/sets\"\n\t\"k8s.io\/test-infra\/prow\/config\"\n\t\"k8s.io\/test-infra\/prow\/tide\"\n\t\"k8s.io\/test-infra\/prow\/tide\/history\"\n)\n\ntype tidePools struct {\n\tQueries     []string\n\tTideQueries []config.TideQuery\n\tPools       []tide.Pool\n}\n\ntype tideHistory struct {\n\tHistory map[string][]history.Record\n}\n\ntype tideAgent struct {\n\tlog          *logrus.Entry\n\tpath         string\n\tupdatePeriod func() time.Duration\n\n\t\/\/ Config for hiding repos\n\thiddenRepos func() []string\n\thiddenOnly  bool\n\tshowHidden  bool\n\n\ttenantIDs []string\n\tcfg       config.Config\n\n\tsync.Mutex\n\tpools   []tide.Pool\n\thistory map[string][]history.Record\n}\n\nfunc (ta *tideAgent) start() {\n\tstartTimePool := time.Now()\n\tif err := ta.updatePools(); err != nil {\n\t\tta.log.WithError(err).Error(\"Updating pools the first time.\")\n\t}\n\tstartTimeHistory := time.Now()\n\tif err := ta.updateHistory(); err != nil {\n\t\tta.log.WithError(err).Error(\"Updating history the first time.\")\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Until(startTimePool.Add(ta.updatePeriod())))\n\t\t\tstartTimePool = time.Now()\n\t\t\tif err := ta.updatePools(); err != nil {\n\t\t\t\tta.log.WithError(err).Error(\"Updating pools.\")\n\t\t\t}\n\t\t}\n\t}()\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Until(startTimeHistory.Add(ta.updatePeriod())))\n\t\t\tstartTimeHistory = time.Now()\n\t\t\tif err := ta.updateHistory(); err != nil {\n\t\t\t\tta.log.WithError(err).Error(\"Updating history.\")\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc fetchTideData(log *logrus.Entry, path string, data interface{}) error {\n\tvar prevErrs []error\n\tvar err error\n\tbackoff := 5 * time.Second\n\tfor i := 0; i < 4; i++ {\n\t\tvar resp *http.Response\n\t\tif err != nil {\n\t\t\tprevErrs = append(prevErrs, err)\n\t\t\ttime.Sleep(backoff)\n\t\t\tbackoff *= 4\n\t\t}\n\t\tresp, err = http.Get(path)\n\t\tif err == nil {\n\t\t\tdefer resp.Body.Close()\n\t\t\tif resp.StatusCode < 200 || resp.StatusCode > 299 {\n\t\t\t\terr = fmt.Errorf(\"response has status code %d\", resp.StatusCode)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err = json.NewDecoder(resp.Body).Decode(data); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/ Either combine previous errors with the returned error, or if we succeeded\n\t\/\/ log once about any errors we saw before succeeding.\n\tprevErr := utilerrors.NewAggregate(prevErrs)\n\tif err != nil {\n\t\treturn utilerrors.NewAggregate([]error{err, prevErr})\n\t}\n\tif prevErr != nil {\n\t\tlog.WithError(prevErr).Infof(\n\t\t\t\"Failed %d retries fetching Tide data before success: %v.\",\n\t\t\tlen(prevErrs),\n\t\t\tprevErr,\n\t\t)\n\t}\n\treturn nil\n}\n\nfunc (ta *tideAgent) updatePools() error {\n\tvar pools []tide.Pool\n\tif err := fetchTideData(ta.log, ta.path, &pools); err != nil {\n\t\treturn err\n\t}\n\tpools = ta.filterPools(pools)\n\n\tta.Lock()\n\tdefer ta.Unlock()\n\tta.pools = pools\n\treturn nil\n}\n\nfunc (ta *tideAgent) updateHistory() error {\n\tpath := strings.TrimSuffix(ta.path, \"\/\") + \"\/history\"\n\tvar history map[string][]history.Record\n\tif err := fetchTideData(ta.log, path, &history); err != nil {\n\t\treturn err\n\t}\n\thistory = ta.filterHistory(history)\n\n\tta.Lock()\n\tdefer ta.Unlock()\n\tta.history = history\n\treturn nil\n}\n\nfunc (ta *tideAgent) matchingIDs(ids []string) bool {\n\treturn len(ids) > 0 && sets.String{}.Insert(ta.tenantIDs...).HasAll(ids...)\n}\n\nfunc (ta *tideAgent) filterPools(pools []tide.Pool) []tide.Pool {\n\tfiltered := make([]tide.Pool, 0, len(pools))\n\tfor _, pool := range pools {\n\t\t\/\/ curIDs are the IDs associated with all PJs in the Pool\n\t\t\/\/ We want to add the ID associated with the OrgRepo for extra protection\n\t\tcurIDs := sets.NewString(pool.TenantIDs...)\n\t\torgRepoID := ta.cfg.GetProwJobDefault(pool.Org+\"\/\"+pool.Repo, \"*\").TenantID\n\t\t\/\/ If the orgrepo is associated with no tenantID OR the default tenantID we ignore it here.\n\t\t\/\/ This prevents already IDd pools from getting the default ID assigned to them when their orgrepo is not associated with an OrgRepo.\n\t\t\/\/ Pools with no tenantID and with default tenantID behave the same, so adding the default ID just causes issues\n\t\tif orgRepoID != \"\" && orgRepoID != config.DefaultTenantID {\n\t\t\tcurIDs.Insert(orgRepoID)\n\t\t}\n\t\tif len(ta.tenantIDs) > 0 {\n\t\t\t\/\/ Deck has tenantIDs\n\t\t\tif ta.matchingIDs(curIDs.List()) {\n\t\t\t\t\/\/ tenantIDs match with the pool\n\t\t\t\tfiltered = append(filtered, pool)\n\t\t\t}\n\t\t} else if needsHide := matches(pool.Org+\"\/\"+pool.Repo, ta.hiddenRepos()); needsHide {\n\t\t\t\/\/ Deck has no tenantIDs, and the Pool needs to be hidden\n\t\t\tif ta.showHidden || ta.hiddenOnly {\n\t\t\t\t\/\/ Show hidden or hidden only is true\n\t\t\t\tfiltered = append(filtered, pool)\n\t\t\t}\n\t\t} else if !ta.hiddenOnly && noTenantIDOrDefaultTenantID(curIDs.List()) {\n\t\t\t\/\/ Pool is not hidden and has no tenantID and Deck is not hidden only.\n\t\t\tfiltered = append(filtered, pool)\n\t\t}\n\t}\n\treturn filtered\n}\n\nfunc noTenantIDOrDefaultTenantID(ids []string) bool {\n\tfor _, id := range ids {\n\t\tif id != \"\" && id != config.DefaultTenantID {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc recordIDs(records []history.Record) sets.String {\n\tres := sets.String{}\n\tfor _, record := range records {\n\t\tres.Insert(record.TenantIDs...)\n\t}\n\treturn res\n}\n\nfunc (ta *tideAgent) filterHistory(hist map[string][]history.Record) map[string][]history.Record {\n\tfiltered := make(map[string][]history.Record, len(hist))\n\tfor pool, records := range hist {\n\t\torgRepo := strings.Split(pool, \":\")[0]\n\t\tcurIDs := recordIDs(records).Insert()\n\t\torgRepoID := ta.cfg.GetProwJobDefault(orgRepo, \"*\").TenantID\n\t\t\/\/ If the orgrepo is associated with no tenantID OR the default tenantID we ignore it here.\n\t\t\/\/ This prevents already IDd History from getting the default ID assigned to them when their orgrepo is not associated with an OrgRepo.\n\t\t\/\/ History with no tenantID and with default tenantID behave the same, so adding the default ID just causes issues\n\t\tif orgRepoID != \"\" && orgRepoID != config.DefaultTenantID {\n\t\t\tcurIDs.Insert(orgRepoID)\n\t\t}\n\t\tif len(ta.tenantIDs) > 0 {\n\t\t\tif ta.matchingIDs(curIDs.List()) {\n\t\t\t\t\/\/ Deck has tenantIDs and they match with the History\n\t\t\t\tfiltered[pool] = records\n\t\t\t}\n\t\t} else if needsHide := matches(orgRepo, ta.hiddenRepos()); needsHide {\n\t\t\tif ta.showHidden || ta.hiddenOnly {\n\t\t\t\tfiltered[pool] = records\n\t\t\t}\n\t\t} else if !ta.hiddenOnly && noTenantIDOrDefaultTenantID(curIDs.List()) {\n\t\t\tfiltered[pool] = records\n\t\t}\n\t}\n\treturn filtered\n}\n\nfunc (ta *tideAgent) filterQueries(queries []config.TideQuery) []config.TideQuery {\n\tfiltered := make([]config.TideQuery, 0, len(queries))\n\tfor _, qc := range queries {\n\t\tcurIDs := qc.TenantIDs(ta.cfg)\n\t\tneedsHide := false\n\t\tif len(ta.tenantIDs) > 0 && ta.matchingIDs(curIDs) {\n\t\t\t\/\/ Deck has tenantIDs and they match with the Query\n\t\t\tfiltered = append(filtered, qc)\n\t\t} else if len(ta.tenantIDs) == 0 {\n\t\t\tfor _, repo := range qc.Repos {\n\t\t\t\tif matches(repo, ta.hiddenRepos()) {\n\t\t\t\t\tneedsHide = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif needsHide && (ta.showHidden || ta.hiddenOnly) {\n\t\t\t\t\/\/ Query is hidden and Deck is showing hidden\n\t\t\t\tfiltered = append(filtered, qc)\n\t\t\t} else if !needsHide && !ta.hiddenOnly && noTenantIDOrDefaultTenantID(curIDs) {\n\t\t\t\t\/\/ Query is not hidden and has no tenantID and Deck is not hidden only.\n\t\t\t\tfiltered = append(filtered, qc)\n\t\t\t}\n\t\t}\n\t}\n\treturn filtered\n}\n\n\/\/ matches returns whether the provided repo intersects\n\/\/ with repos. repo has always the \"org\/repo\" format but\n\/\/ repos can include both orgs and repos.\nfunc matches(repo string, repos []string) bool {\n\torg := strings.Split(repo, \"\/\")[0]\n\tfor _, r := range repos {\n\t\tif r == repo || r == org {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage handle\n\nimport (\n\t\"errors\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/fs\/inode\"\n\t\"github.com\/googlecloudplatform\/gcsfuse\/internal\/gcsx\"\n\t\"golang.org\/x\/net\/context\"\n)\n\ntype FileHandle struct {\n\tinode *inode.FileInode\n\n\t\/\/ A random reader configured to some (potentially previous) generation of\n\t\/\/ the object backing the inode, or nil.\n\t\/\/\n\t\/\/ INVARIANT: If reader != nil, reader.CheckInvariants() doesn't panic.\n\t\/\/\n\t\/\/ GUARDED_BY(inode)\n\treader gcsx.RandomReader\n}\n\nfunc NewFileHandle(inode *inode.FileInode) (fh *FileHandle, err error) {\n\terr = errors.New(\"TODO\")\n\treturn\n}\n\n\/\/ Panic if any internal invariants are violated.\n\/\/\n\/\/ LOCKS_REQUIRED(fh.inode)\nfunc (fh *FileHandle) CheckInvariants() {\n\t\/\/ INVARIANT: If reader != nil, reader.CheckInvariants() doesn't panic.\n\tif fh.reader != nil {\n\t\tfh.reader.CheckInvariants()\n\t}\n}\n\n\/\/ Destroy any resources associated with the handle, which must not be used\n\/\/ again.\nfunc (fh *FileHandle) Destroy() {\n\tpanic(\"TODO\")\n}\n\n\/\/ Return the inode backing this handle.\nfunc (fh *FileHandle) Inode() *inode.FileInode {\n\tpanic(\"TODO\")\n}\n\n\/\/ Equivalent to locking fh.Inode() and calling fh.Inode().Read, but may be\n\/\/ more efficient.\n\/\/\n\/\/ LOCKS_EXCLUDED(fh.inode)\nfunc (fh *FileHandle) Read(\n\tctx context.Context,\n\tdst []byte,\n\toffset int64) (n int, err error) {\n\terr = errors.New(\"TODO\")\n\treturn\n}\n<commit_msg>FileHandle.Destroy<commit_after>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage handle\n\nimport (\n\t\"errors\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/fs\/inode\"\n\t\"github.com\/googlecloudplatform\/gcsfuse\/internal\/gcsx\"\n\t\"golang.org\/x\/net\/context\"\n)\n\ntype FileHandle struct {\n\tinode *inode.FileInode\n\n\t\/\/ A random reader configured to some (potentially previous) generation of\n\t\/\/ the object backing the inode, or nil.\n\t\/\/\n\t\/\/ INVARIANT: If reader != nil, reader.CheckInvariants() doesn't panic.\n\t\/\/\n\t\/\/ GUARDED_BY(inode)\n\treader gcsx.RandomReader\n}\n\nfunc NewFileHandle(inode *inode.FileInode) (fh *FileHandle, err error) {\n\terr = errors.New(\"TODO\")\n\treturn\n}\n\n\/\/ Panic if any internal invariants are violated.\n\/\/\n\/\/ LOCKS_REQUIRED(fh.inode)\nfunc (fh *FileHandle) CheckInvariants() {\n\t\/\/ INVARIANT: If reader != nil, reader.CheckInvariants() doesn't panic.\n\tif fh.reader != nil {\n\t\tfh.reader.CheckInvariants()\n\t}\n}\n\n\/\/ Destroy any resources associated with the handle, which must not be used\n\/\/ again.\nfunc (fh *FileHandle) Destroy() {\n\tif fh.reader != nil {\n\t\tfh.reader.Destroy()\n\t}\n}\n\n\/\/ Return the inode backing this handle.\nfunc (fh *FileHandle) Inode() *inode.FileInode {\n\tpanic(\"TODO\")\n}\n\n\/\/ Equivalent to locking fh.Inode() and calling fh.Inode().Read, but may be\n\/\/ more efficient.\n\/\/\n\/\/ LOCKS_EXCLUDED(fh.inode)\nfunc (fh *FileHandle) Read(\n\tctx context.Context,\n\tdst []byte,\n\toffset int64) (n int, err error) {\n\terr = errors.New(\"TODO\")\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package k8s\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com\/nginxinc\/kubernetes-ingress\/internal\/configs\"\n\tnetworking \"k8s.io\/api\/networking\/v1beta1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/sets\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/validation\/field\"\n)\n\nconst (\n\tmergeableIngressTypeAnnotation       = \"nginx.org\/mergeable-ingress-type\"\n\tlbMethodAnnotation                   = \"nginx.org\/lb-method\"\n\thealthChecksAnnotation               = \"nginx.com\/health-checks\"\n\thealthChecksMandatoryAnnotation      = \"nginx.com\/health-checks-mandatory\"\n\thealthChecksMandatoryQueueAnnotation = \"nginx.com\/health-checks-mandatory-queue\"\n)\n\ntype annotationValidationContext struct {\n\tannotations map[string]string\n\tname        string\n\tvalue       string\n\tisPlus      bool\n\tfieldPath   *field.Path\n}\n\ntype annotationValidationFunc func(context *annotationValidationContext) field.ErrorList\ntype validatorFunc func(val string) error\n\nvar (\n\t\/\/ annotationValidations defines the various validations which will be applied in order to each ingress annotation.\n\t\/\/ If any specified validation fails, the remaining validations for that annotation will not be run.\n\tannotationValidations = map[string][]annotationValidationFunc{\n\t\tmergeableIngressTypeAnnotation: {\n\t\t\tvalidateRequiredAnnotation,\n\t\t\tvalidateMergeableIngressTypeAnnotation,\n\t\t},\n\t\tlbMethodAnnotation: {\n\t\t\tvalidateRequiredAnnotation,\n\t\t\tvalidateLBMethodAnnotation,\n\t\t},\n\t\thealthChecksAnnotation: {\n\t\t\tvalidateRequiredAnnotation,\n\t\t\tvalidatePlusOnlyAnnotation,\n\t\t\tvalidateBoolAnnotation,\n\t\t},\n\t\thealthChecksMandatoryAnnotation: {\n\t\t\tvalidateRelatedAnnotation(healthChecksAnnotation, validateIsTrue),\n\t\t\tvalidateRequiredAnnotation,\n\t\t\tvalidateBoolAnnotation,\n\t\t},\n\t\thealthChecksMandatoryQueueAnnotation: {\n\t\t\tvalidateRelatedAnnotation(healthChecksMandatoryAnnotation, validateIsTrue),\n\t\t\tvalidateRequiredAnnotation,\n\t\t\tvalidateNonNegativeIntAnnotation,\n\t\t},\n\t}\n\tannotationNames = sortedAnnotationNames(annotationValidations)\n)\n\nfunc sortedAnnotationNames(annotationValidations map[string][]annotationValidationFunc) []string {\n\tsortedNames := make([]string, 0)\n\tfor annotationName := range annotationValidations {\n\t\tsortedNames = append(sortedNames, annotationName)\n\t}\n\tsort.Strings(sortedNames)\n\treturn sortedNames\n}\n\n\/\/ validateIngress validate an Ingress resource with rules that our Ingress Controller enforces.\n\/\/ Note that the full validation of Ingress resources is done by Kubernetes.\nfunc validateIngress(ing *networking.Ingress, isPlus bool) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, validateIngressAnnotations(ing.Annotations, isPlus, field.NewPath(\"annotations\"))...)\n\n\tallErrs = append(allErrs, validateIngressSpec(&ing.Spec, field.NewPath(\"spec\"))...)\n\n\tif isMaster(ing) {\n\t\tallErrs = append(allErrs, validateMasterSpec(&ing.Spec, field.NewPath(\"spec\"))...)\n\t} else if isMinion(ing) {\n\t\tallErrs = append(allErrs, validateMinionSpec(&ing.Spec, field.NewPath(\"spec\"))...)\n\t}\n\n\treturn allErrs\n}\n\nfunc validateIngressAnnotations(annotations map[string]string, isPlus bool, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tfor _, name := range annotationNames {\n\t\tif value, nameExists := annotations[name]; nameExists {\n\t\t\tif validationFuncs, validationExists := annotationValidations[name]; validationExists {\n\t\t\t\tfor _, validationFunc := range validationFuncs {\n\t\t\t\t\tvalErrors := validationFunc(&annotationValidationContext{\n\t\t\t\t\t\tannotations: annotations,\n\t\t\t\t\t\tname:        name,\n\t\t\t\t\t\tvalue:       value,\n\t\t\t\t\t\tisPlus:      isPlus,\n\t\t\t\t\t\tfieldPath:   fieldPath.Child(name),\n\t\t\t\t\t})\n\t\t\t\t\tif len(valErrors) > 0 {\n\t\t\t\t\t\tallErrs = append(allErrs, valErrors...)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn allErrs\n}\n\nfunc validateRelatedAnnotation(name string, validator validatorFunc) annotationValidationFunc {\n\treturn func(context *annotationValidationContext) field.ErrorList {\n\t\tallErrs := field.ErrorList{}\n\t\tval, exists := context.annotations[name]\n\t\tif !exists {\n\t\t\treturn append(allErrs, field.Forbidden(context.fieldPath, fmt.Sprintf(\"related annotation %s: must be set\", name)))\n\t\t}\n\n\t\tif err := validator(val); err != nil {\n\t\t\treturn append(allErrs, field.Forbidden(context.fieldPath, fmt.Sprintf(\"related annotation %s: %s\", name, err.Error())))\n\t\t}\n\t\treturn allErrs\n\t}\n}\n\nfunc validateMergeableIngressTypeAnnotation(context *annotationValidationContext) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif context.value != \"master\" && context.value != \"minion\" {\n\t\treturn append(allErrs, field.Invalid(context.fieldPath, context.value, \"must be one of: 'master' or 'minion'\"))\n\t}\n\treturn allErrs\n}\n\nfunc validateLBMethodAnnotation(context *annotationValidationContext) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif context.isPlus {\n\t\tif _, err := configs.ParseLBMethodForPlus(context.value); err != nil {\n\t\t\treturn append(allErrs, field.Invalid(context.fieldPath, context.value, err.Error()))\n\t\t}\n\t} else {\n\t\tif _, err := configs.ParseLBMethod(context.value); err != nil {\n\t\t\treturn append(allErrs, field.Invalid(context.fieldPath, context.value, err.Error()))\n\t\t}\n\t}\n\treturn allErrs\n}\n\nfunc validateRequiredAnnotation(context *annotationValidationContext) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif context.value == \"\" {\n\t\treturn append(allErrs, field.Required(context.fieldPath, \"\"))\n\t}\n\treturn allErrs\n}\n\nfunc validatePlusOnlyAnnotation(context *annotationValidationContext) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif !context.isPlus {\n\t\treturn append(allErrs, field.Forbidden(context.fieldPath, \"annotation requires NGINX Plus\"))\n\t}\n\treturn allErrs\n}\n\nfunc validateBoolAnnotation(context *annotationValidationContext) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif _, err := configs.ParseBool(context.value); err != nil {\n\t\treturn append(allErrs, field.Invalid(context.fieldPath, context.value, \"must be a valid boolean\"))\n\t}\n\treturn allErrs\n}\n\nfunc validateNonNegativeIntAnnotation(context *annotationValidationContext) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif _, err := configs.ParseUint64(context.value); err != nil {\n\t\treturn append(allErrs, field.Invalid(context.fieldPath, context.value, \"must be a non-negative integer\"))\n\t}\n\treturn allErrs\n}\n\nfunc validateIsTrue(v string) error {\n\tb, err := configs.ParseBool(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !b {\n\t\treturn errors.New(\"must be true\")\n\t}\n\treturn nil\n}\n\nfunc validateIngressSpec(spec *networking.IngressSpec, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallHosts := sets.String{}\n\n\tif len(spec.Rules) == 0 {\n\t\treturn append(allErrs, field.Required(fieldPath.Child(\"rules\"), \"\"))\n\t}\n\n\tfor i, r := range spec.Rules {\n\t\tidxPath := fieldPath.Child(\"rules\").Index(i)\n\n\t\tif r.Host == \"\" {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"host\"), \"\"))\n\t\t} else if allHosts.Has(r.Host) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath.Child(\"host\"), r.Host))\n\t\t} else {\n\t\t\tallHosts.Insert(r.Host)\n\t\t}\n\t}\n\n\treturn allErrs\n}\n\nfunc validateMasterSpec(spec *networking.IngressSpec, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(spec.Rules) != 1 {\n\t\treturn append(allErrs, field.TooMany(fieldPath.Child(\"rules\"), len(spec.Rules), 1))\n\t}\n\n\t\/\/ the number of paths of the first rule of the spec must be 0\n\tif spec.Rules[0].HTTP != nil && len(spec.Rules[0].HTTP.Paths) > 0 {\n\t\tpathsField := fieldPath.Child(\"rules\").Index(0).Child(\"http\").Child(\"paths\")\n\t\treturn append(allErrs, field.TooMany(pathsField, len(spec.Rules[0].HTTP.Paths), 0))\n\t}\n\n\treturn allErrs\n}\n\nfunc validateMinionSpec(spec *networking.IngressSpec, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(spec.TLS) > 0 {\n\t\tallErrs = append(allErrs, field.TooMany(fieldPath.Child(\"tls\"), len(spec.TLS), 0))\n\t}\n\n\tif len(spec.Rules) != 1 {\n\t\treturn append(allErrs, field.TooMany(fieldPath.Child(\"rules\"), len(spec.Rules), 1))\n\t}\n\n\t\/\/ the number of paths of the first rule of the spec must be greater than 0\n\tif spec.Rules[0].HTTP == nil || len(spec.Rules[0].HTTP.Paths) == 0 {\n\t\tpathsField := fieldPath.Child(\"rules\").Index(0).Child(\"http\").Child(\"paths\")\n\t\treturn append(allErrs, field.Required(pathsField, \"must include at least one path\"))\n\t}\n\n\treturn allErrs\n}\n<commit_msg>Refactor validateIngressAnnotations func<commit_after>package k8s\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com\/nginxinc\/kubernetes-ingress\/internal\/configs\"\n\tnetworking \"k8s.io\/api\/networking\/v1beta1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/sets\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/validation\/field\"\n)\n\nconst (\n\tmergeableIngressTypeAnnotation       = \"nginx.org\/mergeable-ingress-type\"\n\tlbMethodAnnotation                   = \"nginx.org\/lb-method\"\n\thealthChecksAnnotation               = \"nginx.com\/health-checks\"\n\thealthChecksMandatoryAnnotation      = \"nginx.com\/health-checks-mandatory\"\n\thealthChecksMandatoryQueueAnnotation = \"nginx.com\/health-checks-mandatory-queue\"\n)\n\ntype annotationValidationContext struct {\n\tannotations map[string]string\n\tname        string\n\tvalue       string\n\tisPlus      bool\n\tfieldPath   *field.Path\n}\n\ntype annotationValidationFunc func(context *annotationValidationContext) field.ErrorList\ntype validatorFunc func(val string) error\n\nvar (\n\t\/\/ annotationValidations defines the various validations which will be applied in order to each ingress annotation.\n\t\/\/ If any specified validation fails, the remaining validations for that annotation will not be run.\n\tannotationValidations = map[string][]annotationValidationFunc{\n\t\tmergeableIngressTypeAnnotation: {\n\t\t\tvalidateRequiredAnnotation,\n\t\t\tvalidateMergeableIngressTypeAnnotation,\n\t\t},\n\t\tlbMethodAnnotation: {\n\t\t\tvalidateRequiredAnnotation,\n\t\t\tvalidateLBMethodAnnotation,\n\t\t},\n\t\thealthChecksAnnotation: {\n\t\t\tvalidateRequiredAnnotation,\n\t\t\tvalidatePlusOnlyAnnotation,\n\t\t\tvalidateBoolAnnotation,\n\t\t},\n\t\thealthChecksMandatoryAnnotation: {\n\t\t\tvalidateRelatedAnnotation(healthChecksAnnotation, validateIsTrue),\n\t\t\tvalidateRequiredAnnotation,\n\t\t\tvalidateBoolAnnotation,\n\t\t},\n\t\thealthChecksMandatoryQueueAnnotation: {\n\t\t\tvalidateRelatedAnnotation(healthChecksMandatoryAnnotation, validateIsTrue),\n\t\t\tvalidateRequiredAnnotation,\n\t\t\tvalidateNonNegativeIntAnnotation,\n\t\t},\n\t}\n\tannotationNames = sortedAnnotationNames(annotationValidations)\n)\n\nfunc sortedAnnotationNames(annotationValidations map[string][]annotationValidationFunc) []string {\n\tsortedNames := make([]string, 0)\n\tfor annotationName := range annotationValidations {\n\t\tsortedNames = append(sortedNames, annotationName)\n\t}\n\tsort.Strings(sortedNames)\n\treturn sortedNames\n}\n\n\/\/ validateIngress validate an Ingress resource with rules that our Ingress Controller enforces.\n\/\/ Note that the full validation of Ingress resources is done by Kubernetes.\nfunc validateIngress(ing *networking.Ingress, isPlus bool) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallErrs = append(allErrs, validateIngressAnnotations(ing.Annotations, isPlus, field.NewPath(\"annotations\"))...)\n\n\tallErrs = append(allErrs, validateIngressSpec(&ing.Spec, field.NewPath(\"spec\"))...)\n\n\tif isMaster(ing) {\n\t\tallErrs = append(allErrs, validateMasterSpec(&ing.Spec, field.NewPath(\"spec\"))...)\n\t} else if isMinion(ing) {\n\t\tallErrs = append(allErrs, validateMinionSpec(&ing.Spec, field.NewPath(\"spec\"))...)\n\t}\n\n\treturn allErrs\n}\n\nfunc validateIngressAnnotations(annotations map[string]string, isPlus bool, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tfor _, name := range annotationNames {\n\t\tif value, exists := annotations[name]; exists {\n\t\t\tallErrs = append(allErrs, validateIngressAnnotation(&annotationValidationContext{\n\t\t\t\tannotations: annotations,\n\t\t\t\tname:        name,\n\t\t\t\tvalue:       value,\n\t\t\t\tisPlus:      isPlus,\n\t\t\t\tfieldPath:   fieldPath.Child(name),\n\t\t\t})...)\n\t\t}\n\t}\n\treturn allErrs\n}\n\nfunc validateIngressAnnotation(context *annotationValidationContext) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif validationFuncs, exists := annotationValidations[context.name]; exists {\n\t\tfor _, validationFunc := range validationFuncs {\n\t\t\tvalErrors := validationFunc(context)\n\t\t\tif len(valErrors) > 0 {\n\t\t\t\tallErrs = append(allErrs, valErrors...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn allErrs\n}\n\nfunc validateRelatedAnnotation(name string, validator validatorFunc) annotationValidationFunc {\n\treturn func(context *annotationValidationContext) field.ErrorList {\n\t\tallErrs := field.ErrorList{}\n\t\tval, exists := context.annotations[name]\n\t\tif !exists {\n\t\t\treturn append(allErrs, field.Forbidden(context.fieldPath, fmt.Sprintf(\"related annotation %s: must be set\", name)))\n\t\t}\n\n\t\tif err := validator(val); err != nil {\n\t\t\treturn append(allErrs, field.Forbidden(context.fieldPath, fmt.Sprintf(\"related annotation %s: %s\", name, err.Error())))\n\t\t}\n\t\treturn allErrs\n\t}\n}\n\nfunc validateMergeableIngressTypeAnnotation(context *annotationValidationContext) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif context.value != \"master\" && context.value != \"minion\" {\n\t\treturn append(allErrs, field.Invalid(context.fieldPath, context.value, \"must be one of: 'master' or 'minion'\"))\n\t}\n\treturn allErrs\n}\n\nfunc validateLBMethodAnnotation(context *annotationValidationContext) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif context.isPlus {\n\t\tif _, err := configs.ParseLBMethodForPlus(context.value); err != nil {\n\t\t\treturn append(allErrs, field.Invalid(context.fieldPath, context.value, err.Error()))\n\t\t}\n\t} else {\n\t\tif _, err := configs.ParseLBMethod(context.value); err != nil {\n\t\t\treturn append(allErrs, field.Invalid(context.fieldPath, context.value, err.Error()))\n\t\t}\n\t}\n\treturn allErrs\n}\n\nfunc validateRequiredAnnotation(context *annotationValidationContext) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif context.value == \"\" {\n\t\treturn append(allErrs, field.Required(context.fieldPath, \"\"))\n\t}\n\treturn allErrs\n}\n\nfunc validatePlusOnlyAnnotation(context *annotationValidationContext) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif !context.isPlus {\n\t\treturn append(allErrs, field.Forbidden(context.fieldPath, \"annotation requires NGINX Plus\"))\n\t}\n\treturn allErrs\n}\n\nfunc validateBoolAnnotation(context *annotationValidationContext) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif _, err := configs.ParseBool(context.value); err != nil {\n\t\treturn append(allErrs, field.Invalid(context.fieldPath, context.value, \"must be a valid boolean\"))\n\t}\n\treturn allErrs\n}\n\nfunc validateNonNegativeIntAnnotation(context *annotationValidationContext) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\tif _, err := configs.ParseUint64(context.value); err != nil {\n\t\treturn append(allErrs, field.Invalid(context.fieldPath, context.value, \"must be a non-negative integer\"))\n\t}\n\treturn allErrs\n}\n\nfunc validateIsTrue(v string) error {\n\tb, err := configs.ParseBool(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !b {\n\t\treturn errors.New(\"must be true\")\n\t}\n\treturn nil\n}\n\nfunc validateIngressSpec(spec *networking.IngressSpec, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tallHosts := sets.String{}\n\n\tif len(spec.Rules) == 0 {\n\t\treturn append(allErrs, field.Required(fieldPath.Child(\"rules\"), \"\"))\n\t}\n\n\tfor i, r := range spec.Rules {\n\t\tidxPath := fieldPath.Child(\"rules\").Index(i)\n\n\t\tif r.Host == \"\" {\n\t\t\tallErrs = append(allErrs, field.Required(idxPath.Child(\"host\"), \"\"))\n\t\t} else if allHosts.Has(r.Host) {\n\t\t\tallErrs = append(allErrs, field.Duplicate(idxPath.Child(\"host\"), r.Host))\n\t\t} else {\n\t\t\tallHosts.Insert(r.Host)\n\t\t}\n\t}\n\n\treturn allErrs\n}\n\nfunc validateMasterSpec(spec *networking.IngressSpec, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(spec.Rules) != 1 {\n\t\treturn append(allErrs, field.TooMany(fieldPath.Child(\"rules\"), len(spec.Rules), 1))\n\t}\n\n\t\/\/ the number of paths of the first rule of the spec must be 0\n\tif spec.Rules[0].HTTP != nil && len(spec.Rules[0].HTTP.Paths) > 0 {\n\t\tpathsField := fieldPath.Child(\"rules\").Index(0).Child(\"http\").Child(\"paths\")\n\t\treturn append(allErrs, field.TooMany(pathsField, len(spec.Rules[0].HTTP.Paths), 0))\n\t}\n\n\treturn allErrs\n}\n\nfunc validateMinionSpec(spec *networking.IngressSpec, fieldPath *field.Path) field.ErrorList {\n\tallErrs := field.ErrorList{}\n\n\tif len(spec.TLS) > 0 {\n\t\tallErrs = append(allErrs, field.TooMany(fieldPath.Child(\"tls\"), len(spec.TLS), 0))\n\t}\n\n\tif len(spec.Rules) != 1 {\n\t\treturn append(allErrs, field.TooMany(fieldPath.Child(\"rules\"), len(spec.Rules), 1))\n\t}\n\n\t\/\/ the number of paths of the first rule of the spec must be greater than 0\n\tif spec.Rules[0].HTTP == nil || len(spec.Rules[0].HTTP.Paths) == 0 {\n\t\tpathsField := fieldPath.Child(\"rules\").Index(0).Child(\"http\").Child(\"paths\")\n\t\treturn append(allErrs, field.Required(pathsField, \"must include at least one path\"))\n\t}\n\n\treturn allErrs\n}\n<|endoftext|>"}
{"text":"<commit_before>package snmp\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/influxdata\/telegraf\"\n\t\"github.com\/sleepinggenius2\/gosmi\"\n\t\"github.com\/sleepinggenius2\/gosmi\/types\"\n)\n\n\/\/ must init, append path for each directory, load module for every file\n\/\/ or gosmi will fail without saying why\nvar m sync.Mutex\nvar once sync.Once\nvar cache = make(map[string]bool)\n\ntype MibLoader interface {\n\tloadModule(path string) error\n\tappendPath(path string)\n}\n\ntype GosmiMibLoader struct{}\n\nfunc (*GosmiMibLoader) appendPath(path string) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tgosmi.AppendPath(path)\n}\n\nfunc (*GosmiMibLoader) loadModule(path string) error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\t_, err := gosmi.LoadModule(path)\n\treturn err\n}\n\nfunc ClearCache() {\n\tcache = make(map[string]bool)\n}\n\n\/\/will give all found folders to gosmi and load in all modules found in the folders\nfunc LoadMibsFromPath(paths []string, log telegraf.Logger, loader MibLoader) error {\n\tfolders, err := walkPaths(paths, log)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, path := range folders {\n\t\tloader.appendPath(path)\n\t\tmodules, err := ioutil.ReadDir(path)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Can't read directory %v\", modules)\n\t\t}\n\n\t\tfor _, info := range modules {\n\t\t\tif info.Mode()&os.ModeSymlink != 0 {\n\t\t\t\ttarget, err := filepath.EvalSymlinks(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warnf(\"Bad symbolic link %v\", target)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tinfo, err = os.Lstat(filepath.Join(path, target))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warnf(\"Couldn't stat target %v\", target)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tpath = target\n\t\t\t}\n\t\t\tif info.Mode().IsRegular() {\n\t\t\t\terr := loader.loadModule(info.Name())\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warnf(\"module %v could not be loaded\", info.Name())\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/should walk the paths given and find all folders\nfunc walkPaths(paths []string, log telegraf.Logger) ([]string, error) {\n\tonce.Do(gosmi.Init)\n\tfolders := []string{}\n\n\tfor _, mibPath := range paths {\n\t\t\/\/ Check if we loaded that path already and skip it if so\n\t\tm.Lock()\n\t\tcached := cache[mibPath]\n\t\tcache[mibPath] = true\n\t\tm.Unlock()\n\t\tif cached {\n\t\t\tcontinue\n\t\t}\n\n\t\terr := filepath.Walk(mibPath, func(path string, info os.FileInfo, err error) error {\n\t\t\tif info == nil {\n\t\t\t\tlog.Warnf(\"No mibs found\")\n\t\t\t\tif os.IsNotExist(err) {\n\t\t\t\t\tlog.Warnf(\"MIB path doesn't exist: %q\", mibPath)\n\t\t\t\t} else if err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif info.Mode()&os.ModeSymlink != 0 {\n\t\t\t\ttarget, err := filepath.EvalSymlinks(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warnf(\"Could not evaluate link %v\", target)\n\t\t\t\t}\n\t\t\t\tinfo, err = os.Lstat(target)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warnf(\"Couldn't stat target %v\", path)\n\t\t\t\t}\n\t\t\t\tpath = target\n\t\t\t}\n\t\t\tif info.IsDir() {\n\t\t\t\tfolders = append(folders, path)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn folders, fmt.Errorf(\"Filepath %q could not be walked: %v\", mibPath, err)\n\t\t}\n\t}\n\treturn folders, nil\n}\n\n\/\/ The following is for snmp_trap\ntype MibEntry struct {\n\tMibName string\n\tOidText string\n}\n\nfunc TrapLookup(oid string) (e MibEntry, err error) {\n\tvar givenOid types.Oid\n\tif givenOid, err = types.OidFromString(oid); err != nil {\n\t\treturn e, fmt.Errorf(\"could not convert OID %s: %w\", oid, err)\n\t}\n\n\t\/\/ Get node name\n\tvar node gosmi.SmiNode\n\tif node, err = gosmi.GetNodeByOID(givenOid); err != nil {\n\t\treturn e, err\n\t}\n\te.OidText = node.Name\n\n\t\/\/ Add not found OID part\n\tif !givenOid.Equals(node.Oid) {\n\t\te.OidText += \".\" + givenOid[len(node.Oid):].String()\n\t}\n\n\t\/\/ Get module name\n\tmodule := node.GetModule()\n\tif module.Name != \"<well-known>\" {\n\t\te.MibName = module.Name\n\t}\n\n\treturn e, nil\n}\n\n\/\/ The following is for snmp\n\nfunc GetIndex(oidNum string, mibPrefix string, node gosmi.SmiNode) (col []string, tagOids map[string]struct{}, err error) {\n\t\/\/ first attempt to get the table's tags\n\ttagOids = map[string]struct{}{}\n\n\t\/\/ mimcks grabbing INDEX {} that is returned from snmptranslate -Td MibName\n\tfor _, index := range node.GetIndex() {\n\t\t\/\/nolint:staticcheck \/\/assaignment to nil map to keep backwards compatibilty\n\t\ttagOids[mibPrefix+index.Name] = struct{}{}\n\t}\n\n\t\/\/ grabs all columns from the table\n\t\/\/ mimmicks grabbing everything returned from snmptable -Ch -Cl -c public 127.0.0.1 oidFullName\n\t_, col = node.GetColumns()\n\n\treturn col, tagOids, nil\n}\n\n\/\/nolint:revive \/\/Too many return variable but necessary\nfunc SnmpTranslateCall(oid string) (mibName string, oidNum string, oidText string, conversion string, node gosmi.SmiNode, err error) {\n\tvar out gosmi.SmiNode\n\tvar end string\n\tif strings.ContainsAny(oid, \"::\") {\n\t\t\/\/ split given oid\n\t\t\/\/ for example RFC1213-MIB::sysUpTime.0\n\t\ts := strings.SplitN(oid, \"::\", 2)\n\t\t\/\/ moduleName becomes RFC1213\n\t\tmoduleName := s[0]\n\t\tmodule, err := gosmi.GetModule(moduleName)\n\t\tif err != nil {\n\t\t\treturn oid, oid, oid, oid, gosmi.SmiNode{}, err\n\t\t}\n\t\tif s[1] == \"\" {\n\t\t\treturn \"\", oid, oid, oid, gosmi.SmiNode{}, fmt.Errorf(\"cannot parse %v\\n\", oid)\n\t\t}\n\t\t\/\/ node becomes sysUpTime.0\n\t\tnode := s[1]\n\t\tif strings.ContainsAny(node, \".\") {\n\t\t\ts = strings.SplitN(node, \".\", 2)\n\t\t\t\/\/ node becomes sysUpTime\n\t\t\tnode = s[0]\n\t\t\tend = \".\" + s[1]\n\t\t}\n\n\t\tout, err = module.GetNode(node)\n\t\tif err != nil {\n\t\t\treturn oid, oid, oid, oid, out, err\n\t\t}\n\n\t\tif oidNum = out.RenderNumeric(); oidNum == \"\" {\n\t\t\treturn oid, oid, oid, oid, out, fmt.Errorf(\"cannot make %v numeric, please ensure all imported mibs are in the path\", oid)\n\t\t}\n\n\t\toidNum = \".\" + oidNum + end\n\t} else if strings.ContainsAny(oid, \"abcdefghijklnmopqrstuvwxyz\") {\n\t\t\/\/handle mixed oid ex. .iso.2.3\n\t\ts := strings.Split(oid, \".\")\n\t\tfor i := range s {\n\t\t\tif strings.ContainsAny(s[i], \"abcdefghijklmnopqrstuvwxyz\") {\n\t\t\t\tout, err = gosmi.GetNode(s[i])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn oid, oid, oid, oid, out, err\n\t\t\t\t}\n\t\t\t\ts[i] = out.RenderNumeric()\n\t\t\t}\n\t\t}\n\t\toidNum = strings.Join(s, \".\")\n\t\tout, _ = gosmi.GetNodeByOID(types.OidMustFromString(oidNum))\n\t} else {\n\t\tout, err = gosmi.GetNodeByOID(types.OidMustFromString(oid))\n\t\toidNum = oid\n\t\t\/\/ ensure modules are loaded or node will be empty (might not error)\n\t\t\/\/ do not return the err as the oid is numeric and telegraf can continue\n\t\t\/\/nolint:nilerr\n\t\tif err != nil || out.Name == \"iso\" {\n\t\t\treturn oid, oid, oid, oid, out, nil\n\t\t}\n\t}\n\n\ttc := out.GetSubtree()\n\n\tfor i := range tc {\n\t\t\/\/ case where the mib doesn't have a conversion so Type struct will be nil\n\t\t\/\/ prevents seg fault\n\t\tif tc[i].Type == nil {\n\t\t\tbreak\n\t\t}\n\t\tswitch tc[i].Type.Name {\n\t\tcase \"MacAddress\", \"PhysAddress\":\n\t\t\tconversion = \"hwaddr\"\n\t\tcase \"InetAddressIPv4\", \"InetAddressIPv6\", \"InetAddress\", \"IPSIpAddress\":\n\t\t\tconversion = \"ipaddr\"\n\t\t}\n\t}\n\n\toidText = out.RenderQualified()\n\ti := strings.Index(oidText, \"::\")\n\tif i == -1 {\n\t\treturn \"\", oid, oid, oid, out, fmt.Errorf(\"not found\")\n\t}\n\tmibName = oidText[:i]\n\toidText = oidText[i+2:] + end\n\n\treturn mibName, oidNum, oidText, conversion, out, nil\n}\n<commit_msg>fix: log err when loading mibs (#10735)<commit_after>package snmp\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/influxdata\/telegraf\"\n\t\"github.com\/sleepinggenius2\/gosmi\"\n\t\"github.com\/sleepinggenius2\/gosmi\/types\"\n)\n\n\/\/ must init, append path for each directory, load module for every file\n\/\/ or gosmi will fail without saying why\nvar m sync.Mutex\nvar once sync.Once\nvar cache = make(map[string]bool)\n\ntype MibLoader interface {\n\tloadModule(path string) error\n\tappendPath(path string)\n}\n\ntype GosmiMibLoader struct{}\n\nfunc (*GosmiMibLoader) appendPath(path string) {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tgosmi.AppendPath(path)\n}\n\nfunc (*GosmiMibLoader) loadModule(path string) error {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\t_, err := gosmi.LoadModule(path)\n\treturn err\n}\n\nfunc ClearCache() {\n\tcache = make(map[string]bool)\n}\n\n\/\/will give all found folders to gosmi and load in all modules found in the folders\nfunc LoadMibsFromPath(paths []string, log telegraf.Logger, loader MibLoader) error {\n\tfolders, err := walkPaths(paths, log)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, path := range folders {\n\t\tloader.appendPath(path)\n\t\tmodules, err := ioutil.ReadDir(path)\n\t\tif err != nil {\n\t\t\tlog.Warnf(\"Can't read directory %v\", modules)\n\t\t}\n\n\t\tfor _, info := range modules {\n\t\t\tif info.Mode()&os.ModeSymlink != 0 {\n\t\t\t\ttarget, err := filepath.EvalSymlinks(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warnf(\"Couldn't evaluate symbolic links for %v: %v\", target, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tinfo, err = os.Lstat(filepath.Join(path, target))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warnf(\"Couldn't stat target %v: %v\", target, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tpath = target\n\t\t\t}\n\t\t\tif info.Mode().IsRegular() {\n\t\t\t\terr := loader.loadModule(info.Name())\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warnf(\"Couldn't load module %v: %v\", info.Name(), err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/should walk the paths given and find all folders\nfunc walkPaths(paths []string, log telegraf.Logger) ([]string, error) {\n\tonce.Do(gosmi.Init)\n\tfolders := []string{}\n\n\tfor _, mibPath := range paths {\n\t\t\/\/ Check if we loaded that path already and skip it if so\n\t\tm.Lock()\n\t\tcached := cache[mibPath]\n\t\tcache[mibPath] = true\n\t\tm.Unlock()\n\t\tif cached {\n\t\t\tcontinue\n\t\t}\n\n\t\terr := filepath.Walk(mibPath, func(path string, info os.FileInfo, err error) error {\n\t\t\tif info == nil {\n\t\t\t\tlog.Warnf(\"No mibs found\")\n\t\t\t\tif os.IsNotExist(err) {\n\t\t\t\t\tlog.Warnf(\"MIB path doesn't exist: %q\", mibPath)\n\t\t\t\t} else if err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif info.Mode()&os.ModeSymlink != 0 {\n\t\t\t\ttarget, err := filepath.EvalSymlinks(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warnf(\"Couldn't evaluate symbolic links for %v: %v\", target, err)\n\t\t\t\t}\n\t\t\t\tinfo, err = os.Lstat(target)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warnf(\"Couldn't stat target %v: %v\", target, err)\n\t\t\t\t}\n\t\t\t\tpath = target\n\t\t\t}\n\t\t\tif info.IsDir() {\n\t\t\t\tfolders = append(folders, path)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn folders, fmt.Errorf(\"Couldn't walk path %q: %v\", mibPath, err)\n\t\t}\n\t}\n\treturn folders, nil\n}\n\n\/\/ The following is for snmp_trap\ntype MibEntry struct {\n\tMibName string\n\tOidText string\n}\n\nfunc TrapLookup(oid string) (e MibEntry, err error) {\n\tvar givenOid types.Oid\n\tif givenOid, err = types.OidFromString(oid); err != nil {\n\t\treturn e, fmt.Errorf(\"could not convert OID %s: %w\", oid, err)\n\t}\n\n\t\/\/ Get node name\n\tvar node gosmi.SmiNode\n\tif node, err = gosmi.GetNodeByOID(givenOid); err != nil {\n\t\treturn e, err\n\t}\n\te.OidText = node.Name\n\n\t\/\/ Add not found OID part\n\tif !givenOid.Equals(node.Oid) {\n\t\te.OidText += \".\" + givenOid[len(node.Oid):].String()\n\t}\n\n\t\/\/ Get module name\n\tmodule := node.GetModule()\n\tif module.Name != \"<well-known>\" {\n\t\te.MibName = module.Name\n\t}\n\n\treturn e, nil\n}\n\n\/\/ The following is for snmp\n\nfunc GetIndex(oidNum string, mibPrefix string, node gosmi.SmiNode) (col []string, tagOids map[string]struct{}, err error) {\n\t\/\/ first attempt to get the table's tags\n\ttagOids = map[string]struct{}{}\n\n\t\/\/ mimcks grabbing INDEX {} that is returned from snmptranslate -Td MibName\n\tfor _, index := range node.GetIndex() {\n\t\t\/\/nolint:staticcheck \/\/assaignment to nil map to keep backwards compatibilty\n\t\ttagOids[mibPrefix+index.Name] = struct{}{}\n\t}\n\n\t\/\/ grabs all columns from the table\n\t\/\/ mimmicks grabbing everything returned from snmptable -Ch -Cl -c public 127.0.0.1 oidFullName\n\t_, col = node.GetColumns()\n\n\treturn col, tagOids, nil\n}\n\n\/\/nolint:revive \/\/Too many return variable but necessary\nfunc SnmpTranslateCall(oid string) (mibName string, oidNum string, oidText string, conversion string, node gosmi.SmiNode, err error) {\n\tvar out gosmi.SmiNode\n\tvar end string\n\tif strings.ContainsAny(oid, \"::\") {\n\t\t\/\/ split given oid\n\t\t\/\/ for example RFC1213-MIB::sysUpTime.0\n\t\ts := strings.SplitN(oid, \"::\", 2)\n\t\t\/\/ moduleName becomes RFC1213\n\t\tmoduleName := s[0]\n\t\tmodule, err := gosmi.GetModule(moduleName)\n\t\tif err != nil {\n\t\t\treturn oid, oid, oid, oid, gosmi.SmiNode{}, err\n\t\t}\n\t\tif s[1] == \"\" {\n\t\t\treturn \"\", oid, oid, oid, gosmi.SmiNode{}, fmt.Errorf(\"cannot parse %v\\n\", oid)\n\t\t}\n\t\t\/\/ node becomes sysUpTime.0\n\t\tnode := s[1]\n\t\tif strings.ContainsAny(node, \".\") {\n\t\t\ts = strings.SplitN(node, \".\", 2)\n\t\t\t\/\/ node becomes sysUpTime\n\t\t\tnode = s[0]\n\t\t\tend = \".\" + s[1]\n\t\t}\n\n\t\tout, err = module.GetNode(node)\n\t\tif err != nil {\n\t\t\treturn oid, oid, oid, oid, out, err\n\t\t}\n\n\t\tif oidNum = out.RenderNumeric(); oidNum == \"\" {\n\t\t\treturn oid, oid, oid, oid, out, fmt.Errorf(\"cannot make %v numeric, please ensure all imported mibs are in the path\", oid)\n\t\t}\n\n\t\toidNum = \".\" + oidNum + end\n\t} else if strings.ContainsAny(oid, \"abcdefghijklnmopqrstuvwxyz\") {\n\t\t\/\/handle mixed oid ex. .iso.2.3\n\t\ts := strings.Split(oid, \".\")\n\t\tfor i := range s {\n\t\t\tif strings.ContainsAny(s[i], \"abcdefghijklmnopqrstuvwxyz\") {\n\t\t\t\tout, err = gosmi.GetNode(s[i])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn oid, oid, oid, oid, out, err\n\t\t\t\t}\n\t\t\t\ts[i] = out.RenderNumeric()\n\t\t\t}\n\t\t}\n\t\toidNum = strings.Join(s, \".\")\n\t\tout, _ = gosmi.GetNodeByOID(types.OidMustFromString(oidNum))\n\t} else {\n\t\tout, err = gosmi.GetNodeByOID(types.OidMustFromString(oid))\n\t\toidNum = oid\n\t\t\/\/ ensure modules are loaded or node will be empty (might not error)\n\t\t\/\/ do not return the err as the oid is numeric and telegraf can continue\n\t\t\/\/nolint:nilerr\n\t\tif err != nil || out.Name == \"iso\" {\n\t\t\treturn oid, oid, oid, oid, out, nil\n\t\t}\n\t}\n\n\ttc := out.GetSubtree()\n\n\tfor i := range tc {\n\t\t\/\/ case where the mib doesn't have a conversion so Type struct will be nil\n\t\t\/\/ prevents seg fault\n\t\tif tc[i].Type == nil {\n\t\t\tbreak\n\t\t}\n\t\tswitch tc[i].Type.Name {\n\t\tcase \"MacAddress\", \"PhysAddress\":\n\t\t\tconversion = \"hwaddr\"\n\t\tcase \"InetAddressIPv4\", \"InetAddressIPv6\", \"InetAddress\", \"IPSIpAddress\":\n\t\t\tconversion = \"ipaddr\"\n\t\t}\n\t}\n\n\toidText = out.RenderQualified()\n\ti := strings.Index(oidText, \"::\")\n\tif i == -1 {\n\t\treturn \"\", oid, oid, oid, out, fmt.Errorf(\"not found\")\n\t}\n\tmibName = oidText[:i]\n\toidText = oidText[i+2:] + end\n\n\treturn mibName, oidNum, oidText, conversion, out, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package franklinreiter\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/sourcekris\/goRsaTool\/keys\"\n\t\"github.com\/sourcekris\/goRsaTool\/ln\"\n\n\tfmp \"github.com\/sourcekris\/goflint\"\n)\n\n\/\/ name is the name of this attack.\nconst name = \"franklin reiter related message attack\"\n\n\/\/ Attack implements the franklin reiter related message attack against two keys.\nfunc Attack(ks []*keys.RSA) error {\n\tif len(ks) != 2 {\n\t\treturn fmt.Errorf(\"%s requires exactly 2 keys to work - got %d\", name, len(ks))\n\t}\n\n\tif ks[0].KnownPlainText == nil || ks[1].KnownPlainText == nil {\n\t\treturn fmt.Errorf(\"%s requires each key has a corresponding known plaintext component\", name)\n\t}\n\n\tif ks[0].CipherText == nil || ks[1].CipherText == nil {\n\t\treturn fmt.Errorf(\"%s requires each key has a corresponding ciphertext\", name)\n\t}\n\n\tc1 := ln.BytesToNumber(ks[0].CipherText)\n\tc2 := ln.BytesToNumber(ks[1].CipherText)\n\ts1 := ln.BytesToNumber(ks[0].KnownPlainText)\n\ts2 := ln.BytesToNumber(ks[1].KnownPlainText)\n\te := ks[0].Key.PublicKey.E.GetInt()\n\tn := ks[0].Key.N\n\n\t\/\/ f = (x-s1+s2)^e - c1\n\tf := fmp.NewFmpzModPoly(n).SetCoeffUI(1, 1)\n\tf.Sub(f, fmp.NewFmpzModPoly(n).SetCoeff(0, s2)).Add(f, fmp.NewFmpzModPoly(n).SetCoeff(0, s1)).Pow(f, e)\n\tf.Sub(f, fmp.NewFmpzModPoly(n).SetCoeff(0, c1))\n\n\t\/\/ g = x^e-c2\n\tg := fmp.NewFmpzModPoly(n).SetCoeffUI(1, 1)\n\tg.Pow(g, e).Sub(g, fmp.NewFmpzModPoly(n).SetCoeff(0, c2))\n\n\ta := fmp.NewFmpzModPoly(f.GetMod()).Set(f)\n\tb := fmp.NewFmpzModPoly(g.GetMod()).Set(g)\n\n\tzero := fmp.NewFmpzModPoly(n).Zero()\n\trp := fmp.NewFmpzModPoly(n)\n\n\tif ks[0].Verbose {\n\t\tlog.Printf(\"%s beginning, this can sometimes crash, try it again if it does.\", name)\n\t}\n\n\tvar r *fmp.FmpzModPoly\n\tfor {\n\t\t_, r = a.DivRem(b)\n\n\t\tif r.Equal(zero) {\n\t\t\tco0 := rp.GetCoeff(0)\n\t\t\tco1 := rp.GetCoeff(1)\n\n\t\t\tq, _ := fmp.NewFmpzModPoly(n).SetCoeff(0, ln.BigOne).DivRem(fmp.NewFmpzModPoly(n).SetCoeff(0, co1))\n\t\t\tq.MulScalar(q, ln.BigNOne).MulScalar(q, co0)\n\t\t\tks[0].PlainText = ln.NumberToBytes(q.GetCoeff(0))\n\t\t\treturn nil\n\t\t}\n\n\t\trp.Set(r)\n\t\ta.Set(b)\n\t\tb.Set(r)\n\t}\n}\n<commit_msg>reorg signature attack module<commit_after>package franklinreiter\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/sourcekris\/goRsaTool\/keys\"\n\t\"github.com\/sourcekris\/goRsaTool\/ln\"\n\n\tfmp \"github.com\/sourcekris\/goflint\"\n)\n\n\/\/ name is the name of this attack.\nconst name = \"franklin reiter related message attack\"\n\ntype sigAttack struct {\n\tcs []*fmp.Fmpz\n\tss []*fmp.Fmpz\n\tn  *fmp.Fmpz\n\te  int\n}\n\n\/\/ attempt runs the attack attempt itself.\nfunc (s *sigAttack) attempt(v bool) []byte {\n\t\/\/ f = (x-s1+s2)^e - c1\n\tf := fmp.NewFmpzModPoly(s.n).SetCoeffUI(1, 1)\n\tf.Sub(f, fmp.NewFmpzModPoly(s.n).SetCoeff(0, s.ss[1])).Add(f, fmp.NewFmpzModPoly(s.n).SetCoeff(0, s.ss[0])).Pow(f, s.e)\n\tf.Sub(f, fmp.NewFmpzModPoly(s.n).SetCoeff(0, s.cs[0]))\n\n\t\/\/ g = x^e-c2\n\tg := fmp.NewFmpzModPoly(s.n).SetCoeffUI(1, 1)\n\tg.Pow(g, s.e).Sub(g, fmp.NewFmpzModPoly(s.n).SetCoeff(0, s.cs[1]))\n\n\ta := fmp.NewFmpzModPoly(f.GetMod()).Set(f)\n\tb := fmp.NewFmpzModPoly(g.GetMod()).Set(g)\n\n\tzero := fmp.NewFmpzModPoly(s.n).Zero()\n\trp := fmp.NewFmpzModPoly(s.n)\n\n\tif v {\n\t\tlog.Printf(\"%s beginning, this can sometimes crash, try it again if it does.\", name)\n\t}\n\n\tvar r *fmp.FmpzModPoly\n\tfor {\n\t\t_, r = a.DivRem(b)\n\n\t\tif r.Equal(zero) {\n\t\t\tco0 := rp.GetCoeff(0)\n\t\t\tco1 := rp.GetCoeff(1)\n\n\t\t\tq, _ := fmp.NewFmpzModPoly(s.n).SetCoeff(0, ln.BigOne).DivRem(fmp.NewFmpzModPoly(s.n).SetCoeff(0, co1))\n\t\t\tq.MulScalar(q, ln.BigNOne).MulScalar(q, co0)\n\t\t\treturn ln.NumberToBytes(q.GetCoeff(0))\n\t\t}\n\n\t\trp.Set(r)\n\t\ta.Set(b)\n\t\tb.Set(r)\n\t}\n}\n\n\/\/ Attack implements the franklin reiter related message attack against two keys.\nfunc Attack(ks []*keys.RSA) error {\n\tif len(ks) != 2 {\n\t\treturn fmt.Errorf(\"%s requires exactly 2 keys to work - got %d\", name, len(ks))\n\t}\n\n\tif ks[0].KnownPlainText == nil || ks[1].KnownPlainText == nil {\n\t\treturn fmt.Errorf(\"%s requires each key has a corresponding known plaintext component\", name)\n\t}\n\n\tif ks[0].CipherText == nil || ks[1].CipherText == nil {\n\t\treturn fmt.Errorf(\"%s requires each key has a corresponding ciphertext\", name)\n\t}\n\n\tsa := &sigAttack{n: ks[0].Key.N, e: ks[0].Key.PublicKey.E.GetInt()}\n\tfor i := 0; i < 2; i++ {\n\t\tsa.ss = append(sa.ss, ln.BytesToNumber(ks[i].KnownPlainText))\n\t\tsa.cs = append(sa.cs, ln.BytesToNumber(ks[i].CipherText))\n\t}\n\n\tif res := sa.attempt(ks[0].Verbose); res != nil {\n\t\tks[0].PlainText = res\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"%s failed to recover the plaintext\", name)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"encoding\/json\"\n    \"flag\"\n    \"fmt\"\n    \"io\/ioutil\"\n    \"log\"\n    \"net\"\n    \"net\/http\"\n    \"net\/url\"\n    \"os\"\n    \"os\/signal\"\n    \"strings\"\n    \"sync\"\n    \"syscall\"\n    \"time\"\n    \"tokenbucket\"\n)\n\nconst _VERSION string = \"0.2.0\"\n\ntype Route struct {\n    Bandwidth int64 `json:\"bandwidth\"`    \/\/ Bits per second\n    Buffersize uint64 `json:\"buffersize\"` \/\/ Bytes\n    Inspect bool `json:\"inspect\"`         \/\/ True = proxy, false = reverse proxy\n    Src string `json:\"src\"`\n    Dst []string `json:\"dst\"`\n}\n\ntype Itinerary struct {\n    Map map[string]Route\n}\n\nfunc sigHandler(ch *chan os.Signal) {\n    sig := <-*ch\n    fmt.Println(\"Captured sig\", sig)\n    os.Exit(3)\n}\n\nfunc main() {\n    sigs := make(chan os.Signal, 1)\n    signal.Notify(sigs,\n                  syscall.SIGHUP,\n                  syscall.SIGINT,\n                  syscall.SIGQUIT,\n                  syscall.SIGABRT,\n                  syscall.SIGKILL,\n                  syscall.SIGSEGV,\n                  syscall.SIGTERM)\n\n    log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)\n\n    itineraryFile := flag.String(\"itinerary\", \"itinerary.json\", \"file containing source and destination routes\")\n    flag.Usage = func() {\n        fmt.Fprintf(os.Stderr, \"version %s\\n\", _VERSION)\n        fmt.Fprintln(os.Stderr, \"usage:\")\n        flag.PrintDefaults()\n    }\n    flag.Parse()\n\n    itinerary := loadItinerary(itineraryFile)\n\n    for _, m := range itinerary.Map {\n        go intercept(m)\n    }\n\n    sigHandler(&sigs)\n}\n\nfunc loadItinerary(fileName *string) Itinerary {\n\n    file, _ := os.Open(*fileName)\n    decoder := json.NewDecoder(file)\n    itinerary := Itinerary{}\n    err := decoder.Decode(&itinerary)\n    if err != nil {\n        log.Println(err.Error())\n    }\n\n    return itinerary\n}\n\nfunc intercept(route Route) {\n    listener, err := net.Listen(\"tcp\", route.Src)\n    if err == nil {\n        log.Println(\"Listening on\", route.Src)\n        i := 0\n        count := 0\n\n        for {\n            con, err := listener.Accept()\n            if err == nil {\n                count = count + 1\n\n                if route.Inspect { \/\/ Proxy mode\n                    go findHttpRoute(count, con, route.Bandwidth \/ 8, route.Buffersize)\n                } else { \/\/ Load balancer mode\n                    \/\/ Round-robin for now\n                    go findRoute(count, con, route.Dst[i], route.Bandwidth \/ 8, route.Buffersize)\n                    i = (i + 1) % len(route.Dst)\n                }\n            } else {\n                log.Println(err.Error())\n            }\n        }\n        listener.Close()\n    } else {\n        log.Println(err.Error())\n    }\n}\n\nfunc parseHttpRequestUri(header *http.Request) string {\n    var uri string\n    if header.Method == \"HEAD\" || header.Method == \"PUT\" {\n        url, err := url.Parse(header.RequestURI)\n\n        if err == nil {\n            if strings.ContainsAny(url.Host, \":\") {\n                uri = url.Host\n            } else {\n                switch url.Scheme {\n                    case \"http\":\n                        uri = url.Host + \":80\"\n                    case \"https\":\n                        uri = url.Host + \":443\"\n                    default:\n                        uri = url.Host\n                }\n            }\n        } else {\n            log.Println(err.Error())\n        }\n    } else if header.Method == \"CONNECT\" {\n        uri = header.RequestURI\n    }\n\n    return uri\n}\n\nfunc findHttpRoute(id int, src net.Conn, bandwidth int64, bufferSize uint64) {\n    buf := make([]byte, 65536)\n    size, err := src.Read(buf) \/\/ Assume one read will include entire HTTP header\n\n    if err == nil {\n        reader := bufio.NewReader(strings.NewReader(string(buf[0:size])))\n        header, _ := http.ReadRequest(reader)\n\n        dstAddr := parseHttpRequestUri(header)\n        dst, err := net.Dial(\"tcp\", dstAddr)\n\n        if err == nil && header.Method == \"CONNECT\" {\n            body := \"\"\n            rsp := &http.Response {\n                Status:        \"200 OK\",\n                StatusCode:    200,\n                Proto:         \"HTTP\/1.1\",\n                ProtoMajor:    1,\n                ProtoMinor:    1,\n                Body:          ioutil.NopCloser(bytes.NewBufferString(body)),\n                ContentLength: int64(len(body)),\n                Request:       nil,\n                Header:        make(http.Header, 0),\n            }\n            buff := bytes.NewBuffer(nil)\n            rsp.Write(buff)\n            src.Write(buff.Bytes())\n            startDetour(id, src, dst, bandwidth, bufferSize)\n        } else {\n            src.Close()\n            log.Println(err.Error())\n        }\n    } else {\n        src.Close()\n        log.Println(err.Error())\n    }\n}\n\nfunc findRoute(id int, src net.Conn, dstAddr string, bandwidth int64, bufferSize uint64) {\n    dst, err := net.Dial(\"tcp\", dstAddr)\n\n    if err == nil {\n        startDetour(id, src, dst, bandwidth, bufferSize)\n    } else {\n        src.Close()\n        log.Println(err.Error())\n    }\n}\n\nfunc startDetour(id int, src net.Conn, dst net.Conn, bandwidth int64, bufferSize uint64) {\n    log.Println(\"Opening route\", id, \":\", src.RemoteAddr().String(), \"to\", dst.RemoteAddr().String())\n\n    var wg sync.WaitGroup\n    wg.Add(1)\n    go reroute(&wg, src, dst, bandwidth, bufferSize)\n    reroute(nil, dst, src, bandwidth, bufferSize)\n    wg.Wait()\n\n    log.Println(\"Closing route\", id, \":\", src.RemoteAddr().String(), \"to\", dst.RemoteAddr().String())\n}\n\nfunc reroute(wg *sync.WaitGroup, src net.Conn, dst net.Conn, bandwidth int64, bufferSize uint64) {\n    tb := tokenbucket.New(uint64(bandwidth), 10 * uint64(bandwidth))\n    buf := make([]byte, bufferSize)\n    defer src.Close()\n    defer dst.Close()\n\n    for {\n        bytes := tb.Remove(bufferSize)\n        if bytes < bufferSize {\n            tb.Return(bytes)\n            time.Sleep(1 * time.Millisecond)\n            continue\n        }\n\n        size, err := src.Read(buf)\n        if err == nil {\n            dst.Write(buf[0:size])\n            if size < int(bufferSize) {\n                tb.Return(bufferSize - uint64(size))\n            }\n        } else {\n            break\n        }\n    }\n\n    if wg != nil {\n        wg.Done()\n    }\n}\n<commit_msg>fixed HTTP\/S routes<commit_after>package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"encoding\/json\"\n    \"flag\"\n    \"fmt\"\n    \"io\/ioutil\"\n    \"log\"\n    \"net\"\n    \"net\/http\"\n    \"net\/url\"\n    \"os\"\n    \"os\/signal\"\n    \"strings\"\n    \"sync\"\n    \"syscall\"\n    \"time\"\n    \"tokenbucket\"\n)\n\nconst _VERSION string = \"0.2.0\"\n\ntype Route struct {\n    Bandwidth int64 `json:\"bandwidth\"`    \/\/ Bits per second\n    Buffersize uint64 `json:\"buffersize\"` \/\/ Bytes\n    Inspect bool `json:\"inspect\"`         \/\/ True = proxy, false = reverse proxy\n    Src string `json:\"src\"`\n    Dst []string `json:\"dst\"`\n}\n\ntype Itinerary struct {\n    Map map[string]Route\n}\n\nfunc sigHandler(ch *chan os.Signal) {\n    sig := <-*ch\n    fmt.Println(\"Captured sig\", sig)\n    os.Exit(3)\n}\n\nfunc main() {\n    sigs := make(chan os.Signal, 1)\n    signal.Notify(sigs,\n                  syscall.SIGHUP,\n                  syscall.SIGINT,\n                  syscall.SIGQUIT,\n                  syscall.SIGABRT,\n                  syscall.SIGKILL,\n                  syscall.SIGSEGV,\n                  syscall.SIGTERM)\n\n    log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)\n\n    itineraryFile := flag.String(\"itinerary\", \"itinerary.json\", \"file containing source and destination routes\")\n    flag.Usage = func() {\n        fmt.Fprintf(os.Stderr, \"version %s\\n\", _VERSION)\n        fmt.Fprintln(os.Stderr, \"usage:\")\n        flag.PrintDefaults()\n    }\n    flag.Parse()\n\n    itinerary := loadItinerary(itineraryFile)\n\n    for _, m := range itinerary.Map {\n        go intercept(m)\n    }\n\n    sigHandler(&sigs)\n}\n\nfunc loadItinerary(fileName *string) Itinerary {\n\n    file, _ := os.Open(*fileName)\n    decoder := json.NewDecoder(file)\n    itinerary := Itinerary{}\n    err := decoder.Decode(&itinerary)\n    if err != nil {\n        log.Println(err.Error())\n    }\n\n    return itinerary\n}\n\nfunc intercept(route Route) {\n    listener, err := net.Listen(\"tcp\", route.Src)\n    if err == nil {\n        log.Println(\"Listening on\", route.Src)\n        i := 0\n        count := 0\n\n        for {\n            con, err := listener.Accept()\n            if err == nil {\n                count = count + 1\n\n                if route.Inspect { \/\/ Proxy mode\n                    go findHttpRoute(count, con, route.Bandwidth \/ 8, route.Buffersize)\n                } else { \/\/ Load balancer mode\n                    \/\/ Round-robin for now\n                    go findRoute(count, con, route.Dst[i], route.Bandwidth \/ 8, route.Buffersize)\n                    i = (i + 1) % len(route.Dst)\n                }\n            } else {\n                log.Println(err.Error())\n            }\n        }\n        listener.Close()\n    } else {\n        log.Println(err.Error())\n    }\n}\n\nfunc parseHttpRequestUri(header *http.Request) string {\n    var uri string\n    if header.Method == \"HEAD\" || header.Method == \"PUT\" {\n        url, err := url.Parse(header.RequestURI)\n\n        if err == nil {\n            if strings.ContainsAny(url.Host, \":\") {\n                uri = url.Host\n            } else {\n                switch url.Scheme {\n                    case \"http\":\n                        uri = url.Host + \":80\"\n                    case \"https\":\n                        uri = url.Host + \":443\"\n                    default:\n                        uri = url.Host\n                }\n            }\n        } else {\n            log.Println(err.Error())\n        }\n    } else if header.Method == \"CONNECT\" {\n        uri = header.RequestURI\n    }\n\n    return uri\n}\n\nfunc findHttpRoute(id int, src net.Conn, bandwidth int64, bufferSize uint64) {\n    buf := make([]byte, 65536)\n    size, err := src.Read(buf) \/\/ Assume one read will include entire HTTP header\n\n    if err == nil {\n        reader := bufio.NewReader(strings.NewReader(string(buf[0:size])))\n        header, _ := http.ReadRequest(reader)\n\n        dstAddr := parseHttpRequestUri(header)\n        dst, err := net.Dial(\"tcp\", dstAddr)\n\n        if err == nil {\n            if header.Method == \"CONNECT\" {\n                body := \"\"\n                rsp := &http.Response {\n                    Status:        \"200 OK\",\n                    StatusCode:    200,\n                    Proto:         \"HTTP\/1.1\",\n                    ProtoMajor:    1,\n                    ProtoMinor:    1,\n                    Body:          ioutil.NopCloser(bytes.NewBufferString(body)),\n                    ContentLength: int64(len(body)),\n                    Request:       nil,\n                    Header:        make(http.Header, 0),\n                }\n                rspBuf := bytes.NewBuffer(nil)\n                rsp.Write(rspBuf)\n                src.Write(rspBuf.Bytes())\n            } else {\n                dst.Write(buf[0:size])\n            }\n            startDetour(id, src, dst, bandwidth, bufferSize)\n        } else {\n            src.Close()\n            log.Println(err.Error())\n        }\n    } else {\n        src.Close()\n        log.Println(err.Error())\n    }\n}\n\nfunc findRoute(id int, src net.Conn, dstAddr string, bandwidth int64, bufferSize uint64) {\n    dst, err := net.Dial(\"tcp\", dstAddr)\n\n    if err == nil {\n        startDetour(id, src, dst, bandwidth, bufferSize)\n    } else {\n        src.Close()\n        log.Println(err.Error())\n    }\n}\n\nfunc startDetour(id int, src net.Conn, dst net.Conn, bandwidth int64, bufferSize uint64) {\n    log.Println(\"Opening route\", id, \":\", src.RemoteAddr().String(), \"to\", dst.RemoteAddr().String())\n\n    var wg sync.WaitGroup\n    wg.Add(1)\n    go reroute(&wg, src, dst, bandwidth, bufferSize)\n    reroute(nil, dst, src, bandwidth, bufferSize)\n    wg.Wait()\n\n    log.Println(\"Closing route\", id, \":\", src.RemoteAddr().String(), \"to\", dst.RemoteAddr().String())\n}\n\nfunc reroute(wg *sync.WaitGroup, src net.Conn, dst net.Conn, bandwidth int64, bufferSize uint64) {\n    tb := tokenbucket.New(uint64(bandwidth), 10 * uint64(bandwidth))\n    buf := make([]byte, bufferSize)\n    defer src.Close()\n    defer dst.Close()\n\n    for {\n        bytes := tb.Remove(bufferSize)\n        if bytes < bufferSize {\n            tb.Return(bytes)\n            time.Sleep(1 * time.Millisecond)\n            continue\n        }\n\n        size, err := src.Read(buf)\n        if err == nil {\n            dst.Write(buf[0:size])\n            if size < int(bufferSize) {\n                tb.Return(bufferSize - uint64(size))\n            }\n        } else {\n            break\n        }\n    }\n\n    if wg != nil {\n        wg.Done()\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>package airplay\n\nimport \"github.com\/armon\/mdns\"\n\n\/\/ A Device is an AirPlay Device.\ntype Device struct {\n\tName string\n\tAddr string\n\tPort int\n}\n\n\/\/ Devices returns all AirPlay devices in LAN.\nfunc Devices() []Device {\n\tdevices := []Device{}\n\tentriesCh := make(chan *mdns.ServiceEntry, 4)\n\tdefer close(entriesCh)\n\n\tgo func() {\n\t\tfor entry := range entriesCh {\n\t\t\tdevices = append(\n\t\t\t\tdevices,\n\t\t\t\tDevice{\n\t\t\t\t\tName: entry.Name,\n\t\t\t\t\tAddr: entry.Addr.String(),\n\t\t\t\t\tPort: entry.Port,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t}()\n\n\tmdns.Lookup(\"_airplay._tcp\", entriesCh)\n\n\treturn devices\n}\n<commit_msg>Support IPv6 address AirServer returns.<commit_after>package airplay\n\nimport \"github.com\/armon\/mdns\"\n\n\/\/ A Device is an AirPlay Device.\ntype Device struct {\n\tName string\n\tAddr string\n\tPort int\n}\n\n\/\/ Devices returns all AirPlay devices in LAN.\nfunc Devices() []Device {\n\tdevices := []Device{}\n\tentriesCh := make(chan *mdns.ServiceEntry, 4)\n\tdefer close(entriesCh)\n\n\tgo func() {\n\t\tfor entry := range entriesCh {\n\t\t\tip := entry.Addr\n\t\t\tvar addr string\n\n\t\t\tif ip.To16() != nil {\n\t\t\t\taddr = \"[\" + ip.String() + \"]\"\n\t\t\t} else {\n\t\t\t\taddr = ip.String()\n\t\t\t}\n\n\t\t\tdevices = append(\n\t\t\t\tdevices,\n\t\t\t\tDevice{\n\t\t\t\t\tName: entry.Name,\n\t\t\t\t\tAddr: addr,\n\t\t\t\t\tPort: entry.Port,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t}()\n\n\tmdns.Lookup(\"_airplay._tcp\", entriesCh)\n\n\treturn devices\n}\n<|endoftext|>"}
{"text":"<commit_before>package handlers\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\tctxu \"github.com\/docker\/distribution\/context\"\n\t\"github.com\/gorilla\/mux\"\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/docker\/notary\/server\/errors\"\n\t\"github.com\/docker\/notary\/server\/snapshot\"\n\t\"github.com\/docker\/notary\/server\/storage\"\n\t\"github.com\/docker\/notary\/server\/timestamp\"\n\t\"github.com\/docker\/notary\/tuf\/data\"\n\t\"github.com\/docker\/notary\/tuf\/signed\"\n\t\"github.com\/docker\/notary\/tuf\/validation\"\n\t\"github.com\/docker\/notary\/utils\"\n)\n\n\/\/ MainHandler is the default handler for the server\nfunc MainHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\t\/\/ For now it only supports `GET`\n\tif r.Method != \"GET\" {\n\t\treturn errors.ErrGenericNotFound.WithDetail(nil)\n\t}\n\n\tif _, err := w.Write([]byte(\"{}\")); err != nil {\n\t\treturn errors.ErrUnknown.WithDetail(err)\n\t}\n\treturn nil\n}\n\n\/\/ AtomicUpdateHandler will accept multiple TUF files and ensure that the storage\n\/\/ backend is atomically updated with all the new records.\nfunc AtomicUpdateHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\tdefer r.Body.Close()\n\tvars := mux.Vars(r)\n\treturn atomicUpdateHandler(ctx, w, r, vars)\n}\n\nfunc atomicUpdateHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {\n\tgun := vars[\"imageName\"]\n\ts := ctx.Value(\"metaStore\")\n\tlogger := ctxu.GetLoggerWithField(ctx, gun, \"gun\")\n\tstore, ok := s.(storage.MetaStore)\n\tif !ok {\n\t\tlogger.Error(\"500 POST unable to retrieve storage\")\n\t\treturn errors.ErrNoStorage.WithDetail(nil)\n\t}\n\tcryptoServiceVal := ctx.Value(\"cryptoService\")\n\tcryptoService, ok := cryptoServiceVal.(signed.CryptoService)\n\tif !ok {\n\t\tlogger.Error(\"500 POST unable to retrieve signing service\")\n\t\treturn errors.ErrNoCryptoService.WithDetail(nil)\n\t}\n\n\treader, err := r.MultipartReader()\n\tif err != nil {\n\t\tlogger.Info(\"400 POST unable to parse TUF data\")\n\t\treturn errors.ErrMalformedUpload.WithDetail(nil)\n\t}\n\tvar updates []storage.MetaUpdate\n\tfor {\n\t\tpart, err := reader.NextPart()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\trole := strings.TrimSuffix(part.FileName(), \".json\")\n\t\tif role == \"\" {\n\t\t\tlogger.Info(\"400 POST empty role\")\n\t\t\treturn errors.ErrNoFilename.WithDetail(nil)\n\t\t} else if !data.ValidRole(role) {\n\t\t\tlogger.Infof(\"400 POST invalid role: %s\", role)\n\t\t\treturn errors.ErrInvalidRole.WithDetail(role)\n\t\t}\n\t\tmeta := &data.SignedMeta{}\n\t\tvar input []byte\n\t\tinBuf := bytes.NewBuffer(input)\n\t\tdec := json.NewDecoder(io.TeeReader(part, inBuf))\n\t\terr = dec.Decode(meta)\n\t\tif err != nil {\n\t\t\tlogger.Info(\"400 POST malformed update JSON\")\n\t\t\treturn errors.ErrMalformedJSON.WithDetail(nil)\n\t\t}\n\t\tversion := meta.Signed.Version\n\t\tupdates = append(updates, storage.MetaUpdate{\n\t\t\tRole:    role,\n\t\t\tVersion: version,\n\t\t\tData:    inBuf.Bytes(),\n\t\t})\n\t}\n\tupdates, err = validateUpdate(cryptoService, gun, updates, store)\n\tif err != nil {\n\t\tserializable, serializableError := validation.NewSerializableError(err)\n\t\tif serializableError != nil {\n\t\t\tlogger.Info(\"400 POST error validating update\")\n\t\t\treturn errors.ErrInvalidUpdate.WithDetail(nil)\n\t\t}\n\t\treturn errors.ErrInvalidUpdate.WithDetail(serializable)\n\t}\n\terr = store.UpdateMany(gun, updates)\n\tif err != nil {\n\t\t\/\/ If we have an old version error, surface to user with error code\n\t\tif _, ok := err.(storage.ErrOldVersion); ok {\n\t\t\tlogger.Info(\"400 POST old version error\")\n\t\t\treturn errors.ErrOldVersion.WithDetail(err)\n\t\t}\n\t\t\/\/ More generic storage update error, possibly due to attempted rollback\n\t\tlogger.Errorf(\"500 POST error applying update request: %v\", err)\n\t\treturn errors.ErrUpdating.WithDetail(nil)\n\t}\n\treturn nil\n}\n\n\/\/ GetHandler returns the json for a specified role and GUN.\nfunc GetHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\tdefer r.Body.Close()\n\tvars := mux.Vars(r)\n\treturn getHandler(ctx, w, r, vars)\n}\n\nfunc getHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {\n\tgun := vars[\"imageName\"]\n\tchecksum := vars[\"checksum\"]\n\ttufRole := vars[\"tufRole\"]\n\ts := ctx.Value(\"metaStore\")\n\n\tlogger := ctxu.GetLoggerWithField(ctx, gun, \"gun\")\n\n\tstore, ok := s.(storage.MetaStore)\n\tif !ok {\n\t\tlogger.Error(\"500 GET: no storage exists\")\n\t\treturn errors.ErrNoStorage.WithDetail(nil)\n\t}\n\n\tlastModified, output, err := getRole(ctx, store, gun, tufRole, checksum)\n\tif err != nil {\n\t\tlogger.Infof(\"404 GET %s role\", tufRole)\n\t\treturn err\n\t}\n\tif lastModified != nil {\n\t\t\/\/ This shouldn't always be true, but in case it is nil, and the last modified headers\n\t\t\/\/ are not set, the cache control handler should set the last modified date to the beginning\n\t\t\/\/ of time.\n\t\tutils.SetLastModifiedHeader(w.Header(), *lastModified)\n\t} else {\n\t\tlogrus.Warnf(\"Got bytes out for %s's %s (checksum: %s), but missing lastModified date\",\n\t\t\tgun, tufRole, checksum)\n\t}\n\n\tw.Write(output)\n\treturn nil\n}\n\n\/\/ DeleteHandler deletes all data for a GUN. A 200 responses indicates success.\nfunc DeleteHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\ts := ctx.Value(\"metaStore\")\n\tstore, ok := s.(storage.MetaStore)\n\tif !ok {\n\t\tlogrus.Error(\"500 DELETE repository: no storage exists\")\n\t\treturn errors.ErrNoStorage.WithDetail(nil)\n\t}\n\tvars := mux.Vars(r)\n\tgun := vars[\"imageName\"]\n\tlogger := ctxu.GetLoggerWithField(ctx, gun, \"gun\")\n\terr := store.Delete(gun)\n\tif err != nil {\n\t\tlogger.Error(\"500 DELETE repository\")\n\t\treturn errors.ErrUnknown.WithDetail(err)\n\t}\n\treturn nil\n}\n\n\/\/ GetKeyHandler returns a public key for the specified role, creating a new key-pair\n\/\/ it if it doesn't yet exist\nfunc GetKeyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\tdefer r.Body.Close()\n\tvars := mux.Vars(r)\n\treturn getKeyHandler(ctx, w, r, vars)\n}\n\nfunc getKeyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {\n\tgun, ok := vars[\"imageName\"]\n\tif !ok || gun == \"\" {\n\t\tlogrus.Info(\"400 GET no gun in request\")\n\t\treturn errors.ErrUnknown.WithDetail(\"no gun\")\n\t}\n\n\tlogger := ctxu.GetLoggerWithField(ctx, gun, \"gun\")\n\n\trole, ok := vars[\"tufRole\"]\n\tif !ok || role == \"\" {\n\t\tlogger.Info(\"400 GET no role in request\")\n\t\treturn errors.ErrUnknown.WithDetail(\"no role\")\n\t}\n\n\ts := ctx.Value(\"metaStore\")\n\tstore, ok := s.(storage.MetaStore)\n\tif !ok || store == nil {\n\t\tlogger.Error(\"500 GET storage not configured\")\n\t\treturn errors.ErrNoStorage.WithDetail(nil)\n\t}\n\tc := ctx.Value(\"cryptoService\")\n\tcrypto, ok := c.(signed.CryptoService)\n\tif !ok || crypto == nil {\n\t\tlogger.Error(\"500 GET crypto service not configured\")\n\t\treturn errors.ErrNoCryptoService.WithDetail(nil)\n\t}\n\talgo := ctx.Value(\"keyAlgorithm\")\n\tkeyAlgo, ok := algo.(string)\n\tif !ok || keyAlgo == \"\" {\n\t\tlogger.Error(\"500 GET key algorithm not configured\")\n\t\treturn errors.ErrNoKeyAlgorithm.WithDetail(nil)\n\t}\n\tkeyAlgorithm := keyAlgo\n\n\tvar (\n\t\tkey data.PublicKey\n\t\terr error\n\t)\n\tswitch role {\n\tcase data.CanonicalTimestampRole:\n\t\tkey, err = timestamp.GetOrCreateTimestampKey(gun, store, crypto, keyAlgorithm)\n\tcase data.CanonicalSnapshotRole:\n\t\tkey, err = snapshot.GetOrCreateSnapshotKey(gun, store, crypto, keyAlgorithm)\n\tdefault:\n\t\tlogger.Infof(\"400 GET %s key: %v\", role, err)\n\t\treturn errors.ErrInvalidRole.WithDetail(role)\n\t}\n\tif err != nil {\n\t\tlogger.Errorf(\"500 GET %s key: %v\", role, err)\n\t\treturn errors.ErrUnknown.WithDetail(err)\n\t}\n\n\tout, err := json.Marshal(key)\n\tif err != nil {\n\t\tlogger.Errorf(\"500 GET %s key\", role)\n\t\treturn errors.ErrUnknown.WithDetail(err)\n\t}\n\tlogger.Debugf(\"200 GET %s key\", role)\n\tw.Write(out)\n\treturn nil\n}\n\n\/\/ NotFoundHandler is used as a generic catch all handler to return the ErrMetadataNotFound\n\/\/ 404 response\nfunc NotFoundHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\treturn errors.ErrMetadataNotFound.WithDetail(nil)\n}\n<commit_msg>Change logrus to logger where possible<commit_after>package handlers\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n\n\tctxu \"github.com\/docker\/distribution\/context\"\n\t\"github.com\/gorilla\/mux\"\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/docker\/notary\/server\/errors\"\n\t\"github.com\/docker\/notary\/server\/snapshot\"\n\t\"github.com\/docker\/notary\/server\/storage\"\n\t\"github.com\/docker\/notary\/server\/timestamp\"\n\t\"github.com\/docker\/notary\/tuf\/data\"\n\t\"github.com\/docker\/notary\/tuf\/signed\"\n\t\"github.com\/docker\/notary\/tuf\/validation\"\n\t\"github.com\/docker\/notary\/utils\"\n)\n\n\/\/ MainHandler is the default handler for the server\nfunc MainHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\t\/\/ For now it only supports `GET`\n\tif r.Method != \"GET\" {\n\t\treturn errors.ErrGenericNotFound.WithDetail(nil)\n\t}\n\n\tif _, err := w.Write([]byte(\"{}\")); err != nil {\n\t\treturn errors.ErrUnknown.WithDetail(err)\n\t}\n\treturn nil\n}\n\n\/\/ AtomicUpdateHandler will accept multiple TUF files and ensure that the storage\n\/\/ backend is atomically updated with all the new records.\nfunc AtomicUpdateHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\tdefer r.Body.Close()\n\tvars := mux.Vars(r)\n\treturn atomicUpdateHandler(ctx, w, r, vars)\n}\n\nfunc atomicUpdateHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {\n\tgun := vars[\"imageName\"]\n\ts := ctx.Value(\"metaStore\")\n\tlogger := ctxu.GetLoggerWithField(ctx, gun, \"gun\")\n\tstore, ok := s.(storage.MetaStore)\n\tif !ok {\n\t\tlogger.Error(\"500 POST unable to retrieve storage\")\n\t\treturn errors.ErrNoStorage.WithDetail(nil)\n\t}\n\tcryptoServiceVal := ctx.Value(\"cryptoService\")\n\tcryptoService, ok := cryptoServiceVal.(signed.CryptoService)\n\tif !ok {\n\t\tlogger.Error(\"500 POST unable to retrieve signing service\")\n\t\treturn errors.ErrNoCryptoService.WithDetail(nil)\n\t}\n\n\treader, err := r.MultipartReader()\n\tif err != nil {\n\t\tlogger.Info(\"400 POST unable to parse TUF data\")\n\t\treturn errors.ErrMalformedUpload.WithDetail(nil)\n\t}\n\tvar updates []storage.MetaUpdate\n\tfor {\n\t\tpart, err := reader.NextPart()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\trole := strings.TrimSuffix(part.FileName(), \".json\")\n\t\tif role == \"\" {\n\t\t\tlogger.Info(\"400 POST empty role\")\n\t\t\treturn errors.ErrNoFilename.WithDetail(nil)\n\t\t} else if !data.ValidRole(role) {\n\t\t\tlogger.Infof(\"400 POST invalid role: %s\", role)\n\t\t\treturn errors.ErrInvalidRole.WithDetail(role)\n\t\t}\n\t\tmeta := &data.SignedMeta{}\n\t\tvar input []byte\n\t\tinBuf := bytes.NewBuffer(input)\n\t\tdec := json.NewDecoder(io.TeeReader(part, inBuf))\n\t\terr = dec.Decode(meta)\n\t\tif err != nil {\n\t\t\tlogger.Info(\"400 POST malformed update JSON\")\n\t\t\treturn errors.ErrMalformedJSON.WithDetail(nil)\n\t\t}\n\t\tversion := meta.Signed.Version\n\t\tupdates = append(updates, storage.MetaUpdate{\n\t\t\tRole:    role,\n\t\t\tVersion: version,\n\t\t\tData:    inBuf.Bytes(),\n\t\t})\n\t}\n\tupdates, err = validateUpdate(cryptoService, gun, updates, store)\n\tif err != nil {\n\t\tserializable, serializableError := validation.NewSerializableError(err)\n\t\tif serializableError != nil {\n\t\t\tlogger.Info(\"400 POST error validating update\")\n\t\t\treturn errors.ErrInvalidUpdate.WithDetail(nil)\n\t\t}\n\t\treturn errors.ErrInvalidUpdate.WithDetail(serializable)\n\t}\n\terr = store.UpdateMany(gun, updates)\n\tif err != nil {\n\t\t\/\/ If we have an old version error, surface to user with error code\n\t\tif _, ok := err.(storage.ErrOldVersion); ok {\n\t\t\tlogger.Info(\"400 POST old version error\")\n\t\t\treturn errors.ErrOldVersion.WithDetail(err)\n\t\t}\n\t\t\/\/ More generic storage update error, possibly due to attempted rollback\n\t\tlogger.Errorf(\"500 POST error applying update request: %v\", err)\n\t\treturn errors.ErrUpdating.WithDetail(nil)\n\t}\n\treturn nil\n}\n\n\/\/ GetHandler returns the json for a specified role and GUN.\nfunc GetHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\tdefer r.Body.Close()\n\tvars := mux.Vars(r)\n\treturn getHandler(ctx, w, r, vars)\n}\n\nfunc getHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {\n\tgun := vars[\"imageName\"]\n\tchecksum := vars[\"checksum\"]\n\ttufRole := vars[\"tufRole\"]\n\ts := ctx.Value(\"metaStore\")\n\n\tlogger := ctxu.GetLoggerWithField(ctx, gun, \"gun\")\n\n\tstore, ok := s.(storage.MetaStore)\n\tif !ok {\n\t\tlogger.Error(\"500 GET: no storage exists\")\n\t\treturn errors.ErrNoStorage.WithDetail(nil)\n\t}\n\n\tlastModified, output, err := getRole(ctx, store, gun, tufRole, checksum)\n\tif err != nil {\n\t\tlogger.Infof(\"404 GET %s role\", tufRole)\n\t\treturn err\n\t}\n\tif lastModified != nil {\n\t\t\/\/ This shouldn't always be true, but in case it is nil, and the last modified headers\n\t\t\/\/ are not set, the cache control handler should set the last modified date to the beginning\n\t\t\/\/ of time.\n\t\tutils.SetLastModifiedHeader(w.Header(), *lastModified)\n\t} else {\n\t\tlogger.Warnf(\"Got bytes out for %s's %s (checksum: %s), but missing lastModified date\",\n\t\t\tgun, tufRole, checksum)\n\t}\n\n\tw.Write(output)\n\treturn nil\n}\n\n\/\/ DeleteHandler deletes all data for a GUN. A 200 responses indicates success.\nfunc DeleteHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\tvars := mux.Vars(r)\n\tgun := vars[\"imageName\"]\n\tlogger := ctxu.GetLoggerWithField(ctx, gun, \"gun\")\n\ts := ctx.Value(\"metaStore\")\n\tstore, ok := s.(storage.MetaStore)\n\tif !ok {\n\t\tlogger.Error(\"500 DELETE repository: no storage exists\")\n\t\treturn errors.ErrNoStorage.WithDetail(nil)\n\t}\n\terr := store.Delete(gun)\n\tif err != nil {\n\t\tlogger.Error(\"500 DELETE repository\")\n\t\treturn errors.ErrUnknown.WithDetail(err)\n\t}\n\treturn nil\n}\n\n\/\/ GetKeyHandler returns a public key for the specified role, creating a new key-pair\n\/\/ it if it doesn't yet exist\nfunc GetKeyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\tdefer r.Body.Close()\n\tvars := mux.Vars(r)\n\treturn getKeyHandler(ctx, w, r, vars)\n}\n\nfunc getKeyHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {\n\tgun, ok := vars[\"imageName\"]\n\tlogger := ctxu.GetLoggerWithField(ctx, gun, \"gun\")\n\tif !ok || gun == \"\" {\n\t\tlogger.Info(\"400 GET no gun in request\")\n\t\treturn errors.ErrUnknown.WithDetail(\"no gun\")\n\t}\n\n\trole, ok := vars[\"tufRole\"]\n\tif !ok || role == \"\" {\n\t\tlogger.Info(\"400 GET no role in request\")\n\t\treturn errors.ErrUnknown.WithDetail(\"no role\")\n\t}\n\n\ts := ctx.Value(\"metaStore\")\n\tstore, ok := s.(storage.MetaStore)\n\tif !ok || store == nil {\n\t\tlogger.Error(\"500 GET storage not configured\")\n\t\treturn errors.ErrNoStorage.WithDetail(nil)\n\t}\n\tc := ctx.Value(\"cryptoService\")\n\tcrypto, ok := c.(signed.CryptoService)\n\tif !ok || crypto == nil {\n\t\tlogger.Error(\"500 GET crypto service not configured\")\n\t\treturn errors.ErrNoCryptoService.WithDetail(nil)\n\t}\n\talgo := ctx.Value(\"keyAlgorithm\")\n\tkeyAlgo, ok := algo.(string)\n\tif !ok || keyAlgo == \"\" {\n\t\tlogger.Error(\"500 GET key algorithm not configured\")\n\t\treturn errors.ErrNoKeyAlgorithm.WithDetail(nil)\n\t}\n\tkeyAlgorithm := keyAlgo\n\n\tvar (\n\t\tkey data.PublicKey\n\t\terr error\n\t)\n\tswitch role {\n\tcase data.CanonicalTimestampRole:\n\t\tkey, err = timestamp.GetOrCreateTimestampKey(gun, store, crypto, keyAlgorithm)\n\tcase data.CanonicalSnapshotRole:\n\t\tkey, err = snapshot.GetOrCreateSnapshotKey(gun, store, crypto, keyAlgorithm)\n\tdefault:\n\t\tlogger.Infof(\"400 GET %s key: %v\", role, err)\n\t\treturn errors.ErrInvalidRole.WithDetail(role)\n\t}\n\tif err != nil {\n\t\tlogger.Errorf(\"500 GET %s key: %v\", role, err)\n\t\treturn errors.ErrUnknown.WithDetail(err)\n\t}\n\n\tout, err := json.Marshal(key)\n\tif err != nil {\n\t\tlogger.Errorf(\"500 GET %s key\", role)\n\t\treturn errors.ErrUnknown.WithDetail(err)\n\t}\n\tlogger.Debugf(\"200 GET %s key\", role)\n\tw.Write(out)\n\treturn nil\n}\n\n\/\/ NotFoundHandler is used as a generic catch all handler to return the ErrMetadataNotFound\n\/\/ 404 response\nfunc NotFoundHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\treturn errors.ErrMetadataNotFound.WithDetail(nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package heroku\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/remind101\/empire\"\n\t\"github.com\/remind101\/empire\/pkg\/heroku\"\n\t\"github.com\/remind101\/empire\/pkg\/hijack\"\n\t\"github.com\/remind101\/empire\/pkg\/stdcopy\"\n\tstreamhttp \"github.com\/remind101\/empire\/pkg\/stream\/http\"\n\t\"github.com\/remind101\/empire\/pkg\/timex\"\n\t\"github.com\/remind101\/empire\/server\/auth\"\n)\n\ntype Dyno heroku.Dyno\n\nfunc newDyno(task *empire.Task) *Dyno {\n\treturn &Dyno{\n\t\tCommand:   task.Command.String(),\n\t\tType:      task.Type,\n\t\tName:      task.Name,\n\t\tHost:      heroku.Host{Id: task.Host.ID},\n\t\tState:     task.State,\n\t\tSize:      task.Constraints.String(),\n\t\tUpdatedAt: task.UpdatedAt,\n\t}\n}\n\nfunc newDynos(tasks []*empire.Task) []*Dyno {\n\tdynos := make([]*Dyno, len(tasks))\n\n\tfor i := 0; i < len(tasks); i++ {\n\t\tdynos[i] = newDyno(tasks[i])\n\t}\n\n\treturn dynos\n}\n\nfunc (h *Server) GetProcesses(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\n\ta, err := h.findApp(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Retrieve tasks\n\tjs, err := h.Tasks(ctx, a)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw.WriteHeader(200)\n\treturn Encode(w, newDynos(js))\n}\n\ntype PostProcessForm struct {\n\tCommand string              `json:\"command\"`\n\tAttach  bool                `json:\"attach\"`\n\tEnv     map[string]string   `json:\"env\"`\n\tSize    *empire.Constraints `json:\"size\"`\n}\n\nfunc (h *Server) PostProcess(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\n\tvar form PostProcessForm\n\n\ta, err := h.findApp(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm, err := findMessage(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := Decode(r, &form); err != nil {\n\t\treturn err\n\t}\n\n\tcommand, err := empire.ParseCommand(form.Command)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\topts := empire.RunOpts{\n\t\tUser:        auth.UserFromContext(ctx),\n\t\tApp:         a,\n\t\tCommand:     command,\n\t\tEnv:         form.Env,\n\t\tConstraints: form.Size,\n\t\tMessage:     m,\n\t}\n\n\tif form.Attach {\n\t\tmultiplex := r.Header.Get(\"X-Multiplex\") != \"\"\n\n\t\theader := http.Header{}\n\t\tif multiplex {\n\t\t\theader.Set(\"Content-Type\", \"application\/vnd.empire.stdcopy-stream\")\n\t\t} else {\n\t\t\theader.Set(\"Content-Type\", \"application\/vnd.empire.raw-stream\")\n\t\t}\n\n\t\tstream := &hijack.HijackReadWriter{\n\t\t\tResponse: w,\n\t\t\tHeader:   header,\n\t\t}\n\t\tdefer stream.Close()\n\t\t\/\/ Prevent the ELB idle connection timeout to close the connection.\n\t\tdefer close(streamhttp.Heartbeat(stream, 10*time.Second))\n\n\t\topts.Stdin = stream\n\n\t\tif multiplex {\n\t\t\topts.Stdout = stdcopy.NewStdWriter(stream, stdcopy.Stdout)\n\t\t\topts.Stderr = stdcopy.NewStdWriter(stream, stdcopy.Stderr)\n\t\t} else {\n\t\t\t\/\/ Backwards compatibility for older clients that don't\n\t\t\t\/\/ know how to de-multiplex a stdcopy stream. For these\n\t\t\t\/\/ clients, stdout\/stderr are merged together.\n\t\t\topts.Stdout = stream\n\t\t\topts.Stderr = stream\n\t\t}\n\n\t\tif err := h.Run(ctx, opts); err != nil {\n\t\t\tif stream.Hijacked {\n\t\t\t\tfmt.Fprintf(stream, \"%v\\r\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif err := h.Run(ctx, opts); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdyno := &heroku.Dyno{\n\t\t\tName:      \"run\",\n\t\t\tCommand:   form.Command,\n\t\t\tCreatedAt: timex.Now(),\n\t\t}\n\n\t\tw.WriteHeader(201)\n\t\treturn Encode(w, dyno)\n\t}\n\n\treturn nil\n}\n\nfunc (h *Server) DeleteProcesses(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\n\tvars := Vars(r)\n\tpid := vars[\"pid\"]\n\n\tif vars[\"ptype\"] != \"\" {\n\t\treturn errNotImplemented(\"Restarting a process type is currently not implemented.\")\n\t}\n\n\ta, err := h.findApp(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm, err := findMessage(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := h.Restart(ctx, empire.RestartOpts{\n\t\tUser:    auth.UserFromContext(ctx),\n\t\tApp:     a,\n\t\tPID:     pid,\n\t\tMessage: m,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\treturn NoContent(w)\n}\n<commit_msg>Fix emp run lockup in 0.13 (#1125)<commit_after>package heroku\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/remind101\/empire\"\n\t\"github.com\/remind101\/empire\/pkg\/heroku\"\n\t\"github.com\/remind101\/empire\/pkg\/hijack\"\n\t\"github.com\/remind101\/empire\/pkg\/stdcopy\"\n\t\"github.com\/remind101\/empire\/pkg\/timex\"\n\t\"github.com\/remind101\/empire\/server\/auth\"\n)\n\ntype Dyno heroku.Dyno\n\nfunc newDyno(task *empire.Task) *Dyno {\n\treturn &Dyno{\n\t\tCommand:   task.Command.String(),\n\t\tType:      task.Type,\n\t\tName:      task.Name,\n\t\tHost:      heroku.Host{Id: task.Host.ID},\n\t\tState:     task.State,\n\t\tSize:      task.Constraints.String(),\n\t\tUpdatedAt: task.UpdatedAt,\n\t}\n}\n\nfunc newDynos(tasks []*empire.Task) []*Dyno {\n\tdynos := make([]*Dyno, len(tasks))\n\n\tfor i := 0; i < len(tasks); i++ {\n\t\tdynos[i] = newDyno(tasks[i])\n\t}\n\n\treturn dynos\n}\n\nfunc (h *Server) GetProcesses(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\n\ta, err := h.findApp(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Retrieve tasks\n\tjs, err := h.Tasks(ctx, a)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tw.WriteHeader(200)\n\treturn Encode(w, newDynos(js))\n}\n\ntype PostProcessForm struct {\n\tCommand string              `json:\"command\"`\n\tAttach  bool                `json:\"attach\"`\n\tEnv     map[string]string   `json:\"env\"`\n\tSize    *empire.Constraints `json:\"size\"`\n}\n\nfunc (h *Server) PostProcess(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\n\tvar form PostProcessForm\n\n\ta, err := h.findApp(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm, err := findMessage(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := Decode(r, &form); err != nil {\n\t\treturn err\n\t}\n\n\tcommand, err := empire.ParseCommand(form.Command)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\topts := empire.RunOpts{\n\t\tUser:        auth.UserFromContext(ctx),\n\t\tApp:         a,\n\t\tCommand:     command,\n\t\tEnv:         form.Env,\n\t\tConstraints: form.Size,\n\t\tMessage:     m,\n\t}\n\n\tif form.Attach {\n\t\tmultiplex := r.Header.Get(\"X-Multiplex\") != \"\"\n\n\t\theader := http.Header{}\n\t\tif multiplex {\n\t\t\theader.Set(\"Content-Type\", \"application\/vnd.empire.stdcopy-stream\")\n\t\t} else {\n\t\t\theader.Set(\"Content-Type\", \"application\/vnd.empire.raw-stream\")\n\t\t}\n\n\t\tstream := &hijack.HijackReadWriter{\n\t\t\tResponse: w,\n\t\t\tHeader:   header,\n\t\t}\n\t\tdefer stream.Close()\n\n\t\topts.Stdin = stream\n\n\t\tif multiplex {\n\t\t\topts.Stdout = stdcopy.NewStdWriter(stream, stdcopy.Stdout)\n\t\t\topts.Stderr = stdcopy.NewStdWriter(stream, stdcopy.Stderr)\n\t\t} else {\n\t\t\t\/\/ Backwards compatibility for older clients that don't\n\t\t\t\/\/ know how to de-multiplex a stdcopy stream. For these\n\t\t\t\/\/ clients, stdout\/stderr are merged together.\n\t\t\topts.Stdout = stream\n\t\t\topts.Stderr = stream\n\t\t}\n\n\t\tif err := h.Run(ctx, opts); err != nil {\n\t\t\tif stream.Hijacked {\n\t\t\t\tfmt.Fprintf(stream, \"%v\\r\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif err := h.Run(ctx, opts); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdyno := &heroku.Dyno{\n\t\t\tName:      \"run\",\n\t\t\tCommand:   form.Command,\n\t\t\tCreatedAt: timex.Now(),\n\t\t}\n\n\t\tw.WriteHeader(201)\n\t\treturn Encode(w, dyno)\n\t}\n\n\treturn nil\n}\n\nfunc (h *Server) DeleteProcesses(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\n\tvars := Vars(r)\n\tpid := vars[\"pid\"]\n\n\tif vars[\"ptype\"] != \"\" {\n\t\treturn errNotImplemented(\"Restarting a process type is currently not implemented.\")\n\t}\n\n\ta, err := h.findApp(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm, err := findMessage(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := h.Restart(ctx, empire.RestartOpts{\n\t\tUser:    auth.UserFromContext(ctx),\n\t\tApp:     a,\n\t\tPID:     pid,\n\t\tMessage: m,\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\treturn NoContent(w)\n}\n<|endoftext|>"}
{"text":"<commit_before>package terraform\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com\/hashicorp\/terraform\/config\"\n\t\"github.com\/hashicorp\/terraform\/depgraph\"\n)\n\n\/\/ Terraform is the primary structure that is used to interact with\n\/\/ Terraform from code, and can perform operations such as returning\n\/\/ all resources, a resource tree, a specific resource, etc.\ntype Terraform struct {\n\tconfig    *config.Config\n\tgraph     *depgraph.Graph\n\tmapping   map[*config.Resource]*terraformProvider\n\tvariables map[string]string\n}\n\n\/\/ terraformProvider contains internal state information about a resource\n\/\/ provider for Terraform.\ntype terraformProvider struct {\n\tProvider ResourceProvider\n\tConfig   *config.ProviderConfig\n\n\tsync.Once\n}\n\n\/\/ This is a function type used to implement a walker for the resource\n\/\/ tree internally on the Terraform structure.\ntype genericWalkFunc func(*Resource) (map[string]string, error)\n\n\/\/ Config is the configuration that must be given to instantiate\n\/\/ a Terraform structure.\ntype Config struct {\n\tConfig    *config.Config\n\tProviders map[string]ResourceProviderFactory\n\tVariables map[string]string\n\n\tcomputedPlaceholder string\n}\n\n\/\/ New creates a new Terraform structure, initializes resource providers\n\/\/ for the given configuration, etc.\n\/\/\n\/\/ Semantic checks of the entire configuration structure are done at this\n\/\/ time, as well as richer checks such as verifying that the resource providers\n\/\/ can be properly initialized, can be configured, etc.\nfunc New(c *Config) (*Terraform, error) {\n\tvar errs []error\n\n\t\/\/ Calculate the computed key placeholder\n\tc.computedPlaceholder = \"tf_computed_placeholder\"\n\n\t\/\/ Validate that all required variables have values\n\tif err := smcVariables(c); err != nil {\n\t\terrs = append(errs, err...)\n\t}\n\n\t\/\/ Match all the resources with a provider and initialize the providers\n\tmapping, err := smcProviders(c)\n\tif err != nil {\n\t\terrs = append(errs, err...)\n\t}\n\n\t\/\/ Validate all the configurations, once.\n\ttps := make(map[*terraformProvider]struct{})\n\tfor _, tp := range mapping {\n\t\tif _, ok := tps[tp]; !ok {\n\t\t\ttps[tp] = struct{}{}\n\t\t}\n\t}\n\tfor tp, _ := range tps {\n\t\tvar rc *ResourceConfig\n\t\tif tp.Config != nil {\n\t\t\trc = NewResourceConfig(tp.Config.RawConfig)\n\t\t}\n\n\t\t_, tpErrs := tp.Provider.Validate(rc)\n\t\tif len(tpErrs) > 0 {\n\t\t\terrs = append(errs, tpErrs...)\n\t\t}\n\t}\n\n\t\/\/ Build the resource graph\n\tgraph := c.Config.Graph()\n\tif err := graph.Validate(); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\n\t\t\t\"Resource graph has an error: %s\", err))\n\t}\n\n\t\/\/ If we accumulated any errors, then return them all\n\tif len(errs) > 0 {\n\t\treturn nil, &MultiError{Errors: errs}\n\t}\n\n\treturn &Terraform{\n\t\tconfig:    c.Config,\n\t\tgraph:     graph,\n\t\tmapping:   mapping,\n\t\tvariables: c.Variables,\n\t}, nil\n}\n\nfunc (t *Terraform) Apply(p *Plan) (*State, error) {\n\tresult := new(State)\n\terr := t.graph.Walk(t.applyWalkFn(p, result))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\nfunc (t *Terraform) Plan(s *State) (*Plan, error) {\n\tresult := new(Plan)\n\terr := t.graph.Walk(t.planWalkFn(s, result))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\nfunc (t *Terraform) Refresh(*State) (*State, error) {\n\treturn nil, nil\n}\n\nfunc (t *Terraform) applyWalkFn(\n\tp *Plan,\n\tresult *State) depgraph.WalkFunc {\n\tvar l sync.Mutex\n\n\t\/\/ Initialize the result\n\tresult.init()\n\n\tcb := func(r *Resource) (map[string]string, error) {\n\t\t\/\/ Get the latest diff since there are no computed values anymore\n\t\tdiff, err := r.Provider.Diff(r.State, r.Config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\trs, err := r.Provider.Apply(r.State, diff)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ If no state was returned, then no variables were updated so\n\t\t\/\/ just return.\n\t\tif rs == nil {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\t\/\/ Update the resulting diff\n\t\tl.Lock()\n\t\tresult.Resources[r.Id] = rs\n\t\tl.Unlock()\n\n\t\t\/\/ Determine the new state and update variables\n\t\tvars := make(map[string]string)\n\t\tfor ak, av := range rs.Attributes {\n\t\t\tvars[fmt.Sprintf(\"%s.%s\", r.Id, ak)] = av\n\t\t}\n\n\t\treturn vars, nil\n\t}\n\n\treturn t.genericWalkFn(p.State, p.Diff, p.Vars, cb)\n}\n\nfunc (t *Terraform) planWalkFn(\n\tstate *State, result *Plan) depgraph.WalkFunc {\n\tvar l sync.Mutex\n\n\t\/\/ Initialize the result diff so we can write to it\n\tresult.init()\n\n\t\/\/ Write our configuration out\n\tresult.Config = t.config\n\n\t\/\/ Copy the variables\n\tresult.Vars = make(map[string]string)\n\tfor k, v := range t.variables {\n\t\tresult.Vars[k] = v\n\t}\n\n\tcb := func(r *Resource) (map[string]string, error) {\n\t\t\/\/ Refresh the state so we're working with the latest resource info\n\t\tnewState, err := r.Provider.Refresh(r.State)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ Get a diff from the newest state\n\t\tdiff, err := r.Provider.Diff(newState, r.Config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tl.Lock()\n\t\tif !diff.Empty() {\n\t\t\tresult.Diff.Resources[r.Id] = diff\n\t\t}\n\t\tresult.State.Resources[r.Id] = newState\n\t\tl.Unlock()\n\n\t\t\/\/ Determine the new state and update variables\n\t\tvars := make(map[string]string)\n\t\trs := newState\n\t\tif !diff.Empty() {\n\t\t\trs = r.State.MergeDiff(diff)\n\t\t}\n\t\tif rs != nil {\n\t\t\tfor ak, av := range rs.Attributes {\n\t\t\t\tvars[fmt.Sprintf(\"%s.%s\", r.Id, ak)] = av\n\t\t\t}\n\t\t}\n\n\t\treturn vars, nil\n\t}\n\n\treturn t.genericWalkFn(state, nil, t.variables, cb)\n}\n\nfunc (t *Terraform) genericWalkFn(\n\tstate *State,\n\tdiff *Diff,\n\tinvars map[string]string,\n\tcb genericWalkFunc) depgraph.WalkFunc {\n\tvar l sync.Mutex\n\n\t\/\/ Initialize the variables for application\n\tvars := make(map[string]string)\n\tfor k, v := range invars {\n\t\tvars[fmt.Sprintf(\"var.%s\", k)] = v\n\t}\n\n\treturn func(n *depgraph.Noun) error {\n\t\t\/\/ If it is the root node, ignore\n\t\tif n.Meta == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tswitch n.Meta.(type) {\n\t\tcase *config.ProviderConfig:\n\t\t\t\/\/ Ignore, we don't treat this any differently since we always\n\t\t\t\/\/ initialize the provider on first use and use a lock to make\n\t\t\t\/\/ sure we only do this once.\n\t\t\treturn nil\n\t\tcase *config.Resource:\n\t\t\t\/\/ Continue\n\t\t}\n\n\t\tr := n.Meta.(*config.Resource)\n\t\tp := t.mapping[r]\n\t\tif p == nil {\n\t\t\tpanic(fmt.Sprintf(\"No provider for resource: %s\", r.Id()))\n\t\t}\n\n\t\t\/\/ Initialize the provider if we haven't already\n\t\tif err := p.init(vars); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Get the resource state\n\t\tvar rs *ResourceState\n\t\tif state != nil {\n\t\t\trs = state.Resources[r.Id()]\n\t\t}\n\n\t\t\/\/ Get the resource diff\n\t\tvar rd *ResourceDiff\n\t\tif diff != nil {\n\t\t\trd = diff.Resources[r.Id()]\n\t\t}\n\n\t\tif len(vars) > 0 {\n\t\t\tif err := r.RawConfig.Interpolate(vars); err != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"Interpolate error: %s\", err))\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If we have no state, then create an empty state with the\n\t\t\/\/ type fulfilled at the least.\n\t\tif rs == nil {\n\t\t\trs = new(ResourceState)\n\t\t}\n\t\trs.Type = r.Type\n\n\t\t\/\/ Call the callack\n\t\tnewVars, err := cb(&Resource{\n\t\t\tId:       r.Id(),\n\t\t\tConfig:   NewResourceConfig(r.RawConfig),\n\t\t\tDiff:     rd,\n\t\t\tProvider: p.Provider,\n\t\t\tState:    rs,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(newVars) > 0 {\n\t\t\t\/\/ Acquire a lock since this function is called in parallel\n\t\t\tl.Lock()\n\t\t\tdefer l.Unlock()\n\n\t\t\t\/\/ Update variables\n\t\t\tfor k, v := range newVars {\n\t\t\t\tvars[k] = v\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc (t *terraformProvider) init(vars map[string]string) (err error) {\n\tt.Once.Do(func() {\n\t\tvar rc *ResourceConfig\n\t\tif t.Config != nil {\n\t\t\tif err := t.Config.RawConfig.Interpolate(vars); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\trc = &ResourceConfig{\n\t\t\t\tComputedKeys: t.Config.RawConfig.UnknownKeys(),\n\t\t\t\tRaw:          t.Config.RawConfig.Config(),\n\t\t\t}\n\t\t}\n\n\t\terr = t.Provider.Configure(rc)\n\t})\n\n\treturn\n}\n<commit_msg>terraform: some comments<commit_after>package terraform\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com\/hashicorp\/terraform\/config\"\n\t\"github.com\/hashicorp\/terraform\/depgraph\"\n)\n\n\/\/ Terraform is the primary structure that is used to interact with\n\/\/ Terraform from code, and can perform operations such as returning\n\/\/ all resources, a resource tree, a specific resource, etc.\ntype Terraform struct {\n\tconfig    *config.Config\n\tgraph     *depgraph.Graph\n\tmapping   map[*config.Resource]*terraformProvider\n\tvariables map[string]string\n}\n\n\/\/ terraformProvider contains internal state information about a resource\n\/\/ provider for Terraform.\ntype terraformProvider struct {\n\tProvider ResourceProvider\n\tConfig   *config.ProviderConfig\n\n\tsync.Once\n}\n\n\/\/ This is a function type used to implement a walker for the resource\n\/\/ tree internally on the Terraform structure.\ntype genericWalkFunc func(*Resource) (map[string]string, error)\n\n\/\/ Config is the configuration that must be given to instantiate\n\/\/ a Terraform structure.\ntype Config struct {\n\tConfig    *config.Config\n\tProviders map[string]ResourceProviderFactory\n\tVariables map[string]string\n\n\tcomputedPlaceholder string\n}\n\n\/\/ New creates a new Terraform structure, initializes resource providers\n\/\/ for the given configuration, etc.\n\/\/\n\/\/ Semantic checks of the entire configuration structure are done at this\n\/\/ time, as well as richer checks such as verifying that the resource providers\n\/\/ can be properly initialized, can be configured, etc.\nfunc New(c *Config) (*Terraform, error) {\n\tvar errs []error\n\n\t\/\/ Calculate the computed key placeholder\n\tc.computedPlaceholder = \"tf_computed_placeholder\"\n\n\t\/\/ Validate that all required variables have values\n\tif err := smcVariables(c); err != nil {\n\t\terrs = append(errs, err...)\n\t}\n\n\t\/\/ Match all the resources with a provider and initialize the providers\n\tmapping, err := smcProviders(c)\n\tif err != nil {\n\t\terrs = append(errs, err...)\n\t}\n\n\t\/\/ Validate all the configurations, once.\n\ttps := make(map[*terraformProvider]struct{})\n\tfor _, tp := range mapping {\n\t\tif _, ok := tps[tp]; !ok {\n\t\t\ttps[tp] = struct{}{}\n\t\t}\n\t}\n\tfor tp, _ := range tps {\n\t\tvar rc *ResourceConfig\n\t\tif tp.Config != nil {\n\t\t\trc = NewResourceConfig(tp.Config.RawConfig)\n\t\t}\n\n\t\t_, tpErrs := tp.Provider.Validate(rc)\n\t\tif len(tpErrs) > 0 {\n\t\t\terrs = append(errs, tpErrs...)\n\t\t}\n\t}\n\n\t\/\/ Build the resource graph\n\tgraph := c.Config.Graph()\n\tif err := graph.Validate(); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\n\t\t\t\"Resource graph has an error: %s\", err))\n\t}\n\n\t\/\/ If we accumulated any errors, then return them all\n\tif len(errs) > 0 {\n\t\treturn nil, &MultiError{Errors: errs}\n\t}\n\n\treturn &Terraform{\n\t\tconfig:    c.Config,\n\t\tgraph:     graph,\n\t\tmapping:   mapping,\n\t\tvariables: c.Variables,\n\t}, nil\n}\n\nfunc (t *Terraform) Apply(p *Plan) (*State, error) {\n\tresult := new(State)\n\terr := t.graph.Walk(t.applyWalkFn(p, result))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\nfunc (t *Terraform) Plan(s *State) (*Plan, error) {\n\tresult := new(Plan)\n\terr := t.graph.Walk(t.planWalkFn(s, result))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\nfunc (t *Terraform) Refresh(*State) (*State, error) {\n\treturn nil, nil\n}\n\nfunc (t *Terraform) applyWalkFn(\n\tp *Plan,\n\tresult *State) depgraph.WalkFunc {\n\tvar l sync.Mutex\n\n\t\/\/ Initialize the result\n\tresult.init()\n\n\tcb := func(r *Resource) (map[string]string, error) {\n\t\t\/\/ Get the latest diff since there are no computed values anymore\n\t\tdiff, err := r.Provider.Diff(r.State, r.Config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ TODO(mitchellh): we need to verify the diff doesn't change\n\t\t\/\/ anything and that the diff has no computed values (pre-computed)\n\n\t\t\/\/ With the completed diff, apply!\n\t\trs, err := r.Provider.Apply(r.State, diff)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ If no state was returned, then no variables were updated so\n\t\t\/\/ just return.\n\t\tif rs == nil {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\t\/\/ Update the resulting diff\n\t\tl.Lock()\n\t\tresult.Resources[r.Id] = rs\n\t\tl.Unlock()\n\n\t\t\/\/ Determine the new state and update variables\n\t\tvars := make(map[string]string)\n\t\tfor ak, av := range rs.Attributes {\n\t\t\tvars[fmt.Sprintf(\"%s.%s\", r.Id, ak)] = av\n\t\t}\n\n\t\treturn vars, nil\n\t}\n\n\treturn t.genericWalkFn(p.State, p.Diff, p.Vars, cb)\n}\n\nfunc (t *Terraform) planWalkFn(\n\tstate *State, result *Plan) depgraph.WalkFunc {\n\tvar l sync.Mutex\n\n\t\/\/ Initialize the result diff so we can write to it\n\tresult.init()\n\n\t\/\/ Write our configuration out\n\tresult.Config = t.config\n\n\t\/\/ Copy the variables\n\tresult.Vars = make(map[string]string)\n\tfor k, v := range t.variables {\n\t\tresult.Vars[k] = v\n\t}\n\n\tcb := func(r *Resource) (map[string]string, error) {\n\t\t\/\/ Refresh the state so we're working with the latest resource info\n\t\tnewState, err := r.Provider.Refresh(r.State)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ Get a diff from the newest state\n\t\tdiff, err := r.Provider.Diff(newState, r.Config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tl.Lock()\n\t\tif !diff.Empty() {\n\t\t\tresult.Diff.Resources[r.Id] = diff\n\t\t}\n\t\tresult.State.Resources[r.Id] = newState\n\t\tl.Unlock()\n\n\t\t\/\/ Determine the new state and update variables\n\t\tvars := make(map[string]string)\n\t\trs := newState\n\t\tif !diff.Empty() {\n\t\t\trs = r.State.MergeDiff(diff)\n\t\t}\n\t\tif rs != nil {\n\t\t\tfor ak, av := range rs.Attributes {\n\t\t\t\tvars[fmt.Sprintf(\"%s.%s\", r.Id, ak)] = av\n\t\t\t}\n\t\t}\n\n\t\treturn vars, nil\n\t}\n\n\treturn t.genericWalkFn(state, nil, t.variables, cb)\n}\n\nfunc (t *Terraform) genericWalkFn(\n\tstate *State,\n\tdiff *Diff,\n\tinvars map[string]string,\n\tcb genericWalkFunc) depgraph.WalkFunc {\n\tvar l sync.Mutex\n\n\t\/\/ Initialize the variables for application\n\tvars := make(map[string]string)\n\tfor k, v := range invars {\n\t\tvars[fmt.Sprintf(\"var.%s\", k)] = v\n\t}\n\n\treturn func(n *depgraph.Noun) error {\n\t\t\/\/ If it is the root node, ignore\n\t\tif n.Meta == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tswitch n.Meta.(type) {\n\t\tcase *config.ProviderConfig:\n\t\t\t\/\/ Ignore, we don't treat this any differently since we always\n\t\t\t\/\/ initialize the provider on first use and use a lock to make\n\t\t\t\/\/ sure we only do this once.\n\t\t\treturn nil\n\t\tcase *config.Resource:\n\t\t\t\/\/ Continue\n\t\t}\n\n\t\tr := n.Meta.(*config.Resource)\n\t\tp := t.mapping[r]\n\t\tif p == nil {\n\t\t\tpanic(fmt.Sprintf(\"No provider for resource: %s\", r.Id()))\n\t\t}\n\n\t\t\/\/ Initialize the provider if we haven't already\n\t\tif err := p.init(vars); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Get the resource state\n\t\tvar rs *ResourceState\n\t\tif state != nil {\n\t\t\trs = state.Resources[r.Id()]\n\t\t}\n\n\t\t\/\/ Get the resource diff\n\t\tvar rd *ResourceDiff\n\t\tif diff != nil {\n\t\t\trd = diff.Resources[r.Id()]\n\t\t}\n\n\t\tif len(vars) > 0 {\n\t\t\tif err := r.RawConfig.Interpolate(vars); err != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"Interpolate error: %s\", err))\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If we have no state, then create an empty state with the\n\t\t\/\/ type fulfilled at the least.\n\t\tif rs == nil {\n\t\t\trs = new(ResourceState)\n\t\t}\n\t\trs.Type = r.Type\n\n\t\t\/\/ Call the callack\n\t\tnewVars, err := cb(&Resource{\n\t\t\tId:       r.Id(),\n\t\t\tConfig:   NewResourceConfig(r.RawConfig),\n\t\t\tDiff:     rd,\n\t\t\tProvider: p.Provider,\n\t\t\tState:    rs,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(newVars) > 0 {\n\t\t\t\/\/ Acquire a lock since this function is called in parallel\n\t\t\tl.Lock()\n\t\t\tdefer l.Unlock()\n\n\t\t\t\/\/ Update variables\n\t\t\tfor k, v := range newVars {\n\t\t\t\tvars[k] = v\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc (t *terraformProvider) init(vars map[string]string) (err error) {\n\tt.Once.Do(func() {\n\t\tvar rc *ResourceConfig\n\t\tif t.Config != nil {\n\t\t\tif err := t.Config.RawConfig.Interpolate(vars); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\trc = &ResourceConfig{\n\t\t\t\tComputedKeys: t.Config.RawConfig.UnknownKeys(),\n\t\t\t\tRaw:          t.Config.RawConfig.Config(),\n\t\t\t}\n\t\t}\n\n\t\terr = t.Provider.Configure(rc)\n\t})\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package server\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"net\"\n)\n\nfunc TestParsingOfEnvironmentVariables(t *testing.T) {\n\ta := assert.New(t)\n\n\toriginalArgs := os.Args\n\tos.Args = []string{os.Args[0]}\n\tdefer func() { os.Args = originalArgs }()\n\n\t\/\/ given: some environment variables\n\tos.Setenv(\"GUBLE_HTTP_LISTEN\", \"http_listen\")\n\tdefer os.Unsetenv(\"GUBLE_HTTP_LISTEN\")\n\n\tos.Setenv(\"GUBLE_LOG\", \"debug\")\n\tdefer os.Unsetenv(\"GUBLE_LOG\")\n\n\tos.Setenv(\"GUBLE_ENV\", \"dev\")\n\tdefer os.Unsetenv(\"GUBLE_ENV\")\n\n\tos.Setenv(\"GUBLE_KVS\", \"kvs-backend\")\n\tdefer os.Unsetenv(\"GUBLE_KVS\")\n\n\tos.Setenv(\"GUBLE_STORAGE_PATH\", os.TempDir())\n\tdefer os.Unsetenv(\"GUBLE_STORAGE_PATH\")\n\n\tos.Setenv(\"GUBLE_HEALTH_ENDPOINT\", \"health_endpoint\")\n\tdefer os.Unsetenv(\"GUBLE_HEALTH_ENDPOINT\")\n\n\tos.Setenv(\"GUBLE_METRICS_ENDPOINT\", \"metrics_endpoint\")\n\tdefer os.Unsetenv(\"GUBLE_METRICS_ENDPOINT\")\n\n\tos.Setenv(\"GUBLE_MS\", \"ms-backend\")\n\tdefer os.Unsetenv(\"GUBLE_MS\")\n\n\tos.Setenv(\"GUBLE_GCM\", \"true\")\n\tdefer os.Unsetenv(\"GUBLE_GCM\")\n\n\tos.Setenv(\"GUBLE_GCM_API_KEY\", \"gcm-api-key\")\n\tdefer os.Unsetenv(\"GUBLE_GCM_API_KEY\")\n\n\tos.Setenv(\"GUBLE_GCM_WORKERS\", \"3\")\n\tdefer os.Unsetenv(\"GUBLE_GCM_WORKERS\")\n\n\tos.Setenv(\"GUBLE_NODE_ID\", \"1\")\n\tdefer os.Unsetenv(\"GUBLE_NODE_ID\")\n\n\tos.Setenv(\"GUBLE_NODE_PORT\", \"10000\")\n\tdefer os.Unsetenv(\"GUBLE_NODE_PORT\")\n\n\tos.Setenv(\"GUBLE_PG_HOST\", \"pg-host\")\n\tdefer os.Unsetenv(\"GUBLE_PG_HOST\")\n\n\tos.Setenv(\"GUBLE_PG_PORT\", \"5432\")\n\tdefer os.Unsetenv(\"GUBLE_PG_PORT\")\n\n\tos.Setenv(\"GUBLE_PG_USER\", \"pg-user\")\n\tdefer os.Unsetenv(\"GUBLE_PG_USER\")\n\n\tos.Setenv(\"GUBLE_PG_PASSWORD\", \"pg-password\")\n\tdefer os.Unsetenv(\"GUBLE_PG_PASSWORD\")\n\n\tos.Setenv(\"GUBLE_PG_DBNAME\", \"pg-dbname\")\n\tdefer os.Unsetenv(\"GUBLE_PG_DBNAME\")\n\n\tos.Setenv(\"GUBLE_NODE_REMOTES\", \"127.0.0.1:8080 127.0.0.1:20002\")\n\tdefer os.Unsetenv(\"GUBLE_NODE_REMOTES\")\n\n\t\/\/ when we parse the arguments from environment variables\n\tparseConfig()\n\n\t\/\/ then the parsed parameters are correctly set\n\tassertArguments(a)\n}\n\nfunc TestParsingArgs(t *testing.T) {\n\ta := assert.New(t)\n\n\toriginalArgs := os.Args\n\n\tdefer func() { os.Args = originalArgs }()\n\n\t\/\/ given: a command line\n\tos.Args = []string{os.Args[0],\n\t\t\"--http\", \"http_listen\",\n\t\t\"--env\", \"dev\",\n\t\t\"--log\", \"debug\",\n\t\t\"--storage-path\", os.TempDir(),\n\t\t\"--kvs\", \"kvs-backend\",\n\t\t\"--ms\", \"ms-backend\",\n\t\t\"--health-endpoint\", \"health_endpoint\",\n\t\t\"--metrics-endpoint\", \"metrics_endpoint\",\n\t\t\"--gcm\",\n\t\t\"--gcm-api-key\", \"gcm-api-key\",\n\t\t\"--gcm-workers\", \"3\",\n\t\t\"--node-id\", \"1\",\n\t\t\"--node-port\", \"10000\",\n\t\t\"--pg-host\", \"pg-host\",\n\t\t\"--pg-port\", \"5432\",\n\t\t\"--pg-user\", \"pg-user\",\n\t\t\"--pg-password\", \"pg-password\",\n\t\t\"--pg-dbname\", \"pg-dbname\",\n\t\t\"--tcplist\", \"127.0.0.1:8080 127.0.0.1:20002\",\n\t}\n\n\t\/\/ when we parse the arguments from command-line flags\n\tparseConfig()\n\n\t\/\/ then the parsed parameters are correctly set\n\tassertArguments(a)\n}\n\nfunc assertArguments(a *assert.Assertions) {\n\ta.Equal(\"http_listen\", *config.HttpListen)\n\ta.Equal(\"kvs-backend\", *config.KVS)\n\ta.Equal(os.TempDir(), *config.StoragePath)\n\ta.Equal(\"ms-backend\", *config.MS)\n\ta.Equal(\"health_endpoint\", *config.HealthEndpoint)\n\n\ta.Equal(\"metrics_endpoint\", *config.MetricsEndpoint)\n\n\ta.Equal(true, *config.GCM.Enabled)\n\ta.Equal(\"gcm-api-key\", *config.GCM.APIKey)\n\ta.Equal(3, *config.GCM.Workers)\n\n\ta.Equal(1, *config.Cluster.NodeID)\n\ta.Equal(10000, *config.Cluster.NodePort)\n\n\ta.Equal(\"pg-host\", *config.Postgres.Host)\n\ta.Equal(5432, *config.Postgres.Port)\n\ta.Equal(\"pg-user\", *config.Postgres.User)\n\ta.Equal(\"pg-password\", *config.Postgres.Password)\n\ta.Equal(\"pg-dbname\", *config.Postgres.DbName)\n\n\ta.Equal(\"debug\", *config.Log)\n\ta.Equal(\"dev\", *config.EnvName)\n\tassertRemotesCluster(a)\n\n}\n\nfunc assertRemotesCluster(a *assert.Assertions) {\n\tip1, _ := net.ResolveTCPAddr(\"tcp\", \"127.0.0.1:8080\")\n\tip2, _ := net.ResolveTCPAddr(\"tcp\", \"127.0.0.1:20002\")\n\tipList := make(tcpAddrList, 0)\n\tipList = append(ipList, ip1)\n\tipList = append(ipList, ip2)\n\ta.Equal(ipList, *config.Cluster.Remotes)\n}\n<commit_msg>adding tests<commit_after>package server\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"net\"\n)\n\nfunc TestParsingOfEnvironmentVariables(t *testing.T) {\n\ta := assert.New(t)\n\n\toriginalArgs := os.Args\n\tos.Args = []string{os.Args[0]}\n\tdefer func() { os.Args = originalArgs }()\n\n\t\/\/ given: some environment variables\n\tos.Setenv(\"GUBLE_HTTP_LISTEN\", \"http_listen\")\n\tdefer os.Unsetenv(\"GUBLE_HTTP_LISTEN\")\n\n\tos.Setenv(\"GUBLE_LOG\", \"debug\")\n\tdefer os.Unsetenv(\"GUBLE_LOG\")\n\n\tos.Setenv(\"GUBLE_ENV\", \"dev\")\n\tdefer os.Unsetenv(\"GUBLE_ENV\")\n\n\tos.Setenv(\"GUBLE_PROFILE\", \"mem\")\n\tdefer os.Unsetenv(\"GUBLE_PROFILE\")\n\n\tos.Setenv(\"GUBLE_KVS\", \"kvs-backend\")\n\tdefer os.Unsetenv(\"GUBLE_KVS\")\n\n\tos.Setenv(\"GUBLE_STORAGE_PATH\", os.TempDir())\n\tdefer os.Unsetenv(\"GUBLE_STORAGE_PATH\")\n\n\tos.Setenv(\"GUBLE_HEALTH_ENDPOINT\", \"health_endpoint\")\n\tdefer os.Unsetenv(\"GUBLE_HEALTH_ENDPOINT\")\n\n\tos.Setenv(\"GUBLE_METRICS_ENDPOINT\", \"metrics_endpoint\")\n\tdefer os.Unsetenv(\"GUBLE_METRICS_ENDPOINT\")\n\n\tos.Setenv(\"GUBLE_MS\", \"ms-backend\")\n\tdefer os.Unsetenv(\"GUBLE_MS\")\n\n\tos.Setenv(\"GUBLE_GCM\", \"true\")\n\tdefer os.Unsetenv(\"GUBLE_GCM\")\n\n\tos.Setenv(\"GUBLE_GCM_API_KEY\", \"gcm-api-key\")\n\tdefer os.Unsetenv(\"GUBLE_GCM_API_KEY\")\n\n\tos.Setenv(\"GUBLE_GCM_WORKERS\", \"3\")\n\tdefer os.Unsetenv(\"GUBLE_GCM_WORKERS\")\n\n\tos.Setenv(\"GUBLE_NODE_ID\", \"1\")\n\tdefer os.Unsetenv(\"GUBLE_NODE_ID\")\n\n\tos.Setenv(\"GUBLE_NODE_PORT\", \"10000\")\n\tdefer os.Unsetenv(\"GUBLE_NODE_PORT\")\n\n\tos.Setenv(\"GUBLE_PG_HOST\", \"pg-host\")\n\tdefer os.Unsetenv(\"GUBLE_PG_HOST\")\n\n\tos.Setenv(\"GUBLE_PG_PORT\", \"5432\")\n\tdefer os.Unsetenv(\"GUBLE_PG_PORT\")\n\n\tos.Setenv(\"GUBLE_PG_USER\", \"pg-user\")\n\tdefer os.Unsetenv(\"GUBLE_PG_USER\")\n\n\tos.Setenv(\"GUBLE_PG_PASSWORD\", \"pg-password\")\n\tdefer os.Unsetenv(\"GUBLE_PG_PASSWORD\")\n\n\tos.Setenv(\"GUBLE_PG_DBNAME\", \"pg-dbname\")\n\tdefer os.Unsetenv(\"GUBLE_PG_DBNAME\")\n\n\tos.Setenv(\"GUBLE_NODE_REMOTES\", \"127.0.0.1:8080 127.0.0.1:20002\")\n\tdefer os.Unsetenv(\"GUBLE_NODE_REMOTES\")\n\n\t\/\/ when we parse the arguments from environment variables\n\tparseConfig()\n\n\t\/\/ then the parsed parameters are correctly set\n\tassertArguments(a)\n}\n\nfunc TestParsingArgs(t *testing.T) {\n\ta := assert.New(t)\n\n\toriginalArgs := os.Args\n\n\tdefer func() { os.Args = originalArgs }()\n\n\t\/\/ given: a command line\n\tos.Args = []string{os.Args[0],\n\t\t\"--http\", \"http_listen\",\n\t\t\"--env\", \"dev\",\n\t\t\"--log\", \"debug\",\n\t\t\"--profile\", \"mem\",\n\t\t\"--storage-path\", os.TempDir(),\n\t\t\"--kvs\", \"kvs-backend\",\n\t\t\"--ms\", \"ms-backend\",\n\t\t\"--health-endpoint\", \"health_endpoint\",\n\t\t\"--metrics-endpoint\", \"metrics_endpoint\",\n\t\t\"--gcm\",\n\t\t\"--gcm-api-key\", \"gcm-api-key\",\n\t\t\"--gcm-workers\", \"3\",\n\t\t\"--node-id\", \"1\",\n\t\t\"--node-port\", \"10000\",\n\t\t\"--pg-host\", \"pg-host\",\n\t\t\"--pg-port\", \"5432\",\n\t\t\"--pg-user\", \"pg-user\",\n\t\t\"--pg-password\", \"pg-password\",\n\t\t\"--pg-dbname\", \"pg-dbname\",\n\t\t\"--tcplist\", \"127.0.0.1:8080 127.0.0.1:20002\",\n\t}\n\n\t\/\/ when we parse the arguments from command-line flags\n\tparseConfig()\n\n\t\/\/ then the parsed parameters are correctly set\n\tassertArguments(a)\n}\n\nfunc assertArguments(a *assert.Assertions) {\n\ta.Equal(\"http_listen\", *config.HttpListen)\n\ta.Equal(\"kvs-backend\", *config.KVS)\n\ta.Equal(os.TempDir(), *config.StoragePath)\n\ta.Equal(\"ms-backend\", *config.MS)\n\ta.Equal(\"health_endpoint\", *config.HealthEndpoint)\n\n\ta.Equal(\"metrics_endpoint\", *config.MetricsEndpoint)\n\n\ta.Equal(true, *config.GCM.Enabled)\n\ta.Equal(\"gcm-api-key\", *config.GCM.APIKey)\n\ta.Equal(3, *config.GCM.Workers)\n\n\ta.Equal(1, *config.Cluster.NodeID)\n\ta.Equal(10000, *config.Cluster.NodePort)\n\n\ta.Equal(\"pg-host\", *config.Postgres.Host)\n\ta.Equal(5432, *config.Postgres.Port)\n\ta.Equal(\"pg-user\", *config.Postgres.User)\n\ta.Equal(\"pg-password\", *config.Postgres.Password)\n\ta.Equal(\"pg-dbname\", *config.Postgres.DbName)\n\n\ta.Equal(\"debug\", *config.Log)\n\ta.Equal(\"dev\", *config.EnvName)\n\ta.Equal(\"mem\", *config.Profile)\n\n\tassertClusterRemotes(a)\n}\n\nfunc assertClusterRemotes(a *assert.Assertions) {\n\tip1, _ := net.ResolveTCPAddr(\"tcp\", \"127.0.0.1:8080\")\n\tip2, _ := net.ResolveTCPAddr(\"tcp\", \"127.0.0.1:20002\")\n\tipList := make(tcpAddrList, 0)\n\tipList = append(ipList, ip1)\n\tipList = append(ipList, ip2)\n\ta.Equal(ipList, *config.Cluster.Remotes)\n}\n<|endoftext|>"}
{"text":"<commit_before>package terraform\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/hashicorp\/terraform\/config\"\n\t\"github.com\/hashicorp\/terraform\/config\/module\"\n\t\"github.com\/hashicorp\/terraform\/helper\/hilmapstructure\"\n)\n\n\/\/ Variables returns the fully loaded set of variables to use with\n\/\/ ContextOpts and NewContext, loading any additional variables from\n\/\/ the environment or any other sources.\n\/\/\n\/\/ The given module tree doesn't need to be loaded.\nfunc Variables(\n\tm *module.Tree,\n\toverride map[string]interface{}) (map[string]interface{}, error) {\n\tresult := make(map[string]interface{})\n\n\t\/\/ Variables are loaded in the following sequence. Each additional step\n\t\/\/ will override conflicting variable keys from prior steps:\n\t\/\/\n\t\/\/   * Take default values from config\n\t\/\/   * Take values from TF_VAR_x env vars\n\t\/\/   * Take values specified in the \"override\" param which is usually\n\t\/\/     from -var, -var-file, etc.\n\t\/\/\n\n\t\/\/ First load from the config\n\tfor _, v := range m.Config().Variables {\n\t\t\/\/ If the var has no default, ignore\n\t\tif v.Default == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ If the type isn't a string, we use it as-is since it is a rich type\n\t\tif v.Type() != config.VariableTypeString {\n\t\t\tresult[v.Name] = v.Default\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ v.Default has already been parsed as HCL but it may be an int type\n\t\tswitch typedDefault := v.Default.(type) {\n\t\tcase string:\n\t\t\tif typedDefault == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresult[v.Name] = typedDefault\n\t\tcase int, int64:\n\t\t\tresult[v.Name] = fmt.Sprintf(\"%d\", typedDefault)\n\t\tcase float32, float64:\n\t\t\tresult[v.Name] = fmt.Sprintf(\"%f\", typedDefault)\n\t\tcase bool:\n\t\t\tresult[v.Name] = fmt.Sprintf(\"%t\", typedDefault)\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\n\t\t\t\t\"Unknown default var type: %T\\n\\n\"+\n\t\t\t\t\t\"THIS IS A BUG. Please report it.\",\n\t\t\t\tv.Default))\n\t\t}\n\t}\n\n\t\/\/ Load from env vars\n\tfor _, v := range os.Environ() {\n\t\tif !strings.HasPrefix(v, VarEnvPrefix) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Strip off the prefix and get the value after the first \"=\"\n\t\tidx := strings.Index(v, \"=\")\n\t\tk := v[len(VarEnvPrefix):idx]\n\t\tv = v[idx+1:]\n\n\t\t\/\/ Override the configuration-default values. Note that *not* finding the variable\n\t\t\/\/ in configuration is OK, as we don't want to preclude people from having multiple\n\t\t\/\/ sets of TF_VAR_whatever in their environment even if it is a little weird.\n\t\tfor _, schema := range m.Config().Variables {\n\t\t\tif schema.Name != k {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvarType := schema.Type()\n\t\t\tvarVal, err := parseVariableAsHCL(k, v, varType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tswitch varType {\n\t\t\tcase config.VariableTypeMap:\n\t\t\t\tvarSetMap(result, k, varVal)\n\t\t\tdefault:\n\t\t\t\tresult[k] = varVal\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Load from overrides\n\tfor k, v := range override {\n\t\tfor _, schema := range m.Config().Variables {\n\t\t\tif schema.Name != k {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tswitch schema.Type() {\n\t\t\tcase config.VariableTypeList:\n\t\t\t\tresult[k] = v\n\t\t\tcase config.VariableTypeMap:\n\t\t\t\tvarSetMap(result, k, v)\n\t\t\tcase config.VariableTypeString:\n\t\t\t\t\/\/ Convert to a string and set. We don't catch any errors\n\t\t\t\t\/\/ here because the validation step later should catch\n\t\t\t\t\/\/ any type errors.\n\t\t\t\tvar strVal string\n\t\t\t\tif err := hilmapstructure.WeakDecode(v, &strVal); err == nil {\n\t\t\t\t\tresult[k] = strVal\n\t\t\t\t} else {\n\t\t\t\t\tresult[k] = v\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Sprintf(\n\t\t\t\t\t\"Unhandled var type: %T\\n\\n\"+\n\t\t\t\t\t\t\"THIS IS A BUG. Please report it.\",\n\t\t\t\t\tschema.Type()))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result, nil\n}\n\n\/\/ varSetMap sets or merges the map in \"v\" with the key \"k\" in the\n\/\/ \"current\" set of variables. This is just a private function to remove\n\/\/ duplicate logic in Variables\nfunc varSetMap(current map[string]interface{}, k string, v interface{}) {\n\texisting, ok := current[k]\n\tif !ok {\n\t\tcurrent[k] = v\n\t\treturn\n\t}\n\n\texistingMap, ok := existing.(map[string]interface{})\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"%s is not a map, this is a bug in Terraform.\", k))\n\t}\n\n\tswitch typedV := v.(type) {\n\tcase []map[string]interface{}:\n\t\tfor newKey, newVal := range typedV[0] {\n\t\t\texistingMap[newKey] = newVal\n\t\t}\n\tcase map[string]interface{}:\n\t\tfor newKey, newVal := range typedV {\n\t\t\texistingMap[newKey] = newVal\n\t\t}\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"%s is not a map, this is a bug in Terraform.\", k))\n\t}\n}\n<commit_msg>Return an error for setting a non-map to a map<commit_after>package terraform\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/hashicorp\/terraform\/config\"\n\t\"github.com\/hashicorp\/terraform\/config\/module\"\n\t\"github.com\/hashicorp\/terraform\/helper\/hilmapstructure\"\n)\n\n\/\/ Variables returns the fully loaded set of variables to use with\n\/\/ ContextOpts and NewContext, loading any additional variables from\n\/\/ the environment or any other sources.\n\/\/\n\/\/ The given module tree doesn't need to be loaded.\nfunc Variables(\n\tm *module.Tree,\n\toverride map[string]interface{}) (map[string]interface{}, error) {\n\tresult := make(map[string]interface{})\n\n\t\/\/ Variables are loaded in the following sequence. Each additional step\n\t\/\/ will override conflicting variable keys from prior steps:\n\t\/\/\n\t\/\/   * Take default values from config\n\t\/\/   * Take values from TF_VAR_x env vars\n\t\/\/   * Take values specified in the \"override\" param which is usually\n\t\/\/     from -var, -var-file, etc.\n\t\/\/\n\n\t\/\/ First load from the config\n\tfor _, v := range m.Config().Variables {\n\t\t\/\/ If the var has no default, ignore\n\t\tif v.Default == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ If the type isn't a string, we use it as-is since it is a rich type\n\t\tif v.Type() != config.VariableTypeString {\n\t\t\tresult[v.Name] = v.Default\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ v.Default has already been parsed as HCL but it may be an int type\n\t\tswitch typedDefault := v.Default.(type) {\n\t\tcase string:\n\t\t\tif typedDefault == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tresult[v.Name] = typedDefault\n\t\tcase int, int64:\n\t\t\tresult[v.Name] = fmt.Sprintf(\"%d\", typedDefault)\n\t\tcase float32, float64:\n\t\t\tresult[v.Name] = fmt.Sprintf(\"%f\", typedDefault)\n\t\tcase bool:\n\t\t\tresult[v.Name] = fmt.Sprintf(\"%t\", typedDefault)\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\n\t\t\t\t\"Unknown default var type: %T\\n\\n\"+\n\t\t\t\t\t\"THIS IS A BUG. Please report it.\",\n\t\t\t\tv.Default))\n\t\t}\n\t}\n\n\t\/\/ Load from env vars\n\tfor _, v := range os.Environ() {\n\t\tif !strings.HasPrefix(v, VarEnvPrefix) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Strip off the prefix and get the value after the first \"=\"\n\t\tidx := strings.Index(v, \"=\")\n\t\tk := v[len(VarEnvPrefix):idx]\n\t\tv = v[idx+1:]\n\n\t\t\/\/ Override the configuration-default values. Note that *not* finding the variable\n\t\t\/\/ in configuration is OK, as we don't want to preclude people from having multiple\n\t\t\/\/ sets of TF_VAR_whatever in their environment even if it is a little weird.\n\t\tfor _, schema := range m.Config().Variables {\n\t\t\tif schema.Name != k {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvarType := schema.Type()\n\t\t\tvarVal, err := parseVariableAsHCL(k, v, varType)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tswitch varType {\n\t\t\tcase config.VariableTypeMap:\n\t\t\t\tif err := varSetMap(result, k, varVal); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tresult[k] = varVal\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Load from overrides\n\tfor k, v := range override {\n\t\tfor _, schema := range m.Config().Variables {\n\t\t\tif schema.Name != k {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tswitch schema.Type() {\n\t\t\tcase config.VariableTypeList:\n\t\t\t\tresult[k] = v\n\t\t\tcase config.VariableTypeMap:\n\t\t\t\tif err := varSetMap(result, k, v); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\tcase config.VariableTypeString:\n\t\t\t\t\/\/ Convert to a string and set. We don't catch any errors\n\t\t\t\t\/\/ here because the validation step later should catch\n\t\t\t\t\/\/ any type errors.\n\t\t\t\tvar strVal string\n\t\t\t\tif err := hilmapstructure.WeakDecode(v, &strVal); err == nil {\n\t\t\t\t\tresult[k] = strVal\n\t\t\t\t} else {\n\t\t\t\t\tresult[k] = v\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Sprintf(\n\t\t\t\t\t\"Unhandled var type: %T\\n\\n\"+\n\t\t\t\t\t\t\"THIS IS A BUG. Please report it.\",\n\t\t\t\t\tschema.Type()))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result, nil\n}\n\n\/\/ varSetMap sets or merges the map in \"v\" with the key \"k\" in the\n\/\/ \"current\" set of variables. This is just a private function to remove\n\/\/ duplicate logic in Variables\nfunc varSetMap(current map[string]interface{}, k string, v interface{}) error {\n\texisting, ok := current[k]\n\tif !ok {\n\t\tcurrent[k] = v\n\t\treturn nil\n\t}\n\n\texistingMap, ok := existing.(map[string]interface{})\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"%q is not a map, this is a bug in Terraform.\", k))\n\t}\n\n\tswitch typedV := v.(type) {\n\tcase []map[string]interface{}:\n\t\tfor newKey, newVal := range typedV[0] {\n\t\t\texistingMap[newKey] = newVal\n\t\t}\n\tcase map[string]interface{}:\n\t\tfor newKey, newVal := range typedV {\n\t\t\texistingMap[newKey] = newVal\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"variable %q should be type map, got %s\", k, hclTypeName(v))\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package uniconfig\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar ENV_PREFIX = \"\"\n\ntype ConfigItem struct {\n\tSection string\n\tName    string\n\tValue   reflect.Value\n\tHelp    string\n}\n\nfunc (i *ConfigItem) EnvVarName() string {\n\tname := strings.ToUpper(i.Name)\n\tif i.Section == \"\" {\n\t\treturn ENV_PREFIX + name\n\t}\n\treturn ENV_PREFIX + strings.ToUpper(i.Section) + \"_\" + name\n}\n\nfunc (i *ConfigItem) CmdFlagName() string {\n\tname := strings.ToLower(i.Name)\n\tif i.Section == \"\" {\n\t\treturn name\n\t}\n\treturn strings.ToLower(i.Section) + \"-\" + name\n}\n\nfunc (i *ConfigItem) InitFlag() {\n\tname := i.CmdFlagName()\n\tswitch i.Value.Kind() {\n\tcase reflect.String:\n\t\tv := i.Value.Addr().Interface().(*string)\n\t\tflag.StringVar(v, name, *v, i.Help)\n\tcase reflect.Int:\n\t\tv := i.Value.Addr().Interface().(*int)\n\t\tflag.IntVar(v, name, *v, i.Help)\n\tcase reflect.Int64:\n\t\tv := i.Value.Addr().Interface().(*int64)\n\t\tflag.Int64Var(v, name, *v, i.Help)\n\tcase reflect.Bool:\n\t\tv := i.Value.Addr().Interface().(*bool)\n\t\tflag.BoolVar(v, name, *v, i.Help)\n\tcase reflect.Slice:\n\t\tswitch i.Value.Type() {\n\t\tcase intSliceType:\n\t\t\tv := i.Value.Addr().Interface().(*[]int)\n\t\t\tv1 := NewIntSlice(v)\n\t\t\tflag.Var(v1, name, i.Help)\n\t\tcase strSliceType:\n\t\t\tv := i.Value.Addr().Interface().(*[]string)\n\t\t\tv1 := NewStrSlice(v)\n\t\t\tflag.Var(v1, name, i.Help)\n\t\tcase floatSliceType:\n\t\t\tv := i.Value.Addr().Interface().(*[]float64)\n\t\t\tv1 := NewFloatSlice(v)\n\t\t\tflag.Var(v1, name, i.Help)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Unexpected type of config entry: %v\", i)\n\t\t}\n\tdefault:\n\t\tlog.Fatalf(\"Unexpected type of config entry: %v\", i)\n\t}\n}\n\nfunc ScanConfig(config interface{}) []*ConfigItem {\n\titems := make([]*ConfigItem, 0)\n\n\teConfig := reflect.ValueOf(config).Elem()\n\ttConfig := eConfig.Type()\n\n\tfor i := 0; i < tConfig.NumField(); i++ {\n\t\tf := tConfig.Field(i)\n\n\t\tif f.PkgPath != \"\" {\n\t\t\tcontinue \/\/ skip private fields\n\t\t}\n\t\tv := eConfig.Field(i)\n\t\tif f.Type.Kind() == reflect.Struct {\n\t\t\tfor j := 0; j < f.Type.NumField(); j++ {\n\t\t\t\tff := f.Type.Field(j)\n\t\t\t\tif ff.PkgPath != \"\" {\n\t\t\t\t\tcontinue \/\/ skip private fields\n\t\t\t\t}\n\t\t\t\tvv := v.Field(j)\n\t\t\t\titem := &ConfigItem{\n\t\t\t\t\tSection: f.Name,\n\t\t\t\t\tName:    ff.Name,\n\t\t\t\t\tValue:   vv,\n\t\t\t\t\tHelp:    ff.Tag.Get(\"help\"),\n\t\t\t\t}\n\t\t\t\titems = append(items, item)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\titem := &ConfigItem{\n\t\t\tSection: \"\",\n\t\t\tName:    f.Name,\n\t\t\tValue:   v,\n\t\t\tHelp:    f.Tag.Get(\"help\"),\n\t\t}\n\t\titems = append(items, item)\n\t}\n\treturn items\n}\n\nfunc LoadFromEnv(configItems []*ConfigItem) {\n\tfor _, item := range configItems {\n\t\tv := os.Getenv(item.EnvVarName())\n\t\tif v != \"\" {\n\t\t\tflag.Set(item.CmdFlagName(), v)\n\t\t}\n\t}\n}\n\nfunc ParseIniFile(inifile io.Reader) map[string]string {\n\tscanner := bufio.NewScanner(inifile)\n\tresult := make(map[string]string)\n\t\/\/ keys are stored in form of KEY or SECTION_KEY, always-uppercase\n\t\/\/ (so they match our convention for environment variable names)\n\tsection := \"\"\n\n\treSection := regexp.MustCompile(`^\\[(.*)\\]$`)\n\treKeyValue := regexp.MustCompile(`^([^=]+?)\\s*=\\s*(.*)$`)\n\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\t\tif len(line) == 0 || line[0] == ';' || line[0] == '#' {\n\t\t\tcontinue\n\t\t}\n\t\tif m := reSection.FindStringSubmatch(line); m != nil {\n\t\t\tsection = strings.ToUpper(m[1])\n\t\t\tcontinue\n\t\t}\n\t\tif m := reKeyValue.FindStringSubmatch(line); m != nil {\n\t\t\tkey := strings.ToUpper(m[1])\n\t\t\tif section != \"\" {\n\t\t\t\tkey = section + \"_\" + key\n\t\t\t}\n\t\t\tvalue := m[2]\n\t\t\tresult[key] = value\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn result\n}\n\nfunc GetConfigPathFromCmd(args []string) string {\n\t\/\/ We will search the command line for --config option.\n\t\/\/ We must do this manually and not via `flag` package,\n\t\/\/ because cmd flags must override config file params\n\t\/\/ (and therefore flag.Parse() must be called *after* we've read the config file)\n\treArgValue := regexp.MustCompile(`^[^=]+=\"?(.+?)\"?$`) \/\/ optionally quoted value\n\tfor i, arg := range args {\n\t\tif (arg == \"-config\" || arg == \"--config\") && i < len(args)-1 {\n\t\t\treturn args[i+1]\n\t\t}\n\t\tif strings.HasPrefix(arg, \"-config=\") || strings.HasPrefix(arg, \"--config=\") {\n\t\t\tif m := reArgValue.FindStringSubmatch(arg); m != nil {\n\t\t\t\treturn m[1]\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc SetFromParsedIniFile(configItems []*ConfigItem, ini map[string]string) {\n\tfor _, item := range configItems {\n\t\tk := item.EnvVarName()\n\t\tv, ok := ini[k]\n\t\tif ok {\n\t\t\tflag.Set(item.CmdFlagName(), v)\n\t\t}\n\t}\n}\n\nfunc LoadFromConfigFile(configItems []*ConfigItem) {\n\tconfigFilename := GetConfigPathFromCmd(os.Args[1:])\n\tif configFilename == \"\" {\n\t\treturn\n\t}\n\tf, err := os.Open(configFilename)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error loading config file %s: %s\", configFilename, err)\n\t}\n\tdefer f.Close()\n\tdict := ParseIniFile(f)\n\tSetFromParsedIniFile(configItems, dict)\n}\n\nfunc ItemsAsIniFile(configItems []*ConfigItem) string {\n\tsections := make(map[string][]*ConfigItem)\n\tfor _, item := range configItems {\n\t\tsections[item.Section] = append(sections[item.Section], item)\n\t}\n\tiniLines := make([]string, 0)\n\tdumpSection := func(section string) {\n\t\tfor _, item := range sections[section] {\n\t\t\tline := fmt.Sprintf(\"%s = %v\", item.Name, item.Value.Interface())\n\t\t\tiniLines = append(iniLines, line)\n\t\t}\n\t\tiniLines = append(iniLines, \"\")\n\t}\n\tdumpSection(\"\")\n\tdelete(sections, \"\")\n\tfor section := range sections {\n\t\tline := fmt.Sprintf(\"[%s]\", section)\n\t\tiniLines = append(iniLines, line)\n\t\tdumpSection(section)\n\t}\n\treturn strings.Join(iniLines, \"\\n\")\n}\n\nfunc InitFlags(configItems []*ConfigItem) {\n\tflag.String(\"config\", \"\", \"path to configuration file\") \/\/ only to provide help\n\tfor _, item := range configItems {\n\t\titem.InitFlag()\n\t}\n}\n\nfunc LoadFromFlags(configItems []*ConfigItem) {\n\tflag.Parse()\n}\n\nfunc ConfigAsIniFile(config interface{}) string {\n\titems := ScanConfig(config)\n\treturn ItemsAsIniFile(items)\n}\n\nfunc Load(config interface{}) {\n\titems := ScanConfig(config)\n\tInitFlags(items)\n\tLoadFromConfigFile(items)\n\tLoadFromEnv(items)\n\tLoadFromFlags(items)\n}\n<commit_msg>convert ENV_PREFIX to CamelCase<commit_after>package uniconfig\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nvar EnvPrefix = \"\"\n\ntype ConfigItem struct {\n\tSection string\n\tName    string\n\tValue   reflect.Value\n\tHelp    string\n}\n\nfunc (i *ConfigItem) EnvVarName() string {\n\tname := strings.ToUpper(i.Name)\n\tif i.Section == \"\" {\n\t\treturn EnvPrefix + name\n\t}\n\treturn EnvPrefix + strings.ToUpper(i.Section) + \"_\" + name\n}\n\nfunc (i *ConfigItem) CmdFlagName() string {\n\tname := strings.ToLower(i.Name)\n\tif i.Section == \"\" {\n\t\treturn name\n\t}\n\treturn strings.ToLower(i.Section) + \"-\" + name\n}\n\nfunc (i *ConfigItem) InitFlag() {\n\tname := i.CmdFlagName()\n\tswitch i.Value.Kind() {\n\tcase reflect.String:\n\t\tv := i.Value.Addr().Interface().(*string)\n\t\tflag.StringVar(v, name, *v, i.Help)\n\tcase reflect.Int:\n\t\tv := i.Value.Addr().Interface().(*int)\n\t\tflag.IntVar(v, name, *v, i.Help)\n\tcase reflect.Int64:\n\t\tv := i.Value.Addr().Interface().(*int64)\n\t\tflag.Int64Var(v, name, *v, i.Help)\n\tcase reflect.Bool:\n\t\tv := i.Value.Addr().Interface().(*bool)\n\t\tflag.BoolVar(v, name, *v, i.Help)\n\tcase reflect.Slice:\n\t\tswitch i.Value.Type() {\n\t\tcase intSliceType:\n\t\t\tv := i.Value.Addr().Interface().(*[]int)\n\t\t\tv1 := NewIntSlice(v)\n\t\t\tflag.Var(v1, name, i.Help)\n\t\tcase strSliceType:\n\t\t\tv := i.Value.Addr().Interface().(*[]string)\n\t\t\tv1 := NewStrSlice(v)\n\t\t\tflag.Var(v1, name, i.Help)\n\t\tcase floatSliceType:\n\t\t\tv := i.Value.Addr().Interface().(*[]float64)\n\t\t\tv1 := NewFloatSlice(v)\n\t\t\tflag.Var(v1, name, i.Help)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Unexpected type of config entry: %v\", i)\n\t\t}\n\tdefault:\n\t\tlog.Fatalf(\"Unexpected type of config entry: %v\", i)\n\t}\n}\n\nfunc ScanConfig(config interface{}) []*ConfigItem {\n\titems := make([]*ConfigItem, 0)\n\n\teConfig := reflect.ValueOf(config).Elem()\n\ttConfig := eConfig.Type()\n\n\tfor i := 0; i < tConfig.NumField(); i++ {\n\t\tf := tConfig.Field(i)\n\n\t\tif f.PkgPath != \"\" {\n\t\t\tcontinue \/\/ skip private fields\n\t\t}\n\t\tv := eConfig.Field(i)\n\t\tif f.Type.Kind() == reflect.Struct {\n\t\t\tfor j := 0; j < f.Type.NumField(); j++ {\n\t\t\t\tff := f.Type.Field(j)\n\t\t\t\tif ff.PkgPath != \"\" {\n\t\t\t\t\tcontinue \/\/ skip private fields\n\t\t\t\t}\n\t\t\t\tvv := v.Field(j)\n\t\t\t\titem := &ConfigItem{\n\t\t\t\t\tSection: f.Name,\n\t\t\t\t\tName:    ff.Name,\n\t\t\t\t\tValue:   vv,\n\t\t\t\t\tHelp:    ff.Tag.Get(\"help\"),\n\t\t\t\t}\n\t\t\t\titems = append(items, item)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\titem := &ConfigItem{\n\t\t\tSection: \"\",\n\t\t\tName:    f.Name,\n\t\t\tValue:   v,\n\t\t\tHelp:    f.Tag.Get(\"help\"),\n\t\t}\n\t\titems = append(items, item)\n\t}\n\treturn items\n}\n\nfunc LoadFromEnv(configItems []*ConfigItem) {\n\tfor _, item := range configItems {\n\t\tv := os.Getenv(item.EnvVarName())\n\t\tif v != \"\" {\n\t\t\tflag.Set(item.CmdFlagName(), v)\n\t\t}\n\t}\n}\n\nfunc ParseIniFile(inifile io.Reader) map[string]string {\n\tscanner := bufio.NewScanner(inifile)\n\tresult := make(map[string]string)\n\t\/\/ keys are stored in form of KEY or SECTION_KEY, always-uppercase\n\t\/\/ (so they match our convention for environment variable names)\n\tsection := \"\"\n\n\treSection := regexp.MustCompile(`^\\[(.*)\\]$`)\n\treKeyValue := regexp.MustCompile(`^([^=]+?)\\s*=\\s*(.*)$`)\n\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\t\tif len(line) == 0 || line[0] == ';' || line[0] == '#' {\n\t\t\tcontinue\n\t\t}\n\t\tif m := reSection.FindStringSubmatch(line); m != nil {\n\t\t\tsection = strings.ToUpper(m[1])\n\t\t\tcontinue\n\t\t}\n\t\tif m := reKeyValue.FindStringSubmatch(line); m != nil {\n\t\t\tkey := strings.ToUpper(m[1])\n\t\t\tif section != \"\" {\n\t\t\t\tkey = section + \"_\" + key\n\t\t\t}\n\t\t\tvalue := m[2]\n\t\t\tresult[key] = value\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn result\n}\n\nfunc GetConfigPathFromCmd(args []string) string {\n\t\/\/ We will search the command line for --config option.\n\t\/\/ We must do this manually and not via `flag` package,\n\t\/\/ because cmd flags must override config file params\n\t\/\/ (and therefore flag.Parse() must be called *after* we've read the config file)\n\treArgValue := regexp.MustCompile(`^[^=]+=\"?(.+?)\"?$`) \/\/ optionally quoted value\n\tfor i, arg := range args {\n\t\tif (arg == \"-config\" || arg == \"--config\") && i < len(args)-1 {\n\t\t\treturn args[i+1]\n\t\t}\n\t\tif strings.HasPrefix(arg, \"-config=\") || strings.HasPrefix(arg, \"--config=\") {\n\t\t\tif m := reArgValue.FindStringSubmatch(arg); m != nil {\n\t\t\t\treturn m[1]\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc SetFromParsedIniFile(configItems []*ConfigItem, ini map[string]string) {\n\tfor _, item := range configItems {\n\t\tk := item.EnvVarName()\n\t\tv, ok := ini[k]\n\t\tif ok {\n\t\t\tflag.Set(item.CmdFlagName(), v)\n\t\t}\n\t}\n}\n\nfunc LoadFromConfigFile(configItems []*ConfigItem) {\n\tconfigFilename := GetConfigPathFromCmd(os.Args[1:])\n\tif configFilename == \"\" {\n\t\treturn\n\t}\n\tf, err := os.Open(configFilename)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error loading config file %s: %s\", configFilename, err)\n\t}\n\tdefer f.Close()\n\tdict := ParseIniFile(f)\n\tSetFromParsedIniFile(configItems, dict)\n}\n\nfunc ItemsAsIniFile(configItems []*ConfigItem) string {\n\tsections := make(map[string][]*ConfigItem)\n\tfor _, item := range configItems {\n\t\tsections[item.Section] = append(sections[item.Section], item)\n\t}\n\tiniLines := make([]string, 0)\n\tdumpSection := func(section string) {\n\t\tfor _, item := range sections[section] {\n\t\t\tline := fmt.Sprintf(\"%s = %v\", item.Name, item.Value.Interface())\n\t\t\tiniLines = append(iniLines, line)\n\t\t}\n\t\tiniLines = append(iniLines, \"\")\n\t}\n\tdumpSection(\"\")\n\tdelete(sections, \"\")\n\tfor section := range sections {\n\t\tline := fmt.Sprintf(\"[%s]\", section)\n\t\tiniLines = append(iniLines, line)\n\t\tdumpSection(section)\n\t}\n\treturn strings.Join(iniLines, \"\\n\")\n}\n\nfunc InitFlags(configItems []*ConfigItem) {\n\tflag.String(\"config\", \"\", \"path to configuration file\") \/\/ only to provide help\n\tfor _, item := range configItems {\n\t\titem.InitFlag()\n\t}\n}\n\nfunc LoadFromFlags(configItems []*ConfigItem) {\n\tflag.Parse()\n}\n\nfunc ConfigAsIniFile(config interface{}) string {\n\titems := ScanConfig(config)\n\treturn ItemsAsIniFile(items)\n}\n\nfunc Load(config interface{}) {\n\titems := ScanConfig(config)\n\tInitFlags(items)\n\tLoadFromConfigFile(items)\n\tLoadFromEnv(items)\n\tLoadFromFlags(items)\n}\n<|endoftext|>"}
{"text":"<commit_before>package channel\n\nimport (\n\t\"bytes\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com\/scrapli\/scrapligo\/util\"\n)\n\nfunc (c *Channel) read() {\n\tfor {\n\t\tselect {\n\t\tcase <-c.done:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tb, err := c.t.Read()\n\t\tif err != nil {\n\t\t\t\/\/ we got a transport error, put it into the error channel for processing during\n\t\t\t\/\/ the next read activity\n\t\t\tc.Errs <- err\n\t\t}\n\n\t\t\/\/ not 100% this is required, but has existed in scrapli\/scrapligo for a long time and am\n\t\t\/\/ afraid to remove it!\n\t\tb = bytes.ReplaceAll(b, []byte(\"\\r\"), []byte(\"\"))\n\n\t\t\/\/ trim out all the space we padded in the buffer to read into\n\t\tb = bytes.ReplaceAll(b, []byte(\"\\x00\"), []byte(\"\"))\n\n\t\tif bytes.Contains(b, []byte(\"\\x1b\")) {\n\t\t\tb = util.StripANSI(b)\n\t\t}\n\n\t\tc.Q.Enqueue(b)\n\n\t\tif c.ChannelLog != nil {\n\t\t\t_, err = c.ChannelLog.Write(b)\n\t\t\tif err != nil {\n\t\t\t\tc.l.Criticalf(\"error writing to channel log, ignoring. error: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\ttime.Sleep(c.ReadDelay)\n\t}\n}\n\n\/\/ Read reads and returns the first available bytes from the channel Q object. If there are any\n\/\/ errors on the Errs channel (these would come from the underlying transport), the error is\n\/\/ returned with nil for the byte slice.\nfunc (c *Channel) Read() ([]byte, error) {\n\tselect {\n\tcase err := <-c.Errs:\n\t\treturn nil, err\n\tdefault:\n\t}\n\n\tb := c.Q.Dequeue()\n\n\treturn b, nil\n}\n\n\/\/ ReadAll reads and returns *all* available bytes form the channel Q object. If there are any\n\/\/ errors on the Errs channel  (these would come from the underlying transport), the error is\n\/\/ returned with nil for the byte slice. Be careful using this as it is possible to dequeue \"too\n\/\/ much\" from the channel causing us to not be able to \"find\" the prompt or inputs during normal\n\/\/ operations. In general, this should probably only be used when connecting to consoles\/files.\nfunc (c *Channel) ReadAll() ([]byte, error) {\n\tselect {\n\tcase err := <-c.Errs:\n\t\treturn nil, err\n\tdefault:\n\t}\n\n\tb := c.Q.DequeueAll()\n\n\treturn b, nil\n}\n\n\/\/ ReadUntilInput reads bytes out of the channel Q object until the \"input\" bytes b are \"seen\" in\n\/\/ the channel output. Once b is seen, all read bytes are returned.\nfunc (c *Channel) ReadUntilInput(b []byte) ([]byte, error) {\n\tif len(b) == 0 {\n\t\treturn nil, nil\n\t}\n\n\treturn c.ReadUntilExplicit(b)\n}\n\n\/\/ ReadUntilPrompt reads bytes out of the channel Q object until the channel PromptPattern regex\n\/\/ pattern is seen in the output. Once that pattern is seen, all read bytes are returned.\nfunc (c *Channel) ReadUntilPrompt() ([]byte, error) {\n\tvar rb []byte\n\n\tfor {\n\t\tselect {\n\t\tcase err := <-c.Errs:\n\t\t\treturn nil, err\n\t\tdefault:\n\t\t}\n\n\t\tnb := c.Q.Dequeue()\n\n\t\tif nb == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\trb = append(rb, nb...)\n\n\t\tif c.PromptPattern.Match(rb) {\n\t\t\tc.l.Debugf(\"channel read %#v\", string(rb))\n\n\t\t\treturn rb, nil\n\t\t}\n\t}\n}\n\n\/\/ ReadUntilAnyPrompt reads bytes out of the channel Q object until any of the prompts in the\n\/\/ \"prompts\" argument are seen in the output. Once any pattern is seen, all read bytes are returned.\nfunc (c *Channel) ReadUntilAnyPrompt(prompts []*regexp.Regexp) ([]byte, error) {\n\tvar rb []byte\n\n\tfor {\n\t\tselect {\n\t\tcase err := <-c.Errs:\n\t\t\treturn nil, err\n\t\tdefault:\n\t\t}\n\n\t\tnb := c.Q.Dequeue()\n\n\t\tif nb == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\trb = append(rb, nb...)\n\n\t\tfor _, p := range prompts {\n\t\t\tif p.Match(rb) {\n\t\t\t\tc.l.Debugf(\"channel read %#v\", string(rb))\n\n\t\t\t\treturn rb, nil\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ ReadUntilExplicit reads bytes out of the channel Q object until the bytes b are seen in the\n\/\/ output. Once the bytes are seen all read bytes are returned.\nfunc (c *Channel) ReadUntilExplicit(b []byte) ([]byte, error) {\n\tvar rb []byte\n\n\tfor {\n\t\tselect {\n\t\tcase err := <-c.Errs:\n\t\t\treturn nil, err\n\t\tdefault:\n\t\t}\n\n\t\tnb := c.Q.Dequeue()\n\n\t\tif nb == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\trb = append(rb, nb...)\n\n\t\tif bytes.Contains(rb, b) {\n\t\t\tc.l.Debugf(\"channel read %#v\", string(rb))\n\n\t\t\treturn rb, nil\n\t\t}\n\t}\n}\n<commit_msg>Fix goroutine leak in channel.read when transport is closed<commit_after>package channel\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com\/scrapli\/scrapligo\/util\"\n)\n\nfunc (c *Channel) read() {\n\tfor {\n\t\tselect {\n\t\tcase <-c.done:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tb, err := c.t.Read()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\t\/\/ the underlying transport was closed so just return\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ we got a transport error, put it into the error channel for processing during\n\t\t\t\/\/ the next read activity\n\t\t\tc.Errs <- err\n\t\t}\n\n\t\t\/\/ not 100% this is required, but has existed in scrapli\/scrapligo for a long time and am\n\t\t\/\/ afraid to remove it!\n\t\tb = bytes.ReplaceAll(b, []byte(\"\\r\"), []byte(\"\"))\n\n\t\t\/\/ trim out all the space we padded in the buffer to read into\n\t\tb = bytes.ReplaceAll(b, []byte(\"\\x00\"), []byte(\"\"))\n\n\t\tif bytes.Contains(b, []byte(\"\\x1b\")) {\n\t\t\tb = util.StripANSI(b)\n\t\t}\n\n\t\tc.Q.Enqueue(b)\n\n\t\tif c.ChannelLog != nil {\n\t\t\t_, err = c.ChannelLog.Write(b)\n\t\t\tif err != nil {\n\t\t\t\tc.l.Criticalf(\"error writing to channel log, ignoring. error: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\ttime.Sleep(c.ReadDelay)\n\t}\n}\n\n\/\/ Read reads and returns the first available bytes from the channel Q object. If there are any\n\/\/ errors on the Errs channel (these would come from the underlying transport), the error is\n\/\/ returned with nil for the byte slice.\nfunc (c *Channel) Read() ([]byte, error) {\n\tselect {\n\tcase err := <-c.Errs:\n\t\treturn nil, err\n\tdefault:\n\t}\n\n\tb := c.Q.Dequeue()\n\n\treturn b, nil\n}\n\n\/\/ ReadAll reads and returns *all* available bytes form the channel Q object. If there are any\n\/\/ errors on the Errs channel  (these would come from the underlying transport), the error is\n\/\/ returned with nil for the byte slice. Be careful using this as it is possible to dequeue \"too\n\/\/ much\" from the channel causing us to not be able to \"find\" the prompt or inputs during normal\n\/\/ operations. In general, this should probably only be used when connecting to consoles\/files.\nfunc (c *Channel) ReadAll() ([]byte, error) {\n\tselect {\n\tcase err := <-c.Errs:\n\t\treturn nil, err\n\tdefault:\n\t}\n\n\tb := c.Q.DequeueAll()\n\n\treturn b, nil\n}\n\n\/\/ ReadUntilInput reads bytes out of the channel Q object until the \"input\" bytes b are \"seen\" in\n\/\/ the channel output. Once b is seen, all read bytes are returned.\nfunc (c *Channel) ReadUntilInput(b []byte) ([]byte, error) {\n\tif len(b) == 0 {\n\t\treturn nil, nil\n\t}\n\n\treturn c.ReadUntilExplicit(b)\n}\n\n\/\/ ReadUntilPrompt reads bytes out of the channel Q object until the channel PromptPattern regex\n\/\/ pattern is seen in the output. Once that pattern is seen, all read bytes are returned.\nfunc (c *Channel) ReadUntilPrompt() ([]byte, error) {\n\tvar rb []byte\n\n\tfor {\n\t\tselect {\n\t\tcase err := <-c.Errs:\n\t\t\treturn nil, err\n\t\tdefault:\n\t\t}\n\n\t\tnb := c.Q.Dequeue()\n\n\t\tif nb == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\trb = append(rb, nb...)\n\n\t\tif c.PromptPattern.Match(rb) {\n\t\t\tc.l.Debugf(\"channel read %#v\", string(rb))\n\n\t\t\treturn rb, nil\n\t\t}\n\t}\n}\n\n\/\/ ReadUntilAnyPrompt reads bytes out of the channel Q object until any of the prompts in the\n\/\/ \"prompts\" argument are seen in the output. Once any pattern is seen, all read bytes are returned.\nfunc (c *Channel) ReadUntilAnyPrompt(prompts []*regexp.Regexp) ([]byte, error) {\n\tvar rb []byte\n\n\tfor {\n\t\tselect {\n\t\tcase err := <-c.Errs:\n\t\t\treturn nil, err\n\t\tdefault:\n\t\t}\n\n\t\tnb := c.Q.Dequeue()\n\n\t\tif nb == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\trb = append(rb, nb...)\n\n\t\tfor _, p := range prompts {\n\t\t\tif p.Match(rb) {\n\t\t\t\tc.l.Debugf(\"channel read %#v\", string(rb))\n\n\t\t\t\treturn rb, nil\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ ReadUntilExplicit reads bytes out of the channel Q object until the bytes b are seen in the\n\/\/ output. Once the bytes are seen all read bytes are returned.\nfunc (c *Channel) ReadUntilExplicit(b []byte) ([]byte, error) {\n\tvar rb []byte\n\n\tfor {\n\t\tselect {\n\t\tcase err := <-c.Errs:\n\t\t\treturn nil, err\n\t\tdefault:\n\t\t}\n\n\t\tnb := c.Q.Dequeue()\n\n\t\tif nb == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\trb = append(rb, nb...)\n\n\t\tif bytes.Contains(rb, b) {\n\t\t\tc.l.Debugf(\"channel read %#v\", string(rb))\n\n\t\t\treturn rb, nil\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>bugfix<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Some parts of this file are taken from Lakrizz' example on GitHub\n\/\/ https:\/\/github.com\/lakrizz\/go-pidioder\/blob\/master\/main.go\n\npackage dioder\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"image\/color\"\n\t\"os\"\n\t\"strconv\"\n)\n\n\/\/Pins the numbers of the RGB-pins\ntype Pins struct {\n\tRed   string\n\tGreen string\n\tBlue  string\n}\n\n\/\/Dioder the main structure\ntype Dioder struct {\n\tPinConfiguration   Pins\n\tColorConfiguration color.RGBA\n\tPiBlaster          string\n}\n\n\/\/New creates a new instance\nfunc New(pinConfiguration Pins, piBlasterFile string) Dioder {\n\tif piBlasterFile == \"\" {\n\t\tpiBlasterFile = \"\/dev\/pi-blaster\"\n\t}\n\n\td := Dioder{}\n\n\td.SetPins(pinConfiguration)\n\td.PiBlaster = piBlasterFile\n\n\treturn d\n}\n\n\/\/ GetCurrentColor returns the current color\nfunc (d *Dioder) GetCurrentColor() color.RGBA {\n\treturn d.ColorConfiguration\n}\n\n\/\/ SetAll sets the given values for the channels\nfunc (d *Dioder) SetAll(colorSet color.RGBA) {\n\td.ColorConfiguration = colorSet\n\t\/\/Red\n\tcolorSet.R = calculateOpacity(colorSet.R, colorSet.A)\n\tif colorSet.R != d.ColorConfiguration.R {\n\t\td.SetChannelInteger(colorSet.R, d.PinConfiguration.Red)\n\t}\n\n\t\/\/Green\n\tcolorSet.G = calculateOpacity(colorSet.G, colorSet.A)\n\tif colorSet.G != d.ColorConfiguration.G {\n\t\td.SetChannelInteger(colorSet.G, d.PinConfiguration.Green)\n\t}\n\n\t\/\/Blue\n\tcolorSet.B = calculateOpacity(colorSet.B, colorSet.A)\n\tif colorSet.B != d.ColorConfiguration.B {\n\t\td.SetChannelInteger(colorSet.B, d.PinConfiguration.Blue)\n\t}\n\n}\n\n\/\/SetPins configures the pin-layout\nfunc (d *Dioder) SetPins(pinConfiguration Pins) {\n\td.PinConfiguration = pinConfiguration\n}\n\n\/\/TurnOff turns off the dioder-strips and saves the current configuration\nfunc (d *Dioder) TurnOff() {\n\t\/\/Temporary save the configuration\n\tconfiguration := d.ColorConfiguration\n\td.SetAll(color.RGBA{})\n\td.ColorConfiguration = configuration\n}\n\n\/\/TurnOn turns the dioder-strips on and restores the previous configuration\nfunc (d *Dioder) TurnOn() {\n\tif d.ColorConfiguration.A == 0 && d.ColorConfiguration.B == 0 && d.ColorConfiguration.G == 0 && d.ColorConfiguration.R == 0 {\n\t\td.ColorConfiguration = color.RGBA{255, 255, 255, 100}\n\t}\n\n\t\/\/@ToDo: Refactor\n\t\/\/Ugliy hack, to turn the lights back on\n\tcolorSet := d.ColorConfiguration\n\td.ColorConfiguration = color.RGBA{}\n\n\td.SetAll(colorSet)\n}\n\nfunc floatToString(floatValue float64) string {\n\treturn strconv.FormatFloat(floatValue, 'f', 6, 64)\n}\n\n\/\/SetColor Sets a color on the given channel\nfunc (d *Dioder) SetColor(channel string, value float64) error {\n\tpiBlasterCommand := channel + \"=\" + floatToString(value) + \"\\n\"\n\n\tfile, error := os.OpenFile(d.PiBlaster, os.O_RDWR, os.ModeNamedPipe)\n\n\tif error != nil {\n\t\tpanic(error)\n\t}\n\n\tdefer file.Close()\n\n\tstream := bufio.NewWriter(file)\n\n\t_, error = stream.WriteString(piBlasterCommand)\n\n\tif error != nil {\n\t\tpanic(error)\n\t}\n\n\tstream.Flush()\n\n\treturn nil\n}\n\n\/\/SetChannelInteger check if the value is in the correct range and convert it to float64\nfunc (d *Dioder) SetChannelInteger(value uint8, channel string) error {\n\tif value > 255 {\n\t\treturn errors.New(\"Value can not be over 255\")\n\t}\n\n\tif value < 0 {\n\t\treturn errors.New(\"Value can not be under 0\")\n\t}\n\n\tfloatval := float64(value) \/ 255.0\n\n\td.SetColor(channel, float64(floatval))\n\n\treturn nil\n}\n\n\/*func (d *Dioder) fade(currentValue uint8, targetValue uint8, fadeTime time.Duration, channel string) {\n\t\/\/Fade:\n\t\/\/Einteilung der Werteminderung pro Zeiteinheit anhand der Werte zwischen currentValue und targetValue\n\tvar neededSteps uint8\n\n\tif currentValue < targetValue {\n\t\tneededSteps = targetValue - currentValue\n\t} else {\n\t\tneededSteps = currentValue - targetValue\n\t}\n\n\tfor neededSteps {\n\t\t\/\/set value\n\t\t\/\/sleep duration \/ neededSteps\n\t}\n\n}*\/\n\n\/\/calculateOpacity calculates the value of colorValue after applying some opacity\nfunc calculateOpacity(colorValue uint8, opacity uint8) uint8 {\n\tvar calculatedValue float32\n\n\tif opacity != 100 {\n\t\tcalculatedValue = float32(colorValue) \/ 100 * float32(opacity)\n\t} else {\n\t\tcalculatedValue = float32(colorValue)\n\t}\n\n\treturn uint8(calculatedValue)\n}\n<commit_msg>Just set the color<commit_after>\/\/ Some parts of this file are taken from Lakrizz' example on GitHub\n\/\/ https:\/\/github.com\/lakrizz\/go-pidioder\/blob\/master\/main.go\n\npackage dioder\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"image\/color\"\n\t\"os\"\n\t\"strconv\"\n)\n\n\/\/Pins the numbers of the RGB-pins\ntype Pins struct {\n\tRed   string\n\tGreen string\n\tBlue  string\n}\n\n\/\/Dioder the main structure\ntype Dioder struct {\n\tPinConfiguration   Pins\n\tColorConfiguration color.RGBA\n\tPiBlaster          string\n}\n\n\/\/New creates a new instance\nfunc New(pinConfiguration Pins, piBlasterFile string) Dioder {\n\tif piBlasterFile == \"\" {\n\t\tpiBlasterFile = \"\/dev\/pi-blaster\"\n\t}\n\n\td := Dioder{}\n\n\td.SetPins(pinConfiguration)\n\td.PiBlaster = piBlasterFile\n\n\treturn d\n}\n\n\/\/ GetCurrentColor returns the current color\nfunc (d *Dioder) GetCurrentColor() color.RGBA {\n\treturn d.ColorConfiguration\n}\n\n\/\/ SetAll sets the given values for the channels\nfunc (d *Dioder) SetAll(colorSet color.RGBA) {\n\td.ColorConfiguration = colorSet\n\t\/\/Red\n\tcolorSet.R = calculateOpacity(colorSet.R, colorSet.A)\n\td.SetChannelInteger(colorSet.R, d.PinConfiguration.Red)\n\t\/\/Green\n\tcolorSet.G = calculateOpacity(colorSet.G, colorSet.A)\n\td.SetChannelInteger(colorSet.G, d.PinConfiguration.Green)\n\n\t\/\/Blue\n\tcolorSet.B = calculateOpacity(colorSet.B, colorSet.A)\n\td.SetChannelInteger(colorSet.B, d.PinConfiguration.Blue)\n}\n\n\/\/SetPins configures the pin-layout\nfunc (d *Dioder) SetPins(pinConfiguration Pins) {\n\td.PinConfiguration = pinConfiguration\n}\n\n\/\/TurnOff turns off the dioder-strips and saves the current configuration\nfunc (d *Dioder) TurnOff() {\n\t\/\/Temporary save the configuration\n\tconfiguration := d.ColorConfiguration\n\td.SetAll(color.RGBA{})\n\td.ColorConfiguration = configuration\n}\n\n\/\/TurnOn turns the dioder-strips on and restores the previous configuration\nfunc (d *Dioder) TurnOn() {\n\tif d.ColorConfiguration.A == 0 && d.ColorConfiguration.B == 0 && d.ColorConfiguration.G == 0 && d.ColorConfiguration.R == 0 {\n\t\td.ColorConfiguration = color.RGBA{255, 255, 255, 100}\n\t}\n\n\t\/\/@ToDo: Refactor\n\t\/\/Ugliy hack, to turn the lights back on\n\tcolorSet := d.ColorConfiguration\n\td.ColorConfiguration = color.RGBA{}\n\n\td.SetAll(colorSet)\n}\n\nfunc floatToString(floatValue float64) string {\n\treturn strconv.FormatFloat(floatValue, 'f', 6, 64)\n}\n\n\/\/SetColor Sets a color on the given channel\nfunc (d *Dioder) SetColor(channel string, value float64) error {\n\tpiBlasterCommand := channel + \"=\" + floatToString(value) + \"\\n\"\n\n\tfile, error := os.OpenFile(d.PiBlaster, os.O_RDWR, os.ModeNamedPipe)\n\n\tif error != nil {\n\t\tpanic(error)\n\t}\n\n\tdefer file.Close()\n\n\tstream := bufio.NewWriter(file)\n\n\t_, error = stream.WriteString(piBlasterCommand)\n\n\tif error != nil {\n\t\tpanic(error)\n\t}\n\n\tstream.Flush()\n\n\treturn nil\n}\n\n\/\/SetChannelInteger check if the value is in the correct range and convert it to float64\nfunc (d *Dioder) SetChannelInteger(value uint8, channel string) error {\n\tif value > 255 {\n\t\treturn errors.New(\"Value can not be over 255\")\n\t}\n\n\tif value < 0 {\n\t\treturn errors.New(\"Value can not be under 0\")\n\t}\n\n\tfloatval := float64(value) \/ 255.0\n\n\td.SetColor(channel, float64(floatval))\n\n\treturn nil\n}\n\n\/*func (d *Dioder) fade(currentValue uint8, targetValue uint8, fadeTime time.Duration, channel string) {\n\t\/\/Fade:\n\t\/\/Einteilung der Werteminderung pro Zeiteinheit anhand der Werte zwischen currentValue und targetValue\n\tvar neededSteps uint8\n\n\tif currentValue < targetValue {\n\t\tneededSteps = targetValue - currentValue\n\t} else {\n\t\tneededSteps = currentValue - targetValue\n\t}\n\n\tfor neededSteps {\n\t\t\/\/set value\n\t\t\/\/sleep duration \/ neededSteps\n\t}\n\n}*\/\n\n\/\/calculateOpacity calculates the value of colorValue after applying some opacity\nfunc calculateOpacity(colorValue uint8, opacity uint8) uint8 {\n\tvar calculatedValue float32\n\n\tif opacity != 100 {\n\t\tcalculatedValue = float32(colorValue) \/ 100 * float32(opacity)\n\t} else {\n\t\tcalculatedValue = float32(colorValue)\n\t}\n\n\treturn uint8(calculatedValue)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 The Upspin Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage serverutil\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/ TestShutdown launches a child process, sends it SIGTERM, and, by reading its\n\/\/ standard output, checks that the process runs the required shutdown\n\/\/ functions. It also checks that the process will be forced to exit if a\n\/\/ timeout handler stalls.\nfunc TestShutdown(t *testing.T) {\n\tif os.Getenv(shutdownEnv) == \"true\" {\n\t\ttestShutdownChildProcess()\n\t\treturn\n\t}\n\n\tt.Run(\"clean\", func(t *testing.T) { testShutdown(t, true) })\n\tt.Run(\"messy\", func(t *testing.T) { testShutdown(t, false) })\n}\n\nconst (\n\tshutdownEnv     = \"SHUTDOWN_CHILD_PROCESS\"\n\tshutdownKillEnv = shutdownEnv + \"_KILL\"\n)\n\nvar shutdownMessages = []string{\n\t\"Hello\",\n\t\"How are you?\",\n\t\"Goodbye\",\n}\n\nfunc testShutdown(t *testing.T, clean bool) {\n\tcmd := exec.Command(os.Args[0], \"-test.run=TestShutdown\")\n\tcmd.Env = []string{shutdownEnv + \"=true\"}\n\tif !clean {\n\t\tcmd.Env = append(cmd.Env, shutdownKillEnv+\"=true\")\n\t}\n\n\t\/\/ Scan process output line by line.\n\trc, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tout := bufio.NewScanner(rc)\n\n\tif err := cmd.Start(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Check that we get the initial \"hello\" message from the client,\n\t\/\/ so we know it's running.\n\treadErr := make(chan error, 1)\n\tgo func() {\n\t\tout.Scan()\n\t\tif err := out.Err(); err != nil {\n\t\t\treadErr <- err\n\t\t\treturn\n\t\t}\n\t\tif got, want := out.Text(), shutdownMessages[0]; got != want {\n\t\t\treadErr <- fmt.Errorf(\"child said %q, want %q\", got, want)\n\t\t\treturn\n\t\t}\n\t\treadErr <- nil\n\t}()\n\tselect {\n\tcase err := <-readErr:\n\t\tif err != nil {\n\t\t\tcmd.Process.Kill()\n\t\t\tt.Fatal(err)\n\t\t}\n\tcase <-time.After(2 * time.Second):\n\t\tt.Fatal(\"timed out waiting for child process to say hello\")\n\t}\n\n\t\/\/ Collect and compare the remaining output lines.\n\tgo func() {\n\t\tfor n := 1; n < len(shutdownMessages); n++ {\n\t\t\tif !clean && n == 2 {\n\t\t\t\t\/\/ In messy mode the second shutdown\n\t\t\t\t\/\/ handler will not run.\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif !out.Scan() {\n\t\t\t\treadErr <- fmt.Errorf(\"child output ended, expected more lines\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif got, want := out.Text(), shutdownMessages[n]; got != want {\n\t\t\t\treadErr <- fmt.Errorf(\"child output line %q, want %q\", got, want)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif out.Scan() {\n\t\t\treadErr <- fmt.Errorf(\"child output unexpected line %q\", out.Text())\n\t\t\treturn\n\t\t}\n\t\treadErr <- nil\n\t}()\n\n\t\/\/ Kill the process and wait for it to exit, checking its exit status\n\t\/\/ depending on whether this is a clean or messy text.\n\tif err := syscall.Kill(cmd.Process.Pid, syscall.SIGTERM); err != nil {\n\t\tt.Fatal(err)\n\t}\n\twaitErr := make(chan error, 1)\n\tgo func() {\n\t\twaitErr <- cmd.Wait()\n\t}()\n\tselect {\n\tcase err := <-waitErr:\n\t\tif err != nil && clean {\n\t\t\tt.Fatalf(\"child process exited with non-zero status: %v\", err)\n\t\t} else if err == nil && !clean {\n\t\t\tt.Fatal(\"child proces exited cleanly, want non-zero status\")\n\t\t}\n\tcase <-time.After(2 * time.Second):\n\t\tt.Fatal(\"timed out waiting for child process to exit\")\n\t}\n\n\t\/\/ Check that the output was what we expected.\n\tif err := <-readErr; err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc testShutdownChildProcess() {\n\tvar kill chan bool\n\tif os.Getenv(shutdownKillEnv) == \"true\" {\n\t\tkill = make(chan bool)\n\t\tkillSleep = func(time.Duration) {\n\t\t\t<-kill\n\t\t}\n\t}\n\n\tfmt.Println(shutdownMessages[0])\n\n\tRegisterShutdown(0, func() {\n\t\tfmt.Println(shutdownMessages[1])\n\t\tif kill != nil {\n\t\t\tkill <- true\n\t\t\tselect {} \/\/ Block forever, stalling Shutdown.\n\t\t}\n\t})\n\n\tRegisterShutdown(1, func() {\n\t\tfmt.Println(shutdownMessages[2])\n\t})\n\n\tShutdown()\n\n\t\/\/ If for some reason Shutdown returns the test must time out.\n\tselect {}\n}\n<commit_msg>serverutil: fix race in TestShutdown<commit_after>\/\/ Copyright 2017 The Upspin Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage serverutil\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/ TestShutdown launches a child process, sends it SIGTERM, and, by reading its\n\/\/ standard output, checks that the process runs the required shutdown\n\/\/ functions. It also checks that the process will be forced to exit if a\n\/\/ timeout handler stalls.\nfunc TestShutdown(t *testing.T) {\n\tif os.Getenv(shutdownEnv) == \"true\" {\n\t\ttestShutdownChildProcess()\n\t\treturn\n\t}\n\n\tt.Run(\"clean\", func(t *testing.T) { testShutdown(t, true) })\n\tt.Run(\"messy\", func(t *testing.T) { testShutdown(t, false) })\n}\n\nconst (\n\tshutdownEnv     = \"SHUTDOWN_CHILD_PROCESS\"\n\tshutdownKillEnv = shutdownEnv + \"_KILL\"\n)\n\nvar shutdownMessages = []string{\n\t\"Hello\",\n\t\"How are you?\",\n\t\"Goodbye\",\n}\n\nfunc testShutdown(t *testing.T, clean bool) {\n\tcmd := exec.Command(os.Args[0], \"-test.run=TestShutdown\")\n\tcmd.Env = []string{shutdownEnv + \"=true\"}\n\tif !clean {\n\t\tcmd.Env = append(cmd.Env, shutdownKillEnv+\"=true\")\n\t}\n\n\t\/\/ Scan process output line by line.\n\trc, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tout := bufio.NewScanner(rc)\n\n\tif err := cmd.Start(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Check that we get the initial \"hello\" message from the client,\n\t\/\/ so we know it's running.\n\treadErr := make(chan error, 1)\n\tgo func() {\n\t\tout.Scan()\n\t\tif err := out.Err(); err != nil {\n\t\t\treadErr <- err\n\t\t\treturn\n\t\t}\n\t\tif got, want := out.Text(), shutdownMessages[0]; got != want {\n\t\t\treadErr <- fmt.Errorf(\"child said %q, want %q\", got, want)\n\t\t\treturn\n\t\t}\n\t\treadErr <- nil\n\t}()\n\tselect {\n\tcase err := <-readErr:\n\t\tif err != nil {\n\t\t\tcmd.Process.Kill()\n\t\t\tt.Fatal(err)\n\t\t}\n\tcase <-time.After(2 * time.Second):\n\t\tt.Fatal(\"timed out waiting for child process to say hello\")\n\t}\n\n\t\/\/ Collect and compare the remaining output lines.\n\twaitErr := make(chan error, 1)\n\tgo func() {\n\t\tfor n := 1; n < len(shutdownMessages); n++ {\n\t\t\tif !clean && n == 2 {\n\t\t\t\t\/\/ In messy mode the second shutdown\n\t\t\t\t\/\/ handler will not run.\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif !out.Scan() {\n\t\t\t\treadErr <- fmt.Errorf(\"child output ended, expected more lines\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif got, want := out.Text(), shutdownMessages[n]; got != want {\n\t\t\t\treadErr <- fmt.Errorf(\"child output line %q, want %q\", got, want)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tif out.Scan() {\n\t\t\treadErr <- fmt.Errorf(\"child output unexpected line %q\", out.Text())\n\t\t\treturn\n\t\t}\n\t\treadErr <- nil\n\t\twaitErr <- cmd.Wait()\n\t}()\n\n\t\/\/ Kill the process and wait for it to exit.\n\tif err := syscall.Kill(cmd.Process.Pid, syscall.SIGTERM); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Check that the output was what we expected.\n\tif err := <-readErr; err != nil {\n\t\tcmd.Process.Kill()\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Check exit status.\n\tselect {\n\tcase err := <-waitErr:\n\t\tif err != nil && clean {\n\t\t\tt.Fatalf(\"child process exited with non-zero status: %v\", err)\n\t\t} else if err == nil && !clean {\n\t\t\tt.Fatal(\"child proces exited cleanly, want non-zero status\")\n\t\t}\n\tcase <-time.After(2 * time.Second):\n\t\tcmd.Process.Kill()\n\t\tt.Fatal(\"timed out waiting for child process to exit\")\n\t}\n}\n\nfunc testShutdownChildProcess() {\n\tvar kill chan bool\n\tif os.Getenv(shutdownKillEnv) == \"true\" {\n\t\tkill = make(chan bool)\n\t\tkillSleep = func(time.Duration) {\n\t\t\t<-kill\n\t\t}\n\t}\n\n\tfmt.Println(shutdownMessages[0])\n\n\tRegisterShutdown(0, func() {\n\t\tfmt.Println(shutdownMessages[1])\n\t\tif kill != nil {\n\t\t\tkill <- true\n\t\t\tselect {} \/\/ Block forever, stalling Shutdown.\n\t\t}\n\t})\n\n\tRegisterShutdown(1, func() {\n\t\tfmt.Println(shutdownMessages[2])\n\t})\n\n\tShutdown()\n\n\t\/\/ If for some reason Shutdown returns the test must time out.\n\tselect {}\n}\n<|endoftext|>"}
{"text":"<commit_before>package server\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com\/object88\/langd\/proto\"\n\t\"google.golang.org\/grpc\/reflection\"\n)\n\nfunc (g *GrpcHandler) grpcService() {\n\tfmt.Printf(\"gRPC server starting\\n\")\n\n\tproto.RegisterLangdServer(g.S, g)\n\n\t\/\/ Register reflection service on gRPC server.\n\treflection.Register(g.S)\n\n\terr := g.S.Serve(g.lis)\n\tif err != nil {\n\t\tfmt.Printf(\"Got error when stopping grpc service:\\n%s\\n\", err.Error())\n\t}\n\n\tfmt.Printf(\"gRPC server stopped\\n\")\n}\n\n\/\/ Load returns the CPU and memory load\nfunc (g *GrpcHandler) Load(_ context.Context, _ *proto.EmptyRequest) (*proto.LoadReply, error) {\n\tload := &proto.LoadReply{\n\t\tCpuLoad:    g.srv.load.CPU(),    \/\/ float32(g.pc.Percent),\n\t\tMemoryLoad: g.srv.load.Memory(), \/\/ g.pm.Resident,\n\t}\n\treturn load, nil\n}\n\n\/\/ Shutdown stops the service process\nfunc (g *GrpcHandler) Shutdown(ctx context.Context, _ *proto.EmptyRequest) (*proto.EmptyReply, error) {\n\t\/\/ fmt.Printf(\"Requesting stop on JSON server\\n\")\n\t\/\/ g.SM.Shutdown(ctx)\n\n\tfmt.Printf(\"Requesting stop on gRPC\\n\")\n\t\/\/ g.S.GracefulStop()\n\n\tg.srv.done <- true\n\n\treturn &proto.EmptyReply{}, nil\n}\n\n\/\/ Startup is a no-op to start the service\nfunc (g *GrpcHandler) Startup(_ context.Context, _ *proto.EmptyRequest) (*proto.EmptyReply, error) {\n\treturn &proto.EmptyReply{}, nil\n}\n<commit_msg>Cleanup<commit_after>package server\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com\/object88\/langd\/proto\"\n\t\"google.golang.org\/grpc\/reflection\"\n)\n\nfunc (g *GrpcHandler) grpcService() {\n\tfmt.Printf(\"gRPC server starting\\n\")\n\n\tproto.RegisterLangdServer(g.S, g)\n\n\t\/\/ Register reflection service on gRPC server.\n\treflection.Register(g.S)\n\n\terr := g.S.Serve(g.lis)\n\tif err != nil {\n\t\tfmt.Printf(\"Got error when stopping grpc service:\\n%s\\n\", err.Error())\n\t}\n\n\tfmt.Printf(\"gRPC server stopped\\n\")\n}\n\n\/\/ Load returns the CPU and memory load\nfunc (g *GrpcHandler) Load(_ context.Context, _ *proto.EmptyRequest) (*proto.LoadReply, error) {\n\tload := &proto.LoadReply{\n\t\tCpuLoad:    g.srv.load.CPU(),\n\t\tMemoryLoad: g.srv.load.Memory(),\n\t}\n\treturn load, nil\n}\n\n\/\/ Shutdown stops the service process\nfunc (g *GrpcHandler) Shutdown(ctx context.Context, _ *proto.EmptyRequest) (*proto.EmptyReply, error) {\n\tg.srv.done <- true\n\treturn &proto.EmptyReply{}, nil\n}\n\n\/\/ Startup is a no-op to start the service\nfunc (g *GrpcHandler) Startup(_ context.Context, _ *proto.EmptyRequest) (*proto.EmptyReply, error) {\n\treturn &proto.EmptyReply{}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage oglemock\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\/\/ Create an Action that invokes the supplied actions one after another. The\n\/\/ return values from the final action are used; others are ignored.\nfunc DoAll(first Action, others ...Action) Action {\n\treturn &doAll{\n\t\twrapped: append([]Action{first}, others...),\n\t}\n}\n\ntype doAll struct {\n\twrapped []Action\n}\n\nfunc (a *doAll) SetSignature(signature reflect.Type) (err error) {\n\tfor i, w := range a.wrapped {\n\t\terr = w.SetSignature(signature)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Action %v: %v\", i, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (a *doAll) Invoke(methodArgs []interface{}) (rets []interface{}) {\n\tpanic(\"TODO\")\n}\n<commit_msg>doAll.Invoke<commit_after>\/\/ Copyright 2015 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage oglemock\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\n\/\/ Create an Action that invokes the supplied actions one after another. The\n\/\/ return values from the final action are used; others are ignored.\nfunc DoAll(first Action, others ...Action) Action {\n\treturn &doAll{\n\t\twrapped: append([]Action{first}, others...),\n\t}\n}\n\ntype doAll struct {\n\twrapped []Action\n}\n\nfunc (a *doAll) SetSignature(signature reflect.Type) (err error) {\n\tfor i, w := range a.wrapped {\n\t\terr = w.SetSignature(signature)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Action %v: %v\", i, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (a *doAll) Invoke(methodArgs []interface{}) (rets []interface{}) {\n\tfor _, w := range a.wrapped {\n\t\trets = w.Invoke(methodArgs)\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n*  Copyright 2013 CoreOS, Inc\n*  Copyright 2013 Docker Authors\n*\n*  Licensed under the Apache License, Version 2.0 (the \"License\");\n*  you may not use this file except in compliance with the License.\n*  You may obtain a copy of the License at\n*\n*      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n*  Unless required by applicable law or agreed to in writing, software\n*  distributed under the License is distributed on an \"AS IS\" BASIS,\n*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n*  See the License for the specific language governing permissions and\n*  limitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"os\"\n\t\"path\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"github.com\/dotcloud\/docker\"\n\t\"github.com\/dotcloud\/docker\/registry\"\n\t\"github.com\/gorilla\/mux\"\n\t\"regexp\"\n)\n\nconst ContainerDir = \"\/var\/lib\/containers\/\"\n\ntype Context struct {\n\tPath string\n\tRegistry *registry.Registry\n\tGraph *docker.Graph\n\tRepositories *docker.TagStore\n}\n\nvar context Context\n\nfunc pullImage(c *Context, imgId, registry string, token []string) error {\n\thistory, err := c.Registry.GetRemoteHistory(imgId, registry, token)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ FIXME: Try to stream the images?\n\t\/\/ FIXME: Launch the getRemoteImage() in goroutines\n\tfor _, id := range history {\n\t\tif !c.Graph.Exists(id) {\n\t\t\tlog.Printf(\"Pulling %s metadata\\r\\n\", id)\n\t\t\timgJson, err := c.Registry.GetRemoteImageJson(id, registry, token)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ FIXME: Keep goging in case of error?\n\t\t\t\treturn err\n\t\t\t}\n\t\t\timg, err := docker.NewImgJson(imgJson)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed to parse json: %s\", err)\n\t\t\t}\n\n\t\t\t\/\/ Get the layer\n\t\t\tlog.Printf(\"Pulling %s fs layer\\r\\n\", img.Id)\n\t\t\tlayer, _, err := c.Registry.GetRemoteImageLayer(img.Id, registry, token)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := c.Graph.Register(layer, false, img); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ TODO: add tag support\nfunc pullHandler(w http.ResponseWriter, r *http.Request, c *Context) {\n\tvars := mux.Vars(r)\n\tremote := vars[\"remote\"]\n\n\trepoData, err := c.Registry.GetRepositoryData(remote)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttagsList, err := c.Registry.GetRemoteTags(repoData.Endpoints, remote, repoData.Tokens)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor tag, id := range tagsList {\n\t\trepoData.ImgList[id].Tag = tag\n\t}\n\n\tfor _, img := range repoData.ImgList {\n\t\tlog.Printf(\"Pulling image %s (%s) from %s\\n\", img.Id, img.Tag, remote)\n\t\tsuccess := false\n\n\t\tfor _, ep := range repoData.Endpoints {\n\t\t\tif err := pullImage(c, img.Id, \"https:\/\/\"+ep+\"\/v1\", repoData.Tokens); err != nil {\n\t\t\t\tfmt.Printf(\"Error while retrieving image for tag: %s; checking next endpoint\\n\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsuccess = true\n\t\t\tbreak\n\t\t}\n\n\t\tif !success {\n\t\t\tlog.Fatal(\"Could not find repository on any of the indexed registries.\")\n\t\t}\n\t}\n\n\tfor tag, id := range tagsList {\n\t\tif err := c.Repositories.Set(remote, tag, id, true); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t\treturn\n\t\t}\n\t}\n\tif err := c.Repositories.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"%v\\n\", repoData)\n}\n\nfunc createHandler(w http.ResponseWriter, r *http.Request, c *Context) {\n\timageName := r.FormValue(\"image\")\n\n\t\/\/ TODO: @philips Don't hardcode the tag name here\n\timage, err := c.Repositories.GetImage(imageName, \"latest\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tif imageName == \"\" {\n\t\tw.WriteHeader(404)\n\t\tfmt.Fprintf(w, \"Cannot find container image: %s\", imageName)\n\t\treturn\n\t}\n\n\t\/\/ Figure out the resting place of the container\n\tvars := mux.Vars(r)\n\tcontainer := vars[\"container\"]\n\n\tvalidID := regexp.MustCompile(`^[A-Za-z0-9]+$`)\n\tif !validID.MatchString(container) {\n\t\tw.WriteHeader(400)\n\t\tfmt.Fprintf(w, \"Invalid container name: %s\\n\", container)\n\t\treturn\n\t}\n\n\tcontainer = path.Join(ContainerDir, container)\n\n\terr = os.Mkdir(container, 0700)\n\tif os.IsExist(err) {\n\t\tw.WriteHeader(400)\n\t\tfmt.Fprintf(w, \"Existing container: %s\\n\", container)\n\t\treturn\n\t}\n\tif err != nil {\n\t\tw.WriteHeader(400)\n\t\tfmt.Fprint(w, \"Error\")\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tcopyAll := func(img *docker.Image) (err error) {\n\t\ttarball, err := image.TarLayer(docker.Uncompressed)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := docker.Untar(tarball, container); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn\n\t}\n\n\terr = image.WalkHistory(copyAll)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tfmt.Fprint(w, \"ok\")\n\treturn\n}\n\nfunc setupDocker(r *mux.Router, o Options) {\n\tcontext.Path = o.Path\n\tp := path.Join(context.Path, \"containers\")\n\tif err := os.MkdirAll(p, 0700); err != nil && !os.IsExist(err) {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\tcontext.Registry = registry.NewRegistry(p)\n\n\tp = path.Join(context.Path, \"graph\")\n\tif err := os.MkdirAll(p, 0700); err != nil && !os.IsExist(err) {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\tg, _ := docker.NewGraph(p)\n\tcontext.Graph = g\n\n\tp = path.Join(context.Path, \"repositories\")\n\tt, _ := docker.NewTagStore(p, g)\n\tcontext.Repositories = t\n\n\tmakeHandler := func(fn func(http.ResponseWriter, *http.Request, *Context)) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\tfn(w, r, &context)\n\t\t}\n\t}\n\n\tr.HandleFunc(\"\/registry\/pull\/{remote:.*}\", makeHandler(pullHandler))\n\tr.HandleFunc(\"\/container\/create\/{container:.*}\", makeHandler(createHandler))\n}\n<commit_msg>fix(docker): use img not image in copyAll<commit_after>\/*\n*  Copyright 2013 CoreOS, Inc\n*  Copyright 2013 Docker Authors\n*\n*  Licensed under the Apache License, Version 2.0 (the \"License\");\n*  you may not use this file except in compliance with the License.\n*  You may obtain a copy of the License at\n*\n*      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n*  Unless required by applicable law or agreed to in writing, software\n*  distributed under the License is distributed on an \"AS IS\" BASIS,\n*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n*  See the License for the specific language governing permissions and\n*  limitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"os\"\n\t\"path\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"github.com\/dotcloud\/docker\"\n\t\"github.com\/dotcloud\/docker\/registry\"\n\t\"github.com\/gorilla\/mux\"\n\t\"regexp\"\n)\n\nconst ContainerDir = \"\/var\/lib\/containers\/\"\n\ntype Context struct {\n\tPath string\n\tRegistry *registry.Registry\n\tGraph *docker.Graph\n\tRepositories *docker.TagStore\n}\n\nvar context Context\n\nfunc pullImage(c *Context, imgId, registry string, token []string) error {\n\thistory, err := c.Registry.GetRemoteHistory(imgId, registry, token)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ FIXME: Try to stream the images?\n\t\/\/ FIXME: Launch the getRemoteImage() in goroutines\n\tfor _, id := range history {\n\t\tif !c.Graph.Exists(id) {\n\t\t\tlog.Printf(\"Pulling %s metadata\\r\\n\", id)\n\t\t\timgJson, err := c.Registry.GetRemoteImageJson(id, registry, token)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ FIXME: Keep goging in case of error?\n\t\t\t\treturn err\n\t\t\t}\n\t\t\timg, err := docker.NewImgJson(imgJson)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Failed to parse json: %s\", err)\n\t\t\t}\n\n\t\t\t\/\/ Get the layer\n\t\t\tlog.Printf(\"Pulling %s fs layer\\r\\n\", img.Id)\n\t\t\tlayer, _, err := c.Registry.GetRemoteImageLayer(img.Id, registry, token)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := c.Graph.Register(layer, false, img); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ TODO: add tag support\nfunc pullHandler(w http.ResponseWriter, r *http.Request, c *Context) {\n\tvars := mux.Vars(r)\n\tremote := vars[\"remote\"]\n\n\trepoData, err := c.Registry.GetRepositoryData(remote)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttagsList, err := c.Registry.GetRemoteTags(repoData.Endpoints, remote, repoData.Tokens)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor tag, id := range tagsList {\n\t\trepoData.ImgList[id].Tag = tag\n\t}\n\n\tfor _, img := range repoData.ImgList {\n\t\tlog.Printf(\"Pulling image %s (%s) from %s\\n\", img.Id, img.Tag, remote)\n\t\tsuccess := false\n\n\t\tfor _, ep := range repoData.Endpoints {\n\t\t\tif err := pullImage(c, img.Id, \"https:\/\/\"+ep+\"\/v1\", repoData.Tokens); err != nil {\n\t\t\t\tfmt.Printf(\"Error while retrieving image for tag: %s; checking next endpoint\\n\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tsuccess = true\n\t\t\tbreak\n\t\t}\n\n\t\tif !success {\n\t\t\tlog.Fatal(\"Could not find repository on any of the indexed registries.\")\n\t\t}\n\t}\n\n\tfor tag, id := range tagsList {\n\t\tif err := c.Repositories.Set(remote, tag, id, true); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t\treturn\n\t\t}\n\t}\n\tif err := c.Repositories.Save(); err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"%v\\n\", repoData)\n}\n\nfunc createHandler(w http.ResponseWriter, r *http.Request, c *Context) {\n\timageName := r.FormValue(\"image\")\n\n\t\/\/ TODO: @philips Don't hardcode the tag name here\n\timage, err := c.Repositories.GetImage(imageName, \"latest\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tif imageName == \"\" {\n\t\tw.WriteHeader(404)\n\t\tfmt.Fprintf(w, \"Cannot find container image: %s\", imageName)\n\t\treturn\n\t}\n\n\t\/\/ Figure out the resting place of the container\n\tvars := mux.Vars(r)\n\tcontainer := vars[\"container\"]\n\n\tvalidID := regexp.MustCompile(`^[A-Za-z0-9]+$`)\n\tif !validID.MatchString(container) {\n\t\tw.WriteHeader(400)\n\t\tfmt.Fprintf(w, \"Invalid container name: %s\\n\", container)\n\t\treturn\n\t}\n\n\tcontainer = path.Join(ContainerDir, container)\n\n\terr = os.Mkdir(container, 0700)\n\tif os.IsExist(err) {\n\t\tw.WriteHeader(400)\n\t\tfmt.Fprintf(w, \"Existing container: %s\\n\", container)\n\t\treturn\n\t}\n\tif err != nil {\n\t\tw.WriteHeader(400)\n\t\tfmt.Fprint(w, \"Error\")\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tcopyAll := func(img *docker.Image) (err error) {\n\t\tlog.Printf(\"Copying %s into %s\", img.Id, container)\n\t\ttarball, err := img.TarLayer(docker.Uncompressed)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := docker.Untar(tarball, container); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn\n\t}\n\n\terr = image.WalkHistory(copyAll)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tfmt.Fprint(w, \"ok\")\n\treturn\n}\n\nfunc setupDocker(r *mux.Router, o Options) {\n\tcontext.Path = o.Path\n\tp := path.Join(context.Path, \"containers\")\n\tif err := os.MkdirAll(p, 0700); err != nil && !os.IsExist(err) {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\tcontext.Registry = registry.NewRegistry(p)\n\n\tp = path.Join(context.Path, \"graph\")\n\tif err := os.MkdirAll(p, 0700); err != nil && !os.IsExist(err) {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\tg, _ := docker.NewGraph(p)\n\tcontext.Graph = g\n\n\tp = path.Join(context.Path, \"repositories\")\n\tt, _ := docker.NewTagStore(p, g)\n\tcontext.Repositories = t\n\n\tmakeHandler := func(fn func(http.ResponseWriter, *http.Request, *Context)) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\tfn(w, r, &context)\n\t\t}\n\t}\n\n\tr.HandleFunc(\"\/registry\/pull\/{remote:.*}\", makeHandler(pullHandler))\n\tr.HandleFunc(\"\/container\/create\/{container:.*}\", makeHandler(createHandler))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"code.google.com\/p\/gopass\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"github.com\/percona\/cloud-protocol\/proto\"\n\t\"github.com\/percona\/cloud-tools\/agent\"\n\t\"github.com\/percona\/cloud-tools\/instance\"\n\tmmMySQL \"github.com\/percona\/cloud-tools\/mm\/mysql\"\n\tmmServer \"github.com\/percona\/cloud-tools\/mm\/system\"\n\t\"github.com\/percona\/cloud-tools\/mysql\"\n\t\"github.com\/percona\/cloud-tools\/pct\"\n\t\"github.com\/percona\/cloud-tools\/qan\"\n\tsysconfigMySQL \"github.com\/percona\/cloud-tools\/sysconfig\/mysql\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype Flags map[string]bool\n\nvar portNumberRe = regexp.MustCompile(`\\.\\d+$`)\n\ntype Installer struct {\n\tterm        *Terminal\n\tapi         pct.APIConnector\n\tagentConfig *agent.Config\n\tflags       Flags\n\t\/\/ --\n\thostname string\n}\n\nfunc NewInstaller(term *Terminal, api pct.APIConnector, agentConfig *agent.Config, flags Flags) *Installer {\n\tif agentConfig.ApiHostname == \"\" {\n\t\tagentConfig.ApiHostname = agent.DEFAULT_API_HOSTNAME\n\t}\n\thostname, _ := os.Hostname()\n\tinstaller := &Installer{\n\t\tterm:        term,\n\t\tapi:         api,\n\t\tagentConfig: agentConfig,\n\t\tflags:       flags,\n\t\t\/\/ --\n\t\thostname: hostname,\n\t}\n\treturn installer\n}\n\nfunc (i *Installer) Run() error {\n\n\tfmt.Printf(\"API host: %s\\n\", i.agentConfig.ApiHostname)\n\n\t\/**\n\t * Get the API key.\n\t *\/\n\n\tfor i.agentConfig.ApiKey == \"\" {\n\t\tapiKey, err := i.term.PromptString(\"API key\", \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif apiKey == \"\" {\n\t\t\tfmt.Println(\"API key is required, please try again.\")\n\t\t\tcontinue\n\t\t}\n\t\ti.agentConfig.ApiKey = apiKey\n\t\tbreak\n\t}\n\n\t\/**\n\t * Verify the API key by pinging the API.\n\t *\/\n\nVERIFY_API_KEY:\n\tfor {\n\t\tfmt.Printf(\"Verifying API key %s...\\n\", i.agentConfig.ApiKey)\n\t\tcode, err := pct.Ping(i.agentConfig.ApiHostname, i.agentConfig.ApiKey)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error: %s\\n\", err)\n\t\t}\n\t\tif i.flags[\"debug\"] {\n\t\t\tlog.Printf(\"code=%d\\n\", code)\n\t\t\tlog.Printf(\"err=%s\\n\", err)\n\t\t}\n\t\tok := false\n\t\tif code >= 500 {\n\t\t\tfmt.Printf(\"Sorry, there's an API problem (status code %d). \"+\n\t\t\t\t\"Please try to install again. If the problem continues, contact Percona.\\n\",\n\t\t\t\tcode)\n\t\t} else if code == 401 {\n\t\t\treturn fmt.Errorf(\"Access denied.  Check the API key and try again.\")\n\t\t} else if code >= 300 {\n\t\t\tfmt.Printf(\"Sorry, there's an installer problem (status code %d). \"+\n\t\t\t\t\"Please try to install again. If the problem continues, contact Percona.\\n\",\n\t\t\t\tcode)\n\t\t} else if code != 200 {\n\t\t\tfmt.Printf(\"Sorry, there's an installer problem (status code %d). \"+\n\t\t\t\t\"Please try to install again. If the problem continues, contact Percona.\\n\",\n\t\t\t\tcode)\n\t\t} else {\n\t\t\tok = true\n\t\t}\n\n\t\tif !ok {\n\t\t\tagain, err := i.term.PromptBool(\"Try again?\", \"Y\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !again {\n\t\t\t\treturn fmt.Errorf(\"Failed to verify API key\")\n\t\t\t}\n\t\t\tcontinue VERIFY_API_KEY\n\t\t}\n\n\t\tfmt.Printf(\"API key %s is OK\\n\", i.agentConfig.ApiKey)\n\t\tbreak\n\t}\n\n\t\/**\n\t * Create a MySQL user for the agent, or use an existing one.\n\t *\/\n\n\tagentDSN := mysql.DSN{}\n\tif !i.flags[\"skip-mysql\"] {\n\t\tdsn, err := i.doMySQL()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tagentDSN = dsn\n\t} else {\n\t\tfmt.Println(\"Skip creating MySQL user (-skip-mysql)\")\n\t}\n\n\t\/**\n\t * Create new API resources.\n\t *\/\n\n\tsi, err := i.createServerInstance()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Created server instance: hostname=%s id=%d\\n\", si.Hostname, si.Id)\n\n\tvar mi *proto.MySQLInstance\n\tif !i.flags[\"skip-mysql\"] {\n\t\tmi, err = i.createMySQLInstance(agentDSN)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"Created MySQL instance: dsn=%s hostname=%s id=%d\\n\", mi.DSN, mi.Hostname, si.Id)\n\t} else {\n\t\tfmt.Println(\"Skip creating MySQL instance (-skip-mysql)\")\n\t}\n\n\t\/**\n\t * Get default configs for all services.\n\t *\/\n\n\tmmServerConfig, err := i.getMmServerConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tmmServerConfig.Service = \"server\"\n\tmmServerConfig.InstanceId = si.Id\n\n\tmmMySQLConfig, err := i.getMmMySQLConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsysconfigMySQLConfig, err := i.getSysconfigMySQLConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ MySQL is local if the server hostname == MySQL hostname without port number.\n\tmysqlIsLocal := i.hostname == portNumberRe.ReplaceAllLiteralString(i.hostname, \"\")\n\tvar qanConfig *qan.Config\n\tif mysqlIsLocal {\n\t\tqanConfig, err = i.getQanConfig()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/**\n\t * Create agent with initial service configs.\n\t *\/\n\n\tagentUuid, err := i.createAgent(\n\t\tmmServerConfig,\n\t\tmmMySQLConfig,\n\t\tsysconfigMySQLConfig,\n\t\tqanConfig,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Created agent: uuid=%s\\n\", agentUuid)\n\n\treturn nil\n}\n\nfunc (i *Installer) doMySQL() (dsn mysql.DSN, err error) {\n\t\/\/ XXX Using implicit return\n\tnewMySQLUser, err := i.term.PromptBool(\"Create new MySQL account for agent?\", \"Y\")\n\tif err != nil {\n\t\treturn\n\t}\n\tif newMySQLUser {\n\t\tfmt.Println(\"Connect to MySQL to create new MySQL user for agent\")\n\t\tdsn, err = i.connectMySQL()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tfmt.Println(\"Creating new MySQL user for agent...\")\n\t\tdsn, err = i.createMySQLUser(dsn)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\t\/\/ Let user specify the MySQL account to use for the agent.\n\t\tfmt.Println(\"Use existing MySQL user for agent\")\n\t\tdsn, err = i.connectMySQL()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Printf(\"Agent MySQL user: %s\\n\", dsn)\n\treturn\n}\n\nfunc (i *Installer) connectMySQL() (mysql.DSN, error) {\n\tdsn := mysql.DSN{}\n\tuser, _ := user.Current()\n\tif user != nil {\n\t\tdsn.Username = user.Username\n\t}\n\tvar conn *mysql.Connection\n\nCONNECT_MYSQL:\n\tfor conn == nil {\n\t\tusername, err := i.term.PromptStringRequired(\"MySQL username\", dsn.Username)\n\t\tif err != nil {\n\t\t\treturn dsn, err\n\t\t}\n\t\tdsn.Username = username\n\n\t\tpassword, err := gopass.GetPass(\"MySQL password: \")\n\t\tif err != nil {\n\t\t\treturn dsn, err\n\t\t}\n\t\tdsn.Password = password\n\n\t\thostname, err := i.term.PromptStringRequired(\"MySQL host[:port] or socket file\", \"localhost\")\n\t\tif err != nil {\n\t\t\treturn dsn, err\n\t\t}\n\t\tif filepath.IsAbs(hostname) {\n\t\t\tdsn.Socket = hostname\n\t\t} else {\n\t\t\tf := strings.Split(hostname, \":\")\n\t\t\tdsn.Hostname = f[0]\n\t\t\tif len(f) > 1 {\n\t\t\t\tdsn.Port = f[1]\n\t\t\t} else {\n\t\t\t\tdsn.Port = \"3306\"\n\t\t\t}\n\t\t}\n\n\t\tdsnString, err := dsn.DSN()\n\t\tif err != nil {\n\t\t\treturn dsn, err \/\/ shouldn't happen\n\t\t}\n\n\t\tfmt.Printf(\"Connecting to MySQL %s...\\n\", dsn)\n\t\tconn = mysql.NewConnection(dsnString)\n\t\tif err := conn.Connect(1); err != nil {\n\t\t\tconn = nil\n\t\t\tfmt.Printf(\"Error connecting to MySQL %s: %s\\n\", dsn, err)\n\t\t\tagain, err := i.term.PromptBool(\"Try again?\", \"Y\")\n\t\t\tif err != nil {\n\t\t\t\treturn dsn, err\n\t\t\t}\n\t\t\tif !again {\n\t\t\t\treturn dsn, fmt.Errorf(\"Failed to connect to MySQL\")\n\t\t\t}\n\t\t\tcontinue CONNECT_MYSQL\n\t\t}\n\t\tdefer conn.Close()\n\n\t\tfmt.Printf(\"MySQL connection OK\\n\")\n\t\tbreak\n\t}\n\treturn dsn, nil\n}\n\nfunc (i *Installer) createMySQLUser(dsn mysql.DSN) (mysql.DSN, error) {\n\t\/\/ Same host:port or socket, but different user and pass.\n\tuserDSN := dsn\n\tuserDSN.Username = \"percona-agent\"\n\tuserDSN.Password = fmt.Sprintf(\"%p%d\", &dsn, rand.Uint32())\n\n\tdsnString, _ := dsn.DSN()\n\tconn := mysql.NewConnection(dsnString)\n\tif err := conn.Connect(1); err != nil {\n\t\treturn userDSN, err\n\t}\n\tdefer conn.Close()\n\n\tsql := fmt.Sprintf(\"GRANT SUPER, PROCESS, USAGE ON *.* TO '%s'@'%%' IDENTIFIED BY '%s'\",\n\t\tuserDSN.Username, userDSN.Password)\n\t_, err := conn.DB().Exec(sql)\n\treturn userDSN, err\n}\n\nfunc (i *Installer) createServerInstance() (*proto.ServerInstance, error) {\n\t\/\/ todo: handle duplicate server\n\n\t\/\/ POST <api>\/instances\/server\n\tsi := &proto.ServerInstance{\n\t\tHostname: i.hostname,\n\t}\n\tdata, err := json.Marshal(si)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turl := pct.URL(i.agentConfig.ApiHostname, \"instances\", \"server\")\n\tif i.flags[\"debug\"] {\n\t\tlog.Println(url)\n\t}\n\tresp, _, err := i.api.Post(i.agentConfig.ApiKey, url, data)\n\tif i.flags[\"debug\"] {\n\t\tlog.Printf(\"resp=%#v\\n\", resp)\n\t\tlog.Printf(\"err=%s\\n\", err)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusCreated {\n\t\treturn nil, fmt.Errorf(\"Failed to create server instance (status code %d)\", resp.StatusCode)\n\t}\n\n\t\/\/ API returns URI of new resource in Location header\n\turi := resp.Header.Get(\"Location\")\n\tif uri == \"\" {\n\t\treturn nil, fmt.Errorf(\"API did not return location of new server instance\")\n\t}\n\n\t\/\/ GET <api>\/instances\/server\/id (URI)\n\tcode, data, err := i.api.Get(i.agentConfig.ApiKey, uri)\n\tif i.flags[\"debug\"] {\n\t\tlog.Printf(\"code=%d\\n\", code)\n\t\tlog.Printf(\"err=%s\\n\", err)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif code != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"Failed to get new server instance (status code %d)\", code)\n\t}\n\tif err := json.Unmarshal(data, si); err != nil {\n\t\treturn nil, err\n\t}\n\treturn si, nil\n}\n\nfunc (i *Installer) createMySQLInstance(dsn mysql.DSN) (*proto.MySQLInstance, error) {\n\t\/\/ todo: handle duplicate instance\n\n\t\/\/ First use instance.Manager to fill in details about the MySQL server.\n\tdsnString, _ := dsn.DSN()\n\tmi := &proto.MySQLInstance{\n\t\tHostname: i.hostname,\n\t\tDSN:      dsnString,\n\t}\n\tif err := instance.GetMySQLInfo(mi); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ POST <api>\/instances\/mysql\n\tdata, err := json.Marshal(mi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turl := pct.URL(i.agentConfig.ApiHostname, \"instances\", \"mysql\")\n\tif i.flags[\"debug\"] {\n\t\tlog.Println(url)\n\t}\n\tresp, _, err := i.api.Post(i.agentConfig.ApiKey, url, data)\n\tif i.flags[\"debug\"] {\n\t\tlog.Printf(\"resp=%#v\\n\", resp)\n\t\tlog.Printf(\"err=%s\\n\", err)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusCreated {\n\t\treturn nil, fmt.Errorf(\"Failed to create MySQL instance (status code %d)\", resp.StatusCode)\n\t}\n\n\t\/\/ API returns URI of new resource in Location header\n\turi := resp.Header.Get(\"Location\")\n\tif uri == \"\" {\n\t\treturn nil, fmt.Errorf(\"API did not return location of new MySQL instance\")\n\t}\n\n\t\/\/ GET <api>\/instances\/mysql\/id (URI)\n\tcode, data, err := i.api.Get(i.agentConfig.ApiKey, uri)\n\tif i.flags[\"debug\"] {\n\t\tlog.Printf(\"code=%d\\n\", code)\n\t\tlog.Printf(\"err=%s\\n\", err)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif code != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"Failed to get new MySQL instance (status code %d)\", code)\n\t}\n\tif err := json.Unmarshal(data, mi); err != nil {\n\t\treturn nil, err\n\t}\n\treturn mi, nil\n}\n\nfunc (i *Installer) getMmServerConfig() (*mmServer.Config, error) {\n\treturn nil, nil\n}\nfunc (i *Installer) getMmMySQLConfig() (*mmMySQL.Config, error) {\n\treturn nil, nil\n}\nfunc (i *Installer) getSysconfigMySQLConfig() (*sysconfigMySQL.Config, error) {\n\treturn nil, nil\n}\nfunc (i *Installer) getQanConfig() (*qan.Config, error) {\n\treturn nil, nil\n}\n\nfunc (i *Installer) createAgent(mmserver *mmServer.Config, mmmysql *mmMySQL.Config, cfgmysql *sysconfigMySQL.Config, qan *qan.Config) (string, error) {\n\t\/\/ todo\n\treturn \"\", nil\n}\n<commit_msg>PCT-401: A little better instance duplication handling (todo: user should have a choice what to do) Stuff that was required on api side to make that working (already in master): * https:\/\/github.com\/percona\/cloud-api\/pull\/93 * https:\/\/github.com\/percona\/cloud-api\/pull\/92 * https:\/\/github.com\/percona\/cloud-api\/pull\/91<commit_after>package main\n\nimport (\n\t\"code.google.com\/p\/gopass\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"github.com\/percona\/cloud-protocol\/proto\"\n\t\"github.com\/percona\/cloud-tools\/agent\"\n\t\"github.com\/percona\/cloud-tools\/instance\"\n\tmmMySQL \"github.com\/percona\/cloud-tools\/mm\/mysql\"\n\tmmServer \"github.com\/percona\/cloud-tools\/mm\/system\"\n\t\"github.com\/percona\/cloud-tools\/mysql\"\n\t\"github.com\/percona\/cloud-tools\/pct\"\n\t\"github.com\/percona\/cloud-tools\/qan\"\n\tsysconfigMySQL \"github.com\/percona\/cloud-tools\/sysconfig\/mysql\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype Flags map[string]bool\n\nvar portNumberRe = regexp.MustCompile(`\\.\\d+$`)\n\ntype Installer struct {\n\tterm        *Terminal\n\tapi         pct.APIConnector\n\tagentConfig *agent.Config\n\tflags       Flags\n\t\/\/ --\n\thostname string\n}\n\nfunc NewInstaller(term *Terminal, api pct.APIConnector, agentConfig *agent.Config, flags Flags) *Installer {\n\tif agentConfig.ApiHostname == \"\" {\n\t\tagentConfig.ApiHostname = agent.DEFAULT_API_HOSTNAME\n\t}\n\thostname, _ := os.Hostname()\n\tinstaller := &Installer{\n\t\tterm:        term,\n\t\tapi:         api,\n\t\tagentConfig: agentConfig,\n\t\tflags:       flags,\n\t\t\/\/ --\n\t\thostname: hostname,\n\t}\n\treturn installer\n}\n\nfunc (i *Installer) Run() error {\n\n\tfmt.Printf(\"API host: %s\\n\", i.agentConfig.ApiHostname)\n\n\t\/**\n\t * Get the API key.\n\t *\/\n\n\tfor i.agentConfig.ApiKey == \"\" {\n\t\tapiKey, err := i.term.PromptString(\"API key\", \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif apiKey == \"\" {\n\t\t\tfmt.Println(\"API key is required, please try again.\")\n\t\t\tcontinue\n\t\t}\n\t\ti.agentConfig.ApiKey = apiKey\n\t\tbreak\n\t}\n\n\t\/**\n\t * Verify the API key by pinging the API.\n\t *\/\n\nVERIFY_API_KEY:\n\tfor {\n\t\tfmt.Printf(\"Verifying API key %s...\\n\", i.agentConfig.ApiKey)\n\t\tcode, err := pct.Ping(i.agentConfig.ApiHostname, i.agentConfig.ApiKey)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error: %s\\n\", err)\n\t\t}\n\t\tif i.flags[\"debug\"] {\n\t\t\tlog.Printf(\"code=%d\\n\", code)\n\t\t\tlog.Printf(\"err=%s\\n\", err)\n\t\t}\n\t\tok := false\n\t\tif code >= 500 {\n\t\t\tfmt.Printf(\"Sorry, there's an API problem (status code %d). \"+\n\t\t\t\t\"Please try to install again. If the problem continues, contact Percona.\\n\",\n\t\t\t\tcode)\n\t\t} else if code == 401 {\n\t\t\treturn fmt.Errorf(\"Access denied.  Check the API key and try again.\")\n\t\t} else if code >= 300 {\n\t\t\tfmt.Printf(\"Sorry, there's an installer problem (status code %d). \"+\n\t\t\t\t\"Please try to install again. If the problem continues, contact Percona.\\n\",\n\t\t\t\tcode)\n\t\t} else if code != 200 {\n\t\t\tfmt.Printf(\"Sorry, there's an installer problem (status code %d). \"+\n\t\t\t\t\"Please try to install again. If the problem continues, contact Percona.\\n\",\n\t\t\t\tcode)\n\t\t} else {\n\t\t\tok = true\n\t\t}\n\n\t\tif !ok {\n\t\t\tagain, err := i.term.PromptBool(\"Try again?\", \"Y\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !again {\n\t\t\t\treturn fmt.Errorf(\"Failed to verify API key\")\n\t\t\t}\n\t\t\tcontinue VERIFY_API_KEY\n\t\t}\n\n\t\tfmt.Printf(\"API key %s is OK\\n\", i.agentConfig.ApiKey)\n\t\tbreak\n\t}\n\n\t\/**\n\t * Create a MySQL user for the agent, or use an existing one.\n\t *\/\n\n\tagentDSN := mysql.DSN{}\n\tif !i.flags[\"skip-mysql\"] {\n\t\tdsn, err := i.doMySQL()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tagentDSN = dsn\n\t} else {\n\t\tfmt.Println(\"Skip creating MySQL user (-skip-mysql)\")\n\t}\n\n\t\/**\n\t * Create new API resources.\n\t *\/\n\n\tsi, err := i.createServerInstance()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Created server instance: hostname=%s id=%d\\n\", si.Hostname, si.Id)\n\n\tvar mi *proto.MySQLInstance\n\tif !i.flags[\"skip-mysql\"] {\n\t\tmi, err = i.createMySQLInstance(agentDSN)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"Created MySQL instance: dsn=%s hostname=%s id=%d\\n\", mi.DSN, mi.Hostname, si.Id)\n\t} else {\n\t\tfmt.Println(\"Skip creating MySQL instance (-skip-mysql)\")\n\t}\n\n\t\/**\n\t * Get default configs for all services.\n\t *\/\n\n\tmmServerConfig, err := i.getMmServerConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tmmServerConfig.Service = \"server\"\n\tmmServerConfig.InstanceId = si.Id\n\n\tmmMySQLConfig, err := i.getMmMySQLConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsysconfigMySQLConfig, err := i.getSysconfigMySQLConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ MySQL is local if the server hostname == MySQL hostname without port number.\n\tmysqlIsLocal := i.hostname == portNumberRe.ReplaceAllLiteralString(i.hostname, \"\")\n\tvar qanConfig *qan.Config\n\tif mysqlIsLocal {\n\t\tqanConfig, err = i.getQanConfig()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/**\n\t * Create agent with initial service configs.\n\t *\/\n\n\tagentUuid, err := i.createAgent(\n\t\tmmServerConfig,\n\t\tmmMySQLConfig,\n\t\tsysconfigMySQLConfig,\n\t\tqanConfig,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"Created agent: uuid=%s\\n\", agentUuid)\n\n\treturn nil\n}\n\nfunc (i *Installer) doMySQL() (dsn mysql.DSN, err error) {\n\t\/\/ XXX Using implicit return\n\tnewMySQLUser, err := i.term.PromptBool(\"Create new MySQL account for agent?\", \"Y\")\n\tif err != nil {\n\t\treturn\n\t}\n\tif newMySQLUser {\n\t\tfmt.Println(\"Connect to MySQL to create new MySQL user for agent\")\n\t\tdsn, err = i.connectMySQL()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tfmt.Println(\"Creating new MySQL user for agent...\")\n\t\tdsn, err = i.createMySQLUser(dsn)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\t\/\/ Let user specify the MySQL account to use for the agent.\n\t\tfmt.Println(\"Use existing MySQL user for agent\")\n\t\tdsn, err = i.connectMySQL()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Printf(\"Agent MySQL user: %s\\n\", dsn)\n\treturn\n}\n\nfunc (i *Installer) connectMySQL() (mysql.DSN, error) {\n\tdsn := mysql.DSN{}\n\tuser, _ := user.Current()\n\tif user != nil {\n\t\tdsn.Username = user.Username\n\t}\n\tvar conn *mysql.Connection\n\nCONNECT_MYSQL:\n\tfor conn == nil {\n\t\tusername, err := i.term.PromptStringRequired(\"MySQL username\", dsn.Username)\n\t\tif err != nil {\n\t\t\treturn dsn, err\n\t\t}\n\t\tdsn.Username = username\n\n\t\tpassword, err := gopass.GetPass(\"MySQL password: \")\n\t\tif err != nil {\n\t\t\treturn dsn, err\n\t\t}\n\t\tdsn.Password = password\n\n\t\thostname, err := i.term.PromptStringRequired(\"MySQL host[:port] or socket file\", \"localhost\")\n\t\tif err != nil {\n\t\t\treturn dsn, err\n\t\t}\n\t\tif filepath.IsAbs(hostname) {\n\t\t\tdsn.Socket = hostname\n\t\t} else {\n\t\t\tf := strings.Split(hostname, \":\")\n\t\t\tdsn.Hostname = f[0]\n\t\t\tif len(f) > 1 {\n\t\t\t\tdsn.Port = f[1]\n\t\t\t} else {\n\t\t\t\tdsn.Port = \"3306\"\n\t\t\t}\n\t\t}\n\n\t\tdsnString, err := dsn.DSN()\n\t\tif err != nil {\n\t\t\treturn dsn, err \/\/ shouldn't happen\n\t\t}\n\n\t\tfmt.Printf(\"Connecting to MySQL %s...\\n\", dsn)\n\t\tconn = mysql.NewConnection(dsnString)\n\t\tif err := conn.Connect(1); err != nil {\n\t\t\tconn = nil\n\t\t\tfmt.Printf(\"Error connecting to MySQL %s: %s\\n\", dsn, err)\n\t\t\tagain, err := i.term.PromptBool(\"Try again?\", \"Y\")\n\t\t\tif err != nil {\n\t\t\t\treturn dsn, err\n\t\t\t}\n\t\t\tif !again {\n\t\t\t\treturn dsn, fmt.Errorf(\"Failed to connect to MySQL\")\n\t\t\t}\n\t\t\tcontinue CONNECT_MYSQL\n\t\t}\n\t\tdefer conn.Close()\n\n\t\tfmt.Printf(\"MySQL connection OK\\n\")\n\t\tbreak\n\t}\n\treturn dsn, nil\n}\n\nfunc (i *Installer) createMySQLUser(dsn mysql.DSN) (mysql.DSN, error) {\n\t\/\/ Same host:port or socket, but different user and pass.\n\tuserDSN := dsn\n\tuserDSN.Username = \"percona-agent\"\n\tuserDSN.Password = fmt.Sprintf(\"%p%d\", &dsn, rand.Uint32())\n\n\tdsnString, _ := dsn.DSN()\n\tconn := mysql.NewConnection(dsnString)\n\tif err := conn.Connect(1); err != nil {\n\t\treturn userDSN, err\n\t}\n\tdefer conn.Close()\n\n\tsql := fmt.Sprintf(\"GRANT SUPER, PROCESS, USAGE ON *.* TO '%s'@'%%' IDENTIFIED BY '%s'\",\n\t\tuserDSN.Username, userDSN.Password)\n\t_, err := conn.DB().Exec(sql)\n\treturn userDSN, err\n}\n\nfunc (i *Installer) createServerInstance() (*proto.ServerInstance, error) {\n\t\/\/ POST <api>\/instances\/server\n\tsi := &proto.ServerInstance{\n\t\tHostname: i.hostname,\n\t}\n\tdata, err := json.Marshal(si)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turl := pct.URL(i.agentConfig.ApiHostname, \"instances\", \"server\")\n\tif i.flags[\"debug\"] {\n\t\tlog.Println(url)\n\t}\n\tresp, _, err := i.api.Post(i.agentConfig.ApiKey, url, data)\n\tif i.flags[\"debug\"] {\n\t\tlog.Printf(\"resp=%#v\\n\", resp)\n\t\tlog.Printf(\"err=%s\\n\", err)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Create new instance, if it already exist then just use it\n\t\/\/ todo: better handling of duplicate instance\n\tif resp.StatusCode != http.StatusCreated  && resp.StatusCode != http.StatusConflict {\n\t\treturn nil, fmt.Errorf(\"Failed to create server instance (status code %d)\", resp.StatusCode)\n\t}\n\n\t\/\/ API returns URI of new resource in Location header\n\turi := resp.Header.Get(\"Location\")\n\tif uri == \"\" {\n\t\treturn nil, fmt.Errorf(\"API did not return location of new server instance\")\n\t}\n\n\t\/\/ GET <api>\/instances\/server\/id (URI)\n\tcode, data, err := i.api.Get(i.agentConfig.ApiKey, uri)\n\tif i.flags[\"debug\"] {\n\t\tlog.Printf(\"code=%d\\n\", code)\n\t\tlog.Printf(\"err=%s\\n\", err)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif code != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"Failed to get new server instance (status code %d)\", code)\n\t}\n\tif err := json.Unmarshal(data, si); err != nil {\n\t\treturn nil, err\n\t}\n\treturn si, nil\n}\n\nfunc (i *Installer) createMySQLInstance(dsn mysql.DSN) (*proto.MySQLInstance, error) {\n\t\/\/ First use instance.Manager to fill in details about the MySQL server.\n\tdsnString, _ := dsn.DSN()\n\tmi := &proto.MySQLInstance{\n\t\tHostname: i.hostname,\n\t\tDSN:      dsnString,\n\t}\n\tif err := instance.GetMySQLInfo(mi); err != nil {\n\t\tif i.flags[\"debug\"] {\n\t\t\tlog.Printf(\"err=%s\\n\", err)\n\t\t}\n\t\treturn nil, err\n\t}\n\n\t\/\/ POST <api>\/instances\/mysql\n\tdata, err := json.Marshal(mi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turl := pct.URL(i.agentConfig.ApiHostname, \"instances\", \"mysql\")\n\tif i.flags[\"debug\"] {\n\t\tlog.Println(url)\n\t}\n\tresp, _, err := i.api.Post(i.agentConfig.ApiKey, url, data)\n\tif i.flags[\"debug\"] {\n\t\tlog.Printf(\"resp=%#v\\n\", resp)\n\t\tlog.Printf(\"err=%s\\n\", err)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Create new instance, if it already exist then just use it\n\t\/\/ todo: better handling of duplicate instance\n\tif resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusConflict {\n\t\treturn nil, fmt.Errorf(\"Failed to create MySQL instance (status code %d)\", resp.StatusCode)\n\t}\n\n\t\/\/ API returns URI of new resource in Location header\n\turi := resp.Header.Get(\"Location\")\n\tif uri == \"\" {\n\t\treturn nil, fmt.Errorf(\"API did not return location of new MySQL instance\")\n\t}\n\n\t\/\/ GET <api>\/instances\/mysql\/id (URI)\n\tcode, data, err := i.api.Get(i.agentConfig.ApiKey, uri)\n\tif i.flags[\"debug\"] {\n\t\tlog.Printf(\"code=%d\\n\", code)\n\t\tlog.Printf(\"err=%s\\n\", err)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif code != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"Failed to get new MySQL instance (status code %d)\", code)\n\t}\n\tif err := json.Unmarshal(data, mi); err != nil {\n\t\treturn nil, err\n\t}\n\treturn mi, nil\n}\n\nfunc (i *Installer) getMmServerConfig() (*mmServer.Config, error) {\n\treturn nil, nil\n}\nfunc (i *Installer) getMmMySQLConfig() (*mmMySQL.Config, error) {\n\treturn nil, nil\n}\nfunc (i *Installer) getSysconfigMySQLConfig() (*sysconfigMySQL.Config, error) {\n\treturn nil, nil\n}\nfunc (i *Installer) getQanConfig() (*qan.Config, error) {\n\treturn nil, nil\n}\n\nfunc (i *Installer) createAgent(mmserver *mmServer.Config, mmmysql *mmMySQL.Config, cfgmysql *sysconfigMySQL.Config, qan *qan.Config) (string, error) {\n\t\/\/ todo\n\treturn \"\", nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017, Mitchell Cooper\npackage config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n)\n\n\/\/ parse config\nfunc (conf *Config) Parse() error {\n\n\t\/\/ open the config\n\tfile, err := os.Open(conf.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t\/\/ initial state\n\tstate := &parserState{\n\t\tline:    1,\n\t\tbuffers: make([]bufferInfo, 0, 3),\n\t}\n\tconf.line = &state.line\n\n\tfor {\n\t\tb := make([]byte, 1)\n\t\t_, err := file.Read(b)\n\n\t\t\/\/ eof\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ some other error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ handle the character\n\t\terr = conf.handleByte(state, b[0])\n\t\tstate.lastByte = b[0]\n\n\t\t\/\/ byte error\n\t\tif err != nil {\n\t\t\terr = errors.New(fmt.Sprintf(\"%s:%d: %s\", conf.path, *conf.line, err.Error()))\n\t\t\treturn err\n\t\t}\n\t}\n\n\tstate.line = 0\n\treturn nil\n}\n\n\/\/ produce a warning\nfunc (conf *Config) Warn(msg string) {\n\tlog.Println(conf.getWarn(msg))\n}\n\nfunc (conf *Config) Warnf(msg string, i ...interface{}) {\n\tconf.Warn(conf.getWarnf(msg, i))\n}\n\nfunc (conf *Config) getWarn(msg string) string {\n\treturn conf.getWarnf(\"%s\", msg)\n}\n\nfunc (conf *Config) getWarnf(msg string, i ...interface{}) (res string) {\n\tline := *conf.line\n\tif line == 0 {\n\t\tres = fmt.Sprintf(\"%s: %s\", conf.path, msg, i)\n\t\treturn\n\t}\n\tres = fmt.Sprintf(\"%s:%d: %s\", conf.path, line, msg, i)\n\treturn\n}\n\n\/\/ handle one byte\nfunc (conf *Config) handleByte(state *parserState, b byte) error {\n\n\t\/\/ this character is escaped\n\tif state.escaped {\n\t\tb = 0\n\t\tstate.escaped = false\n\t}\n\n\tif state.lastByte == '\/' && b == '*' {\n\n\t\t\/\/ comment entrance\n\t\tstate.increaseCommentLevel()\n\t\treturn nil\n\n\t} else if state.lastByte == '*' && b == '\/' {\n\n\t\t\/\/ comment closure\n\t\tstate.decreaseCommentLevel()\n\t\treturn nil\n\n\t} else if state.inComment {\n\n\t\t\/\/ we're in a comment currently\n\t\treturn nil\n\t}\n\n\tswitch b {\n\n\t\/\/ escape\n\tcase '\\\\':\n\t\tstate.escaped = true\n\n\t\t\/\/ start of a variable\n\tcase '@', '%':\n\n\t\t\/\/ we're already in a variable name\n\t\tif state.buffType() == VAR_NAME {\n\t\t\treturn errors.New(\"Already in variable name @\" + state.endBuffer())\n\t\t}\n\n\t\t\/\/ this is only allowed at the top level\n\t\tif state.buffType() != NO_BUF {\n\t\t\tgoto realDefault\n\t\t}\n\n\t\t\/\/ we're not in a value, so this starts a variable name\n\t\tstate.varPercent = b == '%'\n\t\tstate.startBuffer(VAR_NAME)\n\n\t\/\/ end of variable name, start of string value\n\tcase ':':\n\n\t\t\/\/ not in a variable name\n\t\tif state.buffType() != VAR_NAME {\n\t\t\tgoto realDefault\n\t\t}\n\n\t\t\/\/ we're in the var name, so terminate it\n\t\tstate.varName = state.endBuffer()\n\t\tstate.startBuffer(VAR_VALUE)\n\n\t\t\/\/ start of a text format\n\tcase '[':\n\n\t\t\/\/ we're already in a text format.\n\t\t\/\/ this is supported by wikifier but not here\n\t\tif state.buffType() == VAR_FORMAT {\n\t\t\treturn errors.New(\"Square brackets in format not yet supported\")\n\t\t}\n\n\t\t\/\/ we aren't in a variable value, or maybe\n\t\t\/\/ the current variable does not allow interpolation\n\t\tif state.buffType() != VAR_VALUE || state.varPercent {\n\t\t\tgoto realDefault\n\t\t}\n\n\t\t\/\/ otherwise, this starts a formatting token\n\t\tstate.startBuffer(VAR_FORMAT)\n\n\t\/\/ end of a text format\n\tcase ']':\n\n\t\t\/\/ not in a format\n\t\tif state.buffType() != VAR_FORMAT {\n\t\t\tgoto realDefault\n\t\t}\n\n\t\t\/\/ otherwise, this terminates a formatting token\n\t\ttok := state.endBuffer()\n\n\t\t\/\/ parse the formatting token\n\t\terr, newVal := conf.getFormattingToken(tok, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif newVal == \"\" {\n\t\t\tconf.Warn(\"[\" + tok + \"] yields empty string\")\n\t\t}\n\n\t\t\/\/ add the value returned by it to the variable value buffer\n\t\tstate.buffer().WriteString(newVal)\n\n\t\/\/ end of a variable definition\n\tcase ';':\n\n\t\tif state.buffType() == VAR_NAME {\n\n\t\t\t\/\/ terminating a boolean\n\t\t\tstate.endBuffer()\n\t\t\tconf.Set(state.getVariable(), \"1\")\n\n\t\t} else if state.buffType() == VAR_VALUE {\n\n\t\t\t\/\/ terminating a string\n\t\t\tvalue := strings.TrimSpace(state.endBuffer())\n\t\t\tconf.Set(state.getVariable(), value)\n\n\t\t} else {\n\t\t\tgoto realDefault\n\t\t}\n\n\tcase '\\n':\n\t\tstate.line++\n\t\tgoto realDefault\n\n\tdefault:\n\t\tgoto realDefault\n\t}\n\n\t\/\/ this is skipped if going to realDefault\n\treturn nil\n\nrealDefault:\n\n\t\/\/ we're in a comment; ignore this\n\tif state.inComment {\n\t\treturn nil\n\t}\n\n\t\/\/ otherwise, write this to the current buffer\n\tif state.buffer() != nil {\n\t\tstate.buffer().WriteByte(b)\n\t}\n\n\treturn nil\n}\n\n\/\/ return the value of a formatting token\nfunc (conf *Config) getFormattingToken(tok string, disableVars bool) (error, string) {\n\n\t\/\/ normal variable\n\tif strings.HasPrefix(tok, \"@\") {\n\t\tif disableVars {\n\t\t\tgoto badVariable\n\t\t}\n\t\treturn nil, conf.Get(strings.TrimPrefix(tok, \"@\"))\n\t}\n\n\t\/\/ interpolable variable\n\tif strings.HasPrefix(tok, \"%\") {\n\t\tif disableVars {\n\t\t\tgoto badVariable\n\t\t}\n\t\tval := strings.TrimPrefix(\"tok\", \"%\")\n\t\treturn conf.getFormattingToken(val, true)\n\t}\n\n\treturn errors.New(\"Unknown formatting token [\" + tok + \"]\"), \"\"\n\nbadVariable:\n\treturn errors.New(\"Recursive variable \" + tok + \" detected\"), \"\"\n}\n\n\/\/ return the map and attribute name for a variable name\nfunc (conf *Config) getWhere(varName string, createAsNeeded bool) (map[string]interface{}, string) {\n\n\t\/\/ split up into parts\n\tvar parts = strings.Split(varName, \".\")\n\tif len(parts) == 0 {\n\t\treturn nil, \"\"\n\t}\n\n\t\/\/ the last one is the final variable name\n\tlastPart, parts := parts[len(parts)-1], parts[:len(parts)-1]\n\n\t\/\/ start with the main map\n\twhere := conf.vars\n\n\t\/\/ for each part, fetch the map inside\n\tfor _, part := range parts {\n\n\t\t\/\/ find interface\n\t\tiface := where[part]\n\t\tif iface == nil {\n\t\t\tif !createAsNeeded {\n\t\t\t\treturn nil, \"\"\n\t\t\t}\n\n\t\t\t\/\/ maybe create a map\n\t\t\tiface = make(map[string]interface{})\n\t\t\twhere[part] = iface\n\t\t}\n\n\t\t\/\/ find map\n\t\tswitch aMap := iface.(type) {\n\t\tcase map[string]interface{}:\n\t\t\twhere = aMap\n\n\t\t\/\/ nothing there; give up\n\t\tdefault:\n\t\t\treturn nil, \"\"\n\t\t}\n\t}\n\n\treturn where, lastPart\n}\n<commit_msg>er needs to add the format strings together<commit_after>\/\/ Copyright (c) 2017, Mitchell Cooper\npackage config\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n)\n\n\/\/ parse config\nfunc (conf *Config) Parse() error {\n\n\t\/\/ open the config\n\tfile, err := os.Open(conf.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t\/\/ initial state\n\tstate := &parserState{\n\t\tline:    1,\n\t\tbuffers: make([]bufferInfo, 0, 3),\n\t}\n\tconf.line = &state.line\n\n\tfor {\n\t\tb := make([]byte, 1)\n\t\t_, err := file.Read(b)\n\n\t\t\/\/ eof\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ some other error\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ handle the character\n\t\terr = conf.handleByte(state, b[0])\n\t\tstate.lastByte = b[0]\n\n\t\t\/\/ byte error\n\t\tif err != nil {\n\t\t\terr = errors.New(fmt.Sprintf(\"%s:%d: %s\", conf.path, *conf.line, err.Error()))\n\t\t\treturn err\n\t\t}\n\t}\n\n\tstate.line = 0\n\treturn nil\n}\n\n\/\/ produce a warning\nfunc (conf *Config) Warn(msg string) {\n\tlog.Println(conf.getWarn(msg))\n}\n\nfunc (conf *Config) Warnf(msg string, i ...interface{}) {\n\tconf.Warn(conf.getWarnf(msg, i))\n}\n\nfunc (conf *Config) getWarn(msg string) string {\n\treturn conf.getWarnf(\"%s\", msg)\n}\n\nfunc (conf *Config) getWarnf(msg string, i ...interface{}) (res string) {\n\tline := *conf.line\n\tif line == 0 {\n\t\tres = fmt.Sprintf(\"%s: \"+msg, conf.path, i)\n\t\treturn\n\t}\n\tres = fmt.Sprintf(\"%s:%d: \"+msg, conf.path, line, i)\n\treturn\n}\n\n\/\/ handle one byte\nfunc (conf *Config) handleByte(state *parserState, b byte) error {\n\n\t\/\/ this character is escaped\n\tif state.escaped {\n\t\tb = 0\n\t\tstate.escaped = false\n\t}\n\n\tif state.lastByte == '\/' && b == '*' {\n\n\t\t\/\/ comment entrance\n\t\tstate.increaseCommentLevel()\n\t\treturn nil\n\n\t} else if state.lastByte == '*' && b == '\/' {\n\n\t\t\/\/ comment closure\n\t\tstate.decreaseCommentLevel()\n\t\treturn nil\n\n\t} else if state.inComment {\n\n\t\t\/\/ we're in a comment currently\n\t\treturn nil\n\t}\n\n\tswitch b {\n\n\t\/\/ escape\n\tcase '\\\\':\n\t\tstate.escaped = true\n\n\t\t\/\/ start of a variable\n\tcase '@', '%':\n\n\t\t\/\/ we're already in a variable name\n\t\tif state.buffType() == VAR_NAME {\n\t\t\treturn errors.New(\"Already in variable name @\" + state.endBuffer())\n\t\t}\n\n\t\t\/\/ this is only allowed at the top level\n\t\tif state.buffType() != NO_BUF {\n\t\t\tgoto realDefault\n\t\t}\n\n\t\t\/\/ we're not in a value, so this starts a variable name\n\t\tstate.varPercent = b == '%'\n\t\tstate.startBuffer(VAR_NAME)\n\n\t\/\/ end of variable name, start of string value\n\tcase ':':\n\n\t\t\/\/ not in a variable name\n\t\tif state.buffType() != VAR_NAME {\n\t\t\tgoto realDefault\n\t\t}\n\n\t\t\/\/ we're in the var name, so terminate it\n\t\tstate.varName = state.endBuffer()\n\t\tstate.startBuffer(VAR_VALUE)\n\n\t\t\/\/ start of a text format\n\tcase '[':\n\n\t\t\/\/ we're already in a text format.\n\t\t\/\/ this is supported by wikifier but not here\n\t\tif state.buffType() == VAR_FORMAT {\n\t\t\treturn errors.New(\"Square brackets in format not yet supported\")\n\t\t}\n\n\t\t\/\/ we aren't in a variable value, or maybe\n\t\t\/\/ the current variable does not allow interpolation\n\t\tif state.buffType() != VAR_VALUE || state.varPercent {\n\t\t\tgoto realDefault\n\t\t}\n\n\t\t\/\/ otherwise, this starts a formatting token\n\t\tstate.startBuffer(VAR_FORMAT)\n\n\t\/\/ end of a text format\n\tcase ']':\n\n\t\t\/\/ not in a format\n\t\tif state.buffType() != VAR_FORMAT {\n\t\t\tgoto realDefault\n\t\t}\n\n\t\t\/\/ otherwise, this terminates a formatting token\n\t\ttok := state.endBuffer()\n\n\t\t\/\/ parse the formatting token\n\t\terr, newVal := conf.getFormattingToken(tok, false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif newVal == \"\" {\n\t\t\tconf.Warn(\"[\" + tok + \"] yields empty string\")\n\t\t}\n\n\t\t\/\/ add the value returned by it to the variable value buffer\n\t\tstate.buffer().WriteString(newVal)\n\n\t\/\/ end of a variable definition\n\tcase ';':\n\n\t\tif state.buffType() == VAR_NAME {\n\n\t\t\t\/\/ terminating a boolean\n\t\t\tstate.endBuffer()\n\t\t\tconf.Set(state.getVariable(), \"1\")\n\n\t\t} else if state.buffType() == VAR_VALUE {\n\n\t\t\t\/\/ terminating a string\n\t\t\tvalue := strings.TrimSpace(state.endBuffer())\n\t\t\tconf.Set(state.getVariable(), value)\n\n\t\t} else {\n\t\t\tgoto realDefault\n\t\t}\n\n\tcase '\\n':\n\t\tstate.line++\n\t\tgoto realDefault\n\n\tdefault:\n\t\tgoto realDefault\n\t}\n\n\t\/\/ this is skipped if going to realDefault\n\treturn nil\n\nrealDefault:\n\n\t\/\/ we're in a comment; ignore this\n\tif state.inComment {\n\t\treturn nil\n\t}\n\n\t\/\/ otherwise, write this to the current buffer\n\tif state.buffer() != nil {\n\t\tstate.buffer().WriteByte(b)\n\t}\n\n\treturn nil\n}\n\n\/\/ return the value of a formatting token\nfunc (conf *Config) getFormattingToken(tok string, disableVars bool) (error, string) {\n\n\t\/\/ normal variable\n\tif strings.HasPrefix(tok, \"@\") {\n\t\tif disableVars {\n\t\t\tgoto badVariable\n\t\t}\n\t\treturn nil, conf.Get(strings.TrimPrefix(tok, \"@\"))\n\t}\n\n\t\/\/ interpolable variable\n\tif strings.HasPrefix(tok, \"%\") {\n\t\tif disableVars {\n\t\t\tgoto badVariable\n\t\t}\n\t\tval := strings.TrimPrefix(\"tok\", \"%\")\n\t\treturn conf.getFormattingToken(val, true)\n\t}\n\n\treturn errors.New(\"Unknown formatting token [\" + tok + \"]\"), \"\"\n\nbadVariable:\n\treturn errors.New(\"Recursive variable \" + tok + \" detected\"), \"\"\n}\n\n\/\/ return the map and attribute name for a variable name\nfunc (conf *Config) getWhere(varName string, createAsNeeded bool) (map[string]interface{}, string) {\n\n\t\/\/ split up into parts\n\tvar parts = strings.Split(varName, \".\")\n\tif len(parts) == 0 {\n\t\treturn nil, \"\"\n\t}\n\n\t\/\/ the last one is the final variable name\n\tlastPart, parts := parts[len(parts)-1], parts[:len(parts)-1]\n\n\t\/\/ start with the main map\n\twhere := conf.vars\n\n\t\/\/ for each part, fetch the map inside\n\tfor _, part := range parts {\n\n\t\t\/\/ find interface\n\t\tiface := where[part]\n\t\tif iface == nil {\n\t\t\tif !createAsNeeded {\n\t\t\t\treturn nil, \"\"\n\t\t\t}\n\n\t\t\t\/\/ maybe create a map\n\t\t\tiface = make(map[string]interface{})\n\t\t\twhere[part] = iface\n\t\t}\n\n\t\t\/\/ find map\n\t\tswitch aMap := iface.(type) {\n\t\tcase map[string]interface{}:\n\t\t\twhere = aMap\n\n\t\t\/\/ nothing there; give up\n\t\tdefault:\n\t\t\treturn nil, \"\"\n\t\t}\n\t}\n\n\treturn where, lastPart\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright The OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage config\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com\/spf13\/cast\"\n\t\"github.com\/spf13\/viper\"\n)\n\nconst (\n\t\/\/ KeyDelimiter is used as the default key delimiter in the default viper instance.\n\tKeyDelimiter = \"::\"\n)\n\n\/\/ newViper creates a new Viper instance with key delimiter KeyDelimiter instead of the\n\/\/ default \".\". This way configs can have keys that contain \".\".\nfunc newViper() *viper.Viper {\n\treturn viper.NewWithOptions(viper.KeyDelimiter(KeyDelimiter))\n}\n\n\/\/ NewParser creates a new empty Parser instance.\nfunc NewParser() *Parser {\n\treturn &Parser{\n\t\tv: newViper(),\n\t}\n}\n\n\/\/ NewParserFromFile creates a new Parser by reading the given file.\nfunc NewParserFromFile(fileName string) (*Parser, error) {\n\t\/\/ Read yaml config from file\n\tv := newViper()\n\tv.SetConfigFile(fileName)\n\tif err := v.ReadInConfig(); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read the file %v: %w\", fileName, err)\n\t}\n\treturn &Parser{v: v}, nil\n}\n\n\/\/ NewParserFromBuffer creates a new Parser by reading the given yaml buffer.\nfunc NewParserFromBuffer(buf io.Reader) (*Parser, error) {\n\tv := newViper()\n\tv.SetConfigType(\"yaml\")\n\tif err := v.ReadConfig(buf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Parser{v: v}, nil\n}\n\n\/\/ NewParserFromStringMap creates a parser from a map[string]interface{}.\nfunc NewParserFromStringMap(data map[string]interface{}) *Parser {\n\tv := newViper()\n\t\/\/ Cannot return error because the subv is empty.\n\t_ = v.MergeConfigMap(data)\n\treturn &Parser{v: v}\n}\n\n\/\/ Parser loads configuration.\ntype Parser struct {\n\tv *viper.Viper\n}\n\n\/\/ AllKeys returns all keys holding a value, regardless of where they are set.\n\/\/ Nested keys are returned with a KeyDelimiter separator\nfunc (l *Parser) AllKeys() []string {\n\treturn l.v.AllKeys()\n}\n\n\/\/ Unmarshal unmarshals the config into a struct. Make sure that the tags\n\/\/ on the fields of the structure are properly set.\nfunc (l *Parser) Unmarshal(rawVal interface{}) error {\n\treturn l.v.Unmarshal(rawVal)\n}\n\n\/\/ UnmarshalExact unmarshals the config into a struct, erroring if a field is nonexistent.\nfunc (l *Parser) UnmarshalExact(intoCfg interface{}) error {\n\tl.v.AllKeys()\n\treturn l.v.UnmarshalExact(intoCfg)\n}\n\n\/\/ Get can retrieve any value given the key to use.\nfunc (l *Parser) Get(key string) interface{} {\n\treturn l.v.Get(key)\n}\n\n\/\/ Set sets the value for the key.\nfunc (l *Parser) Set(key string, value interface{}) {\n\tl.v.Set(key, value)\n}\n\n\/\/ IsSet checks to see if the key has been set in any of the data locations.\n\/\/ IsSet is case-insensitive for a key.\nfunc (l *Parser) IsSet(key string) bool {\n\treturn l.v.IsSet(key)\n}\n\n\/\/ MergeStringMap merges the configuration from the given map with the existing config.\n\/\/ Note that the given map may be modified.\nfunc (l *Parser) MergeStringMap(cfg map[string]interface{}) error {\n\treturn l.v.MergeConfigMap(cfg)\n}\n\n\/\/ Sub returns new Parser instance representing a sub tree of this instance.\nfunc (l *Parser) Sub(key string) (*Parser, error) {\n\t\/\/ Copied from the Viper but changed to use the same delimiter\n\t\/\/ and return error if the sub is not a map.\n\t\/\/ See https:\/\/github.com\/spf13\/viper\/issues\/871\n\tdata := l.Get(key)\n\tif data == nil {\n\t\treturn NewParser(), nil\n\t}\n\n\tif reflect.TypeOf(data).Kind() == reflect.Map {\n\t\tsubv := newViper()\n\t\t\/\/ Cannot return error because the subv is empty.\n\t\t_ = subv.MergeConfigMap(cast.ToStringMap(data))\n\t\treturn &Parser{v: subv}, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unexpected sub-config value kind for key:%s value:%v kind:%v)\", key, data, reflect.TypeOf(data).Kind())\n}\n\n\/\/ Viper returns the viper.Viper implementation of this Parser.\nfunc (l *Parser) Viper() *viper.Viper {\n\treturn l.v\n}\n\n\/\/ deepSearch scans deep maps, following the key indexes listed in the\n\/\/ sequence \"path\".\n\/\/ The last value is expected to be another map, and is returned.\n\/\/\n\/\/ In case intermediate keys do not exist, or map to a non-map value,\n\/\/ a new map is created and inserted, and the search continues from there:\n\/\/ the initial map \"m\" may be modified!\n\/\/ This function comes from Viper code https:\/\/github.com\/spf13\/viper\/blob\/5253694\/util.go#L201-L230\n\/\/ It is used here because of https:\/\/github.com\/spf13\/viper\/issues\/819\nfunc deepSearch(m map[string]interface{}, path []string) map[string]interface{} {\n\tfor _, k := range path {\n\t\tm2, ok := m[k]\n\t\tif !ok {\n\t\t\t\/\/ intermediate key does not exist\n\t\t\t\/\/ => create it and continue from there\n\t\t\tm3 := make(map[string]interface{})\n\t\t\tm[k] = m3\n\t\t\tm = m3\n\t\t\tcontinue\n\t\t}\n\t\tm3, ok := m2.(map[string]interface{})\n\t\tif !ok {\n\t\t\t\/\/ intermediate key is a value\n\t\t\t\/\/ => replace with a new map\n\t\t\tm3 = make(map[string]interface{})\n\t\t\tm[k] = m3\n\t\t}\n\t\t\/\/ continue search from here\n\t\tm = m3\n\t}\n\treturn m\n}\n\n\/\/ ToStringMap creates a map[string]interface{} from a Parser.\nfunc (l *Parser) ToStringMap() map[string]interface{} {\n\t\/\/ This is equivalent to l.v.AllSettings() but it maps nil values\n\t\/\/ We can't use AllSettings here because of https:\/\/github.com\/spf13\/viper\/issues\/819\n\n\tm := map[string]interface{}{}\n\t\/\/ start from the list of keys, and construct the map one value at a time\n\tfor _, k := range l.v.AllKeys() {\n\t\tvalue := l.v.Get(k)\n\t\tpath := strings.Split(k, KeyDelimiter)\n\t\tlastKey := strings.ToLower(path[len(path)-1])\n\t\tdeepestMap := deepSearch(m, path[0:len(path)-1])\n\t\t\/\/ set innermost value\n\t\tdeepestMap[lastKey] = value\n\t}\n\treturn m\n}\n<commit_msg>Remove unused call to viper.AllKeys in Parser.UnmarshalExact (#2939)<commit_after>\/\/ Copyright The OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage config\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com\/spf13\/cast\"\n\t\"github.com\/spf13\/viper\"\n)\n\nconst (\n\t\/\/ KeyDelimiter is used as the default key delimiter in the default viper instance.\n\tKeyDelimiter = \"::\"\n)\n\n\/\/ newViper creates a new Viper instance with key delimiter KeyDelimiter instead of the\n\/\/ default \".\". This way configs can have keys that contain \".\".\nfunc newViper() *viper.Viper {\n\treturn viper.NewWithOptions(viper.KeyDelimiter(KeyDelimiter))\n}\n\n\/\/ NewParser creates a new empty Parser instance.\nfunc NewParser() *Parser {\n\treturn &Parser{\n\t\tv: newViper(),\n\t}\n}\n\n\/\/ NewParserFromFile creates a new Parser by reading the given file.\nfunc NewParserFromFile(fileName string) (*Parser, error) {\n\t\/\/ Read yaml config from file\n\tv := newViper()\n\tv.SetConfigFile(fileName)\n\tif err := v.ReadInConfig(); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read the file %v: %w\", fileName, err)\n\t}\n\treturn &Parser{v: v}, nil\n}\n\n\/\/ NewParserFromBuffer creates a new Parser by reading the given yaml buffer.\nfunc NewParserFromBuffer(buf io.Reader) (*Parser, error) {\n\tv := newViper()\n\tv.SetConfigType(\"yaml\")\n\tif err := v.ReadConfig(buf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Parser{v: v}, nil\n}\n\n\/\/ NewParserFromStringMap creates a parser from a map[string]interface{}.\nfunc NewParserFromStringMap(data map[string]interface{}) *Parser {\n\tv := newViper()\n\t\/\/ Cannot return error because the subv is empty.\n\t_ = v.MergeConfigMap(data)\n\treturn &Parser{v: v}\n}\n\n\/\/ Parser loads configuration.\ntype Parser struct {\n\tv *viper.Viper\n}\n\n\/\/ AllKeys returns all keys holding a value, regardless of where they are set.\n\/\/ Nested keys are returned with a KeyDelimiter separator\nfunc (l *Parser) AllKeys() []string {\n\treturn l.v.AllKeys()\n}\n\n\/\/ Unmarshal unmarshals the config into a struct. Make sure that the tags\n\/\/ on the fields of the structure are properly set.\nfunc (l *Parser) Unmarshal(rawVal interface{}) error {\n\treturn l.v.Unmarshal(rawVal)\n}\n\n\/\/ UnmarshalExact unmarshals the config into a struct, erroring if a field is nonexistent.\nfunc (l *Parser) UnmarshalExact(intoCfg interface{}) error {\n\treturn l.v.UnmarshalExact(intoCfg)\n}\n\n\/\/ Get can retrieve any value given the key to use.\nfunc (l *Parser) Get(key string) interface{} {\n\treturn l.v.Get(key)\n}\n\n\/\/ Set sets the value for the key.\nfunc (l *Parser) Set(key string, value interface{}) {\n\tl.v.Set(key, value)\n}\n\n\/\/ IsSet checks to see if the key has been set in any of the data locations.\n\/\/ IsSet is case-insensitive for a key.\nfunc (l *Parser) IsSet(key string) bool {\n\treturn l.v.IsSet(key)\n}\n\n\/\/ MergeStringMap merges the configuration from the given map with the existing config.\n\/\/ Note that the given map may be modified.\nfunc (l *Parser) MergeStringMap(cfg map[string]interface{}) error {\n\treturn l.v.MergeConfigMap(cfg)\n}\n\n\/\/ Sub returns new Parser instance representing a sub tree of this instance.\nfunc (l *Parser) Sub(key string) (*Parser, error) {\n\t\/\/ Copied from the Viper but changed to use the same delimiter\n\t\/\/ and return error if the sub is not a map.\n\t\/\/ See https:\/\/github.com\/spf13\/viper\/issues\/871\n\tdata := l.Get(key)\n\tif data == nil {\n\t\treturn NewParser(), nil\n\t}\n\n\tif reflect.TypeOf(data).Kind() == reflect.Map {\n\t\tsubv := newViper()\n\t\t\/\/ Cannot return error because the subv is empty.\n\t\t_ = subv.MergeConfigMap(cast.ToStringMap(data))\n\t\treturn &Parser{v: subv}, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"unexpected sub-config value kind for key:%s value:%v kind:%v)\", key, data, reflect.TypeOf(data).Kind())\n}\n\n\/\/ Viper returns the viper.Viper implementation of this Parser.\nfunc (l *Parser) Viper() *viper.Viper {\n\treturn l.v\n}\n\n\/\/ deepSearch scans deep maps, following the key indexes listed in the\n\/\/ sequence \"path\".\n\/\/ The last value is expected to be another map, and is returned.\n\/\/\n\/\/ In case intermediate keys do not exist, or map to a non-map value,\n\/\/ a new map is created and inserted, and the search continues from there:\n\/\/ the initial map \"m\" may be modified!\n\/\/ This function comes from Viper code https:\/\/github.com\/spf13\/viper\/blob\/5253694\/util.go#L201-L230\n\/\/ It is used here because of https:\/\/github.com\/spf13\/viper\/issues\/819\nfunc deepSearch(m map[string]interface{}, path []string) map[string]interface{} {\n\tfor _, k := range path {\n\t\tm2, ok := m[k]\n\t\tif !ok {\n\t\t\t\/\/ intermediate key does not exist\n\t\t\t\/\/ => create it and continue from there\n\t\t\tm3 := make(map[string]interface{})\n\t\t\tm[k] = m3\n\t\t\tm = m3\n\t\t\tcontinue\n\t\t}\n\t\tm3, ok := m2.(map[string]interface{})\n\t\tif !ok {\n\t\t\t\/\/ intermediate key is a value\n\t\t\t\/\/ => replace with a new map\n\t\t\tm3 = make(map[string]interface{})\n\t\t\tm[k] = m3\n\t\t}\n\t\t\/\/ continue search from here\n\t\tm = m3\n\t}\n\treturn m\n}\n\n\/\/ ToStringMap creates a map[string]interface{} from a Parser.\nfunc (l *Parser) ToStringMap() map[string]interface{} {\n\t\/\/ This is equivalent to l.v.AllSettings() but it maps nil values\n\t\/\/ We can't use AllSettings here because of https:\/\/github.com\/spf13\/viper\/issues\/819\n\n\tm := map[string]interface{}{}\n\t\/\/ start from the list of keys, and construct the map one value at a time\n\tfor _, k := range l.v.AllKeys() {\n\t\tvalue := l.v.Get(k)\n\t\tpath := strings.Split(k, KeyDelimiter)\n\t\tlastKey := strings.ToLower(path[len(path)-1])\n\t\tdeepestMap := deepSearch(m, path[0:len(path)-1])\n\t\t\/\/ set innermost value\n\t\tdeepestMap[lastKey] = value\n\t}\n\treturn m\n}\n<|endoftext|>"}
{"text":"<commit_before>package configuration\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc Test_Configuration_Env_UnknownEnvironment(t *testing.T) {\n\tc := Configuration{}\n\t_, err := c.Env(\"test\", map[string]string{})\n\n\tif err == nil {\n\t\tt.Error(\"didn't failed on unknown environment\")\n\t}\n\n\tif err.Error() != \"unkown environment test\" {\n\t\tt.Error(\"didn't returned expected error:\", err)\n\t}\n}\n\nfunc Test_Configuration_Env_Override(t *testing.T) {\n\tvar sEnv = \"env\"\n\tvar iEnv = uint64(1)\n\ttype Case struct {\n\t\tName          string\n\t\tConfiguration Configuration\n\t\tFlags         map[string]string\n\t\tEnv           *Environment\n\t}\n\tvar cases = []Case{\n\t\tCase{\n\t\t\tName: \"test\",\n\t\t\tConfiguration: Configuration{\n\t\t\t\tDriver:    \"base\",\n\t\t\t\tProtocol:  \"base\",\n\t\t\t\tHost:      \"base\",\n\t\t\t\tPort:      0,\n\t\t\t\tUser:      \"base\",\n\t\t\t\tPassword:  \"base\",\n\t\t\t\tDatabase:  \"base\",\n\t\t\t\tDirectory: \"base\",\n\t\t\t\tEnvironments: map[string]RawEnvironment{\n\t\t\t\t\t\"test\": RawEnvironment{\n\t\t\t\t\t\tDriver:    &sEnv,\n\t\t\t\t\t\tProtocol:  &sEnv,\n\t\t\t\t\t\tHost:      &sEnv,\n\t\t\t\t\t\tPort:      &iEnv,\n\t\t\t\t\t\tUser:      &sEnv,\n\t\t\t\t\t\tPassword:  &sEnv,\n\t\t\t\t\t\tDatabase:  &sEnv,\n\t\t\t\t\t\tDirectory: &sEnv,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tFlags: map[string]string{\n\t\t\t\t\"driver\":    \"flag\",\n\t\t\t\t\"protocol\":  \"flag\",\n\t\t\t\t\"host\":      \"flag\",\n\t\t\t\t\"port\":      \"2\",\n\t\t\t\t\"user\":      \"flag\",\n\t\t\t\t\"password\":  \"flag\",\n\t\t\t\t\"database\":  \"flag\",\n\t\t\t\t\"directory\": \"flag\",\n\t\t\t},\n\t\t\tEnv: &Environment{\n\t\t\t\tDriver:    \"flag\",\n\t\t\t\tProtocol:  \"flag\",\n\t\t\t\tHost:      \"flag\",\n\t\t\t\tPort:      2,\n\t\t\t\tUser:      \"flag\",\n\t\t\t\tPassword:  \"flag\",\n\t\t\t\tDatabase:  \"flag\",\n\t\t\t\tDirectory: \"flag\",\n\t\t\t},\n\t\t},\n\t\tCase{\n\t\t\tName: \"test\",\n\t\t\tConfiguration: Configuration{\n\t\t\t\tDriver:    \"base\",\n\t\t\t\tProtocol:  \"base\",\n\t\t\t\tHost:      \"base\",\n\t\t\t\tPort:      0,\n\t\t\t\tUser:      \"base\",\n\t\t\t\tPassword:  \"base\",\n\t\t\t\tDatabase:  \"base\",\n\t\t\t\tDirectory: \"base\",\n\t\t\t\tEnvironments: map[string]RawEnvironment{\n\t\t\t\t\t\"test\": RawEnvironment{\n\t\t\t\t\t\tDriver:    &sEnv,\n\t\t\t\t\t\tProtocol:  &sEnv,\n\t\t\t\t\t\tHost:      &sEnv,\n\t\t\t\t\t\tPort:      &iEnv,\n\t\t\t\t\t\tUser:      &sEnv,\n\t\t\t\t\t\tPassword:  &sEnv,\n\t\t\t\t\t\tDatabase:  &sEnv,\n\t\t\t\t\t\tDirectory: &sEnv,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tFlags: map[string]string{},\n\t\t\tEnv: &Environment{\n\t\t\t\tDriver:    \"env\",\n\t\t\t\tProtocol:  \"env\",\n\t\t\t\tHost:      \"env\",\n\t\t\t\tPort:      1,\n\t\t\t\tUser:      \"env\",\n\t\t\t\tPassword:  \"env\",\n\t\t\t\tDatabase:  \"env\",\n\t\t\t\tDirectory: \"env\",\n\t\t\t},\n\t\t},\n\t\tCase{\n\t\t\tName: \"test\",\n\t\t\tConfiguration: Configuration{\n\t\t\t\tDriver:    \"base\",\n\t\t\t\tProtocol:  \"base\",\n\t\t\t\tHost:      \"base\",\n\t\t\t\tPort:      0,\n\t\t\t\tUser:      \"base\",\n\t\t\t\tPassword:  \"base\",\n\t\t\t\tDatabase:  \"base\",\n\t\t\t\tDirectory: \"base\",\n\t\t\t\tEnvironments: map[string]RawEnvironment{\n\t\t\t\t\t\"test\": RawEnvironment{},\n\t\t\t\t},\n\t\t\t},\n\t\t\tFlags: map[string]string{},\n\t\t\tEnv: &Environment{\n\t\t\t\tDriver:    \"base\",\n\t\t\t\tProtocol:  \"base\",\n\t\t\t\tHost:      \"base\",\n\t\t\t\tPort:      0,\n\t\t\t\tUser:      \"base\",\n\t\t\t\tPassword:  \"base\",\n\t\t\t\tDatabase:  \"base\",\n\t\t\t\tDirectory: \"base\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor n, c := range cases {\n\t\te, err := c.Configuration.Env(c.Name, c.Flags)\n\n\t\tif err != nil {\n\t\t\tt.Error(\"unexpected error\")\n\t\t}\n\n\t\tif !reflect.DeepEqual(e, c.Env) {\n\t\t\tt.Errorf(\"uncorrectly overriden environment for case %d\", n)\n\t\t}\n\t}\n}\n<commit_msg>Delete obsolete tests<commit_after><|endoftext|>"}
{"text":"<commit_before>package gitpods\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestUser_Validate(t *testing.T) {\n\tu := &User{}\n\terr := u.Validate()\n\tassert.Equal(t, \"id: non zero value required;\"+\n\t\t\"email: non zero value required;\"+\n\t\t\"username: non zero value required;\"+\n\t\t\"name: non zero value required;\", err.Error())\n\n\t\/\/ Add values, but not valid ones.\n\tu.ID = \"b755461a-a923-4828-aee1\"\n\tu.Username = \"abc\"\n\tu.Name = \"bla\"\n\tu.Email = \"nomail\"\n\tu.Password = \"password\"\n\n\terr = u.Validate()\n\tassert.Equal(t, \"id: b755461a-a923-4828-aee1 does not validate as uuidv4;\"+\n\t\t\"email: nomail does not validate as email;\"+\n\t\t\"username: abc does not validate as length(4|32);\", err.Error())\n\n\t\/\/ Add valid values\n\tu.ID = \"b755461a-a923-4828-aee1-215903f26e0b\"\n\tu.Username = \"metalmatze\"\n\tu.Name = \"Matthias Loibl\"\n\tu.Email = \"metalmatze@example.com\"\n\tu.Password = \"password\"\n\terr = u.Validate()\n\tassert.NoError(t, err)\n}\n<commit_msg>Delete user_test.go testing Validate method in the entity<commit_after><|endoftext|>"}
{"text":"<commit_before>package s3crypto\n\nimport (\n\t\"encoding\/hex\"\n\t\"io\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/client\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/request\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\/s3iface\"\n)\n\n\/\/ DefaultMinFileSize is used to check whether we want to write to a temp file\n\/\/ or store the data in memory.\nconst DefaultMinFileSize = 1024 * 512 * 5\n\n\/\/ EncryptionClient is an S3 crypto client. By default the SDK will use Authentication mode which\n\/\/ will use KMS for key wrapping and AES GCM for content encryption.\n\/\/ AES GCM will load all data into memory. However, the rest of the content algorithms\n\/\/ do not load the entire contents into memory.\ntype EncryptionClient struct {\n\tS3Client             s3iface.S3API\n\tContentCipherBuilder ContentCipherBuilder\n\t\/\/ SaveStrategy will dictate where the envelope is saved.\n\t\/\/\n\t\/\/ Defaults to the object's metadata\n\tSaveStrategy SaveStrategy\n\t\/\/ TempFolderPath is used to store temp files when calling PutObject.\n\t\/\/ Temporary files are needed to compute the X-Amz-Content-Sha256 header.\n\tTempFolderPath string\n\t\/\/ MinFileSize is the minimum size for the content to write to a\n\t\/\/ temporary file instead of using memory.\n\tMinFileSize int64\n}\n\n\/\/ NewEncryptionClient instantiates a new S3 crypto client\n\/\/\n\/\/ Example:\n\/\/\tcmkID := \"arn:aws:kms:region:000000000000:key\/00000000-0000-0000-0000-000000000000\"\n\/\/\tsess := session.New()\n\/\/\thandler := s3crypto.NewKMSKeyGenerator(kms.New(sess), cmkID)\n\/\/\tsvc := s3crypto.New(sess, s3crypto.AESGCMContentCipherBuilder(handler))\nfunc NewEncryptionClient(prov client.ConfigProvider, builder ContentCipherBuilder, options ...func(*EncryptionClient)) *EncryptionClient {\n\tclient := &EncryptionClient{\n\t\tS3Client:             s3.New(prov),\n\t\tContentCipherBuilder: builder,\n\t\tSaveStrategy:         HeaderV2SaveStrategy{},\n\t\tMinFileSize:          DefaultMinFileSize,\n\t}\n\n\tfor _, option := range options {\n\t\toption(client)\n\t}\n\n\treturn client\n}\n\n\/\/ PutObjectRequest creates a temp file to encrypt the contents into. It then streams\n\/\/ that data to S3.\n\/\/\n\/\/ Example:\n\/\/\tsvc := s3crypto.New(session.New(), s3crypto.AESGCMContentCipherBuilder(handler))\n\/\/\treq, out := svc.PutObjectRequest(&s3.PutObjectInput {\n\/\/\t  Key: aws.String(\"testKey\"),\n\/\/\t  Bucket: aws.String(\"testBucket\"),\n\/\/\t  Body: bytes.NewBuffer(\"test data\"),\n\/\/\t})\n\/\/\terr := req.Send()\nfunc (c *EncryptionClient) PutObjectRequest(input *s3.PutObjectInput) (*request.Request, *s3.PutObjectOutput) {\n\treq, out := c.S3Client.PutObjectRequest(input)\n\n\t\/\/ Get Size of file\n\tn, err := input.Body.Seek(0, 2)\n\tif err != nil {\n\t\treq.Error = err\n\t\treturn req, out\n\t}\n\tinput.Body.Seek(0, 0)\n\n\tdst, err := getWriterStore(req, c.TempFolderPath, n >= c.MinFileSize)\n\tif err != nil {\n\t\treq.Error = err\n\t\treturn req, out\n\t}\n\n\tencryptor, err := c.ContentCipherBuilder.ContentCipher()\n\treq.Handlers.Build.PushFront(func(r *request.Request) {\n\t\tif err != nil {\n\t\t\tr.Error = err\n\t\t\treturn\n\t\t}\n\n\t\tmd5 := newMD5Reader(input.Body)\n\t\tsha := newSHA256Writer(dst)\n\t\treader, err := encryptor.EncryptContents(md5)\n\t\tif err != nil {\n\t\t\tr.Error = err\n\t\t\treturn\n\t\t}\n\n\t\t_, err = io.Copy(sha, reader)\n\t\tif err != nil {\n\t\t\tr.Error = err\n\t\t\treturn\n\t\t}\n\n\t\tdata := encryptor.GetCipherData()\n\t\tenv, err := encodeMeta(md5, data)\n\t\tif err != nil {\n\t\t\tr.Error = err\n\t\t\treturn\n\t\t}\n\n\t\tshaHex := hex.EncodeToString(sha.GetValue())\n\t\treq.HTTPRequest.Header.Set(\"X-Amz-Content-Sha256\", shaHex)\n\n\t\tdst.Seek(0, 0)\n\t\tinput.Body = dst\n\n\t\terr = c.SaveStrategy.Save(env, r)\n\t\tr.Error = err\n\t})\n\n\treturn req, out\n}\n\n\/\/ PutObject is a wrapper for PutObjectRequest\nfunc (c *EncryptionClient) PutObject(input *s3.PutObjectInput) (*s3.PutObjectOutput, error) {\n\treq, out := c.PutObjectRequest(input)\n\treturn out, req.Send()\n}\n\n\/\/ PutObjectWithContext is a wrapper for PutObjectRequest with the additional\n\/\/ context, and request options support.\n\/\/\n\/\/ PutObjectWithContext is the same as PutObject with the additional support for\n\/\/ Context input parameters. The Context must not be nil. A nil Context will\n\/\/ cause a panic. Use the Context to add deadlining, timeouts, ect. In the future\n\/\/ this may create sub-contexts for individual underlying requests.\nfunc (c *EncryptionClient) PutObjectWithContext(ctx aws.Context, input *s3.PutObjectInput, opts ...request.Option) (*s3.PutObjectOutput, error) {\n\treq, out := c.PutObjectRequest(input)\n\treq.SetContext(ctx)\n\treq.ApplyOptions(opts...)\n\treturn out, req.Send()\n}\n<commit_msg>service\/s3\/s3crypto: Correct PutObjectRequest documentation (#1568)<commit_after>package s3crypto\n\nimport (\n\t\"encoding\/hex\"\n\t\"io\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/client\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/request\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\/s3iface\"\n)\n\n\/\/ DefaultMinFileSize is used to check whether we want to write to a temp file\n\/\/ or store the data in memory.\nconst DefaultMinFileSize = 1024 * 512 * 5\n\n\/\/ EncryptionClient is an S3 crypto client. By default the SDK will use Authentication mode which\n\/\/ will use KMS for key wrapping and AES GCM for content encryption.\n\/\/ AES GCM will load all data into memory. However, the rest of the content algorithms\n\/\/ do not load the entire contents into memory.\ntype EncryptionClient struct {\n\tS3Client             s3iface.S3API\n\tContentCipherBuilder ContentCipherBuilder\n\t\/\/ SaveStrategy will dictate where the envelope is saved.\n\t\/\/\n\t\/\/ Defaults to the object's metadata\n\tSaveStrategy SaveStrategy\n\t\/\/ TempFolderPath is used to store temp files when calling PutObject.\n\t\/\/ Temporary files are needed to compute the X-Amz-Content-Sha256 header.\n\tTempFolderPath string\n\t\/\/ MinFileSize is the minimum size for the content to write to a\n\t\/\/ temporary file instead of using memory.\n\tMinFileSize int64\n}\n\n\/\/ NewEncryptionClient instantiates a new S3 crypto client\n\/\/\n\/\/ Example:\n\/\/\tcmkID := \"arn:aws:kms:region:000000000000:key\/00000000-0000-0000-0000-000000000000\"\n\/\/\tsess := session.New()\n\/\/\thandler := s3crypto.NewKMSKeyGenerator(kms.New(sess), cmkID)\n\/\/\tsvc := s3crypto.New(sess, s3crypto.AESGCMContentCipherBuilder(handler))\nfunc NewEncryptionClient(prov client.ConfigProvider, builder ContentCipherBuilder, options ...func(*EncryptionClient)) *EncryptionClient {\n\tclient := &EncryptionClient{\n\t\tS3Client:             s3.New(prov),\n\t\tContentCipherBuilder: builder,\n\t\tSaveStrategy:         HeaderV2SaveStrategy{},\n\t\tMinFileSize:          DefaultMinFileSize,\n\t}\n\n\tfor _, option := range options {\n\t\toption(client)\n\t}\n\n\treturn client\n}\n\n\/\/ PutObjectRequest creates a temp file to encrypt the contents into. It then streams\n\/\/ that data to S3.\n\/\/\n\/\/ Example:\n\/\/\tsvc := s3crypto.New(session.New(), s3crypto.AESGCMContentCipherBuilder(handler))\n\/\/\treq, out := svc.PutObjectRequest(&s3.PutObjectInput {\n\/\/\t  Key: aws.String(\"testKey\"),\n\/\/\t  Bucket: aws.String(\"testBucket\"),\n\/\/\t  Body: strings.NewReader(\"test data\"),\n\/\/\t})\n\/\/\terr := req.Send()\nfunc (c *EncryptionClient) PutObjectRequest(input *s3.PutObjectInput) (*request.Request, *s3.PutObjectOutput) {\n\treq, out := c.S3Client.PutObjectRequest(input)\n\n\t\/\/ Get Size of file\n\tn, err := input.Body.Seek(0, 2)\n\tif err != nil {\n\t\treq.Error = err\n\t\treturn req, out\n\t}\n\tinput.Body.Seek(0, 0)\n\n\tdst, err := getWriterStore(req, c.TempFolderPath, n >= c.MinFileSize)\n\tif err != nil {\n\t\treq.Error = err\n\t\treturn req, out\n\t}\n\n\tencryptor, err := c.ContentCipherBuilder.ContentCipher()\n\treq.Handlers.Build.PushFront(func(r *request.Request) {\n\t\tif err != nil {\n\t\t\tr.Error = err\n\t\t\treturn\n\t\t}\n\n\t\tmd5 := newMD5Reader(input.Body)\n\t\tsha := newSHA256Writer(dst)\n\t\treader, err := encryptor.EncryptContents(md5)\n\t\tif err != nil {\n\t\t\tr.Error = err\n\t\t\treturn\n\t\t}\n\n\t\t_, err = io.Copy(sha, reader)\n\t\tif err != nil {\n\t\t\tr.Error = err\n\t\t\treturn\n\t\t}\n\n\t\tdata := encryptor.GetCipherData()\n\t\tenv, err := encodeMeta(md5, data)\n\t\tif err != nil {\n\t\t\tr.Error = err\n\t\t\treturn\n\t\t}\n\n\t\tshaHex := hex.EncodeToString(sha.GetValue())\n\t\treq.HTTPRequest.Header.Set(\"X-Amz-Content-Sha256\", shaHex)\n\n\t\tdst.Seek(0, 0)\n\t\tinput.Body = dst\n\n\t\terr = c.SaveStrategy.Save(env, r)\n\t\tr.Error = err\n\t})\n\n\treturn req, out\n}\n\n\/\/ PutObject is a wrapper for PutObjectRequest\nfunc (c *EncryptionClient) PutObject(input *s3.PutObjectInput) (*s3.PutObjectOutput, error) {\n\treq, out := c.PutObjectRequest(input)\n\treturn out, req.Send()\n}\n\n\/\/ PutObjectWithContext is a wrapper for PutObjectRequest with the additional\n\/\/ context, and request options support.\n\/\/\n\/\/ PutObjectWithContext is the same as PutObject with the additional support for\n\/\/ Context input parameters. The Context must not be nil. A nil Context will\n\/\/ cause a panic. Use the Context to add deadlining, timeouts, ect. In the future\n\/\/ this may create sub-contexts for individual underlying requests.\nfunc (c *EncryptionClient) PutObjectWithContext(ctx aws.Context, input *s3.PutObjectInput, opts ...request.Option) (*s3.PutObjectOutput, error) {\n\treq, out := c.PutObjectRequest(input)\n\treq.SetContext(ctx)\n\treq.ApplyOptions(opts...)\n\treturn out, req.Send()\n}\n<|endoftext|>"}
{"text":"<commit_before>package util\n\nimport (\n\t\"context\"\n\t\"crypto\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"encoding\/base64\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/mundipagg\/boleto-api\/certificate\"\n\t\"github.com\/mundipagg\/boleto-api\/log\"\n\n\ts \"github.com\/fullsailor\/pkcs7\"\n\t\"github.com\/mundipagg\/boleto-api\/config\"\n)\n\nvar defaultDialer = &net.Dialer{Timeout: 16 * time.Second, KeepAlive: 16 * time.Second}\n\nvar (\n\tclient            *http.Client\n\tonceDefaultClient = &sync.Once{}\n\tonceTransport     = &sync.Once{}\n\ticpCert           certificate.ICPCertificate\n\ttransport         *http.Transport\n)\n\n\/\/ HTTPInterface is an abstraction for HTTP client\ntype HTTPInterface interface {\n\tPost(url string, headers map[string]string, body interface{}) (*http.Response, error)\n}\n\n\/\/ HTTPClient is the struct for making requests\ntype HTTPClient struct{}\n\n\/\/ PostFormEncoded is a function for making requests using Post Http method with content-type application\/x-www-form-urlencoded.\n\/\/\n\/\/ It receives an endpoint, params and pointer for log and it creates a new Post request, returning []byte and a error.\nfunc (hc *HTTPClient) PostFormURLEncoded(endpoint string, params map[string]string, log *log.Log) ([]byte, error) {\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 10,\n\t}\n\n\turi, err := url.ParseRequestURI(endpoint)\n\tif err != nil {\n\t\treturn []byte(\"\"), err\n\t}\n\n\tvalues := uri.Query()\n\tfor k, v := range params {\n\t\tvalues.Set(k, v)\n\t}\n\n\treq, err := http.NewRequest(http.MethodPost, uri.String(), strings.NewReader(values.Encode())) \/\/ URL-encoded payload\n\n\tif err != nil {\n\t\treturn []byte(\"\"), err\n\t}\n\n\theader := map[string]string{\n\t\t\"content-type\":   \"application\/x-www-form-urlencoded\",\n\t\t\"content-length\": strconv.Itoa(len(values.Encode())),\n\t}\n\n\tfor k, v := range header {\n\t\treq.Header.Add(k, v)\n\t}\n\n\tlog.Request(params, endpoint, header)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn []byte(\"\"), err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn []byte(\"\"), fmt.Errorf(\"stone authentication returns status code %d\", resp.StatusCode)\n\t}\n\n\trespByte, err := ioutil.ReadAll(resp.Body)\n\tlog.Response(string(respByte), endpoint)\n\n\treturn respByte, err\n}\n\n\/\/ DefaultHTTPClient retorna um cliente http configurado para dar um skip na validação do certificado digital\nfunc DefaultHTTPClient() *http.Client {\n\tonceDefaultClient.Do(func() {\n\t\tclient = &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDial:                defaultDialer.Dial,\n\t\t\t\tTLSHandshakeTimeout: 16 * time.Second,\n\t\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\t\tInsecureSkipVerify: true,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t})\n\treturn client\n}\n\n\/\/Post faz um requisição POST para uma URL e retorna o response, status e erro\nfunc Post(url, body, timeout string, header map[string]string) (string, int, error) {\n\treturn doRequest(\"POST\", url, body, timeout, header)\n}\n\n\/\/Get faz um requisição GET para uma URL e retorna o response, status e erro\nfunc Get(url, body, timeout string, header map[string]string) (string, int, error) {\n\treturn doRequest(\"GET\", url, body, timeout, header)\n}\n\nfunc doRequest(method, url, body, timeout string, header map[string]string) (string, int, error) {\n\tt := GetDurationTimeoutRequest(timeout) * time.Second\n\n\tctx, cls := context.WithTimeout(context.Background(), t)\n\tdefer cls()\n\n\tclient := DefaultHTTPClient()\n\n\tmessage := strings.NewReader(body)\n\n\treq, err := http.NewRequestWithContext(ctx, method, url, message)\n\tif err != nil {\n\t\treturn \"\", http.StatusInternalServerError, err\n\t}\n\tif header != nil {\n\t\tfor k, v := range header {\n\t\t\treq.Header.Add(k, v)\n\t\t}\n\t}\n\tresp, errResp := client.Do(req)\n\tif errResp != nil {\n\t\treturn \"\", 0, errResp\n\t}\n\tdefer resp.Body.Close()\n\tdata, errResponse := ioutil.ReadAll(resp.Body)\n\tif errResponse != nil {\n\t\treturn \"\", resp.StatusCode, errResponse\n\t}\n\tsData := string(data)\n\treturn sData, resp.StatusCode, nil\n}\n\n\/\/ BuildTLSTransport creates a TLS Client Transport from crt, ca and key files\nfunc BuildTLSTransport() (*http.Transport, error) {\n\n\tif config.Get().MockMode {\n\t\treturn nil, nil\n\t}\n\n\tvar errF error\n\tonceTransport.Do(func() {\n\n\t\tssl, err := certificate.GetCertificateFromStore(config.Get().CertificateSSLName)\n\t\tif err != nil {\n\t\t\terrF = err\n\t\t\treturn\n\t\t}\n\n\t\tcert, err := tls.X509KeyPair(ssl.(certificate.SSLCertificate).PemData, ssl.(certificate.SSLCertificate).PemData)\n\t\tif err != nil {\n\t\t\terrF = err\n\t\t\treturn\n\t\t}\n\n\t\ttransport = &http.Transport{\n\t\t\tDial:                defaultDialer.Dial,\n\t\t\tTLSHandshakeTimeout: 16 * time.Second,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tCertificates:       []tls.Certificate{cert},\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t},\n\t\t}\n\t\treturn\n\t})\n\treturn transport, errF\n}\n\n\/\/Sign request\nfunc SignRequest(request string) (string, error) {\n\n\tif icpCert == (certificate.ICPCertificate{}) {\n\t\ticp, err := certificate.GetCertificateFromStore(config.Get().CertificateICPName)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\ticpCert = icp.(certificate.ICPCertificate)\n\t}\n\n\tsignedData, err := s.NewSignedData([]byte(request))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := signedData.AddSigner(icpCert.Certificate, icpCert.RsaPrivateKey, s.SignerInfoConfig{}); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdetachedSignature, err := signedData.Finish()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsignedRequest := base64.StdEncoding.EncodeToString(detachedSignature)\n\n\treturn signedRequest, nil\n}\n\n\/\/Read privatekey and parse to PKCS#1\nfunc parsePrivateKey() (crypto.PrivateKey, error) {\n\n\tpkeyBytes, err := ioutil.ReadFile(config.Get().CertICP_PathPkey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, _ := pem.Decode(pkeyBytes)\n\tif block == nil {\n\t\treturn nil, errors.New(\"Key Not Found\")\n\t}\n\n\tswitch block.Type {\n\tcase \"RSA PRIVATE KEY\":\n\t\trsa, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn rsa, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"SSH: Unsupported key type %q\", block.Type)\n\t}\n\n}\n\n\/\/\/Read chainCertificates and adapter to x509.Certificate\nfunc parseChainCertificates() (*x509.Certificate, error) {\n\n\tchainCertsBytes, err := ioutil.ReadFile(config.Get().CertICP_PathChainCertificates)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, _ := pem.Decode(chainCertsBytes)\n\tif block == nil {\n\t\treturn nil, errors.New(\"Key Not Found\")\n\t}\n\n\tcert, err := x509.ParseCertificate(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cert, nil\n}\n\nfunc doRequestTLS(method, url, body, timeout string, header map[string]string, transport *http.Transport) (string, int, error) {\n\ttlsClient := &http.Client{}\n\ttlsClient.Transport = transport\n\ttlsClient.Timeout = GetDurationTimeoutRequest(timeout) * time.Second\n\tb := strings.NewReader(body)\n\treq, err := http.NewRequest(method, url, b)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\n\tif header != nil {\n\t\tfor k, v := range header {\n\t\t\treq.Header.Add(k, v)\n\t\t}\n\t}\n\tresp, err := tlsClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\tdefer resp.Body.Close()\n\t\/\/ Dump response\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\tsData := string(data)\n\treturn sData, resp.StatusCode, nil\n}\n\nfunc PostTLS(url, body, timeout string, header map[string]string, transport *http.Transport) (string, int, error) {\n\treturn doRequestTLS(\"POST\", url, body, timeout, header, transport)\n}\n\n\/\/HeaderToMap converte um http Header para um dicionário string -> string\nfunc HeaderToMap(h http.Header) map[string]string {\n\tm := make(map[string]string)\n\tfor k, v := range h {\n\t\tm[k] = v[0]\n\t}\n\treturn m\n}\n<commit_msg>refactor: retorna header da resposta http<commit_after>package util\n\nimport (\n\t\"context\"\n\t\"crypto\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"encoding\/base64\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/mundipagg\/boleto-api\/certificate\"\n\t\"github.com\/mundipagg\/boleto-api\/log\"\n\n\ts \"github.com\/fullsailor\/pkcs7\"\n\t\"github.com\/mundipagg\/boleto-api\/config\"\n)\n\nvar defaultDialer = &net.Dialer{Timeout: 16 * time.Second, KeepAlive: 16 * time.Second}\n\nvar (\n\tclient            *http.Client\n\tonceDefaultClient = &sync.Once{}\n\tonceTransport     = &sync.Once{}\n\ticpCert           certificate.ICPCertificate\n\ttransport         *http.Transport\n)\n\n\/\/ HTTPInterface is an abstraction for HTTP client\ntype HTTPInterface interface {\n\tPost(url string, headers map[string]string, body interface{}) (*http.Response, error)\n}\n\n\/\/ HTTPClient is the struct for making requests\ntype HTTPClient struct{}\n\n\/\/ PostFormEncoded is a function for making requests using Post Http method with content-type application\/x-www-form-urlencoded.\n\/\/\n\/\/ It receives an endpoint, params and pointer for log and it creates a new Post request, returning []byte and a error.\nfunc (hc *HTTPClient) PostFormURLEncoded(endpoint string, params map[string]string, log *log.Log) ([]byte, error) {\n\tclient := &http.Client{\n\t\tTimeout: time.Second * 10,\n\t}\n\n\turi, err := url.ParseRequestURI(endpoint)\n\tif err != nil {\n\t\treturn []byte(\"\"), err\n\t}\n\n\tvalues := uri.Query()\n\tfor k, v := range params {\n\t\tvalues.Set(k, v)\n\t}\n\n\treq, err := http.NewRequest(http.MethodPost, uri.String(), strings.NewReader(values.Encode())) \/\/ URL-encoded payload\n\n\tif err != nil {\n\t\treturn []byte(\"\"), err\n\t}\n\n\theader := map[string]string{\n\t\t\"content-type\":   \"application\/x-www-form-urlencoded\",\n\t\t\"content-length\": strconv.Itoa(len(values.Encode())),\n\t}\n\n\tfor k, v := range header {\n\t\treq.Header.Add(k, v)\n\t}\n\n\tlog.Request(params, endpoint, header)\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn []byte(\"\"), err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn []byte(\"\"), fmt.Errorf(\"stone authentication returns status code %d\", resp.StatusCode)\n\t}\n\n\trespByte, err := ioutil.ReadAll(resp.Body)\n\tlog.Response(string(respByte), endpoint, nil)\n\n\treturn respByte, err\n}\n\n\/\/ DefaultHTTPClient retorna um cliente http configurado para dar um skip na validação do certificado digital\nfunc DefaultHTTPClient() *http.Client {\n\tonceDefaultClient.Do(func() {\n\t\tclient = &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDial:                defaultDialer.Dial,\n\t\t\t\tTLSHandshakeTimeout: 16 * time.Second,\n\t\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\t\tInsecureSkipVerify: true,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t})\n\treturn client\n}\n\n\/\/Post faz um requisição POST para uma URL e retorna o response, status e erro\nfunc PostReponseWithHeader(url, body, timeout string, header map[string]string) (string, string, int, error) {\n\treturn doRequest(\"POST\", url, body, timeout, header)\n}\n\n\/\/Get faz um requisição GET para uma URL e retorna o response, status e erro\nfunc Get(url, body, timeout string, header map[string]string) (string, int, error) {\n\treturn doRequest(\"GET\", url, body, timeout, header)\n\/\/Post faz um requisição POST para uma URL e retorna o response, status e erro\nfunc Post(url, body, timeout string, header map[string]string) (string, int, error) {\n\tresp, _, st, err := doRequest(\"POST\", url, body, timeout, header)\n\treturn resp, st, err\n}\n\nfunc doRequest(method, url, body, timeout string, header map[string]string) (string, string, int, error) {\n\tt := GetDurationTimeoutRequest(timeout) * time.Second\n\n\tctx, cls := context.WithTimeout(context.Background(), t)\n\tdefer cls()\n\n\tclient := DefaultHTTPClient()\n\n\tmessage := strings.NewReader(body)\n\n\treq, err := http.NewRequestWithContext(ctx, method, url, message)\n\tif err != nil {\n\t\treturn \"\", \"\", http.StatusInternalServerError, err\n\t}\n\tif header != nil {\n\t\tfor k, v := range header {\n\t\t\treq.Header.Add(k, v)\n\t\t}\n\t}\n\tresp, errResp := client.Do(req)\n\tif errResp != nil {\n\t\treturn \"\", \"\", 0, errResp\n\t}\n\tdefer resp.Body.Close()\n\trespHeader := fmt.Sprintf(\"%v\", resp.Header)\n\n\tdata, errResponse := ioutil.ReadAll(resp.Body)\n\tif errResponse != nil {\n\t\treturn \"\", respHeader, resp.StatusCode, errResponse\n\t}\n\tsData := string(data)\n\treturn sData, respHeader, resp.StatusCode, nil\n}\n\n\/\/ BuildTLSTransport creates a TLS Client Transport from crt, ca and key files\nfunc BuildTLSTransport() (*http.Transport, error) {\n\n\tif config.Get().MockMode {\n\t\treturn nil, nil\n\t}\n\n\tvar errF error\n\tonceTransport.Do(func() {\n\n\t\tssl, err := certificate.GetCertificateFromStore(config.Get().CertificateSSLName)\n\t\tif err != nil {\n\t\t\terrF = err\n\t\t\treturn\n\t\t}\n\n\t\tcert, err := tls.X509KeyPair(ssl.(certificate.SSLCertificate).PemData, ssl.(certificate.SSLCertificate).PemData)\n\t\tif err != nil {\n\t\t\terrF = err\n\t\t\treturn\n\t\t}\n\n\t\ttransport = &http.Transport{\n\t\t\tDial:                defaultDialer.Dial,\n\t\t\tTLSHandshakeTimeout: 16 * time.Second,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tCertificates:       []tls.Certificate{cert},\n\t\t\t\tInsecureSkipVerify: true,\n\t\t\t},\n\t\t}\n\t\treturn\n\t})\n\treturn transport, errF\n}\n\n\/\/Sign request\nfunc SignRequest(request string) (string, error) {\n\n\tif icpCert == (certificate.ICPCertificate{}) {\n\t\ticp, err := certificate.GetCertificateFromStore(config.Get().CertificateICPName)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\ticpCert = icp.(certificate.ICPCertificate)\n\t}\n\n\tsignedData, err := s.NewSignedData([]byte(request))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err := signedData.AddSigner(icpCert.Certificate, icpCert.RsaPrivateKey, s.SignerInfoConfig{}); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdetachedSignature, err := signedData.Finish()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsignedRequest := base64.StdEncoding.EncodeToString(detachedSignature)\n\n\treturn signedRequest, nil\n}\n\n\/\/Read privatekey and parse to PKCS#1\nfunc parsePrivateKey() (crypto.PrivateKey, error) {\n\n\tpkeyBytes, err := ioutil.ReadFile(config.Get().CertICP_PathPkey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, _ := pem.Decode(pkeyBytes)\n\tif block == nil {\n\t\treturn nil, errors.New(\"Key Not Found\")\n\t}\n\n\tswitch block.Type {\n\tcase \"RSA PRIVATE KEY\":\n\t\trsa, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn rsa, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"SSH: Unsupported key type %q\", block.Type)\n\t}\n\n}\n\n\/\/\/Read chainCertificates and adapter to x509.Certificate\nfunc parseChainCertificates() (*x509.Certificate, error) {\n\n\tchainCertsBytes, err := ioutil.ReadFile(config.Get().CertICP_PathChainCertificates)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, _ := pem.Decode(chainCertsBytes)\n\tif block == nil {\n\t\treturn nil, errors.New(\"Key Not Found\")\n\t}\n\n\tcert, err := x509.ParseCertificate(block.Bytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cert, nil\n}\n\nfunc doRequestTLS(method, url, body, timeout string, header map[string]string, transport *http.Transport) (string, int, error) {\n\ttlsClient := &http.Client{}\n\ttlsClient.Transport = transport\n\ttlsClient.Timeout = GetDurationTimeoutRequest(timeout) * time.Second\n\tb := strings.NewReader(body)\n\treq, err := http.NewRequest(method, url, b)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\n\tif header != nil {\n\t\tfor k, v := range header {\n\t\t\treq.Header.Add(k, v)\n\t\t}\n\t}\n\tresp, err := tlsClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\tdefer resp.Body.Close()\n\t\/\/ Dump response\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\tsData := string(data)\n\treturn sData, resp.StatusCode, nil\n}\n\nfunc PostTLS(url, body, timeout string, header map[string]string, transport *http.Transport) (string, int, error) {\n\treturn doRequestTLS(\"POST\", url, body, timeout, header, transport)\n}\n\n\/\/HeaderToMap converte um http Header para um dicionário string -> string\nfunc HeaderToMap(h http.Header) map[string]string {\n\tm := make(map[string]string)\n\tfor k, v := range h {\n\t\tm[k] = v[0]\n\t}\n\treturn m\n}\n<|endoftext|>"}
{"text":"<commit_before>package check\n\n\/\/ GoLint is the check for the go lint command\ntype GoLint struct {\n\tDir       string\n\tFilenames []string\n}\n\n\/\/ Name returns the name of the display name of the command\nfunc (g GoLint) Name() string {\n\treturn \"golint\"\n}\n\n\/\/ Weight returns the weight this check has in the overall average\nfunc (g GoLint) Weight() float64 {\n\treturn .10\n}\n\n\/\/ Percentage returns the percentage of .go files that pass golint\nfunc (g GoLint) Percentage() (float64, []FileSummary, error) {\n\treturn GoTool(g.Dir, g.Filenames, []string{\"gometalinter\", \"--deadline=180s\", \"--disable-all\", \"--enable=golint\"})\n}\n\n\/\/ Description returns the description of go lint\nfunc (g GoLint) Description() string {\n\treturn `Golint is a linter for Go source code.`\n}\n<commit_msg>#121 increase min_confidence in golint<commit_after>package check\n\n\/\/ GoLint is the check for the go lint command\ntype GoLint struct {\n\tDir       string\n\tFilenames []string\n}\n\n\/\/ Name returns the name of the display name of the command\nfunc (g GoLint) Name() string {\n\treturn \"golint\"\n}\n\n\/\/ Weight returns the weight this check has in the overall average\nfunc (g GoLint) Weight() float64 {\n\treturn .10\n}\n\n\/\/ Percentage returns the percentage of .go files that pass golint\nfunc (g GoLint) Percentage() (float64, []FileSummary, error) {\n\treturn GoTool(g.Dir, g.Filenames, []string{\"gometalinter\", \"--deadline=180s\", \"--disable-all\", \"--enable=golint\", \"--min-confidence=0.85\"})\n}\n\n\/\/ Description returns the description of go lint\nfunc (g GoLint) Description() string {\n\treturn `Golint is a linter for Go source code.`\n}\n<|endoftext|>"}
{"text":"<commit_before>package browserpass\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/dannyvankooten\/browserpass\/pass\"\n)\n\n\/\/ Login represents a single pass login.\ntype Login struct {\n\tUsername string `json:\"u\"`\n\tPassword string `json:\"p\"`\n}\n\nvar endianness = binary.LittleEndian\n\n\/\/ msg defines a message sent from a browser extension.\ntype msg struct {\n\tAction string `json:\"action\"`\n\tDomain string `json:\"domain\"`\n\tEntry  string `json:\"entry\"`\n}\n\n\/\/ Run starts browserpass.\nfunc Run(stdin io.Reader, stdout io.Writer, s pass.Store) error {\n\tfor {\n\t\t\/\/ Get message length, 4 bytes\n\t\tvar n uint32\n\t\tif err := binary.Read(stdin, endianness, &n); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Get message body\n\t\tvar data msg\n\t\tlr := &io.LimitedReader{R: stdin, N: int64(n)}\n\t\tif err := json.NewDecoder(lr).Decode(&data); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar resp interface{}\n\t\tswitch data.Action {\n\t\tcase \"search\":\n\t\t\tlist, err := s.Search(data.Domain)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tresp = list\n\t\tcase \"get\":\n\t\t\trc, err := s.Open(data.Entry)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer rc.Close()\n\t\t\tlogin, err := readLoginGPG(rc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif login.Username == \"\" {\n\t\t\t\tlogin.Username = guessUsername(data.Entry)\n\t\t\t}\n\t\t\tresp = login\n\t\tdefault:\n\t\t\treturn errors.New(\"Invalid action\")\n\t\t}\n\n\t\tvar b bytes.Buffer\n\t\tif err := json.NewEncoder(&b).Encode(resp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := binary.Write(stdout, endianness, uint32(b.Len())); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := b.WriteTo(stdout); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\n\/\/ readLoginGPG reads a encrypted login from r using the system's GPG binary.\nfunc readLoginGPG(r io.Reader) (*Login, error) {\n\t\/\/ Assume gpg1\n\tgpgbin := \"gpg\"\n\topts := []string{\"--decrypt\", \"--yes\", \"--quiet\"}\n\n\t\/\/ Check if gpg2 is available\n\twhich := exec.Command(\"which\", \"gpg2\")\n\tif err := which.Run(); err == nil {\n\t\tgpgbin = \"gpg2\"\n\t\topts = append(opts, \"--use-agent\", \"--batch\")\n\t}\n\n\t\/\/ Tell gpg to read from stdin\n\topts = append(opts, \"-\")\n\n\t\/\/ Run gpg\n\tcmd := exec.Command(gpgbin, opts...)\n\n\tcmd.Stdin = r\n\n\trc, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar errbuf bytes.Buffer\n\tcmd.Stderr = &errbuf\n\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Read decrypted output\n\tlogin, err := parseLogin(rc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trc.Close()\n\n\tif err := cmd.Wait(); err != nil {\n\t\treturn nil, errors.New(err.Error() + \"\\n\" + errbuf.String())\n\t}\n\treturn login, nil\n}\n\n\/\/ parseLogin parses a login and a password from a decrypted password file.\nfunc parseLogin(r io.Reader) (*Login, error) {\n\tlogin := new(Login)\n\n\tscanner := bufio.NewScanner(r)\n\n\t\/\/ The first line is the password\n\tscanner.Scan()\n\tlogin.Password = scanner.Text()\n\n\t\/\/ Keep reading file for string in \"login:\", \"username:\" or \"user:\" format (case insensitive).\n\tre := regexp.MustCompile(\"(?i)^(login|username|user):\")\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\treplaced := re.ReplaceAllString(line, \"\")\n\t\tif len(replaced) != len(line) {\n\t\t\tlogin.Username = strings.TrimSpace(replaced)\n\t\t}\n\t}\n\n\treturn login, nil\n}\n\n\/\/ guessLogin tries to guess a username from an entry's name.\nfunc guessUsername(name string) string {\n\tif strings.Count(name, \"\/\") >= 1 {\n\t\treturn filepath.Base(name)\n\t}\n\treturn \"\"\n}\n<commit_msg>Fixes EOF errors<commit_after>package browserpass\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/dannyvankooten\/browserpass\/pass\"\n)\n\n\/\/ Login represents a single pass login.\ntype Login struct {\n\tUsername string `json:\"u\"`\n\tPassword string `json:\"p\"`\n}\n\nvar endianness = binary.LittleEndian\n\n\/\/ msg defines a message sent from a browser extension.\ntype msg struct {\n\tAction string `json:\"action\"`\n\tDomain string `json:\"domain\"`\n\tEntry  string `json:\"entry\"`\n}\n\n\/\/ Run starts browserpass.\nfunc Run(stdin io.Reader, stdout io.Writer, s pass.Store) error {\n\tfor {\n\t\t\/\/ Get message length, 4 bytes\n\t\tvar n uint32\n\t\tif err := binary.Read(stdin, endianness, &n); err == io.EOF {\n\t\t\treturn nil\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Get message body\n\t\tvar data msg\n\t\tlr := &io.LimitedReader{R: stdin, N: int64(n)}\n\t\tif err := json.NewDecoder(lr).Decode(&data); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar resp interface{}\n\t\tswitch data.Action {\n\t\tcase \"search\":\n\t\t\tlist, err := s.Search(data.Domain)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tresp = list\n\t\tcase \"get\":\n\t\t\trc, err := s.Open(data.Entry)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer rc.Close()\n\t\t\tlogin, err := readLoginGPG(rc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif login.Username == \"\" {\n\t\t\t\tlogin.Username = guessUsername(data.Entry)\n\t\t\t}\n\t\t\tresp = login\n\t\tdefault:\n\t\t\treturn errors.New(\"Invalid action\")\n\t\t}\n\n\t\tvar b bytes.Buffer\n\t\tif err := json.NewEncoder(&b).Encode(resp); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := binary.Write(stdout, endianness, uint32(b.Len())); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := b.WriteTo(stdout); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\n\/\/ readLoginGPG reads a encrypted login from r using the system's GPG binary.\nfunc readLoginGPG(r io.Reader) (*Login, error) {\n\t\/\/ Assume gpg1\n\tgpgbin := \"gpg\"\n\topts := []string{\"--decrypt\", \"--yes\", \"--quiet\"}\n\n\t\/\/ Check if gpg2 is available\n\twhich := exec.Command(\"which\", \"gpg2\")\n\tif err := which.Run(); err == nil {\n\t\tgpgbin = \"gpg2\"\n\t\topts = append(opts, \"--use-agent\", \"--batch\")\n\t}\n\n\t\/\/ Tell gpg to read from stdin\n\topts = append(opts, \"-\")\n\n\t\/\/ Run gpg\n\tcmd := exec.Command(gpgbin, opts...)\n\n\tcmd.Stdin = r\n\n\trc, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar errbuf bytes.Buffer\n\tcmd.Stderr = &errbuf\n\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Read decrypted output\n\tlogin, err := parseLogin(rc)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trc.Close()\n\n\tif err := cmd.Wait(); err != nil {\n\t\treturn nil, errors.New(err.Error() + \"\\n\" + errbuf.String())\n\t}\n\treturn login, nil\n}\n\n\/\/ parseLogin parses a login and a password from a decrypted password file.\nfunc parseLogin(r io.Reader) (*Login, error) {\n\tlogin := new(Login)\n\n\tscanner := bufio.NewScanner(r)\n\n\t\/\/ The first line is the password\n\tscanner.Scan()\n\tlogin.Password = scanner.Text()\n\n\t\/\/ Keep reading file for string in \"login:\", \"username:\" or \"user:\" format (case insensitive).\n\tre := regexp.MustCompile(\"(?i)^(login|username|user):\")\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\treplaced := re.ReplaceAllString(line, \"\")\n\t\tif len(replaced) != len(line) {\n\t\t\tlogin.Username = strings.TrimSpace(replaced)\n\t\t}\n\t}\n\n\treturn login, nil\n}\n\n\/\/ guessLogin tries to guess a username from an entry's name.\nfunc guessUsername(name string) string {\n\tif strings.Count(name, \"\/\") >= 1 {\n\t\treturn filepath.Base(name)\n\t}\n\treturn \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>\n\/\/ This package provides a priority queue implementation and\n\/\/ scaffold interfaces.\n\/\/\n\/\/ Addition to original package, this package adds method and\n\/\/ other internals for inserting only unique items in queue\n\/\/\n\/\/ Copyright (C) 2011 by Krzysztof Kowalik <chris@nu7hat.ch>\npackage mungos\n\nimport (\n\t\"container\/heap\"\n\t\"errors\"\n\t\"sync\"\n)\n\n\/\/ Only items implementing this interface can be enqueued\n\/\/ on the priority queue.\ntype QueueItem interface {\n\tLess(other interface{}) bool\n\tId() interface{}\n}\n\n\/\/ Queue is a threadsafe priority queue exchange. Here's\n\/\/ a trivial example of usage:\n\/\/\n\/\/     q := pqueue.New(0)\n\/\/     go func() {\n\/\/         for {\n\/\/             task := q.Dequeue()\n\/\/             println(task.(*CustomTask).Name)\n\/\/         }\n\/\/     }()\n\/\/     for i := 0; i < 100; i := 1 {\n\/\/         task := CustomTask{Name: \"foo\", priority: rand.Intn(10)}\n\/\/         q.Enqueue(&task)\n\/\/     }\n\/\/\ntype Queue struct {\n\tLimit int\n\thistory map[interface{}]struct{}\n\titems *sorter\n\tcond  *sync.Cond\n}\n\n\/\/ New creates and initializes a new priority queue, taking\n\/\/ a limit as a parameter. If 0 given, then queue will be\n\/\/ unlimited. \nfunc New(max int) (q *Queue) {\n\tvar locker sync.Mutex\n\tq = &Queue{Limit: max}\n\tq.history = make(map[interface{}]struct{}, 0);\n\tq.items = new(sorter)\n\tq.cond = sync.NewCond(&locker)\n\theap.Init(q.items)\n\treturn\n}\n\n\/\/ Enqueue puts given item to the queue.\n\/\/ Lock the queue and calls enqueue()\nfunc (q *Queue) Enqueue(item QueueItem) (err error) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\treturn q.enqueue(item)\n}\n\n\/\/ Enqueue puts given item to the queue.\nfunc (q *Queue) enqueue(item QueueItem) (err error) {\n\tif q.Limit > 0 && q.Len() >= q.Limit {\n\t\treturn errors.New(\"Queue limit reached\")\n\t}\n\tq.history[item.Id()] = struct{}{};\n\theap.Push(q.items, item)\n\tq.cond.Signal()\n\treturn\n}\n\n\/\/ check if item already exists in queue (or it has been into queue)\nfunc (q *Queue) Exists(item QueueItem) bool {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\treturn q.exists(item)\n}\n\nfunc (q *Queue) exists(item QueueItem) bool {\n\tif _, ok := q.history[item.Id()]; ok {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\n\n\/\/ Enqueue puts item in queue only if it hasn't already been in queue\nfunc (q *Queue) EnqueueUnique(item QueueItem) (err error) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\tif !q.exists(item) {\n\t\tq.enqueue(item)\n\t}\n\treturn\n}\n\n\n\n\/\/ Dequeue takes an item from the queue. If queue is empty\n\/\/ then should block waiting for at least one item.\nfunc (q *Queue) Dequeue() (item QueueItem) {\n\tq.cond.L.Lock()\t\n\tdefer q.cond.L.Unlock()\n\tvar x interface{}\n\tfor {\n\t\tx = heap.Pop(q.items)\n\t\tif x == nil {\n\t\t\tq.cond.Wait()\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\titem = x.(QueueItem)\n\treturn\n}\n\n\/\/ Safely changes enqueued items limit. When limit is set\n\/\/ to 0, then queue is unlimited.\nfunc (q *Queue) ChangeLimit(newLimit int) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\tq.Limit = newLimit\n}\n\n\/\/ Len returns number of enqueued elemnents.\nfunc (q *Queue) Len() int {\n\treturn q.items.Len()\n}\n\n\/\/ IsEmpty returns true if queue is empty.\nfunc (q *Queue) IsEmpty() bool {\n\treturn q.Len() == 0\n}\n\ntype sorter []QueueItem\n\nfunc (s *sorter) Push(i interface{}) {\n\titem, ok := i.(QueueItem)\n\tif !ok {\n\t\treturn\n\t}\n\t*s = append((*s)[:], item)\n}\n\nfunc (s *sorter) Pop() (x interface{}) {\n\tif s.Len() > 0 {\n\t\tl := s.Len()-1\n\t\tx = (*s)[l]\n\t\t(*s)[l] = nil\n\t\t*s = (*s)[:l]\n\t}\n\treturn\n}\n\nfunc (s *sorter) Len() int {\n\treturn len((*s)[:])\n}\n\nfunc (s *sorter) Less(i, j int) bool {\n\treturn (*s)[i].Less((*s)[j])\n}\n\nfunc (s *sorter) Swap(i, j int) {\n\tif s.Len() > 0 {\n\t\t(*s)[i], (*s)[j] = (*s)[j], (*s)[i]\n\t}\n}<commit_msg>Modify package name changed back<commit_after>\n\/\/ This package provides a priority queue implementation and\n\/\/ scaffold interfaces.\n\/\/\n\/\/ Addition to original package, this package adds method and\n\/\/ other internals for inserting only unique items in queue\n\/\/\n\/\/ Copyright (C) 2015 by Milos Mileusnic <milos@groowe.com>\n\/\/\n\/\/ Copyright (C) 2011 by Krzysztof Kowalik <chris@nu7hat.ch>\npackage pqueue\n\nimport (\n\t\"container\/heap\"\n\t\"errors\"\n\t\"sync\"\n)\n\n\/\/ Only items implementing this interface can be enqueued\n\/\/ on the priority queue.\ntype QueueItem interface {\n\tLess(other interface{}) bool\n\tId() interface{}\n}\n\n\/\/ Queue is a threadsafe priority queue exchange. Here's\n\/\/ a trivial example of usage:\n\/\/\n\/\/     q := pqueue.New(0)\n\/\/     go func() {\n\/\/         for {\n\/\/             task := q.Dequeue()\n\/\/             println(task.(*CustomTask).Name)\n\/\/         }\n\/\/     }()\n\/\/     for i := 0; i < 100; i := 1 {\n\/\/         task := CustomTask{Name: \"foo\", priority: rand.Intn(10)}\n\/\/         q.Enqueue(&task)\n\/\/     }\n\/\/\ntype Queue struct {\n\tLimit int\n\thistory map[interface{}]struct{}\n\titems *sorter\n\tcond  *sync.Cond\n}\n\n\/\/ New creates and initializes a new priority queue, taking\n\/\/ a limit as a parameter. If 0 given, then queue will be\n\/\/ unlimited. \nfunc New(max int) (q *Queue) {\n\tvar locker sync.Mutex\n\tq = &Queue{Limit: max}\n\tq.history = make(map[interface{}]struct{}, 0);\n\tq.items = new(sorter)\n\tq.cond = sync.NewCond(&locker)\n\theap.Init(q.items)\n\treturn\n}\n\n\/\/ Enqueue puts given item to the queue.\n\/\/ Lock the queue and calls enqueue()\nfunc (q *Queue) Enqueue(item QueueItem) (err error) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\treturn q.enqueue(item)\n}\n\n\/\/ Enqueue puts given item to the queue.\nfunc (q *Queue) enqueue(item QueueItem) (err error) {\n\tif q.Limit > 0 && q.Len() >= q.Limit {\n\t\treturn errors.New(\"Queue limit reached\")\n\t}\n\tq.history[item.Id()] = struct{}{};\n\theap.Push(q.items, item)\n\tq.cond.Signal()\n\treturn\n}\n\n\/\/ check if item already exists in queue (or it has been into queue)\nfunc (q *Queue) Exists(item QueueItem) bool {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\treturn q.exists(item)\n}\n\nfunc (q *Queue) exists(item QueueItem) bool {\n\tif _, ok := q.history[item.Id()]; ok {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\n\n\/\/ Enqueue puts item in queue only if it hasn't already been in queue\nfunc (q *Queue) EnqueueUnique(item QueueItem) (err error) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\tif !q.exists(item) {\n\t\tq.enqueue(item)\n\t}\n\treturn\n}\n\n\n\n\/\/ Dequeue takes an item from the queue. If queue is empty\n\/\/ then should block waiting for at least one item.\nfunc (q *Queue) Dequeue() (item QueueItem) {\n\tq.cond.L.Lock()\t\n\tdefer q.cond.L.Unlock()\n\tvar x interface{}\n\tfor {\n\t\tx = heap.Pop(q.items)\n\t\tif x == nil {\n\t\t\tq.cond.Wait()\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\titem = x.(QueueItem)\n\treturn\n}\n\n\/\/ Safely changes enqueued items limit. When limit is set\n\/\/ to 0, then queue is unlimited.\nfunc (q *Queue) ChangeLimit(newLimit int) {\n\tq.cond.L.Lock()\n\tdefer q.cond.L.Unlock()\n\tq.Limit = newLimit\n}\n\n\/\/ Len returns number of enqueued elemnents.\nfunc (q *Queue) Len() int {\n\treturn q.items.Len()\n}\n\n\/\/ IsEmpty returns true if queue is empty.\nfunc (q *Queue) IsEmpty() bool {\n\treturn q.Len() == 0\n}\n\ntype sorter []QueueItem\n\nfunc (s *sorter) Push(i interface{}) {\n\titem, ok := i.(QueueItem)\n\tif !ok {\n\t\treturn\n\t}\n\t*s = append((*s)[:], item)\n}\n\nfunc (s *sorter) Pop() (x interface{}) {\n\tif s.Len() > 0 {\n\t\tl := s.Len()-1\n\t\tx = (*s)[l]\n\t\t(*s)[l] = nil\n\t\t*s = (*s)[:l]\n\t}\n\treturn\n}\n\nfunc (s *sorter) Len() int {\n\treturn len((*s)[:])\n}\n\nfunc (s *sorter) Less(i, j int) bool {\n\treturn (*s)[i].Less((*s)[j])\n}\n\nfunc (s *sorter) Swap(i, j int) {\n\tif s.Len() > 0 {\n\t\t(*s)[i], (*s)[j] = (*s)[j], (*s)[i]\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013 Conformal Systems LLC.\n\/\/ Use of this source code is governed by an ISC\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/conformal\/btcwire\"\n\t\"github.com\/conformal\/go-flags\"\n\t\"net\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\nconst (\n\tdefaultConfigFilename = \"btcd.conf\"\n\tdefaultLogLevel       = \"info\"\n\tdefaultBtcnet         = btcwire.MainNet\n\tdefaultMaxPeers       = 8\n\tdefaultBanDuration    = time.Hour * 24\n\tdefaultVerifyEnabled  = false\n)\n\nvar (\n\tdefaultConfigFile = filepath.Join(btcdHomeDir(), defaultConfigFilename)\n\tdefaultDbDir      = filepath.Join(btcdHomeDir(), \"db\")\n)\n\n\/\/ config defines the configuration options for btcd.\n\/\/\n\/\/ See loadConfig for details on the configuration load process.\ntype config struct {\n\tDebugLevel     string        `short:\"d\" long:\"debuglevel\" description:\"Logging level {trace, debug, info, warn, error, critical}\"`\n\tAddPeers       []string      `short:\"a\" long:\"addpeer\" description:\"Add a peer to connect with at startup\"`\n\tConnectPeers   []string      `long:\"connect\" description:\"Connect only to the specified peers at startup\"`\n\tSeedPeer       string        `short:\"s\" long:\"seedpeer\" description:\"Retrieve peer addresses from this peer and then disconnect\"`\n\tPort           string        `short:\"p\" long:\"port\" description:\"Listen for connections on this port (default: 8333, testnet: 18333)\"`\n\tMaxPeers       int           `long:\"maxpeers\" description:\"Max number of inbound and outbound peers\"`\n\tBanDuration    time.Duration `long:\"banduration\" description:\"How long to ban misbehaving peers.  Valid time units are {s, m, h}.  Minimum 1 second\"`\n\tVerifyDisabled bool          `long:\"noverify\" description:\"Disable block\/transaction verification -- WARNING: This option can be dangerous and is for development use only\"`\n\tConfigFile     string        `short:\"C\" long:\"configfile\" description:\"Path to configuration file\"`\n\tDbDir          string        `short:\"b\" long:\"dbdir\" description:\"Directory to store database\"`\n\tRpcUser        string        `short:\"u\" long:\"rpcuser\" description:\"Username for rpc connections\"`\n\tRpcPass        string        `short:\"P\" long:\"rpcpass\" description:\"Password for rpc connections\"`\n\tRpcPort        string        `short:\"r\" long:\"rpcport\" description:\"Listen for json\/rpc messages on this port\"`\n\tDisableRpc     bool          `long:\"norpc\" description:\"Disable built-in RPC server -- NOTE: The RPC server is disabled by default if no rpcuser\/rpcpass is specified\"`\n\tDisableDNSSeed bool          `long:\"nodnsseed\" description:\"Disable DNS seeding for peers\"`\n\tTestNet3       bool          `long:\"testnet\" description:\"Use the test network\"`\n\tRegressionTest bool          `long:\"regtest\" description:\"Use the regression test network\"`\n}\n\n\/\/ btcdHomeDir returns an OS appropriate home directory for btcd.\nfunc btcdHomeDir() string {\n\t\/\/ Search for Windows APPDATA first.  This won't exist on POSIX OSes.\n\tappData := os.Getenv(\"APPDATA\")\n\tif appData != \"\" {\n\t\treturn filepath.Join(appData, \"btcd\")\n\t}\n\n\t\/\/ Fall back to standard HOME directory that works for most POSIX OSes.\n\thome := os.Getenv(\"HOME\")\n\tif home != \"\" {\n\t\treturn filepath.Join(home, \".btcd\")\n\t}\n\n\t\/\/ In the worst case, use the current directory.\n\treturn \".\"\n}\n\n\/\/ validLogLevel returns whether or not logLevel is a valid debug log level.\nfunc validLogLevel(logLevel string) bool {\n\tswitch logLevel {\n\tcase \"trace\":\n\t\tfallthrough\n\tcase \"debug\":\n\t\tfallthrough\n\tcase \"info\":\n\t\tfallthrough\n\tcase \"warn\":\n\t\tfallthrough\n\tcase \"error\":\n\t\tfallthrough\n\tcase \"critical\":\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ normalizePeerAddress returns addr with the default peer port appended if\n\/\/ there is not already a port specified.\nfunc normalizePeerAddress(addr string) string {\n\t_, _, err := net.SplitHostPort(addr)\n\tif err != nil {\n\t\treturn net.JoinHostPort(addr, activeNetParams.peerPort)\n\t}\n\treturn addr\n}\n\n\/\/ removeDuplicateAddresses returns a new slice with all duplicate entries in\n\/\/ addrs removed.\nfunc removeDuplicateAddresses(addrs []string) []string {\n\tresult := make([]string, 0)\n\tseen := map[string]bool{}\n\tfor _, val := range addrs {\n\t\tif _, ok := seen[val]; !ok {\n\t\t\tresult = append(result, val)\n\t\t\tseen[val] = true\n\t\t}\n\t}\n\treturn result\n}\n\nfunc normalizeAndRemoveDuplicateAddresses(addrs []string) []string {\n\tfor i, addr := range addrs {\n\t\taddrs[i] = normalizePeerAddress(addr)\n\t}\n\taddrs = removeDuplicateAddresses(addrs)\n\n\treturn addrs\n}\n\n\/\/ updateConfigWithActiveParams update the passed config with parameters\n\/\/ from the active net params if the relevant options in the passed config\n\/\/ object are the default so options specified by the user on the command line\n\/\/ are not overridden.\nfunc updateConfigWithActiveParams(cfg *config) {\n\tif cfg.Port == netParams(defaultBtcnet).listenPort {\n\t\tcfg.Port = activeNetParams.listenPort\n\t}\n\n\tif cfg.RpcPort == netParams(defaultBtcnet).rpcPort {\n\t\tcfg.RpcPort = activeNetParams.rpcPort\n\t}\n}\n\n\/\/ filesExists reports whether the named file or directory exists.\nfunc fileExists(name string) bool {\n\tif _, err := os.Stat(name); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ loadConfig initializes and parses the config using a config file and command\n\/\/ line options.\n\/\/\n\/\/ The configuration proceeds as follows:\n\/\/ \t1) Start with a default config with sane settings\n\/\/ \t2) Pre-parse the command line to check for an alternative config file\n\/\/ \t3) Load configuration file overwriting defaults with any specified options\n\/\/ \t4) Parse CLI options and overwrite\/add any specified options\n\/\/\n\/\/ The above results in btcd functioning properly without any config settings\n\/\/ while still allowing the user to override settings with config files and\n\/\/ command line options.  Command line options always take precedence.\nfunc loadConfig() (*config, []string, error) {\n\t\/\/ Default config.\n\tcfg := config{\n\t\tDebugLevel:  defaultLogLevel,\n\t\tPort:        netParams(defaultBtcnet).listenPort,\n\t\tRpcPort:     netParams(defaultBtcnet).rpcPort,\n\t\tMaxPeers:    defaultMaxPeers,\n\t\tBanDuration: defaultBanDuration,\n\t\tConfigFile:  defaultConfigFile,\n\t\tDbDir:       defaultDbDir,\n\t}\n\n\t\/\/ A config file in the current directory takes precedence.\n\tif fileExists(defaultConfigFilename) {\n\t\tcfg.ConfigFile = defaultConfigFilename\n\t}\n\n\t\/\/ Pre-parse the command line options to see if an alternative config\n\t\/\/ file was specified.\n\tpreCfg := cfg\n\tpreParser := flags.NewParser(&preCfg, flags.Default)\n\t_, err := preParser.Parse()\n\tif err != nil {\n\t\tif e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp {\n\t\t\tpreParser.WriteHelp(os.Stderr)\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Load additional config from file.\n\tparser := flags.NewParser(&cfg, flags.Default)\n\terr = parser.ParseIniFile(preCfg.ConfigFile)\n\tif err != nil {\n\t\tif _, ok := err.(*os.PathError); !ok {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tparser.WriteHelp(os.Stderr)\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tlog.Warnf(\"%v\", err)\n\t}\n\n\t\/\/ Parse command line options again to ensure they take precedence.\n\tremainingArgs, err := parser.Parse()\n\tif err != nil {\n\t\tif e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp {\n\t\t\tparser.WriteHelp(os.Stderr)\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ The two test networks can't be selected simultaneously.\n\tif cfg.TestNet3 && cfg.RegressionTest {\n\t\tstr := \"%s: The testnet and regtest params can't be used \" +\n\t\t\t\"together -- choose one of the two\"\n\t\terr := errors.New(fmt.Sprintf(str, \"loadConfig\"))\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tparser.WriteHelp(os.Stderr)\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Choose the active network params based on the testnet and regression\n\t\/\/ test net flags.\n\tif cfg.TestNet3 {\n\t\tactiveNetParams = netParams(btcwire.TestNet3)\n\t} else if cfg.RegressionTest {\n\t\tactiveNetParams = netParams(btcwire.TestNet)\n\t}\n\tupdateConfigWithActiveParams(&cfg)\n\n\t\/\/ Validate debug log level.\n\tif !validLogLevel(cfg.DebugLevel) {\n\t\tstr := \"%s: The specified debug level is invalid -- parsed [%v]\"\n\t\terr := errors.New(fmt.Sprintf(str, \"loadConfig\", cfg.DebugLevel))\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tparser.WriteHelp(os.Stderr)\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Don't allow ban durations that are too short.\n\tif cfg.BanDuration < time.Duration(time.Second) {\n\t\tstr := \"%s: The banduration option may not be less than 1s -- parsed [%v]\"\n\t\terr := errors.New(fmt.Sprintf(str, \"loadConfig\", cfg.BanDuration))\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tparser.WriteHelp(os.Stderr)\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ --addPeer and --connect do not mix.\n\tif len(cfg.AddPeers) > 0 && len(cfg.ConnectPeers) > 0 {\n\t\tstr := \"%s: the --addpeer and --connect options can not be \" +\n\t\t\t\"mixed\"\n\t\terr := errors.New(fmt.Sprintf(str, \"loadConfig\"))\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tparser.WriteHelp(os.Stderr)\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Connect means no seeding or listening.\n\tif len(cfg.ConnectPeers) > 0 {\n\t\tcfg.DisableDNSSeed = true\n\t\t\/\/ XXX turn off server listening.\n\t}\n\n\t\/\/ The RPC server is disabled if no username or password is provided.\n\tif cfg.RpcUser == \"\" || cfg.RpcPass == \"\" {\n\t\tcfg.DisableRpc = true\n\t}\n\n\t\/\/ Add default port to all added peer addresses if needed and remove\n\t\/\/ duplicate addresses.\n\tcfg.AddPeers = normalizeAndRemoveDuplicateAddresses(cfg.AddPeers)\n\tcfg.ConnectPeers =\n\t\tnormalizeAndRemoveDuplicateAddresses(cfg.ConnectPeers)\n\n\treturn &cfg, remainingArgs, nil\n}\n<commit_msg>Reorder some of the config options.<commit_after>\/\/ Copyright (c) 2013 Conformal Systems LLC.\n\/\/ Use of this source code is governed by an ISC\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/conformal\/btcwire\"\n\t\"github.com\/conformal\/go-flags\"\n\t\"net\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\nconst (\n\tdefaultConfigFilename = \"btcd.conf\"\n\tdefaultLogLevel       = \"info\"\n\tdefaultBtcnet         = btcwire.MainNet\n\tdefaultMaxPeers       = 8\n\tdefaultBanDuration    = time.Hour * 24\n\tdefaultVerifyEnabled  = false\n)\n\nvar (\n\tdefaultConfigFile = filepath.Join(btcdHomeDir(), defaultConfigFilename)\n\tdefaultDbDir      = filepath.Join(btcdHomeDir(), \"db\")\n)\n\n\/\/ config defines the configuration options for btcd.\n\/\/\n\/\/ See loadConfig for details on the configuration load process.\ntype config struct {\n\tConfigFile     string        `short:\"C\" long:\"configfile\" description:\"Path to configuration file\"`\n\tDbDir          string        `short:\"b\" long:\"dbdir\" description:\"Directory to store database\"`\n\tAddPeers       []string      `short:\"a\" long:\"addpeer\" description:\"Add a peer to connect with at startup\"`\n\tConnectPeers   []string      `long:\"connect\" description:\"Connect only to the specified peers at startup\"`\n\tSeedPeer       string        `short:\"s\" long:\"seedpeer\" description:\"Retrieve peer addresses from this peer and then disconnect\"`\n\tPort           string        `short:\"p\" long:\"port\" description:\"Listen for connections on this port (default: 8333, testnet: 18333)\"`\n\tMaxPeers       int           `long:\"maxpeers\" description:\"Max number of inbound and outbound peers\"`\n\tBanDuration    time.Duration `long:\"banduration\" description:\"How long to ban misbehaving peers.  Valid time units are {s, m, h}.  Minimum 1 second\"`\n\tVerifyDisabled bool          `long:\"noverify\" description:\"Disable block\/transaction verification -- WARNING: This option can be dangerous and is for development use only\"`\n\tRpcUser        string        `short:\"u\" long:\"rpcuser\" description:\"Username for rpc connections\"`\n\tRpcPass        string        `short:\"P\" long:\"rpcpass\" description:\"Password for rpc connections\"`\n\tRpcPort        string        `short:\"r\" long:\"rpcport\" description:\"Listen for json\/rpc messages on this port\"`\n\tDisableRpc     bool          `long:\"norpc\" description:\"Disable built-in RPC server -- NOTE: The RPC server is disabled by default if no rpcuser\/rpcpass is specified\"`\n\tDisableDNSSeed bool          `long:\"nodnsseed\" description:\"Disable DNS seeding for peers\"`\n\tTestNet3       bool          `long:\"testnet\" description:\"Use the test network\"`\n\tRegressionTest bool          `long:\"regtest\" description:\"Use the regression test network\"`\n\tDebugLevel     string        `short:\"d\" long:\"debuglevel\" description:\"Logging level {trace, debug, info, warn, error, critical}\"`\n}\n\n\/\/ btcdHomeDir returns an OS appropriate home directory for btcd.\nfunc btcdHomeDir() string {\n\t\/\/ Search for Windows APPDATA first.  This won't exist on POSIX OSes.\n\tappData := os.Getenv(\"APPDATA\")\n\tif appData != \"\" {\n\t\treturn filepath.Join(appData, \"btcd\")\n\t}\n\n\t\/\/ Fall back to standard HOME directory that works for most POSIX OSes.\n\thome := os.Getenv(\"HOME\")\n\tif home != \"\" {\n\t\treturn filepath.Join(home, \".btcd\")\n\t}\n\n\t\/\/ In the worst case, use the current directory.\n\treturn \".\"\n}\n\n\/\/ validLogLevel returns whether or not logLevel is a valid debug log level.\nfunc validLogLevel(logLevel string) bool {\n\tswitch logLevel {\n\tcase \"trace\":\n\t\tfallthrough\n\tcase \"debug\":\n\t\tfallthrough\n\tcase \"info\":\n\t\tfallthrough\n\tcase \"warn\":\n\t\tfallthrough\n\tcase \"error\":\n\t\tfallthrough\n\tcase \"critical\":\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ normalizePeerAddress returns addr with the default peer port appended if\n\/\/ there is not already a port specified.\nfunc normalizePeerAddress(addr string) string {\n\t_, _, err := net.SplitHostPort(addr)\n\tif err != nil {\n\t\treturn net.JoinHostPort(addr, activeNetParams.peerPort)\n\t}\n\treturn addr\n}\n\n\/\/ removeDuplicateAddresses returns a new slice with all duplicate entries in\n\/\/ addrs removed.\nfunc removeDuplicateAddresses(addrs []string) []string {\n\tresult := make([]string, 0)\n\tseen := map[string]bool{}\n\tfor _, val := range addrs {\n\t\tif _, ok := seen[val]; !ok {\n\t\t\tresult = append(result, val)\n\t\t\tseen[val] = true\n\t\t}\n\t}\n\treturn result\n}\n\nfunc normalizeAndRemoveDuplicateAddresses(addrs []string) []string {\n\tfor i, addr := range addrs {\n\t\taddrs[i] = normalizePeerAddress(addr)\n\t}\n\taddrs = removeDuplicateAddresses(addrs)\n\n\treturn addrs\n}\n\n\/\/ updateConfigWithActiveParams update the passed config with parameters\n\/\/ from the active net params if the relevant options in the passed config\n\/\/ object are the default so options specified by the user on the command line\n\/\/ are not overridden.\nfunc updateConfigWithActiveParams(cfg *config) {\n\tif cfg.Port == netParams(defaultBtcnet).listenPort {\n\t\tcfg.Port = activeNetParams.listenPort\n\t}\n\n\tif cfg.RpcPort == netParams(defaultBtcnet).rpcPort {\n\t\tcfg.RpcPort = activeNetParams.rpcPort\n\t}\n}\n\n\/\/ filesExists reports whether the named file or directory exists.\nfunc fileExists(name string) bool {\n\tif _, err := os.Stat(name); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ loadConfig initializes and parses the config using a config file and command\n\/\/ line options.\n\/\/\n\/\/ The configuration proceeds as follows:\n\/\/ \t1) Start with a default config with sane settings\n\/\/ \t2) Pre-parse the command line to check for an alternative config file\n\/\/ \t3) Load configuration file overwriting defaults with any specified options\n\/\/ \t4) Parse CLI options and overwrite\/add any specified options\n\/\/\n\/\/ The above results in btcd functioning properly without any config settings\n\/\/ while still allowing the user to override settings with config files and\n\/\/ command line options.  Command line options always take precedence.\nfunc loadConfig() (*config, []string, error) {\n\t\/\/ Default config.\n\tcfg := config{\n\t\tDebugLevel:  defaultLogLevel,\n\t\tPort:        netParams(defaultBtcnet).listenPort,\n\t\tRpcPort:     netParams(defaultBtcnet).rpcPort,\n\t\tMaxPeers:    defaultMaxPeers,\n\t\tBanDuration: defaultBanDuration,\n\t\tConfigFile:  defaultConfigFile,\n\t\tDbDir:       defaultDbDir,\n\t}\n\n\t\/\/ A config file in the current directory takes precedence.\n\tif fileExists(defaultConfigFilename) {\n\t\tcfg.ConfigFile = defaultConfigFilename\n\t}\n\n\t\/\/ Pre-parse the command line options to see if an alternative config\n\t\/\/ file was specified.\n\tpreCfg := cfg\n\tpreParser := flags.NewParser(&preCfg, flags.Default)\n\t_, err := preParser.Parse()\n\tif err != nil {\n\t\tif e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp {\n\t\t\tpreParser.WriteHelp(os.Stderr)\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Load additional config from file.\n\tparser := flags.NewParser(&cfg, flags.Default)\n\terr = parser.ParseIniFile(preCfg.ConfigFile)\n\tif err != nil {\n\t\tif _, ok := err.(*os.PathError); !ok {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tparser.WriteHelp(os.Stderr)\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tlog.Warnf(\"%v\", err)\n\t}\n\n\t\/\/ Parse command line options again to ensure they take precedence.\n\tremainingArgs, err := parser.Parse()\n\tif err != nil {\n\t\tif e, ok := err.(*flags.Error); !ok || e.Type != flags.ErrHelp {\n\t\t\tparser.WriteHelp(os.Stderr)\n\t\t}\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ The two test networks can't be selected simultaneously.\n\tif cfg.TestNet3 && cfg.RegressionTest {\n\t\tstr := \"%s: The testnet and regtest params can't be used \" +\n\t\t\t\"together -- choose one of the two\"\n\t\terr := errors.New(fmt.Sprintf(str, \"loadConfig\"))\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tparser.WriteHelp(os.Stderr)\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Choose the active network params based on the testnet and regression\n\t\/\/ test net flags.\n\tif cfg.TestNet3 {\n\t\tactiveNetParams = netParams(btcwire.TestNet3)\n\t} else if cfg.RegressionTest {\n\t\tactiveNetParams = netParams(btcwire.TestNet)\n\t}\n\tupdateConfigWithActiveParams(&cfg)\n\n\t\/\/ Validate debug log level.\n\tif !validLogLevel(cfg.DebugLevel) {\n\t\tstr := \"%s: The specified debug level is invalid -- parsed [%v]\"\n\t\terr := errors.New(fmt.Sprintf(str, \"loadConfig\", cfg.DebugLevel))\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tparser.WriteHelp(os.Stderr)\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Don't allow ban durations that are too short.\n\tif cfg.BanDuration < time.Duration(time.Second) {\n\t\tstr := \"%s: The banduration option may not be less than 1s -- parsed [%v]\"\n\t\terr := errors.New(fmt.Sprintf(str, \"loadConfig\", cfg.BanDuration))\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tparser.WriteHelp(os.Stderr)\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ --addPeer and --connect do not mix.\n\tif len(cfg.AddPeers) > 0 && len(cfg.ConnectPeers) > 0 {\n\t\tstr := \"%s: the --addpeer and --connect options can not be \" +\n\t\t\t\"mixed\"\n\t\terr := errors.New(fmt.Sprintf(str, \"loadConfig\"))\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tparser.WriteHelp(os.Stderr)\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Connect means no seeding or listening.\n\tif len(cfg.ConnectPeers) > 0 {\n\t\tcfg.DisableDNSSeed = true\n\t\t\/\/ XXX turn off server listening.\n\t}\n\n\t\/\/ The RPC server is disabled if no username or password is provided.\n\tif cfg.RpcUser == \"\" || cfg.RpcPass == \"\" {\n\t\tcfg.DisableRpc = true\n\t}\n\n\t\/\/ Add default port to all added peer addresses if needed and remove\n\t\/\/ duplicate addresses.\n\tcfg.AddPeers = normalizeAndRemoveDuplicateAddresses(cfg.AddPeers)\n\tcfg.ConnectPeers =\n\t\tnormalizeAndRemoveDuplicateAddresses(cfg.ConnectPeers)\n\n\treturn &cfg, remainingArgs, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * (C) Copyright 2013, Deft Labs\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at:\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage dlshared\n\nimport (\n\t\"os\"\n\t\"github.com\/daviddengcn\/go-ljson-conf\"\n)\n\ntype Configuration struct {\n\n\tVersion string\n\tPidFile string\n\n\tPid int\n\n\tdata *ljconf.Conf\n\n\tHostname string\n\tFileName string\n}\n\nfunc (self *Configuration) String(key string, def string) string {\n\treturn self.data.String(key, def)\n}\n\nfunc (self *Configuration) Int(key string, def int) int {\n\treturn self.data.Int(key, def)\n}\n\nfunc (self *Configuration) Bool(key string, def bool) bool {\n\treturn self.data.Bool(key, def)\n}\n\nfunc (self *Configuration) Float(key string, def float64) float64 {\n\treturn self.data.Float(key, def)\n}\n\nfunc (self *Configuration) StrList(key string, def [] string) []string {\n\treturn self.data.StringList(key, def)\n}\n\nfunc (self *Configuration) IntList(key string, def []int) []int {\n\treturn self.data.IntList(key, def)\n}\n\nfunc NewConfiguration(fileName string) (*Configuration, error) {\n\n\tconf := &Configuration{ FileName : fileName }\n\n\tvar err error\n\tif conf.data, err = ljconf.Load(fileName); err != nil {\n\t\treturn nil, err\n\t}\n\n\tconf.PidFile = conf.data.String(\"pidFile\", \"\")\n\n\tif len(conf.PidFile) == 0 {\n\t\treturn nil, NewStackError(\"Configuration file error - pidFile not set\")\n\t}\n\n\tconf.Version = conf.data.String(\"version\", \"@VERSION@\")\n\n\tconf.Pid = os.Getpid()\n\n\tconf.Hostname, err = os.Hostname()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(conf.Version) == 0 || conf.Version == \"@VERSION@\" {\n\t\treturn nil, NewStackError(\"Configuration file error - version not set\")\n\t}\n\n\treturn conf, nil\n}\n\n<commit_msg>added a required property - environment.<commit_after>\/**\n * (C) Copyright 2013, Deft Labs\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at:\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage dlshared\n\nimport (\n\t\"os\"\n\t\"github.com\/daviddengcn\/go-ljson-conf\"\n)\n\ntype Configuration struct {\n\n\tVersion string\n\tPidFile string\n\n\tPid int\n\n\tdata *ljconf.Conf\n\n\tEnvironment string\n\n\tHostname string\n\tFileName string\n}\n\nfunc (self *Configuration) String(key string, def string) string {\n\treturn self.data.String(key, def)\n}\n\nfunc (self *Configuration) Int(key string, def int) int {\n\treturn self.data.Int(key, def)\n}\n\nfunc (self *Configuration) Bool(key string, def bool) bool {\n\treturn self.data.Bool(key, def)\n}\n\nfunc (self *Configuration) Float(key string, def float64) float64 {\n\treturn self.data.Float(key, def)\n}\n\nfunc (self *Configuration) StrList(key string, def [] string) []string {\n\treturn self.data.StringList(key, def)\n}\n\nfunc (self *Configuration) IntList(key string, def []int) []int {\n\treturn self.data.IntList(key, def)\n}\n\nfunc NewConfiguration(fileName string) (*Configuration, error) {\n\n\tconf := &Configuration{ FileName : fileName }\n\n\tvar err error\n\tif conf.data, err = ljconf.Load(fileName); err != nil {\n\t\treturn nil, err\n\t}\n\n\tconf.PidFile = conf.data.String(\"pidFile\", \"\")\n\n\tif len(conf.PidFile) == 0 {\n\t\treturn nil, NewStackError(\"Configuration file error - pidFile not set\")\n\t}\n\n\tconf.Environment = conf.data.String(\"environment\", \"\")\n\n\tconf.Version = conf.data.String(\"version\", \"\")\n\n\tconf.Pid = os.Getpid()\n\n\tconf.Hostname, err = os.Hostname()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(conf.Version) == 0 {\n\t\treturn nil, NewStackError(\"Configuration file error - version not set\")\n\t}\n\n\tif len(conf.Environment) == 0 {\n\t\treturn nil, NewStackError(\"Configuration file error - environment not set\")\n\t}\n\n\treturn conf, nil\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package windows\n\nimport (\n  \"github.com\/mattn\/go-gtk\/gtk\"\n  \"ghighlighter\/models\"\n)\n\ntype GhMainWindow struct {\n  GtkWindow *gtk.GtkWindow\n}\n\nfunc (w *GhMainWindow) build() {\n  w.GtkWindow.Connect(\"destroy\", gtk.MainQuit)\n\n  w.GtkWindow.SetTitle(\"ghighlights\")\n  w.GtkWindow.Connect(\"destroy\", gtk.MainQuit)\n\n  mainVBox := gtk.VBox(false, 1)\n\n  scrolledTextViewWindow := gtk.ScrolledWindow(nil, nil)\n  scrolledTextViewWindow.SetPolicy(gtk.GTK_POLICY_AUTOMATIC, gtk.GTK_POLICY_AUTOMATIC)\n\n  textView := gtk.TextView()\n  textView.SetSizeRequest(600, 100)\n  scrolledTextViewWindow.Add(textView)\n\n  scrolledTextViewWindow.SetSizeRequest(600, 100)\n  mainVBox.Add(scrolledTextViewWindow)\n\n  readingHBox := gtk.HBox(false, 1)\n\n  readingsComboBox := gtk.ComboBoxText()\n  readings := models.Readings()\n  for _, reading := range readings.Items {\n    readingsComboBox.AppendText(reading.Title)\n  }\n  readingsComboBox.SetActive(0)\n  readingHBox.Add(readingsComboBox)\n\n  mainVBox.Add(readingHBox)\n\n  addHighlightButton := gtk.ButtonWithLabel(\"Add highlight\")\n  highlights := models.Highlights()\n  addHighlightButton.Clicked(func() {\n    readingId := readings.FindByTitle(readingsComboBox.GetActiveText()).ReadmillId\n\n    buffer := textView.GetBuffer()\n    var startIter, endIter gtk.GtkTextIter\n    buffer.GetStartIter(&startIter)\n    buffer.GetEndIter(&endIter)\n    content := buffer.GetText(&startIter, &endIter, true)\n\n    highlight := models.GhHighlight{content, readingId, 0}\n    highlights.Add(highlight)\n  })\n  mainVBox.Add(addHighlightButton)\n\n  w.GtkWindow.Add(mainVBox)\n  return\n}\n\nfunc MainWindow() *GhMainWindow {\n  mainWindow := &GhMainWindow{gtk.Window(gtk.GTK_WINDOW_TOPLEVEL)}\n  mainWindow.build()\n  return mainWindow\n}\n\n<commit_msg>Add menu bar to main window<commit_after>package windows\n\nimport (\n  \"fmt\"\n  \"github.com\/mattn\/go-gtk\/gtk\"\n  \"ghighlighter\/models\"\n)\n\ntype GhMainWindow struct {\n  GtkWindow *gtk.GtkWindow\n}\n\nfunc (w *GhMainWindow) build() {\n  w.GtkWindow.Connect(\"destroy\", gtk.MainQuit)\n\n  w.GtkWindow.SetTitle(\"ghighlights\")\n  w.GtkWindow.Connect(\"destroy\", gtk.MainQuit)\n\n  mainVBox := gtk.VBox(false, 1)\n\n  menubar := w.buildMenuBar()\n  mainVBox.PackStart(menubar, false, false, 0)\n\n  scrolledTextViewWindow := gtk.ScrolledWindow(nil, nil)\n  scrolledTextViewWindow.SetPolicy(gtk.GTK_POLICY_AUTOMATIC, gtk.GTK_POLICY_AUTOMATIC)\n\n  textView := gtk.TextView()\n  textView.SetSizeRequest(600, 100)\n  scrolledTextViewWindow.Add(textView)\n\n  scrolledTextViewWindow.SetSizeRequest(600, 100)\n  mainVBox.Add(scrolledTextViewWindow)\n\n  readingHBox := gtk.HBox(false, 1)\n\n  readingsComboBox := gtk.ComboBoxText()\n  readings := models.Readings()\n  for _, reading := range readings.Items {\n    readingsComboBox.AppendText(reading.Title)\n  }\n  readingsComboBox.SetActive(0)\n  readingHBox.Add(readingsComboBox)\n\n  mainVBox.Add(readingHBox)\n\n  addHighlightButton := gtk.ButtonWithLabel(\"Add highlight\")\n  highlights := models.Highlights()\n  addHighlightButton.Clicked(func() {\n    readingId := readings.FindByTitle(readingsComboBox.GetActiveText()).ReadmillId\n\n    buffer := textView.GetBuffer()\n    var startIter, endIter gtk.GtkTextIter\n    buffer.GetStartIter(&startIter)\n    buffer.GetEndIter(&endIter)\n    content := buffer.GetText(&startIter, &endIter, true)\n\n    highlight := models.GhHighlight{content, readingId, 0}\n    highlights.Add(highlight)\n  })\n  mainVBox.Add(addHighlightButton)\n\n  w.GtkWindow.Add(mainVBox)\n  return\n}\n\nfunc (w *GhMainWindow) buildMenuBar() *gtk.GtkMenuBar {\n  menubar := gtk.MenuBar()\n\n  fileMenuItem := gtk.MenuItemWithMnemonic(\"_File\")\n  menubar.Append(fileMenuItem)\n\n  fileMenu := gtk.Menu()\n  fileMenuItem.SetSubmenu(fileMenu)\n\n  quitMenuItem := gtk.MenuItemWithMnemonic(\"_Quit\")\n  quitMenuItem.Connect(\"activate\", func() {\n    gtk.MainQuit()\n  })\n  fileMenu.Append(quitMenuItem)\n\n  viewMenuItem := gtk.MenuItemWithMnemonic(\"_View\")\n  menubar.Append(viewMenuItem)\n\n  viewMenu := gtk.Menu()\n  viewMenuItem.SetSubmenu(viewMenu)\n\n  queuedHighlightsMenuItem := gtk.MenuItemWithMnemonic(\"Queued _Highlights\")\n  queuedHighlightsMenuItem.Connect(\"activate\", func() {\n    fmt.Println(\"Open queued highlights window\")\n  })\n  viewMenu.Append(queuedHighlightsMenuItem)\n\n  helpMenuItem := gtk.MenuItemWithMnemonic(\"_Help\")\n  menubar.Append(helpMenuItem)\n\n  helpMenu := gtk.Menu()\n  helpMenuItem.SetSubmenu(helpMenu)\n\n  aboutMenuItem := gtk.MenuItemWithMnemonic(\"About\")\n  aboutMenuItem.Connect(\"activate\", func() {\n    fmt.Println(\"Show about dialog\")\n  })\n  helpMenu.Append(aboutMenuItem)\n\n  return menubar\n}\n\nfunc MainWindow() *GhMainWindow {\n  mainWindow := &GhMainWindow{gtk.Window(gtk.GTK_WINDOW_TOPLEVEL)}\n  mainWindow.build()\n  return mainWindow\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 The Cloud Robotics Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n\n\tpb \"github.com\/googlecloudrobotics\/core\/src\/proto\/http-relay\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\nvar (\n\tbrokerRequests = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tName: \"broker_requests\",\n\t\t\tHelp: \"Number of requests to the broker\",\n\t\t},\n\t\t[]string{\"method\"},\n\t)\n\tbrokerResponses = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tName: \"broker_responses\",\n\t\t\tHelp: \"Number of responses from the broker\",\n\t\t},\n\t\t[]string{\"method\", \"result\"},\n\t)\n\tbrokerResponseDurations = prometheus.NewHistogramVec(\n\t\tprometheus.HistogramOpts{\n\t\t\tName: \"broker_responses_durations\",\n\t\t\tHelp: \"Time from request to final response in ms\",\n\t\t},\n\t\t[]string{\"method\"},\n\t)\n)\n\nfunc init() {\n\tprometheus.MustRegister(brokerRequests)\n\tprometheus.MustRegister(brokerResponses)\n\tprometheus.MustRegister(brokerResponseDurations)\n}\n\ntype pendingResponse struct {\n\trequestStream  chan []byte\n\tresponseStream chan *pb.HttpResponse\n\tlastActivity   time.Time\n\t\/\/ For diagnostics only.\n\tstartTime time.Time\n\tserver    string\n}\n\n\/\/ broker implements a thread-safe map for the request and response queues.\n\/\/ Requests (req) are mapped by server-name. There is only channel per relay-\n\/\/ client (identified by the server query parameter)\n\/\/ Responses (resp) are mapped by stream id (randomly generated hex string).\n\/\/ There can be multiple concurrent transfers per relay-client, each identified\n\/\/ by a unique id query parameter.\ntype broker struct {\n\tm    sync.Mutex\n\treq  map[string]chan *pb.HttpRequest\n\tresp map[string]*pendingResponse\n}\n\nfunc newBroker() *broker {\n\tvar r broker\n\tr.req = make(map[string]chan *pb.HttpRequest)\n\tr.resp = make(map[string]*pendingResponse)\n\treturn &r\n}\n\n\/\/ RelayRequest matches a pending relay client's request to the encapsulated\n\/\/ request and returns a channel for the results.\nfunc (r *broker) RelayRequest(server string, request *pb.HttpRequest) (<-chan *pb.HttpResponse, error) {\n\tid := *request.Id\n\n\tr.m.Lock()\n\tif r.req[server] == nil {\n\t\t\/\/ This happens when the relay-client connects for the first time.\n\t\tr.req[server] = make(chan *pb.HttpRequest)\n\t}\n\tif r.resp[id] != nil {\n\t\treturn nil, fmt.Errorf(\"Multiple clients trying to handle request ID %s on server %s\", id, server)\n\t}\n\tts := time.Now()\n\tr.resp[id] = &pendingResponse{\n\t\trequestStream:  make(chan []byte),\n\t\tresponseStream: make(chan *pb.HttpResponse),\n\t\tlastActivity:   ts,\n\t\tstartTime:      ts,\n\t\tserver:         server,\n\t}\n\treqChan := r.req[server]\n\trespChan := r.resp[id].responseStream\n\tr.m.Unlock()\n\n\tlog.Printf(\"Enqueuing request %s for %s\", id, server)\n\tbrokerRequests.WithLabelValues(\"client\").Inc()\n\tselect {\n\tcase reqChan <- request:\n\t\treturn respChan, nil\n\tcase <-time.After(10 * time.Second):\n\t\treturn nil, fmt.Errorf(\"Timeout waiting for relay client to accept request for %s\", server)\n\t}\n}\n\n\/\/ GetRequest obtains a client's request for the server identifier. It blocks\n\/\/ until a client makes a request.\nfunc (r *broker) GetRequest(server string) (*pb.HttpRequest, error) {\n\tr.m.Lock()\n\tif r.req[server] == nil {\n\t\t\/\/ This happens when the relay-server started and a client connects before\n\t\t\/\/ the relay-client connected.\n\t\tr.req[server] = make(chan *pb.HttpRequest)\n\t}\n\treqChan := r.req[server]\n\tr.m.Unlock()\n\n\tbrokerRequests.WithLabelValues(\"server_request\").Inc()\n\tselect {\n\tcase req := <-reqChan:\n\t\tbrokerResponses.WithLabelValues(\"server_request\", \"ok\").Inc()\n\t\treturn req, nil\n\tcase <-time.After(time.Second * 30):\n\t\tbrokerResponses.WithLabelValues(\"server_request\", \"timeout\").Inc()\n\t\treturn nil, fmt.Errorf(\"No request received within timeout\")\n\t}\n}\n\n\/\/ GetRequestStream gets data from the stream that follows a client's HTTP\n\/\/ request. For example, when using `kubectl exec` this passes stdin data from\n\/\/ the broker to the relay client.\n\/\/ If no ongoing request matches the given ID, this returns ok=false.\nfunc (r *broker) GetRequestStream(id string) ([]byte, bool) {\n\tr.m.Lock()\n\tpr := r.resp[id]\n\tr.m.Unlock()\n\tif pr == nil {\n\t\treturn nil, false\n\t}\n\n\tselect {\n\tcase req := <-pr.requestStream:\n\t\treturn req, true\n\tcase <-time.After(time.Second * 30):\n\t\treturn []byte{}, true\n\t}\n}\n\n\/\/ PutsRequestStream adds data from the stream that follows a client's HTTP\n\/\/ request. For example, when using `kubectl exec` this passes stdin data from\n\/\/ kubectl to the broker.\n\/\/ If no ongoing request matches the given ID, this returns ok=false.\nfunc (r *broker) PutRequestStream(id string, data []byte) bool {\n\tr.m.Lock()\n\tpr := r.resp[id]\n\tr.m.Unlock()\n\tif pr == nil {\n\t\treturn false\n\t}\n\n\tpr.requestStream <- data\n\treturn true\n}\n\n\/\/ SendResponse delivers the HttpResponse to the client handler that created the\n\/\/ request. It fails if and only if the request ID is not recognized.\nfunc (r *broker) SendResponse(resp *pb.HttpResponse) error {\n\tid := *resp.Id\n\tr.m.Lock()\n\tpr := r.resp[id]\n\tif pr == nil {\n\t\tr.m.Unlock()\n\t\tbrokerResponses.WithLabelValues(\"server_response\", \"invalid\").Inc()\n\t\treturn fmt.Errorf(\"Duplicate or invalid request ID %s\", id)\n\t}\n\tif resp.GetEof() {\n\t\tdelete(r.resp, id)\n\t} else {\n\t\tpr.lastActivity = time.Now()\n\t}\n\tduration := time.Since(pr.startTime).Seconds()\n\tpr.responseStream <- resp\n\tr.m.Unlock()\n\tbrokerRequests.WithLabelValues(\"server_response\").Inc()\n\tbrokerResponseDurations.WithLabelValues(\"server_response\").Observe(duration)\n\tlog.Printf(\"Delivered response %s for server %s to client, elapsed %.3fs\", id, pr.server, duration)\n\tif resp.GetEof() {\n\t\tclose(pr.responseStream)\n\t}\n\tbrokerResponses.WithLabelValues(\"server_response\", \"ok\").Inc()\n\treturn nil\n}\n\nfunc (r *broker) ReapInactiveRequests(threshold time.Time) {\n\tr.m.Lock()\n\tfor key, value := range r.resp {\n\t\tif value.lastActivity.Before(threshold) {\n\t\t\tlog.Printf(\"Timeout on inactive request %s\", key)\n\t\t\tdefer close(value.requestStream)\n\t\t\tdefer close(value.responseStream)\n\t\t\t\/\/ Amazingly, this is safe in Go: https:\/\/stackoverflow.com\/questions\/23229975\/is-it-safe-to-remove-selected-keys-from-map-within-a-range-loop\n\t\t\tdelete(r.resp, key)\n\t\t}\n\t}\n\tr.m.Unlock()\n}\n<commit_msg>Use a more actionable error for timeouts<commit_after>\/\/ Copyright 2019 The Cloud Robotics Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n\n\tpb \"github.com\/googlecloudrobotics\/core\/src\/proto\/http-relay\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\nvar (\n\tbrokerRequests = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tName: \"broker_requests\",\n\t\t\tHelp: \"Number of requests to the broker\",\n\t\t},\n\t\t[]string{\"method\"},\n\t)\n\tbrokerResponses = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tName: \"broker_responses\",\n\t\t\tHelp: \"Number of responses from the broker\",\n\t\t},\n\t\t[]string{\"method\", \"result\"},\n\t)\n\tbrokerResponseDurations = prometheus.NewHistogramVec(\n\t\tprometheus.HistogramOpts{\n\t\t\tName: \"broker_responses_durations\",\n\t\t\tHelp: \"Time from request to final response in ms\",\n\t\t},\n\t\t[]string{\"method\"},\n\t)\n)\n\nfunc init() {\n\tprometheus.MustRegister(brokerRequests)\n\tprometheus.MustRegister(brokerResponses)\n\tprometheus.MustRegister(brokerResponseDurations)\n}\n\ntype pendingResponse struct {\n\trequestStream  chan []byte\n\tresponseStream chan *pb.HttpResponse\n\tlastActivity   time.Time\n\t\/\/ For diagnostics only.\n\tstartTime time.Time\n\tserver    string\n}\n\n\/\/ broker implements a thread-safe map for the request and response queues.\n\/\/ Requests (req) are mapped by server-name. There is only channel per relay-\n\/\/ client (identified by the server query parameter)\n\/\/ Responses (resp) are mapped by stream id (randomly generated hex string).\n\/\/ There can be multiple concurrent transfers per relay-client, each identified\n\/\/ by a unique id query parameter.\ntype broker struct {\n\tm    sync.Mutex\n\treq  map[string]chan *pb.HttpRequest\n\tresp map[string]*pendingResponse\n}\n\nfunc newBroker() *broker {\n\tvar r broker\n\tr.req = make(map[string]chan *pb.HttpRequest)\n\tr.resp = make(map[string]*pendingResponse)\n\treturn &r\n}\n\n\/\/ RelayRequest matches a pending relay client's request to the encapsulated\n\/\/ request and returns a channel for the results.\nfunc (r *broker) RelayRequest(server string, request *pb.HttpRequest) (<-chan *pb.HttpResponse, error) {\n\tid := *request.Id\n\n\tr.m.Lock()\n\tif r.req[server] == nil {\n\t\t\/\/ This happens when the relay-client connects for the first time.\n\t\tr.req[server] = make(chan *pb.HttpRequest)\n\t}\n\tif r.resp[id] != nil {\n\t\treturn nil, fmt.Errorf(\"Multiple clients trying to handle request ID %s on server %s\", id, server)\n\t}\n\tts := time.Now()\n\tr.resp[id] = &pendingResponse{\n\t\trequestStream:  make(chan []byte),\n\t\tresponseStream: make(chan *pb.HttpResponse),\n\t\tlastActivity:   ts,\n\t\tstartTime:      ts,\n\t\tserver:         server,\n\t}\n\treqChan := r.req[server]\n\trespChan := r.resp[id].responseStream\n\tr.m.Unlock()\n\n\tlog.Printf(\"Enqueuing request %s for %s\", id, server)\n\tbrokerRequests.WithLabelValues(\"client\").Inc()\n\tselect {\n\tcase reqChan <- request:\n\t\treturn respChan, nil\n\tcase <-time.After(10 * time.Second):\n\t\treturn nil, fmt.Errorf(\"%q doesn't appear to be running the relay client. Check that it's turned on, set up, and connected to the internet. (timeout waiting for relay client to accept request)\", server)\n\t}\n}\n\n\/\/ GetRequest obtains a client's request for the server identifier. It blocks\n\/\/ until a client makes a request.\nfunc (r *broker) GetRequest(server string) (*pb.HttpRequest, error) {\n\tr.m.Lock()\n\tif r.req[server] == nil {\n\t\t\/\/ This happens when the relay-server started and a client connects before\n\t\t\/\/ the relay-client connected.\n\t\tr.req[server] = make(chan *pb.HttpRequest)\n\t}\n\treqChan := r.req[server]\n\tr.m.Unlock()\n\n\tbrokerRequests.WithLabelValues(\"server_request\").Inc()\n\tselect {\n\tcase req := <-reqChan:\n\t\tbrokerResponses.WithLabelValues(\"server_request\", \"ok\").Inc()\n\t\treturn req, nil\n\tcase <-time.After(time.Second * 30):\n\t\tbrokerResponses.WithLabelValues(\"server_request\", \"timeout\").Inc()\n\t\treturn nil, fmt.Errorf(\"No request received within timeout\")\n\t}\n}\n\n\/\/ GetRequestStream gets data from the stream that follows a client's HTTP\n\/\/ request. For example, when using `kubectl exec` this passes stdin data from\n\/\/ the broker to the relay client.\n\/\/ If no ongoing request matches the given ID, this returns ok=false.\nfunc (r *broker) GetRequestStream(id string) ([]byte, bool) {\n\tr.m.Lock()\n\tpr := r.resp[id]\n\tr.m.Unlock()\n\tif pr == nil {\n\t\treturn nil, false\n\t}\n\n\tselect {\n\tcase req := <-pr.requestStream:\n\t\treturn req, true\n\tcase <-time.After(time.Second * 30):\n\t\treturn []byte{}, true\n\t}\n}\n\n\/\/ PutsRequestStream adds data from the stream that follows a client's HTTP\n\/\/ request. For example, when using `kubectl exec` this passes stdin data from\n\/\/ kubectl to the broker.\n\/\/ If no ongoing request matches the given ID, this returns ok=false.\nfunc (r *broker) PutRequestStream(id string, data []byte) bool {\n\tr.m.Lock()\n\tpr := r.resp[id]\n\tr.m.Unlock()\n\tif pr == nil {\n\t\treturn false\n\t}\n\n\tpr.requestStream <- data\n\treturn true\n}\n\n\/\/ SendResponse delivers the HttpResponse to the client handler that created the\n\/\/ request. It fails if and only if the request ID is not recognized.\nfunc (r *broker) SendResponse(resp *pb.HttpResponse) error {\n\tid := *resp.Id\n\tr.m.Lock()\n\tpr := r.resp[id]\n\tif pr == nil {\n\t\tr.m.Unlock()\n\t\tbrokerResponses.WithLabelValues(\"server_response\", \"invalid\").Inc()\n\t\treturn fmt.Errorf(\"Duplicate or invalid request ID %s\", id)\n\t}\n\tif resp.GetEof() {\n\t\tdelete(r.resp, id)\n\t} else {\n\t\tpr.lastActivity = time.Now()\n\t}\n\tduration := time.Since(pr.startTime).Seconds()\n\tpr.responseStream <- resp\n\tr.m.Unlock()\n\tbrokerRequests.WithLabelValues(\"server_response\").Inc()\n\tbrokerResponseDurations.WithLabelValues(\"server_response\").Observe(duration)\n\tlog.Printf(\"Delivered response %s for server %s to client, elapsed %.3fs\", id, pr.server, duration)\n\tif resp.GetEof() {\n\t\tclose(pr.responseStream)\n\t}\n\tbrokerResponses.WithLabelValues(\"server_response\", \"ok\").Inc()\n\treturn nil\n}\n\nfunc (r *broker) ReapInactiveRequests(threshold time.Time) {\n\tr.m.Lock()\n\tfor key, value := range r.resp {\n\t\tif value.lastActivity.Before(threshold) {\n\t\t\tlog.Printf(\"Timeout on inactive request %s\", key)\n\t\t\tdefer close(value.requestStream)\n\t\t\tdefer close(value.responseStream)\n\t\t\t\/\/ Amazingly, this is safe in Go: https:\/\/stackoverflow.com\/questions\/23229975\/is-it-safe-to-remove-selected-keys-from-map-within-a-range-loop\n\t\t\tdelete(r.resp, key)\n\t\t}\n\t}\n\tr.m.Unlock()\n}\n<|endoftext|>"}
{"text":"<commit_before>package wingedGrid\n\nimport (\n    \"errors\"\n    \/\/\"fmt\"\n    \"math\"\n)\n\/\/ This file contains functions for testing the expected data structure of\n\/\/ any wingedGrid\n\n\/\/ Returns whether the edge order from the vertex index matches that of the edges\n\/\/ NOT YET IMPLEMENTED\nfunc VertEdgesMatchEdgeOrder(theGrid WingedGrid, vertIndex int32) (bool, error) {\n    \n    return false, nil\n}\n\/\/ Returns whether the edge has its vertices ordered correctly, \n\/\/ such that FirstVertexA it the first vertex encounter when clockwise traversing\n\/\/ FaceA\nfunc EdgeVertsInCorrectOrientation(theGrid WingedGrid, edgeIndex int32) (bool, error){\n    var theEdge WingedEdge = theGrid.Edges[edgeIndex]\n    var nextEdge WingedEdge = theGrid.Edges[theEdge.NextA]\n    \/\/ Second clockwise vertex on theEdge should be the same as the first for \n    \/\/ nextEdgeA for faceA, only need to test for one pair.\n    \/\/ Check with second vertex for next edge incase the next edge is the wrong one\n    if theEdge.FirstVertexB == nextEdge.FirstVertexA ||\n       theEdge.FirstVertexB == nextEdge.FirstVertexB {\n        return true, nil\n    }\n    return false, errors.New(\"This Edge has wrong order\")\n}\n\/\/ Returns whether the edge order from the face index matches that of the edges\n\/\/ taken from edge.next\nfunc FaceEdgesMatchesOrderFromEdge(theGrid WingedGrid, faceIndex int32) (bool, error) {\n    var theFace WingedFace = theGrid.Faces[faceIndex]\n    if len(theFace.Edges) <= 2 {\n        return false, errors.New(\"Face has too few edges.\")\n    }\n    var currentEdge WingedEdge\n    currentEdge = theGrid.Edges[theFace.Edges[len(theFace.Edges) - 1]]\n    for i := 0; i < len(theFace.Edges); i++ {\n        next, err := currentEdge.NextEdgeForFace(faceIndex)\n        if err != nil {\n            return false, err\n        }\n        if next == theFace.Edges[i] {\n            currentEdge = theGrid.Edges[next]\n        } else {\n            return false, nil\n        }\n    }\n    return true, nil\n}\n\/\/ Returns whether a the vertices of a face are within square tolerance distance\n\/\/ from the plane of the first three vertices\n\/\/ NOT FULLY IMPLEMENTED\nfunc FaceVerticesPlanar(theGrid WingedGrid, faceIndex int32, tolerance float64) (bool) {\n    var theFace WingedFace\n    theFace = theGrid.Faces[faceIndex]\n    \/\/ always true for three or fewer points\n    if len(theFace.Edges) <= 3 {\n        return true\n    }\n    \n    return false\n}\n\/\/ Returns whether a face has an orientation in the same direction as the\n\/\/ position of its center, within the square tolerance.\n\/\/ This test is only applicable to WingedGrids that are expected to aproximate a \n\/\/ sphere.\nfunc FaceOrientation(theGrid WingedGrid, faceIndex int32, tolerance float64) (bool, error) {\n    var err error\n    var theFace WingedFace = theGrid.Faces[faceIndex]\n    \/\/ find center of face\n    var vectorP, vectorQ, faceCenter [3]float64\n    var count float64\n    for _, edgeIndex := range theFace.Edges {\n        var vertex WingedVertex\n        var vertexIndex int32\n        vertexIndex, err = theGrid.Edges[edgeIndex].FirstVertexForFace(faceIndex)\n        if err != nil {\n            return false, nil\n        }\n        vertex = theGrid.Vertices[vertexIndex]\n        faceCenter[0] = faceCenter[0] + vertex.Coords[0]\n        faceCenter[1] = faceCenter[1] + vertex.Coords[1]\n        faceCenter[2] = faceCenter[2] + vertex.Coords[2]\n        count = count + 1\n    }\n    faceCenter[0] = faceCenter[0] \/ count\n    faceCenter[1] = faceCenter[1] \/ count\n    faceCenter[1] = faceCenter[1] \/ count\n    \n    \/\/ simply use the first two edges, vectors away from their shared vertex\n    \/\/ from these we get the face normal vector\n    var edgeP, edgeQ WingedEdge\n    edgeP = theGrid.Edges[theFace.Edges[0]]\n    edgeQ = theGrid.Edges[theFace.Edges[1]]\n    \n    \/\/ get and check we find valid vertices\n    var startVertexIndex, endVertexIndex int32\n    endVertexIndex, err = edgeP.FirstVertexForFace(faceIndex)\n    if err != nil {\n        return false, err\n    }\n    startVertexIndex, err = edgeP.SecondVertexForFace(faceIndex)\n    if err != nil {\n        return false, err\n    }\n    \/\/ get vector along edge P\n    vectorP[0] = theGrid.Vertices[endVertexIndex].Coords[0] -\n                    theGrid.Vertices[startVertexIndex].Coords[0]\n    vectorP[1] = theGrid.Vertices[endVertexIndex].Coords[1] -\n                    theGrid.Vertices[startVertexIndex].Coords[1]\n    vectorP[2] = theGrid.Vertices[endVertexIndex].Coords[2] -\n                    theGrid.Vertices[startVertexIndex].Coords[2]\n    \n    \/\/ get and check we find valid vertices\n    endVertexIndex, err = edgeQ.SecondVertexForFace(faceIndex)\n    if err != nil {\n        return false, err\n    }\n    startVertexIndex, err = edgeQ.FirstVertexForFace(faceIndex)\n    if err != nil {\n        return false, err\n    }                        \n    \/\/ get vector along edge Q\n    vectorQ[0] = theGrid.Vertices[endVertexIndex].Coords[0] -\n                    theGrid.Vertices[startVertexIndex].Coords[0]\n    vectorQ[1] = theGrid.Vertices[endVertexIndex].Coords[1] -\n                    theGrid.Vertices[startVertexIndex].Coords[1]\n    vectorQ[2] = theGrid.Vertices[endVertexIndex].Coords[2] -\n                    theGrid.Vertices[startVertexIndex].Coords[2]\n    \n    \/\/ replace with cross product at some point, copying here from original\n    \/\/ icosahedron test where I simply subtracted normalized components\n    var scaleFactor float64\n    \/\/ normalize the center to unit vector\n    scaleFactor = 1\/math.Sqrt(faceCenter[0]*faceCenter[0] + \n                              faceCenter[1]*faceCenter[1] +\n                              faceCenter[2]*faceCenter[2])\n    faceCenter[0] = faceCenter[0] * scaleFactor\n    faceCenter[1] = faceCenter[1] * scaleFactor\n    faceCenter[2] = faceCenter[2] * scaleFactor\n    \n    \/\/ find normal to face, cross product!\n    var faceNormal [3]float64\n    faceNormal[0] = vectorP[1]*vectorQ[2] - vectorP[2]*vectorQ[1]\n    faceNormal[1] = -(vectorP[0]*vectorQ[2] - vectorP[2]*vectorQ[0])\n    faceNormal[2] = vectorP[0]*vectorQ[1] - vectorP[1]*vectorQ[0]\n    \/\/ normalize it!\n    scaleFactor = 1\/math.Sqrt(faceNormal[0]*faceNormal[0] + \n                              faceNormal[1]*faceNormal[1] +\n                              faceNormal[2]*faceNormal[2])\n    faceNormal[0] = faceNormal[0] * scaleFactor\n    faceNormal[1] = faceNormal[1] * scaleFactor\n    faceNormal[2] = faceNormal[2] * scaleFactor\n    \n    \/\/ they should be parallel (not antiparrallel!)\n    \/\/  ie, components should subract to zero, since unit vectors\n    if !((faceNormal[0] - faceCenter[0])*(faceNormal[0] - faceCenter[0])>tolerance ||\n         (faceNormal[1] - faceCenter[1])*(faceNormal[1] - faceCenter[1])>tolerance ||\n         (faceNormal[2] - faceCenter[2])*(faceNormal[2] - faceCenter[2])>tolerance   ) {\n         \n        return false, nil\n    }\n    return true, nil\n}<commit_msg>fix test logic so it actually does something<commit_after>package wingedGrid\n\nimport (\n    \"errors\"\n    \/\/\"fmt\"\n    \"math\"\n    \"log\"\n)\n\/\/ This file contains functions for testing the expected data structure of\n\/\/ any wingedGrid\n\n\/\/ Returns whether the edge order from the vertex index matches that of the edges\n\/\/ NOT YET IMPLEMENTED\nfunc VertEdgesMatchEdgeOrder(theGrid WingedGrid, vertIndex int32) (bool, error) {\n    \n    return false, nil\n}\n\/\/ Returns whether the edge has its vertices ordered correctly, \n\/\/ such that FirstVertexA it the first vertex encounter when clockwise traversing\n\/\/ FaceA\nfunc EdgeVertsInCorrectOrientation(theGrid WingedGrid, edgeIndex int32) (bool, error){\n    var theEdge WingedEdge = theGrid.Edges[edgeIndex]\n    var nextEdge WingedEdge = theGrid.Edges[theEdge.NextA]\n    \/\/ Second clockwise vertex on theEdge should be the same as the first for \n    \/\/ nextEdgeA for faceA, only need to test for one pair.\n    \/\/ Check with second vertex for next edge incase the next edge is the wrong one\n    if theEdge.FirstVertexB == nextEdge.FirstVertexA ||\n       theEdge.FirstVertexB == nextEdge.FirstVertexB {\n        return true, nil\n    }\n    return false, errors.New(\"This Edge has wrong order\")\n}\n\/\/ Returns whether the edge order from the face index matches that of the edges\n\/\/ taken from edge.next\nfunc FaceEdgesMatchesOrderFromEdge(theGrid WingedGrid, faceIndex int32) (bool, error) {\n    var theFace WingedFace = theGrid.Faces[faceIndex]\n    if len(theFace.Edges) <= 2 {\n        return false, errors.New(\"Face has too few edges.\")\n    }\n    var currentEdge WingedEdge\n    currentEdge = theGrid.Edges[theFace.Edges[len(theFace.Edges) - 1]]\n    for i := 0; i < len(theFace.Edges); i++ {\n        next, err := currentEdge.NextEdgeForFace(faceIndex)\n        if err != nil {\n            return false, err\n        }\n        if next == theFace.Edges[i] {\n            currentEdge = theGrid.Edges[next]\n        } else {\n            return false, nil\n        }\n    }\n    return true, nil\n}\n\/\/ Returns whether a the vertices of a face are within square tolerance distance\n\/\/ from the plane of the first three vertices\n\/\/ NOT FULLY IMPLEMENTED\nfunc FaceVerticesPlanar(theGrid WingedGrid, faceIndex int32, tolerance float64) (bool) {\n    var theFace WingedFace\n    theFace = theGrid.Faces[faceIndex]\n    \/\/ always true for three or fewer points\n    if len(theFace.Edges) <= 3 {\n        return true\n    }\n    \n    return false\n}\n\/\/ Returns whether a face has an orientation in the same direction as the\n\/\/ position of its center, within the square tolerance.\n\/\/ This test is only applicable to WingedGrids that are expected to aproximate a \n\/\/ sphere.\nfunc FaceOrientation(theGrid WingedGrid, faceIndex int32, tolerance float64) (bool, error) {\n    var err error\n    var theFace WingedFace = theGrid.Faces[faceIndex]\n    \/\/ find center of face\n    var vectorP, vectorQ, faceCenter [3]float64\n    var count float64\n    for _, edgeIndex := range theFace.Edges {\n        var vertex WingedVertex\n        var vertexIndex int32\n        vertexIndex, err = theGrid.Edges[edgeIndex].FirstVertexForFace(faceIndex)\n        if err != nil {\n            return false, nil\n        }\n        vertex = theGrid.Vertices[vertexIndex]\n        faceCenter[0] = faceCenter[0] + vertex.Coords[0]\n        faceCenter[1] = faceCenter[1] + vertex.Coords[1]\n        faceCenter[2] = faceCenter[2] + vertex.Coords[2]\n        count = count + 1\n    }\n    faceCenter[0] = faceCenter[0] \/ count\n    faceCenter[1] = faceCenter[1] \/ count\n    faceCenter[2] = faceCenter[2] \/ count\n    \n    \/\/ simply use the first two edges, vectors away from their shared vertex\n    \/\/ from these we get the face normal vector\n    var edgeP, edgeQ WingedEdge\n    edgeP = theGrid.Edges[theFace.Edges[0]]\n    edgeQ = theGrid.Edges[theFace.Edges[1]]\n    \n    \/\/ get and check we find valid vertices\n    var startVertexIndex, endVertexIndex int32\n    endVertexIndex, err = edgeP.FirstVertexForFace(faceIndex)\n    if err != nil {\n        return false, err\n    }\n    startVertexIndex, err = edgeP.SecondVertexForFace(faceIndex)\n    if err != nil {\n        return false, err\n    }\n    \/\/ get vector along edge P\n    vectorP[0] = theGrid.Vertices[endVertexIndex].Coords[0] -\n                    theGrid.Vertices[startVertexIndex].Coords[0]\n    vectorP[1] = theGrid.Vertices[endVertexIndex].Coords[1] -\n                    theGrid.Vertices[startVertexIndex].Coords[1]\n    vectorP[2] = theGrid.Vertices[endVertexIndex].Coords[2] -\n                    theGrid.Vertices[startVertexIndex].Coords[2]\n    \n    \/\/ get and check we find valid vertices\n    endVertexIndex, err = edgeQ.SecondVertexForFace(faceIndex)\n    if err != nil {\n        return false, err\n    }\n    startVertexIndex, err = edgeQ.FirstVertexForFace(faceIndex)\n    if err != nil {\n        return false, err\n    }                        \n    \/\/ get vector along edge Q\n    vectorQ[0] = theGrid.Vertices[endVertexIndex].Coords[0] -\n                    theGrid.Vertices[startVertexIndex].Coords[0]\n    vectorQ[1] = theGrid.Vertices[endVertexIndex].Coords[1] -\n                    theGrid.Vertices[startVertexIndex].Coords[1]\n    vectorQ[2] = theGrid.Vertices[endVertexIndex].Coords[2] -\n                    theGrid.Vertices[startVertexIndex].Coords[2]\n    \n    \/\/ replace with cross product at some point, copying here from original\n    \/\/ icosahedron test where I simply subtracted normalized components\n    var scaleFactor float64\n    \/\/ normalize the center to unit vector\n    scaleFactor = 1\/math.Sqrt(faceCenter[0]*faceCenter[0] + \n                              faceCenter[1]*faceCenter[1] +\n                              faceCenter[2]*faceCenter[2])\n    faceCenter[0] = faceCenter[0] * scaleFactor\n    faceCenter[1] = faceCenter[1] * scaleFactor\n    faceCenter[2] = faceCenter[2] * scaleFactor\n    \n    \/\/ find normal to face, cross product!\n    var faceNormal [3]float64\n    faceNormal[0] = vectorP[1]*vectorQ[2] - vectorP[2]*vectorQ[1]\n    faceNormal[1] = -(vectorP[0]*vectorQ[2] - vectorP[2]*vectorQ[0])\n    faceNormal[2] = vectorP[0]*vectorQ[1] - vectorP[1]*vectorQ[0]\n    \/\/ normalize it!\n    scaleFactor = 1\/math.Sqrt(faceNormal[0]*faceNormal[0] + \n                              faceNormal[1]*faceNormal[1] +\n                              faceNormal[2]*faceNormal[2])\n    faceNormal[0] = faceNormal[0] * scaleFactor\n    faceNormal[1] = faceNormal[1] * scaleFactor\n    faceNormal[2] = faceNormal[2] * scaleFactor\n    log.Printf(\"Center: %v Normal: %v\",faceCenter,faceNormal)\n    \/\/ they should be parallel (not antiparrallel!)\n    \/\/  ie, components should subract to zero, since unit vectors\n    if ( (faceNormal[0] - faceCenter[0])*(faceNormal[0] - faceCenter[0])>tolerance ||\n         (faceNormal[1] - faceCenter[1])*(faceNormal[1] - faceCenter[1])>tolerance ||\n         (faceNormal[2] - faceCenter[2])*(faceNormal[2] - faceCenter[2])>tolerance   ) {\n         \n        return false, nil\n    }\n    return true, nil\n}<|endoftext|>"}
{"text":"<commit_before>package mocks\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/konjoot\/reeky\/errors\"\n)\n\ntype ResourceMock struct {\n\tF        interface{}\n\tV        interface{}\n\tInvalid  bool\n\tNotFound bool\n\n\tcreated  bool\n\tfindedBy string\n}\n\nfunc (r *ResourceMock) Created() bool {\n\treturn r.created\n}\n\nfunc (r *ResourceMock) BindedWith(f interface{}) (binded bool) {\n\tvar (\n\t\tname string\n\t\tval  interface{}\n\t)\n\n\tif _, ok := f.(map[string]string); !ok {\n\t\treturn\n\t}\n\n\trForm := reflect.ValueOf(r.F).Elem()\n\n\tfor name, val = range f.(map[string]string) {\n\t\tif field := rForm.FieldByName(name); field.IsValid() && field.Interface() == val {\n\t\t\tcontinue\n\t\t}\n\t\treturn\n\t}\n\n\treturn true\n}\n\nfunc (r *ResourceMock) String() string {\n\treturn fmt.Sprintf(\"ResourceMock{Invalid: %t, created: %t, findedBy: %#v, Form: %#v, View: %#v}\", r.Invalid, r.created, r.findedBy, r.F, r.V)\n}\n\nfunc (r *ResourceMock) Url() string {\n\treturn \"some\/url\"\n}\n\nfunc (r *ResourceMock) Form() interface{} {\n\treturn r.F\n}\n\nfunc (r *ResourceMock) Save() (e error) {\n\tif r.Invalid {\n\t\te = errors.NewConflictError()\n\t\treturn\n\t}\n\n\tr.created = true\n\n\treturn\n}\n\nfunc (r *ResourceMock) FindedBy() string {\n\treturn r.findedBy\n}\n\nfunc (r *ResourceMock) Finded() bool {\n\treturn r.findedBy != \"\"\n}\n<commit_msg>now ResourceMock implements Finder and Viewer interfaces<commit_after>package mocks\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/konjoot\/reeky\/errors\"\n\n\ti \"github.com\/konjoot\/reeky\/interfaces\"\n)\n\ntype ResourceMock struct {\n\tF        interface{}\n\tV        interface{}\n\tInvalid  bool\n\tNotFound bool\n\n\tcreated  bool\n\tfindedBy string\n}\n\nfunc (r *ResourceMock) Created() bool {\n\treturn r.created\n}\n\nfunc (r *ResourceMock) BindedWith(f interface{}) (binded bool) {\n\tvar (\n\t\tname string\n\t\tval  interface{}\n\t)\n\n\tif _, ok := f.(map[string]string); !ok {\n\t\treturn\n\t}\n\n\trForm := reflect.ValueOf(r.F).Elem()\n\n\tfor name, val = range f.(map[string]string) {\n\t\tif field := rForm.FieldByName(name); field.IsValid() && field.Interface() == val {\n\t\t\tcontinue\n\t\t}\n\t\treturn\n\t}\n\n\treturn true\n}\n\nfunc (r *ResourceMock) String() string {\n\treturn fmt.Sprintf(\"ResourceMock{Invalid: %t, created: %t, findedBy: %#v, Form: %#v, View: %#v}\", r.Invalid, r.created, r.findedBy, r.F, r.V)\n}\n\nfunc (r *ResourceMock) Url() string {\n\treturn \"some\/url\"\n}\n\nfunc (r *ResourceMock) Form() interface{} {\n\treturn r.F\n}\n\nfunc (r *ResourceMock) Save() (e error) {\n\tif r.Invalid {\n\t\te = errors.NewConflictError()\n\t\treturn\n\t}\n\n\tr.created = true\n\n\treturn\n}\n\nfunc (r *ResourceMock) FindedBy() string {\n\treturn r.findedBy\n}\n\nfunc (r *ResourceMock) Finded() bool {\n\treturn r.findedBy != \"\"\n}\n\nfunc (r *ResourceMock) Find(id string) (i.Viewer, error) {\n\tr.findedBy = id\n\treturn r, nil\n}\n\nfunc (r *ResourceMock) View() interface{} {\n\treturn r.V\n}\n<|endoftext|>"}
{"text":"<commit_before>package server\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/context\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/intervention-engine\/fhir\/models\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\nfunc ObservationIndexHandler(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tvar result []models.Observation\n\tc := Database.C(\"observations\")\n\titer := c.Find(nil).Limit(100).Iter()\n\terr := iter.All(&result)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tvar observationEntryList []models.ObservationBundleEntry\n\tfor _, observation := range result {\n\t\tvar entry models.ObservationBundleEntry\n\t\tentry.Title = \"Observation \" + observation.Id\n\t\tentry.Id = observation.Id\n\t\tentry.Content = observation\n\t\tobservationEntryList = append(observationEntryList, entry)\n\t}\n\n\tvar bundle models.ObservationBundle\n\tbundle.Type = \"Bundle\"\n\tbundle.Title = \"Observation Index\"\n\tbundle.Id = bson.NewObjectId().Hex()\n\tbundle.Updated = time.Now()\n\tbundle.TotalResults = len(result)\n\tbundle.Entry = observationEntryList\n\n\tlog.Println(\"Setting observation search context\")\n\tcontext.Set(r, \"Observation\", result)\n\tcontext.Set(r, \"Resource\", \"Observation\")\n\tcontext.Set(r, \"Action\", \"search\")\n\n\trw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\trw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tjson.NewEncoder(rw).Encode(bundle)\n}\n\nfunc LoadObservation(r *http.Request) (*models.Observation, error) {\n\tvar id bson.ObjectId\n\n\tidString := mux.Vars(r)[\"id\"]\n\tif bson.IsObjectIdHex(idString) {\n\t\tid = bson.ObjectIdHex(idString)\n\t} else {\n\t\treturn nil, errors.New(\"Invalid id\")\n\t}\n\n\tc := Database.C(\"observations\")\n\tresult := models.Observation{}\n\terr := c.Find(bson.M{\"_id\": id.Hex()}).One(&result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Println(\"Setting observation read context\")\n\tcontext.Set(r, \"Observation\", result)\n\tcontext.Set(r, \"Resource\", \"Observation\")\n\treturn &result, nil\n}\n\nfunc ObservationShowHandler(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tcontext.Set(r, \"Action\", \"read\")\n\t_, err := LoadObservation(r)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\trw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\trw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tjson.NewEncoder(rw).Encode(context.Get(r, \"Observation\"))\n}\n\nfunc ObservationCreateHandler(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tdecoder := json.NewDecoder(r.Body)\n\tobservation := &models.Observation{}\n\terr := decoder.Decode(observation)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tc := Database.C(\"observations\")\n\ti := bson.NewObjectId()\n\tobservation.Id = i.Hex()\n\terr = c.Insert(observation)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tlog.Println(\"Setting observation create context\")\n\tcontext.Set(r, \"Observation\", observation)\n\tcontext.Set(r, \"Resource\", \"Observation\")\n\tcontext.Set(r, \"Action\", \"create\")\n\n\thost, err := os.Hostname()\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\n\trw.Header().Add(\"Location\", \"http:\/\/\"+host+\":3001\/Observation\/\"+i.Hex())\n}\n\nfunc ObservationUpdateHandler(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\n\tvar id bson.ObjectId\n\n\tidString := mux.Vars(r)[\"id\"]\n\tif bson.IsObjectIdHex(idString) {\n\t\tid = bson.ObjectIdHex(idString)\n\t} else {\n\t\thttp.Error(rw, \"Invalid id\", http.StatusBadRequest)\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tobservation := &models.Observation{}\n\terr := decoder.Decode(observation)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tc := Database.C(\"observations\")\n\tobservation.Id = id.Hex()\n\terr = c.Update(bson.M{\"_id\": id.Hex()}, observation)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tlog.Println(\"Setting observation update context\")\n\tcontext.Set(r, \"Observation\", observation)\n\tcontext.Set(r, \"Resource\", \"Observation\")\n\tcontext.Set(r, \"Action\", \"update\")\n}\n\nfunc ObservationDeleteHandler(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tvar id bson.ObjectId\n\n\tidString := mux.Vars(r)[\"id\"]\n\tif bson.IsObjectIdHex(idString) {\n\t\tid = bson.ObjectIdHex(idString)\n\t} else {\n\t\thttp.Error(rw, \"Invalid id\", http.StatusBadRequest)\n\t}\n\n\tc := Database.C(\"observations\")\n\n\terr := c.Remove(bson.M{\"_id\": id.Hex()})\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tlog.Println(\"Setting observation delete context\")\n\tcontext.Set(r, \"Observation\", id.Hex())\n\tcontext.Set(r, \"Resource\", \"Observation\")\n\tcontext.Set(r, \"Action\", \"delete\")\n}\n<commit_msg>initial implementation of search for Observations<commit_after>package server\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\t\"strings\"\n\n\t\"github.com\/gorilla\/context\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/intervention-engine\/fhir\/models\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\nfunc ObservationIndexHandler(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tvar result []models.Observation\n\tc := Database.C(\"observations\")\n\n\tr.ParseForm()\n\tif (len(r.Form) == 0) {\n\t\titer := c.Find(nil).Limit(100).Iter()\n\t\terr := iter.All(&result)\n\t\tif err != nil {\n\t\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t} else {\n\t\tfor key, value := range r.Form {\n\t\t\tsplitKey := strings.Split(key, \":\")\n\t\t\tif (len(splitKey) > 1) && (splitKey[0] == \"subject\") {\n\t\t\t\tsubjectType := splitKey[1]\n\t\t\t\t\/\/TODO:figure out what hostname to use here depending on whether reference is internal or external\n\t\t\t\treferenceString := \"http:\/\/localhost:3001\/\"+subjectType+\"\/\"+value[0]\n\t\t\t\terr := c.Find(bson.M{\"subject.reference\": referenceString}).All(&result)\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar observationEntryList []models.ObservationBundleEntry\n\tfor _, observation := range result {\n\t\tvar entry models.ObservationBundleEntry\n\t\tentry.Title = \"Observation \" + observation.Id\n\t\tentry.Id = observation.Id\n\t\tentry.Content = observation\n\t\tobservationEntryList = append(observationEntryList, entry)\n\t}\n\n\tvar bundle models.ObservationBundle\n\tbundle.Type = \"Bundle\"\n\tbundle.Title = \"Observation Index\"\n\tbundle.Id = bson.NewObjectId().Hex()\n\tbundle.Updated = time.Now()\n\tbundle.TotalResults = len(result)\n\tbundle.Entry = observationEntryList\n\n\tlog.Println(\"Setting observation search context\")\n\tcontext.Set(r, \"Observation\", result)\n\tcontext.Set(r, \"Resource\", \"Observation\")\n\tcontext.Set(r, \"Action\", \"search\")\n\n\trw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\trw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tjson.NewEncoder(rw).Encode(bundle)\n}\n\nfunc LoadObservation(r *http.Request) (*models.Observation, error) {\n\tvar id bson.ObjectId\n\n\tidString := mux.Vars(r)[\"id\"]\n\tif bson.IsObjectIdHex(idString) {\n\t\tid = bson.ObjectIdHex(idString)\n\t} else {\n\t\treturn nil, errors.New(\"Invalid id\")\n\t}\n\n\tc := Database.C(\"observations\")\n\tresult := models.Observation{}\n\terr := c.Find(bson.M{\"_id\": id.Hex()}).One(&result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Println(\"Setting observation read context\")\n\tcontext.Set(r, \"Observation\", result)\n\tcontext.Set(r, \"Resource\", \"Observation\")\n\treturn &result, nil\n}\n\nfunc ObservationShowHandler(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tcontext.Set(r, \"Action\", \"read\")\n\t_, err := LoadObservation(r)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\trw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\trw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tjson.NewEncoder(rw).Encode(context.Get(r, \"Observation\"))\n}\n\nfunc ObservationCreateHandler(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tdecoder := json.NewDecoder(r.Body)\n\tobservation := &models.Observation{}\n\terr := decoder.Decode(observation)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tc := Database.C(\"observations\")\n\ti := bson.NewObjectId()\n\tobservation.Id = i.Hex()\n\terr = c.Insert(observation)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tlog.Println(\"Setting observation create context\")\n\tcontext.Set(r, \"Observation\", observation)\n\tcontext.Set(r, \"Resource\", \"Observation\")\n\tcontext.Set(r, \"Action\", \"create\")\n\n\thost, err := os.Hostname()\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\n\trw.Header().Add(\"Location\", \"http:\/\/\"+host+\":3001\/Observation\/\"+i.Hex())\n}\n\nfunc ObservationUpdateHandler(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\n\tvar id bson.ObjectId\n\n\tidString := mux.Vars(r)[\"id\"]\n\tif bson.IsObjectIdHex(idString) {\n\t\tid = bson.ObjectIdHex(idString)\n\t} else {\n\t\thttp.Error(rw, \"Invalid id\", http.StatusBadRequest)\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tobservation := &models.Observation{}\n\terr := decoder.Decode(observation)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tc := Database.C(\"observations\")\n\tobservation.Id = id.Hex()\n\terr = c.Update(bson.M{\"_id\": id.Hex()}, observation)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tlog.Println(\"Setting observation update context\")\n\tcontext.Set(r, \"Observation\", observation)\n\tcontext.Set(r, \"Resource\", \"Observation\")\n\tcontext.Set(r, \"Action\", \"update\")\n}\n\nfunc ObservationDeleteHandler(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tvar id bson.ObjectId\n\n\tidString := mux.Vars(r)[\"id\"]\n\tif bson.IsObjectIdHex(idString) {\n\t\tid = bson.ObjectIdHex(idString)\n\t} else {\n\t\thttp.Error(rw, \"Invalid id\", http.StatusBadRequest)\n\t}\n\n\tc := Database.C(\"observations\")\n\n\terr := c.Remove(bson.M{\"_id\": id.Hex()})\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tlog.Println(\"Setting observation delete context\")\n\tcontext.Set(r, \"Observation\", id.Hex())\n\tcontext.Set(r, \"Resource\", \"Observation\")\n\tcontext.Set(r, \"Action\", \"delete\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package consul\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/42wim\/registrator-work\/bridge\"\n\tconsulapi \"github.com\/hashicorp\/consul\/api\"\n)\n\nconst DefaultInterval = \"10s\"\n\nfunc init() {\n\tbridge.Register(new(Factory), \"consul\")\n}\n\nfunc (r *ConsulAdapter) interpolateService(script string, service *bridge.Service) string {\n\twithIp := strings.Replace(script, \"$SERVICE_IP\", service.Origin.HostIP, -1)\n\twithPort := strings.Replace(withIp, \"$SERVICE_PORT\", service.Origin.HostPort, -1)\n\treturn withPort\n}\n\ntype Factory struct{}\n\nfunc (f *Factory) New(uri *url.URL) bridge.RegistryAdapter {\n\tconfig := consulapi.DefaultConfig()\n\tif uri.Host != \"\" {\n\t\tconfig.Address = uri.Host\n\t}\n\tclient, err := consulapi.NewClient(config)\n\tif err != nil {\n\t\tlog.Fatal(\"consul: \", uri.Scheme)\n\t}\n\treturn &ConsulAdapter{client: client}\n}\n\ntype ConsulAdapter struct {\n\tclient *consulapi.Client\n}\n\n\/\/ Ping will try to connect to consul by attempting to retrieve the current leader.\nfunc (r *ConsulAdapter) Ping() error {\n\tstatus := r.client.Status()\n\tleader, err := status.Leader()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"consul: current leader \", leader)\n\n\treturn nil\n}\n\nfunc (r *ConsulAdapter) Register(service *bridge.Service) error {\n\tregistration := new(consulapi.AgentServiceRegistration)\n\tregistration.ID = service.ID\n\tregistration.Name = service.Name\n\tregistration.Port = service.Port\n\tregistration.Tags = service.Tags\n\tregistration.Address = service.IP\n\tregistration.Check = r.buildCheck(service)\n\treturn r.client.Agent().ServiceRegister(registration)\n}\n\nfunc (r *ConsulAdapter) buildCheck(service *bridge.Service) *consulapi.AgentServiceCheck {\n\tcheck := new(consulapi.AgentServiceCheck)\n\tif path := service.Attrs[\"check_http\"]; path != \"\" {\n\t\tif net.ParseIP(service.IP).To4() == nil && service.IP[0] != '[' { \/\/ verify if its an ipv6 address\n\t\t\tservice.IP = fmt.Sprintf(\"[%s]\", service.IP)\n\t\t}\n\t\tcheck.HTTP = fmt.Sprintf(\"http:\/\/%s:%d%s\", service.IP, service.Port, path)\n\t\tif timeout := service.Attrs[\"check_timeout\"]; timeout != \"\" {\n\t\t\tcheck.Timeout = timeout\n\t\t}\n\t} else if cmd := service.Attrs[\"check_cmd\"]; cmd != \"\" {\n\t\tcheck.Script = fmt.Sprintf(\"check-cmd %s %s %s\", service.Origin.ContainerID[:12], service.Origin.ExposedPort, cmd)\n\t} else if script := service.Attrs[\"check_script\"]; script != \"\" {\n\t\tcheck.Script = r.interpolateService(script, service)\n\t} else if ttl := service.Attrs[\"check_ttl\"]; ttl != \"\" {\n\t\tcheck.TTL = ttl\n\t} else {\n\t\treturn nil\n\t}\n\tif check.Script != \"\" || check.HTTP != \"\" {\n\t\tif interval := service.Attrs[\"check_interval\"]; interval != \"\" {\n\t\t\tcheck.Interval = interval\n\t\t} else {\n\t\t\tcheck.Interval = DefaultInterval\n\t\t}\n\t}\n\treturn check\n}\n\nfunc (r *ConsulAdapter) Deregister(service *bridge.Service) error {\n\treturn r.client.Agent().ServiceDeregister(service.ID)\n}\n\nfunc (r *ConsulAdapter) Refresh(service *bridge.Service) error {\n\treturn nil\n}\n\nfunc (r *ConsulAdapter) Services() ([]*bridge.Service, error) {\n\tservices, err := r.client.Agent().Services()\n\tif err != nil {\n\t\treturn []*bridge.Service{}, err\n\t}\n\tout := make([]*bridge.Service, len(services))\n\ti := 0\n\tfor _, v := range services {\n\t\ts := &bridge.Service{\n\t\t\tID:   v.ID,\n\t\t\tName: v.Service,\n\t\t\tPort: v.Port,\n\t\t\tTags: v.Tags,\n\t\t\tIP:   v.Address,\n\t\t}\n\t\tout[i] = s\n\t\ti++\n\t}\n\treturn out, nil\n}\n<commit_msg>Fix service.IP overwrite with http_check<commit_after>package consul\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/42wim\/registrator-work\/bridge\"\n\tconsulapi \"github.com\/hashicorp\/consul\/api\"\n)\n\nconst DefaultInterval = \"10s\"\n\nfunc init() {\n\tbridge.Register(new(Factory), \"consul\")\n}\n\nfunc (r *ConsulAdapter) interpolateService(script string, service *bridge.Service) string {\n\twithIp := strings.Replace(script, \"$SERVICE_IP\", service.Origin.HostIP, -1)\n\twithPort := strings.Replace(withIp, \"$SERVICE_PORT\", service.Origin.HostPort, -1)\n\treturn withPort\n}\n\ntype Factory struct{}\n\nfunc (f *Factory) New(uri *url.URL) bridge.RegistryAdapter {\n\tconfig := consulapi.DefaultConfig()\n\tif uri.Host != \"\" {\n\t\tconfig.Address = uri.Host\n\t}\n\tclient, err := consulapi.NewClient(config)\n\tif err != nil {\n\t\tlog.Fatal(\"consul: \", uri.Scheme)\n\t}\n\treturn &ConsulAdapter{client: client}\n}\n\ntype ConsulAdapter struct {\n\tclient *consulapi.Client\n}\n\n\/\/ Ping will try to connect to consul by attempting to retrieve the current leader.\nfunc (r *ConsulAdapter) Ping() error {\n\tstatus := r.client.Status()\n\tleader, err := status.Leader()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"consul: current leader \", leader)\n\n\treturn nil\n}\n\nfunc (r *ConsulAdapter) Register(service *bridge.Service) error {\n\tregistration := new(consulapi.AgentServiceRegistration)\n\tregistration.ID = service.ID\n\tregistration.Name = service.Name\n\tregistration.Port = service.Port\n\tregistration.Tags = service.Tags\n\tregistration.Address = service.IP\n\tregistration.Check = r.buildCheck(service)\n\treturn r.client.Agent().ServiceRegister(registration)\n}\n\nfunc (r *ConsulAdapter) buildCheck(service *bridge.Service) *consulapi.AgentServiceCheck {\n\tcheck := new(consulapi.AgentServiceCheck)\n\tif path := service.Attrs[\"check_http\"]; path != \"\" {\n\t\tif net.ParseIP(service.IP).To4() == nil { \/\/ verify if its an ipv6 address\n\t\t\tcheck.HTTP = fmt.Sprintf(\"http:\/\/%s:%d%s\", fmt.Sprintf(\"[%s]\", service.IP), service.Port, path)\n\t\t}\n\t\tif timeout := service.Attrs[\"check_timeout\"]; timeout != \"\" {\n\t\t\tcheck.Timeout = timeout\n\t\t}\n\t} else if cmd := service.Attrs[\"check_cmd\"]; cmd != \"\" {\n\t\tcheck.Script = fmt.Sprintf(\"check-cmd %s %s %s\", service.Origin.ContainerID[:12], service.Origin.ExposedPort, cmd)\n\t} else if script := service.Attrs[\"check_script\"]; script != \"\" {\n\t\tcheck.Script = r.interpolateService(script, service)\n\t} else if ttl := service.Attrs[\"check_ttl\"]; ttl != \"\" {\n\t\tcheck.TTL = ttl\n\t} else {\n\t\treturn nil\n\t}\n\tif check.Script != \"\" || check.HTTP != \"\" {\n\t\tif interval := service.Attrs[\"check_interval\"]; interval != \"\" {\n\t\t\tcheck.Interval = interval\n\t\t} else {\n\t\t\tcheck.Interval = DefaultInterval\n\t\t}\n\t}\n\treturn check\n}\n\nfunc (r *ConsulAdapter) Deregister(service *bridge.Service) error {\n\treturn r.client.Agent().ServiceDeregister(service.ID)\n}\n\nfunc (r *ConsulAdapter) Refresh(service *bridge.Service) error {\n\treturn nil\n}\n\nfunc (r *ConsulAdapter) Services() ([]*bridge.Service, error) {\n\tservices, err := r.client.Agent().Services()\n\tif err != nil {\n\t\treturn []*bridge.Service{}, err\n\t}\n\tout := make([]*bridge.Service, len(services))\n\ti := 0\n\tfor _, v := range services {\n\t\ts := &bridge.Service{\n\t\t\tID:   v.ID,\n\t\t\tName: v.Service,\n\t\t\tPort: v.Port,\n\t\t\tTags: v.Tags,\n\t\t\tIP:   v.Address,\n\t\t}\n\t\tout[i] = s\n\t\ti++\n\t}\n\treturn out, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package node\n\nimport (\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com\/MG-RAST\/Shock\/shock-server\/cache\"\n\t\"github.com\/MG-RAST\/Shock\/shock-server\/conf\"\n\t\"github.com\/MG-RAST\/Shock\/shock-server\/logger\"\n\t\"github.com\/MG-RAST\/Shock\/shock-server\/node\/locker\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\nvar (\n\tTtl         *NodeReaper\n\tExpireRegex = regexp.MustCompile(`^(\\d+)(M|H|D)$`)\n)\n\nfunc InitReaper() {\n\tTtl = NewNodeReaper()\n}\n\ntype NodeReaper struct{}\n\nfunc NewNodeReaper() *NodeReaper {\n\treturn &NodeReaper{}\n}\n\nfunc (nr *NodeReaper) Handle() {\n\twaitDuration := time.Duration(conf.EXPIRE_WAIT) * time.Minute\nMainLoop:\n\tfor {\n\n\t\t\/\/ sleep\n\t\ttime.Sleep(waitDuration)\n\t\t\/\/ query to get expired nodes\n\t\tnodes := Nodes{}\n\t\tquery := nr.getQuery()\n\t\tnodes.GetAll(query)\n\n\tNodeLoop:\n\t\t\/\/ loop thru all nodes\n\t\tfor _, n := range nodes {\n\t\t\tlogger.Infof(\"Deleting expired node: %s\", n.Id)\n\t\t\t\/\/ delete expired nodes\n\t\t\tif err := n.Delete(); err != nil {\n\t\t\t\terr_msg := \"err:@node_delete: \" + err.Error()\n\t\t\t\tlogger.Error(err_msg)\n\t\t\t}\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\n\t\t\t\/\/ write info for node migration\n\t\t\tlogger.Debug(1, \"writing info for node migration: %s\", n.Id)\n\t\t\t\/\/ CODE MISSING HERE FOR WRITING FILES WITH INFO FOR MIGRATION\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/\tfor this node check all locations to check if node Data files can be erased\n\t\t\tfor _, loc := range n.Locations {\n\t\t\t\tvar counter int = 0 \/\/ we need at least N locations before we can erase data files on local disk\n\n\t\t\t\t\/\/ delete only if other locations exist\n\t\t\t\tlocObj, ok := conf.LocationsMap[loc.ID]\n\n\t\t\t\tif !ok {\n\t\t\t\t\tlogger.Errorf(\"(Reaper-->FileReaper) location %s is not defined in this server instance \\n \", loc)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t\/\/fmt.Printf(\"(Reaper-->FileReaper) locObj.Persistent =  %b  \\n \", locObj.Persistent)\n\t\t\t\tif locObj.Persistent == true {\n\t\t\t\t\tlogger.Debug(2, \"(Reaper-->FileReaper) has remote Location (%s) removing from Data: %s\", loc.ID, n.Id)\n\t\t\t\t\tcounter++ \/\/ increment counter\n\t\t\t\t}\n\t\t\t\tif counter >= conf.MIN_REPLICA_COUNT {\n\t\t\t\t\terr := n.DeleteFiles() \/\/ delete all data files for node in PATH_DATA NOTE: this is different from PATH_CACHE\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogger.Errorf(\"(Reaper-->FileReaper) files for node %s could not be deleted (Err: %s) \", n.Id, err.Error())\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tcontinue NodeLoop\n\t\t\t\t\t\/\/ the innermost loop\n\t\t\t\t}\n\t\t\t\t\/\/\/\n\n\t\t\t}\n\t\t\t\/\/ garbage collection: remove old nodes from Lockers, value is hours old\n\t\t\tlocker.NodeLockMgr.RemoveOld(1)\n\t\t\tlocker.FileLockMgr.RemoveOld(6)\n\t\t\tlocker.IndexLockMgr.RemoveOld(6)\n\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\n\t\t\t\/\/ we do not start deletings files if we are not in cache mode\n\t\t\t\/\/ we might want to change this, if we are in shock-migrate or we do not have a cache_path we skip this\n\t\t\tif conf.PATH_CACHE == \"\" {\n\t\t\t\tcontinue MainLoop\n\t\t\t}\n\t\tCacheMapLoop:\n\t\t\t\/\/ start a FILE REAPER that loops thru CacheMap[*]\n\t\t\tfor ID := range cache.CacheMap {\n\n\t\t\t\tlogger.Debug(3, \"(Reaper-->FileReaper) checking %s in cache\\n\", ID)\n\n\t\t\t\tnow := time.Now()\n\t\t\t\tlru := cache.CacheMap[ID].Access\n\t\t\t\tdiff := now.Sub(lru)\n\n\t\t\t\t\/\/ we use a very simple scheme for caching initially (file not used for 1 day)\n\t\t\t\tif diff.Hours() < float64(conf.CACHE_TTL) {\n\t\t\t\t\tlogger.Debug(3, \"Reaper-->FileReaper) not deleting %s from cache it was last accessed %s hours ago\\n\", ID, diff.Hours())\n\t\t\t\t\tcontinue CacheMapLoop\n\t\t\t\t}\n\n\t\t\t\tn, err := Load(ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Debug(1, \"(Reaper-->FileReaper) Cannot access CacheMapItem[%s] (%s)\", ID, err.Error())\n\t\t\t\t\tcontinue CacheMapLoop\n\t\t\t\t}\n\t\t\t\tcache.Remove(ID)\n\n\t\t\t\tlogger.Errorf(\"(Reaper-->FileReaper) cannot delete %s from cache [This should not happen!!]\", ID)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (nr *NodeReaper) getQuery() (query bson.M) {\n\thasExpire := bson.M{\"expiration\": bson.M{\"$exists\": true}}   \/\/ has the field\n\ttoExpire := bson.M{\"expiration\": bson.M{\"$ne\": time.Time{}}} \/\/ value has been set, not default\n\tisExpired := bson.M{\"expiration\": bson.M{\"$lt\": time.Now()}} \/\/ value is too old\n\tquery = bson.M{\"$and\": []bson.M{hasExpire, toExpire, isExpired}}\n\treturn\n}\n<commit_msg>restructured reaper<commit_after>package node\n\nimport (\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com\/MG-RAST\/Shock\/shock-server\/cache\"\n\t\"github.com\/MG-RAST\/Shock\/shock-server\/conf\"\n\t\"github.com\/MG-RAST\/Shock\/shock-server\/logger\"\n\t\"github.com\/MG-RAST\/Shock\/shock-server\/node\/locker\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\nvar (\n\tTtl         *NodeReaper\n\tExpireRegex = regexp.MustCompile(`^(\\d+)(M|H|D)$`)\n)\n\nfunc InitReaper() {\n\tTtl = NewNodeReaper()\n}\n\ntype NodeReaper struct{}\n\nfunc NewNodeReaper() *NodeReaper {\n\treturn &NodeReaper{}\n}\n\nfunc (nr *NodeReaper) Handle() {\n\twaitDuration := time.Duration(conf.EXPIRE_WAIT) * time.Minute\nMainLoop:\n\tfor {\n\n\t\t\/\/ sleep\n\t\ttime.Sleep(waitDuration)\n\t\t\/\/ query to get expired nodes\n\t\tnodes := Nodes{}\n\t\tquery := nr.getQuery()\n\t\tnodes.GetAll(query)\n\n\tNodeLoop:\n\t\t\/\/ loop thru all nodes\n\t\tfor _, n := range nodes {\n\t\t\tlogger.Infof(\"Deleting expired node: %s\", n.Id)\n\t\t\t\/\/ delete expired nodes\n\t\t\tif err := n.Delete(); err != nil {\n\t\t\t\terr_msg := \"err:@node_delete: \" + err.Error()\n\t\t\t\tlogger.Error(err_msg)\n\t\t\t}\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\n\t\t\t\/\/ write info for node migration\n\t\t\tlogger.Debug(3, \"writing info for node migration: %s\", n.Id)\n\t\t\t\/\/ CODE MISSING HERE FOR WRITING FILES WITH INFO FOR MIGRATION\n\n\t\t\t\/\/ check if we want to migrate nodes\n\t\t\tif conf.NODE_MIGRATION != true {\n\t\t\t\tlogger.Debug(3, \"not starting node migration\")\n\t\t\t\tcontinue MainLoop\n\t\t\t}\n\n\t\t\t\/\/ CODE for data migration here...\n\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/\tfor this node check all locations to check if node Data files can be erased\n\n\t\t\t\/\/ check global flag to see if we want to remove local data\n\t\t\tif conf.NODE_DATA_REMOVAL == true {\n\t\t\t\tfor _, loc := range n.Locations {\n\t\t\t\t\tvar counter int = 0 \/\/ we need at least N locations before we can erase data files on local disk\n\t\t\t\t\t\/\/ delete only if other locations exist\n\t\t\t\t\tlocObj, ok := conf.LocationsMap[loc.ID]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tlogger.Errorf(\"(Reaper-->FileReaper) location %s is not defined in this server instance \\n \", loc)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t\/\/fmt.Printf(\"(Reaper-->FileReaper) locObj.Persistent =  %b  \\n \", locObj.Persistent)\n\t\t\t\t\tif locObj.Persistent == true {\n\t\t\t\t\t\tlogger.Debug(2, \"(Reaper-->FileReaper) has remote Location (%s) removing from Data: %s\", loc.ID, n.Id)\n\t\t\t\t\t\tcounter++ \/\/ increment counter\n\t\t\t\t\t}\n\t\t\t\t\tif counter >= conf.MIN_REPLICA_COUNT {\n\t\t\t\t\t\terr := n.DeleteFiles() \/\/ delete all data files for node in PATH_DATA NOTE: this is different from PATH_CACHE\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlogger.Errorf(\"(Reaper-->FileReaper) files for node %s could not be deleted (Err: %s) \", n.Id, err.Error())\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue NodeLoop\n\t\t\t\t\t\t\/\/ the innermost loop\n\t\t\t\t\t}\n\t\t\t\t\t\/\/\/\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ garbage collection: remove old nodes from Lockers, value is hours old\n\t\t\tlocker.NodeLockMgr.RemoveOld(1)\n\t\t\tlocker.FileLockMgr.RemoveOld(6)\n\t\t\tlocker.IndexLockMgr.RemoveOld(6)\n\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\t\t\t\/\/  ************************ ************************ ************************ ************************ ************************ ************************ ************************ ************************\n\n\t\t\t\/\/ we do not start deletings files if we are not in cache mode\n\t\t\t\/\/ we might want to change this, if we are in shock-migrate or we do not have a cache_path we skip this\n\t\t\tif conf.PATH_CACHE == \"\" {\n\t\t\t\tcontinue MainLoop\n\t\t\t}\n\t\tCacheMapLoop:\n\t\t\t\/\/ start a FILE REAPER that loops thru CacheMap[*]\n\t\t\tfor ID := range cache.CacheMap {\n\n\t\t\t\tlogger.Debug(3, \"(Reaper-->FileReaper) checking %s in cache\\n\", ID)\n\n\t\t\t\tnow := time.Now()\n\t\t\t\tlru := cache.CacheMap[ID].Access\n\t\t\t\tdiff := now.Sub(lru)\n\n\t\t\t\t\/\/ we use a very simple scheme for caching initially (file not used for 1 day)\n\t\t\t\tif diff.Hours() < float64(conf.CACHE_TTL) {\n\t\t\t\t\tlogger.Debug(3, \"Reaper-->FileReaper) not deleting %s from cache it was last accessed %s hours ago\\n\", ID, diff.Hours())\n\t\t\t\t\tcontinue CacheMapLoop\n\t\t\t\t}\n\n\t\t\t\tn, err := Load(ID)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Debug(1, \"(Reaper-->FileReaper) Cannot access CacheMapItem[%s] (%s)\", ID, err.Error())\n\t\t\t\t\tcontinue CacheMapLoop\n\t\t\t\t}\n\t\t\t\tcache.Remove(ID)\n\n\t\t\t\tlogger.Errorf(\"(Reaper-->FileReaper) cannot delete %s from cache [This should not happen!!]\", ID)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (nr *NodeReaper) getQuery() (query bson.M) {\n\thasExpire := bson.M{\"expiration\": bson.M{\"$exists\": true}}   \/\/ has the field\n\ttoExpire := bson.M{\"expiration\": bson.M{\"$ne\": time.Time{}}} \/\/ value has been set, not default\n\tisExpired := bson.M{\"expiration\": bson.M{\"$lt\": time.Now()}} \/\/ value is too old\n\tquery = bson.M{\"$and\": []bson.M{hasExpire, toExpire, isExpired}}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package classpath\n\nimport (\n\t. \"jvmgo\/testing\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestParseClassPath_Empty(t *testing.T) {\n\tcp := ParseClassPath(\"\").ccpe\n\tAssertEquals(0, len(cp.entries))\n}\n\nfunc TestParseClassPath_OneDir(t *testing.T) {\n\tdirs := []string{\".\", \"abc\", \"a\/b\/c\"}\n\tfor _, dir := range dirs {\n\t\tcp := ParseClassPath(dir).ccpe\n\t\tAssertEquals(1, len(cp.entries))\n\t}\n}\n\nfunc TestParseClassPath_List(t *testing.T) {\n\tpathList := []string{\".\", \"rt.jar\"}\n\tpathStr := strings.Join(pathList, pathListSeparator)\n\tcp := ParseClassPath(pathStr).ccpe\n\tAssertEquals(2, len(cp.entries))\n}\n<commit_msg>fix tests<commit_after>package classpath\n\nimport (\n\t. \"jvmgo\/testing\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestParseClassPath_Empty(t *testing.T) {\n\tcp := ParseClassPath(\"\").compoundEntry\n\tAssertEquals(0, len(cp.entries))\n}\n\nfunc TestParseClassPath_OneDir(t *testing.T) {\n\tdirs := []string{\".\", \"abc\", \"a\/b\/c\"}\n\tfor _, dir := range dirs {\n\t\tcp := ParseClassPath(dir).compoundEntry\n\t\tAssertEquals(1, len(cp.entries))\n\t}\n}\n\nfunc TestParseClassPath_List(t *testing.T) {\n\tpathList := []string{\".\", \"rt.jar\"}\n\tpathStr := strings.Join(pathList, pathListSeparator)\n\tcp := ParseClassPath(pathStr).compoundEntry\n\tAssertEquals(2, len(cp.entries))\n}\n<|endoftext|>"}
{"text":"<commit_before>package timeShift\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com\/lomik\/zapwriter\"\n\t\"github.com\/spf13\/viper\"\n\t\"go.uber.org\/zap\"\n\n\t\"github.com\/go-graphite\/carbonapi\/expr\/helper\"\n\t\"github.com\/go-graphite\/carbonapi\/expr\/interfaces\"\n\t\"github.com\/go-graphite\/carbonapi\/expr\/types\"\n\t\"github.com\/go-graphite\/carbonapi\/pkg\/parser\"\n)\n\ntype timeShift struct {\n\tinterfaces.FunctionBase\n\n\tconfig timeShiftConfig\n}\n\nfunc GetOrder() interfaces.Order {\n\treturn interfaces.Any\n}\n\ntype timeShiftConfig struct {\n\tResetEndDefaultValue *bool\n}\n\nfunc New(configFile string) []interfaces.FunctionMetadata {\n\tlogger := zapwriter.Logger(\"functionInit\").With(zap.String(\"function\", \"timeShift\"))\n\tres := make([]interfaces.FunctionMetadata, 0)\n\tf := &timeShift{}\n\tfunctions := []string{\"timeShift\"}\n\tfor _, n := range functions {\n\t\tres = append(res, interfaces.FunctionMetadata{Name: n, F: f})\n\t}\n\n\tcfg := timeShiftConfig{}\n\tv := viper.New()\n\tv.SetConfigFile(configFile)\n\terr := v.ReadInConfig()\n\tif err != nil {\n\t\tlogger.Info(\"failed to read config file, using default\",\n\t\t\tzap.Error(err),\n\t\t)\n\t} else {\n\t\terr = v.Unmarshal(&cfg)\n\t\tif err != nil {\n\t\t\tlogger.Fatal(\"failed to parse config\",\n\t\t\t\tzap.Error(err),\n\t\t\t)\n\t\t\treturn nil\n\t\t}\n\n\t\tf.config = cfg\n\t}\n\n\tif cfg.ResetEndDefaultValue == nil {\n\t\t\/\/ TODO(civil): Change default value in 0.15\n\t\tv := false\n\t\tf.config.ResetEndDefaultValue = &v\n\t\tlogger.Warn(\"timeShift function in graphite-web have a default value for resetEnd set to true.\" +\n\t\t\t\"carbonapi currently forces this to be false. This behavior will change in next major release (0.15)\" +\n\t\t\t\"to be compatible with graphite-web. Please change your dashboards to explicitly pass resetEnd parameter\" +\n\t\t\t\"or create a config file for this function that sets it to false.\" +\n\t\t\t\"Please see https:\/\/github.com\/go-graphite\/carbonapi\/blob\/main\/doc\/configuration.md#example-for-timeshift\")\n\t}\n\n\treturn res\n}\n\nfunc firstTimeRangeMap(values map[parser.MetricRequest][]*types.MetricData) (int64, int64) {\n\tif len(values) == 0 {\n\t\treturn 0, 0\n\t}\n\tfor _, v := range values {\n\t\tif len(v) == 0 {\n\t\t\treturn 0, 0\n\t\t}\n\t\treturn v[0].StartTime, v[0].StopTime\n\t}\n\treturn 0, 0 \/\/ make compiler happy, unreacheble\n}\n\n\/\/ timeShift(seriesList, timeShift, resetEnd=True)\nfunc (f *timeShift) Do(ctx context.Context, e parser.Expr, from, until int64, values map[parser.MetricRequest][]*types.MetricData) ([]*types.MetricData, error) {\n\t\/\/ FIXME(civil): support alignDst\n\n\toffs, err := e.GetIntervalArg(1, -1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresetEnd, err := e.GetBoolArgDefault(2, *f.config.ResetEndDefaultValue)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\targ, err := helper.GetSeriesArg(e.Args()[0], from+int64(offs), until+int64(offs), values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresults := make([]*types.MetricData, 0, len(arg))\n\n\tfor _, a := range arg {\n\t\tr := *a\n\t\tr.Name = fmt.Sprintf(\"timeShift(%s,'%d',%v)\", a.Name, offs, resetEnd)\n\t\tr.StartTime = a.StartTime - int64(offs)\n\t\tr.StopTime = a.StopTime - int64(offs)\n\t\tif resetEnd && r.StopTime > until {\n\t\t\tr.StopTime = until\n\t\t}\n\t\tlength := int((r.StopTime - r.StartTime) \/ r.StepTime)\n\t\tif length < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tr.Values = r.Values[:length]\n\t\tresults = append(results, &r)\n\t}\n\n\treturn results, nil\n}\n\n\/\/ Description is auto-generated description, based on output of https:\/\/github.com\/graphite-project\/graphite-web\nfunc (f *timeShift) Description() map[string]types.FunctionDescription {\n\treturn map[string]types.FunctionDescription{\n\t\t\"timeShift\": {\n\t\t\tDescription: \"Takes one metric or a wildcard seriesList, followed by a quoted string with the\\nlength of time (See ``from \/ until`` in the render\\\\_api_ for examples of time formats).\\n\\nDraws the selected metrics shifted in time. If no sign is given, a minus sign ( - ) is\\nimplied which will shift the metric back in time. If a plus sign ( + ) is given, the\\nmetric will be shifted forward in time.\\n\\nWill reset the end date range automatically to the end of the base stat unless\\nresetEnd is False. Example case is when you timeshift to last week and have the graph\\ndate range set to include a time in the future, will limit this timeshift to pretend\\nending at the current time. If resetEnd is False, will instead draw full range including\\nfuture time.\\n\\nBecause time is shifted by a fixed number of seconds, comparing a time period with DST to\\na time period without DST, and vice-versa, will result in an apparent misalignment. For\\nexample, 8am might be overlaid with 7am. To compensate for this, use the alignDST option.\\n\\nUseful for comparing a metric against itself at a past periods or correcting data\\nstored at an offset.\\n\\nExample:\\n\\n.. code-block:: none\\n\\n  &target=timeShift(Sales.widgets.largeBlue,\\\"7d\\\")\\n  &target=timeShift(Sales.widgets.largeBlue,\\\"-7d\\\")\\n  &target=timeShift(Sales.widgets.largeBlue,\\\"+1h\\\")\",\n\t\t\tFunction:    \"timeShift(seriesList, timeShift, resetEnd=True, alignDST=False)\",\n\t\t\tGroup:       \"Transform\",\n\t\t\tModule:      \"graphite.render.functions\",\n\t\t\tName:        \"timeShift\",\n\t\t\tParams: []types.FunctionParam{\n\t\t\t\t{\n\t\t\t\t\tName:     \"seriesList\",\n\t\t\t\t\tRequired: true,\n\t\t\t\t\tType:     types.SeriesList,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:     \"timeShift\",\n\t\t\t\t\tRequired: true,\n\t\t\t\t\tSuggestions: types.NewSuggestions(\n\t\t\t\t\t\t\"1h\",\n\t\t\t\t\t\t\"6h\",\n\t\t\t\t\t\t\"12h\",\n\t\t\t\t\t\t\"1d\",\n\t\t\t\t\t\t\"2d\",\n\t\t\t\t\t\t\"7d\",\n\t\t\t\t\t\t\"14d\",\n\t\t\t\t\t\t\"30d\",\n\t\t\t\t\t),\n\t\t\t\t\tType: types.Interval,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tDefault: types.NewSuggestion(*f.config.ResetEndDefaultValue),\n\t\t\t\t\tName:    \"resetEnd\",\n\t\t\t\t\tType:    types.Boolean,\n\t\t\t\t},\n\t\t\t\t\/*\n\t\t\t\t\t{\n\t\t\t\t\t\tDefault: types.NewSuggestion(false),\n\t\t\t\t\t\tName:    \"alignDst\",\n\t\t\t\t\t\tType:    types.Boolean,\n\t\t\t\t\t},\n\t\t\t\t*\/\n\t\t\t},\n\t\t},\n\t}\n}\n<commit_msg>timeShift: cleanup<commit_after>package timeShift\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com\/lomik\/zapwriter\"\n\t\"github.com\/spf13\/viper\"\n\t\"go.uber.org\/zap\"\n\n\t\"github.com\/go-graphite\/carbonapi\/expr\/helper\"\n\t\"github.com\/go-graphite\/carbonapi\/expr\/interfaces\"\n\t\"github.com\/go-graphite\/carbonapi\/expr\/types\"\n\t\"github.com\/go-graphite\/carbonapi\/pkg\/parser\"\n)\n\ntype timeShift struct {\n\tinterfaces.FunctionBase\n\n\tconfig timeShiftConfig\n}\n\nfunc GetOrder() interfaces.Order {\n\treturn interfaces.Any\n}\n\ntype timeShiftConfig struct {\n\tResetEndDefaultValue *bool\n}\n\nfunc New(configFile string) []interfaces.FunctionMetadata {\n\tlogger := zapwriter.Logger(\"functionInit\").With(zap.String(\"function\", \"timeShift\"))\n\tres := make([]interfaces.FunctionMetadata, 0)\n\tf := &timeShift{}\n\tfunctions := []string{\"timeShift\"}\n\tfor _, n := range functions {\n\t\tres = append(res, interfaces.FunctionMetadata{Name: n, F: f})\n\t}\n\n\tcfg := timeShiftConfig{}\n\tv := viper.New()\n\tv.SetConfigFile(configFile)\n\terr := v.ReadInConfig()\n\tif err != nil {\n\t\tlogger.Info(\"failed to read config file, using default\",\n\t\t\tzap.Error(err),\n\t\t)\n\t} else {\n\t\terr = v.Unmarshal(&cfg)\n\t\tif err != nil {\n\t\t\tlogger.Fatal(\"failed to parse config\",\n\t\t\t\tzap.Error(err),\n\t\t\t)\n\t\t\treturn nil\n\t\t}\n\n\t\tf.config = cfg\n\t}\n\n\tif cfg.ResetEndDefaultValue == nil {\n\t\t\/\/ TODO(civil): Change default value in 0.15\n\t\tv := false\n\t\tf.config.ResetEndDefaultValue = &v\n\t\tlogger.Warn(\"timeShift function in graphite-web have a default value for resetEnd set to true.\" +\n\t\t\t\"carbonapi currently forces this to be false. This behavior will change in next major release (0.15)\" +\n\t\t\t\"to be compatible with graphite-web. Please change your dashboards to explicitly pass resetEnd parameter\" +\n\t\t\t\"or create a config file for this function that sets it to false.\" +\n\t\t\t\"Please see https:\/\/github.com\/go-graphite\/carbonapi\/blob\/main\/doc\/configuration.md#example-for-timeshift\")\n\t}\n\n\treturn res\n}\n\n\/\/ timeShift(seriesList, timeShift, resetEnd=True)\nfunc (f *timeShift) Do(ctx context.Context, e parser.Expr, from, until int64, values map[parser.MetricRequest][]*types.MetricData) ([]*types.MetricData, error) {\n\t\/\/ FIXME(civil): support alignDst\n\n\toffs, err := e.GetIntervalArg(1, -1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresetEnd, err := e.GetBoolArgDefault(2, *f.config.ResetEndDefaultValue)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\targ, err := helper.GetSeriesArg(e.Args()[0], from+int64(offs), until+int64(offs), values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresults := make([]*types.MetricData, 0, len(arg))\n\n\tfor _, a := range arg {\n\t\tr := *a\n\t\tr.Name = fmt.Sprintf(\"timeShift(%s,'%d',%v)\", a.Name, offs, resetEnd)\n\t\tr.StartTime = a.StartTime - int64(offs)\n\t\tr.StopTime = a.StopTime - int64(offs)\n\t\tif resetEnd && r.StopTime > until {\n\t\t\tr.StopTime = until\n\t\t}\n\t\tlength := int((r.StopTime - r.StartTime) \/ r.StepTime)\n\t\tif length < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tr.Values = r.Values[:length]\n\t\tresults = append(results, &r)\n\t}\n\n\treturn results, nil\n}\n\n\/\/ Description is auto-generated description, based on output of https:\/\/github.com\/graphite-project\/graphite-web\nfunc (f *timeShift) Description() map[string]types.FunctionDescription {\n\treturn map[string]types.FunctionDescription{\n\t\t\"timeShift\": {\n\t\t\tDescription: \"Takes one metric or a wildcard seriesList, followed by a quoted string with the\\nlength of time (See ``from \/ until`` in the render\\\\_api_ for examples of time formats).\\n\\nDraws the selected metrics shifted in time. If no sign is given, a minus sign ( - ) is\\nimplied which will shift the metric back in time. If a plus sign ( + ) is given, the\\nmetric will be shifted forward in time.\\n\\nWill reset the end date range automatically to the end of the base stat unless\\nresetEnd is False. Example case is when you timeshift to last week and have the graph\\ndate range set to include a time in the future, will limit this timeshift to pretend\\nending at the current time. If resetEnd is False, will instead draw full range including\\nfuture time.\\n\\nBecause time is shifted by a fixed number of seconds, comparing a time period with DST to\\na time period without DST, and vice-versa, will result in an apparent misalignment. For\\nexample, 8am might be overlaid with 7am. To compensate for this, use the alignDST option.\\n\\nUseful for comparing a metric against itself at a past periods or correcting data\\nstored at an offset.\\n\\nExample:\\n\\n.. code-block:: none\\n\\n  &target=timeShift(Sales.widgets.largeBlue,\\\"7d\\\")\\n  &target=timeShift(Sales.widgets.largeBlue,\\\"-7d\\\")\\n  &target=timeShift(Sales.widgets.largeBlue,\\\"+1h\\\")\",\n\t\t\tFunction:    \"timeShift(seriesList, timeShift, resetEnd=True, alignDST=False)\",\n\t\t\tGroup:       \"Transform\",\n\t\t\tModule:      \"graphite.render.functions\",\n\t\t\tName:        \"timeShift\",\n\t\t\tParams: []types.FunctionParam{\n\t\t\t\t{\n\t\t\t\t\tName:     \"seriesList\",\n\t\t\t\t\tRequired: true,\n\t\t\t\t\tType:     types.SeriesList,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:     \"timeShift\",\n\t\t\t\t\tRequired: true,\n\t\t\t\t\tSuggestions: types.NewSuggestions(\n\t\t\t\t\t\t\"1h\",\n\t\t\t\t\t\t\"6h\",\n\t\t\t\t\t\t\"12h\",\n\t\t\t\t\t\t\"1d\",\n\t\t\t\t\t\t\"2d\",\n\t\t\t\t\t\t\"7d\",\n\t\t\t\t\t\t\"14d\",\n\t\t\t\t\t\t\"30d\",\n\t\t\t\t\t),\n\t\t\t\t\tType: types.Interval,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tDefault: types.NewSuggestion(*f.config.ResetEndDefaultValue),\n\t\t\t\t\tName:    \"resetEnd\",\n\t\t\t\t\tType:    types.Boolean,\n\t\t\t\t},\n\t\t\t\t\/*\n\t\t\t\t\t{\n\t\t\t\t\t\tDefault: types.NewSuggestion(false),\n\t\t\t\t\t\tName:    \"alignDst\",\n\t\t\t\t\t\tType:    types.Boolean,\n\t\t\t\t\t},\n\t\t\t\t*\/\n\t\t\t},\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package server_test\n\nimport (\n\t\"bytes\"\n\t\"crypto\/hmac\"\n\t\"crypto\/sha256\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"github.com\/WhiteHatCP\/seclab-listener\/server\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype Closer func()\n\ntype countingBackend struct {\n\tnumOpen  int\n\tnumClose int\n}\n\nfunc (b *countingBackend) Open() error {\n\tb.numOpen += 1\n\treturn nil\n}\n\nfunc (b *countingBackend) Close() error {\n\tb.numClose += 1\n\treturn nil\n}\n\ntype errorBackend struct{}\n\nfunc (b *errorBackend) Open() error {\n\treturn errors.New(\"open error\")\n}\nfunc (b *errorBackend) Close() error {\n\treturn errors.New(\"close error\")\n}\nfunc (b *errorBackend) Coffee() error {\n\treturn errors.New(\"coffee error\")\n}\n\nfunc getTestInstance() (server.Server, Closer) {\n\ttempDir, _ := ioutil.TempDir(\"\", \"\")\n\tkeypath := filepath.Join(tempDir, \"key\")\n\tioutil.WriteFile(keypath, []byte(\"dismykey\"), 0644)\n\ts := server.New(keypath, 10)\n\ts.AddBackend(&countingBackend{})\n\treturn s, func() {\n\t\tos.RemoveAll(tempDir)\n\t}\n}\n\nfunc TestBadSignature(t *testing.T) {\n\tmsg := make([]byte, 41)\n\ts, close := getTestInstance()\n\tdefer close()\n\terr := s.CheckMessage(msg)\n\tif err == nil || err.Error() != \"Incorrect HMAC signature\" {\n\t\tt.Error(\"Expected Incorrect HMAC signature, got\", err)\n\t}\n}\n\nfunc TestExpired(t *testing.T) {\n\tpayload := make([]byte, 9)\n\tmac := hmac.New(sha256.New, []byte(\"dismykey\"))\n\tmac.Write(payload)\n\ts, close := getTestInstance()\n\tdefer close()\n\terr := s.CheckMessage(mac.Sum(payload))\n\tif err == nil || err.Error() != \"Request expired\" {\n\t\tt.Error(\"Expected Request expired, got\", err)\n\t}\n}\n\nfunc TestGoodCheck(t *testing.T) {\n\tpayload := make([]byte, 9)\n\tpayload[0] = 0xff\n\tnow64 := time.Now().Unix()\n\tbinary.BigEndian.PutUint64(payload[1:9], uint64(now64))\n\tmac := hmac.New(sha256.New, []byte(\"dismykey\"))\n\tmac.Write(payload)\n\tmessage := mac.Sum(payload)\n\ts, close := getTestInstance()\n\tdefer close()\n\tif err := s.CheckMessage(message); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestDispatchUnknown(t *testing.T) {\n\ts, close := getTestInstance()\n\tdefer close()\n\t_, err := s.DispatchRequest(0x69)\n\tif err == nil || err.Error() != \"Unrecognized status byte: 0x69\" {\n\t\tt.Error(\"Expected Unrecognized status byte: 0x69, got\", err)\n\t}\n}\n\nfunc TestDispatchOpenError(t *testing.T) {\n\ts := server.New(\"\", 10)\n\ts.AddBackend(&errorBackend{})\n\t_, err := s.DispatchRequest(0xff)\n\tif err == nil || err.Error() != \"open error\" {\n\t\tt.Error(\"Expected open error, got\", err)\n\t}\n}\n\nfunc TestDispatchCloseError(t *testing.T) {\n\ts := server.New(\"\", 10)\n\ts.AddBackend(&errorBackend{})\n\t_, err := s.DispatchRequest(0x00)\n\tif err == nil || err.Error() != \"close error\" {\n\t\tt.Error(\"Expected close error, got\", err)\n\t}\n}\n\nfunc TestDispatchOpenGood(t *testing.T) {\n\ts, close := getTestInstance()\n\tdefer close()\n\tresp, err := s.DispatchRequest(0xff)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if resp[0] != 0xff {\n\t\tt.Errorf(\"Expected 0xff, got 0x%x\", resp)\n\t}\n}\n\nfunc TestDispatchCloseGood(t *testing.T) {\n\ts, close := getTestInstance()\n\tdefer close()\n\tresp, err := s.DispatchRequest(0x00)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if resp[0] != 0xff {\n\t\tt.Errorf(\"Expected 0xff, got 0x%x\", resp)\n\t}\n}\n\nfunc TestKeyRotate(t *testing.T) {\n\ttempDir, _ := ioutil.TempDir(\"\", \"\")\n\tkeypath := filepath.Join(tempDir, \"key\")\n\tioutil.WriteFile(keypath, []byte(\"dismykey\"), 0644)\n\ts := server.New(keypath, 10)\n\tresp, err := s.KeyRotate()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tkey, _ := ioutil.ReadFile(keypath)\n\tif bytes.Compare(resp[9:], key) != 0 {\n\t\tt.Error(resp, \"!=\", key)\n\t}\n}\n\nfunc TestMultipleBackends(t *testing.T) {\n\tb := &countingBackend{0, 0}\n\ts := server.New(\"\", 10)\n\ts.AddBackend(b)\n\ts.AddBackend(b)\n\n\tif _, err := s.DispatchRequest(0x00); err != nil {\n\t\tt.Error(err)\n\t}\n\tif _, err := s.DispatchRequest(0xff); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif b.numOpen != 2 {\n\t\tt.Error(\"Expected Open to be called 2 times, was called \", b.numOpen)\n\t} else if b.numClose != 2 {\n\t\tt.Error(\"Expected Close to be called 2 times, was called \", b.numClose)\n\t}\n}\n<commit_msg>Fixing travis tests v2<commit_after>package server_test\n\nimport (\n\t\"bytes\"\n\t\"crypto\/hmac\"\n\t\"crypto\/sha256\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"github.com\/WhiteHatCP\/seclab-listener\/server\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype Closer func()\n\ntype countingBackend struct {\n\tnumOpen  int\n\tnumClose int\n}\n\nfunc (b *countingBackend) Open() error {\n\tb.numOpen += 1\n\treturn nil\n}\n\nfunc (b *countingBackend) Close() error {\n\tb.numClose += 1\n\treturn nil\n}\n\nfunc (b *countingBackend) Coffee() error {\n\tb.numClose += 1\n\treturn nil\n}\n\ntype errorBackend struct{}\n\nfunc (b *errorBackend) Open() error {\n\treturn errors.New(\"open error\")\n}\nfunc (b *errorBackend) Close() error {\n\treturn errors.New(\"close error\")\n}\nfunc (b *errorBackend) Coffee() error {\n\treturn errors.New(\"coffee error\")\n}\n\nfunc getTestInstance() (server.Server, Closer) {\n\ttempDir, _ := ioutil.TempDir(\"\", \"\")\n\tkeypath := filepath.Join(tempDir, \"key\")\n\tioutil.WriteFile(keypath, []byte(\"dismykey\"), 0644)\n\ts := server.New(keypath, 10)\n\ts.AddBackend(&countingBackend{})\n\treturn s, func() {\n\t\tos.RemoveAll(tempDir)\n\t}\n}\n\nfunc TestBadSignature(t *testing.T) {\n\tmsg := make([]byte, 41)\n\ts, close := getTestInstance()\n\tdefer close()\n\terr := s.CheckMessage(msg)\n\tif err == nil || err.Error() != \"Incorrect HMAC signature\" {\n\t\tt.Error(\"Expected Incorrect HMAC signature, got\", err)\n\t}\n}\n\nfunc TestExpired(t *testing.T) {\n\tpayload := make([]byte, 9)\n\tmac := hmac.New(sha256.New, []byte(\"dismykey\"))\n\tmac.Write(payload)\n\ts, close := getTestInstance()\n\tdefer close()\n\terr := s.CheckMessage(mac.Sum(payload))\n\tif err == nil || err.Error() != \"Request expired\" {\n\t\tt.Error(\"Expected Request expired, got\", err)\n\t}\n}\n\nfunc TestGoodCheck(t *testing.T) {\n\tpayload := make([]byte, 9)\n\tpayload[0] = 0xff\n\tnow64 := time.Now().Unix()\n\tbinary.BigEndian.PutUint64(payload[1:9], uint64(now64))\n\tmac := hmac.New(sha256.New, []byte(\"dismykey\"))\n\tmac.Write(payload)\n\tmessage := mac.Sum(payload)\n\ts, close := getTestInstance()\n\tdefer close()\n\tif err := s.CheckMessage(message); err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestDispatchUnknown(t *testing.T) {\n\ts, close := getTestInstance()\n\tdefer close()\n\t_, err := s.DispatchRequest(0x69)\n\tif err == nil || err.Error() != \"Unrecognized status byte: 0x69\" {\n\t\tt.Error(\"Expected Unrecognized status byte: 0x69, got\", err)\n\t}\n}\n\nfunc TestDispatchOpenError(t *testing.T) {\n\ts := server.New(\"\", 10)\n\ts.AddBackend(&errorBackend{})\n\t_, err := s.DispatchRequest(0xff)\n\tif err == nil || err.Error() != \"open error\" {\n\t\tt.Error(\"Expected open error, got\", err)\n\t}\n}\n\nfunc TestDispatchCloseError(t *testing.T) {\n\ts := server.New(\"\", 10)\n\ts.AddBackend(&errorBackend{})\n\t_, err := s.DispatchRequest(0x00)\n\tif err == nil || err.Error() != \"close error\" {\n\t\tt.Error(\"Expected close error, got\", err)\n\t}\n}\n\nfunc TestDispatchOpenGood(t *testing.T) {\n\ts, close := getTestInstance()\n\tdefer close()\n\tresp, err := s.DispatchRequest(0xff)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if resp[0] != 0xff {\n\t\tt.Errorf(\"Expected 0xff, got 0x%x\", resp)\n\t}\n}\n\nfunc TestDispatchCloseGood(t *testing.T) {\n\ts, close := getTestInstance()\n\tdefer close()\n\tresp, err := s.DispatchRequest(0x00)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if resp[0] != 0xff {\n\t\tt.Errorf(\"Expected 0xff, got 0x%x\", resp)\n\t}\n}\n\nfunc TestKeyRotate(t *testing.T) {\n\ttempDir, _ := ioutil.TempDir(\"\", \"\")\n\tkeypath := filepath.Join(tempDir, \"key\")\n\tioutil.WriteFile(keypath, []byte(\"dismykey\"), 0644)\n\ts := server.New(keypath, 10)\n\tresp, err := s.KeyRotate()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tkey, _ := ioutil.ReadFile(keypath)\n\tif bytes.Compare(resp[9:], key) != 0 {\n\t\tt.Error(resp, \"!=\", key)\n\t}\n}\n\nfunc TestMultipleBackends(t *testing.T) {\n\tb := &countingBackend{0, 0}\n\ts := server.New(\"\", 10)\n\ts.AddBackend(b)\n\ts.AddBackend(b)\n\n\tif _, err := s.DispatchRequest(0x00); err != nil {\n\t\tt.Error(err)\n\t}\n\tif _, err := s.DispatchRequest(0xff); err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif b.numOpen != 2 {\n\t\tt.Error(\"Expected Open to be called 2 times, was called \", b.numOpen)\n\t} else if b.numClose != 2 {\n\t\tt.Error(\"Expected Close to be called 2 times, was called \", b.numClose)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package amp\n\n\/**\n * Protocol version.\n *\/\n\nvar version uint8 = 1\n\n\/\/ Encode `args`.\nfunc Encode(args [][]byte) []byte {\n\targc := len(args)\n\tbufl := 1\n\n\t\/\/ data length\n\tfor i := 0; i < argc; i++ {\n\t\tbufl += 4 + len(args[i])\n\t}\n\n\t\/\/ buffer\n\tbuf := make([]byte, bufl)\n\tbuff := buf \/\/ keep a ref to head\n\n\t\/\/ pack meta\n\tbuf[0] = byte((version << 4) | uint8(argc))\n\tbuf = buf[1:]\n\n\t\/\/ pack args\n\tfor i := 0; i < argc; i++ {\n\t\targ := args[i]\n\t\targl := uint32(len(arg))\n\n\t\tbuf[0] = byte(argl >> 24)\n\t\tbuf[1] = byte(argl >> 16)\n\t\tbuf[2] = byte(argl >> 8)\n\t\tbuf[3] = byte(argl)\n\t\tbuf = buf[4:]\n\n\t\tcopy(buf, arg)\n\t\tbuf = buf[argl:]\n\t}\n\n\treturn buff\n}\n<commit_msg>fixed comment<commit_after>package amp\n\n\/\/ Protocol version.\nvar version uint8 = 1\n\n\/\/ Encode `args`.\nfunc Encode(args [][]byte) []byte {\n\targc := len(args)\n\tbufl := 1\n\n\t\/\/ data length\n\tfor i := 0; i < argc; i++ {\n\t\tbufl += 4 + len(args[i])\n\t}\n\n\t\/\/ buffer\n\tbuf := make([]byte, bufl)\n\tbuff := buf \/\/ keep a ref to head\n\n\t\/\/ pack meta\n\tbuf[0] = byte((version << 4) | uint8(argc))\n\tbuf = buf[1:]\n\n\t\/\/ pack args\n\tfor i := 0; i < argc; i++ {\n\t\targ := args[i]\n\t\targl := uint32(len(arg))\n\n\t\tbuf[0] = byte(argl >> 24)\n\t\tbuf[1] = byte(argl >> 16)\n\t\tbuf[2] = byte(argl >> 8)\n\t\tbuf[3] = byte(argl)\n\t\tbuf = buf[4:]\n\n\t\tcopy(buf, arg)\n\t\tbuf = buf[argl:]\n\t}\n\n\treturn buff\n}\n<|endoftext|>"}
{"text":"<commit_before>package msgpack\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"reflect\"\n)\n\nfunc Marshal(v interface{}) ([]byte, error) {\n\tbuf := &bytes.Buffer{}\n\terr := NewEncoder(buf).Encode(v)\n\treturn buf.Bytes(), err\n}\n\ntype Encoder struct {\n\tW io.Writer\n}\n\nfunc NewEncoder(writer io.Writer) *Encoder {\n\treturn &Encoder{\n\t\tW: writer,\n\t}\n}\n\nfunc (e *Encoder) Encode(v interface{}) error {\n\tif v == nil {\n\t\treturn e.EncodeNil()\n\t}\n\treturn e.EncodeValue(reflect.ValueOf(v))\n}\n\nfunc (e *Encoder) EncodeValue(v reflect.Value) error {\n\tswitch v.Kind() {\n\tcase reflect.Bool:\n\t\treturn e.EncodeBool(v.Bool())\n\tcase reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:\n\t\treturn e.EncodeUint64(v.Uint())\n\tcase reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:\n\t\treturn e.EncodeInt64(v.Int())\n\tcase reflect.Float32:\n\t\treturn e.EncodeFloat32(float32(v.Float()))\n\tcase reflect.Float64:\n\t\treturn e.EncodeFloat64(v.Float())\n\tcase reflect.Array, reflect.Slice:\n\t\treturn e.EncodeArray(v)\n\tcase reflect.Map:\n\t\treturn e.EncodeMap(v)\n\tcase reflect.String:\n\t\treturn e.EncodeBytes([]byte(v.String()))\n\tcase reflect.Struct:\n\t\tif enc, ok := typEncMap[v.Type()]; ok {\n\t\t\treturn enc(e, v)\n\t\t}\n\t\treturn e.EncodeStruct(v)\n\tcase reflect.Interface, reflect.Ptr:\n\t\tif v.IsNil() {\n\t\t\treturn e.EncodeNil()\n\t\t}\n\t\tif enc, ok := typEncMap[v.Type()]; ok {\n\t\t\treturn enc(e, v)\n\t\t}\n\t\treturn e.EncodeValue(v.Elem())\n\tdefault:\n\t\treturn fmt.Errorf(\"msgpack: unsupported type %v\", v.Type().String())\n\t}\n\tpanic(\"not reached\")\n}\n\nfunc (e *Encoder) write(data []byte) error {\n\t_, err := e.W.Write(data)\n\treturn err\n}\n\nfunc (e *Encoder) EncodeNil() error {\n\treturn e.write([]byte{nilCode})\n}\n\nfunc (e *Encoder) EncodeUint32Byte(v uint32, c byte) error {\n\treturn e.write([]byte{\n\t\tc,\n\t\tbyte(v >> 24),\n\t\tbyte(v >> 16),\n\t\tbyte(v >> 8),\n\t\tbyte(v),\n\t})\n}\n\nfunc (e *Encoder) EncodeUint64(v uint64) error {\n\tswitch {\n\tcase v < 128:\n\t\treturn e.write([]byte{byte(v)})\n\tcase v < 256:\n\t\treturn e.write([]byte{uint8Code, byte(v)})\n\tcase v < 65536:\n\t\treturn e.write([]byte{uint16Code, byte(v >> 8), byte(v)})\n\tcase v < 4294967296:\n\t\treturn e.write([]byte{\n\t\t\tuint32Code,\n\t\t\tbyte(v >> 24),\n\t\t\tbyte(v >> 16),\n\t\t\tbyte(v >> 8),\n\t\t\tbyte(v),\n\t\t})\n\tdefault:\n\t\treturn e.write([]byte{\n\t\t\tuint64Code,\n\t\t\tbyte(v >> 56),\n\t\t\tbyte(v >> 48),\n\t\t\tbyte(v >> 40),\n\t\t\tbyte(v >> 32),\n\t\t\tbyte(v >> 24),\n\t\t\tbyte(v >> 16),\n\t\t\tbyte(v >> 8),\n\t\t\tbyte(v),\n\t\t})\n\t}\n\tpanic(\"not reached\")\n}\n\nfunc (e *Encoder) EncodeInt64(v int64) error {\n\tswitch {\n\tcase v < -2147483648 || v >= 2147483648:\n\t\treturn e.write([]byte{\n\t\t\tint64Code,\n\t\t\tbyte(v >> 56),\n\t\t\tbyte(v >> 48),\n\t\t\tbyte(v >> 40),\n\t\t\tbyte(v >> 32),\n\t\t\tbyte(v >> 24),\n\t\t\tbyte(v >> 16),\n\t\t\tbyte(v >> 8),\n\t\t\tbyte(v),\n\t\t})\n\tcase v < -32768 || v >= 32768:\n\t\treturn e.write([]byte{\n\t\t\tint32Code,\n\t\t\tbyte(v >> 24),\n\t\t\tbyte(v >> 16),\n\t\t\tbyte(v >> 8),\n\t\t\tbyte(v),\n\t\t})\n\tcase v < -128 || v >= 128:\n\t\treturn e.write([]byte{int16Code, byte(v >> 8), byte(v)})\n\tcase v < -32:\n\t\treturn e.write([]byte{int8Code, byte(v)})\n\tdefault:\n\t\treturn e.write([]byte{byte(v)})\n\t}\n\tpanic(\"not reached\")\n}\n\nfunc (e *Encoder) EncodeBool(value bool) error {\n\tif value {\n\t\treturn e.write([]byte{trueCode})\n\t}\n\treturn e.write([]byte{falseCode})\n}\n\nfunc (e *Encoder) EncodeFloat32(value float32) error {\n\tv := math.Float32bits(value)\n\treturn e.write([]byte{\n\t\tfloatCode,\n\t\tbyte(v >> 24),\n\t\tbyte(v >> 16),\n\t\tbyte(v >> 8),\n\t\tbyte(v),\n\t})\n}\n\nfunc (e *Encoder) EncodeFloat64(value float64) error {\n\tv := math.Float64bits(value)\n\treturn e.write([]byte{\n\t\tdoubleCode,\n\t\tbyte(v >> 56),\n\t\tbyte(v >> 48),\n\t\tbyte(v >> 40),\n\t\tbyte(v >> 32),\n\t\tbyte(v >> 24),\n\t\tbyte(v >> 16),\n\t\tbyte(v >> 8),\n\t\tbyte(v),\n\t})\n}\n\nfunc (e *Encoder) EncodeBytes(v []byte) error {\n\tswitch l := len(v); {\n\tcase l < 32:\n\t\tif err := e.write([]byte{fixRawLowCode | uint8(l)}); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase l < 65536:\n\t\tif err := e.write([]byte{\n\t\t\traw16Code,\n\t\t\tbyte(l >> 8),\n\t\t\tbyte(l),\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\tif err := e.write([]byte{\n\t\t\traw32Code,\n\t\t\tbyte(l >> 24),\n\t\t\tbyte(l >> 16),\n\t\t\tbyte(l >> 8),\n\t\t\tbyte(l),\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn e.write(v)\n}\n\nfunc (e *Encoder) EncodeArray(value reflect.Value) error {\n\telemType := value.Type().Elem()\n\tif elemType.Kind() == reflect.Uint8 {\n\t\treturn e.EncodeBytes(value.Interface().([]byte))\n\t}\n\n\tswitch l := value.Len(); {\n\tcase l < 16:\n\t\tif err := e.write([]byte{fixArrayLowCode | byte(l)}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := 0; i < l; i++ {\n\t\t\tif err := e.EncodeValue(value.Index(i)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tcase l < 65536:\n\t\tif err := e.write([]byte{array16Code, byte(l >> 8), byte(l)}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := 0; i < l; i++ {\n\t\t\tif err := e.EncodeValue(value.Index(i)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\tif err := e.write([]byte{\n\t\t\tarray32Code,\n\t\t\tbyte(l >> 24),\n\t\t\tbyte(l >> 16),\n\t\t\tbyte(l >> 8),\n\t\t\tbyte(l),\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := 0; i < l; i++ {\n\t\t\tif err := e.EncodeValue(value.Index(i)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (e *Encoder) EncodeMap(value reflect.Value) error {\n\tkeys := value.MapKeys()\n\tswitch l := value.Len(); {\n\tcase l < 16:\n\t\tif err := e.write([]byte{fixMapLowCode | byte(l)}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, k := range keys {\n\t\t\tif err := e.EncodeValue(k); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := e.EncodeValue(value.MapIndex(k)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\tcase l < 65536:\n\t\tif err := e.write([]byte{\n\t\t\tmap16Code,\n\t\t\tbyte(l >> 8),\n\t\t\tbyte(l),\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, k := range keys {\n\t\t\tif err := e.EncodeValue(k); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := e.EncodeValue(value.MapIndex(k)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tif err := e.write([]byte{\n\t\t\tmap32Code,\n\t\t\tbyte(l >> 24),\n\t\t\tbyte(l >> 16),\n\t\t\tbyte(l >> 8),\n\t\t\tbyte(l),\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, k := range keys {\n\t\t\tif err := e.EncodeValue(k); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := e.EncodeValue(value.MapIndex(k)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (e *Encoder) EncodeStruct(value reflect.Value) error {\n\tfields := reflectCache.Fields(value.Type())\n\tnum := len(fields)\n\tif num <= 0 {\n\t\treturn e.EncodeNil()\n\t}\n\n\tif err := e.write([]byte{\n\t\tmap32Code,\n\t\tbyte(num >> 24),\n\t\tbyte(num >> 16),\n\t\tbyte(num >> 8),\n\t\tbyte(num),\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, field := range fields {\n\t\tif err := e.EncodeBytes([]byte(field.Name)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := e.EncodeValue(value.Field(field.Ind)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>Remove unused method.<commit_after>package msgpack\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"reflect\"\n)\n\nfunc Marshal(v interface{}) ([]byte, error) {\n\tbuf := &bytes.Buffer{}\n\terr := NewEncoder(buf).Encode(v)\n\treturn buf.Bytes(), err\n}\n\ntype Encoder struct {\n\tW io.Writer\n}\n\nfunc NewEncoder(writer io.Writer) *Encoder {\n\treturn &Encoder{\n\t\tW: writer,\n\t}\n}\n\nfunc (e *Encoder) Encode(v interface{}) error {\n\tif v == nil {\n\t\treturn e.EncodeNil()\n\t}\n\treturn e.EncodeValue(reflect.ValueOf(v))\n}\n\nfunc (e *Encoder) EncodeValue(v reflect.Value) error {\n\tswitch v.Kind() {\n\tcase reflect.Bool:\n\t\treturn e.EncodeBool(v.Bool())\n\tcase reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:\n\t\treturn e.EncodeUint64(v.Uint())\n\tcase reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:\n\t\treturn e.EncodeInt64(v.Int())\n\tcase reflect.Float32:\n\t\treturn e.EncodeFloat32(float32(v.Float()))\n\tcase reflect.Float64:\n\t\treturn e.EncodeFloat64(v.Float())\n\tcase reflect.Array, reflect.Slice:\n\t\treturn e.EncodeArray(v)\n\tcase reflect.Map:\n\t\treturn e.EncodeMap(v)\n\tcase reflect.String:\n\t\treturn e.EncodeBytes([]byte(v.String()))\n\tcase reflect.Struct:\n\t\tif enc, ok := typEncMap[v.Type()]; ok {\n\t\t\treturn enc(e, v)\n\t\t}\n\t\treturn e.EncodeStruct(v)\n\tcase reflect.Interface, reflect.Ptr:\n\t\tif v.IsNil() {\n\t\t\treturn e.EncodeNil()\n\t\t}\n\t\tif enc, ok := typEncMap[v.Type()]; ok {\n\t\t\treturn enc(e, v)\n\t\t}\n\t\treturn e.EncodeValue(v.Elem())\n\tdefault:\n\t\treturn fmt.Errorf(\"msgpack: unsupported type %v\", v.Type().String())\n\t}\n\tpanic(\"not reached\")\n}\n\nfunc (e *Encoder) write(data []byte) error {\n\t_, err := e.W.Write(data)\n\treturn err\n}\n\nfunc (e *Encoder) EncodeNil() error {\n\treturn e.write([]byte{nilCode})\n}\n\nfunc (e *Encoder) EncodeUint64(v uint64) error {\n\tswitch {\n\tcase v < 128:\n\t\treturn e.write([]byte{byte(v)})\n\tcase v < 256:\n\t\treturn e.write([]byte{uint8Code, byte(v)})\n\tcase v < 65536:\n\t\treturn e.write([]byte{uint16Code, byte(v >> 8), byte(v)})\n\tcase v < 4294967296:\n\t\treturn e.write([]byte{\n\t\t\tuint32Code,\n\t\t\tbyte(v >> 24),\n\t\t\tbyte(v >> 16),\n\t\t\tbyte(v >> 8),\n\t\t\tbyte(v),\n\t\t})\n\tdefault:\n\t\treturn e.write([]byte{\n\t\t\tuint64Code,\n\t\t\tbyte(v >> 56),\n\t\t\tbyte(v >> 48),\n\t\t\tbyte(v >> 40),\n\t\t\tbyte(v >> 32),\n\t\t\tbyte(v >> 24),\n\t\t\tbyte(v >> 16),\n\t\t\tbyte(v >> 8),\n\t\t\tbyte(v),\n\t\t})\n\t}\n\tpanic(\"not reached\")\n}\n\nfunc (e *Encoder) EncodeInt64(v int64) error {\n\tswitch {\n\tcase v < -2147483648 || v >= 2147483648:\n\t\treturn e.write([]byte{\n\t\t\tint64Code,\n\t\t\tbyte(v >> 56),\n\t\t\tbyte(v >> 48),\n\t\t\tbyte(v >> 40),\n\t\t\tbyte(v >> 32),\n\t\t\tbyte(v >> 24),\n\t\t\tbyte(v >> 16),\n\t\t\tbyte(v >> 8),\n\t\t\tbyte(v),\n\t\t})\n\tcase v < -32768 || v >= 32768:\n\t\treturn e.write([]byte{\n\t\t\tint32Code,\n\t\t\tbyte(v >> 24),\n\t\t\tbyte(v >> 16),\n\t\t\tbyte(v >> 8),\n\t\t\tbyte(v),\n\t\t})\n\tcase v < -128 || v >= 128:\n\t\treturn e.write([]byte{int16Code, byte(v >> 8), byte(v)})\n\tcase v < -32:\n\t\treturn e.write([]byte{int8Code, byte(v)})\n\tdefault:\n\t\treturn e.write([]byte{byte(v)})\n\t}\n\tpanic(\"not reached\")\n}\n\nfunc (e *Encoder) EncodeBool(value bool) error {\n\tif value {\n\t\treturn e.write([]byte{trueCode})\n\t}\n\treturn e.write([]byte{falseCode})\n}\n\nfunc (e *Encoder) EncodeFloat32(value float32) error {\n\tv := math.Float32bits(value)\n\treturn e.write([]byte{\n\t\tfloatCode,\n\t\tbyte(v >> 24),\n\t\tbyte(v >> 16),\n\t\tbyte(v >> 8),\n\t\tbyte(v),\n\t})\n}\n\nfunc (e *Encoder) EncodeFloat64(value float64) error {\n\tv := math.Float64bits(value)\n\treturn e.write([]byte{\n\t\tdoubleCode,\n\t\tbyte(v >> 56),\n\t\tbyte(v >> 48),\n\t\tbyte(v >> 40),\n\t\tbyte(v >> 32),\n\t\tbyte(v >> 24),\n\t\tbyte(v >> 16),\n\t\tbyte(v >> 8),\n\t\tbyte(v),\n\t})\n}\n\nfunc (e *Encoder) EncodeBytes(v []byte) error {\n\tswitch l := len(v); {\n\tcase l < 32:\n\t\tif err := e.write([]byte{fixRawLowCode | uint8(l)}); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase l < 65536:\n\t\tif err := e.write([]byte{\n\t\t\traw16Code,\n\t\t\tbyte(l >> 8),\n\t\t\tbyte(l),\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\tif err := e.write([]byte{\n\t\t\traw32Code,\n\t\t\tbyte(l >> 24),\n\t\t\tbyte(l >> 16),\n\t\t\tbyte(l >> 8),\n\t\t\tbyte(l),\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn e.write(v)\n}\n\nfunc (e *Encoder) EncodeArray(value reflect.Value) error {\n\telemType := value.Type().Elem()\n\tif elemType.Kind() == reflect.Uint8 {\n\t\treturn e.EncodeBytes(value.Interface().([]byte))\n\t}\n\n\tswitch l := value.Len(); {\n\tcase l < 16:\n\t\tif err := e.write([]byte{fixArrayLowCode | byte(l)}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := 0; i < l; i++ {\n\t\t\tif err := e.EncodeValue(value.Index(i)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tcase l < 65536:\n\t\tif err := e.write([]byte{array16Code, byte(l >> 8), byte(l)}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := 0; i < l; i++ {\n\t\t\tif err := e.EncodeValue(value.Index(i)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\tif err := e.write([]byte{\n\t\t\tarray32Code,\n\t\t\tbyte(l >> 24),\n\t\t\tbyte(l >> 16),\n\t\t\tbyte(l >> 8),\n\t\t\tbyte(l),\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor i := 0; i < l; i++ {\n\t\t\tif err := e.EncodeValue(value.Index(i)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (e *Encoder) EncodeMap(value reflect.Value) error {\n\tkeys := value.MapKeys()\n\tswitch l := value.Len(); {\n\tcase l < 16:\n\t\tif err := e.write([]byte{fixMapLowCode | byte(l)}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, k := range keys {\n\t\t\tif err := e.EncodeValue(k); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := e.EncodeValue(value.MapIndex(k)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\tcase l < 65536:\n\t\tif err := e.write([]byte{\n\t\t\tmap16Code,\n\t\t\tbyte(l >> 8),\n\t\t\tbyte(l),\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, k := range keys {\n\t\t\tif err := e.EncodeValue(k); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := e.EncodeValue(value.MapIndex(k)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tif err := e.write([]byte{\n\t\t\tmap32Code,\n\t\t\tbyte(l >> 24),\n\t\t\tbyte(l >> 16),\n\t\t\tbyte(l >> 8),\n\t\t\tbyte(l),\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, k := range keys {\n\t\t\tif err := e.EncodeValue(k); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := e.EncodeValue(value.MapIndex(k)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (e *Encoder) EncodeStruct(value reflect.Value) error {\n\tfields := reflectCache.Fields(value.Type())\n\tnum := len(fields)\n\tif num <= 0 {\n\t\treturn e.EncodeNil()\n\t}\n\n\tif err := e.write([]byte{\n\t\tmap32Code,\n\t\tbyte(num >> 24),\n\t\tbyte(num >> 16),\n\t\tbyte(num >> 8),\n\t\tbyte(num),\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, field := range fields {\n\t\tif err := e.EncodeBytes([]byte(field.Name)); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := e.EncodeValue(value.Field(field.Ind)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package topology\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/operation\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/security\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/needle\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/types\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/util\"\n)\n\nfunc ReplicatedWrite(masterFn operation.GetMasterFn, s *storage.Store, volumeId needle.VolumeId, n *needle.Needle, r *http.Request) (isUnchanged bool, err error) {\n\n\t\/\/check JWT\n\tjwt := security.GetJwt(r)\n\n\t\/\/ check whether this is a replicated write request\n\tvar remoteLocations []operation.Location\n\tif r.FormValue(\"type\") != \"replicate\" {\n\t\t\/\/ this is the initial request\n\t\tremoteLocations, err = getWritableRemoteReplications(s, volumeId, masterFn)\n\t\tif err != nil {\n\t\t\tglog.V(0).Infoln(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ read fsync value\n\tfsync := false\n\tif r.FormValue(\"fsync\") == \"true\" {\n\t\tfsync = true\n\t}\n\n\tif s.GetVolume(volumeId) != nil {\n\t\tisUnchanged, err = s.WriteVolumeNeedle(volumeId, n, fsync)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"failed to write to local disk: %v\", err)\n\t\t\tglog.V(0).Infoln(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif len(remoteLocations) > 0 { \/\/send to other replica locations\n\t\tif err = distributedOperation(remoteLocations, s, func(location operation.Location) error {\n\t\t\tu := url.URL{\n\t\t\t\tScheme: \"http\",\n\t\t\t\tHost:   location.Url,\n\t\t\t\tPath:   r.URL.Path,\n\t\t\t}\n\t\t\tq := url.Values{\n\t\t\t\t\"type\": {\"replicate\"},\n\t\t\t\t\"ttl\":  {n.Ttl.String()},\n\t\t\t}\n\t\t\tif n.LastModified > 0 {\n\t\t\t\tq.Set(\"ts\", strconv.FormatUint(n.LastModified, 10))\n\t\t\t}\n\t\t\tif n.IsChunkedManifest() {\n\t\t\t\tq.Set(\"cm\", \"true\")\n\t\t\t}\n\t\t\tu.RawQuery = q.Encode()\n\n\t\t\tpairMap := make(map[string]string)\n\t\t\tif n.HasPairs() {\n\t\t\t\ttmpMap := make(map[string]string)\n\t\t\t\terr := json.Unmarshal(n.Pairs, &tmpMap)\n\t\t\t\tif err != nil {\n\t\t\t\t\tglog.V(0).Infoln(\"Unmarshal pairs error:\", err)\n\t\t\t\t}\n\t\t\t\tfor k, v := range tmpMap {\n\t\t\t\t\tpairMap[needle.PairNamePrefix+k] = v\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ volume server do not know about encryption\n\t\t\t\/\/ TODO optimize here to compress data only once\n\t\t\t_, err := operation.UploadData(u.String(), string(n.Name), false, n.Data, n.IsCompressed(), string(n.Mime), pairMap, jwt)\n\t\t\treturn err\n\t\t}); err != nil {\n\t\t\terr = fmt.Errorf(\"failed to write to replicas for volume %d: %v\", volumeId, err)\n\t\t\tglog.V(0).Infoln(err)\n\t\t}\n\t}\n\treturn\n}\n\nfunc ReplicatedDelete(masterFn operation.GetMasterFn, store *storage.Store,\n\tvolumeId needle.VolumeId, n *needle.Needle,\n\tr *http.Request) (size types.Size, err error) {\n\n\t\/\/check JWT\n\tjwt := security.GetJwt(r)\n\n\tvar remoteLocations []operation.Location\n\tif r.FormValue(\"type\") != \"replicate\" {\n\t\tremoteLocations, err = getWritableRemoteReplications(store, volumeId, masterFn)\n\t\tif err != nil {\n\t\t\tglog.V(0).Infoln(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tsize, err = store.DeleteVolumeNeedle(volumeId, n)\n\tif err != nil {\n\t\tglog.V(0).Infoln(\"delete error:\", err)\n\t\treturn\n\t}\n\n\tif len(remoteLocations) > 0 { \/\/send to other replica locations\n\t\tif err = distributedOperation(remoteLocations, store, func(location operation.Location) error {\n\t\t\treturn util.Delete(\"http:\/\/\"+location.Url+r.URL.Path+\"?type=replicate\", string(jwt))\n\t\t}); err != nil {\n\t\t\tsize = 0\n\t\t}\n\t}\n\treturn\n}\n\ntype DistributedOperationResult map[string]error\n\nfunc (dr DistributedOperationResult) Error() error {\n\tvar errs []string\n\tfor k, v := range dr {\n\t\tif v != nil {\n\t\t\terrs = append(errs, fmt.Sprintf(\"[%s]: %v\", k, v))\n\t\t}\n\t}\n\tif len(errs) == 0 {\n\t\treturn nil\n\t}\n\treturn errors.New(strings.Join(errs, \"\\n\"))\n}\n\ntype RemoteResult struct {\n\tHost  string\n\tError error\n}\n\nfunc distributedOperation(locations []operation.Location, store *storage.Store, op func(location operation.Location) error) error {\n\tlength := len(locations)\n\tresults := make(chan RemoteResult)\n\tfor _, location := range locations {\n\t\tgo func(location operation.Location, results chan RemoteResult) {\n\t\t\tresults <- RemoteResult{location.Url, op(location)}\n\t\t}(location, results)\n\t}\n\tret := DistributedOperationResult(make(map[string]error))\n\tfor i := 0; i < length; i++ {\n\t\tresult := <-results\n\t\tret[result.Host] = result.Error\n\t}\n\n\treturn ret.Error()\n}\n\nfunc getWritableRemoteReplications(s *storage.Store, volumeId needle.VolumeId, masterFn operation.GetMasterFn) (\n\tremoteLocations []operation.Location, err error) {\n\n\tv := s.GetVolume(volumeId)\n\tif v != nil && v.ReplicaPlacement.GetCopyCount() == 1 {\n\t\treturn\n\t}\n\n\t\/\/ not on local store, or has replications\n\tlookupResult, lookupErr := operation.Lookup(masterFn, volumeId.String())\n\tif lookupErr == nil {\n\t\tselfUrl := s.Ip + \":\" + strconv.Itoa(s.Port)\n\t\tfor _, location := range lookupResult.Locations {\n\t\t\tif location.Url != selfUrl {\n\t\t\t\tremoteLocations = append(remoteLocations, location)\n\t\t\t}\n\t\t}\n\t} else {\n\t\terr = fmt.Errorf(\"failed to lookup for %d: %v\", volumeId, lookupErr)\n\t\treturn\n\t}\n\n\tif v != nil {\n\t\t\/\/ has one local and has remote replications\n\t\tcopyCount := v.ReplicaPlacement.GetCopyCount()\n\t\tif len(lookupResult.Locations) < copyCount {\n\t\t\terr = fmt.Errorf(\"replicating opetations [%d] is less than volume %d replication copy count [%d]\",\n\t\t\t\tlen(lookupResult.Locations), volumeId, copyCount)\n\t\t}\n\t}\n\n\treturn\n}\n<commit_msg>refactor<commit_after>package topology\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/operation\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/security\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/needle\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/types\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/util\"\n)\n\nfunc ReplicatedWrite(masterFn operation.GetMasterFn, s *storage.Store, volumeId needle.VolumeId, n *needle.Needle, r *http.Request) (isUnchanged bool, err error) {\n\n\t\/\/check JWT\n\tjwt := security.GetJwt(r)\n\n\t\/\/ check whether this is a replicated write request\n\tvar remoteLocations []operation.Location\n\tif r.FormValue(\"type\") != \"replicate\" {\n\t\t\/\/ this is the initial request\n\t\tremoteLocations, err = getWritableRemoteReplications(s, volumeId, masterFn)\n\t\tif err != nil {\n\t\t\tglog.V(0).Infoln(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ read fsync value\n\tfsync := false\n\tif r.FormValue(\"fsync\") == \"true\" {\n\t\tfsync = true\n\t}\n\n\tif s.GetVolume(volumeId) != nil {\n\t\tisUnchanged, err = s.WriteVolumeNeedle(volumeId, n, fsync)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"failed to write to local disk: %v\", err)\n\t\t\tglog.V(0).Infoln(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif len(remoteLocations) > 0 { \/\/send to other replica locations\n\t\tif err = DistributedOperation(remoteLocations, func(location operation.Location) error {\n\t\t\tu := url.URL{\n\t\t\t\tScheme: \"http\",\n\t\t\t\tHost:   location.Url,\n\t\t\t\tPath:   r.URL.Path,\n\t\t\t}\n\t\t\tq := url.Values{\n\t\t\t\t\"type\": {\"replicate\"},\n\t\t\t\t\"ttl\":  {n.Ttl.String()},\n\t\t\t}\n\t\t\tif n.LastModified > 0 {\n\t\t\t\tq.Set(\"ts\", strconv.FormatUint(n.LastModified, 10))\n\t\t\t}\n\t\t\tif n.IsChunkedManifest() {\n\t\t\t\tq.Set(\"cm\", \"true\")\n\t\t\t}\n\t\t\tu.RawQuery = q.Encode()\n\n\t\t\tpairMap := make(map[string]string)\n\t\t\tif n.HasPairs() {\n\t\t\t\ttmpMap := make(map[string]string)\n\t\t\t\terr := json.Unmarshal(n.Pairs, &tmpMap)\n\t\t\t\tif err != nil {\n\t\t\t\t\tglog.V(0).Infoln(\"Unmarshal pairs error:\", err)\n\t\t\t\t}\n\t\t\t\tfor k, v := range tmpMap {\n\t\t\t\t\tpairMap[needle.PairNamePrefix+k] = v\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ volume server do not know about encryption\n\t\t\t\/\/ TODO optimize here to compress data only once\n\t\t\t_, err := operation.UploadData(u.String(), string(n.Name), false, n.Data, n.IsCompressed(), string(n.Mime), pairMap, jwt)\n\t\t\treturn err\n\t\t}); err != nil {\n\t\t\terr = fmt.Errorf(\"failed to write to replicas for volume %d: %v\", volumeId, err)\n\t\t\tglog.V(0).Infoln(err)\n\t\t}\n\t}\n\treturn\n}\n\nfunc ReplicatedDelete(masterFn operation.GetMasterFn, store *storage.Store,\n\tvolumeId needle.VolumeId, n *needle.Needle,\n\tr *http.Request) (size types.Size, err error) {\n\n\t\/\/check JWT\n\tjwt := security.GetJwt(r)\n\n\tvar remoteLocations []operation.Location\n\tif r.FormValue(\"type\") != \"replicate\" {\n\t\tremoteLocations, err = getWritableRemoteReplications(store, volumeId, masterFn)\n\t\tif err != nil {\n\t\t\tglog.V(0).Infoln(err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tsize, err = store.DeleteVolumeNeedle(volumeId, n)\n\tif err != nil {\n\t\tglog.V(0).Infoln(\"delete error:\", err)\n\t\treturn\n\t}\n\n\tif len(remoteLocations) > 0 { \/\/send to other replica locations\n\t\tif err = DistributedOperation(remoteLocations, func(location operation.Location) error {\n\t\t\treturn util.Delete(\"http:\/\/\"+location.Url+r.URL.Path+\"?type=replicate\", string(jwt))\n\t\t}); err != nil {\n\t\t\tsize = 0\n\t\t}\n\t}\n\treturn\n}\n\ntype DistributedOperationResult map[string]error\n\nfunc (dr DistributedOperationResult) Error() error {\n\tvar errs []string\n\tfor k, v := range dr {\n\t\tif v != nil {\n\t\t\terrs = append(errs, fmt.Sprintf(\"[%s]: %v\", k, v))\n\t\t}\n\t}\n\tif len(errs) == 0 {\n\t\treturn nil\n\t}\n\treturn errors.New(strings.Join(errs, \"\\n\"))\n}\n\ntype RemoteResult struct {\n\tHost  string\n\tError error\n}\n\nfunc DistributedOperation(locations []operation.Location, op func(location operation.Location) error) error {\n\tlength := len(locations)\n\tresults := make(chan RemoteResult)\n\tfor _, location := range locations {\n\t\tgo func(location operation.Location, results chan RemoteResult) {\n\t\t\tresults <- RemoteResult{location.Url, op(location)}\n\t\t}(location, results)\n\t}\n\tret := DistributedOperationResult(make(map[string]error))\n\tfor i := 0; i < length; i++ {\n\t\tresult := <-results\n\t\tret[result.Host] = result.Error\n\t}\n\n\treturn ret.Error()\n}\n\nfunc getWritableRemoteReplications(s *storage.Store, volumeId needle.VolumeId, masterFn operation.GetMasterFn) (\n\tremoteLocations []operation.Location, err error) {\n\n\tv := s.GetVolume(volumeId)\n\tif v != nil && v.ReplicaPlacement.GetCopyCount() == 1 {\n\t\treturn\n\t}\n\n\t\/\/ not on local store, or has replications\n\tlookupResult, lookupErr := operation.Lookup(masterFn, volumeId.String())\n\tif lookupErr == nil {\n\t\tselfUrl := s.Ip + \":\" + strconv.Itoa(s.Port)\n\t\tfor _, location := range lookupResult.Locations {\n\t\t\tif location.Url != selfUrl {\n\t\t\t\tremoteLocations = append(remoteLocations, location)\n\t\t\t}\n\t\t}\n\t} else {\n\t\terr = fmt.Errorf(\"failed to lookup for %d: %v\", volumeId, lookupErr)\n\t\treturn\n\t}\n\n\tif v != nil {\n\t\t\/\/ has one local and has remote replications\n\t\tcopyCount := v.ReplicaPlacement.GetCopyCount()\n\t\tif len(lookupResult.Locations) < copyCount {\n\t\t\terr = fmt.Errorf(\"replicating opetations [%d] is less than volume %d replication copy count [%d]\",\n\t\t\t\tlen(lookupResult.Locations), volumeId, copyCount)\n\t\t}\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package internal\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/internal\"\n\tginkgoconfig \"github.com\/onsi\/ginkgo\/config\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gbytes\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n)\n\ntype TestUser struct {\n\tusername       string\n\tpassword       string\n\tcmdStarter     internal.Starter\n\ttimeout        time.Duration\n\tshouldKeepUser bool\n}\n\ntype UserConfig interface {\n\tGetUseExistingUser() bool\n\tGetExistingUser() string\n\tGetExistingUserPassword() string\n\tGetConfigurableTestPassword() string\n\tGetScaledTimeout(time.Duration) time.Duration\n\tGetShouldKeepUser() bool\n\tGetNamePrefix() string\n}\n\ntype AdminUserConfig interface {\n\tGetAdminUser() string\n\tGetAdminPassword() string\n}\n\nfunc NewTestUser(config UserConfig, cmdStarter internal.Starter) *TestUser {\n\tnode := ginkgoconfig.GinkgoConfig.ParallelNode\n\ttimeTag := time.Now().Format(\"2006_01_02-15h04m05.999s\")\n\n\tvar regUser, regUserPass string\n\tregUser = fmt.Sprintf(\"%s-USER-%d-%s\", config.GetNamePrefix(), node, timeTag)\n\tregUserPass = \"meow\"\n\n\tif config.GetUseExistingUser() {\n\t\tregUser = config.GetExistingUser()\n\t\tregUserPass = config.GetExistingUserPassword()\n\t}\n\n\tif config.GetConfigurableTestPassword() != \"\" {\n\t\tregUserPass = config.GetConfigurableTestPassword()\n\t}\n\n\treturn &TestUser{\n\t\tusername:       regUser,\n\t\tpassword:       regUserPass,\n\t\tcmdStarter:     cmdStarter,\n\t\ttimeout:        config.GetScaledTimeout(1 * time.Minute),\n\t\tshouldKeepUser: config.GetShouldKeepUser(),\n\t}\n}\n\nfunc NewAdminUser(config AdminUserConfig, cmdStarter internal.Starter) *TestUser {\n\treturn &TestUser{\n\t\tusername:   config.GetAdminUser(),\n\t\tpassword:   config.GetAdminPassword(),\n\t\tcmdStarter: cmdStarter,\n\t}\n}\n\nfunc (user *TestUser) Create() {\n\tsession := internal.Cf(user.cmdStarter, \"create-user\", user.username, user.password)\n\tEventuallyWithOffset(1, session, user.timeout).Should(Exit())\n\tif session.ExitCode() != 0 {\n\t\tExpectWithOffset(1, session.Out).Should(Say(\"scim_resource_already_exists\"))\n\t}\n}\n\nfunc (user *TestUser) Destroy() {\n\tsession := internal.Cf(user.cmdStarter, \"delete-user\", \"-f\", user.username)\n\tEventuallyWithOffset(1, session, user.timeout).Should(Exit(0))\n}\n\nfunc (user *TestUser) Username() string {\n\treturn user.username\n}\n\nfunc (user *TestUser) Password() string {\n\treturn user.password\n}\n\nfunc (user *TestUser) ShouldRemain() bool {\n\treturn user.shouldKeepUser\n}\n<commit_msg>Unexport UserConfig and AdminuserConfig interfaces<commit_after>package internal\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/internal\"\n\tginkgoconfig \"github.com\/onsi\/ginkgo\/config\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gbytes\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n)\n\ntype TestUser struct {\n\tusername       string\n\tpassword       string\n\tcmdStarter     internal.Starter\n\ttimeout        time.Duration\n\tshouldKeepUser bool\n}\n\ntype userConfig interface {\n\tGetUseExistingUser() bool\n\tGetExistingUser() string\n\tGetExistingUserPassword() string\n\tGetConfigurableTestPassword() string\n\tGetScaledTimeout(time.Duration) time.Duration\n\tGetShouldKeepUser() bool\n\tGetNamePrefix() string\n}\n\ntype adminuserConfig interface {\n\tGetAdminUser() string\n\tGetAdminPassword() string\n}\n\nfunc NewTestUser(config userConfig, cmdStarter internal.Starter) *TestUser {\n\tnode := ginkgoconfig.GinkgoConfig.ParallelNode\n\ttimeTag := time.Now().Format(\"2006_01_02-15h04m05.999s\")\n\n\tvar regUser, regUserPass string\n\tregUser = fmt.Sprintf(\"%s-USER-%d-%s\", config.GetNamePrefix(), node, timeTag)\n\tregUserPass = \"meow\"\n\n\tif config.GetUseExistingUser() {\n\t\tregUser = config.GetExistingUser()\n\t\tregUserPass = config.GetExistingUserPassword()\n\t}\n\n\tif config.GetConfigurableTestPassword() != \"\" {\n\t\tregUserPass = config.GetConfigurableTestPassword()\n\t}\n\n\treturn &TestUser{\n\t\tusername:       regUser,\n\t\tpassword:       regUserPass,\n\t\tcmdStarter:     cmdStarter,\n\t\ttimeout:        config.GetScaledTimeout(1 * time.Minute),\n\t\tshouldKeepUser: config.GetShouldKeepUser(),\n\t}\n}\n\nfunc NewAdminUser(config adminuserConfig, cmdStarter internal.Starter) *TestUser {\n\treturn &TestUser{\n\t\tusername:   config.GetAdminUser(),\n\t\tpassword:   config.GetAdminPassword(),\n\t\tcmdStarter: cmdStarter,\n\t}\n}\n\nfunc (user *TestUser) Create() {\n\tsession := internal.Cf(user.cmdStarter, \"create-user\", user.username, user.password)\n\tEventuallyWithOffset(1, session, user.timeout).Should(Exit())\n\tif session.ExitCode() != 0 {\n\t\tExpectWithOffset(1, session.Out).Should(Say(\"scim_resource_already_exists\"))\n\t}\n}\n\nfunc (user *TestUser) Destroy() {\n\tsession := internal.Cf(user.cmdStarter, \"delete-user\", \"-f\", user.username)\n\tEventuallyWithOffset(1, session, user.timeout).Should(Exit(0))\n}\n\nfunc (user *TestUser) Username() string {\n\treturn user.username\n}\n\nfunc (user *TestUser) Password() string {\n\treturn user.password\n}\n\nfunc (user *TestUser) ShouldRemain() bool {\n\treturn user.shouldKeepUser\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage table\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/osrg\/gobgp\/packet\"\n\t\"time\"\n)\n\ntype ProcessMessage struct {\n\tinnerMessage *bgp.BGPMessage\n\tfromPeer     *PeerInfo\n}\n\nfunc NewProcessMessage(m *bgp.BGPMessage, peerInfo *PeerInfo) *ProcessMessage {\n\treturn &ProcessMessage{\n\t\tinnerMessage: m,\n\t\tfromPeer:     peerInfo,\n\t}\n}\n\nfunc (p *ProcessMessage) nlri2Path(now time.Time) []Path {\n\tupdateMsg := p.innerMessage.Body.(*bgp.BGPUpdate)\n\tpathAttributes := updateMsg.PathAttributes\n\tpathList := make([]Path, 0)\n\tfor _, nlri_info := range updateMsg.NLRI {\n\t\t\/\/ define local variable to pass nlri's address to CreatePath\n\t\tvar nlri bgp.NLRInfo = nlri_info\n\t\t\/\/ create Path object\n\t\tpath := CreatePath(p.fromPeer, &nlri, pathAttributes, false, now)\n\t\tpathList = append(pathList, path)\n\t}\n\treturn pathList\n}\n\nfunc (p *ProcessMessage) withdraw2Path(now time.Time) []Path {\n\tupdateMsg := p.innerMessage.Body.(*bgp.BGPUpdate)\n\tpathAttributes := updateMsg.PathAttributes\n\tpathList := make([]Path, 0)\n\tfor _, nlriWithdraw := range updateMsg.WithdrawnRoutes {\n\t\t\/\/ define local variable to pass nlri's address to CreatePath\n\t\tvar w bgp.WithdrawnRoute = nlriWithdraw\n\t\t\/\/ create withdrawn Path object\n\t\tpath := CreatePath(p.fromPeer, &w, pathAttributes, true, now)\n\t\tpathList = append(pathList, path)\n\t}\n\treturn pathList\n}\n\nfunc (p *ProcessMessage) mpreachNlri2Path(now time.Time) []Path {\n\tupdateMsg := p.innerMessage.Body.(*bgp.BGPUpdate)\n\tpathAttributes := updateMsg.PathAttributes\n\tattrList := []*bgp.PathAttributeMpReachNLRI{}\n\n\tfor _, attr := range pathAttributes {\n\t\ta, ok := attr.(*bgp.PathAttributeMpReachNLRI)\n\t\tif ok {\n\t\t\tattrList = append(attrList, a)\n\t\t\tbreak\n\t\t}\n\t}\n\tpathList := make([]Path, 0)\n\n\tfor _, mp := range attrList {\n\t\tnlri_info := mp.Value\n\t\tfor _, nlri := range nlri_info {\n\t\t\tpath := CreatePath(p.fromPeer, nlri, pathAttributes, false, now)\n\t\t\tpathList = append(pathList, path)\n\t\t}\n\t}\n\treturn pathList\n}\n\nfunc (p *ProcessMessage) mpunreachNlri2Path(now time.Time) []Path {\n\tupdateMsg := p.innerMessage.Body.(*bgp.BGPUpdate)\n\tpathAttributes := updateMsg.PathAttributes\n\tattrList := []*bgp.PathAttributeMpUnreachNLRI{}\n\n\tfor _, attr := range pathAttributes {\n\t\ta, ok := attr.(*bgp.PathAttributeMpUnreachNLRI)\n\t\tif ok {\n\t\t\tattrList = append(attrList, a)\n\t\t\tbreak\n\t\t}\n\t}\n\tpathList := make([]Path, 0)\n\n\tfor _, mp := range attrList {\n\t\tnlri_info := mp.Value\n\n\t\tfor _, nlri := range nlri_info {\n\t\t\tpath := CreatePath(p.fromPeer, nlri, pathAttributes, true, now)\n\t\t\tpathList = append(pathList, path)\n\t\t}\n\t}\n\treturn pathList\n}\n\nfunc (p *ProcessMessage) ToPathList() []Path {\n\tpathList := make([]Path, 0)\n\tnow := time.Now()\n\tpathList = append(pathList, p.nlri2Path(now)...)\n\tpathList = append(pathList, p.withdraw2Path(now)...)\n\tpathList = append(pathList, p.mpreachNlri2Path(now)...)\n\tpathList = append(pathList, p.mpunreachNlri2Path(now)...)\n\treturn pathList\n}\n\ntype TableManager struct {\n\tTables   map[bgp.RouteFamily]Table\n\tlocalAsn uint32\n}\n\nfunc NewTableManager() *TableManager {\n\tt := &TableManager{}\n\tt.Tables = make(map[bgp.RouteFamily]Table)\n\tt.Tables[bgp.RF_IPv4_UC] = NewIPv4Table(0)\n\tt.Tables[bgp.RF_IPv6_UC] = NewIPv6Table(0)\n\treturn t\n}\n\nfunc (manager *TableManager) calculate(destinationList []Destination) ([]Path, []Path, error) {\n\tbestPaths := make([]Path, 0)\n\tlostPaths := make([]Path, 0)\n\n\tfor _, destination := range destinationList {\n\t\t\/\/ compute best path\n\t\tlog.Infof(\"Processing destination: %v\", destination.String())\n\t\tnewBestPath, reason, err := destination.Calculate(manager.localAsn)\n\n\t\tlog.Debugf(\"new best path: %v, reason=%v\", newBestPath, reason)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tdestination.setBestPathReason(reason)\n\t\tcurrentBestPath := destination.getBestPath()\n\n\t\tif newBestPath != nil && currentBestPath == newBestPath {\n\t\t\t\/\/ best path is not changed\n\t\t\tlog.Debug(\"best path is not changed\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif newBestPath == nil {\n\t\t\tlog.Debug(\"best path is nil\")\n\t\t\tif len(destination.getKnownPathList()) == 0 {\n\t\t\t\t\/\/ create withdraw path\n\t\t\t\tif currentBestPath != nil {\n\t\t\t\t\tlog.Debug(\"best path is lost\")\n\t\t\t\t\tp := destination.getBestPath()\n\t\t\t\t\tdestination.setOldBestPath(p)\n\t\t\t\t\tlostPaths = append(lostPaths, p.clone(true))\n\t\t\t\t}\n\t\t\t\tdestination.setBestPath(nil)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"known path list is not empty\")\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Debugf(\"new best path: NLRI: %v, next_hop=%v, reason=%v\",\n\t\t\t\tnewBestPath.getPrefix(),\n\t\t\t\tnewBestPath.getNexthop(),\n\t\t\t\treason)\n\n\t\t\tbestPaths = append(bestPaths, newBestPath)\n\t\t\tdestination.setBestPath(newBestPath)\n\t\t}\n\n\t\tif len(destination.getKnownPathList()) == 0 && destination.getBestPath() == nil {\n\t\t\trf := destination.getRouteFamily()\n\t\t\tt := manager.Tables[rf]\n\t\t\tdeleteDest(t, destination)\n\t\t\tlog.Debugf(\"destination removed route_family=%v, destination=%v\", rf, destination)\n\t\t}\n\t}\n\treturn bestPaths, lostPaths, nil\n}\n\nfunc (manager *TableManager) DeletePathsforPeer(peerInfo *PeerInfo) ([]Path, []Path, error) {\n\tdestinationList := manager.Tables[peerInfo.RF].DeleteDestByPeer(peerInfo)\n\treturn manager.calculate(destinationList)\n\n}\n\nfunc (manager *TableManager) ProcessPaths(pathList []Path) ([]Path, []Path, error) {\n\tdestinationList := make([]Destination, 0)\n\tfor _, path := range pathList {\n\t\trf := path.GetRouteFamily()\n\t\t\/\/ push Path into table\n\t\tdestination := insert(manager.Tables[rf], path)\n\t\tdestinationList = append(destinationList, destination)\n\t}\n\treturn manager.calculate(destinationList)\n}\n\n\/\/ process BGPUpdate message\n\/\/ this function processes only BGPUpdate\nfunc (manager *TableManager) ProcessUpdate(fromPeer *PeerInfo, message *bgp.BGPMessage) ([]Path, []Path, error) {\n\t\/\/ check msg's type if it's BGPUpdate\n\tif message.Header.Type != bgp.BGP_MSG_UPDATE {\n\t\tlog.Warn(\"message is not BGPUpdate\")\n\t\treturn []Path{}, []Path{}, nil\n\t}\n\n\tmsg := &ProcessMessage{\n\t\tinnerMessage: message,\n\t\tfromPeer:     fromPeer,\n\t}\n\n\treturn manager.ProcessPaths(msg.ToPathList())\n}\n\ntype AdjRib struct {\n\tadjRibIn  map[bgp.RouteFamily]map[string]*ReceivedRoute\n\tadjRibOut map[bgp.RouteFamily]map[string]*ReceivedRoute\n}\n\nfunc NewAdjRib() *AdjRib {\n\tr := &AdjRib{\n\t\tadjRibIn:  make(map[bgp.RouteFamily]map[string]*ReceivedRoute),\n\t\tadjRibOut: make(map[bgp.RouteFamily]map[string]*ReceivedRoute),\n\t}\n\tr.adjRibIn[bgp.RF_IPv4_UC] = make(map[string]*ReceivedRoute)\n\tr.adjRibIn[bgp.RF_IPv6_UC] = make(map[string]*ReceivedRoute)\n\tr.adjRibOut[bgp.RF_IPv4_UC] = make(map[string]*ReceivedRoute)\n\tr.adjRibOut[bgp.RF_IPv6_UC] = make(map[string]*ReceivedRoute)\n\treturn r\n}\n\nfunc (adj *AdjRib) update(rib map[bgp.RouteFamily]map[string]*ReceivedRoute, pathList []Path) {\n\tfor _, path := range pathList {\n\t\trf := path.GetRouteFamily()\n\t\tkey := path.getPrefix()\n\t\tif path.IsWithdraw() {\n\t\t\t_, found := rib[rf][key]\n\t\t\tif found {\n\t\t\t\tdelete(rib[rf], key)\n\t\t\t}\n\t\t} else {\n\t\t\trib[rf][key] = NewReceivedRoute(path, false)\n\t\t}\n\t}\n}\n\nfunc (adj *AdjRib) UpdateIn(pathList []Path) {\n\tadj.update(adj.adjRibIn, pathList)\n}\n\nfunc (adj *AdjRib) UpdateOut(pathList []Path) {\n\tadj.update(adj.adjRibOut, pathList)\n}\n\nfunc (adj *AdjRib) getPathList(rib map[string]*ReceivedRoute) []Path {\n\tpathList := []Path{}\n\n\tfor _, rr := range rib {\n\t\tpathList = append(pathList, rr.path)\n\t}\n\treturn pathList\n}\n\nfunc (adj *AdjRib) GetInPathList(rf bgp.RouteFamily) []Path {\n\treturn adj.getPathList(adj.adjRibIn[rf])\n}\n\nfunc (adj *AdjRib) GetOutPathList(rf bgp.RouteFamily) []Path {\n\treturn adj.getPathList(adj.adjRibOut[rf])\n}\n\nfunc (adj *AdjRib) GetInCount(rf bgp.RouteFamily) int {\n\treturn len(adj.adjRibIn[rf])\n}\n\nfunc (adj *AdjRib) GetOutCount(rf bgp.RouteFamily) int {\n\treturn len(adj.adjRibOut[rf])\n}\n\nfunc (adj *AdjRib) DropAllIn(rf bgp.RouteFamily) {\n\t\/\/ replace old one\n\tadj.adjRibIn[rf] = make(map[string]*ReceivedRoute)\n}\n\ntype ReceivedRoute struct {\n\tpath      Path\n\tfiltered  bool\n\ttimestamp time.Time\n}\n\nfunc (rr *ReceivedRoute) String() string {\n\treturn rr.path.(*PathDefault).getPrefix()\n}\n\nfunc NewReceivedRoute(path Path, filtered bool) *ReceivedRoute {\n\n\trroute := &ReceivedRoute{\n\t\tpath:      path,\n\t\tfiltered:  filtered,\n\t\ttimestamp: time.Now(),\n\t}\n\treturn rroute\n}\n<commit_msg>table: remove timestamp in ReceivedRoute<commit_after>\/\/ Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage table\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/osrg\/gobgp\/packet\"\n\t\"time\"\n)\n\ntype ProcessMessage struct {\n\tinnerMessage *bgp.BGPMessage\n\tfromPeer     *PeerInfo\n}\n\nfunc NewProcessMessage(m *bgp.BGPMessage, peerInfo *PeerInfo) *ProcessMessage {\n\treturn &ProcessMessage{\n\t\tinnerMessage: m,\n\t\tfromPeer:     peerInfo,\n\t}\n}\n\nfunc (p *ProcessMessage) nlri2Path(now time.Time) []Path {\n\tupdateMsg := p.innerMessage.Body.(*bgp.BGPUpdate)\n\tpathAttributes := updateMsg.PathAttributes\n\tpathList := make([]Path, 0)\n\tfor _, nlri_info := range updateMsg.NLRI {\n\t\t\/\/ define local variable to pass nlri's address to CreatePath\n\t\tvar nlri bgp.NLRInfo = nlri_info\n\t\t\/\/ create Path object\n\t\tpath := CreatePath(p.fromPeer, &nlri, pathAttributes, false, now)\n\t\tpathList = append(pathList, path)\n\t}\n\treturn pathList\n}\n\nfunc (p *ProcessMessage) withdraw2Path(now time.Time) []Path {\n\tupdateMsg := p.innerMessage.Body.(*bgp.BGPUpdate)\n\tpathAttributes := updateMsg.PathAttributes\n\tpathList := make([]Path, 0)\n\tfor _, nlriWithdraw := range updateMsg.WithdrawnRoutes {\n\t\t\/\/ define local variable to pass nlri's address to CreatePath\n\t\tvar w bgp.WithdrawnRoute = nlriWithdraw\n\t\t\/\/ create withdrawn Path object\n\t\tpath := CreatePath(p.fromPeer, &w, pathAttributes, true, now)\n\t\tpathList = append(pathList, path)\n\t}\n\treturn pathList\n}\n\nfunc (p *ProcessMessage) mpreachNlri2Path(now time.Time) []Path {\n\tupdateMsg := p.innerMessage.Body.(*bgp.BGPUpdate)\n\tpathAttributes := updateMsg.PathAttributes\n\tattrList := []*bgp.PathAttributeMpReachNLRI{}\n\n\tfor _, attr := range pathAttributes {\n\t\ta, ok := attr.(*bgp.PathAttributeMpReachNLRI)\n\t\tif ok {\n\t\t\tattrList = append(attrList, a)\n\t\t\tbreak\n\t\t}\n\t}\n\tpathList := make([]Path, 0)\n\n\tfor _, mp := range attrList {\n\t\tnlri_info := mp.Value\n\t\tfor _, nlri := range nlri_info {\n\t\t\tpath := CreatePath(p.fromPeer, nlri, pathAttributes, false, now)\n\t\t\tpathList = append(pathList, path)\n\t\t}\n\t}\n\treturn pathList\n}\n\nfunc (p *ProcessMessage) mpunreachNlri2Path(now time.Time) []Path {\n\tupdateMsg := p.innerMessage.Body.(*bgp.BGPUpdate)\n\tpathAttributes := updateMsg.PathAttributes\n\tattrList := []*bgp.PathAttributeMpUnreachNLRI{}\n\n\tfor _, attr := range pathAttributes {\n\t\ta, ok := attr.(*bgp.PathAttributeMpUnreachNLRI)\n\t\tif ok {\n\t\t\tattrList = append(attrList, a)\n\t\t\tbreak\n\t\t}\n\t}\n\tpathList := make([]Path, 0)\n\n\tfor _, mp := range attrList {\n\t\tnlri_info := mp.Value\n\n\t\tfor _, nlri := range nlri_info {\n\t\t\tpath := CreatePath(p.fromPeer, nlri, pathAttributes, true, now)\n\t\t\tpathList = append(pathList, path)\n\t\t}\n\t}\n\treturn pathList\n}\n\nfunc (p *ProcessMessage) ToPathList() []Path {\n\tpathList := make([]Path, 0)\n\tnow := time.Now()\n\tpathList = append(pathList, p.nlri2Path(now)...)\n\tpathList = append(pathList, p.withdraw2Path(now)...)\n\tpathList = append(pathList, p.mpreachNlri2Path(now)...)\n\tpathList = append(pathList, p.mpunreachNlri2Path(now)...)\n\treturn pathList\n}\n\ntype TableManager struct {\n\tTables   map[bgp.RouteFamily]Table\n\tlocalAsn uint32\n}\n\nfunc NewTableManager() *TableManager {\n\tt := &TableManager{}\n\tt.Tables = make(map[bgp.RouteFamily]Table)\n\tt.Tables[bgp.RF_IPv4_UC] = NewIPv4Table(0)\n\tt.Tables[bgp.RF_IPv6_UC] = NewIPv6Table(0)\n\treturn t\n}\n\nfunc (manager *TableManager) calculate(destinationList []Destination) ([]Path, []Path, error) {\n\tbestPaths := make([]Path, 0)\n\tlostPaths := make([]Path, 0)\n\n\tfor _, destination := range destinationList {\n\t\t\/\/ compute best path\n\t\tlog.Infof(\"Processing destination: %v\", destination.String())\n\t\tnewBestPath, reason, err := destination.Calculate(manager.localAsn)\n\n\t\tlog.Debugf(\"new best path: %v, reason=%v\", newBestPath, reason)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tdestination.setBestPathReason(reason)\n\t\tcurrentBestPath := destination.getBestPath()\n\n\t\tif newBestPath != nil && currentBestPath == newBestPath {\n\t\t\t\/\/ best path is not changed\n\t\t\tlog.Debug(\"best path is not changed\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif newBestPath == nil {\n\t\t\tlog.Debug(\"best path is nil\")\n\t\t\tif len(destination.getKnownPathList()) == 0 {\n\t\t\t\t\/\/ create withdraw path\n\t\t\t\tif currentBestPath != nil {\n\t\t\t\t\tlog.Debug(\"best path is lost\")\n\t\t\t\t\tp := destination.getBestPath()\n\t\t\t\t\tdestination.setOldBestPath(p)\n\t\t\t\t\tlostPaths = append(lostPaths, p.clone(true))\n\t\t\t\t}\n\t\t\t\tdestination.setBestPath(nil)\n\t\t\t} else {\n\t\t\t\tlog.Error(\"known path list is not empty\")\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Debugf(\"new best path: NLRI: %v, next_hop=%v, reason=%v\",\n\t\t\t\tnewBestPath.getPrefix(),\n\t\t\t\tnewBestPath.getNexthop(),\n\t\t\t\treason)\n\n\t\t\tbestPaths = append(bestPaths, newBestPath)\n\t\t\tdestination.setBestPath(newBestPath)\n\t\t}\n\n\t\tif len(destination.getKnownPathList()) == 0 && destination.getBestPath() == nil {\n\t\t\trf := destination.getRouteFamily()\n\t\t\tt := manager.Tables[rf]\n\t\t\tdeleteDest(t, destination)\n\t\t\tlog.Debugf(\"destination removed route_family=%v, destination=%v\", rf, destination)\n\t\t}\n\t}\n\treturn bestPaths, lostPaths, nil\n}\n\nfunc (manager *TableManager) DeletePathsforPeer(peerInfo *PeerInfo) ([]Path, []Path, error) {\n\tdestinationList := manager.Tables[peerInfo.RF].DeleteDestByPeer(peerInfo)\n\treturn manager.calculate(destinationList)\n\n}\n\nfunc (manager *TableManager) ProcessPaths(pathList []Path) ([]Path, []Path, error) {\n\tdestinationList := make([]Destination, 0)\n\tfor _, path := range pathList {\n\t\trf := path.GetRouteFamily()\n\t\t\/\/ push Path into table\n\t\tdestination := insert(manager.Tables[rf], path)\n\t\tdestinationList = append(destinationList, destination)\n\t}\n\treturn manager.calculate(destinationList)\n}\n\n\/\/ process BGPUpdate message\n\/\/ this function processes only BGPUpdate\nfunc (manager *TableManager) ProcessUpdate(fromPeer *PeerInfo, message *bgp.BGPMessage) ([]Path, []Path, error) {\n\t\/\/ check msg's type if it's BGPUpdate\n\tif message.Header.Type != bgp.BGP_MSG_UPDATE {\n\t\tlog.Warn(\"message is not BGPUpdate\")\n\t\treturn []Path{}, []Path{}, nil\n\t}\n\n\tmsg := &ProcessMessage{\n\t\tinnerMessage: message,\n\t\tfromPeer:     fromPeer,\n\t}\n\n\treturn manager.ProcessPaths(msg.ToPathList())\n}\n\ntype AdjRib struct {\n\tadjRibIn  map[bgp.RouteFamily]map[string]*ReceivedRoute\n\tadjRibOut map[bgp.RouteFamily]map[string]*ReceivedRoute\n}\n\nfunc NewAdjRib() *AdjRib {\n\tr := &AdjRib{\n\t\tadjRibIn:  make(map[bgp.RouteFamily]map[string]*ReceivedRoute),\n\t\tadjRibOut: make(map[bgp.RouteFamily]map[string]*ReceivedRoute),\n\t}\n\tr.adjRibIn[bgp.RF_IPv4_UC] = make(map[string]*ReceivedRoute)\n\tr.adjRibIn[bgp.RF_IPv6_UC] = make(map[string]*ReceivedRoute)\n\tr.adjRibOut[bgp.RF_IPv4_UC] = make(map[string]*ReceivedRoute)\n\tr.adjRibOut[bgp.RF_IPv6_UC] = make(map[string]*ReceivedRoute)\n\treturn r\n}\n\nfunc (adj *AdjRib) update(rib map[bgp.RouteFamily]map[string]*ReceivedRoute, pathList []Path) {\n\tfor _, path := range pathList {\n\t\trf := path.GetRouteFamily()\n\t\tkey := path.getPrefix()\n\t\tif path.IsWithdraw() {\n\t\t\t_, found := rib[rf][key]\n\t\t\tif found {\n\t\t\t\tdelete(rib[rf], key)\n\t\t\t}\n\t\t} else {\n\t\t\trib[rf][key] = NewReceivedRoute(path, false)\n\t\t}\n\t}\n}\n\nfunc (adj *AdjRib) UpdateIn(pathList []Path) {\n\tadj.update(adj.adjRibIn, pathList)\n}\n\nfunc (adj *AdjRib) UpdateOut(pathList []Path) {\n\tadj.update(adj.adjRibOut, pathList)\n}\n\nfunc (adj *AdjRib) getPathList(rib map[string]*ReceivedRoute) []Path {\n\tpathList := []Path{}\n\n\tfor _, rr := range rib {\n\t\tpathList = append(pathList, rr.path)\n\t}\n\treturn pathList\n}\n\nfunc (adj *AdjRib) GetInPathList(rf bgp.RouteFamily) []Path {\n\treturn adj.getPathList(adj.adjRibIn[rf])\n}\n\nfunc (adj *AdjRib) GetOutPathList(rf bgp.RouteFamily) []Path {\n\treturn adj.getPathList(adj.adjRibOut[rf])\n}\n\nfunc (adj *AdjRib) GetInCount(rf bgp.RouteFamily) int {\n\treturn len(adj.adjRibIn[rf])\n}\n\nfunc (adj *AdjRib) GetOutCount(rf bgp.RouteFamily) int {\n\treturn len(adj.adjRibOut[rf])\n}\n\nfunc (adj *AdjRib) DropAllIn(rf bgp.RouteFamily) {\n\t\/\/ replace old one\n\tadj.adjRibIn[rf] = make(map[string]*ReceivedRoute)\n}\n\ntype ReceivedRoute struct {\n\tpath      Path\n\tfiltered  bool\n}\n\nfunc (rr *ReceivedRoute) String() string {\n\treturn rr.path.(*PathDefault).getPrefix()\n}\n\nfunc NewReceivedRoute(path Path, filtered bool) *ReceivedRoute {\n\n\trroute := &ReceivedRoute{\n\t\tpath:      path,\n\t\tfiltered:  filtered,\n\t}\n\treturn rroute\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 The go-hep Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build !travis\n\npackage client\n\nimport (\n\t\"context\"\n\t\"testing\"\n)\n\nfunc testNewSubSession(t *testing.T, addr string) {\n\tsession, err := newSession(context.Background(), addr, \"gopher\", \"\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"could not create initialSession: %v\", err)\n\t}\n\tdefer session.Close()\n\n\tsubSession, err := newSubSession(context.Background(), session)\n\tif err != nil {\n\t\tt.Fatalf(\"could not create subSession: %v\", err)\n\t}\n\n\tif subSession.pathID == 0 {\n\t\tt.Fatalf(\"incorrect subSession.pathID value of 0 was received\")\n\t}\n}\n\nfunc TestNewSubSession(t *testing.T) {\n\tfor _, addr := range testClientAddrs {\n\t\tt.Run(addr, func(t *testing.T) {\n\t\t\ttestNewSubSession(t, addr)\n\t\t})\n\t}\n}\n<commit_msg>xrootd\/client: fix bind test<commit_after>\/\/ Copyright 2018 The go-hep Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build !travis\n\npackage client\n\nimport (\n\t\"context\"\n\t\"testing\"\n)\n\nfunc testNewSubSession(t *testing.T, addr string) {\n\tsession, err := newSession(context.Background(), addr, \"gopher\", \"\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"could not create initialSession: %v\", err)\n\t}\n\tdefer session.Close()\n\n\tsubSession, err := newSubSession(context.Background(), session)\n\tif err != nil {\n\t\tt.Fatalf(\"could not create subSession: %v\", err)\n\t}\n\n\tif subSession.pathID == 0 {\n\t\tt.Fatalf(\"incorrect subSession.pathID value of 0 was received\")\n\t}\n\n\tsession.subs[subSession.pathID] = subSession\n}\n\nfunc TestNewSubSession(t *testing.T) {\n\tfor _, addr := range testClientAddrs {\n\t\tt.Run(addr, func(t *testing.T) {\n\t\t\ttestNewSubSession(t, addr)\n\t\t})\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package dispatch\n\nimport \"fmt\"\n\n\/\/ ProtocolNotImplementError records an error when no Handler found by Request's\n\/\/ Protocol().\ntype ProtocolNotImplementError string\n\n\/\/ Error returns error infomation with the protocol.\nfunc (e ProtocolNotImplementError) Error() string {\n\treturn fmt.Sprintf(\"Protocol %s not implemented.\", e)\n}\n\n\/\/ DestNotFoundError records an error when no Dest found by Request's Address().\ntype DestNotFoundError string\n\n\/\/ Error returns error information with the address.\nfunc (e DestNotFoundError) Error() string {\n\treturn fmt.Sprintf(\"Dest %s not found.\", e)\n}\n\n\/\/ ContextCanceledError records an error when Context canceled before processing\n\/\/ a Request.\ntype ContextCanceledError struct{}\n\n\/\/ Error returns \"Context canceled.\"\nfunc (e ContextCanceledError) Error() string {\n\treturn \"Context canceled.\"\n}\n\n\/\/ PanicError records an error when panic occur when calling a Handler.\ntype PanicError struct {\n\terr   interface{}\n\tstack []byte\n}\n\n\/\/ Error returns panic information and debug stack.\nfunc (e PanicError) Error() string {\n\treturn fmt.Sprintf(\"PANIC: \\nInfomation: %v \\nStack: \\n%s\", e.err, string(e.stack))\n}\n<commit_msg>error type<commit_after>package dispatch\n\nimport \"fmt\"\n\n\/\/ ProtocolNotImplementError records an error when no Handler found by Request's\n\/\/ Protocol().\ntype ProtocolNotImplementError string\n\n\/\/ Error returns error infomation with the protocol.\nfunc (e ProtocolNotImplementError) Error() string {\n\treturn fmt.Sprintf(\"Protocol %s not implemented.\", string(e))\n}\n\n\/\/ DestNotFoundError records an error when no Dest found by Request's Address().\ntype DestNotFoundError string\n\n\/\/ Error returns error information with the address.\nfunc (e DestNotFoundError) Error() string {\n\treturn fmt.Sprintf(\"Dest %s not found.\", string(e))\n}\n\n\/\/ ContextCanceledError records an error when Context canceled before processing\n\/\/ a Request.\ntype ContextCanceledError struct{}\n\n\/\/ Error returns \"Context canceled.\"\nfunc (e ContextCanceledError) Error() string {\n\treturn \"Context canceled.\"\n}\n\n\/\/ PanicError records an error when panic occur when calling a Handler.\ntype PanicError struct {\n\terr   interface{}\n\tstack []byte\n}\n\n\/\/ Error returns panic information and debug stack.\nfunc (e PanicError) Error() string {\n\treturn fmt.Sprintf(\"PANIC: \\nInfomation: %v \\nStack: \\n%s\", e.err, string(e.stack))\n}\n<|endoftext|>"}
{"text":"<commit_before>package grohl\n\nimport (\n\t\"bytes\"\n\t\"reflect\"\n\t\"runtime\/debug\"\n)\n\ntype ErrorReporter interface {\n\tReport(err error, data Data) error\n}\n\n\/\/ Report writes the error to the ErrorReporter, or logs it if there is none.\nfunc (c *Context) Report(err error, data Data) error {\n\tmerged := c.Merge(data)\n\terrorToMap(err, merged)\n\n\tif c.ErrorReporter != nil {\n\t\treturn c.ErrorReporter.Report(err, merged)\n\t} else {\n\t\tvar logErr error\n\t\tlogErr = c.log(merged)\n\t\tif logErr != nil {\n\t\t\treturn logErr\n\t\t}\n\n\t\tfor _, line := range ErrorBacktraceLines(err) {\n\t\t\tlineData := dupeMaps(merged)\n\t\t\tlineData[\"site\"] = line\n\t\t\tlogErr = c.log(lineData)\n\t\t\tif logErr != nil {\n\t\t\t\treturn logErr\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}\n\n\/\/ ErrorBacktrace creates a backtrace of the call stack.\nfunc ErrorBacktrace(err error) string {\n\tlines := errorBacktraceBytes(err)\n\treturn string(bytes.Join(lines, byteLineBreak))\n}\n\n\/\/ ErrorBacktraceLines creates a backtrace of the call stack, split into lines.\nfunc ErrorBacktraceLines(err error) []string {\n\tbyteLines := errorBacktraceBytes(err)\n\tlines := make([]string, len(byteLines))\n\tfor i, byteline := range byteLines {\n\t\tlines[i] = string(byteline)\n\t}\n\treturn lines\n}\n\nfunc errorBacktraceBytes(err error) [][]byte {\n\tbacktrace := debug.Stack()\n\tall := bytes.Split(backtrace, byteLineBreak)\n\tif len(all) < 11 {\n\t\treturn all\n\t} else {\n\t\treturn all[10 : len(all)-1]\n\t}\n}\n\nfunc errorToMap(err error, data Data) {\n\tdata[\"at\"] = \"exception\"\n\tdata[\"class\"] = reflect.TypeOf(err).String()\n\tdata[\"message\"] = err.Error()\n}\n\nvar byteLineBreak = []byte{'\\n'}\n<commit_msg>Prevent issues with stacks exactly 11 deep<commit_after>package grohl\n\nimport (\n\t\"bytes\"\n\t\"reflect\"\n\t\"runtime\/debug\"\n)\n\ntype ErrorReporter interface {\n\tReport(err error, data Data) error\n}\n\n\/\/ Report writes the error to the ErrorReporter, or logs it if there is none.\nfunc (c *Context) Report(err error, data Data) error {\n\tmerged := c.Merge(data)\n\terrorToMap(err, merged)\n\n\tif c.ErrorReporter != nil {\n\t\treturn c.ErrorReporter.Report(err, merged)\n\t} else {\n\t\tvar logErr error\n\t\tlogErr = c.log(merged)\n\t\tif logErr != nil {\n\t\t\treturn logErr\n\t\t}\n\n\t\tfor _, line := range ErrorBacktraceLines(err) {\n\t\t\tlineData := dupeMaps(merged)\n\t\t\tlineData[\"site\"] = line\n\t\t\tlogErr = c.log(lineData)\n\t\t\tif logErr != nil {\n\t\t\t\treturn logErr\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}\n\n\/\/ ErrorBacktrace creates a backtrace of the call stack.\nfunc ErrorBacktrace(err error) string {\n\tlines := errorBacktraceBytes(err)\n\treturn string(bytes.Join(lines, byteLineBreak))\n}\n\n\/\/ ErrorBacktraceLines creates a backtrace of the call stack, split into lines.\nfunc ErrorBacktraceLines(err error) []string {\n\tbyteLines := errorBacktraceBytes(err)\n\tlines := make([]string, len(byteLines))\n\tfor i, byteline := range byteLines {\n\t\tlines[i] = string(byteline)\n\t}\n\treturn lines\n}\n\nfunc errorBacktraceBytes(err error) [][]byte {\n\tbacktrace := debug.Stack()\n\tall := bytes.Split(backtrace, byteLineBreak)\n\tif len(all) <= 10 {\n\t\treturn all\n\t} else {\n\t\treturn all[0:10]\n\t}\n}\n\nfunc errorToMap(err error, data Data) {\n\tdata[\"at\"] = \"exception\"\n\tdata[\"class\"] = reflect.TypeOf(err).String()\n\tdata[\"message\"] = err.Error()\n}\n\nvar byteLineBreak = []byte{'\\n'}\n<|endoftext|>"}
{"text":"<commit_before>package jwp\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n)\n\nfunc CheckHTTPStatus(res *http.Response, body []byte) (err error) {\n\tif res.StatusCode >= 400 && res.StatusCode < 600 {\n\t\tfmt.Println(\"\\t...\")\n\t\terr = errors.New(\"Status Code: \" + res.Status + \", Body: \" + string(body))\n\t}\n\treturn\n}\n\nfunc CheckStatus(status int) (err error) {\n\tswitch status {\n\tcase StatusSuccess:\n\t\terr = nil\n\tcase StatusNoSuchDriver:\n\t\terr = errors.New(\"StatusNoSuchDriver\")\n\n\tcase StatusNoSuchElement:\n\t\terr = errors.New(\"StatusNoSuchElement\")\n\n\tcase StatusNoSuchFrame:\n\t\terr = errors.New(\"StatusNoSuchFrame\")\n\n\tcase StatusUnknownCommand:\n\t\terr = errors.New(\"StatusUnknownCommand\")\n\n\tcase StatusStaleElementReference:\n\t\terr = errors.New(\"StatusStaleElementReference\")\n\n\tcase StatusElementNotVisible:\n\t\terr = errors.New(\"StatusElementNotVisible\")\n\n\tcase StatusInvalidElementState:\n\t\terr = errors.New(\"StatusInvalidElementState\")\n\n\tcase StatusUnknownError:\n\t\terr = errors.New(\"StatusUnknownError\")\n\n\tcase StatusElementIsNotSelectable:\n\t\terr = errors.New(\"StatusElementIsNotSelectable\")\n\n\tcase StatusJavaScriptError:\n\t\terr = errors.New(\"StatusJavaScriptError\")\n\n\tcase StatusXPathLookupError:\n\t\terr = errors.New(\"StatusXPathLookupError\")\n\n\tcase StatusTimeout:\n\t\terr = errors.New(\"StatusTimeout\")\n\n\tcase StatusNoSuchWindow:\n\t\terr = errors.New(\"StatusNoSuchWindow\")\n\n\tcase StatusInvalidCookieDomain:\n\t\terr = errors.New(\"StatusInvalidCookieDomain\")\n\n\tcase StatusUnableToSetCookie:\n\t\terr = errors.New(\"StatusUnableToSetCookie\")\n\n\tcase StatusUnexpectedAlertOpen:\n\t\terr = errors.New(\"StatusUnexpectedAlertOpen\")\n\n\tcase StatusNoAlertOpenError:\n\t\terr = errors.New(\"StatusNoAlertOpenError\")\n\n\tcase StatusScriptTimeout:\n\t\terr = errors.New(\"StatusScriptTimeout\")\n\n\tcase StatusInvalidElementCoordinates:\n\t\terr = errors.New(\"StatusInvalidElementCoordinates\")\n\n\tcase StatusIMEEngineActivationFailed:\n\t\terr = errors.New(\"StatusIMEEngineActivationFailed\")\n\n\tcase StatusInvalidSelector:\n\t\terr = errors.New(\"StatusInvalidSelector\")\n\n\tcase StatusSessionNotCreatedException:\n\t\terr = errors.New(\"StatusSessionNotCreatedException\")\n\n\tcase StatusMoveTargetOutOfBounds:\n\t\terr = errors.New(\"StatusMoveTargetOutOfBounds\")\n\t}\n\treturn\n}\n<commit_msg>Clear code.<commit_after>package jwp\n\nimport (\n\t\"errors\"\n\t\"net\/http\"\n)\n\nfunc CheckHTTPStatus(res *http.Response, body []byte) (err error) {\n\tif res.StatusCode >= 400 && res.StatusCode < 600 {\n\t\terr = errors.New(\"Status Code: \" + res.Status + \", Body: \" + string(body))\n\t}\n\treturn\n}\n\nfunc CheckStatus(status int) (err error) {\n\tswitch status {\n\tcase StatusSuccess:\n\t\terr = nil\n\tcase StatusNoSuchDriver:\n\t\terr = errors.New(\"StatusNoSuchDriver\")\n\n\tcase StatusNoSuchElement:\n\t\terr = errors.New(\"StatusNoSuchElement\")\n\n\tcase StatusNoSuchFrame:\n\t\terr = errors.New(\"StatusNoSuchFrame\")\n\n\tcase StatusUnknownCommand:\n\t\terr = errors.New(\"StatusUnknownCommand\")\n\n\tcase StatusStaleElementReference:\n\t\terr = errors.New(\"StatusStaleElementReference\")\n\n\tcase StatusElementNotVisible:\n\t\terr = errors.New(\"StatusElementNotVisible\")\n\n\tcase StatusInvalidElementState:\n\t\terr = errors.New(\"StatusInvalidElementState\")\n\n\tcase StatusUnknownError:\n\t\terr = errors.New(\"StatusUnknownError\")\n\n\tcase StatusElementIsNotSelectable:\n\t\terr = errors.New(\"StatusElementIsNotSelectable\")\n\n\tcase StatusJavaScriptError:\n\t\terr = errors.New(\"StatusJavaScriptError\")\n\n\tcase StatusXPathLookupError:\n\t\terr = errors.New(\"StatusXPathLookupError\")\n\n\tcase StatusTimeout:\n\t\terr = errors.New(\"StatusTimeout\")\n\n\tcase StatusNoSuchWindow:\n\t\terr = errors.New(\"StatusNoSuchWindow\")\n\n\tcase StatusInvalidCookieDomain:\n\t\terr = errors.New(\"StatusInvalidCookieDomain\")\n\n\tcase StatusUnableToSetCookie:\n\t\terr = errors.New(\"StatusUnableToSetCookie\")\n\n\tcase StatusUnexpectedAlertOpen:\n\t\terr = errors.New(\"StatusUnexpectedAlertOpen\")\n\n\tcase StatusNoAlertOpenError:\n\t\terr = errors.New(\"StatusNoAlertOpenError\")\n\n\tcase StatusScriptTimeout:\n\t\terr = errors.New(\"StatusScriptTimeout\")\n\n\tcase StatusInvalidElementCoordinates:\n\t\terr = errors.New(\"StatusInvalidElementCoordinates\")\n\n\tcase StatusIMEEngineActivationFailed:\n\t\terr = errors.New(\"StatusIMEEngineActivationFailed\")\n\n\tcase StatusInvalidSelector:\n\t\terr = errors.New(\"StatusInvalidSelector\")\n\n\tcase StatusSessionNotCreatedException:\n\t\terr = errors.New(\"StatusSessionNotCreatedException\")\n\n\tcase StatusMoveTargetOutOfBounds:\n\t\terr = errors.New(\"StatusMoveTargetOutOfBounds\")\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package gerrit\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"net\/url\"\n\t\"time\"\n)\n\n\/\/ PatchSet contains detailed information about a specific patch set.\n\/\/\n\/\/ Gerrit API docs: https:\/\/gerrit-review.googlesource.com\/Documentation\/json.html#patchSet\ntype PatchSet struct {\n\tNumber    string      `json:\"number\"`\n\tRevision  string      `json:\"revision\"`\n\tParents   []string    `json:\"parents\"`\n\tRef       string      `json:\"ref\"`\n\tUploader  AccountInfo `json:\"uploader\"`\n\tAuthor    AccountInfo `json:\"author\"`\n\tCreatedOn int         `json:\"createdOn\"`\n\tIsDraft   bool        `json:\"isDraft\"`\n\tKind      string      `json:\"kind\"`\n}\n\n\/\/ RefUpdate contains data about a reference update.\n\/\/\n\/\/ Gerrit API docs: https:\/\/gerrit-review.googlesource.com\/Documentation\/json.html#refUpdate\ntype RefUpdate struct {\n\tOldRev  string `json:\"oldRev\"`\n\tNewRev  string `json:\"newRev\"`\n\tRefName string `json:\"refName\"`\n\tProject string `json:\"project\"`\n}\n\n\/\/ EventInfo contains information about an event emitted by Gerrit.  This\n\/\/ structure can be used either when parsing streamed events or when reading\n\/\/ the output of the events-log plugin.\n\/\/\n\/\/ Gerrit API docs: https:\/\/gerrit-review.googlesource.com\/Documentation\/cmd-stream-events.html#events\ntype EventInfo struct {\n\tType           string        `json:\"type\"`\n\tChange         ChangeInfo    `json:\"change,omitempty\"`\n\tPatchSet       PatchSet      `json:\"patchSet,omitempty\"`\n\tEventCreatedOn int           `json:\"eventCreatedOn,omitempty\"`\n\tReason         string        `json:\"reason,omitempty\"`\n\tAbandoner      AccountInfo   `json:\"abandoner,omitempty\"`\n\tRestorer       AccountInfo   `json:\"restorer,omitempty\"`\n\tSubmitter      AccountInfo   `json:\"submitter,omitempty\"`\n\tAuthor         AccountInfo   `json:\"author,omitempty\"`\n\tUploader       AccountInfo   `json:\"uploader,omitempty\"`\n\tApprovals      []AccountInfo `json:\"approvals,omitempty\"`\n\tComment        string        `json:\"comment,omitempty\"`\n\tEditor         AccountInfo   `json:\"editor,omitempty\"`\n\tAdded          []string      `json:\"added,omitempty\"`\n\tRemoved        []string      `json:\"removed,omitempty\"`\n\tHashtags       []string      `json:\"hashtags,omitempty\"`\n\tRefUpdate      RefUpdate     `json:\"refUpdate,omitempty\"`\n\tProject        string        `json:\"project,omitempty\"`\n\tReviewer       AccountInfo   `json:\"reviewer,omitempty\"`\n\tOldTopic       string        `json:\"oldTopic,omitempty\"`\n\tChanger        AccountInfo   `json:\"changer,omitempty\"`\n}\n\n\/\/ EventsLogService contains functions for querying the API provided\n\/\/ by the optional events-log plugin.\ntype EventsLogService struct {\n\tclient *Client\n}\n\n\/\/ EventsLogOptions contains options for querying events from the events-logs\n\/\/ plugin.\ntype EventsLogOptions struct {\n\tFrom time.Time\n\tTo   time.Time\n}\n\n\/\/ getURL returns the url that should be used in the request.  This will vary\n\/\/ depending on the options provided to GetEvents.\nfunc (events *EventsLogService) getURL(options *EventsLogOptions) (string, error) {\n\tparsed, err := url.Parse(\"\/plugins\/events-log\/events\/\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tquery := parsed.Query()\n\n\tif !options.From.IsZero() {\n\t\tquery.Set(\"t1\", options.From.Format(\"2006-01-02 15:04:05\"))\n\t}\n\n\tif !options.To.IsZero() {\n\t\tquery.Set(\"t2\", options.To.Format(\"2006-01-02 15:04:05\"))\n\t}\n\n\treturn parsed.String(), nil\n}\n\n\/\/ GetEvents returns a list of events for the given input options.  Use of this\n\/\/ function an authenticated user.\n\/\/\n\/\/ Gerrit API docs: https:\/\/<yourserver>\/plugins\/events-log\/Documentation\/rest-api-events.html\nfunc (events *EventsLogService) GetEvents(options *EventsLogOptions) (*[]EventInfo, *Response, error) {\n\trequestURL, err := events.getURL(options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\trequest, err := events.client.NewRequest(\"GET\", requestURL, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Perform the request but do not pass in a structure to unpack\n\t\/\/ the response into.  The format of the response is one EventInfo\n\t\/\/ object per line so we need to manually handle the response here.\n\tresponse, err := events.client.Do(request, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\n\tdefer response.Body.Close()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\teventInfo := new([]EventInfo)\n\tfor _, line := range bytes.Split(body, []byte(\"\\n\")) {\n\t\tif len(line) > 0 {\n\t\t\tevent := EventInfo{}\n\t\t\terr := json.Unmarshal(line, &event)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\t*eventInfo = append(*eventInfo, event)\n\t\t}\n\t}\n\n\treturn eventInfo, response, err\n}\n<commit_msg>add url arguments as part of the raw query<commit_after>package gerrit\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"net\/url\"\n\t\"time\"\n)\n\n\/\/ PatchSet contains detailed information about a specific patch set.\n\/\/\n\/\/ Gerrit API docs: https:\/\/gerrit-review.googlesource.com\/Documentation\/json.html#patchSet\ntype PatchSet struct {\n\tNumber    string      `json:\"number\"`\n\tRevision  string      `json:\"revision\"`\n\tParents   []string    `json:\"parents\"`\n\tRef       string      `json:\"ref\"`\n\tUploader  AccountInfo `json:\"uploader\"`\n\tAuthor    AccountInfo `json:\"author\"`\n\tCreatedOn int         `json:\"createdOn\"`\n\tIsDraft   bool        `json:\"isDraft\"`\n\tKind      string      `json:\"kind\"`\n}\n\n\/\/ RefUpdate contains data about a reference update.\n\/\/\n\/\/ Gerrit API docs: https:\/\/gerrit-review.googlesource.com\/Documentation\/json.html#refUpdate\ntype RefUpdate struct {\n\tOldRev  string `json:\"oldRev\"`\n\tNewRev  string `json:\"newRev\"`\n\tRefName string `json:\"refName\"`\n\tProject string `json:\"project\"`\n}\n\n\/\/ EventInfo contains information about an event emitted by Gerrit.  This\n\/\/ structure can be used either when parsing streamed events or when reading\n\/\/ the output of the events-log plugin.\n\/\/\n\/\/ Gerrit API docs: https:\/\/gerrit-review.googlesource.com\/Documentation\/cmd-stream-events.html#events\ntype EventInfo struct {\n\tType           string        `json:\"type\"`\n\tChange         ChangeInfo    `json:\"change,omitempty\"`\n\tPatchSet       PatchSet      `json:\"patchSet,omitempty\"`\n\tEventCreatedOn int           `json:\"eventCreatedOn,omitempty\"`\n\tReason         string        `json:\"reason,omitempty\"`\n\tAbandoner      AccountInfo   `json:\"abandoner,omitempty\"`\n\tRestorer       AccountInfo   `json:\"restorer,omitempty\"`\n\tSubmitter      AccountInfo   `json:\"submitter,omitempty\"`\n\tAuthor         AccountInfo   `json:\"author,omitempty\"`\n\tUploader       AccountInfo   `json:\"uploader,omitempty\"`\n\tApprovals      []AccountInfo `json:\"approvals,omitempty\"`\n\tComment        string        `json:\"comment,omitempty\"`\n\tEditor         AccountInfo   `json:\"editor,omitempty\"`\n\tAdded          []string      `json:\"added,omitempty\"`\n\tRemoved        []string      `json:\"removed,omitempty\"`\n\tHashtags       []string      `json:\"hashtags,omitempty\"`\n\tRefUpdate      RefUpdate     `json:\"refUpdate,omitempty\"`\n\tProject        string        `json:\"project,omitempty\"`\n\tReviewer       AccountInfo   `json:\"reviewer,omitempty\"`\n\tOldTopic       string        `json:\"oldTopic,omitempty\"`\n\tChanger        AccountInfo   `json:\"changer,omitempty\"`\n}\n\n\/\/ EventsLogService contains functions for querying the API provided\n\/\/ by the optional events-log plugin.\ntype EventsLogService struct {\n\tclient *Client\n}\n\n\/\/ EventsLogOptions contains options for querying events from the events-logs\n\/\/ plugin.\ntype EventsLogOptions struct {\n\tFrom time.Time\n\tTo   time.Time\n}\n\n\/\/ getURL returns the url that should be used in the request.  This will vary\n\/\/ depending on the options provided to GetEvents.\nfunc (events *EventsLogService) getURL(options *EventsLogOptions) (string, error) {\n\tparsed, err := url.Parse(\"\/plugins\/events-log\/events\/\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tquery := parsed.Query()\n\n\tif !options.From.IsZero() {\n\t\tquery.Set(\"t1\", options.From.Format(\"2006-01-02 15:04:05\"))\n\t}\n\n\tif !options.To.IsZero() {\n\t\tquery.Set(\"t2\", options.To.Format(\"2006-01-02 15:04:05\"))\n\t}\n\n\tencoded := query.Encode()\n\tif len(encoded) > 0 {\n\t\tparsed.RawQuery = encoded\n\t}\n\n\treturn parsed.String(), nil\n}\n\n\/\/ GetEvents returns a list of events for the given input options.  Use of this\n\/\/ function an authenticated user.\n\/\/\n\/\/ Gerrit API docs: https:\/\/<yourserver>\/plugins\/events-log\/Documentation\/rest-api-events.html\nfunc (events *EventsLogService) GetEvents(options *EventsLogOptions) (*[]EventInfo, *Response, error) {\n\trequestURL, err := events.getURL(options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\trequest, err := events.client.NewRequest(\"GET\", requestURL, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Perform the request but do not pass in a structure to unpack\n\t\/\/ the response into.  The format of the response is one EventInfo\n\t\/\/ object per line so we need to manually handle the response here.\n\tresponse, err := events.client.Do(request, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tbody, err := ioutil.ReadAll(response.Body)\n\n\tdefer response.Body.Close()\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\teventInfo := new([]EventInfo)\n\tfor _, line := range bytes.Split(body, []byte(\"\\n\")) {\n\t\tif len(line) > 0 {\n\t\t\tevent := EventInfo{}\n\t\t\terr := json.Unmarshal(line, &event)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil, err\n\t\t\t}\n\t\t\t*eventInfo = append(*eventInfo, event)\n\t\t}\n\t}\n\n\treturn eventInfo, response, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 opentsdb-goclient authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\n\/\/ Package client defines the client and the corresponding\n\/\/ rest api implementaion of OpenTSDB.\n\/\/\n\/\/ query.go contains the structs and methods for the implementation of \/api\/query.\n\/\/\npackage client\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n)\n\n\/\/ QueryParam is the structure used to hold\n\/\/ the querying parameters when calling \/api\/query.\n\/\/ Each attributes in QueryParam matches the definition in\n\/\/ (http:\/\/opentsdb.net\/docs\/build\/html\/api_http\/query\/index.html).\n\/\/\ntype QueryParam struct {\n\t\/\/ The start time for the query. This can be a relative or absolute timestamp.\n\t\/\/ The data type can only be string, int, or int64.\n\t\/\/ The value is required with non-zero value of the target type.\n\tStart interface{} `json:\"start\"`\n\n\t\/\/ An end time for the query. If not supplied, the TSD will assume the local\n\t\/\/ system time on the server. This may be a relative or absolute timestamp.\n\t\/\/ The data type can only be string, or int64.\n\t\/\/ The value is optional.\n\tEnd interface{} `json:\"end,omitempty\"`\n\n\t\/\/ One or more sub queries used to select the time series to return.\n\t\/\/ These may be metric m or TSUID tsuids queries\n\t\/\/ The value is required with at least one element\n\tQueries []SubQuery `json:\"queries\"`\n\n\t\/\/ An optional value is used to show whether or not to return annotations with a query.\n\t\/\/ The default is to return annotations for the requested timespan but this flag can disable the return.\n\t\/\/ This affects both local and global notes and overrides globalAnnotations\n\tNoAnnotations bool `json:\"noAnnotations,omitempty\"`\n\n\t\/\/ An optional value is used to show whether or not the query should retrieve global\n\t\/\/ annotations for the requested timespan.\n\tGlobalAnnotations bool `json:\"globalAnnotations,omitempty\"`\n\n\t\/\/ An optional value is used to show whether or not to output data point timestamps in milliseconds or seconds.\n\t\/\/ If this flag is not provided and there are multiple data points within a second,\n\t\/\/ those data points will be down sampled using the query's aggregation function.\n\tMsResolution bool `json:\"msResolution,omitempty\"`\n\n\t\/\/ An optional value is used to show whether or not to output the TSUIDs associated with timeseries in the results.\n\t\/\/ If multiple time series were aggregated into one set, multiple TSUIDs will be returned in a sorted manner.\n\tShowTSUIDs bool `json:\"showTSUIDs,omitempty\"`\n}\n\nfunc (query *QueryParam) String() string {\n\tcontent, _ := json.Marshal(query)\n\treturn string(content)\n}\n\n\/\/ SubQuery is the structure used to hold\n\/\/ the subquery parameters when calling \/api\/query.\n\/\/ Each attributes in SubQuery matches the definition in\n\/\/ (http:\/\/opentsdb.net\/docs\/build\/html\/api_http\/query\/index.html).\n\/\/\ntype SubQuery struct {\n\t\/\/ The name of an aggregation function to use.\n\t\/\/ The value is required with non-empty one in the range of\n\t\/\/ the response of calling \/api\/aggregators.\n\tAggregator string `json:\"aggregator\"`\n\n\t\/\/ The name of a metric stored in the system.\n\t\/\/ The value is reqiured with non-empty value.\n\tMetric string `json:\"metric\"`\n\n\t\/\/ An optional value is used to show whether or not the data should be\n\t\/\/ converted into deltas before returning. This is useful if the metric is a\n\t\/\/ continously incrementing counter and you want to view the rate of change between data points.\n\tRate bool `json:\"rate,omitempty\"`\n\n\t\/\/ rateOptions represents monotonically increasing counter handling options.\n\t\/\/ The value is optional.\n\t\/\/ Currently there is only three kind of value can be set to this map:\n\t\/\/ Only three keys can be set into the rateOption parameter of the QueryParam is\n\t\/\/ QueryRateOptionCounter (value type is bool),  QueryRateOptionCounterMax (value type is int,int64)\n\t\/\/ QueryRateOptionResetValue (value type is int,int64)\n\tRateParams map[string]interface{} `json:\"rateOptions,omitempty\"`\n\n\t\/\/ An optional value downsampling function to reduce the amount of data returned.\n\tDownsample string `json:\"downsample,omitempty\"`\n\n\t\/\/ An optional value to drill down to specific timeseries or group results by tag,\n\t\/\/ supply one or more map values in the same format as the query string. Tags are converted to filters in 2.2.\n\t\/\/ Note that if no tags are specified, all metrics in the system will be aggregated into the results.\n\t\/\/ It will be deprecated in OpenTSDB 2.2.\n\tTags map[string]string `json:\"tags,omitempty\"`\n\n\t\/\/ An optional value used to filter the time series emitted in the results.\n\t\/\/ Note that if no filters are specified, all time series for the given\n\t\/\/ metric will be aggregated into the results.\n\tFiters []Filter `json:\"filters,omitempty\"`\n}\n\n\/\/ Filter is the structure used to hold the filter parameters when calling \/api\/query.\n\/\/ Each attributes in Filter matches the definition in\n\/\/ (http:\/\/opentsdb.net\/docs\/build\/html\/api_http\/query\/index.html).\n\/\/\ntype Filter struct {\n\t\/\/ The name of the filter to invoke. The value is required with a non-empty\n\t\/\/ value in the range of calling \/api\/config\/filters.\n\tType string `json:\"type\"`\n\n\t\/\/ The tag key to invoke the filter on, required with a non-empty value\n\tTagk string `json:\"tagk\"`\n\n\t\/\/ The filter expression to evaluate and depends on the filter being used, required with a non-empty value\n\tFilterExp string `json:\"filter\"`\n\n\t\/\/ An optional value to show whether or not to group the results by each value matched by the filter.\n\t\/\/ By default all values matching the filter will be aggregated into a single series.\n\tGroupBy bool `json:\"groupBy\"`\n}\n\n\/\/ QueryResponse acts as the implementation of Response in the \/api\/query scene.\n\/\/ It holds the status code and the response values defined in the\n\/\/ (http:\/\/opentsdb.net\/docs\/build\/html\/api_http\/query\/index.html).\n\/\/\ntype QueryResponse struct {\n\tStatusCode    int\n\tQueryRespCnts []QueryRespItem `json:\"queryRespCnts\"`\n}\n\nfunc (queryResp *QueryResponse) String() string {\n\tbuffer := bytes.NewBuffer(nil)\n\tcontent, _ := json.Marshal(queryResp)\n\tbuffer.WriteString(fmt.Sprintf(\"%s\\n\", string(content)))\n\treturn buffer.String()\n}\n\nfunc (queryResp *QueryResponse) SetStatus(code int) {\n\tqueryResp.StatusCode = code\n}\n\nfunc (queryResp *QueryResponse) GetCustomParser() func(respCnt []byte) error {\n\treturn func(respCnt []byte) error {\n\t\treturn json.Unmarshal([]byte(fmt.Sprintf(\"{%s:%s}\", `\"queryRespCnts\"`, string(respCnt))), &queryResp)\n\t}\n}\n\n\/\/ QueryRespItem acts as the implementation of Response in the \/api\/query scene.\n\/\/ It holds the response item defined in the\n\/\/ (http:\/\/opentsdb.net\/docs\/build\/html\/api_http\/query\/index.html).\n\/\/\ntype QueryRespItem struct {\n\t\/\/ Name of the metric retreived for the time series\n\tMetric string `json:\"metric\"`\n\n\t\/\/ A list of tags only returned when the results are for a single time series.\n\t\/\/ If results are aggregated, this value may be null or an empty map\n\tTags map[string]string `json:\"tags\"`\n\n\t\/\/ If more than one timeseries were included in the result set, i.e. they were aggregated,\n\t\/\/ this will display a list of tag names that were found in common across all time series.\n\t\/\/ Note that: Api Doc uses 'aggreatedTags', but actual response uses 'aggregateTags'\n\tAggregatedTags []string `json:\"aggregateTags\"`\n\n\t\/\/ Retrieved data points after being processed by the aggregators. Each data point consists\n\t\/\/ of a timestamp and a value, the format determined by the serializer.\n\t\/\/ For the JSON serializer, the timestamp will always be a Unix epoch style integer followed\n\t\/\/ by the value as an integer or a floating point.\n\t\/\/ For example, the default output is \"dps\"{\"<timestamp>\":<value>}.\n\t\/\/ By default the timestamps will be in seconds. If the msResolution flag is set, then the\n\t\/\/ timestamps will be in milliseconds.\n\tDps map[string]interface{} `json:\"dps\"`\n\n\t\/\/ If the query retrieved annotations for timeseries over the requested timespan, they will\n\t\/\/ be returned in this group. Annotations for every timeseries will be merged into one set\n\t\/\/ and sorted by start_time. Aggregator functions do not affect annotations, all annotations\n\t\/\/ will be returned for the span.\n\t\/\/ The value is optional.\n\tAnnotations []Annotation `json:\"annotations,omitempty\"`\n\n\t\/\/ If requested by the user, the query will scan for global annotations during\n\t\/\/ the timespan and the results returned in this group.\n\t\/\/ The value is optional.\n\tGlobalAnnotations []Annotation `json:\"globalAnnotations,omitempty\"`\n}\n\nfunc (c *clientImpl) Query(param QueryParam) (*QueryResponse, error) {\n\tif !isValidQueryParam(&param) {\n\t\treturn nil, errors.New(\"The given query param is invalid.\\n\")\n\t}\n\tqueryEndpoint := fmt.Sprintf(\"%s%s\", c.tsdbEndpoint, QueryPath)\n\treqBodyCnt, err := getQueryBodyContents(&param)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tqueryResp := QueryResponse{}\n\tif err = c.sendRequest(PostMethod, queryEndpoint, reqBodyCnt, &queryResp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &queryResp, nil\n}\n\nfunc getQueryBodyContents(param *QueryParam) (string, error) {\n\tresult, err := json.Marshal(param)\n\tif err != nil {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"Failed to marshal query param: %v\\n\", err))\n\t}\n\treturn string(result), nil\n}\n\nfunc isValidQueryParam(param *QueryParam) bool {\n\tif param.Queries == nil || len(param.Queries) == 0 {\n\t\treturn false\n\t}\n\tif !isValidTimePoint(param.Start) {\n\t\treturn false\n\t}\n\tfor _, query := range param.Queries {\n\t\tif len(query.Aggregator) == 0 || len(query.Metric) == 0 {\n\t\t\treturn false\n\t\t}\n\t\tfor k, _ := range query.RateParams {\n\t\t\tif k != QueryRateOptionCounter && k != QueryRateOptionCounterMax && k != QueryRateOptionResetValue {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\nfunc isValidTimePoint(timePoint interface{}) bool {\n\tif timePoint == nil {\n\t\treturn false\n\t}\n\tswitch v := timePoint.(type) {\n\tcase int:\n\t\tif v <= 0 {\n\t\t\treturn false\n\t\t}\n\tcase int64:\n\t\tif v <= 0 {\n\t\t\treturn false\n\t\t}\n\tcase string:\n\t\tif v == \"\" {\n\t\t\treturn false\n\t\t}\n\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}\n<commit_msg>Solve the problem that query datapoints and receive error<commit_after>\/\/ Copyright 2015 opentsdb-goclient authors. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\n\/\/ Package client defines the client and the corresponding\n\/\/ rest api implementaion of OpenTSDB.\n\/\/\n\/\/ query.go contains the structs and methods for the implementation of \/api\/query.\n\/\/\npackage client\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\/\/ QueryParam is the structure used to hold\n\/\/ the querying parameters when calling \/api\/query.\n\/\/ Each attributes in QueryParam matches the definition in\n\/\/ (http:\/\/opentsdb.net\/docs\/build\/html\/api_http\/query\/index.html).\n\/\/\ntype QueryParam struct {\n\t\/\/ The start time for the query. This can be a relative or absolute timestamp.\n\t\/\/ The data type can only be string, int, or int64.\n\t\/\/ The value is required with non-zero value of the target type.\n\tStart interface{} `json:\"start\"`\n\n\t\/\/ An end time for the query. If not supplied, the TSD will assume the local\n\t\/\/ system time on the server. This may be a relative or absolute timestamp.\n\t\/\/ The data type can only be string, or int64.\n\t\/\/ The value is optional.\n\tEnd interface{} `json:\"end,omitempty\"`\n\n\t\/\/ One or more sub queries used to select the time series to return.\n\t\/\/ These may be metric m or TSUID tsuids queries\n\t\/\/ The value is required with at least one element\n\tQueries []SubQuery `json:\"queries\"`\n\n\t\/\/ An optional value is used to show whether or not to return annotations with a query.\n\t\/\/ The default is to return annotations for the requested timespan but this flag can disable the return.\n\t\/\/ This affects both local and global notes and overrides globalAnnotations\n\tNoAnnotations bool `json:\"noAnnotations,omitempty\"`\n\n\t\/\/ An optional value is used to show whether or not the query should retrieve global\n\t\/\/ annotations for the requested timespan.\n\tGlobalAnnotations bool `json:\"globalAnnotations,omitempty\"`\n\n\t\/\/ An optional value is used to show whether or not to output data point timestamps in milliseconds or seconds.\n\t\/\/ If this flag is not provided and there are multiple data points within a second,\n\t\/\/ those data points will be down sampled using the query's aggregation function.\n\tMsResolution bool `json:\"msResolution,omitempty\"`\n\n\t\/\/ An optional value is used to show whether or not to output the TSUIDs associated with timeseries in the results.\n\t\/\/ If multiple time series were aggregated into one set, multiple TSUIDs will be returned in a sorted manner.\n\tShowTSUIDs bool `json:\"showTSUIDs,omitempty\"`\n}\n\nfunc (query *QueryParam) String() string {\n\tcontent, _ := json.Marshal(query)\n\treturn string(content)\n}\n\n\/\/ SubQuery is the structure used to hold\n\/\/ the subquery parameters when calling \/api\/query.\n\/\/ Each attributes in SubQuery matches the definition in\n\/\/ (http:\/\/opentsdb.net\/docs\/build\/html\/api_http\/query\/index.html).\n\/\/\ntype SubQuery struct {\n\t\/\/ The name of an aggregation function to use.\n\t\/\/ The value is required with non-empty one in the range of\n\t\/\/ the response of calling \/api\/aggregators.\n\tAggregator string `json:\"aggregator\"`\n\n\t\/\/ The name of a metric stored in the system.\n\t\/\/ The value is reqiured with non-empty value.\n\tMetric string `json:\"metric\"`\n\n\t\/\/ An optional value is used to show whether or not the data should be\n\t\/\/ converted into deltas before returning. This is useful if the metric is a\n\t\/\/ continously incrementing counter and you want to view the rate of change between data points.\n\tRate bool `json:\"rate,omitempty\"`\n\n\t\/\/ rateOptions represents monotonically increasing counter handling options.\n\t\/\/ The value is optional.\n\t\/\/ Currently there is only three kind of value can be set to this map:\n\t\/\/ Only three keys can be set into the rateOption parameter of the QueryParam is\n\t\/\/ QueryRateOptionCounter (value type is bool),  QueryRateOptionCounterMax (value type is int,int64)\n\t\/\/ QueryRateOptionResetValue (value type is int,int64)\n\tRateParams map[string]interface{} `json:\"rateOptions,omitempty\"`\n\n\t\/\/ An optional value downsampling function to reduce the amount of data returned.\n\tDownsample string `json:\"downsample,omitempty\"`\n\n\t\/\/ An optional value to drill down to specific timeseries or group results by tag,\n\t\/\/ supply one or more map values in the same format as the query string. Tags are converted to filters in 2.2.\n\t\/\/ Note that if no tags are specified, all metrics in the system will be aggregated into the results.\n\t\/\/ It will be deprecated in OpenTSDB 2.2.\n\tTags map[string]string `json:\"tags,omitempty\"`\n\n\t\/\/ An optional value used to filter the time series emitted in the results.\n\t\/\/ Note that if no filters are specified, all time series for the given\n\t\/\/ metric will be aggregated into the results.\n\tFiters []Filter `json:\"filters,omitempty\"`\n}\n\n\/\/ Filter is the structure used to hold the filter parameters when calling \/api\/query.\n\/\/ Each attributes in Filter matches the definition in\n\/\/ (http:\/\/opentsdb.net\/docs\/build\/html\/api_http\/query\/index.html).\n\/\/\ntype Filter struct {\n\t\/\/ The name of the filter to invoke. The value is required with a non-empty\n\t\/\/ value in the range of calling \/api\/config\/filters.\n\tType string `json:\"type\"`\n\n\t\/\/ The tag key to invoke the filter on, required with a non-empty value\n\tTagk string `json:\"tagk\"`\n\n\t\/\/ The filter expression to evaluate and depends on the filter being used, required with a non-empty value\n\tFilterExp string `json:\"filter\"`\n\n\t\/\/ An optional value to show whether or not to group the results by each value matched by the filter.\n\t\/\/ By default all values matching the filter will be aggregated into a single series.\n\tGroupBy bool `json:\"groupBy\"`\n}\n\n\/\/ QueryResponse acts as the implementation of Response in the \/api\/query scene.\n\/\/ It holds the status code and the response values defined in the\n\/\/ (http:\/\/opentsdb.net\/docs\/build\/html\/api_http\/query\/index.html).\n\/\/\ntype QueryResponse struct {\n\tStatusCode    int\n\tQueryRespCnts []QueryRespItem `json:\"queryRespCnts\"`\n\tErrorMsg      string          `json:\"errorMsg,omitempty\"`\n}\n\nfunc (queryResp *QueryResponse) String() string {\n\tbuffer := bytes.NewBuffer(nil)\n\tcontent, _ := json.Marshal(queryResp)\n\tbuffer.WriteString(fmt.Sprintf(\"%s\\n\", string(content)))\n\treturn buffer.String()\n}\n\nfunc (queryResp *QueryResponse) SetStatus(code int) {\n\tqueryResp.StatusCode = code\n}\n\nfunc (queryResp *QueryResponse) GetCustomParser() func(respCnt []byte) error {\n\treturn func(respCnt []byte) error {\n\t\toriginRespStr := string(respCnt)\n\t\tvar respStr string\n\t\tif queryResp.StatusCode == 200 && strings.Contains(originRespStr, \"[\") && strings.Contains(originRespStr, \"]\") {\n\t\t\trespStr = fmt.Sprintf(\"{%s:%s}\", `\"queryRespCnts\"`, originRespStr)\n\t\t} else {\n\t\t\trespStr = fmt.Sprintf(\"{%s:%s}\", `\"errorMsg\"`, originRespStr)\n\t\t}\n\t\treturn json.Unmarshal([]byte(respStr), &queryResp)\n\t}\n}\n\n\/\/ QueryRespItem acts as the implementation of Response in the \/api\/query scene.\n\/\/ It holds the response item defined in the\n\/\/ (http:\/\/opentsdb.net\/docs\/build\/html\/api_http\/query\/index.html).\n\/\/\ntype QueryRespItem struct {\n\t\/\/ Name of the metric retreived for the time series\n\tMetric string `json:\"metric\"`\n\n\t\/\/ A list of tags only returned when the results are for a single time series.\n\t\/\/ If results are aggregated, this value may be null or an empty map\n\tTags map[string]string `json:\"tags\"`\n\n\t\/\/ If more than one timeseries were included in the result set, i.e. they were aggregated,\n\t\/\/ this will display a list of tag names that were found in common across all time series.\n\t\/\/ Note that: Api Doc uses 'aggreatedTags', but actual response uses 'aggregateTags'\n\tAggregatedTags []string `json:\"aggregateTags\"`\n\n\t\/\/ Retrieved data points after being processed by the aggregators. Each data point consists\n\t\/\/ of a timestamp and a value, the format determined by the serializer.\n\t\/\/ For the JSON serializer, the timestamp will always be a Unix epoch style integer followed\n\t\/\/ by the value as an integer or a floating point.\n\t\/\/ For example, the default output is \"dps\"{\"<timestamp>\":<value>}.\n\t\/\/ By default the timestamps will be in seconds. If the msResolution flag is set, then the\n\t\/\/ timestamps will be in milliseconds.\n\tDps map[string]interface{} `json:\"dps\"`\n\n\t\/\/ If the query retrieved annotations for timeseries over the requested timespan, they will\n\t\/\/ be returned in this group. Annotations for every timeseries will be merged into one set\n\t\/\/ and sorted by start_time. Aggregator functions do not affect annotations, all annotations\n\t\/\/ will be returned for the span.\n\t\/\/ The value is optional.\n\tAnnotations []Annotation `json:\"annotations,omitempty\"`\n\n\t\/\/ If requested by the user, the query will scan for global annotations during\n\t\/\/ the timespan and the results returned in this group.\n\t\/\/ The value is optional.\n\tGlobalAnnotations []Annotation `json:\"globalAnnotations,omitempty\"`\n}\n\nfunc (c *clientImpl) Query(param QueryParam) (*QueryResponse, error) {\n\tif !isValidQueryParam(&param) {\n\t\treturn nil, errors.New(\"The given query param is invalid.\\n\")\n\t}\n\tqueryEndpoint := fmt.Sprintf(\"%s%s\", c.tsdbEndpoint, QueryPath)\n\treqBodyCnt, err := getQueryBodyContents(&param)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tqueryResp := QueryResponse{}\n\tif err = c.sendRequest(PostMethod, queryEndpoint, reqBodyCnt, &queryResp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &queryResp, nil\n}\n\nfunc getQueryBodyContents(param *QueryParam) (string, error) {\n\tresult, err := json.Marshal(param)\n\tif err != nil {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"Failed to marshal query param: %v\\n\", err))\n\t}\n\treturn string(result), nil\n}\n\nfunc isValidQueryParam(param *QueryParam) bool {\n\tif param.Queries == nil || len(param.Queries) == 0 {\n\t\treturn false\n\t}\n\tif !isValidTimePoint(param.Start) {\n\t\treturn false\n\t}\n\tfor _, query := range param.Queries {\n\t\tif len(query.Aggregator) == 0 || len(query.Metric) == 0 {\n\t\t\treturn false\n\t\t}\n\t\tfor k, _ := range query.RateParams {\n\t\t\tif k != QueryRateOptionCounter && k != QueryRateOptionCounterMax && k != QueryRateOptionResetValue {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n\nfunc isValidTimePoint(timePoint interface{}) bool {\n\tif timePoint == nil {\n\t\treturn false\n\t}\n\tswitch v := timePoint.(type) {\n\tcase int:\n\t\tif v <= 0 {\n\t\t\treturn false\n\t\t}\n\tcase int64:\n\t\tif v <= 0 {\n\t\t\treturn false\n\t\t}\n\tcase string:\n\t\tif v == \"\" {\n\t\t\treturn false\n\t\t}\n\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Factom Foundation\n\/\/ Use of this source code is governed by the MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage factom\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n)\n\n\/\/ FBlock represents a Factoid Block returned from factomd.\n\/\/ Note: the FBlock api return does not use a \"Header\" field like the other\n\/\/ block types do for some reason.\ntype FBlock struct {\n\tBodyMR          string `json:\"bodymr\"`          \/\/ Merkle root of the Factoid transactions which accompany this block.\n\tPrevKeyMR       string `json:\"prevkeymr\"`       \/\/ Key Merkle root of previous block.\n\tPrevLedgerKeyMR string `json:\"prevledgerkeymr\"` \/\/ Sha3 of the previous Factoid Block\n\tExchRate        int64  `json:\"exchrate\"`        \/\/ Factoshis per Entry Credit\n\tDBHeight        int64  `json:\"dbheight\"`        \/\/ Directory Block height\n\n\tTransactions []Transaction `json:\"transactions\"`\n}\n\nfunc (f *FBlock) String() string {\n\tvar s string\n\n\ts += fmt.Sprintln(\"BodyMR:\", f.BodyMR)\n\ts += fmt.Sprintln(\"PrevKeyMR:\", f.PrevKeyMR)\n\ts += fmt.Sprintln(\"PrevLedgerKeyMR:\", f.PrevLedgerKeyMR)\n\ts += fmt.Sprintln(\"ExchRate:\", f.ExchRate)\n\ts += fmt.Sprintln(\"DBHeight:\", f.DBHeight)\n\n\ts += fmt.Sprintln(\"Transactions {\")\n\tfor _, t := range f.Transactions {\n\t\ts += fmt.Sprintln(t)\n\t}\n\ts += fmt.Sprintln(\"}\")\n\n\treturn s\n}\n\n\/\/ GetFblock requests a specified Factoid Block from factomd.\nfunc GetFBlock(keymr string) (*FBlock, error) {\n\tparams := keyMRRequest{KeyMR: keymr}\n\treq := NewJSON2Request(\"factoid-block\", APICounter(), params)\n\tresp, err := factomdRequest(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.Error != nil {\n\t\treturn nil, resp.Error\n\t}\n\n\t\/\/ Create temporary struct to unmarshal json object\n\tf := new(struct {\n\t\tFBlock *FBlock `json:\"fblock\"`\n\t})\n\n\tif err := json.Unmarshal(resp.JSONResult(), f); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.FBlock, nil\n}\n<commit_msg>rename for wrapper type<commit_after>\/\/ Copyright 2016 Factom Foundation\n\/\/ Use of this source code is governed by the MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage factom\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n)\n\n\/\/ FBlock represents a Factoid Block returned from factomd.\n\/\/ Note: the FBlock api return does not use a \"Header\" field like the other\n\/\/ block types do for some reason.\ntype FBlock struct {\n\tBodyMR          string `json:\"bodymr\"`          \/\/ Merkle root of the Factoid transactions which accompany this block.\n\tPrevKeyMR       string `json:\"prevkeymr\"`       \/\/ Key Merkle root of previous block.\n\tPrevLedgerKeyMR string `json:\"prevledgerkeymr\"` \/\/ Sha3 of the previous Factoid Block\n\tExchRate        int64  `json:\"exchrate\"`        \/\/ Factoshis per Entry Credit\n\tDBHeight        int64  `json:\"dbheight\"`        \/\/ Directory Block height\n\n\tTransactions []Transaction `json:\"transactions\"`\n}\n\nfunc (f *FBlock) String() string {\n\tvar s string\n\n\ts += fmt.Sprintln(\"BodyMR:\", f.BodyMR)\n\ts += fmt.Sprintln(\"PrevKeyMR:\", f.PrevKeyMR)\n\ts += fmt.Sprintln(\"PrevLedgerKeyMR:\", f.PrevLedgerKeyMR)\n\ts += fmt.Sprintln(\"ExchRate:\", f.ExchRate)\n\ts += fmt.Sprintln(\"DBHeight:\", f.DBHeight)\n\n\ts += fmt.Sprintln(\"Transactions {\")\n\tfor _, t := range f.Transactions {\n\t\ts += fmt.Sprintln(t)\n\t}\n\ts += fmt.Sprintln(\"}\")\n\n\treturn s\n}\n\n\/\/ GetFblock requests a specified Factoid Block from factomd.\nfunc GetFBlock(keymr string) (*FBlock, error) {\n\tparams := keyMRRequest{KeyMR: keymr}\n\treq := NewJSON2Request(\"factoid-block\", APICounter(), params)\n\tresp, err := factomdRequest(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.Error != nil {\n\t\treturn nil, resp.Error\n\t}\n\n\t\/\/ Create temporary struct to unmarshal json object\n\twrap := new(struct {\n\t\tFBlock *FBlock `json:\"fblock\"`\n\t})\n\n\tif err := json.Unmarshal(resp.JSONResult(), wrap); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn wrap.FBlock, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package form\r\n\r\n\/\/ For keeping a list of enclosed functions for struct pointer fields.\r\ntype FieldFuncs map[string]func(m map[string]interface{})\r\n\r\n\/\/ Attemp to call a function in FieldFuncs. Does not call if function does not exist.\r\nfunc (fns FieldFuncs) Call(name string, m map[string]interface{}) {\r\n\tif fns[name] == nil {\r\n\t\treturn\r\n\t}\r\n\tfns[name](m)\r\n}\r\n\r\ntype Field struct {\r\n\tname  string\r\n\tfuncs FieldFuncs\r\n}\r\n\r\n\/\/ Fields\r\ntype Fields struct {\r\n\tm  map[string]FieldFuncs\r\n\tn  map[string]*Field\r\n\tnm map[string]*Field\r\n\tf  []*Field\r\n}\r\n\r\n\/\/ Init Field\r\nfunc (f *Fields) Init(fieldname string, typeCode TypeCode) FieldFuncs {\r\n\tif f.m[fieldname] != nil {\r\n\t\treturn f.m[fieldname]\r\n\t}\r\n\r\n\tfns := FieldFuncs{\r\n\t\t\"init\": func(m map[string]interface{}) {\r\n\t\t\t*(m[\"type\"].(*TypeCode)) = typeCode\r\n\t\t},\r\n\t}\r\n\tafield := &Field{fieldname, fns}\r\n\tif f.nm != nil {\r\n\t\tf.nm[fieldname] = afield\r\n\t}\r\n\tif f.n != nil {\r\n\t\tfns[\"set_name\"] = func(m map[string]interface{}) {\r\n\t\t\tname := m[\"set_name\"].(string)\r\n\t\t\tf.n[name] = afield\r\n\t\t}\r\n\t}\r\n\tf.m[fieldname] = fns\r\n\tf.f = append(f.f, afield)\r\n\treturn fns\r\n}\r\n<commit_msg>Slight improvement<commit_after>package form\r\n\r\n\/\/ For keeping a list of enclosed functions for struct pointer fields.\r\ntype FieldFuncs map[string]func(m map[string]interface{})\r\n\r\n\/\/ Attemp to call a function in FieldFuncs. Does not call if function does not exist.\r\nfunc (fns FieldFuncs) Call(name string, m map[string]interface{}) {\r\n\tif fns[name] == nil {\r\n\t\treturn\r\n\t}\r\n\tfns[name](m)\r\n}\r\n\r\ntype Field struct {\r\n\tname  string\r\n\tfuncs FieldFuncs\r\n}\r\n\r\n\/\/ Fields\r\ntype Fields struct {\r\n\tm  map[string]FieldFuncs\r\n\tn  map[string]*Field\r\n\tnm map[string]*Field\r\n\tf  []*Field\r\n}\r\n\r\n\/\/ Init Field\r\nfunc (f *Fields) Init(fieldname string, typeCode TypeCode) FieldFuncs {\r\n\tif f.m[fieldname] != nil {\r\n\t\treturn f.m[fieldname]\r\n\t}\r\n\r\n\tfns := FieldFuncs{\r\n\t\t\"init\": func(m map[string]interface{}) {\r\n\t\t\t*(m[\"type\"].(*TypeCode)) = typeCode\r\n\t\t},\r\n\t}\r\n\tafield := &Field{fieldname, fns}\r\n\tif f.nm != nil {\r\n\t\tf.nm[fieldname] = afield\r\n\t}\r\n\tif f.n != nil {\r\n\t\tfns[\"set_name\"] = func(m map[string]interface{}) {\r\n\t\t\tname := m[\"set_name\"].(string)\r\n\t\t\tf.n[name] = afield\r\n\t\t}\r\n\t}\r\n\tf.m[fieldname] = fns\r\n\tif f.f != nil {\r\n\t\tf.f = append(f.f, afield)\r\n\t}\r\n\treturn fns\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>package async\n\nimport (\n  \"reflect\"\n)\n\n\/*\n\n  Filter out information from a slice in Waterfall mode.\n\n  You must call the Done function with false as its first argument if you do\n  not want the data to be present in the results. No other arguments will\n  affect the performance of this function. When calling the Done function,\n  an error will cause the filtering to immediately exit.\n\n  For example, take a look at one of the tests for this function:\n    func TestFilterString(t *testing.T) {\n      str := []string{\n        \"test1\",\n        \"test2\",\n        \"test3\",\n        \"test4\",\n        \"test5\",\n      }\n\n      expects := []string{\n        \"test1\",\n        \"test2\",\n        \"test4\",\n        \"test5\",\n      }\n\n      mapper := func(done Done, args ...interface{}) {\n        Status(\"Hit string\")\n        Status(\"Args: %+v\\n\", args)\n        if args[0] == \"test3\" {\n          \/\/ We don't want this result in our return, so we send false back\n          \/\/ as the first argument.\n          done(nil, false)\n          return\n        }\n        \/\/ We want anything else that we get, so we return true here.\n        done(nil, true)\n      }\n\n      final := func(err error, results ...interface{}) {\n        Status(\"Hit string end\")\n        Status(\"Results: %+v\\n\", results)\n        for i := 0; i < len(results); i++ {\n          if results[i] != expects[i] {\n            t.Errorf(\"Did not filter correctly.\")\n            break\n          }\n        }\n      }\n\n      Filter(str, mapper, final)\n    }\n\n  Each Routine function will be passed the current value and its index the\n  slice for its arguments.\n\n*\/\nfunc Filter(data interface{}, routine Routine, callbacks ...Done) {\n  var (\n    routines []Routine\n    results  []interface{}\n  )\n\n  d := reflect.ValueOf(data)\n\n  for i := 0; i < d.Len(); i++ {\n    v := d.Index(i).Interface()\n    routines = append(routines, func(id int) Routine {\n      return func(done Done, args ...interface{}) {\n        done = func(original Done) Done {\n          return func(err error, args ...interface{}) {\n\n            if args[0] != false {\n              results = append(results, v)\n            }\n            if id == (d.Len() - 1) {\n              original(err, results...)\n              return\n            }\n            original(err, args...)\n          }\n        }(done)\n\n        routine(done, v, id)\n      }\n    }(i))\n  }\n\n  Waterfall(routines, callbacks...)\n}\n\n\/*\n\n  Filter out information from a slice in Parallel mode.\n\n  You must call the Done function with false as its first argument if you do\n  not want the data to be present in the results. No other arguments will\n  affect the performance of this function. When calling the Done function,\n  an error will cause the filtering to immediately exit.\n\n  For example, take a look at one of the tests for this function:\n    func TestFilterStringParallel(t *testing.T) {\n      str := []string{\n        \"test1\",\n        \"test2\",\n        \"test3\",\n        \"test4\",\n        \"test5\",\n      }\n\n      expects := []string{\n        \"test1\",\n        \"test2\",\n        \"test4\",\n        \"test5\",\n      }\n\n      mapper := func(done Done, args ...interface{}) {\n        Status(\"Hit string\")\n        Status(\"Args: %+v\\n\", args)\n        if args[0] == \"test3\" {\n          done(nil, false)\n          return\n        }\n        done(nil, true)\n      }\n\n      final := func(err error, results ...interface{}) {\n        Status(\"Hit string end\")\n        Status(\"Results: %+v\\n\", results)\n        for i := 0; i < len(results); i++ {\n          if results[i] != expects[i] {\n            t.Errorf(\"Did not filter correctly.\")\n            break\n          }\n        }\n      }\n\n      FilterParallel(str, mapper, final)\n    }\n\n  Each Routine function will be passed the current value and its index the\n  slice for its arguments.\n\n  The output of filtering in Parallel mode cannot be guaranteed to stay in the\n  same order, due to the fact that it may take longer to process some things\n  in your filter routine. If you need the data to stay in the order it is in,\n  use Filter instead to ensure it stays in order.\n\n*\/\nfunc FilterParallel(data interface{}, routine Routine, callbacks ...Done) {\n  var routines []Routine\n\n  d := reflect.ValueOf(data)\n\n  for i := 0; i < d.Len(); i++ {\n    v := d.Index(i).Interface()\n    routines = append(routines, func(id int) Routine {\n      return func(done Done, args ...interface{}) {\n        done = func(original Done) Done {\n          return func(err error, args ...interface{}) {\n            if args[0] != false {\n              original(err, v)\n            }\n          }\n        }(done)\n\n        routine(done, v, id)\n      }\n    }(i))\n  }\n\n  Parallel(routines, callbacks...)\n}\n<commit_msg>Ensure FilterParallel handles all data<commit_after>package async\n\nimport (\n  \"reflect\"\n)\n\n\/*\n\n  Filter out information from a slice in Waterfall mode.\n\n  You must call the Done function with false as its first argument if you do\n  not want the data to be present in the results. No other arguments will\n  affect the performance of this function. When calling the Done function,\n  an error will cause the filtering to immediately exit.\n\n  For example, take a look at one of the tests for this function:\n    func TestFilterString(t *testing.T) {\n      str := []string{\n        \"test1\",\n        \"test2\",\n        \"test3\",\n        \"test4\",\n        \"test5\",\n      }\n\n      expects := []string{\n        \"test1\",\n        \"test2\",\n        \"test4\",\n        \"test5\",\n      }\n\n      mapper := func(done Done, args ...interface{}) {\n        Status(\"Hit string\")\n        Status(\"Args: %+v\\n\", args)\n        if args[0] == \"test3\" {\n          \/\/ We don't want this result in our return, so we send false back\n          \/\/ as the first argument.\n          done(nil, false)\n          return\n        }\n        \/\/ We want anything else that we get, so we return true here.\n        done(nil, true)\n      }\n\n      final := func(err error, results ...interface{}) {\n        Status(\"Hit string end\")\n        Status(\"Results: %+v\\n\", results)\n        for i := 0; i < len(results); i++ {\n          if results[i] != expects[i] {\n            t.Errorf(\"Did not filter correctly.\")\n            break\n          }\n        }\n      }\n\n      Filter(str, mapper, final)\n    }\n\n  Each Routine function will be passed the current value and its index the\n  slice for its arguments.\n\n*\/\nfunc Filter(data interface{}, routine Routine, callbacks ...Done) {\n  var (\n    routines []Routine\n    results  []interface{}\n  )\n\n  d := reflect.ValueOf(data)\n\n  for i := 0; i < d.Len(); i++ {\n    v := d.Index(i).Interface()\n    routines = append(routines, func(id int) Routine {\n      return func(done Done, args ...interface{}) {\n        done = func(original Done) Done {\n          return func(err error, args ...interface{}) {\n            if args[0] != false {\n              results = append(results, v)\n            }\n            if id == (d.Len() - 1) {\n              original(err, results...)\n              return\n            }\n            original(err, args...)\n          }\n        }(done)\n\n        routine(done, v, id)\n      }\n    }(i))\n  }\n\n  Waterfall(routines, callbacks...)\n}\n\n\/*\n\n  Filter out information from a slice in Parallel mode.\n\n  You must call the Done function with false as its first argument if you do\n  not want the data to be present in the results. No other arguments will\n  affect the performance of this function. When calling the Done function,\n  an error will cause the filtering to immediately exit.\n\n  For example, take a look at one of the tests for this function:\n    func TestFilterStringParallel(t *testing.T) {\n      str := []string{\n        \"test1\",\n        \"test2\",\n        \"test3\",\n        \"test4\",\n        \"test5\",\n      }\n\n      expects := []string{\n        \"test1\",\n        \"test2\",\n        \"test4\",\n        \"test5\",\n      }\n\n      mapper := func(done Done, args ...interface{}) {\n        Status(\"Hit string\")\n        Status(\"Args: %+v\\n\", args)\n        if args[0] == \"test3\" {\n          done(nil, false)\n          return\n        }\n        done(nil, true)\n      }\n\n      final := func(err error, results ...interface{}) {\n        Status(\"Hit string end\")\n        Status(\"Results: %+v\\n\", results)\n        for i := 0; i < len(results); i++ {\n          if results[i] != expects[i] {\n            t.Errorf(\"Did not filter correctly.\")\n            break\n          }\n        }\n      }\n\n      FilterParallel(str, mapper, final)\n    }\n\n  Each Routine function will be passed the current value and its index the\n  slice for its arguments.\n\n  The output of filtering in Parallel mode cannot be guaranteed to stay in the\n  same order, due to the fact that it may take longer to process some things\n  in your filter routine. If you need the data to stay in the order it is in,\n  use Filter instead to ensure it stays in order.\n\n*\/\nfunc FilterParallel(data interface{}, routine Routine, callbacks ...Done) {\n  var routines []Routine\n\n  d := reflect.ValueOf(data)\n\n  for i := 0; i < d.Len(); i++ {\n    v := d.Index(i).Interface()\n    routines = append(routines, func(id int) Routine {\n      return func(done Done, args ...interface{}) {\n        done = func(original Done) Done {\n          return func(err error, args ...interface{}) {\n            if args[0] != false {\n              original(err, v)\n              return\n            }\n            original(err)\n          }\n        }(done)\n\n        routine(done, v, id)\n      }\n    }(i))\n  }\n\n  Parallel(routines, callbacks...)\n}\n<|endoftext|>"}
{"text":"<commit_before>package logrus_fluent\n\nimport (\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/fluent\/fluent-logger-golang\/fluent\"\n)\n\nconst (\n\tTagField     = \"tag\"\n\tMessageField = \"message\"\n\tDefaultTag   = \"log\"\n\n\tRFC3339Milli = \"2006-01-02T15:04:05.999Z07:00\"\n)\n\nvar defaultLevels = []logrus.Level{\n\tlogrus.PanicLevel,\n\tlogrus.FatalLevel,\n\tlogrus.ErrorLevel,\n\tlogrus.WarnLevel,\n\tlogrus.InfoLevel,\n}\n\ntype fluentHook struct {\n\tLogger *fluent.Fluent\n\tlevels []logrus.Level\n}\n\nfunc NewHook(host string, port int) (*fluentHook, error) {\n\tlogger, err := fluent.New(fluent.Config{\n\t\tFluentHost: host,\n\t\tFluentPort: port,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &fluentHook{\n\t\tLogger: logger,\n\t\tlevels: defaultLevels,\n\t}, nil\n}\n\nfunc getTagAndDel(entry *logrus.Entry) string {\n\tvar v interface{}\n\tvar ok bool\n\tif v, ok = entry.Data[TagField]; !ok {\n\t\treturn DefaultTag\n\t}\n\n\tvar val string\n\tif val, ok = v.(string); !ok {\n\t\treturn DefaultTag\n\t}\n\tdelete(entry.Data, TagField)\n\treturn val\n}\n\nfunc setLevelString(entry *logrus.Entry) {\n\tentry.Data[\"level\"] = entry.Level.String()\n}\n\nfunc setMessage(entry *logrus.Entry) {\n\tif _, ok := entry.Data[MessageField]; !ok {\n\t\tentry.Data[MessageField] = entry.Message\n\t}\n}\n\nfunc (hook *fluentHook) Fire(entry *logrus.Entry) error {\n\tsetLevelString(entry)\n\ttag := getTagAndDel(entry)\n\tsetMessage(entry)\n\n\tdata := ConvertFields(entry.Data)\n\tdata[\"@timestamp\"] = entry.Time.Format(RFC3339Milli)\n\treturn hook.Logger.PostWithTime(tag, entry.Time, data)\n}\n\nfunc (hook *fluentHook) Levels() []logrus.Level {\n\treturn hook.levels\n}\n\nfunc (hook *fluentHook) SetLevels(levels []logrus.Level) {\n\thook.levels = levels\n}\n<commit_msg>Switch to RFC3339Nano timestamp<commit_after>package logrus_fluent\n\nimport (\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/fluent\/fluent-logger-golang\/fluent\"\n)\n\nconst (\n\tTagField     = \"tag\"\n\tMessageField = \"message\"\n\tDefaultTag   = \"log\"\n)\n\nvar defaultLevels = []logrus.Level{\n\tlogrus.PanicLevel,\n\tlogrus.FatalLevel,\n\tlogrus.ErrorLevel,\n\tlogrus.WarnLevel,\n\tlogrus.InfoLevel,\n}\n\ntype fluentHook struct {\n\tLogger *fluent.Fluent\n\tlevels []logrus.Level\n}\n\nfunc NewHook(host string, port int) (*fluentHook, error) {\n\tlogger, err := fluent.New(fluent.Config{\n\t\tFluentHost: host,\n\t\tFluentPort: port,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &fluentHook{\n\t\tLogger: logger,\n\t\tlevels: defaultLevels,\n\t}, nil\n}\n\nfunc getTagAndDel(entry *logrus.Entry) string {\n\tvar v interface{}\n\tvar ok bool\n\tif v, ok = entry.Data[TagField]; !ok {\n\t\treturn DefaultTag\n\t}\n\n\tvar val string\n\tif val, ok = v.(string); !ok {\n\t\treturn DefaultTag\n\t}\n\tdelete(entry.Data, TagField)\n\treturn val\n}\n\nfunc setLevelString(entry *logrus.Entry) {\n\tentry.Data[\"level\"] = entry.Level.String()\n}\n\nfunc setMessage(entry *logrus.Entry) {\n\tif _, ok := entry.Data[MessageField]; !ok {\n\t\tentry.Data[MessageField] = entry.Message\n\t}\n}\n\nfunc (hook *fluentHook) Fire(entry *logrus.Entry) error {\n\tsetLevelString(entry)\n\ttag := getTagAndDel(entry)\n\tsetMessage(entry)\n\n\tdata := ConvertFields(entry.Data)\n\tdata[\"@timestamp\"] = entry.Time.UTC().Format(time.RFC3339Nano)\n\treturn hook.Logger.PostWithTime(tag, entry.Time, data)\n}\n\nfunc (hook *fluentHook) Levels() []logrus.Level {\n\treturn hook.levels\n}\n\nfunc (hook *fluentHook) SetLevels(levels []logrus.Level) {\n\thook.levels = levels\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package formam implements functions to decode values of a html form.\npackage formam\n\nimport (\n\t\"encoding\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst TAG_NAME = \"formam\"\n\n\/\/ A pathMap holds the values of a map with its key and values correspondent\ntype pathMap struct {\n\tm reflect.Value\n\n\tkey   string\n\tvalue reflect.Value\n\n\tpath string\n}\n\n\/\/ a pathMaps holds the values for each key\ntype pathMaps []*pathMap\n\n\/\/ find find and get the value by the given key\nfunc (ma pathMaps) find(id reflect.Value, key string) *pathMap {\n\tfor _, v := range ma {\n\t\tif v.m == id && v.key == key {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ A decoder holds the values from form, the 'reflect' value of main struct\n\/\/ and the 'reflect' value of current path\ntype decoder struct {\n\tmain reflect.Value\n\n\tcurr reflect.Value\n\ttyp  reflect.Type\n\n\tmaps pathMaps\n\n\tpath   string\n\tfield  string\n\tvalue  string\n\tvalues []string\n\tindex  int\n}\n\n\/\/ Decode decodes the url.Values into a element that must be a pointer to a type provided by argument\nfunc Decode(vs url.Values, dst interface{}) error {\n\tmain := reflect.ValueOf(dst)\n\tif main.Kind() != reflect.Ptr {\n\t\treturn fmt.Errorf(\"formam: the value passed for decode is not a pointer but a %v\", main.Kind())\n\t}\n\td := &decoder{main: main.Elem()}\n\tfor k, v := range vs {\n\t\td.path = k\n\t\td.field = k\n\t\td.values = v\n\t\td.value = v[0]\n\t\tif d.value != \"\" {\n\t\t\tif err := d.begin(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tfor _, v := range d.maps {\n\t\tkey := v.m.Type().Key()\n\t\tswitch key.Kind() {\n\t\tcase reflect.String:\n\t\t\t\/\/ the key is a string\n\t\t\tv.m.SetMapIndex(reflect.ValueOf(v.key), v.value)\n\t\tdefault:\n\t\t\t\/\/ must to implement the TextUnmarshaler interface for to can to decode the map's key\n\t\t\tvar vv reflect.Value\n\n\t\t\tif key.Kind() == reflect.Ptr {\n\t\t\t\tvv = reflect.New(key.Elem())\n\t\t\t} else {\n\t\t\t\tvv = reflect.New(key).Elem()\n\t\t\t}\n\n\t\t\td.value = v.key\n\t\t\tok, err := d.unmarshalText(vv)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"formam: the key with %s type (%v) in the path %v should implements the TextUnmarshaler interface for to can decode it\", key, v.m.Type(), v.path)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"formam: an error has occured in the UnmarshalText method for type %s: %s\", key, err)\n\t\t\t}\n\n\t\t\tv.m.SetMapIndex(vv, v.value)\n\t\t}\n\t}\n\td.maps = []*pathMap{}\n\treturn nil\n}\n\n\/\/ begin prepare the current path to walk through it\nfunc (d *decoder) begin() (err error) {\n\td.curr = d.main\n\tfields := strings.Split(d.field, \".\")\n\tfor i, field := range fields {\n\t\tb := strings.IndexAny(field, \"[\")\n\t\tif b != -1 {\n\t\t\t\/\/ is a array\n\t\t\te := strings.IndexAny(field, \"]\")\n\t\t\tif e == -1 {\n\t\t\t\treturn errors.New(\"formam: bad syntax array\")\n\t\t\t}\n\t\t\td.field = field[:b]\n\t\t\tif d.index, err = strconv.Atoi(field[b+1 : e]); err != nil {\n\t\t\t\treturn errors.New(\"formam: the index of array is not a number\")\n\t\t\t}\n\t\t\tif len(fields) == i+1 {\n\t\t\t\treturn d.end()\n\t\t\t}\n\t\t\tif err = d.walk(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ not is a array\n\t\t\td.field = field\n\t\t\td.index = -1\n\t\t\tif len(fields) == i+1 {\n\t\t\t\treturn d.end()\n\t\t\t}\n\t\t\tif err = d.walk(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ walk traverses the current path until to the last field\nfunc (d *decoder) walk() error {\n\t\/\/ check if is a struct or map\n\tswitch d.curr.Kind() {\n\tcase reflect.Struct:\n\t\tif err := d.findStructField(); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase reflect.Map:\n\t\td.currentMap()\n\t}\n\t\/\/ check if the struct or map is a interface\n\tif d.curr.Kind() == reflect.Interface {\n\t\td.curr = d.curr.Elem()\n\t}\n\t\/\/ check if the struct or map is a pointer\n\tif d.curr.Kind() == reflect.Ptr {\n\t\tif d.curr.IsNil() {\n\t\t\td.curr.Set(reflect.New(d.curr.Type().Elem()))\n\t\t}\n\t\td.curr = d.curr.Elem()\n\t}\n\t\/\/ finally, check if there are access to slice\/array or not...\n\tif d.index != -1 {\n\t\tswitch d.curr.Kind() {\n\t\tcase reflect.Slice, reflect.Array:\n\t\t\tif d.curr.Len() <= d.index {\n\t\t\t\td.expandSlice(d.index + 1)\n\t\t\t}\n\t\t\td.curr = d.curr.Index(d.index)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"formam: the field \\\"%v\\\" in path \\\"%v\\\" has a index for array but it is not\", d.field, d.path)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ end finds the last field for decode its value correspondent\nfunc (d *decoder) end() error {\n\tif d.curr.Kind() == reflect.Struct {\n\t\tif err := d.findStructField(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif d.value == \"\" {\n\t\treturn nil\n\t}\n\treturn d.decode()\n}\n\n\/\/ decode sets the value in the last field found by end function\nfunc (d *decoder) decode() error {\n\tok, err := d.unmarshalText(d.curr)\n\tif ok {\n\t\treturn err\n\t} else if err != nil {\n\t\treturn err\n\t}\n\n\tswitch d.curr.Kind() {\n\tcase reflect.Map:\n\t\td.currentMap()\n\t\treturn d.decode()\n\tcase reflect.Slice, reflect.Array:\n\t\tif d.index == -1 {\n\t\t\t\/\/ not has index, so to decode all values in the slice\/array\n\t\t\td.expandSlice(len(d.values))\n\t\t\ttmp := d.curr\n\t\t\tfor i, v := range d.values {\n\t\t\t\td.curr = tmp.Index(i)\n\t\t\t\td.value = v\n\t\t\t\tif err := d.decode(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\t\/\/ has index, so to decode value by index indicated\n\t\tif d.curr.Len() <= d.index {\n\t\t\td.expandSlice(d.index + 1)\n\t\t}\n\t\td.curr = d.curr.Index(d.index)\n\t\treturn d.decode()\n\tcase reflect.String:\n\t\td.curr.SetString(d.value)\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tif num, err := strconv.ParseInt(d.value, 10, 64); err != nil {\n\t\t\treturn fmt.Errorf(\"formam: the value of field \\\"%v\\\" in path \\\"%v\\\" should be a valid signed integer number\", d.field, d.path)\n\t\t} else {\n\t\t\td.curr.SetInt(num)\n\t\t}\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\tif num, err := strconv.ParseUint(d.value, 10, 64); err != nil {\n\t\t\treturn fmt.Errorf(\"formam: the value of field \\\"%v\\\" in path \\\"%v\\\" should be a valid unsigned integer number\", d.field, d.path)\n\t\t} else {\n\t\t\td.curr.SetUint(num)\n\t\t}\n\tcase reflect.Float32, reflect.Float64:\n\t\tif num, err := strconv.ParseFloat(d.value, d.curr.Type().Bits()); err != nil {\n\t\t\treturn fmt.Errorf(\"formam: the value of field \\\"%v\\\" in path \\\"%v\\\" should be a valid float number\", d.field, d.path)\n\t\t} else {\n\t\t\td.curr.SetFloat(num)\n\t\t}\n\tcase reflect.Bool:\n\t\tswitch d.value {\n\t\tcase \"true\", \"on\", \"1\":\n\t\t\td.curr.SetBool(true)\n\t\tcase \"false\", \"off\", \"0\":\n\t\t\td.curr.SetBool(false)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"formam: the value of field \\\"%v\\\" in path \\\"%v\\\" is not a valid boolean\", d.field, d.path)\n\t\t}\n\tcase reflect.Interface:\n\t\td.curr.Set(reflect.ValueOf(d.value))\n\tcase reflect.Ptr:\n\t\td.curr.Set(reflect.New(d.curr.Type().Elem()))\n\t\td.curr = d.curr.Elem()\n\t\treturn d.decode()\n\tcase reflect.Struct:\n\t\tswitch d.curr.Interface().(type) {\n\t\tcase time.Time:\n\t\t\tt, err := time.Parse(\"2006-01-02\", d.value)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"formam: the value of field \\\"%v\\\" in path \\\"%v\\\" is not a valid datetime\", d.field, d.path)\n\t\t\t}\n\t\t\td.curr.Set(reflect.ValueOf(t))\n\t\tcase url.URL:\n\t\t\tu, err := url.Parse(d.value)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"formam: the value of field \\\"%v\\\" in path \\\"%v\\\" is not a valid url\", d.field, d.path)\n\t\t\t}\n\t\t\td.curr.Set(reflect.ValueOf(*u))\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"formam: not supported type for field \\\"%v\\\" in path \\\"%v\\\"\", d.field, d.path)\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"formam: not supported type for field \\\"%v\\\" in path \\\"%v\\\"\", d.field, d.path)\n\t}\n\n\treturn nil\n}\n\n\/\/ findField finds a field by its name, if it is not found,\n\/\/ then retry the search examining the tag \"formam\" of every field of struct\nfunc (d *decoder) findStructField() error {\n\tvar anon reflect.Value\n\n\tnum := d.curr.NumField()\n\tfor i := 0; i < num; i++ {\n\t\tfield := d.curr.Type().Field(i)\n\t\tif field.Name == d.field {\n\t\t\t\/\/ check if the field's name is equal\n\t\t\td.curr = d.curr.Field(i)\n\t\t\treturn nil\n\t\t} else if field.Anonymous {\n\t\t\t\/\/ if the field is a anonymous struct, then iterate over its fields\n\t\t\ttmp := d.curr\n\t\t\td.curr = d.curr.FieldByIndex(field.Index)\n\t\t\tif err := d.findStructField(); err != nil {\n\t\t\t\td.curr = tmp\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ field in anonymous struct is found,\n\t\t\t\/\/ but first it should found the field in the rest of struct\n\t\t\t\/\/ (a field with same name in the current struct should have preference over anonymous struct)\n\t\t\tanon = d.curr\n\t\t\td.curr = tmp\n\t\t} else if d.field == field.Tag.Get(TAG_NAME) {\n\t\t\t\/\/ is not found yet, then retry by its tag name \"formam\"\n\t\t\td.curr = d.curr.Field(i)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif anon.IsValid() {\n\t\td.curr = anon\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"formam: not found the field \\\"%v\\\" in the path \\\"%v\\\"\", d.field, d.path)\n}\n\n\/\/ expandSlice expands the length and capacity of the current slice\nfunc (d *decoder) expandSlice(length int) {\n\tsli := reflect.MakeSlice(d.curr.Type(), length, length)\n\treflect.Copy(sli, d.curr)\n\td.curr.Set(sli)\n}\n\n\/\/ currentMap gets in d.curr the map concrete for decode the current value\nfunc (d *decoder) currentMap() {\n\ttyp := d.curr.Type()\n\tif d.curr.IsNil() {\n\t\td.curr.Set(reflect.MakeMap(typ))\n\t\tv := reflect.New(typ.Elem()).Elem()\n\t\td.maps = append(d.maps, &pathMap{d.curr, d.field, v, d.path})\n\t\td.curr = v\n\t} else if a := d.maps.find(d.curr, d.field); a == nil {\n\t\tv := reflect.New(typ.Elem()).Elem()\n\t\td.maps = append(d.maps, &pathMap{d.curr, d.field, v, d.path})\n\t\td.curr = v\n\t} else {\n\t\td.curr = a.value\n\t}\n}\n\nvar (\n\ttimeType  = reflect.TypeOf(time.Time{})\n\ttimePType = reflect.TypeOf(&time.Time{})\n)\n\n\/\/ unmarshalText returns a boolean and error. The boolean is true if the\n\/\/ value implements TextUnmarshaler, and false if not.\nfunc (d *decoder) unmarshalText(v reflect.Value) (bool, error) {\n\t\/\/ skip if the type is time.Time\n\ttyp := v.Type()\n\tif typ.ConvertibleTo(timeType) || typ.ConvertibleTo(timePType) {\n\t\treturn false, nil\n\t}\n\t\/\/ check if implements the interface\n\tt, ok := v.Interface().(encoding.TextUnmarshaler)\n\tcanAddr := v.CanAddr()\n\tif !ok && !canAddr {\n\t\treturn false, nil\n\t} else if canAddr {\n\t\treturn d.unmarshalText(v.Addr())\n\t}\n\t\/\/ return result\n\terr := t.UnmarshalText([]byte(d.value))\n\treturn true, err\n}\n<commit_msg>cleaner<commit_after>\/\/ Package formam implements functions to decode values of a html form.\npackage formam\n\nimport (\n\t\"encoding\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst TAG_NAME = \"formam\"\n\n\/\/ A pathMap holds the values of a map with its key and values correspondent\ntype pathMap struct {\n\tm reflect.Value\n\n\tkey   string\n\tvalue reflect.Value\n\n\tpath string\n}\n\n\/\/ a pathMaps holds the values for each key\ntype pathMaps []*pathMap\n\n\/\/ find find and get the value by the given key\nfunc (ma pathMaps) find(id reflect.Value, key string) *pathMap {\n\tfor _, v := range ma {\n\t\tif v.m == id && v.key == key {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ A decoder holds the values from form, the 'reflect' value of main struct\n\/\/ and the 'reflect' value of current path\ntype decoder struct {\n\tmain reflect.Value\n\n\tcurr   reflect.Value\n\tvalue  string\n\tvalues []string\n\n\tpath  string\n\tfield string\n\tindex int\n\n\tmaps pathMaps\n}\n\n\/\/ Decode decodes the url.Values into a element that must be a pointer to a type provided by argument\nfunc Decode(vs url.Values, dst interface{}) error {\n\tmain := reflect.ValueOf(dst)\n\tif main.Kind() != reflect.Ptr {\n\t\treturn fmt.Errorf(\"formam: the value passed for decode is not a pointer but a %v\", main.Kind())\n\t}\n\n\td := &decoder{main: main.Elem()}\n\n\t\/\/ iterate over the form's values and decode it (except the maps, maps are decoded at the end)\n\tfor k, v := range vs {\n\t\td.path = k\n\t\td.field = k\n\t\td.values = v\n\t\td.value = v[0]\n\t\tif d.value != \"\" {\n\t\t\tif err := d.begin(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ decode maps\n\tfor _, v := range d.maps {\n\t\tkey := v.m.Type().Key()\n\t\tswitch key.Kind() {\n\t\tcase reflect.String:\n\t\t\t\/\/ the key is a string\n\t\t\tv.m.SetMapIndex(reflect.ValueOf(v.key), v.value)\n\t\tdefault:\n\t\t\t\/\/ must to implement the TextUnmarshaler interface for to can to decode the map's key\n\t\t\tvar vv reflect.Value\n\n\t\t\tif key.Kind() == reflect.Ptr {\n\t\t\t\tvv = reflect.New(key.Elem())\n\t\t\t} else {\n\t\t\t\tvv = reflect.New(key).Elem()\n\t\t\t}\n\n\t\t\td.value = v.key\n\t\t\tif ok, err := d.unmarshalText(vv); !ok {\n\t\t\t\treturn fmt.Errorf(\"formam: the key with %s type (%v) in the path %v should implements the TextUnmarshaler interface for to can decode it\", key, v.m.Type(), v.path)\n\t\t\t} else if err != nil {\n\t\t\t\treturn fmt.Errorf(\"formam: an error has occured in the UnmarshalText method for type %s: %s\", key, err)\n\t\t\t}\n\n\t\t\tv.m.SetMapIndex(vv, v.value)\n\t\t}\n\t}\n\n\td.maps = []*pathMap{}\n\treturn nil\n}\n\n\/\/ begin prepare the current path to walk through it\nfunc (d *decoder) begin() (err error) {\n\td.curr = d.main\n\tfields := strings.Split(d.field, \".\")\n\tfor i, field := range fields {\n\t\tb := strings.IndexAny(field, \"[\")\n\t\tif b != -1 {\n\t\t\t\/\/ is a array\n\t\t\te := strings.IndexAny(field, \"]\")\n\t\t\tif e == -1 {\n\t\t\t\treturn errors.New(\"formam: bad syntax array\")\n\t\t\t}\n\t\t\td.field = field[:b]\n\t\t\tif d.index, err = strconv.Atoi(field[b+1 : e]); err != nil {\n\t\t\t\treturn errors.New(\"formam: the index of array is not a number\")\n\t\t\t}\n\t\t\tif len(fields) == i+1 {\n\t\t\t\treturn d.end()\n\t\t\t}\n\t\t\tif err = d.walk(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ not is a array\n\t\t\td.field = field\n\t\t\td.index = -1\n\t\t\tif len(fields) == i+1 {\n\t\t\t\treturn d.end()\n\t\t\t}\n\t\t\tif err = d.walk(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ walk traverses the current path until to the last field\nfunc (d *decoder) walk() error {\n\t\/\/ check if is a struct or map\n\tswitch d.curr.Kind() {\n\tcase reflect.Struct:\n\t\tif err := d.findStructField(); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase reflect.Map:\n\t\td.currentMap()\n\t}\n\t\/\/ check if the struct or map is a interface\n\tif d.curr.Kind() == reflect.Interface {\n\t\td.curr = d.curr.Elem()\n\t}\n\t\/\/ check if the struct or map is a pointer\n\tif d.curr.Kind() == reflect.Ptr {\n\t\tif d.curr.IsNil() {\n\t\t\td.curr.Set(reflect.New(d.curr.Type().Elem()))\n\t\t}\n\t\td.curr = d.curr.Elem()\n\t}\n\t\/\/ finally, check if there are access to slice\/array or not...\n\tif d.index != -1 {\n\t\tswitch d.curr.Kind() {\n\t\tcase reflect.Slice, reflect.Array:\n\t\t\tif d.curr.Len() <= d.index {\n\t\t\t\td.expandSlice(d.index + 1)\n\t\t\t}\n\t\t\td.curr = d.curr.Index(d.index)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"formam: the field \\\"%v\\\" in path \\\"%v\\\" has a index for array but it is not\", d.field, d.path)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ end finds the last field for decode its value correspondent\nfunc (d *decoder) end() error {\n\tif d.curr.Kind() == reflect.Struct {\n\t\tif err := d.findStructField(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif d.value == \"\" {\n\t\treturn nil\n\t}\n\treturn d.decode()\n}\n\n\/\/ decode sets the value in the last field found by end function\nfunc (d *decoder) decode() error {\n\tif ok, err := d.unmarshalText(d.curr); !ok && err != nil {\n\t\treturn err\n\t}\n\n\tswitch d.curr.Kind() {\n\tcase reflect.Map:\n\t\td.currentMap()\n\t\treturn d.decode()\n\tcase reflect.Slice, reflect.Array:\n\t\tif d.index == -1 {\n\t\t\t\/\/ not has index, so to decode all values in the slice\/array\n\t\t\td.expandSlice(len(d.values))\n\t\t\ttmp := d.curr\n\t\t\tfor i, v := range d.values {\n\t\t\t\td.curr = tmp.Index(i)\n\t\t\t\td.value = v\n\t\t\t\tif err := d.decode(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\t\/\/ has index, so to decode value by index indicated\n\t\tif d.curr.Len() <= d.index {\n\t\t\td.expandSlice(d.index + 1)\n\t\t}\n\t\td.curr = d.curr.Index(d.index)\n\t\treturn d.decode()\n\tcase reflect.String:\n\t\td.curr.SetString(d.value)\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\tif num, err := strconv.ParseInt(d.value, 10, 64); err != nil {\n\t\t\treturn fmt.Errorf(\"formam: the value of field \\\"%v\\\" in path \\\"%v\\\" should be a valid signed integer number\", d.field, d.path)\n\t\t} else {\n\t\t\td.curr.SetInt(num)\n\t\t}\n\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:\n\t\tif num, err := strconv.ParseUint(d.value, 10, 64); err != nil {\n\t\t\treturn fmt.Errorf(\"formam: the value of field \\\"%v\\\" in path \\\"%v\\\" should be a valid unsigned integer number\", d.field, d.path)\n\t\t} else {\n\t\t\td.curr.SetUint(num)\n\t\t}\n\tcase reflect.Float32, reflect.Float64:\n\t\tif num, err := strconv.ParseFloat(d.value, d.curr.Type().Bits()); err != nil {\n\t\t\treturn fmt.Errorf(\"formam: the value of field \\\"%v\\\" in path \\\"%v\\\" should be a valid float number\", d.field, d.path)\n\t\t} else {\n\t\t\td.curr.SetFloat(num)\n\t\t}\n\tcase reflect.Bool:\n\t\tswitch d.value {\n\t\tcase \"true\", \"on\", \"1\":\n\t\t\td.curr.SetBool(true)\n\t\tcase \"false\", \"off\", \"0\":\n\t\t\td.curr.SetBool(false)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"formam: the value of field \\\"%v\\\" in path \\\"%v\\\" is not a valid boolean\", d.field, d.path)\n\t\t}\n\tcase reflect.Interface:\n\t\td.curr.Set(reflect.ValueOf(d.value))\n\tcase reflect.Ptr:\n\t\td.curr.Set(reflect.New(d.curr.Type().Elem()))\n\t\td.curr = d.curr.Elem()\n\t\treturn d.decode()\n\tcase reflect.Struct:\n\t\tswitch d.curr.Interface().(type) {\n\t\tcase time.Time:\n\t\t\tt, err := time.Parse(\"2006-01-02\", d.value)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"formam: the value of field \\\"%v\\\" in path \\\"%v\\\" is not a valid datetime\", d.field, d.path)\n\t\t\t}\n\t\t\td.curr.Set(reflect.ValueOf(t))\n\t\tcase url.URL:\n\t\t\tu, err := url.Parse(d.value)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"formam: the value of field \\\"%v\\\" in path \\\"%v\\\" is not a valid url\", d.field, d.path)\n\t\t\t}\n\t\t\td.curr.Set(reflect.ValueOf(*u))\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"formam: not supported type for field \\\"%v\\\" in path \\\"%v\\\"\", d.field, d.path)\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"formam: not supported type for field \\\"%v\\\" in path \\\"%v\\\"\", d.field, d.path)\n\t}\n\n\treturn nil\n}\n\n\/\/ findField finds a field by its name, if it is not found,\n\/\/ then retry the search examining the tag \"formam\" of every field of struct\nfunc (d *decoder) findStructField() error {\n\tvar anon reflect.Value\n\n\tnum := d.curr.NumField()\n\tfor i := 0; i < num; i++ {\n\t\tfield := d.curr.Type().Field(i)\n\t\tif field.Name == d.field {\n\t\t\t\/\/ check if the field's name is equal\n\t\t\td.curr = d.curr.Field(i)\n\t\t\treturn nil\n\t\t} else if field.Anonymous {\n\t\t\t\/\/ if the field is a anonymous struct, then iterate over its fields\n\t\t\ttmp := d.curr\n\t\t\td.curr = d.curr.FieldByIndex(field.Index)\n\t\t\tif err := d.findStructField(); err != nil {\n\t\t\t\td.curr = tmp\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ field in anonymous struct is found,\n\t\t\t\/\/ but first it should found the field in the rest of struct\n\t\t\t\/\/ (a field with same name in the current struct should have preference over anonymous struct)\n\t\t\tanon = d.curr\n\t\t\td.curr = tmp\n\t\t} else if d.field == field.Tag.Get(TAG_NAME) {\n\t\t\t\/\/ is not found yet, then retry by its tag name \"formam\"\n\t\t\td.curr = d.curr.Field(i)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif anon.IsValid() {\n\t\td.curr = anon\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"formam: not found the field \\\"%v\\\" in the path \\\"%v\\\"\", d.field, d.path)\n}\n\n\/\/ expandSlice expands the length and capacity of the current slice\nfunc (d *decoder) expandSlice(length int) {\n\tsli := reflect.MakeSlice(d.curr.Type(), length, length)\n\treflect.Copy(sli, d.curr)\n\td.curr.Set(sli)\n}\n\n\/\/ currentMap gets in d.curr the map concrete for decode the current value\nfunc (d *decoder) currentMap() {\n\ttyp := d.curr.Type()\n\tif d.curr.IsNil() {\n\t\td.curr.Set(reflect.MakeMap(typ))\n\t\tv := reflect.New(typ.Elem()).Elem()\n\t\td.maps = append(d.maps, &pathMap{d.curr, d.field, v, d.path})\n\t\td.curr = v\n\t} else if a := d.maps.find(d.curr, d.field); a == nil {\n\t\tv := reflect.New(typ.Elem()).Elem()\n\t\td.maps = append(d.maps, &pathMap{d.curr, d.field, v, d.path})\n\t\td.curr = v\n\t} else {\n\t\td.curr = a.value\n\t}\n}\n\nvar (\n\ttimeType  = reflect.TypeOf(time.Time{})\n\ttimePType = reflect.TypeOf(&time.Time{})\n)\n\n\/\/ unmarshalText returns a boolean and error. The boolean is true if the\n\/\/ value implements TextUnmarshaler, and false if not.\nfunc (d *decoder) unmarshalText(v reflect.Value) (bool, error) {\n\t\/\/ skip if the type is time.Time\n\ttyp := v.Type()\n\tif typ.ConvertibleTo(timeType) || typ.ConvertibleTo(timePType) {\n\t\treturn false, nil\n\t}\n\t\/\/ check if implements the interface\n\tt, ok := v.Interface().(encoding.TextUnmarshaler)\n\tcanAddr := v.CanAddr()\n\tif !ok && !canAddr {\n\t\treturn false, nil\n\t} else if canAddr {\n\t\treturn d.unmarshalText(v.Addr())\n\t}\n\t\/\/ return result\n\terr := t.UnmarshalText([]byte(d.value))\n\treturn true, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013, Örjan Persson. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage logging\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ TODO see Formatter interface in fmt\/print.go\n\/\/ TODO try text\/template, maybe it have enough performance\n\/\/ TODO other template systems?\n\/\/ TODO make it possible to specify formats per backend?\ntype fmtVerb int\n\nconst (\n\tfmtVerbTime fmtVerb = iota\n\tfmtVerbLevel\n\tfmtVerbId\n\tfmtVerbModule\n\tfmtVerbMessage\n\tfmtVerbLongfile\n\tfmtVerbShortfile\n\n\t\/\/ Keep last, there are no match for these below.\n\tfmtVerbUnknown\n\tfmtVerbStatic\n)\n\nvar fmtVerbs = []string{\n\t\"time\",\n\t\"level\",\n\t\"id\",\n\t\"module\",\n\t\"message\",\n\t\"longfile\",\n\t\"shortfile\",\n}\n\nvar defaultVerbsLayout = []string{\n\t\"2006-01-02T15:04:05.999Z07:00\",\n\t\"s\",\n\t\"d\",\n\t\"s\",\n\t\"s\",\n\t\"s\",\n\t\"s\",\n}\n\nfunc getFmtVerbByName(name string) fmtVerb {\n\tfor i, verb := range fmtVerbs {\n\t\tif name == verb {\n\t\t\treturn fmtVerb(i)\n\t\t}\n\t}\n\treturn fmtVerbUnknown\n}\n\n\/\/ Formatter is the required interface for a custom log record formatter.\ntype Formatter interface {\n\tFormat(calldepth int, r *Record, w io.Writer) error\n}\n\n\/\/ formatter is used by all backends unless otherwise overriden.\nvar formatter struct {\n\tsync.RWMutex\n\tdef Formatter\n}\n\nfunc getFormatter() Formatter {\n\tformatter.RLock()\n\tdefer formatter.RUnlock()\n\treturn formatter.def\n}\n\nvar (\n\t\/\/ DefaultFormatter is the default formatter used and is only the message.\n\tDefaultFormatter Formatter = MustStringFormatter(\"%{message}\")\n\n\t\/\/ TODO add filename and line\n\t\/\/ GlogFormatter Formatter = MustStringFormatter(\"%{level:.1}%%{time:0102 15:04:05.99999} 0 %{file}:%{line} %{message}\")\n)\n\n\/\/ SetFormatter sets the default formatter for all new backends. A backend will\n\/\/ fetch this value once it is needed to format a record. Note that backends\n\/\/ will cache the formatter after the first point. For now, make sure to set\n\/\/ the formatter before logging.\nfunc SetFormatter(f Formatter) {\n\tformatter.Lock()\n\tdefer formatter.Unlock()\n\tformatter.def = f\n}\n\n\/\/ TODO use ${} instead?\nvar formatRe *regexp.Regexp = regexp.MustCompile(`%{([a-z]+)(?::(.*?[^\\\\]))?}`)\n\ntype part struct {\n\tverb   fmtVerb\n\tlayout string\n}\n\n\/\/ stringFormatter contains a list of parts which explains how to build the\n\/\/ formatted string passed on to the logging backend.\ntype stringFormatter struct {\n\tparts []part\n}\n\n\/\/ NewStringFormatter returns a new Formatter which outputs the log record as a\n\/\/ string based on the 'verbs' specified in the format string.\n\/\/\n\/\/ The verbs:\n\/\/\n\/\/ General:\n\/\/     %{id}        Sequence number for log message (uint64).\n\/\/     %{time}      Time when log occurred (time.Time)\n\/\/     %{level}     Log level (Level)\n\/\/     %{module}    Module (string)\n\/\/     %{message}   Message (string)\n\/\/     %{longfile}  Full file name and line number: \/a\/b\/c\/d.go:23\n\/\/     %{shortfile} Final file name element and line number: d.go:23\n\/\/\n\/\/ For normal types, the output can be customized by using the 'verbs' defined\n\/\/ in the fmt package, eg. '%{id:04d}' to make the id output be '%04d' as the\n\/\/ format string.\n\/\/\n\/\/ For time.Time, use the same layout as time.Format to change the time format\n\/\/ when output, eg \"2006-01-02T15:04:05.999Z-07:00\".\nfunc NewStringFormatter(format string) (*stringFormatter, error) {\n\tvar fmter = &stringFormatter{}\n\n\t\/\/ Find the boundaries of all %{vars}\n\tmatches := formatRe.FindAllStringSubmatchIndex(format, -1)\n\tif matches == nil {\n\t\treturn nil, errors.New(\"logger: invalid log format: \" + format)\n\t}\n\n\t\/\/ Collect all variables and static text for the format\n\tprev := 0\n\tfor _, m := range matches {\n\t\tstart, end := m[0], m[1]\n\t\tif start > prev {\n\t\t\tfmter.add(fmtVerbStatic, format[prev:start])\n\t\t}\n\n\t\tname := format[m[2]:m[3]]\n\t\tverb := getFmtVerbByName(name)\n\t\tif verb == fmtVerbUnknown {\n\t\t\treturn nil, errors.New(\"logger: unknown variable: \" + name)\n\t\t}\n\n\t\t\/\/ Handle layout customizations or use the default. If this is not for the\n\t\t\/\/ time formatting, we need to prefix with %.\n\t\tlayout := defaultVerbsLayout[verb]\n\t\tif m[4] != -1 {\n\t\t\tlayout = format[m[4]:m[5]]\n\t\t}\n\t\tif verb != fmtVerbTime {\n\t\t\tlayout = \"%\" + layout\n\t\t}\n\n\t\tfmter.add(verb, layout)\n\t\tprev = end\n\t}\n\tend := format[prev:]\n\tif end != \"\" {\n\t\tfmter.add(fmtVerbStatic, end)\n\t}\n\n\t\/\/ Make a test run to make sure we can format it correctly.\n\tt, err := time.Parse(time.RFC3339, \"2010-02-04T21:00:57-08:00\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr := &Record{\n\t\tId:     12345,\n\t\tTime:   t,\n\t\tModule: \"logger\",\n\t\tfmt:    \"hello %s\",\n\t\targs:   []interface{}{\"go\"},\n\t}\n\tif err := fmter.Format(0, r, &bytes.Buffer{}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tformatter.def = fmter\n\n\treturn fmter, nil\n}\n\n\/\/ MustStringFormatter is equivalent to NewStringFormatter with a call to panic\n\/\/ on error.\nfunc MustStringFormatter(format string) *stringFormatter {\n\tf, err := NewStringFormatter(format)\n\tif err != nil {\n\t\tpanic(\"Failed to initialized string formatter: \" + err.Error())\n\t}\n\treturn f\n}\n\nfunc (f *stringFormatter) add(verb fmtVerb, layout string) {\n\tf.parts = append(f.parts, part{verb, layout})\n}\n\nfunc (f *stringFormatter) Format(calldepth int, r *Record, output io.Writer) error {\n\t\/\/ TODO collect and call fprintf once?\n\tfor _, part := range f.parts {\n\t\tif part.verb == fmtVerbStatic {\n\t\t\toutput.Write([]byte(part.layout))\n\t\t} else if part.verb == fmtVerbTime {\n\t\t\toutput.Write([]byte(r.Time.Format(part.layout)))\n\t\t} else {\n\t\t\tvar v interface{}\n\t\t\tswitch part.verb {\n\t\t\tcase fmtVerbLevel:\n\t\t\t\tv = r.Level\n\t\t\t\tbreak\n\t\t\tcase fmtVerbId:\n\t\t\t\tv = r.Id\n\t\t\t\tbreak\n\t\t\tcase fmtVerbModule:\n\t\t\t\tv = r.Module\n\t\t\t\tbreak\n\t\t\tcase fmtVerbMessage:\n\t\t\t\tv = r.Message()\n\t\t\t\tbreak\n\t\t\tcase fmtVerbLongfile, fmtVerbShortfile:\n\t\t\t\t_, file, line, ok := runtime.Caller(calldepth + 1)\n\t\t\t\tif !ok {\n\t\t\t\t\tfile = \"???\"\n\t\t\t\t\tline = 0\n\t\t\t\t} else if part.verb == fmtVerbShortfile {\n\t\t\t\t\tfile = filepath.Base(file)\n\t\t\t\t}\n\t\t\t\tv = fmt.Sprintf(\"%s:%d\", file, line)\n\t\t\tdefault:\n\t\t\t\tpanic(\"unhandled format part\")\n\t\t\t}\n\t\t\tfmt.Fprintf(output, part.layout, v)\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Added pid and program formatter options<commit_after>\/\/ Copyright 2013, Örjan Persson. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage logging\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ TODO see Formatter interface in fmt\/print.go\n\/\/ TODO try text\/template, maybe it have enough performance\n\/\/ TODO other template systems?\n\/\/ TODO make it possible to specify formats per backend?\ntype fmtVerb int\n\nconst (\n\tfmtVerbTime fmtVerb = iota\n\tfmtVerbLevel\n\tfmtVerbId\n\tfmtVerbPid\n\tfmtVerbProgram\n\tfmtVerbModule\n\tfmtVerbMessage\n\tfmtVerbLongfile\n\tfmtVerbShortfile\n\n\t\/\/ Keep last, there are no match for these below.\n\tfmtVerbUnknown\n\tfmtVerbStatic\n)\n\nvar fmtVerbs = []string{\n\t\"time\",\n\t\"level\",\n\t\"id\",\n\t\"pid\",\n\t\"program\",\n\t\"module\",\n\t\"message\",\n\t\"longfile\",\n\t\"shortfile\",\n}\n\nvar defaultVerbsLayout = []string{\n\t\"2006-01-02T15:04:05.999Z07:00\",\n\t\"s\",\n\t\"d\",\n\t\"d\",\n\t\"s\",\n\t\"s\",\n\t\"s\",\n\t\"s\",\n\t\"s\",\n}\n\nvar (\n\tpid     = os.Getpid()\n\tprogram = filepath.Base(os.Args[0])\n)\n\nfunc getFmtVerbByName(name string) fmtVerb {\n\tfor i, verb := range fmtVerbs {\n\t\tif name == verb {\n\t\t\treturn fmtVerb(i)\n\t\t}\n\t}\n\treturn fmtVerbUnknown\n}\n\n\/\/ Formatter is the required interface for a custom log record formatter.\ntype Formatter interface {\n\tFormat(calldepth int, r *Record, w io.Writer) error\n}\n\n\/\/ formatter is used by all backends unless otherwise overriden.\nvar formatter struct {\n\tsync.RWMutex\n\tdef Formatter\n}\n\nfunc getFormatter() Formatter {\n\tformatter.RLock()\n\tdefer formatter.RUnlock()\n\treturn formatter.def\n}\n\nvar (\n\t\/\/ DefaultFormatter is the default formatter used and is only the message.\n\tDefaultFormatter Formatter = MustStringFormatter(\"%{message}\")\n\n\t\/\/ TODO add filename and line\n\t\/\/ GlogFormatter Formatter = MustStringFormatter(\"%{level:.1}%%{time:0102 15:04:05.99999} 0 %{file}:%{line} %{message}\")\n)\n\n\/\/ SetFormatter sets the default formatter for all new backends. A backend will\n\/\/ fetch this value once it is needed to format a record. Note that backends\n\/\/ will cache the formatter after the first point. For now, make sure to set\n\/\/ the formatter before logging.\nfunc SetFormatter(f Formatter) {\n\tformatter.Lock()\n\tdefer formatter.Unlock()\n\tformatter.def = f\n}\n\n\/\/ TODO use ${} instead?\nvar formatRe *regexp.Regexp = regexp.MustCompile(`%{([a-z]+)(?::(.*?[^\\\\]))?}`)\n\ntype part struct {\n\tverb   fmtVerb\n\tlayout string\n}\n\n\/\/ stringFormatter contains a list of parts which explains how to build the\n\/\/ formatted string passed on to the logging backend.\ntype stringFormatter struct {\n\tparts []part\n}\n\n\/\/ NewStringFormatter returns a new Formatter which outputs the log record as a\n\/\/ string based on the 'verbs' specified in the format string.\n\/\/\n\/\/ The verbs:\n\/\/\n\/\/ General:\n\/\/     %{id}        Sequence number for log message (uint64).\n\/\/     %{pid}       Process id (int)\n\/\/     %{time}      Time when log occurred (time.Time)\n\/\/     %{level}     Log level (Level)\n\/\/     %{module}    Module (string)\n\/\/     %{program}   Basename of os.Args[0] (string)\n\/\/     %{message}   Message (string)\n\/\/     %{longfile}  Full file name and line number: \/a\/b\/c\/d.go:23\n\/\/     %{shortfile} Final file name element and line number: d.go:23\n\/\/\n\/\/ For normal types, the output can be customized by using the 'verbs' defined\n\/\/ in the fmt package, eg. '%{id:04d}' to make the id output be '%04d' as the\n\/\/ format string.\n\/\/\n\/\/ For time.Time, use the same layout as time.Format to change the time format\n\/\/ when output, eg \"2006-01-02T15:04:05.999Z-07:00\".\nfunc NewStringFormatter(format string) (*stringFormatter, error) {\n\tvar fmter = &stringFormatter{}\n\n\t\/\/ Find the boundaries of all %{vars}\n\tmatches := formatRe.FindAllStringSubmatchIndex(format, -1)\n\tif matches == nil {\n\t\treturn nil, errors.New(\"logger: invalid log format: \" + format)\n\t}\n\n\t\/\/ Collect all variables and static text for the format\n\tprev := 0\n\tfor _, m := range matches {\n\t\tstart, end := m[0], m[1]\n\t\tif start > prev {\n\t\t\tfmter.add(fmtVerbStatic, format[prev:start])\n\t\t}\n\n\t\tname := format[m[2]:m[3]]\n\t\tverb := getFmtVerbByName(name)\n\t\tif verb == fmtVerbUnknown {\n\t\t\treturn nil, errors.New(\"logger: unknown variable: \" + name)\n\t\t}\n\n\t\t\/\/ Handle layout customizations or use the default. If this is not for the\n\t\t\/\/ time formatting, we need to prefix with %.\n\t\tlayout := defaultVerbsLayout[verb]\n\t\tif m[4] != -1 {\n\t\t\tlayout = format[m[4]:m[5]]\n\t\t}\n\t\tif verb != fmtVerbTime {\n\t\t\tlayout = \"%\" + layout\n\t\t}\n\n\t\tfmter.add(verb, layout)\n\t\tprev = end\n\t}\n\tend := format[prev:]\n\tif end != \"\" {\n\t\tfmter.add(fmtVerbStatic, end)\n\t}\n\n\t\/\/ Make a test run to make sure we can format it correctly.\n\tt, err := time.Parse(time.RFC3339, \"2010-02-04T21:00:57-08:00\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr := &Record{\n\t\tId:     12345,\n\t\tTime:   t,\n\t\tModule: \"logger\",\n\t\tfmt:    \"hello %s\",\n\t\targs:   []interface{}{\"go\"},\n\t}\n\tif err := fmter.Format(0, r, &bytes.Buffer{}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tformatter.def = fmter\n\n\treturn fmter, nil\n}\n\n\/\/ MustStringFormatter is equivalent to NewStringFormatter with a call to panic\n\/\/ on error.\nfunc MustStringFormatter(format string) *stringFormatter {\n\tf, err := NewStringFormatter(format)\n\tif err != nil {\n\t\tpanic(\"Failed to initialized string formatter: \" + err.Error())\n\t}\n\treturn f\n}\n\nfunc (f *stringFormatter) add(verb fmtVerb, layout string) {\n\tf.parts = append(f.parts, part{verb, layout})\n}\n\nfunc (f *stringFormatter) Format(calldepth int, r *Record, output io.Writer) error {\n\t\/\/ TODO collect and call fprintf once?\n\tfor _, part := range f.parts {\n\t\tif part.verb == fmtVerbStatic {\n\t\t\toutput.Write([]byte(part.layout))\n\t\t} else if part.verb == fmtVerbTime {\n\t\t\toutput.Write([]byte(r.Time.Format(part.layout)))\n\t\t} else {\n\t\t\tvar v interface{}\n\t\t\tswitch part.verb {\n\t\t\tcase fmtVerbLevel:\n\t\t\t\tv = r.Level\n\t\t\t\tbreak\n\t\t\tcase fmtVerbId:\n\t\t\t\tv = r.Id\n\t\t\t\tbreak\n\t\t\tcase fmtVerbPid:\n\t\t\t\tv = pid\n\t\t\t\tbreak\n\t\t\tcase fmtVerbProgram:\n\t\t\t\tv = program\n\t\t\t\tbreak\n\t\t\tcase fmtVerbModule:\n\t\t\t\tv = r.Module\n\t\t\t\tbreak\n\t\t\tcase fmtVerbMessage:\n\t\t\t\tv = r.Message()\n\t\t\t\tbreak\n\t\t\tcase fmtVerbLongfile, fmtVerbShortfile:\n\t\t\t\t_, file, line, ok := runtime.Caller(calldepth + 1)\n\t\t\t\tif !ok {\n\t\t\t\t\tfile = \"???\"\n\t\t\t\t\tline = 0\n\t\t\t\t} else if part.verb == fmtVerbShortfile {\n\t\t\t\t\tfile = filepath.Base(file)\n\t\t\t\t}\n\t\t\t\tv = fmt.Sprintf(\"%s:%d\", file, line)\n\t\t\tdefault:\n\t\t\t\tpanic(\"unhandled format part\")\n\t\t\t}\n\t\t\tfmt.Fprintf(output, part.layout, v)\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright IBM Corp 2016 All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\t\t http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\/\/\"encoding\/json\"\n\n\t\"github.com\/hyperledger\/fabric\/core\/chaincode\/shim\"\n\t\n)\n\n\/\/ SimpleChaincode example simple Chaincode implementation\ntype SimpleChaincode struct {\n}\n\ntype Emp struct{\t\n\tempId string `json:\"empId\"`\n\tname string `json:\"name\"`\n\ttitle string `json:\"title\"`\n\n\n}\n\n\n\n\n\nfunc main() {\n\terr := shim.Start(new(SimpleChaincode))\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting Simple chaincode: %s\", err)\n\t}\n}\n\n\/\/ Init resets all the things\nfunc (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\t\n\t\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\t  err := stub.PutState(\"table_ibminsert\", []byte(args[0]))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\n\t\n\t\/\/ Check if table already exists\n\t_,  err = stub.GetTable(\"EmpTable\")\n\t\n\tif err == nil {\n\t\t\/\/ Table already exists; do not recreate\n\t\treturn nil, nil\n\t}\n     fmt.Println(\"ready to create the table: \")\n\t\/\/ Create application Table\n\terr = stub.CreateTable(\"EmpTable\", []*shim.ColumnDefinition{\n\t\t&shim.ColumnDefinition{Name: \"empId\", Type: shim.ColumnDefinition_STRING, Key: true},\n\t\t&shim.ColumnDefinition{Name: \"name\", Type: shim.ColumnDefinition_STRING, Key: false},\n\t\t&shim.ColumnDefinition{Name: \"title\", Type: shim.ColumnDefinition_STRING, Key: false},\n\t\t\n\t})\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed creating ApplicationTable.\")\n\t\t\n\t}\n\n\treturn nil, nil\n\t}\n\n\/\/ Invoke isur entry point to invoke a chaincode function\nfunc (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"invoke is running \" + function)\n\n\t\/\/ Handle different functions\n\tif function == \"init\" {\n\t\treturn t.Init(stub, \"init\", args)\n\t} else if function == \"write\" {\n\t\treturn t.write(stub, args)\n\t}\n\tfmt.Println(\"invoke did not find func: \" + function)\n\n\tif function == \"submitEmp\" {\n\t\tif len(args) != 3 {\n\t\t\treturn nil, fmt.Errorf(\"Incorrect number of arguments. Expecting 20. Got: %d.\", len(args))\n\t\t}\n\t\t\n\t\tempId := args[0]\n\t\tname := args[1]\n\t\ttitle := args[2]\n\t\t\n\t\t\n\t\t\/\/insert a row\n\t\t\n\t\tok, err := stub.InsertRow(\"EmpTable\", shim.Row{\n\t\tColumns: []*shim.Column{\n\t\t\t\t&shim.Column{Value: &shim.Column_String_{String_: empId}},\n\t\t\t\t&shim.Column{Value: &shim.Column_String_{String_: name}},\n\t\t\t\t&shim.Column{Value: &shim.Column_String_{String_: title}},\n\t\t\t\t}})\n\t\n\tif !ok && err == nil {\n\t\t\treturn nil, errors.New(\"Row already exists.\")\n\t\t}\n\t\n\t}\n\tfmt.Println(\"values Inserted in the table: \")\n\t\n\t\n\t\n\t\n\treturn nil, errors.New(\"Received unknown function invocation: \" + function)\n}\n\n\n\n\/\/ Query is our entry point for queries\nfunc (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\t\n\t\n\tfmt.Println(\"query is running \" + function)\n\n\t\/\/ Handle different functions\n\tif function == \"read\" { \/\/read a variable\n\t\treturn t.read(stub, args)\n\t}\n\tfmt.Println(\"query did not find func: \" + function)\n\n\treturn nil, errors.New(\"Received unknown function query: \" + function)\n}\n\n\n\n\n\n\/\/ write - invoke function to write key\/value pair\nfunc (t *SimpleChaincode) write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tvar key, value string\n\tvar err error\n\tfmt.Println(\"running write()\")\n\n\tif len(args) != 2 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 2. name of the key and value to set\")\n\t}\n\n\tkey = args[0] \/\/rename for funsies\n\tvalue = args[1]\n\terr = stub.PutState(key, []byte(value)) \/\/write the variable into the chaincode state\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn nil, nil\n}\n\n\/\/ read - query function to read key\/value pair\nfunc (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\t\n\t\n\t\n\t\n\t\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting applicationid to query\")\n\t}\n\t\n\tfmt.Println(\"came into read func and geting empid: \")\n\t\n\tempId := args[0]\n\nfmt.Println(\"came into read func and geting empid: \"+empId)\n\n\/\/ Get the row pertaining to this applicationId\n\tvar columns []shim.Column\n\tcol1 := shim.Column{Value: &shim.Column_String_{String_: empId}}\n\tcolumns = append(columns, col1)\n\t\n\t\n\trow, err := stub.GetRow(\"EmpTable\", columns)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to get the data for the dataaa \" + empId + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\t\n\tfmt.Println(\"got the row from table: \")\n\t      var x    =     row.Columns[0].GetString_()\n\t\n\tfmt.Println(\"got the row from table: \"+x)\n\t\/\/res2E := Emp{}\n\t\n\t\n\t\/\/res2E.empId = row.Columns[0].GetString_()\n\t\/\/res2E.name = row.Columns[1].GetString_()\n\t\/\/res2E.title = row.Columns[2].GetString_()\n\t\n\t\n\t\/\/mapB, _ := json.Marshal(res2E)\n    \n\t\/\/fmt.Println(string(mapB))\n\t\n\treturn nil, nil\n}\n<commit_msg>121121<commit_after>\/*\nCopyright IBM Corp 2016 All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\t\t http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\/\/\"encoding\/json\"\n\n\t\"github.com\/hyperledger\/fabric\/core\/chaincode\/shim\"\n\t\n)\n\n\/\/ SimpleChaincode example simple Chaincode implementation\ntype SimpleChaincode struct {\n}\n\ntype Emp struct{\t\n\tempId string `json:\"empId\"`\n\tname string `json:\"name\"`\n\ttitle string `json:\"title\"`\n\n\n}\n\n\n\n\n\nfunc main() {\n\terr := shim.Start(new(SimpleChaincode))\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting Simple chaincode: %s\", err)\n\t}\n}\n\n\/\/ Init resets all the things\nfunc (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\t\n\t\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\t  err := stub.PutState(\"table_ibminsert\", []byte(args[0]))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\n\t\n\t\/\/ Check if table already exists\n\t_,  err = stub.GetTable(\"EmpTable\")\n\t\n\tif err == nil {\n\t\t\/\/ Table already exists; do not recreate\n\t\treturn nil, nil\n\t}\n     fmt.Println(\"ready to create the table: \")\n\t\/\/ Create application Table\n\terr = stub.CreateTable(\"EmpTable\", []*shim.ColumnDefinition{\n\t\t&shim.ColumnDefinition{Name: \"empId\", Type: shim.ColumnDefinition_STRING, Key: true},\n\t\t&shim.ColumnDefinition{Name: \"name\", Type: shim.ColumnDefinition_STRING, Key: false},\n\t\t&shim.ColumnDefinition{Name: \"title\", Type: shim.ColumnDefinition_STRING, Key: false},\n\t\t\n\t})\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed creating ApplicationTable.\")\n\t\t\n\t}\n\n\treturn nil, nil\n\t}\n\n\/\/ Invoke isur entry point to invoke a chaincode function\nfunc (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"invoke is running \" + function)\n\n\t\/\/ Handle different functions\n\tif function == \"init\" {\n\t\treturn t.Init(stub, \"init\", args)\n\t} else if function == \"write\" {\n\t\treturn t.write(stub, args)\n\t}\n\tfmt.Println(\"invoke did not find func: \" + function)\n\n\tif function == \"submitEmp\" {\n\t\tif len(args) != 3 {\n\t\t\treturn nil, fmt.Errorf(\"Incorrect number of arguments. Expecting 20. Got: %d.\", len(args))\n\t\t}\n\t\t\n\t\tempId := args[0]\n\t\tname := args[1]\n\t\ttitle := args[2]\n\t\t\n\t\t\n\t\t\/\/insert a row\n\t\t\n\t\tok, err := stub.InsertRow(\"EmpTable\", shim.Row{\n\t\tColumns: []*shim.Column{\n\t\t\t\t&shim.Column{Value: &shim.Column_String_{String_: empId}},\n\t\t\t\t&shim.Column{Value: &shim.Column_String_{String_: name}},\n\t\t\t\t&shim.Column{Value: &shim.Column_String_{String_: title}},\n\t\t\t\t}})\n\t\n\tif !ok && err == nil {\n\t\t\treturn nil, errors.New(\"Row already exists.\")\n\t\t}\n\t\n\t}\n\tfmt.Println(\"values Inserted in the table: \")\n\t\n\t\n\t\n\t\n\treturn nil, errors.New(\"Received unknown function invocation: \" + function)\n}\n\n\n\n\/\/ Query is our entry point for queries\nfunc (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\t\n\t\n\tfmt.Println(\"query is running \" + function)\n\n\t\/\/ Handle different functions\n\tif function == \"read\" { \/\/read a variable\n\t\treturn t.read(stub, args)\n\t}\n\tfmt.Println(\"query did not find func: \" + function)\n\n\treturn nil, errors.New(\"Received unknown function query: \" + function)\n}\n\n\n\n\n\n\/\/ write - invoke function to write key\/value pair\nfunc (t *SimpleChaincode) write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tvar key, value string\n\tvar err error\n\tfmt.Println(\"running write()\")\n\n\tif len(args) != 2 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 2. name of the key and value to set\")\n\t}\n\n\tkey = args[0] \/\/rename for funsies\n\tvalue = args[1]\n\terr = stub.PutState(key, []byte(value)) \/\/write the variable into the chaincode state\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn nil, nil\n}\n\n\/\/ read - query function to read key\/value pair\nfunc (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\t\n\t\n\t\n\t\n\t\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting applicationid to query\")\n\t}\n\t\n\tfmt.Println(\"came into read func and geting empid: \")\n\t\n\tempId := args[0]\n\nfmt.Println(\"came into read func and geting empid: \"+empId)\n\n\/\/ Get the row pertaining to this applicationId\n\tvar columns []shim.Column\n\tcol1 := shim.Column{Value: &shim.Column_String_{String_: empId}}\n\tcolumns = append(columns, col1)\n\t\n\t\n\trow, err := stub.GetRow(\"EmpTable\", columns)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to get the data for the dataaa \" + empId + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\t\n\tif len(row.Columns) == 0 || row.Columns[2] == nil {\n\t\tfmt.Println(\"no rows returned\")\n\t\t\n\t\treturn nil, errors.New(\"row or column value not found\")\n\t}\n\t\n\t\n\t\/\/res2E := Emp{}\n\t\n\t\n\t\/\/res2E.empId = row.Columns[0].GetString_()\n\t\/\/res2E.name = row.Columns[1].GetString_()\n\t\/\/res2E.title = row.Columns[2].GetString_()\n\t\n\t\n\t\/\/mapB, _ := json.Marshal(res2E)\n    \n\t\/\/fmt.Println(string(mapB))\n\t\n\treturn nil, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nPackage framed adds basic support for message framing over streams.\n\nMessages contain an header and a body, both of which are length prefixed.\n\nHere are the bytes (stored in little-endian byte order):\n\n0-2: unsigned 16 bit int header length\n2-4: unsinged 16 bit int body length\n4+:  message content (header and body)\n\nThe use of a uint16 means that the maximum possible header and body lengths\nare 65535 each.\n\nExample:\n\n\tpackage main\n\n\timport (\n\t\t\"github.com\/oxtoacart\/framed\"\n\t\t\"io\/ioutil\"\n\t\t\"log\"\n\t\t\"net\"\n\t)\n\n\tfunc main() {\n\t\t\/\/ Replace host:port with an actual TCP server, for example the echo service\n\t\tif conn, err := net.Dial(\"tcp\", \"host:port\"); err == nil {\n\t\t\tframedConn = Framed{conn}\n\t\t\tif err := framedConn.WriteFrame([]byte(\"Header\"), []byte(\"Hello World\")); err == nil {\n\t\t\t\tif err, frame := framedConn.ReadInitial(); err == nil {\n\t\t\t\t\t\/\/ Note - Read is just like io.Reader.Read(), so we use ioutil.ReadAll\n\t\t\t\t\tif header, err := ioutil.ReadAll(framedConn.Header); err == nil {\n\t\t\t\t\t\tif body, err := ioutil.ReadAll(framedConn.Body); err == nil {\n\t\t\t\t\t\t\tnextFrame, err := frame.Next()\n\t\t\t\t\t\t\t\/\/ And so on\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n*\/\npackage framed\n\nimport (\n\t\"encoding\/binary\"\n\t\"io\"\n\t\"io\/ioutil\"\n)\n\nvar endianness = binary.LittleEndian\n\n\/*\nA Framed enhances an io.ReadWriteCloser to provide methods that allow writing\nand reading frames.\n\nAlthough the underlying ReadWriteCloser may be safe to use from multiple\ngoroutines, a Framed is not.\n*\/\ntype Framed struct {\n\tio.ReadWriteCloser \/\/ the raw underlying connection\n\thasReadInitial     bool\n}\n\n\/\/ AlreadyReadError is returned when someone has already read from a Frame\ntype AlreadyReadError string\n\nfunc (err AlreadyReadError) Error() string {\n\treturn string(err)\n}\n\n\/\/ Frame encapsulates a frame from a Framed\ntype Frame struct {\n\tframed         *Framed\n\theaderLength   uint16\n\tbodyLength     uint16\n\theader         *FrameSection\n\tbody           *FrameSection\n\tcompletelyRead chan bool\n}\n\n\/\/ FrameSection encapsulates a section of a frame (header or body)\ntype FrameSection struct {\n\tframe          *Frame\n\tinit           func() error\n\tfinish         func()\n\tbytesRemaining int\n\tstartedReading bool\n}\n\n\/\/ NewFramed creates a new Framed on top of the given readWriteCloser\nfunc NewFramed(readWriteCloser io.ReadWriteCloser) *Framed {\n\treturn &Framed{readWriteCloser, false}\n}\n\n\/*\nReadInitial reads the initial frame from the framed.  It returns an\nAlreadyReadError if the initial frame has already been read previously.\n*\/\nfunc (framed *Framed) ReadInitial() (frame *Frame, err error) {\n\tif framed.hasReadInitial {\n\t\treturn nil, AlreadyReadError(\"Initial Frame already read\")\n\t}\n\tframe, err = framed.nextFrame()\n\tframed.hasReadInitial = true\n\treturn\n}\n\n\/*\nNext returns the next frame from the Framed underlying the frame on which\nit is called.  This method blocks until the previous frame has been consumed.\nIf there are no more frames, it returns io.EOF as an error.\n*\/\nfunc (frame *Frame) Next() (nextFrame *Frame, err error) {\n\t<-frame.completelyRead\n\treturn frame.framed.nextFrame()\n}\n\n\/*\nWriteFrame writes the given header and body to the Framed.\nEither or both can be nil.\n*\/\nfunc (framed *Framed) WriteFrame(header []byte, body []byte) (err error) {\n\theaderLength := 0\n\tbodyLength := 0\n\tif header != nil {\n\t\theaderLength = len(header)\n\t}\n\tif body != nil {\n\t\tbodyLength = len(body)\n\t}\n\n\tif err = framed.WriteHeader(uint16(headerLength), uint16(bodyLength)); err != nil {\n\t\treturn err\n\t}\n\n\tif header != nil {\n\t\tif _, err = framed.Write(header); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif body != nil {\n\t\t_, err = framed.Write(body)\n\t}\n\n\treturn\n}\n\n\/\/ WriteHeader writes a frame header with the given lengths to the Framed.\nfunc (framed *Framed) WriteHeader(headerLength uint16, bodyLength uint16) (err error) {\n\treturn writeHeaderTo(framed, headerLength, bodyLength)\n}\n\n\/*\nCopyTo copies the given Frame to the given Writer.  If reading of the Frame\nhas already started before CopyTo is called, CopyTo returns an\nAlreadyReadError.\n*\/\nfunc (frame *Frame) CopyTo(out io.Writer) (err error) {\n\tif frame.header.startedReading || frame.body.startedReading {\n\t\treturn AlreadyReadError(\"Already read from frame, cannot copy\")\n\t}\n\tif err = writeHeaderTo(out, frame.headerLength, frame.bodyLength); err != nil {\n\t\treturn\n\t}\n\t_, err = io.CopyN(out, frame.framed, int64(frame.headerLength+frame.bodyLength))\n\tframe.completelyRead <- true\n\treturn\n}\n\n\/*\nRead implements io.Reader.Read for a FrameSection.  Just like the usual Read(),\nthis one may read incompletely, so make sure to call it until it returns EOF.\n*\/\nfunc (section *FrameSection) Read(p []byte) (n int, err error) {\n\tif section.bytesRemaining == 0 {\n\t\treturn 0, err\n\t}\n\tif section.init != nil {\n\t\tif err = section.init(); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\tsection.startedReading = true\n\tif len(p) > section.bytesRemaining {\n\t\tp = p[0:section.bytesRemaining]\n\t}\n\tn, err = section.frame.framed.Read(p)\n\tif n > 0 {\n\t\tsection.bytesRemaining -= n\n\t}\n\tif section.bytesRemaining == 0 {\n\t\terr = io.EOF\n\t}\n\treturn\n}\n\nfunc (section *FrameSection) Drain() (err error) {\n\tif section.bytesRemaining > 0 {\n\t\t_, err = io.Copy(ioutil.Discard, section)\n\t}\n\treturn\n}\n\nfunc (frame *Frame) HeaderLength() uint16 {\n\treturn frame.headerLength\n}\n\nfunc (frame *Frame) BodyLength() uint16 {\n\treturn frame.bodyLength\n}\n\nfunc (frame *Frame) Header() io.Reader {\n\treturn frame.header\n}\n\nfunc (frame *Frame) Body() io.Reader {\n\treturn frame.body\n}\n\nfunc (framed *Framed) nextFrame() (frame *Frame, err error) {\n\tframe = &Frame{framed: framed, completelyRead: make(chan bool, 10)}\n\tframe.header = &FrameSection{frame: frame}\n\tframe.body = &FrameSection{frame: frame, init: frame.header.Drain, finish: frame.done}\n\tif err = frame.readLengths(); err != nil {\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (frame *Frame) readLengths() (err error) {\n\tif err = binary.Read(frame.framed, endianness, &frame.headerLength); err != nil {\n\t\treturn\n\t}\n\tif err = binary.Read(frame.framed, endianness, &frame.bodyLength); err != nil {\n\t\treturn\n\t}\n\tframe.header.bytesRemaining = int(frame.headerLength)\n\tframe.body.bytesRemaining = int(frame.bodyLength)\n\treturn\n}\n\nfunc (frame *Frame) done() {\n\tframe.completelyRead <- true\n}\n\nfunc writeHeaderTo(out io.Writer, headerLength uint16, bodyLength uint16) (err error) {\n\tif err = binary.Write(out, endianness, headerLength); err != nil {\n\t\treturn\n\t}\n\terr = binary.Write(out, endianness, bodyLength)\n\treturn\n}\n<commit_msg>Drain\/Next improvements<commit_after>\/*\nPackage framed adds basic support for message framing over streams.\n\nMessages contain an header and a body, both of which are length prefixed.\n\nHere are the bytes (stored in little-endian byte order):\n\n0-2: unsigned 16 bit int header length\n2-4: unsinged 16 bit int body length\n4+:  message content (header and body)\n\nThe use of a uint16 means that the maximum possible header and body lengths\nare 65535 each.\n\nExample:\n\n\tpackage main\n\n\timport (\n\t\t\"github.com\/oxtoacart\/framed\"\n\t\t\"io\/ioutil\"\n\t\t\"log\"\n\t\t\"net\"\n\t)\n\n\tfunc main() {\n\t\t\/\/ Replace host:port with an actual TCP server, for example the echo service\n\t\tif conn, err := net.Dial(\"tcp\", \"host:port\"); err == nil {\n\t\t\tframedConn = Framed{conn}\n\t\t\tif err := framedConn.WriteFrame([]byte(\"Header\"), []byte(\"Hello World\")); err == nil {\n\t\t\t\tif err, frame := framedConn.ReadInitial(); err == nil {\n\t\t\t\t\t\/\/ Note - Read is just like io.Reader.Read(), so we use ioutil.ReadAll\n\t\t\t\t\tif header, err := ioutil.ReadAll(framedConn.Header); err == nil {\n\t\t\t\t\t\tif body, err := ioutil.ReadAll(framedConn.Body); err == nil {\n\t\t\t\t\t\t\tnextFrame, err := frame.Next()\n\t\t\t\t\t\t\t\/\/ And so on\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n*\/\npackage framed\n\nimport (\n\t\"encoding\/binary\"\n\t\"io\"\n\t\"io\/ioutil\"\n)\n\nvar endianness = binary.LittleEndian\n\n\/*\nA Framed enhances an io.ReadWriteCloser to provide methods that allow writing\nand reading frames.\n\nAlthough the underlying ReadWriteCloser may be safe to use from multiple\ngoroutines, a Framed is not.\n*\/\ntype Framed struct {\n\tio.ReadWriteCloser \/\/ the raw underlying connection\n\thasReadInitial     bool\n}\n\n\/\/ AlreadyReadError is returned when someone has already read from a Frame\ntype AlreadyReadError string\n\nfunc (err AlreadyReadError) Error() string {\n\treturn string(err)\n}\n\n\/\/ Frame encapsulates a frame from a Framed\ntype Frame struct {\n\tframed         *Framed\n\theaderLength   uint16\n\tbodyLength     uint16\n\theader         *FrameSection\n\tbody           *FrameSection\n\tcompletelyRead chan bool\n}\n\n\/\/ FrameSection encapsulates a section of a frame (header or body)\ntype FrameSection struct {\n\tframe          *Frame\n\tinit           func() error\n\tfinish         func()\n\tbytesRemaining int\n\tstartedReading bool\n}\n\n\/\/ NewFramed creates a new Framed on top of the given readWriteCloser\nfunc NewFramed(readWriteCloser io.ReadWriteCloser) *Framed {\n\treturn &Framed{readWriteCloser, false}\n}\n\n\/*\nReadInitial reads the initial frame from the framed.  It returns an\nAlreadyReadError if the initial frame has already been read previously.\n*\/\nfunc (framed *Framed) ReadInitial() (frame *Frame, err error) {\n\tif framed.hasReadInitial {\n\t\treturn nil, AlreadyReadError(\"Initial Frame already read\")\n\t}\n\tframe, err = framed.nextFrame()\n\tframed.hasReadInitial = true\n\treturn\n}\n\n\/*\nNext returns the next frame from the Framed underlying the frame on which\nit is called.  This method blocks until the previous frame has been consumed.\nIf there are no more frames, it returns io.EOF as an error.\n*\/\nfunc (frame *Frame) Next() (nextFrame *Frame, err error) {\n\t<-frame.completelyRead\n\treturn frame.framed.nextFrame()\n}\n\n\/*\nWriteFrame writes the given header and body to the Framed.\nEither or both can be nil.\n*\/\nfunc (framed *Framed) WriteFrame(header []byte, body []byte) (err error) {\n\theaderLength := 0\n\tbodyLength := 0\n\tif header != nil {\n\t\theaderLength = len(header)\n\t}\n\tif body != nil {\n\t\tbodyLength = len(body)\n\t}\n\n\tif err = framed.WriteHeader(uint16(headerLength), uint16(bodyLength)); err != nil {\n\t\treturn err\n\t}\n\n\tif header != nil {\n\t\tif _, err = framed.Write(header); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif body != nil {\n\t\t_, err = framed.Write(body)\n\t}\n\n\treturn\n}\n\n\/\/ WriteHeader writes a frame header with the given lengths to the Framed.\nfunc (framed *Framed) WriteHeader(headerLength uint16, bodyLength uint16) (err error) {\n\treturn writeHeaderTo(framed, headerLength, bodyLength)\n}\n\n\/*\nCopyTo copies the given Frame to the given Writer.  If reading of the Frame\nhas already started before CopyTo is called, CopyTo returns an\nAlreadyReadError.\n*\/\nfunc (frame *Frame) CopyTo(out io.Writer) (err error) {\n\tif frame.header.startedReading || frame.body.startedReading {\n\t\treturn AlreadyReadError(\"Already read from frame, cannot copy\")\n\t}\n\tif err = writeHeaderTo(out, frame.headerLength, frame.bodyLength); err != nil {\n\t\treturn\n\t}\n\t_, err = io.CopyN(out, frame.framed, int64(frame.headerLength+frame.bodyLength))\n\tframe.completelyRead <- true\n\treturn\n}\n\n\/*\nRead implements io.Reader.Read for a FrameSection.  Just like the usual Read(),\nthis one may read incompletely, so make sure to call it until it returns EOF.\n*\/\nfunc (section *FrameSection) Read(p []byte) (n int, err error) {\n\tif section.bytesRemaining == 0 {\n\t\treturn 0, err\n\t}\n\tif section.init != nil {\n\t\tif err = section.init(); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\tsection.startedReading = true\n\tif len(p) > section.bytesRemaining {\n\t\tp = p[0:section.bytesRemaining]\n\t}\n\tn, err = section.frame.framed.Read(p)\n\tif n > 0 {\n\t\tsection.bytesRemaining -= n\n\t}\n\tif section.bytesRemaining == 0 {\n\t\terr = io.EOF\n\t}\n\treturn\n}\n\nfunc (section *FrameSection) Drain() (err error) {\n\tif section.bytesRemaining > 0 {\n\t\t_, err = io.Copy(ioutil.Discard, section)\n\t}\n\treturn\n}\n\nfunc (frame *Frame) HeaderLength() uint16 {\n\treturn frame.headerLength\n}\n\nfunc (frame *Frame) BodyLength() uint16 {\n\treturn frame.bodyLength\n}\n\nfunc (frame *Frame) Header() io.Reader {\n\treturn frame.header\n}\n\nfunc (frame *Frame) Body() io.Reader {\n\treturn frame.body\n}\n\nfunc (framed *Framed) nextFrame() (frame *Frame, err error) {\n\tframe = &Frame{framed: framed, completelyRead: make(chan bool, 1)}\n\tframe.header = &FrameSection{frame: frame}\n\tframe.body = &FrameSection{frame: frame, init: frame.header.Drain, finish: frame.done}\n\tif err = frame.readLengths(); err != nil {\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (frame *Frame) readLengths() (err error) {\n\tif err = binary.Read(frame.framed, endianness, &frame.headerLength); err != nil {\n\t\treturn\n\t}\n\tif err = binary.Read(frame.framed, endianness, &frame.bodyLength); err != nil {\n\t\treturn\n\t}\n\tframe.header.bytesRemaining = int(frame.headerLength)\n\tframe.body.bytesRemaining = int(frame.bodyLength)\n\treturn\n}\n\nfunc (frame *Frame) done() {\n\tframe.completelyRead <- true\n}\n\nfunc writeHeaderTo(out io.Writer, headerLength uint16, bodyLength uint16) (err error) {\n\tif err = binary.Write(out, endianness, headerLength); err != nil {\n\t\treturn\n\t}\n\terr = binary.Write(out, endianness, bodyLength)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nPackage framed provides an implementations of io.Writer and io.Reader that write\nand read whole frames only.\n\nFrames are length-prefixed.  The first two bytes are an unsigned 16 bit int\nstored in little-endian byte order indicating the length of the content.  The\nremaining bytes are the actual content of the frame.\n\nThe use of a uint16 means that the maximum possible frame size (MaxFrameSize)\nis 65535.\n\nThe frame size can be increased to 4294967295 bytes by calling EnableBigFrames()\non the corresponding Reader and Writer.\n*\/\npackage framed\n\nimport (\n\t\"bufio\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com\/oxtoacart\/bpool\"\n)\n\nvar endianness = binary.LittleEndian\n\nconst (\n\t\/\/ FrameHeaderBits is the size of the frame header in bits\n\tFrameHeaderBits = 16\n\n\t\/\/ FrameHeaderBitsBig is the size of the frame header in bits when big frames are enabled\n\tFrameHeaderBitsBig = 32\n\n\t\/\/ FrameHeaderLength is the size of the frame header in bytes\n\tFrameHeaderLength = FrameHeaderBits \/ 8\n\n\t\/\/ FrameHeaderLengthBig is the size of the frame header in bytes when big frames are enabled\n\tFrameHeaderLengthBig = FrameHeaderBitsBig \/ 8\n\n\t\/\/ MaxFrameLength is the maximum possible size of a frame (not including the\n\t\/\/ length prefix)\n\tMaxFrameLength = 1<<FrameHeaderBits - 1\n\n\t\/\/ MaxFrameLengthBigFrames is the maximum possible size of a frame (not\n\t\/\/ including the length prefix) when big frames are enabled.\n\tMaxFrameLengthBigFrames = 1<<FrameHeaderBitsBig - 1\n\n\ttooLongError = \"Attempted to write frame of length %d which is longer than maximum allowed length of %d\"\n)\n\n\/\/ Framed is the common interface for framed Readers and Writers\ntype Framed interface {\n\t\/\/ EnableBigFrames enables support for frames up to 4294967295 bytes in length\n\t\/\/ by using BigEndian byte order for the frame size and supporting expansion of\n\t\/\/ the size header from 2 to 4 bytes.\n\tEnableBigFrames(framed interface{})\n\n\t\/\/ DisableThreadSafety disables thread safety on reading and writing.\n\tDisableThreadSafety()\n}\n\ntype framed struct {\n\tbigFramesEnabled     bool\n\theaderLength         int\n\tmaxFrameLength       int64\n\tthreadSafetyDisabled bool\n\tmutex                sync.Mutex\n}\n\nfunc newFramed() framed {\n\treturn framed{\n\t\theaderLength:   FrameHeaderLength,\n\t\tmaxFrameLength: MaxFrameLength,\n\t}\n}\n\nfunc (fr *framed) EnableBigFrames() {\n\tfr.mutex.Lock()\n\tfr.bigFramesEnabled = true\n\tfr.headerLength = FrameHeaderLengthBig\n\tfr.maxFrameLength = MaxFrameLengthBigFrames\n\tfr.mutex.Unlock()\n}\n\nfunc (fr *framed) DisableThreadSafety() {\n\tfr.threadSafetyDisabled = true\n}\n\n\/*\nA Reader enhances an io.ReadCloser to read data in contiguous frames. It\nimplements the io.Reader interface, but unlike typical io.Readers it only\nreturns whole frames.\n\nA Reader also supports the ability to read frames using dynamically allocated\nbuffers via the ReadFrame method.\n*\/\ntype Reader struct {\n\tStream io.Reader \/\/ the raw underlying connection\n\tframed\n\tlb []byte\n}\n\n\/*\nA Writer enhances an io.WriteCloser to write data in contiguous frames. It\nimplements the io.Writer interface, but unlike typical io.Writers, it includes\ninformation that allows a corresponding Reader to read whole frames without them\nbeing fragmented.\n\nA Writer also supports a method that writes multiple buffers to the underlying\nstream as a single frame.\n*\/\ntype Writer struct {\n\tStream io.Writer \/\/ the raw underlying connection\n\tframed\n}\n\n\/*\nReadWriteCloser combines a Reader and a Writer on top of an underlying\nReadWriteCloser.\n*\/\ntype ReadWriteCloser struct {\n\tReader\n\tWriter\n\tio.Closer\n}\n\nfunc NewReader(r io.Reader) *Reader {\n\treturn &Reader{\n\t\tStream: r,\n\t\tframed: newFramed(),\n\t\tlb:     make([]byte, 2),\n\t}\n}\n\nfunc (fr *Reader) EnableBigFrames() {\n\tfr.framed.EnableBigFrames()\n\tfr.lb = make([]byte, 4)\n}\n\nfunc NewWriter(w io.Writer) *Writer {\n\treturn &Writer{Stream: w, framed: newFramed()}\n}\n\nfunc NewReadWriteCloser(rwc io.ReadWriteCloser) *ReadWriteCloser {\n\treturn &ReadWriteCloser{\n\t\t*NewReader(rwc),\n\t\t*NewWriter(rwc),\n\t\trwc,\n\t}\n}\n\nfunc (fr *ReadWriteCloser) EnableBigFrames() {\n\tfr.Reader.EnableBigFrames()\n\tfr.Writer.EnableBigFrames()\n}\n\nfunc (fr *ReadWriteCloser) DisableThreadSafety() {\n\tfr.Reader.DisableThreadSafety()\n\tfr.Writer.DisableThreadSafety()\n}\n\n\/\/ EnableBuffering enables buffering of read data\nfunc (fr *Reader) EnableBuffering(size int) {\n\tfr.mutex.Lock()\n\tfr.Stream = bufio.NewReaderSize(fr.Stream, size+fr.headerLength)\n\tfr.mutex.Unlock()\n}\n\n\/*\nRead implements the function from io.Reader.  Unlike io.Reader.Read,\nframe.Read only returns full frames of data (assuming that the data was written\nby a fr.Writer).\n*\/\nfunc (fr *Reader) Read(buffer []byte) (n int, err error) {\n\tif !fr.threadSafetyDisabled {\n\t\tfr.mutex.Lock()\n\t\tdefer fr.mutex.Unlock()\n\t}\n\n\tn, err = fr.readLength()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbufferSize := len(buffer)\n\tif n > bufferSize {\n\t\treturn 0, fmt.Errorf(\"Buffer of size %d is too small to hold frame of size %d\", bufferSize, n)\n\t}\n\n\t\/\/ Read into buffer\n\tn, err = io.ReadFull(fr.Stream, buffer[:n])\n\treturn\n}\n\n\/\/ ReadFrame reads the next frame, using a new buffer sized to hold the frame.\nfunc (fr *Reader) ReadFrame() (frame []byte, err error) {\n\tif !fr.threadSafetyDisabled {\n\t\tfr.mutex.Lock()\n\t\tdefer fr.mutex.Unlock()\n\t}\n\n\tvar n int\n\tn, err = fr.readLength()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tframe = make([]byte, n)\n\n\t\/\/ Read into buffer\n\t_, err = io.ReadFull(fr.Stream, frame)\n\treturn\n}\n\nfunc (fr *Reader) readLength() (int, error) {\n\t_, err := io.ReadFull(fr.Stream, fr.lb)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif fr.bigFramesEnabled {\n\t\treturn int(endianness.Uint32(fr.lb)), nil\n\t}\n\treturn int(endianness.Uint16(fr.lb)), nil\n}\n\n\/*\nWrite implements the Write method from io.Writer.  It prepends a frame length\nheader that allows the fr.Reader on the other end to read the whole frame.\n*\/\nfunc (fr *Writer) Write(frame []byte) (n int, err error) {\n\tif !fr.threadSafetyDisabled {\n\t\tfr.mutex.Lock()\n\t\tdefer fr.mutex.Unlock()\n\t}\n\n\tn = len(frame)\n\tif n, err = fr.writeHeaderLength(n); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Write the data\n\tvar written int\n\tif written, err = fr.Stream.Write(frame); err != nil {\n\t\treturn\n\t}\n\tif written != n {\n\t\terr = fmt.Errorf(\"%d bytes written, expected to write %d\", written, n)\n\t}\n\treturn\n}\n\n\/\/ WriteAtomic writes a the frame and its length header in a single write. This requires\n\/\/ that the frame was read into a buffer obtained from a pool created with\n\/\/ NewHeaderPreservingBufferPool().\nfunc (fr *Writer) WriteAtomic(frame bpool.ByteSlice) (n int, err error) {\n\tif !fr.threadSafetyDisabled {\n\t\tfr.mutex.Lock()\n\t\tdefer fr.mutex.Unlock()\n\t}\n\n\tn = len(frame.Bytes())\n\t_frame := frame.BytesWithHeader()\n\n\tswitch fr.bigFramesEnabled {\n\tcase true:\n\t\tendianness.PutUint32(_frame, uint32(n))\n\tdefault:\n\t\tendianness.PutUint16(_frame, uint16(n))\n\t}\n\n\t\/\/ Write frame and data atomically\n\t_, err = fr.Stream.Write(_frame)\n\tif err != nil {\n\t\tn = 0\n\t}\n\treturn\n}\n\nfunc (fr *Writer) WritePieces(pieces ...[]byte) (n int, err error) {\n\tif !fr.threadSafetyDisabled {\n\t\tfr.mutex.Lock()\n\t\tdefer fr.mutex.Unlock()\n\t}\n\n\tfor _, piece := range pieces {\n\t\tn = n + len(piece)\n\t}\n\n\tif n, err = fr.writeHeaderLength(n); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Write the data\n\tvar written int\n\tfor _, piece := range pieces {\n\t\tvar nw int\n\t\tif nw, err = fr.Stream.Write(piece); err != nil {\n\t\t\treturn\n\t\t}\n\t\twritten = written + nw\n\t}\n\tif written != n {\n\t\terr = fmt.Errorf(\"%d bytes written, expected to write %d\", written, n)\n\t}\n\treturn\n}\n\nfunc (fr *Writer) writeHeaderLength(n int) (int, error) {\n\tif int64(n) > fr.maxFrameLength {\n\t\treturn 0, fmt.Errorf(tooLongError, n, MaxFrameLength)\n\t}\n\n\tif fr.bigFramesEnabled {\n\t\treturn n, binary.Write(fr.Stream, endianness, uint32(n))\n\t}\n\treturn n, binary.Write(fr.Stream, endianness, uint16(n))\n}\n\n\/\/ NewHeaderPreservingBufferPool creates a BufferPool that leaves room at the beginning\n\/\/ of buffers for the framed header. This allows use of the WriteAtomic() capability.\nfunc NewHeaderPreservingBufferPool(maxSize int, width int, enableBigFrames bool) bpool.ByteSlicePool {\n\theaderLength := FrameHeaderLength\n\tif enableBigFrames {\n\t\theaderLength = FrameHeaderLengthBig\n\t}\n\treturn bpool.NewHeaderPreservingByteSlicePool(maxSize, width, headerLength)\n}\n<commit_msg>Sizing buffer pool in bytes rather than frames<commit_after>\/*\nPackage framed provides an implementations of io.Writer and io.Reader that write\nand read whole frames only.\n\nFrames are length-prefixed.  The first two bytes are an unsigned 16 bit int\nstored in little-endian byte order indicating the length of the content.  The\nremaining bytes are the actual content of the frame.\n\nThe use of a uint16 means that the maximum possible frame size (MaxFrameSize)\nis 65535.\n\nThe frame size can be increased to 4294967295 bytes by calling EnableBigFrames()\non the corresponding Reader and Writer.\n*\/\npackage framed\n\nimport (\n\t\"bufio\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com\/oxtoacart\/bpool\"\n)\n\nvar endianness = binary.LittleEndian\n\nconst (\n\t\/\/ FrameHeaderBits is the size of the frame header in bits\n\tFrameHeaderBits = 16\n\n\t\/\/ FrameHeaderBitsBig is the size of the frame header in bits when big frames are enabled\n\tFrameHeaderBitsBig = 32\n\n\t\/\/ FrameHeaderLength is the size of the frame header in bytes\n\tFrameHeaderLength = FrameHeaderBits \/ 8\n\n\t\/\/ FrameHeaderLengthBig is the size of the frame header in bytes when big frames are enabled\n\tFrameHeaderLengthBig = FrameHeaderBitsBig \/ 8\n\n\t\/\/ MaxFrameLength is the maximum possible size of a frame (not including the\n\t\/\/ length prefix)\n\tMaxFrameLength = 1<<FrameHeaderBits - 1\n\n\t\/\/ MaxFrameLengthBigFrames is the maximum possible size of a frame (not\n\t\/\/ including the length prefix) when big frames are enabled.\n\tMaxFrameLengthBigFrames = 1<<FrameHeaderBitsBig - 1\n\n\ttooLongError = \"Attempted to write frame of length %d which is longer than maximum allowed length of %d\"\n)\n\n\/\/ Framed is the common interface for framed Readers and Writers\ntype Framed interface {\n\t\/\/ EnableBigFrames enables support for frames up to 4294967295 bytes in length\n\t\/\/ by using BigEndian byte order for the frame size and supporting expansion of\n\t\/\/ the size header from 2 to 4 bytes.\n\tEnableBigFrames(framed interface{})\n\n\t\/\/ DisableThreadSafety disables thread safety on reading and writing.\n\tDisableThreadSafety()\n}\n\ntype framed struct {\n\tbigFramesEnabled     bool\n\theaderLength         int\n\tmaxFrameLength       int64\n\tthreadSafetyDisabled bool\n\tmutex                sync.Mutex\n}\n\nfunc newFramed() framed {\n\treturn framed{\n\t\theaderLength:   FrameHeaderLength,\n\t\tmaxFrameLength: MaxFrameLength,\n\t}\n}\n\nfunc (fr *framed) EnableBigFrames() {\n\tfr.mutex.Lock()\n\tfr.bigFramesEnabled = true\n\tfr.headerLength = FrameHeaderLengthBig\n\tfr.maxFrameLength = MaxFrameLengthBigFrames\n\tfr.mutex.Unlock()\n}\n\nfunc (fr *framed) DisableThreadSafety() {\n\tfr.threadSafetyDisabled = true\n}\n\n\/*\nA Reader enhances an io.ReadCloser to read data in contiguous frames. It\nimplements the io.Reader interface, but unlike typical io.Readers it only\nreturns whole frames.\n\nA Reader also supports the ability to read frames using dynamically allocated\nbuffers via the ReadFrame method.\n*\/\ntype Reader struct {\n\tStream io.Reader \/\/ the raw underlying connection\n\tframed\n\tlb []byte\n}\n\n\/*\nA Writer enhances an io.WriteCloser to write data in contiguous frames. It\nimplements the io.Writer interface, but unlike typical io.Writers, it includes\ninformation that allows a corresponding Reader to read whole frames without them\nbeing fragmented.\n\nA Writer also supports a method that writes multiple buffers to the underlying\nstream as a single frame.\n*\/\ntype Writer struct {\n\tStream io.Writer \/\/ the raw underlying connection\n\tframed\n}\n\n\/*\nReadWriteCloser combines a Reader and a Writer on top of an underlying\nReadWriteCloser.\n*\/\ntype ReadWriteCloser struct {\n\tReader\n\tWriter\n\tio.Closer\n}\n\nfunc NewReader(r io.Reader) *Reader {\n\treturn &Reader{\n\t\tStream: r,\n\t\tframed: newFramed(),\n\t\tlb:     make([]byte, 2),\n\t}\n}\n\nfunc (fr *Reader) EnableBigFrames() {\n\tfr.framed.EnableBigFrames()\n\tfr.lb = make([]byte, 4)\n}\n\nfunc NewWriter(w io.Writer) *Writer {\n\treturn &Writer{Stream: w, framed: newFramed()}\n}\n\nfunc NewReadWriteCloser(rwc io.ReadWriteCloser) *ReadWriteCloser {\n\treturn &ReadWriteCloser{\n\t\t*NewReader(rwc),\n\t\t*NewWriter(rwc),\n\t\trwc,\n\t}\n}\n\nfunc (fr *ReadWriteCloser) EnableBigFrames() {\n\tfr.Reader.EnableBigFrames()\n\tfr.Writer.EnableBigFrames()\n}\n\nfunc (fr *ReadWriteCloser) DisableThreadSafety() {\n\tfr.Reader.DisableThreadSafety()\n\tfr.Writer.DisableThreadSafety()\n}\n\n\/\/ EnableBuffering enables buffering of read data\nfunc (fr *Reader) EnableBuffering(size int) {\n\tfr.mutex.Lock()\n\tfr.Stream = bufio.NewReaderSize(fr.Stream, size+fr.headerLength)\n\tfr.mutex.Unlock()\n}\n\n\/*\nRead implements the function from io.Reader.  Unlike io.Reader.Read,\nframe.Read only returns full frames of data (assuming that the data was written\nby a fr.Writer).\n*\/\nfunc (fr *Reader) Read(buffer []byte) (n int, err error) {\n\tif !fr.threadSafetyDisabled {\n\t\tfr.mutex.Lock()\n\t\tdefer fr.mutex.Unlock()\n\t}\n\n\tn, err = fr.readLength()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbufferSize := len(buffer)\n\tif n > bufferSize {\n\t\treturn 0, fmt.Errorf(\"Buffer of size %d is too small to hold frame of size %d\", bufferSize, n)\n\t}\n\n\t\/\/ Read into buffer\n\tn, err = io.ReadFull(fr.Stream, buffer[:n])\n\treturn\n}\n\n\/\/ ReadFrame reads the next frame, using a new buffer sized to hold the frame.\nfunc (fr *Reader) ReadFrame() (frame []byte, err error) {\n\tif !fr.threadSafetyDisabled {\n\t\tfr.mutex.Lock()\n\t\tdefer fr.mutex.Unlock()\n\t}\n\n\tvar n int\n\tn, err = fr.readLength()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tframe = make([]byte, n)\n\n\t\/\/ Read into buffer\n\t_, err = io.ReadFull(fr.Stream, frame)\n\treturn\n}\n\nfunc (fr *Reader) readLength() (int, error) {\n\t_, err := io.ReadFull(fr.Stream, fr.lb)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif fr.bigFramesEnabled {\n\t\treturn int(endianness.Uint32(fr.lb)), nil\n\t}\n\treturn int(endianness.Uint16(fr.lb)), nil\n}\n\n\/*\nWrite implements the Write method from io.Writer.  It prepends a frame length\nheader that allows the fr.Reader on the other end to read the whole frame.\n*\/\nfunc (fr *Writer) Write(frame []byte) (n int, err error) {\n\tif !fr.threadSafetyDisabled {\n\t\tfr.mutex.Lock()\n\t\tdefer fr.mutex.Unlock()\n\t}\n\n\tn = len(frame)\n\tif n, err = fr.writeHeaderLength(n); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Write the data\n\tvar written int\n\tif written, err = fr.Stream.Write(frame); err != nil {\n\t\treturn\n\t}\n\tif written != n {\n\t\terr = fmt.Errorf(\"%d bytes written, expected to write %d\", written, n)\n\t}\n\treturn\n}\n\n\/\/ WriteAtomic writes a the frame and its length header in a single write. This requires\n\/\/ that the frame was read into a buffer obtained from a pool created with\n\/\/ NewHeaderPreservingBufferPool().\nfunc (fr *Writer) WriteAtomic(frame bpool.ByteSlice) (n int, err error) {\n\tif !fr.threadSafetyDisabled {\n\t\tfr.mutex.Lock()\n\t\tdefer fr.mutex.Unlock()\n\t}\n\n\tn = len(frame.Bytes())\n\t_frame := frame.BytesWithHeader()\n\n\tswitch fr.bigFramesEnabled {\n\tcase true:\n\t\tendianness.PutUint32(_frame, uint32(n))\n\tdefault:\n\t\tendianness.PutUint16(_frame, uint16(n))\n\t}\n\n\t\/\/ Write frame and data atomically\n\t_, err = fr.Stream.Write(_frame)\n\tif err != nil {\n\t\tn = 0\n\t}\n\treturn\n}\n\nfunc (fr *Writer) WritePieces(pieces ...[]byte) (n int, err error) {\n\tif !fr.threadSafetyDisabled {\n\t\tfr.mutex.Lock()\n\t\tdefer fr.mutex.Unlock()\n\t}\n\n\tfor _, piece := range pieces {\n\t\tn = n + len(piece)\n\t}\n\n\tif n, err = fr.writeHeaderLength(n); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Write the data\n\tvar written int\n\tfor _, piece := range pieces {\n\t\tvar nw int\n\t\tif nw, err = fr.Stream.Write(piece); err != nil {\n\t\t\treturn\n\t\t}\n\t\twritten = written + nw\n\t}\n\tif written != n {\n\t\terr = fmt.Errorf(\"%d bytes written, expected to write %d\", written, n)\n\t}\n\treturn\n}\n\nfunc (fr *Writer) writeHeaderLength(n int) (int, error) {\n\tif int64(n) > fr.maxFrameLength {\n\t\treturn 0, fmt.Errorf(tooLongError, n, MaxFrameLength)\n\t}\n\n\tif fr.bigFramesEnabled {\n\t\treturn n, binary.Write(fr.Stream, endianness, uint32(n))\n\t}\n\treturn n, binary.Write(fr.Stream, endianness, uint16(n))\n}\n\n\/\/ NewHeaderPreservingBufferPool creates a BufferPool that leaves room at the beginning\n\/\/ of buffers for the framed header. This allows use of the WriteAtomic() capability.\nfunc NewHeaderPreservingBufferPool(maxSize int, width int, enableBigFrames bool) bpool.ByteSlicePool {\n\theaderLength := FrameHeaderLength\n\tif enableBigFrames {\n\t\theaderLength = FrameHeaderLengthBig\n\t}\n\treturn bpool.NewHeaderPreservingByteSlicePool(maxSize\/(width+headerLength), width, headerLength)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n    \"net\/http\"\n    \"os\"\n    \"io\"\n    \"time\"\n    \"io\/ioutil\"\n    \"fmt\"\n    fp \"path\/filepath\"\n)\n\nfunc handler(w http.ResponseWriter, r *http.Request, add, isFile bool) {\n  \/\/ after 200000 bytes of file parts stored in memory\n  \/\/ the remainder are persisted to disk in temporary files\n  err := r.ParseMultipartForm(200000)\n  if err != nil {\n    http.Error(w, err.Error(), http.StatusInternalServerError)\n    return\n  }\n\n  formData := r.MultipartForm\n  relPath := formData.Value[\"path\"][0]\n\n  baseDir := os.Getenv(\"APP_SRC_DIR\")\n  if len(baseDir) == 0 {\n    baseDir = \"\/app\/\"\n  }\n\n  filepath := fp.Join(baseDir, relPath)\n\n  if add {\n\n    dir := filepath\n    if isFile {\n      dir = fp.Dir(filepath)\n    }\n\n    err = os.MkdirAll(dir, 0777)\n    if err != nil {\n      http.Error(w, \"Unable to create the folder for writing. Check your write access privilege\", http.StatusInternalServerError)\n      return\n    }\n\n    if isFile {\n      file := formData.File[\"file\"][0]\n\n      f, err := file.Open()\n      defer f.Close()\n      if err != nil {\n        http.Error(w, err.Error(), http.StatusInternalServerError)\n        return\n      }\n\n      dest, err := os.Create(filepath)\n      defer dest.Close()\n      if err != nil {\n        http.Error(w, \"Unable to create the file for writing. Check your write access privilege\", http.StatusInternalServerError)\n        return\n      }\n\n      _, err = io.Copy(dest, f)\n      if err != nil {\n        http.Error(w, err.Error(), http.StatusInternalServerError)\n        return\n      }\n    }\n\n  } else {\n\n    err = os.RemoveAll(filepath)\n    if err != nil {\n      http.Error(w, \"Unable to delete the file\/folder. Check your write access privilege\", http.StatusInternalServerError)\n      return\n    }\n  }\n\n  os.Chtimes(fp.Join(baseDir, \".hotrod-update\"), time.Now(), time.Now())\n\n}\n\nfunc addBaseHandler(w http.ResponseWriter, r *http.Request) {\n  fmt.Fprintf(w, \"Hello, server running.\")\n}\n\nfunc addFileHandler(w http.ResponseWriter, r *http.Request) {\n  handler(w, r, true, true)\n}\n\nfunc addFolderHandler(w http.ResponseWriter, r *http.Request) {\n  handler(w, r, true, false)\n}\n\nfunc removeHandler(w http.ResponseWriter, r *http.Request) {\n  handler(w, r, false, false)\n}\n\nfunc main() {\n\n    baseDir := os.Getenv(\"APP_SRC_DIR\")\n    if len(baseDir) == 0 {\n      baseDir = \"\/app\/\"\n    }\n\n    ioutil.WriteFile(fp.Join(baseDir, \".hotrod-update\"), []byte(\"\"), 0777)\n\n    http.HandleFunc(\"\/\", addBaseHandler)\n    http.HandleFunc(\"\/addFile\", addFileHandler)\n    http.HandleFunc(\"\/addFolder\", addFolderHandler)\n    http.HandleFunc(\"\/remove\", removeHandler)\n    http.ListenAndServe(\":8888\", nil)\n}\n<commit_msg>add const paths<commit_after>package main\n\nimport (\n    \"net\/http\"\n    \"os\"\n    \"io\"\n    \"time\"\n    \"io\/ioutil\"\n    \"fmt\"\n    fp \"path\/filepath\"\n)\n\nconst (\n  UPDATE_FILE = \".hotrod-update\"\n  BASE_DIR = \"\/app\/\"\n)\n\nfunc handler(w http.ResponseWriter, r *http.Request, add, isFile bool) {\n  \/\/ after 200000 bytes of file parts stored in memory\n  \/\/ the remainder are persisted to disk in temporary files\n  err := r.ParseMultipartForm(200000)\n  if err != nil {\n    http.Error(w, err.Error(), http.StatusInternalServerError)\n    return\n  }\n\n  formData := r.MultipartForm\n  relPath := formData.Value[\"path\"][0]\n\n  filepath := fp.Join(BASE_DIR, relPath)\n\n  if add {\n\n    dir := filepath\n    if isFile {\n      dir = fp.Dir(filepath)\n    }\n\n    err = os.MkdirAll(dir, 0777)\n    if err != nil {\n      http.Error(w, \"Unable to create the folder for writing. Check your write access privilege\", http.StatusInternalServerError)\n      return\n    }\n\n    if isFile {\n      file := formData.File[\"file\"][0]\n\n      f, err := file.Open()\n      defer f.Close()\n      if err != nil {\n        http.Error(w, err.Error(), http.StatusInternalServerError)\n        return\n      }\n\n      dest, err := os.Create(filepath)\n      defer dest.Close()\n      if err != nil {\n        http.Error(w, \"Unable to create the file for writing. Check your write access privilege\", http.StatusInternalServerError)\n        return\n      }\n\n      _, err = io.Copy(dest, f)\n      if err != nil {\n        http.Error(w, err.Error(), http.StatusInternalServerError)\n        return\n      }\n    }\n\n  } else {\n\n    err = os.RemoveAll(filepath)\n    if err != nil {\n      http.Error(w, \"Unable to delete the file\/folder. Check your write access privilege\", http.StatusInternalServerError)\n      return\n    }\n  }\n\n  os.Chtimes(fp.Join(BASE_DIR, UPDATE_FILE), time.Now(), time.Now())\n}\n\nfunc addBaseHandler(w http.ResponseWriter, r *http.Request) {\n  fmt.Fprintf(w, \"Hello, server running.\")\n}\n\nfunc addFileHandler(w http.ResponseWriter, r *http.Request) {\n  handler(w, r, true, true)\n}\n\nfunc addFolderHandler(w http.ResponseWriter, r *http.Request) {\n  handler(w, r, true, false)\n}\n\nfunc removeHandler(w http.ResponseWriter, r *http.Request) {\n  handler(w, r, false, false)\n}\n\nfunc main() {\n    ioutil.WriteFile(fp.Join(BASE_DIR, UPDATE_FILE), []byte(\"\"), 0777)\n\n    http.HandleFunc(\"\/\", addBaseHandler)\n    http.HandleFunc(\"\/addFile\", addFileHandler)\n    http.HandleFunc(\"\/addFolder\", addFolderHandler)\n    http.HandleFunc(\"\/remove\", removeHandler)\n    http.ListenAndServe(\":8888\", nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\n\t\"github.com\/gonum\/stat\"\n)\n\nvar noPercent = flag.Bool(\"nopercent\", false, \"don't use percentages, show the true value\")\n\ntype benchResults struct {\n\tvals  []float64\n\tniter []float64\n}\n\nvar benchVals = make(map[string]map[string]benchResults)\n\nfunc main() {\n\tlog.SetPrefix(\"benchsum: \")\n\tlog.SetFlags(0)\n\tflag.Parse()\n\tif flag.NArg() == 0 {\n\t\tb, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tread(b)\n\t} else {\n\t\tfor _, p := range flag.Args() {\n\t\t\tb, err := ioutil.ReadFile(p)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tread(b)\n\t\t}\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 8, 8, 1, ' ', 0)\n\tfmt.Fprint(w, \"name\\tmean\\tstdev\\tstat ...\\n\")\n\tfor name, statmap := range benchVals {\n\t\tfor st, results := range statmap {\n\t\t\tμ, σ := stat.MeanStdDev(results.vals, results.niter)\n\t\t\tif *noPercent {\n\t\t\t\tfmt.Fprintf(w, \"%s\\t%.2e\\t±%.2e\\t%s\\n\", name, μ, σ, st)\n\t\t\t} else {\n\t\t\t\tσPercent := 100 * σ \/ μ\n\t\t\t\tfmt.Fprintf(w, \"%s\\t%.2e\\t±%.0f%%\\t%s\\n\", name, μ, σPercent, st)\n\t\t\t}\n\t\t}\n\t}\n\tw.Flush()\n}\n\nfunc addVal(key, stat string, val, niter float64) {\n\tif benchVals[key] == nil {\n\t\tbenchVals[key] = make(map[string]benchResults)\n\t}\n\tresults := benchVals[key][stat]\n\tresults.vals = append(results.vals, val)\n\tresults.niter = append(results.niter, niter)\n\tbenchVals[key][stat] = results\n}\n\nfunc read(data []byte) {\n\tfor _, line := range strings.Split(string(data), \"\\n\") {\n\t\tf := strings.Fields(line)\n\t\tif len(f) < 4 {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.HasPrefix(f[0], \"Benchmark\") {\n\t\t\tcontinue\n\t\t}\n\t\tname := strings.TrimPrefix(f[0], \"Benchmark\")\n\t\tniter, err := strconv.Atoi(f[1])\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor i := 2; i+2 <= len(f); i += 2 {\n\t\t\tv, err := strconv.ParseFloat(f[i], 64)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taddVal(name, f[i+1], v, float64(niter))\n\t\t}\n\t}\n}\n<commit_msg>perf\/cmd\/benchsum: sort resuts<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\n\t\"github.com\/gonum\/stat\"\n)\n\nvar noPercent = flag.Bool(\"nopercent\", false, \"don't use percentages, show the true value\")\n\ntype benchResults struct {\n\tvals  []float64\n\tniter []float64\n}\n\nvar benchVals = make(map[string]map[string]benchResults)\n\ntype statPair struct {\n\tstat    string\n\tresults benchResults\n}\n\ntype byStat []statPair\n\nfunc (s byStat) Len() int           { return len(s) }\nfunc (s byStat) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }\nfunc (s byStat) Less(i, j int) bool { return s[i].stat < s[j].stat }\n\ntype benchValsPair struct {\n\tname  string\n\tstats []statPair\n}\n\ntype byName []benchValsPair\n\nfunc (s byName) Len() int           { return len(s) }\nfunc (s byName) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }\nfunc (s byName) Less(i, j int) bool { return s[i].name < s[j].name }\n\nfunc main() {\n\tlog.SetPrefix(\"benchsum: \")\n\tlog.SetFlags(0)\n\tflag.Parse()\n\tif flag.NArg() == 0 {\n\t\tb, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tread(b)\n\t} else {\n\t\tfor _, p := range flag.Args() {\n\t\t\tb, err := ioutil.ReadFile(p)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tread(b)\n\t\t}\n\t}\n\n\tw := tabwriter.NewWriter(os.Stdout, 8, 8, 1, ' ', 0)\n\tfmt.Fprint(w, \"name\\tmean\\tstdev\\tstat ...\\n\")\n\tvar allVals []benchValsPair\n\tfor name, statmap := range benchVals {\n\t\tvar stats []statPair\n\t\tfor st, results := range statmap {\n\t\t\tstats = append(stats, statPair{stat: st, results: results})\n\t\t}\n\t\tsort.Sort(byStat(stats))\n\t\tallVals = append(allVals, benchValsPair{name: name, stats: stats})\n\t}\n\tsort.Sort(byName(allVals))\n\tfor _, p := range allVals {\n\t\tname := p.name\n\t\tfor _, p2 := range p.stats {\n\t\t\tst := p2.stat\n\t\t\tresults := p2.results\n\t\t\tμ, σ := stat.MeanStdDev(results.vals, results.niter)\n\t\t\tif *noPercent {\n\t\t\t\tfmt.Fprintf(w, \"%s\\t%.2e\\t±%.2e\\t%s\\n\", name, μ, σ, st)\n\t\t\t} else {\n\t\t\t\tσPercent := 100 * σ \/ μ\n\t\t\t\tfmt.Fprintf(w, \"%s\\t%.2e\\t±%.0f%%\\t%s\\n\", name, μ, σPercent, st)\n\t\t\t}\n\t\t}\n\t}\n\tw.Flush()\n}\n\nfunc addVal(key, stat string, val, niter float64) {\n\tif benchVals[key] == nil {\n\t\tbenchVals[key] = make(map[string]benchResults)\n\t}\n\tresults := benchVals[key][stat]\n\tresults.vals = append(results.vals, val)\n\tresults.niter = append(results.niter, niter)\n\tbenchVals[key][stat] = results\n}\n\nfunc read(data []byte) {\n\tfor _, line := range strings.Split(string(data), \"\\n\") {\n\t\tf := strings.Fields(line)\n\t\tif len(f) < 4 {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.HasPrefix(f[0], \"Benchmark\") {\n\t\t\tcontinue\n\t\t}\n\t\tname := strings.TrimPrefix(f[0], \"Benchmark\")\n\t\tniter, err := strconv.Atoi(f[1])\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor i := 2; i+2 <= len(f); i += 2 {\n\t\t\tv, err := strconv.ParseFloat(f[i], 64)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\taddVal(name, f[i+1], v, float64(niter))\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package docker provides a Pipe that creates and pushes a Docker image\npackage docker\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/apex\/log\"\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/sync\/errgroup\"\n\n\t\"github.com\/goreleaser\/goreleaser\/config\"\n\t\"github.com\/goreleaser\/goreleaser\/context\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/artifact\"\n\t\"github.com\/goreleaser\/goreleaser\/pipeline\"\n)\n\n\/\/ ErrNoDocker is shown when docker cannot be found in $PATH\nvar ErrNoDocker = errors.New(\"docker not present in $PATH\")\n\n\/\/ Pipe for docker\ntype Pipe struct{}\n\nfunc (Pipe) String() string {\n\treturn \"creating Docker images\"\n}\n\n\/\/ Default sets the pipe defaults\nfunc (Pipe) Default(ctx *context.Context) error {\n\tfor i := range ctx.Config.Dockers {\n\t\tvar docker = &ctx.Config.Dockers[i]\n\t\tif docker.OldTagTemplate != \"\" {\n\t\t\t\/\/ TODO: deprecate docker.tag_template in favor of docker.tag_templates\n\t\t\tdocker.TagTemplates = append(docker.TagTemplates, docker.OldTagTemplate)\n\t\t}\n\t\tif len(docker.TagTemplates) == 0 {\n\t\t\tdocker.TagTemplates = append(docker.TagTemplates, \"{{ .Version }}\")\n\t\t}\n\t\tif docker.Goos == \"\" {\n\t\t\tdocker.Goos = \"linux\"\n\t\t}\n\t\tif docker.Goarch == \"\" {\n\t\t\tdocker.Goarch = \"amd64\"\n\t\t}\n\t\tif docker.Latest {\n\t\t\t\/\/ TODO: deprecate docker.Latest in favor of multiple tags?\n\t\t\tdocker.TagTemplates = append(docker.TagTemplates, \"latest\")\n\t\t}\n\t}\n\t\/\/ only set defaults if there is exacly 1 docker setup in the config file.\n\tif len(ctx.Config.Dockers) != 1 {\n\t\treturn nil\n\t}\n\tif ctx.Config.Dockers[0].Binary == \"\" {\n\t\tctx.Config.Dockers[0].Binary = ctx.Config.Builds[0].Binary\n\t}\n\tif ctx.Config.Dockers[0].Dockerfile == \"\" {\n\t\tctx.Config.Dockers[0].Dockerfile = \"Dockerfile\"\n\t}\n\treturn nil\n}\n\n\/\/ Run the pipe\nfunc (Pipe) Run(ctx *context.Context) error {\n\tif len(ctx.Config.Dockers) == 0 || ctx.Config.Dockers[0].Image == \"\" {\n\t\treturn pipeline.Skip(\"docker section is not configured\")\n\t}\n\t_, err := exec.LookPath(\"docker\")\n\tif err != nil {\n\t\treturn ErrNoDocker\n\t}\n\treturn doRun(ctx)\n}\n\nfunc doRun(ctx *context.Context) error {\n\tvar g errgroup.Group\n\tsem := make(chan bool, ctx.Parallelism)\n\tfor _, docker := range ctx.Config.Dockers {\n\t\tdocker := docker\n\t\tsem <- true\n\t\tg.Go(func() error {\n\t\t\tdefer func() {\n\t\t\t\t<-sem\n\t\t\t}()\n\t\t\tlog.WithField(\"docker\", docker).Debug(\"looking for binaries matching\")\n\t\t\tvar binaries = ctx.Artifacts.Filter(\n\t\t\t\tartifact.And(\n\t\t\t\t\tartifact.ByGoos(docker.Goos),\n\t\t\t\t\tartifact.ByGoarch(docker.Goarch),\n\t\t\t\t\tartifact.ByGoarm(docker.Goarm),\n\t\t\t\t\tartifact.ByType(artifact.Binary),\n\t\t\t\t\tfunc(a artifact.Artifact) bool {\n\t\t\t\t\t\treturn a.Extra[\"Binary\"] == docker.Binary\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t).List()\n\t\t\tif len(binaries) == 0 {\n\t\t\t\tlog.Warnf(\"no binaries found for %s\", docker.Binary)\n\t\t\t}\n\t\t\tfor _, binary := range binaries {\n\t\t\t\tif err := process(ctx, docker, binary); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\treturn g.Wait()\n}\n\nfunc tagName(ctx *context.Context, tagTemplate string) (string, error) {\n\tvar out bytes.Buffer\n\tt, err := template.New(\"tag\").Option(\"missingkey=error\").Parse(tagTemplate)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdata := struct {\n\t\tVersion, Tag string\n\t\tEnv          map[string]string\n\t}{\n\t\tVersion: ctx.Version,\n\t\tTag:     ctx.Git.CurrentTag,\n\t\tEnv:     ctx.Env,\n\t}\n\terr = t.Execute(&out, data)\n\treturn out.String(), err\n}\n\nfunc process(ctx *context.Context, docker config.Docker, artifact artifact.Artifact) error {\n\tvar root = filepath.Dir(artifact.Path)\n\tvar dockerfile = filepath.Join(root, filepath.Base(docker.Dockerfile))\n\tvar images []string\n\tfor _, tagTemplate := range docker.TagTemplates {\n\t\ttag, err := tagName(ctx, tagTemplate)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to execute tag template '%s'\", tagTemplate)\n\t\t}\n\t\timages = append(images, fmt.Sprintf(\"%s:%s\", docker.Image, tag))\n\t}\n\tif err := os.Link(docker.Dockerfile, dockerfile); err != nil {\n\t\treturn errors.Wrap(err, \"failed to link dockerfile\")\n\t}\n\tfor _, file := range docker.Files {\n\t\tif err := link(file, filepath.Join(root, filepath.Base(file))); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to link extra file '%s'\", file)\n\t\t}\n\t}\n\tif err := dockerBuild(ctx, root, dockerfile, images[0]); err != nil {\n\t\treturn err\n\t}\n\tfor _, img := range images[1:] {\n\t\tif err := dockerTag(ctx, images[0], img); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn publish(ctx, docker, images)\n}\n\n\/\/ walks the src, recreating dirs and hard-linking files\nfunc link(src, dest string) error {\n\treturn filepath.Walk(src, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ We have the following:\n\t\t\/\/ - src = \"a\/b\"\n\t\t\/\/ - dest = \"dist\/linuxamd64\/b\"\n\t\t\/\/ - path = \"a\/b\/c.txt\"\n\t\t\/\/ So we join \"a\/b\" with \"c.txt\" and use it as the destination.\n\t\tvar dst = filepath.Join(dest, strings.Replace(path, src, \"\", 1))\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"src\": path,\n\t\t\t\"dst\": dst,\n\t\t}).Info(\"extra file\")\n\t\tif info.IsDir() {\n\t\t\treturn os.MkdirAll(dst, info.Mode())\n\t\t}\n\t\treturn os.Link(path, dst)\n\t})\n}\n\nfunc publish(ctx *context.Context, docker config.Docker, images []string) error {\n\tif !ctx.Publish {\n\t\tlog.Warn(\"skipping push because --skip-publish is set\")\n\t\treturn nil\n\t}\n\tfor _, image := range images {\n\t\tif err := dockerPush(ctx, docker, image); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc dockerBuild(ctx *context.Context, root, dockerfile, image string) error {\n\tlog.WithField(\"image\", image).Info(\"building docker image\")\n\t\/* #nosec *\/\n\tvar cmd = exec.CommandContext(ctx, \"docker\", \"build\", \"-f\", dockerfile, \"-t\", image, root)\n\tlog.WithField(\"cmd\", cmd).Debug(\"executing\")\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to build docker image: \\n%s\", string(out))\n\t}\n\tlog.Debugf(\"docker build output: \\n%s\", string(out))\n\treturn nil\n}\n\nfunc dockerTag(ctx *context.Context, image, tag string) error {\n\tlog.WithField(\"image\", image).WithField(\"tag\", tag).Info(\"tagging docker image\")\n\t\/* #nosec *\/\n\tvar cmd = exec.CommandContext(ctx, \"docker\", \"tag\", image, tag)\n\tlog.WithField(\"cmd\", cmd).Debug(\"executing\")\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to tag docker image: \\n%s\", string(out))\n\t}\n\tlog.Debugf(\"docker tag output: \\n%s\", string(out))\n\treturn nil\n}\n\nfunc dockerPush(ctx *context.Context, docker config.Docker, image string) error {\n\tlog.WithField(\"image\", image).Info(\"pushing docker image\")\n\t\/* #nosec *\/\n\tvar cmd = exec.CommandContext(ctx, \"docker\", \"push\", image)\n\tlog.WithField(\"cmd\", cmd).Debug(\"executing\")\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to push docker image: \\n%s\", string(out))\n\t}\n\tlog.Debugf(\"docker push output: \\n%s\", string(out))\n\tctx.Artifacts.Add(artifact.Artifact{\n\t\tType:   artifact.DockerImage,\n\t\tName:   image,\n\t\tPath:   image,\n\t\tGoarch: docker.Goarch,\n\t\tGoos:   docker.Goos,\n\t\tGoarm:  docker.Goarm,\n\t})\n\treturn nil\n}\n<commit_msg>feat: added deprecation warnings<commit_after>\/\/ Package docker provides a Pipe that creates and pushes a Docker image\npackage docker\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/apex\/log\"\n\t\"github.com\/fatih\/color\"\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/sync\/errgroup\"\n\n\t\"github.com\/goreleaser\/goreleaser\/config\"\n\t\"github.com\/goreleaser\/goreleaser\/context\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/artifact\"\n\t\"github.com\/goreleaser\/goreleaser\/pipeline\"\n)\n\n\/\/ ErrNoDocker is shown when docker cannot be found in $PATH\nvar ErrNoDocker = errors.New(\"docker not present in $PATH\")\n\n\/\/ Pipe for docker\ntype Pipe struct{}\n\nfunc (Pipe) String() string {\n\treturn \"creating Docker images\"\n}\n\n\/\/ Default sets the pipe defaults\nfunc (Pipe) Default(ctx *context.Context) error {\n\tvar deprecate = color.New(color.Bold, color.FgHiYellow)\n\tfor i := range ctx.Config.Dockers {\n\t\tvar docker = &ctx.Config.Dockers[i]\n\t\tif docker.OldTagTemplate != \"\" {\n\t\t\tlog.Warn(deprecate.Sprintf(\"`dockers[%d].tag_template` is deprecated. Please consider using `dockers[%d].tag_templates` instead\", i, i))\n\t\t\tdocker.TagTemplates = append(docker.TagTemplates, docker.OldTagTemplate)\n\t\t}\n\t\tif len(docker.TagTemplates) == 0 {\n\t\t\tdocker.TagTemplates = append(docker.TagTemplates, \"{{ .Version }}\")\n\t\t}\n\t\tif docker.Goos == \"\" {\n\t\t\tdocker.Goos = \"linux\"\n\t\t}\n\t\tif docker.Goarch == \"\" {\n\t\t\tdocker.Goarch = \"amd64\"\n\t\t}\n\t\tif docker.Latest {\n\t\t\tlog.Warn(deprecate.Sprintf(\"`dockers[%d].latest` is deprecated. Please consider adding a `latest` tag to the `dockers[%d].tag_templates` list instead\", i, i))\n\t\t\tdocker.TagTemplates = append(docker.TagTemplates, \"latest\")\n\t\t}\n\t}\n\t\/\/ only set defaults if there is exacly 1 docker setup in the config file.\n\tif len(ctx.Config.Dockers) != 1 {\n\t\treturn nil\n\t}\n\tif ctx.Config.Dockers[0].Binary == \"\" {\n\t\tctx.Config.Dockers[0].Binary = ctx.Config.Builds[0].Binary\n\t}\n\tif ctx.Config.Dockers[0].Dockerfile == \"\" {\n\t\tctx.Config.Dockers[0].Dockerfile = \"Dockerfile\"\n\t}\n\treturn nil\n}\n\n\/\/ Run the pipe\nfunc (Pipe) Run(ctx *context.Context) error {\n\tif len(ctx.Config.Dockers) == 0 || ctx.Config.Dockers[0].Image == \"\" {\n\t\treturn pipeline.Skip(\"docker section is not configured\")\n\t}\n\t_, err := exec.LookPath(\"docker\")\n\tif err != nil {\n\t\treturn ErrNoDocker\n\t}\n\treturn doRun(ctx)\n}\n\nfunc doRun(ctx *context.Context) error {\n\tvar g errgroup.Group\n\tsem := make(chan bool, ctx.Parallelism)\n\tfor _, docker := range ctx.Config.Dockers {\n\t\tdocker := docker\n\t\tsem <- true\n\t\tg.Go(func() error {\n\t\t\tdefer func() {\n\t\t\t\t<-sem\n\t\t\t}()\n\t\t\tlog.WithField(\"docker\", docker).Debug(\"looking for binaries matching\")\n\t\t\tvar binaries = ctx.Artifacts.Filter(\n\t\t\t\tartifact.And(\n\t\t\t\t\tartifact.ByGoos(docker.Goos),\n\t\t\t\t\tartifact.ByGoarch(docker.Goarch),\n\t\t\t\t\tartifact.ByGoarm(docker.Goarm),\n\t\t\t\t\tartifact.ByType(artifact.Binary),\n\t\t\t\t\tfunc(a artifact.Artifact) bool {\n\t\t\t\t\t\treturn a.Extra[\"Binary\"] == docker.Binary\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t).List()\n\t\t\tif len(binaries) == 0 {\n\t\t\t\tlog.Warnf(\"no binaries found for %s\", docker.Binary)\n\t\t\t}\n\t\t\tfor _, binary := range binaries {\n\t\t\t\tif err := process(ctx, docker, binary); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\treturn g.Wait()\n}\n\nfunc tagName(ctx *context.Context, tagTemplate string) (string, error) {\n\tvar out bytes.Buffer\n\tt, err := template.New(\"tag\").Option(\"missingkey=error\").Parse(tagTemplate)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdata := struct {\n\t\tVersion, Tag string\n\t\tEnv          map[string]string\n\t}{\n\t\tVersion: ctx.Version,\n\t\tTag:     ctx.Git.CurrentTag,\n\t\tEnv:     ctx.Env,\n\t}\n\terr = t.Execute(&out, data)\n\treturn out.String(), err\n}\n\nfunc process(ctx *context.Context, docker config.Docker, artifact artifact.Artifact) error {\n\tvar root = filepath.Dir(artifact.Path)\n\tvar dockerfile = filepath.Join(root, filepath.Base(docker.Dockerfile))\n\tvar images []string\n\tfor _, tagTemplate := range docker.TagTemplates {\n\t\ttag, err := tagName(ctx, tagTemplate)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to execute tag template '%s'\", tagTemplate)\n\t\t}\n\t\timages = append(images, fmt.Sprintf(\"%s:%s\", docker.Image, tag))\n\t}\n\tif err := os.Link(docker.Dockerfile, dockerfile); err != nil {\n\t\treturn errors.Wrap(err, \"failed to link dockerfile\")\n\t}\n\tfor _, file := range docker.Files {\n\t\tif err := link(file, filepath.Join(root, filepath.Base(file))); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to link extra file '%s'\", file)\n\t\t}\n\t}\n\tif err := dockerBuild(ctx, root, dockerfile, images[0]); err != nil {\n\t\treturn err\n\t}\n\tfor _, img := range images[1:] {\n\t\tif err := dockerTag(ctx, images[0], img); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn publish(ctx, docker, images)\n}\n\n\/\/ walks the src, recreating dirs and hard-linking files\nfunc link(src, dest string) error {\n\treturn filepath.Walk(src, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ We have the following:\n\t\t\/\/ - src = \"a\/b\"\n\t\t\/\/ - dest = \"dist\/linuxamd64\/b\"\n\t\t\/\/ - path = \"a\/b\/c.txt\"\n\t\t\/\/ So we join \"a\/b\" with \"c.txt\" and use it as the destination.\n\t\tvar dst = filepath.Join(dest, strings.Replace(path, src, \"\", 1))\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"src\": path,\n\t\t\t\"dst\": dst,\n\t\t}).Info(\"extra file\")\n\t\tif info.IsDir() {\n\t\t\treturn os.MkdirAll(dst, info.Mode())\n\t\t}\n\t\treturn os.Link(path, dst)\n\t})\n}\n\nfunc publish(ctx *context.Context, docker config.Docker, images []string) error {\n\tif !ctx.Publish {\n\t\tlog.Warn(\"skipping push because --skip-publish is set\")\n\t\treturn nil\n\t}\n\tfor _, image := range images {\n\t\tif err := dockerPush(ctx, docker, image); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc dockerBuild(ctx *context.Context, root, dockerfile, image string) error {\n\tlog.WithField(\"image\", image).Info(\"building docker image\")\n\t\/* #nosec *\/\n\tvar cmd = exec.CommandContext(ctx, \"docker\", \"build\", \"-f\", dockerfile, \"-t\", image, root)\n\tlog.WithField(\"cmd\", cmd).Debug(\"executing\")\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to build docker image: \\n%s\", string(out))\n\t}\n\tlog.Debugf(\"docker build output: \\n%s\", string(out))\n\treturn nil\n}\n\nfunc dockerTag(ctx *context.Context, image, tag string) error {\n\tlog.WithField(\"image\", image).WithField(\"tag\", tag).Info(\"tagging docker image\")\n\t\/* #nosec *\/\n\tvar cmd = exec.CommandContext(ctx, \"docker\", \"tag\", image, tag)\n\tlog.WithField(\"cmd\", cmd).Debug(\"executing\")\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to tag docker image: \\n%s\", string(out))\n\t}\n\tlog.Debugf(\"docker tag output: \\n%s\", string(out))\n\treturn nil\n}\n\nfunc dockerPush(ctx *context.Context, docker config.Docker, image string) error {\n\tlog.WithField(\"image\", image).Info(\"pushing docker image\")\n\t\/* #nosec *\/\n\tvar cmd = exec.CommandContext(ctx, \"docker\", \"push\", image)\n\tlog.WithField(\"cmd\", cmd).Debug(\"executing\")\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to push docker image: \\n%s\", string(out))\n\t}\n\tlog.Debugf(\"docker push output: \\n%s\", string(out))\n\tctx.Artifacts.Add(artifact.Artifact{\n\t\tType:   artifact.DockerImage,\n\t\tName:   image,\n\t\tPath:   image,\n\t\tGoarch: docker.Goarch,\n\t\tGoos:   docker.Goos,\n\t\tGoarm:  docker.Goarm,\n\t})\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst (\n\tLED      = 5  \/\/ Pin 29\n\tRELAY    = 13 \/\/ Pin 33\n\tCAP4700  = 19 \/\/ Pin 35: Also PCM capable\n\tCAP10000 = 6  \/\/ Pin 31\n\tSWITCH   = 26 \/\/ Pin 37\n)\n\nfunc GpioStr(g PiPin) string {\n\tswitch g.Pin() {\n\tcase LED:\n\t\treturn \"LED\"\n\tcase RELAY:\n\t\treturn \"RELAY\"\n\tcase CAP4700:\n\t\treturn \"CAP4700\"\n\tcase CAP10000:\n\t\treturn \"CAP10000\"\n\tcase SWITCH:\n\t\treturn \"SWITCH\"\n\tdefault:\n\t\treturn \"UNKNOWN\"\n\t}\n\treturn \"\"\n}\n\nvar Led PiPin        \/\/ Setup: GPIO -> <1k Resistor -> LED -> GND\nvar TestRelay *Relay \/\/ Setup GPIO -> 4.7k Resistor -> Relay Board\nvar Cap4700 PiPin    \/\/ Setup: +3.3v -> 4.7k Resistor -> GPIO -> 10uF capacitor -> GND\nvar Cap10000 PiPin   \/\/ Setup: +3.3v -> 10k Resistor -> GPIO -> 10uF capacitor -> GND\nvar Switch PiPin     \/\/ Setup: GPIO -> Button Switch -> GND\n\nfunc ExpectedState(t *testing.T, gpio PiPin, exp GpioState) {\n\tif val := gpio.Read(); val != exp {\n\t\tt.Errorf(\"%s: Expected %s but found %s\", GpioStr(gpio), exp, val)\n\t}\n}\n\nfunc TestInitilization(t *testing.T) {\n\terr := GpioInit()\n\tt.Run(\"Init Host\", func(t *testing.T) {\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Problem initializing gpio: %s\", err.Error())\n\t\t}\n\t})\n\n\t\/\/ Initialized GPIOs\n\tLed = NewGpio(LED)\n\tExpectedState(t, Led, Low)\n}\n\nfunc TestBlinkLed(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\tfor i := 0; i < 6; i++ {\n\t\ttime.Sleep(time.Second \/ 5)\n\t\tLed.Output(High)\n\t\tExpectedState(t, Led, High)\n\t\ttime.Sleep(time.Second \/ 5)\n\t\tLed.Output(Low)\n\t\tExpectedState(t, Led, Low)\n\t}\n}\n\nfunc doStop(button *Button, b *bool, t time.Time) {\n\t*b = false\n\tbutton.Stop()\n\t*b = true\n\tInfo(\"doStop - Stopped after %d ms\", time.Now().Sub(t)\/time.Millisecond)\n}\n\nfunc runRelayTestOn(t *testing.T, relay *Relay) {\n\trelay.TurnOn()\n\tInfo(\"Testing Relay On: %s is %s\", relay.Name(), relay.Status())\n\tif !relay.isOn() {\n\t\tt.Errorf(\"Relay(%s) is %s\", relay.Name(), relay.Status())\n\t}\n}\n\nfunc runRelayTestOff(t *testing.T, relay *Relay) {\n\trelay.TurnOff()\n\tInfo(\"Testing Relay Off: %s is %s\", relay.Name(), relay.Status())\n\tif relay.isOn() {\n\t\tt.Errorf(\"Relay(%s) is %s\", relay.Name(), relay.Status())\n\t}\n}\n\nfunc runRelayTest(t *testing.T, r *Relay, sleep time.Duration) {\n\tt.Run(fmt.Sprintf(\"%s.Test\", r.Name()), func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\trunRelayTestOn(t, r)\n\t\ttime.Sleep(sleep)\n\t\trunRelayTestOff(t, r)\n\t})\n}\n\nfunc TestRelays(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\tTestRelay = NewRelay(RELAY, \"Relay\", \"Testing\")\n\trunRelayTest(t, TestRelay, time.Second)\n}\n\nfunc discharge_us(t *GpioThermometer, e Edge, p Pull) time.Duration {\n\tt.mutex.Lock()\n\tdefer t.mutex.Unlock()\n\n\t\/\/Discharge the capacitor (low temps could make this really long)\n\tt.pin.Output(Low)\n\ttime.Sleep(300 * time.Millisecond)\n\n\t\/\/ Start polling\n\tstart := time.Now()\n\tt.pin.InputEdge(p, e)\n\tif !t.pin.WaitForEdge(time.Second \/ 2) {\n\t\tTrace(\"Thermometer %s, Rising read timed out\", t.Name())\n\t\treturn 0.0\n\t}\n\tstop := time.Now()\n\tt.pin.Output(Low)\n\treturn stop.Sub(start)\n}\n\nfunc TestDischargeStrategies(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\ttherm := NewGpioThermometer(\"Fixed 4.7kOhm ResistorTest\", \"TestManufacturer\", CAP4700)\n\tpulls := []Pull{PullDown, PullUp, Float}\n\tedges := []Edge{RisingEdge, FallingEdge, BothEdges}\n\texpected := 4700 * therm.microfarads\n\tfor _, p := range pulls {\n\t\tfor _, e := range edges {\n\t\t\th := NewHistory(10)\n\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\tdt := discharge_us(therm, e, p)\n\t\t\t\tInfo(\"DischargeTime %f us,  %f k-ohms\", us(dt), therm.getOhms(dt))\n\t\t\t\th.Push(us(dt))\n\t\t\t}\n\t\t\tInfo(\"Strategy(%s, %s): Expected %0.3fus %0.3fus stddev=%0.4f pct=%0.2f\",\n\t\t\t\tp, e, expected, h.Average(), h.Stddev(), 100.0*h.Stddev()\/h.Average())\n\t\t}\n\t}\n}\n\nfunc TestThermometer(t *testing.T) {\n\tt.Skip(\"Skipping TestThermometer until it is fixed\")\n\tInfo(\"Running %s\", t.Name())\n\ttherm := NewGpioThermometer(\"Fixed 4.7kOhm ResistorTest\", \"TestManufacturer\", CAP4700)\n\n\tt.Run(\"Calibrate Cap4700\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\tc, err := therm.Calibrate(4700)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failure to Calibrate successfully: %s\", err.Error())\n\t\t}\n\t\tDebug(\"Setting calibration for %0.3f\", c)\n\t\ttherm.SetAdjustment(c)\n\t})\n\tt.Run(\"Temperature Cap4700\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\terr := therm.Update()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Thermometer update failed: %s\", err.Error())\n\t\t}\n\t\tif therm.Temperature() > 44.1 || therm.Temperature() < 43.1 {\n\t\t\tt.Errorf(\"Thermometer value off: %0.1f, expected 43.6\",\n\t\t\t\ttherm.Temperature())\n\t\t}\n\t})\n\n\ttherm = NewGpioThermometer(\"Fixed 10kOhm ResistorTest\", \"TestManufacturer\", CAP10000)\n\tt.Run(\"Calibrate Cap10000\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\tc, err := therm.Calibrate(10000)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failure to Calibrate successfully: %s\", err.Error())\n\t\t}\n\t\tDebug(\"Setting calibration for %0.3f\", c)\n\t\ttherm.SetAdjustment(c)\n\t})\n\tt.Run(\"Temperature Cap4700\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\terr := therm.Update()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Thermometer update failed: %s\", err.Error())\n\t\t}\n\t\tif therm.Temperature() > 25.4 || therm.Temperature() < 24.4 {\n\t\t\tt.Errorf(\"Thermometer value off: %0.1f, expected 24.9\",\n\t\t\t\ttherm.Temperature())\n\t\t}\n\t})\n}\n\nfunc TestPushButton(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\twasRun := 0\n\tbutton := NewGpioButton(SWITCH, func() {\n\t\twasRun++\n\t\tInfo(\"Button Pushed %d!!!\", wasRun)\n\t})\n\n\tInfo(\"Starting button test, push it 3 times!\")\n\tbutton.Start()\n\tfor i := 0; i < 3; i++ {\n\t\tTestRelay.TurnOn()\n\t\ttime.Sleep(time.Second \/ 3)\n\t\tTestRelay.TurnOff()\n\t\ttime.Sleep(2 * time.Second)\n\t}\n\tif wasRun < 3 {\n\t\tt.Errorf(\"Expected 3 button pushes\")\n\t}\n\tInfo(\"Stopping button job\")\n\texited := false\n\tgo doStop(button, &exited, time.Now())\n\ttime.Sleep(time.Second)\n\tif !exited {\n\t\tt.Errorf(\"Button loop should have stopped within time allotted\")\n\t}\n\tInfo(\"Button job stopped\")\n}\n<commit_msg>test sync<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst (\n\tLED      = 5  \/\/ Pin 29\n\tRELAY    = 13 \/\/ Pin 33\n\tCAP4700  = 19 \/\/ Pin 35: Also PCM capable\n\tCAP10000 = 6  \/\/ Pin 31\n\tSWITCH   = 26 \/\/ Pin 37\n)\n\nfunc GpioStr(g PiPin) string {\n\tswitch g.Pin() {\n\tcase LED:\n\t\treturn \"LED\"\n\tcase RELAY:\n\t\treturn \"RELAY\"\n\tcase CAP4700:\n\t\treturn \"CAP4700\"\n\tcase CAP10000:\n\t\treturn \"CAP10000\"\n\tcase SWITCH:\n\t\treturn \"SWITCH\"\n\tdefault:\n\t\treturn \"UNKNOWN\"\n\t}\n\treturn \"\"\n}\n\nvar Led PiPin        \/\/ Setup: GPIO -> <1k Resistor -> LED -> GND\nvar TestRelay *Relay \/\/ Setup GPIO -> 4.7k Resistor -> Relay Board\nvar Cap4700 PiPin    \/\/ Setup: +3.3v -> 4.7k Resistor -> GPIO -> 10uF capacitor -> GND\nvar Cap10000 PiPin   \/\/ Setup: +3.3v -> 10k Resistor -> GPIO -> 10uF capacitor -> GND\nvar Switch PiPin     \/\/ Setup: GPIO -> Button Switch -> GND\n\nfunc ExpectedState(t *testing.T, gpio PiPin, exp GpioState) {\n\tif val := gpio.Read(); val != exp {\n\t\tt.Errorf(\"%s: Expected %s but found %s\", GpioStr(gpio), exp, val)\n\t}\n}\n\nfunc TestInitilization(t *testing.T) {\n\terr := GpioInit()\n\tt.Run(\"Init Host\", func(t *testing.T) {\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Problem initializing gpio: %s\", err.Error())\n\t\t}\n\t})\n\n\t\/\/ Initialized GPIOs\n\tLed = NewGpio(LED)\n\tExpectedState(t, Led, Low)\n}\n\nfunc TestBlinkLed(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\tfor i := 0; i < 6; i++ {\n\t\ttime.Sleep(time.Second \/ 5)\n\t\tLed.Output(High)\n\t\tExpectedState(t, Led, High)\n\t\ttime.Sleep(time.Second \/ 5)\n\t\tLed.Output(Low)\n\t\tExpectedState(t, Led, Low)\n\t}\n}\n\nfunc doStop(button *Button, b *bool, t time.Time) {\n\t*b = false\n\tbutton.Stop()\n\t*b = true\n\tInfo(\"doStop - Stopped after %d ms\", time.Now().Sub(t)\/time.Millisecond)\n}\n\nfunc runRelayTestOn(t *testing.T, relay *Relay) {\n\trelay.TurnOn()\n\tInfo(\"Testing Relay On: %s is %s\", relay.Name(), relay.Status())\n\tif !relay.isOn() {\n\t\tt.Errorf(\"Relay(%s) is %s\", relay.Name(), relay.Status())\n\t}\n}\n\nfunc runRelayTestOff(t *testing.T, relay *Relay) {\n\trelay.TurnOff()\n\tInfo(\"Testing Relay Off: %s is %s\", relay.Name(), relay.Status())\n\tif relay.isOn() {\n\t\tt.Errorf(\"Relay(%s) is %s\", relay.Name(), relay.Status())\n\t}\n}\n\nfunc runRelayTest(t *testing.T, r *Relay, sleep time.Duration) {\n\tt.Run(fmt.Sprintf(\"%s.Test\", r.Name()), func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\trunRelayTestOn(t, r)\n\t\ttime.Sleep(sleep)\n\t\trunRelayTestOff(t, r)\n\t})\n}\n\nfunc TestRelays(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\tTestRelay = NewRelay(RELAY, \"Relay\", \"Testing\")\n\trunRelayTest(t, TestRelay, time.Second)\n}\n\nfunc discharge_us(t *GpioThermometer, e Edge, p Pull) time.Duration {\n\tt.mutex.Lock()\n\tdefer t.mutex.Unlock()\n\n\t\/\/Discharge the capacitor (low temps could make this really long)\n\tt.pin.Output(Low)\n\ttime.Sleep(300 * time.Millisecond)\n\n\t\/\/ Start polling\n\tstart := time.Now()\n\tt.pin.InputEdge(p, e)\n\tif !t.pin.WaitForEdge(time.Second \/ 2) {\n\t\tTrace(\"Thermometer %s, Rising read timed out\", t.Name())\n\t\treturn 0.0\n\t}\n\tstop := time.Now()\n\tt.pin.Output(Low)\n\treturn stop.Sub(start)\n}\n\nfunc TestDischargeStrategies(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\ttherm := NewGpioThermometer(\"Fixed 4.7kOhm ResistorTest\", \"TestManufacturer\", CAP4700)\n\tpulls := []Pull{PullDown, PullUp, Float}\n\tedges := []Edge{RisingEdge, FallingEdge, BothEdges}\n\texpected := 4700 * therm.microfarads\n\tfor _, p := range pulls {\n\t\tfor _, e := range edges {\n\t\t\th := NewHistory(10)\n\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\tdt := discharge_us(therm, e, p)\n\t\t\t\t\/\/Info(\"DischargeTime %f us,  %f k-ohms\", us(dt), therm.getOhms(dt))\n\t\t\t\th.Push(us(dt))\n\t\t\t}\n\t\t\tInfo(\"Strategy(%s, %s): Expected %0.3fus %0.3fus stddev=%0.4f pct=%0.2f\",\n\t\t\t\tp, e, expected, h.Average(), h.Stddev(), 100.0*h.Stddev()\/h.Average())\n\t\t}\n\t}\n}\n\nfunc TestThermometer(t *testing.T) {\n\tt.Skip(\"Skipping TestThermometer until it is fixed\")\n\tInfo(\"Running %s\", t.Name())\n\ttherm := NewGpioThermometer(\"Fixed 4.7kOhm ResistorTest\", \"TestManufacturer\", CAP4700)\n\n\tt.Run(\"Calibrate Cap4700\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\tc, err := therm.Calibrate(4700)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failure to Calibrate successfully: %s\", err.Error())\n\t\t}\n\t\tDebug(\"Setting calibration for %0.3f\", c)\n\t\ttherm.SetAdjustment(c)\n\t})\n\tt.Run(\"Temperature Cap4700\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\terr := therm.Update()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Thermometer update failed: %s\", err.Error())\n\t\t}\n\t\tif therm.Temperature() > 44.1 || therm.Temperature() < 43.1 {\n\t\t\tt.Errorf(\"Thermometer value off: %0.1f, expected 43.6\",\n\t\t\t\ttherm.Temperature())\n\t\t}\n\t})\n\n\ttherm = NewGpioThermometer(\"Fixed 10kOhm ResistorTest\", \"TestManufacturer\", CAP10000)\n\tt.Run(\"Calibrate Cap10000\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\tc, err := therm.Calibrate(10000)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failure to Calibrate successfully: %s\", err.Error())\n\t\t}\n\t\tDebug(\"Setting calibration for %0.3f\", c)\n\t\ttherm.SetAdjustment(c)\n\t})\n\tt.Run(\"Temperature Cap4700\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\terr := therm.Update()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Thermometer update failed: %s\", err.Error())\n\t\t}\n\t\tif therm.Temperature() > 25.4 || therm.Temperature() < 24.4 {\n\t\t\tt.Errorf(\"Thermometer value off: %0.1f, expected 24.9\",\n\t\t\t\ttherm.Temperature())\n\t\t}\n\t})\n}\n\nfunc TestPushButton(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\twasRun := 0\n\tbutton := NewGpioButton(SWITCH, func() {\n\t\twasRun++\n\t\tInfo(\"Button Pushed %d!!!\", wasRun)\n\t})\n\n\tInfo(\"Starting button test, push it 3 times!\")\n\tbutton.Start()\n\tfor i := 0; i < 3; i++ {\n\t\tTestRelay.TurnOn()\n\t\ttime.Sleep(time.Second \/ 3)\n\t\tTestRelay.TurnOff()\n\t\ttime.Sleep(2 * time.Second)\n\t}\n\tif wasRun < 3 {\n\t\tt.Errorf(\"Expected 3 button pushes\")\n\t}\n\tInfo(\"Stopping button job\")\n\texited := false\n\tgo doStop(button, &exited, time.Now())\n\ttime.Sleep(time.Second)\n\tif !exited {\n\t\tt.Errorf(\"Button loop should have stopped within time allotted\")\n\t}\n\tInfo(\"Button job stopped\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst (\n\tLED      = 5  \/\/ Pin 29\n\tRELAY    = 13 \/\/ Pin 33\n\tCAP4700  = 19 \/\/ Pin 35: Also PCM capable\n\tCAP10000 = 6  \/\/ Pin 31\n\tSWITCH   = 26 \/\/ Pin 37\n)\n\nfunc GpioStr(g PiPin) string {\n\tswitch g.Pin() {\n\tcase LED:\n\t\treturn \"LED\"\n\tcase RELAY:\n\t\treturn \"RELAY\"\n\tcase CAP4700:\n\t\treturn \"CAP4700\"\n\tcase CAP10000:\n\t\treturn \"CAP10000\"\n\tcase SWITCH:\n\t\treturn \"SWITCH\"\n\tdefault:\n\t\treturn \"UNKNOWN\"\n\t}\n\treturn \"\"\n}\n\nvar Led PiPin        \/\/ Setup: GPIO -> <1k Resistor -> LED -> GND\nvar TestRelay *Relay \/\/ Setup GPIO -> 4.7k Resistor -> Relay Board\nvar Cap4700 PiPin    \/\/ Setup: +3.3v -> 4.7k Resistor -> GPIO -> 10uF capacitor -> GND\nvar Cap10000 PiPin   \/\/ Setup: +3.3v -> 10k Resistor -> GPIO -> 10uF capacitor -> GND\nvar Switch PiPin     \/\/ Setup: GPIO -> Button Switch -> GND\n\nfunc ExpectedState(t *testing.T, gpio PiPin, exp GpioState) {\n\tif val := gpio.Read(); val != exp {\n\t\tt.Errorf(\"%s: Expected %s but found %s\", GpioStr(gpio), exp, val)\n\t}\n}\n\nfunc TestInitilization(t *testing.T) {\n\terr := GpioInit()\n\tt.Run(\"Init Host\", func(t *testing.T) {\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Problem initializing gpio: %s\", err.Error())\n\t\t}\n\t})\n\n\t\/\/ Initialized GPIOs\n\tLed = NewGpio(LED)\n\tExpectedState(t, Led, Low)\n}\n\nfunc TestBlinkLed(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\tfor i := 0; i < 6; i++ {\n\t\ttime.Sleep(time.Second \/ 5)\n\t\tLed.Output(High)\n\t\tExpectedState(t, Led, High)\n\t\ttime.Sleep(time.Second \/ 5)\n\t\tLed.Output(Low)\n\t\tExpectedState(t, Led, Low)\n\t}\n}\n\nfunc doStop(button *Button, b *bool, t time.Time) {\n\t*b = false\n\tbutton.Stop()\n\t*b = true\n\tInfo(\"doStop - Stopped after %d ms\", time.Now().Sub(t)\/time.Millisecond)\n}\n\nfunc runRelayTestOn(t *testing.T, relay *Relay) {\n\trelay.TurnOn()\n\tInfo(\"Testing Relay On: %s is %s\", relay.Name(), relay.Status())\n\tif !relay.isOn() {\n\t\tt.Errorf(\"Relay(%s) is %s\", relay.Name(), relay.Status())\n\t}\n}\n\nfunc runRelayTestOff(t *testing.T, relay *Relay) {\n\trelay.TurnOff()\n\tInfo(\"Testing Relay Off: %s is %s\", relay.Name(), relay.Status())\n\tif relay.isOn() {\n\t\tt.Errorf(\"Relay(%s) is %s\", relay.Name(), relay.Status())\n\t}\n}\n\nfunc runRelayTest(t *testing.T, r *Relay, sleep time.Duration) {\n\tt.Run(fmt.Sprintf(\"%s.Test\", r.Name()), func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\trunRelayTestOn(t, r)\n\t\ttime.Sleep(sleep)\n\t\trunRelayTestOff(t, r)\n\t})\n}\n\nfunc TestRelays(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\tTestRelay = NewRelay(RELAY, \"Relay\", \"Testing\")\n\trunRelayTest(t, TestRelay, time.Second)\n}\n\nfunc discharge_us(t *GpioThermometer, e Edge, p Pull) time.Duration {\n\tt.mutex.Lock()\n\tdefer t.mutex.Unlock()\n\n\t\/\/Discharge the capacitor (low temps could make this really long)\n\tt.pin.Output(Low)\n\ttime.Sleep(300 * time.Millisecond)\n\n\t\/\/ Start polling\n\tstart := time.Now()\n\tt.pin.InputEdge(p, e)\n\tif !t.pin.WaitForEdge(time.Second \/ 2) {\n\t\tTrace(\"Thermometer %s, Rising read timed out\", t.Name())\n\t\treturn 0.0\n\t}\n\tstop := time.Now()\n\tt.pin.Output(Low)\n\treturn stop.Sub(start)\n}\n\nfunc TestDischargeStrategies(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\ttherm := NewGpioThermometer(\"Fixed 4.7kOhm ResistorTest\", \"TestManufacturer\", CAP4700)\n\tpulls := []Pull{PullDown, PullUp, Float}\n\tedges := []Edge{RisingEdge, FallingEdge, BothEdges}\n\texpected := 4700 * therm.microfarads\n\tInfo(\"Strategy: Pull, Edge, Expected, Average, Stddev, PctVar\")\n\tfor _, p := range pulls {\n\t\tfor _, e := range edges {\n\t\t\th := NewHistory(10)\n\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\tdt := discharge_us(therm, e, p)\n\t\t\t\t\/\/Info(\"DischargeTime %f us,  %f k-ohms\", us(dt), therm.getOhms(dt))\n\t\t\t\th.Push(us(dt))\n\t\t\t}\n\t\t\tInfo(\"Strategy: %s, %s, %0.3f, %0.3f, %0.4f, %0.2f\",\n\t\t\t\tp, e, expected, h.Average(), h.Stddev(), 100.0*h.Stddev()\/h.Average())\n\t\t}\n\t}\n}\n\nfunc TestThermometer(t *testing.T) {\n\tt.Skip(\"Skipping TestThermometer until it is fixed\")\n\tInfo(\"Running %s\", t.Name())\n\ttherm := NewGpioThermometer(\"Fixed 4.7kOhm ResistorTest\", \"TestManufacturer\", CAP4700)\n\n\tt.Run(\"Calibrate Cap4700\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\tc, err := therm.Calibrate(4700)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failure to Calibrate successfully: %s\", err.Error())\n\t\t}\n\t\tDebug(\"Setting calibration for %0.3f\", c)\n\t\ttherm.SetAdjustment(c)\n\t})\n\tt.Run(\"Temperature Cap4700\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\terr := therm.Update()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Thermometer update failed: %s\", err.Error())\n\t\t}\n\t\tif therm.Temperature() > 44.1 || therm.Temperature() < 43.1 {\n\t\t\tt.Errorf(\"Thermometer value off: %0.1f, expected 43.6\",\n\t\t\t\ttherm.Temperature())\n\t\t}\n\t})\n\n\ttherm = NewGpioThermometer(\"Fixed 10kOhm ResistorTest\", \"TestManufacturer\", CAP10000)\n\tt.Run(\"Calibrate Cap10000\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\tc, err := therm.Calibrate(10000)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failure to Calibrate successfully: %s\", err.Error())\n\t\t}\n\t\tDebug(\"Setting calibration for %0.3f\", c)\n\t\ttherm.SetAdjustment(c)\n\t})\n\tt.Run(\"Temperature Cap4700\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\terr := therm.Update()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Thermometer update failed: %s\", err.Error())\n\t\t}\n\t\tif therm.Temperature() > 25.4 || therm.Temperature() < 24.4 {\n\t\t\tt.Errorf(\"Thermometer value off: %0.1f, expected 24.9\",\n\t\t\t\ttherm.Temperature())\n\t\t}\n\t})\n}\n\nfunc TestPushButton(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\twasRun := 0\n\tbutton := NewGpioButton(SWITCH, func() {\n\t\twasRun++\n\t\tLed.Output(High)\n\t\tInfo(\"Button Pushed %d!!!\", wasRun)\n\t})\n\n\tInfo(\"Starting button test, push it 3 times!\")\n\tbutton.Start()\n\ttime.Sleep(time.Second \/ 2) \/\/ let it start TODO Channel?\n\tfor i := 0; i < 3; i++ {\n\t\tTestRelay.TurnOn()\n\t\ttime.Sleep(time.Second \/ 3)\n\t\tTestRelay.TurnOff()\n\t\tLed.Output(Low)\n\t\ttime.Sleep(2 * time.Second)\n\t}\n\tif wasRun < 3 {\n\t\tt.Errorf(\"Expected 3 button pushes\")\n\t}\n\tInfo(\"Stopping button job\")\n\texited := false\n\tgo doStop(button, &exited, time.Now())\n\ttime.Sleep(time.Second)\n\tif !exited {\n\t\tt.Errorf(\"Button loop should have stopped within time allotted\")\n\t}\n\tInfo(\"Button job stopped\")\n}\n<commit_msg>test sync<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst (\n\tLED      = 5  \/\/ Pin 29\n\tRELAY    = 13 \/\/ Pin 33\n\tCAP4700  = 19 \/\/ Pin 35: Also PCM capable\n\tCAP10000 = 6  \/\/ Pin 31\n\tSWITCH   = 26 \/\/ Pin 37\n)\n\nfunc GpioStr(g PiPin) string {\n\tswitch g.Pin() {\n\tcase LED:\n\t\treturn \"LED\"\n\tcase RELAY:\n\t\treturn \"RELAY\"\n\tcase CAP4700:\n\t\treturn \"CAP4700\"\n\tcase CAP10000:\n\t\treturn \"CAP10000\"\n\tcase SWITCH:\n\t\treturn \"SWITCH\"\n\tdefault:\n\t\treturn \"UNKNOWN\"\n\t}\n\treturn \"\"\n}\n\nvar Led PiPin        \/\/ Setup: GPIO -> <1k Resistor -> LED -> GND\nvar TestRelay *Relay \/\/ Setup GPIO -> 4.7k Resistor -> Relay Board\nvar Cap4700 PiPin    \/\/ Setup: +3.3v -> 4.7k Resistor -> GPIO -> 10uF capacitor -> GND\nvar Cap10000 PiPin   \/\/ Setup: +3.3v -> 10k Resistor -> GPIO -> 10uF capacitor -> GND\nvar Switch PiPin     \/\/ Setup: GPIO -> Button Switch -> GND\n\nfunc ExpectedState(t *testing.T, gpio PiPin, exp GpioState) {\n\tif val := gpio.Read(); val != exp {\n\t\tt.Errorf(\"%s: Expected %s but found %s\", GpioStr(gpio), exp, val)\n\t}\n}\n\nfunc TestInitilization(t *testing.T) {\n\terr := GpioInit()\n\tt.Run(\"Init Host\", func(t *testing.T) {\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Problem initializing gpio: %s\", err.Error())\n\t\t}\n\t})\n\n\t\/\/ Initialized GPIOs\n\tLed = NewGpio(LED)\n\tExpectedState(t, Led, Low)\n}\n\nfunc TestBlinkLed(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\tfor i := 0; i < 6; i++ {\n\t\ttime.Sleep(time.Second \/ 5)\n\t\tLed.Output(High)\n\t\tExpectedState(t, Led, High)\n\t\ttime.Sleep(time.Second \/ 5)\n\t\tLed.Output(Low)\n\t\tExpectedState(t, Led, Low)\n\t}\n}\n\nfunc doStop(button *Button, b *bool, t time.Time) {\n\t*b = false\n\tbutton.Stop()\n\t*b = true\n\tInfo(\"doStop - Stopped after %d ms\", time.Now().Sub(t)\/time.Millisecond)\n}\n\nfunc runRelayTestOn(t *testing.T, relay *Relay) {\n\trelay.TurnOn()\n\tInfo(\"Testing Relay On: %s is %s\", relay.Name(), relay.Status())\n\tif !relay.isOn() {\n\t\tt.Errorf(\"Relay(%s) is %s\", relay.Name(), relay.Status())\n\t}\n}\n\nfunc runRelayTestOff(t *testing.T, relay *Relay) {\n\trelay.TurnOff()\n\tInfo(\"Testing Relay Off: %s is %s\", relay.Name(), relay.Status())\n\tif relay.isOn() {\n\t\tt.Errorf(\"Relay(%s) is %s\", relay.Name(), relay.Status())\n\t}\n}\n\nfunc runRelayTest(t *testing.T, r *Relay, sleep time.Duration) {\n\tt.Run(fmt.Sprintf(\"%s.Test\", r.Name()), func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\trunRelayTestOn(t, r)\n\t\ttime.Sleep(sleep)\n\t\trunRelayTestOff(t, r)\n\t})\n}\n\nfunc TestRelays(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\tTestRelay = NewRelay(RELAY, \"Relay\", \"Testing\")\n\trunRelayTest(t, TestRelay, time.Second)\n}\n\nfunc discharge_us(t *GpioThermometer, e Edge, p Pull) time.Duration {\n\tt.mutex.Lock()\n\tdefer t.mutex.Unlock()\n\n\t\/\/Discharge the capacitor (low temps could make this really long)\n\tt.pin.Output(Low)\n\ttime.Sleep(300 * time.Millisecond)\n\n\t\/\/ Start polling\n\tstart := time.Now()\n\tt.pin.InputEdge(p, e)\n\tif !t.pin.WaitForEdge(time.Second \/ 2) {\n\t\tTrace(\"Thermometer %s, Rising read timed out\", t.Name())\n\t\treturn 0.0\n\t}\n\tstop := time.Now()\n\tt.pin.Output(Low)\n\treturn stop.Sub(start)\n}\n\nfunc TestDischargeStrategies(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\ttherm := NewGpioThermometer(\"Fixed 4.7kOhm ResistorTest\", \"TestManufacturer\", CAP4700)\n\tpulls := []Pull{PullDown, PullUp, Float}\n\tedges := []Edge{RisingEdge, FallingEdge, BothEdges}\n\texpected := 4700 * therm.microfarads\n\tInfo(\"Strategy: Pull, Edge, Expected, Average, Stddev, PctVar\")\n\tfor _, p := range pulls {\n\t\tfor _, e := range edges {\n\t\t\th := NewHistory(10)\n\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\tdt := discharge_us(therm, e, p)\n\t\t\t\t\/\/Info(\"DischargeTime %f us,  %f k-ohms\", us(dt), therm.getOhms(dt))\n\t\t\t\th.Push(us(dt))\n\t\t\t}\n\t\t\tInfo(\"Strategy: %s, %s, %0.3f, %0.3f, %0.4f, %0.2f\",\n\t\t\t\tp, e, expected, h.Average(), h.Stddev(), 100.0*h.Stddev()\/h.Average())\n\t\t}\n\t}\n}\n\nfunc TestBestDischargeStrategy(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\ttherm := NewGpioThermometer(\"Fixed 4.7kOhm ResistorTest\", \"TestManufacturer\", CAP4700)\n\tpulls := []Pull{PullDown, PullUp, Float}\n\tedges := []Edge{RisingEdge, FallingEdge, BothEdges}\n\texpected := 4.700 * therm.microfarads\n\tInfo(\"Strategy: Pull, Edge, Expected, Average, Stddev, PctVar\")\n\th := NewHistory(10)\n\tfor i := 0; i < 10; i++ {\n\t\tdt1 := discharge_us(therm, RisingEdge, PullDown)\n\t\tdt2 := discharge_us(therm, FallingEdge, PullDown)\n\t\tdt := dt1 + dt2\n\t\tInfo(\"DischargeTime dt1(%f ms),  dt2(%f ms), dt(%fms), %f k-ohms\",\n\t\t\tms(dt1), ms(dt2), ms(dt), therm.getOhms(dt))\n\t\th.Push(ms(dt1 + dt2))\n\t}\n\tInfo(\"Strategy: %0.3f, %0.3f, %0.4f, %0.2f\",\n\t\texpected, h.Average(), h.Stddev(), 100.0*h.Stddev()\/h.Average())\n}\n\nfunc TestThermometer(t *testing.T) {\n\tt.Skip(\"Skipping TestThermometer until it is fixed\")\n\tInfo(\"Running %s\", t.Name())\n\ttherm := NewGpioThermometer(\"Fixed 4.7kOhm ResistorTest\", \"TestManufacturer\", CAP4700)\n\n\tt.Run(\"Calibrate Cap4700\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\tc, err := therm.Calibrate(4700)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failure to Calibrate successfully: %s\", err.Error())\n\t\t}\n\t\tDebug(\"Setting calibration for %0.3f\", c)\n\t\ttherm.SetAdjustment(c)\n\t})\n\tt.Run(\"Temperature Cap4700\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\terr := therm.Update()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Thermometer update failed: %s\", err.Error())\n\t\t}\n\t\tif therm.Temperature() > 44.1 || therm.Temperature() < 43.1 {\n\t\t\tt.Errorf(\"Thermometer value off: %0.1f, expected 43.6\",\n\t\t\t\ttherm.Temperature())\n\t\t}\n\t})\n\n\ttherm = NewGpioThermometer(\"Fixed 10kOhm ResistorTest\", \"TestManufacturer\", CAP10000)\n\tt.Run(\"Calibrate Cap10000\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\tc, err := therm.Calibrate(10000)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failure to Calibrate successfully: %s\", err.Error())\n\t\t}\n\t\tDebug(\"Setting calibration for %0.3f\", c)\n\t\ttherm.SetAdjustment(c)\n\t})\n\tt.Run(\"Temperature Cap4700\", func(t *testing.T) {\n\t\tInfo(\"Running %s\", t.Name())\n\t\terr := therm.Update()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Thermometer update failed: %s\", err.Error())\n\t\t}\n\t\tif therm.Temperature() > 25.4 || therm.Temperature() < 24.4 {\n\t\t\tt.Errorf(\"Thermometer value off: %0.1f, expected 24.9\",\n\t\t\t\ttherm.Temperature())\n\t\t}\n\t})\n}\n\nfunc TestPushButton(t *testing.T) {\n\tInfo(\"Running %s\", t.Name())\n\twasRun := 0\n\tbutton := NewGpioButton(SWITCH, func() {\n\t\twasRun++\n\t\tLed.Output(High)\n\t\tInfo(\"Button Pushed %d!!!\", wasRun)\n\t})\n\n\tInfo(\"Starting button test, push it 3 times!\")\n\tbutton.Start()\n\ttime.Sleep(time.Second \/ 2) \/\/ let it start TODO Channel?\n\tfor i := 0; i < 3; i++ {\n\t\tTestRelay.TurnOn()\n\t\ttime.Sleep(time.Second \/ 3)\n\t\tTestRelay.TurnOff()\n\t\tLed.Output(Low)\n\t\ttime.Sleep(2 * time.Second)\n\t}\n\tif wasRun < 3 {\n\t\tt.Errorf(\"Expected 3 button pushes\")\n\t}\n\tInfo(\"Stopping button job\")\n\texited := false\n\tgo doStop(button, &exited, time.Now())\n\ttime.Sleep(time.Second)\n\tif !exited {\n\t\tt.Errorf(\"Button loop should have stopped within time allotted\")\n\t}\n\tInfo(\"Button job stopped\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 CoreOS, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/coreos\/rkt\/Godeps\/_workspace\/src\/github.com\/ThomasRooney\/gexpect\"\n)\n\nfunc TestSuccess(t *testing.T) {\n\tpatchTestACI(\"rkt-inspect-exit0.aci\", \"--exec=\/inspect --print-msg=Hello --exit-code=0\")\n\tdefer os.Remove(\"rkt-inspect-exit0.aci\")\n\n\tchild, err := gexpect.Spawn(\"..\/bin\/rkt --debug --insecure-skip-verify run .\/rkt-inspect-exit0.aci\")\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot exec rkt\")\n\t}\n\terr = child.Expect(\"Hello\")\n\tif err != nil {\n\t\tt.Fatalf(\"Missing hello\")\n\t}\n\tforbidden := \"main process exited, code=exited, status=\"\n\t_, receiver := child.AsyncInteractChannels()\n\tfor {\n\t\tmsg, open := <-receiver\n\t\tif !open {\n\t\t\tbreak\n\t\t}\n\t\tif strings.Contains(msg, forbidden) {\n\t\t\tt.Fatalf(\"Forbidden text received\")\n\t\t}\n\t}\n\n\terr = child.Wait()\n\tif err != nil {\n\t\tt.Fatalf(\"rkt didn't terminate correctly: %v\", err)\n\t}\n}\n\nfunc TestFailure(t *testing.T) {\n\tpatchTestACI(\"rkt-inspect-exit20.aci\", \"--exec=\/inspect --print-msg=Hello --exit-code=20\")\n\tdefer os.Remove(\"rkt-inspect-exit20.aci\")\n\n\tchild, err := gexpect.Spawn(\"..\/bin\/rkt --debug --insecure-skip-verify run .\/rkt-inspect-exit20.aci\")\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot exec rkt\")\n\t}\n\terr = child.Expect(\"Hello\")\n\tif err != nil {\n\t\tt.Fatalf(\"Missing hello\")\n\t}\n\terr = child.Expect(\"main process exited, code=exited, status=20\")\n\tif err != nil {\n\t\tt.Fatalf(\"Missing hello\")\n\t}\n\n\terr = child.Wait()\n\tif err != nil {\n\t\tt.Fatalf(\"rkt didn't terminate correctly: %v\", err)\n\t}\n}\n<commit_msg>functional tests: Port exit tests to rkt run context<commit_after>\/\/ Copyright 2015 CoreOS, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/coreos\/rkt\/Godeps\/_workspace\/src\/github.com\/ThomasRooney\/gexpect\"\n)\n\nfunc TestSuccess(t *testing.T) {\n\tpatchTestACI(\"rkt-inspect-exit0.aci\", \"--exec=\/inspect --print-msg=Hello --exit-code=0\")\n\tdefer os.Remove(\"rkt-inspect-exit0.aci\")\n\tctx := newRktRunCtx()\n\tdefer ctx.cleanup()\n\n\tchild, err := gexpect.Spawn(fmt.Sprintf(\"%s --debug --insecure-skip-verify run .\/rkt-inspect-exit0.aci\", ctx.cmd()))\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot exec rkt\")\n\t}\n\terr = child.Expect(\"Hello\")\n\tif err != nil {\n\t\tt.Fatalf(\"Missing hello\")\n\t}\n\tforbidden := \"main process exited, code=exited, status=\"\n\t_, receiver := child.AsyncInteractChannels()\n\tfor {\n\t\tmsg, open := <-receiver\n\t\tif !open {\n\t\t\tbreak\n\t\t}\n\t\tif strings.Contains(msg, forbidden) {\n\t\t\tt.Fatalf(\"Forbidden text received\")\n\t\t}\n\t}\n\n\terr = child.Wait()\n\tif err != nil {\n\t\tt.Fatalf(\"rkt didn't terminate correctly: %v\", err)\n\t}\n}\n\nfunc TestFailure(t *testing.T) {\n\tpatchTestACI(\"rkt-inspect-exit20.aci\", \"--exec=\/inspect --print-msg=Hello --exit-code=20\")\n\tdefer os.Remove(\"rkt-inspect-exit20.aci\")\n\tctx := newRktRunCtx()\n\tdefer ctx.cleanup()\n\n\tchild, err := gexpect.Spawn(fmt.Sprintf(\"%s --debug --insecure-skip-verify run .\/rkt-inspect-exit20.aci\", ctx.cmd()))\n\tif err != nil {\n\t\tt.Fatalf(\"Cannot exec rkt\")\n\t}\n\terr = child.Expect(\"Hello\")\n\tif err != nil {\n\t\tt.Fatalf(\"Missing hello\")\n\t}\n\terr = child.Expect(\"main process exited, code=exited, status=20\")\n\tif err != nil {\n\t\tt.Fatalf(\"Missing hello\")\n\t}\n\n\terr = child.Wait()\n\tif err != nil {\n\t\tt.Fatalf(\"rkt didn't terminate correctly: %v\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build graphite\n\npackage connector\n\nimport (\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/facette\/facette\/pkg\/catalog\"\n\t\"github.com\/facette\/facette\/pkg\/config\"\n\t\"github.com\/facette\/facette\/pkg\/types\"\n\t\"github.com\/facette\/facette\/pkg\/utils\"\n)\n\nconst (\n\tgraphiteURLMetrics     string  = \"\/metrics\/index.json\"\n\tgraphiteURLRender      string  = \"\/render\"\n\tgraphiteDefaultTimeout float64 = 10\n)\n\ntype graphitePlot struct {\n\tTarget     string\n\tDatapoints [][2]float64\n}\n\n\/\/ GraphiteConnector represents the main structure of the Graphite connector.\ntype GraphiteConnector struct {\n\tURL         string\n\tinsecureTLS bool\n\ttimeout     float64\n}\n\nfunc init() {\n\tConnectors[\"graphite\"] = func(settings map[string]interface{}) (Connector, error) {\n\t\tvar err error\n\n\t\tconnector := &GraphiteConnector{\n\t\t\tinsecureTLS: false,\n\t\t}\n\n\t\tif connector.URL, err = config.GetString(settings, \"url\", true); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif connector.insecureTLS, err = config.GetBool(settings, \"allow_insecure_tls\", false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif connector.timeout, err = config.GetFloat(settings, \"timeout\", false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif connector.timeout <= 0 {\n\t\t\tconnector.timeout = graphiteDefaultTimeout\n\t\t}\n\n\t\treturn connector, nil\n\t}\n}\n\n\/\/ GetPlots retrieves time series data from provider based on a query and a time interval.\nfunc (connector *GraphiteConnector) GetPlots(query *types.PlotQuery) ([]*types.PlotResult, error) {\n\tvar result []*types.PlotResult\n\n\tif len(query.Group.Series) == 0 {\n\t\treturn nil, fmt.Errorf(\"group has no series\")\n\t} else if query.Group.Type != OperGroupTypeNone && len(query.Group.Series) == 1 {\n\t\tquery.Group.Type = OperGroupTypeNone\n\t}\n\n\tqueryURL, err := graphiteBuildQueryURL(query.Group, query.StartTime, query.EndTime, query.Sample)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to build Graphite query URL: %s\", err)\n\t}\n\n\thttpTransport := &http.Transport{\n\t\tDial: (&net.Dialer{\n\t\t\t\/\/ Enable dual IPv4\/IPv6 stack connectivity:\n\t\t\tDualStack: true,\n\t\t\t\/\/ Enforce HTTP connection timeout:\n\t\t\tTimeout: time.Duration(connector.timeout) * time.Second,\n\t\t}).Dial,\n\t}\n\n\tif connector.insecureTLS {\n\t\thttpTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\t}\n\n\thttpClient := http.Client{Transport: httpTransport}\n\n\trequest, err := http.NewRequest(\"GET\", strings.TrimSuffix(connector.URL, \"\/\")+queryURL, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to set up HTTP request: %s\", err)\n\t}\n\n\trequest.Header.Add(\"User-Agent\", \"Facette\")\n\trequest.Header.Add(\"X-Requested-With\", \"GraphiteConnector\")\n\n\tresponse, err := httpClient.Do(request)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to perform HTTP request: %s\", err)\n\t}\n\n\tif err = graphiteCheckBackendResponse(response); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid HTTP backend response: %s\", err)\n\t}\n\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read HTTP response body: %s\", err)\n\t}\n\n\tgraphitePlots := make([]graphitePlot, 0)\n\tif err = json.Unmarshal(data, &graphitePlots); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to unmarshal JSON data: %s\", err)\n\t}\n\n\tif result, err = graphiteExtractPlotResult(graphitePlots); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to extract plot values from backend response: %s\", err)\n\t}\n\n\treturn result, nil\n}\n\n\/\/ Refresh triggers a full connector data update.\nfunc (connector *GraphiteConnector) Refresh(originName string, outputChan chan *catalog.CatalogRecord) error {\n\thttpTransport := &http.Transport{\n\t\tDial: (&net.Dialer{\n\t\t\t\/\/ Enable dual IPv4\/IPv6 stack connectivity:\n\t\t\tDualStack: true,\n\t\t\t\/\/ Enforce HTTP connection timeout:\n\t\t\tTimeout: time.Duration(connector.timeout) * time.Second,\n\t\t}).Dial,\n\t}\n\n\tif connector.insecureTLS {\n\t\thttpTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\t}\n\n\thttpClient := http.Client{Transport: httpTransport}\n\n\trequest, err := http.NewRequest(\"GET\", strings.TrimSuffix(connector.URL, \"\/\")+graphiteURLMetrics, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to set up HTTP request: %s\", err)\n\t}\n\n\trequest.Header.Add(\"User-Agent\", \"Facette\")\n\trequest.Header.Add(\"X-Requested-With\", \"GraphiteConnector\")\n\n\tresponse, err := httpClient.Do(request)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to perform HTTP request: %s\", err)\n\t}\n\n\tif err = graphiteCheckBackendResponse(response); err != nil {\n\t\treturn fmt.Errorf(\"invalid HTTP backend response: %s\", err)\n\t}\n\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to read HTTP response body: %s\", err)\n\t}\n\n\tmetrics := make([]string, 0)\n\tif err = json.Unmarshal(data, &metrics); err != nil {\n\t\treturn fmt.Errorf(\"unable to unmarshal JSON data: %s\", err)\n\t}\n\n\tfor _, metric := range metrics {\n\t\tvar sourceName, metricName string\n\n\t\tindex := strings.Index(metric, \".\")\n\n\t\tif index == -1 {\n\t\t\tsourceName = \"unknown\"\n\t\t\tmetricName = metric\n\t\t} else {\n\t\t\tsourceName = metric[0:index]\n\t\t\tmetricName = metric[index+1:]\n\t\t}\n\n\t\toutputChan <- &catalog.CatalogRecord{\n\t\t\tOrigin:    originName,\n\t\t\tSource:    sourceName,\n\t\t\tMetric:    metricName,\n\t\t\tConnector: connector,\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc graphiteCheckBackendResponse(response *http.Response) error {\n\tif response.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"got HTTP status code %d, expected 200\", response.StatusCode)\n\t}\n\n\tif utils.HTTPGetContentType(response) != \"application\/json\" {\n\t\treturn fmt.Errorf(\"got HTTP content type `%s', expected `application\/json'\", response.Header[\"Content-Type\"])\n\t}\n\n\treturn nil\n}\n\nfunc graphiteBuildQueryURL(queryGroup *types.PlotQueryGroup, startTime, endTime time.Time, sample int) (string, error) {\n\tnow := time.Now()\n\n\tfromTime := 0\n\n\tinterval := fmt.Sprintf(\"%.0fseconds\", (endTime.Sub(startTime) \/ time.Duration(sample)).Seconds())\n\n\tqueryURL := fmt.Sprintf(\"%s?format=json\", graphiteURLRender)\n\n\tcount := 0\n\n\tif queryGroup.Type == OperGroupTypeNone {\n\t\tfor _, serie := range queryGroup.Series {\n\t\t\tcount += 1\n\n\t\t\ttarget := fmt.Sprintf(\"%s.%s\", serie.Metric.Source, serie.Metric.Name)\n\n\t\t\tif scale, _ := config.GetFloat(serie.Options, \"scale\", false); scale != 0 {\n\t\t\t\ttarget = fmt.Sprintf(\"scale(%s, %g)\", target, scale)\n\t\t\t}\n\n\t\t\tqueryURL += fmt.Sprintf(\"&target=legendValue(%s, 'min', 'max', 'avg', 'last')\", target)\n\t\t}\n\t} else {\n\t\tcount += 1\n\n\t\ttargets := make([]string, 0)\n\n\t\tfor _, serie := range queryGroup.Series {\n\t\t\ttargets = append(targets, fmt.Sprintf(\"%s.%s\", serie.Metric.Source, serie.Metric.Name))\n\t\t}\n\n\t\ttarget := fmt.Sprintf(\"group(%s)\", strings.Join(targets, \",\"))\n\n\t\tif scale, _ := config.GetFloat(queryGroup.Series[0].Options, \"scale\", false); scale != 0 {\n\t\t\ttarget = fmt.Sprintf(\"scale(%s, %g)\", target, scale)\n\t\t}\n\n\t\tswitch queryGroup.Type {\n\t\tcase OperGroupTypeAvg:\n\t\t\ttarget = fmt.Sprintf(\"averageSeries(%s)\", target)\n\t\tcase OperGroupTypeSum:\n\t\t\ttarget = fmt.Sprintf(\"sumSeries(%s)\", target)\n\t\t}\n\n\t\ttarget = fmt.Sprintf(\"legendValue(%s, 'min', 'max', 'avg', 'last')\", target)\n\n\t\tqueryURL += fmt.Sprintf(\"&target=summarize(%s, \\\"%s\\\", \\\"avg\\\")\", target, interval)\n\t}\n\n\tif startTime.Before(now) {\n\t\tfromTime = int(now.Sub(startTime).Seconds())\n\t}\n\n\tqueryURL += fmt.Sprintf(\"&from=-%ds\", fromTime)\n\n\t\/\/ Only specify `until' parameter if endTime is still in the past\n\tif endTime.Before(now) {\n\t\tuntilTime := int(time.Now().Sub(endTime).Seconds())\n\t\tqueryURL += fmt.Sprintf(\"&until=-%ds\", untilTime)\n\t}\n\n\treturn queryURL, nil\n}\n\nfunc graphiteExtractPlotResult(plots []graphitePlot) ([]*types.PlotResult, error) {\n\tvar min, max, avg, last float64\n\n\tresult := make([]*types.PlotResult, 0)\n\n\tfor _, plot := range plots {\n\t\tplotResult := &types.PlotResult{Info: make(map[string]types.PlotValue)}\n\n\t\tfor _, plotPoint := range plot.Datapoints {\n\t\t\tplotResult.Plots = append(plotResult.Plots, types.PlotValue(plotPoint[0]))\n\t\t}\n\n\t\t\/\/ Scan the target legend for serie name and plot min\/max\/avg\/last info\n\t\tif index := strings.Index(plots[0].Target, \"(min\"); index > 0 {\n\t\t\tfmt.Sscanf(plot.Target[0:index], \"%s \", &plotResult.Name)\n\t\t\tfmt.Sscanf(plot.Target[index:], \"(min: %f) (max: %f) (avg: %f) (last: %f)\", &min, &max, &avg, &last)\n\t\t}\n\n\t\tplotResult.Info[\"min\"] = types.PlotValue(min)\n\t\tplotResult.Info[\"max\"] = types.PlotValue(max)\n\t\tplotResult.Info[\"avg\"] = types.PlotValue(avg)\n\t\tplotResult.Info[\"last\"] = types.PlotValue(last)\n\n\t\tfmt.Printf(\"graphite: serie %s: %#v\\n\", plotResult.Name, plotResult.Info)\n\n\t\tresult = append(result, plotResult)\n\t}\n\n\treturn result, nil\n}\n<commit_msg>Remove call to legendValue() in Graphite connector<commit_after>\/\/ +build graphite\n\npackage connector\n\nimport (\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/facette\/facette\/pkg\/catalog\"\n\t\"github.com\/facette\/facette\/pkg\/config\"\n\t\"github.com\/facette\/facette\/pkg\/types\"\n\t\"github.com\/facette\/facette\/pkg\/utils\"\n)\n\nconst (\n\tgraphiteURLMetrics     string  = \"\/metrics\/index.json\"\n\tgraphiteURLRender      string  = \"\/render\"\n\tgraphiteDefaultTimeout float64 = 10\n)\n\ntype graphitePlot struct {\n\tTarget     string\n\tDatapoints [][2]float64\n}\n\n\/\/ GraphiteConnector represents the main structure of the Graphite connector.\ntype GraphiteConnector struct {\n\tURL         string\n\tinsecureTLS bool\n\ttimeout     float64\n}\n\nfunc init() {\n\tConnectors[\"graphite\"] = func(settings map[string]interface{}) (Connector, error) {\n\t\tvar err error\n\n\t\tconnector := &GraphiteConnector{\n\t\t\tinsecureTLS: false,\n\t\t}\n\n\t\tif connector.URL, err = config.GetString(settings, \"url\", true); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif connector.insecureTLS, err = config.GetBool(settings, \"allow_insecure_tls\", false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif connector.timeout, err = config.GetFloat(settings, \"timeout\", false); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif connector.timeout <= 0 {\n\t\t\tconnector.timeout = graphiteDefaultTimeout\n\t\t}\n\n\t\treturn connector, nil\n\t}\n}\n\n\/\/ GetPlots retrieves time series data from provider based on a query and a time interval.\nfunc (connector *GraphiteConnector) GetPlots(query *types.PlotQuery) ([]*types.PlotResult, error) {\n\tvar result []*types.PlotResult\n\n\tif len(query.Group.Series) == 0 {\n\t\treturn nil, fmt.Errorf(\"group has no series\")\n\t} else if query.Group.Type != OperGroupTypeNone && len(query.Group.Series) == 1 {\n\t\tquery.Group.Type = OperGroupTypeNone\n\t}\n\n\tqueryURL, err := graphiteBuildQueryURL(query.Group, query.StartTime, query.EndTime, query.Sample)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to build Graphite query URL: %s\", err)\n\t}\n\n\thttpTransport := &http.Transport{\n\t\tDial: (&net.Dialer{\n\t\t\t\/\/ Enable dual IPv4\/IPv6 stack connectivity:\n\t\t\tDualStack: true,\n\t\t\t\/\/ Enforce HTTP connection timeout:\n\t\t\tTimeout: time.Duration(connector.timeout) * time.Second,\n\t\t}).Dial,\n\t}\n\n\tif connector.insecureTLS {\n\t\thttpTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\t}\n\n\thttpClient := http.Client{Transport: httpTransport}\n\n\trequest, err := http.NewRequest(\"GET\", strings.TrimSuffix(connector.URL, \"\/\")+queryURL, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to set up HTTP request: %s\", err)\n\t}\n\n\trequest.Header.Add(\"User-Agent\", \"Facette\")\n\trequest.Header.Add(\"X-Requested-With\", \"GraphiteConnector\")\n\n\tresponse, err := httpClient.Do(request)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to perform HTTP request: %s\", err)\n\t}\n\n\tif err = graphiteCheckBackendResponse(response); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid HTTP backend response: %s\", err)\n\t}\n\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read HTTP response body: %s\", err)\n\t}\n\n\tgraphitePlots := make([]graphitePlot, 0)\n\tif err = json.Unmarshal(data, &graphitePlots); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to unmarshal JSON data: %s\", err)\n\t}\n\n\tif result, err = graphiteExtractPlotResult(graphitePlots); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to extract plot values from backend response: %s\", err)\n\t}\n\n\treturn result, nil\n}\n\n\/\/ Refresh triggers a full connector data update.\nfunc (connector *GraphiteConnector) Refresh(originName string, outputChan chan *catalog.CatalogRecord) error {\n\thttpTransport := &http.Transport{\n\t\tDial: (&net.Dialer{\n\t\t\t\/\/ Enable dual IPv4\/IPv6 stack connectivity:\n\t\t\tDualStack: true,\n\t\t\t\/\/ Enforce HTTP connection timeout:\n\t\t\tTimeout: time.Duration(connector.timeout) * time.Second,\n\t\t}).Dial,\n\t}\n\n\tif connector.insecureTLS {\n\t\thttpTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\t}\n\n\thttpClient := http.Client{Transport: httpTransport}\n\n\trequest, err := http.NewRequest(\"GET\", strings.TrimSuffix(connector.URL, \"\/\")+graphiteURLMetrics, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to set up HTTP request: %s\", err)\n\t}\n\n\trequest.Header.Add(\"User-Agent\", \"Facette\")\n\trequest.Header.Add(\"X-Requested-With\", \"GraphiteConnector\")\n\n\tresponse, err := httpClient.Do(request)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to perform HTTP request: %s\", err)\n\t}\n\n\tif err = graphiteCheckBackendResponse(response); err != nil {\n\t\treturn fmt.Errorf(\"invalid HTTP backend response: %s\", err)\n\t}\n\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to read HTTP response body: %s\", err)\n\t}\n\n\tmetrics := make([]string, 0)\n\tif err = json.Unmarshal(data, &metrics); err != nil {\n\t\treturn fmt.Errorf(\"unable to unmarshal JSON data: %s\", err)\n\t}\n\n\tfor _, metric := range metrics {\n\t\tvar sourceName, metricName string\n\n\t\tindex := strings.Index(metric, \".\")\n\n\t\tif index == -1 {\n\t\t\tsourceName = \"unknown\"\n\t\t\tmetricName = metric\n\t\t} else {\n\t\t\tsourceName = metric[0:index]\n\t\t\tmetricName = metric[index+1:]\n\t\t}\n\n\t\toutputChan <- &catalog.CatalogRecord{\n\t\t\tOrigin:    originName,\n\t\t\tSource:    sourceName,\n\t\t\tMetric:    metricName,\n\t\t\tConnector: connector,\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc graphiteCheckBackendResponse(response *http.Response) error {\n\tif response.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"got HTTP status code %d, expected 200\", response.StatusCode)\n\t}\n\n\tif utils.HTTPGetContentType(response) != \"application\/json\" {\n\t\treturn fmt.Errorf(\"got HTTP content type `%s', expected `application\/json'\", response.Header[\"Content-Type\"])\n\t}\n\n\treturn nil\n}\n\nfunc graphiteBuildQueryURL(queryGroup *types.PlotQueryGroup, startTime, endTime time.Time, sample int) (string, error) {\n\tnow := time.Now()\n\n\tfromTime := 0\n\n\tinterval := fmt.Sprintf(\"%.0fseconds\", (endTime.Sub(startTime) \/ time.Duration(sample)).Seconds())\n\n\tqueryURL := fmt.Sprintf(\"%s?format=json\", graphiteURLRender)\n\n\tcount := 0\n\n\tif queryGroup.Type == OperGroupTypeNone {\n\t\tfor _, serie := range queryGroup.Series {\n\t\t\tcount += 1\n\n\t\t\ttarget := fmt.Sprintf(\"%s.%s\", serie.Metric.Source, serie.Metric.Name)\n\n\t\t\tif scale, _ := config.GetFloat(serie.Options, \"scale\", false); scale != 0 {\n\t\t\t\ttarget = fmt.Sprintf(\"scale(%s, %g)\", target, scale)\n\t\t\t}\n\n\t\t\tqueryURL += fmt.Sprintf(\"&target=%s\", target)\n\t\t}\n\t} else {\n\t\tcount += 1\n\n\t\ttargets := make([]string, 0)\n\n\t\tfor _, serie := range queryGroup.Series {\n\t\t\ttargets = append(targets, fmt.Sprintf(\"%s.%s\", serie.Metric.Source, serie.Metric.Name))\n\t\t}\n\n\t\ttarget := fmt.Sprintf(\"group(%s)\", strings.Join(targets, \",\"))\n\n\t\tif scale, _ := config.GetFloat(queryGroup.Series[0].Options, \"scale\", false); scale != 0 {\n\t\t\ttarget = fmt.Sprintf(\"scale(%s, %g)\", target, scale)\n\t\t}\n\n\t\tswitch queryGroup.Type {\n\t\tcase OperGroupTypeAvg:\n\t\t\ttarget = fmt.Sprintf(\"averageSeries(%s)\", target)\n\t\tcase OperGroupTypeSum:\n\t\t\ttarget = fmt.Sprintf(\"sumSeries(%s)\", target)\n\t\t}\n\n\t\tqueryURL += fmt.Sprintf(\"&target=summarize(%s, \\\"%s\\\", \\\"avg\\\")\", target, interval)\n\t}\n\n\tif startTime.Before(now) {\n\t\tfromTime = int(now.Sub(startTime).Seconds())\n\t}\n\n\tqueryURL += fmt.Sprintf(\"&from=-%ds\", fromTime)\n\n\t\/\/ Only specify `until' parameter if endTime is still in the past\n\tif endTime.Before(now) {\n\t\tuntilTime := int(time.Now().Sub(endTime).Seconds())\n\t\tqueryURL += fmt.Sprintf(\"&until=-%ds\", untilTime)\n\t}\n\n\treturn queryURL, nil\n}\n\nfunc graphiteExtractPlotResult(plots []graphitePlot) ([]*types.PlotResult, error) {\n\tresult := make([]*types.PlotResult, 0)\n\n\tfor _, plot := range plots {\n\t\tplotResult := &types.PlotResult{Info: make(map[string]types.PlotValue)}\n\n\t\tfor _, plotPoint := range plot.Datapoints {\n\t\t\tplotResult.Plots = append(plotResult.Plots, types.PlotValue(plotPoint[0]))\n\t\t}\n\n\t\tresult = append(result, plotResult)\n\t}\n\n\treturn result, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build selenium\n\n\/*\n * Copyright (C) 2017 Red Hat, Inc.\n *\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\n *\/\n\npackage tests\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/tebeka\/selenium\"\n\n\tgclient \"github.com\/skydive-project\/skydive\/cmd\/client\"\n\tshttp \"github.com\/skydive-project\/skydive\/http\"\n\t\"github.com\/skydive-project\/skydive\/tests\/helper\"\n)\n\nfunc TestSelenium(t *testing.T) {\n\tgopath := os.Getenv(\"GOPATH\")\n\ttopology := gopath + \"\/src\/github.com\/skydive-project\/skydive\/scripts\/simple.sh\"\n\n\tsetupCmds := []helper.Cmd{\n\t\t{fmt.Sprintf(\"%s start 124.65.54.42\/24 124.65.54.43\/24\", topology), true},\n\t\t{\"sudo docker pull elgalu\/selenium\", true},\n\t\t{\"sudo docker run -d --name=grid -p 4444:24444 -p 5900:25900 -e --shm-size=1g elgalu\/selenium\", true},\n\t\t{\"docker exec grid wait_all_done 30s\", true},\n\t}\n\n\ttearDownCmds := []helper.Cmd{\n\t\t{fmt.Sprintf(\"%s stop\", topology), true},\n\t\t{\"sudo docker exec grid stop\", true},\n\t\t{\"sudo docker stop grid\", true},\n\t\t{\"sudo docker rm grid\", true},\n\t}\n\n\thelper.ExecCmds(t, setupCmds...)\n\tdefer helper.ExecCmds(t, tearDownCmds...)\n\n\tcaps := selenium.Capabilities{\"browserName\": \"chrome\"}\n\twebdriver, err := selenium.NewRemote(caps, \"http:\/\/127.0.0.1:4444\/wd\/hub\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer webdriver.Quit()\n\n\tipaddr, err := getIPv4Addr()\n\tif err != nil {\n\t\tt.Fatal(\"Not able to find Analayzer addr: %v\", err)\n\t}\n\n\tif err := webdriver.Get(\"http:\/\/\" + ipaddr + \":8082\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttime.Sleep(5 * time.Second)\n\n\tstartCapture := func(wd selenium.WebDriver) error {\n\t\tcaptureTab, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='Captures']\")\n\t\tif err != nil || captureTab == nil {\n\t\t\treturn fmt.Errorf(\"Not found capture tab: %v\", err)\n\t\t}\n\t\tif err := captureTab.Click(); err != nil {\n\t\t\treturn fmt.Errorf(\"%v\", err)\n\t\t}\n\t\tcreateBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='create-capture']\")\n\t\tif err != nil || createBtn == nil {\n\t\t\treturn fmt.Errorf(\"Not found create button : %v\", err)\n\t\t}\n\t\tif err := createBtn.Click(); err != nil {\n\t\t\treturn fmt.Errorf(\"%v\", err)\n\t\t}\n\t\ttime.Sleep(2 * time.Second)\n\n\t\tgremlinRdoBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='by-gremlin']\")\n\t\tif err != nil || gremlinRdoBtn == nil {\n\t\t\treturn fmt.Errorf(\"Not found gremlin expression radio button: %v\", err)\n\t\t}\n\t\tif err := gremlinRdoBtn.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tqueryTxtBox, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='capture-query']\")\n\t\tif err != nil || queryTxtBox == nil {\n\t\t\treturn fmt.Errorf(\"Not found Query text box: %v\", err)\n\t\t}\n\t\tif err := queryTxtBox.Clear(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := queryTxtBox.SendKeys(\"G.V().Has('Name', 'br-int', 'Type', 'ovsbridge')\"); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tstartBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='start-capture']\")\n\t\tif err != nil || startBtn == nil {\n\t\t\treturn fmt.Errorf(\"Not found start button: %v\", err)\n\t\t}\n\t\tif err := startBtn.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttime.Sleep(3 * time.Second)\n\n\t\t\/\/check capture created with the given query\n\t\tcaptures, err := wd.FindElements(selenium.ByClassName, \"query\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar foundCapture bool\n\t\tfor _, capture := range captures {\n\t\t\tif txt, _ := capture.Text(); txt == \"G.V().Has('Name', 'br-int', 'Type', 'ovsbridge')\" {\n\t\t\t\tfoundCapture = true\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\t\tif !foundCapture {\n\t\t\treturn fmt.Errorf(\"Capture not found in the list\")\n\t\t}\n\t\treturn nil\n\n\t}\n\n\tinjectPacket := func(wd selenium.WebDriver) error {\n\t\tgeneratorTab, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='Generator']\")\n\t\tif err != nil || generatorTab == nil {\n\t\t\treturn fmt.Errorf(\"Generator tab not found: %v\", err)\n\t\t}\n\t\tif err := generatorTab.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinjectSrc, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='inject-src']\/input\")\n\t\tif err != nil || injectSrc == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := injectSrc.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tauthOptions := &shttp.AuthenticationOpts{}\n\t\tgh := gclient.NewGremlinQueryHelper(authOptions)\n\n\t\tnode1, err := gh.GetNode(\"G.V().Has('Name', 'eth0', 'IPV4', Contains('124.65.54.42\/24')).HasKey('TID')\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnode2, err := gh.GetNode(\"G.V().Has('Name', 'eth0', 'IPV4', Contains('124.65.54.43\/24')).HasKey('TID')\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttid1, _ := node1.GetFieldString(\"TID\")\n\t\ttid2, _ := node2.GetFieldString(\"TID\")\n\n\t\tsrcNode, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@tid='\"+tid1+\"']\")\n\t\tif err != nil || srcNode == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := srcNode.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinjectDst, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='inject-dst']\/input\")\n\t\tif err != nil || injectDst == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := injectDst.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdstNode, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@tid='\"+tid2+\"']\")\n\t\tif err != nil || dstNode == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := dstNode.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinjectBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='inject']\")\n\t\tif err != nil || injectBtn == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif err := injectBtn.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar alertMsg selenium.WebElement\n\t\tfor i := 1; i <= 10; i++ {\n\t\t\talertMsg, err = wd.FindElement(selenium.ByClassName, \"alert-success\")\n\t\t\tif err != nil {\n\t\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tif alertMsg != nil {\n\t\t\tcloseBtn, _ := alertMsg.FindElement(selenium.ByClassName, \"close\")\n\t\t\tif closeBtn != nil {\n\t\t\t\tcloseBtn.Click()\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"No success alert msg.\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tverifyFlows := func(wd selenium.WebDriver) error {\n\t\ttime.Sleep(3 * time.Second)\n\n\t\tflowsTab, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='Flows']\")\n\t\tif err != nil || flowsTab == nil {\n\t\t\treturn fmt.Errorf(\"Flows tab not found: %v\", err)\n\t\t}\n\t\tif err := flowsTab.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tflowQuery, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='flow-table-query']\")\n\t\tif err != nil || flowQuery == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := flowQuery.Clear(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tquery := \"G.Flows().Has('Network.A', '124.65.54.42', 'Network.B', '124.65.54.43')\"\n\t\tif err := flowQuery.SendKeys(query); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\n\t\tflowRow, err := wd.FindElement(selenium.ByClassName, \"flow-row\")\n\t\tif err != nil || flowRow == nil {\n\t\t\treturn err\n\t\t}\n\t\trowData, err := flowRow.FindElements(selenium.ByTagName, \"td\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(rowData) != 7 {\n\t\t\treturn fmt.Errorf(\"By default 7 rows should be return\")\n\t\t}\n\t\ttxt, err := rowData[1].Text()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif txt != \"124.65.54.42\" {\n\t\t\tfmt.Errorf(\"Network.A should be '124.65.54.42' but got: %s\", txt)\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := startCapture(webdriver); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := injectPacket(webdriver); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := verifyFlows(webdriver); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc getIPv4Addr() (string, error) {\n\tifaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, iface := range ifaces {\n\t\t\/\/neglect interfaces which are down\n\t\tif iface.Flags&net.FlagUp == 0 {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/neglect loopback interface\n\t\tif iface.Flags&net.FlagLoopback != 0 {\n\t\t\tcontinue\n\t\t}\n\t\taddrs, err := iface.Addrs()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tfor _, addr := range addrs {\n\t\t\tvar ip net.IP\n\t\t\tswitch t := addr.(type) {\n\t\t\tcase *net.IPNet:\n\t\t\t\tip = t.IP\n\t\t\tcase *net.IPAddr:\n\t\t\t\tip = t.IP\n\t\t\t}\n\t\t\tif ip == nil || ip.IsLoopback() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tip = ip.To4()\n\t\t\tif ip != nil {\n\t\t\t\treturn ip.String(), nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"No IP found\")\n}\n<commit_msg>selenium: add helper to retry when an element is not found<commit_after>\/\/ +build selenium\n\n\/*\n * Copyright (C) 2017 Red Hat, Inc.\n *\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\n *\/\n\npackage tests\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/tebeka\/selenium\"\n\n\tgclient \"github.com\/skydive-project\/skydive\/cmd\/client\"\n\t\"github.com\/skydive-project\/skydive\/common\"\n\tshttp \"github.com\/skydive-project\/skydive\/http\"\n\t\"github.com\/skydive-project\/skydive\/tests\/helper\"\n)\n\nfunc TestSelenium(t *testing.T) {\n\tgopath := os.Getenv(\"GOPATH\")\n\ttopology := gopath + \"\/src\/github.com\/skydive-project\/skydive\/scripts\/simple.sh\"\n\n\tsetupCmds := []helper.Cmd{\n\t\t{fmt.Sprintf(\"%s start 124.65.54.42\/24 124.65.54.43\/24\", topology), true},\n\t\t{\"docker pull elgalu\/selenium\", true},\n\t\t{\"docker run -d --name=grid -p 4444:24444 -p 5900:25900 -e --shm-size=1g elgalu\/selenium\", true},\n\t\t{\"docker exec grid wait_all_done 30s\", true},\n\t}\n\n\ttearDownCmds := []helper.Cmd{\n\t\t{fmt.Sprintf(\"%s stop\", topology), true},\n\t\t{\"docker stop grid\", true},\n\t\t{\"docker rm -f grid\", true},\n\t}\n\n\thelper.ExecCmds(t, setupCmds...)\n\tdefer helper.ExecCmds(t, tearDownCmds...)\n\n\tcaps := selenium.Capabilities{\"browserName\": \"chrome\"}\n\twebdriver, err := selenium.NewRemote(caps, \"http:\/\/127.0.0.1:4444\/wd\/hub\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer webdriver.Quit()\n\n\tipaddr, err := getIPv4Addr()\n\tif err != nil {\n\t\tt.Fatalf(\"Not able to find Analayzer addr: %v\", err)\n\t}\n\n\tif err := webdriver.Get(\"http:\/\/\" + ipaddr + \":8082\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttime.Sleep(5 * time.Second)\n\n\tstartCapture := func(wd selenium.WebDriver) error {\n\t\tcaptureTab, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='Captures']\")\n\t\tif err != nil || captureTab == nil {\n\t\t\treturn fmt.Errorf(\"Not found capture tab: %v\", err)\n\t\t}\n\t\tif err := captureTab.Click(); err != nil {\n\t\t\treturn fmt.Errorf(\"%v\", err)\n\t\t}\n\t\tcreateBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='create-capture']\")\n\t\tif err != nil || createBtn == nil {\n\t\t\treturn fmt.Errorf(\"Not found create button : %v\", err)\n\t\t}\n\t\tif err := createBtn.Click(); err != nil {\n\t\t\treturn fmt.Errorf(\"%v\", err)\n\t\t}\n\t\ttime.Sleep(2 * time.Second)\n\n\t\tgremlinRdoBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='by-gremlin']\")\n\t\tif err != nil || gremlinRdoBtn == nil {\n\t\t\treturn fmt.Errorf(\"Not found gremlin expression radio button: %v\", err)\n\t\t}\n\t\tif err := gremlinRdoBtn.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tqueryTxtBox, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='capture-query']\")\n\t\tif err != nil || queryTxtBox == nil {\n\t\t\treturn fmt.Errorf(\"Not found Query text box: %v\", err)\n\t\t}\n\t\tif err := queryTxtBox.Clear(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := queryTxtBox.SendKeys(\"G.V().Has('Name', 'br-int', 'Type', 'ovsbridge')\"); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tstartBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='start-capture']\")\n\t\tif err != nil || startBtn == nil {\n\t\t\treturn fmt.Errorf(\"Not found start button: %v\", err)\n\t\t}\n\t\tif err := startBtn.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttime.Sleep(3 * time.Second)\n\n\t\t\/\/check capture created with the given query\n\t\tcaptures, err := wd.FindElements(selenium.ByClassName, \"query\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar foundCapture bool\n\t\tfor _, capture := range captures {\n\t\t\tif txt, _ := capture.Text(); txt == \"G.V().Has('Name', 'br-int', 'Type', 'ovsbridge')\" {\n\t\t\t\tfoundCapture = true\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\t\tif !foundCapture {\n\t\t\treturn fmt.Errorf(\"Capture not found in the list\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tfindElement := func(wd selenium.WebDriver, selection, xpath string) (el selenium.WebElement, err error) {\n\t\tcommon.Retry(func() error {\n\t\t\tel, err = wd.FindElement(selection, xpath)\n\t\t\tif err != nil || el == nil {\n\t\t\t\treturn fmt.Errorf(\"Failed to find element for %s (error: %+v)\", xpath, err)\n\t\t\t}\n\t\t\treturn nil\n\t\t}, 10, time.Second)\n\t\treturn\n\t}\n\n\tinjectPacket := func(wd selenium.WebDriver) error {\n\t\tgeneratorTab, err := findElement(wd, selenium.ByXPATH, \".\/\/*[@id='Generator']\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = common.Retry(func() error {\n\t\t\treturn generatorTab.Click()\n\t\t}, 10, time.Second)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Could not click on generator tab: %s\", err.Error())\n\t\t}\n\n\t\tinjectSrc, err := findElement(wd, selenium.ByXPATH, \".\/\/*[@id='inject-src']\/input\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := injectSrc.Click(); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to click on inject input: %s\", err.Error())\n\t\t}\n\n\t\tauthOptions := &shttp.AuthenticationOpts{}\n\t\tgh := gclient.NewGremlinQueryHelper(authOptions)\n\n\t\tnode1, err := gh.GetNode(\"G.V().Has('Name', 'eth0', 'IPV4', Contains('124.65.54.42\/24')).HasKey('TID')\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnode2, err := gh.GetNode(\"G.V().Has('Name', 'eth0', 'IPV4', Contains('124.65.54.43\/24')).HasKey('TID')\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttid1, _ := node1.GetFieldString(\"TID\")\n\t\ttid2, _ := node2.GetFieldString(\"TID\")\n\n\t\tsrcNode, err := findElement(wd, selenium.ByXPATH, \".\/\/*[@tid='\"+tid1+\"']\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := srcNode.Click(); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to click on source node: %s\", err.Error())\n\t\t}\n\n\t\tinjectDst, err := findElement(wd, selenium.ByXPATH, \".\/\/*[@id='inject-dst']\/input\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := injectDst.Click(); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to click on destination input: %s\", err.Error())\n\t\t}\n\n\t\tdstNode, err := findElement(wd, selenium.ByXPATH, \".\/\/*[@tid='\"+tid2+\"']\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := dstNode.Click(); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to click on destination node: %s\", err.Error())\n\t\t}\n\n\t\tinjectBtn, err := findElement(wd, selenium.ByXPATH, \".\/\/*[@id='inject']\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := injectBtn.Click(); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to click on inject button: %s\", err.Error())\n\t\t}\n\n\t\tvar alertMsg selenium.WebElement\n\t\terr = common.Retry(func() error {\n\t\t\talertMsg, err = findElement(wd, selenium.ByClassName, \"alert-success\")\n\t\t\treturn err\n\t\t}, 10, time.Second)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcloseBtn, _ := alertMsg.FindElement(selenium.ByClassName, \"close\")\n\t\tif closeBtn != nil {\n\t\t\tcloseBtn.Click()\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tverifyFlows := func(wd selenium.WebDriver) error {\n\t\ttime.Sleep(3 * time.Second)\n\n\t\tflowsTab, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='Flows']\")\n\t\tif err != nil || flowsTab == nil {\n\t\t\treturn fmt.Errorf(\"Flows tab not found: %v\", err)\n\t\t}\n\t\tif err := flowsTab.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tflowQuery, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='flow-table-query']\")\n\t\tif err != nil || flowQuery == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := flowQuery.Clear(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tquery := \"G.Flows().Has('Network.A', '124.65.54.42', 'Network.B', '124.65.54.43')\"\n\t\tif err := flowQuery.SendKeys(query); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\n\t\tflowRow, err := wd.FindElement(selenium.ByClassName, \"flow-row\")\n\t\tif err != nil || flowRow == nil {\n\t\t\treturn err\n\t\t}\n\t\trowData, err := flowRow.FindElements(selenium.ByTagName, \"td\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(rowData) != 7 {\n\t\t\treturn fmt.Errorf(\"By default 7 rows should be return\")\n\t\t}\n\t\ttxt, err := rowData[1].Text()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif txt != \"124.65.54.42\" {\n\t\t\treturn fmt.Errorf(\"Network.A should be '124.65.54.42' but got: %s\", txt)\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := startCapture(webdriver); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := injectPacket(webdriver); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := verifyFlows(webdriver); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc getIPv4Addr() (string, error) {\n\tifaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, iface := range ifaces {\n\t\t\/\/neglect interfaces which are down\n\t\tif iface.Flags&net.FlagUp == 0 {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/neglect loopback interface\n\t\tif iface.Flags&net.FlagLoopback != 0 {\n\t\t\tcontinue\n\t\t}\n\t\taddrs, err := iface.Addrs()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tfor _, addr := range addrs {\n\t\t\tvar ip net.IP\n\t\t\tswitch t := addr.(type) {\n\t\t\tcase *net.IPNet:\n\t\t\t\tip = t.IP\n\t\t\tcase *net.IPAddr:\n\t\t\t\tip = t.IP\n\t\t\t}\n\t\t\tif ip == nil || ip.IsLoopback() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tip = ip.To4()\n\t\t\tif ip != nil {\n\t\t\t\treturn ip.String(), nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"No IP found\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package mocks\n\nimport \"github.com\/materials-commons\/testify\/mock\"\n\nimport (\n\t\"github.com\/materials-commons\/mcstore\/pkg\/db\/schema\"\n\t\"fmt\"\n)\n\ntype Files struct {\n\tmock.Mock\n}\n\nfunc NewMFiles() *Files {\n\treturn &Files{}\n}\n\nfunc (m *Files) ByID(id string) (*schema.File, error) {\n\tret := m.Called(id)\n\n\tr0 := ret.Get(0).(*schema.File)\n\tr1 := ret.Error(1)\n\n\treturn r0, r1\n}\n\nfunc (m *Files) ByChecksum(checksum string) (*schema.File, error) {\n\tret := m.Called(checksum)\n\n\tr0 := ret.Get(0).(*schema.File)\n\tr1 := ret.Error(1)\n\n\treturn r0, r1\n}\n\nfunc (m *Files) ByPath(name, dirID string) (*schema.File, error) {\n\tret := m.Called(name, dirID)\n\tr0 := ret.Get(0).(*schema.File)\n\tr1 := ret.Error(1)\n\treturn r0, r1\n}\n\nfunc (m *Files) Insert(file *schema.File, dirID string, projectID string) (*schema.File, error) {\n\tret := m.Called()\n\tr0 := ret.Get(0).(*schema.File)\n\tr1 := ret.Error(1)\n\treturn r0, r1\n}\n\nfunc (m *Files) Update(file *schema.File) error {\n\tret := m.Called()\n\tr0 := ret.Error(0)\n\treturn r0\n}\n\nfunc (m *Files) UpdateFields(fileID string, fields map[string]interface{}) error {\n\tret := m.Called(fileID)\n\tr0 := ret.Error(0)\n\treturn r0\n}\n\nfunc (m *Files) Delete(fileID, directoryID, projectID string) (*schema.File, error) {\n\tret := m.Called(fileID, directoryID, projectID)\n\tr0 := ret.Get(0).(*schema.File)\n\tr1 := ret.Error(1)\n\treturn r0, r1\n}\n\nfunc (m *Files) GetProject(fileID string) (*schema.Project, error) {\n\tret := m.Called(fileID)\n\tr0 := ret.Get(0).(*schema.Project)\n\tr1 := ret.Error(1)\n\treturn r0, r1\n}\n\ntype fentry struct {\n\tfile *schema.File\n\terr error\n\tproject *schema.Project\n}\n\ntype Files2 struct {\n\tmethod map[string]*fentry\n\tcurrentMethod string\n}\n\nfunc NewMFiles2() *Files2 {\n\treturn &Files2{\n\t\tmethod: make(map[string]*fentry),\n\t}\n}\n\nfunc (m *Files2) lookup(method string) *fentry {\n\tif e, ok := m.method[method]; ok {\n\t\treturn e\n\t}\n\tpanic(fmt.Sprintf(\"Unable to find method: %s\", method))\n}\n\nfunc (m *Files2) ByID(id string) (*schema.File, error) {\n\te := m.lookup(\"ByID\")\n\treturn e.file, e.err\n}\n\nfunc (m *Files2) ByChecksum(checksum string) (*schema.File, error) {\n\te := m.lookup(\"ByChecksum\")\n\treturn e.file, e.err\n}\n\nfunc (m *Files2) ByPath(name, dirID string) (*schema.File, error) {\n\te := m.lookup(\"ByPath\")\n\treturn e.file, e.err\n}\n\nfunc (m *Files2) Insert(file *schema.File, dirID string, projectID string) (*schema.File, error) {\n\te := m.lookup(\"Insert\")\n\treturn e.file, e.err\n}\n\nfunc (m *Files2) Update(file *schema.File) error {\n\te := m.lookup(\"Update\")\n\treturn e.err\n}\n\nfunc (m *Files2) UpdateFields(fileID string, fields map[string]interface{}) error {\n\te := m.lookup(\"UpdateFields\")\n\treturn e.err\n}\n\nfunc (m *Files2) Delete(fileID, directoryID, projectID string) (*schema.File, error) {\n\te := m.lookup(\"Delete\")\n\treturn e.file, e.err\n}\n\nfunc (m *Files2) GetProject(fileID string) (*schema.Project, error) {\n\te := m.lookup(\"GetProject\")\n\treturn e.project, e.err\n}\n\nfunc (m *Files2) On(method string) *Files2 {\n\tm.currentMethod = method\n\tm.method[method] = &fentry{}\n\treturn m\n}\n\nfunc (m *Files2) SetError(err error) *Files2 {\n\tm.method[m.currentMethod].err = err\n\treturn m\n}\n\nfunc (m *Files2) SetFile(file *schema.File) *Files2 {\n\tm.method[m.currentMethod].file = file\n\treturn m\n}\n\nfunc (m *Files2) SetProject(project *schema.Project) *Files2 {\n\tm.method[m.currentMethod].project = project\n\treturn m\n}<commit_msg>gofmt<commit_after>package mocks\n\nimport \"github.com\/materials-commons\/testify\/mock\"\n\nimport (\n\t\"fmt\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/db\/schema\"\n)\n\ntype Files struct {\n\tmock.Mock\n}\n\nfunc NewMFiles() *Files {\n\treturn &Files{}\n}\n\nfunc (m *Files) ByID(id string) (*schema.File, error) {\n\tret := m.Called(id)\n\n\tr0 := ret.Get(0).(*schema.File)\n\tr1 := ret.Error(1)\n\n\treturn r0, r1\n}\n\nfunc (m *Files) ByChecksum(checksum string) (*schema.File, error) {\n\tret := m.Called(checksum)\n\n\tr0 := ret.Get(0).(*schema.File)\n\tr1 := ret.Error(1)\n\n\treturn r0, r1\n}\n\nfunc (m *Files) ByPath(name, dirID string) (*schema.File, error) {\n\tret := m.Called(name, dirID)\n\tr0 := ret.Get(0).(*schema.File)\n\tr1 := ret.Error(1)\n\treturn r0, r1\n}\n\nfunc (m *Files) Insert(file *schema.File, dirID string, projectID string) (*schema.File, error) {\n\tret := m.Called()\n\tr0 := ret.Get(0).(*schema.File)\n\tr1 := ret.Error(1)\n\treturn r0, r1\n}\n\nfunc (m *Files) Update(file *schema.File) error {\n\tret := m.Called()\n\tr0 := ret.Error(0)\n\treturn r0\n}\n\nfunc (m *Files) UpdateFields(fileID string, fields map[string]interface{}) error {\n\tret := m.Called(fileID)\n\tr0 := ret.Error(0)\n\treturn r0\n}\n\nfunc (m *Files) Delete(fileID, directoryID, projectID string) (*schema.File, error) {\n\tret := m.Called(fileID, directoryID, projectID)\n\tr0 := ret.Get(0).(*schema.File)\n\tr1 := ret.Error(1)\n\treturn r0, r1\n}\n\nfunc (m *Files) GetProject(fileID string) (*schema.Project, error) {\n\tret := m.Called(fileID)\n\tr0 := ret.Get(0).(*schema.Project)\n\tr1 := ret.Error(1)\n\treturn r0, r1\n}\n\ntype fentry struct {\n\tfile    *schema.File\n\terr     error\n\tproject *schema.Project\n}\n\ntype Files2 struct {\n\tmethod        map[string]*fentry\n\tcurrentMethod string\n}\n\nfunc NewMFiles2() *Files2 {\n\treturn &Files2{\n\t\tmethod: make(map[string]*fentry),\n\t}\n}\n\nfunc (m *Files2) lookup(method string) *fentry {\n\tif e, ok := m.method[method]; ok {\n\t\treturn e\n\t}\n\tpanic(fmt.Sprintf(\"Unable to find method: %s\", method))\n}\n\nfunc (m *Files2) ByID(id string) (*schema.File, error) {\n\te := m.lookup(\"ByID\")\n\treturn e.file, e.err\n}\n\nfunc (m *Files2) ByChecksum(checksum string) (*schema.File, error) {\n\te := m.lookup(\"ByChecksum\")\n\treturn e.file, e.err\n}\n\nfunc (m *Files2) ByPath(name, dirID string) (*schema.File, error) {\n\te := m.lookup(\"ByPath\")\n\treturn e.file, e.err\n}\n\nfunc (m *Files2) Insert(file *schema.File, dirID string, projectID string) (*schema.File, error) {\n\te := m.lookup(\"Insert\")\n\treturn e.file, e.err\n}\n\nfunc (m *Files2) Update(file *schema.File) error {\n\te := m.lookup(\"Update\")\n\treturn e.err\n}\n\nfunc (m *Files2) UpdateFields(fileID string, fields map[string]interface{}) error {\n\te := m.lookup(\"UpdateFields\")\n\treturn e.err\n}\n\nfunc (m *Files2) Delete(fileID, directoryID, projectID string) (*schema.File, error) {\n\te := m.lookup(\"Delete\")\n\treturn e.file, e.err\n}\n\nfunc (m *Files2) GetProject(fileID string) (*schema.Project, error) {\n\te := m.lookup(\"GetProject\")\n\treturn e.project, e.err\n}\n\nfunc (m *Files2) On(method string) *Files2 {\n\tm.currentMethod = method\n\tm.method[method] = &fentry{}\n\treturn m\n}\n\nfunc (m *Files2) SetError(err error) *Files2 {\n\tm.method[m.currentMethod].err = err\n\treturn m\n}\n\nfunc (m *Files2) SetFile(file *schema.File) *Files2 {\n\tm.method[m.currentMethod].file = file\n\treturn m\n}\n\nfunc (m *Files2) SetProject(project *schema.Project) *Files2 {\n\tm.method[m.currentMethod].project = project\n\treturn m\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016-2017 Authors of Cilium\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage k8s\n\nimport (\n\tk8sconst \"github.com\/cilium\/cilium\/pkg\/k8s\/apis\/cilium.io\"\n\t\"github.com\/cilium\/cilium\/pkg\/labels\"\n\t\"github.com\/cilium\/cilium\/pkg\/policy\"\n\t\"github.com\/cilium\/cilium\/pkg\/policy\/api\"\n\n\tnetworkingv1 \"k8s.io\/api\/networking\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\n\/\/ GetPolicyLabelsv1 extracts the name of policy name\nfunc GetPolicyLabelsv1(np *networkingv1.NetworkPolicy) labels.LabelArray {\n\tpolicyName := np.Annotations[AnnotationName]\n\tif policyName == \"\" {\n\t\tpolicyName = np.Name\n\t}\n\n\tns := k8sconst.ExtractNamespace(&np.ObjectMeta)\n\n\treturn k8sconst.GetPolicyLabels(ns, policyName)\n}\n\nfunc parseNetworkPolicyPeer(namespace string, peer *networkingv1.NetworkPolicyPeer) *api.EndpointSelector {\n\tvar labelSelector *metav1.LabelSelector\n\n\t\/\/ Only one or the other can be set, not both\n\tif peer.PodSelector != nil {\n\t\tlabelSelector = peer.PodSelector\n\t\tif peer.PodSelector.MatchLabels == nil {\n\t\t\tpeer.PodSelector.MatchLabels = map[string]string{}\n\t\t}\n\t\t\/\/ The PodSelector should only reflect to the same namespace\n\t\t\/\/ the policy is being stored, thus we add the namespace to\n\t\t\/\/ the MatchLabels map.\n\t\tpeer.PodSelector.MatchLabels[k8sconst.PodNamespaceLabel] = namespace\n\t} else if peer.NamespaceSelector != nil {\n\t\tlabelSelector = peer.NamespaceSelector\n\t\tmatchLabels := map[string]string{}\n\t\t\/\/ We use our own special label prefix for namespace metadata,\n\t\t\/\/ thus we need to prefix that prefix to all NamespaceSelector.MatchLabels\n\t\tfor k, v := range peer.NamespaceSelector.MatchLabels {\n\t\t\tmatchLabels[policy.JoinPath(PodNamespaceMetaLabels, k)] = v\n\t\t}\n\t\tpeer.NamespaceSelector.MatchLabels = matchLabels\n\n\t\t\/\/ We use our own special label prefix for namespace metadata,\n\t\t\/\/ thus we need to prefix that prefix to all NamespaceSelector.MatchLabels\n\t\tfor i, lsr := range peer.NamespaceSelector.MatchExpressions {\n\t\t\tlsr.Key = policy.JoinPath(PodNamespaceMetaLabels, lsr.Key)\n\t\t\tpeer.NamespaceSelector.MatchExpressions[i] = lsr\n\t\t}\n\t} else {\n\t\t\/\/ Neither PodSelector nor NamespaceSelector set.\n\t\treturn nil\n\t}\n\n\tselector := api.NewESFromK8sLabelSelector(labels.LabelSourceK8sKeyPrefix, labelSelector)\n\treturn &selector\n}\n\n\/\/ ParseNetworkPolicy parses a k8s NetworkPolicy. Returns a list of\n\/\/ Cilium policy rules that can be added, along with an error if there was an\n\/\/ error sanitizing the rules.\nfunc ParseNetworkPolicy(np *networkingv1.NetworkPolicy) (api.Rules, error) {\n\tingresses := []api.IngressRule{}\n\tegresses := []api.EgressRule{}\n\n\tnamespace := k8sconst.ExtractNamespace(&np.ObjectMeta)\n\tfor _, iRule := range np.Spec.Ingress {\n\t\tingress := api.IngressRule{}\n\t\tif iRule.From != nil && len(iRule.From) > 0 {\n\t\t\tfor _, rule := range iRule.From {\n\t\t\t\tendpointSelector := parseNetworkPolicyPeer(namespace, &rule)\n\n\t\t\t\t\/\/ Case where no label-based selectors were in rule.\n\t\t\t\tif endpointSelector != nil {\n\t\t\t\t\tingress.FromEndpoints = append(ingress.FromEndpoints, *endpointSelector)\n\t\t\t\t}\n\n\t\t\t\t\/\/ Parse CIDR-based parts of rule.\n\t\t\t\tif rule.IPBlock != nil {\n\t\t\t\t\tingress.FromCIDRSet = append(ingress.FromCIDRSet, ipBlockToCIDRRule(rule.IPBlock))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif iRule.Ports != nil && len(iRule.Ports) > 0 {\n\t\t\tingress.ToPorts = parsePorts(iRule.Ports)\n\t\t} else if iRule.From == nil || len(iRule.From) == 0 {\n\t\t\t\/\/ Based on NetworkPolicyIngressRule docs:\n\t\t\t\/\/   From []NetworkPolicyPeer\n\t\t\t\/\/   If this field is empty or missing, this rule matches all\n\t\t\t\/\/   sources (traffic not restricted by source).\n\t\t\tall := api.NewESFromLabels(\n\t\t\t\tlabels.NewLabel(labels.IDNameAll, \"\", labels.LabelSourceReserved),\n\t\t\t)\n\t\t\tingress.FromEndpoints = append(ingress.FromEndpoints, all)\n\t\t}\n\n\t\tingresses = append(ingresses, ingress)\n\t}\n\n\tfor _, eRule := range np.Spec.Egress {\n\t\tegress := api.EgressRule{}\n\t\tif eRule.To != nil && len(eRule.To) > 0 {\n\t\t\tfor _, rule := range eRule.To {\n\t\t\t\tif rule.NamespaceSelector != nil || rule.PodSelector != nil {\n\t\t\t\t\t\/\/ TODO: GH-2095\n\t\t\t\t\tlog.Warning(\"Cilium does not support PodSelector or NamespaceSelector for K8s Egress rules\")\n\t\t\t\t}\n\t\t\t\tif rule.IPBlock != nil {\n\t\t\t\t\tegress.ToCIDRSet = append(egress.ToCIDRSet, ipBlockToCIDRRule(rule.IPBlock))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tegresses = append(egresses, egress)\n\t}\n\n\tif np.Spec.PodSelector.MatchLabels == nil {\n\t\tnp.Spec.PodSelector.MatchLabels = map[string]string{}\n\t}\n\tnp.Spec.PodSelector.MatchLabels[k8sconst.PodNamespaceLabel] = namespace\n\n\trule := &api.Rule{\n\t\tEndpointSelector: api.NewESFromK8sLabelSelector(labels.LabelSourceK8sKeyPrefix, &np.Spec.PodSelector),\n\t\tLabels:           GetPolicyLabelsv1(np),\n\t\tIngress:          ingresses,\n\t\tEgress:           egresses,\n\t}\n\n\tif err := rule.Sanitize(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn api.Rules{rule}, nil\n}\n\nfunc ipBlockToCIDRRule(block *networkingv1.IPBlock) api.CIDRRule {\n\tcidrRule := api.CIDRRule{}\n\tcidrRule.Cidr = api.CIDR(block.CIDR)\n\tfor _, v := range block.Except {\n\t\tcidrRule.ExceptCIDRs = append(cidrRule.ExceptCIDRs, api.CIDR(v))\n\t}\n\treturn cidrRule\n}\n\n\/\/ Converts list of K8s NetworkPolicyPorts to Cilium PortRules.\n\/\/ Assumes that provided list of NetworkPolicyPorts is not nil.\nfunc parsePorts(ports []networkingv1.NetworkPolicyPort) []api.PortRule {\n\tportRules := []api.PortRule{}\n\tfor _, port := range ports {\n\t\tif port.Protocol == nil && port.Port == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tprotocol := api.ProtoTCP\n\t\tif port.Protocol != nil {\n\t\t\tprotocol, _ = api.ParseL4Proto(string(*port.Protocol))\n\t\t}\n\n\t\tportStr := \"\"\n\t\tif port.Port != nil {\n\t\t\tportStr = port.Port.String()\n\t\t}\n\n\t\tportRule := api.PortRule{\n\t\t\tPorts: []api.PortProtocol{\n\t\t\t\t{Port: portStr, Protocol: protocol},\n\t\t\t},\n\t\t}\n\n\t\tportRules = append(portRules, portRule)\n\t}\n\n\treturn portRules\n}\n<commit_msg>pkg\/k8s: log when NetworkPolicy does not have Pod \/ Namespace Selector<commit_after>\/\/ Copyright 2016-2017 Authors of Cilium\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage k8s\n\nimport (\n\tk8sconst \"github.com\/cilium\/cilium\/pkg\/k8s\/apis\/cilium.io\"\n\t\"github.com\/cilium\/cilium\/pkg\/labels\"\n\t\"github.com\/cilium\/cilium\/pkg\/logging\/logfields\"\n\t\"github.com\/cilium\/cilium\/pkg\/policy\"\n\t\"github.com\/cilium\/cilium\/pkg\/policy\/api\"\n\n\tnetworkingv1 \"k8s.io\/api\/networking\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\n\/\/ GetPolicyLabelsv1 extracts the name of policy name\nfunc GetPolicyLabelsv1(np *networkingv1.NetworkPolicy) labels.LabelArray {\n\tpolicyName := np.Annotations[AnnotationName]\n\tif policyName == \"\" {\n\t\tpolicyName = np.Name\n\t}\n\n\tns := k8sconst.ExtractNamespace(&np.ObjectMeta)\n\n\treturn k8sconst.GetPolicyLabels(ns, policyName)\n}\n\nfunc parseNetworkPolicyPeer(namespace string, peer *networkingv1.NetworkPolicyPeer) *api.EndpointSelector {\n\tvar labelSelector *metav1.LabelSelector\n\n\t\/\/ Only one or the other can be set, not both\n\tif peer.PodSelector != nil {\n\t\tlabelSelector = peer.PodSelector\n\t\tif peer.PodSelector.MatchLabels == nil {\n\t\t\tpeer.PodSelector.MatchLabels = map[string]string{}\n\t\t}\n\t\t\/\/ The PodSelector should only reflect to the same namespace\n\t\t\/\/ the policy is being stored, thus we add the namespace to\n\t\t\/\/ the MatchLabels map.\n\t\tpeer.PodSelector.MatchLabels[k8sconst.PodNamespaceLabel] = namespace\n\t} else if peer.NamespaceSelector != nil {\n\t\tlabelSelector = peer.NamespaceSelector\n\t\tmatchLabels := map[string]string{}\n\t\t\/\/ We use our own special label prefix for namespace metadata,\n\t\t\/\/ thus we need to prefix that prefix to all NamespaceSelector.MatchLabels\n\t\tfor k, v := range peer.NamespaceSelector.MatchLabels {\n\t\t\tmatchLabels[policy.JoinPath(PodNamespaceMetaLabels, k)] = v\n\t\t}\n\t\tpeer.NamespaceSelector.MatchLabels = matchLabels\n\n\t\t\/\/ We use our own special label prefix for namespace metadata,\n\t\t\/\/ thus we need to prefix that prefix to all NamespaceSelector.MatchLabels\n\t\tfor i, lsr := range peer.NamespaceSelector.MatchExpressions {\n\t\t\tlsr.Key = policy.JoinPath(PodNamespaceMetaLabels, lsr.Key)\n\t\t\tpeer.NamespaceSelector.MatchExpressions[i] = lsr\n\t\t}\n\t} else {\n\t\t\/\/ Neither PodSelector nor NamespaceSelector set.\n\t\treturn nil\n\t}\n\n\tselector := api.NewESFromK8sLabelSelector(labels.LabelSourceK8sKeyPrefix, labelSelector)\n\treturn &selector\n}\n\n\/\/ ParseNetworkPolicy parses a k8s NetworkPolicy. Returns a list of\n\/\/ Cilium policy rules that can be added, along with an error if there was an\n\/\/ error sanitizing the rules.\nfunc ParseNetworkPolicy(np *networkingv1.NetworkPolicy) (api.Rules, error) {\n\tingresses := []api.IngressRule{}\n\tegresses := []api.EgressRule{}\n\n\tnamespace := k8sconst.ExtractNamespace(&np.ObjectMeta)\n\tfor _, iRule := range np.Spec.Ingress {\n\t\tingress := api.IngressRule{}\n\t\tif iRule.From != nil && len(iRule.From) > 0 {\n\t\t\tfor _, rule := range iRule.From {\n\t\t\t\tendpointSelector := parseNetworkPolicyPeer(namespace, &rule)\n\n\t\t\t\tif endpointSelector != nil {\n\t\t\t\t\tingress.FromEndpoints = append(ingress.FromEndpoints, *endpointSelector)\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ No label-based selectors were in NetworkPolicyPeer.\n\t\t\t\t\tlog.WithField(logfields.K8sNetworkPolicyName, np.Name).Debug(\"NetworkPolicyPeer does not have PodSelector or NamespaceSelector\")\n\t\t\t\t}\n\n\t\t\t\t\/\/ Parse CIDR-based parts of rule.\n\t\t\t\tif rule.IPBlock != nil {\n\t\t\t\t\tingress.FromCIDRSet = append(ingress.FromCIDRSet, ipBlockToCIDRRule(rule.IPBlock))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif iRule.Ports != nil && len(iRule.Ports) > 0 {\n\t\t\tingress.ToPorts = parsePorts(iRule.Ports)\n\t\t} else if iRule.From == nil || len(iRule.From) == 0 {\n\t\t\t\/\/ Based on NetworkPolicyIngressRule docs:\n\t\t\t\/\/   From []NetworkPolicyPeer\n\t\t\t\/\/   If this field is empty or missing, this rule matches all\n\t\t\t\/\/   sources (traffic not restricted by source).\n\t\t\tall := api.NewESFromLabels(\n\t\t\t\tlabels.NewLabel(labels.IDNameAll, \"\", labels.LabelSourceReserved),\n\t\t\t)\n\t\t\tingress.FromEndpoints = append(ingress.FromEndpoints, all)\n\t\t}\n\n\t\tingresses = append(ingresses, ingress)\n\t}\n\n\tfor _, eRule := range np.Spec.Egress {\n\t\tegress := api.EgressRule{}\n\t\tif eRule.To != nil && len(eRule.To) > 0 {\n\t\t\tfor _, rule := range eRule.To {\n\t\t\t\tif rule.NamespaceSelector != nil || rule.PodSelector != nil {\n\t\t\t\t\t\/\/ TODO: GH-2095\n\t\t\t\t\tlog.Warning(\"Cilium does not support PodSelector or NamespaceSelector for K8s Egress rules\")\n\t\t\t\t}\n\t\t\t\tif rule.IPBlock != nil {\n\t\t\t\t\tegress.ToCIDRSet = append(egress.ToCIDRSet, ipBlockToCIDRRule(rule.IPBlock))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tegresses = append(egresses, egress)\n\t}\n\n\tif np.Spec.PodSelector.MatchLabels == nil {\n\t\tnp.Spec.PodSelector.MatchLabels = map[string]string{}\n\t}\n\tnp.Spec.PodSelector.MatchLabels[k8sconst.PodNamespaceLabel] = namespace\n\n\trule := &api.Rule{\n\t\tEndpointSelector: api.NewESFromK8sLabelSelector(labels.LabelSourceK8sKeyPrefix, &np.Spec.PodSelector),\n\t\tLabels:           GetPolicyLabelsv1(np),\n\t\tIngress:          ingresses,\n\t\tEgress:           egresses,\n\t}\n\n\tif err := rule.Sanitize(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn api.Rules{rule}, nil\n}\n\nfunc ipBlockToCIDRRule(block *networkingv1.IPBlock) api.CIDRRule {\n\tcidrRule := api.CIDRRule{}\n\tcidrRule.Cidr = api.CIDR(block.CIDR)\n\tfor _, v := range block.Except {\n\t\tcidrRule.ExceptCIDRs = append(cidrRule.ExceptCIDRs, api.CIDR(v))\n\t}\n\treturn cidrRule\n}\n\n\/\/ Converts list of K8s NetworkPolicyPorts to Cilium PortRules.\n\/\/ Assumes that provided list of NetworkPolicyPorts is not nil.\nfunc parsePorts(ports []networkingv1.NetworkPolicyPort) []api.PortRule {\n\tportRules := []api.PortRule{}\n\tfor _, port := range ports {\n\t\tif port.Protocol == nil && port.Port == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tprotocol := api.ProtoTCP\n\t\tif port.Protocol != nil {\n\t\t\tprotocol, _ = api.ParseL4Proto(string(*port.Protocol))\n\t\t}\n\n\t\tportStr := \"\"\n\t\tif port.Port != nil {\n\t\t\tportStr = port.Port.String()\n\t\t}\n\n\t\tportRule := api.PortRule{\n\t\t\tPorts: []api.PortProtocol{\n\t\t\t\t{Port: portStr, Protocol: protocol},\n\t\t\t},\n\t\t}\n\n\t\tportRules = append(portRules, portRule)\n\t}\n\n\treturn portRules\n}\n<|endoftext|>"}
{"text":"<commit_before>package ginkgo\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar suiteRandomSeed = flag.Int64(\"seed\", time.Now().Unix(), \"The seed used to randomize the spec suite.\")\nvar suiteRandomizeAllSpecs = flag.Bool(\"randomizeAllSpecs\", false, \"If set, ginkgo will randomize all specs together.  By default, ginkgo only randomizes the top level Describe\/Context groups.\")\nvar reporterNoColor = flag.Bool(\"noColor\", false, \"If set, suppress color output in default reporter.\")\nvar reporterSlowSpecThreshold = flag.Float64(\"slowSpecThreshold\", 5.0, \"(in seconds) Specs that take longer to run than this threshold are flagged as slow by the default reporter (default: 5 seconds).\")\nvar reporterNoisyPendings = flag.Bool(\"noisyPendings\", true, \"If set, shout about pending tests.\")\n\nvar globalSuite *suite\n\nfunc init() {\n\tglobalSuite = newSuite()\n}\n\nfunc RunSpecs(t *testing.T, description string) {\n\treporter := newDefaultReporter(*reporterNoColor, *reporterSlowSpecThreshold, *reporterNoisyPendings)\n\tRunSpecsWithCustomReporter(t, description, reporter)\n}\n\nfunc RunSpecsWithCustomReporter(t *testing.T, description string, reporter Reporter) {\n\tglobalSuite.run(t, description, *suiteRandomSeed, *suiteRandomizeAllSpecs, reporter)\n}\n\ntype Done chan<- interface{}\n\nfunc Fail(message string, callerSkip ...int) {\n\tskip := 0\n\tif len(callerSkip) > 0 {\n\t\tskip = callerSkip[0]\n\t}\n\tglobalSuite.fail(message, skip)\n}\n\nfunc Describe(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypeNone, generateCodeLocation(1))\n\treturn true\n}\n\nfunc FDescribe(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypeFocused, generateCodeLocation(1))\n\treturn true\n}\n\nfunc PDescribe(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypePending, generateCodeLocation(1))\n\treturn true\n}\n\nfunc XDescribe(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypePending, generateCodeLocation(1))\n\treturn true\n}\n\nfunc Context(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypeNone, generateCodeLocation(1))\n\treturn true\n}\n\nfunc FContext(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypeFocused, generateCodeLocation(1))\n\treturn true\n}\n\nfunc PContext(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypePending, generateCodeLocation(1))\n\treturn true\n}\n\nfunc XContext(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypePending, generateCodeLocation(1))\n\treturn true\n}\n\nfunc It(text string, body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushItNode(text, body, flagTypeNone, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc FIt(text string, body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushItNode(text, body, flagTypeFocused, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc PIt(text string, body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushItNode(text, body, flagTypePending, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc XIt(text string, body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushItNode(text, body, flagTypePending, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc BeforeEach(body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushBeforeEachNode(body, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc JustBeforeEach(body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushJustBeforeEachNode(body, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc AfterEach(body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushAfterEachNode(body, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc parseTimeout(timeout ...float64) time.Duration {\n\tif len(timeout) == 0 {\n\t\treturn time.Duration(5 * time.Second)\n\t} else {\n\t\treturn time.Duration(timeout[0] * float64(time.Second))\n\t}\n}\n<commit_msg>namespaced flags<commit_after>package ginkgo\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar suiteRandomSeed = flag.Int64(\"ginkgo.seed\", time.Now().Unix(), \"The seed used to randomize the spec suite.\")\nvar suiteRandomizeAllSpecs = flag.Bool(\"ginkgo.randomizeAllSpecs\", false, \"If set, ginkgo will randomize all specs together.  By default, ginkgo only randomizes the top level Describe\/Context groups.\")\nvar reporterNoColor = flag.Bool(\"ginkgo.noColor\", false, \"If set, suppress color output in default reporter.\")\nvar reporterSlowSpecThreshold = flag.Float64(\"ginkgo.slowSpecThreshold\", 5.0, \"(in seconds) Specs that take longer to run than this threshold are flagged as slow by the default reporter (default: 5 seconds).\")\nvar reporterNoisyPendings = flag.Bool(\"ginkgo.noisyPendings\", true, \"If set, default reporter will shout about pending tests.\")\n\nvar globalSuite *suite\n\nfunc init() {\n\tglobalSuite = newSuite()\n}\n\nfunc RunSpecs(t *testing.T, description string) {\n\treporter := newDefaultReporter(*reporterNoColor, *reporterSlowSpecThreshold, *reporterNoisyPendings)\n\tRunSpecsWithCustomReporter(t, description, reporter)\n}\n\nfunc RunSpecsWithCustomReporter(t *testing.T, description string, reporter Reporter) {\n\tglobalSuite.run(t, description, *suiteRandomSeed, *suiteRandomizeAllSpecs, reporter)\n}\n\ntype Done chan<- interface{}\n\nfunc Fail(message string, callerSkip ...int) {\n\tskip := 0\n\tif len(callerSkip) > 0 {\n\t\tskip = callerSkip[0]\n\t}\n\tglobalSuite.fail(message, skip)\n}\n\nfunc Describe(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypeNone, generateCodeLocation(1))\n\treturn true\n}\n\nfunc FDescribe(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypeFocused, generateCodeLocation(1))\n\treturn true\n}\n\nfunc PDescribe(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypePending, generateCodeLocation(1))\n\treturn true\n}\n\nfunc XDescribe(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypePending, generateCodeLocation(1))\n\treturn true\n}\n\nfunc Context(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypeNone, generateCodeLocation(1))\n\treturn true\n}\n\nfunc FContext(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypeFocused, generateCodeLocation(1))\n\treturn true\n}\n\nfunc PContext(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypePending, generateCodeLocation(1))\n\treturn true\n}\n\nfunc XContext(text string, body func()) bool {\n\tglobalSuite.pushContainerNode(text, body, flagTypePending, generateCodeLocation(1))\n\treturn true\n}\n\nfunc It(text string, body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushItNode(text, body, flagTypeNone, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc FIt(text string, body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushItNode(text, body, flagTypeFocused, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc PIt(text string, body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushItNode(text, body, flagTypePending, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc XIt(text string, body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushItNode(text, body, flagTypePending, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc BeforeEach(body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushBeforeEachNode(body, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc JustBeforeEach(body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushJustBeforeEachNode(body, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc AfterEach(body interface{}, timeout ...float64) bool {\n\tglobalSuite.pushAfterEachNode(body, generateCodeLocation(1), parseTimeout(timeout...))\n\treturn true\n}\n\nfunc parseTimeout(timeout ...float64) time.Duration {\n\tif len(timeout) == 0 {\n\t\treturn time.Duration(5 * time.Second)\n\t} else {\n\t\treturn time.Duration(timeout[0] * float64(time.Second))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package ingress\n\nimport (\n\tkubeModels \"github.com\/containerum\/kube-client\/pkg\/model\"\n)\n\ntype Rule struct {\n\tHost      string   `json:\"host\"`\n\tTLSSecret string   `json:\"tls_secret,omitempty\"`\n\tPaths     PathList `json:\"paths\"`\n}\n\nfunc RuleFromKube(kubeRule kubeModels.Rule) Rule {\n\trule := Rule{\n\t\tHost:  kubeRule.Host,\n\t\tPaths: PathListFromKube(kubeRule.Path),\n\t}\n\n\tif kubeRule.TLSSecret != nil {\n\t\trule.TLSSecret = *kubeRule.TLSSecret\n\t}\n\treturn rule\n}\n\nfunc (rule Rule) ToKube() kubeModels.Rule {\n\tkubeRule := kubeModels.Rule{\n\t\tHost: rule.Host,\n\t\tPath: rule.Paths.ToKube(),\n\t}\n\tif rule.TLSSecret != \"\" {\n\t\tkubeRule.TLSSecret = &rule.TLSSecret\n\t}\n\treturn kubeRule\n}\n\nfunc (rule Rule) Copy() Rule {\n\treturn Rule{\n\t\tHost:      rule.Host,\n\t\tTLSSecret: rule.TLSSecret,\n\t\tPaths:     rule.Paths.Copy(),\n\t}\n}\n\ntype RuleList []Rule\n\nfunc RuleListFromKube(kubeList []kubeModels.Rule) RuleList {\n\tvar list RuleList = make([]Rule, 0, len(kubeList))\n\tfor _, rule := range kubeList {\n\t\tlist = append(list, RuleFromKube(rule))\n\t}\n\treturn list\n}\n\nfunc (list RuleList) ToKube() []kubeModels.Rule {\n\tkubeList := make([]kubeModels.Rule, 0, len(list))\n\tfor _, rule := range list {\n\t\tkubeList = append(kubeList, rule.ToKube())\n\t}\n\treturn kubeList\n}\n\nfunc (list RuleList) Len() int {\n\treturn len(list)\n}\n\nfunc (list RuleList) Empty() bool {\n\treturn list.Len() == 0\n}\n\nfunc (list RuleList) Head() Rule {\n\tif list.Empty() {\n\t\treturn Rule{}\n\t}\n\treturn list[0].Copy()\n}\n\nfunc (list RuleList) Copy() RuleList {\n\tcp := append(RuleList{}, list...)\n\tfor i, rule := range cp {\n\t\tcp[i] = rule.Copy()\n\t}\n\treturn cp\n}\n\nfunc (list RuleList) Delete(i int) RuleList {\n\tcp := list.Copy()\n\treturn append(cp[:i], cp[i+1:]...)\n}\n\nfunc (list RuleList) Append(rules ...Rule) RuleList {\n\treturn append(list.Copy(), rules...)\n}\n\nfunc (list RuleList) Hosts() []string {\n\thosts := make([]string, 0, len(list))\n\tfor _, rule := range list {\n\t\thosts = append(hosts, rule.Host)\n\t}\n\treturn hosts\n}\n\nfunc (list RuleList) Paths() PathList {\n\tvar paths = make(PathList, 0, len(list))\n\tfor _, rule := range list {\n\t\tpaths = append(paths, rule.Paths.Copy()...)\n\t}\n\treturn paths\n}\n\nfunc (list RuleList) Services() []Service {\n\tvar services = make([]Service, 0, len(list))\n\tfor _, rule := range list {\n\t\tservices = append(services, rule.Paths.Services()...)\n\t}\n\treturn services\n}\n\nfunc (list RuleList) ServicesNames() []string {\n\tvar services = make([]string, 0, len(list))\n\tfor _, rule := range list {\n\t\tservices = append(services, rule.Paths.ServicesNames()...)\n\t}\n\treturn services\n}\n\nfunc (list RuleList) ServicesTableView() []string {\n\tvar services = make([]string, 0, len(list))\n\tfor _, rule := range list {\n\t\tservices = append(services, rule.Paths.ServicesTableView()...)\n\t}\n\treturn services\n}\n<commit_msg>add empty service list signalisation<commit_after>package ingress\n\nimport (\n\tkubeModels \"github.com\/containerum\/kube-client\/pkg\/model\"\n)\n\ntype Rule struct {\n\tHost      string   `json:\"host\"`\n\tTLSSecret string   `json:\"tls_secret,omitempty\"`\n\tPaths     PathList `json:\"paths\"`\n}\n\nfunc RuleFromKube(kubeRule kubeModels.Rule) Rule {\n\trule := Rule{\n\t\tHost:  kubeRule.Host,\n\t\tPaths: PathListFromKube(kubeRule.Path),\n\t}\n\n\tif kubeRule.TLSSecret != nil {\n\t\trule.TLSSecret = *kubeRule.TLSSecret\n\t}\n\treturn rule\n}\n\nfunc (rule Rule) ToKube() kubeModels.Rule {\n\tkubeRule := kubeModels.Rule{\n\t\tHost: rule.Host,\n\t\tPath: rule.Paths.ToKube(),\n\t}\n\tif rule.TLSSecret != \"\" {\n\t\tkubeRule.TLSSecret = &rule.TLSSecret\n\t}\n\treturn kubeRule\n}\n\nfunc (rule Rule) Copy() Rule {\n\treturn Rule{\n\t\tHost:      rule.Host,\n\t\tTLSSecret: rule.TLSSecret,\n\t\tPaths:     rule.Paths.Copy(),\n\t}\n}\n\ntype RuleList []Rule\n\nfunc RuleListFromKube(kubeList []kubeModels.Rule) RuleList {\n\tvar list RuleList = make([]Rule, 0, len(kubeList))\n\tfor _, rule := range kubeList {\n\t\tlist = append(list, RuleFromKube(rule))\n\t}\n\treturn list\n}\n\nfunc (list RuleList) ToKube() []kubeModels.Rule {\n\tkubeList := make([]kubeModels.Rule, 0, len(list))\n\tfor _, rule := range list {\n\t\tkubeList = append(kubeList, rule.ToKube())\n\t}\n\treturn kubeList\n}\n\nfunc (list RuleList) Len() int {\n\treturn len(list)\n}\n\nfunc (list RuleList) Empty() bool {\n\treturn list.Len() == 0\n}\n\nfunc (list RuleList) Head() Rule {\n\tif list.Empty() {\n\t\treturn Rule{}\n\t}\n\treturn list[0].Copy()\n}\n\nfunc (list RuleList) Copy() RuleList {\n\tcp := append(RuleList{}, list...)\n\tfor i, rule := range cp {\n\t\tcp[i] = rule.Copy()\n\t}\n\treturn cp\n}\n\nfunc (list RuleList) Delete(i int) RuleList {\n\tcp := list.Copy()\n\treturn append(cp[:i], cp[i+1:]...)\n}\n\nfunc (list RuleList) Append(rules ...Rule) RuleList {\n\treturn append(list.Copy(), rules...)\n}\n\nfunc (list RuleList) Hosts() []string {\n\thosts := make([]string, 0, len(list))\n\tfor _, rule := range list {\n\t\thosts = append(hosts, rule.Host)\n\t}\n\treturn hosts\n}\n\nfunc (list RuleList) Paths() PathList {\n\tvar paths = make(PathList, 0, len(list))\n\tfor _, rule := range list {\n\t\tpaths = append(paths, rule.Paths.Copy()...)\n\t}\n\treturn paths\n}\n\nfunc (list RuleList) Services() []Service {\n\tvar services = make([]Service, 0, len(list))\n\tfor _, rule := range list {\n\t\tservices = append(services, rule.Paths.Services()...)\n\t}\n\treturn services\n}\n\nfunc (list RuleList) ServicesNames() []string {\n\tvar services = make([]string, 0, len(list))\n\tfor _, rule := range list {\n\t\tservices = append(services, rule.Paths.ServicesNames()...)\n\t}\n\treturn services\n}\n\nfunc (list RuleList) ServicesTableView() []string {\n\tvar services = make([]string, 0, len(list))\n\tfor _, rule := range list {\n\t\tservices = append(services, rule.Paths.ServicesTableView()...)\n\t}\n\tif len(services) == 0 {\n\t\treturn []string{\"!MISSING SERVICE!\"}\n\t}\n\treturn services\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Use and distribution licensed under the Apache license version 2.\n\/\/\n\/\/ See the COPYING file in the root project directory for full text.\n\/\/\n\npackage snapshot\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/ Attempting to tar up pseudofiles like \/proc\/cpuinfo is an exercise in\n\/\/ futility. Notably, the pseudofiles, when read by syscalls, do not return the\n\/\/ number of bytes read. This causes the tar writer to write zero-length files.\n\/\/\n\/\/ Instead, it is necessary to build a directory structure in a tmpdir and\n\/\/ create actual files with copies of the pseudofile contents\n\n\/\/ CloneTreeInto copies all the pseudofiles that ghw will consume into the root\n\/\/ `scratchDir`, preserving the hieratchy.\nfunc CloneTreeInto(scratchDir string) error {\n\terr := setupScratchDir(scratchDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfileSpecs := ExpectedCloneContent()\n\treturn CopyFilesInto(fileSpecs, scratchDir, nil)\n}\n\n\/\/ ExpectedCloneContent return a slice of glob patterns which represent the pseudofiles\n\/\/ ghw cares about.\n\/\/ The intended usage of this function is to validate a clone tree, checking that the\n\/\/ content matches the expectations.\n\/\/ Beware: the content is host-specific, because the content pertaining some subsystems,\n\/\/ most notably PCI, is host-specific and unpredictable.\nfunc ExpectedCloneContent() []string {\n\tfileSpecs := ExpectedCloneStaticContent()\n\tfileSpecs = append(fileSpecs, ExpectedCloneNetContent()...)\n\tfileSpecs = append(fileSpecs, ExpectedClonePCIContent()...)\n\tfileSpecs = append(fileSpecs, ExpectedCloneGPUContent()...)\n\treturn fileSpecs\n}\n\n\/\/ ValidateClonedTree checks the content of a cloned tree, whose root is `clonedDir`,\n\/\/ against a slice of glob specs which must be included in the cloned tree.\n\/\/ Is not wrong, and this functions doesn't enforce this, that the cloned tree includes\n\/\/ more files than the necessary; ghw will just ignore the files it doesn't care about.\n\/\/ Returns a slice of glob patters expected (given) but not found in the cloned tree,\n\/\/ and the error during the validation (if any).\nfunc ValidateClonedTree(fileSpecs []string, clonedDir string) ([]string, error) {\n\tmissing := []string{}\n\tfor _, fileSpec := range fileSpecs {\n\t\tmatches, err := filepath.Glob(filepath.Join(clonedDir, fileSpec))\n\t\tif err != nil {\n\t\t\treturn missing, err\n\t\t}\n\t\tif len(matches) == 0 {\n\t\t\tmissing = append(missing, fileSpec)\n\t\t}\n\t}\n\treturn missing, nil\n}\n\n\/\/ CopyFileOptions allows to finetune the behaviour of the CopyFilesInto function\ntype CopyFileOptions struct {\n\t\/\/ IsSymlinkFn allows to control the behaviour when handling a symlink.\n\t\/\/ If this hook returns true, the source file is treated as symlink: the cloned\n\t\/\/ tree will thus contain a symlink, with its path adjusted to match the relative\n\t\/\/ path inside the cloned tree. If return false, the symlink will be deferred.\n\t\/\/ The easiest use case of this hook is if you want to avoid symlinks in your cloned\n\t\/\/ tree (having duplicated content). In this case you can just add a function\n\t\/\/ which always return false.\n\tIsSymlinkFn func(path string, info os.FileInfo) bool\n\t\/\/ ShouldCreateDirFn allows to control if empty directories listed as clone\n\t\/\/ content should be created or not. When creating snapshots, empty directories\n\t\/\/ are most often useless (but also harmless). Because of this, directories are only\n\t\/\/ created as side effect of copying the files which are inside, and thus directories\n\t\/\/ are never empty. The only notable exception are device driver on linux: in this\n\t\/\/ case, for a number of technical\/historical reasons, we care about the directory\n\t\/\/ name, but not about the files which are inside.\n\t\/\/ Hence, this is the only case on which ghw clones empty directories.\n\tShouldCreateDirFn func(path string, info os.FileInfo) bool\n}\n\n\/\/ CopyFilesInto copies all the given glob files specs in the given `destDir` directory,\n\/\/ preserving the directory structure. This means you can provide a deeply nested filespec\n\/\/ like\n\/\/ - \/some\/deeply\/nested\/file*\n\/\/ and you DO NOT need to build the tree incrementally like\n\/\/ - \/some\/\n\/\/ - \/some\/deeply\/\n\/\/ ...\n\/\/ all glob patterns supported in `filepath.Glob` are supported.\nfunc CopyFilesInto(fileSpecs []string, destDir string, opts *CopyFileOptions) error {\n\tif opts == nil {\n\t\topts = &CopyFileOptions{\n\t\t\tIsSymlinkFn:       isSymlink,\n\t\t\tShouldCreateDirFn: isDriversDir,\n\t\t}\n\t}\n\tfor _, fileSpec := range fileSpecs {\n\t\ttrace(\"copying spec: %q\\n\", fileSpec)\n\t\tmatches, err := filepath.Glob(fileSpec)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := copyFileTreeInto(matches, destDir, opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc copyFileTreeInto(paths []string, destDir string, opts *CopyFileOptions) error {\n\tfor _, path := range paths {\n\t\ttrace(\"  copying path: %q\\n\", path)\n\t\tbaseDir := filepath.Dir(path)\n\t\tif err := os.MkdirAll(filepath.Join(destDir, baseDir), os.ModePerm); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfi, err := os.Lstat(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ directories must be listed explicitly and created separately.\n\t\t\/\/ In the future we may want to expose this decision as hook point in\n\t\t\/\/ CopyFileOptions, when clear use cases emerge.\n\t\tdestPath := filepath.Join(destDir, path)\n\t\tif fi.IsDir() {\n\t\t\tif opts.ShouldCreateDirFn(path, fi) {\n\t\t\t\tif err := os.MkdirAll(destPath, os.ModePerm); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttrace(\"expanded glob path %q is a directory - skipped\\n\", path)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif opts.IsSymlinkFn(path, fi) {\n\t\t\ttrace(\"    copying link: %q -> %q\\n\", path, destPath)\n\t\t\tif err := copyLink(path, destPath); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\ttrace(\"    copying file: %q -> %q\\n\", path, destPath)\n\t\t\tif err := copyPseudoFile(path, destPath); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc isSymlink(path string, fi os.FileInfo) bool {\n\treturn fi.Mode()&os.ModeSymlink != 0\n}\n\nfunc isDriversDir(path string, fi os.FileInfo) bool {\n\treturn strings.Contains(path, \"drivers\")\n}\n\nfunc copyLink(path, targetPath string) error {\n\ttarget, err := os.Readlink(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttrace(\"      symlink %q -> %q\\n\", target, targetPath)\n\tif err := os.Symlink(target, targetPath); err != nil {\n\t\tif errors.Is(err, os.ErrExist) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc copyPseudoFile(path, targetPath string) error {\n\tbuf, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttrace(\"creating %s\\n\", targetPath)\n\tf, err := os.Create(targetPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err = f.Write(buf); err != nil {\n\t\treturn err\n\t}\n\tf.Close()\n\treturn nil\n}\n<commit_msg>Ignore permission deined errors when creating a snapshot<commit_after>\/\/\n\/\/ Use and distribution licensed under the Apache license version 2.\n\/\/\n\/\/ See the COPYING file in the root project directory for full text.\n\/\/\n\npackage snapshot\n\nimport (\n\t\"errors\"\n\t\"io\/fs\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/ Attempting to tar up pseudofiles like \/proc\/cpuinfo is an exercise in\n\/\/ futility. Notably, the pseudofiles, when read by syscalls, do not return the\n\/\/ number of bytes read. This causes the tar writer to write zero-length files.\n\/\/\n\/\/ Instead, it is necessary to build a directory structure in a tmpdir and\n\/\/ create actual files with copies of the pseudofile contents\n\n\/\/ CloneTreeInto copies all the pseudofiles that ghw will consume into the root\n\/\/ `scratchDir`, preserving the hieratchy.\nfunc CloneTreeInto(scratchDir string) error {\n\terr := setupScratchDir(scratchDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfileSpecs := ExpectedCloneContent()\n\treturn CopyFilesInto(fileSpecs, scratchDir, nil)\n}\n\n\/\/ ExpectedCloneContent return a slice of glob patterns which represent the pseudofiles\n\/\/ ghw cares about.\n\/\/ The intended usage of this function is to validate a clone tree, checking that the\n\/\/ content matches the expectations.\n\/\/ Beware: the content is host-specific, because the content pertaining some subsystems,\n\/\/ most notably PCI, is host-specific and unpredictable.\nfunc ExpectedCloneContent() []string {\n\tfileSpecs := ExpectedCloneStaticContent()\n\tfileSpecs = append(fileSpecs, ExpectedCloneNetContent()...)\n\tfileSpecs = append(fileSpecs, ExpectedClonePCIContent()...)\n\tfileSpecs = append(fileSpecs, ExpectedCloneGPUContent()...)\n\treturn fileSpecs\n}\n\n\/\/ ValidateClonedTree checks the content of a cloned tree, whose root is `clonedDir`,\n\/\/ against a slice of glob specs which must be included in the cloned tree.\n\/\/ Is not wrong, and this functions doesn't enforce this, that the cloned tree includes\n\/\/ more files than the necessary; ghw will just ignore the files it doesn't care about.\n\/\/ Returns a slice of glob patters expected (given) but not found in the cloned tree,\n\/\/ and the error during the validation (if any).\nfunc ValidateClonedTree(fileSpecs []string, clonedDir string) ([]string, error) {\n\tmissing := []string{}\n\tfor _, fileSpec := range fileSpecs {\n\t\tmatches, err := filepath.Glob(filepath.Join(clonedDir, fileSpec))\n\t\tif err != nil {\n\t\t\treturn missing, err\n\t\t}\n\t\tif len(matches) == 0 {\n\t\t\tmissing = append(missing, fileSpec)\n\t\t}\n\t}\n\treturn missing, nil\n}\n\n\/\/ CopyFileOptions allows to finetune the behaviour of the CopyFilesInto function\ntype CopyFileOptions struct {\n\t\/\/ IsSymlinkFn allows to control the behaviour when handling a symlink.\n\t\/\/ If this hook returns true, the source file is treated as symlink: the cloned\n\t\/\/ tree will thus contain a symlink, with its path adjusted to match the relative\n\t\/\/ path inside the cloned tree. If return false, the symlink will be deferred.\n\t\/\/ The easiest use case of this hook is if you want to avoid symlinks in your cloned\n\t\/\/ tree (having duplicated content). In this case you can just add a function\n\t\/\/ which always return false.\n\tIsSymlinkFn func(path string, info os.FileInfo) bool\n\t\/\/ ShouldCreateDirFn allows to control if empty directories listed as clone\n\t\/\/ content should be created or not. When creating snapshots, empty directories\n\t\/\/ are most often useless (but also harmless). Because of this, directories are only\n\t\/\/ created as side effect of copying the files which are inside, and thus directories\n\t\/\/ are never empty. The only notable exception are device driver on linux: in this\n\t\/\/ case, for a number of technical\/historical reasons, we care about the directory\n\t\/\/ name, but not about the files which are inside.\n\t\/\/ Hence, this is the only case on which ghw clones empty directories.\n\tShouldCreateDirFn func(path string, info os.FileInfo) bool\n}\n\n\/\/ CopyFilesInto copies all the given glob files specs in the given `destDir` directory,\n\/\/ preserving the directory structure. This means you can provide a deeply nested filespec\n\/\/ like\n\/\/ - \/some\/deeply\/nested\/file*\n\/\/ and you DO NOT need to build the tree incrementally like\n\/\/ - \/some\/\n\/\/ - \/some\/deeply\/\n\/\/ ...\n\/\/ all glob patterns supported in `filepath.Glob` are supported.\nfunc CopyFilesInto(fileSpecs []string, destDir string, opts *CopyFileOptions) error {\n\tif opts == nil {\n\t\topts = &CopyFileOptions{\n\t\t\tIsSymlinkFn:       isSymlink,\n\t\t\tShouldCreateDirFn: isDriversDir,\n\t\t}\n\t}\n\tfor _, fileSpec := range fileSpecs {\n\t\ttrace(\"copying spec: %q\\n\", fileSpec)\n\t\tmatches, err := filepath.Glob(fileSpec)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := copyFileTreeInto(matches, destDir, opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc copyFileTreeInto(paths []string, destDir string, opts *CopyFileOptions) error {\n\tfor _, path := range paths {\n\t\ttrace(\"  copying path: %q\\n\", path)\n\t\tbaseDir := filepath.Dir(path)\n\t\tif err := os.MkdirAll(filepath.Join(destDir, baseDir), os.ModePerm); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfi, err := os.Lstat(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ directories must be listed explicitly and created separately.\n\t\t\/\/ In the future we may want to expose this decision as hook point in\n\t\t\/\/ CopyFileOptions, when clear use cases emerge.\n\t\tdestPath := filepath.Join(destDir, path)\n\t\tif fi.IsDir() {\n\t\t\tif opts.ShouldCreateDirFn(path, fi) {\n\t\t\t\tif err := os.MkdirAll(destPath, os.ModePerm); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttrace(\"expanded glob path %q is a directory - skipped\\n\", path)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif opts.IsSymlinkFn(path, fi) {\n\t\t\ttrace(\"    copying link: %q -> %q\\n\", path, destPath)\n\t\t\tif err := copyLink(path, destPath); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\ttrace(\"    copying file: %q -> %q\\n\", path, destPath)\n\t\t\tif err := copyPseudoFile(path, destPath); err != nil && !errors.Is(err, fs.ErrPermission) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc isSymlink(path string, fi os.FileInfo) bool {\n\treturn fi.Mode()&os.ModeSymlink != 0\n}\n\nfunc isDriversDir(path string, fi os.FileInfo) bool {\n\treturn strings.Contains(path, \"drivers\")\n}\n\nfunc copyLink(path, targetPath string) error {\n\ttarget, err := os.Readlink(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttrace(\"      symlink %q -> %q\\n\", target, targetPath)\n\tif err := os.Symlink(target, targetPath); err != nil {\n\t\tif errors.Is(err, os.ErrExist) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc copyPseudoFile(path, targetPath string) error {\n\tbuf, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttrace(\"creating %s\\n\", targetPath)\n\tf, err := os.Create(targetPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err = f.Write(buf); err != nil {\n\t\treturn err\n\t}\n\tf.Close()\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/appcelerator\/amp\/api\/client\"\n\t\"github.com\/appcelerator\/amp\/cmd\/amp\/cli\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\t\/\/ Version is set with a linker flag (see Makefile)\n\tVersion string\n\n\t\/\/ Build is set with a linker flag (see Makefile)\n\tBuild string\n\n\t\/\/ AMP manages the connection and state for the client\n\tAMP *client.AMP\n\n\t\/\/ Config is used by command implementations to access the computed client configuration.\n\tConfig     client.Configuration\n\tconfigFile string\n\tverbose    bool\n\tserverAddr string\n\n\t\/\/ RootCmd is the base command for the CLI.\n\tRootCmd = &cobra.Command{\n\t\tUse:   \"amp\",\n\t\tShort: \"AMP CLI\",\n\t\tLong:  `AMP CLI.`,\n\t}\n)\n\n\/\/ All main does is process commands and flags and invoke the app\nfunc main() {\n\tfmt.Printf(\"amp (cli version: %s, build: %s)\\n\", Version, Build)\n\n\tcobra.OnInitialize(func() {\n\t\tInitConfig(configFile, &Config, verbose, serverAddr)\n\t\tfmt.Println(\"Server: \" + Config.ServerAddress)\n\t\tAMP = client.NewAMP(&Config)\n\t\tAMP.Connect()\n\t\tcli.AtExit(func() {\n\t\t\tif AMP != nil {\n\t\t\t\tAMP.Disconnect()\n\t\t\t}\n\t\t})\n\t})\n\n\t\/\/ configCmd represents the Config command\n\tconfigCmd := &cobra.Command{\n\t\tUse:   \"config\",\n\t\tShort: \"Display the current configuration\",\n\t\tLong:  `Display the current configuration.`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Println(Config)\n\t\t},\n\t}\n\t\n\tRootCmd.SetUsageTemplate(usageTemplate)\n\tRootCmd.SetHelpTemplate(helpTemplate)\n\n\tRootCmd.PersistentFlags().StringVar(&configFile, \"Config\", \"\", \"Config file (default is $HOME\/.amp.yaml)\")\n\tRootCmd.PersistentFlags().String(\"target\", \"local\", `target environment (\"local\"|\"virtualbox\"|\"aws\")`)\n\tRootCmd.PersistentFlags().BoolVarP(&verbose, \"verbose\", \"v\", false, `verbose output`)\n\tRootCmd.PersistentFlags().StringVar(&serverAddr, \"server\", client.DefaultServerAddress, \"Server address\")\n\n\tRootCmd.AddCommand(configCmd)\n\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tcli.Exit(-1)\n\t}\n\tcli.Exit(0)\n}\n\nvar usageTemplate = `Usage:\t{{if not .HasSubCommands}}{{.UseLine}}{{end}}{{if .HasSubCommands}}{{ .CommandPath}} COMMAND{{end}}\n\n{{ .Short | trim }}{{if gt .Aliases 0}}\n\nAliases:\n  {{.NameAndAliases}}{{end}}{{if .HasExample}}\n\nExamples:\n{{ .Example }}{{end}}{{if .HasFlags}}\n\nOptions:\n{{.Flags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasAvailableSubCommands}}\n\nCommands:{{range .Commands}}{{if .IsAvailableCommand}}\n  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasSubCommands }}\n\nRun '{{.CommandPath}} COMMAND --help' for more information on a command.{{end}}\n`\n\nvar helpTemplate = `\n{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`\n<commit_msg>Reformatting the Root Cmd (#212)<commit_after>package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/appcelerator\/amp\/api\/client\"\n\t\"github.com\/appcelerator\/amp\/cmd\/amp\/cli\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\t\/\/ Version is set with a linker flag (see Makefile)\n\tVersion string\n\n\t\/\/ Build is set with a linker flag (see Makefile)\n\tBuild string\n\n\t\/\/ AMP manages the connection and state for the client\n\tAMP *client.AMP\n\n\t\/\/ Config is used by command implementations to access the computed client configuration.\n\tConfig     client.Configuration\n\tconfigFile string\n\tverbose    bool\n\tserverAddr string\n\n\t\/\/ RootCmd is the base command for the CLI.\n\tRootCmd = &cobra.Command{\n\t\tUse:   \"amp\",\n\t\tShort: \"AMP CLI\",\n\t\tLong:  `AMP CLI.`,\n\t}\n)\n\n\/\/ All main does is process commands and flags and invoke the app\nfunc main() {\n\tfmt.Printf(\"amp (cli version: %s, build: %s)\\n\", Version, Build)\n\n\tcobra.OnInitialize(func() {\n\t\tInitConfig(configFile, &Config, verbose, serverAddr)\n\t\tfmt.Println(\"Server: \" + Config.ServerAddress)\n\t\tAMP = client.NewAMP(&Config)\n\t\tAMP.Connect()\n\t\tcli.AtExit(func() {\n\t\t\tif AMP != nil {\n\t\t\t\tAMP.Disconnect()\n\t\t\t}\n\t\t})\n\t})\n\n\t\/\/ configCmd represents the Config command\n\tconfigCmd := &cobra.Command{\n\t\tUse:   \"config\",\n\t\tShort: \"Display the current configuration\",\n\t\tLong:  `Display the current configuration.`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Println(Config)\n\t\t},\n\t}\n\t\n\tRootCmd.SetUsageTemplate(usageTemplate)\n\tRootCmd.SetHelpTemplate(helpTemplate)\n\n\tRootCmd.PersistentFlags().StringVar(&configFile, \"Config\", \"\", \"Config file (default is $HOME\/.amp.yaml)\")\n\tRootCmd.PersistentFlags().BoolVarP(&verbose, \"verbose\", \"v\", false, `Verbose output`)\n\tRootCmd.PersistentFlags().StringVar(&serverAddr, \"server\", client.DefaultServerAddress, \"Server address\")\n\n\tRootCmd.AddCommand(configCmd)\n\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tcli.Exit(-1)\n\t}\n\tcli.Exit(0)\n}\n\nvar usageTemplate = `Usage:\t{{if not .HasSubCommands}}{{.UseLine}}{{end}}{{if .HasSubCommands}}{{ .CommandPath}} COMMAND{{end}}\n\n{{ .Short | trim }}{{if gt .Aliases 0}}\n\nAliases:\n  {{.NameAndAliases}}{{end}}{{if .HasExample}}\n\nExamples:\n{{ .Example }}{{end}}{{if .HasFlags}}\n\nOptions:\n{{.Flags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasAvailableSubCommands}}\n\nCommands:{{range .Commands}}{{if .IsAvailableCommand}}\n  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasSubCommands }}\n\nRun '{{.CommandPath}} COMMAND --help' for more information on a command.{{end}}\n`\n\nvar helpTemplate = `\n{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\tnetURL \"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/exercism\/cli\/api\"\n\t\"github.com\/exercism\/cli\/config\"\n\t\"github.com\/exercism\/cli\/workspace\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ downloadCmd represents the download command\nvar downloadCmd = &cobra.Command{\n\tUse:     \"download\",\n\tAliases: []string{\"d\"},\n\tShort:   \"Download an exercise.\",\n\tLong: `Download an exercise.\n\nYou may download an exercise to work on. If you've already\nstarted working on it, the command will also download your\nlatest solution.\n\nDownload other people's solutions by providing the UUID.\n`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tcfg := config.NewConfig()\n\n\t\tv := viper.New()\n\t\tv.AddConfigPath(cfg.Dir)\n\t\tv.SetConfigName(\"user\")\n\t\tv.SetConfigType(\"json\")\n\t\t\/\/ Ignore error. If the file doesn't exist, that is fine.\n\t\t_ = v.ReadInConfig()\n\t\tcfg.UserViperConfig = v\n\n\t\treturn runDownload(cfg, cmd.Flags(), args)\n\t},\n}\n\nfunc runDownload(cfg config.Config, flags *pflag.FlagSet, args []string) error {\n\tusrCfg := cfg.UserViperConfig\n\tif err := validateUserConfig(usrCfg); err != nil {\n\t\treturn err\n\t}\n\n\tidentifier, err := downloadIdentifier(flags)\n\tif err != nil {\n\t\treturn err\n\t}\n\turl := fmt.Sprintf(\"%s\/solutions\/%s\", usrCfg.GetString(\"apibaseurl\"), identifier)\n\n\tclient, err := api.NewClient(usrCfg.GetString(\"token\"), usrCfg.GetString(\"apibaseurl\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := client.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err = addQueryToDownloadRequest(flags, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar payload downloadPayload\n\tdefer res.Body.Close()\n\tif err := json.NewDecoder(res.Body).Decode(&payload); err != nil {\n\t\treturn fmt.Errorf(\"unable to parse API response - %s\", err)\n\t}\n\n\tif res.StatusCode == http.StatusUnauthorized {\n\t\tsiteURL := config.InferSiteURL(usrCfg.GetString(\"apibaseurl\"))\n\t\treturn fmt.Errorf(\"unauthorized request. Please run the configure command. You can find your API token at %s\/my\/settings\", siteURL)\n\t}\n\n\tif res.StatusCode != http.StatusOK {\n\t\tswitch payload.Error.Type {\n\t\tcase \"track_ambiguous\":\n\t\t\treturn fmt.Errorf(\"%s: %s\", payload.Error.Message, strings.Join(payload.Error.PossibleTrackIDs, \", \"))\n\t\tdefault:\n\t\t\treturn errors.New(payload.Error.Message)\n\t\t}\n\t}\n\n\tmetadata := payload.metadata()\n\tdir := metadata.Exercise(usrCfg.GetString(\"workspace\")).MetadataDir()\n\n\tif err := os.MkdirAll(dir, os.FileMode(0755)); err != nil {\n\t\treturn err\n\t}\n\n\terr = metadata.Write(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, file := range payload.Solution.Files {\n\t\tunparsedURL := fmt.Sprintf(\"%s%s\", payload.Solution.FileDownloadBaseURL, file)\n\t\tparsedURL, err := netURL.ParseRequestURI(unparsedURL)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\turl := parsedURL.String()\n\n\t\treq, err := client.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tres, err := client.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer res.Body.Close()\n\n\t\tif res.StatusCode != http.StatusOK {\n\t\t\t\/\/ TODO: deal with it\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Don't bother with empty files.\n\t\tif res.Header.Get(\"Content-Length\") == \"0\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ TODO: if there's a collision, interactively resolve (show diff, ask if overwrite).\n\t\t\/\/ TODO: handle --force flag to overwrite without asking.\n\n\t\t\/\/ Work around a path bug due to an early design decision (later reversed) to\n\t\t\/\/ allow numeric suffixes for exercise directories, allowing people to have\n\t\t\/\/ multiple parallel versions of an exercise.\n\t\tpattern := fmt.Sprintf(`\\A.*[\/\\\\]%s-\\d*\/`, metadata.ExerciseSlug)\n\t\trgxNumericSuffix := regexp.MustCompile(pattern)\n\t\tif rgxNumericSuffix.MatchString(file) {\n\t\t\tfile = string(rgxNumericSuffix.ReplaceAll([]byte(file), []byte(\"\")))\n\t\t}\n\n\t\t\/\/ Rewrite paths submitted with an older, buggy client where the Windows path is being treated as part of the filename.\n\t\tfile = strings.Replace(file, \"\\\\\", \"\/\", -1)\n\n\t\trelativePath := filepath.FromSlash(file)\n\t\tdir := filepath.Join(metadata.Dir, filepath.Dir(relativePath))\n\t\tos.MkdirAll(dir, os.FileMode(0755))\n\n\t\tf, err := os.Create(filepath.Join(metadata.Dir, relativePath))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\t_, err = io.Copy(f, res.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfmt.Fprintf(Err, \"\\nDownloaded to\\n\")\n\tfmt.Fprintf(Out, \"%s\\n\", metadata.Dir)\n\treturn nil\n}\n\ntype downloadPayload struct {\n\tSolution struct {\n\t\tID   string `json:\"id\"`\n\t\tURL  string `json:\"url\"`\n\t\tTeam struct {\n\t\t\tName string `json:\"name\"`\n\t\t\tSlug string `json:\"slug\"`\n\t\t} `json:\"team\"`\n\t\tUser struct {\n\t\t\tHandle      string `json:\"handle\"`\n\t\t\tIsRequester bool   `json:\"is_requester\"`\n\t\t} `json:\"user\"`\n\t\tExercise struct {\n\t\t\tID              string `json:\"id\"`\n\t\t\tInstructionsURL string `json:\"instructions_url\"`\n\t\t\tAutoApprove     bool   `json:\"auto_approve\"`\n\t\t\tTrack           struct {\n\t\t\t\tID       string `json:\"id\"`\n\t\t\t\tLanguage string `json:\"language\"`\n\t\t\t} `json:\"track\"`\n\t\t} `json:\"exercise\"`\n\t\tFileDownloadBaseURL string   `json:\"file_download_base_url\"`\n\t\tFiles               []string `json:\"files\"`\n\t\tIteration           struct {\n\t\t\tSubmittedAt *string `json:\"submitted_at\"`\n\t\t}\n\t} `json:\"solution\"`\n\tError struct {\n\t\tType             string   `json:\"type\"`\n\t\tMessage          string   `json:\"message\"`\n\t\tPossibleTrackIDs []string `json:\"possible_track_ids\"`\n\t} `json:\"error,omitempty\"`\n}\n\nfunc (dp downloadPayload) metadata() workspace.ExerciseMetadata {\n\treturn workspace.ExerciseMetadata{\n\t\tAutoApprove:  dp.Solution.Exercise.AutoApprove,\n\t\tTrack:        dp.Solution.Exercise.Track.ID,\n\t\tTeam:         dp.Solution.Team.Slug,\n\t\tExerciseSlug: dp.Solution.Exercise.ID,\n\t\tID:           dp.Solution.ID,\n\t\tURL:          dp.Solution.URL,\n\t\tHandle:       dp.Solution.User.Handle,\n\t\tIsRequester:  dp.Solution.User.IsRequester,\n\t}\n}\n\n\/\/ downloadIdentifier is the variable for the URI to initiate an exercise download.\nfunc downloadIdentifier(flags *pflag.FlagSet) (string, error) {\n\tuuid, err := flags.GetString(\"uuid\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tslug, err := flags.GetString(\"exercise\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif uuid != \"\" && slug != \"\" || uuid == slug {\n\t\treturn \"\", errors.New(\"need an --exercise name or a solution --uuid\")\n\t}\n\n\tidentifier := \"latest\"\n\tif uuid != \"\" {\n\t\tidentifier = uuid\n\t}\n\treturn identifier, nil\n}\n\nfunc addQueryToDownloadRequest(flags *pflag.FlagSet, req *http.Request) (*http.Request, error) {\n\tuuid, err := flags.GetString(\"uuid\")\n\tif err != nil {\n\t\treturn req, err\n\t}\n\tslug, err := flags.GetString(\"exercise\")\n\tif err != nil {\n\t\treturn req, err\n\t}\n\ttrack, err := flags.GetString(\"track\")\n\tif err != nil {\n\t\treturn req, err\n\t}\n\n\tteam, err := flags.GetString(\"team\")\n\tif err != nil {\n\t\treturn req, err\n\t}\n\n\tif uuid == \"\" {\n\t\tq := req.URL.Query()\n\t\tq.Add(\"exercise_id\", slug)\n\t\tif track != \"\" {\n\t\t\tq.Add(\"track_id\", track)\n\t\t}\n\t\tif team != \"\" {\n\t\t\tq.Add(\"team_id\", team)\n\t\t}\n\t\treq.URL.RawQuery = q.Encode()\n\t}\n\treturn req, nil\n}\n\nfunc setupDownloadFlags(flags *pflag.FlagSet) {\n\tflags.StringP(\"uuid\", \"u\", \"\", \"the solution UUID\")\n\tflags.StringP(\"track\", \"t\", \"\", \"the track ID\")\n\tflags.StringP(\"exercise\", \"e\", \"\", \"the exercise slug\")\n\tflags.StringP(\"team\", \"T\", \"\", \"the team slug\")\n}\n\nfunc init() {\n\tRootCmd.AddCommand(downloadCmd)\n\tsetupDownloadFlags(downloadCmd.Flags())\n}\n<commit_msg>Add download type<commit_after>package cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\tnetURL \"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/exercism\/cli\/api\"\n\t\"github.com\/exercism\/cli\/config\"\n\t\"github.com\/exercism\/cli\/workspace\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ downloadCmd represents the download command\nvar downloadCmd = &cobra.Command{\n\tUse:     \"download\",\n\tAliases: []string{\"d\"},\n\tShort:   \"Download an exercise.\",\n\tLong: `Download an exercise.\n\nYou may download an exercise to work on. If you've already\nstarted working on it, the command will also download your\nlatest solution.\n\nDownload other people's solutions by providing the UUID.\n`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tcfg := config.NewConfig()\n\n\t\tv := viper.New()\n\t\tv.AddConfigPath(cfg.Dir)\n\t\tv.SetConfigName(\"user\")\n\t\tv.SetConfigType(\"json\")\n\t\t\/\/ Ignore error. If the file doesn't exist, that is fine.\n\t\t_ = v.ReadInConfig()\n\t\tcfg.UserViperConfig = v\n\n\t\treturn runDownload(cfg, cmd.Flags(), args)\n\t},\n}\n\nfunc runDownload(cfg config.Config, flags *pflag.FlagSet, args []string) error {\n\tusrCfg := cfg.UserViperConfig\n\tif err := validateUserConfig(usrCfg); err != nil {\n\t\treturn err\n\t}\n\n\tdownload, err := newDownload(flags, usrCfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmetadata := download.payload.metadata()\n\tdir := metadata.Exercise(usrCfg.GetString(\"workspace\")).MetadataDir()\n\n\tif err := os.MkdirAll(dir, os.FileMode(0755)); err != nil {\n\t\treturn err\n\t}\n\n\tif err := metadata.Write(dir); err != nil {\n\t\treturn err\n\t}\n\n\tclient, err := api.NewClient(usrCfg.GetString(\"token\"), usrCfg.GetString(\"apibaseurl\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, file := range download.payload.Solution.Files {\n\t\tunparsedURL := fmt.Sprintf(\"%s%s\", download.payload.Solution.FileDownloadBaseURL, file)\n\t\tparsedURL, err := netURL.ParseRequestURI(unparsedURL)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\turl := parsedURL.String()\n\n\t\treq, err := client.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tres, err := client.Do(req)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer res.Body.Close()\n\n\t\tif res.StatusCode != http.StatusOK {\n\t\t\t\/\/ TODO: deal with it\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Don't bother with empty files.\n\t\tif res.Header.Get(\"Content-Length\") == \"0\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ TODO: if there's a collision, interactively resolve (show diff, ask if overwrite).\n\t\t\/\/ TODO: handle --force flag to overwrite without asking.\n\n\t\t\/\/ Work around a path bug due to an early design decision (later reversed) to\n\t\t\/\/ allow numeric suffixes for exercise directories, allowing people to have\n\t\t\/\/ multiple parallel versions of an exercise.\n\t\tpattern := fmt.Sprintf(`\\A.*[\/\\\\]%s-\\d*\/`, metadata.ExerciseSlug)\n\t\trgxNumericSuffix := regexp.MustCompile(pattern)\n\t\tif rgxNumericSuffix.MatchString(file) {\n\t\t\tfile = string(rgxNumericSuffix.ReplaceAll([]byte(file), []byte(\"\")))\n\t\t}\n\n\t\t\/\/ Rewrite paths submitted with an older, buggy client where the Windows path is being treated as part of the filename.\n\t\tfile = strings.Replace(file, \"\\\\\", \"\/\", -1)\n\n\t\trelativePath := filepath.FromSlash(file)\n\t\tdir := filepath.Join(metadata.Dir, filepath.Dir(relativePath))\n\t\tos.MkdirAll(dir, os.FileMode(0755))\n\n\t\tf, err := os.Create(filepath.Join(metadata.Dir, relativePath))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\t_, err = io.Copy(f, res.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfmt.Fprintf(Err, \"\\nDownloaded to\\n\")\n\tfmt.Fprintf(Out, \"%s\\n\", metadata.Dir)\n\treturn nil\n}\n\ntype download struct {\n\t\/\/ either\/or\n\tslug, uuid string\n\n\t\/\/ user config\n\ttoken, apibaseurl, workspace string\n\n\t\/\/ optional\n\ttrack, team string\n\n\tpayload *downloadPayload\n}\n\nfunc newDownload(flags *pflag.FlagSet, usrCfg *viper.Viper) (*download, error) {\n\tvar err error\n\td := &download{}\n\td.uuid, err = flags.GetString(\"uuid\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td.slug, err = flags.GetString(\"exercise\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td.track, err = flags.GetString(\"track\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td.team, err = flags.GetString(\"team\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td.token = usrCfg.GetString(\"token\")\n\td.apibaseurl = usrCfg.GetString(\"apibaseurl\")\n\td.workspace = usrCfg.GetString(\"workspace\")\n\n\tif err = d.needsSlugXorUUID(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err = d.needsUserConfigValues(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err = d.needsSlugWhenGivenTrackOrTeam(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient, err := api.NewClient(d.token, d.apibaseurl)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := client.NewRequest(\"GET\", d.url(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td.buildQueryParams(req.URL)\n\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tif err := json.NewDecoder(res.Body).Decode(&d.payload); err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to parse API response - %s\", err)\n\t}\n\n\tif res.StatusCode == http.StatusUnauthorized {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"unauthorized request. Please run the configure command. You can find your API token at %s\/my\/settings\",\n\t\t\tconfig.InferSiteURL(d.apibaseurl),\n\t\t)\n\t}\n\tif res.StatusCode != http.StatusOK {\n\t\tswitch d.payload.Error.Type {\n\t\tcase \"track_ambiguous\":\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"%s: %s\",\n\t\t\t\td.payload.Error.Message,\n\t\t\t\tstrings.Join(d.payload.Error.PossibleTrackIDs, \", \"),\n\t\t\t)\n\t\tdefault:\n\t\t\treturn nil, errors.New(d.payload.Error.Message)\n\t\t}\n\t}\n\n\treturn d, d.validate()\n}\n\nfunc (d download) url() string {\n\tid := \"latest\"\n\tif d.uuid != \"\" {\n\t\tid = d.uuid\n\t}\n\treturn fmt.Sprintf(\"%s\/solutions\/%s\", d.apibaseurl, id)\n}\n\nfunc (d download) buildQueryParams(url *netURL.URL) {\n\tquery := url.Query()\n\tif d.slug != \"\" {\n\t\tquery.Add(\"exercise_id\", d.slug)\n\t\tif d.track != \"\" {\n\t\t\tquery.Add(\"track_id\", d.track)\n\t\t}\n\t\tif d.team != \"\" {\n\t\t\tquery.Add(\"team_id\", d.team)\n\t\t}\n\t}\n\turl.RawQuery = query.Encode()\n}\n\nfunc (d download) validate() error {\n\tif d.payload.Solution.ID == \"\" {\n\t\treturn errors.New(\"download missing ID\")\n\t}\n\tif d.payload.Error.Message != \"\" {\n\t\treturn errors.New(d.payload.Error.Message)\n\t}\n\treturn nil\n}\n\n\/\/ needsSlugXorUUID checks the presence of slug XOR uuid.\nfunc (d download) needsSlugXorUUID() error {\n\tif d.slug != \"\" && d.uuid != \"\" || d.uuid == d.slug {\n\t\treturn errors.New(\"need an --exercise name or a solution --uuid\")\n\t}\n\treturn nil\n}\n\n\/\/ needsUserConfigValues checks the presence of required values from the user config.\nfunc (d download) needsUserConfigValues() error {\n\terrMsg := \"missing required user config: '%s'\"\n\tif d.token == \"\" {\n\t\treturn fmt.Errorf(errMsg, \"token\")\n\t}\n\tif d.apibaseurl == \"\" {\n\t\treturn fmt.Errorf(errMsg, \"apibaseurl\")\n\t}\n\tif d.workspace == \"\" {\n\t\treturn fmt.Errorf(errMsg, \"workspace\")\n\t}\n\treturn nil\n}\n\n\/\/ needsSlugWhenGivenTrackOrTeam ensures that track\/team arguments are also given with a slug.\n\/\/ (track\/team meaningless when given a uuid).\nfunc (d download) needsSlugWhenGivenTrackOrTeam() error {\n\tif (d.team != \"\" || d.track != \"\") && d.slug == \"\" {\n\t\treturn errors.New(\"--track or --team requires --exercise (not --uuid)\")\n\t}\n\treturn nil\n}\n\ntype downloadPayload struct {\n\tSolution struct {\n\t\tID   string `json:\"id\"`\n\t\tURL  string `json:\"url\"`\n\t\tTeam struct {\n\t\t\tName string `json:\"name\"`\n\t\t\tSlug string `json:\"slug\"`\n\t\t} `json:\"team\"`\n\t\tUser struct {\n\t\t\tHandle      string `json:\"handle\"`\n\t\t\tIsRequester bool   `json:\"is_requester\"`\n\t\t} `json:\"user\"`\n\t\tExercise struct {\n\t\t\tID              string `json:\"id\"`\n\t\t\tInstructionsURL string `json:\"instructions_url\"`\n\t\t\tAutoApprove     bool   `json:\"auto_approve\"`\n\t\t\tTrack           struct {\n\t\t\t\tID       string `json:\"id\"`\n\t\t\t\tLanguage string `json:\"language\"`\n\t\t\t} `json:\"track\"`\n\t\t} `json:\"exercise\"`\n\t\tFileDownloadBaseURL string   `json:\"file_download_base_url\"`\n\t\tFiles               []string `json:\"files\"`\n\t\tIteration           struct {\n\t\t\tSubmittedAt *string `json:\"submitted_at\"`\n\t\t}\n\t} `json:\"solution\"`\n\tError struct {\n\t\tType             string   `json:\"type\"`\n\t\tMessage          string   `json:\"message\"`\n\t\tPossibleTrackIDs []string `json:\"possible_track_ids\"`\n\t} `json:\"error,omitempty\"`\n}\n\nfunc (dp downloadPayload) metadata() workspace.ExerciseMetadata {\n\treturn workspace.ExerciseMetadata{\n\t\tAutoApprove:  dp.Solution.Exercise.AutoApprove,\n\t\tTrack:        dp.Solution.Exercise.Track.ID,\n\t\tTeam:         dp.Solution.Team.Slug,\n\t\tExerciseSlug: dp.Solution.Exercise.ID,\n\t\tID:           dp.Solution.ID,\n\t\tURL:          dp.Solution.URL,\n\t\tHandle:       dp.Solution.User.Handle,\n\t\tIsRequester:  dp.Solution.User.IsRequester,\n\t}\n}\n\nfunc setupDownloadFlags(flags *pflag.FlagSet) {\n\tflags.StringP(\"uuid\", \"u\", \"\", \"the solution UUID\")\n\tflags.StringP(\"track\", \"t\", \"\", \"the track ID\")\n\tflags.StringP(\"exercise\", \"e\", \"\", \"the exercise slug\")\n\tflags.StringP(\"team\", \"T\", \"\", \"the team slug\")\n}\n\nfunc init() {\n\tRootCmd.AddCommand(downloadCmd)\n\tsetupDownloadFlags(downloadCmd.Flags())\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/  Copyright (c) 2015 Couchbase, Inc.\n\/\/  Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/  you may not use this file except in compliance with the\n\/\/  License. You may obtain a copy of the License at\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/  Unless required by applicable law or agreed to in writing,\n\/\/  software distributed under the License is distributed on an \"AS\n\/\/  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n\/\/  express or implied. See the License for the specific language\n\/\/  governing permissions and limitations under the License.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"expvar\"\n\t\"flag\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\"\n\t\"runtime\"\n\t\"runtime\/pprof\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/couchbase\/clog\"\n\n\t\"github.com\/couchbaselabs\/cbgt\"\n\t\"github.com\/couchbaselabs\/cbgt\/cmd\"\n\t\"github.com\/couchbaselabs\/cbgt\/rebalance\"\n)\n\nvar VERSION = \"v0.0.0\"\n\nvar expvars = expvar.NewMap(\"stats\")\n\nfunc main() {\n\tflag.Parse()\n\n\tif flags.Help {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tif flags.Version {\n\t\tfmt.Printf(\"%s main: %s, data: %s\\n\",\n\t\t\tpath.Base(os.Args[0]), VERSION, cbgt.VERSION)\n\t\tos.Exit(0)\n\t}\n\n\tif os.Getenv(\"GOMAXPROCS\") == \"\" {\n\t\truntime.GOMAXPROCS(runtime.NumCPU())\n\t}\n\n\tlog.Printf(\"main: %s started (%s\/%s)\",\n\t\tos.Args[0], VERSION, cbgt.VERSION)\n\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tgo dumpOnSignalForPlatform()\n\n\tMainWelcome(flagAliases)\n\n\tnodesToRemove := []string(nil)\n\tif len(flags.RemoveNodes) > 0 {\n\t\tnodesToRemove = strings.Split(flags.RemoveNodes, \",\")\n\t}\n\n\tbindHttp := \"NO-BIND-HTTP\"\n\tregister := \"unchanged\"\n\tdataDir := \"NO-DATA-DIR\"\n\n\t\/\/ If cfg is down, we error, leaving it to some user-supplied\n\t\/\/ outside watchdog to backoff and restart\/retry.\n\tcfg, err := cmd.MainCfg(\"mcp\", flags.CfgConnect,\n\t\tbindHttp, register, dataDir)\n\tif err != nil {\n\t\tif err == cmd.ErrorBindHttp {\n\t\t\tlog.Fatalf(\"%v\", err)\n\t\t\treturn\n\t\t}\n\t\tlog.Fatalf(\"main: could not start cfg, cfgConnect: %s, err: %v\\n\"+\n\t\t\t\"  Please check that your -cfg\/-cfgConnect parameter (%q)\\n\"+\n\t\t\t\"  is correct and\/or that your configuration provider\\n\"+\n\t\t\t\"  is available.\",\n\t\t\tflags.CfgConnect, err, flags.CfgConnect)\n\t\treturn\n\t}\n\n\tr, err := rebalance.StartRebalance(cbgt.VERSION, cfg, flags.Server,\n\t\tnodesToRemove,\n\t\trebalance.RebalanceOptions{\n\t\t\tDryRun:  flags.DryRun,\n\t\t\tVerbose: flags.Verbose,\n\t\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"main: StartRebalance, err: %v\", err)\n\t\treturn\n\t}\n\n\treportProgress(r)\n\n\tr.Stop()\n\n\tlog.Printf(\"main: done\")\n}\n\n\/\/ ------------------------------------------------------------\n\ntype ProgressEntry struct {\n\tpindex, sourcePartition, node string \/\/ Immutable.\n\n\tstateOp     rebalance.StateOp\n\tinitUUIDSeq cbgt.UUIDSeq\n\tcurrUUIDSeq cbgt.UUIDSeq\n\twantUUIDSeq cbgt.UUIDSeq\n}\n\nfunc reportProgress(r *rebalance.Rebalancer) {\n\tvar lastEmit string\n\n\tmaxNodeLen := 0\n\tmaxPIndexLen := 0\n\n\tseenNodes := map[string]bool{}\n\tseenNodesSorted := []string(nil)\n\n\t\/\/ Map of pindex -> (source) partition -> node -> *ProgressEntry\n\tprogressEntries := map[string]map[string]map[string]*ProgressEntry{}\n\n\tseenPIndexes := map[string]bool{}\n\tseenPIndexesSorted := []string(nil)\n\n\tupdateProgressEntry := func(pindex, sourcePartition, node string,\n\t\tcb func(*ProgressEntry)) {\n\t\tif !seenNodes[node] {\n\t\t\tseenNodes[node] = true\n\t\t\tseenNodesSorted = append(seenNodesSorted, node)\n\t\t\tsort.Strings(seenNodesSorted)\n\n\t\t\tif maxNodeLen < len(node) {\n\t\t\t\tmaxNodeLen = len(node)\n\t\t\t}\n\t\t}\n\n\t\tif maxPIndexLen < len(pindex) {\n\t\t\tmaxPIndexLen = len(pindex)\n\t\t}\n\n\t\tsourcePartitions, exists := progressEntries[pindex]\n\t\tif !exists || sourcePartitions == nil {\n\t\t\tsourcePartitions = map[string]map[string]*ProgressEntry{}\n\t\t\tprogressEntries[pindex] = sourcePartitions\n\t\t}\n\n\t\tnodes, exists := sourcePartitions[sourcePartition]\n\t\tif !exists || nodes == nil {\n\t\t\tnodes = map[string]*ProgressEntry{}\n\t\t\tsourcePartitions[sourcePartition] = nodes\n\t\t}\n\n\t\tprogressEntry, exists := nodes[node]\n\t\tif !exists || progressEntry == nil {\n\t\t\tprogressEntry = &ProgressEntry{\n\t\t\t\tpindex:          pindex,\n\t\t\t\tsourcePartition: sourcePartition,\n\t\t\t\tnode:            node,\n\t\t\t}\n\t\t\tnodes[node] = progressEntry\n\t\t}\n\n\t\tcb(progressEntry)\n\n\t\t\/\/ TODO: Check UUID matches, too.\n\n\t\tif !seenPIndexes[pindex] {\n\t\t\tseenPIndexes[pindex] = true\n\t\t\tseenPIndexesSorted =\n\t\t\t\tappend(seenPIndexesSorted, pindex)\n\n\t\t\tsort.Strings(seenPIndexesSorted)\n\t\t}\n\t}\n\n\tfor progress := range r.ProgressCh() {\n\t\tif progress.Index == \"\" {\n\t\t\tr.Log(\"main: progress: %+v\", progress)\n\t\t\tcontinue\n\t\t}\n\n\t\tif progress.Error != nil {\n\t\t\tr.Log(\"main: error, progress: %+v\", progress)\n\t\t\tcontinue\n\t\t}\n\n\t\tr.Visit(func(\n\t\t\tcurrStates rebalance.CurrStates,\n\t\t\tcurrSeqs rebalance.CurrSeqs,\n\t\t\twantSeqs rebalance.WantSeqs) {\n\t\t\tfor _, pindexes := range currStates {\n\t\t\t\tfor pindex, nodes := range pindexes {\n\t\t\t\t\tfor node, stateOp := range nodes {\n\t\t\t\t\t\tupdateProgressEntry(pindex, \"\", node,\n\t\t\t\t\t\t\tfunc(pe *ProgressEntry) {\n\t\t\t\t\t\t\t\tpe.stateOp = stateOp\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor pindex, sourcePartitions := range currSeqs {\n\t\t\t\tfor sourcePartition, nodes := range sourcePartitions {\n\t\t\t\t\tfor node, currUUIDSeq := range nodes {\n\t\t\t\t\t\tupdateProgressEntry(pindex,\n\t\t\t\t\t\t\tsourcePartition, node,\n\t\t\t\t\t\t\tfunc(pe *ProgressEntry) {\n\t\t\t\t\t\t\t\tpe.currUUIDSeq = currUUIDSeq\n\n\t\t\t\t\t\t\t\tif pe.initUUIDSeq.UUID == \"\" {\n\t\t\t\t\t\t\t\t\tpe.initUUIDSeq = currUUIDSeq\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor pindex, sourcePartitions := range wantSeqs {\n\t\t\t\tfor sourcePartition, nodes := range sourcePartitions {\n\t\t\t\t\tfor node, wantUUIDSeq := range nodes {\n\t\t\t\t\t\tupdateProgressEntry(pindex,\n\t\t\t\t\t\t\tsourcePartition, node,\n\t\t\t\t\t\t\tfunc(pe *ProgressEntry) {\n\t\t\t\t\t\t\t\tpe.wantUUIDSeq = wantUUIDSeq\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ ----------------------------------------\n\n\t\t\tvar b bytes.Buffer\n\n\t\t\twritten, _ := b.Write([]byte(\"%%%\"))\n\t\t\tfor i := written; i < maxPIndexLen; i++ {\n\t\t\t\tb.WriteByte(' ')\n\t\t\t}\n\t\t\tb.WriteByte(' ')\n\n\t\t\tfor i, seenNode := range seenNodesSorted {\n\t\t\t\tif i > 0 {\n\t\t\t\t\tb.WriteByte(' ')\n\t\t\t\t}\n\t\t\t\tb.Write([]byte(seenNode))\n\t\t\t}\n\t\t\tb.WriteByte('\\n')\n\n\t\t\tfor _, seenPIndex := range seenPIndexesSorted {\n\t\t\t\tb.Write([]byte(\" %                  \"))\n\t\t\t\tb.Write([]byte(seenPIndex))\n\n\t\t\t\tfor _, seenNode := range seenNodesSorted {\n\t\t\t\t\tb.WriteByte(' ')\n\n\t\t\t\t\tsourcePartitions, exists :=\n\t\t\t\t\t\tprogressEntries[seenPIndex]\n\t\t\t\t\tif !exists || sourcePartitions == nil {\n\t\t\t\t\t\temitNodeEntry(&b, nil, nil, maxNodeLen)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tnodes, exists := sourcePartitions[\"\"]\n\t\t\t\t\tif !exists || nodes == nil {\n\t\t\t\t\t\temitNodeEntry(&b, nil, nil, maxNodeLen)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tpe, exists := nodes[seenNode]\n\t\t\t\t\tif !exists || pe == nil {\n\t\t\t\t\t\temitNodeEntry(&b, nil, nil, maxNodeLen)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\temitNodeEntry(&b, pe, sourcePartitions, maxNodeLen)\n\t\t\t\t}\n\n\t\t\t\tb.WriteByte('\\n')\n\t\t\t}\n\n\t\t\tcurrEmit := b.String()\n\t\t\tif currEmit != lastEmit {\n\t\t\t\tr.Log(\"%s\", currEmit)\n\t\t\t}\n\n\t\t\tlastEmit = currEmit\n\t\t})\n\t}\n}\n\nvar opMap = map[string]string{\n\t\"\":        \".\",\n\t\"add\":     \"+\",\n\t\"del\":     \"-\",\n\t\"promote\": \"P\",\n\t\"demote\":  \"D\",\n}\n\nfunc emitNodeEntry(b *bytes.Buffer,\n\tpe *ProgressEntry,\n\tsourcePartitions map[string]map[string]*ProgressEntry,\n\tmaxNodeLen int) {\n\twritten := 0\n\n\ttotPct := 0.0 \/\/ To compute average pct.\n\tnumPct := 0\n\n\tif pe != nil &&\n\t\tsourcePartitions != nil {\n\t\twritten, _ = b.Write([]byte(opMap[pe.stateOp.Op]))\n\n\t\tfor sourcePartition, nodes := range sourcePartitions {\n\t\t\tif sourcePartition == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpex := nodes[pe.node]\n\t\t\tif pex == nil || pex.wantUUIDSeq.UUID == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif pex.wantUUIDSeq.Seq <= pex.currUUIDSeq.Seq {\n\t\t\t\ttotPct = totPct + 1.0\n\t\t\t\tnumPct = numPct + 1\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tn := pex.currUUIDSeq.Seq - pex.initUUIDSeq.Seq\n\t\t\td := pex.wantUUIDSeq.Seq - pex.initUUIDSeq.Seq\n\t\t\tif d > 0 {\n\t\t\t\tpct := float64(n) \/ float64(d)\n\t\t\t\ttotPct = totPct + pct\n\t\t\t\tnumPct = numPct + 1\n\t\t\t}\n\t\t}\n\t} else {\n\t\tb.WriteByte('.')\n\t\twritten = 1\n\t}\n\n\tif numPct > 0 {\n\t\tavgPct := totPct \/ float64(numPct)\n\n\t\tn, _ := fmt.Fprintf(b, \" %.1f%%\", avgPct*100.0)\n\t\twritten = written + n\n\t}\n\n\tfor i := written; i < maxNodeLen; i++ {\n\t\tb.WriteByte(' ')\n\t}\n}\n\n\/\/ ------------------------------------------------------------\n\nfunc MainWelcome(flagAliases map[string][]string) {\n\tflag.VisitAll(func(f *flag.Flag) {\n\t\tif flagAliases[f.Name] != nil {\n\t\t\tlog.Printf(\"  -%s=%q\\n\", f.Name, f.Value)\n\t\t}\n\t})\n\tlog.Printf(\"  GOMAXPROCS=%d\", runtime.GOMAXPROCS(-1))\n}\n\nfunc dumpOnSignal(signals ...os.Signal) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, signals...)\n\tfor _ = range c {\n\t\tlog.Printf(\"dump: goroutine...\")\n\t\tpprof.Lookup(\"goroutine\").WriteTo(os.Stderr, 1)\n\t\tlog.Printf(\"dump: heap...\")\n\t\tpprof.Lookup(\"heap\").WriteTo(os.Stderr, 1)\n\t}\n}\n<commit_msg>progressTable helper func in mcp<commit_after>\/\/  Copyright (c) 2015 Couchbase, Inc.\n\/\/  Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/  you may not use this file except in compliance with the\n\/\/  License. You may obtain a copy of the License at\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/  Unless required by applicable law or agreed to in writing,\n\/\/  software distributed under the License is distributed on an \"AS\n\/\/  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n\/\/  express or implied. See the License for the specific language\n\/\/  governing permissions and limitations under the License.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"expvar\"\n\t\"flag\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\"\n\t\"runtime\"\n\t\"runtime\/pprof\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/couchbase\/clog\"\n\n\t\"github.com\/couchbaselabs\/cbgt\"\n\t\"github.com\/couchbaselabs\/cbgt\/cmd\"\n\t\"github.com\/couchbaselabs\/cbgt\/rebalance\"\n)\n\nvar VERSION = \"v0.0.0\"\n\nvar expvars = expvar.NewMap(\"stats\")\n\nfunc main() {\n\tflag.Parse()\n\n\tif flags.Help {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tif flags.Version {\n\t\tfmt.Printf(\"%s main: %s, data: %s\\n\",\n\t\t\tpath.Base(os.Args[0]), VERSION, cbgt.VERSION)\n\t\tos.Exit(0)\n\t}\n\n\tif os.Getenv(\"GOMAXPROCS\") == \"\" {\n\t\truntime.GOMAXPROCS(runtime.NumCPU())\n\t}\n\n\tlog.Printf(\"main: %s started (%s\/%s)\",\n\t\tos.Args[0], VERSION, cbgt.VERSION)\n\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tgo dumpOnSignalForPlatform()\n\n\tMainWelcome(flagAliases)\n\n\tnodesToRemove := []string(nil)\n\tif len(flags.RemoveNodes) > 0 {\n\t\tnodesToRemove = strings.Split(flags.RemoveNodes, \",\")\n\t}\n\n\tbindHttp := \"NO-BIND-HTTP\"\n\tregister := \"unchanged\"\n\tdataDir := \"NO-DATA-DIR\"\n\n\t\/\/ If cfg is down, we error, leaving it to some user-supplied\n\t\/\/ outside watchdog to backoff and restart\/retry.\n\tcfg, err := cmd.MainCfg(\"mcp\", flags.CfgConnect,\n\t\tbindHttp, register, dataDir)\n\tif err != nil {\n\t\tif err == cmd.ErrorBindHttp {\n\t\t\tlog.Fatalf(\"%v\", err)\n\t\t\treturn\n\t\t}\n\t\tlog.Fatalf(\"main: could not start cfg, cfgConnect: %s, err: %v\\n\"+\n\t\t\t\"  Please check that your -cfg\/-cfgConnect parameter (%q)\\n\"+\n\t\t\t\"  is correct and\/or that your configuration provider\\n\"+\n\t\t\t\"  is available.\",\n\t\t\tflags.CfgConnect, err, flags.CfgConnect)\n\t\treturn\n\t}\n\n\tr, err := rebalance.StartRebalance(cbgt.VERSION, cfg, flags.Server,\n\t\tnodesToRemove,\n\t\trebalance.RebalanceOptions{\n\t\t\tDryRun:  flags.DryRun,\n\t\t\tVerbose: flags.Verbose,\n\t\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"main: StartRebalance, err: %v\", err)\n\t\treturn\n\t}\n\n\treportProgress(r)\n\n\tr.Stop()\n\n\tlog.Printf(\"main: done\")\n}\n\n\/\/ ------------------------------------------------------------\n\ntype ProgressEntry struct {\n\tpindex, sourcePartition, node string \/\/ Immutable.\n\n\tstateOp     rebalance.StateOp\n\tinitUUIDSeq cbgt.UUIDSeq\n\tcurrUUIDSeq cbgt.UUIDSeq\n\twantUUIDSeq cbgt.UUIDSeq\n}\n\nfunc reportProgress(r *rebalance.Rebalancer) {\n\tvar lastEmit string\n\n\tmaxNodeLen := 0\n\tmaxPIndexLen := 0\n\n\tseenNodes := map[string]bool{}\n\tseenNodesSorted := []string(nil)\n\n\t\/\/ Map of pindex -> (source) partition -> node -> *ProgressEntry\n\tprogressEntries := map[string]map[string]map[string]*ProgressEntry{}\n\n\tseenPIndexes := map[string]bool{}\n\tseenPIndexesSorted := []string(nil)\n\n\tupdateProgressEntry := func(pindex, sourcePartition, node string,\n\t\tcb func(*ProgressEntry)) {\n\t\tif !seenNodes[node] {\n\t\t\tseenNodes[node] = true\n\t\t\tseenNodesSorted = append(seenNodesSorted, node)\n\t\t\tsort.Strings(seenNodesSorted)\n\n\t\t\tif maxNodeLen < len(node) {\n\t\t\t\tmaxNodeLen = len(node)\n\t\t\t}\n\t\t}\n\n\t\tif maxPIndexLen < len(pindex) {\n\t\t\tmaxPIndexLen = len(pindex)\n\t\t}\n\n\t\tsourcePartitions, exists := progressEntries[pindex]\n\t\tif !exists || sourcePartitions == nil {\n\t\t\tsourcePartitions = map[string]map[string]*ProgressEntry{}\n\t\t\tprogressEntries[pindex] = sourcePartitions\n\t\t}\n\n\t\tnodes, exists := sourcePartitions[sourcePartition]\n\t\tif !exists || nodes == nil {\n\t\t\tnodes = map[string]*ProgressEntry{}\n\t\t\tsourcePartitions[sourcePartition] = nodes\n\t\t}\n\n\t\tprogressEntry, exists := nodes[node]\n\t\tif !exists || progressEntry == nil {\n\t\t\tprogressEntry = &ProgressEntry{\n\t\t\t\tpindex:          pindex,\n\t\t\t\tsourcePartition: sourcePartition,\n\t\t\t\tnode:            node,\n\t\t\t}\n\t\t\tnodes[node] = progressEntry\n\t\t}\n\n\t\tcb(progressEntry)\n\n\t\t\/\/ TODO: Check UUID matches, too.\n\n\t\tif !seenPIndexes[pindex] {\n\t\t\tseenPIndexes[pindex] = true\n\t\t\tseenPIndexesSorted =\n\t\t\t\tappend(seenPIndexesSorted, pindex)\n\n\t\t\tsort.Strings(seenPIndexesSorted)\n\t\t}\n\t}\n\n\tfor progress := range r.ProgressCh() {\n\t\tif progress.Index == \"\" {\n\t\t\tr.Log(\"main: progress: %+v\", progress)\n\t\t\tcontinue\n\t\t}\n\n\t\tif progress.Error != nil {\n\t\t\tr.Log(\"main: error, progress: %+v\", progress)\n\t\t\tcontinue\n\t\t}\n\n\t\tr.Visit(func(\n\t\t\tcurrStates rebalance.CurrStates,\n\t\t\tcurrSeqs rebalance.CurrSeqs,\n\t\t\twantSeqs rebalance.WantSeqs) {\n\t\t\tfor _, pindexes := range currStates {\n\t\t\t\tfor pindex, nodes := range pindexes {\n\t\t\t\t\tfor node, stateOp := range nodes {\n\t\t\t\t\t\tupdateProgressEntry(pindex, \"\", node,\n\t\t\t\t\t\t\tfunc(pe *ProgressEntry) {\n\t\t\t\t\t\t\t\tpe.stateOp = stateOp\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor pindex, sourcePartitions := range currSeqs {\n\t\t\t\tfor sourcePartition, nodes := range sourcePartitions {\n\t\t\t\t\tfor node, currUUIDSeq := range nodes {\n\t\t\t\t\t\tupdateProgressEntry(pindex,\n\t\t\t\t\t\t\tsourcePartition, node,\n\t\t\t\t\t\t\tfunc(pe *ProgressEntry) {\n\t\t\t\t\t\t\t\tpe.currUUIDSeq = currUUIDSeq\n\n\t\t\t\t\t\t\t\tif pe.initUUIDSeq.UUID == \"\" {\n\t\t\t\t\t\t\t\t\tpe.initUUIDSeq = currUUIDSeq\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor pindex, sourcePartitions := range wantSeqs {\n\t\t\t\tfor sourcePartition, nodes := range sourcePartitions {\n\t\t\t\t\tfor node, wantUUIDSeq := range nodes {\n\t\t\t\t\t\tupdateProgressEntry(pindex,\n\t\t\t\t\t\t\tsourcePartition, node,\n\t\t\t\t\t\t\tfunc(pe *ProgressEntry) {\n\t\t\t\t\t\t\t\tpe.wantUUIDSeq = wantUUIDSeq\n\t\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcurrEmit := progressTable(maxNodeLen, maxPIndexLen,\n\t\t\t\tseenNodes,\n\t\t\t\tseenNodesSorted,\n\t\t\t\tseenPIndexes,\n\t\t\t\tseenPIndexesSorted,\n\t\t\t\tprogressEntries)\n\t\t\tif currEmit != lastEmit {\n\t\t\t\tr.Log(\"%s\", currEmit)\n\t\t\t}\n\n\t\t\tlastEmit = currEmit\n\t\t})\n\t}\n}\n\nfunc progressTable(maxNodeLen, maxPIndexLen int,\n\tseenNodes map[string]bool,\n\tseenNodesSorted []string,\n\tseenPIndexes map[string]bool,\n\tseenPIndexesSorted []string,\n\tprogressEntries map[string]map[string]map[string]*ProgressEntry,\n) string {\n\tvar b bytes.Buffer\n\n\twritten, _ := b.Write([]byte(\"%%%\"))\n\tfor i := written; i < maxPIndexLen; i++ {\n\t\tb.WriteByte(' ')\n\t}\n\tb.WriteByte(' ')\n\n\tfor i, seenNode := range seenNodesSorted {\n\t\tif i > 0 {\n\t\t\tb.WriteByte(' ')\n\t\t}\n\t\tb.Write([]byte(seenNode))\n\t}\n\tb.WriteByte('\\n')\n\n\tfor _, seenPIndex := range seenPIndexesSorted {\n\t\tb.Write([]byte(\" %                  \"))\n\t\tb.Write([]byte(seenPIndex))\n\n\t\tfor _, seenNode := range seenNodesSorted {\n\t\t\tb.WriteByte(' ')\n\n\t\t\tsourcePartitions, exists :=\n\t\t\t\tprogressEntries[seenPIndex]\n\t\t\tif !exists || sourcePartitions == nil {\n\t\t\t\tprogressCell(&b, nil, nil, maxNodeLen)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tnodes, exists := sourcePartitions[\"\"]\n\t\t\tif !exists || nodes == nil {\n\t\t\t\tprogressCell(&b, nil, nil, maxNodeLen)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpe, exists := nodes[seenNode]\n\t\t\tif !exists || pe == nil {\n\t\t\t\tprogressCell(&b, nil, nil, maxNodeLen)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tprogressCell(&b, pe, sourcePartitions, maxNodeLen)\n\t\t}\n\n\t\tb.WriteByte('\\n')\n\t}\n\n\treturn b.String()\n}\n\nvar opMap = map[string]string{\n\t\"\":        \".\",\n\t\"add\":     \"+\",\n\t\"del\":     \"-\",\n\t\"promote\": \"P\",\n\t\"demote\":  \"D\",\n}\n\nfunc progressCell(b *bytes.Buffer,\n\tpe *ProgressEntry,\n\tsourcePartitions map[string]map[string]*ProgressEntry,\n\tmaxNodeLen int) {\n\twritten := 0\n\n\ttotPct := 0.0 \/\/ To compute average pct.\n\tnumPct := 0\n\n\tif pe != nil &&\n\t\tsourcePartitions != nil {\n\t\twritten, _ = b.Write([]byte(opMap[pe.stateOp.Op]))\n\n\t\tfor sourcePartition, nodes := range sourcePartitions {\n\t\t\tif sourcePartition == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpex := nodes[pe.node]\n\t\t\tif pex == nil || pex.wantUUIDSeq.UUID == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif pex.wantUUIDSeq.Seq <= pex.currUUIDSeq.Seq {\n\t\t\t\ttotPct = totPct + 1.0\n\t\t\t\tnumPct = numPct + 1\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tn := pex.currUUIDSeq.Seq - pex.initUUIDSeq.Seq\n\t\t\td := pex.wantUUIDSeq.Seq - pex.initUUIDSeq.Seq\n\t\t\tif d > 0 {\n\t\t\t\tpct := float64(n) \/ float64(d)\n\t\t\t\ttotPct = totPct + pct\n\t\t\t\tnumPct = numPct + 1\n\t\t\t}\n\t\t}\n\t} else {\n\t\tb.WriteByte('.')\n\t\twritten = 1\n\t}\n\n\tif numPct > 0 {\n\t\tavgPct := totPct \/ float64(numPct)\n\n\t\tn, _ := fmt.Fprintf(b, \" %.1f%%\", avgPct*100.0)\n\t\twritten = written + n\n\t}\n\n\tfor i := written; i < maxNodeLen; i++ {\n\t\tb.WriteByte(' ')\n\t}\n}\n\n\/\/ ------------------------------------------------------------\n\nfunc MainWelcome(flagAliases map[string][]string) {\n\tflag.VisitAll(func(f *flag.Flag) {\n\t\tif flagAliases[f.Name] != nil {\n\t\t\tlog.Printf(\"  -%s=%q\\n\", f.Name, f.Value)\n\t\t}\n\t})\n\tlog.Printf(\"  GOMAXPROCS=%d\", runtime.GOMAXPROCS(-1))\n}\n\nfunc dumpOnSignal(signals ...os.Signal) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, signals...)\n\tfor _ = range c {\n\t\tlog.Printf(\"dump: goroutine...\")\n\t\tpprof.Lookup(\"goroutine\").WriteTo(os.Stderr, 1)\n\t\tlog.Printf(\"dump: heap...\")\n\t\tpprof.Lookup(\"heap\").WriteTo(os.Stderr, 1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n\n\t\"github.com\/spf13\/afero\"\n)\n\nfunc init() {\n\tappFS = afero.NewMemMapFs()\n}\n\nfunc TestGetAppPath(t *testing.T) {\n\tt.Parallel()\n\n\tgopath := os.Getenv(\"GOPATH\")\n\tos.Setenv(\"GOPATH\", \"testpath\/test\")\n\n\tappPath, _, importPath, appName, appEnvName, err := getAppPath([]string{\".\", \"\/templatepath\"})\n\tif err == nil {\n\t\tt.Errorf(\"expected error, but got none: %s - %s\", appPath, appName)\n\t}\n\n\tappPath, _, importPath, appName, appEnvName, err = getAppPath([]string{\"\/\", \"\/templatepath\"})\n\tif err == nil {\n\t\tt.Errorf(\"expected error, but got none: %s - %s\", appPath, appName)\n\t}\n\n\tappPath, _, importPath, appName, appEnvName, err = getAppPath([]string{\"\/test\", \"\/templatepath\"})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif appPath != \"testpath\/test\/src\/test\" {\n\t\tt.Errorf(\"mismatch, got %s\", appPath)\n\t}\n\tif appName != \"test\" {\n\t\tt.Errorf(\"mismatch, got %s\", appName)\n\t}\n\tif appEnvName != \"TEST\" {\n\t\tt.Errorf(\"mismatch, got %s\", appEnvName)\n\t}\n\tif importPath != \"\/test\" {\n\t\tt.Errorf(\"mismatch, got %s\", importPath)\n\t}\n\n\tappPath, _, importPath, appName, appEnvName, err = getAppPath([]string{\".\/stuff\/test\"}, \"\/templatepath\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif appPath != \"testpath\/test\/src\/stuff\/test\" {\n\t\tt.Errorf(\"mismatch, got %s\", appPath)\n\t}\n\tif appName != \"test\" {\n\t\tt.Errorf(\"mismatch, got %s\", appName)\n\t}\n\tif appEnvName != \"TEST\" {\n\t\tt.Errorf(\"mismatch, got %s\", appEnvName)\n\t}\n\tif importPath != \"stuff\/test\" {\n\t\tt.Errorf(\"mismatch, got %s\", importPath)\n\t}\n\n\tos.Setenv(\"GOPATH\", gopath)\n}\n\nfunc TestGetProcessedPaths(t *testing.T) {\n\tt.Parallel()\n\n\tcfg := newConfig{\n\t\tAppPath: \"\/test\/myapp\",\n\t\tAppName: \"myapp\",\n\t}\n\n\tinPath := \"\/lol\/\" + templatesDirectory + \"\/file.tmpl\"\n\tcleanPath, fullPath := getProcessedPaths(inPath, \"\/\", cfg)\n\tif cleanPath != \"myapp\/file\" {\n\t\tt.Error(\"mismatch:\", cleanPath)\n\t}\n\tif fullPath != \"\/test\/myapp\/file\" {\n\t\tt.Error(\"mismatch:\", fullPath)\n\t}\n\n\tcfg.AppPath = \"myapp\"\n\tcfg.AppName = \"myapp\"\n\n\tcleanPath, fullPath = getProcessedPaths(inPath, \"\/\", cfg)\n\tif cleanPath != \"myapp\/file\" {\n\t\tt.Error(\"mismatch:\", cleanPath)\n\t}\n\tif fullPath != \"myapp\/file\" {\n\t\tt.Error(\"mismatch:\", fullPath)\n\t}\n}\n\nfunc TestProcessSkips(t *testing.T) {\n\tcfg := newConfig{\n\t\tNoReadme:      true,\n\t\tNoConfig:      true,\n\t\tNoFontAwesome: true,\n\t\tBootstrap:     \"none\",\n\t\tNoBootstrapJS: true,\n\t\tNoSessions:    true,\n\t\tNoGulp:        true,\n\t\tNoLiveReload:  true,\n\t}\n\n\t\/\/ check skip basedir\n\terr := appFS.MkdirAll(\"\/templates\", 0755)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err := appFS.Stat(\"\/templates\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ := processSkips(cfg, \"\/templates\", \"\/templates\", info)\n\tif skip == false {\n\t\tt.Error(\"expected to skip base path\")\n\t}\n\n\t\/\/ check skip skipDirs slice\n\terr = appFS.MkdirAll(\"\/templates\/i18n\", 0755)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/templates\/i18n\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, err = processSkips(cfg, \"\/templates\", \"\/templates\/i18n\", info)\n\tif skip != true || err == nil {\n\t\tt.Error(\"expected to skip skipDir and receive skipdir err\")\n\t}\n\n\t\/\/ check skip readme\n\tf, err := appFS.Create(\"\/templates\/README.md\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/README.md\", info)\n\tif skip != true {\n\t\tt.Error(\"expected to skip skip readme\")\n\t}\n\n\t\/\/ check skip livereload.js\n\tf, err = appFS.Create(\"\/templates\/assets\/vendor\/js\/livereload.js\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/assets\/vendor\/js\/livereload.js\", info)\n\tif skip != true {\n\t\tt.Error(\"expected to skip livereload.js\")\n\t}\n\n\t\/\/ check skip gulp\n\tf, err = appFS.Create(\"\/templates\/gulpfile.js\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/gulpfile.js\", info)\n\tif skip != true {\n\t\tt.Error(\"expected to skip gulpfile.js\")\n\t}\n\tf, err = appFS.Create(\"\/templates\/package.json.tmpl\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/pacakage.json.tmpl\", info)\n\tif skip != true {\n\t\tt.Error(\"expected to skip package.json.tmpl\")\n\t}\n\n\t\/\/ check skip app\/sessions.go.tmpl\n\tf, err = appFS.Create(\"\/templates\/app\/sessions.go.tmpl\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/app\/sessions.go.tmpl\", info)\n\tif skip != true {\n\t\tt.Error(\"expected to skip skip sessions.go.tmpl\")\n\t}\n\n\t\/\/ check skip config.toml\n\tf, err = appFS.Create(\"\/templates\/config.toml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/config.toml\", info)\n\tif skip != true {\n\t\tt.Error(\"expected to skip skip config.toml\")\n\t}\n\n\t\/\/ check no-skip regular go file\n\tf, err = appFS.Create(\"\/templates\/file.go\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/file.go\", info)\n\tif skip == true {\n\t\tt.Error(\"did not expect skip\")\n\t}\n\n\tappFS = afero.NewMemMapFs()\n}\n\nfunc TestNewCmdWalk(t *testing.T) {\n\tcfg := newConfig{\n\t\tAppPath: \"\/my\/app\",\n\t\tAppName: \"app\",\n\t\tSilent:  true,\n\t}\n\n\t\/\/ test skip\n\terr := appFS.MkdirAll(\"\/templates\/i18n\", 0755)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err := appFS.Stat(\"\/templates\/i18n\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = newCmdWalk(cfg, \"\/templates\", \"\/templates\/i18n\", info, nil)\n\tif err == nil {\n\t\tt.Fatal(\"expected error but got nil\")\n\t}\n\tif err != filepath.SkipDir {\n\t\tt.Fatalf(\"expected error type filepath.SkipDir, but got %#v\", err)\n\t}\n\n\t\/\/ check go file write\n\terr = afero.WriteFile(appFS, \"\/templates\/file.go\", []byte(\"hello\"), 0644)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/templates\/file.go\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = newCmdWalk(cfg, \"\/templates\", \"\/templates\/file.go\", info, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/my\/app\/file.go\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif info.IsDir() || info.Size() != 5 {\n\t\tt.Fatalf(\"Expected isdir false and size to be 5, got %t and %d\", info.IsDir(), info.Size())\n\t}\n\n\t\/\/ check template file write\n\terr = afero.WriteFile(appFS, \"\/templates\/template.go.tmpl\", []byte(`package  {{.AppName}}`), 0644)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/templates\/template.go.tmpl\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = newCmdWalk(cfg, \"\/templates\", \"\/templates\/template.go.tmpl\", info, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/my\/app\/template.go\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif info.IsDir() || info.Size() != int64(len(\"package app\\n\")) {\n\t\tb, err := afero.ReadFile(appFS, \"\/my\/app\/template.go\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tt.Fatalf(\"Expected isdir false and size to be %d, got %t and %d, value: %q\", len(\"package app\\n\"), info.IsDir(), info.Size(), string(b))\n\t}\n\n\t\/\/ check dir write\n\terr = appFS.MkdirAll(\"\/templates\/stuff\", 0755)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/templates\/stuff\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = newCmdWalk(cfg, \"\/templates\", \"\/templates\/stuff\", info, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/my\/app\/stuff\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !info.IsDir() {\n\t\tt.Fatalf(\"Expected isdir true, got %t\", info.IsDir())\n\t}\n\n\tappFS = afero.NewMemMapFs()\n}\n\nfunc TestGenerateTLSCerts(t *testing.T) {\n\tcfg := newConfig{\n\t\tAppPath:       \"\/out\/spiders\",\n\t\tAppName:       \"spiders\",\n\t\tTLSCommonName: \"dragons\",\n\t\tSilent:        true,\n\t}\n\n\terr := generateTLSCerts(cfg)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tinfo, err := appFS.Stat(\"\/out\/spiders\/cert.pem\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif info.Size() == 0 {\n\t\tt.Error(\"expected non-0 size for cert file\")\n\t}\n\n\tinfo, err = appFS.Stat(\"\/out\/spiders\/private.key\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif info.Size() == 0 {\n\t\tt.Error(\"expected non-0 size for private key file\")\n\t}\n\n\tappFS = afero.NewMemMapFs()\n}\n<commit_msg>fix broken test<commit_after>package cmd\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n\n\t\"github.com\/spf13\/afero\"\n)\n\nfunc init() {\n\tappFS = afero.NewMemMapFs()\n}\n\nfunc TestGetAppPath(t *testing.T) {\n\tt.Parallel()\n\n\tgopath := os.Getenv(\"GOPATH\")\n\tos.Setenv(\"GOPATH\", \"testpath\/test\")\n\n\tappPath, _, importPath, appName, appEnvName, err := getAppPath([]string{\".\", \"\/templatepath\"})\n\tif err == nil {\n\t\tt.Errorf(\"expected error, but got none: %s - %s\", appPath, appName)\n\t}\n\n\tappPath, _, importPath, appName, appEnvName, err = getAppPath([]string{\"\/\", \"\/templatepath\"})\n\tif err == nil {\n\t\tt.Errorf(\"expected error, but got none: %s - %s\", appPath, appName)\n\t}\n\n\tappPath, _, importPath, appName, appEnvName, err = getAppPath([]string{\"\/test\", \"\/templatepath\"})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif appPath != \"testpath\/test\/src\/test\" {\n\t\tt.Errorf(\"mismatch, got %s\", appPath)\n\t}\n\tif appName != \"test\" {\n\t\tt.Errorf(\"mismatch, got %s\", appName)\n\t}\n\tif appEnvName != \"TEST\" {\n\t\tt.Errorf(\"mismatch, got %s\", appEnvName)\n\t}\n\tif importPath != \"\/test\" {\n\t\tt.Errorf(\"mismatch, got %s\", importPath)\n\t}\n\n\tappPath, _, importPath, appName, appEnvName, err = getAppPath([]string{\".\/stuff\/test\", \"\/templatepath\"})\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif appPath != \"testpath\/test\/src\/stuff\/test\" {\n\t\tt.Errorf(\"mismatch, got %s\", appPath)\n\t}\n\tif appName != \"test\" {\n\t\tt.Errorf(\"mismatch, got %s\", appName)\n\t}\n\tif appEnvName != \"TEST\" {\n\t\tt.Errorf(\"mismatch, got %s\", appEnvName)\n\t}\n\tif importPath != \"stuff\/test\" {\n\t\tt.Errorf(\"mismatch, got %s\", importPath)\n\t}\n\n\tos.Setenv(\"GOPATH\", gopath)\n}\n\nfunc TestGetProcessedPaths(t *testing.T) {\n\tt.Parallel()\n\n\tcfg := newConfig{\n\t\tAppPath: \"\/test\/myapp\",\n\t\tAppName: \"myapp\",\n\t}\n\n\tinPath := \"\/lol\/\" + templatesDirectory + \"\/file.tmpl\"\n\tcleanPath, fullPath := getProcessedPaths(inPath, \"\/\", cfg)\n\tif cleanPath != \"myapp\/file\" {\n\t\tt.Error(\"mismatch:\", cleanPath)\n\t}\n\tif fullPath != \"\/test\/myapp\/file\" {\n\t\tt.Error(\"mismatch:\", fullPath)\n\t}\n\n\tcfg.AppPath = \"myapp\"\n\tcfg.AppName = \"myapp\"\n\n\tcleanPath, fullPath = getProcessedPaths(inPath, \"\/\", cfg)\n\tif cleanPath != \"myapp\/file\" {\n\t\tt.Error(\"mismatch:\", cleanPath)\n\t}\n\tif fullPath != \"myapp\/file\" {\n\t\tt.Error(\"mismatch:\", fullPath)\n\t}\n}\n\nfunc TestProcessSkips(t *testing.T) {\n\tcfg := newConfig{\n\t\tNoReadme:      true,\n\t\tNoConfig:      true,\n\t\tNoFontAwesome: true,\n\t\tBootstrap:     \"none\",\n\t\tNoBootstrapJS: true,\n\t\tNoSessions:    true,\n\t\tNoGulp:        true,\n\t\tNoLiveReload:  true,\n\t}\n\n\t\/\/ check skip basedir\n\terr := appFS.MkdirAll(\"\/templates\", 0755)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err := appFS.Stat(\"\/templates\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ := processSkips(cfg, \"\/templates\", \"\/templates\", info)\n\tif skip == false {\n\t\tt.Error(\"expected to skip base path\")\n\t}\n\n\t\/\/ check skip skipDirs slice\n\terr = appFS.MkdirAll(\"\/templates\/i18n\", 0755)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/templates\/i18n\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, err = processSkips(cfg, \"\/templates\", \"\/templates\/i18n\", info)\n\tif skip != true || err == nil {\n\t\tt.Error(\"expected to skip skipDir and receive skipdir err\")\n\t}\n\n\t\/\/ check skip readme\n\tf, err := appFS.Create(\"\/templates\/README.md\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/README.md\", info)\n\tif skip != true {\n\t\tt.Error(\"expected to skip skip readme\")\n\t}\n\n\t\/\/ check skip livereload.js\n\tf, err = appFS.Create(\"\/templates\/assets\/vendor\/js\/livereload.js\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/assets\/vendor\/js\/livereload.js\", info)\n\tif skip != true {\n\t\tt.Error(\"expected to skip livereload.js\")\n\t}\n\n\t\/\/ check skip gulp\n\tf, err = appFS.Create(\"\/templates\/gulpfile.js\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/gulpfile.js\", info)\n\tif skip != true {\n\t\tt.Error(\"expected to skip gulpfile.js\")\n\t}\n\tf, err = appFS.Create(\"\/templates\/package.json.tmpl\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/pacakage.json.tmpl\", info)\n\tif skip != true {\n\t\tt.Error(\"expected to skip package.json.tmpl\")\n\t}\n\n\t\/\/ check skip app\/sessions.go.tmpl\n\tf, err = appFS.Create(\"\/templates\/app\/sessions.go.tmpl\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/app\/sessions.go.tmpl\", info)\n\tif skip != true {\n\t\tt.Error(\"expected to skip skip sessions.go.tmpl\")\n\t}\n\n\t\/\/ check skip config.toml\n\tf, err = appFS.Create(\"\/templates\/config.toml\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/config.toml\", info)\n\tif skip != true {\n\t\tt.Error(\"expected to skip skip config.toml\")\n\t}\n\n\t\/\/ check no-skip regular go file\n\tf, err = appFS.Create(\"\/templates\/file.go\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = f.Stat()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tskip, _ = processSkips(cfg, \"\/templates\", \"\/templates\/file.go\", info)\n\tif skip == true {\n\t\tt.Error(\"did not expect skip\")\n\t}\n\n\tappFS = afero.NewMemMapFs()\n}\n\nfunc TestNewCmdWalk(t *testing.T) {\n\tcfg := newConfig{\n\t\tAppPath: \"\/my\/app\",\n\t\tAppName: \"app\",\n\t\tSilent:  true,\n\t}\n\n\t\/\/ test skip\n\terr := appFS.MkdirAll(\"\/templates\/i18n\", 0755)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err := appFS.Stat(\"\/templates\/i18n\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = newCmdWalk(cfg, \"\/templates\", \"\/templates\/i18n\", info, nil)\n\tif err == nil {\n\t\tt.Fatal(\"expected error but got nil\")\n\t}\n\tif err != filepath.SkipDir {\n\t\tt.Fatalf(\"expected error type filepath.SkipDir, but got %#v\", err)\n\t}\n\n\t\/\/ check go file write\n\terr = afero.WriteFile(appFS, \"\/templates\/file.go\", []byte(\"hello\"), 0644)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/templates\/file.go\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = newCmdWalk(cfg, \"\/templates\", \"\/templates\/file.go\", info, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/my\/app\/file.go\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif info.IsDir() || info.Size() != 5 {\n\t\tt.Fatalf(\"Expected isdir false and size to be 5, got %t and %d\", info.IsDir(), info.Size())\n\t}\n\n\t\/\/ check template file write\n\terr = afero.WriteFile(appFS, \"\/templates\/template.go.tmpl\", []byte(`package  {{.AppName}}`), 0644)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/templates\/template.go.tmpl\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = newCmdWalk(cfg, \"\/templates\", \"\/templates\/template.go.tmpl\", info, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/my\/app\/template.go\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif info.IsDir() || info.Size() != int64(len(\"package app\\n\")) {\n\t\tb, err := afero.ReadFile(appFS, \"\/my\/app\/template.go\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tt.Fatalf(\"Expected isdir false and size to be %d, got %t and %d, value: %q\", len(\"package app\\n\"), info.IsDir(), info.Size(), string(b))\n\t}\n\n\t\/\/ check dir write\n\terr = appFS.MkdirAll(\"\/templates\/stuff\", 0755)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/templates\/stuff\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = newCmdWalk(cfg, \"\/templates\", \"\/templates\/stuff\", info, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tinfo, err = appFS.Stat(\"\/my\/app\/stuff\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !info.IsDir() {\n\t\tt.Fatalf(\"Expected isdir true, got %t\", info.IsDir())\n\t}\n\n\tappFS = afero.NewMemMapFs()\n}\n\nfunc TestGenerateTLSCerts(t *testing.T) {\n\tcfg := newConfig{\n\t\tAppPath:       \"\/out\/spiders\",\n\t\tAppName:       \"spiders\",\n\t\tTLSCommonName: \"dragons\",\n\t\tSilent:        true,\n\t}\n\n\terr := generateTLSCerts(cfg)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tinfo, err := appFS.Stat(\"\/out\/spiders\/cert.pem\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif info.Size() == 0 {\n\t\tt.Error(\"expected non-0 size for cert file\")\n\t}\n\n\tinfo, err = appFS.Stat(\"\/out\/spiders\/private.key\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif info.Size() == 0 {\n\t\tt.Error(\"expected non-0 size for private key file\")\n\t}\n\n\tappFS = afero.NewMemMapFs()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/concourse\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/globs\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/logger\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/md5sum\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/metadata\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/out\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/out\/release\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/pivnet\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/s3\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/uploader\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/useragent\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/validator\"\n\t\"github.com\/robdimsdale\/sanitizer\"\n)\n\nconst (\n\ts3OutBinaryName = \"s3-out\"\n\tdefaultBucket   = \"pivotalnetwork\"\n\tdefaultRegion   = \"eu-west-1\"\n)\n\nvar (\n\t\/\/ version is deliberately left uninitialized so it can be set at compile-time\n\tversion string\n)\n\nfunc main() {\n\tif version == \"\" {\n\t\tversion = \"dev\"\n\t}\n\n\tif len(os.Args) < 2 {\n\t\tlog.Fatalln(fmt.Sprintf(\n\t\t\t\"not enough args - usage: %s <sources directory>\", os.Args[0]))\n\t}\n\n\tsourcesDir := os.Args[1]\n\n\toutDir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tvar input concourse.OutRequest\n\n\terr = json.NewDecoder(os.Stdin).Decode(&input)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tfmt.Fprintf(os.Stderr, \"PivNet Resource version: %s\\n\", version)\n\n\tsanitized := concourse.SanitizedSource(input.Source)\n\tsanitizer := sanitizer.NewSanitizer(sanitized, os.Stderr)\n\n\tl := logger.NewLogger(sanitizer)\n\n\tvar endpoint string\n\tif input.Source.Endpoint != \"\" {\n\t\tendpoint = input.Source.Endpoint\n\t} else {\n\t\tendpoint = pivnet.Endpoint\n\t}\n\n\tclientConfig := pivnet.NewClientConfig{\n\t\tEndpoint:  endpoint,\n\t\tToken:     input.Source.APIToken,\n\t\tUserAgent: useragent.UserAgent(version, \"put\", input.Source.ProductSlug),\n\t}\n\n\tspecialLogger := logger.NewLogger(ioutil.Discard)\n\n\tpivnetClient := pivnet.NewClient(\n\t\tclientConfig,\n\t\tspecialLogger,\n\t)\n\n\tbucket := input.Source.Bucket\n\tif bucket == \"\" {\n\t\tbucket = defaultBucket\n\t}\n\n\tregion := input.Source.Region\n\tif region == \"\" {\n\t\tregion = defaultRegion\n\t}\n\n\ts3Client := s3.NewClient(s3.NewClientConfig{\n\t\tAccessKeyID:     input.Source.AccessKeyID,\n\t\tSecretAccessKey: input.Source.SecretAccessKey,\n\t\tRegionName:      region,\n\t\tBucket:          bucket,\n\t\tLogger:          l,\n\t\tStdout:          os.Stdout,\n\t\tStderr:          os.Stderr,\n\t\tOutBinaryPath:   filepath.Join(outDir, s3OutBinaryName),\n\t})\n\n\tuploaderClient := uploader.NewClient(uploader.Config{\n\t\tFilepathPrefix: input.Params.FilepathPrefix,\n\t\tSourcesDir:     sourcesDir,\n\t\tLogger:         l,\n\t\tTransport:      s3Client,\n\t})\n\n\tglobber := globs.NewGlobber(globs.GlobberConfig{\n\t\tFileGlob:   input.Params.FileGlob,\n\t\tSourcesDir: sourcesDir,\n\t\tLogger:     l,\n\t})\n\n\tskipUpload := input.Params.FileGlob == \"\" && input.Params.FilepathPrefix == \"\"\n\n\tvar m metadata.Metadata\n\tvar skipFileCheck bool\n\tif input.Params.MetadataFile != \"\" {\n\t\tmetadataFilepath := filepath.Join(sourcesDir, input.Params.MetadataFile)\n\t\tmetadataBytes, err := ioutil.ReadFile(metadataFilepath)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"metadata_file could not be read: %s\", err.Error())\n\t\t}\n\n\t\terr = yaml.Unmarshal(metadataBytes, &m)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"metadata_file could not be parsed: %s\", err.Error())\n\t\t}\n\n\t\terr = m.Validate()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"metadata_file is invalid: %s\", err.Error())\n\t\t}\n\n\t\tskipFileCheck = true\n\t}\n\n\tvalidation := validator.NewOutValidator(input)\n\n\tmetadataFetcher := release.NewMetadataFetcher(m, skipFileCheck)\n\n\tmd5summer := md5sum.NewFileSummer()\n\n\treleaseCreator := release.NewReleaseCreator(pivnetClient, metadataFetcher, l, m, skipFileCheck, input.Params, sourcesDir, input.Source.ProductSlug)\n\treleaseUploader := release.NewReleaseUploader(uploaderClient, pivnetClient, l, md5summer, m, skipUpload, sourcesDir, input.Source.ProductSlug)\n\treleaseFinalizer := release.NewFinalizer(pivnetClient, metadataFetcher, input.Params, sourcesDir, input.Source.ProductSlug)\n\n\toutCmd := out.NewOutCommand(out.OutCommandConfig{\n\t\tSkipFileCheck: skipFileCheck,\n\t\tLogger:        l,\n\t\tOutDir:        outDir,\n\t\tSourcesDir:    sourcesDir,\n\t\tScreenWriter:  log.New(os.Stderr, \"\", 0),\n\t\tGlobClient:    globber,\n\t\tValidation:    validation,\n\t\tCreator:       releaseCreator,\n\t\tUploader:      releaseUploader,\n\t\tFinalizer:     releaseFinalizer,\n\t\tM:             m,\n\t})\n\n\tresponse, err := outCmd.Run(input)\n\tif err != nil {\n\t\tl.Debugf(\"Exiting with error: %v\\n\", err)\n\t\tlog.Fatalln(err)\n\t}\n\n\tl.Debugf(\"Returning output: %+v\\n\", response)\n\n\terr = json.NewEncoder(os.Stdout).Encode(response)\n\tif err != nil {\n\t\tl.Debugf(\"Exiting with error: %v\\n\", err)\n\t\tlog.Fatalln(err)\n\t}\n}\n<commit_msg>Missed removing logger in out cmd<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/concourse\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/globs\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/md5sum\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/metadata\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/out\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/out\/release\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/pivnet\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/s3\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/uploader\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/useragent\"\n\t\"github.com\/pivotal-cf-experimental\/pivnet-resource\/validator\"\n\t\"github.com\/pivotal-golang\/lager\"\n\t\"github.com\/robdimsdale\/sanitizer\"\n)\n\nconst (\n\ts3OutBinaryName = \"s3-out\"\n\tdefaultBucket   = \"pivotalnetwork\"\n\tdefaultRegion   = \"eu-west-1\"\n)\n\nvar (\n\t\/\/ version is deliberately left uninitialized so it can be set at compile-time\n\tversion string\n)\n\nfunc main() {\n\tif version == \"\" {\n\t\tversion = \"dev\"\n\t}\n\n\tif len(os.Args) < 2 {\n\t\tlog.Fatalln(fmt.Sprintf(\n\t\t\t\"not enough args - usage: %s <sources directory>\", os.Args[0]))\n\t}\n\n\tsourcesDir := os.Args[1]\n\n\toutDir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tvar input concourse.OutRequest\n\n\terr = json.NewDecoder(os.Stdin).Decode(&input)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tfmt.Fprintf(os.Stderr, \"PivNet Resource version: %s\\n\", version)\n\n\tsanitized := concourse.SanitizedSource(input.Source)\n\tsanitizer := sanitizer.NewSanitizer(sanitized, os.Stderr)\n\n\tl = lager.NewLogger(\"pivnet-resource\")\n\tl.RegisterSink(lager.NewWriterSink(sanitizer, lager.DEBUG))\n\n\tvar endpoint string\n\tif input.Source.Endpoint != \"\" {\n\t\tendpoint = input.Source.Endpoint\n\t} else {\n\t\tendpoint = pivnet.Endpoint\n\t}\n\n\tclientConfig := pivnet.NewClientConfig{\n\t\tEndpoint:  endpoint,\n\t\tToken:     input.Source.APIToken,\n\t\tUserAgent: useragent.UserAgent(version, \"put\", input.Source.ProductSlug),\n\t}\n\n\tpivnetClient := pivnet.NewClient(\n\t\tclientConfig,\n\t\tl,\n\t)\n\n\tbucket := input.Source.Bucket\n\tif bucket == \"\" {\n\t\tbucket = defaultBucket\n\t}\n\n\tregion := input.Source.Region\n\tif region == \"\" {\n\t\tregion = defaultRegion\n\t}\n\n\ts3Client := s3.NewClient(s3.NewClientConfig{\n\t\tAccessKeyID:     input.Source.AccessKeyID,\n\t\tSecretAccessKey: input.Source.SecretAccessKey,\n\t\tRegionName:      region,\n\t\tBucket:          bucket,\n\t\tLogger:          l,\n\t\tStdout:          os.Stdout,\n\t\tStderr:          os.Stderr,\n\t\tOutBinaryPath:   filepath.Join(outDir, s3OutBinaryName),\n\t})\n\n\tuploaderClient := uploader.NewClient(uploader.Config{\n\t\tFilepathPrefix: input.Params.FilepathPrefix,\n\t\tSourcesDir:     sourcesDir,\n\t\tLogger:         l,\n\t\tTransport:      s3Client,\n\t})\n\n\tglobber := globs.NewGlobber(globs.GlobberConfig{\n\t\tFileGlob:   input.Params.FileGlob,\n\t\tSourcesDir: sourcesDir,\n\t\tLogger:     l,\n\t})\n\n\tskipUpload := input.Params.FileGlob == \"\" && input.Params.FilepathPrefix == \"\"\n\n\tvar m metadata.Metadata\n\tvar skipFileCheck bool\n\tif input.Params.MetadataFile != \"\" {\n\t\tmetadataFilepath := filepath.Join(sourcesDir, input.Params.MetadataFile)\n\t\tmetadataBytes, err := ioutil.ReadFile(metadataFilepath)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"metadata_file could not be read: %s\", err.Error())\n\t\t}\n\n\t\terr = yaml.Unmarshal(metadataBytes, &m)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"metadata_file could not be parsed: %s\", err.Error())\n\t\t}\n\n\t\terr = m.Validate()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"metadata_file is invalid: %s\", err.Error())\n\t\t}\n\n\t\tskipFileCheck = true\n\t}\n\n\tvalidation := validator.NewOutValidator(input)\n\n\tmetadataFetcher := release.NewMetadataFetcher(m, skipFileCheck)\n\n\tmd5summer := md5sum.NewFileSummer()\n\n\treleaseCreator := release.NewReleaseCreator(pivnetClient, metadataFetcher, l, m, skipFileCheck, input.Params, sourcesDir, input.Source.ProductSlug)\n\treleaseUploader := release.NewReleaseUploader(uploaderClient, pivnetClient, l, md5summer, m, skipUpload, sourcesDir, input.Source.ProductSlug)\n\treleaseFinalizer := release.NewFinalizer(pivnetClient, metadataFetcher, input.Params, sourcesDir, input.Source.ProductSlug)\n\n\toutCmd := out.NewOutCommand(out.OutCommandConfig{\n\t\tSkipFileCheck: skipFileCheck,\n\t\tLogger:        l,\n\t\tOutDir:        outDir,\n\t\tSourcesDir:    sourcesDir,\n\t\tScreenWriter:  log.New(os.Stderr, \"\", 0),\n\t\tGlobClient:    globber,\n\t\tValidation:    validation,\n\t\tCreator:       releaseCreator,\n\t\tUploader:      releaseUploader,\n\t\tFinalizer:     releaseFinalizer,\n\t\tM:             m,\n\t})\n\n\tresponse, err := outCmd.Run(input)\n\tif err != nil {\n\t\tl.Debug(\"Exiting with error\", lager.Data{\"error\": err})\n\t\tlog.Fatalln(err)\n\t}\n\n\tl.Debug(\"Returning output\", lager.Data{\"response\": response})\n\n\terr = json.NewEncoder(os.Stdout).Encode(response)\n\tif err != nil {\n\t\tl.Debug(\"Exiting with error\", lager.Data{\"error\": err})\n\t\tlog.Fatalln(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 tsuru authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"github.com\/globocom\/config\"\n\t\"github.com\/globocom\/tsuru\/cmd\"\n\t\"github.com\/globocom\/tsuru\/provision\"\n\t_ \"github.com\/globocom\/tsuru\/provision\/docker\"\n\t_ \"github.com\/globocom\/tsuru\/provision\/juju\"\n\t\"os\"\n)\n\nconst defaultConfigPath = \"\/etc\/tsuru\/tsuru.conf\"\n\nfunc buildManager() *cmd.Manager {\n\tm := cmd.NewManager(\"tsr\", \"0.2.6\", \"\", os.Stdout, os.Stderr, os.Stdin)\n\tm.Register(&tsrCommand{Command: &apiCmd{}})\n\tm.Register(&tsrCommand{Command: &collectorCmd{}})\n\tm.Register(&tsrCommand{Command: tokenCmd{}})\n\tm.Register(&tsrCommand{Command: &healerCmd{}})\n\tregisterProvisionersCommands(m)\n\treturn m\n}\n\nfunc registerProvisionersCommands(m *cmd.Manager) {\n\tprovisioners := provision.Registry()\n\tfor _, p := range provisioners {\n\t\tif c, ok := p.(provision.Commandable); ok {\n\t\t\tcommands := c.Commands()\n\t\t\tfor _, cmd := range commands {\n\t\t\t\tm.Register(&tsrCommand{Command: cmd})\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc main() {\n\tconfig.ReadConfigFile(defaultConfigPath)\n\tm := buildManager()\n\tm.Run(os.Args[1:])\n}\n<commit_msg>cmd\/tsr: bump to 0.2.7<commit_after>\/\/ Copyright 2013 tsuru authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"github.com\/globocom\/config\"\n\t\"github.com\/globocom\/tsuru\/cmd\"\n\t\"github.com\/globocom\/tsuru\/provision\"\n\t_ \"github.com\/globocom\/tsuru\/provision\/docker\"\n\t_ \"github.com\/globocom\/tsuru\/provision\/juju\"\n\t\"os\"\n)\n\nconst defaultConfigPath = \"\/etc\/tsuru\/tsuru.conf\"\n\nfunc buildManager() *cmd.Manager {\n\tm := cmd.NewManager(\"tsr\", \"0.2.7\", \"\", os.Stdout, os.Stderr, os.Stdin)\n\tm.Register(&tsrCommand{Command: &apiCmd{}})\n\tm.Register(&tsrCommand{Command: &collectorCmd{}})\n\tm.Register(&tsrCommand{Command: tokenCmd{}})\n\tm.Register(&tsrCommand{Command: &healerCmd{}})\n\tregisterProvisionersCommands(m)\n\treturn m\n}\n\nfunc registerProvisionersCommands(m *cmd.Manager) {\n\tprovisioners := provision.Registry()\n\tfor _, p := range provisioners {\n\t\tif c, ok := p.(provision.Commandable); ok {\n\t\t\tcommands := c.Commands()\n\t\t\tfor _, cmd := range commands {\n\t\t\t\tm.Register(&tsrCommand{Command: cmd})\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc main() {\n\tconfig.ReadConfigFile(defaultConfigPath)\n\tm := buildManager()\n\tm.Run(os.Args[1:])\n}\n<|endoftext|>"}
{"text":"<commit_before>package gosupplychain\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/client9\/go-license\"\n\t\"github.com\/google\/go-github\/github\"\n\t\"golang.org\/x\/oauth2\"\n)\n\n\/\/ Repo describes a repo basic\n\/\/ NOTE: likely to be replaced with a larger structure\ntype Repo struct {\n\tName        string\n\tDescription string\n\tUpdated     time.Time\n}\n\n\/\/ User is the top level GitHub user (maybe be a company or user)\n\/\/ NOTE: like to be replaced with a larger structure\ntype User struct {\n\tName  string\n\tRepos []Repo\n}\n\n\/\/ GitHubFile is contains everything needed to represent a file at a point in time\n\/\/  Likely to be generalized later\ntype GitHubFile struct {\n\tOwner string\n\tRepo  string\n\tPath  string\n\tTree  string\n\tSHA   string\n}\n\n\/\/ RawURL returns a URL to the raw content, without formatting\nfunc (file GitHubFile) RawURL() string {\n\treturn fmt.Sprintf(\"https:\/\/raw.githubusercontent.com\/%s\/%s\/%s\/%s\", file.Owner, file.Repo, file.Tree, file.Path)\n}\n\n\/\/ WebURL returns a human-friend URL to github\nfunc (file GitHubFile) WebURL() string {\n\treturn fmt.Sprintf(\"https:\/\/github.com\/%s\/%s\/blob\/%s\/%s\", file.Owner, file.Repo, file.Tree, file.Path)\n}\n\n\/\/ GitHub is a VCS\ntype GitHub struct {\n\tClient *github.Client\n}\n\n\/\/ NewGitHub creates a github client using oauth token\nfunc NewGitHub(oauthToken string) GitHub {\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{\n\t\t\tAccessToken: oauthToken,\n\t\t})\n\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\treturn GitHub{\n\t\tClient: github.NewClient(tc),\n\t}\n}\n\n\/\/ GetFileContentsURL generates a download URL\nfunc (gh GitHub) GetFileContentsURL(owner, repo, sha, filepath string) string {\n\treturn fmt.Sprintf(\"https:\/\/raw.githubusercontent.com\/%s\/%s\/%s\/%s\", owner, repo, sha, filepath)\n}\n\n\/\/ GetFileContents down loads a file\nfunc (gh GitHub) GetFileContents(owner, repo, tree, filepath string) (string, error) {\n\turl := gh.GetFileContentsURL(owner, repo, tree, filepath)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\treturn string(body), err\n}\n\n\/\/ GetTreeFiles returns the list of files given a tree.\n\/\/\n\/\/ sha must be a valid git sha value or \"master\"\nfunc (gh GitHub) GetTreeFiles(owner string, repo string, sha string) ([]GitHubFile, error) {\n\ttree, _, err := gh.Client.Git.GetTree(owner, repo, sha, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/log.Printf(\"TREE: %+v\", *tree)\n\tout := make([]GitHubFile, 0, len(tree.Entries))\n\tfor _, t := range tree.Entries {\n\t\tout = append(out, GitHubFile{\n\t\t\tOwner: owner,\n\t\t\tRepo:  repo,\n\t\t\tTree:  sha,\n\t\t\tPath:  *t.Path,\n\t\t\tSHA:   *t.SHA,\n\t\t})\n\n\t\t\/\/log.Printf(\"TREE: %s\", t)\n\t}\n\treturn out, nil\n}\n\n\/\/ SearchByUsers performs a search on multiple users\nfunc (gh GitHub) SearchByUsers(oauthToken string, searchQuery string, users []string) ([]User, error) {\n\topts := &github.SearchOptions{\n\t\tSort:  \"updated\",\n\t\tOrder: \"desc\",\n\t\tListOptions: github.ListOptions{\n\t\t\tPerPage: 100,\n\t\t},\n\t}\n\n\tout := make([]User, 0, len(users))\n\n\t\/\/ assume each query takes 1 second round trip\n\t\/\/  and we get 20\/minute\n\t\/\/  wait 4 seconds between calls\n\tfor pos, co := range users {\n\t\tif pos > 0 {\n\t\t\ttime.Sleep(time.Second * 4)\n\t\t}\n\t\tq := fmt.Sprintf(\"user:%s %s\", co, searchQuery)\n\t\tlog.Printf(\"Running query %q\", q)\n\t\trepos, _, err := gh.Client.Search.Repositories(q, opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif repos == nil || *repos.Total == 0 || repos.Repositories == nil {\n\t\t\tcontinue\n\t\t}\n\t\tuser := User{\n\t\t\tName: co,\n\t\t}\n\t\tfor _, val := range repos.Repositories {\n\n\t\t\tr := Repo{}\n\t\t\tif val.FullName != nil {\n\t\t\t\tr.Name = *val.FullName\n\t\t\t}\n\t\t\tif val.Description != nil {\n\t\t\t\tr.Description = *val.Description\n\t\t\t}\n\t\t\tif val.UpdatedAt != nil {\n\t\t\t\t\/\/ UpdateAt is a odd github.Time that embeds a time.Time\n\t\t\t\ttmp := *val.UpdatedAt\n\t\t\t\tr.Updated = tmp.Time\n\t\t\t}\n\t\t\tuser.Repos = append(user.Repos, r)\n\t\t}\n\t\tout = append(out, user)\n\t}\n\treturn out, nil\n}\n\n\/\/ GuessLicenseFromRepo attempts to determine a license\nfunc (gh GitHub) GuessLicenseFromRepo(owner string, repo string, sha string) (license.License, error) {\n\n\tfiles, err := gh.GetTreeFiles(owner, repo, sha)\n\tif err != nil {\n\t\treturn license.License{}, err\n\t}\n\tout := []string{}\n\tfor _, filename := range files {\n\t\tif IsPossibleLicenseFile(filename.Path) {\n\t\t\tout = append(out, filename.Path)\n\t\t\tbody, err := gh.GetFileContents(owner, repo, sha, filename.Path)\n\t\t\tif err != nil {\n\t\t\t\treturn license.License{}, fmt.Errorf(\"Unable to download %s: %s\", filename, err)\n\t\t\t}\n\t\t\tlic := license.License{\n\t\t\t\tText: body,\n\t\t\t\tFile: filename.WebURL(),\n\t\t\t}\n\t\t\terr = lic.GuessType()\n\t\t\tif err == nil {\n\t\t\t\treturn lic, nil\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ empty\n\treturn license.License{}, nil\n}\n<commit_msg>fix error message<commit_after>package gosupplychain\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/client9\/go-license\"\n\t\"github.com\/google\/go-github\/github\"\n\t\"golang.org\/x\/oauth2\"\n)\n\n\/\/ Repo describes a repo basic\n\/\/ NOTE: likely to be replaced with a larger structure\ntype Repo struct {\n\tName        string\n\tDescription string\n\tUpdated     time.Time\n}\n\n\/\/ User is the top level GitHub user (maybe be a company or user)\n\/\/ NOTE: like to be replaced with a larger structure\ntype User struct {\n\tName  string\n\tRepos []Repo\n}\n\n\/\/ GitHubFile is contains everything needed to represent a file at a point in time\n\/\/  Likely to be generalized later\ntype GitHubFile struct {\n\tOwner string\n\tRepo  string\n\tPath  string\n\tTree  string\n\tSHA   string\n}\n\n\/\/ RawURL returns a URL to the raw content, without formatting\nfunc (file GitHubFile) RawURL() string {\n\treturn fmt.Sprintf(\"https:\/\/raw.githubusercontent.com\/%s\/%s\/%s\/%s\", file.Owner, file.Repo, file.Tree, file.Path)\n}\n\n\/\/ WebURL returns a human-friend URL to github\nfunc (file GitHubFile) WebURL() string {\n\treturn fmt.Sprintf(\"https:\/\/github.com\/%s\/%s\/blob\/%s\/%s\", file.Owner, file.Repo, file.Tree, file.Path)\n}\n\n\/\/ GitHub is a VCS\ntype GitHub struct {\n\tClient *github.Client\n}\n\n\/\/ NewGitHub creates a github client using oauth token\nfunc NewGitHub(oauthToken string) GitHub {\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{\n\t\t\tAccessToken: oauthToken,\n\t\t})\n\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\treturn GitHub{\n\t\tClient: github.NewClient(tc),\n\t}\n}\n\n\/\/ GetFileContentsURL generates a download URL\nfunc (gh GitHub) GetFileContentsURL(owner, repo, sha, filepath string) string {\n\treturn fmt.Sprintf(\"https:\/\/raw.githubusercontent.com\/%s\/%s\/%s\/%s\", owner, repo, sha, filepath)\n}\n\n\/\/ GetFileContents down loads a file\nfunc (gh GitHub) GetFileContents(owner, repo, tree, filepath string) (string, error) {\n\turl := gh.GetFileContentsURL(owner, repo, tree, filepath)\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\treturn string(body), err\n}\n\n\/\/ GetTreeFiles returns the list of files given a tree.\n\/\/\n\/\/ sha must be a valid git sha value or \"master\"\nfunc (gh GitHub) GetTreeFiles(owner string, repo string, sha string) ([]GitHubFile, error) {\n\ttree, _, err := gh.Client.Git.GetTree(owner, repo, sha, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/log.Printf(\"TREE: %+v\", *tree)\n\tout := make([]GitHubFile, 0, len(tree.Entries))\n\tfor _, t := range tree.Entries {\n\t\tout = append(out, GitHubFile{\n\t\t\tOwner: owner,\n\t\t\tRepo:  repo,\n\t\t\tTree:  sha,\n\t\t\tPath:  *t.Path,\n\t\t\tSHA:   *t.SHA,\n\t\t})\n\n\t\t\/\/log.Printf(\"TREE: %s\", t)\n\t}\n\treturn out, nil\n}\n\n\/\/ SearchByUsers performs a search on multiple users\nfunc (gh GitHub) SearchByUsers(oauthToken string, searchQuery string, users []string) ([]User, error) {\n\topts := &github.SearchOptions{\n\t\tSort:  \"updated\",\n\t\tOrder: \"desc\",\n\t\tListOptions: github.ListOptions{\n\t\t\tPerPage: 100,\n\t\t},\n\t}\n\n\tout := make([]User, 0, len(users))\n\n\t\/\/ assume each query takes 1 second round trip\n\t\/\/  and we get 20\/minute\n\t\/\/  wait 4 seconds between calls\n\tfor pos, co := range users {\n\t\tif pos > 0 {\n\t\t\ttime.Sleep(time.Second * 4)\n\t\t}\n\t\tq := fmt.Sprintf(\"user:%s %s\", co, searchQuery)\n\t\tlog.Printf(\"Running query %q\", q)\n\t\trepos, _, err := gh.Client.Search.Repositories(q, opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif repos == nil || *repos.Total == 0 || repos.Repositories == nil {\n\t\t\tcontinue\n\t\t}\n\t\tuser := User{\n\t\t\tName: co,\n\t\t}\n\t\tfor _, val := range repos.Repositories {\n\n\t\t\tr := Repo{}\n\t\t\tif val.FullName != nil {\n\t\t\t\tr.Name = *val.FullName\n\t\t\t}\n\t\t\tif val.Description != nil {\n\t\t\t\tr.Description = *val.Description\n\t\t\t}\n\t\t\tif val.UpdatedAt != nil {\n\t\t\t\t\/\/ UpdateAt is a odd github.Time that embeds a time.Time\n\t\t\t\ttmp := *val.UpdatedAt\n\t\t\t\tr.Updated = tmp.Time\n\t\t\t}\n\t\t\tuser.Repos = append(user.Repos, r)\n\t\t}\n\t\tout = append(out, user)\n\t}\n\treturn out, nil\n}\n\n\/\/ GuessLicenseFromRepo attempts to determine a license\nfunc (gh GitHub) GuessLicenseFromRepo(owner string, repo string, sha string) (license.License, error) {\n\n\tfiles, err := gh.GetTreeFiles(owner, repo, sha)\n\tif err != nil {\n\t\treturn license.License{}, err\n\t}\n\tout := []string{}\n\tfor _, filename := range files {\n\t\tif IsPossibleLicenseFile(filename.Path) {\n\t\t\tout = append(out, filename.Path)\n\t\t\tbody, err := gh.GetFileContents(owner, repo, sha, filename.Path)\n\t\t\tif err != nil {\n\t\t\t\treturn license.License{}, fmt.Errorf(\"unable to download %s: %s\", filename, err)\n\t\t\t}\n\t\t\tlic := license.License{\n\t\t\t\tText: body,\n\t\t\t\tFile: filename.WebURL(),\n\t\t\t}\n\t\t\terr = lic.GuessType()\n\t\t\tif err == nil {\n\t\t\t\treturn lic, nil\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ empty\n\treturn license.License{}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main;\n\nimport (\n    \"github.com\/herman-rogers\/kingkai\"\n    \"github.com\/hudl\/fargo\"\n);\n\nfunc main() {\n    RegisterEureka();\n    kingkai.StartKingKai(routes, \":9000\");\n}\n\nfunc RegisterEureka() {\n    c := fargo.NewConn(\"http:\/\/eureka-gamebuildr.herokuapp.com\")\n    c.GetApps()\n}\n<commit_msg>Attempt to open at port 80<commit_after>package main;\n\nimport (\n    \"github.com\/herman-rogers\/kingkai\"\n    \"github.com\/hudl\/fargo\"\n);\n\nfunc main() {\n    RegisterEureka();\n    kingkai.StartKingKai(routes, \"\");\n}\n\nfunc RegisterEureka() {\n    c := fargo.NewConn(\"http:\/\/eureka-gamebuildr.herokuapp.com\")\n    c.GetApps()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main;\n\nimport (\n    \"github.com\/herman-rogers\/kingkai\"\n    \"github.com\/hudl\/fargo\"\n);\n\nfunc main() {\n    RegisterEureka();\n    kingkai.StartKingKai(routes, \"\");\n}\n\nfunc RegisterEureka() {\n    c := fargo.NewConn(\"http:\/\/eureka-gamebuildr.herokuapp.com\")\n    c.GetApps()\n}\n<commit_msg>Add test for kingkai server running<commit_after>package main;\n\nimport (\n    \"github.com\/herman-rogers\/kingkai\"\n    \/\/\"github.com\/hudl\/fargo\"\n);\n\nfunc main() {\n    RegisterEureka();\n    kingkai.StartKingKai(routes, \"\");\n}\n\nfunc RegisterEureka() {\n    \/\/e := fargo.NewConn(\"http:\/\/eureka-gamebuildr.herokuapp.com\");\n    \/\/ \/\/ app, _ := e.GetApp(\"TESTAPP\");\n    \/\/e.GetApps();\n    \/\/ fmt.Println(apps);\n    \/\/ for k, v := range apps {\n    \/\/     fmt.Println(\"k:\", k, \"v:\", v);\n    \/\/ }\n\n    \/\/ e, _ := fargo.NewConnFromConfigFile(\"\/etc\/fargo.gcfg\")\n    \/\/ app, _ := e.GetApp(\"TESTAPP\")\n    \/\/ \/\/ starts a goroutine that updates the application on poll interval\n    \/\/ e.UpdateApp(&app)\n    \/\/ for {\n    \/\/     for _, ins := range app.Instances {\n    \/\/         fmt.Printf(\"%s, \", ins.HostName)\n    \/\/     }\n    \/\/     fmt.Println(len(app.Instances))\n    \/\/     <-time.After(10 * time.Second)\n    \/\/ }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This package provides a framework for creating powerful lexical\n\/\/ preprocessors for go code.\npackage goprep\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"go\/printer\"\n\t\"go\/parser\"\n\t\"go\/scanner\"\n\t\"go\/token\"\n\t\"os\"\n)\n\n\/\/ Represents a token as returned by scanner.Scanner.Scan(), with the position,\n\/\/ token type, and string representation.\ntype TokenInfo struct {\n\tPos   token.Pos\n\tToken token.Token\n\tStr   string\n}\n\n\/\/ StdInit initializes appropriate processing channels for os.Stdin and\n\/\/ os.Stdout. For the most part, this should be used instead of specific calls\n\/\/ to Write and Read.\nfunc StdInit() (<-chan TokenInfo, chan<- string, <-chan interface{}) {\n\ttokIn := Read(os.Stdin)\n\ttokOut, done := Write(os.Stdout)\n\treturn tokIn, tokOut, done\n}\n\n\/\/ Write allows writing properly formatted go code to a given io.Writer via a\n\/\/ series of token strings passed to the returned channel. The second returned\n\/\/ channel will have a single nil value sent when writing is complete.\nfunc Write(output io.Writer) (chan<- string, <-chan interface{}) {\n\ttokC := make(chan string)\n\tdone := make(chan interface{})\n\n\treader, writer := io.Pipe()\n\n\t\/\/ spit the tokens to the write end of the pipe\n\tgo func(output io.WriteCloser, tokC <-chan string) {\n\t\tfor tok := range tokC {\n\t\t\tfmt.Fprintf(output, \" %s\", tok)\n\t\t}\n\t\toutput.Close()\n\t}(writer, tokC)\n\n\t\/\/ parse the tokens into an AST and write to output\n\tgo func(reader io.ReadCloser, output io.Writer, done chan interface{}) {\n\t\tfset := token.NewFileSet()\n\t\tfile, err := parser.ParseFile(\n\t\t\tfset, \"<stdin>\", reader, parser.ParseComments)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tprinter.Fprint(output, fset, file)\n\t\tdone <- nil\n\t}(reader, output, done)\n\n\treturn tokC, done\n}\n\n\/\/ Read reads from the given io.Reader and writes a series of TokenInfo objects\n\/\/ to the returned channel.\nfunc Read(input io.Reader) <-chan TokenInfo {\n\t\/\/ start reading\n\tsrc, err := ioutil.ReadAll(input)\n\tif err != nil { panic(err) }\n\n\tfset := token.NewFileSet()\n\tfile := fset.AddFile(\"<stdin>\", fset.Base(), len(src))\n\n\ts := scanner.Scanner{}\n\ts.Init(file, src, nil, scanner.InsertSemis | scanner.ScanComments)\n\n\ttokC := make(chan TokenInfo)\n\n\tgo func(s scanner.Scanner, tokC chan<- TokenInfo) {\n\t\tpos, tok, str := s.Scan()\n\t\tfor tok != token.EOF {\n\t\t\tif tok == token.COMMENT {\n\t\t\t\tstr = str + \"\\n\"\n\t\t\t}\n\t\t\ttokC <- TokenInfo{pos, tok, str}\n\t\t\tpos, tok, str = s.Scan()\n\t\t}\n\t\tclose(tokC)\n\t}(s, tokC)\n\n\treturn tokC\n}\n\n\/\/ Ignore produces a modified input stream that does not include any tokens for\n\/\/ which f evaluates to true, thus discarding a certain class of tokens.\nfunc Ignore(tIn <-chan TokenInfo, out chan<- string, f func(TokenInfo) bool) <-chan TokenInfo {\n\ttOut := make(chan TokenInfo)\n\tgo func() {\n\t\tfor tok := range tIn {\n\t\t\tif !f(tok) {\n\t\t\t\ttOut <- tok\n\t\t\t}\n\t\t}\n\t\tclose(tOut)\n\t}()\n\treturn tOut\n}\n\n\/\/ IgnoreToken is like Ignore, discarding all tokens whose string content is\n\/\/ equal to the given string.\nfunc IgnoreToken(tIn <-chan TokenInfo, out chan<- string, str string) <-chan TokenInfo {\n\treturn Ignore(tIn, out, func(ti TokenInfo) bool {\n\t\treturn ti.Str == str\n\t})\n}\n\n\/\/ IgnoreType is like Ignore, discarding all tokens of a certain type.\nfunc IgnoreType(tIn <-chan TokenInfo, out chan<- string, tok token.Token) <-chan TokenInfo {\n\treturn Ignore(tIn, out, func(ti TokenInfo) bool {\n\t\treturn ti.Token == tok\n\t})\n}\n\n\/\/ Pass redirects all tokens for which f evaluates to true to the output\n\/\/ channel, returning the altered input channel.\nfunc Pass(tIn <-chan TokenInfo, out chan<- string, f func(TokenInfo) bool) <-chan TokenInfo {\n\ttOut := make(chan TokenInfo)\n\tgo func() {\n\t\tfor tok := range tIn {\n\t\t\tif f(tok) {\n\t\t\t\tout <- tok.Str\n\t\t\t} else {\n\t\t\t\ttOut <- tok\n\t\t\t}\n\t\t}\n\t\tclose(tOut)\n\t}()\n\treturn tOut\n}\n\n<commit_msg>Adding PassToken and PassType<commit_after>\/\/ This package provides a framework for creating powerful lexical\n\/\/ preprocessors for go code.\npackage goprep\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"go\/printer\"\n\t\"go\/parser\"\n\t\"go\/scanner\"\n\t\"go\/token\"\n\t\"os\"\n)\n\n\/\/ Represents a token as returned by scanner.Scanner.Scan(), with the position,\n\/\/ token type, and string representation.\ntype TokenInfo struct {\n\tPos   token.Pos\n\tToken token.Token\n\tStr   string\n}\n\n\/\/ StdInit initializes appropriate processing channels for os.Stdin and\n\/\/ os.Stdout. For the most part, this should be used instead of specific calls\n\/\/ to Write and Read.\nfunc StdInit() (<-chan TokenInfo, chan<- string, <-chan interface{}) {\n\ttokIn := Read(os.Stdin)\n\ttokOut, done := Write(os.Stdout)\n\treturn tokIn, tokOut, done\n}\n\n\/\/ Write allows writing properly formatted go code to a given io.Writer via a\n\/\/ series of token strings passed to the returned channel. The second returned\n\/\/ channel will have a single nil value sent when writing is complete.\nfunc Write(output io.Writer) (chan<- string, <-chan interface{}) {\n\ttokC := make(chan string)\n\tdone := make(chan interface{})\n\n\treader, writer := io.Pipe()\n\n\t\/\/ spit the tokens to the write end of the pipe\n\tgo func(output io.WriteCloser, tokC <-chan string) {\n\t\tfor tok := range tokC {\n\t\t\tfmt.Fprintf(output, \" %s\", tok)\n\t\t}\n\t\toutput.Close()\n\t}(writer, tokC)\n\n\t\/\/ parse the tokens into an AST and write to output\n\tgo func(reader io.ReadCloser, output io.Writer, done chan interface{}) {\n\t\tfset := token.NewFileSet()\n\t\tfile, err := parser.ParseFile(\n\t\t\tfset, \"<stdin>\", reader, parser.ParseComments)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tprinter.Fprint(output, fset, file)\n\t\tdone <- nil\n\t}(reader, output, done)\n\n\treturn tokC, done\n}\n\n\/\/ Read reads from the given io.Reader and writes a series of TokenInfo objects\n\/\/ to the returned channel.\nfunc Read(input io.Reader) <-chan TokenInfo {\n\t\/\/ start reading\n\tsrc, err := ioutil.ReadAll(input)\n\tif err != nil { panic(err) }\n\n\tfset := token.NewFileSet()\n\tfile := fset.AddFile(\"<stdin>\", fset.Base(), len(src))\n\n\ts := scanner.Scanner{}\n\ts.Init(file, src, nil, scanner.InsertSemis | scanner.ScanComments)\n\n\ttokC := make(chan TokenInfo)\n\n\tgo func(s scanner.Scanner, tokC chan<- TokenInfo) {\n\t\tpos, tok, str := s.Scan()\n\t\tfor tok != token.EOF {\n\t\t\tif tok == token.COMMENT {\n\t\t\t\tstr = str + \"\\n\"\n\t\t\t}\n\t\t\ttokC <- TokenInfo{pos, tok, str}\n\t\t\tpos, tok, str = s.Scan()\n\t\t}\n\t\tclose(tokC)\n\t}(s, tokC)\n\n\treturn tokC\n}\n\n\/\/ Ignore produces a modified input stream that does not include any tokens for\n\/\/ which f evaluates to true, thus discarding a certain class of tokens.\nfunc Ignore(tIn <-chan TokenInfo, out chan<- string, f func(TokenInfo) bool) <-chan TokenInfo {\n\ttOut := make(chan TokenInfo)\n\tgo func() {\n\t\tfor tok := range tIn {\n\t\t\tif !f(tok) {\n\t\t\t\ttOut <- tok\n\t\t\t}\n\t\t}\n\t\tclose(tOut)\n\t}()\n\treturn tOut\n}\n\n\/\/ IgnoreToken is like Ignore, discarding all tokens whose string content is\n\/\/ equal to the given string.\nfunc IgnoreToken(tIn <-chan TokenInfo, out chan<- string, str string) <-chan TokenInfo {\n\treturn Ignore(tIn, out, func(ti TokenInfo) bool {\n\t\treturn ti.Str == str\n\t})\n}\n\n\/\/ IgnoreType is like Ignore, discarding all tokens of a certain type.\nfunc IgnoreType(tIn <-chan TokenInfo, out chan<- string, tok token.Token) <-chan TokenInfo {\n\treturn Ignore(tIn, out, func(ti TokenInfo) bool {\n\t\treturn ti.Token == tok\n\t})\n}\n\n\/\/ Pass redirects all tokens for which f evaluates to true to the output\n\/\/ channel, returning the altered input channel.\nfunc Pass(tIn <-chan TokenInfo, out chan<- string, f func(TokenInfo) bool) <-chan TokenInfo {\n\ttOut := make(chan TokenInfo)\n\tgo func() {\n\t\tfor tok := range tIn {\n\t\t\tif f(tok) {\n\t\t\t\tout <- tok.Str\n\t\t\t} else {\n\t\t\t\ttOut <- tok\n\t\t\t}\n\t\t}\n\t\tclose(tOut)\n\t}()\n\treturn tOut\n}\n\n\/\/ PassToken is like Pass, passing all tokens whose string content is equal to\n\/\/ the given string.\nfunc PassToken(tIn <-chan TokenInfo, out chan<- string, str string) <-chan TokenInfo {\n\treturn Pass(tIn, out, func(ti TokenInfo) bool {\n\t\treturn ti.Str == str\n\t})\n}\n\n\/\/ PassType is like Pass, passing all tokens of a certain type.\nfunc PassType(tIn <-chan TokenInfo, out chan<- string, tok token.Token) <-chan TokenInfo {\n\treturn Pass(tIn, out, func(ti TokenInfo) bool {\n\t\treturn ti.Token == tok\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package goraph\n\nimport \"errors\"\nimport \"fmt\"\n\ntype Node struct {\n\tid    int\n\tLabel string\n}\n\nvar nilNode = Node{id: -1}\n\nfunc (n Node) isNil() bool {\n\treturn n.id == -1\n}\n\ntype Edge struct {\n\tnode1 Node\n\tnode2 Node\n}\n\ntype BipartiteGraph struct {\n\tLeft  []Node\n\tRight []Node\n\tEdges []Edge\n}\n\nfunc NewBipartiteGraph(leftValues, rightValues []interface{}, neighbours func(interface{}, interface{}) (bool, error)) (*BipartiteGraph, error) {\n\tif len(leftValues) != len(rightValues) {\n\t\treturn nil, errors.New(fmt.Sprintf(\"left and right values have mismatched lengths: %d and %d\", len(leftValues), len(rightValues)))\n\t}\n\n\tleft := []Node{}\n\tfor i, _ := range leftValues {\n\t\tleft = append(left, Node{i, \"left\"})\n\t}\n\n\tright := []Node{}\n\tfor j, _ := range rightValues {\n\t\tright = append(right, Node{j, \"right\"})\n\t}\n\n\tedges := []Edge{}\n\tfor i, leftValue := range leftValues {\n\t\tfor j, rightValue := range rightValues {\n\t\t\tneighbours, err := neighbours(leftValue, rightValue)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"error determining adjacency for %v and %v: %s\", leftValue, rightValue, err.Error()))\n\t\t\t}\n\n\t\t\tif neighbours {\n\t\t\t\tedges = append(edges, Edge{left[i], right[j]})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &BipartiteGraph{left, right, edges}, nil\n}\n\nfunc (bg *BipartiteGraph) Neighbours(n1, n2 Node) bool {\n\tfor _, edge := range bg.Edges {\n\t\tif (edge.node1 == n1 && edge.node2 == n2) || (edge.node1 == n2 && edge.node2 == n1) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (bg *BipartiteGraph) bfs(leftRight, rightLeft map[Node]Node, dist map[Node]int) bool {\n\tqueue := []Node{}\n\n\tfor _, v := range bg.Left {\n\t\tif leftRight[v].isNil() {\n\t\t\tdist[v] = 0\n\t\t\tqueue = append(queue, v)\n\t\t} else {\n\t\t\tdist[v] = -1\n\t\t}\n\t}\n\tdist[nilNode] = -1\n\n\tfor len(queue) > 0 {\n\t\tv := queue[0]\n\t\tqueue = queue[1:]\n\n\t\tif dist[v] != -1 && (dist[v] < dist[nilNode] || dist[nilNode] == -1) {\n\t\t\tfor _, u := range bg.Right {\n\t\t\t\tw := rightLeft[u]\n\n\t\t\t\tif bg.Neighbours(v, u) && dist[w] == -1 {\n\t\t\t\t\tdist[w] = dist[v] + 1\n\t\t\t\t\tqueue = append(queue, w)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn dist[nilNode] != -1\n}\n\nfunc (bg *BipartiteGraph) dfs(v Node, leftRight, rightLeft map[Node]Node, dist map[Node]int) bool {\n\tif !v.isNil() {\n\t\tfor _, u := range bg.Right {\n\t\t\tw := rightLeft[u]\n\n\t\t\tif bg.Neighbours(v, u) && dist[w] == dist[v]+1 && bg.dfs(w, leftRight, rightLeft, dist) {\n\t\t\t\trightLeft[u] = v\n\t\t\t\tleftRight[v] = u\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\tdist[v] = -1\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (bg *BipartiteGraph) LargestMatchingSize() int {\n\tleftRight := make(map[Node]Node)\n\trightLeft := make(map[Node]Node)\n\tdist := make(map[Node]int)\n\n\tfor _, v := range bg.Left {\n\t\tleftRight[v] = nilNode\n\t}\n\tfor _, u := range bg.Right {\n\t\trightLeft[u] = nilNode\n\t}\n\tleftRight[nilNode] = nilNode\n\trightLeft[nilNode] = nilNode\n\n\tmatching := 0\n\n\tfor bg.bfs(leftRight, rightLeft, dist) {\n\t\tfor _, v := range bg.Left {\n\t\t\tif leftRight[v].isNil() && bg.dfs(v, leftRight, rightLeft, dist) {\n\t\t\t\tmatching = matching + 1\n\t\t\t}\n\t\t}\n\t}\n\n\treturn matching\n}\n<commit_msg>make algorithm easier to understand<commit_after>package goraph\n\nimport \"errors\"\nimport \"fmt\"\nimport \"math\"\n\ntype Node struct {\n\tid    int\n\tLabel string\n}\n\ntype Edge struct {\n\tnode1 Node\n\tnode2 Node\n}\n\ntype BipartiteGraph struct {\n\tLeft  []Node\n\tRight []Node\n\tEdges []Edge \/\/ all edges go from Left to Right nodes\n}\n\nfunc NewBipartiteGraph(leftValues, rightValues []interface{}, neighbours func(interface{}, interface{}) (bool, error)) (*BipartiteGraph, error) {\n\tif len(leftValues) != len(rightValues) {\n\t\treturn nil, errors.New(fmt.Sprintf(\"left and right values have mismatched lengths: %d and %d\", len(leftValues), len(rightValues)))\n\t}\n\n\tleft := []Node{}\n\tfor i, _ := range leftValues {\n\t\tleft = append(left, Node{i, \"left\"})\n\t}\n\n\tright := []Node{}\n\tfor j, _ := range rightValues {\n\t\tright = append(right, Node{j, \"right\"})\n\t}\n\n\tedges := []Edge{}\n\tfor i, leftValue := range leftValues {\n\t\tfor j, rightValue := range rightValues {\n\t\t\tneighbours, err := neighbours(leftValue, rightValue)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.New(fmt.Sprintf(\"error determining adjacency for %v and %v: %s\", leftValue, rightValue, err.Error()))\n\t\t\t}\n\n\t\t\tif neighbours {\n\t\t\t\tedges = append(edges, Edge{left[i], right[j]})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &BipartiteGraph{left, right, edges}, nil\n}\n\nfunc free(node Node, matching []Edge) bool {\n\tfor _, edge := range matching {\n\t\tif edge.node1 == node || edge.node2 == node {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (bg *BipartiteGraph) partition(matching []Edge) [][]Node {\n\tlayers := [][]Node{}\n\tused := make(map[Node]bool)\n\tdone := false\n\n\tcurrentLayer := []Node{}\n\tfor _, node := range bg.Left {\n\t\tif free(node, matching) {\n\t\t\tused[node] = true\n\t\t\tcurrentLayer = append(currentLayer, node)\n\t\t}\n\t}\n\tlayers = append(layers, currentLayer)\n\n\tfor !done {\n\t\tlastLayer := currentLayer\n\t\tcurrentLayer = []Node{}\n\n\t\tif math.Mod(float64(len(layers)), 2.0) == 1.0 {\n\t\t\tfor _, leftNode := range lastLayer {\n\t\t\t\tfor _, rightNode := range bg.Right {\n\t\t\t\t\tif used[rightNode] {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tedge, found := bg.findEdge(leftNode, rightNode)\n\t\t\t\t\tif !found || edgeInMatching(edge, matching) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentLayer = append(currentLayer, rightNode)\n\t\t\t\t\tused[rightNode] = true\n\n\t\t\t\t\tif free(rightNode, matching) {\n\t\t\t\t\t\tdone = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, rightNode := range lastLayer {\n\t\t\t\tfor _, leftNode := range bg.Left {\n\t\t\t\t\tif used[leftNode] {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tedge, found := bg.findEdge(leftNode, rightNode)\n\t\t\t\t\tif !found || !edgeInMatching(edge, matching) {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentLayer = append(currentLayer, leftNode)\n\t\t\t\t\tused[leftNode] = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tlayers = append(layers, currentLayer)\n\t}\n\n\treturn layers\n}\n\nfunc edgeInMatching(edge Edge, matching []Edge) bool {\n\tfor _, e := range matching {\n\t\tif edge == e {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (bg *BipartiteGraph) findEdge(node1, node2 Node) (Edge, bool) {\n\tfor _, edge := range bg.Edges {\n\t\tif (edge.node1 == node1 && edge.node2 == node2) || (edge.node1 == node2 && edge.node2 == node1) {\n\t\t\treturn edge, true\n\t\t}\n\t}\n\n\treturn Edge{}, false\n}\n\nfunc (bg *BipartiteGraph) findDisjointSLAPHelper(currentNode Node, currentSLAP []Edge, currentLevel int, matching []Edge, layers [][]Node, used map[Node]bool) ([]Edge, bool) {\n\tused[currentNode] = true\n\n\tif currentLevel == 0 {\n\t\treturn currentSLAP, true\n\t}\n\n\tfor _, nextNode := range layers[currentLevel-1] {\n\t\tif used[nextNode] {\n\t\t\tcontinue\n\t\t}\n\n\t\tedge, found := bg.findEdge(currentNode, nextNode)\n\t\tif !found {\n\t\t\tcontinue\n\t\t}\n\n\t\tif edgeInMatching(edge, matching) == (math.Mod(float64(currentLevel), 2.0) == 1.0) {\n\t\t\tcontinue\n\t\t}\n\n\t\tcurrentSLAP = append(currentSLAP, edge)\n\t\tslap, found := bg.findDisjointSLAPHelper(nextNode, currentSLAP, currentLevel-1, matching, layers, used)\n\t\tif found {\n\t\t\treturn slap, true\n\t\t}\n\t\tcurrentSLAP = currentSLAP[:len(currentSLAP)-1]\n\t}\n\n\tused[currentNode] = false\n\treturn nil, false\n}\n\nfunc (bg *BipartiteGraph) findDisjointSLAP(start Node, matching []Edge, layers [][]Node, used map[Node]bool) ([]Edge, bool) {\n\treturn bg.findDisjointSLAPHelper(start, []Edge{}, len(layers)-1, matching, layers, used)\n}\n\nfunc (bg *BipartiteGraph) maximalDisjointSLAPCollection(matching []Edge) [][]Edge {\n\tlayers := bg.partition(matching)\n\tused := make(map[Node]bool)\n\tresult := [][]Edge{}\n\n\tfor _, u := range layers[len(layers)-1] {\n\t\tslap, found := bg.findDisjointSLAP(u, matching, layers, used)\n\t\tif found {\n\t\t\tfor _, edge := range slap {\n\t\t\t\tused[edge.node1] = true\n\t\t\t\tused[edge.node2] = true\n\t\t\t}\n\t\t\tresult = append(result, slap)\n\t\t}\n\t}\n\n\treturn result\n}\n\n\/\/ assumes each input slice has no repeat elements\nfunc symmetricDifference(edges1, edges2 []Edge) []Edge {\n\tedgesToInclude := make(map[Edge]bool)\n\n\tfor _, edge := range edges1 {\n\t\tedgesToInclude[edge] = true\n\t}\n\n\tfor _, edge := range edges2 {\n\t\tedgesToInclude[edge] = !edgesToInclude[edge]\n\t}\n\n\tedges := []Edge{}\n\tfor edge, include := range edgesToInclude {\n\t\tif include {\n\t\t\tedges = append(edges, edge)\n\t\t}\n\t}\n\n\treturn edges\n}\n\nfunc (bg *BipartiteGraph) LargestMatching() []Edge {\n\tmatching := []Edge{}\n\tpaths := bg.maximalDisjointSLAPCollection(matching)\n\n\tfor len(paths) > 0 {\n\t\tfor _, path := range paths {\n\t\t\tmatching = symmetricDifference(matching, path)\n\t\t}\n\t\tpaths = bg.maximalDisjointSLAPCollection(matching)\n\t}\n\n\treturn matching\n}\n\nfunc (bg *BipartiteGraph) LargestMatchingSize() int {\n\treturn len(bg.LargestMatching())\n}\n<|endoftext|>"}
{"text":"<commit_before>package gosmtp\n\nimport(\n\t\"net\/smtp\"\n\t\"fmt\"\n\t\"encoding\/base64\"\n\t\"time\"\n\t\"crypto\/md5\"\n)\n\nconst QueueSize = 100\n\ntype EmailSender struct{\n\tServerAddr string\n\tServerPort int\t\n\tSenderEmail string\n\tUsername string\n\tPassword string\n\tconn *smtp.Client\n\tqueue chan *Task\n}\n\nfunc (e *EmailSender) AddQueue(t *Task) <-chan error {\n\tif e.queue == nil {\n\t\te.queue = make(chan *Task,QueueSize)\n\t}\n\tt.err = make(chan error,1)\n\te.queue <- t\n\treturn t.err\n}\n\nfunc (e *EmailSender) run(done chan <- interface{}) error{\n\ttimer := time.NewTimer(10 * time.Second)\n\tif e.conn == nil || e.conn.Hello(\"localhost\")!=nil{\n\t\tvar err error\n\t\tif e.conn, err = smtp.Dial(fmt.Sprintf(\"%s:%d\",e.ServerAddr, e.ServerPort));err!=nil{\n\t\t\treturn fmt.Errorf(\"[EMAIL] SERVER Connect Failed，%s\",err)\n\t\t}\n\t\tif e.Username != \"\"{\n\t\t\tauth := smtp.PlainAuth(\"\", e.Username, e.Password, e.ServerAddr)\n\t\t\tif err := e.conn.Auth(auth);err !=nil {\n\t\t\t\treturn fmt.Errorf(\"[EMAIL] SERVER Auth failed，%s\",err)\n\t\t\t}\n\t\t}\n\t}\n\tgo func(){\n\t\tloop:\n\t\tfor{\n\t\t\tselect{\n\t\t\t\tcase t := <-e.queue:\t\t\t\t\n\t\t\t\t\tif err := e.send(t);err != nil{\n\t\t\t\t\t\tselect{\n\t\t\t\t\t\t\tcase t.err <- err:\n\t\t\t\t\t\t\tcase <- timer.C:\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tclose(t.err)\n\t\t\t\tcase <- timer.C:\n\t\t\t\t\tbreak loop\n\t\t\t}\n\t\t\ttimer.Reset(10 * time.Second)\n\t\t}\n\t\tdone <- \"ok\"\n\t\te.conn.Close()\n\t\te.conn.Quit()\n\t}()\n\treturn nil\n}\n\nfunc (e *EmailSender) send(t *Task) error{\n\tif err := e.conn.Mail(e.SenderEmail); err != nil {\n\t\treturn fmt.Errorf(\"[EMAIL] Server can't accept sender，%s，%s\",e.SenderEmail,err)\n\t}\n\tfor _, r := range(t.To){\n\t\tif err := e.conn.Rcpt(r);err != nil{\n\t\t\treturn fmt.Errorf(\"[EMAIL] Server can't accept recipient，%s，%s\",r,err)\n\t\t}\n\t}\n\tif wc,err:=e.conn.Data();err == nil{\n\t\tboundary := fmt.Sprintf(\"%x\",md5.Sum(t.Content))\n\t\twc.Write([]byte(\"Subject: \" + \"=?UTF-8?B?\" + base64.StdEncoding.EncodeToString([]byte(t.Subject)) +\"?=\\n\"))\n\t\twc.Write([]byte(\"MIME-Version: 1.0\" + \"\\n\"))\n\t\twc.Write([]byte(\"Date: \" + time.Now().Format(time.RFC1123Z) + \"\\n\"))\n\t\twc.Write([]byte(\"From: \" + e.SenderEmail + \"\\n\"))\n\t\twc.Write([]byte(\"To: undisclosed-recipients:;\\n\"))\n\t\twc.Write([]byte(\"Content-Type: multipart\/mixed; boundary = b\" + boundary + \"\\n\"))\n\t\twc.Write([]byte(\"This is a multi-part message in MIME format.\\n\\n--b\" + boundary + \"\\n\"))\n\t\twc.Write([]byte(\"Content-Type: text\/html;charset=uft-8\\n\"))\n\t\twc.Write([]byte(\"Content-Transfer-Encoding: base64\\n\\n\"))\n\t\tbody := base64.StdEncoding.EncodeToString(t.Content)\n\t\tfor len(body)>76{\n\t\t\twc.Write([]byte(body[0:76]))\n\t\t\twc.Write([]byte(\"\\n\"))\n\t\t\tbody = body[76:]\t\t\n\t\t}\n\t\twc.Write([]byte(body[0:]))\t\t\n\t\twc.Write([]byte(\"\\n\\n--b\"+boundary))\n\t\twc.Close()\n\t}\n\treturn nil\n}\n\nfunc (e *EmailSender) Init() <-chan error{\n\ter := make(chan error,1)\n\tgo func(){\n\t\tdone := make(chan interface{},1)\n\t\tfor{\n\t\t\tif len(e.queue)>0{\n\t\t\t\tif err := e.run(done);err!=nil{\n\t\t\t\t\ter <- err\n\t\t\t\t\tcontinue\n\t\t\t\t}\t\t\t\t\n\t\t\t\t<- done\n\t\t\t}\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\t}()\n\treturn er\n}\n\ntype Task struct{\n\tSubject string\n\tTo []string\n\tContent []byte\n\terr chan error\n}<commit_msg>add support to TLS<commit_after>package gosmtp\n\nimport (\n\t\"crypto\/md5\"\n\t\"crypto\/tls\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"net\/smtp\"\n\t\"time\"\n\t\"github.com\/pborman\/uuid\"\n)\n\nconst QueueSize = 100\n\ntype EmailSender struct {\n\tServerAddr  string\n\tServerPort  int\n\tSenderEmail string\n\tUsername    string\n\tPassword    string\n\tUseTLS      bool\n\tconn        *smtp.Client\n\tqueue       chan *Task\n}\n\nfunc (e *EmailSender) AddQueue(t *Task) <-chan error {\n\tif e.queue == nil {\n\t\te.queue = make(chan *Task, QueueSize)\n\t}\n\tt.err = make(chan error, 1)\n\te.queue <- t\n\treturn t.err\n}\n\nfunc (e *EmailSender) run(done chan<- interface{}) error {\n\ttimer := time.NewTimer(10 * time.Second)\n\tif e.conn == nil || e.conn.Hello(\"localhost\") != nil {\n\n\t\tif e.UseTLS {\n\t\t\tconfig := &tls.Config{\n\t\t\t\tServerName: e.ServerAddr,\n\t\t\t}\n\n\t\t\tif conn, err := tls.Dial(\"tcp\", fmt.Sprintf(\"%s:%d\", e.ServerAddr, 465), config); err != nil {\n\t\t\t\treturn fmt.Errorf(\"[EMAIL] SERVER Connect Failed，%s\", err)\n\t\t\t} else {\n\t\t\t\tvar err error\n\t\t\t\tif e.conn, err = smtp.NewClient(conn, e.ServerAddr); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"[EMAIL] SERVER Auth failed，%s\", err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tvar err error\n\t\t\tif e.conn, err = smtp.Dial(fmt.Sprintf(\"%s:%d\", e.ServerAddr, e.ServerPort)); err != nil {\n\t\t\t\treturn fmt.Errorf(\"[EMAIL] SERVER Connect Failed，%s\", err)\n\t\t\t}\n\t\t}\n\t\tif e.Username != \"\" {\n\t\t\tauth := smtp.PlainAuth(\"\", e.Username, e.Password, e.ServerAddr)\n\t\t\tif err := e.conn.Auth(auth); err != nil {\n\t\t\t\treturn fmt.Errorf(\"[EMAIL] SERVER Auth failed，%s\", err)\n\t\t\t}\n\t\t}\n\t}\n\tgo func() {\n\tloop:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase t := <-e.queue:\n\t\t\t\tif err := e.send(t); err != nil {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase t.err <- err:\n\t\t\t\t\tcase <-timer.C:\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tclose(t.err)\n\t\t\tcase <-timer.C:\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t\ttimer.Reset(10 * time.Second)\n\t\t}\n\t\tdone <- \"ok\"\n\t\te.conn.Close()\n\t\te.conn.Quit()\n\t}()\n\treturn nil\n}\n\nfunc (e *EmailSender) send(t *Task) error {\n\tif err := e.conn.Mail(e.SenderEmail); err != nil {\n\t\treturn fmt.Errorf(\"[EMAIL] Server can't accept sender，%s，%s\", e.SenderEmail, err)\n\t}\n\tfor _, r := range t.To {\n\t\tif err := e.conn.Rcpt(r); err != nil {\n\t\t\treturn fmt.Errorf(\"[EMAIL] Server can't accept recipient，%s，%s\", r, err)\n\t\t}\n\t}\n\tif wc, err := e.conn.Data(); err == nil {\n\t\tboundary := fmt.Sprintf(\"%x\", md5.Sum(t.Content))\n\t\twc.Write([]byte(\"Message-ID:<\" + uuid.New() + \"@hotelnabe.com.tw>\\n\"))\n\t\twc.Write([]byte(\"Subject: \" + \"=?UTF-8?B?\" + base64.StdEncoding.EncodeToString([]byte(t.Subject)) + \"?=\\n\"))\n\t\twc.Write([]byte(\"MIME-Version: 1.0\" + \"\\n\"))\n\t\twc.Write([]byte(\"Date: \" + time.Now().Format(time.RFC1123Z) + \"\\n\"))\n\t\twc.Write([]byte(\"From: \" + e.SenderEmail + \"\\n\"))\n\t\twc.Write([]byte(\"To: undisclosed-recipients:;\\n\"))\n\t\twc.Write([]byte(\"Content-Type: multipart\/mixed; boundary=b\" + boundary + \"\\n\\n\"))\n\t\twc.Write([]byte(\"This is a multi-part message in MIME format.\\n\\n--b\" + boundary + \"\\n\"))\n\t\twc.Write([]byte(\"Content-Type: text\/html;charset=UTF-8\\n\"))\n\t\twc.Write([]byte(\"Content-Transfer-Encoding: base64\\n\\n\"))\n\t\tbody := base64.StdEncoding.EncodeToString(t.Content)\n\t\tfor len(body) > 76 {\n\t\t\twc.Write([]byte(body[0:76]))\n\t\t\twc.Write([]byte(\"\\n\"))\n\t\t\tbody = body[76:]\n\t\t}\n\t\twc.Write([]byte(body[0:]))\n\t\twc.Write([]byte(\"\\n\\n--b\"+boundary+\"--\"))\n\t\twc.Close()\n\t}else{\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (e *EmailSender) Init() <-chan error {\n\ter := make(chan error, 1)\n\tgo func() {\n\t\tdone := make(chan interface{}, 1)\n\t\tfor {\n\t\t\tif len(e.queue) > 0 {\n\t\t\t\tif err := e.run(done); err != nil {\n\t\t\t\t\ter <- err\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t<-done\n\t\t\t}\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\t}()\n\treturn er\n}\n\ntype Task struct {\n\tSubject string\n\tTo      []string\n\tContent []byte\n\terr     chan error\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 Andreas Louca. All rights reserved.\n\/\/ Use of this source code is goverend by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage gosnmp\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype GoSNMP struct {\n\tTarget    string\n\tCommunity string\n\tVersion   SnmpVersion\n}\n\nfunc NewGoSNMP(target, community string, version SnmpVersion) *GoSNMP {\n\ts := &GoSNMP{target, community, version}\n\n\treturn s\n}\n\nfunc marshalOID(oid string) ([]byte, error) {\n\tvar err error\n\n\t\/\/ Encode the oid\n\toid = strings.Trim(oid, \".\")\n\toidParts := strings.Split(oid, \".\")\n\toidBytes := make([]int, len(oidParts))\n\n\t\/\/ Convert the string OID to an array of integers\n\tfor i := 0; i < len(oidParts); i++ {\n\t\toidBytes[i], err = strconv.Atoi(oidParts[i])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to parse OID: %s\\n\", err.Error())\n\t\t}\n\t}\n\n\tmOid, err := marshalObjectIdentifier(oidBytes)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to marshal OID: %s\\n\", err.Error())\n\t}\n\n\treturn mOid, err\n}\n\nfunc (x *GoSNMP) Get(oid string) (*Variable, error) {\n\tvar err error\n\n\t\/\/ Open a UDP connection to the target\n\tconn, err := net.Dial(\"udp\", fmt.Sprintf(\"%s:161\", x.Target))\n\tdefer conn.Close()\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error establishing connection to host: %s\\n\", err.Error())\n\t}\n\n\tpacket := new(snmpPacket)\n\n\tpacket.Community = x.Community\n\tpacket.Error = 0\n\tpacket.ErrorIndex = 0\n\tpacket.RequestType = GetRequest\n\tpacket.Version = 1 \/\/ version 2\n\tpacket.Variables = []snmpPDU{snmpPDU{Name: oid, Type: Null}}\n\n\tfBuf, err := packet.marshal()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Send the packet!\n\t_, err = conn.Write(fBuf)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error writing to socket: %s\\n\", err.Error())\n\t}\n\t\/\/ Try to read the response\n\tresp := make([]byte, 2048, 2048)\n\tn, err := conn.Read(resp)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading from UDP: %s\\n\", err.Error())\n\t}\n\n\tpdu, err := decode(resp[:n])\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to decode packet: %s\\n\", err.Error())\n\t} else {\n\t\tif len(pdu.VarBindList) < 1 {\n\t\t\treturn nil, fmt.Errorf(\"No responses received.\")\n\t\t} else {\n\t\t\treturn pdu.VarBindList[0], nil\n\t\t}\n\t}\n\n\treturn nil, nil\n}\n\ntype MessageType byte\n\nconst (\n\tSequence   MessageType = 0x30\n\tGetRequest MessageType = 0xa0\n\tSetRequest             = 0x1\n)\n\ntype SnmpVersion uint8\n\nconst (\n\tVersion1  SnmpVersion = 0x0\n\tVersion2c SnmpVersion = 0x1\n)\n\ntype snmpPacket struct {\n\tVersion     SnmpVersion\n\tCommunity   string\n\tRequestType MessageType\n\tRequestID   uint8\n\tError       uint8\n\tErrorIndex  uint8\n\tVariables   []snmpPDU\n}\n\ntype snmpPDU struct {\n\tName  string\n\tType  Asn1BER\n\tValue interface{}\n}\n\nfunc (packet *snmpPacket) marshal() ([]byte, error) {\n\t\/\/ Prepare the buffer to send\n\tbuffer := make([]byte, 0, 1024)\n\tbuf := bytes.NewBuffer(buffer)\n\n\t\/\/ Write the packet header (Message type 0x30) & Version = 2\n\tbuf.Write([]byte{byte(Sequence), 0, 2, 1, byte(packet.Version)})\n\n\t\/\/ Write Community\n\tbuf.Write([]byte{4, uint8(len(packet.Community))})\n\tbuf.WriteString(packet.Community)\n\n\t\/\/ Marshal the SNMP PDU\n\tsnmpPduBuffer := make([]byte, 0, 1024)\n\tsnmpPduBuf := bytes.NewBuffer(snmpPduBuffer)\n\n\tsnmpPduBuf.Write([]byte{byte(packet.RequestType), 0, 2, 1, packet.RequestID, 2, 1, packet.Error, 2, 1, packet.ErrorIndex, byte(Sequence), 0})\n\n\tpduLength := 0\n\tfor _, varlist := range packet.Variables {\n\t\tpdu, err := marshalPDU(&varlist)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpduLength += len(pdu)\n\t\tsnmpPduBuf.Write(pdu)\n\t}\n\n\tpduBytes := snmpPduBuf.Bytes()\n\t\/\/ Varbind list length\n\tpduBytes[12] = byte(pduLength)\n\t\/\/ SNMP PDU length (PDU header + varbind list length)\n\tpduBytes[1] = byte(pduLength + 11)\n\n\tbuf.Write(pduBytes)\n\n\t\/\/ Write the \n\t\/\/buf.Write([]byte{packet.RequestType, uint8(17 + len(mOid)), 2, 1, 1, 2, 1, 0, 2, 1, 0, 0x30, uint8(6 + len(mOid)), 0x30, uint8(4 + len(mOid)), 6, uint8(len(mOid))})\n\t\/\/buf.Write(mOid)\n\t\/\/buf.Write([]byte{5, 0})\n\n\tret := buf.Bytes()\n\n\t\/\/ Set the packet size\n\tret[1] = uint8(len(ret) - 2)\n\n\treturn ret, nil\n}\n\nfunc marshalPDU(pdu *snmpPDU) ([]byte, error) {\n\toid, err := marshalOID(pdu.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpduBuffer := make([]byte, 0, 1024)\n\tpduBuf := bytes.NewBuffer(pduBuffer)\n\n\t\/\/ Mashal the PDU type into the appropriate BER\n\tswitch pdu.Type {\n\tcase Null:\n\t\tpduBuf.Write([]byte{byte(Sequence), byte(len(oid) + 4)})\n\t\tpduBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})\n\t\tpduBuf.Write(oid)\n\t\tpduBuf.Write([]byte{Null, 0x00})\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unable to marshal PDU: uknown BER type %d\", pdu.Type)\n\t}\n\n\treturn pduBuf.Bytes(), nil\n}\n<commit_msg>Added support for timeout. Defaults to 10 seconds<commit_after>\/\/ Copyright 2012 Andreas Louca. All rights reserved.\n\/\/ Use of this source code is goverend by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage gosnmp\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype GoSNMP struct {\n\tTarget    string\n\tCommunity string\n\tVersion   SnmpVersion\n\tTimeout   time.Duration\n}\n\nfunc NewGoSNMP(target, community string, version SnmpVersion) *GoSNMP {\n\ts := &GoSNMP{target, community, version, 10 * time.Second}\n\n\treturn s\n}\n\nfunc marshalOID(oid string) ([]byte, error) {\n\tvar err error\n\n\t\/\/ Encode the oid\n\toid = strings.Trim(oid, \".\")\n\toidParts := strings.Split(oid, \".\")\n\toidBytes := make([]int, len(oidParts))\n\n\t\/\/ Convert the string OID to an array of integers\n\tfor i := 0; i < len(oidParts); i++ {\n\t\toidBytes[i], err = strconv.Atoi(oidParts[i])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to parse OID: %s\\n\", err.Error())\n\t\t}\n\t}\n\n\tmOid, err := marshalObjectIdentifier(oidBytes)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to marshal OID: %s\\n\", err.Error())\n\t}\n\n\treturn mOid, err\n}\n\nfunc (x *GoSNMP) Get(oid string) (*Variable, error) {\n\tvar err error\n\n\t\/\/ Open a UDP connection to the target\n\tconn, err := net.DialTimeout(\"udp\", fmt.Sprintf(\"%s:161\", x.Target), x.Timeout)\n\tdefer conn.Close()\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error establishing connection to host: %s\\n\", err.Error())\n\t}\n\n\t\/\/ Set timeouts on the connection\n\tdeadline := time.Now()\n\tconn.SetDeadline(deadline.Add(x.Timeout))\n\n\tpacket := new(snmpPacket)\n\n\tpacket.Community = x.Community\n\tpacket.Error = 0\n\tpacket.ErrorIndex = 0\n\tpacket.RequestType = GetRequest\n\tpacket.Version = 1 \/\/ version 2\n\tpacket.Variables = []snmpPDU{snmpPDU{Name: oid, Type: Null}}\n\n\tfBuf, err := packet.marshal()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Send the packet!\n\t_, err = conn.Write(fBuf)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error writing to socket: %s\\n\", err.Error())\n\t}\n\t\/\/ Try to read the response\n\tresp := make([]byte, 2048, 2048)\n\tn, err := conn.Read(resp)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading from UDP: %s\\n\", err.Error())\n\t}\n\n\tpdu, err := decode(resp[:n])\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to decode packet: %s\\n\", err.Error())\n\t} else {\n\t\tif len(pdu.VarBindList) < 1 {\n\t\t\treturn nil, fmt.Errorf(\"No responses received.\")\n\t\t} else {\n\t\t\treturn pdu.VarBindList[0], nil\n\t\t}\n\t}\n\n\treturn nil, nil\n}\n\ntype MessageType byte\n\nconst (\n\tSequence   MessageType = 0x30\n\tGetRequest MessageType = 0xa0\n\tSetRequest             = 0x1\n)\n\ntype SnmpVersion uint8\n\nconst (\n\tVersion1  SnmpVersion = 0x0\n\tVersion2c SnmpVersion = 0x1\n)\n\ntype snmpPacket struct {\n\tVersion     SnmpVersion\n\tCommunity   string\n\tRequestType MessageType\n\tRequestID   uint8\n\tError       uint8\n\tErrorIndex  uint8\n\tVariables   []snmpPDU\n}\n\ntype snmpPDU struct {\n\tName  string\n\tType  Asn1BER\n\tValue interface{}\n}\n\nfunc (packet *snmpPacket) marshal() ([]byte, error) {\n\t\/\/ Prepare the buffer to send\n\tbuffer := make([]byte, 0, 1024)\n\tbuf := bytes.NewBuffer(buffer)\n\n\t\/\/ Write the packet header (Message type 0x30) & Version = 2\n\tbuf.Write([]byte{byte(Sequence), 0, 2, 1, byte(packet.Version)})\n\n\t\/\/ Write Community\n\tbuf.Write([]byte{4, uint8(len(packet.Community))})\n\tbuf.WriteString(packet.Community)\n\n\t\/\/ Marshal the SNMP PDU\n\tsnmpPduBuffer := make([]byte, 0, 1024)\n\tsnmpPduBuf := bytes.NewBuffer(snmpPduBuffer)\n\n\tsnmpPduBuf.Write([]byte{byte(packet.RequestType), 0, 2, 1, packet.RequestID, 2, 1, packet.Error, 2, 1, packet.ErrorIndex, byte(Sequence), 0})\n\n\tpduLength := 0\n\tfor _, varlist := range packet.Variables {\n\t\tpdu, err := marshalPDU(&varlist)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpduLength += len(pdu)\n\t\tsnmpPduBuf.Write(pdu)\n\t}\n\n\tpduBytes := snmpPduBuf.Bytes()\n\t\/\/ Varbind list length\n\tpduBytes[12] = byte(pduLength)\n\t\/\/ SNMP PDU length (PDU header + varbind list length)\n\tpduBytes[1] = byte(pduLength + 11)\n\n\tbuf.Write(pduBytes)\n\n\t\/\/ Write the \n\t\/\/buf.Write([]byte{packet.RequestType, uint8(17 + len(mOid)), 2, 1, 1, 2, 1, 0, 2, 1, 0, 0x30, uint8(6 + len(mOid)), 0x30, uint8(4 + len(mOid)), 6, uint8(len(mOid))})\n\t\/\/buf.Write(mOid)\n\t\/\/buf.Write([]byte{5, 0})\n\n\tret := buf.Bytes()\n\n\t\/\/ Set the packet size\n\tret[1] = uint8(len(ret) - 2)\n\n\treturn ret, nil\n}\n\nfunc marshalPDU(pdu *snmpPDU) ([]byte, error) {\n\toid, err := marshalOID(pdu.Name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpduBuffer := make([]byte, 0, 1024)\n\tpduBuf := bytes.NewBuffer(pduBuffer)\n\n\t\/\/ Mashal the PDU type into the appropriate BER\n\tswitch pdu.Type {\n\tcase Null:\n\t\tpduBuf.Write([]byte{byte(Sequence), byte(len(oid) + 4)})\n\t\tpduBuf.Write([]byte{byte(ObjectIdentifier), byte(len(oid))})\n\t\tpduBuf.Write(oid)\n\t\tpduBuf.Write([]byte{Null, 0x00})\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unable to marshal PDU: uknown BER type %d\", pdu.Type)\n\t}\n\n\treturn pduBuf.Bytes(), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport  (\n        \"fmt\"\n        \"..\/go-todotxt\"\n        \"github.com\/spf13\/cobra\"\n        \"os\/user\"\n        \"strings\"\n        \"strconv\"\n        \"github.com\/rakyll\/globalconf\"\n        \"flag\"\n)\n\nfunc extendedLoader(filename string) (todotxt.TaskList, error) {\n        usr, err := user.Current()\n        if err != nil {\n                return nil, err\n        }\n\n        filename = strings.Replace(filename, \"~\", usr.HomeDir, -1)\n        tasks := todotxt.LoadTaskList(filename)\n\n        return tasks, nil\n}\n\nfunc main() {\n\n        conf, _ := globalconf.New(\"gotodo\")\n\n        var numtasks bool\n        var sortby string\n        var finished bool\n        var prettyformat string\n        var filename string\n\n        var flagFilename = flag.String(\"file\", \"\", \"Location of the todo.txt file.\")\n\n        var cmdList = &cobra.Command{\n            Use:   \"list [keyword]\",\n            Short: \"Lists tasks that contain keyword, if any\",\n            Long:  `List is the most basic command that is used for listing tasks.\n                    You can specify a keyword as well as other options.`,\n            Run: func(cmd *cobra.Command, args []string) {\n                tasks, err := extendedLoader(filename)\n                if err != nil {\n                        fmt.Println(err)\n                        return\n                }\n\n                if numtasks {\n                    fmt.Println(tasks.Len())\n                } else {\n                    tasks.Sort(sortby)\n\n                    var filteredTasks todotxt.TaskList\n                    for _, task := range tasks {\n                        if (!task.Finished() && !finished) ||\n                           (task.Finished() && finished) {\n                           filteredTasks = append(filteredTasks, task)\n                        }\n                    }\n\n                    for _, task := range filteredTasks {\n                            task.SetIdPaddingBy(tasks)\n                            fmt.Println(task.PrettyPrint(prettyformat))\n                    }\n                }\n            },\n        }\n        cmdList.Flags().BoolVarP(&numtasks, \"num-tasks\", \"n\", false,\n                                 \"Show the number of tasks\")\n        cmdList.Flags().BoolVarP(&finished, \"finished\", \"f\", false,\n                                 \"Show finished tasks\")\n        cmdList.Flags().StringVarP(&sortby, \"sort\", \"s\", \"prio\",\n                                   \"Sort tasks by parameter (prio|date|len|prio-rev|date-rev|len-rev|id|rand)\")\n        cmdList.Flags().StringVarP(&prettyformat, \"pretty\", \"\", \"%i %p %t\",\n                                   \"Pretty print tasks\")\n\n        var cmdAdd = &cobra.Command{\n            Use:   \"add [task]\",\n            Short: \"Adds a task to the todo list.\",\n            Long:  `Adds a task to the todo list.`,\n            Run: func(cmd *cobra.Command, args []string) {\n                tasks, err := extendedLoader(filename)\n                if err != nil {\n                        fmt.Println(err)\n                        return\n                }\n\n                task := strings.Join(args, \" \")\n                tasks.Add(task)\n\n                tasks.Save(filename)\n            },\n        }\n\n        var nofinishdate bool\n        var cmdDone = &cobra.Command{\n            Use:   \"done [taskid]\",\n            Short: \"Marks task as done.\",\n            Long:  `Marks task as done.`,\n            Run: func(cmd *cobra.Command, args []string) {\n                tasks, err := extendedLoader(filename)\n                if err != nil {\n                        fmt.Println(err)\n                        return\n                }\n\n                if len(args) < 1 {\n                        fmt.Println(\"So what needs to be done?\")\n                        return\n                }\n\n                taskid, err := strconv.Atoi(args[0])\n                if err != nil {\n                        fmt.Printf(\"Do you really consider that a number? %v\\n\", err)\n                        return\n                }\n\n                err = tasks.Done(taskid, !nofinishdate)\n                if err != nil {\n                        fmt.Printf(\"There was an error %v\\n\", err)\n                }\n\n                tasks.Save(filename)\n            },\n        }\n        cmdDone.Flags().BoolVarP(&nofinishdate, \"no-finish-date\", \"D\", false,\n                                        \"Do not mark finished tasks with date.\")\n\n        var cmdArchive = &cobra.Command{\n            Use:   \"archive [taskid]\",\n            Short: \"Archives task.\",\n            Long:  `Archives task.`,\n            Run: func(cmd *cobra.Command, args []string) {\n                tasks, err := extendedLoader(filename)\n                if err != nil {\n                        fmt.Println(err)\n                        return\n                }\n\n                if len(args) < 1 {\n                        fmt.Println(\"So what needs to be done?\")\n                        return\n                }\n\n                taskid, err := strconv.Atoi(args[0])\n                if err != nil {\n                        fmt.Printf(\"Do you really consider that a number? %v\\n\", err)\n                        return\n                }\n\n                fmt.Printf(\"Archiving task %v\\n\", taskid)\n\n                tasks.Save(filename)\n            },\n        }\n\n\n        var editprio string\n        var edittodo string\n        var cmdEdit = &cobra.Command{\n            Use:   \"edit [taskid]\",\n            Short: \"Edits given task.\",\n            Long:  `Edits given task.`,\n            Run: func(cmd *cobra.Command, args []string) {\n                tasks, err := extendedLoader(filename)\n                if err != nil {\n                        fmt.Println(err)\n                        return\n                }\n\n                if len(args) < 1 {\n                        fmt.Println(\"So what do you want to edit?\")\n                        return\n                }\n\n                taskid, err := strconv.Atoi(args[0])\n                if err != nil {\n                        fmt.Printf(\"Do you really consider that a number? %v\\n\", err)\n                        return\n                }\n\n                if len(editprio) > 0 {\n                        tasks[taskid].SetPriority(editprio[0])\n                        tasks[taskid].RebuildRawTodo()\n                }\n\n                if len(edittodo) > 0 {\n                        tasks[taskid].SetTodo(edittodo)\n                        tasks[taskid].RebuildRawTodo()\n                }\n\n                tasks.Save(filename)\n            },\n        }\n\n        cmdEdit.PersistentFlags().StringVarP(&editprio, \"priority\", \"p\", \"\",\n                                     \"Sets task's priority.\")\n        cmdEdit.PersistentFlags().StringVarP(&edittodo, \"todo\", \"t\", \"\",\n                                     \"Edit task's todo.\")\n\n        var GotodoCmd = &cobra.Command{\n            Use:   \"gotodo\",\n            Short: \"Gotodo is a go implementation of todo.txt.\",\n            Long: `A small, fast and fun implementation of todo.txt`,\n            Run: func(cmd *cobra.Command, args []string) {\n                cmdList.Run(cmd, nil)\n            },\n        }\n\n        GotodoCmd.PersistentFlags().StringVarP(&filename, \"filename\", \"f\", \"\",\n                                     \"Load tasks from this file.\")\n\n        conf.ParseAll()\n\n        \/\/ sadly, this is the best we can do right now\n        if filename == \"\" {\n                fmt.Println(*flagFilename)\n                if *flagFilename == \"\" {\n                        filename = \"todo.txt\"\n                } else {\n                        filename = *flagFilename\n                }\n        }\n\n        GotodoCmd.AddCommand(cmdList)\n        GotodoCmd.AddCommand(cmdAdd)\n        GotodoCmd.AddCommand(cmdDone)\n        GotodoCmd.AddCommand(cmdArchive)\n        GotodoCmd.AddCommand(cmdEdit)\n        GotodoCmd.Execute()\n}\n<commit_msg>cmdConfig<commit_after>package main\n\nimport  (\n        \"fmt\"\n        \"..\/go-todotxt\"\n        \"github.com\/spf13\/cobra\"\n        \"os\/user\"\n        \"strings\"\n        \"strconv\"\n        \"github.com\/rakyll\/globalconf\"\n        \"flag\"\n)\n\nfunc extendedLoader(filename string) (todotxt.TaskList, error) {\n        usr, err := user.Current()\n        if err != nil {\n                return nil, err\n        }\n\n        filename = strings.Replace(filename, \"~\", usr.HomeDir, -1)\n        tasks := todotxt.LoadTaskList(filename)\n\n        return tasks, nil\n}\n\nfunc main() {\n\n        conf, _ := globalconf.New(\"gotodo\")\n\n        var numtasks bool\n        var sortby string\n        var finished bool\n        var prettyformat string\n        var filename string\n\n        var flagFilename = flag.String(\"file\", \"\", \"Location of the todo.txt file.\")\n\n        var cmdConfig = &cobra.Command{\n            Use:   \"config [key] [value]\",\n            Short: \"Show and sets config values\",\n            Long:  `Config can be used to see and also set configuration variables.`,\n            Run: func(cmd *cobra.Command, args []string) {\n                fmt.Printf(\"%v\\n\", args)\n            },\n        }\n\n        var cmdList = &cobra.Command{\n            Use:   \"list [keyword]\",\n            Short: \"Lists tasks that contain keyword, if any\",\n            Long:  `List is the most basic command that is used for listing tasks.\n                    You can specify a keyword as well as other options.`,\n            Run: func(cmd *cobra.Command, args []string) {\n                tasks, err := extendedLoader(filename)\n                if err != nil {\n                        fmt.Println(err)\n                        return\n                }\n\n                if numtasks {\n                    fmt.Println(tasks.Len())\n                } else {\n                    tasks.Sort(sortby)\n\n                    var filteredTasks todotxt.TaskList\n                    for _, task := range tasks {\n                        if (!task.Finished() && !finished) ||\n                           (task.Finished() && finished) {\n                           filteredTasks = append(filteredTasks, task)\n                        }\n                    }\n\n                    for _, task := range filteredTasks {\n                            task.SetIdPaddingBy(tasks)\n                            fmt.Println(task.PrettyPrint(prettyformat))\n                    }\n                }\n            },\n        }\n        cmdList.Flags().BoolVarP(&numtasks, \"num-tasks\", \"n\", false,\n                                 \"Show the number of tasks\")\n        cmdList.Flags().BoolVarP(&finished, \"finished\", \"f\", false,\n                                 \"Show finished tasks\")\n        cmdList.Flags().StringVarP(&sortby, \"sort\", \"s\", \"prio\",\n                                   \"Sort tasks by parameter (prio|date|len|prio-rev|date-rev|len-rev|id|rand)\")\n        cmdList.Flags().StringVarP(&prettyformat, \"pretty\", \"\", \"%i %p %t\",\n                                   \"Pretty print tasks\")\n\n        var cmdAdd = &cobra.Command{\n            Use:   \"add [task]\",\n            Short: \"Adds a task to the todo list.\",\n            Long:  `Adds a task to the todo list.`,\n            Run: func(cmd *cobra.Command, args []string) {\n                tasks, err := extendedLoader(filename)\n                if err != nil {\n                        fmt.Println(err)\n                        return\n                }\n\n                task := strings.Join(args, \" \")\n                tasks.Add(task)\n\n                tasks.Save(filename)\n            },\n        }\n\n        var nofinishdate bool\n        var cmdDone = &cobra.Command{\n            Use:   \"done [taskid]\",\n            Short: \"Marks task as done.\",\n            Long:  `Marks task as done.`,\n            Run: func(cmd *cobra.Command, args []string) {\n                tasks, err := extendedLoader(filename)\n                if err != nil {\n                        fmt.Println(err)\n                        return\n                }\n\n                if len(args) < 1 {\n                        fmt.Println(\"So what needs to be done?\")\n                        return\n                }\n\n                taskid, err := strconv.Atoi(args[0])\n                if err != nil {\n                        fmt.Printf(\"Do you really consider that a number? %v\\n\", err)\n                        return\n                }\n\n                err = tasks.Done(taskid, !nofinishdate)\n                if err != nil {\n                        fmt.Printf(\"There was an error %v\\n\", err)\n                }\n\n                tasks.Save(filename)\n            },\n        }\n        cmdDone.Flags().BoolVarP(&nofinishdate, \"no-finish-date\", \"D\", false,\n                                        \"Do not mark finished tasks with date.\")\n\n        var cmdArchive = &cobra.Command{\n            Use:   \"archive [taskid]\",\n            Short: \"Archives task.\",\n            Long:  `Archives task.`,\n            Run: func(cmd *cobra.Command, args []string) {\n                tasks, err := extendedLoader(filename)\n                if err != nil {\n                        fmt.Println(err)\n                        return\n                }\n\n                if len(args) < 1 {\n                        fmt.Println(\"So what needs to be done?\")\n                        return\n                }\n\n                taskid, err := strconv.Atoi(args[0])\n                if err != nil {\n                        fmt.Printf(\"Do you really consider that a number? %v\\n\", err)\n                        return\n                }\n\n                fmt.Printf(\"Archiving task %v\\n\", taskid)\n\n                tasks.Save(filename)\n            },\n        }\n\n\n        var editprio string\n        var edittodo string\n        var cmdEdit = &cobra.Command{\n            Use:   \"edit [taskid]\",\n            Short: \"Edits given task.\",\n            Long:  `Edits given task.`,\n            Run: func(cmd *cobra.Command, args []string) {\n                tasks, err := extendedLoader(filename)\n                if err != nil {\n                        fmt.Println(err)\n                        return\n                }\n\n                if len(args) < 1 {\n                        fmt.Println(\"So what do you want to edit?\")\n                        return\n                }\n\n                taskid, err := strconv.Atoi(args[0])\n                if err != nil {\n                        fmt.Printf(\"Do you really consider that a number? %v\\n\", err)\n                        return\n                }\n\n                if len(editprio) > 0 {\n                        tasks[taskid].SetPriority(editprio[0])\n                        tasks[taskid].RebuildRawTodo()\n                }\n\n                if len(edittodo) > 0 {\n                        tasks[taskid].SetTodo(edittodo)\n                        tasks[taskid].RebuildRawTodo()\n                }\n\n                tasks.Save(filename)\n            },\n        }\n\n        cmdEdit.PersistentFlags().StringVarP(&editprio, \"priority\", \"p\", \"\",\n                                     \"Sets task's priority.\")\n        cmdEdit.PersistentFlags().StringVarP(&edittodo, \"todo\", \"t\", \"\",\n                                     \"Edit task's todo.\")\n\n        var GotodoCmd = &cobra.Command{\n            Use:   \"gotodo\",\n            Short: \"Gotodo is a go implementation of todo.txt.\",\n            Long: `A small, fast and fun implementation of todo.txt`,\n            Run: func(cmd *cobra.Command, args []string) {\n                cmdList.Run(cmd, nil)\n            },\n        }\n\n        GotodoCmd.PersistentFlags().StringVarP(&filename, \"filename\", \"f\", \"\",\n                                     \"Load tasks from this file.\")\n\n        conf.ParseAll()\n\n        \/\/ sadly, this is the best we can do right now\n        if filename == \"\" {\n                fmt.Println(*flagFilename)\n                if *flagFilename == \"\" {\n                        filename = \"todo.txt\"\n                } else {\n                        filename = *flagFilename\n                }\n        }\n\n        GotodoCmd.AddCommand(cmdList)\n        GotodoCmd.AddCommand(cmdAdd)\n        GotodoCmd.AddCommand(cmdDone)\n        GotodoCmd.AddCommand(cmdArchive)\n        GotodoCmd.AddCommand(cmdEdit)\n        GotodoCmd.AddCommand(cmdConfig)\n        GotodoCmd.Execute()\n}\n<|endoftext|>"}
{"text":"<commit_before>package daemon\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/docker\/docker\/testutil\/environment\"\n)\n\n\/\/ Option is used to configure a daemon.\ntype Option func(*Daemon)\n\n\/\/ WithDefaultCgroupNamespaceMode sets the default cgroup namespace mode for the daemon\nfunc WithDefaultCgroupNamespaceMode(mode string) Option {\n\treturn func(d *Daemon) {\n\t\td.defaultCgroupNamespaceMode = mode\n\t}\n}\n\n\/\/ WithTestLogger causes the daemon to log certain actions to the provided test.\nfunc WithTestLogger(t testing.TB) func(*Daemon) {\n\treturn func(d *Daemon) {\n\t\td.log = t\n\t}\n}\n\n\/\/ WithExperimental sets the daemon in experimental mode\nfunc WithExperimental(d *Daemon) {\n\td.experimental = true\n}\n\n\/\/ WithInit sets the daemon init\nfunc WithInit(d *Daemon) {\n\td.init = true\n}\n\n\/\/ WithDockerdBinary sets the dockerd binary to the specified one\nfunc WithDockerdBinary(dockerdBinary string) Option {\n\treturn func(d *Daemon) {\n\t\td.dockerdBinary = dockerdBinary\n\t}\n}\n\n\/\/ WithSwarmPort sets the swarm port to use for swarm mode\nfunc WithSwarmPort(port int) Option {\n\treturn func(d *Daemon) {\n\t\td.SwarmPort = port\n\t}\n}\n\n\/\/ WithSwarmListenAddr sets the swarm listen addr to use for swarm mode\nfunc WithSwarmListenAddr(listenAddr string) Option {\n\treturn func(d *Daemon) {\n\t\td.swarmListenAddr = listenAddr\n\t}\n}\n\n\/\/ WithSwarmDefaultAddrPool sets the swarm default address pool to use for swarm mode\nfunc WithSwarmDefaultAddrPool(defaultAddrPool []string) Option {\n\treturn func(d *Daemon) {\n\t\td.DefaultAddrPool = defaultAddrPool\n\t}\n}\n\n\/\/ WithSwarmDefaultAddrPoolSubnetSize sets the subnet length mask of swarm default address pool to use for swarm mode\nfunc WithSwarmDefaultAddrPoolSubnetSize(subnetSize uint32) Option {\n\treturn func(d *Daemon) {\n\t\td.SubnetSize = subnetSize\n\t}\n}\n\n\/\/ WithSwarmDataPathPort sets the  swarm datapath port to use for swarm mode\nfunc WithSwarmDataPathPort(datapathPort uint32) Option {\n\treturn func(d *Daemon) {\n\t\td.DataPathPort = datapathPort\n\t}\n}\n\n\/\/ WithEnvironment sets options from testutil\/environment.Execution struct\nfunc WithEnvironment(e environment.Execution) Option {\n\treturn func(d *Daemon) {\n\t\tif e.DaemonInfo.ExperimentalBuild {\n\t\t\td.experimental = true\n\t\t}\n\t}\n}\n\n\/\/ WithStorageDriver sets store driver option\nfunc WithStorageDriver(driver string) Option {\n\treturn func(d *Daemon) {\n\t\td.storageDriver = driver\n\t}\n}\n<commit_msg>testutil: update WithTestLogger to use daemon.Option as return type<commit_after>package daemon\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/docker\/docker\/testutil\/environment\"\n)\n\n\/\/ Option is used to configure a daemon.\ntype Option func(*Daemon)\n\n\/\/ WithDefaultCgroupNamespaceMode sets the default cgroup namespace mode for the daemon\nfunc WithDefaultCgroupNamespaceMode(mode string) Option {\n\treturn func(d *Daemon) {\n\t\td.defaultCgroupNamespaceMode = mode\n\t}\n}\n\n\/\/ WithTestLogger causes the daemon to log certain actions to the provided test.\nfunc WithTestLogger(t testing.TB) Option {\n\treturn func(d *Daemon) {\n\t\td.log = t\n\t}\n}\n\n\/\/ WithExperimental sets the daemon in experimental mode\nfunc WithExperimental(d *Daemon) {\n\td.experimental = true\n}\n\n\/\/ WithInit sets the daemon init\nfunc WithInit(d *Daemon) {\n\td.init = true\n}\n\n\/\/ WithDockerdBinary sets the dockerd binary to the specified one\nfunc WithDockerdBinary(dockerdBinary string) Option {\n\treturn func(d *Daemon) {\n\t\td.dockerdBinary = dockerdBinary\n\t}\n}\n\n\/\/ WithSwarmPort sets the swarm port to use for swarm mode\nfunc WithSwarmPort(port int) Option {\n\treturn func(d *Daemon) {\n\t\td.SwarmPort = port\n\t}\n}\n\n\/\/ WithSwarmListenAddr sets the swarm listen addr to use for swarm mode\nfunc WithSwarmListenAddr(listenAddr string) Option {\n\treturn func(d *Daemon) {\n\t\td.swarmListenAddr = listenAddr\n\t}\n}\n\n\/\/ WithSwarmDefaultAddrPool sets the swarm default address pool to use for swarm mode\nfunc WithSwarmDefaultAddrPool(defaultAddrPool []string) Option {\n\treturn func(d *Daemon) {\n\t\td.DefaultAddrPool = defaultAddrPool\n\t}\n}\n\n\/\/ WithSwarmDefaultAddrPoolSubnetSize sets the subnet length mask of swarm default address pool to use for swarm mode\nfunc WithSwarmDefaultAddrPoolSubnetSize(subnetSize uint32) Option {\n\treturn func(d *Daemon) {\n\t\td.SubnetSize = subnetSize\n\t}\n}\n\n\/\/ WithSwarmDataPathPort sets the  swarm datapath port to use for swarm mode\nfunc WithSwarmDataPathPort(datapathPort uint32) Option {\n\treturn func(d *Daemon) {\n\t\td.DataPathPort = datapathPort\n\t}\n}\n\n\/\/ WithEnvironment sets options from testutil\/environment.Execution struct\nfunc WithEnvironment(e environment.Execution) Option {\n\treturn func(d *Daemon) {\n\t\tif e.DaemonInfo.ExperimentalBuild {\n\t\t\td.experimental = true\n\t\t}\n\t}\n}\n\n\/\/ WithStorageDriver sets store driver option\nfunc WithStorageDriver(driver string) Option {\n\treturn func(d *Daemon) {\n\t\td.storageDriver = driver\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package thesaurus\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n)\n\n\/\/ func main() {\n\/\/ \tapi, err := New()\n\/\/ \tif err != nil {\n\/\/ \t\tlog.Fatal(err)\n\/\/ \t}\n\/\/ \t\/\/ map[verb:map[syn:[accredit account ascribe assign attribute bank calculate impute rely swear trust] ant:[debit]] noun:map[syn:[recognition credit entry deferred payment course credit citation cite acknowledgment reference mention quotation accomplishment accounting entry achievement annotation approval assets attainment commendation entry ledger entry notation note payment title] ant:[cash debit]]]\n\/\/ \trs, err := api.GetSynonyms(\"health\")\n\/\/ \tif err != nil {\n\/\/ \t\tlog.Fatal(err)\n\/\/ \t}\n\/\/ \tfmt.Println(rs)\n\/\/ }\n\n\/\/ API implements Merriam-Webster API client.\ntype API struct {\n\tkey string\n\t*http.Client\n}\n\n\/\/ New returns a new API with default http.Client.\nfunc New() (*API, error) {\n\takey := os.Getenv(\"THESAURUS_KEY\")\n\tif akey == \"\" {\n\t\treturn nil, errors.New(\"no environment variable THESAURUS_KEY\")\n\t}\n\tapi := API{\n\t\tkey:    akey,\n\t\tClient: http.DefaultClient,\n\t}\n\treturn &api, nil\n}\n\n\/\/ NewCustom returns a new API with customized http.Client.\nfunc NewCustom(client *http.Client) (*API, error) {\n\takey := os.Getenv(\"THESAURUS_KEY\")\n\tif akey == \"\" {\n\t\treturn nil, errors.New(\"no environment variable set for dictionary\")\n\t}\n\tapi := API{\n\t\tkey:    akey,\n\t\tClient: client,\n\t}\n\treturn &api, nil\n}\n\nconst endpoint = \"http:\/\/words.bighugelabs.com\/api\/2\/%s\/%s\/json\"\n\n\/\/ GetSynonyms returns the synonyms of an input word.\nfunc (a *API) GetSynonyms(word string) ([]string, error) {\n\tnword := strings.TrimSpace(word)\n\tnword = strings.ToLower(nword)\n\turl := fmt.Sprintf(endpoint, a.key, nword)\n\tresp, err := a.Client.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\t\/\/ body, err := ioutil.ReadAll(resp.Body)\n\t\/\/ fmt.Println(string(body))\n\tresult := map[string]map[string][]string{}\n\terr = json.NewDecoder(resp.Body).Decode(&result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsmap := make(map[string]bool)\n\tfor _, val := range result {\n\t\tfor k, v := range val {\n\t\t\tif k == \"syn\" {\n\t\t\t\tfor _, elem := range v {\n\t\t\t\t\tsmap[elem] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tslice := []string{}\n\tfor key := range smap {\n\t\tslice = append(slice, key)\n\t}\n\tsort.Strings(slice)\n\treturn slice, nil\n}\n<commit_msg>Update logging<commit_after>package thesaurus\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n)\n\n\/\/ func main() {\n\/\/ \tapi, err := New()\n\/\/ \tif err != nil {\n\/\/ \t\tlog.Fatal(err)\n\/\/ \t}\n\/\/ \t\/\/ map[verb:map[syn:[accredit account ascribe assign attribute bank calculate impute rely swear trust] ant:[debit]] noun:map[syn:[recognition credit entry deferred payment course credit citation cite acknowledgment reference mention quotation accomplishment accounting entry achievement annotation approval assets attainment commendation entry ledger entry notation note payment title] ant:[cash debit]]]\n\/\/ \trs, err := api.GetSynonyms(\"health\")\n\/\/ \tif err != nil {\n\/\/ \t\tlog.Fatal(err)\n\/\/ \t}\n\/\/ \tfmt.Println(rs)\n\/\/ }\n\n\/\/ API implements Merriam-Webster API client.\ntype API struct {\n\tkey string\n\t*http.Client\n}\n\n\/\/ New returns a new API with default http.Client.\nfunc New() (*API, error) {\n\takey := os.Getenv(\"THESAURUS_KEY\")\n\tif akey == \"\" {\n\t\treturn nil, errors.New(\"no environment variable THESAURUS_KEY\")\n\t}\n\tapi := API{\n\t\tkey:    akey,\n\t\tClient: http.DefaultClient,\n\t}\n\treturn &api, nil\n}\n\n\/\/ NewCustom returns a new API with customized http.Client.\nfunc NewCustom(client *http.Client) (*API, error) {\n\takey := os.Getenv(\"THESAURUS_KEY\")\n\tif akey == \"\" {\n\t\treturn nil, errors.New(\"no environment variable THESAURUS_KEY\")\n\t}\n\tapi := API{\n\t\tkey:    akey,\n\t\tClient: client,\n\t}\n\treturn &api, nil\n}\n\nconst endpoint = \"http:\/\/words.bighugelabs.com\/api\/2\/%s\/%s\/json\"\n\n\/\/ GetSynonyms returns the synonyms of an input word.\nfunc (a *API) GetSynonyms(word string) ([]string, error) {\n\tnword := strings.TrimSpace(word)\n\tnword = strings.ToLower(nword)\n\turl := fmt.Sprintf(endpoint, a.key, nword)\n\tresp, err := a.Client.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\t\/\/ body, err := ioutil.ReadAll(resp.Body)\n\t\/\/ fmt.Println(string(body))\n\tresult := map[string]map[string][]string{}\n\terr = json.NewDecoder(resp.Body).Decode(&result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsmap := make(map[string]bool)\n\tfor _, val := range result {\n\t\tfor k, v := range val {\n\t\t\tif k == \"syn\" {\n\t\t\t\tfor _, elem := range v {\n\t\t\t\t\tsmap[elem] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tslice := []string{}\n\tfor key := range smap {\n\t\tslice = append(slice, key)\n\t}\n\tsort.Strings(slice)\n\treturn slice, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage featuretests\n\nimport (\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\n\t\"github.com\/juju\/cmd\"\n\t\"github.com\/juju\/errors\"\n\tjc \"github.com\/juju\/testing\/checkers\"\n\tgc \"gopkg.in\/check.v1\"\n\tgoyaml \"gopkg.in\/yaml.v1\"\n\n\t\"github.com\/juju\/juju\/api\"\n\t\"github.com\/juju\/juju\/api\/environmentmanager\"\n\t\"github.com\/juju\/juju\/cmd\/envcmd\"\n\t\"github.com\/juju\/juju\/cmd\/juju\/system\"\n\t\"github.com\/juju\/juju\/environs\/configstore\"\n\t\"github.com\/juju\/juju\/feature\"\n\t\"github.com\/juju\/juju\/juju\"\n\tjujutesting \"github.com\/juju\/juju\/juju\/testing\"\n\t\"github.com\/juju\/juju\/testing\"\n\t\"github.com\/juju\/juju\/testing\/factory\"\n)\n\ntype cmdSystemSuite struct {\n\tjujutesting.JujuConnSuite\n}\n\nfunc (s *cmdSystemSuite) SetUpTest(c *gc.C) {\n\ts.JujuConnSuite.SetUpTest(c)\n\ts.SetFeatureFlags(feature.JES)\n}\n\nfunc (s *cmdSystemSuite) run(c *gc.C, args ...string) *cmd.Context {\n\tcommand := system.NewSuperCommand()\n\tcontext, err := testing.RunCommand(c, command, args...)\n\tc.Assert(err, jc.ErrorIsNil)\n\treturn context\n}\n\nfunc (s *cmdSystemSuite) createEnv(c *gc.C, envname string, isServer bool) {\n\tconn, err := juju.NewAPIState(s.AdminUserTag(c), s.Environ, api.DialOpts{})\n\tc.Assert(err, jc.ErrorIsNil)\n\ts.AddCleanup(func(*gc.C) { conn.Close() })\n\ts.SetFeatureFlags(feature.JES)\n\tenvManager := environmentmanager.NewClient(conn)\n\t_, err = envManager.CreateEnvironment(s.AdminUserTag(c).Id(), nil, map[string]interface{}{\n\t\t\"name\":            envname,\n\t\t\"authorized-keys\": \"ssh-key\",\n\t\t\"state-server\":    isServer,\n\t})\n\tc.Assert(err, jc.ErrorIsNil)\n}\n\nfunc (s *cmdSystemSuite) TestSystemListCommand(c *gc.C) {\n\tcontext := s.run(c, \"list\")\n\tc.Assert(testing.Stdout(context), gc.Equals, \"dummyenv\\n\")\n}\n\nfunc (s *cmdSystemSuite) TestSystemEnvironmentsCommand(c *gc.C) {\n\tc.Assert(envcmd.WriteCurrentSystem(\"dummyenv\"), jc.ErrorIsNil)\n\ts.createEnv(c, \"new-env\", false)\n\tcontext := s.run(c, \"environments\")\n\tc.Assert(testing.Stdout(context), gc.Equals, \"\"+\n\t\t\"NAME      OWNER              LAST CONNECTION\\n\"+\n\t\t\"dummyenv  dummy-admin@local  just now\\n\"+\n\t\t\"new-env   dummy-admin@local  never connected\\n\"+\n\t\t\"\\n\")\n}\n\nfunc (s *cmdSystemSuite) TestSystemLoginCommand(c *gc.C) {\n\tuser := s.Factory.MakeUser(c, &factory.UserParams{\n\t\tNoEnvUser: true,\n\t\tPassword:  \"super-secret\",\n\t})\n\tapiInfo := s.APIInfo(c)\n\tserverFile := envcmd.ServerFile{\n\t\tAddresses: apiInfo.Addrs,\n\t\tCACert:    apiInfo.CACert,\n\t\tUsername:  user.Name(),\n\t\tPassword:  \"super-secret\",\n\t}\n\tserverFilePath := filepath.Join(c.MkDir(), \"server.yaml\")\n\tcontent, err := goyaml.Marshal(serverFile)\n\tc.Assert(err, jc.ErrorIsNil)\n\terr = ioutil.WriteFile(serverFilePath, []byte(content), 0644)\n\tc.Assert(err, jc.ErrorIsNil)\n\n\ts.run(c, \"login\", \"--server\", serverFilePath, \"just-a-system\")\n\n\t\/\/ Make sure that the saved server details are sufficient to connect\n\t\/\/ to the api server.\n\tapi, err := juju.NewAPIFromName(\"just-a-system\")\n\tc.Assert(err, jc.ErrorIsNil)\n\tapi.Close()\n}\n\nfunc (s *cmdSystemSuite) TestCreateEnvironment(c *gc.C) {\n\tc.Assert(envcmd.WriteCurrentSystem(\"dummyenv\"), jc.ErrorIsNil)\n\t\/\/ The JujuConnSuite doesn't set up an ssh key in the fake home dir,\n\t\/\/ so fake one on the command line.  The dummy provider also expects\n\t\/\/ a config value for 'state-server'.\n\tcontext := s.run(c, \"create-environment\", \"new-env\", \"authorized-keys=fake-key\", \"state-server=false\")\n\tc.Check(testing.Stdout(context), gc.Equals, \"\")\n\tc.Check(testing.Stderr(context), gc.Equals, `\ncreated environment \"new-env\"\ndummyenv (system) -> new-env\n`[1:])\n\n\t\/\/ Make sure that the saved server details are sufficient to connect\n\t\/\/ to the api server.\n\tapi, err := juju.NewAPIFromName(\"new-env\")\n\tc.Assert(err, jc.ErrorIsNil)\n\tapi.Close()\n}\n\nfunc (s *cmdSystemSuite) TestSystemDestroy(c *gc.C) {\n\tst := s.Factory.MakeEnvironment(c, &factory.EnvParams{\n\t\tName:        \"just-a-system\",\n\t\tConfigAttrs: testing.Attrs{\"state-server\": true},\n\t})\n\n\tports, err := st.APIHostPorts()\n\tc.Assert(err, jc.ErrorIsNil)\n\tinfo := s.ConfigStore.CreateInfo(\"just-a-system\")\n\tendpoint := configstore.APIEndpoint{\n\t\tCACert:      testing.CACert,\n\t\tEnvironUUID: st.EnvironUUID(),\n\t\tAddresses:   []string{ports[0][0].String()},\n\t}\n\tinfo.SetAPIEndpoint(endpoint)\n\terr = info.Write()\n\tc.Assert(err, jc.ErrorIsNil)\n\n\tst.Close()\n\ts.run(c, \"destroy\", \"just-a-system\", \"-y\")\n\n\tstore, err := configstore.Default()\n\t_, err = store.ReadInfo(\"just-a-system\")\n\tc.Assert(err, jc.Satisfies, errors.IsNotFound)\n}\n<commit_msg>Fix the feature test.<commit_after>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage featuretests\n\nimport (\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\n\t\"github.com\/juju\/cmd\"\n\t\"github.com\/juju\/errors\"\n\tjc \"github.com\/juju\/testing\/checkers\"\n\tgc \"gopkg.in\/check.v1\"\n\tgoyaml \"gopkg.in\/yaml.v1\"\n\n\t\"github.com\/juju\/juju\/api\"\n\t\"github.com\/juju\/juju\/api\/environmentmanager\"\n\t\"github.com\/juju\/juju\/cmd\/envcmd\"\n\t\"github.com\/juju\/juju\/cmd\/juju\/system\"\n\t\"github.com\/juju\/juju\/environs\/configstore\"\n\t\"github.com\/juju\/juju\/feature\"\n\t\"github.com\/juju\/juju\/juju\"\n\tjujutesting \"github.com\/juju\/juju\/juju\/testing\"\n\t\"github.com\/juju\/juju\/testing\"\n\t\"github.com\/juju\/juju\/testing\/factory\"\n)\n\ntype cmdSystemSuite struct {\n\tjujutesting.JujuConnSuite\n}\n\nfunc (s *cmdSystemSuite) SetUpTest(c *gc.C) {\n\ts.SetInitialFeatureFlags(feature.JES)\n\ts.JujuConnSuite.SetUpTest(c)\n}\n\nfunc (s *cmdSystemSuite) run(c *gc.C, args ...string) *cmd.Context {\n\tcommand := system.NewSuperCommand()\n\tcontext, err := testing.RunCommand(c, command, args...)\n\tc.Assert(err, jc.ErrorIsNil)\n\treturn context\n}\n\nfunc (s *cmdSystemSuite) createEnv(c *gc.C, envname string, isServer bool) {\n\tconn, err := juju.NewAPIState(s.AdminUserTag(c), s.Environ, api.DialOpts{})\n\tc.Assert(err, jc.ErrorIsNil)\n\ts.AddCleanup(func(*gc.C) { conn.Close() })\n\tenvManager := environmentmanager.NewClient(conn)\n\t_, err = envManager.CreateEnvironment(s.AdminUserTag(c).Id(), nil, map[string]interface{}{\n\t\t\"name\":            envname,\n\t\t\"authorized-keys\": \"ssh-key\",\n\t\t\"state-server\":    isServer,\n\t})\n\tc.Assert(err, jc.ErrorIsNil)\n}\n\nfunc (s *cmdSystemSuite) TestSystemListCommand(c *gc.C) {\n\tcontext := s.run(c, \"list\")\n\tc.Assert(testing.Stdout(context), gc.Equals, \"dummyenv\\n\")\n}\n\nfunc (s *cmdSystemSuite) TestSystemEnvironmentsCommand(c *gc.C) {\n\tc.Assert(envcmd.WriteCurrentSystem(\"dummyenv\"), jc.ErrorIsNil)\n\ts.createEnv(c, \"new-env\", false)\n\tcontext := s.run(c, \"environments\")\n\tc.Assert(testing.Stdout(context), gc.Equals, \"\"+\n\t\t\"NAME      OWNER              LAST CONNECTION\\n\"+\n\t\t\"dummyenv  dummy-admin@local  just now\\n\"+\n\t\t\"new-env   dummy-admin@local  never connected\\n\"+\n\t\t\"\\n\")\n}\n\nfunc (s *cmdSystemSuite) TestSystemLoginCommand(c *gc.C) {\n\tuser := s.Factory.MakeUser(c, &factory.UserParams{\n\t\tNoEnvUser: true,\n\t\tPassword:  \"super-secret\",\n\t})\n\tapiInfo := s.APIInfo(c)\n\tserverFile := envcmd.ServerFile{\n\t\tAddresses: apiInfo.Addrs,\n\t\tCACert:    apiInfo.CACert,\n\t\tUsername:  user.Name(),\n\t\tPassword:  \"super-secret\",\n\t}\n\tserverFilePath := filepath.Join(c.MkDir(), \"server.yaml\")\n\tcontent, err := goyaml.Marshal(serverFile)\n\tc.Assert(err, jc.ErrorIsNil)\n\terr = ioutil.WriteFile(serverFilePath, []byte(content), 0644)\n\tc.Assert(err, jc.ErrorIsNil)\n\n\ts.run(c, \"login\", \"--server\", serverFilePath, \"just-a-system\")\n\n\t\/\/ Make sure that the saved server details are sufficient to connect\n\t\/\/ to the api server.\n\tapi, err := juju.NewAPIFromName(\"just-a-system\")\n\tc.Assert(err, jc.ErrorIsNil)\n\tapi.Close()\n}\n\nfunc (s *cmdSystemSuite) TestCreateEnvironment(c *gc.C) {\n\tc.Assert(envcmd.WriteCurrentSystem(\"dummyenv\"), jc.ErrorIsNil)\n\t\/\/ The JujuConnSuite doesn't set up an ssh key in the fake home dir,\n\t\/\/ so fake one on the command line.  The dummy provider also expects\n\t\/\/ a config value for 'state-server'.\n\tcontext := s.run(c, \"create-environment\", \"new-env\", \"authorized-keys=fake-key\", \"state-server=false\")\n\tc.Check(testing.Stdout(context), gc.Equals, \"\")\n\tc.Check(testing.Stderr(context), gc.Equals, `\ncreated environment \"new-env\"\ndummyenv (system) -> new-env\n`[1:])\n\n\t\/\/ Make sure that the saved server details are sufficient to connect\n\t\/\/ to the api server.\n\tapi, err := juju.NewAPIFromName(\"new-env\")\n\tc.Assert(err, jc.ErrorIsNil)\n\tapi.Close()\n}\n\nfunc (s *cmdSystemSuite) TestSystemDestroy(c *gc.C) {\n\tst := s.Factory.MakeEnvironment(c, &factory.EnvParams{\n\t\tName:        \"just-a-system\",\n\t\tConfigAttrs: testing.Attrs{\"state-server\": true},\n\t})\n\n\tst.Close()\n\ts.run(c, \"destroy\", \"dummyenv\", \"-y\", \"--destroy-all-environments\")\n\n\tstore, err := configstore.Default()\n\t_, err = store.ReadInfo(\"dummyenv\")\n\tc.Assert(err, jc.Satisfies, errors.IsNotFound)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2016  Arista Networks, Inc.\n\/\/ Use of this source code is governed by the Apache License 2.0\n\/\/ that can be found in the COPYING file.\n\npackage producer\n\nimport (\n\t\"expvar\"\n\t\"fmt\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/aristanetworks\/glog\"\n\t\"github.com\/aristanetworks\/goarista\/kafka\"\n\t\"github.com\/aristanetworks\/goarista\/kafka\/openconfig\"\n\t\"github.com\/aristanetworks\/goarista\/monitor\"\n\t\"github.com\/golang\/protobuf\/proto\"\n)\n\n\/\/ counter counts the number Sysdb clients we have, and is used to guarantee that we\n\/\/ always have a unique name exported to expvar\nvar counter uint32\n\n\/\/ MessageEncoder defines the encoding from topic, key, proto.Message to sarama.ProducerMessage\ntype MessageEncoder func(string, sarama.Encoder, string, proto.Message) (*sarama.ProducerMessage,\n\terror)\n\n\/\/ Producer forwards messages recvd on a channel to kafka.\ntype Producer interface {\n\tRun()\n\tWrite(proto.Message)\n\tStop()\n}\n\ntype producer struct {\n\tnotifsChan    chan proto.Message\n\tkafkaProducer sarama.AsyncProducer\n\ttopic         string\n\tkey           sarama.Encoder\n\tdataset       string\n\tencoder       MessageEncoder\n\tdone          chan struct{}\n\twg            sync.WaitGroup\n\n\t\/\/ Used for monitoring\n\thistogram    *monitor.Histogram\n\tnumSuccesses monitor.Uint\n\tnumFailures  monitor.Uint\n}\n\n\/\/ New creates new Kafka producer\nfunc New(topic string, notifsChan chan proto.Message, client sarama.Client, key sarama.Encoder,\n\tdataset string, encoder MessageEncoder) (Producer, error) {\n\tif notifsChan == nil {\n\t\tnotifsChan = make(chan proto.Message)\n\t}\n\tkafkaProducer, err := sarama.NewAsyncProducerFromClient(client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Setup monitoring structures\n\thistName := \"kafkaProducerHistogram\"\n\tstatsName := \"messagesStats\"\n\tif id := atomic.AddUint32(&counter, 1); id > 1 {\n\t\thistName = fmt.Sprintf(\"%s-%d\", histName, id)\n\t\tstatsName = fmt.Sprintf(\"%s-%d\", statsName, id)\n\t}\n\thist := monitor.NewHistogram(histName, 32, 0.3, 1000, 0)\n\tstatsMap := expvar.NewMap(statsName)\n\n\tp := &producer{\n\t\tnotifsChan:    notifsChan,\n\t\tkafkaProducer: kafkaProducer,\n\t\ttopic:         topic,\n\t\tkey:           key,\n\t\tdataset:       dataset,\n\t\tencoder:       encoder,\n\t\tdone:          make(chan struct{}),\n\t\twg:            sync.WaitGroup{},\n\t\thistogram:     hist,\n\t}\n\n\tstatsMap.Set(\"successes\", &p.numSuccesses)\n\tstatsMap.Set(\"failures\", &p.numFailures)\n\n\treturn p, nil\n}\n\nfunc (p *producer) Run() {\n\tp.wg.Add(2)\n\tgo p.handleSuccesses()\n\tgo p.handleErrors()\n\n\tp.wg.Add(1)\n\tdefer p.wg.Done()\n\tfor {\n\t\tselect {\n\t\tcase batch, open := <-p.notifsChan:\n\t\t\tif !open {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr := p.produceNotification(batch)\n\t\t\tif err != nil {\n\t\t\t\tif _, ok := err.(openconfig.UnhandledSubscribeResponseError); !ok {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-p.done:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (p *producer) Write(m proto.Message) {\n\tp.notifsChan <- m\n}\n\nfunc (p *producer) Stop() {\n\tclose(p.done)\n\tp.kafkaProducer.Close()\n\tp.wg.Wait()\n}\n\nfunc (p *producer) produceNotification(protoMessage proto.Message) error {\n\tmessage, err := p.encoder(p.topic, p.key, p.dataset, protoMessage)\n\tif err != nil {\n\t\treturn err\n\t}\n\tselect {\n\tcase p.kafkaProducer.Input() <- message:\n\t\treturn nil\n\tcase <-p.done:\n\t\treturn nil\n\t}\n}\n\n\/\/ handleSuccesses reads from the producer's successes channel and collects some\n\/\/ information for monitoring\nfunc (p *producer) handleSuccesses() {\n\tdefer p.wg.Done()\n\tfor msg := range p.kafkaProducer.Successes() {\n\t\tmetadata := msg.Metadata.(kafka.Metadata)\n\t\t\/\/ TODO: Add a monotonic clock source when one becomes available\n\t\tp.histogram.UpdateLatencyValues(metadata.StartTime, time.Now())\n\t\tp.numSuccesses.Add(uint64(metadata.NumMessages))\n\t}\n}\n\n\/\/ handleErrors reads from the producer's errors channel and collects some information\n\/\/ for monitoring\nfunc (p *producer) handleErrors() {\n\tdefer p.wg.Done()\n\tfor msg := range p.kafkaProducer.Errors() {\n\t\tmetadata := msg.Msg.Metadata.(kafka.Metadata)\n\t\t\/\/ TODO: Add a monotonic clock source when one becomes available\n\t\tp.histogram.UpdateLatencyValues(metadata.StartTime, time.Now())\n\t\tglog.Errorf(\"Kafka Producer error: %s\", msg.Error())\n\t\tp.numFailures.Add(uint64(metadata.NumMessages))\n\t}\n}\n<commit_msg>kafka\/producer: log produced messages<commit_after>\/\/ Copyright (C) 2016  Arista Networks, Inc.\n\/\/ Use of this source code is governed by the Apache License 2.0\n\/\/ that can be found in the COPYING file.\n\npackage producer\n\nimport (\n\t\"expvar\"\n\t\"fmt\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/aristanetworks\/glog\"\n\t\"github.com\/aristanetworks\/goarista\/kafka\"\n\t\"github.com\/aristanetworks\/goarista\/kafka\/openconfig\"\n\t\"github.com\/aristanetworks\/goarista\/monitor\"\n\t\"github.com\/golang\/protobuf\/proto\"\n)\n\n\/\/ counter counts the number Sysdb clients we have, and is used to guarantee that we\n\/\/ always have a unique name exported to expvar\nvar counter uint32\n\n\/\/ MessageEncoder defines the encoding from topic, key, proto.Message to sarama.ProducerMessage\ntype MessageEncoder func(string, sarama.Encoder, string, proto.Message) (*sarama.ProducerMessage,\n\terror)\n\n\/\/ Producer forwards messages recvd on a channel to kafka.\ntype Producer interface {\n\tRun()\n\tWrite(proto.Message)\n\tStop()\n}\n\ntype producer struct {\n\tnotifsChan    chan proto.Message\n\tkafkaProducer sarama.AsyncProducer\n\ttopic         string\n\tkey           sarama.Encoder\n\tdataset       string\n\tencoder       MessageEncoder\n\tdone          chan struct{}\n\twg            sync.WaitGroup\n\n\t\/\/ Used for monitoring\n\thistogram    *monitor.Histogram\n\tnumSuccesses monitor.Uint\n\tnumFailures  monitor.Uint\n}\n\n\/\/ New creates new Kafka producer\nfunc New(topic string, notifsChan chan proto.Message, client sarama.Client, key sarama.Encoder,\n\tdataset string, encoder MessageEncoder) (Producer, error) {\n\tif notifsChan == nil {\n\t\tnotifsChan = make(chan proto.Message)\n\t}\n\tkafkaProducer, err := sarama.NewAsyncProducerFromClient(client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Setup monitoring structures\n\thistName := \"kafkaProducerHistogram\"\n\tstatsName := \"messagesStats\"\n\tif id := atomic.AddUint32(&counter, 1); id > 1 {\n\t\thistName = fmt.Sprintf(\"%s-%d\", histName, id)\n\t\tstatsName = fmt.Sprintf(\"%s-%d\", statsName, id)\n\t}\n\thist := monitor.NewHistogram(histName, 32, 0.3, 1000, 0)\n\tstatsMap := expvar.NewMap(statsName)\n\n\tp := &producer{\n\t\tnotifsChan:    notifsChan,\n\t\tkafkaProducer: kafkaProducer,\n\t\ttopic:         topic,\n\t\tkey:           key,\n\t\tdataset:       dataset,\n\t\tencoder:       encoder,\n\t\tdone:          make(chan struct{}),\n\t\twg:            sync.WaitGroup{},\n\t\thistogram:     hist,\n\t}\n\n\tstatsMap.Set(\"successes\", &p.numSuccesses)\n\tstatsMap.Set(\"failures\", &p.numFailures)\n\n\treturn p, nil\n}\n\nfunc (p *producer) Run() {\n\tp.wg.Add(2)\n\tgo p.handleSuccesses()\n\tgo p.handleErrors()\n\n\tp.wg.Add(1)\n\tdefer p.wg.Done()\n\tfor {\n\t\tselect {\n\t\tcase batch, open := <-p.notifsChan:\n\t\t\tif !open {\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr := p.produceNotification(batch)\n\t\t\tif err != nil {\n\t\t\t\tif _, ok := err.(openconfig.UnhandledSubscribeResponseError); !ok {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-p.done:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (p *producer) Write(m proto.Message) {\n\tp.notifsChan <- m\n}\n\nfunc (p *producer) Stop() {\n\tclose(p.done)\n\tp.kafkaProducer.Close()\n\tp.wg.Wait()\n}\n\nfunc (p *producer) produceNotification(protoMessage proto.Message) error {\n\tmessage, err := p.encoder(p.topic, p.key, p.dataset, protoMessage)\n\tif err != nil {\n\t\treturn err\n\t}\n\tselect {\n\tcase p.kafkaProducer.Input() <- message:\n\t\tglog.V(9).Infof(\"Message produced to Kafka: %s\", message)\n\t\treturn nil\n\tcase <-p.done:\n\t\treturn nil\n\t}\n}\n\n\/\/ handleSuccesses reads from the producer's successes channel and collects some\n\/\/ information for monitoring\nfunc (p *producer) handleSuccesses() {\n\tdefer p.wg.Done()\n\tfor msg := range p.kafkaProducer.Successes() {\n\t\tmetadata := msg.Metadata.(kafka.Metadata)\n\t\t\/\/ TODO: Add a monotonic clock source when one becomes available\n\t\tp.histogram.UpdateLatencyValues(metadata.StartTime, time.Now())\n\t\tp.numSuccesses.Add(uint64(metadata.NumMessages))\n\t}\n}\n\n\/\/ handleErrors reads from the producer's errors channel and collects some information\n\/\/ for monitoring\nfunc (p *producer) handleErrors() {\n\tdefer p.wg.Done()\n\tfor msg := range p.kafkaProducer.Errors() {\n\t\tmetadata := msg.Msg.Metadata.(kafka.Metadata)\n\t\t\/\/ TODO: Add a monotonic clock source when one becomes available\n\t\tp.histogram.UpdateLatencyValues(metadata.StartTime, time.Now())\n\t\tglog.Errorf(\"Kafka Producer error: %s\", msg.Error())\n\t\tp.numFailures.Add(uint64(metadata.NumMessages))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/UniversityRadioYork\/baps3-go\"\n)\n\n\/\/ TestHasFeature tests whether serviceState.hasFeature seems to work.\nfunc TestHasFeature(t *testing.T) {\n\tcases := []struct {\n\t\tfeat    Feature\n\t\tpresent bool\n\t}{\n\t\t\/\/ We check the presence of some features and the absence of\n\t\t\/\/ others.  This is a shuffled, but even distribution of both.\n\t\t{FtFileLoad, true},\n\t\t{FtPlayStop, true},\n\t\t{FtSeek, false},\n\t\t{FtEnd, true},\n\t\t{FtTimeReport, false},\n\t\t{FtPlaylist, true},\n\t\t{FtPlaylistAutoAdvance, false},\n\t\t{FtPlaylistTextItems, false},\n\t}\n\n\t\/\/ This is for collecting the features we do want to enable.\n\tpresents := []Feature{}\n\n\t\/\/ All features should be absent on a new serviceState.\n\tsrv := initServiceState()\n\n\tfor _, c := range cases {\n\t\tif srv.hasFeature(c.feat) {\n\t\t\tt.Errorf(\"initial serviceState shouldn't have feature %q\", c.feat)\n\t\t}\n\t\tif c.present {\n\t\t\tpresents = append(presents, c.feat)\n\t\t}\n\t}\n\n\t\/\/ Now set the features we want.\n\tmsg := baps3.NewMessage(baps3.RsFeatures)\n\tfor _, p := range presents {\n\t\tmsg.AddArg(p.String())\n\t}\n\n\tif err := srv.update(*msg); err != nil {\n\t\tt.Errorf(\"error when setting features: %s\", err)\n\t}\n\n\t\/\/ Now check if hasFeature works (!)\n\tfor _, d := range cases {\n\t\thas := srv.hasFeature(d.feat)\n\t\tif has && !d.present {\n\t\t\tt.Errorf(\"service should not have feature %q, but does\", d.feat)\n\t\t} else if !has && d.present {\n\t\t\tt.Errorf(\"service should have feature %q, but does not\", d.feat)\n\t\t}\n\t}\n}\n\n\/\/ TestServiceStateUpdateFail tests the behaviour of a serviceState when it\n\/\/ receives a malformed message.\nfunc TestServiceStateUpdateFail(t *testing.T) {\n\t\/\/ TODO(CaptainHayashi): maybe test what the error actually is\n\tcases := []struct {\n\t\tmsg    *baps3.Message\n\t\thasErr bool\n\t}{\n\t\t\/\/ Request where response was expected\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RqLoad).AddArg(\"\/quux\"),\n\t\t\tfalse, \/\/ TODO(CaptainHayashi): error on requests?\n\t\t},\n\t\t\/\/ Too few arguments\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsFile),\n\t\t\ttrue,\n\t\t},\n\t\t\/\/ Too many arguments\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsTime).AddArg(\"3003\").AddArg(\"lol\"),\n\t\t\ttrue,\n\t\t},\n\t\t\/\/ Unknown request (should be ignored)\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsUnknown).AddArg(\"heh\"),\n\t\t\tfalse,\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\terr := initServiceState().update(*c.msg)\n\t\tif c.hasErr && (err == nil) {\n\t\t\tt.Errorf(\"expected %q to produce error, none produced\", c.msg)\n\t\t} else if !c.hasErr && (err != nil) {\n\t\t\tt.Errorf(\"expected %q not to produce error, one produced\", c.msg)\n\t\t}\n\t}\n}\n\n\/\/ TestServiceStateUpdate tests the updating of a serviceState by messages.\nfunc TestServiceStateUpdate(t *testing.T) {\n\t\/\/ TODO(CaptainHayashi): test failure states as well as successes\n\n\tcases := []struct {\n\t\tmsg *baps3.Message\n\t\tcmp func(*serviceState) error\n\t}{\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsFeatures).AddArg(\"End\").AddArg(\"FileLoad\"),\n\t\t\tfunc(s *serviceState) (err error) {\n\t\t\t\t_, endIn := s.features[FtEnd]\n\t\t\t\t_, flIn := s.features[FtFileLoad]\n\n\t\t\t\tif !endIn || !flIn {\n\t\t\t\t\terr = fmt.Errorf(\n\t\t\t\t\t\t\"features should contain End and Fileload, got %d\",\n\t\t\t\t\t\ts.features,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsFile).AddArg(\"\/home\/foo\/bar.mp3\"),\n\t\t\tfunc(s *serviceState) (err error) {\n\t\t\t\tif s.file != \"\/home\/foo\/bar.mp3\" {\n\t\t\t\t\terr = fmt.Errorf(\n\t\t\t\t\t\t\"file should be %d, got %d\",\n\t\t\t\t\t\t\"\/home\/foo\/bar.mp3\",\n\t\t\t\t\t\ts.file,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsState).AddArg(\"Ejected\"),\n\t\t\tfunc(s *serviceState) (err error) {\n\t\t\t\tif s.state != \"Ejected\" {\n\t\t\t\t\terr = fmt.Errorf(\n\t\t\t\t\t\t\"state should be %d, got %d\",\n\t\t\t\t\t\t\"Ejected\",\n\t\t\t\t\t\ts.state,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsTime).AddArg(\"1337000000\"),\n\t\t\tfunc(s *serviceState) (err error) {\n\t\t\t\tif s.time.Seconds() != 1337 {\n\t\t\t\t\terr = fmt.Errorf(\n\t\t\t\t\t\t\"time should be %i secs, got %i\",\n\t\t\t\t\t\t1337,\n\t\t\t\t\t\ts.time,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tst := initServiceState()\n\t\tif err := st.update(*c.msg); err != nil {\n\t\t\tt.Errorf(\"error when sending %d: %s\", c.msg, err)\n\t\t}\n\t\tif err := c.cmp(st); err != nil {\n\t\t\tt.Errorf(\"sent %d, but got error: %s\", c.msg, err)\n\t\t}\n\t}\n\n}\n<commit_msg>Fix test for moved features stuff<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/UniversityRadioYork\/baps3-go\"\n)\n\n\/\/ TestHasFeature tests whether serviceState.hasFeature seems to work.\nfunc TestHasFeature(t *testing.T) {\n\tcases := []struct {\n\t\tfeat    baps3.Feature\n\t\tpresent bool\n\t}{\n\t\t\/\/ We check the presence of some features and the absence of\n\t\t\/\/ others.  This is a shuffled, but even distribution of both.\n\t\t{baps3.FtFileLoad, true},\n\t\t{baps3.FtPlayStop, true},\n\t\t{baps3.FtSeek, false},\n\t\t{baps3.FtEnd, true},\n\t\t{baps3.FtTimeReport, false},\n\t\t{baps3.FtPlaylist, true},\n\t\t{baps3.FtPlaylistAutoAdvance, false},\n\t\t{baps3.FtPlaylistTextItems, false},\n\t}\n\n\t\/\/ This is for collecting the features we do want to enable.\n\tpresents := []baps3.Feature{}\n\n\t\/\/ All features should be absent on a new serviceState.\n\tsrv := initServiceState()\n\n\tfor _, c := range cases {\n\t\tif srv.hasFeature(c.feat) {\n\t\t\tt.Errorf(\"initial serviceState shouldn't have feature %q\", c.feat)\n\t\t}\n\t\tif c.present {\n\t\t\tpresents = append(presents, c.feat)\n\t\t}\n\t}\n\n\t\/\/ Now set the features we want.\n\tmsg := baps3.NewMessage(baps3.RsFeatures)\n\tfor _, p := range presents {\n\t\tmsg.AddArg(p.String())\n\t}\n\n\tif err := srv.update(*msg); err != nil {\n\t\tt.Errorf(\"error when setting features: %s\", err)\n\t}\n\n\t\/\/ Now check if hasFeature works (!)\n\tfor _, d := range cases {\n\t\thas := srv.hasFeature(d.feat)\n\t\tif has && !d.present {\n\t\t\tt.Errorf(\"service should not have feature %q, but does\", d.feat)\n\t\t} else if !has && d.present {\n\t\t\tt.Errorf(\"service should have feature %q, but does not\", d.feat)\n\t\t}\n\t}\n}\n\n\/\/ TestServiceStateUpdateFail tests the behaviour of a serviceState when it\n\/\/ receives a malformed message.\nfunc TestServiceStateUpdateFail(t *testing.T) {\n\t\/\/ TODO(CaptainHayashi): maybe test what the error actually is\n\tcases := []struct {\n\t\tmsg    *baps3.Message\n\t\thasErr bool\n\t}{\n\t\t\/\/ Request where response was expected\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RqLoad).AddArg(\"\/quux\"),\n\t\t\tfalse, \/\/ TODO(CaptainHayashi): error on requests?\n\t\t},\n\t\t\/\/ Too few arguments\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsFile),\n\t\t\ttrue,\n\t\t},\n\t\t\/\/ Too many arguments\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsTime).AddArg(\"3003\").AddArg(\"lol\"),\n\t\t\ttrue,\n\t\t},\n\t\t\/\/ Unknown request (should be ignored)\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsUnknown).AddArg(\"heh\"),\n\t\t\tfalse,\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\terr := initServiceState().update(*c.msg)\n\t\tif c.hasErr && (err == nil) {\n\t\t\tt.Errorf(\"expected %q to produce error, none produced\", c.msg)\n\t\t} else if !c.hasErr && (err != nil) {\n\t\t\tt.Errorf(\"expected %q not to produce error, one produced\", c.msg)\n\t\t}\n\t}\n}\n\n\/\/ TestServiceStateUpdate tests the updating of a serviceState by messages.\nfunc TestServiceStateUpdate(t *testing.T) {\n\t\/\/ TODO(CaptainHayashi): test failure states as well as successes\n\n\tcases := []struct {\n\t\tmsg *baps3.Message\n\t\tcmp func(*serviceState) error\n\t}{\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsFeatures).AddArg(\"End\").AddArg(\"FileLoad\"),\n\t\t\tfunc(s *serviceState) (err error) {\n\t\t\t\t_, endIn := s.features[baps3.FtEnd]\n\t\t\t\t_, flIn := s.features[baps3.FtFileLoad]\n\n\t\t\t\tif !endIn || !flIn {\n\t\t\t\t\terr = fmt.Errorf(\n\t\t\t\t\t\t\"features should contain End and Fileload, got %d\",\n\t\t\t\t\t\ts.features,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsFile).AddArg(\"\/home\/foo\/bar.mp3\"),\n\t\t\tfunc(s *serviceState) (err error) {\n\t\t\t\tif s.file != \"\/home\/foo\/bar.mp3\" {\n\t\t\t\t\terr = fmt.Errorf(\n\t\t\t\t\t\t\"file should be %d, got %d\",\n\t\t\t\t\t\t\"\/home\/foo\/bar.mp3\",\n\t\t\t\t\t\ts.file,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsState).AddArg(\"Ejected\"),\n\t\t\tfunc(s *serviceState) (err error) {\n\t\t\t\tif s.state != \"Ejected\" {\n\t\t\t\t\terr = fmt.Errorf(\n\t\t\t\t\t\t\"state should be %d, got %d\",\n\t\t\t\t\t\t\"Ejected\",\n\t\t\t\t\t\ts.state,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tbaps3.NewMessage(baps3.RsTime).AddArg(\"1337000000\"),\n\t\t\tfunc(s *serviceState) (err error) {\n\t\t\t\tif s.time.Seconds() != 1337 {\n\t\t\t\t\terr = fmt.Errorf(\n\t\t\t\t\t\t\"time should be %i secs, got %i\",\n\t\t\t\t\t\t1337,\n\t\t\t\t\t\ts.time,\n\t\t\t\t\t)\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tst := initServiceState()\n\t\tif err := st.update(*c.msg); err != nil {\n\t\t\tt.Errorf(\"error when sending %d: %s\", c.msg, err)\n\t\t}\n\t\tif err := c.cmp(st); err != nil {\n\t\t\tt.Errorf(\"sent %d, but got error: %s\", c.msg, err)\n\t\t}\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package asm\n\nimport (\n\t\"io\"\n\t\"io\/ioutil\"\n\n\t\"github.com\/vbatts\/tar-split\/archive\/tar\"\n\t\"github.com\/vbatts\/tar-split\/tar\/storage\"\n)\n\n\/\/ NewInputTarStream wraps the Reader stream of a tar archive and provides a\n\/\/ Reader stream of the same.\n\/\/\n\/\/ In the middle it will pack the segments and file metadata to storage.Packer\n\/\/ `p`.\n\/\/\n\/\/ The the storage.FilePutter is where payload of files in the stream are\n\/\/ stashed. If this stashing is not needed, you can provide a nil\n\/\/ storage.FilePutter. Since the checksumming is still needed, then a default\n\/\/ of NewDiscardFilePutter will be used internally\nfunc NewInputTarStream(r io.Reader, p storage.Packer, fp storage.FilePutter) (io.Reader, error) {\n\t\/\/ What to do here... folks will want their own access to the Reader that is\n\t\/\/ their tar archive stream, but we'll need that same stream to use our\n\t\/\/ forked 'archive\/tar'.\n\t\/\/ Perhaps do an io.TeeReader that hands back an io.Reader for them to read\n\t\/\/ from, and we'll MITM the stream to store metadata.\n\t\/\/ We'll need a storage.FilePutter too ...\n\n\t\/\/ Another concern, whether to do any storage.FilePutter operations, such that we\n\t\/\/ don't extract any amount of the archive. But then again, we're not making\n\t\/\/ files\/directories, hardlinks, etc. Just writing the io to the storage.FilePutter.\n\t\/\/ Perhaps we have a DiscardFilePutter that is a bit bucket.\n\n\t\/\/ we'll return the pipe reader, since TeeReader does not buffer and will\n\t\/\/ only read what the outputRdr Read's. Since Tar archives have padding on\n\t\/\/ the end, we want to be the one reading the padding, even if the user's\n\t\/\/ `archive\/tar` doesn't care.\n\tpR, pW := io.Pipe()\n\toutputRdr := io.TeeReader(r, pW)\n\n\t\/\/ we need a putter that will generate the crc64 sums of file payloads\n\tif fp == nil {\n\t\tfp = storage.NewDiscardFilePutter()\n\t}\n\n\tgo func() {\n\t\ttr := tar.NewReader(outputRdr)\n\t\ttr.RawAccounting = true\n\t\tfor {\n\t\t\thdr, err := tr.Next()\n\t\t\tif err != nil {\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\tpW.CloseWithError(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t\/\/ even when an EOF is reached, there is often 1024 null bytes on\n\t\t\t\t\/\/ the end of an archive. Collect them too.\n\t\t\t\t_, err := p.AddEntry(storage.Entry{\n\t\t\t\t\tType:    storage.SegmentType,\n\t\t\t\t\tPayload: tr.RawBytes(),\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tpW.CloseWithError(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tbreak \/\/ not return. We need the end of the reader.\n\t\t\t}\n\t\t\tif hdr == nil {\n\t\t\t\tbreak \/\/ not return. We need the end of the reader.\n\t\t\t}\n\n\t\t\tif _, err := p.AddEntry(storage.Entry{\n\t\t\t\tType:    storage.SegmentType,\n\t\t\t\tPayload: tr.RawBytes(),\n\t\t\t}); err != nil {\n\t\t\t\tpW.CloseWithError(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar csum []byte\n\t\t\tif hdr.Size > 0 {\n\t\t\t\tvar err error\n\t\t\t\t_, csum, err = fp.Put(hdr.Name, tr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpW.CloseWithError(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ File entries added, regardless of size\n\t\t\t_, err = p.AddEntry(storage.Entry{\n\t\t\t\tType:    storage.FileType,\n\t\t\t\tName:    hdr.Name,\n\t\t\t\tSize:    hdr.Size,\n\t\t\t\tPayload: csum,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tpW.CloseWithError(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif b := tr.RawBytes(); len(b) > 0 {\n\t\t\t\t_, err = p.AddEntry(storage.Entry{\n\t\t\t\t\tType:    storage.SegmentType,\n\t\t\t\t\tPayload: b,\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tpW.CloseWithError(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ it is allowable, and not uncommon that there is further padding on the\n\t\t\/\/ end of an archive, apart from the expected 1024 null bytes.\n\t\tremainder, err := ioutil.ReadAll(outputRdr)\n\t\tif err != nil && err != io.EOF {\n\t\t\tpW.CloseWithError(err)\n\t\t\treturn\n\t\t}\n\t\t_, err = p.AddEntry(storage.Entry{\n\t\t\tType:    storage.SegmentType,\n\t\t\tPayload: remainder,\n\t\t})\n\t\tif err != nil {\n\t\t\tpW.CloseWithError(err)\n\t\t\treturn\n\t\t}\n\t\tpW.Close()\n\t}()\n\n\treturn pR, nil\n}\n<commit_msg>tar\/asm: check length before adding an entry<commit_after>package asm\n\nimport (\n\t\"io\"\n\t\"io\/ioutil\"\n\n\t\"github.com\/vbatts\/tar-split\/archive\/tar\"\n\t\"github.com\/vbatts\/tar-split\/tar\/storage\"\n)\n\n\/\/ NewInputTarStream wraps the Reader stream of a tar archive and provides a\n\/\/ Reader stream of the same.\n\/\/\n\/\/ In the middle it will pack the segments and file metadata to storage.Packer\n\/\/ `p`.\n\/\/\n\/\/ The the storage.FilePutter is where payload of files in the stream are\n\/\/ stashed. If this stashing is not needed, you can provide a nil\n\/\/ storage.FilePutter. Since the checksumming is still needed, then a default\n\/\/ of NewDiscardFilePutter will be used internally\nfunc NewInputTarStream(r io.Reader, p storage.Packer, fp storage.FilePutter) (io.Reader, error) {\n\t\/\/ What to do here... folks will want their own access to the Reader that is\n\t\/\/ their tar archive stream, but we'll need that same stream to use our\n\t\/\/ forked 'archive\/tar'.\n\t\/\/ Perhaps do an io.TeeReader that hands back an io.Reader for them to read\n\t\/\/ from, and we'll MITM the stream to store metadata.\n\t\/\/ We'll need a storage.FilePutter too ...\n\n\t\/\/ Another concern, whether to do any storage.FilePutter operations, such that we\n\t\/\/ don't extract any amount of the archive. But then again, we're not making\n\t\/\/ files\/directories, hardlinks, etc. Just writing the io to the storage.FilePutter.\n\t\/\/ Perhaps we have a DiscardFilePutter that is a bit bucket.\n\n\t\/\/ we'll return the pipe reader, since TeeReader does not buffer and will\n\t\/\/ only read what the outputRdr Read's. Since Tar archives have padding on\n\t\/\/ the end, we want to be the one reading the padding, even if the user's\n\t\/\/ `archive\/tar` doesn't care.\n\tpR, pW := io.Pipe()\n\toutputRdr := io.TeeReader(r, pW)\n\n\t\/\/ we need a putter that will generate the crc64 sums of file payloads\n\tif fp == nil {\n\t\tfp = storage.NewDiscardFilePutter()\n\t}\n\n\tgo func() {\n\t\ttr := tar.NewReader(outputRdr)\n\t\ttr.RawAccounting = true\n\t\tfor {\n\t\t\thdr, err := tr.Next()\n\t\t\tif err != nil {\n\t\t\t\tif err != io.EOF {\n\t\t\t\t\tpW.CloseWithError(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t\/\/ even when an EOF is reached, there is often 1024 null bytes on\n\t\t\t\t\/\/ the end of an archive. Collect them too.\n\t\t\t\tif b := tr.RawBytes(); len(b) > 0 {\n\t\t\t\t\t_, err := p.AddEntry(storage.Entry{\n\t\t\t\t\t\tType:    storage.SegmentType,\n\t\t\t\t\t\tPayload: b,\n\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tpW.CloseWithError(err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak \/\/ not return. We need the end of the reader.\n\t\t\t}\n\t\t\tif hdr == nil {\n\t\t\t\tbreak \/\/ not return. We need the end of the reader.\n\t\t\t}\n\n\t\t\tif b := tr.RawBytes(); len(b) > 0 {\n\t\t\t\t_, err := p.AddEntry(storage.Entry{\n\t\t\t\t\tType:    storage.SegmentType,\n\t\t\t\t\tPayload: b,\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tpW.CloseWithError(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar csum []byte\n\t\t\tif hdr.Size > 0 {\n\t\t\t\tvar err error\n\t\t\t\t_, csum, err = fp.Put(hdr.Name, tr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpW.CloseWithError(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ File entries added, regardless of size\n\t\t\t_, err = p.AddEntry(storage.Entry{\n\t\t\t\tType:    storage.FileType,\n\t\t\t\tName:    hdr.Name,\n\t\t\t\tSize:    hdr.Size,\n\t\t\t\tPayload: csum,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tpW.CloseWithError(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif b := tr.RawBytes(); len(b) > 0 {\n\t\t\t\t_, err = p.AddEntry(storage.Entry{\n\t\t\t\t\tType:    storage.SegmentType,\n\t\t\t\t\tPayload: b,\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tpW.CloseWithError(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ it is allowable, and not uncommon that there is further padding on the\n\t\t\/\/ end of an archive, apart from the expected 1024 null bytes.\n\t\tremainder, err := ioutil.ReadAll(outputRdr)\n\t\tif err != nil && err != io.EOF {\n\t\t\tpW.CloseWithError(err)\n\t\t\treturn\n\t\t}\n\t\t_, err = p.AddEntry(storage.Entry{\n\t\t\tType:    storage.SegmentType,\n\t\t\tPayload: remainder,\n\t\t})\n\t\tif err != nil {\n\t\t\tpW.CloseWithError(err)\n\t\t\treturn\n\t\t}\n\t\tpW.Close()\n\t}()\n\n\treturn pR, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\tzmq \"github.com\/pebbe\/zmq4\"\n\t\"flag\"\n\t\"os\"\n\t\"fmt\"\n)\n\nfunc Exitf(code int, format string, v... interface{}) {\n\tfmt.Fprintf(os.Stderr, \"Fatal: \")\n\tfmt.Fprintf(os.Stderr, format, v...)\n\tos.Exit(code)\n}\n\nfunc main() {\n\tblock := flag.Bool(\"block\", true, \"Use a blocking zmq_recv.\")\n\ttext := flag.Bool(\"text\", false, \"Read messages as strings.\")\n\tmultipart := flag.Bool(\"multipart\", false, \"Read multipart messages and print the parts individually.\")\n\tflag.Usage = func() {\n\t\tExitf(2, \"Usage of %s:\\n\", os.Args[0])\n\t\tExitf(2, \"%s <zmq_endpoint> [opts]\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\tflag.Parse()\n\tif flag.NArg() < 1 {\n\t\tflag.Usage()\n\t}\n\turi := flag.Arg(0)\n\tsock, err := zmq.NewSocket(zmq.SUB)\n\tif err != nil {\n\t\tExitf(2, \"Could not create ZMQ socket: %v\", err)\n\t}\n\terr = sock.Connect(uri)\n\tif err != nil {\n\t\tExitf(2, \"Could not connect to endpoint %s: %v\", uri, err)\n\t}\n\terr = sock.SetSubscribe(\"\")\n\tif err != nil {\n\t\tExitf(2, \"Could not subscribe: %v\", err)\n\t}\n\tvar recvFlag zmq.Flag\n\tif *block {\n\t\trecvFlag = 0\n\t} else {\n\t\trecvFlag = zmq.DONTWAIT\n\t}\n\tfor {\n\t\tif *multipart && *text {\n\t\t\tmsg, err := sock.RecvMessage(recvFlag)\n\t\t\tif err != nil {\n\t\t\t\tExitf(2, \"Could not receive bytes: %v\", err)\n\t\t\t}\n\t\t\tfor _, part := range msg {\n\t\t\t\tfmt.Println(part)\n\t\t\t}\n\t\t} else if *multipart {\n\t\t\tmsg, err := sock.RecvMessageBytes(recvFlag)\n\t\t\tif err != nil {\n\t\t\t\tExitf(2, \"Could not receive bytes: %v\", err)\n\t\t\t}\n\t\t\tfor _, part := range msg {\n\t\t\t\tos.Stdout.Write(part)\n\t\t\t}\n\t\t} else if *text {\n\t\t\tmsg, err := sock.Recv(recvFlag)\n\t\t\tif err != nil {\n\t\t\t\tExitf(2, \"Could not receive bytes: %v\", err)\n\t\t\t}\n\t\t\tfmt.Println(msg)\n\t\t}\n\t}\n}\n<commit_msg>Refactor<commit_after>package main\n\nimport (\n\tzmq \"github.com\/pebbe\/zmq4\"\n\t\"flag\"\n\t\"os\"\n\t\"fmt\"\n)\n\nfunc Exitf(code int, format string, v... interface{}) {\n\tfmt.Fprintf(os.Stderr, \"Fatal: \")\n\tfmt.Fprintf(os.Stderr, format, v...)\n\tos.Exit(code)\n}\n\nfunc main() {\n\tblock := flag.Bool(\"block\", true, \"Use a blocking zmq_recv.\")\n\ttext := flag.Bool(\"text\", false, \"Read messages as strings.\")\n\tmultipart := flag.Bool(\"multipart\", false, \"Read multipart messages and print the parts individually.\")\n\tflag.Usage = func() {\n\t\tExitf(2, \"Usage of %s:\\n\", os.Args[0])\n\t\tExitf(2, \"%s <zmq_endpoint> [opts]\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\tflag.Parse()\n\tif flag.NArg() < 1 {\n\t\tflag.Usage()\n\t}\n\turi := flag.Arg(0)\n\tsock, err := zmq.NewSocket(zmq.SUB)\n\tif err != nil {\n\t\tExitf(2, \"Could not create ZMQ socket: %v\", err)\n\t}\n\terr = sock.Connect(uri)\n\tif err != nil {\n\t\tExitf(2, \"Could not connect to endpoint %s: %v\", uri, err)\n\t}\n\terr = sock.SetSubscribe(\"\")\n\tif err != nil {\n\t\tExitf(2, \"Could not subscribe: %v\", err)\n\t}\n\tvar recvFlag zmq.Flag\n\tif *block {\n\t\trecvFlag = 0\n\t} else {\n\t\trecvFlag = zmq.DONTWAIT\n\t}\n\tvar strMsg string\n\tvar strMsgMulti []string\n\tvar rawMsg []byte\n\tvar rawMsgMulti [][]byte\n\tfor {\n\t\tswitch {\n\t\tcase *multipart && *text:\n\t\t\tstrMsgMulti, err = sock.RecvMessage(recvFlag)\n\t\tcase *multipart:\n\t\t\trawMsgMulti, err = sock.RecvMessageBytes(recvFlag)\n\t\tcase *text:\n\t\t\tstrMsg, err = sock.Recv(recvFlag)\n\t\tdefault:\n\t\t\trawMsg, err = sock.RecvBytes(recvFlag)\n\t\t}\n\t\tif err != nil {\n\t\t\tExitf(2, \"Could not receive bytes: %v\", err)\n\t\t}\n\t\tswitch {\n\t\tcase *multipart && *text:\n\t\t\tfor _, part := range strMsgMulti {\n\t\t\t\tfmt.Println(part)\n\t\t\t}\n\t\tcase *multipart:\n\t\t\tfor _, part := range rawMsgMulti {\n\t\t\t\tos.Stdout.Write(part)\n\t\t\t}\n\t\tcase *text:\n\t\t\tfmt.Println(strMsg)\n\t\tdefault:\n\t\t\tos.Stdout.Write(rawMsg)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\n\t\"github.com\/mozilla\/tls-observatory\/config\"\n\t\"github.com\/mozilla\/tls-observatory\/connection\"\n\tpg \"github.com\/mozilla\/tls-observatory\/database\"\n\t\"github.com\/mozilla\/tls-observatory\/logger\"\n\t\"github.com\/mozilla\/tls-observatory\/worker\"\n)\n\nvar db *pg.DB\nvar log = logger.GetLogger()\n\nvar activeScanners int = 0\n\nfunc main() {\n\tvar (\n\t\tcfgFile, cipherscan string\n\t\tdebug               bool\n\t)\n\tflag.StringVar(&cfgFile, \"c\", \"\/etc\/tls-observatory\/scanner.cfg\", \"Configuration file\")\n\tflag.StringVar(&cipherscan, \"b\", \"\/opt\/cipherscan\/cipherscan\", \"Cipherscan binary location\")\n\tflag.BoolVar(&debug, \"debug\", false, \"Set debug logging\")\n\tflag.Parse()\n\n\tif debug {\n\t\tlogger.SetLevelToDebug()\n\t}\n\n\tconf, err := config.Load(cfgFile)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Failed to load configuration: %v\", err))\n\t}\n\tif !conf.General.Enable && os.Getenv(\"TLSOBS_SCANNER_ENABLE\") != \"on\" {\n\t\tlog.Fatal(\"Scanner is disabled in configuration\")\n\t}\n\n\t_, err = os.Stat(cipherscan)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Error(\"Could not locate cipherscan executable. TLS connection capabilities will not be available.\")\n\t}\n\n\t\/\/ increase the n\n\truntime.GOMAXPROCS(conf.General.MaxProc)\n\n\tdbtls := \"disable\"\n\tif conf.General.PostgresUseTLS {\n\t\tdbtls = \"verify-full\"\n\t}\n\tdb, err = pg.RegisterConnection(\n\t\tconf.General.PostgresDB,\n\t\tconf.General.PostgresUser,\n\t\tconf.General.PostgresPass,\n\t\tconf.General.Postgres,\n\t\tdbtls)\n\tdefer db.Close()\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatal(\"Failed to connect to database\")\n\t}\n\tdb.SetMaxOpenConns(conf.General.MaxProc)\n\tdb.SetMaxIdleConns(10)\n\tincomingScans := db.RegisterScanListener(conf.General.PostgresDB, conf.General.PostgresUser, conf.General.PostgresPass, conf.General.Postgres, \"disable\")\n\tSetup(conf)\n\n\tfor scanID := range incomingScans {\n\t\t\/\/ wait until we have an available scanner\n\t\tfor {\n\t\t\tif activeScanners >= conf.General.MaxProc {\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tgo scan(scanID, cipherscan)\n\t}\n}\n\nfunc scan(scanID int64, cipherscan string) {\n\tactiveScanners++\n\tdefer func() {\n\t\tactiveScanners--\n\t}()\n\tlog.WithFields(logrus.Fields{\n\t\t\"scan_id\": scanID,\n\t}).Info(\"Received new scan\")\n\n\tdb.Exec(\"UPDATE scans SET attempts = attempts + 1 WHERE id=$1\", scanID)\n\n\tscan, err := db.GetScanByID(scanID)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t\t\"error\":   err.Error(),\n\t\t}).Error(\"Could not find\/decode scan\")\n\t\treturn\n\t}\n\tvar completion int\n\n\t\/\/ Retrieve the certificate from the target\n\tcertID, trustID, err := handleCert(scan.Target)\n\tif err != nil {\n\t\tdb.Exec(\"UPDATE scans SET has_tls=FALSE, completion_perc=100 WHERE id=$1\", scanID)\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\":     scanID,\n\t\t\t\"scan_Target\": scan.Target,\n\t\t\t\"error\":       err.Error(),\n\t\t}).Error(\"Could not get certificate info\")\n\t\treturn\n\t}\n\tlog.WithFields(logrus.Fields{\n\t\t\"scan_id\":  scanID,\n\t\t\"cert_id\":  certID,\n\t\t\"trust_id\": trustID,\n\t}).Debug(\"Retrieved certs\")\n\n\tisTrustValid, err := db.IsTrustValid(trustID)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t\t\"cert_id\": certID,\n\t\t\t\"error\":   err.Error(),\n\t\t}).Error(\"Could not get if trust is valid\")\n\t\treturn\n\t}\n\tcompletion += 20\n\t_, err = db.Exec(`UPDATE scans\n\t\t\tSET cert_id=$1, trust_id=$2, has_tls=TRUE, is_valid=$3, completion_perc=$4\n\t\t\tWHERE id=$5`, certID, trustID, isTrustValid, completion, scanID)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t\t\"cert_id\": certID,\n\t\t\t\"error\":   err.Error(),\n\t\t}).Error(\"Could not update scans for cert\")\n\t\treturn\n\t}\n\n\t\/\/ Cipherscan the target\n\tjs, err := connection.Connect(scan.Target, cipherscan)\n\tif err != nil {\n\t\terr, ok := err.(connection.NoTLSConnErr)\n\t\tif ok {\n\t\t\t\/\/does not implement TLS\n\t\t\tdb.Exec(\"UPDATE scans SET has_tls=FALSE, completion_perc=100 WHERE id=$1\", scanID)\n\t\t} else {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"scan_id\": scanID,\n\t\t\t\t\"error\":   err.Error(),\n\t\t\t}).Error(\"Could not get TLS connection info\")\n\t\t}\n\t\treturn\n\t}\n\tcompletion += 20\n\t_, err = db.Exec(\"UPDATE scans SET conn_info=$1, completion_perc=$2 WHERE id=$3\",\n\t\tjs, completion, scanID)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t\t\"error\":   err.Error(),\n\t\t}).Error(\"Could not update connection information for scan\")\n\t}\n\n\t\/\/ Prepare worker input\n\tcert, err := db.GetCertByID(certID)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t\t\"cert_id\": certID,\n\t\t}).Error(\"Could not get certificate from db to pass to workers\")\n\t\treturn\n\t}\n\tvar conn_info connection.Stored\n\terr = json.Unmarshal(js, &conn_info)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t}).Error(\"Could not parse connection info to pass to workers\")\n\t\treturn\n\t}\n\tworkerInput := worker.Input{\n\t\tDBHandle:    db,\n\t\tScanid:      scanID,\n\t\tCertificate: *cert,\n\t\tConnection:  conn_info,\n\t}\n\t\/\/ launch workers that evaluate the results\n\tresChan := make(chan worker.Result)\n\ttotalWorkers := 0\n\tfor _, wrkInfo := range worker.AvailableWorkers {\n\t\tgo wrkInfo.Runner.(worker.Worker).Run(workerInput, resChan)\n\t\ttotalWorkers++\n\t}\n\tlog.WithFields(logrus.Fields{\n\t\t\"scan_id\": scanID,\n\t\t\"count\":   totalWorkers,\n\t}).Info(\"Running workers\")\n\n\t\/\/ read the results from the results chan in a loop until all workers have ran or expired\n\tfor endedWorkers := 0; endedWorkers < totalWorkers; endedWorkers++ {\n\t\tselect {\n\t\tcase <-time.After(30 * time.Second):\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"scan_id\": scanID,\n\t\t\t}).Error(\"Analysis workers timed out after 30 seconds\")\n\t\t\treturn\n\t\tcase res := <-resChan:\n\t\t\tendedWorkers += endedWorkers\n\t\t\tcompletion = ((endedWorkers\/totalWorkers)*60 + completion)\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"scan_id\":     scanID,\n\t\t\t\t\"worker_name\": res.WorkerName,\n\t\t\t\t\"success\":     res.Success,\n\t\t\t\t\"result\":      string(res.Result),\n\t\t\t}).Debug(\"Received results from worker\")\n\n\t\t\terr = db.UpdateScanCompletionPercentage(scanID, completion)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"scan_id\": scanID,\n\t\t\t\t\t\"error\":   err.Error(),\n\t\t\t\t}).Error(\"Could not update completion percentage\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !res.Success {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"worker_name\": res.WorkerName,\n\t\t\t\t\t\"errors\":      res.Errors,\n\t\t\t\t}).Error(\"Worker returned with errors\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t_, err = db.Exec(\"INSERT INTO analysis(scan_id,worker_name,output) VALUES($1,$2,$3)\",\n\t\t\t\tscanID, res.WorkerName, res.Result)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"scan_id\": scanID,\n\t\t\t\t\t\"error\":   err.Error(),\n\t\t\t\t}).Error(\"Could not insert worker results in database\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"scan_id\":     scanID,\n\t\t\t\t\"worker_name\": res.WorkerName,\n\t\t\t}).Info(\"Results from worker stored in database\")\n\t\t}\n\t}\n\terr = db.UpdateScanCompletionPercentage(scanID, 100)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t\t\"error\":   err.Error(),\n\t\t}).Error(\"Could not update completion percentage\")\n\t}\n\treturn\n}\n<commit_msg>minor tweak to handling of concurrent scanners<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\n\t\"github.com\/mozilla\/tls-observatory\/config\"\n\t\"github.com\/mozilla\/tls-observatory\/connection\"\n\tpg \"github.com\/mozilla\/tls-observatory\/database\"\n\t\"github.com\/mozilla\/tls-observatory\/logger\"\n\t\"github.com\/mozilla\/tls-observatory\/worker\"\n)\n\nvar db *pg.DB\nvar log = logger.GetLogger()\n\nfunc main() {\n\tvar (\n\t\tcfgFile, cipherscan string\n\t\tdebug               bool\n\t)\n\tflag.StringVar(&cfgFile, \"c\", \"\/etc\/tls-observatory\/scanner.cfg\", \"Configuration file\")\n\tflag.StringVar(&cipherscan, \"b\", \"\/opt\/cipherscan\/cipherscan\", \"Cipherscan binary location\")\n\tflag.BoolVar(&debug, \"debug\", false, \"Set debug logging\")\n\tflag.Parse()\n\n\tif debug {\n\t\tlogger.SetLevelToDebug()\n\t}\n\n\tconf, err := config.Load(cfgFile)\n\tif err != nil {\n\t\tlog.Fatal(fmt.Sprintf(\"Failed to load configuration: %v\", err))\n\t}\n\tif !conf.General.Enable && os.Getenv(\"TLSOBS_SCANNER_ENABLE\") != \"on\" {\n\t\tlog.Fatal(\"Scanner is disabled in configuration\")\n\t}\n\n\t_, err = os.Stat(cipherscan)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Error(\"Could not locate cipherscan executable. TLS connection capabilities will not be available.\")\n\t}\n\n\t\/\/ increase the n\n\truntime.GOMAXPROCS(conf.General.MaxProc)\n\n\tdbtls := \"disable\"\n\tif conf.General.PostgresUseTLS {\n\t\tdbtls = \"verify-full\"\n\t}\n\tdb, err = pg.RegisterConnection(\n\t\tconf.General.PostgresDB,\n\t\tconf.General.PostgresUser,\n\t\tconf.General.PostgresPass,\n\t\tconf.General.Postgres,\n\t\tdbtls)\n\tdefer db.Close()\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"error\": err.Error(),\n\t\t}).Fatal(\"Failed to connect to database\")\n\t}\n\tdb.SetMaxOpenConns(conf.General.MaxProc)\n\tdb.SetMaxIdleConns(10)\n\tincomingScans := db.RegisterScanListener(\n\t\tconf.General.PostgresDB,\n\t\tconf.General.PostgresUser,\n\t\tconf.General.PostgresPass,\n\t\tconf.General.Postgres,\n\t\t\"disable\")\n\tSetup(conf)\n\n\tactiveScanners := 0\n\tfor scanID := range incomingScans {\n\t\t\/\/ wait until we have an available scanner\n\t\tfor {\n\t\t\tif activeScanners >= conf.General.MaxProc {\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tgo func() {\n\t\t\tactiveScanners++\n\t\t\tscan(scanID, cipherscan)\n\t\t\tactiveScanners--\n\t\t}()\n\t}\n}\n\nfunc scan(scanID int64, cipherscan string) {\n\tlog.WithFields(logrus.Fields{\n\t\t\"scan_id\": scanID,\n\t}).Info(\"Received new scan\")\n\n\tdb.Exec(\"UPDATE scans SET attempts = attempts + 1 WHERE id=$1\", scanID)\n\n\tscan, err := db.GetScanByID(scanID)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t\t\"error\":   err.Error(),\n\t\t}).Error(\"Could not find\/decode scan\")\n\t\treturn\n\t}\n\tvar completion int\n\n\t\/\/ Retrieve the certificate from the target\n\tcertID, trustID, err := handleCert(scan.Target)\n\tif err != nil {\n\t\tdb.Exec(\"UPDATE scans SET has_tls=FALSE, completion_perc=100 WHERE id=$1\", scanID)\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\":     scanID,\n\t\t\t\"scan_Target\": scan.Target,\n\t\t\t\"error\":       err.Error(),\n\t\t}).Error(\"Could not get certificate info\")\n\t\treturn\n\t}\n\tlog.WithFields(logrus.Fields{\n\t\t\"scan_id\":  scanID,\n\t\t\"cert_id\":  certID,\n\t\t\"trust_id\": trustID,\n\t}).Debug(\"Retrieved certs\")\n\n\tisTrustValid, err := db.IsTrustValid(trustID)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t\t\"cert_id\": certID,\n\t\t\t\"error\":   err.Error(),\n\t\t}).Error(\"Could not get if trust is valid\")\n\t\treturn\n\t}\n\tcompletion += 20\n\t_, err = db.Exec(`UPDATE scans\n\t\t\tSET cert_id=$1, trust_id=$2, has_tls=TRUE, is_valid=$3, completion_perc=$4\n\t\t\tWHERE id=$5`, certID, trustID, isTrustValid, completion, scanID)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t\t\"cert_id\": certID,\n\t\t\t\"error\":   err.Error(),\n\t\t}).Error(\"Could not update scans for cert\")\n\t\treturn\n\t}\n\n\t\/\/ Cipherscan the target\n\tjs, err := connection.Connect(scan.Target, cipherscan)\n\tif err != nil {\n\t\terr, ok := err.(connection.NoTLSConnErr)\n\t\tif ok {\n\t\t\t\/\/does not implement TLS\n\t\t\tdb.Exec(\"UPDATE scans SET has_tls=FALSE, completion_perc=100 WHERE id=$1\", scanID)\n\t\t} else {\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"scan_id\": scanID,\n\t\t\t\t\"error\":   err.Error(),\n\t\t\t}).Error(\"Could not get TLS connection info\")\n\t\t}\n\t\treturn\n\t}\n\tcompletion += 20\n\t_, err = db.Exec(\"UPDATE scans SET conn_info=$1, completion_perc=$2 WHERE id=$3\",\n\t\tjs, completion, scanID)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t\t\"error\":   err.Error(),\n\t\t}).Error(\"Could not update connection information for scan\")\n\t}\n\n\t\/\/ Prepare worker input\n\tcert, err := db.GetCertByID(certID)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t\t\"cert_id\": certID,\n\t\t}).Error(\"Could not get certificate from db to pass to workers\")\n\t\treturn\n\t}\n\tvar conn_info connection.Stored\n\terr = json.Unmarshal(js, &conn_info)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t}).Error(\"Could not parse connection info to pass to workers\")\n\t\treturn\n\t}\n\tworkerInput := worker.Input{\n\t\tDBHandle:    db,\n\t\tScanid:      scanID,\n\t\tCertificate: *cert,\n\t\tConnection:  conn_info,\n\t}\n\t\/\/ launch workers that evaluate the results\n\tresChan := make(chan worker.Result)\n\ttotalWorkers := 0\n\tfor _, wrkInfo := range worker.AvailableWorkers {\n\t\tgo wrkInfo.Runner.(worker.Worker).Run(workerInput, resChan)\n\t\ttotalWorkers++\n\t}\n\tlog.WithFields(logrus.Fields{\n\t\t\"scan_id\": scanID,\n\t\t\"count\":   totalWorkers,\n\t}).Info(\"Running workers\")\n\n\t\/\/ read the results from the results chan in a loop until all workers have ran or expired\n\tfor endedWorkers := 0; endedWorkers < totalWorkers; endedWorkers++ {\n\t\tselect {\n\t\tcase <-time.After(30 * time.Second):\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"scan_id\": scanID,\n\t\t\t}).Error(\"Analysis workers timed out after 30 seconds\")\n\t\t\treturn\n\t\tcase res := <-resChan:\n\t\t\tendedWorkers += endedWorkers\n\t\t\tcompletion = ((endedWorkers\/totalWorkers)*60 + completion)\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"scan_id\":     scanID,\n\t\t\t\t\"worker_name\": res.WorkerName,\n\t\t\t\t\"success\":     res.Success,\n\t\t\t\t\"result\":      string(res.Result),\n\t\t\t}).Debug(\"Received results from worker\")\n\n\t\t\terr = db.UpdateScanCompletionPercentage(scanID, completion)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"scan_id\": scanID,\n\t\t\t\t\t\"error\":   err.Error(),\n\t\t\t\t}).Error(\"Could not update completion percentage\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !res.Success {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"worker_name\": res.WorkerName,\n\t\t\t\t\t\"errors\":      res.Errors,\n\t\t\t\t}).Error(\"Worker returned with errors\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t_, err = db.Exec(\"INSERT INTO analysis(scan_id,worker_name,output) VALUES($1,$2,$3)\",\n\t\t\t\tscanID, res.WorkerName, res.Result)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\t\"scan_id\": scanID,\n\t\t\t\t\t\"error\":   err.Error(),\n\t\t\t\t}).Error(\"Could not insert worker results in database\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.WithFields(logrus.Fields{\n\t\t\t\t\"scan_id\":     scanID,\n\t\t\t\t\"worker_name\": res.WorkerName,\n\t\t\t}).Info(\"Results from worker stored in database\")\n\t\t}\n\t}\n\terr = db.UpdateScanCompletionPercentage(scanID, 100)\n\tif err != nil {\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"scan_id\": scanID,\n\t\t\t\"error\":   err.Error(),\n\t\t}).Error(\"Could not update completion percentage\")\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package util\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/rackspace\/gophercloud\"\n)\n\n\/\/ Name is the name of the CLI\nvar name = \"rack\"\n\n\/\/ Version is the current CLI version\nvar Version = \"0.0.0-dev\"\n\n\/\/ Usage return a string that specifies how to call a particular command.\nfunc Usage(commandPrefix, action, mandatoryFlags string) string {\n\treturn fmt.Sprintf(\"%s [GLOBALS] %s %s %s [OPTIONS]\", name, commandPrefix, action, mandatoryFlags)\n}\n\n\/\/ Contains checks whether a given string is in a provided slice of strings.\nfunc Contains(s []string, e string) bool {\n\tfor _, a := range s {\n\t\tif a == e {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ RackDir returns the location of the `rack` directory. This directory is for\n\/\/ storing `rack`-specific information such as the cache or a config file.\nfunc RackDir() (string, error) {\n\thomeDir := os.Getenv(\"HOME\") \/\/ *nix\n\tif homeDir == \"\" {           \/\/ Windows\n\t\thomeDir = os.Getenv(\"USERPROFILE\")\n\t}\n\tif homeDir == \"\" {\n\t\treturn \"\", errors.New(\"User home directory not found.\")\n\t}\n\tdirpath := path.Join(homeDir, \".rack\")\n\terr := os.MkdirAll(dirpath, 0644)\n\treturn dirpath, err\n}\n\n\/\/ CheckArgNum checks that the provided number of arguments has the same\n\/\/ cardinality as the expected number of arguments.\nfunc CheckArgNum(c *cli.Context, expected int) error {\n\targsLen := len(c.Args())\n\tif argsLen != expected {\n\t\treturn fmt.Errorf(\"Expected %d args but got %d\\nUsage: %s\", expected, argsLen, c.Command.Usage)\n\t}\n\treturn nil\n}\n\n\/\/ CheckFlagsSet checks that the given flag names are set for the command.\nfunc CheckFlagsSet(c *cli.Context, flagNames []string) error {\n\tfor _, flagName := range flagNames {\n\t\tif !c.IsSet(flagName) {\n\t\t\treturn Error(c, ErrMissingFlag{\n\t\t\t\tMsg: fmt.Sprintf(\"--%s is required.\", flagName),\n\t\t\t})\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ IDOrName is a function for retrieving a resources unique identifier based on\n\/\/ whether he or she passed an `id` or a `name` flag.\nfunc IDOrName(c *cli.Context, client *gophercloud.ServiceClient, idFromName func(*gophercloud.ServiceClient, string) (string, error)) (string, error) {\n\tif c.IsSet(\"id\") {\n\t\treturn c.String(\"id\"), nil\n\t} else if c.IsSet(\"name\") {\n\t\tname := c.String(\"name\")\n\t\tid, err := idFromName(client, name)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Error converting name [%s] to ID: %s\", name, err)\n\t\t}\n\t\treturn id, nil\n\t} else {\n\t\treturn \"\", Error(c, ErrMissingFlag{\n\t\t\tMsg: \"One of either --id or --name must be provided.\",\n\t\t})\n\t}\n}\n\n\/\/ IDAndNameFlags are flags for commands that allow either an ID or a name.\nvar IDAndNameFlags = []cli.Flag{\n\tcli.StringFlag{\n\t\tName:  \"id\",\n\t\tUsage: \"[optional; required if 'name' is not provided] The ID of the resource\",\n\t},\n\tcli.StringFlag{\n\t\tName:  \"name\",\n\t\tUsage: \"[optional; required if 'id' is not provided] The name of the resource\",\n\t},\n}\n\n\/\/ IDOrNameUsage returns flag usage information for resources that allow either\n\/\/ an ID or a name.\nfunc IDOrNameUsage(resource string) string {\n\treturn fmt.Sprintf(\"[--id <%sID> | --name <%sName>]\", resource, resource)\n}\n<commit_msg>error if both id and name are provided<commit_after>package util\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/rackspace\/gophercloud\"\n)\n\n\/\/ Name is the name of the CLI\nvar name = \"rack\"\n\n\/\/ Version is the current CLI version\nvar Version = \"0.0.0-dev\"\n\n\/\/ Usage return a string that specifies how to call a particular command.\nfunc Usage(commandPrefix, action, mandatoryFlags string) string {\n\treturn fmt.Sprintf(\"%s [GLOBALS] %s %s %s [OPTIONS]\", name, commandPrefix, action, mandatoryFlags)\n}\n\n\/\/ Contains checks whether a given string is in a provided slice of strings.\nfunc Contains(s []string, e string) bool {\n\tfor _, a := range s {\n\t\tif a == e {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ RackDir returns the location of the `rack` directory. This directory is for\n\/\/ storing `rack`-specific information such as the cache or a config file.\nfunc RackDir() (string, error) {\n\thomeDir := os.Getenv(\"HOME\") \/\/ *nix\n\tif homeDir == \"\" {           \/\/ Windows\n\t\thomeDir = os.Getenv(\"USERPROFILE\")\n\t}\n\tif homeDir == \"\" {\n\t\treturn \"\", errors.New(\"User home directory not found.\")\n\t}\n\tdirpath := path.Join(homeDir, \".rack\")\n\terr := os.MkdirAll(dirpath, 0644)\n\treturn dirpath, err\n}\n\n\/\/ CheckArgNum checks that the provided number of arguments has the same\n\/\/ cardinality as the expected number of arguments.\nfunc CheckArgNum(c *cli.Context, expected int) error {\n\targsLen := len(c.Args())\n\tif argsLen != expected {\n\t\treturn fmt.Errorf(\"Expected %d args but got %d\\nUsage: %s\", expected, argsLen, c.Command.Usage)\n\t}\n\treturn nil\n}\n\n\/\/ CheckFlagsSet checks that the given flag names are set for the command.\nfunc CheckFlagsSet(c *cli.Context, flagNames []string) error {\n\tfor _, flagName := range flagNames {\n\t\tif !c.IsSet(flagName) {\n\t\t\treturn Error(c, ErrMissingFlag{\n\t\t\t\tMsg: fmt.Sprintf(\"--%s is required.\", flagName),\n\t\t\t})\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ IDOrName is a function for retrieving a resources unique identifier based on\n\/\/ whether he or she passed an `id` or a `name` flag.\nfunc IDOrName(c *cli.Context, client *gophercloud.ServiceClient, idFromName func(*gophercloud.ServiceClient, string) (string, error)) (string, error) {\n\tif c.IsSet(\"id\") {\n\t\tif c.IsSet(\"name\") {\n\t\t\treturn \"\", fmt.Errorf(\"Only one of either --id or --name may be provided.\")\n\t\t}\n\t\treturn c.String(\"id\"), nil\n\t} else if c.IsSet(\"name\") {\n\t\tname := c.String(\"name\")\n\t\tid, err := idFromName(client, name)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Error converting name [%s] to ID: %s\", name, err)\n\t\t}\n\t\treturn id, nil\n\t} else {\n\t\treturn \"\", Error(c, ErrMissingFlag{\n\t\t\tMsg: \"One of either --id or --name must be provided.\",\n\t\t})\n\t}\n}\n\n\/\/ IDAndNameFlags are flags for commands that allow either an ID or a name.\nvar IDAndNameFlags = []cli.Flag{\n\tcli.StringFlag{\n\t\tName:  \"id\",\n\t\tUsage: \"[optional; required if 'name' is not provided] The ID of the resource\",\n\t},\n\tcli.StringFlag{\n\t\tName:  \"name\",\n\t\tUsage: \"[optional; required if 'id' is not provided] The name of the resource\",\n\t},\n}\n\n\/\/ IDOrNameUsage returns flag usage information for resources that allow either\n\/\/ an ID or a name.\nfunc IDOrNameUsage(resource string) string {\n\treturn fmt.Sprintf(\"[--id <%sID> | --name <%sName>]\", resource, resource)\n}\n<|endoftext|>"}
{"text":"<commit_before>package iso\n\nimport (\n\t\"fmt\"\n\t\"github.com\/mitchellh\/multistep\"\n\tparallelscommon \"github.com\/mitchellh\/packer\/builder\/parallels\/common\"\n\t\"github.com\/mitchellh\/packer\/packer\"\n\t\"log\"\n)\n\n\/\/ This step attaches the ISO to the virtual machine.\n\/\/\n\/\/ Uses:\n\/\/   driver Driver\n\/\/   isoPath string\n\/\/   ui packer.Ui\n\/\/   vmName string\n\/\/\n\/\/ Produces:\ntype stepAttachISO struct {\n\tcdromDevice string\n}\n\nfunc (s *stepAttachISO) Run(state multistep.StateBag) multistep.StepAction {\n\tdriver := state.Get(\"driver\").(parallelscommon.Driver)\n\tisoPath := state.Get(\"iso_path\").(string)\n\tui := state.Get(\"ui\").(packer.Ui)\n\tvmName := state.Get(\"vmName\").(string)\n\n\t\/\/ Attach the disk to the controller\n\tui.Say(\"Attaching ISO to the new CD\/DVD drive...\")\n\tcdrom, err := driver.DeviceAddCdRom(vmName, isoPath)\n\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Error attaching ISO: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Set new boot order\n\tui.Say(\"Setting the boot order...\")\n\tcommand := []string{\n\t\t\"set\", vmName,\n\t\t\"--device-bootorder\", fmt.Sprintf(\"hdd0 %s cdrom0 net0\", cdrom),\n\t}\n\n\tif err := driver.Prlctl(command...); err != nil {\n\t\terr := fmt.Errorf(\"Error setting the boot order: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Disable 'cdrom0' device\n\tui.Say(\"Disabling default CD\/DVD drive...\")\n\tcommand = []string{\n\t\t\"set\", vmName,\n\t\t\"--device-set\", \"cdrom0\", \"--disable\",\n\t}\n\n\tif err := driver.Prlctl(command...); err != nil {\n\t\terr := fmt.Errorf(\"Error disabling default CD\/DVD drive: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Track the device name so that we can can delete later\n\ts.cdromDevice = cdrom\n\n\treturn multistep.ActionContinue\n}\n\nfunc (s *stepAttachISO) Cleanup(state multistep.StateBag) {\n\tdriver := state.Get(\"driver\").(parallelscommon.Driver)\n\tui := state.Get(\"ui\").(packer.Ui)\n\tvmName := state.Get(\"vmName\").(string)\n\n\t\/\/ Enable 'cdrom0' device back\n\tlog.Println(\"Enabling default CD\/DVD drive...\")\n\tcommand := []string{\n\t\t\"set\", vmName,\n\t\t\"--device-set\", \"cdrom0\", \"--enable\", \"--disconnect\",\n\t}\n\n\tif err := driver.Prlctl(command...); err != nil {\n\t\tui.Error(fmt.Sprintf(\"Error enabling default CD\/DVD drive: %s\", err))\n\t}\n\n\t\/\/ Detach ISO\n\tif s.cdromDevice == \"\" {\n\t\treturn\n\t}\n\n\tlog.Println(\"Detaching ISO...\")\n\tcommand = []string{\n\t\t\"set\", vmName,\n\t\t\"--device-del\", s.cdromDevice,\n\t}\n\n\tif err := driver.Prlctl(command...); err != nil {\n\t\tui.Error(fmt.Sprintf(\"Error detaching ISO: %s\", err))\n\t}\n}\n<commit_msg>builder\/parallels: Attach bootable ISO exactly to cdrom0 [GH-1667]<commit_after>package iso\n\nimport (\n\t\"fmt\"\n\t\"github.com\/mitchellh\/multistep\"\n\tparallelscommon \"github.com\/mitchellh\/packer\/builder\/parallels\/common\"\n\t\"github.com\/mitchellh\/packer\/packer\"\n\t\"log\"\n)\n\n\/\/ This step attaches the ISO to the virtual machine.\n\/\/\n\/\/ Uses:\n\/\/   driver Driver\n\/\/   isoPath string\n\/\/   ui packer.Ui\n\/\/   vmName string\n\/\/\n\/\/ Produces:\n\/\/\t attachedIso bool\ntype stepAttachISO struct{}\n\nfunc (s *stepAttachISO) Run(state multistep.StateBag) multistep.StepAction {\n\tdriver := state.Get(\"driver\").(parallelscommon.Driver)\n\tisoPath := state.Get(\"iso_path\").(string)\n\tui := state.Get(\"ui\").(packer.Ui)\n\tvmName := state.Get(\"vmName\").(string)\n\n\t\/\/ Set new boot order\n\tui.Say(\"Setting the boot order...\")\n\tcommand := []string{\n\t\t\"set\", vmName,\n\t\t\"--device-bootorder\", fmt.Sprintf(\"hdd0 cdrom0 net0\"),\n\t}\n\n\tif err := driver.Prlctl(command...); err != nil {\n\t\terr := fmt.Errorf(\"Error setting the boot order: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Attach the disk to the cdrom0 device. We couldn't use a separated device because it is failed to boot in PD9 [GH-1667]\n\tui.Say(\"Attaching ISO to the default CD\/DVD ROM device...\")\n\tcommand = []string{\n\t\t\"set\", vmName,\n\t\t\"--device-set\", \"cdrom0\",\n\t\t\"--image\", isoPath,\n\t\t\"--enable\", \"--connect\",\n\t}\n\tif err := driver.Prlctl(command...); err != nil {\n\t\terr := fmt.Errorf(\"Error attaching ISO: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\n\t\/\/ Set some state so we know to remove\n\tstate.Put(\"attachedIso\", true)\n\n\treturn multistep.ActionContinue\n}\n\nfunc (s *stepAttachISO) Cleanup(state multistep.StateBag) {\n\tif _, ok := state.GetOk(\"attachedIso\"); !ok {\n\t\treturn\n\t}\n\n\tdriver := state.Get(\"driver\").(parallelscommon.Driver)\n\tui := state.Get(\"ui\").(packer.Ui)\n\tvmName := state.Get(\"vmName\").(string)\n\n\t\/\/ Detach ISO by setting an empty string image.\n\tlog.Println(\"Detaching ISO from the default CD\/DVD ROM device...\")\n\tcommand := []string{\n\t\t\"set\", vmName,\n\t\t\"--device-set\", \"cdrom0\",\n\t\t\"--image\", \"\", \"--disconnect\", \"--enable\",\n\t}\n\n\tif err := driver.Prlctl(command...); err != nil {\n\t\tui.Error(fmt.Sprintf(\"Error detaching ISO: %s\", err))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2020 Jigsaw Operations LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage shadowsocks\n\nimport (\n\t\"crypto\/aes\"\n\t\"crypto\/cipher\"\n\t\"crypto\/sha1\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\n\t\"golang.org\/x\/crypto\/chacha20poly1305\"\n\t\"golang.org\/x\/crypto\/hkdf\"\n)\n\n\/\/ SuportedCipherNames lists the names of the AEAD ciphers that are supported.\nvar SuportedCipherNames []string\n\nfunc init() {\n\tSuportedCipherNames = make([]string, len(supportedAEADs))\n\tfor i, spec := range supportedAEADs {\n\t\tSuportedCipherNames[i] = spec.name\n\t}\n}\n\ntype aeadSpec struct {\n\tname        string\n\tnewInstance func(key []byte) (cipher.AEAD, error)\n\tkeySize     int\n\ttagSize     int\n}\n\n\/\/ List of supported AEAD ciphers, as specified at https:\/\/shadowsocks.org\/en\/spec\/AEAD-Ciphers.html\nvar supportedAEADs = []aeadSpec{\n\tnewAeadSpec(\"chacha20-ietf-poly1305\", chacha20poly1305.New, chacha20poly1305.KeySize),\n\tnewAeadSpec(\"aes-256-gcm\", newAesGCM, 32),\n\tnewAeadSpec(\"aes-192-gcm\", newAesGCM, 24),\n\tnewAeadSpec(\"aes-128-gcm\", newAesGCM, 16),\n}\n\nfunc newAeadSpec(name string, newInstance func(key []byte) (cipher.AEAD, error), keySize int) aeadSpec {\n\tdummyAead, err := newInstance(make([]byte, keySize))\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to initialize AEAD %v\", name))\n\t}\n\treturn aeadSpec{name, newInstance, keySize, dummyAead.Overhead()}\n}\n\nfunc newAesGCM(key []byte) (cipher.AEAD, error) {\n\tblk, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cipher.NewGCM(blk)\n}\n\n\/\/ Cipher encapsulates a Shadowsocks AEAD spec and a secret\ntype Cipher struct {\n\taead   aeadSpec\n\tsecret []byte\n}\n\n\/\/ SaltSize is the size of the salt for this Cipher\nfunc (c *Cipher) SaltSize() int {\n\treturn c.aead.keySize\n}\n\n\/\/ TagSize is the size of the AEAD tag for this Cipher\nfunc (c *Cipher) TagSize() int {\n\treturn c.aead.tagSize\n}\n\n\/\/ NewAEAD creates the AEAD for this cipher\nfunc (c *Cipher) NewAEAD(salt []byte) (cipher.AEAD, error) {\n\tsessionKey := make([]byte, c.aead.keySize)\n\tr := hkdf.New(sha1.New, c.secret, salt, []byte(\"ss-subkey\"))\n\tif _, err := io.ReadFull(r, sessionKey); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.aead.newInstance(sessionKey)\n}\n\nfunc getAEADSpec(name string) (*aeadSpec, error) {\n\tname = strings.ToLower(name)\n\tfor _, aeadSpec := range supportedAEADs {\n\t\tif aeadSpec.name == name {\n\t\t\treturn &aeadSpec, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"Unknown cipher %v\", name)\n}\n\n\/\/ NewCipher creates a Cipher given a cipher name and a secret\nfunc NewCipher(cipherName string, secretText string) (*Cipher, error) {\n\tsecret := []byte(secretText)\n\taeadSpec, err := getAEADSpec(cipherName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Cipher{*aeadSpec, secret}, nil\n}\n\n\/\/ Assumes all ciphers have NonceSize() <= 12.\nvar zeroNonce [12]byte\n\n\/\/ DecryptOnce will decrypt the cipherText using the cipher and salt, appending the output to plainText.\nfunc DecryptOnce(cipher *Cipher, salt []byte, plainText, cipherText []byte) ([]byte, error) {\n\taead, err := cipher.NewAEAD(salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(cipherText) < aead.Overhead() {\n\t\treturn nil, io.ErrUnexpectedEOF\n\t}\n\tif cap(plainText)-len(plainText) < len(cipherText)-aead.Overhead() {\n\t\treturn nil, io.ErrShortBuffer\n\t}\n\treturn aead.Open(plainText, zeroNonce[:aead.NonceSize()], cipherText, nil)\n}\n<commit_msg>Update shadowsocks\/cipher.go<commit_after>\/\/ Copyright 2020 Jigsaw Operations LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage shadowsocks\n\nimport (\n\t\"crypto\/aes\"\n\t\"crypto\/cipher\"\n\t\"crypto\/sha1\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\n\t\"golang.org\/x\/crypto\/chacha20poly1305\"\n\t\"golang.org\/x\/crypto\/hkdf\"\n)\n\n\/\/ SuportedCipherNames lists the names of the AEAD ciphers that are supported.\nvar SuportedCipherNames []string\n\nfunc init() {\n\tSuportedCipherNames = make([]string, len(supportedAEADs))\n\tfor i, spec := range supportedAEADs {\n\t\tSuportedCipherNames[i] = spec.name\n\t}\n}\n\ntype aeadSpec struct {\n\tname        string\n\tnewInstance func(key []byte) (cipher.AEAD, error)\n\tkeySize     int\n\ttagSize     int\n}\n\n\/\/ List of supported AEAD ciphers, as specified at https:\/\/shadowsocks.org\/en\/spec\/AEAD-Ciphers.html\nvar supportedAEADs = [...]aeadSpec{\n\tnewAeadSpec(\"chacha20-ietf-poly1305\", chacha20poly1305.New, chacha20poly1305.KeySize),\n\tnewAeadSpec(\"aes-256-gcm\", newAesGCM, 32),\n\tnewAeadSpec(\"aes-192-gcm\", newAesGCM, 24),\n\tnewAeadSpec(\"aes-128-gcm\", newAesGCM, 16),\n}\n\nfunc newAeadSpec(name string, newInstance func(key []byte) (cipher.AEAD, error), keySize int) aeadSpec {\n\tdummyAead, err := newInstance(make([]byte, keySize))\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Failed to initialize AEAD %v\", name))\n\t}\n\treturn aeadSpec{name, newInstance, keySize, dummyAead.Overhead()}\n}\n\nfunc newAesGCM(key []byte) (cipher.AEAD, error) {\n\tblk, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cipher.NewGCM(blk)\n}\n\n\/\/ Cipher encapsulates a Shadowsocks AEAD spec and a secret\ntype Cipher struct {\n\taead   aeadSpec\n\tsecret []byte\n}\n\n\/\/ SaltSize is the size of the salt for this Cipher\nfunc (c *Cipher) SaltSize() int {\n\treturn c.aead.keySize\n}\n\n\/\/ TagSize is the size of the AEAD tag for this Cipher\nfunc (c *Cipher) TagSize() int {\n\treturn c.aead.tagSize\n}\n\n\/\/ NewAEAD creates the AEAD for this cipher\nfunc (c *Cipher) NewAEAD(salt []byte) (cipher.AEAD, error) {\n\tsessionKey := make([]byte, c.aead.keySize)\n\tr := hkdf.New(sha1.New, c.secret, salt, []byte(\"ss-subkey\"))\n\tif _, err := io.ReadFull(r, sessionKey); err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.aead.newInstance(sessionKey)\n}\n\nfunc getAEADSpec(name string) (*aeadSpec, error) {\n\tname = strings.ToLower(name)\n\tfor _, aeadSpec := range supportedAEADs {\n\t\tif aeadSpec.name == name {\n\t\t\treturn &aeadSpec, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"Unknown cipher %v\", name)\n}\n\n\/\/ NewCipher creates a Cipher given a cipher name and a secret\nfunc NewCipher(cipherName string, secretText string) (*Cipher, error) {\n\tsecret := []byte(secretText)\n\taeadSpec, err := getAEADSpec(cipherName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Cipher{*aeadSpec, secret}, nil\n}\n\n\/\/ Assumes all ciphers have NonceSize() <= 12.\nvar zeroNonce [12]byte\n\n\/\/ DecryptOnce will decrypt the cipherText using the cipher and salt, appending the output to plainText.\nfunc DecryptOnce(cipher *Cipher, salt []byte, plainText, cipherText []byte) ([]byte, error) {\n\taead, err := cipher.NewAEAD(salt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(cipherText) < aead.Overhead() {\n\t\treturn nil, io.ErrUnexpectedEOF\n\t}\n\tif cap(plainText)-len(plainText) < len(cipherText)-aead.Overhead() {\n\t\treturn nil, io.ErrShortBuffer\n\t}\n\treturn aead.Open(plainText, zeroNonce[:aead.NonceSize()], cipherText, nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package v8\n\n\/*\n#include \"v8_wrap.h\"\n#include <stdlib.h>\n*\/\nimport \"C\"\nimport \"unsafe\"\nimport \"reflect\"\n\ntype PropertyAttribute int\n\nconst (\n\tPA_None       PropertyAttribute = 0\n\tPA_ReadOnly                     = 1 << 0\n\tPA_DontEnum                     = 1 << 1\n\tPA_DontDelete                   = 1 << 2\n)\n\ntype External struct {\n\t*Value\n\tdata interface{}\n}\n\nfunc (e *Engine) NewExternal(value interface{}) *External {\n\tif value == nil {\n\t\tpanic(\"value is nil\")\n\t}\n\n\texternal := &External{\n\t\tdata: value,\n\t}\n\n\texternal.Value = newValue(e, C.V8_NewExternal(\n\t\te.self, unsafe.Pointer(&(external.data)),\n\t))\n\n\texternal.setOwner(external)\n\n\treturn external\n}\n\nfunc (ex *External) GetValue() interface{} {\n\tif ex.data == nil {\n\t\tptr := C.V8_External_Value(ex.self)\n\t\tex.data = *(*interface{})(ptr)\n\t}\n\n\treturn ex.data\n}\n\n\/\/ A JavaScript object (ECMA-262, 4.3.3)\n\/\/\ntype Object struct {\n\t*Value\n\tinternalFields []interface{}\n\taccessor       *accessorInfo\n}\n\nfunc (e *Engine) NewObject() *Value {\n\treturn newValue(e, C.V8_NewObject(e.self))\n}\n\nfunc (o *Object) SetProperty(key string, value *Value) bool {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_SetProperty(\n\t\to.self, (*C.char)(keyPtr), C.int(len(key)), value.self,\n\t) == 1\n}\n\nfunc (o *Object) GetProperty(key string) *Value {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn newValue(o.engine, C.V8_Object_GetProperty(\n\t\to.self, (*C.char)(keyPtr), C.int(len(key)),\n\t))\n}\n\nfunc (o *Object) SetElement(index int, value *Value) bool {\n\treturn C.V8_Object_SetElement(\n\t\to.self, C.uint32_t(index), value.self,\n\t) == 1\n}\n\nfunc (o *Object) GetElement(index int) *Value {\n\treturn newValue(o.engine, C.V8_Object_GetElement(o.self, C.uint32_t(index)))\n}\n\nfunc (o *Object) GetPropertyAttributes(key string) PropertyAttribute {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn PropertyAttribute(C.V8_Object_GetPropertyAttributes(\n\t\to.self, (*C.char)(keyPtr), C.int(len(key)),\n\t))\n}\n\nfunc (o *Object) InternalFieldCount() int {\n\treturn int(C.V8_Object_InternalFieldCount(o.self))\n}\n\nfunc (o *Object) GetInternalField(index int) interface{} {\n\tdata := C.V8_Object_GetInternalField(o.self, C.int(index))\n\tif data == nil {\n\t\treturn nil\n\t}\n\treturn *(*interface{})(data)\n}\n\nfunc (o *Object) SetInternalField(index int, value interface{}) {\n\tC.V8_Object_SetInternalField(\n\t\to.self,\n\t\tC.int(index),\n\t\tunsafe.Pointer(&value),\n\t)\n\n\t\/\/ the value reference by object so the value can't destory by GC\n\to.internalFields = append(o.internalFields, value)\n\to.setOwner(o)\n}\n\nfunc (o *Object) SetAccessor(\n\tkey string,\n\tgetter AccessorGetterCallback,\n\tsetter AccessorSetterCallback,\n\tdata interface{},\n\tattribs PropertyAttribute,\n) {\n\to.setAccessor(&accessorInfo{\n\t\tkey:     key,\n\t\tgetter:  getter,\n\t\tsetter:  setter,\n\t\tdata:    data,\n\t\tattribs: attribs,\n\t})\n}\n\nfunc (o *Object) setAccessor(info *accessorInfo) {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&info.key)).Data)\n\tvar getterPointer, setterPointer unsafe.Pointer\n\tif info.getter != nil {\n\t\tgetterPointer = unsafe.Pointer(&info.getter)\n\t}\n\n\tif info.setter != nil {\n\t\tsetterPointer = unsafe.Pointer(&info.setter)\n\t}\n\n\to.accessor = info\n\to.setOwner(o)\n\n\tC.V8_Object_SetAccessor(\n\t\to.self,\n\t\t(*C.char)(keyPtr), C.int(len(info.key)),\n\t\tgetterPointer,\n\t\tsetterPointer,\n\t\tunsafe.Pointer(&info.data),\n\t\tC.int(info.attribs),\n\t)\n}\n\n\/\/ Sets a local property on this object bypassing interceptors and\n\/\/ overriding accessors or read-only properties.\n\/\/\n\/\/ Note that if the object has an interceptor the property will be set\n\/\/ locally, but since the interceptor takes precedence the local property\n\/\/ will only be returned if the interceptor doesn't return a value.\n\/\/\n\/\/ Note also that this only works for named properties.\nfunc (o *Object) ForceSetProperty(key string, value *Value, attribs PropertyAttribute) bool {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_ForceSetProperty(o.self,\n\t\t(*C.char)(keyPtr), C.int(len(key)), value.self, C.int(attribs),\n\t) == 1\n}\n\nfunc (o *Object) HasProperty(key string) bool {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_HasProperty(\n\t\to.self, (*C.char)(keyPtr), C.int(len(key)),\n\t) == 1\n}\n\nfunc (o *Object) DeleteProperty(key string) bool {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_DeleteProperty(\n\t\to.self, (*C.char)(keyPtr), C.int(len(key)),\n\t) == 1\n}\n\n\/\/ Delete a property on this object bypassing interceptors and\n\/\/ ignoring dont-delete attributes.\nfunc (o *Object) ForceDeleteProperty(key string) bool {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_ForceDeleteProperty(\n\t\to.self, (*C.char)(keyPtr), C.int(len(key)),\n\t) == 1\n}\n\nfunc (o *Object) HasElement(index int) bool {\n\treturn C.V8_Object_HasElement(\n\t\to.self, C.uint32_t(index),\n\t) == 1\n}\n\nfunc (o *Object) DeleteElement(index int) bool {\n\treturn C.V8_Object_DeleteElement(\n\t\to.self, C.uint32_t(index),\n\t) == 1\n}\n\n\/\/ Returns an array containing the names of the enumerable properties\n\/\/ of this object, including properties from prototype objects.  The\n\/\/ array returned by this method contains the same values as would\n\/\/ be enumerated by a for-in statement over this object.\n\/\/\nfunc (o *Object) GetPropertyNames() *Array {\n\treturn newValue(o.engine, C.V8_Object_GetPropertyNames(o.self)).ToArray()\n}\n\n\/\/ This function has the same functionality as GetPropertyNames but\n\/\/ the returned array doesn't contain the names of properties from\n\/\/ prototype objects.\n\/\/\nfunc (o *Object) GetOwnPropertyNames() *Array {\n\treturn newValue(o.engine, C.V8_Object_GetOwnPropertyNames(o.self)).ToArray()\n}\n\n\/\/ Get the prototype object.  This does not skip objects marked to\n\/\/ be skipped by __proto__ and it does not consult the security\n\/\/ handler.\n\/\/\nfunc (o *Object) GetPrototype() *Object {\n\treturn newValue(o.engine, C.V8_Object_GetPrototype(o.self)).ToObject()\n}\n\n\/\/ Set the prototype object.  This does not skip objects marked to\n\/\/ be skipped by __proto__ and it does not consult the security\n\/\/ handler.\n\/\/\nfunc (o *Object) SetPrototype(proto *Object) bool {\n\treturn C.V8_Object_SetPrototype(o.self, proto.self) == 1\n}\n\nfunc (o *Object) SetHiddenValue(key string, value *Value) bool{\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_SetHiddenValue(o.self, (*C.char)(keyPtr), value.self) == 1\n}\n\nfunc (o *Object) DeleteHiddenValue(key string) bool{\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_DeleteHiddenValue(o.self, (*C.char)(keyPtr)) == 1\n}\n\nfunc (o *Object) GetConstructorName() string{\n\treturn newValue(o.engine, C.V8_Object_GetConstructorName(o.self)).ToString()\n}\n\n\/\/ An instance of the built-in array constructor (ECMA-262, 15.4.2).\n\/\/\ntype Array struct {\n\t*Object\n}\n\nfunc (e *Engine) NewArray(length int) *Value {\n\treturn newValue(e, C.V8_NewArray(\n\t\te.self, C.int(length),\n\t))\n}\n\nfunc (a *Array) Length() int {\n\treturn int(C.V8_Array_Length(a.self))\n}\n\ntype RegExpFlags int\n\n\/\/ Regular expression flag bits. They can be or'ed to enable a set\n\/\/ of flags.\n\/\/\nconst (\n\tRF_None       RegExpFlags = 0\n\tRF_Global                 = 1\n\tRF_IgnoreCase             = 2\n\tRF_Multiline              = 4\n)\n\ntype RegExp struct {\n\t*Object\n\tpattern       string\n\tpatternCached bool\n\tflags         RegExpFlags\n\tflagsCached   bool\n}\n\n\/\/ Creates a regular expression from the given pattern string and\n\/\/ the flags bit field. May throw a JavaScript exception as\n\/\/ described in ECMA-262, 15.10.4.1.\n\/\/\n\/\/ For example,\n\/\/   NewRegExp(\"foo\", RF_Global | RF_Multiline)\n\/\/\n\/\/ is equivalent to evaluating \"\/foo\/gm\".\n\/\/\nfunc (e *Engine) NewRegExp(pattern string, flags RegExpFlags) *Value {\n\tpatternPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&pattern)).Data)\n\n\treturn newValue(e, C.V8_NewRegExp(\n\t\te.self, (*C.char)(patternPtr), C.int(len(pattern)), C.int(flags),\n\t))\n}\n\n\/\/ Returns the value of the source property: a string representing\n\/\/ the regular expression.\nfunc (r *RegExp) Pattern() string {\n\tif !r.patternCached {\n\t\tcstring := C.V8_RegExp_Pattern(r.self)\n\t\tr.pattern = C.GoString(cstring)\n\t\tr.patternCached = true\n\t\tC.free(unsafe.Pointer(cstring))\n\t}\n\treturn r.pattern\n}\n\n\/\/ Returns the flags bit field.\n\/\/\nfunc (r *RegExp) Flags() RegExpFlags {\n\tif !r.flagsCached {\n\t\tr.flags = RegExpFlags(C.V8_RegExp_Flags(r.self))\n\t\tr.flagsCached = true\n\t}\n\treturn r.flags\n}\n<commit_msg>add functin <SetAlignedPointerInInternalField,GetAlignedPointerFromInternalField><commit_after>package v8\n\n\/*\n#include \"v8_wrap.h\"\n#include <stdlib.h>\n*\/\nimport \"C\"\nimport \"unsafe\"\nimport \"reflect\"\n\ntype PropertyAttribute int\n\nconst (\n\tPA_None       PropertyAttribute = 0\n\tPA_ReadOnly                     = 1 << 0\n\tPA_DontEnum                     = 1 << 1\n\tPA_DontDelete                   = 1 << 2\n)\n\ntype External struct {\n\t*Value\n\tdata interface{}\n}\n\nfunc (e *Engine) NewExternal(value interface{}) *External {\n\tif value == nil {\n\t\tpanic(\"value is nil\")\n\t}\n\n\texternal := &External{\n\t\tdata: value,\n\t}\n\n\texternal.Value = newValue(e, C.V8_NewExternal(\n\t\te.self, unsafe.Pointer(&(external.data)),\n\t))\n\n\texternal.setOwner(external)\n\n\treturn external\n}\n\nfunc (ex *External) GetValue() interface{} {\n\tif ex.data == nil {\n\t\tptr := C.V8_External_Value(ex.self)\n\t\tex.data = *(*interface{})(ptr)\n\t}\n\n\treturn ex.data\n}\n\n\/\/ A JavaScript object (ECMA-262, 4.3.3)\n\/\/\ntype Object struct {\n\t*Value\n\tinternalFields []interface{}\n\taccessor       *accessorInfo\n}\n\nfunc (e *Engine) NewObject() *Value {\n\treturn newValue(e, C.V8_NewObject(e.self))\n}\n\nfunc (o *Object) SetProperty(key string, value *Value) bool {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_SetProperty(\n\t\to.self, (*C.char)(keyPtr), C.int(len(key)), value.self,\n\t) == 1\n}\n\nfunc (o *Object) GetProperty(key string) *Value {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn newValue(o.engine, C.V8_Object_GetProperty(\n\t\to.self, (*C.char)(keyPtr), C.int(len(key)),\n\t))\n}\n\nfunc (o *Object) SetElement(index int, value *Value) bool {\n\treturn C.V8_Object_SetElement(\n\t\to.self, C.uint32_t(index), value.self,\n\t) == 1\n}\n\nfunc (o *Object) GetElement(index int) *Value {\n\treturn newValue(o.engine, C.V8_Object_GetElement(o.self, C.uint32_t(index)))\n}\n\nfunc (o *Object) GetPropertyAttributes(key string) PropertyAttribute {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn PropertyAttribute(C.V8_Object_GetPropertyAttributes(\n\t\to.self, (*C.char)(keyPtr), C.int(len(key)),\n\t))\n}\n\nfunc (o *Object) InternalFieldCount() int {\n\treturn int(C.V8_Object_InternalFieldCount(o.self))\n}\n\nfunc (o *Object) GetInternalField(index int) interface{} {\n\tdata := C.V8_Object_GetInternalField(o.self, C.int(index))\n\tif data == nil {\n\t\treturn nil\n\t}\n\treturn *(*interface{})(data)\n}\n\nfunc (o *Object) SetInternalField(index int, value interface{}) {\n\tC.V8_Object_SetInternalField(\n\t\to.self,\n\t\tC.int(index),\n\t\tunsafe.Pointer(&value),\n\t)\n\n\t\/\/ the value reference by object so the value can't destory by GC\n\to.internalFields = append(o.internalFields, value)\n\to.setOwner(o)\n}\n\nfunc (o *Object) SetAccessor(\n\tkey string,\n\tgetter AccessorGetterCallback,\n\tsetter AccessorSetterCallback,\n\tdata interface{},\n\tattribs PropertyAttribute,\n) {\n\to.setAccessor(&accessorInfo{\n\t\tkey:     key,\n\t\tgetter:  getter,\n\t\tsetter:  setter,\n\t\tdata:    data,\n\t\tattribs: attribs,\n\t})\n}\n\nfunc (o *Object) setAccessor(info *accessorInfo) {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&info.key)).Data)\n\tvar getterPointer, setterPointer unsafe.Pointer\n\tif info.getter != nil {\n\t\tgetterPointer = unsafe.Pointer(&info.getter)\n\t}\n\n\tif info.setter != nil {\n\t\tsetterPointer = unsafe.Pointer(&info.setter)\n\t}\n\n\to.accessor = info\n\to.setOwner(o)\n\n\tC.V8_Object_SetAccessor(\n\t\to.self,\n\t\t(*C.char)(keyPtr), C.int(len(info.key)),\n\t\tgetterPointer,\n\t\tsetterPointer,\n\t\tunsafe.Pointer(&info.data),\n\t\tC.int(info.attribs),\n\t)\n}\n\n\/\/ Sets a local property on this object bypassing interceptors and\n\/\/ overriding accessors or read-only properties.\n\/\/\n\/\/ Note that if the object has an interceptor the property will be set\n\/\/ locally, but since the interceptor takes precedence the local property\n\/\/ will only be returned if the interceptor doesn't return a value.\n\/\/\n\/\/ Note also that this only works for named properties.\nfunc (o *Object) ForceSetProperty(key string, value *Value, attribs PropertyAttribute) bool {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_ForceSetProperty(o.self,\n\t\t(*C.char)(keyPtr), C.int(len(key)), value.self, C.int(attribs),\n\t) == 1\n}\n\nfunc (o *Object) HasProperty(key string) bool {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_HasProperty(\n\t\to.self, (*C.char)(keyPtr), C.int(len(key)),\n\t) == 1\n}\n\nfunc (o *Object) DeleteProperty(key string) bool {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_DeleteProperty(\n\t\to.self, (*C.char)(keyPtr), C.int(len(key)),\n\t) == 1\n}\n\n\/\/ Delete a property on this object bypassing interceptors and\n\/\/ ignoring dont-delete attributes.\nfunc (o *Object) ForceDeleteProperty(key string) bool {\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_ForceDeleteProperty(\n\t\to.self, (*C.char)(keyPtr), C.int(len(key)),\n\t) == 1\n}\n\nfunc (o *Object) HasElement(index int) bool {\n\treturn C.V8_Object_HasElement(\n\t\to.self, C.uint32_t(index),\n\t) == 1\n}\n\nfunc (o *Object) DeleteElement(index int) bool {\n\treturn C.V8_Object_DeleteElement(\n\t\to.self, C.uint32_t(index),\n\t) == 1\n}\n\n\/\/ Returns an array containing the names of the enumerable properties\n\/\/ of this object, including properties from prototype objects.  The\n\/\/ array returned by this method contains the same values as would\n\/\/ be enumerated by a for-in statement over this object.\n\/\/\nfunc (o *Object) GetPropertyNames() *Array {\n\treturn newValue(o.engine, C.V8_Object_GetPropertyNames(o.self)).ToArray()\n}\n\n\/\/ This function has the same functionality as GetPropertyNames but\n\/\/ the returned array doesn't contain the names of properties from\n\/\/ prototype objects.\n\/\/\nfunc (o *Object) GetOwnPropertyNames() *Array {\n\treturn newValue(o.engine, C.V8_Object_GetOwnPropertyNames(o.self)).ToArray()\n}\n\n\/\/ Get the prototype object.  This does not skip objects marked to\n\/\/ be skipped by __proto__ and it does not consult the security\n\/\/ handler.\n\/\/\nfunc (o *Object) GetPrototype() *Object {\n\treturn newValue(o.engine, C.V8_Object_GetPrototype(o.self)).ToObject()\n}\n\n\/\/ Set the prototype object.  This does not skip objects marked to\n\/\/ be skipped by __proto__ and it does not consult the security\n\/\/ handler.\n\/\/\nfunc (o *Object) SetPrototype(proto *Object) bool {\n\treturn C.V8_Object_SetPrototype(o.self, proto.self) == 1\n}\n\nfunc (o *Object) SetHiddenValue(key string, value *Value) bool{\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_SetHiddenValue(o.self, (*C.char)(keyPtr), value.self) == 1\n}\n\nfunc (o *Object) DeleteHiddenValue(key string) bool{\n\tkeyPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&key)).Data)\n\treturn C.V8_Object_DeleteHiddenValue(o.self, (*C.char)(keyPtr)) == 1\n}\n\nfunc (o *Object) GetConstructorName() string{\n\treturn newValue(o.engine, C.V8_Object_GetConstructorName(o.self)).ToString()\n}\n\nfunc (o *Object) SetAlignedPointerInInternalField(index int, val_ptr unsafe.Pointer) {\n\tC.V8_Object_SetAlignedPointerInInternalField(o.self, C.int(index), val_ptr)\n}\n\nfunc (o *Object) GetAlignedPointerFromInternalField(index int) unsafe.Pointer{\n\treturn C.V8_Object_GetAlignedPointerFromInternalField(o.self, C.int(index))\n}\n\/\/ An instance of the built-in array constructor (ECMA-262, 15.4.2).\n\/\/\ntype Array struct {\n\t*Object\n}\n\nfunc (e *Engine) NewArray(length int) *Value {\n\treturn newValue(e, C.V8_NewArray(\n\t\te.self, C.int(length),\n\t))\n}\n\nfunc (a *Array) Length() int {\n\treturn int(C.V8_Array_Length(a.self))\n}\n\ntype RegExpFlags int\n\n\/\/ Regular expression flag bits. They can be or'ed to enable a set\n\/\/ of flags.\n\/\/\nconst (\n\tRF_None       RegExpFlags = 0\n\tRF_Global                 = 1\n\tRF_IgnoreCase             = 2\n\tRF_Multiline              = 4\n)\n\ntype RegExp struct {\n\t*Object\n\tpattern       string\n\tpatternCached bool\n\tflags         RegExpFlags\n\tflagsCached   bool\n}\n\n\/\/ Creates a regular expression from the given pattern string and\n\/\/ the flags bit field. May throw a JavaScript exception as\n\/\/ described in ECMA-262, 15.10.4.1.\n\/\/\n\/\/ For example,\n\/\/   NewRegExp(\"foo\", RF_Global | RF_Multiline)\n\/\/\n\/\/ is equivalent to evaluating \"\/foo\/gm\".\n\/\/\nfunc (e *Engine) NewRegExp(pattern string, flags RegExpFlags) *Value {\n\tpatternPtr := unsafe.Pointer((*reflect.StringHeader)(unsafe.Pointer(&pattern)).Data)\n\n\treturn newValue(e, C.V8_NewRegExp(\n\t\te.self, (*C.char)(patternPtr), C.int(len(pattern)), C.int(flags),\n\t))\n}\n\n\/\/ Returns the value of the source property: a string representing\n\/\/ the regular expression.\nfunc (r *RegExp) Pattern() string {\n\tif !r.patternCached {\n\t\tcstring := C.V8_RegExp_Pattern(r.self)\n\t\tr.pattern = C.GoString(cstring)\n\t\tr.patternCached = true\n\t\tC.free(unsafe.Pointer(cstring))\n\t}\n\treturn r.pattern\n}\n\n\/\/ Returns the flags bit field.\n\/\/\nfunc (r *RegExp) Flags() RegExpFlags {\n\tif !r.flagsCached {\n\t\tr.flags = RegExpFlags(C.V8_RegExp_Flags(r.self))\n\t\tr.flagsCached = true\n\t}\n\treturn r.flags\n}\n<|endoftext|>"}
{"text":"<commit_before>package cache\n\nimport (\n\t\"gondola\/log\"\n\t\"net\/url\"\n)\n\ntype BackendInitializer func(*url.URL) Backend\n\nvar (\n\tdefaultCacheUrl string\n\tbackends        = map[string]BackendInitializer{}\n\tcodecs          = map[string]*Codec{}\n)\n\ntype Backend interface {\n\tSet(key string, b []byte, timeout int) error\n\tGet(key string) ([]byte, error)\n\tGetMulti(keys []string) (map[string][]byte, error)\n\tDelete(key string) error\n\tClose() error\n}\n\ntype Codec struct {\n\tEncode func(v interface{}) ([]byte, error)\n\tDecode func(data []byte, v interface{}) error\n}\n\ntype Cache struct {\n\tPrefix  string\n\tBackend Backend\n\tCodec   *Codec\n}\n\nfunc (c *Cache) manipulatesKeys() bool {\n\treturn c.Prefix != \"\"\n}\n\nfunc (c *Cache) backendKey(key string) string {\n\treturn c.Prefix + key\n}\n\nfunc (c *Cache) frontendKey(key string) string {\n\tif c.Prefix != \"\" {\n\t\treturn key[len(c.Prefix):]\n\t}\n\treturn key\n}\n\n\/\/ Set stores the given object in the cache associated with the\n\/\/ given key. Timeout is the number of seconds until the item\n\/\/ expires. If the timeout is 0, the item is never expired and\n\/\/ might be only purged from cache when running out of space\nfunc (c *Cache) Set(key string, object interface{}, timeout int) {\n\tb, err := c.Codec.Encode(&object)\n\tif err != nil {\n\t\tlog.Errorf(\"Error encoding object for key %s: %s\", key, err)\n\t\treturn\n\t}\n\tc.SetBytes(key, b, timeout)\n}\n\n\/\/ Get returns the item assocciated with the given key\nfunc (c *Cache) Get(key string) interface{} {\n\tb := c.GetBytes(key)\n\tif b != nil {\n\t\tvar object interface{}\n\t\terr := c.Codec.Decode(b, &object)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error decoding object for key %s: %s\", key, err)\n\t\t}\n\t\treturn object\n\t}\n\treturn nil\n}\n\n\/\/ GetMulti returns several objects as a map[string]interface{}\n\/\/ in only one roundtrip to the cache\nfunc (c *Cache) GetMulti(keys []string) map[string]interface{} {\n\tif c.manipulatesKeys() {\n\t\tk := make([]string, len(keys))\n\t\tfor ii, v := range keys {\n\t\t\tk[ii] = c.backendKey(v)\n\t\t}\n\t\tkeys = k\n\t}\n\tdata, err := c.Backend.GetMulti(keys)\n\tif err != nil {\n\t\tlog.Errorf(\"Error querying cache for keys %v: %v\", keys, err)\n\t\treturn nil\n\t}\n\tobjects := make(map[string]interface{}, len(data))\n\tif c.manipulatesKeys() {\n\t\tfor k, v := range data {\n\t\t\tvar object interface{}\n\t\t\terr := c.Codec.Decode(v, &object)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error decoding object for key %s: %s\", k, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tobjects[c.frontendKey(k)] = object\n\t\t}\n\t} else {\n\t\tfor k, v := range data {\n\t\t\tvar object interface{}\n\t\t\terr := c.Codec.Decode(v, &object)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error decoding object for key %s: %s\", k, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tobjects[k] = object\n\t\t}\n\t}\n\treturn objects\n}\n\n\/\/ SetBytes stores the given byte array assocciated with\n\/\/ the given key. See the documentation for Set for an\n\/\/ explanation of the timeout parameter\nfunc (c *Cache) SetBytes(key string, b []byte, timeout int) {\n\tlog.Debugf(\"Setting key %s\", c.backendKey(key))\n\terr := c.Backend.Set(c.backendKey(key), b, timeout)\n\tif err != nil {\n\t\tlog.Errorf(\"Error setting cache key %s: %s\", key, err)\n\t}\n}\n\n\/\/ GetBytes returns the byte array assocciated with the given key\nfunc (c *Cache) GetBytes(key string) []byte {\n\tb, err := c.Backend.Get(c.backendKey(key))\n\tif err != nil {\n\t\tlog.Errorf(\"Error getting cache key %s: %s\", key, err)\n\t\treturn nil\n\t}\n\treturn b\n}\n\nfunc (c *Cache) Delete(key string) {\n\terr := c.Backend.Delete(c.backendKey(key))\n\tif err != nil {\n\t\tlog.Errorf(\"Error deleting cache key %s: %s\", key, err)\n\t}\n}\n\nfunc (c *Cache) Close() {\n\tc.Backend.Close()\n}\n\nfunc RegisterBackend(scheme string, f BackendInitializer) {\n\tbackends[scheme] = f\n}\n\nfunc RegisterCodec(name string, codec *Codec) {\n\tcodecs[name] = codec\n}\n\nfunc SetDefaultUrl(url string) {\n\tdefaultCacheUrl = url\n}\n\nfunc DefaultUrl() string {\n\treturn defaultCacheUrl\n}\n\nfunc New(cacheUrl string) *Cache {\n\tcache := &Cache{}\n\tvar query url.Values\n\tu, err := url.Parse(cacheUrl)\n\tif err != nil {\n\t\tif err != nil && cacheUrl != \"\" {\n\t\t\tlog.Errorf(\"Invalid cache URL '%s': %s\\n\", cacheUrl, err)\n\t\t}\n\t} else {\n\t\tquery = u.Query()\n\t}\n\tvar codec *Codec = nil\n\tif query != nil {\n\t\tcodecName := query.Get(\"codec\")\n\t\tif codecName != \"\" {\n\t\t\tif c, ok := codecs[codecName]; ok {\n\t\t\t\tcodec = c\n\t\t\t} else {\n\t\t\t\tlog.Errorf(\"Unknown cache codec name '%s'\\n\", codecName)\n\t\t\t}\n\t\t}\n\t\tcache.Prefix = query.Get(\"prefix\")\n\t}\n\tif codec == nil {\n\t\tcodec = &GobEncoder\n\t}\n\tcache.Codec = codec\n\tvar backendInitializer BackendInitializer\n\tif u != nil {\n\t\tbackendInitializer = backends[u.Scheme]\n\t\tif backendInitializer == nil {\n\t\t\tlog.Errorf(\"Unknown cache backend type '%s'\\n\", u.Scheme)\n\t\t}\n\t}\n\tif backendInitializer == nil {\n\t\tbackendInitializer = InitializeDummyBackend\n\t}\n\tcache.Backend = backendInitializer(u)\n\treturn cache\n}\n\nfunc NewDefault() *Cache {\n\treturn New(defaultCacheUrl)\n}\n<commit_msg>Better log messages<commit_after>package cache\n\nimport (\n\t\"gondola\/log\"\n\t\"net\/url\"\n)\n\ntype BackendInitializer func(*url.URL) Backend\n\nvar (\n\tdefaultCacheUrl string\n\tbackends        = map[string]BackendInitializer{}\n\tcodecs          = map[string]*Codec{}\n)\n\ntype Backend interface {\n\tSet(key string, b []byte, timeout int) error\n\tGet(key string) ([]byte, error)\n\tGetMulti(keys []string) (map[string][]byte, error)\n\tDelete(key string) error\n\tClose() error\n}\n\ntype Codec struct {\n\tEncode func(v interface{}) ([]byte, error)\n\tDecode func(data []byte, v interface{}) error\n}\n\ntype Cache struct {\n\tPrefix  string\n\tBackend Backend\n\tCodec   *Codec\n}\n\nfunc (c *Cache) manipulatesKeys() bool {\n\treturn c.Prefix != \"\"\n}\n\nfunc (c *Cache) backendKey(key string) string {\n\treturn c.Prefix + key\n}\n\nfunc (c *Cache) frontendKey(key string) string {\n\tif c.Prefix != \"\" {\n\t\treturn key[len(c.Prefix):]\n\t}\n\treturn key\n}\n\n\/\/ Set stores the given object in the cache associated with the\n\/\/ given key. Timeout is the number of seconds until the item\n\/\/ expires. If the timeout is 0, the item is never expired and\n\/\/ might be only purged from cache when running out of space\nfunc (c *Cache) Set(key string, object interface{}, timeout int) {\n\tb, err := c.Codec.Encode(&object)\n\tif err != nil {\n\t\tlog.Errorf(\"Error encoding object for key %s: %s\", key, err)\n\t\treturn\n\t}\n\tc.SetBytes(key, b, timeout)\n}\n\n\/\/ Get returns the item assocciated with the given key\nfunc (c *Cache) Get(key string) interface{} {\n\tb := c.GetBytes(key)\n\tif b != nil {\n\t\tvar object interface{}\n\t\terr := c.Codec.Decode(b, &object)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Error decoding object for key %s: %s\", key, err)\n\t\t}\n\t\treturn object\n\t}\n\treturn nil\n}\n\n\/\/ GetMulti returns several objects as a map[string]interface{}\n\/\/ in only one roundtrip to the cache\nfunc (c *Cache) GetMulti(keys []string) map[string]interface{} {\n\tif c.manipulatesKeys() {\n\t\tk := make([]string, len(keys))\n\t\tfor ii, v := range keys {\n\t\t\tk[ii] = c.backendKey(v)\n\t\t}\n\t\tkeys = k\n\t}\n\tdata, err := c.Backend.GetMulti(keys)\n\tif err != nil {\n\t\tlog.Errorf(\"Error querying cache for keys %v: %v\", keys, err)\n\t\treturn nil\n\t}\n\tobjects := make(map[string]interface{}, len(data))\n\tif c.manipulatesKeys() {\n\t\tfor k, v := range data {\n\t\t\tvar object interface{}\n\t\t\terr := c.Codec.Decode(v, &object)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error decoding object for key %s: %s\", k, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tobjects[c.frontendKey(k)] = object\n\t\t}\n\t} else {\n\t\tfor k, v := range data {\n\t\t\tvar object interface{}\n\t\t\terr := c.Codec.Decode(v, &object)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error decoding object for key %s: %s\", k, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tobjects[k] = object\n\t\t}\n\t}\n\treturn objects\n}\n\n\/\/ SetBytes stores the given byte array assocciated with\n\/\/ the given key. See the documentation for Set for an\n\/\/ explanation of the timeout parameter\nfunc (c *Cache) SetBytes(key string, b []byte, timeout int) {\n\tlog.Debugf(\"Setting key %s\", c.backendKey(key))\n\terr := c.Backend.Set(c.backendKey(key), b, timeout)\n\tif err != nil {\n\t\tlog.Errorf(\"Error setting cache key %s: %s\", key, err)\n\t}\n}\n\n\/\/ GetBytes returns the byte array assocciated with the given key\nfunc (c *Cache) GetBytes(key string) []byte {\n\tb, err := c.Backend.Get(c.backendKey(key))\n\tif err != nil {\n\t\tlog.Errorf(\"Error getting cache key %s: %s\", key, err)\n\t\treturn nil\n\t}\n\treturn b\n}\n\nfunc (c *Cache) Delete(key string) {\n\terr := c.Backend.Delete(c.backendKey(key))\n\tif err != nil {\n\t\tlog.Errorf(\"Error deleting cache key %s: %s\", key, err)\n\t}\n}\n\nfunc (c *Cache) Close() {\n\tc.Backend.Close()\n}\n\nfunc RegisterBackend(scheme string, f BackendInitializer) {\n\tbackends[scheme] = f\n}\n\nfunc RegisterCodec(name string, codec *Codec) {\n\tcodecs[name] = codec\n}\n\nfunc SetDefaultUrl(url string) {\n\tdefaultCacheUrl = url\n}\n\nfunc DefaultUrl() string {\n\treturn defaultCacheUrl\n}\n\nfunc New(cacheUrl string) *Cache {\n\tcache := &Cache{}\n\tvar query url.Values\n\tu, err := url.Parse(cacheUrl)\n\tif err != nil {\n\t\tif err != nil && cacheUrl != \"\" {\n\t\t\tlog.Errorf(\"Invalid cache URL %q: %s\\n\", cacheUrl, err)\n\t\t}\n\t} else {\n\t\tquery = u.Query()\n\t}\n\tvar codec *Codec = nil\n\tif query != nil {\n\t\tcodecName := query.Get(\"codec\")\n\t\tif codecName != \"\" {\n\t\t\tif c, ok := codecs[codecName]; ok {\n\t\t\t\tcodec = c\n\t\t\t} else {\n\t\t\t\tlog.Errorf(\"Unknown cache codec name %q\\n\", codecName)\n\t\t\t}\n\t\t}\n\t\tcache.Prefix = query.Get(\"prefix\")\n\t}\n\tif codec == nil {\n\t\tcodec = &GobEncoder\n\t}\n\tcache.Codec = codec\n\tvar backendInitializer BackendInitializer\n\tif u != nil {\n\t\tbackendInitializer = backends[u.Scheme]\n\t\tif backendInitializer == nil && cacheUrl != \"\" {\n\t\t\tlog.Errorf(\"Unknown cache backend type %q\\n\", u.Scheme)\n\t\t}\n\t}\n\tif backendInitializer == nil {\n\t\tbackendInitializer = InitializeDummyBackend\n\t}\n\tcache.Backend = backendInitializer(u)\n\treturn cache\n}\n\nfunc NewDefault() *Cache {\n\treturn New(defaultCacheUrl)\n}\n<|endoftext|>"}
{"text":"<commit_before>package cache\n\nimport (\n\t\"fmt\"\n\t\"hash\/fnv\"\n\t\"io\/ioutil\"\n\t\"os\"\n)\n\n\/\/ Hash returns the hash for an string\nfunc Hash(input string) (hash string) {\n\th := fnv.New32a()\n\th.Write([]byte(input))\n\treturn fmt.Sprint(h.Sum32())\n}\n\n\/\/ IsCached check if a hash is cached on a path\nfunc IsCached(path string, hash string) bool {\n\tfilename := path + \"\/\" + hash\n\tif _, err := os.Stat(filename); err == nil {\n\t\tfmt.Println(\"Caché exists : \" + filename)\n\t\treturn true\n\t}\n\tfmt.Println(\"Not cached : \" + filename)\n\treturn false\n}\n\n\/\/ Save saves the content to the caché\nfunc Save(path string, hash string, payload string) (err error) {\n\tfilename := path + \"\/\" + hash\n\terr = ioutil.WriteFile(filename, []byte(payload), 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Get gets the content from the caché\nfunc Get(path string, hash string) (data []byte, err error) {\n\tfilename := path + \"\/\" + hash\n\tdata, err = ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn data, err\n\t}\n\treturn data, nil\n}\n<commit_msg>Using filepath package<commit_after>package cache\n\nimport (\n\t\"fmt\"\n\t\"hash\/fnv\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\n\/\/ Hash returns the hash for an string\nfunc Hash(input string) (hash string) {\n\th := fnv.New32a()\n\th.Write([]byte(input))\n\treturn fmt.Sprint(h.Sum32())\n}\n\n\/\/ IsCached check if a hash is cached on a path\nfunc IsCached(path string, hash string) bool {\n\tfilename := filepath.Join(path, hash)\n\tif _, err := os.Stat(filename); err == nil {\n\t\tfmt.Println(\"Caché exists : \" + filename)\n\t\treturn true\n\t}\n\tfmt.Println(\"Not cached : \" + filename)\n\treturn false\n}\n\n\/\/ Save saves the content to the caché\nfunc Save(path string, hash string, payload string) (err error) {\n\tfilename := filepath.Join(path, hash)\n\terr = ioutil.WriteFile(filename, []byte(payload), 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Get gets the content from the caché\nfunc Get(path string, hash string) (data []byte, err error) {\n\tfilename := filepath.Join(path, hash)\n\tdata, err = ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn data, err\n\t}\n\treturn data, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cache\n\nimport (\n\t\"encoding\/gob\"\n\t\"golang.org\/x\/net\/context\"\n\t\"log\"\n\t\"time\"\n\n\t\"google.golang.org\/appengine\"\n\t\"google.golang.org\/appengine\/memcache\"\n)\n\n\/\/http:\/\/www.funcmain.com\/gob_encoding_an_interface\n\/\/http:\/\/stackoverflow.com\/questions\/13264555\/store-an-object-in-memcache-of-gae-in-go\n\ntype SlowRetrieve func(ctx context.Context) (interface{}, error)\n\nfunc Remember(ctx context.Context, key string, expiration time.Duration, p SlowRetrieve, disable ...bool) (interface{}, error) {\n\n\t\/\/For debugging, you can disable cache\n\tif len(disable) != 0 && disable[0] == true {\n\t\treturn p(ctx)\n\t}\n\n\t\/\/Check if item exists\n\tvar v interface{}\n\tif _, err := memcache.Gob.Get(ctx, key, &v); err == nil {\n\t\t\/\/Item exists in cache\n\t\tif appengine.IsDevAppServer() {\n\t\t\tlog.Println(\"\\x1b[36mFound in Cache key:\", key, \"\\x1b[39;49m\")\n\t\t}\n\t\treturn v, nil\n\t} else {\n\t\tif appengine.IsDevAppServer() {\n\t\t\tlog.Println(\"\\x1b[31mGrabbing from SlowRetrieve key:\", key, err, \"\\x1b[39;49m\")\n\t\t}\n\t}\n\n\t\/\/Item does not exist in cache so grab it from the persistent store\n\titemToStore, err := p(ctx)\n\tfunc(itemToStore interface{}) {\n\t\tdefer func() {\n\t\t\trecover()\n\t\t}()\n\t\tgob.Register(itemToStore)\n\t}(itemToStore)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/Store item in Cache\n\titem := &memcache.Item{\n\t\tKey:        key,\n\t\tObject:     &itemToStore,\n\t\tExpiration: expiration,\n\t}\n\n\terr = memcache.Gob.Set(ctx, item)\n\tif err != nil {\n\t\t\/\/Memcache storage failed\n\t\tif appengine.IsDevAppServer() {\n\t\t\tlog.Println(\"\\x1b[31mCould not store item to memcache key:\", key, err, itemToStore, \"\\x1b[39;49m\")\n\t\t}\n\t}\n\treturn itemToStore, nil\n}\n\n\/\/Delete key from memcache\nfunc Delete(ctx context.Context, key string) error {\n\treturn memcache.Delete(ctx, key)\n}\n\nfunc DeleteMulti(ctx context.Context, keys []string) error {\n\treturn memcache.DeleteMulti(ctx, keys)\n}\n<commit_msg>Added fresh parameter for caching.<commit_after>package cache\n\nimport (\n\t\"encoding\/gob\"\n\t\"golang.org\/x\/net\/context\"\n\t\"log\"\n\t\"time\"\n\n\t\"google.golang.org\/appengine\"\n\t\"google.golang.org\/appengine\/memcache\"\n)\n\n\/\/http:\/\/www.funcmain.com\/gob_encoding_an_interface\n\/\/http:\/\/stackoverflow.com\/questions\/13264555\/store-an-object-in-memcache-of-gae-in-go\n\ntype SlowRetrieve func(ctx context.Context) (interface{}, error)\n\n\/\/Options:\n\/\/param 1 (bool): disable caching. (Usually for debugging)\n\/\/Param 2 (bool): Obtain fresh copy. Ignore content in cache but store fresh copy in cache.\n\/\/NB: In order for Param 2 to be activated, param 1 must be false.\nfunc Remember(ctx context.Context, key string, expiration time.Duration, p SlowRetrieve, options ...bool) (interface{}, error) {\n\n\tdisableCache := false\n\tfresh := false\n\n\tif len(options) != 0 {\n\t\tdisableCache = options[0]\n\t\tif len(options) >= 2 {\n\t\t\tfresh = options[1]\n\t\t}\n\t}\n\n\t\/\/For debugging, you can disable cache\n\tif disableCache {\n\t\treturn p(ctx)\n\t}\n\n\tvar v interface{}\n\n\tif fresh {\n\t\tif appengine.IsDevAppServer() {\n\t\t\tlog.Println(\"\\x1b[31mGrabbing (fresh) from SlowRetrieve key:\", key, \"\\x1b[39;49m\")\n\t\t}\n\t\tgoto fresh\n\t}\n\n\t\/\/Check if item exists\n\tif _, err := memcache.Gob.Get(ctx, key, &v); err == nil {\n\t\t\/\/Item exists in cache\n\t\tif appengine.IsDevAppServer() {\n\t\t\tlog.Println(\"\\x1b[36mFound in Cache key:\", key, \"\\x1b[39;49m\")\n\t\t}\n\t\treturn v, nil\n\t} else {\n\t\tif appengine.IsDevAppServer() {\n\t\t\tlog.Println(\"\\x1b[31mGrabbing from SlowRetrieve key:\", key, err, \"\\x1b[39;49m\")\n\t\t}\n\t}\n\nfresh:\n\t\/\/Item does not exist in cache so grab it from the persistent store\n\titemToStore, err := p(ctx)\n\tfunc(itemToStore interface{}) {\n\t\tdefer func() {\n\t\t\trecover()\n\t\t}()\n\t\tgob.Register(itemToStore)\n\t}(itemToStore)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/Store item in Cache\n\titem := &memcache.Item{\n\t\tKey:        key,\n\t\tObject:     &itemToStore,\n\t\tExpiration: expiration,\n\t}\n\n\terr = memcache.Gob.Set(ctx, item)\n\tif err != nil {\n\t\t\/\/Memcache storage failed\n\t\tif appengine.IsDevAppServer() {\n\t\t\tlog.Println(\"\\x1b[31mCould not store item to memcache key:\", key, err, itemToStore, \"\\x1b[39;49m\")\n\t\t}\n\t}\n\treturn itemToStore, nil\n}\n\n\/\/Delete key from memcache\nfunc Delete(ctx context.Context, key string) error {\n\treturn memcache.Delete(ctx, key)\n}\n\nfunc DeleteMulti(ctx context.Context, keys []string) error {\n\treturn memcache.DeleteMulti(ctx, keys)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage cache\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sync\"\n\n\t\"github.com\/golang\/groupcache\/lru\"\n\t\"github.com\/pkg\/errors\"\n)\n\nconst (\n\tdefaultMaxLRUCacheEntry = 10\n\tdefaultMaxCacheFds      = 10\n)\n\ntype DirectoryCacheConfig struct {\n\tMaxLRUCacheEntry int  `toml:\"max_lru_cache_entry\"`\n\tMaxCacheFds      int  `toml:\"max_cache_fds\"`\n\tSyncAdd          bool `toml:\"sync_add\"`\n}\n\n\/\/ TODO: contents validation.\n\ntype BlobCache interface {\n\tAdd(key string, p []byte, opts ...Option)\n\tFetchAt(key string, offset int64, p []byte, opts ...Option) (n int, err error)\n}\n\ntype cacheOpt struct {\n\tdirect bool\n}\n\ntype Option func(o *cacheOpt) *cacheOpt\n\n\/\/ When Direct option is specified for FetchAt and Add methods, these operation\n\/\/ won't use on-memory caches. When you know that the targeting value won't be\n\/\/ used immediately, you can prevent the limited space of on-memory caches from\n\/\/ being polluted by these unimportant values.\nfunc Direct() Option {\n\treturn func(o *cacheOpt) *cacheOpt {\n\t\to.direct = true\n\t\treturn o\n\t}\n}\n\nfunc NewDirectoryCache(directory string, config DirectoryCacheConfig) (BlobCache, error) {\n\tmaxEntry := config.MaxLRUCacheEntry\n\tif maxEntry == 0 {\n\t\tmaxEntry = defaultMaxLRUCacheEntry\n\t}\n\tmaxFds := config.MaxCacheFds\n\tif maxFds == 0 {\n\t\tmaxFds = defaultMaxCacheFds\n\t}\n\tif err := os.MkdirAll(directory, os.ModePerm); err != nil {\n\t\treturn nil, err\n\t}\n\tdc := &directoryCache{\n\t\tcache:     newObjectCache(maxEntry),\n\t\tfileCache: newObjectCache(maxFds),\n\t\tdirectory: directory,\n\t\tbufPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn new(bytes.Buffer)\n\t\t\t},\n\t\t},\n\t}\n\tdc.cache.finalize = func(value interface{}) {\n\t\tdc.bufPool.Put(value)\n\t}\n\tdc.fileCache.finalize = func(value interface{}) {\n\t\tvalue.(*os.File).Close()\n\t}\n\tdc.syncAdd = config.SyncAdd\n\treturn dc, nil\n}\n\n\/\/ directoryCache is a cache implementation which backend is a directory.\ntype directoryCache struct {\n\tcache     *objectCache\n\tfileCache *objectCache\n\tdirectory string\n\n\tbufPool sync.Pool\n\n\tsyncAdd bool\n}\n\nfunc (dc *directoryCache) FetchAt(key string, offset int64, p []byte, opts ...Option) (n int, err error) {\n\topt := &cacheOpt{}\n\tfor _, o := range opts {\n\t\topt = o(opt)\n\t}\n\n\tif !opt.direct {\n\t\t\/\/ Get data from memory\n\t\tif b, done, ok := dc.cache.get(key); ok {\n\t\t\tdefer done()\n\t\t\tdata := b.(*bytes.Buffer).Bytes()\n\t\t\tif int64(len(data)) < offset {\n\t\t\t\treturn 0, fmt.Errorf(\"invalid offset %d exceeds chunk size %d\",\n\t\t\t\t\toffset, len(data))\n\t\t\t}\n\t\t\treturn copy(p, data[offset:]), nil\n\t\t}\n\n\t\t\/\/ Get data from disk. If the file is already opened, use it.\n\t\tif f, done, ok := dc.fileCache.get(key); ok {\n\t\t\tdefer done()\n\t\t\treturn f.(*os.File).ReadAt(p, offset)\n\t\t}\n\t}\n\n\t\/\/ Open the cache file and read the target region\n\t\/\/ TODO: If the target cache is write-in-progress, should we wait for the completion\n\t\/\/       or simply report the cache miss?\n\tfile, err := os.Open(dc.cachePath(key))\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"failed to open blob file for %q\", key)\n\t}\n\tif n, err = file.ReadAt(p, offset); err == io.EOF {\n\t\terr = nil\n\t}\n\n\t\/\/ Cache the opened file for future use. If \"direct\" option is specified, this\n\t\/\/ won't be done. This option is useful for preventing file cache from being\n\t\/\/ polluted by data that won't be accessed immediately.\n\tif opt.direct || !dc.fileCache.add(key, file) {\n\t\tfile.Close()\n\t}\n\n\t\/\/ TODO: should we cache the entire file data on memory?\n\t\/\/       but making I\/O (possibly huge) on every fetching\n\t\/\/       might be costly.\n\n\treturn n, err\n}\n\nfunc (dc *directoryCache) Add(key string, p []byte, opts ...Option) {\n\topt := &cacheOpt{}\n\tfor _, o := range opts {\n\t\topt = o(opt)\n\t}\n\n\tif !opt.direct {\n\t\t\/\/ Cache the passed data on memory. This enables to serve this data even\n\t\t\/\/ during writing it to the disk. If \"direct\" option is specified, this\n\t\t\/\/ won't be done. This option is useful for preventing memory cache from being\n\t\t\/\/ polluted by data that won't be accessed immediately.\n\t\tb := dc.bufPool.Get().(*bytes.Buffer)\n\t\tb.Reset()\n\t\tb.Write(p)\n\t\tif !dc.cache.add(key, b) {\n\t\t\tdc.bufPool.Put(b) \/\/ Already exists. No need to cache.\n\t\t}\n\t}\n\n\t\/\/ Cache the passed data to disk.\n\tb2 := dc.bufPool.Get().(*bytes.Buffer)\n\tb2.Reset()\n\tb2.Write(p)\n\taddFunc := func() {\n\t\tdefer dc.bufPool.Put(b2)\n\n\t\tvar (\n\t\t\tc   = dc.cachePath(key)\n\t\t\twip = dc.wipPath(key)\n\t\t)\n\t\tif _, err := os.Stat(wip); err == nil {\n\t\t\treturn \/\/ Write in progress\n\t\t}\n\t\tif _, err := os.Stat(c); err == nil {\n\t\t\treturn \/\/ Already exists.\n\t\t}\n\n\t\t\/\/ Write the contents to a temporary file\n\t\tif err := os.MkdirAll(filepath.Dir(wip), os.ModePerm); err != nil {\n\t\t\tfmt.Printf(\"Warning: Failed to Create blob cache directory %q: %v\\n\", c, err)\n\t\t\treturn\n\t\t}\n\t\twipfile, err := os.Create(wip)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Warning: failed to prepare temp file for storing cache %q\", key)\n\t\t\treturn\n\t\t}\n\t\tdefer func() {\n\t\t\twipfile.Close()\n\t\t\tos.Remove(wipfile.Name())\n\t\t}()\n\t\twant := b2.Len()\n\t\tif _, err := io.CopyN(wipfile, b2, int64(want)); err != nil {\n\t\t\tfmt.Printf(\"Warning: failed to write cache: %v\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Commit the cache contents\n\t\tif err := os.MkdirAll(filepath.Dir(c), os.ModePerm); err != nil {\n\t\t\tfmt.Printf(\"Warning: Failed to Create blob cache directory %q: %v\\n\", c, err)\n\t\t\treturn\n\t\t}\n\t\tif err := os.Rename(wipfile.Name(), c); err != nil {\n\t\t\tfmt.Printf(\"Warning: failed to commit cache to %q: %v\\n\", c, err)\n\t\t\treturn\n\t\t}\n\t\tfile, err := os.Open(c)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Warning: failed to open cache on %q: %v\\n\", c, err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Cache the opened file for future use. If \"direct\" option is specified, this\n\t\t\/\/ won't be done. This option is useful for preventing file cache from being\n\t\t\/\/ polluted by data that won't be accessed immediately.\n\t\tif opt.direct || !dc.fileCache.add(key, file) {\n\t\t\tfile.Close()\n\t\t}\n\t}\n\n\tif dc.syncAdd {\n\t\taddFunc()\n\t} else {\n\t\tgo addFunc()\n\t}\n}\n\nfunc (dc *directoryCache) cachePath(key string) string {\n\treturn filepath.Join(dc.directory, key[:2], key)\n}\n\nfunc (dc *directoryCache) wipPath(key string) string {\n\treturn filepath.Join(dc.directory, key[:2], \"w\", key)\n}\n\nfunc newObjectCache(maxEntries int) *objectCache {\n\toc := &objectCache{\n\t\tcache: lru.New(maxEntries),\n\t}\n\toc.cache.OnEvicted = func(key lru.Key, value interface{}) {\n\t\tvalue.(*object).release() \/\/ Decrease ref count incremented in add operation.\n\t}\n\treturn oc\n}\n\ntype objectCache struct {\n\tcache    *lru.Cache\n\tcacheMu  sync.Mutex\n\tfinalize func(interface{})\n}\n\nfunc (oc *objectCache) get(key string) (value interface{}, done func(), ok bool) {\n\toc.cacheMu.Lock()\n\tdefer oc.cacheMu.Unlock()\n\to, ok := oc.cache.Get(key)\n\tif !ok {\n\t\treturn nil, nil, false\n\t}\n\to.(*object).use()\n\treturn o.(*object).v, func() { o.(*object).release() }, true\n}\n\nfunc (oc *objectCache) add(key string, value interface{}) bool {\n\toc.cacheMu.Lock()\n\tdefer oc.cacheMu.Unlock()\n\tif _, ok := oc.cache.Get(key); ok {\n\t\treturn false \/\/ TODO: should we swap the object?\n\t}\n\to := &object{\n\t\tv:        value,\n\t\tfinalize: oc.finalize,\n\t}\n\to.use() \/\/ Keep this object having at least 1 ref count (will be decreased on eviction)\n\toc.cache.Add(key, o)\n\treturn true\n}\n\ntype object struct {\n\tv interface{}\n\n\trefCounts int64\n\tfinalize  func(interface{})\n\n\tmu sync.Mutex\n}\n\nfunc (o *object) use() {\n\to.mu.Lock()\n\tdefer o.mu.Unlock()\n\to.refCounts++\n}\n\nfunc (o *object) release() {\n\to.mu.Lock()\n\tdefer o.mu.Unlock()\n\to.refCounts--\n\tif o.refCounts <= 0 && o.finalize != nil {\n\t\t\/\/ nobody will refer this object\n\t\to.finalize(o.v)\n\t}\n}\n\nfunc NewMemoryCache() BlobCache {\n\treturn &memoryCache{\n\t\tmembuf: map[string]string{},\n\t}\n}\n\n\/\/ memoryCache is a cache implementation which backend is a memory.\ntype memoryCache struct {\n\tmembuf map[string]string \/\/ read-only []byte map is more ideal but we don't have it in golang...\n\tmu     sync.Mutex\n}\n\nfunc (mc *memoryCache) FetchAt(key string, offset int64, p []byte, opts ...Option) (n int, err error) {\n\tmc.mu.Lock()\n\tdefer mc.mu.Unlock()\n\n\tcache, ok := mc.membuf[key]\n\tif !ok {\n\t\treturn 0, fmt.Errorf(\"Missed cache: %q\", key)\n\t}\n\treturn copy(p, cache[offset:]), nil\n}\n\nfunc (mc *memoryCache) Add(key string, p []byte, opts ...Option) {\n\tmc.mu.Lock()\n\tdefer mc.mu.Unlock()\n\tmc.membuf[key] = string(p)\n}\n<commit_msg>Avoid race condition on writing cache contents to files<commit_after>\/*\n   Copyright The containerd Authors.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage cache\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sync\"\n\n\t\"github.com\/golang\/groupcache\/lru\"\n\t\"github.com\/pkg\/errors\"\n)\n\nconst (\n\tdefaultMaxLRUCacheEntry = 10\n\tdefaultMaxCacheFds      = 10\n)\n\ntype DirectoryCacheConfig struct {\n\tMaxLRUCacheEntry int  `toml:\"max_lru_cache_entry\"`\n\tMaxCacheFds      int  `toml:\"max_cache_fds\"`\n\tSyncAdd          bool `toml:\"sync_add\"`\n}\n\n\/\/ TODO: contents validation.\n\ntype BlobCache interface {\n\tAdd(key string, p []byte, opts ...Option)\n\tFetchAt(key string, offset int64, p []byte, opts ...Option) (n int, err error)\n}\n\ntype cacheOpt struct {\n\tdirect bool\n}\n\ntype Option func(o *cacheOpt) *cacheOpt\n\n\/\/ When Direct option is specified for FetchAt and Add methods, these operation\n\/\/ won't use on-memory caches. When you know that the targeting value won't be\n\/\/ used immediately, you can prevent the limited space of on-memory caches from\n\/\/ being polluted by these unimportant values.\nfunc Direct() Option {\n\treturn func(o *cacheOpt) *cacheOpt {\n\t\to.direct = true\n\t\treturn o\n\t}\n}\n\nfunc NewDirectoryCache(directory string, config DirectoryCacheConfig) (BlobCache, error) {\n\tmaxEntry := config.MaxLRUCacheEntry\n\tif maxEntry == 0 {\n\t\tmaxEntry = defaultMaxLRUCacheEntry\n\t}\n\tmaxFds := config.MaxCacheFds\n\tif maxFds == 0 {\n\t\tmaxFds = defaultMaxCacheFds\n\t}\n\tif err := os.MkdirAll(directory, os.ModePerm); err != nil {\n\t\treturn nil, err\n\t}\n\tdc := &directoryCache{\n\t\tcache:     newObjectCache(maxEntry),\n\t\tfileCache: newObjectCache(maxFds),\n\t\twipLock:   &namedLock{},\n\t\tdirectory: directory,\n\t\tbufPool: sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn new(bytes.Buffer)\n\t\t\t},\n\t\t},\n\t}\n\tdc.cache.finalize = func(value interface{}) {\n\t\tdc.bufPool.Put(value)\n\t}\n\tdc.fileCache.finalize = func(value interface{}) {\n\t\tvalue.(*os.File).Close()\n\t}\n\tdc.syncAdd = config.SyncAdd\n\treturn dc, nil\n}\n\n\/\/ directoryCache is a cache implementation which backend is a directory.\ntype directoryCache struct {\n\tcache     *objectCache\n\tfileCache *objectCache\n\tdirectory string\n\twipLock   *namedLock\n\n\tbufPool sync.Pool\n\n\tsyncAdd bool\n}\n\nfunc (dc *directoryCache) FetchAt(key string, offset int64, p []byte, opts ...Option) (n int, err error) {\n\topt := &cacheOpt{}\n\tfor _, o := range opts {\n\t\topt = o(opt)\n\t}\n\n\tif !opt.direct {\n\t\t\/\/ Get data from memory\n\t\tif b, done, ok := dc.cache.get(key); ok {\n\t\t\tdefer done()\n\t\t\tdata := b.(*bytes.Buffer).Bytes()\n\t\t\tif int64(len(data)) < offset {\n\t\t\t\treturn 0, fmt.Errorf(\"invalid offset %d exceeds chunk size %d\",\n\t\t\t\t\toffset, len(data))\n\t\t\t}\n\t\t\treturn copy(p, data[offset:]), nil\n\t\t}\n\n\t\t\/\/ Get data from disk. If the file is already opened, use it.\n\t\tif f, done, ok := dc.fileCache.get(key); ok {\n\t\t\tdefer done()\n\t\t\treturn f.(*os.File).ReadAt(p, offset)\n\t\t}\n\t}\n\n\t\/\/ Open the cache file and read the target region\n\t\/\/ TODO: If the target cache is write-in-progress, should we wait for the completion\n\t\/\/       or simply report the cache miss?\n\tfile, err := os.Open(dc.cachePath(key))\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"failed to open blob file for %q\", key)\n\t}\n\tif n, err = file.ReadAt(p, offset); err == io.EOF {\n\t\terr = nil\n\t}\n\n\t\/\/ Cache the opened file for future use. If \"direct\" option is specified, this\n\t\/\/ won't be done. This option is useful for preventing file cache from being\n\t\/\/ polluted by data that won't be accessed immediately.\n\tif opt.direct || !dc.fileCache.add(key, file) {\n\t\tfile.Close()\n\t}\n\n\t\/\/ TODO: should we cache the entire file data on memory?\n\t\/\/       but making I\/O (possibly huge) on every fetching\n\t\/\/       might be costly.\n\n\treturn n, err\n}\n\nfunc (dc *directoryCache) Add(key string, p []byte, opts ...Option) {\n\topt := &cacheOpt{}\n\tfor _, o := range opts {\n\t\topt = o(opt)\n\t}\n\n\tif !opt.direct {\n\t\t\/\/ Cache the passed data on memory. This enables to serve this data even\n\t\t\/\/ during writing it to the disk. If \"direct\" option is specified, this\n\t\t\/\/ won't be done. This option is useful for preventing memory cache from being\n\t\t\/\/ polluted by data that won't be accessed immediately.\n\t\tb := dc.bufPool.Get().(*bytes.Buffer)\n\t\tb.Reset()\n\t\tb.Write(p)\n\t\tif !dc.cache.add(key, b) {\n\t\t\tdc.bufPool.Put(b) \/\/ Already exists. No need to cache.\n\t\t}\n\t}\n\n\t\/\/ Cache the passed data to disk.\n\tb2 := dc.bufPool.Get().(*bytes.Buffer)\n\tb2.Reset()\n\tb2.Write(p)\n\taddFunc := func() {\n\t\tdefer dc.bufPool.Put(b2)\n\n\t\tvar (\n\t\t\tc   = dc.cachePath(key)\n\t\t\twip = dc.wipPath(key)\n\t\t)\n\n\t\tdc.wipLock.lock(key)\n\t\tif _, err := os.Stat(wip); err == nil {\n\t\t\tdc.wipLock.unlock(key)\n\t\t\treturn \/\/ Write in progress\n\t\t}\n\t\tif _, err := os.Stat(c); err == nil {\n\t\t\tdc.wipLock.unlock(key)\n\t\t\treturn \/\/ Already exists.\n\t\t}\n\n\t\t\/\/ Write the contents to a temporary file\n\t\tif err := os.MkdirAll(filepath.Dir(wip), os.ModePerm); err != nil {\n\t\t\tfmt.Printf(\"Warning: Failed to Create blob cache directory %q: %v\\n\", c, err)\n\t\t\tdc.wipLock.unlock(key)\n\t\t\treturn\n\t\t}\n\t\twipfile, err := os.Create(wip)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Warning: failed to prepare temp file for storing cache %q\", key)\n\t\t\tdc.wipLock.unlock(key)\n\t\t\treturn\n\t\t}\n\t\tdc.wipLock.unlock(key)\n\n\t\tdefer func() {\n\t\t\twipfile.Close()\n\t\t\tos.Remove(wipfile.Name())\n\t\t}()\n\t\twant := b2.Len()\n\t\tif _, err := io.CopyN(wipfile, b2, int64(want)); err != nil {\n\t\t\tfmt.Printf(\"Warning: failed to write cache: %v\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Commit the cache contents\n\t\tif err := os.MkdirAll(filepath.Dir(c), os.ModePerm); err != nil {\n\t\t\tfmt.Printf(\"Warning: Failed to Create blob cache directory %q: %v\\n\", c, err)\n\t\t\treturn\n\t\t}\n\t\tif err := os.Rename(wipfile.Name(), c); err != nil {\n\t\t\tfmt.Printf(\"Warning: failed to commit cache to %q: %v\\n\", c, err)\n\t\t\treturn\n\t\t}\n\t\tfile, err := os.Open(c)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Warning: failed to open cache on %q: %v\\n\", c, err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Cache the opened file for future use. If \"direct\" option is specified, this\n\t\t\/\/ won't be done. This option is useful for preventing file cache from being\n\t\t\/\/ polluted by data that won't be accessed immediately.\n\t\tif opt.direct || !dc.fileCache.add(key, file) {\n\t\t\tfile.Close()\n\t\t}\n\t}\n\n\tif dc.syncAdd {\n\t\taddFunc()\n\t} else {\n\t\tgo addFunc()\n\t}\n}\n\nfunc (dc *directoryCache) cachePath(key string) string {\n\treturn filepath.Join(dc.directory, key[:2], key)\n}\n\nfunc (dc *directoryCache) wipPath(key string) string {\n\treturn filepath.Join(dc.directory, key[:2], \"w\", key)\n}\n\ntype namedLock struct {\n\tmuMap  map[string]*sync.Mutex\n\trefMap map[string]int\n\n\tmu sync.Mutex\n}\n\nfunc (nl *namedLock) lock(name string) {\n\tnl.mu.Lock()\n\tif nl.muMap == nil {\n\t\tnl.muMap = make(map[string]*sync.Mutex)\n\t}\n\tif nl.refMap == nil {\n\t\tnl.refMap = make(map[string]int)\n\t}\n\tif _, ok := nl.muMap[name]; !ok {\n\t\tnl.muMap[name] = &sync.Mutex{}\n\t}\n\tmu := nl.muMap[name]\n\tnl.refMap[name]++\n\tnl.mu.Unlock()\n\tmu.Lock()\n}\n\nfunc (nl *namedLock) unlock(name string) {\n\tnl.mu.Lock()\n\tmu := nl.muMap[name]\n\tnl.refMap[name]--\n\tif nl.refMap[name] <= 0 {\n\t\tdelete(nl.muMap, name)\n\t\tdelete(nl.refMap, name)\n\t}\n\tnl.mu.Unlock()\n\tmu.Unlock()\n}\n\nfunc newObjectCache(maxEntries int) *objectCache {\n\toc := &objectCache{\n\t\tcache: lru.New(maxEntries),\n\t}\n\toc.cache.OnEvicted = func(key lru.Key, value interface{}) {\n\t\tvalue.(*object).release() \/\/ Decrease ref count incremented in add operation.\n\t}\n\treturn oc\n}\n\ntype objectCache struct {\n\tcache    *lru.Cache\n\tcacheMu  sync.Mutex\n\tfinalize func(interface{})\n}\n\nfunc (oc *objectCache) get(key string) (value interface{}, done func(), ok bool) {\n\toc.cacheMu.Lock()\n\tdefer oc.cacheMu.Unlock()\n\to, ok := oc.cache.Get(key)\n\tif !ok {\n\t\treturn nil, nil, false\n\t}\n\to.(*object).use()\n\treturn o.(*object).v, func() { o.(*object).release() }, true\n}\n\nfunc (oc *objectCache) add(key string, value interface{}) bool {\n\toc.cacheMu.Lock()\n\tdefer oc.cacheMu.Unlock()\n\tif _, ok := oc.cache.Get(key); ok {\n\t\treturn false \/\/ TODO: should we swap the object?\n\t}\n\to := &object{\n\t\tv:        value,\n\t\tfinalize: oc.finalize,\n\t}\n\to.use() \/\/ Keep this object having at least 1 ref count (will be decreased on eviction)\n\toc.cache.Add(key, o)\n\treturn true\n}\n\ntype object struct {\n\tv interface{}\n\n\trefCounts int64\n\tfinalize  func(interface{})\n\n\tmu sync.Mutex\n}\n\nfunc (o *object) use() {\n\to.mu.Lock()\n\tdefer o.mu.Unlock()\n\to.refCounts++\n}\n\nfunc (o *object) release() {\n\to.mu.Lock()\n\tdefer o.mu.Unlock()\n\to.refCounts--\n\tif o.refCounts <= 0 && o.finalize != nil {\n\t\t\/\/ nobody will refer this object\n\t\to.finalize(o.v)\n\t}\n}\n\nfunc NewMemoryCache() BlobCache {\n\treturn &memoryCache{\n\t\tmembuf: map[string]string{},\n\t}\n}\n\n\/\/ memoryCache is a cache implementation which backend is a memory.\ntype memoryCache struct {\n\tmembuf map[string]string \/\/ read-only []byte map is more ideal but we don't have it in golang...\n\tmu     sync.Mutex\n}\n\nfunc (mc *memoryCache) FetchAt(key string, offset int64, p []byte, opts ...Option) (n int, err error) {\n\tmc.mu.Lock()\n\tdefer mc.mu.Unlock()\n\n\tcache, ok := mc.membuf[key]\n\tif !ok {\n\t\treturn 0, fmt.Errorf(\"Missed cache: %q\", key)\n\t}\n\treturn copy(p, cache[offset:]), nil\n}\n\nfunc (mc *memoryCache) Add(key string, p []byte, opts ...Option) {\n\tmc.mu.Lock()\n\tdefer mc.mu.Unlock()\n\tmc.membuf[key] = string(p)\n}\n<|endoftext|>"}
{"text":"<commit_before>package cache\n\nimport \"time\"\n\ntype Backend int\n\nconst (\n    INMEMORY = iota\n    REDIS\n)\n\ntype Store interface {\n    \/\/ Get retrieves item from cache, i.e., (item, true).\n    \/\/ If the key is not found, return (nil, false).\n    Get(key string) (interface{}, error)\n\n    \/\/ Set sets item to cache.\n    \/\/ If the key exists, replace the item.\n    Set(key string, value interface{}, expire time.Duration) error\n\n    \/\/ Delete removes item from cache.\n    \/\/ If the key does not exist, do nothing.\n    Delete(key string) error\n\n    \/\/ Clear all items from cache.\n    Clear() error\n}\n<commit_msg>Update<commit_after>package cache\n\nimport (\n    \"time\"\n    \"errors\"\n)\n\ntype Backend int\n\nconst (\n    MEMORY = iota\n    REDIS\n)\n\nconst (\n    DEFAULT = time.Duration(0)\n    FOREVER = time.Duration(-1)\n)\n\nvar ErrCacheMiss = errors.New(\"cache missing\")\n\ntype Store interface {\n    \/\/ Get retrieves item from cache, and return nil.\n    \/\/ If the key is not found, return ErrCacheMiss.\n    \/\/ Value must be a pointer.\n    Get(key string, ptr interface{}) error\n\n    \/\/ Set sets item to cache.\n    \/\/ If the key exists, replace the item.\n    Set(key string, value interface{}, expire time.Duration) error\n\n    \/\/ Delete removes item from cache.\n    \/\/ If the key does not exist, do nothing.\n    Delete(key string) error\n\n    \/\/ Clear all items from\n    Clear() error\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/fzzy\/radix\/extra\/pool\"\n\t\"github.com\/fzzy\/radix\/redis\"\n\t\"github.com\/minotar\/minecraft\"\n\t\"image\/png\"\n)\n\ntype CacheRedis struct {\n\tClient *redis.Client\n\tPool   *pool.Pool\n}\n\nfunc (c *CacheRedis) setup() {\n\tpool, err := pool.NewPool(\"tcp\", config.Redis.Address, config.Redis.PoolSize)\n\tif err != nil {\n\t\tlog.Error(\"Error connecting to redis database\")\n\t\treturn\n\t}\n\n\tc.Pool = pool\n\tclient, err := c.Pool.Get()\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\tdefer c.Pool.Put(client)\n\n\t_ = client.Cmd(\"AUTH\", config.Redis.Auth)\n\n\tlog.Info(\"Loaded Redis cache (pool: \" + fmt.Sprintf(\"%v\", config.Redis.PoolSize) + \")\")\n}\n\nfunc (c *CacheRedis) has(username string) bool {\n\tclient, err := c.Pool.Get()\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\tdefer c.Pool.Put(client)\n\n\tres := client.Cmd(\"EXISTS\", config.Redis.Prefix+username)\n\n\texists, err := res.Bool()\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn false\n\t}\n\n\treturn exists\n}\n\nfunc (c *CacheRedis) pull(username string) minecraft.Skin {\n\tclient, err := c.Pool.Get()\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\tdefer c.Pool.Put(client)\n\n\tresp := client.Cmd(\"GET\", config.Redis.Prefix+username)\n\n\tskin, err := getSkinFromReply(resp)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\n\t\tc.remove(username)\n\t\tchar, _ := minecraft.FetchSkinForChar()\n\n\t\treturn char\n\t}\n\n\treturn skin\n}\n\nfunc (c *CacheRedis) add(username string, skin minecraft.Skin) {\n\tclient, err := c.Pool.Get()\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\tdefer c.Pool.Put(client)\n\n\tskinBuf := new(bytes.Buffer)\n\t_ = png.Encode(skinBuf, skin.Image)\n\n\t_ = client.Cmd(\"SETEX\", \"skins:\"+username, config.Redis.Ttl, skinBuf.Bytes())\n}\n\nfunc (c *CacheRedis) remove(username string) {\n\tclient, err := c.Pool.Get()\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\tdefer c.Pool.Put(client)\n\n\t_ = client.Cmd(\"DEL\", config.Redis.Prefix+username)\n}\n\nfunc getSkinFromReply(resp *redis.Reply) (minecraft.Skin, error) {\n\trespBytes, respErr := resp.Bytes()\n\tif respErr != nil {\n\t\treturn minecraft.Skin{}, respErr\n\t}\n\n\timgBuf := bytes.NewBuffer(respBytes)\n\n\tskin, skinErr := minecraft.DecodeSkin(imgBuf)\n\tif skinErr != nil {\n\t\treturn minecraft.Skin{}, skinErr\n\t}\n\n\treturn skin, nil\n}\n<commit_msg>Auth before every command<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/fzzy\/radix\/extra\/pool\"\n\t\"github.com\/fzzy\/radix\/redis\"\n\t\"github.com\/minotar\/minecraft\"\n\t\"image\/png\"\n)\n\ntype CacheRedis struct {\n\tClient *redis.Client\n\tPool   *pool.Pool\n}\n\nfunc (c *CacheRedis) setup() {\n\tpool, err := pool.NewPool(\"tcp\", config.Redis.Address, config.Redis.PoolSize)\n\tif err != nil {\n\t\tlog.Error(\"Error connecting to redis database\")\n\t\treturn\n\t}\n\n\tc.Pool = pool\n\tclient, err := c.Pool.Get()\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\tdefer c.Pool.Put(client)\n\n\tlog.Info(\"Loaded Redis cache (pool: \" + fmt.Sprintf(\"%v\", config.Redis.PoolSize) + \")\")\n}\n\nfunc (c *CacheRedis) has(username string) bool {\n\tclient, err := c.Pool.Get()\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\tdefer c.Pool.Put(client)\n\n\t_ = client.Cmd(\"AUTH\", config.Redis.Auth)\n\tres := client.Cmd(\"EXISTS\", config.Redis.Prefix+username)\n\n\texists, err := res.Bool()\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn false\n\t}\n\n\treturn exists\n}\n\nfunc (c *CacheRedis) pull(username string) minecraft.Skin {\n\tclient, err := c.Pool.Get()\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\tdefer c.Pool.Put(client)\n\n\t_ = client.Cmd(\"AUTH\", config.Redis.Auth)\n\tresp := client.Cmd(\"GET\", config.Redis.Prefix+username)\n\n\tskin, err := getSkinFromReply(resp)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\n\t\tc.remove(username)\n\t\tchar, _ := minecraft.FetchSkinForChar()\n\n\t\treturn char\n\t}\n\n\treturn skin\n}\n\nfunc (c *CacheRedis) add(username string, skin minecraft.Skin) {\n\tclient, err := c.Pool.Get()\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\tdefer c.Pool.Put(client)\n\n\tskinBuf := new(bytes.Buffer)\n\t_ = png.Encode(skinBuf, skin.Image)\n\n\t_ = client.Cmd(\"AUTH\", config.Redis.Auth)\n\t_ = client.Cmd(\"SETEX\", \"skins:\"+username, config.Redis.Ttl, skinBuf.Bytes())\n}\n\nfunc (c *CacheRedis) remove(username string) {\n\tclient, err := c.Pool.Get()\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t}\n\tdefer c.Pool.Put(client)\n\n\t_ = client.Cmd(\"AUTH\", config.Redis.Auth)\n\t_ = client.Cmd(\"DEL\", config.Redis.Prefix+username)\n}\n\nfunc getSkinFromReply(resp *redis.Reply) (minecraft.Skin, error) {\n\trespBytes, respErr := resp.Bytes()\n\tif respErr != nil {\n\t\treturn minecraft.Skin{}, respErr\n\t}\n\n\timgBuf := bytes.NewBuffer(respBytes)\n\n\tskin, skinErr := minecraft.DecodeSkin(imgBuf)\n\tif skinErr != nil {\n\t\treturn minecraft.Skin{}, skinErr\n\t}\n\n\treturn skin, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package rds\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/denverdino\/aliyungo\/common\"\n)\n\nfunc TestDBPostpaidClassicInstanceCreationAndDeletion(t *testing.T) {\n\n\tif TestIAmRich == false {\n\t\t\/\/ Avoid payment\n\t\treturn\n\t}\n\n\tclient := NewTestClient()\n\n\targs := CreateOrderArgs{\n\t\tRegionId:          TestRegionID,\n\t\tCommodityCode:     Bards,\n\t\tEngine:            MySQL,\n\t\tEngineVersion:     EngineVersion,\n\t\tDBInstanceClass:   DBInstanceClass,\n\t\tDBInstanceStorage: 10,\n\t\tQuantity:          1,\n\t\tPayType:           Postpaid,\n\t\tDBInstanceNetType: common.Intranet,\n\t\tResource:          DefaultResource,\n\t}\n\n\tresp, err := client.CreateOrder(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create db instance %v\", err)\n\t}\n\tinstanceId := resp.DBInstanceId\n\tt.Logf(\"Instance %s is created successfully.\", instanceId)\n\n\tarrtArgs := DescribeDBInstancesArgs{\n\t\tDBInstanceId: instanceId,\n\t}\n\tattrResp, err := client.DescribeDBInstanceAttribute(&arrtArgs)\n\tt.Logf(\"Instance: %++v  %v\", attrResp, err)\n\n\terr = client.WaitForInstance(instanceId, Running, 500)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create instance %s: %v\", instanceId, err)\n\t}\n\n\terr = client.DeleteInstance(instanceId)\n\n\tif err != nil {\n\t\tt.Errorf(\"Failed to delete instance %s: %v\", instanceId, err)\n\t}\n\tt.Logf(\"Instance %s is deleted successfully.\", instanceId)\n}\n\nfunc TestDBPrepaidInstanceCreation(t *testing.T) {\n\n\tif TestIAmRich == false {\n\t\t\/\/ Avoid payment\n\t\treturn\n\t}\n\n\tclient := NewTestClient()\n\n\targs := CreateOrderArgs{\n\t\tRegionId:          TestRegionID,\n\t\tCommodityCode:     Rds,\n\t\tEngine:            MySQL,\n\t\tEngineVersion:     EngineVersion,\n\t\tDBInstanceClass:   DBInstanceClass,\n\t\tDBInstanceStorage: 10,\n\t\tQuantity:          1,\n\t\tPayType:           Prepaid,\n\t\tDBInstanceNetType: common.Intranet,\n\t\tResource:          DefaultResource,\n\t\tTimeType:          common.Month,\n\t\tUsedTime:          1,\n\t\tAutoPay:           strconv.FormatBool(false),\n\t}\n\n\tresp, err := client.CreateOrder(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create db instance %v\", err)\n\t}\n\n\tinstanceId := resp.DBInstanceId\n\tt.Logf(\"Instance %s is created successfully.\", instanceId)\n\n\tarrtArgs := DescribeDBInstancesArgs{\n\t\tDBInstanceId: instanceId,\n\t}\n\tattrResp, err := client.DescribeDBInstanceAttribute(&arrtArgs)\n\tt.Logf(\"Instance: %++v  %v\", attrResp, err)\n\n\terr = client.WaitForInstance(instanceId, Running, 500)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create instance %s: %v\", instanceId, err)\n\t}\n\tt.Logf(\"Instance %s is running successfully.\", instanceId)\n}\n\nfunc TestDBPostpaidVpcInstanceCreationAndDeletion(t *testing.T) {\n\n\tif TestIAmRich == false {\n\t\t\/\/ Avoid payment\n\t\treturn\n\t}\n\n\tclient := NewTestClient()\n\n\targs := CreateOrderArgs{\n\t\tRegionId:            TestRegionID,\n\t\tZoneId:              ZoneId,\n\t\tCommodityCode:       Bards,\n\t\tEngine:              MySQL,\n\t\tEngineVersion:       EngineVersion,\n\t\tDBInstanceClass:     DBInstanceClass,\n\t\tDBInstanceStorage:   10,\n\t\tQuantity:            1,\n\t\tPayType:             Postpaid,\n\t\tDBInstanceNetType:   common.Intranet,\n\t\tInstanceNetworkType: common.VPC,\n\t\tVPCId:               VPCId,\n\t\tVSwitchId:           VSwitchId,\n\t\tSecurityIPList:      \"127.0.0.1\",\n\t\tResource:            DefaultResource,\n\t}\n\n\tresp, err := client.CreateOrder(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create db instance %v\", err)\n\t}\n\tinstanceId := resp.DBInstanceId\n\tt.Logf(\"Instance %s is created successfully.\", instanceId)\n\n\tarrtArgs := DescribeDBInstancesArgs{\n\t\tDBInstanceId: instanceId,\n\t}\n\tattrResp, err := client.DescribeDBInstanceAttribute(&arrtArgs)\n\tt.Logf(\"Instance: %++v  %v\", attrResp, err)\n\n\terr = client.WaitForInstance(instanceId, Running, 600)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create instance %s: %v\", instanceId, err)\n\t}\n\n\terr = client.DeleteInstance(instanceId)\n\n\tif err != nil {\n\t\tt.Errorf(\"Failed to delete instance %s: %v\", instanceId, err)\n\t}\n\tt.Logf(\"Instance %s is deleted successfully.\", instanceId)\n}\n\nfunc TestGetZonesByRegionId(t *testing.T) {\n\n\tclient := NewTestClient()\n\tresp, err := client.DescribeRegions()\n\tif err != nil {\n\t\tt.Errorf(\"Failed to describe rds regions %v\", err)\n\t}\n\n\tregions := resp.Regions.RDSRegion\n\tt.Logf(\"all regions %++v.\", regions)\n\n\tzoneIds := []string{}\n\tfor _, r := range regions {\n\t\tif strings.Contains(r.RegionId, string(TestRegionID)) {\n\t\t\tzoneIds = append(zoneIds, r.ZoneId)\n\t\t}\n\t}\n\tt.Logf(\"all zones %++v of current region.\", zoneIds)\n}\n\nfunc TestDatabaseCreationAndDeletion(t *testing.T) {\n\tclient := NewTestClient()\n\n\targs := CreateDatabaseArgs{\n\t\tDBInstanceId:     DBInstanceId,\n\t\tDBName:           DBName,\n\t\tCharacterSetName: \"utf8\",\n\t\tDBDescription:    \"test\",\n\t}\n\n\t_, err := client.CreateDatabase(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create db instance %v\", err)\n\t}\n\tt.Logf(\"Database %s is created successfully.\", DBName)\n\n\tq := [1]string{DBName}\n\terr = client.WaitForAllDatabase(DBInstanceId, q[:], Running, 600)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create database %s: %v\", DBName, err)\n\t}\n\n\terr = client.DeleteDatabase(DBInstanceId, DBName)\n\n\tif err != nil {\n\t\tt.Errorf(\"Failed to delete database %s: %v\", DBName, err)\n\t}\n\tt.Logf(\"Database %s is deleted successfully.\", DBName)\n}\n\nfunc TestAccountCreationAndDeletion(t *testing.T) {\n\tclient := NewTestClient()\n\n\targs := CreateAccountArgs{\n\t\tDBInstanceId:       DBInstanceId,\n\t\tAccountName:        AccountName,\n\t\tAccountPassword:    AccountPassword,\n\t\tAccountDescription: \"test\",\n\t}\n\n\t_, err := client.CreateAccount(&args)\n\terr = client.WaitForAccount(DBInstanceId, AccountName, Available, 600)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create account %s: %v\", AccountName, err)\n\t}\n\tt.Logf(\"Account %s is created successfully.\", AccountName)\n\n\tpargs := GrantAccountPrivilegeArgs{\n\t\tDBInstanceId:     DBInstanceId,\n\t\tAccountName:      AccountName,\n\t\tDBName:           DBName,\n\t\tAccountPrivilege: ReadWrite,\n\t}\n\t_, err = client.GrantAccountPrivilege(&pargs)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to grant privilege to account %v\", err)\n\t}\n\tt.Logf(\"Grant privilege to account %s successfully.\", AccountName)\n\n\terr = client.WaitForAccountPrivilege(DBInstanceId, AccountName, DBName, ReadWrite, 200)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to grant privilege to account %s: %v\", AccountName, err)\n\t}\n\tt.Logf(\"Grant privilege to account %s successfully.\", AccountName)\n\n\t_, err = client.DeleteAccount(DBInstanceId, AccountName)\n\n\tif err != nil {\n\t\tt.Errorf(\"Failed to delete account %s: %v\", AccountName, err)\n\t}\n\tt.Logf(\"Account %s is deleted successfully.\", AccountName)\n}\n\nfunc TestAccountAllocatePublicConnection(t *testing.T) {\n\tclient := NewTestClient()\n\n\targs := AllocateInstancePublicConnectionArgs{\n\t\tDBInstanceId:           DBInstanceId,\n\t\tConnectionStringPrefix: DBInstanceId + \"o\",\n\t\tPort: \"3306\",\n\t}\n\n\t_, err := client.AllocateInstancePublicConnection(&args)\n\terr = client.WaitForPublicConnection(DBInstanceId, 600)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to allocate public connection: %v\", err)\n\t}\n\tt.Logf(\"Allocate public connection successfully.\")\n\n}\n\nfunc TestModifyBackupPolicy(t *testing.T) {\n\tclient := NewTestClient()\n\n\tbargs := BackupPolicy{\n\t\tPreferredBackupTime:   \"00:00Z-01:00Z\",\n\t\tPreferredBackupPeriod: \"Wednesday\",\n\t\tBackupRetentionPeriod: 9,\n\t}\n\targs := ModifyBackupPolicyArgs{\n\t\tDBInstanceId: DBInstanceId,\n\t\tBackupPolicy: bargs,\n\t}\n\n\t_, err := client.ModifyBackupPolicy(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to modify backup policy: %v\", err)\n\t}\n\tt.Logf(\"Modify backup policy successfully.\")\n\n}\n\nfunc TestModifySecurityIps(t *testing.T) {\n\tclient := NewTestClient()\n\n\tsecurityIps := \"127.0.0.1\"\n\n\targs := ModifySecurityIpsArgs{\n\t\tDBInstanceId: DBInstanceId,\n\t\tSecurityIps:  securityIps,\n\t}\n\n\t_, err := client.ModifySecurityIps(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to modify security ips: %v\", err)\n\t}\n\tt.Logf(\"Modify security ips successfully.\")\n\n}\n\nfunc TestModifyDBInstanceSpec(t *testing.T) {\n\tclient := NewTestClient()\n\n\targs := ModifyDBInstanceSpecArgs{\n\t\tDBInstanceId:    DBInstanceUpgradeId,\n\t\tPayType:         Postpaid,\n\t\tDBInstanceClass: DBInstanceUpgradeClass,\n\t}\n\n\t_, err := client.ModifyDBInstanceSpec(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to modify db instance spec: %v\", err)\n\t}\n\n\terr = client.WaitForInstance(DBInstanceUpgradeId, Running, 600)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to modify db instance %s: %v\", DBInstanceUpgradeId, err)\n\t}\n\n\tarrtArgs := DescribeDBInstancesArgs{\n\t\tDBInstanceId: DBInstanceUpgradeId,\n\t}\n\tattrResp, err := client.DescribeDBInstanceAttribute(&arrtArgs)\n\tt.Logf(\"Instance: %++v  %v\", attrResp, err)\n\n\tif attrResp.Items.DBInstanceAttribute[0].DBInstanceClass != DBInstanceUpgradeClass {\n\t\tt.Errorf(\"Failed to modify db instance spec: %v\", err)\n\t}\n\n\tt.Logf(\"Modify db instance spec successfully.\")\n}\n\nfunc TestClient_DescribeRegions(t *testing.T) {\n\tclient := NewTestClientForDebug()\n\tclient.SetSecurityToken(TestSecurityToken)\n\n\tregions, err := client.DescribeRegions()\n\tif err != nil {\n\t\tt.Fatalf(\"Error %++v\", err)\n\t} else {\n\t\tt.Logf(\"Result = %++v\", regions)\n\t}\n}\n<commit_msg>fix rds test issue<commit_after>package rds\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/denverdino\/aliyungo\/common\"\n)\n\nfunc TestDBPostpaidClassicInstanceCreationAndDeletion(t *testing.T) {\n\n\tif TestIAmRich == false {\n\t\t\/\/ Avoid payment\n\t\treturn\n\t}\n\n\tclient := NewTestClient()\n\n\targs := CreateOrderArgs{\n\t\tRegionId:          TestRegionID,\n\t\tCommodityCode:     Bards,\n\t\tEngine:            MySQL,\n\t\tEngineVersion:     EngineVersion,\n\t\tDBInstanceClass:   DBInstanceClass,\n\t\tDBInstanceStorage: 10,\n\t\tQuantity:          1,\n\t\tPayType:           Postpaid,\n\t\tDBInstanceNetType: common.Intranet,\n\t\tResource:          DefaultResource,\n\t}\n\n\tresp, err := client.CreateOrder(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create db instance %v\", err)\n\t}\n\tinstanceId := resp.DBInstanceId\n\tt.Logf(\"Instance %s is created successfully.\", instanceId)\n\n\tarrtArgs := DescribeDBInstanceAttributeArgs{\n\t\tDBInstanceId: instanceId,\n\t}\n\tattrResp, err := client.DescribeDBInstanceAttribute(&arrtArgs)\n\tt.Logf(\"Instance: %++v  %v\", attrResp, err)\n\n\terr = client.WaitForInstance(instanceId, Running, 500)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create instance %s: %v\", instanceId, err)\n\t}\n\n\terr = client.DeleteInstance(instanceId)\n\n\tif err != nil {\n\t\tt.Errorf(\"Failed to delete instance %s: %v\", instanceId, err)\n\t}\n\tt.Logf(\"Instance %s is deleted successfully.\", instanceId)\n}\n\nfunc TestDBPrepaidInstanceCreation(t *testing.T) {\n\n\tif TestIAmRich == false {\n\t\t\/\/ Avoid payment\n\t\treturn\n\t}\n\n\tclient := NewTestClient()\n\n\targs := CreateOrderArgs{\n\t\tRegionId:          TestRegionID,\n\t\tCommodityCode:     Rds,\n\t\tEngine:            MySQL,\n\t\tEngineVersion:     EngineVersion,\n\t\tDBInstanceClass:   DBInstanceClass,\n\t\tDBInstanceStorage: 10,\n\t\tQuantity:          1,\n\t\tPayType:           Prepaid,\n\t\tDBInstanceNetType: common.Intranet,\n\t\tResource:          DefaultResource,\n\t\tTimeType:          common.Month,\n\t\tUsedTime:          1,\n\t\tAutoPay:           strconv.FormatBool(false),\n\t}\n\n\tresp, err := client.CreateOrder(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create db instance %v\", err)\n\t}\n\n\tinstanceId := resp.DBInstanceId\n\tt.Logf(\"Instance %s is created successfully.\", instanceId)\n\n\tarrtArgs := DescribeDBInstanceAttributeArgs{\n\t\tDBInstanceId: instanceId,\n\t}\n\tattrResp, err := client.DescribeDBInstanceAttribute(&arrtArgs)\n\tt.Logf(\"Instance: %++v  %v\", attrResp, err)\n\n\terr = client.WaitForInstance(instanceId, Running, 500)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create instance %s: %v\", instanceId, err)\n\t}\n\tt.Logf(\"Instance %s is running successfully.\", instanceId)\n}\n\nfunc TestDBPostpaidVpcInstanceCreationAndDeletion(t *testing.T) {\n\n\tif TestIAmRich == false {\n\t\t\/\/ Avoid payment\n\t\treturn\n\t}\n\n\tclient := NewTestClient()\n\n\targs := CreateOrderArgs{\n\t\tRegionId:            TestRegionID,\n\t\tZoneId:              ZoneId,\n\t\tCommodityCode:       Bards,\n\t\tEngine:              MySQL,\n\t\tEngineVersion:       EngineVersion,\n\t\tDBInstanceClass:     DBInstanceClass,\n\t\tDBInstanceStorage:   10,\n\t\tQuantity:            1,\n\t\tPayType:             Postpaid,\n\t\tDBInstanceNetType:   common.Intranet,\n\t\tInstanceNetworkType: common.VPC,\n\t\tVPCId:               VPCId,\n\t\tVSwitchId:           VSwitchId,\n\t\tSecurityIPList:      \"127.0.0.1\",\n\t\tResource:            DefaultResource,\n\t}\n\n\tresp, err := client.CreateOrder(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create db instance %v\", err)\n\t}\n\tinstanceId := resp.DBInstanceId\n\tt.Logf(\"Instance %s is created successfully.\", instanceId)\n\n\tarrtArgs := DescribeDBInstanceAttributeArgs{\n\t\tDBInstanceId: instanceId,\n\t}\n\tattrResp, err := client.DescribeDBInstanceAttribute(&arrtArgs)\n\tt.Logf(\"Instance: %++v  %v\", attrResp, err)\n\n\terr = client.WaitForInstance(instanceId, Running, 600)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create instance %s: %v\", instanceId, err)\n\t}\n\n\terr = client.DeleteInstance(instanceId)\n\n\tif err != nil {\n\t\tt.Errorf(\"Failed to delete instance %s: %v\", instanceId, err)\n\t}\n\tt.Logf(\"Instance %s is deleted successfully.\", instanceId)\n}\n\nfunc TestGetZonesByRegionId(t *testing.T) {\n\n\tclient := NewTestClient()\n\tresp, err := client.DescribeRegions()\n\tif err != nil {\n\t\tt.Errorf(\"Failed to describe rds regions %v\", err)\n\t}\n\n\tregions := resp.Regions.RDSRegion\n\tt.Logf(\"all regions %++v.\", regions)\n\n\tzoneIds := []string{}\n\tfor _, r := range regions {\n\t\tif strings.Contains(r.RegionId, string(TestRegionID)) {\n\t\t\tzoneIds = append(zoneIds, r.ZoneId)\n\t\t}\n\t}\n\tt.Logf(\"all zones %++v of current region.\", zoneIds)\n}\n\nfunc TestDatabaseCreationAndDeletion(t *testing.T) {\n\tclient := NewTestClient()\n\n\targs := CreateDatabaseArgs{\n\t\tDBInstanceId:     DBInstanceId,\n\t\tDBName:           DBName,\n\t\tCharacterSetName: \"utf8\",\n\t\tDBDescription:    \"test\",\n\t}\n\n\t_, err := client.CreateDatabase(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create db instance %v\", err)\n\t}\n\tt.Logf(\"Database %s is created successfully.\", DBName)\n\n\tq := [1]string{DBName}\n\terr = client.WaitForAllDatabase(DBInstanceId, q[:], Running, 600)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create database %s: %v\", DBName, err)\n\t}\n\n\terr = client.DeleteDatabase(DBInstanceId, DBName)\n\n\tif err != nil {\n\t\tt.Errorf(\"Failed to delete database %s: %v\", DBName, err)\n\t}\n\tt.Logf(\"Database %s is deleted successfully.\", DBName)\n}\n\nfunc TestAccountCreationAndDeletion(t *testing.T) {\n\tclient := NewTestClient()\n\n\targs := CreateAccountArgs{\n\t\tDBInstanceId:       DBInstanceId,\n\t\tAccountName:        AccountName,\n\t\tAccountPassword:    AccountPassword,\n\t\tAccountDescription: \"test\",\n\t}\n\n\t_, err := client.CreateAccount(&args)\n\terr = client.WaitForAccount(DBInstanceId, AccountName, Available, 600)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create account %s: %v\", AccountName, err)\n\t}\n\tt.Logf(\"Account %s is created successfully.\", AccountName)\n\n\tpargs := GrantAccountPrivilegeArgs{\n\t\tDBInstanceId:     DBInstanceId,\n\t\tAccountName:      AccountName,\n\t\tDBName:           DBName,\n\t\tAccountPrivilege: ReadWrite,\n\t}\n\t_, err = client.GrantAccountPrivilege(&pargs)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to grant privilege to account %v\", err)\n\t}\n\tt.Logf(\"Grant privilege to account %s successfully.\", AccountName)\n\n\terr = client.WaitForAccountPrivilege(DBInstanceId, AccountName, DBName, ReadWrite, 200)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to grant privilege to account %s: %v\", AccountName, err)\n\t}\n\tt.Logf(\"Grant privilege to account %s successfully.\", AccountName)\n\n\t_, err = client.DeleteAccount(DBInstanceId, AccountName)\n\n\tif err != nil {\n\t\tt.Errorf(\"Failed to delete account %s: %v\", AccountName, err)\n\t}\n\tt.Logf(\"Account %s is deleted successfully.\", AccountName)\n}\n\nfunc TestAccountAllocatePublicConnection(t *testing.T) {\n\tclient := NewTestClient()\n\n\targs := AllocateInstancePublicConnectionArgs{\n\t\tDBInstanceId:           DBInstanceId,\n\t\tConnectionStringPrefix: DBInstanceId + \"o\",\n\t\tPort: \"3306\",\n\t}\n\n\t_, err := client.AllocateInstancePublicConnection(&args)\n\terr = client.WaitForPublicConnection(DBInstanceId, 600)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to allocate public connection: %v\", err)\n\t}\n\tt.Logf(\"Allocate public connection successfully.\")\n\n}\n\nfunc TestModifyBackupPolicy(t *testing.T) {\n\tclient := NewTestClient()\n\n\tbargs := BackupPolicy{\n\t\tPreferredBackupTime:   \"00:00Z-01:00Z\",\n\t\tPreferredBackupPeriod: \"Wednesday\",\n\t\tBackupRetentionPeriod: 9,\n\t}\n\targs := ModifyBackupPolicyArgs{\n\t\tDBInstanceId: DBInstanceId,\n\t\tBackupPolicy: bargs,\n\t}\n\n\t_, err := client.ModifyBackupPolicy(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to modify backup policy: %v\", err)\n\t}\n\tt.Logf(\"Modify backup policy successfully.\")\n\n}\n\nfunc TestModifySecurityIps(t *testing.T) {\n\tclient := NewTestClient()\n\n\tsecurityIps := \"127.0.0.1\"\n\n\targs := ModifySecurityIpsArgs{\n\t\tDBInstanceId: DBInstanceId,\n\t\tSecurityIps:  securityIps,\n\t}\n\n\t_, err := client.ModifySecurityIps(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to modify security ips: %v\", err)\n\t}\n\tt.Logf(\"Modify security ips successfully.\")\n\n}\n\nfunc TestModifyDBInstanceSpec(t *testing.T) {\n\tclient := NewTestClient()\n\n\targs := ModifyDBInstanceSpecArgs{\n\t\tDBInstanceId:    DBInstanceUpgradeId,\n\t\tPayType:         Postpaid,\n\t\tDBInstanceClass: DBInstanceUpgradeClass,\n\t}\n\n\t_, err := client.ModifyDBInstanceSpec(&args)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to modify db instance spec: %v\", err)\n\t}\n\n\terr = client.WaitForInstance(DBInstanceUpgradeId, Running, 600)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to modify db instance %s: %v\", DBInstanceUpgradeId, err)\n\t}\n\n\tarrtArgs := DescribeDBInstanceAttributeArgs{\n\t\tDBInstanceId: DBInstanceUpgradeId,\n\t}\n\tattrResp, err := client.DescribeDBInstanceAttribute(&arrtArgs)\n\tt.Logf(\"Instance: %++v  %v\", attrResp, err)\n\n\tif attrResp.Items.DBInstanceAttribute[0].DBInstanceClass != DBInstanceUpgradeClass {\n\t\tt.Errorf(\"Failed to modify db instance spec: %v\", err)\n\t}\n\n\tt.Logf(\"Modify db instance spec successfully.\")\n}\n\nfunc TestClient_DescribeRegions(t *testing.T) {\n\tclient := NewTestClientForDebug()\n\tclient.SetSecurityToken(TestSecurityToken)\n\n\tregions, err := client.DescribeRegions()\n\tif err != nil {\n\t\tt.Fatalf(\"Error %++v\", err)\n\t} else {\n\t\tt.Logf(\"Result = %++v\", regions)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/juju\/ratelimit\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/tomnomnom\/linkheader\"\n)\n\nfunc PubSubMakeCallbackURL(baseURL, id string) string {\n\treturn baseURL + \"\/\" + id\n}\n\ntype PubSubSubscription struct {\n\tID          string\n\tHub         string\n\tTopic       string\n\tCallbackURL string\n\tCreatedAt   time.Time\n\tUpdatedAt   time.Time\n\tExpiresAt   *time.Time\n}\n\ntype PubSubState interface {\n\tAll() (subscriptions []PubSubSubscription, err error)\n\tAdd(hub, topic, baseURL string) (subscription *PubSubSubscription, oldCallbackURL string, err error)\n\tGet(hub, topic string) (subscription *PubSubSubscription, err error)\n\tGetByID(id string) (subscription *PubSubSubscription, err error)\n\tSet(hub, topic string, updatedAt, expiresAt time.Time) (err error)\n\tDel(hub, topic string) (err error)\n}\n\ntype PubSubMessageHandler func(id string, s *PubSubSubscription, rd io.ReadCloser)\n\ntype PubSubClient struct {\n\tCallbackURL string\n\tState       PubSubState\n\tOnMessage   PubSubMessageHandler\n}\n\nfunc NewPubSubClient(callbackURL string, state PubSubState, onMessage PubSubMessageHandler) *PubSubClient {\n\treturn &PubSubClient{\n\t\tCallbackURL: callbackURL,\n\t\tState:       state,\n\t\tOnMessage:   onMessage,\n\t}\n}\n\nfunc (c *PubSubClient) Refresh(forceUpdate bool, interval time.Duration) error {\n\ta, err := c.State.All()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"PubSubClient.Refresh\")\n\t}\n\n\tlogrus.WithField(\"count\", len(a)).Debug(\"pubsub: got subscriptions to refresh\")\n\n\tm := make(map[string]*ratelimit.Bucket)\n\tvar l sync.RWMutex\n\n\tgetBucket := func(host string) *ratelimit.Bucket {\n\t\tl.RLock()\n\t\tif b, ok := m[host]; ok {\n\t\t\tl.RUnlock()\n\t\t\treturn b\n\t\t}\n\t\tl.RUnlock()\n\n\t\tl.Lock()\n\t\tif b, ok := m[host]; ok {\n\t\t\tl.Unlock()\n\t\t\treturn b\n\t\t}\n\t\tdefer l.Unlock()\n\n\t\tm[host] = ratelimit.NewBucket(time.Second*30, 4)\n\n\t\treturn m[host]\n\t}\n\n\tvar g WorkerGroup\n\n\tfor _, e := range a {\n\t\te := e\n\n\t\tcallbackURL := c.CallbackURL + \"\/\" + e.ID\n\n\t\tl := logrus.WithFields(logrus.Fields{\n\t\t\t\"id\":               e.ID,\n\t\t\t\"hub\":              e.Hub,\n\t\t\t\"topic\":            e.Topic,\n\t\t\t\"callback_url\":     e.CallbackURL,\n\t\t\t\"new_callback_url\": callbackURL,\n\t\t\t\"created_at\":       e.CreatedAt,\n\t\t\t\"updated_at\":       e.UpdatedAt,\n\t\t\t\"expires_at\":       e.ExpiresAt,\n\t\t\t\"force_update\":     forceUpdate,\n\t\t})\n\n\t\tif e.ExpiresAt == nil {\n\t\t\tl.Debug(\"pubsub: not refreshing subscription which has never been verified\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif forceUpdate || e.ExpiresAt.Sub(time.Now()) < interval || e.CallbackURL != callbackURL {\n\t\t\tl.Debug(\"pubsub: refreshing subscription\")\n\n\t\t\tg.Add(func() error {\n\t\t\t\tu, err := url.Parse(e.Hub)\n\t\t\t\tif err != nil {\n\t\t\t\t\tl.WithError(err).Warn(\"pubsub: couldn't parse hub url\")\n\t\t\t\t\treturn errors.Wrap(err, \"PubSubClient.RefreshWorker\")\n\t\t\t\t}\n\n\t\t\t\tif dur, skip := getBucket(u.Host).TakeMaxDuration(1, *pubsubRefreshInterval); skip {\n\t\t\t\t\tl.Debug(\"pubsub: skipping renewing for now as we'd have to wait too long\")\n\t\t\t\t\treturn nil\n\t\t\t\t} else if dur > 0 {\n\t\t\t\t\tl.WithField(\"duration\", dur).Debug(\"pubsub: waiting so as not to overwhelm the endpoint\")\n\t\t\t\t\ttime.Sleep(dur)\n\t\t\t\t}\n\n\t\t\t\tif err := c.Subscribe(e.Hub, e.Topic); err != nil {\n\t\t\t\t\tl.WithError(err).Warn(\"pubsub: couldn't subscribe to topic\")\n\t\t\t\t\treturn errors.Wrap(err, \"PubSubClient.RefreshWorker\")\n\t\t\t\t}\n\n\t\t\t\tl.Debug(\"pubsub: subscribed successfully\")\n\t\t\t\treturn nil\n\t\t\t})\n\t\t}\n\t}\n\n\treturn errors.Wrap(g.Run(4), \"PubSubClient.Refresh\")\n}\n\nfunc (c *PubSubClient) Subscribe(hub, topic string) error {\n\tlogrus.WithFields(logrus.Fields{\"hub\": hub, \"topic\": topic}).Debug(\"pubsub: subscribing\")\n\n\ts, oldCallbackURL, err := c.State.Add(hub, topic, c.CallbackURL)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"PubSubClient.Subscribe\")\n\t}\n\n\tif oldCallbackURL != s.CallbackURL {\n\t\tif oldCallbackURL != \"\" {\n\t\t\tif err := PubSubUnsubscribe(hub, topic, oldCallbackURL); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"PubSubClient.Subscribe\")\n\t\t\t}\n\t\t}\n\n\t\tif err := PubSubSubscribe(hub, topic, s.CallbackURL); err != nil {\n\t\t\treturn errors.Wrap(err, \"PubSubClient.Subscribe\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *PubSubClient) Unsubscribe(hub, topic string) error {\n\tlogrus.WithFields(logrus.Fields{\"hub\": hub, \"topic\": topic}).Debug(\"pubsub: unsubscribing\")\n\n\ts, err := c.State.Get(hub, topic)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"PubSubClient.Unsubscribe\")\n\t}\n\n\tif s != nil {\n\t\tif err := PubSubUnsubscribe(hub, topic, s.CallbackURL); err != nil {\n\t\t\treturn errors.Wrap(err, \"PubSubClient.Unsubscribe\")\n\t\t}\n\n\t\tif err := c.State.Del(s.Hub, s.Topic); err != nil {\n\t\t\treturn errors.Wrap(err, \"PubSubClient.Unsubscribe\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *PubSubClient) Handler() *PubSubHandler {\n\treturn &PubSubHandler{\n\t\tOnChallenge: func(id, topic, mode string, leaseTime time.Duration) error {\n\t\t\tl := logrus.WithFields(logrus.Fields{\n\t\t\t\t\"id\":         id,\n\t\t\t\t\"topic\":      topic,\n\t\t\t\t\"mode\":       mode,\n\t\t\t\t\"lease_time\": leaseTime,\n\t\t\t})\n\n\t\t\tl.Debug(\"pubsub: received challenge\")\n\n\t\t\ts, err := c.State.GetByID(id)\n\t\t\tif err != nil {\n\t\t\t\tl.WithError(err).Warn(\"pubsub: error fetching subscription during challenge\")\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif s == nil {\n\t\t\t\tl.WithError(err).Warn(\"pubsub: subscription not found during challenge\")\n\t\t\t\treturn errors.Errorf(\"PubSubClient.Handler: subscription not found\")\n\t\t\t}\n\n\t\t\treturn errors.Wrap(c.State.Set(s.Hub, s.Topic, time.Now(), time.Now().Add(leaseTime)), \"PubSubClient.Handler\")\n\t\t},\n\t\tOnMessage: func(id, topic string, rd io.ReadCloser) {\n\t\t\tl := logrus.WithFields(logrus.Fields{\n\t\t\t\t\"id\":    id,\n\t\t\t\t\"topic\": topic,\n\t\t\t})\n\n\t\t\tl.Debug(\"pubsub: received message\")\n\n\t\t\tdefer rd.Close()\n\n\t\t\tif c.OnMessage != nil {\n\t\t\t\ts, err := c.State.GetByID(id)\n\t\t\t\tif err != nil {\n\t\t\t\t\tl.WithError(err).Warn(\"pubsub: error fetching subscription during reception\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tc.OnMessage(id, s, rd)\n\t\t\t}\n\t\t},\n\t}\n}\n\nfunc PubSubAlter(hub, topic, callbackURL, mode string) error {\n\tres, err := http.PostForm(hub, url.Values{\n\t\t\"hub.callback\":      []string{callbackURL},\n\t\t\"hub.mode\":          []string{mode},\n\t\t\"hub.topic\":         []string{topic},\n\t\t\"hub.verify\":        []string{\"async\"},\n\t\t\"hub.lease_seconds\": []string{\"604800\"},\n\t})\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"PubSubAlter\")\n\t}\n\n\tif res.StatusCode < 200 || res.StatusCode >= 300 {\n\t\treturn errors.Errorf(\"PubSubAlter: invalid status code; expected 2xx but got %d\", res.StatusCode)\n\t}\n\n\treturn nil\n}\n\nfunc PubSubSubscribe(hub, topic, callbackURL string) error {\n\treturn errors.Wrap(PubSubAlter(hub, topic, callbackURL, \"subscribe\"), \"PubSubSubscribe\")\n}\n\nfunc PubSubUnsubscribe(hub, topic, callbackURL string) error {\n\treturn errors.Wrap(PubSubAlter(hub, topic, callbackURL, \"unsubscribe\"), \"PubSubSubscribe\")\n}\n\ntype PubSubHandler struct {\n\tOnChallenge func(id, topic, mode string, leaseTime time.Duration) error\n\tOnMessage   func(id, topic string, rd io.ReadCloser)\n}\n\nfunc (h *PubSubHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\tq := r.URL.Query()\n\n\tbits := strings.Split(r.URL.Path, \"\/\")\n\tid := bits[len(bits)-1]\n\n\tif r.Method == http.MethodGet && q.Get(\"hub.challenge\") != \"\" {\n\t\tif h.OnChallenge != nil {\n\t\t\tleaseTime := time.Hour * 12\n\t\t\tif n, err := strconv.ParseInt(q.Get(\"hub.lease_seconds\"), 10, 64); err == nil {\n\t\t\t\tleaseTime = time.Second * time.Duration(n)\n\t\t\t}\n\n\t\t\tif err := h.OnChallenge(id, q.Get(\"hub.topic\"), q.Get(\"hub.mode\"), leaseTime); err != nil {\n\t\t\t\trw.WriteHeader(http.StatusNotFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\trw.Write([]byte(r.URL.Query().Get(\"hub.challenge\")))\n\t\treturn\n\t}\n\n\tif r.Method != http.MethodPost {\n\t\trw.WriteHeader(http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tlinks := linkheader.ParseMultiple(r.Header[\"Link\"])\n\n\tvar topic string\n\tif a := links.FilterByRel(\"self\"); len(a) > 0 {\n\t\ttopic = a[0].URL\n\t}\n\n\trw.WriteHeader(http.StatusAccepted)\n\n\tif h.OnMessage != nil {\n\t\th.OnMessage(id, topic, r.Body)\n\t}\n}\n<commit_msg>only log when a refresh is actually starting<commit_after>package main\n\nimport (\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/juju\/ratelimit\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/tomnomnom\/linkheader\"\n)\n\nfunc PubSubMakeCallbackURL(baseURL, id string) string {\n\treturn baseURL + \"\/\" + id\n}\n\ntype PubSubSubscription struct {\n\tID          string\n\tHub         string\n\tTopic       string\n\tCallbackURL string\n\tCreatedAt   time.Time\n\tUpdatedAt   time.Time\n\tExpiresAt   *time.Time\n}\n\ntype PubSubState interface {\n\tAll() (subscriptions []PubSubSubscription, err error)\n\tAdd(hub, topic, baseURL string) (subscription *PubSubSubscription, oldCallbackURL string, err error)\n\tGet(hub, topic string) (subscription *PubSubSubscription, err error)\n\tGetByID(id string) (subscription *PubSubSubscription, err error)\n\tSet(hub, topic string, updatedAt, expiresAt time.Time) (err error)\n\tDel(hub, topic string) (err error)\n}\n\ntype PubSubMessageHandler func(id string, s *PubSubSubscription, rd io.ReadCloser)\n\ntype PubSubClient struct {\n\tCallbackURL string\n\tState       PubSubState\n\tOnMessage   PubSubMessageHandler\n}\n\nfunc NewPubSubClient(callbackURL string, state PubSubState, onMessage PubSubMessageHandler) *PubSubClient {\n\treturn &PubSubClient{\n\t\tCallbackURL: callbackURL,\n\t\tState:       state,\n\t\tOnMessage:   onMessage,\n\t}\n}\n\nfunc (c *PubSubClient) Refresh(forceUpdate bool, interval time.Duration) error {\n\ta, err := c.State.All()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"PubSubClient.Refresh\")\n\t}\n\n\tlogrus.WithField(\"count\", len(a)).Debug(\"pubsub: got subscriptions to refresh\")\n\n\tm := make(map[string]*ratelimit.Bucket)\n\tvar l sync.RWMutex\n\n\tgetBucket := func(host string) *ratelimit.Bucket {\n\t\tl.RLock()\n\t\tif b, ok := m[host]; ok {\n\t\t\tl.RUnlock()\n\t\t\treturn b\n\t\t}\n\t\tl.RUnlock()\n\n\t\tl.Lock()\n\t\tif b, ok := m[host]; ok {\n\t\t\tl.Unlock()\n\t\t\treturn b\n\t\t}\n\t\tdefer l.Unlock()\n\n\t\tm[host] = ratelimit.NewBucket(time.Second*30, 4)\n\n\t\treturn m[host]\n\t}\n\n\tvar g WorkerGroup\n\n\tfor _, e := range a {\n\t\te := e\n\n\t\tcallbackURL := c.CallbackURL + \"\/\" + e.ID\n\n\t\tl := logrus.WithFields(logrus.Fields{\n\t\t\t\"id\":               e.ID,\n\t\t\t\"hub\":              e.Hub,\n\t\t\t\"topic\":            e.Topic,\n\t\t\t\"callback_url\":     e.CallbackURL,\n\t\t\t\"new_callback_url\": callbackURL,\n\t\t\t\"created_at\":       e.CreatedAt,\n\t\t\t\"updated_at\":       e.UpdatedAt,\n\t\t\t\"expires_at\":       e.ExpiresAt,\n\t\t\t\"force_update\":     forceUpdate,\n\t\t})\n\n\t\tif e.ExpiresAt == nil {\n\t\t\tl.Debug(\"pubsub: not refreshing subscription which has never been verified\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif forceUpdate || e.ExpiresAt.Sub(time.Now()) < interval || e.CallbackURL != callbackURL {\n\t\t\tg.Add(func() error {\n\t\t\t\tu, err := url.Parse(e.Hub)\n\t\t\t\tif err != nil {\n\t\t\t\t\tl.WithError(err).Warn(\"pubsub: couldn't parse hub url\")\n\t\t\t\t\treturn errors.Wrap(err, \"PubSubClient.RefreshWorker\")\n\t\t\t\t}\n\n\t\t\t\tif dur, skip := getBucket(u.Host).TakeMaxDuration(1, *pubsubRefreshInterval); skip {\n\t\t\t\t\tl.Debug(\"pubsub: skipping renewing for now as we'd have to wait too long\")\n\t\t\t\t\treturn nil\n\t\t\t\t} else if dur > 0 {\n\t\t\t\t\tl.WithField(\"duration\", dur).Debug(\"pubsub: waiting so as not to overwhelm the endpoint\")\n\t\t\t\t\ttime.Sleep(dur)\n\t\t\t\t}\n\n\t\t\t\tl.Debug(\"pubsub: refreshing subscription\")\n\n\t\t\t\tif err := c.Subscribe(e.Hub, e.Topic); err != nil {\n\t\t\t\t\tl.WithError(err).Warn(\"pubsub: couldn't subscribe to topic\")\n\t\t\t\t\treturn errors.Wrap(err, \"PubSubClient.RefreshWorker\")\n\t\t\t\t}\n\n\t\t\t\tl.Debug(\"pubsub: subscribed successfully\")\n\t\t\t\treturn nil\n\t\t\t})\n\t\t}\n\t}\n\n\treturn errors.Wrap(g.Run(4), \"PubSubClient.Refresh\")\n}\n\nfunc (c *PubSubClient) Subscribe(hub, topic string) error {\n\tlogrus.WithFields(logrus.Fields{\"hub\": hub, \"topic\": topic}).Debug(\"pubsub: subscribing\")\n\n\ts, oldCallbackURL, err := c.State.Add(hub, topic, c.CallbackURL)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"PubSubClient.Subscribe\")\n\t}\n\n\tif oldCallbackURL != s.CallbackURL {\n\t\tif oldCallbackURL != \"\" {\n\t\t\tif err := PubSubUnsubscribe(hub, topic, oldCallbackURL); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"PubSubClient.Subscribe\")\n\t\t\t}\n\t\t}\n\n\t\tif err := PubSubSubscribe(hub, topic, s.CallbackURL); err != nil {\n\t\t\treturn errors.Wrap(err, \"PubSubClient.Subscribe\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *PubSubClient) Unsubscribe(hub, topic string) error {\n\tlogrus.WithFields(logrus.Fields{\"hub\": hub, \"topic\": topic}).Debug(\"pubsub: unsubscribing\")\n\n\ts, err := c.State.Get(hub, topic)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"PubSubClient.Unsubscribe\")\n\t}\n\n\tif s != nil {\n\t\tif err := PubSubUnsubscribe(hub, topic, s.CallbackURL); err != nil {\n\t\t\treturn errors.Wrap(err, \"PubSubClient.Unsubscribe\")\n\t\t}\n\n\t\tif err := c.State.Del(s.Hub, s.Topic); err != nil {\n\t\t\treturn errors.Wrap(err, \"PubSubClient.Unsubscribe\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *PubSubClient) Handler() *PubSubHandler {\n\treturn &PubSubHandler{\n\t\tOnChallenge: func(id, topic, mode string, leaseTime time.Duration) error {\n\t\t\tl := logrus.WithFields(logrus.Fields{\n\t\t\t\t\"id\":         id,\n\t\t\t\t\"topic\":      topic,\n\t\t\t\t\"mode\":       mode,\n\t\t\t\t\"lease_time\": leaseTime,\n\t\t\t})\n\n\t\t\tl.Debug(\"pubsub: received challenge\")\n\n\t\t\ts, err := c.State.GetByID(id)\n\t\t\tif err != nil {\n\t\t\t\tl.WithError(err).Warn(\"pubsub: error fetching subscription during challenge\")\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif s == nil {\n\t\t\t\tl.WithError(err).Warn(\"pubsub: subscription not found during challenge\")\n\t\t\t\treturn errors.Errorf(\"PubSubClient.Handler: subscription not found\")\n\t\t\t}\n\n\t\t\treturn errors.Wrap(c.State.Set(s.Hub, s.Topic, time.Now(), time.Now().Add(leaseTime)), \"PubSubClient.Handler\")\n\t\t},\n\t\tOnMessage: func(id, topic string, rd io.ReadCloser) {\n\t\t\tl := logrus.WithFields(logrus.Fields{\n\t\t\t\t\"id\":    id,\n\t\t\t\t\"topic\": topic,\n\t\t\t})\n\n\t\t\tl.Debug(\"pubsub: received message\")\n\n\t\t\tdefer rd.Close()\n\n\t\t\tif c.OnMessage != nil {\n\t\t\t\ts, err := c.State.GetByID(id)\n\t\t\t\tif err != nil {\n\t\t\t\t\tl.WithError(err).Warn(\"pubsub: error fetching subscription during reception\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tc.OnMessage(id, s, rd)\n\t\t\t}\n\t\t},\n\t}\n}\n\nfunc PubSubAlter(hub, topic, callbackURL, mode string) error {\n\tres, err := http.PostForm(hub, url.Values{\n\t\t\"hub.callback\":      []string{callbackURL},\n\t\t\"hub.mode\":          []string{mode},\n\t\t\"hub.topic\":         []string{topic},\n\t\t\"hub.verify\":        []string{\"async\"},\n\t\t\"hub.lease_seconds\": []string{\"604800\"},\n\t})\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"PubSubAlter\")\n\t}\n\n\tif res.StatusCode < 200 || res.StatusCode >= 300 {\n\t\treturn errors.Errorf(\"PubSubAlter: invalid status code; expected 2xx but got %d\", res.StatusCode)\n\t}\n\n\treturn nil\n}\n\nfunc PubSubSubscribe(hub, topic, callbackURL string) error {\n\treturn errors.Wrap(PubSubAlter(hub, topic, callbackURL, \"subscribe\"), \"PubSubSubscribe\")\n}\n\nfunc PubSubUnsubscribe(hub, topic, callbackURL string) error {\n\treturn errors.Wrap(PubSubAlter(hub, topic, callbackURL, \"unsubscribe\"), \"PubSubSubscribe\")\n}\n\ntype PubSubHandler struct {\n\tOnChallenge func(id, topic, mode string, leaseTime time.Duration) error\n\tOnMessage   func(id, topic string, rd io.ReadCloser)\n}\n\nfunc (h *PubSubHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\tq := r.URL.Query()\n\n\tbits := strings.Split(r.URL.Path, \"\/\")\n\tid := bits[len(bits)-1]\n\n\tif r.Method == http.MethodGet && q.Get(\"hub.challenge\") != \"\" {\n\t\tif h.OnChallenge != nil {\n\t\t\tleaseTime := time.Hour * 12\n\t\t\tif n, err := strconv.ParseInt(q.Get(\"hub.lease_seconds\"), 10, 64); err == nil {\n\t\t\t\tleaseTime = time.Second * time.Duration(n)\n\t\t\t}\n\n\t\t\tif err := h.OnChallenge(id, q.Get(\"hub.topic\"), q.Get(\"hub.mode\"), leaseTime); err != nil {\n\t\t\t\trw.WriteHeader(http.StatusNotFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\trw.Write([]byte(r.URL.Query().Get(\"hub.challenge\")))\n\t\treturn\n\t}\n\n\tif r.Method != http.MethodPost {\n\t\trw.WriteHeader(http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tlinks := linkheader.ParseMultiple(r.Header[\"Link\"])\n\n\tvar topic string\n\tif a := links.FilterByRel(\"self\"); len(a) > 0 {\n\t\ttopic = a[0].URL\n\t}\n\n\trw.WriteHeader(http.StatusAccepted)\n\n\tif h.OnMessage != nil {\n\t\th.OnMessage(id, topic, r.Body)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package cblog\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\nconst LOG_OUTPUT_BUFFER = 1024\n\ntype logMesg struct {\n\tmesg  string\n\tfatal bool\n}\n\ntype loggerHandler interface {\n\tsetup(config map[string]interface{}) error\n\twrite(mesg *logMesg)\n}\n\ntype Logger struct {\n\tmessages chan *logMesg\n\toutputs  map[string]loggerHandler\n}\n\nfunc New() *Logger {\n\tl := &Logger{\n\t\tmessages: make(chan *logMesg, LOG_OUTPUT_BUFFER),\n\t\toutputs:  make(map[string]loggerHandler),\n\t}\n\tgo l.run()\n\treturn l\n}\n\nfunc (l *Logger) SetLogger(handlerType string, cfg map[string]interface{}) {\n\tvar handler loggerHandler\n\tswitch handlerType {\n\tcase \"console\":\n\t\thandler = newConsoleHandler()\n\tcase \"file\":\n\t\thandler = newFileHandler()\n\tdefault:\n\t\tpanic(\"Unknown log handler.\")\n\t}\n\n\thandler.setup(cfg)\n\tl.outputs[handlerType] = handler\n}\n\nfunc (l *Logger) run() {\n\tfor {\n\t\tselect {\n\t\tcase mesg := <-l.messages:\n\t\t\tfor _, handler := range l.outputs {\n\t\t\t\thandler.write(mesg)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (l *Logger) writeMesg(mesg string, fatal bool) {\n\tlm := &logMesg{\n\t\tmesg:  mesg,\n\t\tfatal: fatal,\n\t}\n\tl.messages <- lm\n}\n\nfunc (l *Logger) Debug(format string, v ...interface{}) {\n\tmesg := fmt.Sprintf(\"[DEBUG] \"+format, v...)\n\tl.writeMesg(mesg, false)\n}\n\nfunc (l *Logger) Info(format string, v ...interface{}) {\n\tmesg := fmt.Sprintf(\"[INFO] \"+format, v...)\n\tl.writeMesg(mesg, false)\n}\n\nfunc (l *Logger) Notice(format string, v ...interface{}) {\n\tmesg := fmt.Sprintf(\"[NOTICE] \"+format, v...)\n\tl.writeMesg(mesg, false)\n}\n\nfunc (l *Logger) Warn(format string, v ...interface{}) {\n\tmesg := fmt.Sprintf(\"[WARN] \"+format, v...)\n\tl.writeMesg(mesg, false)\n}\n\nfunc (l *Logger) Error(format string, v ...interface{}) {\n\tmesg := fmt.Sprintf(\"[ERROR] \"+format, v...)\n\tl.writeMesg(mesg, false)\n}\n\nfunc (l *Logger) Fatal(format string, v ...interface{}) {\n\tmesg := fmt.Sprintf(\"[FATAL] \"+format, v...)\n\tl.writeMesg(mesg, true)\n}\n\ntype consoleHandler struct {\n\tlogger *log.Logger\n}\n\nfunc newConsoleHandler() loggerHandler {\n\treturn new(consoleHandler)\n}\n\nfunc (h *consoleHandler) setup(cfg map[string]interface{}) error {\n\th.logger = log.New(os.Stdout, \"\", log.Ldate|log.Ltime)\n\treturn nil\n}\n\nfunc (h *consoleHandler) write(lm *logMesg) {\n\tif !lm.fatal {\n\t\th.logger.Println(lm.mesg)\n\t} else {\n\t\th.logger.Fatalln(lm.mesg)\n\t}\n}\n\ntype fileHandler struct {\n\tfile   string\n\tlogger *log.Logger\n}\n\nfunc newFileHandler() loggerHandler {\n\treturn new(fileHandler)\n}\n\nfunc (h *fileHandler) setup(config map[string]interface{}) error {\n\tif file, ok := config[\"file\"]; ok {\n\t\th.file = file.(string)\n\t\tif _, err := os.Stat(h.file); os.IsNotExist(err) {\n\t\t\t_ = os.MkdirAll(filepath.Dir(h.file), 0755)\n\t\t\tif _, err := os.Create(h.file); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\toutput, _ := os.Create(h.file)\n\t\th.logger = log.New(output, \"\", log.Ldate|log.Ltime)\n\t}\n\n\treturn nil\n}\n\nfunc (h *fileHandler) write(lm *logMesg) {\n\tif h.logger == nil {\n\t\treturn\n\t}\n\n\tif !lm.fatal {\n\t\th.logger.Println(lm.mesg)\n\t} else {\n\t\th.logger.Fatalln(lm.mesg)\n\t}\n}\n<commit_msg>gnocco: fixed go lint issues with cblog<commit_after>\/\/ Package cblog provides a channel based logger.\npackage cblog\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\n\/\/ LOG_OUTPUT_BUFFER is the size of the channel buffer used for logging.\nconst LOG_OUTPUT_BUFFER = 1024\n\ntype logMesg struct {\n\tmesg  string\n\tfatal bool\n}\n\ntype loggerHandler interface {\n\tsetup(config map[string]interface{}) error\n\twrite(mesg *logMesg)\n}\n\n\/\/ Logger is the logging object.\ntype Logger struct {\n\tmessages chan *logMesg\n\toutputs  map[string]loggerHandler\n}\n\n\/\/ New creates a new Logger.\nfunc New() *Logger {\n\tl := &Logger{\n\t\tmessages: make(chan *logMesg, LOG_OUTPUT_BUFFER),\n\t\toutputs:  make(map[string]loggerHandler),\n\t}\n\tgo l.run()\n\treturn l\n}\n\n\/\/ SetLogger sets the Logger object output.\nfunc (l *Logger) SetLogger(handlerType string, cfg map[string]interface{}) {\n\t\/\/ BUG(karasz): SetLogger should be replaced with SetOutput in order to become stdlib compatible\n\tvar handler loggerHandler\n\tswitch handlerType {\n\tcase \"console\":\n\t\thandler = newConsoleHandler()\n\tcase \"file\":\n\t\thandler = newFileHandler()\n\tdefault:\n\t\tpanic(\"Unknown log handler.\")\n\t}\n\n\thandler.setup(cfg)\n\tl.outputs[handlerType] = handler\n}\n\nfunc (l *Logger) run() {\n\tfor {\n\t\tselect {\n\t\tcase mesg := <-l.messages:\n\t\t\tfor _, handler := range l.outputs {\n\t\t\t\thandler.write(mesg)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (l *Logger) writeMesg(mesg string, fatal bool) {\n\tlm := &logMesg{\n\t\tmesg:  mesg,\n\t\tfatal: fatal,\n\t}\n\tl.messages <- lm\n}\n\n\/\/ Debug calls l.writeMesg prefixing the message with [DEBUG]\nfunc (l *Logger) Debug(format string, v ...interface{}) {\n\tmesg := fmt.Sprintf(\"[DEBUG] \"+format, v...)\n\tl.writeMesg(mesg, false)\n}\n\n\/\/ Info calls l.writeMesg prefixing the message with [INFO]\nfunc (l *Logger) Info(format string, v ...interface{}) {\n\tmesg := fmt.Sprintf(\"[INFO] \"+format, v...)\n\tl.writeMesg(mesg, false)\n}\n\n\/\/ Notice calls l.writeMesg prefixing the message with [NOTICE]\nfunc (l *Logger) Notice(format string, v ...interface{}) {\n\tmesg := fmt.Sprintf(\"[NOTICE] \"+format, v...)\n\tl.writeMesg(mesg, false)\n}\n\n\/\/ Warn calls l.writeMesg prefixing the message with [WARN]\nfunc (l *Logger) Warn(format string, v ...interface{}) {\n\tmesg := fmt.Sprintf(\"[WARN] \"+format, v...)\n\tl.writeMesg(mesg, false)\n}\n\n\/\/ Error calls l.writeMesg prefixing the message with [ERROR]\nfunc (l *Logger) Error(format string, v ...interface{}) {\n\tmesg := fmt.Sprintf(\"[ERROR] \"+format, v...)\n\tl.writeMesg(mesg, false)\n}\n\n\/\/ Fatal calls l.writeMesg prefixing the message with [FATAL]\nfunc (l *Logger) Fatal(format string, v ...interface{}) {\n\tmesg := fmt.Sprintf(\"[FATAL] \"+format, v...)\n\tl.writeMesg(mesg, true)\n}\n\ntype consoleHandler struct {\n\tlogger *log.Logger\n}\n\nfunc newConsoleHandler() loggerHandler {\n\treturn new(consoleHandler)\n}\n\nfunc (h *consoleHandler) setup(cfg map[string]interface{}) error {\n\th.logger = log.New(os.Stdout, \"\", log.Ldate|log.Ltime)\n\treturn nil\n}\n\nfunc (h *consoleHandler) write(lm *logMesg) {\n\tif !lm.fatal {\n\t\th.logger.Println(lm.mesg)\n\t} else {\n\t\th.logger.Fatalln(lm.mesg)\n\t}\n}\n\ntype fileHandler struct {\n\tfile   string\n\tlogger *log.Logger\n}\n\nfunc newFileHandler() loggerHandler {\n\treturn new(fileHandler)\n}\n\nfunc (h *fileHandler) setup(config map[string]interface{}) error {\n\tif file, ok := config[\"file\"]; ok {\n\t\th.file = file.(string)\n\t\tif _, err := os.Stat(h.file); os.IsNotExist(err) {\n\t\t\t_ = os.MkdirAll(filepath.Dir(h.file), 0755)\n\t\t\tif _, err := os.Create(h.file); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\toutput, _ := os.Create(h.file)\n\t\th.logger = log.New(output, \"\", log.Ldate|log.Ltime)\n\t}\n\n\treturn nil\n}\n\nfunc (h *fileHandler) write(lm *logMesg) {\n\tif h.logger == nil {\n\t\treturn\n\t}\n\n\tif !lm.fatal {\n\t\th.logger.Println(lm.mesg)\n\t} else {\n\t\th.logger.Fatalln(lm.mesg)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package hstspreload\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\t\/\/ Value that indictes when HSTSHeader.MaxAge is invalid.\n\tMAX_AGE_NOT_PRESENT = (-1)\n\n\t\/\/ 18 weeks\n\thstsMinimumMaxAge = 10886400 \/\/ seconds\n\n\t\/\/ 1 year: https:\/\/code.google.com\/p\/chromium\/codesearch#chromium\/src\/net\/http\/http_security_headers.h&q=kMaxHSTSAgeSecs\n\thstsChromeMaxAgeCapOneYear = 86400 * 365 \/\/ seconds\n)\n\n\/\/ Unless all values are known at initialization time, use\n\/\/ NewHSTSHeader() instead of constructing an `HSTSHeader` directly.\n\/\/ This makes sure that `MaxAge` is initialized to\n\/\/ `MAX_AGE_NOT_PRESENT`.\ntype HSTSHeader struct {\n\t\/\/ MaxAge == MAX_AGE_NOT_PRESENT indicates that this value is invalid.\n\t\/\/ A valid `maxAge` value is a non-negative integer.\n\tMaxAge            int64\n\tIncludeSubDomains bool\n\tPreload           bool\n}\n\nfunc NewHSTSHeader() HSTSHeader {\n\treturn HSTSHeader{\n\t\tPreload:           false,\n\t\tIncludeSubDomains: false,\n\t\tMaxAge:            MAX_AGE_NOT_PRESENT,\n\t}\n}\n\n\/\/ Mainly useful for testing.\nfunc headersEqual(header1 HSTSHeader, header2 HSTSHeader) bool {\n\tif header1.Preload != header2.Preload {\n\t\treturn false\n\t}\n\n\tif header1.IncludeSubDomains != header2.IncludeSubDomains {\n\t\treturn false\n\t}\n\n\tif header1.MaxAge != header2.MaxAge {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ Iff Issues has no errors, the output integer is the max-age in seconds.\nfunc parseMaxAge(directive string) (int64, Issues) {\n\tissues := NewIssues()\n\n\tmaxAgeNumericalString := directive[8:]\n\n\t\/\/ TODO: Use more concise validation code to parse a digit string to a signed int.\n\tfor i, c := range maxAgeNumericalString {\n\t\tif i == 0 && c == '0' && len(maxAgeNumericalString) > 1 {\n\t\t\tissues = issues.addWarning(fmt.Sprintf(\"Syntax warning: max-age value contains a leading 0: `%s`\", directive))\n\t\t}\n\t\tif c < '0' || c > '9' {\n\t\t\treturn MAX_AGE_NOT_PRESENT, issues.addError(fmt.Sprintf(\"Syntax error: max-age value contains characters that are not digits: `%s`\", directive))\n\t\t}\n\t}\n\n\tmaxAge, err := strconv.ParseInt(maxAgeNumericalString, 10, 64)\n\n\tif err != nil {\n\t\treturn MAX_AGE_NOT_PRESENT, issues.addError(fmt.Sprintf(\"Syntax error: Could not parse max-age value `%s`.\", maxAgeNumericalString))\n\t}\n\n\tif maxAge < 0 {\n\t\treturn MAX_AGE_NOT_PRESENT, issues.addError(fmt.Sprintf(\"Internal error: unexpected negative integer: `%d`\", maxAge))\n\t}\n\n\treturn maxAge, issues\n}\n\n\/\/ This function parses an HSTS header.\n\/\/\n\/\/ It will report syntax errors and warnings, but does NOT calculate\n\/\/ whether the header value is semantically valid.\n\/\/\n\/\/ To interpret the issues, see the list of conventions in the\n\/\/ documentation for `Issues`.\n\/\/\n\/\/ Example Usage:\n\/\/\n\/\/     hstsHeader, issues := ParseHeaderString(\"includeSubDomains; max-age;\")\n\/\/\n\/\/     issues.Errors[0] == []string{\"Syntax error: A max-age directive name is present without an associated value.\"}\n\/\/     issues.Warnings[0] == []string{\"Syntax warning: Header includes an empty directive or extra semicolon.\"}\nfunc ParseHeaderString(headerString string) (HSTSHeader, Issues) {\n\thstsHeader := NewHSTSHeader()\n\tissues := NewIssues()\n\n\tdirectives := strings.Split(headerString, \";\")\n\tfor i, directive := range directives {\n\t\t\/\/ TODO: this trims more than spaces and tabs (LWS). https:\/\/crbug.com\/596561#c10\n\t\tdirectives[i] = strings.TrimSpace(directive)\n\t}\n\n\t\/\/ If strings.Split() is given whitespace, it still returns an (empty) directive.\n\t\/\/ So we handle this case separately.\n\tif len(directives) == 1 && directives[0] == \"\" {\n\t\t\/\/ Return immediately, because all the extra information is redundant.\n\t\treturn hstsHeader, issues.addWarning(\"Syntax warning: Header is empty.\")\n\t}\n\n\tfor _, directive := range directives {\n\t\tdirectiveEqualsIgnoringCase := func(s string) bool {\n\t\t\treturn strings.ToLower(directive) == strings.ToLower(s)\n\t\t}\n\n\t\tdirectiveHasPrefixIgnoringCase := func(prefix string) bool {\n\t\t\treturn strings.HasPrefix(strings.ToLower(directive), strings.ToLower(prefix))\n\t\t}\n\n\t\tswitch {\n\t\tcase directiveEqualsIgnoringCase(\"preload\"):\n\t\t\tif hstsHeader.Preload {\n\t\t\t\tissues = issues.addUniqueWarning(\"Syntax warning: Header contains a repeated directive: `preload`\")\n\t\t\t} else {\n\t\t\t\thstsHeader.Preload = true\n\t\t\t}\n\n\t\tcase directiveHasPrefixIgnoringCase(\"preload\"):\n\t\t\tissues = issues.addUniqueWarning(\"Syntax warning: Header contains a `preload` directive with extra directives.\")\n\n\t\tcase directiveEqualsIgnoringCase(\"includeSubDomains\"):\n\t\t\tif hstsHeader.IncludeSubDomains {\n\t\t\t\tissues = issues.addUniqueWarning(\"Syntax warning: Header contains a repeated directive: `includeSubDomains`\")\n\t\t\t} else {\n\t\t\t\thstsHeader.IncludeSubDomains = true\n\t\t\t\tif directive != \"includeSubDomains\" {\n\t\t\t\t\tissues = issues.addUniqueWarning(fmt.Sprintf(\n\t\t\t\t\t\t\"Syntax warning: Header contains the token `%s`. The recommended capitalization is `includeSubDomains`.\",\n\t\t\t\t\t\tdirective,\n\t\t\t\t\t))\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase directiveHasPrefixIgnoringCase(\"includeSubDomains\"):\n\t\t\tissues = issues.addUniqueWarning(\"Syntax warning: Header contains an `includeSubDomains` directive with extra directives.\")\n\n\t\tcase directiveHasPrefixIgnoringCase(\"max-age=\"):\n\t\t\tmaxAge, maxAgeIssues := parseMaxAge(directive)\n\t\t\tissues = combineIssues(issues, maxAgeIssues)\n\n\t\t\tif len(maxAgeIssues.Errors) > 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif hstsHeader.MaxAge == MAX_AGE_NOT_PRESENT {\n\t\t\t\thstsHeader.MaxAge = maxAge\n\t\t\t} else {\n\t\t\t\tissues = issues.addUniqueWarning(fmt.Sprintf(\"Syntax warning: Header contains a repeated directive: `max-age`\"))\n\t\t\t}\n\n\t\tcase directiveHasPrefixIgnoringCase(\"max-age\"):\n\t\t\tissues = issues.addUniqueError(\"Syntax error: A max-age directive name is present without an associated value.\")\n\n\t\tcase directiveEqualsIgnoringCase(\"\"):\n\t\t\tissues = issues.addUniqueWarning(\"Syntax warning: Header includes an empty directive or extra semicolon.\")\n\n\t\tdefault:\n\t\t\tissues = issues.addWarning(fmt.Sprintf(\"Syntax warning: Header contains an unknown directive: `%s`\", directive))\n\t\t}\n\t}\n\treturn hstsHeader, issues\n}\n\n\/\/ This function checks whether the `HSTSHeader` matches all\n\/\/ requirements for preloading in Chromium.\n\/\/\n\/\/ To interpret the result, see the list of conventions in the\n\/\/ documentation for `Issues`.\n\/\/\n\/\/ Most of the time, you'll probably want to use `CheckHeaderString()` instead.\nfunc CheckHeader(hstsHeader HSTSHeader) Issues {\n\tissues := NewIssues()\n\n\tif !hstsHeader.IncludeSubDomains {\n\t\tissues = issues.addError(\"Header requirement error: Header must contain the `includeSubDomains` directive.\")\n\t}\n\n\tif !hstsHeader.Preload {\n\t\tissues = issues.addError(\"Header requirement error: Header must contain the `preload` directive.\")\n\t}\n\n\tswitch {\n\tcase hstsHeader.MaxAge == MAX_AGE_NOT_PRESENT:\n\t\tissues = issues.addError(\"Header requirement error: Header must contain a valid `max-age` directive.\")\n\n\tcase hstsHeader.MaxAge < 0:\n\t\tissues = issues.addError(fmt.Sprintf(\"Internal error: encountered an HSTSHeader with a negative max-age that does not equal MAX_AGE_NOT_PRESENT: %d\", hstsHeader.MaxAge))\n\n\tcase hstsHeader.MaxAge < hstsMinimumMaxAge:\n\t\tissues = issues.addError(fmt.Sprintf(\n\t\t\t\"Header requirement error: The max-age must be at least 10886400 seconds (== 18 weeks), but the header only had max-age=%d.\",\n\t\t\thstsHeader.MaxAge,\n\t\t))\n\n\tcase hstsHeader.MaxAge > hstsChromeMaxAgeCapOneYear:\n\t\tissues = issues.addWarning(fmt.Sprintf(\n\t\t\t\"Header FYI: The max-age (%d seconds) is longer than a year. Note that Chrome will round HSTS header max-age values down to 1 year (%d seconds).\",\n\t\t\thstsHeader.MaxAge,\n\t\t\thstsChromeMaxAgeCapOneYear,\n\t\t))\n\n\t}\n\n\treturn issues\n}\n\n\/\/ This convenience function calls ParseHeaderString() and then calls on\n\/\/ the parsed headerCheckHeader(). It returns all issues from both calls, combined.\n\/\/\n\/\/ To interpret the result, see the list of conventions in the\n\/\/ documentation for `Issues`.\n\/\/\n\/\/ Example Usage:\n\/\/\n\/\/     hstsHeader, issues := ParseHeaderString(\"includeSubDomains; max-age;\")\n\/\/\n\/\/     hstsHeader.Errors[0] == \"Header requirement error: Header must contain the `preload` directive.\"\n\/\/     hstsHeader.Warnings[0] == \"Header FYI: The max-age (31536001 seconds) is longer than a year. Note that Chrome will round HSTS header max-age values down to 1 year (31536000 seconds).\"\nfunc CheckHeaderString(headerString string) Issues {\n\thstsHeader, issues := ParseHeaderString(headerString)\n\treturn combineIssues(issues, CheckHeader(hstsHeader))\n}\n<commit_msg>Fix a MaxAge capitalization type in the HSTSHeader struct doc comment.<commit_after>package hstspreload\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\t\/\/ Value that indictes when HSTSHeader.MaxAge is invalid.\n\tMAX_AGE_NOT_PRESENT = (-1)\n\n\t\/\/ 18 weeks\n\thstsMinimumMaxAge = 10886400 \/\/ seconds\n\n\t\/\/ 1 year: https:\/\/code.google.com\/p\/chromium\/codesearch#chromium\/src\/net\/http\/http_security_headers.h&q=kMaxHSTSAgeSecs\n\thstsChromeMaxAgeCapOneYear = 86400 * 365 \/\/ seconds\n)\n\n\/\/ Unless all values are known at initialization time, use\n\/\/ NewHSTSHeader() instead of constructing an `HSTSHeader` directly.\n\/\/ This makes sure that `MaxAge` is initialized to\n\/\/ `MAX_AGE_NOT_PRESENT`.\ntype HSTSHeader struct {\n\t\/\/ MaxAge == MAX_AGE_NOT_PRESENT indicates that this value is invalid.\n\t\/\/ A valid `MaxAge` value is a non-negative integer.\n\tMaxAge            int64\n\tIncludeSubDomains bool\n\tPreload           bool\n}\n\nfunc NewHSTSHeader() HSTSHeader {\n\treturn HSTSHeader{\n\t\tPreload:           false,\n\t\tIncludeSubDomains: false,\n\t\tMaxAge:            MAX_AGE_NOT_PRESENT,\n\t}\n}\n\n\/\/ Mainly useful for testing.\nfunc headersEqual(header1 HSTSHeader, header2 HSTSHeader) bool {\n\tif header1.Preload != header2.Preload {\n\t\treturn false\n\t}\n\n\tif header1.IncludeSubDomains != header2.IncludeSubDomains {\n\t\treturn false\n\t}\n\n\tif header1.MaxAge != header2.MaxAge {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ Iff Issues has no errors, the output integer is the max-age in seconds.\nfunc parseMaxAge(directive string) (int64, Issues) {\n\tissues := NewIssues()\n\n\tmaxAgeNumericalString := directive[8:]\n\n\t\/\/ TODO: Use more concise validation code to parse a digit string to a signed int.\n\tfor i, c := range maxAgeNumericalString {\n\t\tif i == 0 && c == '0' && len(maxAgeNumericalString) > 1 {\n\t\t\tissues = issues.addWarning(fmt.Sprintf(\"Syntax warning: max-age value contains a leading 0: `%s`\", directive))\n\t\t}\n\t\tif c < '0' || c > '9' {\n\t\t\treturn MAX_AGE_NOT_PRESENT, issues.addError(fmt.Sprintf(\"Syntax error: max-age value contains characters that are not digits: `%s`\", directive))\n\t\t}\n\t}\n\n\tmaxAge, err := strconv.ParseInt(maxAgeNumericalString, 10, 64)\n\n\tif err != nil {\n\t\treturn MAX_AGE_NOT_PRESENT, issues.addError(fmt.Sprintf(\"Syntax error: Could not parse max-age value `%s`.\", maxAgeNumericalString))\n\t}\n\n\tif maxAge < 0 {\n\t\treturn MAX_AGE_NOT_PRESENT, issues.addError(fmt.Sprintf(\"Internal error: unexpected negative integer: `%d`\", maxAge))\n\t}\n\n\treturn maxAge, issues\n}\n\n\/\/ This function parses an HSTS header.\n\/\/\n\/\/ It will report syntax errors and warnings, but does NOT calculate\n\/\/ whether the header value is semantically valid.\n\/\/\n\/\/ To interpret the issues, see the list of conventions in the\n\/\/ documentation for `Issues`.\n\/\/\n\/\/ Example Usage:\n\/\/\n\/\/     hstsHeader, issues := ParseHeaderString(\"includeSubDomains; max-age;\")\n\/\/\n\/\/     issues.Errors[0] == []string{\"Syntax error: A max-age directive name is present without an associated value.\"}\n\/\/     issues.Warnings[0] == []string{\"Syntax warning: Header includes an empty directive or extra semicolon.\"}\nfunc ParseHeaderString(headerString string) (HSTSHeader, Issues) {\n\thstsHeader := NewHSTSHeader()\n\tissues := NewIssues()\n\n\tdirectives := strings.Split(headerString, \";\")\n\tfor i, directive := range directives {\n\t\t\/\/ TODO: this trims more than spaces and tabs (LWS). https:\/\/crbug.com\/596561#c10\n\t\tdirectives[i] = strings.TrimSpace(directive)\n\t}\n\n\t\/\/ If strings.Split() is given whitespace, it still returns an (empty) directive.\n\t\/\/ So we handle this case separately.\n\tif len(directives) == 1 && directives[0] == \"\" {\n\t\t\/\/ Return immediately, because all the extra information is redundant.\n\t\treturn hstsHeader, issues.addWarning(\"Syntax warning: Header is empty.\")\n\t}\n\n\tfor _, directive := range directives {\n\t\tdirectiveEqualsIgnoringCase := func(s string) bool {\n\t\t\treturn strings.ToLower(directive) == strings.ToLower(s)\n\t\t}\n\n\t\tdirectiveHasPrefixIgnoringCase := func(prefix string) bool {\n\t\t\treturn strings.HasPrefix(strings.ToLower(directive), strings.ToLower(prefix))\n\t\t}\n\n\t\tswitch {\n\t\tcase directiveEqualsIgnoringCase(\"preload\"):\n\t\t\tif hstsHeader.Preload {\n\t\t\t\tissues = issues.addUniqueWarning(\"Syntax warning: Header contains a repeated directive: `preload`\")\n\t\t\t} else {\n\t\t\t\thstsHeader.Preload = true\n\t\t\t}\n\n\t\tcase directiveHasPrefixIgnoringCase(\"preload\"):\n\t\t\tissues = issues.addUniqueWarning(\"Syntax warning: Header contains a `preload` directive with extra directives.\")\n\n\t\tcase directiveEqualsIgnoringCase(\"includeSubDomains\"):\n\t\t\tif hstsHeader.IncludeSubDomains {\n\t\t\t\tissues = issues.addUniqueWarning(\"Syntax warning: Header contains a repeated directive: `includeSubDomains`\")\n\t\t\t} else {\n\t\t\t\thstsHeader.IncludeSubDomains = true\n\t\t\t\tif directive != \"includeSubDomains\" {\n\t\t\t\t\tissues = issues.addUniqueWarning(fmt.Sprintf(\n\t\t\t\t\t\t\"Syntax warning: Header contains the token `%s`. The recommended capitalization is `includeSubDomains`.\",\n\t\t\t\t\t\tdirective,\n\t\t\t\t\t))\n\t\t\t\t}\n\t\t\t}\n\n\t\tcase directiveHasPrefixIgnoringCase(\"includeSubDomains\"):\n\t\t\tissues = issues.addUniqueWarning(\"Syntax warning: Header contains an `includeSubDomains` directive with extra directives.\")\n\n\t\tcase directiveHasPrefixIgnoringCase(\"max-age=\"):\n\t\t\tmaxAge, maxAgeIssues := parseMaxAge(directive)\n\t\t\tissues = combineIssues(issues, maxAgeIssues)\n\n\t\t\tif len(maxAgeIssues.Errors) > 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif hstsHeader.MaxAge == MAX_AGE_NOT_PRESENT {\n\t\t\t\thstsHeader.MaxAge = maxAge\n\t\t\t} else {\n\t\t\t\tissues = issues.addUniqueWarning(fmt.Sprintf(\"Syntax warning: Header contains a repeated directive: `max-age`\"))\n\t\t\t}\n\n\t\tcase directiveHasPrefixIgnoringCase(\"max-age\"):\n\t\t\tissues = issues.addUniqueError(\"Syntax error: A max-age directive name is present without an associated value.\")\n\n\t\tcase directiveEqualsIgnoringCase(\"\"):\n\t\t\tissues = issues.addUniqueWarning(\"Syntax warning: Header includes an empty directive or extra semicolon.\")\n\n\t\tdefault:\n\t\t\tissues = issues.addWarning(fmt.Sprintf(\"Syntax warning: Header contains an unknown directive: `%s`\", directive))\n\t\t}\n\t}\n\treturn hstsHeader, issues\n}\n\n\/\/ This function checks whether the `HSTSHeader` matches all\n\/\/ requirements for preloading in Chromium.\n\/\/\n\/\/ To interpret the result, see the list of conventions in the\n\/\/ documentation for `Issues`.\n\/\/\n\/\/ Most of the time, you'll probably want to use `CheckHeaderString()` instead.\nfunc CheckHeader(hstsHeader HSTSHeader) Issues {\n\tissues := NewIssues()\n\n\tif !hstsHeader.IncludeSubDomains {\n\t\tissues = issues.addError(\"Header requirement error: Header must contain the `includeSubDomains` directive.\")\n\t}\n\n\tif !hstsHeader.Preload {\n\t\tissues = issues.addError(\"Header requirement error: Header must contain the `preload` directive.\")\n\t}\n\n\tswitch {\n\tcase hstsHeader.MaxAge == MAX_AGE_NOT_PRESENT:\n\t\tissues = issues.addError(\"Header requirement error: Header must contain a valid `max-age` directive.\")\n\n\tcase hstsHeader.MaxAge < 0:\n\t\tissues = issues.addError(fmt.Sprintf(\"Internal error: encountered an HSTSHeader with a negative max-age that does not equal MAX_AGE_NOT_PRESENT: %d\", hstsHeader.MaxAge))\n\n\tcase hstsHeader.MaxAge < hstsMinimumMaxAge:\n\t\tissues = issues.addError(fmt.Sprintf(\n\t\t\t\"Header requirement error: The max-age must be at least 10886400 seconds (== 18 weeks), but the header only had max-age=%d.\",\n\t\t\thstsHeader.MaxAge,\n\t\t))\n\n\tcase hstsHeader.MaxAge > hstsChromeMaxAgeCapOneYear:\n\t\tissues = issues.addWarning(fmt.Sprintf(\n\t\t\t\"Header FYI: The max-age (%d seconds) is longer than a year. Note that Chrome will round HSTS header max-age values down to 1 year (%d seconds).\",\n\t\t\thstsHeader.MaxAge,\n\t\t\thstsChromeMaxAgeCapOneYear,\n\t\t))\n\n\t}\n\n\treturn issues\n}\n\n\/\/ This convenience function calls ParseHeaderString() and then calls on\n\/\/ the parsed headerCheckHeader(). It returns all issues from both calls, combined.\n\/\/\n\/\/ To interpret the result, see the list of conventions in the\n\/\/ documentation for `Issues`.\n\/\/\n\/\/ Example Usage:\n\/\/\n\/\/     hstsHeader, issues := ParseHeaderString(\"includeSubDomains; max-age;\")\n\/\/\n\/\/     hstsHeader.Errors[0] == \"Header requirement error: Header must contain the `preload` directive.\"\n\/\/     hstsHeader.Warnings[0] == \"Header FYI: The max-age (31536001 seconds) is longer than a year. Note that Chrome will round HSTS header max-age values down to 1 year (31536000 seconds).\"\nfunc CheckHeaderString(headerString string) Issues {\n\thstsHeader, issues := ParseHeaderString(headerString)\n\treturn combineIssues(issues, CheckHeader(hstsHeader))\n}\n<|endoftext|>"}
{"text":"<commit_before>package compiler\n\nimport (\n\tboshmodels \"bosh\/agent\/applier\/models\"\n\tfakepa \"bosh\/agent\/applier\/packageapplier\/fakes\"\n\tfakeblobstore \"bosh\/blobstore\/fakes\"\n\tfakecmd \"bosh\/platform\/commands\/fakes\"\n\tboshdirs \"bosh\/settings\/directories\"\n\tboshsys \"bosh\/system\"\n\tfakesys \"bosh\/system\/fakes\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestCompileReturnsBlobIdAndSha1(t *testing.T) {\n\t_, blobstore, _, _, _, compiler := buildCompiler()\n\n\tblobstore.CreateBlobId = \"my-blob-id\"\n\tblobstore.CreateFingerprint = \"blob-sha1\"\n\tpkg, deps := getCompileArgs()\n\n\tblobId, sha1, err := compiler.Compile(pkg, deps)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, \"my-blob-id\", blobId)\n\tassert.Equal(t, \"blob-sha1\", sha1)\n}\n\nfunc TestCompileFetchesSourcePackageFromBlobstore(t *testing.T) {\n\t_, blobstore, _, _, _, compiler := buildCompiler()\n\n\tpkg, deps := getCompileArgs()\n\n\t_, _, err := compiler.Compile(pkg, deps)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, \"blobstore_id\", blobstore.GetBlobIds[0])\n\tassert.Equal(t, \"sha1\", blobstore.GetFingerprints[0])\n}\n\nfunc TestCompileInstallsDependentPackages(t *testing.T) {\n\t_, _, _, _, packageApplier, compiler := buildCompiler()\n\n\tpkg, deps := getCompileArgs()\n\n\t_, _, err := compiler.Compile(pkg, deps)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, packageApplier.AppliedPackages, deps)\n}\n\nfunc TestCompileExtractsSourcePkgToCompileDir(t *testing.T) {\n\tcompressor, blobstore, fs, _, _, compiler := buildCompiler()\n\n\tpkg, deps := getCompileArgs()\n\n\tblobstore.GetFileName = \"\/dev\/null\"\n\n\t_, _, err := compiler.Compile(pkg, deps)\n\tassert.NoError(t, err)\n\n\tassert.True(t, fs.FileExists(\"\/fake-dir\/data\/compile\/pkg_name\"))\n\tassert.Equal(t, compressor.DecompressFileToDirDirs[0], \"\/fake-dir\/data\/compile\/pkg_name-bosh-agent-unpack\")\n\tassert.Equal(t, compressor.DecompressFileToDirTarballPaths[0], blobstore.GetFileName)\n\n\tassert.Equal(t, fs.RenameOldPaths[0], \"\/fake-dir\/data\/compile\/pkg_name-bosh-agent-unpack\")\n\tassert.Equal(t, fs.RenameNewPaths[0], \"\/fake-dir\/data\/compile\/pkg_name\")\n}\n\nfunc TestCompileCreatesInstallDir(t *testing.T) {\n\t_, _, fs, _, _, compiler := buildCompiler()\n\n\tpkg, deps := getCompileArgs()\n\n\tinstallDir := \"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\"\n\n\tassert.False(t, fs.FileExists(installDir))\n\n\t_, _, err := compiler.Compile(pkg, deps)\n\tassert.NoError(t, err)\n\n\tassert.True(t, fs.FileExists(installDir))\n\tinstallDirStats := fs.GetFileTestStat(installDir)\n\tassert.Equal(t, os.FileMode(0755), installDirStats.FileMode.Perm())\n}\n\nfunc TestCompileRecreatesInstallDir(t *testing.T) {\n\t_, _, fs, _, _, compiler := buildCompiler()\n\n\tpkg, deps := getCompileArgs()\n\n\terr := fs.MkdirAll(\"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\", os.FileMode(0755))\n\tassert.NoError(t, err)\n\n\t_, err = fs.WriteToFile(\"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\/should_be_deleted\", \"test\")\n\tassert.NoError(t, err)\n\n\tassert.True(t, fs.FileExists(\"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\/should_be_deleted\"))\n\n\t_, _, err = compiler.Compile(pkg, deps)\n\tassert.NoError(t, err)\n\n\tassert.False(t, fs.FileExists(\"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\/should_be_deleted\"))\n}\n\nfunc TestCompileSymlinksInstallDir(t *testing.T) {\n\t_, _, fs, _, _, compiler := buildCompiler()\n\n\tpkg, deps := getCompileArgs()\n\n\t_, _, err := compiler.Compile(pkg, deps)\n\tassert.NoError(t, err)\n\n\tfileStats := fs.GetFileTestStat(\"\/fake-dir\/packages\/pkg_name\")\n\tassert.NotNil(t, fileStats)\n\tassert.Equal(t, fakesys.FakeFileTypeSymlink, fileStats.FileType)\n\tassert.Equal(t, \"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\", fileStats.SymlinkTarget)\n}\n\nfunc TestCompileCompressesCompiledPackage(t *testing.T) {\n\tcompressor, _, _, _, _, compiler := buildCompiler()\n\n\tpkg, deps := getCompileArgs()\n\n\t_, _, err := compiler.Compile(pkg, deps)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, \"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\", compressor.CompressFilesInDirDir)\n}\n\nfunc TestCompileWhenScriptDoesNotExist(t *testing.T) {\n\t_, _, _, runner, _, compiler := buildCompiler()\n\n\tpkg, deps := getCompileArgs()\n\n\t_, _, err := compiler.Compile(pkg, deps)\n\tassert.NoError(t, err)\n\n\tassert.Empty(t, runner.RunCommands)\n}\n\nfunc TestCompileWhenScriptExists(t *testing.T) {\n\tcompressor, _, fs, runner, _, compiler := buildCompiler()\n\n\tpkg, deps := getCompileArgs()\n\n\tcompressor.DecompressFileToDirCallBack = func() {\n\t\tfs.WriteToFile(\"\/fake-dir\/data\/compile\/pkg_name\/packaging\", \"hi\")\n\t}\n\n\t_, _, err := compiler.Compile(pkg, deps)\n\tassert.NoError(t, err)\n\n\texpectedCmd := boshsys.Command{\n\t\tName: \"bash\",\n\t\tArgs: []string{\"-x\", \"packaging\"},\n\t\tEnv: map[string]string{\n\t\t\t\"BOSH_COMPILE_TARGET\":  \"\/fake-dir\/data\/compile\/pkg_name\",\n\t\t\t\"BOSH_INSTALL_TARGET\":  \"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\",\n\t\t\t\"BOSH_PACKAGE_NAME\":    \"pkg_name\",\n\t\t\t\"BOSH_PACKAGE_VERSION\": \"pkg_version\",\n\t\t},\n\t\tWorkingDir: \"\/fake-dir\/data\/compile\/pkg_name\",\n\t}\n\n\tassert.Equal(t, 1, len(runner.RunComplexCommands))\n\tassert.Equal(t, expectedCmd, runner.RunComplexCommands[0])\n}\n\nfunc TestCompileUploadsCompressedPackage(t *testing.T) {\n\tcompressor, blobstore, _, _, _, compiler := buildCompiler()\n\n\tpkg, deps := getCompileArgs()\n\n\tcompressor.CompressFilesInDirTarballPath = \"\/tmp\/foo\"\n\n\t_, _, err := compiler.Compile(pkg, deps)\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"\/tmp\/foo\", blobstore.CreateFileName)\n}\n\nfunc getCompileArgs() (pkg Package, deps []boshmodels.Package) {\n\tpkg = Package{\n\t\tBlobstoreId: \"blobstore_id\",\n\t\tSha1:        \"sha1\",\n\t\tName:        \"pkg_name\",\n\t\tVersion:     \"pkg_version\",\n\t}\n\tdeps = []boshmodels.Package{\n\t\t{\n\t\t\tName:    \"first_dep\",\n\t\t\tVersion: \"first_dep_version\",\n\t\t\tSource: boshmodels.Source{\n\t\t\t\tSha1:        \"first_dep_sha1\",\n\t\t\t\tBlobstoreId: \"first_dep_blobstore_id\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:    \"sec_dep\",\n\t\t\tVersion: \"sec_dep_version\",\n\t\t\tSource: boshmodels.Source{\n\t\t\t\tSha1:        \"sec_dep_sha1\",\n\t\t\t\tBlobstoreId: \"sec_dep_blobstore_id\",\n\t\t\t},\n\t\t},\n\t}\n\treturn\n}\n\nfunc buildCompiler() (\n\tcompressor *fakecmd.FakeCompressor,\n\tblobstore *fakeblobstore.FakeBlobstore,\n\tfs *fakesys.FakeFileSystem,\n\trunner *fakesys.FakeCmdRunner,\n\tpackageApplier *fakepa.FakePackageApplier,\n\tcompiler Compiler,\n) {\n\tcompressor = fakecmd.NewFakeCompressor()\n\tblobstore = &fakeblobstore.FakeBlobstore{}\n\tfs = fakesys.NewFakeFileSystem()\n\trunner = fakesys.NewFakeCmdRunner()\n\tpackageApplier = fakepa.NewFakePackageApplier()\n\tcompiler = NewConcreteCompiler(compressor, blobstore, fs, runner, boshdirs.NewDirectoriesProvider(\"\/fake-dir\"), packageApplier)\n\treturn\n}\n<commit_msg>use dependency struct to simplify tests for concreteCompiler<commit_after>package compiler\n\nimport (\n\tboshmodels \"bosh\/agent\/applier\/models\"\n\tfakepa \"bosh\/agent\/applier\/packageapplier\/fakes\"\n\tfakeblobstore \"bosh\/blobstore\/fakes\"\n\tfakecmd \"bosh\/platform\/commands\/fakes\"\n\tboshdirs \"bosh\/settings\/directories\"\n\tboshsys \"bosh\/system\"\n\tfakesys \"bosh\/system\/fakes\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestCompileReturnsBlobIdAndSha1(t *testing.T) {\n\tdeps, compiler := buildCompiler()\n\n\tdeps.blobstore.CreateBlobId = \"my-blob-id\"\n\tdeps.blobstore.CreateFingerprint = \"blob-sha1\"\n\tpkg, pkgDeps := getCompileArgs()\n\n\tblobId, sha1, err := compiler.Compile(pkg, pkgDeps)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, \"my-blob-id\", blobId)\n\tassert.Equal(t, \"blob-sha1\", sha1)\n}\n\nfunc TestCompileFetchesSourcePackageFromBlobstore(t *testing.T) {\n\tdeps, compiler := buildCompiler()\n\n\tpkg, pkgDeps := getCompileArgs()\n\n\t_, _, err := compiler.Compile(pkg, pkgDeps)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, \"blobstore_id\", deps.blobstore.GetBlobIds[0])\n\tassert.Equal(t, \"sha1\", deps.blobstore.GetFingerprints[0])\n}\n\nfunc TestCompileInstallsDependentPackages(t *testing.T) {\n\tdeps, compiler := buildCompiler()\n\n\tpkg, pkgDeps := getCompileArgs()\n\n\t_, _, err := compiler.Compile(pkg, pkgDeps)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, deps.packageApplier.AppliedPackages, pkgDeps)\n}\n\nfunc TestCompileExtractsSourcePkgToCompileDir(t *testing.T) {\n\tdeps, compiler := buildCompiler()\n\n\tpkg, pkgDeps := getCompileArgs()\n\n\tdeps.blobstore.GetFileName = \"\/dev\/null\"\n\n\t_, _, err := compiler.Compile(pkg, pkgDeps)\n\tassert.NoError(t, err)\n\n\tassert.True(t, deps.fs.FileExists(\"\/fake-dir\/data\/compile\/pkg_name\"))\n\tassert.Equal(t, deps.compressor.DecompressFileToDirDirs[0], \"\/fake-dir\/data\/compile\/pkg_name-bosh-agent-unpack\")\n\tassert.Equal(t, deps.compressor.DecompressFileToDirTarballPaths[0], deps.blobstore.GetFileName)\n\n\tassert.Equal(t, deps.fs.RenameOldPaths[0], \"\/fake-dir\/data\/compile\/pkg_name-bosh-agent-unpack\")\n\tassert.Equal(t, deps.fs.RenameNewPaths[0], \"\/fake-dir\/data\/compile\/pkg_name\")\n}\n\nfunc TestCompileCreatesInstallDir(t *testing.T) {\n\tdeps, compiler := buildCompiler()\n\n\tpkg, pkgDeps := getCompileArgs()\n\n\tinstallDir := \"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\"\n\n\tassert.False(t, deps.fs.FileExists(installDir))\n\n\t_, _, err := compiler.Compile(pkg, pkgDeps)\n\tassert.NoError(t, err)\n\n\tassert.True(t, deps.fs.FileExists(installDir))\n\tinstallDirStats := deps.fs.GetFileTestStat(installDir)\n\tassert.Equal(t, os.FileMode(0755), installDirStats.FileMode.Perm())\n}\n\nfunc TestCompileRecreatesInstallDir(t *testing.T) {\n\tdeps, compiler := buildCompiler()\n\n\tpkg, pkgDeps := getCompileArgs()\n\n\terr := deps.fs.MkdirAll(\"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\", os.FileMode(0755))\n\tassert.NoError(t, err)\n\n\t_, err = deps.fs.WriteToFile(\"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\/should_be_deleted\", \"test\")\n\tassert.NoError(t, err)\n\n\tassert.True(t, deps.fs.FileExists(\"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\/should_be_deleted\"))\n\n\t_, _, err = compiler.Compile(pkg, pkgDeps)\n\tassert.NoError(t, err)\n\n\tassert.False(t, deps.fs.FileExists(\"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\/should_be_deleted\"))\n}\n\nfunc TestCompileSymlinksInstallDir(t *testing.T) {\n\tdeps, compiler := buildCompiler()\n\n\tpkg, pkgDeps := getCompileArgs()\n\n\t_, _, err := compiler.Compile(pkg, pkgDeps)\n\tassert.NoError(t, err)\n\n\tfileStats := deps.fs.GetFileTestStat(\"\/fake-dir\/packages\/pkg_name\")\n\tassert.NotNil(t, fileStats)\n\tassert.Equal(t, fakesys.FakeFileTypeSymlink, fileStats.FileType)\n\tassert.Equal(t, \"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\", fileStats.SymlinkTarget)\n}\n\nfunc TestCompileCompressesCompiledPackage(t *testing.T) {\n\tdeps, compiler := buildCompiler()\n\n\tpkg, pkgDeps := getCompileArgs()\n\n\t_, _, err := compiler.Compile(pkg, pkgDeps)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, \"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\", deps.compressor.CompressFilesInDirDir)\n}\n\nfunc TestCompileWhenScriptDoesNotExist(t *testing.T) {\n\tdeps, compiler := buildCompiler()\n\n\tpkg, pkgDeps := getCompileArgs()\n\n\t_, _, err := compiler.Compile(pkg, pkgDeps)\n\tassert.NoError(t, err)\n\n\tassert.Empty(t, deps.runner.RunCommands)\n}\n\nfunc TestCompileWhenScriptExists(t *testing.T) {\n\tdeps, compiler := buildCompiler()\n\n\tpkg, pkgDeps := getCompileArgs()\n\n\tdeps.compressor.DecompressFileToDirCallBack = func() {\n\t\tdeps.fs.WriteToFile(\"\/fake-dir\/data\/compile\/pkg_name\/packaging\", \"hi\")\n\t}\n\n\t_, _, err := compiler.Compile(pkg, pkgDeps)\n\tassert.NoError(t, err)\n\n\texpectedCmd := boshsys.Command{\n\t\tName: \"bash\",\n\t\tArgs: []string{\"-x\", \"packaging\"},\n\t\tEnv: map[string]string{\n\t\t\t\"BOSH_COMPILE_TARGET\":  \"\/fake-dir\/data\/compile\/pkg_name\",\n\t\t\t\"BOSH_INSTALL_TARGET\":  \"\/fake-dir\/data\/packages\/pkg_name\/pkg_version\",\n\t\t\t\"BOSH_PACKAGE_NAME\":    \"pkg_name\",\n\t\t\t\"BOSH_PACKAGE_VERSION\": \"pkg_version\",\n\t\t},\n\t\tWorkingDir: \"\/fake-dir\/data\/compile\/pkg_name\",\n\t}\n\n\tassert.Equal(t, 1, len(deps.runner.RunComplexCommands))\n\tassert.Equal(t, expectedCmd, deps.runner.RunComplexCommands[0])\n}\n\nfunc TestCompileUploadsCompressedPackage(t *testing.T) {\n\tdeps, compiler := buildCompiler()\n\n\tpkg, pkgDeps := getCompileArgs()\n\n\tdeps.compressor.CompressFilesInDirTarballPath = \"\/tmp\/foo\"\n\n\t_, _, err := compiler.Compile(pkg, pkgDeps)\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"\/tmp\/foo\", deps.blobstore.CreateFileName)\n}\n\nfunc getCompileArgs() (pkg Package, pkgDeps []boshmodels.Package) {\n\tpkg = Package{\n\t\tBlobstoreId: \"blobstore_id\",\n\t\tSha1:        \"sha1\",\n\t\tName:        \"pkg_name\",\n\t\tVersion:     \"pkg_version\",\n\t}\n\tpkgDeps = []boshmodels.Package{\n\t\t{\n\t\t\tName:    \"first_dep\",\n\t\t\tVersion: \"first_dep_version\",\n\t\t\tSource: boshmodels.Source{\n\t\t\t\tSha1:        \"first_dep_sha1\",\n\t\t\t\tBlobstoreId: \"first_dep_blobstore_id\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:    \"sec_dep\",\n\t\t\tVersion: \"sec_dep_version\",\n\t\t\tSource: boshmodels.Source{\n\t\t\t\tSha1:        \"sec_dep_sha1\",\n\t\t\t\tBlobstoreId: \"sec_dep_blobstore_id\",\n\t\t\t},\n\t\t},\n\t}\n\treturn\n}\n\ntype compilerDeps struct {\n\tcompressor     *fakecmd.FakeCompressor\n\tblobstore      *fakeblobstore.FakeBlobstore\n\tfs             *fakesys.FakeFileSystem\n\trunner         *fakesys.FakeCmdRunner\n\tpackageApplier *fakepa.FakePackageApplier\n}\n\nfunc buildCompiler() (\n\tdeps compilerDeps,\n\tcompiler Compiler,\n) {\n\tdeps.compressor = fakecmd.NewFakeCompressor()\n\tdeps.blobstore = &fakeblobstore.FakeBlobstore{}\n\tdeps.fs = fakesys.NewFakeFileSystem()\n\tdeps.runner = fakesys.NewFakeCmdRunner()\n\tdeps.packageApplier = fakepa.NewFakePackageApplier()\n\n\tcompiler = NewConcreteCompiler(\n\t\tdeps.compressor,\n\t\tdeps.blobstore,\n\t\tdeps.fs,\n\t\tdeps.runner,\n\t\tboshdirs.NewDirectoriesProvider(\"\/fake-dir\"),\n\t\tdeps.packageApplier,\n\t)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ The supervisor acts as the glue between the cli and the storm topology\n\/\/ - The storm topology communicates with the supervisor in order to determine settings, etc.\n\/\/ - The cli communicates with the supervisor to modify settings, get results, etc.\n\/\/ @author Robin Verlangen\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/base64\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/RobinUS2\/golang-jresp\"\n\t\"github.com\/julienschmidt\/httprouter\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\nvar serverPort int\nvar basicAuthUsr string\nvar basicAuthPwd string\nvar dbFile string\nvar filterManager *FilterManager\n\nfunc init() {\n\tflag.IntVar(&serverPort, \"port\", 1525, \"Server port\")\n\tflag.StringVar(&basicAuthUsr, \"auth-user\", \"cloud\", \"Username\")\n\tflag.StringVar(&basicAuthPwd, \"auth-password\", \"pelican\", \"Password\")\n\tflag.StringVar(&dbFile, \"db-file\", \"cloudpelican_lsd_supervisor.db\", \"Database file\")\n\tflag.Parse()\n}\n\nfunc main() {\n\t\/\/ Filter manager\n\tfilterManager = NewFilterManager()\n\n\t\/\/ Routing\n\trouter := httprouter.New()\n\n\t\/\/ Docs\n\trouter.GET(\"\/\", GetHome)\n\n\t\/\/ Filters\n\trouter.POST(\"\/filter\", PostFilter)                \/\/ Create new filter\n\trouter.GET(\"\/filter\/:id\/result\", GetFilterResult) \/\/ Get results of a single filter\n\trouter.PUT(\"\/filter\/:id\/result\", PutFilterResult) \/\/ Store new results into a filter\n\trouter.GET(\"\/filter\", GetFilter)                  \/\/ Get all filters\n\trouter.DELETE(\"\/filter\/:id\", DeleteFilter)        \/\/ Delete a filter\n\n\t\/\/ Start webserver\n\tlog.Println(fmt.Sprintf(\"Starting supervisor service at port %d\", serverPort))\n\tlog.Fatal(http.ListenAndServe(fmt.Sprintf(\":%d\", serverPort), router))\n}\n\nfunc GetHome(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tif !basicAuth(w, r) {\n\t\treturn\n\t}\n\tjresp := jresp.NewJsonResp()\n\tjresp.Set(\"hello\", \"This is the CloudPelican supervisor\")\n\tjresp.OK()\n\tfmt.Fprint(w, jresp.ToString(false))\n}\n\nfunc PostFilter(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tif !basicAuth(w, r) {\n\t\treturn\n\t}\n\tjresp := jresp.NewJsonResp()\n\n\t\/\/ Validate\n\tregex := strings.TrimSpace(r.URL.Query().Get(\"regex\"))\n\tif len(regex) < 1 {\n\t\tjresp.Error(\"Please provide a regex\")\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\tname := strings.TrimSpace(r.URL.Query().Get(\"name\"))\n\tif len(name) < 1 {\n\t\tjresp.Error(\"Please provide a name\")\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\n\t\/\/ Create filter\n\tid, err := filterManager.CreateFilter(name, r.RemoteAddr, regex)\n\tif err != nil {\n\t\tjresp.Error(fmt.Sprintf(\"Failed to create filter: %s\", err))\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\n\t\/\/ OK :)\n\tjresp.Set(\"filter_id\", id)\n\tjresp.OK()\n\tfmt.Fprint(w, jresp.ToString(false))\n}\n\nfunc GetFilterResult(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tif !basicAuth(w, r) {\n\t\treturn\n\t}\n\tjresp := jresp.NewJsonResp()\n\tid := strings.TrimSpace(ps.ByName(\"id\"))\n\tif len(id) < 1 {\n\t\tjresp.Error(\"Please provide an ID\")\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\tfilter := filterManager.GetFilter(id)\n\tif filter == nil {\n\t\tjresp.Error(fmt.Sprintf(\"Filter %s not found\", id))\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\tjresp.Set(\"results\", filter.Results)\n\tjresp.OK()\n\tfmt.Fprint(w, jresp.ToString(false))\n}\n\nfunc PutFilterResult(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tif !basicAuth(w, r) {\n\t\treturn\n\t}\n\tjresp := jresp.NewJsonResp()\n\tid := strings.TrimSpace(ps.ByName(\"id\"))\n\tif len(id) < 1 {\n\t\tjresp.Error(\"Please provide an ID\")\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\tfilter := filterManager.GetFilter(id)\n\tif filter == nil {\n\t\tjresp.Error(fmt.Sprintf(\"Filter %s not found\", id))\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\n\t\/\/ Read body\n\tscanner := bufio.NewScanner(r.Body)\n\tscanner.Split(bufio.ScanLines)\n\tvar lines []string = make([]string, 0)\n\tfor scanner.Scan() {\n\t\tlines = append(lines, scanner.Text())\n\t}\n\n\t\/\/ Add results\n\tres := filter.AddResults(lines)\n\tjresp.Set(\"ack\", res)\n\tjresp.Set(\"lines\", len(lines))\n\tjresp.OK()\n\tfmt.Fprint(w, jresp.ToString(false))\n}\n\nfunc GetFilter(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tif !basicAuth(w, r) {\n\t\treturn\n\t}\n\tjresp := jresp.NewJsonResp()\n\tfilters := filterManager.GetFilters()\n\tvar filtersNoRes []*Filter = make([]*Filter, 0)\n\tfor _, filter := range filters {\n\t\tfilter.Results = nil\n\t\tfiltersNoRes = append(filtersNoRes, filter)\n\t}\n\tjresp.Set(\"filters\", filtersNoRes)\n\tjresp.OK()\n\tfmt.Fprint(w, jresp.ToString(false))\n}\n\nfunc DeleteFilter(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tif !basicAuth(w, r) {\n\t\treturn\n\t}\n\tjresp := jresp.NewJsonResp()\n\tid := strings.TrimSpace(ps.ByName(\"id\"))\n\tif len(id) < 1 {\n\t\tjresp.Error(\"Please provide an ID\")\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\tres := filterManager.DeleteFilter(id)\n\tjresp.Set(\"deleted\", res)\n\tjresp.OK()\n\tfmt.Fprint(w, jresp.ToString(false))\n}\n\nfunc basicAuth(w http.ResponseWriter, r *http.Request) bool {\n\tif r.Header[\"Authorization\"] == nil || len(r.Header[\"Authorization\"]) < 1 {\n\t\tlog.Printf(\"%s\", r.Header)\n\t\thttp.Error(w, \"bad syntax a\", http.StatusBadRequest)\n\t\treturn false\n\t}\n\tauth := strings.SplitN(r.Header[\"Authorization\"][0], \" \", 2)\n\n\tif len(auth) != 2 || auth[0] != \"Basic\" {\n\t\tlog.Printf(\"%s\", r.Header)\n\t\thttp.Error(w, \"bad syntax b\", http.StatusBadRequest)\n\t\treturn false\n\t}\n\n\tpayload, _ := base64.StdEncoding.DecodeString(auth[1])\n\tpair := strings.SplitN(string(payload), \":\", 2)\n\n\tif len(pair) != 2 || !validateAuth(pair[0], pair[1]) {\n\t\thttp.Error(w, \"authorization failed\", http.StatusUnauthorized)\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc validateAuth(username, password string) bool {\n\tif username == basicAuthUsr && password == basicAuthPwd {\n\t\treturn true\n\t}\n\treturn false\n}\n<commit_msg>Clear res after retrieve<commit_after>\/\/ The supervisor acts as the glue between the cli and the storm topology\n\/\/ - The storm topology communicates with the supervisor in order to determine settings, etc.\n\/\/ - The cli communicates with the supervisor to modify settings, get results, etc.\n\/\/ @author Robin Verlangen\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/base64\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/RobinUS2\/golang-jresp\"\n\t\"github.com\/julienschmidt\/httprouter\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\nvar serverPort int\nvar basicAuthUsr string\nvar basicAuthPwd string\nvar dbFile string\nvar filterManager *FilterManager\n\nfunc init() {\n\tflag.IntVar(&serverPort, \"port\", 1525, \"Server port\")\n\tflag.StringVar(&basicAuthUsr, \"auth-user\", \"cloud\", \"Username\")\n\tflag.StringVar(&basicAuthPwd, \"auth-password\", \"pelican\", \"Password\")\n\tflag.StringVar(&dbFile, \"db-file\", \"cloudpelican_lsd_supervisor.db\", \"Database file\")\n\tflag.Parse()\n}\n\nfunc main() {\n\t\/\/ Filter manager\n\tfilterManager = NewFilterManager()\n\n\t\/\/ Routing\n\trouter := httprouter.New()\n\n\t\/\/ Docs\n\trouter.GET(\"\/\", GetHome)\n\n\t\/\/ Filters\n\trouter.POST(\"\/filter\", PostFilter)                \/\/ Create new filter\n\trouter.GET(\"\/filter\/:id\/result\", GetFilterResult) \/\/ Get results of a single filter\n\trouter.PUT(\"\/filter\/:id\/result\", PutFilterResult) \/\/ Store new results into a filter\n\trouter.GET(\"\/filter\", GetFilter)                  \/\/ Get all filters\n\trouter.DELETE(\"\/filter\/:id\", DeleteFilter)        \/\/ Delete a filter\n\n\t\/\/ Start webserver\n\tlog.Println(fmt.Sprintf(\"Starting supervisor service at port %d\", serverPort))\n\tlog.Fatal(http.ListenAndServe(fmt.Sprintf(\":%d\", serverPort), router))\n}\n\nfunc GetHome(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tif !basicAuth(w, r) {\n\t\treturn\n\t}\n\tjresp := jresp.NewJsonResp()\n\tjresp.Set(\"hello\", \"This is the CloudPelican supervisor\")\n\tjresp.OK()\n\tfmt.Fprint(w, jresp.ToString(false))\n}\n\nfunc PostFilter(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tif !basicAuth(w, r) {\n\t\treturn\n\t}\n\tjresp := jresp.NewJsonResp()\n\n\t\/\/ Validate\n\tregex := strings.TrimSpace(r.URL.Query().Get(\"regex\"))\n\tif len(regex) < 1 {\n\t\tjresp.Error(\"Please provide a regex\")\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\tname := strings.TrimSpace(r.URL.Query().Get(\"name\"))\n\tif len(name) < 1 {\n\t\tjresp.Error(\"Please provide a name\")\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\n\t\/\/ Create filter\n\tid, err := filterManager.CreateFilter(name, r.RemoteAddr, regex)\n\tif err != nil {\n\t\tjresp.Error(fmt.Sprintf(\"Failed to create filter: %s\", err))\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\n\t\/\/ OK :)\n\tjresp.Set(\"filter_id\", id)\n\tjresp.OK()\n\tfmt.Fprint(w, jresp.ToString(false))\n}\n\nfunc GetFilterResult(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tif !basicAuth(w, r) {\n\t\treturn\n\t}\n\tjresp := jresp.NewJsonResp()\n\tid := strings.TrimSpace(ps.ByName(\"id\"))\n\tif len(id) < 1 {\n\t\tjresp.Error(\"Please provide an ID\")\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\tfilter := filterManager.GetFilter(id)\n\tif filter == nil {\n\t\tjresp.Error(fmt.Sprintf(\"Filter %s not found\", id))\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\tfilter.resultsMux.RLock()\n\tjresp.Set(\"results\", filter.Results)\n\tfilter.resultsMux.RUnlock()\n\tjresp.OK()\n\tfmt.Fprint(w, jresp.ToString(false))\n\n\t\/\/ Clear results\n\tfilter.resultsMux.Lock()\n\tfilter.Results = make([]string, 0)\n\tfilter.resultsMux.Unlock()\n\tfilter.Save()\n}\n\nfunc PutFilterResult(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tif !basicAuth(w, r) {\n\t\treturn\n\t}\n\tjresp := jresp.NewJsonResp()\n\tid := strings.TrimSpace(ps.ByName(\"id\"))\n\tif len(id) < 1 {\n\t\tjresp.Error(\"Please provide an ID\")\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\tfilter := filterManager.GetFilter(id)\n\tif filter == nil {\n\t\tjresp.Error(fmt.Sprintf(\"Filter %s not found\", id))\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\n\t\/\/ Read body\n\tscanner := bufio.NewScanner(r.Body)\n\tscanner.Split(bufio.ScanLines)\n\tvar lines []string = make([]string, 0)\n\tfor scanner.Scan() {\n\t\tlines = append(lines, scanner.Text())\n\t}\n\n\t\/\/ Add results\n\tres := filter.AddResults(lines)\n\tjresp.Set(\"ack\", res)\n\tjresp.Set(\"lines\", len(lines))\n\tjresp.OK()\n\tfmt.Fprint(w, jresp.ToString(false))\n}\n\nfunc GetFilter(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tif !basicAuth(w, r) {\n\t\treturn\n\t}\n\tjresp := jresp.NewJsonResp()\n\tfilters := filterManager.GetFilters()\n\tvar filtersNoRes []*Filter = make([]*Filter, 0)\n\tfor _, filter := range filters {\n\t\tfilter.Results = nil\n\t\tfiltersNoRes = append(filtersNoRes, filter)\n\t}\n\tjresp.Set(\"filters\", filtersNoRes)\n\tjresp.OK()\n\tfmt.Fprint(w, jresp.ToString(false))\n}\n\nfunc DeleteFilter(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tif !basicAuth(w, r) {\n\t\treturn\n\t}\n\tjresp := jresp.NewJsonResp()\n\tid := strings.TrimSpace(ps.ByName(\"id\"))\n\tif len(id) < 1 {\n\t\tjresp.Error(\"Please provide an ID\")\n\t\tfmt.Fprint(w, jresp.ToString(false))\n\t\treturn\n\t}\n\tres := filterManager.DeleteFilter(id)\n\tjresp.Set(\"deleted\", res)\n\tjresp.OK()\n\tfmt.Fprint(w, jresp.ToString(false))\n}\n\nfunc basicAuth(w http.ResponseWriter, r *http.Request) bool {\n\tif r.Header[\"Authorization\"] == nil || len(r.Header[\"Authorization\"]) < 1 {\n\t\tlog.Printf(\"%s\", r.Header)\n\t\thttp.Error(w, \"bad syntax a\", http.StatusBadRequest)\n\t\treturn false\n\t}\n\tauth := strings.SplitN(r.Header[\"Authorization\"][0], \" \", 2)\n\n\tif len(auth) != 2 || auth[0] != \"Basic\" {\n\t\tlog.Printf(\"%s\", r.Header)\n\t\thttp.Error(w, \"bad syntax b\", http.StatusBadRequest)\n\t\treturn false\n\t}\n\n\tpayload, _ := base64.StdEncoding.DecodeString(auth[1])\n\tpair := strings.SplitN(string(payload), \":\", 2)\n\n\tif len(pair) != 2 || !validateAuth(pair[0], pair[1]) {\n\t\thttp.Error(w, \"authorization failed\", http.StatusUnauthorized)\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc validateAuth(username, password string) bool {\n\tif username == basicAuthUsr && password == basicAuthPwd {\n\t\treturn true\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package trust\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/docker\/cli\/cli\"\n\t\"github.com\/docker\/cli\/cli\/command\"\n\t\"github.com\/docker\/cli\/cli\/trust\"\n\t\"github.com\/docker\/notary\/client\"\n\t\"github.com\/docker\/notary\/tuf\/data\"\n\t\"github.com\/spf13\/cobra\"\n)\n\ntype signerRemoveOptions struct {\n\tforceYes bool\n}\n\nfunc newSignerRemoveCommand(dockerCli command.Cli) *cobra.Command {\n\toptions := signerRemoveOptions{}\n\tcmd := &cobra.Command{\n\t\tUse:   \"signer-remove NAME IMAGE [IMAGE...]\",\n\t\tShort: \"Remove a signer\",\n\t\tArgs:  cli.RequiresMinArgs(2),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn removeSigner(dockerCli, args[0], args[1:], &options)\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.BoolVarP(&options.forceYes, \"yes\", \"y\", false, \"Answer yes to removing most recent signer (no confirmation)\")\n\treturn cmd\n}\n\nfunc removeSigner(cli command.Cli, signer string, images []string, options *signerRemoveOptions) error {\n\tfor _, image := range images {\n\t\tif err := removeSingleSigner(cli, image, signer, options.forceYes); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc isLastSignerForReleases(roleWithSig data.Role, allRoles []client.RoleWithSignatures) (bool, error) {\n\tvar releasesRoleWithSigs client.RoleWithSignatures\n\tfor _, role := range allRoles {\n\t\tif role.Name == releasesRoleTUFName {\n\t\t\treleasesRoleWithSigs = role\n\t\t\tbreak\n\t\t}\n\t}\n\tcounter := len(releasesRoleWithSigs.Signatures)\n\tif counter == 0 {\n\t\treturn false, fmt.Errorf(\"All signed tags are currently revoked, use docker trust sign to fix\")\n\t}\n\tfor _, signature := range releasesRoleWithSigs.Signatures {\n\t\tfor _, key := range roleWithSig.KeyIDs {\n\t\t\tif signature.KeyID == key {\n\t\t\t\tcounter--\n\t\t\t}\n\t\t}\n\t}\n\treturn counter < releasesRoleWithSigs.Threshold, nil\n}\n\nfunc removeSingleSigner(cli command.Cli, image, signerName string, forceYes bool) error {\n\t_, ref, repoInfo, authConfig, err := getImageReferencesAndAuth(cli, image)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsignerDelegation := data.RoleName(\"targets\/\" + signerName)\n\tif signerDelegation == releasesRoleTUFName {\n\t\treturn fmt.Errorf(\"releases is a reserved keyword and cannot be removed\")\n\t}\n\tnotaryRepo, err := trust.GetNotaryRepository(cli, repoInfo, *authConfig, \"push\", \"pull\")\n\tif err != nil {\n\t\treturn trust.NotaryError(ref.Name(), err)\n\t}\n\tdelegationRoles, err := notaryRepo.GetDelegationRoles()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error retrieving signers for %s\", image)\n\t}\n\tvar role data.Role\n\tfor _, delRole := range delegationRoles {\n\t\tif delRole.Name == signerDelegation {\n\t\t\trole = delRole\n\t\t\tbreak\n\t\t}\n\t}\n\tif role.Name == \"\" {\n\t\treturn fmt.Errorf(\"No signer %s for image %s\", signerName, image)\n\t}\n\tallRoles, err := notaryRepo.ListRoles()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ok, err := isLastSignerForReleases(role, allRoles); ok && !forceYes {\n\t\tremoveSigner := command.PromptForConfirmation(os.Stdin, cli.Out(), fmt.Sprintf(\"The signer %s signed the last released version of %s. \"+\n\t\t\t\"Removing them will lead to signed tags from %s being unpullable.\"+\n\t\t\t\"Are you sure you want to continue?: \",\n\t\t\tsignerName, image, image,\n\t\t))\n\n\t\tif !removeSigner {\n\t\t\tfmt.Fprintf(cli.Out(), \"\\nAborting action.\\n\")\n\t\t\treturn nil\n\t\t}\n\t} else if err != nil {\n\t\tfmt.Fprintf(cli.Out(), err.Error())\n\t}\n\tif err = notaryRepo.RemoveDelegationKeys(releasesRoleTUFName, role.KeyIDs); err != nil {\n\t\treturn err\n\t}\n\tif err = notaryRepo.RemoveDelegationRole(signerDelegation); err != nil {\n\t\treturn err\n\t}\n\tif err = notaryRepo.Publish(); err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(cli.Out(), \"Successfully removed %s from %s\\n\", signerName, image)\n\treturn nil\n}\n<commit_msg>docker trust remove: add newline to error print<commit_after>package trust\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/docker\/cli\/cli\"\n\t\"github.com\/docker\/cli\/cli\/command\"\n\t\"github.com\/docker\/cli\/cli\/trust\"\n\t\"github.com\/docker\/notary\/client\"\n\t\"github.com\/docker\/notary\/tuf\/data\"\n\t\"github.com\/spf13\/cobra\"\n)\n\ntype signerRemoveOptions struct {\n\tforceYes bool\n}\n\nfunc newSignerRemoveCommand(dockerCli command.Cli) *cobra.Command {\n\toptions := signerRemoveOptions{}\n\tcmd := &cobra.Command{\n\t\tUse:   \"signer-remove NAME IMAGE [IMAGE...]\",\n\t\tShort: \"Remove a signer\",\n\t\tArgs:  cli.RequiresMinArgs(2),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn removeSigner(dockerCli, args[0], args[1:], &options)\n\t\t},\n\t}\n\tflags := cmd.Flags()\n\tflags.BoolVarP(&options.forceYes, \"yes\", \"y\", false, \"Answer yes to removing most recent signer (no confirmation)\")\n\treturn cmd\n}\n\nfunc removeSigner(cli command.Cli, signer string, images []string, options *signerRemoveOptions) error {\n\tfor _, image := range images {\n\t\tif err := removeSingleSigner(cli, image, signer, options.forceYes); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc isLastSignerForReleases(roleWithSig data.Role, allRoles []client.RoleWithSignatures) (bool, error) {\n\tvar releasesRoleWithSigs client.RoleWithSignatures\n\tfor _, role := range allRoles {\n\t\tif role.Name == releasesRoleTUFName {\n\t\t\treleasesRoleWithSigs = role\n\t\t\tbreak\n\t\t}\n\t}\n\tcounter := len(releasesRoleWithSigs.Signatures)\n\tif counter == 0 {\n\t\treturn false, fmt.Errorf(\"All signed tags are currently revoked, use docker trust sign to fix\")\n\t}\n\tfor _, signature := range releasesRoleWithSigs.Signatures {\n\t\tfor _, key := range roleWithSig.KeyIDs {\n\t\t\tif signature.KeyID == key {\n\t\t\t\tcounter--\n\t\t\t}\n\t\t}\n\t}\n\treturn counter < releasesRoleWithSigs.Threshold, nil\n}\n\nfunc removeSingleSigner(cli command.Cli, image, signerName string, forceYes bool) error {\n\t_, ref, repoInfo, authConfig, err := getImageReferencesAndAuth(cli, image)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsignerDelegation := data.RoleName(\"targets\/\" + signerName)\n\tif signerDelegation == releasesRoleTUFName {\n\t\treturn fmt.Errorf(\"releases is a reserved keyword and cannot be removed\")\n\t}\n\tnotaryRepo, err := trust.GetNotaryRepository(cli, repoInfo, *authConfig, \"push\", \"pull\")\n\tif err != nil {\n\t\treturn trust.NotaryError(ref.Name(), err)\n\t}\n\tdelegationRoles, err := notaryRepo.GetDelegationRoles()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error retrieving signers for %s\", image)\n\t}\n\tvar role data.Role\n\tfor _, delRole := range delegationRoles {\n\t\tif delRole.Name == signerDelegation {\n\t\t\trole = delRole\n\t\t\tbreak\n\t\t}\n\t}\n\tif role.Name == \"\" {\n\t\treturn fmt.Errorf(\"No signer %s for image %s\", signerName, image)\n\t}\n\tallRoles, err := notaryRepo.ListRoles()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ok, err := isLastSignerForReleases(role, allRoles); ok && !forceYes {\n\t\tremoveSigner := command.PromptForConfirmation(os.Stdin, cli.Out(), fmt.Sprintf(\"The signer %s signed the last released version of %s. \"+\n\t\t\t\"Removing them will lead to signed tags from %s being unpullable.\"+\n\t\t\t\"Are you sure you want to continue?: \",\n\t\t\tsignerName, image, image,\n\t\t))\n\n\t\tif !removeSigner {\n\t\t\tfmt.Fprintf(cli.Out(), \"\\nAborting action.\\n\")\n\t\t\treturn nil\n\t\t}\n\t} else if err != nil {\n\t\tfmt.Fprintln(cli.Out(), err.Error())\n\t}\n\tif err = notaryRepo.RemoveDelegationKeys(releasesRoleTUFName, role.KeyIDs); err != nil {\n\t\treturn err\n\t}\n\tif err = notaryRepo.RemoveDelegationRole(signerDelegation); err != nil {\n\t\treturn err\n\t}\n\tif err = notaryRepo.Publish(); err != nil {\n\t\treturn err\n\t}\n\tfmt.Fprintf(cli.Out(), \"Successfully removed %s from %s\\n\", signerName, image)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/require\"\n\n\t\"github.com\/kopia\/kopia\/internal\/testutil\"\n\t\"github.com\/kopia\/kopia\/tests\/testenv\"\n)\n\nfunc TestServerControl(t *testing.T) {\n\tenv := testenv.NewCLITest(t, testenv.RepoFormatNotImportant, testenv.NewInProcRunner(t))\n\n\tdir0 := testutil.TempDirectory(t)\n\tdir1 := testutil.TempDirectory(t)\n\tdir2 := testutil.TempDirectory(t)\n\tdir3 := testutil.TempDirectory(t)\n\n\tenv.RunAndExpectSuccess(t, \"repo\", \"create\", \"filesystem\", \"--path\", env.RepoDir, \"--override-username=another-user\", \"--override-hostname=another-host\")\n\tenv.RunAndExpectSuccess(t, \"snap\", \"create\", dir0)\n\n\tenv.RunAndExpectSuccess(t, \"repo\", \"connect\", \"filesystem\", \"--path\", env.RepoDir, \"--override-username=test-user\", \"--override-hostname=test-host\")\n\tenv.RunAndExpectSuccess(t, \"snap\", \"create\", dir1)\n\tenv.RunAndExpectSuccess(t, \"snap\", \"create\", dir2)\n\n\tserverStarted := make(chan struct{})\n\tserverStopped := make(chan struct{})\n\n\tvar sp testutil.ServerParameters\n\n\tgo func() {\n\t\tkill := env.RunAndProcessStderr(t, sp.ProcessOutput,\n\t\t\t\"server\", \"start\", \"--insecure\", \"--random-server-control-password\", \"--address=127.0.0.1:0\")\n\n\t\tclose(serverStarted)\n\n\t\tdefer kill()\n\n\t\tclose(serverStopped)\n\t}()\n\n\tselect {\n\tcase <-serverStarted:\n\t\tt.Logf(\"server started on %v\", sp.BaseURL)\n\n\tcase <-time.After(5 * time.Second):\n\t\tt.Fatalf(\"server did not start in time\")\n\t}\n\n\tconst (\n\t\tpollFrequency = 100 * time.Millisecond\n\t\twaitTimeout   = 5 * time.Second\n\t)\n\n\trequire.Eventually(t, func() bool {\n\t\tlines := env.RunAndExpectSuccess(t, \"server\", \"status\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\t\treturn hasLine(lines, \"IDLE: test-user@test-host:\"+dir1) && hasLine(lines, \"IDLE: test-user@test-host:\"+dir2)\n\t}, waitTimeout, pollFrequency)\n\n\tlines := env.RunAndExpectSuccess(t, \"server\", \"status\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, \"--remote\")\n\trequire.Len(t, lines, 3)\n\trequire.Contains(t, lines, \"IDLE: test-user@test-host:\"+dir1)\n\trequire.Contains(t, lines, \"IDLE: test-user@test-host:\"+dir2)\n\trequire.Contains(t, lines, \"REMOTE: another-user@another-host:\"+dir0)\n\n\t\/\/ create snapshot outside of the server\n\tenv.RunAndExpectSuccess(t, \"snap\", \"create\", dir3)\n\tenv.RunAndExpectSuccess(t, \"server\", \"refresh\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\n\trequire.Eventually(t, func() bool {\n\t\treturn hasLine(\n\t\t\tenv.RunAndExpectSuccess(t, \"server\", \"status\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, \"--remote\"),\n\t\t\t\"IDLE: test-user@test-host:\"+dir3)\n\t}, waitTimeout, pollFrequency)\n\n\tenv.RunAndExpectSuccess(t, \"server\", \"flush\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\n\t\/\/ trigger server snapshot\n\tenv.RunAndExpectSuccess(t, \"server\", \"snapshot\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, \"--all\")\n\tenv.RunAndExpectSuccess(t, \"server\", \"snapshot\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, dir1)\n\tenv.RunAndExpectFailure(t, \"server\", \"snapshot\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, \"no-such-dir\")\n\n\t\/\/ neither dir nor --all specified\n\tenv.RunAndExpectFailure(t, \"server\", \"snapshot\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\n\t\/\/ cancel snapshot\n\tenv.RunAndExpectSuccess(t, \"server\", \"cancel\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, \"--all\")\n\n\tenv.RunAndExpectSuccess(t, \"server\", \"pause\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, dir1)\n\tenv.RunAndExpectSuccess(t, \"server\", \"resume\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, dir1)\n\n\tenv.RunAndExpectSuccess(t, \"server\", \"shutdown\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\n\tselect {\n\tcase <-serverStopped:\n\t\tt.Logf(\"server shut down\")\n\n\tcase <-time.After(5 * time.Second):\n\t\tt.Fatalf(\"server did not shutdown in time\")\n\t}\n\n\t\/\/ this will fail since the server is down\n\tenv.RunAndExpectFailure(t, \"server\", \"status\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\tenv.RunAndExpectFailure(t, \"server\", \"flush\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\tenv.RunAndExpectFailure(t, \"server\", \"refresh\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\tenv.RunAndExpectFailure(t, \"server\", \"shutdown\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n}\n\nfunc hasLine(lines []string, lookFor string) bool {\n\tfor _, l := range lines {\n\t\tif l == lookFor {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n<commit_msg>fix(ci): fixed flaky TestServerControl (#1840)<commit_after>package cli_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/require\"\n\n\t\"github.com\/kopia\/kopia\/internal\/testutil\"\n\t\"github.com\/kopia\/kopia\/tests\/testenv\"\n)\n\nfunc TestServerControl(t *testing.T) {\n\tenv := testenv.NewCLITest(t, testenv.RepoFormatNotImportant, testenv.NewInProcRunner(t))\n\n\tdir0 := testutil.TempDirectory(t)\n\tdir1 := testutil.TempDirectory(t)\n\tdir2 := testutil.TempDirectory(t)\n\tdir3 := testutil.TempDirectory(t)\n\n\tenv.RunAndExpectSuccess(t, \"repo\", \"create\", \"filesystem\", \"--path\", env.RepoDir, \"--override-username=another-user\", \"--override-hostname=another-host\")\n\tenv.RunAndExpectSuccess(t, \"snap\", \"create\", dir0)\n\n\tenv.RunAndExpectSuccess(t, \"repo\", \"connect\", \"filesystem\", \"--path\", env.RepoDir, \"--override-username=test-user\", \"--override-hostname=test-host\")\n\tenv.RunAndExpectSuccess(t, \"snap\", \"create\", dir1)\n\tenv.RunAndExpectSuccess(t, \"snap\", \"create\", dir2)\n\n\tserverStarted := make(chan struct{})\n\tserverStopped := make(chan struct{})\n\n\tvar sp testutil.ServerParameters\n\n\tgo func() {\n\t\tkill := env.RunAndProcessStderr(t, sp.ProcessOutput,\n\t\t\t\"server\", \"start\", \"--insecure\", \"--random-server-control-password\", \"--address=127.0.0.1:0\")\n\n\t\tclose(serverStarted)\n\n\t\tdefer kill()\n\n\t\tclose(serverStopped)\n\t}()\n\n\tselect {\n\tcase <-serverStarted:\n\t\tt.Logf(\"server started on %v\", sp.BaseURL)\n\n\tcase <-time.After(5 * time.Second):\n\t\tt.Fatalf(\"server did not start in time\")\n\t}\n\n\tconst (\n\t\tpollFrequency = 100 * time.Millisecond\n\t\twaitTimeout   = 15 * time.Second\n\t)\n\n\trequire.Eventually(t, func() bool {\n\t\tlines := env.RunAndExpectSuccess(t, \"server\", \"status\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\t\tt.Logf(\"lines: %v\", lines)\n\t\treturn hasLine(lines, \"IDLE: test-user@test-host:\"+dir1) && hasLine(lines, \"IDLE: test-user@test-host:\"+dir2)\n\t}, waitTimeout, pollFrequency)\n\n\tlines := env.RunAndExpectSuccess(t, \"server\", \"status\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, \"--remote\")\n\trequire.Len(t, lines, 3)\n\trequire.Contains(t, lines, \"IDLE: test-user@test-host:\"+dir1)\n\trequire.Contains(t, lines, \"IDLE: test-user@test-host:\"+dir2)\n\trequire.Contains(t, lines, \"REMOTE: another-user@another-host:\"+dir0)\n\n\t\/\/ create snapshot outside of the server\n\tenv.RunAndExpectSuccess(t, \"snap\", \"create\", dir3)\n\tenv.RunAndExpectSuccess(t, \"server\", \"refresh\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\n\trequire.Eventually(t, func() bool {\n\t\tlines := env.RunAndExpectSuccess(t, \"server\", \"status\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, \"--remote\")\n\t\tt.Logf(\"lines: %v\", lines)\n\t\treturn hasLine(lines, \"IDLE: test-user@test-host:\"+dir3)\n\t}, waitTimeout, pollFrequency)\n\n\tenv.RunAndExpectSuccess(t, \"server\", \"flush\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\n\t\/\/ trigger server snapshot\n\tenv.RunAndExpectSuccess(t, \"server\", \"snapshot\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, \"--all\")\n\tenv.RunAndExpectSuccess(t, \"server\", \"snapshot\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, dir1)\n\tenv.RunAndExpectFailure(t, \"server\", \"snapshot\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, \"no-such-dir\")\n\n\t\/\/ neither dir nor --all specified\n\tenv.RunAndExpectFailure(t, \"server\", \"snapshot\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\n\t\/\/ cancel snapshot\n\tenv.RunAndExpectSuccess(t, \"server\", \"cancel\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, \"--all\")\n\n\tenv.RunAndExpectSuccess(t, \"server\", \"pause\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, dir1)\n\tenv.RunAndExpectSuccess(t, \"server\", \"resume\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword, dir1)\n\n\tenv.RunAndExpectSuccess(t, \"server\", \"shutdown\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\n\tselect {\n\tcase <-serverStopped:\n\t\tt.Logf(\"server shut down\")\n\n\tcase <-time.After(15 * time.Second):\n\t\tt.Fatalf(\"server did not shutdown in time\")\n\t}\n\n\t\/\/ this will fail since the server is down\n\tenv.RunAndExpectFailure(t, \"server\", \"status\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\tenv.RunAndExpectFailure(t, \"server\", \"flush\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\tenv.RunAndExpectFailure(t, \"server\", \"refresh\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n\tenv.RunAndExpectFailure(t, \"server\", \"shutdown\", \"--address\", sp.BaseURL, \"--server-control-password\", sp.ServerControlPassword)\n}\n\nfunc hasLine(lines []string, lookFor string) bool {\n\tfor _, l := range lines {\n\t\tif l == lookFor {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The LUCI Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage lib\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com\/bazelbuild\/remote-apis-sdks\/go\/pkg\/chunker\"\n\t\"github.com\/bazelbuild\/remote-apis-sdks\/go\/pkg\/command\"\n\t\"github.com\/bazelbuild\/remote-apis-sdks\/go\/pkg\/filemetadata\"\n\t\"github.com\/bazelbuild\/remote-apis-sdks\/go\/pkg\/tree\"\n\t\"github.com\/maruel\/subcommands\"\n\n\t\"go.chromium.org\/luci\/client\/archiver\"\n\t\"go.chromium.org\/luci\/client\/isolated\"\n\t\"go.chromium.org\/luci\/common\/data\/text\/units\"\n\t\"go.chromium.org\/luci\/common\/errors\"\n\tisol \"go.chromium.org\/luci\/common\/isolated\"\n\t\"go.chromium.org\/luci\/common\/system\/signals\"\n)\n\n\/\/ CmdArchive returns an object for the `archive` subcommand.\nfunc CmdArchive(options CommandOptions) *subcommands.Command {\n\treturn &subcommands.Command{\n\t\tUsageLine: \"archive <options>...\",\n\t\tShortDesc: \"creates a .isolated file and uploads the tree to an isolate server\",\n\t\tLongDesc: `Given a list of files and directories, creates a .isolated file and uploads the\ntree to to an isolate server.\n\nWhen specifying directories and files, you must also specify a current working\ndirectory for that file or directory. The current working directory will not\nbe included in the archived path. For example, to isolate '.\/usr\/foo\/bar' and\nhave it appear as 'foo\/bar' in the .isolated, specify '-files .\/usr:foo\/bar' or\n'-files usr:foo\/bar'. When the .isolated is then downloaded, it will then appear\nunder 'foo\/bar' in the desired directory.\n\nNote that '.' may be omitted in general, so to upload 'foo' from the current\nworking directory, '-files :foo' is sufficient.`,\n\t\tCommandRun: func() subcommands.CommandRun {\n\t\t\tc := archiveRun{\n\t\t\t\tCommandOptions: options,\n\t\t\t}\n\t\t\tc.commonFlags.Init(options.DefaultAuthOpts)\n\t\t\tc.Flags.Var(&c.dirs, \"dirs\", \"Directory(ies) to archive. Specify as <working directory>:<relative path to dir>\")\n\t\t\tc.Flags.Var(&c.files, \"files\", \"Individual file(s) to archive. Specify as <working directory>:<relative path to file>\")\n\t\t\tc.Flags.StringVar(&c.dumpHash, \"dump-hash\", \"\",\n\t\t\t\t\"Write the composite isolated hash to a file\")\n\t\t\tc.Flags.StringVar(&c.isolated, \"isolated\", \"\",\n\t\t\t\t\"Write the composite isolated to a file\")\n\t\t\tc.Flags.StringVar(&c.dumpStatsJSON, \"dump-stats-json\", \"\",\n\t\t\t\t\"Write the upload stats to this file as JSON\")\n\t\t\treturn &c\n\t\t},\n\t}\n}\n\ntype archiveRun struct {\n\tcommonFlags\n\tCommandOptions\n\tdirs          isolated.ScatterGather\n\tfiles         isolated.ScatterGather\n\tdumpHash      string\n\tisolated      string\n\tdumpStatsJSON string\n}\n\nfunc (c *archiveRun) Parse(a subcommands.Application, args []string) error {\n\tif err := c.commonFlags.Parse(); err != nil {\n\t\treturn err\n\t}\n\tif len(args) != 0 {\n\t\treturn errors.Reason(\"position arguments not expected\").Err()\n\t}\n\treturn nil\n}\n\n\/\/ getRoot returns root directory if there is only one working directory.\nfunc getRoot(dirs, files isolated.ScatterGather) (string, error) {\n\tvar rel0, wd0 string\n\tpickedOne := false\n\tfor rel, wd := range dirs {\n\t\tif !pickedOne {\n\t\t\trel0 = rel\n\t\t\twd0 = wd\n\t\t\tpickedOne = true\n\t\t\tcontinue\n\t\t}\n\n\t\tif wd0 != wd {\n\t\t\treturn \"\", errors.Reason(\"different root (working) directory is not supported: %s:%s vs %s:%s\", wd0, rel0, wd, rel).Err()\n\t\t}\n\t}\n\n\tfor rel, wd := range files {\n\t\tif !pickedOne {\n\t\t\trel0 = rel\n\t\t\twd0 = wd\n\t\t\tpickedOne = true\n\t\t\tcontinue\n\t\t}\n\n\t\tif wd0 != wd {\n\t\t\treturn \"\", errors.Reason(\"different root (working) directory is not supported: %s:%s vs %s:%s\", wd0, rel0, wd, rel).Err()\n\t\t}\n\t}\n\n\tif !pickedOne {\n\t\treturn \"\", errors.Reason(\"-dirs or -files should be specified at least once\").Err()\n\t}\n\n\treturn wd0, nil\n}\n\nfunc (c *archiveRun) doCASAarchive(ctx context.Context) error {\n\troot, err := getRoot(c.dirs, c.files)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tis := command.InputSpec{}\n\tfor dir := range c.dirs {\n\t\tis.Inputs = append(is.Inputs, dir)\n\t}\n\tfor file := range c.files {\n\t\tis.Inputs = append(is.Inputs, file)\n\t}\n\n\trootDg, chunkers, _, err := tree.ComputeMerkleTree(root, &is, chunker.DefaultChunkSize, filemetadata.NewNoopCache())\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"failed to call ComputeMerkleTree\").Err()\n\t}\n\n\tclient, err := c.casFlags.NewClient(ctx)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"failed to create cas client\").Err()\n\t}\n\tdefer client.Close()\n\n\tif err := client.UploadIfMissing(ctx, chunkers...); err != nil {\n\t\treturn errors.Annotate(err, \"failed to call UploadIfMissing\").Err()\n\t}\n\n\tif c.dumpHash != \"\" {\n\t\tif err := ioutil.WriteFile(c.dumpHash, []byte(rootDg.String()), 0644); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *archiveRun) doIsolatedArchive(ctx context.Context) (stats *archiver.Stats, err error) {\n\tisolatedClient, isolErr := c.createIsolatedClient(ctx, c.CommandOptions)\n\tif isolErr != nil {\n\t\terr = errors.Annotate(isolErr, \"failed to create isolated client\").Err()\n\t\treturn\n\t}\n\tout := os.Stdout\n\tarch := archiver.New(ctx, isolatedClient, out)\n\tdefer func() {\n\t\t\/\/ This waits for all uploads.\n\t\tif cerr := arch.Close(); err == nil {\n\t\t\terr = cerr\n\t\t}\n\t\t\/\/ We must take the stats until after all the uploads have finished\n\t\tif err == nil {\n\t\t\tstats = arch.Stats()\n\t\t}\n\t}()\n\n\topts := isolated.ArchiveOptions{\n\t\tFiles:    c.files,\n\t\tDirs:     c.dirs,\n\t\tIsolated: c.isolated,\n\t}\n\tif len(c.isolated) != 0 {\n\t\tvar dumpIsolated *os.File\n\t\tdumpIsolated, err = os.Create(c.isolated)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t\/\/ This is OK to close before arch because isolated.Archive\n\t\t\/\/ does the writing (it's not handed off elsewhere).\n\t\tdefer dumpIsolated.Close()\n\t\topts.LeakIsolated = dumpIsolated\n\t}\n\titem := isolated.Archive(ctx, arch, &opts)\n\tif err = item.Error(); err != nil {\n\t\treturn\n\t}\n\n\titem.WaitForHashed()\n\tif len(c.dumpHash) != 0 {\n\t\tif err = ioutil.WriteFile(c.dumpHash, []byte(item.Digest()), 0644); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ Does the archive by uploading to isolate-server, then return the archive stats and error.\nfunc (c *archiveRun) doArchive(a subcommands.Application, args []string) (stats *archiver.Stats, err error) {\n\tctx, cancel := context.WithCancel(c.defaultFlags.MakeLoggingContext(os.Stderr))\n\tsignals.HandleInterrupt(cancel)\n\n\tif c.casFlags.Instance != \"\" {\n\t\t\/\/ TODO(crbug.com\/1110569): get stats\n\t\treturn &archiver.Stats{}, c.doCASAarchive(ctx)\n\t}\n\n\treturn c.doIsolatedArchive(ctx)\n}\n\nfunc (c *archiveRun) postprocessStats(stats *archiver.Stats, start time.Time) error {\n\tif !c.defaultFlags.Quiet {\n\t\tduration := time.Since(start)\n\t\tfmt.Fprintf(os.Stderr, \"Hits    : %5d (%s)\\n\", stats.TotalHits(), stats.TotalBytesHits())\n\t\tfmt.Fprintf(os.Stderr, \"Misses  : %5d (%s)\\n\", stats.TotalMisses(), stats.TotalBytesPushed())\n\t\tfmt.Fprintf(os.Stderr, \"Duration: %s\\n\", units.Round(duration, time.Millisecond))\n\t}\n\tif c.dumpStatsJSON != \"\" {\n\t\treturn dumpStatsJSON(c.dumpStatsJSON, stats)\n\t}\n\treturn nil\n}\n\nfunc (c *archiveRun) Run(a subcommands.Application, args []string, _ subcommands.Env) int {\n\tif err := c.Parse(a, args); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tcl, err := c.defaultFlags.StartTracing()\n\tif err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tdefer cl.Close()\n\tdefer c.profilerFlags.Stop()\n\tstart := time.Now()\n\tstats, err := c.doArchive(a, args)\n\tif err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tif err := c.postprocessStats(stats, start); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\treturn 0\n}\n\nfunc dumpStatsJSON(jsonPath string, stats *archiver.Stats) error {\n\thits := make([]int64, len(stats.Hits))\n\tfor i, h := range stats.Hits {\n\t\thits[i] = int64(h)\n\t}\n\tsort.Slice(hits, func(i, j int) bool { return hits[i] < hits[j] })\n\titemsHot, err := isol.Pack(hits)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"failed to pack itemsHot\").Err()\n\t}\n\n\tpushed := make([]int64, len(stats.Pushed))\n\tfor i, p := range stats.Pushed {\n\t\tpushed[i] = int64(p.Size)\n\t}\n\tsort.Slice(pushed, func(i, j int) bool { return pushed[i] < pushed[j] })\n\titemsCold, err := isol.Pack(pushed)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"failed to pack itemsCold\").Err()\n\t}\n\n\tstatsJSON, err := json.Marshal(struct {\n\t\tItemsCold []byte `json:\"items_cold\"`\n\t\tItemsHot  []byte `json:\"items_hot\"`\n\t}{\n\t\tItemsCold: itemsCold,\n\t\tItemsHot:  itemsHot,\n\t})\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"failed to marshal result json\").Err()\n\t}\n\tif err := ioutil.WriteFile(jsonPath, statsJSON, 0664); err != nil {\n\t\treturn errors.Annotate(err, \"failed to write stats json to %s\", jsonPath).Err()\n\t}\n\treturn nil\n}\n<commit_msg>[isolated] Silence output when -quiet is true<commit_after>\/\/ Copyright 2015 The LUCI Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage lib\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com\/bazelbuild\/remote-apis-sdks\/go\/pkg\/chunker\"\n\t\"github.com\/bazelbuild\/remote-apis-sdks\/go\/pkg\/command\"\n\t\"github.com\/bazelbuild\/remote-apis-sdks\/go\/pkg\/filemetadata\"\n\t\"github.com\/bazelbuild\/remote-apis-sdks\/go\/pkg\/tree\"\n\t\"github.com\/maruel\/subcommands\"\n\n\t\"go.chromium.org\/luci\/client\/archiver\"\n\t\"go.chromium.org\/luci\/client\/isolated\"\n\t\"go.chromium.org\/luci\/common\/data\/text\/units\"\n\t\"go.chromium.org\/luci\/common\/errors\"\n\tisol \"go.chromium.org\/luci\/common\/isolated\"\n\t\"go.chromium.org\/luci\/common\/system\/signals\"\n)\n\n\/\/ CmdArchive returns an object for the `archive` subcommand.\nfunc CmdArchive(options CommandOptions) *subcommands.Command {\n\treturn &subcommands.Command{\n\t\tUsageLine: \"archive <options>...\",\n\t\tShortDesc: \"creates a .isolated file and uploads the tree to an isolate server\",\n\t\tLongDesc: `Given a list of files and directories, creates a .isolated file and uploads the\ntree to to an isolate server.\n\nWhen specifying directories and files, you must also specify a current working\ndirectory for that file or directory. The current working directory will not\nbe included in the archived path. For example, to isolate '.\/usr\/foo\/bar' and\nhave it appear as 'foo\/bar' in the .isolated, specify '-files .\/usr:foo\/bar' or\n'-files usr:foo\/bar'. When the .isolated is then downloaded, it will then appear\nunder 'foo\/bar' in the desired directory.\n\nNote that '.' may be omitted in general, so to upload 'foo' from the current\nworking directory, '-files :foo' is sufficient.`,\n\t\tCommandRun: func() subcommands.CommandRun {\n\t\t\tc := archiveRun{\n\t\t\t\tCommandOptions: options,\n\t\t\t}\n\t\t\tc.commonFlags.Init(options.DefaultAuthOpts)\n\t\t\tc.Flags.Var(&c.dirs, \"dirs\", \"Directory(ies) to archive. Specify as <working directory>:<relative path to dir>\")\n\t\t\tc.Flags.Var(&c.files, \"files\", \"Individual file(s) to archive. Specify as <working directory>:<relative path to file>\")\n\t\t\tc.Flags.StringVar(&c.dumpHash, \"dump-hash\", \"\",\n\t\t\t\t\"Write the composite isolated hash to a file\")\n\t\t\tc.Flags.StringVar(&c.isolated, \"isolated\", \"\",\n\t\t\t\t\"Write the composite isolated to a file\")\n\t\t\tc.Flags.StringVar(&c.dumpStatsJSON, \"dump-stats-json\", \"\",\n\t\t\t\t\"Write the upload stats to this file as JSON\")\n\t\t\treturn &c\n\t\t},\n\t}\n}\n\ntype archiveRun struct {\n\tcommonFlags\n\tCommandOptions\n\tdirs          isolated.ScatterGather\n\tfiles         isolated.ScatterGather\n\tdumpHash      string\n\tisolated      string\n\tdumpStatsJSON string\n}\n\nfunc (c *archiveRun) Parse(a subcommands.Application, args []string) error {\n\tif err := c.commonFlags.Parse(); err != nil {\n\t\treturn err\n\t}\n\tif len(args) != 0 {\n\t\treturn errors.Reason(\"position arguments not expected\").Err()\n\t}\n\treturn nil\n}\n\n\/\/ getRoot returns root directory if there is only one working directory.\nfunc getRoot(dirs, files isolated.ScatterGather) (string, error) {\n\tvar rel0, wd0 string\n\tpickedOne := false\n\tfor rel, wd := range dirs {\n\t\tif !pickedOne {\n\t\t\trel0 = rel\n\t\t\twd0 = wd\n\t\t\tpickedOne = true\n\t\t\tcontinue\n\t\t}\n\n\t\tif wd0 != wd {\n\t\t\treturn \"\", errors.Reason(\"different root (working) directory is not supported: %s:%s vs %s:%s\", wd0, rel0, wd, rel).Err()\n\t\t}\n\t}\n\n\tfor rel, wd := range files {\n\t\tif !pickedOne {\n\t\t\trel0 = rel\n\t\t\twd0 = wd\n\t\t\tpickedOne = true\n\t\t\tcontinue\n\t\t}\n\n\t\tif wd0 != wd {\n\t\t\treturn \"\", errors.Reason(\"different root (working) directory is not supported: %s:%s vs %s:%s\", wd0, rel0, wd, rel).Err()\n\t\t}\n\t}\n\n\tif !pickedOne {\n\t\treturn \"\", errors.Reason(\"-dirs or -files should be specified at least once\").Err()\n\t}\n\n\treturn wd0, nil\n}\n\nfunc (c *archiveRun) doCASAarchive(ctx context.Context) error {\n\troot, err := getRoot(c.dirs, c.files)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tis := command.InputSpec{}\n\tfor dir := range c.dirs {\n\t\tis.Inputs = append(is.Inputs, dir)\n\t}\n\tfor file := range c.files {\n\t\tis.Inputs = append(is.Inputs, file)\n\t}\n\n\trootDg, chunkers, _, err := tree.ComputeMerkleTree(root, &is, chunker.DefaultChunkSize, filemetadata.NewNoopCache())\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"failed to call ComputeMerkleTree\").Err()\n\t}\n\n\tclient, err := c.casFlags.NewClient(ctx)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"failed to create cas client\").Err()\n\t}\n\tdefer client.Close()\n\n\tif err := client.UploadIfMissing(ctx, chunkers...); err != nil {\n\t\treturn errors.Annotate(err, \"failed to call UploadIfMissing\").Err()\n\t}\n\n\tif c.dumpHash != \"\" {\n\t\tif err := ioutil.WriteFile(c.dumpHash, []byte(rootDg.String()), 0644); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *archiveRun) doIsolatedArchive(ctx context.Context) (stats *archiver.Stats, err error) {\n\tisolatedClient, isolErr := c.createIsolatedClient(ctx, c.CommandOptions)\n\tif isolErr != nil {\n\t\terr = errors.Annotate(isolErr, \"failed to create isolated client\").Err()\n\t\treturn\n\t}\n\tvar out io.Writer = os.Stdout\n\tif c.defaultFlags.Quiet {\n\t\tout = ioutil.Discard\n\t}\n\tarch := archiver.New(ctx, isolatedClient, out)\n\tdefer func() {\n\t\t\/\/ This waits for all uploads.\n\t\tif cerr := arch.Close(); err == nil {\n\t\t\terr = cerr\n\t\t}\n\t\t\/\/ We must take the stats until after all the uploads have finished\n\t\tif err == nil {\n\t\t\tstats = arch.Stats()\n\t\t}\n\t}()\n\n\topts := isolated.ArchiveOptions{\n\t\tFiles:    c.files,\n\t\tDirs:     c.dirs,\n\t\tIsolated: c.isolated,\n\t}\n\tif len(c.isolated) != 0 {\n\t\tvar dumpIsolated *os.File\n\t\tdumpIsolated, err = os.Create(c.isolated)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t\/\/ This is OK to close before arch because isolated.Archive\n\t\t\/\/ does the writing (it's not handed off elsewhere).\n\t\tdefer dumpIsolated.Close()\n\t\topts.LeakIsolated = dumpIsolated\n\t}\n\titem := isolated.Archive(ctx, arch, &opts)\n\tif err = item.Error(); err != nil {\n\t\treturn\n\t}\n\n\titem.WaitForHashed()\n\tif len(c.dumpHash) != 0 {\n\t\tif err = ioutil.WriteFile(c.dumpHash, []byte(item.Digest()), 0644); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ Does the archive by uploading to isolate-server, then return the archive stats and error.\nfunc (c *archiveRun) doArchive(a subcommands.Application, args []string) (stats *archiver.Stats, err error) {\n\tctx, cancel := context.WithCancel(c.defaultFlags.MakeLoggingContext(os.Stderr))\n\tsignals.HandleInterrupt(cancel)\n\n\tif c.casFlags.Instance != \"\" {\n\t\t\/\/ TODO(crbug.com\/1110569): get stats\n\t\treturn &archiver.Stats{}, c.doCASAarchive(ctx)\n\t}\n\n\treturn c.doIsolatedArchive(ctx)\n}\n\nfunc (c *archiveRun) postprocessStats(stats *archiver.Stats, start time.Time) error {\n\tif !c.defaultFlags.Quiet {\n\t\tduration := time.Since(start)\n\t\tfmt.Fprintf(os.Stderr, \"Hits    : %5d (%s)\\n\", stats.TotalHits(), stats.TotalBytesHits())\n\t\tfmt.Fprintf(os.Stderr, \"Misses  : %5d (%s)\\n\", stats.TotalMisses(), stats.TotalBytesPushed())\n\t\tfmt.Fprintf(os.Stderr, \"Duration: %s\\n\", units.Round(duration, time.Millisecond))\n\t}\n\tif c.dumpStatsJSON != \"\" {\n\t\treturn dumpStatsJSON(c.dumpStatsJSON, stats)\n\t}\n\treturn nil\n}\n\nfunc (c *archiveRun) Run(a subcommands.Application, args []string, _ subcommands.Env) int {\n\tif err := c.Parse(a, args); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tcl, err := c.defaultFlags.StartTracing()\n\tif err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tdefer cl.Close()\n\tdefer c.profilerFlags.Stop()\n\tstart := time.Now()\n\tstats, err := c.doArchive(a, args)\n\tif err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tif err := c.postprocessStats(stats, start); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\treturn 0\n}\n\nfunc dumpStatsJSON(jsonPath string, stats *archiver.Stats) error {\n\thits := make([]int64, len(stats.Hits))\n\tfor i, h := range stats.Hits {\n\t\thits[i] = int64(h)\n\t}\n\tsort.Slice(hits, func(i, j int) bool { return hits[i] < hits[j] })\n\titemsHot, err := isol.Pack(hits)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"failed to pack itemsHot\").Err()\n\t}\n\n\tpushed := make([]int64, len(stats.Pushed))\n\tfor i, p := range stats.Pushed {\n\t\tpushed[i] = int64(p.Size)\n\t}\n\tsort.Slice(pushed, func(i, j int) bool { return pushed[i] < pushed[j] })\n\titemsCold, err := isol.Pack(pushed)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"failed to pack itemsCold\").Err()\n\t}\n\n\tstatsJSON, err := json.Marshal(struct {\n\t\tItemsCold []byte `json:\"items_cold\"`\n\t\tItemsHot  []byte `json:\"items_hot\"`\n\t}{\n\t\tItemsCold: itemsCold,\n\t\tItemsHot:  itemsHot,\n\t})\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"failed to marshal result json\").Err()\n\t}\n\tif err := ioutil.WriteFile(jsonPath, statsJSON, 0664); err != nil {\n\t\treturn errors.Annotate(err, \"failed to write stats json to %s\", jsonPath).Err()\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\tcloudTypes \"github.com\/atlassian\/gostatsd\/cloudprovider\/types\"\n\t\"github.com\/atlassian\/gostatsd\/types\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/credentials\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/credentials\/ec2rolecreds\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/ec2metadata\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ec2\"\n\t\"github.com\/spf13\/viper\"\n)\n\nconst (\n\t\/\/ ProviderName is the name of AWS cloud provider.\n\tProviderName = \"aws\"\n)\n\nconst sampleConfig = `\n[aws]\n\t# maximum number of retries in case of retriable errors\n\tmax_retries = 5 # optional, default to 3\n`\n\n\/\/ Provider represents an AWS provider.\ntype Provider struct {\n\tMetadata *ec2metadata.EC2Metadata\n\tEc2      *ec2.EC2\n}\n\n\/\/ DescribeInstances is an implementation of EC2.Instances.\nfunc (p *Provider) describeInstances(ctx context.Context, request *ec2.DescribeInstancesInput) ([]*ec2.Instance, error) {\n\t\/\/ Instances are paged\n\tresults := []*ec2.Instance{}\n\n\tfor {\n\t\treq, response := p.Ec2.DescribeInstancesRequest(request)\n\t\treq.HTTPRequest = req.HTTPRequest.WithContext(ctx)\n\t\terr := req.Send()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error listing AWS instances: %v\", err)\n\t\t}\n\n\t\tfor _, reservation := range response.Reservations {\n\t\t\tresults = append(results, reservation.Instances...)\n\t\t}\n\n\t\tif response.NextToken == nil {\n\t\t\tbreak\n\t\t}\n\t\trequest.NextToken = response.NextToken\n\t}\n\n\treturn results, nil\n}\n\nfunc newEc2Filter(name string, value string) *ec2.Filter {\n\treturn &ec2.Filter{\n\t\tName: aws.String(name),\n\t\tValues: []*string{\n\t\t\taws.String(value),\n\t\t},\n\t}\n}\n\n\/\/ Instance returns the instance details from aws.\nfunc (p *Provider) Instance(ctx context.Context, IP types.IP) (*cloudTypes.Instance, error) {\n\tfilters := []*ec2.Filter{newEc2Filter(\"private-ip-address\", string(IP))}\n\trequest := &ec2.DescribeInstancesInput{\n\t\tFilters: filters,\n\t}\n\n\tinstances, err := p.describeInstances(ctx, request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(instances) == 0 {\n\t\treturn nil, errors.New(\"no instances returned\")\n\t}\n\n\ti := instances[0]\n\tregion, err := azToRegion(aws.StringValue(i.Placement.AvailabilityZone))\n\tif err != nil {\n\t\tlog.Errorf(\"Error getting instance region: %v\", err)\n\t}\n\ttags := make(types.Tags, len(i.Tags))\n\tfor idx, tag := range i.Tags {\n\t\ttags[idx] = fmt.Sprintf(\"%s:%s\",\n\t\t\ttypes.NormalizeTagKey(aws.StringValue(tag.Key)),\n\t\t\taws.StringValue(tag.Value))\n\t}\n\tinstance := &cloudTypes.Instance{\n\t\tID:     aws.StringValue(i.InstanceId),\n\t\tRegion: region,\n\t\tTags:   tags,\n\t}\n\treturn instance, nil\n}\n\n\/\/ ProviderName returns the name of the provider.\nfunc (p *Provider) ProviderName() string {\n\treturn ProviderName\n}\n\n\/\/ SampleConfig returns the sample config for the datadog backend.\nfunc (p *Provider) SampleConfig() string {\n\treturn sampleConfig\n}\n\n\/\/ SelfIP returns host's IPv4 address.\nfunc (p *Provider) SelfIP() (types.IP, error) {\n\tip, err := p.Metadata.GetMetadata(\"local-ipv4\")\n\treturn types.IP(ip), err\n}\n\n\/\/ Derives the region from a valid az name.\n\/\/ Returns an error if the az is known invalid (empty).\nfunc azToRegion(az string) (string, error) {\n\tif az == \"\" {\n\t\treturn \"\", errors.New(\"invalid (empty) AZ\")\n\t}\n\tregion := az[:len(az)-1]\n\treturn region, nil\n}\n\n\/\/ NewProviderFromViper returns a new aws provider.\nfunc NewProviderFromViper(v *viper.Viper) (cloudTypes.Interface, error) {\n\ta := getSubViper(v, \"aws\")\n\ta.SetDefault(\"max_retries\", 3)\n\ta.SetDefault(\"http_timeout\", 3*time.Second)\n\thttpTimeout := a.GetDuration(\"http_timeout\")\n\tif httpTimeout <= 0 {\n\t\treturn nil, errors.New(\"http client timeout must be positive\")\n\t}\n\n\t\/\/ This is the main config without credentials.\n\tconfig := &aws.Config{\n\t\tMaxRetries: aws.Int(a.GetInt(\"max_retries\")),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: httpTimeout,\n\t\t},\n\t}\n\tmetadata := ec2metadata.New(session.New(config))\n\taz, err := metadata.GetMetadata(\"placement\/availability-zone\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting availability zone: %v\", err)\n\t}\n\tregion, err := azToRegion(az)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting aws region: %v\", err)\n\t}\n\treturn &Provider{\n\t\tMetadata: metadata,\n\t\tEc2: ec2.New(session.New(config.Copy(&aws.Config{\n\t\t\tCredentials: credentials.NewChainCredentials(\n\t\t\t\t[]credentials.Provider{\n\t\t\t\t\t&credentials.EnvProvider{},\n\t\t\t\t\t&ec2rolecreds.EC2RoleProvider{\n\t\t\t\t\t\tClient: metadata,\n\t\t\t\t\t},\n\t\t\t\t\t&credentials.SharedCredentialsProvider{},\n\t\t\t\t}),\n\t\t\tRegion: aws.String(region),\n\t\t}))),\n\t}, nil\n}\n\nfunc getSubViper(v *viper.Viper, key string) *viper.Viper {\n\tn := v.Sub(key)\n\tif n == nil {\n\t\tn = viper.New()\n\t}\n\treturn n\n}\n<commit_msg>Use built-in pagination<commit_after>package aws\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\tcloudTypes \"github.com\/atlassian\/gostatsd\/cloudprovider\/types\"\n\t\"github.com\/atlassian\/gostatsd\/types\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/credentials\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/credentials\/ec2rolecreds\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/ec2metadata\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ec2\"\n\t\"github.com\/spf13\/viper\"\n)\n\nconst (\n\t\/\/ ProviderName is the name of AWS cloud provider.\n\tProviderName = \"aws\"\n)\n\nconst sampleConfig = `\n[aws]\n\t# maximum number of retries in case of retriable errors\n\tmax_retries = 5 # optional, default to 3\n`\n\n\/\/ Provider represents an AWS provider.\ntype Provider struct {\n\tMetadata *ec2metadata.EC2Metadata\n\tEc2      *ec2.EC2\n}\n\nfunc newEc2Filter(name string, value string) *ec2.Filter {\n\treturn &ec2.Filter{\n\t\tName: aws.String(name),\n\t\tValues: []*string{\n\t\t\taws.String(value),\n\t\t},\n\t}\n}\n\n\/\/ Instance returns the instance details from aws.\nfunc (p *Provider) Instance(ctx context.Context, IP types.IP) (*cloudTypes.Instance, error) {\n\treq, _ := p.Ec2.DescribeInstancesRequest(&ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\tnewEc2Filter(\"private-ip-address\", string(IP)),\n\t\t},\n\t})\n\treq.HTTPRequest = req.HTTPRequest.WithContext(ctx)\n\tvar inst *ec2.Instance\n\terr := req.EachPage(func(data interface{}, isLastPage bool) bool {\n\t\tfor _, reservation := range data.(*ec2.DescribeInstancesOutput).Reservations {\n\t\t\tfor _, instance := range reservation.Instances {\n\t\t\t\tinst = instance\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error listing AWS instances: %v\", err)\n\t}\n\tif inst == nil {\n\t\treturn nil, errors.New(\"no instances found\")\n\t}\n\tregion, err := azToRegion(aws.StringValue(inst.Placement.AvailabilityZone))\n\tif err != nil {\n\t\tlog.Errorf(\"Error getting instance region: %v\", err)\n\t}\n\ttags := make(types.Tags, len(inst.Tags))\n\tfor idx, tag := range inst.Tags {\n\t\ttags[idx] = fmt.Sprintf(\"%s:%s\",\n\t\t\ttypes.NormalizeTagKey(aws.StringValue(tag.Key)),\n\t\t\taws.StringValue(tag.Value))\n\t}\n\tinstance := &cloudTypes.Instance{\n\t\tID:     aws.StringValue(inst.InstanceId),\n\t\tRegion: region,\n\t\tTags:   tags,\n\t}\n\treturn instance, nil\n}\n\n\/\/ ProviderName returns the name of the provider.\nfunc (p *Provider) ProviderName() string {\n\treturn ProviderName\n}\n\n\/\/ SampleConfig returns the sample config for the datadog backend.\nfunc (p *Provider) SampleConfig() string {\n\treturn sampleConfig\n}\n\n\/\/ SelfIP returns host's IPv4 address.\nfunc (p *Provider) SelfIP() (types.IP, error) {\n\tip, err := p.Metadata.GetMetadata(\"local-ipv4\")\n\treturn types.IP(ip), err\n}\n\n\/\/ Derives the region from a valid az name.\n\/\/ Returns an error if the az is known invalid (empty).\nfunc azToRegion(az string) (string, error) {\n\tif az == \"\" {\n\t\treturn \"\", errors.New(\"invalid (empty) AZ\")\n\t}\n\tregion := az[:len(az)-1]\n\treturn region, nil\n}\n\n\/\/ NewProviderFromViper returns a new aws provider.\nfunc NewProviderFromViper(v *viper.Viper) (cloudTypes.Interface, error) {\n\ta := getSubViper(v, \"aws\")\n\ta.SetDefault(\"max_retries\", 3)\n\ta.SetDefault(\"http_timeout\", 3*time.Second)\n\thttpTimeout := a.GetDuration(\"http_timeout\")\n\tif httpTimeout <= 0 {\n\t\treturn nil, errors.New(\"http client timeout must be positive\")\n\t}\n\n\t\/\/ This is the main config without credentials.\n\tconfig := &aws.Config{\n\t\tMaxRetries: aws.Int(a.GetInt(\"max_retries\")),\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: httpTimeout,\n\t\t},\n\t}\n\tmetadata := ec2metadata.New(session.New(config))\n\taz, err := metadata.GetMetadata(\"placement\/availability-zone\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting availability zone: %v\", err)\n\t}\n\tregion, err := azToRegion(az)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting aws region: %v\", err)\n\t}\n\treturn &Provider{\n\t\tMetadata: metadata,\n\t\tEc2: ec2.New(session.New(config.Copy(&aws.Config{\n\t\t\tCredentials: credentials.NewChainCredentials(\n\t\t\t\t[]credentials.Provider{\n\t\t\t\t\t&credentials.EnvProvider{},\n\t\t\t\t\t&ec2rolecreds.EC2RoleProvider{\n\t\t\t\t\t\tClient: metadata,\n\t\t\t\t\t},\n\t\t\t\t\t&credentials.SharedCredentialsProvider{},\n\t\t\t\t}),\n\t\t\tRegion: aws.String(region),\n\t\t}))),\n\t}, nil\n}\n\nfunc getSubViper(v *viper.Viper, key string) *viper.Viper {\n\tn := v.Sub(key)\n\tif n == nil {\n\t\tn = viper.New()\n\t}\n\treturn n\n}\n<|endoftext|>"}
{"text":"<commit_before>package rabbus\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\t\"time\"\n\n\tamqpwrap \"github.com\/rafaeljesus\/rabbus\/internal\/amqp\"\n\t\"github.com\/rafaeljesus\/retry-go\"\n\t\"github.com\/sony\/gobreaker\"\n\t\"github.com\/streadway\/amqp\"\n)\n\nconst (\n\t\/\/ Transient means higher throughput but messages will not be restored on broker restart.\n\tTransient uint8 = 1\n\t\/\/ Persistent messages will be restored to durable queues and lost on non-durable queues during server restart.\n\tPersistent uint8 = 2\n\t\/\/ ContentTypeJSON define json content type\n\tContentTypeJSON = \"application\/json\"\n\t\/\/ ContentTypePlain define plain text content type\n\tContentTypePlain = \"plain\/text\"\n\n\tcontentEncoding = \"UTF-8\"\n)\n\ntype (\n\t\/\/ Option represents an option you can pass to New.\n\t\/\/ See the documentation for the individual options.\n\tOption func(*Rabbus) error\n\t\/\/ OnStateChangeFunc is the callback function when circuit breaker state changes.\n\tOnStateChangeFunc func(name, from, to string)\n\n\t\/\/ Message carries fields for sending messages.\n\tMessage struct {\n\t\t\/\/ Exchange the exchange name.\n\t\tExchange string\n\t\t\/\/ Kind the exchange type.\n\t\tKind string\n\t\t\/\/ Key the routing key name.\n\t\tKey string\n\t\t\/\/ Payload the message payload.\n\t\tPayload []byte\n\t\t\/\/ DeliveryMode indicates if the is Persistent or Transient.\n\t\tDeliveryMode uint8\n\t\t\/\/ ContentType the message content-type.\n\t\tContentType string\n\t\t\/\/ Headers the message application headers\n\t\tHeaders map[string]interface{}\n\t}\n\n\t\/\/ ListenConfig carries fields for listening messages.\n\tListenConfig struct {\n\t\t\/\/ Exchange the exchange name.\n\t\tExchange string\n\t\t\/\/ Kind the exchange type.\n\t\tKind string\n\t\t\/\/ Key the routing key name.\n\t\tKey string\n\t\t\/\/ PassiveExchange determines a passive exchange connection it uses\n\t\t\/\/ amqp's ExchangeDeclarePassive instead the default ExchangeDeclare\n\t\tPassiveExchange bool\n\t\t\/\/ Queue the queue name\n\t\tQueue string\n\t}\n\n\t\/\/ Delivery wraps amqp.Delivery struct\n\tDelivery struct {\n\t\tamqp.Delivery\n\t}\n\n\t\/\/ Rabbus interpret (implement) Rabbus interface definition\n\tRabbus struct {\n\t\tAmqp\n\t\tmu         sync.RWMutex\n\t\tbreaker    *gobreaker.CircuitBreaker\n\t\temit       chan Message\n\t\temitErr    chan error\n\t\temitOk     chan struct{}\n\t\treconn     chan struct{}\n\t\texDeclared map[string]struct{}\n\t\tconfig\n\t\tconDeclared int \/\/ conDeclared is a counter for the declared consumers\n\t}\n\n\t\/\/ Amqp expose a interface for interacting with amqp broker\n\tAmqp interface {\n\t\t\/\/ Publish wraps amqp.Publish method\n\t\tPublish(exchange, key string, opts amqp.Publishing) error\n\t\t\/\/ CreateConsumer creates a amqp consumer\n\t\tCreateConsumer(exchange, key, kind, queue string, durable bool) (<-chan amqp.Delivery, error)\n\t\t\/\/ WithExchange creates a amqp exchange\n\t\tWithExchange(exchange, kind string, durable bool) error\n\t\t\/\/ WithQos wrapper over amqp.Qos method\n\t\tWithQos(count, size int, global bool) error\n\t\t\/\/ NotifyClose wrapper over notifyClose method\n\t\tNotifyClose(c chan *amqp.Error) chan *amqp.Error\n\t\t\/\/ Close closes the running amqp connection and channel\n\t\tClose() error\n\t}\n\n\tconfig struct {\n\t\tdsn                string\n\t\tdurable, passiveex bool\n\t\tretrycfg\n\t\tbreaker\n\t\tqos\n\t}\n\n\tretrycfg struct {\n\t\tattempts              int\n\t\tsleep, reconnectSleep time.Duration\n\t}\n\n\tbreaker struct {\n\t\tinterval, timeout time.Duration\n\t\tthreshold         uint32\n\t\tonStateChange     OnStateChangeFunc\n\t}\n\n\tqos struct {\n\t\tprefetchCount, prefetchSize int\n\t\tglobal                      bool\n\t}\n)\n\nfunc (lc ListenConfig) validate() error {\n\tif lc.Exchange == \"\" {\n\t\treturn ErrMissingExchange\n\t}\n\n\tif lc.Kind == \"\" {\n\t\treturn ErrMissingKind\n\t}\n\n\tif lc.Queue == \"\" {\n\t\treturn ErrMissingQueue\n\t}\n\n\treturn nil\n}\n\n\/\/ New returns a new Rabbus configured with the\n\/\/ variables from the config parameter, or returning an non-nil err\n\/\/ if an error occurred while creating connection and channel.\nfunc New(dsn string, options ...Option) (*Rabbus, error) {\n\tr := &Rabbus{\n\t\temit:       make(chan Message),\n\t\temitErr:    make(chan error),\n\t\temitOk:     make(chan struct{}),\n\t\treconn:     make(chan struct{}, 10),\n\t\texDeclared: make(map[string]struct{}),\n\t}\n\n\tfor _, o := range options {\n\t\tif err := o(r); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif r.Amqp == nil {\n\t\tamqpWrapper, err := amqpwrap.New(dsn, r.config.passiveex)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr.Amqp = amqpWrapper\n\t}\n\n\tif err := r.WithQos(\n\t\tr.config.qos.prefetchCount,\n\t\tr.config.qos.prefetchSize,\n\t\tr.config.qos.global,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.config.dsn = dsn\n\tr.breaker = gobreaker.NewCircuitBreaker(newBreakerSettings(r.config))\n\n\treturn r, nil\n}\n\n\/\/ Run starts rabbus channels for emitting and listening for amqp connection close\n\/\/ returns ctx error in case of any.\nfunc (r *Rabbus) Run(ctx context.Context) error {\n\tfor {\n\t\tselect {\n\t\tcase m, ok := <-r.emit:\n\t\t\tif ok {\n\t\t\t\tr.produce(m)\n\t\t\t}\n\t\tcase err, ok := <-r.NotifyClose(make(chan *amqp.Error)):\n\t\t\tif ok {\n\t\t\t\tr.handleAmqpClose(err)\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\t}\n\t}\n}\n\n\/\/ EmitAsync emits a message to RabbitMQ, but does not wait for the response from broker.\nfunc (r *Rabbus) EmitAsync() chan<- Message { return r.emit }\n\n\/\/ EmitErr returns an error if encoding payload fails, or if after circuit breaker is open or retries attempts exceed.\nfunc (r *Rabbus) EmitErr() <-chan error { return r.emitErr }\n\n\/\/ EmitOk returns true when the message was sent.\nfunc (r *Rabbus) EmitOk() <-chan struct{} { return r.emitOk }\n\n\/\/ Listen to a message from RabbitMQ, returns\n\/\/ an error if exchange, queue name and function handler not passed or if an error occurred while creating\n\/\/ amqp consumer.\nfunc (r *Rabbus) Listen(c ListenConfig) (chan ConsumerMessage, error) {\n\tif err := c.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmsgs, err := r.CreateConsumer(c.Exchange, c.Key, c.Kind, c.Queue, r.config.durable)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.conDeclared++ \/\/ increase the declared consumer's counter\n\tr.mu.Lock()\n\tr.exDeclared[c.Exchange] = struct{}{}\n\tr.mu.Unlock()\n\n\tmessages := make(chan ConsumerMessage, 256)\n\tgo r.wrapMessage(c, msgs, messages)\n\tgo r.listenReconn(c, messages)\n\n\treturn messages, nil\n}\n\n\/\/ Close channels and attempt to close channel and connection.\nfunc (r *Rabbus) Close() error {\n\tclose(r.emit)\n\tclose(r.emitOk)\n\tclose(r.emitErr)\n\tclose(r.reconn)\n\n\treturn r.Amqp.Close()\n}\n\nfunc (r *Rabbus) produce(m Message) {\n\tif _, ok := r.exDeclared[m.Exchange]; !ok {\n\t\tif err := r.WithExchange(m.Exchange, m.Kind, r.config.durable); err != nil {\n\t\t\tr.emitErr <- err\n\t\t\treturn\n\t\t}\n\t\tr.exDeclared[m.Exchange] = struct{}{}\n\t}\n\n\tif m.ContentType == \"\" {\n\t\tm.ContentType = ContentTypeJSON\n\t}\n\n\tif m.DeliveryMode == 0 {\n\t\tm.DeliveryMode = Persistent\n\t}\n\n\topts := amqp.Publishing{\n\t\tHeaders:         amqp.Table(m.Headers),\n\t\tContentType:     m.ContentType,\n\t\tContentEncoding: contentEncoding,\n\t\tDeliveryMode:    m.DeliveryMode,\n\t\tTimestamp:       time.Now(),\n\t\tBody:            m.Payload,\n\t}\n\n\tif _, err := r.breaker.Execute(func() (interface{}, error) {\n\t\treturn nil, retry.Do(func() error {\n\t\t\treturn r.Publish(m.Exchange, m.Key, opts)\n\t\t}, r.config.retrycfg.attempts, r.config.retrycfg.sleep)\n\t}); err != nil {\n\t\tr.emitErr <- err\n\t\treturn\n\t}\n\n\tr.emitOk <- struct{}{}\n}\n\n\/\/ Durable indicates of the queue will survive broker restarts. Default to true.\nfunc Durable(durable bool) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.durable = durable\n\t\treturn nil\n\t}\n}\n\n\/\/ PassiveExchange forces passive connection with all exchanges using\n\/\/ amqp's ExchangeDeclarePassive instead the default ExchangeDeclare\nfunc PassiveExchange(passiveex bool) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.passiveex = passiveex\n\t\treturn nil\n\t}\n}\n\n\/\/ PrefetchCount limit the number of unacknowledged messages.\nfunc PrefetchCount(count int) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.qos.prefetchCount = count\n\t\treturn nil\n\t}\n}\n\n\/\/ PrefetchSize when greater than zero, the server will try to keep at least\n\/\/ that many bytes of deliveries flushed to the network before receiving\n\/\/ acknowledgments from the consumers.\nfunc PrefetchSize(size int) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.qos.prefetchSize = size\n\t\treturn nil\n\t}\n}\n\n\/\/ QosGlobal when global is true, these Qos settings apply to all existing and future\n\/\/ consumers on all channels on the same connection. When false, the Channel.Qos\n\/\/ settings will apply to all existing and future consumers on this channel.\n\/\/ RabbitMQ does not implement the global flag.\nfunc QosGlobal(global bool) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.qos.global = global\n\t\treturn nil\n\t}\n}\n\n\/\/ Attempts is the max number of retries on broker outages.\nfunc Attempts(attempts int) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.retrycfg.attempts = attempts\n\t\treturn nil\n\t}\n}\n\n\/\/ Sleep is the sleep time of the retry mechanism.\nfunc Sleep(sleep time.Duration) Option {\n\treturn func(r *Rabbus) error {\n\t\tif sleep == 0 {\n\t\t\tr.config.retrycfg.reconnectSleep = time.Second * 10\n\t\t}\n\t\tr.config.retrycfg.sleep = sleep\n\t\treturn nil\n\t}\n}\n\n\/\/ BreakerInterval is the cyclic period of the closed state for CircuitBreaker to clear the internal counts,\n\/\/ If Interval is 0, CircuitBreaker doesn't clear the internal counts during the closed state.\nfunc BreakerInterval(interval time.Duration) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.breaker.interval = interval\n\t\treturn nil\n\t}\n}\n\n\/\/ BreakerTimeout is the period of the open state, after which the state of CircuitBreaker becomes half-open.\n\/\/ If Timeout is 0, the timeout value of CircuitBreaker is set to 60 seconds.\nfunc BreakerTimeout(timeout time.Duration) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.breaker.timeout = timeout\n\t\treturn nil\n\t}\n}\n\n\/\/ Threshold when a threshold of failures has been reached, future calls to the broker will not run.\n\/\/ During this state, the circuit breaker will periodically allow the calls to run and, if it is successful,\n\/\/ will start running the function again. Default value is 5.\nfunc Threshold(threshold uint32) Option {\n\treturn func(r *Rabbus) error {\n\t\tif threshold == 0 {\n\t\t\tthreshold = 5\n\t\t}\n\t\tr.config.breaker.threshold = threshold\n\t\treturn nil\n\t}\n}\n\n\/\/ OnStateChange is called whenever the state of CircuitBreaker changes.\nfunc OnStateChange(fn OnStateChangeFunc) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.breaker.onStateChange = fn\n\t\treturn nil\n\t}\n}\n\n\/\/ AmqpProvider expose a interface for interacting with amqp broker\nfunc AmqpProvider(provider Amqp) Option {\n\treturn func(r *Rabbus) error {\n\t\tif provider != nil {\n\t\t\tr.Amqp = provider\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"unexpected amqp provider\")\n\t}\n}\n\nfunc (r *Rabbus) wrapMessage(c ListenConfig, sourceChan <-chan amqp.Delivery, targetChan chan ConsumerMessage) {\n\tfor m := range sourceChan {\n\t\ttargetChan <- newConsumerMessage(m)\n\t}\n}\n\nfunc (r *Rabbus) handleAmqpClose(err error) {\n\tfor {\n\t\ttime.Sleep(time.Second)\n\t\taw, err := amqpwrap.New(r.config.dsn, r.config.passiveex)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tr.mu.Lock()\n\t\tr.Amqp = aw\n\t\tr.mu.Unlock()\n\t\tfor i := 1; i <= r.conDeclared; i++ {\n\t\t\tr.reconn <- struct{}{}\n\t\t}\n\t\tbreak\n\t}\n}\n\nfunc (r *Rabbus) listenReconn(c ListenConfig, messages chan ConsumerMessage) {\n\tfor range r.reconn {\n\t\tmsgs, err := r.CreateConsumer(c.Exchange, c.Key, c.Kind, c.Queue, r.config.durable)\n\t\tif err != nil {\n\t\t\tr.Close()\n\t\t\tcontinue\n\t\t}\n\n\t\tgo r.wrapMessage(c, msgs, messages)\n\t\tgo r.listenReconn(c, messages)\n\t\tbreak\n\t}\n}\n\nfunc newBreakerSettings(c config) gobreaker.Settings {\n\ts := gobreaker.Settings{}\n\ts.Name = \"rabbus-circuit-breaker\"\n\ts.Interval = c.breaker.interval\n\ts.Timeout = c.breaker.timeout\n\ts.ReadyToTrip = func(counts gobreaker.Counts) bool {\n\t\treturn counts.ConsecutiveFailures > c.breaker.threshold\n\t}\n\tif c.breaker.onStateChange != nil {\n\t\ts.OnStateChange = func(name string, from gobreaker.State, to gobreaker.State) {\n\t\t\tc.breaker.onStateChange(name, from.String(), to.String())\n\t\t}\n\t}\n\treturn s\n}\n<commit_msg>the counter is locked by the mutex<commit_after>package rabbus\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\t\"time\"\n\n\tamqpwrap \"github.com\/rafaeljesus\/rabbus\/internal\/amqp\"\n\t\"github.com\/rafaeljesus\/retry-go\"\n\t\"github.com\/sony\/gobreaker\"\n\t\"github.com\/streadway\/amqp\"\n)\n\nconst (\n\t\/\/ Transient means higher throughput but messages will not be restored on broker restart.\n\tTransient uint8 = 1\n\t\/\/ Persistent messages will be restored to durable queues and lost on non-durable queues during server restart.\n\tPersistent uint8 = 2\n\t\/\/ ContentTypeJSON define json content type\n\tContentTypeJSON = \"application\/json\"\n\t\/\/ ContentTypePlain define plain text content type\n\tContentTypePlain = \"plain\/text\"\n\n\tcontentEncoding = \"UTF-8\"\n)\n\ntype (\n\t\/\/ Option represents an option you can pass to New.\n\t\/\/ See the documentation for the individual options.\n\tOption func(*Rabbus) error\n\t\/\/ OnStateChangeFunc is the callback function when circuit breaker state changes.\n\tOnStateChangeFunc func(name, from, to string)\n\n\t\/\/ Message carries fields for sending messages.\n\tMessage struct {\n\t\t\/\/ Exchange the exchange name.\n\t\tExchange string\n\t\t\/\/ Kind the exchange type.\n\t\tKind string\n\t\t\/\/ Key the routing key name.\n\t\tKey string\n\t\t\/\/ Payload the message payload.\n\t\tPayload []byte\n\t\t\/\/ DeliveryMode indicates if the is Persistent or Transient.\n\t\tDeliveryMode uint8\n\t\t\/\/ ContentType the message content-type.\n\t\tContentType string\n\t\t\/\/ Headers the message application headers\n\t\tHeaders map[string]interface{}\n\t}\n\n\t\/\/ ListenConfig carries fields for listening messages.\n\tListenConfig struct {\n\t\t\/\/ Exchange the exchange name.\n\t\tExchange string\n\t\t\/\/ Kind the exchange type.\n\t\tKind string\n\t\t\/\/ Key the routing key name.\n\t\tKey string\n\t\t\/\/ PassiveExchange determines a passive exchange connection it uses\n\t\t\/\/ amqp's ExchangeDeclarePassive instead the default ExchangeDeclare\n\t\tPassiveExchange bool\n\t\t\/\/ Queue the queue name\n\t\tQueue string\n\t}\n\n\t\/\/ Delivery wraps amqp.Delivery struct\n\tDelivery struct {\n\t\tamqp.Delivery\n\t}\n\n\t\/\/ Rabbus interpret (implement) Rabbus interface definition\n\tRabbus struct {\n\t\tAmqp\n\t\tmu         sync.RWMutex\n\t\tbreaker    *gobreaker.CircuitBreaker\n\t\temit       chan Message\n\t\temitErr    chan error\n\t\temitOk     chan struct{}\n\t\treconn     chan struct{}\n\t\texDeclared map[string]struct{}\n\t\tconfig\n\t\tconDeclared int \/\/ conDeclared is a counter for the declared consumers\n\t}\n\n\t\/\/ Amqp expose a interface for interacting with amqp broker\n\tAmqp interface {\n\t\t\/\/ Publish wraps amqp.Publish method\n\t\tPublish(exchange, key string, opts amqp.Publishing) error\n\t\t\/\/ CreateConsumer creates a amqp consumer\n\t\tCreateConsumer(exchange, key, kind, queue string, durable bool) (<-chan amqp.Delivery, error)\n\t\t\/\/ WithExchange creates a amqp exchange\n\t\tWithExchange(exchange, kind string, durable bool) error\n\t\t\/\/ WithQos wrapper over amqp.Qos method\n\t\tWithQos(count, size int, global bool) error\n\t\t\/\/ NotifyClose wrapper over notifyClose method\n\t\tNotifyClose(c chan *amqp.Error) chan *amqp.Error\n\t\t\/\/ Close closes the running amqp connection and channel\n\t\tClose() error\n\t}\n\n\tconfig struct {\n\t\tdsn                string\n\t\tdurable, passiveex bool\n\t\tretrycfg\n\t\tbreaker\n\t\tqos\n\t}\n\n\tretrycfg struct {\n\t\tattempts              int\n\t\tsleep, reconnectSleep time.Duration\n\t}\n\n\tbreaker struct {\n\t\tinterval, timeout time.Duration\n\t\tthreshold         uint32\n\t\tonStateChange     OnStateChangeFunc\n\t}\n\n\tqos struct {\n\t\tprefetchCount, prefetchSize int\n\t\tglobal                      bool\n\t}\n)\n\nfunc (lc ListenConfig) validate() error {\n\tif lc.Exchange == \"\" {\n\t\treturn ErrMissingExchange\n\t}\n\n\tif lc.Kind == \"\" {\n\t\treturn ErrMissingKind\n\t}\n\n\tif lc.Queue == \"\" {\n\t\treturn ErrMissingQueue\n\t}\n\n\treturn nil\n}\n\n\/\/ New returns a new Rabbus configured with the\n\/\/ variables from the config parameter, or returning an non-nil err\n\/\/ if an error occurred while creating connection and channel.\nfunc New(dsn string, options ...Option) (*Rabbus, error) {\n\tr := &Rabbus{\n\t\temit:       make(chan Message),\n\t\temitErr:    make(chan error),\n\t\temitOk:     make(chan struct{}),\n\t\treconn:     make(chan struct{}, 10),\n\t\texDeclared: make(map[string]struct{}),\n\t}\n\n\tfor _, o := range options {\n\t\tif err := o(r); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif r.Amqp == nil {\n\t\tamqpWrapper, err := amqpwrap.New(dsn, r.config.passiveex)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tr.Amqp = amqpWrapper\n\t}\n\n\tif err := r.WithQos(\n\t\tr.config.qos.prefetchCount,\n\t\tr.config.qos.prefetchSize,\n\t\tr.config.qos.global,\n\t); err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.config.dsn = dsn\n\tr.breaker = gobreaker.NewCircuitBreaker(newBreakerSettings(r.config))\n\n\treturn r, nil\n}\n\n\/\/ Run starts rabbus channels for emitting and listening for amqp connection close\n\/\/ returns ctx error in case of any.\nfunc (r *Rabbus) Run(ctx context.Context) error {\n\tfor {\n\t\tselect {\n\t\tcase m, ok := <-r.emit:\n\t\t\tif ok {\n\t\t\t\tr.produce(m)\n\t\t\t}\n\t\tcase err, ok := <-r.NotifyClose(make(chan *amqp.Error)):\n\t\t\tif ok {\n\t\t\t\tr.handleAmqpClose(err)\n\t\t\t}\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\t}\n\t}\n}\n\n\/\/ EmitAsync emits a message to RabbitMQ, but does not wait for the response from broker.\nfunc (r *Rabbus) EmitAsync() chan<- Message { return r.emit }\n\n\/\/ EmitErr returns an error if encoding payload fails, or if after circuit breaker is open or retries attempts exceed.\nfunc (r *Rabbus) EmitErr() <-chan error { return r.emitErr }\n\n\/\/ EmitOk returns true when the message was sent.\nfunc (r *Rabbus) EmitOk() <-chan struct{} { return r.emitOk }\n\n\/\/ Listen to a message from RabbitMQ, returns\n\/\/ an error if exchange, queue name and function handler not passed or if an error occurred while creating\n\/\/ amqp consumer.\nfunc (r *Rabbus) Listen(c ListenConfig) (chan ConsumerMessage, error) {\n\tif err := c.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmsgs, err := r.CreateConsumer(c.Exchange, c.Key, c.Kind, c.Queue, r.config.durable)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.mu.Lock()\n\tr.conDeclared++ \/\/ increase the declared consumers counter\n\tr.exDeclared[c.Exchange] = struct{}{}\n\tr.mu.Unlock()\n\n\tmessages := make(chan ConsumerMessage, 256)\n\tgo r.wrapMessage(c, msgs, messages)\n\tgo r.listenReconn(c, messages)\n\n\treturn messages, nil\n}\n\n\/\/ Close channels and attempt to close channel and connection.\nfunc (r *Rabbus) Close() error {\n\tclose(r.emit)\n\tclose(r.emitOk)\n\tclose(r.emitErr)\n\tclose(r.reconn)\n\n\treturn r.Amqp.Close()\n}\n\nfunc (r *Rabbus) produce(m Message) {\n\tif _, ok := r.exDeclared[m.Exchange]; !ok {\n\t\tif err := r.WithExchange(m.Exchange, m.Kind, r.config.durable); err != nil {\n\t\t\tr.emitErr <- err\n\t\t\treturn\n\t\t}\n\t\tr.exDeclared[m.Exchange] = struct{}{}\n\t}\n\n\tif m.ContentType == \"\" {\n\t\tm.ContentType = ContentTypeJSON\n\t}\n\n\tif m.DeliveryMode == 0 {\n\t\tm.DeliveryMode = Persistent\n\t}\n\n\topts := amqp.Publishing{\n\t\tHeaders:         amqp.Table(m.Headers),\n\t\tContentType:     m.ContentType,\n\t\tContentEncoding: contentEncoding,\n\t\tDeliveryMode:    m.DeliveryMode,\n\t\tTimestamp:       time.Now(),\n\t\tBody:            m.Payload,\n\t}\n\n\tif _, err := r.breaker.Execute(func() (interface{}, error) {\n\t\treturn nil, retry.Do(func() error {\n\t\t\treturn r.Publish(m.Exchange, m.Key, opts)\n\t\t}, r.config.retrycfg.attempts, r.config.retrycfg.sleep)\n\t}); err != nil {\n\t\tr.emitErr <- err\n\t\treturn\n\t}\n\n\tr.emitOk <- struct{}{}\n}\n\n\/\/ Durable indicates of the queue will survive broker restarts. Default to true.\nfunc Durable(durable bool) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.durable = durable\n\t\treturn nil\n\t}\n}\n\n\/\/ PassiveExchange forces passive connection with all exchanges using\n\/\/ amqp's ExchangeDeclarePassive instead the default ExchangeDeclare\nfunc PassiveExchange(passiveex bool) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.passiveex = passiveex\n\t\treturn nil\n\t}\n}\n\n\/\/ PrefetchCount limit the number of unacknowledged messages.\nfunc PrefetchCount(count int) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.qos.prefetchCount = count\n\t\treturn nil\n\t}\n}\n\n\/\/ PrefetchSize when greater than zero, the server will try to keep at least\n\/\/ that many bytes of deliveries flushed to the network before receiving\n\/\/ acknowledgments from the consumers.\nfunc PrefetchSize(size int) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.qos.prefetchSize = size\n\t\treturn nil\n\t}\n}\n\n\/\/ QosGlobal when global is true, these Qos settings apply to all existing and future\n\/\/ consumers on all channels on the same connection. When false, the Channel.Qos\n\/\/ settings will apply to all existing and future consumers on this channel.\n\/\/ RabbitMQ does not implement the global flag.\nfunc QosGlobal(global bool) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.qos.global = global\n\t\treturn nil\n\t}\n}\n\n\/\/ Attempts is the max number of retries on broker outages.\nfunc Attempts(attempts int) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.retrycfg.attempts = attempts\n\t\treturn nil\n\t}\n}\n\n\/\/ Sleep is the sleep time of the retry mechanism.\nfunc Sleep(sleep time.Duration) Option {\n\treturn func(r *Rabbus) error {\n\t\tif sleep == 0 {\n\t\t\tr.config.retrycfg.reconnectSleep = time.Second * 10\n\t\t}\n\t\tr.config.retrycfg.sleep = sleep\n\t\treturn nil\n\t}\n}\n\n\/\/ BreakerInterval is the cyclic period of the closed state for CircuitBreaker to clear the internal counts,\n\/\/ If Interval is 0, CircuitBreaker doesn't clear the internal counts during the closed state.\nfunc BreakerInterval(interval time.Duration) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.breaker.interval = interval\n\t\treturn nil\n\t}\n}\n\n\/\/ BreakerTimeout is the period of the open state, after which the state of CircuitBreaker becomes half-open.\n\/\/ If Timeout is 0, the timeout value of CircuitBreaker is set to 60 seconds.\nfunc BreakerTimeout(timeout time.Duration) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.breaker.timeout = timeout\n\t\treturn nil\n\t}\n}\n\n\/\/ Threshold when a threshold of failures has been reached, future calls to the broker will not run.\n\/\/ During this state, the circuit breaker will periodically allow the calls to run and, if it is successful,\n\/\/ will start running the function again. Default value is 5.\nfunc Threshold(threshold uint32) Option {\n\treturn func(r *Rabbus) error {\n\t\tif threshold == 0 {\n\t\t\tthreshold = 5\n\t\t}\n\t\tr.config.breaker.threshold = threshold\n\t\treturn nil\n\t}\n}\n\n\/\/ OnStateChange is called whenever the state of CircuitBreaker changes.\nfunc OnStateChange(fn OnStateChangeFunc) Option {\n\treturn func(r *Rabbus) error {\n\t\tr.config.breaker.onStateChange = fn\n\t\treturn nil\n\t}\n}\n\n\/\/ AmqpProvider expose a interface for interacting with amqp broker\nfunc AmqpProvider(provider Amqp) Option {\n\treturn func(r *Rabbus) error {\n\t\tif provider != nil {\n\t\t\tr.Amqp = provider\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"unexpected amqp provider\")\n\t}\n}\n\nfunc (r *Rabbus) wrapMessage(c ListenConfig, sourceChan <-chan amqp.Delivery, targetChan chan ConsumerMessage) {\n\tfor m := range sourceChan {\n\t\ttargetChan <- newConsumerMessage(m)\n\t}\n}\n\nfunc (r *Rabbus) handleAmqpClose(err error) {\n\tfor {\n\t\ttime.Sleep(time.Second)\n\t\taw, err := amqpwrap.New(r.config.dsn, r.config.passiveex)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tr.mu.Lock()\n\t\tr.Amqp = aw\n\t\tr.mu.Unlock()\n\t\tfor i := 1; i <= r.conDeclared; i++ {\n\t\t\tr.reconn <- struct{}{}\n\t\t}\n\t\tbreak\n\t}\n}\n\nfunc (r *Rabbus) listenReconn(c ListenConfig, messages chan ConsumerMessage) {\n\tfor range r.reconn {\n\t\tmsgs, err := r.CreateConsumer(c.Exchange, c.Key, c.Kind, c.Queue, r.config.durable)\n\t\tif err != nil {\n\t\t\tr.Close()\n\t\t\tcontinue\n\t\t}\n\n\t\tgo r.wrapMessage(c, msgs, messages)\n\t\tgo r.listenReconn(c, messages)\n\t\tbreak\n\t}\n}\n\nfunc newBreakerSettings(c config) gobreaker.Settings {\n\ts := gobreaker.Settings{}\n\ts.Name = \"rabbus-circuit-breaker\"\n\ts.Interval = c.breaker.interval\n\ts.Timeout = c.breaker.timeout\n\ts.ReadyToTrip = func(counts gobreaker.Counts) bool {\n\t\treturn counts.ConsecutiveFailures > c.breaker.threshold\n\t}\n\tif c.breaker.onStateChange != nil {\n\t\ts.OnStateChange = func(name string, from gobreaker.State, to gobreaker.State) {\n\t\t\tc.breaker.onStateChange(name, from.String(), to.String())\n\t\t}\n\t}\n\treturn s\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cmd\n\nimport (\n\t\"os\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/cluster\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/config\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/constants\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/exit\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/kubeconfig\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/machine\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/out\"\n)\n\n\/\/ updateContextCmd represents the update-context command\nvar updateContextCmd = &cobra.Command{\n\tUse:   \"update-context\",\n\tShort: \"Verify the IP address of the running cluster in kubeconfig.\",\n\tLong: `Retrieves the IP address of the running cluster, checks it\n\t\t\twith IP in kubeconfig, and corrects kubeconfig if incorrect.`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tapi, err := machine.NewAPIClient()\n\t\tif err != nil {\n\t\t\texit.WithError(\"Error getting client\", err)\n\t\t}\n\t\tdefer api.Close()\n\t\tmachineName := viper.GetString(config.MachineProfile)\n\t\tip, err := cluster.GetHostDriverIP(api, machineName)\n\t\tif err != nil {\n\t\t\texit.WithError(\"Error host driver ip status\", err)\n\t\t}\n\t\tupdated := false\n\t\tkubeConfigPath := os.Getenv(\"KUBECONFIG\")\n\t\tif kubeConfigPath == \"\" {\n\t\t\tupdated, err = kubeconfig.UpdateIP(ip, machineName, constants.KubeconfigPath)\n\t\t} else {\n\t\t\tupdated, err = kubeconfig.UpdateIP(ip, machineName, kubeConfigPath)\n\t\t}\n\t\tif err != nil {\n\t\t\texit.WithError(\"update config\", err)\n\t\t}\n\t\tif updated {\n\t\t\tout.T(out.Celebrate, \"{{.machine}} IP has been updated to point at {{.ip}}\", out.V{\"machine\": machineName, \"ip\": ip})\n\t\t} else {\n\t\t\tout.T(out.Meh, \"{{.machine}} IP was already correctly configured for {{.ip}}\", out.V{\"machine\": machineName, \"ip\": ip})\n\t\t}\n\n\t},\n}\n<commit_msg>Minor: change assignment to declaration<commit_after>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cmd\n\nimport (\n\t\"os\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/cluster\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/config\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/constants\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/exit\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/kubeconfig\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/machine\"\n\t\"k8s.io\/minikube\/pkg\/minikube\/out\"\n)\n\n\/\/ updateContextCmd represents the update-context command\nvar updateContextCmd = &cobra.Command{\n\tUse:   \"update-context\",\n\tShort: \"Verify the IP address of the running cluster in kubeconfig.\",\n\tLong: `Retrieves the IP address of the running cluster, checks it\n\t\t\twith IP in kubeconfig, and corrects kubeconfig if incorrect.`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tapi, err := machine.NewAPIClient()\n\t\tif err != nil {\n\t\t\texit.WithError(\"Error getting client\", err)\n\t\t}\n\t\tdefer api.Close()\n\t\tmachineName := viper.GetString(config.MachineProfile)\n\t\tip, err := cluster.GetHostDriverIP(api, machineName)\n\t\tif err != nil {\n\t\t\texit.WithError(\"Error host driver ip status\", err)\n\t\t}\n\t\tvar updated bool\n\t\tkubeConfigPath := os.Getenv(\"KUBECONFIG\")\n\t\tif kubeConfigPath == \"\" {\n\t\t\tupdated, err = kubeconfig.UpdateIP(ip, machineName, constants.KubeconfigPath)\n\t\t} else {\n\t\t\tupdated, err = kubeconfig.UpdateIP(ip, machineName, kubeConfigPath)\n\t\t}\n\t\tif err != nil {\n\t\t\texit.WithError(\"update config\", err)\n\t\t}\n\t\tif updated {\n\t\t\tout.T(out.Celebrate, \"{{.machine}} IP has been updated to point at {{.ip}}\", out.V{\"machine\": machineName, \"ip\": ip})\n\t\t} else {\n\t\t\tout.T(out.Meh, \"{{.machine}} IP was already correctly configured for {{.ip}}\", out.V{\"machine\": machineName, \"ip\": ip})\n\t\t}\n\n\t},\n}\n<|endoftext|>"}
{"text":"<commit_before>package crypto\n\nimport (\n\t\"crypto\/aes\"\n\t\"crypto\/cipher\"\n\tcrand \"crypto\/rand\"\n\t\"encoding\/hex\"\n\t\"io\"\n\t\"sync\"\n\n\t. \"github.com\/tendermint\/go-common\"\n)\n\nvar gRandInfo *randInfo\n\nfunc init() {\n\tgRandInfo = &randInfo{}\n\tgRandInfo.AddSeed(randBytes(32)) \/\/ Init\n}\n\n\/\/ Add additional bytes of randomness, e.g. from hardware, user-input, etc.\n\/\/ It is OK to call it multiple times.  It does not deminish security.\nfunc Seed(seedBytes []byte) {\n\tgRandInfo.AddSeed(seedBytes)\n}\n\n\/\/ This only uses the OS's randomness\nfunc randBytes(numBytes int) []byte {\n\tb := make([]byte, numBytes)\n\t_, err := crand.Read(b)\n\tif err != nil {\n\t\tPanicCrisis(err)\n\t}\n\treturn b\n}\n\n\/\/ This uses the OS and the Seed(s).\nfunc CRandBytes(numBytes int) []byte {\n\tb := make([]byte, numBytes)\n\t_, err := gRandInfo.Read(b)\n\tif err != nil {\n\t\tPanicCrisis(err)\n\t}\n\treturn b\n}\n\n\/\/ RandHex(24) gives 96 bits of randomness, strong enough for most purposes.\nfunc CRandHex(numDigits int) string {\n\treturn hex.EncodeToString(CRandBytes(numDigits \/ 2))\n}\n\n\/\/ Returns a crand.Reader mixed with user-supplied entropy\nfunc CReader() io.Reader {\n\treturn gRandInfo\n}\n\n\/\/--------------------------------------------------------------------------------\n\ntype randInfo struct {\n\tmtx          sync.Mutex\n\tseedBytes    [32]byte\n\tcipherAES256 cipher.Block\n\tstreamAES256 cipher.Stream\n\treader       io.Reader\n}\n\n\/\/ You can call this as many times as you'd like.\n\/\/ XXX TODO review\nfunc (ri *randInfo) AddSeed(seedBytes []byte) {\n\tri.mtx.Lock()\n\tdefer ri.mtx.Unlock()\n\t\/\/ Make new ri.seedBytes\n\thashBytes := Sha256(seedBytes)\n\thashBytes32 := [32]byte{}\n\tcopy(hashBytes32[:], hashBytes)\n\tri.seedBytes = xorBytes32(ri.seedBytes, hashBytes32)\n\t\/\/ Create new cipher.Block\n\tvar err error\n\tri.cipherAES256, err = aes.NewCipher(ri.seedBytes[:])\n\tif err != nil {\n\t\tPanicSanity(\"Error creating AES256 cipher: \" + err.Error())\n\t}\n\t\/\/ Create new stream\n\tri.streamAES256 = cipher.NewCTR(ri.cipherAES256, randBytes(aes.BlockSize))\n\t\/\/ Create new reader\n\tri.reader = &cipher.StreamReader{S: ri.streamAES256, R: crand.Reader}\n}\n\nfunc (ri *randInfo) Read(b []byte) (n int, err error) {\n\tri.mtx.Lock()\n\tdefer ri.mtx.Unlock()\n\treturn ri.reader.Read(b)\n}\n\nfunc xorBytes32(bytesA [32]byte, bytesB [32]byte) (res [32]byte) {\n\tfor i, b := range bytesA {\n\t\tres[i] = b ^ bytesB[i]\n\t}\n\treturn res\n}\n<commit_msg>s\/Seed\/MixEntropy\/g<commit_after>package crypto\n\nimport (\n\t\"crypto\/aes\"\n\t\"crypto\/cipher\"\n\tcrand \"crypto\/rand\"\n\t\"encoding\/hex\"\n\t\"io\"\n\t\"sync\"\n\n\t. \"github.com\/tendermint\/go-common\"\n)\n\nvar gRandInfo *randInfo\n\nfunc init() {\n\tgRandInfo = &randInfo{}\n\tgRandInfo.MixEntropy(randBytes(32)) \/\/ Init\n}\n\n\/\/ Mix additional bytes of randomness, e.g. from hardware, user-input, etc.\n\/\/ It is OK to call it multiple times.  It does not diminish security.\nfunc MixEntropy(seedBytes []byte) {\n\tgRandInfo.MixEntropy(seedBytes)\n}\n\n\/\/ This only uses the OS's randomness\nfunc randBytes(numBytes int) []byte {\n\tb := make([]byte, numBytes)\n\t_, err := crand.Read(b)\n\tif err != nil {\n\t\tPanicCrisis(err)\n\t}\n\treturn b\n}\n\n\/\/ This uses the OS and the Seed(s).\nfunc CRandBytes(numBytes int) []byte {\n\tb := make([]byte, numBytes)\n\t_, err := gRandInfo.Read(b)\n\tif err != nil {\n\t\tPanicCrisis(err)\n\t}\n\treturn b\n}\n\n\/\/ RandHex(24) gives 96 bits of randomness, strong enough for most purposes.\nfunc CRandHex(numDigits int) string {\n\treturn hex.EncodeToString(CRandBytes(numDigits \/ 2))\n}\n\n\/\/ Returns a crand.Reader mixed with user-supplied entropy\nfunc CReader() io.Reader {\n\treturn gRandInfo\n}\n\n\/\/--------------------------------------------------------------------------------\n\ntype randInfo struct {\n\tmtx          sync.Mutex\n\tseedBytes    [32]byte\n\tcipherAES256 cipher.Block\n\tstreamAES256 cipher.Stream\n\treader       io.Reader\n}\n\n\/\/ You can call this as many times as you'd like.\n\/\/ XXX TODO review\nfunc (ri *randInfo) MixEntropy(seedBytes []byte) {\n\tri.mtx.Lock()\n\tdefer ri.mtx.Unlock()\n\t\/\/ Make new ri.seedBytes\n\thashBytes := Sha256(seedBytes)\n\thashBytes32 := [32]byte{}\n\tcopy(hashBytes32[:], hashBytes)\n\tri.seedBytes = xorBytes32(ri.seedBytes, hashBytes32)\n\t\/\/ Create new cipher.Block\n\tvar err error\n\tri.cipherAES256, err = aes.NewCipher(ri.seedBytes[:])\n\tif err != nil {\n\t\tPanicSanity(\"Error creating AES256 cipher: \" + err.Error())\n\t}\n\t\/\/ Create new stream\n\tri.streamAES256 = cipher.NewCTR(ri.cipherAES256, randBytes(aes.BlockSize))\n\t\/\/ Create new reader\n\tri.reader = &cipher.StreamReader{S: ri.streamAES256, R: crand.Reader}\n}\n\nfunc (ri *randInfo) Read(b []byte) (n int, err error) {\n\tri.mtx.Lock()\n\tdefer ri.mtx.Unlock()\n\treturn ri.reader.Read(b)\n}\n\nfunc xorBytes32(bytesA [32]byte, bytesB [32]byte) (res [32]byte) {\n\tfor i, b := range bytesA {\n\t\tres[i] = b ^ bytesB[i]\n\t}\n\treturn res\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\n\t\"bufio\"\n\t\"github.com\/rgbkrk\/libvirt-go\"\n\t\"html\"\n\t\"strings\"\n)\n\ntype virtlauncher struct {\n\tdomainXML  string\n\tdomainUUID string\n\tconnURI    string\n\tuser       string\n\tpass       string\n}\n\nfunc main() {\n\txmlPath := flag.String(\"domain-path\", \"\/var\/run\/virt-launcher\/dom.xml\", \"Where to look for the domain xml.\")\n\tdownwardAPIPath := flag.String(\"downward-api-path\", \"\", \"Load domain from this downward API file\")\n\tconUri := flag.String(\"libvirt-uri\", \"qemu:\/\/\/system\", \"Libvirt connection string.\")\n\tuser := flag.String(\"user\", \"vdsm@ovirt\", \"Libvirt user\")\n\tpass := flag.String(\"pass\", \"shibboleth\", \"Libvirt password\")\n\treceiveOnly := flag.Bool(\"receive-only\", false, \"Do not create the domain\")\n\tflag.Parse()\n\n\tlauncher := virtlauncher{\n\t\tconnURI: *conUri,\n\t\tuser:    *user,\n\t\tpass:    *pass,\n\t}\n\n\tif !*receiveOnly {\n\t\tlauncher.ReadDomainXML(*xmlPath, *downwardAPIPath)\n\t\tlauncher.CreateDomain()\n\t}\n\n\twaitUntilSignal()\n}\n\nfunc (vl *virtlauncher) CreateDomain() {\n\tconn, err := libvirt.NewVirConnectionWithAuth(vl.connURI, vl.user, vl.pass)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not connect to libvirt using %s: %s\", vl.connURI, err))\n\t}\n\tdefer func() {\n\t\tif _, closeErr := conn.CloseConnection(); closeErr != nil {\n\t\t\tlog.Fatalf(\"CloseConnection() failed: %s\", closeErr)\n\t\t}\n\t\tlog.Print(\"Connection closed\")\n\t}()\n\n\tlog.Print(\"Libvirt connection established\")\n\n\t\/\/ Launch VM\n\t_, err = conn.DomainCreateXML(vl.domainXML, 0)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not create the libvirt domain: %s\", err))\n\t}\n\n\tlog.Print(\"Domain started\")\n}\n\nfunc waitUntilSignal() {\n\t\/\/ Wait for termination\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt,\n\t\tsyscall.SIGHUP,\n\t\tsyscall.SIGINT,\n\t\tsyscall.SIGTERM,\n\t\tsyscall.SIGQUIT,\n\t)\n\n\tlog.Printf(\"Waiting forever...\")\n\ts := <-c\n\tlog.Print(\"Got signal: \", s)\n}\n\nfunc (vl *virtlauncher) ReadDomainXML(xmlPath string, downwardAPIPath string) {\n\tif downwardAPIPath == \"\" {\n\t\tlog.Print(\"Loading Domain from XML file\")\n\t\trawXML, err := ioutil.ReadFile(xmlPath)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tvl.domainXML = string(rawXML)\n\t} else {\n\t\tlog.Print(\"Loading Domain from downward API file\")\n\t\tf, err := os.Open(downwardAPIPath)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer f.Close()\n\t\tscanner := bufio.NewScanner(f)\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif strings.HasPrefix(line, `domainXML=\"`) {\n\t\t\t\tvl.domainXML = DecodeDomainXML(strings.Trim(strings.TrimPrefix(line, \"domainXML=\"), `\"`))\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif vl.domainXML == \"\" {\n\t\tpanic(\"Could not load domain XML. The resulting XML is empty\")\n\t}\n\tlog.Print(\"Domain description loaded.\")\n}\n\nfunc DecodeDomainXML(domainXML string) string {\n\tdecodedXML := html.UnescapeString(string(domainXML))\n\tdecodedXML = strings.Replace(decodedXML, \"\\\\\\\\\", \"\\\\\", -1)\n\tdecodedXML = strings.Replace(decodedXML, \"\\\\n\", \"\\n\", -1)\n\treturn decodedXML\n}\n<commit_msg>virt-launcher: monitor qemu process<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"bufio\"\n\t\"github.com\/rgbkrk\/libvirt-go\"\n\t\"html\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype virtlauncher struct {\n\tdomainXML  string\n\tdomainUUID string\n\tconnURI    string\n\tuser       string\n\tpass       string\n}\n\ntype monitor struct {\n\ttimeout   time.Duration\n\tpid       int\n\texename   string\n\tstart     time.Time\n\tisDone    bool\n\tdebugMode bool\n}\n\nfunc (mon *monitor) refresh() {\n\tif mon.isDone {\n\t\tlog.Print(\"Called refresh after done!\")\n\t\treturn\n\t}\n\n\tif mon.debugMode {\n\t\tlog.Printf(\"Refreshing executable %s pid %d\", mon.exename, mon.pid)\n\t}\n\n\t\/\/ is the procecess there?\n\tif mon.pid == 0 {\n\t\tvar err error\n\t\tmon.pid, err = pidOf(mon.exename)\n\t\tif err == nil {\n\t\t\tlog.Printf(\"Found PID for %s: %d\", mon.exename, mon.pid)\n\t\t} else {\n\t\t\tif mon.debugMode {\n\t\t\t\tlog.Printf(\"Missing PID for %s\", mon.exename)\n\t\t\t}\n\t\t\t\/\/ if the proces is not there yet, is it too late?\n\t\t\telapsed := time.Since(mon.start)\n\t\t\tif mon.timeout > 0 && elapsed >= mon.timeout {\n\t\t\t\tlog.Printf(\"%s not found after timeout\", mon.exename)\n\t\t\t\tmon.isDone = true\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ is the process gone? mon.pid != 0 -> mon.pid == 0\n\t\/\/ note libvirt deliver one event for this, but since we need\n\t\/\/ to poll procfs anyway to detect incoming QEMUs after migrations,\n\t\/\/ we choose to not use this. Bonus: we can close the connection\n\t\/\/ and open it only when needed, which is a tiny part of the\n\t\/\/ virt-launcher lifetime.\n\tif !pidExists(mon.pid) {\n\t\tlog.Printf(\"Process %s is gone!\", mon.exename)\n\t\tmon.pid = 0\n\t\tmon.isDone = true\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (mon *monitor) RunForever(startTimeout time.Duration) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt,\n\t\tsyscall.SIGHUP,\n\t\tsyscall.SIGINT,\n\t\tsyscall.SIGTERM,\n\t\tsyscall.SIGQUIT,\n\t)\n\n\t\/\/ random value, no real rationale\n\trate := 500 * time.Millisecond\n\n\tif mon.debugMode {\n\t\ttimeoutRepr := fmt.Sprintf(\"%v\", startTimeout)\n\t\tif startTimeout == 0 {\n\t\t\ttimeoutRepr = \"disabled\"\n\t\t}\n\t\tlog.Printf(\"Monitoring loop: rate %v start timeout %s\", rate, timeoutRepr)\n\t}\n\n\tticker := time.NewTicker(rate)\n\n\tgotSignal := false\n\tmon.isDone = false\n\tmon.timeout = startTimeout\n\tmon.start = time.Now()\n\n\tlog.Printf(\"Waiting forever...\")\n\tfor !gotSignal && !mon.isDone {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tmon.refresh()\n\t\tcase s := <-c:\n\t\t\tlog.Print(\"Got signal: \", s)\n\t\t\tgotSignal = true\n\t\t}\n\t}\n\n\tticker.Stop()\n\tlog.Printf(\"Exiting...\")\n}\n\nfunc main() {\n\tstartTimeout := 0 * time.Second\n\n\txmlPath := flag.String(\"domain-path\", \"\/var\/run\/virt-launcher\/dom.xml\", \"Where to look for the domain xml.\")\n\tdownwardAPIPath := flag.String(\"downward-api-path\", \"\", \"Load domain from this downward API file\")\n\tconUri := flag.String(\"libvirt-uri\", \"qemu:\/\/\/system\", \"Libvirt connection string.\")\n\tuser := flag.String(\"user\", \"vdsm@ovirt\", \"Libvirt user\")\n\tpass := flag.String(\"pass\", \"shibboleth\", \"Libvirt password\")\n\treceiveOnly := flag.Bool(\"receive-only\", false, \"Do not create the domain\")\n\tqemuTimeout := flag.Duration(\"qemu-timeout\", startTimeout, \"Amount of time to wait for qemu\")\n\tdebugMode := flag.Bool(\"debug\", false, \"Enable debug messages\")\n\tflag.Parse()\n\n\tmon := monitor{\n\t\texename:   \"qemu\",\n\t\tdebugMode: *debugMode,\n\t}\n\n\tlauncher := virtlauncher{\n\t\tconnURI: *conUri,\n\t\tuser:    *user,\n\t\tpass:    *pass,\n\t}\n\n\tif !*receiveOnly {\n\t\tlauncher.ReadDomainXML(*xmlPath, *downwardAPIPath)\n\t\tlauncher.CreateDomain()\n\t}\n\n\tmon.RunForever(*qemuTimeout)\n}\n\nfunc (vl *virtlauncher) CreateDomain() {\n\tconn, err := libvirt.NewVirConnectionWithAuth(vl.connURI, vl.user, vl.pass)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not connect to libvirt using %s: %s\", vl.connURI, err))\n\t}\n\tdefer func() {\n\t\tif _, closeErr := conn.CloseConnection(); closeErr != nil {\n\t\t\tlog.Fatalf(\"CloseConnection() failed: %s\", closeErr)\n\t\t}\n\t\tlog.Print(\"Connection closed\")\n\t}()\n\n\tlog.Print(\"Libvirt connection established\")\n\n\t\/\/ Launch VM\n\t_, err = conn.DomainCreateXML(vl.domainXML, 0)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not create the libvirt domain: %s\", err))\n\t}\n\n\tlog.Print(\"Domain started\")\n}\n\nfunc (vl *virtlauncher) ReadDomainXML(xmlPath string, downwardAPIPath string) {\n\tif downwardAPIPath == \"\" {\n\t\tlog.Print(\"Loading Domain from XML file\")\n\t\trawXML, err := ioutil.ReadFile(xmlPath)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tvl.domainXML = string(rawXML)\n\t} else {\n\t\tlog.Print(\"Loading Domain from downward API file\")\n\t\tf, err := os.Open(downwardAPIPath)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer f.Close()\n\t\tscanner := bufio.NewScanner(f)\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif strings.HasPrefix(line, `domainXML=\"`) {\n\t\t\t\tvl.domainXML = DecodeDomainXML(strings.Trim(strings.TrimPrefix(line, \"domainXML=\"), `\"`))\n\t\t\t}\n\t\t}\n\n\t}\n\n\tif vl.domainXML == \"\" {\n\t\tpanic(\"Could not load domain XML. The resulting XML is empty\")\n\t}\n\tlog.Print(\"Domain description loaded.\")\n}\n\nfunc DecodeDomainXML(domainXML string) string {\n\tdecodedXML := html.UnescapeString(string(domainXML))\n\tdecodedXML = strings.Replace(decodedXML, \"\\\\\\\\\", \"\\\\\", -1)\n\tdecodedXML = strings.Replace(decodedXML, \"\\\\n\", \"\\n\", -1)\n\treturn decodedXML\n}\n\nfunc readProcCmdline(pathname string) ([]string, error) {\n\tcontent, err := ioutil.ReadFile(pathname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn strings.Split(string(content), \"\\x00\"), nil\n}\n\nfunc pidOf(exename string) (int, error) {\n\tentries, err := filepath.Glob(\"\/proc\/*\/cmdline\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tfor _, entry := range entries {\n\t\targv, err := readProcCmdline(entry)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\t\/\/ we need to support both\n\t\t\/\/ - \/usr\/bin\/qemu-system-$ARCH (fedora)\n\t\t\/\/ - \/usr\/libexec\/qemu-kvm (*EL, CentOS)\n\t\tmatch, _ := filepath.Match(fmt.Sprintf(\"%s*\", exename), filepath.Base(argv[0]))\n\n\t\tif match {\n\t\t\t\/\/   <empty> \/    proc     \/    $PID   \/   cmdline\n\t\t\t\/\/ items[0] sep items[1] sep items[2] sep  items[3]\n\t\t\titems := strings.Split(entry, string(os.PathSeparator))\n\t\t\tpid, err := strconv.Atoi(items[2])\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\n\t\t\treturn pid, nil\n\t\t}\n\t}\n\treturn 0, fmt.Errorf(\"Process %s not found in \/proc\", exename)\n}\n\nfunc pidExists(pid int) bool {\n\tpath := fmt.Sprintf(\"\/proc\/%d\/cmdline\", pid)\n\tif _, err := os.Stat(path); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package v7\n\nimport (\n\t\"code.cloudfoundry.org\/cli\/actor\/sharedaction\"\n\t\"code.cloudfoundry.org\/cli\/actor\/v7action\"\n\t\"code.cloudfoundry.org\/cli\/command\"\n\t\"code.cloudfoundry.org\/cli\/command\/flag\"\n\t\"code.cloudfoundry.org\/cli\/command\/v7\/shared\"\n\t\"code.cloudfoundry.org\/clock\"\n)\n\n\/\/go:generate counterfeiter . DeleteSpaceActor\n\ntype DeleteSpaceActor interface {\n\tDeleteSpaceByNameAndOrganizationName(spaceName string, orgName string) (v7action.Warnings, error)\n}\n\ntype DeleteSpaceCommand struct {\n\tRequiredArgs flag.Space  `positional-args:\"yes\"`\n\tForce        bool        `short:\"f\" description:\"Force deletion without confirmation\"`\n\tOrg          string      `short:\"o\" description:\"Delete space within specified org\"`\n\tusage        interface{} `usage:\"CF_NAME delete-space SPACE [-o ORG] [-f]\"`\n\n\tConfig      command.Config\n\tUI          command.UI\n\tSharedActor command.SharedActor\n\tActor       DeleteSpaceActor\n}\n\nfunc (cmd *DeleteSpaceCommand) Setup(config command.Config, ui command.UI) error {\n\tcmd.Config = config\n\tcmd.UI = ui\n\tsharedActor := sharedaction.NewActor(config)\n\tcmd.SharedActor = sharedActor\n\n\tccClient, uaaClient, err := shared.NewClients(config, ui, true, \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd.Actor = v7action.NewActor(ccClient, config, sharedActor, uaaClient, clock.NewClock())\n\n\treturn nil\n}\n\nfunc (cmd DeleteSpaceCommand) Execute(args []string) error {\n\tvar (\n\t\terr     error\n\t\torgName string\n\t)\n\n\tif cmd.Org == \"\" {\n\t\terr = cmd.SharedActor.CheckTarget(true, false)\n\t\torgName = cmd.Config.TargetedOrganization().Name\n\t} else {\n\t\terr = cmd.SharedActor.CheckTarget(false, false)\n\t\torgName = cmd.Org\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuser, err := cmd.Config.CurrentUser()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !cmd.Force {\n\t\tpromptMessage := \"This action impacts all resources scoped to this space, including apps, service instances, and space-scoped service brokers.\\nReally delete the space {{.SpaceName}}?\"\n\t\tdeleteSpace, promptErr := cmd.UI.DisplayBoolPrompt(false, promptMessage, map[string]interface{}{\"SpaceName\": cmd.RequiredArgs.Space})\n\n\t\tif promptErr != nil {\n\t\t\treturn promptErr\n\t\t}\n\n\t\tif !deleteSpace {\n\t\t\tcmd.UI.DisplayTextWithFlavor(\"'{{.TargetSpace}}' has not been deleted.\",\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"TargetSpace\": cmd.RequiredArgs.Space,\n\t\t\t\t})\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tcmd.UI.DisplayTextWithFlavor(\"Deleting space {{.TargetSpace}} in org {{.TargetOrg}} as {{.CurrentUser}}...\",\n\t\tmap[string]interface{}{\n\t\t\t\"TargetSpace\": cmd.RequiredArgs.Space,\n\t\t\t\"TargetOrg\":   orgName,\n\t\t\t\"CurrentUser\": user.Name,\n\t\t})\n\n\twarnings, err := cmd.Actor.DeleteSpaceByNameAndOrganizationName(cmd.RequiredArgs.Space, orgName)\n\tcmd.UI.DisplayWarnings(warnings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.UI.DisplayOK()\n\n\tif cmd.Config.TargetedOrganization().Name == orgName &&\n\t\tcmd.Config.TargetedSpace().Name == cmd.RequiredArgs.Space {\n\t\tcmd.Config.UnsetSpaceInformation()\n\t\tcmd.UI.DisplayText(\"TIP: No space targeted, use '{{.CfTargetCommand}}' to target a space.\",\n\t\t\tmap[string]interface{}{\"CfTargetCommand\": cmd.Config.BinaryName() + \" target -s\"})\n\t}\n\n\treturn nil\n}\n<commit_msg>Fix style errors in V7 delete-space command<commit_after>package v7\n\nimport (\n\t\"code.cloudfoundry.org\/cli\/actor\/sharedaction\"\n\t\"code.cloudfoundry.org\/cli\/actor\/v7action\"\n\t\"code.cloudfoundry.org\/cli\/command\"\n\t\"code.cloudfoundry.org\/cli\/command\/flag\"\n\t\"code.cloudfoundry.org\/cli\/command\/v7\/shared\"\n\t\"code.cloudfoundry.org\/clock\"\n)\n\n\/\/go:generate counterfeiter . DeleteSpaceActor\n\ntype DeleteSpaceActor interface {\n\tDeleteSpaceByNameAndOrganizationName(spaceName string, orgName string) (v7action.Warnings, error)\n}\n\ntype DeleteSpaceCommand struct {\n\tRequiredArgs flag.Space  `positional-args:\"yes\"`\n\tForce        bool        `short:\"f\" description:\"Force deletion without confirmation\"`\n\tOrg          string      `short:\"o\" description:\"Delete space within specified org\"`\n\tusage        interface{} `usage:\"CF_NAME delete-space SPACE [-o ORG] [-f]\"`\n\n\tConfig      command.Config\n\tUI          command.UI\n\tSharedActor command.SharedActor\n\tActor       DeleteSpaceActor\n}\n\nfunc (cmd *DeleteSpaceCommand) Setup(config command.Config, ui command.UI) error {\n\tcmd.Config = config\n\tcmd.UI = ui\n\tsharedActor := sharedaction.NewActor(config)\n\tcmd.SharedActor = sharedActor\n\n\tccClient, uaaClient, err := shared.NewClients(config, ui, true, \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd.Actor = v7action.NewActor(ccClient, config, sharedActor, uaaClient, clock.NewClock())\n\n\treturn nil\n}\n\nfunc (cmd DeleteSpaceCommand) Execute(args []string) error {\n\tvar (\n\t\terr     error\n\t\torgName string\n\t)\n\n\tif cmd.Org == \"\" {\n\t\terr = cmd.SharedActor.CheckTarget(true, false)\n\t\torgName = cmd.Config.TargetedOrganization().Name\n\t} else {\n\t\terr = cmd.SharedActor.CheckTarget(false, false)\n\t\torgName = cmd.Org\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuser, err := cmd.Config.CurrentUser()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !cmd.Force {\n\t\tcmd.UI.DisplayText(\"This action impacts all resources scoped to this space, including apps, service instances, and space-scoped service brokers.\")\n\t\tpromptMessage := \"Really delete the space {{.SpaceName}}?\"\n\t\tdeleteSpace, promptErr := cmd.UI.DisplayBoolPrompt(false, promptMessage, map[string]interface{}{\"SpaceName\": cmd.RequiredArgs.Space})\n\n\t\tif promptErr != nil {\n\t\t\treturn promptErr\n\t\t}\n\n\t\tif !deleteSpace {\n\t\t\tcmd.UI.DisplayText(\"'{{.TargetSpace}}' has not been deleted.\",\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"TargetSpace\": cmd.RequiredArgs.Space,\n\t\t\t\t})\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tcmd.UI.DisplayTextWithFlavor(\"Deleting space {{.TargetSpace}} in org {{.TargetOrg}} as {{.CurrentUser}}...\",\n\t\tmap[string]interface{}{\n\t\t\t\"TargetSpace\": cmd.RequiredArgs.Space,\n\t\t\t\"TargetOrg\":   orgName,\n\t\t\t\"CurrentUser\": user.Name,\n\t\t})\n\n\twarnings, err := cmd.Actor.DeleteSpaceByNameAndOrganizationName(cmd.RequiredArgs.Space, orgName)\n\tcmd.UI.DisplayWarnings(warnings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.UI.DisplayOK()\n\n\tif cmd.Config.TargetedOrganization().Name == orgName &&\n\t\tcmd.Config.TargetedSpace().Name == cmd.RequiredArgs.Space {\n\t\tcmd.Config.UnsetSpaceInformation()\n\t\tcmd.UI.DisplayText(\"TIP: No space targeted, use '{{.CfTargetCommand}}' to target a space.\",\n\t\t\tmap[string]interface{}{\"CfTargetCommand\": cmd.Config.BinaryName() + \" target -s\"})\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package parse\n\nimport \"errors\"\n\n\/\/ ErrBadSubstitution represents a substitution parsing error.\nvar ErrBadSubstitution = errors.New(\"bad substitution\")\n\n\/\/ Tree is the representation of a single parsed SQL statement.\ntype Tree struct {\n\tRoot Node\n\n\t\/\/ Parsing only; cleared after parse.\n\tscanner *scanner\n}\n\n\/\/ Parse parses the string and returns a Tree.\nfunc Parse(buf string) (*Tree, error) {\n\tt := new(Tree)\n\tt.scanner = new(scanner)\n\treturn t.Parse(buf)\n}\n\n\/\/ Parse parses the string buffer to construct an ast\n\/\/ representation for expansion.\nfunc (t *Tree) Parse(buf string) (tree *Tree, err error) {\n\tt.scanner.init(buf)\n\tt.Root, err = t.parseAny()\n\treturn t, err\n}\n\nfunc (t *Tree) parseAny() (Node, error) {\n\tt.scanner.accept = acceptRune\n\tt.scanner.mode = scanIdent | scanLbrack\n\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tleft := newTextNode(\n\t\t\tt.scanner.string(),\n\t\t)\n\t\tright, err := t.parseAny()\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\treturn nil, err\n\t\tcase right == empty:\n\t\t\treturn left, nil\n\t\t}\n\t\treturn newListNode(left, right), nil\n\tcase tokenEOF:\n\t\treturn empty, nil\n\tcase tokenLbrack:\n\t\tleft, err := t.parseFunc()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tright, err := t.parseAny()\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\treturn nil, err\n\t\tcase right == empty:\n\t\t\treturn left, nil\n\t\t}\n\t\treturn newListNode(left, right), nil\n\t}\n\n\treturn nil, ErrBadSubstitution\n}\n\nfunc (t *Tree) parseFunc() (Node, error) {\n\tswitch t.scanner.peek() {\n\tcase '#':\n\t\treturn t.parseLenFunc()\n\t}\n\n\tvar name string\n\tt.scanner.accept = acceptIdent\n\tt.scanner.mode = scanIdent\n\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tname = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\tswitch t.scanner.peek() {\n\tcase ':':\n\t\treturn t.parseDefaultOrSubstr(name)\n\tcase '=':\n\t\treturn t.parseDefaultFunc(name)\n\tcase ',', '^':\n\t\treturn t.parseCasingFunc(name)\n\tcase '\/':\n\t\treturn t.parseReplaceFunc(name)\n\tcase '#':\n\t\treturn t.parseRemoveFunc(name, acceptHashFunc)\n\tcase '%':\n\t\treturn t.parseRemoveFunc(name, acceptPercentFunc)\n\t}\n\n\tt.scanner.accept = acceptIdent\n\tt.scanner.mode = scanRbrack\n\tswitch t.scanner.scan() {\n\tcase tokenRbrack:\n\t\treturn newFuncNode(name), nil\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n}\n\n\/\/ parse a substitution function parameter.\nfunc (t *Tree) parseParam(accept acceptFunc, mode byte) (Node, error) {\n\tt.scanner.accept = accept\n\tt.scanner.mode = mode | scanLbrack\n\tswitch t.scanner.scan() {\n\tcase tokenLbrack:\n\t\treturn t.parseFunc()\n\tcase tokenIdent:\n\t\treturn newTextNode(\n\t\t\tt.scanner.string(),\n\t\t), nil\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n}\n\n\/\/ parse either a default or substring substitution function.\nfunc (t *Tree) parseDefaultOrSubstr(name string) (Node, error) {\n\tt.scanner.read()\n\tr := t.scanner.peek()\n\tt.scanner.unread()\n\tswitch r {\n\tcase '=', '-', '?', '+':\n\t\treturn t.parseDefaultFunc(name)\n\tdefault:\n\t\treturn t.parseSubstrFunc(name)\n\t}\n}\n\n\/\/ parses the ${param:offset} string function\n\/\/ parses the ${param:offset:length} string function\nfunc (t *Tree) parseSubstrFunc(name string) (Node, error) {\n\tnode := new(FuncNode)\n\tnode.Param = name\n\n\tt.scanner.accept = acceptOneColon\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Name = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\t\/\/ scan arg[1]\n\t{\n\t\tparam, err := t.parseParam(rejectColonClose, scanIdent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ param.Value = t.scanner.string()\n\t\tnode.Args = append(node.Args, param)\n\t}\n\n\t\/\/ expect delimiter or close\n\tt.scanner.accept = acceptColon\n\tt.scanner.mode = scanIdent | scanRbrack\n\tswitch t.scanner.scan() {\n\tcase tokenRbrack:\n\t\treturn node, nil\n\tcase tokenIdent:\n\t\t\/\/ no-op\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\t\/\/ err := t.consumeDelimiter(acceptColon, scanIdent|scanRbrack)\n\t\/\/ if err != nil {\n\t\/\/ \treturn nil, err\n\t\/\/ }\n\n\t\/\/ scan arg[2]\n\t{\n\t\tparam, err := t.parseParam(acceptNotClosing, scanIdent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnode.Args = append(node.Args, param)\n\t}\n\n\treturn node, t.consumeRbrack()\n}\n\n\/\/ parses the ${param%word} string function\n\/\/ parses the ${param%%word} string function\n\/\/ parses the ${param#word} string function\n\/\/ parses the ${param##word} string function\nfunc (t *Tree) parseRemoveFunc(name string, accept acceptFunc) (Node, error) {\n\tnode := new(FuncNode)\n\tnode.Param = name\n\n\tt.scanner.accept = accept\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Name = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\t\/\/ scan arg[1]\n\t{\n\t\tparam, err := t.parseParam(acceptNotClosing, scanIdent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ param.Value = t.scanner.string()\n\t\tnode.Args = append(node.Args, param)\n\t}\n\n\treturn node, t.consumeRbrack()\n}\n\n\/\/ parses the ${param\/pattern\/string} string function\n\/\/ parses the ${param\/\/pattern\/string} string function\n\/\/ parses the ${param\/#pattern\/string} string function\n\/\/ parses the ${param\/%pattern\/string} string function\nfunc (t *Tree) parseReplaceFunc(name string) (Node, error) {\n\tnode := new(FuncNode)\n\tnode.Param = name\n\n\tt.scanner.accept = acceptReplaceFunc\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Name = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\t\/\/ scan arg[1]\n\t{\n\t\tparam, err := t.parseParam(acceptNotSlash, scanIdent|scanEscape)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnode.Args = append(node.Args, param)\n\t}\n\n\t\/\/ expect delimiter\n\tt.scanner.accept = acceptSlash\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\t\/\/ no-op\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\t{\n\t\tparam, err := t.parseParam(acceptNotClosing, scanIdent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnode.Args = append(node.Args, param)\n\t}\n\n\treturn node, t.consumeRbrack()\n}\n\n\/\/ parses the ${parameter=word} string function\n\/\/ parses the ${parameter:=word} string function\n\/\/ parses the ${parameter:-word} string function\n\/\/ parses the ${parameter:?word} string function\n\/\/ parses the ${parameter:+word} string function\nfunc (t *Tree) parseDefaultFunc(name string) (Node, error) {\n\tnode := new(FuncNode)\n\tnode.Param = name\n\n\tt.scanner.accept = acceptDefaultFunc\n\tif t.scanner.peek() == '=' {\n\t\tt.scanner.accept = acceptOneEqual\n\t}\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Name = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\t\/\/ scan arg[1]\n\t{\n\t\tparam, err := t.parseParam(acceptNotClosing, scanIdent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ param.Value = t.scanner.string()\n\t\tnode.Args = append(node.Args, param)\n\t}\n\n\treturn node, t.consumeRbrack()\n}\n\n\/\/ parses the ${param,} string function\n\/\/ parses the ${param,,} string function\n\/\/ parses the ${param^} string function\n\/\/ parses the ${param^^} string function\nfunc (t *Tree) parseCasingFunc(name string) (Node, error) {\n\tnode := new(FuncNode)\n\tnode.Param = name\n\n\tt.scanner.accept = acceptCasingFunc\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Name = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\treturn node, t.consumeRbrack()\n}\n\n\/\/ parses the ${#param} string function\nfunc (t *Tree) parseLenFunc() (Node, error) {\n\tnode := new(FuncNode)\n\n\tt.scanner.accept = acceptOneHash\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Name = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\tt.scanner.accept = acceptIdent\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Param = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\treturn node, t.consumeRbrack()\n}\n\n\/\/ consumeRbrack consumes a right closing bracket. If a closing\n\/\/ bracket token is not consumed an ErrBadSubstitution is returned.\nfunc (t *Tree) consumeRbrack() error {\n\tt.scanner.mode = scanRbrack\n\tif t.scanner.scan() != tokenRbrack {\n\t\treturn ErrBadSubstitution\n\t}\n\treturn nil\n}\n\n\/\/ consumeDelimiter consumes a function argument delimiter. If a\n\/\/ delimiter is not consumed an ErrBadSubstitution is returned.\n\/\/ func (t *Tree) consumeDelimiter(accept acceptFunc, mode uint) error {\n\/\/ \tt.scanner.accept = accept\n\/\/ \tt.scanner.mode = mode\n\/\/ \tif t.scanner.scan() != tokenRbrack {\n\/\/ \t\treturn ErrBadSubstitution\n\/\/ \t}\n\/\/ \treturn nil\n\/\/ }\n<commit_msg>Add escape to initial scanner mode<commit_after>package parse\n\nimport \"errors\"\n\n\/\/ ErrBadSubstitution represents a substitution parsing error.\nvar ErrBadSubstitution = errors.New(\"bad substitution\")\n\n\/\/ Tree is the representation of a single parsed SQL statement.\ntype Tree struct {\n\tRoot Node\n\n\t\/\/ Parsing only; cleared after parse.\n\tscanner *scanner\n}\n\n\/\/ Parse parses the string and returns a Tree.\nfunc Parse(buf string) (*Tree, error) {\n\tt := new(Tree)\n\tt.scanner = new(scanner)\n\treturn t.Parse(buf)\n}\n\n\/\/ Parse parses the string buffer to construct an ast\n\/\/ representation for expansion.\nfunc (t *Tree) Parse(buf string) (tree *Tree, err error) {\n\tt.scanner.init(buf)\n\tt.Root, err = t.parseAny()\n\treturn t, err\n}\n\nfunc (t *Tree) parseAny() (Node, error) {\n\tt.scanner.accept = acceptRune\n\tt.scanner.mode = scanIdent | scanLbrack | scanEscape\n\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tleft := newTextNode(\n\t\t\tt.scanner.string(),\n\t\t)\n\t\tright, err := t.parseAny()\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\treturn nil, err\n\t\tcase right == empty:\n\t\t\treturn left, nil\n\t\t}\n\t\treturn newListNode(left, right), nil\n\tcase tokenEOF:\n\t\treturn empty, nil\n\tcase tokenLbrack:\n\t\tleft, err := t.parseFunc()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tright, err := t.parseAny()\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\treturn nil, err\n\t\tcase right == empty:\n\t\t\treturn left, nil\n\t\t}\n\t\treturn newListNode(left, right), nil\n\t}\n\n\treturn nil, ErrBadSubstitution\n}\n\nfunc (t *Tree) parseFunc() (Node, error) {\n\tswitch t.scanner.peek() {\n\tcase '#':\n\t\treturn t.parseLenFunc()\n\t}\n\n\tvar name string\n\tt.scanner.accept = acceptIdent\n\tt.scanner.mode = scanIdent\n\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tname = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\tswitch t.scanner.peek() {\n\tcase ':':\n\t\treturn t.parseDefaultOrSubstr(name)\n\tcase '=':\n\t\treturn t.parseDefaultFunc(name)\n\tcase ',', '^':\n\t\treturn t.parseCasingFunc(name)\n\tcase '\/':\n\t\treturn t.parseReplaceFunc(name)\n\tcase '#':\n\t\treturn t.parseRemoveFunc(name, acceptHashFunc)\n\tcase '%':\n\t\treturn t.parseRemoveFunc(name, acceptPercentFunc)\n\t}\n\n\tt.scanner.accept = acceptIdent\n\tt.scanner.mode = scanRbrack\n\tswitch t.scanner.scan() {\n\tcase tokenRbrack:\n\t\treturn newFuncNode(name), nil\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n}\n\n\/\/ parse a substitution function parameter.\nfunc (t *Tree) parseParam(accept acceptFunc, mode byte) (Node, error) {\n\tt.scanner.accept = accept\n\tt.scanner.mode = mode | scanLbrack\n\tswitch t.scanner.scan() {\n\tcase tokenLbrack:\n\t\treturn t.parseFunc()\n\tcase tokenIdent:\n\t\treturn newTextNode(\n\t\t\tt.scanner.string(),\n\t\t), nil\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n}\n\n\/\/ parse either a default or substring substitution function.\nfunc (t *Tree) parseDefaultOrSubstr(name string) (Node, error) {\n\tt.scanner.read()\n\tr := t.scanner.peek()\n\tt.scanner.unread()\n\tswitch r {\n\tcase '=', '-', '?', '+':\n\t\treturn t.parseDefaultFunc(name)\n\tdefault:\n\t\treturn t.parseSubstrFunc(name)\n\t}\n}\n\n\/\/ parses the ${param:offset} string function\n\/\/ parses the ${param:offset:length} string function\nfunc (t *Tree) parseSubstrFunc(name string) (Node, error) {\n\tnode := new(FuncNode)\n\tnode.Param = name\n\n\tt.scanner.accept = acceptOneColon\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Name = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\t\/\/ scan arg[1]\n\t{\n\t\tparam, err := t.parseParam(rejectColonClose, scanIdent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ param.Value = t.scanner.string()\n\t\tnode.Args = append(node.Args, param)\n\t}\n\n\t\/\/ expect delimiter or close\n\tt.scanner.accept = acceptColon\n\tt.scanner.mode = scanIdent | scanRbrack\n\tswitch t.scanner.scan() {\n\tcase tokenRbrack:\n\t\treturn node, nil\n\tcase tokenIdent:\n\t\t\/\/ no-op\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\t\/\/ err := t.consumeDelimiter(acceptColon, scanIdent|scanRbrack)\n\t\/\/ if err != nil {\n\t\/\/ \treturn nil, err\n\t\/\/ }\n\n\t\/\/ scan arg[2]\n\t{\n\t\tparam, err := t.parseParam(acceptNotClosing, scanIdent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnode.Args = append(node.Args, param)\n\t}\n\n\treturn node, t.consumeRbrack()\n}\n\n\/\/ parses the ${param%word} string function\n\/\/ parses the ${param%%word} string function\n\/\/ parses the ${param#word} string function\n\/\/ parses the ${param##word} string function\nfunc (t *Tree) parseRemoveFunc(name string, accept acceptFunc) (Node, error) {\n\tnode := new(FuncNode)\n\tnode.Param = name\n\n\tt.scanner.accept = accept\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Name = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\t\/\/ scan arg[1]\n\t{\n\t\tparam, err := t.parseParam(acceptNotClosing, scanIdent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ param.Value = t.scanner.string()\n\t\tnode.Args = append(node.Args, param)\n\t}\n\n\treturn node, t.consumeRbrack()\n}\n\n\/\/ parses the ${param\/pattern\/string} string function\n\/\/ parses the ${param\/\/pattern\/string} string function\n\/\/ parses the ${param\/#pattern\/string} string function\n\/\/ parses the ${param\/%pattern\/string} string function\nfunc (t *Tree) parseReplaceFunc(name string) (Node, error) {\n\tnode := new(FuncNode)\n\tnode.Param = name\n\n\tt.scanner.accept = acceptReplaceFunc\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Name = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\t\/\/ scan arg[1]\n\t{\n\t\tparam, err := t.parseParam(acceptNotSlash, scanIdent|scanEscape)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnode.Args = append(node.Args, param)\n\t}\n\n\t\/\/ expect delimiter\n\tt.scanner.accept = acceptSlash\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\t\/\/ no-op\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\t{\n\t\tparam, err := t.parseParam(acceptNotClosing, scanIdent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnode.Args = append(node.Args, param)\n\t}\n\n\treturn node, t.consumeRbrack()\n}\n\n\/\/ parses the ${parameter=word} string function\n\/\/ parses the ${parameter:=word} string function\n\/\/ parses the ${parameter:-word} string function\n\/\/ parses the ${parameter:?word} string function\n\/\/ parses the ${parameter:+word} string function\nfunc (t *Tree) parseDefaultFunc(name string) (Node, error) {\n\tnode := new(FuncNode)\n\tnode.Param = name\n\n\tt.scanner.accept = acceptDefaultFunc\n\tif t.scanner.peek() == '=' {\n\t\tt.scanner.accept = acceptOneEqual\n\t}\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Name = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\t\/\/ scan arg[1]\n\t{\n\t\tparam, err := t.parseParam(acceptNotClosing, scanIdent)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ param.Value = t.scanner.string()\n\t\tnode.Args = append(node.Args, param)\n\t}\n\n\treturn node, t.consumeRbrack()\n}\n\n\/\/ parses the ${param,} string function\n\/\/ parses the ${param,,} string function\n\/\/ parses the ${param^} string function\n\/\/ parses the ${param^^} string function\nfunc (t *Tree) parseCasingFunc(name string) (Node, error) {\n\tnode := new(FuncNode)\n\tnode.Param = name\n\n\tt.scanner.accept = acceptCasingFunc\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Name = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\treturn node, t.consumeRbrack()\n}\n\n\/\/ parses the ${#param} string function\nfunc (t *Tree) parseLenFunc() (Node, error) {\n\tnode := new(FuncNode)\n\n\tt.scanner.accept = acceptOneHash\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Name = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\tt.scanner.accept = acceptIdent\n\tt.scanner.mode = scanIdent\n\tswitch t.scanner.scan() {\n\tcase tokenIdent:\n\t\tnode.Param = t.scanner.string()\n\tdefault:\n\t\treturn nil, ErrBadSubstitution\n\t}\n\n\treturn node, t.consumeRbrack()\n}\n\n\/\/ consumeRbrack consumes a right closing bracket. If a closing\n\/\/ bracket token is not consumed an ErrBadSubstitution is returned.\nfunc (t *Tree) consumeRbrack() error {\n\tt.scanner.mode = scanRbrack\n\tif t.scanner.scan() != tokenRbrack {\n\t\treturn ErrBadSubstitution\n\t}\n\treturn nil\n}\n\n\/\/ consumeDelimiter consumes a function argument delimiter. If a\n\/\/ delimiter is not consumed an ErrBadSubstitution is returned.\n\/\/ func (t *Tree) consumeDelimiter(accept acceptFunc, mode uint) error {\n\/\/ \tt.scanner.accept = accept\n\/\/ \tt.scanner.mode = mode\n\/\/ \tif t.scanner.scan() != tokenRbrack {\n\/\/ \t\treturn ErrBadSubstitution\n\/\/ \t}\n\/\/ \treturn nil\n\/\/ }\n<|endoftext|>"}
{"text":"<commit_before>\/\/ go-rst - A reStructuredText parser for Go\n\/\/ 2014 (c) The go-rst Authors\n\/\/ MIT Licensed. See LICENSE for details.\n\npackage parse\n\nimport (\n\t\"code.google.com\/p\/go.text\/unicode\/norm\"\n\t\"fmt\"\n\t\"github.com\/demizer\/go-elog\"\n\t\"github.com\/demizer\/go-spew\/spew\"\n\t\"reflect\"\n)\n\nvar spd = spew.ConfigState{Indent: \"\\t\", DisableMethods: true}\n\ntype systemMessageLevel int\n\nconst (\n\tlevelInfo systemMessageLevel = iota\n\tlevelWarning\n\tlevelError\n\tlevelSevere\n)\n\nvar systemMessageLevels = [...]string{\n\t\"INFO\",\n\t\"WARNING\",\n\t\"ERROR\",\n\t\"SEVERE\",\n}\n\nfunc (s systemMessageLevel) String() string {\n\treturn systemMessageLevels[s]\n}\n\ntype parserMessage int\n\nconst (\n\twarningShortUnderline parserMessage = iota\n\terrorUnexpectedSectionTitle\n\terrorUnexpectedSectionTitleOrTransition\n)\n\nvar parserErrors = [...]string{\n\t\"warningShortUnderline\",\n\t\"errorUnexpectedSectionTitle\",\n\t\"errorUnexpectedSectionTitleOrTransition\",\n}\n\nfunc (p parserMessage) String() string {\n\treturn parserErrors[p]\n}\n\nfunc (p parserMessage) Message() (s string) {\n\tswitch p {\n\tcase warningShortUnderline:\n\t\ts = \"Title underline too short.\"\n\tcase errorUnexpectedSectionTitle:\n\t\ts = \"Unexpected section title.\"\n\tcase errorUnexpectedSectionTitleOrTransition:\n\t\ts = \"Unexpected section title or transition.\"\n\t}\n\treturn\n}\n\nfunc (p parserMessage) Level() (s systemMessageLevel) {\n\tswitch p {\n\tcase warningShortUnderline:\n\t\ts = levelWarning\n\tcase errorUnexpectedSectionTitle:\n\t\ts = levelSevere\n\tcase errorUnexpectedSectionTitleOrTransition:\n\t\ts = levelSevere\n\t}\n\treturn\n}\n\ntype sectionLevels []*SectionNode\n\nfunc (s *sectionLevels) String() string {\n\tvar out string\n\tfor _, sec := range *s {\n\t\tout += fmt.Sprintf(\"level: %d, rune: %q, overline: %t, length: %d\\n\",\n\t\t\tsec.Level, sec.UnderLine.Rune, sec.OverLine != nil, sec.Length)\n\t}\n\treturn out\n}\n\n\/\/ Returns nil if not found\nfunc (s *sectionLevels) FindByRune(adornChar rune) *SectionNode {\n\tfor _, sec := range *s {\n\t\tif sec.UnderLine.Rune == adornChar {\n\t\t\treturn sec\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ If exists == true, a section node with the same text and underline has been found in\n\/\/ sectionLevels, sec is the matching SectionNode. If exists == false, then the sec return value is\n\/\/ the similarly leveled SectionNode. If exists == false and sec == nil, then the SectionNode added\n\/\/ to sectionLevels is a new Node.\nfunc (s *sectionLevels) Add(section *SectionNode) (exists bool, sec *SectionNode) {\n\tsec = s.FindByRune(section.UnderLine.Rune)\n\tif sec != nil {\n\t\tif sec.Text == section.Text {\n\t\t\treturn true, sec\n\t\t} else if sec.Text != section.Text {\n\t\t\tsection.Level = sec.Level\n\t\t}\n\t} else {\n\t\tsection.Level = len(*s) + 1\n\t}\n\texists = false\n\t*s = append(*s, section)\n\treturn\n}\n\nfunc (s *sectionLevels) Level() int {\n\treturn len(*s)\n}\n\n\/\/ Parse is the entry point for the reStructuredText parser.\nfunc Parse(name, text string) (t *Tree, errors []error) {\n\tt = New(name)\n\tif !norm.NFC.IsNormalString(text) {\n\t\ttext = norm.NFC.String(text)\n\t}\n\tt.text = text\n\t_, errors = t.Parse(text, t)\n\treturn\n}\n\nfunc New(name string) *Tree {\n\treturn &Tree{\n\t\tName:          name,\n\t\tNodes:         newList(),\n\t\tnodeTarget:    newList(),\n\t\tsectionLevels: new(sectionLevels),\n\t\tindentWidth:   indentWidth,\n\t}\n}\n\nconst (\n\ttokenZero   = 3\n\tindentWidth = 4 \/\/ Default indent width\n)\n\ntype Tree struct {\n\tName             string\n\tNodes            *NodeList \/\/ The root node list\n\tnodeTarget       *NodeList \/\/ Used by the parser to add nodes to a target NodeList\n\tErrors           []error\n\ttext             string\n\tlex              *lexer\n\ttokenBackupCount int\n\ttokenPeekCount   int\n\ttoken            [7]*item\n\tsectionLevels    *sectionLevels \/\/ Encountered section levels\n\tid               int            \/\/ The unique id of the node in the tree\n\tindentWidth      int\n\tindentLevel      int\n}\n\nfunc (t *Tree) errorf(format string, args ...interface{}) {\n\tformat = fmt.Sprintf(\"go-rst: %s:%d: %s\\n\", t.Name, t.lex.lineNumber(), format)\n\tt.Errors = append(t.Errors, fmt.Errorf(format, args...))\n}\n\nfunc (t *Tree) error(err error) {\n\tt.errorf(\"%s\\n\", err)\n}\n\n\/\/ startParse initializes the parser, using the lexer.\nfunc (t *Tree) startParse(lex *lexer) {\n\tt.lex = lex\n}\n\n\/\/ stopParse terminates parsing.\nfunc (t *Tree) stopParse() {\n\tt.Nodes = nil\n\tt.nodeTarget = nil\n\tt.lex = nil\n}\n\nfunc (t *Tree) Parse(text string, treeSet *Tree) (tree *Tree, errors []error) {\n\tlog.Debugln(\"Start\")\n\tt.startParse(lex(t.Name, text))\n\tt.text = text\n\tt.parse(treeSet)\n\tlog.Debugln(\"End\")\n\treturn t, t.Errors\n}\n\nfunc (t *Tree) parse(tree *Tree) {\n\tlog.Debugln(\"Start\")\n\n\tt.nodeTarget = t.Nodes\n\n\tfor t.peek(1).Type != itemEOF {\n\t\tvar n Node\n\n\t\ttoken := t.next()\n\t\tlog.Infof(\"\\nParser got token: %#+v\\n\\n\", token)\n\n\t\tswitch token.Type {\n\t\tcase itemSectionAdornment:\n\t\t\tn = t.section(token)\n\t\tcase itemParagraph:\n\t\t\tn = newParagraph(token, &t.id)\n\t\tcase itemSpace:\n\t\t\tn = t.indent(token)\n\t\t\tif n == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase itemTitle, itemBlankLine:\n\t\t\t\/\/ itemTitle is consumed when evaluating itemSectionAdornment\n\t\t\tcontinue\n\t\tcase itemEOF:\n\t\t\tgoto exit\n\t\tdefault:\n\t\t\tt.errorf(\"%q Not implemented!\", token.Type)\n\t\t\tcontinue\n\t\t}\n\n\t\tt.nodeTarget.append(n)\n\t\tswitch n.NodeType() {\n\t\tcase NodeSection, NodeBlockQuote:\n\t\t\t\/\/ Set the loop to append items to the NodeList of the new section\n\t\t\tt.nodeTarget = reflect.ValueOf(n).Elem().FieldByName(\"NodeList\").Addr().Interface().(*NodeList)\n\t\t}\n\t}\n\n\texit:\n\tlog.Debugln(\"End\")\n}\n\nfunc (t *Tree) backup() *item {\n\tt.tokenBackupCount++\n\t\/\/ log.Debugln(\"t.tokenBackupCount:\", t.tokenPeekCount)\n\tfor i := len(t.token) - 1; i > 0; i-- {\n\t\tt.token[i] = t.token[i-1]\n\t\tt.token[i-1] = nil\n\t}\n\t\/\/ log.Debugf(\"\\n##### backup() aftermath #####\\n\\n\")\n\t\/\/ spd.Dump(t.token)\n\treturn t.token[tokenZero-t.tokenBackupCount]\n}\n\nfunc (t *Tree) peekBack(pos int) *item {\n\treturn t.token[tokenZero-pos]\n}\n\nfunc (t *Tree) peek(pos int) *item {\n\t\/\/ log.Debugln(\"t.tokenPeekCount:\", t.tokenPeekCount, \"Pos:\", pos)\n\tif pos < 1 {\n\t\tpanic(\"pos cannot be < 1\")\n\t}\n\tvar nItem *item\n\tfor i := 0; i < pos; i++ {\n\t\t\/\/ log.Debugln(\"i:\", i, \"peekCount:\", t.tokenPeekCount, \"pos:\", pos)\n\t\tif t.tokenPeekCount > i {\n\t\t\tnItem = t.token[tokenZero+i]\n\t\t\tlog.Debugf(\"Using %#+v\\n\", nItem)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Debugln(tokenZero + t.tokenPeekCount + i)\n\t\tif t.token[tokenZero + t.tokenPeekCount + i + 1] == nil {\n\t\t\tt.tokenPeekCount++\n\t\t\t\/\/ log.Debugln(\"Getting next item\")\n\t\t\tt.token[tokenZero+t.tokenPeekCount+i] = t.lex.nextItem()\n\t\t\tnItem = t.token[tokenZero+t.tokenPeekCount+i]\n\t\t} else {\n\t\t\tnItem = t.token[tokenZero+t.tokenPeekCount+i]\n\t\t}\n\t}\n\t\/\/ log.Debugf(\"\\n##### peek() aftermath #####\\n\\n\")\n\t\/\/ spd.Dump(t.token)\n\t\/\/ log.Debugf(\"Returning: %#+v\\n\", nItem)\n\treturn nItem\n}\n\n\/\/ skip shifts the pointers left in t.token, pos is the amount to shift\nfunc (t *Tree) skip(num int) {\n\tfor i := num; i > 0; i-- {\n\t\tfor x := 0; x < len(t.token)-1; x++ {\n\t\t\tt.token[x] = t.token[x+1]\n\t\t\tt.token[x+1] = nil\n\t\t}\n\t}\n}\n\nfunc (t *Tree) next() *item {\n\t\/\/ log.Debugln(\"t.tokenPeekCount:\", t.tokenPeekCount)\n\tif t.tokenPeekCount > 0 {\n\t\tt.skip(t.tokenPeekCount)\n\t} else {\n\t\tt.skip(1)\n\t\tt.token[tokenZero] = t.lex.nextItem()\n\t}\n\tt.tokenBackupCount, t.tokenPeekCount = 0, 0\n\t\/\/ log.Debugf(\"\\n##### next() aftermath #####\\n\\n\")\n\t\/\/ spd.Dump(t.token)\n\treturn t.token[tokenZero]\n}\n\nfunc (t *Tree) section(i *item) Node {\n\tlog.Debugln(\"Start\")\n\tvar overAdorn, title, underAdorn *item\n\tvar overline bool\n\tvar sysMessage Node\n\n\tpeekBack := t.peekBack(1)\n\tif peekBack != nil {\n\t\tif peekBack.Type == itemSpace {\n\t\t\t\/\/ Looking back past the white space\n\t\t\tif t.peekBack(2).Type == itemTitle {\n\t\t\t\treturn t.systemMessage(errorUnexpectedSectionTitle)\n\t\t\t}\n\t\t\treturn t.systemMessage(errorUnexpectedSectionTitleOrTransition)\n\t\t} else if peekBack.Type == itemTitle {\n\t\t\tif t.peekBack(2) != nil && t.peekBack(2).Type == itemSectionAdornment {\n\t\t\t\t\/\/ The overline of the section\n\t\t\t\toverline = true\n\t\t\t\toverAdorn = peekBack\n\t\t\t}\n\t\t}\n\t}\n\n\ttitle = t.peekBack(1)\n\tunderAdorn = i\n\n\t\/\/ TODO: Change these into proper error messages!\n\t\/\/ Check adornment for proper syntax\n\tif underAdorn.Type == itemSpace {\n\t\tt.backup() \/\/ Put the parser back on the title\n\t\treturn t.systemMessage(errorUnexpectedSectionTitle)\n\t} else if overline && title.Length != overAdorn.Length {\n\t\tt.errorf(\"Section over line not equal to title length!\")\n\t} else if overline && overAdorn.Text != underAdorn.Text {\n\t\tt.errorf(\"Section title over line does not match section title under line.\")\n\t}\n\n\tsec := newSection(title, overAdorn, underAdorn, &t.id)\n\texists, eSec := t.sectionLevels.Add(sec)\n\tif exists && eSec != nil {\n\t\tt.errorf(\"SectionNode using Text \\\"%s\\\" and Rune '%s' was previously parsed!\",\n\t\t\tsec.Text, string(sec.UnderLine.Rune))\n\t} else if !exists && eSec != nil {\n\t\t\/\/ There is a matching level in sectionLevels\n\t\tt.nodeTarget = &(*t.sectionLevels)[sec.Level-2].NodeList\n\t}\n\n\t\/\/ System messages have to be applied after the section is created in order to preserve\n\t\/\/ a consecutive id number.\n\tif title.Length != underAdorn.Length {\n\t\tsysMessage = t.systemMessage(warningShortUnderline)\n\t\tsec.NodeList = append(sec.NodeList, sysMessage)\n\t}\n\n\tlog.Debugln(\"End\")\n\treturn sec\n}\n\nfunc (t *Tree) systemMessage(err parserMessage) Node {\n\tvar lbText string\n\tvar lbTextLen int\n\tvar backToken int\n\n\ts := newSystemMessage(&item{\n\t\tType: itemSystemMessage,\n\t\tLine: t.token[tokenZero].Line,\n\t},\n\t\terr.Level(), &t.id)\n\n\tmsg := newParagraph(&item{\n\t\tText:   err.Message(),\n\t\tLength: len(err.Message()),\n\t}, &t.id)\n\n\tswitch err {\n\tcase warningShortUnderline, errorUnexpectedSectionTitle:\n\t\tlog.Debugln(\"FOUND\", err)\n\t\tbackToken = tokenZero - 1\n\t\tif t.peekBack(1).Type == itemSpace {\n\t\t\tbackToken = tokenZero - 2\n\t\t}\n\t\tlbText = t.token[backToken].Text.(string) + \"\\n\" + t.token[tokenZero].Text.(string)\n\t\tlbTextLen = len(lbText) + 1\n\tcase errorUnexpectedSectionTitleOrTransition:\n\t\tlog.Debugln(\"FOUND errorUnexpectedSectionTitleOrTransition\")\n\t\tlbText = t.token[tokenZero].Text.(string)\n\t\tlbTextLen = len(lbText)\n\t}\n\n\tlb := newLiteralBlock(&item{\n\t\tType:   itemLiteralBlock,\n\t\tText:   lbText,\n\t\tLength: lbTextLen, \/\/ Add one to account for the backslash\n\t}, &t.id)\n\n\ts.NodeList = append(s.NodeList, msg, lb)\n\treturn s\n}\n\nfunc (t *Tree) indent(i *item) Node {\n\tlevel := i.Length \/ t.indentWidth\n\tif t.peekBack(1).Type == itemBlankLine {\n\t\tif t.indentLevel == level {\n\t\t\t\/\/ Append to the current blockquote NodeList\n\t\t\treturn nil\n\t\t}\n\t\tt.indentLevel = level\n\t\treturn newBlockQuote(&item{Type: itemBlockquote, Line: i.Line}, level, &t.id)\n\t}\n\treturn nil\n}\n<commit_msg>parse.go: Move skip() back into next()<commit_after>\/\/ go-rst - A reStructuredText parser for Go\n\/\/ 2014 (c) The go-rst Authors\n\/\/ MIT Licensed. See LICENSE for details.\n\npackage parse\n\nimport (\n\t\"code.google.com\/p\/go.text\/unicode\/norm\"\n\t\"fmt\"\n\t\"github.com\/demizer\/go-elog\"\n\t\"github.com\/demizer\/go-spew\/spew\"\n\t\"reflect\"\n)\n\nvar spd = spew.ConfigState{Indent: \"\\t\", DisableMethods: true}\n\ntype systemMessageLevel int\n\nconst (\n\tlevelInfo systemMessageLevel = iota\n\tlevelWarning\n\tlevelError\n\tlevelSevere\n)\n\nvar systemMessageLevels = [...]string{\n\t\"INFO\",\n\t\"WARNING\",\n\t\"ERROR\",\n\t\"SEVERE\",\n}\n\nfunc (s systemMessageLevel) String() string {\n\treturn systemMessageLevels[s]\n}\n\ntype parserMessage int\n\nconst (\n\twarningShortUnderline parserMessage = iota\n\terrorUnexpectedSectionTitle\n\terrorUnexpectedSectionTitleOrTransition\n)\n\nvar parserErrors = [...]string{\n\t\"warningShortUnderline\",\n\t\"errorUnexpectedSectionTitle\",\n\t\"errorUnexpectedSectionTitleOrTransition\",\n}\n\nfunc (p parserMessage) String() string {\n\treturn parserErrors[p]\n}\n\nfunc (p parserMessage) Message() (s string) {\n\tswitch p {\n\tcase warningShortUnderline:\n\t\ts = \"Title underline too short.\"\n\tcase errorUnexpectedSectionTitle:\n\t\ts = \"Unexpected section title.\"\n\tcase errorUnexpectedSectionTitleOrTransition:\n\t\ts = \"Unexpected section title or transition.\"\n\t}\n\treturn\n}\n\nfunc (p parserMessage) Level() (s systemMessageLevel) {\n\tswitch p {\n\tcase warningShortUnderline:\n\t\ts = levelWarning\n\tcase errorUnexpectedSectionTitle:\n\t\ts = levelSevere\n\tcase errorUnexpectedSectionTitleOrTransition:\n\t\ts = levelSevere\n\t}\n\treturn\n}\n\ntype sectionLevels []*SectionNode\n\nfunc (s *sectionLevels) String() string {\n\tvar out string\n\tfor _, sec := range *s {\n\t\tout += fmt.Sprintf(\"level: %d, rune: %q, overline: %t, length: %d\\n\",\n\t\t\tsec.Level, sec.UnderLine.Rune, sec.OverLine != nil, sec.Length)\n\t}\n\treturn out\n}\n\n\/\/ Returns nil if not found\nfunc (s *sectionLevels) FindByRune(adornChar rune) *SectionNode {\n\tfor _, sec := range *s {\n\t\tif sec.UnderLine.Rune == adornChar {\n\t\t\treturn sec\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ If exists == true, a section node with the same text and underline has been found in\n\/\/ sectionLevels, sec is the matching SectionNode. If exists == false, then the sec return value is\n\/\/ the similarly leveled SectionNode. If exists == false and sec == nil, then the SectionNode added\n\/\/ to sectionLevels is a new Node.\nfunc (s *sectionLevels) Add(section *SectionNode) (exists bool, sec *SectionNode) {\n\tsec = s.FindByRune(section.UnderLine.Rune)\n\tif sec != nil {\n\t\tif sec.Text == section.Text {\n\t\t\treturn true, sec\n\t\t} else if sec.Text != section.Text {\n\t\t\tsection.Level = sec.Level\n\t\t}\n\t} else {\n\t\tsection.Level = len(*s) + 1\n\t}\n\texists = false\n\t*s = append(*s, section)\n\treturn\n}\n\nfunc (s *sectionLevels) Level() int {\n\treturn len(*s)\n}\n\n\/\/ Parse is the entry point for the reStructuredText parser.\nfunc Parse(name, text string) (t *Tree, errors []error) {\n\tt = New(name)\n\tif !norm.NFC.IsNormalString(text) {\n\t\ttext = norm.NFC.String(text)\n\t}\n\tt.text = text\n\t_, errors = t.Parse(text, t)\n\treturn\n}\n\nfunc New(name string) *Tree {\n\treturn &Tree{\n\t\tName:          name,\n\t\tNodes:         newList(),\n\t\tnodeTarget:    newList(),\n\t\tsectionLevels: new(sectionLevels),\n\t\tindentWidth:   indentWidth,\n\t}\n}\n\nconst (\n\ttokenZero   = 3\n\tindentWidth = 4 \/\/ Default indent width\n)\n\ntype Tree struct {\n\tName             string\n\tNodes            *NodeList \/\/ The root node list\n\tnodeTarget       *NodeList \/\/ Used by the parser to add nodes to a target NodeList\n\tErrors           []error\n\ttext             string\n\tlex              *lexer\n\ttokenBackupCount int\n\ttokenPeekCount   int\n\ttoken            [7]*item\n\tsectionLevels    *sectionLevels \/\/ Encountered section levels\n\tid               int            \/\/ The unique id of the node in the tree\n\tindentWidth      int\n\tindentLevel      int\n}\n\nfunc (t *Tree) errorf(format string, args ...interface{}) {\n\tformat = fmt.Sprintf(\"go-rst: %s:%d: %s\\n\", t.Name, t.lex.lineNumber(), format)\n\tt.Errors = append(t.Errors, fmt.Errorf(format, args...))\n}\n\nfunc (t *Tree) error(err error) {\n\tt.errorf(\"%s\\n\", err)\n}\n\n\/\/ startParse initializes the parser, using the lexer.\nfunc (t *Tree) startParse(lex *lexer) {\n\tt.lex = lex\n}\n\n\/\/ stopParse terminates parsing.\nfunc (t *Tree) stopParse() {\n\tt.Nodes = nil\n\tt.nodeTarget = nil\n\tt.lex = nil\n}\n\nfunc (t *Tree) Parse(text string, treeSet *Tree) (tree *Tree, errors []error) {\n\tlog.Debugln(\"Start\")\n\tt.startParse(lex(t.Name, text))\n\tt.text = text\n\tt.parse(treeSet)\n\tlog.Debugln(\"End\")\n\treturn t, t.Errors\n}\n\nfunc (t *Tree) parse(tree *Tree) {\n\tlog.Debugln(\"Start\")\n\n\tt.nodeTarget = t.Nodes\n\n\tfor t.peek(1).Type != itemEOF {\n\t\tvar n Node\n\n\t\ttoken := t.next()\n\t\tlog.Infof(\"\\nParser got token: %#+v\\n\\n\", token)\n\n\t\tswitch token.Type {\n\t\tcase itemSectionAdornment:\n\t\t\tn = t.section(token)\n\t\tcase itemParagraph:\n\t\t\tn = newParagraph(token, &t.id)\n\t\tcase itemSpace:\n\t\t\tn = t.indent(token)\n\t\t\tif n == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase itemTitle, itemBlankLine:\n\t\t\t\/\/ itemTitle is consumed when evaluating itemSectionAdornment\n\t\t\tcontinue\n\t\tcase itemEOF:\n\t\t\tgoto exit\n\t\tdefault:\n\t\t\tt.errorf(\"%q Not implemented!\", token.Type)\n\t\t\tcontinue\n\t\t}\n\n\t\tt.nodeTarget.append(n)\n\t\tswitch n.NodeType() {\n\t\tcase NodeSection, NodeBlockQuote:\n\t\t\t\/\/ Set the loop to append items to the NodeList of the new section\n\t\t\tt.nodeTarget = reflect.ValueOf(n).Elem().FieldByName(\"NodeList\").Addr().Interface().(*NodeList)\n\t\t}\n\t}\n\n\texit:\n\tlog.Debugln(\"End\")\n}\n\nfunc (t *Tree) backup() *item {\n\tt.tokenBackupCount++\n\t\/\/ log.Debugln(\"t.tokenBackupCount:\", t.tokenPeekCount)\n\tfor i := len(t.token) - 1; i > 0; i-- {\n\t\tt.token[i] = t.token[i-1]\n\t\tt.token[i-1] = nil\n\t}\n\t\/\/ log.Debugf(\"\\n##### backup() aftermath #####\\n\\n\")\n\t\/\/ spd.Dump(t.token)\n\treturn t.token[tokenZero-t.tokenBackupCount]\n}\n\nfunc (t *Tree) peekBack(pos int) *item {\n\treturn t.token[tokenZero-pos]\n}\n\nfunc (t *Tree) peek(pos int) *item {\n\t\/\/ log.Debugln(\"t.tokenPeekCount:\", t.tokenPeekCount, \"Pos:\", pos)\n\tif pos < 1 {\n\t\tpanic(\"pos cannot be < 1\")\n\t}\n\tvar nItem *item\n\tfor i := 0; i < pos; i++ {\n\t\t\/\/ log.Debugln(\"i:\", i, \"peekCount:\", t.tokenPeekCount, \"pos:\", pos)\n\t\tif t.tokenPeekCount > i {\n\t\t\tnItem = t.token[tokenZero+i]\n\t\t\tlog.Debugf(\"Using %#+v\\n\", nItem)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Debugln(tokenZero + t.tokenPeekCount + i)\n\t\tif t.token[tokenZero + t.tokenPeekCount + i + 1] == nil {\n\t\t\tt.tokenPeekCount++\n\t\t\t\/\/ log.Debugln(\"Getting next item\")\n\t\t\tt.token[tokenZero+t.tokenPeekCount+i] = t.lex.nextItem()\n\t\t\tnItem = t.token[tokenZero+t.tokenPeekCount+i]\n\t\t} else {\n\t\t\tnItem = t.token[tokenZero+t.tokenPeekCount+i]\n\t\t}\n\t}\n\t\/\/ log.Debugf(\"\\n##### peek() aftermath #####\\n\\n\")\n\t\/\/ spd.Dump(t.token)\n\t\/\/ log.Debugf(\"Returning: %#+v\\n\", nItem)\n\treturn nItem\n}\n\n\nfunc (t *Tree) next() *item {\n\t\/\/ log.Debugln(\"t.tokenPeekCount:\", t.tokenPeekCount)\n\t\/\/ skip shifts the pointers left in t.token, pos is the amount to shift\n\tskip := func(num int) {\n\t\tfor i := num; i > 0; i-- {\n\t\t\tfor x := 0; x < len(t.token)-1; x++ {\n\t\t\t\tt.token[x] = t.token[x+1]\n\t\t\t\tt.token[x+1] = nil\n\t\t\t}\n\t\t}\n\t}\n\tif t.tokenPeekCount > 0 {\n\t\tskip(t.tokenPeekCount)\n\t} else {\n\t\tskip(1)\n\t\tt.token[tokenZero] = t.lex.nextItem()\n\t}\n\tt.tokenBackupCount, t.tokenPeekCount = 0, 0\n\t\/\/ log.Debugf(\"\\n##### next() aftermath #####\\n\\n\")\n\t\/\/ spd.Dump(t.token)\n\treturn t.token[tokenZero]\n}\n\nfunc (t *Tree) section(i *item) Node {\n\tlog.Debugln(\"Start\")\n\tvar overAdorn, title, underAdorn *item\n\tvar overline bool\n\tvar sysMessage Node\n\n\tpeekBack := t.peekBack(1)\n\tif peekBack != nil {\n\t\tif peekBack.Type == itemSpace {\n\t\t\t\/\/ Looking back past the white space\n\t\t\tif t.peekBack(2).Type == itemTitle {\n\t\t\t\treturn t.systemMessage(errorUnexpectedSectionTitle)\n\t\t\t}\n\t\t\treturn t.systemMessage(errorUnexpectedSectionTitleOrTransition)\n\t\t} else if peekBack.Type == itemTitle {\n\t\t\tif t.peekBack(2) != nil && t.peekBack(2).Type == itemSectionAdornment {\n\t\t\t\t\/\/ The overline of the section\n\t\t\t\toverline = true\n\t\t\t\toverAdorn = peekBack\n\t\t\t}\n\t\t}\n\t}\n\n\ttitle = t.peekBack(1)\n\tunderAdorn = i\n\n\t\/\/ TODO: Change these into proper error messages!\n\t\/\/ Check adornment for proper syntax\n\tif underAdorn.Type == itemSpace {\n\t\tt.backup() \/\/ Put the parser back on the title\n\t\treturn t.systemMessage(errorUnexpectedSectionTitle)\n\t} else if overline && title.Length != overAdorn.Length {\n\t\tt.errorf(\"Section over line not equal to title length!\")\n\t} else if overline && overAdorn.Text != underAdorn.Text {\n\t\tt.errorf(\"Section title over line does not match section title under line.\")\n\t}\n\n\tsec := newSection(title, overAdorn, underAdorn, &t.id)\n\texists, eSec := t.sectionLevels.Add(sec)\n\tif exists && eSec != nil {\n\t\tt.errorf(\"SectionNode using Text \\\"%s\\\" and Rune '%s' was previously parsed!\",\n\t\t\tsec.Text, string(sec.UnderLine.Rune))\n\t} else if !exists && eSec != nil {\n\t\t\/\/ There is a matching level in sectionLevels\n\t\tt.nodeTarget = &(*t.sectionLevels)[sec.Level-2].NodeList\n\t}\n\n\t\/\/ System messages have to be applied after the section is created in order to preserve\n\t\/\/ a consecutive id number.\n\tif title.Length != underAdorn.Length {\n\t\tsysMessage = t.systemMessage(warningShortUnderline)\n\t\tsec.NodeList = append(sec.NodeList, sysMessage)\n\t}\n\n\tlog.Debugln(\"End\")\n\treturn sec\n}\n\nfunc (t *Tree) systemMessage(err parserMessage) Node {\n\tvar lbText string\n\tvar lbTextLen int\n\tvar backToken int\n\n\ts := newSystemMessage(&item{\n\t\tType: itemSystemMessage,\n\t\tLine: t.token[tokenZero].Line,\n\t},\n\t\terr.Level(), &t.id)\n\n\tmsg := newParagraph(&item{\n\t\tText:   err.Message(),\n\t\tLength: len(err.Message()),\n\t}, &t.id)\n\n\tswitch err {\n\tcase warningShortUnderline, errorUnexpectedSectionTitle:\n\t\tlog.Debugln(\"FOUND\", err)\n\t\tbackToken = tokenZero - 1\n\t\tif t.peekBack(1).Type == itemSpace {\n\t\t\tbackToken = tokenZero - 2\n\t\t}\n\t\tlbText = t.token[backToken].Text.(string) + \"\\n\" + t.token[tokenZero].Text.(string)\n\t\tlbTextLen = len(lbText) + 1\n\tcase errorUnexpectedSectionTitleOrTransition:\n\t\tlog.Debugln(\"FOUND errorUnexpectedSectionTitleOrTransition\")\n\t\tlbText = t.token[tokenZero].Text.(string)\n\t\tlbTextLen = len(lbText)\n\t}\n\n\tlb := newLiteralBlock(&item{\n\t\tType:   itemLiteralBlock,\n\t\tText:   lbText,\n\t\tLength: lbTextLen, \/\/ Add one to account for the backslash\n\t}, &t.id)\n\n\ts.NodeList = append(s.NodeList, msg, lb)\n\treturn s\n}\n\nfunc (t *Tree) indent(i *item) Node {\n\tlevel := i.Length \/ t.indentWidth\n\tif t.peekBack(1).Type == itemBlankLine {\n\t\tif t.indentLevel == level {\n\t\t\t\/\/ Append to the current blockquote NodeList\n\t\t\treturn nil\n\t\t}\n\t\tt.indentLevel = level\n\t\treturn newBlockQuote(&item{Type: itemBlockquote, Line: i.Line}, level, &t.id)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/haklop\/bazooka\/commons\/matrix\"\n\n\tlib \"github.com\/haklop\/bazooka\/commons\"\n)\n\nconst (\n\tSourceFolder      = \"\/bazooka\"\n\tOutputFolder      = \"\/bazooka-output\"\n\tMetaFolder        = \"\/meta\"\n\tBazookaConfigFile = \".bazooka.yml\"\n\tTravisConfigFile  = \".travis.yml\"\n\tMX_ENV_PREFIX     = \"env::\"\n)\n\nfunc main() {\n\t\/\/ Find either .travis.yml or .bazooka.yml file in the project\n\tconfigFile, err := lib.ResolveConfigFile(SourceFolder)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ parse the configuration\n\tconfig := &lib.Config{}\n\terr = lib.Parse(configFile, config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"Parsed configuration: %+v\\n\", config)\n\n\t\/\/ resolve the docker image corresponding to this particular language parser\n\timage, err := resolveLanguageParser(config.Language)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ run the parser image\n\tlangParser := &LanguageParser{\n\t\tImage: image,\n\t}\n\terr = langParser.Parse()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ if all went well, the parser should have generated one or more \"sub\" .bazooka.*.yml files\n\t\/\/ one for each compiler version for example\n\t\/\/\n\t\/\/ they are also supposed to enrich it with a from attribute corresponding to a base docker image\n\t\/\/ to be used to run the build\n\tfiles, err := lib.ListFilesWithPrefix(OutputFolder, \".bazooka\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ for each of those files (the \"sub\" .bazooka.*.yml)\n\tfor _, file := range files {\n\t\t\/\/ parse the damned thing\n\t\tconfig := &lib.Config{}\n\t\terr = lib.Parse(file, config)\n\t\tif err != nil {\n\t\t\tlog.Fatal(fmt.Errorf(\"Error while parsing config file %s: %v\", file, err))\n\t\t}\n\n\t\t\/\/ create a matrix from the environment variables\n\t\t\/\/ a matrix has N variables (dimensions) where each variable has M values\n\t\t\/\/ config.Env is a list of key=value strings\n\t\t\/\/ explodeProps transforms that into a map[string][]string\n\t\t\/\/ for example [\"A=1\", \"A=2\", B=\"3\"]\n\t\t\/\/ when exploded gets transformed into\n\t\t\/\/ {A: [1, 2], B: [3]}\n\t\t\/\/ this matches the matrix layout, so we could store them directly into the matrix\n\t\t\/\/ but since we would like to be able to extract them later, and to avoid mixing them with a language specific variables (like jdk, go, etc.)\n\t\t\/\/ explode prefixes the env variables names with a prefix defined in the constant MX_ENV_PREFIX\n\t\t\/\/ Hence, our matrix is more like: {\"env::A\": [1, 2], \"env::B\": [3]}\n\t\tmx := matrix.Matrix(explodeProps(config.Env, MX_ENV_PREFIX))\n\n\t\t\/\/ extract the \"*\" part from the .bazooka.*.yml file\n\t\trootCounter := parseCounter(file)\n\t\t\/\/ for every .bazooka.*.yml file, the language parser is also supposed to have generated a meta\/* file\n\t\t\/\/ which is a simple yml file containing the language specific  matrix variables\n\t\t\/\/ for example, if the original .bazooka.yml file defined 2 go versions:\n\t\t\/\/\n\t\t\/\/ go:\n\t\t\/\/ - 1.2.2\n\t\t\/\/ - 1.3.1\n\t\t\/\/\n\t\t\/\/ the language parser should generate 2 meta files, one for each go version in this format:\n\t\t\/\/\n\t\t\/\/ go: 1.2.2\n\t\t\/\/\n\t\t\/\/ and\n\t\t\/\/\n\t\t\/\/ go: 1.3.1\n\t\trootMetaFile := fmt.Sprintf(\"%s\/%s\", MetaFolder, rootCounter)\n\t\t\/\/ since we have no idea of the generated meta file structure, we'll parse it into a map[string]interface{}\n\t\tvar langExtraVars map[string]interface{}\n\t\terr := lib.Parse(rootMetaFile, &langExtraVars)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t\/\/ and then add the new language specific variables parsed from the meta file to the build matrix (which already contains the env variables)\n\t\terr = feedMatrix(langExtraVars, &mx)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\t\/\/ we're not done yet: we need to also handle the matrix exclusions\n\t\t\/\/ we parse them into a list of matrices\n\t\texclusions, err := exclusionsMatrices(config.Matrix.Exclude)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\t\/\/ and finally, we iterate over all the permutations of the build matrix\n\t\t\/\/ these permutations are the list of all the combinations of env variables and language specific variables, minux the exclusions\n\t\tmx.IterAll(func(permutation map[string]string, counter string) {\n\t\t\t\/\/ we get called for every non-excluded permutations with the different variables values for this permutations and a unique permutation counter\n\t\t\t\/\/ handlePermutation will start from the .bazooka.*.yml file, which should already contain a single language specific permutation\n\t\t\t\/\/ and enrich it with the env variables combination\n\t\t\t\/\/ the same goes for the meta file\n\t\t\tif err := handlePermutation(permutation, config, counter, rootCounter); err != nil {\n\t\t\t\tlog.Fatal(fmt.Errorf(\"Error while generating the permutations: %v\", err))\n\t\t\t}\n\t\t}, exclusions)\n\n\t\t\/\/ after we're done iterating over the .bazooka.*.yml, and since we generated a new set of build files\n\t\t\/\/ we can now safely remove them\n\t\terr = os.Remove(file)\n\t\tif err != nil {\n\t\t\tlog.Fatal(fmt.Errorf(\"Error while removing file %s: %v\", file, err))\n\t\t}\n\n\t\t\/\/ same for the meta files\n\t\terr = os.Remove(fmt.Sprintf(\"%s\/%s\", MetaFolder, rootCounter))\n\t\tif err != nil {\n\t\t\tlog.Fatal(fmt.Errorf(\"Error while removing meta folders: %v\", err))\n\t\t}\n\t}\n\n\t\/\/ Now we're left with the final build files\n\tfiles, err = lib.ListFilesWithPrefix(OutputFolder, \".bazooka\")\n\tif err != nil {\n\t\tlog.Fatal(fmt.Errorf(\"Error while listing .bazooka* files: %v\", err))\n\t}\n\n\tfor _, file := range files {\n\t\tconfig := &lib.Config{}\n\t\terr = lib.Parse(file, config)\n\t\tif err != nil {\n\t\t\tlog.Fatal(fmt.Errorf(\"Error while parsing config file %s: %v\", file, err))\n\t\t}\n\n\t\t\/\/ transform the .bazooka.x.yml file into a set of dockerfile + shell scripts who perform the actual build\n\t\tg := &Generator{\n\t\t\tConfig:       config,\n\t\t\tOutputFolder: OutputFolder,\n\t\t\tIndex:        parseCounter(file),\n\t\t}\n\t\terr = g.GenerateDockerfile()\n\t\tif err != nil {\n\t\t\tfmt.Errorf(\"Error while generating a dockerfile: %v\", err)\n\t\t}\n\t}\n\n}\n\nfunc handlePermutation(permutation map[string]string, config *lib.Config, counter, rootCounter string) error {\n\t\/\/Flush file\n\t\/\/ start from the language-spcecific permutation\n\tnewConfig := *config\n\n\t\/\/ and replace its env variables with this unique permutation\n\tenvMap := extractPrefixedKeysMap(permutation, MX_ENV_PREFIX)\n\tnewConfig.Env = lib.FlattenEnvMap(envMap)\n\tif err := lib.Flush(newConfig, fmt.Sprintf(\"%s\/.bazooka.%s.yml\", OutputFolder, counter)); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ do the same for the meta file\n\t\/\/ start from the language specific permutation meta file\n\trootMetaFile := fmt.Sprintf(\"%s\/%s\", MetaFolder, rootCounter)\n\t\/\/ copy it to a global (lang specific+env vars) permutation meta file\n\tif err := lib.CopyFile(rootMetaFile, fmt.Sprintf(\"%s\/%s\", MetaFolder, counter)); err != nil {\n\t\treturn err\n\t}\n\t\/\/ and add to it this unique permutation of env variables\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"env:\\n\")\n\tfor _, env := range lib.FlattenEnvMap(envMap) {\n\t\tbuffer.WriteString(fmt.Sprintf(\" - %s\\n\", env))\n\t}\n\t\/\/ and write it to disk\n\tif err := lib.AppendToFile(fmt.Sprintf(\"%s\/%s\", MetaFolder, counter), buffer.String(), 0755); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc feedMatrix(extra map[string]interface{}, mx *matrix.Matrix) error {\n\tfor k, v := range extra {\n\t\tswitch k {\n\t\tcase \"env\":\n\t\t\tif vs, ok := v.([]interface{}); ok {\n\t\t\t\tenvVars := []string{}\n\t\t\t\tfor _, envVar := range vs {\n\t\t\t\t\tif strEnvVar, ok := envVar.(string); ok {\n\t\t\t\t\t\tenvVars = append(envVars, strEnvVar)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn fmt.Errorf(\"Invalid config: env should contain a sequence of strings: found a non string value %v:%T\", envVar, envVar)\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmx.Merge(explodeProps(envVars, MX_ENV_PREFIX))\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"Invalid config: env should contain a sequence of strings: %v:%T\", v, v)\n\t\t\t}\n\n\t\tdefault:\n\t\t\tif s, ok := v.(string); ok {\n\t\t\t\tmx.AddVar(k, s)\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"Invalid config: Unsupported variable type (%v) for the key %v\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc exclusionsMatrices(xs []map[string]interface{}) ([]*matrix.Matrix, error) {\n\tres := make([]*matrix.Matrix, len(xs))\n\tfor i, x := range xs {\n\t\tmx := matrix.Matrix{}\n\t\tif err := feedMatrix(x, &mx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tres[i] = &mx\n\t}\n\treturn res, nil\n}\n\n\/\/ parseCounter extract the * part from a .bazooka.*.yml file name\nfunc parseCounter(filePath string) string {\n\tsplits := strings.Split(filePath, \"\/\")\n\tfile := splits[len(splits)-1]\n\treturn strings.Split(file, \".\")[2]\n}\n\n\/\/ explodeProps starts from a list of key=valye strings and stores them into a map\n\/\/ it also handles repeated values, so [\"A=1\", \"A=2\", B=\"3\"] gets transformed into {A: [1, 2], B: [3]}\nfunc explodeProps(props []string, keyPrefix string) map[string][]string {\n\tenvKeyMap := make(map[string][]string)\n\tfor _, env := range props {\n\t\tenvSplit := strings.Split(env, \"=\")\n\t\tenvKeyMap[keyPrefix+envSplit[0]] = append(envKeyMap[keyPrefix+envSplit[0]], envSplit[1])\n\t}\n\treturn envKeyMap\n}\n\n\/\/ prefixMapKeys returns a new map where all keys are prefixed with prefix\nfunc prefixMapKeys(m map[string][]string, prefix string) map[string][]string {\n\tres := make(map[string][]string)\n\tfor k, v := range m {\n\t\tres[prefix+k] = v\n\t}\n\treturn res\n}\n\n\/\/ extractPrefixedKeysMap returns a new map containing only the values whose keys have the specified prefix, removing the latter in the process\n\/\/ Given {xA: 1, B: 2, xC: 3}, it returns {A: 1, C: 3} if given a prefix x\nfunc extractPrefixedKeysMap(m map[string]string, prefix string) map[string]string {\n\tres := make(map[string]string)\n\tfor k, v := range m {\n\t\tif strings.HasPrefix(k, prefix) {\n\t\t\tres[k[len(prefix):]] = v\n\t\t}\n\t}\n\treturn res\n}\n\nfunc resolveLanguageParser(language string) (string, error) {\n\tparserMap := map[string]string{\n\t\t\"golang\": \"bazooka\/parser-golang\",\n\t\t\"go\":     \"bazooka\/parser-golang\",\n\t\t\"java\":   \"bazooka\/parser-java\",\n\t}\n\tif val, ok := parserMap[language]; ok {\n\t\treturn val, nil\n\t}\n\treturn \"\", fmt.Errorf(\"Unable to find Bazooka Docker Image for Language Parser %s\\n\", language)\n}\n<commit_msg>Fix type problem<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/haklop\/bazooka\/commons\/matrix\"\n\n\tlib \"github.com\/haklop\/bazooka\/commons\"\n)\n\nconst (\n\tSourceFolder      = \"\/bazooka\"\n\tOutputFolder      = \"\/bazooka-output\"\n\tMetaFolder        = \"\/meta\"\n\tBazookaConfigFile = \".bazooka.yml\"\n\tTravisConfigFile  = \".travis.yml\"\n\tMX_ENV_PREFIX     = \"env::\"\n)\n\nfunc main() {\n\t\/\/ Find either .travis.yml or .bazooka.yml file in the project\n\tconfigFile, err := lib.ResolveConfigFile(SourceFolder)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ parse the configuration\n\tconfig := &lib.Config{}\n\terr = lib.Parse(configFile, config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Printf(\"Parsed configuration: %+v\\n\", config)\n\n\t\/\/ resolve the docker image corresponding to this particular language parser\n\timage, err := resolveLanguageParser(config.Language)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ run the parser image\n\tlangParser := &LanguageParser{\n\t\tImage: image,\n\t}\n\terr = langParser.Parse()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ if all went well, the parser should have generated one or more \"sub\" .bazooka.*.yml files\n\t\/\/ one for each compiler version for example\n\t\/\/\n\t\/\/ they are also supposed to enrich it with a from attribute corresponding to a base docker image\n\t\/\/ to be used to run the build\n\tfiles, err := lib.ListFilesWithPrefix(OutputFolder, \".bazooka\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ for each of those files (the \"sub\" .bazooka.*.yml)\n\tfor _, file := range files {\n\t\t\/\/ parse the damned thing\n\t\tconfig := &lib.Config{}\n\t\terr = lib.Parse(file, config)\n\t\tif err != nil {\n\t\t\tlog.Fatal(fmt.Errorf(\"Error while parsing config file %s: %v\", file, err))\n\t\t}\n\n\t\t\/\/ create a matrix from the environment variables\n\t\t\/\/ a matrix has N variables (dimensions) where each variable has M values\n\t\t\/\/ config.Env is a list of key=value strings\n\t\t\/\/ explodeProps transforms that into a map[string][]string\n\t\t\/\/ for example [\"A=1\", \"A=2\", B=\"3\"]\n\t\t\/\/ when exploded gets transformed into\n\t\t\/\/ {A: [1, 2], B: [3]}\n\t\t\/\/ this matches the matrix layout, so we could store them directly into the matrix\n\t\t\/\/ but since we would like to be able to extract them later, and to avoid mixing them with a language specific variables (like jdk, go, etc.)\n\t\t\/\/ explode prefixes the env variables names with a prefix defined in the constant MX_ENV_PREFIX\n\t\t\/\/ Hence, our matrix is more like: {\"env::A\": [1, 2], \"env::B\": [3]}\n\t\tmx := matrix.Matrix(explodeProps(config.Env, MX_ENV_PREFIX))\n\n\t\t\/\/ extract the \"*\" part from the .bazooka.*.yml file\n\t\trootCounter := parseCounter(file)\n\t\t\/\/ for every .bazooka.*.yml file, the language parser is also supposed to have generated a meta\/* file\n\t\t\/\/ which is a simple yml file containing the language specific  matrix variables\n\t\t\/\/ for example, if the original .bazooka.yml file defined 2 go versions:\n\t\t\/\/\n\t\t\/\/ go:\n\t\t\/\/ - 1.2.2\n\t\t\/\/ - 1.3.1\n\t\t\/\/\n\t\t\/\/ the language parser should generate 2 meta files, one for each go version in this format:\n\t\t\/\/\n\t\t\/\/ go: 1.2.2\n\t\t\/\/\n\t\t\/\/ and\n\t\t\/\/\n\t\t\/\/ go: 1.3.1\n\t\trootMetaFile := fmt.Sprintf(\"%s\/%s\", MetaFolder, rootCounter)\n\t\t\/\/ since we have no idea of the generated meta file structure, we'll parse it into a map[string]interface{}\n\t\tvar langExtraVars map[string]interface{}\n\t\terr := lib.Parse(rootMetaFile, &langExtraVars)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t\/\/ and then add the new language specific variables parsed from the meta file to the build matrix (which already contains the env variables)\n\t\terr = feedMatrix(langExtraVars, &mx)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\t\/\/ we're not done yet: we need to also handle the matrix exclusions\n\t\t\/\/ we parse them into a list of matrices\n\t\texclusions, err := exclusionsMatrices(config.Matrix.Exclude)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\t\/\/ and finally, we iterate over all the permutations of the build matrix\n\t\t\/\/ these permutations are the list of all the combinations of env variables and language specific variables, minux the exclusions\n\t\tmx.IterAll(func(permutation map[string]string, counter string) {\n\t\t\t\/\/ we get called for every non-excluded permutations with the different variables values for this permutations and a unique permutation counter\n\t\t\t\/\/ handlePermutation will start from the .bazooka.*.yml file, which should already contain a single language specific permutation\n\t\t\t\/\/ and enrich it with the env variables combination\n\t\t\t\/\/ the same goes for the meta file\n\t\t\tif err := handlePermutation(permutation, config, counter, rootCounter); err != nil {\n\t\t\t\tlog.Fatal(fmt.Errorf(\"Error while generating the permutations: %v\", err))\n\t\t\t}\n\t\t}, exclusions)\n\n\t\t\/\/ after we're done iterating over the .bazooka.*.yml, and since we generated a new set of build files\n\t\t\/\/ we can now safely remove them\n\t\terr = os.Remove(file)\n\t\tif err != nil {\n\t\t\tlog.Fatal(fmt.Errorf(\"Error while removing file %s: %v\", file, err))\n\t\t}\n\n\t\t\/\/ same for the meta files\n\t\terr = os.Remove(fmt.Sprintf(\"%s\/%s\", MetaFolder, rootCounter))\n\t\tif err != nil {\n\t\t\tlog.Fatal(fmt.Errorf(\"Error while removing meta folders: %v\", err))\n\t\t}\n\t}\n\n\t\/\/ Now we're left with the final build files\n\tfiles, err = lib.ListFilesWithPrefix(OutputFolder, \".bazooka\")\n\tif err != nil {\n\t\tlog.Fatal(fmt.Errorf(\"Error while listing .bazooka* files: %v\", err))\n\t}\n\n\tfor _, file := range files {\n\t\tconfig := &lib.Config{}\n\t\terr = lib.Parse(file, config)\n\t\tif err != nil {\n\t\t\tlog.Fatal(fmt.Errorf(\"Error while parsing config file %s: %v\", file, err))\n\t\t}\n\n\t\t\/\/ transform the .bazooka.x.yml file into a set of dockerfile + shell scripts who perform the actual build\n\t\tg := &Generator{\n\t\t\tConfig:       config,\n\t\t\tOutputFolder: OutputFolder,\n\t\t\tIndex:        parseCounter(file),\n\t\t}\n\t\terr = g.GenerateDockerfile()\n\t\tif err != nil {\n\t\t\tfmt.Errorf(\"Error while generating a dockerfile: %v\", err)\n\t\t}\n\t}\n\n}\n\nfunc handlePermutation(permutation map[string]string, config *lib.Config, counter, rootCounter string) error {\n\t\/\/Flush file\n\t\/\/ start from the language-spcecific permutation\n\tnewConfig := *config\n\n\t\/\/ and replace its env variables with this unique permutation\n\tenvMap := extractPrefixedKeysMap(permutation, MX_ENV_PREFIX)\n\tnewConfig.Env = lib.FlattenEnvMap(envMap)\n\tif err := lib.Flush(newConfig, fmt.Sprintf(\"%s\/.bazooka.%s.yml\", OutputFolder, counter)); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ do the same for the meta file\n\t\/\/ start from the language specific permutation meta file\n\trootMetaFile := fmt.Sprintf(\"%s\/%s\", MetaFolder, rootCounter)\n\t\/\/ copy it to a global (lang specific+env vars) permutation meta file\n\tif err := lib.CopyFile(rootMetaFile, fmt.Sprintf(\"%s\/%s\", MetaFolder, counter)); err != nil {\n\t\treturn err\n\t}\n\t\/\/ and add to it this unique permutation of env variables\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"env:\\n\")\n\tfor _, env := range lib.FlattenEnvMap(envMap) {\n\t\tbuffer.WriteString(fmt.Sprintf(\" - %s\\n\", env))\n\t}\n\t\/\/ and write it to disk\n\tif err := lib.AppendToFile(fmt.Sprintf(\"%s\/%s\", MetaFolder, counter), buffer.String(), 0755); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc feedMatrix(extra map[string]interface{}, mx *matrix.Matrix) error {\n\tfor k, v := range extra {\n\t\tswitch k {\n\t\tcase \"env\":\n\t\t\tif vs, ok := v.([]interface{}); ok {\n\t\t\t\tenvVars := []string{}\n\t\t\t\tfor _, envVar := range vs {\n\t\t\t\t\tif strEnvVar, ok := envVar.(string); ok {\n\t\t\t\t\t\tenvVars = append(envVars, strEnvVar)\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn fmt.Errorf(\"Invalid config: env should contain a sequence of strings: found a non string value %v:%T\", envVar, envVar)\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmx.Merge(explodeProps(envVars, MX_ENV_PREFIX))\n\t\t\t} else {\n\t\t\t\treturn fmt.Errorf(\"Invalid config: env should contain a sequence of strings: %v:%T\", v, v)\n\t\t\t}\n\n\t\tdefault:\n\t\t\tmx.AddVar(k, fmt.Sprintf(\"%v\", v))\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc exclusionsMatrices(xs []map[string]interface{}) ([]*matrix.Matrix, error) {\n\tres := make([]*matrix.Matrix, len(xs))\n\tfor i, x := range xs {\n\t\tmx := matrix.Matrix{}\n\t\tif err := feedMatrix(x, &mx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tres[i] = &mx\n\t}\n\treturn res, nil\n}\n\n\/\/ parseCounter extract the * part from a .bazooka.*.yml file name\nfunc parseCounter(filePath string) string {\n\tsplits := strings.Split(filePath, \"\/\")\n\tfile := splits[len(splits)-1]\n\treturn strings.Split(file, \".\")[2]\n}\n\n\/\/ explodeProps starts from a list of key=valye strings and stores them into a map\n\/\/ it also handles repeated values, so [\"A=1\", \"A=2\", B=\"3\"] gets transformed into {A: [1, 2], B: [3]}\nfunc explodeProps(props []string, keyPrefix string) map[string][]string {\n\tenvKeyMap := make(map[string][]string)\n\tfor _, env := range props {\n\t\tenvSplit := strings.Split(env, \"=\")\n\t\tenvKeyMap[keyPrefix+envSplit[0]] = append(envKeyMap[keyPrefix+envSplit[0]], envSplit[1])\n\t}\n\treturn envKeyMap\n}\n\n\/\/ prefixMapKeys returns a new map where all keys are prefixed with prefix\nfunc prefixMapKeys(m map[string][]string, prefix string) map[string][]string {\n\tres := make(map[string][]string)\n\tfor k, v := range m {\n\t\tres[prefix+k] = v\n\t}\n\treturn res\n}\n\n\/\/ extractPrefixedKeysMap returns a new map containing only the values whose keys have the specified prefix, removing the latter in the process\n\/\/ Given {xA: 1, B: 2, xC: 3}, it returns {A: 1, C: 3} if given a prefix x\nfunc extractPrefixedKeysMap(m map[string]string, prefix string) map[string]string {\n\tres := make(map[string]string)\n\tfor k, v := range m {\n\t\tif strings.HasPrefix(k, prefix) {\n\t\t\tres[k[len(prefix):]] = v\n\t\t}\n\t}\n\treturn res\n}\n\nfunc resolveLanguageParser(language string) (string, error) {\n\tparserMap := map[string]string{\n\t\t\"golang\": \"bazooka\/parser-golang\",\n\t\t\"go\":     \"bazooka\/parser-golang\",\n\t\t\"java\":   \"bazooka\/parser-java\",\n\t}\n\tif val, ok := parserMap[language]; ok {\n\t\treturn val, nil\n\t}\n\treturn \"\", fmt.Errorf(\"Unable to find Bazooka Docker Image for Language Parser %s\\n\", language)\n}\n<|endoftext|>"}
{"text":"<commit_before>package pgparser\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nvar (\n\tsingleRecordString   = `({http:\/\/www.example.com\/image1.png,http:\/\/www.example.com\/image2.png},image\/png,\"a logo\",123456)`\n\tmultipleRecordString = `{\"({http:\/\/www.example.com\/image1.png,http:\/\/www.example.com\/image2.png},image\/png,\\\"a logo\\\",123456)\",\"({http:\/\/www.example.com\/banner.png},image\/png,\\\"a banner\\\",123456)\"}`\n\tunquotedString       = `this is a test`\n\temptyArray           = `{}`\n)\n\ntype record struct {\n\tURLs []string\n\tType string\n\tName string\n\tSize int\n}\n\nfunc TestSingleRecord(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r record\n\n\tif !a.NoError(Unmarshal(singleRecordString, &r)) {\n\t\treturn\n\t}\n\n\ta.Equal(record{\n\t\tURLs: []string{\n\t\t\t\"http:\/\/www.example.com\/image1.png\",\n\t\t\t\"http:\/\/www.example.com\/image2.png\",\n\t\t},\n\t\tType: \"image\/png\",\n\t\tName: \"a logo\",\n\t\tSize: 123456,\n\t}, r)\n}\n\nfunc TestMultipleRecords(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r []record\n\n\tif !a.NoError(Unmarshal(multipleRecordString, &r)) {\n\t\treturn\n\t}\n\n\ta.Equal([]record{\n\t\t{\n\t\t\tURLs: []string{\n\t\t\t\t\"http:\/\/www.example.com\/image1.png\",\n\t\t\t\t\"http:\/\/www.example.com\/image2.png\",\n\t\t\t},\n\t\t\tType: \"image\/png\",\n\t\t\tName: \"a logo\",\n\t\t\tSize: 123456,\n\t\t},\n\t\t{\n\t\t\tURLs: []string{\n\t\t\t\t\"http:\/\/www.example.com\/banner.png\",\n\t\t\t},\n\t\t\tType: \"image\/png\",\n\t\t\tName: \"a banner\",\n\t\t\tSize: 123456,\n\t\t},\n\t}, r)\n}\n\nfunc TestByteSlice(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r []byte\n\n\tif !a.NoError(Unmarshal(unquotedString, &r)) {\n\t\treturn\n\t}\n\n\ta.Equal([]byte(unquotedString), r)\n}\n\nfunc TestByteSliceQuoted(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r []byte\n\n\tif !a.NoError(Unmarshal(\"\\\"\"+unquotedString+\"\\\"\", &r)) {\n\t\treturn\n\t}\n\n\ta.Equal([]byte(unquotedString), r)\n}\n\nfunc TestString(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r string\n\n\tif !a.NoError(Unmarshal(unquotedString, &r)) {\n\t\treturn\n\t}\n\n\ta.Equal(unquotedString, r)\n}\n\nfunc TestStringQuoted(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r string\n\n\tif !a.NoError(Unmarshal(\"\\\"\"+unquotedString+\"\\\"\", &r)) {\n\t\treturn\n\t}\n\n\ta.Equal(unquotedString, r)\n}\n\nfunc TestBadTarget(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r interface{}\n\n\ta.Error(Unmarshal(\"t\", &r))\n}\n\nfunc TestNonPointerTarget(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r string\n\n\ta.Error(Unmarshal(\"t\", r))\n}\n\nfunc TestBadSourceForString(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar s string\n\n\ta.Error(Unmarshal(emptyArray, &s))\n}\n\nfunc TestBadSourceForByteSlice(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar s []byte\n\n\ta.Error(Unmarshal(emptyArray, &s))\n}\n\nfunc TestGoodInt(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int\n\n\tif a.NoError(Unmarshal(\"2147483647\", &i)) {\n\t\ta.Equal(\"2147483647\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodUint(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint\n\n\tif a.NoError(Unmarshal(\"4294967295\", &i)) {\n\t\ta.Equal(\"4294967295\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodInt8(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int8\n\n\tif a.NoError(Unmarshal(\"127\", &i)) {\n\t\ta.Equal(\"127\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodUint8(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint8\n\n\tif a.NoError(Unmarshal(\"255\", &i)) {\n\t\ta.Equal(\"255\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodInt16(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int16\n\n\tif a.NoError(Unmarshal(\"32767\", &i)) {\n\t\ta.Equal(\"32767\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodUint16(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint16\n\n\tif a.NoError(Unmarshal(\"65535\", &i)) {\n\t\ta.Equal(\"65535\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodInt32(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int32\n\n\tif a.NoError(Unmarshal(\"2147483647\", &i)) {\n\t\ta.Equal(\"2147483647\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodUint32(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint32\n\n\tif a.NoError(Unmarshal(\"4294967295\", &i)) {\n\t\ta.Equal(\"4294967295\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodInt64(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int64\n\n\tif a.NoError(Unmarshal(\"9223372036854775807\", &i)) {\n\t\ta.Equal(\"9223372036854775807\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodUint64(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint64\n\n\tif a.NoError(Unmarshal(\"18446744073709551615\", &i)) {\n\t\ta.Equal(\"18446744073709551615\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestTooLongInt(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int\n\n\ta.Error(Unmarshal(\"2147483648\", &i))\n}\n\nfunc TestTooLongUint(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint\n\n\ta.Error(Unmarshal(\"4294967296\", &i))\n}\n\nfunc TestTooLongInt8(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int8\n\n\ta.Error(Unmarshal(\"128\", &i))\n}\n\nfunc TestTooLongUint8(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint8\n\n\ta.Error(Unmarshal(\"256\", &i))\n}\n\nfunc TestTooLongInt16(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int16\n\n\ta.Error(Unmarshal(\"32768\", &i))\n}\n\nfunc TestTooLongUint16(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint16\n\n\ta.Error(Unmarshal(\"65536\", &i))\n}\n\nfunc TestTooLongInt32(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int32\n\n\ta.Error(Unmarshal(\"2147483648\", &i))\n}\n\nfunc TestTooLongUint32(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint32\n\n\ta.Error(Unmarshal(\"4294967296\", &i))\n}\n\nfunc TestTooLongInt64(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int64\n\n\ta.Error(Unmarshal(\"9223372036854775808\", &i))\n}\n\nfunc TestTooLongUint64(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint64\n\n\ta.Error(Unmarshal(\"18446744073709551616\", &i))\n}\n\nfunc TestBadSourceForInt(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForUint(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForInt8(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int8\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForUint8(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint8\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForInt16(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int16\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForUint16(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint16\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForInt32(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int32\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForUint32(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint32\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForInt64(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int64\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForUint64(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint64\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n<commit_msg>more tests<commit_after>package pgparser\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nvar (\n\tsingleRecordString   = `({http:\/\/www.example.com\/image1.png,http:\/\/www.example.com\/image2.png},image\/png,\"a logo\",123456)`\n\tmultipleRecordString = `{\"({http:\/\/www.example.com\/image1.png,http:\/\/www.example.com\/image2.png},image\/png,\\\"a logo\\\",123456)\",\"({http:\/\/www.example.com\/banner.png},image\/png,\\\"a banner\\\",123456)\"}`\n\tunquotedString       = `this is a test`\n\temptyArray           = `{}`\n)\n\ntype record struct {\n\tURLs []string\n\tType string\n\tName string\n\tSize int\n}\n\nfunc TestSingleRecord(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r record\n\n\tif !a.NoError(Unmarshal(singleRecordString, &r)) {\n\t\treturn\n\t}\n\n\ta.Equal(record{\n\t\tURLs: []string{\n\t\t\t\"http:\/\/www.example.com\/image1.png\",\n\t\t\t\"http:\/\/www.example.com\/image2.png\",\n\t\t},\n\t\tType: \"image\/png\",\n\t\tName: \"a logo\",\n\t\tSize: 123456,\n\t}, r)\n}\n\nfunc TestMultipleRecords(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r []record\n\n\tif !a.NoError(Unmarshal(multipleRecordString, &r)) {\n\t\treturn\n\t}\n\n\ta.Equal([]record{\n\t\t{\n\t\t\tURLs: []string{\n\t\t\t\t\"http:\/\/www.example.com\/image1.png\",\n\t\t\t\t\"http:\/\/www.example.com\/image2.png\",\n\t\t\t},\n\t\t\tType: \"image\/png\",\n\t\t\tName: \"a logo\",\n\t\t\tSize: 123456,\n\t\t},\n\t\t{\n\t\t\tURLs: []string{\n\t\t\t\t\"http:\/\/www.example.com\/banner.png\",\n\t\t\t},\n\t\t\tType: \"image\/png\",\n\t\t\tName: \"a banner\",\n\t\t\tSize: 123456,\n\t\t},\n\t}, r)\n}\n\nfunc TestByteSlice(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r []byte\n\n\tif !a.NoError(Unmarshal(unquotedString, &r)) {\n\t\treturn\n\t}\n\n\ta.Equal([]byte(unquotedString), r)\n}\n\nfunc TestByteSliceQuoted(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r []byte\n\n\tif !a.NoError(Unmarshal(\"\\\"\"+unquotedString+\"\\\"\", &r)) {\n\t\treturn\n\t}\n\n\ta.Equal([]byte(unquotedString), r)\n}\n\nfunc TestString(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r string\n\n\tif !a.NoError(Unmarshal(unquotedString, &r)) {\n\t\treturn\n\t}\n\n\ta.Equal(unquotedString, r)\n}\n\nfunc TestStringQuoted(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r string\n\n\tif !a.NoError(Unmarshal(\"\\\"\"+unquotedString+\"\\\"\", &r)) {\n\t\treturn\n\t}\n\n\ta.Equal(unquotedString, r)\n}\n\nfunc TestBadTarget(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r interface{}\n\n\ta.Error(Unmarshal(\"t\", &r))\n}\n\nfunc TestNonPointerTarget(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar r string\n\n\ta.Error(Unmarshal(\"t\", r))\n}\n\nfunc TestBadSourceForString(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar s string\n\n\ta.Error(Unmarshal(emptyArray, &s))\n}\n\nfunc TestBadSourceForByteSlice(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar s []byte\n\n\ta.Error(Unmarshal(emptyArray, &s))\n}\n\nfunc TestBadSourceForArray(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar l []string\n\n\ta.Error(Unmarshal(\"x\", &l))\n}\n\nfunc TestBadSourceForTuple(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar s struct{ A, B, C string }\n\n\ta.Error(Unmarshal(\"x\", &s))\n}\n\nfunc TestUnclosedArray(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar l []string\n\n\ta.Error(Unmarshal(\"{a,b,c\", &l))\n}\n\nfunc TestUnclosedTuple(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar s struct{ A, B, C string }\n\n\ta.Error(Unmarshal(\"(a,b,c\", &s))\n}\n\nfunc TestMismatchedArrayDelimiters(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar l []string\n\n\ta.Error(Unmarshal(\"{a,b,c)\", &l))\n}\n\nfunc TestMismatchedTupleDelimiters(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar s struct{ A, B, C string }\n\n\ta.Error(Unmarshal(\"(a,b,c}\", &s))\n}\n\nfunc TestUnfinishedTuple(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar s struct{ A, B, C string }\n\n\ta.Error(Unmarshal(\"(a,b)\", &s))\n}\n\nfunc TestGoodInt(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int\n\n\tif a.NoError(Unmarshal(\"2147483647\", &i)) {\n\t\ta.Equal(\"2147483647\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodUint(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint\n\n\tif a.NoError(Unmarshal(\"4294967295\", &i)) {\n\t\ta.Equal(\"4294967295\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodInt8(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int8\n\n\tif a.NoError(Unmarshal(\"127\", &i)) {\n\t\ta.Equal(\"127\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodUint8(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint8\n\n\tif a.NoError(Unmarshal(\"255\", &i)) {\n\t\ta.Equal(\"255\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodInt16(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int16\n\n\tif a.NoError(Unmarshal(\"32767\", &i)) {\n\t\ta.Equal(\"32767\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodUint16(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint16\n\n\tif a.NoError(Unmarshal(\"65535\", &i)) {\n\t\ta.Equal(\"65535\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodInt32(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int32\n\n\tif a.NoError(Unmarshal(\"2147483647\", &i)) {\n\t\ta.Equal(\"2147483647\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodUint32(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint32\n\n\tif a.NoError(Unmarshal(\"4294967295\", &i)) {\n\t\ta.Equal(\"4294967295\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodInt64(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int64\n\n\tif a.NoError(Unmarshal(\"9223372036854775807\", &i)) {\n\t\ta.Equal(\"9223372036854775807\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestGoodUint64(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint64\n\n\tif a.NoError(Unmarshal(\"18446744073709551615\", &i)) {\n\t\ta.Equal(\"18446744073709551615\", fmt.Sprintf(\"%d\", i))\n\t}\n}\n\nfunc TestTooLongInt(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int\n\n\ta.Error(Unmarshal(\"2147483648\", &i))\n}\n\nfunc TestTooLongUint(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint\n\n\ta.Error(Unmarshal(\"4294967296\", &i))\n}\n\nfunc TestTooLongInt8(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int8\n\n\ta.Error(Unmarshal(\"128\", &i))\n}\n\nfunc TestTooLongUint8(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint8\n\n\ta.Error(Unmarshal(\"256\", &i))\n}\n\nfunc TestTooLongInt16(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int16\n\n\ta.Error(Unmarshal(\"32768\", &i))\n}\n\nfunc TestTooLongUint16(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint16\n\n\ta.Error(Unmarshal(\"65536\", &i))\n}\n\nfunc TestTooLongInt32(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int32\n\n\ta.Error(Unmarshal(\"2147483648\", &i))\n}\n\nfunc TestTooLongUint32(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint32\n\n\ta.Error(Unmarshal(\"4294967296\", &i))\n}\n\nfunc TestTooLongInt64(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int64\n\n\ta.Error(Unmarshal(\"9223372036854775808\", &i))\n}\n\nfunc TestTooLongUint64(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint64\n\n\ta.Error(Unmarshal(\"18446744073709551616\", &i))\n}\n\nfunc TestBadSourceForInt(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForUint(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForInt8(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int8\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForUint8(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint8\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForInt16(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int16\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForUint16(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint16\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForInt32(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int32\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForUint32(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint32\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForInt64(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i int64\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n\nfunc TestBadSourceForUint64(t *testing.T) {\n\ta := assert.New(t)\n\n\tvar i uint64\n\n\ta.Error(Unmarshal(emptyArray, &i))\n}\n<|endoftext|>"}
{"text":"<commit_before>package jsonparser\n\nimport (\n\t\"bytes\"\n\t_ \"fmt\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc toArray(data []byte) (result [][]byte) {\n\tArrayEach(data, func(value []byte, dataType int, offset int, err error) {\n\t\tresult = append(result, value)\n\t})\n\n\treturn\n}\n\nfunc TestValidJSON(t *testing.T) {\n    if v, _, _, err := Get([]byte(`{\"a\":[{\"b\":1},{\"b\":2},3],\"c\":{\"c\":[1,2]}} }`), \"c\", \"c\"); !bytes.Equal(v, []byte(`[1,2]`)) {\n        t.Errorf(\"Should handle multiple nested keys with same name: %s, %v\", string(v), err)\n    }\n\n\tif v, _, _, e := Get([]byte(`{\"a\":\"b\"}`), \"a\"); !bytes.Equal(v, []byte(\"b\")) {\n\t\tt.Errorf(\"Should read basic key %s %v\", string(v), e)\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": \"b\"}`), \"a\"); !bytes.Equal(v, []byte(\"b\")) {\n\t\tt.Errorf(\"Should read basic key with space %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": { \"b\":{\"c\":\"d\" }}}`), \"a\", \"b\", \"c\"); !bytes.Equal(v, []byte(\"d\")) {\n\t\tt.Errorf(\"Should read composite key %s\", string(v))\n\t}\n\n\tif v, _, _, err := Get([]byte(`{\"a\": { \"b\": 1}, \"c\": 2 }`), \"a\", \"b\", \"c\"); err == nil {\n\t\tt.Errorf(\"Should apply scope of parent when search for nested key: %s, %v\", string(v), err)\n\t}\n\n\tif v, _, _, err := Get([]byte(`{\"a\": { \"b\": 1}, \"c\": 2 }`), \"b\"); err == nil {\n\t\tt.Errorf(\"Should apply scope to key level: %s, %v\", string(v), err)\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": \"b\", \"c\": 1}`), \"c\"); !bytes.Equal(v, []byte(\"1\")) {\n\t\tt.Errorf(\"Should read numberic value as string %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": \"string\\\"with\\\"quotes\"}`), \"a\"); !bytes.Equal(v, []byte(`string\\\"with\\\"quotes`)) {\n\t\tt.Errorf(\"Should read string values with quotes %s\", string(v))\n\t}\n\n\tif v, _, _ := GetNumber([]byte(`{\"a\": \"b\", \"c\": 1}`), \"c\"); v != 1 {\n\t\tt.Errorf(\"Should read numberic value as number %s\", string(v))\n\t}\n\n    if v, _, _, err := Get([]byte(`{\"a\":[{\"b\":1},{\"b\":2},3],\"c\":{\"c\":[1,2]}} }`), \"c\", \"c\"); !bytes.Equal(v, []byte(`[1,2]`)) {\n        t.Errorf(\"Should handle multiple nested keys with same name: %s, %v\", string(v), err)\n    }\n\n\tif v, _, _ := GetNumber([]byte(\"{\\\"a\\\": \\\"b\\\", \\\"c\\\": 1 \\n}\"), \"c\"); v != 1 {\n\t\tt.Errorf(\"Should read numberic values in formatted json %s\", string(v))\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(`{\"a\": \"b\", \"c\": true}`), \"c\"); !v {\n\t\tt.Errorf(\"Should read boolean true as boolean %s\", string(v))\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(\"{\\\"a\\\": \\\"b\\\", \\\"c\\\": true \\n}\"), \"c\"); !v {\n\t\tt.Errorf(\"Should read boolean true in formatted json %s\", string(v))\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(`{\"a\": \"b\", \"c\": false}`), \"c\"); v {\n\t\tt.Errorf(\"Should read boolean false as boolean %s\", string(v))\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(\"{\\\"a\\\": \\\"b\\\", \\\"c\\\": false \\n}\"), \"c\"); v {\n\t\tt.Errorf(\"Should read boolean false in formatted json %s\", string(v))\n\t}\n\n\tif v, _, _ := GetNumber([]byte(\"{\\\"a\\\": \\\"b\\\", \\\"c\\\": 1 \\n}\"), \"c\"); v != 1 {\n\t\tt.Errorf(\"Should read numberic values in formatted json %s\", string(v))\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(`{\"a\": \"b\", \"c\": true}`), \"c\"); !v {\n\t\tt.Errorf(\"Should read boolean true as boolean %s\", string(v))\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(\"{\\\"a\\\": \\\"b\\\", \\\"c\\\": true \\n}\"), \"c\"); !v {\n\t\tt.Errorf(\"Should read boolean true in formatted json %s\", string(v))\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(`{\"a\": \"b\", \"c\": false}`), \"c\"); v {\n\t\tt.Errorf(\"Should read boolean false as boolean %s\", string(v))\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(\"{\\\"a\\\": \\\"b\\\", \\\"c\\\": false \\n}\"), \"c\"); v {\n\t\tt.Errorf(\"Should read boolean false in formatted json %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": { \"b\":{\"c\":\"d\" }}}`), \"a\", \"b\", \"c\"); !bytes.Equal(v, []byte(\"d\")) {\n\t\tt.Errorf(\"Should read composite key %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": { \"b\":{\"c\":\"d\" }}}`), \"a\", \"b\"); !bytes.Equal(v, []byte(`{\"c\":\"d\" }`)) {\n\t\tt.Errorf(\"Should read object %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"c\":\"d\" }`)); !bytes.Equal(v, []byte(`{\"c\":\"d\" }`)) {\n\t\tt.Errorf(\"Should handle empty path %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": { \"b\":[1,2,3,4]}}`), \"a\", \"b\"); !reflect.DeepEqual(toArray(v), [][]byte{[]byte(\"1\"), []byte(\"2\"), []byte(\"3\"), []byte(`4`)}) {\n\t\tt.Errorf(\"Should read array of simple values: %s, %v\", string(v), toArray(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`[1,2,3,4]`)); !reflect.DeepEqual(toArray(v), [][]byte{[]byte(\"1\"), []byte(\"2\"), []byte(\"3\"), []byte(`4`)}) {\n\t\tt.Errorf(\"Should parse array without specifying path: %s %v\", string(v), toArray(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": { \"b\":[{\"x\":1},{\"x\":2},{\"x\":3},{\"x\":4}]}}`), \"a\", \"b\"); !reflect.DeepEqual(toArray(v), [][]byte{[]byte(`{\"x\":1}`), []byte(`{\"x\":2}`), []byte(`{\"x\":3}`), []byte(`{\"x\":4}`)}) {\n\t\tt.Errorf(\"Should read array of objects %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": [[[1]],[[2]]]}`), \"a\"); !reflect.DeepEqual(toArray(v), [][]byte{[]byte(\"[[1]]\"), []byte(\"[[2]]\")}) {\n\t\tt.Errorf(\"Should parse nested array %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(\"{\\n  \\\"a\\\": \\\"b\\\"\\n}\"), \"a\"); !bytes.Equal(v, []byte(\"b\")) {\n\t\tt.Errorf(\"Should read formated json value %s\", string(v))\n\t}\n\n\tif v, _, _, e := Get([]byte(\"{\\n  \\\"a\\\":\\n    {\\n\\\"b\\\":\\n   {\\\"c\\\":\\\"d\\\",\\n\\\"e\\\": \\\"f\\\"}\\n}\\n}\"), \"a\", \"b\"); !bytes.Equal(v, []byte(\"{\\\"c\\\":\\\"d\\\",\\n\\\"e\\\": \\\"f\\\"}\")) {\n\t\tt.Errorf(\"Should read formated json object %s %v\", string(v), e)\n\t}\n}\n\nfunc TestInvalidJSON(t *testing.T) {\n\tif _, _, _, e := Get([]byte(`{\"a\":\"b\"`), \"c\"); e == nil || e.Error() != \"Key path not found\" {\n\t\tt.Errorf(\"Should not found key: %v\", e)\n\t}\n\n\tif v, _, _, e := Get([]byte(`{\"a\":\"b\"`), \"a\"); !bytes.Equal(v, []byte(\"b\")) || e != nil {\n\t\tt.Errorf(\"Should not found missing bracket, because key still found: %s\", string(v))\n\t}\n\n\tif _, _, _, e := Get([]byte(`{\"a\":\"b`), \"a\"); e == nil || e.Error() != \"Value is string, but can't find closing '\\\"' symbol\" {\n\t\tt.Errorf(\"Should raise error since end of string not found: %v\", e)\n\t}\n\n\tif v, _, _, e := Get([]byte(`{\"a\": { \"b\": \"c\"`), \"a\"); e == nil || e.Error() != \"Value looks like object, but can't find closing '}' symbol\" {\n\t\tt.Errorf(\"Should raise error if closing brace not found: %v %s\", e, string(v))\n\t}\n\n\tif v, _, _, e := Get([]byte(`{\"a\": [1, 2, 3 }`), \"a\"); e == nil || e.Error() != \"Value is array, but can't find closing ']' symbol\" {\n\t\tt.Errorf(\"Should raise error if closing bracket not found: %v %s\", e, string(v))\n\t}\n\n\tif _, _, _, e := Get([]byte(`{\"a\": `), \"a\"); e == nil || e.Error() != \"Malformed JSON error\" {\n\t\tt.Errorf(\"Should raise malformed json error: %v\", e)\n\t}\n}\n\nfunc TestTrickyJSON(t *testing.T) {\n\tkiller := []byte(`{\n          \"parentkey\": {\n            \"childkey\": {\n              \"grandchildkey\": 111\n            },\n            \"otherchildkey\": 222\n          },\n          \"bad key\\\"good key\": 333,\n        }`)\n\n\tif data, jtype, _, _ := Get(killer, \"childkey\"); jtype != NotExist {\n\t\tt.Errorf(`Get(\"childkey\") should not exist, but found data %s`, string(data))\n\t}\n\n\tif data, jtype, _, _ := Get(killer, \"parentkey\", \"childkey\", \"otherchildkey\"); jtype != NotExist {\n\t\tt.Errorf(`Get(\"parentkey\", \"childkey\", \"otherchildkey\") should not exist, but found data %s`, string(data))\n\t}\n\n\tif data, jtype, _, _ := Get(killer, \"good key\"); jtype != NotExist {\n\t\tt.Errorf(`Get(\"good key\") should not exist, but found data %s`, string(data))\n\t}\n}\n<commit_msg>Fix tests<commit_after>package jsonparser\n\nimport (\n\t\"bytes\"\n\t_ \"fmt\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc toArray(data []byte) (result [][]byte) {\n\tArrayEach(data, func(value []byte, dataType int, offset int, err error) {\n\t\tresult = append(result, value)\n\t})\n\n\treturn\n}\n\nfunc TestValidJSON(t *testing.T) {\n    if v, _, _, err := Get([]byte(`{\"a\":[{\"b\":1},{\"b\":2},3],\"c\":{\"c\":[1,2]}} }`), \"c\", \"c\"); !bytes.Equal(v, []byte(`[1,2]`)) {\n        t.Errorf(\"Should handle multiple nested keys with same name: %s, %v\", string(v), err)\n    }\n\n\tif v, _, _, e := Get([]byte(`{\"a\":\"b\"}`), \"a\"); !bytes.Equal(v, []byte(\"b\")) {\n\t\tt.Errorf(\"Should read basic key %s %v\", string(v), e)\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": \"b\"}`), \"a\"); !bytes.Equal(v, []byte(\"b\")) {\n\t\tt.Errorf(\"Should read basic key with space %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": { \"b\":{\"c\":\"d\" }}}`), \"a\", \"b\", \"c\"); !bytes.Equal(v, []byte(\"d\")) {\n\t\tt.Errorf(\"Should read composite key %s\", string(v))\n\t}\n\n\tif v, _, _, err := Get([]byte(`{\"a\": { \"b\": 1}, \"c\": 2 }`), \"a\", \"b\", \"c\"); err == nil {\n\t\tt.Errorf(\"Should apply scope of parent when search for nested key: %s, %v\", string(v), err)\n\t}\n\n\tif v, _, _, err := Get([]byte(`{\"a\": { \"b\": 1}, \"c\": 2 }`), \"b\"); err == nil {\n\t\tt.Errorf(\"Should apply scope to key level: %s, %v\", string(v), err)\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": \"b\", \"c\": 1}`), \"c\"); !bytes.Equal(v, []byte(\"1\")) {\n\t\tt.Errorf(\"Should read numberic value as string %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": \"string\\\"with\\\"quotes\"}`), \"a\"); !bytes.Equal(v, []byte(`string\\\"with\\\"quotes`)) {\n\t\tt.Errorf(\"Should read string values with quotes %s\", string(v))\n\t}\n\n\tif v, _, _ := GetNumber([]byte(`{\"a\": \"b\", \"c\": 1}`), \"c\"); v != 1 {\n\t\tt.Errorf(\"Should read numberic value as number %d\", v)\n\t}\n\n    if v, _, _, err := Get([]byte(`{\"a\":[{\"b\":1},{\"b\":2},3],\"c\":{\"c\":[1,2]}} }`), \"c\", \"c\"); !bytes.Equal(v, []byte(`[1,2]`)) {\n        t.Errorf(\"Should handle multiple nested keys with same name: %s, %v\", string(v), err)\n    }\n\n\tif v, _, _ := GetNumber([]byte(\"{\\\"a\\\": \\\"b\\\", \\\"c\\\": 1 \\n}\"), \"c\"); v != 1 {\n\t\tt.Errorf(\"Should read numberic values in formatted json %d\", v)\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(`{\"a\": \"b\", \"c\": true}`), \"c\"); !v {\n\t\tt.Errorf(\"Should read boolean true as boolean %v\", v)\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(\"{\\\"a\\\": \\\"b\\\", \\\"c\\\": true \\n}\"), \"c\"); !v {\n\t\tt.Errorf(\"Should read boolean true in formatted json %v\", v)\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(`{\"a\": \"b\", \"c\": false}`), \"c\"); v {\n\t\tt.Errorf(\"Should read boolean false as boolean %v\", v)\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(\"{\\\"a\\\": \\\"b\\\", \\\"c\\\": false \\n}\"), \"c\"); v {\n\t\tt.Errorf(\"Should read boolean false in formatted json %v\", v)\n\t}\n\n\tif v, _, _ := GetNumber([]byte(\"{\\\"a\\\": \\\"b\\\", \\\"c\\\": 1 \\n}\"), \"c\"); v != 1 {\n\t\tt.Errorf(\"Should read numberic values in formatted json %d\", v)\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(`{\"a\": \"b\", \"c\": true}`), \"c\"); !v {\n\t\tt.Errorf(\"Should read boolean true as boolean %v\", v)\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(\"{\\\"a\\\": \\\"b\\\", \\\"c\\\": true \\n}\"), \"c\"); !v {\n\t\tt.Errorf(\"Should read boolean true in formatted json %v\", v)\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(`{\"a\": \"b\", \"c\": false}`), \"c\"); v {\n\t\tt.Errorf(\"Should read boolean false as boolean %v\", v)\n\t}\n\n\tif v, _, _ := GetBoolean([]byte(\"{\\\"a\\\": \\\"b\\\", \\\"c\\\": false \\n}\"), \"c\"); v {\n\t\tt.Errorf(\"Should read boolean false in formatted json %v\", v)\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": { \"b\":{\"c\":\"d\" }}}`), \"a\", \"b\", \"c\"); !bytes.Equal(v, []byte(\"d\")) {\n\t\tt.Errorf(\"Should read composite key %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": { \"b\":{\"c\":\"d\" }}}`), \"a\", \"b\"); !bytes.Equal(v, []byte(`{\"c\":\"d\" }`)) {\n\t\tt.Errorf(\"Should read object %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"c\":\"d\" }`)); !bytes.Equal(v, []byte(`{\"c\":\"d\" }`)) {\n\t\tt.Errorf(\"Should handle empty path %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": { \"b\":[1,2,3,4]}}`), \"a\", \"b\"); !reflect.DeepEqual(toArray(v), [][]byte{[]byte(\"1\"), []byte(\"2\"), []byte(\"3\"), []byte(`4`)}) {\n\t\tt.Errorf(\"Should read array of simple values: %s, %v\", string(v), toArray(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`[1,2,3,4]`)); !reflect.DeepEqual(toArray(v), [][]byte{[]byte(\"1\"), []byte(\"2\"), []byte(\"3\"), []byte(`4`)}) {\n\t\tt.Errorf(\"Should parse array without specifying path: %s %v\", string(v), toArray(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": { \"b\":[{\"x\":1},{\"x\":2},{\"x\":3},{\"x\":4}]}}`), \"a\", \"b\"); !reflect.DeepEqual(toArray(v), [][]byte{[]byte(`{\"x\":1}`), []byte(`{\"x\":2}`), []byte(`{\"x\":3}`), []byte(`{\"x\":4}`)}) {\n\t\tt.Errorf(\"Should read array of objects %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(`{\"a\": [[[1]],[[2]]]}`), \"a\"); !reflect.DeepEqual(toArray(v), [][]byte{[]byte(\"[[1]]\"), []byte(\"[[2]]\")}) {\n\t\tt.Errorf(\"Should parse nested array %s\", string(v))\n\t}\n\n\tif v, _, _, _ := Get([]byte(\"{\\n  \\\"a\\\": \\\"b\\\"\\n}\"), \"a\"); !bytes.Equal(v, []byte(\"b\")) {\n\t\tt.Errorf(\"Should read formated json value %s\", string(v))\n\t}\n\n\tif v, _, _, e := Get([]byte(\"{\\n  \\\"a\\\":\\n    {\\n\\\"b\\\":\\n   {\\\"c\\\":\\\"d\\\",\\n\\\"e\\\": \\\"f\\\"}\\n}\\n}\"), \"a\", \"b\"); !bytes.Equal(v, []byte(\"{\\\"c\\\":\\\"d\\\",\\n\\\"e\\\": \\\"f\\\"}\")) {\n\t\tt.Errorf(\"Should read formated json object %s %v\", string(v), e)\n\t}\n}\n\nfunc TestInvalidJSON(t *testing.T) {\n\tif _, _, _, e := Get([]byte(`{\"a\":\"b\"`), \"c\"); e == nil || e.Error() != \"Key path not found\" {\n\t\tt.Errorf(\"Should not found key: %v\", e)\n\t}\n\n\tif v, _, _, e := Get([]byte(`{\"a\":\"b\"`), \"a\"); !bytes.Equal(v, []byte(\"b\")) || e != nil {\n\t\tt.Errorf(\"Should not found missing bracket, because key still found: %s\", string(v))\n\t}\n\n\tif _, _, _, e := Get([]byte(`{\"a\":\"b`), \"a\"); e == nil || e.Error() != \"Value is string, but can't find closing '\\\"' symbol\" {\n\t\tt.Errorf(\"Should raise error since end of string not found: %v\", e)\n\t}\n\n\tif v, _, _, e := Get([]byte(`{\"a\": { \"b\": \"c\"`), \"a\"); e == nil || e.Error() != \"Value looks like object, but can't find closing '}' symbol\" {\n\t\tt.Errorf(\"Should raise error if closing brace not found: %v %s\", e, string(v))\n\t}\n\n\tif v, _, _, e := Get([]byte(`{\"a\": [1, 2, 3 }`), \"a\"); e == nil || e.Error() != \"Value is array, but can't find closing ']' symbol\" {\n\t\tt.Errorf(\"Should raise error if closing bracket not found: %v %s\", e, string(v))\n\t}\n\n\tif _, _, _, e := Get([]byte(`{\"a\": `), \"a\"); e == nil || e.Error() != \"Malformed JSON error\" {\n\t\tt.Errorf(\"Should raise malformed json error: %v\", e)\n\t}\n}\n\nfunc TestTrickyJSON(t *testing.T) {\n\tkiller := []byte(`{\n          \"parentkey\": {\n            \"childkey\": {\n              \"grandchildkey\": 111\n            },\n            \"otherchildkey\": 222\n          },\n          \"bad key\\\"good key\": 333,\n        }`)\n\n\tif data, jtype, _, _ := Get(killer, \"childkey\"); jtype != NotExist {\n\t\tt.Errorf(`Get(\"childkey\") should not exist, but found data %s`, string(data))\n\t}\n\n\tif data, jtype, _, _ := Get(killer, \"parentkey\", \"childkey\", \"otherchildkey\"); jtype != NotExist {\n\t\tt.Errorf(`Get(\"parentkey\", \"childkey\", \"otherchildkey\") should not exist, but found data %s`, string(data))\n\t}\n\n\tif data, jtype, _, _ := Get(killer, \"good key\"); jtype != NotExist {\n\t\tt.Errorf(`Get(\"good key\") should not exist, but found data %s`, string(data))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package checkpostgresql\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\/\/ PostgreSQL Driver\n\t_ \"github.com\/lib\/pq\"\n\t\"github.com\/mackerelio\/checkers\"\n)\n\nvar commands = map[string](func([]string) *checkers.Checker){\n\t\"connection\": checkConnection,\n}\n\ntype postgresqlSetting struct {\n\tHost     string `short:\"H\" long:\"host\" default:\"localhost\" description:\"Hostname\"`\n\tPort     string `short:\"p\" long:\"port\" default:\"5432\" description:\"Port\"`\n\tUser     string `short:\"u\" long:\"user\" default:\"postgres\" description:\"Username\"`\n\tPassword string `short:\"P\" long:\"password\" default:\"\" description:\"Password\"`\n\tDatabase string `short:\"d\" long:\"database\" description:\"DBname\"`\n\tSSLmode  string `short:\"s\" long:\"sslmode\" default:\"disable\" description:\"SSLmode\"`\n\tTimeout  int    `short:\"t\" long:\"timeout\" default:\"5\" description:\"Maximum wait for connection, in seconds.\"`\n}\n\nfunc (p postgresqlSetting) getDriverAndDataSourceName() (string, string) {\n\tdbName := p.User\n\tif p.Database != \"\" {\n\t\tdbName = p.Database\n\t}\n\tdataSourceName := fmt.Sprintf(\"user=%s password=%s host=%s port=%s dbname=%s sslmode=%s connect_timeout=%d\", p.User, p.Password, p.Host, p.Port, dbName, p.SSLmode, p.Timeout)\n\treturn \"postgres\", dataSourceName\n}\n\nfunc separateSub(argv []string) (string, []string) {\n\tif len(argv) == 0 || strings.HasPrefix(argv[0], \"-\") {\n\t\treturn \"\", argv\n\t}\n\treturn argv[0], argv[1:]\n}\n\n\/\/ Do the plugin\nfunc Do() {\n\tsubCmd, argv := separateSub(os.Args[1:])\n\tfn, ok := commands[subCmd]\n\tif !ok {\n\t\tfmt.Println(`Usage:\n  check-postgresql [subcommand] [OPTIONS]\n\nSubCommands:`)\n\t\tfor k := range commands {\n\t\t\tfmt.Printf(\"  %s\\n\", k)\n\t\t}\n\t\tos.Exit(1)\n\t}\n\tckr := fn(argv)\n\tckr.Name = fmt.Sprintf(\"PostgreSQL %s\", strings.Title(subCmd))\n\tckr.Exit()\n}\n<commit_msg>update check-postgresql for setting password via environment variable<commit_after>package checkpostgresql\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\/\/ PostgreSQL Driver\n\t_ \"github.com\/lib\/pq\"\n\t\"github.com\/mackerelio\/checkers\"\n)\n\nvar commands = map[string](func([]string) *checkers.Checker){\n\t\"connection\": checkConnection,\n}\n\ntype postgresqlSetting struct {\n\tHost     string `short:\"H\" long:\"host\" default:\"localhost\" description:\"Hostname\"`\n\tPort     string `short:\"p\" long:\"port\" default:\"5432\" description:\"Port\"`\n\tUser     string `short:\"u\" long:\"user\" default:\"postgres\" description:\"Username\"`\n\tPassword string `short:\"P\" long:\"password\" default:\"\" description:\"Password\" env:\"PGPASSWORD\"`\n\tDatabase string `short:\"d\" long:\"database\" description:\"DBname\"`\n\tSSLmode  string `short:\"s\" long:\"sslmode\" default:\"disable\" description:\"SSLmode\"`\n\tTimeout  int    `short:\"t\" long:\"timeout\" default:\"5\" description:\"Maximum wait for connection, in seconds.\"`\n}\n\nfunc (p postgresqlSetting) getDriverAndDataSourceName() (string, string) {\n\tdbName := p.User\n\tif p.Database != \"\" {\n\t\tdbName = p.Database\n\t}\n\tdataSourceName := fmt.Sprintf(\"user=%s password=%s host=%s port=%s dbname=%s sslmode=%s connect_timeout=%d\", p.User, p.Password, p.Host, p.Port, dbName, p.SSLmode, p.Timeout)\n\treturn \"postgres\", dataSourceName\n}\n\nfunc separateSub(argv []string) (string, []string) {\n\tif len(argv) == 0 || strings.HasPrefix(argv[0], \"-\") {\n\t\treturn \"\", argv\n\t}\n\treturn argv[0], argv[1:]\n}\n\n\/\/ Do the plugin\nfunc Do() {\n\tsubCmd, argv := separateSub(os.Args[1:])\n\tfn, ok := commands[subCmd]\n\tif !ok {\n\t\tfmt.Println(`Usage:\n  check-postgresql [subcommand] [OPTIONS]\n\nSubCommands:`)\n\t\tfor k := range commands {\n\t\t\tfmt.Printf(\"  %s\\n\", k)\n\t\t}\n\t\tos.Exit(1)\n\t}\n\tckr := fn(argv)\n\tckr.Name = fmt.Sprintf(\"PostgreSQL %s\", strings.Title(subCmd))\n\tckr.Exit()\n}\n<|endoftext|>"}
{"text":"<commit_before>package maxminddb\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"reflect\"\n)\n\nconst (\n\t\/\/ NotFound is returned by LookupOffset when a matched root record offset\n\t\/\/ cannot be found.\n\tNotFound = ^uintptr(0)\n\n\tdataSectionSeparatorSize = 16\n)\n\nvar metadataStartMarker = []byte(\"\\xAB\\xCD\\xEFMaxMind.com\")\n\n\/\/ Reader holds the data corresponding to the MaxMind DB file. Its only public\n\/\/ field is Metadata, which contains the metadata from the MaxMind DB file.\ntype Reader struct {\n\thasMappedFile     bool\n\tbuffer            []byte\n\tdecoder           decoder\n\tMetadata          Metadata\n\tipv4Start         uint\n\tipv4StartBitDepth int\n}\n\n\/\/ Metadata holds the metadata decoded from the MaxMind DB file. In particular\n\/\/ in has the format version, the build time as Unix epoch time, the database\n\/\/ type and description, the IP version supported, and a slice of the natural\n\/\/ languages included.\ntype Metadata struct {\n\tBinaryFormatMajorVersion uint              `maxminddb:\"binary_format_major_version\"`\n\tBinaryFormatMinorVersion uint              `maxminddb:\"binary_format_minor_version\"`\n\tBuildEpoch               uint              `maxminddb:\"build_epoch\"`\n\tDatabaseType             string            `maxminddb:\"database_type\"`\n\tDescription              map[string]string `maxminddb:\"description\"`\n\tIPVersion                uint              `maxminddb:\"ip_version\"`\n\tLanguages                []string          `maxminddb:\"languages\"`\n\tNodeCount                uint              `maxminddb:\"node_count\"`\n\tRecordSize               uint              `maxminddb:\"record_size\"`\n}\n\n\/\/ FromBytes takes a byte slice corresponding to a MaxMind DB file and returns\n\/\/ a Reader structure or an error.\nfunc FromBytes(buffer []byte) (*Reader, error) {\n\tmetadataStart := bytes.LastIndex(buffer, metadataStartMarker)\n\n\tif metadataStart == -1 {\n\t\treturn nil, newInvalidDatabaseError(\"error opening database: invalid MaxMind DB file\")\n\t}\n\n\tmetadataStart += len(metadataStartMarker)\n\tmetadataDecoder := decoder{buffer[metadataStart:]}\n\n\tvar metadata Metadata\n\n\trvMetdata := reflect.ValueOf(&metadata)\n\t_, err := metadataDecoder.decode(0, rvMetdata, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchTreeSize := metadata.NodeCount * metadata.RecordSize \/ 4\n\tdataSectionStart := searchTreeSize + dataSectionSeparatorSize\n\tdataSectionEnd := uint(metadataStart - len(metadataStartMarker))\n\tif dataSectionStart > dataSectionEnd {\n\t\treturn nil, newInvalidDatabaseError(\"the MaxMind DB contains invalid metadata\")\n\t}\n\td := decoder{\n\t\tbuffer[searchTreeSize+dataSectionSeparatorSize : metadataStart-len(metadataStartMarker)],\n\t}\n\n\treader := &Reader{\n\t\tbuffer:    buffer,\n\t\tdecoder:   d,\n\t\tMetadata:  metadata,\n\t\tipv4Start: 0,\n\t}\n\n\terr = reader.setIPv4Start()\n\n\treturn reader, err\n}\n\nfunc (r *Reader) setIPv4Start() error {\n\tif r.Metadata.IPVersion != 6 {\n\t\treturn nil\n\t}\n\n\tnodeCount := r.Metadata.NodeCount\n\n\tnode := uint(0)\n\tvar err error\n\ti := 0\n\tfor ; i < 96 && node < nodeCount; i++ {\n\t\tnode, err = r.readNode(node, 0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tr.ipv4Start = node\n\tr.ipv4StartBitDepth = i\n\treturn err\n}\n\n\/\/ Lookup retrieves the database record for ip and stores it in the value\n\/\/ pointed to by result. If result is nil or not a pointer, an error is\n\/\/ returned. If the data in the database record cannot be stored in result\n\/\/ because of type differences, an UnmarshalTypeError is returned. If the\n\/\/ database is invalid or otherwise cannot be read, an InvalidDatabaseError\n\/\/ is returned.\nfunc (r *Reader) Lookup(ip net.IP, result interface{}) error {\n\tif r.buffer == nil {\n\t\treturn errors.New(\"cannot call Lookup on a closed database\")\n\t}\n\tpointer, _, _, err := r.lookupPointer(ip)\n\tif pointer == 0 || err != nil {\n\t\treturn err\n\t}\n\treturn r.retrieveData(pointer, result)\n}\n\n\/\/ LookupNetwork retrieves the database record for ip and stores it in the\n\/\/ value pointed to by result. The network returned is the network associated\n\/\/ with the data record in the database. The ok return value indicates whether\n\/\/ the database contained a record for the ip.\n\/\/\n\/\/ If result is nil or not a pointer, an error is returned. If the data in the\n\/\/ database record cannot be stored in result because of type differences, an\n\/\/ UnmarshalTypeError is returned. If the database is invalid or otherwise\n\/\/ cannot be read, an InvalidDatabaseError is returned.\nfunc (r *Reader) LookupNetwork(ip net.IP, result interface{}) (network *net.IPNet, ok bool, err error) {\n\tif r.buffer == nil {\n\t\treturn nil, false, errors.New(\"cannot call Lookup on a closed database\")\n\t}\n\tpointer, prefixLength, ip, err := r.lookupPointer(ip)\n\n\tnetwork = r.cidr(ip, prefixLength)\n\tif pointer == 0 || err != nil {\n\t\treturn network, false, err\n\t}\n\n\treturn network, true, r.retrieveData(pointer, result)\n}\n\n\/\/ LookupOffset maps an argument net.IP to a corresponding record offset in the\n\/\/ database. NotFound is returned if no such record is found, and a record may\n\/\/ otherwise be extracted by passing the returned offset to Decode. LookupOffset\n\/\/ is an advanced API, which exists to provide clients with a means to cache\n\/\/ previously-decoded records.\nfunc (r *Reader) LookupOffset(ip net.IP) (uintptr, error) {\n\tif r.buffer == nil {\n\t\treturn 0, errors.New(\"cannot call LookupOffset on a closed database\")\n\t}\n\tpointer, _, _, err := r.lookupPointer(ip)\n\tif pointer == 0 || err != nil {\n\t\treturn NotFound, err\n\t}\n\treturn r.resolveDataPointer(pointer)\n}\n\nfunc (r *Reader) cidr(ip net.IP, prefixLength int) *net.IPNet {\n\t\/\/ This is necessary as the node that the IPv4 start is at may\n\t\/\/ be at a bit depth that is less that 96, i.e., ipv4Start points\n\t\/\/ to a leaf node.\n\tif r.Metadata.IPVersion == 6 &&\n\t\tlen(ip) == net.IPv4len &&\n\t\tr.ipv4StartBitDepth != 96 {\n\t\treturn &net.IPNet{IP: net.ParseIP(\"::\"), Mask: net.CIDRMask(r.ipv4StartBitDepth, 128)}\n\t}\n\n\tmask := net.CIDRMask(prefixLength, len(ip)*8)\n\treturn &net.IPNet{IP: ip.Mask(mask), Mask: mask}\n}\n\n\/\/ Decode the record at |offset| into |result|. The result value pointed to\n\/\/ must be a data value that corresponds to a record in the database. This may\n\/\/ include a struct representation of the data, a map capable of holding the\n\/\/ data or an empty interface{} value.\n\/\/\n\/\/ If result is a pointer to a struct, the struct need not include a field\n\/\/ for every value that may be in the database. If a field is not present in\n\/\/ the structure, the decoder will not decode that field, reducing the time\n\/\/ required to decode the record.\n\/\/\n\/\/ As a special case, a struct field of type uintptr will be used to capture\n\/\/ the offset of the value. Decode may later be used to extract the stored\n\/\/ value from the offset. MaxMind DBs are highly normalized: for example in\n\/\/ the City database, all records of the same country will reference a\n\/\/ single representative record for that country. This uintptr behavior allows\n\/\/ clients to leverage this normalization in their own sub-record caching.\nfunc (r *Reader) Decode(offset uintptr, result interface{}) error {\n\tif r.buffer == nil {\n\t\treturn errors.New(\"cannot call Decode on a closed database\")\n\t}\n\treturn r.decode(offset, result)\n}\n\nfunc (r *Reader) decode(offset uintptr, result interface{}) error {\n\trv := reflect.ValueOf(result)\n\tif rv.Kind() != reflect.Ptr || rv.IsNil() {\n\t\treturn errors.New(\"result param must be a pointer\")\n\t}\n\n\t_, err := r.decoder.decode(uint(offset), rv, 0)\n\treturn err\n}\n\nfunc (r *Reader) lookupPointer(ip net.IP) (uint, int, net.IP, error) {\n\tif ip == nil {\n\t\treturn 0, 0, ip, errors.New(\"IP passed to Lookup cannot be nil\")\n\t}\n\n\tipV4Address := ip.To4()\n\tif ipV4Address != nil {\n\t\tip = ipV4Address\n\t}\n\tif len(ip) == 16 && r.Metadata.IPVersion == 4 {\n\t\treturn 0, 0, ip, fmt.Errorf(\"error looking up '%s': you attempted to look up an IPv6 address in an IPv4-only database\", ip.String())\n\t}\n\n\tbitCount := uint(len(ip) * 8)\n\n\tvar node uint\n\tif bitCount == 32 {\n\t\tnode = r.ipv4Start\n\t}\n\n\tnodeCount := r.Metadata.NodeCount\n\n\ti := uint(0)\n\tfor ; i < bitCount && node < nodeCount; i++ {\n\t\tbit := uint(1) & (uint(ip[i>>3]) >> (7 - (i % 8)))\n\n\t\tvar err error\n\t\tnode, err = r.readNode(node, bit)\n\t\tif err != nil {\n\t\t\treturn 0, int(i), ip, err\n\t\t}\n\t}\n\tif node == nodeCount {\n\t\t\/\/ Record is empty\n\t\treturn 0, int(i), ip, nil\n\t} else if node > nodeCount {\n\t\treturn node, int(i), ip, nil\n\t}\n\n\treturn 0, int(i), ip, newInvalidDatabaseError(\"invalid node in search tree\")\n}\n\nfunc (r *Reader) readNode(nodeNumber uint, index uint) (uint, error) {\n\tRecordSize := r.Metadata.RecordSize\n\n\tbaseOffset := nodeNumber * RecordSize \/ 4\n\n\tvar nodeBytes []byte\n\tvar prefix uint\n\tswitch RecordSize {\n\tcase 24:\n\t\toffset := baseOffset + index*3\n\t\tnodeBytes = r.buffer[offset : offset+3]\n\tcase 28:\n\t\tprefix = uint(r.buffer[baseOffset+3])\n\t\tif index != 0 {\n\t\t\tprefix &= 0x0F\n\t\t} else {\n\t\t\tprefix = (0xF0 & prefix) >> 4\n\t\t}\n\t\toffset := baseOffset + index*4\n\t\tnodeBytes = r.buffer[offset : offset+3]\n\tcase 32:\n\t\toffset := baseOffset + index*4\n\t\tnodeBytes = r.buffer[offset : offset+4]\n\tdefault:\n\t\treturn 0, newInvalidDatabaseError(\"unknown record size: %d\", RecordSize)\n\t}\n\treturn uintFromBytes(prefix, nodeBytes), nil\n}\n\nfunc (r *Reader) retrieveData(pointer uint, result interface{}) error {\n\toffset, err := r.resolveDataPointer(pointer)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn r.decode(offset, result)\n}\n\nfunc (r *Reader) resolveDataPointer(pointer uint) (uintptr, error) {\n\tvar resolved = uintptr(pointer - r.Metadata.NodeCount - dataSectionSeparatorSize)\n\n\tif resolved > uintptr(len(r.buffer)) {\n\t\treturn 0, newInvalidDatabaseError(\"the MaxMind DB file's search tree is corrupt\")\n\t}\n\treturn resolved, nil\n}\n<commit_msg>Try to clarify comment on IPv4 start bit depth<commit_after>package maxminddb\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"reflect\"\n)\n\nconst (\n\t\/\/ NotFound is returned by LookupOffset when a matched root record offset\n\t\/\/ cannot be found.\n\tNotFound = ^uintptr(0)\n\n\tdataSectionSeparatorSize = 16\n)\n\nvar metadataStartMarker = []byte(\"\\xAB\\xCD\\xEFMaxMind.com\")\n\n\/\/ Reader holds the data corresponding to the MaxMind DB file. Its only public\n\/\/ field is Metadata, which contains the metadata from the MaxMind DB file.\ntype Reader struct {\n\thasMappedFile     bool\n\tbuffer            []byte\n\tdecoder           decoder\n\tMetadata          Metadata\n\tipv4Start         uint\n\tipv4StartBitDepth int\n}\n\n\/\/ Metadata holds the metadata decoded from the MaxMind DB file. In particular\n\/\/ in has the format version, the build time as Unix epoch time, the database\n\/\/ type and description, the IP version supported, and a slice of the natural\n\/\/ languages included.\ntype Metadata struct {\n\tBinaryFormatMajorVersion uint              `maxminddb:\"binary_format_major_version\"`\n\tBinaryFormatMinorVersion uint              `maxminddb:\"binary_format_minor_version\"`\n\tBuildEpoch               uint              `maxminddb:\"build_epoch\"`\n\tDatabaseType             string            `maxminddb:\"database_type\"`\n\tDescription              map[string]string `maxminddb:\"description\"`\n\tIPVersion                uint              `maxminddb:\"ip_version\"`\n\tLanguages                []string          `maxminddb:\"languages\"`\n\tNodeCount                uint              `maxminddb:\"node_count\"`\n\tRecordSize               uint              `maxminddb:\"record_size\"`\n}\n\n\/\/ FromBytes takes a byte slice corresponding to a MaxMind DB file and returns\n\/\/ a Reader structure or an error.\nfunc FromBytes(buffer []byte) (*Reader, error) {\n\tmetadataStart := bytes.LastIndex(buffer, metadataStartMarker)\n\n\tif metadataStart == -1 {\n\t\treturn nil, newInvalidDatabaseError(\"error opening database: invalid MaxMind DB file\")\n\t}\n\n\tmetadataStart += len(metadataStartMarker)\n\tmetadataDecoder := decoder{buffer[metadataStart:]}\n\n\tvar metadata Metadata\n\n\trvMetdata := reflect.ValueOf(&metadata)\n\t_, err := metadataDecoder.decode(0, rvMetdata, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchTreeSize := metadata.NodeCount * metadata.RecordSize \/ 4\n\tdataSectionStart := searchTreeSize + dataSectionSeparatorSize\n\tdataSectionEnd := uint(metadataStart - len(metadataStartMarker))\n\tif dataSectionStart > dataSectionEnd {\n\t\treturn nil, newInvalidDatabaseError(\"the MaxMind DB contains invalid metadata\")\n\t}\n\td := decoder{\n\t\tbuffer[searchTreeSize+dataSectionSeparatorSize : metadataStart-len(metadataStartMarker)],\n\t}\n\n\treader := &Reader{\n\t\tbuffer:    buffer,\n\t\tdecoder:   d,\n\t\tMetadata:  metadata,\n\t\tipv4Start: 0,\n\t}\n\n\terr = reader.setIPv4Start()\n\n\treturn reader, err\n}\n\nfunc (r *Reader) setIPv4Start() error {\n\tif r.Metadata.IPVersion != 6 {\n\t\treturn nil\n\t}\n\n\tnodeCount := r.Metadata.NodeCount\n\n\tnode := uint(0)\n\tvar err error\n\ti := 0\n\tfor ; i < 96 && node < nodeCount; i++ {\n\t\tnode, err = r.readNode(node, 0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tr.ipv4Start = node\n\tr.ipv4StartBitDepth = i\n\treturn err\n}\n\n\/\/ Lookup retrieves the database record for ip and stores it in the value\n\/\/ pointed to by result. If result is nil or not a pointer, an error is\n\/\/ returned. If the data in the database record cannot be stored in result\n\/\/ because of type differences, an UnmarshalTypeError is returned. If the\n\/\/ database is invalid or otherwise cannot be read, an InvalidDatabaseError\n\/\/ is returned.\nfunc (r *Reader) Lookup(ip net.IP, result interface{}) error {\n\tif r.buffer == nil {\n\t\treturn errors.New(\"cannot call Lookup on a closed database\")\n\t}\n\tpointer, _, _, err := r.lookupPointer(ip)\n\tif pointer == 0 || err != nil {\n\t\treturn err\n\t}\n\treturn r.retrieveData(pointer, result)\n}\n\n\/\/ LookupNetwork retrieves the database record for ip and stores it in the\n\/\/ value pointed to by result. The network returned is the network associated\n\/\/ with the data record in the database. The ok return value indicates whether\n\/\/ the database contained a record for the ip.\n\/\/\n\/\/ If result is nil or not a pointer, an error is returned. If the data in the\n\/\/ database record cannot be stored in result because of type differences, an\n\/\/ UnmarshalTypeError is returned. If the database is invalid or otherwise\n\/\/ cannot be read, an InvalidDatabaseError is returned.\nfunc (r *Reader) LookupNetwork(ip net.IP, result interface{}) (network *net.IPNet, ok bool, err error) {\n\tif r.buffer == nil {\n\t\treturn nil, false, errors.New(\"cannot call Lookup on a closed database\")\n\t}\n\tpointer, prefixLength, ip, err := r.lookupPointer(ip)\n\n\tnetwork = r.cidr(ip, prefixLength)\n\tif pointer == 0 || err != nil {\n\t\treturn network, false, err\n\t}\n\n\treturn network, true, r.retrieveData(pointer, result)\n}\n\n\/\/ LookupOffset maps an argument net.IP to a corresponding record offset in the\n\/\/ database. NotFound is returned if no such record is found, and a record may\n\/\/ otherwise be extracted by passing the returned offset to Decode. LookupOffset\n\/\/ is an advanced API, which exists to provide clients with a means to cache\n\/\/ previously-decoded records.\nfunc (r *Reader) LookupOffset(ip net.IP) (uintptr, error) {\n\tif r.buffer == nil {\n\t\treturn 0, errors.New(\"cannot call LookupOffset on a closed database\")\n\t}\n\tpointer, _, _, err := r.lookupPointer(ip)\n\tif pointer == 0 || err != nil {\n\t\treturn NotFound, err\n\t}\n\treturn r.resolveDataPointer(pointer)\n}\n\nfunc (r *Reader) cidr(ip net.IP, prefixLength int) *net.IPNet {\n\t\/\/ This is necessary as the node that the IPv4 start is at may\n\t\/\/ be at a bit depth that is less that 96, i.e., ipv4Start points\n\t\/\/ to a leaf node. For instance, if a record was inserted at ::\/8,\n\t\/\/ the ipv4Start would point directly at the leaf node for the\n\t\/\/ record and would have a bit depth of 8. This would not happen\n\t\/\/ with databases currently distributed by MaxMind as all of them\n\t\/\/ have an IPv4 subtree that is greater than a single node.\n\tif r.Metadata.IPVersion == 6 &&\n\t\tlen(ip) == net.IPv4len &&\n\t\tr.ipv4StartBitDepth != 96 {\n\t\treturn &net.IPNet{IP: net.ParseIP(\"::\"), Mask: net.CIDRMask(r.ipv4StartBitDepth, 128)}\n\t}\n\n\tmask := net.CIDRMask(prefixLength, len(ip)*8)\n\treturn &net.IPNet{IP: ip.Mask(mask), Mask: mask}\n}\n\n\/\/ Decode the record at |offset| into |result|. The result value pointed to\n\/\/ must be a data value that corresponds to a record in the database. This may\n\/\/ include a struct representation of the data, a map capable of holding the\n\/\/ data or an empty interface{} value.\n\/\/\n\/\/ If result is a pointer to a struct, the struct need not include a field\n\/\/ for every value that may be in the database. If a field is not present in\n\/\/ the structure, the decoder will not decode that field, reducing the time\n\/\/ required to decode the record.\n\/\/\n\/\/ As a special case, a struct field of type uintptr will be used to capture\n\/\/ the offset of the value. Decode may later be used to extract the stored\n\/\/ value from the offset. MaxMind DBs are highly normalized: for example in\n\/\/ the City database, all records of the same country will reference a\n\/\/ single representative record for that country. This uintptr behavior allows\n\/\/ clients to leverage this normalization in their own sub-record caching.\nfunc (r *Reader) Decode(offset uintptr, result interface{}) error {\n\tif r.buffer == nil {\n\t\treturn errors.New(\"cannot call Decode on a closed database\")\n\t}\n\treturn r.decode(offset, result)\n}\n\nfunc (r *Reader) decode(offset uintptr, result interface{}) error {\n\trv := reflect.ValueOf(result)\n\tif rv.Kind() != reflect.Ptr || rv.IsNil() {\n\t\treturn errors.New(\"result param must be a pointer\")\n\t}\n\n\t_, err := r.decoder.decode(uint(offset), rv, 0)\n\treturn err\n}\n\nfunc (r *Reader) lookupPointer(ip net.IP) (uint, int, net.IP, error) {\n\tif ip == nil {\n\t\treturn 0, 0, ip, errors.New(\"IP passed to Lookup cannot be nil\")\n\t}\n\n\tipV4Address := ip.To4()\n\tif ipV4Address != nil {\n\t\tip = ipV4Address\n\t}\n\tif len(ip) == 16 && r.Metadata.IPVersion == 4 {\n\t\treturn 0, 0, ip, fmt.Errorf(\"error looking up '%s': you attempted to look up an IPv6 address in an IPv4-only database\", ip.String())\n\t}\n\n\tbitCount := uint(len(ip) * 8)\n\n\tvar node uint\n\tif bitCount == 32 {\n\t\tnode = r.ipv4Start\n\t}\n\n\tnodeCount := r.Metadata.NodeCount\n\n\ti := uint(0)\n\tfor ; i < bitCount && node < nodeCount; i++ {\n\t\tbit := uint(1) & (uint(ip[i>>3]) >> (7 - (i % 8)))\n\n\t\tvar err error\n\t\tnode, err = r.readNode(node, bit)\n\t\tif err != nil {\n\t\t\treturn 0, int(i), ip, err\n\t\t}\n\t}\n\tif node == nodeCount {\n\t\t\/\/ Record is empty\n\t\treturn 0, int(i), ip, nil\n\t} else if node > nodeCount {\n\t\treturn node, int(i), ip, nil\n\t}\n\n\treturn 0, int(i), ip, newInvalidDatabaseError(\"invalid node in search tree\")\n}\n\nfunc (r *Reader) readNode(nodeNumber uint, index uint) (uint, error) {\n\tRecordSize := r.Metadata.RecordSize\n\n\tbaseOffset := nodeNumber * RecordSize \/ 4\n\n\tvar nodeBytes []byte\n\tvar prefix uint\n\tswitch RecordSize {\n\tcase 24:\n\t\toffset := baseOffset + index*3\n\t\tnodeBytes = r.buffer[offset : offset+3]\n\tcase 28:\n\t\tprefix = uint(r.buffer[baseOffset+3])\n\t\tif index != 0 {\n\t\t\tprefix &= 0x0F\n\t\t} else {\n\t\t\tprefix = (0xF0 & prefix) >> 4\n\t\t}\n\t\toffset := baseOffset + index*4\n\t\tnodeBytes = r.buffer[offset : offset+3]\n\tcase 32:\n\t\toffset := baseOffset + index*4\n\t\tnodeBytes = r.buffer[offset : offset+4]\n\tdefault:\n\t\treturn 0, newInvalidDatabaseError(\"unknown record size: %d\", RecordSize)\n\t}\n\treturn uintFromBytes(prefix, nodeBytes), nil\n}\n\nfunc (r *Reader) retrieveData(pointer uint, result interface{}) error {\n\toffset, err := r.resolveDataPointer(pointer)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn r.decode(offset, result)\n}\n\nfunc (r *Reader) resolveDataPointer(pointer uint) (uintptr, error) {\n\tvar resolved = uintptr(pointer - r.Metadata.NodeCount - dataSectionSeparatorSize)\n\n\tif resolved > uintptr(len(r.buffer)) {\n\t\treturn 0, newInvalidDatabaseError(\"the MaxMind DB file's search tree is corrupt\")\n\t}\n\treturn resolved, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package iso9660\n\nimport (\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"github.com\/c4milo\/gotoolkit\"\n)\n\nvar (\n\t\/\/ ErrInvalidImage is returned when an attempt to unpack the image Primary Volume Descriptor failed or\n\t\/\/ when the end of the image was reached without finding a primary volume descriptor\n\tErrInvalidImage = func(err error) error { return fmt.Errorf(\"invalid-iso9660-image: %s\", err) }\n\t\/\/ ErrCorruptedImage is returned when a seek operation, on the image, failed.\n\tErrCorruptedImage = func(err error) error { return fmt.Errorf(\"corrupted-image: %s\", err) }\n)\n\n\/\/ Reader defines the state of the ISO9660 image reader. It needs to be instantiated\n\/\/ from its constructor.\ntype Reader struct {\n\t\/\/ File descriptor to the opened ISO image\n\timage io.ReadSeeker\n\t\/\/ Copy of unencoded Primary Volume Descriptor\n\tpvd PrimaryVolume\n\t\/\/ Queue used to walk through file system iteratively\n\tqueue gotoolkit.Queue\n\t\/\/ Current sector\n\tsector uint32\n\t\/\/ Current bytes read from current sector.\n\tread uint32\n}\n\n\/\/ NewReader creates a new ISO9660 reader.\nfunc NewReader(rs io.ReadSeeker) (*Reader, error) {\n\t\/\/ Starts reading from image data area\n\tsector := dataAreaSector\n\t\/\/ Iterates over volume descriptors until it finds the primary volume descriptor\n\t\/\/ or an error condition.\n\tfor {\n\t\toffset, err := rs.Seek(int64(sector*sectorSize), os.SEEK_SET)\n\t\tif err != nil {\n\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t}\n\n\t\tvar volDesc VolumeDescriptor\n\t\tif err := binary.Read(rs, binary.BigEndian, &volDesc); err != nil {\n\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t}\n\n\t\tif volDesc.Type == primaryVol {\n\t\t\t\/\/ backs up to the beginning of the sector again in order to unpack\n\t\t\t\/\/ the entire primary volume descriptor more easily.\n\t\t\tif _, err := rs.Seek(offset, os.SEEK_SET); err != nil {\n\t\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t\t}\n\n\t\t\treader := new(Reader)\n\t\t\treader.image = rs\n\t\t\treader.queue = new(gotoolkit.SliceQueue)\n\n\t\t\tif err := reader.unpackPVD(); err != nil {\n\t\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t\t}\n\n\t\t\treturn reader, nil\n\t\t}\n\n\t\tif volDesc.Type == volSetTerminator {\n\t\t\treturn nil, ErrInvalidImage(errors.New(\"Volume Set Terminator reached. A Primary Volume Descriptor was not found.\"))\n\t\t}\n\t\tsector++\n\t}\n}\n\n\/\/ Next moves onto the next directory record using breadth-first search one step\n\/\/ at the time. It first moves\nfunc (r *Reader) Next() (os.FileInfo, error) {\n\tif r == nil {\n\t\tpanic(\"missing reader instance. Use the constructor to create a Reader instance.\")\n\t}\n\n\tif r.queue.IsEmpty() {\n\t\treturn nil, io.EOF\n\t}\n\n\t\/\/ We only dequeue the directory when it does not contain more children\n\t\/\/ or when it is empty and there is no children to iterate over.\n\titem, err := r.queue.Peek()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfi := item.(FileStat)\n\n\tif r.sector == 0 {\n\t\tr.sector = fi.ExtentLocationBE\n\t}\n\n\tvar drecord FileStat\n\tvar len byte\n\t\/\/ This loops exists so we can skip .. and . directories\n\tfor {\n\t\tif (r.read % sectorSize) == 0 {\n\t\t\t_, err := r.image.Seek(int64(r.sector*sectorSize), os.SEEK_SET)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t\t}\n\t\t\tr.sector++\n\t\t}\n\n\t\tif len, err = r.unpackDRecord(&drecord); err != nil && err != io.EOF {\n\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t}\n\n\t\tif err == io.EOF {\n\t\t\t\/\/ directory record is empty, sector wasted, move onto next sector.\n\t\t\trsize := (sectorSize - (r.read % sectorSize))\n\t\t\tbuf := make([]byte, rsize)\n\t\t\tif err := binary.Read(r.image, binary.BigEndian, buf); err != nil {\n\t\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t\t}\n\t\t\tr.read += rsize\n\t\t}\n\t\tr.read += uint32(len)\n\n\t\tif drecord.fileID != \"\\x00\" && drecord.fileID != \"\\x01\" {\n\t\t\tbreak\n\t\t}\n\t}\n\t\/\/ If there is no more entries in the current directory, dequeue it\n\t\/\/ and move on the next directory in the queue.\n\tif r.read > fi.ExtentLengthBE {\n\t\tr.read = 0\n\t\tr.sector = 0\n\t\tr.queue.Dequeue()\n\t}\n\n\tif drecord.fileID == \"\" {\n\t\treturn r.Next()\n\t}\n\n\tif drecord.IsDir() {\n\t\tr.queue.Enqueue(drecord)\n\t} else {\n\t\tdrecord.image = r.image\n\t}\n\n\treturn &drecord, nil\n}\n\n\/\/ unpackDRecord unpacks directory record bits into Go's struct\nfunc (r *Reader) unpackDRecord(fi *FileStat) (byte, error) {\n\t\/\/ Gets the directory record length\n\tvar len byte\n\tif err := binary.Read(r.image, binary.BigEndian, &len); err != nil {\n\t\treturn len, ErrCorruptedImage(err)\n\t}\n\n\tif len == 0 {\n\t\treturn len + 1, io.EOF\n\t}\n\n\t\/\/ Reads directory record into Go struct\n\tvar drecord DirectoryRecord\n\tif err := binary.Read(r.image, binary.BigEndian, &drecord); err != nil {\n\t\treturn len, ErrCorruptedImage(err)\n\t}\n\n\tfi.DirectoryRecord = drecord\n\t\/\/ Gets the name\n\tname := make([]byte, drecord.FileIDLength)\n\tif err := binary.Read(r.image, binary.BigEndian, name); err != nil {\n\t\treturn len, ErrCorruptedImage(err)\n\t}\n\tfi.fileID = string(name)\n\n\t\/\/ Padding field as per section 9.1.12 in ECMA-119\n\tif (drecord.FileIDLength % 2) == 0 {\n\t\tvar zero byte\n\t\tif err := binary.Read(r.image, binary.BigEndian, &zero); err != nil {\n\t\t\treturn len, ErrCorruptedImage(err)\n\t\t}\n\t}\n\n\t\/\/ System use field as per section 9.1.13 in ECMA-119\n\t\/\/ Directory record has 34 bytes in addition to the name's\n\t\/\/ variable length and the padding field mentioned in section 9.1.12\n\ttotalLen := 34 + drecord.FileIDLength - (drecord.FileIDLength % 2)\n\tsysUseLen := int64(len - totalLen)\n\tif sysUseLen > 0 {\n\t\tsysData := make([]byte, sysUseLen)\n\t\tif err := binary.Read(r.image, binary.BigEndian, sysData); err != nil {\n\t\t\treturn len, ErrCorruptedImage(err)\n\t\t}\n\t}\n\treturn len, nil\n}\n\n\/\/ unpackPVD unpacks Primary Volume Descriptor in three phases. This is\n\/\/ because the root directory record is a variable-length record and Go's binary\n\/\/ package doesn't support unpacking variable-length structs easily.\nfunc (r *Reader) unpackPVD() error {\n\t\/\/ Unpack first half\n\tvar pvd1 PrimaryVolumePart1\n\tif err := binary.Read(r.image, binary.BigEndian, &pvd1); err != nil {\n\t\treturn ErrCorruptedImage(err)\n\t}\n\tr.pvd.PrimaryVolumePart1 = pvd1\n\n\t\/\/ Unpack root directory record\n\tvar drecord FileStat\n\tif _, err := r.unpackDRecord(&drecord); err != nil {\n\t\treturn ErrCorruptedImage(err)\n\t}\n\tr.pvd.DirectoryRecord = drecord.DirectoryRecord\n\tr.queue.Enqueue(drecord)\n\n\t\/\/ Unpack second half\n\tvar pvd2 PrimaryVolumePart2\n\tif err := binary.Read(r.image, binary.BigEndian, &pvd2); err != nil {\n\t\treturn ErrCorruptedImage(err)\n\t}\n\tr.pvd.PrimaryVolumePart2 = pvd2\n\n\treturn nil\n}\n<commit_msg>Renames dir records so they contain full file path<commit_after>package iso9660\n\nimport (\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/c4milo\/gotoolkit\"\n)\n\nvar (\n\t\/\/ ErrInvalidImage is returned when an attempt to unpack the image Primary Volume Descriptor failed or\n\t\/\/ when the end of the image was reached without finding a primary volume descriptor\n\tErrInvalidImage = func(err error) error { return fmt.Errorf(\"invalid-iso9660-image: %s\", err) }\n\t\/\/ ErrCorruptedImage is returned when a seek operation, on the image, failed.\n\tErrCorruptedImage = func(err error) error { return fmt.Errorf(\"corrupted-image: %s\", err) }\n)\n\n\/\/ Reader defines the state of the ISO9660 image reader. It needs to be instantiated\n\/\/ from its constructor.\ntype Reader struct {\n\t\/\/ File descriptor to the opened ISO image\n\timage io.ReadSeeker\n\t\/\/ Copy of unencoded Primary Volume Descriptor\n\tpvd PrimaryVolume\n\t\/\/ Queue used to walk through file system iteratively\n\tqueue gotoolkit.Queue\n\t\/\/ Current sector\n\tsector uint32\n\t\/\/ Current bytes read from current sector.\n\tread uint32\n}\n\n\/\/ NewReader creates a new ISO9660 reader.\nfunc NewReader(rs io.ReadSeeker) (*Reader, error) {\n\t\/\/ Starts reading from image data area\n\tsector := dataAreaSector\n\t\/\/ Iterates over volume descriptors until it finds the primary volume descriptor\n\t\/\/ or an error condition.\n\tfor {\n\t\toffset, err := rs.Seek(int64(sector*sectorSize), os.SEEK_SET)\n\t\tif err != nil {\n\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t}\n\n\t\tvar volDesc VolumeDescriptor\n\t\tif err := binary.Read(rs, binary.BigEndian, &volDesc); err != nil {\n\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t}\n\n\t\tif volDesc.Type == primaryVol {\n\t\t\t\/\/ backs up to the beginning of the sector again in order to unpack\n\t\t\t\/\/ the entire primary volume descriptor more easily.\n\t\t\tif _, err := rs.Seek(offset, os.SEEK_SET); err != nil {\n\t\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t\t}\n\n\t\t\treader := new(Reader)\n\t\t\treader.image = rs\n\t\t\treader.queue = new(gotoolkit.SliceQueue)\n\n\t\t\tif err := reader.unpackPVD(); err != nil {\n\t\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t\t}\n\n\t\t\treturn reader, nil\n\t\t}\n\n\t\tif volDesc.Type == volSetTerminator {\n\t\t\treturn nil, ErrInvalidImage(errors.New(\"Volume Set Terminator reached. A Primary Volume Descriptor was not found.\"))\n\t\t}\n\t\tsector++\n\t}\n}\n\n\/\/ Next moves onto the next directory record.\nfunc (r *Reader) Next() (os.FileInfo, error) {\n\tif r == nil {\n\t\tpanic(\"missing reader instance. Use the constructor to create a Reader instance.\")\n\t}\n\n\tif r.queue.IsEmpty() {\n\t\treturn nil, io.EOF\n\t}\n\n\t\/\/ We only dequeue the directory when it does not contain more children\n\t\/\/ or when it is empty and there is no children to iterate over.\n\titem, err := r.queue.Peek()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfi := item.(FileStat)\n\n\tif r.sector == 0 {\n\t\tr.sector = fi.ExtentLocationBE\n\t}\n\n\tvar drecord FileStat\n\tvar len byte\n\t\/\/ This loops exists so we can skip .. and . directories\n\tfor {\n\t\tif (r.read % sectorSize) == 0 {\n\t\t\t_, err := r.image.Seek(int64(r.sector*sectorSize), os.SEEK_SET)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t\t}\n\t\t\tr.sector++\n\t\t}\n\n\t\tif len, err = r.unpackDRecord(&drecord); err != nil && err != io.EOF {\n\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t}\n\n\t\tif err == io.EOF {\n\t\t\t\/\/ directory record is empty, sector space wasted, move onto next sector.\n\t\t\trsize := (sectorSize - (r.read % sectorSize))\n\t\t\tbuf := make([]byte, rsize)\n\t\t\tif err := binary.Read(r.image, binary.BigEndian, buf); err != nil {\n\t\t\t\treturn nil, ErrCorruptedImage(err)\n\t\t\t}\n\t\t\tr.read += rsize\n\t\t}\n\t\tr.read += uint32(len)\n\n\t\tif drecord.fileID != \"\\x00\" && drecord.fileID != \"\\x01\" {\n\t\t\tbreak\n\t\t}\n\t}\n\t\/\/ If there is no more entries in the current directory, dequeue it\n\t\/\/ and move on the next directory in the queue.\n\tif r.read > fi.ExtentLengthBE {\n\t\tr.read = 0\n\t\tr.sector = 0\n\t\tr.queue.Dequeue()\n\t}\n\n\tif drecord.fileID == \"\" {\n\t\treturn r.Next()\n\t}\n\n\tif drecord.IsDir() {\n\t\tparent := fi.Name()\n\t\tif parent == \"\\x00\" {\n\t\t\tparent = \"\/\"\n\t\t}\n\t\tdrecord.fileID = filepath.Join(parent, drecord.fileID)\n\n\t\tr.queue.Enqueue(drecord)\n\t} else {\n\t\tdrecord.image = r.image\n\t}\n\n\treturn &drecord, nil\n}\n\n\/\/ unpackDRecord unpacks directory record bits into Go's struct\nfunc (r *Reader) unpackDRecord(fi *FileStat) (byte, error) {\n\t\/\/ Gets the directory record length\n\tvar len byte\n\tif err := binary.Read(r.image, binary.BigEndian, &len); err != nil {\n\t\treturn len, ErrCorruptedImage(err)\n\t}\n\n\tif len == 0 {\n\t\treturn len + 1, io.EOF\n\t}\n\n\t\/\/ Reads directory record into Go struct\n\tvar drecord DirectoryRecord\n\tif err := binary.Read(r.image, binary.BigEndian, &drecord); err != nil {\n\t\treturn len, ErrCorruptedImage(err)\n\t}\n\n\tfi.DirectoryRecord = drecord\n\t\/\/ Gets the name\n\tname := make([]byte, drecord.FileIDLength)\n\tif err := binary.Read(r.image, binary.BigEndian, name); err != nil {\n\t\treturn len, ErrCorruptedImage(err)\n\t}\n\tfi.fileID = string(name)\n\n\t\/\/ Padding field as per section 9.1.12 in ECMA-119\n\tif (drecord.FileIDLength % 2) == 0 {\n\t\tvar zero byte\n\t\tif err := binary.Read(r.image, binary.BigEndian, &zero); err != nil {\n\t\t\treturn len, ErrCorruptedImage(err)\n\t\t}\n\t}\n\n\t\/\/ System use field as per section 9.1.13 in ECMA-119\n\t\/\/ Directory record has 34 bytes in addition to the name's\n\t\/\/ variable length and the padding field mentioned in section 9.1.12\n\ttotalLen := 34 + drecord.FileIDLength - (drecord.FileIDLength % 2)\n\tsysUseLen := int64(len - totalLen)\n\tif sysUseLen > 0 {\n\t\tsysData := make([]byte, sysUseLen)\n\t\tif err := binary.Read(r.image, binary.BigEndian, sysData); err != nil {\n\t\t\treturn len, ErrCorruptedImage(err)\n\t\t}\n\t}\n\treturn len, nil\n}\n\n\/\/ unpackPVD unpacks Primary Volume Descriptor in three phases. This is\n\/\/ because the root directory record is a variable-length record and Go's binary\n\/\/ package doesn't support unpacking variable-length structs easily.\nfunc (r *Reader) unpackPVD() error {\n\t\/\/ Unpack first half\n\tvar pvd1 PrimaryVolumePart1\n\tif err := binary.Read(r.image, binary.BigEndian, &pvd1); err != nil {\n\t\treturn ErrCorruptedImage(err)\n\t}\n\tr.pvd.PrimaryVolumePart1 = pvd1\n\n\t\/\/ Unpack root directory record\n\tvar drecord FileStat\n\tif _, err := r.unpackDRecord(&drecord); err != nil {\n\t\treturn ErrCorruptedImage(err)\n\t}\n\tr.pvd.DirectoryRecord = drecord.DirectoryRecord\n\tr.queue.Enqueue(drecord)\n\n\t\/\/ Unpack second half\n\tvar pvd2 PrimaryVolumePart2\n\tif err := binary.Read(r.image, binary.BigEndian, &pvd2); err != nil {\n\t\treturn ErrCorruptedImage(err)\n\t}\n\tr.pvd.PrimaryVolumePart2 = pvd2\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package vsphere\n\nconst (\n\tBaseOps = `---\n- type: replace\n  path: \/azs\n  value:\n  - name: z1\n    cloud_properties:\n      datacenters:\n      - name: ((vcenter_dc))\n        clusters:\n        - ((vcenter_cluster)):\n            resource_pool: ((vcenter_rp))\n  - name: z2\n    cloud_properties:\n      datacenters:\n      - name: ((vcenter_dc))\n        clusters:\n        - ((vcenter_cluster)):\n            resource_pool: ((vcenter_rp))\n  - name: z3\n    cloud_properties:\n      datacenters:\n      - name: ((vcenter_dc))\n        clusters:\n        - ((vcenter_cluster)):\n            resource_pool: ((vcenter_rp))\n\n- type: replace\n  path: \/compilation\n  value:\n    workers: 5\n    reuse_compilation_vms: true\n    az: z1\n    vm_type: default\n    network: default\n\n- type: replace\n  path: \/disk_types\/name=default\/disk_size?\n  value: 3000\n\n- type: replace\n  path: \/networks\n  value:\n  - name: default\n    type: manual\n    subnets:\n    - range: ((internal_cidr))\n      gateway: ((internal_gw))\n      azs: [z1, z2, z3]\n      dns: [8.8.8.8]\n      reserved: [((jumpbox__internal_ip))]\n      cloud_properties:\n        name: ((network_name))\n\n- type: replace\n  path: \/vm_types\/name=default\/cloud_properties?\n  value:\n    cpu: 2\n    ram: 8_192\n    disk: 30_000\n\n- type: replace\n  path: \/vm_types\/name=large\/cloud_properties?\n  value:\n    cpu: 2\n    ram: 8_192\n    disk: 640_000\n\n- type: replace\n  path: \/vm_types\/name=minimal\/cloud_properties?\n  value:\n    cpu: 1\n    ram: 4096\n    disk: 10240\n\n- type: replace\n  path: \/vm_types\/name=small\/cloud_properties?\n  value:\n    cpu: 2\n    ram: 8192\n    disk: 10240\n\n- type: replace\n  path: \/vm_types\/name=small-highmem\/cloud_properties?\n  value:\n    cpu: 4\n    ram: 32768\n    disk: 10240\n\n- type: replace\n  path: \/vm_extensions\/name=50GB_ephemeral_disk\/cloud_properties?\n  value:\n    disk: 51200\n\n- type: replace\n  path: \/vm_extensions\/name=100GB_ephemeral_disk\/cloud_properties?\n  value:\n    disk: 102400\n\n- type: replace\n  path: \/vm_extensions\/-\n  value:\n    name: cf-router-network-properties\n\n- type: replace\n  path: \/vm_extensions\/-\n  value:\n    name: cf-tcp-router-network-properties\n\n- type: replace\n  path: \/vm_extensions\/-\n  value:\n    name: diego-ssh-proxy-network-properties\n`\n)\n<commit_msg>Add disk value for 500 GB ephemeral disk vm extension for vsphere<commit_after>package vsphere\n\nconst (\n\tBaseOps = `---\n- type: replace\n  path: \/azs\n  value:\n  - name: z1\n    cloud_properties:\n      datacenters:\n      - name: ((vcenter_dc))\n        clusters:\n        - ((vcenter_cluster)):\n            resource_pool: ((vcenter_rp))\n  - name: z2\n    cloud_properties:\n      datacenters:\n      - name: ((vcenter_dc))\n        clusters:\n        - ((vcenter_cluster)):\n            resource_pool: ((vcenter_rp))\n  - name: z3\n    cloud_properties:\n      datacenters:\n      - name: ((vcenter_dc))\n        clusters:\n        - ((vcenter_cluster)):\n            resource_pool: ((vcenter_rp))\n\n- type: replace\n  path: \/compilation\n  value:\n    workers: 5\n    reuse_compilation_vms: true\n    az: z1\n    vm_type: default\n    network: default\n\n- type: replace\n  path: \/disk_types\/name=default\/disk_size?\n  value: 3000\n\n- type: replace\n  path: \/networks\n  value:\n  - name: default\n    type: manual\n    subnets:\n    - range: ((internal_cidr))\n      gateway: ((internal_gw))\n      azs: [z1, z2, z3]\n      dns: [8.8.8.8]\n      reserved: [((jumpbox__internal_ip))]\n      cloud_properties:\n        name: ((network_name))\n\n- type: replace\n  path: \/vm_types\/name=default\/cloud_properties?\n  value:\n    cpu: 2\n    ram: 8_192\n    disk: 30_000\n\n- type: replace\n  path: \/vm_types\/name=large\/cloud_properties?\n  value:\n    cpu: 2\n    ram: 8_192\n    disk: 640_000\n\n- type: replace\n  path: \/vm_types\/name=minimal\/cloud_properties?\n  value:\n    cpu: 1\n    ram: 4096\n    disk: 10240\n\n- type: replace\n  path: \/vm_types\/name=small\/cloud_properties?\n  value:\n    cpu: 2\n    ram: 8192\n    disk: 10240\n\n- type: replace\n  path: \/vm_types\/name=small-highmem\/cloud_properties?\n  value:\n    cpu: 4\n    ram: 32768\n    disk: 10240\n\n- type: replace\n  path: \/vm_extensions\/name=50GB_ephemeral_disk\/cloud_properties?\n  value:\n    disk: 51200\n\n- type: replace\n  path: \/vm_extensions\/name=100GB_ephemeral_disk\/cloud_properties?\n  value:\n    disk: 102400\n\n- type: replace\n  path: \/vm_extensions\/name=500GB_ephemeral_disk\/cloud_properties?\n  value:\n    disk: 512000\n\n- type: replace\n  path: \/vm_extensions\/-\n  value:\n    name: cf-router-network-properties\n\n- type: replace\n  path: \/vm_extensions\/-\n  value:\n    name: cf-tcp-router-network-properties\n\n- type: replace\n  path: \/vm_extensions\/-\n  value:\n    name: diego-ssh-proxy-network-properties\n`\n)\n<|endoftext|>"}
{"text":"<commit_before>package blockscore\n\nimport \"testing\"\n\nfunc init() {\n\t\/\/ In order to execute the Unit Test, you must set your BlockScore\n\t\/\/ API key as environment variable: BLOCKSCORE_API_KEY=xxxx\n\tif err := SetKeyEnv(); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nvar peopleParams = PersonParams{\n\tNameFirst:          \"John\",\n\tNameMiddle:         \"P\",\n\tNameLast:           \"Denver\",\n\tDocumentType:       \"ssn\",\n\tDocumentValue:      \"0000\",\n\tBirthDay:           7,\n\tBirthMonth:         6,\n\tBirthYear:          1980,\n\tAddressStreet1:     \"1234 Main Street\",\n\tAddressStreet2:     \"APT 12\",\n\tAddressCity:        \"Palo Alto\",\n\tAddressSubdivision: \"California\",\n\tAddressPostalCode:  \"94025\",\n\tAddressCountryCode: \"US\",\n\tPhoneNumber:        \"123-456-78910\",\n\tIPAddress:          \"127.0.0.1\",\n\tNote:               \"Hello, world\",\n}\n\nvar personID string\n\nfunc TestCreatePeople(t *testing.T) {\n\t\/\/ Create the People.\n\tresp, err := People.Create(&peopleParams)\n\n\tif err != nil {\n\t\tt.Errorf(\"Expected successful People creation, got Error %s\", err.Error())\n\t}\n\n\tpersonID = resp.Id\n\n\tif resp.NameFirst != peopleParams.NameFirst {\n\t\tt.Errorf(\"Expected NameFirst: %s, got: %s\", peopleParams.NameFirst, resp.NameFirst)\n\t}\n\n\tif resp.NameMiddle != peopleParams.NameMiddle {\n\t\tt.Errorf(\"Expected NameMiddle: %s, got: %s\", peopleParams.NameMiddle, resp.NameMiddle)\n\t}\n\n\tif resp.NameLast != peopleParams.NameLast {\n\t\tt.Errorf(\"Expected NameLast: %s, got: %s\", peopleParams.NameLast, resp.NameLast)\n\t}\n\n\tif resp.DocumentType != peopleParams.DocumentType {\n\t\tt.Errorf(\"Expected DocumentType: %s, got: %s\", peopleParams.DocumentType, resp.DocumentType)\n\t}\n\n\tif resp.DocumentValue != peopleParams.DocumentValue {\n\t\tt.Errorf(\"Expected DocumentValue: %s, got: %s\", peopleParams.DocumentValue, resp.DocumentValue)\n\t}\n\n\tif resp.BirthDay != peopleParams.BirthDay {\n\t\tt.Errorf(\"Expected BirthDay: %s, got: %s\", peopleParams.BirthDay, resp.BirthDay)\n\t}\n\n\tif resp.BirthMonth != peopleParams.BirthMonth {\n\t\tt.Errorf(\"Expected BirthMonth: %s, got: %s\", peopleParams.BirthMonth, resp.BirthMonth)\n\t}\n\n\tif resp.BirthYear != peopleParams.BirthYear {\n\t\tt.Errorf(\"Expected BirthYear: %s, got: %s\", peopleParams.BirthYear, resp.BirthYear)\n\t}\n\n\tif resp.AddressStreet1 != peopleParams.AddressStreet1 {\n\t\tt.Errorf(\"Expected AddressStreet1: %s, got: %s\", peopleParams.AddressStreet1, resp.AddressStreet1)\n\t}\n\n\tif resp.AddressStreet2 != peopleParams.AddressStreet2 {\n\t\tt.Errorf(\"Expected AddressStreet2: %s, got: %s\", peopleParams.AddressStreet2, resp.AddressStreet2)\n\t}\n\n\tif resp.AddressCity != peopleParams.AddressCity {\n\t\tt.Errorf(\"Expected AddressCity: %s, got: %s\", peopleParams.AddressCity, resp.AddressCity)\n\t}\n\n\tif resp.AddressSubdivision != peopleParams.AddressSubdivision {\n\t\tt.Errorf(\"Expected AddressSubdivision: %s, got: %s\", peopleParams.AddressSubdivision, resp.AddressSubdivision)\n\t}\n\n\tif resp.AddressPostalCode != peopleParams.AddressPostalCode {\n\t\tt.Errorf(\"Expected AddressPostalCode: %s, got: %s\", peopleParams.AddressPostalCode, resp.AddressPostalCode)\n\t}\n\n\tif resp.AddressCountryCode != peopleParams.AddressCountryCode {\n\t\tt.Errorf(\"Expected AddressCountryCode: %s, got: %s\", peopleParams.AddressCountryCode, resp.AddressCountryCode)\n\t}\n\n\tif resp.PhoneNumber != peopleParams.PhoneNumber {\n\t\tt.Errorf(\"Expected PhoneNumber: %s, got: %s\", peopleParams.PhoneNumber, resp.PhoneNumber)\n\t}\n\n\tif resp.IPAddress != peopleParams.IPAddress {\n\t\tt.Errorf(\"Expected IPAddress: %s, got: %s\", peopleParams.IPAddress, resp.IPAddress)\n\t}\n\n\tif resp.Note != peopleParams.Note {\n\t\tt.Errorf(\"Expected Note: %s, got: %s\", peopleParams.Note, resp.Note)\n\t}\n}\n\nfunc TestRetrievePeople(t *testing.T) {\n\tresp, err := People.Retrieve(personID)\n\n\tif err != nil {\n\t\tt.Errorf(\"Expected successful People creation, got Error %s\", err.Error())\n\t}\n\n\tif resp.NameFirst != peopleParams.NameFirst {\n\t\tt.Errorf(\"Expected NameFirst: %s, got: %s\", peopleParams.NameFirst, resp.NameFirst)\n\t}\n\n\tif resp.NameMiddle != peopleParams.NameMiddle {\n\t\tt.Errorf(\"Expected NameMiddle: %s, got: %s\", peopleParams.NameMiddle, resp.NameMiddle)\n\t}\n\n\tif resp.NameLast != peopleParams.NameLast {\n\t\tt.Errorf(\"Expected NameLast: %s, got: %s\", peopleParams.NameLast, resp.NameLast)\n\t}\n\n\tif resp.DocumentType != peopleParams.DocumentType {\n\t\tt.Errorf(\"Expected DocumentType: %s, got: %s\", peopleParams.DocumentType, resp.DocumentType)\n\t}\n\n\tif resp.DocumentValue != peopleParams.DocumentValue {\n\t\tt.Errorf(\"Expected DocumentValue: %s, got: %s\", peopleParams.DocumentValue, resp.DocumentValue)\n\t}\n\n\tif resp.BirthDay != peopleParams.BirthDay {\n\t\tt.Errorf(\"Expected BirthDay: %s, got: %s\", peopleParams.BirthDay, resp.BirthDay)\n\t}\n\n\tif resp.BirthMonth != peopleParams.BirthMonth {\n\t\tt.Errorf(\"Expected BirthMonth: %s, got: %s\", peopleParams.BirthMonth, resp.BirthMonth)\n\t}\n\n\tif resp.BirthYear != peopleParams.BirthYear {\n\t\tt.Errorf(\"Expected BirthYear: %s, got: %s\", peopleParams.BirthYear, resp.BirthYear)\n\t}\n\n\tif resp.AddressStreet1 != peopleParams.AddressStreet1 {\n\t\tt.Errorf(\"Expected AddressStreet1: %s, got: %s\", peopleParams.AddressStreet1, resp.AddressStreet1)\n\t}\n\n\tif resp.AddressStreet2 != peopleParams.AddressStreet2 {\n\t\tt.Errorf(\"Expected AddressStreet2: %s, got: %s\", peopleParams.AddressStreet2, resp.AddressStreet2)\n\t}\n\n\tif resp.AddressCity != peopleParams.AddressCity {\n\t\tt.Errorf(\"Expected AddressCity: %s, got: %s\", peopleParams.AddressCity, resp.AddressCity)\n\t}\n\n\tif resp.AddressSubdivision != peopleParams.AddressSubdivision {\n\t\tt.Errorf(\"Expected AddressSubdivision: %s, got: %s\", peopleParams.AddressSubdivision, resp.AddressSubdivision)\n\t}\n\n\tif resp.AddressPostalCode != peopleParams.AddressPostalCode {\n\t\tt.Errorf(\"Expected AddressPostalCode: %s, got: %s\", peopleParams.AddressPostalCode, resp.AddressPostalCode)\n\t}\n\n\tif resp.AddressCountryCode != peopleParams.AddressCountryCode {\n\t\tt.Errorf(\"Expected AddressCountryCode: %s, got: %s\", peopleParams.AddressCountryCode, resp.AddressCountryCode)\n\t}\n\n\tif resp.PhoneNumber != peopleParams.PhoneNumber {\n\t\tt.Errorf(\"Expected PhoneNumber: %s, got: %s\", peopleParams.PhoneNumber, resp.PhoneNumber)\n\t}\n\n\tif resp.IPAddress != peopleParams.IPAddress {\n\t\tt.Errorf(\"Expected IPAddress: %s, got: %s\", peopleParams.IPAddress, resp.IPAddress)\n\t}\n\n\tif resp.Note != peopleParams.Note {\n\t\tt.Errorf(\"Expected Note: %s, got: %s\", peopleParams.Note, resp.Note)\n\t}\n}\n\nfunc TestListPeople(t *testing.T) {\n\t_, err := People.List()\n\tif err != nil {\n\t\tt.Errorf(\"Error: %s\", err.Error())\n\t}\n}\n\nfunc TestListNPeople(t *testing.T) {\n\t_, err := People.ListN(2, 5)\n\tif err != nil {\n\t\tt.Errorf(\"Error: %s\", err.Error())\n\t}\n}\n<commit_msg>tweak printed text<commit_after>package blockscore\n\nimport \"testing\"\n\nfunc init() {\n\t\/\/ In order to execute the Unit Test, you must set your BlockScore\n\t\/\/ API key as environment variable: BLOCKSCORE_API_KEY=xxxx\n\tif err := SetKeyEnv(); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nvar peopleParams = PersonParams{\n\tNameFirst:          \"John\",\n\tNameMiddle:         \"P\",\n\tNameLast:           \"Denver\",\n\tDocumentType:       \"ssn\",\n\tDocumentValue:      \"0000\",\n\tBirthDay:           7,\n\tBirthMonth:         6,\n\tBirthYear:          1980,\n\tAddressStreet1:     \"1234 Main Street\",\n\tAddressStreet2:     \"APT 12\",\n\tAddressCity:        \"Palo Alto\",\n\tAddressSubdivision: \"California\",\n\tAddressPostalCode:  \"94025\",\n\tAddressCountryCode: \"US\",\n\tPhoneNumber:        \"123-456-78910\",\n\tIPAddress:          \"127.0.0.1\",\n\tNote:               \"Hello, world\",\n}\n\nvar personID string\n\nfunc TestCreatePeople(t *testing.T) {\n\t\/\/ Create the People.\n\tresp, err := People.Create(&peopleParams)\n\n\tif err != nil {\n\t\tt.Errorf(\"Expected successful Person creation, got Error %s\", err.Error())\n\t}\n\n\tpersonID = resp.Id\n\n\tif resp.NameFirst != peopleParams.NameFirst {\n\t\tt.Errorf(\"Expected NameFirst: %s, got: %s\", peopleParams.NameFirst, resp.NameFirst)\n\t}\n\n\tif resp.NameMiddle != peopleParams.NameMiddle {\n\t\tt.Errorf(\"Expected NameMiddle: %s, got: %s\", peopleParams.NameMiddle, resp.NameMiddle)\n\t}\n\n\tif resp.NameLast != peopleParams.NameLast {\n\t\tt.Errorf(\"Expected NameLast: %s, got: %s\", peopleParams.NameLast, resp.NameLast)\n\t}\n\n\tif resp.DocumentType != peopleParams.DocumentType {\n\t\tt.Errorf(\"Expected DocumentType: %s, got: %s\", peopleParams.DocumentType, resp.DocumentType)\n\t}\n\n\tif resp.DocumentValue != peopleParams.DocumentValue {\n\t\tt.Errorf(\"Expected DocumentValue: %s, got: %s\", peopleParams.DocumentValue, resp.DocumentValue)\n\t}\n\n\tif resp.BirthDay != peopleParams.BirthDay {\n\t\tt.Errorf(\"Expected BirthDay: %s, got: %s\", peopleParams.BirthDay, resp.BirthDay)\n\t}\n\n\tif resp.BirthMonth != peopleParams.BirthMonth {\n\t\tt.Errorf(\"Expected BirthMonth: %s, got: %s\", peopleParams.BirthMonth, resp.BirthMonth)\n\t}\n\n\tif resp.BirthYear != peopleParams.BirthYear {\n\t\tt.Errorf(\"Expected BirthYear: %s, got: %s\", peopleParams.BirthYear, resp.BirthYear)\n\t}\n\n\tif resp.AddressStreet1 != peopleParams.AddressStreet1 {\n\t\tt.Errorf(\"Expected AddressStreet1: %s, got: %s\", peopleParams.AddressStreet1, resp.AddressStreet1)\n\t}\n\n\tif resp.AddressStreet2 != peopleParams.AddressStreet2 {\n\t\tt.Errorf(\"Expected AddressStreet2: %s, got: %s\", peopleParams.AddressStreet2, resp.AddressStreet2)\n\t}\n\n\tif resp.AddressCity != peopleParams.AddressCity {\n\t\tt.Errorf(\"Expected AddressCity: %s, got: %s\", peopleParams.AddressCity, resp.AddressCity)\n\t}\n\n\tif resp.AddressSubdivision != peopleParams.AddressSubdivision {\n\t\tt.Errorf(\"Expected AddressSubdivision: %s, got: %s\", peopleParams.AddressSubdivision, resp.AddressSubdivision)\n\t}\n\n\tif resp.AddressPostalCode != peopleParams.AddressPostalCode {\n\t\tt.Errorf(\"Expected AddressPostalCode: %s, got: %s\", peopleParams.AddressPostalCode, resp.AddressPostalCode)\n\t}\n\n\tif resp.AddressCountryCode != peopleParams.AddressCountryCode {\n\t\tt.Errorf(\"Expected AddressCountryCode: %s, got: %s\", peopleParams.AddressCountryCode, resp.AddressCountryCode)\n\t}\n\n\tif resp.PhoneNumber != peopleParams.PhoneNumber {\n\t\tt.Errorf(\"Expected PhoneNumber: %s, got: %s\", peopleParams.PhoneNumber, resp.PhoneNumber)\n\t}\n\n\tif resp.IPAddress != peopleParams.IPAddress {\n\t\tt.Errorf(\"Expected IPAddress: %s, got: %s\", peopleParams.IPAddress, resp.IPAddress)\n\t}\n\n\tif resp.Note != peopleParams.Note {\n\t\tt.Errorf(\"Expected Note: %s, got: %s\", peopleParams.Note, resp.Note)\n\t}\n}\n\nfunc TestRetrievePeople(t *testing.T) {\n\tresp, err := People.Retrieve(personID)\n\n\tif err != nil {\n\t\tt.Errorf(\"Expected successful People retrieval, got Error %s\", err.Error())\n\t}\n\n\tif resp.NameFirst != peopleParams.NameFirst {\n\t\tt.Errorf(\"Expected NameFirst: %s, got: %s\", peopleParams.NameFirst, resp.NameFirst)\n\t}\n\n\tif resp.NameMiddle != peopleParams.NameMiddle {\n\t\tt.Errorf(\"Expected NameMiddle: %s, got: %s\", peopleParams.NameMiddle, resp.NameMiddle)\n\t}\n\n\tif resp.NameLast != peopleParams.NameLast {\n\t\tt.Errorf(\"Expected NameLast: %s, got: %s\", peopleParams.NameLast, resp.NameLast)\n\t}\n\n\tif resp.DocumentType != peopleParams.DocumentType {\n\t\tt.Errorf(\"Expected DocumentType: %s, got: %s\", peopleParams.DocumentType, resp.DocumentType)\n\t}\n\n\tif resp.DocumentValue != peopleParams.DocumentValue {\n\t\tt.Errorf(\"Expected DocumentValue: %s, got: %s\", peopleParams.DocumentValue, resp.DocumentValue)\n\t}\n\n\tif resp.BirthDay != peopleParams.BirthDay {\n\t\tt.Errorf(\"Expected BirthDay: %s, got: %s\", peopleParams.BirthDay, resp.BirthDay)\n\t}\n\n\tif resp.BirthMonth != peopleParams.BirthMonth {\n\t\tt.Errorf(\"Expected BirthMonth: %s, got: %s\", peopleParams.BirthMonth, resp.BirthMonth)\n\t}\n\n\tif resp.BirthYear != peopleParams.BirthYear {\n\t\tt.Errorf(\"Expected BirthYear: %s, got: %s\", peopleParams.BirthYear, resp.BirthYear)\n\t}\n\n\tif resp.AddressStreet1 != peopleParams.AddressStreet1 {\n\t\tt.Errorf(\"Expected AddressStreet1: %s, got: %s\", peopleParams.AddressStreet1, resp.AddressStreet1)\n\t}\n\n\tif resp.AddressStreet2 != peopleParams.AddressStreet2 {\n\t\tt.Errorf(\"Expected AddressStreet2: %s, got: %s\", peopleParams.AddressStreet2, resp.AddressStreet2)\n\t}\n\n\tif resp.AddressCity != peopleParams.AddressCity {\n\t\tt.Errorf(\"Expected AddressCity: %s, got: %s\", peopleParams.AddressCity, resp.AddressCity)\n\t}\n\n\tif resp.AddressSubdivision != peopleParams.AddressSubdivision {\n\t\tt.Errorf(\"Expected AddressSubdivision: %s, got: %s\", peopleParams.AddressSubdivision, resp.AddressSubdivision)\n\t}\n\n\tif resp.AddressPostalCode != peopleParams.AddressPostalCode {\n\t\tt.Errorf(\"Expected AddressPostalCode: %s, got: %s\", peopleParams.AddressPostalCode, resp.AddressPostalCode)\n\t}\n\n\tif resp.AddressCountryCode != peopleParams.AddressCountryCode {\n\t\tt.Errorf(\"Expected AddressCountryCode: %s, got: %s\", peopleParams.AddressCountryCode, resp.AddressCountryCode)\n\t}\n\n\tif resp.PhoneNumber != peopleParams.PhoneNumber {\n\t\tt.Errorf(\"Expected PhoneNumber: %s, got: %s\", peopleParams.PhoneNumber, resp.PhoneNumber)\n\t}\n\n\tif resp.IPAddress != peopleParams.IPAddress {\n\t\tt.Errorf(\"Expected IPAddress: %s, got: %s\", peopleParams.IPAddress, resp.IPAddress)\n\t}\n\n\tif resp.Note != peopleParams.Note {\n\t\tt.Errorf(\"Expected Note: %s, got: %s\", peopleParams.Note, resp.Note)\n\t}\n}\n\nfunc TestListPeople(t *testing.T) {\n\t_, err := People.List()\n\tif err != nil {\n\t\tt.Errorf(\"Error: %s\", err.Error())\n\t}\n}\n\nfunc TestListNPeople(t *testing.T) {\n\t_, err := People.ListN(2, 5)\n\tif err != nil {\n\t\tt.Errorf(\"Error: %s\", err.Error())\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"context\"\n\t\"log\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"golang.org\/x\/oauth2\"\n)\n\ntype permissions struct {\n\ttoken         string\n\talwaysAllowed []string\n\tteamMembers   map[string][]string \/\/ repo -> list of members\n}\n\nfunc (p *permissions) isAllowed(repo, login string) bool {\n\t\/\/ Check the list of always allowed users\n\tfor _, user := range p.alwaysAllowed {\n\t\tif login == user {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t\/\/ Check the cached list of team members for the given repo\n\tfor _, user := range p.teamMembers[repo] {\n\t\tif login == user {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t\/\/ Refresh the team members list as it may be out of date\n\tlog.Println(\"Refreshing the list of collaborators on\", repo, \"...\")\n\tusers, err := p.collaborators(repo)\n\tif err != nil {\n\t\treturn false\n\t}\n\tlog.Println(\" ... got\", users)\n\tp.teamMembers[repo] = users\n\tfor _, user := range p.teamMembers[repo] {\n\t\tif login == user {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tlog.Println(\"Permission denied for\", login)\n\n\t\/\/ Nope, no match\n\treturn false\n}\n\nfunc (p *permissions) collaborators(repo string) ([]string, error) {\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: p.token},\n\t)\n\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\n\tclient := github.NewClient(tc)\n\n\topt := &github.ListOptions{PerPage: 50}\n\tvar allCollabs []*github.User\n\tps := strings.Split(repo, \"\/\")\n\towner, repo := ps[0], ps[1]\n\tfor {\n\t\tusers, resp, err := client.Repositories.ListCollaborators(context.TODO(), owner, repo, opt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tallCollabs = append(allCollabs, users...)\n\t\tif resp.NextPage == 0 {\n\t\t\tbreak\n\t\t}\n\t\topt.Page = resp.NextPage\n\t}\n\n\tuserMap := make(map[string]bool)\n\tfor _, user := range allCollabs {\n\t\tuserMap[*user.Login] = true\n\t}\n\n\tvar users []string\n\tfor user := range userMap {\n\t\tusers = append(users, user)\n\t}\n\tsort.Strings(users)\n\treturn users, nil\n}\n<commit_msg>GitHub API update<commit_after>package main\n\nimport (\n\t\"context\"\n\t\"log\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"golang.org\/x\/oauth2\"\n)\n\ntype permissions struct {\n\ttoken         string\n\talwaysAllowed []string\n\tteamMembers   map[string][]string \/\/ repo -> list of members\n}\n\nfunc (p *permissions) isAllowed(repo, login string) bool {\n\t\/\/ Check the list of always allowed users\n\tfor _, user := range p.alwaysAllowed {\n\t\tif login == user {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t\/\/ Check the cached list of team members for the given repo\n\tfor _, user := range p.teamMembers[repo] {\n\t\tif login == user {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t\/\/ Refresh the team members list as it may be out of date\n\tlog.Println(\"Refreshing the list of collaborators on\", repo, \"...\")\n\tusers, err := p.collaborators(repo)\n\tif err != nil {\n\t\treturn false\n\t}\n\tlog.Println(\" ... got\", users)\n\tp.teamMembers[repo] = users\n\tfor _, user := range p.teamMembers[repo] {\n\t\tif login == user {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tlog.Println(\"Permission denied for\", login)\n\n\t\/\/ Nope, no match\n\treturn false\n}\n\nfunc (p *permissions) collaborators(repo string) ([]string, error) {\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: p.token},\n\t)\n\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\n\tclient := github.NewClient(tc)\n\n\topt := new(github.ListCollaboratorsOptions)\n\topt.PerPage = 50\n\tvar allCollabs []*github.User\n\tps := strings.Split(repo, \"\/\")\n\towner, repo := ps[0], ps[1]\n\tfor {\n\t\tusers, resp, err := client.Repositories.ListCollaborators(context.TODO(), owner, repo, opt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tallCollabs = append(allCollabs, users...)\n\t\tif resp.NextPage == 0 {\n\t\t\tbreak\n\t\t}\n\t\topt.Page = resp.NextPage\n\t}\n\n\tuserMap := make(map[string]bool)\n\tfor _, user := range allCollabs {\n\t\tuserMap[*user.Login] = true\n\t}\n\n\tvar users []string\n\tfor user := range userMap {\n\t\tusers = append(users, user)\n\t}\n\tsort.Strings(users)\n\treturn users, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst requestTimeout = time.Second * 5\n\nvar (\n\tedgeHost    = flag.String(\"edgeHost\", \"www.gov.uk\", \"Hostname of edge\")\n\toriginPort  = flag.Int(\"originPort\", 8080, \"Origin port to listen on for requests\")\n\tinsecureTLS = flag.Bool(\"insecureTLS\", false, \"Whether to check server certificates\")\n\n\tclient       *http.Transport\n\toriginServer *CDNServeMux\n)\n\n\/\/ Setup clients and servers.\nfunc init() {\n\n\tflag.Parse()\n\n\ttlsOptions := &tls.Config{}\n\tif *insecureTLS {\n\t\ttlsOptions.InsecureSkipVerify = true\n\t}\n\n\tclient = &http.Transport{\n\t\tResponseHeaderTimeout: requestTimeout,\n\t\tTLSClientConfig:       tlsOptions,\n\t}\n\toriginServer = StartServer(*originPort)\n\n\tlog.Println(\"Confirming that CDN has successfully probed Origin\")\n\terr := confirmOriginIsEnabled(originServer, *edgeHost)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc TestHelpers(t *testing.T) {\n\ttestHelpersCDNServeMuxHandlers(t, originServer)\n\ttestHelpersCDNServeMuxProbes(t, originServer)\n}\n\n\/\/ Should redirect from HTTP to HTTPS without hitting origin.\nfunc TestProtocolRedirect(t *testing.T) {\n\toriginServer.SwitchHandler(func(w http.ResponseWriter, r *http.Request) {\n\t\tt.Error(\"Request should not have made it to origin\")\n\t})\n\n\tsourceUrl := fmt.Sprintf(\"http:\/\/%s\/foo\/bar\", *edgeHost)\n\tdestUrl := fmt.Sprintf(\"https:\/\/%s\/foo\/bar\", *edgeHost)\n\n\treq, _ := http.NewRequest(\"GET\", sourceUrl, nil)\n\tresp, err := client.RoundTrip(req)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif resp.StatusCode != 301 {\n\t\tt.Errorf(\"Status code expected 301, got %d\", resp.StatusCode)\n\t}\n\tif d := resp.Header.Get(\"Location\"); d != destUrl {\n\t\tt.Errorf(\"Location header expected %s, got %s\", destUrl, d)\n\t}\n}\n\n\/\/ Should send request to origin by default\nfunc TestRequestsGoToOriginByDefault(t *testing.T) {\n\tuuid := NewUUID()\n\toriginServer.SwitchHandler(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == \"GET\" && r.URL.Path == fmt.Sprintf(\"\/%s\", uuid) {\n\t\t\tw.Header().Set(\"EnsureOriginServed\", uuid)\n\t\t}\n\t})\n\n\tsourceUrl := fmt.Sprintf(\"https:\/\/%s\/%s\", *edgeHost, uuid)\n\n\treq, _ := http.NewRequest(\"GET\", sourceUrl, nil)\n\tresp, err := client.RoundTrip(req)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif resp.StatusCode != 200 {\n\t\tt.Errorf(\"Status code expected 200, got %d\", resp.StatusCode)\n\t}\n\tif d := resp.Header.Get(\"EnsureOriginServed\"); d != uuid {\n\t\tt.Errorf(\"EnsureOriginServed header has not come from Origin: expected %q, got %q\", uuid, d)\n\t}\n\n}\n\n\/\/ Should cache first response and return it on second request without\n\/\/ hitting origin again.\nfunc TestFirstResponseCached(t *testing.T) {\n\tconst bodyExpected = \"first request\"\n\tconst requestsExpectedCount = 1\n\trequestsReceivedCount := 0\n\n\toriginServer.SwitchHandler(func(w http.ResponseWriter, r *http.Request) {\n\t\tif requestsReceivedCount == 0 {\n\t\t\tw.Write([]byte(bodyExpected))\n\t\t} else {\n\t\t\tw.Write([]byte(\"subsequent request\"))\n\t\t}\n\n\t\trequestsReceivedCount++\n\t})\n\n\turl := fmt.Sprintf(\"https:\/\/%s\/%s\", *edgeHost, NewUUID())\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\n\tfor i := 0; i < 2; i++ {\n\t\tresp, err := client.RoundTrip(req)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tdefer resp.Body.Close()\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif string(body) != bodyExpected {\n\t\t\tt.Errorf(\"Incorrect response body. Expected %q, got %q\", bodyExpected, body)\n\t\t}\n\t}\n\n\tif requestsReceivedCount > requestsExpectedCount {\n\t\tt.Errorf(\"originServer got too many requests. Expected %d requests, got %d\", requestsExpectedCount, requestsReceivedCount)\n\t}\n}\n\n\/\/ Should return 403 for PURGE requests from IPs not in the whitelist.\nfunc TestRestrictPurgeRequests(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should create an X-Forwarded-For header containing the client's IP.\nfunc TestHeaderCreateXFF(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should append client's IP to existing X-Forwarded-For header.\nfunc TestHeaderAppendXFF(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should create a True-Client-IP header containing the client's IP\n\/\/ address, discarding the value provided in the original request.\nfunc TestHeaderUnspoofableClientIP(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not modify Host header from original request.\nfunc TestHeaderHostUnmodified(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should set a default TTL if the response doesn't set one.\nfunc TestDefaultTTL(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should serve stale object and not hit mirror(s) if origin is down and\n\/\/ object is beyond TTL but still in cache.\nfunc TestFailoverOriginDownServeStale(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should serve stale object and not hit mirror(s) if origin returns a 5xx\n\/\/ response and object is beyond TTL but still in cache.\nfunc TestFailoverOrigin5xxServeStale(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to first mirror if origin is down and object is not in\n\/\/ cache (active or stale).\nfunc TestFailoverOriginDownUseFirstMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to first mirror if origin returns 5xx response and object\n\/\/ is not in cache (active or stale).\nfunc TestFailoverOrigin5xxUseFirstMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to second mirror if both origin and first mirror are\n\/\/ down.\nfunc TestFailoverOriginDownFirstMirrorDownUseSecondMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to second mirror if both origin and first mirror return\n\/\/ 5xx responses.\nfunc TestFailoverOrigin5xxFirstMirror5xxUseSecondMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not fallback to mirror if origin returns a 5xx response with a\n\/\/ No-Fallback header.\nfunc TestFailoverNoFallbackHeader(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should serve a known static error page if cannot serve a page\n\/\/ from origin, stale or any mirror.\n\/\/ NB: ideally this should be a page that we control that has a mechanism\n\/\/     to alert us that it has been served.\nfunc TestErrorPageIsServedWhenNoBackendAvailable(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not cache a response with a Set-Cookie a header.\nfunc TestNoCacheHeaderSetCookie(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not cache a response with a Cache-Control: private header.\nfunc TestNoCacheHeaderCacheControlPrivate(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ ---------------------------------------------------------\n\/\/ Test that useful common cache-related parameters are sent to the\n\/\/ client by this CDN provider.\n\n\/\/ Should set an Age header itself rather than passing the Age header from origin.\nfunc TestAgeHeaderIsSetByProviderNotOrigin(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should set an X-Cache header containing HIT\/MISS from 'origin, itself'\nfunc TestXCacheHeaderContainsHitMissFromBothProviderAndOrigin(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should set an X-Served-By header giving information on the node and location served from.\nfunc TestXServedByHeaderContainsANodeIdAndLocation(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should set an X-Cache-Hits header containing hit count for this object,\n\/\/ from the provider not origin\nfunc TestXCacheHitsContainsProviderHitCountForThisObject(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n<commit_msg>Implement test for PURGE returning 403<commit_after>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst requestTimeout = time.Second * 5\n\nvar (\n\tedgeHost    = flag.String(\"edgeHost\", \"www.gov.uk\", \"Hostname of edge\")\n\toriginPort  = flag.Int(\"originPort\", 8080, \"Origin port to listen on for requests\")\n\tinsecureTLS = flag.Bool(\"insecureTLS\", false, \"Whether to check server certificates\")\n\n\tclient       *http.Transport\n\toriginServer *CDNServeMux\n)\n\n\/\/ Setup clients and servers.\nfunc init() {\n\n\tflag.Parse()\n\n\ttlsOptions := &tls.Config{}\n\tif *insecureTLS {\n\t\ttlsOptions.InsecureSkipVerify = true\n\t}\n\n\tclient = &http.Transport{\n\t\tResponseHeaderTimeout: requestTimeout,\n\t\tTLSClientConfig:       tlsOptions,\n\t}\n\toriginServer = StartServer(*originPort)\n\n\tlog.Println(\"Confirming that CDN has successfully probed Origin\")\n\terr := confirmOriginIsEnabled(originServer, *edgeHost)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc TestHelpers(t *testing.T) {\n\ttestHelpersCDNServeMuxHandlers(t, originServer)\n\ttestHelpersCDNServeMuxProbes(t, originServer)\n}\n\n\/\/ Should redirect from HTTP to HTTPS without hitting origin.\nfunc TestProtocolRedirect(t *testing.T) {\n\toriginServer.SwitchHandler(func(w http.ResponseWriter, r *http.Request) {\n\t\tt.Error(\"Request should not have made it to origin\")\n\t})\n\n\tsourceUrl := fmt.Sprintf(\"http:\/\/%s\/foo\/bar\", *edgeHost)\n\tdestUrl := fmt.Sprintf(\"https:\/\/%s\/foo\/bar\", *edgeHost)\n\n\treq, _ := http.NewRequest(\"GET\", sourceUrl, nil)\n\tresp, err := client.RoundTrip(req)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif resp.StatusCode != 301 {\n\t\tt.Errorf(\"Status code expected 301, got %d\", resp.StatusCode)\n\t}\n\tif d := resp.Header.Get(\"Location\"); d != destUrl {\n\t\tt.Errorf(\"Location header expected %s, got %s\", destUrl, d)\n\t}\n}\n\n\/\/ Should send request to origin by default\nfunc TestRequestsGoToOriginByDefault(t *testing.T) {\n\tuuid := NewUUID()\n\toriginServer.SwitchHandler(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == \"GET\" && r.URL.Path == fmt.Sprintf(\"\/%s\", uuid) {\n\t\t\tw.Header().Set(\"EnsureOriginServed\", uuid)\n\t\t}\n\t})\n\n\tsourceUrl := fmt.Sprintf(\"https:\/\/%s\/%s\", *edgeHost, uuid)\n\n\treq, _ := http.NewRequest(\"GET\", sourceUrl, nil)\n\tresp, err := client.RoundTrip(req)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif resp.StatusCode != 200 {\n\t\tt.Errorf(\"Status code expected 200, got %d\", resp.StatusCode)\n\t}\n\tif d := resp.Header.Get(\"EnsureOriginServed\"); d != uuid {\n\t\tt.Errorf(\"EnsureOriginServed header has not come from Origin: expected %q, got %q\", uuid, d)\n\t}\n\n}\n\n\/\/ Should cache first response and return it on second request without\n\/\/ hitting origin again.\nfunc TestFirstResponseCached(t *testing.T) {\n\tconst bodyExpected = \"first request\"\n\tconst requestsExpectedCount = 1\n\trequestsReceivedCount := 0\n\n\toriginServer.SwitchHandler(func(w http.ResponseWriter, r *http.Request) {\n\t\tif requestsReceivedCount == 0 {\n\t\t\tw.Write([]byte(bodyExpected))\n\t\t} else {\n\t\t\tw.Write([]byte(\"subsequent request\"))\n\t\t}\n\n\t\trequestsReceivedCount++\n\t})\n\n\turl := fmt.Sprintf(\"https:\/\/%s\/%s\", *edgeHost, NewUUID())\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\n\tfor i := 0; i < 2; i++ {\n\t\tresp, err := client.RoundTrip(req)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tdefer resp.Body.Close()\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif string(body) != bodyExpected {\n\t\t\tt.Errorf(\"Incorrect response body. Expected %q, got %q\", bodyExpected, body)\n\t\t}\n\t}\n\n\tif requestsReceivedCount > requestsExpectedCount {\n\t\tt.Errorf(\"originServer got too many requests. Expected %d requests, got %d\", requestsExpectedCount, requestsReceivedCount)\n\t}\n}\n\n\/\/ Should return 403 for PURGE requests from IPs not in the whitelist. We\n\/\/ assume that this is not running from a whitelisted address.\nfunc TestRestrictPurgeRequests(t *testing.T) {\n\tconst expectedStatusCode = 403\n\n\toriginServer.SwitchHandler(func(w http.ResponseWriter, r *http.Request) {\n\t\tt.Error(\"Request should not have made it to origin\")\n\t})\n\n\turl := fmt.Sprintf(\"https:\/\/%s\/\", *edgeHost)\n\treq, _ := http.NewRequest(\"PURGE\", url, nil)\n\n\tresp, err := client.RoundTrip(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif resp.StatusCode != expectedStatusCode {\n\t\tt.Errorf(\"Incorrect status code. Expected %d, got %d\", expectedStatusCode, resp.StatusCode)\n\t}\n}\n\n\/\/ Should create an X-Forwarded-For header containing the client's IP.\nfunc TestHeaderCreateXFF(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should append client's IP to existing X-Forwarded-For header.\nfunc TestHeaderAppendXFF(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should create a True-Client-IP header containing the client's IP\n\/\/ address, discarding the value provided in the original request.\nfunc TestHeaderUnspoofableClientIP(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not modify Host header from original request.\nfunc TestHeaderHostUnmodified(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should set a default TTL if the response doesn't set one.\nfunc TestDefaultTTL(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should serve stale object and not hit mirror(s) if origin is down and\n\/\/ object is beyond TTL but still in cache.\nfunc TestFailoverOriginDownServeStale(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should serve stale object and not hit mirror(s) if origin returns a 5xx\n\/\/ response and object is beyond TTL but still in cache.\nfunc TestFailoverOrigin5xxServeStale(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to first mirror if origin is down and object is not in\n\/\/ cache (active or stale).\nfunc TestFailoverOriginDownUseFirstMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to first mirror if origin returns 5xx response and object\n\/\/ is not in cache (active or stale).\nfunc TestFailoverOrigin5xxUseFirstMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to second mirror if both origin and first mirror are\n\/\/ down.\nfunc TestFailoverOriginDownFirstMirrorDownUseSecondMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to second mirror if both origin and first mirror return\n\/\/ 5xx responses.\nfunc TestFailoverOrigin5xxFirstMirror5xxUseSecondMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not fallback to mirror if origin returns a 5xx response with a\n\/\/ No-Fallback header.\nfunc TestFailoverNoFallbackHeader(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should serve a known static error page if cannot serve a page\n\/\/ from origin, stale or any mirror.\n\/\/ NB: ideally this should be a page that we control that has a mechanism\n\/\/     to alert us that it has been served.\nfunc TestErrorPageIsServedWhenNoBackendAvailable(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not cache a response with a Set-Cookie a header.\nfunc TestNoCacheHeaderSetCookie(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not cache a response with a Cache-Control: private header.\nfunc TestNoCacheHeaderCacheControlPrivate(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ ---------------------------------------------------------\n\/\/ Test that useful common cache-related parameters are sent to the\n\/\/ client by this CDN provider.\n\n\/\/ Should set an Age header itself rather than passing the Age header from origin.\nfunc TestAgeHeaderIsSetByProviderNotOrigin(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should set an X-Cache header containing HIT\/MISS from 'origin, itself'\nfunc TestXCacheHeaderContainsHitMissFromBothProviderAndOrigin(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should set an X-Served-By header giving information on the node and location served from.\nfunc TestXServedByHeaderContainsANodeIdAndLocation(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should set an X-Cache-Hits header containing hit count for this object,\n\/\/ from the provider not origin\nfunc TestXCacheHitsContainsProviderHitCountForThisObject(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"testing\"\n)\n\nvar edgeHost = flag.String(\"edgeHost\", \"www.gov.uk\", \"Hostname of edge\")\n\n\/\/ Should redirect from HTTP to HTTPS without hitting origin.\nfunc TestProtocolRedirect(t *testing.T) {\n\tsourceUrl := fmt.Sprintf(\"http:\/\/%s\/foo\/bar\", *edgeHost)\n\tdestUrl := fmt.Sprintf(\"https:\/\/%s\/foo\/bar\", *edgeHost)\n\n\tclient := &http.Transport{}\n\treq, _ := http.NewRequest(\"GET\", sourceUrl, nil)\n\tresp, err := client.RoundTrip(req)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif resp.StatusCode != 301 {\n\t\tt.Errorf(\"Status code expected 301, got %d\", resp.StatusCode)\n\t}\n\tif d := resp.Header.Get(\"Location\"); d != destUrl {\n\t\tt.Errorf(\"Location header expected %s, got %s\", destUrl, d)\n\t}\n\n\tt.Error(\"Not implemented test to confirm that it doesn't hit origin\")\n}\n\n\/\/ Should send request to origin by default\nfunc TestRequestsGoToOriginByDefault(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should return 403 for PURGE requests from IPs not in the whitelist.\nfunc TestRestrictPurgeRequests(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should create an X-Forwarded-For header containing the client's IP.\nfunc TestHeaderCreateXFF(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should append client's IP to existing X-Forwarded-For header.\nfunc TestHeaderAppendXFF(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should create a True-Client-IP header containing the client's IP\n\/\/ address, discarding the value provided in the original request.\nfunc TestHeaderUnspoofableClientIP(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not modify Host header from original request.\nfunc TestHeaderHostUnmodified(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should set a default TTL if the response doesn't set one.\nfunc TestDefaultTTL(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should serve stale object and not hit mirror(s) if origin is down and\n\/\/ object is beyond TTL but still in cache.\nfunc TestFailoverOriginDownServeStale(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should serve stale object and not hit mirror(s) if origin returns a 5xx\n\/\/ response and object is beyond TTL but still in cache.\nfunc TestFailoverOrigin5xxServeStale(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to first mirror if origin is down and object is not in\n\/\/ cache (active or stale).\nfunc TestFailoverOriginDownUseFirstMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to first mirror if origin returns 5xx response and object\n\/\/ is not in cache (active or stale).\nfunc TestFailoverOrigin5xxUseFirstMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to second mirror if both origin and first mirror are\n\/\/ down.\nfunc TestFailoverOriginDownFirstMirrorDownUseSecondMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to second mirror if both origin and first mirror return\n\/\/ 5xx responses.\nfunc TestFailoverOrigin5xxFirstMirror5xxUseSecondMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not fallback to mirror if origin returns a 5xx response with a\n\/\/ No-Fallback header.\nfunc TestFailoverNoFallbackHeader(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should serve a known static error page if cannot serve a page\n\/\/ from origin, stale or any mirror.\n\/\/ NB: ideally this should be a page that we control that has a mechanism\n\/\/     to alert us that it has been served.\nfunc TestErrorPageIsServedWhenNoBackendAvailable(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not cache a response with a Set-Cookie a header.\nfunc TestNoCacheHeaderSetCookie(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not cache a response with a Cache-Control: private header.\nfunc TestNoCacheHeaderCacheControlPrivate(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n<commit_msg>Empty tests describing useful response headers<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"testing\"\n)\n\nvar edgeHost = flag.String(\"edgeHost\", \"www.gov.uk\", \"Hostname of edge\")\n\n\/\/ Should redirect from HTTP to HTTPS without hitting origin.\nfunc TestProtocolRedirect(t *testing.T) {\n\tsourceUrl := fmt.Sprintf(\"http:\/\/%s\/foo\/bar\", *edgeHost)\n\tdestUrl := fmt.Sprintf(\"https:\/\/%s\/foo\/bar\", *edgeHost)\n\n\tclient := &http.Transport{}\n\treq, _ := http.NewRequest(\"GET\", sourceUrl, nil)\n\tresp, err := client.RoundTrip(req)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif resp.StatusCode != 301 {\n\t\tt.Errorf(\"Status code expected 301, got %d\", resp.StatusCode)\n\t}\n\tif d := resp.Header.Get(\"Location\"); d != destUrl {\n\t\tt.Errorf(\"Location header expected %s, got %s\", destUrl, d)\n\t}\n\n\tt.Error(\"Not implemented test to confirm that it doesn't hit origin\")\n}\n\n\/\/ Should send request to origin by default\nfunc TestRequestsGoToOriginByDefault(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should return 403 for PURGE requests from IPs not in the whitelist.\nfunc TestRestrictPurgeRequests(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should create an X-Forwarded-For header containing the client's IP.\nfunc TestHeaderCreateXFF(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should append client's IP to existing X-Forwarded-For header.\nfunc TestHeaderAppendXFF(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should create a True-Client-IP header containing the client's IP\n\/\/ address, discarding the value provided in the original request.\nfunc TestHeaderUnspoofableClientIP(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not modify Host header from original request.\nfunc TestHeaderHostUnmodified(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should set a default TTL if the response doesn't set one.\nfunc TestDefaultTTL(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should serve stale object and not hit mirror(s) if origin is down and\n\/\/ object is beyond TTL but still in cache.\nfunc TestFailoverOriginDownServeStale(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should serve stale object and not hit mirror(s) if origin returns a 5xx\n\/\/ response and object is beyond TTL but still in cache.\nfunc TestFailoverOrigin5xxServeStale(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to first mirror if origin is down and object is not in\n\/\/ cache (active or stale).\nfunc TestFailoverOriginDownUseFirstMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to first mirror if origin returns 5xx response and object\n\/\/ is not in cache (active or stale).\nfunc TestFailoverOrigin5xxUseFirstMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to second mirror if both origin and first mirror are\n\/\/ down.\nfunc TestFailoverOriginDownFirstMirrorDownUseSecondMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should fallback to second mirror if both origin and first mirror return\n\/\/ 5xx responses.\nfunc TestFailoverOrigin5xxFirstMirror5xxUseSecondMirror(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not fallback to mirror if origin returns a 5xx response with a\n\/\/ No-Fallback header.\nfunc TestFailoverNoFallbackHeader(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should serve a known static error page if cannot serve a page\n\/\/ from origin, stale or any mirror.\n\/\/ NB: ideally this should be a page that we control that has a mechanism\n\/\/     to alert us that it has been served.\nfunc TestErrorPageIsServedWhenNoBackendAvailable(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not cache a response with a Set-Cookie a header.\nfunc TestNoCacheHeaderSetCookie(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should not cache a response with a Cache-Control: private header.\nfunc TestNoCacheHeaderCacheControlPrivate(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ ---------------------------------------------------------\n\/\/ Test that useful common cache-related parameters are sent to the\n\/\/ client by this CDN provider.\n\n\/\/ Should set an Age header itself rather than passing the Age header from origin.\nfunc TestAgeHeaderIsSetByProviderNotOrigin(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should set an X-Cache header containing HIT\/MISS from 'origin, itself'\nfunc TestXCacheHeaderContainsHitMissFromBothProviderAndOrigin(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should set an X-Served-By header giving information on the node and location served from.\nfunc TestXServedByHeaderContainsANodeIdAndLocation(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n\n\/\/ Should set an X-Cache-Hits header containing hit count for this object,\n\/\/ from the provider not origin\nfunc TestXCacheHitsContainsProviderHitCountForThisObject(t *testing.T) {\n\tt.Error(\"Not implemented\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Andreas Pannewitz. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage das \/\/ Dictionary by any for strings\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"text\/template\"\n)\n\nvar keyBuff = bytes.NewBufferString(\"Test\")\nvar keyTmpl = template.New(\"Test\")\nvar keyStrg = \"Test\"\nvar keyInt8 = 4711\nvar keyBool = true\n\nvar newData = []string{\"Foo\", \"Bar\", \"Buh\", \"Foo\", \"Bar\"}\nvar addData = []string{\"Foo\", \"Bar\", \"Buh\", \"Foo\", \"Bar\"}\n\nfunc ExampleDas_Assign() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n}\n\nfunc ExampleDas_Append() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n}\n\nfunc ExampleDas_Das() {\n\tvar das *Das \/\/ test also lazyInit\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tfor key, val := range das.Das() {\n\t\tfmt.Printf(\"%s:\\t\\t\\n\", key)\n\t\tfor v := range val {\n\t\t\tfmt.Printf(\"\\t%s\\t\\n\", v)\n\t\t}\n\t}\n}\n\nfunc ExampleDas_Delete() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tdas = das.Delete(keyBuff)\n\tdas = das.Delete(keyTmpl)\n\tdas = das.Delete(keyStrg)\n\tdas = das.Delete(keyInt8)\n\tdas = das.Delete(keyBool)\n\n\tfmt.Println(\"Len == 0 ?\", das.Len())\n}\n\nfunc ExampleDas_Fetch() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tkey := keyBool\n\tfmt.Printf(\"%s:\\t\\t\\n\", key)\n\tfor v := range das.Fetch(key) {\n\t\tfmt.Printf(\"\\t%s\\t\\n\", v)\n\t}\n}\n\nfunc ExampleDas_Len() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tfmt.Println(\"Len == 10 ?\", das.Len())\n}\n\nfunc ExampleDas_Lookup() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tvar res []string\n\tres = das.Lookup(keyBuff)\n\tres = das.Lookup(keyTmpl)\n\tres = das.Lookup(keyStrg)\n\tres = das.Lookup(keyInt8)\n\tres = das.Lookup(keyBool)\n\n\tfmt.Println(\"Len == 5 ?\", len(res))\n}\n\nfunc ExampleDas_KeyS() {\n\tdas := New()\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tvar res []interface{}\n\tres = das.KeyS()\n\tfmt.Println(\"Len == 3 ???\", len(res))\n\tfmt.Println(\"Is result sorted?\", res)\n\n}\n\nfunc ExampleDas_Init() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tfmt.Println(\"Len == 5 ?\", das.Len())\n\tdas = das.Init()\n\tfmt.Println(\"Len == 0 ?\", das.Len())\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tfmt.Println(\"Len == 5 ?\", das.Len())\n}\n<commit_msg>was stupid<commit_after>\/\/ Copyright 2016 Andreas Pannewitz. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage das \/\/ Dictionary by any for strings\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"text\/template\"\n)\n\nvar keyBuff = bytes.NewBufferString(\"Test\")\nvar keyTmpl = template.New(\"Test\")\nvar keyStrg = \"Test\"\nvar keyInt8 = 4711\nvar keyBool = true\n\nvar newData = []string{\"Foo\", \"Bar\", \"Buh\", \"Foo\", \"Bar\"}\nvar addData = []string{\"Foo\", \"Bar\", \"Buh\", \"Foo\", \"Bar\"}\n\nfunc ExampleDas_Assign() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n}\n\nfunc ExampleDas_Append() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n}\n\nfunc ExampleDas_Das() {\n\tvar das *Das \/\/ test also lazyInit\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tfor key, val := range das.Das() {\n\t\tfmt.Printf(\"%s:\\t\\t\\n\", key)\n\t\tfor v := range val {\n\t\t\tfmt.Printf(\"\\t%s\\t\\n\", v)\n\t\t}\n\t}\n}\n\nfunc ExampleDas_Delete() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tdas = das.Delete(keyBuff)\n\tdas = das.Delete(keyTmpl)\n\tdas = das.Delete(keyStrg)\n\tdas = das.Delete(keyInt8)\n\tdas = das.Delete(keyBool)\n\n\tfmt.Println(\"Len == 0 ?\", das.Len())\n}\n\nfunc ExampleDas_Fetch() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tkey := keyBool\n\tfmt.Printf(\"%s:\\t\\t\\n\", key)\n\tif vS, ok := das.Fetch(key); ok {\n\t\tfor i := range vS {\n\t\t\tfmt.Printf(\"\\t%s\\t\\n\", vS[i])\n\t\t}\n\t}\n}\n\nfunc ExampleDas_Len() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tfmt.Println(\"Len == 10 ?\", das.Len())\n}\n\nfunc ExampleDas_Lookup() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tvar res []string\n\tres = das.Lookup(keyBuff)\n\tres = das.Lookup(keyTmpl)\n\tres = das.Lookup(keyStrg)\n\tres = das.Lookup(keyInt8)\n\tres = das.Lookup(keyBool)\n\n\tfmt.Println(\"Len == 5 ?\", len(res))\n}\n\nfunc ExampleDas_KeyS() {\n\tdas := New()\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tvar res []interface{}\n\tres = das.KeyS()\n\tfmt.Println(\"Len == 3 ???\", len(res))\n\tfmt.Println(\"Is result sorted?\", res)\n\n}\n\nfunc ExampleDas_Init() {\n\tvar das *Das \/\/ test also lazyInit\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tfmt.Println(\"Len == 5 ?\", das.Len())\n\tdas = das.Init()\n\tfmt.Println(\"Len == 0 ?\", das.Len())\n\n\tdas = das.Assign(keyBuff, newData...)\n\tdas = das.Assign(keyTmpl, newData...)\n\tdas = das.Assign(keyStrg, newData...)\n\tdas = das.Assign(keyInt8, newData...)\n\tdas = das.Assign(keyBool, newData...)\n\n\tdas = das.Append(keyBuff, addData...)\n\tdas = das.Append(keyTmpl, addData...)\n\tdas = das.Append(keyStrg, addData...)\n\tdas = das.Append(keyInt8, addData...)\n\tdas = das.Append(keyBool, addData...)\n\n\tfmt.Println(\"Len == 5 ?\", das.Len())\n}\n<|endoftext|>"}
{"text":"<commit_before>package core\n\nimport (\n    \"fmt\"\n    \"io\/ioutil\"\n    \"os\"\n    \"os\/user\"\n    \"time\"\n\n    \"github.com\/astaxie\/beego\/config\"\n)\n\nconst (\n    CONF_NAME string = \"app.conf\"\n    APP_NAME string = \"watcher\"\n    permMode os.FileMode = 0666\n)\n\n\/\/ Singleton\nvar instantiated *Settings = nil\n\nfunc SettingsPtr() *Settings {\n    if instantiated == nil {\n        instantiated = new(Settings);\n    }\n    return instantiated;\n}\n\ntype Settings struct {\n    HomeDir string\n    Idle time.Duration\n    Work time.Duration\n    IdleConst time.Duration\n    WorkConst time.Duration\n    TotalIdle time.Duration\n    TotalWork time.Duration\n    Tick time.Duration\n    Protect time.Duration\n    StartTime time.Time\n    UpTime time.Duration\n    cfg config.ConfigContainer\n    dir string\n    Stage string\n    Last_stage string\n    Ready bool\n    Paused bool\n    Idle_work_title string\n    Idle_work_body string\n    Idle_work_image string\n    Work_idle_title string\n    Work_idle_body string\n    Work_idle_image string\n    Unfinished_idle_title string\n    Unfinished_idle_body string\n    Unfinished_idle_image string\n    Alarm_file string\n    Maximum_notify int\n    Notify_count int\n    Webserver_address string\n}\n\nfunc (s *Settings) GetHomeDir() (string, error) {\n    \n    if len(s.HomeDir) != 0 {\n        return s.HomeDir, nil\n    }\n\n    user, err := user.Current()\n    if err != nil {\n        return s.HomeDir, err\n    }\n\n    s.HomeDir = user.HomeDir\n\n    return s.HomeDir, nil\n}\n\nfunc (s *Settings) Init() *Settings {\n\n    fmt.Printf(\"Settings init ...\\n\")\n\n    if len(s.HomeDir) == 0 {\n        s.GetHomeDir()\n    }\n\n    s.StartTime = time.Now()\n    s.dir = fmt.Sprintf(\"%s\/.%s\/\", s.HomeDir, APP_NAME)\n\n    s.Paused = false\n    s.WorkConst = 2700 * time.Second \/\/ 45min\n    s.IdleConst = 900 * time.Second \/\/ 15min\n    s.Tick = 1 * time.Second\n    s.Protect = 30 * time.Second\n    s.Stage = \"work\" \/\/ work|idle|signal\n    s.Idle_work_title = \"Внимание\"\n    s.Idle_work_body = \"Ты отдыхаешь уже {idle_time} пора приниматся за работу!\"\n    s.Idle_work_image = \"\"\n    s.Work_idle_title = \"Внимание\"\n    s.Work_idle_body = \"Ты работешь уже {work_time}, иди отдохни, выпей чаю!\"\n    s.Work_idle_image = \"\"\n    s.Unfinished_idle_title = \"Внимание\"\n    s.Unfinished_idle_body = \"{idle} ещё не прошло, иди отдохни, выпей чаю!\"\n    s.Unfinished_idle_image = \"\"\n    s.Alarm_file = \"aperture_logo_bells_01_01.wav\"\n    s.Webserver_address = \"0.0.0.0:8080\"\n    s.Maximum_notify = 3\n\n\/\/    create app conf dir\n    fileList, _ := ioutil.ReadDir(s.HomeDir)\n\n    var exist bool\n    for _, file := range fileList {\n        if file.Name() == \".\"+APP_NAME {\n            exist = true\n            break\n        }\n    }\n\n    if !exist {\n        dir := fmt.Sprintf(`%s\/.%s`, s.HomeDir, APP_NAME)\n        fmt.Printf(\"create dir: %s\\n\", dir)\n        os.MkdirAll(dir, os.ModePerm)\n    }\n\n    return s\n}\n\nfunc (s *Settings) Save() (*Settings, error) {\n\n    if len(s.HomeDir) == 0 {\n        s.GetHomeDir()\n    }\n\n    if _, err := os.Stat(s.dir + CONF_NAME); os.IsNotExist(err) {\n        ioutil.WriteFile(s.dir + CONF_NAME, []byte{}, permMode)\n    }\n\n    cfg, err := config.NewConfig(\"ini\", s.dir + CONF_NAME)\n    if err != nil {\n        return s, err\n    }\n\n    cfg.Set(\"paused\", fmt.Sprintf(\"%t\", s.Paused))\n    cfg.Set(\"idle\", fmt.Sprintf(\"%v\", s.IdleConst.Seconds()))\n    cfg.Set(\"work\", fmt.Sprintf(\"%v\", s.WorkConst.Seconds()))\n    cfg.Set(\"protect\", fmt.Sprintf(\"%v\", s.Protect.Seconds()))\n    cfg.Set(\"idle_work_title\", s.Idle_work_title)\n    cfg.Set(\"idle_work_body\", s.Idle_work_body)\n    cfg.Set(\"idle_work_image\", s.Idle_work_image)\n    cfg.Set(\"work_idle_title\", s.Work_idle_title)\n    cfg.Set(\"work_idle_body\", s.Work_idle_body)\n    cfg.Set(\"work_idle_image\", s.Work_idle_image)\n    cfg.Set(\"unfinished_idle_title\", s.Unfinished_idle_title)\n    cfg.Set(\"unfinished_idle_body\", s.Unfinished_idle_body)\n    cfg.Set(\"unfinished_idle_image\", s.Unfinished_idle_image)\n    cfg.Set(\"alarm_file\", s.Alarm_file)\n    cfg.Set(\"webserver_address\", s.Webserver_address)\n    cfg.Set(\"maximum_notify\", string(s.Maximum_notify))\n\n    if err := cfg.SaveConfigFile(s.dir + CONF_NAME); err != nil {\n        fmt.Printf(\"err with create conf file: %s\\n\", s.dir + CONF_NAME)\n        return s, err\n    }\n\n    return s, nil\n}\n\nfunc (s *Settings) Load() (*Settings, error) {\n\n    fmt.Printf(\"read config: %s\\n\", s.dir + CONF_NAME)\n\n    if _, err := os.Stat(s.dir + CONF_NAME); os.IsNotExist(err) {\n        return s.Save()\n    }\n\n    \/\/ read config file\n    cfg, err := config.NewConfig(\"ini\", s.dir + CONF_NAME)\n    if err != nil {\n        return s, err\n    }\n\n    second := func(key string) time.Duration {\n        val, _ := cfg.Int(key)\n        return time.Duration(val) * time.Second\n    }\n\n    s.Ready = true\n    s.Paused, _ = cfg.Bool(\"paused\")\n    s.IdleConst = second(\"idle\")\n    s.WorkConst = second(\"work\")\n    s.Protect = second(\"protect\")\n    s.Idle_work_title = cfg.String(\"idle_work_title\")\n    s.Idle_work_body = cfg.String(\"idle_work_body\")\n    s.Idle_work_image = cfg.String(\"idle_work_image\")\n    s.Work_idle_title = cfg.String(\"work_idle_title\")\n    s.Work_idle_body = cfg.String(\"work_idle_body\")\n    s.Work_idle_image = cfg.String(\"work_idle_image\")\n    s.Unfinished_idle_title = cfg.String(\"unfinished_idle_title\")\n    s.Unfinished_idle_body = cfg.String(\"unfinished_idle_body\")\n    s.Unfinished_idle_image = cfg.String(\"unfinished_idle_image\")\n    s.Alarm_file = cfg.String(\"alarm_file\")\n    s.Webserver_address = cfg.String(\"webserver_address\")\n    s.Maximum_notify, _ = cfg.Int(\"maximum_notify\")\n\n    return s, nil\n}\n<commit_msg>fix maximum_notify variable<commit_after>package core\n\nimport (\n    \"fmt\"\n    \"io\/ioutil\"\n    \"os\"\n    \"os\/user\"\n    \"time\"\n\n    \"github.com\/astaxie\/beego\/config\"\n)\n\nconst (\n    CONF_NAME string = \"app.conf\"\n    APP_NAME string = \"watcher\"\n    permMode os.FileMode = 0666\n)\n\n\/\/ Singleton\nvar instantiated *Settings = nil\n\nfunc SettingsPtr() *Settings {\n    if instantiated == nil {\n        instantiated = new(Settings);\n    }\n    return instantiated;\n}\n\ntype Settings struct {\n    HomeDir string\n    Idle time.Duration\n    Work time.Duration\n    IdleConst time.Duration\n    WorkConst time.Duration\n    TotalIdle time.Duration\n    TotalWork time.Duration\n    Tick time.Duration\n    Protect time.Duration\n    StartTime time.Time\n    UpTime time.Duration\n    cfg config.ConfigContainer\n    dir string\n    Stage string\n    Last_stage string\n    Ready bool\n    Paused bool\n    Idle_work_title string\n    Idle_work_body string\n    Idle_work_image string\n    Work_idle_title string\n    Work_idle_body string\n    Work_idle_image string\n    Unfinished_idle_title string\n    Unfinished_idle_body string\n    Unfinished_idle_image string\n    Alarm_file string\n    Maximum_notify int\n    Notify_count int\n    Webserver_address string\n}\n\nfunc (s *Settings) GetHomeDir() (string, error) {\n    \n    if len(s.HomeDir) != 0 {\n        return s.HomeDir, nil\n    }\n\n    user, err := user.Current()\n    if err != nil {\n        return s.HomeDir, err\n    }\n\n    s.HomeDir = user.HomeDir\n\n    return s.HomeDir, nil\n}\n\nfunc (s *Settings) Init() *Settings {\n\n    fmt.Printf(\"Settings init ...\\n\")\n\n    if len(s.HomeDir) == 0 {\n        s.GetHomeDir()\n    }\n\n    s.StartTime = time.Now()\n    s.dir = fmt.Sprintf(\"%s\/.%s\/\", s.HomeDir, APP_NAME)\n\n    s.Paused = false\n    s.WorkConst = 2700 * time.Second \/\/ 45min\n    s.IdleConst = 900 * time.Second \/\/ 15min\n    s.Tick = 1 * time.Second\n    s.Protect = 30 * time.Second\n    s.Stage = \"work\" \/\/ work|idle|signal\n    s.Idle_work_title = \"Внимание\"\n    s.Idle_work_body = \"Ты отдыхаешь уже {idle_time} пора приниматся за работу!\"\n    s.Idle_work_image = \"\"\n    s.Work_idle_title = \"Внимание\"\n    s.Work_idle_body = \"Ты работешь уже {work_time}, иди отдохни, выпей чаю!\"\n    s.Work_idle_image = \"\"\n    s.Unfinished_idle_title = \"Внимание\"\n    s.Unfinished_idle_body = \"{idle} ещё не прошло, иди отдохни, выпей чаю!\"\n    s.Unfinished_idle_image = \"\"\n    s.Alarm_file = \"aperture_logo_bells_01_01.wav\"\n    s.Webserver_address = \"0.0.0.0:8080\"\n    s.Maximum_notify = 3\n\n\/\/    create app conf dir\n    fileList, _ := ioutil.ReadDir(s.HomeDir)\n\n    var exist bool\n    for _, file := range fileList {\n        if file.Name() == \".\"+APP_NAME {\n            exist = true\n            break\n        }\n    }\n\n    if !exist {\n        dir := fmt.Sprintf(`%s\/.%s`, s.HomeDir, APP_NAME)\n        fmt.Printf(\"create dir: %s\\n\", dir)\n        os.MkdirAll(dir, os.ModePerm)\n    }\n\n    return s\n}\n\nfunc (s *Settings) Save() (*Settings, error) {\n\n    if len(s.HomeDir) == 0 {\n        s.GetHomeDir()\n    }\n\n    if _, err := os.Stat(s.dir + CONF_NAME); os.IsNotExist(err) {\n        ioutil.WriteFile(s.dir + CONF_NAME, []byte{}, permMode)\n    }\n\n    cfg, err := config.NewConfig(\"ini\", s.dir + CONF_NAME)\n    if err != nil {\n        return s, err\n    }\n\n    cfg.Set(\"paused\", fmt.Sprintf(\"%t\", s.Paused))\n    cfg.Set(\"idle\", fmt.Sprintf(\"%v\", s.IdleConst.Seconds()))\n    cfg.Set(\"work\", fmt.Sprintf(\"%v\", s.WorkConst.Seconds()))\n    cfg.Set(\"protect\", fmt.Sprintf(\"%v\", s.Protect.Seconds()))\n    cfg.Set(\"idle_work_title\", s.Idle_work_title)\n    cfg.Set(\"idle_work_body\", s.Idle_work_body)\n    cfg.Set(\"idle_work_image\", s.Idle_work_image)\n    cfg.Set(\"work_idle_title\", s.Work_idle_title)\n    cfg.Set(\"work_idle_body\", s.Work_idle_body)\n    cfg.Set(\"work_idle_image\", s.Work_idle_image)\n    cfg.Set(\"unfinished_idle_title\", s.Unfinished_idle_title)\n    cfg.Set(\"unfinished_idle_body\", s.Unfinished_idle_body)\n    cfg.Set(\"unfinished_idle_image\", s.Unfinished_idle_image)\n    cfg.Set(\"alarm_file\", s.Alarm_file)\n    cfg.Set(\"webserver_address\", s.Webserver_address)\n    cfg.Set(\"maximum_notify\", fmt.Sprintf(\"%d\", s.Maximum_notify))\n\n    if err := cfg.SaveConfigFile(s.dir + CONF_NAME); err != nil {\n        fmt.Printf(\"err with create conf file: %s\\n\", s.dir + CONF_NAME)\n        return s, err\n    }\n\n    return s, nil\n}\n\nfunc (s *Settings) Load() (*Settings, error) {\n\n    fmt.Printf(\"read config: %s\\n\", s.dir + CONF_NAME)\n\n    if _, err := os.Stat(s.dir + CONF_NAME); os.IsNotExist(err) {\n        return s.Save()\n    }\n\n    \/\/ read config file\n    cfg, err := config.NewConfig(\"ini\", s.dir + CONF_NAME)\n    if err != nil {\n        return s, err\n    }\n\n    second := func(key string) time.Duration {\n        val, _ := cfg.Int(key)\n        return time.Duration(val) * time.Second\n    }\n\n    s.Ready = true\n    s.Paused, _ = cfg.Bool(\"paused\")\n    s.IdleConst = second(\"idle\")\n    s.WorkConst = second(\"work\")\n    s.Protect = second(\"protect\")\n    s.Idle_work_title = cfg.String(\"idle_work_title\")\n    s.Idle_work_body = cfg.String(\"idle_work_body\")\n    s.Idle_work_image = cfg.String(\"idle_work_image\")\n    s.Work_idle_title = cfg.String(\"work_idle_title\")\n    s.Work_idle_body = cfg.String(\"work_idle_body\")\n    s.Work_idle_image = cfg.String(\"work_idle_image\")\n    s.Unfinished_idle_title = cfg.String(\"unfinished_idle_title\")\n    s.Unfinished_idle_body = cfg.String(\"unfinished_idle_body\")\n    s.Unfinished_idle_image = cfg.String(\"unfinished_idle_image\")\n    s.Alarm_file = cfg.String(\"alarm_file\")\n    s.Webserver_address = cfg.String(\"webserver_address\")\n    s.Maximum_notify, _ = cfg.Int(\"maximum_notify\")\n\n    return s, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package core\n\n\/*\n#cgo CFLAGS: -I.\/src\/include\n#include \"lwip\/tcp.h\"\n*\/\nimport \"C\"\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"sync\"\n\t\"unsafe\"\n)\n\ntype tcpConn struct {\n\tsync.Mutex\n\n\tpcb         *C.struct_tcp_pcb\n\thandler     ConnectionHandler\n\tnetwork     string\n\tremoteAddr  net.Addr\n\tlocalAddr   net.Addr\n\tconnKeyArg  unsafe.Pointer\n\tconnKey     uint32\n\tclosing     bool\n\tlocalClosed bool\n\taborting    bool\n\tctx         context.Context\n\tcancel      context.CancelFunc\n\n\t\/\/ Data from remote not yet write to local will buffer into this channel.\n\tlocalWriteCh    chan []byte\n\tlocalWriteSubCh chan []byte\n}\n\nfunc checkTCPConns() {\n\ttcpConns.Range(func(_, c interface{}) bool {\n\t\tstate := c.(*tcpConn).pcb.state\n\t\tif c.(*tcpConn).pcb == nil ||\n\t\t\tstate == C.CLOSED ||\n\t\t\tstate == C.CLOSE_WAIT {\n\t\t\tc.(*tcpConn).Release()\n\t\t}\n\t\treturn true\n\t})\n}\n\nfunc NewTCPConnection(pcb *C.struct_tcp_pcb, handler ConnectionHandler) (Connection, error) {\n\t\/\/ prepare key\n\tconnKeyArg := NewConnKeyArg()\n\tconnKey := rand.Uint32()\n\tSetConnKeyVal(unsafe.Pointer(connKeyArg), connKey)\n\n\tif tcpConnectionHandler == nil {\n\t\treturn nil, errors.New(\"no registered TCP connection handlers found\")\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tconn := &tcpConn{\n\t\tpcb:             pcb,\n\t\thandler:         handler,\n\t\tnetwork:         \"tcp\",\n\t\tlocalAddr:       ParseTCPAddr(IPAddrNTOA(pcb.remote_ip), uint16(pcb.remote_port)),\n\t\tremoteAddr:      ParseTCPAddr(IPAddrNTOA(pcb.local_ip), uint16(pcb.local_port)),\n\t\tconnKeyArg:      connKeyArg,\n\t\tconnKey:         connKey,\n\t\tclosing:         false,\n\t\tlocalClosed:     false,\n\t\taborting:        false,\n\t\tctx:             ctx,\n\t\tcancel:          cancel,\n\t\tlocalWriteCh:    make(chan []byte, 32),\n\t\tlocalWriteSubCh: make(chan []byte, 1),\n\t}\n\n\t\/\/ Associate conn with key and save to the global map.\n\ttcpConns.Store(connKey, conn)\n\n\tgo checkTCPConns()\n\n\t\/\/ Pass the key as arg for subsequent tcp callbacks.\n\tC.tcp_arg(pcb, unsafe.Pointer(connKeyArg))\n\n\tSetTCPRecvCallback(pcb)\n\tSetTCPSentCallback(pcb)\n\tSetTCPErrCallback(pcb)\n\tSetTCPPollCallback(pcb, C.u8_t(1)) \/\/ interval 1 means Poll will be called twice a second\n\n\terr := handler.Connect(conn, conn.RemoteAddr())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn conn, nil\n}\n\nfunc (conn *tcpConn) RemoteAddr() net.Addr {\n\treturn conn.remoteAddr\n}\n\nfunc (conn *tcpConn) LocalAddr() net.Addr {\n\treturn conn.localAddr\n}\n\nfunc (conn *tcpConn) Receive(data []byte) error {\n\tif conn.isClosing() {\n\t\treturn errors.New(fmt.Sprintf(\"conn %v <-> %v is closing\", conn.LocalAddr(), conn.RemoteAddr()))\n\t}\n\n\terr := conn.handler.DidReceive(conn, data)\n\tif err != nil {\n\t\treturn errors.New(fmt.Sprintf(\"write proxy failed: %v\", err))\n\t}\n\n\tC.tcp_recved(conn.pcb, C.u16_t(len(data)))\n\n\treturn nil\n}\n\nfunc (conn *tcpConn) tryWriteLocal() {\n\tlwipMutex.Lock()\n\tdefer lwipMutex.Unlock()\n\nLoop:\n\tfor {\n\t\t\/\/ Using 2 select to ensure data in localWriteSubCh will be drained first.\n\t\tselect {\n\t\tcase data := <-conn.localWriteSubCh:\n\t\t\twritten, err := conn.tcpWrite(data)\n\t\t\tif !written || err != nil {\n\t\t\t\t\/\/ TODO the check is for debug purpose, and should be removed later\n\t\t\t\tif len(conn.localWriteSubCh) > 0 {\n\t\t\t\t\tlog.Fatal(\"send to non-empty sub chan\")\n\t\t\t\t}\n\t\t\t\t\/\/ Data not written, buffer again.\n\t\t\t\tconn.localWriteSubCh <- data\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tdefault:\n\t\t}\n\n\t\tselect {\n\t\tcase data := <-conn.localWriteSubCh:\n\t\t\twritten, err := conn.tcpWrite(data)\n\t\t\tif !written || err != nil {\n\t\t\t\t\/\/ TODO the check is for debug purpose, and should be removed later\n\t\t\t\tif len(conn.localWriteSubCh) > 0 {\n\t\t\t\t\tlog.Fatal(\"send to non-empty sub chan\")\n\t\t\t\t}\n\t\t\t\t\/\/ Data not written, buffer again.\n\t\t\t\tconn.localWriteSubCh <- data\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tcase data := <-conn.localWriteCh:\n\t\t\twritten, err := conn.tcpWrite(data)\n\t\t\tif !written || err != nil {\n\t\t\t\t\/\/ TODO the check is for debug purpose, and should be removed later\n\t\t\t\tif len(conn.localWriteSubCh) > 0 {\n\t\t\t\t\tlog.Fatal(\"send to non-empty sub chan\")\n\t\t\t\t}\n\t\t\t\t\/\/ If writing is not success, buffer to the sub channel, and next time\n\t\t\t\t\/\/ we try to read from the sub channel first. Using a sub channel here\n\t\t\t\t\/\/ because the data must be sent in correct order and we have no way\n\t\t\t\t\/\/ to prepend data to the head of a channel.\n\t\t\t\tconn.localWriteSubCh <- data\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tdefault:\n\t\t\tbreak Loop\n\t\t}\n\t}\n\n\t\/\/ TODO the check is for debug purpose, and should be removed later\n\tif conn.pcb == nil {\n\t\tlog.Fatal(\"tcp_output nil pcb\")\n\t}\n\t\/\/ Actually send data.\n\terr := C.tcp_output(conn.pcb)\n\tif err != C.ERR_OK {\n\t\tlog.Printf(\"tcp_output error with lwip error code: %v\", int(err))\n\t}\n}\n\n\/\/ tcpWrite enqueues data to snd_buf, and treats ERR_MEM returned by tcp_write not an error,\n\/\/ but instead tells the caller that data is not successfully enqueued, and should try\n\/\/ again another time. By calling this function, the lwIP thread is assumed to be already\n\/\/ locked by the caller.\nfunc (conn *tcpConn) tcpWrite(data []byte) (bool, error) {\n\tif len(data) <= int(conn.pcb.snd_buf) {\n\t\t\/\/ Enqueue data, data copy here! Copying is required because lwIP must keep the data until they\n\t\t\/\/ are acknowledged (receiving ACK segments) by other hosts for retransmission purposes, it's\n\t\t\/\/ not obvious how to implement zero-copy here.\n\t\terr := C.tcp_write(conn.pcb, unsafe.Pointer(&data[0]), C.u16_t(len(data)), C.TCP_WRITE_FLAG_COPY)\n\t\tif err == C.ERR_OK {\n\t\t\treturn true, nil\n\t\t} else if err != C.ERR_MEM {\n\t\t\treturn false, errors.New(fmt.Sprintf(\"lwip tcp_write failed with error code: %v\", int(err)))\n\t\t}\n\t}\n\treturn false, nil\n}\n\nfunc (conn *tcpConn) Write(data []byte) (int, error) {\n\tif conn.isLocalClosed() {\n\t\treturn 0, errors.New(fmt.Sprintf(\"conn %v <-> %v is closing\", conn.LocalAddr(), conn.RemoteAddr()))\n\t}\n\n\tvar written = false\n\tvar err error\n\n\t\/\/ If there isn't any pending data left, we can try to write the data first to avoid one copy,\n\t\/\/ if there is pending data not yet sent, we must copy and buffer the data in order to maintain\n\t\/\/ the transmission order.\n\tif !conn.hasPendingLocalData() {\n\t\tlwipMutex.Lock()\n\t\twritten, err = conn.tcpWrite(data)\n\t\tlwipMutex.Unlock()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tif !written {\n\t\tselect {\n\t\t\/\/ Buffer the data here and try sending it later, one could set a smaller localWriteCh size\n\t\t\/\/ to limit data copying times and memory usage, by sacrificing performance. But writing data\n\t\t\/\/ to local is quite fast, thus it should be safe even has a size of 1 localWriteCh.\n\t\tcase conn.localWriteCh <- append([]byte(nil), data...): \/\/ data copy here!\n\t\tcase <-conn.ctx.Done():\n\t\t\treturn 0, conn.ctx.Err()\n\t\t}\n\t}\n\n\t\/\/ Try to send pending data if any, and call tcp_output().\n\tgo conn.tryWriteLocal()\n\n\treturn len(data), nil\n}\n\nfunc (conn *tcpConn) Sent(len uint16) error {\n\tconn.handler.DidSend(conn, len)\n\t\/\/ Some packets are acknowledged by local client, check if any pending data to send.\n\treturn conn.CheckState()\n}\n\nfunc (conn *tcpConn) isClosing() bool {\n\tconn.Lock()\n\tdefer conn.Unlock()\n\treturn conn.closing\n}\n\nfunc (conn *tcpConn) isAborting() bool {\n\tconn.Lock()\n\tdefer conn.Unlock()\n\treturn conn.aborting\n}\n\nfunc (conn *tcpConn) isLocalClosed() bool {\n\tconn.Lock()\n\tdefer conn.Unlock()\n\treturn conn.localClosed\n}\n\nfunc (conn *tcpConn) hasPendingLocalData() bool {\n\tif len(conn.localWriteCh) > 0 || len(conn.localWriteSubCh) > 0 {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (conn *tcpConn) CheckState() error {\n\t\/\/ Still have data to send\n\tif conn.hasPendingLocalData() && !conn.isLocalClosed() {\n\t\tgo conn.tryWriteLocal()\n\t\t\/\/ Return and wait for the Sent() callback to be called, and then check again.\n\t\treturn NewLWIPError(LWIP_ERR_OK)\n\t}\n\n\tif conn.isClosing() || conn.isLocalClosed() {\n\t\tconn.closeInternal()\n\t}\n\n\tif conn.isAborting() {\n\t\tconn.abortInternal()\n\t\treturn NewLWIPError(LWIP_ERR_ABRT)\n\t}\n\n\treturn NewLWIPError(LWIP_ERR_OK)\n}\n\nfunc (conn *tcpConn) Close() error {\n\tconn.Lock()\n\tdefer conn.Unlock()\n\n\t\/\/ Close maybe called outside of lwIP thread, we should not call tcp_close() in this\n\t\/\/ function, instead just make a flag to indicate we are closing the connection.\n\tconn.closing = true\n\treturn nil\n}\n\nfunc (conn *tcpConn) setLocalClosed() error {\n\tconn.Lock()\n\tdefer conn.Unlock()\n\n\tconn.localClosed = true\n\treturn nil\n}\n\nfunc (conn *tcpConn) closeInternal() error {\n\tif conn.pcb == nil {\n\t\tlog.Fatal(\"nil pcb when close, maybe aborted already\")\n\t}\n\n\tC.tcp_arg(conn.pcb, nil)\n\tC.tcp_recv(conn.pcb, nil)\n\tC.tcp_sent(conn.pcb, nil)\n\tC.tcp_err(conn.pcb, nil)\n\tC.tcp_poll(conn.pcb, nil, 0)\n\n\tconn.Release()\n\n\tconn.cancel()\n\n\terr := C.tcp_close(conn.pcb)\n\tif err == C.ERR_OK {\n\t\treturn nil\n\t} else {\n\t\treturn errors.New(fmt.Sprint(\"close TCP connection failed, lwip error code %d\", int(err)))\n\t}\n}\n\nfunc (conn *tcpConn) abortInternal() {\n\tlog.Printf(\"abort TCP connection %v->%v\", conn.LocalAddr(), conn.RemoteAddr())\n\tconn.Release()\n\tC.tcp_abort(conn.pcb)\n}\n\nfunc (conn *tcpConn) Abort() {\n\tconn.Lock()\n\tdefer conn.Unlock()\n\n\tconn.aborting = true\n}\n\n\/\/ The corresponding pcb is already freed when this callback is called\nfunc (conn *tcpConn) Err(err error) {\n\tlog.Printf(\"error on TCP connection %v->%v: %v\", conn.LocalAddr(), conn.RemoteAddr(), err)\n\tconn.Release()\n\tconn.cancel()\n\tconn.handler.DidClose(conn)\n}\n\nfunc (conn *tcpConn) LocalDidClose() error {\n\tlog.Printf(\"local close TCP connection %v->%v\", conn.LocalAddr(), conn.RemoteAddr())\n\tconn.handler.LocalDidClose(conn)\n\tconn.setLocalClosed()    \/\/ flag closing\n\treturn conn.CheckState() \/\/ check pending data\n}\n\nfunc (conn *tcpConn) Release() {\n\tif _, found := tcpConns.Load(conn.connKey); found {\n\t\tFreeConnKeyArg(conn.connKeyArg)\n\t\ttcpConns.Delete(conn.connKey)\n\t}\n\tlog.Printf(\"ended TCP connection %v->%v\", conn.LocalAddr(), conn.RemoteAddr())\n}\n\nfunc (conn *tcpConn) Poll() error {\n\treturn conn.CheckState()\n}\n<commit_msg>checks are causing error and seems not necessary<commit_after>package core\n\n\/*\n#cgo CFLAGS: -I.\/src\/include\n#include \"lwip\/tcp.h\"\n*\/\nimport \"C\"\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"sync\"\n\t\"unsafe\"\n)\n\ntype tcpConn struct {\n\tsync.Mutex\n\n\tpcb         *C.struct_tcp_pcb\n\thandler     ConnectionHandler\n\tnetwork     string\n\tremoteAddr  net.Addr\n\tlocalAddr   net.Addr\n\tconnKeyArg  unsafe.Pointer\n\tconnKey     uint32\n\tclosing     bool\n\tlocalClosed bool\n\taborting    bool\n\tctx         context.Context\n\tcancel      context.CancelFunc\n\n\t\/\/ Data from remote not yet write to local will buffer into this channel.\n\tlocalWriteCh    chan []byte\n\tlocalWriteSubCh chan []byte\n}\n\n\/\/ func checkTCPConns() {\n\/\/ \ttcpConns.Range(func(_, c interface{}) bool {\n\/\/ \t\tstate := c.(*tcpConn).pcb.state\n\/\/ \t\tif c.(*tcpConn).pcb == nil ||\n\/\/ \t\t\tstate == C.CLOSED ||\n\/\/ \t\t\tstate == C.CLOSE_WAIT {\n\/\/ \t\t\tc.(*tcpConn).Release()\n\/\/ \t\t}\n\/\/ \t\treturn true\n\/\/ \t})\n\/\/ }\n\nfunc NewTCPConnection(pcb *C.struct_tcp_pcb, handler ConnectionHandler) (Connection, error) {\n\t\/\/ prepare key\n\tconnKeyArg := NewConnKeyArg()\n\tconnKey := rand.Uint32()\n\tSetConnKeyVal(unsafe.Pointer(connKeyArg), connKey)\n\n\tif tcpConnectionHandler == nil {\n\t\treturn nil, errors.New(\"no registered TCP connection handlers found\")\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tconn := &tcpConn{\n\t\tpcb:             pcb,\n\t\thandler:         handler,\n\t\tnetwork:         \"tcp\",\n\t\tlocalAddr:       ParseTCPAddr(IPAddrNTOA(pcb.remote_ip), uint16(pcb.remote_port)),\n\t\tremoteAddr:      ParseTCPAddr(IPAddrNTOA(pcb.local_ip), uint16(pcb.local_port)),\n\t\tconnKeyArg:      connKeyArg,\n\t\tconnKey:         connKey,\n\t\tclosing:         false,\n\t\tlocalClosed:     false,\n\t\taborting:        false,\n\t\tctx:             ctx,\n\t\tcancel:          cancel,\n\t\tlocalWriteCh:    make(chan []byte, 32),\n\t\tlocalWriteSubCh: make(chan []byte, 1),\n\t}\n\n\t\/\/ Associate conn with key and save to the global map.\n\ttcpConns.Store(connKey, conn)\n\n\t\/\/ go checkTCPConns()\n\n\t\/\/ Pass the key as arg for subsequent tcp callbacks.\n\tC.tcp_arg(pcb, unsafe.Pointer(connKeyArg))\n\n\tSetTCPRecvCallback(pcb)\n\tSetTCPSentCallback(pcb)\n\tSetTCPErrCallback(pcb)\n\tSetTCPPollCallback(pcb, C.u8_t(1)) \/\/ interval 1 means Poll will be called twice a second\n\n\terr := handler.Connect(conn, conn.RemoteAddr())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn conn, nil\n}\n\nfunc (conn *tcpConn) RemoteAddr() net.Addr {\n\treturn conn.remoteAddr\n}\n\nfunc (conn *tcpConn) LocalAddr() net.Addr {\n\treturn conn.localAddr\n}\n\nfunc (conn *tcpConn) Receive(data []byte) error {\n\tif conn.isClosing() {\n\t\treturn errors.New(fmt.Sprintf(\"conn %v <-> %v is closing\", conn.LocalAddr(), conn.RemoteAddr()))\n\t}\n\n\terr := conn.handler.DidReceive(conn, data)\n\tif err != nil {\n\t\treturn errors.New(fmt.Sprintf(\"write proxy failed: %v\", err))\n\t}\n\n\tC.tcp_recved(conn.pcb, C.u16_t(len(data)))\n\n\treturn nil\n}\n\nfunc (conn *tcpConn) tryWriteLocal() {\n\tlwipMutex.Lock()\n\tdefer lwipMutex.Unlock()\n\nLoop:\n\tfor {\n\t\t\/\/ Using 2 select to ensure data in localWriteSubCh will be drained first.\n\t\tselect {\n\t\tcase data := <-conn.localWriteSubCh:\n\t\t\twritten, err := conn.tcpWrite(data)\n\t\t\tif !written || err != nil {\n\t\t\t\t\/\/ TODO the check is for debug purpose, and should be removed later\n\t\t\t\tif len(conn.localWriteSubCh) > 0 {\n\t\t\t\t\tlog.Fatal(\"send to non-empty sub chan\")\n\t\t\t\t}\n\t\t\t\t\/\/ Data not written, buffer again.\n\t\t\t\tconn.localWriteSubCh <- data\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tdefault:\n\t\t}\n\n\t\tselect {\n\t\tcase data := <-conn.localWriteSubCh:\n\t\t\twritten, err := conn.tcpWrite(data)\n\t\t\tif !written || err != nil {\n\t\t\t\t\/\/ TODO the check is for debug purpose, and should be removed later\n\t\t\t\tif len(conn.localWriteSubCh) > 0 {\n\t\t\t\t\tlog.Fatal(\"send to non-empty sub chan\")\n\t\t\t\t}\n\t\t\t\t\/\/ Data not written, buffer again.\n\t\t\t\tconn.localWriteSubCh <- data\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tcase data := <-conn.localWriteCh:\n\t\t\twritten, err := conn.tcpWrite(data)\n\t\t\tif !written || err != nil {\n\t\t\t\t\/\/ TODO the check is for debug purpose, and should be removed later\n\t\t\t\tif len(conn.localWriteSubCh) > 0 {\n\t\t\t\t\tlog.Fatal(\"send to non-empty sub chan\")\n\t\t\t\t}\n\t\t\t\t\/\/ If writing is not success, buffer to the sub channel, and next time\n\t\t\t\t\/\/ we try to read from the sub channel first. Using a sub channel here\n\t\t\t\t\/\/ because the data must be sent in correct order and we have no way\n\t\t\t\t\/\/ to prepend data to the head of a channel.\n\t\t\t\tconn.localWriteSubCh <- data\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\tdefault:\n\t\t\tbreak Loop\n\t\t}\n\t}\n\n\t\/\/ TODO the check is for debug purpose, and should be removed later\n\tif conn.pcb == nil {\n\t\tlog.Fatal(\"tcp_output nil pcb\")\n\t}\n\t\/\/ Actually send data.\n\terr := C.tcp_output(conn.pcb)\n\tif err != C.ERR_OK {\n\t\tlog.Printf(\"tcp_output error with lwip error code: %v\", int(err))\n\t}\n}\n\n\/\/ tcpWrite enqueues data to snd_buf, and treats ERR_MEM returned by tcp_write not an error,\n\/\/ but instead tells the caller that data is not successfully enqueued, and should try\n\/\/ again another time. By calling this function, the lwIP thread is assumed to be already\n\/\/ locked by the caller.\nfunc (conn *tcpConn) tcpWrite(data []byte) (bool, error) {\n\tif len(data) <= int(conn.pcb.snd_buf) {\n\t\t\/\/ Enqueue data, data copy here! Copying is required because lwIP must keep the data until they\n\t\t\/\/ are acknowledged (receiving ACK segments) by other hosts for retransmission purposes, it's\n\t\t\/\/ not obvious how to implement zero-copy here.\n\t\terr := C.tcp_write(conn.pcb, unsafe.Pointer(&data[0]), C.u16_t(len(data)), C.TCP_WRITE_FLAG_COPY)\n\t\tif err == C.ERR_OK {\n\t\t\treturn true, nil\n\t\t} else if err != C.ERR_MEM {\n\t\t\treturn false, errors.New(fmt.Sprintf(\"lwip tcp_write failed with error code: %v\", int(err)))\n\t\t}\n\t}\n\treturn false, nil\n}\n\nfunc (conn *tcpConn) Write(data []byte) (int, error) {\n\tif conn.isLocalClosed() {\n\t\treturn 0, errors.New(fmt.Sprintf(\"conn %v <-> %v is closing\", conn.LocalAddr(), conn.RemoteAddr()))\n\t}\n\n\tvar written = false\n\tvar err error\n\n\t\/\/ If there isn't any pending data left, we can try to write the data first to avoid one copy,\n\t\/\/ if there is pending data not yet sent, we must copy and buffer the data in order to maintain\n\t\/\/ the transmission order.\n\tif !conn.hasPendingLocalData() {\n\t\tlwipMutex.Lock()\n\t\twritten, err = conn.tcpWrite(data)\n\t\tlwipMutex.Unlock()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tif !written {\n\t\tselect {\n\t\t\/\/ Buffer the data here and try sending it later, one could set a smaller localWriteCh size\n\t\t\/\/ to limit data copying times and memory usage, by sacrificing performance. But writing data\n\t\t\/\/ to local is quite fast, thus it should be safe even has a size of 1 localWriteCh.\n\t\tcase conn.localWriteCh <- append([]byte(nil), data...): \/\/ data copy here!\n\t\tcase <-conn.ctx.Done():\n\t\t\treturn 0, conn.ctx.Err()\n\t\t}\n\t}\n\n\t\/\/ Try to send pending data if any, and call tcp_output().\n\tgo conn.tryWriteLocal()\n\n\treturn len(data), nil\n}\n\nfunc (conn *tcpConn) Sent(len uint16) error {\n\tconn.handler.DidSend(conn, len)\n\t\/\/ Some packets are acknowledged by local client, check if any pending data to send.\n\treturn conn.CheckState()\n}\n\nfunc (conn *tcpConn) isClosing() bool {\n\tconn.Lock()\n\tdefer conn.Unlock()\n\treturn conn.closing\n}\n\nfunc (conn *tcpConn) isAborting() bool {\n\tconn.Lock()\n\tdefer conn.Unlock()\n\treturn conn.aborting\n}\n\nfunc (conn *tcpConn) isLocalClosed() bool {\n\tconn.Lock()\n\tdefer conn.Unlock()\n\treturn conn.localClosed\n}\n\nfunc (conn *tcpConn) hasPendingLocalData() bool {\n\tif len(conn.localWriteCh) > 0 || len(conn.localWriteSubCh) > 0 {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (conn *tcpConn) CheckState() error {\n\t\/\/ Still have data to send\n\tif conn.hasPendingLocalData() && !conn.isLocalClosed() {\n\t\tgo conn.tryWriteLocal()\n\t\t\/\/ Return and wait for the Sent() callback to be called, and then check again.\n\t\treturn NewLWIPError(LWIP_ERR_OK)\n\t}\n\n\tif conn.isClosing() || conn.isLocalClosed() {\n\t\tconn.closeInternal()\n\t}\n\n\tif conn.isAborting() {\n\t\tconn.abortInternal()\n\t\treturn NewLWIPError(LWIP_ERR_ABRT)\n\t}\n\n\treturn NewLWIPError(LWIP_ERR_OK)\n}\n\nfunc (conn *tcpConn) Close() error {\n\tconn.Lock()\n\tdefer conn.Unlock()\n\n\t\/\/ Close maybe called outside of lwIP thread, we should not call tcp_close() in this\n\t\/\/ function, instead just make a flag to indicate we are closing the connection.\n\tconn.closing = true\n\treturn nil\n}\n\nfunc (conn *tcpConn) setLocalClosed() error {\n\tconn.Lock()\n\tdefer conn.Unlock()\n\n\tconn.localClosed = true\n\treturn nil\n}\n\nfunc (conn *tcpConn) closeInternal() error {\n\tif conn.pcb == nil {\n\t\tlog.Fatal(\"nil pcb when close, maybe aborted already\")\n\t}\n\n\tC.tcp_arg(conn.pcb, nil)\n\tC.tcp_recv(conn.pcb, nil)\n\tC.tcp_sent(conn.pcb, nil)\n\tC.tcp_err(conn.pcb, nil)\n\tC.tcp_poll(conn.pcb, nil, 0)\n\n\tconn.Release()\n\n\tconn.cancel()\n\n\terr := C.tcp_close(conn.pcb)\n\tif err == C.ERR_OK {\n\t\treturn nil\n\t} else {\n\t\treturn errors.New(fmt.Sprint(\"close TCP connection failed, lwip error code %d\", int(err)))\n\t}\n}\n\nfunc (conn *tcpConn) abortInternal() {\n\tlog.Printf(\"abort TCP connection %v->%v\", conn.LocalAddr(), conn.RemoteAddr())\n\tconn.Release()\n\tC.tcp_abort(conn.pcb)\n}\n\nfunc (conn *tcpConn) Abort() {\n\tconn.Lock()\n\tdefer conn.Unlock()\n\n\tconn.aborting = true\n}\n\n\/\/ The corresponding pcb is already freed when this callback is called\nfunc (conn *tcpConn) Err(err error) {\n\tlog.Printf(\"error on TCP connection %v->%v: %v\", conn.LocalAddr(), conn.RemoteAddr(), err)\n\tconn.Release()\n\tconn.cancel()\n\tconn.handler.DidClose(conn)\n}\n\nfunc (conn *tcpConn) LocalDidClose() error {\n\tlog.Printf(\"local close TCP connection %v->%v\", conn.LocalAddr(), conn.RemoteAddr())\n\tconn.handler.LocalDidClose(conn)\n\tconn.setLocalClosed()    \/\/ flag closing\n\treturn conn.CheckState() \/\/ check pending data\n}\n\nfunc (conn *tcpConn) Release() {\n\tif _, found := tcpConns.Load(conn.connKey); found {\n\t\tFreeConnKeyArg(conn.connKeyArg)\n\t\ttcpConns.Delete(conn.connKey)\n\t}\n\tlog.Printf(\"ended TCP connection %v->%v\", conn.LocalAddr(), conn.RemoteAddr())\n}\n\nfunc (conn *tcpConn) Poll() error {\n\treturn conn.CheckState()\n}\n<|endoftext|>"}
{"text":"<commit_before>package cc\n\nfunc maxPower(s string) int {\n\treturn 0\n}\n<commit_msg>solve 1446 use onepass<commit_after>package cc\n\nimport \"github.com\/catorpilor\/leetcode\/utils\"\n\nfunc maxPower(s string) int {\n\treturn useOnepass(s)\n}\n\n\/\/ useOnepass time complexity O(N), space complexity O(1)\nfunc useOnepass(s string) int {\n\tn := len(s)\n\tif n <= 1 {\n\t\treturn n\n\t}\n\tans, cur := 1, 1\n\tfor i := 1; i < n; i++ {\n\t\tif s[i] != s[i-1] {\n\t\t\tcur = 1\n\t\t\tcontinue\n\t\t}\n\t\tcur++\n\t\tans = utils.Max(ans, cur)\n\t}\n\treturn ans\n}\n<|endoftext|>"}
{"text":"<commit_before>package app_files\n\nimport (\n\t\"archive\/zip\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/cloudfoundry\/cli\/cf\/errors\"\n\t\"github.com\/cloudfoundry\/gofileutils\/fileutils\"\n)\n\ntype Zipper interface {\n\tZip(dirToZip string, targetFile *os.File) (err error)\n\tIsZipFile(path string) bool\n\tUnzip(appDir string, destDir string) (err error)\n\tGetZipSize(zipFile *os.File) (int64, error)\n}\n\ntype ApplicationZipper struct{}\n\nfunc (zipper ApplicationZipper) Zip(dirOrZipFile string, targetFile *os.File) (err error) {\n\tif zipper.IsZipFile(dirOrZipFile) {\n\t\terr = fileutils.CopyPathToWriter(dirOrZipFile, targetFile)\n\t} else {\n\t\terr = writeZipFile(dirOrZipFile, targetFile)\n\t}\n\ttargetFile.Seek(0, os.SEEK_SET)\n\treturn\n}\n\nfunc (zipper ApplicationZipper) IsZipFile(file string) (result bool) {\n\t_, err := zip.OpenReader(file)\n\treturn err == nil\n}\n\nfunc writeZipFile(dir string, targetFile *os.File) error {\n\tisEmpty, err := fileutils.IsDirEmpty(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif isEmpty {\n\t\treturn errors.NewEmptyDirError(dir)\n\t}\n\n\twriter := zip.NewWriter(targetFile)\n\tdefer writer.Close()\n\n\tappfiles := ApplicationFiles{}\n\treturn appfiles.WalkAppFiles(dir, func(fileName string, fullPath string) error {\n\t\tfileInfo, err := os.Stat(fullPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\theader, err := zip.FileInfoHeader(fileInfo)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\theader.Name = filepath.ToSlash(fileName)\n\n\t\tif fileInfo.IsDir() {\n\t\t\theader.Name += \"\/\"\n\t\t}\n\n\t\tzipFilePart, err := writer.CreateHeader(header)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif fileInfo.IsDir() {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn fileutils.CopyPathToWriter(fullPath, zipFilePart)\n\t\t}\n\t})\n}\n\nfunc (zipper ApplicationZipper) Unzip(appDir string, destDir string) (err error) {\n\tr, err := zip.OpenReader(appDir)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer r.Close()\n\n\tfor _, f := range r.File {\n\t\tfunc() {\n\t\t\tif f.FileInfo().IsDir() {\n\t\t\t\tos.MkdirAll(filepath.Join(destDir, f.Name), os.ModeDir|os.ModePerm)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar rc io.ReadCloser\n\t\t\trc, err = f.Open()\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ functional scope from above is important\n\t\t\t\/\/ otherwise this only closes the last file handle\n\t\t\tdefer rc.Close()\n\n\t\t\tdestFilePath := filepath.Join(destDir, f.Name)\n\n\t\t\terr = fileutils.CopyReaderToPath(rc, destFilePath)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = os.Chmod(destFilePath, f.FileInfo().Mode())\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn\n}\n\nfunc (zipper ApplicationZipper) GetZipSize(zipFile *os.File) (int64, error) {\n\tzipFileSize := int64(0)\n\n\tstat, err := zipFile.Stat()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tzipFileSize = int64(stat.Size())\n\n\treturn zipFileSize, nil\n}\n<commit_msg>Update ApplicationZipper Unzip()<commit_after>package app_files\n\nimport (\n\t\"archive\/zip\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/cloudfoundry\/cli\/cf\/errors\"\n\t\"github.com\/cloudfoundry\/gofileutils\/fileutils\"\n)\n\ntype Zipper interface {\n\tZip(dirToZip string, targetFile *os.File) (err error)\n\tIsZipFile(path string) bool\n\tUnzip(appDir string, destDir string) (err error)\n\tGetZipSize(zipFile *os.File) (int64, error)\n}\n\ntype ApplicationZipper struct{}\n\nfunc (zipper ApplicationZipper) Zip(dirOrZipFile string, targetFile *os.File) (err error) {\n\tif zipper.IsZipFile(dirOrZipFile) {\n\t\terr = fileutils.CopyPathToWriter(dirOrZipFile, targetFile)\n\t} else {\n\t\terr = writeZipFile(dirOrZipFile, targetFile)\n\t}\n\ttargetFile.Seek(0, os.SEEK_SET)\n\treturn\n}\n\nfunc (zipper ApplicationZipper) IsZipFile(file string) (result bool) {\n\t_, err := zip.OpenReader(file)\n\treturn err == nil\n}\n\nfunc writeZipFile(dir string, targetFile *os.File) error {\n\tisEmpty, err := fileutils.IsDirEmpty(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif isEmpty {\n\t\treturn errors.NewEmptyDirError(dir)\n\t}\n\n\twriter := zip.NewWriter(targetFile)\n\tdefer writer.Close()\n\n\tappfiles := ApplicationFiles{}\n\treturn appfiles.WalkAppFiles(dir, func(fileName string, fullPath string) error {\n\t\tfileInfo, err := os.Stat(fullPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\theader, err := zip.FileInfoHeader(fileInfo)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\theader.Name = filepath.ToSlash(fileName)\n\n\t\tif fileInfo.IsDir() {\n\t\t\theader.Name += \"\/\"\n\t\t}\n\n\t\tzipFilePart, err := writer.CreateHeader(header)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif fileInfo.IsDir() {\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn fileutils.CopyPathToWriter(fullPath, zipFilePart)\n\t\t}\n\t})\n}\n\nfunc (zipper ApplicationZipper) Unzip(appDir string, destDir string) error {\n\tr, err := zip.OpenReader(appDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\n\tfor _, f := range r.File {\n\t\t\/\/ anonymous func allows the defer of rc.Close()\n\t\terr = func() error {\n\t\t\tif f.FileInfo().IsDir() {\n\t\t\t\tos.MkdirAll(filepath.Join(destDir, f.Name), os.ModeDir|os.ModePerm)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tvar rc io.ReadCloser\n\t\t\trc, err = f.Open()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tdefer rc.Close()\n\n\t\t\tdestFilePath := filepath.Join(destDir, f.Name)\n\n\t\t\terr = fileutils.CopyReaderToPath(rc, destFilePath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = os.Chmod(destFilePath, f.FileInfo().Mode())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}()\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (zipper ApplicationZipper) GetZipSize(zipFile *os.File) (int64, error) {\n\tzipFileSize := int64(0)\n\n\tstat, err := zipFile.Stat()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tzipFileSize = int64(stat.Size())\n\n\treturn zipFileSize, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/hyperledger\/fabric\/core\/chaincode\/shim\"\n\tpb \"github.com\/hyperledger\/fabric\/protos\/peer\"\n)\n\ntype CarChaincode struct {\n}\n\nconst carIndexStr string = \"_cars\"\nconst insurerIndexStr string = \"_insurers\"\nconst registrationProposalIndexStr string = \"_registrationProposals\"\n\nfunc (t *CarChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\tfmt.Println(\"Car demo Init\")\n\n\tvar aval int\n\tvar err error\n\n\t_, args := stub.GetFunctionAndParameters()\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 1 integer to test chain.\")\n\t}\n\n\t\/\/ initialize the chaincode\n\taval, err = strconv.Atoi(args[0])\n\tif err != nil {\n\t\treturn shim.Error(\"Expecting integer value for asset holding\")\n\t}\n\n\t\/\/ write the state to the ledger\n\t\/\/ make a test var \"abc\" in order to able to query it and see if it worked\n\terr = stub.PutState(\"abc\", []byte(strconv.Itoa(aval)))\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t\/\/ clear the car index\n\terr = clearCarIndex(carIndexStr, stub)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t\/\/ clear the insurer index\n\terr = clearInsurerIndex(insurerIndexStr, stub)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t\/\/ clear the registration proposal index\n\terr = clearRegistrationProposalIndex(registrationProposalIndexStr, stub)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tfmt.Println(\"Init terminated\")\n\treturn shim.Success(nil)\n}\n\n\/*\n * Invokes an action on the ledger.\n *\n * Expects 'username' and 'role' as first two parameters.\n * Unrestricted queries can only be done from test files.\n *\/\nfunc (t *CarChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n\tfunction, args := stub.GetFunctionAndParameters()\n\n\tif len(args) < 2 {\n\t\treturn shim.Error(\"Invoke expects 'username' and 'role' as first two args.\")\n\t}\n\n\tusername := args[0]\n\trole := args[1]\n\targs = args[2:]\n\n\tfmt.Printf(\"Invoke is running as user '%s' with role '%s'\\n\", username, role)\n\tfmt.Printf(\"Invoke is running function '%s' with args: %s\\n\", function, strings.Join(args, \", \"))\n\n\tif function == \"create\" {\n\t\tif role != \"garage\" {\n\t\t\treturn shim.Error(\"'create' expects you to be a garage user\")\n\t\t}\n\t\treturn t.create(stub, username, args)\n\t} else if function == \"read\" {\n\t\tif len(args) != 1 {\n\t\t\treturn shim.Error(\"'read' expects a key to do the look up\")\n\t\t} else if reflect.TypeOf(stub).String() != \"*shim.MockStub\" {\n\t\t\t\/\/ only allow unrestricted queries from the test files\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to do unrestricted queries on the ledger.\", role))\n\t\t} else {\n\t\t\treturn t.read(stub, args[0])\n\t\t}\n\t} else if function == \"readCar\" {\n\t\tif len(args) != 1 {\n\t\t\treturn shim.Error(\"'readCar' expects a car vin to do the look up\")\n\t\t} else {\n\t\t\treturn t.readCar(stub, username, args[0])\n\t\t}\n\t} else if function == \"readRegistrationProposals\" {\n\t\tif role != \"dot\" {\n\t\t\t\/\/ only the DOT is allowed to read registration proposals\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to read reigistration proposals.\", role))\n\t\t} else {\n\t\t\treturn t.readRegistrationProposals(stub)\n\t\t}\n\t} else if function == \"register\" {\n\t\tif len(args) != 1 {\n\t\t\treturn shim.Error(\"'register' expects a car vin to register\")\n\t\t} else if role != \"dot\" {\n\t\t\t\/\/ only the DOT is allowed to register new cars\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to register cars.\", role))\n\t\t} else {\n\t\t\treturn t.register(stub, username, args[0])\n\t\t}\n\t} else if function == \"confirm\" {\n\t\tif len(args) != 2 {\n\t\t\treturn shim.Error(\"'confirm' expects a car vin and numberplate to confirm a car\")\n\t\t} else if role != \"dot\" {\n\t\t\t\/\/ only the DOT is allowed to confirm cars\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to confirm cars.\", role))\n\t\t} else {\n\t\t\treturn t.confirm(stub, username, args)\n\t\t}\n\t} else if function == \"transfer\" {\n\t\tif len(args) != 2 {\n\t\t\treturn shim.Error(\"'transfer' expects a car vin and name of the new owner to confirm a car\")\n\t\t} else if role != \"user\" {\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to confirm cars.\", role))\n\t\t} else {\n\t\t\treturn t.transfer(stub, username, args)\n\t\t}\n\t} else if function == \"revoke\" {\n\t\tif len(args) != 1 {\n\t\t\treturn shim.Error(\"'revoke' expects a car vin to revoke a car\")\n\t\t} else if role != \"dot\" {\n\t\t\t\/\/ only the DOT is allowed to revoke cars\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to revoke cars.\", role))\n\t\t} else {\n\t\t\treturn t.revoke(stub, username, args)\n\t\t}\n\t} else if function == \"delete\" {\n\t\tif len(args) != 1 {\n\t\t\treturn shim.Error(\"'delete' expects a car vin to delete a car\")\n\t\t} else if role != \"dot\" {\n\t\t\t\/\/ only the DOT is allowed to delete cars\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to revoke cars.\", role))\n\t\t} else {\n\t\t\treturn t.delete(stub, args)\n\t\t}\n\t} else if function == \"insureProposal\" {\n\t\tif len(args) != 2 {\n\t\t\treturn shim.Error(\"'insureProposal' expects a car vin and an insurance company\")\n\t\t} else if role != \"user\" {\n\t\t\t\/\/ only normal users are allowed to do insurance proposals\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to create an insurance proposal.\", role))\n\t\t} else {\n\t\t\treturn t.insureProposal(stub, username, args[0], args[1])\n\t\t}\n\t} else if function == \"insuranceAccept\" {\n\t\tif len(args) != 2 {\n\t\t\treturn shim.Error(\"'insuranceAccept' expects a car vin and an insurance company\")\n\t\t} else if role != \"insurer\" {\n\t\t\t\/\/ only normal users are allowed to do insurance proposals\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to create an insurance proposal.\", role))\n\t\t} else {\n\t\t\treturn t.insuranceAccept(stub, username, args[0], args[1])\n\t\t}\n\t} else if function == \"getInsurer\" {\n\t\tif len(args) != 1 {\n\t\t\treturn shim.Error(\"'getInsurer' expects an insurance company name\")\n\t\t} else if role != \"insurer\" {\n\t\t\t\/\/ only normal users are allowed to do insurance proposals\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to create an insurance proposal.\", role))\n\t\t} else {\n\t\t\treturn t.getInsurer(stub, args[0])\n\t\t}\n\t}\n\n\treturn shim.Error(\"Invoke did not find function: \" + function)\n}\n\n\/*\n * Reads ledger state from position 'key'.\n *\n * Can be any of:\n *  - Car   (expects car timestamp as key)\n *  - User  (expects user name as key)\n *  - or an index like '_cars'\n *\n * On success,\n * returns ledger state in bytes at position 'key'.\n *\/\nfunc (t *CarChaincode) read(stub shim.ChaincodeStubInterface, key string) pb.Response {\n\tif key == \"\" {\n\t\treturn shim.Error(\"'read' expects a non-empty key to do the look up\")\n\t}\n\n\tvalAsBytes, err := stub.GetState(key)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to fetch value at key '\" + key + \"' from ledger\")\n\t}\n\n\treturn shim.Success(valAsBytes)\n}\n\nfunc main() {\n\terr := shim.Start(new(CarChaincode))\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting Simple chaincode: %s\", err)\n\t}\n}\n<commit_msg>allows garage users to transfer() cars<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/hyperledger\/fabric\/core\/chaincode\/shim\"\n\tpb \"github.com\/hyperledger\/fabric\/protos\/peer\"\n)\n\ntype CarChaincode struct {\n}\n\nconst carIndexStr string = \"_cars\"\nconst insurerIndexStr string = \"_insurers\"\nconst registrationProposalIndexStr string = \"_registrationProposals\"\n\nfunc (t *CarChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {\n\tfmt.Println(\"Car demo Init\")\n\n\tvar aval int\n\tvar err error\n\n\t_, args := stub.GetFunctionAndParameters()\n\tif len(args) != 1 {\n\t\treturn shim.Error(\"Incorrect number of arguments. Expecting 1 integer to test chain.\")\n\t}\n\n\t\/\/ initialize the chaincode\n\taval, err = strconv.Atoi(args[0])\n\tif err != nil {\n\t\treturn shim.Error(\"Expecting integer value for asset holding\")\n\t}\n\n\t\/\/ write the state to the ledger\n\t\/\/ make a test var \"abc\" in order to able to query it and see if it worked\n\terr = stub.PutState(\"abc\", []byte(strconv.Itoa(aval)))\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t\/\/ clear the car index\n\terr = clearCarIndex(carIndexStr, stub)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t\/\/ clear the insurer index\n\terr = clearInsurerIndex(insurerIndexStr, stub)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\t\/\/ clear the registration proposal index\n\terr = clearRegistrationProposalIndex(registrationProposalIndexStr, stub)\n\tif err != nil {\n\t\treturn shim.Error(err.Error())\n\t}\n\n\tfmt.Println(\"Init terminated\")\n\treturn shim.Success(nil)\n}\n\n\/*\n * Invokes an action on the ledger.\n *\n * Expects 'username' and 'role' as first two parameters.\n * Unrestricted queries can only be done from test files.\n *\/\nfunc (t *CarChaincode) Invoke(stub shim.ChaincodeStubInterface) pb.Response {\n\tfunction, args := stub.GetFunctionAndParameters()\n\n\tif len(args) < 2 {\n\t\treturn shim.Error(\"Invoke expects 'username' and 'role' as first two args.\")\n\t}\n\n\tusername := args[0]\n\trole := args[1]\n\targs = args[2:]\n\n\tfmt.Printf(\"Invoke is running as user '%s' with role '%s'\\n\", username, role)\n\tfmt.Printf(\"Invoke is running function '%s' with args: %s\\n\", function, strings.Join(args, \", \"))\n\n\tif function == \"create\" {\n\t\tif role != \"garage\" {\n\t\t\treturn shim.Error(\"'create' expects you to be a garage user\")\n\t\t}\n\t\treturn t.create(stub, username, args)\n\t} else if function == \"read\" {\n\t\tif len(args) != 1 {\n\t\t\treturn shim.Error(\"'read' expects a key to do the look up\")\n\t\t} else if reflect.TypeOf(stub).String() != \"*shim.MockStub\" {\n\t\t\t\/\/ only allow unrestricted queries from the test files\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to do unrestricted queries on the ledger.\", role))\n\t\t} else {\n\t\t\treturn t.read(stub, args[0])\n\t\t}\n\t} else if function == \"readCar\" {\n\t\tif len(args) != 1 {\n\t\t\treturn shim.Error(\"'readCar' expects a car vin to do the look up\")\n\t\t} else {\n\t\t\treturn t.readCar(stub, username, args[0])\n\t\t}\n\t} else if function == \"readRegistrationProposals\" {\n\t\tif role != \"dot\" {\n\t\t\t\/\/ only the DOT is allowed to read registration proposals\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to read reigistration proposals.\", role))\n\t\t} else {\n\t\t\treturn t.readRegistrationProposals(stub)\n\t\t}\n\t} else if function == \"register\" {\n\t\tif len(args) != 1 {\n\t\t\treturn shim.Error(\"'register' expects a car vin to register\")\n\t\t} else if role != \"dot\" {\n\t\t\t\/\/ only the DOT is allowed to register new cars\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to register cars.\", role))\n\t\t} else {\n\t\t\treturn t.register(stub, username, args[0])\n\t\t}\n\t} else if function == \"confirm\" {\n\t\tif len(args) != 2 {\n\t\t\treturn shim.Error(\"'confirm' expects a car vin and numberplate to confirm a car\")\n\t\t} else if role != \"dot\" {\n\t\t\t\/\/ only the DOT is allowed to confirm cars\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to confirm cars.\", role))\n\t\t} else {\n\t\t\treturn t.confirm(stub, username, args)\n\t\t}\n\t} else if function == \"transfer\" {\n\t\tif len(args) != 2 {\n\t\t\treturn shim.Error(\"'transfer' expects a car vin and name of the new owner to transfer a car\")\n\t\t} else if role == \"user\" || role == \"garage\" {\n            \/\/ only allow users and garage users to transer cars\n            return t.transfer(stub, username, args)\n\t\t} else {\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to transfer cars.\", role))\n\t\t}\n\t} else if function == \"revoke\" {\n\t\tif len(args) != 1 {\n\t\t\treturn shim.Error(\"'revoke' expects a car vin to revoke a car\")\n\t\t} else if role != \"dot\" {\n\t\t\t\/\/ only the DOT is allowed to revoke cars\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to revoke cars.\", role))\n\t\t} else {\n\t\t\treturn t.revoke(stub, username, args)\n\t\t}\n\t} else if function == \"delete\" {\n\t\tif len(args) != 1 {\n\t\t\treturn shim.Error(\"'delete' expects a car vin to delete a car\")\n\t\t} else if role != \"dot\" {\n\t\t\t\/\/ only the DOT is allowed to delete cars\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to revoke cars.\", role))\n\t\t} else {\n\t\t\treturn t.delete(stub, args)\n\t\t}\n\t} else if function == \"insureProposal\" {\n\t\tif len(args) != 2 {\n\t\t\treturn shim.Error(\"'insureProposal' expects a car vin and an insurance company\")\n\t\t} else if role != \"user\" {\n\t\t\t\/\/ only normal users are allowed to do insurance proposals\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to create an insurance proposal.\", role))\n\t\t} else {\n\t\t\treturn t.insureProposal(stub, username, args[0], args[1])\n\t\t}\n\t} else if function == \"insuranceAccept\" {\n\t\tif len(args) != 2 {\n\t\t\treturn shim.Error(\"'insuranceAccept' expects a car vin and an insurance company\")\n\t\t} else if role != \"insurer\" {\n\t\t\t\/\/ only normal users are allowed to do insurance proposals\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to create an insurance proposal.\", role))\n\t\t} else {\n\t\t\treturn t.insuranceAccept(stub, username, args[0], args[1])\n\t\t}\n\t} else if function == \"getInsurer\" {\n\t\tif len(args) != 1 {\n\t\t\treturn shim.Error(\"'getInsurer' expects an insurance company name\")\n\t\t} else if role != \"insurer\" {\n\t\t\t\/\/ only normal users are allowed to do insurance proposals\n\t\t\treturn shim.Error(fmt.Sprintf(\"Sorry, role '%s' is not allowed to create an insurance proposal.\", role))\n\t\t} else {\n\t\t\treturn t.getInsurer(stub, args[0])\n\t\t}\n\t}\n\n\treturn shim.Error(\"Invoke did not find function: \" + function)\n}\n\n\/*\n * Reads ledger state from position 'key'.\n *\n * Can be any of:\n *  - Car   (expects car timestamp as key)\n *  - User  (expects user name as key)\n *  - or an index like '_cars'\n *\n * On success,\n * returns ledger state in bytes at position 'key'.\n *\/\nfunc (t *CarChaincode) read(stub shim.ChaincodeStubInterface, key string) pb.Response {\n\tif key == \"\" {\n\t\treturn shim.Error(\"'read' expects a non-empty key to do the look up\")\n\t}\n\n\tvalAsBytes, err := stub.GetState(key)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to fetch value at key '\" + key + \"' from ledger\")\n\t}\n\n\treturn shim.Success(valAsBytes)\n}\n\nfunc main() {\n\terr := shim.Start(new(CarChaincode))\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting Simple chaincode: %s\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage cpu\n\nimport (\n\t\"runtime\"\n)\n\n\/\/ byteOrder is a subset of encoding\/binary.ByteOrder.\ntype byteOrder interface {\n\tUint32([]byte) uint32\n\tUint64([]byte) uint64\n}\n\ntype littleEndian struct{}\ntype bigEndian struct{}\n\nfunc (littleEndian) Uint32(b []byte) uint32 {\n\t_ = b[3] \/\/ bounds check hint to compiler; see golang.org\/issue\/14808\n\treturn uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24\n}\n\nfunc (littleEndian) Uint64(b []byte) uint64 {\n\t_ = b[7] \/\/ bounds check hint to compiler; see golang.org\/issue\/14808\n\treturn uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |\n\t\tuint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56\n}\n\nfunc (bigEndian) Uint32(b []byte) uint32 {\n\t_ = b[3] \/\/ bounds check hint to compiler; see golang.org\/issue\/14808\n\treturn uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24\n}\n\nfunc (bigEndian) Uint64(b []byte) uint64 {\n\t_ = b[7] \/\/ bounds check hint to compiler; see golang.org\/issue\/14808\n\treturn uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 |\n\t\tuint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56\n}\n\n\/\/ hostByteOrder returns binary.LittleEndian on little-endian machines and\n\/\/ binary.BigEndian on big-endian machines.\nfunc hostByteOrder() byteOrder {\n\tswitch runtime.GOARCH {\n\tcase \"386\", \"amd64\", \"amd64p32\",\n\t\t\"arm\", \"arm64\",\n\t\t\"mipsle\", \"mips64le\", \"mips64p32le\",\n\t\t\"ppc64le\",\n\t\t\"riscv\", \"riscv64\":\n\t\treturn littleEndian{}\n\tcase \"armbe\", \"arm64be\",\n\t\t\"mips\", \"mips64\", \"mips64p32\",\n\t\t\"ppc\", \"ppc64\",\n\t\t\"s390\", \"s390x\",\n\t\t\"sparc\", \"sparc64\":\n\t\treturn bigEndian{}\n\t}\n\tpanic(\"unknown architecture\")\n}\n<commit_msg>cpu: add all GOARCHes supported by gccgo<commit_after>\/\/ Copyright 2019 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage cpu\n\nimport (\n\t\"runtime\"\n)\n\n\/\/ byteOrder is a subset of encoding\/binary.ByteOrder.\ntype byteOrder interface {\n\tUint32([]byte) uint32\n\tUint64([]byte) uint64\n}\n\ntype littleEndian struct{}\ntype bigEndian struct{}\n\nfunc (littleEndian) Uint32(b []byte) uint32 {\n\t_ = b[3] \/\/ bounds check hint to compiler; see golang.org\/issue\/14808\n\treturn uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24\n}\n\nfunc (littleEndian) Uint64(b []byte) uint64 {\n\t_ = b[7] \/\/ bounds check hint to compiler; see golang.org\/issue\/14808\n\treturn uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |\n\t\tuint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56\n}\n\nfunc (bigEndian) Uint32(b []byte) uint32 {\n\t_ = b[3] \/\/ bounds check hint to compiler; see golang.org\/issue\/14808\n\treturn uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24\n}\n\nfunc (bigEndian) Uint64(b []byte) uint64 {\n\t_ = b[7] \/\/ bounds check hint to compiler; see golang.org\/issue\/14808\n\treturn uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 |\n\t\tuint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56\n}\n\n\/\/ hostByteOrder returns binary.LittleEndian on little-endian machines and\n\/\/ binary.BigEndian on big-endian machines.\nfunc hostByteOrder() byteOrder {\n\tswitch runtime.GOARCH {\n\tcase \"386\", \"amd64\", \"amd64p32\",\n\t\t\"alpha\",\n\t\t\"arm\", \"arm64\",\n\t\t\"mipsle\", \"mips64le\", \"mips64p32le\",\n\t\t\"nios2\",\n\t\t\"ppc64le\",\n\t\t\"riscv\", \"riscv64\",\n\t\t\"sh\":\n\t\treturn littleEndian{}\n\tcase \"armbe\", \"arm64be\",\n\t\t\"m68k\",\n\t\t\"mips\", \"mips64\", \"mips64p32\",\n\t\t\"ppc\", \"ppc64\",\n\t\t\"s390\", \"s390x\",\n\t\t\"shbe\",\n\t\t\"sparc\", \"sparc64\":\n\t\treturn bigEndian{}\n\t}\n\tpanic(\"unknown architecture\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 the u-root Authors. All rights reserved\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage dt\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"unicode\"\n)\n\n\/\/ Empty represents an empty Device Tree value.\ntype Empty struct{}\n\n\/\/ PHandle represents a pointer to another Node.\ntype PHandle uint32\n\n\/\/ PropertyType is an enum of possible property types.\ntype PropertyType int\n\n\/\/ These are the possible values for PropertyType.\nconst (\n\tEmptyType PropertyType = iota\n\tU32Type\n\tU64Type\n\tStringType\n\tPropEncodedArrayType\n\tPHandleType\n\tStringListType\n)\n\n\/\/ StandardPropertyTypes maps properties to values as defined by the spec.\nvar StandardPropertyTypes = map[string]PropertyType{\n\t\"compatible\":     StringListType,\n\t\"model\":          StringType,\n\t\"phandle\":        PHandleType,\n\t\"status\":         StringType,\n\t\"#address-cells\": U32Type,\n\t\"#size-cells\":    U32Type,\n\t\"reg\":            PropEncodedArrayType, \/\/ TODO: support cells\n\t\"virtual-reg\":    U32Type,\n\t\"ranges\":         PropEncodedArrayType, \/\/ TODO: or EmptyType\n\t\"dma-ranges\":     PropEncodedArrayType, \/\/ TODO: or EmptyType\n\t\"name\":           StringType,           \/\/ deprecated\n\t\"device_tree\":    StringType,           \/\/ deprecated\n}\n\n\/\/ Node is one Node in the Device Tree.\ntype Node struct {\n\tName       string\n\tProperties []Property `json:\",omitempty\"`\n\tChildren   []*Node    `json:\",omitempty\"`\n}\n\n\/\/ Walk calls f on a Node and alls its descendents.\nfunc (n *Node) Walk(f func(*Node) error) error {\n\tif err := f(n); err != nil {\n\t\treturn err\n\t}\n\tfor _, child := range n.Children {\n\t\tif err := child.Walk(f); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Find finds a Node starting at a node, given a matching function.\nfunc (n *Node) Find(f func(*Node) bool) (*Node, bool) {\n\tif ok := f(n); ok {\n\t\treturn n, ok\n\t}\n\tfor _, child := range n.Children {\n\t\tif nn, ok := child.Find(f); ok {\n\t\t\treturn nn, ok\n\t\t}\n\t}\n\treturn nil, false\n}\n\n\/\/ FindAll returns all Node starting at a node, given a matching function.\nfunc (n *Node) FindAll(f func(*Node) bool) ([]*Node, bool) {\n\tvar nodes []*Node\n\tif ok := f(n); ok {\n\t\tnodes = append(nodes, n)\n\t}\n\n\tfor _, child := range n.Children {\n\t\tif matching, ok := child.FindAll(f); ok {\n\t\t\tnodes = append(nodes, matching...)\n\t\t}\n\t}\n\tif len(nodes) == 0 {\n\t\treturn nil, false\n\t}\n\treturn nodes, true\n}\n\n\/\/ NodeByName uses Find to find a node by name.\nfunc (n *Node) NodeByName(name string) (*Node, bool) {\n\treturn n.Find(func(n *Node) bool {\n\t\treturn n.Name == name\n\t})\n}\n\n\/\/ LookProperty finds a property by name.\nfunc (n *Node) LookProperty(name string) (*Property, bool) {\n\tfor _, p := range n.Properties {\n\t\tif p.Name == name {\n\t\t\treturn &p, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\n\/\/ Property is a name-value pair. Note the PropertyType of Value is not\n\/\/ encoded.\ntype Property struct {\n\tName  string\n\tValue []byte\n}\n\n\/\/ PredictType makes a prediction on what value the property contains based on\n\/\/ its name and data. The data types are not encoded in the data structure, so\n\/\/ some heuristics are used.\nfunc (p *Property) PredictType() PropertyType {\n\t\/\/ Standard properties\n\tif value, ok := StandardPropertyTypes[p.Name]; ok {\n\t\tif _, err := p.AsType(value); err == nil {\n\t\t\treturn value\n\t\t}\n\t}\n\n\t\/\/ Heuristic match\n\tif _, err := p.AsEmpty(); err == nil {\n\t\treturn EmptyType\n\t}\n\tif _, err := p.AsString(); err == nil {\n\t\treturn StringType\n\t}\n\tif _, err := p.AsStringList(); err == nil {\n\t\treturn StringListType\n\t}\n\tif _, err := p.AsU32(); err == nil {\n\t\treturn U32Type\n\t}\n\tif _, err := p.AsU64(); err == nil {\n\t\treturn U64Type\n\t}\n\treturn PropEncodedArrayType\n}\n\n\/\/ AsType converts a Property to a Go type using one of the AsXYX() functions.\n\/\/ The resulting Go type is as follows:\n\/\/\n\/\/     AsType(fdt.EmptyType)            -> fdt.Empty\n\/\/     AsType(fdt.U32Type)              -> uint32\n\/\/     AsType(fdt.U64Type)              -> uint64\n\/\/     AsType(fdt.StringType)           -> string\n\/\/     AsType(fdt.PropEncodedArrayType) -> []byte\n\/\/     AsType(fdt.PHandleType)          -> fdt.PHandle\n\/\/     AsType(fdt.StringListType)       -> []string\nfunc (p *Property) AsType(val PropertyType) (interface{}, error) {\n\tswitch val {\n\tcase EmptyType:\n\t\treturn p.AsEmpty()\n\tcase U32Type:\n\t\treturn p.AsU32()\n\tcase U64Type:\n\t\treturn p.AsU64()\n\tcase StringType:\n\t\treturn p.AsString()\n\tcase PropEncodedArrayType:\n\t\treturn p.AsPropEncodedArray()\n\tcase PHandleType:\n\t\treturn p.AsPHandle()\n\tcase StringListType:\n\t\treturn p.AsStringList()\n\t}\n\treturn nil, fmt.Errorf(\"%d not in the PropertyType enum\", val)\n}\n\n\/\/ AsEmpty converts the property to the Go fdt.Empty type.\nfunc (p *Property) AsEmpty() (Empty, error) {\n\tif len(p.Value) != 0 {\n\t\treturn Empty{}, fmt.Errorf(\"property %q is not <empty>\", p.Name)\n\t}\n\treturn Empty{}, nil\n}\n\n\/\/ AsU32 converts the property to the Go uint32 type.\nfunc (p *Property) AsU32() (uint32, error) {\n\tif len(p.Value) != 4 {\n\t\treturn 0, fmt.Errorf(\"property %q is not <u32>\", p.Name)\n\t}\n\tvar val uint32\n\terr := binary.Read(bytes.NewBuffer(p.Value), binary.BigEndian, &val)\n\treturn val, err\n}\n\n\/\/ AsU64 converts the property to the Go uint64 type.\nfunc (p *Property) AsU64() (uint64, error) {\n\tif len(p.Value) != 8 {\n\t\treturn 0, fmt.Errorf(\"property %q is not <u64>\", p.Name)\n\t}\n\tvar val uint64\n\terr := binary.Read(bytes.NewBuffer(p.Value), binary.BigEndian, &val)\n\treturn val, err\n}\n\n\/\/ AsString converts the property to the Go string type. The trailing null\n\/\/ character is stripped.\nfunc (p *Property) AsString() (string, error) {\n\tif len(p.Value) == 0 || p.Value[len(p.Value)-1] != 0 {\n\t\treturn \"\", fmt.Errorf(\"property %q is not <string>\", p.Name)\n\t}\n\tstr := p.Value[:len(p.Value)-1]\n\tif !isPrintableASCII(str) {\n\t\treturn \"\", fmt.Errorf(\"property %q is not <string>\", p.Name)\n\t}\n\treturn string(str), nil\n}\n\n\/\/ AsPropEncodedArray converts the property to the Go []byte type.\nfunc (p *Property) AsPropEncodedArray() ([]byte, error) {\n\treturn p.Value, nil\n}\n\n\/\/ AsPHandle converts the property to the Go fdt.PHandle type.\nfunc (p *Property) AsPHandle() (PHandle, error) {\n\tval, err := p.AsU32()\n\treturn PHandle(val), err\n}\n\n\/\/ AsStringList converts the property to the Go []string type. The trailing\n\/\/ null character of each string is stripped.\nfunc (p *Property) AsStringList() ([]string, error) {\n\tif len(p.Value) == 0 || p.Value[len(p.Value)-1] != 0 {\n\t\treturn nil, fmt.Errorf(\"property %q is not <stringlist>\", p.Name)\n\t}\n\tvalue := p.Value\n\tstrs := []string{}\n\tfor len(p.Value) > 0 {\n\t\tnextNull := bytes.IndexByte(value, 0) \/\/ cannot be -1\n\t\tvar str []byte\n\t\tstr, value = value[:nextNull], value[nextNull+1:]\n\t\tif !isPrintableASCII(str) {\n\t\t\treturn nil, fmt.Errorf(\"property %q is not <stringlist>\", p.Name)\n\t\t}\n\t\tstrs = append(strs, string(str))\n\t}\n\treturn strs, nil\n}\n\nfunc isPrintableASCII(s []byte) bool {\n\tfor _, v := range s {\n\t\tif v > unicode.MaxASCII || !unicode.IsPrint(rune(v)) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n<commit_msg>change the lookup functions to return references<commit_after>\/\/ Copyright 2019 the u-root Authors. All rights reserved\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage dt\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"unicode\"\n)\n\n\/\/ Empty represents an empty Device Tree value.\ntype Empty struct{}\n\n\/\/ PHandle represents a pointer to another Node.\ntype PHandle uint32\n\n\/\/ PropertyType is an enum of possible property types.\ntype PropertyType int\n\n\/\/ These are the possible values for PropertyType.\nconst (\n\tEmptyType PropertyType = iota\n\tU32Type\n\tU64Type\n\tStringType\n\tPropEncodedArrayType\n\tPHandleType\n\tStringListType\n)\n\n\/\/ StandardPropertyTypes maps properties to values as defined by the spec.\nvar StandardPropertyTypes = map[string]PropertyType{\n\t\"compatible\":     StringListType,\n\t\"model\":          StringType,\n\t\"phandle\":        PHandleType,\n\t\"status\":         StringType,\n\t\"#address-cells\": U32Type,\n\t\"#size-cells\":    U32Type,\n\t\"reg\":            PropEncodedArrayType, \/\/ TODO: support cells\n\t\"virtual-reg\":    U32Type,\n\t\"ranges\":         PropEncodedArrayType, \/\/ TODO: or EmptyType\n\t\"dma-ranges\":     PropEncodedArrayType, \/\/ TODO: or EmptyType\n\t\"name\":           StringType,           \/\/ deprecated\n\t\"device_tree\":    StringType,           \/\/ deprecated\n}\n\n\/\/ Node is one Node in the Device Tree.\ntype Node struct {\n\tName       string\n\tProperties []Property `json:\",omitempty\"`\n\tChildren   []*Node    `json:\",omitempty\"`\n}\n\n\/\/ Walk calls f on a Node and alls its descendents.\nfunc (n *Node) Walk(f func(*Node) error) error {\n\tif err := f(n); err != nil {\n\t\treturn err\n\t}\n\tfor idx := range n.Children {\n\t\tif err := n.Children[idx].Walk(f); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Find finds a Node starting at a node, given a matching function.\nfunc (n *Node) Find(f func(*Node) bool) (*Node, bool) {\n\tif ok := f(n); ok {\n\t\treturn n, ok\n\t}\n\tfor idx := range n.Children {\n\t\tif nn, ok := n.Children[idx].Find(f); ok {\n\t\t\treturn nn, ok\n\t\t}\n\t}\n\treturn nil, false\n}\n\n\/\/ FindAll returns all Node starting at a node, given a matching function.\nfunc (n *Node) FindAll(f func(*Node) bool) ([]*Node, bool) {\n\tvar nodes []*Node\n\tif ok := f(n); ok {\n\t\tnodes = append(nodes, n)\n\t}\n\n\tfor idx := range n.Children {\n\t\tif matching, ok := n.Children[idx].FindAll(f); ok {\n\t\t\tnodes = append(nodes, matching...)\n\t\t}\n\t}\n\tif len(nodes) == 0 {\n\t\treturn nil, false\n\t}\n\treturn nodes, true\n}\n\n\/\/ NodeByName uses Find to find a node by name.\nfunc (n *Node) NodeByName(name string) (*Node, bool) {\n\treturn n.Find(func(n *Node) bool {\n\t\treturn n.Name == name\n\t})\n}\n\n\/\/ LookProperty finds a property by name.\nfunc (n *Node) LookProperty(name string) (*Property, bool) {\n\tfor idx := range n.Properties {\n\t\tif n.Properties[idx].Name == name {\n\t\t\treturn &n.Properties[idx], true\n\t\t}\n\t}\n\treturn nil, false\n}\n\n\/\/ Property is a name-value pair. Note the PropertyType of Value is not\n\/\/ encoded.\ntype Property struct {\n\tName  string\n\tValue []byte\n}\n\n\/\/ PredictType makes a prediction on what value the property contains based on\n\/\/ its name and data. The data types are not encoded in the data structure, so\n\/\/ some heuristics are used.\nfunc (p *Property) PredictType() PropertyType {\n\t\/\/ Standard properties\n\tif value, ok := StandardPropertyTypes[p.Name]; ok {\n\t\tif _, err := p.AsType(value); err == nil {\n\t\t\treturn value\n\t\t}\n\t}\n\n\t\/\/ Heuristic match\n\tif _, err := p.AsEmpty(); err == nil {\n\t\treturn EmptyType\n\t}\n\tif _, err := p.AsString(); err == nil {\n\t\treturn StringType\n\t}\n\tif _, err := p.AsStringList(); err == nil {\n\t\treturn StringListType\n\t}\n\tif _, err := p.AsU32(); err == nil {\n\t\treturn U32Type\n\t}\n\tif _, err := p.AsU64(); err == nil {\n\t\treturn U64Type\n\t}\n\treturn PropEncodedArrayType\n}\n\n\/\/ AsType converts a Property to a Go type using one of the AsXYX() functions.\n\/\/ The resulting Go type is as follows:\n\/\/\n\/\/     AsType(fdt.EmptyType)            -> fdt.Empty\n\/\/     AsType(fdt.U32Type)              -> uint32\n\/\/     AsType(fdt.U64Type)              -> uint64\n\/\/     AsType(fdt.StringType)           -> string\n\/\/     AsType(fdt.PropEncodedArrayType) -> []byte\n\/\/     AsType(fdt.PHandleType)          -> fdt.PHandle\n\/\/     AsType(fdt.StringListType)       -> []string\nfunc (p *Property) AsType(val PropertyType) (interface{}, error) {\n\tswitch val {\n\tcase EmptyType:\n\t\treturn p.AsEmpty()\n\tcase U32Type:\n\t\treturn p.AsU32()\n\tcase U64Type:\n\t\treturn p.AsU64()\n\tcase StringType:\n\t\treturn p.AsString()\n\tcase PropEncodedArrayType:\n\t\treturn p.AsPropEncodedArray()\n\tcase PHandleType:\n\t\treturn p.AsPHandle()\n\tcase StringListType:\n\t\treturn p.AsStringList()\n\t}\n\treturn nil, fmt.Errorf(\"%d not in the PropertyType enum\", val)\n}\n\n\/\/ AsEmpty converts the property to the Go fdt.Empty type.\nfunc (p *Property) AsEmpty() (Empty, error) {\n\tif len(p.Value) != 0 {\n\t\treturn Empty{}, fmt.Errorf(\"property %q is not <empty>\", p.Name)\n\t}\n\treturn Empty{}, nil\n}\n\n\/\/ AsU32 converts the property to the Go uint32 type.\nfunc (p *Property) AsU32() (uint32, error) {\n\tif len(p.Value) != 4 {\n\t\treturn 0, fmt.Errorf(\"property %q is not <u32>\", p.Name)\n\t}\n\tvar val uint32\n\terr := binary.Read(bytes.NewBuffer(p.Value), binary.BigEndian, &val)\n\treturn val, err\n}\n\n\/\/ AsU64 converts the property to the Go uint64 type.\nfunc (p *Property) AsU64() (uint64, error) {\n\tif len(p.Value) != 8 {\n\t\treturn 0, fmt.Errorf(\"property %q is not <u64>\", p.Name)\n\t}\n\tvar val uint64\n\terr := binary.Read(bytes.NewBuffer(p.Value), binary.BigEndian, &val)\n\treturn val, err\n}\n\n\/\/ AsString converts the property to the Go string type. The trailing null\n\/\/ character is stripped.\nfunc (p *Property) AsString() (string, error) {\n\tif len(p.Value) == 0 || p.Value[len(p.Value)-1] != 0 {\n\t\treturn \"\", fmt.Errorf(\"property %q is not <string>\", p.Name)\n\t}\n\tstr := p.Value[:len(p.Value)-1]\n\tif !isPrintableASCII(str) {\n\t\treturn \"\", fmt.Errorf(\"property %q is not <string>\", p.Name)\n\t}\n\treturn string(str), nil\n}\n\n\/\/ AsPropEncodedArray converts the property to the Go []byte type.\nfunc (p *Property) AsPropEncodedArray() ([]byte, error) {\n\treturn p.Value, nil\n}\n\n\/\/ AsPHandle converts the property to the Go fdt.PHandle type.\nfunc (p *Property) AsPHandle() (PHandle, error) {\n\tval, err := p.AsU32()\n\treturn PHandle(val), err\n}\n\n\/\/ AsStringList converts the property to the Go []string type. The trailing\n\/\/ null character of each string is stripped.\nfunc (p *Property) AsStringList() ([]string, error) {\n\tif len(p.Value) == 0 || p.Value[len(p.Value)-1] != 0 {\n\t\treturn nil, fmt.Errorf(\"property %q is not <stringlist>\", p.Name)\n\t}\n\tvalue := p.Value\n\tstrs := []string{}\n\tfor len(p.Value) > 0 {\n\t\tnextNull := bytes.IndexByte(value, 0) \/\/ cannot be -1\n\t\tvar str []byte\n\t\tstr, value = value[:nextNull], value[nextNull+1:]\n\t\tif !isPrintableASCII(str) {\n\t\t\treturn nil, fmt.Errorf(\"property %q is not <stringlist>\", p.Name)\n\t\t}\n\t\tstrs = append(strs, string(str))\n\t}\n\treturn strs, nil\n}\n\nfunc isPrintableASCII(s []byte) bool {\n\tfor _, v := range s {\n\t\tif v > unicode.MaxASCII || !unicode.IsPrint(rune(v)) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>package mux\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n\n\t\"github.com\/bitfinexcom\/bitfinex-api-go\/pkg\/models\/event\"\n\t\"github.com\/bitfinexcom\/bitfinex-api-go\/pkg\/mux\/client\"\n\t\"github.com\/bitfinexcom\/bitfinex-api-go\/pkg\/mux\/msg\"\n)\n\n\/\/ Mux will manage all connections and subscriptions. Will check if subscriptions\n\/\/ limit is reached and spawn new connection when that happens. It will also listen\n\/\/ to all incomming client messages and reconnect client with all its subscriptions\n\/\/ in case of a failure\ntype Mux struct {\n\tcid           int\n\tpublicChan    chan msg.Msg\n\tpublicClients map[int]*client.Client\n\tprivateChan   chan msg.Msg\n\tprivateClient *client.Client\n\tmtx           *sync.RWMutex\n\tErr           error\n\ttransform     bool\n\tapikey        string\n\tapisec        string\n\tsubInfo       map[int64]event.Info\n\tauthenticated bool\n}\n\n\/\/ New returns pointer to instance of mux\nfunc New() *Mux {\n\treturn &Mux{\n\t\tpublicChan:    make(chan msg.Msg),\n\t\tprivateChan:   make(chan msg.Msg),\n\t\tpublicClients: make(map[int]*client.Client),\n\t\tmtx:           &sync.RWMutex{},\n\t\tsubInfo:       map[int64]event.Info{},\n\t}\n}\n\n\/\/ TransformRaw enables data transformation and mapping to appropriate\n\/\/ models before sending it to consumer\nfunc (m *Mux) TransformRaw() *Mux {\n\tm.transform = true\n\treturn m\n}\n\n\/\/ WithAPIKEY accepts and persists api key\nfunc (m *Mux) WithAPIKEY(key string) *Mux {\n\tm.apikey = key\n\treturn m\n}\n\n\/\/ WithAPISEC accepts and persists api sec\nfunc (m *Mux) WithAPISEC(sec string) *Mux {\n\tm.apisec = sec\n\treturn m\n}\n\n\/\/ Subscribe - given the details in form of event.Subscribe,\n\/\/ subscribes client to public channels\nfunc (m *Mux) Subscribe(sub event.Subscribe) *Mux {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\n\tif m.Err != nil {\n\t\treturn m\n\t}\n\n\tif alreadySubscribed := m.publicClients[m.cid].Subs.Added(sub); alreadySubscribed {\n\t\treturn m\n\t}\n\n\tm.publicClients[m.cid].Subscribe(sub)\n\n\tif limitReached := m.publicClients[m.cid].Subs.LimitReached(); limitReached {\n\t\tlog.Printf(\"subs limit is reached on cid: %d, spawning new conn\\n\", m.cid)\n\t\tm.addPublicClient()\n\t}\n\treturn m\n}\n\n\/\/ Start creates initial clients for accepting connections\nfunc (m *Mux) Start() *Mux {\n\tif m.Err != nil {\n\t\treturn m\n\t}\n\n\tif m.hasAPIKeys() && m.privateClient == nil {\n\t\tm.addPrivateClient()\n\t}\n\n\treturn m.addPublicClient()\n}\n\n\/\/ Listen accepts a callback func that will get called each time mux\n\/\/ receives a message from any of its clients\/subscriptions. It\n\/\/ should be called last, after all setup calls are made\nfunc (m *Mux) Listen(cb func(interface{}, error)) error {\n\tif m.Err != nil {\n\t\treturn m.Err\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase ms, ok := <-m.publicChan:\n\t\t\tif !ok {\n\t\t\t\treturn errors.New(\"channel has closed unexpectedly\")\n\t\t\t}\n\t\t\tif ms.Err != nil {\n\t\t\t\tcb(nil, fmt.Errorf(\"conn:%d has failed | err:%s | reconnecting\", ms.CID, ms.Err))\n\t\t\t\tm.resetPublicClient(ms.CID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ return raw payload data if transform is off\n\t\t\tif !m.transform {\n\t\t\t\tcb(ms.Data, nil)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ handle event type message\n\t\t\tif ms.IsEvent() {\n\t\t\t\tcb(m.handleEvent(ms.ProcessEvent()))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ handle data type message\n\t\t\tif ms.IsRaw() {\n\t\t\t\tcb(ms.ProcessRaw(m.subInfo))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcb(nil, fmt.Errorf(\"unrecognized msg signature: %s\", ms.Data))\n\t\tcase ms, ok := <-m.privateChan:\n\t\t\tif !ok {\n\t\t\t\treturn errors.New(\"private channel has closed unexpectedly\")\n\t\t\t}\n\t\t\tif ms.Err != nil {\n\t\t\t\tcb(nil, fmt.Errorf(\"err: %s | reconnecting\", ms.Err))\n\t\t\t\tm.resetPrivateClient()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ return raw payload data if transform is off\n\t\t\tif !m.transform {\n\t\t\t\tcb(ms.Data, nil)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ handle event type message\n\t\t\tif ms.IsEvent() {\n\t\t\t\tcb(m.handleEvent(ms.ProcessEvent()))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ handle data type message\n\t\t\tif ms.IsRaw() {\n\t\t\t\tcb(ms.ProcessPrivateRaw())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcb(nil, fmt.Errorf(\"unrecognized msg signature: %s\", ms.Data))\n\t\t}\n\t}\n}\n\n\/\/ Send meant for authenticated input, takes payload in form of interface\n\/\/ and calls client with it\nfunc (m *Mux) Send(pld interface{}) error {\n\tif !m.authenticated || m.privateClient == nil {\n\t\treturn errors.New(\"not authorized\")\n\t}\n\treturn m.privateClient.Send(pld)\n}\n\nfunc (m *Mux) hasAPIKeys() bool {\n\treturn len(m.apikey) != 0 && len(m.apisec) != 0\n}\n\nfunc (m *Mux) handleEvent(i event.Info, err error) (event.Info, error) {\n\tswitch i.Event {\n\tcase \"subscribed\":\n\t\tm.subInfo[i.ChanID] = i\n\tcase \"auth\":\n\t\tif i.Status == \"OK\" {\n\t\t\tm.subInfo[i.ChanID] = i\n\t\t\tm.authenticated = true\n\t\t}\n\t}\n\t\/\/ add more cases if\/when needed\n\treturn i, err\n}\n\nfunc (m *Mux) resetPublicClient(cid int) {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\t\/\/ pull old client subscriptions\n\tsubs := m.publicClients[cid].Subs.GetAll()\n\t\/\/ add fresh client\n\tm.addPublicClient()\n\t\/\/ resubscribe old events\n\tfor _, sub := range subs {\n\t\tlog.Printf(\"resubscribing: %+v\\n\", sub)\n\t\tm.Subscribe(sub)\n\t}\n\t\/\/ remove old, closed channel from the list\n\tdelete(m.publicClients, cid)\n}\n\nfunc (m *Mux) resetPrivateClient() {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\tm.privateClient = nil\n\tm.addPrivateClient()\n}\n\nfunc (m *Mux) addPublicClient() *Mux {\n\t\/\/ adding new client so making sure we increment cid\n\tm.cid++\n\t\/\/ create new public client and pass error to mux if any\n\tc := client.New(m.cid).Public()\n\tif c.Err != nil {\n\t\tm.Err = c.Err\n\t\treturn m\n\t}\n\t\/\/ add new client to list for later reference\n\tm.publicClients[m.cid] = c\n\t\/\/ start listening for incoming client messages\n\tgo c.Read(m.publicChan)\n\treturn m\n}\n\nfunc (m *Mux) addPrivateClient() *Mux {\n\t\/\/ create new private client and pass error to mux if any\n\tc := client.New(0).Private(m.apikey, m.apisec)\n\tif c.Err != nil {\n\t\tm.Err = c.Err\n\t\treturn m\n\t}\n\n\tm.privateClient = c\n\tgo c.Read(m.privateChan)\n\treturn m\n}\n<commit_msg>removing redundant locks<commit_after>package mux\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n\n\t\"github.com\/bitfinexcom\/bitfinex-api-go\/pkg\/models\/event\"\n\t\"github.com\/bitfinexcom\/bitfinex-api-go\/pkg\/mux\/client\"\n\t\"github.com\/bitfinexcom\/bitfinex-api-go\/pkg\/mux\/msg\"\n)\n\n\/\/ Mux will manage all connections and subscriptions. Will check if subscriptions\n\/\/ limit is reached and spawn new connection when that happens. It will also listen\n\/\/ to all incomming client messages and reconnect client with all its subscriptions\n\/\/ in case of a failure\ntype Mux struct {\n\tcid           int\n\tpublicChan    chan msg.Msg\n\tpublicClients map[int]*client.Client\n\tprivateChan   chan msg.Msg\n\tprivateClient *client.Client\n\tmtx           *sync.RWMutex\n\tErr           error\n\ttransform     bool\n\tapikey        string\n\tapisec        string\n\tsubInfo       map[int64]event.Info\n\tauthenticated bool\n}\n\n\/\/ New returns pointer to instance of mux\nfunc New() *Mux {\n\treturn &Mux{\n\t\tpublicChan:    make(chan msg.Msg),\n\t\tprivateChan:   make(chan msg.Msg),\n\t\tpublicClients: make(map[int]*client.Client),\n\t\tmtx:           &sync.RWMutex{},\n\t\tsubInfo:       map[int64]event.Info{},\n\t}\n}\n\n\/\/ TransformRaw enables data transformation and mapping to appropriate\n\/\/ models before sending it to consumer\nfunc (m *Mux) TransformRaw() *Mux {\n\tm.transform = true\n\treturn m\n}\n\n\/\/ WithAPIKEY accepts and persists api key\nfunc (m *Mux) WithAPIKEY(key string) *Mux {\n\tm.apikey = key\n\treturn m\n}\n\n\/\/ WithAPISEC accepts and persists api sec\nfunc (m *Mux) WithAPISEC(sec string) *Mux {\n\tm.apisec = sec\n\treturn m\n}\n\n\/\/ Subscribe - given the details in form of event.Subscribe,\n\/\/ subscribes client to public channels\nfunc (m *Mux) Subscribe(sub event.Subscribe) *Mux {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\n\tif m.Err != nil {\n\t\treturn m\n\t}\n\n\tif alreadySubscribed := m.publicClients[m.cid].Subs.Added(sub); alreadySubscribed {\n\t\treturn m\n\t}\n\n\tm.publicClients[m.cid].Subscribe(sub)\n\n\tif limitReached := m.publicClients[m.cid].Subs.LimitReached(); limitReached {\n\t\tlog.Printf(\"subs limit is reached on cid: %d, spawning new conn\\n\", m.cid)\n\t\tm.addPublicClient()\n\t}\n\treturn m\n}\n\n\/\/ Start creates initial clients for accepting connections\nfunc (m *Mux) Start() *Mux {\n\tif m.Err != nil {\n\t\treturn m\n\t}\n\n\tif m.hasAPIKeys() && m.privateClient == nil {\n\t\tm.addPrivateClient()\n\t}\n\n\treturn m.addPublicClient()\n}\n\n\/\/ Listen accepts a callback func that will get called each time mux\n\/\/ receives a message from any of its clients\/subscriptions. It\n\/\/ should be called last, after all setup calls are made\nfunc (m *Mux) Listen(cb func(interface{}, error)) error {\n\tif m.Err != nil {\n\t\treturn m.Err\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase ms, ok := <-m.publicChan:\n\t\t\tif !ok {\n\t\t\t\treturn errors.New(\"channel has closed unexpectedly\")\n\t\t\t}\n\t\t\tif ms.Err != nil {\n\t\t\t\tcb(nil, fmt.Errorf(\"conn:%d has failed | err:%s | reconnecting\", ms.CID, ms.Err))\n\t\t\t\tm.resetPublicClient(ms.CID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ return raw payload data if transform is off\n\t\t\tif !m.transform {\n\t\t\t\tcb(ms.Data, nil)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ handle event type message\n\t\t\tif ms.IsEvent() {\n\t\t\t\tcb(m.handleEvent(ms.ProcessEvent()))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ handle data type message\n\t\t\tif ms.IsRaw() {\n\t\t\t\tcb(ms.ProcessRaw(m.subInfo))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcb(nil, fmt.Errorf(\"unrecognized msg signature: %s\", ms.Data))\n\t\tcase ms, ok := <-m.privateChan:\n\t\t\tif !ok {\n\t\t\t\treturn errors.New(\"channel has closed unexpectedly\")\n\t\t\t}\n\t\t\tif ms.Err != nil {\n\t\t\t\tcb(nil, fmt.Errorf(\"err: %s | reconnecting\", ms.Err))\n\t\t\t\tm.resetPrivateClient()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ return raw payload data if transform is off\n\t\t\tif !m.transform {\n\t\t\t\tcb(ms.Data, nil)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ handle event type message\n\t\t\tif ms.IsEvent() {\n\t\t\t\tcb(m.handleEvent(ms.ProcessEvent()))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ handle data type message\n\t\t\tif ms.IsRaw() {\n\t\t\t\tcb(ms.ProcessPrivateRaw())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcb(nil, fmt.Errorf(\"unrecognized msg signature: %s\", ms.Data))\n\t\t}\n\t}\n}\n\n\/\/ Send meant for authenticated input, takes payload in form of interface\n\/\/ and calls client with it\nfunc (m *Mux) Send(pld interface{}) error {\n\tif !m.authenticated || m.privateClient == nil {\n\t\treturn errors.New(\"not authorized\")\n\t}\n\treturn m.privateClient.Send(pld)\n}\n\nfunc (m *Mux) hasAPIKeys() bool {\n\treturn len(m.apikey) != 0 && len(m.apisec) != 0\n}\n\nfunc (m *Mux) handleEvent(i event.Info, err error) (event.Info, error) {\n\tswitch i.Event {\n\tcase \"subscribed\":\n\t\tm.subInfo[i.ChanID] = i\n\tcase \"auth\":\n\t\tif i.Status == \"OK\" {\n\t\t\tm.subInfo[i.ChanID] = i\n\t\t\tm.authenticated = true\n\t\t}\n\t}\n\t\/\/ add more cases if\/when needed\n\treturn i, err\n}\n\nfunc (m *Mux) resetPublicClient(cid int) {\n\t\/\/ pull old client subscriptions\n\tsubs := m.publicClients[cid].Subs.GetAll()\n\t\/\/ add fresh client\n\tm.addPublicClient()\n\t\/\/ resubscribe old events\n\tfor _, sub := range subs {\n\t\tlog.Printf(\"resubscribing: %+v\\n\", sub)\n\t\tm.Subscribe(sub)\n\t}\n\t\/\/ remove old, closed channel from the list\n\tdelete(m.publicClients, cid)\n}\n\nfunc (m *Mux) resetPrivateClient() {\n\tm.privateClient = nil\n\tm.addPrivateClient()\n}\n\nfunc (m *Mux) addPublicClient() *Mux {\n\t\/\/ adding new client so making sure we increment cid\n\tm.cid++\n\t\/\/ create new public client and pass error to mux if any\n\tc := client.New(m.cid).Public()\n\tif c.Err != nil {\n\t\tm.Err = c.Err\n\t\treturn m\n\t}\n\t\/\/ add new client to list for later reference\n\tm.publicClients[m.cid] = c\n\t\/\/ start listening for incoming client messages\n\tgo c.Read(m.publicChan)\n\treturn m\n}\n\nfunc (m *Mux) addPrivateClient() *Mux {\n\t\/\/ create new private client and pass error to mux if any\n\tc := client.New(0).Private(m.apikey, m.apisec)\n\tif c.Err != nil {\n\t\tm.Err = c.Err\n\t\treturn m\n\t}\n\n\tm.privateClient = c\n\tgo c.Read(m.privateChan)\n\treturn m\n}\n<|endoftext|>"}
{"text":"<commit_before>package place\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha256\"\n\t\"encoding\/gob\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/syndtr\/goleveldb\/leveldb\"\n\t\"github.com\/syndtr\/goleveldb\/leveldb\/util\"\n\t\"gopkg.in\/h2non\/filetype.v1\"\n\t\"gopkg.in\/h2non\/filetype.v1\/types\"\n)\n\ntype Place struct {\n\tConfigPath string\n\tConfig     Config\n\tDb         *leveldb.DB\n\tPreview    bool\n\tNumber     int\n\tHistory    History\n\tTmpFile    map[string][]byte\n}\n\nfunc (p *Place) Run(files []string) {\n\tp.loadConfig()\n\tp.getNumber()\n\tp.History.Files = make(map[string]string)\n\tlog.Debug(\"Run:\", files)\n\tfor _, v := range files {\n\t\tp.run(v)\n\t}\n\tif !p.Preview {\n\t\tp.saveHistory()\n\t}\n}\n\nfunc (p *Place) getNumber() {\n\tname := []byte(\"count\")\n\tbs, _ := p.Db.Get(name, nil)\n\tp.Number = Bytes2Int(bs)\n\tp.Number += 1\n\tlog.Debugf(\"操作次数: %d\", p.Number)\n\tp.Db.Put(name, Int2Bytes(p.Number), nil)\n}\n\nfunc (p *Place) saveHistory() {\n\tlog.Debugf(\"保存历史: %v\", p.History.Files)\n\tp.History.Timestamp = time.Now()\n\tbf := bytes.NewBuffer(nil)\n\tenc := gob.NewEncoder(bf)\n\terr := enc.Encode(p.History)\n\tif err != nil {\n\t\tpanic(\"操作记录编码失败\")\n\t}\n\tp.Db.Put([]byte(fmt.Sprintf(\"no-%04d\", p.Number)), bf.Bytes(), nil)\n}\n\nfunc (p *Place) loadConfig() {\n\tp.Config = Config{}\n\tp.Config.Load(p.ConfigPath)\n}\n\nfunc (p *Place) run(file string) {\n\tinfo, err := os.Stat(file)\n\tif os.IsNotExist(err) {\n\t\tlog.Error(\"文件未找到: \", file)\n\t\treturn\n\t}\n\tlog.Debugf(\"%s 目录: %t\", file, info.IsDir())\n\tif info.IsDir() {\n\t\tlog.Info(\"忽略目录: \", file)\n\t} else {\n\t\tlog.Debug(\"处理文件: \", file)\n\t\tbs, _ := ioutil.ReadFile(file)\n\t\thead := bs[:261]\n\t\tif filetype.IsImage(head) {\n\t\t\tlog.Debugf(\"文件 %s 是图片\", file)\n\t\t} else {\n\t\t\tlog.Debugf(\"文件 %s 不是图片\", file)\n\t\t}\n\t\thash := sha256.New()\n\t\thash.Write(bs)\n\t\tlog.Debugf(\"%s sha256: %x\", file, hash.Sum(nil))\n\t\tkind := Mime(head, file)\n\t\told := p.find(hash.Sum(nil))\n\t\tif old == \"\" {\n\t\t\tnewFile, err := p.moveName(kind, file, info)\n\t\t\tif err == nil {\n\t\t\t\tif p.Preview {\n\t\t\t\t\tlog.Infof(\"预览: %s >>> %s\", file, newFile)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Infof(\"移动: %s >>> %s\", file, newFile)\n\t\t\t\t\tp.History.Files[file] = newFile\n\t\t\t\t\tos.Rename(file, newFile)\n\t\t\t\t\tp.Db.Put(BytesPrefix(\"f-\", hash.Sum(nil)), []byte(newFile), nil)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Errorf(\"%s %s Mime: %s, Subtype: %s\", err, file, kind.MIME.Type, kind.MIME.Subtype)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warnf(\"文件 %s 重复, 原文件 %s\", file, old)\n\t\t}\n\t}\n}\n\nfunc (p *Place) find(hash []byte) string {\n\tfile, err := p.Db.Get(BytesPrefix(\"f-\", hash), nil)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn string(file)\n}\n\nfunc (p *Place) moveName(t types.Type, file string, info os.FileInfo) (string, error) {\n\tlog.Debugf(\"mime: %s, subtype: %s, 搬移文件: %s\", t.MIME.Type, t.MIME.Subtype, file)\n\text := path.Ext(file)\n\tfor _, ap := range p.Config.Paths {\n\t\tsubtypes := []string{\"\"}\n\t\tif ap.Subtype != \"\" {\n\t\t\tsubtypes = Split(ap.Subtype)\n\t\t}\n\t\texts := []string{\"\"}\n\t\tif ap.Ext != \"\" {\n\t\t\texts = Split(ap.Ext)\n\t\t}\n\t\tfor _, st := range subtypes {\n\t\t\tfor _, apExt := range exts {\n\t\t\t\tif matching(ap, strings.ToLower(st), t, ext, apExt) {\n\t\t\t\t\tnewDir := ap.Dir\n\t\t\t\t\tif ap.Subdir != \"\" {\n\t\t\t\t\t\tnewDir = path.Join(newDir, TimeFormat(info.ModTime(), ap.Subdir))\n\t\t\t\t\t}\n\t\t\t\t\tdir := ToPath(newDir)\n\t\t\t\t\tnewFile := path.Join(dir, path.Base(file))\n\t\t\t\t\tinfo, err := os.Stat(newFile)\n\t\t\t\t\tif os.IsNotExist(err) {\n\t\t\t\t\t\treturn newFile, nil\n\t\t\t\t\t}\n\t\t\t\t\tif info.IsDir() {\n\t\t\t\t\t\treturn file, errors.New(\"同名目录已经存在\")\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn file, errors.New(\"同名文件已经存在\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn file, errors.New(\"无匹配设置\")\n}\n\nfunc matching(ap *Path, subType string, t types.Type, ext string, apExt string) bool {\n\tif (strings.EqualFold(ap.Mime, t.MIME.Type) && strings.HasPrefix(t.MIME.Subtype, subType)) ||\n\t\t(ap.Mime == \"\" && ap.Subtype == \"\" && t == filetype.Unknown) ||\n\t\t(strings.EqualFold(ap.Mime, t.MIME.Type) && ap.Subtype == \"\") {\n\t\tif apExt == \"\" || strings.EqualFold(apExt, ext) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *Place) Scan() {\n\tlog.Info(\"开始目录扫描\")\n\tp.loadConfig()\n\n\tp.TmpFile = make(map[string][]byte)\n\titer := p.Db.NewIterator(util.BytesPrefix([]byte(\"f-\")), nil)\n\tfor iter.Next() {\n\t\tfile := string(iter.Value())\n\t\tp.TmpFile[file] = iter.Key()\n\t\tlog.Debug(\"缓存文件: \", file)\n\t}\n\titer.Release()\n\n\tfor _, ap := range p.Config.Paths {\n\t\tlog.Debug(\"扫描目录: \", ap.Dir)\n\t\tp.scanning(ToPath(ap.Dir))\n\t}\n\n\tfor file, key := range p.TmpFile {\n\t\tlog.Debug(\"删除缓存: \", file)\n\t\tp.Db.Delete(key, nil)\n\t}\n}\n\nfunc (p *Place) scanning(dir string) {\n\terr := filepath.Walk(dir, func(filename string, fi os.FileInfo, err error) error {\n\t\tif filename == dir {\n\t\t\treturn nil\n\t\t}\n\t\tif fi.IsDir() {\n\t\t\tp.scanning(filename)\n\t\t} else {\n\t\t\tlog.Debug(\"扫描文件: \", filename)\n\t\t\t_, ok := p.TmpFile[filename]\n\t\t\tif ok {\n\t\t\t\tdelete(p.TmpFile, filename)\n\t\t\t} else {\n\t\t\t\tbs, _ := ioutil.ReadFile(filename)\n\t\t\t\thash := sha256.New()\n\t\t\t\thash.Write(bs)\n\t\t\t\tkey := BytesPrefix(\"f-\", hash.Sum(nil))\n\t\t\t\told, err := p.Db.Get(key, nil)\n\t\t\t\tif err == nil {\n\t\t\t\t\tif filename != string(old) {\n\t\t\t\t\t\tlog.Warnf(\"文件重复: %s = %s\", filename, old)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Info(\"新增文件: \", filename)\n\t\t\t\t\tp.Db.Put(key, []byte(filename), nil)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Error(\"目录扫描错误: \", err)\n\t}\n}\n\nfunc (p *Place) Reset() {\n\tlog.Info(\"开始根据配置重置目录\")\n\n\tp.TmpFile = make(map[string][]byte)\n\titer := p.Db.NewIterator(util.BytesPrefix([]byte(\"f-\")), nil)\n\tfor iter.Next() {\n\t\tfile := string(iter.Value())\n\t\tp.TmpFile[file] = iter.Key()\n\t\tlog.Debug(\"缓存文件: \", file)\n\t}\n\titer.Release()\n\n\tfor _, ap := range p.Config.Paths {\n\t\tlog.Debug(\"扫描目录: \", ap.Dir)\n\t\tp.reset(ToPath(ap.Dir))\n\t}\n}\n\nfunc (p *Place) reset(dir string) {\n\tcount := 0\n\terr := filepath.Walk(dir, func(filename string, fi os.FileInfo, err error) error {\n\t\tif filename == dir {\n\t\t\treturn nil\n\t\t}\n\t\tcount += 1\n\t\tif fi.IsDir() {\n\t\t\tp.reset(filename)\n\t\t} else {\n\t\t\tlog.Debug(\"重置文件: \", filename)\n\t\t\tbs, _ := ioutil.ReadFile(filename)\n\t\t\thead := bs[:261]\n\t\t\tkind, _ := filetype.Match(head)\n\t\t\tnewFile, err := p.moveName(kind, filename, fi)\n\t\t\tif err != nil || newFile == filename {\n\t\t\t\tlog.Debug(\"无需移动: \", filename)\n\t\t\t} else {\n\t\t\t\tlog.Infof(\"移动: %s >>> %s\", filename, newFile)\n\t\t\t\tos.Rename(filename, newFile)\n\t\t\t\tkey, _ := p.TmpFile[filename]\n\t\t\t\tp.Db.Put(key, []byte(newFile), nil)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err == nil {\n\t\tlog.Debugf(\"%s 子文件数量: %d\", dir, count)\n\t\tif count == 0 {\n\t\t\tlog.Info(\"删除空目录: \", dir)\n\t\t\tos.Remove(dir)\n\t\t}\n\t} else {\n\t\tlog.Error(\"目录扫描错误: \", err)\n\t}\n}\n<commit_msg>fix #16<commit_after>package place\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto\/sha256\"\n\t\"encoding\/gob\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/syndtr\/goleveldb\/leveldb\"\n\t\"github.com\/syndtr\/goleveldb\/leveldb\/util\"\n\t\"gopkg.in\/h2non\/filetype.v1\"\n\t\"gopkg.in\/h2non\/filetype.v1\/types\"\n)\n\ntype Place struct {\n\tConfigPath string\n\tConfig     Config\n\tDb         *leveldb.DB\n\tPreview    bool\n\tNumber     int\n\tHistory    History\n\tTmpFile    map[string][]byte\n}\n\nfunc (p *Place) Run(files []string) {\n\tp.loadConfig()\n\tp.getNumber()\n\tp.History.Files = make(map[string]string)\n\tlog.Debug(\"Run:\", files)\n\tfor _, v := range files {\n\t\tp.run(v)\n\t}\n\tif !p.Preview {\n\t\tp.saveHistory()\n\t}\n}\n\nfunc (p *Place) getNumber() {\n\tname := []byte(\"count\")\n\tbs, _ := p.Db.Get(name, nil)\n\tp.Number = Bytes2Int(bs)\n\tp.Number += 1\n\tlog.Debugf(\"操作次数: %d\", p.Number)\n\tp.Db.Put(name, Int2Bytes(p.Number), nil)\n}\n\nfunc (p *Place) saveHistory() {\n\tlog.Debugf(\"保存历史: %v\", p.History.Files)\n\tp.History.Timestamp = time.Now()\n\tbf := bytes.NewBuffer(nil)\n\tenc := gob.NewEncoder(bf)\n\terr := enc.Encode(p.History)\n\tif err != nil {\n\t\tpanic(\"操作记录编码失败\")\n\t}\n\tp.Db.Put([]byte(fmt.Sprintf(\"no-%04d\", p.Number)), bf.Bytes(), nil)\n}\n\nfunc (p *Place) loadConfig() {\n\tp.Config = Config{}\n\tp.Config.Load(p.ConfigPath)\n}\n\nfunc (p *Place) run(file string) {\n\tinfo, err := os.Stat(file)\n\tif os.IsNotExist(err) {\n\t\tlog.Error(\"文件未找到: \", file)\n\t\treturn\n\t}\n\tlog.Debugf(\"%s 目录: %t\", file, info.IsDir())\n\tif info.IsDir() {\n\t\tlog.Info(\"忽略目录: \", file)\n\t} else {\n\t\tlog.Debug(\"处理文件: \", file)\n\t\tvar (\n\t\t\tf     *os.File\n\t\t\tcount int\n\t\t\tkind  types.Type\n\t\t)\n\t\tif f, err = os.Open(file); err != nil {\n\t\t\tlog.Errorf(\"文件 %s 无法读取\", file)\n\t\t\treturn\n\t\t}\n\t\treader := bufio.NewReader(f)\n\t\tbuffer := make([]byte, 16384)\n\t\thash := sha256.New()\n\t\tisHead := true\n\t\tfor {\n\t\t\tif count, err = reader.Read(buffer); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif isHead {\n\t\t\t\tisHead = false\n\t\t\t\thead := buffer[:261]\n\t\t\t\tif filetype.IsImage(head) {\n\t\t\t\t\tlog.Debugf(\"文件 %s 是图片\", file)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Debugf(\"文件 %s 不是图片\", file)\n\t\t\t\t}\n\t\t\t\tkind = Mime(head, file)\n\t\t\t}\n\t\t\thash.Write(buffer[:count])\n\t\t}\n\t\tlog.Debugf(\"%s sha256: %x\", file, hash.Sum(nil))\n\t\t\/\/ bs, _ := ioutil.ReadFile(file)\n\t\told := p.find(hash.Sum(nil))\n\t\tif old == \"\" {\n\t\t\tnewFile, err := p.moveName(kind, file, info)\n\t\t\tif err == nil {\n\t\t\t\tif p.Preview {\n\t\t\t\t\tlog.Infof(\"预览: %s >>> %s\", file, newFile)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Infof(\"移动: %s >>> %s\", file, newFile)\n\t\t\t\t\tp.History.Files[file] = newFile\n\t\t\t\t\tos.Rename(file, newFile)\n\t\t\t\t\tp.Db.Put(BytesPrefix(\"f-\", hash.Sum(nil)), []byte(newFile), nil)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Errorf(\"%s %s Mime: %s, Subtype: %s\", err, file, kind.MIME.Type, kind.MIME.Subtype)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warnf(\"文件 %s 重复, 原文件 %s\", file, old)\n\t\t}\n\t}\n}\n\nfunc (p *Place) find(hash []byte) string {\n\tfile, err := p.Db.Get(BytesPrefix(\"f-\", hash), nil)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn string(file)\n}\n\nfunc (p *Place) moveName(t types.Type, file string, info os.FileInfo) (string, error) {\n\tlog.Debugf(\"mime: %s, subtype: %s, 搬移文件: %s\", t.MIME.Type, t.MIME.Subtype, file)\n\text := path.Ext(file)\n\tfor _, ap := range p.Config.Paths {\n\t\tsubtypes := []string{\"\"}\n\t\tif ap.Subtype != \"\" {\n\t\t\tsubtypes = Split(ap.Subtype)\n\t\t}\n\t\texts := []string{\"\"}\n\t\tif ap.Ext != \"\" {\n\t\t\texts = Split(ap.Ext)\n\t\t}\n\t\tfor _, st := range subtypes {\n\t\t\tfor _, apExt := range exts {\n\t\t\t\tif matching(ap, strings.ToLower(st), t, ext, apExt) {\n\t\t\t\t\tnewDir := ap.Dir\n\t\t\t\t\tif ap.Subdir != \"\" {\n\t\t\t\t\t\tnewDir = path.Join(newDir, TimeFormat(info.ModTime(), ap.Subdir))\n\t\t\t\t\t}\n\t\t\t\t\tdir := ToPath(newDir)\n\t\t\t\t\tnewFile := path.Join(dir, path.Base(file))\n\t\t\t\t\tinfo, err := os.Stat(newFile)\n\t\t\t\t\tif os.IsNotExist(err) {\n\t\t\t\t\t\treturn newFile, nil\n\t\t\t\t\t}\n\t\t\t\t\tif info.IsDir() {\n\t\t\t\t\t\treturn file, errors.New(\"同名目录已经存在\")\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn file, errors.New(\"同名文件已经存在\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn file, errors.New(\"无匹配设置\")\n}\n\nfunc matching(ap *Path, subType string, t types.Type, ext string, apExt string) bool {\n\tif (strings.EqualFold(ap.Mime, t.MIME.Type) && strings.HasPrefix(t.MIME.Subtype, subType)) ||\n\t\t(ap.Mime == \"\" && ap.Subtype == \"\" && t == filetype.Unknown) ||\n\t\t(strings.EqualFold(ap.Mime, t.MIME.Type) && ap.Subtype == \"\") {\n\t\tif apExt == \"\" || strings.EqualFold(apExt, ext) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (p *Place) Scan() {\n\tlog.Info(\"开始目录扫描\")\n\tp.loadConfig()\n\n\tp.TmpFile = make(map[string][]byte)\n\titer := p.Db.NewIterator(util.BytesPrefix([]byte(\"f-\")), nil)\n\tfor iter.Next() {\n\t\tfile := string(iter.Value())\n\t\tp.TmpFile[file] = iter.Key()\n\t\tlog.Debug(\"缓存文件: \", file)\n\t}\n\titer.Release()\n\n\tfor _, ap := range p.Config.Paths {\n\t\tlog.Debug(\"扫描目录: \", ap.Dir)\n\t\tp.scanning(ToPath(ap.Dir))\n\t}\n\n\tfor file, key := range p.TmpFile {\n\t\tlog.Debug(\"删除缓存: \", file)\n\t\tp.Db.Delete(key, nil)\n\t}\n}\n\nfunc (p *Place) scanning(dir string) {\n\terr := filepath.Walk(dir, func(filename string, fi os.FileInfo, err error) error {\n\t\tif filename == dir {\n\t\t\treturn nil\n\t\t}\n\t\tif fi.IsDir() {\n\t\t\tp.scanning(filename)\n\t\t} else {\n\t\t\tlog.Debug(\"扫描文件: \", filename)\n\t\t\t_, ok := p.TmpFile[filename]\n\t\t\tif ok {\n\t\t\t\tdelete(p.TmpFile, filename)\n\t\t\t} else {\n\t\t\t\tbs, _ := ioutil.ReadFile(filename)\n\t\t\t\thash := sha256.New()\n\t\t\t\thash.Write(bs)\n\t\t\t\tkey := BytesPrefix(\"f-\", hash.Sum(nil))\n\t\t\t\told, err := p.Db.Get(key, nil)\n\t\t\t\tif err == nil {\n\t\t\t\t\tif filename != string(old) {\n\t\t\t\t\t\tlog.Warnf(\"文件重复: %s = %s\", filename, old)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Info(\"新增文件: \", filename)\n\t\t\t\t\tp.Db.Put(key, []byte(filename), nil)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Error(\"目录扫描错误: \", err)\n\t}\n}\n\nfunc (p *Place) Reset() {\n\tlog.Info(\"开始根据配置重置目录\")\n\n\tp.TmpFile = make(map[string][]byte)\n\titer := p.Db.NewIterator(util.BytesPrefix([]byte(\"f-\")), nil)\n\tfor iter.Next() {\n\t\tfile := string(iter.Value())\n\t\tp.TmpFile[file] = iter.Key()\n\t\tlog.Debug(\"缓存文件: \", file)\n\t}\n\titer.Release()\n\n\tfor _, ap := range p.Config.Paths {\n\t\tlog.Debug(\"扫描目录: \", ap.Dir)\n\t\tp.reset(ToPath(ap.Dir))\n\t}\n}\n\nfunc (p *Place) reset(dir string) {\n\tcount := 0\n\terr := filepath.Walk(dir, func(filename string, fi os.FileInfo, err error) error {\n\t\tif filename == dir {\n\t\t\treturn nil\n\t\t}\n\t\tcount += 1\n\t\tif fi.IsDir() {\n\t\t\tp.reset(filename)\n\t\t} else {\n\t\t\tlog.Debug(\"重置文件: \", filename)\n\t\t\tbs, _ := ioutil.ReadFile(filename)\n\t\t\thead := bs[:261]\n\t\t\tkind, _ := filetype.Match(head)\n\t\t\tnewFile, err := p.moveName(kind, filename, fi)\n\t\t\tif err != nil || newFile == filename {\n\t\t\t\tlog.Debug(\"无需移动: \", filename)\n\t\t\t} else {\n\t\t\t\tlog.Infof(\"移动: %s >>> %s\", filename, newFile)\n\t\t\t\tos.Rename(filename, newFile)\n\t\t\t\tkey, _ := p.TmpFile[filename]\n\t\t\t\tp.Db.Put(key, []byte(newFile), nil)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err == nil {\n\t\tlog.Debugf(\"%s 子文件数量: %d\", dir, count)\n\t\tif count == 0 {\n\t\t\tlog.Info(\"删除空目录: \", dir)\n\t\t\tos.Remove(dir)\n\t\t}\n\t} else {\n\t\tlog.Error(\"目录扫描错误: \", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package ploop\n\n\/\/ #include <ploop\/libploop.h>\nimport \"C\"\nimport \"fmt\"\n\ntype PloopErr struct {\n\tC int\n\ts string\n}\n\n\/\/ SYSEXIT_* errors\nconst (\n\t_ = iota\n\tE_CREAT\n\tE_DEVICE\n\tE_DEVIOC\n\tE_OPEN\n\tE_MALLOC\n\tE_READ\n\tE_WRITE\n\tE_RESERVED_8\n\tE_SYSFS\n\tE_RESERVED_10\n\tE_PLOOPFMT\n\tE_SYS\n\tE_PROTOCOL\n\tE_LOOP\n\tE_FSTAT\n\tE_FSYNC\n\tE_EBUSY\n\tE_FLOCK\n\tE_FTRUNCATE\n\tE_FALLOCATE\n\tE_MOUNT\n\tE_UMOUNT\n\tE_LOCK\n\tE_MKFS\n\tE_RESERVED_25\n\tE_RESIZE_FS\n\tE_MKDIR\n\tE_RENAME\n\tE_ABORT\n\tE_RELOC\n\tE_RESERVED_31\n\tE_RESERVED_32\n\tE_CHANGE_GPT\n\tE_RESERVED_34\n\tE_UNLINK\n\tE_MKNOD\n\tE_PLOOPINUSE\n\tE_PARAM\n\tE_DISKDESCR\n\tE_DEV_NOT_MOUNTED\n\tE_FSCK\n\tE_RESERVED_42\n\tE_NOSNAP\n)\n\nvar ErrCodes = []string{\n\tE_CREAT:           \"E_CREAT\",\n\tE_DEVICE:          \"E_DEVICE\",\n\tE_DEVIOC:          \"E_DEVIOC\",\n\tE_OPEN:            \"E_OPEN\",\n\tE_MALLOC:          \"E_MALLOC\",\n\tE_READ:            \"E_READ\",\n\tE_WRITE:           \"E_WRITE\",\n\tE_RESERVED_8:      \"E_RESERVED\",\n\tE_SYSFS:           \"E_SYSFS\",\n\tE_RESERVED_10:     \"E_RESERVED\",\n\tE_PLOOPFMT:        \"E_PLOOPFMT\",\n\tE_SYS:             \"E_SYS\",\n\tE_PROTOCOL:        \"E_PROTOCOL\",\n\tE_LOOP:            \"E_LOOP\",\n\tE_FSTAT:           \"E_FSTAT\",\n\tE_FSYNC:           \"E_FSYNC\",\n\tE_EBUSY:           \"E_EBUSY\",\n\tE_FLOCK:           \"E_FLOCK\",\n\tE_FTRUNCATE:       \"E_FTRUNCATE\",\n\tE_FALLOCATE:       \"E_FALLOCATE\",\n\tE_MOUNT:           \"E_MOUNT\",\n\tE_UMOUNT:          \"E_UMOUNT\",\n\tE_LOCK:            \"E_LOCK\",\n\tE_MKFS:            \"E_MKFS\",\n\tE_RESERVED_25:     \"E_RESERVED\",\n\tE_RESIZE_FS:       \"E_RESIZE_FS\",\n\tE_MKDIR:           \"E_MKDIR\",\n\tE_RENAME:          \"E_RENAME\",\n\tE_ABORT:           \"E_ABORT\",\n\tE_RELOC:           \"E_RELOC\",\n\tE_RESERVED_31:     \"E_RESERVED\",\n\tE_RESERVED_32:     \"E_RESERVED\",\n\tE_CHANGE_GPT:      \"E_CHANGE_GPT\",\n\tE_RESERVED_34:     \"E_RESERVED\",\n\tE_UNLINK:          \"E_UNLINK\",\n\tE_MKNOD:           \"E_MKNOD\",\n\tE_PLOOPINUSE:      \"E_PLOOPINUSE\",\n\tE_PARAM:           \"E_PARAM\",\n\tE_DISKDESCR:       \"E_DISKDESCR\",\n\tE_DEV_NOT_MOUNTED: \"E_DEV_NOT_MOUNTED\",\n\tE_FSCK:            \"E_FSCK\",\n\tE_RESERVED_42:     \"E_RESERVED\",\n\tE_NOSNAP:          \"E_NOSNAP\",\n}\n\nfunc (e *PloopErr) Error() string {\n\treturn fmt.Sprintf(\"ploop error %d (%s): %s\", e.C, ErrCodes[e.C], e.s)\n}\n\nfunc mkerr(ret C.int) error {\n\tif ret == 0 {\n\t\treturn nil\n\t}\n\n\treturn &PloopErr{C: int(ret), s: C.GoString(C.ploop_get_last_error())}\n}\n<commit_msg>Error(): report unknown errors<commit_after>package ploop\n\n\/\/ #include <ploop\/libploop.h>\nimport \"C\"\nimport \"fmt\"\n\ntype PloopErr struct {\n\tC int\n\ts string\n}\n\n\/\/ SYSEXIT_* errors\nconst (\n\t_ = iota\n\tE_CREAT\n\tE_DEVICE\n\tE_DEVIOC\n\tE_OPEN\n\tE_MALLOC\n\tE_READ\n\tE_WRITE\n\tE_RESERVED_8\n\tE_SYSFS\n\tE_RESERVED_10\n\tE_PLOOPFMT\n\tE_SYS\n\tE_PROTOCOL\n\tE_LOOP\n\tE_FSTAT\n\tE_FSYNC\n\tE_EBUSY\n\tE_FLOCK\n\tE_FTRUNCATE\n\tE_FALLOCATE\n\tE_MOUNT\n\tE_UMOUNT\n\tE_LOCK\n\tE_MKFS\n\tE_RESERVED_25\n\tE_RESIZE_FS\n\tE_MKDIR\n\tE_RENAME\n\tE_ABORT\n\tE_RELOC\n\tE_RESERVED_31\n\tE_RESERVED_32\n\tE_CHANGE_GPT\n\tE_RESERVED_34\n\tE_UNLINK\n\tE_MKNOD\n\tE_PLOOPINUSE\n\tE_PARAM\n\tE_DISKDESCR\n\tE_DEV_NOT_MOUNTED\n\tE_FSCK\n\tE_RESERVED_42\n\tE_NOSNAP\n)\n\nvar ErrCodes = []string{\n\tE_CREAT:           \"E_CREAT\",\n\tE_DEVICE:          \"E_DEVICE\",\n\tE_DEVIOC:          \"E_DEVIOC\",\n\tE_OPEN:            \"E_OPEN\",\n\tE_MALLOC:          \"E_MALLOC\",\n\tE_READ:            \"E_READ\",\n\tE_WRITE:           \"E_WRITE\",\n\tE_RESERVED_8:      \"E_RESERVED\",\n\tE_SYSFS:           \"E_SYSFS\",\n\tE_RESERVED_10:     \"E_RESERVED\",\n\tE_PLOOPFMT:        \"E_PLOOPFMT\",\n\tE_SYS:             \"E_SYS\",\n\tE_PROTOCOL:        \"E_PROTOCOL\",\n\tE_LOOP:            \"E_LOOP\",\n\tE_FSTAT:           \"E_FSTAT\",\n\tE_FSYNC:           \"E_FSYNC\",\n\tE_EBUSY:           \"E_EBUSY\",\n\tE_FLOCK:           \"E_FLOCK\",\n\tE_FTRUNCATE:       \"E_FTRUNCATE\",\n\tE_FALLOCATE:       \"E_FALLOCATE\",\n\tE_MOUNT:           \"E_MOUNT\",\n\tE_UMOUNT:          \"E_UMOUNT\",\n\tE_LOCK:            \"E_LOCK\",\n\tE_MKFS:            \"E_MKFS\",\n\tE_RESERVED_25:     \"E_RESERVED\",\n\tE_RESIZE_FS:       \"E_RESIZE_FS\",\n\tE_MKDIR:           \"E_MKDIR\",\n\tE_RENAME:          \"E_RENAME\",\n\tE_ABORT:           \"E_ABORT\",\n\tE_RELOC:           \"E_RELOC\",\n\tE_RESERVED_31:     \"E_RESERVED\",\n\tE_RESERVED_32:     \"E_RESERVED\",\n\tE_CHANGE_GPT:      \"E_CHANGE_GPT\",\n\tE_RESERVED_34:     \"E_RESERVED\",\n\tE_UNLINK:          \"E_UNLINK\",\n\tE_MKNOD:           \"E_MKNOD\",\n\tE_PLOOPINUSE:      \"E_PLOOPINUSE\",\n\tE_PARAM:           \"E_PARAM\",\n\tE_DISKDESCR:       \"E_DISKDESCR\",\n\tE_DEV_NOT_MOUNTED: \"E_DEV_NOT_MOUNTED\",\n\tE_FSCK:            \"E_FSCK\",\n\tE_RESERVED_42:     \"E_RESERVED\",\n\tE_NOSNAP:          \"E_NOSNAP\",\n}\n\nfunc (e *PloopErr) Error() string {\n\ts := \"E_UNKNOWN\"\n\tif e.C > 0 && e.C < len(ErrCodes) {\n\t\ts = ErrCodes[e.C]\n\t}\n\n\treturn fmt.Sprintf(\"ploop error %d (%s): %s\", e.C, s, e.s)\n}\n\nfunc mkerr(ret C.int) error {\n\tif ret == 0 {\n\t\treturn nil\n\t}\n\n\treturn &PloopErr{C: int(ret), s: C.GoString(C.ploop_get_last_error())}\n}\n<|endoftext|>"}
{"text":"<commit_before>package plugins\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/belak\/irc\"\n\t\"github.com\/belak\/seabird\/bot\"\n\t\"github.com\/jmoiron\/sqlx\"\n)\n\nfunc init() {\n\tbot.RegisterPlugin(\"remind\", NewReminderPlugin)\n}\n\ntype ReminderPlugin struct {\n\tdb *sqlx.DB\n}\n\ntype reminder struct {\n\tID           int64\n\tTarget       string\n\tTargetType   string `db:\"target_type\"`\n\tContent      string\n\tReminderTime time.Time `db:\"reminder_time\"`\n}\n\nfunc NewReminderPlugin(b *bot.Bot) (bot.Plugin, error) {\n\tb.LoadPlugin(\"db\")\n\tp := &ReminderPlugin{b.Plugins[\"db\"].(*sqlx.DB)}\n\n\tb.BasicMux.Event(\"001\", p.InitialDispatch)\n\tb.BasicMux.Event(\"JOIN\", p.JoinDispatch)\n\tb.CommandMux.Event(\"remind\", p.RemindCommand, &bot.HelpInfo{\n\t\tUsage:       \"<duration> <message>\",\n\t\tDescription: \"Remind yourself to do something.\",\n\t})\n\n\treturn nil, nil\n}\n\nfunc (p *ReminderPlugin) dispatch(b *bot.Bot, r *reminder) {\n\t\/\/ Because time.Sleep handles negative values (and 0) by simply\n\t\/\/ returning, this will be handled correctly even with negative\n\t\/\/ durations.\n\twaitDur := r.ReminderTime.Sub(time.Now())\n\n\t\/\/ Try to sleep this goroutine until the message needs to be delivered\n\ttime.Sleep(waitDur)\n\n\t\/\/ Send the message\n\tb.Send(&irc.Message{\n\t\tCommand: \"PRIVMSG\",\n\t\tParams:  []string{r.Target, r.Content},\n\t})\n\n\t\/\/ Nuke the reminder now that it's been sent\n\t_, err := p.db.Exec(\"DELETE FROM reminders WHERE id=$1\", r.ID)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}\n\n\/\/ InitialDispatch is used to send private messages to users on connection. We\n\/\/ can't queue up the channels yet because we haven't joined them.\nfunc (p *ReminderPlugin) InitialDispatch(b *bot.Bot, m *irc.Message) {\n\treminders := []*reminder{}\n\terr := p.db.Select(reminders, \"SELECT * FROM reminders WHERE target_type=$1\", \"private\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfor _, r := range reminders {\n\t\tgo p.dispatch(b, r)\n\t}\n}\n\n\/\/ When we join a channel, we need to see if there are any reminders to be\n\/\/ queued up.\nfunc (p *ReminderPlugin) JoinDispatch(b *bot.Bot, m *irc.Message) {\n\t\/\/ If it's not the bot, we ignore it.\n\tif m.Prefix.Name != b.CurrentNick() || len(m.Params) < 1 {\n\t\treturn\n\t}\n\n\treminders := []*reminder{}\n\terr := p.db.Select(reminders, \"SELECT * FROM reminders WHERE target_type=$1 AND target=$2\", \"public\", m.Params[0])\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfor _, r := range reminders {\n\t\tgo p.dispatch(b, r)\n\t}\n}\n\nfunc (p *ReminderPlugin) RemindCommand(b *bot.Bot, m *irc.Message) {\n\tsplit := strings.SplitN(m.Trailing(), \" \", 2)\n\tif len(split) != 2 {\n\t\tb.MentionReply(m, \"Not enough args\")\n\t\treturn\n\t}\n\n\tdur, err := time.ParseDuration(split[0])\n\tif err != nil {\n\t\tb.MentionReply(m, \"Invalid duration: %s\", err)\n\t\treturn\n\t}\n\n\tr := &reminder{\n\t\tTarget:       m.Prefix.Name,\n\t\tTargetType:   \"private\",\n\t\tContent:      split[1],\n\t\tReminderTime: time.Now().Add(dur),\n\t}\n\n\tif m.FromChannel() {\n\t\t\/\/ If it was from a channel, we need to prepend the user's name.\n\t\tr.Target = m.Params[0]\n\t\tr.TargetType = \"public\"\n\t\tr.Content = m.Prefix.Name + \": \" + r.Content\n\t}\n\n\tresult, err := p.db.Exec(\n\t\t\"INSERT INTO reminders (target, target_type, content, reminder_time) VALUES ($1, $2, $3, $4)\",\n\t\tr.Target, r.TargetType, r.Content, r.ReminderTime)\n\tif err != nil {\n\t\tb.MentionReply(m, \"Failed to store reminder: %s\", err)\n\t\treturn\n\t}\n\n\tr.ID, err = result.LastInsertId()\n\tif err != nil {\n\t\tb.MentionReply(m, \"Failed to get ID of stored reminder. This event may be fired a second time after the bot is restarted: %s\", err)\n\t}\n\n\tgo p.dispatch(b, r)\n}\n<commit_msg>Fix a few crashes in the remind plugin<commit_after>package plugins\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/belak\/irc\"\n\t\"github.com\/belak\/seabird\/bot\"\n\t\"github.com\/jmoiron\/sqlx\"\n)\n\nfunc init() {\n\tbot.RegisterPlugin(\"remind\", NewReminderPlugin)\n}\n\ntype ReminderPlugin struct {\n\tdb *sqlx.DB\n}\n\ntype reminder struct {\n\tID           int64\n\tTarget       string\n\tTargetType   string `db:\"target_type\"`\n\tContent      string\n\tReminderTime time.Time `db:\"reminder_time\"`\n}\n\nfunc NewReminderPlugin(b *bot.Bot) (bot.Plugin, error) {\n\tb.LoadPlugin(\"db\")\n\tp := &ReminderPlugin{b.Plugins[\"db\"].(*sqlx.DB)}\n\n\tif p.db.DriverName() != \"postgres\" {\n\t\treturn nil, errors.New(\"The reminder plugin must be used with postgres\")\n\t}\n\n\tb.BasicMux.Event(\"001\", p.InitialDispatch)\n\tb.BasicMux.Event(\"JOIN\", p.JoinDispatch)\n\tb.CommandMux.Event(\"remind\", p.RemindCommand, &bot.HelpInfo{\n\t\tUsage:       \"<duration> <message>\",\n\t\tDescription: \"Remind yourself to do something.\",\n\t})\n\n\treturn nil, nil\n}\n\nfunc (p *ReminderPlugin) dispatch(b *bot.Bot, r *reminder) {\n\t\/\/ Because time.Sleep handles negative values (and 0) by simply\n\t\/\/ returning, this will be handled correctly even with negative\n\t\/\/ durations.\n\twaitDur := r.ReminderTime.Sub(time.Now())\n\n\t\/\/ Try to sleep this goroutine until the message needs to be delivered\n\ttime.Sleep(waitDur)\n\n\t\/\/ Send the message\n\tb.Send(&irc.Message{\n\t\tPrefix:  &irc.Prefix{},\n\t\tCommand: \"PRIVMSG\",\n\t\tParams:  []string{r.Target, r.Content},\n\t})\n\n\t\/\/ Nuke the reminder now that it's been sent\n\t_, err := p.db.Exec(\"DELETE FROM reminders WHERE id=$1\", r.ID)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}\n\n\/\/ InitialDispatch is used to send private messages to users on connection. We\n\/\/ can't queue up the channels yet because we haven't joined them.\nfunc (p *ReminderPlugin) InitialDispatch(b *bot.Bot, m *irc.Message) {\n\treminders := []*reminder{}\n\terr := p.db.Select(&reminders, \"SELECT * FROM reminders WHERE target_type=$1\", \"private\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfor _, r := range reminders {\n\t\tgo p.dispatch(b, r)\n\t}\n}\n\n\/\/ When we join a channel, we need to see if there are any reminders to be\n\/\/ queued up.\nfunc (p *ReminderPlugin) JoinDispatch(b *bot.Bot, m *irc.Message) {\n\t\/\/ If it's not the bot, we ignore it.\n\tif m.Prefix.Name != b.CurrentNick() || len(m.Params) < 1 {\n\t\treturn\n\t}\n\n\treminders := []*reminder{}\n\terr := p.db.Select(&reminders, \"SELECT * FROM reminders WHERE target_type=$1 AND target=$2\", \"public\", m.Params[0])\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfor _, r := range reminders {\n\t\tgo p.dispatch(b, r)\n\t}\n}\n\nfunc (p *ReminderPlugin) RemindCommand(b *bot.Bot, m *irc.Message) {\n\tsplit := strings.SplitN(m.Trailing(), \" \", 2)\n\tif len(split) != 2 {\n\t\tb.MentionReply(m, \"Not enough args\")\n\t\treturn\n\t}\n\n\tdur, err := time.ParseDuration(split[0])\n\tif err != nil {\n\t\tb.MentionReply(m, \"Invalid duration: %s\", err)\n\t\treturn\n\t}\n\n\tr := &reminder{\n\t\tTarget:       m.Prefix.Name,\n\t\tTargetType:   \"private\",\n\t\tContent:      split[1],\n\t\tReminderTime: time.Now().Add(dur),\n\t}\n\n\tif m.FromChannel() {\n\t\t\/\/ If it was from a channel, we need to prepend the user's name.\n\t\tr.Target = m.Params[0]\n\t\tr.TargetType = \"public\"\n\t\tr.Content = m.Prefix.Name + \": \" + r.Content\n\t}\n\n\t\/\/ pq doesn't support .LastInsertId so we need to do this\n\tvar rowID int64\n\terr = p.db.QueryRow(\n\t\t\"INSERT INTO reminders (target, target_type, content, reminder_time) VALUES ($1, $2, $3, $4) RETURNING id\",\n\t\tr.Target, r.TargetType, r.Content, r.ReminderTime).Scan(&rowID)\n\tif err != nil {\n\t\tb.MentionReply(m, \"Failed to store reminder: %s\", err)\n\t\treturn\n\t}\n\n\tr.ID = rowID\n\n\tgo p.dispatch(b, r)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package create is used for copying skeleton app\n\/\/ to a requested destination.\n\/\/ Herewith, import path of the skeleton app is expected\n\/\/ to be rewritten to a new one.\npackage create\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/anonx\/sunplate\/command\"\n\t\"github.com\/anonx\/sunplate\/generation\/output\"\n\t\"github.com\/anonx\/sunplate\/log\"\n\tp \"github.com\/anonx\/sunplate\/path\"\n)\n\n\/\/ result represents objects found when scanning a skeleton directory.\n\/\/ There are a few possible kind of them: directories, static files,\n\/\/ go source files (that require additional processing of their content).\ntype result struct {\n\tdirs, files, srcs map[string]string \/\/ Keys are full paths, values are relative ones.\n}\n\n\/\/ Start is an entry point of the command.\nfunc Start(action string, params command.Data) {\n\toldImport := p.SunplateImport(\"skeleton\")\n\tnewImport := p.AbsoluteImport(params.Default(action, \".\/\"))\n\n\tinputDir := p.SunplateDir(\"skeleton\")\n\toutputDir := p.PackageDir(newImport)\n\n\trs, fn := walkFunc(inputDir)\n\tfilepath.Walk(inputDir, fn)\n\n\tfor _, v := range rs.dirs {\n\t\tt := output.Type{}\n\t\tt.CreateDir(filepath.Join(outputDir, v))\n\t}\n\n\tfor k, v := range rs.files {\n\t\tcopyFile(k, filepath.Join(outputDir, v))\n\t}\n\n\tfor k, v := range rs.srcs {\n\t\tcopyModifiedFile(k, filepath.Join(outputDir, v), map[string]string{\n\t\t\toldImport: newImport,\n\t\t})\n\t}\n\n\tlog.Info.Printf(info, newImport, newImport)\n}\n\n\/\/ walkFunc returns a result instance and a function that may be used for validation\n\/\/ of found elements. Successfully validated ones are stored to the returned result.\nfunc walkFunc(dir string) (result, func(string, os.FileInfo, error) error) {\n\trs := result{\n\t\tdirs:  map[string]string{},\n\t\tfiles: map[string]string{},\n\t\tsrcs:  map[string]string{},\n\t}\n\n\treturn rs, func(path string, info os.FileInfo, err error) error {\n\t\t\/\/ Make sure there are no any errors.\n\t\tif err != nil {\n\t\t\tlog.Warn.Printf(`An error occured while scanning a skeleton: \"%s\".`, err)\n\t\t\treturn err\n\t\t}\n\n\t\trelPath := p.Prefixless(path, dir)\n\n\t\t\/\/ Check whether current element is a directory.\n\t\tif info.IsDir() {\n\t\t\trs.dirs[path] = relPath\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Find out whether it is a static file or a go source.\n\t\tif filepath.Ext(path) == \".go\" {\n\t\t\trs.srcs[path] = relPath\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ If it is a static file, add it to the list.\n\t\trs.files[path] = relPath\n\t\treturn err\n\t}\n}\n\nvar info = `Your application is ready:\n\t%s\nYou can run it with:\n\tsunplate run %s\n`\n<commit_msg>Make sure dir doesn't exist before creating a project<commit_after>\/\/ Package create is used for copying skeleton app\n\/\/ to a requested destination.\n\/\/ Herewith, import path of the skeleton app is expected\n\/\/ to be rewritten to a new one.\npackage create\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/anonx\/sunplate\/command\"\n\t\"github.com\/anonx\/sunplate\/generation\/output\"\n\t\"github.com\/anonx\/sunplate\/log\"\n\tp \"github.com\/anonx\/sunplate\/path\"\n)\n\n\/\/ result represents objects found when scanning a skeleton directory.\n\/\/ There are a few possible kind of them: directories, static files,\n\/\/ go source files (that require additional processing of their content).\ntype result struct {\n\tdirs, files, srcs map[string]string \/\/ Keys are full paths, values are relative ones.\n}\n\n\/\/ Start is an entry point of the command.\nfunc Start(action string, params command.Data) {\n\toldImport := p.SunplateImport(\"skeleton\")\n\tnewImport := p.AbsoluteImport(params.Default(action, \".\/\"))\n\n\tinputDir := p.SunplateDir(\"skeleton\")\n\toutputDir := p.PackageDir(newImport)\n\n\t\/\/ Make sure the output directory does not exist yet.\n\tif _, err := os.Stat(outputDir); !os.IsNotExist(err) {\n\t\tlog.Error.Fatalf(`Abort: Import path \"%s\" already exists.`, newImport)\n\t}\n\n\trs, fn := walkFunc(inputDir)\n\tfilepath.Walk(inputDir, fn)\n\n\tfor _, v := range rs.dirs {\n\t\tt := output.Type{}\n\t\tt.CreateDir(filepath.Join(outputDir, v))\n\t}\n\n\tfor k, v := range rs.files {\n\t\tcopyFile(k, filepath.Join(outputDir, v))\n\t}\n\n\tfor k, v := range rs.srcs {\n\t\tcopyModifiedFile(k, filepath.Join(outputDir, v), map[string]string{\n\t\t\toldImport: newImport,\n\t\t})\n\t}\n\n\tlog.Info.Printf(info, newImport, newImport)\n}\n\n\/\/ walkFunc returns a result instance and a function that may be used for validation\n\/\/ of found elements. Successfully validated ones are stored to the returned result.\nfunc walkFunc(dir string) (result, func(string, os.FileInfo, error) error) {\n\trs := result{\n\t\tdirs:  map[string]string{},\n\t\tfiles: map[string]string{},\n\t\tsrcs:  map[string]string{},\n\t}\n\n\treturn rs, func(path string, info os.FileInfo, err error) error {\n\t\t\/\/ Make sure there are no any errors.\n\t\tif err != nil {\n\t\t\tlog.Warn.Printf(`An error occured while scanning a skeleton: \"%s\".`, err)\n\t\t\treturn err\n\t\t}\n\n\t\trelPath := p.Prefixless(path, dir)\n\n\t\t\/\/ Check whether current element is a directory.\n\t\tif info.IsDir() {\n\t\t\trs.dirs[path] = relPath\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Find out whether it is a static file or a go source.\n\t\tif filepath.Ext(path) == \".go\" {\n\t\t\trs.srcs[path] = relPath\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ If it is a static file, add it to the list.\n\t\trs.files[path] = relPath\n\t\treturn err\n\t}\n}\n\nvar info = `Your application \"%s\" is ready:\nYou can run it with:\n\tsunplate run %s\n`\n<|endoftext|>"}
{"text":"<commit_before>package plugins\n\nimport (\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/josledp\/termcolor\"\n)\n\n\/\/Aws is the plugin struct\ntype Aws struct {\n\trole   string\n\texpire time.Time\n}\n\n\/\/Name returns the plugin name\nfunc (Aws) Name() string {\n\treturn \"aws\"\n}\n\n\/\/Load is the load function of the plugin\nfunc (a *Aws) Load(options map[string]interface{}) error {\n\trole := os.Getenv(\"AWS_ROLE\")\n\tif role != \"\" {\n\t\ttmp := strings.Split(role, \":\")\n\t\trole = tmp[0]\n\t\ttmp = strings.Split(tmp[1], \"-\")\n\t\trole += \":\" + tmp[2]\n\t}\n\ta.role = role\n\tiExpire, _ := strconv.ParseInt(os.Getenv(\"AWS_SESSION_EXPIRE\"), 10, 0)\n\ta.expire = time.Unix(iExpire, int64(0))\n\treturn nil\n}\n\n\/\/Get returns the string to use in the prompt\nfunc (a Aws) Get(format func(string, ...termcolor.Mode) string) (string, []termcolor.Mode) {\n\tif a.role != \"\" {\n\t\tt := termcolor.FgGreen\n\t\td := time.Until(a.expire).Seconds()\n\t\tif d < 0 {\n\t\t\tt = termcolor.FgRed\n\t\t} else if d < 1800 {\n\t\t\tt = termcolor.FgBlue\n\t\t} else if d < 600 {\n\t\t\tt = termcolor.FgYellow\n\t\t}\n\t\treturn format(a.role, t), []termcolor.Mode{t}\n\t}\n\treturn \"\", nil\n}\n<commit_msg>remove extra mode from aws role<commit_after>package plugins\n\nimport (\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/josledp\/termcolor\"\n)\n\n\/\/Aws is the plugin struct\ntype Aws struct {\n\trole   string\n\texpire time.Time\n}\n\n\/\/Name returns the plugin name\nfunc (Aws) Name() string {\n\treturn \"aws\"\n}\n\n\/\/Load is the load function of the plugin\nfunc (a *Aws) Load(options map[string]interface{}) error {\n\trole := os.Getenv(\"AWS_ROLE\")\n\tif role != \"\" {\n\t\ttmp := strings.Split(role, \":\")\n\t\trole = tmp[0]\n\t\ttmp = strings.Split(tmp[1], \"-\")\n\t\trole += \":\" + tmp[2]\n\t}\n\ta.role = role\n\tiExpire, _ := strconv.ParseInt(os.Getenv(\"AWS_SESSION_EXPIRE\"), 10, 0)\n\ta.expire = time.Unix(iExpire, int64(0))\n\treturn nil\n}\n\n\/\/Get returns the string to use in the prompt\nfunc (a Aws) Get(format func(string, ...termcolor.Mode) string) (string, []termcolor.Mode) {\n\tif a.role != \"\" {\n\t\tt := termcolor.FgGreen\n\t\td := time.Until(a.expire).Seconds()\n\t\tif d < 0 {\n\t\t\tt = termcolor.FgRed\n\t\t} else if d < 1800 {\n\t\t\tt = termcolor.FgBlue\n\t\t} else if d < 600 {\n\t\t\tt = termcolor.FgYellow\n\t\t}\n\t\treturn format(a.role, t), nil\n\t}\n\treturn \"\", nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017, Oracle and\/or its affiliates. All rights reserved.\n\npackage lb\n\nimport (\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\n\t\"github.com\/oracle\/terraform-provider-baremetal\/client\"\n\t\"github.com\/oracle\/terraform-provider-baremetal\/crud\"\n)\n\nfunc LoadBalancerBackendSetResource() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: createLoadBalancerBackendSet,\n\t\tRead:   readLoadBalancerBackendSet,\n\t\tUpdate: updateLoadBalancerBackendSet,\n\t\tDelete: deleteLoadBalancerBackendSet,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"load_balancer_id\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"backendset_name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t\"policy\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"health_checker\":    HealthCheckerSchema,\n\t\t\t\"ssl_configuration\": SSLConfigSchema,\n\t\t\t\"backend\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tComputed: true,\n\t\t\t\tElem:     LoadBalancerBackendResource(),\n\t\t\t},\n\t\t\t\/\/ internal for work request access\n\t\t\t\"state\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc createLoadBalancerBackendSet(d *schema.ResourceData, m interface{}) (e error) {\n\tsync := &LoadBalancerBackendSetResourceCrud{}\n\tsync.D = d\n\tsync.Client = m.(client.BareMetalClient)\n\treturn crud.CreateResource(d, sync)\n}\n\nfunc readLoadBalancerBackendSet(d *schema.ResourceData, m interface{}) (e error) {\n\tsync := &LoadBalancerBackendSetResourceCrud{}\n\tsync.D = d\n\tsync.Client = m.(client.BareMetalClient)\n\treturn crud.ReadResource(sync)\n}\n\nfunc updateLoadBalancerBackendSet(d *schema.ResourceData, m interface{}) (e error) {\n\tsync := &LoadBalancerBackendSetResourceCrud{}\n\tsync.D = d\n\tsync.Client = m.(client.BareMetalClient)\n\treturn crud.UpdateResource(d, sync)\n}\n\nfunc deleteLoadBalancerBackendSet(d *schema.ResourceData, m interface{}) (e error) {\n\tsync := &LoadBalancerBackendSetResourceCrud{}\n\tsync.D = d\n\tsync.Client = m.(client.BareMetalClient)\n\treturn crud.DeleteResource(d, sync)\n}\n<commit_msg>Redo schemas so resources can be laid out in a .tf format and updated appropriately. This breaks everything, we need to go back and fix the crud pieces of this too<commit_after>\/\/ Copyright (c) 2017, Oracle and\/or its affiliates. All rights reserved.\n\npackage lb\n\nimport (\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\n\t\"github.com\/oracle\/terraform-provider-baremetal\/client\"\n\t\"github.com\/oracle\/terraform-provider-baremetal\/crud\"\n)\n\nfunc LoadBalancerBackendSetResource() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: createLoadBalancerBackendSet,\n\t\tRead:   readLoadBalancerBackendSet,\n\t\tUpdate: updateLoadBalancerBackendSet,\n\t\tDelete: deleteLoadBalancerBackendSet,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"load_balancer_id\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"policy\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"health_checker\":    HealthCheckerSchema,\n\t\t\t\"ssl_configuration\": SSLConfigSchema,\n\t\t\t\"backend\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tComputed: true,\n\t\t\t\tElem:     LoadBalancerBackendResource(),\n\t\t\t},\n\t\t\t\/\/ internal for work request access\n\t\t\t\"state\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc createLoadBalancerBackendSet(d *schema.ResourceData, m interface{}) (e error) {\n\tsync := &LoadBalancerBackendSetResourceCrud{}\n\tsync.D = d\n\tsync.Client = m.(client.BareMetalClient)\n\treturn crud.CreateResource(d, sync)\n}\n\nfunc readLoadBalancerBackendSet(d *schema.ResourceData, m interface{}) (e error) {\n\tsync := &LoadBalancerBackendSetResourceCrud{}\n\tsync.D = d\n\tsync.Client = m.(client.BareMetalClient)\n\treturn crud.ReadResource(sync)\n}\n\nfunc updateLoadBalancerBackendSet(d *schema.ResourceData, m interface{}) (e error) {\n\tsync := &LoadBalancerBackendSetResourceCrud{}\n\tsync.D = d\n\tsync.Client = m.(client.BareMetalClient)\n\treturn crud.UpdateResource(d, sync)\n}\n\nfunc deleteLoadBalancerBackendSet(d *schema.ResourceData, m interface{}) (e error) {\n\tsync := &LoadBalancerBackendSetResourceCrud{}\n\tsync.D = d\n\tsync.Client = m.(client.BareMetalClient)\n\treturn crud.DeleteResource(d, sync)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nPackage render implements a simple wrapper around Webkit that primarily allows for the capture of screenshots.\n\nThis package will typically only compile on a modern Linux distribution and requires a running X server. A utility binary is also provided.\n\n*\/\npackage render\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/auroralaboratories\/go-webkit2\/webkit2\"\n\t\"github.com\/auroralaboratories\/gotk3\/glib\"\n\t\"github.com\/auroralaboratories\/gotk3\/gtk\"\n\t\"github.com\/fsnotify\/fsnotify\"\n\t\"github.com\/sqs\/gojs\"\n\t\"image\"\n\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar (\n\t\/\/ ErrLoadFailed signifies that Webkit reports failure of of the page load\n\tErrLoadFailed = errors.New(\"load-failed\")\n\t\/\/ ErrViewClosed signifies that the View has already been closed, not further operations allowed\n\tErrViewClosed = errors.New(\"view-closed\")\n\t\/\/ ErrTimeout signifies that the supplied timeout has been triggered\n\tErrTimeout = errors.New(\"timeout\")\n\t\/\/ ErrNoImage signifies that snapshot did not return a usable image\n\tErrNoImage = errors.New(\"no-image\")\n\t\/\/ ErrNoTiming signifies that no timing information is available\n\tErrNoTiming = errors.New(\"load-not-timed\")\n\t\/\/ ErrNoX signifies that we did not find a usable X display server\n\tErrNoX = errors.New(\"no-x-display\")\n)\n\nvar gtkOnce sync.Once\n\nfunc newTimeout(t *time.Duration) chan bool {\n\ttimeout := make(chan bool, 1)\n\tif t != nil && *t != 0 {\n\t\tgo func() {\n\t\t\ttime.Sleep(*t)\n\t\t\ttimeout <- true\n\t\t}()\n\t}\n\treturn timeout\n}\n\ntype View struct {\n\t*webkit2.WebView\n\tload        chan struct{}\n\tlastLoadErr error\n\tclosed      bool\n\n\tloadRequested *time.Time\n\tloadStarted   *time.Time\n\tloadFinished  *time.Time\n}\n\nfunc (v *View) TimeToStart() (time.Duration, error) {\n\tif v.loadRequested == nil || v.loadStarted == nil {\n\t\treturn 0, ErrNoTiming\n\t}\n\n\treturn v.loadStarted.Sub(*v.loadRequested), nil\n}\n\nfunc (v *View) TimeToLoad() (time.Duration, error) {\n\tif v.loadStarted == nil || v.loadFinished == nil {\n\t\treturn 0, ErrNoTiming\n\t}\n\n\treturn v.loadFinished.Sub(*v.loadStarted), nil\n}\n\nfunc (v *View) TimeToFinish() (time.Duration, error) {\n\tif v.loadRequested == nil || v.loadFinished == nil {\n\t\treturn 0, ErrNoTiming\n\t}\n\n\treturn v.loadFinished.Sub(*v.loadRequested), nil\n}\n\nfunc (v *View) LoadURI(url string) error {\n\tif v.closed {\n\t\treturn ErrViewClosed\n\t}\n\n\tv.load = make(chan struct{}, 1)\n\tv.lastLoadErr = nil\n\tv.loadRequested = nil\n\tv.loadStarted = nil\n\tv.loadFinished = nil\n\n\tglib.IdleAdd(func() bool {\n\t\tt := time.Now()\n\t\tv.loadRequested = &t\n\t\tv.WebView.LoadURI(url)\n\t\treturn false\n\t})\n\n\treturn nil\n}\n\nfunc (v *View) LoadHTML(content, baseURI string) error {\n\tif v.closed {\n\t\treturn ErrViewClosed\n\t}\n\n\tv.load = make(chan struct{}, 1)\n\tv.lastLoadErr = nil\n\tv.loadRequested = nil\n\tv.loadStarted = nil\n\tv.loadFinished = nil\n\n\tglib.IdleAdd(func() bool {\n\t\tt := time.Now()\n\t\tv.loadRequested = &t\n\t\tv.WebView.LoadHTML(content, baseURI)\n\t\treturn false\n\t})\n\n\treturn nil\n}\n\nfunc (v *View) NewSnapshot(t *time.Duration) (result *image.RGBA, err error) {\n\tif v.closed {\n\t\treturn nil, ErrViewClosed\n\t}\n\n\tresultChan := make(chan *image.RGBA, 1)\n\terrChan := make(chan error, 1)\n\ttimeout := newTimeout(t)\n\n\tglib.IdleAdd(func() bool {\n\t\tv.GetSnapshot(func(img *image.RGBA, err error) {\n\t\t\tif err != nil {\n\t\t\t\terrChan <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif img == nil {\n\t\t\t\terrChan <- ErrNoImage\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresultChan <- img\n\t\t})\n\t\treturn false\n\t})\n\n\tselect {\n\tcase result = <-resultChan:\n\t\treturn result, nil\n\tcase err = <-errChan:\n\t\treturn nil, err\n\tcase <-timeout:\n\t\treturn nil, ErrTimeout\n\t}\n}\n\nfunc (v *View) EvaluateJavaScript(script string, t *time.Duration) (result interface{}, err error) {\n\tif v.closed {\n\t\treturn nil, ErrViewClosed\n\t}\n\n\tresultChan := make(chan interface{}, 1)\n\terrChan := make(chan error, 1)\n\ttimeout := newTimeout(t)\n\n\tglib.IdleAdd(func() bool {\n\t\tv.WebView.RunJavaScript(script, func(result *gojs.Value, err error) {\n\t\t\tif err == nil {\n\t\t\t\tgoval, err := result.GoValue()\n\t\t\t\tif err != nil {\n\t\t\t\t\terrChan <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t\/\/ Patch the value type to int64 if a whole number\n\t\t\t\tif goval != nil && (reflect.TypeOf(goval).Kind() == reflect.Float64) {\n\t\t\t\t\tf := goval.(float64)\n\t\t\t\t\tif i := int64(f); float64(i) == f {\n\t\t\t\t\t\tgoval = i\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresultChan <- goval\n\t\t\t} else {\n\t\t\t\terrChan <- err\n\t\t\t}\n\t\t\treturn\n\t\t})\n\t\treturn false\n\t})\n\n\tselect {\n\tcase result = <-resultChan:\n\t\treturn result, nil\n\tcase err = <-errChan:\n\t\treturn nil, err\n\tcase <-timeout:\n\t\treturn nil, ErrTimeout\n\t}\n}\n\n\/\/ Wait for the current page to finish loading.\nfunc (v *View) Wait(t *time.Duration) error {\n\tif v.closed {\n\t\treturn ErrViewClosed\n\t}\n\n\ttimeout := newTimeout(t)\n\n\tselect {\n\tcase <-timeout:\n\t\treturn ErrTimeout\n\tcase <-v.load:\n\t\treturn v.lastLoadErr\n\t}\n\n}\n\nfunc (v *View) Close() {\n\tif v.closed {\n\t\treturn\n\t}\n\n\tv.closed = true\n\tv.Destroy()\n}\n\ntype Renderer struct {\n\tsync.Mutex\n}\n\nconst envDisplay = \"DISPLAY\"\nconst xLockParent = \"\/tmp\"\n\nfunc (r *Renderer) waitForX() error {\n\td := os.Getenv(envDisplay)\n\tif d == \"\" {\n\t\treturn fmt.Errorf(\"No %s variable set for X\", envDisplay)\n\t}\n\n\tif len(d) < 2 {\n\t\treturn fmt.Errorf(\"%s variable %q is malformed\", envDisplay, d)\n\t}\n\tn := d[1:]\n\n\tf := fmt.Sprintf(\"%s\/.X%s-lock\", xLockParent, n)\n\n\tw, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer w.Close()\n\n\tt := 10 * time.Second\n\ttimeout := newTimeout(&t)\n\tfound := make(chan struct{})\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-w.Events:\n\t\t\t\tif event.Op&fsnotify.Create == fsnotify.Create {\n\t\t\t\t\tif event.Name == f {\n\t\t\t\t\t\t\/\/ got it\n\t\t\t\t\t\tclose(found)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase err := <-w.Errors:\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t} \/\/ else the watcher was closed\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = w.Add(xLockParent)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := os.Stat(f); os.IsNotExist(err) {\n\t\tlog.Printf(\"Waiting on %s\", f)\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\treturn ErrNoX\n\t\tcase <-found:\n\t\t\treturn nil\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\n\/\/ NewRenderer creates a new GTK based rendering context\nfunc NewRenderer() (*Renderer, error) {\n\tr := Renderer{}\n\n\tif err := r.waitForX(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.start()\n\n\treturn &r, nil\n}\n\n\/\/ Ensure that the GTK+ main loop has started. If it has already been\nfunc (r *Renderer) start() {\n\tgtkOnce.Do(func() {\n\t\tgtk.Init(nil)\n\t\tgo func() {\n\t\t\truntime.LockOSThread()\n\t\t\tgtk.Main()\n\t\t}()\n\t})\n}\n\n\/\/ NewView creates a new Webkit view\nfunc (r *Renderer) NewView(appName, appVersion string, autoLoadImages, consoleStdout bool) *View {\n\tc := make(chan *View, 1)\n\n\tr.Lock()\n\n\tglib.IdleAdd(func() bool {\n\t\twebView := webkit2.NewWebView()\n\t\tsettings := webView.Settings()\n\t\tsettings.SetAutoLoadImages(autoLoadImages)\n\t\tsettings.SetEnableWriteConsoleMessagesToStdout(consoleStdout)\n\t\tsettings.SetUserAgentWithApplicationDetails(appName, appVersion)\n\t\tv := &View{WebView: webView}\n\t\tloadChangedHandler, _ := webView.Connect(\"load-changed\", func(_ *glib.Object, loadEvent webkit2.LoadEvent) {\n\t\t\tt := time.Now()\n\t\t\tswitch loadEvent {\n\t\t\tcase webkit2.LoadStarted:\n\t\t\t\tv.loadStarted = &t\n\t\t\tcase webkit2.LoadFinished:\n\t\t\t\tv.loadFinished = &t\n\t\t\t\tv.load <- struct{}{}\n\t\t\t}\n\t\t})\n\t\twebView.Connect(\"load-failed\", func() {\n\t\t\tv.lastLoadErr = ErrLoadFailed\n\t\t\twebView.HandlerDisconnect(loadChangedHandler)\n\t\t})\n\t\tc <- v\n\t\treturn false\n\t})\n\n\tr.Unlock()\n\n\treturn <-c\n}\n<commit_msg>Fixed wait for X spin<commit_after>\/*\nPackage render implements a simple wrapper around Webkit that primarily allows for the capture of screenshots.\n\nThis package will typically only compile on a modern Linux distribution and requires a running X server. A utility binary is also provided.\n\n*\/\npackage render\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/auroralaboratories\/go-webkit2\/webkit2\"\n\t\"github.com\/auroralaboratories\/gotk3\/glib\"\n\t\"github.com\/auroralaboratories\/gotk3\/gtk\"\n\t\"github.com\/fsnotify\/fsnotify\"\n\t\"github.com\/sqs\/gojs\"\n\t\"image\"\n\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar (\n\t\/\/ ErrLoadFailed signifies that Webkit reports failure of of the page load\n\tErrLoadFailed = errors.New(\"load-failed\")\n\t\/\/ ErrViewClosed signifies that the View has already been closed, not further operations allowed\n\tErrViewClosed = errors.New(\"view-closed\")\n\t\/\/ ErrTimeout signifies that the supplied timeout has been triggered\n\tErrTimeout = errors.New(\"timeout\")\n\t\/\/ ErrNoImage signifies that snapshot did not return a usable image\n\tErrNoImage = errors.New(\"no-image\")\n\t\/\/ ErrNoTiming signifies that no timing information is available\n\tErrNoTiming = errors.New(\"load-not-timed\")\n\t\/\/ ErrNoX signifies that we did not find a usable X display server\n\tErrNoX = errors.New(\"no-x-display\")\n)\n\nvar gtkOnce sync.Once\n\nfunc newTimeout(t *time.Duration) chan bool {\n\ttimeout := make(chan bool, 1)\n\tif t != nil && *t != 0 {\n\t\tgo func() {\n\t\t\ttime.Sleep(*t)\n\t\t\ttimeout <- true\n\t\t}()\n\t}\n\treturn timeout\n}\n\ntype View struct {\n\t*webkit2.WebView\n\tload        chan struct{}\n\tlastLoadErr error\n\tclosed      bool\n\n\tloadRequested *time.Time\n\tloadStarted   *time.Time\n\tloadFinished  *time.Time\n}\n\nfunc (v *View) TimeToStart() (time.Duration, error) {\n\tif v.loadRequested == nil || v.loadStarted == nil {\n\t\treturn 0, ErrNoTiming\n\t}\n\n\treturn v.loadStarted.Sub(*v.loadRequested), nil\n}\n\nfunc (v *View) TimeToLoad() (time.Duration, error) {\n\tif v.loadStarted == nil || v.loadFinished == nil {\n\t\treturn 0, ErrNoTiming\n\t}\n\n\treturn v.loadFinished.Sub(*v.loadStarted), nil\n}\n\nfunc (v *View) TimeToFinish() (time.Duration, error) {\n\tif v.loadRequested == nil || v.loadFinished == nil {\n\t\treturn 0, ErrNoTiming\n\t}\n\n\treturn v.loadFinished.Sub(*v.loadRequested), nil\n}\n\nfunc (v *View) LoadURI(url string) error {\n\tif v.closed {\n\t\treturn ErrViewClosed\n\t}\n\n\tv.load = make(chan struct{}, 1)\n\tv.lastLoadErr = nil\n\tv.loadRequested = nil\n\tv.loadStarted = nil\n\tv.loadFinished = nil\n\n\tglib.IdleAdd(func() bool {\n\t\tt := time.Now()\n\t\tv.loadRequested = &t\n\t\tv.WebView.LoadURI(url)\n\t\treturn false\n\t})\n\n\treturn nil\n}\n\nfunc (v *View) LoadHTML(content, baseURI string) error {\n\tif v.closed {\n\t\treturn ErrViewClosed\n\t}\n\n\tv.load = make(chan struct{}, 1)\n\tv.lastLoadErr = nil\n\tv.loadRequested = nil\n\tv.loadStarted = nil\n\tv.loadFinished = nil\n\n\tglib.IdleAdd(func() bool {\n\t\tt := time.Now()\n\t\tv.loadRequested = &t\n\t\tv.WebView.LoadHTML(content, baseURI)\n\t\treturn false\n\t})\n\n\treturn nil\n}\n\nfunc (v *View) NewSnapshot(t *time.Duration) (result *image.RGBA, err error) {\n\tif v.closed {\n\t\treturn nil, ErrViewClosed\n\t}\n\n\tresultChan := make(chan *image.RGBA, 1)\n\terrChan := make(chan error, 1)\n\ttimeout := newTimeout(t)\n\n\tglib.IdleAdd(func() bool {\n\t\tv.GetSnapshot(func(img *image.RGBA, err error) {\n\t\t\tif err != nil {\n\t\t\t\terrChan <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif img == nil {\n\t\t\t\terrChan <- ErrNoImage\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresultChan <- img\n\t\t})\n\t\treturn false\n\t})\n\n\tselect {\n\tcase result = <-resultChan:\n\t\treturn result, nil\n\tcase err = <-errChan:\n\t\treturn nil, err\n\tcase <-timeout:\n\t\treturn nil, ErrTimeout\n\t}\n}\n\nfunc (v *View) EvaluateJavaScript(script string, t *time.Duration) (result interface{}, err error) {\n\tif v.closed {\n\t\treturn nil, ErrViewClosed\n\t}\n\n\tresultChan := make(chan interface{}, 1)\n\terrChan := make(chan error, 1)\n\ttimeout := newTimeout(t)\n\n\tglib.IdleAdd(func() bool {\n\t\tv.WebView.RunJavaScript(script, func(result *gojs.Value, err error) {\n\t\t\tif err == nil {\n\t\t\t\tgoval, err := result.GoValue()\n\t\t\t\tif err != nil {\n\t\t\t\t\terrChan <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t\/\/ Patch the value type to int64 if a whole number\n\t\t\t\tif goval != nil && (reflect.TypeOf(goval).Kind() == reflect.Float64) {\n\t\t\t\t\tf := goval.(float64)\n\t\t\t\t\tif i := int64(f); float64(i) == f {\n\t\t\t\t\t\tgoval = i\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresultChan <- goval\n\t\t\t} else {\n\t\t\t\terrChan <- err\n\t\t\t}\n\t\t\treturn\n\t\t})\n\t\treturn false\n\t})\n\n\tselect {\n\tcase result = <-resultChan:\n\t\treturn result, nil\n\tcase err = <-errChan:\n\t\treturn nil, err\n\tcase <-timeout:\n\t\treturn nil, ErrTimeout\n\t}\n}\n\n\/\/ Wait for the current page to finish loading.\nfunc (v *View) Wait(t *time.Duration) error {\n\tif v.closed {\n\t\treturn ErrViewClosed\n\t}\n\n\ttimeout := newTimeout(t)\n\n\tselect {\n\tcase <-timeout:\n\t\treturn ErrTimeout\n\tcase <-v.load:\n\t\treturn v.lastLoadErr\n\t}\n\n}\n\nfunc (v *View) Close() {\n\tif v.closed {\n\t\treturn\n\t}\n\n\tv.closed = true\n\tv.Destroy()\n}\n\ntype Renderer struct {\n\tsync.Mutex\n}\n\nconst envDisplay = \"DISPLAY\"\nconst xLockParent = \"\/tmp\"\n\nfunc (r *Renderer) waitForX() error {\n\td := os.Getenv(envDisplay)\n\tif d == \"\" {\n\t\treturn fmt.Errorf(\"No %s variable set for X\", envDisplay)\n\t}\n\n\tif len(d) < 2 {\n\t\treturn fmt.Errorf(\"%s variable %q is malformed\", envDisplay, d)\n\t}\n\tn := d[1:]\n\n\tf := fmt.Sprintf(\"%s\/.X%s-lock\", xLockParent, n)\n\n\tw, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer w.Close()\n\n\tt := 10 * time.Second\n\ttimeout := newTimeout(&t)\n\tfound := make(chan struct{})\n\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-w.Events:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif event.Op&fsnotify.Create == fsnotify.Create {\n\t\t\t\t\tif event.Name == f {\n\t\t\t\t\t\t\/\/ got it\n\t\t\t\t\t\tclose(found)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase err, ok := <-w.Errors:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}()\n\n\terr = w.Add(xLockParent)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := os.Stat(f); os.IsNotExist(err) {\n\t\tlog.Printf(\"Waiting on %s\", f)\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\treturn ErrNoX\n\t\tcase <-found:\n\t\t\treturn nil\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\n\/\/ NewRenderer creates a new GTK based rendering context\nfunc NewRenderer() (*Renderer, error) {\n\tr := Renderer{}\n\n\tif err := r.waitForX(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.start()\n\n\treturn &r, nil\n}\n\n\/\/ Ensure that the GTK+ main loop has started. If it has already been\nfunc (r *Renderer) start() {\n\tgtkOnce.Do(func() {\n\t\tgtk.Init(nil)\n\t\tgo func() {\n\t\t\truntime.LockOSThread()\n\t\t\tgtk.Main()\n\t\t}()\n\t})\n}\n\n\/\/ NewView creates a new Webkit view\nfunc (r *Renderer) NewView(appName, appVersion string, autoLoadImages, consoleStdout bool) *View {\n\tc := make(chan *View, 1)\n\n\tr.Lock()\n\n\tglib.IdleAdd(func() bool {\n\t\twebView := webkit2.NewWebView()\n\t\tsettings := webView.Settings()\n\t\tsettings.SetAutoLoadImages(autoLoadImages)\n\t\tsettings.SetEnableWriteConsoleMessagesToStdout(consoleStdout)\n\t\tsettings.SetUserAgentWithApplicationDetails(appName, appVersion)\n\t\tv := &View{WebView: webView}\n\t\tloadChangedHandler, _ := webView.Connect(\"load-changed\", func(_ *glib.Object, loadEvent webkit2.LoadEvent) {\n\t\t\tt := time.Now()\n\t\t\tswitch loadEvent {\n\t\t\tcase webkit2.LoadStarted:\n\t\t\t\tv.loadStarted = &t\n\t\t\tcase webkit2.LoadFinished:\n\t\t\t\tv.loadFinished = &t\n\t\t\t\tv.load <- struct{}{}\n\t\t\t}\n\t\t})\n\t\twebView.Connect(\"load-failed\", func() {\n\t\t\tv.lastLoadErr = ErrLoadFailed\n\t\t\twebView.HandlerDisconnect(loadChangedHandler)\n\t\t})\n\t\tc <- v\n\t\treturn false\n\t})\n\n\tr.Unlock()\n\n\treturn <-c\n}\n<|endoftext|>"}
{"text":"<commit_before>package ale\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/oxtoacart\/bpool\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ BufPoolSize is the size of the BufferPool.\nvar BufPoolSize = 32\n\n\/\/ BufPoolAlloc is the maximum size of each buffer.\nvar BufPoolAlloc = 10 * 1024\n\nvar bufpool *bpool.SizedBufferPool\n\nfunc initBufPool() {\n\tbufpool = bpool.NewSizedBufferPool(BufPoolSize, BufPoolAlloc)\n}\n\nfunc getBuf() *bytes.Buffer {\n\tif bufpool == nil {\n\t\tinitBufPool()\n\t}\n\treturn bufpool.Get()\n}\n\nfunc putBuf(b *bytes.Buffer) {\n\tbufpool.Put(b)\n}\n\nfunc (s *Server) template(name string) (*template.Template, error) {\n\tif s.TemplateDir == \"\" {\n\t\treturn nil, errors.Errorf(\"No TemplateDir specified\")\n\t}\n\ttmplFile := s.TemplateDir + \"\/\" + name\n\tif _, err := os.Stat(tmplFile); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Unable to read requested template `%s'\", tmplFile)\n\t}\n\tt := template.New(\"\")\n\tif s.View.FuncMap != nil {\n\t\tt = t.Funcs(s.View.FuncMap)\n\t}\n\t_, err := t.ParseFiles(tmplFile)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Unable to parse template '%s'\", tmplFile)\n\t}\n\tlibPath := s.TemplateDir + \"\/lib\"\n\tif _, err := os.Stat(libPath); err != nil && !os.IsNotExist(err) {\n\t\treturn nil, errors.Wrapf(err, \"Unable to read templates lib `%s`\", libPath)\n\t} else if err == nil {\n\t\t_, err := t.ParseGlob(libPath + \"\/*\")\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Error parsing templates in '%s'\", libPath)\n\t\t}\n\t}\n\treturn t, nil\n}\n\n\/\/ Render renders the page\nfunc (s *Server) Render(w ResponseWriter, r *http.Request) {\n\tif w.Written() {\n\t\treturn\n\t}\n\tif err := s.renderTemplate(w, r); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"Error executing template: %s\\n\", err)\n\t}\n}\n\nfunc (s *Server) renderTemplate(w ResponseWriter, r *http.Request) error {\n\tview := GetView(r)\n\tviewName := view.View\n\tif viewName == \"\" {\n\t\treturn errors.Errorf(\"No view defined for %s\", r.URL.Path)\n\t}\n\ttmplName := view.Template\n\tif tmplName == \"\" {\n\t\ttmplName = viewName\n\t}\n\n\tt, err := s.template(viewName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif view.FuncMap != nil {\n\t\tt.Funcs(view.FuncMap)\n\t}\n\tbuf := getBuf()\n\tdefer putBuf(buf)\n\tif err := t.ExecuteTemplate(buf, tmplName, GetStash(r)); err != nil {\n\t\treturn err\n\t}\n\tw.Header().Set(\"Content-Type\", \"text\/html; charset=utf-8\")\n\tbuf.WriteTo(w)\n\treturn nil\n}\n<commit_msg>Set content type for errors, so gzip doesn't break stuff<commit_after>package ale\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/oxtoacart\/bpool\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ BufPoolSize is the size of the BufferPool.\nvar BufPoolSize = 32\n\n\/\/ BufPoolAlloc is the maximum size of each buffer.\nvar BufPoolAlloc = 10 * 1024\n\nvar bufpool *bpool.SizedBufferPool\n\nfunc initBufPool() {\n\tbufpool = bpool.NewSizedBufferPool(BufPoolSize, BufPoolAlloc)\n}\n\nfunc getBuf() *bytes.Buffer {\n\tif bufpool == nil {\n\t\tinitBufPool()\n\t}\n\treturn bufpool.Get()\n}\n\nfunc putBuf(b *bytes.Buffer) {\n\tbufpool.Put(b)\n}\n\nfunc (s *Server) template(name string) (*template.Template, error) {\n\tif s.TemplateDir == \"\" {\n\t\treturn nil, errors.Errorf(\"No TemplateDir specified\")\n\t}\n\ttmplFile := s.TemplateDir + \"\/\" + name\n\tif _, err := os.Stat(tmplFile); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Unable to read requested template `%s'\", tmplFile)\n\t}\n\tt := template.New(\"\")\n\tif s.View.FuncMap != nil {\n\t\tt = t.Funcs(s.View.FuncMap)\n\t}\n\t_, err := t.ParseFiles(tmplFile)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"Unable to parse template '%s'\", tmplFile)\n\t}\n\tlibPath := s.TemplateDir + \"\/lib\"\n\tif _, err := os.Stat(libPath); err != nil && !os.IsNotExist(err) {\n\t\treturn nil, errors.Wrapf(err, \"Unable to read templates lib `%s`\", libPath)\n\t} else if err == nil {\n\t\t_, err := t.ParseGlob(libPath + \"\/*\")\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"Error parsing templates in '%s'\", libPath)\n\t\t}\n\t}\n\treturn t, nil\n}\n\n\/\/ Render renders the page\nfunc (s *Server) Render(w ResponseWriter, r *http.Request) {\n\tif w.Written() {\n\t\treturn\n\t}\n\tif err := s.renderTemplate(w, r); err != nil {\n\t\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=utf-8\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"Error executing template: %s\\n\", err)\n\t}\n}\n\nfunc (s *Server) renderTemplate(w ResponseWriter, r *http.Request) error {\n\tview := GetView(r)\n\tviewName := view.View\n\tif viewName == \"\" {\n\t\treturn errors.Errorf(\"No view defined for %s\", r.URL.Path)\n\t}\n\ttmplName := view.Template\n\tif tmplName == \"\" {\n\t\ttmplName = viewName\n\t}\n\n\tt, err := s.template(viewName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif view.FuncMap != nil {\n\t\tt.Funcs(view.FuncMap)\n\t}\n\tbuf := getBuf()\n\tdefer putBuf(buf)\n\tif err := t.ExecuteTemplate(buf, tmplName, GetStash(r)); err != nil {\n\t\treturn err\n\t}\n\tw.Header().Set(\"Content-Type\", \"text\/html; charset=utf-8\")\n\tbuf.WriteTo(w)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"testing\"\n)\n\nvar sut pokenv\n\nfunc init() {\n\tsut = pokenv{\n\t\tenvironment: make(map[string][]string),\n\t\tregistry:    mock,\n\t}\n\tlog.SetOutput(ioutil.Discard)\n}\n\nfunc TestProcessLineValue(t *testing.T) {\n\tsut.currentVariable = \"TESTING\"\n\tsut.addCurrent(\"\")\n\n\tsut.processLine(\" value # comment\")\n\tassertEquals(t, \"value\", sut.environment[sut.currentVariable][0])\n}\n\nfunc TestProcessLineSection(t *testing.T) {\n\tsut.processLine(\"[ A SECTION ]\")\n\tassertEquals(t, \"ASECTION\", sut.currentVariable)\n}\n\nfunc TestProcessTestFile(t *testing.T) {\n\tsut.importEnv(PATH_MACHINE, `data\/setvar.txt`)\n\tassertEquals(t, \"valueline1\", mock.env[\"POKE_SECTION\"])\n}\n\nfunc assertEquals(t *testing.T, expected string, actual string) {\n\tif actual != expected {\n\t\tt.Errorf(\"Expected: %q, was: %q\", expected, actual)\n\t}\n}\n\nfunc TestCheckPath(t *testing.T) {\n\tpaths := []string{\n\t\t`c:\\Windows`,\n\t\t`c:\\Windows\\system32`,\n\t\t`%windir%`,\n\t\t`%windir%\\system32`,\n\t\t`.`,\n\t}\n\tfor _, path := range paths {\n\t\tif isPathInvalid(path) {\n\t\t\tt.Errorf(\"Invalid path:\", path)\n\t\t}\n\t}\n}\n<commit_msg>skip test on non-windows os<commit_after>package main\n\nimport (\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nvar sut pokenv\n\nfunc init() {\n\tsut = pokenv{\n\t\tenvironment: make(map[string][]string),\n\t\tregistry:    mock,\n\t}\n\tlog.SetOutput(ioutil.Discard)\n}\n\nfunc TestProcessLineValue(t *testing.T) {\n\tsut.currentVariable = \"TESTING\"\n\tsut.addCurrent(\"\")\n\n\tsut.processLine(\" value # comment\")\n\tassertEquals(t, \"value\", sut.environment[sut.currentVariable][0])\n}\n\nfunc TestProcessLineSection(t *testing.T) {\n\tsut.processLine(\"[ A SECTION ]\")\n\tassertEquals(t, \"ASECTION\", sut.currentVariable)\n}\n\nfunc TestProcessTestFile(t *testing.T) {\n\tsut.importEnv(PATH_MACHINE, `data\/setvar.txt`)\n\tassertEquals(t, \"valueline1\", mock.env[\"POKE_SECTION\"])\n}\n\nfunc assertEquals(t *testing.T, expected string, actual string) {\n\tif actual != expected {\n\t\tt.Errorf(\"Expected: %q, was: %q\", expected, actual)\n\t}\n}\n\nfunc TestCheckPath(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tpaths := []string{\n\t\t\t`c:\\Windows`,\n\t\t\t`c:\\Windows\\system32`,\n\t\t\t`%windir%`,\n\t\t\t`%windir%\\system32`,\n\t\t\t`.`,\n\t\t}\n\t\tfor _, path := range paths {\n\t\t\tif isPathInvalid(path) {\n\t\t\t\tt.Errorf(\"Invalid path:\", path)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tt.Skip(\"Cannot test windows paths\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package daemon\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"time\"\n\n\tlog \"github.com\/socketplane\/socketplane\/Godeps\/_workspace\/src\/github.com\/Sirupsen\/logrus\"\n\t\"github.com\/socketplane\/socketplane\/Godeps\/_workspace\/src\/github.com\/codegangsta\/cli\"\n\t\"github.com\/socketplane\/socketplane\/datastore\"\n)\n\ntype Daemon struct {\n\tConfiguration *Configuration\n\tConnections   map[string]*Connection\n\tcC            chan *ConnectionContext\n}\n\nfunc NewDaemon() *Daemon {\n\treturn &Daemon{\n\t\t&Configuration{},\n\t\tmap[string]*Connection{},\n\t\tmake(chan *ConnectionContext),\n\t}\n}\n\nfunc (d *Daemon) Run(ctx *cli.Context) {\n\tif ctx.Bool(\"debug\") {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\tbootstrapNode := ctx.Bool(\"bootstrap\")\n\tserialChan := make(chan bool)\n\tbindChan = make(chan string)\n\n\tvar bindInterface string\n\tgo ServeAPI(d)\n\n\tgo func() {\n\t\tif ctx.String(\"iface\") != \"auto\" {\n\t\t\tbindInterface = ctx.String(\"iface\")\n\t\t} else {\n\t\t\tintf := identifyInterfaceToBind()\n\t\t\tif intf != nil {\n\t\t\t\tbindInterface = intf.Name\n\t\t\t}\n\t\t}\n\t\tif bindInterface != \"\" {\n\t\t\tlog.Printf(\"Binding to %s\", bindInterface)\n\t\t} else {\n\t\t\tlog.Errorf(\"Unable to identify any Interface to Bind to. Going with Defaults\")\n\t\t}\n\t\tBonjour(bindInterface)\n\t\tif clusterListener == \"\" {\n\t\t\tbindChan <- bindInterface\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\tbindInterface = <-bindChan\n\t\t\tif bindInterface == clusterListener {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tonce := true\n\t\t\tif clusterListener != \"\" {\n\t\t\t\tonce = false\n\t\t\t\tdatastore.Leave()\n\t\t\t\ttime.Sleep(time.Second * 5)\n\t\t\t}\n\t\t\tclusterListener = bindInterface\n\t\t\tdatastore.Init(clusterListener, bootstrapNode)\n\t\t\tif !bootstrapNode && once {\n\t\t\t\tserialChan <- true\n\t\t\t}\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tif !bootstrapNode {\n\t\t\tlog.Printf(\"Non-Bootstrap node waiting on peer discovery\")\n\t\t\t<-serialChan\n\t\t\tlog.Printf(\"Non-Bootstrap node admitted into cluster\")\n\t\t}\n\t\terr := CreateBridge()\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error)\n\t\t}\n\t\td.populateConnections()\n\t\t_, err = CreateDefaultNetwork()\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error)\n\t\t}\n\t}()\n\n\tgo RunConnectionHandler(d)\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\tfor _ = range c {\n\t\t\tos.Exit(0)\n\t\t}\n\t}()\n\tselect {}\n}\n\nvar bindChan chan string\nvar clusterListener string\n\nfunc ConfigureClusterListenerPort(listen string) error {\n\tiface, err := net.InterfaceByName(listen)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif iface.Flags&net.FlagUp == 0 {\n\t\treturn errors.New(\"Interface is down\")\n\t}\n\tbindChan <- listen\n\treturn nil\n}\n\nfunc identifyInterfaceToBind() *net.Interface {\n\t\/\/ If the user isnt binding an interface using --iface option and let the daemon to\n\t\/\/ identify the interface, the daemon will try its best to identify the best interface\n\t\/\/ for the job.\n\t\/\/ In a few auto-install \/ zerotouch config scenarios, eligible interfaces may\n\t\/\/ be identified after the socketplane daemon is up and running.\n\n\tfor {\n\t\tvar intf *net.Interface\n\t\tif clusterListener != \"\" {\n\t\t\tintf, _ = net.InterfaceByName(clusterListener)\n\t\t} else {\n\t\t\tintf = InterfaceToBind()\n\t\t}\n\t\tif intf != nil {\n\t\t\treturn intf\n\t\t}\n\t\ttime.Sleep(time.Second * 5)\n\t\tlog.Infof(\"Identifying interface to bind ... Use --iface option for static binding\")\n\t}\n\treturn nil\n}\n\nfunc (d *Daemon) populateConnections() {\n\tfor key, val := range ContextCache {\n\t\tconnection := &Connection{}\n\t\terr := json.Unmarshal([]byte(val), connection)\n\t\tif err == nil {\n\t\t\td.Connections[key] = connection\n\t\t}\n\t}\n}\n<commit_msg>Resolving a consul flap issue introduced by recent branch merge<commit_after>package daemon\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"time\"\n\n\tlog \"github.com\/socketplane\/socketplane\/Godeps\/_workspace\/src\/github.com\/Sirupsen\/logrus\"\n\t\"github.com\/socketplane\/socketplane\/Godeps\/_workspace\/src\/github.com\/codegangsta\/cli\"\n\t\"github.com\/socketplane\/socketplane\/datastore\"\n)\n\ntype Daemon struct {\n\tConfiguration *Configuration\n\tConnections   map[string]*Connection\n\tcC            chan *ConnectionContext\n}\n\nfunc NewDaemon() *Daemon {\n\treturn &Daemon{\n\t\t&Configuration{},\n\t\tmap[string]*Connection{},\n\t\tmake(chan *ConnectionContext),\n\t}\n}\n\nfunc (d *Daemon) Run(ctx *cli.Context) {\n\tif ctx.Bool(\"debug\") {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\tbootstrapNode := ctx.Bool(\"bootstrap\")\n\tserialChan := make(chan bool)\n\n\tgo ServeAPI(d)\n\tgo func() {\n\t\tvar bindInterface string\n\t\tif ctx.String(\"iface\") != \"auto\" {\n\t\t\tbindInterface = ctx.String(\"iface\")\n\t\t} else {\n\t\t\tintf := identifyInterfaceToBind()\n\t\t\tif intf != nil {\n\t\t\t\tbindInterface = intf.Name\n\t\t\t}\n\t\t}\n\t\tif bindInterface != \"\" {\n\t\t\tlog.Printf(\"Binding to %s\", bindInterface)\n\t\t} else {\n\t\t\tlog.Errorf(\"Unable to identify any Interface to Bind to. Going with Defaults\")\n\t\t}\n\t\tdatastore.Init(bindInterface, bootstrapNode)\n\t\tBonjour(bindInterface)\n\t\tif !bootstrapNode {\n\t\t\tserialChan <- true\n\t\t}\n\t}()\n\n\t\/*\n\t\tTODO : Enable this while addressing #69\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tbindInterface = <-bindChan\n\t\t\t\tif bindInterface == clusterListener {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tonce := true\n\t\t\t\tif clusterListener != \"\" {\n\t\t\t\t\tonce = false\n\t\t\t\t\tdatastore.Leave()\n\t\t\t\t\ttime.Sleep(time.Second * 5)\n\t\t\t\t}\n\t\t\t\tclusterListener = bindInterface\n\t\t\t\tdatastore.Init(clusterListener, bootstrapNode)\n\t\t\t\tif !bootstrapNode && once {\n\t\t\t\t\tserialChan <- true\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t*\/\n\tgo func() {\n\t\tif !bootstrapNode {\n\t\t\tlog.Printf(\"Non-Bootstrap node waiting on peer discovery\")\n\t\t\t<-serialChan\n\t\t\tlog.Printf(\"Non-Bootstrap node admitted into cluster\")\n\t\t}\n\t\terr := CreateBridge()\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error)\n\t\t}\n\t\td.populateConnections()\n\t\t_, err = CreateDefaultNetwork()\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error)\n\t\t}\n\t}()\n\n\tgo RunConnectionHandler(d)\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\tfor _ = range c {\n\t\t\tos.Exit(0)\n\t\t}\n\t}()\n\tselect {}\n}\n\nvar bindChan chan string\nvar clusterListener string\n\nfunc ConfigureClusterListenerPort(listen string) error {\n\tiface, err := net.InterfaceByName(listen)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif iface.Flags&net.FlagUp == 0 {\n\t\treturn errors.New(\"Interface is down\")\n\t}\n\t\/\/ TODO : enable this while addressing #69\n\t\/\/ bindChan <- listen\n\treturn nil\n}\n\nfunc identifyInterfaceToBind() *net.Interface {\n\t\/\/ If the user isnt binding an interface using --iface option and let the daemon to\n\t\/\/ identify the interface, the daemon will try its best to identify the best interface\n\t\/\/ for the job.\n\t\/\/ In a few auto-install \/ zerotouch config scenarios, eligible interfaces may\n\t\/\/ be identified after the socketplane daemon is up and running.\n\n\tfor {\n\t\tvar intf *net.Interface\n\t\tif clusterListener != \"\" {\n\t\t\tintf, _ = net.InterfaceByName(clusterListener)\n\t\t} else {\n\t\t\tintf = InterfaceToBind()\n\t\t}\n\t\tif intf != nil {\n\t\t\treturn intf\n\t\t}\n\t\ttime.Sleep(time.Second * 5)\n\t\tlog.Infof(\"Identifying interface to bind ... Use --iface option for static binding\")\n\t}\n\treturn nil\n}\n\nfunc (d *Daemon) populateConnections() {\n\tfor key, val := range ContextCache {\n\t\tconnection := &Connection{}\n\t\terr := json.Unmarshal([]byte(val), connection)\n\t\tif err == nil {\n\t\t\td.Connections[key] = connection\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package emil\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"time\"\n)\n\ntype positionKey string\n\n\/\/ PositionEntry is an entry in the PositionDb\ntype PositionEntry struct {\n\tPosition      *position\n\tDtm           int\n\tPrevPositions map[positionKey]*Move\n\tNextPositions map[positionKey]*Move\n}\n\n\/\/ NewPositionEntry ceates a new *PositionEntry\nfunc NewPositionEntry(p *position) *PositionEntry {\n\treturn &PositionEntry{\n\t\tPosition:      p,\n\t\tDtm:           initial,\n\t\tPrevPositions: make(map[positionKey]*Move),\n\t\tNextPositions: make(map[positionKey]*Move)}\n}\n\nfunc (entry *PositionEntry) addMoveToNextPosition(next *position, m *Move) {\n}\n\n\/\/ PositionDb to query for mate in 1,2, etc.\ntype PositionDb struct {\n\tPositions map[positionKey]*PositionEntry\n}\n\nfunc (db *PositionDb) addPosition(p *position) {\n\tif _, ok := db.Positions[p.key()]; ok {\n\t\tpanic(\"key exsists in db \" + p.key())\n\t}\n\tentry := NewPositionEntry(p)\n\tdb.retrogradeAnalysisStep0(entry)\n\tdb.Positions[p.key()] = entry\n}\n\nfunc (db *PositionDb) AddPrevPositions() {\n\tfor key, entry := range db.Positions {\n\t\tfor nextKey, moveToNext := range entry.NextPositions {\n\t\t\tnextPosition := PositionFromKey(string(nextKey))\n\t\t\tnextEntry, ok := db.Positions[nextPosition.key()]\n\t\t\tif ok {\n\t\t\t\tnextEntry.PrevPositions[key] = moveToNext\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ generate all moves\nfunc (db *PositionDb) retrogradeAnalysisStep0(entry *PositionEntry) {\n\tmoves := GenerateMoves(entry.Position)\n\tother := otherPlayer(entry.Position.player)\n\tfor _, move := range moves {\n\t\tnextBoard := entry.Position.board.DoMove(move)\n\t\tnextPosition := NewPosition(nextBoard, other)\n\t\tentry.NextPositions[nextPosition.key()] = move\n\t}\n}\n\n\/\/ NewPositionDB creates a new *PositionDB\nfunc NewPositionDB() *PositionDb {\n\treturn &PositionDb{\n\t\tPositions: make(map[positionKey]*PositionEntry)}\n}\n\nfunc (db *PositionDb) FillWithKRKPositions() {\n\tvar err error\n\n\tfor wk := A1; wk <= H8; wk++ {\n\t\t\/\/for wk := E3; wk <= E3; wk++ {\n\t\tif DEBUG {\n\t\t\tfmt.Printf(\"White king on %s\\n\", BoardSquares[wk])\n\t\t}\n\t\tfor wr := A1; wr <= H8; wr++ {\n\t\t\tfor bk := A1; bk <= H8; bk++ {\n\n\t\t\t\tboard := NewBoard()\n\n\t\t\t\terr = board.Setup(WhiteKing, wk)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\terr = board.Setup(WhiteRock, wr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\terr = board.Setup(BlackKing, bk)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\terr = board.kingsToClose()\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tdb.addPosition(NewPosition(board, WHITE))\n\t\t\t\tdb.addPosition(NewPosition(board, BLACK))\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ SaveEndGameDb saves the an end game DB for KRK to file\nfunc (db *PositionDb) SavePositionDb(file string) error {\n\tfmt.Println(\"WriteDataToFile: \", file)\n\n\tstart := time.Now()\n\tfmt.Printf(\"json.MarshalIndent\\n\")\n\tb, err := json.MarshalIndent(db, \"\", \"  \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tend := time.Now()\n\tfmt.Printf(\"json.MarshalIndent %v\\n\", end.Sub(start))\n\n\tstart = time.Now()\n\tfmt.Printf(\"ioutil.WriteFile\\n\")\n\terr = ioutil.WriteFile(file, b, 0666)\n\tend = time.Now()\n\tfmt.Printf(\"ioutil.WriteFile %v, error=%v\\n\", end.Sub(start), err)\n\treturn err\n}\n<commit_msg>LoadPositionDb<commit_after>package emil\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"time\"\n)\n\ntype positionKey string\n\n\/\/ PositionEntry is an entry in the PositionDb\ntype PositionEntry struct {\n\tPosition      *position\n\tDtm           int\n\tPrevPositions map[positionKey]*Move\n\tNextPositions map[positionKey]*Move\n}\n\n\/\/ NewPositionEntry ceates a new *PositionEntry\nfunc NewPositionEntry(p *position) *PositionEntry {\n\treturn &PositionEntry{\n\t\tPosition:      p,\n\t\tDtm:           initial,\n\t\tPrevPositions: make(map[positionKey]*Move),\n\t\tNextPositions: make(map[positionKey]*Move)}\n}\n\nfunc (entry *PositionEntry) addMoveToNextPosition(next *position, m *Move) {\n}\n\n\/\/ PositionDb to query for mate in 1,2, etc.\ntype PositionDb struct {\n\tPositions map[positionKey]*PositionEntry\n}\n\nfunc (db *PositionDb) addPosition(p *position) {\n\tif _, ok := db.Positions[p.key()]; ok {\n\t\tpanic(\"key exsists in db \" + p.key())\n\t}\n\tentry := NewPositionEntry(p)\n\tdb.retrogradeAnalysisStep0(entry)\n\tdb.Positions[p.key()] = entry\n}\n\nfunc (db *PositionDb) AddPrevPositions() {\n\tfor key, entry := range db.Positions {\n\t\tfor nextKey, moveToNext := range entry.NextPositions {\n\t\t\tnextPosition := PositionFromKey(string(nextKey))\n\t\t\tnextEntry, ok := db.Positions[nextPosition.key()]\n\t\t\tif ok {\n\t\t\t\tnextEntry.PrevPositions[key] = moveToNext\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ generate all moves\nfunc (db *PositionDb) retrogradeAnalysisStep0(entry *PositionEntry) {\n\tmoves := GenerateMoves(entry.Position)\n\tother := otherPlayer(entry.Position.player)\n\tfor _, move := range moves {\n\t\tnextBoard := entry.Position.board.DoMove(move)\n\t\tnextPosition := NewPosition(nextBoard, other)\n\t\tentry.NextPositions[nextPosition.key()] = move\n\t}\n}\n\n\/\/ NewPositionDB creates a new *PositionDB\nfunc NewPositionDB() *PositionDb {\n\treturn &PositionDb{\n\t\tPositions: make(map[positionKey]*PositionEntry)}\n}\n\nfunc (db *PositionDb) FillWithKRKPositions() {\n\tvar err error\n\n\tfor wk := A1; wk <= H8; wk++ {\n\t\t\/\/for wk := E3; wk <= E3; wk++ {\n\t\tif DEBUG {\n\t\t\tfmt.Printf(\"White king on %s\\n\", BoardSquares[wk])\n\t\t}\n\t\tfor wr := A1; wr <= H8; wr++ {\n\t\t\tfor bk := A1; bk <= H8; bk++ {\n\n\t\t\t\tboard := NewBoard()\n\n\t\t\t\terr = board.Setup(WhiteKing, wk)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\terr = board.Setup(WhiteRock, wr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\terr = board.Setup(BlackKing, bk)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\terr = board.kingsToClose()\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tdb.addPosition(NewPosition(board, WHITE))\n\t\t\t\tdb.addPosition(NewPosition(board, BLACK))\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ SaveEndGameDb saves the an end game DB for KRK to file\nfunc (db *PositionDb) SavePositionDb(file string) error {\n\tfmt.Println(\"WriteDataToFile: \", file)\n\n\tstart := time.Now()\n\tfmt.Printf(\"json.MarshalIndent\\n\")\n\tb, err := json.MarshalIndent(db, \"\", \"  \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tend := time.Now()\n\tfmt.Printf(\"json.MarshalIndent %v\\n\", end.Sub(start))\n\n\tstart = time.Now()\n\tfmt.Printf(\"ioutil.WriteFile\\n\")\n\terr = ioutil.WriteFile(file, b, 0666)\n\tend = time.Now()\n\tfmt.Printf(\"ioutil.WriteFile %v, error=%v\\n\", end.Sub(start), err)\n\treturn err\n}\nfunc LoadPositionDb(file string) (db *PositionDb, err error) {\n\tfmt.Println(\"LoadDataFromFile: \", file)\n\n\tstart := time.Now()\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn db, err\n\t}\n\tend := time.Now()\n\tfmt.Printf(\"ioutil.ReadFile %v,b=%d, error=%v\\n\", end.Sub(start), len(b), err)\n\n\tdata := NewPositionDB()\n\tstart = time.Now()\n\terr = json.Unmarshal(b, data)\n\tif err != nil {\n\t\treturn db, err\n\t}\n\tend = time.Now()\n\tfmt.Printf(\"json.Unmarshal%v\\n\", end.Sub(start))\n\treturn data, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/mackerelio\/checkers\"\n)\n\nvar opts struct {\n\tStateDir        string  `short:\"s\" long:\"state-dir\" default:\"\/var\/mackerel-cache\/check-log\" value-name:\"DIR\" description:\"Dir to keep state files under\"`\n\tLogFile         string  `short:\"f\" long:\"log-file\" value-name:\"FILE\" description:\"Path to log file\"`\n\tPattern         string  `short:\"q\" long:\"pattern\" required:\"true\" value-name:\"PAT\" description:\"Pattern to search for\"`\n\tExclude         string  `short:\"E\" long:\"exclude\" value-name:\"PAT\" description:\"Pattern to exclude from matching\"`\n\tWarnOver        int64   `short:\"w\" long:\"warning-over\" default:\"0\" description:\"Trigger a warning if matched lines is over a number\"`\n\tCritOver        int64   `short:\"c\" long:\"critical-over\" default:\"0\" description:\"Trigger a critical if matched lines is over a number\"`\n\tWarnLevel       float64 `long:\"warning-level\" value-name:\"N\" description:\"Warning level if pattern has a group\"`\n\tCritLevel       float64 `long:\"critical-level\" value-name:\"N\" description:\"Critical level if pattern has a group\"`\n\tCaseInsensitive bool    `short:\"i\" long:\"icase\" description:\"Run a case insensitive match\"`\n\tFilePattern     string  `short:\"F\" long:\"filepattern\" value-name:\"FILE\" description:\"Check a pattern of files, instead of one file\"`\n\tReturnContent   bool    `short:\"r\" long:\"return\" description:\"Return matched line\"`\n}\n\nfunc main() {\n\tckr := run(os.Args[1:])\n\tckr.Name = \"LOG\"\n\tckr.Exit()\n}\n\nfunc regCompileWithCase(ptn string, caseInsensitive bool) (*regexp.Regexp, error) {\n\tif caseInsensitive {\n\t\tptn = strings.ToLower(ptn)\n\t}\n\treturn regexp.Compile(ptn)\n}\n\nfunc run(args []string) *checkers.Checker {\n\t_, err := flags.ParseArgs(&opts, args)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tif opts.LogFile == \"\" && opts.FilePattern == \"\" {\n\t\treturn checkers.Unknown(\"No log file specified\")\n\t}\n\n\tpatternReg, err := regCompileWithCase(opts.Pattern, opts.CaseInsensitive)\n\tif err != nil {\n\t\treturn checkers.Unknown(\"pattern is invalid\")\n\t}\n\n\tvar excludeReg *regexp.Regexp\n\tif opts.Exclude != \"\" {\n\t\texcludeReg, err = regCompileWithCase(opts.Exclude, opts.CaseInsensitive)\n\t\tif err != nil {\n\t\t\treturn checkers.Unknown(\"exclude pattern is invalid\")\n\t\t}\n\t}\n\n\tfileList := []string{}\n\tif opts.LogFile != \"\" {\n\t\tfileList = append(fileList, opts.LogFile)\n\t}\n\n\tif opts.FilePattern != \"\" {\n\t\tdirStr := filepath.Dir(opts.FilePattern)\n\t\tfilePat := filepath.Base(opts.FilePattern)\n\t\treg, err := regCompileWithCase(filePat, opts.CaseInsensitive)\n\t\tif err != nil {\n\t\t\treturn checkers.Unknown(\"file-pattern is invalid\")\n\t\t}\n\n\t\tfileInfos, err := ioutil.ReadDir(dirStr)\n\t\tif err != nil {\n\t\t\treturn checkers.Unknown(\"cannot read the Directory:\" + err.Error())\n\t\t}\n\n\t\tfor _, fileInfo := range fileInfos {\n\t\t\tif fileInfo.IsDir() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfname := fileInfo.Name()\n\t\t\tif opts.CaseInsensitive {\n\t\t\t\tfname = strings.ToLower(fname)\n\t\t\t}\n\t\t\tif reg.MatchString(fname) {\n\t\t\t\tfileList = append(fileList, dirStr+string(filepath.Separator)+fileInfo.Name())\n\t\t\t}\n\t\t}\n\t}\n\n\twarnNum := int64(0)\n\tcritNum := int64(0)\n\terrorOverall := \"\"\n\n\tfor _, f := range fileList {\n\t\tw, c, errLines, err := searchLog(f, patternReg, excludeReg)\n\t\tif err != nil {\n\t\t\treturn checkers.Unknown(err.Error())\n\t\t}\n\t\twarnNum += w\n\t\tcritNum += c\n\t\tif opts.ReturnContent {\n\t\t\terrorOverall += errLines\n\t\t}\n\t}\n\n\tcheckSt := checkers.OK\n\tif warnNum > opts.WarnOver {\n\t\tcheckSt = checkers.WARNING\n\t}\n\tif critNum > opts.CritOver {\n\t\tcheckSt = checkers.CRITICAL\n\t}\n\tmsg := fmt.Sprintf(\"%d warnings, %d criticals for pattern %s. %s\", warnNum, critNum, opts.Pattern, errorOverall)\n\treturn checkers.NewChecker(checkSt, msg)\n}\n\nfunc searchLog(logFile string, patternReg, excludeReg *regexp.Regexp) (int64, int64, string, error) {\n\tstateFile := getStateFile(opts.StateDir, logFile)\n\tskipBytes, err := getBytesToSkip(stateFile)\n\tif err != nil {\n\t\treturn 0, 0, \"\", err\n\t}\n\tf, err := os.Open(logFile)\n\tif err != nil {\n\t\treturn 0, 0, \"\", err\n\t}\n\tdefer f.Close()\n\n\tstat, err := f.Stat()\n\tif err != nil {\n\t\treturn 0, 0, \"\", err\n\t}\n\n\treadBytes := int64(0)\n\tif skipBytes > 0 && stat.Size() >= skipBytes {\n\t\tf.Seek(skipBytes, 0)\n\t\treadBytes = skipBytes\n\t}\n\twarnNum := int64(0)\n\tcritNum := int64(0)\n\terrLines := \"\"\n\tr := bufio.NewReader(f)\n\n\tfor {\n\t\tlineBytes, err := r.ReadBytes('\\n')\n\t\treadBytes += int64(len(lineBytes))\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn 0, 0, \"\", err\n\t\t}\n\t\tline := strings.Trim(string(lineBytes), \"\\r\\n\")\n\t\tcheckLine := line\n\t\tif opts.CaseInsensitive {\n\t\t\tcheckLine = strings.ToLower(checkLine)\n\t\t}\n\t\tif patternReg.MatchString(checkLine) && (excludeReg == nil || !excludeReg.MatchString(checkLine)) {\n\t\t\twarnNum++\n\t\t\tcritNum++\n\t\t\terrLines += \"\\n\" + line\n\t\t}\n\t}\n\terr = writeBytesToSkip(stateFile, readBytes)\n\treturn warnNum, critNum, errLines, nil\n}\n\nvar stateRe = regexp.MustCompile(`^([A-Z]):[\/\\\\]`)\n\nfunc getStateFile(stateDir, f string) string {\n\treturn filepath.Join(stateDir, stateRe.ReplaceAllString(f, `$1`+string(filepath.Separator)))\n}\n\nfunc getBytesToSkip(f string) (int64, error) {\n\t_, err := os.Stat(f)\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\tb, err := ioutil.ReadFile(f)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ti, err := strconv.Atoi(strings.Trim(string(b), \" \\r\\n\"))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn int64(i), nil\n}\n\nfunc writeBytesToSkip(f string, num int64) error {\n\terr := os.MkdirAll(filepath.Dir(f), 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(f, []byte(fmt.Sprintf(\"%d\", num)), 0755)\n}\n<commit_msg>support captured wanrning\/critical levels<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/mackerelio\/checkers\"\n)\n\nvar opts struct {\n\tStateDir        string  `short:\"s\" long:\"state-dir\" default:\"\/var\/mackerel-cache\/check-log\" value-name:\"DIR\" description:\"Dir to keep state files under\"`\n\tLogFile         string  `short:\"f\" long:\"log-file\" value-name:\"FILE\" description:\"Path to log file\"`\n\tPattern         string  `short:\"q\" long:\"pattern\" required:\"true\" value-name:\"PAT\" description:\"Pattern to search for\"`\n\tExclude         string  `short:\"E\" long:\"exclude\" value-name:\"PAT\" description:\"Pattern to exclude from matching\"`\n\tWarnOver        int64   `short:\"w\" long:\"warning-over\" description:\"Trigger a warning if matched lines is over a number\"`\n\tCritOver        int64   `short:\"c\" long:\"critical-over\" description:\"Trigger a critical if matched lines is over a number\"`\n\tWarnLevel       float64 `long:\"warning-level\" value-name:\"N\" description:\"Warning level if pattern has a group\"`\n\tCritLevel       float64 `long:\"critical-level\" value-name:\"N\" description:\"Critical level if pattern has a group\"`\n\tCaseInsensitive bool    `short:\"i\" long:\"icase\" description:\"Run a case insensitive match\"`\n\tFilePattern     string  `short:\"F\" long:\"filepattern\" value-name:\"FILE\" description:\"Check a pattern of files, instead of one file\"`\n\tReturnContent   bool    `short:\"r\" long:\"return\" description:\"Return matched line\"`\n}\n\nfunc main() {\n\tckr := run(os.Args[1:])\n\tckr.Name = \"LOG\"\n\tckr.Exit()\n}\n\nfunc regCompileWithCase(ptn string, caseInsensitive bool) (*regexp.Regexp, error) {\n\tif caseInsensitive {\n\t\tptn = strings.ToLower(ptn)\n\t}\n\treturn regexp.Compile(ptn)\n}\n\nfunc run(args []string) *checkers.Checker {\n\t_, err := flags.ParseArgs(&opts, args)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tif opts.LogFile == \"\" && opts.FilePattern == \"\" {\n\t\treturn checkers.Unknown(\"No log file specified\")\n\t}\n\n\tpatternReg, err := regCompileWithCase(opts.Pattern, opts.CaseInsensitive)\n\tif err != nil {\n\t\treturn checkers.Unknown(\"pattern is invalid\")\n\t}\n\n\tvar excludeReg *regexp.Regexp\n\tif opts.Exclude != \"\" {\n\t\texcludeReg, err = regCompileWithCase(opts.Exclude, opts.CaseInsensitive)\n\t\tif err != nil {\n\t\t\treturn checkers.Unknown(\"exclude pattern is invalid\")\n\t\t}\n\t}\n\n\tfileList := []string{}\n\tif opts.LogFile != \"\" {\n\t\tfileList = append(fileList, opts.LogFile)\n\t}\n\n\tif opts.FilePattern != \"\" {\n\t\tdirStr := filepath.Dir(opts.FilePattern)\n\t\tfilePat := filepath.Base(opts.FilePattern)\n\t\treg, err := regCompileWithCase(filePat, opts.CaseInsensitive)\n\t\tif err != nil {\n\t\t\treturn checkers.Unknown(\"file-pattern is invalid\")\n\t\t}\n\n\t\tfileInfos, err := ioutil.ReadDir(dirStr)\n\t\tif err != nil {\n\t\t\treturn checkers.Unknown(\"cannot read the Directory:\" + err.Error())\n\t\t}\n\n\t\tfor _, fileInfo := range fileInfos {\n\t\t\tif fileInfo.IsDir() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfname := fileInfo.Name()\n\t\t\tif opts.CaseInsensitive {\n\t\t\t\tfname = strings.ToLower(fname)\n\t\t\t}\n\t\t\tif reg.MatchString(fname) {\n\t\t\t\tfileList = append(fileList, dirStr+string(filepath.Separator)+fileInfo.Name())\n\t\t\t}\n\t\t}\n\t}\n\n\twarnNum := int64(0)\n\tcritNum := int64(0)\n\terrorOverall := \"\"\n\n\tfor _, f := range fileList {\n\t\tw, c, errLines, err := searchLog(f, patternReg, excludeReg)\n\t\tif err != nil {\n\t\t\treturn checkers.Unknown(err.Error())\n\t\t}\n\t\twarnNum += w\n\t\tcritNum += c\n\t\tif opts.ReturnContent {\n\t\t\terrorOverall += errLines\n\t\t}\n\t}\n\n\tcheckSt := checkers.OK\n\tif warnNum > opts.WarnOver {\n\t\tcheckSt = checkers.WARNING\n\t}\n\tif critNum > opts.CritOver {\n\t\tcheckSt = checkers.CRITICAL\n\t}\n\tmsg := fmt.Sprintf(\"%d warnings, %d criticals for pattern %s. %s\", warnNum, critNum, opts.Pattern, errorOverall)\n\treturn checkers.NewChecker(checkSt, msg)\n}\n\nfunc searchLog(logFile string, patternReg, excludeReg *regexp.Regexp) (int64, int64, string, error) {\n\tstateFile := getStateFile(opts.StateDir, logFile)\n\tskipBytes, err := getBytesToSkip(stateFile)\n\tif err != nil {\n\t\treturn 0, 0, \"\", err\n\t}\n\tf, err := os.Open(logFile)\n\tif err != nil {\n\t\treturn 0, 0, \"\", err\n\t}\n\tdefer f.Close()\n\n\tstat, err := f.Stat()\n\tif err != nil {\n\t\treturn 0, 0, \"\", err\n\t}\n\n\treadBytes := int64(0)\n\tif skipBytes > 0 && stat.Size() >= skipBytes {\n\t\tf.Seek(skipBytes, 0)\n\t\treadBytes = skipBytes\n\t}\n\twarnNum := int64(0)\n\tcritNum := int64(0)\n\terrLines := \"\"\n\tr := bufio.NewReader(f)\n\n\tfor {\n\t\tlineBytes, err := r.ReadBytes('\\n')\n\t\treadBytes += int64(len(lineBytes))\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn 0, 0, \"\", err\n\t\t}\n\t\tline := strings.Trim(string(lineBytes), \"\\r\\n\")\n\t\tcheckLine := line\n\t\tif opts.CaseInsensitive {\n\t\t\tcheckLine = strings.ToLower(checkLine)\n\t\t}\n\t\tif matches := patternReg.FindStringSubmatch(checkLine); len(matches) > 0 && (excludeReg == nil || !excludeReg.MatchString(checkLine)) {\n\t\t\tif len(matches) > 1 && (opts.WarnLevel > 0 || opts.CritLevel > 0) {\n\t\t\t\tlevel, err := strconv.ParseFloat(matches[1], 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\twarnNum++\n\t\t\t\t\tcritNum++\n\t\t\t\t\terrLines += \"\\n\" + line\n\t\t\t\t} else {\n\t\t\t\t\tlevelOver := false\n\t\t\t\t\tif level > opts.WarnLevel {\n\t\t\t\t\t\tlevelOver = true\n\t\t\t\t\t\twarnNum++\n\t\t\t\t\t}\n\t\t\t\t\tif level > opts.CritLevel {\n\t\t\t\t\t\tlevelOver = true\n\t\t\t\t\t\tcritNum++\n\t\t\t\t\t}\n\t\t\t\t\tif levelOver {\n\t\t\t\t\t\terrLines += \"\\n\" + line\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\twarnNum++\n\t\t\t\tcritNum++\n\t\t\t\terrLines += \"\\n\" + line\n\t\t\t}\n\t\t}\n\t}\n\terr = writeBytesToSkip(stateFile, readBytes)\n\treturn warnNum, critNum, errLines, nil\n}\n\nvar stateRe = regexp.MustCompile(`^([A-Z]):[\/\\\\]`)\n\nfunc getStateFile(stateDir, f string) string {\n\treturn filepath.Join(stateDir, stateRe.ReplaceAllString(f, `$1`+string(filepath.Separator)))\n}\n\nfunc getBytesToSkip(f string) (int64, error) {\n\t_, err := os.Stat(f)\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\tb, err := ioutil.ReadFile(f)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ti, err := strconv.Atoi(strings.Trim(string(b), \" \\r\\n\"))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn int64(i), nil\n}\n\nfunc writeBytesToSkip(f string, num int64) error {\n\terr := os.MkdirAll(filepath.Dir(f), 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(f, []byte(fmt.Sprintf(\"%d\", num)), 0755)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com\/hyperledger\/fabric\/core\/chaincode\/shim\"\n)\n\n\/\/ SimpleChaincode implementation\ntype SimpleChaincode struct {\n}\n\nfunc (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n\tvar err error\n\n\tif len(args) == 0 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. At least one Meter's name is required.\")\n\t}\n\n\tfor _,name := range args {\n\t\tif len(name) == 0{\n\t\t\tcontinue\n\t\t}\n\t\terr = stub.PutState( \"kwh_\" + name, []byte(strconv.Itoa(0)));\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Meter cannot be created\")\n\t\t}\n\t\terr = stub.PutState( name, []byte(strconv.Itoa(0)));\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Meter cannot be created\")\n\t\t}\n\t}\n\n\treturn nil, nil\n}\n\n\/\/ Deletes an entity from state\nfunc (t *SimpleChaincode) settle(stub *shim.ChaincodeStub, args []string) ([]byte, error) {\n\t\/\/var err error\n\tvar key string\n\tvar val int\n\tvar exchange_rate, previous_val, amount float64\n\n\texchange_rate = 0.1;\n\n\t\/\/TODO iteration by id is not an option. you should load keys from fabric\n\tfor i := 1; i < 10; i++ {\n\t\tkey = strconv.Itoa(i)\n\t\tvalue, err := stub.GetState(\"kwh_\" + key)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif value == nil {\n\t\t\tcontinue\n\t\t}\n\t\tval, _ = strconv.Atoi(string(value))\n\t\tamount = float64(val)* -1 * exchange_rate;\n\t\t\/\/f := \"change\"\n\t\t\/\/queryArgs := []string{name,string(amount)}\n\t\t\/\/_, err := stub.InvokeChaincode(\"2780b7463c57f343a9e107854c4b53150018cdd8fd74ca970c028de6bfa707f6e9f6cf2b20f0af4fdd04d2167651eb29c7bfabf19e6a93ae2aff65f55202d0e6\", f, queryArgs)\n\t\t\/\/if err != nil {\n\t\t\/\/\terrStr := fmt.Sprintf(\"Failed to query chaincode. Got error: %s\", err.Error())\n\t\t\/\/\tfmt.Printf(errStr)\n\t\t\/\/\treturn nil, errors.New(errStr)\n\t\t\/\/}\n\t\tcoins, err := stub.GetState(key)\n\t\tif err != nil {\n\t\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to get state for \" + key + \"\\\"}\"\n\t\t\treturn nil, errors.New(jsonResp)\n\t\t}\n\t\tif(coins == nil){\n\t\t\tprevious_val = 0\n\t\t}else{\n\t\t\tprevious_val, _ = strconv.ParseFloat(string(coins), 64);\n\t\t}\n\n\n\t\terr = stub.PutState(key, []byte(strconv.FormatFloat(amount + previous_val, 'f', 6, 64)))\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = stub.PutState(\"kwh_\" + key, []byte(strconv.Itoa(0)));\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Meter cannot be updated\")\n\t\t}\n\t}\n\n\n\treturn nil, nil\n}\n\nfunc (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n\n\tif function == \"settle\" {\n\t\treturn t.settle(stub, args)\n\t}\n\n\tif function != \"report\" {\n\t\treturn nil, errors.New(\"Unimplemented '\" + function + \"' invoked\")\n\t}\n\n\tvar name string    \/\/ Entities\n\tvar val int \/\/ Asset holdings\n\tvar err error\n\n\tif len(args) != 2 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tname = args[0]\n\tval, _ = strconv.Atoi(string(args[1]))\n\n\terr = stub.PutState(\"kwh_\" + name, []byte(strconv.Itoa(val)))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n\n\n\/\/ Query callback representing the query of a chaincode\nfunc (t *SimpleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n\n\tif function == \"balance\" {\n\t\treturn t.balance(stub, args)\n\t}\n\n\tif function != \"reported_kwh\" {\n\t\treturn nil, errors.New(\"Invalid query function name. Expecting \\\"querybalance\\\"\")\n\t}\n\tvar name string \/\/ Entities\n\tvar err error\n\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting name of the Meter to query\")\n\t}\n\n\tname = args[0]\n\n\t\/\/ Get the state from the ledger\n\tvalue, err := stub.GetState(\"kwh_\" + name)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to get state for \" + name + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tif value == nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Nil amount for Meter\" + name + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tjsonResp := \"{\\\"Name\\\":\\\"\" + name + \"\\\",\\\"Amount\\\":\\\"\" + string(value) + \"\\\"}\"\n\tfmt.Printf(\"Query Response:%s\\n\", jsonResp)\n\treturn value, nil\n}\n\nfunc (t *SimpleChaincode) balance(stub *shim.ChaincodeStub, args []string) ([]byte, error) {\n\tvar name string \/\/ Entities\n\tvar err error\n\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting name of the Meter to query\")\n\t}\n\n\tname = args[0]\n\n\t\/\/ Get the state from the ledger\n\tvalue, err := stub.GetState(name)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to get state for \" + name + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tif value == nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Nil amount for Meter \" + name + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tjsonResp := \"{\\\"Name\\\":\\\"\" + name + \"\\\",\\\"Amount\\\":\\\"\" + string(value) + \"\\\"}\"\n\tfmt.Printf(\"Query Response:%s\\n\", jsonResp)\n\treturn value, nil\n}\n\nfunc main() {\n\terr := shim.Start(new(SimpleChaincode))\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting Simple chaincode: %s\", err)\n\t}\n}\n<commit_msg>move Change method from settle chain code to report<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com\/hyperledger\/fabric\/core\/chaincode\/shim\"\n)\n\n\/\/ SimpleChaincode implementation\ntype SimpleChaincode struct {\n}\n\nfunc (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n\tvar err error\n\n\tif len(args) == 0 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. At least one Meter's name is required.\")\n\t}\n\n\tfor _,name := range args {\n\t\tif len(name) == 0{\n\t\t\tcontinue\n\t\t}\n\t\terr = stub.PutState( \"kwh_\" + name, []byte(strconv.Itoa(0)));\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Meter cannot be created\")\n\t\t}\n\t\terr = stub.PutState( name, []byte(strconv.Itoa(0)));\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Meter cannot be created\")\n\t\t}\n\t}\n\n\treturn nil, nil\n}\n\n\/\/ Deletes an entity from state\nfunc (t *SimpleChaincode) settle(stub *shim.ChaincodeStub, args []string) ([]byte, error) {\n\t\/\/var err error\n\tvar key string\n\tvar val int\n\tvar exchange_rate, previous_val, amount float64\n\n\texchange_rate = 0.1;\n\n\t\/\/TODO iteration by id is not an option. you should load keys from fabric\n\tfor i := 1; i < 10; i++ {\n\t\tkey = strconv.Itoa(i)\n\t\tvalue, err := stub.GetState(\"kwh_\" + key)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif value == nil {\n\t\t\tcontinue\n\t\t}\n\t\tval, _ = strconv.Atoi(string(value))\n\t\tamount = float64(val)* -1 * exchange_rate;\n\t\t\/\/f := \"change\"\n\t\t\/\/queryArgs := []string{name,string(amount)}\n\t\t\/\/_, err := stub.InvokeChaincode(\"2780b7463c57f343a9e107854c4b53150018cdd8fd74ca970c028de6bfa707f6e9f6cf2b20f0af4fdd04d2167651eb29c7bfabf19e6a93ae2aff65f55202d0e6\", f, queryArgs)\n\t\t\/\/if err != nil {\n\t\t\/\/\terrStr := fmt.Sprintf(\"Failed to query chaincode. Got error: %s\", err.Error())\n\t\t\/\/\tfmt.Printf(errStr)\n\t\t\/\/\treturn nil, errors.New(errStr)\n\t\t\/\/}\n\t\tcoins, err := stub.GetState(key)\n\t\tif err != nil {\n\t\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to get state for \" + key + \"\\\"}\"\n\t\t\treturn nil, errors.New(jsonResp)\n\t\t}\n\t\tif(coins == nil){\n\t\t\tprevious_val = 0\n\t\t}else{\n\t\t\tprevious_val, _ = strconv.ParseFloat(string(coins), 64);\n\t\t}\n\n\n\t\terr = stub.PutState(key, []byte(strconv.FormatFloat(amount + previous_val, 'f', 6, 64)))\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = stub.PutState(\"kwh_\" + key, []byte(strconv.Itoa(0)));\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Meter cannot be updated\")\n\t\t}\n\t}\n\n\n\treturn nil, nil\n}\n\n\nfunc (t *SimpleChaincode) change(stub *shim.ChaincodeStub,  args []string) ([]byte, error) {\n\n\tvar name string\n\tvar val, previous_val float64\n\tvar err error\n\n\tif len(args) != 2 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\n\tname = args[0]\n\t\/\/ Get the state from the ledger\n\tvalue, err := stub.GetState(name)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to get state for \" + name + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tprevious_val, _ = strconv.ParseFloat(string(value), 64);\n\tval, _ = strconv.ParseFloat(string(args[1]), 64);\n\n\terr = stub.PutState(name, []byte(strconv.FormatFloat(val + previous_val, 'f', 6, 64)))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n\n\nfunc (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n\n\tif function == \"settle\" {\n\t\treturn t.settle(stub, args)\n\t}\n\n\tif function != \"change\" {\n\t\treturn t.change(stub, args)\n\t}\n\tif function != \"report\" {\n\t\treturn nil, errors.New(\"Unimplemented '\" + function + \"' invoked\")\n\t}\n\n\tvar name string    \/\/ Entities\n\tvar val int \/\/ Asset holdings\n\tvar err error\n\n\tif len(args) != 2 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tname = args[0]\n\tval, _ = strconv.Atoi(string(args[1]))\n\n\terr = stub.PutState(\"kwh_\" + name, []byte(strconv.Itoa(val)))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n\n\n\/\/ Query callback representing the query of a chaincode\nfunc (t *SimpleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n\n\tif function == \"balance\" {\n\t\treturn t.balance(stub, args)\n\t}\n\n\tif function != \"reported_kwh\" {\n\t\treturn nil, errors.New(\"Invalid query function name. Expecting \\\"querybalance\\\"\")\n\t}\n\tvar name string \/\/ Entities\n\tvar err error\n\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting name of the Meter to query\")\n\t}\n\n\tname = args[0]\n\n\t\/\/ Get the state from the ledger\n\tvalue, err := stub.GetState(\"kwh_\" + name)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to get state for \" + name + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tif value == nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Nil amount for Meter\" + name + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tjsonResp := \"{\\\"Name\\\":\\\"\" + name + \"\\\",\\\"Amount\\\":\\\"\" + string(value) + \"\\\"}\"\n\tfmt.Printf(\"Query Response:%s\\n\", jsonResp)\n\treturn value, nil\n}\n\nfunc (t *SimpleChaincode) balance(stub *shim.ChaincodeStub, args []string) ([]byte, error) {\n\tvar name string \/\/ Entities\n\tvar err error\n\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting name of the Meter to query\")\n\t}\n\n\tname = args[0]\n\n\t\/\/ Get the state from the ledger\n\tvalue, err := stub.GetState(name)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to get state for \" + name + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tif value == nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Nil amount for Meter \" + name + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tjsonResp := \"{\\\"Name\\\":\\\"\" + name + \"\\\",\\\"Amount\\\":\\\"\" + string(value) + \"\\\"}\"\n\tfmt.Printf(\"Query Response:%s\\n\", jsonResp)\n\treturn value, nil\n}\n\nfunc main() {\n\terr := shim.Start(new(SimpleChaincode))\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting Simple chaincode: %s\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nPresent displays slide presentations and articles. It runs a web server that\npresents slide and article files from the current directory.\n\nIt may be run as a stand-alone command or an App Engine app.\nThe stand-alone version permits the execution of programs from within a\npresentation. The App Engine version does not provide this functionality.\n\nUsage of present:\n  -base=\"\": base path for slide template and static resources\n  -http=\"127.0.0.1:3999\": host:port to listen on\n\nYou may use the app.yaml file provided in the root of the go.talks repository\nto deploy present to App Engine:\n\tappcfg.py update -A your-app-id -V your-app-version \/path\/to\/go.talks\n\nInput files are named foo.extension, where \"extension\" defines the format of\nthe generated output. The supported formats are:\n\t.slide        \/\/ HTML5 slide presentation\n\t.article      \/\/ article format, such as a blog post\n\nThe present file format is documented by the present package:\nhttp:\/\/godoc.org\/code.google.com\/p\/go.tools\/godoc\/present\n*\/\npackage main\n<commit_msg>go.talk\/present: fix a link.<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nPresent displays slide presentations and articles. It runs a web server that\npresents slide and article files from the current directory.\n\nIt may be run as a stand-alone command or an App Engine app.\nThe stand-alone version permits the execution of programs from within a\npresentation. The App Engine version does not provide this functionality.\n\nUsage of present:\n  -base=\"\": base path for slide template and static resources\n  -http=\"127.0.0.1:3999\": host:port to listen on\n\nYou may use the app.yaml file provided in the root of the go.talks repository\nto deploy present to App Engine:\n\tappcfg.py update -A your-app-id -V your-app-version \/path\/to\/go.talks\n\nInput files are named foo.extension, where \"extension\" defines the format of\nthe generated output. The supported formats are:\n\t.slide        \/\/ HTML5 slide presentation\n\t.article      \/\/ article format, such as a blog post\n\nThe present file format is documented by the present package:\nhttp:\/\/godoc.org\/code.google.com\/p\/go.tools\/present\n*\/\npackage main\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nThe present file format\n\nPresent files have the following format.  The first non-blank non-comment\nline is the title, so the header looks like\n\n\tTitle of document\n\tSubtitle of document\n\t15:04 2 Jan 2006\n\tTags: foo, bar, baz\n\t<blank line>\n\tAuthor Name\n\tJob title, Company\n\tjoe@example.com\n\thttp:\/\/url\/\n\t@twitter_name\n\nThe subtitle, date, and tags lines are optional.\n\nThe date line may be written without a time:\n\t2 Jan 2006\nIn this case, the time will be interpreted as 10am UTC on that date.\n\nThe tags line is a comma-separated list of tags that may be used to categorize\nthe document.\n\nThe author section may contain a mixture of text, twitter names, and links.\nFor slide presentations, only the plain text lines will be displayed on the\nfirst slide.\n\nMultiple presenters may be specified, separated by a blank line.\n\nAfter that come slides\/sections, each after a blank line:\n\n\t* Title of slide or section (must have asterisk)\n\n\tSome Text\n\n\t** Subsection\n\n\t- bullets\n\t- more bullets\n\t- a bullet with\n\n\t*** Sub-subsection\n\n\tSome More text\n\n\t  Preformatted text\n\t  is indented (however you like)\n\n\tFurther Text, including invocations like:\n\n\t.code x.go \/^func main\/,\/^}\/\n\t.play y.go\n\t.image image.jpg\n\t.background image.jpg\n\t.iframe http:\/\/foo\n\t.link http:\/\/foo label\n\t.html file.html\n\t.caption _Gopher_ by [[https:\/\/www.instagram.com\/reneefrench\/][Renée French]]\n\n\tAgain, more text\n\nBlank lines are OK (not mandatory) after the title and after the\ntext.  Text, bullets, and .code etc. are all optional; title is\nnot.\n\nLines starting with # in column 1 are commentary.\n\nFonts:\n\nWithin the input for plain text or lists, text bracketed by font\nmarkers will be presented in italic, bold, or program font.\nMarker characters are _ (italic), * (bold) and ` (program font).\nAn opening marker must be preceded by a space or punctuation\ncharacter or else be at start of a line; similarly, a closing\nmarker must be followed by a space or punctuation character or\nelse be at the end of a line. Unmatched markers appear as plain text.\nThere must be no spaces between markers. Within marked text,\na single marker character becomes a space and a doubled single\nmarker quotes the marker character.\n\n\t_italic_\n\t*bold*\n\t`program`\n\tMarkup—_especially_italic_text_—can easily be overused.\n\t_Why_use_scoped__ptr_? Use plain ***ptr* instead.\n\nInline links:\n\nLinks can be included in any text with the form [[url][label]], or\n[[url]] to use the URL itself as the label.\n\nFunctions:\n\nA number of template functions are available through invocations\nin the input text. Each such invocation contains a period as the\nfirst character on the line, followed immediately by the name of\nthe function, followed by any arguments. A typical invocation might\nbe\n\t.play demo.go \/^func show\/,\/^}\/\n(except that the \".play\" must be at the beginning of the line and\nnot be indented like this.)\n\nHere follows a description of the functions:\n\ncode:\n\nInjects program source into the output by extracting code from files\nand injecting them as HTML-escaped <pre> blocks.  The argument is\na file name followed by an optional address that specifies what\nsection of the file to display. The address syntax is similar in\nits simplest form to that of ed, but comes from sam and is more\ngeneral. See\n\thttps:\/\/plan9.io\/sys\/doc\/sam\/sam.html Table II\nfor full details. The displayed block is always rounded out to a\nfull line at both ends.\n\nIf no pattern is present, the entire file is displayed.\n\nAny line in the program that ends with the four characters\n\tOMIT\nis deleted from the source before inclusion, making it easy\nto write things like\n\t.code test.go \/START OMIT\/,\/END OMIT\/\nto find snippets like this\n\ttedious_code = boring_function()\n\t\/\/ START OMIT\n\tinteresting_code = fascinating_function()\n\t\/\/ END OMIT\nand see only this:\n\tinteresting_code = fascinating_function()\n\nAlso, inside the displayed text a line that ends\n\t\/\/ HL\nwill be highlighted in the display; the 'h' key in the browser will\ntoggle extra emphasis of any highlighted lines. A highlighting mark\nmay have a suffix word, such as\n\t\/\/ HLxxx\nSuch highlights are enabled only if the code invocation ends with\n\"HL\" followed by the word:\n\t.code test.go \/^type Foo\/,\/^}\/ HLxxx\n\nThe .code function may take one or more flags immediately preceding\nthe filename. This command shows test.go in an editable text area:\n\t.code -edit test.go\nThis command shows test.go with line numbers:\n\t.code -numbers test.go\n\nplay:\n\nThe function \"play\" is the same as \"code\" but puts a button\non the displayed source so the program can be run from the browser.\nAlthough only the selected text is shown, all the source is included\nin the HTML output so it can be presented to the compiler.\n\nlink:\n\nCreate a hyperlink. The syntax is 1 or 2 space-separated arguments.\nThe first argument is always the HTTP URL.  If there is a second\nargument, it is the text label to display for this link.\n\n\t.link http:\/\/golang.org golang.org\n\nimage:\n\nThe template uses the function \"image\" to inject picture files.\n\nThe syntax is simple: 1 or 3 space-separated arguments.\nThe first argument is always the file name.\nIf there are more arguments, they are the height and width;\nboth must be present, or substituted with an underscore.\nReplacing a dimension argument with the underscore parameter\npreserves the aspect ratio of the image when scaling.\n\n\t.image images\/betsy.jpg 100 200\n\n\t.image images\/janet.jpg _ 300\n\nvideo:\n\nThe template uses the function \"video\" to inject video files.\n\nThe syntax is simple: 2 or 4 space-separated arguments.\nThe first argument is always the file name.\nThe second argument is always the file content-type.\nIf there are more arguments, they are the height and width;\nboth must be present, or substituted with an underscore.\nReplacing a dimension argument with the underscore parameter\npreserves the aspect ratio of the video when scaling.\n\n\t.video videos\/evangeline.mp4 video\/mp4 400 600\n\n\t.video videos\/mabel.ogg video\/ogg 500 _\n\nbackground:\n\nThe template uses the function \"background\" to set the background image for\na slide.  The only argument is the file name of the image.\n\n\t.background images\/susan.jpg\n\ncaption:\n\nThe template uses the function \"caption\" to inject figure captions.\n\nThe text after \".caption\" is embedded in a figcaption element after\nprocessing styling and links as in standard text lines.\n\n\t.caption _Gopher_ by [[http:\/\/www.reneefrench.com][Renée French]]\n\niframe:\n\nThe function \"iframe\" injects iframes (pages inside pages).\nIts syntax is the same as that of image.\n\nhtml:\n\nThe function html includes the contents of the specified file as\nunescaped HTML. This is useful for including custom HTML elements\nthat cannot be created using only the slide format.\nIt is your responsibility to make sure the included HTML is valid and safe.\n\n\t.html file.html\n\nPresenter notes:\n\nPresenter notes may be enabled by appending the \"-notes\" flag when you run\nyour \"present\" binary.\n\nThis will allow you to open a second window by pressing 'N' from your browser\ndisplaying your slides. The second window is completely synced with your main\nwindow, except that presenter notes are only visible on the second window.\n\nLines that begin with \": \" are treated as presenter notes.\n\n\t* Title of slide\n\n\tSome Text\n\n\t: Presenter notes (first paragraph)\n\t: Presenter notes (subsequent paragraph(s))\n\nNotes may appear anywhere within the slide text. For example:\n\n\t* Title of slide\n\n\t: Presenter notes (first paragraph)\n\n\tSome Text\n\n\t: Presenter notes (subsequent paragraph(s))\n\nThis has the same result as the example above.\n\n*\/\npackage present \/\/ import \"golang.org\/x\/tools\/present\"\n<commit_msg>present: remove mention of non-existing emphasis toggle<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nThe present file format\n\nPresent files have the following format.  The first non-blank non-comment\nline is the title, so the header looks like\n\n\tTitle of document\n\tSubtitle of document\n\t15:04 2 Jan 2006\n\tTags: foo, bar, baz\n\t<blank line>\n\tAuthor Name\n\tJob title, Company\n\tjoe@example.com\n\thttp:\/\/url\/\n\t@twitter_name\n\nThe subtitle, date, and tags lines are optional.\n\nThe date line may be written without a time:\n\t2 Jan 2006\nIn this case, the time will be interpreted as 10am UTC on that date.\n\nThe tags line is a comma-separated list of tags that may be used to categorize\nthe document.\n\nThe author section may contain a mixture of text, twitter names, and links.\nFor slide presentations, only the plain text lines will be displayed on the\nfirst slide.\n\nMultiple presenters may be specified, separated by a blank line.\n\nAfter that come slides\/sections, each after a blank line:\n\n\t* Title of slide or section (must have asterisk)\n\n\tSome Text\n\n\t** Subsection\n\n\t- bullets\n\t- more bullets\n\t- a bullet with\n\n\t*** Sub-subsection\n\n\tSome More text\n\n\t  Preformatted text\n\t  is indented (however you like)\n\n\tFurther Text, including invocations like:\n\n\t.code x.go \/^func main\/,\/^}\/\n\t.play y.go\n\t.image image.jpg\n\t.background image.jpg\n\t.iframe http:\/\/foo\n\t.link http:\/\/foo label\n\t.html file.html\n\t.caption _Gopher_ by [[https:\/\/www.instagram.com\/reneefrench\/][Renée French]]\n\n\tAgain, more text\n\nBlank lines are OK (not mandatory) after the title and after the\ntext.  Text, bullets, and .code etc. are all optional; title is\nnot.\n\nLines starting with # in column 1 are commentary.\n\nFonts:\n\nWithin the input for plain text or lists, text bracketed by font\nmarkers will be presented in italic, bold, or program font.\nMarker characters are _ (italic), * (bold) and ` (program font).\nAn opening marker must be preceded by a space or punctuation\ncharacter or else be at start of a line; similarly, a closing\nmarker must be followed by a space or punctuation character or\nelse be at the end of a line. Unmatched markers appear as plain text.\nThere must be no spaces between markers. Within marked text,\na single marker character becomes a space and a doubled single\nmarker quotes the marker character.\n\n\t_italic_\n\t*bold*\n\t`program`\n\tMarkup—_especially_italic_text_—can easily be overused.\n\t_Why_use_scoped__ptr_? Use plain ***ptr* instead.\n\nInline links:\n\nLinks can be included in any text with the form [[url][label]], or\n[[url]] to use the URL itself as the label.\n\nFunctions:\n\nA number of template functions are available through invocations\nin the input text. Each such invocation contains a period as the\nfirst character on the line, followed immediately by the name of\nthe function, followed by any arguments. A typical invocation might\nbe\n\t.play demo.go \/^func show\/,\/^}\/\n(except that the \".play\" must be at the beginning of the line and\nnot be indented like this.)\n\nHere follows a description of the functions:\n\ncode:\n\nInjects program source into the output by extracting code from files\nand injecting them as HTML-escaped <pre> blocks.  The argument is\na file name followed by an optional address that specifies what\nsection of the file to display. The address syntax is similar in\nits simplest form to that of ed, but comes from sam and is more\ngeneral. See\n\thttps:\/\/plan9.io\/sys\/doc\/sam\/sam.html Table II\nfor full details. The displayed block is always rounded out to a\nfull line at both ends.\n\nIf no pattern is present, the entire file is displayed.\n\nAny line in the program that ends with the four characters\n\tOMIT\nis deleted from the source before inclusion, making it easy\nto write things like\n\t.code test.go \/START OMIT\/,\/END OMIT\/\nto find snippets like this\n\ttedious_code = boring_function()\n\t\/\/ START OMIT\n\tinteresting_code = fascinating_function()\n\t\/\/ END OMIT\nand see only this:\n\tinteresting_code = fascinating_function()\n\nAlso, inside the displayed text a line that ends\n\t\/\/ HL\nwill be highlighted in the display. A highlighting mark may have a\nsuffix word, such as\n\t\/\/ HLxxx\nSuch highlights are enabled only if the code invocation ends with\n\"HL\" followed by the word:\n\t.code test.go \/^type Foo\/,\/^}\/ HLxxx\n\nThe .code function may take one or more flags immediately preceding\nthe filename. This command shows test.go in an editable text area:\n\t.code -edit test.go\nThis command shows test.go with line numbers:\n\t.code -numbers test.go\n\nplay:\n\nThe function \"play\" is the same as \"code\" but puts a button\non the displayed source so the program can be run from the browser.\nAlthough only the selected text is shown, all the source is included\nin the HTML output so it can be presented to the compiler.\n\nlink:\n\nCreate a hyperlink. The syntax is 1 or 2 space-separated arguments.\nThe first argument is always the HTTP URL.  If there is a second\nargument, it is the text label to display for this link.\n\n\t.link http:\/\/golang.org golang.org\n\nimage:\n\nThe template uses the function \"image\" to inject picture files.\n\nThe syntax is simple: 1 or 3 space-separated arguments.\nThe first argument is always the file name.\nIf there are more arguments, they are the height and width;\nboth must be present, or substituted with an underscore.\nReplacing a dimension argument with the underscore parameter\npreserves the aspect ratio of the image when scaling.\n\n\t.image images\/betsy.jpg 100 200\n\n\t.image images\/janet.jpg _ 300\n\nvideo:\n\nThe template uses the function \"video\" to inject video files.\n\nThe syntax is simple: 2 or 4 space-separated arguments.\nThe first argument is always the file name.\nThe second argument is always the file content-type.\nIf there are more arguments, they are the height and width;\nboth must be present, or substituted with an underscore.\nReplacing a dimension argument with the underscore parameter\npreserves the aspect ratio of the video when scaling.\n\n\t.video videos\/evangeline.mp4 video\/mp4 400 600\n\n\t.video videos\/mabel.ogg video\/ogg 500 _\n\nbackground:\n\nThe template uses the function \"background\" to set the background image for\na slide.  The only argument is the file name of the image.\n\n\t.background images\/susan.jpg\n\ncaption:\n\nThe template uses the function \"caption\" to inject figure captions.\n\nThe text after \".caption\" is embedded in a figcaption element after\nprocessing styling and links as in standard text lines.\n\n\t.caption _Gopher_ by [[http:\/\/www.reneefrench.com][Renée French]]\n\niframe:\n\nThe function \"iframe\" injects iframes (pages inside pages).\nIts syntax is the same as that of image.\n\nhtml:\n\nThe function html includes the contents of the specified file as\nunescaped HTML. This is useful for including custom HTML elements\nthat cannot be created using only the slide format.\nIt is your responsibility to make sure the included HTML is valid and safe.\n\n\t.html file.html\n\nPresenter notes:\n\nPresenter notes may be enabled by appending the \"-notes\" flag when you run\nyour \"present\" binary.\n\nThis will allow you to open a second window by pressing 'N' from your browser\ndisplaying your slides. The second window is completely synced with your main\nwindow, except that presenter notes are only visible on the second window.\n\nLines that begin with \": \" are treated as presenter notes.\n\n\t* Title of slide\n\n\tSome Text\n\n\t: Presenter notes (first paragraph)\n\t: Presenter notes (subsequent paragraph(s))\n\nNotes may appear anywhere within the slide text. For example:\n\n\t* Title of slide\n\n\t: Presenter notes (first paragraph)\n\n\tSome Text\n\n\t: Presenter notes (subsequent paragraph(s))\n\nThis has the same result as the example above.\n\n*\/\npackage present \/\/ import \"golang.org\/x\/tools\/present\"\n<|endoftext|>"}
{"text":"<commit_before>package golog\n\n\/\/ This file runs Go tests for Prolog test files under a 't' directory.\n\/\/ This gives us an easy way to write many Prolog tests without writing\n\/\/ a bunch of manual Go tests.  Because the tests are written in Prolog\n\/\/ they can be reused by other Prolog implementations.\n\nimport \"os\"\nimport \"testing\"\nimport \"github.com\/mndrix\/golog\/read\"\nimport \"github.com\/mndrix\/golog\/term\"\nimport . \"github.com\/mndrix\/golog\/util\"\n\nfunc TestPureProlog(t *testing.T) {\n\t\/\/ find all t\/*.pl files\n\tfile, err := os.Open(\"t\")\n\tMaybePanic(err)\n\tnames, err := file.Readdirnames(-1)\n\n\t\/\/ run tests found in each file\n\tfor _, name := range names {\n\t\tif name[0] == '.' {\n\t\t\tcontinue \/\/ skip hidden files\n\t\t}\n\t\topenTest := func() *os.File {\n\t\t\tf, err := os.Open(\"t\/\" + name)\n\t\t\tMaybePanic(err)\n\t\t\treturn f\n\t\t}\n\n\t\t\/\/ which tests does the file have?\n\t\ttests := make([]term.Term, 0)\n\t\tterms := read.TermAll_(openTest())\n\t\tfor _, t := range terms {\n\t\t\tx := t.(term.Callable)\n\t\t\tif x.Indicator() == \":-\/2\" {\n\t\t\t\ttests = append(tests, x.Arguments()[0])\n\t\t\t}\n\t\t}\n\n\t\t\/\/ run each test in this file\n\t\tm := NewMachine().Consult(openTest())\n\t\tfor _, test := range tests {\n\t\t\tx := test.(term.Callable)\n\t\t\tcanProve := m.CanProve(test)\n\t\t\tif x.Arity() > 0 && x.Arguments()[0].String() == \"fail\" {\n\t\t\t\tif canProve {\n\t\t\t\t\tt.Errorf(\"%s: %s should fail\", name, test)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif !canProve {\n\t\t\t\t\tt.Errorf(\"%s: %s failed\", name, test)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Run TAP tests that don't have names<commit_after>package golog\n\n\/\/ This file runs Go tests for Prolog test files under a 't' directory.\n\/\/ This gives us an easy way to write many Prolog tests without writing\n\/\/ a bunch of manual Go tests.  Because the tests are written in Prolog\n\/\/ they can be reused by other Prolog implementations.\n\nimport \"os\"\nimport \"testing\"\nimport \"github.com\/mndrix\/golog\/read\"\nimport \"github.com\/mndrix\/golog\/term\"\nimport . \"github.com\/mndrix\/golog\/util\"\n\nfunc TestPureProlog(t *testing.T) {\n\t\/\/ find all t\/*.pl files\n\tfile, err := os.Open(\"t\")\n\tMaybePanic(err)\n\tnames, err := file.Readdirnames(-1)\n\n\tuseModule := read.Term_(`:- use_module(library(tap)).`)\n\tenv := term.NewBindings()\n\n\t\/\/ run tests found in each file\n\tfor _, name := range names {\n\t\tif name[0] == '.' {\n\t\t\tcontinue \/\/ skip hidden files\n\t\t}\n\t\t\/\/t.Logf(\"-------------- %s\", name)\n\t\topenTest := func() *os.File {\n\t\t\tf, err := os.Open(\"t\/\" + name)\n\t\t\tMaybePanic(err)\n\t\t\treturn f\n\t\t}\n\n\t\t\/\/ which tests does the file have?\n\t\tpastUseModule := false\n\t\ttests := make([]term.Term, 0)\n\t\tterms := read.TermAll_(openTest())\n\t\tfor _, s := range terms {\n\t\t\tx := s.(term.Callable)\n\t\t\tif pastUseModule {\n\t\t\t\tif x.Arity() == 2 && x.Name() == \":-\" {\n\t\t\t\t\ttests = append(tests, x.Arguments()[0])\n\t\t\t\t} else {\n\t\t\t\t\ttests = append(tests, x)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ look for use_module(library(tap)) declaration\n\t\t\t\t_, err := s.Unify(env, useModule)\n\t\t\t\tif err == nil {\n\t\t\t\t\tpastUseModule = true\n\t\t\t\t\t\/\/t.Logf(\"found use_module directive\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ run each test in this file\n\t\tm := NewMachine().Consult(openTest())\n\t\tfor _, test := range tests {\n\t\t\tx := test.(term.Callable)\n\t\t\t\/\/t.Logf(\"proving: %s\", test)\n\t\t\tcanProve := m.CanProve(test)\n\t\t\tif x.Arity() > 0 && x.Arguments()[0].String() == \"fail\" {\n\t\t\t\tif canProve {\n\t\t\t\t\tt.Errorf(\"%s: %s should fail\", name, test)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif !canProve {\n\t\t\t\t\tt.Errorf(\"%s: %s failed\", name, test)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package proto\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nimport (\n\t\"butler\/crypto\"\n\t\"butler\/null\"\n\tpb \"code.google.com\/p\/goprotobuf\/proto\"\n\t\"manhattan\/util\/fileutil\"\n)\n\nfunc NewMixer(path string) *Mixer {\n\tversion, err := ioutil.ReadFile(filepath.Join(path, \"VERSION\"))\n\n\tif err != nil {\n\t\tpanic(\"Couldn't find a version for mixer:\" + path + \":\" + err.Error())\n\t}\n\n\tversionStr := strings.TrimSpace(string(version))\n\n\t_, name := filepath.Split(path)\n\n\treturn &Mixer{\n\t\tName:      pb.String(name),\n\t\tVersion:   pb.String(versionStr),\n\t\tRewriters: make([]*File, 0),\n\t\tPackage:   nil,\n\t}\n}\n\nfunc (m *Mixer) Write(path string) (outputPath string, err error) {\n\n\tname := null.GetString(m.Name)\n\tversion := null.GetString(m.Version)\n\toutputPath = filepath.Join(path, name+\"-\"+version+\".mxr\")\n\n\tbytes, err := pb.Marshal(m)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbytes = crypto.Encrypt(bytes)\n\n\terr = os.MkdirAll(path, fileutil.DIR_PERMS)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = ioutil.WriteFile(outputPath, bytes, 0644)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (m *Mixer) Inspect(printFunctions bool) {\n\tprintln(\"\\tRewriters:\")\n\tfor _, rewriter := range m.Rewriters {\n\t\tfmt.Printf(\"\\t\\t -- %v\\n\", null.GetString(rewriter.Path))\n\t}\n\n\tprintln(\"\\tRoot Package:\")\n\tfmt.Printf(m.packageSummary(printFunctions))\n}\n\nfunc (m *Mixer) Unpack(path string) {\n\tfullPath := filepath.Join(path, null.GetString(m.Name)+\"-\"+null.GetString(m.Version))\n\terr := os.MkdirAll(fullPath, 0755)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\terr = m.unpackFiles(filepath.Join(fullPath, \"rewriters\"), m.Rewriters)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsummary := m.packageSummary(true)\n\tpackageFile := filepath.Join(fullPath, \"package-summary.txt\")\n\n\terr = ioutil.WriteFile(packageFile, []byte(summary), 0644)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Warning : Couldn't write package summary\")\n\t}\n\n\tfmt.Printf(\"* %v\\n\", packageFile)\n}\n\nfunc (m *Mixer) unpackFiles(path string, files []*File) (err error) {\n\tfl := &FileList{\n\t\tRootDirectory: path,\n\t\tFiles:         files,\n\t}\n\n\terr = fl.Unpack(true)\n\n\treturn\n}\n\nfunc (m *Mixer) packageSummary(printFunctions bool) string {\n\tsummary := \"\"\n\tif m.Package != nil {\n\t\tsummary += fmt.Sprintf(\"\\t\\t -- Name: %v\\n\", null.GetString(m.Package.Name))\n\t\tsummary += fmt.Sprintf(\"\\t\\t -- Types: %v\\n\", m.Package.Types)\n\t\tsummary += fmt.Sprintf(\"\\t\\t -- Dependencies:  %v\\n\", m.Package.Dependencies)\n\t\tif printFunctions {\n\t\t\tsummary += fmt.Sprintf(\"\\t\\t -- Functions (%v):\\n\", len(m.Package.Functions))\n\t\t\tfor _, function := range m.Package.Functions {\n\t\t\t\tsummary += fmt.Sprintf(\"\\t\\t\\t %v\\n\", function.Stub(m.Package))\n\t\t\t}\n\t\t}\n\t}\n\treturn summary\n}\n<commit_msg>Updating to use fileutil.FILE_PERMS<commit_after>package proto\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nimport (\n\t\"butler\/crypto\"\n\t\"butler\/null\"\n\tpb \"code.google.com\/p\/goprotobuf\/proto\"\n\t\"manhattan\/util\/fileutil\"\n)\n\nfunc NewMixer(path string) *Mixer {\n\tversion, err := ioutil.ReadFile(filepath.Join(path, \"VERSION\"))\n\n\tif err != nil {\n\t\tpanic(\"Couldn't find a version for mixer:\" + path + \":\" + err.Error())\n\t}\n\n\tversionStr := strings.TrimSpace(string(version))\n\n\t_, name := filepath.Split(path)\n\n\treturn &Mixer{\n\t\tName:      pb.String(name),\n\t\tVersion:   pb.String(versionStr),\n\t\tRewriters: make([]*File, 0),\n\t\tPackage:   nil,\n\t}\n}\n\nfunc (m *Mixer) Write(path string) (outputPath string, err error) {\n\n\tname := null.GetString(m.Name)\n\tversion := null.GetString(m.Version)\n\toutputPath = filepath.Join(path, name+\"-\"+version+\".mxr\")\n\n\tbytes, err := pb.Marshal(m)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbytes = crypto.Encrypt(bytes)\n\n\terr = os.MkdirAll(path, fileutil.DIR_PERMS)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = ioutil.WriteFile(outputPath, bytes, fileutil.FILE_PERMS)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (m *Mixer) Inspect(printFunctions bool) {\n\tprintln(\"\\tRewriters:\")\n\tfor _, rewriter := range m.Rewriters {\n\t\tfmt.Printf(\"\\t\\t -- %v\\n\", null.GetString(rewriter.Path))\n\t}\n\n\tprintln(\"\\tRoot Package:\")\n\tfmt.Printf(m.packageSummary(printFunctions))\n}\n\nfunc (m *Mixer) Unpack(path string) {\n\tfullPath := filepath.Join(path, null.GetString(m.Name)+\"-\"+null.GetString(m.Version))\n\terr := os.MkdirAll(fullPath, 0755)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\terr = m.unpackFiles(filepath.Join(fullPath, \"rewriters\"), m.Rewriters)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsummary := m.packageSummary(true)\n\tpackageFile := filepath.Join(fullPath, \"package-summary.txt\")\n\n\terr = ioutil.WriteFile(packageFile, []byte(summary), 0644)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Warning : Couldn't write package summary\")\n\t}\n\n\tfmt.Printf(\"* %v\\n\", packageFile)\n}\n\nfunc (m *Mixer) unpackFiles(path string, files []*File) (err error) {\n\tfl := &FileList{\n\t\tRootDirectory: path,\n\t\tFiles:         files,\n\t}\n\n\terr = fl.Unpack(true)\n\n\treturn\n}\n\nfunc (m *Mixer) packageSummary(printFunctions bool) string {\n\tsummary := \"\"\n\tif m.Package != nil {\n\t\tsummary += fmt.Sprintf(\"\\t\\t -- Name: %v\\n\", null.GetString(m.Package.Name))\n\t\tsummary += fmt.Sprintf(\"\\t\\t -- Types: %v\\n\", m.Package.Types)\n\t\tsummary += fmt.Sprintf(\"\\t\\t -- Dependencies:  %v\\n\", m.Package.Dependencies)\n\t\tif printFunctions {\n\t\t\tsummary += fmt.Sprintf(\"\\t\\t -- Functions (%v):\\n\", len(m.Package.Functions))\n\t\t\tfor _, function := range m.Package.Functions {\n\t\t\t\tsummary += fmt.Sprintf(\"\\t\\t\\t %v\\n\", function.Stub(m.Package))\n\t\t\t}\n\t\t}\n\t}\n\treturn summary\n}\n<|endoftext|>"}
{"text":"<commit_before>package govkbot\n\nimport (\n\t\"log\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tvkAPIURL        = \"https:\/\/api.vk.com\/method\/\"\n\tvkAPIVer        = \"5.52\"\n\tmessagesCount   = 200\n\trequestInterval = 400 \/\/ 3 requests per second VK limit\n)\n\n\/\/ VKBot - bot config\ntype VKBot struct {\n\tmsgRoutes        map[string]func(*Message) string\n\tactionRoutes     map[string]func(*Message) string\n\tcmdHandlers      map[string]func(*Message) string\n\tmsgHandlers      map[string]func(*Message) string\n\terrorHandler     func(*Message, error)\n\tLastMsg          int\n\tmarkedMessages   map[int]*Message\n\tlastUserMessages map[int]int\n\tlastChatMessages map[int]int\n\tautoFriend       bool\n}\n\nvar bot = newBot()\n\n\/\/API - bot API\nvar API = newAPI()\n\n\/\/ SetDebug - enable\/disable debug messages logging\nfunc SetDebug(debug bool) {\n\tAPI.DEBUG = debug\n}\n\nfunc newBot() *VKBot {\n\treturn &VKBot{\n\t\tmsgRoutes:        make(map[string]func(*Message) string),\n\t\tactionRoutes:     make(map[string]func(*Message) string),\n\t\tmarkedMessages:   make(map[int]*Message),\n\t\tlastUserMessages: make(map[int]int),\n\t\tlastChatMessages: make(map[int]int),\n\t}\n}\n\nfunc newAPI() *VkAPI {\n\treturn &VkAPI{\n\t\tToken:           \"\",\n\t\tURL:             vkAPIURL,\n\t\tVer:             vkAPIVer,\n\t\tMessagesCount:   messagesCount,\n\t\tRequestInterval: requestInterval,\n\t\tDEBUG:           false,\n\t\tHTTPS:           true,\n\t}\n}\n\n\/\/ SetToken - set bot token\nfunc SetToken(token string) {\n\tAPI.Token = token\n}\n\n\/\/ SetAutoFriend - enables mutual auto friending\nfunc SetAutoFriend(af bool) {\n\tbot.autoFriend = af\n}\n\n\/\/ SetAPI - setup API config\nfunc SetAPI(token string, url string, ver string) {\n\tSetToken(token)\n\tif url != \"\" {\n\t\tAPI.URL = url\n\t}\n\tif ver != \"\" {\n\t\tAPI.Ver = ver\n\t}\n}\n\n\/\/ SetLang - sets VK response language. Default auto. Available: en, ru, ua, be, es, fi, de, it\nfunc SetLang(lang string) {\n\tAPI.Lang = lang\n}\n\n\/\/ HandleMessage - add substr message handler.\n\/\/ Function must return string to reply or \"\" (if no reply)\n\/\/ You can use m.Reply(string), if need more replies in handler\nfunc HandleMessage(command string, handler func(*Message) string) {\n\tbot.msgRoutes[command] = handler\n}\n\n\/\/ HandleAction - add action handler.\n\/\/ Function must return string to reply or \"\" (if no reply)\n\/\/ You can use m.Reply(string), if need more replies in handler\nfunc HandleAction(command string, handler func(*Message) string) {\n\tbot.actionRoutes[command] = handler\n}\n\n\/\/ HandleError - add error handler\nfunc HandleError(handler func(*Message, error)) {\n\tbot.errorHandler = handler\n}\n\n\/\/ GetMessages - request unread messages from VK (more than 200)\nfunc GetMessages() ([]*Message, error) {\n\tvar allMessages []*Message\n\tlastMsg := bot.LastMsg\n\toffset := 0\n\tvar err error\n\tvar messages *Messages\n\tfor {\n\t\tmessages, err = API.GetMessages(API.MessagesCount, offset)\n\t\tif len(messages.Items) > 0 {\n\t\t\tif messages.Items[0].ID > lastMsg {\n\t\t\t\tlastMsg = messages.Items[0].ID\n\t\t\t}\n\t\t}\n\t\tallMessages = append(allMessages, messages.Items...)\n\t\tif bot.LastMsg > 0 {\n\t\t\tif len(messages.Items) > 0 {\n\t\t\t\tif messages.Items[len(messages.Items)-1].ID <= bot.LastMsg {\n\t\t\t\t\tbot.LastMsg = lastMsg\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\toffset += API.MessagesCount\n\t\t} else {\n\t\t\tbot.LastMsg = lastMsg\n\t\t\tbreak\n\t\t}\n\t}\n\tif offset > 0 {\n\t\tAPI.NotifyAdmin(\"many messages in interval. offset: \" + strconv.Itoa(offset))\n\t}\n\treturn allMessages, err\n}\n\nfunc sendError(msg *Message, err error) {\n\tif bot.errorHandler != nil {\n\t\tbot.errorHandler(msg, err)\n\t} else {\n\t\tlog.Fatalf(\"VKBot error: %+v\\n\", err.Error())\n\t}\n\n}\n\n\/\/RouteAction routes an action\nfunc RouteAction(m *Message) (replies []string, err error) {\n\tif m.Action != \"\" {\n\t\tdebugPrint(\"route action: %+v\\n\", m.Action)\n\t\tfor k, v := range bot.actionRoutes {\n\t\t\tif m.Action == k {\n\t\t\t\tbot.markedMessages[m.ID] = m\n\t\t\t\tmsg := v(m)\n\t\t\t\tif msg != \"\" {\n\t\t\t\t\treplies = append(replies, msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn replies, nil\n}\n\n\/\/ RouteMessage routes single message\nfunc RouteMessage(m *Message) (replies []string, err error) {\n\tmessage := strings.TrimSpace(strings.ToLower(m.Body))\n\tif HasPrefix(message, \"\/ \") {\n\t\tmessage = \"\/\" + TrimPrefix(message, \"\/ \")\n\t}\n\tif m.Action != \"\" {\n\t\treplies, err = RouteAction(m)\n\t\treturn replies, err\n\t}\n\tmarked := false\n\tfor k, v := range bot.msgRoutes {\n\t\tif HasPrefix(message, k) {\n\t\t\tmsg := v(m)\n\t\t\tif msg != \"\" {\n\t\t\t\tmarked = true\n\t\t\t\t_, ok := bot.markedMessages[m.ID]\n\t\t\t\tif ok {\n\t\t\t\t\tdelete(bot.markedMessages, m.ID)\n\t\t\t\t}\n\t\t\t\treplies = append(replies, msg)\n\t\t\t} else {\n\t\t\t\tif !marked {\n\t\t\t\t\tbot.markedMessages[m.ID] = m\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn replies, nil\n}\n\n\/\/ RouteMessages routes inbound messages\nfunc RouteMessages(messages []*Message) (result map[*Message][]string) {\n\tresult = make(map[*Message][]string)\n\tfor _, m := range messages {\n\t\t\/\/if m.ID <= bot.LastMsg {\n\t\t\/\/\tbreak\n\t\t\/\/}\n\t\tif m.ReadState == 0 {\n\t\t\treplies, err := RouteMessage(m)\n\t\t\tif err != nil {\n\t\t\t\tsendError(m, err)\n\t\t\t}\n\t\t\tif len(replies) > 0 {\n\t\t\t\tresult[m] = replies\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\n\/\/ MainRoute - main router func. Working cycle Listen.\nfunc MainRoute() {\n\tbot.markedMessages = make(map[int]*Message)\n\tmessages, err := GetMessages()\n\tif err != nil {\n\t\tsendError(nil, err)\n\t}\n\treplies := RouteMessages(messages)\n\tfor m, msgs := range replies {\n\t\tfor _, msg := range msgs {\n\t\t\tif msg != \"\" {\n\t\t\t\t_, err = m.Reply(msg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tsendError(m, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, m := range bot.markedMessages {\n\t\tm.MarkAsRead()\n\t}\n}\n\n\/\/ Listen - start server\nfunc Listen(token string, url string, ver string, adminID int) {\n\tSetAPI(token, url, ver)\n\tAPI.AdminID = adminID\n\tu, err := API.Me()\n\tif err != nil {\n\t\tsendError(nil, err)\n\t}\n\tAPI.UID = u.ID\n\n\tgo friendReceiver()\n\n\tc := time.Tick(3 * time.Second)\n\tfor range c {\n\t\tMainRoute()\n\t}\n}\n\n\/\/ CheckFriends checking friend invites and mathes and deletes mutual\nfunc CheckFriends() {\n\tuids, _ := API.GetFriendRequests(false)\n\tif len(uids) > 0 {\n\t\tfor _, uid := range uids {\n\t\t\tAPI.AddFriend(uid)\n\t\t\tfor k, v := range bot.actionRoutes {\n\t\t\t\tif k == \"friend_add\" {\n\t\t\t\t\tm := Message{Action: \"friend_add\", UserID: uid}\n\t\t\t\t\tv(&m)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tuids, _ = API.GetFriendRequests(true)\n\tif len(uids) > 0 {\n\t\tfor _, uid := range uids {\n\t\t\tAPI.DeleteFriend(uid)\n\t\t\tfor k, v := range bot.actionRoutes {\n\t\t\t\tif k == \"friend_delete\" {\n\t\t\t\t\tm := Message{Action: \"friend_delete\", UserID: uid}\n\t\t\t\t\tv(&m)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc friendReceiver() {\n\tCheckFriends()\n\tc := time.Tick(30 * time.Second)\n\tfor range c {\n\t\tCheckFriends()\n\t}\n}\n\n\/\/ NotifyAdmin - notify AdminID by VK\nfunc NotifyAdmin(msg string) error {\n\treturn API.NotifyAdmin(msg)\n}\n<commit_msg>log message if error<commit_after>package govkbot\n\nimport (\n\t\"log\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tvkAPIURL        = \"https:\/\/api.vk.com\/method\/\"\n\tvkAPIVer        = \"5.52\"\n\tmessagesCount   = 200\n\trequestInterval = 400 \/\/ 3 requests per second VK limit\n)\n\n\/\/ VKBot - bot config\ntype VKBot struct {\n\tmsgRoutes        map[string]func(*Message) string\n\tactionRoutes     map[string]func(*Message) string\n\tcmdHandlers      map[string]func(*Message) string\n\tmsgHandlers      map[string]func(*Message) string\n\terrorHandler     func(*Message, error)\n\tLastMsg          int\n\tmarkedMessages   map[int]*Message\n\tlastUserMessages map[int]int\n\tlastChatMessages map[int]int\n\tautoFriend       bool\n}\n\nvar bot = newBot()\n\n\/\/API - bot API\nvar API = newAPI()\n\n\/\/ SetDebug - enable\/disable debug messages logging\nfunc SetDebug(debug bool) {\n\tAPI.DEBUG = debug\n}\n\nfunc newBot() *VKBot {\n\treturn &VKBot{\n\t\tmsgRoutes:        make(map[string]func(*Message) string),\n\t\tactionRoutes:     make(map[string]func(*Message) string),\n\t\tmarkedMessages:   make(map[int]*Message),\n\t\tlastUserMessages: make(map[int]int),\n\t\tlastChatMessages: make(map[int]int),\n\t}\n}\n\nfunc newAPI() *VkAPI {\n\treturn &VkAPI{\n\t\tToken:           \"\",\n\t\tURL:             vkAPIURL,\n\t\tVer:             vkAPIVer,\n\t\tMessagesCount:   messagesCount,\n\t\tRequestInterval: requestInterval,\n\t\tDEBUG:           false,\n\t\tHTTPS:           true,\n\t}\n}\n\n\/\/ SetToken - set bot token\nfunc SetToken(token string) {\n\tAPI.Token = token\n}\n\n\/\/ SetAutoFriend - enables mutual auto friending\nfunc SetAutoFriend(af bool) {\n\tbot.autoFriend = af\n}\n\n\/\/ SetAPI - setup API config\nfunc SetAPI(token string, url string, ver string) {\n\tSetToken(token)\n\tif url != \"\" {\n\t\tAPI.URL = url\n\t}\n\tif ver != \"\" {\n\t\tAPI.Ver = ver\n\t}\n}\n\n\/\/ SetLang - sets VK response language. Default auto. Available: en, ru, ua, be, es, fi, de, it\nfunc SetLang(lang string) {\n\tAPI.Lang = lang\n}\n\n\/\/ HandleMessage - add substr message handler.\n\/\/ Function must return string to reply or \"\" (if no reply)\n\/\/ You can use m.Reply(string), if need more replies in handler\nfunc HandleMessage(command string, handler func(*Message) string) {\n\tbot.msgRoutes[command] = handler\n}\n\n\/\/ HandleAction - add action handler.\n\/\/ Function must return string to reply or \"\" (if no reply)\n\/\/ You can use m.Reply(string), if need more replies in handler\nfunc HandleAction(command string, handler func(*Message) string) {\n\tbot.actionRoutes[command] = handler\n}\n\n\/\/ HandleError - add error handler\nfunc HandleError(handler func(*Message, error)) {\n\tbot.errorHandler = handler\n}\n\n\/\/ GetMessages - request unread messages from VK (more than 200)\nfunc GetMessages() ([]*Message, error) {\n\tvar allMessages []*Message\n\tlastMsg := bot.LastMsg\n\toffset := 0\n\tvar err error\n\tvar messages *Messages\n\tfor {\n\t\tmessages, err = API.GetMessages(API.MessagesCount, offset)\n\t\tif len(messages.Items) > 0 {\n\t\t\tif messages.Items[0].ID > lastMsg {\n\t\t\t\tlastMsg = messages.Items[0].ID\n\t\t\t}\n\t\t}\n\t\tallMessages = append(allMessages, messages.Items...)\n\t\tif bot.LastMsg > 0 {\n\t\t\tif len(messages.Items) > 0 {\n\t\t\t\tif messages.Items[len(messages.Items)-1].ID <= bot.LastMsg {\n\t\t\t\t\tbot.LastMsg = lastMsg\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\toffset += API.MessagesCount\n\t\t} else {\n\t\t\tbot.LastMsg = lastMsg\n\t\t\tbreak\n\t\t}\n\t}\n\tif offset > 0 {\n\t\tAPI.NotifyAdmin(\"many messages in interval. offset: \" + strconv.Itoa(offset))\n\t}\n\treturn allMessages, err\n}\n\nfunc sendError(msg *Message, err error) {\n\tif bot.errorHandler != nil {\n\t\tbot.errorHandler(msg, err)\n\t} else {\n\t\tlog.Fatalf(\"VKBot error: %+v\\n\", err.Error())\n\t}\n\n}\n\n\/\/RouteAction routes an action\nfunc RouteAction(m *Message) (replies []string, err error) {\n\tif m.Action != \"\" {\n\t\tdebugPrint(\"route action: %+v\\n\", m.Action)\n\t\tfor k, v := range bot.actionRoutes {\n\t\t\tif m.Action == k {\n\t\t\t\tbot.markedMessages[m.ID] = m\n\t\t\t\tmsg := v(m)\n\t\t\t\tif msg != \"\" {\n\t\t\t\t\treplies = append(replies, msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn replies, nil\n}\n\n\/\/ RouteMessage routes single message\nfunc RouteMessage(m *Message) (replies []string, err error) {\n\tmessage := strings.TrimSpace(strings.ToLower(m.Body))\n\tif HasPrefix(message, \"\/ \") {\n\t\tmessage = \"\/\" + TrimPrefix(message, \"\/ \")\n\t}\n\tif m.Action != \"\" {\n\t\treplies, err = RouteAction(m)\n\t\treturn replies, err\n\t}\n\tmarked := false\n\tfor k, v := range bot.msgRoutes {\n\t\tif HasPrefix(message, k) {\n\t\t\tmsg := v(m)\n\t\t\tif msg != \"\" {\n\t\t\t\tmarked = true\n\t\t\t\t_, ok := bot.markedMessages[m.ID]\n\t\t\t\tif ok {\n\t\t\t\t\tdelete(bot.markedMessages, m.ID)\n\t\t\t\t}\n\t\t\t\treplies = append(replies, msg)\n\t\t\t} else {\n\t\t\t\tif !marked {\n\t\t\t\t\tbot.markedMessages[m.ID] = m\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn replies, nil\n}\n\n\/\/ RouteMessages routes inbound messages\nfunc RouteMessages(messages []*Message) (result map[*Message][]string) {\n\tresult = make(map[*Message][]string)\n\tfor _, m := range messages {\n\t\t\/\/if m.ID <= bot.LastMsg {\n\t\t\/\/\tbreak\n\t\t\/\/}\n\t\tif m.ReadState == 0 {\n\t\t\treplies, err := RouteMessage(m)\n\t\t\tif err != nil {\n\t\t\t\tsendError(m, err)\n\t\t\t}\n\t\t\tif len(replies) > 0 {\n\t\t\t\tresult[m] = replies\n\t\t\t}\n\t\t}\n\t}\n\treturn result\n}\n\n\/\/ MainRoute - main router func. Working cycle Listen.\nfunc MainRoute() {\n\tbot.markedMessages = make(map[int]*Message)\n\tmessages, err := GetMessages()\n\tif err != nil {\n\t\tsendError(nil, err)\n\t}\n\treplies := RouteMessages(messages)\n\tfor m, msgs := range replies {\n\t\tfor _, msg := range msgs {\n\t\t\tif msg != \"\" {\n\t\t\t\t_, err = m.Reply(msg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error sending message: '%+v'\\n\", msg)\n\t\t\t\t\tsendError(m, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, m := range bot.markedMessages {\n\t\tm.MarkAsRead()\n\t}\n}\n\n\/\/ Listen - start server\nfunc Listen(token string, url string, ver string, adminID int) {\n\tSetAPI(token, url, ver)\n\tAPI.AdminID = adminID\n\tu, err := API.Me()\n\tif err != nil {\n\t\tsendError(nil, err)\n\t}\n\tAPI.UID = u.ID\n\n\tgo friendReceiver()\n\n\tc := time.Tick(3 * time.Second)\n\tfor range c {\n\t\tMainRoute()\n\t}\n}\n\n\/\/ CheckFriends checking friend invites and mathes and deletes mutual\nfunc CheckFriends() {\n\tuids, _ := API.GetFriendRequests(false)\n\tif len(uids) > 0 {\n\t\tfor _, uid := range uids {\n\t\t\tAPI.AddFriend(uid)\n\t\t\tfor k, v := range bot.actionRoutes {\n\t\t\t\tif k == \"friend_add\" {\n\t\t\t\t\tm := Message{Action: \"friend_add\", UserID: uid}\n\t\t\t\t\tv(&m)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tuids, _ = API.GetFriendRequests(true)\n\tif len(uids) > 0 {\n\t\tfor _, uid := range uids {\n\t\t\tAPI.DeleteFriend(uid)\n\t\t\tfor k, v := range bot.actionRoutes {\n\t\t\t\tif k == \"friend_delete\" {\n\t\t\t\t\tm := Message{Action: \"friend_delete\", UserID: uid}\n\t\t\t\t\tv(&m)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc friendReceiver() {\n\tCheckFriends()\n\tc := time.Tick(30 * time.Second)\n\tfor range c {\n\t\tCheckFriends()\n\t}\n}\n\n\/\/ NotifyAdmin - notify AdminID by VK\nfunc NotifyAdmin(msg string) error {\n\treturn API.NotifyAdmin(msg)\n}\n<|endoftext|>"}
{"text":"<commit_before>package webgo\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/\/ urlchars is regex to validate characters in a URI parameter\n\/\/ const urlchars = `([a-zA-Z0-9\\*\\-+._~!$()=&',;:@%]+)`\n\/\/ Regex prepared based on http:\/\/stackoverflow.com\/a\/4669750\/1359163,\n\/\/ https:\/\/tools.ietf.org\/html\/rfc3986\n\/\/ Though the current one allows invalid characters in the URI parameter, it has better performance.\nconst (\n\turlchars            = `([^\/]+)`\n\turlwildcard         = `(.*)`\n\ttrailingSlash       = `[\\\/]?`\n\terrMultiHeaderWrite = `http: multiple response.WriteHeader calls`\n\terrMultiWrite       = `http: multiple response.Write calls`\n\terrDuplicateKey     = `Error: Duplicate URI keys found`\n)\n\nvar validHTTPMethods = []string{\n\thttp.MethodOptions,\n\thttp.MethodHead,\n\thttp.MethodGet,\n\thttp.MethodPost,\n\thttp.MethodPut,\n\thttp.MethodPatch,\n\thttp.MethodDelete,\n}\n\ntype ctxkey string\n\nconst wgoCtxKey = ctxkey(\"webgocontext\")\n\n\/\/ customResponseWriter is a custom HTTP response writer\ntype customResponseWriter struct {\n\thttp.ResponseWriter\n\tstatusCode int\n\twritten    bool\n}\n\n\/\/ WriteHeader is the interface implementation to get HTTP response code and add\n\/\/ it to the custom response writer\nfunc (crw *customResponseWriter) WriteHeader(code int) {\n\tif crw.written {\n\t\twarnLogger.Println(errMultiHeaderWrite)\n\t\treturn\n\t}\n\n\tcrw.statusCode = code\n\tcrw.ResponseWriter.WriteHeader(code)\n}\n\n\/\/ Write is the interface implementation to respond to the HTTP request,\n\/\/ but check if a response was already sent.\nfunc (crw *customResponseWriter) Write(body []byte) (int, error) {\n\tif crw.written {\n\t\twarnLogger.Println(errMultiWrite)\n\t\treturn 0, nil\n\t}\n\n\tcrw.written = true\n\treturn crw.ResponseWriter.Write(body)\n}\n\n\/\/ Route defines a route for each API\ntype Route struct {\n\t\/\/ Name is unique identifier for the route\n\tName string\n\t\/\/ Method is the HTTP request method\/type\n\tMethod string\n\t\/\/ Pattern is the URI pattern to match\n\tPattern string\n\t\/\/ TrailingSlash if set to true, the URI will be matched with or without\n\t\/\/ a trailing slash. Note: It does not *do* a redirect.\n\tTrailingSlash bool\n\n\t\/\/ FallThroughPostResponse if enabled will execute all the handlers even if a response was already sent to the client\n\tFallThroughPostResponse bool\n\n\t\/\/ Handlers is a slice of http.HandlerFunc which can be middlewares or anything else. Though only 1 of them will be allowed to respond to client.\n\t\/\/ subsequent writes from the following handlers will be ignored\n\tHandlers []http.HandlerFunc\n\n\t\/\/ uriKeys is the list of URI parameter variables available for this route\n\turiKeys []string\n\t\/\/ uriPatternString is the pattern string which is compiled to regex object\n\turiPatternString string\n\t\/\/ uriPattern is the compiled regex to match the URI pattern\n\turiPattern *regexp.Regexp\n}\n\n\/\/ init prepares the URIKeys, compile regex for the provided pattern\nfunc (r *Route) init() error {\n\tpatternString := r.Pattern\n\n\tif strings.Contains(r.Pattern, \":\") {\n\t\t\/\/ uriValues is a map of URI Key and it's respective value,\n\t\t\/\/ this is calculated per request\n\t\tkey := \"\"\n\t\thasKey := false\n\t\thasWildcard := false\n\n\t\tfor i := 0; i < len(r.Pattern); i++ {\n\t\t\tchar := string(r.Pattern[i])\n\n\t\t\tif char == \":\" {\n\t\t\t\thasKey = true\n\t\t\t} else if char == \"*\" {\n\t\t\t\thasWildcard = true\n\t\t\t} else if hasKey && char != \"\/\" {\n\t\t\t\tkey += char\n\t\t\t} else if hasKey && len(key) > 0 {\n\t\t\t\tregexPattern := \"\"\n\t\t\t\tpatternKey := \"\"\n\t\t\t\tif hasWildcard {\n\t\t\t\t\tpatternKey = fmt.Sprintf(\":%s*\", key)\n\t\t\t\t\tregexPattern = urlwildcard\n\t\t\t\t} else {\n\t\t\t\t\tpatternKey = fmt.Sprintf(\":%s\", key)\n\t\t\t\t\tregexPattern = urlchars\n\t\t\t\t}\n\n\t\t\t\tpatternString = strings.Replace(patternString, patternKey, regexPattern, 1)\n\n\t\t\t\tfor idx, k := range r.uriKeys {\n\t\t\t\t\tif key == k {\n\t\t\t\t\t\terrLogger.Fatalln(errDuplicateKey, \"\\nURI: \", r.Pattern, \"\\nKey:\", k, \", Position:\", idx+1)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tr.uriKeys = append(r.uriKeys, key)\n\n\t\t\t\thasWildcard, hasKey = false, false\n\t\t\t\tkey = \"\"\n\t\t\t}\n\t\t}\n\n\t\tif hasKey && len(key) > 0 {\n\t\t\tregexPattern := \"\"\n\t\t\tpatternKey := \"\"\n\t\t\tif hasWildcard {\n\t\t\t\tpatternKey = fmt.Sprintf(\":%s*\", key)\n\t\t\t\tregexPattern = urlwildcard\n\t\t\t} else {\n\t\t\t\tpatternKey = fmt.Sprintf(\":%s\", key)\n\t\t\t\tregexPattern = urlchars\n\t\t\t}\n\n\t\t\tpatternString = strings.Replace(patternString, patternKey, regexPattern, 1)\n\n\t\t\tfor idx, k := range r.uriKeys {\n\t\t\t\tif key == k {\n\t\t\t\t\terrLogger.Fatalln(errDuplicateKey, \"\\nURI: \", r.Pattern, \"\\nKey:\", k, \", Position:\", idx+1)\n\t\t\t\t}\n\t\t\t}\n\t\t\tr.uriKeys = append(r.uriKeys, key)\n\t\t}\n\n\t}\n\n\tif r.TrailingSlash {\n\t\tpatternString = fmt.Sprintf(\"^%s%s$\", patternString, trailingSlash)\n\t} else {\n\t\tpatternString = fmt.Sprintf(\"^%s$\", patternString)\n\t}\n\n\t\/\/ compile the regex for the pattern string calculated\n\treg, err := regexp.Compile(patternString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.uriPattern = reg\n\tr.uriPatternString = patternString\n\treturn nil\n}\n\n\/\/ matchAndGet returns if the request URI matches the pattern defined in a Route as well as\n\/\/ all the URI parameters configured for the route.\nfunc (r *Route) matchAndGet(requestURI string) (bool, map[string]string) {\n\tif r.Pattern == requestURI {\n\t\treturn true, nil\n\t}\n\n\tif !r.uriPattern.Match([]byte(requestURI)) {\n\t\treturn false, nil\n\t}\n\n\t\/\/ Getting URI parameters\n\tvalues := r.uriPattern.FindStringSubmatch(requestURI)\n\tif len(values) == 0 {\n\t\treturn true, nil\n\t}\n\n\turiValues := make(map[string]string, len(values)-1)\n\tfor i := 1; i < len(values); i++ {\n\t\turiValues[r.uriKeys[i-1]] = values[i]\n\t}\n\treturn true, uriValues\n\n}\n\n\/\/ Router is the HTTP router\ntype Router struct {\n\toptHandlers    []*Route\n\theadHandlers   []*Route\n\tgetHandlers    []*Route\n\tpostHandlers   []*Route\n\tputHandlers    []*Route\n\tpatchHandlers  []*Route\n\tdeleteHandlers []*Route\n\n\t\/\/ NotFound is the generic handler for 404 resource not found response\n\tNotFound http.HandlerFunc\n\t\/\/ AppContext holds all the app specific context which is to be injected into all HTTP\n\t\/\/ request context\n\tAppContext map[string]interface{}\n\n\t\/\/ config has all the app config\n\tconfig       *Config\n\tserveHandler http.HandlerFunc\n\t\/\/ httpServer is the server handler for the active HTTP server\n\thttpServer *http.Server\n\t\/\/ httpsServer is the server handler for the active HTTPS server\n\thttpsServer *http.Server\n}\n\nfunc (rtr *Router) serve(rw http.ResponseWriter, req *http.Request) {\n\tvar rr []*Route\n\n\tswitch req.Method {\n\tcase http.MethodOptions:\n\t\trr = rtr.optHandlers\n\tcase http.MethodHead:\n\t\trr = rtr.headHandlers\n\tcase http.MethodGet:\n\t\trr = rtr.getHandlers\n\tcase http.MethodPost:\n\t\trr = rtr.postHandlers\n\tcase http.MethodPut:\n\t\trr = rtr.putHandlers\n\tcase http.MethodPatch:\n\t\trr = rtr.patchHandlers\n\tcase http.MethodDelete:\n\t\trr = rtr.deleteHandlers\n\t}\n\n\tvar route *Route\n\tok := false\n\tparams := make(map[string]string, 0)\n\tpath := req.URL.EscapedPath()\n\tfor _, r := range rr {\n\t\tif ok, params = r.matchAndGet(path); ok {\n\t\t\troute = r\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !ok {\n\t\t\/\/ serve 404 when there are no matching routes\n\t\trtr.NotFound(rw, req)\n\t\treturn\n\t}\n\n\tcrw := &customResponseWriter{\n\t\tResponseWriter: rw,\n\t}\n\t\/\/ webgo context object created and is injected to the request context\n\treqwc := req.WithContext(\n\t\tcontext.WithValue(\n\t\t\treq.Context(),\n\t\t\twgoCtxKey,\n\t\t\t&WC{\n\t\t\t\tParams:     params,\n\t\t\t\tRoute:      route,\n\t\t\t\tAppContext: rtr.AppContext,\n\t\t\t},\n\t\t),\n\t)\n\n\tfor _, handler := range route.Handlers {\n\t\tif crw.written == false {\n\t\t\t\/\/ If there has been no write to response writer yet\n\t\t\thandler(crw, reqwc)\n\t\t} else if route.FallThroughPostResponse {\n\t\t\t\/\/ run a handler post response write, only if fall through is enabled\n\t\t\thandler(crw, reqwc)\n\t\t} else {\n\t\t\t\/\/ Do not run any more handlers if already responded and no fall through enabled\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n\/\/ ServeHTTP is the required `ServeHTTP` implementation to listen to HTTP requests\nfunc (rtr *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\trtr.serveHandler(rw, req)\n}\n\n\/\/ Use adds a middleware layer\nfunc (rtr *Router) Use(f func(http.ResponseWriter, *http.Request, http.HandlerFunc)) {\n\tsrv := rtr.serveHandler\n\trtr.serveHandler = func(rw http.ResponseWriter, req *http.Request) {\n\t\tf(rw, req, srv)\n\t}\n}\n\n\/\/ NewRouter initializes returns a new router instance with all the configurations and routes set\nfunc NewRouter(cfg *Config, routes []*Route) *Router {\n\thandlers := make(map[string][]*Route, len(validHTTPMethods))\n\n\tfor _, validMethod := range validHTTPMethods {\n\t\thandlers[validMethod] = []*Route{}\n\t}\n\n\tfor idx, route := range routes {\n\t\tfound := false\n\t\tfor _, validMethod := range validHTTPMethods {\n\t\t\tif route.Method == validMethod {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\terrLogger.Fatalln(\"Unsupported HTTP request method provided. Method:\", route.Method)\n\t\t}\n\n\t\tif route.Handlers == nil || len(route.Handlers) == 0 {\n\t\t\terrLogger.Fatalln(\"No handlers provided for the route '\", route.Pattern, \"', method '\", route.Method, \"'\")\n\t\t}\n\n\t\terr := route.init()\n\t\tif err != nil {\n\t\t\terrLogger.Fatalln(\"Unsupported URI pattern.\", route.Pattern, err)\n\t\t}\n\n\t\t\/\/ checking if the URI pattern is duplicated\n\t\tfor i := 0; i < idx; i++ {\n\t\t\trt := routes[i]\n\n\t\t\tif rt.Name == route.Name {\n\t\t\t\twarnLogger.Println(\"Duplicate route name(\\\"\" + rt.Name + \"\\\") detected. Route name should be unique.\")\n\t\t\t}\n\n\t\t\tif rt.Method == route.Method {\n\t\t\t\t\/\/ regex pattern match\n\t\t\t\tif ok, _ := rt.matchAndGet(route.Pattern); ok {\n\t\t\t\t\twarnLogger.Println(\"Duplicate URI pattern detected.\\nPattern: '\" + rt.Pattern + \"'\\nDuplicate pattern: '\" + route.Pattern + \"'\")\n\t\t\t\t\tinfoLogger.Println(\"Only the first route to match the URI pattern would handle the request\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\thandlers[route.Method] = append(handlers[route.Method], route)\n\t}\n\n\tr := &Router{\n\t\toptHandlers:    handlers[http.MethodOptions],\n\t\theadHandlers:   handlers[http.MethodHead],\n\t\tgetHandlers:    handlers[http.MethodGet],\n\t\tpostHandlers:   handlers[http.MethodPost],\n\t\tputHandlers:    handlers[http.MethodPut],\n\t\tpatchHandlers:  handlers[http.MethodPatch],\n\t\tdeleteHandlers: handlers[http.MethodDelete],\n\n\t\tNotFound:   http.NotFound,\n\t\tAppContext: make(map[string]interface{}, 0),\n\t\tconfig:     cfg,\n\t}\n\t\/\/ setting the default serve handler\n\tr.serveHandler = r.serve\n\n\treturn r\n}\n<commit_msg>updated route init to reduce cyclo complexity.<commit_after>package webgo\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/\/ urlchars is regex to validate characters in a URI parameter\n\/\/ const urlchars = `([a-zA-Z0-9\\*\\-+._~!$()=&',;:@%]+)`\n\/\/ Regex prepared based on http:\/\/stackoverflow.com\/a\/4669750\/1359163,\n\/\/ https:\/\/tools.ietf.org\/html\/rfc3986\n\/\/ Though the current one allows invalid characters in the URI parameter, it has better performance.\nconst (\n\turlchars            = `([^\/]+)`\n\turlwildcard         = `(.*)`\n\ttrailingSlash       = `[\\\/]?`\n\terrMultiHeaderWrite = `http: multiple response.WriteHeader calls`\n\terrMultiWrite       = `http: multiple response.Write calls`\n\terrDuplicateKey     = `Error: Duplicate URI keys found`\n)\n\nvar validHTTPMethods = []string{\n\thttp.MethodOptions,\n\thttp.MethodHead,\n\thttp.MethodGet,\n\thttp.MethodPost,\n\thttp.MethodPut,\n\thttp.MethodPatch,\n\thttp.MethodDelete,\n}\n\ntype ctxkey string\n\nconst wgoCtxKey = ctxkey(\"webgocontext\")\n\n\/\/ customResponseWriter is a custom HTTP response writer\ntype customResponseWriter struct {\n\thttp.ResponseWriter\n\tstatusCode int\n\twritten    bool\n}\n\n\/\/ WriteHeader is the interface implementation to get HTTP response code and add\n\/\/ it to the custom response writer\nfunc (crw *customResponseWriter) WriteHeader(code int) {\n\tif crw.written {\n\t\twarnLogger.Println(errMultiHeaderWrite)\n\t\treturn\n\t}\n\n\tcrw.statusCode = code\n\tcrw.ResponseWriter.WriteHeader(code)\n}\n\n\/\/ Write is the interface implementation to respond to the HTTP request,\n\/\/ but check if a response was already sent.\nfunc (crw *customResponseWriter) Write(body []byte) (int, error) {\n\tif crw.written {\n\t\twarnLogger.Println(errMultiWrite)\n\t\treturn 0, nil\n\t}\n\n\tcrw.written = true\n\treturn crw.ResponseWriter.Write(body)\n}\n\n\/\/ Route defines a route for each API\ntype Route struct {\n\t\/\/ Name is unique identifier for the route\n\tName string\n\t\/\/ Method is the HTTP request method\/type\n\tMethod string\n\t\/\/ Pattern is the URI pattern to match\n\tPattern string\n\t\/\/ TrailingSlash if set to true, the URI will be matched with or without\n\t\/\/ a trailing slash. Note: It does not *do* a redirect.\n\tTrailingSlash bool\n\n\t\/\/ FallThroughPostResponse if enabled will execute all the handlers even if a response was already sent to the client\n\tFallThroughPostResponse bool\n\n\t\/\/ Handlers is a slice of http.HandlerFunc which can be middlewares or anything else. Though only 1 of them will be allowed to respond to client.\n\t\/\/ subsequent writes from the following handlers will be ignored\n\tHandlers []http.HandlerFunc\n\n\t\/\/ uriKeys is the list of URI parameter variables available for this route\n\turiKeys []string\n\t\/\/ uriPatternString is the pattern string which is compiled to regex object\n\turiPatternString string\n\t\/\/ uriPattern is the compiled regex to match the URI pattern\n\turiPattern *regexp.Regexp\n}\n\n\/\/ computerPatternStr computes the pattern string required for the route's regex.\n\/\/ It also adds the URI parameter key to the route's `keys` field\nfunc (r *Route) computerPatternStr(patternString string, hasWildcard bool, key string) string {\n\tregexPattern := \"\"\n\tpatternKey := \"\"\n\tif hasWildcard {\n\t\tpatternKey = fmt.Sprintf(\":%s*\", key)\n\t\tregexPattern = urlwildcard\n\t} else {\n\t\tpatternKey = fmt.Sprintf(\":%s\", key)\n\t\tregexPattern = urlchars\n\t}\n\n\tpatternString = strings.Replace(patternString, patternKey, regexPattern, 1)\n\n\tfor idx, k := range r.uriKeys {\n\t\tif key == k {\n\t\t\terrLogger.Fatalln(errDuplicateKey, \"\\nURI: \", r.Pattern, \"\\nKey:\", k, \", Position:\", idx+1)\n\t\t}\n\t}\n\n\tr.uriKeys = append(r.uriKeys, key)\n\treturn patternString\n}\n\n\/\/ init prepares the URIKeys, compile regex for the provided pattern\nfunc (r *Route) init() error {\n\tpatternString := r.Pattern\n\n\tif strings.Contains(r.Pattern, \":\") {\n\t\t\/\/ uriValues is a map of URI Key and it's respective value,\n\t\t\/\/ this is calculated per request\n\t\tkey := \"\"\n\t\thasKey := false\n\t\thasWildcard := false\n\n\t\tfor i := 0; i < len(r.Pattern); i++ {\n\t\t\tchar := string(r.Pattern[i])\n\n\t\t\tif char == \":\" {\n\t\t\t\thasKey = true\n\t\t\t} else if char == \"*\" {\n\t\t\t\thasWildcard = true\n\t\t\t} else if hasKey && char != \"\/\" {\n\t\t\t\tkey += char\n\t\t\t} else if hasKey && len(key) > 0 {\n\t\t\t\tpatternString = r.computerPatternStr(patternString, hasWildcard, key)\n\t\t\t\thasWildcard, hasKey = false, false\n\t\t\t\tkey = \"\"\n\t\t\t}\n\t\t}\n\n\t\tif hasKey && len(key) > 0 {\n\t\t\tpatternString = r.computerPatternStr(patternString, hasWildcard, key)\n\t\t}\n\n\t}\n\n\tif r.TrailingSlash {\n\t\tpatternString = fmt.Sprintf(\"^%s%s$\", patternString, trailingSlash)\n\t} else {\n\t\tpatternString = fmt.Sprintf(\"^%s$\", patternString)\n\t}\n\n\t\/\/ compile the regex for the pattern string calculated\n\treg, err := regexp.Compile(patternString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.uriPattern = reg\n\tr.uriPatternString = patternString\n\treturn nil\n}\n\n\/\/ matchAndGet returns if the request URI matches the pattern defined in a Route as well as\n\/\/ all the URI parameters configured for the route.\nfunc (r *Route) matchAndGet(requestURI string) (bool, map[string]string) {\n\tif r.Pattern == requestURI {\n\t\treturn true, nil\n\t}\n\n\tif !r.uriPattern.Match([]byte(requestURI)) {\n\t\treturn false, nil\n\t}\n\n\t\/\/ Getting URI parameters\n\tvalues := r.uriPattern.FindStringSubmatch(requestURI)\n\tif len(values) == 0 {\n\t\treturn true, nil\n\t}\n\n\turiValues := make(map[string]string, len(values)-1)\n\tfor i := 1; i < len(values); i++ {\n\t\turiValues[r.uriKeys[i-1]] = values[i]\n\t}\n\treturn true, uriValues\n\n}\n\n\/\/ Router is the HTTP router\ntype Router struct {\n\toptHandlers    []*Route\n\theadHandlers   []*Route\n\tgetHandlers    []*Route\n\tpostHandlers   []*Route\n\tputHandlers    []*Route\n\tpatchHandlers  []*Route\n\tdeleteHandlers []*Route\n\n\t\/\/ NotFound is the generic handler for 404 resource not found response\n\tNotFound http.HandlerFunc\n\t\/\/ AppContext holds all the app specific context which is to be injected into all HTTP\n\t\/\/ request context\n\tAppContext map[string]interface{}\n\n\t\/\/ config has all the app config\n\tconfig       *Config\n\tserveHandler http.HandlerFunc\n\t\/\/ httpServer is the server handler for the active HTTP server\n\thttpServer *http.Server\n\t\/\/ httpsServer is the server handler for the active HTTPS server\n\thttpsServer *http.Server\n}\n\nfunc (rtr *Router) serve(rw http.ResponseWriter, req *http.Request) {\n\tvar rr []*Route\n\n\tswitch req.Method {\n\tcase http.MethodOptions:\n\t\trr = rtr.optHandlers\n\tcase http.MethodHead:\n\t\trr = rtr.headHandlers\n\tcase http.MethodGet:\n\t\trr = rtr.getHandlers\n\tcase http.MethodPost:\n\t\trr = rtr.postHandlers\n\tcase http.MethodPut:\n\t\trr = rtr.putHandlers\n\tcase http.MethodPatch:\n\t\trr = rtr.patchHandlers\n\tcase http.MethodDelete:\n\t\trr = rtr.deleteHandlers\n\t}\n\n\tvar route *Route\n\tok := false\n\tparams := make(map[string]string, 0)\n\tpath := req.URL.EscapedPath()\n\tfor _, r := range rr {\n\t\tif ok, params = r.matchAndGet(path); ok {\n\t\t\troute = r\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !ok {\n\t\t\/\/ serve 404 when there are no matching routes\n\t\trtr.NotFound(rw, req)\n\t\treturn\n\t}\n\n\tcrw := &customResponseWriter{\n\t\tResponseWriter: rw,\n\t}\n\t\/\/ webgo context object created and is injected to the request context\n\treqwc := req.WithContext(\n\t\tcontext.WithValue(\n\t\t\treq.Context(),\n\t\t\twgoCtxKey,\n\t\t\t&WC{\n\t\t\t\tParams:     params,\n\t\t\t\tRoute:      route,\n\t\t\t\tAppContext: rtr.AppContext,\n\t\t\t},\n\t\t),\n\t)\n\n\tfor _, handler := range route.Handlers {\n\t\tif crw.written == false {\n\t\t\t\/\/ If there has been no write to response writer yet\n\t\t\thandler(crw, reqwc)\n\t\t} else if route.FallThroughPostResponse {\n\t\t\t\/\/ run a handler post response write, only if fall through is enabled\n\t\t\thandler(crw, reqwc)\n\t\t} else {\n\t\t\t\/\/ Do not run any more handlers if already responded and no fall through enabled\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n\/\/ ServeHTTP is the required `ServeHTTP` implementation to listen to HTTP requests\nfunc (rtr *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\trtr.serveHandler(rw, req)\n}\n\n\/\/ Use adds a middleware layer\nfunc (rtr *Router) Use(f func(http.ResponseWriter, *http.Request, http.HandlerFunc)) {\n\tsrv := rtr.serveHandler\n\trtr.serveHandler = func(rw http.ResponseWriter, req *http.Request) {\n\t\tf(rw, req, srv)\n\t}\n}\n\n\/\/ NewRouter initializes returns a new router instance with all the configurations and routes set\nfunc NewRouter(cfg *Config, routes []*Route) *Router {\n\thandlers := make(map[string][]*Route, len(validHTTPMethods))\n\n\tfor _, validMethod := range validHTTPMethods {\n\t\thandlers[validMethod] = []*Route{}\n\t}\n\n\tfor idx, route := range routes {\n\t\tfound := false\n\t\tfor _, validMethod := range validHTTPMethods {\n\t\t\tif route.Method == validMethod {\n\t\t\t\tfound = true\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\terrLogger.Fatalln(\"Unsupported HTTP request method provided. Method:\", route.Method)\n\t\t}\n\n\t\tif route.Handlers == nil || len(route.Handlers) == 0 {\n\t\t\terrLogger.Fatalln(\"No handlers provided for the route '\", route.Pattern, \"', method '\", route.Method, \"'\")\n\t\t}\n\n\t\terr := route.init()\n\t\tif err != nil {\n\t\t\terrLogger.Fatalln(\"Unsupported URI pattern.\", route.Pattern, err)\n\t\t}\n\n\t\t\/\/ checking if the URI pattern is duplicated\n\t\tfor i := 0; i < idx; i++ {\n\t\t\trt := routes[i]\n\n\t\t\tif rt.Name == route.Name {\n\t\t\t\twarnLogger.Println(\"Duplicate route name(\\\"\" + rt.Name + \"\\\") detected. Route name should be unique.\")\n\t\t\t}\n\n\t\t\tif rt.Method == route.Method {\n\t\t\t\t\/\/ regex pattern match\n\t\t\t\tif ok, _ := rt.matchAndGet(route.Pattern); ok {\n\t\t\t\t\twarnLogger.Println(\"Duplicate URI pattern detected.\\nPattern: '\" + rt.Pattern + \"'\\nDuplicate pattern: '\" + route.Pattern + \"'\")\n\t\t\t\t\tinfoLogger.Println(\"Only the first route to match the URI pattern would handle the request\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\thandlers[route.Method] = append(handlers[route.Method], route)\n\t}\n\n\tr := &Router{\n\t\toptHandlers:    handlers[http.MethodOptions],\n\t\theadHandlers:   handlers[http.MethodHead],\n\t\tgetHandlers:    handlers[http.MethodGet],\n\t\tpostHandlers:   handlers[http.MethodPost],\n\t\tputHandlers:    handlers[http.MethodPut],\n\t\tpatchHandlers:  handlers[http.MethodPatch],\n\t\tdeleteHandlers: handlers[http.MethodDelete],\n\n\t\tNotFound:   http.NotFound,\n\t\tAppContext: make(map[string]interface{}, 0),\n\t\tconfig:     cfg,\n\t}\n\t\/\/ setting the default serve handler\n\tr.serveHandler = r.serve\n\n\treturn r\n}\n<|endoftext|>"}
{"text":"<commit_before>package air\n\nimport (\n\t\"strings\"\n\t\"unsafe\"\n)\n\n\/\/ router is a registry of all registered routes.\ntype router struct {\n\ttree      *node\n\tmaxParams int\n}\n\n\/\/ routerSingleton is the singleton of the `router`.\nvar routerSingleton = &router{\n\ttree: &node{\n\t\thandlers: map[string]Handler{},\n\t},\n}\n\n\/\/ register registers a new route for the method and the path with the matching\n\/\/ h in the r with the optional route-level gases..\nfunc (r *router) register(method, path string, h Handler, gases ...Gas) {\n\tif path != \"\/\" && hasLastSlash(path) {\n\t\tpath = path[:len(path)-1]\n\t}\n\n\tif path == \"\" {\n\t\tpanic(\"air: the path cannot be empty\")\n\t} else if path[0] != '\/' {\n\t\tpanic(\"air: the path must start with the \/\")\n\t} else if strings.Contains(path, \"\/\/\") {\n\t\tpanic(\"air: the path cannot have the \/\/\")\n\t} else if strings.Count(path, \":\") > 1 {\n\t\tps := strings.Split(path, \"\/\")\n\t\tfor _, p := range ps {\n\t\t\tif strings.Count(p, \":\") > 1 {\n\t\t\t\tpanic(\"air: adjacent params in the path must \" +\n\t\t\t\t\t\"be separated by the \/\")\n\t\t\t}\n\t\t}\n\t} else if strings.Contains(path, \"*\") {\n\t\tif strings.Count(path, \"*\") > 1 {\n\t\t\tpanic(\"air: only one * is allowed in the path\")\n\t\t} else if path[len(path)-1] != '*' {\n\t\t\tpanic(\"air: the * can only appear at the end of the \" +\n\t\t\t\t\"path\")\n\t\t} else if strings.Contains(\n\t\t\tpath[strings.LastIndex(path, \"\/\"):],\n\t\t\t\":\",\n\t\t) {\n\t\t\tpanic(\"air: adjacent param and the * in the path \" +\n\t\t\t\t\"must be separated by the \/\")\n\t\t}\n\t}\n\n\tnh := func(req *Request, res *Response) error {\n\t\th := h\n\t\tfor i := len(gases) - 1; i >= 0; i-- {\n\t\t\th = gases[i](h)\n\t\t}\n\t\treturn h(req, res)\n\t}\n\n\tparamNames := []string{}\n\n\tfor i, l := 0, len(path); i < l; i++ {\n\t\tif path[i] == ':' {\n\t\t\tj := i + 1\n\n\t\t\tr.insert(method, path[:i], nil, staticKind, nil)\n\n\t\t\tfor ; i < l && path[i] != '\/'; i++ {\n\t\t\t}\n\n\t\t\tparamName := path[j:i]\n\n\t\t\tfor _, pn := range paramNames {\n\t\t\t\tif pn == paramName {\n\t\t\t\t\tpanic(\"air: the path cannot have \" +\n\t\t\t\t\t\t\"duplicate param names\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tparamNames = append(paramNames, paramName)\n\t\t\tpath = path[:j] + path[i:]\n\n\t\t\tif i, l = j, len(path); i == l {\n\t\t\t\tr.insert(method, path, nh, paramKind, paramNames)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tr.insert(method, path[:i], nil, paramKind, paramNames)\n\t\t} else if path[i] == '*' {\n\t\t\tr.insert(method, path[:i], nil, staticKind, nil)\n\t\t\tparamNames = append(paramNames, \"*\")\n\t\t\tr.insert(method, path[:i+1], nh, anyKind, paramNames)\n\t\t\treturn\n\t\t}\n\t}\n\n\tr.insert(method, path, nh, staticKind, paramNames)\n}\n\n\/\/ insert inserts a new route into the `tree` of the r.\nfunc (r *router) insert(\n\tmethod,\n\tpath string,\n\th Handler,\n\tnk uint8,\n\tparamNames []string,\n) {\n\tif l := len(paramNames); l > r.maxParams {\n\t\tr.maxParams = l\n\t}\n\n\tcn := r.tree \/\/ Current node as the root of the `tree` of the r\n\n\tvar (\n\t\ts   = path \/\/ Search\n\t\tnn  *node  \/\/ Next node\n\t\tsl  int    \/\/ Search length\n\t\tpl  int    \/\/ Prefix length\n\t\tll  int    \/\/ LCP length\n\t\tmax int    \/\/ Max number of sl and pl\n\t)\n\n\tfor {\n\t\tsl = len(s)\n\t\tpl = len(cn.prefix)\n\t\tll = 0\n\n\t\tmax = pl\n\t\tif sl < max {\n\t\t\tmax = sl\n\t\t}\n\n\t\tfor ; ll < max && s[ll] == cn.prefix[ll]; ll++ {\n\t\t}\n\n\t\tif ll == 0 {\n\t\t\t\/\/ At root node\n\t\t\tcn.label = s[0]\n\t\t\tcn.prefix = s\n\t\t\tif h != nil {\n\t\t\t\tcn.kind = nk\n\t\t\t\tcn.handlers[method] = h\n\t\t\t\tcn.paramNames = paramNames\n\t\t\t}\n\t\t} else if ll < pl {\n\t\t\t\/\/ Split node\n\t\t\tnn = &node{\n\t\t\t\tkind:       cn.kind,\n\t\t\t\tlabel:      cn.prefix[ll],\n\t\t\t\tprefix:     cn.prefix[ll:],\n\t\t\t\thandlers:   cn.handlers,\n\t\t\t\tparent:     cn,\n\t\t\t\tchildren:   cn.children,\n\t\t\t\tparamNames: cn.paramNames,\n\t\t\t}\n\n\t\t\t\/\/ Reset parent node\n\t\t\tcn.kind = staticKind\n\t\t\tcn.label = cn.prefix[0]\n\t\t\tcn.prefix = cn.prefix[:ll]\n\t\t\tcn.children = nil\n\t\t\tcn.handlers = map[string]Handler{}\n\t\t\tcn.paramNames = nil\n\t\t\tcn.children = append(cn.children, nn)\n\n\t\t\tif ll == sl {\n\t\t\t\t\/\/ At parent node\n\t\t\t\tcn.kind = nk\n\t\t\t\tcn.handlers[method] = h\n\t\t\t\tcn.paramNames = paramNames\n\t\t\t} else {\n\t\t\t\t\/\/ Create child node\n\t\t\t\tnn = &node{\n\t\t\t\t\tkind:       nk,\n\t\t\t\t\tlabel:      s[ll],\n\t\t\t\t\tprefix:     s[ll:],\n\t\t\t\t\thandlers:   map[string]Handler{},\n\t\t\t\t\tparent:     cn,\n\t\t\t\t\tparamNames: paramNames,\n\t\t\t\t}\n\t\t\t\tnn.handlers[method] = h\n\t\t\t\tcn.children = append(cn.children, nn)\n\t\t\t}\n\t\t} else if ll < sl {\n\t\t\ts = s[ll:]\n\n\t\t\tif nn = cn.childByLabel(s[0]); nn != nil {\n\t\t\t\t\/\/ Go deeper\n\t\t\t\tcn = nn\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ Create child node\n\t\t\tnn = &node{\n\t\t\t\tkind:       nk,\n\t\t\t\tlabel:      s[0],\n\t\t\t\tprefix:     s,\n\t\t\t\thandlers:   map[string]Handler{},\n\t\t\t\tparent:     cn,\n\t\t\t\tparamNames: paramNames,\n\t\t\t}\n\t\t\tnn.handlers[method] = h\n\t\t\tcn.children = append(cn.children, nn)\n\t\t} else if h != nil {\n\t\t\t\/\/ Node already exists\n\t\t\tcn.handlers[method] = h\n\t\t\tcn.paramNames = paramNames\n\t\t}\n\n\t\treturn\n\t}\n}\n\n\/\/ route returns a handler registered for the req.\nfunc (r *router) route(req *Request) Handler {\n\tcn := r.tree \/\/ Current node as root of the `tree` of the r\n\n\tvar (\n\t\ts   = pathClean(req.URL.Path)        \/\/ Search\n\t\tnn  *node                            \/\/ Next node\n\t\tnk  uint8                            \/\/ Next kind\n\t\tsn  *node                            \/\/ Saved node\n\t\tss  string                           \/\/ Saved search\n\t\tsl  int                              \/\/ Search length\n\t\tpl  int                              \/\/ Prefix length\n\t\tll  int                              \/\/ LCP length\n\t\tmax int                              \/\/ Max number of sl and pl\n\t\tsi  int                              \/\/ Start index\n\t\tpvs = make([]string, 0, r.maxParams) \/\/ Param values\n\t)\n\n\t\/\/ Search order: static > param > any\n\tfor {\n\t\tif s == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tpl = 0\n\t\tll = 0\n\n\t\tif cn.label != ':' {\n\t\t\tsl = len(s)\n\t\t\tpl = len(cn.prefix)\n\n\t\t\tmax = pl\n\t\t\tif sl < max {\n\t\t\t\tmax = sl\n\t\t\t}\n\n\t\t\tfor ; ll < max && s[ll] == cn.prefix[ll]; ll++ {\n\t\t\t}\n\t\t}\n\n\t\tif ll != pl {\n\t\t\tgoto Struggle\n\t\t}\n\n\t\tif s = s[ll:]; s == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Static node\n\t\tif nn = cn.child(s[0], staticKind); nn != nil {\n\t\t\t\/\/ Save next\n\t\t\tif hasLastSlash(cn.prefix) {\n\t\t\t\tnk = paramKind\n\t\t\t\tsn = cn\n\t\t\t\tss = s\n\t\t\t}\n\n\t\t\tcn = nn\n\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Param node\n\tParam:\n\t\tif nn = cn.childByKind(paramKind); nn != nil {\n\t\t\t\/\/ Save next\n\t\t\tif hasLastSlash(cn.prefix) {\n\t\t\t\tnk = anyKind\n\t\t\t\tsn = cn\n\t\t\t\tss = s\n\t\t\t}\n\n\t\t\tcn = nn\n\n\t\t\tfor si = 0; si < len(s) && s[si] != '\/'; si++ {\n\t\t\t}\n\n\t\t\tpvs = append(pvs, unescape(s[:si]))\n\t\t\ts = s[si:]\n\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Any node\n\tAny:\n\t\tif cn = cn.childByKind(anyKind); cn != nil {\n\t\t\tif hasLastSlash(req.URL.Path) {\n\t\t\t\tsi = len(req.URL.Path) - 1\n\t\t\t\tfor ; si > 0 && req.URL.Path[si] == '\/'; si-- {\n\t\t\t\t}\n\t\t\t\ts += req.URL.Path[si+1:]\n\t\t\t}\n\n\t\t\tif len(pvs) < len(cn.paramNames) {\n\t\t\t\tpvs = append(pvs, unescape(s))\n\t\t\t} else {\n\t\t\t\tpvs[len(cn.paramNames)-1] = unescape(s)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Struggle for the former node\n\tStruggle:\n\t\tif sn != nil {\n\t\t\tcn = sn\n\t\t\tsn = nil\n\t\t\ts = ss\n\n\t\t\tswitch nk {\n\t\t\tcase paramKind:\n\t\t\t\tgoto Param\n\t\t\tcase anyKind:\n\t\t\t\tgoto Any\n\t\t\t}\n\t\t}\n\n\t\treturn NotFoundHandler\n\t}\n\n\tif handler := cn.handlers[req.Method]; handler != nil {\n\t\tfor i := range pvs {\n\t\t\treq.PathParams[cn.paramNames[i]] = pvs[i]\n\t\t}\n\t\treturn handler\n\t} else if len(cn.handlers) != 0 {\n\t\treturn MethodNotAllowedHandler\n\t}\n\n\treturn NotFoundHandler\n}\n\n\/\/ hasLastSlash reports whether the s has the last '\/'.\nfunc hasLastSlash(s string) bool {\n\treturn len(s) > 0 && s[len(s)-1] == '\/'\n}\n\n\/\/ pathWithoutParamNames returns a path from the p without the param names.\nfunc pathWithoutParamNames(p string) string {\n\tfor i, l := 0, len(p); i < l; i++ {\n\t\tif p[i] == ':' {\n\t\t\tj := i + 1\n\n\t\t\tfor ; i < l && p[i] != '\/'; i++ {\n\t\t\t}\n\n\t\t\tp = p[:j] + p[i:]\n\t\t\ti, l = j, len(p)\n\n\t\t\tif i == l {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn p\n}\n\n\/\/ pathClean returns a clean path from the p.\nfunc pathClean(p string) string {\n\tif p == \"\" {\n\t\treturn \"\/\"\n\t}\n\n\tb := make([]byte, 0, len(p))\n\n\ti, l := 0, len(p)\n\tif p[0] == '\/' {\n\t\ti = 1\n\t}\n\n\tfor i < l {\n\t\tif p[i] == '\/' {\n\t\t\ti++\n\t\t} else {\n\t\t\tb = append(b, '\/')\n\t\t\tfor ; i < l && p[i] != '\/'; i++ {\n\t\t\t\tb = append(b, p[i])\n\t\t\t}\n\t\t}\n\t}\n\n\treturn *(*string)(unsafe.Pointer(&b))\n}\n\n\/\/ unescape return a normal string unescaped from the s.\nfunc unescape(s string) string {\n\t\/\/ Count the %, check that they're well-formed.\n\tn := 0\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] == '%' {\n\t\t\tn++\n\t\t\tif i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {\n\t\t\t\ts = s[i:]\n\t\t\t\tif len(s) > 3 {\n\t\t\t\t\ts = s[:3]\n\t\t\t\t}\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\ti += 2\n\t\t}\n\t}\n\n\tif n == 0 {\n\t\treturn s\n\t}\n\n\tt := make([]byte, len(s)-2*n)\n\tfor i, j := 0, 0; i < len(s); i++ {\n\t\tswitch s[i] {\n\t\tcase '%':\n\t\t\tt[j] = unhex(s[i+1])<<4 | unhex(s[i+2])\n\t\t\tj++\n\t\t\ti += 2\n\t\tcase '+':\n\t\t\tt[j] = ' '\n\t\t\tj++\n\t\tdefault:\n\t\t\tt[j] = s[i]\n\t\t\tj++\n\t\t}\n\t}\n\treturn string(t)\n}\n\n\/\/ ishex reports whether the c is hex.\nfunc ishex(c byte) bool {\n\tswitch {\n\tcase '0' <= c && c <= '9':\n\t\treturn true\n\tcase 'a' <= c && c <= 'f':\n\t\treturn true\n\tcase 'A' <= c && c <= 'F':\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ unhex returns the normal byte from the hex char c.\nfunc unhex(c byte) byte {\n\tswitch {\n\tcase '0' <= c && c <= '9':\n\t\treturn c - '0'\n\tcase 'a' <= c && c <= 'f':\n\t\treturn c - 'a' + 10\n\tcase 'A' <= c && c <= 'F':\n\t\treturn c - 'A' + 10\n\t}\n\treturn 0\n}\n\n\/\/ node is the node of the radix tree.\ntype node struct {\n\tkind       uint8\n\tlabel      byte\n\tprefix     string\n\thandlers   map[string]Handler\n\tparent     *node\n\tchildren   []*node\n\tparamNames []string\n}\n\n\/\/ node kinds\nconst (\n\tstaticKind uint8 = iota\n\tparamKind\n\tanyKind\n)\n\n\/\/ child returns a child `node` of the n by the label and the kind.\nfunc (n *node) child(label byte, kind uint8) *node {\n\tfor _, c := range n.children {\n\t\tif c.label == label && c.kind == kind {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ childByLabel returns a child `node` of the n by the l.\nfunc (n *node) childByLabel(l byte) *node {\n\tfor _, c := range n.children {\n\t\tif c.label == l {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ childByKind returns a child `node` of the n by the k.\nfunc (n *node) childByKind(k uint8) *node {\n\tfor _, c := range n.children {\n\t\tif c.kind == k {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>feat: add `nodeKind`<commit_after>package air\n\nimport (\n\t\"strings\"\n\t\"unsafe\"\n)\n\n\/\/ router is a registry of all registered routes.\ntype router struct {\n\ttree      *node\n\tmaxParams int\n}\n\n\/\/ routerSingleton is the singleton of the `router`.\nvar routerSingleton = &router{\n\ttree: &node{\n\t\thandlers: map[string]Handler{},\n\t},\n}\n\n\/\/ register registers a new route for the method and the path with the matching\n\/\/ h in the r with the optional route-level gases..\nfunc (r *router) register(method, path string, h Handler, gases ...Gas) {\n\tif path != \"\/\" && hasLastSlash(path) {\n\t\tpath = path[:len(path)-1]\n\t}\n\n\tif path == \"\" {\n\t\tpanic(\"air: the path cannot be empty\")\n\t} else if path[0] != '\/' {\n\t\tpanic(\"air: the path must start with the \/\")\n\t} else if strings.Contains(path, \"\/\/\") {\n\t\tpanic(\"air: the path cannot have the \/\/\")\n\t} else if strings.Count(path, \":\") > 1 {\n\t\tps := strings.Split(path, \"\/\")\n\t\tfor _, p := range ps {\n\t\t\tif strings.Count(p, \":\") > 1 {\n\t\t\t\tpanic(\"air: adjacent params in the path must \" +\n\t\t\t\t\t\"be separated by the \/\")\n\t\t\t}\n\t\t}\n\t} else if strings.Contains(path, \"*\") {\n\t\tif strings.Count(path, \"*\") > 1 {\n\t\t\tpanic(\"air: only one * is allowed in the path\")\n\t\t} else if path[len(path)-1] != '*' {\n\t\t\tpanic(\"air: the * can only appear at the end of the \" +\n\t\t\t\t\"path\")\n\t\t} else if strings.Contains(\n\t\t\tpath[strings.LastIndex(path, \"\/\"):],\n\t\t\t\":\",\n\t\t) {\n\t\t\tpanic(\"air: adjacent param and the * in the path \" +\n\t\t\t\t\"must be separated by the \/\")\n\t\t}\n\t}\n\n\tnh := func(req *Request, res *Response) error {\n\t\th := h\n\t\tfor i := len(gases) - 1; i >= 0; i-- {\n\t\t\th = gases[i](h)\n\t\t}\n\t\treturn h(req, res)\n\t}\n\n\tparamNames := []string{}\n\n\tfor i, l := 0, len(path); i < l; i++ {\n\t\tif path[i] == ':' {\n\t\t\tj := i + 1\n\n\t\t\tr.insert(method, path[:i], nil, static, nil)\n\n\t\t\tfor ; i < l && path[i] != '\/'; i++ {\n\t\t\t}\n\n\t\t\tparamName := path[j:i]\n\n\t\t\tfor _, pn := range paramNames {\n\t\t\t\tif pn == paramName {\n\t\t\t\t\tpanic(\"air: the path cannot have \" +\n\t\t\t\t\t\t\"duplicate param names\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tparamNames = append(paramNames, paramName)\n\t\t\tpath = path[:j] + path[i:]\n\n\t\t\tif i, l = j, len(path); i == l {\n\t\t\t\tr.insert(method, path, nh, param, paramNames)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tr.insert(method, path[:i], nil, param, paramNames)\n\t\t} else if path[i] == '*' {\n\t\t\tr.insert(method, path[:i], nil, static, nil)\n\t\t\tparamNames = append(paramNames, \"*\")\n\t\t\tr.insert(method, path[:i+1], nh, any, paramNames)\n\t\t\treturn\n\t\t}\n\t}\n\n\tr.insert(method, path, nh, static, paramNames)\n}\n\n\/\/ insert inserts a new route into the `tree` of the r.\nfunc (r *router) insert(\n\tmethod,\n\tpath string,\n\th Handler,\n\tnk nodeKind,\n\tparamNames []string,\n) {\n\tif l := len(paramNames); l > r.maxParams {\n\t\tr.maxParams = l\n\t}\n\n\tcn := r.tree \/\/ Current node as the root of the `tree` of the r\n\n\tvar (\n\t\ts   = path \/\/ Search\n\t\tnn  *node  \/\/ Next node\n\t\tsl  int    \/\/ Search length\n\t\tpl  int    \/\/ Prefix length\n\t\tll  int    \/\/ LCP length\n\t\tmax int    \/\/ Max number of sl and pl\n\t)\n\n\tfor {\n\t\tsl = len(s)\n\t\tpl = len(cn.prefix)\n\t\tll = 0\n\n\t\tmax = pl\n\t\tif sl < max {\n\t\t\tmax = sl\n\t\t}\n\n\t\tfor ; ll < max && s[ll] == cn.prefix[ll]; ll++ {\n\t\t}\n\n\t\tif ll == 0 {\n\t\t\t\/\/ At root node\n\t\t\tcn.label = s[0]\n\t\t\tcn.prefix = s\n\t\t\tif h != nil {\n\t\t\t\tcn.kind = nk\n\t\t\t\tcn.handlers[method] = h\n\t\t\t\tcn.paramNames = paramNames\n\t\t\t}\n\t\t} else if ll < pl {\n\t\t\t\/\/ Split node\n\t\t\tnn = &node{\n\t\t\t\tkind:       cn.kind,\n\t\t\t\tlabel:      cn.prefix[ll],\n\t\t\t\tprefix:     cn.prefix[ll:],\n\t\t\t\thandlers:   cn.handlers,\n\t\t\t\tparent:     cn,\n\t\t\t\tchildren:   cn.children,\n\t\t\t\tparamNames: cn.paramNames,\n\t\t\t}\n\n\t\t\t\/\/ Reset parent node\n\t\t\tcn.kind = static\n\t\t\tcn.label = cn.prefix[0]\n\t\t\tcn.prefix = cn.prefix[:ll]\n\t\t\tcn.children = nil\n\t\t\tcn.handlers = map[string]Handler{}\n\t\t\tcn.paramNames = nil\n\t\t\tcn.children = append(cn.children, nn)\n\n\t\t\tif ll == sl {\n\t\t\t\t\/\/ At parent node\n\t\t\t\tcn.kind = nk\n\t\t\t\tcn.handlers[method] = h\n\t\t\t\tcn.paramNames = paramNames\n\t\t\t} else {\n\t\t\t\t\/\/ Create child node\n\t\t\t\tnn = &node{\n\t\t\t\t\tkind:       nk,\n\t\t\t\t\tlabel:      s[ll],\n\t\t\t\t\tprefix:     s[ll:],\n\t\t\t\t\thandlers:   map[string]Handler{},\n\t\t\t\t\tparent:     cn,\n\t\t\t\t\tparamNames: paramNames,\n\t\t\t\t}\n\t\t\t\tnn.handlers[method] = h\n\t\t\t\tcn.children = append(cn.children, nn)\n\t\t\t}\n\t\t} else if ll < sl {\n\t\t\ts = s[ll:]\n\n\t\t\tif nn = cn.childByLabel(s[0]); nn != nil {\n\t\t\t\t\/\/ Go deeper\n\t\t\t\tcn = nn\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ Create child node\n\t\t\tnn = &node{\n\t\t\t\tkind:       nk,\n\t\t\t\tlabel:      s[0],\n\t\t\t\tprefix:     s,\n\t\t\t\thandlers:   map[string]Handler{},\n\t\t\t\tparent:     cn,\n\t\t\t\tparamNames: paramNames,\n\t\t\t}\n\t\t\tnn.handlers[method] = h\n\t\t\tcn.children = append(cn.children, nn)\n\t\t} else if h != nil {\n\t\t\t\/\/ Node already exists\n\t\t\tcn.handlers[method] = h\n\t\t\tcn.paramNames = paramNames\n\t\t}\n\n\t\treturn\n\t}\n}\n\n\/\/ route returns a handler registered for the req.\nfunc (r *router) route(req *Request) Handler {\n\tcn := r.tree \/\/ Current node as root of the `tree` of the r\n\n\tvar (\n\t\ts   = pathClean(req.URL.Path)        \/\/ Search\n\t\tnn  *node                            \/\/ Next node\n\t\tnk  nodeKind                         \/\/ Next kind\n\t\tsn  *node                            \/\/ Saved node\n\t\tss  string                           \/\/ Saved search\n\t\tsl  int                              \/\/ Search length\n\t\tpl  int                              \/\/ Prefix length\n\t\tll  int                              \/\/ LCP length\n\t\tmax int                              \/\/ Max number of sl and pl\n\t\tsi  int                              \/\/ Start index\n\t\tpvs = make([]string, 0, r.maxParams) \/\/ Param values\n\t)\n\n\t\/\/ Search order: static > param > any\n\tfor {\n\t\tif s == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tpl = 0\n\t\tll = 0\n\n\t\tif cn.label != ':' {\n\t\t\tsl = len(s)\n\t\t\tpl = len(cn.prefix)\n\n\t\t\tmax = pl\n\t\t\tif sl < max {\n\t\t\t\tmax = sl\n\t\t\t}\n\n\t\t\tfor ; ll < max && s[ll] == cn.prefix[ll]; ll++ {\n\t\t\t}\n\t\t}\n\n\t\tif ll != pl {\n\t\t\tgoto Struggle\n\t\t}\n\n\t\tif s = s[ll:]; s == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Static node\n\t\tif nn = cn.child(s[0], static); nn != nil {\n\t\t\t\/\/ Save next\n\t\t\tif hasLastSlash(cn.prefix) {\n\t\t\t\tnk = param\n\t\t\t\tsn = cn\n\t\t\t\tss = s\n\t\t\t}\n\n\t\t\tcn = nn\n\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Param node\n\tParam:\n\t\tif nn = cn.childByKind(param); nn != nil {\n\t\t\t\/\/ Save next\n\t\t\tif hasLastSlash(cn.prefix) {\n\t\t\t\tnk = any\n\t\t\t\tsn = cn\n\t\t\t\tss = s\n\t\t\t}\n\n\t\t\tcn = nn\n\n\t\t\tfor si = 0; si < len(s) && s[si] != '\/'; si++ {\n\t\t\t}\n\n\t\t\tpvs = append(pvs, unescape(s[:si]))\n\t\t\ts = s[si:]\n\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Any node\n\tAny:\n\t\tif cn = cn.childByKind(any); cn != nil {\n\t\t\tif hasLastSlash(req.URL.Path) {\n\t\t\t\tsi = len(req.URL.Path) - 1\n\t\t\t\tfor ; si > 0 && req.URL.Path[si] == '\/'; si-- {\n\t\t\t\t}\n\t\t\t\ts += req.URL.Path[si+1:]\n\t\t\t}\n\n\t\t\tif len(pvs) < len(cn.paramNames) {\n\t\t\t\tpvs = append(pvs, unescape(s))\n\t\t\t} else {\n\t\t\t\tpvs[len(cn.paramNames)-1] = unescape(s)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Struggle for the former node\n\tStruggle:\n\t\tif sn != nil {\n\t\t\tcn = sn\n\t\t\tsn = nil\n\t\t\ts = ss\n\n\t\t\tswitch nk {\n\t\t\tcase param:\n\t\t\t\tgoto Param\n\t\t\tcase any:\n\t\t\t\tgoto Any\n\t\t\t}\n\t\t}\n\n\t\treturn NotFoundHandler\n\t}\n\n\tif handler := cn.handlers[req.Method]; handler != nil {\n\t\tfor i := range pvs {\n\t\t\treq.PathParams[cn.paramNames[i]] = pvs[i]\n\t\t}\n\t\treturn handler\n\t} else if len(cn.handlers) != 0 {\n\t\treturn MethodNotAllowedHandler\n\t}\n\n\treturn NotFoundHandler\n}\n\n\/\/ hasLastSlash reports whether the s has the last '\/'.\nfunc hasLastSlash(s string) bool {\n\treturn len(s) > 0 && s[len(s)-1] == '\/'\n}\n\n\/\/ pathWithoutParamNames returns a path from the p without the param names.\nfunc pathWithoutParamNames(p string) string {\n\tfor i, l := 0, len(p); i < l; i++ {\n\t\tif p[i] == ':' {\n\t\t\tj := i + 1\n\n\t\t\tfor ; i < l && p[i] != '\/'; i++ {\n\t\t\t}\n\n\t\t\tp = p[:j] + p[i:]\n\t\t\ti, l = j, len(p)\n\n\t\t\tif i == l {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn p\n}\n\n\/\/ pathClean returns a clean path from the p.\nfunc pathClean(p string) string {\n\tif p == \"\" {\n\t\treturn \"\/\"\n\t}\n\n\tb := make([]byte, 0, len(p))\n\n\ti, l := 0, len(p)\n\tif p[0] == '\/' {\n\t\ti = 1\n\t}\n\n\tfor i < l {\n\t\tif p[i] == '\/' {\n\t\t\ti++\n\t\t} else {\n\t\t\tb = append(b, '\/')\n\t\t\tfor ; i < l && p[i] != '\/'; i++ {\n\t\t\t\tb = append(b, p[i])\n\t\t\t}\n\t\t}\n\t}\n\n\treturn *(*string)(unsafe.Pointer(&b))\n}\n\n\/\/ unescape return a normal string unescaped from the s.\nfunc unescape(s string) string {\n\t\/\/ Count the %, check that they're well-formed.\n\tn := 0\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] == '%' {\n\t\t\tn++\n\t\t\tif i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {\n\t\t\t\ts = s[i:]\n\t\t\t\tif len(s) > 3 {\n\t\t\t\t\ts = s[:3]\n\t\t\t\t}\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\ti += 2\n\t\t}\n\t}\n\n\tif n == 0 {\n\t\treturn s\n\t}\n\n\tt := make([]byte, len(s)-2*n)\n\tfor i, j := 0, 0; i < len(s); i++ {\n\t\tswitch s[i] {\n\t\tcase '%':\n\t\t\tt[j] = unhex(s[i+1])<<4 | unhex(s[i+2])\n\t\t\tj++\n\t\t\ti += 2\n\t\tcase '+':\n\t\t\tt[j] = ' '\n\t\t\tj++\n\t\tdefault:\n\t\t\tt[j] = s[i]\n\t\t\tj++\n\t\t}\n\t}\n\treturn string(t)\n}\n\n\/\/ ishex reports whether the c is hex.\nfunc ishex(c byte) bool {\n\tswitch {\n\tcase '0' <= c && c <= '9':\n\t\treturn true\n\tcase 'a' <= c && c <= 'f':\n\t\treturn true\n\tcase 'A' <= c && c <= 'F':\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ unhex returns the normal byte from the hex char c.\nfunc unhex(c byte) byte {\n\tswitch {\n\tcase '0' <= c && c <= '9':\n\t\treturn c - '0'\n\tcase 'a' <= c && c <= 'f':\n\t\treturn c - 'a' + 10\n\tcase 'A' <= c && c <= 'F':\n\t\treturn c - 'A' + 10\n\t}\n\treturn 0\n}\n\n\/\/ node is the node of the radix tree.\ntype node struct {\n\tkind       nodeKind\n\tlabel      byte\n\tprefix     string\n\thandlers   map[string]Handler\n\tparent     *node\n\tchildren   []*node\n\tparamNames []string\n}\n\n\/\/ nodeKind is a kind of the `node`.\ntype nodeKind uint8\n\n\/\/ node kinds\nconst (\n\tstatic nodeKind = iota\n\tparam\n\tany\n)\n\n\/\/ child returns a child `node` of the n by the label and the kind.\nfunc (n *node) child(label byte, kind nodeKind) *node {\n\tfor _, c := range n.children {\n\t\tif c.label == label && c.kind == kind {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ childByLabel returns a child `node` of the n by the l.\nfunc (n *node) childByLabel(l byte) *node {\n\tfor _, c := range n.children {\n\t\tif c.label == l {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ childByKind returns a child `node` of the n by the k.\nfunc (n *node) childByKind(k nodeKind) *node {\n\tfor _, c := range n.children {\n\t\tif c.kind == k {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package amber\r\n\r\nimport (\r\n\t\"os\"\r\n\t\"fmt\"\r\n\t\"strings\"\r\n\t\"regexp\"\r\n\t\"net\/http\"\r\n\t\"reflect\"\r\n\t\"runtime\"\r\n)\r\n\r\ntype route struct {\r\n\tpattern\t\t\t\tstring\r\n\tmethod\t\t\t\tstring\r\n\tisController \tbool\r\n\tcName\t\t\t\t\tstring\r\n\tcAction\t\t\t\tstring\r\n\thandler \t\t\tHandler\r\n\trouter \t\t\t\t*router\r\n\tregex \t\t\t\t*regexp.Regexp\r\n}\r\n\r\ntype router struct {\r\n\tnamedRoutes \tmap[string]*route\r\n\troutes\t\t\t\t[]*route\r\n}\r\n\r\nfunc newRouter() *router {\r\n\treturn &router{namedRoutes: make(map[string]*route)}\r\n}\r\n\r\nfunc (r *router) AddRoute(method string, pattern string, handler Handler) *route {\r\n\troute := newRoute(method, pattern, handler, r)\r\n\tr.routes = append(r.routes, route)\r\n\r\n\tif route.isController {\r\n\t\troute.Name(cName + \"#\" + cAction)\r\n\t}\r\n\r\n\treturn route\r\n}\r\n\r\nfunc (r *router) searchRoute(method string, request string) (*route, Param) {\r\n\tfor i, route := range r.routes {\r\n\t\tmatches := route.regex.FindStringSubmatch(request)\r\n\t\tif route.method == method || method == \"Any\" {\r\n\t\t\tif len(matches) > 0 && matches[0] == request {\r\n\t\t\t\tparams := make(Param)\r\n\t\t\t\tfor i := 1; i < len(matches); i++ {\r\n\t\t\t\t\tparams[route.regex.SubexpNames()[i]] = matches[i]\r\n\t\t\t\t}\r\n\t\t\t\treturn r.routes[i], params\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn nil, nil\r\n}\r\n\r\nfunc (r *router) getReverseUrl(name string, param []interface{}) string {\r\n\troute := getNamedRoute\r\n\tnParam := len(param)\r\n\tif route != nil {\r\n\t\ti := -1\r\n\t\tregex := regexp.MustCompile(\"{.*}\")\r\n\t\turl := regex.ReplaceAllStringFunc(route.pattern, func(str string) string {\r\n\t\t\ti = i + 1\r\n\t\t\tif i <= nParam - 1 {\r\n\t\t\t\treturn param[i].(string)\r\n\t\t\t} else {\r\n\t\t\t\treturn \"\"\r\n\t\t\t}\r\n\t\t})\r\n\r\n\t\treturn url\r\n\t}\r\n\r\n\treturn \"\"\r\n}\r\n\r\nfunc (r *router) getNamedRoute(name string) *route {\r\n\treturn r.namedRoutes[strings.ToLower(name)]\r\n}\r\n\r\nfunc (r *route) Name(name string) {\r\n\tr.router.namedRoutes[strings.ToLower(name)] = r\r\n}\r\n\r\nfunc newRoute(method string, pattern string, handler Handler, router *router) *route {\r\n\tregex := regexp.MustCompile(\"{[a-zA-Z0-9]+}\")\r\n\tregexPattern := regex.ReplaceAllStringFunc(pattern, func(s string) string {\r\n\t\treturn fmt.Sprintf(\"(?P<%s>[a-z]+)\", s[1:len(s)-1])\r\n\t})\r\n\r\n\tcName := \"\"\r\n\tcAction := \"\"\r\n\tisController := false\r\n\r\n\tif isControllerHandler(handler) {\r\n\t\tvar fn *runtime.Func\r\n\t  if fn = runtime.FuncForPC(reflect.ValueOf(handler).Pointer()); fn == nil {\r\n\t\t\tlogger.Println(\"Failed to add route. Can't fetch controller function\")\r\n\t\t\treturn nil\r\n\t  }\r\n\r\n\t  isController = true\r\n\t\ttoken := strings.Split(fn.Name(), \".\")\r\n\t\tcName = token[1][2:len(token[1])-1]\r\n\t\tcAction = token[2]\r\n\t}\r\n\t\r\n\treturn &route{pattern, method, isController, cName, cAction, handler, router, regexp.MustCompile(regexPattern)}\r\n}\r\n\r\nfunc servePublic(rw http.ResponseWriter, req *http.Request) {\r\n\tvar file http.File\r\n\tvar err error\r\n\tvar stat os.FileInfo\r\n\tfname := req.URL.Path[len(\"\/public\/\"):]\r\n\r\n\tif !strings.HasPrefix(fname, \".\") {\r\n\t\tif file, err = http.Dir(\"public\").Open(fname); err == nil {\r\n\t\t\tif stat, err = file.Stat(); err == nil {\r\n\t\t\t\tif !stat.IsDir() {\r\n\t\t\t\t\thttp.ServeContent(rw, req, req.URL.Path, stat.ModTime(), file)\r\n\t\t\t\t\tfile.Close()\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\thttp.NotFound(rw, req)\r\n}<commit_msg>fixed some minor errors<commit_after>package amber\r\n\r\nimport (\r\n\t\"os\"\r\n\t\"fmt\"\r\n\t\"strings\"\r\n\t\"regexp\"\r\n\t\"net\/http\"\r\n\t\"reflect\"\r\n\t\"runtime\"\r\n)\r\n\r\ntype route struct {\r\n\tpattern\t\t\t\tstring\r\n\tmethod\t\t\t\tstring\r\n\tisController \tbool\r\n\tcName\t\t\t\t\tstring\r\n\tcAction\t\t\t\tstring\r\n\thandler \t\t\tHandler\r\n\trouter \t\t\t\t*router\r\n\tregex \t\t\t\t*regexp.Regexp\r\n}\r\n\r\ntype router struct {\r\n\tnamedRoutes \tmap[string]*route\r\n\troutes\t\t\t\t[]*route\r\n}\r\n\r\nfunc newRouter() *router {\r\n\treturn &router{namedRoutes: make(map[string]*route)}\r\n}\r\n\r\nfunc (r *router) AddRoute(method string, pattern string, handler Handler) *route {\r\n\troute := newRoute(method, pattern, handler, r)\r\n\tr.routes = append(r.routes, route)\r\n\r\n\tif route.isController {\r\n\t\troute.Name(route.cName + \"#\" + route.cAction)\r\n\t}\r\n\r\n\treturn route\r\n}\r\n\r\nfunc (r *router) searchRoute(method string, request string) (*route, Param) {\r\n\tfor i, route := range r.routes {\r\n\t\tmatches := route.regex.FindStringSubmatch(request)\r\n\t\tif route.method == method || method == \"Any\" {\r\n\t\t\tif len(matches) > 0 && matches[0] == request {\r\n\t\t\t\tparams := make(Param)\r\n\t\t\t\tfor i := 1; i < len(matches); i++ {\r\n\t\t\t\t\tparams[route.regex.SubexpNames()[i]] = matches[i]\r\n\t\t\t\t}\r\n\t\t\t\treturn r.routes[i], params\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn nil, nil\r\n}\r\n\r\nfunc (r *router) getReverseUrl(name string, param []interface{}) string {\r\n\troute := r.getNamedRoute(name)\r\n\tnParam := len(param)\r\n\tif route != nil {\r\n\t\ti := -1\r\n\t\tregex := regexp.MustCompile(\"{.*}\")\r\n\t\turl := regex.ReplaceAllStringFunc(route.pattern, func(str string) string {\r\n\t\t\ti = i + 1\r\n\t\t\tif i <= nParam - 1 {\r\n\t\t\t\treturn param[i].(string)\r\n\t\t\t} else {\r\n\t\t\t\treturn \"\"\r\n\t\t\t}\r\n\t\t})\r\n\r\n\t\treturn url\r\n\t}\r\n\r\n\treturn \"\"\r\n}\r\n\r\nfunc (r *router) getNamedRoute(name string) *route {\r\n\treturn r.namedRoutes[strings.ToLower(name)]\r\n}\r\n\r\nfunc (r *route) Name(name string) {\r\n\tr.router.namedRoutes[strings.ToLower(name)] = r\r\n}\r\n\r\nfunc newRoute(method string, pattern string, handler Handler, router *router) *route {\r\n\tregex := regexp.MustCompile(\"{[a-zA-Z0-9]+}\")\r\n\tregexPattern := regex.ReplaceAllStringFunc(pattern, func(s string) string {\r\n\t\treturn fmt.Sprintf(\"(?P<%s>[a-z]+)\", s[1:len(s)-1])\r\n\t})\r\n\r\n\tcName := \"\"\r\n\tcAction := \"\"\r\n\tisController := false\r\n\r\n\tif isControllerHandler(handler) {\r\n\t\tvar fn *runtime.Func\r\n\t  if fn = runtime.FuncForPC(reflect.ValueOf(handler).Pointer()); fn == nil {\r\n\t\t\tlogger.Println(\"Failed to add route. Can't fetch controller function\")\r\n\t\t\treturn nil\r\n\t  }\r\n\r\n\t  isController = true\r\n\t\ttoken := strings.Split(fn.Name(), \".\")\r\n\t\tcName = token[1][2:len(token[1])-1]\r\n\t\tcAction = token[2]\r\n\t}\r\n\t\r\n\treturn &route{pattern, method, isController, cName, cAction, handler, router, regexp.MustCompile(regexPattern)}\r\n}\r\n\r\nfunc servePublic(rw http.ResponseWriter, req *http.Request) {\r\n\tvar file http.File\r\n\tvar err error\r\n\tvar stat os.FileInfo\r\n\tfname := req.URL.Path[len(\"\/public\/\"):]\r\n\r\n\tif !strings.HasPrefix(fname, \".\") {\r\n\t\tif file, err = http.Dir(\"public\").Open(fname); err == nil {\r\n\t\t\tif stat, err = file.Stat(); err == nil {\r\n\t\t\t\tif !stat.IsDir() {\r\n\t\t\t\t\thttp.ServeContent(rw, req, req.URL.Path, stat.ModTime(), file)\r\n\t\t\t\t\tfile.Close()\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\thttp.NotFound(rw, req)\r\n}<|endoftext|>"}
{"text":"<commit_before>package typhon\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/julienschmidt\/httprouter\"\n\t\"github.com\/monzo\/terrors\"\n)\n\ntype Router interface {\n\t\/\/ OPTIONS is a shortcut for Register(\"OPTIONS\", svc).\n\tOPTIONS(path string, svc Service)\n\t\/\/ GET is a shortcut for Register(\"GET\", svc).\n\tGET(path string, svc Service)\n\t\/\/ HEAD is a shortcut for Register(\"HEAD\", svc).\n\tHEAD(path string, svc Service)\n\t\/\/ POST is a shortcut for Register(\"POST\", svc).\n\tPOST(path string, svc Service)\n\t\/\/ PUT is a shortcut for Register(\"PUT\", svc).\n\tPUT(path string, svc Service)\n\t\/\/ DELETE is a shortcut for Register(\"DELETE\", svc).\n\tDELETE(path string, svc Service)\n\t\/\/ TRACE is a shortcut for Register(\"TRACE\", svc).\n\tTRACE(path string, svc Service)\n\t\/\/ Register associates a Service with a method and path.\n\tRegister(method, path string, svc Service)\n\t\/\/ Lookup returns the Service and extracted path parameters for the HTTP method and path.\n\tLookup(method, path string) (svc Service, params map[string]string, ok bool)\n\t\/\/ Serve returns a Service which will route inbound requests to the enclosed routes.\n\tServe() Service\n\t\/\/ Params returns extracted URL parameters, assuming the request has been routed and has captured parameters.\n\tParams(req Request) map[string]string\n}\n\ntype router struct {\n\timpl *httprouter.Router\n}\n\nfunc NewRouter() Router {\n\treturn &router{\n\t\timpl: httprouter.New()}\n}\n\nfunc (r *router) Register(method, path string, svc Service) {\n\t\/\/ Forgive me.\n\tr.impl.Handle(method, path, func(rw_ http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\t\trw := rw_.(*routerRw)\n\t\trw.svc = svc\n\t})\n}\n\nfunc (r *router) Lookup(method, path string) (Service, map[string]string, bool) {\n\thf, params_, _ := r.impl.Lookup(method, path)\n\tif hf == nil {\n\t\treturn nil, nil, false\n\t}\n\n\tparams := make(map[string]string, len(params_))\n\tfor _, p := range params_ {\n\t\tparams[p.Key] = p.Value\n\t}\n\n\trw := routerRw{}\n\thf(&rw, nil, nil)\n\treturn rw.svc, params, true\n}\n\nfunc (r *router) Serve() Service {\n\treturn func(req Request) Response {\n\t\tsvc, _, ok := r.Lookup(req.Method, req.URL.Path)\n\t\tif !ok {\n\t\t\ttxt := fmt.Sprintf(\"No handler for %s %s\", req.Method, req.URL.Path)\n\t\t\trsp := NewResponse(req)\n\t\t\trsp.Error = terrors.NotFound(\"no_handler\", txt, nil)\n\t\t\treturn rsp\n\t\t}\n\t\treturn svc(req)\n\t}\n}\n\nfunc (r *router) Params(req Request) map[string]string {\n\t_, params, _ := r.Lookup(req.Method, req.URL.Path)\n\treturn params\n}\n\n\/\/ Sugar\nfunc (r *router) OPTIONS(path string, svc Service) { r.Register(\"OPTIONS\", path, svc) }\nfunc (r *router) GET(path string, svc Service)     { r.Register(\"GET\", path, svc) }\nfunc (r *router) HEAD(path string, svc Service)    { r.Register(\"HEAD\", path, svc) }\nfunc (r *router) POST(path string, svc Service)    { r.Register(\"POST\", path, svc) }\nfunc (r *router) PUT(path string, svc Service)     { r.Register(\"PUT\", path, svc) }\nfunc (r *router) DELETE(path string, svc Service)  { r.Register(\"DELETE\", path, svc) }\nfunc (r *router) TRACE(path string, svc Service)   { r.Register(\"TRACE\", path, svc) }\n\n\/\/ I'm sorry, dear reader, I really am. To do this properly is more work than I have the appetite for right now.\n\/\/\n\/\/ Future me will remove this horrific cruft and provide a URL router that acts on Services directly, without needing\n\/\/ the kabuki of a fake Handler and ResponseWriter.\n\/\/\n\/\/ As it is, here's the fake ResponseWriter.\ntype routerRw struct {\n\tsvc Service\n}\n\nfunc (r *routerRw) Header() http.Header         { return nil }\nfunc (r *routerRw) WriteHeader(_ int)           {}\nfunc (r *routerRw) Write(_ []byte) (int, error) { return 0, nil }\n<commit_msg>Switch router internals to use labstack\/echo<commit_after>package typhon\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/monzo\/terrors\"\n)\n\ntype Router interface {\n\t\/\/ OPTIONS is a shortcut for Register(\"OPTIONS\", svc).\n\tOPTIONS(path string, svc Service)\n\t\/\/ GET is a shortcut for Register(\"GET\", svc).\n\tGET(path string, svc Service)\n\t\/\/ HEAD is a shortcut for Register(\"HEAD\", svc).\n\tHEAD(path string, svc Service)\n\t\/\/ POST is a shortcut for Register(\"POST\", svc).\n\tPOST(path string, svc Service)\n\t\/\/ PUT is a shortcut for Register(\"PUT\", svc).\n\tPUT(path string, svc Service)\n\t\/\/ DELETE is a shortcut for Register(\"DELETE\", svc).\n\tDELETE(path string, svc Service)\n\t\/\/ TRACE is a shortcut for Register(\"TRACE\", svc).\n\tTRACE(path string, svc Service)\n\t\/\/ Register associates a Service with a method and path.\n\tRegister(method, path string, svc Service)\n\t\/\/ Lookup returns the Service and extracted path parameters for the HTTP method and path.\n\tLookup(method, path string) (svc Service, params map[string]string, ok bool)\n\t\/\/ Serve returns a Service which will route inbound requests to the enclosed routes.\n\tServe() Service\n\t\/\/ Params returns extracted URL parameters, assuming the request has been routed and has captured parameters.\n\tParams(req Request) map[string]string\n}\n\ntype router struct {\n\te    *echo.Echo\n\tr    *echo.Router\n\tsvcs map[string]Service\n\tm    sync.RWMutex\n}\n\n\/\/ NewRouter vends a new implementation of Router\nfunc NewRouter() Router {\n\te := echo.New()\n\treturn &router{\n\t\te:    e,\n\t\tr:    echo.NewRouter(e),\n\t\tsvcs: make(map[string]Service, 10)}\n}\n\nfunc (r *router) identityHandler(c echo.Context) error {\n\treturn nil\n}\n\nfunc (r *router) Register(method, path string, svc Service) {\n\tr.m.Lock()\n\tdefer r.m.Unlock()\n\tr.r.Add(method, path, r.identityHandler)\n\tr.svcs[method+path] = svc\n}\n\nfunc (r *router) Lookup(method, path string) (Service, map[string]string, bool) {\n\tc := r.e.AcquireContext()\n\tdefer r.e.ReleaseContext(c)\n\tc.Reset(nil, nil)\n\tc.SetPath(\"\") \/\/ Annoyingly, this isn't done as part of Reset()\n\n\tr.m.RLock()\n\tr.r.Find(method, path, c)\n\tif c.Path() == \"\" {\n\t\tr.m.RUnlock()\n\t\treturn nil, nil, false\n\t}\n\tsvc := r.svcs[method+c.Path()]\n\tr.m.RUnlock()\n\n\tif svc == nil {\n\t\treturn nil, nil, false\n\t}\n\n\tnames := c.ParamNames()\n\tparams := make(map[string]string, len(names))\n\tfor _, name := range names {\n\t\tparams[name] = c.Param(name)\n\t}\n\treturn svc, params, true\n\n\t\/\/ hf, params_, _ := r.impl.Lookup(method, path)\n\t\/\/ if hf == nil {\n\t\/\/ \treturn nil, nil, false\n\t\/\/ }\n\t\/\/\n\t\/\/ params := make(map[string]string, len(params_))\n\t\/\/ for _, p := range params_ {\n\t\/\/ \tparams[p.Key] = p.Value\n\t\/\/ }\n\t\/\/\n\t\/\/ rw := routerRw{}\n\t\/\/ hf(&rw, nil, nil)\n\t\/\/ return rw.svc, params, true\n}\n\nfunc (r *router) Serve() Service {\n\treturn func(req Request) Response {\n\t\tsvc, _, ok := r.Lookup(req.Method, req.URL.Path)\n\t\tif !ok {\n\t\t\ttxt := fmt.Sprintf(\"No handler for %s %s\", req.Method, req.URL.Path)\n\t\t\trsp := NewResponse(req)\n\t\t\trsp.Error = terrors.NotFound(\"no_handler\", txt, nil)\n\t\t\treturn rsp\n\t\t}\n\t\treturn svc(req)\n\t}\n}\n\nfunc (r *router) Params(req Request) map[string]string {\n\t_, params, _ := r.Lookup(req.Method, req.URL.Path)\n\treturn params\n}\n\n\/\/ Sugar\nfunc (r *router) OPTIONS(path string, svc Service) { r.Register(\"OPTIONS\", path, svc) }\nfunc (r *router) GET(path string, svc Service)     { r.Register(\"GET\", path, svc) }\nfunc (r *router) HEAD(path string, svc Service)    { r.Register(\"HEAD\", path, svc) }\nfunc (r *router) POST(path string, svc Service)    { r.Register(\"POST\", path, svc) }\nfunc (r *router) PUT(path string, svc Service)     { r.Register(\"PUT\", path, svc) }\nfunc (r *router) DELETE(path string, svc Service)  { r.Register(\"DELETE\", path, svc) }\nfunc (r *router) TRACE(path string, svc Service)   { r.Register(\"TRACE\", path, svc) }\n<|endoftext|>"}
{"text":"<commit_before>package tachyon\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\ntype RunResult struct {\n\tTask    *Task\n\tResult  *Result\n\tRuntime time.Duration\n}\n\ntype Runner struct {\n\tenv       *Environment\n\tplays     []*Play\n\twait      sync.WaitGroup\n\tto_notify map[string]struct{}\n\tasync     chan *AsyncAction\n\treport    Reporter\n\n\tResults []RunResult\n\tRuntime time.Duration\n}\n\nfunc NewRunner(env *Environment, plays []*Play) *Runner {\n\tr := &Runner{\n\t\tenv:       env,\n\t\tplays:     plays,\n\t\tto_notify: make(map[string]struct{}),\n\t\tasync:     make(chan *AsyncAction),\n\t\treport:    env.report,\n\t}\n\n\tgo r.handleAsync()\n\n\treturn r\n}\n\nfunc (r *Runner) SetReport(rep Reporter) {\n\tr.report = rep\n}\n\nfunc (r *Runner) AddNotify(n string) {\n\tr.to_notify[n] = struct{}{}\n}\n\nfunc (r *Runner) ShouldRunHandler(name string) bool {\n\t_, ok := r.to_notify[name]\n\n\treturn ok\n}\n\nfunc (r *Runner) AsyncChannel() chan *AsyncAction {\n\treturn r.async\n}\n\nfunc (r *Runner) Run(env *Environment) error {\n\tstart := time.Now()\n\tdefer func() {\n\t\tr.Runtime = time.Since(start)\n\t}()\n\n\tr.report.StartTasks(r)\n\n\tfor _, play := range r.plays {\n\t\tfs := NewFutureScope(play.Vars)\n\n\t\tfor _, task := range play.Tasks {\n\t\t\terr := r.runTask(env, play, task, fs, fs)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tr.Results = append(r.Results, fs.Results()...)\n\t}\n\n\tr.report.FinishTasks(r)\n\n\tr.wait.Wait()\n\n\tr.report.StartHandlers(r)\n\n\tfor _, play := range r.plays {\n\t\tfs := NewFutureScope(play.Vars)\n\n\t\tfor _, task := range play.Handlers {\n\t\t\tif r.ShouldRunHandler(task.Name()) {\n\t\t\t\terr := r.runTask(env, play, task, fs, fs)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfs.Wait()\n\t}\n\n\tr.report.FinishHandlers(r)\n\n\treturn nil\n}\n\nfunc RunAdhocTask(cmd, args string) (*Result, error) {\n\tenv := NewEnv(NewNestedScope(nil), &Config{})\n\tdefer env.Cleanup()\n\n\ttask := AdhocTask(cmd, args)\n\n\tstr, err := ExpandVars(env.Vars, task.Args())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tobj, err := MakeCommand(env.Vars, task, str)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tce := &CommandEnv{env, env.Paths}\n\n\treturn obj.Run(ce, str)\n}\n\ntype PriorityScope struct {\n\ttask Vars\n\trest Scope\n}\n\nfunc (p *PriorityScope) Get(key string) (Value, bool) {\n\tif p.task != nil {\n\t\tif v, ok := p.task[key]; ok {\n\t\t\treturn Any(v), true\n\t\t}\n\t}\n\n\treturn p.rest.Get(key)\n}\n\nfunc (p *PriorityScope) Set(key string, val interface{}) {\n\tp.rest.Set(key, val)\n}\n\nfunc boolify(str string) bool {\n\tswitch str {\n\tcase \"\", \"false\", \"no\":\n\t\treturn false\n\tdefault:\n\t\treturn true\n\t}\n}\n\ntype ModuleRun struct {\n\tPlay        *Play\n\tTask        *Task\n\tModule      *Module\n\tRunner      *Runner\n\tScope       Scope\n\tFutureScope *FutureScope\n}\n\nfunc (m *ModuleRun) Run(env *CommandEnv, args string) (*Result, error) {\n\tfor _, task := range m.Module.ModTasks {\n\t\tns := NewNestedScope(m.Scope)\n\t\tsm, err := ParseSimpleMap(ns, args)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor k, v := range sm {\n\t\t\tns.Set(k, v)\n\t\t}\n\n\t\tm.Runner.runTask(env.Env, m.Play, task, ns, m.FutureScope)\n\t}\n\n\treturn NewResult(true), nil\n}\n\nfunc (r *Runner) runTask(env *Environment, play *Play, task *Task, s Scope, fs *FutureScope) error {\n\tps := &PriorityScope{task.IncludeVars, s}\n\n\tstart := time.Now()\n\n\tif when := task.When(); when != \"\" {\n\t\twhen, err := ExpandVars(ps, when)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !boolify(when) {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif items := task.Items(); items != nil {\n\t\tvar results []*Result\n\n\t\tanyChanged := false\n\n\t\tfor _, item := range items {\n\t\t\tns := NewNestedScope(ps)\n\t\t\tns.Set(\"item\", item)\n\n\t\t\tstr, err := ExpandVars(ns, task.Args())\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcmd, err := MakeCommand(ns, task, str)\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tr.report.StartTask(task, cmd, str)\n\n\t\t\tce := &CommandEnv{env, task.Paths}\n\n\t\t\tres, err := cmd.Run(ce, str)\n\n\t\t\tif err != nil {\n\t\t\t\tres = NewResult(false)\n\t\t\t\tres.Data.Set(\"failed\", true)\n\t\t\t\tres.Data.Set(\"error\", err.Error())\n\t\t\t}\n\n\t\t\tif res.Changed {\n\t\t\t\tanyChanged = true\n\t\t\t}\n\n\t\t\tresults = append(results, res)\n\t\t}\n\n\t\tres := NewResult(anyChanged)\n\t\tres.Data.Set(\"items\", len(items))\n\t\tres.Data.Set(\"results\", results)\n\n\t\tif name := task.Register(); name != \"\" {\n\t\t\tfs.Set(name, res)\n\t\t}\n\n\t\truntime := time.Since(start)\n\n\t\tr.Results = append(r.Results, RunResult{task, res, runtime})\n\n\t\tr.report.FinishTask(task, res)\n\n\t\tfor _, x := range task.Notify() {\n\t\t\tr.AddNotify(x)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tstr, err := ExpandVars(ps, task.Args())\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar cmd Command\n\n\tif mod, ok := play.Modules[task.Command()]; ok {\n\t\tcmd = &ModuleRun{\n\t\t\tPlay:   play,\n\t\t\tTask:   task,\n\t\t\tModule: mod,\n\t\t\tRunner: r,\n\t\t\tScope:  s,\n\t\t}\n\t} else {\n\t\tcmd, err = MakeCommand(ps, task, str)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tr.report.StartTask(task, cmd, str)\n\n\tce := &CommandEnv{env, task.Paths}\n\n\tif name := task.Future(); name != \"\" {\n\t\tfuture := NewFuture(start, task, func() (*Result, error) {\n\t\t\treturn cmd.Run(ce, str)\n\t\t})\n\n\t\tfs.AddFuture(name, future)\n\n\t\treturn nil\n\t}\n\n\tif task.Async() {\n\t\tasyncAction := &AsyncAction{Task: task}\n\t\tasyncAction.Init(r)\n\n\t\tgo func() {\n\t\t\tasyncAction.Finish(cmd.Run(ce, str))\n\t\t}()\n\t} else {\n\t\tres, err := cmd.Run(ce, str)\n\n\t\tif name := task.Register(); name != \"\" {\n\t\t\tfs.Set(name, res)\n\t\t}\n\n\t\truntime := time.Since(start)\n\n\t\tif err != nil {\n\t\t\tres = NewResult(false)\n\t\t\tres.Data.Set(\"failed\", true)\n\t\t\tres.Data.Set(\"error\", err.Error())\n\t\t}\n\n\t\tr.Results = append(r.Results, RunResult{task, res, runtime})\n\n\t\tr.report.FinishTask(task, res)\n\n\t\tif err == nil {\n\t\t\tfor _, x := range task.Notify() {\n\t\t\t\tr.AddNotify(x)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn err\n}\n<commit_msg>refactor with_items usage out<commit_after>package tachyon\n\nimport (\n\t\"sync\"\n\t\"time\"\n)\n\ntype RunResult struct {\n\tTask    *Task\n\tResult  *Result\n\tRuntime time.Duration\n}\n\ntype Runner struct {\n\tenv       *Environment\n\tplays     []*Play\n\twait      sync.WaitGroup\n\tto_notify map[string]struct{}\n\tasync     chan *AsyncAction\n\treport    Reporter\n\n\tResults []RunResult\n\tRuntime time.Duration\n}\n\nfunc NewRunner(env *Environment, plays []*Play) *Runner {\n\tr := &Runner{\n\t\tenv:       env,\n\t\tplays:     plays,\n\t\tto_notify: make(map[string]struct{}),\n\t\tasync:     make(chan *AsyncAction),\n\t\treport:    env.report,\n\t}\n\n\tgo r.handleAsync()\n\n\treturn r\n}\n\nfunc (r *Runner) SetReport(rep Reporter) {\n\tr.report = rep\n}\n\nfunc (r *Runner) AddNotify(n string) {\n\tr.to_notify[n] = struct{}{}\n}\n\nfunc (r *Runner) ShouldRunHandler(name string) bool {\n\t_, ok := r.to_notify[name]\n\n\treturn ok\n}\n\nfunc (r *Runner) AsyncChannel() chan *AsyncAction {\n\treturn r.async\n}\n\nfunc (r *Runner) Run(env *Environment) error {\n\tstart := time.Now()\n\tdefer func() {\n\t\tr.Runtime = time.Since(start)\n\t}()\n\n\tr.report.StartTasks(r)\n\n\tfor _, play := range r.plays {\n\t\tfs := NewFutureScope(play.Vars)\n\n\t\tfor _, task := range play.Tasks {\n\t\t\terr := r.runTask(env, play, task, fs, fs)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tr.Results = append(r.Results, fs.Results()...)\n\t}\n\n\tr.report.FinishTasks(r)\n\n\tr.wait.Wait()\n\n\tr.report.StartHandlers(r)\n\n\tfor _, play := range r.plays {\n\t\tfs := NewFutureScope(play.Vars)\n\n\t\tfor _, task := range play.Handlers {\n\t\t\tif r.ShouldRunHandler(task.Name()) {\n\t\t\t\terr := r.runTask(env, play, task, fs, fs)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfs.Wait()\n\t}\n\n\tr.report.FinishHandlers(r)\n\n\treturn nil\n}\n\nfunc RunAdhocTask(cmd, args string) (*Result, error) {\n\tenv := NewEnv(NewNestedScope(nil), &Config{})\n\tdefer env.Cleanup()\n\n\ttask := AdhocTask(cmd, args)\n\n\tstr, err := ExpandVars(env.Vars, task.Args())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tobj, err := MakeCommand(env.Vars, task, str)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tce := &CommandEnv{env, env.Paths}\n\n\treturn obj.Run(ce, str)\n}\n\ntype PriorityScope struct {\n\ttask Vars\n\trest Scope\n}\n\nfunc (p *PriorityScope) Get(key string) (Value, bool) {\n\tif p.task != nil {\n\t\tif v, ok := p.task[key]; ok {\n\t\t\treturn Any(v), true\n\t\t}\n\t}\n\n\treturn p.rest.Get(key)\n}\n\nfunc (p *PriorityScope) Set(key string, val interface{}) {\n\tp.rest.Set(key, val)\n}\n\nfunc boolify(str string) bool {\n\tswitch str {\n\tcase \"\", \"false\", \"no\":\n\t\treturn false\n\tdefault:\n\t\treturn true\n\t}\n}\n\ntype ModuleRun struct {\n\tPlay        *Play\n\tTask        *Task\n\tModule      *Module\n\tRunner      *Runner\n\tScope       Scope\n\tFutureScope *FutureScope\n}\n\nfunc (m *ModuleRun) Run(env *CommandEnv, args string) (*Result, error) {\n\tfor _, task := range m.Module.ModTasks {\n\t\tns := NewNestedScope(m.Scope)\n\t\tsm, err := ParseSimpleMap(ns, args)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor k, v := range sm {\n\t\t\tns.Set(k, v)\n\t\t}\n\n\t\tm.Runner.runTask(env.Env, m.Play, task, ns, m.FutureScope)\n\t}\n\n\treturn NewResult(true), nil\n}\n\nfunc (r *Runner) runTaskItems(env *Environment, play *Play, task *Task, s Scope, fs *FutureScope, start time.Time) error {\n\tvar results []*Result\n\n\tanyChanged := false\n\n\tfor _, item := range task.Items() {\n\t\tns := NewNestedScope(s)\n\t\tns.Set(\"item\", item)\n\n\t\tstr, err := ExpandVars(ns, task.Args())\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcmd, err := MakeCommand(ns, task, str)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tr.report.StartTask(task, cmd, str)\n\n\t\tce := &CommandEnv{env, task.Paths}\n\n\t\tres, err := cmd.Run(ce, str)\n\n\t\tif err != nil {\n\t\t\tres = NewResult(false)\n\t\t\tres.Data.Set(\"failed\", true)\n\t\t\tres.Data.Set(\"error\", err.Error())\n\t\t}\n\n\t\tif res.Changed {\n\t\t\tanyChanged = true\n\t\t}\n\n\t\tresults = append(results, res)\n\t}\n\n\tres := NewResult(anyChanged)\n\tres.Data.Set(\"items\", len(task.Items()))\n\tres.Data.Set(\"results\", results)\n\n\tif name := task.Register(); name != \"\" {\n\t\tfs.Set(name, res)\n\t}\n\n\truntime := time.Since(start)\n\n\tr.Results = append(r.Results, RunResult{task, res, runtime})\n\n\tr.report.FinishTask(task, res)\n\n\tfor _, x := range task.Notify() {\n\t\tr.AddNotify(x)\n\t}\n\n\treturn nil\n}\n\nfunc (r *Runner) runTask(env *Environment, play *Play, task *Task, s Scope, fs *FutureScope) error {\n\tps := &PriorityScope{task.IncludeVars, s}\n\n\tstart := time.Now()\n\n\tif when := task.When(); when != \"\" {\n\t\twhen, err := ExpandVars(ps, when)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !boolify(when) {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tif items := task.Items(); items != nil {\n\t\treturn r.runTaskItems(env, play, task, s, fs, start)\n\t}\n\n\tstr, err := ExpandVars(ps, task.Args())\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar cmd Command\n\n\tif mod, ok := play.Modules[task.Command()]; ok {\n\t\tcmd = &ModuleRun{\n\t\t\tPlay:   play,\n\t\t\tTask:   task,\n\t\t\tModule: mod,\n\t\t\tRunner: r,\n\t\t\tScope:  s,\n\t\t}\n\t} else {\n\t\tcmd, err = MakeCommand(ps, task, str)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tr.report.StartTask(task, cmd, str)\n\n\tce := &CommandEnv{env, task.Paths}\n\n\tif name := task.Future(); name != \"\" {\n\t\tfuture := NewFuture(start, task, func() (*Result, error) {\n\t\t\treturn cmd.Run(ce, str)\n\t\t})\n\n\t\tfs.AddFuture(name, future)\n\n\t\treturn nil\n\t}\n\n\tif task.Async() {\n\t\tasyncAction := &AsyncAction{Task: task}\n\t\tasyncAction.Init(r)\n\n\t\tgo func() {\n\t\t\tasyncAction.Finish(cmd.Run(ce, str))\n\t\t}()\n\t} else {\n\t\tres, err := cmd.Run(ce, str)\n\n\t\tif name := task.Register(); name != \"\" {\n\t\t\tfs.Set(name, res)\n\t\t}\n\n\t\truntime := time.Since(start)\n\n\t\tif err != nil {\n\t\t\tres = NewResult(false)\n\t\t\tres.Data.Set(\"failed\", true)\n\t\t\tres.Data.Set(\"error\", err.Error())\n\t\t}\n\n\t\tr.Results = append(r.Results, RunResult{task, res, runtime})\n\n\t\tr.report.FinishTask(task, res)\n\n\t\tif err == nil {\n\t\t\tfor _, x := range task.Notify() {\n\t\t\t\tr.AddNotify(x)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package gucumber\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com\/lsegal\/gucumber\/gherkin\"\n\t\"github.com\/shiena\/ansicolor\"\n)\n\nconst (\n\tclrWhite  = \"0\"\n\tclrRed    = \"31\"\n\tclrGreen  = \"32\"\n\tclrYellow = \"33\"\n\tclrCyan   = \"36\"\n\n\ttxtUnmatchInt   = `(\\d+)`\n\ttxtUnmatchFloat = `(-?\\d+(?:\\.\\d+)?)`\n\ttxtUnmatchStr   = `\"(.+?)\"`\n)\n\nvar (\n\treUnmatchInt   = regexp.MustCompile(txtUnmatchInt)\n\treUnmatchFloat = regexp.MustCompile(txtUnmatchFloat)\n\treUnmatchStr   = regexp.MustCompile(`(<|\").+?(\"|>)`)\n\treOutlineVal   = regexp.MustCompile(`<(.+?)>`)\n)\n\ntype Runner struct {\n\t*Context\n\tFeatures  []*gherkin.Feature\n\tResults   []RunnerResult\n\tUnmatched []*gherkin.Step\n\tFailCount int\n\tSkipCount int\n}\n\ntype RunnerResult struct {\n\t*TestingT\n\t*gherkin.Feature\n\t*gherkin.Scenario\n}\n\nfunc (c *Context) RunDir(dir string) (*Runner, error) {\n\tg, _ := filepath.Glob(filepath.Join(dir, \"*.feature\"))\n\tg2, _ := filepath.Glob(filepath.Join(dir, \"**\", \"*.feature\"))\n\tg = append(g, g2...)\n\n\trunner, err := c.RunFiles(g)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif len(runner.Unmatched) > 0 {\n\t\tfmt.Println(\"Some steps were missing, you can add them by using the following step definition stubs: \")\n\t\tfmt.Println(\"\")\n\t\tfmt.Print(runner.MissingMatcherStubs())\n\t}\n\n\tos.Exit(runner.FailCount)\n\treturn runner, err\n}\n\nfunc (c *Context) RunFiles(featureFiles []string) (*Runner, error) {\n\tr := Runner{\n\t\tContext:   c,\n\t\tFeatures:  []*gherkin.Feature{},\n\t\tResults:   []RunnerResult{},\n\t\tUnmatched: []*gherkin.Step{},\n\t}\n\n\tfor _, file := range featureFiles {\n\t\tfd, err := os.Open(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer fd.Close()\n\n\t\tb, err := ioutil.ReadAll(fd)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfs, err := gherkin.ParseFilename(string(b), file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, f := range fs {\n\t\t\tr.Features = append(r.Features, &f)\n\t\t}\n\t}\n\n\tr.run()\n\treturn &r, nil\n}\n\nfunc (c *Runner) MissingMatcherStubs() string {\n\tvar buf bytes.Buffer\n\tmatches := map[string]bool{}\n\n\tbuf.WriteString(`import . \"github.com\/lsegal\/gucumber\"` + \"\\n\\n\")\n\tbuf.WriteString(\"func init() {\\n\")\n\n\tfor _, m := range c.Unmatched {\n\t\tnumInts, numFloats, numStrs := 1, 1, 1\n\t\tstr, args := m.Text, []string{}\n\t\tstr = reUnmatchInt.ReplaceAllStringFunc(str, func(s string) string {\n\t\t\targs = append(args, fmt.Sprintf(\"i%d int\", numInts))\n\t\t\tnumInts++\n\t\t\treturn txtUnmatchInt\n\t\t})\n\t\tstr = reUnmatchFloat.ReplaceAllStringFunc(str, func(s string) string {\n\t\t\targs = append(args, fmt.Sprintf(\"s%d float64\", numFloats))\n\t\t\tnumFloats++\n\t\t\treturn txtUnmatchFloat\n\t\t})\n\t\tstr = reUnmatchStr.ReplaceAllStringFunc(str, func(s string) string {\n\t\t\targs = append(args, fmt.Sprintf(\"s%d string\", numStrs))\n\t\t\tnumStrs++\n\t\t\treturn txtUnmatchStr\n\t\t})\n\n\t\tif m.Argument.IsTabular() {\n\t\t\targs = append(args, \"table [][]string\")\n\t\t} else {\n\t\t\targs = append(args, \"data string\")\n\t\t}\n\n\t\t\/\/ Don't duplicate matchers. This is mostly for scenario outlines.\n\t\tif matches[str] {\n\t\t\tcontinue\n\t\t}\n\t\tmatches[str] = true\n\n\t\tfmt.Fprintf(&buf, \"\\t%s(`^%s$`, func(%s) {\\n\\t\\tT.Skip() \/\/ pending\\n\\t})\\n\\n\",\n\t\t\tm.Type, str, strings.Join(args, \", \"))\n\t}\n\n\tbuf.WriteString(\"}\\n\")\n\treturn buf.String()\n}\n\nfunc (c *Runner) run() {\n\tif c.BeforeAllFilter != nil {\n\t\tc.BeforeAllFilter()\n\t}\n\tfor _, f := range c.Features {\n\t\tc.runFeature(f)\n\t}\n\tif c.AfterAllFilter != nil {\n\t\tc.AfterAllFilter()\n\t}\n\n\tc.line(\"0;1\", \"Finished (%d passed, %d failed, %d skipped).\\n\",\n\t\tlen(c.Results)-c.FailCount-c.SkipCount, c.FailCount, c.SkipCount)\n}\n\nfunc (c *Runner) runFeature(f *gherkin.Feature) {\n\tif !f.FilterMatched(c.Filters...) {\n\t\tresult := false\n\n\t\t\/\/ if any scenarios match, we will run those\n\t\tfor _, s := range f.Scenarios {\n\t\t\tif s.FilterMatched(c.Filters...) {\n\t\t\t\tresult = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !result {\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor k, fn := range c.BeforeFilters {\n\t\tif f.FilterMatched(strings.Split(k, \"|\")...) {\n\t\t\tfn()\n\t\t}\n\t}\n\n\tif len(f.Tags) > 0 {\n\t\tc.line(clrCyan, strings.Join([]string(f.Tags), \" \"))\n\t}\n\tc.line(\"0;1\", \"Feature: %s\", f.Title)\n\n\tif f.Background.Steps != nil {\n\t\tc.runScenario(\"Background\", f, &f.Background, false)\n\t}\n\n\tfor _, s := range f.Scenarios {\n\t\tc.runScenario(\"Scenario\", f, &s, false)\n\t}\n\n\tfor k, fn := range c.AfterFilters {\n\t\tif f.FilterMatched(strings.Split(k, \"|\")...) {\n\t\t\tfn()\n\t\t}\n\t}\n}\n\nfunc (c *Runner) runScenario(title string, f *gherkin.Feature, s *gherkin.Scenario, isExample bool) {\n\tif !s.FilterMatched(c.Filters...) {\n\t\treturn\n\t}\n\n\tfor k, fn := range c.BeforeFilters {\n\t\tif s.FilterMatched(strings.Split(k, \"|\")...) {\n\t\t\tfn()\n\t\t}\n\t}\n\n\tif s.Examples != \"\" { \/\/ run scenario outline data\n\t\texrows := strings.Split(string(s.Examples), \"\\n\")\n\n\t\tc.line(clrCyan, \"  \"+strings.Join([]string(s.Tags), \" \"))\n\t\tc.fileLine(\"0;1\", \"  %s Outline: %s\", s.Filename, s.Line, s.LongestLine()+1,\n\t\t\ttitle, s.Title)\n\n\t\tfor _, step := range s.Steps {\n\t\t\tc.fileLine(\"0;0\", \"    %s %s\", step.Filename, step.Line,\n\t\t\t\ts.LongestLine()+1, step.Type, step.Text)\n\t\t}\n\n\t\tc.line(clrWhite, \"\")\n\t\tc.line(\"0;1\", \"  Examples:\")\n\t\tc.line(clrCyan, \"    %s\", exrows[0])\n\n\t\ttab := s.Examples.ToTable()\n\t\ttabmap := tab.ToMap()\n\t\tfor i, rows := 1, len(tab); i < rows; i++ {\n\t\t\tother := gherkin.Scenario{\n\t\t\t\tFilename: s.Filename,\n\t\t\t\tLine:     s.Line,\n\t\t\t\tTitle:    s.Title,\n\t\t\t\tExamples: gherkin.StringData(\"\"),\n\t\t\t\tSteps:    []gherkin.Step{},\n\t\t\t}\n\n\t\t\tfor _, step := range s.Steps {\n\t\t\t\tstep.Text = reOutlineVal.ReplaceAllStringFunc(step.Text, func(t string) string {\n\t\t\t\t\treturn tabmap[t[1:len(t)-1]][i-1]\n\t\t\t\t})\n\t\t\t\tother.Steps = append(other.Steps, step)\n\t\t\t}\n\n\t\t\tfc := c.FailCount\n\t\t\tclr := clrGreen\n\t\t\tc.runScenario(title, f, &other, true)\n\n\t\t\tif fc != c.FailCount {\n\t\t\t\tclr = clrRed\n\t\t\t}\n\n\t\t\tc.line(clr, \"    %s\", exrows[i])\n\t\t}\n\t\tc.line(clrWhite, \"\")\n\n\t\tfor k, fn := range c.AfterFilters {\n\t\t\tif s.FilterMatched(strings.Split(k, \"|\")...) {\n\t\t\t\tfn()\n\t\t\t}\n\t\t}\n\n\t\treturn\n\t}\n\n\tt := &TestingT{}\n\tskipping := false\n\tclr := clrGreen\n\n\tif !isExample {\n\t\tif len(s.Tags) > 0 {\n\t\t\tc.line(clrCyan, \"  \"+strings.Join([]string(s.Tags), \" \"))\n\t\t}\n\t\tc.fileLine(\"0;1\", \"  %s: %s\", s.Filename, s.Line, s.LongestLine(),\n\t\t\ttitle, s.Title)\n\t}\n\n\tfor _, step := range s.Steps {\n\t\terrCount := len(t.errors)\n\t\tfound := false\n\t\tif !skipping {\n\t\t\tdone := make(chan bool)\n\t\t\tgo func() {\n\t\t\t\tdefer func() {\n\t\t\t\t\tc.Results = append(c.Results, RunnerResult{t, f, s})\n\n\t\t\t\t\tif t.Skipped() {\n\t\t\t\t\t\tc.SkipCount++\n\t\t\t\t\t\tskipping = true\n\t\t\t\t\t\tclr = clrYellow\n\t\t\t\t\t} else if t.Failed() {\n\t\t\t\t\t\tc.FailCount++\n\t\t\t\t\t\tclr = clrRed\n\t\t\t\t\t}\n\n\t\t\t\t\tdone <- true\n\t\t\t\t}()\n\n\t\t\t\tf, err := c.Execute(t, step.Text, string(step.Argument))\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t\tfound = f\n\n\t\t\t\tif !f {\n\t\t\t\t\tt.Skip(\"no match function for step\")\n\t\t\t\t}\n\t\t\t}()\n\t\t\t<-done\n\t\t}\n\n\t\tif skipping && !found {\n\t\t\tcstep := step\n\t\t\tc.Unmatched = append(c.Unmatched, &cstep)\n\t\t}\n\n\t\tif !isExample {\n\t\t\tc.fileLine(clr, \"    %s %s\", step.Filename, step.Line,\n\t\t\t\ts.LongestLine(), step.Type, step.Text)\n\t\t\tif len(step.Argument) > 0 {\n\t\t\t\tif !step.Argument.IsTabular() {\n\t\t\t\t\tc.line(clrWhite, `      \"\"\"`)\n\t\t\t\t}\n\t\t\t\tfor _, l := range strings.Split(string(step.Argument), \"\\n\") {\n\t\t\t\t\tc.line(clrWhite, \"      %s\", l)\n\t\t\t\t}\n\t\t\t\tif !step.Argument.IsTabular() {\n\t\t\t\t\tc.line(clrWhite, `      \"\"\"`)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(t.errors) > errCount {\n\t\t\tc.line(clrRed, \"\\n\"+t.errors[len(t.errors)-1].message)\n\t\t}\n\t}\n\tif !isExample {\n\t\tc.line(clrWhite, \"\")\n\t}\n\n\tfor k, fn := range c.AfterFilters {\n\t\tif s.FilterMatched(strings.Split(k, \"|\")...) {\n\t\t\tfn()\n\t\t}\n\t}\n}\n\nvar writer = ansicolor.NewAnsiColorWriter(os.Stdout)\n\nfunc (c *Runner) line(clr, text string, args ...interface{}) {\n\tfmt.Fprintf(writer, \"\\033[%sm%s\\033[0;0m\\n\", clr, fmt.Sprintf(text, args...))\n}\n\nfunc (c *Runner) fileLine(clr, text, filename string, line int, max int, args ...interface{}) {\n\tspace, str := \"\", fmt.Sprintf(text, args...)\n\tif l := max + 5 - len(str); l > 0 {\n\t\tspace = strings.Repeat(\" \", l)\n\t}\n\tcomment := fmt.Sprintf(\"%s \\033[39;0m# %s:%d\", space, filename, line)\n\tc.line(clr, \"%s%s\", str, comment)\n}\n\ntype Tester interface {\n\tErrorf(format string, args ...interface{})\n}\n\ntype TestingT struct {\n\tskipped bool\n\terrors  []TestError\n}\n\ntype TestError struct {\n\tmessage string\n\tstack   []byte\n}\n\nfunc (t *TestingT) Errorf(format string, args ...interface{}) {\n\tvar buf bytes.Buffer\n\n\tstr := fmt.Sprintf(format, args...)\n\tsbuf := make([]byte, 8192)\n\tfor {\n\t\tsize := runtime.Stack(sbuf, false)\n\t\tif size < len(sbuf) {\n\t\t\tbreak\n\t\t}\n\t\tbuf.Write(sbuf[0:size])\n\t}\n\n\tt.errors = append(t.errors, TestError{message: str, stack: buf.Bytes()})\n}\n\nfunc (t *TestingT) Skip(args ...interface{}) {\n\tt.skipped = true\n}\n\nfunc (t *TestingT) Skipped() bool {\n\treturn t.skipped\n}\n\nfunc (t *TestingT) Failed() bool {\n\treturn len(t.errors) > 0\n}\n\nfunc (t *TestingT) Error(err error) {\n\tt.errors = append(t.errors, TestError{message: err.Error()})\n}\n<commit_msg>Add Skip() to Tester interface<commit_after>package gucumber\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com\/lsegal\/gucumber\/gherkin\"\n\t\"github.com\/shiena\/ansicolor\"\n)\n\nconst (\n\tclrWhite  = \"0\"\n\tclrRed    = \"31\"\n\tclrGreen  = \"32\"\n\tclrYellow = \"33\"\n\tclrCyan   = \"36\"\n\n\ttxtUnmatchInt   = `(\\d+)`\n\ttxtUnmatchFloat = `(-?\\d+(?:\\.\\d+)?)`\n\ttxtUnmatchStr   = `\"(.+?)\"`\n)\n\nvar (\n\treUnmatchInt   = regexp.MustCompile(txtUnmatchInt)\n\treUnmatchFloat = regexp.MustCompile(txtUnmatchFloat)\n\treUnmatchStr   = regexp.MustCompile(`(<|\").+?(\"|>)`)\n\treOutlineVal   = regexp.MustCompile(`<(.+?)>`)\n)\n\ntype Runner struct {\n\t*Context\n\tFeatures  []*gherkin.Feature\n\tResults   []RunnerResult\n\tUnmatched []*gherkin.Step\n\tFailCount int\n\tSkipCount int\n}\n\ntype RunnerResult struct {\n\t*TestingT\n\t*gherkin.Feature\n\t*gherkin.Scenario\n}\n\nfunc (c *Context) RunDir(dir string) (*Runner, error) {\n\tg, _ := filepath.Glob(filepath.Join(dir, \"*.feature\"))\n\tg2, _ := filepath.Glob(filepath.Join(dir, \"**\", \"*.feature\"))\n\tg = append(g, g2...)\n\n\trunner, err := c.RunFiles(g)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif len(runner.Unmatched) > 0 {\n\t\tfmt.Println(\"Some steps were missing, you can add them by using the following step definition stubs: \")\n\t\tfmt.Println(\"\")\n\t\tfmt.Print(runner.MissingMatcherStubs())\n\t}\n\n\tos.Exit(runner.FailCount)\n\treturn runner, err\n}\n\nfunc (c *Context) RunFiles(featureFiles []string) (*Runner, error) {\n\tr := Runner{\n\t\tContext:   c,\n\t\tFeatures:  []*gherkin.Feature{},\n\t\tResults:   []RunnerResult{},\n\t\tUnmatched: []*gherkin.Step{},\n\t}\n\n\tfor _, file := range featureFiles {\n\t\tfd, err := os.Open(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer fd.Close()\n\n\t\tb, err := ioutil.ReadAll(fd)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfs, err := gherkin.ParseFilename(string(b), file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, f := range fs {\n\t\t\tr.Features = append(r.Features, &f)\n\t\t}\n\t}\n\n\tr.run()\n\treturn &r, nil\n}\n\nfunc (c *Runner) MissingMatcherStubs() string {\n\tvar buf bytes.Buffer\n\tmatches := map[string]bool{}\n\n\tbuf.WriteString(`import . \"github.com\/lsegal\/gucumber\"` + \"\\n\\n\")\n\tbuf.WriteString(\"func init() {\\n\")\n\n\tfor _, m := range c.Unmatched {\n\t\tnumInts, numFloats, numStrs := 1, 1, 1\n\t\tstr, args := m.Text, []string{}\n\t\tstr = reUnmatchInt.ReplaceAllStringFunc(str, func(s string) string {\n\t\t\targs = append(args, fmt.Sprintf(\"i%d int\", numInts))\n\t\t\tnumInts++\n\t\t\treturn txtUnmatchInt\n\t\t})\n\t\tstr = reUnmatchFloat.ReplaceAllStringFunc(str, func(s string) string {\n\t\t\targs = append(args, fmt.Sprintf(\"s%d float64\", numFloats))\n\t\t\tnumFloats++\n\t\t\treturn txtUnmatchFloat\n\t\t})\n\t\tstr = reUnmatchStr.ReplaceAllStringFunc(str, func(s string) string {\n\t\t\targs = append(args, fmt.Sprintf(\"s%d string\", numStrs))\n\t\t\tnumStrs++\n\t\t\treturn txtUnmatchStr\n\t\t})\n\n\t\tif m.Argument.IsTabular() {\n\t\t\targs = append(args, \"table [][]string\")\n\t\t} else {\n\t\t\targs = append(args, \"data string\")\n\t\t}\n\n\t\t\/\/ Don't duplicate matchers. This is mostly for scenario outlines.\n\t\tif matches[str] {\n\t\t\tcontinue\n\t\t}\n\t\tmatches[str] = true\n\n\t\tfmt.Fprintf(&buf, \"\\t%s(`^%s$`, func(%s) {\\n\\t\\tT.Skip() \/\/ pending\\n\\t})\\n\\n\",\n\t\t\tm.Type, str, strings.Join(args, \", \"))\n\t}\n\n\tbuf.WriteString(\"}\\n\")\n\treturn buf.String()\n}\n\nfunc (c *Runner) run() {\n\tif c.BeforeAllFilter != nil {\n\t\tc.BeforeAllFilter()\n\t}\n\tfor _, f := range c.Features {\n\t\tc.runFeature(f)\n\t}\n\tif c.AfterAllFilter != nil {\n\t\tc.AfterAllFilter()\n\t}\n\n\tc.line(\"0;1\", \"Finished (%d passed, %d failed, %d skipped).\\n\",\n\t\tlen(c.Results)-c.FailCount-c.SkipCount, c.FailCount, c.SkipCount)\n}\n\nfunc (c *Runner) runFeature(f *gherkin.Feature) {\n\tif !f.FilterMatched(c.Filters...) {\n\t\tresult := false\n\n\t\t\/\/ if any scenarios match, we will run those\n\t\tfor _, s := range f.Scenarios {\n\t\t\tif s.FilterMatched(c.Filters...) {\n\t\t\t\tresult = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !result {\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor k, fn := range c.BeforeFilters {\n\t\tif f.FilterMatched(strings.Split(k, \"|\")...) {\n\t\t\tfn()\n\t\t}\n\t}\n\n\tif len(f.Tags) > 0 {\n\t\tc.line(clrCyan, strings.Join([]string(f.Tags), \" \"))\n\t}\n\tc.line(\"0;1\", \"Feature: %s\", f.Title)\n\n\tif f.Background.Steps != nil {\n\t\tc.runScenario(\"Background\", f, &f.Background, false)\n\t}\n\n\tfor _, s := range f.Scenarios {\n\t\tc.runScenario(\"Scenario\", f, &s, false)\n\t}\n\n\tfor k, fn := range c.AfterFilters {\n\t\tif f.FilterMatched(strings.Split(k, \"|\")...) {\n\t\t\tfn()\n\t\t}\n\t}\n}\n\nfunc (c *Runner) runScenario(title string, f *gherkin.Feature, s *gherkin.Scenario, isExample bool) {\n\tif !s.FilterMatched(c.Filters...) {\n\t\treturn\n\t}\n\n\tfor k, fn := range c.BeforeFilters {\n\t\tif s.FilterMatched(strings.Split(k, \"|\")...) {\n\t\t\tfn()\n\t\t}\n\t}\n\n\tif s.Examples != \"\" { \/\/ run scenario outline data\n\t\texrows := strings.Split(string(s.Examples), \"\\n\")\n\n\t\tc.line(clrCyan, \"  \"+strings.Join([]string(s.Tags), \" \"))\n\t\tc.fileLine(\"0;1\", \"  %s Outline: %s\", s.Filename, s.Line, s.LongestLine()+1,\n\t\t\ttitle, s.Title)\n\n\t\tfor _, step := range s.Steps {\n\t\t\tc.fileLine(\"0;0\", \"    %s %s\", step.Filename, step.Line,\n\t\t\t\ts.LongestLine()+1, step.Type, step.Text)\n\t\t}\n\n\t\tc.line(clrWhite, \"\")\n\t\tc.line(\"0;1\", \"  Examples:\")\n\t\tc.line(clrCyan, \"    %s\", exrows[0])\n\n\t\ttab := s.Examples.ToTable()\n\t\ttabmap := tab.ToMap()\n\t\tfor i, rows := 1, len(tab); i < rows; i++ {\n\t\t\tother := gherkin.Scenario{\n\t\t\t\tFilename: s.Filename,\n\t\t\t\tLine:     s.Line,\n\t\t\t\tTitle:    s.Title,\n\t\t\t\tExamples: gherkin.StringData(\"\"),\n\t\t\t\tSteps:    []gherkin.Step{},\n\t\t\t}\n\n\t\t\tfor _, step := range s.Steps {\n\t\t\t\tstep.Text = reOutlineVal.ReplaceAllStringFunc(step.Text, func(t string) string {\n\t\t\t\t\treturn tabmap[t[1:len(t)-1]][i-1]\n\t\t\t\t})\n\t\t\t\tother.Steps = append(other.Steps, step)\n\t\t\t}\n\n\t\t\tfc := c.FailCount\n\t\t\tclr := clrGreen\n\t\t\tc.runScenario(title, f, &other, true)\n\n\t\t\tif fc != c.FailCount {\n\t\t\t\tclr = clrRed\n\t\t\t}\n\n\t\t\tc.line(clr, \"    %s\", exrows[i])\n\t\t}\n\t\tc.line(clrWhite, \"\")\n\n\t\tfor k, fn := range c.AfterFilters {\n\t\t\tif s.FilterMatched(strings.Split(k, \"|\")...) {\n\t\t\t\tfn()\n\t\t\t}\n\t\t}\n\n\t\treturn\n\t}\n\n\tt := &TestingT{}\n\tskipping := false\n\tclr := clrGreen\n\n\tif !isExample {\n\t\tif len(s.Tags) > 0 {\n\t\t\tc.line(clrCyan, \"  \"+strings.Join([]string(s.Tags), \" \"))\n\t\t}\n\t\tc.fileLine(\"0;1\", \"  %s: %s\", s.Filename, s.Line, s.LongestLine(),\n\t\t\ttitle, s.Title)\n\t}\n\n\tfor _, step := range s.Steps {\n\t\terrCount := len(t.errors)\n\t\tfound := false\n\t\tif !skipping {\n\t\t\tdone := make(chan bool)\n\t\t\tgo func() {\n\t\t\t\tdefer func() {\n\t\t\t\t\tc.Results = append(c.Results, RunnerResult{t, f, s})\n\n\t\t\t\t\tif t.Skipped() {\n\t\t\t\t\t\tc.SkipCount++\n\t\t\t\t\t\tskipping = true\n\t\t\t\t\t\tclr = clrYellow\n\t\t\t\t\t} else if t.Failed() {\n\t\t\t\t\t\tc.FailCount++\n\t\t\t\t\t\tclr = clrRed\n\t\t\t\t\t}\n\n\t\t\t\t\tdone <- true\n\t\t\t\t}()\n\n\t\t\t\tf, err := c.Execute(t, step.Text, string(step.Argument))\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Error(err)\n\t\t\t\t}\n\t\t\t\tfound = f\n\n\t\t\t\tif !f {\n\t\t\t\t\tt.Skip(\"no match function for step\")\n\t\t\t\t}\n\t\t\t}()\n\t\t\t<-done\n\t\t}\n\n\t\tif skipping && !found {\n\t\t\tcstep := step\n\t\t\tc.Unmatched = append(c.Unmatched, &cstep)\n\t\t}\n\n\t\tif !isExample {\n\t\t\tc.fileLine(clr, \"    %s %s\", step.Filename, step.Line,\n\t\t\t\ts.LongestLine(), step.Type, step.Text)\n\t\t\tif len(step.Argument) > 0 {\n\t\t\t\tif !step.Argument.IsTabular() {\n\t\t\t\t\tc.line(clrWhite, `      \"\"\"`)\n\t\t\t\t}\n\t\t\t\tfor _, l := range strings.Split(string(step.Argument), \"\\n\") {\n\t\t\t\t\tc.line(clrWhite, \"      %s\", l)\n\t\t\t\t}\n\t\t\t\tif !step.Argument.IsTabular() {\n\t\t\t\t\tc.line(clrWhite, `      \"\"\"`)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(t.errors) > errCount {\n\t\t\tc.line(clrRed, \"\\n\"+t.errors[len(t.errors)-1].message)\n\t\t}\n\t}\n\tif !isExample {\n\t\tc.line(clrWhite, \"\")\n\t}\n\n\tfor k, fn := range c.AfterFilters {\n\t\tif s.FilterMatched(strings.Split(k, \"|\")...) {\n\t\t\tfn()\n\t\t}\n\t}\n}\n\nvar writer = ansicolor.NewAnsiColorWriter(os.Stdout)\n\nfunc (c *Runner) line(clr, text string, args ...interface{}) {\n\tfmt.Fprintf(writer, \"\\033[%sm%s\\033[0;0m\\n\", clr, fmt.Sprintf(text, args...))\n}\n\nfunc (c *Runner) fileLine(clr, text, filename string, line int, max int, args ...interface{}) {\n\tspace, str := \"\", fmt.Sprintf(text, args...)\n\tif l := max + 5 - len(str); l > 0 {\n\t\tspace = strings.Repeat(\" \", l)\n\t}\n\tcomment := fmt.Sprintf(\"%s \\033[39;0m# %s:%d\", space, filename, line)\n\tc.line(clr, \"%s%s\", str, comment)\n}\n\ntype Tester interface {\n\tErrorf(format string, args ...interface{})\n\tSkip(args ...interface{})\n}\n\ntype TestingT struct {\n\tskipped bool\n\terrors  []TestError\n}\n\ntype TestError struct {\n\tmessage string\n\tstack   []byte\n}\n\nfunc (t *TestingT) Errorf(format string, args ...interface{}) {\n\tvar buf bytes.Buffer\n\n\tstr := fmt.Sprintf(format, args...)\n\tsbuf := make([]byte, 8192)\n\tfor {\n\t\tsize := runtime.Stack(sbuf, false)\n\t\tif size < len(sbuf) {\n\t\t\tbreak\n\t\t}\n\t\tbuf.Write(sbuf[0:size])\n\t}\n\n\tt.errors = append(t.errors, TestError{message: str, stack: buf.Bytes()})\n}\n\nfunc (t *TestingT) Skip(args ...interface{}) {\n\tt.skipped = true\n}\n\nfunc (t *TestingT) Skipped() bool {\n\treturn t.skipped\n}\n\nfunc (t *TestingT) Failed() bool {\n\treturn len(t.errors) > 0\n}\n\nfunc (t *TestingT) Error(err error) {\n\tt.errors = append(t.errors, TestError{message: err.Error()})\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\ntype PackageInfo struct {\n\tpackageName    string\n\tpackageVersion string\n\trepositoryUrl  string\n\trepositoryType string\n}\n\n\/\/ Flags\nvar (\n\tsatisPath  string\n\tconfigPath string\n\trepoPath   string\n\n\tlisten string\n)\n\n\/\/ Operation vars\nvar (\n\tshouldGenerateConfig bool\n\tshouldGenerateRepo   bool\n\trunningGoroutines    = 0\n\n\tpendingUpdates map[string]*PackageInfo = make(map[string]*PackageInfo)\n\n\tupdateMutex sync.Mutex\n\tconfigMutex sync.RWMutex\n)\n\nfunc init() {\n\tflag.StringVar(&satisPath, \"satis\", \"\", \"The path to the satis binary (required)\")\n\tflag.StringVar(&configPath, \"config\", \"\", \"The path to the satis repo configuration file (required)\")\n\tflag.StringVar(&repoPath, \"repo\", \"\", \"The path to the satis repository (required)\")\n\n\tflag.StringVar(&listen, \"listen\", \":8080\", \"The address to listen on\")\n}\n\nfunc printHelp() {\n\tflag.PrintDefaults()\n}\n\n\/\/ Writes the satis configuration file upon receiving a signal\nfunc configGenerator(abortChan chan bool) {\n\trunningGoroutines += 1\n\tdefer func() {\n\t\trunningGoroutines -= 1\n\t}()\n\n\tvar config map[string]interface{}\n\tfor {\n\t\t\/\/ check if we're shutting down\n\t\tselect {\n\t\tcase <-abortChan:\n\t\t\treturn\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Have we been flagged for a config rebuild?\n\t\tif !shouldGenerateConfig {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Read the existing config\n\t\tconfigMutex.RLock()\n\t\tdata, err := ioutil.ReadFile(configPath)\n\t\tif err != nil {\n\t\t\tconfigMutex.RUnlock()\n\t\t\tfmt.Fprintf(os.Stderr, \"Failed to load satis config file: %s\", err)\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\t\tconfigMutex.RUnlock()\n\t\t\/\/ Decode the config\n\t\terr = json.Unmarshal(data, &config)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Failed to decode satis config file: %s\", err)\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar repositories []map[string]interface{}\n\t\tvar packages map[string]interface{}\n\n\t\t\/\/ Create the keys if they don't exist,\n\t\t\/\/ but assume they're the correct type if they do exist\n\t\tif tmp, ok := config[\"repositories\"]; !ok {\n\t\t\trepositories = make([]map[string]interface{}, 0, 1)\n\t\t} else {\n\t\t\ttmp2 := tmp.([]interface{})\n\t\t\trepositories = make([]map[string]interface{}, len(tmp2))\n\t\t\tfor k, repo := range tmp2 {\n\t\t\t\trepositories[k] = repo.(map[string]interface{})\n\t\t\t}\n\t\t}\n\t\tif tmp, ok := config[\"require\"]; !ok {\n\t\t\tpackages = make(map[string]interface{})\n\t\t} else {\n\t\t\tpackages = tmp.(map[string]interface{})\n\t\t}\n\n\t\t\/\/ Update the config\n\t\tupdateMutex.Lock()\n\t\tfor _, packageInfo := range pendingUpdates {\n\t\t\tvar repoExists = false\n\n\t\t\t\/\/ Update the repo if it already exists\n\t\t\tfor _, repo := range repositories {\n\t\t\t\tif repo[\"url\"] == packageInfo.repositoryUrl {\n\t\t\t\t\trepo[\"type\"] = packageInfo.repositoryType\n\t\t\t\t\trepoExists = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Create the repo if it doesn't exist\n\t\t\tif !repoExists {\n\t\t\t\trepositories = append(repositories, map[string]interface{}{\n\t\t\t\t\t\"url\":  packageInfo.repositoryUrl,\n\t\t\t\t\t\"type\": packageInfo.repositoryType,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t\/\/ Update the package version\n\t\t\tpackages[packageInfo.packageName] = packageInfo.packageVersion\n\t\t}\n\t\tupdateMutex.Unlock()\n\n\t\t\/\/ Write the config changes\n\t\tconfig[\"repositories\"] = repositories\n\t\tconfig[\"require\"] = packages\n\n\t\tdata, err = json.MarshalIndent(config, \"\", \"    \")\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Failed to encode satis config file: %s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tconfigMutex.Lock()\n\t\terr = ioutil.WriteFile(configPath, data, 0644)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Failed to write satis config file: %s\", err)\n\t\t\tcontinue\n\t\t}\n\t\tconfigMutex.Unlock()\n\n\t\tlog.Println(\"Generated config file for\", len(pendingUpdates), \"updates\")\n\t\tpendingUpdates = make(map[string]*PackageInfo)\n\n\t\t\/\/ Update the worker flags to trigger a build\n\t\tshouldGenerateConfig = false\n\t\tshouldGenerateRepo = true\n\t}\n}\n\n\/\/ Generates the satis repositroy upon receiving a signal\nfunc repoGenerator(abortChan chan bool) {\n\trunningGoroutines += 1\n\tdefer func() {\n\t\trunningGoroutines -= 1\n\t}()\n\n\tfor {\n\t\t\/\/ check if we're shutting down\n\t\tselect {\n\t\tcase <-abortChan:\n\t\t\treturn\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Check if we should generate the repo\n\t\tif !shouldGenerateRepo {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Lock the config writer for an arbitrary amount of time on the off chance we want to write\n\t\t\/\/ to just as we launch satis\n\t\tconfigMutex.RLock()\n\t\tgo func() {\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tconfigMutex.RUnlock()\n\t\t}()\n\n\t\tcommand := exec.Command(satisPath, \"build\", configPath, repoPath)\n\t\tcommand.Stdout = os.Stdout\n\t\tcommand.Stderr = os.Stderr\n\t\tcommand.Stdin = os.Stdin\n\t\terr := command.Run()\n\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"failed to execute satis: %s\", err)\n\t\t}\n\n\t\tshouldGenerateRepo = false\n\t}\n}\n\nfunc serveHttp(abortChan chan bool) {\n\trunningGoroutines += 1\n\tdefer func() {\n\t\trunningGoroutines -= 1\n\t}()\n\n\t\/\/ Serve the repo config\n\thttp.HandleFunc(\"\/config.json\", func(w http.ResponseWriter, r *http.Request) {\n\t\tconfigMutex.RLock()\n\t\tdefer configMutex.RUnlock()\n\t\thttp.ServeFile(w, r, configPath)\n\t})\n\n\t\/\/ Endpoint to force regeneration\n\thttp.HandleFunc(\"\/generate\", func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"HTTP triggered repo generation\")\n\n\t\tshouldGenerateRepo = true\n\n\t\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\t\tw.WriteHeader(200)\n\t\tw.Write([]byte(\"{\\\"success\\\": true}\"))\n\t})\n\n\t\/\/ Endpoint to register a repo update\n\thttp.HandleFunc(\"\/register\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\n\t\tparams := r.URL.Query()\n\t\tvar update = &PackageInfo{\n\t\t\trepositoryUrl:  params.Get(\"repo\"),\n\t\t\trepositoryType: params.Get(\"repoType\"),\n\t\t\tpackageName:    params.Get(\"package\"),\n\t\t\tpackageVersion: params.Get(\"version\"),\n\t\t}\n\n\t\t\/\/ Basic sanity checking\n\t\tif update.packageName == \"\" {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write([]byte(\"{\\\"error\\\": \\\"missing package\\\"}\"))\n\t\t\treturn\n\t\t}\n\n\t\tif update.repositoryUrl == \"\" {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write([]byte(\"{\\\"error\\\": \\\"missing repo\\\"}\"))\n\t\t\treturn\n\t\t}\n\n\t\tif update.repositoryType == \"\" {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write([]byte(\"{\\\"error\\\": \\\"missing repoType\\\"}\"))\n\t\t\treturn\n\t\t}\n\n\t\tif update.packageVersion == \"\" {\n\t\t\tupdate.packageVersion = \"*\"\n\t\t}\n\n\t\tupdateMutex.Lock()\n\t\tpendingUpdates[update.packageName] = update\n\t\tupdateMutex.Unlock()\n\n\t\tshouldGenerateRepo = true\n\t\tw.WriteHeader(200)\n\t\tw.Write([]byte(\"{\\\"success\\\": true}\"))\n\t})\n\n\t\/\/ Serve the repo\n\tfs := http.FileServer(http.Dir(repoPath))\n\thttp.Handle(\"\/\", fs)\n\n\tvar server = http.Server{Addr: listen}\n\tvar errorChan = make(chan error)\n\n\tgo func() {\n\t\tfmt.Println(\"listening on\", listen)\n\t\terrorChan <- server.ListenAndServe()\n\t}()\n\n\tselect {\n\tcase err := <-errorChan:\n\t\tlog.Fatalln(\"HTTP listener error:\", err)\n\t\tbreak\n\tcase <-abortChan:\n\t\tserver.Close()\n\t\tbreak\n\t}\n\n}\n\nfunc main() {\n\tfmt.Println(\"satisd - dynamic satis repository generator daemon\")\n\tflag.Parse()\n\n\tif satisPath == \"\" || configPath == \"\" || repoPath == \"\" {\n\t\tprintHelp()\n\t\treturn\n\t}\n\n\t\/\/ Check that the files exist\n\tif _, err := os.Stat(satisPath); os.IsNotExist(err) {\n\t\tlog.Fatalln(\"satis binary not found at\", satisPath)\n\t}\n\tif _, err := os.Stat(configPath); os.IsNotExist(err) {\n\t\tlog.Fatalln(\"satis configuration not found at\", configPath)\n\t}\n\n\t\/\/ Perform a basic sanity check on the config\n\tvar config map[string]interface{}\n\tdata, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to load satis config file: %s\", err)\n\t\tos.Exit(1)\n\t}\n\terr = json.Unmarshal(data, &config)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to decode satis config file: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Spin up the worker goroutines\n\tshutdownChannel := make(chan bool)\n\tgo configGenerator(shutdownChannel)\n\tgo repoGenerator(shutdownChannel)\n\tgo serveHttp(shutdownChannel)\n\n\t\/\/ Catch signals\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\n\t\/\/ We've got a kill signal? - do a clean shutdown\n\tsig := <-sigs\n\tfmt.Println(\"Received signal\", sig)\n\tclose(shutdownChannel)\n\n\t\/\/ Wait for the goroutines to exit\n\tfor {\n\t\tif runningGoroutines == 0 {\n\t\t\treturn\n\t\t}\n\t\truntime.Gosched()\n\t}\n}\n<commit_msg>Stop workers running wild while waiting for work<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\ntype PackageInfo struct {\n\tpackageName    string\n\tpackageVersion string\n\trepositoryUrl  string\n\trepositoryType string\n}\n\n\/\/ Flags\nvar (\n\tsatisPath  string\n\tconfigPath string\n\trepoPath   string\n\n\tlisten string\n)\n\n\/\/ Operation vars\nvar (\n\tshouldGenerateConfig bool\n\tshouldGenerateRepo   bool\n\trunningGoroutines    = 0\n\n\tpendingUpdates map[string]*PackageInfo = make(map[string]*PackageInfo)\n\n\tupdateMutex sync.Mutex\n\tconfigMutex sync.RWMutex\n)\n\nfunc init() {\n\tflag.StringVar(&satisPath, \"satis\", \"\", \"The path to the satis binary (required)\")\n\tflag.StringVar(&configPath, \"config\", \"\", \"The path to the satis repo configuration file (required)\")\n\tflag.StringVar(&repoPath, \"repo\", \"\", \"The path to the satis repository (required)\")\n\n\tflag.StringVar(&listen, \"listen\", \":8080\", \"The address to listen on\")\n}\n\nfunc printHelp() {\n\tflag.PrintDefaults()\n}\n\n\/\/ Writes the satis configuration file upon receiving a signal\nfunc configGenerator(abortChan chan bool) {\n\trunningGoroutines += 1\n\tdefer func() {\n\t\trunningGoroutines -= 1\n\t}()\n\n\tvar config map[string]interface{}\n\tfor {\n\t\t\/\/ check if we're shutting down\n\t\tselect {\n\t\tcase <-abortChan:\n\t\t\treturn\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Have we been flagged for a config rebuild?\n\t\tif !shouldGenerateConfig {\n\t\t\ttime.Sleep(time.Second * 1)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Read the existing config\n\t\tconfigMutex.RLock()\n\t\tdata, err := ioutil.ReadFile(configPath)\n\t\tif err != nil {\n\t\t\tconfigMutex.RUnlock()\n\t\t\tfmt.Fprintf(os.Stderr, \"Failed to load satis config file: %s\", err)\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\t\tconfigMutex.RUnlock()\n\t\t\/\/ Decode the config\n\t\terr = json.Unmarshal(data, &config)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Failed to decode satis config file: %s\", err)\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar repositories []map[string]interface{}\n\t\tvar packages map[string]interface{}\n\n\t\t\/\/ Create the keys if they don't exist,\n\t\t\/\/ but assume they're the correct type if they do exist\n\t\tif tmp, ok := config[\"repositories\"]; !ok {\n\t\t\trepositories = make([]map[string]interface{}, 0, 1)\n\t\t} else {\n\t\t\ttmp2 := tmp.([]interface{})\n\t\t\trepositories = make([]map[string]interface{}, len(tmp2))\n\t\t\tfor k, repo := range tmp2 {\n\t\t\t\trepositories[k] = repo.(map[string]interface{})\n\t\t\t}\n\t\t}\n\t\tif tmp, ok := config[\"require\"]; !ok {\n\t\t\tpackages = make(map[string]interface{})\n\t\t} else {\n\t\t\tpackages = tmp.(map[string]interface{})\n\t\t}\n\n\t\t\/\/ Update the config\n\t\tupdateMutex.Lock()\n\t\tfor _, packageInfo := range pendingUpdates {\n\t\t\tvar repoExists = false\n\n\t\t\t\/\/ Update the repo if it already exists\n\t\t\tfor _, repo := range repositories {\n\t\t\t\tif repo[\"url\"] == packageInfo.repositoryUrl {\n\t\t\t\t\trepo[\"type\"] = packageInfo.repositoryType\n\t\t\t\t\trepoExists = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Create the repo if it doesn't exist\n\t\t\tif !repoExists {\n\t\t\t\trepositories = append(repositories, map[string]interface{}{\n\t\t\t\t\t\"url\":  packageInfo.repositoryUrl,\n\t\t\t\t\t\"type\": packageInfo.repositoryType,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t\/\/ Update the package version\n\t\t\tpackages[packageInfo.packageName] = packageInfo.packageVersion\n\t\t}\n\t\tupdateMutex.Unlock()\n\n\t\t\/\/ Write the config changes\n\t\tconfig[\"repositories\"] = repositories\n\t\tconfig[\"require\"] = packages\n\n\t\tdata, err = json.MarshalIndent(config, \"\", \"    \")\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Failed to encode satis config file: %s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tconfigMutex.Lock()\n\t\terr = ioutil.WriteFile(configPath, data, 0644)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Failed to write satis config file: %s\", err)\n\t\t\tcontinue\n\t\t}\n\t\tconfigMutex.Unlock()\n\n\t\tlog.Println(\"Generated config file for\", len(pendingUpdates), \"updates\")\n\t\tpendingUpdates = make(map[string]*PackageInfo)\n\n\t\t\/\/ Update the worker flags to trigger a build\n\t\tshouldGenerateConfig = false\n\t\tshouldGenerateRepo = true\n\t}\n}\n\n\/\/ Generates the satis repositroy upon receiving a signal\nfunc repoGenerator(abortChan chan bool) {\n\trunningGoroutines += 1\n\tdefer func() {\n\t\trunningGoroutines -= 1\n\t}()\n\n\tfor {\n\t\t\/\/ check if we're shutting down\n\t\tselect {\n\t\tcase <-abortChan:\n\t\t\treturn\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Check if we should generate the repo\n\t\tif !shouldGenerateRepo {\n\t\t\ttime.Sleep(time.Second * 1)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Lock the config writer for an arbitrary amount of time on the off chance we want to write\n\t\t\/\/ to just as we launch satis\n\t\tconfigMutex.RLock()\n\t\tgo func() {\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t\tconfigMutex.RUnlock()\n\t\t}()\n\n\t\tcommand := exec.Command(satisPath, \"build\", configPath, repoPath)\n\t\tcommand.Stdout = os.Stdout\n\t\tcommand.Stderr = os.Stderr\n\t\tcommand.Stdin = os.Stdin\n\t\terr := command.Run()\n\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"failed to execute satis: %s\", err)\n\t\t}\n\n\t\tshouldGenerateRepo = false\n\t}\n}\n\nfunc serveHttp(abortChan chan bool) {\n\trunningGoroutines += 1\n\tdefer func() {\n\t\trunningGoroutines -= 1\n\t}()\n\n\t\/\/ Serve the repo config\n\thttp.HandleFunc(\"\/config.json\", func(w http.ResponseWriter, r *http.Request) {\n\t\tconfigMutex.RLock()\n\t\tdefer configMutex.RUnlock()\n\t\thttp.ServeFile(w, r, configPath)\n\t})\n\n\t\/\/ Endpoint to force regeneration\n\thttp.HandleFunc(\"\/generate\", func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"HTTP triggered repo generation\")\n\n\t\tshouldGenerateRepo = true\n\n\t\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\t\tw.WriteHeader(200)\n\t\tw.Write([]byte(\"{\\\"success\\\": true}\"))\n\t})\n\n\t\/\/ Endpoint to register a repo update\n\thttp.HandleFunc(\"\/register\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\n\t\tparams := r.URL.Query()\n\t\tvar update = &PackageInfo{\n\t\t\trepositoryUrl:  params.Get(\"repo\"),\n\t\t\trepositoryType: params.Get(\"repoType\"),\n\t\t\tpackageName:    params.Get(\"package\"),\n\t\t\tpackageVersion: params.Get(\"version\"),\n\t\t}\n\n\t\t\/\/ Basic sanity checking\n\t\tif update.packageName == \"\" {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write([]byte(\"{\\\"error\\\": \\\"missing package\\\"}\"))\n\t\t\treturn\n\t\t}\n\n\t\tif update.repositoryUrl == \"\" {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write([]byte(\"{\\\"error\\\": \\\"missing repo\\\"}\"))\n\t\t\treturn\n\t\t}\n\n\t\tif update.repositoryType == \"\" {\n\t\t\tw.WriteHeader(400)\n\t\t\tw.Write([]byte(\"{\\\"error\\\": \\\"missing repoType\\\"}\"))\n\t\t\treturn\n\t\t}\n\n\t\tif update.packageVersion == \"\" {\n\t\t\tupdate.packageVersion = \"*\"\n\t\t}\n\n\t\tupdateMutex.Lock()\n\t\tpendingUpdates[update.packageName] = update\n\t\tupdateMutex.Unlock()\n\n\t\tshouldGenerateRepo = true\n\t\tw.WriteHeader(200)\n\t\tw.Write([]byte(\"{\\\"success\\\": true}\"))\n\t})\n\n\t\/\/ Serve the repo\n\tfs := http.FileServer(http.Dir(repoPath))\n\thttp.Handle(\"\/\", fs)\n\n\tvar server = http.Server{Addr: listen}\n\tvar errorChan = make(chan error)\n\n\tgo func() {\n\t\tfmt.Println(\"listening on\", listen)\n\t\terrorChan <- server.ListenAndServe()\n\t}()\n\n\tselect {\n\tcase err := <-errorChan:\n\t\tlog.Fatalln(\"HTTP listener error:\", err)\n\t\tbreak\n\tcase <-abortChan:\n\t\tserver.Close()\n\t\tbreak\n\t}\n\n}\n\nfunc main() {\n\tfmt.Println(\"satisd - dynamic satis repository generator daemon\")\n\tflag.Parse()\n\n\tif satisPath == \"\" || configPath == \"\" || repoPath == \"\" {\n\t\tprintHelp()\n\t\treturn\n\t}\n\n\t\/\/ Check that the files exist\n\tif _, err := os.Stat(satisPath); os.IsNotExist(err) {\n\t\tlog.Fatalln(\"satis binary not found at\", satisPath)\n\t}\n\tif _, err := os.Stat(configPath); os.IsNotExist(err) {\n\t\tlog.Fatalln(\"satis configuration not found at\", configPath)\n\t}\n\n\t\/\/ Perform a basic sanity check on the config\n\tvar config map[string]interface{}\n\tdata, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to load satis config file: %s\", err)\n\t\tos.Exit(1)\n\t}\n\terr = json.Unmarshal(data, &config)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Failed to decode satis config file: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Spin up the worker goroutines\n\tshutdownChannel := make(chan bool)\n\tgo configGenerator(shutdownChannel)\n\tgo repoGenerator(shutdownChannel)\n\tgo serveHttp(shutdownChannel)\n\n\t\/\/ Catch signals\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)\n\n\t\/\/ We've got a kill signal? - do a clean shutdown\n\tsig := <-sigs\n\tfmt.Println(\"Received signal\", sig)\n\tclose(shutdownChannel)\n\n\t\/\/ Wait for the goroutines to exit\n\tfor {\n\t\tif runningGoroutines == 0 {\n\t\t\treturn\n\t\t}\n\t\truntime.Gosched()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package graphql\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/golang\/sync\/syncmap\"\n\t\"github.com\/sprucehealth\/graphql\/gqlerrors\"\n)\n\ntype SchemaConfig struct {\n\tQuery        *Object\n\tMutation     *Object\n\tSubscription *Object\n\tTypes        []Type\n\tDirectives   []*Directive\n}\n\ntype TypeMap map[string]Type\n\n\/\/ Schema Definition\n\/\/ A Schema is created by supplying the root types of each type of operation,\n\/\/ query, mutation (optional) and subscription (optional). A schema definition is then supplied to the\n\/\/ validator and executor.\n\/\/ Example:\n\/\/     myAppSchema, err := NewSchema(SchemaConfig({\n\/\/       Query: MyAppQueryRootType,\n\/\/       Mutation: MyAppMutationRootType,\n\/\/       Subscription: MyAppSubscriptionRootType,\n\/\/     });\n\/\/ Note: If an array of `directives` are provided to GraphQLSchema, that will be\n\/\/ the exact list of directives represented and allowed. If `directives` is not\n\/\/ provided then a default set of the specified directives (e.g. @include and\n\/\/ @skip) will be used. If you wish to provide *additional* directives to these\n\/\/ specified directives, you must explicitly declare them. Example:\n\/\/\n\/\/     const MyAppSchema = new GraphQLSchema({\n\/\/       ...\n\/\/       directives: specifiedDirectives.concat([ myCustomDirective ]),\n\/\/     })\ntype Schema struct {\n\ttypeMap    TypeMap\n\tdirectives []*Directive\n\n\tqueryType        *Object\n\tmutationType     *Object\n\tsubscriptionType *Object\n\timplementations  map[string][]*Object\n\tpossibleTypeMap  *syncmap.Map \/\/ abstract type name -> map[string]struct{}\n}\n\nfunc NewSchema(config SchemaConfig) (Schema, error) {\n\tschema := Schema{\n\t\tpossibleTypeMap: &syncmap.Map{},\n\t}\n\n\tif config.Query == nil {\n\t\treturn schema, gqlerrors.NewFormattedError(\"Schema query must be Object Type but got: nil.\")\n\t}\n\n\t\/\/ if schema config contains error at creation time, return those errors\n\tif config.Query != nil && config.Query.Error() != nil {\n\t\treturn schema, config.Query.Error()\n\t}\n\tif config.Mutation != nil && config.Mutation.Error() != nil {\n\t\treturn schema, config.Mutation.Error()\n\t}\n\n\tschema.queryType = config.Query\n\tschema.mutationType = config.Mutation\n\tschema.subscriptionType = config.Subscription\n\n\t\/\/ Provide specified directives (e.g. @include and @skip) by default.\n\tschema.directives = config.Directives\n\tif len(schema.directives) == 0 {\n\t\tschema.directives = SpecifiedDirectives\n\t}\n\t\/\/ Ensure directive definitions are error-free\n\tfor _, dir := range schema.directives {\n\t\tif dir.err != nil {\n\t\t\treturn schema, dir.err\n\t\t}\n\t}\n\n\t\/\/ Build type map now to detect any errors within this schema.\n\ttypeMap := TypeMap{}\n\tinitialTypes := make([]Type, 0, 4+len(config.Types))\n\tif schema.QueryType() != nil {\n\t\tinitialTypes = append(initialTypes, schema.QueryType())\n\t}\n\tif schema.MutationType() != nil {\n\t\tinitialTypes = append(initialTypes, schema.MutationType())\n\t}\n\tif schema.SubscriptionType() != nil {\n\t\tinitialTypes = append(initialTypes, schema.SubscriptionType())\n\t}\n\tif SchemaType != nil {\n\t\tinitialTypes = append(initialTypes, SchemaType)\n\t}\n\n\tfor _, ttype := range config.Types {\n\t\t\/\/ assume that user will never add a nil object to config\n\t\tinitialTypes = append(initialTypes, ttype)\n\t}\n\n\tfor _, ttype := range initialTypes {\n\t\tif ttype.Error() != nil {\n\t\t\treturn schema, ttype.Error()\n\t\t}\n\t\tvar err error\n\t\ttypeMap, err = typeMapReducer(&schema, typeMap, ttype)\n\t\tif err != nil {\n\t\t\treturn schema, err\n\t\t}\n\t}\n\n\tschema.typeMap = typeMap\n\n\t\/\/ Keep track of all implementations by interface name.\n\tif schema.implementations == nil {\n\t\tschema.implementations = map[string][]*Object{}\n\t}\n\tfor _, ttype := range schema.typeMap {\n\t\tif ttype, ok := ttype.(*Object); ok {\n\t\t\tfor _, iface := range ttype.Interfaces() {\n\t\t\t\tschema.implementations[iface.Name()] = append(schema.implementations[iface.Name()], ttype)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Enforce correct interface implementations\n\tfor _, ttype := range schema.typeMap {\n\t\tif ttype, ok := ttype.(*Object); ok {\n\t\t\tfor _, iface := range ttype.Interfaces() {\n\t\t\t\terr := assertObjectImplementsInterface(&schema, ttype, iface)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn schema, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn schema, nil\n}\n\nfunc (gq *Schema) QueryType() *Object {\n\treturn gq.queryType\n}\n\nfunc (gq *Schema) MutationType() *Object {\n\treturn gq.mutationType\n}\n\nfunc (gq *Schema) SubscriptionType() *Object {\n\treturn gq.subscriptionType\n}\n\nfunc (gq *Schema) Directives() []*Directive {\n\treturn gq.directives\n}\n\nfunc (gq *Schema) Directive(name string) *Directive {\n\tfor _, directive := range gq.Directives() {\n\t\tif directive.Name == name {\n\t\t\treturn directive\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (gq *Schema) TypeMap() TypeMap {\n\treturn gq.typeMap\n}\n\nfunc (gq *Schema) Type(name string) Type {\n\treturn gq.TypeMap()[name]\n}\n\nfunc (gq *Schema) PossibleTypes(abstractType Abstract) []*Object {\n\tswitch abstractType := abstractType.(type) {\n\tcase *Union:\n\t\treturn abstractType.Types()\n\tcase *Interface:\n\t\tif impls, ok := gq.implementations[abstractType.Name()]; ok {\n\t\t\treturn impls\n\t\t}\n\t}\n\treturn []*Object{}\n}\nfunc (gq *Schema) IsPossibleType(abstractType Abstract, possibleType *Object) bool {\n\tname := abstractType.Name()\n\ttypeMapVal, _ := gq.possibleTypeMap.Load(name)\n\ttypeMap, ok := typeMapVal.(map[string]struct{})\n\n\tif !ok {\n\t\tpossibleTypes := gq.PossibleTypes(abstractType)\n\t\ttypeMap = make(map[string]struct{}, len(possibleTypes))\n\t\tfor _, possibleType := range possibleTypes {\n\t\t\ttypeMap[possibleType.Name()] = struct{}{}\n\t\t}\n\t\tgq.possibleTypeMap.Store(name, typeMap)\n\t}\n\n\t_, isPossible := typeMap[possibleType.Name()]\n\treturn isPossible\n}\nfunc typeMapReducer(schema *Schema, typeMap TypeMap, objectType Type) (TypeMap, error) {\n\tvar err error\n\tif objectType == nil || objectType.Name() == \"\" {\n\t\treturn typeMap, nil\n\t}\n\n\tswitch objectType := objectType.(type) {\n\tcase *List:\n\t\tif objectType.OfType != nil {\n\t\t\treturn typeMapReducer(schema, typeMap, objectType.OfType)\n\t\t}\n\tcase *NonNull:\n\t\tif objectType.OfType != nil {\n\t\t\treturn typeMapReducer(schema, typeMap, objectType.OfType)\n\t\t}\n\tcase *Object:\n\t\tif objectType.Error() != nil {\n\t\t\treturn typeMap, objectType.Error()\n\t\t}\n\t}\n\n\tif mappedObjectType, ok := typeMap[objectType.Name()]; ok {\n\t\tif mappedObjectType != objectType {\n\t\t\treturn typeMap, gqlerrors.NewFormattedError(fmt.Sprintf(`Schema must contain unique named types but contains multiple types named \"%v\".`, objectType.Name()))\n\t\t}\n\t\treturn typeMap, nil\n\t}\n\tif objectType.Name() == \"\" {\n\t\treturn typeMap, nil\n\t}\n\n\ttypeMap[objectType.Name()] = objectType\n\n\tswitch objectType := objectType.(type) {\n\tcase *Union:\n\t\ttypes := schema.PossibleTypes(objectType)\n\t\tif objectType.Error() != nil {\n\t\t\treturn typeMap, objectType.Error()\n\t\t}\n\t\tfor _, innerObjectType := range types {\n\t\t\tif innerObjectType.Error() != nil {\n\t\t\t\treturn typeMap, innerObjectType.Error()\n\t\t\t}\n\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, innerObjectType)\n\t\t\tif err != nil {\n\t\t\t\treturn typeMap, err\n\t\t\t}\n\t\t}\n\tcase *Interface:\n\t\ttypes := schema.PossibleTypes(objectType)\n\t\tif objectType.err != nil {\n\t\t\treturn typeMap, objectType.err\n\t\t}\n\t\tfor _, innerObjectType := range types {\n\t\t\tif innerObjectType.Error() != nil {\n\t\t\t\treturn typeMap, innerObjectType.Error()\n\t\t\t}\n\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, innerObjectType)\n\t\t\tif err != nil {\n\t\t\t\treturn typeMap, err\n\t\t\t}\n\t\t}\n\tcase *Object:\n\t\tinterfaces := objectType.Interfaces()\n\t\tif objectType.Error() != nil {\n\t\t\treturn typeMap, objectType.Error()\n\t\t}\n\t\tfor _, innerObjectType := range interfaces {\n\t\t\tif innerObjectType.Error() != nil {\n\t\t\t\treturn typeMap, innerObjectType.Error()\n\t\t\t}\n\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, innerObjectType)\n\t\t\tif err != nil {\n\t\t\t\treturn typeMap, err\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch objectType := objectType.(type) {\n\tcase *Object:\n\t\tfieldMap := objectType.Fields()\n\t\tif objectType.Error() != nil {\n\t\t\treturn typeMap, objectType.Error()\n\t\t}\n\t\tfor _, field := range fieldMap {\n\t\t\tfor _, arg := range field.Args {\n\t\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, arg.Type)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn typeMap, err\n\t\t\t\t}\n\t\t\t}\n\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, field.Type)\n\t\t\tif err != nil {\n\t\t\t\treturn typeMap, err\n\t\t\t}\n\t\t}\n\tcase *Interface:\n\t\tfieldMap := objectType.Fields()\n\t\tif objectType.Error() != nil {\n\t\t\treturn typeMap, objectType.Error()\n\t\t}\n\t\tfor _, field := range fieldMap {\n\t\t\tfor _, arg := range field.Args {\n\t\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, arg.Type)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn typeMap, err\n\t\t\t\t}\n\t\t\t}\n\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, field.Type)\n\t\t\tif err != nil {\n\t\t\t\treturn typeMap, err\n\t\t\t}\n\t\t}\n\tcase *InputObject:\n\t\tfieldMap := objectType.Fields()\n\t\tif objectType.err != nil {\n\t\t\treturn typeMap, objectType.err\n\t\t}\n\t\tfor _, field := range fieldMap {\n\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, field.Type)\n\t\t\tif err != nil {\n\t\t\t\treturn typeMap, err\n\t\t\t}\n\t\t}\n\t}\n\treturn typeMap, nil\n}\n\nfunc assertObjectImplementsInterface(schema *Schema, object *Object, iface *Interface) error {\n\tobjectFieldMap := object.Fields()\n\tifaceFieldMap := iface.Fields()\n\n\t\/\/ Assert each interface field is implemented.\n\tfor fieldName := range ifaceFieldMap {\n\t\tobjectField := objectFieldMap[fieldName]\n\t\tifaceField := ifaceFieldMap[fieldName]\n\n\t\t\/\/ Assert interface field exists on object.\n\t\tif objectField == nil {\n\t\t\treturn gqlerrors.NewFormattedError(fmt.Sprintf(`\"%v\" expects field \"%v\" but \"%v\" does not provide it.`, iface, fieldName, object))\n\t\t}\n\n\t\t\/\/ Assert interface field type matches object field type.\n\t\tif !isTypeSubTypeOf(schema, objectField.Type, ifaceField.Type) {\n\t\t\treturn gqlerrors.NewFormattedError(fmt.Sprintf(`%v.%v expects type \"%v\" but %v.%v provides type \"%v\".`,\n\t\t\t\tiface, fieldName, ifaceField.Type,\n\t\t\t\tobject, fieldName, objectField.Type))\n\t\t}\n\n\t\t\/\/ Assert each interface field arg is implemented.\n\t\tfor _, ifaceArg := range ifaceField.Args {\n\t\t\targName := ifaceArg.PrivateName\n\t\t\tvar objectArg *Argument\n\t\t\tfor _, arg := range objectField.Args {\n\t\t\t\tif arg.PrivateName == argName {\n\t\t\t\t\tobjectArg = arg\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Assert interface field arg exists on object field.\n\t\t\tif objectArg == nil {\n\t\t\t\treturn gqlerrors.NewFormattedError(fmt.Sprintf(`%v.%v expects argument \"%v\" but %v.%v does not provide it.`,\n\t\t\t\t\tiface, fieldName, argName,\n\t\t\t\t\tobject, fieldName))\n\t\t\t}\n\n\t\t\t\/\/ Assert interface field arg type matches object field arg type.\n\t\t\tif !isEqualType(ifaceArg.Type, objectArg.Type) {\n\t\t\t\treturn gqlerrors.NewFormattedError(fmt.Sprintf(\n\t\t\t\t\t`%v.%v(%v:) expects type \"%v\" `+\n\t\t\t\t\t\t`but %v.%v(%v:) provides `+\n\t\t\t\t\t\t`type \"%v\".`,\n\t\t\t\t\tiface, fieldName, argName, ifaceArg.Type,\n\t\t\t\t\tobject, fieldName, argName, objectArg.Type))\n\t\t\t}\n\t\t}\n\t\t\/\/ Assert additional arguments must not be required.\n\t\tfor _, objectArg := range objectField.Args {\n\t\t\targName := objectArg.PrivateName\n\t\t\tvar ifaceArg *Argument\n\t\t\tfor _, arg := range ifaceField.Args {\n\t\t\t\tif arg.PrivateName == argName {\n\t\t\t\t\tifaceArg = arg\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ifaceArg == nil {\n\t\t\t\t_, ok := objectArg.Type.(*NonNull)\n\t\t\t\tif ok {\n\t\t\t\t\treturn gqlerrors.NewFormattedError(\n\t\t\t\t\t\tfmt.Sprintf(`%v.%v(%v:) is of required type \"%v\" but is not also provided by the interface %v.%v.`,\n\t\t\t\t\t\t\tobject, fieldName, argName, objectArg.Type, iface, fieldName))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc isEqualType(typeA, typeB Type) bool {\n\t\/\/ Equivalent type is a valid subtype\n\tif typeA == typeB {\n\t\treturn true\n\t}\n\t\/\/ If either type is non-null, the other must also be non-null.\n\tif typeA, ok := typeA.(*NonNull); ok {\n\t\tif typeB, ok := typeB.(*NonNull); ok {\n\t\t\treturn isEqualType(typeA.OfType, typeB.OfType)\n\t\t}\n\t}\n\t\/\/ If either type is a list, the other must also be a list.\n\tif typeA, ok := typeA.(*List); ok {\n\t\tif typeB, ok := typeB.(*List); ok {\n\t\t\treturn isEqualType(typeA.OfType, typeB.OfType)\n\t\t}\n\t}\n\treturn typeA == typeB\n}\n\n\/\/ isTypeSubTypeOf Provided a type and a super type, return true if the first type is either\n\/\/ equal or a subset of the second super type (covariant).\nfunc isTypeSubTypeOf(schema *Schema, maybeSubType Type, superType Type) bool {\n\t\/\/ Equivalent type is a valid subtype\n\tif maybeSubType == superType {\n\t\treturn true\n\t}\n\n\t\/\/ If superType is non-null, maybeSubType must also be nullable.\n\tif superType, ok := superType.(*NonNull); ok {\n\t\tif maybeSubType, ok := maybeSubType.(*NonNull); ok {\n\t\t\treturn isTypeSubTypeOf(schema, maybeSubType.OfType, superType.OfType)\n\t\t}\n\t\treturn false\n\t}\n\tif maybeSubType, ok := maybeSubType.(*NonNull); ok {\n\t\t\/\/ If superType is nullable, maybeSubType may be non-null.\n\t\treturn isTypeSubTypeOf(schema, maybeSubType.OfType, superType)\n\t}\n\n\t\/\/ If superType type is a list, maybeSubType type must also be a list.\n\tif superType, ok := superType.(*List); ok {\n\t\tif maybeSubType, ok := maybeSubType.(*List); ok {\n\t\t\treturn isTypeSubTypeOf(schema, maybeSubType.OfType, superType.OfType)\n\t\t}\n\t\treturn false\n\t} else if _, ok := maybeSubType.(*List); ok {\n\t\t\/\/ If superType is not a list, maybeSubType must also be not a list.\n\t\treturn false\n\t}\n\n\t\/\/ If superType type is an abstract type, maybeSubType type may be a currently\n\t\/\/ possible object type.\n\tif superType, ok := superType.(*Interface); ok {\n\t\tif maybeSubType, ok := maybeSubType.(*Object); ok && schema.IsPossibleType(superType, maybeSubType) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif superType, ok := superType.(*Union); ok {\n\t\tif maybeSubType, ok := maybeSubType.(*Object); ok && schema.IsPossibleType(superType, maybeSubType) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t\/\/ Otherwise, the child type is not a valid subtype of the parent type.\n\treturn false\n}\n<commit_msg>Use sync pkg instead of syncmap<commit_after>package graphql\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com\/sprucehealth\/graphql\/gqlerrors\"\n)\n\ntype SchemaConfig struct {\n\tQuery        *Object\n\tMutation     *Object\n\tSubscription *Object\n\tTypes        []Type\n\tDirectives   []*Directive\n}\n\ntype TypeMap map[string]Type\n\n\/\/ Schema Definition\n\/\/ A Schema is created by supplying the root types of each type of operation,\n\/\/ query, mutation (optional) and subscription (optional). A schema definition is then supplied to the\n\/\/ validator and executor.\n\/\/ Example:\n\/\/     myAppSchema, err := NewSchema(SchemaConfig({\n\/\/       Query: MyAppQueryRootType,\n\/\/       Mutation: MyAppMutationRootType,\n\/\/       Subscription: MyAppSubscriptionRootType,\n\/\/     });\n\/\/ Note: If an array of `directives` are provided to GraphQLSchema, that will be\n\/\/ the exact list of directives represented and allowed. If `directives` is not\n\/\/ provided then a default set of the specified directives (e.g. @include and\n\/\/ @skip) will be used. If you wish to provide *additional* directives to these\n\/\/ specified directives, you must explicitly declare them. Example:\n\/\/\n\/\/     const MyAppSchema = new GraphQLSchema({\n\/\/       ...\n\/\/       directives: specifiedDirectives.concat([ myCustomDirective ]),\n\/\/     })\ntype Schema struct {\n\ttypeMap    TypeMap\n\tdirectives []*Directive\n\n\tqueryType        *Object\n\tmutationType     *Object\n\tsubscriptionType *Object\n\timplementations  map[string][]*Object\n\tpossibleTypeMap  *sync.Map \/\/ abstract type name -> map[string]struct{}\n}\n\nfunc NewSchema(config SchemaConfig) (Schema, error) {\n\tschema := Schema{\n\t\tpossibleTypeMap: &sync.Map{},\n\t}\n\n\tif config.Query == nil {\n\t\treturn schema, gqlerrors.NewFormattedError(\"Schema query must be Object Type but got: nil.\")\n\t}\n\n\t\/\/ if schema config contains error at creation time, return those errors\n\tif config.Query != nil && config.Query.Error() != nil {\n\t\treturn schema, config.Query.Error()\n\t}\n\tif config.Mutation != nil && config.Mutation.Error() != nil {\n\t\treturn schema, config.Mutation.Error()\n\t}\n\n\tschema.queryType = config.Query\n\tschema.mutationType = config.Mutation\n\tschema.subscriptionType = config.Subscription\n\n\t\/\/ Provide specified directives (e.g. @include and @skip) by default.\n\tschema.directives = config.Directives\n\tif len(schema.directives) == 0 {\n\t\tschema.directives = SpecifiedDirectives\n\t}\n\t\/\/ Ensure directive definitions are error-free\n\tfor _, dir := range schema.directives {\n\t\tif dir.err != nil {\n\t\t\treturn schema, dir.err\n\t\t}\n\t}\n\n\t\/\/ Build type map now to detect any errors within this schema.\n\ttypeMap := TypeMap{}\n\tinitialTypes := make([]Type, 0, 4+len(config.Types))\n\tif schema.QueryType() != nil {\n\t\tinitialTypes = append(initialTypes, schema.QueryType())\n\t}\n\tif schema.MutationType() != nil {\n\t\tinitialTypes = append(initialTypes, schema.MutationType())\n\t}\n\tif schema.SubscriptionType() != nil {\n\t\tinitialTypes = append(initialTypes, schema.SubscriptionType())\n\t}\n\tif SchemaType != nil {\n\t\tinitialTypes = append(initialTypes, SchemaType)\n\t}\n\n\tfor _, ttype := range config.Types {\n\t\t\/\/ assume that user will never add a nil object to config\n\t\tinitialTypes = append(initialTypes, ttype)\n\t}\n\n\tfor _, ttype := range initialTypes {\n\t\tif ttype.Error() != nil {\n\t\t\treturn schema, ttype.Error()\n\t\t}\n\t\tvar err error\n\t\ttypeMap, err = typeMapReducer(&schema, typeMap, ttype)\n\t\tif err != nil {\n\t\t\treturn schema, err\n\t\t}\n\t}\n\n\tschema.typeMap = typeMap\n\n\t\/\/ Keep track of all implementations by interface name.\n\tif schema.implementations == nil {\n\t\tschema.implementations = map[string][]*Object{}\n\t}\n\tfor _, ttype := range schema.typeMap {\n\t\tif ttype, ok := ttype.(*Object); ok {\n\t\t\tfor _, iface := range ttype.Interfaces() {\n\t\t\t\tschema.implementations[iface.Name()] = append(schema.implementations[iface.Name()], ttype)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Enforce correct interface implementations\n\tfor _, ttype := range schema.typeMap {\n\t\tif ttype, ok := ttype.(*Object); ok {\n\t\t\tfor _, iface := range ttype.Interfaces() {\n\t\t\t\terr := assertObjectImplementsInterface(&schema, ttype, iface)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn schema, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn schema, nil\n}\n\nfunc (gq *Schema) QueryType() *Object {\n\treturn gq.queryType\n}\n\nfunc (gq *Schema) MutationType() *Object {\n\treturn gq.mutationType\n}\n\nfunc (gq *Schema) SubscriptionType() *Object {\n\treturn gq.subscriptionType\n}\n\nfunc (gq *Schema) Directives() []*Directive {\n\treturn gq.directives\n}\n\nfunc (gq *Schema) Directive(name string) *Directive {\n\tfor _, directive := range gq.Directives() {\n\t\tif directive.Name == name {\n\t\t\treturn directive\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (gq *Schema) TypeMap() TypeMap {\n\treturn gq.typeMap\n}\n\nfunc (gq *Schema) Type(name string) Type {\n\treturn gq.TypeMap()[name]\n}\n\nfunc (gq *Schema) PossibleTypes(abstractType Abstract) []*Object {\n\tswitch abstractType := abstractType.(type) {\n\tcase *Union:\n\t\treturn abstractType.Types()\n\tcase *Interface:\n\t\tif impls, ok := gq.implementations[abstractType.Name()]; ok {\n\t\t\treturn impls\n\t\t}\n\t}\n\treturn []*Object{}\n}\nfunc (gq *Schema) IsPossibleType(abstractType Abstract, possibleType *Object) bool {\n\tname := abstractType.Name()\n\ttypeMapVal, _ := gq.possibleTypeMap.Load(name)\n\ttypeMap, ok := typeMapVal.(map[string]struct{})\n\n\tif !ok {\n\t\tpossibleTypes := gq.PossibleTypes(abstractType)\n\t\ttypeMap = make(map[string]struct{}, len(possibleTypes))\n\t\tfor _, possibleType := range possibleTypes {\n\t\t\ttypeMap[possibleType.Name()] = struct{}{}\n\t\t}\n\t\tgq.possibleTypeMap.Store(name, typeMap)\n\t}\n\n\t_, isPossible := typeMap[possibleType.Name()]\n\treturn isPossible\n}\nfunc typeMapReducer(schema *Schema, typeMap TypeMap, objectType Type) (TypeMap, error) {\n\tvar err error\n\tif objectType == nil || objectType.Name() == \"\" {\n\t\treturn typeMap, nil\n\t}\n\n\tswitch objectType := objectType.(type) {\n\tcase *List:\n\t\tif objectType.OfType != nil {\n\t\t\treturn typeMapReducer(schema, typeMap, objectType.OfType)\n\t\t}\n\tcase *NonNull:\n\t\tif objectType.OfType != nil {\n\t\t\treturn typeMapReducer(schema, typeMap, objectType.OfType)\n\t\t}\n\tcase *Object:\n\t\tif objectType.Error() != nil {\n\t\t\treturn typeMap, objectType.Error()\n\t\t}\n\t}\n\n\tif mappedObjectType, ok := typeMap[objectType.Name()]; ok {\n\t\tif mappedObjectType != objectType {\n\t\t\treturn typeMap, gqlerrors.NewFormattedError(fmt.Sprintf(`Schema must contain unique named types but contains multiple types named \"%v\".`, objectType.Name()))\n\t\t}\n\t\treturn typeMap, nil\n\t}\n\tif objectType.Name() == \"\" {\n\t\treturn typeMap, nil\n\t}\n\n\ttypeMap[objectType.Name()] = objectType\n\n\tswitch objectType := objectType.(type) {\n\tcase *Union:\n\t\ttypes := schema.PossibleTypes(objectType)\n\t\tif objectType.Error() != nil {\n\t\t\treturn typeMap, objectType.Error()\n\t\t}\n\t\tfor _, innerObjectType := range types {\n\t\t\tif innerObjectType.Error() != nil {\n\t\t\t\treturn typeMap, innerObjectType.Error()\n\t\t\t}\n\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, innerObjectType)\n\t\t\tif err != nil {\n\t\t\t\treturn typeMap, err\n\t\t\t}\n\t\t}\n\tcase *Interface:\n\t\ttypes := schema.PossibleTypes(objectType)\n\t\tif objectType.err != nil {\n\t\t\treturn typeMap, objectType.err\n\t\t}\n\t\tfor _, innerObjectType := range types {\n\t\t\tif innerObjectType.Error() != nil {\n\t\t\t\treturn typeMap, innerObjectType.Error()\n\t\t\t}\n\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, innerObjectType)\n\t\t\tif err != nil {\n\t\t\t\treturn typeMap, err\n\t\t\t}\n\t\t}\n\tcase *Object:\n\t\tinterfaces := objectType.Interfaces()\n\t\tif objectType.Error() != nil {\n\t\t\treturn typeMap, objectType.Error()\n\t\t}\n\t\tfor _, innerObjectType := range interfaces {\n\t\t\tif innerObjectType.Error() != nil {\n\t\t\t\treturn typeMap, innerObjectType.Error()\n\t\t\t}\n\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, innerObjectType)\n\t\t\tif err != nil {\n\t\t\t\treturn typeMap, err\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch objectType := objectType.(type) {\n\tcase *Object:\n\t\tfieldMap := objectType.Fields()\n\t\tif objectType.Error() != nil {\n\t\t\treturn typeMap, objectType.Error()\n\t\t}\n\t\tfor _, field := range fieldMap {\n\t\t\tfor _, arg := range field.Args {\n\t\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, arg.Type)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn typeMap, err\n\t\t\t\t}\n\t\t\t}\n\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, field.Type)\n\t\t\tif err != nil {\n\t\t\t\treturn typeMap, err\n\t\t\t}\n\t\t}\n\tcase *Interface:\n\t\tfieldMap := objectType.Fields()\n\t\tif objectType.Error() != nil {\n\t\t\treturn typeMap, objectType.Error()\n\t\t}\n\t\tfor _, field := range fieldMap {\n\t\t\tfor _, arg := range field.Args {\n\t\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, arg.Type)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn typeMap, err\n\t\t\t\t}\n\t\t\t}\n\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, field.Type)\n\t\t\tif err != nil {\n\t\t\t\treturn typeMap, err\n\t\t\t}\n\t\t}\n\tcase *InputObject:\n\t\tfieldMap := objectType.Fields()\n\t\tif objectType.err != nil {\n\t\t\treturn typeMap, objectType.err\n\t\t}\n\t\tfor _, field := range fieldMap {\n\t\t\ttypeMap, err = typeMapReducer(schema, typeMap, field.Type)\n\t\t\tif err != nil {\n\t\t\t\treturn typeMap, err\n\t\t\t}\n\t\t}\n\t}\n\treturn typeMap, nil\n}\n\nfunc assertObjectImplementsInterface(schema *Schema, object *Object, iface *Interface) error {\n\tobjectFieldMap := object.Fields()\n\tifaceFieldMap := iface.Fields()\n\n\t\/\/ Assert each interface field is implemented.\n\tfor fieldName := range ifaceFieldMap {\n\t\tobjectField := objectFieldMap[fieldName]\n\t\tifaceField := ifaceFieldMap[fieldName]\n\n\t\t\/\/ Assert interface field exists on object.\n\t\tif objectField == nil {\n\t\t\treturn gqlerrors.NewFormattedError(fmt.Sprintf(`\"%v\" expects field \"%v\" but \"%v\" does not provide it.`, iface, fieldName, object))\n\t\t}\n\n\t\t\/\/ Assert interface field type matches object field type.\n\t\tif !isTypeSubTypeOf(schema, objectField.Type, ifaceField.Type) {\n\t\t\treturn gqlerrors.NewFormattedError(fmt.Sprintf(`%v.%v expects type \"%v\" but %v.%v provides type \"%v\".`,\n\t\t\t\tiface, fieldName, ifaceField.Type,\n\t\t\t\tobject, fieldName, objectField.Type))\n\t\t}\n\n\t\t\/\/ Assert each interface field arg is implemented.\n\t\tfor _, ifaceArg := range ifaceField.Args {\n\t\t\targName := ifaceArg.PrivateName\n\t\t\tvar objectArg *Argument\n\t\t\tfor _, arg := range objectField.Args {\n\t\t\t\tif arg.PrivateName == argName {\n\t\t\t\t\tobjectArg = arg\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ Assert interface field arg exists on object field.\n\t\t\tif objectArg == nil {\n\t\t\t\treturn gqlerrors.NewFormattedError(fmt.Sprintf(`%v.%v expects argument \"%v\" but %v.%v does not provide it.`,\n\t\t\t\t\tiface, fieldName, argName,\n\t\t\t\t\tobject, fieldName))\n\t\t\t}\n\n\t\t\t\/\/ Assert interface field arg type matches object field arg type.\n\t\t\tif !isEqualType(ifaceArg.Type, objectArg.Type) {\n\t\t\t\treturn gqlerrors.NewFormattedError(fmt.Sprintf(\n\t\t\t\t\t`%v.%v(%v:) expects type \"%v\" `+\n\t\t\t\t\t\t`but %v.%v(%v:) provides `+\n\t\t\t\t\t\t`type \"%v\".`,\n\t\t\t\t\tiface, fieldName, argName, ifaceArg.Type,\n\t\t\t\t\tobject, fieldName, argName, objectArg.Type))\n\t\t\t}\n\t\t}\n\t\t\/\/ Assert additional arguments must not be required.\n\t\tfor _, objectArg := range objectField.Args {\n\t\t\targName := objectArg.PrivateName\n\t\t\tvar ifaceArg *Argument\n\t\t\tfor _, arg := range ifaceField.Args {\n\t\t\t\tif arg.PrivateName == argName {\n\t\t\t\t\tifaceArg = arg\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ifaceArg == nil {\n\t\t\t\t_, ok := objectArg.Type.(*NonNull)\n\t\t\t\tif ok {\n\t\t\t\t\treturn gqlerrors.NewFormattedError(\n\t\t\t\t\t\tfmt.Sprintf(`%v.%v(%v:) is of required type \"%v\" but is not also provided by the interface %v.%v.`,\n\t\t\t\t\t\t\tobject, fieldName, argName, objectArg.Type, iface, fieldName))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc isEqualType(typeA, typeB Type) bool {\n\t\/\/ Equivalent type is a valid subtype\n\tif typeA == typeB {\n\t\treturn true\n\t}\n\t\/\/ If either type is non-null, the other must also be non-null.\n\tif typeA, ok := typeA.(*NonNull); ok {\n\t\tif typeB, ok := typeB.(*NonNull); ok {\n\t\t\treturn isEqualType(typeA.OfType, typeB.OfType)\n\t\t}\n\t}\n\t\/\/ If either type is a list, the other must also be a list.\n\tif typeA, ok := typeA.(*List); ok {\n\t\tif typeB, ok := typeB.(*List); ok {\n\t\t\treturn isEqualType(typeA.OfType, typeB.OfType)\n\t\t}\n\t}\n\treturn typeA == typeB\n}\n\n\/\/ isTypeSubTypeOf Provided a type and a super type, return true if the first type is either\n\/\/ equal or a subset of the second super type (covariant).\nfunc isTypeSubTypeOf(schema *Schema, maybeSubType Type, superType Type) bool {\n\t\/\/ Equivalent type is a valid subtype\n\tif maybeSubType == superType {\n\t\treturn true\n\t}\n\n\t\/\/ If superType is non-null, maybeSubType must also be nullable.\n\tif superType, ok := superType.(*NonNull); ok {\n\t\tif maybeSubType, ok := maybeSubType.(*NonNull); ok {\n\t\t\treturn isTypeSubTypeOf(schema, maybeSubType.OfType, superType.OfType)\n\t\t}\n\t\treturn false\n\t}\n\tif maybeSubType, ok := maybeSubType.(*NonNull); ok {\n\t\t\/\/ If superType is nullable, maybeSubType may be non-null.\n\t\treturn isTypeSubTypeOf(schema, maybeSubType.OfType, superType)\n\t}\n\n\t\/\/ If superType type is a list, maybeSubType type must also be a list.\n\tif superType, ok := superType.(*List); ok {\n\t\tif maybeSubType, ok := maybeSubType.(*List); ok {\n\t\t\treturn isTypeSubTypeOf(schema, maybeSubType.OfType, superType.OfType)\n\t\t}\n\t\treturn false\n\t} else if _, ok := maybeSubType.(*List); ok {\n\t\t\/\/ If superType is not a list, maybeSubType must also be not a list.\n\t\treturn false\n\t}\n\n\t\/\/ If superType type is an abstract type, maybeSubType type may be a currently\n\t\/\/ possible object type.\n\tif superType, ok := superType.(*Interface); ok {\n\t\tif maybeSubType, ok := maybeSubType.(*Object); ok && schema.IsPossibleType(superType, maybeSubType) {\n\t\t\treturn true\n\t\t}\n\t}\n\tif superType, ok := superType.(*Union); ok {\n\t\tif maybeSubType, ok := maybeSubType.(*Object); ok && schema.IsPossibleType(superType, maybeSubType) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t\/\/ Otherwise, the child type is not a valid subtype of the parent type.\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"container\/list\"\n\t\"fmt\"\n\t\"github.com\/mattn\/go-runewidth\"\n\t\"github.com\/nsf\/termbox-go\"\n\t\"gopkg.in\/sorcix\/irc.v2\"\n\t\"strings\"\n\t\"unicode\/utf8\"\n)\n\nvar buffer *list.List\nvar limit int\n\nfunc formatmessage(msg *irc.Message) string {\n\tprefix := msg.Prefix\n\tif prefix == nil {\n\t\tprefix = &irc.Prefix{\"unknown\", \"unknown\", \"unknown\"}\n\t}\n\tswitch msg.Command {\n\tcase \"JOIN\":\n\t\treturn fmt.Sprintf(\"%s has joined %s\\n\", prefix.Name, msg.Params[0])\n\tcase \"PRIVMSG\":\n\t\treturn fmt.Sprintf(\"%s ─→ %s: %s\\n\", prefix.Name, strings.TrimSpace(msg.Params[0]), msg.Params[1])\n\tcase \"MODE\":\n\t\treturn fmt.Sprintf(\"%s sets mode %s\\n\", prefix.Name, strings.Join(msg.Params[0:], \" \"))\n\tcase \"NOTICE\":\n\t\treturn fmt.Sprintf(\"Notice from %s to %s: %s\\n\", prefix.Name, msg.Params[0], msg.Params[1])\n\tcase \"001\":\n\t\tfallthrough\n\tcase \"002\":\n\t\tfallthrough\n\tcase \"003\":\n\t\tfallthrough\n\tcase \"372\":\n\t\tfallthrough\n\tcase \"375\":\n\t\tfallthrough\n\tcase \"376\":\n\t\treturn fmt.Sprintln(msg.Params[1])\n\tcase \"QUIT\":\n\t\treturn fmt.Sprintf(\"%s has quit (%s)\\n\", prefix.Name, msg.Params[0])\n\tcase \"CTCP\":\n\t\tif strings.HasPrefix(msg.Params[1], \"ACTION\") {\n\t\t\treturn fmt.Sprintf(\"%s: * %s %s\\n\", msg.Params[0], prefix.Name, msg.Params[1][7:])\n\t\t} else {\n\t\t\treturn fmt.Sprintf(\"CTCP request from %s to %s: %s\\n\", prefix.Name, msg.Params[0], msg.Params[1])\n\t\t}\n\tcase \"CTCPREPLY\":\n\t\treturn fmt.Sprintf(\"CTCP reply from %s to %s: %s\\n\", prefix.Name, msg.Params[0], msg.Params[1])\n\tdefault:\n\t\treturn fmt.Sprint(\"RAW:\", msg.String())\n\t}\n}\n\n\/* This function should really be in termbox... *\/\nfunc drawString(x, y int, str string) {\n\ti := 0\n\tfor _, runeValue := range str {\n\t\tputCh(x+i, y, runeValue)\n\t\ti += runewidth.RuneWidth(runeValue)\n\t}\n}\n\nfunc printstring(str string, anchor, width int) int {\n\tretval := anchor - (len(str) \/ width)\n\tretval--\n\ty := retval\n\tclearLine(y, width)\n\ti := 0\n\tfor _, runeValue := range str {\n\t\tif i%width == 0 && i >= width {\n\t\t\ty++\n\t\t\tclearLine(y, width)\n\t\t}\n\t\tputCh(i%width, y, runeValue)\n\t\ti += runewidth.RuneWidth(runeValue)\n\t}\n\treturn retval\n}\n\nfunc updatescreen() {\n\twidth, height := termbox.Size()\n\tanchor := height - 2\n\ti := buffer.Front()\n\tfor anchor > 0 && i != nil {\n\t\tanchor = printstring(i.Value.(string), anchor, width)\n\t\ti = i.Next()\n\t}\n\ttermbox.Flush()\n}\n\nfunc clearLine(y, width int) {\n\tfor i := 0; i < width; i++ {\n\t\teraseCh(i, y)\n\t}\n}\n\nfunc putCh(x, y int, ch rune) {\n\ttermbox.SetCell(x, y, ch, termbox.ColorDefault, termbox.ColorDefault)\n}\n\nfunc eraseCh(x, y int) {\n\tputCh(x, y, ' ')\n}\n\nfunc GetString() string {\n\twidth, height := termbox.Size()\n\tclearLine(height-1, width)\n\tretval := \"\"\n\tcursor := 0\n\ttlen := len(target) + 3\n\tdrawString(0, height-1, fmt.Sprint(target, \" >\"))\n\tfor {\n\t\tdrawString(tlen, height-1, retval)\n\t\ttermbox.SetCursor(tlen+cursor, height-1)\n\t\ttermbox.Flush()\n\t\tev := termbox.PollEvent()\n\t\tif ev.Ch == 0 {\n\t\t\tswitch ev.Key {\n\t\t\tcase termbox.KeySpace:\n\t\t\t\tretval += \" \"\n\t\t\t\tcursor++\n\t\t\tcase termbox.KeyEnter:\n\t\t\t\tif len(retval) > 0 {\n\t\t\t\t\ttermbox.HideCursor()\n\t\t\t\t\treturn retval\n\t\t\t\t}\n\t\t\tcase termbox.KeyDelete:\n\t\t\t\tfallthrough\n\t\t\tcase termbox.KeyBackspace:\n\t\t\t\tif cursor > 0 {\n\t\t\t\t\tr, rs :=\n\t\t\t\t\t\tutf8.DecodeLastRuneInString(retval)\n\t\t\t\t\tretval = retval[0 : len(retval)-rs]\n\t\t\t\t\teraseCh(cursor+(tlen)-runewidth.RuneWidth(r), height-1)\n\t\t\t\t\tcursor -= runewidth.RuneWidth(r)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if ev.Ch > 31 {\n\t\t\tretval += string(ev.Ch)\n\t\t\tcursor += runewidth.RuneWidth(ev.Ch)\n\t\t}\n\t}\n}\n\nfunc sendtobuffer(str string) {\n\tbuffer.PushFront(StripMircFormatting(str))\n\tif buffer.Len() > limit {\n\t\tbuffer.Remove(buffer.Back())\n\t}\n}\n\nfunc printmsg(msg *irc.Message) {\n\tsendtobuffer(formatmessage(msg))\n}\n\nfunc initscreen() {\n\ttermbox.Init()\n}\n\nfunc outputloop(client *Client, scrollback int) {\n\tlimit = scrollback\n\tbuffer = list.New()\n\tfor {\n\t\tmsg, err := client.Receive()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Output loop closing:\", err)\n\t\t\treturn\n\t\t}\n\t\tif msg != nil {\n\t\t\tif msg.Command != \"PING\" {\n\t\t\t\tprintmsg(msg)\n\t\t\t}\n\t\t\tif msg.Command == \"ERROR\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tupdatescreen()\n\t}\n}\n\nfunc inputloop(client *Client) {\n\tdefer termbox.Close()\n\tfor {\n\t\ttext := GetString()\n\t\tsendtobuffer(fmt.Sprint(\"(\", target, \") \", text))\n\t\tupdatescreen()\n\t\tif Command(client, text) {\n\t\t\treturn\n\t\t}\n\t}\n}\n<commit_msg>more readable privmsg format<commit_after>package main\n\nimport (\n\t\"container\/list\"\n\t\"fmt\"\n\t\"github.com\/mattn\/go-runewidth\"\n\t\"github.com\/nsf\/termbox-go\"\n\t\"gopkg.in\/sorcix\/irc.v2\"\n\t\"strings\"\n\t\"unicode\/utf8\"\n)\n\nvar buffer *list.List\nvar limit int\n\nfunc formatmessage(msg *irc.Message) string {\n\tprefix := msg.Prefix\n\tif prefix == nil {\n\t\tprefix = &irc.Prefix{\"unknown\", \"unknown\", \"unknown\"}\n\t}\n\tswitch msg.Command {\n\tcase \"JOIN\":\n\t\treturn fmt.Sprintf(\"%s has joined %s\\n\", prefix.Name, msg.Params[0])\n\tcase \"PRIVMSG\":\n\t\treturn fmt.Sprintf(\"(%s) %s: %s\\n\", msg.Params[0], prefix.Name, msg.Params[1])\n\tcase \"MODE\":\n\t\treturn fmt.Sprintf(\"%s sets mode %s\\n\", prefix.Name, strings.Join(msg.Params[0:], \" \"))\n\tcase \"NOTICE\":\n\t\treturn fmt.Sprintf(\"Notice from %s to %s: %s\\n\", prefix.Name, msg.Params[0], msg.Params[1])\n\tcase \"001\":\n\t\tfallthrough\n\tcase \"002\":\n\t\tfallthrough\n\tcase \"003\":\n\t\tfallthrough\n\tcase \"372\":\n\t\tfallthrough\n\tcase \"375\":\n\t\tfallthrough\n\tcase \"376\":\n\t\treturn fmt.Sprintln(msg.Params[1])\n\tcase \"QUIT\":\n\t\treturn fmt.Sprintf(\"%s has quit (%s)\\n\", prefix.Name, msg.Params[0])\n\tcase \"CTCP\":\n\t\tif strings.HasPrefix(msg.Params[1], \"ACTION\") {\n\t\t\treturn fmt.Sprintf(\"%s: * %s %s\\n\", msg.Params[0], prefix.Name, msg.Params[1][7:])\n\t\t} else {\n\t\t\treturn fmt.Sprintf(\"CTCP request from %s to %s: %s\\n\", prefix.Name, msg.Params[0], msg.Params[1])\n\t\t}\n\tcase \"CTCPREPLY\":\n\t\treturn fmt.Sprintf(\"CTCP reply from %s to %s: %s\\n\", prefix.Name, msg.Params[0], msg.Params[1])\n\tdefault:\n\t\treturn fmt.Sprint(\"RAW:\", msg.String())\n\t}\n}\n\n\/* This function should really be in termbox... *\/\nfunc drawString(x, y int, str string) {\n\ti := 0\n\tfor _, runeValue := range str {\n\t\tputCh(x+i, y, runeValue)\n\t\ti += runewidth.RuneWidth(runeValue)\n\t}\n}\n\nfunc printstring(str string, anchor, width int) int {\n\tretval := anchor - (len(str) \/ width)\n\tretval--\n\ty := retval\n\tclearLine(y, width)\n\ti := 0\n\tfor _, runeValue := range str {\n\t\tif i%width == 0 && i >= width {\n\t\t\ty++\n\t\t\tclearLine(y, width)\n\t\t}\n\t\tputCh(i%width, y, runeValue)\n\t\ti += runewidth.RuneWidth(runeValue)\n\t}\n\treturn retval\n}\n\nfunc updatescreen() {\n\twidth, height := termbox.Size()\n\tanchor := height - 2\n\ti := buffer.Front()\n\tfor anchor > 0 && i != nil {\n\t\tanchor = printstring(i.Value.(string), anchor, width)\n\t\ti = i.Next()\n\t}\n\ttermbox.Flush()\n}\n\nfunc clearLine(y, width int) {\n\tfor i := 0; i < width; i++ {\n\t\teraseCh(i, y)\n\t}\n}\n\nfunc putCh(x, y int, ch rune) {\n\ttermbox.SetCell(x, y, ch, termbox.ColorDefault, termbox.ColorDefault)\n}\n\nfunc eraseCh(x, y int) {\n\tputCh(x, y, ' ')\n}\n\nfunc GetString() string {\n\twidth, height := termbox.Size()\n\tclearLine(height-1, width)\n\tretval := \"\"\n\tcursor := 0\n\ttlen := len(target) + 3\n\tdrawString(0, height-1, fmt.Sprint(target, \" >\"))\n\tfor {\n\t\tdrawString(tlen, height-1, retval)\n\t\ttermbox.SetCursor(tlen+cursor, height-1)\n\t\ttermbox.Flush()\n\t\tev := termbox.PollEvent()\n\t\tif ev.Ch == 0 {\n\t\t\tswitch ev.Key {\n\t\t\tcase termbox.KeySpace:\n\t\t\t\tretval += \" \"\n\t\t\t\tcursor++\n\t\t\tcase termbox.KeyEnter:\n\t\t\t\tif len(retval) > 0 {\n\t\t\t\t\ttermbox.HideCursor()\n\t\t\t\t\treturn retval\n\t\t\t\t}\n\t\t\tcase termbox.KeyDelete:\n\t\t\t\tfallthrough\n\t\t\tcase termbox.KeyBackspace:\n\t\t\t\tif cursor > 0 {\n\t\t\t\t\tr, rs :=\n\t\t\t\t\t\tutf8.DecodeLastRuneInString(retval)\n\t\t\t\t\tretval = retval[0 : len(retval)-rs]\n\t\t\t\t\teraseCh(cursor+(tlen)-runewidth.RuneWidth(r), height-1)\n\t\t\t\t\tcursor -= runewidth.RuneWidth(r)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if ev.Ch > 31 {\n\t\t\tretval += string(ev.Ch)\n\t\t\tcursor += runewidth.RuneWidth(ev.Ch)\n\t\t}\n\t}\n}\n\nfunc sendtobuffer(str string) {\n\tbuffer.PushFront(StripMircFormatting(str))\n\tif buffer.Len() > limit {\n\t\tbuffer.Remove(buffer.Back())\n\t}\n}\n\nfunc printmsg(msg *irc.Message) {\n\tsendtobuffer(formatmessage(msg))\n}\n\nfunc initscreen() {\n\ttermbox.Init()\n}\n\nfunc outputloop(client *Client, scrollback int) {\n\tlimit = scrollback\n\tbuffer = list.New()\n\tfor {\n\t\tmsg, err := client.Receive()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Output loop closing:\", err)\n\t\t\treturn\n\t\t}\n\t\tif msg != nil {\n\t\t\tif msg.Command != \"PING\" {\n\t\t\t\tprintmsg(msg)\n\t\t\t}\n\t\t\tif msg.Command == \"ERROR\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tupdatescreen()\n\t}\n}\n\nfunc inputloop(client *Client) {\n\tdefer termbox.Close()\n\tfor {\n\t\ttext := GetString()\n\t\tsendtobuffer(fmt.Sprint(\"(\", target, \") \", text))\n\t\tupdatescreen()\n\t\tif Command(client, text) {\n\t\t\treturn\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package infermedica\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"strconv\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\ntype SearchRes struct {\n\tID    string `json:\"id\"`\n\tLabel string `json:\"label\"`\n}\n\ntype SearchType string\n\nconst (\n\tSearchTypeSymptom    SearchType = \"symptom\"\n\tSearchTypeRiskFactor SearchType = \"risk_factor\"\n\tSearchTypeLabTest    SearchType = \"lab_test\"\n)\n\nfunc (s SearchType) Ptr() *SearchType { return &s }\nfunc (s SearchType) String() string   { return string(s) }\n\nfunc (s *SearchType) IsValid() bool {\n\t_, err := SearchTypeFromString(s.String())\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc SearchTypeFromString(x string) (SearchType, error) {\n\tswitch strings.ToLower(x) {\n\tcase \"symptom\":\n\t\treturn SearchTypeSymptom, nil\n\tcase \"risk_factor\":\n\t\treturn SearchTypeRiskFactor, nil\n\tcase \"lab_test\":\n\t\treturn SearchTypeLabTest, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Unexpected value for search type: %q\", x)\n\t}\n}\n\nfunc (a *App) Search(phrase string, sex Sex, maxResults int, st SearchType) (*[]SearchRes, error) {\n\tif !sex.IsValid() {\n\t\treturn nil, errors.New(\"Unexpected value for Sex\")\n\t}\n\tif !st.IsValid() {\n\t\treturn nil, errors.New(\"Unexpected value for search type\")\n\t}\n\turl := \"search?phrase=\" + phrase + \"&sex=\" + sex.String() + \"&max_results=\" + strconv.Itoa(maxResults) + \"&type=\" + st.String()\n\treq, err := a.prepareRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &http.Client{}\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := []SearchRes{}\n\terr = json.NewDecoder(res.Body).Decode(&r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &r, nil\n}\n<commit_msg>fixed problem with spaces<commit_after>package infermedica\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"strconv\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\ntype SearchRes struct {\n\tID    string `json:\"id\"`\n\tLabel string `json:\"label\"`\n}\n\ntype SearchType string\n\nconst (\n\tSearchTypeSymptom    SearchType = \"symptom\"\n\tSearchTypeRiskFactor SearchType = \"risk_factor\"\n\tSearchTypeLabTest    SearchType = \"lab_test\"\n)\n\nfunc (s SearchType) Ptr() *SearchType { return &s }\nfunc (s SearchType) String() string   { return string(s) }\n\nfunc (s *SearchType) IsValid() bool {\n\t_, err := SearchTypeFromString(s.String())\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc SearchTypeFromString(x string) (SearchType, error) {\n\tswitch strings.ToLower(x) {\n\tcase \"symptom\":\n\t\treturn SearchTypeSymptom, nil\n\tcase \"risk_factor\":\n\t\treturn SearchTypeRiskFactor, nil\n\tcase \"lab_test\":\n\t\treturn SearchTypeLabTest, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Unexpected value for search type: %q\", x)\n\t}\n}\n\nfunc (a *App) Search(phrase string, sex Sex, maxResults int, st SearchType) (*[]SearchRes, error) {\n\tif !sex.IsValid() {\n\t\treturn nil, errors.New(\"Unexpected value for Sex\")\n\t}\n\tif !st.IsValid() {\n\t\treturn nil, errors.New(\"Unexpected value for search type\")\n\t}\n\turl := \"search?phrase=\" + url.QueryEscape(phrase) + \"&sex=\" + sex.String() + \"&max_results=\" + strconv.Itoa(maxResults) + \"&type=\" + st.String()\n\treq, err := a.prepareRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &http.Client{}\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := []SearchRes{}\n\terr = json.NewDecoder(res.Body).Decode(&r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &r, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n)\n\nconst (\n\tevalInf = 50000\n)\n\n\/\/ SearchPosition searches a Position to the specified depth via iterative deepening\n\/\/ and returns the evaluation score relative to the side to move and the search results.\nfunc SearchPosition(ctx context.Context, pos Position, depth int) (score int, results Results) {\n\tfor d := 1; d <= depth; d++ {\n\t\tif ctx.Err() != nil {\n\t\t\treturn\n\t\t}\n\t\tscore, results = negamax(ctx, pos, results, NewWindow(-evalInf, evalInf), d, true, make([]int, d+1))\n\t}\n\treturn\n}\n\n\/\/ negamax recursively searches a Position to the specified depth and returns the evaluation score\n\/\/ relative to the side to move and the search results. It employs alpha-beta pruning outside of\n\/\/ the specified Window. If recommended is zero length, negamax will generate and search all\n\/\/ pseudo-legal moves; if recommended moves are provided, they must all be pseudo-legal, and\n\/\/ only they will be searched.\nfunc negamax(ctx context.Context, pos Position, recommended Results, w Window, depth int, allowCutoff bool, counters []int) (bestScore int, results Results) {\n\tcounters[0]++\n\n\tif len(recommended) == 0 {\n\t\tmoves := Candidates(pos) \/\/ pseudo-legal\n\n\t\tif !anyLegal(pos, moves) { \/\/ checkmate or stalemate\n\t\t\tif IsCheck(pos) {\n\t\t\t\tbestScore = -evalInf\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif depth == 0 {\n\t\t\tbestScore = Eval(pos) * evalMult(pos.ToMove)\n\t\t\treturn\n\t\t}\n\n\t\trecommended = make(Results, 0, len(moves))\n\t\tfor _, m := range moves {\n\t\t\trecommended = append(recommended, Result{move: m})\n\t\t}\n\t}\n\n\tresults = make(Results, 0, len(recommended))\n\tfor _, r := range recommended {\n\t\tnewpos := Make(pos, r.move)\n\t\tif !IsLegal(newpos) {\n\t\t\tcontinue\n\t\t}\n\n\t\tscore, cont := negamax(ctx, newpos, Results{}, w.Neg(), depth-1, allowCutoff, counters[1:])\n\t\tscore *= -1\n\n\t\t\/\/ Store the score in results relative to White\n\t\tresults = append(results, Result{move: r.move, score: score * evalMult(pos.ToMove), depth: depth - 1, cont: cont})\n\n\t\tif depth >= 3 && ctx.Err() != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tvar constrained, ok bool\n\t\tw, constrained, ok = w.Constrain(score)\n\t\tif constrained {\n\t\t\t\/\/ improved lower bound\n\t\t}\n\t\tif !ok && allowCutoff {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif pos.ToMove == White {\n\t\t\/\/ highest score first\n\t\tsort.Sort(sort.Reverse(results))\n\t} else {\n\t\tsort.Sort(results)\n\t}\n\treturn w.alpha, results\n}\n\n\/\/ IsPseudoLegal returns whether a Move is pseudo-legal in a Position.\n\/\/ A move is pseudo-legal if the square to be moved from contains the specified piece\n\/\/ and the piece is capable of moving to the target square if doing so would not put the king in check.\nfunc IsPseudoLegal(pos Position, move Move) bool {\n\tfor _, m := range PieceMoves[move.Piece](pos) {\n\t\tif m == move {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ IsLegal returns whether a Position results from a legal move.\n\/\/ A position is illegal if the king of the side that just moved is in check.\nfunc IsLegal(pos Position) bool {\n\treturn !IsAttacked(pos, pos.KingSquare[pos.Opp()], pos.ToMove)\n}\n\n\/\/ IsCheck returns whether the king of the side to move is in check.\nfunc IsCheck(pos Position) bool {\n\treturn IsAttacked(pos, pos.KingSquare[pos.ToMove], pos.Opp())\n}\n\n\/\/ IsTerminal returns whether or not a Position is checkmate or stalemate.\n\/\/ A position is checkmate or stalemate if the side to move has no legal moves.\nfunc IsTerminal(pos Position) bool { return !anyLegal(pos, Candidates(pos)) }\n\n\/\/ anyLegal returns whether any of the given Moves are legal in the given Position.\nfunc anyLegal(pos Position, moves []Move) bool {\n\tfor _, m := range moves {\n\t\tif IsLegal(Make(pos, m)) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ A Result holds the score of a searched Move (relative to White),\n\/\/ the search depth, and the continuation Results of the search.\ntype Result struct {\n\tmove  Move\n\tscore int\n\tdepth int\n\tcont  Results\n}\n\n\/\/ String returns a string representation of r, including its principal variation.\nfunc (r Result) String() string {\n\treturn fmt.Sprintf(\"%v (%v) %v\", float64(r.score)\/100, r.depth, r.PV())\n}\n\n\/\/ PV returns a string representation of r's principal variation.\nfunc (r Result) PV() string {\n\tif r.depth == 0 || len(r.cont) == 0 {\n\t\treturn LongAlgebraic(r.move)\n\t}\n\treturn LongAlgebraic(r.move) + \" \" + r.cont[0].PV()\n}\n\n\/\/ A Results contains the results of a search. Results satisfies sort.Interface.\n\/\/ A Results should be sorted by the function generating it before it is returned.\ntype Results []Result\n\nfunc (r Results) Len() int      { return len(r) }\nfunc (r Results) Swap(i, j int) { r[i], r[j] = r[j], r[i] }\n\n\/\/ Less reports whether the Result with index i should sort before the Result with index j.\n\/\/ It sorts first by depth and then by score.\nfunc (r Results) Less(i, j int) bool {\n\treturn r[i].depth < r[j].depth || r[i].depth == r[j].depth && r[i].score < r[j].score\n}\n\n\/\/ String returns a string representation of all Result values in r.\nfunc (r Results) String() string {\n\tvar s string\n\tfor _, result := range r {\n\t\ts += fmt.Sprintf(\"%v\\n\", result.String())\n\t}\n\treturn s\n}\n\n\/\/ A Window represents the bounds of a position's evaluation.\ntype Window struct{ alpha, beta int }\n\n\/\/ NewWindow returns a Window with the given bounds. It panics if alpha > beta.\nfunc NewWindow(alpha, beta int) Window {\n\tif alpha > beta {\n\t\tpanic(fmt.Sprintf(\"invalid window bounds %v, %v\", alpha, beta))\n\t}\n\treturn Window{alpha, beta}\n}\n\n\/\/ Constrain updates the lower bound of w, if applicable, and returns the updated window,\n\/\/ whether the lower bound was changed, and whether the returned Window remains valid.\nfunc (w Window) Constrain(n int) (c Window, constrained bool, ok bool) {\n\tif n <= w.alpha {\n\t\treturn w, false, true\n\t}\n\treturn Window{n, w.beta}, true, n <= w.beta\n}\n\n\/\/ Neg returns the additive inverse of w.\nfunc (w Window) Neg() Window { return Window{-w.beta, -w.alpha} }\n<commit_msg>factor SortFor<commit_after>package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n)\n\nconst (\n\tevalInf = 50000\n)\n\n\/\/ SearchPosition searches a Position to the specified depth via iterative deepening\n\/\/ and returns the evaluation score relative to the side to move and the search results.\nfunc SearchPosition(ctx context.Context, pos Position, depth int) (score int, results Results) {\n\tfor d := 1; d <= depth; d++ {\n\t\tif ctx.Err() != nil {\n\t\t\treturn\n\t\t}\n\t\tscore, results = negamax(ctx, pos, results, NewWindow(-evalInf, evalInf), d, true, make([]int, d+1))\n\t}\n\treturn\n}\n\n\/\/ negamax recursively searches a Position to the specified depth and returns the evaluation score\n\/\/ relative to the side to move and the search results. It employs alpha-beta pruning outside of\n\/\/ the specified Window. If recommended is zero length, negamax will generate and search all\n\/\/ pseudo-legal moves; if recommended moves are provided, they must all be pseudo-legal, and\n\/\/ only they will be searched.\nfunc negamax(ctx context.Context, pos Position, recommended Results, w Window, depth int, allowCutoff bool, counters []int) (bestScore int, results Results) {\n\tcounters[0]++\n\n\tif len(recommended) == 0 {\n\t\tmoves := Candidates(pos) \/\/ pseudo-legal\n\n\t\tif !anyLegal(pos, moves) { \/\/ checkmate or stalemate\n\t\t\tif IsCheck(pos) {\n\t\t\t\tbestScore = -evalInf\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif depth == 0 {\n\t\t\tbestScore = Eval(pos) * evalMult(pos.ToMove)\n\t\t\treturn\n\t\t}\n\n\t\trecommended = make(Results, 0, len(moves))\n\t\tfor _, m := range moves {\n\t\t\trecommended = append(recommended, Result{move: m})\n\t\t}\n\t}\n\n\tresults = make(Results, 0, len(recommended))\n\tfor _, r := range recommended {\n\t\tnewpos := Make(pos, r.move)\n\t\tif !IsLegal(newpos) {\n\t\t\tcontinue\n\t\t}\n\n\t\tscore, cont := negamax(ctx, newpos, Results{}, w.Neg(), depth-1, allowCutoff, counters[1:])\n\t\tscore *= -1\n\n\t\t\/\/ Store the score in results relative to White\n\t\tresults = append(results, Result{move: r.move, score: score * evalMult(pos.ToMove), depth: depth - 1, cont: cont})\n\n\t\tif depth >= 3 && ctx.Err() != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tvar constrained, ok bool\n\t\tw, constrained, ok = w.Constrain(score)\n\t\tif constrained {\n\t\t\t\/\/ improved lower bound\n\t\t}\n\t\tif !ok && allowCutoff {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tresults.SortFor(pos.ToMove)\n\treturn w.alpha, results\n}\n\n\/\/ IsPseudoLegal returns whether a Move is pseudo-legal in a Position.\n\/\/ A move is pseudo-legal if the square to be moved from contains the specified piece\n\/\/ and the piece is capable of moving to the target square if doing so would not put the king in check.\nfunc IsPseudoLegal(pos Position, move Move) bool {\n\tfor _, m := range PieceMoves[move.Piece](pos) {\n\t\tif m == move {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ IsLegal returns whether a Position results from a legal move.\n\/\/ A position is illegal if the king of the side that just moved is in check.\nfunc IsLegal(pos Position) bool {\n\treturn !IsAttacked(pos, pos.KingSquare[pos.Opp()], pos.ToMove)\n}\n\n\/\/ IsCheck returns whether the king of the side to move is in check.\nfunc IsCheck(pos Position) bool {\n\treturn IsAttacked(pos, pos.KingSquare[pos.ToMove], pos.Opp())\n}\n\n\/\/ IsTerminal returns whether or not a Position is checkmate or stalemate.\n\/\/ A position is checkmate or stalemate if the side to move has no legal moves.\nfunc IsTerminal(pos Position) bool { return !anyLegal(pos, Candidates(pos)) }\n\n\/\/ anyLegal returns whether any of the given Moves are legal in the given Position.\nfunc anyLegal(pos Position, moves []Move) bool {\n\tfor _, m := range moves {\n\t\tif IsLegal(Make(pos, m)) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ A Result holds the score of a searched Move (relative to White),\n\/\/ the search depth, and the continuation Results of the search.\ntype Result struct {\n\tmove  Move\n\tscore int\n\tdepth int\n\tcont  Results\n}\n\n\/\/ String returns a string representation of r, including its principal variation.\nfunc (r Result) String() string {\n\treturn fmt.Sprintf(\"%v (%v) %v\", float64(r.score)\/100, r.depth, r.PV())\n}\n\n\/\/ PV returns a string representation of r's principal variation.\nfunc (r Result) PV() string {\n\tif r.depth == 0 || len(r.cont) == 0 {\n\t\treturn LongAlgebraic(r.move)\n\t}\n\treturn LongAlgebraic(r.move) + \" \" + r.cont[0].PV()\n}\n\n\/\/ A Results contains the results of a search. Results satisfies sort.Interface.\n\/\/ A Results should be sorted by the function generating it before it is returned.\ntype Results []Result\n\nfunc (r Results) Len() int      { return len(r) }\nfunc (r Results) Swap(i, j int) { r[i], r[j] = r[j], r[i] }\n\n\/\/ Less reports whether the Result with index i should sort before the Result with index j.\n\/\/ It sorts first by depth and then by score.\nfunc (r Results) Less(i, j int) bool {\n\treturn r[i].depth < r[j].depth || r[i].depth == r[j].depth && r[i].score < r[j].score\n}\n\n\/\/ SortFor sorts r beginning with the best move for c.\nfunc (r Results) SortFor(c Color) {\n\tif c == White {\n\t\t\/\/ highest score first\n\t\tsort.Sort(sort.Reverse(r))\n\t} else {\n\t\tsort.Sort(r)\n\t}\n}\n\n\/\/ String returns a string representation of all Result values in r.\nfunc (r Results) String() string {\n\tvar s string\n\tfor _, result := range r {\n\t\ts += fmt.Sprintf(\"%v\\n\", result.String())\n\t}\n\treturn s\n}\n\n\/\/ A Window represents the bounds of a position's evaluation.\ntype Window struct{ alpha, beta int }\n\n\/\/ NewWindow returns a Window with the given bounds. It panics if alpha > beta.\nfunc NewWindow(alpha, beta int) Window {\n\tif alpha > beta {\n\t\tpanic(fmt.Sprintf(\"invalid window bounds %v, %v\", alpha, beta))\n\t}\n\treturn Window{alpha, beta}\n}\n\n\/\/ Constrain updates the lower bound of w, if applicable, and returns the updated window,\n\/\/ whether the lower bound was changed, and whether the returned Window remains valid.\nfunc (w Window) Constrain(n int) (c Window, constrained bool, ok bool) {\n\tif n <= w.alpha {\n\t\treturn w, false, true\n\t}\n\treturn Window{n, w.beta}, true, n <= w.beta\n}\n\n\/\/ Neg returns the additive inverse of w.\nfunc (w Window) Neg() Window { return Window{-w.beta, -w.alpha} }\n<|endoftext|>"}
{"text":"<commit_before>package utils\n\n\/*\n * Copyright 2016, 2017 SUSE LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"golang.org\/x\/sys\/unix\"\n)\n\n\/\/ MaxSendfdLen is the maximum length of the name of a file descriptor being\n\/\/ sent using SendFd. The name of the file handle returned by RecvFd will never\n\/\/ be larger than this value.\nconst MaxNameLen = 4096\n\n\/\/ oobSpace is the size of the oob slice required to store a single FD. Note\n\/\/ that unix.UnixRights appears to make the assumption that fd is always int32,\n\/\/ so sizeof(fd) = 4.\nvar oobSpace = unix.CmsgSpace(4)\n\n\/\/ RecvFd waits for a file descriptor to be sent over the given AF_UNIX\n\/\/ socket. The file name of the remote file descriptor will be recreated\n\/\/ locally (it is sent as non-auxiliary data in the same payload).\nfunc RecvFd(socket *os.File) (*os.File, error) {\n\t\/\/ For some reason, unix.Recvmsg uses the length rather than the capacity\n\t\/\/ when passing the msg_controllen and other attributes to recvmsg.  So we\n\t\/\/ have to actually set the length.\n\tname := make([]byte, MaxNameLen)\n\toob := make([]byte, oobSpace)\n\n\tsockfd := socket.Fd()\n\tn, oobn, _, _, err := unix.Recvmsg(int(sockfd), name, oob, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n >= MaxNameLen || oobn != oobSpace {\n\t\treturn nil, fmt.Errorf(\"recvfd: incorrect number of bytes read (n=%d oobn=%d)\", n, oobn)\n\t}\n\n\t\/\/ Truncate.\n\tname = name[:n]\n\toob = oob[:oobn]\n\n\tscms, err := unix.ParseSocketControlMessage(oob)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(scms) != 1 {\n\t\treturn nil, fmt.Errorf(\"recvfd: number of SCMs is not 1: %d\", len(scms))\n\t}\n\tscm := scms[0]\n\n\tfds, err := unix.ParseUnixRights(&scm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(fds) != 1 {\n\t\treturn nil, fmt.Errorf(\"recvfd: number of fds is not 1: %d\", len(fds))\n\t}\n\tfd := uintptr(fds[0])\n\n\treturn os.NewFile(fd, string(name)), nil\n}\n\n\/\/ SendFd sends a file descriptor over the given AF_UNIX socket. In\n\/\/ addition, the file.Name() of the given file will also be sent as\n\/\/ non-auxiliary data in the same payload (allowing to send contextual\n\/\/ information for a file descriptor).\nfunc SendFd(socket *os.File, name string, fd uintptr) error {\n\tif len(name) >= MaxNameLen {\n\t\treturn fmt.Errorf(\"sendfd: filename too long: %s\", name)\n\t}\n\toob := unix.UnixRights(int(fd))\n\treturn unix.Sendmsg(int(socket.Fd()), []byte(name), oob, nil, 0)\n}\n<commit_msg>libcontainer\/utils: introduce SendFds<commit_after>package utils\n\n\/*\n * Copyright 2016, 2017 SUSE LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"golang.org\/x\/sys\/unix\"\n)\n\n\/\/ MaxSendfdLen is the maximum length of the name of a file descriptor being\n\/\/ sent using SendFd. The name of the file handle returned by RecvFd will never\n\/\/ be larger than this value.\nconst MaxNameLen = 4096\n\n\/\/ oobSpace is the size of the oob slice required to store a single FD. Note\n\/\/ that unix.UnixRights appears to make the assumption that fd is always int32,\n\/\/ so sizeof(fd) = 4.\nvar oobSpace = unix.CmsgSpace(4)\n\n\/\/ RecvFd waits for a file descriptor to be sent over the given AF_UNIX\n\/\/ socket. The file name of the remote file descriptor will be recreated\n\/\/ locally (it is sent as non-auxiliary data in the same payload).\nfunc RecvFd(socket *os.File) (*os.File, error) {\n\t\/\/ For some reason, unix.Recvmsg uses the length rather than the capacity\n\t\/\/ when passing the msg_controllen and other attributes to recvmsg.  So we\n\t\/\/ have to actually set the length.\n\tname := make([]byte, MaxNameLen)\n\toob := make([]byte, oobSpace)\n\n\tsockfd := socket.Fd()\n\tn, oobn, _, _, err := unix.Recvmsg(int(sockfd), name, oob, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif n >= MaxNameLen || oobn != oobSpace {\n\t\treturn nil, fmt.Errorf(\"recvfd: incorrect number of bytes read (n=%d oobn=%d)\", n, oobn)\n\t}\n\n\t\/\/ Truncate.\n\tname = name[:n]\n\toob = oob[:oobn]\n\n\tscms, err := unix.ParseSocketControlMessage(oob)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(scms) != 1 {\n\t\treturn nil, fmt.Errorf(\"recvfd: number of SCMs is not 1: %d\", len(scms))\n\t}\n\tscm := scms[0]\n\n\tfds, err := unix.ParseUnixRights(&scm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(fds) != 1 {\n\t\treturn nil, fmt.Errorf(\"recvfd: number of fds is not 1: %d\", len(fds))\n\t}\n\tfd := uintptr(fds[0])\n\n\treturn os.NewFile(fd, string(name)), nil\n}\n\n\/\/ SendFd sends a file descriptor over the given AF_UNIX socket. In\n\/\/ addition, the file.Name() of the given file will also be sent as\n\/\/ non-auxiliary data in the same payload (allowing to send contextual\n\/\/ information for a file descriptor).\nfunc SendFd(socket *os.File, name string, fd uintptr) error {\n\tif len(name) >= MaxNameLen {\n\t\treturn fmt.Errorf(\"sendfd: filename too long: %s\", name)\n\t}\n\treturn SendFds(socket, []byte(name), int(fd))\n}\n\n\/\/ SendFds sends a list of files descriptor and msg over the given AF_UNIX socket.\nfunc SendFds(socket *os.File, msg []byte, fds ...int) error {\n\toob := unix.UnixRights(fds...)\n\treturn unix.Sendmsg(int(socket.Fd()), msg, oob, nil, 0)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Keybase Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD\n\/\/ license that can be found in the LICENSE file.\n\npackage libkbfs\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/keybase\/client\/go\/libkb\"\n\t\"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n\t\"github.com\/keybase\/go-framed-msgpack-rpc\"\n)\n\nconst (\n\t\/\/ StatusCodeMDServerError is the error code for a generic server error.\n\tStatusCodeMDServerError = 2800\n\t\/\/ StatusCodeMDServerErrorBadRequest is the error code for a generic client error.\n\tStatusCodeMDServerErrorBadRequest = 2801\n\t\/\/ StatusCodeMDServerErrorConflictRevision is the error code for a revision conflict error.\n\tStatusCodeMDServerErrorConflictRevision = 2802\n\t\/\/ StatusCodeMDServerErrorConflictPrevRoot is the error code for a PrevRoot pointer conflict error.\n\tStatusCodeMDServerErrorConflictPrevRoot = 2803\n\t\/\/ StatusCodeMDServerErrorConflictDiskUsage is the error code for a disk usage conflict error.\n\tStatusCodeMDServerErrorConflictDiskUsage = 2804\n\t\/\/ StatusCodeMDServerErrorLocked is the error code to indicate the folder truncation lock is locked.\n\tStatusCodeMDServerErrorLocked = 2805\n\t\/\/ StatusCodeMDServerErrorUnauthorized is the error code to indicate the client is unauthorized to perform\n\t\/\/ a certain operation. This is also used to indicate an object isn't found.\n\tStatusCodeMDServerErrorUnauthorized = 2806\n\t\/\/ StatusCodeMDServerErrorThrottle is the error code to indicate the client should initiate backoff.\n\tStatusCodeMDServerErrorThrottle = 2807\n\t\/\/ StatusCodeMDServerErrorConditionFailed is the error code to indicate the write condition failed.\n\tStatusCodeMDServerErrorConditionFailed = 2808\n\t\/\/ StatusCodeMDServerErrorWriteAccess is the error code to indicate the client isn't authorized to\n\t\/\/ write to a TLF.\n\tStatusCodeMDServerErrorWriteAccess = 2809\n\t\/\/ StatusCodeMDServerErrorConflictFolderMapping is the error code for a folder handle to folder ID\n\t\/\/ mapping conflict error.\n\tStatusCodeMDServerErrorConflictFolderMapping = 2810\n)\n\n\/\/ MDServerError is a generic server-side error.\ntype MDServerError struct {\n\tErr error\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerError.\nfunc (e MDServerError) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerError\n\ts.Name = \"SERVER_ERROR\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ Error implements the Error interface for MDServerError.\nfunc (e MDServerError) Error() string {\n\tif e.Err != nil {\n\t\treturn e.Err.Error()\n\t}\n\treturn \"MDServerError\"\n}\n\n\/\/ MDServerErrorBadRequest is a generic client-side error.\ntype MDServerErrorBadRequest struct {\n\tReason string\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorBadRequest.\nfunc (e MDServerErrorBadRequest) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorBadRequest\n\ts.Name = \"BAD_REQUEST\"\n\ts.Desc = e.Reason\n\treturn\n}\n\n\/\/ Error implements the Error interface for MDServerErrorBadRequest.\nfunc (e MDServerErrorBadRequest) Error() string {\n\treturn fmt.Sprintf(\"Bad MD server request: %s\", e.Reason)\n}\n\n\/\/ MDServerErrorConflictRevision is returned when the passed MD block is inconsistent with current history.\ntype MDServerErrorConflictRevision struct {\n\tDesc     string\n\tExpected MetadataRevision\n\tActual   MetadataRevision\n}\n\n\/\/ Error implements the Error interface for MDServerErrorConflictRevision.\nfunc (e MDServerErrorConflictRevision) Error() string {\n\tif e.Desc == \"\" {\n\t\treturn fmt.Sprintf(\"Conflict: expected revision %d, actual %d\", e.Expected, e.Actual)\n\t}\n\treturn \"MDServerConflictRevision{\" + e.Desc + \"}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorConflictRevision.\nfunc (e MDServerErrorConflictRevision) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorConflictRevision\n\ts.Name = \"CONFLICT_REVISION\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ MDServerErrorConflictPrevRoot is returned when the passed MD block is inconsistent with current history.\ntype MDServerErrorConflictPrevRoot struct {\n\tDesc     string\n\tExpected MdID\n\tActual   MdID\n}\n\n\/\/ Error implements the Error interface for MDServerErrorConflictPrevRoot.\nfunc (e MDServerErrorConflictPrevRoot) Error() string {\n\tif e.Desc == \"\" {\n\t\treturn fmt.Sprintf(\"Conflict: expected previous root %v, actual %v\", e.Expected, e.Actual)\n\t}\n\treturn \"MDServerConflictPrevRoot{\" + e.Desc + \"}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorConflictPrevRoot.\nfunc (e MDServerErrorConflictPrevRoot) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorConflictPrevRoot\n\ts.Name = \"CONFLICT_PREV_ROOT\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ MDServerErrorConflictDiskUsage is returned when the passed MD block is inconsistent with current history.\ntype MDServerErrorConflictDiskUsage struct {\n\tDesc     string\n\tExpected uint64\n\tActual   uint64\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorConflictDiskUsage.\nfunc (e MDServerErrorConflictDiskUsage) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorConflictDiskUsage\n\ts.Name = \"CONFLICT_DISK_USAGE\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ Error implements the Error interface for MDServerErrorConflictDiskUsage\nfunc (e MDServerErrorConflictDiskUsage) Error() string {\n\tif e.Desc == \"\" {\n\t\treturn fmt.Sprintf(\"Conflict: expected disk usage %d, actual %d\", e.Expected, e.Actual)\n\t}\n\treturn \"MDServerConflictDiskUsage{\" + e.Desc + \"}\"\n}\n\n\/\/ MDServerErrorLocked is returned when the folder truncation lock is acquired by someone else.\ntype MDServerErrorLocked struct {\n}\n\n\/\/ Error implements the Error interface for MDServerErrorLocked.\nfunc (e MDServerErrorLocked) Error() string {\n\treturn \"MDServerErrorLocked{}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorLocked.\nfunc (e MDServerErrorLocked) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorLocked\n\ts.Name = \"LOCKED\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ MDServerErrorUnauthorized is returned when a device requests a key half which doesn't belong to it.\ntype MDServerErrorUnauthorized struct {\n\tErr error\n}\n\n\/\/ Error implements the Error interface for MDServerErrorUnauthorized.\nfunc (e MDServerErrorUnauthorized) Error() string {\n\tmsg := \"MDServer Unauthorized\"\n\tif e.Err != nil {\n\t\tmsg += \": \" + e.Err.Error()\n\t}\n\treturn msg\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorUnauthorized.\nfunc (e MDServerErrorUnauthorized) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorUnauthorized\n\ts.Name = \"UNAUTHORIZED\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ MDServerErrorWriteAccess is returned when the client isn't authorized to\n\/\/ write to a TLF.\ntype MDServerErrorWriteAccess struct{}\n\n\/\/ Error implements the Error interface for MDServerErrorWriteAccess.\nfunc (e MDServerErrorWriteAccess) Error() string {\n\treturn \"MDServerErrorWriteAccess{}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorWriteAccess.\nfunc (e MDServerErrorWriteAccess) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorWriteAccess\n\ts.Name = \"WRITE_ACCESS\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ MDServerErrorThrottle is returned when the server wants the client to backoff.\ntype MDServerErrorThrottle struct {\n\tErr error\n}\n\n\/\/ Error implements the Error interface for MDServerErrorThrottle.\nfunc (e MDServerErrorThrottle) Error() string {\n\treturn \"MDServerErrorThrottle{\" + e.Err.Error() + \"}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorThrottle.\nfunc (e MDServerErrorThrottle) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorThrottle\n\ts.Name = \"THROTTLE\"\n\ts.Desc = e.Err.Error()\n\treturn\n}\n\n\/\/ MDServerErrorConditionFailed is returned when a conditonal write failed.\n\/\/ This means there was a race and the caller should consider it a conflcit.\ntype MDServerErrorConditionFailed struct {\n\tErr error\n}\n\n\/\/ Error implements the Error interface for MDServerErrorConditionFailed.\nfunc (e MDServerErrorConditionFailed) Error() string {\n\treturn \"MDServerErrorConditionFailed{\" + e.Err.Error() + \"}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorConditionFailed.\nfunc (e MDServerErrorConditionFailed) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorThrottle\n\ts.Name = \"CONDITION_FAILED\"\n\ts.Desc = e.Err.Error()\n\treturn\n}\n\n\/\/ MDServerErrorConflictFolderMapping is returned when there is a folder handle to folder\n\/\/ ID mapping mismatch.\ntype MDServerErrorConflictFolderMapping struct {\n\tDesc     string\n\tExpected TlfID\n\tActual   TlfID\n}\n\n\/\/ Error implements the Error interface for MDServerErrorConflictFolderMapping.\nfunc (e MDServerErrorConflictFolderMapping) Error() string {\n\tif e.Desc == \"\" {\n\t\treturn fmt.Sprintf(\"Conflict: expected folder ID %s, actual %s\",\n\t\t\te.Expected, e.Actual)\n\t}\n\treturn \"MDServerErrorConflictFolderMapping{\" + e.Desc + \"}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorConflictFolderMapping\nfunc (e MDServerErrorConflictFolderMapping) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorConflictFolderMapping\n\ts.Name = \"CONFLICT_FOLDER_MAPPING\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ MDServerErrorUnwrapper is an implementation of rpc.ErrorUnwrapper\n\/\/ for errors coming from the MDServer.\ntype MDServerErrorUnwrapper struct{}\n\nvar _ rpc.ErrorUnwrapper = MDServerErrorUnwrapper{}\n\n\/\/ MakeArg implements rpc.ErrorUnwrapper for MDServerErrorUnwrapper.\nfunc (eu MDServerErrorUnwrapper) MakeArg() interface{} {\n\treturn &keybase1.Status{}\n}\n\n\/\/ UnwrapError implements rpc.ErrorUnwrapper for MDServerErrorUnwrapper.\nfunc (eu MDServerErrorUnwrapper) UnwrapError(arg interface{}) (appError error, dispatchError error) {\n\ts, ok := arg.(*keybase1.Status)\n\tif !ok {\n\t\treturn nil, errors.New(\"Error converting arg to keybase1.Status object in MDServerErrorUnwrapper.UnwrapError\")\n\t}\n\n\tif s == nil || s.Code == 0 {\n\t\treturn nil, nil\n\t}\n\n\tswitch s.Code {\n\tcase StatusCodeMDServerError:\n\t\tappError = MDServerError{errors.New(s.Desc)}\n\t\tbreak\n\tcase StatusCodeMDServerErrorBadRequest:\n\t\tappError = MDServerErrorBadRequest{Reason: s.Desc}\n\t\tbreak\n\tcase StatusCodeMDServerErrorConflictRevision:\n\t\tappError = MDServerErrorConflictRevision{Desc: s.Desc}\n\t\tbreak\n\tcase StatusCodeMDServerErrorConflictPrevRoot:\n\t\tappError = MDServerErrorConflictPrevRoot{Desc: s.Desc}\n\t\tbreak\n\tcase StatusCodeMDServerErrorConflictDiskUsage:\n\t\tappError = MDServerErrorConflictDiskUsage{Desc: s.Desc}\n\t\tbreak\n\tcase StatusCodeMDServerErrorLocked:\n\t\tappError = MDServerErrorLocked{}\n\t\tbreak\n\tcase StatusCodeMDServerErrorUnauthorized:\n\t\tappError = MDServerErrorUnauthorized{}\n\t\tbreak\n\tcase StatusCodeMDServerErrorThrottle:\n\t\tappError = MDServerErrorThrottle{errors.New(s.Desc)}\n\t\tbreak\n\tcase StatusCodeMDServerErrorConditionFailed:\n\t\tappError = MDServerErrorConditionFailed{errors.New(s.Desc)}\n\t\tbreak\n\tcase StatusCodeMDServerErrorWriteAccess:\n\t\tappError = MDServerErrorWriteAccess{}\n\t\tbreak\n\tcase StatusCodeMDServerErrorConflictFolderMapping:\n\t\tappError = MDServerErrorConflictFolderMapping{Desc: s.Desc}\n\t\tbreak\n\tdefault:\n\t\tase := libkb.AppStatusError{\n\t\t\tCode:   s.Code,\n\t\t\tName:   s.Name,\n\t\t\tDesc:   s.Desc,\n\t\t\tFields: make(map[string]string),\n\t\t}\n\t\tfor _, f := range s.Fields {\n\t\t\tase.Fields[f.Key] = f.Value\n\t\t}\n\t\tappError = ase\n\t}\n\n\treturn appError, nil\n}\n<commit_msg>Added MDServer error for trying to create too many folders<commit_after>\/\/ Copyright 2016 Keybase Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD\n\/\/ license that can be found in the LICENSE file.\n\npackage libkbfs\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/keybase\/client\/go\/libkb\"\n\t\"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n\t\"github.com\/keybase\/go-framed-msgpack-rpc\"\n)\n\nconst (\n\t\/\/ StatusCodeMDServerError is the error code for a generic server error.\n\tStatusCodeMDServerError = 2800\n\t\/\/ StatusCodeMDServerErrorBadRequest is the error code for a generic client error.\n\tStatusCodeMDServerErrorBadRequest = 2801\n\t\/\/ StatusCodeMDServerErrorConflictRevision is the error code for a revision conflict error.\n\tStatusCodeMDServerErrorConflictRevision = 2802\n\t\/\/ StatusCodeMDServerErrorConflictPrevRoot is the error code for a PrevRoot pointer conflict error.\n\tStatusCodeMDServerErrorConflictPrevRoot = 2803\n\t\/\/ StatusCodeMDServerErrorConflictDiskUsage is the error code for a disk usage conflict error.\n\tStatusCodeMDServerErrorConflictDiskUsage = 2804\n\t\/\/ StatusCodeMDServerErrorLocked is the error code to indicate the folder truncation lock is locked.\n\tStatusCodeMDServerErrorLocked = 2805\n\t\/\/ StatusCodeMDServerErrorUnauthorized is the error code to indicate the client is unauthorized to perform\n\t\/\/ a certain operation. This is also used to indicate an object isn't found.\n\tStatusCodeMDServerErrorUnauthorized = 2806\n\t\/\/ StatusCodeMDServerErrorThrottle is the error code to indicate the client should initiate backoff.\n\tStatusCodeMDServerErrorThrottle = 2807\n\t\/\/ StatusCodeMDServerErrorConditionFailed is the error code to indicate the write condition failed.\n\tStatusCodeMDServerErrorConditionFailed = 2808\n\t\/\/ StatusCodeMDServerErrorWriteAccess is the error code to indicate the client isn't authorized to\n\t\/\/ write to a TLF.\n\tStatusCodeMDServerErrorWriteAccess = 2809\n\t\/\/ StatusCodeMDServerErrorConflictFolderMapping is the error code for a folder handle to folder ID\n\t\/\/ mapping conflict error.\n\tStatusCodeMDServerErrorConflictFolderMapping = 2810\n\t\/\/ StatusCodeMDServerErrorTooManyFoldersCreated is the error code to\n\t\/\/ indicate that the user has created more folders than their limit.\n\tStatusCodeMDServerErrorTooManyFoldersCreated = 2811\n)\n\n\/\/ MDServerError is a generic server-side error.\ntype MDServerError struct {\n\tErr error\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerError.\nfunc (e MDServerError) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerError\n\ts.Name = \"SERVER_ERROR\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ Error implements the Error interface for MDServerError.\nfunc (e MDServerError) Error() string {\n\tif e.Err != nil {\n\t\treturn e.Err.Error()\n\t}\n\treturn \"MDServerError\"\n}\n\n\/\/ MDServerErrorBadRequest is a generic client-side error.\ntype MDServerErrorBadRequest struct {\n\tReason string\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorBadRequest.\nfunc (e MDServerErrorBadRequest) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorBadRequest\n\ts.Name = \"BAD_REQUEST\"\n\ts.Desc = e.Reason\n\treturn\n}\n\n\/\/ Error implements the Error interface for MDServerErrorBadRequest.\nfunc (e MDServerErrorBadRequest) Error() string {\n\treturn fmt.Sprintf(\"Bad MD server request: %s\", e.Reason)\n}\n\n\/\/ MDServerErrorConflictRevision is returned when the passed MD block is inconsistent with current history.\ntype MDServerErrorConflictRevision struct {\n\tDesc     string\n\tExpected MetadataRevision\n\tActual   MetadataRevision\n}\n\n\/\/ Error implements the Error interface for MDServerErrorConflictRevision.\nfunc (e MDServerErrorConflictRevision) Error() string {\n\tif e.Desc == \"\" {\n\t\treturn fmt.Sprintf(\"Conflict: expected revision %d, actual %d\", e.Expected, e.Actual)\n\t}\n\treturn \"MDServerConflictRevision{\" + e.Desc + \"}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorConflictRevision.\nfunc (e MDServerErrorConflictRevision) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorConflictRevision\n\ts.Name = \"CONFLICT_REVISION\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ MDServerErrorConflictPrevRoot is returned when the passed MD block is inconsistent with current history.\ntype MDServerErrorConflictPrevRoot struct {\n\tDesc     string\n\tExpected MdID\n\tActual   MdID\n}\n\n\/\/ Error implements the Error interface for MDServerErrorConflictPrevRoot.\nfunc (e MDServerErrorConflictPrevRoot) Error() string {\n\tif e.Desc == \"\" {\n\t\treturn fmt.Sprintf(\"Conflict: expected previous root %v, actual %v\", e.Expected, e.Actual)\n\t}\n\treturn \"MDServerConflictPrevRoot{\" + e.Desc + \"}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorConflictPrevRoot.\nfunc (e MDServerErrorConflictPrevRoot) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorConflictPrevRoot\n\ts.Name = \"CONFLICT_PREV_ROOT\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ MDServerErrorConflictDiskUsage is returned when the passed MD block is inconsistent with current history.\ntype MDServerErrorConflictDiskUsage struct {\n\tDesc     string\n\tExpected uint64\n\tActual   uint64\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorConflictDiskUsage.\nfunc (e MDServerErrorConflictDiskUsage) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorConflictDiskUsage\n\ts.Name = \"CONFLICT_DISK_USAGE\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ Error implements the Error interface for MDServerErrorConflictDiskUsage\nfunc (e MDServerErrorConflictDiskUsage) Error() string {\n\tif e.Desc == \"\" {\n\t\treturn fmt.Sprintf(\"Conflict: expected disk usage %d, actual %d\", e.Expected, e.Actual)\n\t}\n\treturn \"MDServerConflictDiskUsage{\" + e.Desc + \"}\"\n}\n\n\/\/ MDServerErrorLocked is returned when the folder truncation lock is acquired by someone else.\ntype MDServerErrorLocked struct {\n}\n\n\/\/ Error implements the Error interface for MDServerErrorLocked.\nfunc (e MDServerErrorLocked) Error() string {\n\treturn \"MDServerErrorLocked{}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorLocked.\nfunc (e MDServerErrorLocked) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorLocked\n\ts.Name = \"LOCKED\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ MDServerErrorUnauthorized is returned when a device requests a key half which doesn't belong to it.\ntype MDServerErrorUnauthorized struct {\n\tErr error\n}\n\n\/\/ Error implements the Error interface for MDServerErrorUnauthorized.\nfunc (e MDServerErrorUnauthorized) Error() string {\n\tmsg := \"MDServer Unauthorized\"\n\tif e.Err != nil {\n\t\tmsg += \": \" + e.Err.Error()\n\t}\n\treturn msg\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorUnauthorized.\nfunc (e MDServerErrorUnauthorized) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorUnauthorized\n\ts.Name = \"UNAUTHORIZED\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ MDServerErrorWriteAccess is returned when the client isn't authorized to\n\/\/ write to a TLF.\ntype MDServerErrorWriteAccess struct{}\n\n\/\/ Error implements the Error interface for MDServerErrorWriteAccess.\nfunc (e MDServerErrorWriteAccess) Error() string {\n\treturn \"MDServerErrorWriteAccess{}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorWriteAccess.\nfunc (e MDServerErrorWriteAccess) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorWriteAccess\n\ts.Name = \"WRITE_ACCESS\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ MDServerErrorThrottle is returned when the server wants the client to backoff.\ntype MDServerErrorThrottle struct {\n\tErr error\n}\n\n\/\/ Error implements the Error interface for MDServerErrorThrottle.\nfunc (e MDServerErrorThrottle) Error() string {\n\treturn \"MDServerErrorThrottle{\" + e.Err.Error() + \"}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorThrottle.\nfunc (e MDServerErrorThrottle) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorThrottle\n\ts.Name = \"THROTTLE\"\n\ts.Desc = e.Err.Error()\n\treturn\n}\n\n\/\/ MDServerErrorConditionFailed is returned when a conditonal write failed.\n\/\/ This means there was a race and the caller should consider it a conflcit.\ntype MDServerErrorConditionFailed struct {\n\tErr error\n}\n\n\/\/ Error implements the Error interface for MDServerErrorConditionFailed.\nfunc (e MDServerErrorConditionFailed) Error() string {\n\treturn \"MDServerErrorConditionFailed{\" + e.Err.Error() + \"}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorConditionFailed.\nfunc (e MDServerErrorConditionFailed) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorThrottle\n\ts.Name = \"CONDITION_FAILED\"\n\ts.Desc = e.Err.Error()\n\treturn\n}\n\n\/\/ MDServerErrorConflictFolderMapping is returned when there is a folder handle to folder\n\/\/ ID mapping mismatch.\ntype MDServerErrorConflictFolderMapping struct {\n\tDesc     string\n\tExpected TlfID\n\tActual   TlfID\n}\n\n\/\/ Error implements the Error interface for MDServerErrorConflictFolderMapping.\nfunc (e MDServerErrorConflictFolderMapping) Error() string {\n\tif e.Desc == \"\" {\n\t\treturn fmt.Sprintf(\"Conflict: expected folder ID %s, actual %s\",\n\t\t\te.Expected, e.Actual)\n\t}\n\treturn \"MDServerErrorConflictFolderMapping{\" + e.Desc + \"}\"\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorConflictFolderMapping\nfunc (e MDServerErrorConflictFolderMapping) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorConflictFolderMapping\n\ts.Name = \"CONFLICT_FOLDER_MAPPING\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ MDServerErrorTooManyFoldersCreated is returned when a user has created more\n\/\/ folders than their limit allows.\ntype MDServerErrorTooManyFoldersCreated struct {\n\tCreated uint64\n\tLimit   uint64\n}\n\n\/\/ Error implements the Error interface for MDServerErrorTooManyFoldersCreated.\nfunc (e MDServerErrorTooManyFoldersCreated) Error() string {\n\treturn fmt.Sprintf(\"Too many folders created. Created: %d, limit: %d\",\n\t\te.Created, e.Limit)\n}\n\n\/\/ ToStatus implements the ExportableError interface for MDServerErrorConflictFolderMapping\nfunc (e MDServerErrorTooManyFoldersCreated) ToStatus() (s keybase1.Status) {\n\ts.Code = StatusCodeMDServerErrorTooManyFoldersCreated\n\ts.Name = \"TOO_MANY_FOLDERS_CREATED\"\n\ts.Desc = e.Error()\n\treturn\n}\n\n\/\/ MDServerErrorUnwrapper is an implementation of rpc.ErrorUnwrapper\n\/\/ for errors coming from the MDServer.\ntype MDServerErrorUnwrapper struct{}\n\nvar _ rpc.ErrorUnwrapper = MDServerErrorUnwrapper{}\n\n\/\/ MakeArg implements rpc.ErrorUnwrapper for MDServerErrorUnwrapper.\nfunc (eu MDServerErrorUnwrapper) MakeArg() interface{} {\n\treturn &keybase1.Status{}\n}\n\n\/\/ UnwrapError implements rpc.ErrorUnwrapper for MDServerErrorUnwrapper.\nfunc (eu MDServerErrorUnwrapper) UnwrapError(arg interface{}) (appError error, dispatchError error) {\n\ts, ok := arg.(*keybase1.Status)\n\tif !ok {\n\t\treturn nil, errors.New(\"Error converting arg to keybase1.Status object in MDServerErrorUnwrapper.UnwrapError\")\n\t}\n\n\tif s == nil || s.Code == 0 {\n\t\treturn nil, nil\n\t}\n\n\tswitch s.Code {\n\tcase StatusCodeMDServerError:\n\t\tappError = MDServerError{errors.New(s.Desc)}\n\t\tbreak\n\tcase StatusCodeMDServerErrorBadRequest:\n\t\tappError = MDServerErrorBadRequest{Reason: s.Desc}\n\t\tbreak\n\tcase StatusCodeMDServerErrorConflictRevision:\n\t\tappError = MDServerErrorConflictRevision{Desc: s.Desc}\n\t\tbreak\n\tcase StatusCodeMDServerErrorConflictPrevRoot:\n\t\tappError = MDServerErrorConflictPrevRoot{Desc: s.Desc}\n\t\tbreak\n\tcase StatusCodeMDServerErrorConflictDiskUsage:\n\t\tappError = MDServerErrorConflictDiskUsage{Desc: s.Desc}\n\t\tbreak\n\tcase StatusCodeMDServerErrorLocked:\n\t\tappError = MDServerErrorLocked{}\n\t\tbreak\n\tcase StatusCodeMDServerErrorUnauthorized:\n\t\tappError = MDServerErrorUnauthorized{}\n\t\tbreak\n\tcase StatusCodeMDServerErrorThrottle:\n\t\tappError = MDServerErrorThrottle{errors.New(s.Desc)}\n\t\tbreak\n\tcase StatusCodeMDServerErrorConditionFailed:\n\t\tappError = MDServerErrorConditionFailed{errors.New(s.Desc)}\n\t\tbreak\n\tcase StatusCodeMDServerErrorWriteAccess:\n\t\tappError = MDServerErrorWriteAccess{}\n\t\tbreak\n\tcase StatusCodeMDServerErrorConflictFolderMapping:\n\t\tappError = MDServerErrorConflictFolderMapping{Desc: s.Desc}\n\t\tbreak\n\tcase StatusCodeMDServerErrorTooManyFoldersCreated:\n\t\tappError = MDServerErrorTooManyFoldersCreated{}\n\t\tbreak\n\tdefault:\n\t\tase := libkb.AppStatusError{\n\t\t\tCode:   s.Code,\n\t\t\tName:   s.Name,\n\t\t\tDesc:   s.Desc,\n\t\t\tFields: make(map[string]string),\n\t\t}\n\t\tfor _, f := range s.Fields {\n\t\t\tase.Fields[f.Key] = f.Value\n\t\t}\n\t\tappError = ase\n\t}\n\n\treturn appError, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package builder\n\nimport (\n\t\"strings\"\n)\n\ntype Query struct {\n\tTypeQuery     string\n\tColumns       []interface{}\n\tTableName     string\n\tWhereCond     []WhereStruct\n\tGroupByStruct []interface{}\n}\n\ntype WhereStruct struct {\n\tExpression string\n\tValue      interface{}\n\tDelimiter  string\n}\n\nfunc Select(columns ...interface{}) *Query {\n\n\treturn &Query{\n\t\tColumns:   columns,\n\t\tTypeQuery: \"Select\",\n\t}\n}\n\nfunc (query *Query) From(table string) *Query {\n\tquery.TableName = strings.Replace(table, \" \", \"\", -1)\n\treturn query\n}\n\nfunc (query *Query) FromSubquery(table string) *Query {\n\tquery.TableName = \"(\" + table + \")\"\n\treturn query\n}\n\nfunc (query *Query) Where(query_str string, value interface{}) *Query {\n\tquery.WhereCond = append(query.WhereCond, WhereStruct{Expression: query_str, Value: value})\n\treturn query\n}\n\nfunc (query *Query) And(query_str string, value interface{}) *Query {\n\tquery.WhereCond = append(query.WhereCond, WhereStruct{Expression: query_str, Value: value, Delimiter: \" And \"})\n\treturn query\n}\n\nfunc (query *Query) Or(query_str string, value interface{}) *Query {\n\tquery.WhereCond = append(query.WhereCond, WhereStruct{Expression: query_str, Value: value, Delimiter: \" Or \"})\n\treturn query\n}\n\nfunc (query *Query) GroupBy(values ...interface{}) *Query {\n\tquery.GroupByStruct = values\n\treturn query\n}\n<commit_msg>GroupBy - replace ...interface to interface<commit_after>package builder\n\nimport (\n\t\"strings\"\n)\n\ntype Query struct {\n\tTypeQuery     string\n\tColumns       []interface{}\n\tTableName     string\n\tWhereCond     []WhereStruct\n\tGroupByStruct []interface{}\n}\n\ntype WhereStruct struct {\n\tExpression string\n\tValue      interface{}\n\tDelimiter  string\n}\n\nfunc Select(columns ...interface{}) *Query {\n\n\treturn &Query{\n\t\tColumns:   columns,\n\t\tTypeQuery: \"Select\",\n\t}\n}\n\nfunc (query *Query) From(table string) *Query {\n\tquery.TableName = strings.Replace(table, \" \", \"\", -1)\n\treturn query\n}\n\nfunc (query *Query) FromSubquery(table string) *Query {\n\tquery.TableName = \"(\" + table + \")\"\n\treturn query\n}\n\nfunc (query *Query) Where(query_str string, value interface{}) *Query {\n\tquery.WhereCond = append(query.WhereCond, WhereStruct{Expression: query_str, Value: value})\n\treturn query\n}\n\nfunc (query *Query) And(query_str string, value interface{}) *Query {\n\tquery.WhereCond = append(query.WhereCond, WhereStruct{Expression: query_str, Value: value, Delimiter: \" And \"})\n\treturn query\n}\n\nfunc (query *Query) Or(query_str string, value interface{}) *Query {\n\tquery.WhereCond = append(query.WhereCond, WhereStruct{Expression: query_str, Value: value, Delimiter: \" Or \"})\n\treturn query\n}\n\nfunc (query *Query) GroupBy(values interface{}) *Query {\n\tquery.GroupByStruct = values\n\treturn query\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/gophergala2016\/sendto\/client\"\n)\n\nconst (\n\tv = \"0.1\"\n)\n\nfunc main() {\n\tcommand := \"\"\n\targs := os.Args[1:] \/\/ remove app path from args\n\n\t\/\/ We expect either a username or a subcommand and then a set of files in args\n\tif len(args) > 0 {\n\t\tcommand = args[0]\n\t\targs = args[1:]\n\t}\n\n\t\/\/ Load our configuration\n\terr := client.LoadConfig()\n\tif err != nil {\n\t\tlog.Fatalf(\"Sorry, an error occurred:\\n\\t%s\", err)\n\t}\n\n\tswitch command {\n\tcase \"encrypt\", \"e\":\n\t\terr = Encrypt(args)\n\tcase \"decrypt\", \"d\":\n\t\terr = Decrypt(args)\n\tcase \"identity\", \"i\":\n\t\terr = Identity(args)\n\tcase \"version\", \"v\":\n\t\tVersion()\n\tcase \"help\", \"h\":\n\t\tHelp()\n\tdefault:\n\t\t\/\/ Default action is to send to (if we have a username and files)\n\t\tif len(args) > 0 {\n\t\t\terr = SendTo(command, args)\n\t\t} else {\n\t\t\tHelp()\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Sorry, an error occurred:\\n\\t%s\", err)\n\t}\n}\n\n\/\/ Version prints the version of this app\nfunc Version() {\n\tfmt.Printf(\"\\n\\t-----\\n\\tSend to client - version:%s\\n\\t-----\\n\", v)\n}\n\n\/\/ Usage returns standard usage as a string\nfunc Usage() string {\n\treturn fmt.Sprintf(\"\\tUsage: sendto kennygrant [files] - send files to the username kennygrant\\n\")\n}\n\n\/\/ Help prints the usage and commands\nfunc Help() {\n\tVersion()\n\tfmt.Printf(Usage())\n\tfmt.Printf(\"\\t-----\\n\")\n\tfmt.Printf(\"\\tCommands:\\n\")\n\tfmt.Printf(\"\\tsendto version - display version\\n\")\n\tfmt.Printf(\"\\tsendto [username] [files] - encrypt files for a given user\\n\")\n\tfmt.Printf(\"\\tsendto encrypt [file] - encrypt a file\\n\")\n\t\/\/\tfmt.Printf(\"\\tsendto decrypt [file] - decrypt a file\\n\")\n\tfmt.Printf(\"\\tsendto identity [name] - sets default sender identity\\n\\n\")\n}\n\n\/\/ Decrypt files specified, using the user's private key\n\/\/ TODO: to support decryption we'd need access to private keys, perhaps leave this for hackathon\nfunc Decrypt(args []string) error {\n\tlog.Printf(\"Sorry, this client does not yet support decrypt\")\n\n\treturn nil\n}\n\n\/\/ Encrypt the files specified\nfunc Encrypt(args []string) error {\n\n\tlog.Printf(\"Sorry, this client does not yet support encryption\")\n\treturn nil\n}\n\n\/\/ SendTo sends files held in args to recipient\nfunc SendTo(recipient string, args []string) error {\n\n\t\/\/ We expect at least 1 file to send\n\tif len(args) < 1 {\n\t\treturn fmt.Errorf(\"Not enough arguments - %s\", Usage())\n\t}\n\n\t\/\/ Notify the user that we're starting to send\n\tfmt.Printf(\"Sending %d %s to %s as %s...\\n\", len(args), filesString(len(args)), recipient, client.Config[\"sender\"])\n\n\t\/\/ Fetch the recipient's key (from disk or server)\n\n\t\/\/ For the moment as a test, use keybase.io, should be using our server\n\tkeyURL := fmt.Sprintf(client.Config[\"keyserver\"], recipient)\n\tkeyPath, err := client.LoadKey(recipient, keyURL)\n\tif err != nil {\n\t\t\/\/ Warn user in a nicer way here that key could not be found\n\t\treturn fmt.Errorf(\"Failed to find key:%s\", err)\n\t}\n\tfmt.Printf(\"Loaded key for %s:\\n%s\\n\", recipient, keyPath)\n\n\t\/\/ Zip and Encrypt our arguments (files or folders) using key\n\tdataPath, err := client.EncryptFiles(args, recipient, keyPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Send the file to the recipient on the server\n\tpostURL := fmt.Sprintf(\"%s\/files\/create\", client.Config[\"server\"])\n\n\tfmt.Printf(\"Sending files for %s to %s\\n\", recipient, postURL)\n\n\terr = client.PostData(client.Config[\"sender\"], recipient, dataPath, postURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Identity sets the default sender identity (as opposed to username)\nfunc Identity(args []string) error {\n\tif len(args) < 1 {\n\t\treturn fmt.Errorf(\"Identity command requires a sender name\")\n\t}\n\n\tidentity := args[0]\n\tclient.Config[\"sender\"] = identity\n\n\tfmt.Printf(\"Setting sender identity to:%s\\n\", identity)\n\n\treturn client.SaveConfig()\n}\n\n\/\/ Perhaps also allow setting default server?\n\n\/\/ Return a nicely formatted string for the word files\nfunc filesString(i int) string {\n\tif i > 1 {\n\t\treturn \"files\"\n\t}\n\treturn \"file\"\n}\n<commit_msg>Fix import<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/send-to\/sendto\/client\"\n)\n\nconst (\n\tv = \"0.1\"\n)\n\nfunc main() {\n\tcommand := \"\"\n\targs := os.Args[1:] \/\/ remove app path from args\n\n\t\/\/ We expect either a username or a subcommand and then a set of files in args\n\tif len(args) > 0 {\n\t\tcommand = args[0]\n\t\targs = args[1:]\n\t}\n\n\t\/\/ Load our configuration\n\terr := client.LoadConfig()\n\tif err != nil {\n\t\tlog.Fatalf(\"Sorry, an error occurred:\\n\\t%s\", err)\n\t}\n\n\tswitch command {\n\tcase \"encrypt\", \"e\":\n\t\terr = Encrypt(args)\n\tcase \"decrypt\", \"d\":\n\t\terr = Decrypt(args)\n\tcase \"identity\", \"i\":\n\t\terr = Identity(args)\n\tcase \"version\", \"v\":\n\t\tVersion()\n\tcase \"help\", \"h\":\n\t\tHelp()\n\tdefault:\n\t\t\/\/ Default action is to send to (if we have a username and files)\n\t\tif len(args) > 0 {\n\t\t\terr = SendTo(command, args)\n\t\t} else {\n\t\t\tHelp()\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Sorry, an error occurred:\\n\\t%s\", err)\n\t}\n}\n\n\/\/ Version prints the version of this app\nfunc Version() {\n\tfmt.Printf(\"\\n\\t-----\\n\\tSend to client - version:%s\\n\\t-----\\n\", v)\n}\n\n\/\/ Usage returns standard usage as a string\nfunc Usage() string {\n\treturn fmt.Sprintf(\"\\tUsage: sendto kennygrant [files] - send files to the username kennygrant\\n\")\n}\n\n\/\/ Help prints the usage and commands\nfunc Help() {\n\tVersion()\n\tfmt.Printf(Usage())\n\tfmt.Printf(\"\\t-----\\n\")\n\tfmt.Printf(\"\\tCommands:\\n\")\n\tfmt.Printf(\"\\tsendto version - display version\\n\")\n\tfmt.Printf(\"\\tsendto [username] [files] - encrypt files for a given user\\n\")\n\tfmt.Printf(\"\\tsendto encrypt [file] - encrypt a file\\n\")\n\t\/\/\tfmt.Printf(\"\\tsendto decrypt [file] - decrypt a file\\n\")\n\tfmt.Printf(\"\\tsendto identity [name] - sets default sender identity\\n\\n\")\n}\n\n\/\/ Decrypt files specified, using the user's private key\n\/\/ TODO: to support decryption we'd need access to private keys, perhaps leave this for hackathon\nfunc Decrypt(args []string) error {\n\tlog.Printf(\"Sorry, this client does not yet support decrypt\")\n\n\treturn nil\n}\n\n\/\/ Encrypt the files specified\nfunc Encrypt(args []string) error {\n\n\tlog.Printf(\"Sorry, this client does not yet support encryption\")\n\treturn nil\n}\n\n\/\/ SendTo sends files held in args to recipient\nfunc SendTo(recipient string, args []string) error {\n\n\t\/\/ We expect at least 1 file to send\n\tif len(args) < 1 {\n\t\treturn fmt.Errorf(\"Not enough arguments - %s\", Usage())\n\t}\n\n\t\/\/ Notify the user that we're starting to send\n\tfmt.Printf(\"Sending %d %s to %s as %s...\\n\", len(args), filesString(len(args)), recipient, client.Config[\"sender\"])\n\n\t\/\/ Fetch the recipient's key (from disk or server)\n\n\t\/\/ For the moment as a test, use keybase.io, should be using our server\n\tkeyURL := fmt.Sprintf(client.Config[\"keyserver\"], recipient)\n\tkeyPath, err := client.LoadKey(recipient, keyURL)\n\tif err != nil {\n\t\t\/\/ Warn user in a nicer way here that key could not be found\n\t\treturn fmt.Errorf(\"Failed to find key:%s\", err)\n\t}\n\tfmt.Printf(\"Loaded key for %s:\\n%s\\n\", recipient, keyPath)\n\n\t\/\/ Zip and Encrypt our arguments (files or folders) using key\n\tdataPath, err := client.EncryptFiles(args, recipient, keyPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Send the file to the recipient on the server\n\tpostURL := fmt.Sprintf(\"%s\/files\/create\", client.Config[\"server\"])\n\n\tfmt.Printf(\"Sending files for %s to %s\\n\", recipient, postURL)\n\n\terr = client.PostData(client.Config[\"sender\"], recipient, dataPath, postURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Identity sets the default sender identity (as opposed to username)\nfunc Identity(args []string) error {\n\tif len(args) < 1 {\n\t\treturn fmt.Errorf(\"Identity command requires a sender name\")\n\t}\n\n\tidentity := args[0]\n\tclient.Config[\"sender\"] = identity\n\n\tfmt.Printf(\"Setting sender identity to:%s\\n\", identity)\n\n\treturn client.SaveConfig()\n}\n\n\/\/ Perhaps also allow setting default server?\n\n\/\/ Return a nicely formatted string for the word files\nfunc filesString(i int) string {\n\tif i > 1 {\n\t\treturn \"files\"\n\t}\n\treturn \"file\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package empire\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/gorilla\/mux\"\n)\n\n\/\/ Decoder represents a function that can decode a request into an interface\n\/\/ value.\ntype Decoder func(r *http.Request, v interface{}) error\n\nfunc JSONDecode(r *http.Request, v interface{}) error {\n\treturn json.NewDecoder(r.Body).Decode(v)\n}\n\n\/\/ Request wraps an http.Request for convenience.\ntype Request struct {\n\t*http.Request\n\tVars map[string]string\n\tDecoder\n}\n\n\/\/ NewRequest parse the mux vars and returns a new Request instance.\nfunc NewRequest(r *http.Request) *Request {\n\treturn &Request{Request: r, Vars: mux.Vars(r)}\n}\n\n\/\/ Decode decodes the request using the Decoder.\nfunc (r *Request) Decode(v interface{}) error {\n\td := r.Decoder\n\n\tif d == nil {\n\t\td = JSONDecode\n\t}\n\n\treturn d(r.Request, v)\n}\n\n\/\/ Handler defines an interface for service an HTTP request.\ntype Handler interface {\n\tServe(*Request) (int, interface{}, error)\n}\n\n\/\/ ErrorResource represents the error response format that we return.\ntype ErrorResource struct {\n\tErr string `json:\"error\"`\n}\n\n\/\/ Error implements error interface.\nfunc (e *ErrorResource) Error() string {\n\treturn e.Err\n}\n\n\/\/ Endpoint wraps a Handler to implement the http.Handler interface.\ntype Endpoint struct {\n\tHandler\n}\n\n\/\/ ServeHTTP implements the http.Handler interface. It will parse the form\n\/\/ params, then serve the request, finally JSON encoding the returned value.\nfunc (e *Endpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\treq := NewRequest(r)\n\n\tstatus, v, err := e.Handler.Serve(req)\n\tif err != nil {\n\t\tif _, ok := err.(*ErrorResource); ok {\n\t\t\tv = err\n\t\t} else {\n\t\t\tv = &ErrorResource{Err: err.Error()}\n\t\t}\n\t\tlog.Printf(\"Error: %v\\n\", v)\n\t}\n\n\tw.WriteHeader(status)\n\tjson.NewEncoder(w).Encode(v)\n}\n\n\/\/ Server represents the API.\ntype Server struct {\n\thttp.Handler\n}\n\n\/\/ NewServer creates the API routes and returns a new Server instance.\nfunc NewServer(e *Empire) *Server {\n\tr := newRouter()\n\n\t\/\/ Apps\n\tr.Handle(\"GET\", \"\/apps\", &GetApps{e.AppsService})   \/\/ hk apps\n\tr.Handle(\"POST\", \"\/apps\", &PostApps{e.AppsService}) \/\/ hk create\n\n\t\/\/ Deploys\n\tr.Handle(\"POST\", \"\/deploys\", &PostDeploys{e.DeploysService}) \/\/ Deploy an app\n\n\t\/\/ Releases\n\tr.Handle(\"GET\", \"\/apps\/{app}\/releases\", &GetReleases{e.AppsService, e.ReleasesService}) \/\/ hk releases\n\n\t\/\/ Configs\n\tr.Handle(\"GET\", \"\/apps\/{app}\/config-vars\", &GetConfigs{e.AppsService, e.ConfigsService})                        \/\/ hk env, hk get\n\tr.Handle(\"PATCH\", \"\/apps\/{app}\/config-vars\", &PatchConfigs{e.AppsService, e.ReleasesService, e.ConfigsService}) \/\/ hk set\n\n\t\/\/ Processes\n\tr.Handle(\"GET\", \"\/apps\/{app}\/dynos\", &GetProcesses{e.AppsService, e.Manager}) \/\/ hk dynos\n\n\t\/\/ Formations\n\tr.Handle(\"PATCH\", \"\/apps\/{app}\/formation\", &PatchFormation{e.AppsService, e.ReleasesService, e.Manager}) \/\/ hk scale\n\n\tn := negroni.Classic()\n\tn.UseHandler(r)\n\n\treturn &Server{n}\n}\n\n\/\/ router is an http router for Handlers.\ntype router struct {\n\t*mux.Router\n}\n\n\/\/ newRouter returns a new router instance.\nfunc newRouter() *router {\n\treturn &router{Router: mux.NewRouter()}\n}\n\n\/\/ Handle sets up a route for a Handler.\nfunc (r *router) Handle(method, path string, h Handler) {\n\tr.Router.Handle(path, &Endpoint{Handler: h}).Methods(method)\n}\n\ntype GetApps struct {\n\tAppsService AppsService\n}\n\nfunc (h *GetApps) Serve(req *Request) (int, interface{}, error) {\n\tapps, err := h.AppsService.FindAll()\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\treturn 200, apps, nil\n}\n\ntype PostAppsForm struct {\n\tName string `json:\"name\"`\n\tRepo string `json:\"repo\"`\n}\n\ntype PostApps struct {\n\tAppsService AppsService\n}\n\nfunc (h *PostApps) Serve(req *Request) (int, interface{}, error) {\n\tvar form PostAppsForm\n\n\tif err := req.Decode(&form); err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tapp, err := NewApp(AppName(form.Name), Repo(form.Repo))\n\tif err != nil {\n\t\treturn http.StatusBadRequest, nil, err\n\t}\n\n\ta, err := h.AppsService.Create(app)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\treturn 201, a, nil\n}\n\n\/\/ PostDeploys is a Handler for the POST \/v1\/deploys endpoint.\ntype PostDeploys struct {\n\tDeploysService DeploysService\n}\n\n\/\/ PostDeployForm is the form object that represents the POST body.\ntype PostDeployForm struct {\n\tImage struct {\n\t\tID   string `json:\"id\"`\n\t\tRepo string `json:\"repo\"`\n\t} `json:\"image\"`\n}\n\n\/\/ Serve implements the Handler interface.\nfunc (h *PostDeploys) Serve(req *Request) (int, interface{}, error) {\n\tvar form PostDeployForm\n\n\tif err := req.Decode(&form); err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\td, err := h.DeploysService.Deploy(&Image{\n\t\tRepo: Repo(form.Image.Repo),\n\t\tID:   form.Image.ID,\n\t})\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\treturn 201, d, nil\n}\n\ntype GetReleases struct {\n\tAppsService     AppsService\n\tReleasesService ReleasesService\n}\n\nfunc (h *GetReleases) Serve(req *Request) (int, interface{}, error) {\n\tname := AppName(req.Vars[\"app\"])\n\n\ta, err := h.AppsService.FindByName(name)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tif a == nil {\n\t\treturn http.StatusNotFound, nil, nil\n\t}\n\n\trels, err := h.ReleasesService.FindByApp(a)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\treturn 200, rels, nil\n}\n\ntype GetConfigs struct {\n\tAppsService    AppsService\n\tConfigsService ConfigsService\n}\n\nfunc (h *GetConfigs) Serve(req *Request) (int, interface{}, error) {\n\tname := AppName(req.Vars[\"app\"])\n\n\ta, err := h.AppsService.FindByName(name)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tif a == nil {\n\t\treturn http.StatusNotFound, nil, nil\n\t}\n\n\tc, err := h.ConfigsService.Head(a)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\treturn 200, c.Vars, nil\n}\n\ntype PatchConfigs struct {\n\tAppsService     AppsService\n\tReleasesService ReleasesService\n\tConfigsService  ConfigsService\n}\n\nfunc (h *PatchConfigs) Serve(req *Request) (int, interface{}, error) {\n\tvar configVars Vars\n\n\tif err := req.Decode(&configVars); err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tname := AppName(req.Vars[\"app\"])\n\n\t\/\/ Find app\n\ta, err := h.AppsService.FindByName(name)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tif a == nil {\n\t\treturn http.StatusNotFound, nil, nil\n\t}\n\n\t\/\/ Update the config\n\tc, err := h.ConfigsService.Apply(a, configVars)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\t\/\/ Find current release\n\tr, err := h.ReleasesService.Head(a)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\t\/\/ If there is an existing release, create a new one\n\tif r != nil {\n\t\t\/\/ Create new release based on new config and old slug\n\t\t_, err = h.ReleasesService.Create(a, c, r.Slug)\n\t\tif err != nil {\n\t\t\treturn http.StatusInternalServerError, nil, err\n\t\t}\n\t}\n\n\treturn 200, c.Vars, nil\n}\n\ntype GetProcesses struct {\n\tAppsService AppsService\n\tManager     Manager\n}\n\nfunc (h *GetProcesses) Serve(req *Request) (int, interface{}, error) {\n\tname := AppName(req.Vars[\"app\"])\n\n\ta, err := h.AppsService.FindByName(name)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tif a == nil {\n\t\treturn http.StatusNotFound, nil, nil\n\t}\n\n\t\/\/ Retrieve job states\n\tjs, err := h.Manager.JobStatesByApp(a)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\treturn 200, js, nil\n}\n\ntype PatchFormation struct {\n\tAppsService     AppsService\n\tReleasesService ReleasesService\n\tManager         Manager\n}\n\ntype PatchFormationForm struct {\n\tUpdates []struct {\n\t\tProcess  string `json:\"process\"` \/\/ Refers to process type\n\t\tQuantity int    `json:\"quantity\"`\n\t\tSize     string `json:\"size\"`\n\t} `json:\"updates\"`\n}\n\nfunc (h *PatchFormation) Serve(req *Request) (int, interface{}, error) {\n\tvar form PatchFormationForm\n\n\tif err := req.Decode(&form); err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tname := AppName(req.Vars[\"app\"])\n\n\ta, err := h.AppsService.FindByName(name)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tif a == nil {\n\t\treturn http.StatusNotFound, nil, nil\n\t}\n\n\tqm := ProcessQuantityMap{}\n\tfor _, up := range form.Updates {\n\t\tqm[ProcessType(up.Process)] = up.Quantity\n\t}\n\n\tr, err := h.ReleasesService.Head(a)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tif r == nil {\n\t\treturn http.StatusNotFound, nil, nil\n\t}\n\n\terr = h.Manager.ScaleRelease(r, qm)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\treturn 200, nil, nil\n}\n<commit_msg>Add hk compat output<commit_after>package empire\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/gorilla\/mux\"\n)\n\n\/\/ Decoder represents a function that can decode a request into an interface\n\/\/ value.\ntype Decoder func(r *http.Request, v interface{}) error\n\nfunc JSONDecode(r *http.Request, v interface{}) error {\n\treturn json.NewDecoder(r.Body).Decode(v)\n}\n\n\/\/ Request wraps an http.Request for convenience.\ntype Request struct {\n\t*http.Request\n\tVars map[string]string\n\tDecoder\n}\n\n\/\/ NewRequest parse the mux vars and returns a new Request instance.\nfunc NewRequest(r *http.Request) *Request {\n\treturn &Request{Request: r, Vars: mux.Vars(r)}\n}\n\n\/\/ Decode decodes the request using the Decoder.\nfunc (r *Request) Decode(v interface{}) error {\n\td := r.Decoder\n\n\tif d == nil {\n\t\td = JSONDecode\n\t}\n\n\treturn d(r.Request, v)\n}\n\n\/\/ Handler defines an interface for service an HTTP request.\ntype Handler interface {\n\tServe(*Request) (int, interface{}, error)\n}\n\n\/\/ ErrorResource represents the error response format that we return.\ntype ErrorResource struct {\n\tErr string `json:\"error\"`\n}\n\n\/\/ Error implements error interface.\nfunc (e *ErrorResource) Error() string {\n\treturn e.Err\n}\n\n\/\/ Endpoint wraps a Handler to implement the http.Handler interface.\ntype Endpoint struct {\n\tHandler\n}\n\n\/\/ ServeHTTP implements the http.Handler interface. It will parse the form\n\/\/ params, then serve the request, finally JSON encoding the returned value.\nfunc (e *Endpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\treq := NewRequest(r)\n\n\tstatus, v, err := e.Handler.Serve(req)\n\tif err != nil {\n\t\tif _, ok := err.(*ErrorResource); ok {\n\t\t\tv = err\n\t\t} else {\n\t\t\tv = &ErrorResource{Err: err.Error()}\n\t\t}\n\t\tlog.Printf(\"Error: %v\\n\", v)\n\t}\n\n\tw.WriteHeader(status)\n\tjson.NewEncoder(w).Encode(v)\n}\n\n\/\/ Server represents the API.\ntype Server struct {\n\thttp.Handler\n}\n\n\/\/ NewServer creates the API routes and returns a new Server instance.\nfunc NewServer(e *Empire) *Server {\n\tr := newRouter()\n\n\t\/\/ Apps\n\tr.Handle(\"GET\", \"\/apps\", &GetApps{e.AppsService})   \/\/ hk apps\n\tr.Handle(\"POST\", \"\/apps\", &PostApps{e.AppsService}) \/\/ hk create\n\n\t\/\/ Deploys\n\tr.Handle(\"POST\", \"\/deploys\", &PostDeploys{e.DeploysService}) \/\/ Deploy an app\n\n\t\/\/ Releases\n\tr.Handle(\"GET\", \"\/apps\/{app}\/releases\", &GetReleases{e.AppsService, e.ReleasesService}) \/\/ hk releases\n\n\t\/\/ Configs\n\tr.Handle(\"GET\", \"\/apps\/{app}\/config-vars\", &GetConfigs{e.AppsService, e.ConfigsService})                        \/\/ hk env, hk get\n\tr.Handle(\"PATCH\", \"\/apps\/{app}\/config-vars\", &PatchConfigs{e.AppsService, e.ReleasesService, e.ConfigsService}) \/\/ hk set\n\n\t\/\/ Processes\n\tr.Handle(\"GET\", \"\/apps\/{app}\/dynos\", &GetProcesses{e.AppsService, e.Manager}) \/\/ hk dynos\n\n\t\/\/ Formations\n\tr.Handle(\"PATCH\", \"\/apps\/{app}\/formation\", &PatchFormation{e.AppsService, e.ReleasesService, e.Manager}) \/\/ hk scale\n\n\tn := negroni.Classic()\n\tn.UseHandler(r)\n\n\treturn &Server{n}\n}\n\n\/\/ router is an http router for Handlers.\ntype router struct {\n\t*mux.Router\n}\n\n\/\/ newRouter returns a new router instance.\nfunc newRouter() *router {\n\treturn &router{Router: mux.NewRouter()}\n}\n\n\/\/ Handle sets up a route for a Handler.\nfunc (r *router) Handle(method, path string, h Handler) {\n\tr.Router.Handle(path, &Endpoint{Handler: h}).Methods(method)\n}\n\ntype GetApps struct {\n\tAppsService AppsService\n}\n\nfunc (h *GetApps) Serve(req *Request) (int, interface{}, error) {\n\tapps, err := h.AppsService.FindAll()\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\treturn 200, apps, nil\n}\n\ntype PostAppsForm struct {\n\tName string `json:\"name\"`\n\tRepo string `json:\"repo\"`\n}\n\ntype PostApps struct {\n\tAppsService AppsService\n}\n\nfunc (h *PostApps) Serve(req *Request) (int, interface{}, error) {\n\tvar form PostAppsForm\n\n\tif err := req.Decode(&form); err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tapp, err := NewApp(AppName(form.Name), Repo(form.Repo))\n\tif err != nil {\n\t\treturn http.StatusBadRequest, nil, err\n\t}\n\n\ta, err := h.AppsService.Create(app)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\treturn 201, a, nil\n}\n\n\/\/ PostDeploys is a Handler for the POST \/v1\/deploys endpoint.\ntype PostDeploys struct {\n\tDeploysService DeploysService\n}\n\n\/\/ PostDeployForm is the form object that represents the POST body.\ntype PostDeployForm struct {\n\tImage struct {\n\t\tID   string `json:\"id\"`\n\t\tRepo string `json:\"repo\"`\n\t} `json:\"image\"`\n}\n\n\/\/ Serve implements the Handler interface.\nfunc (h *PostDeploys) Serve(req *Request) (int, interface{}, error) {\n\tvar form PostDeployForm\n\n\tif err := req.Decode(&form); err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\td, err := h.DeploysService.Deploy(&Image{\n\t\tRepo: Repo(form.Image.Repo),\n\t\tID:   form.Image.ID,\n\t})\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\treturn 201, d, nil\n}\n\ntype GetReleases struct {\n\tAppsService     AppsService\n\tReleasesService ReleasesService\n}\n\nfunc (h *GetReleases) Serve(req *Request) (int, interface{}, error) {\n\tname := AppName(req.Vars[\"app\"])\n\n\ta, err := h.AppsService.FindByName(name)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tif a == nil {\n\t\treturn http.StatusNotFound, nil, nil\n\t}\n\n\trels, err := h.ReleasesService.FindByApp(a)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\treturn 200, rels, nil\n}\n\ntype GetConfigs struct {\n\tAppsService    AppsService\n\tConfigsService ConfigsService\n}\n\nfunc (h *GetConfigs) Serve(req *Request) (int, interface{}, error) {\n\tname := AppName(req.Vars[\"app\"])\n\n\ta, err := h.AppsService.FindByName(name)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tif a == nil {\n\t\treturn http.StatusNotFound, nil, nil\n\t}\n\n\tc, err := h.ConfigsService.Head(a)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\treturn 200, c.Vars, nil\n}\n\ntype PatchConfigs struct {\n\tAppsService     AppsService\n\tReleasesService ReleasesService\n\tConfigsService  ConfigsService\n}\n\nfunc (h *PatchConfigs) Serve(req *Request) (int, interface{}, error) {\n\tvar configVars Vars\n\n\tif err := req.Decode(&configVars); err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tname := AppName(req.Vars[\"app\"])\n\n\t\/\/ Find app\n\ta, err := h.AppsService.FindByName(name)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tif a == nil {\n\t\treturn http.StatusNotFound, nil, nil\n\t}\n\n\t\/\/ Update the config\n\tc, err := h.ConfigsService.Apply(a, configVars)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\t\/\/ Find current release\n\tr, err := h.ReleasesService.Head(a)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\t\/\/ If there is an existing release, create a new one\n\tif r != nil {\n\t\t\/\/ Create new release based on new config and old slug\n\t\t_, err = h.ReleasesService.Create(a, c, r.Slug)\n\t\tif err != nil {\n\t\t\treturn http.StatusInternalServerError, nil, err\n\t\t}\n\t}\n\n\treturn 200, c.Vars, nil\n}\n\ntype GetProcesses struct {\n\tAppsService AppsService\n\tManager     Manager\n}\n\ntype dyno struct {\n\tCommand string `json:\"command\"`\n\tName    string `json:\"name\"`\n\tState   string `json:\"state\"`\n}\n\nfunc (h *GetProcesses) Serve(req *Request) (int, interface{}, error) {\n\tname := AppName(req.Vars[\"app\"])\n\n\ta, err := h.AppsService.FindByName(name)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tif a == nil {\n\t\treturn http.StatusNotFound, nil, nil\n\t}\n\n\t\/\/ Retrieve job states\n\tjs, err := h.Manager.JobStatesByApp(a)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\t\/\/ Convert to hk compatible format\n\tdynos := make([]dyno, len(js))\n\tfor i, j := range js {\n\t\tdynos[i] = dyno{\n\t\t\tCommand: string(j.Job.Command),\n\t\t\tName:    string(j.Name),\n\t\t\tState:   j.State,\n\t\t}\n\t}\n\n\treturn 200, dynos, nil\n}\n\ntype PatchFormation struct {\n\tAppsService     AppsService\n\tReleasesService ReleasesService\n\tManager         Manager\n}\n\ntype PatchFormationForm struct {\n\tUpdates []struct {\n\t\tProcess  string `json:\"process\"` \/\/ Refers to process type\n\t\tQuantity int    `json:\"quantity\"`\n\t\tSize     string `json:\"size\"`\n\t} `json:\"updates\"`\n}\n\nfunc (h *PatchFormation) Serve(req *Request) (int, interface{}, error) {\n\tvar form PatchFormationForm\n\n\tif err := req.Decode(&form); err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tname := AppName(req.Vars[\"app\"])\n\n\ta, err := h.AppsService.FindByName(name)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tif a == nil {\n\t\treturn http.StatusNotFound, nil, nil\n\t}\n\n\tqm := ProcessQuantityMap{}\n\tfor _, up := range form.Updates {\n\t\tqm[ProcessType(up.Process)] = up.Quantity\n\t}\n\n\tr, err := h.ReleasesService.Head(a)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\tif r == nil {\n\t\treturn http.StatusNotFound, nil, nil\n\t}\n\n\terr = h.Manager.ScaleRelease(r, qm)\n\tif err != nil {\n\t\treturn http.StatusInternalServerError, nil, err\n\t}\n\n\treturn 200, nil, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The httpserver Authors. All rights reserved.  Use of this\n\/\/ source code is governed by a MIT-style license that can be found in the\n\/\/ LICENSE file.\npackage httpserver\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"text\/template\"\n\n\t\"github.com\/gorilla\/mux\"\n)\n\nconst (\n\tSkipCheckHttpMethod = \"\"\n\tGetMethod           = \"GET\"\n\tPutMethod           = \"PUT\"\n\tPostMethod          = \"POST\"\n\tDeleteMethod        = \"DELETE\"\n)\n\ntype HttpServer struct {\n\tport             string\n\taddress          string\n\terrTemplate      *template.Template\n\tnotFoundTemplate *template.Template\n\tRouter           HttpRouter\n}\n\ntype HttpRouter interface {\n\tHandleFunc(string, func(http.ResponseWriter, *http.Request)) *mux.Route\n\tHandle(string, http.Handler) *mux.Route\n\tServeHTTP(http.ResponseWriter, *http.Request)\n}\n\nfunc NewHttpServer(a string, p string) *HttpServer {\n\trouter := mux.NewRouter()\n\ts := &HttpServer{Router: router, address: a, port: p}\n\treturn s\n}\n\nfunc (s *HttpServer) SetErrTemplate(t *template.Template) {\n\ts.errTemplate = t\n}\n\nfunc (s *HttpServer) SetNotFoundTemplate(t *template.Template) {\n\ts.notFoundTemplate = t\n}\n\nfunc (s *HttpServer) errorHandler(route *Route) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif recoverErr := recover(); recoverErr != nil {\n\t\t\t\terror := NewError(fmt.Sprintf(\"\\\"%v\\\"\", recoverErr))\n\t\t\t\tw.WriteHeader(500)\n\t\t\t\tif s.errTemplate != nil {\n\t\t\t\t\ts.errTemplate.Execute(w, error)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(w, fmt.Sprintf(\"\\\"%v\\\"\", recoverErr))\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tif route.HasIncorrectHttpMethod(r.Method) {\n\t\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\t\treturn\n\t\t}\n\t\troute.HandleFunc(w, r)\n\t}\n}\nfunc (s *HttpServer) NotFound(w http.ResponseWriter, r *http.Request) {\n\n\tw.WriteHeader(404)\n\tif s.notFoundTemplate != nil {\n\t\ts.notFoundTemplate.Execute(w, nil)\n\t} else {\n\t\tfmt.Fprintf(w, \"Not found\")\n\t}\n\n}\n\nfunc (s *HttpServer) DeployAtBase(h RouteHandler) {\n\ts.Deploy(\"\", h)\n}\n\nfunc (s *HttpServer) Deploy(context string, h RouteHandler) {\n\troutes := h.GetRoutes()\n\tfor _, r := range routes {\n\t\ts.Router.HandleFunc(fmt.Sprintf(\"%s\/%s\", context, r.Path), s.errorHandler(r))\n\t}\n}\n\nfunc (s *HttpServer) Start() error {\n\thttp.Handle(\"\/static\/\", http.StripPrefix(\"\/static\/\", http.FileServer(http.Dir(\".\/static\"))))\n\thttp.Handle(\"\/\", s.Router)\n\t\/\/s.Router.NotFoundHandler = http.HandlerFunc(s.NotFound)\n\treturn http.ListenAndServe(fmt.Sprintf(\"%s:%s\", s.address, s.port), nil)\n}\n<commit_msg>notfound handler test<commit_after>\/\/ Copyright 2015 The httpserver Authors. All rights reserved.  Use of this\n\/\/ source code is governed by a MIT-style license that can be found in the\n\/\/ LICENSE file.\npackage httpserver\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"reflect\"\n\t\"text\/template\"\n\n\t\"github.com\/gorilla\/mux\"\n)\n\nconst (\n\tSkipCheckHttpMethod = \"\"\n\tGetMethod           = \"GET\"\n\tPutMethod           = \"PUT\"\n\tPostMethod          = \"POST\"\n\tDeleteMethod        = \"DELETE\"\n)\n\ntype HttpServer struct {\n\tport             string\n\taddress          string\n\terrTemplate      *template.Template\n\tnotFoundTemplate *template.Template\n\tRouter           HttpRouter\n}\n\ntype HttpRouter interface {\n\tHandleFunc(string, func(http.ResponseWriter, *http.Request)) *mux.Route\n\tHandle(string, http.Handler) *mux.Route\n\tServeHTTP(http.ResponseWriter, *http.Request)\n}\n\nfunc NewHttpServer(a string, p string) *HttpServer {\n\trouter := mux.NewRouter()\n\ts := &HttpServer{Router: router, address: a, port: p}\n\treturn s\n}\n\nfunc (s *HttpServer) SetErrTemplate(t *template.Template) {\n\ts.errTemplate = t\n}\n\nfunc (s *HttpServer) SetNotFoundTemplate(t *template.Template) {\n\ts.notFoundTemplate = t\n}\n\nfunc (s *HttpServer) errorHandler(route *Route) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tdefer func() {\n\t\t\tif recoverErr := recover(); recoverErr != nil {\n\t\t\t\terror := NewError(fmt.Sprintf(\"\\\"%v\\\"\", recoverErr))\n\t\t\t\tw.WriteHeader(500)\n\t\t\t\tif s.errTemplate != nil {\n\t\t\t\t\ts.errTemplate.Execute(w, error)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(w, fmt.Sprintf(\"\\\"%v\\\"\", recoverErr))\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t\tif route.HasIncorrectHttpMethod(r.Method) {\n\t\t\thttp.Error(w, \"Method not allowed\", 405)\n\t\t\treturn\n\t\t}\n\t\troute.HandleFunc(w, r)\n\t}\n}\nfunc (s *HttpServer) NotFound(w http.ResponseWriter, r *http.Request) {\n\n\tw.WriteHeader(404)\n\tif s.notFoundTemplate != nil {\n\t\ts.notFoundTemplate.Execute(w, nil)\n\t} else {\n\t\tfmt.Fprintf(w, \"Not found\")\n\t}\n\n}\n\nfunc (s *HttpServer) DeployAtBase(h RouteHandler) {\n\ts.Deploy(\"\", h)\n}\n\nfunc (s *HttpServer) Deploy(context string, h RouteHandler) {\n\troutes := h.GetRoutes()\n\tfor _, r := range routes {\n\t\ts.Router.HandleFunc(fmt.Sprintf(\"%s\/%s\", context, r.Path), s.errorHandler(r))\n\t}\n}\n\nfunc (s *HttpServer) Start() error {\n\thttp.Handle(\"\/static\/\", http.StripPrefix(\"\/static\/\", http.FileServer(http.Dir(\".\/static\"))))\n\thttp.Handle(\"\/\", s.Router)\n\tss := reflect.ValueOf(&s.Router).Elem()\n\ttypeOfT := ss.Type()\n\tfor i := 0; i < ss.NumField(); i++ {\n\t\tf := ss.Field(i)\n\t\tfmt.Printf(\"%d: %s %s = %v\\n\", i,\n\t\t\ttypeOfT.Field(i).Name, f.Type(), f.Interface())\n\t}\n\tfmt.Println(\"egi\")\n\t\/\/http.NotFoundHandler = http.HandlerFunc(s.NotFound)\n\treturn http.ListenAndServe(fmt.Sprintf(\"%s:%s\", s.address, s.port), nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package osc\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"sync\/atomic\"\n\t\"time\"\n\t\"unsafe\"\n)\n\n\/\/ Common errors.\nvar (\n\tErrAlreadyRunning = errors.New(\"server is already running\")\n\tErrNoDispatcher   = errors.New(\"no dispatcher defined\")\n\tErrPrematureClose = errors.New(\"server cannot be closed before calling Listen\")\n\tErrInvalidTypeTag = errors.New(\"invalid type tag\")\n)\n\n\/\/ Server is an OSC server.\ntype Server struct {\n\tAddress     string         \/\/ Address is the listening address.\n\tListening   chan struct{}  \/\/ Listening is a channel used to indicate when the server is running.\n\treadTimeout time.Duration  \/\/ readTimeout is the timeout for reading from a connection.\n\tdispatcher  *OscDispatcher \/\/ Dispatcher that dispatches OSC packets\/messages.\n\trunning     bool           \/\/ Flag to store if the server is running or not.\n\tconn        *net.UDPConn   \/\/ conn is a UDP connection object.\n}\n\n\/\/ NewServer returns a new OSC Server.\nfunc NewServer(addr string) (*Server, error) {\n\treturn &Server{\n\t\tAddress:     addr,\n\t\tListening:   make(chan struct{}),\n\t\treadTimeout: 0,\n\t\tdispatcher:  NewOscDispatcher(),\n\t}, nil\n}\n\n\/\/ connect initializes the server's connection.\nfunc (self *Server) connect() error {\n\taddr, err := net.ResolveUDPAddr(\"udp\", self.Address)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn, err := net.ListenUDP(\"udp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdest := (*unsafe.Pointer)(unsafe.Pointer(&self.conn))\n\tif !atomic.CompareAndSwapPointer(dest, unsafe.Pointer(self.conn), unsafe.Pointer(conn)) {\n\t\treturn errors.New(\"could not initialize connection\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Close stops the OSC server and closes the connection.\nfunc (self *Server) Close() error {\n\tif self.conn == nil {\n\t\treturn nil\n\t}\n\treturn self.conn.Close()\n}\n\n\/\/ AddMsgHandler registers a new message handler function for an OSC address. The handler\n\/\/ is the function called for incoming Messages that match 'address'.\nfunc (self *Server) AddMsgHandler(address string, handler HandlerFunc) error {\n\treturn self.dispatcher.AddMsgHandler(address, handler)\n}\n\n\/\/ ListenAndServe retrieves incoming OSC packets and dispatches the retrieved OSC packets.\nfunc (self *Server) ListenAndDispatch() error {\n\tif self.running {\n\t\treturn ErrAlreadyRunning\n\t}\n\n\tif self.dispatcher == nil {\n\t\treturn ErrNoDispatcher\n\t}\n\n\tif err := self.connect(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Set read timeout\n\tif self.readTimeout != 0 {\n\t\tif err := self.conn.SetReadDeadline(time.Now().Add(self.readTimeout)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tself.running = true\n\tself.Listening <- struct{}{}\n\n\tfor self.running {\n\t\tmsg, err := self.readFromConnection()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tself.dispatcher.Dispatch(msg)\n\t}\n\n\treturn nil\n}\n\n\/\/ Listen causes the server to start listening for packets.\nfunc (self *Server) Listen() error {\n\tif self.conn == nil {\n\t\tif err := self.connect(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif self.running {\n\t\treturn ErrAlreadyRunning\n\t}\n\n\t\/\/ Set read timeout\n\tif self.readTimeout != 0 {\n\t\tself.conn.SetReadDeadline(time.Now().Add(self.readTimeout))\n\t}\n\n\tself.running = true\n\tself.Listening <- struct{}{}\n\n\treturn nil\n}\n\n\/\/ Listen listens for incoming OSC packets and returns the packet if one is received.\nfunc (self *Server) ReceivePacket() (packet Packet, err error) {\n\tmsg, err := self.readFromConnection()\n\tif err == nil {\n\t\treturn msg, nil\n\t}\n\n\treturn nil, err\n}\n\n\/\/ Send sends an OSC Bundle or an OSC Message.\nfunc (self *Server) SendTo(addr net.Addr, packet Packet) (err error) {\n\tif self.conn == nil {\n\t\treturn fmt.Errorf(\"connection not initialized\")\n\t}\n\tdata, err := packet.ToByteArray()\n\tif err != nil {\n\t\tself.conn.Close()\n\t\treturn err\n\t}\n\n\twritten, err := self.conn.WriteTo(data, addr)\n\tif err != nil {\n\t\tfmt.Println(\"could not write packet\")\n\t\tself.conn.Close()\n\t\treturn err\n\t}\n\tif written != len(data) {\n\t\terrmsg := \"only wrote %d bytes of osc packet with length %d\"\n\t\treturn fmt.Errorf(errmsg, written, len(data))\n\t}\n\n\treturn nil\n}\n\n\/\/ readFromConnection retrieves OSC packets.\nfunc (self *Server) readFromConnection() (packet Packet, err error) {\n\tif self.conn == nil {\n\t\treturn nil, fmt.Errorf(\"self.conn is nil\")\n\t}\n\tdata := make([]byte, 65535)\n\tvar n, start int\n\tn, _, err = self.conn.ReadFromUDP(data)\n\tpacket, err = self.readPacket(bufio.NewReader(bytes.NewBuffer(data)), &start, n)\n\n\treturn packet, nil\n}\n\n\/\/ receivePacket receives an OSC packet from the given reader.\nfunc (self *Server) readPacket(reader *bufio.Reader, start *int, end int) (packet Packet, err error) {\n\tvar buf []byte\n\tbuf, err = reader.Peek(1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ An OSC Message starts with a '\/'\n\tif buf[0] == '\/' {\n\t\tpacket, err = self.readMessage(reader, start)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else if buf[0] == '#' { \/\/ An OSC bundle starts with a '#'\n\t\tpacket, err = self.readBundle(reader, start, end)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn packet, nil\n}\n\n\/\/ readBundle reads an Bundle from reader.\nfunc (self *Server) readBundle(reader *bufio.Reader, start *int, end int) (bundle *Bundle, err error) {\n\t\/\/ Read the '#bundle' OSC string\n\tvar startTag string\n\tvar n int\n\tstartTag, n, err = readPaddedString(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t*start += n\n\n\tif startTag != BundleTag {\n\t\treturn nil, fmt.Errorf(\"Invalid bundle start tag: %s\", startTag)\n\t}\n\n\t\/\/ Read the timetag\n\tvar timeTag uint64\n\tif err := binary.Read(reader, binary.BigEndian, &timeTag); err != nil {\n\t\treturn nil, err\n\t}\n\t*start += 8\n\n\t\/\/ Create a new bundle\n\tbundle = NewBundle(timetagToTime(timeTag))\n\n\t\/\/ Read until the end of the buffer\n\tfor *start < end {\n\t\t\/\/ Read the size of the bundle element\n\t\tvar length int32\n\t\terr = binary.Read(reader, binary.BigEndian, &length)\n\t\t*start += 4\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar packet Packet\n\t\tpacket, err = self.readPacket(reader, start, end)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbundle.Append(packet)\n\t}\n\n\treturn bundle, nil\n}\n\n\/\/ readMessage reads one OSC Message from reader.\nfunc (self *Server) readMessage(reader *bufio.Reader, start *int) (msg *Message, err error) {\n\t\/\/ First, read the OSC address\n\tvar n int\n\taddress, n, err := readPaddedString(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t*start += n\n\n\t\/\/ Create a new message\n\tmsg = &Message{address: address}\n\n\t\/\/ Read all arguments\n\tif err = self.readArguments(msg, reader, start); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn msg, nil\n}\n\n\/\/ readArguments reads all arguments from the reader and adds it to the OSC message.\nfunc (self *Server) readArguments(msg *Message, reader *bufio.Reader, start *int) error {\n\t\/\/ Read the type tag string\n\tvar n int\n\ttypetags, n, err := readPaddedString(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*start += n\n\n\t\/\/ If the typetag doesn't start with ',', it's not valid\n\tif typetags[0] != ',' {\n\t\treturn ErrInvalidTypeTag\n\t}\n\n\t\/\/ Remove ',' from the type tag\n\ttypetags = typetags[1:]\n\n\tfor _, c := range typetags {\n\t\tswitch c {\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"Unsupported type tag: %c\", c)\n\n\t\t\/\/ int32\n\t\tcase 'i':\n\t\t\tvar i int32\n\t\t\tif err = binary.Read(reader, binary.BigEndian, &i); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*start += 4\n\t\t\tmsg.Append(i)\n\n\t\t\/\/ int64\n\t\tcase 'h':\n\t\t\tvar i int64\n\t\t\tif err = binary.Read(reader, binary.BigEndian, &i); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*start += 8\n\t\t\tmsg.Append(i)\n\n\t\t\/\/ float32\n\t\tcase 'f':\n\t\t\tvar f float32\n\t\t\tif err = binary.Read(reader, binary.BigEndian, &f); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*start += 4\n\t\t\tmsg.Append(f)\n\n\t\t\/\/ float64\/double\n\t\tcase 'd':\n\t\t\tvar d float64\n\t\t\tif err = binary.Read(reader, binary.BigEndian, &d); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*start += 8\n\t\t\tmsg.Append(d)\n\n\t\t\/\/ string\n\t\tcase 's':\n\t\t\t\/\/ TODO: fix reading string value\n\t\t\tvar s string\n\t\t\tif s, _, err = readPaddedString(reader); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*start += len(s) + padBytesNeeded(len(s))\n\t\t\tmsg.Append(s)\n\n\t\t\/\/ blob\n\t\tcase 'b':\n\t\t\tvar buf []byte\n\t\t\tvar n int\n\t\t\tif buf, n, err = readBlob(reader); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*start += n\n\t\t\tmsg.Append(buf)\n\n\t\t\/\/ OSC Time Tag\n\t\tcase 't':\n\t\t\tvar tt uint64\n\t\t\tif err = binary.Read(reader, binary.BigEndian, &tt); err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t*start += 8\n\t\t\tmsg.Append(Timetag(tt))\n\n\t\t\/\/ True\n\t\tcase 'T':\n\t\t\tmsg.Append(true)\n\n\t\t\/\/ False\n\t\tcase 'F':\n\t\t\tmsg.Append(false)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ readBlob reads an OSC Blob from the blob byte array. Padding bytes are removed\n\/\/ from the reader and not returned.\nfunc readBlob(reader *bufio.Reader) (blob []byte, n int, err error) {\n\t\/\/ First, get the length\n\tvar blobLen int\n\tif err = binary.Read(reader, binary.BigEndian, &blobLen); err != nil {\n\t\treturn nil, 0, err\n\t}\n\tn = 4 + blobLen\n\n\t\/\/ Read the data\n\tblob = make([]byte, blobLen)\n\tif _, err = reader.Read(blob); err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\t\/\/ Remove the padding bytes\n\tnumPadBytes := padBytesNeeded(blobLen)\n\tif numPadBytes > 0 {\n\t\tn += numPadBytes\n\t\tdummy := make([]byte, numPadBytes)\n\t\tif _, err = reader.Read(dummy); err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t}\n\n\treturn blob, n, nil\n}\n<commit_msg>get rid of ReceivePacket method<commit_after>package osc\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"sync\/atomic\"\n\t\"time\"\n\t\"unsafe\"\n)\n\n\/\/ Common errors.\nvar (\n\tErrAlreadyRunning = errors.New(\"server is already running\")\n\tErrNoDispatcher   = errors.New(\"no dispatcher defined\")\n\tErrPrematureClose = errors.New(\"server cannot be closed before calling Listen\")\n\tErrInvalidTypeTag = errors.New(\"invalid type tag\")\n)\n\n\/\/ Server is an OSC server.\ntype Server struct {\n\tAddress     string         \/\/ Address is the listening address.\n\tListening   chan struct{}  \/\/ Listening is a channel used to indicate when the server is running.\n\treadTimeout time.Duration  \/\/ readTimeout is the timeout for reading from a connection.\n\tdispatcher  *OscDispatcher \/\/ Dispatcher that dispatches OSC packets\/messages.\n\trunning     bool           \/\/ Flag to store if the server is running or not.\n\tconn        *net.UDPConn   \/\/ conn is a UDP connection object.\n}\n\n\/\/ NewServer returns a new OSC Server.\nfunc NewServer(addr string) (*Server, error) {\n\treturn &Server{\n\t\tAddress:     addr,\n\t\tListening:   make(chan struct{}),\n\t\treadTimeout: 0,\n\t\tdispatcher:  NewOscDispatcher(),\n\t}, nil\n}\n\n\/\/ connect initializes the server's connection.\nfunc (self *Server) connect() error {\n\taddr, err := net.ResolveUDPAddr(\"udp\", self.Address)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconn, err := net.ListenUDP(\"udp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdest := (*unsafe.Pointer)(unsafe.Pointer(&self.conn))\n\tif !atomic.CompareAndSwapPointer(dest, unsafe.Pointer(self.conn), unsafe.Pointer(conn)) {\n\t\treturn errors.New(\"could not initialize connection\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Close stops the OSC server and closes the connection.\nfunc (self *Server) Close() error {\n\tif self.conn == nil {\n\t\treturn nil\n\t}\n\treturn self.conn.Close()\n}\n\n\/\/ AddMsgHandler registers a new message handler function for an OSC address. The handler\n\/\/ is the function called for incoming Messages that match 'address'.\nfunc (self *Server) AddMsgHandler(address string, handler HandlerFunc) error {\n\treturn self.dispatcher.AddMsgHandler(address, handler)\n}\n\n\/\/ ListenAndServe retrieves incoming OSC packets and dispatches the retrieved OSC packets.\nfunc (self *Server) ListenAndDispatch() error {\n\tif self.running {\n\t\treturn ErrAlreadyRunning\n\t}\n\n\tif self.dispatcher == nil {\n\t\treturn ErrNoDispatcher\n\t}\n\n\tif err := self.connect(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Set read timeout\n\tif self.readTimeout != 0 {\n\t\tif err := self.conn.SetReadDeadline(time.Now().Add(self.readTimeout)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tself.running = true\n\tself.Listening <- struct{}{}\n\n\tfor self.running {\n\t\tmsg, err := self.readFromConnection()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tself.dispatcher.Dispatch(msg)\n\t}\n\n\treturn nil\n}\n\n\/\/ Listen causes the server to start listening for packets.\nfunc (self *Server) Listen() error {\n\tif self.conn == nil {\n\t\tif err := self.connect(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif self.running {\n\t\treturn ErrAlreadyRunning\n\t}\n\n\t\/\/ Set read timeout\n\tif self.readTimeout != 0 {\n\t\tself.conn.SetReadDeadline(time.Now().Add(self.readTimeout))\n\t}\n\n\tself.running = true\n\tself.Listening <- struct{}{}\n\n\treturn nil\n}\n\n\/\/ Send sends an OSC Bundle or an OSC Message.\nfunc (self *Server) SendTo(addr net.Addr, packet Packet) (err error) {\n\tif self.conn == nil {\n\t\treturn fmt.Errorf(\"connection not initialized\")\n\t}\n\tdata, err := packet.ToByteArray()\n\tif err != nil {\n\t\tself.conn.Close()\n\t\treturn err\n\t}\n\n\twritten, err := self.conn.WriteTo(data, addr)\n\tif err != nil {\n\t\tfmt.Println(\"could not write packet\")\n\t\tself.conn.Close()\n\t\treturn err\n\t}\n\tif written != len(data) {\n\t\terrmsg := \"only wrote %d bytes of osc packet with length %d\"\n\t\treturn fmt.Errorf(errmsg, written, len(data))\n\t}\n\n\treturn nil\n}\n\n\/\/ readFromConnection retrieves OSC packets.\nfunc (self *Server) readFromConnection() (packet Packet, err error) {\n\tif self.conn == nil {\n\t\treturn nil, fmt.Errorf(\"self.conn is nil\")\n\t}\n\tdata := make([]byte, 65535)\n\tvar n, start int\n\tn, _, err = self.conn.ReadFromUDP(data)\n\tpacket, err = self.readPacket(bufio.NewReader(bytes.NewBuffer(data)), &start, n)\n\n\treturn packet, nil\n}\n\n\/\/ receivePacket receives an OSC packet from the given reader.\nfunc (self *Server) readPacket(reader *bufio.Reader, start *int, end int) (packet Packet, err error) {\n\tvar buf []byte\n\tbuf, err = reader.Peek(1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ An OSC Message starts with a '\/'\n\tif buf[0] == '\/' {\n\t\tpacket, err = self.readMessage(reader, start)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else if buf[0] == '#' { \/\/ An OSC bundle starts with a '#'\n\t\tpacket, err = self.readBundle(reader, start, end)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn packet, nil\n}\n\n\/\/ readBundle reads an Bundle from reader.\nfunc (self *Server) readBundle(reader *bufio.Reader, start *int, end int) (bundle *Bundle, err error) {\n\t\/\/ Read the '#bundle' OSC string\n\tvar startTag string\n\tvar n int\n\tstartTag, n, err = readPaddedString(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t*start += n\n\n\tif startTag != BundleTag {\n\t\treturn nil, fmt.Errorf(\"Invalid bundle start tag: %s\", startTag)\n\t}\n\n\t\/\/ Read the timetag\n\tvar timeTag uint64\n\tif err := binary.Read(reader, binary.BigEndian, &timeTag); err != nil {\n\t\treturn nil, err\n\t}\n\t*start += 8\n\n\t\/\/ Create a new bundle\n\tbundle = NewBundle(timetagToTime(timeTag))\n\n\t\/\/ Read until the end of the buffer\n\tfor *start < end {\n\t\t\/\/ Read the size of the bundle element\n\t\tvar length int32\n\t\terr = binary.Read(reader, binary.BigEndian, &length)\n\t\t*start += 4\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar packet Packet\n\t\tpacket, err = self.readPacket(reader, start, end)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbundle.Append(packet)\n\t}\n\n\treturn bundle, nil\n}\n\n\/\/ readMessage reads one OSC Message from reader.\nfunc (self *Server) readMessage(reader *bufio.Reader, start *int) (msg *Message, err error) {\n\t\/\/ First, read the OSC address\n\tvar n int\n\taddress, n, err := readPaddedString(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t*start += n\n\n\t\/\/ Create a new message\n\tmsg = &Message{address: address}\n\n\t\/\/ Read all arguments\n\tif err = self.readArguments(msg, reader, start); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn msg, nil\n}\n\n\/\/ readArguments reads all arguments from the reader and adds it to the OSC message.\nfunc (self *Server) readArguments(msg *Message, reader *bufio.Reader, start *int) error {\n\t\/\/ Read the type tag string\n\tvar n int\n\ttypetags, n, err := readPaddedString(reader)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*start += n\n\n\t\/\/ If the typetag doesn't start with ',', it's not valid\n\tif typetags[0] != ',' {\n\t\treturn ErrInvalidTypeTag\n\t}\n\n\t\/\/ Remove ',' from the type tag\n\ttypetags = typetags[1:]\n\n\tfor _, c := range typetags {\n\t\tswitch c {\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"Unsupported type tag: %c\", c)\n\n\t\t\/\/ int32\n\t\tcase 'i':\n\t\t\tvar i int32\n\t\t\tif err = binary.Read(reader, binary.BigEndian, &i); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*start += 4\n\t\t\tmsg.Append(i)\n\n\t\t\/\/ int64\n\t\tcase 'h':\n\t\t\tvar i int64\n\t\t\tif err = binary.Read(reader, binary.BigEndian, &i); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*start += 8\n\t\t\tmsg.Append(i)\n\n\t\t\/\/ float32\n\t\tcase 'f':\n\t\t\tvar f float32\n\t\t\tif err = binary.Read(reader, binary.BigEndian, &f); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*start += 4\n\t\t\tmsg.Append(f)\n\n\t\t\/\/ float64\/double\n\t\tcase 'd':\n\t\t\tvar d float64\n\t\t\tif err = binary.Read(reader, binary.BigEndian, &d); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*start += 8\n\t\t\tmsg.Append(d)\n\n\t\t\/\/ string\n\t\tcase 's':\n\t\t\t\/\/ TODO: fix reading string value\n\t\t\tvar s string\n\t\t\tif s, _, err = readPaddedString(reader); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*start += len(s) + padBytesNeeded(len(s))\n\t\t\tmsg.Append(s)\n\n\t\t\/\/ blob\n\t\tcase 'b':\n\t\t\tvar buf []byte\n\t\t\tvar n int\n\t\t\tif buf, n, err = readBlob(reader); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*start += n\n\t\t\tmsg.Append(buf)\n\n\t\t\/\/ OSC Time Tag\n\t\tcase 't':\n\t\t\tvar tt uint64\n\t\t\tif err = binary.Read(reader, binary.BigEndian, &tt); err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t*start += 8\n\t\t\tmsg.Append(Timetag(tt))\n\n\t\t\/\/ True\n\t\tcase 'T':\n\t\t\tmsg.Append(true)\n\n\t\t\/\/ False\n\t\tcase 'F':\n\t\t\tmsg.Append(false)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ readBlob reads an OSC Blob from the blob byte array. Padding bytes are removed\n\/\/ from the reader and not returned.\nfunc readBlob(reader *bufio.Reader) (blob []byte, n int, err error) {\n\t\/\/ First, get the length\n\tvar blobLen int\n\tif err = binary.Read(reader, binary.BigEndian, &blobLen); err != nil {\n\t\treturn nil, 0, err\n\t}\n\tn = 4 + blobLen\n\n\t\/\/ Read the data\n\tblob = make([]byte, blobLen)\n\tif _, err = reader.Read(blob); err != nil {\n\t\treturn nil, 0, err\n\t}\n\n\t\/\/ Remove the padding bytes\n\tnumPadBytes := padBytesNeeded(blobLen)\n\tif numPadBytes > 0 {\n\t\tn += numPadBytes\n\t\tdummy := make([]byte, numPadBytes)\n\t\tif _, err = reader.Read(dummy); err != nil {\n\t\t\treturn nil, 0, err\n\t\t}\n\t}\n\n\treturn blob, n, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage websocket\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ HandshakeError describes an error with the handshake from the peer.\ntype HandshakeError struct {\n\tmessage string\n}\n\nfunc (e HandshakeError) Error() string { return e.message }\n\n\/\/ Upgrader specifies parameters for upgrading an HTTP connection to a\n\/\/ WebSocket connection.\ntype Upgrader struct {\n\t\/\/ HandshakeTimeout specifies the duration for the handshake to complete.\n\tHandshakeTimeout time.Duration\n\n\t\/\/ ReadBufferSize and WriteBufferSize specify I\/O buffer sizes. If a buffer\n\t\/\/ size is zero, then a default value of 4096 is used. The I\/O buffer sizes\n\t\/\/ do not limit the size of the messages that can be sent or received.\n\tReadBufferSize, WriteBufferSize int\n\n\t\/\/ Subprotocols specifies the server's supported protocols in order of\n\t\/\/ preference. If this field is set, then the Upgrade method negotiates a\n\t\/\/ subprotocol by selecting the first match in this list with a protocol\n\t\/\/ requested by the client.\n\tSubprotocols []string\n\n\t\/\/ Error specifies the function for generating HTTP error responses. If Error\n\t\/\/ is nil, then http.Error is used to generate the HTTP response.\n\tError func(w http.ResponseWriter, r *http.Request, status int, reason error)\n\n\t\/\/ CheckOrigin returns true if the request Origin header is acceptable. If\n\t\/\/ CheckOrigin is nil, the host in the Origin header must not be set or\n\t\/\/ must match the host of the request.\n\tCheckOrigin func(r *http.Request) bool\n}\n\nfunc (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) {\n\terr := HandshakeError{reason}\n\tif u.Error != nil {\n\t\tu.Error(w, r, status, err)\n\t} else {\n\t\thttp.Error(w, http.StatusText(status), status)\n\t}\n\treturn nil, err\n}\n\n\/\/ checkSameOrigin returns true if the origin is not set or is equal to the request host.\nfunc checkSameOrigin(r *http.Request) bool {\n\torigin := r.Header[\"Origin\"]\n\tif len(origin) == 0 {\n\t\treturn true\n\t}\n\tu, err := url.Parse(origin[0])\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn u.Host == r.Host\n}\n\nfunc (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string {\n\tif u.Subprotocols != nil {\n\t\tclientProtocols := Subprotocols(r)\n\t\tfor _, serverProtocol := range u.Subprotocols {\n\t\t\tfor _, clientProtocol := range clientProtocols {\n\t\t\t\tif clientProtocol == serverProtocol {\n\t\t\t\t\treturn clientProtocol\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if responseHeader != nil {\n\t\treturn responseHeader.Get(\"Sec-Websocket-Protocol\")\n\t}\n\treturn \"\"\n}\n\n\/\/ Upgrade upgrades the HTTP server connection to the WebSocket protocol.\n\/\/\n\/\/ The responseHeader is included in the response to the client's upgrade\n\/\/ request. Use the responseHeader to specify cookies (Set-Cookie) and the\n\/\/ application negotiated subprotocol (Sec-Websocket-Protocol).\nfunc (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {\n\tif values := r.Header[\"Sec-Websocket-Version\"]; len(values) == 0 || values[0] != \"13\" {\n\t\treturn u.returnError(w, r, http.StatusBadRequest, \"websocket: version != 13\")\n\t}\n\n\tif !tokenListContainsValue(r.Header, \"Connection\", \"upgrade\") {\n\t\treturn u.returnError(w, r, http.StatusBadRequest, \"websocket: could not find connection header with token 'upgrade'\")\n\t}\n\n\tif !tokenListContainsValue(r.Header, \"Upgrade\", \"websocket\") {\n\t\treturn u.returnError(w, r, http.StatusBadRequest, \"websocket: could not find upgrade header with token 'websocket'\")\n\t}\n\n\tcheckOrigin := u.CheckOrigin\n\tif checkOrigin == nil {\n\t\tcheckOrigin = checkSameOrigin\n\t}\n\tif !checkOrigin(r) {\n\t\treturn u.returnError(w, r, http.StatusForbidden, \"websocket: origin not allowed\")\n\t}\n\n\tchallengeKey := r.Header.Get(\"Sec-Websocket-Key\")\n\tif challengeKey == \"\" {\n\t\treturn u.returnError(w, r, http.StatusBadRequest, \"websocket: key missing or blank\")\n\t}\n\n\tsubprotocol := u.selectSubprotocol(r, responseHeader)\n\n\tvar (\n\t\tnetConn net.Conn\n\t\tbr      *bufio.Reader\n\t\terr     error\n\t)\n\n\th, ok := w.(http.Hijacker)\n\tif !ok {\n\t\treturn u.returnError(w, r, http.StatusInternalServerError, \"websocket: response does not implement http.Hijacker\")\n\t}\n\tvar rw *bufio.ReadWriter\n\tnetConn, rw, err = h.Hijack()\n\tif err != nil {\n\t\treturn u.returnError(w, r, http.StatusInternalServerError, err.Error())\n\t}\n\tbr = rw.Reader\n\n\tif br.Buffered() > 0 {\n\t\tnetConn.Close()\n\t\treturn nil, errors.New(\"websocket: client sent data before handshake is complete\")\n\t}\n\n\tc := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize)\n\tc.subprotocol = subprotocol\n\n\tp := c.writeBuf[:0]\n\tp = append(p, \"HTTP\/1.1 101 Switching Protocols\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Accept: \"...)\n\tp = append(p, computeAcceptKey(challengeKey)...)\n\tp = append(p, \"\\r\\n\"...)\n\tif c.subprotocol != \"\" {\n\t\tp = append(p, \"Sec-Websocket-Protocol: \"...)\n\t\tp = append(p, c.subprotocol...)\n\t\tp = append(p, \"\\r\\n\"...)\n\t}\n\tfor k, vs := range responseHeader {\n\t\tif k == \"Sec-Websocket-Protocol\" {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, v := range vs {\n\t\t\tp = append(p, k...)\n\t\t\tp = append(p, \": \"...)\n\t\t\tfor i := 0; i < len(v); i++ {\n\t\t\t\tb := v[i]\n\t\t\t\tif b <= 31 {\n\t\t\t\t\t\/\/ prevent response splitting.\n\t\t\t\t\tb = ' '\n\t\t\t\t}\n\t\t\t\tp = append(p, b)\n\t\t\t}\n\t\t\tp = append(p, \"\\r\\n\"...)\n\t\t}\n\t}\n\tp = append(p, \"\\r\\n\"...)\n\n\t\/\/ Clear deadlines set by HTTP server.\n\tnetConn.SetDeadline(time.Time{})\n\n\tif u.HandshakeTimeout > 0 {\n\t\tnetConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))\n\t}\n\tif _, err = netConn.Write(p); err != nil {\n\t\tnetConn.Close()\n\t\treturn nil, err\n\t}\n\tif u.HandshakeTimeout > 0 {\n\t\tnetConn.SetWriteDeadline(time.Time{})\n\t}\n\n\treturn c, nil\n}\n\n\/\/ Upgrade upgrades the HTTP server connection to the WebSocket protocol.\n\/\/\n\/\/ This function is deprecated, use websocket.Upgrader instead.\n\/\/\n\/\/ The application is responsible for checking the request origin before\n\/\/ calling Upgrade. An example implementation of the same origin policy is:\n\/\/\n\/\/\tif req.Header.Get(\"Origin\") != \"http:\/\/\"+req.Host {\n\/\/\t\thttp.Error(w, \"Origin not allowed\", 403)\n\/\/\t\treturn\n\/\/\t}\n\/\/\n\/\/ If the endpoint supports subprotocols, then the application is responsible\n\/\/ for negotiating the protocol used on the connection. Use the Subprotocols()\n\/\/ function to get the subprotocols requested by the client. Use the\n\/\/ Sec-Websocket-Protocol response header to specify the subprotocol selected\n\/\/ by the application.\n\/\/\n\/\/ The responseHeader is included in the response to the client's upgrade\n\/\/ request. Use the responseHeader to specify cookies (Set-Cookie) and the\n\/\/ negotiated subprotocol (Sec-Websocket-Protocol).\n\/\/\n\/\/ The connection buffers IO to the underlying network connection. The\n\/\/ readBufSize and writeBufSize parameters specify the size of the buffers to\n\/\/ use. Messages can be larger than the buffers.\n\/\/\n\/\/ If the request is not a valid WebSocket handshake, then Upgrade returns an\n\/\/ error of type HandshakeError. Applications should handle this error by\n\/\/ replying to the client with an HTTP error response.\nfunc Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {\n\tu := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}\n\tu.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {\n\t\t\/\/ don't return errors to maintain backwards compatibility\n\t}\n\tu.CheckOrigin = func(r *http.Request) bool {\n\t\t\/\/ allow all connections by default\n\t\treturn true\n\t}\n\treturn u.Upgrade(w, r, responseHeader)\n}\n\n\/\/ Subprotocols returns the subprotocols requested by the client in the\n\/\/ Sec-Websocket-Protocol header.\nfunc Subprotocols(r *http.Request) []string {\n\th := strings.TrimSpace(r.Header.Get(\"Sec-Websocket-Protocol\"))\n\tif h == \"\" {\n\t\treturn nil\n\t}\n\tprotocols := strings.Split(h, \",\")\n\tfor i := range protocols {\n\t\tprotocols[i] = strings.TrimSpace(protocols[i])\n\t}\n\treturn protocols\n}\n<commit_msg>ignore other previously sent headers in upgrade<commit_after>\/\/ Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage websocket\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ HandshakeError describes an error with the handshake from the peer.\ntype HandshakeError struct {\n\tmessage string\n}\n\nfunc (e HandshakeError) Error() string { return e.message }\n\n\/\/ Upgrader specifies parameters for upgrading an HTTP connection to a\n\/\/ WebSocket connection.\ntype Upgrader struct {\n\t\/\/ HandshakeTimeout specifies the duration for the handshake to complete.\n\tHandshakeTimeout time.Duration\n\n\t\/\/ ReadBufferSize and WriteBufferSize specify I\/O buffer sizes. If a buffer\n\t\/\/ size is zero, then a default value of 4096 is used. The I\/O buffer sizes\n\t\/\/ do not limit the size of the messages that can be sent or received.\n\tReadBufferSize, WriteBufferSize int\n\n\t\/\/ Subprotocols specifies the server's supported protocols in order of\n\t\/\/ preference. If this field is set, then the Upgrade method negotiates a\n\t\/\/ subprotocol by selecting the first match in this list with a protocol\n\t\/\/ requested by the client.\n\tSubprotocols []string\n\n\t\/\/ Error specifies the function for generating HTTP error responses. If Error\n\t\/\/ is nil, then http.Error is used to generate the HTTP response.\n\tError func(w http.ResponseWriter, r *http.Request, status int, reason error)\n\n\t\/\/ CheckOrigin returns true if the request Origin header is acceptable. If\n\t\/\/ CheckOrigin is nil, the host in the Origin header must not be set or\n\t\/\/ must match the host of the request.\n\tCheckOrigin func(r *http.Request) bool\n}\n\nfunc (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) {\n\terr := HandshakeError{reason}\n\tif u.Error != nil {\n\t\tu.Error(w, r, status, err)\n\t} else {\n\t\thttp.Error(w, http.StatusText(status), status)\n\t}\n\treturn nil, err\n}\n\n\/\/ checkSameOrigin returns true if the origin is not set or is equal to the request host.\nfunc checkSameOrigin(r *http.Request) bool {\n\torigin := r.Header[\"Origin\"]\n\tif len(origin) == 0 {\n\t\treturn true\n\t}\n\tu, err := url.Parse(origin[0])\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn u.Host == r.Host\n}\n\nfunc (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string {\n\tif u.Subprotocols != nil {\n\t\tclientProtocols := Subprotocols(r)\n\t\tfor _, serverProtocol := range u.Subprotocols {\n\t\t\tfor _, clientProtocol := range clientProtocols {\n\t\t\t\tif clientProtocol == serverProtocol {\n\t\t\t\t\treturn clientProtocol\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else if responseHeader != nil {\n\t\treturn responseHeader.Get(\"Sec-Websocket-Protocol\")\n\t}\n\treturn \"\"\n}\n\n\/\/ Upgrade upgrades the HTTP server connection to the WebSocket protocol.\n\/\/\n\/\/ The responseHeader is included in the response to the client's upgrade\n\/\/ request. Use the responseHeader to specify cookies (Set-Cookie) and the\n\/\/ application negotiated subprotocol (Sec-Websocket-Protocol).\nfunc (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {\n\tif values := r.Header[\"Sec-Websocket-Version\"]; len(values) == 0 || values[0] != \"13\" {\n\t\treturn u.returnError(w, r, http.StatusBadRequest, \"websocket: version != 13\")\n\t}\n\n\tif !tokenListContainsValue(r.Header, \"Connection\", \"upgrade\") {\n\t\treturn u.returnError(w, r, http.StatusBadRequest, \"websocket: could not find connection header with token 'upgrade'\")\n\t}\n\n\tif !tokenListContainsValue(r.Header, \"Upgrade\", \"websocket\") {\n\t\treturn u.returnError(w, r, http.StatusBadRequest, \"websocket: could not find upgrade header with token 'websocket'\")\n\t}\n\n\tcheckOrigin := u.CheckOrigin\n\tif checkOrigin == nil {\n\t\tcheckOrigin = checkSameOrigin\n\t}\n\tif !checkOrigin(r) {\n\t\treturn u.returnError(w, r, http.StatusForbidden, \"websocket: origin not allowed\")\n\t}\n\n\tchallengeKey := r.Header.Get(\"Sec-Websocket-Key\")\n\tif challengeKey == \"\" {\n\t\treturn u.returnError(w, r, http.StatusBadRequest, \"websocket: key missing or blank\")\n\t}\n\n\tsubprotocol := u.selectSubprotocol(r, responseHeader)\n\n\tvar (\n\t\tnetConn net.Conn\n\t\tbr      *bufio.Reader\n\t\terr     error\n\t)\n\n\th, ok := w.(http.Hijacker)\n\tif !ok {\n\t\treturn u.returnError(w, r, http.StatusInternalServerError, \"websocket: response does not implement http.Hijacker\")\n\t}\n\tvar rw *bufio.ReadWriter\n\tnetConn, rw, err = h.Hijack()\n\tif err != nil {\n\t\treturn u.returnError(w, r, http.StatusInternalServerError, err.Error())\n\t}\n\tbr = rw.Reader\n\n\tif br.Buffered() > 0 {\n\t\tnetConn.Close()\n\t\treturn nil, errors.New(\"websocket: client sent data before handshake is complete\")\n\t}\n\n\tc := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize)\n\tc.subprotocol = subprotocol\n\n\tp := c.writeBuf[:0]\n\tp = append(p, \"HTTP\/1.1 101 Switching Protocols\\r\\nUpgrade: websocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Accept: \"...)\n\tp = append(p, computeAcceptKey(challengeKey)...)\n\tp = append(p, \"\\r\\n\"...)\n\tif c.subprotocol != \"\" {\n\t\tp = append(p, \"Sec-Websocket-Protocol: \"...)\n\t\tp = append(p, c.subprotocol...)\n\t\tp = append(p, \"\\r\\n\"...)\n\t}\n\tfor k, vs := range responseHeader {\n\t\tif k == \"Upgrade\" || k == \"Connection\" || k == \"Sec-Websocket-Accept\" || k == \"Sec-Websocket-Protocol\" {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, v := range vs {\n\t\t\tp = append(p, k...)\n\t\t\tp = append(p, \": \"...)\n\t\t\tfor i := 0; i < len(v); i++ {\n\t\t\t\tb := v[i]\n\t\t\t\tif b <= 31 {\n\t\t\t\t\t\/\/ prevent response splitting.\n\t\t\t\t\tb = ' '\n\t\t\t\t}\n\t\t\t\tp = append(p, b)\n\t\t\t}\n\t\t\tp = append(p, \"\\r\\n\"...)\n\t\t}\n\t}\n\tp = append(p, \"\\r\\n\"...)\n\n\t\/\/ Clear deadlines set by HTTP server.\n\tnetConn.SetDeadline(time.Time{})\n\n\tif u.HandshakeTimeout > 0 {\n\t\tnetConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))\n\t}\n\tif _, err = netConn.Write(p); err != nil {\n\t\tnetConn.Close()\n\t\treturn nil, err\n\t}\n\tif u.HandshakeTimeout > 0 {\n\t\tnetConn.SetWriteDeadline(time.Time{})\n\t}\n\n\treturn c, nil\n}\n\n\/\/ Upgrade upgrades the HTTP server connection to the WebSocket protocol.\n\/\/\n\/\/ This function is deprecated, use websocket.Upgrader instead.\n\/\/\n\/\/ The application is responsible for checking the request origin before\n\/\/ calling Upgrade. An example implementation of the same origin policy is:\n\/\/\n\/\/\tif req.Header.Get(\"Origin\") != \"http:\/\/\"+req.Host {\n\/\/\t\thttp.Error(w, \"Origin not allowed\", 403)\n\/\/\t\treturn\n\/\/\t}\n\/\/\n\/\/ If the endpoint supports subprotocols, then the application is responsible\n\/\/ for negotiating the protocol used on the connection. Use the Subprotocols()\n\/\/ function to get the subprotocols requested by the client. Use the\n\/\/ Sec-Websocket-Protocol response header to specify the subprotocol selected\n\/\/ by the application.\n\/\/\n\/\/ The responseHeader is included in the response to the client's upgrade\n\/\/ request. Use the responseHeader to specify cookies (Set-Cookie) and the\n\/\/ negotiated subprotocol (Sec-Websocket-Protocol).\n\/\/\n\/\/ The connection buffers IO to the underlying network connection. The\n\/\/ readBufSize and writeBufSize parameters specify the size of the buffers to\n\/\/ use. Messages can be larger than the buffers.\n\/\/\n\/\/ If the request is not a valid WebSocket handshake, then Upgrade returns an\n\/\/ error of type HandshakeError. Applications should handle this error by\n\/\/ replying to the client with an HTTP error response.\nfunc Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {\n\tu := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}\n\tu.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {\n\t\t\/\/ don't return errors to maintain backwards compatibility\n\t}\n\tu.CheckOrigin = func(r *http.Request) bool {\n\t\t\/\/ allow all connections by default\n\t\treturn true\n\t}\n\treturn u.Upgrade(w, r, responseHeader)\n}\n\n\/\/ Subprotocols returns the subprotocols requested by the client in the\n\/\/ Sec-Websocket-Protocol header.\nfunc Subprotocols(r *http.Request) []string {\n\th := strings.TrimSpace(r.Header.Get(\"Sec-Websocket-Protocol\"))\n\tif h == \"\" {\n\t\treturn nil\n\t}\n\tprotocols := strings.Split(h, \",\")\n\tfor i := range protocols {\n\t\tprotocols[i] = strings.TrimSpace(protocols[i])\n\t}\n\treturn protocols\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"log\"\n)\n\nvar read_buf []byte = make([]byte, BUF_SIZE)\n\nfunc server() {\n\tconn, err := net.ListenUDP(\"udp\", &net.UDPAddr{IP: net.IPv4zero, Port: TUNTUNTUN_SERVER_PORT})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>Server receives packets on port 71<commit_after>package main\n\nimport (\n\t\"log\"\n\t\"net\"\n)\n\nvar read_buf []byte = make([]byte, BUF_SIZE)\n\nfunc server() {\n\tconn, err := net.ListenUDP(\"udp\", &net.UDPAddr{IP: net.IPv4zero, Port: TUNTUNTUN_SERVER_PORT})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor {\n\t\tcount, remote_addr, err := conn.ReadFromUDP(read_buf)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tlog.Printf(\"Got %d bytes from %s addressed to %s\",\n\t\t\tcount, remote_addr,\n\t\t\tget_ip_dest(read_buf[ENVELOPE_LENGTH:]))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package endly\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/viant\/toolbox\"\n\t\"log\"\n\t\"net\/http\"\n)\n\ntype Request struct {\n\tData           map[string]interface{}\n\tServiceRequest interface{}\n}\n\ntype Response struct {\n\tStatus   string\n\tError    string\n\tResponse interface{}\n\tInfo     *SessionInfo\n}\n\ntype Server struct {\n\tport    string\n\tmanager Manager\n}\n\nfunc (s *Server) requestService(serviceName, method string, httpRequest *http.Request, httpResponse http.ResponseWriter) (*Response, error) {\n\tvar service Service\n\tvar serviceRequest interface{}\n\tvar err error\n\tservice, err = s.manager.Service(toolbox.AsString(serviceName))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserviceRequest, err = service.NewRequest(toolbox.AsString(method))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trequest := &Request{\n\t\tServiceRequest: serviceRequest,\n\t}\n\terr = json.NewDecoder(httpRequest.Body).Decode(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontext := s.manager.NewContext(toolbox.NewContext())\n\tdefer context.Close()\n\tstate := context.State()\n\tstate.Apply(request.Data)\n\tserviceResponse := service.Run(context, request.ServiceRequest)\n\n\tvar sessionInfo = context.SessionInfo()\n\tvar response = &Response{\n\t\tStatus:   serviceResponse.Status,\n\t\tError:    serviceResponse.Error,\n\t\tResponse: serviceResponse.Response,\n\t\tInfo:     sessionInfo,\n\t}\n\treturn response, nil\n}\n\nfunc (s *Server) routeHandler(serviceRouting *toolbox.ServiceRouting, httpRequest *http.Request, httpResponse http.ResponseWriter, uriParameters map[string]interface{}) (err error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tserviceResponse := &Response{\n\t\t\t\tError: fmt.Sprintf(\"%v\", err),\n\t\t\t}\n\t\t\terr = toolbox.WriteServiceRoutingResponse(httpResponse, httpRequest, serviceRouting, serviceResponse)\n\t\t}\n\n\t}()\n\n\tserviceName, ok := uriParameters[\"service\"]\n\tif !ok {\n\t\treturn fmt.Errorf(\"Service name was missing %v\", uriParameters)\n\t}\n\tmethod, ok := uriParameters[\"method\"]\n\tif !ok {\n\t\treturn fmt.Errorf(\"method was missing %v\", uriParameters)\n\t}\n\n\tvar response *Response\n\tresponse, err = s.requestService(toolbox.AsString(serviceName), toolbox.AsString(method), httpRequest, httpResponse)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = toolbox.WriteServiceRoutingResponse(httpResponse, httpRequest, serviceRouting, response)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n\n}\n\nfunc (s *Server) Start() error {\n\n\trouter := toolbox.NewServiceRouter(\n\t\ttoolbox.ServiceRouting{\n\t\t\tHTTPMethod:     \"POST\",\n\t\t\tURI:            \"\/v1\/endly\/service\/{service}\/{method}\/\",\n\t\t\tHandler:        s.requestService,\n\t\t\tHandlerInvoker: s.routeHandler,\n\t\t\tParameters:     []string{\"service\", \"method\", \"@httpRequest\", \"@httpResponseWriter\"},\n\t\t})\n\n\thttp.HandleFunc(\"\/v1\/\", func(response http.ResponseWriter, reader *http.Request) {\n\t\terr := router.Route(response, reader)\n\t\tif err != nil {\n\t\t\tresponse.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t})\n\tfmt.Printf(\"Started test server on port %v\\n\", s.port)\n\tlog.Fatal(http.ListenAndServe(\":\"+s.port, nil))\n\treturn nil\n}\n\nfunc NewServer(port string) *Server {\n\treturn &Server{\n\t\tport:    port,\n\t\tmanager: GetManager(),\n\t}\n}\n<commit_msg>added request state to the response<commit_after>package endly\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/viant\/toolbox\"\n\t\"log\"\n\t\"net\/http\"\n)\n\ntype Request struct {\n\tData           map[string]interface{}\n\tServiceRequest interface{}\n}\n\ntype Response struct {\n\tStatus   string\n\tError    string\n\tResponse interface{}\n\tInfo     *SessionInfo\n\tState    map[string]interface{}\n}\n\ntype Server struct {\n\tport    string\n\tmanager Manager\n}\n\nfunc (s *Server) requestService(serviceName, method string, httpRequest *http.Request, httpResponse http.ResponseWriter) (*Response, error) {\n\tvar service Service\n\tvar serviceRequest interface{}\n\tvar err error\n\tservice, err = s.manager.Service(toolbox.AsString(serviceName))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tserviceRequest, err = service.NewRequest(toolbox.AsString(method))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trequest := &Request{\n\t\tServiceRequest: serviceRequest,\n\t}\n\terr = json.NewDecoder(httpRequest.Body).Decode(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcontext := s.manager.NewContext(toolbox.NewContext())\n\tdefer context.Close()\n\tstate := context.State()\n\tstate.Apply(request.Data)\n\tserviceResponse := service.Run(context, request.ServiceRequest)\n\tvar sessionInfo = context.SessionInfo()\n\tvar response = &Response{\n\t\tStatus:   serviceResponse.Status,\n\t\tError:    serviceResponse.Error,\n\t\tResponse: serviceResponse.Response,\n\t\tInfo:     sessionInfo,\n\t\tState:    context.State(),\n\t}\n\treturn response, nil\n}\n\nfunc (s *Server) routeHandler(serviceRouting *toolbox.ServiceRouting, httpRequest *http.Request, httpResponse http.ResponseWriter, uriParameters map[string]interface{}) (err error) {\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tserviceResponse := &Response{\n\t\t\t\tError: fmt.Sprintf(\"%v\", err),\n\t\t\t}\n\t\t\terr = toolbox.WriteServiceRoutingResponse(httpResponse, httpRequest, serviceRouting, serviceResponse)\n\t\t}\n\n\t}()\n\n\tserviceName, ok := uriParameters[\"service\"]\n\tif !ok {\n\t\treturn fmt.Errorf(\"Service name was missing %v\", uriParameters)\n\t}\n\tmethod, ok := uriParameters[\"method\"]\n\tif !ok {\n\t\treturn fmt.Errorf(\"method was missing %v\", uriParameters)\n\t}\n\n\tvar response *Response\n\tresponse, err = s.requestService(toolbox.AsString(serviceName), toolbox.AsString(method), httpRequest, httpResponse)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = toolbox.WriteServiceRoutingResponse(httpResponse, httpRequest, serviceRouting, response)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n\n}\n\nfunc (s *Server) Start() error {\n\n\trouter := toolbox.NewServiceRouter(\n\t\ttoolbox.ServiceRouting{\n\t\t\tHTTPMethod:     \"POST\",\n\t\t\tURI:            \"\/v1\/endly\/service\/{service}\/{method}\/\",\n\t\t\tHandler:        s.requestService,\n\t\t\tHandlerInvoker: s.routeHandler,\n\t\t\tParameters:     []string{\"service\", \"method\", \"@httpRequest\", \"@httpResponseWriter\"},\n\t\t})\n\n\thttp.HandleFunc(\"\/v1\/\", func(response http.ResponseWriter, reader *http.Request) {\n\t\terr := router.Route(response, reader)\n\t\tif err != nil {\n\t\t\tresponse.WriteHeader(http.StatusInternalServerError)\n\t\t}\n\t})\n\tfmt.Printf(\"Started test server on port %v\\n\", s.port)\n\tlog.Fatal(http.ListenAndServe(\":\"+s.port, nil))\n\treturn nil\n}\n\nfunc NewServer(port string) *Server {\n\treturn &Server{\n\t\tport:    port,\n\t\tmanager: GetManager(),\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/gorilla\/mux\"\n\n\tneturl \"net\/url\"\n)\n\ntype server struct {\n\t\/\/ ShortURLPrefix is an optional prefix to return even shorter URLs than\n\t\/\/ using the request's hostname and path.\n\tShortURLPrefix string\n\n\tDB database\n}\n\n\/\/ illegalChars is a string containing all characters that are illegal in short\n\/\/ URL names. They are illegal because they have a special meaning when using\n\/\/ the short URL link.\nconst illegalChars = \"\/?#\"\n\nfunc (s server) Save(response http.ResponseWriter, request *http.Request) {\n\tdecoder := json.NewDecoder(request.Body)\n\tvar data struct {\n\t\tName string `json:\"name\"`\n\t\tURL  string `json:\"url\"`\n\t}\n\tif err := decoder.Decode(&data); err != nil {\n\t\thttp.Error(response, `{\"error\":\"Unable to parse json\"}`, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif data.Name == \"\" {\n\t\thttp.Error(response, `{\"error\":\"Missing name\"}`, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif strings.ContainsAny(data.Name, illegalChars) {\n\t\tif jsonData, ok := marshalJson(response, map[string]string{\"error\": fmt.Sprintf(\"Name (%q) contains an illegal character: %q\", data.Name, illegalChars)}); ok {\n\t\t\thttp.Error(response, string(jsonData), http.StatusBadRequest)\n\t\t}\n\t\treturn\n\t}\n\n\tif data.URL == \"\" {\n\t\tif jsonData, ok := marshalJson(response, map[string]string{\"error\": fmt.Sprintf(\"Missing URL for %q\", data.Name)}); ok {\n\t\t\thttp.Error(response, string(jsonData), http.StatusBadRequest)\n\t\t}\n\t\treturn\n\t}\n\n\tif _, err := neturl.Parse(data.URL); err != nil {\n\t\tif jsonData, ok := marshalJson(response, map[string]string{\"error\": fmt.Sprintf(\"Not a valid URL: %q.\", data.URL)}); ok {\n\t\t\thttp.Error(response, string(jsonData), http.StatusBadRequest)\n\t\t}\n\t\treturn\n\t}\n\n\tif err := s.DB.SaveURL(data.Name, data.URL); err != nil {\n\t\tif jsonData, ok := marshalJson(response, map[string]string{\"error\": err.Error()}); ok {\n\t\t\thttp.Error(response, string(jsonData), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tresp := map[string]string{\"name\": data.Name}\n\tif s.ShortURLPrefix != \"\" {\n\t\tresp[\"url\"] = s.ShortURLPrefix\n\t}\n\tif jsonData, ok := marshalJson(response, resp); ok {\n\t\tresponse.Write(jsonData)\n\t}\n}\n\nfunc (s server) Load(response http.ResponseWriter, request *http.Request) {\n\tname := mux.Vars(request)[\"name\"]\n\n\turl, err := s.DB.LoadURL(name)\n\tif err != nil {\n\t\tif _, ok := err.(NotFoundError); ok {\n\t\t\tq := neturl.Values{}\n\t\t\tq.Add(\"name\", name)\n\t\t\tq.Add(\"error\", \"No such URL yet. Feel free to add one.\")\n\t\t\thttp.Redirect(response, request, \".#\/?\"+q.Encode(), http.StatusFound)\n\t\t}\n\n\t\tif jsonData, ok := marshalJson(response, map[string]string{\"error\": err.Error()}); ok {\n\t\t\thttp.Error(response, string(jsonData), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tvar u *neturl.URL\n\tif u, err = neturl.Parse(url); err != nil {\n\t\thttp.Redirect(response, request, url, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\tvar tinkered bool\n\n\tif folder := mux.Vars(request)[\"folder\"]; folder != \"\" {\n\t\tu.Path += folder\n\t\ttinkered = true\n\t}\n\n\tif q := request.URL.RawQuery; q != \"\" && u.RawQuery == \"\" {\n\t\tu.RawQuery = q\n\t\ttinkered = true\n\t}\n\n\tif tinkered {\n\t\turl = u.String()\n\t}\n\n\thttp.Redirect(response, request, url, http.StatusMovedPermanently)\n}\n\nfunc marshalJson(response http.ResponseWriter, reply map[string]string) ([]byte, bool) {\n\tjsonData, err := json.Marshal(reply)\n\tif err != nil {\n\t\thttp.Error(response, `{\"error\":\"Unable to encode json\"}`, http.StatusInternalServerError)\n\t\treturn nil, false\n\t}\n\treturn jsonData, true\n}\n<commit_msg>Return just after the Redirection.<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/gorilla\/mux\"\n\n\tneturl \"net\/url\"\n)\n\ntype server struct {\n\t\/\/ ShortURLPrefix is an optional prefix to return even shorter URLs than\n\t\/\/ using the request's hostname and path.\n\tShortURLPrefix string\n\n\tDB database\n}\n\n\/\/ illegalChars is a string containing all characters that are illegal in short\n\/\/ URL names. They are illegal because they have a special meaning when using\n\/\/ the short URL link.\nconst illegalChars = \"\/?#\"\n\nfunc (s server) Save(response http.ResponseWriter, request *http.Request) {\n\tdecoder := json.NewDecoder(request.Body)\n\tvar data struct {\n\t\tName string `json:\"name\"`\n\t\tURL  string `json:\"url\"`\n\t}\n\tif err := decoder.Decode(&data); err != nil {\n\t\thttp.Error(response, `{\"error\":\"Unable to parse json\"}`, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif data.Name == \"\" {\n\t\thttp.Error(response, `{\"error\":\"Missing name\"}`, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif strings.ContainsAny(data.Name, illegalChars) {\n\t\tif jsonData, ok := marshalJson(response, map[string]string{\"error\": fmt.Sprintf(\"Name (%q) contains an illegal character: %q\", data.Name, illegalChars)}); ok {\n\t\t\thttp.Error(response, string(jsonData), http.StatusBadRequest)\n\t\t}\n\t\treturn\n\t}\n\n\tif data.URL == \"\" {\n\t\tif jsonData, ok := marshalJson(response, map[string]string{\"error\": fmt.Sprintf(\"Missing URL for %q\", data.Name)}); ok {\n\t\t\thttp.Error(response, string(jsonData), http.StatusBadRequest)\n\t\t}\n\t\treturn\n\t}\n\n\tif _, err := neturl.Parse(data.URL); err != nil {\n\t\tif jsonData, ok := marshalJson(response, map[string]string{\"error\": fmt.Sprintf(\"Not a valid URL: %q.\", data.URL)}); ok {\n\t\t\thttp.Error(response, string(jsonData), http.StatusBadRequest)\n\t\t}\n\t\treturn\n\t}\n\n\tif err := s.DB.SaveURL(data.Name, data.URL); err != nil {\n\t\tif jsonData, ok := marshalJson(response, map[string]string{\"error\": err.Error()}); ok {\n\t\t\thttp.Error(response, string(jsonData), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tresp := map[string]string{\"name\": data.Name}\n\tif s.ShortURLPrefix != \"\" {\n\t\tresp[\"url\"] = s.ShortURLPrefix\n\t}\n\tif jsonData, ok := marshalJson(response, resp); ok {\n\t\tresponse.Write(jsonData)\n\t}\n}\n\nfunc (s server) Load(response http.ResponseWriter, request *http.Request) {\n\tname := mux.Vars(request)[\"name\"]\n\n\turl, err := s.DB.LoadURL(name)\n\tif err != nil {\n\t\tif _, ok := err.(NotFoundError); ok {\n\t\t\tq := neturl.Values{}\n\t\t\tq.Add(\"name\", name)\n\t\t\tq.Add(\"error\", \"No such URL yet. Feel free to add one.\")\n\t\t\thttp.Redirect(response, request, \".#\/?\"+q.Encode(), http.StatusFound)\n\t\t\treturn\n\t\t}\n\n\t\tif jsonData, ok := marshalJson(response, map[string]string{\"error\": err.Error()}); ok {\n\t\t\thttp.Error(response, string(jsonData), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tvar u *neturl.URL\n\tif u, err = neturl.Parse(url); err != nil {\n\t\thttp.Redirect(response, request, url, http.StatusMovedPermanently)\n\t\treturn\n\t}\n\n\tvar tinkered bool\n\n\tif folder := mux.Vars(request)[\"folder\"]; folder != \"\" {\n\t\tu.Path += folder\n\t\ttinkered = true\n\t}\n\n\tif q := request.URL.RawQuery; q != \"\" && u.RawQuery == \"\" {\n\t\tu.RawQuery = q\n\t\ttinkered = true\n\t}\n\n\tif tinkered {\n\t\turl = u.String()\n\t}\n\n\thttp.Redirect(response, request, url, http.StatusMovedPermanently)\n}\n\nfunc marshalJson(response http.ResponseWriter, reply map[string]string) ([]byte, bool) {\n\tjsonData, err := json.Marshal(reply)\n\tif err != nil {\n\t\thttp.Error(response, `{\"error\":\"Unable to encode json\"}`, http.StatusInternalServerError)\n\t\treturn nil, false\n\t}\n\treturn jsonData, true\n}\n<|endoftext|>"}
{"text":"<commit_before>package revel\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/websocket\"\n)\n\nvar (\n\tMainRouter         *Router\n\tMainTemplateLoader *TemplateLoader\n\tMainWatcher        *Watcher\n\tServer             *http.Server\n)\n\n\/\/ This method handles all requests.  It dispatches to handleInternal after\n\/\/ handling \/ adapting websocket connections.\nfunc handle(w http.ResponseWriter, r *http.Request) {\n\tr.Body = http.MaxBytesReader(w, r.Body, int64(Config.IntDefault(\"http.maxRequestSize\", 10000000)))\n\tupgrade := r.Header.Get(\"Upgrade\")\n\tif upgrade == \"websocket\" || upgrade == \"Websocket\" {\n\t\twebsocket.Handler(func(ws *websocket.Conn) {\n\t\t\t\/\/Override default Read\/Write timeout with sane value for a web socket request\n\t\t\tws.SetDeadline(time.Now().Add(time.Hour * 24))\n\t\t\tr.Method = \"WS\"\n\t\t\thandleInternal(w, r, ws)\n\t\t}).ServeHTTP(w, r)\n\t} else {\n\t\thandleInternal(w, r, nil)\n\t}\n}\n\nfunc handleInternal(w http.ResponseWriter, r *http.Request, ws *websocket.Conn) {\n\tvar (\n\t\treq  = NewRequest(r)\n\t\tresp = NewResponse(w)\n\t\tc    = NewController(req, resp)\n\t)\n\treq.Websocket = ws\n\n\tFilters[0](c, Filters[1:])\n\tif c.Result != nil {\n\t\tc.Result.Apply(req, resp)\n\t} else if c.Response.Status != 0 {\n\t\tc.Response.Out.WriteHeader(c.Response.Status)\n\t}\n\t\/\/ Close the Writer if we can\n\tif w, ok := resp.Out.(io.Closer); ok {\n\t\tw.Close()\n\t}\n}\n\n\/\/ Run the server.\n\/\/ This is called from the generated main file.\n\/\/ If port is non-zero, use that.  Else, read the port from app.conf.\nfunc Run(port int) {\n\taddress := HttpAddr\n\tif port == 0 {\n\t\tport = HttpPort\n\t}\n\n\tvar network = \"tcp\"\n\tvar localAddress string\n\n\t\/\/ If the port is zero, treat the address as a fully qualified local address.\n\t\/\/ This address must be prefixed with the network type followed by a colon,\n\t\/\/ e.g. unix:\/tmp\/app.socket or tcp6:::1 (equivalent to tcp6:0:0:0:0:0:0:0:1)\n\tif port == 0 {\n\t\tparts := strings.SplitN(address, \":\", 2)\n\t\tnetwork = parts[0]\n\t\tlocalAddress = parts[1]\n\t} else {\n\t\tlocalAddress = address + \":\" + strconv.Itoa(port)\n\t}\n\n\tServer = &http.Server{\n\t\tAddr:         localAddress,\n\t\tHandler:      http.HandlerFunc(handle),\n\t\tReadTimeout:  time.Minute,\n\t\tWriteTimeout: time.Minute,\n\t}\n\n\trunStartupHooks()\n\n\t\/\/ Load templates\n\tMainTemplateLoader = NewTemplateLoader(TemplatePaths)\n\tMainTemplateLoader.Refresh()\n\n\t\/\/ The \"watch\" config variable can turn on and off all watching.\n\t\/\/ (As a convenient way to control it all together.)\n\tif Config.BoolDefault(\"watch\", true) {\n\t\tMainWatcher = NewWatcher()\n\t\tFilters = append([]Filter{WatchFilter}, Filters...)\n\t}\n\n\t\/\/ If desired (or by default), create a watcher for templates and routes.\n\t\/\/ The watcher calls Refresh() on things on the first request.\n\tif MainWatcher != nil && Config.BoolDefault(\"watch.templates\", true) {\n\t\tMainWatcher.Listen(MainTemplateLoader, MainTemplateLoader.paths...)\n\t}\n\n\tgo func() {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tfmt.Printf(\"Listening on %s...\\n\", localAddress)\n\t}()\n\n\tif HttpSsl {\n\t\tif network != \"tcp\" {\n\t\t\t\/\/ This limitation is just to reduce complexity, since it is standard\n\t\t\t\/\/ to terminate SSL upstream when using unix domain sockets.\n\t\t\tERROR.Fatalln(\"SSL is only supported for TCP sockets. Specify a port to listen on.\")\n\t\t}\n\t\tERROR.Fatalln(\"Failed to listen:\",\n\t\t\tServer.ListenAndServeTLS(HttpSslCert, HttpSslKey))\n\t} else {\n\t\tlistener, err := net.Listen(network, localAddress)\n\t\tif err != nil {\n\t\t\tERROR.Fatalln(\"Failed to listen:\", err)\n\t\t}\n\t\tERROR.Fatalln(\"Failed to serve:\", Server.Serve(listener))\n\t}\n}\n\nfunc runStartupHooks() {\n\tfor _, hook := range startupHooks {\n\t\thook()\n\t}\n}\n\nvar startupHooks []func()\n\n\/\/ Register a function to be run at app startup.\n\/\/\n\/\/ The order you register the functions will be the order they are run.\n\/\/ You can think of it as a FIFO queue.\n\/\/ This process will happen after the config file is read\n\/\/ and before the server is listening for connections.\n\/\/\n\/\/ Ideally, your application should have only one call to init() in the file init.go.\n\/\/ The reason being that the call order of multiple init() functions in\n\/\/ the same package is undefined.\n\/\/ Inside of init() call revel.OnAppStart() for each function you wish to register.\n\/\/\n\/\/ Example:\n\/\/\n\/\/      \/\/ from: yourapp\/app\/controllers\/somefile.go\n\/\/      func InitDB() {\n\/\/          \/\/ do DB connection stuff here\n\/\/      }\n\/\/\n\/\/      func FillCache() {\n\/\/          \/\/ fill a cache from DB\n\/\/          \/\/ this depends on InitDB having been run\n\/\/      }\n\/\/\n\/\/      \/\/ from: yourapp\/app\/init.go\n\/\/      func init() {\n\/\/          \/\/ set up filters...\n\/\/\n\/\/          \/\/ register startup functions\n\/\/          revel.OnAppStart(InitDB)\n\/\/          revel.OnAppStart(FillCache)\n\/\/      }\n\/\/\n\/\/ This can be useful when you need to establish connections to databases or third-party services,\n\/\/ setup app components, compile assets, or any thing you need to do between starting Revel and accepting connections.\n\/\/\nfunc OnAppStart(f func()) {\n\tstartupHooks = append(startupHooks, f)\n}\n<commit_msg>Rename maxRequestSize setting, default to unset<commit_after>package revel\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/websocket\"\n)\n\nvar (\n\tMainRouter         *Router\n\tMainTemplateLoader *TemplateLoader\n\tMainWatcher        *Watcher\n\tServer             *http.Server\n)\n\n\/\/ This method handles all requests.  It dispatches to handleInternal after\n\/\/ handling \/ adapting websocket connections.\nfunc handle(w http.ResponseWriter, r *http.Request) {\n\tif maxRequestSize := int64(Config.IntDefault(\"http.maxrequestsize\", 0)); maxRequestSize > 0 {\n\t\tr.Body = http.MaxBytesReader(w, r.Body, maxRequestSize)\n\t}\n\n\tupgrade := r.Header.Get(\"Upgrade\")\n\tif upgrade == \"websocket\" || upgrade == \"Websocket\" {\n\t\twebsocket.Handler(func(ws *websocket.Conn) {\n\t\t\t\/\/Override default Read\/Write timeout with sane value for a web socket request\n\t\t\tws.SetDeadline(time.Now().Add(time.Hour * 24))\n\t\t\tr.Method = \"WS\"\n\t\t\thandleInternal(w, r, ws)\n\t\t}).ServeHTTP(w, r)\n\t} else {\n\t\thandleInternal(w, r, nil)\n\t}\n}\n\nfunc handleInternal(w http.ResponseWriter, r *http.Request, ws *websocket.Conn) {\n\tvar (\n\t\treq  = NewRequest(r)\n\t\tresp = NewResponse(w)\n\t\tc    = NewController(req, resp)\n\t)\n\treq.Websocket = ws\n\n\tFilters[0](c, Filters[1:])\n\tif c.Result != nil {\n\t\tc.Result.Apply(req, resp)\n\t} else if c.Response.Status != 0 {\n\t\tc.Response.Out.WriteHeader(c.Response.Status)\n\t}\n\t\/\/ Close the Writer if we can\n\tif w, ok := resp.Out.(io.Closer); ok {\n\t\tw.Close()\n\t}\n}\n\n\/\/ Run the server.\n\/\/ This is called from the generated main file.\n\/\/ If port is non-zero, use that.  Else, read the port from app.conf.\nfunc Run(port int) {\n\taddress := HttpAddr\n\tif port == 0 {\n\t\tport = HttpPort\n\t}\n\n\tvar network = \"tcp\"\n\tvar localAddress string\n\n\t\/\/ If the port is zero, treat the address as a fully qualified local address.\n\t\/\/ This address must be prefixed with the network type followed by a colon,\n\t\/\/ e.g. unix:\/tmp\/app.socket or tcp6:::1 (equivalent to tcp6:0:0:0:0:0:0:0:1)\n\tif port == 0 {\n\t\tparts := strings.SplitN(address, \":\", 2)\n\t\tnetwork = parts[0]\n\t\tlocalAddress = parts[1]\n\t} else {\n\t\tlocalAddress = address + \":\" + strconv.Itoa(port)\n\t}\n\n\tServer = &http.Server{\n\t\tAddr:         localAddress,\n\t\tHandler:      http.HandlerFunc(handle),\n\t\tReadTimeout:  time.Minute,\n\t\tWriteTimeout: time.Minute,\n\t}\n\n\trunStartupHooks()\n\n\t\/\/ Load templates\n\tMainTemplateLoader = NewTemplateLoader(TemplatePaths)\n\tMainTemplateLoader.Refresh()\n\n\t\/\/ The \"watch\" config variable can turn on and off all watching.\n\t\/\/ (As a convenient way to control it all together.)\n\tif Config.BoolDefault(\"watch\", true) {\n\t\tMainWatcher = NewWatcher()\n\t\tFilters = append([]Filter{WatchFilter}, Filters...)\n\t}\n\n\t\/\/ If desired (or by default), create a watcher for templates and routes.\n\t\/\/ The watcher calls Refresh() on things on the first request.\n\tif MainWatcher != nil && Config.BoolDefault(\"watch.templates\", true) {\n\t\tMainWatcher.Listen(MainTemplateLoader, MainTemplateLoader.paths...)\n\t}\n\n\tgo func() {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tfmt.Printf(\"Listening on %s...\\n\", localAddress)\n\t}()\n\n\tif HttpSsl {\n\t\tif network != \"tcp\" {\n\t\t\t\/\/ This limitation is just to reduce complexity, since it is standard\n\t\t\t\/\/ to terminate SSL upstream when using unix domain sockets.\n\t\t\tERROR.Fatalln(\"SSL is only supported for TCP sockets. Specify a port to listen on.\")\n\t\t}\n\t\tERROR.Fatalln(\"Failed to listen:\",\n\t\t\tServer.ListenAndServeTLS(HttpSslCert, HttpSslKey))\n\t} else {\n\t\tlistener, err := net.Listen(network, localAddress)\n\t\tif err != nil {\n\t\t\tERROR.Fatalln(\"Failed to listen:\", err)\n\t\t}\n\t\tERROR.Fatalln(\"Failed to serve:\", Server.Serve(listener))\n\t}\n}\n\nfunc runStartupHooks() {\n\tfor _, hook := range startupHooks {\n\t\thook()\n\t}\n}\n\nvar startupHooks []func()\n\n\/\/ Register a function to be run at app startup.\n\/\/\n\/\/ The order you register the functions will be the order they are run.\n\/\/ You can think of it as a FIFO queue.\n\/\/ This process will happen after the config file is read\n\/\/ and before the server is listening for connections.\n\/\/\n\/\/ Ideally, your application should have only one call to init() in the file init.go.\n\/\/ The reason being that the call order of multiple init() functions in\n\/\/ the same package is undefined.\n\/\/ Inside of init() call revel.OnAppStart() for each function you wish to register.\n\/\/\n\/\/ Example:\n\/\/\n\/\/      \/\/ from: yourapp\/app\/controllers\/somefile.go\n\/\/      func InitDB() {\n\/\/          \/\/ do DB connection stuff here\n\/\/      }\n\/\/\n\/\/      func FillCache() {\n\/\/          \/\/ fill a cache from DB\n\/\/          \/\/ this depends on InitDB having been run\n\/\/      }\n\/\/\n\/\/      \/\/ from: yourapp\/app\/init.go\n\/\/      func init() {\n\/\/          \/\/ set up filters...\n\/\/\n\/\/          \/\/ register startup functions\n\/\/          revel.OnAppStart(InitDB)\n\/\/          revel.OnAppStart(FillCache)\n\/\/      }\n\/\/\n\/\/ This can be useful when you need to establish connections to databases or third-party services,\n\/\/ setup app components, compile assets, or any thing you need to do between starting Revel and accepting connections.\n\/\/\nfunc OnAppStart(f func()) {\n\tstartupHooks = append(startupHooks, f)\n}\n<|endoftext|>"}
{"text":"<commit_before>package caspercloud\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/BigTong\/gocounter\"\n\t\"github.com\/xlvector\/dlog\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"runtime\/debug\"\n)\n\nconst (\n\tkInternalErrorResut = \"server get internal result\"\n)\n\ntype CasperServer struct {\n\tcmdCache   *CommandCache\n\tct         *gocounter.Counter\n\tcmdFactory CommandFactory\n}\n\nfunc NewCasperServer(cf CommandFactory) *CasperServer {\n\treturn &CasperServer{\n\t\tcmdCache:   NewCommandCache(),\n\t\tct:         gocounter.NewCounter(),\n\t\tcmdFactory: cf,\n\t}\n}\n\nfunc (self *CasperServer) setArgs(cmd Command, params url.Values) *Output {\n\targs := self.getArgs(params)\n\tdlog.Println(\"setArgs:\", args)\n\tcmd.SetInputArgs(args)\n\n\tif message := cmd.GetMessage(); message != nil {\n\t\treturn message\n\t}\n\treturn nil\n}\n\nfunc (self *CasperServer) getArgs(params url.Values) map[string]string {\n\targs := make(map[string]string)\n\tfor k, v := range params {\n\t\targs[k] = v[0]\n\t}\n\treturn args\n}\n\nfunc (self *CasperServer) Process(params url.Values) *Output {\n\tdlog.Info(\"%s\", params.Encode())\n\tid := params.Get(\"id\")\n\tif len(id) == 0 {\n\t\tc := self.cmdFactory.CreateCommand(params)\n\t\tif c == nil {\n\t\t\treturn &Output{Status: FAIL, Data: \"no create command\"}\n\t\t}\n\t\tself.cmdCache.SetCommand(c)\n\t\tparams.Set(\"id\", c.GetId())\n\t\treturn self.setArgs(c, params)\n\t}\n\n\tdlog.Info(\"get id:%s\", id)\n\tc := self.cmdCache.GetCommand(id)\n\tif c == nil {\n\t\tdlog.Warn(\"get nil command id:%s\", id)\n\t\treturn &Output{Status: FAIL, Data: \"not get command\"}\n\t}\n\n\tdlog.Info(\"get cmd:%s\", id)\n\tret := self.setArgs(c, params)\n\n\tif c.Finished() {\n\t\tc.Successed()\n\t\tself.cmdCache.Delete(id)\n\t\treturn &Output{Status: FINISH_FETCH_DATA}\n\t}\n\n\tif ret.Status == FAIL {\n\t\tc.Successed()\n\t\treturn &Output{Status: FAIL, Data: ret.Data}\n\t}\n\n\treturn ret\n}\n\nfunc (self *CasperServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tdlog.Println(\"ERROR: http submit\", r)\n\t\t\tdebug.PrintStack()\n\t\t}\n\t}()\n\tself.ct.Incr(\"request\", 1)\n\tparams := req.URL.Query()\n\tret := self.Process(params)\n\toutput, _ := json.Marshal(ret)\n\tfmt.Fprint(w, string(output))\n\treturn\n}\n<commit_msg>delete id<commit_after>package caspercloud\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/BigTong\/gocounter\"\n\t\"github.com\/xlvector\/dlog\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"runtime\/debug\"\n)\n\nconst (\n\tkInternalErrorResut = \"server get internal result\"\n)\n\ntype CasperServer struct {\n\tcmdCache   *CommandCache\n\tct         *gocounter.Counter\n\tcmdFactory CommandFactory\n}\n\nfunc NewCasperServer(cf CommandFactory) *CasperServer {\n\treturn &CasperServer{\n\t\tcmdCache:   NewCommandCache(),\n\t\tct:         gocounter.NewCounter(),\n\t\tcmdFactory: cf,\n\t}\n}\n\nfunc (self *CasperServer) setArgs(cmd Command, params url.Values) *Output {\n\targs := self.getArgs(params)\n\tdlog.Println(\"setArgs:\", args)\n\tcmd.SetInputArgs(args)\n\n\tif message := cmd.GetMessage(); message != nil {\n\t\treturn message\n\t}\n\treturn nil\n}\n\nfunc (self *CasperServer) getArgs(params url.Values) map[string]string {\n\targs := make(map[string]string)\n\tfor k, v := range params {\n\t\targs[k] = v[0]\n\t}\n\treturn args\n}\n\nfunc (self *CasperServer) Process(params url.Values) *Output {\n\tdlog.Info(\"%s\", params.Encode())\n\tid := params.Get(\"id\")\n\tif len(id) == 0 {\n\t\tc := self.cmdFactory.CreateCommand(params)\n\t\tif c == nil {\n\t\t\treturn &Output{Status: FAIL, Data: \"no create command\"}\n\t\t}\n\t\tself.cmdCache.SetCommand(c)\n\t\tparams.Set(\"id\", c.GetId())\n\t\treturn self.setArgs(c, params)\n\t}\n\n\tdlog.Info(\"get id:%s\", id)\n\tc := self.cmdCache.GetCommand(id)\n\tif c == nil {\n\t\tdlog.Warn(\"get nil command id:%s\", id)\n\t\treturn &Output{Status: FAIL, Data: \"not get command\"}\n\t}\n\n\tdlog.Info(\"get cmd:%s\", id)\n\tret := self.setArgs(c, params)\n\n\tif c.Finished() || ret.Status == FAIL || ret.Status == FINISH_FETCH_DATA || ret.Status == FINISH_ALL {\n\t\tc.Successed()\n\t\tself.cmdCache.Delete(id)\n\t}\n\n\treturn ret\n}\n\nfunc (self *CasperServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tdlog.Println(\"ERROR: http submit\", r)\n\t\t\tdebug.PrintStack()\n\t\t}\n\t}()\n\tself.ct.Incr(\"request\", 1)\n\tparams := req.URL.Query()\n\tret := self.Process(params)\n\toutput, _ := json.Marshal(ret)\n\tfmt.Fprint(w, string(output))\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package pixel\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"log\/syslog\"\n\t\"net\/http\"\n\t\"time\"\n)\n\ntype Server struct {\n\tlistenAddress  string\n\thttpServer     *http.Server\n\tsyslogAddress  string\n\tsyslogPriority syslog.Priority\n\tlogger         *log.Logger\n\tnow            func() time.Time\n}\n\ntype Event struct {\n\tTime      string            `json:\"t\"`\n\tParams    map[string]string `json:\"params\"`\n\tUserAgent string            `json:\"ua,omitempty\"`\n\tIP        string            `json:\"ip,omitempty\"`\n\tProto     string            `json:\"proto,omitempty\"`\n}\n\nconst ISO8601_FORMAT = \"2006-01-02T15:04:05Z\"\n\nconst TRANSPARENT_1_PX_GIF = \"\\x47\\x49\\x46\\x38\\x39\\x61\\x01\\x00\" +\n\t\"\\x01\\x00\\x80\\x00\\x00\\xff\\xff\\xff\\x00\\x00\\x00\\x2c\\x00\\x00\\x00\\x00\" +\n\t\"\\x01\\x00\\x01\\x00\\x00\\x02\\x02\\x44\\x01\\x00\\x3b\"\n\nvar BAD_REQUEST string\nvar TRANSPARENT_1_PX_GIF_BYTES []byte\n\nfunc init() {\n\tTRANSPARENT_1_PX_GIF_BYTES = []byte(TRANSPARENT_1_PX_GIF)\n\tBAD_REQUEST = http.StatusText(http.StatusBadRequest)\n}\n\nfunc NewSyslogPriority(level string, facility string) (p syslog.Priority) {\n\tswitch level {\n\tcase \"LOG_EMERG\":\n\t\tp = syslog.LOG_EMERG\n\tcase \"LOG_ALERT\":\n\t\tp = syslog.LOG_ALERT\n\tcase \"LOG_CRIT\":\n\t\tp = syslog.LOG_CRIT\n\tcase \"LOG_ERR\":\n\t\tp = syslog.LOG_ERR\n\tcase \"LOG_WARNING\":\n\t\tp = syslog.LOG_WARNING\n\tcase \"LOG_NOTICE\":\n\t\tp = syslog.LOG_NOTICE\n\tcase \"LOG_INFO\":\n\t\tp = syslog.LOG_INFO\n\tcase \"LOG_DEBUG\":\n\t\tp = syslog.LOG_DEBUG\n\tdefault:\n\t\tp = syslog.LOG_INFO\n\t}\n\n\tswitch facility {\n\tcase \"LOG_KERN\":\n\t\tp |= syslog.LOG_KERN\n\tcase \"LOG_USER\":\n\t\tp |= syslog.LOG_USER\n\tcase \"LOG_MAIL\":\n\t\tp |= syslog.LOG_MAIL\n\tcase \"LOG_DAEMON\":\n\t\tp |= syslog.LOG_DAEMON\n\tcase \"LOG_AUTH\":\n\t\tp |= syslog.LOG_AUTH\n\tcase \"LOG_SYSLOG\":\n\t\tp |= syslog.LOG_SYSLOG\n\tcase \"LOG_LPR\":\n\t\tp |= syslog.LOG_LPR\n\tcase \"LOG_NEWS\":\n\t\tp |= syslog.LOG_NEWS\n\tcase \"LOG_UUCP\":\n\t\tp |= syslog.LOG_UUCP\n\tcase \"LOG_CRON\":\n\t\tp |= syslog.LOG_CRON\n\tcase \"LOG_AUTHPRIV\":\n\t\tp |= syslog.LOG_AUTHPRIV\n\tcase \"LOG_FTP\":\n\t\tp |= syslog.LOG_FTP\n\tcase \"LOG_LOCAL0\":\n\t\tp |= syslog.LOG_LOCAL0\n\tcase \"LOG_LOCAL1\":\n\t\tp |= syslog.LOG_LOCAL1\n\tcase \"LOG_LOCAL2\":\n\t\tp |= syslog.LOG_LOCAL2\n\tcase \"LOG_LOCAL3\":\n\t\tp |= syslog.LOG_LOCAL3\n\tcase \"LOG_LOCAL4\":\n\t\tp |= syslog.LOG_LOCAL4\n\tcase \"LOG_LOCAL5\":\n\t\tp |= syslog.LOG_LOCAL5\n\tcase \"LOG_LOCAL6\":\n\t\tp |= syslog.LOG_LOCAL6\n\tcase \"LOG_LOCAL7\":\n\t\tp |= syslog.LOG_LOCAL7\n\tdefault:\n\t\tp |= syslog.LOG_LOCAL7\n\t}\n\treturn p\n}\n\nfunc NewServer(syslogAddress string, syslogPriority syslog.Priority) (*Server, error) {\n\tvar err error\n\tvar writer *syslog.Writer\n\ts := new(Server)\n\ts.syslogAddress = syslogAddress\n\ts.syslogPriority = syslogPriority\n\n\twriter, err = syslog.Dial(\"udp\", s.syslogAddress, s.syslogPriority,\n\t\t\"pixel\")\n\t\/\/ log.Printf(\"dial: %s %d\", s.syslogAddress, s.syslogPriority)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.logger = log.New(writer, \"\", 0)\n\ts.now = time.Now\n\treturn s, err\n}\n\nfunc NewEvent(t time.Time, r *http.Request) (event *Event, err error) {\n\terr = r.ParseForm()\n\tif err != nil {\n\t\tlog.Printf(\"Malformed query string: %s\", err)\n\t\treturn\n\t}\n\n\tevent = &Event{\n\t\tTime:   t.UTC().Format(ISO8601_FORMAT),\n\t\tParams: make(map[string]string),\n\t}\n\n\tfor key, values := range r.Form {\n\t\tevent.Params[key] = values[0]\n\t}\n\n\tevent.UserAgent = r.Header.Get(\"User-Agent\")\n\tevent.IP = r.Header.Get(\"X-Forwarded-For\")\n\tevent.Proto = r.Header.Get(\"X-Forwarded-Proto\")\n\treturn event, err\n}\n\nfunc (s *Server) trackPixel(w http.ResponseWriter, r *http.Request) {\n\tvar event *Event\n\tvar err error\n\tvar jsondata []byte\n\n\tevent, err = NewEvent(s.now(), r)\n\tif err != nil {\n\t\tlog.Printf(\"%s\", err)\n\t\thttp.Error(w, BAD_REQUEST, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"image\/gif\")\n\tw.Write(TRANSPARENT_1_PX_GIF_BYTES)\n\n\tjsondata, err = json.Marshal(event)\n\tif err != nil {\n\t\tlog.Printf(\"json encode error: %s\", err)\n\t} else {\n\t\ts.logger.Printf(\"%s\", jsondata)\n\t}\n}\n\nfunc (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\ts.trackPixel(w, r)\n\t\treturn\n\n\tdefault:\n\t\thttp.Error(w, BAD_REQUEST, http.StatusBadRequest)\n\t}\n}\n\nfunc (s *Server) ListenAndServe(address string) {\n\ts.httpServer = &http.Server{\n\t\tAddr:           address,\n\t\tHandler:        s,\n\t\tReadTimeout:    10 * time.Second,\n\t\tWriteTimeout:   10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\tlog.Fatal(s.httpServer.ListenAndServe())\n}\n<commit_msg>remove logging comment; standardize return args<commit_after>package pixel\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"log\/syslog\"\n\t\"net\/http\"\n\t\"time\"\n)\n\ntype Server struct {\n\tlistenAddress  string\n\thttpServer     *http.Server\n\tsyslogAddress  string\n\tsyslogPriority syslog.Priority\n\tlogger         *log.Logger\n\tnow            func() time.Time\n}\n\ntype Event struct {\n\tTime      string            `json:\"t\"`\n\tParams    map[string]string `json:\"params\"`\n\tUserAgent string            `json:\"ua,omitempty\"`\n\tIP        string            `json:\"ip,omitempty\"`\n\tProto     string            `json:\"proto,omitempty\"`\n}\n\nconst ISO8601_FORMAT = \"2006-01-02T15:04:05Z\"\n\nconst TRANSPARENT_1_PX_GIF = \"\\x47\\x49\\x46\\x38\\x39\\x61\\x01\\x00\" +\n\t\"\\x01\\x00\\x80\\x00\\x00\\xff\\xff\\xff\\x00\\x00\\x00\\x2c\\x00\\x00\\x00\\x00\" +\n\t\"\\x01\\x00\\x01\\x00\\x00\\x02\\x02\\x44\\x01\\x00\\x3b\"\n\nvar BAD_REQUEST string\nvar TRANSPARENT_1_PX_GIF_BYTES []byte\n\nfunc init() {\n\tTRANSPARENT_1_PX_GIF_BYTES = []byte(TRANSPARENT_1_PX_GIF)\n\tBAD_REQUEST = http.StatusText(http.StatusBadRequest)\n}\n\nfunc NewSyslogPriority(level string, facility string) (p syslog.Priority) {\n\tswitch level {\n\tcase \"LOG_EMERG\":\n\t\tp = syslog.LOG_EMERG\n\tcase \"LOG_ALERT\":\n\t\tp = syslog.LOG_ALERT\n\tcase \"LOG_CRIT\":\n\t\tp = syslog.LOG_CRIT\n\tcase \"LOG_ERR\":\n\t\tp = syslog.LOG_ERR\n\tcase \"LOG_WARNING\":\n\t\tp = syslog.LOG_WARNING\n\tcase \"LOG_NOTICE\":\n\t\tp = syslog.LOG_NOTICE\n\tcase \"LOG_INFO\":\n\t\tp = syslog.LOG_INFO\n\tcase \"LOG_DEBUG\":\n\t\tp = syslog.LOG_DEBUG\n\tdefault:\n\t\tp = syslog.LOG_INFO\n\t}\n\n\tswitch facility {\n\tcase \"LOG_KERN\":\n\t\tp |= syslog.LOG_KERN\n\tcase \"LOG_USER\":\n\t\tp |= syslog.LOG_USER\n\tcase \"LOG_MAIL\":\n\t\tp |= syslog.LOG_MAIL\n\tcase \"LOG_DAEMON\":\n\t\tp |= syslog.LOG_DAEMON\n\tcase \"LOG_AUTH\":\n\t\tp |= syslog.LOG_AUTH\n\tcase \"LOG_SYSLOG\":\n\t\tp |= syslog.LOG_SYSLOG\n\tcase \"LOG_LPR\":\n\t\tp |= syslog.LOG_LPR\n\tcase \"LOG_NEWS\":\n\t\tp |= syslog.LOG_NEWS\n\tcase \"LOG_UUCP\":\n\t\tp |= syslog.LOG_UUCP\n\tcase \"LOG_CRON\":\n\t\tp |= syslog.LOG_CRON\n\tcase \"LOG_AUTHPRIV\":\n\t\tp |= syslog.LOG_AUTHPRIV\n\tcase \"LOG_FTP\":\n\t\tp |= syslog.LOG_FTP\n\tcase \"LOG_LOCAL0\":\n\t\tp |= syslog.LOG_LOCAL0\n\tcase \"LOG_LOCAL1\":\n\t\tp |= syslog.LOG_LOCAL1\n\tcase \"LOG_LOCAL2\":\n\t\tp |= syslog.LOG_LOCAL2\n\tcase \"LOG_LOCAL3\":\n\t\tp |= syslog.LOG_LOCAL3\n\tcase \"LOG_LOCAL4\":\n\t\tp |= syslog.LOG_LOCAL4\n\tcase \"LOG_LOCAL5\":\n\t\tp |= syslog.LOG_LOCAL5\n\tcase \"LOG_LOCAL6\":\n\t\tp |= syslog.LOG_LOCAL6\n\tcase \"LOG_LOCAL7\":\n\t\tp |= syslog.LOG_LOCAL7\n\tdefault:\n\t\tp |= syslog.LOG_LOCAL7\n\t}\n\treturn p\n}\n\nfunc NewServer(syslogAddress string, syslogPriority syslog.Priority) (*Server, error) {\n\tvar err error\n\tvar writer *syslog.Writer\n\ts := new(Server)\n\ts.syslogAddress = syslogAddress\n\ts.syslogPriority = syslogPriority\n\n\twriter, err = syslog.Dial(\"udp\", s.syslogAddress, s.syslogPriority,\n\t\t\"pixel\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.logger = log.New(writer, \"\", 0)\n\ts.now = time.Now\n\treturn s, err\n}\n\nfunc NewEvent(t time.Time, r *http.Request) (event *Event, err error) {\n\terr = r.ParseForm()\n\tif err != nil {\n\t\tlog.Printf(\"Malformed query string: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tevent = &Event{\n\t\tTime:   t.UTC().Format(ISO8601_FORMAT),\n\t\tParams: make(map[string]string),\n\t}\n\n\tfor key, values := range r.Form {\n\t\tevent.Params[key] = values[0]\n\t}\n\n\tevent.UserAgent = r.Header.Get(\"User-Agent\")\n\tevent.IP = r.Header.Get(\"X-Forwarded-For\")\n\tevent.Proto = r.Header.Get(\"X-Forwarded-Proto\")\n\treturn event, err\n}\n\nfunc (s *Server) trackPixel(w http.ResponseWriter, r *http.Request) {\n\tvar event *Event\n\tvar err error\n\tvar jsondata []byte\n\n\tevent, err = NewEvent(s.now(), r)\n\tif err != nil {\n\t\tlog.Printf(\"%s\", err)\n\t\thttp.Error(w, BAD_REQUEST, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"image\/gif\")\n\tw.Write(TRANSPARENT_1_PX_GIF_BYTES)\n\n\tjsondata, err = json.Marshal(event)\n\tif err != nil {\n\t\tlog.Printf(\"json encode error: %s\", err)\n\t} else {\n\t\ts.logger.Printf(\"%s\", jsondata)\n\t}\n}\n\nfunc (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\ts.trackPixel(w, r)\n\t\treturn\n\n\tdefault:\n\t\thttp.Error(w, BAD_REQUEST, http.StatusBadRequest)\n\t}\n}\n\nfunc (s *Server) ListenAndServe(address string) {\n\ts.httpServer = &http.Server{\n\t\tAddr:           address,\n\t\tHandler:        s,\n\t\tReadTimeout:    10 * time.Second,\n\t\tWriteTimeout:   10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\tlog.Fatal(s.httpServer.ListenAndServe())\n}\n<|endoftext|>"}
{"text":"<commit_before>package hookah\n\nimport (\n\t\"bytes\"\n\t\"crypto\/hmac\"\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar errsNotDir = errors.New(\"Given path is not a dir\")\nvar validGhEvent = regexp.MustCompile(`^[a-z_]{1,30}$`)\n\n\/\/ HookServer implements net\/http.Handler\ntype HookServer struct {\n\tRootDir string\n\tTimeout time.Duration\n\tsecret  string\n\tsync.Mutex\n}\n\n\/\/ NewHookServer instantiates a new HookServer with some basic validation\n\/\/ on the root directory\nfunc NewHookServer(rootdir, secret string, timeout time.Duration) (*HookServer, error) {\n\tf, err := os.Open(rootdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !fi.IsDir() {\n\t\treturn nil, errsNotDir\n\t}\n\n\treturn &HookServer{\n\t\tRootDir: rootdir,\n\t\tTimeout: timeout,\n\t\tsecret:  secret,\n\t}, nil\n}\n\nfunc (h *HookServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tghEvent := r.Header.Get(\"X-Github-Event\")\n\n\tif !validGhEvent.MatchString(ghEvent) {\n\t\thttp.Error(w, \"Request requires valid X-Github-Event\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif ghEvent == \"ping\" {\n\t\tfmt.Fprintln(w, \"pong\")\n\t\treturn\n\t}\n\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tbuff := bytes.NewReader(b)\n\n\tif h.secret != \"\" {\n\t\txSig := r.Header.Get(\"X-Hub-Signature\")\n\n\t\tif xSig == \"\" {\n\t\t\thttp.Error(w, \"Missing required X-Hub-Signature for HMAC verification\", http.StatusForbidden)\n\t\t\tlog.Println(\"missing X-Hub-Signature\")\n\t\t\treturn\n\t\t}\n\n\t\thash := hmac.New(sha1.New, []byte(h.secret))\n\t\thash.Write(b)\n\n\t\tehash := hash.Sum(nil)\n\t\tesig := \"sha1=\" + hex.EncodeToString(ehash)\n\n\t\tif !hmac.Equal([]byte(esig), []byte(xSig)) {\n\t\t\thttp.Error(w, \"HMAC verification failed\", http.StatusForbidden)\n\t\t\tlog.Println(\"HMAC verification failed\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tbasicHook := &HookJSON{}\n\n\tdecoder := json.NewDecoder(buff)\n\terr = decoder.Decode(basicHook)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tlogin := basicHook.Repository.Owner.GetLogin()\n\trepo := basicHook.Repository.Name\n\n\tfmt.Fprintf(w, \"%s\/%s\", login, repo)\n\n\tif repo == \"\" || login == \"\" {\n\t\thttp.Error(w, \"Failed parsing JSON HTTP Body\", http.StatusBadRequest)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\thook := HookExec{\n\t\tRootDir: h.RootDir,\n\n\t\tOwner: login,\n\t\tRepo:  repo,\n\n\t\tEvent: ghEvent,\n\t\tData:  buff,\n\n\t\tHookServer: h,\n\t}\n\n\tgo hook.Exec(h.Timeout)\n}\n\n\/\/ HookUserJSON exists because some hooks use Login, some use Name\n\/\/ - it's horribly inconsistant\ntype HookUserJSON struct {\n\tLogin string `json:\"login\"`\n\tName  string `json:\"name\"`\n}\n\n\/\/ GetLogin is used to get the login from the data github decided to pass today\nfunc (h *HookUserJSON) GetLogin() string {\n\tif h.Login != \"\" {\n\t\treturn h.Login\n\t}\n\n\treturn h.Name\n}\n\n\/\/ HookJSON represents the minimum body we need to parse\ntype HookJSON struct {\n\tRepository struct {\n\t\tName  string       `json:\"name\"`\n\t\tOwner HookUserJSON `json:\"owner\"`\n\t} `json:\"repository\"`\n\tSender HookUserJSON `json:\"sender\"`\n}\n<commit_msg>Corrects spelling<commit_after>package hookah\n\nimport (\n\t\"bytes\"\n\t\"crypto\/hmac\"\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar errsNotDir = errors.New(\"Given path is not a dir\")\nvar validGhEvent = regexp.MustCompile(`^[a-z_]{1,30}$`)\n\n\/\/ HookServer implements net\/http.Handler\ntype HookServer struct {\n\tRootDir string\n\tTimeout time.Duration\n\tsecret  string\n\tsync.Mutex\n}\n\n\/\/ NewHookServer instantiates a new HookServer with some basic validation\n\/\/ on the root directory\nfunc NewHookServer(rootdir, secret string, timeout time.Duration) (*HookServer, error) {\n\tf, err := os.Open(rootdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !fi.IsDir() {\n\t\treturn nil, errsNotDir\n\t}\n\n\treturn &HookServer{\n\t\tRootDir: rootdir,\n\t\tTimeout: timeout,\n\t\tsecret:  secret,\n\t}, nil\n}\n\nfunc (h *HookServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tghEvent := r.Header.Get(\"X-Github-Event\")\n\n\tif !validGhEvent.MatchString(ghEvent) {\n\t\thttp.Error(w, \"Request requires valid X-Github-Event\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif ghEvent == \"ping\" {\n\t\tfmt.Fprintln(w, \"pong\")\n\t\treturn\n\t}\n\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tbuff := bytes.NewReader(b)\n\n\tif h.secret != \"\" {\n\t\txSig := r.Header.Get(\"X-Hub-Signature\")\n\n\t\tif xSig == \"\" {\n\t\t\thttp.Error(w, \"Missing required X-Hub-Signature for HMAC verification\", http.StatusForbidden)\n\t\t\tlog.Println(\"missing X-Hub-Signature\")\n\t\t\treturn\n\t\t}\n\n\t\thash := hmac.New(sha1.New, []byte(h.secret))\n\t\thash.Write(b)\n\n\t\tehash := hash.Sum(nil)\n\t\tesig := \"sha1=\" + hex.EncodeToString(ehash)\n\n\t\tif !hmac.Equal([]byte(esig), []byte(xSig)) {\n\t\t\thttp.Error(w, \"HMAC verification failed\", http.StatusForbidden)\n\t\t\tlog.Println(\"HMAC verification failed\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tbasicHook := &HookJSON{}\n\n\tdecoder := json.NewDecoder(buff)\n\terr = decoder.Decode(basicHook)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tlogin := basicHook.Repository.Owner.GetLogin()\n\trepo := basicHook.Repository.Name\n\n\tfmt.Fprintf(w, \"%s\/%s\", login, repo)\n\n\tif repo == \"\" || login == \"\" {\n\t\thttp.Error(w, \"Failed parsing JSON HTTP Body\", http.StatusBadRequest)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\thook := HookExec{\n\t\tRootDir: h.RootDir,\n\n\t\tOwner: login,\n\t\tRepo:  repo,\n\n\t\tEvent: ghEvent,\n\t\tData:  buff,\n\n\t\tHookServer: h,\n\t}\n\n\tgo hook.Exec(h.Timeout)\n}\n\n\/\/ HookUserJSON exists because some hooks use Login, some use Name\n\/\/ - it's horribly inconsistent\ntype HookUserJSON struct {\n\tLogin string `json:\"login\"`\n\tName  string `json:\"name\"`\n}\n\n\/\/ GetLogin is used to get the login from the data github decided to pass today\nfunc (h *HookUserJSON) GetLogin() string {\n\tif h.Login != \"\" {\n\t\treturn h.Login\n\t}\n\n\treturn h.Name\n}\n\n\/\/ HookJSON represents the minimum body we need to parse\ntype HookJSON struct {\n\tRepository struct {\n\t\tName  string       `json:\"name\"`\n\t\tOwner HookUserJSON `json:\"owner\"`\n\t} `json:\"repository\"`\n\tSender HookUserJSON `json:\"sender\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n)\n\nvar (\n\t\/\/ cfg is the global configuration for the server. It's read in at startup from\n\t\/\/ the config.json file and enviornment variables, see config.go for more info.\n\tcfg *config\n\t\/\/ log output\n\tlogger = log.New(os.Stderr, \"\", log.Ldate|log.Ltime|log.Lshortfile)\n\t\/\/ application database connection\n\tappDB *sql.DB\n)\n\nfunc main() {\n\tvar err error\n\tcfg, err = initConfig(os.Getenv(\"GOLANG_ENV\"))\n\tif err != nil {\n\t\t\/\/ panic if the server is missing a vital configuration detail\n\t\tpanic(fmt.Errorf(\"server configuration error: %s\", err.Error()))\n\t}\n\n\tconnectToAppDb()\n\n\ts := &http.Server{}\n\tm := http.NewServeMux()\n\n\tm.HandleFunc(\"\/\", NotFoundHandler)\n\tm.Handle(\"\/status\", middleware(HealthCheckHandler))\n\tm.HandleFunc(\"\/.well-known\/acme-challenge\/\", CertbotHandler)\n\n\t\/\/ m.Handle(\"\/v0\/users\", middleware(UserHandler))\n\t\/\/ m.Handle(\"\/v0\/users\/\", middleware(UsersHandler))\n\tm.Handle(\"\/v0\/primers\", middleware(PrimersHandler))\n\tm.Handle(\"\/v0\/primers\/\", middleware(PrimerHandler))\n\tm.Handle(\"\/v0\/sources\", middleware(SourcesHandler))\n\tm.Handle(\"\/v0\/sources\/\", middleware(SourceHandler))\n\tm.Handle(\"\/v0\/urls\", middleware(UrlsHandler))\n\tm.Handle(\"\/v0\/urls\/\", middleware(UrlHandler))\n\t\/\/ m.Handle(\"\/v0\/links\", middleware(UrlHandler))\n\t\/\/ m.Handle(\"\/v0\/links\/\", middleware(UrlsHandler))\n\t\/\/ m.Handle(\"\/v0\/snapshots\", middleware())\n\t\/\/ m.Handle(\"\/v0\/snapshots\/\", middleware())\n\t\/\/ m.Handle(\"\/v0\/content\", middleware())\n\t\/\/ m.Handle(\"\/v0\/content\/\", middleware())\n\t\/\/ m.Handle(\"\/v0\/metadata\", middleware())\n\t\/\/ m.Handle(\"\/v0\/metadata\/\", middleware())\n\t\/\/ m.Handle(\"\/v0\/consensus\", middleware())\n\t\/\/ m.Handle(\"\/v0\/consensus\/\", middleware())\n\t\/\/ m.Handle(\"\/v0\/collections\", middleware())\n\t\/\/ m.Handle(\"\/v0\/collections\/\", middleware())\n\n\t\/\/ connect mux to server\n\ts.Handler = m\n\n\t\/\/ print notable config settings\n\tprintConfigInfo()\n\n\t\/\/ fire it up!\n\tfmt.Println(\"starting server on port\", cfg.Port)\n\n\t\/\/ start server wrapped in a log.Fatal b\/c http.ListenAndServe will not\n\t\/\/ return unless there's an error\n\tlogger.Fatal(StartServer(cfg, s))\n}\n<commit_msg>safety commit<commit_after>package main\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n)\n\nvar (\n\t\/\/ cfg is the global configuration for the server. It's read in at startup from\n\t\/\/ the config.json file and enviornment variables, see config.go for more info.\n\tcfg *config\n\t\/\/ log output\n\tlogger = log.New(os.Stderr, \"\", log.Ldate|log.Ltime|log.Lshortfile)\n\t\/\/ application database connection\n\tappDB *sql.DB\n)\n\nfunc main() {\n\tvar err error\n\tcfg, err = initConfig(os.Getenv(\"GOLANG_ENV\"))\n\tif err != nil {\n\t\t\/\/ panic if the server is missing a vital configuration detail\n\t\tpanic(fmt.Errorf(\"server configuration error: %s\", err.Error()))\n\t}\n\n\tconnectToAppDb()\n\n\ts := &http.Server{}\n\tm := http.NewServeMux()\n\n\tm.HandleFunc(\"\/\", NotFoundHandler)\n\tm.Handle(\"\/status\", middleware(HealthCheckHandler))\n\tm.HandleFunc(\"\/.well-known\/acme-challenge\/\", CertbotHandler)\n\n\t\/\/ m.Handle(\"\/v0\/users\", middleware(UserHandler))\n\t\/\/ m.Handle(\"\/v0\/users\/\", middleware(UsersHandler))\n\tm.Handle(\"\/v0\/primers\", middleware(PrimersHandler))\n\tm.Handle(\"\/v0\/primers\/\", middleware(PrimerHandler))\n\tm.Handle(\"\/v0\/sources\", middleware(SourcesHandler))\n\tm.Handle(\"\/v0\/sources\/\", middleware(SourceHandler))\n\tm.Handle(\"\/v0\/urls\", middleware(UrlsHandler))\n\tm.Handle(\"\/v0\/urls\/\", middleware(UrlHandler))\n\n\t\/\/ m.Handle(\"\/v0\/links\", middleware(UrlHandler))\n\t\/\/ m.Handle(\"\/v0\/links\/\", middleware(UrlsHandler))\n\t\/\/ m.Handle(\"\/v0\/snapshots\", middleware())\n\t\/\/ m.Handle(\"\/v0\/snapshots\/\", middleware())\n\t\/\/ m.Handle(\"\/v0\/content\", middleware())\n\t\/\/ m.Handle(\"\/v0\/content\/\", middleware())\n\t\/\/ m.Handle(\"\/v0\/metadata\", middleware())\n\t\/\/ m.Handle(\"\/v0\/metadata\/\", middleware())\n\t\/\/ m.Handle(\"\/v0\/consensus\", middleware())\n\t\/\/ m.Handle(\"\/v0\/consensus\/\", middleware())\n\t\/\/ m.Handle(\"\/v0\/collections\", middleware())\n\t\/\/ m.Handle(\"\/v0\/collections\/\", middleware())\n\n\t\/\/ connect mux to server\n\ts.Handler = m\n\n\t\/\/ print notable config settings\n\tprintConfigInfo()\n\n\t\/\/ fire it up!\n\tfmt.Println(\"starting server on port\", cfg.Port)\n\n\t\/\/ start server wrapped in a log.Fatal b\/c http.ListenAndServe will not\n\t\/\/ return unless there's an error\n\tlogger.Fatal(StartServer(cfg, s))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package mannersagain combines manners and goagain to provide graceful hot\n\/\/ restarting of net\/http servers.\npackage mannersagain\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/braintree\/manners\"\n\t\"github.com\/titanous\/goagain\"\n)\n\nfunc newListener(l net.Listener) net.Listener {\n\treturn listener{Listener: l, closed: make(chan struct{})}\n}\n\ntype listener struct {\n\tnet.Listener\n\tclosed chan struct{}\n}\n\nvar ErrClosed = errors.New(\"mannersagain: listener has been gracefully closed\")\n\nfunc (l listener) Accept() (net.Conn, error) {\n\tfor {\n\t\tselect {\n\t\tcase <-l.closed:\n\t\t\treturn nil, ErrClosed\n\t\tdefault:\n\t\t}\n\n\t\t\/\/ Set a deadline so Accept doesn't block forever, which gives\n\t\t\/\/ us an opportunity to stop gracefully.\n\t\tl.Listener.(*net.TCPListener).SetDeadline(time.Now().Add(100 * time.Millisecond))\n\t\tc, err := l.Listener.Accept()\n\t\tif opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {\n\t\t\tcontinue\n\t\t}\n\t\treturn c, err\n\t}\n}\n\nfunc (l listener) Close() error {\n\tclose(l.closed)\n\treturn nil\n}\n\nfunc ListenAndServe(addr string, handler http.Handler) error {\n\tvar gl *manners.GracefulListener\n\tsrv := manners.NewServer()\n\n\tdone := make(chan struct{})\n\tserve := func(l net.Listener) {\n\t\tsrv.Serve(l, handler)\n\t\tclose(done)\n\t}\n\n\t\/\/ Attempt to inherit a listener from our parent\n\tl, err := goagain.Listener()\n\tif err != nil {\n\t\t\/\/ We don't have an inherited listener, create a new one\n\t\tl, err = net.Listen(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"Listening on\", l.Addr())\n\t\tgl = manners.NewListener(newListener(l), srv)\n\t\tgo serve(gl)\n\t} else {\n\t\tlog.Println(\"Resuming listening on\", l.Addr())\n\t\tgl = manners.NewListener(newListener(l), srv)\n\t\tgo serve(gl)\n\n\t\tif err := goagain.Kill(); nil != err {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Block the main goroutine awaiting signals.\n\tsig, err := goagain.Wait(l)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Wait returns one of SIGINT, SIGTERM, SIGQUIT, SIGUSR2\n\t\/\/ We should stop gracefully if we receive one of the second two\n\tif sig != goagain.SIGINT && sig != goagain.SIGTERM {\n\t\t\/\/ Stop accepting new connections\n\t\tgl.Close()\n\t\t\/\/ Wait for all existing connections to complete\n\t\t<-done\n\t}\n\n\tif goagain.Strategy == goagain.Double && sig == goagain.SIGUSR2 {\n\t\t\/\/ If we received SIGUSR2, re-exec the parent process.\n\t\tif err := goagain.Exec(l); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ We were told to exit, so do it!\n\tos.Exit(0)\n\treturn nil\n}\n<commit_msg>Use fork of manners to fix WaitGroup multiple decrement<commit_after>\/\/ Package mannersagain combines manners and goagain to provide graceful hot\n\/\/ restarting of net\/http servers.\npackage mannersagain\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/titanous\/goagain\"\n\t\"github.com\/titanous\/manners\"\n)\n\nfunc newListener(l net.Listener) net.Listener {\n\treturn listener{Listener: l, closed: make(chan struct{})}\n}\n\ntype listener struct {\n\tnet.Listener\n\tclosed chan struct{}\n}\n\nvar ErrClosed = errors.New(\"mannersagain: listener has been gracefully closed\")\n\nfunc (l listener) Accept() (net.Conn, error) {\n\tfor {\n\t\tselect {\n\t\tcase <-l.closed:\n\t\t\treturn nil, ErrClosed\n\t\tdefault:\n\t\t}\n\n\t\t\/\/ Set a deadline so Accept doesn't block forever, which gives\n\t\t\/\/ us an opportunity to stop gracefully.\n\t\tl.Listener.(*net.TCPListener).SetDeadline(time.Now().Add(100 * time.Millisecond))\n\t\tc, err := l.Listener.Accept()\n\t\tif opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {\n\t\t\tcontinue\n\t\t}\n\t\treturn c, err\n\t}\n}\n\nfunc (l listener) Close() error {\n\tclose(l.closed)\n\treturn nil\n}\n\nfunc ListenAndServe(addr string, handler http.Handler) error {\n\tvar gl *manners.GracefulListener\n\tsrv := manners.NewServer()\n\n\tdone := make(chan struct{})\n\tserve := func(l net.Listener) {\n\t\tsrv.Serve(l, handler)\n\t\tclose(done)\n\t}\n\n\t\/\/ Attempt to inherit a listener from our parent\n\tl, err := goagain.Listener()\n\tif err != nil {\n\t\t\/\/ We don't have an inherited listener, create a new one\n\t\tl, err = net.Listen(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Println(\"Listening on\", l.Addr())\n\t\tgl = manners.NewListener(newListener(l), srv)\n\t\tgo serve(gl)\n\t} else {\n\t\tlog.Println(\"Resuming listening on\", l.Addr())\n\t\tgl = manners.NewListener(newListener(l), srv)\n\t\tgo serve(gl)\n\n\t\tif err := goagain.Kill(); nil != err {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Block the main goroutine awaiting signals.\n\tsig, err := goagain.Wait(l)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Wait returns one of SIGINT, SIGTERM, SIGQUIT, SIGUSR2\n\t\/\/ We should stop gracefully if we receive one of the second two\n\tif sig != goagain.SIGINT && sig != goagain.SIGTERM {\n\t\t\/\/ Stop accepting new connections\n\t\tgl.Close()\n\t\t\/\/ Wait for all existing connections to complete\n\t\t<-done\n\t}\n\n\tif goagain.Strategy == goagain.Double && sig == goagain.SIGUSR2 {\n\t\t\/\/ If we received SIGUSR2, re-exec the parent process.\n\t\tif err := goagain.Exec(l); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ We were told to exit, so do it!\n\tos.Exit(0)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package datahub\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strconv\"\n\n\t\"github.com\/NeowayLabs\/datahub\/company\"\n\t\"github.com\/NeowayLabs\/datahub\/scientists\"\n\t\"github.com\/julienschmidt\/httprouter\"\n)\n\n\/\/ Server ...\ntype Server struct {\n\trouter     *httprouter.Router\n\tdatadir    string\n\tlog        *log.Logger\n\tcompany    *company.Company\n\tscientists *scientists.Scientists\n}\n\n\/\/ NewServer ...\nfunc NewServer() *Server {\n\tconst datadir string = \".\/.repo\"\n\tlog := log.New(os.Stdout, \"datahub.server\", log.Lshortfile|log.Lmicroseconds)\n\terr := os.MkdirAll(datadir, 0755)\n\tif err != nil {\n\t\tlog.Fatalf(\"error %q creating data dir %q\", err, datadir)\n\t}\n\n\trouter := httprouter.New()\n\tcompany := company.NewCompany()\n\tscientists := scientists.NewScientists()\n\n\td := &Server{\n\t\trouter:     router,\n\t\tdatadir:    datadir,\n\t\tlog:        log,\n\t\tcompany:    company,\n\t\tscientists: scientists,\n\t}\n\n\trouter.GET(\"\/api\/companies\/jobs\", d.companiesGetJobs)\n\n\trouter.POST(\"\/api\/companies\/jobs\", d.companiesCreateJob)\n\trouter.GET(\"\/api\/companies\/jobs\/:id\", d.companiesGetJob)\n\trouter.POST(\"\/api\/companies\/job\/:id\/upload\", d.companiesUploadJob)\n\trouter.POST(\"\/api\/companies\/jobs\/:id\/start\", d.companiesStartJob)\n\n\trouter.GET(\"\/api\/scientists\", d.scientistsList)\n\n\trouter.GET(\"\/api\/scientists\/:id\/jobs\", d.scientistsGetJobs)\n\trouter.POST(\"\/api\/scientists\/:id\/jobs\/:job\/apply\", d.scientistsApplyJob)\n\trouter.GET(\"\/api\/scientists\/:id\/jobs\/:job\/workspace\", d.scientistsGetWorkspace)\n\trouter.POST(\"\/api\/scientists\/:id\/jobs\/:job\/upload\", d.companiesUploadCode)\n\n\trouter.POST(\"\/api\/execR\", d.execR)\n\n\treturn d\n}\n\nfunc (d *Server) companiesUploadJob(w http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tuploadFileNames := []string{\n\t\t\"code.r\",\n\t\t\"trainingset.csv\",\n\t\t\"testset.challenge.csv\",\n\t\t\"testset.result.csv\",\n\t}\n\n\tjobID := params.ByName(\"id\")\n\n\tsuccess := false\n\tfor _, filename := range uploadFileNames {\n\t\tres := d.receiveUpload(req, filename, jobID)\n\t\tif res {\n\t\t\tsuccess = res\n\t\t}\n\t}\n\tif !success {\n\t\td.failrequest(\n\t\t\tw,\n\t\t\t\"no dataset received, expected one of these: %q\",\n\t\t\tuploadFileNames,\n\t\t)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n}\n\n\/\/ Jobs ...\ntype Jobs struct {\n\tPending []*company.Job `json:\"pending\"`\n\tDoing   []*company.Job `json:\"doing\"`\n\tDone    []*company.Job `json:\"done\"`\n}\n\nfunc (d *Server) companiesGetJobs(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tdefer func() {\n\t\tif err := req.Body.Close(); err != nil {\n\t\t\td.log.Printf(\"body close: error %q\", err)\n\t\t}\n\t}()\n\n\tscientists := d.scientists.GetScientists()\n\n\tbytes, err := json.Marshal(scientists)\n\tif err != nil {\n\t\td.log.Printf(\"marshal: error %q\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tif _, err := w.Write(bytes); err != nil {\n\t\td.log.Printf(\"write: error %q\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n}\n\nfunc (d *Server) companiesCreateJob(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tdefer func() {\n\t\tif err := req.Body.Close(); err != nil {\n\t\t\td.log.Printf(\"body close: error %q\", err)\n\t\t}\n\t}()\n\n\tdecoder := json.NewDecoder(req.Body)\n\n\tvar job company.Job\n\tif err := decoder.Decode(&job); err != nil {\n\t\td.log.Printf(\"unmarshal: error %q\", err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\td.company.AddNewJob(&job)\n\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc getID(params httprouter.Params) (int, error) {\n\ts := params.ByName(\"id\")\n\tif s == \"\" {\n\t\treturn 0, fmt.Errorf(\"param: id is empty\")\n\t}\n\n\tid, err := strconv.Atoi(s)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"param: id is not a number\")\n\t}\n\n\treturn id, nil\n}\n\nfunc (d *Server) companiesGetJob(w http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tdefer func() {\n\t\tif err := req.Body.Close(); err != nil {\n\t\t\td.log.Printf(\"body close: error %q\", err)\n\t\t}\n\t}()\n\n\tid, err := getID(params)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tjob := d.company.GetJob(id)\n\tif job == nil {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tbytes, err := json.Marshal(job)\n\tif err != nil {\n\t\td.log.Printf(\"marshal: error %q\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tif _, err := w.Write(bytes); err != nil {\n\t\td.log.Printf(\"write: error %q\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n}\n\nfunc (d *Server) companiesStartJob(w http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tdefer func() {\n\t\tif err := req.Body.Close(); err != nil {\n\t\t\td.log.Printf(\"body close: error %q\", err)\n\t\t}\n\t}()\n\n\ttype Scientists struct {\n\t\tScientists []*company.Scientist `json:\"scientists\"`\n\t}\n\n\tjob, err := getID(params)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdecoder := json.NewDecoder(req.Body)\n\n\tvar scientists Scientists\n\tif err := decoder.Decode(&scientists); err != nil {\n\t\td.log.Printf(\"unmarshal: error %q\", err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := d.company.StartJob(job, scientists.Scientists); err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc (d *Server) scientistsList(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tdefer func() {\n\t\tif err := req.Body.Close(); err != nil {\n\t\t\td.log.Printf(\"body close: error %q\", err)\n\t\t}\n\t}()\n\n\tw.WriteHeader(http.StatusNotImplemented)\n}\n\nfunc (d *Server) scientistsGetJobs(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\t\/\/TODO\n\tw.WriteHeader(http.StatusNotImplemented)\n}\n\nfunc (d *Server) scientistsApplyJob(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\t\/\/TODO\n\tw.WriteHeader(http.StatusNotImplemented)\n}\n\nfunc (d *Server) scientistsGetWorkspace(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\t\/\/TODO\n\tw.WriteHeader(http.StatusNotImplemented)\n}\n\nfunc (d *Server) companiesUploadCode(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\t\/\/TODO\n\tw.WriteHeader(http.StatusNotImplemented)\n}\n\nfunc (d *Server) execR(\n\tw http.ResponseWriter,\n\treq *http.Request,\n\t_ httprouter.Params,\n) {\n\t\/\/ TODO: Still not getting stderr\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\td.failrequest(w, \"getwd: unexpected error %q\", err)\n\t\treturn\n\t}\n\terr = os.Chdir(cwd + \"\/\" + d.datadir)\n\tif err != nil {\n\t\td.failrequest(w, \"chdir: unexpected error %q\", err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err := os.Chdir(cwd); err != nil {\n\t\t\td.log.Printf(\"chdir: unexpected error %q\", err)\n\t\t}\n\t}()\n\n\tcmd := exec.Command(\"R\", \"-f\", \".\/code.r\")\n\td.log.Printf(\"executing R code\")\n\tres, err := cmd.CombinedOutput()\n\n\tif err != nil {\n\t\td.failrequest(w, \"exec R: unexpected error %q\", err)\n\t\treturn\n\t}\n\td.log.Printf(\"executed R code with success\")\n\n\tw.WriteHeader(http.StatusOK)\n\t_, err = w.Write(res)\n\tif err != nil {\n\t\td.log.Printf(\"unexpected error %q sending response\", err)\n\t\treturn\n\t}\n}\n\nfunc (d *Server) receiveUpload(\n\treq *http.Request,\n\tfilename string,\n\tjobID string,\n) bool {\n\tuploadedfile, _, err := req.FormFile(filename)\n\tif err != nil {\n\t\td.log.Printf(\"%q parsing form\", err)\n\t\treturn false\n\t}\n\n\tdefer func() {\n\t\tif err := uploadedfile.Close(); err != nil {\n\t\t\td.log.Printf(\"close: unexpected error %q\", err)\n\t\t}\n\t}()\n\n\tfilepath := d.datadir + \"\/\" + filename\n\td.log.Printf(\"creating file %q\", filepath)\n\tfile, err := os.Create(filepath)\n\tif err != nil {\n\t\td.log.Printf(\"error: %q opening file %q\", err, filepath)\n\t\treturn false\n\t}\n\td.log.Printf(\"created file with success, copying contents\")\n\t_, err = io.Copy(file, uploadedfile)\n\tif err != nil {\n\t\td.log.Printf(\"error: %q copying file\", err)\n\t\treturn false\n\t}\n\td.log.Printf(\"finished copying from form %q with success\", filename)\n\treturn true\n}\n\nfunc (d *Server) failrequest(\n\tw http.ResponseWriter,\n\tfmt string,\n\targs ...interface{},\n) {\n\td.log.Printf(fmt, args...)\n\tw.WriteHeader(http.StatusInternalServerError)\n}\n\n\/\/ Handler ...\nfunc (d *Server) Handler() http.Handler {\n\treturn d.router\n}\n\n\/\/ ListenAndServe ...\nfunc (d *Server) ListenAndServe(addr string) error {\n\td.log.Printf(\"WebServer running at %q\", addr)\n\treturn http.ListenAndServe(addr, d.router)\n}\n<commit_msg>Fixed GetCompanyJobs<commit_after>package datahub\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strconv\"\n\n\t\"github.com\/NeowayLabs\/datahub\/company\"\n\t\"github.com\/NeowayLabs\/datahub\/scientists\"\n\t\"github.com\/julienschmidt\/httprouter\"\n)\n\n\/\/ Server ...\ntype Server struct {\n\trouter     *httprouter.Router\n\tdatadir    string\n\tlog        *log.Logger\n\tcompany    *company.Company\n\tscientists *scientists.Scientists\n}\n\n\/\/ NewServer ...\nfunc NewServer() *Server {\n\tconst datadir string = \".\/.repo\"\n\tlog := log.New(os.Stdout, \"datahub.server\", log.Lshortfile|log.Lmicroseconds)\n\terr := os.MkdirAll(datadir, 0755)\n\tif err != nil {\n\t\tlog.Fatalf(\"error %q creating data dir %q\", err, datadir)\n\t}\n\n\trouter := httprouter.New()\n\tcompany := company.NewCompany()\n\tscientists := scientists.NewScientists()\n\n\td := &Server{\n\t\trouter:     router,\n\t\tdatadir:    datadir,\n\t\tlog:        log,\n\t\tcompany:    company,\n\t\tscientists: scientists,\n\t}\n\n\trouter.GET(\"\/api\/companies\/jobs\", d.companiesGetJobs)\n\n\trouter.POST(\"\/api\/companies\/jobs\", d.companiesCreateJob)\n\trouter.GET(\"\/api\/companies\/jobs\/:id\", d.companiesGetJob)\n\trouter.POST(\"\/api\/companies\/job\/:id\/upload\", d.companiesUploadJob)\n\trouter.POST(\"\/api\/companies\/jobs\/:id\/start\", d.companiesStartJob)\n\n\trouter.GET(\"\/api\/scientists\", d.scientistsList)\n\n\trouter.GET(\"\/api\/scientists\/:id\/jobs\", d.scientistsGetJobs)\n\trouter.POST(\"\/api\/scientists\/:id\/jobs\/:job\/apply\", d.scientistsApplyJob)\n\trouter.GET(\"\/api\/scientists\/:id\/jobs\/:job\/workspace\", d.scientistsGetWorkspace)\n\trouter.POST(\"\/api\/scientists\/:id\/jobs\/:job\/upload\", d.companiesUploadCode)\n\n\trouter.POST(\"\/api\/execR\", d.execR)\n\n\treturn d\n}\n\nfunc (d *Server) companiesUploadJob(w http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tuploadFileNames := []string{\n\t\t\"code.r\",\n\t\t\"trainingset.csv\",\n\t\t\"testset.challenge.csv\",\n\t\t\"testset.result.csv\",\n\t}\n\n\tjobID := params.ByName(\"id\")\n\n\tsuccess := false\n\tfor _, filename := range uploadFileNames {\n\t\tres := d.receiveUpload(req, filename, jobID)\n\t\tif res {\n\t\t\tsuccess = res\n\t\t}\n\t}\n\tif !success {\n\t\td.failrequest(\n\t\t\tw,\n\t\t\t\"no dataset received, expected one of these: %q\",\n\t\t\tuploadFileNames,\n\t\t)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n}\n\n\/\/ Jobs ...\ntype Jobs struct {\n\tPending []*company.Job `json:\"pending\"`\n\tDoing   []*company.Job `json:\"doing\"`\n\tDone    []*company.Job `json:\"done\"`\n}\n\nfunc (d *Server) companiesGetJobs(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tdefer func() {\n\t\tif err := req.Body.Close(); err != nil {\n\t\t\td.log.Printf(\"body close: error %q\", err)\n\t\t}\n\t}()\n\n\tpending := d.company.GetJobsByStatus(\"pending\")\n\tdoing := d.company.GetJobsByStatus(\"doing\")\n\tdone := d.company.GetJobsByStatus(\"done\")\n\n\tjobs := &Jobs{\n\t\tPending: pending,\n\t\tDoing:   doing,\n\t\tDone:    done,\n\t}\n\n\tbytes, err := json.Marshal(jobs)\n\tif err != nil {\n\t\td.log.Printf(\"marshal: error %q\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tif _, err := w.Write(bytes); err != nil {\n\t\td.log.Printf(\"write: error %q\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n}\n\nfunc (d *Server) companiesCreateJob(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tdefer func() {\n\t\tif err := req.Body.Close(); err != nil {\n\t\t\td.log.Printf(\"body close: error %q\", err)\n\t\t}\n\t}()\n\n\tdecoder := json.NewDecoder(req.Body)\n\n\tvar job company.Job\n\tif err := decoder.Decode(&job); err != nil {\n\t\td.log.Printf(\"unmarshal: error %q\", err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\td.company.AddNewJob(&job)\n\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc getID(params httprouter.Params) (int, error) {\n\ts := params.ByName(\"id\")\n\tif s == \"\" {\n\t\treturn 0, fmt.Errorf(\"param: id is empty\")\n\t}\n\n\tid, err := strconv.Atoi(s)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"param: id is not a number\")\n\t}\n\n\treturn id, nil\n}\n\nfunc (d *Server) companiesGetJob(w http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tdefer func() {\n\t\tif err := req.Body.Close(); err != nil {\n\t\t\td.log.Printf(\"body close: error %q\", err)\n\t\t}\n\t}()\n\n\tid, err := getID(params)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tjob := d.company.GetJob(id)\n\tif job == nil {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tbytes, err := json.Marshal(job)\n\tif err != nil {\n\t\td.log.Printf(\"marshal: error %q\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tif _, err := w.Write(bytes); err != nil {\n\t\td.log.Printf(\"write: error %q\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n}\n\nfunc (d *Server) companiesStartJob(w http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tdefer func() {\n\t\tif err := req.Body.Close(); err != nil {\n\t\t\td.log.Printf(\"body close: error %q\", err)\n\t\t}\n\t}()\n\n\ttype Scientists struct {\n\t\tScientists []*company.Scientist `json:\"scientists\"`\n\t}\n\n\tjob, err := getID(params)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdecoder := json.NewDecoder(req.Body)\n\n\tvar scientists Scientists\n\tif err := decoder.Decode(&scientists); err != nil {\n\t\td.log.Printf(\"unmarshal: error %q\", err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err := d.company.StartJob(job, scientists.Scientists); err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc (d *Server) scientistsList(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tdefer func() {\n\t\tif err := req.Body.Close(); err != nil {\n\t\t\td.log.Printf(\"body close: error %q\", err)\n\t\t}\n\t}()\n\n\tscientists := d.scientists.GetScientists()\n\n\tbytes, err := json.Marshal(scientists)\n\tif err != nil {\n\t\td.log.Printf(\"marshal: error %q\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tif _, err := w.Write(bytes); err != nil {\n\t\td.log.Printf(\"write: error %q\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n}\n\nfunc (d *Server) scientistsGetJobs(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\t\/\/TODO\n\tw.WriteHeader(http.StatusNotImplemented)\n}\n\nfunc (d *Server) scientistsApplyJob(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\t\/\/TODO\n\tw.WriteHeader(http.StatusNotImplemented)\n}\n\nfunc (d *Server) scientistsGetWorkspace(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\t\/\/TODO\n\tw.WriteHeader(http.StatusNotImplemented)\n}\n\nfunc (d *Server) companiesUploadCode(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {\n\t\/\/TODO\n\tw.WriteHeader(http.StatusNotImplemented)\n}\n\nfunc (d *Server) execR(\n\tw http.ResponseWriter,\n\treq *http.Request,\n\t_ httprouter.Params,\n) {\n\t\/\/ TODO: Still not getting stderr\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\td.failrequest(w, \"getwd: unexpected error %q\", err)\n\t\treturn\n\t}\n\terr = os.Chdir(cwd + \"\/\" + d.datadir)\n\tif err != nil {\n\t\td.failrequest(w, \"chdir: unexpected error %q\", err)\n\t\treturn\n\t}\n\tdefer func() {\n\t\tif err := os.Chdir(cwd); err != nil {\n\t\t\td.log.Printf(\"chdir: unexpected error %q\", err)\n\t\t}\n\t}()\n\n\tcmd := exec.Command(\"R\", \"-f\", \".\/code.r\")\n\td.log.Printf(\"executing R code\")\n\tres, err := cmd.CombinedOutput()\n\n\tif err != nil {\n\t\td.failrequest(w, \"exec R: unexpected error %q\", err)\n\t\treturn\n\t}\n\td.log.Printf(\"executed R code with success\")\n\n\tw.WriteHeader(http.StatusOK)\n\t_, err = w.Write(res)\n\tif err != nil {\n\t\td.log.Printf(\"unexpected error %q sending response\", err)\n\t\treturn\n\t}\n}\n\nfunc (d *Server) receiveUpload(\n\treq *http.Request,\n\tfilename string,\n\tjobID string,\n) bool {\n\tuploadedfile, _, err := req.FormFile(filename)\n\tif err != nil {\n\t\td.log.Printf(\"%q parsing form\", err)\n\t\treturn false\n\t}\n\n\tdefer func() {\n\t\tif err := uploadedfile.Close(); err != nil {\n\t\t\td.log.Printf(\"close: unexpected error %q\", err)\n\t\t}\n\t}()\n\n\tfilepath := d.datadir + \"\/\" + filename\n\td.log.Printf(\"creating file %q\", filepath)\n\tfile, err := os.Create(filepath)\n\tif err != nil {\n\t\td.log.Printf(\"error: %q opening file %q\", err, filepath)\n\t\treturn false\n\t}\n\td.log.Printf(\"created file with success, copying contents\")\n\t_, err = io.Copy(file, uploadedfile)\n\tif err != nil {\n\t\td.log.Printf(\"error: %q copying file\", err)\n\t\treturn false\n\t}\n\td.log.Printf(\"finished copying from form %q with success\", filename)\n\treturn true\n}\n\nfunc (d *Server) failrequest(\n\tw http.ResponseWriter,\n\tfmt string,\n\targs ...interface{},\n) {\n\td.log.Printf(fmt, args...)\n\tw.WriteHeader(http.StatusInternalServerError)\n}\n\n\/\/ Handler ...\nfunc (d *Server) Handler() http.Handler {\n\treturn d.router\n}\n\n\/\/ ListenAndServe ...\nfunc (d *Server) ListenAndServe(addr string) error {\n\td.log.Printf(\"WebServer running at %q\", addr)\n\treturn http.ListenAndServe(addr, d.router)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n    \"fmt\"\n    \"regexp\"\n    \"net\/http\"\n) \n\n\/\/ Define HTTP route structure for the server\ntype Route struct {\n    pattern *regexp.Regexp\n    method  string\n    handler http.Handler\n}\n\n\n\n\n<commit_msg>Very small gorilla mux based router + server<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"net\/http\"\n)\n\n\/\/ Main entry point\nfunc main() {\n\trouter := mux.NewRouter()\n\n\t\/\/ Define error'd route handler\n\trouter.NotFoundHandler = http.HandlerFunc(Render404)\n\n\t\/\/ Define various application routes here\n\trouter.HandleFunc(\"\/\", RenderIndex).Methods(\"GET\")\n\n\t\/\/ Use the above router for all routes\n\thttp.Handle(\"\/\", router)\n\n\tfmt.Printf(\"Server up and listening...\")\n\thttp.ListenAndServe(\"0.0.0.0:3000\", nil)\n}\n\n\/\/ Render 4040 page\nfunc Render404(response http.ResponseWriter, request *http.Request) {\n\tresponse.Write([]byte(\"Hmm looks like we 404'd trying to find: \" + request.URL.Path))\n}\n\n\/\/ Render Home page\nfunc RenderIndex(response http.ResponseWriter, request *http.Request) {\n\tresponse.Write([]byte(\"Hello world!\"))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 struktur AG. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage httputils\n\nimport (\n\t\"crypto\/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"syscall\"\n)\n\n\/\/ Provide a HTTP server implementation which can listen on TPC\n\/\/ and Unix Domain sockets.\ntype Server struct {\n\thttp.Server\n\t*log.Logger\n}\n\n\/\/ ListenAndServe binds sockets according to the configuration of srv and blocks\n\/\/ until the socket closes or an exit signal is received.\nfunc (srv *Server) ListenAndServe() error {\n\n\taddr := srv.Addr\n\tif addr == \"\" {\n\t\taddr = \":http\"\n\t}\n\n\tvar closing = false\n\tvar err error\n\tvar l net.Listener\n\tif l, err = srv.socketListen(addr); err != nil {\n\t\treturn err\n\t}\n\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, os.Interrupt, syscall.SIGTERM)\n\tgo func() {\n\t\ts := <-sig\n\t\tmsg := \"Received exit signal %d - Closing ...\"\n\t\tif srv.Logger != nil {\n\t\t\tsrv.Logger.Printf(msg, s)\n\t\t} else {\n\t\t\tlog.Printf(msg, s)\n\t\t}\n\t\tclosing = true\n\t\tl.Close()\n\t}()\n\n\terr = srv.Serve(l)\n\tif err != nil {\n\t\tif closing {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n\n}\n\n\/\/ ListenAndServeTLS binds sockets according to the configuration of srv and blocks\n\/\/ until the socket closes or an exit signal is received.\nfunc (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {\n\n\taddr := srv.Addr\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tconfig := &tls.Config{}\n\tif srv.TLSConfig != nil {\n\t\t*config = *srv.TLSConfig\n\t}\n\tif config.NextProtos == nil {\n\t\tconfig.NextProtos = []string{\"http\/1.1\"}\n\t}\n\n\tvar err error\n\tconfig.Certificates = make([]tls.Certificate, 1)\n\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar closing = false\n\tvar l net.Listener\n\tif l, err = srv.socketListen(addr); err != nil {\n\t\treturn err\n\t}\n\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, os.Interrupt, syscall.SIGTERM)\n\tgo func() {\n\t\ts := <-sig\n\t\tmsg := \"Received exit signal %d - Closing ...\"\n\t\tif srv.Logger != nil {\n\t\t\tsrv.Logger.Printf(msg, s)\n\t\t} else {\n\t\t\tlog.Printf(msg, s)\n\t\t}\n\t\tclosing = true\n\t\tl.Close()\n\t}()\n\n\ttlsListener := tls.NewListener(l, config)\n\n\terr = srv.Serve(tlsListener)\n\tif err != nil {\n\t\tif closing {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n\n}\n\n\/\/ ListenAndServeTLSAdvanced binds sockets according to the configuration\n\/\/ of srv and blocks until the socket closes or an exit signal is received. A\n\/\/ TLSConfig needs to be available at the server.\nfunc (srv *Server) ListenAndServeTLSAdvanced() error {\n\n\taddr := srv.Addr\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tconfig := srv.TLSConfig\n\n\tif config == nil {\n\t\treturn errors.New(\"TLSConfig required\")\n\t}\n\tif config.NextProtos == nil {\n\t\tconfig.NextProtos = []string{\"http\/1.1\"}\n\t}\n\n\tif len(config.Certificates) == 0 {\n\t\treturn errors.New(\"TLSConfig has no certificate\")\n\t}\n\n\tvar err error\n\tvar closing = false\n\tvar l net.Listener\n\tif l, err = srv.socketListen(addr); err != nil {\n\t\treturn err\n\t}\n\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, os.Interrupt, syscall.SIGTERM)\n\tgo func() {\n\t\ts := <-sig\n\t\tmsg := \"Received exit signal %d - Closing ...\"\n\t\tif srv.Logger != nil {\n\t\t\tsrv.Logger.Printf(msg, s)\n\t\t} else {\n\t\t\tlog.Printf(msg, s)\n\t\t}\n\t\tclosing = true\n\t\tl.Close()\n\t}()\n\n\ttlsListener := tls.NewListener(l, config)\n\n\terr = srv.Serve(tlsListener)\n\tif err != nil {\n\t\tif closing {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n\n}\n\nfunc (srv *Server) socketListen(addr string) (net.Listener, error) {\n\n\tvar err error\n\tvar l net.Listener\n\n\tif strings.HasPrefix(addr, \"\/\") {\n\t\tvar laddr *net.UnixAddr\n\t\tif laddr, err = net.ResolveUnixAddr(\"unix\", addr); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif l, err = createUnixSocket(laddr); err != nil {\n\t\t\t\/\/ Unix-domain-socket already exists, try to connect to it to\n\t\t\t\/\/ see if it still is usedb by another process\n\t\t\tif _, err = net.Dial(\"unix\", addr); err != nil {\n\t\t\t\tif err = os.Remove(addr); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif l, err = createUnixSocket(laddr); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"another process seems to be listening on %s already\", addr)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tvar laddr *net.TCPAddr\n\t\tif laddr, err = net.ResolveTCPAddr(\"tcp\", addr); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif l, err = net.ListenTCP(\"tcp\", laddr); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn l, nil\n\n}\n\nfunc createUnixSocket(addr *net.UnixAddr) (l net.Listener, err error) {\n\tl, err = net.ListenUnix(\"unix\", addr)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ TODO(lcooper): Not sure if this sequence is completely safe.\n\t\/\/ It would be better if we could get the underlying FD of the socket\n\t\/\/ and stat() + chmod() that instead.\n\tfi, err := os.Stat(addr.String())\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ NOTE(lcooper): This only ensures g+w other then on Linux,\n\t\/\/ BSD systems only use parent directory permissions.\n\t\/\/ See http:\/\/stackoverflow.com\/questions\/5977556 .\n\terr = os.Chmod(addr.String(), fi.Mode()|0060)\n\treturn\n}\n<commit_msg>Removed duplicated code.<commit_after>\/\/ Copyright 2014 struktur AG. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage httputils\n\nimport (\n\t\"crypto\/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"syscall\"\n)\n\n\/\/ Provide a HTTP server implementation which can listen on TPC\n\/\/ and Unix Domain sockets.\ntype Server struct {\n\thttp.Server\n\t*log.Logger\n}\n\n\/\/ ListenAndServe binds sockets according to the configuration of srv and blocks\n\/\/ until the socket closes or an exit signal is received.\nfunc (srv *Server) ListenAndServe() error {\n\n\taddr := srv.Addr\n\tif addr == \"\" {\n\t\taddr = \":http\"\n\t}\n\n\tvar closing = false\n\tvar err error\n\tvar l net.Listener\n\tif l, err = srv.socketListen(addr); err != nil {\n\t\treturn err\n\t}\n\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, os.Interrupt, syscall.SIGTERM)\n\tgo func() {\n\t\ts := <-sig\n\t\tmsg := \"Received exit signal %d - Closing ...\"\n\t\tif srv.Logger != nil {\n\t\t\tsrv.Logger.Printf(msg, s)\n\t\t} else {\n\t\t\tlog.Printf(msg, s)\n\t\t}\n\t\tclosing = true\n\t\tl.Close()\n\t}()\n\n\terr = srv.Serve(l)\n\tif err != nil {\n\t\tif closing {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n\n}\n\n\/\/ ListenAndServeTLS binds sockets according to the configuration of srv and blocks\n\/\/ until the socket closes or an exit signal is received.\nfunc (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {\n\n\tconfig := &tls.Config{}\n\tif srv.TLSConfig != nil {\n\t\t*config = *srv.TLSConfig\n\t}\n\t\n\tvar err error\n\tconfig.Certificates = make([]tls.Certificate, 1)\n\tconfig.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n    return srv.ListenAndServeTLSWithConfig(config)\n\n}\n\n\/\/ ListenAndServeTLSAdvanced binds sockets according to the configuration\n\/\/ of srv and blocks until the socket closes or an exit signal is received. A\n\/\/ TLSConfig needs to be available at the server.\nfunc (srv *Server) ListenAndServeTLSWithConfig(config *tls.Config) error {\n\n\taddr := srv.Addr\n\tif addr == \"\" {\n\t\taddr = \":https\"\n\t}\n\n\tif config == nil {\n\t\treturn errors.New(\"TLSConfig required\")\n\t}\n\tif config.NextProtos == nil {\n\t\tconfig.NextProtos = []string{\"http\/1.1\"}\n\t}\n\n\tif len(config.Certificates) == 0 {\n\t\treturn errors.New(\"TLSConfig has no certificate\")\n\t}\n\n\tvar err error\n\tvar closing = false\n\tvar l net.Listener\n\tif l, err = srv.socketListen(addr); err != nil {\n\t\treturn err\n\t}\n\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, os.Interrupt, syscall.SIGTERM)\n\tgo func() {\n\t\ts := <-sig\n\t\tmsg := \"Received exit signal %d - Closing ...\"\n\t\tif srv.Logger != nil {\n\t\t\tsrv.Logger.Printf(msg, s)\n\t\t} else {\n\t\t\tlog.Printf(msg, s)\n\t\t}\n\t\tclosing = true\n\t\tl.Close()\n\t}()\n\n\ttlsListener := tls.NewListener(l, config)\n\n\terr = srv.Serve(tlsListener)\n\tif err != nil {\n\t\tif closing {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn err\n\n}\n\nfunc (srv *Server) socketListen(addr string) (net.Listener, error) {\n\n\tvar err error\n\tvar l net.Listener\n\n\tif strings.HasPrefix(addr, \"\/\") {\n\t\tvar laddr *net.UnixAddr\n\t\tif laddr, err = net.ResolveUnixAddr(\"unix\", addr); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif l, err = createUnixSocket(laddr); err != nil {\n\t\t\t\/\/ Unix-domain-socket already exists, try to connect to it to\n\t\t\t\/\/ see if it still is usedb by another process\n\t\t\tif _, err = net.Dial(\"unix\", addr); err != nil {\n\t\t\t\tif err = os.Remove(addr); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tif l, err = createUnixSocket(laddr); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn nil, fmt.Errorf(\"another process seems to be listening on %s already\", addr)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tvar laddr *net.TCPAddr\n\t\tif laddr, err = net.ResolveTCPAddr(\"tcp\", addr); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif l, err = net.ListenTCP(\"tcp\", laddr); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn l, nil\n\n}\n\nfunc createUnixSocket(addr *net.UnixAddr) (l net.Listener, err error) {\n\tl, err = net.ListenUnix(\"unix\", addr)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ TODO(lcooper): Not sure if this sequence is completely safe.\n\t\/\/ It would be better if we could get the underlying FD of the socket\n\t\/\/ and stat() + chmod() that instead.\n\tfi, err := os.Stat(addr.String())\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ NOTE(lcooper): This only ensures g+w other then on Linux,\n\t\/\/ BSD systems only use parent directory permissions.\n\t\/\/ See http:\/\/stackoverflow.com\/questions\/5977556 .\n\terr = os.Chmod(addr.String(), fi.Mode()|0060)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ get show and movie source download links\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/PuerkitoBio\/goquery\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/cookiejar\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype Media struct {\n\tName string\n\tSize string\n\tLink string\n}\n\n\/\/zmz.tv needs to login before downloading\nvar zmzClient http.Client\n\nfunc getMovieFromLBL(movie string, results chan string, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tvar id string\n\tresp, _ := http.Get(\"http:\/\/www.lbldy.com\/search\/\" + movie)\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tre, _ := regexp.Compile(\"<div class=\\\"postlist\\\" id=\\\"post-(.*?)\\\">\")\n\t\/\/find first match case\n\tfirstId := re.FindSubmatch(body)\n\tif len(firstId) == 0 {\n\t\tresults <- fmt.Sprintf(\"No results for *%s* from LBL\", movie)\n\t\treturn\n\t} else {\n\t\tid = string(firstId[1])\n\t\tresp, _ = http.Get(\"http:\/\/www.lbldy.com\/movie\/\" + id + \".html\")\n\t\tdefer resp.Body.Close()\n\t\tre, _ = regexp.Compile(`<p><a href=\"(.*?)\"( target=\"_blank\">|>)(.*?)<\/a><\/p>`)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\t\/\/go does not support (?!) regex\n\t\tbody = []byte(strings.Replace(string(body), `<a href=\"\/xunlei\/\"`, \"\", -1))\n\t\tdownloads := re.FindAllSubmatch(body, -1)\n\t\tif len(downloads) == 0 {\n\t\t\tresults <- fmt.Sprintf(\"No results for *%s* from LBL\", movie)\n\t\t\treturn\n\t\t} else {\n\t\t\tret := \"Results from LBL:\\n\\n\"\n\t\t\tfor i := range downloads {\n\t\t\t\tret += fmt.Sprintf(\"*%s*\\n```%s```\\n\\n\", string(downloads[i][3]), string(downloads[i][1]))\n\t\t\t\t\/\/when results are too large, we split it.\n\t\t\t\tif i%5 == 0 && i > 0 {\n\t\t\t\t\tresults <- ret\n\t\t\t\t\tret = fmt.Sprintf(\"*LBL Part %d*\\n\\n\", i\/5+1)\n\t\t\t\t}\n\t\t\t}\n\t\t\tresults <- ret\n\t\t}\n\t}\n}\n\nfunc getMovieFromZMZ(movie string, results chan string, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tloginZMZ()\n\tif ms := getZMZResource(movie, \"0\", \"0\"); ms == nil {\n\t\tresults <- fmt.Sprintf(\"No results for *%s* from ZMZ\", movie)\n\t\treturn\n\t} else {\n\t\tret := \"Results from ZMZ:\\n\\n\"\n\t\tfor i, m := range ms {\n\t\t\tname := m.Name\n\t\t\tsize := m.Size\n\t\t\tlink := m.Link\n\t\t\tret += fmt.Sprintf(\"*%s*(%s)\\n```%s```\\n\\n\", name, size, link)\n\t\t\tif i%3 == 0 && i > 0 {\n\t\t\t\tresults <- ret\n\t\t\t\tret = fmt.Sprintf(\"*ZMZ Part %d*\\n\\n\", i\/3+1)\n\t\t\t}\n\t\t}\n\t\tresults <- ret\n\t}\n\treturn\n}\n\nfunc getShowFromZMZ(show, s, e string, results chan string) (found bool) {\n\tloginZMZ()\n\tms := getZMZResource(show, s, e)\n\tif ms == nil {\n\t\tresults <- fmt.Sprintf(\"No results found for *S%sE%s*\", s, e)\n\t\treturn false\n\t}\n\tfor _, m := range ms {\n\t\tname := m.Name\n\t\tsize := m.Size\n\t\tlink := m.Link\n\t\tresults <- fmt.Sprintf(\"*ZMZ %s*(%s)\\n```%s```\\n\\n\", name, size, link)\n\t}\n\treturn true\n}\n\n\/\/get show and get movie from zmz both uses this function\nfunc getZMZResource(name, season, episode string) []Media {\n\tid := getZMZResourceId(name)\n\tif id == \"\" {\n\t\treturn nil\n\t}\n\tresourceURL := \"http:\/\/www.zimuzu.tv\/resource\/list\/\" + id\n\tresp, _ := zmzClient.Get(resourceURL)\n\tdefer resp.Body.Close()\n\t\/\/1.name 2.size 3.link\n\tvar ms []Media\n\tdoc, err := goquery.NewDocumentFromReader(io.Reader(resp.Body))\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdoc.Find(\"li.clearfix\").Each(func(i int, selection *goquery.Selection) {\n\t\ts, _ := selection.Attr(\"season\")\n\t\te, _ := selection.Attr(\"episode\")\n\t\tif e != episode || s != season {\n\t\t\treturn\n\t\t}\n\t\tname := selection.Find(\".fl a\").Text()\n\t\tlink, _ := selection.Find(\".fr a\").Attr(\"href\")\n\t\tvar size string\n\t\tif strings.HasPrefix(link, \"ed2k\") || strings.HasPrefix(link, \"magnet\") {\n\t\t\tsize = selection.Find(\".fl font.f3\").Text()\n\t\t\tif size == \"\" || size == \"0\" {\n\t\t\t\tsize = \"unknown_size\"\n\t\t\t}\n\t\t\tm := Media{\n\t\t\t\tName: name,\n\t\t\t\tLink: link,\n\t\t\t\tSize: size,\n\t\t\t}\n\t\t\tms = append(ms, m)\n\t\t}\n\t})\n\treturn ms\n}\n\nfunc getZMZResourceId(name string) (id string) {\n\tqueryURL := fmt.Sprintf(\"http:\/\/www.zimuzu.tv\/search?keyword=%s&type=resource\", name)\n\tre, _ := regexp.Compile(`<div class=\"t f14\"><a href=\"\/resource\/(.*?)\"><strong class=\"list_title\">`)\n\tresp, _ := zmzClient.Get(queryURL)\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\/\/find first match case\n\tfirstId := re.FindSubmatch(body)\n\tif len(firstId) == 0 {\n\t\treturn\n\t} else {\n\t\tlog.Println(id)\n\t\tid = string(firstId[1])\n\t\treturn\n\t}\n}\n\n\/\/login zmz first because zmz don't allow login at different browsers, but I have two robots...\nfunc loginZMZ() {\n\tgCookieJar, _ := cookiejar.New(nil)\n\tzmzURL := \"http:\/\/www.zimuzu.tv\/User\/Login\/ajaxLogin\"\n\tzmzClient = http.Client{\n\t\tJar: gCookieJar,\n\t}\n\t\/\/post with my public account, you can use it also\n\tzmzClient.PostForm(zmzURL, url.Values{\"account\": {\"evol4snow\"}, \"password\": {\"104545\"}, \"remember\": {\"0\"}})\n}\n<commit_msg>echo each one<commit_after>\/\/ get show and movie source download links\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/PuerkitoBio\/goquery\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/cookiejar\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype Media struct {\n\tName string\n\tSize string\n\tLink string\n}\n\n\/\/zmz.tv needs to login before downloading\nvar zmzClient http.Client\n\nfunc getMovieFromLBL(movie string, results chan string, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tvar id string\n\tresp, _ := http.Get(\"http:\/\/www.lbldy.com\/search\/\" + movie)\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tre, _ := regexp.Compile(\"<div class=\\\"postlist\\\" id=\\\"post-(.*?)\\\">\")\n\t\/\/find first match case\n\tfirstId := re.FindSubmatch(body)\n\tif len(firstId) == 0 {\n\t\tresults <- fmt.Sprintf(\"No results for *%s* from LBL\", movie)\n\t\treturn\n\t} else {\n\t\tid = string(firstId[1])\n\t\tresp, _ = http.Get(\"http:\/\/www.lbldy.com\/movie\/\" + id + \".html\")\n\t\tdefer resp.Body.Close()\n\t\tre, _ = regexp.Compile(`<p><a href=\"(.*?)\"( target=\"_blank\">|>)(.*?)<\/a><\/p>`)\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\t\/\/go does not support (?!) regex\n\t\tbody = []byte(strings.Replace(string(body), `<a href=\"\/xunlei\/\"`, \"\", -1))\n\t\tdownloads := re.FindAllSubmatch(body, -1)\n\t\tif len(downloads) == 0 {\n\t\t\tresults <- fmt.Sprintf(\"No results for *%s* from LBL\", movie)\n\t\t\treturn\n\t\t} else {\n\t\t\tret := \"Results from LBL:\\n\\n\"\n\t\t\tfor i := range downloads {\n\t\t\t\tret += fmt.Sprintf(\"*%s*\\n```%s```\\n\\n\", string(downloads[i][3]), string(downloads[i][1]))\n\t\t\t\t\/\/when results are too large, we split it.\n\t\t\t\tif i%5 == 0 && i > 0 {\n\t\t\t\t\tresults <- ret\n\t\t\t\t\tret = fmt.Sprintf(\"*LBL Part %d*\\n\\n\", i\/5+1)\n\t\t\t\t}\n\t\t\t}\n\t\t\tresults <- ret\n\t\t}\n\t}\n}\n\nfunc getMovieFromZMZ(movie string, results chan string, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tloginZMZ()\n\tif ms := getZMZResource(movie, \"0\", \"0\"); ms == nil {\n\t\tresults <- fmt.Sprintf(\"No results for *%s* from ZMZ\", movie)\n\t\treturn\n\t} else {\n\t\tresults <- \"Results from ZMZ:\\n\\n\"\n\t\tfor _, m := range ms {\n\t\t\tname := m.Name\n\t\t\tsize := m.Size\n\t\t\tlink := m.Link\n\t\t\tresults <- fmt.Sprintf(\"*%s*(%s)\\n```%s```\\n\\n\", name, size, link)\n\t\t}\n\t}\n\treturn\n}\n\nfunc getShowFromZMZ(show, s, e string, results chan string) (found bool) {\n\tloginZMZ()\n\tms := getZMZResource(show, s, e)\n\tif ms == nil {\n\t\tresults <- fmt.Sprintf(\"No results found for *S%sE%s*\", s, e)\n\t\treturn false\n\t}\n\tfor _, m := range ms {\n\t\tname := m.Name\n\t\tsize := m.Size\n\t\tlink := m.Link\n\t\tresults <- fmt.Sprintf(\"*ZMZ %s*(%s)\\n```%s```\\n\\n\", name, size, link)\n\t}\n\treturn true\n}\n\n\/\/get show and get movie from zmz both uses this function\nfunc getZMZResource(name, season, episode string) []Media {\n\tid := getZMZResourceId(name)\n\tif id == \"\" {\n\t\treturn nil\n\t}\n\tresourceURL := \"http:\/\/www.zimuzu.tv\/resource\/list\/\" + id\n\tresp, _ := zmzClient.Get(resourceURL)\n\tdefer resp.Body.Close()\n\t\/\/1.name 2.size 3.link\n\tvar ms []Media\n\tdoc, err := goquery.NewDocumentFromReader(io.Reader(resp.Body))\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdoc.Find(\"li.clearfix\").Each(func(i int, selection *goquery.Selection) {\n\t\ts, _ := selection.Attr(\"season\")\n\t\te, _ := selection.Attr(\"episode\")\n\t\tif e != episode || s != season {\n\t\t\treturn\n\t\t}\n\t\tname := selection.Find(\".fl a\").Text()\n\t\tlink, _ := selection.Find(\".fr a\").Attr(\"href\")\n\t\tvar size string\n\t\tif strings.HasPrefix(link, \"ed2k\") || strings.HasPrefix(link, \"magnet\") {\n\t\t\tsize = selection.Find(\".fl font.f3\").Text()\n\t\t\tif size == \"\" || size == \"0\" {\n\t\t\t\tsize = \"unknown_size\"\n\t\t\t}\n\t\t\tm := Media{\n\t\t\t\tName: name,\n\t\t\t\tLink: link,\n\t\t\t\tSize: size,\n\t\t\t}\n\t\t\tms = append(ms, m)\n\t\t}\n\t})\n\treturn ms\n}\n\nfunc getZMZResourceId(name string) (id string) {\n\tqueryURL := fmt.Sprintf(\"http:\/\/www.zimuzu.tv\/search?keyword=%s&type=resource\", name)\n\tre, _ := regexp.Compile(`<div class=\"t f14\"><a href=\"\/resource\/(.*?)\"><strong class=\"list_title\">`)\n\tresp, _ := zmzClient.Get(queryURL)\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\/\/find first match case\n\tfirstId := re.FindSubmatch(body)\n\tif len(firstId) == 0 {\n\t\treturn\n\t} else {\n\t\tlog.Println(id)\n\t\tid = string(firstId[1])\n\t\treturn\n\t}\n}\n\n\/\/login zmz first because zmz don't allow login at different browsers, but I have two robots...\nfunc loginZMZ() {\n\tgCookieJar, _ := cookiejar.New(nil)\n\tzmzURL := \"http:\/\/www.zimuzu.tv\/User\/Login\/ajaxLogin\"\n\tzmzClient = http.Client{\n\t\tJar: gCookieJar,\n\t}\n\t\/\/post with my public account, you can use it also\n\tzmzClient.PostForm(zmzURL, url.Values{\"account\": {\"evol4snow\"}, \"password\": {\"104545\"}, \"remember\": {\"0\"}})\n}\n<|endoftext|>"}
{"text":"<commit_before>package stripe\n\nimport (\n\t\"encoding\/json\"\n\n\t\"github.com\/stripe\/stripe-go\/form\"\n)\n\n\/\/ SourceCodeVerificationFlowStatus represents the possible statuses of a code verification flow.\ntype SourceCodeVerificationFlowStatus string\n\n\/\/ List of values that SourceCodeVerificationFlowStatus can take.\nconst (\n\tSourceCodeVerificationFlowStatusFailed    SourceCodeVerificationFlowStatus = \"failed\"\n\tSourceCodeVerificationFlowStatusPending   SourceCodeVerificationFlowStatus = \"pending\"\n\tSourceCodeVerificationFlowStatusSucceeded SourceCodeVerificationFlowStatus = \"succeeded\"\n)\n\n\/\/ SourceFlow represents the possible flows of a source object.\ntype SourceFlow string\n\n\/\/ List of values that SourceFlow can take.\nconst (\n\tSourceFlowCodeVerification SourceFlow = \"code_verification\"\n\tSourceFlowNone             SourceFlow = \"none\"\n\tSourceFlowReceiver         SourceFlow = \"receiver\"\n\tSourceFlowRedirect         SourceFlow = \"redirect\"\n)\n\n\/\/ SourceMandateAcceptanceStatus represents the possible failure reasons of a redirect flow.\ntype SourceMandateAcceptanceStatus string\n\n\/\/ List of values that SourceMandateAcceptanceStatus can take.\nconst (\n\tSourceMandateAcceptanceStatusAccepted SourceMandateAcceptanceStatus = \"accepted\"\n\tSourceMandateAcceptanceStatusRefused  SourceMandateAcceptanceStatus = \"refused\"\n)\n\n\/\/ SourceMandateNotificationMethod represents the possible methods of notification for a mandate.\ntype SourceMandateNotificationMethod string\n\n\/\/ List of values that SourceMandateNotificationMethod can take.\nconst (\n\tSourceMandateNotificationMethodEmail  SourceMandateNotificationMethod = \"email\"\n\tSourceMandateNotificationMethodManual SourceMandateNotificationMethod = \"manual\"\n\tSourceMandateNotificationMethodNone   SourceMandateNotificationMethod = \"none\"\n)\n\n\/\/ SourceSourceOrderItemType describes the type of source order items on source\n\/\/ orders for sources.\ntype SourceSourceOrderItemType string\n\n\/\/ The list of possible values for source order item types.\nconst (\n\tSourceSourceOrderItemTypeDiscount SourceSourceOrderItemType = \"discount\"\n\tSourceSourceOrderItemTypeSKU      SourceSourceOrderItemType = \"sku\"\n\tSourceSourceOrderItemTypeShipping SourceSourceOrderItemType = \"shipping\"\n\tSourceSourceOrderItemTypeTax      SourceSourceOrderItemType = \"tax\"\n)\n\n\/\/ SourceRedirectFlowFailureReason represents the possible failure reasons of a redirect flow.\ntype SourceRedirectFlowFailureReason string\n\n\/\/ List of values that SourceRedirectFlowFailureReason can take.\nconst (\n\tSourceRedirectFlowFailureReasonDeclined        SourceRedirectFlowFailureReason = \"declined\"\n\tSourceRedirectFlowFailureReasonProcessingError SourceRedirectFlowFailureReason = \"processing_error\"\n\tSourceRedirectFlowFailureReasonUserAbort       SourceRedirectFlowFailureReason = \"user_abort\"\n)\n\n\/\/ SourceRedirectFlowStatus represents the possible statuses of a redirect flow.\ntype SourceRedirectFlowStatus string\n\n\/\/ List of values that SourceRedirectFlowStatus can take.\nconst (\n\tSourceRedirectFlowStatusFailed      SourceRedirectFlowStatus = \"failed\"\n\tSourceRedirectFlowStatusNotRequired SourceRedirectFlowStatus = \"not_required\"\n\tSourceRedirectFlowStatusPending     SourceRedirectFlowStatus = \"pending\"\n\tSourceRedirectFlowStatusSucceeded   SourceRedirectFlowStatus = \"succeeded\"\n)\n\n\/\/ SourceRefundAttributesMethod are the possible method to retrieve a receiver's refund attributes.\ntype SourceRefundAttributesMethod string\n\n\/\/ List of values that SourceRefundAttributesMethod can take.\nconst (\n\tSourceRefundAttributesMethodEmail  SourceRefundAttributesMethod = \"email\"\n\tSourceRefundAttributesMethodManual SourceRefundAttributesMethod = \"manual\"\n)\n\n\/\/ SourceRefundAttributesStatus are the possible status of a receiver's refund attributes.\ntype SourceRefundAttributesStatus string\n\n\/\/ List of values that SourceRefundAttributesStatus can take.\nconst (\n\tSourceRefundAttributesStatusAvailable SourceRefundAttributesStatus = \"available\"\n\tSourceRefundAttributesStatusMissing   SourceRefundAttributesStatus = \"missing\"\n\tSourceRefundAttributesStatusRequested SourceRefundAttributesStatus = \"requested\"\n)\n\n\/\/ SourceStatus represents the possible statuses of a source object.\ntype SourceStatus string\n\n\/\/ List of values that SourceStatus can take.\nconst (\n\tSourceStatusCanceled   SourceStatus = \"canceled\"\n\tSourceStatusChargeable SourceStatus = \"chargeable\"\n\tSourceStatusConsumed   SourceStatus = \"consumed\"\n\tSourceStatusFailed     SourceStatus = \"failed\"\n\tSourceStatusPending    SourceStatus = \"pending\"\n)\n\n\/\/ SourceUsage represents the possible usages of a source object.\ntype SourceUsage string\n\n\/\/ List of values that SourceUsage can take.\nconst (\n\tSourceUsageReusable  SourceUsage = \"reusable\"\n\tSourceUsageSingleUse SourceUsage = \"single_use\"\n)\n\n\/\/ SourceOwnerParams is the set of parameters allowed for the owner hash on\n\/\/ source creation or update.\ntype SourceOwnerParams struct {\n\tAddress *AddressParams `form:\"address\"`\n\tEmail   *string        `form:\"email\"`\n\tName    *string        `form:\"name\"`\n\tPhone   *string        `form:\"phone\"`\n}\n\n\/\/ RedirectParams is the set of parameters allowed for the redirect hash on\n\/\/ source creation or update.\ntype RedirectParams struct {\n\tReturnURL *string `form:\"return_url\"`\n}\n\n\/\/ SourceOrderItemsParams is the set of parameters allowed for the items on a\n\/\/ source order for a source.\ntype SourceOrderItemsParams struct {\n\tAmount      *int64  `form:\"amount\"`\n\tCurrency    *string `form:\"currency\"`\n\tDescription *string `form:\"description\"`\n\tParent      *string `form:\"parent\"`\n\tQuantity    *int64  `form:\"quantity\"`\n\tType        *string `form:\"type\"`\n}\n\n\/\/ SourceOrderParams is the set of parameters allowed for the source order of a\n\/\/ source.\ntype SourceOrderParams struct {\n\tItems    []*SourceOrderItemsParams `form:\"items\"`\n\tShipping *ShippingDetailsParams    `form:\"shipping\"`\n}\n\n\/\/ SourceObjectParams is the set of parameters allowed on source creation or update.\ntype SourceObjectParams struct {\n\tParams              `form:\"*\"`\n\tAmount              *int64                `form:\"amount\"`\n\tCurrency            *string               `form:\"currency\"`\n\tCustomer            *string               `form:\"customer\"`\n\tFlow                *string               `form:\"flow\"`\n\tMandate             *SourceMandateParams  `form:\"mandate\"`\n\tOriginalSource      *string               `form:\"original_source\"`\n\tOwner               *SourceOwnerParams    `form:\"owner\"`\n\tReceiver            *SourceReceiverParams `form:\"receiver\"`\n\tRedirect            *RedirectParams       `form:\"redirect\"`\n\tSourceOrder         *SourceOrderParams    `form:\"source_order\"`\n\tStatementDescriptor *string               `form:\"statement_descriptor\"`\n\tToken               *string               `form:\"token\"`\n\tType                *string               `form:\"type\"`\n\tTypeData            map[string]string     `form:\"-\"`\n\tUsage               *string               `form:\"usage\"`\n}\n\n\/\/ SourceMandateAcceptanceParams describes the set of parameters allowed for the `acceptance`\n\/\/ hash on source creation or update.\ntype SourceMandateAcceptanceParams struct {\n\tDate      *int64                                `form:\"date\"`\n\tIP        *string                               `form:\"ip\"`\n\tOffline   *SourceMandateAcceptanceOfflineParams `form:\"offline\"`\n\tOnline    *SourceMandateAcceptanceOnlineParams  `form:\"online\"`\n\tStatus    *string                               `form:\"status\"`\n\tType      *string                               `form:\"type\"`\n\tUserAgent *string                               `form:\"user_agent\"`\n}\n\ntype SourceMandateAcceptanceOnlineParams struct {\n\tDate      *int64  `form:\"date\"`\n\tIP        *string `form:\"ip\"`\n\tUserAgent *string `form:\"user_agent\"`\n}\n\ntype SourceMandateAcceptanceOfflineParams struct {\n\tContactEmail *string `form:\"contact_email\"`\n}\n\n\/\/ SourceMandateParams describes the set of parameters allowed for the `mandate` hash on\n\/\/ source creation or update.\ntype SourceMandateParams struct {\n\tAmount             *int64                         `form:\"amount\"`\n\tAcceptance         *SourceMandateAcceptanceParams `form:\"acceptance\"`\n\tCurrency           *string                        `form:\"currency\"`\n\tInterval           *string                        `form:\"interval\"`\n\tNotificationMethod *string                        `form:\"notification_method\"`\n}\n\n\/\/ SourceReceiverParams is the set of parameters allowed for the `receiver` hash on\n\/\/ source creation or update.\ntype SourceReceiverParams struct {\n\tRefundAttributesMethod *string `form:\"refund_attributes_method\"`\n}\n\n\/\/ SourceObjectDetachParams is the set of parameters that can be used when detaching\n\/\/ a source from a customer.\ntype SourceObjectDetachParams struct {\n\tParams   `form:\"*\"`\n\tCustomer *string `form:\"-\"`\n}\n\n\/\/ SourceOwner describes the owner hash on a source.\ntype SourceOwner struct {\n\tAddress         *Address `json:\"address,omitempty\"`\n\tEmail           string   `json:\"email\"`\n\tName            string   `json:\"name\"`\n\tPhone           string   `json:\"phone\"`\n\tVerifiedAddress *Address `json:\"verified_address,omitempty\"`\n\tVerifiedEmail   string   `json:\"verified_email\"`\n\tVerifiedName    string   `json:\"verified_name\"`\n\tVerifiedPhone   string   `json:\"verified_phone\"`\n}\n\n\/\/ RedirectFlow informs of the state of a redirect authentication flow.\ntype RedirectFlow struct {\n\tFailureReason SourceRedirectFlowFailureReason `json:\"failure_reason\"`\n\tReturnURL     string                          `json:\"return_url\"`\n\tStatus        SourceRedirectFlowStatus        `json:\"status\"`\n\tURL           string                          `json:\"url\"`\n}\n\n\/\/ ReceiverFlow informs of the state of a receiver authentication flow.\ntype ReceiverFlow struct {\n\tAddress                string                       `json:\"address\"`\n\tAmountCharged          int64                        `json:\"amount_charged\"`\n\tAmountReceived         int64                        `json:\"amount_received\"`\n\tAmountReturned         int64                        `json:\"amount_returned\"`\n\tRefundAttributesMethod SourceRefundAttributesMethod `json:\"refund_attributes_method\"`\n\tRefundAttributesStatus SourceRefundAttributesStatus `json:\"refund_attributes_status\"`\n}\n\n\/\/ CodeVerificationFlow informs of the state of a verification authentication flow.\ntype CodeVerificationFlow struct {\n\tAttemptsRemaining int64                            `json:\"attempts_remaining\"`\n\tStatus            SourceCodeVerificationFlowStatus `json:\"status\"`\n}\n\n\/\/ SourceMandateAcceptance describes a source mandate acceptance state.\ntype SourceMandateAcceptance struct {\n\tDate      int64                         `json:\"date\"`\n\tIP        string                        `json:\"ip\"`\n\tStatus    SourceMandateAcceptanceStatus `json:\"status\"`\n\tUserAgent string                        `json:\"user_agent\"`\n}\n\n\/\/ SourceMandate describes a source mandate.\ntype SourceMandate struct {\n\tAcceptance         *SourceMandateAcceptance        `json:\"acceptance\"`\n\tNotificationMethod SourceMandateNotificationMethod `json:\"notification_method\"`\n\tReference          string                          `json:\"reference\"`\n\tURL                string                          `json:\"url\"`\n}\n\n\/\/ SourceSourceOrderItems describes the items on source orders for sources.\ntype SourceSourceOrderItems struct {\n\tAmount      int64                     `json:\"amount\"`\n\tCurrency    Currency                  `json:\"currency\"`\n\tDescription string                    `json:\"description\"`\n\tQuantity    int64                     `json:\"quantity\"`\n\tType        SourceSourceOrderItemType `json:\"type\"`\n}\n\n\/\/ SourceSourceOrder describes a source order for a source.\ntype SourceSourceOrder struct {\n\tAmount   int64                   `json:\"amount\"`\n\tCurrency Currency                `json:\"currency\"`\n\tEmail    string                  `json:\"email\"`\n\tItems    *SourceSourceOrderItems `json:\"items\"`\n\tShipping *ShippingDetails        `json:\"shipping\"`\n}\n\n\/\/ Source is the resource representing a Source.\n\/\/ For more details see https:\/\/stripe.com\/docs\/api#sources.\ntype Source struct {\n\tAmount              int64                 `json:\"amount\"`\n\tClientSecret        string                `json:\"client_secret\"`\n\tCodeVerification    *CodeVerificationFlow `json:\"code_verification,omitempty\"`\n\tCreated             int64                 `json:\"created\"`\n\tCurrency            Currency              `json:\"currency\"`\n\tCustomer            string                `json:\"customer\"`\n\tFlow                SourceFlow            `json:\"flow\"`\n\tID                  string                `json:\"id\"`\n\tLivemode            bool                  `json:\"livemode\"`\n\tMandate             *SourceMandate        `json:\"mandate\"`\n\tMetadata            map[string]string     `json:\"metadata\"`\n\tOwner               *SourceOwner          `json:\"owner\"`\n\tReceiver            *ReceiverFlow         `json:\"receiver,omitempty\"`\n\tRedirect            *RedirectFlow         `json:\"redirect,omitempty\"`\n\tStatementDescriptor string                `json:\"statement_descriptor\"`\n\tSourceOrder         *SourceSourceOrder    `json:\"source_order\"`\n\tStatus              SourceStatus          `json:\"status\"`\n\tType                string                `json:\"type\"`\n\tTypeData            map[string]interface{}\n\tUsage               SourceUsage `json:\"usage\"`\n}\n\n\/\/ AppendTo implements custom encoding logic for SourceObjectParams so that the special\n\/\/ \"TypeData\" value for is sent as the correct parameter based on the Source type\nfunc (p *SourceObjectParams) AppendTo(body *form.Values, keyParts []string) {\n\tif len(p.TypeData) > 0 && p.Type == nil {\n\t\tpanic(\"You can not fill TypeData if you don't explicitly set Type\")\n\t}\n\n\tfor k, vs := range p.TypeData {\n\t\tbody.Add(form.FormatKey(append(keyParts, StringValue(p.Type), k)), vs)\n\t}\n}\n\n\/\/ UnmarshalJSON handles deserialization of an Source. This custom unmarshaling\n\/\/ is needed to extract the type specific data (accessible under `TypeData`)\n\/\/ but stored in JSON under a hash named after the `type` of the source.\nfunc (s *Source) UnmarshalJSON(data []byte) error {\n\ttype source Source\n\tvar v source\n\tif err := json.Unmarshal(data, &v); err != nil {\n\t\treturn err\n\t}\n\t*s = Source(v)\n\n\tvar raw map[string]interface{}\n\tif err := json.Unmarshal(data, &raw); err != nil {\n\t\treturn err\n\t}\n\n\tif d, ok := raw[s.Type]; ok {\n\t\tif m, ok := d.(map[string]interface{}); ok {\n\t\t\ts.TypeData = m\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>Fix linting error<commit_after>package stripe\n\nimport (\n\t\"encoding\/json\"\n\n\t\"github.com\/stripe\/stripe-go\/form\"\n)\n\n\/\/ SourceCodeVerificationFlowStatus represents the possible statuses of a code verification flow.\ntype SourceCodeVerificationFlowStatus string\n\n\/\/ List of values that SourceCodeVerificationFlowStatus can take.\nconst (\n\tSourceCodeVerificationFlowStatusFailed    SourceCodeVerificationFlowStatus = \"failed\"\n\tSourceCodeVerificationFlowStatusPending   SourceCodeVerificationFlowStatus = \"pending\"\n\tSourceCodeVerificationFlowStatusSucceeded SourceCodeVerificationFlowStatus = \"succeeded\"\n)\n\n\/\/ SourceFlow represents the possible flows of a source object.\ntype SourceFlow string\n\n\/\/ List of values that SourceFlow can take.\nconst (\n\tSourceFlowCodeVerification SourceFlow = \"code_verification\"\n\tSourceFlowNone             SourceFlow = \"none\"\n\tSourceFlowReceiver         SourceFlow = \"receiver\"\n\tSourceFlowRedirect         SourceFlow = \"redirect\"\n)\n\n\/\/ SourceMandateAcceptanceStatus represents the possible failure reasons of a redirect flow.\ntype SourceMandateAcceptanceStatus string\n\n\/\/ List of values that SourceMandateAcceptanceStatus can take.\nconst (\n\tSourceMandateAcceptanceStatusAccepted SourceMandateAcceptanceStatus = \"accepted\"\n\tSourceMandateAcceptanceStatusRefused  SourceMandateAcceptanceStatus = \"refused\"\n)\n\n\/\/ SourceMandateNotificationMethod represents the possible methods of notification for a mandate.\ntype SourceMandateNotificationMethod string\n\n\/\/ List of values that SourceMandateNotificationMethod can take.\nconst (\n\tSourceMandateNotificationMethodEmail  SourceMandateNotificationMethod = \"email\"\n\tSourceMandateNotificationMethodManual SourceMandateNotificationMethod = \"manual\"\n\tSourceMandateNotificationMethodNone   SourceMandateNotificationMethod = \"none\"\n)\n\n\/\/ SourceSourceOrderItemType describes the type of source order items on source\n\/\/ orders for sources.\ntype SourceSourceOrderItemType string\n\n\/\/ The list of possible values for source order item types.\nconst (\n\tSourceSourceOrderItemTypeDiscount SourceSourceOrderItemType = \"discount\"\n\tSourceSourceOrderItemTypeSKU      SourceSourceOrderItemType = \"sku\"\n\tSourceSourceOrderItemTypeShipping SourceSourceOrderItemType = \"shipping\"\n\tSourceSourceOrderItemTypeTax      SourceSourceOrderItemType = \"tax\"\n)\n\n\/\/ SourceRedirectFlowFailureReason represents the possible failure reasons of a redirect flow.\ntype SourceRedirectFlowFailureReason string\n\n\/\/ List of values that SourceRedirectFlowFailureReason can take.\nconst (\n\tSourceRedirectFlowFailureReasonDeclined        SourceRedirectFlowFailureReason = \"declined\"\n\tSourceRedirectFlowFailureReasonProcessingError SourceRedirectFlowFailureReason = \"processing_error\"\n\tSourceRedirectFlowFailureReasonUserAbort       SourceRedirectFlowFailureReason = \"user_abort\"\n)\n\n\/\/ SourceRedirectFlowStatus represents the possible statuses of a redirect flow.\ntype SourceRedirectFlowStatus string\n\n\/\/ List of values that SourceRedirectFlowStatus can take.\nconst (\n\tSourceRedirectFlowStatusFailed      SourceRedirectFlowStatus = \"failed\"\n\tSourceRedirectFlowStatusNotRequired SourceRedirectFlowStatus = \"not_required\"\n\tSourceRedirectFlowStatusPending     SourceRedirectFlowStatus = \"pending\"\n\tSourceRedirectFlowStatusSucceeded   SourceRedirectFlowStatus = \"succeeded\"\n)\n\n\/\/ SourceRefundAttributesMethod are the possible method to retrieve a receiver's refund attributes.\ntype SourceRefundAttributesMethod string\n\n\/\/ List of values that SourceRefundAttributesMethod can take.\nconst (\n\tSourceRefundAttributesMethodEmail  SourceRefundAttributesMethod = \"email\"\n\tSourceRefundAttributesMethodManual SourceRefundAttributesMethod = \"manual\"\n)\n\n\/\/ SourceRefundAttributesStatus are the possible status of a receiver's refund attributes.\ntype SourceRefundAttributesStatus string\n\n\/\/ List of values that SourceRefundAttributesStatus can take.\nconst (\n\tSourceRefundAttributesStatusAvailable SourceRefundAttributesStatus = \"available\"\n\tSourceRefundAttributesStatusMissing   SourceRefundAttributesStatus = \"missing\"\n\tSourceRefundAttributesStatusRequested SourceRefundAttributesStatus = \"requested\"\n)\n\n\/\/ SourceStatus represents the possible statuses of a source object.\ntype SourceStatus string\n\n\/\/ List of values that SourceStatus can take.\nconst (\n\tSourceStatusCanceled   SourceStatus = \"canceled\"\n\tSourceStatusChargeable SourceStatus = \"chargeable\"\n\tSourceStatusConsumed   SourceStatus = \"consumed\"\n\tSourceStatusFailed     SourceStatus = \"failed\"\n\tSourceStatusPending    SourceStatus = \"pending\"\n)\n\n\/\/ SourceUsage represents the possible usages of a source object.\ntype SourceUsage string\n\n\/\/ List of values that SourceUsage can take.\nconst (\n\tSourceUsageReusable  SourceUsage = \"reusable\"\n\tSourceUsageSingleUse SourceUsage = \"single_use\"\n)\n\n\/\/ SourceOwnerParams is the set of parameters allowed for the owner hash on\n\/\/ source creation or update.\ntype SourceOwnerParams struct {\n\tAddress *AddressParams `form:\"address\"`\n\tEmail   *string        `form:\"email\"`\n\tName    *string        `form:\"name\"`\n\tPhone   *string        `form:\"phone\"`\n}\n\n\/\/ RedirectParams is the set of parameters allowed for the redirect hash on\n\/\/ source creation or update.\ntype RedirectParams struct {\n\tReturnURL *string `form:\"return_url\"`\n}\n\n\/\/ SourceOrderItemsParams is the set of parameters allowed for the items on a\n\/\/ source order for a source.\ntype SourceOrderItemsParams struct {\n\tAmount      *int64  `form:\"amount\"`\n\tCurrency    *string `form:\"currency\"`\n\tDescription *string `form:\"description\"`\n\tParent      *string `form:\"parent\"`\n\tQuantity    *int64  `form:\"quantity\"`\n\tType        *string `form:\"type\"`\n}\n\n\/\/ SourceOrderParams is the set of parameters allowed for the source order of a\n\/\/ source.\ntype SourceOrderParams struct {\n\tItems    []*SourceOrderItemsParams `form:\"items\"`\n\tShipping *ShippingDetailsParams    `form:\"shipping\"`\n}\n\n\/\/ SourceObjectParams is the set of parameters allowed on source creation or update.\ntype SourceObjectParams struct {\n\tParams              `form:\"*\"`\n\tAmount              *int64                `form:\"amount\"`\n\tCurrency            *string               `form:\"currency\"`\n\tCustomer            *string               `form:\"customer\"`\n\tFlow                *string               `form:\"flow\"`\n\tMandate             *SourceMandateParams  `form:\"mandate\"`\n\tOriginalSource      *string               `form:\"original_source\"`\n\tOwner               *SourceOwnerParams    `form:\"owner\"`\n\tReceiver            *SourceReceiverParams `form:\"receiver\"`\n\tRedirect            *RedirectParams       `form:\"redirect\"`\n\tSourceOrder         *SourceOrderParams    `form:\"source_order\"`\n\tStatementDescriptor *string               `form:\"statement_descriptor\"`\n\tToken               *string               `form:\"token\"`\n\tType                *string               `form:\"type\"`\n\tTypeData            map[string]string     `form:\"-\"`\n\tUsage               *string               `form:\"usage\"`\n}\n\n\/\/ SourceMandateAcceptanceParams describes the set of parameters allowed for the `acceptance`\n\/\/ hash on source creation or update.\ntype SourceMandateAcceptanceParams struct {\n\tDate      *int64                                `form:\"date\"`\n\tIP        *string                               `form:\"ip\"`\n\tOffline   *SourceMandateAcceptanceOfflineParams `form:\"offline\"`\n\tOnline    *SourceMandateAcceptanceOnlineParams  `form:\"online\"`\n\tStatus    *string                               `form:\"status\"`\n\tType      *string                               `form:\"type\"`\n\tUserAgent *string                               `form:\"user_agent\"`\n}\n\n\/\/ SourceMandateAcceptanceOnlineParams describes the set of parameters for online accepted mandate\ntype SourceMandateAcceptanceOnlineParams struct {\n\tDate      *int64  `form:\"date\"`\n\tIP        *string `form:\"ip\"`\n\tUserAgent *string `form:\"user_agent\"`\n}\n\n\/\/ SourceMandateAcceptanceOfflineParams describes the set of parameters for offline accepted mandate\ntype SourceMandateAcceptanceOfflineParams struct {\n\tContactEmail *string `form:\"contact_email\"`\n}\n\n\/\/ SourceMandateParams describes the set of parameters allowed for the `mandate` hash on\n\/\/ source creation or update.\ntype SourceMandateParams struct {\n\tAmount             *int64                         `form:\"amount\"`\n\tAcceptance         *SourceMandateAcceptanceParams `form:\"acceptance\"`\n\tCurrency           *string                        `form:\"currency\"`\n\tInterval           *string                        `form:\"interval\"`\n\tNotificationMethod *string                        `form:\"notification_method\"`\n}\n\n\/\/ SourceReceiverParams is the set of parameters allowed for the `receiver` hash on\n\/\/ source creation or update.\ntype SourceReceiverParams struct {\n\tRefundAttributesMethod *string `form:\"refund_attributes_method\"`\n}\n\n\/\/ SourceObjectDetachParams is the set of parameters that can be used when detaching\n\/\/ a source from a customer.\ntype SourceObjectDetachParams struct {\n\tParams   `form:\"*\"`\n\tCustomer *string `form:\"-\"`\n}\n\n\/\/ SourceOwner describes the owner hash on a source.\ntype SourceOwner struct {\n\tAddress         *Address `json:\"address,omitempty\"`\n\tEmail           string   `json:\"email\"`\n\tName            string   `json:\"name\"`\n\tPhone           string   `json:\"phone\"`\n\tVerifiedAddress *Address `json:\"verified_address,omitempty\"`\n\tVerifiedEmail   string   `json:\"verified_email\"`\n\tVerifiedName    string   `json:\"verified_name\"`\n\tVerifiedPhone   string   `json:\"verified_phone\"`\n}\n\n\/\/ RedirectFlow informs of the state of a redirect authentication flow.\ntype RedirectFlow struct {\n\tFailureReason SourceRedirectFlowFailureReason `json:\"failure_reason\"`\n\tReturnURL     string                          `json:\"return_url\"`\n\tStatus        SourceRedirectFlowStatus        `json:\"status\"`\n\tURL           string                          `json:\"url\"`\n}\n\n\/\/ ReceiverFlow informs of the state of a receiver authentication flow.\ntype ReceiverFlow struct {\n\tAddress                string                       `json:\"address\"`\n\tAmountCharged          int64                        `json:\"amount_charged\"`\n\tAmountReceived         int64                        `json:\"amount_received\"`\n\tAmountReturned         int64                        `json:\"amount_returned\"`\n\tRefundAttributesMethod SourceRefundAttributesMethod `json:\"refund_attributes_method\"`\n\tRefundAttributesStatus SourceRefundAttributesStatus `json:\"refund_attributes_status\"`\n}\n\n\/\/ CodeVerificationFlow informs of the state of a verification authentication flow.\ntype CodeVerificationFlow struct {\n\tAttemptsRemaining int64                            `json:\"attempts_remaining\"`\n\tStatus            SourceCodeVerificationFlowStatus `json:\"status\"`\n}\n\n\/\/ SourceMandateAcceptance describes a source mandate acceptance state.\ntype SourceMandateAcceptance struct {\n\tDate      int64                         `json:\"date\"`\n\tIP        string                        `json:\"ip\"`\n\tStatus    SourceMandateAcceptanceStatus `json:\"status\"`\n\tUserAgent string                        `json:\"user_agent\"`\n}\n\n\/\/ SourceMandate describes a source mandate.\ntype SourceMandate struct {\n\tAcceptance         *SourceMandateAcceptance        `json:\"acceptance\"`\n\tNotificationMethod SourceMandateNotificationMethod `json:\"notification_method\"`\n\tReference          string                          `json:\"reference\"`\n\tURL                string                          `json:\"url\"`\n}\n\n\/\/ SourceSourceOrderItems describes the items on source orders for sources.\ntype SourceSourceOrderItems struct {\n\tAmount      int64                     `json:\"amount\"`\n\tCurrency    Currency                  `json:\"currency\"`\n\tDescription string                    `json:\"description\"`\n\tQuantity    int64                     `json:\"quantity\"`\n\tType        SourceSourceOrderItemType `json:\"type\"`\n}\n\n\/\/ SourceSourceOrder describes a source order for a source.\ntype SourceSourceOrder struct {\n\tAmount   int64                   `json:\"amount\"`\n\tCurrency Currency                `json:\"currency\"`\n\tEmail    string                  `json:\"email\"`\n\tItems    *SourceSourceOrderItems `json:\"items\"`\n\tShipping *ShippingDetails        `json:\"shipping\"`\n}\n\n\/\/ Source is the resource representing a Source.\n\/\/ For more details see https:\/\/stripe.com\/docs\/api#sources.\ntype Source struct {\n\tAmount              int64                 `json:\"amount\"`\n\tClientSecret        string                `json:\"client_secret\"`\n\tCodeVerification    *CodeVerificationFlow `json:\"code_verification,omitempty\"`\n\tCreated             int64                 `json:\"created\"`\n\tCurrency            Currency              `json:\"currency\"`\n\tCustomer            string                `json:\"customer\"`\n\tFlow                SourceFlow            `json:\"flow\"`\n\tID                  string                `json:\"id\"`\n\tLivemode            bool                  `json:\"livemode\"`\n\tMandate             *SourceMandate        `json:\"mandate\"`\n\tMetadata            map[string]string     `json:\"metadata\"`\n\tOwner               *SourceOwner          `json:\"owner\"`\n\tReceiver            *ReceiverFlow         `json:\"receiver,omitempty\"`\n\tRedirect            *RedirectFlow         `json:\"redirect,omitempty\"`\n\tStatementDescriptor string                `json:\"statement_descriptor\"`\n\tSourceOrder         *SourceSourceOrder    `json:\"source_order\"`\n\tStatus              SourceStatus          `json:\"status\"`\n\tType                string                `json:\"type\"`\n\tTypeData            map[string]interface{}\n\tUsage               SourceUsage `json:\"usage\"`\n}\n\n\/\/ AppendTo implements custom encoding logic for SourceObjectParams so that the special\n\/\/ \"TypeData\" value for is sent as the correct parameter based on the Source type\nfunc (p *SourceObjectParams) AppendTo(body *form.Values, keyParts []string) {\n\tif len(p.TypeData) > 0 && p.Type == nil {\n\t\tpanic(\"You can not fill TypeData if you don't explicitly set Type\")\n\t}\n\n\tfor k, vs := range p.TypeData {\n\t\tbody.Add(form.FormatKey(append(keyParts, StringValue(p.Type), k)), vs)\n\t}\n}\n\n\/\/ UnmarshalJSON handles deserialization of an Source. This custom unmarshaling\n\/\/ is needed to extract the type specific data (accessible under `TypeData`)\n\/\/ but stored in JSON under a hash named after the `type` of the source.\nfunc (s *Source) UnmarshalJSON(data []byte) error {\n\ttype source Source\n\tvar v source\n\tif err := json.Unmarshal(data, &v); err != nil {\n\t\treturn err\n\t}\n\t*s = Source(v)\n\n\tvar raw map[string]interface{}\n\tif err := json.Unmarshal(data, &raw); err != nil {\n\t\treturn err\n\t}\n\n\tif d, ok := raw[s.Type]; ok {\n\t\tif m, ok := d.(map[string]interface{}); ok {\n\t\t\ts.TypeData = m\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * sshbox is a utility to encrypt a file using SSH keys.\n *\/\npackage main\n\nimport (\n\t\"crypto\/rand\"\n\t\"crypto\/rsa\"\n\t\"crypto\/sha256\"\n\t\"encoding\/asn1\"\n\t\"encoding\/pem\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/gokyle\/cryptobox\/secretbox\"\n\t\"github.com\/gokyle\/sshkey\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"regexp\"\n)\n\ntype boxPackage struct {\n\tLockedKey []byte\n\tBox       []byte\n}\n\ntype sshPublicKey struct {\n\tAlgorithm []byte\n\tModulus   []byte\n\tExponent  []byte\n}\n\nvar pubkeyRegexp = regexp.MustCompile(\"(?m)^ssh-... (\\\\S+).*$\")\nvar remoteCheck = regexp.MustCompile(\"^https?:\/\/\")\n\nfunc main() {\n\tflArmour := flag.Bool(\"a\", false, \"ASCII armour the box\")\n\tflDecrypt := flag.Bool(\"d\", false, \"decrypt file\")\n\tflEncrypt := flag.Bool(\"e\", false, \"encrypt file\")\n\tflKeyFile := flag.String(\"k\", \"\", \"SSH key file\")\n\tflag.Parse()\n\n\tif *flDecrypt && *flEncrypt {\n\t\tfmt.Println(\"[!] only one of -d or -e can be specified!\")\n\t\tos.Exit(1)\n\t}\n\n\tif flag.NArg() != 2 {\n\t\tfmt.Println(\"[!] source and target must both be specified.\")\n\t\tfmt.Printf(\"\\t%s [options] source target\\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\tsource := flag.Args()[0]\n\ttarget := flag.Args()[1]\n\n\tif *flKeyFile == \"\" {\n\t\tfmt.Println(\"[!] no key was specified!\\n\")\n\t\tos.Exit(1)\n\t}\n\n\tremote := remoteCheck.MatchString(*flKeyFile)\n\tif remote {\n\t\tif *flDecrypt {\n\t\t\tfmt.Println(\"[+] remotely fetching private keys is not allowed.\")\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Println(\"[+] will fetch key\")\n\t}\n\n\tif *flEncrypt {\n\t\terr := encrypt(source, target, *flKeyFile, !remote, *flArmour)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[!] failed.\")\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Println(\"[+] success\")\n\t\tos.Exit(0)\n\t} else {\n\t\terr := decrypt(source, target, *flKeyFile, *flArmour)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[!] failed.\")\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Println(\"[+] success.\")\n\t\tos.Exit(0)\n\t}\n}\n\n\/\/ Generate a random box key, encrypt the key to the RSA public key,\n\/\/ package the box appropriately, and write it out to a file.\nfunc encrypt(in, out, keyfile string, local, armour bool) (err error) {\n\tpub, err := sshkey.LoadPublicKeyFile(keyfile, local)\n\tif err != nil {\n\t\treturn\n\t}\n\tboxKey, err := secretbox.GenerateKey()\n\tif err != nil {\n\t\tfmt.Println(\"[!] failed to generate the box key.\")\n\t\treturn\n\t}\n\n\thash := sha256.New()\n\tlockedKey, err := rsa.EncryptOAEP(hash, rand.Reader, pub, boxKey, nil)\n\tif err != nil {\n\t\tfmt.Println(\"[!] RSA encryption failed:\", err.Error())\n\t\treturn\n\t}\n\n\tmessage, err := ioutil.ReadFile(in)\n\tif err != nil {\n\t\tfmt.Println(\"[!]\", err.Error())\n\t\treturn\n\t}\n\n\tbox, ok := secretbox.Seal(message, boxKey)\n\tif !ok {\n\t\tfmt.Println(\"[!] failed to seal the message.\")\n\t\terr = fmt.Errorf(\"sealing failure\")\n\t\treturn\n\t}\n\tpkg, err := packageBox(lockedKey, box, armour)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = ioutil.WriteFile(out, pkg, 0644)\n\tif err != nil {\n\t\tfmt.Println(\"[!]\", err.Error())\n\t}\n\treturn\n}\n\n\/\/ packageBox actually handles boxing. It can output either PEM-encoded or\n\/\/ DER-encoded boxes.\nfunc packageBox(lockedKey, box []byte, armour bool) (pkg []byte, err error) {\n\tvar pkgBox = boxPackage{lockedKey, box}\n\n\tpkg, err = asn1.Marshal(pkgBox)\n\tif err != nil {\n\t\tfmt.Println(\"[!] couldn't package the box\")\n\t\treturn\n\t}\n\n\tif armour {\n\t\tvar block pem.Block\n\t\tblock.Type = \"SSHBOX ENCRYPTED FILE\"\n\t\tblock.Bytes = pkg\n\t\tpkg = pem.EncodeToMemory(&block)\n\t}\n\treturn\n}\n\n\/\/ Decrypt loads the box, recovers the key using the RSA private key, open\n\/\/ the box, and write the message to a file.\nfunc decrypt(in, out, keyfile string, armour bool) (err error) {\n\tkey, err := sshkey.LoadPrivateKeyFile(keyfile)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpkg, err := ioutil.ReadFile(in)\n\tif err != nil {\n\t\tfmt.Println(\"[!]\", err.Error())\n\t\treturn\n\t}\n\n\tlockedKey, box, err := unpackageBox(pkg)\n\tif err != nil {\n\t\treturn\n\t}\n\n\thash := sha256.New()\n\tboxKey, err := rsa.DecryptOAEP(hash, rand.Reader, key, lockedKey, nil)\n\tif err != nil {\n\t\tfmt.Println(\"[!] RSA decryption failed:\", err.Error())\n\t\treturn\n\t}\n\n\tmessage, ok := secretbox.Open(box, boxKey)\n\tif !ok {\n\t\tfmt.Println(\"[!] failed to open box.\")\n\t\terr = fmt.Errorf(\"opening box failed\")\n\t\treturn\n\t}\n\terr = ioutil.WriteFile(out, message, 0644)\n\treturn\n}\n\n\/\/ unpackageBox handles the loading of a box; it first attempts to decode the\n\/\/ box as a DER-encoded box. If this fails, it attempts to decode the box as\n\/\/ a PEM-encoded box.\nfunc unpackageBox(pkg []byte) (lockedKey, box []byte, err error) {\n\tvar pkgStruct boxPackage\n\n\t_, err = asn1.Unmarshal(pkg, &pkgStruct)\n\tif err == nil {\n\t\treturn pkgStruct.LockedKey, pkgStruct.Box, nil\n\t}\n\n\tblock, _ := pem.Decode(pkg)\n\tif block == nil || block.Type != \"SSHBOX ENCRYPTED FILE\" {\n\t\tfmt.Println(\"[!] invalid box.\")\n\t\terr = fmt.Errorf(\"invalid box\")\n\t\treturn\n\t}\n\t_, err = asn1.Unmarshal(block.Bytes, &pkgStruct)\n\treturn pkgStruct.LockedKey, pkgStruct.Box, err\n}\n<commit_msg>Add error messages for key loading.<commit_after>\/*\n * sshbox is a utility to encrypt a file using SSH keys.\n *\/\npackage main\n\nimport (\n\t\"crypto\/rand\"\n\t\"crypto\/rsa\"\n\t\"crypto\/sha256\"\n\t\"encoding\/asn1\"\n\t\"encoding\/pem\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/gokyle\/cryptobox\/secretbox\"\n\t\"github.com\/gokyle\/sshkey\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"regexp\"\n)\n\ntype boxPackage struct {\n\tLockedKey []byte\n\tBox       []byte\n}\n\ntype sshPublicKey struct {\n\tAlgorithm []byte\n\tModulus   []byte\n\tExponent  []byte\n}\n\nvar pubkeyRegexp = regexp.MustCompile(\"(?m)^ssh-... (\\\\S+).*$\")\nvar remoteCheck = regexp.MustCompile(\"^https?:\/\/\")\n\nfunc main() {\n\tflArmour := flag.Bool(\"a\", false, \"ASCII armour the box\")\n\tflDecrypt := flag.Bool(\"d\", false, \"decrypt file\")\n\tflEncrypt := flag.Bool(\"e\", false, \"encrypt file\")\n\tflKeyFile := flag.String(\"k\", \"\", \"SSH key file\")\n\tflag.Parse()\n\n\tif *flDecrypt && *flEncrypt {\n\t\tfmt.Println(\"[!] only one of -d or -e can be specified!\")\n\t\tos.Exit(1)\n\t}\n\n\tif flag.NArg() != 2 {\n\t\tfmt.Println(\"[!] source and target must both be specified.\")\n\t\tfmt.Printf(\"\\t%s [options] source target\\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\tsource := flag.Args()[0]\n\ttarget := flag.Args()[1]\n\n\tif *flKeyFile == \"\" {\n\t\tfmt.Println(\"[!] no key was specified!\\n\")\n\t\tos.Exit(1)\n\t}\n\n\tremote := remoteCheck.MatchString(*flKeyFile)\n\tif remote {\n\t\tif *flDecrypt {\n\t\t\tfmt.Println(\"[+] remotely fetching private keys is not allowed.\")\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Println(\"[+] will fetch key\")\n\t}\n\n\tif *flEncrypt {\n\t\terr := encrypt(source, target, *flKeyFile, !remote, *flArmour)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[!] failed.\")\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Println(\"[+] success\")\n\t\tos.Exit(0)\n\t} else {\n\t\terr := decrypt(source, target, *flKeyFile, *flArmour)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"[!] failed.\")\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Println(\"[+] success.\")\n\t\tos.Exit(0)\n\t}\n}\n\n\/\/ Generate a random box key, encrypt the key to the RSA public key,\n\/\/ package the box appropriately, and write it out to a file.\nfunc encrypt(in, out, keyfile string, local, armour bool) (err error) {\n\tpub, err := sshkey.LoadPublicKeyFile(keyfile, local)\n\tif err != nil {\n\t\tfmt.Printf(\"[!] failed to load the public key:\\n\\t%s\\n\",\n\t\t    err.Error())\n\t\treturn\n\t}\n\tboxKey, err := secretbox.GenerateKey()\n\tif err != nil {\n\t\tfmt.Println(\"[!] failed to generate the box key.\")\n\t\treturn\n\t}\n\n\thash := sha256.New()\n\tlockedKey, err := rsa.EncryptOAEP(hash, rand.Reader, pub, boxKey, nil)\n\tif err != nil {\n\t\tfmt.Println(\"[!] RSA encryption failed:\", err.Error())\n\t\treturn\n\t}\n\n\tmessage, err := ioutil.ReadFile(in)\n\tif err != nil {\n\t\tfmt.Println(\"[!]\", err.Error())\n\t\treturn\n\t}\n\n\tbox, ok := secretbox.Seal(message, boxKey)\n\tif !ok {\n\t\tfmt.Println(\"[!] failed to seal the message.\")\n\t\terr = fmt.Errorf(\"sealing failure\")\n\t\treturn\n\t}\n\tpkg, err := packageBox(lockedKey, box, armour)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = ioutil.WriteFile(out, pkg, 0644)\n\tif err != nil {\n\t\tfmt.Println(\"[!]\", err.Error())\n\t}\n\treturn\n}\n\n\/\/ packageBox actually handles boxing. It can output either PEM-encoded or\n\/\/ DER-encoded boxes.\nfunc packageBox(lockedKey, box []byte, armour bool) (pkg []byte, err error) {\n\tvar pkgBox = boxPackage{lockedKey, box}\n\n\tpkg, err = asn1.Marshal(pkgBox)\n\tif err != nil {\n\t\tfmt.Println(\"[!] couldn't package the box\")\n\t\treturn\n\t}\n\n\tif armour {\n\t\tvar block pem.Block\n\t\tblock.Type = \"SSHBOX ENCRYPTED FILE\"\n\t\tblock.Bytes = pkg\n\t\tpkg = pem.EncodeToMemory(&block)\n\t}\n\treturn\n}\n\n\/\/ Decrypt loads the box, recovers the key using the RSA private key, open\n\/\/ the box, and write the message to a file.\nfunc decrypt(in, out, keyfile string, armour bool) (err error) {\n\tkey, err := sshkey.LoadPrivateKeyFile(keyfile)\n\tif err != nil {\n\t\tfmt.Printf(\"[!] failed to load the private key:\\n\\t%s\\n\",\n\t\t    err.Error())\n\t\treturn\n\t}\n\n\tpkg, err := ioutil.ReadFile(in)\n\tif err != nil {\n\t\tfmt.Println(\"[!]\", err.Error())\n\t\treturn\n\t}\n\n\tlockedKey, box, err := unpackageBox(pkg)\n\tif err != nil {\n\t\treturn\n\t}\n\n\thash := sha256.New()\n\tboxKey, err := rsa.DecryptOAEP(hash, rand.Reader, key, lockedKey, nil)\n\tif err != nil {\n\t\tfmt.Println(\"[!] RSA decryption failed:\", err.Error())\n\t\treturn\n\t}\n\n\tmessage, ok := secretbox.Open(box, boxKey)\n\tif !ok {\n\t\tfmt.Println(\"[!] failed to open box.\")\n\t\terr = fmt.Errorf(\"opening box failed\")\n\t\treturn\n\t}\n\terr = ioutil.WriteFile(out, message, 0644)\n\treturn\n}\n\n\/\/ unpackageBox handles the loading of a box; it first attempts to decode the\n\/\/ box as a DER-encoded box. If this fails, it attempts to decode the box as\n\/\/ a PEM-encoded box.\nfunc unpackageBox(pkg []byte) (lockedKey, box []byte, err error) {\n\tvar pkgStruct boxPackage\n\n\t_, err = asn1.Unmarshal(pkg, &pkgStruct)\n\tif err == nil {\n\t\treturn pkgStruct.LockedKey, pkgStruct.Box, nil\n\t}\n\n\tblock, _ := pem.Decode(pkg)\n\tif block == nil || block.Type != \"SSHBOX ENCRYPTED FILE\" {\n\t\tfmt.Println(\"[!] invalid box.\")\n\t\terr = fmt.Errorf(\"invalid box\")\n\t\treturn\n\t}\n\t_, err = asn1.Unmarshal(block.Bytes, &pkgStruct)\n\treturn pkgStruct.LockedKey, pkgStruct.Box, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\n\/\/ This source file is for the special case of serving a single file.\n\nimport (\n\t\"errors\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tdefaultStaticCacheSize = 128 * MiB\n\n\tmaxAttemptsAtIncreasingPortNumber = 128\n\n\twaitBeforeOpen = time.Second * 1\n)\n\n\/\/ nextPort increases the port number by 1\nfunc nextPort(colonPort string) (string, error) {\n\tif !strings.HasPrefix(colonPort, \":\") {\n\t\treturn colonPort, errors.New(\"colonPort does not start with a colon! \\\"\" + colonPort + \"\\\"\")\n\t}\n\tnum, err := strconv.Atoi(colonPort[1:])\n\tif err != nil {\n\t\treturn colonPort, errors.New(\"Could not convert port number to string: \\\"\" + colonPort[1:] + \"\\\"\")\n\t}\n\t\/\/ Increase the port number by 1, add a colon, convert to string and return\n\treturn \":\" + strconv.Itoa(num+1), nil\n}\n\n\/\/ This is a bit hacky, but it's only used when serving a single static file\nfunc openAfter(wait time.Duration, hostname, colonPort string, https bool, cancelChannel chan bool) {\n\t\/\/ Wait a bit\n\ttime.Sleep(wait)\n\tselect {\n\tcase _ = <-cancelChannel:\n\t\t\/\/ Got a message on the cancelChannel:\n\t\t\/\/ don't open the URL with an external application.\n\t\treturn\n\tcase <-time.After(waitBeforeOpen):\n\t\t\/\/ Got timeout, assume the port was not busy\n\t\topenURL(hostname, colonPort, https)\n\t}\n}\n\n\/\/ shortInfo outputs a short string about which file is served where\nfunc shortInfoAndOpen(filename, colonPort string, cancelChannel chan bool) {\n\thostname := \"localhost\"\n\tif serverHost != \"\" {\n\t\thostname = serverHost\n\t}\n\tlog.Info(\"Serving \" + filename + \" on http:\/\/\" + hostname + colonPort)\n\n\tif openURLAfterServing {\n\t\tgo openAfter(waitBeforeOpen, hostname, colonPort, false, cancelChannel)\n\t}\n}\n\n\/\/ Convenience function for serving only a single file\n\/\/ (quick and easy way to view a README.md file)\nfunc serveStaticFile(filename, colonPort string) {\n\tlog.Info(\"Single file mode. Not using the regular parameters.\")\n\n\tcancelChannel := make(chan bool, 1)\n\n\tshortInfoAndOpen(filename, colonPort, cancelChannel)\n\n\tmux := http.NewServeMux()\n\t\/\/ 64 MiB cache, use cache compression, no per-file size limit, use best gzip compression\n\tpreferSpeed = false\n\tcache := newFileCache(defaultStaticCacheSize, true, 0)\n\tmux.HandleFunc(\"\/\", func(w http.ResponseWriter, req *http.Request) {\n\t\tw.Header().Set(\"Server\", versionString)\n\t\tfilePage(w, req, filename, nil, nil, cache)\n\t})\n\tHTTPserver := newGracefulServer(mux, false, serverHost+colonPort, 5*time.Second)\n\n\t\/\/ Attempt to serve just the single file\n\tif err := HTTPserver.ListenAndServe(); err != nil {\n\t\t\/\/ If it fails, try several times, increasing the port by 1 each time\n\t\tfor i := 0; i < maxAttemptsAtIncreasingPortNumber; i++ {\n\t\t\tif err := HTTPserver.ListenAndServe(); err != nil {\n\t\t\t\tcancelChannel <- true\n\t\t\t\tif !strings.HasSuffix(err.Error(), \"already in use\") {\n\t\t\t\t\t\/\/ Not a problem with address already being in use\n\t\t\t\t\tfatalExit(err)\n\t\t\t\t}\n\t\t\t\tlog.Warn(\"Address already in use. Using next port number.\")\n\t\t\t\tif newPort, err2 := nextPort(colonPort); err2 != nil {\n\t\t\t\t\tfatalExit(err)\n\t\t\t\t} else {\n\t\t\t\t\tcolonPort = newPort\n\t\t\t\t}\n\n\t\t\t\t\/\/ Make a new cancel channel, and use the new URL\n\t\t\t\tcancelChannel = make(chan bool, 1)\n\t\t\t\tshortInfoAndOpen(filename, colonPort, cancelChannel)\n\n\t\t\t\tHTTPserver = newGracefulServer(mux, false, serverHost+colonPort, 5*time.Second)\n\t\t\t}\n\t\t}\n\t\t\/\/ Several attempts failed\n\t\tfatalExit(err)\n\t}\n}\n<commit_msg>Decrease delay before opening Markdown in a browser<commit_after>package main\n\n\/\/ This source file is for the special case of serving a single file.\n\nimport (\n\t\"errors\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tdefaultStaticCacheSize = 128 * MiB\n\n\tmaxAttemptsAtIncreasingPortNumber = 128\n\n\twaitBeforeOpen = time.Millisecond * 200\n)\n\n\/\/ nextPort increases the port number by 1\nfunc nextPort(colonPort string) (string, error) {\n\tif !strings.HasPrefix(colonPort, \":\") {\n\t\treturn colonPort, errors.New(\"colonPort does not start with a colon! \\\"\" + colonPort + \"\\\"\")\n\t}\n\tnum, err := strconv.Atoi(colonPort[1:])\n\tif err != nil {\n\t\treturn colonPort, errors.New(\"Could not convert port number to string: \\\"\" + colonPort[1:] + \"\\\"\")\n\t}\n\t\/\/ Increase the port number by 1, add a colon, convert to string and return\n\treturn \":\" + strconv.Itoa(num+1), nil\n}\n\n\/\/ This is a bit hacky, but it's only used when serving a single static file\nfunc openAfter(wait time.Duration, hostname, colonPort string, https bool, cancelChannel chan bool) {\n\t\/\/ Wait a bit\n\ttime.Sleep(wait)\n\tselect {\n\tcase _ = <-cancelChannel:\n\t\t\/\/ Got a message on the cancelChannel:\n\t\t\/\/ don't open the URL with an external application.\n\t\treturn\n\tcase <-time.After(waitBeforeOpen):\n\t\t\/\/ Got timeout, assume the port was not busy\n\t\topenURL(hostname, colonPort, https)\n\t}\n}\n\n\/\/ shortInfo outputs a short string about which file is served where\nfunc shortInfoAndOpen(filename, colonPort string, cancelChannel chan bool) {\n\thostname := \"localhost\"\n\tif serverHost != \"\" {\n\t\thostname = serverHost\n\t}\n\tlog.Info(\"Serving \" + filename + \" on http:\/\/\" + hostname + colonPort)\n\n\tif openURLAfterServing {\n\t\tgo openAfter(waitBeforeOpen, hostname, colonPort, false, cancelChannel)\n\t}\n}\n\n\/\/ Convenience function for serving only a single file\n\/\/ (quick and easy way to view a README.md file)\nfunc serveStaticFile(filename, colonPort string) {\n\tlog.Info(\"Single file mode. Not using the regular parameters.\")\n\n\tcancelChannel := make(chan bool, 1)\n\n\tshortInfoAndOpen(filename, colonPort, cancelChannel)\n\n\tmux := http.NewServeMux()\n\t\/\/ 64 MiB cache, use cache compression, no per-file size limit, use best gzip compression\n\tpreferSpeed = false\n\tcache := newFileCache(defaultStaticCacheSize, true, 0)\n\tmux.HandleFunc(\"\/\", func(w http.ResponseWriter, req *http.Request) {\n\t\tw.Header().Set(\"Server\", versionString)\n\t\tfilePage(w, req, filename, nil, nil, cache)\n\t})\n\tHTTPserver := newGracefulServer(mux, false, serverHost+colonPort, 5*time.Second)\n\n\t\/\/ Attempt to serve just the single file\n\tif err := HTTPserver.ListenAndServe(); err != nil {\n\t\t\/\/ If it fails, try several times, increasing the port by 1 each time\n\t\tfor i := 0; i < maxAttemptsAtIncreasingPortNumber; i++ {\n\t\t\tif err := HTTPserver.ListenAndServe(); err != nil {\n\t\t\t\tcancelChannel <- true\n\t\t\t\tif !strings.HasSuffix(err.Error(), \"already in use\") {\n\t\t\t\t\t\/\/ Not a problem with address already being in use\n\t\t\t\t\tfatalExit(err)\n\t\t\t\t}\n\t\t\t\tlog.Warn(\"Address already in use. Using next port number.\")\n\t\t\t\tif newPort, err2 := nextPort(colonPort); err2 != nil {\n\t\t\t\t\tfatalExit(err)\n\t\t\t\t} else {\n\t\t\t\t\tcolonPort = newPort\n\t\t\t\t}\n\n\t\t\t\t\/\/ Make a new cancel channel, and use the new URL\n\t\t\t\tcancelChannel = make(chan bool, 1)\n\t\t\t\tshortInfoAndOpen(filename, colonPort, cancelChannel)\n\n\t\t\t\tHTTPserver = newGracefulServer(mux, false, serverHost+colonPort, 5*time.Second)\n\t\t\t}\n\t\t}\n\t\t\/\/ Several attempts failed\n\t\tfatalExit(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright 2013-2016 Seagate Technology LLC.\n *\n * This Source Code Form is subject to the terms of the Mozilla\n * Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at\n * https:\/\/mozilla.org\/MP:\/2.0\/.\n *\n * This program is distributed in the hope that it will be useful,\n * but is provided AS-IS, WITHOUT ANY WARRANTY; including without\n * the implied warranty of MERCHANTABILITY, NON-INFRINGEMENT or\n * FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public\n * License for more details.\n *\n * See www.openkinetic.org for more project information\n *\/\n\npackage kinetic\n\nimport (\n\t\"strconv\"\n\n\tkproto \"github.com\/Kinetic\/kinetic-go\/proto\"\n)\n\n\/\/ StatusCode for kinetic message.\n\/\/ Including status code get from device, or client internal error code.\ntype StatusCode int32\n\n\/\/ StatusCode code value\nconst (\n\tRemoteNotAttempted                 StatusCode = iota\n\tOK                                 StatusCode = iota\n\tClientIOError                      StatusCode = iota\n\tClientShutdown                     StatusCode = iota\n\tClientInternalError                StatusCode = iota\n\tClientResponseHMACError            StatusCode = iota\n\tRemoteHMACError                    StatusCode = iota\n\tRemoteNotAuthorized                StatusCode = iota\n\tRemoteClusterVersionMismatch       StatusCode = iota\n\tRemoteInvalidRequest               StatusCode = iota\n\tRemoteInternalError                StatusCode = iota\n\tRemoteHeaderRequired               StatusCode = iota\n\tRemoteNotFound                     StatusCode = iota\n\tRemoteVersionMismatch              StatusCode = iota\n\tRemoteServiceBusy                  StatusCode = iota\n\tRemoteExpired                      StatusCode = iota\n\tRemoteDataError                    StatusCode = iota\n\tRemotePermDataError                StatusCode = iota\n\tRemoteConnectionError              StatusCode = iota\n\tRemoteNoSpace                      StatusCode = iota\n\tRemoteNoSuchHMACAlgorithm          StatusCode = iota\n\tRemoteOtherError                   StatusCode = iota\n\tProtocolErrorResponseNoAckSequence StatusCode = iota\n\tRemoteNestedOperationErrors        StatusCode = iota\n\tRemoteDeviceLocked                 StatusCode = iota\n\tRemoteDeviceAlreadyUnlocked        StatusCode = iota\n\tRemoteConnectionTerminated         StatusCode = iota\n\tRemoteInvalidBatch                 StatusCode = iota\n\tRemoteInvalidExecute               StatusCode = iota\n\tRemoteExecuteComplete              StatusCode = iota\n\tRemoteHibernate                    StatusCode = iota\n\tRemoteShutdown                     StatusCode = iota\n)\n\nvar statusName = map[StatusCode]string{\n\tRemoteNotAttempted:                 \"REMOTE_NOT_ATTEMPTED\",\n\tOK:                                 \"OK\",\n\tClientIOError:                      \"CLIENT_IO_ERROR\",\n\tClientShutdown:                     \"CLIENT_SHUTDOWN\",\n\tClientInternalError:                \"CLIENT_INTERNAL_ERROR\",\n\tClientResponseHMACError:            \"CLIENT_RESPONSE_HMAC_VERIFICATION_ERROR\",\n\tRemoteHMACError:                    \"REMOTE_HMAC_ERROR\",\n\tRemoteNotAuthorized:                \"REMOTE_NOT_AUTHORIZED\",\n\tRemoteClusterVersionMismatch:       \"REMOTE_CLUSTER_VERSION_MISMATCH\",\n\tRemoteInvalidRequest:               \"REMOTE_INVALID_REQUEST\",\n\tRemoteInternalError:                \"REMOTE_INTERNAL_ERROR\",\n\tRemoteHeaderRequired:               \"REMOTE_HEADER_REQUIRED\",\n\tRemoteNotFound:                     \"REMOTE_NOT_FOUND\",\n\tRemoteVersionMismatch:              \"REMOTE_VERSION_MISMATCH\",\n\tRemoteServiceBusy:                  \"REMOTE_SERVICE_BUSY\",\n\tRemoteExpired:                      \"REMOTE_EXPIRED\",\n\tRemoteDataError:                    \"REMOTE_DATA_ERROR\",\n\tRemotePermDataError:                \"REMOTE_PERM_DATA_ERROR\",\n\tRemoteConnectionError:              \"REMOTE_CONNECTION_ERROR\",\n\tRemoteNoSpace:                      \"REMOTE_NO_SPACE\",\n\tRemoteNoSuchHMACAlgorithm:          \"REMOTE_NO_SUCH_HMAC_ALGORITHM\",\n\tRemoteOtherError:                   \"REMOTE_OTHER_ERROR\",\n\tProtocolErrorResponseNoAckSequence: \"PROTOCOL_ERROR_RESPONSE_NO_ACKSEQUENCE \",\n\tRemoteNestedOperationErrors:        \"REMOTE_NESTED_OPERATION_ERRORS\",\n\tRemoteDeviceLocked:                 \"REMOTE_DEVICE_LOCKED\",\n\tRemoteDeviceAlreadyUnlocked:        \"REMOTE_DEVICE_ALREADY_UNLOCKED\",\n\tRemoteConnectionTerminated:         \"REMOTE_CONNECTION_TERMINATED\",\n\tRemoteInvalidBatch:                 \"REMOTE_INVALID_BATCH\",\n\tRemoteInvalidExecute:               \"REMOTE_INVALID_EXECUTE\",\n\tRemoteExecuteComplete:              \"REMOTE_EXECUTE_COMPLETE\",\n\tRemoteHibernate:                    \"REMOTE_HIBERNATE\",\n\tRemoteShutdown:                     \"REMOTE_SHUTDOWN\",\n}\n\n\/\/ Status for each kinetic message.\n\/\/ Code is the status code and ErrorMsg is the detail message\ntype Status struct {\n\tCode                   StatusCode\n\tErrorMsg               string\n\tExpectedClusterVersion int64\n}\n\n\/\/ Error returns the detail status message if Status.Code != OK\nfunc (s Status) Error() string {\n\treturn s.ErrorMsg\n}\n\nfunc (s Status) String() string {\n\tret := \"Unknown Status\"\n\tstr, ok := statusName[s.Code]\n\tif ok {\n\t\tret = str + \" : \" + s.ErrorMsg\n\t\tif s.Code == RemoteClusterVersionMismatch {\n\t\t\tret = ret + \", Expected cluster version =\" + strconv.Itoa(int(s.ExpectedClusterVersion))\n\t\t}\n\t}\n\treturn ret\n}\n\nfunc convertStatusCodeToProto(s StatusCode) kproto.Command_Status_StatusCode {\n\tret := kproto.Command_Status_INVALID_STATUS_CODE\n\tswitch s {\n\tcase RemoteNotAttempted:\n\t\tret = kproto.Command_Status_NOT_ATTEMPTED\n\tcase OK:\n\t\tret = kproto.Command_Status_SUCCESS\n\tcase RemoteHMACError:\n\t\tret = kproto.Command_Status_HMAC_FAILURE\n\tcase RemoteNotAuthorized:\n\t\tret = kproto.Command_Status_NOT_AUTHORIZED\n\tcase RemoteClusterVersionMismatch:\n\t\tret = kproto.Command_Status_VERSION_FAILURE\n\tcase RemoteInternalError:\n\t\tret = kproto.Command_Status_INTERNAL_ERROR\n\tcase RemoteHeaderRequired:\n\t\tret = kproto.Command_Status_HEADER_REQUIRED\n\tcase RemoteNotFound:\n\t\tret = kproto.Command_Status_NOT_FOUND\n\tcase RemoteVersionMismatch:\n\t\tret = kproto.Command_Status_VERSION_MISMATCH\n\tcase RemoteServiceBusy:\n\t\tret = kproto.Command_Status_SERVICE_BUSY\n\tcase RemoteExpired:\n\t\tret = kproto.Command_Status_EXPIRED\n\tcase RemoteDataError:\n\t\tret = kproto.Command_Status_DATA_ERROR\n\tcase RemotePermDataError:\n\t\tret = kproto.Command_Status_PERM_DATA_ERROR\n\tcase RemoteConnectionError:\n\t\tret = kproto.Command_Status_REMOTE_CONNECTION_ERROR\n\tcase RemoteNoSpace:\n\t\tret = kproto.Command_Status_NO_SPACE\n\tcase RemoteNoSuchHMACAlgorithm:\n\t\tret = kproto.Command_Status_NO_SUCH_HMAC_ALGORITHM\n\tcase RemoteInvalidRequest:\n\t\tret = kproto.Command_Status_INVALID_REQUEST\n\tcase RemoteNestedOperationErrors:\n\t\tret = kproto.Command_Status_NESTED_OPERATION_ERRORS\n\tcase RemoteDeviceLocked:\n\t\tret = kproto.Command_Status_DEVICE_LOCKED\n\tcase RemoteDeviceAlreadyUnlocked:\n\t\tret = kproto.Command_Status_DEVICE_ALREADY_UNLOCKED\n\tcase RemoteConnectionTerminated:\n\t\tret = kproto.Command_Status_CONNECTION_TERMINATED\n\tcase RemoteInvalidBatch:\n\t\tret = kproto.Command_Status_INVALID_BATCH\n\tcase RemoteHibernate:\n\t\tret = kproto.Command_Status_HIBERNATE\n\tcase RemoteShutdown:\n\t\tret = kproto.Command_Status_SHUTDOWN\n\t}\n\treturn ret\n}\n\nfunc convertStatusCodeFromProto(s kproto.Command_Status_StatusCode) StatusCode {\n\tret := RemoteOtherError\n\tswitch s {\n\tcase kproto.Command_Status_NOT_ATTEMPTED:\n\t\tret = RemoteNotAttempted\n\tcase kproto.Command_Status_SUCCESS:\n\t\tret = OK\n\tcase kproto.Command_Status_HMAC_FAILURE:\n\t\tret = RemoteHMACError\n\tcase kproto.Command_Status_NOT_AUTHORIZED:\n\t\tret = RemoteNotAuthorized\n\tcase kproto.Command_Status_VERSION_FAILURE:\n\t\tret = RemoteClusterVersionMismatch\n\tcase kproto.Command_Status_INTERNAL_ERROR:\n\t\tret = RemoteInternalError\n\tcase kproto.Command_Status_HEADER_REQUIRED:\n\t\tret = RemoteHeaderRequired\n\tcase kproto.Command_Status_NOT_FOUND:\n\t\tret = RemoteNotFound\n\tcase kproto.Command_Status_VERSION_MISMATCH:\n\t\tret = RemoteVersionMismatch\n\tcase kproto.Command_Status_SERVICE_BUSY:\n\t\tret = RemoteServiceBusy\n\tcase kproto.Command_Status_EXPIRED:\n\t\tret = RemoteExpired\n\tcase kproto.Command_Status_DATA_ERROR:\n\t\tret = RemoteDataError\n\tcase kproto.Command_Status_PERM_DATA_ERROR:\n\t\tret = RemotePermDataError\n\tcase kproto.Command_Status_REMOTE_CONNECTION_ERROR:\n\t\tret = RemoteConnectionError\n\tcase kproto.Command_Status_NO_SPACE:\n\t\tret = RemoteNoSpace\n\tcase kproto.Command_Status_NO_SUCH_HMAC_ALGORITHM:\n\t\tret = RemoteNoSuchHMACAlgorithm\n\tcase kproto.Command_Status_INVALID_REQUEST:\n\t\tret = RemoteInvalidRequest\n\tcase kproto.Command_Status_NESTED_OPERATION_ERRORS:\n\t\tret = RemoteNestedOperationErrors\n\tcase kproto.Command_Status_DEVICE_LOCKED:\n\t\tret = RemoteDeviceLocked\n\tcase kproto.Command_Status_DEVICE_ALREADY_UNLOCKED:\n\t\tret = RemoteDeviceAlreadyUnlocked\n\tcase kproto.Command_Status_CONNECTION_TERMINATED:\n\t\tret = RemoteConnectionTerminated\n\tcase kproto.Command_Status_INVALID_BATCH:\n\t\tret = RemoteInvalidBatch\n\tcase kproto.Command_Status_HIBERNATE:\n\t\tret = RemoteHibernate\n\tcase kproto.Command_Status_SHUTDOWN:\n\t\tret = RemoteShutdown\n\t}\n\treturn ret\n}\n\nfunc getStatusFromProto(cmd *kproto.Command) Status {\n\tcode := convertStatusCodeFromProto(cmd.GetStatus().GetCode())\n\tmsg := cmd.GetStatus().GetStatusMessage()\n\tversion := cmd.GetHeader().GetClusterVersion()\n\n\treturn Status{code, msg, version}\n}\n<commit_msg>add function to return StatusCode as string<commit_after>\/**\n * Copyright 2013-2016 Seagate Technology LLC.\n *\n * This Source Code Form is subject to the terms of the Mozilla\n * Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at\n * https:\/\/mozilla.org\/MP:\/2.0\/.\n *\n * This program is distributed in the hope that it will be useful,\n * but is provided AS-IS, WITHOUT ANY WARRANTY; including without\n * the implied warranty of MERCHANTABILITY, NON-INFRINGEMENT or\n * FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public\n * License for more details.\n *\n * See www.openkinetic.org for more project information\n *\/\n\npackage kinetic\n\nimport (\n\t\"strconv\"\n\n\tkproto \"github.com\/Kinetic\/kinetic-go\/proto\"\n)\n\n\/\/ StatusCode for kinetic message.\n\/\/ Including status code get from device, or client internal error code.\ntype StatusCode int32\n\n\/\/ StatusCode code value\nconst (\n\tRemoteNotAttempted                 StatusCode = iota\n\tOK                                 StatusCode = iota\n\tClientIOError                      StatusCode = iota\n\tClientShutdown                     StatusCode = iota\n\tClientInternalError                StatusCode = iota\n\tClientResponseHMACError            StatusCode = iota\n\tRemoteHMACError                    StatusCode = iota\n\tRemoteNotAuthorized                StatusCode = iota\n\tRemoteClusterVersionMismatch       StatusCode = iota\n\tRemoteInvalidRequest               StatusCode = iota\n\tRemoteInternalError                StatusCode = iota\n\tRemoteHeaderRequired               StatusCode = iota\n\tRemoteNotFound                     StatusCode = iota\n\tRemoteVersionMismatch              StatusCode = iota\n\tRemoteServiceBusy                  StatusCode = iota\n\tRemoteExpired                      StatusCode = iota\n\tRemoteDataError                    StatusCode = iota\n\tRemotePermDataError                StatusCode = iota\n\tRemoteConnectionError              StatusCode = iota\n\tRemoteNoSpace                      StatusCode = iota\n\tRemoteNoSuchHMACAlgorithm          StatusCode = iota\n\tRemoteOtherError                   StatusCode = iota\n\tProtocolErrorResponseNoAckSequence StatusCode = iota\n\tRemoteNestedOperationErrors        StatusCode = iota\n\tRemoteDeviceLocked                 StatusCode = iota\n\tRemoteDeviceAlreadyUnlocked        StatusCode = iota\n\tRemoteConnectionTerminated         StatusCode = iota\n\tRemoteInvalidBatch                 StatusCode = iota\n\tRemoteInvalidExecute               StatusCode = iota\n\tRemoteExecuteComplete              StatusCode = iota\n\tRemoteHibernate                    StatusCode = iota\n\tRemoteShutdown                     StatusCode = iota\n)\n\nvar statusName = map[StatusCode]string{\n\tRemoteNotAttempted:                 \"REMOTE_NOT_ATTEMPTED\",\n\tOK:                                 \"OK\",\n\tClientIOError:                      \"CLIENT_IO_ERROR\",\n\tClientShutdown:                     \"CLIENT_SHUTDOWN\",\n\tClientInternalError:                \"CLIENT_INTERNAL_ERROR\",\n\tClientResponseHMACError:            \"CLIENT_RESPONSE_HMAC_VERIFICATION_ERROR\",\n\tRemoteHMACError:                    \"REMOTE_HMAC_ERROR\",\n\tRemoteNotAuthorized:                \"REMOTE_NOT_AUTHORIZED\",\n\tRemoteClusterVersionMismatch:       \"REMOTE_CLUSTER_VERSION_MISMATCH\",\n\tRemoteInvalidRequest:               \"REMOTE_INVALID_REQUEST\",\n\tRemoteInternalError:                \"REMOTE_INTERNAL_ERROR\",\n\tRemoteHeaderRequired:               \"REMOTE_HEADER_REQUIRED\",\n\tRemoteNotFound:                     \"REMOTE_NOT_FOUND\",\n\tRemoteVersionMismatch:              \"REMOTE_VERSION_MISMATCH\",\n\tRemoteServiceBusy:                  \"REMOTE_SERVICE_BUSY\",\n\tRemoteExpired:                      \"REMOTE_EXPIRED\",\n\tRemoteDataError:                    \"REMOTE_DATA_ERROR\",\n\tRemotePermDataError:                \"REMOTE_PERM_DATA_ERROR\",\n\tRemoteConnectionError:              \"REMOTE_CONNECTION_ERROR\",\n\tRemoteNoSpace:                      \"REMOTE_NO_SPACE\",\n\tRemoteNoSuchHMACAlgorithm:          \"REMOTE_NO_SUCH_HMAC_ALGORITHM\",\n\tRemoteOtherError:                   \"REMOTE_OTHER_ERROR\",\n\tProtocolErrorResponseNoAckSequence: \"PROTOCOL_ERROR_RESPONSE_NO_ACKSEQUENCE \",\n\tRemoteNestedOperationErrors:        \"REMOTE_NESTED_OPERATION_ERRORS\",\n\tRemoteDeviceLocked:                 \"REMOTE_DEVICE_LOCKED\",\n\tRemoteDeviceAlreadyUnlocked:        \"REMOTE_DEVICE_ALREADY_UNLOCKED\",\n\tRemoteConnectionTerminated:         \"REMOTE_CONNECTION_TERMINATED\",\n\tRemoteInvalidBatch:                 \"REMOTE_INVALID_BATCH\",\n\tRemoteInvalidExecute:               \"REMOTE_INVALID_EXECUTE\",\n\tRemoteExecuteComplete:              \"REMOTE_EXECUTE_COMPLETE\",\n\tRemoteHibernate:                    \"REMOTE_HIBERNATE\",\n\tRemoteShutdown:                     \"REMOTE_SHUTDOWN\",\n}\n\n\/\/ String returns string value of StatusCode.\nfunc (c StatusCode) String() string {\n\tstr, ok := statusName[c]\n\tif ok {\n\t\treturn str\n\t}\n\n\treturn \"Unknown Status\"\n}\n\n\/\/ Status for each kinetic message.\n\/\/ Code is the status code and ErrorMsg is the detail message\ntype Status struct {\n\tCode                   StatusCode\n\tErrorMsg               string\n\tExpectedClusterVersion int64\n}\n\n\/\/ Error returns the detail status message if Status.Code != OK\nfunc (s Status) Error() string {\n\treturn s.ErrorMsg\n}\n\nfunc (s Status) String() string {\n\tret := \"Unknown Status\"\n\tstr, ok := statusName[s.Code]\n\tif ok {\n\t\tret = str + \" : \" + s.ErrorMsg\n\t\tif s.Code == RemoteClusterVersionMismatch {\n\t\t\tret = ret + \", Expected cluster version =\" + strconv.Itoa(int(s.ExpectedClusterVersion))\n\t\t}\n\t}\n\treturn ret\n}\n\nfunc convertStatusCodeToProto(s StatusCode) kproto.Command_Status_StatusCode {\n\tret := kproto.Command_Status_INVALID_STATUS_CODE\n\tswitch s {\n\tcase RemoteNotAttempted:\n\t\tret = kproto.Command_Status_NOT_ATTEMPTED\n\tcase OK:\n\t\tret = kproto.Command_Status_SUCCESS\n\tcase RemoteHMACError:\n\t\tret = kproto.Command_Status_HMAC_FAILURE\n\tcase RemoteNotAuthorized:\n\t\tret = kproto.Command_Status_NOT_AUTHORIZED\n\tcase RemoteClusterVersionMismatch:\n\t\tret = kproto.Command_Status_VERSION_FAILURE\n\tcase RemoteInternalError:\n\t\tret = kproto.Command_Status_INTERNAL_ERROR\n\tcase RemoteHeaderRequired:\n\t\tret = kproto.Command_Status_HEADER_REQUIRED\n\tcase RemoteNotFound:\n\t\tret = kproto.Command_Status_NOT_FOUND\n\tcase RemoteVersionMismatch:\n\t\tret = kproto.Command_Status_VERSION_MISMATCH\n\tcase RemoteServiceBusy:\n\t\tret = kproto.Command_Status_SERVICE_BUSY\n\tcase RemoteExpired:\n\t\tret = kproto.Command_Status_EXPIRED\n\tcase RemoteDataError:\n\t\tret = kproto.Command_Status_DATA_ERROR\n\tcase RemotePermDataError:\n\t\tret = kproto.Command_Status_PERM_DATA_ERROR\n\tcase RemoteConnectionError:\n\t\tret = kproto.Command_Status_REMOTE_CONNECTION_ERROR\n\tcase RemoteNoSpace:\n\t\tret = kproto.Command_Status_NO_SPACE\n\tcase RemoteNoSuchHMACAlgorithm:\n\t\tret = kproto.Command_Status_NO_SUCH_HMAC_ALGORITHM\n\tcase RemoteInvalidRequest:\n\t\tret = kproto.Command_Status_INVALID_REQUEST\n\tcase RemoteNestedOperationErrors:\n\t\tret = kproto.Command_Status_NESTED_OPERATION_ERRORS\n\tcase RemoteDeviceLocked:\n\t\tret = kproto.Command_Status_DEVICE_LOCKED\n\tcase RemoteDeviceAlreadyUnlocked:\n\t\tret = kproto.Command_Status_DEVICE_ALREADY_UNLOCKED\n\tcase RemoteConnectionTerminated:\n\t\tret = kproto.Command_Status_CONNECTION_TERMINATED\n\tcase RemoteInvalidBatch:\n\t\tret = kproto.Command_Status_INVALID_BATCH\n\tcase RemoteHibernate:\n\t\tret = kproto.Command_Status_HIBERNATE\n\tcase RemoteShutdown:\n\t\tret = kproto.Command_Status_SHUTDOWN\n\t}\n\treturn ret\n}\n\nfunc convertStatusCodeFromProto(s kproto.Command_Status_StatusCode) StatusCode {\n\tret := RemoteOtherError\n\tswitch s {\n\tcase kproto.Command_Status_NOT_ATTEMPTED:\n\t\tret = RemoteNotAttempted\n\tcase kproto.Command_Status_SUCCESS:\n\t\tret = OK\n\tcase kproto.Command_Status_HMAC_FAILURE:\n\t\tret = RemoteHMACError\n\tcase kproto.Command_Status_NOT_AUTHORIZED:\n\t\tret = RemoteNotAuthorized\n\tcase kproto.Command_Status_VERSION_FAILURE:\n\t\tret = RemoteClusterVersionMismatch\n\tcase kproto.Command_Status_INTERNAL_ERROR:\n\t\tret = RemoteInternalError\n\tcase kproto.Command_Status_HEADER_REQUIRED:\n\t\tret = RemoteHeaderRequired\n\tcase kproto.Command_Status_NOT_FOUND:\n\t\tret = RemoteNotFound\n\tcase kproto.Command_Status_VERSION_MISMATCH:\n\t\tret = RemoteVersionMismatch\n\tcase kproto.Command_Status_SERVICE_BUSY:\n\t\tret = RemoteServiceBusy\n\tcase kproto.Command_Status_EXPIRED:\n\t\tret = RemoteExpired\n\tcase kproto.Command_Status_DATA_ERROR:\n\t\tret = RemoteDataError\n\tcase kproto.Command_Status_PERM_DATA_ERROR:\n\t\tret = RemotePermDataError\n\tcase kproto.Command_Status_REMOTE_CONNECTION_ERROR:\n\t\tret = RemoteConnectionError\n\tcase kproto.Command_Status_NO_SPACE:\n\t\tret = RemoteNoSpace\n\tcase kproto.Command_Status_NO_SUCH_HMAC_ALGORITHM:\n\t\tret = RemoteNoSuchHMACAlgorithm\n\tcase kproto.Command_Status_INVALID_REQUEST:\n\t\tret = RemoteInvalidRequest\n\tcase kproto.Command_Status_NESTED_OPERATION_ERRORS:\n\t\tret = RemoteNestedOperationErrors\n\tcase kproto.Command_Status_DEVICE_LOCKED:\n\t\tret = RemoteDeviceLocked\n\tcase kproto.Command_Status_DEVICE_ALREADY_UNLOCKED:\n\t\tret = RemoteDeviceAlreadyUnlocked\n\tcase kproto.Command_Status_CONNECTION_TERMINATED:\n\t\tret = RemoteConnectionTerminated\n\tcase kproto.Command_Status_INVALID_BATCH:\n\t\tret = RemoteInvalidBatch\n\tcase kproto.Command_Status_HIBERNATE:\n\t\tret = RemoteHibernate\n\tcase kproto.Command_Status_SHUTDOWN:\n\t\tret = RemoteShutdown\n\t}\n\treturn ret\n}\n\nfunc getStatusFromProto(cmd *kproto.Command) Status {\n\tcode := convertStatusCodeFromProto(cmd.GetStatus().GetCode())\n\tmsg := cmd.GetStatus().GetStatusMessage()\n\tversion := cmd.GetHeader().GetClusterVersion()\n\n\treturn Status{code, msg, version}\n}\n<|endoftext|>"}
{"text":"<commit_before>package smux\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ Stream implements net.Conn\ntype Stream struct {\n\tid   uint32\n\tsess *Session\n\n\tbuffers [][]byte\n\theads   [][]byte \/\/ slice heads kept for recycle\n\n\tbufferLock sync.Mutex\n\tframeSize  int\n\n\t\/\/ notify a read event\n\tchReadEvent chan struct{}\n\n\t\/\/ flag the stream has closed\n\tdie     chan struct{}\n\tdieOnce sync.Once\n\n\t\/\/ FIN\n\tchFinEvent   chan struct{}\n\tfinEventOnce sync.Once\n\n\t\/\/ deadlines\n\treadDeadline  atomic.Value\n\twriteDeadline atomic.Value\n\n\t\/\/ count writes\n\tnumWrite uint64\n}\n\n\/\/ newStream initiates a Stream struct\nfunc newStream(id uint32, frameSize int, sess *Session) *Stream {\n\ts := new(Stream)\n\ts.id = id\n\ts.chReadEvent = make(chan struct{}, 1)\n\ts.frameSize = frameSize\n\ts.sess = sess\n\ts.die = make(chan struct{})\n\ts.chFinEvent = make(chan struct{})\n\treturn s\n}\n\n\/\/ ID returns the unique stream ID.\nfunc (s *Stream) ID() uint32 {\n\treturn s.id\n}\n\n\/\/ Read implements net.Conn\nfunc (s *Stream) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tfor {\n\t\ts.bufferLock.Lock()\n\t\tif len(s.buffers) > 0 {\n\t\t\tn = copy(b, s.buffers[0])\n\t\t\ts.buffers[0] = s.buffers[0][n:]\n\t\t\tif len(s.buffers[0]) == 0 {\n\t\t\t\ts.buffers[0] = nil\n\t\t\t\ts.buffers = s.buffers[1:]\n\t\t\t\t\/\/ full recycle\n\t\t\t\tdefaultAllocator.Put(s.heads[0])\n\t\t\t\ts.heads = s.heads[1:]\n\t\t\t}\n\t\t}\n\t\ts.bufferLock.Unlock()\n\n\t\tif n > 0 {\n\t\t\ts.sess.returnTokens(n)\n\t\t\treturn n, nil\n\t\t}\n\n\t\tif ew := s.waitRead(); ew != nil {\n\t\t\treturn 0, ew\n\t\t}\n\t}\n}\n\n\/\/ WriteTo implements io.WriteTo\nfunc (s *Stream) WriteTo(w io.Writer) (n int64, err error) {\n\tfor {\n\t\tvar buf []byte\n\t\ts.bufferLock.Lock()\n\t\tif len(s.buffers) > 0 {\n\t\t\tbuf = s.buffers[0]\n\t\t\ts.buffers = s.buffers[1:]\n\t\t\ts.heads = s.heads[1:]\n\t\t}\n\t\ts.bufferLock.Unlock()\n\n\t\tif buf != nil {\n\t\t\tnw, ew := w.Write(buf)\n\t\t\tdefaultAllocator.Put(buf)\n\t\t\ts.sess.returnTokens(len(buf))\n\t\t\tif nw > 0 {\n\t\t\t\tn += int64(nw)\n\t\t\t}\n\n\t\t\tif ew != nil {\n\t\t\t\treturn n, ew\n\t\t\t}\n\t\t} else if ew := s.waitRead(); ew != nil {\n\t\t\treturn n, ew\n\t\t}\n\t}\n}\n\nfunc (s *Stream) waitRead() error {\n\tvar timer *time.Timer\n\tvar deadline <-chan time.Time\n\tif d, ok := s.readDeadline.Load().(time.Time); ok && !d.IsZero() {\n\t\ttimer = time.NewTimer(time.Until(d))\n\t\tdefer timer.Stop()\n\t\tdeadline = timer.C\n\t}\n\n\tselect {\n\tcase <-s.chReadEvent:\n\t\treturn nil\n\tcase <-s.chFinEvent:\n\t\treturn errors.WithStack(io.EOF)\n\tcase <-s.sess.chSocketReadError:\n\t\treturn s.sess.socketReadError.Load().(error)\n\tcase <-s.sess.chProtoError:\n\t\treturn s.sess.protoError.Load().(error)\n\tcase <-deadline:\n\t\treturn errors.WithStack(ErrTimeout)\n\tcase <-s.die:\n\t\treturn errors.WithStack(io.ErrClosedPipe)\n\t}\n\n}\n\n\/\/ Write implements net.Conn\nfunc (s *Stream) Write(b []byte) (n int, err error) {\n\tvar deadline <-chan time.Time\n\tif d, ok := s.writeDeadline.Load().(time.Time); ok && !d.IsZero() {\n\t\ttimer := time.NewTimer(time.Until(d))\n\t\tdefer timer.Stop()\n\t\tdeadline = timer.C\n\t}\n\n\t\/\/ check if stream has closed\n\tselect {\n\tcase <-s.die:\n\t\treturn 0, errors.WithStack(io.ErrClosedPipe)\n\tdefault:\n\t}\n\n\t\/\/ frame split and transmit\n\tsent := 0\n\tframe := newFrame(cmdPSH, s.id)\n\tbts := b\n\tfor len(bts) > 0 {\n\t\tsz := len(bts)\n\t\tif sz > s.frameSize {\n\t\t\tsz = s.frameSize\n\t\t}\n\t\tframe.data = bts[:sz]\n\t\tbts = bts[sz:]\n\t\tn, err := s.sess.writeFrameInternal(frame, deadline, s.numWrite)\n\t\ts.numWrite++\n\t\tsent += n\n\t\tif err != nil {\n\t\t\treturn sent, errors.WithStack(err)\n\t\t}\n\t}\n\n\treturn sent, nil\n}\n\n\/\/ Close implements net.Conn\nfunc (s *Stream) Close() error {\n\tvar once bool\n\tvar err error\n\ts.dieOnce.Do(func() {\n\t\tclose(s.die)\n\t\tonce = true\n\t})\n\n\tif once {\n\t\t_, err = s.sess.writeFrame(newFrame(cmdFIN, s.id))\n\t\ts.sess.streamClosed(s.id)\n\t\treturn err\n\t} else {\n\t\treturn errors.WithStack(io.ErrClosedPipe)\n\t}\n}\n\n\/\/ GetDieCh returns a readonly chan which can be readable\n\/\/ when the stream is to be closed.\nfunc (s *Stream) GetDieCh() <-chan struct{} {\n\treturn s.die\n}\n\n\/\/ SetReadDeadline sets the read deadline as defined by\n\/\/ net.Conn.SetReadDeadline.\n\/\/ A zero time value disables the deadline.\nfunc (s *Stream) SetReadDeadline(t time.Time) error {\n\ts.readDeadline.Store(t)\n\treturn nil\n}\n\n\/\/ SetWriteDeadline sets the write deadline as defined by\n\/\/ net.Conn.SetWriteDeadline.\n\/\/ A zero time value disables the deadline.\nfunc (s *Stream) SetWriteDeadline(t time.Time) error {\n\ts.writeDeadline.Store(t)\n\treturn nil\n}\n\n\/\/ SetDeadline sets both read and write deadlines as defined by\n\/\/ net.Conn.SetDeadline.\n\/\/ A zero time value disables the deadlines.\nfunc (s *Stream) SetDeadline(t time.Time) error {\n\tif err := s.SetReadDeadline(t); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tif err := s.SetWriteDeadline(t); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}\n\n\/\/ session closes\nfunc (s *Stream) sessionClose() { s.dieOnce.Do(func() { close(s.die) }) }\n\n\/\/ LocalAddr satisfies net.Conn interface\nfunc (s *Stream) LocalAddr() net.Addr {\n\tif ts, ok := s.sess.conn.(interface {\n\t\tLocalAddr() net.Addr\n\t}); ok {\n\t\treturn ts.LocalAddr()\n\t}\n\treturn nil\n}\n\n\/\/ RemoteAddr satisfies net.Conn interface\nfunc (s *Stream) RemoteAddr() net.Addr {\n\tif ts, ok := s.sess.conn.(interface {\n\t\tRemoteAddr() net.Addr\n\t}); ok {\n\t\treturn ts.RemoteAddr()\n\t}\n\treturn nil\n}\n\n\/\/ pushBytes append buf to buffers\nfunc (s *Stream) pushBytes(buf []byte) (written int, err error) {\n\ts.bufferLock.Lock()\n\ts.buffers = append(s.buffers, buf)\n\ts.heads = append(s.heads, buf)\n\ts.bufferLock.Unlock()\n\treturn\n}\n\n\/\/ recycleTokens transform remaining bytes to tokens(will truncate buffer)\nfunc (s *Stream) recycleTokens() (n int) {\n\ts.bufferLock.Lock()\n\tfor k := range s.buffers {\n\t\tn += len(s.buffers[k])\n\t\tdefaultAllocator.Put(s.heads[k])\n\t}\n\ts.buffers = nil\n\ts.heads = nil\n\ts.bufferLock.Unlock()\n\treturn\n}\n\n\/\/ notify read event\nfunc (s *Stream) notifyReadEvent() {\n\tselect {\n\tcase s.chReadEvent <- struct{}{}:\n\tdefault:\n\t}\n}\n\n\/\/ mark this stream has been closed in protocol\nfunc (s *Stream) fin() {\n\ts.finEventOnce.Do(func() {\n\t\tclose(s.chFinEvent)\n\t})\n}\n<commit_msg>fix a possible race condition<commit_after>package smux\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ Stream implements net.Conn\ntype Stream struct {\n\tid   uint32\n\tsess *Session\n\n\tbuffers [][]byte\n\theads   [][]byte \/\/ slice heads kept for recycle\n\n\tbufferLock sync.Mutex\n\tframeSize  int\n\n\t\/\/ notify a read event\n\tchReadEvent chan struct{}\n\n\t\/\/ flag the stream has closed\n\tdie     chan struct{}\n\tdieOnce sync.Once\n\n\t\/\/ FIN\n\tchFinEvent   chan struct{}\n\tfinEventOnce sync.Once\n\n\t\/\/ deadlines\n\treadDeadline  atomic.Value\n\twriteDeadline atomic.Value\n\n\t\/\/ count writes\n\tnumWrite uint64\n}\n\n\/\/ newStream initiates a Stream struct\nfunc newStream(id uint32, frameSize int, sess *Session) *Stream {\n\ts := new(Stream)\n\ts.id = id\n\ts.chReadEvent = make(chan struct{}, 1)\n\ts.frameSize = frameSize\n\ts.sess = sess\n\ts.die = make(chan struct{})\n\ts.chFinEvent = make(chan struct{})\n\treturn s\n}\n\n\/\/ ID returns the unique stream ID.\nfunc (s *Stream) ID() uint32 {\n\treturn s.id\n}\n\n\/\/ Read implements net.Conn\nfunc (s *Stream) Read(b []byte) (n int, err error) {\n\tif len(b) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tfor {\n\t\ts.bufferLock.Lock()\n\t\tif len(s.buffers) > 0 {\n\t\t\tn = copy(b, s.buffers[0])\n\t\t\ts.buffers[0] = s.buffers[0][n:]\n\t\t\tif len(s.buffers[0]) == 0 {\n\t\t\t\ts.buffers[0] = nil\n\t\t\t\ts.buffers = s.buffers[1:]\n\t\t\t\t\/\/ full recycle\n\t\t\t\tdefaultAllocator.Put(s.heads[0])\n\t\t\t\ts.heads = s.heads[1:]\n\t\t\t}\n\t\t}\n\t\ts.bufferLock.Unlock()\n\n\t\tif n > 0 {\n\t\t\ts.sess.returnTokens(n)\n\t\t\treturn n, nil\n\t\t}\n\n\t\tif ew := s.waitRead(); ew != nil {\n\t\t\treturn 0, ew\n\t\t}\n\t}\n}\n\n\/\/ WriteTo implements io.WriteTo\nfunc (s *Stream) WriteTo(w io.Writer) (n int64, err error) {\n\tfor {\n\t\tvar buf []byte\n\t\ts.bufferLock.Lock()\n\t\tif len(s.buffers) > 0 {\n\t\t\tbuf = s.buffers[0]\n\t\t\ts.buffers = s.buffers[1:]\n\t\t\ts.heads = s.heads[1:]\n\t\t}\n\t\ts.bufferLock.Unlock()\n\n\t\tif buf != nil {\n\t\t\tnw, ew := w.Write(buf)\n\t\t\ts.sess.returnTokens(len(buf))\n\t\t\tdefaultAllocator.Put(buf)\n\t\t\tif nw > 0 {\n\t\t\t\tn += int64(nw)\n\t\t\t}\n\n\t\t\tif ew != nil {\n\t\t\t\treturn n, ew\n\t\t\t}\n\t\t} else if ew := s.waitRead(); ew != nil {\n\t\t\treturn n, ew\n\t\t}\n\t}\n}\n\nfunc (s *Stream) waitRead() error {\n\tvar timer *time.Timer\n\tvar deadline <-chan time.Time\n\tif d, ok := s.readDeadline.Load().(time.Time); ok && !d.IsZero() {\n\t\ttimer = time.NewTimer(time.Until(d))\n\t\tdefer timer.Stop()\n\t\tdeadline = timer.C\n\t}\n\n\tselect {\n\tcase <-s.chReadEvent:\n\t\treturn nil\n\tcase <-s.chFinEvent:\n\t\treturn errors.WithStack(io.EOF)\n\tcase <-s.sess.chSocketReadError:\n\t\treturn s.sess.socketReadError.Load().(error)\n\tcase <-s.sess.chProtoError:\n\t\treturn s.sess.protoError.Load().(error)\n\tcase <-deadline:\n\t\treturn errors.WithStack(ErrTimeout)\n\tcase <-s.die:\n\t\treturn errors.WithStack(io.ErrClosedPipe)\n\t}\n\n}\n\n\/\/ Write implements net.Conn\nfunc (s *Stream) Write(b []byte) (n int, err error) {\n\tvar deadline <-chan time.Time\n\tif d, ok := s.writeDeadline.Load().(time.Time); ok && !d.IsZero() {\n\t\ttimer := time.NewTimer(time.Until(d))\n\t\tdefer timer.Stop()\n\t\tdeadline = timer.C\n\t}\n\n\t\/\/ check if stream has closed\n\tselect {\n\tcase <-s.die:\n\t\treturn 0, errors.WithStack(io.ErrClosedPipe)\n\tdefault:\n\t}\n\n\t\/\/ frame split and transmit\n\tsent := 0\n\tframe := newFrame(cmdPSH, s.id)\n\tbts := b\n\tfor len(bts) > 0 {\n\t\tsz := len(bts)\n\t\tif sz > s.frameSize {\n\t\t\tsz = s.frameSize\n\t\t}\n\t\tframe.data = bts[:sz]\n\t\tbts = bts[sz:]\n\t\tn, err := s.sess.writeFrameInternal(frame, deadline, s.numWrite)\n\t\ts.numWrite++\n\t\tsent += n\n\t\tif err != nil {\n\t\t\treturn sent, errors.WithStack(err)\n\t\t}\n\t}\n\n\treturn sent, nil\n}\n\n\/\/ Close implements net.Conn\nfunc (s *Stream) Close() error {\n\tvar once bool\n\tvar err error\n\ts.dieOnce.Do(func() {\n\t\tclose(s.die)\n\t\tonce = true\n\t})\n\n\tif once {\n\t\t_, err = s.sess.writeFrame(newFrame(cmdFIN, s.id))\n\t\ts.sess.streamClosed(s.id)\n\t\treturn err\n\t} else {\n\t\treturn errors.WithStack(io.ErrClosedPipe)\n\t}\n}\n\n\/\/ GetDieCh returns a readonly chan which can be readable\n\/\/ when the stream is to be closed.\nfunc (s *Stream) GetDieCh() <-chan struct{} {\n\treturn s.die\n}\n\n\/\/ SetReadDeadline sets the read deadline as defined by\n\/\/ net.Conn.SetReadDeadline.\n\/\/ A zero time value disables the deadline.\nfunc (s *Stream) SetReadDeadline(t time.Time) error {\n\ts.readDeadline.Store(t)\n\treturn nil\n}\n\n\/\/ SetWriteDeadline sets the write deadline as defined by\n\/\/ net.Conn.SetWriteDeadline.\n\/\/ A zero time value disables the deadline.\nfunc (s *Stream) SetWriteDeadline(t time.Time) error {\n\ts.writeDeadline.Store(t)\n\treturn nil\n}\n\n\/\/ SetDeadline sets both read and write deadlines as defined by\n\/\/ net.Conn.SetDeadline.\n\/\/ A zero time value disables the deadlines.\nfunc (s *Stream) SetDeadline(t time.Time) error {\n\tif err := s.SetReadDeadline(t); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tif err := s.SetWriteDeadline(t); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}\n\n\/\/ session closes\nfunc (s *Stream) sessionClose() { s.dieOnce.Do(func() { close(s.die) }) }\n\n\/\/ LocalAddr satisfies net.Conn interface\nfunc (s *Stream) LocalAddr() net.Addr {\n\tif ts, ok := s.sess.conn.(interface {\n\t\tLocalAddr() net.Addr\n\t}); ok {\n\t\treturn ts.LocalAddr()\n\t}\n\treturn nil\n}\n\n\/\/ RemoteAddr satisfies net.Conn interface\nfunc (s *Stream) RemoteAddr() net.Addr {\n\tif ts, ok := s.sess.conn.(interface {\n\t\tRemoteAddr() net.Addr\n\t}); ok {\n\t\treturn ts.RemoteAddr()\n\t}\n\treturn nil\n}\n\n\/\/ pushBytes append buf to buffers\nfunc (s *Stream) pushBytes(buf []byte) (written int, err error) {\n\ts.bufferLock.Lock()\n\ts.buffers = append(s.buffers, buf)\n\ts.heads = append(s.heads, buf)\n\ts.bufferLock.Unlock()\n\treturn\n}\n\n\/\/ recycleTokens transform remaining bytes to tokens(will truncate buffer)\nfunc (s *Stream) recycleTokens() (n int) {\n\ts.bufferLock.Lock()\n\tfor k := range s.buffers {\n\t\tn += len(s.buffers[k])\n\t\tdefaultAllocator.Put(s.heads[k])\n\t}\n\ts.buffers = nil\n\ts.heads = nil\n\ts.bufferLock.Unlock()\n\treturn\n}\n\n\/\/ notify read event\nfunc (s *Stream) notifyReadEvent() {\n\tselect {\n\tcase s.chReadEvent <- struct{}{}:\n\tdefault:\n\t}\n}\n\n\/\/ mark this stream has been closed in protocol\nfunc (s *Stream) fin() {\n\ts.finEventOnce.Do(func() {\n\t\tclose(s.chFinEvent)\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package quic\n\nimport (\n\t\"github.com\/lucas-clemente\/quic-go\/frames\"\n\t\"github.com\/lucas-clemente\/quic-go\/protocol\"\n\t\"github.com\/lucas-clemente\/quic-go\/utils\"\n)\n\n\/\/ A Stream assembles the data from StreamFrames and provides a super-convenient Read-Interface\ntype Stream struct {\n\tSession        *Session\n\tStreamID       protocol.StreamID\n\tStreamFrames   chan *frames.StreamFrame\n\tCurrentFrame   *frames.StreamFrame\n\tReadPosInFrame int\n\tWriteOffset    uint64\n}\n\n\/\/ NewStream creates a new Stream\nfunc NewStream(session *Session, StreamID protocol.StreamID) *Stream {\n\treturn &Stream{\n\t\tSession:      session,\n\t\tStreamID:     StreamID,\n\t\tStreamFrames: make(chan *frames.StreamFrame, 8), \/\/ ToDo: add config option for this number\n\t}\n}\n\n\/\/ Read reads data\nfunc (s *Stream) Read(p []byte) (int, error) {\n\tbytesRead := 0\n\tfor bytesRead < len(p) {\n\t\tif s.CurrentFrame == nil {\n\t\t\tselect {\n\t\t\tcase s.CurrentFrame = <-s.StreamFrames:\n\t\t\tdefault:\n\t\t\t\tif bytesRead == 0 {\n\t\t\t\t\ts.CurrentFrame = <-s.StreamFrames\n\t\t\t\t} else {\n\t\t\t\t\treturn bytesRead, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\ts.ReadPosInFrame = 0\n\t\t}\n\t\tm := utils.Min(len(p)-bytesRead, len(s.CurrentFrame.Data)-s.ReadPosInFrame)\n\t\tcopy(p[bytesRead:], s.CurrentFrame.Data[s.ReadPosInFrame:])\n\t\ts.ReadPosInFrame += m\n\t\tbytesRead += m\n\t\tif s.ReadPosInFrame >= len(s.CurrentFrame.Data) {\n\t\t\ts.CurrentFrame = nil\n\t\t}\n\t}\n\n\treturn bytesRead, nil\n}\n\n\/\/ ReadByte implements io.ByteReader\nfunc (s *Stream) ReadByte() (byte, error) {\n\t\/\/ TODO: Optimize\n\tp := make([]byte, 1)\n\tn, err := s.Read(p)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif n != 1 {\n\t\tpanic(\"Stream: should have returned error\")\n\t}\n\treturn p[0], nil\n}\n\nfunc (s *Stream) Write(p []byte) (int, error) {\n\tframe := &frames.StreamFrame{\n\t\tStreamID: s.StreamID,\n\t\tOffset:   s.WriteOffset,\n\t\tData:     p,\n\t}\n\terr := s.Session.SendFrames([]frames.Frame{frame})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ts.WriteOffset += uint64(len(p))\n\treturn len(p), nil\n}\n\n\/\/ AddStreamFrame adds a new stream frame\nfunc (s *Stream) AddStreamFrame(frame *frames.StreamFrame) error {\n\ts.StreamFrames <- frame\n\treturn nil\n}\n<commit_msg>add stream.Close<commit_after>package quic\n\nimport (\n\t\"github.com\/lucas-clemente\/quic-go\/frames\"\n\t\"github.com\/lucas-clemente\/quic-go\/protocol\"\n\t\"github.com\/lucas-clemente\/quic-go\/utils\"\n)\n\n\/\/ A Stream assembles the data from StreamFrames and provides a super-convenient Read-Interface\ntype Stream struct {\n\tSession        *Session\n\tStreamID       protocol.StreamID\n\tStreamFrames   chan *frames.StreamFrame\n\tCurrentFrame   *frames.StreamFrame\n\tReadPosInFrame int\n\tWriteOffset    uint64\n}\n\n\/\/ NewStream creates a new Stream\nfunc NewStream(session *Session, StreamID protocol.StreamID) *Stream {\n\treturn &Stream{\n\t\tSession:      session,\n\t\tStreamID:     StreamID,\n\t\tStreamFrames: make(chan *frames.StreamFrame, 8), \/\/ ToDo: add config option for this number\n\t}\n}\n\n\/\/ Read reads data\nfunc (s *Stream) Read(p []byte) (int, error) {\n\tbytesRead := 0\n\tfor bytesRead < len(p) {\n\t\tif s.CurrentFrame == nil {\n\t\t\tselect {\n\t\t\tcase s.CurrentFrame = <-s.StreamFrames:\n\t\t\tdefault:\n\t\t\t\tif bytesRead == 0 {\n\t\t\t\t\ts.CurrentFrame = <-s.StreamFrames\n\t\t\t\t} else {\n\t\t\t\t\treturn bytesRead, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\ts.ReadPosInFrame = 0\n\t\t}\n\t\tm := utils.Min(len(p)-bytesRead, len(s.CurrentFrame.Data)-s.ReadPosInFrame)\n\t\tcopy(p[bytesRead:], s.CurrentFrame.Data[s.ReadPosInFrame:])\n\t\ts.ReadPosInFrame += m\n\t\tbytesRead += m\n\t\tif s.ReadPosInFrame >= len(s.CurrentFrame.Data) {\n\t\t\ts.CurrentFrame = nil\n\t\t}\n\t}\n\n\treturn bytesRead, nil\n}\n\n\/\/ ReadByte implements io.ByteReader\nfunc (s *Stream) ReadByte() (byte, error) {\n\t\/\/ TODO: Optimize\n\tp := make([]byte, 1)\n\tn, err := s.Read(p)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif n != 1 {\n\t\tpanic(\"Stream: should have returned error\")\n\t}\n\treturn p[0], nil\n}\n\nfunc (s *Stream) Write(p []byte) (int, error) {\n\tframe := &frames.StreamFrame{\n\t\tStreamID: s.StreamID,\n\t\tOffset:   s.WriteOffset,\n\t\tData:     p,\n\t}\n\terr := s.Session.SendFrames([]frames.Frame{frame})\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ts.WriteOffset += uint64(len(p))\n\treturn len(p), nil\n}\n\nfunc (s *Stream) Close() error {\n\treturn s.Session.SendFrame(&frames.StreamFrame{\n\t\tStreamID: s.StreamID,\n\t\tOffset:   s.WriteOffset,\n\t\tFinBit:   true,\n\t})\n}\n\n\/\/ AddStreamFrame adds a new stream frame\nfunc (s *Stream) AddStreamFrame(frame *frames.StreamFrame) error {\n\ts.StreamFrames <- frame\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package null provides an opinionated yet reasonable way of handling null values.\npackage null\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n)\n\n\/\/ String is a nullable string.\ntype String struct {\n\tsql.NullString\n}\n\n\/\/ StringFrom creates a new String that will be null if s is blank.\nfunc StringFrom(s string) String {\n\treturn NewString(s, s != \"\")\n}\n\n\/\/ NewString creates a new String\nfunc NewString(s string, valid bool) String {\n\treturn String{\n\t\tNullString: sql.NullString{\n\t\t\tString: s,\n\t\t\tValid:  s != \"\",\n\t\t},\n\t}\n}\n\n\/\/ UnmarshalJSON implements json.Unmarshaler.\n\/\/ It supports string and null input. Blank string input produces a null String.\n\/\/ It also supports unmarshalling a sql.NullString.\nfunc (s *String) UnmarshalJSON(data []byte) error {\n\tvar err error\n\tvar v interface{}\n\tjson.Unmarshal(data, &v)\n\tswitch v.(type) {\n\tcase string:\n\t\terr = json.Unmarshal(data, &s.String)\n\tcase map[string]interface{}:\n\t\terr = json.Unmarshal(data, &s.NullString)\n\tcase nil:\n\t\ts.Valid = false\n\t\treturn nil\n\t}\n\ts.Valid = (err == nil) && (s.String != \"\")\n\treturn err\n}\n\n\/\/ MarshalText implements encoding.TextMarshaler.\n\/\/ It will encode a blank string when this String is null.\nfunc (s String) MarshalText() ([]byte, error) {\n\tif !s.Valid {\n\t\treturn []byte{}, nil\n\t}\n\treturn []byte(s.String), nil\n}\n\n\/\/ UnmarshalText implements encoding.TextUnmarshaler.\n\/\/ It will unmarshal to a null String if the input is a blank string.\nfunc (s *String) UnmarshalText(text []byte) error {\n\ts.String = string(text)\n\ts.Valid = s.String != \"\"\n\treturn nil\n}\n\n\/\/ Pointer returns a pointer to this String's value, or a nil pointer if this String is null.\nfunc (s String) Pointer() *string {\n\tif s.String == \"\" {\n\t\treturn nil\n\t}\n\treturn &s.String\n}\n\n\/\/ IsZero returns true for null or empty strings, for future omitempty support. (Go 1.4?)\nfunc (s String) IsZero() bool {\n\treturn !s.Valid || s.String == \"\"\n}\n<commit_msg>fix NewString()<commit_after>\/\/ Package null provides an opinionated yet reasonable way of handling null values.\npackage null\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n)\n\n\/\/ String is a nullable string.\ntype String struct {\n\tsql.NullString\n}\n\n\/\/ StringFrom creates a new String that will be null if s is blank.\nfunc StringFrom(s string) String {\n\treturn NewString(s, s != \"\")\n}\n\n\/\/ NewString creates a new String\nfunc NewString(s string, valid bool) String {\n\treturn String{\n\t\tNullString: sql.NullString{\n\t\t\tString: s,\n\t\t\tValid:  valid,\n\t\t},\n\t}\n}\n\n\/\/ UnmarshalJSON implements json.Unmarshaler.\n\/\/ It supports string and null input. Blank string input produces a null String.\n\/\/ It also supports unmarshalling a sql.NullString.\nfunc (s *String) UnmarshalJSON(data []byte) error {\n\tvar err error\n\tvar v interface{}\n\tjson.Unmarshal(data, &v)\n\tswitch v.(type) {\n\tcase string:\n\t\terr = json.Unmarshal(data, &s.String)\n\tcase map[string]interface{}:\n\t\terr = json.Unmarshal(data, &s.NullString)\n\tcase nil:\n\t\ts.Valid = false\n\t\treturn nil\n\t}\n\ts.Valid = (err == nil) && (s.String != \"\")\n\treturn err\n}\n\n\/\/ MarshalText implements encoding.TextMarshaler.\n\/\/ It will encode a blank string when this String is null.\nfunc (s String) MarshalText() ([]byte, error) {\n\tif !s.Valid {\n\t\treturn []byte{}, nil\n\t}\n\treturn []byte(s.String), nil\n}\n\n\/\/ UnmarshalText implements encoding.TextUnmarshaler.\n\/\/ It will unmarshal to a null String if the input is a blank string.\nfunc (s *String) UnmarshalText(text []byte) error {\n\ts.String = string(text)\n\ts.Valid = s.String != \"\"\n\treturn nil\n}\n\n\/\/ Pointer returns a pointer to this String's value, or a nil pointer if this String is null.\nfunc (s String) Pointer() *string {\n\tif s.String == \"\" {\n\t\treturn nil\n\t}\n\treturn &s.String\n}\n\n\/\/ IsZero returns true for null or empty strings, for future omitempty support. (Go 1.4?)\nfunc (s String) IsZero() bool {\n\treturn !s.Valid || s.String == \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Marshalling and unmarshalling of\n\/\/ bit torrent bencode data into Go structs using reflection.\n\/\/\n\/\/ Based upon the standard Go language JSON package.\n\npackage bencode\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype structBuilder struct {\n\tval reflect.Value\n\n\t\/\/ if map_ != nil, write val to map_[key] on each change\n\tmap_ *reflect.MapValue\n\tkey  reflect.Value\n}\n\nvar nobuilder *structBuilder\n\nfunc isfloat(v reflect.Value) bool {\n\tswitch v.(type) {\n\tcase *reflect.FloatValue:\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc setfloat(v reflect.Value, f float64) {\n\tswitch v := v.(type) {\n\tcase *reflect.FloatValue:\n\t\tv.Set(f)\n\t}\n}\n\nfunc setint(val reflect.Value, i int64) {\n\tswitch v := val.(type) {\n\tcase *reflect.IntValue:\n\t\tv.Set(int64(i))\n\tcase *reflect.UintValue:\n\t\tv.Set(uint64(i))\n\tcase *reflect.InterfaceValue:\n\t\tv.Set(reflect.NewValue(i))\n\t}\n}\n\n\/\/ If updating b.val is not enough to update the original,\n\/\/ copy a changed b.val out to the original.\nfunc (b *structBuilder) Flush() {\n\tif b == nil {\n\t\treturn\n\t}\n\tif b.map_ != nil {\n\t\tb.map_.SetElem(b.key, b.val)\n\t}\n}\n\nfunc (b *structBuilder) Int64(i int64) {\n\tif b == nil {\n\t\treturn\n\t}\n\tv := b.val\n\tif isfloat(v) {\n\t\tsetfloat(v, float64(i))\n\t} else {\n\t\tsetint(v, i)\n\t}\n}\n\nfunc (b *structBuilder) Uint64(i uint64) {\n\tif b == nil {\n\t\treturn\n\t}\n\tv := b.val\n\tif isfloat(v) {\n\t\tsetfloat(v, float64(i))\n\t} else {\n\t\tsetint(v, int64(i))\n\t}\n}\n\nfunc (b *structBuilder) Float64(f float64) {\n\tif b == nil {\n\t\treturn\n\t}\n\tv := b.val\n\tif isfloat(v) {\n\t\tsetfloat(v, f)\n\t} else {\n\t\tsetint(v, int64(f))\n\t}\n}\n\nfunc (b *structBuilder) String(s string) {\n\tif b == nil {\n\t\treturn\n\t}\n\n\tswitch v := b.val.(type) {\n\tcase *reflect.StringValue:\n\t\tv.Set(s)\n\tcase *reflect.InterfaceValue:\n\t\tv.Set(reflect.NewValue(s))\n\t}\n}\n\nfunc (b *structBuilder) Array() {\n\tif b == nil {\n\t\treturn\n\t}\n\tif v, ok := b.val.(*reflect.SliceValue); ok {\n\t\tif v.IsNil() {\n\t\t\tv.Set(reflect.MakeSlice(v.Type().(*reflect.SliceType), 0, 8))\n\t\t}\n\t}\n}\n\nfunc (b *structBuilder) Elem(i int) Builder {\n\tif b == nil || i < 0 {\n\t\treturn nobuilder\n\t}\n\tswitch v := b.val.(type) {\n\tcase *reflect.ArrayValue:\n\t\tif i < v.Len() {\n\t\t\treturn &structBuilder{val: v.Elem(i)}\n\t\t}\n\tcase *reflect.SliceValue:\n\t\tif i >= v.Cap() {\n\t\t\tn := v.Cap()\n\t\t\tif n < 8 {\n\t\t\t\tn = 8\n\t\t\t}\n\t\t\tfor n <= i {\n\t\t\t\tn *= 2\n\t\t\t}\n\t\t\tnv := reflect.MakeSlice(v.Type().(*reflect.SliceType), v.Len(), n)\n\t\t\treflect.ArrayCopy(nv, v)\n\t\t\tv.Set(nv)\n\t\t}\n\t\tif v.Len() <= i && i < v.Cap() {\n\t\t\tv.SetLen(i + 1)\n\t\t}\n\t\tif i < v.Len() {\n\t\t\treturn &structBuilder{val: v.Elem(i)}\n\t\t}\n\t}\n\treturn nobuilder\n}\n\nfunc (b *structBuilder) Map() {\n\tif b == nil {\n\t\treturn\n\t}\n\tif v, ok := b.val.(*reflect.PtrValue); ok && v.IsNil() {\n\t\tif v.IsNil() {\n\t\t\tv.PointTo(reflect.MakeZero(v.Type().(*reflect.PtrType).Elem()))\n\t\t\tb.Flush()\n\t\t}\n\t\tb.map_ = nil\n\t\tb.val = v.Elem()\n\t}\n\tif v, ok := b.val.(*reflect.MapValue); ok && v.IsNil() {\n\t\tv.Set(reflect.MakeMap(v.Type().(*reflect.MapType)))\n\t}\n}\n\nfunc (b *structBuilder) Key(k string) Builder {\n\tif b == nil {\n\t\treturn nobuilder\n\t}\n\tswitch v := reflect.Indirect(b.val).(type) {\n\tcase *reflect.StructValue:\n\t\tt := v.Type().(*reflect.StructType)\n\t\t\/\/ Case-insensitive field lookup.\n\t\tk = strings.ToLower(k)\n\t\tfor i := 0; i < t.NumField(); i++ {\n\t\t\tfield := t.Field(i)\n\t\t\tif strings.ToLower(field.Tag) == k ||\n\t\t\t\tstrings.ToLower(field.Name) == k {\n\t\t\t\treturn &structBuilder{val: v.Field(i)}\n\t\t\t}\n\t\t}\n\tcase *reflect.MapValue:\n\t\tt := v.Type().(*reflect.MapType)\n\t\tif t.Key() != reflect.Typeof(k) {\n\t\t\tbreak\n\t\t}\n\t\tkey := reflect.NewValue(k)\n\t\telem := v.Elem(key)\n\t\tif elem == nil {\n\t\t\tv.SetElem(key, reflect.MakeZero(t.Elem()))\n\t\t\telem = v.Elem(key)\n\t\t}\n\t\treturn &structBuilder{val: elem, map_: v, key: key}\n\t}\n\treturn nobuilder\n}\n\n\/\/ Unmarshal parses the bencode syntax string s and fills in\n\/\/ an arbitrary struct or slice pointed at by val.\n\/\/ It uses the reflect package to assign to fields\n\/\/ and arrays embedded in val.  Well-formed data that does not fit\n\/\/ into the struct is discarded.\n\/\/\n\/\/ For example, given these definitions:\n\/\/\n\/\/\ttype Email struct {\n\/\/\t\tWhere string;\n\/\/\t\tAddr string;\n\/\/\t}\n\/\/\n\/\/\ttype Result struct {\n\/\/\t\tName string;\n\/\/\t\tPhone string;\n\/\/\t\tEmail []Email\n\/\/\t}\n\/\/\n\/\/\tvar r = Result{ \"name\", \"phone\", nil }\n\/\/\n\/\/ unmarshalling the bencode syntax string\n\/\/\n\/\/\td5:emailld5:where4:home4:addr15:gre@example.come\\\n\/\/  d5:where4:work4:addr12:gre@work.comee4:name14:Gr\\\n\/\/  ace R. Emlin7:address15:123 Main Streete\n\/\/\n\/\/ via Unmarshal(s, &r) is equivalent to assigning\n\/\/\n\/\/\tr = Result{\n\/\/\t\t\"Grace R. Emlin\",\t\/\/ name\n\/\/\t\t\"phone\",\t\t\/\/ no phone given\n\/\/\t\t[]Email{\n\/\/\t\t\tEmail{ \"home\", \"gre@example.com\" },\n\/\/\t\t\tEmail{ \"work\", \"gre@work.com\" }\n\/\/\t\t}\n\/\/\t}\n\/\/\n\/\/ Note that the field r.Phone has not been modified and\n\/\/ that the bencode field \"address\" was discarded.\n\/\/\n\/\/ Because Unmarshal uses the reflect package, it can only\n\/\/ assign to upper case fields.  Unmarshal uses a case-insensitive\n\/\/ comparison to match bencode field names to struct field names.\n\/\/\n\/\/ If you provide a tag string for a struct member, the tag string\n\/\/ will be used as the bencode dictionary key for that member.\n\/\/\n\/\/ To unmarshal a top-level bencode array, pass in a pointer to an empty\n\/\/ slice of the correct type.\n\/\/\n\nfunc Unmarshal(r io.Reader, val interface{}) (err os.Error) {\n\t\/\/ If e represents a value, the answer won't get back to the\n\t\/\/ caller.  Make sure it's a pointer.\n\tif _, ok := reflect.Typeof(val).(*reflect.PtrType); !ok {\n\t\terr = os.ErrorString(\"Attempt to unmarshal into a non-pointer\")\n\t\treturn\n\t}\n\terr = UnmarshalValue(r, reflect.NewValue(val))\n\treturn\n}\n\n\/\/ This API is public primarily to make testing easier, but it is available if you\n\/\/ have a use for it.\n\nfunc UnmarshalValue(r io.Reader, v reflect.Value) (err os.Error) {\n\tvar b *structBuilder\n\n\t\/\/ If val is a pointer to a slice, we append to the slice.\n\tif ptr, ok := v.(*reflect.PtrValue); ok {\n\t\tif slice, ok := ptr.Elem().(*reflect.SliceValue); ok {\n\t\t\tb = &structBuilder{val: slice}\n\t\t}\n\t}\n\n\tif b == nil {\n\t\tb = &structBuilder{val: v}\n\t}\n\n\terr = Parse(r, b)\n\treturn\n}\n\ntype MarshalError struct {\n\tT reflect.Type\n}\n\nfunc (e *MarshalError) String() string {\n\treturn \"bencode cannot encode value of type \" + e.T.String()\n}\n\nfunc writeArrayOrSlice(w io.Writer, val reflect.ArrayOrSliceValue) (err os.Error) {\n\t_, err = fmt.Fprint(w, \"l\")\n\tif err != nil {\n\t\treturn\n\t}\n\tfor i := 0; i < val.Len(); i++ {\n\t\tif err := writeValue(w, val.Elem(i)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t_, err = fmt.Fprint(w, \"e\")\n\tif err != nil {\n\t\treturn\n\t}\n\treturn nil\n}\n\ntype StringValue struct {\n\tkey   string\n\tvalue reflect.Value\n}\n\ntype StringValueArray []StringValue\n\n\/\/ Satisfy sort.Interface\n\nfunc (a StringValueArray) Len() int { return len(a) }\n\nfunc (a StringValueArray) Less(i, j int) bool { return a[i].key < a[j].key }\n\nfunc (a StringValueArray) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\n\nfunc writeSVList(w io.Writer, svList StringValueArray) (err os.Error) {\n\tsort.Sort(svList)\n\n\tfor _, sv := range (svList) {\n\t\tif isValueNil(sv.value) {\n\t\t\tcontinue \/\/ Skip null values\n\t\t}\n\t\ts := sv.key\n\t\t_, err = fmt.Fprintf(w, \"%d:%s\", len(s), s)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif err = writeValue(w, sv.value); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\n\nfunc writeMap(w io.Writer, val *reflect.MapValue) (err os.Error) {\n\tkey := val.Type().(*reflect.MapType).Key()\n\tif _, ok := key.(*reflect.StringType); !ok {\n\t\treturn &MarshalError{val.Type()}\n\t}\n\t_, err = fmt.Fprint(w, \"d\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tkeys := val.Keys()\n\n\t\/\/ Sort keys\n\n\tsvList := make(StringValueArray, len(keys))\n\tfor i, key := range (keys) {\n\t\tsvList[i].key = key.(*reflect.StringValue).Get()\n\t\tsvList[i].value = val.Elem(key)\n\t}\n\n\terr = writeSVList(w, svList)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t_, err = fmt.Fprint(w, \"e\")\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}\n\nfunc writeStruct(w io.Writer, val *reflect.StructValue) (err os.Error) {\n\t_, err = fmt.Fprint(w, \"d\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\ttyp := val.Type().(*reflect.StructType)\n\n\tnumFields := val.NumField()\n\tsvList := make(StringValueArray, numFields)\n\n\tfor i := 0; i < numFields; i++ {\n\t\tfield := typ.Field(i)\n\t\tkey := field.Name\n\t\tif len(field.Tag) > 0 {\n\t\t\tkey = field.Tag\n\t\t}\n\t\tsvList[i].key = key\n\t\tsvList[i].value = val.Field(i)\n\t}\n\n\terr = writeSVList(w, svList)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t_, err = fmt.Fprint(w, \"e\")\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}\n\nfunc writeValue(w io.Writer, val reflect.Value) (err os.Error) {\n\tif val == nil {\n\t\terr = os.NewError(\"Can't write null value\")\n\t\treturn\n\t}\n\n\tswitch v := val.(type) {\n\tcase *reflect.StringValue:\n\t\ts := v.Get()\n\t\t_, err = fmt.Fprintf(w, \"%d:%s\", len(s), s)\n\tcase *reflect.IntValue:\n\t\t_, err = fmt.Fprintf(w, \"i%de\", v.Get())\n\tcase *reflect.UintValue:\n\t\t_, err = fmt.Fprintf(w, \"i%de\", v.Get())\n\tcase *reflect.ArrayValue:\n\t\terr = writeArrayOrSlice(w, v)\n\tcase *reflect.SliceValue:\n\t\terr = writeArrayOrSlice(w, v)\n\tcase *reflect.MapValue:\n\t\terr = writeMap(w, v)\n\tcase *reflect.StructValue:\n\t\terr = writeStruct(w, v)\n\tcase *reflect.InterfaceValue:\n\t\terr = writeValue(w, v.Elem())\n\tdefault:\n\t\terr = &MarshalError{val.Type()}\n\t}\n\treturn\n}\n\nfunc isValueNil(val reflect.Value) bool {\n\tif val == nil {\n\t\treturn true\n\t}\n\tswitch v := val.(type) {\n\tcase *reflect.InterfaceValue:\n\t\treturn isValueNil(v.Elem())\n\tdefault:\n\t\treturn false\n\t}\n\treturn false\n}\n\nfunc Marshal(w io.Writer, val interface{}) os.Error {\n\treturn writeValue(w, reflect.NewValue(val))\n}\n<commit_msg>gofmt<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Marshalling and unmarshalling of\n\/\/ bit torrent bencode data into Go structs using reflection.\n\/\/\n\/\/ Based upon the standard Go language JSON package.\n\npackage bencode\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype structBuilder struct {\n\tval reflect.Value\n\n\t\/\/ if map_ != nil, write val to map_[key] on each change\n\tmap_ *reflect.MapValue\n\tkey  reflect.Value\n}\n\nvar nobuilder *structBuilder\n\nfunc isfloat(v reflect.Value) bool {\n\tswitch v.(type) {\n\tcase *reflect.FloatValue:\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc setfloat(v reflect.Value, f float64) {\n\tswitch v := v.(type) {\n\tcase *reflect.FloatValue:\n\t\tv.Set(f)\n\t}\n}\n\nfunc setint(val reflect.Value, i int64) {\n\tswitch v := val.(type) {\n\tcase *reflect.IntValue:\n\t\tv.Set(int64(i))\n\tcase *reflect.UintValue:\n\t\tv.Set(uint64(i))\n\tcase *reflect.InterfaceValue:\n\t\tv.Set(reflect.NewValue(i))\n\t}\n}\n\n\/\/ If updating b.val is not enough to update the original,\n\/\/ copy a changed b.val out to the original.\nfunc (b *structBuilder) Flush() {\n\tif b == nil {\n\t\treturn\n\t}\n\tif b.map_ != nil {\n\t\tb.map_.SetElem(b.key, b.val)\n\t}\n}\n\nfunc (b *structBuilder) Int64(i int64) {\n\tif b == nil {\n\t\treturn\n\t}\n\tv := b.val\n\tif isfloat(v) {\n\t\tsetfloat(v, float64(i))\n\t} else {\n\t\tsetint(v, i)\n\t}\n}\n\nfunc (b *structBuilder) Uint64(i uint64) {\n\tif b == nil {\n\t\treturn\n\t}\n\tv := b.val\n\tif isfloat(v) {\n\t\tsetfloat(v, float64(i))\n\t} else {\n\t\tsetint(v, int64(i))\n\t}\n}\n\nfunc (b *structBuilder) Float64(f float64) {\n\tif b == nil {\n\t\treturn\n\t}\n\tv := b.val\n\tif isfloat(v) {\n\t\tsetfloat(v, f)\n\t} else {\n\t\tsetint(v, int64(f))\n\t}\n}\n\nfunc (b *structBuilder) String(s string) {\n\tif b == nil {\n\t\treturn\n\t}\n\n\tswitch v := b.val.(type) {\n\tcase *reflect.StringValue:\n\t\tv.Set(s)\n\tcase *reflect.InterfaceValue:\n\t\tv.Set(reflect.NewValue(s))\n\t}\n}\n\nfunc (b *structBuilder) Array() {\n\tif b == nil {\n\t\treturn\n\t}\n\tif v, ok := b.val.(*reflect.SliceValue); ok {\n\t\tif v.IsNil() {\n\t\t\tv.Set(reflect.MakeSlice(v.Type().(*reflect.SliceType), 0, 8))\n\t\t}\n\t}\n}\n\nfunc (b *structBuilder) Elem(i int) Builder {\n\tif b == nil || i < 0 {\n\t\treturn nobuilder\n\t}\n\tswitch v := b.val.(type) {\n\tcase *reflect.ArrayValue:\n\t\tif i < v.Len() {\n\t\t\treturn &structBuilder{val: v.Elem(i)}\n\t\t}\n\tcase *reflect.SliceValue:\n\t\tif i >= v.Cap() {\n\t\t\tn := v.Cap()\n\t\t\tif n < 8 {\n\t\t\t\tn = 8\n\t\t\t}\n\t\t\tfor n <= i {\n\t\t\t\tn *= 2\n\t\t\t}\n\t\t\tnv := reflect.MakeSlice(v.Type().(*reflect.SliceType), v.Len(), n)\n\t\t\treflect.ArrayCopy(nv, v)\n\t\t\tv.Set(nv)\n\t\t}\n\t\tif v.Len() <= i && i < v.Cap() {\n\t\t\tv.SetLen(i + 1)\n\t\t}\n\t\tif i < v.Len() {\n\t\t\treturn &structBuilder{val: v.Elem(i)}\n\t\t}\n\t}\n\treturn nobuilder\n}\n\nfunc (b *structBuilder) Map() {\n\tif b == nil {\n\t\treturn\n\t}\n\tif v, ok := b.val.(*reflect.PtrValue); ok && v.IsNil() {\n\t\tif v.IsNil() {\n\t\t\tv.PointTo(reflect.MakeZero(v.Type().(*reflect.PtrType).Elem()))\n\t\t\tb.Flush()\n\t\t}\n\t\tb.map_ = nil\n\t\tb.val = v.Elem()\n\t}\n\tif v, ok := b.val.(*reflect.MapValue); ok && v.IsNil() {\n\t\tv.Set(reflect.MakeMap(v.Type().(*reflect.MapType)))\n\t}\n}\n\nfunc (b *structBuilder) Key(k string) Builder {\n\tif b == nil {\n\t\treturn nobuilder\n\t}\n\tswitch v := reflect.Indirect(b.val).(type) {\n\tcase *reflect.StructValue:\n\t\tt := v.Type().(*reflect.StructType)\n\t\t\/\/ Case-insensitive field lookup.\n\t\tk = strings.ToLower(k)\n\t\tfor i := 0; i < t.NumField(); i++ {\n\t\t\tfield := t.Field(i)\n\t\t\tif strings.ToLower(field.Tag) == k ||\n\t\t\t\tstrings.ToLower(field.Name) == k {\n\t\t\t\treturn &structBuilder{val: v.Field(i)}\n\t\t\t}\n\t\t}\n\tcase *reflect.MapValue:\n\t\tt := v.Type().(*reflect.MapType)\n\t\tif t.Key() != reflect.Typeof(k) {\n\t\t\tbreak\n\t\t}\n\t\tkey := reflect.NewValue(k)\n\t\telem := v.Elem(key)\n\t\tif elem == nil {\n\t\t\tv.SetElem(key, reflect.MakeZero(t.Elem()))\n\t\t\telem = v.Elem(key)\n\t\t}\n\t\treturn &structBuilder{val: elem, map_: v, key: key}\n\t}\n\treturn nobuilder\n}\n\n\/\/ Unmarshal parses the bencode syntax string s and fills in\n\/\/ an arbitrary struct or slice pointed at by val.\n\/\/ It uses the reflect package to assign to fields\n\/\/ and arrays embedded in val.  Well-formed data that does not fit\n\/\/ into the struct is discarded.\n\/\/\n\/\/ For example, given these definitions:\n\/\/\n\/\/\ttype Email struct {\n\/\/\t\tWhere string;\n\/\/\t\tAddr string;\n\/\/\t}\n\/\/\n\/\/\ttype Result struct {\n\/\/\t\tName string;\n\/\/\t\tPhone string;\n\/\/\t\tEmail []Email\n\/\/\t}\n\/\/\n\/\/\tvar r = Result{ \"name\", \"phone\", nil }\n\/\/\n\/\/ unmarshalling the bencode syntax string\n\/\/\n\/\/\td5:emailld5:where4:home4:addr15:gre@example.come\\\n\/\/  d5:where4:work4:addr12:gre@work.comee4:name14:Gr\\\n\/\/  ace R. Emlin7:address15:123 Main Streete\n\/\/\n\/\/ via Unmarshal(s, &r) is equivalent to assigning\n\/\/\n\/\/\tr = Result{\n\/\/\t\t\"Grace R. Emlin\",\t\/\/ name\n\/\/\t\t\"phone\",\t\t\/\/ no phone given\n\/\/\t\t[]Email{\n\/\/\t\t\tEmail{ \"home\", \"gre@example.com\" },\n\/\/\t\t\tEmail{ \"work\", \"gre@work.com\" }\n\/\/\t\t}\n\/\/\t}\n\/\/\n\/\/ Note that the field r.Phone has not been modified and\n\/\/ that the bencode field \"address\" was discarded.\n\/\/\n\/\/ Because Unmarshal uses the reflect package, it can only\n\/\/ assign to upper case fields.  Unmarshal uses a case-insensitive\n\/\/ comparison to match bencode field names to struct field names.\n\/\/\n\/\/ If you provide a tag string for a struct member, the tag string\n\/\/ will be used as the bencode dictionary key for that member.\n\/\/\n\/\/ To unmarshal a top-level bencode array, pass in a pointer to an empty\n\/\/ slice of the correct type.\n\/\/\n\nfunc Unmarshal(r io.Reader, val interface{}) (err os.Error) {\n\t\/\/ If e represents a value, the answer won't get back to the\n\t\/\/ caller.  Make sure it's a pointer.\n\tif _, ok := reflect.Typeof(val).(*reflect.PtrType); !ok {\n\t\terr = os.ErrorString(\"Attempt to unmarshal into a non-pointer\")\n\t\treturn\n\t}\n\terr = UnmarshalValue(r, reflect.NewValue(val))\n\treturn\n}\n\n\/\/ This API is public primarily to make testing easier, but it is available if you\n\/\/ have a use for it.\n\nfunc UnmarshalValue(r io.Reader, v reflect.Value) (err os.Error) {\n\tvar b *structBuilder\n\n\t\/\/ If val is a pointer to a slice, we append to the slice.\n\tif ptr, ok := v.(*reflect.PtrValue); ok {\n\t\tif slice, ok := ptr.Elem().(*reflect.SliceValue); ok {\n\t\t\tb = &structBuilder{val: slice}\n\t\t}\n\t}\n\n\tif b == nil {\n\t\tb = &structBuilder{val: v}\n\t}\n\n\terr = Parse(r, b)\n\treturn\n}\n\ntype MarshalError struct {\n\tT reflect.Type\n}\n\nfunc (e *MarshalError) String() string {\n\treturn \"bencode cannot encode value of type \" + e.T.String()\n}\n\nfunc writeArrayOrSlice(w io.Writer, val reflect.ArrayOrSliceValue) (err os.Error) {\n\t_, err = fmt.Fprint(w, \"l\")\n\tif err != nil {\n\t\treturn\n\t}\n\tfor i := 0; i < val.Len(); i++ {\n\t\tif err := writeValue(w, val.Elem(i)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t_, err = fmt.Fprint(w, \"e\")\n\tif err != nil {\n\t\treturn\n\t}\n\treturn nil\n}\n\ntype StringValue struct {\n\tkey   string\n\tvalue reflect.Value\n}\n\ntype StringValueArray []StringValue\n\n\/\/ Satisfy sort.Interface\n\nfunc (a StringValueArray) Len() int { return len(a) }\n\nfunc (a StringValueArray) Less(i, j int) bool { return a[i].key < a[j].key }\n\nfunc (a StringValueArray) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\n\nfunc writeSVList(w io.Writer, svList StringValueArray) (err os.Error) {\n\tsort.Sort(svList)\n\n\tfor _, sv := range svList {\n\t\tif isValueNil(sv.value) {\n\t\t\tcontinue \/\/ Skip null values\n\t\t}\n\t\ts := sv.key\n\t\t_, err = fmt.Fprintf(w, \"%d:%s\", len(s), s)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif err = writeValue(w, sv.value); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\n\nfunc writeMap(w io.Writer, val *reflect.MapValue) (err os.Error) {\n\tkey := val.Type().(*reflect.MapType).Key()\n\tif _, ok := key.(*reflect.StringType); !ok {\n\t\treturn &MarshalError{val.Type()}\n\t}\n\t_, err = fmt.Fprint(w, \"d\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tkeys := val.Keys()\n\n\t\/\/ Sort keys\n\n\tsvList := make(StringValueArray, len(keys))\n\tfor i, key := range keys {\n\t\tsvList[i].key = key.(*reflect.StringValue).Get()\n\t\tsvList[i].value = val.Elem(key)\n\t}\n\n\terr = writeSVList(w, svList)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t_, err = fmt.Fprint(w, \"e\")\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}\n\nfunc writeStruct(w io.Writer, val *reflect.StructValue) (err os.Error) {\n\t_, err = fmt.Fprint(w, \"d\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\ttyp := val.Type().(*reflect.StructType)\n\n\tnumFields := val.NumField()\n\tsvList := make(StringValueArray, numFields)\n\n\tfor i := 0; i < numFields; i++ {\n\t\tfield := typ.Field(i)\n\t\tkey := field.Name\n\t\tif len(field.Tag) > 0 {\n\t\t\tkey = field.Tag\n\t\t}\n\t\tsvList[i].key = key\n\t\tsvList[i].value = val.Field(i)\n\t}\n\n\terr = writeSVList(w, svList)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t_, err = fmt.Fprint(w, \"e\")\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}\n\nfunc writeValue(w io.Writer, val reflect.Value) (err os.Error) {\n\tif val == nil {\n\t\terr = os.NewError(\"Can't write null value\")\n\t\treturn\n\t}\n\n\tswitch v := val.(type) {\n\tcase *reflect.StringValue:\n\t\ts := v.Get()\n\t\t_, err = fmt.Fprintf(w, \"%d:%s\", len(s), s)\n\tcase *reflect.IntValue:\n\t\t_, err = fmt.Fprintf(w, \"i%de\", v.Get())\n\tcase *reflect.UintValue:\n\t\t_, err = fmt.Fprintf(w, \"i%de\", v.Get())\n\tcase *reflect.ArrayValue:\n\t\terr = writeArrayOrSlice(w, v)\n\tcase *reflect.SliceValue:\n\t\terr = writeArrayOrSlice(w, v)\n\tcase *reflect.MapValue:\n\t\terr = writeMap(w, v)\n\tcase *reflect.StructValue:\n\t\terr = writeStruct(w, v)\n\tcase *reflect.InterfaceValue:\n\t\terr = writeValue(w, v.Elem())\n\tdefault:\n\t\terr = &MarshalError{val.Type()}\n\t}\n\treturn\n}\n\nfunc isValueNil(val reflect.Value) bool {\n\tif val == nil {\n\t\treturn true\n\t}\n\tswitch v := val.(type) {\n\tcase *reflect.InterfaceValue:\n\t\treturn isValueNil(v.Elem())\n\tdefault:\n\t\treturn false\n\t}\n\treturn false\n}\n\nfunc Marshal(w io.Writer, val interface{}) os.Error {\n\treturn writeValue(w, reflect.NewValue(val))\n}\n<|endoftext|>"}
{"text":"<commit_before>package sudoku\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n)\n\ntype Availables struct {\n\tSize    int\n\tNumbers map[int]bool\n\tLength  int\n}\n\ntype Sudoku struct {\n\tDebug      bool\n\tSize       int\n\tSquareSize int\n\tGrid       [][]int\n\tAvailables [][]Availables\n\tGroups     Groups\n\tBruteLimit int\n\n\tDoResolveNumbersThatAreOnlyInOnePosition    bool\n\tDoResolveNumbersThatCanOnlyBeInFewPositions bool\n\tDoResolveOnlyOne                            bool\n}\n\ntype GroupType int\n\nconst (\n\tHorizontalGroup GroupType = iota\n\tVerticalGroup\n\tRegionGroup\n)\n\ntype Groups map[GroupType][]Group\n\ntype Position struct {\n\tY int\n\tX int\n}\n\ntype Group struct {\n\tSize      int\n\tPositions []Position\n}\n\nfunc NewSudoku() Sudoku {\n\treturn NewSudokuWithSize(3)\n}\n\nfunc (s *Sudoku) Clone(dest *Sudoku) {\n\tdest.Debug = s.Debug\n\tdest.Size = s.Size\n\tdest.SquareSize = s.SquareSize\n\tdest.BruteLimit = s.BruteLimit\n\n\tdest.DoResolveNumbersThatAreOnlyInOnePosition = s.DoResolveNumbersThatAreOnlyInOnePosition\n\tdest.DoResolveNumbersThatCanOnlyBeInFewPositions = s.DoResolveNumbersThatCanOnlyBeInFewPositions\n\tdest.DoResolveOnlyOne = s.DoResolveOnlyOne\n\n\tdest.initFields()\n\tdest.Groups = s.Groups\n\n\tfor y := 0; y < s.Size; y++ {\n\t\tfor x := 0; x < s.Size; x++ {\n\t\t\tif s.Grid[y][x] > 0 {\n\t\t\t\tdest.SetNumber(y, x, s.Grid[y][x])\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (s *Sudoku) initFields() {\n\ts.Grid = make([][]int, s.Size)\n\ts.Availables = make([][]Availables, s.Size)\n\ts.Groups = make(map[GroupType][]Group, 0)\n\tfor i := 0; i < s.Size; i++ {\n\t\ts.Grid[i] = make([]int, s.Size)\n\t\ts.Availables[i] = make([]Availables, s.Size)\n\t\tfor j := 0; j < s.Size; j++ {\n\t\t\ts.Availables[i][j] = NewAvailables(s.Size)\n\t\t}\n\t}\n}\n\nfunc NewSudokuWithSize(sqsize int) Sudoku {\n\tsize := sqsize * sqsize\n\tsudoku := Sudoku{\n\t\tDebug:      os.Getenv(\"DEBUG\") == \"1\",\n\t\tSquareSize: sqsize,\n\t\tSize:       size,\n\t\tBruteLimit: 2,\n\n\t\tDoResolveNumbersThatAreOnlyInOnePosition:    true,\n\t\tDoResolveNumbersThatCanOnlyBeInFewPositions: true,\n\t\tDoResolveOnlyOne:                            true,\n\t}\n\tsudoku.initFields()\n\tsudoku.initGroups()\n\treturn sudoku\n}\n\nfunc (s *Sudoku) initGroups() {\n\t\/\/ horizontal groups\n\tfor y := 0; y < s.Size; y++ {\n\t\tgroup := Group{}\n\t\tfor x := 0; x < s.Size; x++ {\n\t\t\tgroup.Positions = append(group.Positions, Position{y, x})\n\t\t}\n\t\ts.Groups[HorizontalGroup] = append(s.Groups[HorizontalGroup], group)\n\t}\n\n\t\/\/ vertical groups\n\tfor x := 0; x < s.Size; x++ {\n\t\tgroup := Group{}\n\t\tfor y := 0; y < s.Size; y++ {\n\t\t\tgroup.Positions = append(group.Positions, Position{y, x})\n\t\t}\n\t\ts.Groups[VerticalGroup] = append(s.Groups[VerticalGroup], group)\n\t}\n\t\/\/ zone groups\n\tfor a := 0; a < s.SquareSize; a++ {\n\t\tfor b := 0; b < s.SquareSize; b++ {\n\t\t\tgroup := Group{}\n\t\t\tfor c := 0; c < s.SquareSize; c++ {\n\t\t\t\tfor d := 0; d < s.SquareSize; d++ {\n\t\t\t\t\ty := a*s.SquareSize + c\n\t\t\t\t\tx := b*s.SquareSize + d\n\t\t\t\t\tgroup.Positions = append(group.Positions, Position{y, x})\n\t\t\t\t}\n\t\t\t}\n\t\t\ts.Groups[RegionGroup] = append(s.Groups[RegionGroup], group)\n\t\t}\n\t}\n}\n\nfunc NewAvailables(size int) Availables {\n\tavailables := Availables{\n\t\tSize:    size,\n\t\tNumbers: make(map[int]bool, size),\n\t\tLength:  size,\n\t}\n\tfor i := 1; i <= size; i++ {\n\t\tavailables.Numbers[i] = true\n\t}\n\treturn availables\n}\n\nfunc (a *Availables) String() string {\n\toutput := \"\"\n\tfor i := 1; i <= a.Size; i++ {\n\t\tif a.Numbers[i] {\n\t\t\toutput += strconv.Itoa(i)\n\t\t} else {\n\t\t\toutput += \".\"\n\t\t}\n\t}\n\treturn output\n}\n\nfunc (a *Availables) SetNumber(number int) {\n\tfor i := 1; i <= a.Size; i++ {\n\t\ta.Numbers[i] = i == number\n\t}\n\ta.Length = 1\n}\n\nfunc (a *Availables) Availables() []int {\n\tavailables := []int{}\n\tfor i := 1; i <= a.Size; i++ {\n\t\tif a.Numbers[i] {\n\t\t\tavailables = append(availables, i)\n\t\t}\n\t}\n\treturn availables\n}\n\nfunc (a *Availables) RemoveNumber(number int) bool {\n\tif a.Numbers[number] {\n\t\ta.Length--\n\t\ta.Numbers[number] = false\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (g *Groups) AllGroups() []Group {\n\tgroups := []Group{}\n\tfor _, typeGroups := range *g {\n\t\tgroups = append(groups, typeGroups...)\n\t}\n\treturn groups\n}\n\nfunc (g *Groups) MatchCoords(y, x int) []Group {\n\tgroups := []Group{}\n\tfor _, group := range g.AllGroups() {\n\t\tfor _, pos := range group.Positions {\n\t\t\tif pos.Y == y && pos.X == x {\n\t\t\t\tgroups = append(groups, group)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn groups\n}\n\nfunc (s *Sudoku) SetNumber(y, x, number int) {\n\ts.Grid[y][x] = number\n\ts.Availables[y][x].SetNumber(number)\n\tfor _, group := range s.Groups.MatchCoords(y, x) {\n\t\tfor _, pos := range group.Positions {\n\t\t\ts.Availables[pos.Y][pos.X].RemoveNumber(number)\n\t\t}\n\t}\n}\n\nfunc (s *Sudoku) ParseString(input string) error {\n\tinput = strings.TrimSpace(input)\n\tlines := strings.Split(input, \"\\n\")\n\tfor y, line := range lines[1 : s.Size+1] {\n\t\tfor x := 0; x < s.Size; x++ {\n\t\t\tcol := line[1+x*2 : 1+x*2+1]\n\t\t\tif col != \" \" {\n\t\t\t\tcolNb, err := strconv.Atoi(col)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ts.SetNumber(y, x, colNb)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *Sudoku) String() string {\n\tlines := []string{}\n\tlines = append(lines, fmt.Sprintf(\"+%s+\", strings.Repeat(\"-\", s.Size*2-1)))\n\n\tfor _, gridLine := range s.Grid {\n\t\tline := []string{}\n\t\tfor _, col := range gridLine {\n\t\t\tline = append(line, strconv.Itoa(col))\n\t\t}\n\t\tlineStr := fmt.Sprintf(\"|%s|\", strings.Join(line, \" \"))\n\t\tlineStr = strings.Replace(lineStr, \"0\", \" \", -1)\n\t\tlines = append(lines, lineStr)\n\t}\n\tlines = append(lines, fmt.Sprintf(\"+%s+\", strings.Repeat(\"-\", s.Size*2-1)))\n\treturn strings.Join(lines, \"\\n\")\n}\n\nfunc (s *Sudoku) AvailablesString() string {\n\tlines := []string{}\n\tlines = append(lines, fmt.Sprintf(\"+%s+\", strings.Repeat(\"-\", s.Size*(s.Size+1)-1)))\n\tfor _, availablesLine := range s.Availables {\n\t\tline := []string{}\n\t\tfor _, availables := range availablesLine {\n\t\t\tline = append(line, availables.String())\n\t\t}\n\t\tlineStr := fmt.Sprintf(\"|%s|\", strings.Join(line, \" \"))\n\t\tlines = append(lines, lineStr)\n\t}\n\tlines = append(lines, fmt.Sprintf(\"+%s+\", strings.Repeat(\"-\", s.Size*(s.Size+1)-1)))\n\treturn strings.Join(lines, \"\\n\")\n}\n\nfunc (s *Sudoku) Missings() int {\n\tmissings := 0\n\tfor _, line := range s.Grid {\n\t\tfor _, col := range line {\n\t\t\tif col == 0 {\n\t\t\t\tmissings++\n\t\t\t}\n\t\t}\n\t}\n\treturn missings\n}\n\nfunc (s *Sudoku) ResolveOnlyOne() int {\n\tchanged := 0\n\tfor y := 0; y < s.Size; y++ {\n\t\tfor x := 0; x < s.Size; x++ {\n\t\t\tif s.Grid[y][x] != 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif s.Availables[y][x].Length == 1 {\n\t\t\t\ts.SetNumber(y, x, s.Availables[y][x].Availables()[0])\n\t\t\t\tchanged++\n\t\t\t}\n\t\t}\n\t}\n\treturn changed\n}\n\nfunc (s *Sudoku) RemoveNumbersThatCanOnlyBeInFewPositions() int {\n\tchanges := 0\n\tfor _, group := range s.Groups.AllGroups() {\n\t\tfor idxA, posA := range group.Positions {\n\t\t\tidenticalSlots := 0\n\t\t\tavailableA := s.Availables[posA.Y][posA.X]\n\t\t\tfor idxB, posB := range group.Positions {\n\t\t\t\tif idxA == idxB {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tavailableB := s.Availables[posB.Y][posB.X]\n\t\t\t\tif availableA.String() == availableB.String() {\n\t\t\t\t\tidenticalSlots++\n\t\t\t\t}\n\t\t\t}\n\t\t\tif identicalSlots != availableA.Length-1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor idxB, posB := range group.Positions {\n\t\t\t\tif idxA == idxB {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tavailableB := s.Availables[posB.Y][posB.X]\n\t\t\t\tif availableA.String() != availableB.String() {\n\t\t\t\t\tfor _, number := range availableA.Availables() {\n\t\t\t\t\t\tif s.Availables[posB.Y][posB.X].RemoveNumber(number) {\n\t\t\t\t\t\t\tchanges++\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn changes\n}\n\nfunc (s *Sudoku) ResolveNumbersThatAreOnlyInOnePosition() int {\n\tchanges := 0\n\tfor _, group := range s.Groups.AllGroups() {\n\t\tfor number := 1; number <= s.Size; number++ {\n\t\t\tcount := 0\n\t\t\tfor _, pos := range group.Positions {\n\t\t\t\tif s.Availables[pos.Y][pos.X].Numbers[number] {\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t\t}\n\t\t\tif count == 1 {\n\t\t\t\tfor _, pos := range group.Positions {\n\t\t\t\t\tif s.Availables[pos.Y][pos.X].Numbers[number] {\n\t\t\t\t\t\ts.SetNumber(pos.Y, pos.X, number)\n\t\t\t\t\t\tchanges++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn changes\n}\n\nfunc (s *Sudoku) ResolveRec(depth int) (*Sudoku, error) {\n\tchanges := 0\n\titeration := 0\n\tkind := \"start\"\n\nstart:\n\tif s.Debug {\n\t\tlogrus.Infof(\"#######  depth=%-2d iteration=%-3d changes=%-2d missings=%d kind=%s\\n%s\\n%s\", depth, iteration, changes, s.Missings(), kind, s.String(), s.AvailablesString())\n\t\tlogrus.Infof(strings.Repeat(\"#\", 42))\n\t}\n\titeration++\n\n\tif s.DoResolveOnlyOne {\n\t\tkind = \"resolve-only-one\"\n\t\tif changes = s.ResolveOnlyOne(); changes > 0 {\n\t\t\tgoto start\n\t\t}\n\t}\n\n\tif s.DoResolveNumbersThatAreOnlyInOnePosition {\n\t\tkind = \"resolve-numbers-that-are-only-in-one-position\"\n\t\tif changes = s.ResolveNumbersThatAreOnlyInOnePosition(); changes > 0 {\n\t\t\tgoto start\n\t\t}\n\t}\n\n\tif s.DoResolveNumbersThatCanOnlyBeInFewPositions && depth == 0 {\n\t\tkind = \"resolve-numbers-that-can-only-be-in-few-positions\"\n\t\tif changes = s.RemoveNumbersThatCanOnlyBeInFewPositions(); changes > 0 {\n\t\t\tgoto start\n\t\t}\n\t}\n\n\t\/\/ Brute force\n\tif s.Missings() == 0 {\n\t\treturn s, nil\n\t}\n\n\tif depth >= s.BruteLimit {\n\t\treturn s, fmt.Errorf(\"Too deep\")\n\t}\n\n\tfor y := 0; y < s.Size; y++ {\n\t\tfor x := 0; x < s.Size; x++ {\n\t\t\tif s.Availables[y][x].Length > 0 {\n\t\t\t\tclone := Sudoku{}\n\t\t\t\ts.Clone(&clone)\n\t\t\t\tclone.SetNumber(y, x, s.Availables[y][x].Availables()[0])\n\t\t\t\tnewSudoku, err := clone.ResolveRec(depth + 1)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif newSudoku.Missings() == 0 {\n\t\t\t\t\treturn newSudoku, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn s, nil\n}\n\nfunc (s *Sudoku) Resolve() error {\n\tnewSudoku, err := s.ResolveRec(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif newSudoku != s {\n\t\tnewSudoku.Clone(s)\n\t}\n\treturn nil\n}\n<commit_msg>Disable slow algorightm<commit_after>package sudoku\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n)\n\ntype Availables struct {\n\tSize    int\n\tNumbers map[int]bool\n\tLength  int\n}\n\ntype Sudoku struct {\n\tDebug      bool\n\tSize       int\n\tSquareSize int\n\tGrid       [][]int\n\tAvailables [][]Availables\n\tGroups     Groups\n\tBruteLimit int\n\n\tDoResolveNumbersThatAreOnlyInOnePosition    bool\n\tDoResolveNumbersThatCanOnlyBeInFewPositions bool\n\tDoResolveOnlyOne                            bool\n}\n\ntype GroupType int\n\nconst (\n\tHorizontalGroup GroupType = iota\n\tVerticalGroup\n\tRegionGroup\n)\n\ntype Groups map[GroupType][]Group\n\ntype Position struct {\n\tY int\n\tX int\n}\n\ntype Group struct {\n\tSize      int\n\tPositions []Position\n}\n\nfunc NewSudoku() Sudoku {\n\treturn NewSudokuWithSize(3)\n}\n\nfunc (s *Sudoku) Clone(dest *Sudoku) {\n\tdest.Debug = s.Debug\n\tdest.Size = s.Size\n\tdest.SquareSize = s.SquareSize\n\tdest.BruteLimit = s.BruteLimit\n\n\tdest.DoResolveNumbersThatAreOnlyInOnePosition = s.DoResolveNumbersThatAreOnlyInOnePosition\n\tdest.DoResolveNumbersThatCanOnlyBeInFewPositions = s.DoResolveNumbersThatCanOnlyBeInFewPositions\n\tdest.DoResolveOnlyOne = s.DoResolveOnlyOne\n\n\tdest.initFields()\n\tdest.Groups = s.Groups\n\n\tfor y := 0; y < s.Size; y++ {\n\t\tfor x := 0; x < s.Size; x++ {\n\t\t\tif s.Grid[y][x] > 0 {\n\t\t\t\tdest.SetNumber(y, x, s.Grid[y][x])\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (s *Sudoku) initFields() {\n\ts.Grid = make([][]int, s.Size)\n\ts.Availables = make([][]Availables, s.Size)\n\ts.Groups = make(map[GroupType][]Group, 0)\n\tfor i := 0; i < s.Size; i++ {\n\t\ts.Grid[i] = make([]int, s.Size)\n\t\ts.Availables[i] = make([]Availables, s.Size)\n\t\tfor j := 0; j < s.Size; j++ {\n\t\t\ts.Availables[i][j] = NewAvailables(s.Size)\n\t\t}\n\t}\n}\n\nfunc NewSudokuWithSize(sqsize int) Sudoku {\n\tsize := sqsize * sqsize\n\tsudoku := Sudoku{\n\t\tDebug:      os.Getenv(\"DEBUG\") == \"1\",\n\t\tSquareSize: sqsize,\n\t\tSize:       size,\n\t\tBruteLimit: 2,\n\n\t\tDoResolveNumbersThatAreOnlyInOnePosition:    true,\n\t\tDoResolveNumbersThatCanOnlyBeInFewPositions: false,\n\t\tDoResolveOnlyOne:                            true,\n\t}\n\tsudoku.initFields()\n\tsudoku.initGroups()\n\treturn sudoku\n}\n\nfunc (s *Sudoku) initGroups() {\n\t\/\/ horizontal groups\n\tfor y := 0; y < s.Size; y++ {\n\t\tgroup := Group{}\n\t\tfor x := 0; x < s.Size; x++ {\n\t\t\tgroup.Positions = append(group.Positions, Position{y, x})\n\t\t}\n\t\ts.Groups[HorizontalGroup] = append(s.Groups[HorizontalGroup], group)\n\t}\n\n\t\/\/ vertical groups\n\tfor x := 0; x < s.Size; x++ {\n\t\tgroup := Group{}\n\t\tfor y := 0; y < s.Size; y++ {\n\t\t\tgroup.Positions = append(group.Positions, Position{y, x})\n\t\t}\n\t\ts.Groups[VerticalGroup] = append(s.Groups[VerticalGroup], group)\n\t}\n\t\/\/ zone groups\n\tfor a := 0; a < s.SquareSize; a++ {\n\t\tfor b := 0; b < s.SquareSize; b++ {\n\t\t\tgroup := Group{}\n\t\t\tfor c := 0; c < s.SquareSize; c++ {\n\t\t\t\tfor d := 0; d < s.SquareSize; d++ {\n\t\t\t\t\ty := a*s.SquareSize + c\n\t\t\t\t\tx := b*s.SquareSize + d\n\t\t\t\t\tgroup.Positions = append(group.Positions, Position{y, x})\n\t\t\t\t}\n\t\t\t}\n\t\t\ts.Groups[RegionGroup] = append(s.Groups[RegionGroup], group)\n\t\t}\n\t}\n}\n\nfunc NewAvailables(size int) Availables {\n\tavailables := Availables{\n\t\tSize:    size,\n\t\tNumbers: make(map[int]bool, size),\n\t\tLength:  size,\n\t}\n\tfor i := 1; i <= size; i++ {\n\t\tavailables.Numbers[i] = true\n\t}\n\treturn availables\n}\n\nfunc (a *Availables) String() string {\n\toutput := \"\"\n\tfor i := 1; i <= a.Size; i++ {\n\t\tif a.Numbers[i] {\n\t\t\toutput += strconv.Itoa(i)\n\t\t} else {\n\t\t\toutput += \".\"\n\t\t}\n\t}\n\treturn output\n}\n\nfunc (a *Availables) SetNumber(number int) {\n\tfor i := 1; i <= a.Size; i++ {\n\t\ta.Numbers[i] = i == number\n\t}\n\ta.Length = 1\n}\n\nfunc (a *Availables) Availables() []int {\n\tavailables := []int{}\n\tfor i := 1; i <= a.Size; i++ {\n\t\tif a.Numbers[i] {\n\t\t\tavailables = append(availables, i)\n\t\t}\n\t}\n\treturn availables\n}\n\nfunc (a *Availables) RemoveNumber(number int) bool {\n\tif a.Numbers[number] {\n\t\ta.Length--\n\t\ta.Numbers[number] = false\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (g *Groups) AllGroups() []Group {\n\tgroups := []Group{}\n\tfor _, typeGroups := range *g {\n\t\tgroups = append(groups, typeGroups...)\n\t}\n\treturn groups\n}\n\nfunc (g *Groups) MatchCoords(y, x int) []Group {\n\tgroups := []Group{}\n\tfor _, group := range g.AllGroups() {\n\t\tfor _, pos := range group.Positions {\n\t\t\tif pos.Y == y && pos.X == x {\n\t\t\t\tgroups = append(groups, group)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn groups\n}\n\nfunc (s *Sudoku) SetNumber(y, x, number int) {\n\ts.Grid[y][x] = number\n\ts.Availables[y][x].SetNumber(number)\n\tfor _, group := range s.Groups.MatchCoords(y, x) {\n\t\tfor _, pos := range group.Positions {\n\t\t\ts.Availables[pos.Y][pos.X].RemoveNumber(number)\n\t\t}\n\t}\n}\n\nfunc (s *Sudoku) ParseString(input string) error {\n\tinput = strings.TrimSpace(input)\n\tlines := strings.Split(input, \"\\n\")\n\tfor y, line := range lines[1 : s.Size+1] {\n\t\tfor x := 0; x < s.Size; x++ {\n\t\t\tcol := line[1+x*2 : 1+x*2+1]\n\t\t\tif col != \" \" {\n\t\t\t\tcolNb, err := strconv.Atoi(col)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\ts.SetNumber(y, x, colNb)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *Sudoku) String() string {\n\tlines := []string{}\n\tlines = append(lines, fmt.Sprintf(\"+%s+\", strings.Repeat(\"-\", s.Size*2-1)))\n\n\tfor _, gridLine := range s.Grid {\n\t\tline := []string{}\n\t\tfor _, col := range gridLine {\n\t\t\tline = append(line, strconv.Itoa(col))\n\t\t}\n\t\tlineStr := fmt.Sprintf(\"|%s|\", strings.Join(line, \" \"))\n\t\tlineStr = strings.Replace(lineStr, \"0\", \" \", -1)\n\t\tlines = append(lines, lineStr)\n\t}\n\tlines = append(lines, fmt.Sprintf(\"+%s+\", strings.Repeat(\"-\", s.Size*2-1)))\n\treturn strings.Join(lines, \"\\n\")\n}\n\nfunc (s *Sudoku) AvailablesString() string {\n\tlines := []string{}\n\tlines = append(lines, fmt.Sprintf(\"+%s+\", strings.Repeat(\"-\", s.Size*(s.Size+1)-1)))\n\tfor _, availablesLine := range s.Availables {\n\t\tline := []string{}\n\t\tfor _, availables := range availablesLine {\n\t\t\tline = append(line, availables.String())\n\t\t}\n\t\tlineStr := fmt.Sprintf(\"|%s|\", strings.Join(line, \" \"))\n\t\tlines = append(lines, lineStr)\n\t}\n\tlines = append(lines, fmt.Sprintf(\"+%s+\", strings.Repeat(\"-\", s.Size*(s.Size+1)-1)))\n\treturn strings.Join(lines, \"\\n\")\n}\n\nfunc (s *Sudoku) Missings() int {\n\tmissings := 0\n\tfor _, line := range s.Grid {\n\t\tfor _, col := range line {\n\t\t\tif col == 0 {\n\t\t\t\tmissings++\n\t\t\t}\n\t\t}\n\t}\n\treturn missings\n}\n\nfunc (s *Sudoku) ResolveOnlyOne() int {\n\tchanged := 0\n\tfor y := 0; y < s.Size; y++ {\n\t\tfor x := 0; x < s.Size; x++ {\n\t\t\tif s.Grid[y][x] != 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif s.Availables[y][x].Length == 1 {\n\t\t\t\ts.SetNumber(y, x, s.Availables[y][x].Availables()[0])\n\t\t\t\tchanged++\n\t\t\t}\n\t\t}\n\t}\n\treturn changed\n}\n\nfunc (s *Sudoku) RemoveNumbersThatCanOnlyBeInFewPositions() int {\n\tchanges := 0\n\tfor _, group := range s.Groups.AllGroups() {\n\t\tfor idxA, posA := range group.Positions {\n\t\t\tidenticalSlots := 0\n\t\t\tavailableA := s.Availables[posA.Y][posA.X]\n\t\t\tfor idxB, posB := range group.Positions {\n\t\t\t\tif idxA == idxB {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tavailableB := s.Availables[posB.Y][posB.X]\n\t\t\t\tif availableA.String() == availableB.String() {\n\t\t\t\t\tidenticalSlots++\n\t\t\t\t}\n\t\t\t}\n\t\t\tif identicalSlots != availableA.Length-1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor idxB, posB := range group.Positions {\n\t\t\t\tif idxA == idxB {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tavailableB := s.Availables[posB.Y][posB.X]\n\t\t\t\tif availableA.String() != availableB.String() {\n\t\t\t\t\tfor _, number := range availableA.Availables() {\n\t\t\t\t\t\tif s.Availables[posB.Y][posB.X].RemoveNumber(number) {\n\t\t\t\t\t\t\tchanges++\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn changes\n}\n\nfunc (s *Sudoku) ResolveNumbersThatAreOnlyInOnePosition() int {\n\tchanges := 0\n\tfor _, group := range s.Groups.AllGroups() {\n\t\tfor number := 1; number <= s.Size; number++ {\n\t\t\tcount := 0\n\t\t\tfor _, pos := range group.Positions {\n\t\t\t\tif s.Availables[pos.Y][pos.X].Numbers[number] {\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t\t}\n\t\t\tif count == 1 {\n\t\t\t\tfor _, pos := range group.Positions {\n\t\t\t\t\tif s.Availables[pos.Y][pos.X].Numbers[number] {\n\t\t\t\t\t\ts.SetNumber(pos.Y, pos.X, number)\n\t\t\t\t\t\tchanges++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn changes\n}\n\nfunc (s *Sudoku) ResolveRec(depth int) (*Sudoku, error) {\n\tchanges := 0\n\titeration := 0\n\tkind := \"start\"\n\nstart:\n\tif s.Debug {\n\t\tlogrus.Infof(\"#######  depth=%-2d iteration=%-3d changes=%-2d missings=%d kind=%s\\n%s\\n%s\", depth, iteration, changes, s.Missings(), kind, s.String(), s.AvailablesString())\n\t\tlogrus.Infof(strings.Repeat(\"#\", 42))\n\t}\n\titeration++\n\n\tif s.DoResolveOnlyOne {\n\t\tkind = \"resolve-only-one\"\n\t\tif changes = s.ResolveOnlyOne(); changes > 0 {\n\t\t\tgoto start\n\t\t}\n\t}\n\n\tif s.DoResolveNumbersThatAreOnlyInOnePosition {\n\t\tkind = \"resolve-numbers-that-are-only-in-one-position\"\n\t\tif changes = s.ResolveNumbersThatAreOnlyInOnePosition(); changes > 0 {\n\t\t\tgoto start\n\t\t}\n\t}\n\n\tif s.DoResolveNumbersThatCanOnlyBeInFewPositions && depth == 0 {\n\t\tkind = \"resolve-numbers-that-can-only-be-in-few-positions\"\n\t\tif changes = s.RemoveNumbersThatCanOnlyBeInFewPositions(); changes > 0 {\n\t\t\tgoto start\n\t\t}\n\t}\n\n\t\/\/ Brute force\n\tif s.Missings() == 0 {\n\t\treturn s, nil\n\t}\n\n\tif depth >= s.BruteLimit {\n\t\treturn s, fmt.Errorf(\"Too deep\")\n\t}\n\n\tfor y := 0; y < s.Size; y++ {\n\t\tfor x := 0; x < s.Size; x++ {\n\t\t\tif s.Availables[y][x].Length > 0 {\n\t\t\t\tclone := Sudoku{}\n\t\t\t\ts.Clone(&clone)\n\t\t\t\tclone.SetNumber(y, x, s.Availables[y][x].Availables()[0])\n\t\t\t\tnewSudoku, err := clone.ResolveRec(depth + 1)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif newSudoku.Missings() == 0 {\n\t\t\t\t\treturn newSudoku, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn s, nil\n}\n\nfunc (s *Sudoku) Resolve() error {\n\tnewSudoku, err := s.ResolveRec(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif newSudoku != s {\n\t\tnewSudoku.Clone(s)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype paste struct {\n\tPaste  []set\n\tTitle  string\n\tAuthor string\n\tNotes  string\n}\n\ntype set struct {\n\tPokemon uint\n\tForm    uint\n\tItem    uint\n\tText    template.HTML\n}\n\nvar (\n\treHead = regexp.MustCompile(`^(?:(.* \\()([A-Z][a-z0-9:']+\\.?(?:[- ][A-Za-z][a-z0-9:']*\\.?)*)(\\))|([A-Z][a-z0-9:']+\\.?(?:[- ][A-Za-z][a-z0-9:']*\\.?)*))(?:( \\()([MF])(\\)))?(?:( @ )([A-Z][a-z0-9:']+(?:[- ][A-Z][a-z0-9:']*)*))?( *)$`)\n\treMove = regexp.MustCompile(`^(-)( ([A-Z][a-z\\']*(?:[- ][A-Za-z][a-z\\']*)*)(?: \\[([A-Z][a-z]+)\\])?(?: \/ [A-Z][a-z\\']*(?:[- ][A-Za-z][a-z\\']*)*)* *)$`)\n\treStat = regexp.MustCompile(`^(\\d+ HP)?( \/ )?(\\d+ Atk)?( \/ )?(\\d+ Def)?( \/ )?(\\d+ SpA)?( \/ )?(\\d+ SpD)?( \/ )?(\\d+ Spe)?( *)$`)\n\n\ttmpl = template.Must(template.ParseFiles(\"paste.tmpl\"))\n)\n\nfunc renderPaste(w http.ResponseWriter, text, title, author, notes []byte) {\n\tsets := bytes.Split(text, []byte(\"\\r\\n\\r\\n\"))\n\tfpaste := paste{\n\t\tPaste:  make([]set, 0, len(sets)),\n\t\tTitle:  string(title),\n\t\tAuthor: string(author),\n\t\tNotes:  string(notes),\n\t}\n\n\tfor _, bset := range sets {\n\t\tif len(bset) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar fset set\n\t\tvar b strings.Builder\n\n\t\tlines := bytes.Split(bset, []byte(\"\\r\\n\"))\n\n\t\tm := reHead.FindSubmatch(lines[0])\n\t\tif m == nil {\n\t\t\ttemplate.HTMLEscape(&b, bset)\n\t\t\tfset.Text = template.HTML(b.String())\n\t\t\tfpaste.Paste = append(fpaste.Paste, fset)\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(m[2]) != 0 {\n\t\t\tif p, ok := pokemonData[string(m[2])]; ok {\n\t\t\t\tfset.Pokemon = p[\"id\"].(uint)\n\t\t\t\tfset.Form = p[\"form\"].(uint)\n\t\t\t\ttemplate.HTMLEscape(&b, m[1])\n\t\t\t\tb.WriteString(`<span class=\"type-`)\n\t\t\t\tb.WriteString(p[\"type\"].(string))\n\t\t\t\tb.WriteString(`\">`)\n\t\t\t\ttemplate.HTMLEscape(&b, m[2])\n\t\t\t\tb.WriteString(`<\/span>`)\n\t\t\t\ttemplate.HTMLEscape(&b, m[3])\n\t\t\t} else {\n\t\t\t\ttemplate.HTMLEscape(&b, m[1])\n\t\t\t\ttemplate.HTMLEscape(&b, m[2])\n\t\t\t\ttemplate.HTMLEscape(&b, m[3])\n\t\t\t}\n\t\t} else if len(m[4]) != 0 {\n\t\t\tif p, ok := pokemonData[string(m[4])]; ok {\n\t\t\t\tfset.Pokemon = p[\"id\"].(uint)\n\t\t\t\tfset.Form = p[\"form\"].(uint)\n\t\t\t\tb.WriteString(`<span class=\"type-`)\n\t\t\t\tb.WriteString(p[\"type\"].(string))\n\t\t\t\tb.WriteString(`\">`)\n\t\t\t\ttemplate.HTMLEscape(&b, m[4])\n\t\t\t\tb.WriteString(`<\/span>`)\n\t\t\t} else {\n\t\t\t\ttemplate.HTMLEscape(&b, m[4])\n\t\t\t}\n\t\t}\n\n\t\tif len(m[6]) != 0 {\n\t\t\ttemplate.HTMLEscape(&b, m[5])\n\t\t\tif m[6][0] == 'M' {\n\t\t\t\tb.WriteString(`<span class=\"gender-m\">`)\n\t\t\t} else if m[6][0] == 'F' {\n\t\t\t\tb.WriteString(`<span class=\"gender-f\">`)\n\t\t\t} else {\n\t\t\t\tb.WriteString(`<span>`)\n\t\t\t}\n\t\t\ttemplate.HTMLEscape(&b, m[6])\n\t\t\tb.WriteString(`<\/span>`)\n\t\t\ttemplate.HTMLEscape(&b, m[7])\n\t\t}\n\n\t\tif len(m[9]) != 0 {\n\t\t\tif i, ok := itemData[string(m[9])]; ok {\n\t\t\t\tfset.Item = i[\"id\"].(uint)\n\t\t\t\ttemplate.HTMLEscape(&b, m[8])\n\t\t\t\tif t, ok := i[\"type\"]; ok {\n\t\t\t\t\tb.WriteString(`<span class=\"type-`)\n\t\t\t\t\tb.WriteString(t.(string))\n\t\t\t\t\tb.WriteString(`\">`)\n\t\t\t\t\ttemplate.HTMLEscape(&b, m[9])\n\t\t\t\t\tb.WriteString(`<\/span>`)\n\t\t\t\t} else {\n\t\t\t\t\ttemplate.HTMLEscape(&b, m[9])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttemplate.HTMLEscape(&b, m[8])\n\t\t\t\ttemplate.HTMLEscape(&b, m[9])\n\t\t\t}\n\t\t}\n\n\t\tb.Write(m[10])\n\t\tb.WriteByte('\\n')\n\n\t\tfor _, line := range lines[1:] {\n\t\t\tif m := reMove.FindSubmatch(line); m != nil {\n\t\t\t\tif mv, ok := moveData[string(m[3])]; ok {\n\t\t\t\t\tb.WriteString(`<span class=\"type-`)\n\t\t\t\t\tif len(m[4]) > 0 {\n\t\t\t\t\t\ttemplate.HTMLEscape(&b, bytes.ToLower(m[4]))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tb.WriteString(mv[\"type\"].(string))\n\t\t\t\t\t}\n\t\t\t\t\tb.WriteString(`\">`)\n\t\t\t\t\ttemplate.HTMLEscape(&b, m[1])\n\t\t\t\t\tb.WriteString(`<\/span>`)\n\t\t\t\t} else {\n\t\t\t\t\ttemplate.HTMLEscape(&b, m[1])\n\t\t\t\t}\n\t\t\t\ttemplate.HTMLEscape(&b, m[2])\n\t\t\t} else if m := bytes.SplitAfterN(line, []byte(\": \"), 2); len(m) == 2 {\n\t\t\t\tb.WriteString(`<span class=\"attr\">`)\n\t\t\t\ttemplate.HTMLEscape(&b, m[0])\n\t\t\t\tb.WriteString(`<\/span>`)\n\t\t\t\tif len(m[0]) == 5 && m[0][1] == 'V' && m[0][2] == 's' {\n\t\t\t\t\tattr := m[1]\n\t\t\t\t\tif m := reStat.FindSubmatch(attr); m != nil {\n\t\t\t\t\t\tfor i, stat := range [...]string{\"hp\", \"atk\", \"def\", \"spa\", \"spd\", \"spe\"} {\n\t\t\t\t\t\t\tif len(m[i*2+1]) > 0 {\n\t\t\t\t\t\t\t\tb.WriteString(`<span class=\"stat-`)\n\t\t\t\t\t\t\t\tb.WriteString(stat)\n\t\t\t\t\t\t\t\tb.WriteString(`\">`)\n\t\t\t\t\t\t\t\ttemplate.HTMLEscape(&b, m[i*2+1])\n\t\t\t\t\t\t\t\tb.WriteString(`<\/span>`)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttemplate.HTMLEscape(&b, m[i*2+2])\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttemplate.HTMLEscape(&b, attr)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ttemplate.HTMLEscape(&b, m[1])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttemplate.HTMLEscape(&b, line)\n\t\t\t}\n\t\t\tb.WriteByte('\\n')\n\t\t}\n\n\t\tfset.Text = template.HTML(b.String())\n\n\t\tfpaste.Paste = append(fpaste.Paste, fset)\n\t}\n\n\terr := tmpl.Execute(w, fpaste)\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n<commit_msg>Allow \"X Tier\" as a valid item format<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype paste struct {\n\tPaste  []set\n\tTitle  string\n\tAuthor string\n\tNotes  string\n}\n\ntype set struct {\n\tPokemon uint\n\tForm    uint\n\tItem    uint\n\tText    template.HTML\n}\n\nvar (\n\treHead = regexp.MustCompile(`^(?:(.* \\()([A-Z][a-z0-9:']+\\.?(?:[- ][A-Za-z][a-z0-9:']*\\.?)*)(\\))|([A-Z][a-z0-9:']+\\.?(?:[- ][A-Za-z][a-z0-9:']*\\.?)*))(?:( \\()([MF])(\\)))?(?:( @ )([A-Z][a-z0-9:']*(?:[- ][A-Z][a-z0-9:']*)*))?( *)$`)\n\treMove = regexp.MustCompile(`^(-)( ([A-Z][a-z\\']*(?:[- ][A-Za-z][a-z\\']*)*)(?: \\[([A-Z][a-z]+)\\])?(?: \/ [A-Z][a-z\\']*(?:[- ][A-Za-z][a-z\\']*)*)* *)$`)\n\treStat = regexp.MustCompile(`^(\\d+ HP)?( \/ )?(\\d+ Atk)?( \/ )?(\\d+ Def)?( \/ )?(\\d+ SpA)?( \/ )?(\\d+ SpD)?( \/ )?(\\d+ Spe)?( *)$`)\n\n\ttmpl = template.Must(template.ParseFiles(\"paste.tmpl\"))\n)\n\nfunc renderPaste(w http.ResponseWriter, text, title, author, notes []byte) {\n\tsets := bytes.Split(text, []byte(\"\\r\\n\\r\\n\"))\n\tfpaste := paste{\n\t\tPaste:  make([]set, 0, len(sets)),\n\t\tTitle:  string(title),\n\t\tAuthor: string(author),\n\t\tNotes:  string(notes),\n\t}\n\n\tfor _, bset := range sets {\n\t\tif len(bset) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar fset set\n\t\tvar b strings.Builder\n\n\t\tlines := bytes.Split(bset, []byte(\"\\r\\n\"))\n\n\t\tm := reHead.FindSubmatch(lines[0])\n\t\tif m == nil {\n\t\t\ttemplate.HTMLEscape(&b, bset)\n\t\t\tfset.Text = template.HTML(b.String())\n\t\t\tfpaste.Paste = append(fpaste.Paste, fset)\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(m[2]) != 0 {\n\t\t\tif p, ok := pokemonData[string(m[2])]; ok {\n\t\t\t\tfset.Pokemon = p[\"id\"].(uint)\n\t\t\t\tfset.Form = p[\"form\"].(uint)\n\t\t\t\ttemplate.HTMLEscape(&b, m[1])\n\t\t\t\tb.WriteString(`<span class=\"type-`)\n\t\t\t\tb.WriteString(p[\"type\"].(string))\n\t\t\t\tb.WriteString(`\">`)\n\t\t\t\ttemplate.HTMLEscape(&b, m[2])\n\t\t\t\tb.WriteString(`<\/span>`)\n\t\t\t\ttemplate.HTMLEscape(&b, m[3])\n\t\t\t} else {\n\t\t\t\ttemplate.HTMLEscape(&b, m[1])\n\t\t\t\ttemplate.HTMLEscape(&b, m[2])\n\t\t\t\ttemplate.HTMLEscape(&b, m[3])\n\t\t\t}\n\t\t} else if len(m[4]) != 0 {\n\t\t\tif p, ok := pokemonData[string(m[4])]; ok {\n\t\t\t\tfset.Pokemon = p[\"id\"].(uint)\n\t\t\t\tfset.Form = p[\"form\"].(uint)\n\t\t\t\tb.WriteString(`<span class=\"type-`)\n\t\t\t\tb.WriteString(p[\"type\"].(string))\n\t\t\t\tb.WriteString(`\">`)\n\t\t\t\ttemplate.HTMLEscape(&b, m[4])\n\t\t\t\tb.WriteString(`<\/span>`)\n\t\t\t} else {\n\t\t\t\ttemplate.HTMLEscape(&b, m[4])\n\t\t\t}\n\t\t}\n\n\t\tif len(m[6]) != 0 {\n\t\t\ttemplate.HTMLEscape(&b, m[5])\n\t\t\tif m[6][0] == 'M' {\n\t\t\t\tb.WriteString(`<span class=\"gender-m\">`)\n\t\t\t} else if m[6][0] == 'F' {\n\t\t\t\tb.WriteString(`<span class=\"gender-f\">`)\n\t\t\t} else {\n\t\t\t\tb.WriteString(`<span>`)\n\t\t\t}\n\t\t\ttemplate.HTMLEscape(&b, m[6])\n\t\t\tb.WriteString(`<\/span>`)\n\t\t\ttemplate.HTMLEscape(&b, m[7])\n\t\t}\n\n\t\tif len(m[9]) != 0 {\n\t\t\tif i, ok := itemData[string(m[9])]; ok {\n\t\t\t\tfset.Item = i[\"id\"].(uint)\n\t\t\t\ttemplate.HTMLEscape(&b, m[8])\n\t\t\t\tif t, ok := i[\"type\"]; ok {\n\t\t\t\t\tb.WriteString(`<span class=\"type-`)\n\t\t\t\t\tb.WriteString(t.(string))\n\t\t\t\t\tb.WriteString(`\">`)\n\t\t\t\t\ttemplate.HTMLEscape(&b, m[9])\n\t\t\t\t\tb.WriteString(`<\/span>`)\n\t\t\t\t} else {\n\t\t\t\t\ttemplate.HTMLEscape(&b, m[9])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttemplate.HTMLEscape(&b, m[8])\n\t\t\t\ttemplate.HTMLEscape(&b, m[9])\n\t\t\t}\n\t\t}\n\n\t\tb.Write(m[10])\n\t\tb.WriteByte('\\n')\n\n\t\tfor _, line := range lines[1:] {\n\t\t\tif m := reMove.FindSubmatch(line); m != nil {\n\t\t\t\tif mv, ok := moveData[string(m[3])]; ok {\n\t\t\t\t\tb.WriteString(`<span class=\"type-`)\n\t\t\t\t\tif len(m[4]) > 0 {\n\t\t\t\t\t\ttemplate.HTMLEscape(&b, bytes.ToLower(m[4]))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tb.WriteString(mv[\"type\"].(string))\n\t\t\t\t\t}\n\t\t\t\t\tb.WriteString(`\">`)\n\t\t\t\t\ttemplate.HTMLEscape(&b, m[1])\n\t\t\t\t\tb.WriteString(`<\/span>`)\n\t\t\t\t} else {\n\t\t\t\t\ttemplate.HTMLEscape(&b, m[1])\n\t\t\t\t}\n\t\t\t\ttemplate.HTMLEscape(&b, m[2])\n\t\t\t} else if m := bytes.SplitAfterN(line, []byte(\": \"), 2); len(m) == 2 {\n\t\t\t\tb.WriteString(`<span class=\"attr\">`)\n\t\t\t\ttemplate.HTMLEscape(&b, m[0])\n\t\t\t\tb.WriteString(`<\/span>`)\n\t\t\t\tif len(m[0]) == 5 && m[0][1] == 'V' && m[0][2] == 's' {\n\t\t\t\t\tattr := m[1]\n\t\t\t\t\tif m := reStat.FindSubmatch(attr); m != nil {\n\t\t\t\t\t\tfor i, stat := range [...]string{\"hp\", \"atk\", \"def\", \"spa\", \"spd\", \"spe\"} {\n\t\t\t\t\t\t\tif len(m[i*2+1]) > 0 {\n\t\t\t\t\t\t\t\tb.WriteString(`<span class=\"stat-`)\n\t\t\t\t\t\t\t\tb.WriteString(stat)\n\t\t\t\t\t\t\t\tb.WriteString(`\">`)\n\t\t\t\t\t\t\t\ttemplate.HTMLEscape(&b, m[i*2+1])\n\t\t\t\t\t\t\t\tb.WriteString(`<\/span>`)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttemplate.HTMLEscape(&b, m[i*2+2])\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttemplate.HTMLEscape(&b, attr)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\ttemplate.HTMLEscape(&b, m[1])\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttemplate.HTMLEscape(&b, line)\n\t\t\t}\n\t\t\tb.WriteByte('\\n')\n\t\t}\n\n\t\tfset.Text = template.HTML(b.String())\n\n\t\tfpaste.Paste = append(fpaste.Paste, fset)\n\t}\n\n\terr := tmpl.Execute(w, fpaste)\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/mesosphere\/dcos-commons\/cli\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc main() {\n\tmodName, err := cli.GetModuleName()\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\n\tapp, err := cli.NewApp(\n\t\t\"0.1.0\",\n\t\t\"Mesosphere\",\n\t\tfmt.Sprintf(\"Deploy and manage %s clusters\", strings.Title(modName)))\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\n\t\/\/ Omit standard \"connection\" section. Cassandra isn't on the standard paths yet, and omit\n\t\/\/ standard \"config\" and \"state\" sections since Cassandra isn't installing\n\t\/\/ ConfigResource\/StateResource yet.\n\t\/\/ Once these are fixed, this block can all be replaced with a call to \"HandleCommonArgs\"\n\tcli.HandleCommonFlags(app, modName, fmt.Sprintf(\"%s DC\/OS CLI Module\", strings.Title(modName)))\n\t\/\/cli.HandleConfigSection(app)\n\t\/\/cli.HandleConnectionSection(app)\n\tcli.HandlePlanSection(app)\n\t\/\/cli.HandleStateSection(app)\n\n\thandleSeedsCommand(app)\n\thandleCustomConnectionCommand(app, modName)\n\n\thandleNodeSection(app, modName)\n\thandleBackupRestoreSections(app, modName)\n\thandleCleanupRepairSections(app)\n\n\t\/\/ Omit modname:\n\tkingpin.MustParse(app.Parse(os.Args[2:]))\n}\n\nfunc handleSeedsCommand(app *kingpin.Application) {\n\tapp.Command(\"seeds\", \"Retrieve seed node information\").Action(\n\t\tfunc(c *kingpin.ParseContext) error {\n\t\t\tcli.PrintJSON(cli.HTTPGet(\"v1\/seeds\"))\n\t\t\treturn nil\n\t\t})\n}\n\ntype ConnectionHandler struct {\n\tshowAddress bool\n\tshowDns bool\n}\nfunc (cmd *ConnectionHandler) runBase(c *kingpin.ParseContext) error {\n\tif cmd.showAddress {\n\t\tcli.PrintJSON(cli.HTTPGet(\"v1\/nodes\/connect\/address\"))\n\t} else if cmd.showDns {\n\t\tcli.PrintJSON(cli.HTTPGet(\"v1\/nodes\/connect\/dns\"))\n\t} else {\n\t\tcli.PrintJSON(cli.HTTPGet(\"v1\/nodes\/connect\"))\n\t}\n\treturn nil\n}\nfunc handleCustomConnectionCommand(app *kingpin.Application, modName string) {\n\tcmd := &ConnectionHandler{}\n\n\t\/\/ Have three explicit commands, to ensure that each possibility shows up in --help:\n\tconnection := app.Command(\"connection\", fmt.Sprintf(\"Provides %s connection information\", modName)).Action(cmd.runBase)\n\tconnection.Flag(\"address\", fmt.Sprintf(\"Provide addresses of the %s nodes\", modName)).BoolVar(&cmd.showAddress)\n\tconnection.Flag(\"dns\", fmt.Sprintf(\"Provide dns names of the %s nodes\", modName)).BoolVar(&cmd.showDns)\n}\n\n\ntype NodeHandler struct {\n\tnodeId int\n}\nfunc (cmd *NodeHandler) runDescribe(c *kingpin.ParseContext) error {\n\tcli.PrintJSON(cli.HTTPGet(fmt.Sprintf(\"v1\/nodes\/node-%d\/info\", cmd.nodeId)))\n\treturn nil\n}\nfunc (cmd *NodeHandler) runList(c *kingpin.ParseContext) error {\n\tcli.PrintJSON(cli.HTTPGet(\"v1\/nodes\/list\"))\n\treturn nil\n}\nfunc (cmd *NodeHandler) runReplace(c *kingpin.ParseContext) error {\n\tcli.PrintJSON(cli.HTTPGet(fmt.Sprintf(\"v1\/nodes\/replace?node=node-%d\", cmd.nodeId)))\n\treturn nil\n}\nfunc (cmd *NodeHandler) runRestart(c *kingpin.ParseContext) error {\n\tcli.PrintJSON(cli.HTTPGet(fmt.Sprintf(\"v1\/nodes\/restart?node=node-%d\", cmd.nodeId)))\n\treturn nil\n}\nfunc (cmd *NodeHandler) runStatus(c *kingpin.ParseContext) error {\n\tcli.PrintJSON(cli.HTTPGet(fmt.Sprintf(\"v1\/nodes\/node-%d\/status\", cmd.nodeId)))\n\treturn nil\n}\nfunc handleNodeSection(app *kingpin.Application, modName string) {\n\tcmd := &NodeHandler{}\n\tconnection := app.Command(\"node\", fmt.Sprintf(\"Manage %s nodes\", modName))\n\n\tdescribe := connection.Command(\"describe\", \"Describes a single node\").Action(cmd.runDescribe)\n\tdescribe.Arg(\"node_id\", \"The node id to describe\").IntVar(&cmd.nodeId)\n\n\tconnection.Command(\"list\", \"Lists all nodes\").Action(cmd.runList)\n\n\treplace := connection.Command(\"replace\", \"Replaces a single node job, moving it to a different agent\").Action(cmd.runReplace)\n\treplace.Arg(\"node_id\", \"The node id to replace\").IntVar(&cmd.nodeId)\n\n\trestart := connection.Command(\"restart\", \"Restarts a single node job, keeping it on the same agent\").Action(cmd.runRestart)\n\trestart.Arg(\"node_id\", \"The node id to restart\").IntVar(&cmd.nodeId)\n\n\tstatus := connection.Command(\"status\", \"Gets the status of a single node\").Action(cmd.runStatus)\n\tstatus.Arg(\"node_id\", \"The node id to check\").IntVar(&cmd.nodeId)\n}\n\n\/\/ Reuse same struct for both 'backup start' and 'restore start' (same args)\ntype BackupRestoreHandler struct {\n\tbackupName string\n\texternalLocation string\n\ts3AccessKey string\n\ts3SecretKey string\n\tazureAccount string\n\tazureKey string\n}\nfunc (cmd *BackupRestoreHandler) getArgs() map[string]interface{} {\n\treturn map[string]interface{} {\n\t\t\"backup_name\": cmd.backupName,\n\t\t\"external_location\": cmd.externalLocation,\n\t\t\"s3_access_key\": cmd.s3AccessKey,\n\t\t\"s3_secret_key\": cmd.s3SecretKey,\n\t\t\"azure_account\": cmd.azureAccount,\n\t\t\"key\": cmd.azureKey,\n\t}\n}\nfunc (cmd *BackupRestoreHandler) runBackup(c *kingpin.ParseContext) error {\n\tpayload, err := json.Marshal(cmd.getArgs())\n\tif err != nil {\n\t\treturn err\n\t}\n\tcli.PrintJSON(cli.HTTPPutJSON(\"v1\/backup\/start\", string(payload)))\n\treturn nil\n}\nfunc (cmd *BackupRestoreHandler) runRestore(c *kingpin.ParseContext) error {\n\tpayload, err := json.Marshal(cmd.getArgs())\n\tif err != nil {\n\t\treturn err\n\t}\n\tcli.PrintJSON(cli.HTTPPutJSON(\"v1\/restore\/start\", string(payload)))\n\treturn nil\n}\nfunc handleBackupRestoreSections(app *kingpin.Application, modName string) {\n\tcmd := &BackupRestoreHandler{}\n\tplanCmd := &cli.PlanHandler{}\n\n\tbackup := app.Command(\"backup\", fmt.Sprintf(\"Backup %s cluster data\", modName))\n\tbackupStart := backup.Command(\n\t\t\"start\",\n\t\t\"Perform cluster backup via snapshot mechanism\").Action(cmd.runBackup)\n\tbackupStart.Flag(\"backup_name\", \"Name of the snapshot\").StringVar(&cmd.backupName)\n\tbackupStart.Flag(\"external_location\", \"External location where the snapshot should be stored\").StringVar(&cmd.externalLocation)\n\tbackupStart.Flag(\"s3_access_key\", \"S3 access key\").StringVar(&cmd.s3AccessKey)\n\tbackupStart.Flag(\"s3_secret_key\", \"S3 secret key\").StringVar(&cmd.s3SecretKey)\n\tbackupStart.Flag(\"azure_account\", \"Azure storage account\").StringVar(&cmd.azureAccount)\n\tbackupStart.Flag(\"azure_key\", \"Azure secret key\").StringVar(&cmd.azureKey)\n\t\/\/ same as 'plan show':\n\tbackup.Command(\n\t\t\"status\",\n\t\t\"Displays the status of the backup\").Action(planCmd.RunShow)\n\n\trestore := app.Command(\"restore\", fmt.Sprintf(\"Restore %s cluster from backup\", modName))\n\trestoreStart := restore.Command(\n\t\t\"start\",\n\t\t\"Restores cluster to a previous snapshot\").Action(cmd.runRestore)\n\trestoreStart.Flag(\"backup_name\", \"Name of the snapshot to restore\").StringVar(&cmd.backupName)\n\trestoreStart.Flag(\"external_location\", \"External location where the snapshot is stored\").StringVar(&cmd.externalLocation)\n\trestoreStart.Flag(\"s3_access_key\", \"S3 access key\").StringVar(&cmd.s3AccessKey)\n\trestoreStart.Flag(\"s3_secret_key\", \"S3 secret key\").StringVar(&cmd.s3SecretKey)\n\trestoreStart.Flag(\"azure_account\", \"Azure storage account\").StringVar(&cmd.azureAccount)\n\trestoreStart.Flag(\"azure_key\", \"Azure secret key\").StringVar(&cmd.azureKey)\n\t\/\/ same as 'plan show':\n\trestore.Command(\n\t\t\"status\",\n\t\t\"Displays the status of the restore\").Action(planCmd.RunShow)\n}\n\n\/\/ Reuse same struct for both 'cleanup start' and 'repair start' (same args)\ntype CleanupRepairHandler struct {\n\tnodes string\n\tkeySpaces string\n\tcolumnFamilies string\n}\nfunc (cmd *CleanupRepairHandler) getArgs() map[string]interface{} {\n\tnodesList := []string{}\n\tfor _, node := range strings.Split(cmd.nodes, \",\") {\n\t\tnodesList = append(nodesList, fmt.Sprintf(\"node-%s\", strings.TrimSpace(node)))\n\t}\n\n\tdict := map[string]interface{} {\"nodes\": nodesList}\n\n\tif len(cmd.keySpaces) != 0 {\n\t\tdict[\"key_spaces\"] = cmd.keySpaces\n\t}\n\tif len(cmd.keySpaces) != 0 {\n\t\tdict[\"column_families\"] = cmd.columnFamilies\n\t}\n\treturn dict\n}\nfunc (cmd *CleanupRepairHandler) runCleanup(c *kingpin.ParseContext) error {\n\tpayload, err := json.Marshal(cmd.getArgs())\n\tif err != nil {\n\t\treturn err\n\t}\n\tcli.PrintJSON(cli.HTTPPutJSON(\"v1\/cleanup\/start\", string(payload)))\n\treturn nil\n}\nfunc (cmd *CleanupRepairHandler) runRepair(c *kingpin.ParseContext) error {\n\tpayload, err := json.Marshal(cmd.getArgs())\n\tif err != nil {\n\t\treturn err\n\t}\n\tcli.PrintJSON(cli.HTTPPutJSON(\"v1\/repair\/start\", string(payload)))\n\treturn nil\n}\nfunc handleCleanupRepairSections(app *kingpin.Application) {\n\tcmd := &CleanupRepairHandler{}\n\n\tcleanup := app.Command(\"cleanup\", \"Clean up old token mappings\")\n\tcleanupStart := cleanup.Command(\n\t\t\"start\",\n\t\t\"Perform cluster cleanup of deleted or moved keys\").Action(cmd.runCleanup)\n\tcleanupStart.Flag(\"nodes\", \"A list of the nodes to cleanup or * for all.\").Default(\"*\").StringVar(&cmd.nodes)\n\tcleanupStart.Flag(\"key_spaces\", \"The key spaces to cleanup or empty for all.\").StringVar(&cmd.keySpaces)\n\tcleanupStart.Flag(\"column_families\", \"The column families to cleanup.\").StringVar(&cmd.columnFamilies)\n\n\trepair := app.Command(\"repair\", \"Perform primary range repair\")\n\trepairStart := repair.Command(\n\t\t\"start\",\n\t\t\"Perform primary range anti-entropy repair\").Action(cmd.runRepair)\n\trepairStart.Flag(\"nodes\", \"A list of the nodes to repair or * for all.\").Default(\"*\").StringVar(&cmd.nodes)\n\trepairStart.Flag(\"key_spaces\", \"The key spaces to repair or empty for all.\").StringVar(&cmd.keySpaces)\n\trepairStart.Flag(\"column_families\", \"The column families to repair.\").StringVar(&cmd.columnFamilies)\n}\n<commit_msg>Fix query params for replace\/restart<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/mesosphere\/dcos-commons\/cli\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"log\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc main() {\n\tmodName, err := cli.GetModuleName()\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\n\tapp, err := cli.NewApp(\n\t\t\"0.1.0\",\n\t\t\"Mesosphere\",\n\t\tfmt.Sprintf(\"Deploy and manage %s clusters\", strings.Title(modName)))\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\n\t\/\/ Omit standard \"connection\" section. Cassandra isn't on the standard paths yet, and omit\n\t\/\/ standard \"config\" and \"state\" sections since Cassandra isn't installing\n\t\/\/ ConfigResource\/StateResource yet.\n\t\/\/ Once these are fixed, this block can all be replaced with a call to \"HandleCommonArgs\"\n\tcli.HandleCommonFlags(app, modName, fmt.Sprintf(\"%s DC\/OS CLI Module\", strings.Title(modName)))\n\t\/\/cli.HandleConfigSection(app)\n\t\/\/cli.HandleConnectionSection(app)\n\tcli.HandlePlanSection(app)\n\t\/\/cli.HandleStateSection(app)\n\n\thandleSeedsCommand(app)\n\thandleCustomConnectionCommand(app, modName)\n\n\thandleNodeSection(app, modName)\n\thandleBackupRestoreSections(app, modName)\n\thandleCleanupRepairSections(app)\n\n\t\/\/ Omit modname:\n\tkingpin.MustParse(app.Parse(os.Args[2:]))\n}\n\nfunc handleSeedsCommand(app *kingpin.Application) {\n\tapp.Command(\"seeds\", \"Retrieve seed node information\").Action(\n\t\tfunc(c *kingpin.ParseContext) error {\n\t\t\tcli.PrintJSON(cli.HTTPGet(\"v1\/seeds\"))\n\t\t\treturn nil\n\t\t})\n}\n\ntype ConnectionHandler struct {\n\tshowAddress bool\n\tshowDns bool\n}\nfunc (cmd *ConnectionHandler) runBase(c *kingpin.ParseContext) error {\n\tif cmd.showAddress {\n\t\tcli.PrintJSON(cli.HTTPGet(\"v1\/nodes\/connect\/address\"))\n\t} else if cmd.showDns {\n\t\tcli.PrintJSON(cli.HTTPGet(\"v1\/nodes\/connect\/dns\"))\n\t} else {\n\t\tcli.PrintJSON(cli.HTTPGet(\"v1\/nodes\/connect\"))\n\t}\n\treturn nil\n}\nfunc handleCustomConnectionCommand(app *kingpin.Application, modName string) {\n\tcmd := &ConnectionHandler{}\n\n\t\/\/ Have three explicit commands, to ensure that each possibility shows up in --help:\n\tconnection := app.Command(\"connection\", fmt.Sprintf(\"Provides %s connection information\", modName)).Action(cmd.runBase)\n\tconnection.Flag(\"address\", fmt.Sprintf(\"Provide addresses of the %s nodes\", modName)).BoolVar(&cmd.showAddress)\n\tconnection.Flag(\"dns\", fmt.Sprintf(\"Provide dns names of the %s nodes\", modName)).BoolVar(&cmd.showDns)\n}\n\n\ntype NodeHandler struct {\n\tnodeId int\n}\nfunc (cmd *NodeHandler) runDescribe(c *kingpin.ParseContext) error {\n\tcli.PrintJSON(cli.HTTPGet(fmt.Sprintf(\"v1\/nodes\/node-%d\/info\", cmd.nodeId)))\n\treturn nil\n}\nfunc (cmd *NodeHandler) runList(c *kingpin.ParseContext) error {\n\tcli.PrintJSON(cli.HTTPGet(\"v1\/nodes\/list\"))\n\treturn nil\n}\nfunc (cmd *NodeHandler) runReplace(c *kingpin.ParseContext) error {\n\tquery := url.Values{}\n\tquery.Set(\"node\", fmt.Sprintf(\"node-%d\", cmd.nodeId))\n\tcli.PrintJSON(cli.HTTPGetQuery(\"v1\/nodes\/replace\", query.Encode()))\n\treturn nil\n}\nfunc (cmd *NodeHandler) runRestart(c *kingpin.ParseContext) error {\n\tquery := url.Values{}\n\tquery.Set(\"node\", fmt.Sprintf(\"node-%d\", cmd.nodeId))\n\tcli.PrintJSON(cli.HTTPGetQuery(\"v1\/nodes\/restart\", query.Encode()))\n\treturn nil\n}\nfunc (cmd *NodeHandler) runStatus(c *kingpin.ParseContext) error {\n\tcli.PrintJSON(cli.HTTPGet(fmt.Sprintf(\"v1\/nodes\/node-%d\/status\", cmd.nodeId)))\n\treturn nil\n}\nfunc handleNodeSection(app *kingpin.Application, modName string) {\n\tcmd := &NodeHandler{}\n\tconnection := app.Command(\"node\", fmt.Sprintf(\"Manage %s nodes\", modName))\n\n\tdescribe := connection.Command(\"describe\", \"Describes a single node\").Action(cmd.runDescribe)\n\tdescribe.Arg(\"node_id\", \"The node id to describe\").IntVar(&cmd.nodeId)\n\n\tconnection.Command(\"list\", \"Lists all nodes\").Action(cmd.runList)\n\n\treplace := connection.Command(\"replace\", \"Replaces a single node job, moving it to a different agent\").Action(cmd.runReplace)\n\treplace.Arg(\"node_id\", \"The node id to replace\").IntVar(&cmd.nodeId)\n\n\trestart := connection.Command(\"restart\", \"Restarts a single node job, keeping it on the same agent\").Action(cmd.runRestart)\n\trestart.Arg(\"node_id\", \"The node id to restart\").IntVar(&cmd.nodeId)\n\n\tstatus := connection.Command(\"status\", \"Gets the status of a single node\").Action(cmd.runStatus)\n\tstatus.Arg(\"node_id\", \"The node id to check\").IntVar(&cmd.nodeId)\n}\n\n\/\/ Reuse same struct for both 'backup start' and 'restore start' (same args)\ntype BackupRestoreHandler struct {\n\tbackupName string\n\texternalLocation string\n\ts3AccessKey string\n\ts3SecretKey string\n\tazureAccount string\n\tazureKey string\n}\nfunc (cmd *BackupRestoreHandler) getArgs() map[string]interface{} {\n\treturn map[string]interface{} {\n\t\t\"backup_name\": cmd.backupName,\n\t\t\"external_location\": cmd.externalLocation,\n\t\t\"s3_access_key\": cmd.s3AccessKey,\n\t\t\"s3_secret_key\": cmd.s3SecretKey,\n\t\t\"azure_account\": cmd.azureAccount,\n\t\t\"key\": cmd.azureKey,\n\t}\n}\nfunc (cmd *BackupRestoreHandler) runBackup(c *kingpin.ParseContext) error {\n\tpayload, err := json.Marshal(cmd.getArgs())\n\tif err != nil {\n\t\treturn err\n\t}\n\tcli.PrintJSON(cli.HTTPPutJSON(\"v1\/backup\/start\", string(payload)))\n\treturn nil\n}\nfunc (cmd *BackupRestoreHandler) runRestore(c *kingpin.ParseContext) error {\n\tpayload, err := json.Marshal(cmd.getArgs())\n\tif err != nil {\n\t\treturn err\n\t}\n\tcli.PrintJSON(cli.HTTPPutJSON(\"v1\/restore\/start\", string(payload)))\n\treturn nil\n}\nfunc handleBackupRestoreSections(app *kingpin.Application, modName string) {\n\tcmd := &BackupRestoreHandler{}\n\tplanCmd := &cli.PlanHandler{}\n\n\tbackup := app.Command(\"backup\", fmt.Sprintf(\"Backup %s cluster data\", modName))\n\tbackupStart := backup.Command(\n\t\t\"start\",\n\t\t\"Perform cluster backup via snapshot mechanism\").Action(cmd.runBackup)\n\tbackupStart.Flag(\"backup_name\", \"Name of the snapshot\").StringVar(&cmd.backupName)\n\tbackupStart.Flag(\"external_location\", \"External location where the snapshot should be stored\").StringVar(&cmd.externalLocation)\n\tbackupStart.Flag(\"s3_access_key\", \"S3 access key\").StringVar(&cmd.s3AccessKey)\n\tbackupStart.Flag(\"s3_secret_key\", \"S3 secret key\").StringVar(&cmd.s3SecretKey)\n\tbackupStart.Flag(\"azure_account\", \"Azure storage account\").StringVar(&cmd.azureAccount)\n\tbackupStart.Flag(\"azure_key\", \"Azure secret key\").StringVar(&cmd.azureKey)\n\t\/\/ same as 'plan show':\n\tbackup.Command(\n\t\t\"status\",\n\t\t\"Displays the status of the backup\").Action(planCmd.RunShow)\n\n\trestore := app.Command(\"restore\", fmt.Sprintf(\"Restore %s cluster from backup\", modName))\n\trestoreStart := restore.Command(\n\t\t\"start\",\n\t\t\"Restores cluster to a previous snapshot\").Action(cmd.runRestore)\n\trestoreStart.Flag(\"backup_name\", \"Name of the snapshot to restore\").StringVar(&cmd.backupName)\n\trestoreStart.Flag(\"external_location\", \"External location where the snapshot is stored\").StringVar(&cmd.externalLocation)\n\trestoreStart.Flag(\"s3_access_key\", \"S3 access key\").StringVar(&cmd.s3AccessKey)\n\trestoreStart.Flag(\"s3_secret_key\", \"S3 secret key\").StringVar(&cmd.s3SecretKey)\n\trestoreStart.Flag(\"azure_account\", \"Azure storage account\").StringVar(&cmd.azureAccount)\n\trestoreStart.Flag(\"azure_key\", \"Azure secret key\").StringVar(&cmd.azureKey)\n\t\/\/ same as 'plan show':\n\trestore.Command(\n\t\t\"status\",\n\t\t\"Displays the status of the restore\").Action(planCmd.RunShow)\n}\n\n\/\/ Reuse same struct for both 'cleanup start' and 'repair start' (same args)\ntype CleanupRepairHandler struct {\n\tnodes string\n\tkeySpaces string\n\tcolumnFamilies string\n}\nfunc (cmd *CleanupRepairHandler) getArgs() map[string]interface{} {\n\tnodesList := []string{}\n\tfor _, node := range strings.Split(cmd.nodes, \",\") {\n\t\tnodesList = append(nodesList, fmt.Sprintf(\"node-%s\", strings.TrimSpace(node)))\n\t}\n\n\tdict := map[string]interface{} {\"nodes\": nodesList}\n\n\tif len(cmd.keySpaces) != 0 {\n\t\tdict[\"key_spaces\"] = cmd.keySpaces\n\t}\n\tif len(cmd.keySpaces) != 0 {\n\t\tdict[\"column_families\"] = cmd.columnFamilies\n\t}\n\treturn dict\n}\nfunc (cmd *CleanupRepairHandler) runCleanup(c *kingpin.ParseContext) error {\n\tpayload, err := json.Marshal(cmd.getArgs())\n\tif err != nil {\n\t\treturn err\n\t}\n\tcli.PrintJSON(cli.HTTPPutJSON(\"v1\/cleanup\/start\", string(payload)))\n\treturn nil\n}\nfunc (cmd *CleanupRepairHandler) runRepair(c *kingpin.ParseContext) error {\n\tpayload, err := json.Marshal(cmd.getArgs())\n\tif err != nil {\n\t\treturn err\n\t}\n\tcli.PrintJSON(cli.HTTPPutJSON(\"v1\/repair\/start\", string(payload)))\n\treturn nil\n}\nfunc handleCleanupRepairSections(app *kingpin.Application) {\n\tcmd := &CleanupRepairHandler{}\n\n\tcleanup := app.Command(\"cleanup\", \"Clean up old token mappings\")\n\tcleanupStart := cleanup.Command(\n\t\t\"start\",\n\t\t\"Perform cluster cleanup of deleted or moved keys\").Action(cmd.runCleanup)\n\tcleanupStart.Flag(\"nodes\", \"A list of the nodes to cleanup or * for all.\").Default(\"*\").StringVar(&cmd.nodes)\n\tcleanupStart.Flag(\"key_spaces\", \"The key spaces to cleanup or empty for all.\").StringVar(&cmd.keySpaces)\n\tcleanupStart.Flag(\"column_families\", \"The column families to cleanup.\").StringVar(&cmd.columnFamilies)\n\n\trepair := app.Command(\"repair\", \"Perform primary range repair\")\n\trepairStart := repair.Command(\n\t\t\"start\",\n\t\t\"Perform primary range anti-entropy repair\").Action(cmd.runRepair)\n\trepairStart.Flag(\"nodes\", \"A list of the nodes to repair or * for all.\").Default(\"*\").StringVar(&cmd.nodes)\n\trepairStart.Flag(\"key_spaces\", \"The key spaces to repair or empty for all.\").StringVar(&cmd.keySpaces)\n\trepairStart.Flag(\"column_families\", \"The column families to repair.\").StringVar(&cmd.columnFamilies)\n}\n<|endoftext|>"}
{"text":"<commit_before>package wspacego\n\nimport (\n\t. \"github.com\/r7kamura\/gospel\"\n\t\"testing\"\n)\n\nfunc TestCommnad(t *testing.T) {\n\tDescribe(t, \"Command Tests\", func() {\n\t\tContext(\"コマンドだけ指定する\", func() {\n\t\t\tIt(\"インスタンスが作成できること\", func() {\n\t\t\t\tcmd := \"cmd\"\n\t\t\t\tsut := NewCommand(cmd)\n\t\t\t\tExpect(sut).To(Exist)\n\t\t\t})\n\t\t\tIt(\"コマンドだけ変数が書き換えられていること\", func() {\n\t\t\t\tcmd := \"cmd\"\n\t\t\t\tsut := NewCommand(cmd)\n\t\t\t\tExpect(sut.cmd).To(Equal, cmd)\n\t\t\t\tExpect(sut.subcmd).To(Equal, \"\")\n\t\t\t\tExpect(sut.param).To(Equal, 0)\n\t\t\t})\n\t\t})\n\t\tContext(\"サブコマンドを作成する\", func() {\n\t\t\tIt(\"インスタンスが作成できること\", func() {\n\t\t\t\tcmd, subcmd := \"cmd\", \"subcmd\"\n\t\t\t\tExpect(NewSubCommand(cmd, subcmd)).To(Exist)\n\t\t\t})\n\t\t\tIt(\"コマンドとサブコマンドが指定した値で書き換えられていること\", func() {\n\t\t\t\tcmd, subcmd := \"cmd\", \"subcmd\"\n\t\t\t\tsut := NewSubCommand(cmd, subcmd)\n\t\t\t\tExpect(sut.cmd).To(Equal, cmd)\n\t\t\t\tExpect(sut.subcmd).To(Equal, subcmd)\n\t\t\t\tExpect(sut.param).To(Equal, 0)\n\t\t\t})\n\t\t})\n\t\tContext(\"Create Instance\", func() {\n\t\t\tIt(\"is exists\", func() {\n\t\t\t\tcmd := \"cmd\"\n\t\t\t\tparam := 1\n\t\t\t\tsut := NewCommandWithParam(cmd, param)\n\t\t\t\tExpect(sut).To(Exist)\n\t\t\t})\n\t\t})\n\t\tContext(\"Create Instance\", func() {\n\t\t\tIt(\"Initialize Instance\", func() {\n\t\t\t\tcmd := \"cmd\"\n\t\t\t\tparam := 1\n\t\t\t\tsut := NewCommandWithParam(cmd, param)\n\t\t\t\tExpect(sut.cmd).To(Equal, cmd)\n\t\t\t\tExpect(sut.subcmd).To(Equal, \"\")\n\t\t\t\tExpect(sut.param).To(Equal, 1)\n\t\t\t})\n\t\t})\n\t})\n}\n<commit_msg>パラメータ付きコマンド作成関数のテストケースを変更<commit_after>package wspacego\n\nimport (\n\t. \"github.com\/r7kamura\/gospel\"\n\t\"testing\"\n)\n\nfunc TestCommnad(t *testing.T) {\n\tDescribe(t, \"Command Tests\", func() {\n\t\tContext(\"コマンドだけ指定する\", func() {\n\t\t\tIt(\"インスタンスが作成できること\", func() {\n\t\t\t\tcmd := \"cmd\"\n\t\t\t\tsut := NewCommand(cmd)\n\t\t\t\tExpect(sut).To(Exist)\n\t\t\t})\n\t\t\tIt(\"コマンドだけ変数が書き換えられていること\", func() {\n\t\t\t\tcmd := \"cmd\"\n\t\t\t\tsut := NewCommand(cmd)\n\t\t\t\tExpect(sut.cmd).To(Equal, cmd)\n\t\t\t\tExpect(sut.subcmd).To(Equal, \"\")\n\t\t\t\tExpect(sut.param).To(Equal, 0)\n\t\t\t})\n\t\t})\n\t\tContext(\"サブコマンドを作成する\", func() {\n\t\t\tIt(\"インスタンスが作成できること\", func() {\n\t\t\t\tcmd, subcmd := \"cmd\", \"subcmd\"\n\t\t\t\tExpect(NewSubCommand(cmd, subcmd)).To(Exist)\n\t\t\t})\n\t\t\tIt(\"コマンドとサブコマンドが指定した値で書き換えられていること\", func() {\n\t\t\t\tcmd, subcmd := \"cmd\", \"subcmd\"\n\t\t\t\tsut := NewSubCommand(cmd, subcmd)\n\t\t\t\tExpect(sut.cmd).To(Equal, cmd)\n\t\t\t\tExpect(sut.subcmd).To(Equal, subcmd)\n\t\t\t\tExpect(sut.param).To(Equal, 0)\n\t\t\t})\n\t\t})\n\t\tContext(\"パラメータ付きのコマンドを作成する\", func() {\n\t\t\tIt(\"インスタンスが作成できること\", func() {\n\t\t\t\tcmd := \"cmd\"\n\t\t\t\tparam := 1\n\t\t\t\tsut := NewCommandWithParam(cmd, param)\n\t\t\t\tExpect(sut).To(Exist)\n\t\t\t})\n\t\t\tIt(\"コマンドとパラメータが指定した値で書き換えられていること\", func() {\n\t\t\t\tcmd := \"cmd\"\n\t\t\t\tparam := 1\n\t\t\t\tsut := NewCommandWithParam(cmd, param)\n\t\t\t\tExpect(sut.cmd).To(Equal, cmd)\n\t\t\t\tExpect(sut.subcmd).To(Equal, \"\")\n\t\t\t\tExpect(sut.param).To(Equal, 1)\n\t\t\t})\n\t\t})\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package cl11\n\nimport (\n\t\"strings\"\n\n\tclw \"github.com\/rdwilliamson\/clw11\"\n)\n\n\/\/ Not thread safe.\ntype CommandQueue struct {\n\tid         clw.CommandQueue\n\tContext    *Context\n\tDevice     *Device\n\tProperties CommandQueueProperties\n\n\t\/\/ Scratch space to avoid allocating memory when converting a wait list.\n\teventsScratch []clw.Event\n}\n\ntype CommandQueueProperties int\n\n\/\/ Bitfield.\nconst (\n\tQueueOutOfOrderExecution = CommandQueueProperties(clw.QueueOutOfOrderExecModeEnable)\n\tQueueProfilingEnable     = CommandQueueProperties(clw.QueueProfilingEnable)\n)\n\nfunc (cqp CommandQueueProperties) String() string {\n\tvar propertiesStrings []string\n\tif cqp&QueueOutOfOrderExecution != 0 {\n\t\tpropertiesStrings = append(propertiesStrings, \"out of order execution\")\n\t}\n\tif cqp&QueueProfilingEnable != 0 {\n\t\tpropertiesStrings = append(propertiesStrings, \"profiling\")\n\t}\n\treturn \"{\" + strings.Join(propertiesStrings, \", \") + \"}\"\n}\n\nfunc (c *Context) CreateCommandQueue(d *Device, cqp CommandQueueProperties) (*CommandQueue, error) {\n\n\tcommandQueue, err := clw.CreateCommandQueue(c.id, d.id, clw.CommandQueueProperties(cqp))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &CommandQueue{id: commandQueue, Context: c, Device: d, Properties: cqp}, nil\n}\n\nfunc (cq *CommandQueue) Flush() error {\n\treturn clw.Flush(cq.id)\n}\n\nfunc (cq *CommandQueue) Finish() error {\n\treturn clw.Finish(cq.id)\n}\n\nfunc (cq *CommandQueue) Retain() error {\n\treturn clw.RetainCommandQueue(cq.id)\n}\n\nfunc (cq *CommandQueue) Release() error {\n\treturn clw.ReleaseCommandQueue(cq.id)\n}\n\nfunc (cq *CommandQueue) EnqueueMarker(e *Event) error {\n\n\tif e != nil {\n\t\te.Context = cq.Context\n\t\te.CommandType = CommandMarker\n\t\te.CommandQueue = cq\n\t}\n\n\treturn clw.EnqueueMarker(cq.id, &e.id)\n}\n\nfunc (cq *CommandQueue) EnqueueWaitForEvents(waitList []*Event) error {\n\treturn clw.EnqueueWaitForEvents(cq.id, cq.toEvents(waitList))\n}\n\nfunc (cq *CommandQueue) EnqueueBarrier() error {\n\treturn clw.EnqueueBarrier(cq.id)\n}\n\nfunc (cq *CommandQueue) toEvents(in []*Event) []clw.Event {\n\n\tif in == nil {\n\t\treturn nil\n\t}\n\n\tif len(cq.eventsScratch) < len(in) {\n\t\tcq.eventsScratch = make([]clw.Event, len(in))\n\t}\n\n\tfor i := range in {\n\t\tcq.eventsScratch[i] = in[i].id\n\t}\n\n\treturn cq.eventsScratch[:len(in)]\n}\n<commit_msg>Started adding command queue documentation.<commit_after>package cl11\n\nimport (\n\t\"strings\"\n\n\tclw \"github.com\/rdwilliamson\/clw11\"\n)\n\n\/\/ The OpenCL functions that are submitted to a command-queue are enqueued in\n\/\/ the order the calls are made but can be configured to execute in-order or\n\/\/ out-of-order. In addition, a wait for events or a barrier command can be\n\/\/ enqueued to the command-queue. The wait for events command ensures that\n\/\/ previously enqueued commands identified by the list of events to wait for\n\/\/ have finished before the next batch of commands is executed. The barrier\n\/\/ command ensures that all previously enqueued commands in a command-queue have\n\/\/ finished execution before the next batch of commands is executed.\ntype CommandQueue struct {\n\tid clw.CommandQueue\n\n\t\/\/ The context the command queue was created on.\n\tContext *Context\n\n\t\/\/ The device the command queue was created for.\n\tDevice *Device\n\n\t\/\/ Bit-field list of properties for the command queue.\n\tProperties CommandQueueProperties\n\n\t\/\/ Scratch space to avoid allocating memory when converting a wait list.\n\teventsScratch []clw.Event\n}\n\ntype CommandQueueProperties int\n\n\/\/ Bitfield.\nconst (\n\tQueueOutOfOrderExecution = CommandQueueProperties(clw.QueueOutOfOrderExecModeEnable)\n\tQueueProfilingEnable     = CommandQueueProperties(clw.QueueProfilingEnable)\n)\n\nfunc (cqp CommandQueueProperties) String() string {\n\tvar propertiesStrings []string\n\tif cqp&QueueOutOfOrderExecution != 0 {\n\t\tpropertiesStrings = append(propertiesStrings, \"out of order execution\")\n\t}\n\tif cqp&QueueProfilingEnable != 0 {\n\t\tpropertiesStrings = append(propertiesStrings, \"profiling\")\n\t}\n\treturn \"{\" + strings.Join(propertiesStrings, \", \") + \"}\"\n}\n\nfunc (c *Context) CreateCommandQueue(d *Device, cqp CommandQueueProperties) (*CommandQueue, error) {\n\n\tcommandQueue, err := clw.CreateCommandQueue(c.id, d.id, clw.CommandQueueProperties(cqp))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &CommandQueue{id: commandQueue, Context: c, Device: d, Properties: cqp}, nil\n}\n\nfunc (cq *CommandQueue) Flush() error {\n\treturn clw.Flush(cq.id)\n}\n\nfunc (cq *CommandQueue) Finish() error {\n\treturn clw.Finish(cq.id)\n}\n\nfunc (cq *CommandQueue) Retain() error {\n\treturn clw.RetainCommandQueue(cq.id)\n}\n\nfunc (cq *CommandQueue) Release() error {\n\treturn clw.ReleaseCommandQueue(cq.id)\n}\n\nfunc (cq *CommandQueue) EnqueueMarker(e *Event) error {\n\n\tif e != nil {\n\t\te.Context = cq.Context\n\t\te.CommandType = CommandMarker\n\t\te.CommandQueue = cq\n\t}\n\n\treturn clw.EnqueueMarker(cq.id, &e.id)\n}\n\nfunc (cq *CommandQueue) EnqueueWaitForEvents(waitList []*Event) error {\n\treturn clw.EnqueueWaitForEvents(cq.id, cq.toEvents(waitList))\n}\n\nfunc (cq *CommandQueue) EnqueueBarrier() error {\n\treturn clw.EnqueueBarrier(cq.id)\n}\n\nfunc (cq *CommandQueue) toEvents(in []*Event) []clw.Event {\n\n\tif in == nil {\n\t\treturn nil\n\t}\n\n\tif len(cq.eventsScratch) < len(in) {\n\t\tcq.eventsScratch = make([]clw.Event, len(in))\n\t}\n\n\tfor i := range in {\n\t\tcq.eventsScratch[i] = in[i].id\n\t}\n\n\treturn cq.eventsScratch[:len(in)]\n}\n<|endoftext|>"}
{"text":"<commit_before>package commands\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\n\tcli \"github.com\/urfave\/cli\"\n\n\t\"github.com\/ipfs\/iptb\/testbed\"\n\t\"github.com\/ipfs\/iptb\/testbed\/interfaces\"\n)\n\nvar RunCmd = cli.Command{\n\tCategory:  \"CORE\",\n\tName:      \"run\",\n\tUsage:     \"run command on specified nodes (or all)\",\n\tArgsUsage: \"[nodes] -- <command...>\",\n\tFlags: []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName:   \"terminator\",\n\t\t\tHidden: true,\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:   \"stdin\",\n\t\t\tHidden: true,\n\t\t},\n\t},\n\tBefore: func(c *cli.Context) error {\n\t\tif c.NArg() == 0 {\n\t\t\treturn c.Set(\"stdin\", \"true\")\n\t\t}\n\t\tif present := isTerminatorPresent(c); present {\n\t\t\treturn c.Set(\"terminator\", \"true\")\n\t\t}\n\t\treturn nil\n\t},\n\tAction: func(c *cli.Context) error {\n\t\tflagRoot := c.GlobalString(\"IPTB_ROOT\")\n\t\tflagTestbed := c.GlobalString(\"testbed\")\n\n\t\ttb := testbed.NewTestbed(path.Join(flagRoot, \"testbeds\", flagTestbed))\n\t\tnodes, err := tb.Nodes()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar args [][]string\n\t\tvar terminatorPresent bool\n\t\tif c.IsSet(\"stdin\") {\n\t\t\tterminatorPresent = false\n\t\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\t\tfor scanner.Scan() {\n\t\t\t\ttokens := strings.Fields(scanner.Text())\n\t\t\t\targs = append(args, tokens)\n\t\t\t}\n\t\t} else {\n\t\t\tterminatorPresent = c.IsSet(\"terminator\")\n\t\t\tcArgsStr := make([]string, c.NArg())\n\t\t\tfor i, arg := range c.Args() {\n\t\t\t\tcArgsStr[i] = arg\n\t\t\t}\n\t\t\targs = append(args, cArgsStr)\n\t\t}\n\n\t\tranges := make([][]int, len(args))\n\t\trunCmds := make([]outputFunc, len(args))\n\t\tfor i, cmd := range args {\n\t\t\tnodeRange, tokens := parseCommand(cmd, terminatorPresent)\n\t\t\tif nodeRange == \"\" {\n\t\t\t\tnodeRange = fmt.Sprintf(\"[0-%d]\", len(nodes)-1)\n\t\t\t}\n\t\t\tlist, err := parseRange(nodeRange)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not parse node range %s\", nodeRange)\n\t\t\t}\n\t\t\tranges[i] = list\n\n\t\t\trunCmd := func(node testbedi.Core) (testbedi.Output, error) {\n\t\t\t\treturn node.RunCmd(context.Background(), nil, tokens...)\n\t\t\t}\n\t\t\trunCmds[i] = runCmd\n\t\t}\n\n\t\tresults, err := mapListWithOutput(ranges, nodes, runCmds)\n\t\treturn buildReport(results)\n\t},\n}\n<commit_msg>Abstract out `bufio.Reader` from the rest of the logic.<commit_after>package commands\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\n\tcli \"github.com\/urfave\/cli\"\n\n\t\"github.com\/ipfs\/iptb\/testbed\"\n\t\"github.com\/ipfs\/iptb\/testbed\/interfaces\"\n)\n\nvar RunCmd = cli.Command{\n\tCategory:  \"CORE\",\n\tName:      \"run\",\n\tUsage:     \"run command on specified nodes (or all)\",\n\tArgsUsage: \"[nodes] -- <command...>\",\n\tFlags: []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName:   \"terminator\",\n\t\t\tHidden: true,\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:   \"stdin\",\n\t\t\tHidden: true,\n\t\t},\n\t},\n\tBefore: func(c *cli.Context) error {\n\t\tif c.NArg() == 0 {\n\t\t\treturn c.Set(\"stdin\", \"true\")\n\t\t}\n\t\tif present := isTerminatorPresent(c); present {\n\t\t\treturn c.Set(\"terminator\", \"true\")\n\t\t}\n\t\treturn nil\n\t},\n\tAction: func(c *cli.Context) error {\n\t\tflagRoot := c.GlobalString(\"IPTB_ROOT\")\n\t\tflagTestbed := c.GlobalString(\"testbed\")\n\n\t\ttb := testbed.NewTestbed(path.Join(flagRoot, \"testbeds\", flagTestbed))\n\t\tnodes, err := tb.Nodes()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar reader io.Reader\n\t\tif c.IsSet(\"stdin\") {\n\t\t\treader = bufio.NewReader(os.Stdin)\n\t\t} else {\n\t\t\tvar builder strings.Builder\n\t\t\tif c.IsSet(\"terminator\") {\n\t\t\t\tbuilder.WriteString(\"-- \")\n\t\t\t}\n\t\t\tfor i, arg := range c.Args() {\n\t\t\t\tbuilder.WriteString(arg)\n\t\t\t\tif i != c.NArg()-1 {\n\t\t\t\t\tbuilder.WriteString(\" \")\n\t\t\t\t}\n\t\t\t}\n\t\t\treader = strings.NewReader(builder.String())\n\t\t}\n\n\t\tvar args [][]string\n\t\tscanner := bufio.NewScanner(reader)\n\t\tfor scanner.Scan() {\n\t\t\ttokens := strings.Fields(scanner.Text())\n\t\t\targs = append(args, tokens)\n\t\t}\n\n\t\tranges := make([][]int, len(args))\n\t\trunCmds := make([]outputFunc, len(args))\n\t\tfor i, cmd := range args {\n\t\t\tnodeRange, tokens := parseCommand(cmd, false)\n\t\t\tif nodeRange == \"\" {\n\t\t\t\tnodeRange = fmt.Sprintf(\"[0-%d]\", len(nodes)-1)\n\t\t\t}\n\t\t\tlist, err := parseRange(nodeRange)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not parse node range %s\", nodeRange)\n\t\t\t}\n\t\t\tranges[i] = list\n\n\t\t\trunCmd := func(node testbedi.Core) (testbedi.Output, error) {\n\t\t\t\treturn node.RunCmd(context.Background(), nil, tokens...)\n\t\t\t}\n\t\t\trunCmds[i] = runCmd\n\t\t}\n\n\t\tresults, err := mapListWithOutput(ranges, nodes, runCmds)\n\t\treturn buildReport(results)\n\t},\n}\n<|endoftext|>"}
{"text":"<commit_before>package livesplit\n\nimport (\n\t\"encoding\/xml\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/glacials\/tugnut\/run\"\n)\n\n\/\/ parser implements parser.Parser\ntype parser struct {\n\tf io.Reader\n\tr RunTag\n}\n\nfunc NewParser(r io.Reader) *parser {\n\tp := parser{\n\t\tf: r,\n\t}\n\n\treturn &p\n}\n\nfunc (p *parser) Parse() error {\n\tb := make([]byte, 1024*1024)\n\tbytesRead, err := p.f.Read(b)\n\tif err != nil {\n\t\tpanic(\"Can't read\")\n\t}\n\n\tlog.Printf(\"LiveSplit parser read %d bytes\", bytesRead)\n\n\terr = xml.Unmarshal(b[:bytesRead], &p.r)\n\tif err != nil {\n\t\treturn errors.New(fmt.Sprintf(\"can't parse LiveSplit file: %s\", err))\n\t}\n\treturn nil\n}\n\nfunc (p *parser) Game() string {\n\treturn p.r.Game\n}\n\nfunc (p *parser) Category() string {\n\treturn p.r.Category\n}\n\nfunc (p *parser) Attempts() uint {\n\treturn p.r.Attempts\n}\n\nfunc (p *parser) Segments() ([]run.Segment, error) {\n\tsegments := make([]run.Segment, len(p.r.Segments.Segments))\n\n\tfor i, s := range p.r.Segments.Segments {\n\n\t\t\/\/ The current segment's start time is equal to the previous segment's end time\n\t\tvar startTime run.Duration\n\t\tif i == 0 {\n\t\t\tstartTime = run.Duration{\n\t\t\t\tRealTime: time.Duration(0),\n\t\t\t\tGameTime: time.Duration(0),\n\t\t\t}\n\t\t} else {\n\t\t\tstartTime = segments[i-1].EndTime\n\t\t}\n\n\t\trealEndTime, err := parseTime(\n\t\t\ts.SplitTimes.SplitTimes[0].RealTime,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn []run.Segment{}, fmt.Errorf(\"can't parse segment real time: %s\", err)\n\t\t}\n\t\tgameEndTime, err := parseTime(\n\t\t\ts.SplitTimes.SplitTimes[0].GameTime,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn []run.Segment{}, fmt.Errorf(\"can't parse segment game time: %s\", err)\n\t\t}\n\n\t\tsegments[i] = run.Segment{\n\t\t\tName:      s.Name,\n\t\t\tStartTime: startTime,\n\t\t\tEndTime: run.Duration{\n\t\t\t\tRealTime: realEndTime,\n\t\t\t\tGameTime: gameEndTime,\n\t\t\t},\n\t\t}\n\t}\n\treturn segments, nil\n}\n<commit_msg>Include segment durations<commit_after>package livesplit\n\nimport (\n\t\"encoding\/xml\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/glacials\/tugnut\/run\"\n)\n\n\/\/ parser implements parser.Parser\ntype parser struct {\n\tf io.Reader\n\tr RunTag\n}\n\nfunc NewParser(r io.Reader) *parser {\n\tp := parser{\n\t\tf: r,\n\t}\n\n\treturn &p\n}\n\nfunc (p *parser) Parse() error {\n\tb := make([]byte, 1024*1024)\n\tbytesRead, err := p.f.Read(b)\n\tif err != nil {\n\t\tpanic(\"Can't read\")\n\t}\n\n\tlog.Printf(\"LiveSplit parser read %d bytes\", bytesRead)\n\n\terr = xml.Unmarshal(b[:bytesRead], &p.r)\n\tif err != nil {\n\t\treturn errors.New(fmt.Sprintf(\"can't parse LiveSplit file: %s\", err))\n\t}\n\treturn nil\n}\n\nfunc (p *parser) Game() string {\n\treturn p.r.Game\n}\n\nfunc (p *parser) Category() string {\n\treturn p.r.Category\n}\n\nfunc (p *parser) Attempts() uint {\n\treturn p.r.Attempts\n}\n\nfunc (p *parser) Segments() ([]run.Segment, error) {\n\tsegments := make([]run.Segment, len(p.r.Segments.Segments))\n\n\tfor i, s := range p.r.Segments.Segments {\n\n\t\t\/\/ The current segment's start time is equal to the previous segment's end time\n\t\tvar startTime run.Duration\n\t\tif i == 0 {\n\t\t\tstartTime = run.Duration{\n\t\t\t\tRealTime: time.Duration(0),\n\t\t\t\tGameTime: time.Duration(0),\n\t\t\t}\n\t\t} else {\n\t\t\tstartTime = segments[i-1].EndTime\n\t\t}\n\n\t\trealEndTime, err := parseTime(\n\t\t\ts.SplitTimes.SplitTimes[0].RealTime,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn []run.Segment{}, fmt.Errorf(\"can't parse segment real time: %s\", err)\n\t\t}\n\t\tgameEndTime, err := parseTime(\n\t\t\ts.SplitTimes.SplitTimes[0].GameTime,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn []run.Segment{}, fmt.Errorf(\"can't parse segment game time: %s\", err)\n\t\t}\n\n\t\tendTime := run.Duration{\n\t\t\tRealTime: realEndTime,\n\t\t\tGameTime: gameEndTime,\n\t\t}\n\n\t\tsegments[i] = run.Segment{\n\t\t\tName:      s.Name,\n\t\t\tStartTime: startTime,\n\t\t\tEndTime:   endTime,\n\t\t}\n\t\tsegments[i].Duration = run.Duration{\n\t\t\tRealTime: endTime.RealTime - startTime.RealTime,\n\t\t\tGameTime: endTime.GameTime - startTime.GameTime,\n\t\t}\n\t}\n\treturn segments, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package authenticator\n\nimport (\n\t\"net\/http\"\n\t\"testing\"\n)\n\nfunc TestAlwaysAuthenticated(t *testing.T) {\n\n\tvar request, _ = http.NewRequest(\"GET\", \"\", nil)\n\tvar sut = NewAlwaysAuthenticated()\n\n\tif sut.UserID(request) != \"\" {\n\t\tt.Fatalf(\"UserID is not '', but '%v'\", sut.UserID(request))\n\t}\n\tif !sut.IsAuthenticated(request) {\n\t\tt.Fatalf(\"UserID '' not returned as authenticated\")\n\t}\n\n}\n\nfunc TestNeverAuthenticated(t *testing.T) {\n\n\tvar request, _ = http.NewRequest(\"GET\", \"\", nil)\n\tvar sut = NewNeverAuthenticated()\n\n\tif sut.UserID(request) != \"\" {\n\t\tt.Fatalf(\"UserID is not '', but '%v'\", sut.UserID(request))\n\t}\n\tif sut.IsAuthenticated(request) {\n\t\tt.Fatalf(\"UserID '' returned as authenticated\")\n\t}\n\n}\n<commit_msg>wip #21: improve tests<commit_after>package authenticator\n\nimport (\n\t\"net\/http\"\n\t\"testing\"\n)\n\nfunc TestAlwaysAuthenticated(t *testing.T) {\n\n\tvar request, _ = http.NewRequest(\"GET\", \"\", nil)\n\tvar sut = NewAlwaysAuthenticated()\n\tsut.SetUserID(nil, request, \"x\") \/\/ should be ignored\n\n\tif sut.UserID(request) != \"\" {\n\t\tt.Fatalf(\"UserID is not '', but '%v'\", sut.UserID(request))\n\t}\n\tif !sut.IsAuthenticated(request) {\n\t\tt.Fatalf(\"UserID '' not returned as authenticated\")\n\t}\n\n}\n\nfunc TestNeverAuthenticated(t *testing.T) {\n\n\tvar request, _ = http.NewRequest(\"GET\", \"\", nil)\n\tvar sut = NewNeverAuthenticated()\n\tsut.SetUserID(nil, request, \"x\") \/\/ should be ignored\n\n\tif sut.UserID(request) != \"\" {\n\t\tt.Fatalf(\"UserID is not '', but '%v'\", sut.UserID(request))\n\t}\n\tif sut.IsAuthenticated(request) {\n\t\tt.Fatalf(\"UserID '' returned as authenticated\")\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package siesta\n\nimport \"time\"\n\ntype RecordAccumulatorConfig struct {\n\tbatchSize         int\n\ttotalMemorySize   int\n\tcompressionType   string\n\tlinger            time.Duration\n\tretryBackoff      time.Duration\n\tblockOnBufferFull bool\n\tmetrics           map[string]Metric\n\ttime              time.Time\n\tmetricTags        map[string]string\n\tnetworkClient     *NetworkClient\n}\n\ntype RecordAccumulator struct {\n\tconfig        *RecordAccumulatorConfig\n\tnetworkClient *NetworkClient\n\tbatchSize     int\n\tbatches       map[string]map[int32][]*ProducerRecord\n\n\taddChan      chan *ProducerRecord\n\tflushed      map[string]map[int32]chan bool\n\tclosing      chan bool\n\tclosed       chan bool\n\tmetadataChan chan *RecordMetadata\n\trecords      map[string]map[int32]chan *ProducerRecord\n}\n\nfunc NewRecordAccumulator(config *RecordAccumulatorConfig, metadataChan chan *RecordMetadata) *RecordAccumulator {\n\taccumulator := &RecordAccumulator{}\n\taccumulator.config = config\n\taccumulator.batchSize = config.batchSize\n\taccumulator.addChan = make(chan *ProducerRecord, 100) \/\/TODO config\n\taccumulator.batches = make(map[string]map[int32][]*ProducerRecord)\n\taccumulator.networkClient = config.networkClient\n\taccumulator.closing = make(chan bool)\n\taccumulator.closed = make(chan bool)\n\taccumulator.metadataChan = metadataChan\n\taccumulator.records = make(map[string]map[int32]chan *ProducerRecord)\n\n\tgo accumulator.sender()\n\n\treturn accumulator\n}\n\nfunc (ra *RecordAccumulator) sender() {\n\tfor {\n\t\tselect {\n\t\tcase <-ra.closing:\n\t\t\tra.cleanup()\n\t\t\treturn\n\t\tdefault:\n\t\t\t{\n\t\t\t\tselect {\n\t\t\t\tcase <-ra.closing:\n\t\t\t\t\tra.cleanup()\n\t\t\t\t\treturn\n\t\t\t\tcase record := <-ra.addChan:\n\t\t\t\t\tra.addRecord(record)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (ra *RecordAccumulator) cleanup() {\n\tra.flushAll()\n\tclose(ra.addChan)\n\tra.networkClient.close()\n\tra.closed <- true\n}\n\nfunc (ra *RecordAccumulator) addRecord(record *ProducerRecord) {\n\tif ra.batches[record.Topic] == nil {\n\t\tra.batches[record.Topic] = make(map[int32][]*ProducerRecord)\n\t}\n\tif ra.batches[record.Topic][record.partition] == nil {\n\t\tra.createBatch(record.Topic, record.partition)\n\t}\n\tra.records[record.Topic][record.partition] <- record\n}\n\nfunc (ra *RecordAccumulator) createBatch(topic string, partition int32) {\n\tra.batches[topic][partition] = make([]*ProducerRecord, 0, ra.batchSize)\n\tra.records[topic] = make(map[int32]chan *ProducerRecord)\n\tra.records[topic][partition] = make(chan *ProducerRecord, ra.batchSize)\n\tgo ra.watcher(topic, partition)\n}\n\nfunc (ra *RecordAccumulator) watcher(topic string, partition int32) {\n\ttimeout := time.After(ra.config.linger)\n\tfor {\n\t\tif len(ra.batches[topic][partition]) >= ra.batchSize {\n\t\t\tra.flush(topic, partition, ra.batches[topic][partition])\n\t\t\tgo ra.watcher(topic, partition)\n\t\t\treturn\n\t\t}\n\t\tselect {\n\t\tcase record := <-ra.records[topic][partition]:\n\t\t\tif len(ra.batches[record.Topic][record.partition]) == 0 {\n\t\t\t\tra.batches[topic][partition] = make([]*ProducerRecord, 0, ra.batchSize)\n\t\t\t}\n\t\t\tra.batches[record.Topic][record.partition] = append(ra.batches[record.Topic][record.partition], record)\n\t\tcase <-timeout:\n\t\t\tra.flush(topic, partition, ra.batches[topic][partition])\n\t\t\tgo ra.watcher(topic, partition)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (ra *RecordAccumulator) flush(topic string, partition int32, batch []*ProducerRecord) {\n\tif len(batch) > 0 {\n\t\tra.networkClient.send(topic, partition, batch)\n\t\tra.batches[topic][partition] = make([]*ProducerRecord, 0, ra.batchSize)\n\t}\n}\n\nfunc (ra *RecordAccumulator) flushAll() {\n\tfor topic, partitionBatches := range ra.batches {\n\t\tfor partition, _ := range partitionBatches {\n\t\t\tra.flush(topic, partition, ra.batches[topic][partition])\n\t\t}\n\t}\n}\n\nfunc (ra *RecordAccumulator) close() chan bool {\n\tra.closing <- true\n\treturn ra.closed\n}\n<commit_msg>Cleanup.<commit_after>package siesta\n\nimport \"time\"\n\ntype RecordAccumulatorConfig struct {\n\tbatchSize         int\n\ttotalMemorySize   int\n\tcompressionType   string\n\tlinger            time.Duration\n\tretryBackoff      time.Duration\n\tblockOnBufferFull bool\n\tmetrics           map[string]Metric\n\ttime              time.Time\n\tmetricTags        map[string]string\n\tnetworkClient     *NetworkClient\n}\n\ntype RecordAccumulator struct {\n\tconfig        *RecordAccumulatorConfig\n\tnetworkClient *NetworkClient\n\tbatchSize     int\n\tbatches       map[string]map[int32][]*ProducerRecord\n\n\taddChan      chan *ProducerRecord\n\tflushed      map[string]map[int32]chan bool\n\tclosing      chan bool\n\tclosed       chan bool\n\tmetadataChan chan *RecordMetadata\n\trecords      map[string]map[int32]chan *ProducerRecord\n}\n\nfunc NewRecordAccumulator(config *RecordAccumulatorConfig, metadataChan chan *RecordMetadata) *RecordAccumulator {\n\taccumulator := &RecordAccumulator{}\n\taccumulator.config = config\n\taccumulator.batchSize = config.batchSize\n\taccumulator.addChan = make(chan *ProducerRecord, 100) \/\/TODO config\n\taccumulator.batches = make(map[string]map[int32][]*ProducerRecord)\n\taccumulator.networkClient = config.networkClient\n\taccumulator.closing = make(chan bool)\n\taccumulator.closed = make(chan bool)\n\taccumulator.metadataChan = metadataChan\n\taccumulator.records = make(map[string]map[int32]chan *ProducerRecord)\n\n\tgo accumulator.sender()\n\n\treturn accumulator\n}\n\nfunc (ra *RecordAccumulator) sender() {\n\tfor {\n\t\tselect {\n\t\tcase <-ra.closing:\n\t\t\tra.cleanup()\n\t\t\treturn\n\t\tdefault:\n\t\t\t{\n\t\t\t\tselect {\n\t\t\t\tcase <-ra.closing:\n\t\t\t\t\tra.cleanup()\n\t\t\t\t\treturn\n\t\t\t\tcase record := <-ra.addChan:\n\t\t\t\t\tra.addRecord(record)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (ra *RecordAccumulator) cleanup() {\n\tra.flushAll()\n\tclose(ra.addChan)\n\tra.networkClient.close()\n\tra.closed <- true\n}\n\nfunc (ra *RecordAccumulator) addRecord(record *ProducerRecord) {\n\tif ra.batches[record.Topic] == nil {\n\t\tra.batches[record.Topic] = make(map[int32][]*ProducerRecord)\n\t}\n\tif ra.batches[record.Topic][record.partition] == nil {\n\t\tra.createBatch(record.Topic, record.partition)\n\t}\n\tra.records[record.Topic][record.partition] <- record\n}\n\nfunc (ra *RecordAccumulator) createBatch(topic string, partition int32) {\n\tra.batches[topic][partition] = make([]*ProducerRecord, 0, ra.batchSize)\n\tra.records[topic] = make(map[int32]chan *ProducerRecord)\n\tra.records[topic][partition] = make(chan *ProducerRecord, ra.batchSize)\n\tgo ra.watcher(topic, partition)\n}\n\nfunc (ra *RecordAccumulator) watcher(topic string, partition int32) {\n\ttimeout := time.After(ra.config.linger)\n\tfor {\n\t\tif len(ra.batches[topic][partition]) >= ra.batchSize {\n\t\t\tra.flush(topic, partition, ra.batches[topic][partition])\n\t\t\tgo ra.watcher(topic, partition)\n\t\t\treturn\n\t\t}\n\t\tselect {\n\t\tcase record := <-ra.records[topic][partition]:\n\t\t\tra.batches[record.Topic][record.partition] = append(ra.batches[record.Topic][record.partition], record)\n\t\tcase <-timeout:\n\t\t\tra.flush(topic, partition, ra.batches[topic][partition])\n\t\t\tgo ra.watcher(topic, partition)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (ra *RecordAccumulator) flush(topic string, partition int32, batch []*ProducerRecord) {\n\tif len(batch) > 0 {\n\t\tra.networkClient.send(topic, partition, batch)\n\t\tra.batches[topic][partition] = make([]*ProducerRecord, 0, ra.batchSize)\n\t}\n}\n\nfunc (ra *RecordAccumulator) flushAll() {\n\tfor topic, partitionBatches := range ra.batches {\n\t\tfor partition, _ := range partitionBatches {\n\t\t\tra.flush(topic, partition, ra.batches[topic][partition])\n\t\t}\n\t}\n}\n\nfunc (ra *RecordAccumulator) close() chan bool {\n\tra.closing <- true\n\treturn ra.closed\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 The goyy Authors.  All rights reserved.\r\n\/\/ Use of this source code is governed by a MIT-style\r\n\/\/ license that can be found in the LICENSE file.\r\n\r\npackage main\r\n\r\nimport (\r\n\t\"bytes\"\r\n\t\"io\/ioutil\"\r\n\t\"strconv\"\r\n\r\n\t_ \"github.com\/go-sql-driver\/mysql\"\r\n\t\"gopkg.in\/goyy\/goyy.v0\/comm\/log\"\r\n\t\"gopkg.in\/goyy\/goyy.v0\/data\/xsql\"\r\n\t\"gopkg.in\/goyy\/goyy.v0\/util\/files\"\r\n\t\"gopkg.in\/goyy\/goyy.v0\/util\/strings\"\r\n\t\"gopkg.in\/goyy\/goyy.v0\/util\/times\"\r\n\t\"gopkg.in\/goyy\/goyy.v0\/util\/uuids\"\r\n)\r\n\r\nfunc genMenu() {\r\n\txsql.SetPriority(log.Perror)\r\n\t\/\/ generate the header.html\r\n\tfor _, p := range conf.projects {\r\n\t\tclidir := \"..\/\" + strings.AfterLast(p.Admpath(), \"\/\")\r\n\t\tdir := clidir + \"\/templates\/layout\/include\/\"\r\n\t\tdstfile := dir + \"header.html\"\r\n\t\tif !files.IsExist(dstfile) {\r\n\t\t\tfiles.MkdirAll(dir, 0755)\r\n\t\t}\r\n\t\tdata := map[string]interface{}{\r\n\t\t\t\"Project\": p,\r\n\t\t\t\"Modules\": conf.modules,\r\n\t\t\t\"Tables\":  conf.tables,\r\n\t\t}\r\n\t\tbuf := bytes.Buffer{}\r\n\t\ttmpl := newTmpl(tmplMenu)\r\n\t\ttmpl.Execute(&buf, data)\r\n\t\tioutil.WriteFile(dstfile, buf.Bytes(), 0755)\r\n\t}\r\n\t\/\/ insert into sys_menu\r\n\tfor _, p := range conf.projects {\r\n\t\tinsertRootMenu(p.database.driverName, p.ID())\r\n\t\tfor mi, m := range conf.modules {\r\n\t\t\tif p.ID() == m.project.ID() && m.Menu() == \"true\" {\r\n\t\t\t\troot := &menu{\r\n\t\t\t\t\tid:      \"root\",\r\n\t\t\t\t\tcode:    \"00\",\r\n\t\t\t\t\tname:    i18N.Message(\"tmpl.menu.data.root\"),\r\n\t\t\t\t\tordinal: \"00\",\r\n\t\t\t\t}\r\n\t\t\t\tpo := strings.PadLeft(strconv.Itoa(mi+1), 2, \"0\")\r\n\t\t\t\tpp := addMenu(p.database.driverName, p.ID(), m.ID(), \"\", m.Name(), po, \"10\", root) \/\/ module\r\n\t\t\t\tfor ti, t := range conf.tables {\r\n\t\t\t\t\tif m.ID() == t.module.ID() && t.Menu() == \"true\" && t.ID() != \"-\" {\r\n\t\t\t\t\t\tto := strings.PadLeft(strconv.Itoa(ti+1), 2, \"0\")\r\n\t\t\t\t\t\tmp := addMenu(p.database.driverName, p.ID(), m.ID(), t.ID(), t.Name(), to, \"20\", pp) \/\/ table\r\n\t\t\t\t\t\tbuttons := strings.Split(t.Buttons(), \",\")\r\n\t\t\t\t\t\tfor i, button := range buttons {\r\n\t\t\t\t\t\t\tif strings.IsBlank(button) {\r\n\t\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\taddMenu(p.database.driverName, p.ID(), m.ID(), t.ID(), button, strconv.Itoa((i+2)*5), \"30\", mp)\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunc insertRootMenu(driverName, pid string) {\r\n\tdb := getDB(driverName, pid)\r\n\tcsql := \"SELECT count(1) FROM sys_menu WHERE id = ?\"\r\n\r\n\tsql := `INSERT INTO sys_menu\r\n\t(id, href, target, icon, hidden, permission, code, name, fullname, genre, ordinal, parent_id, parent_ids, parent_codes, parent_names, leaf, grade, memo, creates, creater, created, modifier, modified, version, deletion, artifical, history)\r\n\tVALUES\r\n\t('root', null, null, null, 0, null, '00', ?, null, '00', '00', null, null, null, null, 0, 1, null, null, null, ?, null, ?, 0, 0, 0, 0);`\r\n\r\n\tcount, err := db.Query(csql, \"root\").Int()\r\n\tif err != nil {\r\n\t\tlogger.Error(err)\r\n\t\treturn\r\n\t}\r\n\tif count == 0 {\r\n\t\tname := i18N.Message(\"tmpl.menu.data.root\")\r\n\t\tnow := times.NowUnix()\r\n\t\t_, err = db.Exec(sql, name, now, now)\r\n\t\tif err != nil {\r\n\t\t\tlogger.Error(err)\r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunc addMenu(driverName, pid, mid, tid, xname, ordinal, genre string, parent *menu) *menu {\r\n\tdb := getDB(driverName, pid)\r\n\tid := uuids.New()\r\n\tnow := times.NowUnix()\r\n\tm := &menu{\r\n\t\tid:       id,\r\n\t\thidden:   \"0\",\r\n\t\tcode:     parent.ordinal + ordinal,\r\n\t\tname:     xname,\r\n\t\tparentID: parent.id,\r\n\t\tleaf:     \"0\",\r\n\t\tgenre:    genre,\r\n\t\tordinal:  parent.ordinal + ordinal,\r\n\t}\r\n\tif parent.id == \"root\" {\r\n\t\tm.parentIDs = parent.id\r\n\t\tm.parentCodes = parent.code\r\n\t} else {\r\n\t\tm.parentIDs = parent.parentIDs + \",\" + parent.id\r\n\t\tm.parentCodes = parent.parentCodes + \",\" + parent.code\r\n\t}\r\n\tswitch genre {\r\n\tcase \"10\":\r\n\t\tif parent.id == \"root\" {\r\n\t\t\tm.fullname = xname\r\n\t\t\tm.parentNames = parent.name\r\n\t\t} else {\r\n\t\t\tm.fullname = parent.fullname + \" - \" + xname\r\n\t\t\tm.parentNames = parent.parentNames + \",\" + parent.name\r\n\t\t}\r\n\t\tm.grade = \"2\"\r\n\tcase \"20\":\r\n\t\tm.href = \"\/\" + mid + \"\/\" + tid\r\n\t\tm.name = xname + i18N.Message(\"tmpl.menu.manage\")\r\n\t\tif parent.id == \"root\" {\r\n\t\t\tm.fullname = m.name\r\n\t\t\tm.parentNames = parent.name\r\n\t\t} else {\r\n\t\t\tm.fullname = parent.fullname + \" - \" + m.name\r\n\t\t\tm.parentNames = parent.parentNames + \",\" + parent.name\r\n\t\t}\r\n\t\tm.grade = \"3\"\r\n\tcase \"30\":\r\n\t\tvar name string\r\n\t\txconf := util.DecodeXML(xbuttons)\r\n\t\tfor _, v := range xconf.Buttons.Button {\r\n\t\t\tif v.ID == xname {\r\n\t\t\t\tname = v.Name\r\n\t\t\t}\r\n\t\t}\r\n\t\tm.hidden = \"1\"\r\n\t\tm.permission = mid + \":\" + tid + \":\" + xname\r\n\t\tm.name = name\r\n\t\tif parent.id == \"root\" {\r\n\t\t\tm.fullname = m.name\r\n\t\t\tm.parentNames = parent.name\r\n\t\t} else {\r\n\t\t\tm.fullname = parent.fullname + \" - \" + m.name\r\n\t\t\tm.parentNames = parent.parentNames + \",\" + parent.name\r\n\t\t}\r\n\t\tm.leaf = \"1\"\r\n\t\tm.grade = \"4\"\r\n\t}\r\n\r\n\tcsql := \"SELECT count(1) FROM sys_menu WHERE code = ?\"\r\n\r\n\tsql := `INSERT INTO sys_menu\r\n\t(id, href, target, icon, hidden, permission, code, name, fullname, genre, ordinal, parent_id, parent_ids, parent_codes, parent_names, leaf, grade, memo, creates, creater, created, modifier, modified, version, deletion, artifical, history)\r\n\tVALUES\r\n\t(?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, ?, NULL, ?, 0, 0, 0, 0)`\r\n\r\n\tcount, err := db.Query(csql, m.code).Int()\r\n\tif err != nil {\r\n\t\tlogger.Error(err)\r\n\t\treturn m\r\n\t}\r\n\tif count == 0 {\r\n\t\t_, err = db.Exec(sql, m.id, m.href, m.hidden, m.permission, m.code, m.name, m.fullname, m.genre, m.ordinal, m.parentID, m.parentIDs, m.parentCodes, m.parentNames, m.leaf, m.grade, now, now)\r\n\t\tif err != nil {\r\n\t\t\tlogger.Error(err)\r\n\t\t\treturn m\r\n\t\t}\r\n\t}\r\n\treturn m\r\n}\r\n\r\ntype menu struct {\r\n\tid, href, hidden, permission, code, name, fullname, genre, ordinal, parentID, parentIDs, parentCodes, parentNames, leaf, grade string\r\n}\r\n<commit_msg>Add support to new project on xgen<commit_after>\/\/ Copyright 2014 The goyy Authors.  All rights reserved.\r\n\/\/ Use of this source code is governed by a MIT-style\r\n\/\/ license that can be found in the LICENSE file.\r\n\r\npackage main\r\n\r\nimport (\r\n\t\"bytes\"\r\n\t\"io\/ioutil\"\r\n\t\"strconv\"\r\n\r\n\t_ \"github.com\/go-sql-driver\/mysql\"\r\n\t\"gopkg.in\/goyy\/goyy.v0\/comm\/log\"\r\n\t\"gopkg.in\/goyy\/goyy.v0\/data\/xsql\"\r\n\t\"gopkg.in\/goyy\/goyy.v0\/util\/files\"\r\n\t\"gopkg.in\/goyy\/goyy.v0\/util\/strings\"\r\n\t\"gopkg.in\/goyy\/goyy.v0\/util\/times\"\r\n\t\"gopkg.in\/goyy\/goyy.v0\/util\/uuids\"\r\n)\r\n\r\nfunc genMenu() {\r\n\txsql.SetPriority(log.Perror)\r\n\t\/\/ generate the header.html\r\n\tfor _, p := range conf.projects {\r\n\t\tclidir := \"..\/\" + strings.AfterLast(p.Admpath(), \"\/\")\r\n\t\tdir := clidir + \"\/templates\/layout\/include\/\"\r\n\t\tdstfile := dir + \"header.html\"\r\n\t\tif !files.IsExist(dstfile) {\r\n\t\t\tfiles.MkdirAll(dir, 0755)\r\n\t\t}\r\n\t\tdata := map[string]interface{}{\r\n\t\t\t\"Project\": p,\r\n\t\t\t\"Modules\": conf.modules,\r\n\t\t\t\"Tables\":  conf.tables,\r\n\t\t}\r\n\t\tbuf := bytes.Buffer{}\r\n\t\ttmpl := newTmpl(tmplMenu)\r\n\t\ttmpl.Execute(&buf, data)\r\n\t\tioutil.WriteFile(dstfile, buf.Bytes(), 0755)\r\n\t}\r\n\t\/\/ insert into sys_menu\r\n\tfor _, p := range conf.projects {\r\n\t\tinsertRootMenu(p.database.driverName, p.ID())\r\n\t\tfor mi, m := range conf.modules {\r\n\t\t\tif p.ID() == m.project.ID() && m.Menu() == \"true\" {\r\n\t\t\t\troot := &menu{\r\n\t\t\t\t\tid:      \"root\",\r\n\t\t\t\t\tcode:    \"00\",\r\n\t\t\t\t\tname:    i18N.Message(\"tmpl.menu.data.root\"),\r\n\t\t\t\t\tordinal: \"00\",\r\n\t\t\t\t}\r\n\t\t\t\tpo := strings.PadLeft(strconv.Itoa(mi+1), 2, \"0\")\r\n\t\t\t\tpp := addMenu(p.database.driverName, p.ID(), m.ID(), \"\", m.Name(), po, \"10\", root) \/\/ module\r\n\t\t\t\tfor ti, t := range conf.tables {\r\n\t\t\t\t\tif m.ID() == t.module.ID() && t.Menu() == \"true\" && t.ID() != \"-\" {\r\n\t\t\t\t\t\tto := strings.PadLeft(strconv.Itoa(ti+1), 2, \"0\")\r\n\t\t\t\t\t\tmp := addMenu(p.database.driverName, p.ID(), m.ID(), t.ID(), t.Name(), to, \"20\", pp) \/\/ table\r\n\t\t\t\t\t\tbuttons := strings.Split(t.Buttons(), \",\")\r\n\t\t\t\t\t\tfor i, button := range buttons {\r\n\t\t\t\t\t\t\tif strings.IsBlank(button) {\r\n\t\t\t\t\t\t\t\tcontinue\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\taddMenu(p.database.driverName, p.ID(), m.ID(), t.ID(), button, strconv.Itoa((i+2)*5), \"30\", mp)\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunc insertRootMenu(driverName, pid string) {\r\n\tdb := getDB(driverName, pid)\r\n\tcsql := \"SELECT count(1) FROM sys_menu WHERE id = ?\"\r\n\r\n\tsql := `INSERT INTO sys_menu\r\n\t(id, href, target, icon, hidden, permission, code, name, fullname, genre, ordinal, parent_id, parent_ids, parent_codes, parent_names, leaf, grade, memo, creates, creater, created, modifier, modified, version, deletion, artifical, history)\r\n\tVALUES\r\n\t('root', null, null, null, 0, null, '00', ?, null, '00', '00', null, null, null, null, 0, 1, null, null, null, ?, null, ?, 0, 0, 0, 0);`\r\n\r\n\tcount, err := db.Query(csql, \"root\").Int()\r\n\tif err != nil {\r\n\t\tlogger.Error(err)\r\n\t\treturn\r\n\t}\r\n\tif count == 0 {\r\n\t\tname := i18N.Message(\"tmpl.menu.data.root\")\r\n\t\tnow := times.NowUnix()\r\n\t\t_, err = db.Exec(sql, name, now, now)\r\n\t\tif err != nil {\r\n\t\t\tlogger.Error(err)\r\n\t\t\treturn\r\n\t\t}\r\n\t}\r\n}\r\n\r\nfunc addMenu(driverName, pid, mid, tid, xname, ordinal, genre string, parent *menu) *menu {\r\n\tdb := getDB(driverName, pid)\r\n\tid := uuids.New()\r\n\tnow := times.NowUnix()\r\n\tm := &menu{\r\n\t\tid:       id,\r\n\t\thidden:   \"0\",\r\n\t\tcode:     parent.ordinal + ordinal,\r\n\t\tname:     xname,\r\n\t\tparentID: parent.id,\r\n\t\tleaf:     \"0\",\r\n\t\tgenre:    genre,\r\n\t\tordinal:  parent.ordinal + ordinal,\r\n\t}\r\n\tif parent.id == \"root\" {\r\n\t\tm.parentIDs = parent.id\r\n\t\tm.parentCodes = parent.code\r\n\t} else {\r\n\t\tm.parentIDs = parent.parentIDs + \",\" + parent.id\r\n\t\tm.parentCodes = parent.parentCodes + \",\" + parent.code\r\n\t}\r\n\tswitch genre {\r\n\tcase \"10\":\r\n\t\tif parent.id == \"root\" {\r\n\t\t\tm.fullname = xname\r\n\t\t\tm.parentNames = parent.name\r\n\t\t} else {\r\n\t\t\tm.fullname = parent.fullname + \" - \" + xname\r\n\t\t\tm.parentNames = parent.parentNames + \",\" + parent.name\r\n\t\t}\r\n\t\tm.grade = \"2\"\r\n\tcase \"20\":\r\n\t\tm.href = \"\/\" + mid + \"\/\" + tid\r\n\t\tm.name = xname + i18N.Message(\"tmpl.menu.manage\")\r\n\t\tif parent.id == \"root\" {\r\n\t\t\tm.fullname = m.name\r\n\t\t\tm.parentNames = parent.name\r\n\t\t} else {\r\n\t\t\tm.fullname = parent.fullname + \" - \" + m.name\r\n\t\t\tm.parentNames = parent.parentNames + \",\" + parent.name\r\n\t\t}\r\n\t\tm.grade = \"3\"\r\n\tcase \"30\":\r\n\t\tvar name string\r\n\t\txconf := util.DecodeXML(xbuttons)\r\n\t\tfor _, v := range xconf.Buttons.Button {\r\n\t\t\tif v.ID == xname {\r\n\t\t\t\tname = v.Name\r\n\t\t\t}\r\n\t\t}\r\n\t\tm.hidden = \"1\"\r\n\t\tm.permission = mid + \":\" + tid + \":\" + xname\r\n\t\tm.name = name\r\n\t\tif parent.id == \"root\" {\r\n\t\t\tm.fullname = m.name\r\n\t\t\tm.parentNames = parent.name\r\n\t\t} else {\r\n\t\t\tm.fullname = parent.fullname + \" - \" + m.name\r\n\t\t\tm.parentNames = parent.parentNames + \",\" + parent.name\r\n\t\t}\r\n\t\tm.leaf = \"1\"\r\n\t\tm.grade = \"4\"\r\n\t}\r\n\r\n\tcsql := \"SELECT count(1) FROM sys_menu WHERE fullname = ?\"\r\n\r\n\tsql := `INSERT INTO sys_menu\r\n\t(id, href, target, icon, hidden, permission, code, name, fullname, genre, ordinal, parent_id, parent_ids, parent_codes, parent_names, leaf, grade, memo, creates, creater, created, modifier, modified, version, deletion, artifical, history)\r\n\tVALUES\r\n\t(?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, ?, NULL, ?, 0, 0, 0, 0)`\r\n\r\n\tcount, err := db.Query(csql, m.fullname).Int()\r\n\tif err != nil {\r\n\t\tlogger.Error(err)\r\n\t\treturn m\r\n\t}\r\n\tif count == 0 {\r\n\t\t_, err = db.Exec(sql, m.id, m.href, m.hidden, m.permission, m.code, m.name, m.fullname, m.genre, m.ordinal, m.parentID, m.parentIDs, m.parentCodes, m.parentNames, m.leaf, m.grade, now, now)\r\n\t\tif err != nil {\r\n\t\t\tlogger.Error(err)\r\n\t\t\treturn m\r\n\t\t}\r\n\t}\r\n\treturn m\r\n}\r\n\r\ntype menu struct {\r\n\tid, href, hidden, permission, code, name, fullname, genre, ordinal, parentID, parentIDs, parentCodes, parentNames, leaf, grade string\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2014 Steve Francia <spf@spf13.com>.\n\/\/\n\/\/ Use of this source code is governed by an MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage jwalterweatherman\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\n\/\/ Level describes the chosen log level between\n\/\/ debug and critical.\ntype Level int\n\ntype NotePad struct {\n\tHandle io.Writer\n\tLevel  Level\n\tPrefix string\n\tLogger **log.Logger\n}\n\n\/\/ Feedback is special. It writes plainly to the output while\n\/\/ logging with the standard extra information (date, file, etc)\n\/\/ Only Println and Printf are currently provided for this\ntype Feedback struct{}\n\nconst (\n\tLevelTrace Level = iota\n\tLevelDebug\n\tLevelInfo\n\tLevelWarn\n\tLevelError\n\tLevelCritical\n\tLevelFatal\n\tDefaultLogThreshold    = LevelWarn\n\tDefaultStdoutThreshold = LevelError\n)\n\nvar (\n\tTRACE      *log.Logger\n\tDEBUG      *log.Logger\n\tINFO       *log.Logger\n\tWARN       *log.Logger\n\tERROR      *log.Logger\n\tCRITICAL   *log.Logger\n\tFATAL      *log.Logger\n\tLOG        *log.Logger\n\tFEEDBACK   Feedback\n\tLogHandle  io.Writer  = ioutil.Discard\n\tOutHandle  io.Writer  = os.Stdout\n\tBothHandle io.Writer  = io.MultiWriter(LogHandle, OutHandle)\n\tNotePads   []*NotePad = []*NotePad{trace, debug, info, warn, err, critical, fatal}\n\n\ttrace           *NotePad = &NotePad{Level: LevelTrace, Handle: os.Stdout, Logger: &TRACE, Prefix: \"TRACE: \"}\n\tdebug           *NotePad = &NotePad{Level: LevelDebug, Handle: os.Stdout, Logger: &DEBUG, Prefix: \"DEBUG: \"}\n\tinfo            *NotePad = &NotePad{Level: LevelInfo, Handle: os.Stdout, Logger: &INFO, Prefix: \"INFO: \"}\n\twarn            *NotePad = &NotePad{Level: LevelWarn, Handle: os.Stdout, Logger: &WARN, Prefix: \"WARN: \"}\n\terr             *NotePad = &NotePad{Level: LevelError, Handle: os.Stdout, Logger: &ERROR, Prefix: \"ERROR: \"}\n\tcritical        *NotePad = &NotePad{Level: LevelCritical, Handle: os.Stdout, Logger: &CRITICAL, Prefix: \"CRITICAL: \"}\n\tfatal           *NotePad = &NotePad{Level: LevelFatal, Handle: os.Stdout, Logger: &FATAL, Prefix: \"FATAL: \"}\n\tlogThreshold    Level    = DefaultLogThreshold\n\toutputThreshold Level    = DefaultStdoutThreshold\n\n\tDATE     = log.Ldate\n\tTIME     = log.Ltime\n\tSFILE    = log.Lshortfile\n\tLFILE    = log.Llongfile\n\tMSEC     = log.Lmicroseconds\n\tlogFlags = DATE | TIME | SFILE\n)\n\nfunc init() {\n\tSetStdoutThreshold(DefaultStdoutThreshold)\n}\n\n\/\/ initialize will setup the jWalterWeatherman standard approach of providing the user\n\/\/ some feedback and logging a potentially different amount based on independent log and output thresholds.\n\/\/ By default the output has a lower threshold than logged\n\/\/ Don't use if you have manually set the Handles of the different levels as it will overwrite them.\nfunc initialize() {\n\tBothHandle = io.MultiWriter(LogHandle, OutHandle)\n\n\tfor _, n := range NotePads {\n\t\tif n.Level < outputThreshold && n.Level < logThreshold {\n\t\t\tn.Handle = ioutil.Discard\n\t\t} else if n.Level >= outputThreshold && n.Level >= logThreshold {\n\t\t\tn.Handle = BothHandle\n\t\t} else if n.Level >= outputThreshold && n.Level < logThreshold {\n\t\t\tn.Handle = OutHandle\n\t\t} else {\n\t\t\tn.Handle = LogHandle\n\t\t}\n\t}\n\n\tfor _, n := range NotePads {\n\t\t*n.Logger = log.New(n.Handle, n.Prefix, logFlags)\n\t}\n\n\tLOG = log.New(LogHandle,\n\t\t\"LOG:   \",\n\t\tlogFlags)\n}\n\n\/\/ Set the log Flags (Available flag: DATE, TIME, SFILE, LFILE and MSEC)\nfunc SetLogFlag(flags int) {\n\tlogFlags = flags\n}\n\n\/\/ Level returns the current global log threshold.\nfunc LogThreshold() Level {\n\treturn logThreshold\n}\n\n\/\/ Level returns the current global output threshold.\nfunc StdoutThreshold() Level {\n\treturn outputThreshold\n}\n\n\/\/ Ensures that the level provided is within the bounds of available levels\nfunc levelCheck(level Level) Level {\n\tswitch {\n\tcase level <= LevelTrace:\n\t\treturn LevelTrace\n\tcase level >= LevelFatal:\n\t\treturn LevelFatal\n\tdefault:\n\t\treturn level\n\t}\n}\n\n\/\/ Establishes a threshold where anything matching or above will be logged\nfunc SetLogThreshold(level Level) {\n\tlogThreshold = levelCheck(level)\n\tinitialize()\n}\n\n\/\/ Establishes a threshold where anything matching or above will be output\nfunc SetStdoutThreshold(level Level) {\n\toutputThreshold = levelCheck(level)\n\tinitialize()\n}\n\n\/\/ Conveniently Sets the Log Handle to a io.writer created for the file behind the given filepath\n\/\/ Will only append to this file\nfunc SetLogFile(path string) {\n\tfile, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\tCRITICAL.Println(\"Failed to open log file:\", path, err)\n\t\tos.Exit(-1)\n\t}\n\n\tINFO.Println(\"Logging to\", file.Name())\n\n\tLogHandle = file\n\tinitialize()\n}\n\n\/\/ Conveniently Creates a temporary file and sets the Log Handle to a io.writer created for it\nfunc UseTempLogFile(prefix string) {\n\tfile, err := ioutil.TempFile(os.TempDir(), prefix)\n\tif err != nil {\n\t\tCRITICAL.Println(err)\n\t}\n\n\tINFO.Println(\"Logging to\", file.Name())\n\n\tLogHandle = file\n\tinitialize()\n}\n\n\/\/ Disables logging for the entire JWW system\nfunc DiscardLogging() {\n\tLogHandle = ioutil.Discard\n\tinitialize()\n}\n\n\/\/ Feedback is special. It writes plainly to the output while\n\/\/ logging with the standard extra information (date, file, etc)\n\/\/ Only Println and Printf are currently provided for this\nfunc (fb *Feedback) Println(v ...interface{}) {\n\ts := fmt.Sprintln(v...)\n\tfmt.Print(s)\n\tLOG.Output(2, s)\n}\n\n\/\/ Feedback is special. It writes plainly to the output while\n\/\/ logging with the standard extra information (date, file, etc)\n\/\/ Only Println and Printf are currently provided for this\nfunc (fb *Feedback) Printf(format string, v ...interface{}) {\n\ts := fmt.Sprintf(format, v...)\n\tfmt.Print(s)\n\tLOG.Output(2, s)\n}\n<commit_msg>Declare logFlags constants as... const!<commit_after>\/\/ Copyright © 2014 Steve Francia <spf@spf13.com>.\n\/\/\n\/\/ Use of this source code is governed by an MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage jwalterweatherman\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n)\n\n\/\/ Level describes the chosen log level between\n\/\/ debug and critical.\ntype Level int\n\ntype NotePad struct {\n\tHandle io.Writer\n\tLevel  Level\n\tPrefix string\n\tLogger **log.Logger\n}\n\n\/\/ Feedback is special. It writes plainly to the output while\n\/\/ logging with the standard extra information (date, file, etc)\n\/\/ Only Println and Printf are currently provided for this\ntype Feedback struct{}\n\nconst (\n\tLevelTrace Level = iota\n\tLevelDebug\n\tLevelInfo\n\tLevelWarn\n\tLevelError\n\tLevelCritical\n\tLevelFatal\n\tDefaultLogThreshold    = LevelWarn\n\tDefaultStdoutThreshold = LevelError\n)\n\nvar (\n\tTRACE      *log.Logger\n\tDEBUG      *log.Logger\n\tINFO       *log.Logger\n\tWARN       *log.Logger\n\tERROR      *log.Logger\n\tCRITICAL   *log.Logger\n\tFATAL      *log.Logger\n\tLOG        *log.Logger\n\tFEEDBACK   Feedback\n\tLogHandle  io.Writer  = ioutil.Discard\n\tOutHandle  io.Writer  = os.Stdout\n\tBothHandle io.Writer  = io.MultiWriter(LogHandle, OutHandle)\n\tNotePads   []*NotePad = []*NotePad{trace, debug, info, warn, err, critical, fatal}\n\n\ttrace           *NotePad = &NotePad{Level: LevelTrace, Handle: os.Stdout, Logger: &TRACE, Prefix: \"TRACE: \"}\n\tdebug           *NotePad = &NotePad{Level: LevelDebug, Handle: os.Stdout, Logger: &DEBUG, Prefix: \"DEBUG: \"}\n\tinfo            *NotePad = &NotePad{Level: LevelInfo, Handle: os.Stdout, Logger: &INFO, Prefix: \"INFO: \"}\n\twarn            *NotePad = &NotePad{Level: LevelWarn, Handle: os.Stdout, Logger: &WARN, Prefix: \"WARN: \"}\n\terr             *NotePad = &NotePad{Level: LevelError, Handle: os.Stdout, Logger: &ERROR, Prefix: \"ERROR: \"}\n\tcritical        *NotePad = &NotePad{Level: LevelCritical, Handle: os.Stdout, Logger: &CRITICAL, Prefix: \"CRITICAL: \"}\n\tfatal           *NotePad = &NotePad{Level: LevelFatal, Handle: os.Stdout, Logger: &FATAL, Prefix: \"FATAL: \"}\n\tlogThreshold    Level    = DefaultLogThreshold\n\toutputThreshold Level    = DefaultStdoutThreshold\n)\n\nconst (\n\tDATE  = log.Ldate\n\tTIME  = log.Ltime\n\tSFILE = log.Lshortfile\n\tLFILE = log.Llongfile\n\tMSEC  = log.Lmicroseconds\n)\n\nvar logFlags = DATE | TIME | SFILE\n\nfunc init() {\n\tSetStdoutThreshold(DefaultStdoutThreshold)\n}\n\n\/\/ initialize will setup the jWalterWeatherman standard approach of providing the user\n\/\/ some feedback and logging a potentially different amount based on independent log and output thresholds.\n\/\/ By default the output has a lower threshold than logged\n\/\/ Don't use if you have manually set the Handles of the different levels as it will overwrite them.\nfunc initialize() {\n\tBothHandle = io.MultiWriter(LogHandle, OutHandle)\n\n\tfor _, n := range NotePads {\n\t\tif n.Level < outputThreshold && n.Level < logThreshold {\n\t\t\tn.Handle = ioutil.Discard\n\t\t} else if n.Level >= outputThreshold && n.Level >= logThreshold {\n\t\t\tn.Handle = BothHandle\n\t\t} else if n.Level >= outputThreshold && n.Level < logThreshold {\n\t\t\tn.Handle = OutHandle\n\t\t} else {\n\t\t\tn.Handle = LogHandle\n\t\t}\n\t}\n\n\tfor _, n := range NotePads {\n\t\t*n.Logger = log.New(n.Handle, n.Prefix, logFlags)\n\t}\n\n\tLOG = log.New(LogHandle,\n\t\t\"LOG:   \",\n\t\tlogFlags)\n}\n\n\/\/ Set the log Flags (Available flag: DATE, TIME, SFILE, LFILE and MSEC)\nfunc SetLogFlag(flags int) {\n\tlogFlags = flags\n}\n\n\/\/ Level returns the current global log threshold.\nfunc LogThreshold() Level {\n\treturn logThreshold\n}\n\n\/\/ Level returns the current global output threshold.\nfunc StdoutThreshold() Level {\n\treturn outputThreshold\n}\n\n\/\/ Ensures that the level provided is within the bounds of available levels\nfunc levelCheck(level Level) Level {\n\tswitch {\n\tcase level <= LevelTrace:\n\t\treturn LevelTrace\n\tcase level >= LevelFatal:\n\t\treturn LevelFatal\n\tdefault:\n\t\treturn level\n\t}\n}\n\n\/\/ Establishes a threshold where anything matching or above will be logged\nfunc SetLogThreshold(level Level) {\n\tlogThreshold = levelCheck(level)\n\tinitialize()\n}\n\n\/\/ Establishes a threshold where anything matching or above will be output\nfunc SetStdoutThreshold(level Level) {\n\toutputThreshold = levelCheck(level)\n\tinitialize()\n}\n\n\/\/ Conveniently Sets the Log Handle to a io.writer created for the file behind the given filepath\n\/\/ Will only append to this file\nfunc SetLogFile(path string) {\n\tfile, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)\n\tif err != nil {\n\t\tCRITICAL.Println(\"Failed to open log file:\", path, err)\n\t\tos.Exit(-1)\n\t}\n\n\tINFO.Println(\"Logging to\", file.Name())\n\n\tLogHandle = file\n\tinitialize()\n}\n\n\/\/ Conveniently Creates a temporary file and sets the Log Handle to a io.writer created for it\nfunc UseTempLogFile(prefix string) {\n\tfile, err := ioutil.TempFile(os.TempDir(), prefix)\n\tif err != nil {\n\t\tCRITICAL.Println(err)\n\t}\n\n\tINFO.Println(\"Logging to\", file.Name())\n\n\tLogHandle = file\n\tinitialize()\n}\n\n\/\/ Disables logging for the entire JWW system\nfunc DiscardLogging() {\n\tLogHandle = ioutil.Discard\n\tinitialize()\n}\n\n\/\/ Feedback is special. It writes plainly to the output while\n\/\/ logging with the standard extra information (date, file, etc)\n\/\/ Only Println and Printf are currently provided for this\nfunc (fb *Feedback) Println(v ...interface{}) {\n\ts := fmt.Sprintln(v...)\n\tfmt.Print(s)\n\tLOG.Output(2, s)\n}\n\n\/\/ Feedback is special. It writes plainly to the output while\n\/\/ logging with the standard extra information (date, file, etc)\n\/\/ Only Println and Printf are currently provided for this\nfunc (fb *Feedback) Printf(format string, v ...interface{}) {\n\ts := fmt.Sprintf(format, v...)\n\tfmt.Print(s)\n\tLOG.Output(2, s)\n}\n<|endoftext|>"}
{"text":"<commit_before>package response\n\nimport (\n\t\"encoding\/json\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/volatile\/core\"\n)\n\nconst viewsDir = \"views\"\n\nvar views *template.Template\n\nfunc init() {\n\tviews = template.New(\"views\")\n\n\t\/\/ Built-in views funcs\n\tviews.Funcs(template.FuncMap{\n\t\t\"html\":  viewsFuncHTML,\n\t\t\"nl2br\": viewsFuncNL2BR,\n\t})\n\n\tcore.BeforeRun(func() {\n\t\tif _, err := os.Stat(viewsDir); err == nil {\n\t\t\terr = filepath.Walk(viewsDir, func(path string, f os.FileInfo, err error) error {\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif !f.IsDir() {\n\t\t\t\t\tif _, err = views.ParseFiles(path); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t})\n}\n\n\/\/ FuncMap is the type of the map defining the mapping from names to functions.\n\/\/ Each function must have either a single return value, or two return values of which the second has type error.\n\/\/ In that case, if the second (error) argument evaluates to non-nil during execution, execution terminates and Execute returns that error.\n\/\/ FuncMap has the same base type as FuncMap in \"text\/template\", copied here so clients need not import \"text\/template\".\ntype FuncMap map[string]interface{}\n\n\/\/ ViewsFuncs adds a function that will be available to all templates.\nfunc ViewsFuncs(funcMap FuncMap) {\n\tviews.Funcs(template.FuncMap(funcMap))\n}\n\n\/\/ Status responds with the given status code.\nfunc Status(c *core.Context, v int) {\n\thttp.Error(c.ResponseWriter, http.StatusText(v), v)\n}\n\n\/\/ String responds with the given string.\nfunc String(c *core.Context, s string) {\n\tc.ResponseWriter.Write([]byte(s))\n}\n\n\/\/ Bytes responds with the given slice of byte.\nfunc Bytes(c *core.Context, b []byte) {\n\tc.ResponseWriter.Write(b)\n}\n\n\/\/ JSON set the correct header and responds with the marshalled content.\nfunc JSON(c *core.Context, v interface{}) {\n\tc.ResponseWriter.Header().Set(\"Content-Type\", \"application\/json\")\n\n\tvar js []byte\n\tvar err error\n\n\tif core.Production {\n\t\tjs, err = json.Marshal(v)\n\t} else {\n\t\tjs, err = json.MarshalIndent(v, \"\", \"\\t\")\n\t}\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(c.ResponseWriter, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tc.ResponseWriter.Write(js)\n}\n\n\/\/ View pass the data to the template associated to name, and responds with it.\nfunc View(c *core.Context, name string, data map[string]interface{}) {\n\tdata[\"c\"] = c\n\terr := views.ExecuteTemplate(c.ResponseWriter, name, data)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(c.ResponseWriter, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n<commit_msg>Improve readability of helper.go<commit_after>package response\n\nimport (\n\t\"encoding\/json\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/volatile\/core\"\n)\n\nconst viewsDir = \"views\"\n\nvar views *template.Template\n\nfunc init() {\n\tviews = template.New(\"views\")\n\n\t\/\/ Built-in views funcs\n\tviews.Funcs(template.FuncMap{\n\t\t\"html\":  viewsFuncHTML,\n\t\t\"nl2br\": viewsFuncNL2BR,\n\t})\n\n\tcore.BeforeRun(func() {\n\t\tif _, err := os.Stat(viewsDir); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif err := filepath.Walk(viewsDir, walk); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t})\n}\n\n\/\/ walk is the path\/filepath.WalkFunc that is used to walk viewsDir in order to initialize\n\/\/ views. It will try to parse all files it encounters and recurse into subdirectories.\nfunc walk(path string, f os.FileInfo, err error) error {\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif f.IsDir() {\n\t\treturn nil\n\t}\n\n\t_, err = views.ParseFiles(path)\n\n\treturn err\n}\n\n\/\/ FuncMap is the type of the map defining the mapping from names to functions.\n\/\/ Each function must have either a single return value, or two return values of which the second has type error.\n\/\/ In that case, if the second (error) argument evaluates to non-nil during execution, execution terminates and Execute returns that error.\n\/\/ FuncMap has the same base type as FuncMap in \"text\/template\", copied here so clients need not import \"text\/template\".\ntype FuncMap map[string]interface{}\n\n\/\/ ViewsFuncs adds a function that will be available to all templates.\nfunc ViewsFuncs(funcMap FuncMap) {\n\tviews.Funcs(template.FuncMap(funcMap))\n}\n\n\/\/ Status responds with the given status code.\nfunc Status(c *core.Context, v int) {\n\thttp.Error(c.ResponseWriter, http.StatusText(v), v)\n}\n\n\/\/ String responds with the given string.\nfunc String(c *core.Context, s string) {\n\tc.ResponseWriter.Write([]byte(s))\n}\n\n\/\/ Bytes responds with the given slice of byte.\nfunc Bytes(c *core.Context, b []byte) {\n\tc.ResponseWriter.Write(b)\n}\n\n\/\/ JSON set the correct header and responds with the marshalled content.\nfunc JSON(c *core.Context, v interface{}) {\n\tc.ResponseWriter.Header().Set(\"Content-Type\", \"application\/json\")\n\n\tvar js []byte\n\tvar err error\n\n\tif core.Production {\n\t\tjs, err = json.Marshal(v)\n\t} else {\n\t\tjs, err = json.MarshalIndent(v, \"\", \"\\t\")\n\t}\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(c.ResponseWriter, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tc.ResponseWriter.Write(js)\n}\n\n\/\/ View pass the data to the template associated to name, and responds with it.\nfunc View(c *core.Context, name string, data map[string]interface{}) {\n\tdata[\"c\"] = c\n\terr := views.ExecuteTemplate(c.ResponseWriter, name, data)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(c.ResponseWriter, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2022 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage managedwriter\n\n\/\/ [START bigquerystorage_write_pending_complexschema]\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"time\"\n\n\t\"cloud.google.com\/go\/bigquery\/storage\/managedwriter\"\n\t\"cloud.google.com\/go\/bigquery\/storage\/managedwriter\/adapt\"\n\t\"github.com\/GoogleCloudPlatform\/golang-samples\/bigquery\/snippets\/managedwriter\/exampleproto\"\n\tstoragepb \"google.golang.org\/genproto\/googleapis\/cloud\/bigquery\/storage\/v1\"\n\t\"google.golang.org\/protobuf\/proto\"\n)\n\n\/\/ generateExampleMessage generates an example protobuf message using a statically defined and\n\/\/ compiled protocol buffer file, and returns the binary serialized representation.\nfunc generateExampleMessage() ([]byte, error) {\n\n\trandom := rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\t\/\/ Our example data embeds an array of structs, so we'll construct that first.\n\tsList := make([]*exampleproto.SampleStruct, 5)\n\tfor i := 0; i < int(random.Int63n(5)+1); i++ {\n\t\tsList[i] = &exampleproto.SampleStruct{\n\t\t\tSubIntCol: proto.Int64(random.Int63()),\n\t\t}\n\t}\n\n\tm := &exampleproto.SampleData{\n\t\tBoolCol:    proto.Bool(true),\n\t\tBytesCol:   []byte(\"some bytes\"),\n\t\tFloat64Col: proto.Float64(3.14),\n\t\tInt64Col:   proto.Int64(123),\n\t\tStringCol:  proto.String(\"example string value\"),\n\n\t\t\/\/ These types require special encoding\/formatting to transmit.\n\n\t\t\/\/ DATE values are number of days since the Unix epoch.\n\t\tDateCol: proto.Int32(int32(time.Now().UnixMilli() \/ 86400000)),\n\n\t\t\/\/ DATETIME uses the literal format.\n\t\tDatetimeCol: proto.String(\"2022-01-01 12:13:14.000000\"),\n\n\t\t\/\/ GEOGRAPHY uses Well-Known-Text (WKT) format.\n\t\tGeographyCol: proto.String(\"POINT(-122.350220 47.649154)\"),\n\n\t\t\/\/ NUMERIC and BIGNUMERIC can be passed as string, or more efficiently\n\t\t\/\/ using a packed byte representation.\n\t\tNumericCol:    proto.String(\"99999999999999999999999999999.999999999\"),\n\t\tBignumericCol: proto.String(\"578960446186580977117854925043439539266.34992332820282019728792003956564819967\"),\n\n\t\t\/\/ TIME also uses literal format.\n\t\tTimeCol: proto.String(\"12:13:14.000000\"),\n\n\t\t\/\/ TIMESTAMP uses microseconds since Unix epoch.\n\t\tTimestampCol: proto.Int64(time.Now().UnixMicro()),\n\n\t\t\/\/ Int64List is an array of INT64 types.\n\t\tInt64List: []int64{2, 4, 6, 8},\n\n\t\t\/\/ This is a required field, and thus must be present.\n\t\tRowNum: proto.Int64(23),\n\n\t\t\/\/ StructCol is a single nested message.\n\t\tStructCol: &exampleproto.SampleStruct{\n\t\t\tSubIntCol: proto.Int64(random.Int63()),\n\t\t},\n\n\t\t\/\/ StructList is a repeated array of a nested message.\n\t\tStructList: sList,\n\t}\n\n\t\/\/ Now that the protocol message has been populated, serialize it to binary form and return.\n\treturn proto.Marshal(m)\n}\n\n\/\/ appendToPendingStream demonstrates using the managedwriter package to write some example data\n\/\/ to a pending stream, and then committing it to a table.\nfunc appendToPendingStream(w io.Writer, projectID, datasetID, tableID string) error {\n\t\/\/ projectID := \"myproject\"\n\t\/\/ datasetID := \"mydataset\"\n\t\/\/ tableID := \"mytable\"\n\n\tctx := context.Background()\n\tclient, err := managedwriter.NewClient(ctx, projectID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"managedwriter.NewClient: %v\", err)\n\t}\n\n\t\/\/ Create a new pending stream.  We'll use the stream name to construct a writer.\n\tpendingStream, err := client.CreateWriteStream(ctx, &storagepb.CreateWriteStreamRequest{\n\t\tParent: fmt.Sprintf(\"projects\/%s\/datasets\/%s\/tables\/%s\", projectID, datasetID, tableID),\n\t\tWriteStream: &storagepb.WriteStream{\n\t\t\tType: storagepb.WriteStream_PENDING,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"CreateWriteStream: %v\", err)\n\t}\n\n\t\/\/ We need to communicate the descriptor of the protocol buffer message we're using, which\n\t\/\/ is analagous to the \"schema\" for the message.  Both SampleData and SampleStruct are\n\t\/\/ two distinct messages in the compiled proto file, so we'll use adapt.NormalizeDescriptor\n\t\/\/ to unify them into a single self-contained descriptor representation.\n\tm := &exampleproto.SampleData{}\n\tdescriptorProto, err := adapt.NormalizeDescriptor(m.ProtoReflect().Descriptor())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NormalizeDescriptor: %v\", err)\n\t}\n\n\t\/\/ Instantiate a ManagedStream, which manages low level details like connection state and provides\n\t\/\/ additional features like a future-like callback for appends, etc.  NewManagedStream can also create\n\t\/\/ the stream on your behalf, but in this example we're being explicit about stream creation.\n\tmanagedStream, err := client.NewManagedStream(ctx, managedwriter.WithStreamName(pendingStream.GetName()),\n\t\tmanagedwriter.WithSchemaDescriptor(descriptorProto))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewManagedStream: %v\", err)\n\t}\n\n\t\/\/ First, we'll append a single row.\n\trowBytes, err := generateExampleMessage()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"generateExampleMessage: %v\", err)\n\t}\n\n\t\/\/ We'll keep track of the current offset in the stream with curOffset.\n\tvar curOffset int64\n\t\/\/ We can append data asyncronously, so we'll check our appends at the end.\n\tvar results []*managedwriter.AppendResult\n\n\tresult, err := managedStream.AppendRows(ctx, [][]byte{rowBytes}, managedwriter.WithOffset(0))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"AppendRows first call error: %v\", err)\n\t}\n\tresults = append(results, result)\n\n\t\/\/ Advance our current offset.\n\tcurOffset = curOffset + 1\n\n\t\/\/ This time, we'll append three more rows in a single request.\n\tresult, err = managedStream.AppendRows(ctx, [][]byte{rowBytes, rowBytes, rowBytes}, managedwriter.WithOffset(curOffset))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"AppendRows second call error: %v\", err)\n\t}\n\tresults = append(results, result)\n\n\t\/\/ Advance our offset again.\n\tcurOffset = curOffset + 3\n\n\t\/\/ Finally, we'll append two more rows.\n\tresult, err = managedStream.AppendRows(ctx, [][]byte{rowBytes, rowBytes, rowBytes}, managedwriter.WithOffset(curOffset))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"AppendRows third call error: %v\", err)\n\t}\n\tresults = append(results, result)\n\n\t\/\/ Now, we'll check that our batch of three appends all completed successfully.\n\t\/\/ Monitoring the results could also be done out of band via a goroutine.\n\tfor k, v := range results {\n\t\t\/\/ GetResult blocks until we receive a response from the API.\n\t\trecvOffset, err := v.GetResult(ctx)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"append %d returned error: %v\", k, err)\n\t\t}\n\t\tfmt.Fprintf(w, \"Successfully appended data at offset %d.\\n\", recvOffset)\n\t}\n\n\t\/\/ We're now done appending to this stream.  We now mark pending stream finalized, which blocks\n\t\/\/ further appends.\n\trowCount, err := managedStream.Finalize(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error during Finalize: %v\", err)\n\t}\n\n\tfmt.Fprintf(w, \"Stream %s finalized with %d rows.\\n\", managedStream.StreamName(), rowCount)\n\n\t\/\/ To commit the data to the table, we need to run a batch commit.  You can commit several streams\n\t\/\/ atomically as a group, but in this instance we'll only commit the single stream.\n\treq := &storagepb.BatchCommitWriteStreamsRequest{\n\t\tParent:       managedwriter.TableParentFromStreamName(managedStream.StreamName()),\n\t\tWriteStreams: []string{managedStream.StreamName()},\n\t}\n\n\tresp, err := client.BatchCommitWriteStreams(ctx, req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"client.BatchCommit: %v\", err)\n\t}\n\tif len(resp.GetStreamErrors()) > 0 {\n\t\treturn fmt.Errorf(\"stream errors present: %v\", resp.GetStreamErrors())\n\t}\n\n\tfmt.Fprintf(w, \"Table data committed at %s\\n\", resp.GetCommitTime().AsTime().Format(time.RFC3339Nano))\n\n\treturn nil\n}\n\n\/\/ [END bigquerystorage_write_pending_complexschema]\n<commit_msg>docs: improve managedwriter sample (#2406)<commit_after>\/\/ Copyright 2022 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage managedwriter\n\n\/\/ [START bigquerystorage_write_pending_complexschema]\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"time\"\n\n\t\"cloud.google.com\/go\/bigquery\/storage\/managedwriter\"\n\t\"cloud.google.com\/go\/bigquery\/storage\/managedwriter\/adapt\"\n\t\"github.com\/GoogleCloudPlatform\/golang-samples\/bigquery\/snippets\/managedwriter\/exampleproto\"\n\tstoragepb \"google.golang.org\/genproto\/googleapis\/cloud\/bigquery\/storage\/v1\"\n\t\"google.golang.org\/protobuf\/proto\"\n)\n\n\/\/ generateExampleMessages generates a slice of serialized protobuf messages using a statically defined\n\/\/ and compiled protocol buffer file, and returns the binary serialized representation.\nfunc generateExampleMessages(numMessages int) ([][]byte, error) {\n\tmsgs := make([][]byte, numMessages)\n\tfor i := 0; i < numMessages; i++ {\n\n\t\trandom := rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\t\t\/\/ Our example data embeds an array of structs, so we'll construct that first.\n\t\tsList := make([]*exampleproto.SampleStruct, 5)\n\t\tfor i := 0; i < int(random.Int63n(5)+1); i++ {\n\t\t\tsList[i] = &exampleproto.SampleStruct{\n\t\t\t\tSubIntCol: proto.Int64(random.Int63()),\n\t\t\t}\n\t\t}\n\n\t\tm := &exampleproto.SampleData{\n\t\t\tBoolCol:    proto.Bool(true),\n\t\t\tBytesCol:   []byte(\"some bytes\"),\n\t\t\tFloat64Col: proto.Float64(3.14),\n\t\t\tInt64Col:   proto.Int64(123),\n\t\t\tStringCol:  proto.String(\"example string value\"),\n\n\t\t\t\/\/ These types require special encoding\/formatting to transmit.\n\n\t\t\t\/\/ DATE values are number of days since the Unix epoch.\n\n\t\t\tDateCol: proto.Int32(int32(time.Now().UnixNano() \/ 86400000000000)),\n\n\t\t\t\/\/ DATETIME uses the literal format.\n\t\t\tDatetimeCol: proto.String(\"2022-01-01 12:13:14.000000\"),\n\n\t\t\t\/\/ GEOGRAPHY uses Well-Known-Text (WKT) format.\n\t\t\tGeographyCol: proto.String(\"POINT(-122.350220 47.649154)\"),\n\n\t\t\t\/\/ NUMERIC and BIGNUMERIC can be passed as string, or more efficiently\n\t\t\t\/\/ using a packed byte representation.\n\t\t\tNumericCol:    proto.String(\"99999999999999999999999999999.999999999\"),\n\t\t\tBignumericCol: proto.String(\"578960446186580977117854925043439539266.34992332820282019728792003956564819967\"),\n\n\t\t\t\/\/ TIME also uses literal format.\n\t\t\tTimeCol: proto.String(\"12:13:14.000000\"),\n\n\t\t\t\/\/ TIMESTAMP uses microseconds since Unix epoch.\n\t\t\tTimestampCol: proto.Int64(time.Now().UnixNano() \/ 1000),\n\n\t\t\t\/\/ Int64List is an array of INT64 types.\n\t\t\tInt64List: []int64{2, 4, 6, 8},\n\n\t\t\t\/\/ This is a required field, and thus must be present.\n\t\t\tRowNum: proto.Int64(23),\n\n\t\t\t\/\/ StructCol is a single nested message.\n\t\t\tStructCol: &exampleproto.SampleStruct{\n\t\t\t\tSubIntCol: proto.Int64(random.Int63()),\n\t\t\t},\n\n\t\t\t\/\/ StructList is a repeated array of a nested message.\n\t\t\tStructList: sList,\n\t\t}\n\n\t\tb, err := proto.Marshal(m)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error generating message %d: %v\", i, err)\n\t\t}\n\t\tmsgs[i] = b\n\t}\n\treturn msgs, nil\n}\n\n\/\/ appendToPendingStream demonstrates using the managedwriter package to write some example data\n\/\/ to a pending stream, and then committing it to a table.\nfunc appendToPendingStream(w io.Writer, projectID, datasetID, tableID string) error {\n\t\/\/ projectID := \"myproject\"\n\t\/\/ datasetID := \"mydataset\"\n\t\/\/ tableID := \"mytable\"\n\n\tctx := context.Background()\n\tclient, err := managedwriter.NewClient(ctx, projectID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"managedwriter.NewClient: %v\", err)\n\t}\n\n\t\/\/ Create a new pending stream.  We'll use the stream name to construct a writer.\n\tpendingStream, err := client.CreateWriteStream(ctx, &storagepb.CreateWriteStreamRequest{\n\t\tParent: fmt.Sprintf(\"projects\/%s\/datasets\/%s\/tables\/%s\", projectID, datasetID, tableID),\n\t\tWriteStream: &storagepb.WriteStream{\n\t\t\tType: storagepb.WriteStream_PENDING,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"CreateWriteStream: %v\", err)\n\t}\n\n\t\/\/ We need to communicate the descriptor of the protocol buffer message we're using, which\n\t\/\/ is analagous to the \"schema\" for the message.  Both SampleData and SampleStruct are\n\t\/\/ two distinct messages in the compiled proto file, so we'll use adapt.NormalizeDescriptor\n\t\/\/ to unify them into a single self-contained descriptor representation.\n\tm := &exampleproto.SampleData{}\n\tdescriptorProto, err := adapt.NormalizeDescriptor(m.ProtoReflect().Descriptor())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NormalizeDescriptor: %v\", err)\n\t}\n\n\t\/\/ Instantiate a ManagedStream, which manages low level details like connection state and provides\n\t\/\/ additional features like a future-like callback for appends, etc.  NewManagedStream can also create\n\t\/\/ the stream on your behalf, but in this example we're being explicit about stream creation.\n\tmanagedStream, err := client.NewManagedStream(ctx, managedwriter.WithStreamName(pendingStream.GetName()),\n\t\tmanagedwriter.WithSchemaDescriptor(descriptorProto))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewManagedStream: %v\", err)\n\t}\n\n\t\/\/ First, we'll append a single row.\n\trows, err := generateExampleMessages(1)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"generateExampleMessages: %v\", err)\n\t}\n\n\t\/\/ We'll keep track of the current offset in the stream with curOffset.\n\tvar curOffset int64\n\t\/\/ We can append data asyncronously, so we'll check our appends at the end.\n\tvar results []*managedwriter.AppendResult\n\n\tresult, err := managedStream.AppendRows(ctx, rows, managedwriter.WithOffset(0))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"AppendRows first call error: %v\", err)\n\t}\n\tresults = append(results, result)\n\n\t\/\/ Advance our current offset.\n\tcurOffset = curOffset + 1\n\n\t\/\/ This time, we'll append three more rows in a single request.\n\trows, err = generateExampleMessages(3)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"generateExampleMessages: %v\", err)\n\t}\n\tresult, err = managedStream.AppendRows(ctx, rows, managedwriter.WithOffset(curOffset))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"AppendRows second call error: %v\", err)\n\t}\n\tresults = append(results, result)\n\n\t\/\/ Advance our offset again.\n\tcurOffset = curOffset + 3\n\n\t\/\/ Finally, we'll append two more rows.\n\trows, err = generateExampleMessages(2)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"generateExampleMessages: %v\", err)\n\t}\n\tresult, err = managedStream.AppendRows(ctx, rows, managedwriter.WithOffset(curOffset))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"AppendRows third call error: %v\", err)\n\t}\n\tresults = append(results, result)\n\n\t\/\/ Now, we'll check that our batch of three appends all completed successfully.\n\t\/\/ Monitoring the results could also be done out of band via a goroutine.\n\tfor k, v := range results {\n\t\t\/\/ GetResult blocks until we receive a response from the API.\n\t\trecvOffset, err := v.GetResult(ctx)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"append %d returned error: %v\", k, err)\n\t\t}\n\t\tfmt.Fprintf(w, \"Successfully appended data at offset %d.\\n\", recvOffset)\n\t}\n\n\t\/\/ We're now done appending to this stream.  We now mark pending stream finalized, which blocks\n\t\/\/ further appends.\n\trowCount, err := managedStream.Finalize(ctx)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error during Finalize: %v\", err)\n\t}\n\n\tfmt.Fprintf(w, \"Stream %s finalized with %d rows.\\n\", managedStream.StreamName(), rowCount)\n\n\t\/\/ To commit the data to the table, we need to run a batch commit.  You can commit several streams\n\t\/\/ atomically as a group, but in this instance we'll only commit the single stream.\n\treq := &storagepb.BatchCommitWriteStreamsRequest{\n\t\tParent:       managedwriter.TableParentFromStreamName(managedStream.StreamName()),\n\t\tWriteStreams: []string{managedStream.StreamName()},\n\t}\n\n\tresp, err := client.BatchCommitWriteStreams(ctx, req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"client.BatchCommit: %v\", err)\n\t}\n\tif len(resp.GetStreamErrors()) > 0 {\n\t\treturn fmt.Errorf(\"stream errors present: %v\", resp.GetStreamErrors())\n\t}\n\n\tfmt.Fprintf(w, \"Table data committed at %s\\n\", resp.GetCommitTime().AsTime().Format(time.RFC3339Nano))\n\n\treturn nil\n}\n\n\/\/ [END bigquerystorage_write_pending_complexschema]\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Licensed to the Apache Software Foundation (ASF) under one or more\n\/\/ contributor license agreements.  See the NOTICE file distributed with\n\/\/ this work for additional information regarding copyright ownership.\n\/\/ The ASF licenses this file to You under the Apache License, Version 2.0\n\/\/ (the \"License\"); you may not use this file except in compliance with\n\/\/ the License.  You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage coder\n\nimport (\n\t\"bytes\"\n\t\"math\"\n\t\"testing\"\n\n\t\"github.com\/apache\/beam\/sdks\/v2\/go\/pkg\/beam\/core\/typex\"\n)\n\nfunc makePaneInfo(timing typex.PaneTiming, first, last bool, index, nsIndex int64) typex.PaneInfo {\n\treturn typex.PaneInfo{Timing: timing, IsFirst: first, IsLast: last, Index: index, NonSpeculativeIndex: nsIndex}\n}\n\nfunc equalPanes(left, right typex.PaneInfo) bool {\n\treturn (left.Timing == right.Timing) && (left.IsFirst == right.IsFirst) && (left.IsLast == right.IsLast) && (left.Index == right.Index) && (left.NonSpeculativeIndex == right.NonSpeculativeIndex)\n}\n\nfunc TestPaneCoder(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\ttiming  typex.PaneTiming\n\t\tfirst   bool\n\t\tlast    bool\n\t\tindex   int64\n\t\tnsIndex int64\n\t}{\n\t\t{\n\t\t\t\"false bools\",\n\t\t\ttypex.PaneUnknown,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\t0,\n\t\t\t0,\n\t\t},\n\t\t{\n\t\t\t\"true bools\",\n\t\t\ttypex.PaneUnknown,\n\t\t\ttrue,\n\t\t\ttrue,\n\t\t\t0,\n\t\t\t0,\n\t\t},\n\t\t{\n\t\t\t\"first pane\",\n\t\t\ttypex.PaneUnknown,\n\t\t\ttrue,\n\t\t\tfalse,\n\t\t\t0,\n\t\t\t0,\n\t\t},\n\t\t{\n\t\t\t\"last pane\",\n\t\t\ttypex.PaneUnknown,\n\t\t\tfalse,\n\t\t\ttrue,\n\t\t\t0,\n\t\t\t0,\n\t\t},\n\t\t{\n\t\t\t\"on time, different index and non-speculative\",\n\t\t\ttypex.PaneOnTime,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\t1,\n\t\t\t2,\n\t\t},\n\t\t{\n\t\t\t\"valid early pane\",\n\t\t\ttypex.PaneEarly,\n\t\t\ttrue,\n\t\t\tfalse,\n\t\t\tmath.MaxInt64,\n\t\t\t-1,\n\t\t},\n\t\t{\n\t\t\t\"on time, max non-speculative index\",\n\t\t\ttypex.PaneOnTime,\n\t\t\tfalse,\n\t\t\ttrue,\n\t\t\t0,\n\t\t\tmath.MaxInt64,\n\t\t},\n\t\t{\n\t\t\t\"late pane, max index\",\n\t\t\ttypex.PaneLate,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\tmath.MaxInt64,\n\t\t\t0,\n\t\t},\n\t\t{\n\t\t\t\"on time, min non-speculative index\",\n\t\t\ttypex.PaneOnTime,\n\t\t\tfalse,\n\t\t\ttrue,\n\t\t\t0,\n\t\t\tmath.MinInt64,\n\t\t},\n\t\t{\n\t\t\t\"late, min index\",\n\t\t\ttypex.PaneLate,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\tmath.MinInt64,\n\t\t\t0,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tinput := makePaneInfo(test.timing, test.first, test.last, test.index, test.nsIndex)\n\t\t\tvar buf bytes.Buffer\n\t\t\terr := EncodePane(input, &buf)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to encode pane %v, got %v\", input, err)\n\t\t\t}\n\t\t\tgot, err := DecodePane(&buf)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to decode pane from buffer %v, got %v\", buf, err)\n\t\t\t}\n\t\t\tif want := input; !equalPanes(got, want) {\n\t\t\t\tt.Errorf(\"got pane %v, want %v\", got, want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestEncodePane_bad(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\ttiming  typex.PaneTiming\n\t\tfirst   bool\n\t\tlast    bool\n\t\tindex   int64\n\t\tnsIndex int64\n\t}{\n\t\t{\n\t\t\t\"invalid early pane, max ints\",\n\t\t\ttypex.PaneEarly,\n\t\t\ttrue,\n\t\t\tfalse,\n\t\t\tmath.MaxInt64,\n\t\t\tmath.MaxInt64,\n\t\t},\n\t\t{\n\t\t\t\"invalid early pane, min ints\",\n\t\t\ttypex.PaneEarly,\n\t\t\ttrue,\n\t\t\tfalse,\n\t\t\tmath.MinInt64,\n\t\t\tmath.MinInt64,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tinput := makePaneInfo(test.timing, test.first, test.last, test.index, test.nsIndex)\n\t\t\tvar buf bytes.Buffer\n\t\t\terr := EncodePane(input, &buf)\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"successfully encoded pane when it should have failed, got %v\", buf)\n\t\t\t}\n\t\t})\n\t}\n}\n<commit_msg>fixes copy by value error for bytes.Buffer in Error (#17469)<commit_after>\/\/ Licensed to the Apache Software Foundation (ASF) under one or more\n\/\/ contributor license agreements.  See the NOTICE file distributed with\n\/\/ this work for additional information regarding copyright ownership.\n\/\/ The ASF licenses this file to You under the Apache License, Version 2.0\n\/\/ (the \"License\"); you may not use this file except in compliance with\n\/\/ the License.  You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage coder\n\nimport (\n\t\"bytes\"\n\t\"math\"\n\t\"testing\"\n\n\t\"github.com\/apache\/beam\/sdks\/v2\/go\/pkg\/beam\/core\/typex\"\n)\n\nfunc makePaneInfo(timing typex.PaneTiming, first, last bool, index, nsIndex int64) typex.PaneInfo {\n\treturn typex.PaneInfo{Timing: timing, IsFirst: first, IsLast: last, Index: index, NonSpeculativeIndex: nsIndex}\n}\n\nfunc equalPanes(left, right typex.PaneInfo) bool {\n\treturn (left.Timing == right.Timing) && (left.IsFirst == right.IsFirst) && (left.IsLast == right.IsLast) && (left.Index == right.Index) && (left.NonSpeculativeIndex == right.NonSpeculativeIndex)\n}\n\nfunc TestPaneCoder(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\ttiming  typex.PaneTiming\n\t\tfirst   bool\n\t\tlast    bool\n\t\tindex   int64\n\t\tnsIndex int64\n\t}{\n\t\t{\n\t\t\t\"false bools\",\n\t\t\ttypex.PaneUnknown,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\t0,\n\t\t\t0,\n\t\t},\n\t\t{\n\t\t\t\"true bools\",\n\t\t\ttypex.PaneUnknown,\n\t\t\ttrue,\n\t\t\ttrue,\n\t\t\t0,\n\t\t\t0,\n\t\t},\n\t\t{\n\t\t\t\"first pane\",\n\t\t\ttypex.PaneUnknown,\n\t\t\ttrue,\n\t\t\tfalse,\n\t\t\t0,\n\t\t\t0,\n\t\t},\n\t\t{\n\t\t\t\"last pane\",\n\t\t\ttypex.PaneUnknown,\n\t\t\tfalse,\n\t\t\ttrue,\n\t\t\t0,\n\t\t\t0,\n\t\t},\n\t\t{\n\t\t\t\"on time, different index and non-speculative\",\n\t\t\ttypex.PaneOnTime,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\t1,\n\t\t\t2,\n\t\t},\n\t\t{\n\t\t\t\"valid early pane\",\n\t\t\ttypex.PaneEarly,\n\t\t\ttrue,\n\t\t\tfalse,\n\t\t\tmath.MaxInt64,\n\t\t\t-1,\n\t\t},\n\t\t{\n\t\t\t\"on time, max non-speculative index\",\n\t\t\ttypex.PaneOnTime,\n\t\t\tfalse,\n\t\t\ttrue,\n\t\t\t0,\n\t\t\tmath.MaxInt64,\n\t\t},\n\t\t{\n\t\t\t\"late pane, max index\",\n\t\t\ttypex.PaneLate,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\tmath.MaxInt64,\n\t\t\t0,\n\t\t},\n\t\t{\n\t\t\t\"on time, min non-speculative index\",\n\t\t\ttypex.PaneOnTime,\n\t\t\tfalse,\n\t\t\ttrue,\n\t\t\t0,\n\t\t\tmath.MinInt64,\n\t\t},\n\t\t{\n\t\t\t\"late, min index\",\n\t\t\ttypex.PaneLate,\n\t\t\tfalse,\n\t\t\tfalse,\n\t\t\tmath.MinInt64,\n\t\t\t0,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tinput := makePaneInfo(test.timing, test.first, test.last, test.index, test.nsIndex)\n\t\t\tvar buf bytes.Buffer\n\t\t\terr := EncodePane(input, &buf)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to encode pane %v, got %v\", input, err)\n\t\t\t}\n\t\t\tgot, err := DecodePane(&buf)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"failed to decode pane from buffer %v, got %v\", &buf, err)\n\t\t\t}\n\t\t\tif want := input; !equalPanes(got, want) {\n\t\t\t\tt.Errorf(\"got pane %v, want %v\", got, want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestEncodePane_bad(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\ttiming  typex.PaneTiming\n\t\tfirst   bool\n\t\tlast    bool\n\t\tindex   int64\n\t\tnsIndex int64\n\t}{\n\t\t{\n\t\t\t\"invalid early pane, max ints\",\n\t\t\ttypex.PaneEarly,\n\t\t\ttrue,\n\t\t\tfalse,\n\t\t\tmath.MaxInt64,\n\t\t\tmath.MaxInt64,\n\t\t},\n\t\t{\n\t\t\t\"invalid early pane, min ints\",\n\t\t\ttypex.PaneEarly,\n\t\t\ttrue,\n\t\t\tfalse,\n\t\t\tmath.MinInt64,\n\t\t\tmath.MinInt64,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tinput := makePaneInfo(test.timing, test.first, test.last, test.index, test.nsIndex)\n\t\t\tvar buf bytes.Buffer\n\t\t\terr := EncodePane(input, &buf)\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"successfully encoded pane when it should have failed, got %v\", &buf)\n\t\t\t}\n\t\t})\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) OpenFaaS Author(s). All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\npackage handlers\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/openfaas\/faas\/gateway\/types\"\n)\n\n\/\/ functionMatcher parses out the service name (group 1) and rest of path (group 2).\nvar functionMatcher = regexp.MustCompile(\"^\/?(?:async-)?function\/([^\/?]+)([^?]*)\")\n\n\/\/ Indices and meta-data for functionMatcher regex parts\nconst (\n\thasPathCount = 3\n\trouteIndex   = 0 \/\/ routeIndex corresponds to \/function\/ or \/async-function\/\n\tnameIndex    = 1 \/\/ nameIndex is the function name\n\tpathIndex    = 2 \/\/ pathIndex is the path i.e. \/employee\/:id\/\n)\n\n\/\/ BaseURLResolver URL resolver for upstream requests\ntype BaseURLResolver interface {\n\tResolve(r *http.Request) string\n}\n\n\/\/ URLPathTransformer Transform the incoming URL path for upstream requests\ntype URLPathTransformer interface {\n\tTransform(r *http.Request) string\n}\n\n\/\/ MakeForwardingProxyHandler create a handler which forwards HTTP requests\nfunc MakeForwardingProxyHandler(proxy *types.HTTPClientReverseProxy, notifiers []HTTPNotifier, baseURLResolver BaseURLResolver, urlPathTransformer URLPathTransformer) http.HandlerFunc {\n\n\twriteRequestURI := false\n\tif _, exists := os.LookupEnv(\"write_request_uri\"); exists {\n\t\twriteRequestURI = exists\n\t}\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tbaseURL := baseURLResolver.Resolve(r)\n\t\toriginalURL := r.URL.String()\n\n\t\trequestURL := urlPathTransformer.Transform(r)\n\n\t\tstart := time.Now()\n\n\t\tstatusCode, err := forwardRequest(w, r, proxy.Client, baseURL, requestURL, proxy.Timeout, writeRequestURI)\n\n\t\tseconds := time.Since(start)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error with upstream request to: %s, %s\\n\", requestURL, err.Error())\n\t\t}\n\n\t\t\/\/ defer func() {\n\t\tfor _, notifier := range notifiers {\n\t\t\tnotifier.Notify(r.Method, requestURL, originalURL, statusCode, seconds)\n\t\t}\n\t\t\/\/ }()\n\n\t}\n}\n\nfunc buildUpstreamRequest(r *http.Request, baseURL string, requestURL string) *http.Request {\n\turl := baseURL + requestURL\n\n\tif len(r.URL.RawQuery) > 0 {\n\t\turl = fmt.Sprintf(\"%s?%s\", url, r.URL.RawQuery)\n\t}\n\n\tupstreamReq, _ := http.NewRequest(r.Method, url, nil)\n\n\tcopyHeaders(upstreamReq.Header, &r.Header)\n\tdeleteHeaders(&upstreamReq.Header, &hopHeaders)\n\n\tif len(r.Host) > 0 && upstreamReq.Header.Get(\"X-Forwarded-Host\") == \"\" {\n\t\tupstreamReq.Header[\"X-Forwarded-Host\"] = []string{r.Host}\n\t}\n\tif upstreamReq.Header.Get(\"X-Forwarded-For\") == \"\" {\n\t\tupstreamReq.Header[\"X-Forwarded-For\"] = []string{r.RemoteAddr}\n\t}\n\n\tif r.Body != nil {\n\t\tupstreamReq.Body = r.Body\n\t}\n\n\treturn upstreamReq\n}\n\nfunc forwardRequest(w http.ResponseWriter, r *http.Request, proxyClient *http.Client, baseURL string, requestURL string, timeout time.Duration, writeRequestURI bool) (int, error) {\n\n\tupstreamReq := buildUpstreamRequest(r, baseURL, requestURL)\n\tif upstreamReq.Body != nil {\n\t\tdefer upstreamReq.Body.Close()\n\t}\n\n\tif writeRequestURI {\n\t\tlog.Printf(\"forwardRequest: %s %s\\n\", upstreamReq.Host, upstreamReq.URL.String())\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\tres, resErr := proxyClient.Do(upstreamReq.WithContext(ctx))\n\tif resErr != nil {\n\t\tbadStatus := http.StatusBadGateway\n\t\tw.WriteHeader(badStatus)\n\t\treturn badStatus, resErr\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tcopyHeaders(w.Header(), &res.Header)\n\n\t\/\/ Write status code\n\tw.WriteHeader(res.StatusCode)\n\n\tif res.Body != nil {\n\t\t\/\/ Copy the body over\n\t\tio.CopyBuffer(w, res.Body, nil)\n\t}\n\n\treturn res.StatusCode, nil\n}\n\nfunc copyHeaders(destination http.Header, source *http.Header) {\n\tfor k, v := range *source {\n\t\tvClone := make([]string, len(v))\n\t\tcopy(vClone, v)\n\t\t(destination)[k] = vClone\n\t}\n}\n\nfunc deleteHeaders(target *http.Header, exclude *[]string) {\n\tfor _, h := range *exclude {\n\t\ttarget.Del(h)\n\t}\n}\n\n\/\/ SingleHostBaseURLResolver resolves URLs against a single BaseURL\ntype SingleHostBaseURLResolver struct {\n\tBaseURL string\n}\n\n\/\/ Resolve the base URL for a request\nfunc (s SingleHostBaseURLResolver) Resolve(r *http.Request) string {\n\n\tbaseURL := s.BaseURL\n\n\tif strings.HasSuffix(baseURL, \"\/\") {\n\t\tbaseURL = baseURL[0 : len(baseURL)-1]\n\t}\n\treturn baseURL\n}\n\n\/\/ FunctionAsHostBaseURLResolver resolves URLs using a function from the URL as a host\ntype FunctionAsHostBaseURLResolver struct {\n\tFunctionSuffix string\n}\n\n\/\/ Resolve the base URL for a request\nfunc (f FunctionAsHostBaseURLResolver) Resolve(r *http.Request) string {\n\tsvcName := getServiceName(r.URL.Path)\n\n\tconst watchdogPort = 8080\n\tvar suffix string\n\tif len(f.FunctionSuffix) > 0 {\n\t\tsuffix = \".\" + f.FunctionSuffix\n\t}\n\n\treturn fmt.Sprintf(\"http:\/\/%s%s:%d\", svcName, suffix, watchdogPort)\n}\n\n\/\/ TransparentURLPathTransformer passes the requested URL path through untouched.\ntype TransparentURLPathTransformer struct {\n}\n\n\/\/ Transform returns the URL path unchanged.\nfunc (f TransparentURLPathTransformer) Transform(r *http.Request) string {\n\treturn r.URL.Path\n}\n\n\/\/ FunctionPrefixTrimmingURLPathTransformer removes the \"\/function\/servicename\/\" prefix from the URL path.\ntype FunctionPrefixTrimmingURLPathTransformer struct {\n}\n\n\/\/ Transform removes the \"\/function\/servicename\/\" prefix from the URL path.\nfunc (f FunctionPrefixTrimmingURLPathTransformer) Transform(r *http.Request) string {\n\tret := r.URL.Path\n\n\tif ret != \"\" {\n\t\t\/\/ When forwarding to a function, since the `\/function\/xyz` portion\n\t\t\/\/ of a path like `\/function\/xyz\/rest\/of\/path` is only used or needed\n\t\t\/\/ by the Gateway, we want to trim it down to `\/rest\/of\/path` for the\n\t\t\/\/ upstream request.  In the following regex, in the case of a match\n\t\t\/\/ the r.URL.Path will be at `0`, the function name at `1` and the\n\t\t\/\/ rest of the path (the part we are interested in) at `2`.\n\t\tmatcher := functionMatcher.Copy()\n\t\tparts := matcher.FindStringSubmatch(ret)\n\t\tif len(parts) == hasPathCount {\n\t\t\tret = parts[pathIndex]\n\t\t}\n\t}\n\n\treturn ret\n}\n\n\/\/ Hop-by-hop headers. These are removed when sent to the backend.\n\/\/ As of RFC 7230, hop-by-hop headers are required to appear in the\n\/\/ Connection header field. These are the headers defined by the\n\/\/ obsoleted RFC 2616 (section 13.5.1) and are used for backward\n\/\/ compatibility.\nvar hopHeaders = []string{\n\t\"Connection\",\n\t\"Proxy-Connection\", \/\/ non-standard but still sent by libcurl and rejected by e.g. google\n\t\"Keep-Alive\",\n\t\"Proxy-Authenticate\",\n\t\"Proxy-Authorization\",\n\t\"Te\",      \/\/ canonicalized version of \"TE\"\n\t\"Trailer\", \/\/ not Trailers per URL above; https:\/\/www.rfc-editor.org\/errata_search.php?eid=4522\n\t\"Transfer-Encoding\",\n\t\"Upgrade\",\n}\n<commit_msg>Quote source of hop headers<commit_after>\/\/ Copyright (c) OpenFaaS Author(s). All rights reserved.\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\npackage handlers\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/openfaas\/faas\/gateway\/types\"\n)\n\n\/\/ functionMatcher parses out the service name (group 1) and rest of path (group 2).\nvar functionMatcher = regexp.MustCompile(\"^\/?(?:async-)?function\/([^\/?]+)([^?]*)\")\n\n\/\/ Indices and meta-data for functionMatcher regex parts\nconst (\n\thasPathCount = 3\n\trouteIndex   = 0 \/\/ routeIndex corresponds to \/function\/ or \/async-function\/\n\tnameIndex    = 1 \/\/ nameIndex is the function name\n\tpathIndex    = 2 \/\/ pathIndex is the path i.e. \/employee\/:id\/\n)\n\n\/\/ BaseURLResolver URL resolver for upstream requests\ntype BaseURLResolver interface {\n\tResolve(r *http.Request) string\n}\n\n\/\/ URLPathTransformer Transform the incoming URL path for upstream requests\ntype URLPathTransformer interface {\n\tTransform(r *http.Request) string\n}\n\n\/\/ MakeForwardingProxyHandler create a handler which forwards HTTP requests\nfunc MakeForwardingProxyHandler(proxy *types.HTTPClientReverseProxy, notifiers []HTTPNotifier, baseURLResolver BaseURLResolver, urlPathTransformer URLPathTransformer) http.HandlerFunc {\n\n\twriteRequestURI := false\n\tif _, exists := os.LookupEnv(\"write_request_uri\"); exists {\n\t\twriteRequestURI = exists\n\t}\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tbaseURL := baseURLResolver.Resolve(r)\n\t\toriginalURL := r.URL.String()\n\n\t\trequestURL := urlPathTransformer.Transform(r)\n\n\t\tstart := time.Now()\n\n\t\tstatusCode, err := forwardRequest(w, r, proxy.Client, baseURL, requestURL, proxy.Timeout, writeRequestURI)\n\n\t\tseconds := time.Since(start)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error with upstream request to: %s, %s\\n\", requestURL, err.Error())\n\t\t}\n\n\t\t\/\/ defer func() {\n\t\tfor _, notifier := range notifiers {\n\t\t\tnotifier.Notify(r.Method, requestURL, originalURL, statusCode, seconds)\n\t\t}\n\t\t\/\/ }()\n\n\t}\n}\n\nfunc buildUpstreamRequest(r *http.Request, baseURL string, requestURL string) *http.Request {\n\turl := baseURL + requestURL\n\n\tif len(r.URL.RawQuery) > 0 {\n\t\turl = fmt.Sprintf(\"%s?%s\", url, r.URL.RawQuery)\n\t}\n\n\tupstreamReq, _ := http.NewRequest(r.Method, url, nil)\n\n\tcopyHeaders(upstreamReq.Header, &r.Header)\n\tdeleteHeaders(&upstreamReq.Header, &hopHeaders)\n\n\tif len(r.Host) > 0 && upstreamReq.Header.Get(\"X-Forwarded-Host\") == \"\" {\n\t\tupstreamReq.Header[\"X-Forwarded-Host\"] = []string{r.Host}\n\t}\n\tif upstreamReq.Header.Get(\"X-Forwarded-For\") == \"\" {\n\t\tupstreamReq.Header[\"X-Forwarded-For\"] = []string{r.RemoteAddr}\n\t}\n\n\tif r.Body != nil {\n\t\tupstreamReq.Body = r.Body\n\t}\n\n\treturn upstreamReq\n}\n\nfunc forwardRequest(w http.ResponseWriter, r *http.Request, proxyClient *http.Client, baseURL string, requestURL string, timeout time.Duration, writeRequestURI bool) (int, error) {\n\n\tupstreamReq := buildUpstreamRequest(r, baseURL, requestURL)\n\tif upstreamReq.Body != nil {\n\t\tdefer upstreamReq.Body.Close()\n\t}\n\n\tif writeRequestURI {\n\t\tlog.Printf(\"forwardRequest: %s %s\\n\", upstreamReq.Host, upstreamReq.URL.String())\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\tres, resErr := proxyClient.Do(upstreamReq.WithContext(ctx))\n\tif resErr != nil {\n\t\tbadStatus := http.StatusBadGateway\n\t\tw.WriteHeader(badStatus)\n\t\treturn badStatus, resErr\n\t}\n\n\tif res.Body != nil {\n\t\tdefer res.Body.Close()\n\t}\n\n\tcopyHeaders(w.Header(), &res.Header)\n\n\t\/\/ Write status code\n\tw.WriteHeader(res.StatusCode)\n\n\tif res.Body != nil {\n\t\t\/\/ Copy the body over\n\t\tio.CopyBuffer(w, res.Body, nil)\n\t}\n\n\treturn res.StatusCode, nil\n}\n\nfunc copyHeaders(destination http.Header, source *http.Header) {\n\tfor k, v := range *source {\n\t\tvClone := make([]string, len(v))\n\t\tcopy(vClone, v)\n\t\t(destination)[k] = vClone\n\t}\n}\n\nfunc deleteHeaders(target *http.Header, exclude *[]string) {\n\tfor _, h := range *exclude {\n\t\ttarget.Del(h)\n\t}\n}\n\n\/\/ SingleHostBaseURLResolver resolves URLs against a single BaseURL\ntype SingleHostBaseURLResolver struct {\n\tBaseURL string\n}\n\n\/\/ Resolve the base URL for a request\nfunc (s SingleHostBaseURLResolver) Resolve(r *http.Request) string {\n\n\tbaseURL := s.BaseURL\n\n\tif strings.HasSuffix(baseURL, \"\/\") {\n\t\tbaseURL = baseURL[0 : len(baseURL)-1]\n\t}\n\treturn baseURL\n}\n\n\/\/ FunctionAsHostBaseURLResolver resolves URLs using a function from the URL as a host\ntype FunctionAsHostBaseURLResolver struct {\n\tFunctionSuffix string\n}\n\n\/\/ Resolve the base URL for a request\nfunc (f FunctionAsHostBaseURLResolver) Resolve(r *http.Request) string {\n\tsvcName := getServiceName(r.URL.Path)\n\n\tconst watchdogPort = 8080\n\tvar suffix string\n\tif len(f.FunctionSuffix) > 0 {\n\t\tsuffix = \".\" + f.FunctionSuffix\n\t}\n\n\treturn fmt.Sprintf(\"http:\/\/%s%s:%d\", svcName, suffix, watchdogPort)\n}\n\n\/\/ TransparentURLPathTransformer passes the requested URL path through untouched.\ntype TransparentURLPathTransformer struct {\n}\n\n\/\/ Transform returns the URL path unchanged.\nfunc (f TransparentURLPathTransformer) Transform(r *http.Request) string {\n\treturn r.URL.Path\n}\n\n\/\/ FunctionPrefixTrimmingURLPathTransformer removes the \"\/function\/servicename\/\" prefix from the URL path.\ntype FunctionPrefixTrimmingURLPathTransformer struct {\n}\n\n\/\/ Transform removes the \"\/function\/servicename\/\" prefix from the URL path.\nfunc (f FunctionPrefixTrimmingURLPathTransformer) Transform(r *http.Request) string {\n\tret := r.URL.Path\n\n\tif ret != \"\" {\n\t\t\/\/ When forwarding to a function, since the `\/function\/xyz` portion\n\t\t\/\/ of a path like `\/function\/xyz\/rest\/of\/path` is only used or needed\n\t\t\/\/ by the Gateway, we want to trim it down to `\/rest\/of\/path` for the\n\t\t\/\/ upstream request.  In the following regex, in the case of a match\n\t\t\/\/ the r.URL.Path will be at `0`, the function name at `1` and the\n\t\t\/\/ rest of the path (the part we are interested in) at `2`.\n\t\tmatcher := functionMatcher.Copy()\n\t\tparts := matcher.FindStringSubmatch(ret)\n\t\tif len(parts) == hasPathCount {\n\t\t\tret = parts[pathIndex]\n\t\t}\n\t}\n\n\treturn ret\n}\n\n\/\/ Hop-by-hop headers. These are removed when sent to the backend.\n\/\/ As of RFC 7230, hop-by-hop headers are required to appear in the\n\/\/ Connection header field. These are the headers defined by the\n\/\/ obsoleted RFC 2616 (section 13.5.1) and are used for backward\n\/\/ compatibility.\n\/\/ Copied from: https:\/\/golang.org\/src\/net\/http\/httputil\/reverseproxy.go\nvar hopHeaders = []string{\n\t\"Connection\",\n\t\"Proxy-Connection\", \/\/ non-standard but still sent by libcurl and rejected by e.g. google\n\t\"Keep-Alive\",\n\t\"Proxy-Authenticate\",\n\t\"Proxy-Authorization\",\n\t\"Te\",      \/\/ canonicalized version of \"TE\"\n\t\"Trailer\", \/\/ not Trailers per URL above; https:\/\/www.rfc-editor.org\/errata_search.php?eid=4522\n\t\"Transfer-Encoding\",\n\t\"Upgrade\",\n}\n<|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"net\"\n\t\"os\"\n\t\"testing\"\n)\n\ntype mockNetConn struct {\n\t*testing.T\n\n\tIn, Out chan string\n\tin, out chan []byte\n\n\tclosed bool\n\trt, wt int64\n}\n\nfunc MockNetConn(t *testing.T) (*mockNetConn) {\n\t\/\/ Our mock connection is a testing object\n\tm := &mockNetConn{T: t}\n\n\t\/\/ set known values for conn info\n\tm.closed = false\n\tm.rt = 0\n\tm.wt = 0\n\n\t\/\/ buffer input\n\tm.In = make(chan string, 20)\n\tm.in = make(chan []byte)\n\tgo func() {\n\t\tfor !m.closed {\n\t\t\tm.in <- []byte(<-m.In)\n\t\t}\n\t}()\n\n\t\/\/ buffer output\n\tm.Out = make(chan string)\n\tm.out = make(chan []byte, 20)\n\tgo func() {\n\t\tfor !m.closed {\n\t\t\tm.Out <- string(<-m.out)\n\t\t}\n\t}()\n\treturn m\n}\n\n\/\/ Test helper\nfunc (m *mockNetConn) Expect(e string) {\n\ts := <-m.Out\n\tif e + \"\\r\\n\" != s {\n\t\tm.Errorf(\"Mock connection received unexpected value.\\n\\t\" +\n\t\t\t\"Expected: %s\\n\\tGot: %s\", e, s)\n\t}\n}\n\n\/\/ Implement net.Conn interface\nfunc (m *mockNetConn) Read(b []byte) (int, os.Error) {\n\ts := <-m.in\n\tcopy(b, s)\n\treturn len(s), nil\n}\n\nfunc (m *mockNetConn) Write(s []byte) (int, os.Error) {\n\tb := make([]byte, len(s))\n\tcopy(b, s)\n\tm.out <- b\n\treturn len(b), nil\n}\n\nfunc (m *mockNetConn) Close() os.Error {\n\tm.closed = true\n\treturn nil\n}\n\nfunc (m *mockNetConn) LocalAddr() net.Addr {\n\treturn &net.IPAddr{net.IPv4(127,0,0,1)}\n}\n\nfunc (m *mockNetConn) RemoteAddr() net.Addr {\n\treturn &net.IPAddr{net.IPv4(127,0,0,1)}\n}\n\nfunc (m *mockNetConn) SetTimeout(ns int64) os.Error {\n\tm.rt = ns\n\tm.wt = ns\n\treturn nil\n}\n\nfunc (m *mockNetConn) SetReadTimeout(ns int64) os.Error {\n\tm.rt = ns\n\treturn nil\n}\n\nfunc (m *mockNetConn) SetWriteTimeout(ns int64) os.Error {\n\tm.wt = ns\n\treturn nil\n}\n<commit_msg>Add Send method for mockNetConn, and make Read\/Write return errors when closed.<commit_after>package client\n\nimport (\n\t\"net\"\n\t\"os\"\n\t\"testing\"\n)\n\ntype mockNetConn struct {\n\t*testing.T\n\n\tIn, Out chan string\n\tin, out chan []byte\n\n\tclosed bool\n\trt, wt int64\n}\n\nfunc MockNetConn(t *testing.T) (*mockNetConn) {\n\t\/\/ Our mock connection is a testing object\n\tm := &mockNetConn{T: t}\n\n\t\/\/ set known values for conn info\n\tm.closed = false\n\tm.rt = 0\n\tm.wt = 0\n\n\t\/\/ buffer input\n\tm.In = make(chan string, 20)\n\tm.in = make(chan []byte)\n\tgo func() {\n\t\tfor !m.closed {\n\t\t\tm.in <- []byte(<-m.In)\n\t\t}\n\t}()\n\n\t\/\/ buffer output\n\tm.Out = make(chan string)\n\tm.out = make(chan []byte, 20)\n\tgo func() {\n\t\tfor !m.closed {\n\t\t\tm.Out <- string(<-m.out)\n\t\t}\n\t}()\n\treturn m\n}\n\n\/\/ Test helpers\nfunc (m *mockNetConn) Send(s string) {\n\tm.In <- s + \"\\r\\n\"\n}\n\nfunc (m *mockNetConn) Expect(e string) {\n\ts := <-m.Out\n\tif e + \"\\r\\n\" != s {\n\t\tm.Errorf(\"Mock connection received unexpected value.\\n\\t\" +\n\t\t\t\"Expected: %s\\n\\tGot: %s\", e, s)\n\t}\n}\n\n\/\/ Implement net.Conn interface\nfunc (m *mockNetConn) Read(b []byte) (int, os.Error) {\n\tif m.closed {\n\t\treturn 0, os.NewError(\"EOF\")\n\t}\n\ts := <-m.in\n\tcopy(b, s)\n\treturn len(s), nil\n}\n\nfunc (m *mockNetConn) Write(s []byte) (int, os.Error) {\n\tif m.closed {\n\t\treturn 0, os.NewError(\"Can't write to closed socket.\")\n\t}\n\tb := make([]byte, len(s))\n\tcopy(b, s)\n\tm.out <- b\n\treturn len(b), nil\n}\n\nfunc (m *mockNetConn) Close() os.Error {\n\tm.closed = true\n\treturn nil\n}\n\nfunc (m *mockNetConn) LocalAddr() net.Addr {\n\treturn &net.IPAddr{net.IPv4(127,0,0,1)}\n}\n\nfunc (m *mockNetConn) RemoteAddr() net.Addr {\n\treturn &net.IPAddr{net.IPv4(127,0,0,1)}\n}\n\nfunc (m *mockNetConn) SetTimeout(ns int64) os.Error {\n\tm.rt = ns\n\tm.wt = ns\n\treturn nil\n}\n\nfunc (m *mockNetConn) SetReadTimeout(ns int64) os.Error {\n\tm.rt = ns\n\treturn nil\n}\n\nfunc (m *mockNetConn) SetWriteTimeout(ns int64) os.Error {\n\tm.wt = ns\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage timeutil_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/jacobsa\/gcsfuse\/timeutil\"\n\t. \"github.com\/jacobsa\/ogletest\"\n)\n\nfunc TestTimeEq(t *testing.T) { RunTests(t) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Boilerplate\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype TimeEqTest struct {\n}\n\nfunc init() { RegisterTestSuite(&TimeEqTest{}) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *TimeEqTest) Description() {\n\texpected := time.Now()\n\tmatcher := timeutil.TimeEq(expected)\n\tExpectEq(expected.String(), matcher.Description())\n}\n\nfunc (t *TimeEqTest) DoesFoo() {\n\tAssertTrue(false, \"TODO\")\n}\n<commit_msg>Added test names.<commit_after>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage timeutil_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/jacobsa\/gcsfuse\/timeutil\"\n\t. \"github.com\/jacobsa\/ogletest\"\n)\n\nfunc TestTimeEq(t *testing.T) { RunTests(t) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Boilerplate\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype TimeEqTest struct {\n}\n\nfunc init() { RegisterTestSuite(&TimeEqTest{}) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *TimeEqTest) Description() {\n\texpected := time.Now()\n\tmatcher := timeutil.TimeEq(expected)\n\tExpectEq(expected.String(), matcher.Description())\n}\n\nfunc (t *TimeEqTest) ActualIsNil() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *TimeEqTest) ActualIsString() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *TimeEqTest) ActualIsBeforeExpected() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *TimeEqTest) ActualIsAfterExpected() {\n\tAssertTrue(false, \"TODO\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package tools\n\nimport (\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n)\n\n\/\/ KeyValueStore provides an in-memory key\/value store which is persisted to\n\/\/ a file. The file handle itself is not kept locked for the duration; it is\n\/\/ only locked during load and save, to make it concurrency friendly. When\n\/\/ saving, the store uses optimistic locking to determine whether the db on disk\n\/\/ has been modified by another process; in which case it loads the latest\n\/\/ version and re-applies modifications made during this session. This means\n\/\/ the Lost Update db concurrency issue is possible; so don't use this if you\n\/\/ need more DB integrity than Read Committed isolation levels.\ntype KeyValueStore struct {\n\tmu       sync.RWMutex\n\tfilename string\n\tlog      []keyValueChange\n\n\t\/\/ This is the persistent data\n\t\/\/ version for optimistic locking, this field is incremented with every Save()\n\tversion int64\n\tdb      map[string]interface{}\n}\n\ntype keyValueOperation int\n\nconst (\n\t\/\/ Set a value for a key\n\tkeyValueSetOperation = keyValueOperation(iota)\n\t\/\/ Removed a value for a key\n\tkeyValueRemoveOperation = keyValueOperation(iota)\n)\n\ntype keyValueChange struct {\n\toperation keyValueOperation\n\tkey       string\n\tvalue     interface{}\n}\n\n\/\/ NewKeyValueStore creates a new store and initialises it with contents from\n\/\/ the named file, if it exists\nfunc NewKeyValueStore(filepath string) (*KeyValueStore, error) {\n\tkv := &KeyValueStore{filename: filepath, db: make(map[string]interface{})}\n\terr := kv.loadAndMergeIfNeeded()\n\treturn kv, err\n}\n\n\/\/ Set updates the key\/value store in memory\n\/\/ Changes are not persisted until you call Save()\nfunc (k *KeyValueStore) Set(key string, value interface{}) {\n\tk.mu.Lock()\n\tdefer k.mu.Unlock()\n\n\tk.db[key] = value\n\tk.log = append(k.log, keyValueChange{keyValueSetOperation, key, value})\n}\n\n\/\/ Remove removes the key and its value from the store in memory\n\/\/ Changes are not persisted until you call Save()\nfunc (k *KeyValueStore) Remove(key string) {\n\tk.mu.Lock()\n\tdefer k.mu.Unlock()\n\n\tdelete(k.db, key)\n\tk.log = append(k.log, keyValueChange{keyValueRemoveOperation, key, nil})\n}\n\n\/\/ Get retrieves a value from the store, or nil if it is not present\nfunc (k *KeyValueStore) Get(key string) interface{} {\n\t\/\/ Read-only lock\n\tk.mu.RLock()\n\tdefer k.mu.RUnlock()\n\n\t\/\/ zero value of interface{} is nil so this does what we want\n\treturn k.db[key]\n}\n\n\/\/ Save persists the changes made to disk\n\/\/ If any changes have been written by other code they will be merged\nfunc (k *KeyValueStore) Save() error {\n\tk.mu.Lock()\n\tdefer k.mu.Unlock()\n\n\t\/\/ Short-circuit if we have no changes\n\tif len(k.log) == 0 {\n\t\treturn nil\n\t}\n\n\t\/\/ firstly peek at version; open read\/write to keep lock between check & write\n\tf, err := os.OpenFile(k.filename, os.O_RDWR|os.O_CREATE, 0664)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstat, _ := os.Stat(k.filename)\n\n\tdefer f.Close()\n\n\t\/\/ Only try to merge if > 0 bytes, ignore empty files (decoder will fail)\n\tif stat.Size() > 0 {\n\t\tk.loadAndMergeReaderIfNeeded(f)\n\t\t\/\/ Now we overwrite the file\n\t\tf.Seek(0, os.SEEK_SET)\n\t\tf.Truncate(0)\n\t}\n\n\tk.version++\n\n\tenc := gob.NewEncoder(f)\n\terr = enc.Encode(k.version)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error while writing version data to %v: %v\", k.filename, err)\n\t}\n\terr = enc.Encode(k.db)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error while writing new key\/value data to %v: %v\", k.filename, err)\n\t}\n\t\/\/ Clear log now that it's saved\n\tk.log = nil\n\n\treturn nil\n}\n\n\/\/ Reads as little as possible from the passed in file to determine if the\n\/\/ contents are different from the version already held. If so, reads the\n\/\/ contents and merges with any outstanding changes. If not, stops early without\n\/\/ reading the rest of the file\nfunc (k *KeyValueStore) loadAndMergeIfNeeded() error {\n\tstat, err := os.Stat(k.filename)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \/\/ missing is OK\n\t\t}\n\t\treturn err\n\t}\n\t\/\/ Do nothing if empty file\n\tif stat.Size() == 0 {\n\t\treturn nil\n\t}\n\n\tf, err := os.OpenFile(k.filename, os.O_RDONLY, 0664)\n\tif err == nil {\n\t\tdefer f.Close()\n\t\treturn k.loadAndMergeReaderIfNeeded(f)\n\t} else if !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ As loadAndMergeIfNeeded but lets caller decide how to manage file handles\nfunc (k *KeyValueStore) loadAndMergeReaderIfNeeded(f io.Reader) error {\n\tvar versionOnDisk int64\n\t\/\/ Decode *only* the version field to check whether anyone else has\n\t\/\/ modified the db; gob serializes structs in order so it will always be 1st\n\tdec := gob.NewDecoder(f)\n\terr := dec.Decode(&versionOnDisk)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Problem checking version of key\/value data from %v: %v\", k.filename, err)\n\t}\n\t\/\/ Totally uninitialised Version == 0, saved versions are always >=1\n\tif versionOnDisk != k.version {\n\t\t\/\/ Reload data & merge\n\t\tvar dbOnDisk map[string]interface{}\n\t\terr = dec.Decode(&dbOnDisk)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Problem reading updated key\/value data from %v: %v\", k.filename, err)\n\t\t}\n\t\tk.reapplyChanges(dbOnDisk)\n\t\tk.version = versionOnDisk\n\t}\n\treturn nil\n}\n\n\/\/ reapplyChanges replays the changes made since the last load onto baseDb\n\/\/ and stores the result as our own DB\nfunc (k *KeyValueStore) reapplyChanges(baseDb map[string]interface{}) {\n\tfor _, change := range k.log {\n\t\tswitch change.operation {\n\t\tcase keyValueSetOperation:\n\t\t\tbaseDb[change.key] = change.value\n\t\tcase keyValueRemoveOperation:\n\t\t\tdelete(baseDb, change.key)\n\t\t}\n\t}\n\t\/\/ Note, log is not cleared here, that only happens on Save since it's a\n\t\/\/ list of unsaved changes\n\tk.db = baseDb\n\n}\n\n\/\/ RegisterTypeForKeyValueStorage registers a custom type (e.g. a struct) for\n\/\/ use in the key value store. This is necessary if you intend to pass custom\n\/\/ structs to KeyValueStore.Set() rather than primitive types.\nfunc RegisterTypeForKeyValueStorage(val interface{}) {\n\tgob.Register(val)\n}\n<commit_msg>PR feedback<commit_after>package tools\n\nimport (\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n)\n\n\/\/ KeyValueStore provides an in-memory key\/value store which is persisted to\n\/\/ a file. The file handle itself is not kept locked for the duration; it is\n\/\/ only locked during load and save, to make it concurrency friendly. When\n\/\/ saving, the store uses optimistic locking to determine whether the db on disk\n\/\/ has been modified by another process; in which case it loads the latest\n\/\/ version and re-applies modifications made during this session. This means\n\/\/ the Lost Update db concurrency issue is possible; so don't use this if you\n\/\/ need more DB integrity than Read Committed isolation levels.\ntype KeyValueStore struct {\n\t\/\/ Locks the entire store\n\tmu       sync.RWMutex\n\tfilename string\n\tlog      []keyValueChange\n\n\t\/\/ This is the persistent data\n\t\/\/ version for optimistic locking, this field is incremented with every Save()\n\tversion int64\n\tdb      map[string]interface{}\n}\n\ntype keyValueOperation int\n\nconst (\n\t\/\/ Set a value for a key\n\tkeyValueSetOperation = keyValueOperation(iota)\n\t\/\/ Removed a value for a key\n\tkeyValueRemoveOperation = keyValueOperation(iota)\n)\n\ntype keyValueChange struct {\n\toperation keyValueOperation\n\tkey       string\n\tvalue     interface{}\n}\n\n\/\/ NewKeyValueStore creates a new store and initialises it with contents from\n\/\/ the named file, if it exists\nfunc NewKeyValueStore(filepath string) (*KeyValueStore, error) {\n\tkv := &KeyValueStore{filename: filepath, db: make(map[string]interface{})}\n\treturn kv, kv.loadAndMergeIfNeeded()\n}\n\n\/\/ Set updates the key\/value store in memory\n\/\/ Changes are not persisted until you call Save()\nfunc (k *KeyValueStore) Set(key string, value interface{}) {\n\tk.mu.Lock()\n\tdefer k.mu.Unlock()\n\n\tk.db[key] = value\n\tk.logChange(keyValueSetOperation, key, value)\n}\n\n\/\/ Remove removes the key and its value from the store in memory\n\/\/ Changes are not persisted until you call Save()\nfunc (k *KeyValueStore) Remove(key string) {\n\tk.mu.Lock()\n\tdefer k.mu.Unlock()\n\n\tdelete(k.db, key)\n\tk.logChange(keyValueRemoveOperation, key, nil)\n}\n\n\/\/ Append a change to the log; mutex must already be locked\nfunc (k *KeyValueStore) logChange(op keyValueOperation, key string, value interface{}) {\n\tk.log = append(k.log, keyValueChange{op, key, value})\n}\n\n\/\/ Get retrieves a value from the store, or nil if it is not present\nfunc (k *KeyValueStore) Get(key string) interface{} {\n\t\/\/ Read-only lock\n\tk.mu.RLock()\n\tdefer k.mu.RUnlock()\n\n\t\/\/ zero value of interface{} is nil so this does what we want\n\treturn k.db[key]\n}\n\n\/\/ Save persists the changes made to disk\n\/\/ If any changes have been written by other code they will be merged\nfunc (k *KeyValueStore) Save() error {\n\tk.mu.Lock()\n\tdefer k.mu.Unlock()\n\n\t\/\/ Short-circuit if we have no changes\n\tif len(k.log) == 0 {\n\t\treturn nil\n\t}\n\n\t\/\/ firstly peek at version; open read\/write to keep lock between check & write\n\tf, err := os.OpenFile(k.filename, os.O_RDWR|os.O_CREATE, 0664)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstat, _ := os.Stat(k.filename)\n\n\tdefer f.Close()\n\n\t\/\/ Only try to merge if > 0 bytes, ignore empty files (decoder will fail)\n\tif stat.Size() > 0 {\n\t\tk.loadAndMergeReaderIfNeeded(f)\n\t\t\/\/ Now we overwrite the file\n\t\tf.Seek(0, os.SEEK_SET)\n\t\tf.Truncate(0)\n\t}\n\n\tk.version++\n\n\tenc := gob.NewEncoder(f)\n\tif err := enc.Encode(k.version); err != nil {\n\t\treturn fmt.Errorf(\"Error while writing version data to %v: %v\", k.filename, err)\n\t}\n\tif err := enc.Encode(k.db); err != nil {\n\t\treturn fmt.Errorf(\"Error while writing new key\/value data to %v: %v\", k.filename, err)\n\t}\n\t\/\/ Clear log now that it's saved\n\tk.log = nil\n\n\treturn nil\n}\n\n\/\/ Reads as little as possible from the passed in file to determine if the\n\/\/ contents are different from the version already held. If so, reads the\n\/\/ contents and merges with any outstanding changes. If not, stops early without\n\/\/ reading the rest of the file\nfunc (k *KeyValueStore) loadAndMergeIfNeeded() error {\n\tstat, err := os.Stat(k.filename)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil \/\/ missing is OK\n\t\t}\n\t\treturn err\n\t}\n\t\/\/ Do nothing if empty file\n\tif stat.Size() == 0 {\n\t\treturn nil\n\t}\n\n\tf, err := os.OpenFile(k.filename, os.O_RDONLY, 0664)\n\tif err == nil {\n\t\tdefer f.Close()\n\t\treturn k.loadAndMergeReaderIfNeeded(f)\n\t} else {\n\t\treturn err\n\t}\n}\n\n\/\/ As loadAndMergeIfNeeded but lets caller decide how to manage file handles\nfunc (k *KeyValueStore) loadAndMergeReaderIfNeeded(f io.Reader) error {\n\tvar versionOnDisk int64\n\t\/\/ Decode *only* the version field to check whether anyone else has\n\t\/\/ modified the db; gob serializes structs in order so it will always be 1st\n\tdec := gob.NewDecoder(f)\n\terr := dec.Decode(&versionOnDisk)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Problem checking version of key\/value data from %v: %v\", k.filename, err)\n\t}\n\t\/\/ Totally uninitialised Version == 0, saved versions are always >=1\n\tif versionOnDisk != k.version {\n\t\t\/\/ Reload data & merge\n\t\tvar dbOnDisk map[string]interface{}\n\t\terr = dec.Decode(&dbOnDisk)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Problem reading updated key\/value data from %v: %v\", k.filename, err)\n\t\t}\n\t\tk.reapplyChanges(dbOnDisk)\n\t\tk.version = versionOnDisk\n\t}\n\treturn nil\n}\n\n\/\/ reapplyChanges replays the changes made since the last load onto baseDb\n\/\/ and stores the result as our own DB\nfunc (k *KeyValueStore) reapplyChanges(baseDb map[string]interface{}) {\n\tfor _, change := range k.log {\n\t\tswitch change.operation {\n\t\tcase keyValueSetOperation:\n\t\t\tbaseDb[change.key] = change.value\n\t\tcase keyValueRemoveOperation:\n\t\t\tdelete(baseDb, change.key)\n\t\t}\n\t}\n\t\/\/ Note, log is not cleared here, that only happens on Save since it's a\n\t\/\/ list of unsaved changes\n\tk.db = baseDb\n\n}\n\n\/\/ RegisterTypeForKeyValueStorage registers a custom type (e.g. a struct) for\n\/\/ use in the key value store. This is necessary if you intend to pass custom\n\/\/ structs to KeyValueStore.Set() rather than primitive types.\nfunc RegisterTypeForKeyValueStorage(val interface{}) {\n\tgob.Register(val)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package hiprus provides a Hipchat hook for the logrus loggin package.\npackage hiprus\n\nimport (\n\t\"net\/url\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/tbruyelle\/hipchat-go\/hipchat\"\n)\n\nconst (\n\tVERSION     = \"2.0.0\"\n\tColorYellow = \"yellow\"\n\tColorRed    = \"red\"\n\tColorGreen  = \"green\"\n\tColorPurple = \"purple\"\n\tColorGray   = \"gray\"\n\tColorRandom = \"random\"\n)\n\n\/\/ HiprusHook is a logrus Hook for dispatching messages to the specified\n\/\/ channel on Hipchat.\ntype HiprusHook struct {\n\t\/\/ Messages with a log level not contained in this array\n\t\/\/ will not be dispatched. If nil, all messages will be dispatched.\n\tAcceptedLevels []logrus.Level\n\tAuthToken      string\n\tRoomName       string\n\t\/\/ If empty, \"Hiprus\" will be used.\n\tUsername string\n\t\/\/ If empty, will point to hipchat cloud\n\tBaseURL string\n\tc       *hipchat.Client\n}\n\nfunc (hh *HiprusHook) Levels() []logrus.Level {\n\tif hh.AcceptedLevels == nil {\n\t\treturn AllLevels\n\t}\n\treturn hh.AcceptedLevels\n}\n\nfunc (hh *HiprusHook) Fire(e *logrus.Entry) error {\n\tif hh.c == nil {\n\t\tif err := hh.initClient(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tcolor := \"\"\n\tnotify := false\n\tswitch e.Level {\n\tcase logrus.DebugLevel:\n\t\tcolor = ColorPurple\n\tcase logrus.InfoLevel:\n\t\tcolor = ColorGreen\n\tcase logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:\n\t\tcolor = ColorRed\n\t\tnotify = true\n\tdefault:\n\t\tcolor = ColorYellow\n\t\tnotify = true\n\t}\n\n\t_, err := hh.c.Room.Notification(hh.RoomName, &hipchat.NotificationRequest{\n\t\tFrom:          hh.Username,\n\t\tMessage:       e.Message,\n\t\tMessageFormat: \"text\",\n\t\tNotify:        notify,\n\t\tColor:         color,\n\t})\n\n\treturn err\n}\n\nfunc (hh *HiprusHook) initClient() error {\n\tc := hipchat.NewClient(hh.AuthToken)\n\n\tif hh.BaseURL != \"\" {\n\t\thipchatUrl, _ := url.Parse(hh.BaseURL)\n\t\tc.BaseURL = hipchatUrl\n\t}\n\n\thh.c = c\n\n\tif hh.Username == \"\" {\n\t\thh.Username = \"HipRus\"\n\t}\n\n\treturn nil\n}\n<commit_msg>Changing color type to hipchat.Color to fix build errors<commit_after>\/\/ Package hiprus provides a Hipchat hook for the logrus loggin package.\npackage hiprus\n\nimport (\n\t\"net\/url\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/tbruyelle\/hipchat-go\/hipchat\"\n)\n\nconst (\n\tVERSION                   = \"2.0.0\"\n\tColorYellow hipchat.Color = \"yellow\"\n\tColorRed    hipchat.Color = \"red\"\n\tColorGreen  hipchat.Color = \"green\"\n\tColorPurple hipchat.Color = \"purple\"\n\tColorGray   hipchat.Color = \"gray\"\n\tColorRandom hipchat.Color = \"random\"\n)\n\n\/\/ HiprusHook is a logrus Hook for dispatching messages to the specified\n\/\/ channel on Hipchat.\ntype HiprusHook struct {\n\t\/\/ Messages with a log level not contained in this array\n\t\/\/ will not be dispatched. If nil, all messages will be dispatched.\n\tAcceptedLevels []logrus.Level\n\tAuthToken      string\n\tRoomName       string\n\t\/\/ If empty, \"Hiprus\" will be used.\n\tUsername string\n\t\/\/ If empty, will point to hipchat cloud\n\tBaseURL string\n\tc       *hipchat.Client\n}\n\nfunc (hh *HiprusHook) Levels() []logrus.Level {\n\tif hh.AcceptedLevels == nil {\n\t\treturn AllLevels\n\t}\n\treturn hh.AcceptedLevels\n}\n\nfunc (hh *HiprusHook) Fire(e *logrus.Entry) error {\n\tif hh.c == nil {\n\t\tif err := hh.initClient(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar color hipchat.Color\n\tnotify := false\n\tswitch e.Level {\n\tcase logrus.DebugLevel:\n\t\tcolor = ColorPurple\n\tcase logrus.InfoLevel:\n\t\tcolor = ColorGreen\n\tcase logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:\n\t\tcolor = ColorRed\n\t\tnotify = true\n\tdefault:\n\t\tcolor = ColorYellow\n\t\tnotify = true\n\t}\n\n\t_, err := hh.c.Room.Notification(hh.RoomName, &hipchat.NotificationRequest{\n\t\tFrom:          hh.Username,\n\t\tMessage:       e.Message,\n\t\tMessageFormat: \"text\",\n\t\tNotify:        notify,\n\t\tColor:         color,\n\t})\n\n\treturn err\n}\n\nfunc (hh *HiprusHook) initClient() error {\n\tc := hipchat.NewClient(hh.AuthToken)\n\n\tif hh.BaseURL != \"\" {\n\t\thipchatUrl, _ := url.Parse(hh.BaseURL)\n\t\tc.BaseURL = hipchatUrl\n\t}\n\n\thh.c = c\n\n\tif hh.Username == \"\" {\n\t\thh.Username = \"HipRus\"\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package transform\n\nimport (\n\t\"mater\/vect\"\n\t\"math\"\n)\n\ntype Rotation struct {\n\t\/\/sine and cosine.\n\tS, C float64\n}\n\nfunc (rot *Rotation) SetIdentity() {\n\trot.S = 0\n\trot.C = 1\n}\n\nfunc (rot *Rotation) SetAngle(angle float64) {\n\trot.C = math.Cos(angle)\n\trot.S = math.Sin(angle)\n}\n\nfunc (rot *Rotation) Angle() float64 {\n\treturn math.Atan2(rot.S, rot.C)\n}\n\nfunc (rot *Rotation) RotateVect(v vect.Vect) vect.Vect {\n\treturn vect.Vect {\n\t\tX: v.X * rot.C - v.Y * rot.S,\n\t\tY: v.X * rot.S + v.Y * rot.C,\n\t}\n}\n\ntype Transform struct {\n\tPosition vect.Vect\n\tRotation\n}\n\nfunc (xf *Transform) SetIdentity() {\n\txf.Position = vect.Vect{}\n\txf.Rotation.SetIdentity()\n}\n\nfunc (xf *Transform) Set(pos vect.Vect, rot float64) {\n\txf.Position = pos\n\txf.SetAngle(rot)\n}\n<commit_msg>added transform.TransformVect<commit_after>package transform\n\nimport (\n\t\"mater\/vect\"\n\t\"math\"\n)\n\ntype Rotation struct {\n\t\/\/sine and cosine.\n\tS, C float64\n}\n\nfunc (rot *Rotation) SetIdentity() {\n\trot.S = 0\n\trot.C = 1\n}\n\nfunc (rot *Rotation) SetAngle(angle float64) {\n\trot.C = math.Cos(angle)\n\trot.S = math.Sin(angle)\n}\n\nfunc (rot *Rotation) Angle() float64 {\n\treturn math.Atan2(rot.S, rot.C)\n}\n\n\/\/rotates the input vector.\nfunc (rot *Rotation) RotateVect(v vect.Vect) vect.Vect {\n\treturn vect.Vect {\n\t\tX: v.X * rot.C - v.Y * rot.S,\n\t\tY: v.X * rot.S + v.Y * rot.C,\n\t}\n}\n\ntype Transform struct {\n\tPosition vect.Vect\n\tRotation\n}\n\nfunc (xf *Transform) SetIdentity() {\n\txf.Position = vect.Vect{}\n\txf.Rotation.SetIdentity()\n}\n\nfunc (xf *Transform) Set(pos vect.Vect, rot float64) {\n\txf.Position = pos\n\txf.SetAngle(rot)\n}\n\n\/\/moves and roates the input vector.\nfunc (xf *Transform) TransformVect(v vect.Vect) vect.Vect {\n\treturn vect.Add(xf.Position, xf.RotateVect(v))\n}<|endoftext|>"}
{"text":"<commit_before>package honoka\n\nimport (\n    \"crypto\/sha256\"\n    \"encoding\/hex\"\n    \"encoding\/json\"\n    \"errors\"\n    \"io\/ioutil\"\n    \"os\"\n    \"path\/filepath\"\n    \"strconv\"\n    \"time\"\n\n    homedir \"github.com\/mitchellh\/go-homedir\"\n    \"github.com\/mitchellh\/mapstructure\"\n\n    \/\/ for Debug\n    \/\/ \"fmt\"\n    \/\/ \"github.com\/davecgh\/go-spew\/spew\"\n)\n\n\/\/ Cache client\ntype Client struct {\n    \/\/ Cache Index list\n    Indexer IndexList\n}\n\n\/\/ Cache index list\ntype IndexList map[string]Index\n\n\/\/ Cache index\ntype Index struct {\n    \/\/ The index key.\n    Key        string\n\n    \/\/ The bucket name that saved cache data.\n    Bucket     string\n\n    \/\/ The maximum elapsed time since the last file update.\n    Expiration int64\n}\n\n\/\/ The structure is used when use clean method.\ntype CleanResult struct {\n    \/\/ The bucket name that saved cache data.\n    Bucket string\n\n    \/\/ Error when delete the specified bucket.\n    Error  error\n}\n\ntype UpdateFunc func() (interface{}, error)\n\nvar (\n    Version = \"0.0.1\"\n    BucketFileNotFound = errors.New(\"Not found specified bucket file\")\n    IndexFileNotFound  = errors.New(\"Not found specified index file\")\n    CacheIsExpired     = errors.New(\"specified cache is expired\")\n)\n\n\/\/ New is a function for making a new cache\nfunc New() (*Client, error) {\n    idx, err := getIndexList()\n    if err != nil {\n        if err == IndexFileNotFound {\n            idx = nil\n        } else {\n            return nil, err\n        }\n    }\n\n    c := &Client{\n        Indexer: idx,\n    }\n    return c, nil\n}\n\n\/\/ Get is used to retrieve a cache by specified key.\n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   var output interface{}\n\/\/   cli.Get(\"foobar\", &output)\n\/\/   \/\/ OR\n\/\/   result, err := cli.Get(\"foobar\", &output)\nfunc (c *Client) Get(key string, output interface{}) (interface{}, error) {\n    if c.Expire(key) {\n        return nil, CacheIsExpired\n    }\n    cache, err := c.GetJson(key)\n    if err != nil {\n        return nil, err\n    }\n    var result interface{}\n    err = json.Unmarshal(cache, &result)\n    if err != nil {\n        return nil, err\n    }\n    err = mapstructure.WeakDecode(result, &output);\n    return &output, err\n}\n\n\/\/ Get is used to retrieve a cache by specified key.\n\/\/ Return value is JSON string\n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   result, err := cli.GetJson(\"foobar\")\nfunc (c *Client) GetJson(key string) ([]byte, error) {\n    if c.Expire(key) {\n        return nil, CacheIsExpired\n    }\n\n    idx := c.Indexer[key]\n    cache, err := getCacheFromBucket(idx.Bucket)\n    if err != nil {\n        return nil, err\n    }\n    return cache, nil\n}\n\n\/\/ Get is used to create a cache if specified key has not used yet.\n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   err := cli.Set(\"foobar\", \"fizzbizz\", 100)\nfunc (c *Client) Set(key string, val interface{}, expire int64) error {\n    if ! c.Expire(key) {\n        return nil\n    }\n\n    exp := createExpiration(expire)\n    name := getBucketName(key, exp)\n    _, err := createNewBucket(name, val)\n    if err != nil {\n        return err\n    }\n    var idx IndexList\n    idx, err = getIndexList()\n    if err != nil {\n        if (err == IndexFileNotFound) {\n            idx = map[string]Index{}\n        } else {\n            return err\n        }\n    }\n\n    idx[key] = Index{\n        Key:        key,\n        Bucket:     name,\n        Expiration: exp,\n    }\n    c.setIndexer(idx)\n\n    return nil\n}\n\n\/\/ Update calls the cache update function on the cached data.\n\/\/ Get is used to retrieve a cache by specified key.\n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   var output interface{}\n\/\/   f := func() { return \"fizzbizz\" }\n\/\/   cli.Update(\"foobar\", f, 100, &output)\n\/\/   \/\/ OR\n\/\/   result, err := cli.Get(\"foobar\", f, 100, &output)\nfunc (c *Client) Update(key string, updater UpdateFunc, expire int64, output interface{}) (interface{}, error) {\n    b, err := c.UpdateJson(key, updater, expire)\n    if b != nil {\n        var result interface{}\n        e := json.Unmarshal(b, &result)\n        if e != nil {\n            return nil, e\n        }\n\n        e = mapstructure.WeakDecode(result, &output);\n        if e != nil {\n            return nil, e\n        }\n    }\n\n    return output, err\n}\n\n\/\/ Update calls the cache update function on the cached data.\n\/\/ Return value is JSON string.\n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   f := func() { return \"fizzbizz\" }\n\/\/   result, err := cli.UpdateJson(\"foobar\", f, 100)\nfunc (c *Client) UpdateJson(key string, updater UpdateFunc, expire int64) ([]byte, error) {\n    if ! c.Expire(key) {\n        return c.GetJson(key)\n    }\n\n    val, err := updater()\n    if err != nil {\n        return nil, err\n    }\n\n    exp := createExpiration(expire)\n    name := getBucketName(key, exp)\n    jval, err := createNewBucket(name, val)\n    if err != nil {\n        return jval, err\n    }\n    var idx IndexList\n    idx, err = getIndexList()\n    if err != nil {\n        idx = c.Indexer\n    }\n\n    idx[key] = Index{\n        Key:        key,\n        Bucket:     name,\n        Expiration: exp,\n    }\n    c.setIndexer(idx)\n\n    return jval, nil\n}\n\n\/\/ Delete is used to delete a cache by specified key.\n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   err = cli.Delete(\"foobar\")\nfunc (c *Client) Delete(key string) error {\n    idx := c.Indexer[key]\n    path, err := getBucketPath(idx.Bucket)\n    if err != nil {\n        return err\n    }\n    if fileExists(path) {\n        err = os.Remove(path)\n        if err != nil {\n            return err\n        }\n    }\n\n    delete(c.Indexer, key)\n    c.setIndexer(c.Indexer)\n    return nil\n}\n\n\/\/ Expire is a predicate which determines if the cache should be updated.\n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   expired := cli.Expire(\"foobar\")\nfunc (c *Client) Expire(key string) bool {\n    if nil == c.Indexer {\n        return true\n    }\n\n    idx, exists := c.Indexer[key]\n    if exists {\n        if idx.Expiration <= time.Now().Unix() {\n            c.Delete(key)\n            return true\n        } else {\n            return false\n        }\n    }\n    return true\n}\n\n\/\/ Outdated is used to retrive no-indexed bucket.\n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   list, err := cli.Outdated()\nfunc (c *Client) Outdated() ([]string, error) {\n    idx, err := c.getIndexer(true)\n    if err != nil {\n        return nil, err\n    }\n    currents := make(map[string]string)\n    for _, i := range idx {\n        currents[i.Bucket] = \"\"\n    }\n\n    var list []string\n    buckets, err := getBucketList()\n    if err != nil {\n        return nil, err\n    }\n    for _, bucket := range buckets {\n        if _, exists := currents[bucket]; !exists {\n            list = append(list, bucket)\n        }\n    }\n    return list, nil\n}\n\n\/\/ Clean is used to delete no-indexed bucket.\n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   result, err := cli.Clean()\nfunc (c *Client) Clean() ([]CleanResult, error) {\n    bucketsDir, err := getBucketsDirPath()\n    if err != nil {\n        return nil, err\n    }\n    list, err := c.Outdated()\n    if err != nil {\n        return nil, err\n    }\n\n    var result []CleanResult\n    for _, bucket := range list {\n        e := os.Remove(filepath.Join(bucketsDir, bucket))\n        r := CleanResult{\n            Bucket: bucket,\n            Error:  e,\n        }\n        result = append(result, r)\n    }\n    return result, nil\n}\n\n\/\/ List is used to retrive cache indexes.\n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   list, err := cli.List()\nfunc (c *Client) List() ([]Index, error) {\n    idx, err := c.getIndexer(true)\n    if err != nil {\n        return nil, err\n    }\n    var list []Index\n    for _, i := range idx {\n        list = append(list, i)\n    }\n    \n    return list, nil  \n}\n\nfunc (c *Client) getIndexer(replace bool) (IndexList, error) {\n    if replace || c.Indexer == nil {\n        idx, err := getIndexList()\n        if err != nil {\n            return nil, err\n        }\n        c.Indexer = idx\n    }\n    return c.Indexer, nil\n}\n\nfunc (c *Client) setIndexer(indexes IndexList) error {\n    idx, err := json.Marshal(indexes)\n    if err != nil {\n        return err\n    }\n\n    if err = updateIndexFile(idx); err != nil {\n        return err\n    }\n    c.Indexer = indexes\n    return nil\n}\n\nfunc getBucketsDirPath() (string, error) {\n    home, err := homedir.Dir()\n    if err != nil {\n        return \"\", err\n    }\n    bucketsDir := filepath.Join(home, \".honoka\", \"buckets\")\n    os.MkdirAll(bucketsDir, 0700)\n    return bucketsDir, err\n}\n\nfunc getBucketPath(bucketName string) (string, error) {\n    bucketsDir, err := getBucketsDirPath()\n    if err != nil {\n        return \"\", err\n    }\n    return filepath.Join(bucketsDir, bucketName), nil\n}\n\nfunc getCacheFromBucket(bucketName string) ([]byte, error) {\n    path, err := getBucketPath(bucketName)\n    if err != nil {\n        return nil, err\n    }\n    if !fileExists(path) {\n        return nil, BucketFileNotFound\n    }\n    return ioutil.ReadFile(path);\n}\n\nfunc getBucketList() ([]string, error) {\n    bucketsDir, err := getBucketsDirPath()\n    if err != nil {\n        return nil, err\n    }\n    files, err := ioutil.ReadDir(bucketsDir)\n    var list []string\n    for _, fi := range files {\n        if !fi.IsDir() {\n            filename := fi.Name()\n            list = append(list, filename)\n        }\n    }\n    return list, nil\n}\n\nfunc createNewBucket(name string, val interface{}) ([]byte, error) {\n    jval, err := json.Marshal(val)\n    if err != nil {\n        return nil, err\n    }\n    path, err := getBucketPath(name)\n    if err != nil {\n        return jval, err\n    }\n    err = ioutil.WriteFile(path, jval, 0644)\n    return jval, err\n}\n\nfunc getBucketName(key string, expiration int64) string {\n    k := key + \".\" + strconv.FormatInt(expiration, 10)\n    bytes := sha256.Sum256([]byte(k))\n    return hex.EncodeToString(bytes[:])\n}\n\nfunc getIndexPath() (string, error) {\n    home, err := homedir.Dir()\n    if err != nil {\n        return \"\", err\n    }\n    indexDir := filepath.Join(home, \".honoka\")\n    os.MkdirAll(indexDir, 0700)\n    return filepath.Join(indexDir, \"index\"), err\n}\n\nfunc getIndexList() (IndexList, error) {\n    b, err := getIndexFromFile()\n    if err != nil {\n        return nil, err\n    }\n    var list IndexList\n    err = json.Unmarshal(b, &list)\n    if  err != nil {\n        return nil, err\n    }\n    return list, nil\n}\n\nfunc getIndexFromFile() ([]byte, error) {\n    path, err := getIndexPath()\n    if err != nil {\n        return nil, err\n    }\n    if !fileExists(path) {\n        return nil, IndexFileNotFound\n    }\n    return ioutil.ReadFile(path);\n}\n\nfunc updateIndexFile(indexes []byte) error {\n    path, err := getIndexPath()\n    if err != nil {\n        return err\n    }\n    return ioutil.WriteFile(path, indexes, 0644);\n}\n\nfunc fileExists(filename string) bool {\n    _, err := os.Stat(filename)\n    return err == nil\n}\n\nfunc createExpiration(expire int64) int64 {\n    return time.Now().Unix() + expire\n}\n<commit_msg>fix godoc<commit_after>package honoka\n\nimport (\n    \"crypto\/sha256\"\n    \"encoding\/hex\"\n    \"encoding\/json\"\n    \"errors\"\n    \"io\/ioutil\"\n    \"os\"\n    \"path\/filepath\"\n    \"strconv\"\n    \"time\"\n\n    homedir \"github.com\/mitchellh\/go-homedir\"\n    \"github.com\/mitchellh\/mapstructure\"\n\n    \/\/ for Debug\n    \/\/ \"fmt\"\n    \/\/ \"github.com\/davecgh\/go-spew\/spew\"\n)\n\n\/\/ Cache client\ntype Client struct {\n    \/\/ Cache Index list\n    Indexer IndexList\n}\n\n\/\/ Cache index list\ntype IndexList map[string]Index\n\n\/\/ Cache index\ntype Index struct {\n    \/\/ The index key.\n    Key        string\n\n    \/\/ The bucket name that saved cache data.\n    Bucket     string\n\n    \/\/ The maximum elapsed time since the last file update.\n    Expiration int64\n}\n\n\/\/ The structure is used when use clean method.\ntype CleanResult struct {\n    \/\/ The bucket name that saved cache data.\n    Bucket string\n\n    \/\/ Error when delete the specified bucket.\n    Error  error\n}\n\ntype UpdateFunc func() (interface{}, error)\n\nvar (\n    Version = \"0.0.1\"\n    BucketFileNotFound = errors.New(\"Not found specified bucket file\")\n    IndexFileNotFound  = errors.New(\"Not found specified index file\")\n    CacheIsExpired     = errors.New(\"specified cache is expired\")\n)\n\n\/\/ New is a function for making a new cache\nfunc New() (*Client, error) {\n    idx, err := getIndexList()\n    if err != nil {\n        if err == IndexFileNotFound {\n            idx = nil\n        } else {\n            return nil, err\n        }\n    }\n\n    c := &Client{\n        Indexer: idx,\n    }\n    return c, nil\n}\n\n\/\/ Get is used to retrieve a cache by specified key.\n\/\/ \n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   var output interface{}\n\/\/   cli.Get(\"foobar\", &output)\n\/\/   \/\/ OR\n\/\/   result, err := cli.Get(\"foobar\", &output)\nfunc (c *Client) Get(key string, output interface{}) (interface{}, error) {\n    if c.Expire(key) {\n        return nil, CacheIsExpired\n    }\n    cache, err := c.GetJson(key)\n    if err != nil {\n        return nil, err\n    }\n    var result interface{}\n    err = json.Unmarshal(cache, &result)\n    if err != nil {\n        return nil, err\n    }\n    err = mapstructure.WeakDecode(result, &output);\n    return &output, err\n}\n\n\/\/ Get is used to retrieve a cache by specified key.\n\/\/ Return value is JSON string\n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   result, err := cli.GetJson(\"foobar\")\nfunc (c *Client) GetJson(key string) ([]byte, error) {\n    if c.Expire(key) {\n        return nil, CacheIsExpired\n    }\n\n    idx := c.Indexer[key]\n    cache, err := getCacheFromBucket(idx.Bucket)\n    if err != nil {\n        return nil, err\n    }\n    return cache, nil\n}\n\n\/\/ Get is used to create a cache if specified key has not used yet.\n\/\/ \n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   err := cli.Set(\"foobar\", \"fizzbizz\", 100)\nfunc (c *Client) Set(key string, val interface{}, expire int64) error {\n    if ! c.Expire(key) {\n        return nil\n    }\n\n    exp := createExpiration(expire)\n    name := getBucketName(key, exp)\n    _, err := createNewBucket(name, val)\n    if err != nil {\n        return err\n    }\n    var idx IndexList\n    idx, err = getIndexList()\n    if err != nil {\n        if (err == IndexFileNotFound) {\n            idx = map[string]Index{}\n        } else {\n            return err\n        }\n    }\n\n    idx[key] = Index{\n        Key:        key,\n        Bucket:     name,\n        Expiration: exp,\n    }\n    c.setIndexer(idx)\n\n    return nil\n}\n\n\/\/ Update calls the cache update function on the cached data.\n\/\/ Get is used to retrieve a cache by specified key.\n\/\/ \n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   var output interface{}\n\/\/   f := func() { return \"fizzbizz\" }\n\/\/   cli.Update(\"foobar\", f, 100, &output)\n\/\/   \/\/ OR\n\/\/   result, err := cli.Get(\"foobar\", f, 100, &output)\nfunc (c *Client) Update(key string, updater UpdateFunc, expire int64, output interface{}) (interface{}, error) {\n    b, err := c.UpdateJson(key, updater, expire)\n    if b != nil {\n        var result interface{}\n        e := json.Unmarshal(b, &result)\n        if e != nil {\n            return nil, e\n        }\n\n        e = mapstructure.WeakDecode(result, &output);\n        if e != nil {\n            return nil, e\n        }\n    }\n\n    return output, err\n}\n\n\/\/ Update calls the cache update function on the cached data.\n\/\/ Return value is JSON string.\n\/\/ \n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   f := func() { return \"fizzbizz\" }\n\/\/   result, err := cli.UpdateJson(\"foobar\", f, 100)\nfunc (c *Client) UpdateJson(key string, updater UpdateFunc, expire int64) ([]byte, error) {\n    if ! c.Expire(key) {\n        return c.GetJson(key)\n    }\n\n    val, err := updater()\n    if err != nil {\n        return nil, err\n    }\n\n    exp := createExpiration(expire)\n    name := getBucketName(key, exp)\n    jval, err := createNewBucket(name, val)\n    if err != nil {\n        return jval, err\n    }\n    var idx IndexList\n    idx, err = getIndexList()\n    if err != nil {\n        idx = c.Indexer\n    }\n\n    idx[key] = Index{\n        Key:        key,\n        Bucket:     name,\n        Expiration: exp,\n    }\n    c.setIndexer(idx)\n\n    return jval, nil\n}\n\n\/\/ Delete is used to delete a cache by specified key.\n\/\/ \n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   err = cli.Delete(\"foobar\")\nfunc (c *Client) Delete(key string) error {\n    idx := c.Indexer[key]\n    path, err := getBucketPath(idx.Bucket)\n    if err != nil {\n        return err\n    }\n    if fileExists(path) {\n        err = os.Remove(path)\n        if err != nil {\n            return err\n        }\n    }\n\n    delete(c.Indexer, key)\n    c.setIndexer(c.Indexer)\n    return nil\n}\n\n\/\/ Expire is a predicate which determines if the cache should be updated.\n\/\/ \n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   expired := cli.Expire(\"foobar\")\nfunc (c *Client) Expire(key string) bool {\n    if nil == c.Indexer {\n        return true\n    }\n\n    idx, exists := c.Indexer[key]\n    if exists {\n        if idx.Expiration <= time.Now().Unix() {\n            c.Delete(key)\n            return true\n        } else {\n            return false\n        }\n    }\n    return true\n}\n\n\/\/ Outdated is used to retrive no-indexed bucket.\n\/\/ \n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   list, err := cli.Outdated()\nfunc (c *Client) Outdated() ([]string, error) {\n    idx, err := c.getIndexer(true)\n    if err != nil {\n        return nil, err\n    }\n    currents := make(map[string]string)\n    for _, i := range idx {\n        currents[i.Bucket] = \"\"\n    }\n\n    var list []string\n    buckets, err := getBucketList()\n    if err != nil {\n        return nil, err\n    }\n    for _, bucket := range buckets {\n        if _, exists := currents[bucket]; !exists {\n            list = append(list, bucket)\n        }\n    }\n    return list, nil\n}\n\n\/\/ Clean is used to delete no-indexed bucket.\n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   result, err := cli.Clean()\nfunc (c *Client) Clean() ([]CleanResult, error) {\n    bucketsDir, err := getBucketsDirPath()\n    if err != nil {\n        return nil, err\n    }\n    list, err := c.Outdated()\n    if err != nil {\n        return nil, err\n    }\n\n    var result []CleanResult\n    for _, bucket := range list {\n        e := os.Remove(filepath.Join(bucketsDir, bucket))\n        r := CleanResult{\n            Bucket: bucket,\n            Error:  e,\n        }\n        result = append(result, r)\n    }\n    return result, nil\n}\n\n\/\/ List is used to retrive cache indexes.\n\/\/ \n\/\/ Example:\n\/\/   cli, err := honoka.New()\n\/\/   list, err := cli.List()\nfunc (c *Client) List() ([]Index, error) {\n    idx, err := c.getIndexer(true)\n    if err != nil {\n        return nil, err\n    }\n    var list []Index\n    for _, i := range idx {\n        list = append(list, i)\n    }\n    \n    return list, nil  \n}\n\nfunc (c *Client) getIndexer(replace bool) (IndexList, error) {\n    if replace || c.Indexer == nil {\n        idx, err := getIndexList()\n        if err != nil {\n            return nil, err\n        }\n        c.Indexer = idx\n    }\n    return c.Indexer, nil\n}\n\nfunc (c *Client) setIndexer(indexes IndexList) error {\n    idx, err := json.Marshal(indexes)\n    if err != nil {\n        return err\n    }\n\n    if err = updateIndexFile(idx); err != nil {\n        return err\n    }\n    c.Indexer = indexes\n    return nil\n}\n\nfunc getBucketsDirPath() (string, error) {\n    home, err := homedir.Dir()\n    if err != nil {\n        return \"\", err\n    }\n    bucketsDir := filepath.Join(home, \".honoka\", \"buckets\")\n    os.MkdirAll(bucketsDir, 0700)\n    return bucketsDir, err\n}\n\nfunc getBucketPath(bucketName string) (string, error) {\n    bucketsDir, err := getBucketsDirPath()\n    if err != nil {\n        return \"\", err\n    }\n    return filepath.Join(bucketsDir, bucketName), nil\n}\n\nfunc getCacheFromBucket(bucketName string) ([]byte, error) {\n    path, err := getBucketPath(bucketName)\n    if err != nil {\n        return nil, err\n    }\n    if !fileExists(path) {\n        return nil, BucketFileNotFound\n    }\n    return ioutil.ReadFile(path);\n}\n\nfunc getBucketList() ([]string, error) {\n    bucketsDir, err := getBucketsDirPath()\n    if err != nil {\n        return nil, err\n    }\n    files, err := ioutil.ReadDir(bucketsDir)\n    var list []string\n    for _, fi := range files {\n        if !fi.IsDir() {\n            filename := fi.Name()\n            list = append(list, filename)\n        }\n    }\n    return list, nil\n}\n\nfunc createNewBucket(name string, val interface{}) ([]byte, error) {\n    jval, err := json.Marshal(val)\n    if err != nil {\n        return nil, err\n    }\n    path, err := getBucketPath(name)\n    if err != nil {\n        return jval, err\n    }\n    err = ioutil.WriteFile(path, jval, 0644)\n    return jval, err\n}\n\nfunc getBucketName(key string, expiration int64) string {\n    k := key + \".\" + strconv.FormatInt(expiration, 10)\n    bytes := sha256.Sum256([]byte(k))\n    return hex.EncodeToString(bytes[:])\n}\n\nfunc getIndexPath() (string, error) {\n    home, err := homedir.Dir()\n    if err != nil {\n        return \"\", err\n    }\n    indexDir := filepath.Join(home, \".honoka\")\n    os.MkdirAll(indexDir, 0700)\n    return filepath.Join(indexDir, \"index\"), err\n}\n\nfunc getIndexList() (IndexList, error) {\n    b, err := getIndexFromFile()\n    if err != nil {\n        return nil, err\n    }\n    var list IndexList\n    err = json.Unmarshal(b, &list)\n    if  err != nil {\n        return nil, err\n    }\n    return list, nil\n}\n\nfunc getIndexFromFile() ([]byte, error) {\n    path, err := getIndexPath()\n    if err != nil {\n        return nil, err\n    }\n    if !fileExists(path) {\n        return nil, IndexFileNotFound\n    }\n    return ioutil.ReadFile(path);\n}\n\nfunc updateIndexFile(indexes []byte) error {\n    path, err := getIndexPath()\n    if err != nil {\n        return err\n    }\n    return ioutil.WriteFile(path, indexes, 0644);\n}\n\nfunc fileExists(filename string) bool {\n    _, err := os.Stat(filename)\n    return err == nil\n}\n\nfunc createExpiration(expire int64) int64 {\n    return time.Now().Unix() + expire\n}\n<|endoftext|>"}
{"text":"<commit_before>package check\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tkafka \"github.com\/Shopify\/sarama\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/samuel\/go-zookeeper\/zk\"\n)\n\nfunc (check *HealthCheck) connect(firstConnection bool, stop <-chan struct{}) error {\n\tvar createHealthTopicIfMissing = firstConnection\n\tvar createReplicationTopicIfMissing = firstConnection\n\tticker := time.NewTicker(check.config.retryInterval)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif err := check.tryConnectOnce(&createHealthTopicIfMissing, &createReplicationTopicIfMissing); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase <-stop:\n\t\t\treturn errors.New(\"connect was asked to stop\")\n\t\t}\n\t}\n}\n\nfunc (check *HealthCheck) tryConnectOnce(createBrokerTopic, createReplicationTopic *bool) error {\n\tpauseTime := check.config.retryInterval\n\t\/\/ connect to kafka cluster\n\tconnectString := fmt.Sprintf(\"localhost:%d\", check.config.brokerPort)\n\terr := check.broker.Dial(connectString, check.brokerConfig())\n\tif err != nil {\n\t\tlog.Printf(\"unable to connect to broker, retrying in %s (%s)\", pauseTime.String(), err)\n\t\treturn err\n\t}\n\n\tmetadata, err := check.broker.Metadata()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failure retrieving metadata\")\n\t}\n\n\tcheck.partitionID, err = check.findPartitionID(check.config.topicName, true, createBrokerTopic, metadata)\n\tif err != nil {\n\t\tlog.Printf(\"%s retrying in %s\", err.Error(), pauseTime)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tcheck.replicationPartitionID, err = check.findPartitionID(check.config.replicationTopicName, false, createReplicationTopic, metadata)\n\tif err != nil {\n\t\tlog.Printf(\"%s retrying in %s\", err.Error(), pauseTime)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tconsumer, err := check.broker.Consumer(check.consumerConfig())\n\tif err != nil {\n\t\tlog.Printf(\"unable to create consumer, retrying in %s: %s\", pauseTime.String(), err)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tproducer, err := check.broker.Producer(check.producerConfig())\n\tif err != nil {\n\t\tlog.Printf(\"unable to create producer, retrying in %s: %s\", pauseTime.String(), err)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tcheck.consumer = consumer\n\tcheck.producer = producer\n\treturn nil\n}\n\nfunc (check *HealthCheck) findPartitionID(topicName string, forHealthCheck bool, createIfMissing *bool, metadata *kafka.MetadataResponse) (int32, error) {\n\tbrokerID := int32(check.config.brokerID)\n\n\tif !brokerExists(brokerID, metadata) {\n\t\treturn 0, fmt.Errorf(\"unable to find broker %d in metadata\", brokerID)\n\t}\n\n\ttopic, ok := findTopic(topicName, metadata)\n\n\tif ok {\n\t\tfor _, partition := range topic.Partitions {\n\t\t\tif forHealthCheck && partition.Leader != brokerID {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !contains(partition.Replicas, brokerID) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlog.Printf(`found partition id %d for broker %d in topic \"%s\"`, partition.ID, brokerID, topicName)\n\t\t\treturn partition.ID, nil\n\t\t}\n\t}\n\n\tif *createIfMissing {\n\t\terr := check.createTopic(topicName, forHealthCheck)\n\t\tif err != nil {\n\t\t\treturn 0, errors.Wrapf(err, `unable to create topic \"%s\"`, topicName)\n\t\t}\n\t\tlog.Printf(`topic \"%s\" created`, topicName)\n\t\t*createIfMissing = false\n\t\treturn 0, errors.New(\"topic created, try again\")\n\t}\n\n\tif ok {\n\t\treturn 0, fmt.Errorf(`Unable to find broker's parition in topic \"%s\" in metadata`, topicName)\n\t}\n\treturn 0, fmt.Errorf(`Unable to find broker's topic \"%s\" in metadata`, topicName)\n}\n\nfunc findTopic(name string, metadata *kafka.MetadataResponse) (*kafka.TopicMetadata, bool) {\n\tfor _, topic := range metadata.Topics {\n\t\tif topic.Name == name {\n\t\t\treturn topic, true\n\t\t}\n\t}\n\n\treturn nil, false\n}\n\nfunc brokerExists(brokerID int32, metadata *kafka.MetadataResponse) bool {\n\tfor _, broker := range metadata.Brokers {\n\t\tif broker.ID() == brokerID {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc zookeeperEnsembleAndChroot(connectString string) (ensemble []string, chroot string) {\n\tresult := strings.Split(connectString, \"\/\")\n\tswitch len(result) {\n\tcase 1:\n\t\tensemble = strings.Split(result[0], \",\")\n\t\tchroot = \"\"\n\tdefault:\n\t\tensemble = strings.Split(result[0], \",\")\n\t\tchroot = \"\/\" + strings.Join(result[1:], \"\/\")\n\t\tif strings.HasSuffix(chroot, \"\/\") {\n\t\t\tchroot = chroot[:len(chroot)-1]\n\t\t}\n\t}\n\treturn\n}\n\nfunc (check *HealthCheck) createTopic(name string, forHealthCheck bool) (err error) {\n\tlog.Printf(\"connecting to ZooKeeper ensemble %s\", check.config.zookeeperConnect)\n\tconnectString, chroot := zookeeperEnsembleAndChroot(check.config.zookeeperConnect)\n\tzkConn := check.zookeeper\n\n\tif _, err = zkConn.Connect(connectString, 10*time.Second); err != nil {\n\t\treturn\n\t}\n\tdefer zkConn.Close()\n\n\ttopicPath := chroot + \"\/config\/topics\/\" + name\n\n\texists := false\n\tif !forHealthCheck {\n\t\texists, _, err = zkConn.Exists(topicPath)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tbrokerID := int32(check.config.brokerID)\n\n\tif !exists {\n\t\ttopicConfig := `{\"version\":1,\"config\":{\"delete.retention.ms\":\"10000\",` +\n\t\t\t`\"cleanup.policy\":\"delete\",\"compression.type\":\"uncompressed\"}}`\n\t\tlog.Infof(`creating topic \"%s\" configuration node`, name)\n\n\t\tif err = createZkNode(zkConn, topicPath, topicConfig, forHealthCheck); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tpartitionAssignment := fmt.Sprintf(`{\"version\":1,\"partitions\":{\"0\":[%d]}}`, brokerID)\n\t\tlog.Infof(`creating topic \"%s\" partition assignment node`, name)\n\n\t\tif err = createZkNode(zkConn, chroot+\"\/brokers\/topics\/\"+name, partitionAssignment, forHealthCheck); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif !forHealthCheck {\n\t\terr = maybeExpandReplicationTopic(zkConn, brokerID, check.replicationPartitionID, name, chroot)\n\t}\n\n\treturn\n\n}\n\nfunc maybeExpandReplicationTopic(zk ZkConnection, brokerID, partitionID int32, topicName, chroot string) error {\n\ttopic := ZkTopic{Name: topicName}\n\terr := zkPartitions(&topic, zk, topicName, chroot)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Unable to determine if replication topic should be expanded\")\n\t}\n\n\treplicas, ok := topic.Partitions[strconv.Itoa(int(partitionID))]\n\tif !ok {\n\t\treturn fmt.Errorf(`Cannot find partition with ID %d in topic \"%s\"`, partitionID, topicName)\n\t}\n\n\tif !contains(replicas, brokerID) {\n\t\tlog.Info(\"Expanding replication check topic to include broker \", brokerID)\n\t\treplicas = append(replicas, brokerID)\n\n\t\treturn reassignPartition(zk, partitionID, replicas, topicName, chroot)\n\t}\n\treturn nil\n}\n\nfunc reassignPartition(zk ZkConnection, partitionID int32, replicas []int32, topicName, chroot string) (err error) {\n\n\trepeat := true\n\tfor repeat {\n\t\ttime.Sleep(1 * time.Second)\n\t\texists, _, rpErr := zk.Exists(chroot + \"\/admin\/reassign_partitions\")\n\t\tif rpErr != nil {\n\t\t\tlog.Warn(\"Error while checking if reassign_partitions node exists\", rpErr)\n\t\t}\n\t\trepeat = exists || rpErr != nil\n\t}\n\n\tvar replicasStr []string\n\tfor _, ID := range replicas {\n\t\treplicasStr = append(replicasStr, fmt.Sprintf(\"%d\", ID))\n\t}\n\n\treassign := fmt.Sprintf(`{\"version\":1,\"partitions\":[{\"topic\":\"%s\",\"partition\":%d,\"replicas\":[%s]}]}`,\n\t\ttopicName, partitionID, strings.Join(replicasStr, \",\"))\n\n\trepeat = true\n\tfor repeat {\n\t\tlog.Info(\"Creating reassign partition node\")\n\t\terr = createZkNode(zk, chroot+\"\/admin\/reassign_partitions\", reassign, true)\n\t\tif err != nil {\n\t\t\tlog.Warn(\"Error while creating reassignment node\", err)\n\t\t}\n\t\trepeat = err != nil\n\t}\n\n\treturn\n}\n\nfunc createZkNode(zookeeper ZkConnection, path string, content string, failIfExists bool) error {\n\tnodeExists, _, err := zookeeper.Exists(path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif nodeExists {\n\t\tif failIfExists {\n\t\t\treturn fmt.Errorf(\"node %s cannot be created, exists already\", path)\n\t\t}\n\t\treturn nil\n\t}\n\n\tlog.Println(\"creating node\", path)\n\tflags := int32(0) \/\/ permanent node.\n\tacl := zk.WorldACL(zk.PermAll)\n\t_, err = zookeeper.Create(path, []byte(content), flags, acl)\n\treturn err\n}\n\nfunc (check *HealthCheck) closeConnection(deleteTopicIfPresent bool) {\n\tif deleteTopicIfPresent {\n\t\tlog.Infof(\"connecting to ZooKeeper ensemble %s\", check.config.zookeeperConnect)\n\t\tconnectString, chroot := zookeeperEnsembleAndChroot(check.config.zookeeperConnect)\n\n\t\tzkConn := check.zookeeper\n\t\t_, err := zkConn.Connect(connectString, 10*time.Second)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdefer zkConn.Close()\n\n\t\tcheck.deleteTopic(zkConn, chroot, check.config.topicName, check.partitionID)\n\t\tcheck.deleteTopic(zkConn, chroot, check.config.replicationTopicName, check.replicationPartitionID)\n\t}\n\tcheck.broker.Close()\n}\n\nfunc (check *HealthCheck) deleteTopic(zkConn ZkConnection, chroot, name string, partitionID int32) error {\n\ttopic := ZkTopic{Name: name}\n\terr := zkPartitions(&topic, zkConn, name, chroot)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treplicas, ok := topic.Partitions[strconv.Itoa(int(partitionID))]\n\tif !ok {\n\t\treturn fmt.Errorf(`Cannot find partition with ID %d in topic \"%s\"`, partitionID, name)\n\t}\n\n\tbrokerID := int32(check.config.brokerID)\n\tif len(replicas) > 1 {\n\t\tlog.Info(\"Shrinking replication check topic to exclude broker \", brokerID)\n\t\treplicas = delAll(replicas, brokerID)\n\t\treturn reassignPartition(zkConn, partitionID, replicas, name, chroot)\n\t}\n\n\tdelTopicPath := chroot + \"\/admin\/delete_topics\/\" + name\n\n\terr = createZkNode(check.zookeeper, delTopicPath, \"\", true)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn check.waitForTopicDeletion(delTopicPath)\n}\n\nfunc (check *HealthCheck) waitForTopicDeletion(topicPath string) error {\n\tfor {\n\t\texists, _, err := check.zookeeper.Exists(topicPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !exists {\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(check.config.retryInterval)\n\t}\n}\n\nfunc (check *HealthCheck) reconnect(stop <-chan struct{}) error {\n\tcheck.closeConnection(false)\n\treturn check.connect(false, stop)\n}\n<commit_msg>Don't fail if topic exists<commit_after>package check\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tkafka \"github.com\/Shopify\/sarama\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/samuel\/go-zookeeper\/zk\"\n)\n\nfunc (check *HealthCheck) connect(firstConnection bool, stop <-chan struct{}) error {\n\tvar createHealthTopicIfMissing = firstConnection\n\tvar createReplicationTopicIfMissing = firstConnection\n\tticker := time.NewTicker(check.config.retryInterval)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif err := check.tryConnectOnce(&createHealthTopicIfMissing, &createReplicationTopicIfMissing); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase <-stop:\n\t\t\treturn errors.New(\"connect was asked to stop\")\n\t\t}\n\t}\n}\n\nfunc (check *HealthCheck) tryConnectOnce(createBrokerTopic, createReplicationTopic *bool) error {\n\tpauseTime := check.config.retryInterval\n\t\/\/ connect to kafka cluster\n\tconnectString := fmt.Sprintf(\"localhost:%d\", check.config.brokerPort)\n\terr := check.broker.Dial(connectString, check.brokerConfig())\n\tif err != nil {\n\t\tlog.Printf(\"unable to connect to broker, retrying in %s (%s)\", pauseTime.String(), err)\n\t\treturn err\n\t}\n\n\tmetadata, err := check.broker.Metadata()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failure retrieving metadata\")\n\t}\n\n\tcheck.partitionID, err = check.findPartitionID(check.config.topicName, true, createBrokerTopic, metadata)\n\tif err != nil {\n\t\tlog.Printf(\"%s retrying in %s\", err.Error(), pauseTime)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tcheck.replicationPartitionID, err = check.findPartitionID(check.config.replicationTopicName, false, createReplicationTopic, metadata)\n\tif err != nil {\n\t\tlog.Printf(\"%s retrying in %s\", err.Error(), pauseTime)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tconsumer, err := check.broker.Consumer(check.consumerConfig())\n\tif err != nil {\n\t\tlog.Printf(\"unable to create consumer, retrying in %s: %s\", pauseTime.String(), err)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tproducer, err := check.broker.Producer(check.producerConfig())\n\tif err != nil {\n\t\tlog.Printf(\"unable to create producer, retrying in %s: %s\", pauseTime.String(), err)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tcheck.consumer = consumer\n\tcheck.producer = producer\n\treturn nil\n}\n\nfunc (check *HealthCheck) findPartitionID(topicName string, forHealthCheck bool, createIfMissing *bool, metadata *kafka.MetadataResponse) (int32, error) {\n\tbrokerID := int32(check.config.brokerID)\n\n\tif !brokerExists(brokerID, metadata) {\n\t\treturn 0, fmt.Errorf(\"unable to find broker %d in metadata\", brokerID)\n\t}\n\n\ttopic, ok := findTopic(topicName, metadata)\n\n\tif ok {\n\t\tfor _, partition := range topic.Partitions {\n\t\t\tif forHealthCheck && partition.Leader != brokerID {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !contains(partition.Replicas, brokerID) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlog.Printf(`found partition id %d for broker %d in topic \"%s\"`, partition.ID, brokerID, topicName)\n\t\t\treturn partition.ID, nil\n\t\t}\n\t}\n\n\tif *createIfMissing {\n\t\terr := check.createTopic(topicName, forHealthCheck)\n\t\tif err != nil {\n\t\t\treturn 0, errors.Wrapf(err, `unable to create topic \"%s\"`, topicName)\n\t\t}\n\t\tlog.Printf(`topic \"%s\" created`, topicName)\n\t\t*createIfMissing = false\n\t\treturn 0, errors.New(\"topic created, try again\")\n\t}\n\n\tif ok {\n\t\treturn 0, fmt.Errorf(`Unable to find broker's parition in topic \"%s\" in metadata`, topicName)\n\t}\n\treturn 0, fmt.Errorf(`Unable to find broker's topic \"%s\" in metadata`, topicName)\n}\n\nfunc findTopic(name string, metadata *kafka.MetadataResponse) (*kafka.TopicMetadata, bool) {\n\tfor _, topic := range metadata.Topics {\n\t\tif topic.Name == name {\n\t\t\treturn topic, true\n\t\t}\n\t}\n\n\treturn nil, false\n}\n\nfunc brokerExists(brokerID int32, metadata *kafka.MetadataResponse) bool {\n\tfor _, broker := range metadata.Brokers {\n\t\tif broker.ID() == brokerID {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc zookeeperEnsembleAndChroot(connectString string) (ensemble []string, chroot string) {\n\tresult := strings.Split(connectString, \"\/\")\n\tswitch len(result) {\n\tcase 1:\n\t\tensemble = strings.Split(result[0], \",\")\n\t\tchroot = \"\"\n\tdefault:\n\t\tensemble = strings.Split(result[0], \",\")\n\t\tchroot = \"\/\" + strings.Join(result[1:], \"\/\")\n\t\tif strings.HasSuffix(chroot, \"\/\") {\n\t\t\tchroot = chroot[:len(chroot)-1]\n\t\t}\n\t}\n\treturn\n}\n\nfunc (check *HealthCheck) createTopic(name string, forHealthCheck bool) (err error) {\n\tlog.Printf(\"connecting to ZooKeeper ensemble %s\", check.config.zookeeperConnect)\n\tconnectString, chroot := zookeeperEnsembleAndChroot(check.config.zookeeperConnect)\n\tzkConn := check.zookeeper\n\n\tif _, err = zkConn.Connect(connectString, 10*time.Second); err != nil {\n\t\treturn\n\t}\n\tdefer zkConn.Close()\n\n\ttopicPath := chroot + \"\/config\/topics\/\" + name\n\n\texists := false\n\tif !forHealthCheck {\n\t\texists, _, err = zkConn.Exists(topicPath)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tbrokerID := int32(check.config.brokerID)\n\n\tif !exists {\n\t\ttopicConfig := `{\"version\":1,\"config\":{\"delete.retention.ms\":\"10000\",` +\n\t\t\t`\"cleanup.policy\":\"delete\",\"compression.type\":\"uncompressed\"}}`\n\t\tlog.Infof(`creating topic \"%s\" configuration node`, name)\n\n\t\tif err = createZkNode(zkConn, topicPath, topicConfig, false); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tpartitionAssignment := fmt.Sprintf(`{\"version\":1,\"partitions\":{\"0\":[%d]}}`, brokerID)\n\t\tlog.Infof(`creating topic \"%s\" partition assignment node`, name)\n\n\t\tif err = createZkNode(zkConn, chroot+\"\/brokers\/topics\/\"+name, partitionAssignment, false); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif !forHealthCheck {\n\t\terr = maybeExpandReplicationTopic(zkConn, brokerID, check.replicationPartitionID, name, chroot)\n\t}\n\n\treturn\n\n}\n\nfunc maybeExpandReplicationTopic(zk ZkConnection, brokerID, partitionID int32, topicName, chroot string) error {\n\ttopic := ZkTopic{Name: topicName}\n\terr := zkPartitions(&topic, zk, topicName, chroot)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Unable to determine if replication topic should be expanded\")\n\t}\n\n\treplicas, ok := topic.Partitions[strconv.Itoa(int(partitionID))]\n\tif !ok {\n\t\treturn fmt.Errorf(`Cannot find partition with ID %d in topic \"%s\"`, partitionID, topicName)\n\t}\n\n\tif !contains(replicas, brokerID) {\n\t\tlog.Info(\"Expanding replication check topic to include broker \", brokerID)\n\t\treplicas = append(replicas, brokerID)\n\n\t\treturn reassignPartition(zk, partitionID, replicas, topicName, chroot)\n\t}\n\treturn nil\n}\n\nfunc reassignPartition(zk ZkConnection, partitionID int32, replicas []int32, topicName, chroot string) (err error) {\n\n\trepeat := true\n\tfor repeat {\n\t\ttime.Sleep(1 * time.Second)\n\t\texists, _, rpErr := zk.Exists(chroot + \"\/admin\/reassign_partitions\")\n\t\tif rpErr != nil {\n\t\t\tlog.Warn(\"Error while checking if reassign_partitions node exists\", rpErr)\n\t\t}\n\t\trepeat = exists || rpErr != nil\n\t}\n\n\tvar replicasStr []string\n\tfor _, ID := range replicas {\n\t\treplicasStr = append(replicasStr, fmt.Sprintf(\"%d\", ID))\n\t}\n\n\treassign := fmt.Sprintf(`{\"version\":1,\"partitions\":[{\"topic\":\"%s\",\"partition\":%d,\"replicas\":[%s]}]}`,\n\t\ttopicName, partitionID, strings.Join(replicasStr, \",\"))\n\n\trepeat = true\n\tfor repeat {\n\t\tlog.Info(\"Creating reassign partition node\")\n\t\terr = createZkNode(zk, chroot+\"\/admin\/reassign_partitions\", reassign, true)\n\t\tif err != nil {\n\t\t\tlog.Warn(\"Error while creating reassignment node\", err)\n\t\t}\n\t\trepeat = err != nil\n\t}\n\n\treturn\n}\n\nfunc createZkNode(zookeeper ZkConnection, path string, content string, failIfExists bool) error {\n\tnodeExists, _, err := zookeeper.Exists(path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif nodeExists {\n\t\tif failIfExists {\n\t\t\treturn fmt.Errorf(\"node %s cannot be created, exists already\", path)\n\t\t}\n\t\treturn nil\n\t}\n\n\tlog.Println(\"creating node\", path)\n\tflags := int32(0) \/\/ permanent node.\n\tacl := zk.WorldACL(zk.PermAll)\n\t_, err = zookeeper.Create(path, []byte(content), flags, acl)\n\treturn err\n}\n\nfunc (check *HealthCheck) closeConnection(deleteTopicIfPresent bool) {\n\tif deleteTopicIfPresent {\n\t\tlog.Infof(\"connecting to ZooKeeper ensemble %s\", check.config.zookeeperConnect)\n\t\tconnectString, chroot := zookeeperEnsembleAndChroot(check.config.zookeeperConnect)\n\n\t\tzkConn := check.zookeeper\n\t\t_, err := zkConn.Connect(connectString, 10*time.Second)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdefer zkConn.Close()\n\n\t\tcheck.deleteTopic(zkConn, chroot, check.config.topicName, check.partitionID)\n\t\tcheck.deleteTopic(zkConn, chroot, check.config.replicationTopicName, check.replicationPartitionID)\n\t}\n\tcheck.broker.Close()\n}\n\nfunc (check *HealthCheck) deleteTopic(zkConn ZkConnection, chroot, name string, partitionID int32) error {\n\ttopic := ZkTopic{Name: name}\n\terr := zkPartitions(&topic, zkConn, name, chroot)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treplicas, ok := topic.Partitions[strconv.Itoa(int(partitionID))]\n\tif !ok {\n\t\treturn fmt.Errorf(`Cannot find partition with ID %d in topic \"%s\"`, partitionID, name)\n\t}\n\n\tbrokerID := int32(check.config.brokerID)\n\tif len(replicas) > 1 {\n\t\tlog.Info(\"Shrinking replication check topic to exclude broker \", brokerID)\n\t\treplicas = delAll(replicas, brokerID)\n\t\treturn reassignPartition(zkConn, partitionID, replicas, name, chroot)\n\t}\n\n\tdelTopicPath := chroot + \"\/admin\/delete_topics\/\" + name\n\n\terr = createZkNode(check.zookeeper, delTopicPath, \"\", true)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn check.waitForTopicDeletion(delTopicPath)\n}\n\nfunc (check *HealthCheck) waitForTopicDeletion(topicPath string) error {\n\tfor {\n\t\texists, _, err := check.zookeeper.Exists(topicPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !exists {\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(check.config.retryInterval)\n\t}\n}\n\nfunc (check *HealthCheck) reconnect(stop <-chan struct{}) error {\n\tcheck.closeConnection(false)\n\treturn check.connect(false, stop)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build linux\n\n\/\/ Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n\/\/ not use this file except in compliance with the License. A copy of the\n\/\/ License is located at\n\/\/\n\/\/\thttpaws.amazon.com\/apache2.0\/\n\/\/\n\/\/ or in the \"license\" file accompanying this file. This file is distributed\n\/\/ on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n\/\/ express or implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\npackage config\n\nfunc parseGMSACapability() bool {\n\treturn false\n}\n\nfunc parseFSxWindowsFileServerCapability() bool {\n\treturn false\n}\n\n\/\/ GetOperatingSystemFamily() returns \"linux\" as operating system family for linux based ecs instances\nfunc GetOperatingSystemFamily() string {\n\treturn OSType\n}\n<commit_msg>Revert \"Changes to advertise OSType while registering the container instance with cluster\"<commit_after>\/\/ +build linux\n\n\/\/ Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n\/\/ not use this file except in compliance with the License. A copy of the\n\/\/ License is located at\n\/\/\n\/\/\thttpaws.amazon.com\/apache2.0\/\n\/\/\n\/\/ or in the \"license\" file accompanying this file. This file is distributed\n\/\/ on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n\/\/ express or implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\npackage config\n\nfunc parseGMSACapability() bool {\n\treturn false\n}\n\nfunc parseFSxWindowsFileServerCapability() bool {\n\treturn false\n}\n\/\/ GetOperatingSystemFamily() returns \"linux\" as operating system family for linux based ecs instances\nfunc GetOperatingSystemFamily() string {\n\treturn OSType\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Matthew Baird\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage gochimp\n\n\/\/ see http:\/\/apidocs.mailchimp.com\/api\/2.0\/\nconst (\n\tlists_subscribe_endpoint         string = \"\/lists\/subscribe.json\"\n\tlists_unsubscribe_endpoint       string = \"\/lists\/unsubscribe.json\"\n\tlists_list_endpoint              string = \"\/lists\/list.json\"\n\tlists_update_member_endpoint     string = \"\/lists\/update-member.json\"\n\tlists_members_endpoint           string = \"\/lists\/members.json\"\n\tlists_member_info_endpoint       string = \"\/lists\/member-info.json\"\n\tlists_batch_unsubscribe_endpoint string = \"\/lists\/batch-unsubscribe.json\"\n)\n\nfunc (a *ChimpAPI) BatchUnsubscribe(req BatchUnsubscribe) (BatchResponse, error) {\n\tvar response BatchResponse\n\treq.ApiKey = a.Key\n\terr := parseChimpJson(a, lists_batch_unsubscribe_endpoint, req, &response)\n\treturn response, err\n}\n\nfunc (a *ChimpAPI) ListsSubscribe(req ListsSubscribe) (Email, error) {\n\tvar response Email\n\treq.ApiKey = a.Key\n\terr := parseChimpJson(a, lists_subscribe_endpoint, req, &response)\n\treturn response, err\n}\n\nfunc (a *ChimpAPI) ListsUnsubscribe(req ListsUnsubscribe) error {\n\treq.ApiKey = a.Key\n\treturn parseChimpJson(a, lists_unsubscribe_endpoint, req, nil)\n}\n\nfunc (a *ChimpAPI) ListsList(req ListsList) (ListsListResponse, error) {\n\treq.ApiKey = a.Key\n\tvar response ListsListResponse\n\terr := parseChimpJson(a, lists_list_endpoint, req, &response)\n\treturn response, err\n}\n\nfunc (a *ChimpAPI) UpdateMember(req UpdateMember) error {\n\treq.ApiKey = a.Key\n\treturn parseChimpJson(a, lists_update_member_endpoint, req, nil)\n}\n\nfunc (a *ChimpAPI) Members(req ListsMembers) (ListsMembersResponse, error) {\n\treq.ApiKey = a.Key\n\tvar response ListsMembersResponse\n\terr := parseChimpJson(a, lists_members_endpoint, req, &response)\n\treturn response, err\n}\n\nfunc (a *ChimpAPI) MemberInfo(req ListsMemberInfo) (ListsMemberInfoResponse, error) {\n\treq.ApiKey = a.Key\n\tvar response ListsMemberInfoResponse\n\terr := parseChimpJson(a, lists_member_info_endpoint, req, &response)\n\treturn response, err\n}\n\ntype BatchUnsubscribe struct {\n\tApiKey       string  `json:\"apikey\"`\n\tListId       string  `json:\"id\"`\n\tBatch        []Email `json:\"batch\"`\n\tDeleteMember bool    `json:\"delete_member\"`\n\tSendGoodbye  bool    `json:\"send_goodbye\"`\n\tSendNotify   bool    `json:\"send_notify\"`\n}\n\ntype ListsUnsubscribe struct {\n\tApiKey       string `json:\"apikey\"`\n\tListId       string `json:\"id\"`\n\tEmail        Email  `json:\"email\"`\n\tDeleteMember bool   `json:\"delete_member\"`\n\tSendGoodbye  bool   `json:\"send_goodbye\"`\n\tSendNotify   bool   `json:\"send_notify\"`\n}\n\ntype ListsSubscribe struct {\n\tApiKey           string                 `json:\"apikey\"`\n\tListId           string                 `json:\"id\"`\n\tEmail            Email                  `json:\"email\"`\n\tMergeVars        map[string]interface{} `json:\"merge_vars,omitempty\"`\n\tEmailType        string                 `json:\"email_type,omitempty\"`\n\tDoubleOptIn      bool                   `json:\"double_optin\"`\n\tUpdateExisting   bool                   `json:\"update_existing\"`\n\tReplaceInterests bool                   `json:\"replace_interests\"`\n\tSendWelcome      bool                   `json:\"send_welcome\"`\n}\n\ntype ListFilter struct {\n\tListId        string `json:\"list_id\"`\n\tListName      string `json:\"list_name\"`\n\tFromName      string `json:\"from_name\"`\n\tFromEmail     string `json:\"from_email\"`\n\tFromSubject   string `json:\"from_subject\"`\n\tCreatedBefore string `json:\"created_before\"`\n\tCreatedAfter  string `json:\"created_after\"`\n\tExact         bool   `json:\"exact\"`\n}\n\ntype ListStat struct {\n\tMemberCount               float64 `json:\"member_count\"`\n\tUnsubscribeCount          float64 `json:\"unsubscribe_count\"`\n\tCleanedCount              float64 `json:\"cleaned_count\"`\n\tMemberCountSinceSend      float64 `json:\"member_count_since_send\"`\n\tUnsubscribeCountSinceSend float64 `json:\"unsubscribe_count_since_send\"`\n\tCleanedCountSinceSend     float64 `json:\"cleaned_count_since_send\"`\n\tCampaignCount             float64 `json:\"campaign_count\"`\n\tGroupingCount             float64 `json:\"grouping_count\"`\n\tGroupCount                float64 `json:\"group_count\"`\n\tMergeVarCount             float64 `json:\"merge_var_count\"`\n\tAvgSubRate                float64 `json:\"avg_sub_rate\"`\n\tAvgUnsubRate              float64 `json:\"avg_unsub_rate\"`\n\tTargetSubRate             float64 `json:\"target_sub_rate \"`\n\tOpenRate                  float64 `json:\"open_rate \"`\n\tClickRate                 float64 `json:\"click_rate \"`\n}\n\ntype ListData struct {\n\tId                string   `json:\"id\"`\n\tWebId             int      `json:\"web_id\"`\n\tName              string   `json:\"name\"`\n\tDateCreated       string   `json:\"date_created\"`\n\tEmailTypeOption   bool     `json:\"email_type_option\"`\n\tUseAwesomeBar     bool     `json:\"use_awesomebar\"`\n\tDefaultFromName   string   `json:\"default_from_name\"`\n\tDefaultFromEmail  string   `json:\"default_from_email\"`\n\tDefaultSubject    string   `json:\"default_subject\"`\n\tDefaultLanguage   string   `json:\"default_language\"`\n\tListRating        float64  `json:\"list_rating\"`\n\tSubscribeShortUrl string   `json:\"subscribe_url_short\"`\n\tSubscribeLongUrl  string   `json:\"subscribe_url_long\"`\n\tBeamerAddress     string   `json:\"beamer_address\"`\n\tVisibility        string   `json:\"visibility\"`\n\tStats             ListStat `json:\"stats\"`\n\tModules           []string `json:\"modules\"`\n}\n\ntype BatchResponse struct {\n\tSuccess     int          `json:\"success_count\"`\n\tErrorCount  int          `json:\"error_count\"`\n\tBatchErrors []BatchError `json:\"errors\"`\n}\n\ntype BatchError struct {\n\tEmails Email  `json:\"email\"`\n\tCode   int    `json:\"code\"`\n\tError  string `json:\"error\"`\n}\n\ntype ListError struct {\n\tParam string `json:\"param\"`\n\tCode  int    `json:\"code\"`\n\tError string `json:\"error\"`\n}\n\ntype ListsListResponse struct {\n\tTotal  int         `json:\"total\"`\n\tData   []ListData  `json:\"data\"`\n\tErrors []ListError `json:\"errors\"`\n}\n\ntype ListsList struct {\n\tApiKey        string     `json:\"apikey\"`\n\tFilters       ListFilter `json:\"filters,omitempty\"`\n\tStart         int        `json:\"start,omitempty\"`\n\tLimit         int        `json:\"limit,omitempty\"`\n\tSortField     string     `json:\"sort_field,omitempty\"`\n\tSortDirection string     `json:\"sort_dir,omitempty\"`\n}\n\ntype UpdateMember struct {\n\tApiKey           string                 `json:\"apikey\"`\n\tListId           string                 `json:\"id\"`\n\tEmail            Email                  `json:\"email\"`\n\tMergeVars        map[string]interface{} `json:\"merge_vars,omitempty\"`\n\tEmailType        string                 `json:\"email_type,omitempty\"`\n\tReplaceInterests bool                   `json:\"replace_interests\"`\n}\n\ntype Email struct {\n\tEmail string `json:\"email\"`\n\tEuid  string `json:\"euid\"`\n\tLeid  string `json:\"leid\"`\n}\n\ntype ListsMembers struct {\n\tApiKey  string          `json:\"apikey\"`\n\tListId  string          `json:\"id\"`\n\tOptions ListsMembersOpt `json:\"opts,omitempty\"`\n}\n\ntype ListsMembersOpt struct {\n\tStart         int    `json:\"start,omitempty\"`\n\tLimit         int    `json:\"limit,omitempty\"`\n\tSortField     string `json:\"sort_field,omitempty\"`\n\tSortDirection string `json:\"sort_dir,omitempty\"`\n}\n\ntype ListsMembersResponse struct {\n\tTotal int          `json:\"total\"`\n\tData  []MemberInfo `json:\"data\"`\n}\n\ntype ListsMemberInfo struct {\n\tApiKey string  `json:\"apikey\"`\n\tListId string  `json:\"id\"`\n\tEmails []Email `json:\"emails\"`\n}\n\ntype ListsMemberInfoResponse struct {\n\tSuccessCount      int          `json:\"success_count\"`\n\tErrorCount        int          `json:\"error_count\"`\n\tErrors            []ListError  `json:\"errors\"`\n\tMemberInfoRecords []MemberInfo `json:\"data\"`\n}\n\ntype MemberInfo struct {\n\tEmail           string                 `json:\"email\"`\n\tEuid            string                 `json:\"euid\"`\n\tEmailType       string                 `json:\"email_type\"`\n\tIpSignup        string                 `json:\"ip_signup,omitempty\"`\n\tTimestampSignup string                 `json:\"timestamp_signup,omitempty\"`\n\tIpOpt           string                 `json:\"ip_opt\"`\n\tTimestampOpt    string                 `json:\"timestamp_opt\"`\n\tMemberRating    int                    `json:\"member_rating\"`\n\tInfoChanged     string                 `json:\"info_changed\"`\n\tLeid            int                    `json:\"leid\"`\n\tLanguage        string                 `json:\"language,omitempty\"`\n\tListId          string                 `json:\"list_id\"`\n\tListName        string                 `json:\"list_name\"`\n\tMerges          map[string]interface{} `json:\"merges\"`\n\tStatus          string                 `json:\"status\"`\n\tTimestamp       string                 `json:\"timestamp\"`\n}\n<commit_msg>ListsMembers Status was missing<commit_after>\/\/ Copyright 2013 Matthew Baird\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage gochimp\n\n\/\/ see http:\/\/apidocs.mailchimp.com\/api\/2.0\/\nconst (\n\tlists_subscribe_endpoint         string = \"\/lists\/subscribe.json\"\n\tlists_unsubscribe_endpoint       string = \"\/lists\/unsubscribe.json\"\n\tlists_list_endpoint              string = \"\/lists\/list.json\"\n\tlists_update_member_endpoint     string = \"\/lists\/update-member.json\"\n\tlists_members_endpoint           string = \"\/lists\/members.json\"\n\tlists_member_info_endpoint       string = \"\/lists\/member-info.json\"\n\tlists_batch_unsubscribe_endpoint string = \"\/lists\/batch-unsubscribe.json\"\n)\n\nfunc (a *ChimpAPI) BatchUnsubscribe(req BatchUnsubscribe) (BatchResponse, error) {\n\tvar response BatchResponse\n\treq.ApiKey = a.Key\n\terr := parseChimpJson(a, lists_batch_unsubscribe_endpoint, req, &response)\n\treturn response, err\n}\n\nfunc (a *ChimpAPI) ListsSubscribe(req ListsSubscribe) (Email, error) {\n\tvar response Email\n\treq.ApiKey = a.Key\n\terr := parseChimpJson(a, lists_subscribe_endpoint, req, &response)\n\treturn response, err\n}\n\nfunc (a *ChimpAPI) ListsUnsubscribe(req ListsUnsubscribe) error {\n\treq.ApiKey = a.Key\n\treturn parseChimpJson(a, lists_unsubscribe_endpoint, req, nil)\n}\n\nfunc (a *ChimpAPI) ListsList(req ListsList) (ListsListResponse, error) {\n\treq.ApiKey = a.Key\n\tvar response ListsListResponse\n\terr := parseChimpJson(a, lists_list_endpoint, req, &response)\n\treturn response, err\n}\n\nfunc (a *ChimpAPI) UpdateMember(req UpdateMember) error {\n\treq.ApiKey = a.Key\n\treturn parseChimpJson(a, lists_update_member_endpoint, req, nil)\n}\n\nfunc (a *ChimpAPI) Members(req ListsMembers) (ListsMembersResponse, error) {\n\treq.ApiKey = a.Key\n\tvar response ListsMembersResponse\n\terr := parseChimpJson(a, lists_members_endpoint, req, &response)\n\treturn response, err\n}\n\nfunc (a *ChimpAPI) MemberInfo(req ListsMemberInfo) (ListsMemberInfoResponse, error) {\n\treq.ApiKey = a.Key\n\tvar response ListsMemberInfoResponse\n\terr := parseChimpJson(a, lists_member_info_endpoint, req, &response)\n\treturn response, err\n}\n\ntype BatchUnsubscribe struct {\n\tApiKey       string  `json:\"apikey\"`\n\tListId       string  `json:\"id\"`\n\tBatch        []Email `json:\"batch\"`\n\tDeleteMember bool    `json:\"delete_member\"`\n\tSendGoodbye  bool    `json:\"send_goodbye\"`\n\tSendNotify   bool    `json:\"send_notify\"`\n}\n\ntype ListsUnsubscribe struct {\n\tApiKey       string `json:\"apikey\"`\n\tListId       string `json:\"id\"`\n\tEmail        Email  `json:\"email\"`\n\tDeleteMember bool   `json:\"delete_member\"`\n\tSendGoodbye  bool   `json:\"send_goodbye\"`\n\tSendNotify   bool   `json:\"send_notify\"`\n}\n\ntype ListsSubscribe struct {\n\tApiKey           string                 `json:\"apikey\"`\n\tListId           string                 `json:\"id\"`\n\tEmail            Email                  `json:\"email\"`\n\tMergeVars        map[string]interface{} `json:\"merge_vars,omitempty\"`\n\tEmailType        string                 `json:\"email_type,omitempty\"`\n\tDoubleOptIn      bool                   `json:\"double_optin\"`\n\tUpdateExisting   bool                   `json:\"update_existing\"`\n\tReplaceInterests bool                   `json:\"replace_interests\"`\n\tSendWelcome      bool                   `json:\"send_welcome\"`\n}\n\ntype ListFilter struct {\n\tListId        string `json:\"list_id\"`\n\tListName      string `json:\"list_name\"`\n\tFromName      string `json:\"from_name\"`\n\tFromEmail     string `json:\"from_email\"`\n\tFromSubject   string `json:\"from_subject\"`\n\tCreatedBefore string `json:\"created_before\"`\n\tCreatedAfter  string `json:\"created_after\"`\n\tExact         bool   `json:\"exact\"`\n}\n\ntype ListStat struct {\n\tMemberCount               float64 `json:\"member_count\"`\n\tUnsubscribeCount          float64 `json:\"unsubscribe_count\"`\n\tCleanedCount              float64 `json:\"cleaned_count\"`\n\tMemberCountSinceSend      float64 `json:\"member_count_since_send\"`\n\tUnsubscribeCountSinceSend float64 `json:\"unsubscribe_count_since_send\"`\n\tCleanedCountSinceSend     float64 `json:\"cleaned_count_since_send\"`\n\tCampaignCount             float64 `json:\"campaign_count\"`\n\tGroupingCount             float64 `json:\"grouping_count\"`\n\tGroupCount                float64 `json:\"group_count\"`\n\tMergeVarCount             float64 `json:\"merge_var_count\"`\n\tAvgSubRate                float64 `json:\"avg_sub_rate\"`\n\tAvgUnsubRate              float64 `json:\"avg_unsub_rate\"`\n\tTargetSubRate             float64 `json:\"target_sub_rate \"`\n\tOpenRate                  float64 `json:\"open_rate \"`\n\tClickRate                 float64 `json:\"click_rate \"`\n}\n\ntype ListData struct {\n\tId                string   `json:\"id\"`\n\tWebId             int      `json:\"web_id\"`\n\tName              string   `json:\"name\"`\n\tDateCreated       string   `json:\"date_created\"`\n\tEmailTypeOption   bool     `json:\"email_type_option\"`\n\tUseAwesomeBar     bool     `json:\"use_awesomebar\"`\n\tDefaultFromName   string   `json:\"default_from_name\"`\n\tDefaultFromEmail  string   `json:\"default_from_email\"`\n\tDefaultSubject    string   `json:\"default_subject\"`\n\tDefaultLanguage   string   `json:\"default_language\"`\n\tListRating        float64  `json:\"list_rating\"`\n\tSubscribeShortUrl string   `json:\"subscribe_url_short\"`\n\tSubscribeLongUrl  string   `json:\"subscribe_url_long\"`\n\tBeamerAddress     string   `json:\"beamer_address\"`\n\tVisibility        string   `json:\"visibility\"`\n\tStats             ListStat `json:\"stats\"`\n\tModules           []string `json:\"modules\"`\n}\n\ntype BatchResponse struct {\n\tSuccess     int          `json:\"success_count\"`\n\tErrorCount  int          `json:\"error_count\"`\n\tBatchErrors []BatchError `json:\"errors\"`\n}\n\ntype BatchError struct {\n\tEmails Email  `json:\"email\"`\n\tCode   int    `json:\"code\"`\n\tError  string `json:\"error\"`\n}\n\ntype ListError struct {\n\tParam string `json:\"param\"`\n\tCode  int    `json:\"code\"`\n\tError string `json:\"error\"`\n}\n\ntype ListsListResponse struct {\n\tTotal  int         `json:\"total\"`\n\tData   []ListData  `json:\"data\"`\n\tErrors []ListError `json:\"errors\"`\n}\n\ntype ListsList struct {\n\tApiKey        string     `json:\"apikey\"`\n\tFilters       ListFilter `json:\"filters,omitempty\"`\n\tStart         int        `json:\"start,omitempty\"`\n\tLimit         int        `json:\"limit,omitempty\"`\n\tSortField     string     `json:\"sort_field,omitempty\"`\n\tSortDirection string     `json:\"sort_dir,omitempty\"`\n}\n\ntype UpdateMember struct {\n\tApiKey           string                 `json:\"apikey\"`\n\tListId           string                 `json:\"id\"`\n\tEmail            Email                  `json:\"email\"`\n\tMergeVars        map[string]interface{} `json:\"merge_vars,omitempty\"`\n\tEmailType        string                 `json:\"email_type,omitempty\"`\n\tReplaceInterests bool                   `json:\"replace_interests\"`\n}\n\ntype Email struct {\n\tEmail string `json:\"email\"`\n\tEuid  string `json:\"euid\"`\n\tLeid  string `json:\"leid\"`\n}\n\ntype ListsMembers struct {\n\tApiKey  string          `json:\"apikey\"`\n\tListId  string          `json:\"id\"`\n\tStatus  string          `json:\"status\"`\n\tOptions ListsMembersOpt `json:\"opts,omitempty\"`\n}\n\ntype ListsMembersOpt struct {\n\tStart         int    `json:\"start,omitempty\"`\n\tLimit         int    `json:\"limit,omitempty\"`\n\tSortField     string `json:\"sort_field,omitempty\"`\n\tSortDirection string `json:\"sort_dir,omitempty\"`\n}\n\ntype ListsMembersResponse struct {\n\tTotal int          `json:\"total\"`\n\tData  []MemberInfo `json:\"data\"`\n}\n\ntype ListsMemberInfo struct {\n\tApiKey string  `json:\"apikey\"`\n\tListId string  `json:\"id\"`\n\tEmails []Email `json:\"emails\"`\n}\n\ntype ListsMemberInfoResponse struct {\n\tSuccessCount      int          `json:\"success_count\"`\n\tErrorCount        int          `json:\"error_count\"`\n\tErrors            []ListError  `json:\"errors\"`\n\tMemberInfoRecords []MemberInfo `json:\"data\"`\n}\n\ntype MemberInfo struct {\n\tEmail           string                 `json:\"email\"`\n\tEuid            string                 `json:\"euid\"`\n\tEmailType       string                 `json:\"email_type\"`\n\tIpSignup        string                 `json:\"ip_signup,omitempty\"`\n\tTimestampSignup string                 `json:\"timestamp_signup,omitempty\"`\n\tIpOpt           string                 `json:\"ip_opt\"`\n\tTimestampOpt    string                 `json:\"timestamp_opt\"`\n\tMemberRating    int                    `json:\"member_rating\"`\n\tInfoChanged     string                 `json:\"info_changed\"`\n\tLeid            int                    `json:\"leid\"`\n\tLanguage        string                 `json:\"language,omitempty\"`\n\tListId          string                 `json:\"list_id\"`\n\tListName        string                 `json:\"list_name\"`\n\tMerges          map[string]interface{} `json:\"merges\"`\n\tStatus          string                 `json:\"status\"`\n\tTimestamp       string                 `json:\"timestamp\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype handler struct {\n\tdest url.URL\n}\n\nvar rewriter *strings.Replacer\n\nfunc (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tdu := h.dest\n\tdu.Path = req.URL.Path\n\tdu.RawQuery = req.URL.RawQuery\n\treq.URL = &du\n\treq.RequestURI = \"\"\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\n\tfor k, v := range res.Header {\n\t\tres.Header[k] = v\n\t}\n\tw.WriteHeader(res.StatusCode)\n\n\tio.Copy(w, rewriteJson(res.Body, rewriter.Replace))\n}\n\nfunc initRewrite(conf string) {\n\tif conf == \"\" {\n\t\trewriter = strings.NewReplacer()\n\t\treturn\n\t}\n\n\tf, err := os.Open(conf)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error opening %v: %v\", conf, err)\n\t}\n\tdefer f.Close()\n\td := json.NewDecoder(f)\n\tm := map[string]string{}\n\terr = d.Decode(&m)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error parsing %v: %v\", conf, err)\n\t}\n\n\tparams := []string{}\n\tfor k, v := range m {\n\t\tparams = append(params, k, v)\n\t}\n\n\trewriter = strings.NewReplacer(params...)\n}\n\nfunc main() {\n\tbindAddr := flag.String(\"bind\", \":7081\", \"Address to listen\")\n\trewriteConf := flag.String(\"rewriteconf\", \"\",\n\t\t\"Path to json rewrite rules\")\n\n\tflag.Parse()\n\n\tif flag.NArg() != 1 {\n\t\tlog.Fatalf(\"Where to, sir?\")\n\t}\n\n\tinitRewrite(*rewriteConf)\n\n\tu, err := url.Parse(flag.Arg(0))\n\tif err != nil {\n\t\tlog.Fatalf(\"Error parsing url: %v\", err)\n\t}\n\n\tlog.Fatal(http.ListenAndServe(*bindAddr, &handler{*u}))\n}\n<commit_msg>Only sed things claiming to be json<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype handler struct {\n\tdest url.URL\n}\n\nvar rewriter *strings.Replacer\n\nfunc (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tdu := h.dest\n\tdu.Path = req.URL.Path\n\tdu.RawQuery = req.URL.RawQuery\n\treq.URL = &du\n\treq.RequestURI = \"\"\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\n\tfor k, vs := range res.Header {\n\t\th := w.Header()\n\t\th.Del(k)\n\t\tfor _, v := range vs {\n\t\t\th.Add(k, v)\n\t\t}\n\t}\n\tw.WriteHeader(res.StatusCode)\n\n\tif strings.Contains(res.Header.Get(\"content-type\"), \"json\") {\n\t\tio.Copy(w, rewriteJson(res.Body, rewriter.Replace))\n\t} else {\n\t\tio.Copy(w, res.Body)\n\t}\n}\n\nfunc initRewrite(conf string) {\n\tif conf == \"\" {\n\t\trewriter = strings.NewReplacer()\n\t\treturn\n\t}\n\n\tf, err := os.Open(conf)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error opening %v: %v\", conf, err)\n\t}\n\tdefer f.Close()\n\td := json.NewDecoder(f)\n\tm := map[string]string{}\n\terr = d.Decode(&m)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error parsing %v: %v\", conf, err)\n\t}\n\n\tparams := []string{}\n\tfor k, v := range m {\n\t\tparams = append(params, k, v)\n\t}\n\n\trewriter = strings.NewReplacer(params...)\n}\n\nfunc main() {\n\tbindAddr := flag.String(\"bind\", \":7081\", \"Address to listen\")\n\trewriteConf := flag.String(\"rewriteconf\", \"\",\n\t\t\"Path to json rewrite rules\")\n\n\tflag.Parse()\n\n\tif flag.NArg() != 1 {\n\t\tlog.Fatalf(\"Where to, sir?\")\n\t}\n\n\tinitRewrite(*rewriteConf)\n\n\tu, err := url.Parse(flag.Arg(0))\n\tif err != nil {\n\t\tlog.Fatalf(\"Error parsing url: %v\", err)\n\t}\n\n\tlog.Fatal(http.ListenAndServe(*bindAddr, &handler{*u}))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build mage\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/magefile\/mage\/mg\"\n\t\"github.com\/magefile\/mage\/sh\"\n)\n\n\/\/ getBuildMatrix returns the build matrix from the current version of the go compiler\nfunc getBuildMatrix() (map[string][]string, error) {\n\tjsonData, err := sh.Output(\"go\", \"tool\", \"dist\", \"list\", \"-json\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar data []struct {\n\t\tGoos   string\n\t\tGoarch string\n\t}\n\tif err := json.Unmarshal([]byte(jsonData), &data); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmatrix := map[string][]string{}\n\tfor _, v := range data {\n\t\tif val, ok := matrix[v.Goos]; ok {\n\t\t\tmatrix[v.Goos] = append(val, v.Goarch)\n\t\t} else {\n\t\t\tmatrix[v.Goos] = []string{v.Goarch}\n\t\t}\n\t}\n\n\treturn matrix, nil\n}\n\nfunc CrossBuild() error {\n\tmatrix, err := getBuildMatrix()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor os, arches := range matrix {\n\t\tfor _, arch := range arches {\n\t\t\tenv := map[string]string{\n\t\t\t\t\"GOOS\":   os,\n\t\t\t\t\"GOARCH\": arch,\n\t\t\t}\n\t\t\tif mg.Verbose() {\n\t\t\t\tfmt.Printf(\"Building for GOOS=%s GOARCH=%s\\n\", os, arch)\n\t\t\t}\n\t\t\tif err := sh.RunWith(env, \"go\", \"build\", \".\/...\"); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc Lint() error {\n\tgopath := os.Getenv(\"GOPATH\")\n\tif gopath == \"\" {\n\t\treturn fmt.Errorf(\"cannot retrieve GOPATH\")\n\t}\n\n\treturn sh.Run(path.Join(gopath, \"bin\", \"golangci-lint\"), \"run\", \".\/...\")\n}\n\n\/\/ Run the test suite\nfunc Test() error {\n\treturn sh.RunWith(map[string]string{\"GORACE\": \"halt_on_error=1\"},\n\t\t\"go\", \"test\", \"-race\", \"-v\", \".\/...\")\n}\n<commit_msg>reduce the list of cross build target<commit_after>\/\/go:build mage\n\/\/ +build mage\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"sort\"\n\n\t\"github.com\/magefile\/mage\/mg\"\n\t\"github.com\/magefile\/mage\/sh\"\n)\n\nfunc intersect(a, b []string) []string {\n\tsort.Strings(a)\n\tsort.Strings(b)\n\n\tres := make([]string, 0, func() int {\n\t\tif len(a) < len(b) {\n\t\t\treturn len(a)\n\t\t}\n\t\treturn len(b)\n\t}())\n\n\tfor _, v := range a {\n\t\tidx := sort.SearchStrings(b, v)\n\t\tif idx < len(b) && b[idx] == v {\n\t\t\tres = append(res, v)\n\t\t}\n\t}\n\treturn res\n}\n\n\/\/ getBuildMatrix returns the build matrix from the current version of the go compiler\nfunc getFullBuildMatrix() (map[string][]string, error) {\n\tjsonData, err := sh.Output(\"go\", \"tool\", \"dist\", \"list\", \"-json\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar data []struct {\n\t\tGoos   string\n\t\tGoarch string\n\t}\n\tif err := json.Unmarshal([]byte(jsonData), &data); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmatrix := map[string][]string{}\n\tfor _, v := range data {\n\t\tif val, ok := matrix[v.Goos]; ok {\n\t\t\tmatrix[v.Goos] = append(val, v.Goarch)\n\t\t} else {\n\t\t\tmatrix[v.Goos] = []string{v.Goarch}\n\t\t}\n\t}\n\n\treturn matrix, nil\n}\n\nfunc getBuildMatrix() (map[string][]string, error) {\n\tminimalMatrix := map[string][]string{\n\t\t\"linux\":   []string{\"amd64\"},\n\t\t\"darwin\":  []string{\"amd64\", \"arm64\"},\n\t\t\"freebsd\": []string{\"amd64\"},\n\t\t\"js\":      []string{\"wasm\"},\n\t\t\"solaris\": []string{\"amd64\"},\n\t\t\"windows\": []string{\"amd64\", \"arm64\"},\n\t}\n\n\tfullMatrix, err := getFullBuildMatrix()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor os, arches := range minimalMatrix {\n\t\tif fullV, ok := fullMatrix[os]; !ok {\n\t\t\tdelete(minimalMatrix, os)\n\t\t} else {\n\t\t\tminimalMatrix[os] = intersect(arches, fullV)\n\t\t}\n\t}\n\treturn minimalMatrix, nil\n}\n\nfunc CrossBuild() error {\n\tmatrix, err := getBuildMatrix()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor os, arches := range matrix {\n\t\tfor _, arch := range arches {\n\t\t\tenv := map[string]string{\n\t\t\t\t\"GOOS\":   os,\n\t\t\t\t\"GOARCH\": arch,\n\t\t\t}\n\t\t\tif mg.Verbose() {\n\t\t\t\tfmt.Printf(\"Building for GOOS=%s GOARCH=%s\\n\", os, arch)\n\t\t\t}\n\t\t\tif err := sh.RunWith(env, \"go\", \"build\", \".\/...\"); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc Lint() error {\n\tgopath := os.Getenv(\"GOPATH\")\n\tif gopath == \"\" {\n\t\treturn fmt.Errorf(\"cannot retrieve GOPATH\")\n\t}\n\n\treturn sh.Run(path.Join(gopath, \"bin\", \"golangci-lint\"), \"run\", \".\/...\")\n}\n\n\/\/ Run the test suite\nfunc Test() error {\n\treturn sh.RunWith(map[string]string{\"GORACE\": \"halt_on_error=1\"},\n\t\t\"go\", \"test\", \"-race\", \"-v\", \".\/...\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package downloader\n\nimport (\n    \"bytes\"\n\n    \"github.com\/PuerkitoBio\/goquery\"\n    \"github.com\/bitly\/go-simplejson\"\n    \/\/    iconv \"github.com\/djimenez\/iconv-go\"\n    \"github.com\/hu17889\/go_spider\/core\/common\/mlog\"\n    \"github.com\/hu17889\/go_spider\/core\/common\/page\"\n    \"github.com\/hu17889\/go_spider\/core\/common\/request\"\n    \"github.com\/hu17889\/go_spider\/core\/common\/util\"\n    \/\/    \"golang.org\/x\/text\/encoding\/simplifiedchinese\"\n    \/\/    \"golang.org\/x\/text\/transform\"\n    \"io\"\n    \"io\/ioutil\"\n    \"net\/http\"\n    \"net\/url\"\n    \/\/\"fmt\"\n    \"golang.org\/x\/net\/html\/charset\"\n    \/\/    \"regexp\"\n    \/\/    \"golang.org\/x\/net\/html\"\n    \"strings\"\n\t\"compress\/gzip\"\n)\n\n\/\/ The HttpDownloader download page by package net\/http.\n\/\/ The \"html\" content is contained in dom parser of package goquery.\n\/\/ The \"json\" content is saved.\n\/\/ The \"jsonp\" content is modified to json.\n\/\/ The \"text\" content will save body plain text only.\n\/\/ The page result is saved in Page.\ntype HttpDownloader struct {\n}\n\nfunc NewHttpDownloader() *HttpDownloader {\n    return &HttpDownloader{}\n}\n\nfunc (this *HttpDownloader) Download(req *request.Request) *page.Page {\n    var mtype string\n    var p = page.NewPage(req)\n    mtype = req.GetResponceType()\n    switch mtype {\n    case \"html\":\n        return this.downloadHtml(p, req)\n    case \"json\":\n        fallthrough\n    case \"jsonp\":\n        return this.downloadJson(p, req)\n    case \"text\":\n        return this.downloadText(p, req)\n    default:\n        mlog.LogInst().LogError(\"error request type:\" + mtype)\n    }\n    return p\n}\n\n\/*\n\/\/ The acceptableCharset is test for whether Content-Type is UTF-8 or not\nfunc (this *HttpDownloader) acceptableCharset(contentTypes []string) bool {\n    \/\/ each type is like [text\/html; charset=UTF-8]\n    \/\/ we want the UTF-8 only\n    for _, cType := range contentTypes {\n        if strings.Index(cType, \"UTF-8\") != -1 || strings.Index(cType, \"utf-8\") != -1 {\n            return true\n        }\n    }\n    return false\n}\n\n\n\/\/ The getCharset used for parsing the header[\"Content-Type\"] string to get charset of the page.\nfunc (this *HttpDownloader) getCharset(header http.Header) string {\n    reg, err := regexp.Compile(\"charset=(.*)$\")\n    if err != nil {\n        mlog.LogInst().LogError(err.Error())\n        return \"\"\n    }\n\n    var charset string\n    for _, cType := range header[\"Content-Type\"] {\n        substrings := reg.FindStringSubmatch(cType)\n        if len(substrings) == 2 {\n            charset = substrings[1]\n        }\n    }\n\n    return charset\n}\n\n\n\n\n\/\/ Use golang.org\/x\/text\/encoding. Get page body and change it to utf-8\nfunc (this *HttpDownloader) changeCharsetEncoding(charset string, sor io.ReadCloser) string {\n    ischange := true\n    var tr transform.Transformer\n    cs := strings.ToLower(charset)\n    if cs == \"gbk\" {\n        tr = simplifiedchinese.GBK.NewDecoder()\n    } else if cs == \"gb18030\" {\n        tr = simplifiedchinese.GB18030.NewDecoder()\n    } else if cs == \"hzgb2312\" || cs == \"gb2312\" || cs == \"hz-gb2312\" {\n        tr = simplifiedchinese.HZGB2312.NewDecoder()\n    } else {\n        ischange = false\n    }\n\n    var destReader io.Reader\n    if ischange {\n        transReader := transform.NewReader(sor, tr)\n        destReader = transReader\n    } else {\n        destReader = sor\n    }\n\n    var sorbody []byte\n    var err error\n    if sorbody, err = ioutil.ReadAll(destReader); err != nil {\n        mlog.LogInst().LogError(err.Error())\n        return \"\"\n    }\n    bodystr := string(sorbody)\n\n    return bodystr\n}\n\n\/\/ Use go-iconv. Get page body and change it to utf-8\n\nfunc (this *HttpDownloader) changeCharsetGoIconv(charset string, sor io.ReadCloser) string {\n    var err error\n    var converter *iconv.Converter\n    if charset != \"\" && strings.ToLower(charset) != \"utf-8\" && strings.ToLower(charset) != \"utf8\" {\n        converter, err = iconv.NewConverter(charset, \"utf-8\")\n        if err != nil {\n            mlog.LogInst().LogError(err.Error())\n            return \"\"\n        }\n        defer converter.Close()\n    }\n\n    var sorbody []byte\n    if sorbody, err = ioutil.ReadAll(sor); err != nil {\n        mlog.LogInst().LogError(err.Error())\n        return \"\"\n    }\n    bodystr := string(sorbody)\n\n    var destbody string\n    if converter != nil {\n        \/\/ convert to utf8\n        destbody, err = converter.ConvertString(bodystr)\n        if err != nil {\n            mlog.LogInst().LogError(err.Error())\n            return \"\"\n        }\n    } else {\n        destbody = bodystr\n    }\n    return destbody\n}\n*\/\n\n\/\/ Charset auto determine. Use golang.org\/x\/net\/html\/charset. Get page body and change it to utf-8\nfunc (this *HttpDownloader) changeCharsetEncodingAuto(contentTypeStr string, sor io.ReadCloser) string {\n    var err error\n    destReader, err := charset.NewReader(sor, contentTypeStr)\n\n    if err != nil {\n        mlog.LogInst().LogError(err.Error())\n        destReader = sor\n    }\n\n    var sorbody []byte\n    if sorbody, err = ioutil.ReadAll(destReader); err != nil {\n        mlog.LogInst().LogError(err.Error())\n        \/\/ For gb2312, an error will be returned.\n        \/\/ Error like: simplifiedchinese: invalid GBK encoding\n        \/\/ return \"\"\n    }\n    \/\/e,name,certain := charset.DetermineEncoding(sorbody,contentTypeStr)\n    bodystr := string(sorbody)\n\n    return bodystr\n}\n\nfunc (this *HttpDownloader) changeCharsetEncodingAutoGzipSupport(contentTypeStr string, sor io.ReadCloser) string {\n\tvar err error\n\tgzipReader, err := gzip.NewReader(sor)\n\tif err != nil {\n\t\tmlog.LogInst().LogError(err.Error())\n\t\treturn \"\"\n\t}\n\tdestReader, err := charset.NewReader(gzipReader, contentTypeStr)\n\n\tif err != nil {\n\t\tmlog.LogInst().LogError(err.Error())\n\t\tdestReader = sor\n\t}\n\n\tvar sorbody []byte\n\tif sorbody, err = ioutil.ReadAll(destReader); err != nil {\n\t\tmlog.LogInst().LogError(err.Error())\n\t\t\/\/ For gb2312, an error will be returned.\n\t\t\/\/ Error like: simplifiedchinese: invalid GBK encoding\n\t\t\/\/ return \"\"\n\t}\n\t\/\/e,name,certain := charset.DetermineEncoding(sorbody,contentTypeStr)\n\tbodystr := string(sorbody)\n\n\treturn bodystr\n}\n\n\/\/ choose http GET\/method to download\nfunc connectByHttp(p *page.Page, req *request.Request) (*http.Response, error) {\n    client := &http.Client{\n        CheckRedirect: req.GetRedirectFunc(),\n    }\n\n    httpreq, err := http.NewRequest(req.GetMethod(), req.GetUrl(), strings.NewReader(req.GetPostdata()))\n    if header := req.GetHeader(); header != nil {\n        httpreq.Header = req.GetHeader()\n    }\n\n    if cookies := req.GetCookies(); cookies != nil {\n        for i := range cookies {\n            httpreq.AddCookie(cookies[i])\n        }\n    }\n\n    var resp *http.Response\n    if resp, err = client.Do(httpreq); err != nil {\n        if e, ok := err.(*url.Error); ok && e.Err != nil && e.Err.Error() == \"normal\" {\n            \/\/  normal\n        } else {\n            mlog.LogInst().LogError(err.Error())\n            p.SetStatus(true, err.Error())\n            \/\/fmt.Printf(\"client do error %v \\r\\n\", err)\n            return nil, err\n        }\n    }\n\n    return resp, nil\n}\n\n\/\/ choose a proxy server to excute http GET\/method to download\nfunc connectByHttpProxy(p *page.Page, in_req *request.Request) (*http.Response, error) {\n    request, _ := http.NewRequest(\"GET\", in_req.GetUrl(), nil)\n    proxy, err := url.Parse(in_req.GetProxyHost())\n    if err != nil {\n        return nil, err\n    }\n    client := &http.Client{\n        Transport: &http.Transport{\n            Proxy: http.ProxyURL(proxy),\n        },\n    }\n    resp, err := client.Do(request)\n    if err != nil {\n        return nil, err\n    }\n    return resp, nil\n\n}\n\n\/\/ Download file and change the charset of page charset.\nfunc (this *HttpDownloader) downloadFile(p *page.Page, req *request.Request) (*page.Page, string) {\n    var err error\n    var urlstr string\n    if urlstr = req.GetUrl(); len(urlstr) == 0 {\n        mlog.LogInst().LogError(\"url is empty\")\n        p.SetStatus(true, \"url is empty\")\n        return p, \"\"\n    }\n\n    var resp *http.Response\n\n    if proxystr := req.GetProxyHost(); len(proxystr) != 0 {\n        \/\/using http proxy\n        \/\/fmt.Print(\"HttpProxy Enter \",proxystr,\"\\n\")\n        resp, err = connectByHttpProxy(p, req)\n    } else {\n        \/\/normal http download\n        \/\/fmt.Print(\"Http Normal Enter \\n\",proxystr,\"\\n\")\n        resp, err = connectByHttp(p, req)\n    }\n\n    if err != nil {\n        return p, \"\"\n    }\n\n    \/\/b, _ := ioutil.ReadAll(resp.Body)\n    \/\/fmt.Printf(\"Resp body %v \\r\\n\", string(b))\n\n    p.SetHeader(resp.Header)\n    p.SetCookies(resp.Cookies())\n\n    \/\/ get converter to utf-8\n\tvar bodyStr string\n\tif resp.Header.Get(\"Content-Encoding\") == \"gzip\" {\n\t\tbodyStr = this.changeCharsetEncodingAutoGzipSupport(resp.Header.Get(\"Content-Type\"), resp.Body)\n\t} else {\n\t\tbodyStr = this.changeCharsetEncodingAuto(resp.Header.Get(\"Content-Type\"), resp.Body)\n\t}\n    \/\/fmt.Printf(\"utf-8 body %v \\r\\n\", bodyStr)\n    defer resp.Body.Close()\n    return p, bodyStr\n}\n\nfunc (this *HttpDownloader) downloadHtml(p *page.Page, req *request.Request) *page.Page {\n    var err error\n    p, destbody := this.downloadFile(p, req)\n    \/\/fmt.Printf(\"Destbody %v \\r\\n\", destbody)\n    if !p.IsSucc() {\n        \/\/fmt.Print(\"Page error \\r\\n\")\n        return p\n    }\n    bodyReader := bytes.NewReader([]byte(destbody))\n\n    var doc *goquery.Document\n    if doc, err = goquery.NewDocumentFromReader(bodyReader); err != nil {\n        mlog.LogInst().LogError(err.Error())\n        p.SetStatus(true, err.Error())\n        return p\n    }\n\n    var body string\n    if body, err = doc.Html(); err != nil {\n        mlog.LogInst().LogError(err.Error())\n        p.SetStatus(true, err.Error())\n        return p\n    }\n\n    p.SetBodyStr(body).SetHtmlParser(doc).SetStatus(false, \"\")\n\n    return p\n}\n\nfunc (this *HttpDownloader) downloadJson(p *page.Page, req *request.Request) *page.Page {\n    var err error\n    p, destbody := this.downloadFile(p, req)\n    if !p.IsSucc() {\n        return p\n    }\n\n    var body []byte\n    body = []byte(destbody)\n    mtype := req.GetResponceType()\n    if mtype == \"jsonp\" {\n        tmpstr := util.JsonpToJson(destbody)\n        body = []byte(tmpstr)\n    }\n\n    var r *simplejson.Json\n    if r, err = simplejson.NewJson(body); err != nil {\n        mlog.LogInst().LogError(string(body) + \"\\t\" + err.Error())\n        p.SetStatus(true, err.Error())\n        return p\n    }\n\n    \/\/ json result\n    p.SetBodyStr(string(body)).SetJson(r).SetStatus(false, \"\")\n\n    return p\n}\n\nfunc (this *HttpDownloader) downloadText(p *page.Page, req *request.Request) *page.Page {\n    p, destbody := this.downloadFile(p, req)\n    if !p.IsSucc() {\n        return p\n    }\n\n    p.SetBodyStr(destbody).SetStatus(false, \"\")\n    return p\n}\n<commit_msg>#修复了GzipReader没有Close内存泄露的可能<commit_after>package downloader\n\nimport (\n    \"bytes\"\n\n    \"github.com\/PuerkitoBio\/goquery\"\n    \"github.com\/bitly\/go-simplejson\"\n    \/\/    iconv \"github.com\/djimenez\/iconv-go\"\n    \"github.com\/hu17889\/go_spider\/core\/common\/mlog\"\n    \"github.com\/hu17889\/go_spider\/core\/common\/page\"\n    \"github.com\/hu17889\/go_spider\/core\/common\/request\"\n    \"github.com\/hu17889\/go_spider\/core\/common\/util\"\n    \/\/    \"golang.org\/x\/text\/encoding\/simplifiedchinese\"\n    \/\/    \"golang.org\/x\/text\/transform\"\n    \"io\"\n    \"io\/ioutil\"\n    \"net\/http\"\n    \"net\/url\"\n    \/\/\"fmt\"\n    \"golang.org\/x\/net\/html\/charset\"\n    \/\/    \"regexp\"\n    \/\/    \"golang.org\/x\/net\/html\"\n    \"strings\"\n\t\"compress\/gzip\"\n)\n\n\/\/ The HttpDownloader download page by package net\/http.\n\/\/ The \"html\" content is contained in dom parser of package goquery.\n\/\/ The \"json\" content is saved.\n\/\/ The \"jsonp\" content is modified to json.\n\/\/ The \"text\" content will save body plain text only.\n\/\/ The page result is saved in Page.\ntype HttpDownloader struct {\n}\n\nfunc NewHttpDownloader() *HttpDownloader {\n    return &HttpDownloader{}\n}\n\nfunc (this *HttpDownloader) Download(req *request.Request) *page.Page {\n    var mtype string\n    var p = page.NewPage(req)\n    mtype = req.GetResponceType()\n    switch mtype {\n    case \"html\":\n        return this.downloadHtml(p, req)\n    case \"json\":\n        fallthrough\n    case \"jsonp\":\n        return this.downloadJson(p, req)\n    case \"text\":\n        return this.downloadText(p, req)\n    default:\n        mlog.LogInst().LogError(\"error request type:\" + mtype)\n    }\n    return p\n}\n\n\/*\n\/\/ The acceptableCharset is test for whether Content-Type is UTF-8 or not\nfunc (this *HttpDownloader) acceptableCharset(contentTypes []string) bool {\n    \/\/ each type is like [text\/html; charset=UTF-8]\n    \/\/ we want the UTF-8 only\n    for _, cType := range contentTypes {\n        if strings.Index(cType, \"UTF-8\") != -1 || strings.Index(cType, \"utf-8\") != -1 {\n            return true\n        }\n    }\n    return false\n}\n\n\n\/\/ The getCharset used for parsing the header[\"Content-Type\"] string to get charset of the page.\nfunc (this *HttpDownloader) getCharset(header http.Header) string {\n    reg, err := regexp.Compile(\"charset=(.*)$\")\n    if err != nil {\n        mlog.LogInst().LogError(err.Error())\n        return \"\"\n    }\n\n    var charset string\n    for _, cType := range header[\"Content-Type\"] {\n        substrings := reg.FindStringSubmatch(cType)\n        if len(substrings) == 2 {\n            charset = substrings[1]\n        }\n    }\n\n    return charset\n}\n\n\n\n\n\/\/ Use golang.org\/x\/text\/encoding. Get page body and change it to utf-8\nfunc (this *HttpDownloader) changeCharsetEncoding(charset string, sor io.ReadCloser) string {\n    ischange := true\n    var tr transform.Transformer\n    cs := strings.ToLower(charset)\n    if cs == \"gbk\" {\n        tr = simplifiedchinese.GBK.NewDecoder()\n    } else if cs == \"gb18030\" {\n        tr = simplifiedchinese.GB18030.NewDecoder()\n    } else if cs == \"hzgb2312\" || cs == \"gb2312\" || cs == \"hz-gb2312\" {\n        tr = simplifiedchinese.HZGB2312.NewDecoder()\n    } else {\n        ischange = false\n    }\n\n    var destReader io.Reader\n    if ischange {\n        transReader := transform.NewReader(sor, tr)\n        destReader = transReader\n    } else {\n        destReader = sor\n    }\n\n    var sorbody []byte\n    var err error\n    if sorbody, err = ioutil.ReadAll(destReader); err != nil {\n        mlog.LogInst().LogError(err.Error())\n        return \"\"\n    }\n    bodystr := string(sorbody)\n\n    return bodystr\n}\n\n\/\/ Use go-iconv. Get page body and change it to utf-8\n\nfunc (this *HttpDownloader) changeCharsetGoIconv(charset string, sor io.ReadCloser) string {\n    var err error\n    var converter *iconv.Converter\n    if charset != \"\" && strings.ToLower(charset) != \"utf-8\" && strings.ToLower(charset) != \"utf8\" {\n        converter, err = iconv.NewConverter(charset, \"utf-8\")\n        if err != nil {\n            mlog.LogInst().LogError(err.Error())\n            return \"\"\n        }\n        defer converter.Close()\n    }\n\n    var sorbody []byte\n    if sorbody, err = ioutil.ReadAll(sor); err != nil {\n        mlog.LogInst().LogError(err.Error())\n        return \"\"\n    }\n    bodystr := string(sorbody)\n\n    var destbody string\n    if converter != nil {\n        \/\/ convert to utf8\n        destbody, err = converter.ConvertString(bodystr)\n        if err != nil {\n            mlog.LogInst().LogError(err.Error())\n            return \"\"\n        }\n    } else {\n        destbody = bodystr\n    }\n    return destbody\n}\n*\/\n\n\/\/ Charset auto determine. Use golang.org\/x\/net\/html\/charset. Get page body and change it to utf-8\nfunc (this *HttpDownloader) changeCharsetEncodingAuto(contentTypeStr string, sor io.ReadCloser) string {\n    var err error\n    destReader, err := charset.NewReader(sor, contentTypeStr)\n\n    if err != nil {\n        mlog.LogInst().LogError(err.Error())\n        destReader = sor\n    }\n\n    var sorbody []byte\n    if sorbody, err = ioutil.ReadAll(destReader); err != nil {\n        mlog.LogInst().LogError(err.Error())\n        \/\/ For gb2312, an error will be returned.\n        \/\/ Error like: simplifiedchinese: invalid GBK encoding\n        \/\/ return \"\"\n    }\n    \/\/e,name,certain := charset.DetermineEncoding(sorbody,contentTypeStr)\n    bodystr := string(sorbody)\n\n    return bodystr\n}\n\nfunc (this *HttpDownloader) changeCharsetEncodingAutoGzipSupport(contentTypeStr string, sor io.ReadCloser) string {\n\tvar err error\n\tgzipReader, err := gzip.NewReader(sor)\n\tdefer gzipReader.Close()\n\tif err != nil {\n\t\tmlog.LogInst().LogError(err.Error())\n\t\treturn \"\"\n\t}\n\tdestReader, err := charset.NewReader(gzipReader, contentTypeStr)\n\n\tif err != nil {\n\t\tmlog.LogInst().LogError(err.Error())\n\t\tdestReader = sor\n\t}\n\n\tvar sorbody []byte\n\tif sorbody, err = ioutil.ReadAll(destReader); err != nil {\n\t\tmlog.LogInst().LogError(err.Error())\n\t\t\/\/ For gb2312, an error will be returned.\n\t\t\/\/ Error like: simplifiedchinese: invalid GBK encoding\n\t\t\/\/ return \"\"\n\t}\n\t\/\/e,name,certain := charset.DetermineEncoding(sorbody,contentTypeStr)\n\tbodystr := string(sorbody)\n\n\treturn bodystr\n}\n\n\/\/ choose http GET\/method to download\nfunc connectByHttp(p *page.Page, req *request.Request) (*http.Response, error) {\n    client := &http.Client{\n        CheckRedirect: req.GetRedirectFunc(),\n    }\n\n    httpreq, err := http.NewRequest(req.GetMethod(), req.GetUrl(), strings.NewReader(req.GetPostdata()))\n    if header := req.GetHeader(); header != nil {\n        httpreq.Header = req.GetHeader()\n    }\n\n    if cookies := req.GetCookies(); cookies != nil {\n        for i := range cookies {\n            httpreq.AddCookie(cookies[i])\n        }\n    }\n\n    var resp *http.Response\n    if resp, err = client.Do(httpreq); err != nil {\n        if e, ok := err.(*url.Error); ok && e.Err != nil && e.Err.Error() == \"normal\" {\n            \/\/  normal\n        } else {\n            mlog.LogInst().LogError(err.Error())\n            p.SetStatus(true, err.Error())\n            \/\/fmt.Printf(\"client do error %v \\r\\n\", err)\n            return nil, err\n        }\n    }\n\n    return resp, nil\n}\n\n\/\/ choose a proxy server to excute http GET\/method to download\nfunc connectByHttpProxy(p *page.Page, in_req *request.Request) (*http.Response, error) {\n    request, _ := http.NewRequest(\"GET\", in_req.GetUrl(), nil)\n    proxy, err := url.Parse(in_req.GetProxyHost())\n    if err != nil {\n        return nil, err\n    }\n    client := &http.Client{\n        Transport: &http.Transport{\n            Proxy: http.ProxyURL(proxy),\n        },\n    }\n    resp, err := client.Do(request)\n    if err != nil {\n        return nil, err\n    }\n    return resp, nil\n\n}\n\n\/\/ Download file and change the charset of page charset.\nfunc (this *HttpDownloader) downloadFile(p *page.Page, req *request.Request) (*page.Page, string) {\n    var err error\n    var urlstr string\n    if urlstr = req.GetUrl(); len(urlstr) == 0 {\n        mlog.LogInst().LogError(\"url is empty\")\n        p.SetStatus(true, \"url is empty\")\n        return p, \"\"\n    }\n\n    var resp *http.Response\n\n    if proxystr := req.GetProxyHost(); len(proxystr) != 0 {\n        \/\/using http proxy\n        \/\/fmt.Print(\"HttpProxy Enter \",proxystr,\"\\n\")\n        resp, err = connectByHttpProxy(p, req)\n    } else {\n        \/\/normal http download\n        \/\/fmt.Print(\"Http Normal Enter \\n\",proxystr,\"\\n\")\n        resp, err = connectByHttp(p, req)\n    }\n\n    if err != nil {\n        return p, \"\"\n    }\n\n    \/\/b, _ := ioutil.ReadAll(resp.Body)\n    \/\/fmt.Printf(\"Resp body %v \\r\\n\", string(b))\n\n    p.SetHeader(resp.Header)\n    p.SetCookies(resp.Cookies())\n\n    \/\/ get converter to utf-8\n\tvar bodyStr string\n\tif resp.Header.Get(\"Content-Encoding\") == \"gzip\" {\n\t\tbodyStr = this.changeCharsetEncodingAutoGzipSupport(resp.Header.Get(\"Content-Type\"), resp.Body)\n\t} else {\n\t\tbodyStr = this.changeCharsetEncodingAuto(resp.Header.Get(\"Content-Type\"), resp.Body)\n\t}\n    \/\/fmt.Printf(\"utf-8 body %v \\r\\n\", bodyStr)\n    defer resp.Body.Close()\n    return p, bodyStr\n}\n\nfunc (this *HttpDownloader) downloadHtml(p *page.Page, req *request.Request) *page.Page {\n    var err error\n    p, destbody := this.downloadFile(p, req)\n    \/\/fmt.Printf(\"Destbody %v \\r\\n\", destbody)\n    if !p.IsSucc() {\n        \/\/fmt.Print(\"Page error \\r\\n\")\n        return p\n    }\n    bodyReader := bytes.NewReader([]byte(destbody))\n\n    var doc *goquery.Document\n    if doc, err = goquery.NewDocumentFromReader(bodyReader); err != nil {\n        mlog.LogInst().LogError(err.Error())\n        p.SetStatus(true, err.Error())\n        return p\n    }\n\n    var body string\n    if body, err = doc.Html(); err != nil {\n        mlog.LogInst().LogError(err.Error())\n        p.SetStatus(true, err.Error())\n        return p\n    }\n\n    p.SetBodyStr(body).SetHtmlParser(doc).SetStatus(false, \"\")\n\n    return p\n}\n\nfunc (this *HttpDownloader) downloadJson(p *page.Page, req *request.Request) *page.Page {\n    var err error\n    p, destbody := this.downloadFile(p, req)\n    if !p.IsSucc() {\n        return p\n    }\n\n    var body []byte\n    body = []byte(destbody)\n    mtype := req.GetResponceType()\n    if mtype == \"jsonp\" {\n        tmpstr := util.JsonpToJson(destbody)\n        body = []byte(tmpstr)\n    }\n\n    var r *simplejson.Json\n    if r, err = simplejson.NewJson(body); err != nil {\n        mlog.LogInst().LogError(string(body) + \"\\t\" + err.Error())\n        p.SetStatus(true, err.Error())\n        return p\n    }\n\n    \/\/ json result\n    p.SetBodyStr(string(body)).SetJson(r).SetStatus(false, \"\")\n\n    return p\n}\n\nfunc (this *HttpDownloader) downloadText(p *page.Page, req *request.Request) *page.Page {\n    p, destbody := this.downloadFile(p, req)\n    if !p.IsSucc() {\n        return p\n    }\n\n    p.SetBodyStr(destbody).SetStatus(false, \"\")\n    return p\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/consul\/api\"\n\t\"github.com\/nu7hatch\/gouuid\"\n\n\t\"code.cloudfoundry.org\/auctioneer\"\n\t\"code.cloudfoundry.org\/auctioneer\/auctionmetricemitterdelegate\"\n\t\"code.cloudfoundry.org\/auctioneer\/auctionrunnerdelegate\"\n\t\"code.cloudfoundry.org\/auctioneer\/handlers\"\n\t\"code.cloudfoundry.org\/bbs\"\n\t\"code.cloudfoundry.org\/consuladapter\"\n\t\"code.cloudfoundry.org\/locket\"\n\t\"code.cloudfoundry.org\/rep\"\n\t\"github.com\/cloudfoundry-incubator\/cf-debug-server\"\n\tcf_lager \"github.com\/cloudfoundry-incubator\/cf-lager\"\n\t\"github.com\/cloudfoundry-incubator\/cf_http\"\n\t\"github.com\/pivotal-golang\/lager\"\n\t\"github.com\/pivotal-golang\/localip\"\n\n\t\"code.cloudfoundry.org\/auction\/auctionrunner\"\n\t\"code.cloudfoundry.org\/auction\/auctiontypes\"\n\t\"github.com\/cloudfoundry\/dropsonde\"\n\t\"github.com\/cloudfoundry\/gunk\/workpool\"\n\t\"github.com\/pivotal-golang\/clock\"\n\t\"github.com\/tedsuo\/ifrit\"\n\t\"github.com\/tedsuo\/ifrit\/grouper\"\n\t\"github.com\/tedsuo\/ifrit\/http_server\"\n\t\"github.com\/tedsuo\/ifrit\/sigmon\"\n)\n\nvar communicationTimeout = flag.Duration(\n\t\"communicationTimeout\",\n\t10*time.Second,\n\t\"Timeout applied to all HTTP requests.\",\n)\n\nvar cellStateTimeout = flag.Duration(\n\t\"cellStateTimeout\",\n\t1*time.Second,\n\t\"Timeout applied to HTTP requests to the Cell State endpoint.\",\n)\n\nvar consulCluster = flag.String(\n\t\"consulCluster\",\n\t\"\",\n\t\"comma-separated list of consul server addresses (ip:port)\",\n)\n\nvar dropsondePort = flag.Int(\n\t\"dropsondePort\",\n\t3457,\n\t\"port the local metron agent is listening on\",\n)\n\nvar lockTTL = flag.Duration(\n\t\"lockTTL\",\n\tlocket.LockTTL,\n\t\"TTL for service lock\",\n)\n\nvar lockRetryInterval = flag.Duration(\n\t\"lockRetryInterval\",\n\tlocket.RetryInterval,\n\t\"interval to wait before retrying a failed lock acquisition\",\n)\n\nvar listenAddr = flag.String(\n\t\"listenAddr\",\n\t\"0.0.0.0:9016\",\n\t\"host:port to serve auction and LRP stop requests on\",\n)\n\nvar bbsAddress = flag.String(\n\t\"bbsAddress\",\n\t\"\",\n\t\"Address to the BBS Server\",\n)\n\nvar bbsCACert = flag.String(\n\t\"bbsCACert\",\n\t\"\",\n\t\"path to certificate authority cert used for mutually authenticated TLS BBS communication\",\n)\n\nvar bbsClientCert = flag.String(\n\t\"bbsClientCert\",\n\t\"\",\n\t\"path to client cert used for mutually authenticated TLS BBS communication\",\n)\n\nvar bbsClientKey = flag.String(\n\t\"bbsClientKey\",\n\t\"\",\n\t\"path to client key used for mutually authenticated TLS BBS communication\",\n)\n\nvar bbsClientSessionCacheSize = flag.Int(\n\t\"bbsClientSessionCacheSize\",\n\t0,\n\t\"Capacity of the ClientSessionCache option on the TLS configuration. If zero, golang's default will be used\",\n)\n\nvar bbsMaxIdleConnsPerHost = flag.Int(\n\t\"bbsMaxIdleConnsPerHost\",\n\t0,\n\t\"Controls the maximum number of idle (keep-alive) connctions per host. If zero, golang's default will be used\",\n)\n\nvar auctionRunnerWorkers = flag.Int(\n\t\"auctionRunnerWorkers\",\n\t1000,\n\t\"Max concurrency for cell operations in the auction runner\",\n)\n\nvar startingContainerWeight = flag.Float64(\n\t\"startingContainerWeight\",\n\t0.25,\n\t\"Factor to bias against cells with starting containers (0.0 - 1.0)\",\n)\n\nconst (\n\tauctionRunnerTimeout = 10 * time.Second\n\tdropsondeOrigin      = \"auctioneer\"\n\tserverProtocol       = \"http\"\n)\n\nfunc main() {\n\tcf_debug_server.AddFlags(flag.CommandLine)\n\tcf_lager.AddFlags(flag.CommandLine)\n\tflag.Parse()\n\n\tcf_http.Initialize(*communicationTimeout)\n\n\tlogger, reconfigurableSink := cf_lager.New(\"auctioneer\")\n\tinitializeDropsonde(logger)\n\n\tif err := validateBBSAddress(); err != nil {\n\t\tlogger.Fatal(\"invalid-bbs-address\", err)\n\t}\n\n\tconsulClient, err := consuladapter.NewClientFromUrl(*consulCluster)\n\tif err != nil {\n\t\tlogger.Fatal(\"new-client-failed\", err)\n\t}\n\n\tport, err := strconv.Atoi(strings.Split(*listenAddr, \":\")[1])\n\tif err != nil {\n\t\tlogger.Fatal(\"invalid-port\", err)\n\t}\n\n\tclock := clock.NewClock()\n\tauctioneerServiceClient := auctioneer.NewServiceClient(consulClient, clock)\n\n\tauctionRunner := initializeAuctionRunner(logger, *cellStateTimeout,\n\t\tinitializeBBSClient(logger), *startingContainerWeight)\n\tauctionServer := initializeAuctionServer(logger, auctionRunner)\n\tlockMaintainer := initializeLockMaintainer(logger, auctioneerServiceClient, port)\n\tregistrationRunner := initializeRegistrationRunner(logger, consulClient, clock, port)\n\n\tmembers := grouper.Members{\n\t\t{\"lock-maintainer\", lockMaintainer},\n\t\t{\"auction-runner\", auctionRunner},\n\t\t{\"auction-server\", auctionServer},\n\t\t{\"registration-runner\", registrationRunner},\n\t}\n\n\tif dbgAddr := cf_debug_server.DebugAddress(flag.CommandLine); dbgAddr != \"\" {\n\t\tmembers = append(grouper.Members{\n\t\t\t{\"debug-server\", cf_debug_server.Runner(dbgAddr, reconfigurableSink)},\n\t\t}, members...)\n\t}\n\n\tgroup := grouper.NewOrdered(os.Interrupt, members)\n\n\tmonitor := ifrit.Invoke(sigmon.New(group))\n\n\tlogger.Info(\"started\")\n\n\terr = <-monitor.Wait()\n\tif err != nil {\n\t\tlogger.Error(\"exited-with-failure\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlogger.Info(\"exited\")\n}\n\nfunc initializeAuctionRunner(logger lager.Logger, cellStateTimeout time.Duration, bbsClient bbs.InternalClient, startingContainerWeight float64) auctiontypes.AuctionRunner {\n\thttpClient := cf_http.NewClient()\n\tstateClient := cf_http.NewCustomTimeoutClient(cellStateTimeout)\n\trepClientFactory := rep.NewClientFactory(httpClient, stateClient)\n\n\tdelegate := auctionrunnerdelegate.New(repClientFactory, bbsClient, logger)\n\tmetricEmitter := auctionmetricemitterdelegate.New()\n\tworkPool, err := workpool.NewWorkPool(*auctionRunnerWorkers)\n\tif err != nil {\n\t\tlogger.Fatal(\"failed-to-construct-auction-runner-workpool\", err, lager.Data{\"num-workers\": *auctionRunnerWorkers}) \/\/ should never happen\n\t}\n\n\treturn auctionrunner.New(\n\t\tlogger,\n\t\tdelegate,\n\t\tmetricEmitter,\n\t\tclock.NewClock(),\n\t\tworkPool,\n\t\tstartingContainerWeight,\n\t)\n}\n\nfunc initializeDropsonde(logger lager.Logger) {\n\tdropsondeDestination := fmt.Sprint(\"localhost:\", *dropsondePort)\n\terr := dropsonde.Initialize(dropsondeDestination, dropsondeOrigin)\n\tif err != nil {\n\t\tlogger.Error(\"failed to initialize dropsonde: %v\", err)\n\t}\n}\n\nfunc initializeAuctionServer(logger lager.Logger, runner auctiontypes.AuctionRunner) ifrit.Runner {\n\treturn http_server.New(*listenAddr, handlers.New(runner, logger))\n}\n\nfunc initializeRegistrationRunner(logger lager.Logger, consulClient consuladapter.Client, clock clock.Clock, port int) ifrit.Runner {\n\tregistration := &api.AgentServiceRegistration{\n\t\tName: \"auctioneer\",\n\t\tPort: port,\n\t\tCheck: &api.AgentServiceCheck{\n\t\t\tTTL: \"3s\",\n\t\t},\n\t}\n\treturn locket.NewRegistrationRunner(logger, registration, consulClient, locket.RetryInterval, clock)\n}\n\nfunc initializeLockMaintainer(logger lager.Logger, serviceClient auctioneer.ServiceClient, port int) ifrit.Runner {\n\tuuid, err := uuid.NewV4()\n\tif err != nil {\n\t\tlogger.Fatal(\"Couldn't generate uuid\", err)\n\t}\n\n\tlocalIP, err := localip.LocalIP()\n\tif err != nil {\n\t\tlogger.Fatal(\"Couldn't determine local IP\", err)\n\t}\n\n\taddress := fmt.Sprintf(\"%s:\/\/%s:%d\", serverProtocol, localIP, port)\n\tauctioneerPresence := auctioneer.NewPresence(uuid.String(), address)\n\n\tlockMaintainer, err := serviceClient.NewAuctioneerLockRunner(logger, auctioneerPresence, *lockRetryInterval, *lockTTL)\n\tif err != nil {\n\t\tlogger.Fatal(\"Couldn't create lock maintainer\", err)\n\t}\n\n\treturn lockMaintainer\n}\n\nfunc validateBBSAddress() error {\n\tif *bbsAddress == \"\" {\n\t\treturn errors.New(\"bbsAddress is required\")\n\t}\n\treturn nil\n}\n\nfunc initializeBBSClient(logger lager.Logger) bbs.InternalClient {\n\tbbsURL, err := url.Parse(*bbsAddress)\n\tif err != nil {\n\t\tlogger.Fatal(\"Invalid BBS URL\", err)\n\t}\n\n\tif bbsURL.Scheme != \"https\" {\n\t\treturn bbs.NewClient(*bbsAddress)\n\t}\n\n\tbbsClient, err := bbs.NewSecureClient(*bbsAddress, *bbsCACert, *bbsClientCert, *bbsClientKey, *bbsClientSessionCacheSize, *bbsMaxIdleConnsPerHost)\n\tif err != nil {\n\t\tlogger.Fatal(\"Failed to configure secure BBS client\", err)\n\t}\n\treturn bbsClient\n}\n<commit_msg>Update and rename cf-debug-server -> debugserver<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/consul\/api\"\n\t\"github.com\/nu7hatch\/gouuid\"\n\n\t\"code.cloudfoundry.org\/auctioneer\"\n\t\"code.cloudfoundry.org\/auctioneer\/auctionmetricemitterdelegate\"\n\t\"code.cloudfoundry.org\/auctioneer\/auctionrunnerdelegate\"\n\t\"code.cloudfoundry.org\/auctioneer\/handlers\"\n\t\"code.cloudfoundry.org\/bbs\"\n\t\"code.cloudfoundry.org\/consuladapter\"\n\t\"code.cloudfoundry.org\/debugserver\"\n\t\"code.cloudfoundry.org\/locket\"\n\t\"code.cloudfoundry.org\/rep\"\n\tcf_lager \"github.com\/cloudfoundry-incubator\/cf-lager\"\n\t\"github.com\/cloudfoundry-incubator\/cf_http\"\n\t\"github.com\/pivotal-golang\/lager\"\n\t\"github.com\/pivotal-golang\/localip\"\n\n\t\"code.cloudfoundry.org\/auction\/auctionrunner\"\n\t\"code.cloudfoundry.org\/auction\/auctiontypes\"\n\t\"github.com\/cloudfoundry\/dropsonde\"\n\t\"github.com\/cloudfoundry\/gunk\/workpool\"\n\t\"github.com\/pivotal-golang\/clock\"\n\t\"github.com\/tedsuo\/ifrit\"\n\t\"github.com\/tedsuo\/ifrit\/grouper\"\n\t\"github.com\/tedsuo\/ifrit\/http_server\"\n\t\"github.com\/tedsuo\/ifrit\/sigmon\"\n)\n\nvar communicationTimeout = flag.Duration(\n\t\"communicationTimeout\",\n\t10*time.Second,\n\t\"Timeout applied to all HTTP requests.\",\n)\n\nvar cellStateTimeout = flag.Duration(\n\t\"cellStateTimeout\",\n\t1*time.Second,\n\t\"Timeout applied to HTTP requests to the Cell State endpoint.\",\n)\n\nvar consulCluster = flag.String(\n\t\"consulCluster\",\n\t\"\",\n\t\"comma-separated list of consul server addresses (ip:port)\",\n)\n\nvar dropsondePort = flag.Int(\n\t\"dropsondePort\",\n\t3457,\n\t\"port the local metron agent is listening on\",\n)\n\nvar lockTTL = flag.Duration(\n\t\"lockTTL\",\n\tlocket.LockTTL,\n\t\"TTL for service lock\",\n)\n\nvar lockRetryInterval = flag.Duration(\n\t\"lockRetryInterval\",\n\tlocket.RetryInterval,\n\t\"interval to wait before retrying a failed lock acquisition\",\n)\n\nvar listenAddr = flag.String(\n\t\"listenAddr\",\n\t\"0.0.0.0:9016\",\n\t\"host:port to serve auction and LRP stop requests on\",\n)\n\nvar bbsAddress = flag.String(\n\t\"bbsAddress\",\n\t\"\",\n\t\"Address to the BBS Server\",\n)\n\nvar bbsCACert = flag.String(\n\t\"bbsCACert\",\n\t\"\",\n\t\"path to certificate authority cert used for mutually authenticated TLS BBS communication\",\n)\n\nvar bbsClientCert = flag.String(\n\t\"bbsClientCert\",\n\t\"\",\n\t\"path to client cert used for mutually authenticated TLS BBS communication\",\n)\n\nvar bbsClientKey = flag.String(\n\t\"bbsClientKey\",\n\t\"\",\n\t\"path to client key used for mutually authenticated TLS BBS communication\",\n)\n\nvar bbsClientSessionCacheSize = flag.Int(\n\t\"bbsClientSessionCacheSize\",\n\t0,\n\t\"Capacity of the ClientSessionCache option on the TLS configuration. If zero, golang's default will be used\",\n)\n\nvar bbsMaxIdleConnsPerHost = flag.Int(\n\t\"bbsMaxIdleConnsPerHost\",\n\t0,\n\t\"Controls the maximum number of idle (keep-alive) connctions per host. If zero, golang's default will be used\",\n)\n\nvar auctionRunnerWorkers = flag.Int(\n\t\"auctionRunnerWorkers\",\n\t1000,\n\t\"Max concurrency for cell operations in the auction runner\",\n)\n\nvar startingContainerWeight = flag.Float64(\n\t\"startingContainerWeight\",\n\t0.25,\n\t\"Factor to bias against cells with starting containers (0.0 - 1.0)\",\n)\n\nconst (\n\tauctionRunnerTimeout = 10 * time.Second\n\tdropsondeOrigin      = \"auctioneer\"\n\tserverProtocol       = \"http\"\n)\n\nfunc main() {\n\tdebugserver.AddFlags(flag.CommandLine)\n\tcf_lager.AddFlags(flag.CommandLine)\n\tflag.Parse()\n\n\tcf_http.Initialize(*communicationTimeout)\n\n\tlogger, reconfigurableSink := cf_lager.New(\"auctioneer\")\n\tinitializeDropsonde(logger)\n\n\tif err := validateBBSAddress(); err != nil {\n\t\tlogger.Fatal(\"invalid-bbs-address\", err)\n\t}\n\n\tconsulClient, err := consuladapter.NewClientFromUrl(*consulCluster)\n\tif err != nil {\n\t\tlogger.Fatal(\"new-client-failed\", err)\n\t}\n\n\tport, err := strconv.Atoi(strings.Split(*listenAddr, \":\")[1])\n\tif err != nil {\n\t\tlogger.Fatal(\"invalid-port\", err)\n\t}\n\n\tclock := clock.NewClock()\n\tauctioneerServiceClient := auctioneer.NewServiceClient(consulClient, clock)\n\n\tauctionRunner := initializeAuctionRunner(logger, *cellStateTimeout,\n\t\tinitializeBBSClient(logger), *startingContainerWeight)\n\tauctionServer := initializeAuctionServer(logger, auctionRunner)\n\tlockMaintainer := initializeLockMaintainer(logger, auctioneerServiceClient, port)\n\tregistrationRunner := initializeRegistrationRunner(logger, consulClient, clock, port)\n\n\tmembers := grouper.Members{\n\t\t{\"lock-maintainer\", lockMaintainer},\n\t\t{\"auction-runner\", auctionRunner},\n\t\t{\"auction-server\", auctionServer},\n\t\t{\"registration-runner\", registrationRunner},\n\t}\n\n\tif dbgAddr := debugserver.DebugAddress(flag.CommandLine); dbgAddr != \"\" {\n\t\tmembers = append(grouper.Members{\n\t\t\t{\"debug-server\", debugserver.Runner(dbgAddr, reconfigurableSink)},\n\t\t}, members...)\n\t}\n\n\tgroup := grouper.NewOrdered(os.Interrupt, members)\n\n\tmonitor := ifrit.Invoke(sigmon.New(group))\n\n\tlogger.Info(\"started\")\n\n\terr = <-monitor.Wait()\n\tif err != nil {\n\t\tlogger.Error(\"exited-with-failure\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlogger.Info(\"exited\")\n}\n\nfunc initializeAuctionRunner(logger lager.Logger, cellStateTimeout time.Duration, bbsClient bbs.InternalClient, startingContainerWeight float64) auctiontypes.AuctionRunner {\n\thttpClient := cf_http.NewClient()\n\tstateClient := cf_http.NewCustomTimeoutClient(cellStateTimeout)\n\trepClientFactory := rep.NewClientFactory(httpClient, stateClient)\n\n\tdelegate := auctionrunnerdelegate.New(repClientFactory, bbsClient, logger)\n\tmetricEmitter := auctionmetricemitterdelegate.New()\n\tworkPool, err := workpool.NewWorkPool(*auctionRunnerWorkers)\n\tif err != nil {\n\t\tlogger.Fatal(\"failed-to-construct-auction-runner-workpool\", err, lager.Data{\"num-workers\": *auctionRunnerWorkers}) \/\/ should never happen\n\t}\n\n\treturn auctionrunner.New(\n\t\tlogger,\n\t\tdelegate,\n\t\tmetricEmitter,\n\t\tclock.NewClock(),\n\t\tworkPool,\n\t\tstartingContainerWeight,\n\t)\n}\n\nfunc initializeDropsonde(logger lager.Logger) {\n\tdropsondeDestination := fmt.Sprint(\"localhost:\", *dropsondePort)\n\terr := dropsonde.Initialize(dropsondeDestination, dropsondeOrigin)\n\tif err != nil {\n\t\tlogger.Error(\"failed to initialize dropsonde: %v\", err)\n\t}\n}\n\nfunc initializeAuctionServer(logger lager.Logger, runner auctiontypes.AuctionRunner) ifrit.Runner {\n\treturn http_server.New(*listenAddr, handlers.New(runner, logger))\n}\n\nfunc initializeRegistrationRunner(logger lager.Logger, consulClient consuladapter.Client, clock clock.Clock, port int) ifrit.Runner {\n\tregistration := &api.AgentServiceRegistration{\n\t\tName: \"auctioneer\",\n\t\tPort: port,\n\t\tCheck: &api.AgentServiceCheck{\n\t\t\tTTL: \"3s\",\n\t\t},\n\t}\n\treturn locket.NewRegistrationRunner(logger, registration, consulClient, locket.RetryInterval, clock)\n}\n\nfunc initializeLockMaintainer(logger lager.Logger, serviceClient auctioneer.ServiceClient, port int) ifrit.Runner {\n\tuuid, err := uuid.NewV4()\n\tif err != nil {\n\t\tlogger.Fatal(\"Couldn't generate uuid\", err)\n\t}\n\n\tlocalIP, err := localip.LocalIP()\n\tif err != nil {\n\t\tlogger.Fatal(\"Couldn't determine local IP\", err)\n\t}\n\n\taddress := fmt.Sprintf(\"%s:\/\/%s:%d\", serverProtocol, localIP, port)\n\tauctioneerPresence := auctioneer.NewPresence(uuid.String(), address)\n\n\tlockMaintainer, err := serviceClient.NewAuctioneerLockRunner(logger, auctioneerPresence, *lockRetryInterval, *lockTTL)\n\tif err != nil {\n\t\tlogger.Fatal(\"Couldn't create lock maintainer\", err)\n\t}\n\n\treturn lockMaintainer\n}\n\nfunc validateBBSAddress() error {\n\tif *bbsAddress == \"\" {\n\t\treturn errors.New(\"bbsAddress is required\")\n\t}\n\treturn nil\n}\n\nfunc initializeBBSClient(logger lager.Logger) bbs.InternalClient {\n\tbbsURL, err := url.Parse(*bbsAddress)\n\tif err != nil {\n\t\tlogger.Fatal(\"Invalid BBS URL\", err)\n\t}\n\n\tif bbsURL.Scheme != \"https\" {\n\t\treturn bbs.NewClient(*bbsAddress)\n\t}\n\n\tbbsClient, err := bbs.NewSecureClient(*bbsAddress, *bbsCACert, *bbsClientCert, *bbsClientKey, *bbsClientSessionCacheSize, *bbsMaxIdleConnsPerHost)\n\tif err != nil {\n\t\tlogger.Fatal(\"Failed to configure secure BBS client\", err)\n\t}\n\treturn bbsClient\n}\n<|endoftext|>"}
{"text":"<commit_before>package catalog\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc CommentString(\n\tintNames, floatNames []string, order, sizes []int,\n) string {\n\n\ttokens := []string{\"# Column contents:\"}\n\tfor i := range intNames {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%s\", intNames[i]))\n\t}\n\tfor i := range floatNames {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%s\", floatNames[i]))\n\t}\n\n\torderedTokens := []string{tokens[0]}\n\torderedSizes := []int{}\n\tfor _, idx := range order {\n\t\tif idx >= len(intNames)+len(floatNames) {\n\t\t\tpanic(\"Column ordering out of range.\")\n\t\t}\n\n\t\torderedTokens = append(orderedTokens, tokens[idx+1])\n\t\torderedSizes = append(orderedSizes, sizes[idx])\n\n\t}\n\n\tn := 0\n\tfor i := 1; i < len(orderedTokens); i++ {\n\t\tif orderedSizes[i-1] == 1 {\n\t\t\torderedTokens[i] = fmt.Sprintf(\"%s(%d)\", orderedTokens[i], n)\n\t\t} else {\n\t\t\torderedTokens[i] = fmt.Sprintf(\"%s(%d-%d)\", orderedTokens[i],\n\t\t\t\tn, n+orderedSizes[i-1]-1)\n\t\t}\n\t\tn += orderedSizes[i-1]\n\t}\n\n\treturn strings.Join(orderedTokens, \" \")\n}\n\nfunc FormatCols(intCols [][]int, floatCols [][]float64, order []int) []string {\n\tif (len(intCols) == 0 && len(floatCols) == 0) ||\n\t\t(len(intCols) > 0 && len(intCols[0]) == 0) ||\n\t\t(len(floatCols) > 0 && len(floatCols[0]) == 0) {\n\t\treturn []string{}\n\t}\n\n\tformattedIntCols := make([][]string, len(intCols))\n\tformattedFloatCols := make([][]string, len(floatCols))\n\n\theight := -1\n\tfor i := range intCols {\n\t\tformattedIntCols[i] = formatIntCol(intCols[i])\n\t\tif height == -1 {\n\t\t\theight = len(intCols[i])\n\t\t} else if height != len(intCols[i]) {\n\t\t\tpanic(\"Columns of unequal height.\")\n\t\t}\n\t}\n\n\tfor i := range floatCols {\n\t\tformattedFloatCols[i] = formatFloatCol(floatCols[i])\n\t\tif height == -1 {\n\t\t\theight = len(floatCols[i])\n\t\t} else if height != len(floatCols[i]) {\n\t\t\tpanic(\"Columns of unequal height.\")\n\t\t}\n\t}\n\n\torderedCols := [][]string{}\n\tfor _, idx := range order {\n\t\tif idx >= len(intCols)+len(floatCols) {\n\t\t\tpanic(\"Column ordering out of range.\")\n\t\t}\n\n\t\tif idx < len(intCols) {\n\t\t\torderedCols = append(orderedCols, formattedIntCols[idx])\n\t\t} else {\n\t\t\tidx -= len(intCols)\n\t\t\torderedCols = append(orderedCols, formattedFloatCols[idx])\n\t\t}\n\t}\n\n\tlines := []string{}\n\ttokens := make([]string, len(intCols)+len(floatCols))\n\tfor i := 0; i < height; i++ {\n\t\tfor j := range orderedCols {\n\t\t\ttokens[j] = orderedCols[j][i]\n\t\t}\n\t\tline := strings.Join(tokens, \" \")\n\t\tlines = append(lines, line)\n\t}\n\n\treturn lines\n}\n\nfunc formatIntCol(col []int) []string {\n\twidth := len(fmt.Sprintf(\"%d\", col[0]))\n\tfor i := 1; i < len(col); i++ {\n\t\tn := len(fmt.Sprintf(\"%d\", col[i]))\n\t\tif n > width {\n\t\t\twidth = n\n\t\t}\n\t}\n\n\tout := []string{}\n\tfor i := range col {\n\t\tout = append(out, fmt.Sprintf(\"%*d\", width, col[i]))\n\t}\n\n\treturn out\n}\n\nfunc formatFloatCol(col []float64) []string {\n\twidth := len(fmt.Sprintf(\"%.6g\", col[0]))\n\tfor i := 1; i < len(col); i++ {\n\t\tn := len(fmt.Sprintf(\"%.6g\", col[i]))\n\t\tif n > width {\n\t\t\twidth = n\n\t\t}\n\t}\n\n\tout := []string{}\n\tfor i := range col {\n\t\tout = append(out, fmt.Sprintf(\"%*.6g\", width, col[i]))\n\t}\n\n\treturn out\n}\n\nfunc Uncomment(lines []string) (out []string, lineNums []int) {\n\tfor i := range lines {\n\t\tidx := strings.Index(lines[i], \"#\")\n\t\tif idx >= 0 {\n\t\t\tlines[i] = lines[i][:idx]\n\t\t}\n\t}\n\n\tout = []string{}\n\tlineNums = []int{}\n\tfor i := range lines {\n\t\ttrimmed := strings.Trim(lines[i], \" \\t\")\n\t\tif len(trimmed) > 0 {\n\t\t\tout = append(out, trimmed)\n\t\t\tlineNums = append(lineNums, i+1)\n\t\t}\n\t}\n\treturn out, lineNums\n}\n\nfunc ParseCols(\n\tlines []string, intIdxs, floatIdxs []int,\n) ([][]int, [][]float64, error) {\n\tif len(intIdxs) == 0 && len(floatIdxs) == 0 {\n\t\treturn nil, nil, nil\n\t}\n\n\tfLines, lineNums := Uncomment(lines)\n\tminWidth := -1\n\tfor _, x := range intIdxs {\n\t\tif x > minWidth {\n\t\t\tminWidth = x\n\t\t}\n\t}\n\tfor _, x := range floatIdxs {\n\t\tif x > minWidth {\n\t\t\tminWidth = x\n\t\t}\n\t}\n\tminWidth++\n\n\tintCols := make([][]int, len(intIdxs))\n\tfloatCols := make([][]float64, len(floatIdxs))\n\n\tfor i := range fLines {\n\t\ttoks := tokenize(fLines[i])\n\n\t\tif len(toks) < minWidth {\n\t\t\treturn nil, nil, fmt.Errorf(\n\t\t\t\t\"Line %d has %d columns, but I need %d columns.\",\n\t\t\t\tlineNums[i], len(toks), minWidth,\n\t\t\t)\n\t\t} else {\n\t\t\tfor colIdx, j := range intIdxs {\n\t\t\t\tn, err := strconv.Atoi(toks[j])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, fmt.Errorf(\"Cannot parse column %d of \"+\n\t\t\t\t\t\t\"line %d, '%s', to an int.\", j, lineNums[i], toks[j])\n\t\t\t\t}\n\t\t\t\tintCols[colIdx] = append(intCols[j], n)\n\t\t\t}\n\n\t\t\tfor colIdx, j := range floatIdxs {\n\t\t\t\tx, err := strconv.ParseFloat(toks[j], 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, fmt.Errorf(\"Cannot parse column %d of \"+\n\t\t\t\t\t\t\"line %d, '%s', to a float.\", j, lineNums[i], toks[j])\n\t\t\t\t}\n\t\t\t\tfloatCols[colIdx] = append(floatCols[colIdx], x)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn intCols, floatCols, nil\n}\n\nfunc tokenize(line string) []string {\n\ttoks := strings.Split(line, \" \")\n\tfToks := []string{}\n\tfor i := range toks {\n\t\tif len(toks[i]) > 0 {\n\t\t\tfToks = append(fToks, toks[i])\n\t\t}\n\t}\n\treturn fToks\n}\n<commit_msg>Fixed bug in parsing of int columns.<commit_after>package catalog\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc CommentString(\n\tintNames, floatNames []string, order, sizes []int,\n) string {\n\n\ttokens := []string{\"# Column contents:\"}\n\tfor i := range intNames {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%s\", intNames[i]))\n\t}\n\tfor i := range floatNames {\n\t\ttokens = append(tokens, fmt.Sprintf(\"%s\", floatNames[i]))\n\t}\n\n\torderedTokens := []string{tokens[0]}\n\torderedSizes := []int{}\n\tfor _, idx := range order {\n\t\tif idx >= len(intNames)+len(floatNames) {\n\t\t\tpanic(\"Column ordering out of range.\")\n\t\t}\n\n\t\torderedTokens = append(orderedTokens, tokens[idx+1])\n\t\torderedSizes = append(orderedSizes, sizes[idx])\n\n\t}\n\n\tn := 0\n\tfor i := 1; i < len(orderedTokens); i++ {\n\t\tif orderedSizes[i-1] == 1 {\n\t\t\torderedTokens[i] = fmt.Sprintf(\"%s(%d)\", orderedTokens[i], n)\n\t\t} else {\n\t\t\torderedTokens[i] = fmt.Sprintf(\"%s(%d-%d)\", orderedTokens[i],\n\t\t\t\tn, n+orderedSizes[i-1]-1)\n\t\t}\n\t\tn += orderedSizes[i-1]\n\t}\n\n\treturn strings.Join(orderedTokens, \" \")\n}\n\nfunc FormatCols(intCols [][]int, floatCols [][]float64, order []int) []string {\n\tif (len(intCols) == 0 && len(floatCols) == 0) ||\n\t\t(len(intCols) > 0 && len(intCols[0]) == 0) ||\n\t\t(len(floatCols) > 0 && len(floatCols[0]) == 0) {\n\t\treturn []string{}\n\t}\n\n\tformattedIntCols := make([][]string, len(intCols))\n\tformattedFloatCols := make([][]string, len(floatCols))\n\n\theight := -1\n\tfor i := range intCols {\n\t\tformattedIntCols[i] = formatIntCol(intCols[i])\n\t\tif height == -1 {\n\t\t\theight = len(intCols[i])\n\t\t} else if height != len(intCols[i]) {\n\t\t\tpanic(\"Columns of unequal height.\")\n\t\t}\n\t}\n\n\tfor i := range floatCols {\n\t\tformattedFloatCols[i] = formatFloatCol(floatCols[i])\n\t\tif height == -1 {\n\t\t\theight = len(floatCols[i])\n\t\t} else if height != len(floatCols[i]) {\n\t\t\tpanic(\"Columns of unequal height.\")\n\t\t}\n\t}\n\n\torderedCols := [][]string{}\n\tfor _, idx := range order {\n\t\tif idx >= len(intCols)+len(floatCols) {\n\t\t\tpanic(\"Column ordering out of range.\")\n\t\t}\n\n\t\tif idx < len(intCols) {\n\t\t\torderedCols = append(orderedCols, formattedIntCols[idx])\n\t\t} else {\n\t\t\tidx -= len(intCols)\n\t\t\torderedCols = append(orderedCols, formattedFloatCols[idx])\n\t\t}\n\t}\n\n\tlines := []string{}\n\ttokens := make([]string, len(intCols)+len(floatCols))\n\tfor i := 0; i < height; i++ {\n\t\tfor j := range orderedCols {\n\t\t\ttokens[j] = orderedCols[j][i]\n\t\t}\n\t\tline := strings.Join(tokens, \" \")\n\t\tlines = append(lines, line)\n\t}\n\n\treturn lines\n}\n\nfunc formatIntCol(col []int) []string {\n\twidth := len(fmt.Sprintf(\"%d\", col[0]))\n\tfor i := 1; i < len(col); i++ {\n\t\tn := len(fmt.Sprintf(\"%d\", col[i]))\n\t\tif n > width {\n\t\t\twidth = n\n\t\t}\n\t}\n\n\tout := []string{}\n\tfor i := range col {\n\t\tout = append(out, fmt.Sprintf(\"%*d\", width, col[i]))\n\t}\n\n\treturn out\n}\n\nfunc formatFloatCol(col []float64) []string {\n\twidth := len(fmt.Sprintf(\"%.6g\", col[0]))\n\tfor i := 1; i < len(col); i++ {\n\t\tn := len(fmt.Sprintf(\"%.6g\", col[i]))\n\t\tif n > width {\n\t\t\twidth = n\n\t\t}\n\t}\n\n\tout := []string{}\n\tfor i := range col {\n\t\tout = append(out, fmt.Sprintf(\"%*.6g\", width, col[i]))\n\t}\n\n\treturn out\n}\n\nfunc Uncomment(lines []string) (out []string, lineNums []int) {\n\tfor i := range lines {\n\t\tidx := strings.Index(lines[i], \"#\")\n\t\tif idx >= 0 {\n\t\t\tlines[i] = lines[i][:idx]\n\t\t}\n\t}\n\n\tout = []string{}\n\tlineNums = []int{}\n\tfor i := range lines {\n\t\ttrimmed := strings.Trim(lines[i], \" \\t\")\n\t\tif len(trimmed) > 0 {\n\t\t\tout = append(out, trimmed)\n\t\t\tlineNums = append(lineNums, i+1)\n\t\t}\n\t}\n\treturn out, lineNums\n}\n\nfunc ParseCols(\n\tlines []string, intIdxs, floatIdxs []int,\n) ([][]int, [][]float64, error) {\n\tif len(intIdxs) == 0 && len(floatIdxs) == 0 {\n\t\treturn nil, nil, nil\n\t}\n\n\tfLines, lineNums := Uncomment(lines)\n\tminWidth := -1\n\tfor _, x := range intIdxs {\n\t\tif x > minWidth {\n\t\t\tminWidth = x\n\t\t}\n\t}\n\tfor _, x := range floatIdxs {\n\t\tif x > minWidth {\n\t\t\tminWidth = x\n\t\t}\n\t}\n\tminWidth++\n\n\tintCols := make([][]int, len(intIdxs))\n\tfloatCols := make([][]float64, len(floatIdxs))\n\t\n\tfor i := range fLines {\n\t\ttoks := tokenize(fLines[i])\n\n\t\tif len(toks) < minWidth {\n\t\t\treturn nil, nil, fmt.Errorf(\n\t\t\t\t\"Line %d has %d columns, but I need %d columns.\",\n\t\t\t\tlineNums[i], len(toks), minWidth,\n\t\t\t)\n\t\t} else {\n\t\t\tfor colIdx, j := range intIdxs {\n\t\t\t\tn, err := strconv.Atoi(toks[j])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, fmt.Errorf(\"Cannot parse column %d of \"+\n\t\t\t\t\t\t\"line %d, '%s', to an int.\", j, lineNums[i], toks[j])\n\t\t\t\t}\n\t\t\t\tintCols[colIdx] = append(intCols[colIdx], n)\n\t\t\t}\n\n\t\t\tfor colIdx, j := range floatIdxs {\n\t\t\t\tx, err := strconv.ParseFloat(toks[j], 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, nil, fmt.Errorf(\"Cannot parse column %d of \"+\n\t\t\t\t\t\t\"line %d, '%s', to a float.\", j, lineNums[i], toks[j])\n\t\t\t\t}\n\t\t\t\tfloatCols[colIdx] = append(floatCols[colIdx], x)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn intCols, floatCols, nil\n}\n\nfunc tokenize(line string) []string {\n\ttoks := strings.Split(line, \" \")\n\tfToks := []string{}\n\tfor i := range toks {\n\t\tif len(toks[i]) > 0 {\n\t\t\tfToks = append(fToks, toks[i])\n\t\t}\n\t}\n\treturn fToks\n}\n<|endoftext|>"}
{"text":"<commit_before>package cliedit\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/elves\/elvish\/cli\"\n\t\"github.com\/elves\/elvish\/diag\"\n\t\"github.com\/elves\/elvish\/eval\"\n\t\"github.com\/elves\/elvish\/eval\/vals\"\n\t\"github.com\/elves\/elvish\/eval\/vars\"\n\t\"github.com\/xiaq\/persistent\/hashmap\"\n)\n\nfunc initAPI(app *cli.App, ev *eval.Evaler, ns eval.Ns) {\n\tinitMaxHeight(app, ns)\n\tinitBeforeReadline(app, ev, ns)\n\tinitAfterReadline(app, ev, ns)\n\tinitInsert(app, ev, ns)\n\n\tinitMiscBuiltins(app, ns)\n\tinitBufferBuiltins(app, ns)\n}\n\nfunc initMaxHeight(app *cli.App, ns eval.Ns) {\n\tmaxHeight := -1\n\tmaxHeightVar := vars.FromPtr(&maxHeight)\n\tapp.Config.MaxHeight = func() int { return maxHeightVar.Get().(int) }\n\tns.Add(\"max-height\", maxHeightVar)\n}\n\nfunc initBeforeReadline(app *cli.App, ev *eval.Evaler, ns eval.Ns) {\n\thook := vals.EmptyList\n\thookVar := vars.FromPtr(&hook)\n\tns[\"before-readline\"] = hookVar\n\tapp.Config.BeforeReadline = func() {\n\t\ti := -1\n\t\thook := hookVar.Get().(vals.List)\n\t\tfor it := hook.Iterator(); it.HasElem(); it.Next() {\n\t\t\ti++\n\t\t\tname := fmt.Sprintf(\"$before-readline[%d]\", i)\n\t\t\tfn, ok := it.Elem().(eval.Callable)\n\t\t\tif !ok {\n\t\t\t\t\/\/ TODO(xiaq): This is not testable as it depends on stderr.\n\t\t\t\t\/\/ Make it testable.\n\t\t\t\tdiag.Complainf(\"%s not function\", name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ TODO(xiaq): This should use stdPorts, but stdPorts is currently\n\t\t\t\/\/ unexported from eval.\n\t\t\tports := []*eval.Port{\n\t\t\t\t{File: os.Stdin}, {File: os.Stdout}, {File: os.Stderr}}\n\t\t\tfm := eval.NewTopFrame(ev, eval.NewInternalSource(name), ports)\n\t\t\tfm.Call(fn, eval.NoArgs, eval.NoOpts)\n\t\t}\n\t}\n}\n\nfunc initAfterReadline(app *cli.App, ev *eval.Evaler, ns eval.Ns) {\n\thook := vals.EmptyList\n\thookVar := vars.FromPtr(&hook)\n\tns[\"after-readline\"] = hookVar\n\tapp.Config.AfterReadline = func(code string) {\n\t\ti := -1\n\t\thook := hookVar.Get().(vals.List)\n\t\tfor it := hook.Iterator(); it.HasElem(); it.Next() {\n\t\t\ti++\n\t\t\tname := fmt.Sprintf(\"$after-readline[%d]\", i)\n\t\t\tfn, ok := it.Elem().(eval.Callable)\n\t\t\tif !ok {\n\t\t\t\t\/\/ TODO(xiaq): This is not testable as it depends on stderr.\n\t\t\t\t\/\/ Make it testable.\n\t\t\t\tdiag.Complainf(\"%s not function\", name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ TODO(xiaq): This should use stdPorts, but stdPorts is currently\n\t\t\t\/\/ unexported from eval.\n\t\t\tports := []*eval.Port{\n\t\t\t\t{File: os.Stdin}, {File: os.Stdout}, {File: os.Stderr}}\n\t\t\tfm := eval.NewTopFrame(ev, eval.NewInternalSource(name), ports)\n\t\t\tfm.Call(fn, []interface{}{code}, eval.NoOpts)\n\t\t}\n\t}\n}\n\nfunc initInsert(app *cli.App, ev *eval.Evaler, ns eval.Ns) {\n\tabbr := vals.EmptyMap\n\tabbrVar := vars.FromPtr(&abbr)\n\tapp.CodeArea.Abbreviations = makeMapIterator(abbrVar)\n\n\t\/\/ TODO(xiaq): Synchronize properly.\n\tbinding := emptyBindingMap\n\tbindingVar := vars.FromPtr(&binding)\n\tapp.CodeArea.OverlayHandler = newMapBinding(app, ev, &binding)\n\n\tquotePaste := false\n\tquotePasteVar := vars.FromPtr(&quotePaste)\n\tapp.CodeArea.QuotePaste = func() bool { return quotePasteVar.Get().(bool) }\n\n\tns.AddNs(\"insert\", eval.Ns{\n\t\t\"abbr\":        abbrVar,\n\t\t\"binding\":     bindingVar,\n\t\t\"quote-paste\": quotePasteVar,\n\t})\n}\n\nfunc makeMapIterator(mv vars.Var) func(func(a, b string)) {\n\treturn func(f func(a, b string)) {\n\t\tfor it := mv.Get().(hashmap.Map).Iterator(); it.HasElem(); it.Next() {\n\t\t\tk, v := it.Elem()\n\t\t\tks, kok := k.(string)\n\t\t\tvs, vok := v.(string)\n\t\t\tif !kok || !vok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tf(ks, vs)\n\t\t}\n\t}\n}\n<commit_msg>cliedit: Use PtrVar.GetRaw.<commit_after>package cliedit\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/elves\/elvish\/cli\"\n\t\"github.com\/elves\/elvish\/diag\"\n\t\"github.com\/elves\/elvish\/eval\"\n\t\"github.com\/elves\/elvish\/eval\/vals\"\n\t\"github.com\/elves\/elvish\/eval\/vars\"\n\t\"github.com\/xiaq\/persistent\/hashmap\"\n)\n\nfunc initAPI(app *cli.App, ev *eval.Evaler, ns eval.Ns) {\n\tinitMaxHeight(app, ns)\n\tinitBeforeReadline(app, ev, ns)\n\tinitAfterReadline(app, ev, ns)\n\tinitInsert(app, ev, ns)\n\n\tinitMiscBuiltins(app, ns)\n\tinitBufferBuiltins(app, ns)\n}\n\nfunc initMaxHeight(app *cli.App, ns eval.Ns) {\n\tmaxHeight := -1\n\tmaxHeightVar := vars.FromPtr(&maxHeight)\n\tapp.Config.MaxHeight = func() int { return maxHeightVar.GetRaw().(int) }\n\tns.Add(\"max-height\", maxHeightVar)\n}\n\nfunc initBeforeReadline(app *cli.App, ev *eval.Evaler, ns eval.Ns) {\n\thook := vals.EmptyList\n\thookVar := vars.FromPtr(&hook)\n\tns[\"before-readline\"] = hookVar\n\tapp.Config.BeforeReadline = func() {\n\t\ti := -1\n\t\thook := hookVar.GetRaw().(vals.List)\n\t\tfor it := hook.Iterator(); it.HasElem(); it.Next() {\n\t\t\ti++\n\t\t\tname := fmt.Sprintf(\"$before-readline[%d]\", i)\n\t\t\tfn, ok := it.Elem().(eval.Callable)\n\t\t\tif !ok {\n\t\t\t\t\/\/ TODO(xiaq): This is not testable as it depends on stderr.\n\t\t\t\t\/\/ Make it testable.\n\t\t\t\tdiag.Complainf(\"%s not function\", name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ TODO(xiaq): This should use stdPorts, but stdPorts is currently\n\t\t\t\/\/ unexported from eval.\n\t\t\tports := []*eval.Port{\n\t\t\t\t{File: os.Stdin}, {File: os.Stdout}, {File: os.Stderr}}\n\t\t\tfm := eval.NewTopFrame(ev, eval.NewInternalSource(name), ports)\n\t\t\tfm.Call(fn, eval.NoArgs, eval.NoOpts)\n\t\t}\n\t}\n}\n\nfunc initAfterReadline(app *cli.App, ev *eval.Evaler, ns eval.Ns) {\n\thook := vals.EmptyList\n\thookVar := vars.FromPtr(&hook)\n\tns[\"after-readline\"] = hookVar\n\tapp.Config.AfterReadline = func(code string) {\n\t\ti := -1\n\t\thook := hookVar.GetRaw().(vals.List)\n\t\tfor it := hook.Iterator(); it.HasElem(); it.Next() {\n\t\t\ti++\n\t\t\tname := fmt.Sprintf(\"$after-readline[%d]\", i)\n\t\t\tfn, ok := it.Elem().(eval.Callable)\n\t\t\tif !ok {\n\t\t\t\t\/\/ TODO(xiaq): This is not testable as it depends on stderr.\n\t\t\t\t\/\/ Make it testable.\n\t\t\t\tdiag.Complainf(\"%s not function\", name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ TODO(xiaq): This should use stdPorts, but stdPorts is currently\n\t\t\t\/\/ unexported from eval.\n\t\t\tports := []*eval.Port{\n\t\t\t\t{File: os.Stdin}, {File: os.Stdout}, {File: os.Stderr}}\n\t\t\tfm := eval.NewTopFrame(ev, eval.NewInternalSource(name), ports)\n\t\t\tfm.Call(fn, []interface{}{code}, eval.NoOpts)\n\t\t}\n\t}\n}\n\nfunc initInsert(app *cli.App, ev *eval.Evaler, ns eval.Ns) {\n\tabbr := vals.EmptyMap\n\tabbrVar := vars.FromPtr(&abbr)\n\tapp.CodeArea.Abbreviations = makeMapIterator(abbrVar)\n\n\t\/\/ TODO(xiaq): Synchronize properly.\n\tbinding := emptyBindingMap\n\tbindingVar := vars.FromPtr(&binding)\n\tapp.CodeArea.OverlayHandler = newMapBinding(app, ev, &binding)\n\n\tquotePaste := false\n\tquotePasteVar := vars.FromPtr(&quotePaste)\n\tapp.CodeArea.QuotePaste = func() bool { return quotePasteVar.GetRaw().(bool) }\n\n\tns.AddNs(\"insert\", eval.Ns{\n\t\t\"abbr\":        abbrVar,\n\t\t\"binding\":     bindingVar,\n\t\t\"quote-paste\": quotePasteVar,\n\t})\n}\n\nfunc makeMapIterator(mv vars.PtrVar) func(func(a, b string)) {\n\treturn func(f func(a, b string)) {\n\t\tfor it := mv.GetRaw().(hashmap.Map).Iterator(); it.HasElem(); it.Next() {\n\t\t\tk, v := it.Elem()\n\t\t\tks, kok := k.(string)\n\t\t\tvs, vok := v.(string)\n\t\t\tif !kok || !vok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tf(ks, vs)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   - support for RelayState\n   - does not seem to work: incl. Capitalization content-security-policy: referrer no-referrer;\n   - redo no-referer - current version does not work !!!\n   - MDQ lookup by location also for hub md\n   - Trusted proxy\n   - wayf:wayf i hub_ops metadata\n        - AttributeNameFormat for Krib -> WAYF SPS - ie if none -> repeat wayf error both formats but error\n        - schacHomeOrganization\n        - schacHomeOrganizationType\n   - collect schema errors\n   - illegal attributes from IdP - ignore or provoke error\n*\/\n\npackage gohybrid\n\nimport (\n\t\"encoding\/base64\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/gorilla\/securecookie\"\n\t\"github.com\/wayf-dk\/go-libxml2\/types\"\n\t\"github.com\/wayf-dk\/gosaml\"\n\t\"github.com\/wayf-dk\/goxml\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"sync\"\n)\n\ntype (\n\tformdata struct {\n\t\tAcs          string\n\t\tSamlresponse string\n\t\tRelayState   string\n\t\tArd template.JS\n\t}\n\n\tidpsppair struct {\n\t\tidp string\n\t\tsp  string\n\t}\n\n\tConf struct {\n\t\tDiscoveryService        string\n\t\tDomain                  string\n\t\tHubEntityID             string\n\t\tEptidSalt               string\n\t\tHubRequestedAttributes  *goxml.Xp\n\t\tInternal, External, Hub gosaml.Md\n\t\tSecureCookieHashKey     string\n\t\tPostFormTemplate        string\n\t\tAttributeReleaseTemplate        string\n\t\tBasic2uri               map[string]string\n\t\tStdTiming               gosaml.IdAndTiming\n\t\tElementsToSign          []string\n\t\tAttributeHandler        func(*goxml.Xp, *goxml.Xp, *goxml.Xp, *goxml.Xp) (error, map[string][]string)\n\t}\n)\n\nconst (\n\tidpCertQuery = `.\/md:IDPSSODescriptor\/md:KeyDescriptor[@use=\"signing\" or not(@use)]\/ds:KeyInfo\/ds:X509Data\/ds:X509Certificate`\n)\n\nvar (\n\t_     = log.Printf \/\/ For debugging; delete when done.\n\t_     = fmt.Printf\n\tremap = map[string]idpsppair{\n\t\t\"https:\/\/nemlogin.wayf.dk\": idpsppair{\"https:\/\/saml.nemlog-in.dk\", \"https:\/\/nemlogin.wayf.dk\"},\n\t}\n\n\tcontextmutex sync.RWMutex\n\tcontext      = make(map[*http.Request]map[string]string)\n\tbify         = regexp.MustCompile(\"^(https?:\/\/)(.*)$\")\n\tdebify       = regexp.MustCompile(\"^(https?:\/\/)(?:(?:birk|krib)\\\\.wayf.dk\/(?:birk|krib)\\\\.php\/)(.+)$\")\n\n\tpostForm,attributeReleaseForm  *template.Template\n\thashKey   []byte\n\tseccookie *securecookie.SecureCookie\n\tconfig    = Conf{}\n)\n\nfunc Config(configuration Conf) {\n\tconfig = configuration\n\thashKey, _ := hex.DecodeString(config.SecureCookieHashKey)\n\tseccookie = securecookie.New(hashKey, nil)\n\tpostForm = template.Must(template.New(\"post\").Parse(config.PostFormTemplate))\n\tattributeReleaseForm = template.Must(template.New(\"post\").Parse(config.AttributeReleaseTemplate))\n}\n\nfunc SsoService(w http.ResponseWriter, r *http.Request) (err error) {\n\tdefer r.Body.Close()\n\t\/\/ handle non ok urls gracefully\n\t\/\/ var err error\n\t\/\/ check issuer and acs in md\n\t\/\/ receiveRequest -> request, issuer md, receiver md\n\t\/\/     check for IDPList 1st in md, then in request then in query\n\t\/\/     sanitize idp from query or request\n\trequest, spmd, _, relayState, err := gosaml.ReceiveSAMLRequest(r, config.Internal, config.Hub)\n\tif err != nil {\n\t\treturn\n\t}\n\tentityID := spmd.Query1(nil, \"@entityID\")\n\tidp := spmd.Query1(nil, \"\/\/IDPList\/ProviderID\") \/\/ Need to find a place for IDPList\n\tif idp == \"\" {\n\t\tidp = request.Query1(nil, \"IDPList\/ProviderID\")\n\t}\n\tif idp == \"\" {\n\t\tidp = r.URL.Query().Get(\"idpentityid\")\n\t}\n\tif idp == \"\" {\n\t\tdata := url.Values{}\n\t\tdata.Set(\"return\", \"https:\/\/\"+r.Host+r.RequestURI)\n\t\tdata.Set(\"returnIDParam\", \"idpentityid\")\n\t\tdata.Set(\"entityID\", entityID)\n\t\thttp.Redirect(w, r, config.DiscoveryService+data.Encode(), http.StatusFound)\n\t} else {\n\t\tvar idpmd *goxml.Xp\n\t\t\/**\/\n\t\t\/\/ check overlap btw ad-hoc feds for the idp and the sp\n\t\tkribID := bify.ReplaceAllString(entityID, \"${1}krib.wayf.dk\/krib.php\/$2\")\n\t\tif kribID == entityID {\n\t\t\tkribID = \"urn:oid:1.3.6.1.4.1.39153:42:\" + entityID\n\t\t}\n\n\t\trequest.QueryDashP(nil, \"\/saml:Issuer\", kribID, nil)\n\t\tacs := request.Query1(nil, \"@AssertionConsumerServiceURL\")\n\t\tacsurl := bify.ReplaceAllString(acs, \"${1}krib.wayf.dk\/krib.php\/$2\")\n\t\trequest.QueryDashP(nil, \"@AssertionConsumerServiceURL\", acsurl, nil)\n\t\t\/**\/\n\t\tidpmd, err = config.External.MDQ(idp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tconst ssoquery = \".\/md:IDPSSODescriptor\/md:SingleSignOnService[@Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect']\/@Location\"\n\t\tssoservice := idpmd.Query1(nil, ssoquery)\n\t\tif ssoservice == \"\" {\n\n\t\t}\n\t\trequest.QueryDashP(nil, \"@Destination\", ssoservice, nil)\n\t\tu, _ := gosaml.SAMLRequest2Url(request, relayState, \"\", \"\", \"\")\n\t\tlog.Println(request.Doc.Dump(true))\n\t\thttp.Redirect(w, r, u.String(), http.StatusFound)\n\t}\n\treturn\n}\n\nfunc BirkService(w http.ResponseWriter, r *http.Request) (err error) {\n\t\/\/ use incoming request for crafting the new one\n\t\/\/ remember to add the Scoping element to inform the IdP of requesterID - if stated in metadata for the IdP\n\t\/\/ check ad-hoc feds overlab\n\tdefer r.Body.Close()\n\t\/\/ get the sp as well to check for allowed acs\n\trequest, _, mdbirkidp, relayState, err := gosaml.ReceiveSAMLRequest(r, config.External, config.External)\n\tif err != nil {\n\t\treturn\n\t}\n\t\/\/ Save the issuer and destination in a cookie for when the response comes back\n\n\tcookievalue, err := seccookie.Encode(\"BIRK\", gosaml.Deflate(request.Doc.Dump(true)))\n\thttp.SetCookie(w, &http.Cookie{Name: \"BIRK\", Value: cookievalue, Domain: config.Domain, Path: \"\/\", Secure: true, HttpOnly: true})\n\n\tidp := debify.ReplaceAllString(mdbirkidp.Query1(nil, \"@entityID\"), \"$1$2\")\n\n\tvar mdhub, mdidp *goxml.Xp\n\t\/\/ are we remapping - for now only use case is https:\/\/nemlogin.wayf.dk -> https:\/\/saml.nemlog-in.dk\n\tif rm, ok := remap[idp]; ok {\n\t\tmdidp, err = config.Internal.MDQ(rm.idp)\n\t\tmdhub, err = config.Internal.MDQ(rm.sp)\n\t} else {\n\t\tmdidp, err = config.Internal.MDQ(idp)\n\t\tmdhub, err = config.Hub.MDQ(config.HubEntityID)\n\t}\n\t\/\/ use a std request - we take care of NameID etc in acsService below\n\tnewrequest := gosaml.NewAuthnRequest(config.StdTiming.Refresh(), mdhub, mdidp)\n\tu, _ := gosaml.SAMLRequest2Url(newrequest, relayState, \"\", \"\", \"\") \/\/ not signed so blank key, pw and algo\n\thttp.Redirect(w, r, u.String(), http.StatusFound)\n\treturn\n}\n\nfunc AcsService(w http.ResponseWriter, r *http.Request) (err error) {\n\tdefer r.Body.Close()\n\tbirk, err := r.Cookie(\"BIRK\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalue := []byte{}\n\tif err = seccookie.Decode(\"BIRK\", birk.Value, &value); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ we checked the request when we received in birkService - we can use it without fear ie. we just parse it\n\tlog.Println(\"cookie\", string(gosaml.Inflate(value)))\n\trequest := goxml.NewXp(string(gosaml.Inflate(value)))\n\n\thttp.SetCookie(w, &http.Cookie{Name: \"BIRK\", Value: \"\", Domain: config.Domain, Path: \"\/\", Secure: true, HttpOnly: true, MaxAge: -1})\n\tsp_md, err := config.External.MDQ(request.Query1(nil, \"\/samlp:AuthnRequest\/saml:Issuer\"))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresponse, idp_md, _, relayState, err := gosaml.ReceiveSAMLResponse(r, config.Internal, config.Hub)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr, ard := config.AttributeHandler(idp_md, config.HubRequestedAttributes, sp_md, response)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbirkmd, err := config.External.MDQ(request.Query1(nil, \"\/samlp:AuthnRequest\/@Destination\"))\n\tif err != nil {\n\t\treturn\n\t}\n\tnameid := response.Query(nil, \".\/saml:Assertion\/saml:Subject\/saml:NameID\")[0]\n\t\/\/ respect nameID in req, give persistent id + all computed attributes + nameformat conversion\n\tnameidformat := sp_md.Query1(nil, \".\/md:SPSSODescriptor\/md:NameIDFormat\")\n\tif nameidformat == gosaml.Persistent {\n\t\tresponse.QueryDashP(nameid, \"@Format\", gosaml.Persistent, nil)\n\t\teptid := response.Query1(nil, `.\/saml:Assertion\/saml:AttributeStatement\/saml:Attribute[@FriendlyName=\"eduPersonTargetedID\"]\/saml:AttributeValue`)\n\t\tresponse.QueryDashP(nameid, \".\", eptid, nil)\n\t} else if nameidformat == gosaml.Transient {\n\t\tresponse.QueryDashP(nameid, \".\", gosaml.Id(), nil)\n\t}\n\n\tnewresponse := gosaml.NewResponse(config.StdTiming.Refresh(), birkmd, sp_md, request, response)\n\n\tfor _, q := range config.ElementsToSign {\n\t\terr = gosaml.SignResponse(newresponse, q, birkmd)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ Prepare data for the attributerelease form\n\n\n\t\/\/ when consent as a service is ready - we will post to that\n\tacs := newresponse.Query1(nil, \"@Destination\")\n\n    ardjson, err := json.Marshal(ard)\n\tdata := formdata{Acs: acs, Samlresponse: base64.StdEncoding.EncodeToString([]byte(newresponse.Doc.Dump(false))), RelayState: relayState, Ard: template.JS(ardjson)}\n\tattributeReleaseForm.Execute(w, data)\n\treturn\n}\n\nfunc KribService(w http.ResponseWriter, r *http.Request) (err error) {\n\t\/\/ check ad-hoc feds overlap\n\tdefer r.Body.Close()\n\n\tresponse, _, _, relayState, err := gosaml.ReceiveSAMLResponse(r, config.External, config.External)\n\tif err != nil {\n\t\treturn\n\t}\n\tdestination := debify.ReplaceAllString(response.Query1(nil, \"@Destination\"), \"$1$2\")\n\tresponse.QueryDashP(nil, \"@Destination\", destination, nil)\n\tresponse.QueryDashP(nil, \".\/saml:Assertion\/saml:Subject\/saml:SubjectConfirmation\/saml:SubjectConfirmationData\/@Recipient\", destination, nil)\n\tissuer := config.HubEntityID\n\tresponse.QueryDashP(nil, \".\/saml:Issuer\", issuer, nil)\n\tresponse.QueryDashP(nil, \".\/saml:Assertion\/saml:Issuer\", issuer, nil)\n\t\/\/ Krib always receives attributes with nameformat=urn. Before sending to the real SP we need to look into\n\t\/\/ the metadata for SP to determine the actual nameformat - as WAYF supports both for internal SPs.\n\tmdsp, err := config.Internal.MDQ(destination)\n\tif err != nil {\n\t\treturn\n\t}\n\trequestedattributes := mdsp.Query(nil, \".\/md:SPSSODescriptor\/md:AttributeConsumingService\/md:RequestedAttribute\")\n\tattributestatement := response.Query(nil, \".\/saml:Assertion\/saml:AttributeStatement\")[0]\n\tfor _, attr := range requestedattributes {\n\t\tnameFormat, _ := attr.(types.Element).GetAttribute(\"NameFormat\")\n\t\tif nameFormat.NodeValue() == gosaml.Basic {\n\t\t\tbasicname, _ := attr.(types.Element).GetAttribute(\"Name\")\n\t\t\turiname := config.Basic2uri[basicname.NodeValue()]\n\t\t\tresponseattribute := response.Query(attributestatement, \"saml:Attribute[@Name='\"+uriname+\"']\")\n\t\t\tif len(responseattribute) > 0 {\n\t\t\t\tresponseattribute[0].(types.Element).SetAttribute(\"Name\", basicname.NodeValue())\n\t\t\t\tresponseattribute[0].(types.Element).SetAttribute(\"NameFormat\", gosaml.Basic)\n\t\t\t}\n\t\t}\n\t}\n\n\tmdhub, err := config.Hub.MDQ(config.HubEntityID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, q := range config.ElementsToSign {\n\t\terr = gosaml.SignResponse(response, q, mdhub)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tdata := formdata{Acs: destination, Samlresponse: base64.StdEncoding.EncodeToString([]byte(response.Doc.Dump(false))), RelayState: relayState}\n\tpostForm.Execute(w, data)\n\treturn\n}\n<commit_msg>added support for attributerelaseform<commit_after>\/*\n   - support for RelayState\n   - does not seem to work: incl. Capitalization content-security-policy: referrer no-referrer;\n   - redo no-referer - current version does not work !!!\n   - MDQ lookup by location also for hub md\n   - Trusted proxy\n   - wayf:wayf i hub_ops metadata\n        - AttributeNameFormat for Krib -> WAYF SPS - ie if none -> repeat wayf error both formats but error\n        - schacHomeOrganization\n        - schacHomeOrganizationType\n   - collect schema errors\n   - illegal attributes from IdP - ignore or provoke error\n*\/\n\npackage gohybrid\n\nimport (\n\t\"encoding\/base64\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/gorilla\/securecookie\"\n\t\"github.com\/wayf-dk\/go-libxml2\/types\"\n\t\"github.com\/wayf-dk\/gosaml\"\n\t\"github.com\/wayf-dk\/goxml\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"sync\"\n)\n\ntype (\n\tformdata struct {\n\t\tAcs          string\n\t\tSamlresponse string\n\t\tRelayState   string\n\t\tArd          template.JS\n\t}\n\n\tidpsppair struct {\n\t\tidp string\n\t\tsp  string\n\t}\n\n\tAttributeReleaseData struct {\n\t\tValues         map[string][]string\n\t\tIdPDisplayName map[string]string\n\t\tIdPLogo        string\n\t\tSPDisplayName  map[string]string\n\t\tSPDescription  map[string]string\n\t\tSPLogo         string\n\t\tSPEntityID     string\n\t\tKey            string\n\t\tHash           string\n\t}\n\n\tConf struct {\n\t\tDiscoveryService         string\n\t\tDomain                   string\n\t\tHubEntityID              string\n\t\tEptidSalt                string\n\t\tHubRequestedAttributes   *goxml.Xp\n\t\tInternal, External, Hub  gosaml.Md\n\t\tSecureCookieHashKey      string\n\t\tPostFormTemplate         string\n\t\tAttributeReleaseTemplate string\n\t\tBasic2uri                map[string]string\n\t\tStdTiming                gosaml.IdAndTiming\n\t\tElementsToSign           []string\n\t\tAttributeHandler         func(*goxml.Xp, *goxml.Xp, *goxml.Xp, *goxml.Xp) (error, AttributeReleaseData)\n\t}\n)\n\nconst (\n\tidpCertQuery = `.\/md:IDPSSODescriptor\/md:KeyDescriptor[@use=\"signing\" or not(@use)]\/ds:KeyInfo\/ds:X509Data\/ds:X509Certificate`\n)\n\nvar (\n\t_     = log.Printf \/\/ For debugging; delete when done.\n\t_     = fmt.Printf\n\tremap = map[string]idpsppair{\n\t\t\"https:\/\/nemlogin.wayf.dk\": idpsppair{\"https:\/\/saml.nemlog-in.dk\", \"https:\/\/nemlogin.wayf.dk\"},\n\t}\n\n\tcontextmutex sync.RWMutex\n\tcontext      = make(map[*http.Request]map[string]string)\n\tbify         = regexp.MustCompile(\"^(https?:\/\/)(.*)$\")\n\tdebify       = regexp.MustCompile(\"^(https?:\/\/)(?:(?:birk|krib)\\\\.wayf.dk\/(?:birk|krib)\\\\.php\/)(.+)$\")\n\n\tpostForm, attributeReleaseForm *template.Template\n\thashKey                        []byte\n\tseccookie                      *securecookie.SecureCookie\n\tconfig                         = Conf{}\n)\n\nfunc Config(configuration Conf) {\n\tconfig = configuration\n\thashKey, _ := hex.DecodeString(config.SecureCookieHashKey)\n\tseccookie = securecookie.New(hashKey, nil)\n\tpostForm = template.Must(template.New(\"post\").Parse(config.PostFormTemplate))\n\tattributeReleaseForm = template.Must(template.New(\"post\").Parse(config.AttributeReleaseTemplate))\n}\n\nfunc SsoService(w http.ResponseWriter, r *http.Request) (err error) {\n\tdefer r.Body.Close()\n\t\/\/ handle non ok urls gracefully\n\t\/\/ var err error\n\t\/\/ check issuer and acs in md\n\t\/\/ receiveRequest -> request, issuer md, receiver md\n\t\/\/     check for IDPList 1st in md, then in request then in query\n\t\/\/     sanitize idp from query or request\n\trequest, spmd, _, relayState, err := gosaml.ReceiveSAMLRequest(r, config.Internal, config.Hub)\n\tif err != nil {\n\t\treturn\n\t}\n\tentityID := spmd.Query1(nil, \"@entityID\")\n\tidp := spmd.Query1(nil, \"\/\/IDPList\/ProviderID\") \/\/ Need to find a place for IDPList\n\tif idp == \"\" {\n\t\tidp = request.Query1(nil, \"IDPList\/ProviderID\")\n\t}\n\tif idp == \"\" {\n\t\tidp = r.URL.Query().Get(\"idpentityid\")\n\t}\n\tif idp == \"\" {\n\t\tdata := url.Values{}\n\t\tdata.Set(\"return\", \"https:\/\/\"+r.Host+r.RequestURI)\n\t\tdata.Set(\"returnIDParam\", \"idpentityid\")\n\t\tdata.Set(\"entityID\", entityID)\n\t\thttp.Redirect(w, r, config.DiscoveryService+data.Encode(), http.StatusFound)\n\t} else {\n\t\tvar idpmd *goxml.Xp\n\t\t\/**\/\n\t\t\/\/ check overlap btw ad-hoc feds for the idp and the sp\n\t\tkribID := bify.ReplaceAllString(entityID, \"${1}krib.wayf.dk\/krib.php\/$2\")\n\t\tif kribID == entityID {\n\t\t\tkribID = \"urn:oid:1.3.6.1.4.1.39153:42:\" + entityID\n\t\t}\n\n\t\trequest.QueryDashP(nil, \"\/saml:Issuer\", kribID, nil)\n\t\tacs := request.Query1(nil, \"@AssertionConsumerServiceURL\")\n\t\tacsurl := bify.ReplaceAllString(acs, \"${1}krib.wayf.dk\/krib.php\/$2\")\n\t\trequest.QueryDashP(nil, \"@AssertionConsumerServiceURL\", acsurl, nil)\n\t\t\/**\/\n\t\tidpmd, err = config.External.MDQ(idp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tconst ssoquery = \".\/md:IDPSSODescriptor\/md:SingleSignOnService[@Binding='urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect']\/@Location\"\n\t\tssoservice := idpmd.Query1(nil, ssoquery)\n\t\tif ssoservice == \"\" {\n\n\t\t}\n\t\trequest.QueryDashP(nil, \"@Destination\", ssoservice, nil)\n\t\tu, _ := gosaml.SAMLRequest2Url(request, relayState, \"\", \"\", \"\")\n\t\thttp.Redirect(w, r, u.String(), http.StatusFound)\n\t}\n\treturn\n}\n\nfunc BirkService(w http.ResponseWriter, r *http.Request) (err error) {\n\t\/\/ use incoming request for crafting the new one\n\t\/\/ remember to add the Scoping element to inform the IdP of requesterID - if stated in metadata for the IdP\n\t\/\/ check ad-hoc feds overlab\n\tdefer r.Body.Close()\n\t\/\/ get the sp as well to check for allowed acs\n\trequest, _, mdbirkidp, relayState, err := gosaml.ReceiveSAMLRequest(r, config.External, config.External)\n\tif err != nil {\n\t\treturn\n\t}\n\t\/\/ Save the issuer and destination in a cookie for when the response comes back\n\n\tcookievalue, err := seccookie.Encode(\"BIRK\", gosaml.Deflate(request.Doc.Dump(true)))\n\thttp.SetCookie(w, &http.Cookie{Name: \"BIRK\", Value: cookievalue, Domain: config.Domain, Path: \"\/\", Secure: true, HttpOnly: true})\n\n\tidp := debify.ReplaceAllString(mdbirkidp.Query1(nil, \"@entityID\"), \"$1$2\")\n\n\tvar mdhub, mdidp *goxml.Xp\n\t\/\/ are we remapping - for now only use case is https:\/\/nemlogin.wayf.dk -> https:\/\/saml.nemlog-in.dk\n\tif rm, ok := remap[idp]; ok {\n\t\tmdidp, err = config.Internal.MDQ(rm.idp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tmdhub, err = config.Internal.MDQ(rm.sp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tmdidp, err = config.Internal.MDQ(idp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tmdhub, err = config.Hub.MDQ(config.HubEntityID)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\t\/\/ use a std request - we take care of NameID etc in acsService below\n\tnewrequest := gosaml.NewAuthnRequest(config.StdTiming.Refresh(), mdhub, mdidp)\n\tu, _ := gosaml.SAMLRequest2Url(newrequest, relayState, \"\", \"\", \"\") \/\/ not signed so blank key, pw and algo\n\thttp.Redirect(w, r, u.String(), http.StatusFound)\n\treturn\n}\n\nfunc AcsService(w http.ResponseWriter, r *http.Request) (err error) {\n\tdefer r.Body.Close()\n\tbirk, err := r.Cookie(\"BIRK\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvalue := []byte{}\n\tif err = seccookie.Decode(\"BIRK\", birk.Value, &value); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ we checked the request when we received in birkService - we can use it without fear ie. we just parse it\n\trequest := goxml.NewXp(string(gosaml.Inflate(value)))\n\n\thttp.SetCookie(w, &http.Cookie{Name: \"BIRK\", Value: \"\", Domain: config.Domain, Path: \"\/\", Secure: true, HttpOnly: true, MaxAge: -1})\n\tsp_md, err := config.External.MDQ(request.Query1(nil, \"\/samlp:AuthnRequest\/saml:Issuer\"))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tresponse, idp_md, _, relayState, err := gosaml.ReceiveSAMLResponse(r, config.Internal, config.Hub)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr, ard := config.AttributeHandler(idp_md, config.HubRequestedAttributes, sp_md, response)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbirkmd, err := config.External.MDQ(request.Query1(nil, \"\/samlp:AuthnRequest\/@Destination\"))\n\tif err != nil {\n\t\treturn\n\t}\n\tnameid := response.Query(nil, \".\/saml:Assertion\/saml:Subject\/saml:NameID\")[0]\n\t\/\/ respect nameID in req, give persistent id + all computed attributes + nameformat conversion\n\tnameidformat := sp_md.Query1(nil, \".\/md:SPSSODescriptor\/md:NameIDFormat\")\n\tif nameidformat == gosaml.Persistent {\n\t\tresponse.QueryDashP(nameid, \"@Format\", gosaml.Persistent, nil)\n\t\teptid := response.Query1(nil, `.\/saml:Assertion\/saml:AttributeStatement\/saml:Attribute[@FriendlyName=\"eduPersonTargetedID\"]\/saml:AttributeValue`)\n\t\tresponse.QueryDashP(nameid, \".\", eptid, nil)\n\t} else if nameidformat == gosaml.Transient {\n\t\tresponse.QueryDashP(nameid, \".\", gosaml.Id(), nil)\n\t}\n\n\tnewresponse := gosaml.NewResponse(config.StdTiming.Refresh(), birkmd, sp_md, request, response)\n\n\tfor _, q := range config.ElementsToSign {\n\t\terr = gosaml.SignResponse(newresponse, q, birkmd)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ Prepare data for the attributerelease form\n\n\t\/\/ when consent as a service is ready - we will post to that\n\tacs := newresponse.Query1(nil, \"@Destination\")\n\n\tardjson, err := json.Marshal(ard)\n\tdata := formdata{Acs: acs, Samlresponse: base64.StdEncoding.EncodeToString([]byte(newresponse.Doc.Dump(false))), RelayState: relayState, Ard: template.JS(ardjson)}\n\tattributeReleaseForm.Execute(w, data)\n\treturn\n}\n\nfunc KribService(w http.ResponseWriter, r *http.Request) (err error) {\n\t\/\/ check ad-hoc feds overlap\n\tdefer r.Body.Close()\n\n\tresponse, _, _, relayState, err := gosaml.ReceiveSAMLResponse(r, config.External, config.External)\n\tif err != nil {\n\t\treturn\n\t}\n\tdestination := debify.ReplaceAllString(response.Query1(nil, \"@Destination\"), \"$1$2\")\n\tresponse.QueryDashP(nil, \"@Destination\", destination, nil)\n\tresponse.QueryDashP(nil, \".\/saml:Assertion\/saml:Subject\/saml:SubjectConfirmation\/saml:SubjectConfirmationData\/@Recipient\", destination, nil)\n\tissuer := config.HubEntityID\n\tresponse.QueryDashP(nil, \".\/saml:Issuer\", issuer, nil)\n\tresponse.QueryDashP(nil, \".\/saml:Assertion\/saml:Issuer\", issuer, nil)\n\t\/\/ Krib always receives attributes with nameformat=urn. Before sending to the real SP we need to look into\n\t\/\/ the metadata for SP to determine the actual nameformat - as WAYF supports both for internal SPs.\n\tmdsp, err := config.Internal.MDQ(destination)\n\tif err != nil {\n\t\treturn\n\t}\n\trequestedattributes := mdsp.Query(nil, \".\/md:SPSSODescriptor\/md:AttributeConsumingService\/md:RequestedAttribute\")\n\tattributestatement := response.Query(nil, \".\/saml:Assertion\/saml:AttributeStatement\")[0]\n\tfor _, attr := range requestedattributes {\n\t\tnameFormat, _ := attr.(types.Element).GetAttribute(\"NameFormat\")\n\t\tif nameFormat.NodeValue() == gosaml.Basic {\n\t\t\tbasicname, _ := attr.(types.Element).GetAttribute(\"Name\")\n\t\t\turiname := config.Basic2uri[basicname.NodeValue()]\n\t\t\tresponseattribute := response.Query(attributestatement, \"saml:Attribute[@Name='\"+uriname+\"']\")\n\t\t\tif len(responseattribute) > 0 {\n\t\t\t\tresponseattribute[0].(types.Element).SetAttribute(\"Name\", basicname.NodeValue())\n\t\t\t\tresponseattribute[0].(types.Element).SetAttribute(\"NameFormat\", gosaml.Basic)\n\t\t\t}\n\t\t}\n\t}\n\n\tmdhub, err := config.Hub.MDQ(config.HubEntityID)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, q := range config.ElementsToSign {\n\t\terr = gosaml.SignResponse(response, q, mdhub)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tdata := formdata{Acs: destination, Samlresponse: base64.StdEncoding.EncodeToString([]byte(response.Doc.Dump(false))), RelayState: relayState}\n\tpostForm.Execute(w, data)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package sockaddr\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\n\/\/ IfAddr is a union of a SockAddr and a net.Interface.\ntype IfAddr struct {\n\tSockAddr\n\tnet.Interface\n}\n\n\/\/ Attr returns the named attribute as a string\nfunc (ifAddr IfAddr) Attr(attrName AttrName) string {\n\tsa := ifAddr.SockAddr\n\tswitch sockType := sa.Type(); {\n\tcase sockType&TypeIP != 0:\n\t\tip := *ToIPAddr(sa)\n\t\tattrVal := IPAddrAttr(ip, attrName)\n\t\tif attrVal != \"\" {\n\t\t\treturn attrVal\n\t\t}\n\n\t\tif sa.Type() == TypeIPv4 {\n\t\t\tipv4 := *ToIPv4Addr(sa)\n\t\t\tattrVal := IPAddrAttr(ipv4, attrName)\n\t\t\tif attrVal != \"\" {\n\t\t\t\treturn attrVal\n\t\t\t}\n\t\t}\n\n\t\tif sa.Type() == TypeIPv6 {\n\t\t\tipv6 := *ToIPv6Addr(sa)\n\t\t\tattrVal := IPAddrAttr(ipv6, attrName)\n\t\t\tif attrVal != \"\" {\n\t\t\t\treturn attrVal\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Random attribute names that are Interface specific\n\t\tswitch attrName {\n\t\tcase \"name\":\n\t\t\treturn ifAddr.Interface.Name\n\t\tcase \"flags\":\n\t\t\treturn ifAddr.Interface.Flags.String()\n\t\t}\n\tcase sockType == TypeUnix:\n\t\tus := *ToUnixSock(sa)\n\t\tattrVal := UnixSockAttr(us, attrName)\n\t\tif attrVal != \"\" {\n\t\t\treturn attrVal\n\t\t}\n\t}\n\n\t\/\/ Non type-specific attributes\n\tswitch attrName {\n\tcase \"string\":\n\t\treturn sa.String()\n\tcase \"type\":\n\t\treturn sa.Type().String()\n\t}\n\n\treturn fmt.Sprintf(\"<unsupported attribute name %q>\", attrName)\n}\n<commit_msg>Fix two issues when taking type of an IPAddr.<commit_after>package sockaddr\n\nimport (\n\t\"fmt\"\n\t\"net\"\n)\n\n\/\/ IfAddr is a union of a SockAddr and a net.Interface.\ntype IfAddr struct {\n\tSockAddr\n\tnet.Interface\n}\n\n\/\/ Attr returns the named attribute as a string\nfunc (ifAddr IfAddr) Attr(attrName AttrName) string {\n\tsa := ifAddr.SockAddr\n\tswitch sockType := sa.Type(); {\n\tcase sockType&TypeIP != 0:\n\t\tip := *ToIPAddr(sa)\n\t\tattrVal := IPAddrAttr(ip, attrName)\n\t\tif attrVal != \"\" {\n\t\t\treturn attrVal\n\t\t}\n\n\t\tif sa.Type() == TypeIPv4 {\n\t\t\tipv4 := *ToIPv4Addr(sa)\n\t\t\tattrVal := IPv4AddrAttr(ipv4, attrName)\n\t\t\tif attrVal != \"\" {\n\t\t\t\treturn attrVal\n\t\t\t}\n\t\t}\n\n\t\tif sa.Type() == TypeIPv6 {\n\t\t\tipv6 := *ToIPv6Addr(sa)\n\t\t\tattrVal := IPv6AddrAttr(ipv6, attrName)\n\t\t\tif attrVal != \"\" {\n\t\t\t\treturn attrVal\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Random attribute names that are Interface specific\n\t\tswitch attrName {\n\t\tcase \"name\":\n\t\t\treturn ifAddr.Interface.Name\n\t\tcase \"flags\":\n\t\t\treturn ifAddr.Interface.Flags.String()\n\t\t}\n\tcase sockType == TypeUnix:\n\t\tus := *ToUnixSock(sa)\n\t\tattrVal := UnixSockAttr(us, attrName)\n\t\tif attrVal != \"\" {\n\t\t\treturn attrVal\n\t\t}\n\t}\n\n\t\/\/ Non type-specific attributes\n\tswitch attrName {\n\tcase \"string\":\n\t\treturn sa.String()\n\tcase \"type\":\n\t\treturn sa.Type().String()\n\t}\n\n\treturn fmt.Sprintf(\"<unsupported attribute name %q>\", attrName)\n}\n<|endoftext|>"}
{"text":"<commit_before>package lxd\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/lxc\/lxd\/shared\"\n)\n\nfunc tlsHTTPClient(client *http.Client, tlsClientCert string, tlsClientKey string, tlsCA string, tlsServerCert string, insecureSkipVerify bool, proxy func(req *http.Request) (*url.URL, error)) (*http.Client, error) {\n\t\/\/ Get the TLS configuration\n\ttlsConfig, err := shared.GetTLSConfigMem(tlsClientCert, tlsClientKey, tlsCA, tlsServerCert, insecureSkipVerify)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Support disabling of strict ciphers\n\tif shared.IsTrue(os.Getenv(\"LXD_INSECURE_TLS\")) {\n\t\ttlsConfig.CipherSuites = nil\n\t}\n\n\t\/\/ Define the http transport\n\ttransport := &http.Transport{\n\t\tTLSClientConfig:   tlsConfig,\n\t\tDial:              shared.RFC3493Dialer,\n\t\tProxy:             shared.ProxyFromEnvironment,\n\t\tDisableKeepAlives: true,\n\t}\n\n\t\/\/ Allow overriding the proxy\n\tif proxy != nil {\n\t\ttransport.Proxy = proxy\n\t}\n\n\t\/\/ Special TLS handling\n\t\/\/lint:ignore SA1019 DialContext doesn't exist in Go 1.13\n\ttransport.DialTLS = func(network string, addr string) (net.Conn, error) {\n\t\ttlsDial := func(network string, addr string, config *tls.Config, resetName bool) (net.Conn, error) {\n\t\t\t\/\/ TCP connection\n\t\t\t\/\/lint:ignore SA1019 DialContext doesn't exist in Go 1.13\n\t\t\tconn, err := transport.Dial(network, addr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t\/\/ Setup TLS\n\t\t\tif resetName {\n\t\t\t\thostName, _, err := net.SplitHostPort(addr)\n\t\t\t\tif err != nil {\n\t\t\t\t\thostName = addr\n\t\t\t\t}\n\n\t\t\t\tconfig = config.Clone()\n\t\t\t\tconfig.ServerName = hostName\n\t\t\t}\n\t\t\ttlsConn := tls.Client(conn, config)\n\n\t\t\t\/\/ Validate the connection\n\t\t\terr = tlsConn.Handshake()\n\t\t\tif err != nil {\n\t\t\t\tconn.Close()\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif !config.InsecureSkipVerify {\n\t\t\t\terr := tlsConn.VerifyHostname(config.ServerName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn tlsConn, nil\n\t\t}\n\n\t\tconn, err := tlsDial(network, addr, transport.TLSClientConfig, false)\n\t\tif err != nil {\n\t\t\t\/\/ We may have gotten redirected to a non-LXD machine\n\t\t\treturn tlsDial(network, addr, transport.TLSClientConfig, true)\n\t\t}\n\n\t\treturn conn, nil\n\t}\n\n\t\/\/ Define the http client\n\tif client == nil {\n\t\tclient = &http.Client{}\n\t}\n\tclient.Transport = transport\n\n\t\/\/ Setup redirect policy\n\tclient.CheckRedirect = func(req *http.Request, via []*http.Request) error {\n\t\t\/\/ Replicate the headers\n\t\treq.Header = via[len(via)-1].Header\n\n\t\treturn nil\n\t}\n\n\treturn client, nil\n}\n\nfunc unixHTTPClient(client *http.Client, path string) (*http.Client, error) {\n\t\/\/ Setup a Unix socket dialer\n\tunixDial := func(network, addr string) (net.Conn, error) {\n\t\traddr, err := net.ResolveUnixAddr(\"unix\", path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn net.DialUnix(\"unix\", nil, raddr)\n\t}\n\n\t\/\/ Define the http transport\n\ttransport := &http.Transport{\n\t\tDial:              unixDial,\n\t\tDisableKeepAlives: true,\n\t}\n\n\t\/\/ Define the http client\n\tif client == nil {\n\t\tclient = &http.Client{}\n\t}\n\tclient.Transport = transport\n\n\t\/\/ Setup redirect policy\n\tclient.CheckRedirect = func(req *http.Request, via []*http.Request) error {\n\t\t\/\/ Replicate the headers\n\t\treq.Header = via[len(via)-1].Header\n\n\t\treturn nil\n\t}\n\n\treturn client, nil\n}\n\n\/\/ remoteOperationResult used for storing the error that occurred for a particular remote URL.\ntype remoteOperationResult struct {\n\tURL   string\n\tError error\n}\n\nfunc remoteOperationError(msg string, errors []remoteOperationResult) error {\n\t\/\/ Check if empty\n\tif len(errors) == 0 {\n\t\treturn nil\n\t}\n\n\t\/\/ Check if all identical\n\tvar err error\n\tfor _, entry := range errors {\n\t\tif err != nil && entry.Error.Error() != err.Error() {\n\t\t\terrorStrs := make([]string, 0, len(errors))\n\t\t\tfor _, error := range errors {\n\t\t\t\terrorStrs = append(errorStrs, fmt.Sprintf(\"%s: %v\", error.URL, error.Error))\n\t\t\t}\n\n\t\t\treturn fmt.Errorf(\"%s:\\n - %s\", msg, strings.Join(errorStrs, \"\\n - \"))\n\t\t}\n\n\t\terr = entry.Error\n\t}\n\n\t\/\/ Check if successful\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %s\", msg, err)\n\t}\n\n\treturn nil\n}\n\n\/\/ Set the value of a query parameter in the given URI.\nfunc setQueryParam(uri, param, value string) (string, error) {\n\tfields, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvalues := fields.Query()\n\tvalues.Set(param, url.QueryEscape(value))\n\n\tfields.RawQuery = values.Encode()\n\n\treturn fields.String(), nil\n}\n<commit_msg>client\/util: Adds urlsToResourceNames function<commit_after>package lxd\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/lxc\/lxd\/shared\"\n)\n\nfunc tlsHTTPClient(client *http.Client, tlsClientCert string, tlsClientKey string, tlsCA string, tlsServerCert string, insecureSkipVerify bool, proxy func(req *http.Request) (*url.URL, error)) (*http.Client, error) {\n\t\/\/ Get the TLS configuration\n\ttlsConfig, err := shared.GetTLSConfigMem(tlsClientCert, tlsClientKey, tlsCA, tlsServerCert, insecureSkipVerify)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Support disabling of strict ciphers\n\tif shared.IsTrue(os.Getenv(\"LXD_INSECURE_TLS\")) {\n\t\ttlsConfig.CipherSuites = nil\n\t}\n\n\t\/\/ Define the http transport\n\ttransport := &http.Transport{\n\t\tTLSClientConfig:   tlsConfig,\n\t\tDial:              shared.RFC3493Dialer,\n\t\tProxy:             shared.ProxyFromEnvironment,\n\t\tDisableKeepAlives: true,\n\t}\n\n\t\/\/ Allow overriding the proxy\n\tif proxy != nil {\n\t\ttransport.Proxy = proxy\n\t}\n\n\t\/\/ Special TLS handling\n\t\/\/lint:ignore SA1019 DialContext doesn't exist in Go 1.13\n\ttransport.DialTLS = func(network string, addr string) (net.Conn, error) {\n\t\ttlsDial := func(network string, addr string, config *tls.Config, resetName bool) (net.Conn, error) {\n\t\t\t\/\/ TCP connection\n\t\t\t\/\/lint:ignore SA1019 DialContext doesn't exist in Go 1.13\n\t\t\tconn, err := transport.Dial(network, addr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t\/\/ Setup TLS\n\t\t\tif resetName {\n\t\t\t\thostName, _, err := net.SplitHostPort(addr)\n\t\t\t\tif err != nil {\n\t\t\t\t\thostName = addr\n\t\t\t\t}\n\n\t\t\t\tconfig = config.Clone()\n\t\t\t\tconfig.ServerName = hostName\n\t\t\t}\n\t\t\ttlsConn := tls.Client(conn, config)\n\n\t\t\t\/\/ Validate the connection\n\t\t\terr = tlsConn.Handshake()\n\t\t\tif err != nil {\n\t\t\t\tconn.Close()\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif !config.InsecureSkipVerify {\n\t\t\t\terr := tlsConn.VerifyHostname(config.ServerName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tconn.Close()\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn tlsConn, nil\n\t\t}\n\n\t\tconn, err := tlsDial(network, addr, transport.TLSClientConfig, false)\n\t\tif err != nil {\n\t\t\t\/\/ We may have gotten redirected to a non-LXD machine\n\t\t\treturn tlsDial(network, addr, transport.TLSClientConfig, true)\n\t\t}\n\n\t\treturn conn, nil\n\t}\n\n\t\/\/ Define the http client\n\tif client == nil {\n\t\tclient = &http.Client{}\n\t}\n\tclient.Transport = transport\n\n\t\/\/ Setup redirect policy\n\tclient.CheckRedirect = func(req *http.Request, via []*http.Request) error {\n\t\t\/\/ Replicate the headers\n\t\treq.Header = via[len(via)-1].Header\n\n\t\treturn nil\n\t}\n\n\treturn client, nil\n}\n\nfunc unixHTTPClient(client *http.Client, path string) (*http.Client, error) {\n\t\/\/ Setup a Unix socket dialer\n\tunixDial := func(network, addr string) (net.Conn, error) {\n\t\traddr, err := net.ResolveUnixAddr(\"unix\", path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn net.DialUnix(\"unix\", nil, raddr)\n\t}\n\n\t\/\/ Define the http transport\n\ttransport := &http.Transport{\n\t\tDial:              unixDial,\n\t\tDisableKeepAlives: true,\n\t}\n\n\t\/\/ Define the http client\n\tif client == nil {\n\t\tclient = &http.Client{}\n\t}\n\tclient.Transport = transport\n\n\t\/\/ Setup redirect policy\n\tclient.CheckRedirect = func(req *http.Request, via []*http.Request) error {\n\t\t\/\/ Replicate the headers\n\t\treq.Header = via[len(via)-1].Header\n\n\t\treturn nil\n\t}\n\n\treturn client, nil\n}\n\n\/\/ remoteOperationResult used for storing the error that occurred for a particular remote URL.\ntype remoteOperationResult struct {\n\tURL   string\n\tError error\n}\n\nfunc remoteOperationError(msg string, errors []remoteOperationResult) error {\n\t\/\/ Check if empty\n\tif len(errors) == 0 {\n\t\treturn nil\n\t}\n\n\t\/\/ Check if all identical\n\tvar err error\n\tfor _, entry := range errors {\n\t\tif err != nil && entry.Error.Error() != err.Error() {\n\t\t\terrorStrs := make([]string, 0, len(errors))\n\t\t\tfor _, error := range errors {\n\t\t\t\terrorStrs = append(errorStrs, fmt.Sprintf(\"%s: %v\", error.URL, error.Error))\n\t\t\t}\n\n\t\t\treturn fmt.Errorf(\"%s:\\n - %s\", msg, strings.Join(errorStrs, \"\\n - \"))\n\t\t}\n\n\t\terr = entry.Error\n\t}\n\n\t\/\/ Check if successful\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %s\", msg, err)\n\t}\n\n\treturn nil\n}\n\n\/\/ Set the value of a query parameter in the given URI.\nfunc setQueryParam(uri, param, value string) (string, error) {\n\tfields, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvalues := fields.Query()\n\tvalues.Set(param, url.QueryEscape(value))\n\n\tfields.RawQuery = values.Encode()\n\n\treturn fields.String(), nil\n}\n\n\/\/ urlsToResourceNames returns a list of resource names extracted from one or more URLs of the same resource type.\n\/\/ The resource type path prefix to match is provided by the matchPathPrefix argument.\nfunc urlsToResourceNames(matchPathPrefix string, urls ...string) ([]string, error) {\n\tvar resourceNames []string\n\n\tfor _, urlRaw := range urls {\n\t\tu, err := url.Parse(urlRaw)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Failed parsing URL %q: %w\", urlRaw, err)\n\t\t}\n\n\t\tfields := strings.Split(u.Path, fmt.Sprintf(\"%s\/\", matchPathPrefix))\n\t\tif len(fields) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected URL path %q\", u)\n\t\t}\n\n\t\tresourceNames = append(resourceNames, fields[len(fields)-1])\n\t}\n\n\treturn resourceNames, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/urfave\/cli\"\n\t\"github.com\/usefathom\/fathom\/pkg\/models\"\n)\n\nvar registerCmd = cli.Command{\n\tName:    \"register\",\n\tAliases: []string{\"r\"},\n\tUsage:   \"register a new admin user\",\n\tAction:  register,\n\tFlags: []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"email, e\",\n\t\t\tUsage: \"user email\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"password, p\",\n\t\t\tUsage: \"user password\",\n\t\t},\n\t},\n}\n\nfunc register(c *cli.Context) error {\n\temail := c.String(\"email\")\n\tif email == \"\" {\n\t\treturn errors.New(\"Invalid arguments: missing email\")\n\t}\n\n\tpassword := c.String(\"password\")\n\tif password == \"\" {\n\t\treturn errors.New(\"Invalid arguments: missing password\")\n\t}\n\n\tuser := models.NewUser(email, password)\n\terr := app.database.SaveUser(&user)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating user: %s\", err)\n\t}\n\n\tlog.Infof(\"Created user %s\", user.Email)\n\treturn nil\n}\n<commit_msg>remove alias for register command<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/urfave\/cli\"\n\t\"github.com\/usefathom\/fathom\/pkg\/models\"\n)\n\nvar registerCmd = cli.Command{\n\tName:   \"register\",\n\tUsage:  \"register a new admin user\",\n\tAction: register,\n\tFlags: []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"email, e\",\n\t\t\tUsage: \"user email\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"password, p\",\n\t\t\tUsage: \"user password\",\n\t\t},\n\t},\n}\n\nfunc register(c *cli.Context) error {\n\temail := c.String(\"email\")\n\tif email == \"\" {\n\t\treturn errors.New(\"Invalid arguments: missing email\")\n\t}\n\n\tpassword := c.String(\"password\")\n\tif password == \"\" {\n\t\treturn errors.New(\"Invalid arguments: missing password\")\n\t}\n\n\tuser := models.NewUser(email, password)\n\terr := app.database.SaveUser(&user)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating user: %s\", err)\n\t}\n\n\tlog.Infof(\"Created user %s\", user.Email)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2015, Daniel Martí <mvdan@mvdan.cc>\n\/\/ See LICENSE for licensing information\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/mvdan\/adb\"\n\n\t\"github.com\/mvdan\/fdroidcl\"\n)\n\nvar cmdSearch = &Command{\n\tUsageLine: \"search [<regexp...>]\",\n\tShort:     \"Search available apps\",\n}\n\nvar (\n\tquiet     = cmdSearch.Flag.Bool(\"q\", false, \"Print package names only\")\n\tinstalled = cmdSearch.Flag.Bool(\"i\", false, \"Filter installed apps\")\n\tupdates   = cmdSearch.Flag.Bool(\"u\", false, \"Filter apps with updates\")\n\tcategory  = cmdSearch.Flag.String(\"c\", \"\", \"Filter apps by category\")\n\tsortBy    = cmdSearch.Flag.String(\"o\", \"\", \"Sort order (added, updated)\")\n)\n\nfunc init() {\n\tcmdSearch.Run = runSearch\n}\n\nfunc runSearch(args []string) {\n\tif *installed && *updates {\n\t\tfmt.Fprintf(os.Stderr, \"-i is redundant if -u is specified\\n\")\n\t\tcmdSearch.Flag.Usage()\n\t}\n\tsfunc, err := sortFunc(*sortBy)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tcmdSearch.Flag.Usage()\n\t}\n\tvar device *adb.Device\n\tif *installed || *updates {\n\t\tdevice = mustOneDevice()\n\t}\n\tapps := filterAppsSearch(mustLoadIndexes(), args)\n\tinstPkgs := mustInstalled(device)\n\tif *installed {\n\t\tapps = filterAppsInstalled(apps, instPkgs)\n\t}\n\tif *updates {\n\t\tapps = filterAppsUpdates(apps, instPkgs)\n\t}\n\tif *category != \"\" {\n\t\tapps = filterAppsCategory(apps, *category)\n\t\tif apps == nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"No such category: %s\\n\", *category)\n\t\t\tcmdSearch.Flag.Usage()\n\t\t}\n\t}\n\tif sfunc != nil {\n\t\tapps = sortApps(apps, sfunc)\n\t}\n\tif *quiet {\n\t\tfor _, app := range apps {\n\t\t\tfmt.Println(app.ID)\n\t\t}\n\t} else {\n\t\tprintApps(apps, instPkgs)\n\t}\n}\n\nfunc filterAppsSearch(apps []fdroidcl.App, terms []string) []fdroidcl.App {\n\tregexes := make([]*regexp.Regexp, len(terms))\n\tfor i, term := range terms {\n\t\tregexes[i] = regexp.MustCompile(term)\n\t}\n\tvar result []fdroidcl.App\n\tfor _, app := range apps {\n\t\tfields := []string{\n\t\t\tstrings.ToLower(app.ID),\n\t\t\tstrings.ToLower(app.Name),\n\t\t\tstrings.ToLower(app.Summary),\n\t\t\tstrings.ToLower(app.Desc),\n\t\t}\n\t\tif !appMatches(fields, regexes) {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, app)\n\t}\n\treturn result\n}\n\nfunc appMatches(fields []string, regexes []*regexp.Regexp) bool {\nfieldLoop:\n\tfor _, field := range fields {\n\t\tfor _, regex := range regexes {\n\t\t\tif !regex.MatchString(field) {\n\t\t\t\tcontinue fieldLoop\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc printApps(apps []fdroidcl.App, inst map[string]adb.Package) {\n\tmaxIDLen := 0\n\tfor _, app := range apps {\n\t\tif len(app.ID) > maxIDLen {\n\t\t\tmaxIDLen = len(app.ID)\n\t\t}\n\t}\n\tfor _, app := range apps {\n\t\tvar pkg *adb.Package\n\t\tp, e := inst[app.ID]\n\t\tif e {\n\t\t\tpkg = &p\n\t\t}\n\t\tprintApp(app, maxIDLen, pkg)\n\t}\n}\n\nfunc descVersion(app fdroidcl.App, inst *adb.Package) string {\n\tcur := app.CurApk()\n\tif cur == nil {\n\t\treturn \"(no version available)\"\n\t}\n\tif inst == nil {\n\t\treturn fmt.Sprintf(\"%s (%d)\", cur.VName, cur.VCode)\n\t}\n\tif inst.VCode < cur.VCode {\n\t\treturn fmt.Sprintf(\"%s (%d) -> %s (%d)\", inst.VName, inst.VCode,\n\t\t\tcur.VName, cur.VCode)\n\t}\n\tif !*installed {\n\t\treturn fmt.Sprintf(\"%s (%d) [installed]\", cur.VName, cur.VCode)\n\t}\n\treturn fmt.Sprintf(\"%s (%d)\", cur.VName, cur.VCode)\n}\n\nfunc printApp(app fdroidcl.App, IDLen int, inst *adb.Package) {\n\tfmt.Printf(\"%s%s %s - %s\\n\", app.ID, strings.Repeat(\" \", IDLen-len(app.ID)),\n\t\tapp.Name, descVersion(app, inst))\n\tfmt.Printf(\"    %s\\n\", app.Summary)\n}\n\nfunc mustInstalled(device *adb.Device) map[string]adb.Package {\n\tif device == nil {\n\t\treturn nil\n\t}\n\tinst, err := device.Installed()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get installed packages: %v\", err)\n\t}\n\treturn inst\n}\n\nfunc filterAppsInstalled(apps []fdroidcl.App, inst map[string]adb.Package) []fdroidcl.App {\n\tvar result []fdroidcl.App\n\tfor _, app := range apps {\n\t\tif _, e := inst[app.ID]; !e {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, app)\n\t}\n\treturn result\n}\n\nfunc filterAppsUpdates(apps []fdroidcl.App, inst map[string]adb.Package) []fdroidcl.App {\n\tvar result []fdroidcl.App\n\tfor _, app := range apps {\n\t\tp, e := inst[app.ID]\n\t\tif !e {\n\t\t\tcontinue\n\t\t}\n\t\tcur := app.CurApk()\n\t\tif cur == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif p.VCode >= cur.VCode {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, app)\n\t}\n\treturn result\n}\n\nfunc contains(l []string, s string) bool {\n\tfor _, s1 := range l {\n\t\tif s1 == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc filterAppsCategory(apps []fdroidcl.App, categ string) []fdroidcl.App {\n\tvar result []fdroidcl.App\n\tfor _, app := range apps {\n\t\tif !contains(app.Categs, categ) {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, app)\n\t}\n\treturn result\n}\n\nfunc cmpAdded(a, b *fdroidcl.App) bool {\n\treturn a.Added.Before(b.Added.Time)\n}\n\nfunc cmpUpdated(a, b *fdroidcl.App) bool {\n\treturn a.Updated.Before(b.Updated.Time)\n}\n\nfunc sortFunc(sortBy string) (func(a, b *fdroidcl.App) bool, error) {\n\tswitch sortBy {\n\tcase \"added\":\n\t\treturn cmpAdded, nil\n\tcase \"updated\":\n\t\treturn cmpUpdated, nil\n\tcase \"\":\n\t\treturn nil, nil\n\t}\n\treturn nil, fmt.Errorf(\"Unknown sort order: %s\", sortBy)\n}\n\ntype appList struct {\n\tl []fdroidcl.App\n\tf func(a, b *fdroidcl.App) bool\n}\n\nfunc (al appList) Len() int           { return len(al.l) }\nfunc (al appList) Swap(i, j int)      { al.l[i], al.l[j] = al.l[j], al.l[i] }\nfunc (al appList) Less(i, j int) bool { return al.f(&al.l[i], &al.l[j]) }\n\nfunc sortApps(apps []fdroidcl.App, f func(a, b *fdroidcl.App) bool) []fdroidcl.App {\n\tsort.Sort(appList{l: apps, f: f})\n\treturn apps\n}\n<commit_msg>search: consider suggestions<commit_after>\/\/ Copyright (c) 2015, Daniel Martí <mvdan@mvdan.cc>\n\/\/ See LICENSE for licensing information\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/mvdan\/adb\"\n\n\t\"github.com\/mvdan\/fdroidcl\"\n)\n\nvar cmdSearch = &Command{\n\tUsageLine: \"search [<regexp...>]\",\n\tShort:     \"Search available apps\",\n}\n\nvar (\n\tquiet     = cmdSearch.Flag.Bool(\"q\", false, \"Print package names only\")\n\tinstalled = cmdSearch.Flag.Bool(\"i\", false, \"Filter installed apps\")\n\tupdates   = cmdSearch.Flag.Bool(\"u\", false, \"Filter apps with updates\")\n\tcategory  = cmdSearch.Flag.String(\"c\", \"\", \"Filter apps by category\")\n\tsortBy    = cmdSearch.Flag.String(\"o\", \"\", \"Sort order (added, updated)\")\n)\n\nfunc init() {\n\tcmdSearch.Run = runSearch\n}\n\nfunc runSearch(args []string) {\n\tif *installed && *updates {\n\t\tfmt.Fprintf(os.Stderr, \"-i is redundant if -u is specified\\n\")\n\t\tcmdSearch.Flag.Usage()\n\t}\n\tsfunc, err := sortFunc(*sortBy)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tcmdSearch.Flag.Usage()\n\t}\n\tvar device *adb.Device\n\tif *installed || *updates {\n\t\tdevice = mustOneDevice()\n\t}\n\tapps := filterAppsSearch(mustLoadIndexes(), args)\n\tif *installed {\n\t\tapps = filterAppsInstalled(apps, device)\n\t}\n\tif *updates {\n\t\tapps = filterAppsUpdates(apps, device)\n\t}\n\tif *category != \"\" {\n\t\tapps = filterAppsCategory(apps, *category)\n\t\tif apps == nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"No such category: %s\\n\", *category)\n\t\t\tcmdSearch.Flag.Usage()\n\t\t}\n\t}\n\tif sfunc != nil {\n\t\tapps = sortApps(apps, sfunc)\n\t}\n\tif *quiet {\n\t\tfor _, app := range apps {\n\t\t\tfmt.Println(app.ID)\n\t\t}\n\t} else {\n\t\tprintApps(apps, device)\n\t}\n}\n\nfunc filterAppsSearch(apps []fdroidcl.App, terms []string) []fdroidcl.App {\n\tregexes := make([]*regexp.Regexp, len(terms))\n\tfor i, term := range terms {\n\t\tregexes[i] = regexp.MustCompile(term)\n\t}\n\tvar result []fdroidcl.App\n\tfor _, app := range apps {\n\t\tfields := []string{\n\t\t\tstrings.ToLower(app.ID),\n\t\t\tstrings.ToLower(app.Name),\n\t\t\tstrings.ToLower(app.Summary),\n\t\t\tstrings.ToLower(app.Desc),\n\t\t}\n\t\tif !appMatches(fields, regexes) {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, app)\n\t}\n\treturn result\n}\n\nfunc appMatches(fields []string, regexes []*regexp.Regexp) bool {\nfieldLoop:\n\tfor _, field := range fields {\n\t\tfor _, regex := range regexes {\n\t\t\tif !regex.MatchString(field) {\n\t\t\t\tcontinue fieldLoop\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc printApps(apps []fdroidcl.App, device *adb.Device) {\n\tmaxIDLen := 0\n\tfor _, app := range apps {\n\t\tif len(app.ID) > maxIDLen {\n\t\t\tmaxIDLen = len(app.ID)\n\t\t}\n\t}\n\tinst := mustInstalled(device)\n\tfor _, app := range apps {\n\t\tvar pkg *adb.Package\n\t\tp, e := inst[app.ID]\n\t\tif e {\n\t\t\tpkg = &p\n\t\t}\n\t\tprintApp(app, maxIDLen, pkg, device)\n\t}\n}\n\nfunc descVersion(app fdroidcl.App, inst *adb.Package, device *adb.Device) string {\n\t\/\/ With \"-u\" or \"-i\" option there must be a connected device\n\tif *updates || *installed {\n\t\tsuggested := app.SuggestedApk(device)\n\t\tif suggested != nil && inst.VCode < suggested.VCode {\n\t\t\treturn fmt.Sprintf(\"%s (%d) -> %s (%d)\", inst.VName, inst.VCode,\n\t\t\t\tsuggested.VName, suggested.VCode)\n\t\t}\n\t\treturn fmt.Sprintf(\"%s (%d)\", inst.VName, inst.VCode)\n\t}\n\t\/\/ Without \"-u\" or \"-i\" we only have repositories indices\n\treturn fmt.Sprintf(\"%s (%d)\", app.CVName, app.CVCode)\n}\n\nfunc printApp(app fdroidcl.App, IDLen int, inst *adb.Package, device *adb.Device) {\n\tfmt.Printf(\"%s%s %s - %s\\n\", app.ID, strings.Repeat(\" \", IDLen-len(app.ID)),\n\t\tapp.Name, descVersion(app, inst, device))\n\tfmt.Printf(\"    %s\\n\", app.Summary)\n}\n\nfunc mustInstalled(device *adb.Device) map[string]adb.Package {\n\tif device == nil {\n\t\treturn nil\n\t}\n\tinst, err := device.Installed()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get installed packages: %v\", err)\n\t}\n\treturn inst\n}\n\nfunc filterAppsInstalled(apps []fdroidcl.App, device *adb.Device) []fdroidcl.App {\n\tvar result []fdroidcl.App\n\tinst := mustInstalled(device)\n\tfor _, app := range apps {\n\t\tif _, e := inst[app.ID]; !e {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, app)\n\t}\n\treturn result\n}\n\nfunc filterAppsUpdates(apps []fdroidcl.App, device *adb.Device) []fdroidcl.App {\n\tvar result []fdroidcl.App\n\tinst := mustInstalled(device)\n\tfor _, app := range apps {\n\t\tp, e := inst[app.ID]\n\t\tif !e {\n\t\t\tcontinue\n\t\t}\n\t\tsuggested := app.SuggestedApk(device)\n\t\tif suggested == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif p.VCode >= suggested.VCode {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, app)\n\t}\n\treturn result\n}\n\nfunc contains(l []string, s string) bool {\n\tfor _, s1 := range l {\n\t\tif s1 == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc filterAppsCategory(apps []fdroidcl.App, categ string) []fdroidcl.App {\n\tvar result []fdroidcl.App\n\tfor _, app := range apps {\n\t\tif !contains(app.Categs, categ) {\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, app)\n\t}\n\treturn result\n}\n\nfunc cmpAdded(a, b *fdroidcl.App) bool {\n\treturn a.Added.Before(b.Added.Time)\n}\n\nfunc cmpUpdated(a, b *fdroidcl.App) bool {\n\treturn a.Updated.Before(b.Updated.Time)\n}\n\nfunc sortFunc(sortBy string) (func(a, b *fdroidcl.App) bool, error) {\n\tswitch sortBy {\n\tcase \"added\":\n\t\treturn cmpAdded, nil\n\tcase \"updated\":\n\t\treturn cmpUpdated, nil\n\tcase \"\":\n\t\treturn nil, nil\n\t}\n\treturn nil, fmt.Errorf(\"Unknown sort order: %s\", sortBy)\n}\n\ntype appList struct {\n\tl []fdroidcl.App\n\tf func(a, b *fdroidcl.App) bool\n}\n\nfunc (al appList) Len() int           { return len(al.l) }\nfunc (al appList) Swap(i, j int)      { al.l[i], al.l[j] = al.l[j], al.l[i] }\nfunc (al appList) Less(i, j int) bool { return al.f(&al.l[i], &al.l[j]) }\n\nfunc sortApps(apps []fdroidcl.App, f func(a, b *fdroidcl.App) bool) []fdroidcl.App {\n\tsort.Sort(appList{l: apps, f: f})\n\treturn apps\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"code.google.com\/p\/goauth2\/oauth\"\n\t\"code.google.com\/p\/google-api-go-client\/storage\/v1\"\n\t\"fmt\"\n\t\"github.com\/TheHippo\/gcssync\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/dustin\/go-humanize\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\nconst (\n\t_                = iota\n\terrorAuthInfo    = iota\n\terrorProjectInfo = iota\n\terrorClientInit  = iota\n\terrorListFiles   = iota\n\terrorUploadFiles = iota\n\terrorSyncFiles   = iota\n)\n\nconst (\n\tscope       = storage.DevstorageFull_controlScope\n\tauthURL     = \"https:\/\/accounts.google.com\/o\/oauth2\/auth\"\n\ttokenURL    = \"https:\/\/accounts.google.com\/o\/oauth2\/token\"\n\tentityName  = \"allUsers\"\n\tredirectURL = \"urn:ietf:wg:oauth:2.0:oob\"\n)\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"gcssync\"\n\tapp.Usage = \"Sync files with Google Cloud Storage\"\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:   \"cachefile\",\n\t\t\tValue:  \"cache.json\",\n\t\t\tUsage:  \"Cache file for caching auth tokens\",\n\t\t\tEnvVar: \"AUTH_CACHE_FILE\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"bucketname, b\",\n\t\t\tValue:  \"\",\n\t\t\tUsage:  \"Name of bucket\",\n\t\t\tEnvVar: \"BUCKET_NAME\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"projectid, p\",\n\t\t\tValue:  \"\",\n\t\t\tUsage:  \"Google project\",\n\t\t\tEnvVar: \"PROJECT_ID\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"clientid, c\",\n\t\t\tValue:  \"\",\n\t\t\tUsage:  \"Auth client id\",\n\t\t\tEnvVar: \"AUTH_CLIENT_ID\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"clientsecret, s\",\n\t\t\tValue:  \"\",\n\t\t\tUsage:  \"Client secrect\",\n\t\t\tEnvVar: \"AUTH_CLIENT_SECRET\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"code\",\n\t\t\tValue:  \"\",\n\t\t\tUsage:  \"Authorization Code\",\n\t\t\tEnvVar: \"AUTH_CODE\",\n\t\t},\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:      \"list\",\n\t\t\tShortName: \"l\",\n\t\t\tUsage:     \"List remote files\",\n\t\t\tAction:    listFiles,\n\t\t},\n\t\t{\n\t\t\tName:      \"upload\",\n\t\t\tShortName: \"u\",\n\t\t\tUsage:     \"Upload a single file\",\n\t\t\tAction:    uploadFile,\n\t\t},\n\t\t{\n\t\t\tName:      \"sync\",\n\t\t\tShortName: \"s\",\n\t\t\tUsage:     \"Syncs a folder to a Google Cloudstorage bucket\",\n\t\t\tAction:    syncFolder,\n\t\t},\n\t}\n\tapp.Run(os.Args)\n}\n\nfunc generateOAuthConfig(c *cli.Context) (*oauth.Config, error) {\n\tclientId := c.GlobalString(\"clientid\")\n\tif clientId == \"\" {\n\t\treturn &oauth.Config{}, fmt.Errorf(\"Could not find Client ID\")\n\t}\n\tclientSecret := c.GlobalString(\"clientsecret\")\n\tif clientSecret == \"\" {\n\t\treturn &oauth.Config{}, fmt.Errorf(\"Could not find Client Secret\")\n\t}\n\n\treturn &oauth.Config{\n\t\tClientId:     clientId,\n\t\tClientSecret: clientSecret,\n\t\tScope:        scope,\n\t\tAuthURL:      authURL,\n\t\tTokenURL:     tokenURL,\n\t\tTokenCache:   oauth.CacheFile(c.GlobalString(\"cachefile\")),\n\t\tRedirectURL:  redirectURL,\n\t}, nil\n}\n\nfunc generateServiceConfig(c *cli.Context) (*gcssync.ServiceConfig, error) {\n\tprojectID := c.GlobalString(\"projectid\")\n\tif projectID == \"\" {\n\t\treturn &gcssync.ServiceConfig{}, fmt.Errorf(\"Could not find project id\")\n\t}\n\tbucketName := c.GlobalString(\"bucketname\")\n\tif bucketName == \"\" {\n\t\treturn &gcssync.ServiceConfig{}, fmt.Errorf(\"Cloud not find bucket name\")\n\t}\n\treturn &gcssync.ServiceConfig{\n\t\tProjectID:  projectID,\n\t\tBucketName: bucketName,\n\t}, nil\n}\n\nfunc getClient(c *cli.Context) *gcssync.Client {\n\toauthConfig, err := generateOAuthConfig(c)\n\tif err != nil {\n\t\tfmt.Println(\"Missing auth informations\", err.Error())\n\t\tos.Exit(errorAuthInfo)\n\t}\n\tserviceConfig, err := generateServiceConfig(c)\n\tif err != nil {\n\t\tfmt.Println(\"Missing project config\", err.Error())\n\t\tos.Exit(errorProjectInfo)\n\t}\n\n\tclient, err := gcssync.NewClient(oauthConfig, c.GlobalString(\"code\"), serviceConfig)\n\tif err != nil {\n\t\tfmt.Println(\"Error initilizing client: \", err.Error())\n\t\tos.Exit(errorClientInit)\n\t}\n\n\treturn client\n}\n\nfunc listFiles(c *cli.Context) {\n\tclient := getClient(c)\n\tfiles, err := client.ListFiles()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(errorListFiles)\n\t\treturn\n\t}\n\tfor _, object := range files {\n\t\tfmt.Printf(\"%s %s\\n\", object.Name, humanize.Bytes(object.Size))\n\t}\n\tfmt.Printf(\"Objects in %s - %d\\n\", client.GetBucketname(), len(files))\n}\n\nfunc uploadFile(c *cli.Context) {\n\tclient := getClient(c)\n\tif len(c.Args()) != 2 {\n\t\tfmt.Println(\"Need local and remote name!\")\n\t\tos.Exit(errorUploadFiles)\n\t}\n\n\tsuccess, object, err := client.UploadFile(c.Args().Get(0), c.Args().Get(1))\n\tif !success {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(errorUploadFiles)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Uploaded file to %s\\n\", client.GetBucketname())\n\tfmt.Printf(\"%s %s\\n\", object.Name, humanize.Bytes(object.Size))\n\n}\n\nfunc syncFolder(c *cli.Context) {\n\tclient := getClient(c)\n\tvar local, remote string\n\tswitch len(c.Args()) {\n\tcase 0:\n\t\tlocal = \"\"\n\t\tremote = \"\"\n\tcase 1:\n\t\tlocal = c.Args().Get(0)\n\t\tremote = \"\"\n\tcase 2:\n\t\tlocal = c.Args().Get(0)\n\t\tremote = c.Args().Get(1)\n\tdefault:\n\t\tfmt.Println(\"To many arguments\")\n\t\tos.Exit(errorSyncFiles)\n\t}\n\tlocal, err := filepath.Abs(local)\n\tif err != nil {\n\t\tfmt.Println(\"Could not get absolute path\")\n\t\tos.Exit(errorSyncFiles)\n\t}\n\tclient.SyncFolder(local, remote)\n}\n<commit_msg>fix(version): added versionnumber for first release<commit_after>package main\n\nimport (\n\t\"code.google.com\/p\/goauth2\/oauth\"\n\t\"code.google.com\/p\/google-api-go-client\/storage\/v1\"\n\t\"fmt\"\n\t\"github.com\/TheHippo\/gcssync\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/dustin\/go-humanize\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\nconst (\n\t_                = iota\n\terrorAuthInfo    = iota\n\terrorProjectInfo = iota\n\terrorClientInit  = iota\n\terrorListFiles   = iota\n\terrorUploadFiles = iota\n\terrorSyncFiles   = iota\n)\n\nconst (\n\tversion = \"0.1.0\"\n)\n\nconst (\n\tscope       = storage.DevstorageFull_controlScope\n\tauthURL     = \"https:\/\/accounts.google.com\/o\/oauth2\/auth\"\n\ttokenURL    = \"https:\/\/accounts.google.com\/o\/oauth2\/token\"\n\tentityName  = \"allUsers\"\n\tredirectURL = \"urn:ietf:wg:oauth:2.0:oob\"\n)\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"gcssync\"\n\tapp.Usage = \"Sync files with Google Cloud Storage\"\n\tapp.Version = version\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:   \"cachefile\",\n\t\t\tValue:  \"cache.json\",\n\t\t\tUsage:  \"Cache file for caching auth tokens\",\n\t\t\tEnvVar: \"AUTH_CACHE_FILE\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"bucketname, b\",\n\t\t\tValue:  \"\",\n\t\t\tUsage:  \"Name of bucket\",\n\t\t\tEnvVar: \"BUCKET_NAME\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"projectid, p\",\n\t\t\tValue:  \"\",\n\t\t\tUsage:  \"Google project\",\n\t\t\tEnvVar: \"PROJECT_ID\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"clientid, c\",\n\t\t\tValue:  \"\",\n\t\t\tUsage:  \"Auth client id\",\n\t\t\tEnvVar: \"AUTH_CLIENT_ID\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"clientsecret, s\",\n\t\t\tValue:  \"\",\n\t\t\tUsage:  \"Client secrect\",\n\t\t\tEnvVar: \"AUTH_CLIENT_SECRET\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"code\",\n\t\t\tValue:  \"\",\n\t\t\tUsage:  \"Authorization Code\",\n\t\t\tEnvVar: \"AUTH_CODE\",\n\t\t},\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:      \"list\",\n\t\t\tShortName: \"l\",\n\t\t\tUsage:     \"List remote files\",\n\t\t\tAction:    listFiles,\n\t\t},\n\t\t{\n\t\t\tName:      \"upload\",\n\t\t\tShortName: \"u\",\n\t\t\tUsage:     \"Upload a single file\",\n\t\t\tAction:    uploadFile,\n\t\t},\n\t\t{\n\t\t\tName:      \"sync\",\n\t\t\tShortName: \"s\",\n\t\t\tUsage:     \"Syncs a folder to a Google Cloudstorage bucket\",\n\t\t\tAction:    syncFolder,\n\t\t},\n\t}\n\tapp.Run(os.Args)\n}\n\nfunc generateOAuthConfig(c *cli.Context) (*oauth.Config, error) {\n\tclientId := c.GlobalString(\"clientid\")\n\tif clientId == \"\" {\n\t\treturn &oauth.Config{}, fmt.Errorf(\"Could not find Client ID\")\n\t}\n\tclientSecret := c.GlobalString(\"clientsecret\")\n\tif clientSecret == \"\" {\n\t\treturn &oauth.Config{}, fmt.Errorf(\"Could not find Client Secret\")\n\t}\n\n\treturn &oauth.Config{\n\t\tClientId:     clientId,\n\t\tClientSecret: clientSecret,\n\t\tScope:        scope,\n\t\tAuthURL:      authURL,\n\t\tTokenURL:     tokenURL,\n\t\tTokenCache:   oauth.CacheFile(c.GlobalString(\"cachefile\")),\n\t\tRedirectURL:  redirectURL,\n\t}, nil\n}\n\nfunc generateServiceConfig(c *cli.Context) (*gcssync.ServiceConfig, error) {\n\tprojectID := c.GlobalString(\"projectid\")\n\tif projectID == \"\" {\n\t\treturn &gcssync.ServiceConfig{}, fmt.Errorf(\"Could not find project id\")\n\t}\n\tbucketName := c.GlobalString(\"bucketname\")\n\tif bucketName == \"\" {\n\t\treturn &gcssync.ServiceConfig{}, fmt.Errorf(\"Cloud not find bucket name\")\n\t}\n\treturn &gcssync.ServiceConfig{\n\t\tProjectID:  projectID,\n\t\tBucketName: bucketName,\n\t}, nil\n}\n\nfunc getClient(c *cli.Context) *gcssync.Client {\n\toauthConfig, err := generateOAuthConfig(c)\n\tif err != nil {\n\t\tfmt.Println(\"Missing auth informations\", err.Error())\n\t\tos.Exit(errorAuthInfo)\n\t}\n\tserviceConfig, err := generateServiceConfig(c)\n\tif err != nil {\n\t\tfmt.Println(\"Missing project config\", err.Error())\n\t\tos.Exit(errorProjectInfo)\n\t}\n\n\tclient, err := gcssync.NewClient(oauthConfig, c.GlobalString(\"code\"), serviceConfig)\n\tif err != nil {\n\t\tfmt.Println(\"Error initilizing client: \", err.Error())\n\t\tos.Exit(errorClientInit)\n\t}\n\n\treturn client\n}\n\nfunc listFiles(c *cli.Context) {\n\tclient := getClient(c)\n\tfiles, err := client.ListFiles()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(errorListFiles)\n\t\treturn\n\t}\n\tfor _, object := range files {\n\t\tfmt.Printf(\"%s %s\\n\", object.Name, humanize.Bytes(object.Size))\n\t}\n\tfmt.Printf(\"Objects in %s - %d\\n\", client.GetBucketname(), len(files))\n}\n\nfunc uploadFile(c *cli.Context) {\n\tclient := getClient(c)\n\tif len(c.Args()) != 2 {\n\t\tfmt.Println(\"Need local and remote name!\")\n\t\tos.Exit(errorUploadFiles)\n\t}\n\n\tsuccess, object, err := client.UploadFile(c.Args().Get(0), c.Args().Get(1))\n\tif !success {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(errorUploadFiles)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"Uploaded file to %s\\n\", client.GetBucketname())\n\tfmt.Printf(\"%s %s\\n\", object.Name, humanize.Bytes(object.Size))\n\n}\n\nfunc syncFolder(c *cli.Context) {\n\tclient := getClient(c)\n\tvar local, remote string\n\tswitch len(c.Args()) {\n\tcase 0:\n\t\tlocal = \"\"\n\t\tremote = \"\"\n\tcase 1:\n\t\tlocal = c.Args().Get(0)\n\t\tremote = \"\"\n\tcase 2:\n\t\tlocal = c.Args().Get(0)\n\t\tremote = c.Args().Get(1)\n\tdefault:\n\t\tfmt.Println(\"To many arguments\")\n\t\tos.Exit(errorSyncFiles)\n\t}\n\tlocal, err := filepath.Abs(local)\n\tif err != nil {\n\t\tfmt.Println(\"Could not get absolute path\")\n\t\tos.Exit(errorSyncFiles)\n\t}\n\tclient.SyncFolder(local, remote)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2022 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nGovulncheck reports known vulnerabilities that affect Go code. It uses static\nanalysis of source code or a binary's symbol table to narrow down reports to\nonly those that potentially affect the application. For more information about\nthe API behind govulncheck, see https:\/\/go.dev\/security\/vuln\/vulncheck.\n\nBy default, govulncheck uses the Go vulnerability database at\nhttps:\/\/vuln.go.dev. Set the GOVULNDB environment variable to specify a\ndifferent database.  The database must follow the specification at\nhttps:\/\/go.dev\/security\/vuln\/database.\n\nGovulncheck requires Go version 1.18 or higher to run.\n\n# Usage\n\nTo analyze source code, run govulncheck from the module directory, using the\nsame package path syntax that the go command uses:\n\n\t$ cd my-module\n\t$ govulncheck .\/...\n\nIf no vulnerabilities are found, govulncheck will display a short message. If\nthere are vulnerabilities, each is displayed briefly, with a summary of a call\nstack.\n\nThe call stack summary shows in brief how the package calls a vulnerable\nfunction. For example, it might say\n\n\tmain.go:[line]:[column]: mypackage.main calls golang.org\/x\/text\/language.Parse\n\nFor a more detailed call path that resembles Go panic stack traces, use the -v\nflag.\n\nTo control which files are processed, use the -tags flag to provide a\ncomma-separated list of build tags, and the -tests flag to indicate that test\nfiles should be included.\n\nTo run govulncheck on a compiled binary, pass it the path to the binary file:\n\n\t$ govulncheck $HOME\/go\/bin\/my-go-program\n\nGovulncheck uses the binary's symbol information to find mentions of vulnerable\nfunctions. Its output and exit codes are as described above, except that\nwithout source it cannot produce call stacks.\n\n# Other Modes\n\nA few flags control govulncheck's output. Regardless of output, govulncheck\nexits successfully if there are no vulnerabilities, and exits unsuccessfully if\nthere are.\n\nThe -v flag outputs more information about call stacks when run on source. It\nhas no effect when run on a binary.\n\nThe -json flag outputs a JSON object with vulnerability information. The output\ncorresponds to the type golang.org\/x\/vuln\/vulncheck.Result.\n\n# Weaknesses\n\nGovulncheck is built on top of golang.org\/x\/vuln\/vulncheck library and thus\nshares its limitations described at\nhttps:\/\/go.dev\/security\/vulncheck#limitations.\n*\/\npackage main\n<commit_msg>cmd\/govulncheck: update docs<commit_after>\/\/ Copyright 2022 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\nGovulncheck reports known vulnerabilities that affect Go code. It uses static\nanalysis of source code or a binary's symbol table to narrow down reports to\nonly those that could affect the application.\n\nBy default, govulncheck makes requests to the Go vulnerability database at\nhttps:\/\/vuln.go.dev. Requests to the vulnerability database contain only module\npaths, not code or other properties of your program. See\nhttps:\/\/vuln.go.dev\/privacy.html for more. Set the GOVULNDB environment\nvariable to specify a different database, which must implement the\nspecification at https:\/\/go.dev\/security\/vuln\/database.\n\nGovulncheck looks for vulnerabilities in Go programs using a specific build\nconfiguration. For analyzing source code, that configuration is the operating\nsystem, architecture, and Go version specified by GOOS, GOARCH, and the “go”\ncommand found on the PATH. For binaries, the build configuration is the one\nused to build the binary. Note that different build configurations may have\ndifferent known vulnerabilities. For example, a dependency with a\nWindows-specific vulnerability will not be reported for a Linux build.\n\nGovulncheck must be built with Go version 1.18 or later.\n\n# Usage\n\nTo analyze source code, run govulncheck from the module directory, using the\nsame package path syntax that the go command uses:\n\n\t$ cd my-module\n\t$ govulncheck .\/...\n\nIf no vulnerabilities are found, govulncheck will display a short message. If\nthere are vulnerabilities, each is displayed briefly, with a summary of a call\nstack.\n\nThe call stack summary shows in brief how the package calls a vulnerable\nfunction. For example, it might say\n\n\tmain.go:[line]:[column]: mypackage.main calls golang.org\/x\/text\/language.Parse\n\nFor a more detailed call path that resembles Go panic stack traces, use the -v flag.\n\nTo control which files are processed, use the -tags flag to provide a\ncomma-separated list of build tags, and the -test flag to indicate that test\nfiles should be included.\n\nTo run govulncheck on a compiled binary, pass it the path to the binary file:\n\n\t$ govulncheck $HOME\/go\/bin\/my-go-program\n\nGovulncheck uses the binary's symbol information to find mentions of vulnerable\nfunctions. Its output omits call stacks, which require source code analysis.\n\nGovulncheck exits successfully (exit code 0) if there are no vulnerabilities,\nand exits unsuccessfully if there are.\n\n# Flags\n\nA few flags control govulncheck's behavior.\n\nThe -v flag causes govulncheck to output more information about call stacks\nwhen run on source. It has no effect when run on a binary.\n\nThe -json flag causes govulncheck to print its output as a JSON object\ncorresponding to the type [golang.org\/x\/vuln\/vulncheck.Result].\n\nThe -tags flag accepts a comma-separated list of build tags to control which\nfiles should be included in loaded packages for source analysis.\n\nThe -test flag causes govulncheck to include test files in the source analysis.\n\n# Limitations\n\nGovulncheck uses [golang.org\/x\/vuln\/vulncheck], which has these limitations:\n\n  - Govulncheck analyzes function pointer and interface calls conservatively,\n    which may result in false positives or inaccurate call stacks in some cases.\n  - Calls to functions made using package reflect are not visible to static\n    analysis. Vulnerable code reachable only through those calls will not be\n    reported.\n  - Because Go binaries do not contain detailed call information, vulncheck\n    cannot show the call graphs for detected vulnerabilities. It may also\n    report false positives for code that is in the binary but unreachable.\n  - Govulncheck does not report vulnerabilities in\n    vendored packages for binaries.\n  - There is no support for silencing vulnerability findings.\n  - Govulncheck only reads binaries compiled with Go 1.18 and later.\n\n# Feedback\n\nGovulncheck is an experimental tool under active development. To share\nfeedback, see https:\/\/go.dev\/security\/vuln#feedback.\n*\/\npackage main\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/gobs\/args\"\n\t\"github.com\/gobs\/cmd\"\n\t\"github.com\/gobs\/httpclient\"\n\t\"github.com\/gobs\/simplejson\"\n\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\tcompletion_words = []string{}\n)\n\nfunc CompletionFunction(text, line string) (matches []string) {\n\t\/\/ for the \"ls\" command we let readline show real file names\n\tif strings.HasPrefix(line, \"ls \") {\n\t\treturn\n\t}\n\n\t\/\/ for all other commands, we pick from our list of completion words\n\tfor _, w := range completion_words {\n\t\tif strings.HasPrefix(w, text) {\n\t\t\tmatches = append(matches, w)\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc request(client *httpclient.HttpClient, method, params string) *httpclient.HttpResponse {\n\toptions := []httpclient.RequestOption{client.Method(method)}\n\targs := args.ParseArgs(params)\n\n\tif len(args.Arguments) > 0 {\n\t\toptions = append(options, client.Path(args.Arguments[0]))\n\t}\n\n\tif len(args.Arguments) > 1 {\n\t\tdata := strings.Join(args.Arguments[1:], \" \")\n\t\toptions = append(options, client.Body(strings.NewReader(data)))\n\t}\n\n\tres, err := client.SendRequest(options...)\n\tif err == nil {\n\t\terr = res.ResponseError()\n\t}\n\tif err != nil {\n\t\tfmt.Println(\"ERROR:\", err)\n\t} else {\n\t\tbody := res.Content()\n\t\tfmt.Println(string(body))\n\t}\n\n\treturn res\n}\n\nfunc main() {\n\tvar interrupted bool\n\tvar client = httpclient.NewHttpClient(\"\")\n\n\tclient.UserAgent = \"httpclient\/0.1\"\n\n\tcommander := &cmd.Cmd{\n\t\tHistoryFile: \".httpclient_history\",\n\t\tComplete:    CompletionFunction,\n\t\tEnableShell: true,\n\t\tInterrupt:   func(sig os.Signal) bool { interrupted = true; return false },\n\t}\n\n\tcommander.Init()\n\n\tcommander.Vars = map[string]string{}\n\n\tcommander.Add(cmd.Command{\n\t\t\"base\",\n\t\t`base [url]`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tif line != \"\" {\n\t\t\t\tval, err := url.Parse(line)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tclient.BaseURL = val\n\t\t\t\tcommander.Prompt = fmt.Sprintf(\"%v> \", client.BaseURL)\n\t\t\t}\n\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\n\t\t\"insecure\",\n\t\t`insecure [true|false]`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tif line != \"\" {\n\t\t\t\tval, err := strconv.ParseBool(line)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tclient.AllowInsecure(val)\n\t\t\t}\n\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\n\t\t\"timeout\",\n\t\t`timeout [duration]`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tif line != \"\" {\n\t\t\t\tval, err := time.ParseDuration(line)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tclient.SetTimeout(val)\n\t\t\t}\n\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\n\t\t\"verbose\",\n\t\t`verbose [true|false]`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tif line != \"\" {\n\t\t\t\tval, err := strconv.ParseBool(line)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tclient.Verbose = val\n\t\t\t}\n\n\t\t\tfmt.Println(\"Verbose\", client.Verbose)\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\n\t\t\"agent\",\n\t\t`agent user-agent-string`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tif line != \"\" {\n\t\t\t\tclient.UserAgent = line\n\t\t\t}\n\n\t\t\tfmt.Println(\"User-Agent:\", client.UserAgent)\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\n\t\t\"header\",\n\t\t`header [name [value]]`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tif line == \"\" {\n\t\t\t\tif len(client.Headers) == 0 {\n\t\t\t\t\tfmt.Println(\"No headers\")\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"Headers:\")\n\t\t\t\t\tfor k, v := range client.Headers {\n\t\t\t\t\t\tfmt.Printf(\"  %v: %v\\n\", k, v)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tparts := strings.SplitN(line, \" \", 2)\n\t\t\tif len(parts) == 2 {\n\t\t\t\tclient.Headers[parts[0]] = parts[1]\n\t\t\t}\n\n\t\t\tfmt.Printf(\"%v: %v\\n\", parts[0], client.Headers[parts[0]])\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\"get\",\n\t\t`\n                get [url-path] [short-data]\n                `,\n\t\tfunc(line string) (stop bool) {\n\t\t\trequest(client, \"get\", line)\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\"head\",\n\t\t`\n                head [url-path] [short-data]\n                `,\n\t\tfunc(line string) (stop bool) {\n\t\t\tres := request(client, \"head\", line)\n\t\t\tif res != nil {\n\t\t\t\tfmt.Println(simplejson.MustDumpString(res.Header, simplejson.Indent(\"  \")))\n\t\t\t}\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\"post\",\n\t\t`\n                post [url-path] [short-data]\n                `,\n\t\tfunc(line string) (stop bool) {\n\t\t\trequest(client, \"post\", line)\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\"put\",\n\t\t`\n                put [url-path] [short-data]\n                `,\n\t\tfunc(line string) (stop bool) {\n\t\t\trequest(client, \"put\", line)\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\"delete\",\n\t\t`\n                delete [url-path] [short-data]\n                `,\n\t\tfunc(line string) (stop bool) {\n\t\t\trequest(client, \"delete\", line)\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\n\t\t\"exit\",\n\t\t`exit script`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tfmt.Println(\"goodbye!\")\n\t\t\treturn true\n\t\t},\n\t\tnil})\n\n\tswitch len(os.Args) {\n\tcase 1: \/\/ program name only\n\t\tbreak\n\n\tcase 2: \/\/ one arg - expect URL\n\t\tcommander.OneCmd(\"base \" + os.Args[1])\n\n\tdefault:\n\t\tfmt.Println(\"usage:\", os.Args[0], \"[base-url]\")\n\t\treturn\n\t}\n\n\tcommander.CmdLoop()\n}\n<commit_msg>Normalize header names (to Mixed-Case) and format JSON responses.<commit_after>package main\n\nimport (\n\t\"github.com\/gobs\/args\"\n\t\"github.com\/gobs\/cmd\"\n\t\"github.com\/gobs\/httpclient\"\n\t\"github.com\/gobs\/simplejson\"\n\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\tcompletion_words = []string{}\n)\n\nfunc CompletionFunction(text, line string) (matches []string) {\n\t\/\/ for the \"ls\" command we let readline show real file names\n\tif strings.HasPrefix(line, \"ls \") {\n\t\treturn\n\t}\n\n\t\/\/ for all other commands, we pick from our list of completion words\n\tfor _, w := range completion_words {\n\t\tif strings.HasPrefix(w, text) {\n\t\t\tmatches = append(matches, w)\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc request(client *httpclient.HttpClient, method, params string) *httpclient.HttpResponse {\n\toptions := []httpclient.RequestOption{client.Method(method)}\n\targs := args.ParseArgs(params)\n\n\tif len(args.Arguments) > 0 {\n\t\toptions = append(options, client.Path(args.Arguments[0]))\n\t}\n\n\tif len(args.Arguments) > 1 {\n\t\tdata := strings.Join(args.Arguments[1:], \" \")\n\t\toptions = append(options, client.Body(strings.NewReader(data)))\n\t}\n\n\tres, err := client.SendRequest(options...)\n\tif err == nil {\n\t\terr = res.ResponseError()\n\t}\n\tif err != nil {\n\t\tfmt.Println(\"ERROR:\", err)\n\t}\n\n\tbody := res.Content()\n\tif len(body) > 0 {\n\t\tif strings.Contains(res.Header.Get(\"Content-Type\"), \"json\") {\n\t\t\tjbody, err := simplejson.LoadBytes(body)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t} else {\n\t\t\t\tfmt.Println(simplejson.MustDumpString(jbody.Data(), simplejson.Indent(\"  \")))\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(string(body))\n\t\t}\n\t}\n\n\treturn res\n}\n\nfunc headerName(s string) string {\n\ts = strings.ToLower(s)\n\tparts := strings.Split(s, \"-\")\n\tfor i, p := range parts {\n\t\tif len(p) > 0 {\n\t\t\tparts[i] = strings.ToUpper(p[0:1]) + p[1:]\n\t\t}\n\t}\n\treturn strings.Join(parts, \"-\")\n}\n\nfunc unquote(s string) string {\n\tif res, err := strconv.Unquote(s); err == nil {\n\t\treturn res\n\t}\n\n\treturn s\n}\n\nfunc main() {\n\tvar interrupted bool\n\tvar client = httpclient.NewHttpClient(\"\")\n\n\tclient.UserAgent = \"httpclient\/0.1\"\n\n\tcommander := &cmd.Cmd{\n\t\tHistoryFile: \".httpclient_history\",\n\t\tComplete:    CompletionFunction,\n\t\tEnableShell: true,\n\t\tInterrupt:   func(sig os.Signal) bool { interrupted = true; return false },\n\t}\n\n\tcommander.Init()\n\n\tcommander.Vars = map[string]string{}\n\n\tcommander.Add(cmd.Command{\n\t\t\"base\",\n\t\t`base [url]`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tif line != \"\" {\n\t\t\t\tval, err := url.Parse(line)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tclient.BaseURL = val\n\t\t\t\tcommander.Prompt = fmt.Sprintf(\"%v> \", client.BaseURL)\n\t\t\t}\n\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\n\t\t\"insecure\",\n\t\t`insecure [true|false]`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tif line != \"\" {\n\t\t\t\tval, err := strconv.ParseBool(line)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tclient.AllowInsecure(val)\n\t\t\t}\n\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\n\t\t\"timeout\",\n\t\t`timeout [duration]`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tif line != \"\" {\n\t\t\t\tval, err := time.ParseDuration(line)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tclient.SetTimeout(val)\n\t\t\t}\n\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\n\t\t\"verbose\",\n\t\t`verbose [true|false]`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tif line != \"\" {\n\t\t\t\tval, err := strconv.ParseBool(line)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tclient.Verbose = val\n\t\t\t}\n\n\t\t\tfmt.Println(\"Verbose\", client.Verbose)\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\n\t\t\"agent\",\n\t\t`agent user-agent-string`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tif line != \"\" {\n\t\t\t\tclient.UserAgent = line\n\t\t\t}\n\n\t\t\tfmt.Println(\"User-Agent:\", client.UserAgent)\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\n\t\t\"header\",\n\t\t`header [name [value]]`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tif line == \"\" {\n\t\t\t\tif len(client.Headers) == 0 {\n\t\t\t\t\tfmt.Println(\"No headers\")\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"Headers:\")\n\t\t\t\t\tfor k, v := range client.Headers {\n\t\t\t\t\t\tfmt.Printf(\"  %v: %v\\n\", k, v)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tparts := args.GetArgsN(line, 2)\n\t\t\tname := headerName(parts[0])\n\n\t\t\tif len(parts) == 2 {\n\t\t\t\tclient.Headers[name] = unquote(parts[1])\n\t\t\t}\n\n\t\t\tfmt.Printf(\"%v: %v\\n\", name, client.Headers[name])\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\"get\",\n\t\t`\n                get [url-path] [short-data]\n                `,\n\t\tfunc(line string) (stop bool) {\n\t\t\trequest(client, \"get\", line)\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\"head\",\n\t\t`\n                head [url-path] [short-data]\n                `,\n\t\tfunc(line string) (stop bool) {\n\t\t\tres := request(client, \"head\", line)\n\t\t\tif res != nil {\n\t\t\t\tfmt.Println(simplejson.MustDumpString(res.Header, simplejson.Indent(\"  \")))\n\t\t\t}\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\"post\",\n\t\t`\n                post [url-path] [short-data]\n                `,\n\t\tfunc(line string) (stop bool) {\n\t\t\trequest(client, \"post\", line)\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\"put\",\n\t\t`\n                put [url-path] [short-data]\n                `,\n\t\tfunc(line string) (stop bool) {\n\t\t\trequest(client, \"put\", line)\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\"delete\",\n\t\t`\n                delete [url-path] [short-data]\n                `,\n\t\tfunc(line string) (stop bool) {\n\t\t\trequest(client, \"delete\", line)\n\t\t\treturn\n\t\t},\n\t\tnil})\n\n\tcommander.Add(cmd.Command{\n\t\t\"exit\",\n\t\t`exit script`,\n\t\tfunc(line string) (stop bool) {\n\t\t\tfmt.Println(\"goodbye!\")\n\t\t\treturn true\n\t\t},\n\t\tnil})\n\n\tswitch len(os.Args) {\n\tcase 1: \/\/ program name only\n\t\tbreak\n\n\tcase 2: \/\/ one arg - expect URL\n\t\tcommander.OneCmd(\"base \" + os.Args[1])\n\n\tdefault:\n\t\tfmt.Println(\"usage:\", os.Args[0], \"[base-url]\")\n\t\treturn\n\t}\n\n\tcommander.CmdLoop()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"text\/tabwriter\"\n\t\"time\"\n\n\t\"github.com\/influxdb\/influxdb\/cmd\/influx_tsm\/b1\"\n\t\"github.com\/influxdb\/influxdb\/cmd\/influx_tsm\/bz1\"\n\t\"github.com\/influxdb\/influxdb\/cmd\/influx_tsm\/tsdb\"\n)\n\ntype ShardReader interface {\n\tKeyIterator\n\tOpen() error\n\tClose() error\n}\n\nconst (\n\tbackupExt = \"bak\"\n\ttsmExt    = \"tsm\"\n)\n\nvar description = fmt.Sprintf(`\nConvert a database from b1 or bz1 format to tsm1 format.\n\nThis tool will backup any directory before conversion. It is up to the\nend-user to delete the backup on the disk, once the end-user is happy\nwith the converted data. Backups are named by suffixing the database\nname with '.%s'. The backups will be ignored by the system since they\nare not registered with the cluster.\n\nTo restore a backup, delete the tsm1 version, rename the backup directory\nrestart the node.`, backupExt)\n\nvar dataPath string\nvar ds string\nvar tsmSz uint64\nvar parallel bool\nvar disBack bool\n\nconst maxTSMSz = 2 * 1000 * 1000 * 1000\n\nfunc init() {\n\tflag.StringVar(&ds, \"dbs\", \"\", \"Comma-delimited list of databases to convert. Default is to convert all databases.\")\n\tflag.Uint64Var(&tsmSz, \"sz\", maxTSMSz, \"Maximum size of individual TSM files.\")\n\tflag.BoolVar(&parallel, \"parallel\", false, \"Perform parallel conversion.\")\n\tflag.BoolVar(&disBack, \"nobackup\", false, \"Disable database backups. Not recommended.\")\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s [options] <data-path> \\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, \"%s\\n\\n\", description)\n\t\tflag.PrintDefaults()\n\t\tfmt.Fprintf(os.Stderr, \"\\n\")\n\t}\n}\n\nfunc main() {\n\tpg := NewParallelGroup(1)\n\n\tflag.Parse()\n\tif len(flag.Args()) < 1 {\n\t\tfmt.Fprintf(os.Stderr, \"No data directory specified\\n\")\n\t\tos.Exit(1)\n\t}\n\tdataPath = flag.Args()[0]\n\n\tif tsmSz > maxTSMSz {\n\t\tfmt.Fprintf(os.Stderr, \"Maximum TSM file size is %d\\n\", maxTSMSz)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Check if specific directories were requested.\n\treqDs := strings.Split(ds, \",\")\n\tif len(reqDs) == 1 && reqDs[0] == \"\" {\n\t\treqDs = nil\n\t}\n\n\t\/\/ Determine the list of databases\n\tdbs, err := ioutil.ReadDir(dataPath)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to access data directory at %s: %s\\n\", dataPath, err.Error())\n\t\tos.Exit(1)\n\t}\n\tfmt.Println() \/\/ Cleanly separate output from start of program.\n\n\t\/\/ Dump summary of what is about to happen.\n\tfmt.Println(\"b1 and bz1 shard conversion.\")\n\tfmt.Println(\"-----------------------------------\")\n\tfmt.Println(\"Data directory is:       \", dataPath)\n\tfmt.Println(\"Databases specified:     \", allDBs(reqDs))\n\tfmt.Println(\"Database backups enabled:\", yesno(!disBack))\n\tfmt.Println(\"Parallel mode enabled:   \", yesno(parallel))\n\tfmt.Println()\n\n\t\/\/ Get the list of shards for conversion.\n\tvar shards []*tsdb.ShardInfo\n\tfor _, db := range dbs {\n\t\tif strings.HasSuffix(db.Name(), backupExt) {\n\t\t\tfmt.Printf(\"Skipping %s as it looks like a backup.\\n\", db.Name())\n\t\t\tcontinue\n\t\t}\n\n\t\td := tsdb.NewDatabase(filepath.Join(dataPath, db.Name()))\n\t\tshs, err := d.Shards()\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"failed to access shards for database %s: %s\\n\", d.Name(), err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t\tshards = append(shards, shs...)\n\t}\n\tsort.Sort(tsdb.ShardInfos(shards))\n\tusl := len(shards)\n\tshards = tsdb.ShardInfos(shards).FilterFormat(tsdb.TSM1).ExclusiveDatabases(reqDs)\n\tsl := len(shards)\n\n\t\/\/ Anything to convert?\n\tfmt.Printf(\"\\n%d shard(s) detected, %d non-TSM shards detected.\\n\", usl, sl)\n\tif len(shards) == 0 {\n\t\tfmt.Printf(\"Nothing to do.\\n\")\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Display list of convertible shards.\n\tfmt.Println()\n\tw := new(tabwriter.Writer)\n\tw.Init(os.Stdout, 0, 8, 1, '\\t', 0)\n\tfmt.Fprintln(w, \"Database\\tRetention\\tPath\\tEngine\\tSize\")\n\tfor _, si := range shards {\n\t\tfmt.Fprintf(w, \"%s\\t%s\\t%s\\t%s\\t%d\\n\", si.Database, si.RetentionPolicy, si.FullPath(dataPath), si.FormatAsString(), si.Size)\n\t}\n\tw.Flush()\n\n\t\/\/ Get confirmation from user.\n\tfmt.Printf(\"\\nThese shards will be converted. Proceed? y\/N: \")\n\tliner := bufio.NewReader(os.Stdin)\n\tyn, err := liner.ReadString('\\n')\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"failed to read response: %s\", err.Error())\n\t\tos.Exit(1)\n\t}\n\tyn = strings.TrimRight(strings.ToLower(yn), \"\\n\")\n\tif yn != \"y\" {\n\t\tfmt.Println(\"Conversion aborted.\")\n\t\tos.Exit(1)\n\t}\n\tfmt.Println(\"Conversion starting....\")\n\n\t\/\/ Backup each directory.\n\tconversionStart := time.Now()\n\tif !disBack {\n\t\tdatabases := tsdb.ShardInfos(shards).Databases()\n\t\tfmt.Printf(\"Backing up %d databases...\\n\", len(databases))\n\t\tif parallel {\n\t\t\tpg = NewParallelGroup(len(databases))\n\t\t}\n\t\tfor _, db := range databases {\n\t\t\tpg.Request()\n\t\t\tgo func(db string) {\n\t\t\t\tdefer pg.Release()\n\n\t\t\t\tstart := time.Now()\n\t\t\t\terr := backupDatabase(filepath.Join(dataPath, db))\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintf(os.Stderr, \"Backup of database %s failed: %s\\n\", db, err.Error())\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"Database %s backed up (%v)\\n\", db, time.Now().Sub(start))\n\t\t\t}(db)\n\t\t}\n\t\tpg.Wait()\n\t} else {\n\t\tfmt.Println(\"Database backup disabled.\")\n\t}\n\n\t\/\/ Convert each shard.\n\tif parallel {\n\t\tpg = NewParallelGroup(len(shards))\n\t}\n\tfor _, si := range shards {\n\t\tpg.Request()\n\t\tgo func(si *tsdb.ShardInfo) {\n\t\t\tdefer pg.Release()\n\n\t\t\tstart := time.Now()\n\t\t\tif err := convertShard(si); err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"Failed to convert %s: %s\\n\", si.FullPath(dataPath), err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tfmt.Printf(\"Conversion of %s successful (%s)\\n\", si.FullPath(dataPath), time.Now().Sub(start))\n\t\t}(si)\n\t}\n\tpg.Wait()\n\n\t\/\/ Dump stats.\n\tpreSize := tsdb.ShardInfos(shards).Size()\n\tpostSize := TsmBytesWritten\n\tfmt.Printf(\"\\nSummary statistics\\n========================================\\n\")\n\tfmt.Printf(\"Databases converted:                 %d\\n\", len(tsdb.ShardInfos(shards).Databases()))\n\tfmt.Printf(\"Shards converted:                    %d\\n\", len(shards))\n\tfmt.Printf(\"TSM files created:                   %d\\n\", TsmFilesCreated)\n\tfmt.Printf(\"Points read:                         %d\\n\", PointsRead)\n\tfmt.Printf(\"Points written:                      %d\\n\", PointsWritten)\n\tfmt.Printf(\"NaN filtered:                        %d\\n\", NanFiltered)\n\tfmt.Printf(\"Inf filtered:                        %d\\n\", InfFiltered)\n\tfmt.Printf(\"Points without fields filtered:      %d\\n\", b1.NoFieldsFiltered+bz1.NoFieldsFiltered)\n\tfmt.Printf(\"Disk usage pre-conversion (bytes):   %d\\n\", preSize)\n\tfmt.Printf(\"Disk usage post-conversion (bytes):  %d\\n\", postSize)\n\tfmt.Printf(\"Reduction factor:                    %d%%\\n\", (100*preSize-postSize)\/preSize)\n\tfmt.Printf(\"Bytes per TSM point:                 %.2f\\n\", float64(postSize)\/float64(PointsWritten))\n\tfmt.Printf(\"Total conversion time:               %v\\n\", time.Now().Sub(conversionStart))\n\tfmt.Println()\n}\n\n\/\/ backupDatabase backs up the database at src.\nfunc backupDatabase(src string) error {\n\tdest := filepath.Join(src + \".\" + backupExt)\n\tif _, err := os.Stat(dest); !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"backup of %s already exists\", src)\n\t}\n\treturn copyDir(dest, src)\n}\n\n\/\/ copyDir copies the directory at src to dest. If dest does not exist it\n\/\/ will be created. It is up to the caller to ensure the paths don't overlap.\nfunc copyDir(dest, src string) error {\n\tcopyFile := func(path string, info os.FileInfo, err error) error {\n\t\t\/\/ Strip the src from the path and replace with dest.\n\t\ttoPath := strings.Replace(path, src, dest, 1)\n\n\t\t\/\/ Copy it.\n\t\tif info.IsDir() {\n\t\t\tif err := os.MkdirAll(toPath, info.Mode()); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\terr := func() error {\n\t\t\t\tin, err := os.Open(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tdefer in.Close()\n\n\t\t\t\tout, err := os.OpenFile(toPath, os.O_CREATE|os.O_WRONLY, info.Mode())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tdefer out.Close()\n\n\t\t\t\t_, err = io.Copy(out, in)\n\t\t\t\treturn err\n\t\t\t}()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn filepath.Walk(src, copyFile)\n}\n\n\/\/ convertShard converts the shard in-place.\nfunc convertShard(si *tsdb.ShardInfo) error {\n\tsrc := si.FullPath(dataPath)\n\tdst := fmt.Sprintf(\"%s.%s\", src, tsmExt)\n\n\tvar reader ShardReader\n\tswitch si.Format {\n\tcase tsdb.BZ1:\n\t\treader = bz1.NewReader(src)\n\tcase tsdb.B1:\n\t\treader = b1.NewReader(src)\n\tdefault:\n\t\treturn fmt.Errorf(\"Unsupported shard format: %s\", si.FormatAsString())\n\t}\n\tdefer reader.Close()\n\n\t\/\/ Open the shard, and create a converter.\n\tif err := reader.Open(); err != nil {\n\t\treturn fmt.Errorf(\"Failed to open %s for conversion: %s\", src, err.Error())\n\t}\n\tconverter := NewConverter(dst, uint32(tsmSz))\n\n\t\/\/ Perform the conversion.\n\tif err := converter.Process(reader); err != nil {\n\t\treturn fmt.Errorf(\"Conversion of %s failed: %s\", src, err.Error())\n\t}\n\n\t\/\/ Delete source shard, and rename new tsm1 shard.\n\tif err := reader.Close(); err != nil {\n\t\treturn fmt.Errorf(\"Conversion of %s failed due to close: %s\", src, err.Error())\n\t}\n\n\tif err := os.RemoveAll(si.FullPath(dataPath)); err != nil {\n\t\treturn fmt.Errorf(\"Deletion of %s failed: %s\", src, err.Error())\n\t}\n\tif err := os.Rename(dst, src); err != nil {\n\t\treturn fmt.Errorf(\"Rename of %s to %s failed: %s\", dst, src, err.Error())\n\t}\n\n\treturn nil\n}\n\n\/\/ ParallelGroup allows the maximum parrallelism of a set of operations to be controlled.\ntype ParallelGroup struct {\n\tc  chan struct{}\n\twg sync.WaitGroup\n}\n\n\/\/ NewParallelGroup returns a group which allows n operations to run in parallel. A value of 0\n\/\/ means no operations will ever run.\nfunc NewParallelGroup(n int) *ParallelGroup {\n\treturn &ParallelGroup{\n\t\tc: make(chan struct{}, n),\n\t}\n}\n\n\/\/ Request requests permission to start an operation. It will block unless and until\n\/\/ the parallel requirements would not be violated.\nfunc (p *ParallelGroup) Request() {\n\tp.wg.Add(1)\n\tp.c <- struct{}{}\n}\n\n\/\/ Release informs the group that a previoulsy requested operation has completed.\nfunc (p *ParallelGroup) Release() {\n\t<-p.c\n\tp.wg.Done()\n}\n\n\/\/ Wait blocks until the ParallelGroup has no unreleased operations.\nfunc (p *ParallelGroup) Wait() {\n\tp.wg.Wait()\n}\n\n\/\/ yesno returns \"yes\" for true, \"no\" for false.\nfunc yesno(b bool) string {\n\tif b {\n\t\treturn \"yes\"\n\t}\n\treturn \"no\"\n}\n\n\/\/ allDBs returns \"all\" if all databases are requested for conversion.\nfunc allDBs(dbs []string) string {\n\tif dbs == nil {\n\t\treturn \"all\"\n\t}\n\treturn fmt.Sprintf(\"%v\", dbs)\n}\n<commit_msg>Limit parallelism for 'influx_tsm -parallel'<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"text\/tabwriter\"\n\t\"time\"\n\n\t\"github.com\/influxdb\/influxdb\/cmd\/influx_tsm\/b1\"\n\t\"github.com\/influxdb\/influxdb\/cmd\/influx_tsm\/bz1\"\n\t\"github.com\/influxdb\/influxdb\/cmd\/influx_tsm\/tsdb\"\n)\n\ntype ShardReader interface {\n\tKeyIterator\n\tOpen() error\n\tClose() error\n}\n\nconst (\n\tbackupExt = \"bak\"\n\ttsmExt    = \"tsm\"\n)\n\nvar description = fmt.Sprintf(`\nConvert a database from b1 or bz1 format to tsm1 format.\n\nThis tool will backup any directory before conversion. It is up to the\nend-user to delete the backup on the disk, once the end-user is happy\nwith the converted data. Backups are named by suffixing the database\nname with '.%v'. The backups will be ignored by the system since they\nare not registered with the cluster.\n\nTo restore a backup, delete the tsm1 version, rename the backup directory\nrestart the node.`, backupExt)\n\ntype options struct {\n\tDataPath       string\n\tDBs            []string\n\tTSMSize        uint64\n\tParallel       bool\n\tSkipBackup     bool\n\tUpdateInterval time.Duration\n\tQuiet          bool\n}\n\nfunc (o *options) Parse() error {\n\tfs := flag.NewFlagSet(os.Args[0], flag.ExitOnError)\n\n\tvar dbs string\n\n\tfs.StringVar(&dbs, \"dbs\", \"\", \"Comma-delimited list of databases to convert. Default is to convert all databases.\")\n\tfs.Uint64Var(&opts.TSMSize, \"sz\", maxTSMSz, \"Maximum size of individual TSM files.\")\n\tfs.BoolVar(&opts.Parallel, \"parallel\", false, \"Perform parallel conversion. (up to GOMAXPROCS shards at once)\")\n\tfs.BoolVar(&opts.SkipBackup, \"nobackup\", false, \"Disable database backups. Not recommended.\")\n\tfs.BoolVar(&opts.Quiet, \"quiet\", false, \"Suppresses the regular status updates.\")\n\tfs.DurationVar(&opts.UpdateInterval, \"interval\", 5*time.Second, \"How often status updates are printed.\")\n\tfs.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %v [options] <data-path> \\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\\n\", description)\n\t\tfs.PrintDefaults()\n\t\tfmt.Fprintf(os.Stderr, \"\\n\")\n\t}\n\n\tif err := fs.Parse(os.Args[1:]); err != nil {\n\t\treturn err\n\t}\n\n\tif len(fs.Args()) < 1 {\n\t\treturn errors.New(\"no data directory specified\")\n\t}\n\to.DataPath = fs.Args()[0]\n\n\tif o.TSMSize > maxTSMSz {\n\t\treturn fmt.Errorf(\"bad TSM file size, maximum TSM file size is %d\", maxTSMSz)\n\t}\n\n\t\/\/ Check if specific databases were requested.\n\to.DBs = strings.Split(dbs, \",\")\n\tif len(o.DBs) == 1 && o.DBs[0] == \"\" {\n\t\to.DBs = nil\n\t}\n\n\treturn nil\n}\n\nvar opts options\n\nconst maxTSMSz = 2 * 1000 * 1000 * 1000\n\nfunc init() {\n\tlog.SetOutput(os.Stderr)\n\tlog.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)\n}\n\nfunc main() {\n\tif err := opts.Parse(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Determine the list of databases\n\tdbs, err := ioutil.ReadDir(opts.DataPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to access data directory at %v: %v\\n\", opts.DataPath, err)\n\t}\n\tfmt.Println() \/\/ Cleanly separate output from start of program.\n\n\tif opts.Parallel {\n\t\tif !isEnvSet(\"GOMAXPROCS\") {\n\t\t\t\/\/ Only modify GOMAXPROCS if it wasn't set in the environment\n\t\t\t\/\/ This means 'GOMAXPROCS=1 influx_tsm -parallel' will not actually\n\t\t\t\/\/ run in parallel\n\t\t\truntime.GOMAXPROCS(runtime.NumCPU())\n\t\t}\n\t}\n\n\t\/\/ Dump summary of what is about to happen.\n\tfmt.Println(\"b1 and bz1 shard conversion.\")\n\tfmt.Println(\"-----------------------------------\")\n\tfmt.Println(\"Data directory is:       \", opts.DataPath)\n\tfmt.Println(\"Databases specified:     \", allDBs(opts.DBs))\n\tfmt.Println(\"Database backups enabled:\", yesno(!opts.SkipBackup))\n\tfmt.Println(\"Parallel mode enabled:   \", yesno(opts.Parallel), runtime.GOMAXPROCS(0))\n\tfmt.Println()\n\n\tshards := collectShards(dbs)\n\n\t\/\/ Anything to convert?\n\tfmt.Printf(\"\\nFound %d shards that will be converted.\\n\", len(shards))\n\tif len(shards) == 0 {\n\t\tfmt.Println(\"Nothing to do.\")\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Display list of convertible shards.\n\tfmt.Println()\n\tw := new(tabwriter.Writer)\n\tw.Init(os.Stdout, 0, 8, 1, '\\t', 0)\n\tfmt.Fprintln(w, \"Database\\tRetention\\tPath\\tEngine\\tSize\")\n\tfor _, si := range shards {\n\t\tfmt.Fprintf(w, \"%v\\t%v\\t%v\\t%v\\t%d\\n\", si.Database, si.RetentionPolicy, si.FullPath(opts.DataPath), si.FormatAsString(), si.Size)\n\t}\n\tw.Flush()\n\n\t\/\/ Get confirmation from user.\n\tfmt.Printf(\"\\nThese shards will be converted. Proceed? y\/N: \")\n\tliner := bufio.NewReader(os.Stdin)\n\tyn, err := liner.ReadString('\\n')\n\tif err != nil {\n\t\tlog.Printf(\"failed to read response: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tyn = strings.TrimRight(strings.ToLower(yn), \"\\n\")\n\tif yn != \"y\" {\n\t\tfmt.Println(\"Conversion aborted.\")\n\t\tos.Exit(1)\n\t}\n\tfmt.Println(\"Conversion starting....\")\n\n\t\/\/ GOMAXPROCS(0) just queires the current value\n\tpg := NewParallelGroup(runtime.GOMAXPROCS(0))\n\tvar wg sync.WaitGroup\n\n\tconversionStart := time.Now()\n\n\t\/\/ Backup each directory.\n\tif !opts.SkipBackup {\n\t\tdatabases := shards.Databases()\n\t\tfmt.Printf(\"Backing up %d databases...\\n\", len(databases))\n\t\twg.Add(len(databases))\n\t\tfor i := range databases {\n\t\t\tdb := databases[i]\n\t\t\tgo pg.Do(func() {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tstart := time.Now()\n\t\t\t\tlog.Printf(\"Backup of databse '%v' started\", db)\n\t\t\t\terr := backupDatabase(filepath.Join(opts.DataPath, db))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Backup of database %v failed: %v\\n\", db, err)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"Database %v backed up (%v)\\n\", db, time.Now().Sub(start))\n\t\t\t})\n\t\t}\n\t\twg.Wait()\n\t} else {\n\t\tfmt.Println(\"Database backup disabled.\")\n\t}\n\n\twg.Add(len(shards))\n\tfor i := range shards {\n\t\tsi := shards[i]\n\t\tgo pg.Do(func() {\n\t\t\tdefer wg.Done()\n\n\t\t\tstart := time.Now()\n\t\t\tlog.Printf(\"Starting conversion of shard: %v\", si.FullPath(opts.DataPath))\n\t\t\tif err := convertShard(si); err != nil {\n\t\t\t\tlog.Printf(\"Failed to convert %v: %v\\n\", si.FullPath(opts.DataPath), err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tlog.Printf(\"Conversion of %v successful (%v)\\n\", si.FullPath(opts.DataPath), time.Since(start))\n\t\t})\n\t}\n\twg.Wait()\n\n\t\/\/ Dump stats.\n\tpreSize := shards.Size()\n\tpostSize := TsmBytesWritten\n\ttotalTime := time.Since(conversionStart)\n\n\tfmt.Printf(\"\\nSummary statistics\\n========================================\\n\")\n\tfmt.Printf(\"Databases converted:                 %d\\n\", len(shards.Databases()))\n\tfmt.Printf(\"Shards converted:                    %d\\n\", len(shards))\n\tfmt.Printf(\"TSM files created:                   %d\\n\", TsmFilesCreated)\n\tfmt.Printf(\"Points read:                         %d\\n\", PointsRead)\n\tfmt.Printf(\"Points written:                      %d\\n\", PointsWritten)\n\tfmt.Printf(\"NaN filtered:                        %d\\n\", NanFiltered)\n\tfmt.Printf(\"Inf filtered:                        %d\\n\", InfFiltered)\n\tfmt.Printf(\"Points without fields filtered:      %d\\n\", b1.NoFieldsFiltered+bz1.NoFieldsFiltered)\n\tfmt.Printf(\"Disk usage pre-conversion (bytes):   %d\\n\", preSize)\n\tfmt.Printf(\"Disk usage post-conversion (bytes):  %d\\n\", postSize)\n\tfmt.Printf(\"Reduction factor:                    %d%%\\n\", 100*(preSize-postSize)\/preSize)\n\tfmt.Printf(\"Bytes per TSM point:                 %.2f\\n\", float64(postSize)\/float64(PointsWritten))\n\tfmt.Printf(\"Total conversion time:               %v\\n\", totalTime)\n\tfmt.Println()\n}\n\nfunc collectShards(dbs []os.FileInfo) tsdb.ShardInfos {\n\t\/\/ Get the list of shards for conversion.\n\tvar shards tsdb.ShardInfos\n\tfor _, db := range dbs {\n\t\tif strings.HasSuffix(db.Name(), backupExt) {\n\t\t\tlog.Printf(\"Skipping %v as it looks like a backup.\\n\", db.Name())\n\t\t\tcontinue\n\t\t}\n\n\t\td := tsdb.NewDatabase(filepath.Join(opts.DataPath, db.Name()))\n\t\tshs, err := d.Shards()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to access shards for database %v: %v\\n\", d.Name(), err)\n\t\t}\n\t\tshards = append(shards, shs...)\n\t}\n\n\tsort.Sort(shards)\n\tshards = shards.FilterFormat(tsdb.TSM1)\n\tif len(dbs) > 0 {\n\t\tshards = shards.ExclusiveDatabases(opts.DBs)\n\t}\n\n\treturn shards\n}\n\n\/\/ backupDatabase backs up the database at src.\nfunc backupDatabase(src string) error {\n\tdest := filepath.Join(src + \".\" + backupExt)\n\treturn copyDir(dest, src)\n}\n\n\/\/ copyDir copies the directory at src to dest. If dest does not exist it\n\/\/ will be created. It is up to the caller to ensure the paths don't overlap.\nfunc copyDir(dest, src string) error {\n\tcopyFile := func(path string, info os.FileInfo, err error) error {\n\t\t\/\/ Strip the src from the path and replace with dest.\n\t\ttoPath := strings.Replace(path, src, dest, 1)\n\n\t\t\/\/ Copy it.\n\t\tif info.IsDir() {\n\t\t\tif err := os.MkdirAll(toPath, info.Mode()); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\terr := func() error {\n\t\t\t\tin, err := os.Open(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tdefer in.Close()\n\n\t\t\t\tout, err := os.OpenFile(toPath, os.O_CREATE|os.O_WRONLY, info.Mode())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tdefer out.Close()\n\n\t\t\t\t_, err = io.Copy(out, in)\n\t\t\t\treturn err\n\t\t\t}()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn filepath.Walk(src, copyFile)\n}\n\n\/\/ convertShard converts the shard in-place.\nfunc convertShard(si *tsdb.ShardInfo) error {\n\tsrc := si.FullPath(opts.DataPath)\n\tdst := fmt.Sprintf(\"%v.%v\", src, tsmExt)\n\n\tvar reader ShardReader\n\tswitch si.Format {\n\tcase tsdb.BZ1:\n\t\treader = bz1.NewReader(src)\n\tcase tsdb.B1:\n\t\treader = b1.NewReader(src)\n\tdefault:\n\t\treturn fmt.Errorf(\"Unsupported shard format: %v\", si.FormatAsString())\n\t}\n\tdefer reader.Close()\n\n\t\/\/ Open the shard, and create a converter.\n\tif err := reader.Open(); err != nil {\n\t\treturn fmt.Errorf(\"Failed to open %v for conversion: %v\", src, err)\n\t}\n\tconverter := NewConverter(dst, uint32(opts.TSMSize))\n\n\t\/\/ Perform the conversion.\n\tif err := converter.Process(reader); err != nil {\n\t\treturn fmt.Errorf(\"Conversion of %v failed: %v\", src, err)\n\t}\n\n\t\/\/ Delete source shard, and rename new tsm1 shard.\n\tif err := reader.Close(); err != nil {\n\t\treturn fmt.Errorf(\"Conversion of %v failed due to close: %v\", src, err)\n\t}\n\n\tif err := os.RemoveAll(si.FullPath(opts.DataPath)); err != nil {\n\t\treturn fmt.Errorf(\"Deletion of %v failed: %v\", src, err)\n\t}\n\tif err := os.Rename(dst, src); err != nil {\n\t\treturn fmt.Errorf(\"Rename of %v to %v failed: %v\", dst, src, err)\n\t}\n\n\treturn nil\n}\n\n\/\/ ParallelGroup allows the maximum parrallelism of a set of operations to be controlled.\ntype ParallelGroup chan struct{}\n\n\/\/ NewParallelGroup returns a group which allows n operations to run in parallel. A value of 0\n\/\/ means no operations will ever run.\nfunc NewParallelGroup(n int) ParallelGroup {\n\treturn make(chan struct{}, n)\n}\n\nfunc (p ParallelGroup) Do(f func()) {\n\tp <- struct{}{} \/\/ acquire working slot\n\tdefer func() { <-p }()\n\n\tf()\n}\n\n\/\/ yesno returns \"yes\" for true, \"no\" for false.\nfunc yesno(b bool) string {\n\tif b {\n\t\treturn \"yes\"\n\t}\n\treturn \"no\"\n}\n\n\/\/ allDBs returns \"all\" if all databases are requested for conversion.\nfunc allDBs(dbs []string) string {\n\tif dbs == nil {\n\t\treturn \"all\"\n\t}\n\treturn fmt.Sprintf(\"%v\", dbs)\n}\n\n\/\/ isEnvSet checks to see if a variable was set in the environment\nfunc isEnvSet(name string) bool {\n\tfor _, s := range os.Environ() {\n\t\tif strings.SplitN(s, \"=\", 2)[0] == name {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/zyedidia\/clipboard\"\n\t\"github.com\/zyedidia\/tcell\"\n)\n\n\/\/ TermMessage sends a message to the user in the terminal. This usually occurs before\n\/\/ micro has been fully initialized -- ie if there is an error in the syntax highlighting\n\/\/ regular expressions\n\/\/ The function must be called when the screen is not initialized\n\/\/ This will write the message, and wait for the user\n\/\/ to press and key to continue\nfunc TermMessage(msg ...interface{}) {\n\tscreenWasNil := screen == nil\n\tif !screenWasNil {\n\t\tscreen.Fini()\n\t}\n\n\tfmt.Println(msg...)\n\tfmt.Print(\"\\nPress enter to continue\")\n\n\treader := bufio.NewReader(os.Stdin)\n\treader.ReadString('\\n')\n\n\tif !screenWasNil {\n\t\tInitScreen()\n\t}\n}\n\n\/\/ TermError sends an error to the user in the terminal. Like TermMessage except formatted\n\/\/ as an error\nfunc TermError(filename string, lineNum int, err string) {\n\tTermMessage(filename + \", \" + strconv.Itoa(lineNum) + \": \" + err)\n}\n\n\/\/ Messenger is an object that makes it easy to send messages to the user\n\/\/ and get input from the user\ntype Messenger struct {\n\t\/\/ Are we currently prompting the user?\n\thasPrompt bool\n\t\/\/ Is there a message to print\n\thasMessage bool\n\n\t\/\/ Message to print\n\tmessage string\n\t\/\/ The user's response to a prompt\n\tresponse string\n\t\/\/ style to use when drawing the message\n\tstyle tcell.Style\n\n\t\/\/ We have to keep track of the cursor for prompting\n\tcursorx int\n\n\t\/\/ This map stores the history for all the different kinds of uses Prompt has\n\t\/\/ It's a map of history type -> history array\n\thistory    map[string][]string\n\thistoryNum int\n\n\t\/\/ Is the current message a message from the gutter\n\tgutterMessage bool\n}\n\n\/\/ Message sends a message to the user\nfunc (m *Messenger) Message(msg ...interface{}) {\n\tbuf := new(bytes.Buffer)\n\tfmt.Fprint(buf, msg...)\n\tm.message = buf.String()\n\tm.style = defStyle\n\n\tif _, ok := colorscheme[\"message\"]; ok {\n\t\tm.style = colorscheme[\"message\"]\n\t}\n\tm.hasMessage = true\n}\n\n\/\/ Error sends an error message to the user\nfunc (m *Messenger) Error(msg ...interface{}) {\n\tbuf := new(bytes.Buffer)\n\tfmt.Fprint(buf, msg...)\n\tm.message = buf.String()\n\tm.style = defStyle.\n\t\tForeground(tcell.ColorBlack).\n\t\tBackground(tcell.ColorMaroon)\n\n\tif _, ok := colorscheme[\"error-message\"]; ok {\n\t\tm.style = colorscheme[\"error-message\"]\n\t}\n\tm.hasMessage = true\n}\n\n\/\/ YesNoPrompt asks the user a yes or no question (waits for y or n) and returns the result\nfunc (m *Messenger) YesNoPrompt(prompt string) (bool, bool) {\n\tm.Message(prompt)\n\n\t_, h := screen.Size()\n\tfor {\n\t\tm.Clear()\n\t\tm.Display()\n\t\tscreen.ShowCursor(Count(m.message), h-1)\n\t\tscreen.Show()\n\t\tevent := <-events\n\n\t\tswitch e := event.(type) {\n\t\tcase *tcell.EventKey:\n\t\t\tswitch e.Key() {\n\t\t\tcase tcell.KeyRune:\n\t\t\t\tif e.Rune() == 'y' {\n\t\t\t\t\treturn true, false\n\t\t\t\t} else if e.Rune() == 'n' {\n\t\t\t\t\treturn false, false\n\t\t\t\t}\n\t\t\tcase tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:\n\t\t\t\treturn false, true\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ LetterPrompt gives the user a prompt and waits for a one letter response\nfunc (m *Messenger) LetterPrompt(prompt string, responses ...rune) (rune, bool) {\n\tm.Message(prompt)\n\n\t_, h := screen.Size()\n\tfor {\n\t\tm.Clear()\n\t\tm.Display()\n\t\tscreen.ShowCursor(Count(m.message), h-1)\n\t\tscreen.Show()\n\t\tevent := <-events\n\n\t\tswitch e := event.(type) {\n\t\tcase *tcell.EventKey:\n\t\t\tswitch e.Key() {\n\t\t\tcase tcell.KeyRune:\n\t\t\t\tfor _, r := range responses {\n\t\t\t\t\tif e.Rune() == r {\n\t\t\t\t\t\tm.Reset()\n\t\t\t\t\t\treturn r, false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:\n\t\t\t\treturn ' ', true\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype Completion int\n\nconst (\n\tNoCompletion Completion = iota\n\tFileCompletion\n\tCommandCompletion\n\tHelpCompletion\n\tOptionCompletion\n)\n\n\/\/ Prompt sends the user a message and waits for a response to be typed in\n\/\/ This function blocks the main loop while waiting for input\nfunc (m *Messenger) Prompt(prompt, historyType string, completionTypes ...Completion) (string, bool) {\n\tm.hasPrompt = true\n\tm.Message(prompt)\n\tif _, ok := m.history[historyType]; !ok {\n\t\tm.history[historyType] = []string{\"\"}\n\t} else {\n\t\tm.history[historyType] = append(m.history[historyType], \"\")\n\t}\n\tm.historyNum = len(m.history[historyType]) - 1\n\n\tresponse, canceled := \"\", true\n\n\tRedrawAll()\n\tfor m.hasPrompt {\n\t\tvar suggestions []string\n\t\tm.Clear()\n\n\t\tevent := <-events\n\n\t\tswitch e := event.(type) {\n\t\tcase *tcell.EventKey:\n\t\t\tswitch e.Key() {\n\t\t\tcase tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:\n\t\t\t\t\/\/ Cancel\n\t\t\t\tm.hasPrompt = false\n\t\t\tcase tcell.KeyEnter:\n\t\t\t\t\/\/ User is done entering their response\n\t\t\t\tm.hasPrompt = false\n\t\t\t\tresponse, canceled = m.response, false\n\t\t\t\tm.history[historyType][len(m.history[historyType])-1] = response\n\t\t\tcase tcell.KeyTab:\n\t\t\t\targs := strings.Split(m.response, \" \")\n\t\t\t\tcurrentArgNum := len(args) - 1\n\t\t\t\tcurrentArg := args[currentArgNum]\n\t\t\t\tvar completionType Completion\n\n\t\t\t\tif completionTypes[0] == CommandCompletion && currentArgNum > 0 {\n\t\t\t\t\tif command, ok := commands[args[0]]; ok {\n\t\t\t\t\t\tcompletionTypes = append([]Completion{CommandCompletion}, command.completions...)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif currentArgNum >= len(completionTypes) {\n\t\t\t\t\tcompletionType = completionTypes[len(completionTypes)-1]\n\t\t\t\t} else {\n\t\t\t\t\tcompletionType = completionTypes[currentArgNum]\n\t\t\t\t}\n\n\t\t\t\tvar chosen string\n\t\t\t\tif completionType == FileCompletion {\n\t\t\t\t\tchosen, suggestions = FileComplete(currentArg)\n\t\t\t\t} else if completionType == CommandCompletion {\n\t\t\t\t\tchosen, suggestions = CommandComplete(currentArg)\n\t\t\t\t} else if completionType == HelpCompletion {\n\t\t\t\t\tchosen, suggestions = HelpComplete(currentArg)\n\t\t\t\t} else if completionType == OptionCompletion {\n\t\t\t\t\tchosen, suggestions = OptionComplete(currentArg)\n\t\t\t\t}\n\n\t\t\t\tif len(suggestions) > 1 {\n\t\t\t\t\tchosen = chosen + CommonSubstring(suggestions...)\n\t\t\t\t}\n\n\t\t\t\tif chosen != \"\" {\n\t\t\t\t\tif len(args) > 1 {\n\t\t\t\t\t\tchosen = \" \" + chosen\n\t\t\t\t\t}\n\t\t\t\t\tm.response = strings.Join(args[:len(args)-1], \" \") + chosen\n\t\t\t\t\tm.cursorx = Count(m.response)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tm.HandleEvent(event, m.history[historyType])\n\n\t\tmessenger.Clear()\n\t\tfor _, v := range tabs[curTab].views {\n\t\t\tv.Display()\n\t\t}\n\t\tDisplayTabs()\n\t\tmessenger.Display()\n\t\tif len(suggestions) > 1 {\n\t\t\tm.DisplaySuggestions(suggestions)\n\t\t}\n\t\tscreen.Show()\n\t}\n\n\tm.Reset()\n\treturn response, canceled\n}\n\n\/\/ HandleEvent handles an event for the prompter\nfunc (m *Messenger) HandleEvent(event tcell.Event, history []string) {\n\tswitch e := event.(type) {\n\tcase *tcell.EventKey:\n\t\tswitch e.Key() {\n\t\tcase tcell.KeyUp:\n\t\t\tif m.historyNum > 0 {\n\t\t\t\tm.historyNum--\n\t\t\t\tm.response = history[m.historyNum]\n\t\t\t\tm.cursorx = Count(m.response)\n\t\t\t}\n\t\tcase tcell.KeyDown:\n\t\t\tif m.historyNum < len(history)-1 {\n\t\t\t\tm.historyNum++\n\t\t\t\tm.response = history[m.historyNum]\n\t\t\t\tm.cursorx = Count(m.response)\n\t\t\t}\n\t\tcase tcell.KeyLeft:\n\t\t\tif m.cursorx > 0 {\n\t\t\t\tm.cursorx--\n\t\t\t}\n\t\tcase tcell.KeyRight:\n\t\t\tif m.cursorx < Count(m.response) {\n\t\t\t\tm.cursorx++\n\t\t\t}\n\t\tcase tcell.KeyBackspace2, tcell.KeyBackspace:\n\t\t\tif m.cursorx > 0 {\n\t\t\t\tm.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])\n\t\t\t\tm.cursorx--\n\t\t\t}\n\t\tcase tcell.KeyCtrlV:\n\t\t\tclip, _ := clipboard.ReadAll()\n\t\t\tm.response = Insert(m.response, m.cursorx, clip)\n\t\t\tm.cursorx += Count(clip)\n\t\tcase tcell.KeyRune:\n\t\t\tm.response = Insert(m.response, m.cursorx, string(e.Rune()))\n\t\t\tm.cursorx++\n\t\t}\n\t\thistory[m.historyNum] = m.response\n\n\tcase *tcell.EventPaste:\n\t\tclip := e.Text()\n\t\tm.response = Insert(m.response, m.cursorx, clip)\n\t\tm.cursorx += Count(clip)\n\t}\n}\n\n\/\/ Reset resets the messenger's cursor, message and response\nfunc (m *Messenger) Reset() {\n\tm.cursorx = 0\n\tm.message = \"\"\n\tm.response = \"\"\n}\n\n\/\/ Clear clears the line at the bottom of the editor\nfunc (m *Messenger) Clear() {\n\tw, h := screen.Size()\n\tfor x := 0; x < w; x++ {\n\t\tscreen.SetContent(x, h-1, ' ', nil, defStyle)\n\t}\n}\n\nfunc (m *Messenger) DisplaySuggestions(suggestions []string) {\n\tw, screenH := screen.Size()\n\n\ty := screenH - 2\n\n\tstatusLineStyle := defStyle.Reverse(true)\n\tif style, ok := colorscheme[\"statusline\"]; ok {\n\t\tstatusLineStyle = style\n\t}\n\n\tfor x := 0; x < w; x++ {\n\t\tscreen.SetContent(x, y, ' ', nil, statusLineStyle)\n\t}\n\n\tx := 0\n\tfor _, suggestion := range suggestions {\n\t\tfor _, c := range suggestion {\n\t\t\tscreen.SetContent(x, y, c, nil, statusLineStyle)\n\t\t\tx++\n\t\t}\n\t\tscreen.SetContent(x, y, ' ', nil, statusLineStyle)\n\t\tx++\n\t}\n}\n\n\/\/ Display displays messages or prompts\nfunc (m *Messenger) Display() {\n\t_, h := screen.Size()\n\tif m.hasMessage {\n\t\tif !m.hasPrompt {\n\t\t\treturn\n\t\t}\n\t\trunes := []rune(m.message + m.response)\n\t\tfor x := 0; x < len(runes); x++ {\n\t\t\tscreen.SetContent(x, h-1, runes[x], nil, m.style)\n\t\t}\n\t}\n\tif m.hasPrompt {\n\t\tscreen.ShowCursor(Count(m.message)+m.cursorx, h-1)\n\t\tscreen.Show()\n\t}\n}\n\n\/\/ A GutterMessage is a message displayed on the side of the editor\ntype GutterMessage struct {\n\tlineNum int\n\tmsg     string\n\tkind    int\n}\n\n\/\/ These are the different types of messages\nconst (\n\t\/\/ GutterInfo represents a simple info message\n\tGutterInfo = iota\n\t\/\/ GutterWarning represents a compiler warning\n\tGutterWarning\n\t\/\/ GutterError represents a compiler error\n\tGutterError\n)\n<commit_msg>Fix prompts not displaying because of infobar<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/zyedidia\/clipboard\"\n\t\"github.com\/zyedidia\/tcell\"\n)\n\n\/\/ TermMessage sends a message to the user in the terminal. This usually occurs before\n\/\/ micro has been fully initialized -- ie if there is an error in the syntax highlighting\n\/\/ regular expressions\n\/\/ The function must be called when the screen is not initialized\n\/\/ This will write the message, and wait for the user\n\/\/ to press and key to continue\nfunc TermMessage(msg ...interface{}) {\n\tscreenWasNil := screen == nil\n\tif !screenWasNil {\n\t\tscreen.Fini()\n\t}\n\n\tfmt.Println(msg...)\n\tfmt.Print(\"\\nPress enter to continue\")\n\n\treader := bufio.NewReader(os.Stdin)\n\treader.ReadString('\\n')\n\n\tif !screenWasNil {\n\t\tInitScreen()\n\t}\n}\n\n\/\/ TermError sends an error to the user in the terminal. Like TermMessage except formatted\n\/\/ as an error\nfunc TermError(filename string, lineNum int, err string) {\n\tTermMessage(filename + \", \" + strconv.Itoa(lineNum) + \": \" + err)\n}\n\n\/\/ Messenger is an object that makes it easy to send messages to the user\n\/\/ and get input from the user\ntype Messenger struct {\n\t\/\/ Are we currently prompting the user?\n\thasPrompt bool\n\t\/\/ Is there a message to print\n\thasMessage bool\n\n\t\/\/ Message to print\n\tmessage string\n\t\/\/ The user's response to a prompt\n\tresponse string\n\t\/\/ style to use when drawing the message\n\tstyle tcell.Style\n\n\t\/\/ We have to keep track of the cursor for prompting\n\tcursorx int\n\n\t\/\/ This map stores the history for all the different kinds of uses Prompt has\n\t\/\/ It's a map of history type -> history array\n\thistory    map[string][]string\n\thistoryNum int\n\n\t\/\/ Is the current message a message from the gutter\n\tgutterMessage bool\n}\n\n\/\/ Message sends a message to the user\nfunc (m *Messenger) Message(msg ...interface{}) {\n\tbuf := new(bytes.Buffer)\n\tfmt.Fprint(buf, msg...)\n\tm.message = buf.String()\n\tm.style = defStyle\n\n\tif _, ok := colorscheme[\"message\"]; ok {\n\t\tm.style = colorscheme[\"message\"]\n\t}\n\tm.hasMessage = true\n}\n\n\/\/ Error sends an error message to the user\nfunc (m *Messenger) Error(msg ...interface{}) {\n\tbuf := new(bytes.Buffer)\n\tfmt.Fprint(buf, msg...)\n\tm.message = buf.String()\n\tm.style = defStyle.\n\t\tForeground(tcell.ColorBlack).\n\t\tBackground(tcell.ColorMaroon)\n\n\tif _, ok := colorscheme[\"error-message\"]; ok {\n\t\tm.style = colorscheme[\"error-message\"]\n\t}\n\tm.hasMessage = true\n}\n\n\/\/ YesNoPrompt asks the user a yes or no question (waits for y or n) and returns the result\nfunc (m *Messenger) YesNoPrompt(prompt string) (bool, bool) {\n\tm.Message(prompt)\n\n\t_, h := screen.Size()\n\tfor {\n\t\tm.Clear()\n\t\tm.Display()\n\t\tscreen.ShowCursor(Count(m.message), h-1)\n\t\tscreen.Show()\n\t\tevent := <-events\n\n\t\tswitch e := event.(type) {\n\t\tcase *tcell.EventKey:\n\t\t\tswitch e.Key() {\n\t\t\tcase tcell.KeyRune:\n\t\t\t\tif e.Rune() == 'y' {\n\t\t\t\t\treturn true, false\n\t\t\t\t} else if e.Rune() == 'n' {\n\t\t\t\t\treturn false, false\n\t\t\t\t}\n\t\t\tcase tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:\n\t\t\t\treturn false, true\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ LetterPrompt gives the user a prompt and waits for a one letter response\nfunc (m *Messenger) LetterPrompt(prompt string, responses ...rune) (rune, bool) {\n\tm.Message(prompt)\n\n\t_, h := screen.Size()\n\tfor {\n\t\tm.Clear()\n\t\tm.Display()\n\t\tscreen.ShowCursor(Count(m.message), h-1)\n\t\tscreen.Show()\n\t\tevent := <-events\n\n\t\tswitch e := event.(type) {\n\t\tcase *tcell.EventKey:\n\t\t\tswitch e.Key() {\n\t\t\tcase tcell.KeyRune:\n\t\t\t\tfor _, r := range responses {\n\t\t\t\t\tif e.Rune() == r {\n\t\t\t\t\t\tm.Reset()\n\t\t\t\t\t\treturn r, false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase tcell.KeyCtrlC, tcell.KeyCtrlQ, tcell.KeyEscape:\n\t\t\t\treturn ' ', true\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype Completion int\n\nconst (\n\tNoCompletion Completion = iota\n\tFileCompletion\n\tCommandCompletion\n\tHelpCompletion\n\tOptionCompletion\n)\n\n\/\/ Prompt sends the user a message and waits for a response to be typed in\n\/\/ This function blocks the main loop while waiting for input\nfunc (m *Messenger) Prompt(prompt, historyType string, completionTypes ...Completion) (string, bool) {\n\tm.hasPrompt = true\n\tm.Message(prompt)\n\tif _, ok := m.history[historyType]; !ok {\n\t\tm.history[historyType] = []string{\"\"}\n\t} else {\n\t\tm.history[historyType] = append(m.history[historyType], \"\")\n\t}\n\tm.historyNum = len(m.history[historyType]) - 1\n\n\tresponse, canceled := \"\", true\n\n\tRedrawAll()\n\tfor m.hasPrompt {\n\t\tvar suggestions []string\n\t\tm.Clear()\n\n\t\tevent := <-events\n\n\t\tswitch e := event.(type) {\n\t\tcase *tcell.EventKey:\n\t\t\tswitch e.Key() {\n\t\t\tcase tcell.KeyCtrlQ, tcell.KeyCtrlC, tcell.KeyEscape:\n\t\t\t\t\/\/ Cancel\n\t\t\t\tm.hasPrompt = false\n\t\t\tcase tcell.KeyEnter:\n\t\t\t\t\/\/ User is done entering their response\n\t\t\t\tm.hasPrompt = false\n\t\t\t\tresponse, canceled = m.response, false\n\t\t\t\tm.history[historyType][len(m.history[historyType])-1] = response\n\t\t\tcase tcell.KeyTab:\n\t\t\t\targs := strings.Split(m.response, \" \")\n\t\t\t\tcurrentArgNum := len(args) - 1\n\t\t\t\tcurrentArg := args[currentArgNum]\n\t\t\t\tvar completionType Completion\n\n\t\t\t\tif completionTypes[0] == CommandCompletion && currentArgNum > 0 {\n\t\t\t\t\tif command, ok := commands[args[0]]; ok {\n\t\t\t\t\t\tcompletionTypes = append([]Completion{CommandCompletion}, command.completions...)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif currentArgNum >= len(completionTypes) {\n\t\t\t\t\tcompletionType = completionTypes[len(completionTypes)-1]\n\t\t\t\t} else {\n\t\t\t\t\tcompletionType = completionTypes[currentArgNum]\n\t\t\t\t}\n\n\t\t\t\tvar chosen string\n\t\t\t\tif completionType == FileCompletion {\n\t\t\t\t\tchosen, suggestions = FileComplete(currentArg)\n\t\t\t\t} else if completionType == CommandCompletion {\n\t\t\t\t\tchosen, suggestions = CommandComplete(currentArg)\n\t\t\t\t} else if completionType == HelpCompletion {\n\t\t\t\t\tchosen, suggestions = HelpComplete(currentArg)\n\t\t\t\t} else if completionType == OptionCompletion {\n\t\t\t\t\tchosen, suggestions = OptionComplete(currentArg)\n\t\t\t\t}\n\n\t\t\t\tif len(suggestions) > 1 {\n\t\t\t\t\tchosen = chosen + CommonSubstring(suggestions...)\n\t\t\t\t}\n\n\t\t\t\tif chosen != \"\" {\n\t\t\t\t\tif len(args) > 1 {\n\t\t\t\t\t\tchosen = \" \" + chosen\n\t\t\t\t\t}\n\t\t\t\t\tm.response = strings.Join(args[:len(args)-1], \" \") + chosen\n\t\t\t\t\tm.cursorx = Count(m.response)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tm.HandleEvent(event, m.history[historyType])\n\n\t\tmessenger.Clear()\n\t\tfor _, v := range tabs[curTab].views {\n\t\t\tv.Display()\n\t\t}\n\t\tDisplayTabs()\n\t\tmessenger.Display()\n\t\tif len(suggestions) > 1 {\n\t\t\tm.DisplaySuggestions(suggestions)\n\t\t}\n\t\tscreen.Show()\n\t}\n\n\tm.Reset()\n\treturn response, canceled\n}\n\n\/\/ HandleEvent handles an event for the prompter\nfunc (m *Messenger) HandleEvent(event tcell.Event, history []string) {\n\tswitch e := event.(type) {\n\tcase *tcell.EventKey:\n\t\tswitch e.Key() {\n\t\tcase tcell.KeyUp:\n\t\t\tif m.historyNum > 0 {\n\t\t\t\tm.historyNum--\n\t\t\t\tm.response = history[m.historyNum]\n\t\t\t\tm.cursorx = Count(m.response)\n\t\t\t}\n\t\tcase tcell.KeyDown:\n\t\t\tif m.historyNum < len(history)-1 {\n\t\t\t\tm.historyNum++\n\t\t\t\tm.response = history[m.historyNum]\n\t\t\t\tm.cursorx = Count(m.response)\n\t\t\t}\n\t\tcase tcell.KeyLeft:\n\t\t\tif m.cursorx > 0 {\n\t\t\t\tm.cursorx--\n\t\t\t}\n\t\tcase tcell.KeyRight:\n\t\t\tif m.cursorx < Count(m.response) {\n\t\t\t\tm.cursorx++\n\t\t\t}\n\t\tcase tcell.KeyBackspace2, tcell.KeyBackspace:\n\t\t\tif m.cursorx > 0 {\n\t\t\t\tm.response = string([]rune(m.response)[:m.cursorx-1]) + string([]rune(m.response)[m.cursorx:])\n\t\t\t\tm.cursorx--\n\t\t\t}\n\t\tcase tcell.KeyCtrlV:\n\t\t\tclip, _ := clipboard.ReadAll()\n\t\t\tm.response = Insert(m.response, m.cursorx, clip)\n\t\t\tm.cursorx += Count(clip)\n\t\tcase tcell.KeyRune:\n\t\t\tm.response = Insert(m.response, m.cursorx, string(e.Rune()))\n\t\t\tm.cursorx++\n\t\t}\n\t\thistory[m.historyNum] = m.response\n\n\tcase *tcell.EventPaste:\n\t\tclip := e.Text()\n\t\tm.response = Insert(m.response, m.cursorx, clip)\n\t\tm.cursorx += Count(clip)\n\t}\n}\n\n\/\/ Reset resets the messenger's cursor, message and response\nfunc (m *Messenger) Reset() {\n\tm.cursorx = 0\n\tm.message = \"\"\n\tm.response = \"\"\n}\n\n\/\/ Clear clears the line at the bottom of the editor\nfunc (m *Messenger) Clear() {\n\tw, h := screen.Size()\n\tfor x := 0; x < w; x++ {\n\t\tscreen.SetContent(x, h-1, ' ', nil, defStyle)\n\t}\n}\n\nfunc (m *Messenger) DisplaySuggestions(suggestions []string) {\n\tw, screenH := screen.Size()\n\n\ty := screenH - 2\n\n\tstatusLineStyle := defStyle.Reverse(true)\n\tif style, ok := colorscheme[\"statusline\"]; ok {\n\t\tstatusLineStyle = style\n\t}\n\n\tfor x := 0; x < w; x++ {\n\t\tscreen.SetContent(x, y, ' ', nil, statusLineStyle)\n\t}\n\n\tx := 0\n\tfor _, suggestion := range suggestions {\n\t\tfor _, c := range suggestion {\n\t\t\tscreen.SetContent(x, y, c, nil, statusLineStyle)\n\t\t\tx++\n\t\t}\n\t\tscreen.SetContent(x, y, ' ', nil, statusLineStyle)\n\t\tx++\n\t}\n}\n\n\/\/ Display displays messages or prompts\nfunc (m *Messenger) Display() {\n\t_, h := screen.Size()\n\tif m.hasMessage {\n\t\tif !m.hasPrompt && !globalSettings[\"infobar\"].(bool) {\n\t\t\treturn\n\t\t}\n\t\trunes := []rune(m.message + m.response)\n\t\tfor x := 0; x < len(runes); x++ {\n\t\t\tscreen.SetContent(x, h-1, runes[x], nil, m.style)\n\t\t}\n\t}\n\tif m.hasPrompt {\n\t\tscreen.ShowCursor(Count(m.message)+m.cursorx, h-1)\n\t\tscreen.Show()\n\t}\n}\n\n\/\/ A GutterMessage is a message displayed on the side of the editor\ntype GutterMessage struct {\n\tlineNum int\n\tmsg     string\n\tkind    int\n}\n\n\/\/ These are the different types of messages\nconst (\n\t\/\/ GutterInfo represents a simple info message\n\tGutterInfo = iota\n\t\/\/ GutterWarning represents a compiler warning\n\tGutterWarning\n\t\/\/ GutterError represents a compiler error\n\tGutterError\n)\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"k8s.io\/dns\/cmd\/node-cache\/app\"\n\n\tcorednsmain \"github.com\/coredns\/coredns\/coremain\"\n\tclog \"github.com\/coredns\/coredns\/plugin\/pkg\/log\"\n\tutilnet \"k8s.io\/utils\/net\"\n\n\t\/\/ blank imports to make sure the plugin code is pulled in from vendor when building node-cache image\n\t\"github.com\/caddyserver\/caddy\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/bind\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/cache\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/debug\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/errors\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/forward\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/health\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/hosts\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/loadbalance\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/log\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/loop\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/metrics\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/pprof\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/reload\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/template\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/whoami\"\n\t\"k8s.io\/dns\/pkg\/version\"\n)\n\nvar cache *app.CacheApp\n\nfunc init() {\n\tclog.Infof(\"Starting node-cache image: %+v\", version.VERSION)\n\tparams, err := parseAndValidateFlags()\n\tif err != nil {\n\t\tclog.Fatalf(\"Error parsing flags - %s, Exiting\", err)\n\t}\n\tcache, err = app.NewCacheApp(params)\n\tif err != nil {\n\t\tclog.Fatalf(\"Failed to obtain CacheApp instance, err %v\", err)\n\t}\n\tcache.Init()\n\tif !params.SkipTeardown {\n\t\tcaddy.OnProcessExit = append(caddy.OnProcessExit, func() { cache.TeardownNetworking() })\n\t}\n}\n\nfunc parseAndValidateFlags() (*app.ConfigParams, error) {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, \"Runs CoreDNS v%s as a nodelocal cache listening on the specified ip:port\\n\\n\", corednsmain.CoreVersion)\n\t\tflag.PrintDefaults()\n\t}\n\n\tparams := &app.ConfigParams{LocalPort: \"53\"}\n\n\tflag.StringVar(&params.LocalIPStr, \"localip\", \"\", \"comma-separated string of ip addresses to bind dnscache to\")\n\tflag.BoolVar(&params.SetupInterface, \"setupinterface\", true, \"indicates whether network interface should be setup\")\n\tflag.StringVar(&params.InterfaceName, \"interfacename\", \"nodelocaldns\", \"name of the interface to be created\")\n\tflag.DurationVar(&params.Interval, \"syncinterval\", 60, \"interval(in seconds) to check for iptables rules\")\n\tflag.StringVar(&params.MetricsListenAddress, \"metrics-listen-address\", \"0.0.0.0:9353\", \"address to serve metrics on\")\n\tflag.BoolVar(&params.SetupIptables, \"setupiptables\", true, \"indicates whether iptables rules should be setup\")\n\tflag.BoolVar(&params.SetupEbtables, \"setupebtables\", false, \"indicates whether ebtables rules should be setup\")\n\tflag.StringVar(&params.BaseCoreFile, \"basecorefile\", \"\/etc\/coredns\/Corefile.base\", \"Path to the template Corefile for node-cache\")\n\tflag.StringVar(&params.CoreFile, \"corefile\", \"\/etc\/Corefile\", \"Path to the Corefile to be used by node-cache\")\n\tflag.StringVar(&params.KubednsCMPath, \"kubednscm\", \"\", \"Path where the kube-dns configmap will be mounted\")\n\tflag.StringVar(&params.UpstreamSvcName, \"upstreamsvc\", \"kube-dns\", \"Service name whose cluster IP is upstream for node-cache\")\n\tflag.StringVar(&params.HealthPort, \"health-port\", \"8080\", \"port used by health plugin\")\n\tflag.BoolVar(&params.SkipTeardown, \"skipteardown\", false, \"indicates whether iptables rules should be torn down on exit\")\n\tflag.Parse()\n\n\tfor _, ipstr := range strings.Split(params.LocalIPStr, \",\") {\n\t\tnewIP := net.ParseIP(ipstr)\n\t\tif newIP == nil {\n\t\t\treturn params, fmt.Errorf(\"Invalid localip specified - %q\", ipstr)\n\t\t}\n\t\tparams.LocalIPs = append(params.LocalIPs, newIP)\n\t}\n\n\t\/\/ validate all the IPs have the same IP family\n\tfor _, ip := range params.LocalIPs {\n\t\tif utilnet.IsIPv6(params.LocalIPs[0]) != utilnet.IsIPv6(ip) {\n\t\t\treturn params, fmt.Errorf(\"Unexpected IP Family for localIP - %q, want IPv6=%v\", ip, utilnet.IsIPv6(params.LocalIPs[0]))\n\t\t}\n\t}\n\t\/\/ lookup specified dns port\n\tf := flag.Lookup(\"dns.port\")\n\tif f == nil {\n\t\treturn nil, fmt.Errorf(\"Failed to lookup \\\"dns.port\\\" parameter\")\n\t}\n\tparams.LocalPort = f.Value.String()\n\tif _, err := strconv.Atoi(params.LocalPort); err != nil {\n\t\treturn nil, fmt.Errorf(\"Invalid port specified - %q\", params.LocalPort)\n\t}\n\tif _, err := strconv.Atoi(params.HealthPort); err != nil {\n\t\treturn nil, fmt.Errorf(\"Invalid healthcheck port specified - %q\", params.HealthPort)\n\t}\n\tif f = flag.Lookup(\"conf\"); f != nil {\n\t\tparams.CoreFile = f.Value.String()\n\t\tclog.Infof(\"Using Corefile %s\", params.CoreFile)\n\t}\n\treturn params, nil\n}\n\nfunc main() {\n\tcache.RunApp()\n}\n<commit_msg>Add support for rewrite plugin in node-cache<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"k8s.io\/dns\/cmd\/node-cache\/app\"\n\n\tcorednsmain \"github.com\/coredns\/coredns\/coremain\"\n\tclog \"github.com\/coredns\/coredns\/plugin\/pkg\/log\"\n\tutilnet \"k8s.io\/utils\/net\"\n\n\t\/\/ blank imports to make sure the plugin code is pulled in from vendor when building node-cache image\n\t\"github.com\/caddyserver\/caddy\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/bind\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/cache\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/debug\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/errors\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/forward\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/health\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/hosts\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/loadbalance\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/log\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/loop\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/metrics\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/pprof\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/reload\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/rewrite\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/template\"\n\t_ \"github.com\/coredns\/coredns\/plugin\/whoami\"\n\t\"k8s.io\/dns\/pkg\/version\"\n)\n\nvar cache *app.CacheApp\n\nfunc init() {\n\tclog.Infof(\"Starting node-cache image: %+v\", version.VERSION)\n\tparams, err := parseAndValidateFlags()\n\tif err != nil {\n\t\tclog.Fatalf(\"Error parsing flags - %s, Exiting\", err)\n\t}\n\tcache, err = app.NewCacheApp(params)\n\tif err != nil {\n\t\tclog.Fatalf(\"Failed to obtain CacheApp instance, err %v\", err)\n\t}\n\tcache.Init()\n\tif !params.SkipTeardown {\n\t\tcaddy.OnProcessExit = append(caddy.OnProcessExit, func() { cache.TeardownNetworking() })\n\t}\n}\n\nfunc parseAndValidateFlags() (*app.ConfigParams, error) {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, \"Runs CoreDNS v%s as a nodelocal cache listening on the specified ip:port\\n\\n\", corednsmain.CoreVersion)\n\t\tflag.PrintDefaults()\n\t}\n\n\tparams := &app.ConfigParams{LocalPort: \"53\"}\n\n\tflag.StringVar(&params.LocalIPStr, \"localip\", \"\", \"comma-separated string of ip addresses to bind dnscache to\")\n\tflag.BoolVar(&params.SetupInterface, \"setupinterface\", true, \"indicates whether network interface should be setup\")\n\tflag.StringVar(&params.InterfaceName, \"interfacename\", \"nodelocaldns\", \"name of the interface to be created\")\n\tflag.DurationVar(&params.Interval, \"syncinterval\", 60, \"interval(in seconds) to check for iptables rules\")\n\tflag.StringVar(&params.MetricsListenAddress, \"metrics-listen-address\", \"0.0.0.0:9353\", \"address to serve metrics on\")\n\tflag.BoolVar(&params.SetupIptables, \"setupiptables\", true, \"indicates whether iptables rules should be setup\")\n\tflag.BoolVar(&params.SetupEbtables, \"setupebtables\", false, \"indicates whether ebtables rules should be setup\")\n\tflag.StringVar(&params.BaseCoreFile, \"basecorefile\", \"\/etc\/coredns\/Corefile.base\", \"Path to the template Corefile for node-cache\")\n\tflag.StringVar(&params.CoreFile, \"corefile\", \"\/etc\/Corefile\", \"Path to the Corefile to be used by node-cache\")\n\tflag.StringVar(&params.KubednsCMPath, \"kubednscm\", \"\", \"Path where the kube-dns configmap will be mounted\")\n\tflag.StringVar(&params.UpstreamSvcName, \"upstreamsvc\", \"kube-dns\", \"Service name whose cluster IP is upstream for node-cache\")\n\tflag.StringVar(&params.HealthPort, \"health-port\", \"8080\", \"port used by health plugin\")\n\tflag.BoolVar(&params.SkipTeardown, \"skipteardown\", false, \"indicates whether iptables rules should be torn down on exit\")\n\tflag.Parse()\n\n\tfor _, ipstr := range strings.Split(params.LocalIPStr, \",\") {\n\t\tnewIP := net.ParseIP(ipstr)\n\t\tif newIP == nil {\n\t\t\treturn params, fmt.Errorf(\"Invalid localip specified - %q\", ipstr)\n\t\t}\n\t\tparams.LocalIPs = append(params.LocalIPs, newIP)\n\t}\n\n\t\/\/ validate all the IPs have the same IP family\n\tfor _, ip := range params.LocalIPs {\n\t\tif utilnet.IsIPv6(params.LocalIPs[0]) != utilnet.IsIPv6(ip) {\n\t\t\treturn params, fmt.Errorf(\"Unexpected IP Family for localIP - %q, want IPv6=%v\", ip, utilnet.IsIPv6(params.LocalIPs[0]))\n\t\t}\n\t}\n\t\/\/ lookup specified dns port\n\tf := flag.Lookup(\"dns.port\")\n\tif f == nil {\n\t\treturn nil, fmt.Errorf(\"Failed to lookup \\\"dns.port\\\" parameter\")\n\t}\n\tparams.LocalPort = f.Value.String()\n\tif _, err := strconv.Atoi(params.LocalPort); err != nil {\n\t\treturn nil, fmt.Errorf(\"Invalid port specified - %q\", params.LocalPort)\n\t}\n\tif _, err := strconv.Atoi(params.HealthPort); err != nil {\n\t\treturn nil, fmt.Errorf(\"Invalid healthcheck port specified - %q\", params.HealthPort)\n\t}\n\tif f = flag.Lookup(\"conf\"); f != nil {\n\t\tparams.CoreFile = f.Value.String()\n\t\tclog.Infof(\"Using Corefile %s\", params.CoreFile)\n\t}\n\treturn params, nil\n}\n\nfunc main() {\n\tcache.RunApp()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\tThis file is part of go-ethereum\n\n\tgo-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tgo-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with go-ethereum.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n*\/\npackage main\n\nimport (\n\t\"crypto\/elliptic\"\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/ethereum\/go-ethereum\/crypto\"\n\t\"github.com\/ethereum\/go-ethereum\/logger\"\n\t\"github.com\/ethereum\/go-ethereum\/p2p\"\n)\n\nvar (\n\tnatType    = flag.String(\"nat\", \"\", \"NAT traversal implementation\")\n\tpmpGateway = flag.String(\"gateway\", \"\", \"gateway address for NAT-PMP\")\n\tlistenAddr = flag.String(\"addr\", \":30301\", \"listen address\")\n)\n\nfunc main() {\n\tflag.Parse()\n\tnat, err := p2p.ParseNAT(*natType, *pmpGateway)\n\tif err != nil {\n\t\tlog.Fatal(\"invalid nat:\", err)\n\t}\n\n\tlogger.AddLogSystem(logger.NewStdLogSystem(os.Stdout, log.LstdFlags, logger.InfoLevel))\n\tkey, _ := crypto.GenerateKey()\n\tmarshaled := elliptic.Marshal(crypto.S256(), key.PublicKey.X, key.PublicKey.Y)\n\n\tsrv := p2p.Server{\n\t\tMaxPeers:   100,\n\t\tIdentity:   p2p.NewSimpleClientIdentity(\"Ethereum(G)\", \"0.1\", \"Peer Server Two\", marshaled),\n\t\tListenAddr: *listenAddr,\n\t\tNAT:        nat,\n\t\tNoDial:     true,\n\t}\n\tif err := srv.Start(); err != nil {\n\t\tlog.Fatal(\"could not start server:\", err)\n\t}\n\tselect {}\n}\n<commit_msg>cmd\/peerserver: is gone<commit_after><|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"path\"\n\n\t\"github.com\/DeedleFake\/signage\"\n)\n\nfunc marshalRSS(t string, bills []signage.Bill) (io.Reader, error) {\n\tvar buf bytes.Buffer\n\terr := tmpl.ExecuteTemplate(&buf, \"rss\", map[string]interface{}{\n\t\t\"Type\":  t,\n\t\t\"Bills\": bills,\n\t})\n\treturn &buf, err\n}\n\nfunc marshalJSON(t string, bills []signage.Bill) (io.Reader, error) {\n\tpanic(\"Not implemented.\")\n}\n\nfunc handleSigned(rw http.ResponseWriter, req *http.Request) {\n\tmode := path.Ext(req.URL.Path)\n\tif mode == \"\" {\n\t\tmode = \".rss\"\n\t}\n\n\tvar marshal func(t string, bills []signage.Bill) (io.Reader, error)\n\tswitch mode {\n\tcase \".rss\":\n\t\tmarshal = marshalRSS\n\tcase \".json\":\n\t\tmarshal = marshalJSON\n\tdefault:\n\t\thttp.Error(rw, fmt.Sprintf(\"Unknown format: %q\", mode), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tbills, err := signage.GetSigned()\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tbuf, err := marshal(\"Signed\", bills)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t_, err = io.Copy(rw, buf)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", handleSigned)\n\tlog.Fatalln(http.ListenAndServe(\":8080\", nil))\n}\n<commit_msg>cmd\/signage: Add JSON support.<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"path\"\n\n\t\"github.com\/DeedleFake\/signage\"\n)\n\nfunc marshalRSS(t string, bills []signage.Bill) (io.Reader, error) {\n\tvar buf bytes.Buffer\n\terr := tmpl.ExecuteTemplate(&buf, \"rss\", map[string]interface{}{\n\t\t\"Type\":  t,\n\t\t\"Bills\": bills,\n\t})\n\treturn &buf, err\n}\n\nfunc marshalJSON(t string, bills []signage.Bill) (io.Reader, error) {\n\tbuf, err := json.Marshal(map[string]interface{}{\n\t\t\"type\":  t,\n\t\t\"bills\": bills,\n\t})\n\treturn bytes.NewReader(buf), err\n}\n\nfunc handleSigned(rw http.ResponseWriter, req *http.Request) {\n\tmode := path.Ext(req.URL.Path)\n\tif mode == \"\" {\n\t\tmode = \".rss\"\n\t}\n\n\tvar marshal func(t string, bills []signage.Bill) (io.Reader, error)\n\tswitch mode {\n\tcase \".rss\":\n\t\tmarshal = marshalRSS\n\tcase \".json\":\n\t\tmarshal = marshalJSON\n\tdefault:\n\t\thttp.Error(rw, fmt.Sprintf(\"Unknown format: %q\", mode), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tbills, err := signage.GetSigned()\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tbuf, err := marshal(\"Signed\", bills)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t_, err = io.Copy(rw, buf)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", handleSigned)\n\tlog.Fatalln(http.ListenAndServe(\":8080\", nil))\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"fmt\"\n\t\"github.com\/smira\/aptly\/deb\"\n\t\"github.com\/smira\/aptly\/query\"\n\t\"github.com\/smira\/commander\"\n\t\"github.com\/smira\/flag\"\n)\n\nfunc aptlySnapshotMirrorRepoSearch(cmd *commander.Command, args []string) error {\n\tvar err error\n\tif len(args) != 2 {\n\t\tcmd.Usage()\n\t\treturn commander.ErrCommandError\n\t}\n\n\tname := args[0]\n\tcommand := cmd.Parent.Name()\n\n\tvar reflist *deb.PackageRefList\n\n\tif command == \"snapshot\" {\n\t\tsnapshot, err := context.CollectionFactory().SnapshotCollection().ByName(name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t\t}\n\n\t\terr = context.CollectionFactory().SnapshotCollection().LoadComplete(snapshot)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t\t}\n\n\t\treflist = snapshot.RefList()\n\t} else if command == \"mirror\" {\n\t\trepo, err := context.CollectionFactory().RemoteRepoCollection().ByName(name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t\t}\n\n\t\terr = context.CollectionFactory().RemoteRepoCollection().LoadComplete(repo)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t\t}\n\n\t\treflist = repo.RefList()\n\t} else if command == \"repo\" {\n\t\trepo, err := context.CollectionFactory().LocalRepoCollection().ByName(name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t\t}\n\n\t\terr = context.CollectionFactory().LocalRepoCollection().LoadComplete(repo)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t\t}\n\n\t\treflist = repo.RefList()\n\t} else {\n\t\tpanic(\"unknown command\")\n\t}\n\n\tlist, err := deb.NewPackageListFromRefList(reflist, context.CollectionFactory().PackageCollection(), context.Progress())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t}\n\n\tlist.PrepareIndex()\n\n\tq, err := query.Parse(args[1])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t}\n\n\tresult, err := list.Filter([]deb.PackageQuery{q}, context.flags.Lookup(\"with-deps\").Value.Get().(bool),\n\t\tnil, context.DependencyOptions(), context.ArchitecturesList())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t}\n\n\tresult.ForEach(func(p *deb.Package) error {\n\t\tcontext.Progress().Printf(\"%s\\n\", p)\n\t\treturn nil\n\t})\n\n\treturn err\n}\n\nfunc makeCmdSnapshotSearch() *commander.Command {\n\tcmd := &commander.Command{\n\t\tRun:       aptlySnapshotMirrorRepoSearch,\n\t\tUsageLine: \"search <name> <package-query>\",\n\t\tShort:     \"search snapshot for packages matching query\",\n\t\tLong: `\nCommand search displays list of packages in snapshot that match package query\n\nExample:\n\n    $ aptly snapshot search wheezy-main '$Architecture (i386), Name (% *-dev)'\n`,\n\t\tFlag: *flag.NewFlagSet(\"aptly-snapshot-search\", flag.ExitOnError),\n\t}\n\n\tcmd.Flag.Bool(\"with-deps\", false, \"include dependencies into search results\")\n\n\treturn cmd\n}\n<commit_msg>Fix -with-deps searching. #81<commit_after>package cmd\n\nimport (\n\t\"fmt\"\n\t\"github.com\/smira\/aptly\/deb\"\n\t\"github.com\/smira\/aptly\/query\"\n\t\"github.com\/smira\/commander\"\n\t\"github.com\/smira\/flag\"\n\t\"sort\"\n)\n\nfunc aptlySnapshotMirrorRepoSearch(cmd *commander.Command, args []string) error {\n\tvar err error\n\tif len(args) != 2 {\n\t\tcmd.Usage()\n\t\treturn commander.ErrCommandError\n\t}\n\n\tname := args[0]\n\tcommand := cmd.Parent.Name()\n\n\tvar reflist *deb.PackageRefList\n\n\tif command == \"snapshot\" {\n\t\tsnapshot, err := context.CollectionFactory().SnapshotCollection().ByName(name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t\t}\n\n\t\terr = context.CollectionFactory().SnapshotCollection().LoadComplete(snapshot)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t\t}\n\n\t\treflist = snapshot.RefList()\n\t} else if command == \"mirror\" {\n\t\trepo, err := context.CollectionFactory().RemoteRepoCollection().ByName(name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t\t}\n\n\t\terr = context.CollectionFactory().RemoteRepoCollection().LoadComplete(repo)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t\t}\n\n\t\treflist = repo.RefList()\n\t} else if command == \"repo\" {\n\t\trepo, err := context.CollectionFactory().LocalRepoCollection().ByName(name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t\t}\n\n\t\terr = context.CollectionFactory().LocalRepoCollection().LoadComplete(repo)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t\t}\n\n\t\treflist = repo.RefList()\n\t} else {\n\t\tpanic(\"unknown command\")\n\t}\n\n\tlist, err := deb.NewPackageListFromRefList(reflist, context.CollectionFactory().PackageCollection(), context.Progress())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t}\n\n\tlist.PrepareIndex()\n\n\tq, err := query.Parse(args[1])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t}\n\n\twithDeps := context.flags.Lookup(\"with-deps\").Value.Get().(bool)\n\tarchitecturesList := []string{}\n\n\tif withDeps {\n\t\tif len(context.ArchitecturesList()) > 0 {\n\t\t\tarchitecturesList = context.ArchitecturesList()\n\t\t} else {\n\t\t\tarchitecturesList = list.Architectures(false)\n\t\t}\n\n\t\tsort.Strings(architecturesList)\n\n\t\tif len(architecturesList) == 0 {\n\t\t\treturn fmt.Errorf(\"unable to determine list of architectures, please specify explicitly\")\n\t\t}\n\t}\n\n\tresult, err := list.Filter([]deb.PackageQuery{q}, withDeps,\n\t\tnil, context.DependencyOptions(), architecturesList)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to search: %s\", err)\n\t}\n\n\tresult.ForEach(func(p *deb.Package) error {\n\t\tcontext.Progress().Printf(\"%s\\n\", p)\n\t\treturn nil\n\t})\n\n\treturn err\n}\n\nfunc makeCmdSnapshotSearch() *commander.Command {\n\tcmd := &commander.Command{\n\t\tRun:       aptlySnapshotMirrorRepoSearch,\n\t\tUsageLine: \"search <name> <package-query>\",\n\t\tShort:     \"search snapshot for packages matching query\",\n\t\tLong: `\nCommand search displays list of packages in snapshot that match package query\n\nExample:\n\n    $ aptly snapshot search wheezy-main '$Architecture (i386), Name (% *-dev)'\n`,\n\t\tFlag: *flag.NewFlagSet(\"aptly-snapshot-search\", flag.ExitOnError),\n\t}\n\n\tcmd.Flag.Bool(\"with-deps\", false, \"include dependencies into search results\")\n\n\treturn cmd\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 Mirantis\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\tgoflag \"flag\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\tflag \"github.com\/spf13\/pflag\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n\n\t\"github.com\/Mirantis\/virtlet\/pkg\/api\/virtlet.k8s\/v1\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/cni\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/config\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/diag\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/libvirttools\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/manager\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/nsfix\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/tapmanager\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/utils\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/version\"\n)\n\nconst (\n\twantTapManagerEnv = \"WANT_TAP_MANAGER\"\n\tnodeNameEnv       = \"KUBE_NODE_NAME\"\n\tdiagSocket        = \"\/run\/virtlet-diag.sock\"\n\tnetnsDiagCommand  = `if [ -d \/var\/run\/netns ]; then cd \/var\/run\/netns; for ns in *; do echo \"*** ${ns} ***\"; ip netns exec \"${ns}\" ip a; ip netns exec \"${ns}\" ip r; echo; done; fi`\n\tqemuLogDir        = \"\/var\/log\/libvirt\/qemu\"\n)\n\nvar (\n\tdumpConfig     = flag.Bool(\"dump-config\", false, \"Dump node-specific Virtlet config as a shell script and exit\")\n\tdumpDiag       = flag.Bool(\"diag\", false, \"Dump diagnostics as JSON and exit\")\n\tdisplayVersion = flag.Bool(\"version\", false, \"Display version and exit\")\n\tversionFormat  = flag.String(\"version-format\", \"text\", \"Version format to use (text, short, json, yaml)\")\n)\n\nfunc configWithDefaults(cfg *v1.VirtletConfig) *v1.VirtletConfig {\n\tr := config.GetDefaultConfig()\n\tconfig.Override(r, cfg)\n\treturn r\n}\n\nfunc runVirtlet(config *v1.VirtletConfig, clientCfg clientcmd.ClientConfig, diagSet *diag.DiagSet) {\n\tmanager := manager.NewVirtletManager(config, nil, clientCfg, diagSet)\n\tif err := manager.Run(); err != nil {\n\t\tglog.Errorf(\"Error: %v\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc runTapManager(config *v1.VirtletConfig) {\n\tcniClient, err := cni.NewClient(*config.CNIPluginDir, *config.CNIConfigDir)\n\tif err != nil {\n\t\tglog.Errorf(\"Error initializing CNI client: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tsrc, err := tapmanager.NewTapFDSource(cniClient, *config.EnableSriov, *config.CalicoSubnetSize)\n\tif err != nil {\n\t\tglog.Errorf(\"Error creating tap fd source: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tos.Remove(*config.FDServerSocketPath) \/\/ FIXME\n\ts := tapmanager.NewFDServer(*config.FDServerSocketPath, src)\n\tif err = s.Serve(); err != nil {\n\t\tglog.Errorf(\"FD server returned error: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tif err := libvirttools.ChownForEmulator(*config.FDServerSocketPath); err != nil {\n\t\tglog.Warningf(\"Couldn't set tapmanager socket permissions: %v\", err)\n\t}\n\tfor {\n\t\ttime.Sleep(1000 * time.Hour)\n\t}\n}\n\nfunc printVersion() {\n\tout, err := version.Get().ToBytes(*versionFormat)\n\tif err == nil {\n\t\t_, err = os.Stdout.Write(out)\n\t}\n\tif err != nil {\n\t\tglog.Errorf(\"Error printing version info: %v\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc setLogLevel(config *v1.VirtletConfig) {\n\tgoflag.CommandLine.Parse([]string{\n\t\tfmt.Sprintf(\"-v=%d\", config.LogLevel),\n\t\t\"-logtostderr=true\",\n\t})\n}\n\nfunc runDiagServer() *diag.DiagSet {\n\tdiagSet := diag.NewDiagSet()\n\tdiagSet.RegisterDiagSource(\"ip-a\", diag.NewCommandSource(\"txt\", []string{\"ip\", \"a\"}))\n\tdiagSet.RegisterDiagSource(\"ip-r\", diag.NewCommandSource(\"txt\", []string{\"ip\", \"r\"}))\n\tdiagSet.RegisterDiagSource(\"netns\", diag.NewCommandSource(\"txt\", []string{\"\/bin\/bash\", \"-c\", netnsDiagCommand}))\n\tdiagSet.RegisterDiagSource(\"libvirt-logs\", diag.NewLogDirSource(qemuLogDir))\n\tdiagSet.RegisterDiagSource(\"stack\", diag.StackDumpSource)\n\tserver := diag.NewServer(diagSet)\n\tgo func() {\n\t\terr := server.Serve(diagSocket, nil)\n\t\tglog.V(1).Infof(\"Diag server returned: %v\", err)\n\t}()\n\treturn diagSet\n}\n\nfunc doDiag() {\n\tdr, err := diag.RetrieveDiagnostics(diagSocket)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to retrieve diagnostics: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tos.Stdout.Write(dr.ToJSON())\n}\n\nfunc main() {\n\tnsfix.HandleReexec()\n\tclientCfg := utils.BindFlags(flag.CommandLine)\n\tvar cb *config.Binder\n\tcb = config.NewBinder(flag.CommandLine)\n\tflag.Parse()\n\tlocalConfig := cb.GetConfig()\n\n\trand.Seed(time.Now().UnixNano())\n\tsetLogLevel(configWithDefaults(localConfig))\n\tswitch {\n\tcase *displayVersion:\n\t\tprintVersion()\n\tcase *dumpConfig:\n\t\tnodeConfig := config.NewNodeConfig(clientCfg)\n\t\tnodeName := os.Getenv(nodeNameEnv)\n\t\tcfg, err := nodeConfig.LoadConfig(localConfig, nodeName)\n\t\tif err != nil {\n\t\t\tglog.Warningf(\"Failed to load per-node configs, using local config only: %v\", err)\n\t\t\tcfg = localConfig\n\t\t}\n\t\tif _, err := os.Stdout.Write([]byte(config.DumpEnv(cfg))); err != nil {\n\t\t\tglog.Errorf(\"Error writing config: %v\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\tcase *dumpDiag:\n\t\tdoDiag()\n\tdefault:\n\t\tlocalConfig = configWithDefaults(localConfig)\n\t\tgo runTapManager(localConfig)\n\t\tdiagSet := runDiagServer()\n\t\trunVirtlet(localConfig, clientCfg, diagSet)\n\t}\n}\n<commit_msg>Include CRI Proxy logs in the diagnostics<commit_after>\/*\nCopyright 2017 Mirantis\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\tgoflag \"flag\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\tflag \"github.com\/spf13\/pflag\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n\n\t\"github.com\/Mirantis\/virtlet\/pkg\/api\/virtlet.k8s\/v1\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/cni\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/config\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/diag\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/libvirttools\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/manager\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/nsfix\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/tapmanager\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/utils\"\n\t\"github.com\/Mirantis\/virtlet\/pkg\/version\"\n)\n\nconst (\n\twantTapManagerEnv  = \"WANT_TAP_MANAGER\"\n\tnodeNameEnv        = \"KUBE_NODE_NAME\"\n\tdiagSocket         = \"\/run\/virtlet-diag.sock\"\n\tnetnsDiagCommand   = `if [ -d \/var\/run\/netns ]; then cd \/var\/run\/netns; for ns in *; do echo \"*** ${ns} ***\"; ip netns exec \"${ns}\" ip a; ip netns exec \"${ns}\" ip r; echo; done; fi`\n\tcriproxyLogCommand = `nsenter -t 1 -m -u -i journalctl -xe -u criproxy -n 20000 --no-pager || true`\n\tqemuLogDir         = \"\/var\/log\/libvirt\/qemu\"\n)\n\nvar (\n\tdumpConfig     = flag.Bool(\"dump-config\", false, \"Dump node-specific Virtlet config as a shell script and exit\")\n\tdumpDiag       = flag.Bool(\"diag\", false, \"Dump diagnostics as JSON and exit\")\n\tdisplayVersion = flag.Bool(\"version\", false, \"Display version and exit\")\n\tversionFormat  = flag.String(\"version-format\", \"text\", \"Version format to use (text, short, json, yaml)\")\n)\n\nfunc configWithDefaults(cfg *v1.VirtletConfig) *v1.VirtletConfig {\n\tr := config.GetDefaultConfig()\n\tconfig.Override(r, cfg)\n\treturn r\n}\n\nfunc runVirtlet(config *v1.VirtletConfig, clientCfg clientcmd.ClientConfig, diagSet *diag.DiagSet) {\n\tmanager := manager.NewVirtletManager(config, nil, clientCfg, diagSet)\n\tif err := manager.Run(); err != nil {\n\t\tglog.Errorf(\"Error: %v\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc runTapManager(config *v1.VirtletConfig) {\n\tcniClient, err := cni.NewClient(*config.CNIPluginDir, *config.CNIConfigDir)\n\tif err != nil {\n\t\tglog.Errorf(\"Error initializing CNI client: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tsrc, err := tapmanager.NewTapFDSource(cniClient, *config.EnableSriov, *config.CalicoSubnetSize)\n\tif err != nil {\n\t\tglog.Errorf(\"Error creating tap fd source: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tos.Remove(*config.FDServerSocketPath) \/\/ FIXME\n\ts := tapmanager.NewFDServer(*config.FDServerSocketPath, src)\n\tif err = s.Serve(); err != nil {\n\t\tglog.Errorf(\"FD server returned error: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tif err := libvirttools.ChownForEmulator(*config.FDServerSocketPath); err != nil {\n\t\tglog.Warningf(\"Couldn't set tapmanager socket permissions: %v\", err)\n\t}\n\tfor {\n\t\ttime.Sleep(1000 * time.Hour)\n\t}\n}\n\nfunc printVersion() {\n\tout, err := version.Get().ToBytes(*versionFormat)\n\tif err == nil {\n\t\t_, err = os.Stdout.Write(out)\n\t}\n\tif err != nil {\n\t\tglog.Errorf(\"Error printing version info: %v\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc setLogLevel(config *v1.VirtletConfig) {\n\tgoflag.CommandLine.Parse([]string{\n\t\tfmt.Sprintf(\"-v=%d\", config.LogLevel),\n\t\t\"-logtostderr=true\",\n\t})\n}\n\nfunc runDiagServer() *diag.DiagSet {\n\tdiagSet := diag.NewDiagSet()\n\tdiagSet.RegisterDiagSource(\"ip-a\", diag.NewCommandSource(\"txt\", []string{\"ip\", \"a\"}))\n\tdiagSet.RegisterDiagSource(\"ip-r\", diag.NewCommandSource(\"txt\", []string{\"ip\", \"r\"}))\n\tdiagSet.RegisterDiagSource(\"netns\", diag.NewCommandSource(\"txt\", []string{\"\/bin\/bash\", \"-c\", netnsDiagCommand}))\n\tdiagSet.RegisterDiagSource(\"criproxy\", diag.NewCommandSource(\"log\", []string{\"\/bin\/bash\", \"-c\", criproxyLogCommand}))\n\tdiagSet.RegisterDiagSource(\"libvirt-logs\", diag.NewLogDirSource(qemuLogDir))\n\tdiagSet.RegisterDiagSource(\"stack\", diag.StackDumpSource)\n\tserver := diag.NewServer(diagSet)\n\tgo func() {\n\t\terr := server.Serve(diagSocket, nil)\n\t\tglog.V(1).Infof(\"Diag server returned: %v\", err)\n\t}()\n\treturn diagSet\n}\n\nfunc doDiag() {\n\tdr, err := diag.RetrieveDiagnostics(diagSocket)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to retrieve diagnostics: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tos.Stdout.Write(dr.ToJSON())\n}\n\nfunc main() {\n\tnsfix.HandleReexec()\n\tclientCfg := utils.BindFlags(flag.CommandLine)\n\tvar cb *config.Binder\n\tcb = config.NewBinder(flag.CommandLine)\n\tflag.Parse()\n\tlocalConfig := cb.GetConfig()\n\n\trand.Seed(time.Now().UnixNano())\n\tsetLogLevel(configWithDefaults(localConfig))\n\tswitch {\n\tcase *displayVersion:\n\t\tprintVersion()\n\tcase *dumpConfig:\n\t\tnodeConfig := config.NewNodeConfig(clientCfg)\n\t\tnodeName := os.Getenv(nodeNameEnv)\n\t\tcfg, err := nodeConfig.LoadConfig(localConfig, nodeName)\n\t\tif err != nil {\n\t\t\tglog.Warningf(\"Failed to load per-node configs, using local config only: %v\", err)\n\t\t\tcfg = localConfig\n\t\t}\n\t\tif _, err := os.Stdout.Write([]byte(config.DumpEnv(cfg))); err != nil {\n\t\t\tglog.Errorf(\"Error writing config: %v\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\tcase *dumpDiag:\n\t\tdoDiag()\n\tdefault:\n\t\tlocalConfig = configWithDefaults(localConfig)\n\t\tgo runTapManager(localConfig)\n\t\tdiagSet := runDiagServer()\n\t\trunVirtlet(localConfig, clientCfg, diagSet)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/mrspock\/godocsis\"\n\t\"net\"\n\t\"os\"\n)\n\nfunc main() {\n\t\/\/var ip string\n\tflag.Parse()\n\tif len(flag.Args()) == 0 {\n\t\tHelp(os.Args[0])\n\t\treturn\n\t}\n\tfor _, host := range flag.Args() {\n\t\tip, err := net.LookupHost(host)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, \"Host lookup error:\", err)\n\t\t\t\/\/os.Exit(1)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, address := range ip {\n\t\t\t\/\/fmt.Println(address)\n\t\t\terr := godocsis.ResetCm(address)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"NG: Wystąpił błąd komunikacji z modemem\", address, \":\", err)\n\t\t\t\t\/\/os.Exit(1)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tfmt.Fprintln(os.Stdout, \"OK: Modem\", address, \"w trakcie restartu..\")\n\t\t\t\t\/\/os.Exit(0)\n\t\t\t}\n\t\t}\n\t}\n\tos.Exit(1)\n}\n\nfunc Help(name string) {\n\tfmt.Fprintf(os.Stderr, \"======= Cable Modem restarter by Spock (BSD) ========\\nUsage: %s cm1_ipaddr cm2_ipaddr\\n============================================\\n\", name)\n}\n<commit_msg>correct exit code<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/mrspock\/godocsis\"\n\t\"net\"\n\t\"os\"\n)\n\nfunc main() {\n\t\/\/var ip string\n\tflag.Parse()\n\tif len(flag.Args()) == 0 {\n\t\tHelp(os.Args[0])\n\t\treturn\n\t}\n\tfor _, host := range flag.Args() {\n\t\tip, err := net.LookupHost(host)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, \"Host lookup error:\", err)\n\t\t\t\/\/os.Exit(1)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, address := range ip {\n\t\t\t\/\/fmt.Println(address)\n\t\t\terr := godocsis.ResetCm(address)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, \"NG: Wystąpił błąd komunikacji z modemem\", address, \":\", err)\n\t\t\t\t\/\/os.Exit(1)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tfmt.Fprintln(os.Stdout, \"OK: Modem\", address, \"w trakcie restartu..\")\n\t\t\t\t\/\/os.Exit(0)\n\t\t\t}\n\t\t}\n\t}\n\tos.Exit(0)\n}\n\nfunc Help(name string) {\n\tfmt.Fprintf(os.Stderr, \"======= Cable Modem restarter by Spock (BSD) ========\\nUsage: %s cm1_ipaddr cm2_ipaddr\\n============================================\\n\", name)\n}\n<|endoftext|>"}
{"text":"<commit_before>package proto\n\ntype Message struct {\n\tData []byte\n}\n\nfunc (m Message) MarshalJSON() ([]byte, error) {\n\treturn m.Data, nil\n}\n\nfunc (m *Message) UnmarshalJSON(data []byte) error {\n\tm.Data = data\n\treturn nil\n}\n\nfunc (m *Message) ProtoMessage() {}\n\nfunc (m *Message) Reset() {\n\t*m = Message{}\n}\n\nfunc (m *Message) String() string {\n\treturn string(m.Data)\n}\n\nfunc (m *Message) Marshal() ([]byte, error) {\n\treturn m.Data, nil\n}\n\nfunc (m *Message) Unmarshal(data []byte) error {\n\tm.Data = data\n\treturn nil\n}\n\nfunc NewMessage(data []byte) *Message {\n\treturn &Message{data}\n}\n<commit_msg>fix missing pointer<commit_after>package proto\n\ntype Message struct {\n\tData []byte\n}\n\nfunc (m *Message) MarshalJSON() ([]byte, error) {\n\treturn m.Data, nil\n}\n\nfunc (m *Message) UnmarshalJSON(data []byte) error {\n\tm.Data = data\n\treturn nil\n}\n\nfunc (m *Message) ProtoMessage() {}\n\nfunc (m *Message) Reset() {\n\t*m = Message{}\n}\n\nfunc (m *Message) String() string {\n\treturn string(m.Data)\n}\n\nfunc (m *Message) Marshal() ([]byte, error) {\n\treturn m.Data, nil\n}\n\nfunc (m *Message) Unmarshal(data []byte) error {\n\tm.Data = data\n\treturn nil\n}\n\nfunc NewMessage(data []byte) *Message {\n\treturn &Message{data}\n}\n<|endoftext|>"}
{"text":"<commit_before>package collector\n\nimport (\n\t\"fmt\"\n\t\"github.com\/timeredbull\/tsuru\/api\/app\"\n\t\"github.com\/timeredbull\/tsuru\/db\"\n\t\"launchpad.net\/goyaml\"\n\t\"launchpad.net\/mgo\/bson\"\n\t\"os\/exec\"\n)\n\ntype Collector struct{}\n\ntype Unit struct {\n\tMachine int\n\tState   string\n}\n\ntype Service struct {\n\tUnits map[string]Unit\n}\n\ntype output struct {\n\tServices map[string]Service\n\tMachines map[int]interface{}\n}\n\nfunc (c *Collector) Collect() ([]byte, error) {\n\tfmt.Println(\"collecting status\")\n\treturn exec.Command(\"juju\", \"status\").Output()\n}\n\nfunc (c *Collector) Parse(data []byte) *output {\n\tfmt.Println(\"parsing yaml\")\n\traw := new(output)\n\t_ = goyaml.Unmarshal(data, raw)\n\treturn raw\n}\n\nfunc (c *Collector) Update(out *output) {\n\tfmt.Println(\"updating status\")\n\n\tfor serviceName, service := range out.Services {\n\t\tfor _, unit := range service.Units {\n\t\t\tappUnit := app.App{Name: serviceName}\n\t\t\tappUnit.Get()\n\t\t\tif unit.State == \"started\" {\n\t\t\t\tappUnit.State = \"STARTED\"\n\t\t\t} else {\n\t\t\t\tappUnit.State = \"STOPPED\"\n\t\t\t}\n\t\t\tappUnit.Ip = out.Machines[unit.Machine].(map[interface{}]interface{})[\"dns-name\"].(string)\n\t\t\tdb.Session.Apps().Update(bson.M{\"name\": appUnit.Name}, appUnit)\n\t\t}\n\t}\n}\n<commit_msg>using log in collector<commit_after>package collector\n\nimport (\n\t\"github.com\/timeredbull\/tsuru\/api\/app\"\n\t\"github.com\/timeredbull\/tsuru\/db\"\n\t\"github.com\/timeredbull\/tsuru\/log\"\n\t\"launchpad.net\/goyaml\"\n\t\"launchpad.net\/mgo\/bson\"\n\t\"os\/exec\"\n)\n\ntype Collector struct{}\n\ntype Unit struct {\n\tMachine int\n\tState   string\n}\n\ntype Service struct {\n\tUnits map[string]Unit\n}\n\ntype output struct {\n\tServices map[string]Service\n\tMachines map[int]interface{}\n}\n\nfunc (c *Collector) Collect() ([]byte, error) {\n\tlog.Print(\"collecting status\")\n\treturn exec.Command(\"juju\", \"status\").Output()\n}\n\nfunc (c *Collector) Parse(data []byte) *output {\n\tlog.Print(\"parsing yaml\")\n\traw := new(output)\n\t_ = goyaml.Unmarshal(data, raw)\n\treturn raw\n}\n\nfunc (c *Collector) Update(out *output) {\n\tlog.Print(\"updating status\")\n\tfor serviceName, service := range out.Services {\n\t\tfor _, unit := range service.Units {\n\t\t\tappUnit := app.App{Name: serviceName}\n\t\t\tappUnit.Get()\n\t\t\tif unit.State == \"started\" {\n\t\t\t\tappUnit.State = \"STARTED\"\n\t\t\t} else {\n\t\t\t\tappUnit.State = \"STOPPED\"\n\t\t\t}\n\t\t\tappUnit.Ip = out.Machines[unit.Machine].(map[interface{}]interface{})[\"dns-name\"].(string)\n\t\t\tdb.Session.Apps().Update(bson.M{\"name\": appUnit.Name}, appUnit)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage sse\n\nimport (\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nvar url string\nvar srv *Server\nvar server *httptest.Server\n\nfunc setup(empty bool) {\n\t\/\/ New Server\n\tsrv = New()\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"\/events\", srv.HTTPHandler)\n\tserver = httptest.NewServer(mux)\n\turl = server.URL + \"\/events\"\n\n\tsrv.CreateStream(\"test\")\n\n\t\/\/ Send continuous string of events to the client\n\tgo func(s *Server) {\n\t\tfor {\n\t\t\tif empty {\n\t\t\t\ts.Publish(\"test\", &Event{Data: []byte(\"\\n\")})\n\t\t\t} else {\n\t\t\t\ts.Publish(\"test\", &Event{Data: []byte(\"ping\")})\n\t\t\t}\n\t\t\ttime.Sleep(time.Millisecond * 50)\n\t\t}\n\t}(srv)\n}\n\nfunc cleanup() {\n\tserver.CloseClientConnections()\n\tserver.Close()\n\tsrv.Close()\n}\n\nfunc TestClientSubscribe(t *testing.T) {\n\tsetup(false)\n\tdefer cleanup()\n\n\tc := NewClient(url)\n\n\tevents := make(chan *Event)\n\tvar cErr error\n\tgo func() {\n\t\tcErr = c.Subscribe(\"test\", func(msg *Event) {\n\t\t\tif msg.Data != nil {\n\t\t\t\tevents <- msg\n\t\t\t\treturn\n\t\t\t}\n\t\t})\n\t}()\n\n\tfor i := 0; i < 5; i++ {\n\t\tmsg, err := wait(events, time.Second*1)\n\t\trequire.Nil(t, err)\n\t\tassert.Equal(t, []byte(`ping`), msg)\n\t}\n\n\tassert.Nil(t, cErr)\n}\n\nfunc TestClientChanSubscribeEmptyMessage(t *testing.T) {\n\tsetup(true)\n\tdefer cleanup()\n\n\tc := NewClient(url)\n\n\tevents := make(chan *Event)\n\terr := c.SubscribeChan(\"test\", events)\n\trequire.Nil(t, err)\n\n\tfor i := 0; i < 5; i++ {\n\t\t_, err := waitEvent(events, time.Second)\n\t\trequire.Nil(t, err)\n\t}\n}\n\nfunc TestClientChanSubscribe(t *testing.T) {\n\tsetup(false)\n\tdefer cleanup()\n\n\tc := NewClient(url)\n\n\tevents := make(chan *Event)\n\terr := c.SubscribeChan(\"test\", events)\n\trequire.Nil(t, err)\n\n\tfor i := 0; i < 5; i++ {\n\t\tmsg, merr := wait(events, time.Second*1)\n\t\tif msg == nil {\n\t\t\ti--\n\t\t\tcontinue\n\t\t}\n\t\tassert.Nil(t, merr)\n\t\tassert.Equal(t, []byte(`ping`), msg)\n\t}\n\tc.Unsubscribe(events)\n}\n\nfunc TestClientOnDisconnect(t *testing.T) {\n\tsetup(false)\n\tdefer cleanup()\n\n\tc := NewClient(url)\n\n\tcalled := make(chan bool)\n\tc.OnDisconnect(func(client *Client) {\n\t\tcalled <- true\n\t})\n\n\tgo c.Subscribe(\"test\", func(msg *Event) {})\n\n\ttime.Sleep(time.Second)\n\tserver.CloseClientConnections()\n\n\tassert.True(t, <-called)\n}\n\nfunc TestClientChanReconnect(t *testing.T) {\n\tsetup(false)\n\tdefer cleanup()\n\n\tc := NewClient(url)\n\n\tevents := make(chan *Event)\n\terr := c.SubscribeChan(\"test\", events)\n\trequire.Nil(t, err)\n\n\tfor i := 0; i < 10; i++ {\n\t\tif i == 5 {\n\t\t\t\/\/ kill connection\n\t\t\tserver.CloseClientConnections()\n\t\t}\n\t\tmsg, merr := wait(events, time.Second*1)\n\t\tif msg == nil {\n\t\t\ti--\n\t\t\tcontinue\n\t\t}\n\t\tassert.Nil(t, merr)\n\t\tassert.Equal(t, []byte(`ping`), msg)\n\t}\n\tc.Unsubscribe(events)\n}\n\nfunc TestClientUnsubscribe(t *testing.T) {\n\tsetup(false)\n\tdefer cleanup()\n\n\tc := NewClient(url)\n\n\tevents := make(chan *Event)\n\terr := c.SubscribeChan(\"test\", events)\n\trequire.Nil(t, err)\n\n\ttime.Sleep(time.Millisecond * 500)\n\n\tgo c.Unsubscribe(events)\n\tgo c.Unsubscribe(events)\n}\n<commit_msg>Test for unsubscribe blocking<commit_after>\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage sse\n\nimport (\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nvar url string\nvar srv *Server\nvar server *httptest.Server\n\nfunc setup(empty bool) {\n\t\/\/ New Server\n\tsrv = newServer()\n\t\/\/ Send almost-continuous string of events to the client\n\tgo publishMsgs(srv, empty, 100000000)\n}\n\nfunc setupCount(empty bool, count int) {\n\tsrv = newServer()\n\tgo publishMsgs(srv, empty, count)\n}\n\nfunc newServer() *Server {\n\tsrv = New()\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"\/events\", srv.HTTPHandler)\n\tserver = httptest.NewServer(mux)\n\turl = server.URL + \"\/events\"\n\n\tsrv.CreateStream(\"test\")\n\n\treturn srv\n}\n\nfunc publishMsgs(s *Server, empty bool, count int) {\n\tfor a := 0; a < count; a++ {\n\t\tif empty {\n\t\t\ts.Publish(\"test\", &Event{Data: []byte(\"\\n\")})\n\t\t} else {\n\t\t\ts.Publish(\"test\", &Event{Data: []byte(\"ping\")})\n\t\t}\n\t\ttime.Sleep(time.Millisecond * 50)\n\t}\n}\n\nfunc cleanup() {\n\tserver.CloseClientConnections()\n\tserver.Close()\n\tsrv.Close()\n}\n\nfunc TestClientSubscribe(t *testing.T) {\n\tsetup(false)\n\tdefer cleanup()\n\n\tc := NewClient(url)\n\n\tevents := make(chan *Event)\n\tvar cErr error\n\tgo func() {\n\t\tcErr = c.Subscribe(\"test\", func(msg *Event) {\n\t\t\tif msg.Data != nil {\n\t\t\t\tevents <- msg\n\t\t\t\treturn\n\t\t\t}\n\t\t})\n\t}()\n\n\tfor i := 0; i < 5; i++ {\n\t\tmsg, err := wait(events, time.Second*1)\n\t\trequire.Nil(t, err)\n\t\tassert.Equal(t, []byte(`ping`), msg)\n\t}\n\n\tassert.Nil(t, cErr)\n}\n\nfunc TestClientChanSubscribeEmptyMessage(t *testing.T) {\n\tsetup(true)\n\tdefer cleanup()\n\n\tc := NewClient(url)\n\n\tevents := make(chan *Event)\n\terr := c.SubscribeChan(\"test\", events)\n\trequire.Nil(t, err)\n\n\tfor i := 0; i < 5; i++ {\n\t\t_, err := waitEvent(events, time.Second)\n\t\trequire.Nil(t, err)\n\t}\n}\n\nfunc TestClientChanSubscribe(t *testing.T) {\n\tsetup(false)\n\tdefer cleanup()\n\n\tc := NewClient(url)\n\n\tevents := make(chan *Event)\n\terr := c.SubscribeChan(\"test\", events)\n\trequire.Nil(t, err)\n\n\tfor i := 0; i < 5; i++ {\n\t\tmsg, merr := wait(events, time.Second*1)\n\t\tif msg == nil {\n\t\t\ti--\n\t\t\tcontinue\n\t\t}\n\t\tassert.Nil(t, merr)\n\t\tassert.Equal(t, []byte(`ping`), msg)\n\t}\n\tc.Unsubscribe(events)\n}\n\nfunc TestClientOnDisconnect(t *testing.T) {\n\tsetup(false)\n\tdefer cleanup()\n\n\tc := NewClient(url)\n\n\tcalled := make(chan bool)\n\tc.OnDisconnect(func(client *Client) {\n\t\tcalled <- true\n\t})\n\n\tgo c.Subscribe(\"test\", func(msg *Event) {})\n\n\ttime.Sleep(time.Second)\n\tserver.CloseClientConnections()\n\n\tassert.True(t, <-called)\n}\n\nfunc TestClientChanReconnect(t *testing.T) {\n\tsetup(false)\n\tdefer cleanup()\n\n\tc := NewClient(url)\n\n\tevents := make(chan *Event)\n\terr := c.SubscribeChan(\"test\", events)\n\trequire.Nil(t, err)\n\n\tfor i := 0; i < 10; i++ {\n\t\tif i == 5 {\n\t\t\t\/\/ kill connection\n\t\t\tserver.CloseClientConnections()\n\t\t}\n\t\tmsg, merr := wait(events, time.Second*1)\n\t\tif msg == nil {\n\t\t\ti--\n\t\t\tcontinue\n\t\t}\n\t\tassert.Nil(t, merr)\n\t\tassert.Equal(t, []byte(`ping`), msg)\n\t}\n\tc.Unsubscribe(events)\n}\n\nfunc TestClientUnsubscribe(t *testing.T) {\n\tsetup(false)\n\tdefer cleanup()\n\n\tc := NewClient(url)\n\n\tevents := make(chan *Event)\n\terr := c.SubscribeChan(\"test\", events)\n\trequire.Nil(t, err)\n\n\ttime.Sleep(time.Millisecond * 500)\n\n\tgo c.Unsubscribe(events)\n\tgo c.Unsubscribe(events)\n}\n\nfunc TestClientUnsubscribeNonBlock(t *testing.T) {\n\tcount := 2\n\tsetupCount(false, count)\n\tdefer cleanup()\n\n\tc := NewClient(url)\n\n\tevents := make(chan *Event)\n\terr := c.SubscribeChan(\"test\", events)\n\trequire.Nil(t, err)\n\n\t\/\/ Read count messages from the channel\n\tfor i := 0; i < count; i++ {\n\t\tmsg, merr := wait(events, time.Second*1)\n\t\tassert.Nil(t, merr)\n\t\tassert.Equal(t, []byte(`ping`), msg)\n\t}\n\t\/\/No more data is available to be read in the channel\n\t\/\/ Make sure Unsubscribe returns quickly\n\tdoneCh := make(chan *Event)\n\tgo func() {\n\t\tvar e Event\n\t\tc.Unsubscribe(events)\n\t\tdoneCh <- &e\n\t}()\n\t_, merr := wait(doneCh, time.Millisecond*100)\n\tassert.Nil(t, merr)\n}\n<|endoftext|>"}
{"text":"<commit_before>package twitch\n\nimport (\n\t\"bufio\"\n\t\"net\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestCanCreateClient(t *testing.T) {\n\tclient := NewClient(\"justinfan123123\", \"oauth:1123123\")\n\n\tif reflect.TypeOf(*client) != reflect.TypeOf(Client{}) {\n\t\tt.Error(\"client is not of type Client\")\n\t}\n}\n\nfunc TestCanConnectAndAuthenticate(t *testing.T) {\n\tvar nicknameMsg string\n\tvar oauthMsg string\n\n\tgo func() {\n\t\tln, _ := net.Listen(\"tcp\", \":4321\")\n\t\tconn, _ := ln.Accept()\n\n\t\tfor {\n\t\t\tmessage, _ := bufio.NewReader(conn).ReadString('\\n')\n\t\t\tmessage = strings.Replace(message, \"\\r\\n\", \"\", 1)\n\t\t\tif strings.HasPrefix(message, \"NICK\") {\n\t\t\t\tnicknameMsg = message\n\t\t\t}\n\t\t\tif strings.HasPrefix(message, \"PASS\") {\n\t\t\t\toauthMsg = message\n\t\t\t}\n\t\t\tif nicknameMsg != \"\" && oauthMsg != \"\" {\n\t\t\t\tln.Close()\n\t\t\t}\n\t\t}\n\t}()\n\n\tclient := NewClient(\"justinfan123123\", \"oauth:123123132\")\n\tclient.SetIrcAddress(\"127.0.0.1:4321\")\n\tgo client.Connect()\n\n\t\/\/ wait for client to connect and server to read messages\n\ttime.Sleep(time.Second)\n\n\tif nicknameMsg != \"NICK justinfan123123\" || oauthMsg != \"PASS oauth:123123132\" {\n\t\tt.Fatalf(\"invalid authentication data: username: %s, oauth: %s\", nicknameMsg, oauthMsg)\n\t}\n}\n<commit_msg>change ip address<commit_after>package twitch\n\nimport (\n\t\"bufio\"\n\t\"net\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestCanCreateClient(t *testing.T) {\n\tclient := NewClient(\"justinfan123123\", \"oauth:1123123\")\n\n\tif reflect.TypeOf(*client) != reflect.TypeOf(Client{}) {\n\t\tt.Error(\"client is not of type Client\")\n\t}\n}\n\nfunc TestCanConnectAndAuthenticate(t *testing.T) {\n\tvar nicknameMsg string\n\tvar oauthMsg string\n\n\tgo func() {\n\t\tln, _ := net.Listen(\"tcp\", \":4321\")\n\t\tconn, _ := ln.Accept()\n\n\t\tfor {\n\t\t\tmessage, _ := bufio.NewReader(conn).ReadString('\\n')\n\t\t\tmessage = strings.Replace(message, \"\\r\\n\", \"\", 1)\n\t\t\tif strings.HasPrefix(message, \"NICK\") {\n\t\t\t\tnicknameMsg = message\n\t\t\t}\n\t\t\tif strings.HasPrefix(message, \"PASS\") {\n\t\t\t\toauthMsg = message\n\t\t\t}\n\t\t\tif nicknameMsg != \"\" && oauthMsg != \"\" {\n\t\t\t\tln.Close()\n\t\t\t}\n\t\t}\n\t}()\n\n\tclient := NewClient(\"justinfan123123\", \"oauth:123123132\")\n\tclient.SetIrcAddress(\":4321\")\n\tgo client.Connect()\n\n\t\/\/ wait for client to connect and server to read messages\n\ttime.Sleep(time.Second)\n\n\tif nicknameMsg != \"NICK justinfan123123\" || oauthMsg != \"PASS oauth:123123132\" {\n\t\tt.Fatalf(\"invalid authentication data: username: %s, oauth: %s\", nicknameMsg, oauthMsg)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"fmt\"\n\ntype versionCommand struct{}\n\nfunc (cmd *versionCommand) Execute(args []string) error {\n\treturn runInContext(func(current *executionContext) error {\n\t\tversion := buildVersion\n\t\tif version == \"\" {\n\t\t\tversion = \"0.0.0-development\"\n\t\t}\n\n\t\tfmt.Printf(\"%s %s\\n\", ProjectId, version)\n\t\treturn nil\n\t})\n}\n\nfunc init() {\n\tcommandParser.AddCommand(\"version\", \"\", \"\", &versionCommand{})\n}\n<commit_msg>remove old version cmd<commit_after><|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"os\"\n\n\t\"github.com\/develed\/develed\/slackbot\"\n\t\"github.com\/nlopes\/slack\"\n)\n\nfunc main() {\n\tbot := slackbot.New(os.Getenv(\"SLACK_BOT_TOKEN\"))\n\n\tbot.DefaultResponse(func(b *slackbot.Bot, msg *slack.Msg) {\n\t\tbot.Message(msg.Channel, \"Non ho capito\")\n\t})\n\n\tbot.RespondTo(\"ciao\", func(b *slackbot.Bot, msg *slack.Msg, args ...string) {\n\t\tbot.Message(msg.Channel, \"Olà!\")\n\t})\n\n\tbot.RespondTo(\"echo (.*)\", func(b *slackbot.Bot, msg *slack.Msg, args ...string) {\n\t\tbot.Message(msg.Channel, \"Hai scritto: \"+args[1])\n\t})\n\n\tbot.Start()\n}\n<commit_msg>bot: support for textd functionalities<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/develed\/develed\/config\"\n\tsrv \"github.com\/develed\/develed\/services\"\n\t\"github.com\/develed\/develed\/slackbot\"\n\t\"github.com\/nlopes\/slack\"\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\"\n)\n\nvar (\n\tcfg = flag.String(\"config\", \"\/etc\/develed.toml\", \"configuration file\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tconf, err := config.Load(*cfg)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tbot := slackbot.New(os.Getenv(\"SLACK_BOT_TOKEN\"))\n\n\tconn, err := grpc.Dial(conf.Textd.GRPCServerAddress, grpc.WithInsecure())\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer conn.Close()\n\n\ttextd := srv.NewTextdClient(conn)\n\n\tbot.DefaultResponse(func(b *slackbot.Bot, msg *slack.Msg) {\n\t\tbot.Message(msg.Channel, \"Non ho capito\")\n\t})\n\n\tbot.RespondTo(\"scrivi (.*)\", func(b *slackbot.Bot, msg *slack.Msg, args ...string) {\n\t\ttext := args[1]\n\n\t\t_, err := textd.Write(context.Background(), &srv.TextRequest{\n\t\t\tText: text,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Errorln(err)\n\t\t} else {\n\t\t\tbot.Message(msg.Channel, \"Hai scritto: \"+text)\n\t\t}\n\t})\n\n\tbot.Start()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * MinIO Cloud Storage, (C) 2016-2020 MinIO, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage cmd\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/minio\/minio\/cmd\/logger\"\n\t\"github.com\/minio\/minio\/pkg\/bpool\"\n\t\"github.com\/minio\/minio\/pkg\/color\"\n\t\"github.com\/minio\/minio\/pkg\/dsync\"\n\t\"github.com\/minio\/minio\/pkg\/madmin\"\n\t\"github.com\/minio\/minio\/pkg\/sync\/errgroup\"\n)\n\n\/\/ OfflineDisk represents an unavailable disk.\nvar OfflineDisk StorageAPI \/\/ zero value is nil\n\n\/\/ partialOperation is a successful upload\/delete of an object\n\/\/ but not written in all disks (having quorum)\ntype partialOperation struct {\n\tbucket    string\n\tobject    string\n\tversionID string\n\tfailedSet int\n}\n\n\/\/ erasureObjects - Implements ER object layer.\ntype erasureObjects struct {\n\tGatewayUnsupported\n\n\tsetDriveCount      int\n\tdefaultParityCount int\n\n\tsetNumber int\n\n\t\/\/ getDisks returns list of storageAPIs.\n\tgetDisks func() []StorageAPI\n\n\t\/\/ getLockers returns list of remote and local lockers.\n\tgetLockers func() ([]dsync.NetLocker, string)\n\n\t\/\/ getEndpoints returns list of endpoint strings belonging this set.\n\t\/\/ some may be local and some remote.\n\tgetEndpoints func() []string\n\n\t\/\/ Locker mutex map.\n\tnsMutex *nsLockMap\n\n\t\/\/ Byte pools used for temporary i\/o buffers.\n\tbp *bpool.BytePoolCap\n\n\tmrfOpCh chan partialOperation\n}\n\n\/\/ NewNSLock - initialize a new namespace RWLocker instance.\nfunc (er erasureObjects) NewNSLock(bucket string, objects ...string) RWLocker {\n\treturn er.nsMutex.NewNSLock(er.getLockers, bucket, objects...)\n}\n\n\/\/ Shutdown function for object storage interface.\nfunc (er erasureObjects) Shutdown(ctx context.Context) error {\n\t\/\/ Add any object layer shutdown activities here.\n\tcloseStorageDisks(er.getDisks())\n\treturn nil\n}\n\n\/\/ byDiskTotal is a collection satisfying sort.Interface.\ntype byDiskTotal []madmin.Disk\n\nfunc (d byDiskTotal) Len() int      { return len(d) }\nfunc (d byDiskTotal) Swap(i, j int) { d[i], d[j] = d[j], d[i] }\nfunc (d byDiskTotal) Less(i, j int) bool {\n\treturn d[i].TotalSpace < d[j].TotalSpace\n}\n\nfunc diskErrToDriveState(err error) (state string) {\n\tstate = madmin.DriveStateUnknown\n\tswitch {\n\tcase errors.Is(err, errDiskNotFound):\n\t\tstate = madmin.DriveStateOffline\n\tcase errors.Is(err, errCorruptedFormat):\n\t\tstate = madmin.DriveStateCorrupt\n\tcase errors.Is(err, errUnformattedDisk):\n\t\tstate = madmin.DriveStateUnformatted\n\tcase errors.Is(err, errDiskAccessDenied):\n\t\tstate = madmin.DriveStatePermission\n\tcase errors.Is(err, errFaultyDisk):\n\t\tstate = madmin.DriveStateFaulty\n\tcase err == nil:\n\t\tstate = madmin.DriveStateOk\n\t}\n\treturn\n}\n\nfunc getOnlineOfflineDisksStats(disksInfo []madmin.Disk) (onlineDisks, offlineDisks madmin.BackendDisks) {\n\tonlineDisks = make(madmin.BackendDisks)\n\tofflineDisks = make(madmin.BackendDisks)\n\n\tfor _, disk := range disksInfo {\n\t\tep := disk.Endpoint\n\t\tif _, ok := offlineDisks[ep]; !ok {\n\t\t\tofflineDisks[ep] = 0\n\t\t}\n\t\tif _, ok := onlineDisks[ep]; !ok {\n\t\t\tonlineDisks[ep] = 0\n\t\t}\n\t}\n\n\t\/\/ Wait for the routines.\n\tfor _, disk := range disksInfo {\n\t\tep := disk.Endpoint\n\t\tstate := disk.State\n\t\tif state != madmin.DriveStateOk && state != madmin.DriveStateUnformatted {\n\t\t\tofflineDisks[ep]++\n\t\t\tcontinue\n\t\t}\n\t\tonlineDisks[ep]++\n\t}\n\n\trootDiskCount := 0\n\tfor _, di := range disksInfo {\n\t\tif di.RootDisk {\n\t\t\trootDiskCount++\n\t\t}\n\t}\n\n\t\/\/ Count offline disks as well to ensure consistent\n\t\/\/ reportability of offline drives on local setups.\n\tif len(disksInfo) == (rootDiskCount + offlineDisks.Sum()) {\n\t\t\/\/ Success.\n\t\treturn onlineDisks, offlineDisks\n\t}\n\n\t\/\/ Root disk should be considered offline\n\tfor i := range disksInfo {\n\t\tep := disksInfo[i].Endpoint\n\t\tif disksInfo[i].RootDisk {\n\t\t\tofflineDisks[ep]++\n\t\t\tonlineDisks[ep]--\n\t\t}\n\t}\n\n\treturn onlineDisks, offlineDisks\n}\n\n\/\/ getDisksInfo - fetch disks info across all other storage API.\nfunc getDisksInfo(disks []StorageAPI, endpoints []string) (disksInfo []madmin.Disk, errs []error) {\n\tdisksInfo = make([]madmin.Disk, len(disks))\n\n\tg := errgroup.WithNErrs(len(disks))\n\tfor index := range disks {\n\t\tindex := index\n\t\tg.Go(func() error {\n\t\t\tif disks[index] == OfflineDisk {\n\t\t\t\tlogger.LogIf(GlobalContext, fmt.Errorf(\"%s: %s\", errDiskNotFound, endpoints[index]))\n\t\t\t\tdisksInfo[index] = madmin.Disk{\n\t\t\t\t\tState:    diskErrToDriveState(errDiskNotFound),\n\t\t\t\t\tEndpoint: endpoints[index],\n\t\t\t\t}\n\t\t\t\t\/\/ Storage disk is empty, perhaps ignored disk or not available.\n\t\t\t\treturn errDiskNotFound\n\t\t\t}\n\t\t\tinfo, err := disks[index].DiskInfo(context.TODO())\n\t\t\tdi := madmin.Disk{\n\t\t\t\tEndpoint:       endpoints[index],\n\t\t\t\tDrivePath:      info.MountPath,\n\t\t\t\tTotalSpace:     info.Total,\n\t\t\t\tUsedSpace:      info.Used,\n\t\t\t\tAvailableSpace: info.Free,\n\t\t\t\tUUID:           info.ID,\n\t\t\t\tRootDisk:       info.RootDisk,\n\t\t\t\tHealing:        info.Healing,\n\t\t\t\tState:          diskErrToDriveState(err),\n\t\t\t}\n\t\t\tif info.Total > 0 {\n\t\t\t\tdi.Utilization = float64(info.Used \/ info.Total * 100)\n\t\t\t}\n\t\t\tdisksInfo[index] = di\n\t\t\treturn err\n\t\t}, index)\n\t}\n\n\treturn disksInfo, g.Wait()\n}\n\n\/\/ Get an aggregated storage info across all disks.\nfunc getStorageInfo(disks []StorageAPI, endpoints []string) (StorageInfo, []error) {\n\tdisksInfo, errs := getDisksInfo(disks, endpoints)\n\n\t\/\/ Sort so that the first element is the smallest.\n\tsort.Sort(byDiskTotal(disksInfo))\n\n\tstorageInfo := StorageInfo{\n\t\tDisks: disksInfo,\n\t}\n\n\tstorageInfo.Backend.Type = BackendErasure\n\treturn storageInfo, errs\n}\n\n\/\/ StorageInfo - returns underlying storage statistics.\nfunc (er erasureObjects) StorageInfo(ctx context.Context) (StorageInfo, []error) {\n\tdisks := er.getDisks()\n\tendpoints := er.getEndpoints()\n\treturn getStorageInfo(disks, endpoints)\n}\n\nfunc (er erasureObjects) getOnlineDisksWithHealing() (newDisks []StorageAPI, healing bool) {\n\tvar wg sync.WaitGroup\n\tdisks := er.getDisks()\n\tinfos := make([]DiskInfo, len(disks))\n\tfor _, i := range hashOrder(UTCNow().String(), len(disks)) {\n\t\ti := i\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\n\t\t\tdisk := disks[i-1]\n\n\t\t\tif disk == nil {\n\t\t\t\tinfos[i-1].Error = \"nil disk\"\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tdi, err := disk.DiskInfo(context.Background())\n\t\t\tif err != nil {\n\t\t\t\t\/\/ - Do not consume disks which are not reachable\n\t\t\t\t\/\/   unformatted or simply not accessible for some reason.\n\t\t\t\t\/\/\n\t\t\t\t\/\/\n\t\t\t\t\/\/ - Future: skip busy disks\n\t\t\t\tinfos[i-1].Error = err.Error()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tinfos[i-1] = di\n\t\t}()\n\t}\n\twg.Wait()\n\n\tfor i, info := range infos {\n\t\t\/\/ Check if one of the drives in the set is being healed.\n\t\t\/\/ this information is used by crawler to skip healing\n\t\t\/\/ this erasure set while it calculates the usage.\n\t\tif info.Healing || info.Error != \"\" {\n\t\t\thealing = true\n\t\t\tcontinue\n\t\t}\n\t\tnewDisks = append(newDisks, disks[i])\n\t}\n\n\treturn newDisks, healing\n}\n\n\/\/ CrawlAndGetDataUsage will start crawling buckets and send updated totals as they are traversed.\n\/\/ Updates are sent on a regular basis and the caller *must* consume them.\nfunc (er erasureObjects) crawlAndGetDataUsage(ctx context.Context, buckets []BucketInfo, bf *bloomFilter, updates chan<- dataUsageCache) error {\n\tif len(buckets) == 0 {\n\t\tlogger.Info(color.Green(\"data-crawl:\") + \" No buckets found, skipping crawl\")\n\t\treturn nil\n\t}\n\n\t\/\/ Collect disks we can use.\n\tdisks, healing := er.getOnlineDisksWithHealing()\n\tif len(disks) == 0 {\n\t\tlogger.Info(color.Green(\"data-crawl:\") + \" all disks are offline or being healed, skipping crawl\")\n\t\treturn nil\n\t}\n\n\t\/\/ Collect disks for healing.\n\tallDisks := er.getDisks()\n\tallDiskIDs := make([]string, 0, len(allDisks))\n\tfor _, disk := range allDisks {\n\t\tif disk == OfflineDisk {\n\t\t\t\/\/ its possible that disk is OfflineDisk\n\t\t\tcontinue\n\t\t}\n\t\tid, _ := disk.GetDiskID()\n\t\tif id == \"\" {\n\t\t\t\/\/ its possible that disk is unformatted\n\t\t\t\/\/ or just went offline\n\t\t\tcontinue\n\t\t}\n\t\tallDiskIDs = append(allDiskIDs, id)\n\t}\n\n\t\/\/ Load bucket totals\n\toldCache := dataUsageCache{}\n\tif err := oldCache.load(ctx, er, dataUsageCacheName); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ New cache..\n\tcache := dataUsageCache{\n\t\tInfo: dataUsageCacheInfo{\n\t\t\tName:      dataUsageRoot,\n\t\t\tNextCycle: oldCache.Info.NextCycle,\n\t\t},\n\t\tCache: make(map[string]dataUsageEntry, len(oldCache.Cache)),\n\t}\n\tbloom := bf.bytes()\n\n\t\/\/ Put all buckets into channel.\n\tbucketCh := make(chan BucketInfo, len(buckets))\n\t\/\/ Add new buckets first\n\tfor _, b := range buckets {\n\t\tif oldCache.find(b.Name) == nil {\n\t\t\tbucketCh <- b\n\t\t}\n\t}\n\n\t\/\/ Add existing buckets.\n\tfor _, b := range buckets {\n\t\te := oldCache.find(b.Name)\n\t\tif e != nil {\n\t\t\tcache.replace(b.Name, dataUsageRoot, *e)\n\t\t\tbucketCh <- b\n\t\t}\n\t}\n\n\tclose(bucketCh)\n\tbucketResults := make(chan dataUsageEntryInfo, len(disks))\n\n\t\/\/ Start async collector\/saver.\n\t\/\/ This goroutine owns the cache.\n\tvar saverWg sync.WaitGroup\n\tsaverWg.Add(1)\n\tgo func() {\n\t\tconst updateTime = 30 * time.Second\n\t\tt := time.NewTicker(updateTime)\n\t\tdefer t.Stop()\n\t\tdefer saverWg.Done()\n\t\tvar lastSave time.Time\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\t\/\/ Return without saving.\n\t\t\t\treturn\n\t\t\tcase <-t.C:\n\t\t\t\tif cache.Info.LastUpdate.Equal(lastSave) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlogger.LogIf(ctx, cache.save(ctx, er, dataUsageCacheName))\n\t\t\t\tupdates <- cache.clone()\n\t\t\t\tlastSave = cache.Info.LastUpdate\n\t\t\tcase v, ok := <-bucketResults:\n\t\t\t\tif !ok {\n\t\t\t\t\t\/\/ Save final state...\n\t\t\t\t\tcache.Info.NextCycle++\n\t\t\t\t\tcache.Info.LastUpdate = time.Now()\n\t\t\t\t\tlogger.LogIf(ctx, cache.save(ctx, er, dataUsageCacheName))\n\t\t\t\t\tupdates <- cache\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcache.replace(v.Name, v.Parent, v.Entry)\n\t\t\t\tcache.Info.LastUpdate = time.Now()\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ Start one crawler per disk\n\tvar wg sync.WaitGroup\n\twg.Add(len(disks))\n\tfor i := range disks {\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\t\t\tdisk := disks[i]\n\n\t\t\tfor bucket := range bucketCh {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t}\n\n\t\t\t\t\/\/ Load cache for bucket\n\t\t\t\tcacheName := pathJoin(bucket.Name, dataUsageCacheName)\n\t\t\t\tcache := dataUsageCache{}\n\t\t\t\tlogger.LogIf(ctx, cache.load(ctx, er, cacheName))\n\t\t\t\tif cache.Info.Name == \"\" {\n\t\t\t\t\tcache.Info.Name = bucket.Name\n\t\t\t\t}\n\t\t\t\tcache.Info.BloomFilter = bloom\n\t\t\t\tcache.Info.SkipHealing = healing\n\t\t\t\tcache.Disks = allDiskIDs\n\t\t\t\tif cache.Info.Name != bucket.Name {\n\t\t\t\t\tlogger.LogIf(ctx, fmt.Errorf(\"cache name mismatch: %s != %s\", cache.Info.Name, bucket.Name))\n\t\t\t\t\tcache.Info = dataUsageCacheInfo{\n\t\t\t\t\t\tName:       bucket.Name,\n\t\t\t\t\t\tLastUpdate: time.Time{},\n\t\t\t\t\t\tNextCycle:  0,\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ Calc usage\n\t\t\t\tbefore := cache.Info.LastUpdate\n\t\t\t\tvar err error\n\t\t\t\tcache, err = disk.CrawlAndGetDataUsage(ctx, cache)\n\t\t\t\tcache.Info.BloomFilter = nil\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.LogIf(ctx, err)\n\t\t\t\t\tif cache.Info.LastUpdate.After(before) {\n\t\t\t\t\t\tlogger.LogIf(ctx, cache.save(ctx, er, cacheName))\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tvar root dataUsageEntry\n\t\t\t\tif r := cache.root(); r != nil {\n\t\t\t\t\troot = cache.flatten(*r)\n\t\t\t\t}\n\t\t\t\tbucketResults <- dataUsageEntryInfo{\n\t\t\t\t\tName:   cache.Info.Name,\n\t\t\t\t\tParent: dataUsageRoot,\n\t\t\t\t\tEntry:  root,\n\t\t\t\t}\n\t\t\t\t\/\/ Save cache\n\t\t\t\tlogger.LogIf(ctx, cache.save(ctx, er, cacheName))\n\t\t\t}\n\t\t}(i)\n\t}\n\twg.Wait()\n\tclose(bucketResults)\n\tsaverWg.Wait()\n\n\treturn nil\n}\n<commit_msg>Reduce redundant crawler logging (#11448)<commit_after>\/*\n * MinIO Cloud Storage, (C) 2016-2020 MinIO, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage cmd\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/minio\/minio\/cmd\/logger\"\n\t\"github.com\/minio\/minio\/pkg\/bpool\"\n\t\"github.com\/minio\/minio\/pkg\/color\"\n\t\"github.com\/minio\/minio\/pkg\/dsync\"\n\t\"github.com\/minio\/minio\/pkg\/madmin\"\n\t\"github.com\/minio\/minio\/pkg\/sync\/errgroup\"\n)\n\n\/\/ OfflineDisk represents an unavailable disk.\nvar OfflineDisk StorageAPI \/\/ zero value is nil\n\n\/\/ partialOperation is a successful upload\/delete of an object\n\/\/ but not written in all disks (having quorum)\ntype partialOperation struct {\n\tbucket    string\n\tobject    string\n\tversionID string\n\tfailedSet int\n}\n\n\/\/ erasureObjects - Implements ER object layer.\ntype erasureObjects struct {\n\tGatewayUnsupported\n\n\tsetDriveCount      int\n\tdefaultParityCount int\n\n\tsetNumber int\n\n\t\/\/ getDisks returns list of storageAPIs.\n\tgetDisks func() []StorageAPI\n\n\t\/\/ getLockers returns list of remote and local lockers.\n\tgetLockers func() ([]dsync.NetLocker, string)\n\n\t\/\/ getEndpoints returns list of endpoint strings belonging this set.\n\t\/\/ some may be local and some remote.\n\tgetEndpoints func() []string\n\n\t\/\/ Locker mutex map.\n\tnsMutex *nsLockMap\n\n\t\/\/ Byte pools used for temporary i\/o buffers.\n\tbp *bpool.BytePoolCap\n\n\tmrfOpCh chan partialOperation\n}\n\n\/\/ NewNSLock - initialize a new namespace RWLocker instance.\nfunc (er erasureObjects) NewNSLock(bucket string, objects ...string) RWLocker {\n\treturn er.nsMutex.NewNSLock(er.getLockers, bucket, objects...)\n}\n\n\/\/ Shutdown function for object storage interface.\nfunc (er erasureObjects) Shutdown(ctx context.Context) error {\n\t\/\/ Add any object layer shutdown activities here.\n\tcloseStorageDisks(er.getDisks())\n\treturn nil\n}\n\n\/\/ byDiskTotal is a collection satisfying sort.Interface.\ntype byDiskTotal []madmin.Disk\n\nfunc (d byDiskTotal) Len() int      { return len(d) }\nfunc (d byDiskTotal) Swap(i, j int) { d[i], d[j] = d[j], d[i] }\nfunc (d byDiskTotal) Less(i, j int) bool {\n\treturn d[i].TotalSpace < d[j].TotalSpace\n}\n\nfunc diskErrToDriveState(err error) (state string) {\n\tstate = madmin.DriveStateUnknown\n\tswitch {\n\tcase errors.Is(err, errDiskNotFound):\n\t\tstate = madmin.DriveStateOffline\n\tcase errors.Is(err, errCorruptedFormat):\n\t\tstate = madmin.DriveStateCorrupt\n\tcase errors.Is(err, errUnformattedDisk):\n\t\tstate = madmin.DriveStateUnformatted\n\tcase errors.Is(err, errDiskAccessDenied):\n\t\tstate = madmin.DriveStatePermission\n\tcase errors.Is(err, errFaultyDisk):\n\t\tstate = madmin.DriveStateFaulty\n\tcase err == nil:\n\t\tstate = madmin.DriveStateOk\n\t}\n\treturn\n}\n\nfunc getOnlineOfflineDisksStats(disksInfo []madmin.Disk) (onlineDisks, offlineDisks madmin.BackendDisks) {\n\tonlineDisks = make(madmin.BackendDisks)\n\tofflineDisks = make(madmin.BackendDisks)\n\n\tfor _, disk := range disksInfo {\n\t\tep := disk.Endpoint\n\t\tif _, ok := offlineDisks[ep]; !ok {\n\t\t\tofflineDisks[ep] = 0\n\t\t}\n\t\tif _, ok := onlineDisks[ep]; !ok {\n\t\t\tonlineDisks[ep] = 0\n\t\t}\n\t}\n\n\t\/\/ Wait for the routines.\n\tfor _, disk := range disksInfo {\n\t\tep := disk.Endpoint\n\t\tstate := disk.State\n\t\tif state != madmin.DriveStateOk && state != madmin.DriveStateUnformatted {\n\t\t\tofflineDisks[ep]++\n\t\t\tcontinue\n\t\t}\n\t\tonlineDisks[ep]++\n\t}\n\n\trootDiskCount := 0\n\tfor _, di := range disksInfo {\n\t\tif di.RootDisk {\n\t\t\trootDiskCount++\n\t\t}\n\t}\n\n\t\/\/ Count offline disks as well to ensure consistent\n\t\/\/ reportability of offline drives on local setups.\n\tif len(disksInfo) == (rootDiskCount + offlineDisks.Sum()) {\n\t\t\/\/ Success.\n\t\treturn onlineDisks, offlineDisks\n\t}\n\n\t\/\/ Root disk should be considered offline\n\tfor i := range disksInfo {\n\t\tep := disksInfo[i].Endpoint\n\t\tif disksInfo[i].RootDisk {\n\t\t\tofflineDisks[ep]++\n\t\t\tonlineDisks[ep]--\n\t\t}\n\t}\n\n\treturn onlineDisks, offlineDisks\n}\n\n\/\/ getDisksInfo - fetch disks info across all other storage API.\nfunc getDisksInfo(disks []StorageAPI, endpoints []string) (disksInfo []madmin.Disk, errs []error) {\n\tdisksInfo = make([]madmin.Disk, len(disks))\n\n\tg := errgroup.WithNErrs(len(disks))\n\tfor index := range disks {\n\t\tindex := index\n\t\tg.Go(func() error {\n\t\t\tif disks[index] == OfflineDisk {\n\t\t\t\tlogger.LogIf(GlobalContext, fmt.Errorf(\"%s: %s\", errDiskNotFound, endpoints[index]))\n\t\t\t\tdisksInfo[index] = madmin.Disk{\n\t\t\t\t\tState:    diskErrToDriveState(errDiskNotFound),\n\t\t\t\t\tEndpoint: endpoints[index],\n\t\t\t\t}\n\t\t\t\t\/\/ Storage disk is empty, perhaps ignored disk or not available.\n\t\t\t\treturn errDiskNotFound\n\t\t\t}\n\t\t\tinfo, err := disks[index].DiskInfo(context.TODO())\n\t\t\tdi := madmin.Disk{\n\t\t\t\tEndpoint:       endpoints[index],\n\t\t\t\tDrivePath:      info.MountPath,\n\t\t\t\tTotalSpace:     info.Total,\n\t\t\t\tUsedSpace:      info.Used,\n\t\t\t\tAvailableSpace: info.Free,\n\t\t\t\tUUID:           info.ID,\n\t\t\t\tRootDisk:       info.RootDisk,\n\t\t\t\tHealing:        info.Healing,\n\t\t\t\tState:          diskErrToDriveState(err),\n\t\t\t}\n\t\t\tif info.Total > 0 {\n\t\t\t\tdi.Utilization = float64(info.Used \/ info.Total * 100)\n\t\t\t}\n\t\t\tdisksInfo[index] = di\n\t\t\treturn err\n\t\t}, index)\n\t}\n\n\treturn disksInfo, g.Wait()\n}\n\n\/\/ Get an aggregated storage info across all disks.\nfunc getStorageInfo(disks []StorageAPI, endpoints []string) (StorageInfo, []error) {\n\tdisksInfo, errs := getDisksInfo(disks, endpoints)\n\n\t\/\/ Sort so that the first element is the smallest.\n\tsort.Sort(byDiskTotal(disksInfo))\n\n\tstorageInfo := StorageInfo{\n\t\tDisks: disksInfo,\n\t}\n\n\tstorageInfo.Backend.Type = BackendErasure\n\treturn storageInfo, errs\n}\n\n\/\/ StorageInfo - returns underlying storage statistics.\nfunc (er erasureObjects) StorageInfo(ctx context.Context) (StorageInfo, []error) {\n\tdisks := er.getDisks()\n\tendpoints := er.getEndpoints()\n\treturn getStorageInfo(disks, endpoints)\n}\n\nfunc (er erasureObjects) getOnlineDisksWithHealing() (newDisks []StorageAPI, healing bool) {\n\tvar wg sync.WaitGroup\n\tdisks := er.getDisks()\n\tinfos := make([]DiskInfo, len(disks))\n\tfor _, i := range hashOrder(UTCNow().String(), len(disks)) {\n\t\ti := i\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\n\t\t\tdisk := disks[i-1]\n\n\t\t\tif disk == nil {\n\t\t\t\tinfos[i-1].Error = \"nil disk\"\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tdi, err := disk.DiskInfo(context.Background())\n\t\t\tif err != nil {\n\t\t\t\t\/\/ - Do not consume disks which are not reachable\n\t\t\t\t\/\/   unformatted or simply not accessible for some reason.\n\t\t\t\t\/\/\n\t\t\t\t\/\/\n\t\t\t\t\/\/ - Future: skip busy disks\n\t\t\t\tinfos[i-1].Error = err.Error()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tinfos[i-1] = di\n\t\t}()\n\t}\n\twg.Wait()\n\n\tfor i, info := range infos {\n\t\t\/\/ Check if one of the drives in the set is being healed.\n\t\t\/\/ this information is used by crawler to skip healing\n\t\t\/\/ this erasure set while it calculates the usage.\n\t\tif info.Healing || info.Error != \"\" {\n\t\t\thealing = true\n\t\t\tcontinue\n\t\t}\n\t\tnewDisks = append(newDisks, disks[i])\n\t}\n\n\treturn newDisks, healing\n}\n\n\/\/ CrawlAndGetDataUsage will start crawling buckets and send updated totals as they are traversed.\n\/\/ Updates are sent on a regular basis and the caller *must* consume them.\nfunc (er erasureObjects) crawlAndGetDataUsage(ctx context.Context, buckets []BucketInfo, bf *bloomFilter, updates chan<- dataUsageCache) error {\n\tif len(buckets) == 0 {\n\t\treturn nil\n\t}\n\n\t\/\/ Collect disks we can use.\n\tdisks, healing := er.getOnlineDisksWithHealing()\n\tif len(disks) == 0 {\n\t\tlogger.Info(color.Green(\"data-crawl:\") + \" all disks are offline or being healed, skipping crawl\")\n\t\treturn nil\n\t}\n\n\t\/\/ Collect disks for healing.\n\tallDisks := er.getDisks()\n\tallDiskIDs := make([]string, 0, len(allDisks))\n\tfor _, disk := range allDisks {\n\t\tif disk == OfflineDisk {\n\t\t\t\/\/ its possible that disk is OfflineDisk\n\t\t\tcontinue\n\t\t}\n\t\tid, _ := disk.GetDiskID()\n\t\tif id == \"\" {\n\t\t\t\/\/ its possible that disk is unformatted\n\t\t\t\/\/ or just went offline\n\t\t\tcontinue\n\t\t}\n\t\tallDiskIDs = append(allDiskIDs, id)\n\t}\n\n\t\/\/ Load bucket totals\n\toldCache := dataUsageCache{}\n\tif err := oldCache.load(ctx, er, dataUsageCacheName); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ New cache..\n\tcache := dataUsageCache{\n\t\tInfo: dataUsageCacheInfo{\n\t\t\tName:      dataUsageRoot,\n\t\t\tNextCycle: oldCache.Info.NextCycle,\n\t\t},\n\t\tCache: make(map[string]dataUsageEntry, len(oldCache.Cache)),\n\t}\n\tbloom := bf.bytes()\n\n\t\/\/ Put all buckets into channel.\n\tbucketCh := make(chan BucketInfo, len(buckets))\n\t\/\/ Add new buckets first\n\tfor _, b := range buckets {\n\t\tif oldCache.find(b.Name) == nil {\n\t\t\tbucketCh <- b\n\t\t}\n\t}\n\n\t\/\/ Add existing buckets.\n\tfor _, b := range buckets {\n\t\te := oldCache.find(b.Name)\n\t\tif e != nil {\n\t\t\tcache.replace(b.Name, dataUsageRoot, *e)\n\t\t\tbucketCh <- b\n\t\t}\n\t}\n\n\tclose(bucketCh)\n\tbucketResults := make(chan dataUsageEntryInfo, len(disks))\n\n\t\/\/ Start async collector\/saver.\n\t\/\/ This goroutine owns the cache.\n\tvar saverWg sync.WaitGroup\n\tsaverWg.Add(1)\n\tgo func() {\n\t\tconst updateTime = 30 * time.Second\n\t\tt := time.NewTicker(updateTime)\n\t\tdefer t.Stop()\n\t\tdefer saverWg.Done()\n\t\tvar lastSave time.Time\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\t\/\/ Return without saving.\n\t\t\t\treturn\n\t\t\tcase <-t.C:\n\t\t\t\tif cache.Info.LastUpdate.Equal(lastSave) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlogger.LogIf(ctx, cache.save(ctx, er, dataUsageCacheName))\n\t\t\t\tupdates <- cache.clone()\n\t\t\t\tlastSave = cache.Info.LastUpdate\n\t\t\tcase v, ok := <-bucketResults:\n\t\t\t\tif !ok {\n\t\t\t\t\t\/\/ Save final state...\n\t\t\t\t\tcache.Info.NextCycle++\n\t\t\t\t\tcache.Info.LastUpdate = time.Now()\n\t\t\t\t\tlogger.LogIf(ctx, cache.save(ctx, er, dataUsageCacheName))\n\t\t\t\t\tupdates <- cache\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcache.replace(v.Name, v.Parent, v.Entry)\n\t\t\t\tcache.Info.LastUpdate = time.Now()\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ Start one crawler per disk\n\tvar wg sync.WaitGroup\n\twg.Add(len(disks))\n\tfor i := range disks {\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\t\t\tdisk := disks[i]\n\n\t\t\tfor bucket := range bucketCh {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t}\n\n\t\t\t\t\/\/ Load cache for bucket\n\t\t\t\tcacheName := pathJoin(bucket.Name, dataUsageCacheName)\n\t\t\t\tcache := dataUsageCache{}\n\t\t\t\tlogger.LogIf(ctx, cache.load(ctx, er, cacheName))\n\t\t\t\tif cache.Info.Name == \"\" {\n\t\t\t\t\tcache.Info.Name = bucket.Name\n\t\t\t\t}\n\t\t\t\tcache.Info.BloomFilter = bloom\n\t\t\t\tcache.Info.SkipHealing = healing\n\t\t\t\tcache.Disks = allDiskIDs\n\t\t\t\tif cache.Info.Name != bucket.Name {\n\t\t\t\t\tlogger.LogIf(ctx, fmt.Errorf(\"cache name mismatch: %s != %s\", cache.Info.Name, bucket.Name))\n\t\t\t\t\tcache.Info = dataUsageCacheInfo{\n\t\t\t\t\t\tName:       bucket.Name,\n\t\t\t\t\t\tLastUpdate: time.Time{},\n\t\t\t\t\t\tNextCycle:  0,\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ Calc usage\n\t\t\t\tbefore := cache.Info.LastUpdate\n\t\t\t\tvar err error\n\t\t\t\tcache, err = disk.CrawlAndGetDataUsage(ctx, cache)\n\t\t\t\tcache.Info.BloomFilter = nil\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.LogIf(ctx, err)\n\t\t\t\t\tif cache.Info.LastUpdate.After(before) {\n\t\t\t\t\t\tlogger.LogIf(ctx, cache.save(ctx, er, cacheName))\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tvar root dataUsageEntry\n\t\t\t\tif r := cache.root(); r != nil {\n\t\t\t\t\troot = cache.flatten(*r)\n\t\t\t\t}\n\t\t\t\tbucketResults <- dataUsageEntryInfo{\n\t\t\t\t\tName:   cache.Info.Name,\n\t\t\t\t\tParent: dataUsageRoot,\n\t\t\t\t\tEntry:  root,\n\t\t\t\t}\n\t\t\t\t\/\/ Save cache\n\t\t\t\tlogger.LogIf(ctx, cache.save(ctx, er, cacheName))\n\t\t\t}\n\t\t}(i)\n\t}\n\twg.Wait()\n\tclose(bucketResults)\n\tsaverWg.Wait()\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/stts-se\/rbg2p\"\n\n\t\"github.com\/sergi\/go-diff\/diffmatchpatch\"\n)\n\nvar l = log.New(os.Stderr, \"\", 0)\n\nfunc print(input string, orth string, transes []string) {\n\tfmt.Printf(\"%s\\t%s\\n\", input, strings.Join(transes, \"  #  \"))\n}\n\ntype transResult struct {\n\torth    string\n\ttranses []string\n\tresult  bool\n}\n\nfunc transcribe(ruleSet rbg2p.RuleSet, orth string) transResult {\n\ttranses, err := ruleSet.Apply(orth)\n\tif err != nil {\n\t\tl.Printf(\"Couldn't transcribe '%s' : %s\", orth, err)\n\t\treturn transResult{orth: orth, transes: transes, result: false}\n\t}\n\treturn transResult{orth: orth, transes: transes, result: true}\n}\n\nvar removeStressAndBoundaries = regexp.MustCompile(\"[.\\\"%!~] *\")\n\nfunc cleanTransForDiff(t string) string {\n\tvar res = t\n\tres = removeStressAndBoundaries.ReplaceAllString(res, \"\")\n\t\/\/res = strings.Replace(res, \"'\", \"\", -1)\n\treturn res\n}\n\nfunc cleanTransForIJDiff(t string) string {\n\tvar res = t\n\tres = strings.Replace(res, \" i \", \" j \", -1)\n\treturn res\n}\n\nfunc compareForDiff(old []string, new []string) (string, bool) {\n\tfor i, s := range old {\n\t\told[i] = cleanTransForDiff(s)\n\t}\n\tfor i, s := range new {\n\t\tnew[i] = cleanTransForDiff(s)\n\t}\n\t\/\/ var oldIJ = []string{}\n\t\/\/ var newIJ = []string{}\n\t\/\/ for _, s := range old {\n\t\/\/ \toldIJ = append(oldIJ, cleanTransForIJDiff(s))\n\t\/\/ }\n\t\/\/ for _, s := range new {\n\t\/\/ \tnewIJ = append(newIJ, cleanTransForIJDiff(s))\n\t\/\/ }\n\tif reflect.DeepEqual(old, new) {\n\t\treturn \"ALL EQ\", true\n\t} else if old[0] == new[0] {\n\t\treturn \"#1 EQ\", false\n\t\t\/\/ } else if reflect.DeepEqual(oldIJ, newIJ) {\n\t\t\/\/ \treturn \"ALL EQ IJ\", false\n\t\t\/\/ } else if oldIJ[0] == newIJ[0] {\n\t\t\/\/ \treturn \"#1 EQ IJ\", false\n\t} else {\n\t\treturn \"DIFF\", false\n\t}\n}\n\nfunc main() {\n\n\tvar f = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)\n\tvar debug = f.Bool(\"debug\", false, \"print extra debug info (default: false)\")\n\tvar force = f.Bool(\"force\", false, \"print transcriptions even if errors are found (default: false)\")\n\tvar column = f.Int(\"column\", 0, \"only convert specified column (default: first field)\")\n\tvar quiet = f.Bool(\"quiet\", false, \"inhibit warnings (default: false)\")\n\tvar test = f.Bool(\"test\", false, \"test g2p against input file; orth <tab> trans (default: false)\")\n\tvar ssFile = f.String(\"symbolset\", \"\", \"use specified symbol set file for validating the symbols in the g2p rule set (default: none; overrides the g2p rule file's symbolset, if any)\")\n\tvar help = f.Bool(\"help\", false, \"print help message\")\n\n\tvar usage = `go run g2p.go <FLAGS> <G2P RULE FILE> <WORDS (FILES OR LIST OF WORDS)> (optional)\n\nFLAGS:\n   -force      bool    print transcriptions even if errors are found (default: false)\n   -debug      bool    print extra debug info (default: false)\n   -column     string  only convert specified column (default: first field)\n   -quiet      bool    inhibit warnings (default: false)\n   -test       bool    test g2p against input file; orth <tab> trans (default: false)\n   -symbolset  string  use specified symbol set file for validating the symbols in the g2p rule set (default: none)\n   -help       bool    print help message`\n\n\tf.Usage = func() {\n\t\tl.Printf(usage)\n\t}\n\n\tvar args = os.Args\n\tif strings.HasSuffix(args[0], \"g2p\") {\n\t\targs = args[1:] \/\/ remove first argument if it's the program name\n\t}\n\terr := f.Parse(args)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\targs = f.Args()\n\n\tif *help {\n\t\tl.Println(usage)\n\t\tos.Exit(1)\n\t}\n\n\tif len(args) < 1 {\n\t\tl.Println(usage)\n\t\tos.Exit(1)\n\t}\n\n\trbg2p.Debug = *debug\n\n\tg2pFile := args[0]\n\truleSet, err := rbg2p.LoadFile(g2pFile)\n\tif err != nil {\n\t\tl.Printf(\"couldn't load rule file %s : %s\", g2pFile, err)\n\t\tos.Exit(1)\n\t}\n\n\tif *ssFile != \"\" {\n\t\tphonemeSet, err := rbg2p.LoadPhonemeSetFile(*ssFile, ruleSet.PhonemeDelimiter)\n\t\tif err != nil {\n\t\t\tl.Printf(\"couldn't load symbol set : %s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\truleSet.PhonemeSet = phonemeSet\n\t}\n\n\thaltingError := false\n\tresult := ruleSet.Test()\n\tfor _, e := range result.Errors {\n\t\tl.Printf(\"ERROR: %v\\n\", e)\n\t}\n\tl.Printf(\"%d ERROR(S) FOR %s\\n\", len(result.Errors), g2pFile)\n\tif !*quiet {\n\t\tfor _, e := range result.Warnings {\n\t\t\tl.Printf(\"WARNING: %v\\n\", e)\n\t\t}\n\t}\n\tl.Printf(\"%d WARNING(S) FOR %s\\n\", len(result.Warnings), g2pFile)\n\tif len(result.Errors) > 0 {\n\t\thaltingError = true\n\t}\n\tif len(result.FailedTests) > 0 {\n\t\tfor _, e := range result.FailedTests {\n\t\t\tl.Printf(\"FAILED TEST: %v\\n\", e)\n\t\t}\n\t\tl.Printf(\"%d OF %d TESTS FAILED FOR %s\\n\", len(result.FailedTests), len(ruleSet.Tests), g2pFile)\n\t\thaltingError = true\n\t} else {\n\t\tl.Printf(\"ALL %d TESTS PASSED FOR %s\\n\", len(ruleSet.Tests), g2pFile)\n\t}\n\n\tif haltingError && !*force {\n\t\tos.Exit(1)\n\t}\n\n\tnTotal := 0\n\tnErrs := 0\n\tnTrans := 0\n\tnTests := 0\n\ttestRes := make(map[string]int)\n\tif *test {\n\t\tfmt.Println(\"ORTH\\tNEW TRANSES\\tOLD TRANSES\\tDIFFTAG\\t(DIFF)?\")\n\t}\n\tvar processString = func(s string) {\n\t\tnTotal = nTotal + 1\n\t\tfs := strings.Split(s, \"\\t\")\n\t\to := fs[*column]\n\t\tres := transcribe(ruleSet, o)\n\t\tif res.result || *force {\n\t\t\tnTrans = nTrans + 1\n\t\t\tif *test {\n\t\t\t\trefTranses := fs[(*column + 1):]\n\t\t\t\tnTests++\n\t\t\t\tinfo, _ := compareForDiff(res.transes, refTranses)\n\t\t\t\ttestRes[info]++\n\t\t\t\toutFs := []string{res.orth, strings.Join(res.transes, \" # \"), strings.Join(refTranses, \"#\"), info}\n\t\t\t\tif info == \"DIFF\" {\n\t\t\t\t\tdmp := diffmatchpatch.New()\n\t\t\t\t\tdiffs := dmp.DiffMain(outFs[1], outFs[2], false)\n\t\t\t\t\tdiffsOnly := []diffmatchpatch.Diff{}\n\t\t\t\t\tdiffsOnlyText := []string{}\n\t\t\t\t\tfor _, d := range diffs {\n\t\t\t\t\t\tif d.Type != diffmatchpatch.DiffEqual {\n\t\t\t\t\t\t\tdiffsOnly = append(diffsOnly, d)\n\t\t\t\t\t\t\tdiffsOnlyText = append(diffsOnlyText, d.Text)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\toutFs = append(outFs, dmp.DiffPrettyText(diffs))\n\t\t\t\t\toutFs = append(outFs, fmt.Sprintf(\"%v\", diffsOnly))\n\t\t\t\t\toutFs = append(outFs, strings.Join(diffsOnlyText, \"|\"))\n\t\t\t\t}\n\n\t\t\t\tfmt.Println(strings.Join(outFs, \"\\t\"))\n\t\t\t} else {\n\t\t\t\tprint(s, res.orth, res.transes)\n\t\t\t}\n\t\t}\n\t\tif !res.result {\n\t\t\tnErrs = nErrs + 1\n\t\t}\n\t}\n\n\tif len(args) > 1 {\n\t\tfor i := 1; i < len(args); i++ {\n\t\t\ts := args[i]\n\t\t\tif _, err := os.Stat(s); os.IsNotExist(err) {\n\t\t\t\tprocessString(s)\n\t\t\t\t\/\/ nTotal = nTotal + 1\n\t\t\t\t\/\/ res := transcribe(ruleSet, s)\n\t\t\t\t\/\/ if res.result || *force {\n\t\t\t\t\/\/ \tnTrans = nTrans + 1\n\t\t\t\t\/\/ \tfmt.Printf(\"%s\\t%s\\n\", s, strings.Join(res.transes, \"\\t\"))\n\t\t\t\t\/\/ }\n\t\t\t\t\/\/ if !res.result {\n\t\t\t\t\/\/ \tnErrs = nErrs + 1\n\t\t\t\t\/\/ }\n\t\t\t} else {\n\t\t\t\tfh, err := os.Open(filepath.Clean(s))\n\t\t\t\tif err != nil {\n\t\t\t\t\tl.Println(err)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t\tdefer fh.Close()\n\t\t\t\tsc := bufio.NewScanner(fh)\n\t\t\t\tfor sc.Scan() {\n\t\t\t\t\tif err := sc.Err(); err != nil {\n\t\t\t\t\t\tl.Println(err)\n\t\t\t\t\t\tos.Exit(1)\n\t\t\t\t\t}\n\t\t\t\t\tline := sc.Text()\n\t\t\t\t\tif strings.TrimSpace(line) == \"\" {\n\t\t\t\t\t\tl.Println(\"Skipping empty line\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif strings.HasPrefix(strings.TrimSpace(line), \"#\") {\n\t\t\t\t\t\tl.Println(\"Skipping line \" + line)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tprocessString(line)\n\t\t\t\t\t\/\/ \tnTotal = nTotal + 1\n\t\t\t\t\t\/\/ \tfs := strings.Split(line, \"\\t\")\n\t\t\t\t\t\/\/ \to, refTranses := fs[0], fs[1:]\n\t\t\t\t\t\/\/ \tres := transcribe(ruleSet, o)\n\t\t\t\t\t\/\/ \tif res.result || *force {\n\t\t\t\t\t\/\/ \t\tnTrans = nTrans + 1\n\t\t\t\t\t\/\/ \t\tif *test {\n\t\t\t\t\t\/\/ \t\t\tnTests++\n\t\t\t\t\t\/\/ \t\t\tinfo, _ := compareForDiff(res.transes, refTranses)\n\t\t\t\t\t\/\/ \t\t\ttestRes[info]++\n\t\t\t\t\t\/\/ \t\t\toutFs := []string{res.orth, strings.Join(res.transes, \" # \"), strings.Join(refTranses, \"#\"), info}\n\t\t\t\t\t\/\/ \t\t\tif info == \"DIFF\" {\n\t\t\t\t\t\/\/ \t\t\t\tdmp := diffmatchpatch.New()\n\t\t\t\t\t\/\/ \t\t\t\tdiffs := dmp.DiffMain(outFs[1], outFs[2], false)\n\t\t\t\t\t\/\/ \t\t\t\tdiffsOnly := []diffmatchpatch.Diff{}\n\t\t\t\t\t\/\/ \t\t\t\tdiffsOnlyText := []string{}\n\t\t\t\t\t\/\/ \t\t\t\tfor _, d := range diffs {\n\t\t\t\t\t\/\/ \t\t\t\t\tif d.Type != diffmatchpatch.DiffEqual {\n\t\t\t\t\t\/\/ \t\t\t\t\t\tdiffsOnly = append(diffsOnly, d)\n\t\t\t\t\t\/\/ \t\t\t\t\t\tdiffsOnlyText = append(diffsOnlyText, d.Text)\n\t\t\t\t\t\/\/ \t\t\t\t\t}\n\t\t\t\t\t\/\/ \t\t\t\t}\n\t\t\t\t\t\/\/ \t\t\t\toutFs = append(outFs, dmp.DiffPrettyText(diffs))\n\t\t\t\t\t\/\/ \t\t\t\toutFs = append(outFs, fmt.Sprintf(\"%v\", diffsOnly))\n\t\t\t\t\t\/\/ \t\t\t\toutFs = append(outFs, strings.Join(diffsOnlyText, \"|\"))\n\t\t\t\t\t\/\/ \t\t\t}\n\n\t\t\t\t\t\/\/ \t\t\tfmt.Println(strings.Join(outFs, \"\\t\"))\n\t\t\t\t\t\/\/ \t\t} else {\n\t\t\t\t\t\/\/ \t\t\tprint(res.orth, res.transes)\n\t\t\t\t\t\/\/ \t\t}\n\t\t\t\t\t\/\/ \t}\n\t\t\t\t\t\/\/ \tif !res.result {\n\t\t\t\t\t\/\/ \t\tnErrs = nErrs + 1\n\t\t\t\t\t\/\/ \t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, \"Reading input from stdin...\\n\")\n\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif strings.TrimSpace(line) == \"\" {\n\t\t\t\tl.Println(\"Skipping empty line\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.HasPrefix(strings.TrimSpace(line), \"#\") {\n\t\t\t\tl.Println(\"Skipping line \" + line)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tprocessString(line)\n\t\t}\n\t}\n\tl.Printf(\"%-18s: % 7d\", \"TOTAL INPUT\", nTotal)\n\tl.Printf(\"%-18s: % 7d\", \"ERRORS\", nErrs)\n\tl.Printf(\"%-18s: % 7d\", \"TRANSCRIBED\", nTrans)\n\tif *test {\n\t\tl.Printf(\"%-18s: % 7d\", \"TESTED\", nTests)\n\t\tvar keys []string\n\t\tfor k := range testRes {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Strings(keys)\n\t\tfor _, tag := range keys {\n\t\t\tfreq := testRes[tag]\n\t\t\ts := \" > TEST \" + tag\n\t\t\tl.Printf(\"%-18s: % 7d\", s, freq)\n\t\t}\n\t}\n}\n<commit_msg>g2p.go removing stress is now optional when using the -test switch (-testremovestress)<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/stts-se\/rbg2p\"\n\n\t\"github.com\/sergi\/go-diff\/diffmatchpatch\"\n)\n\nvar l = log.New(os.Stderr, \"\", 0)\n\nfunc print(input string, orth string, transes []string) {\n\tfmt.Printf(\"%s\\t%s\\n\", input, strings.Join(transes, \"  #  \"))\n}\n\ntype transResult struct {\n\torth    string\n\ttranses []string\n\tresult  bool\n}\n\nfunc transcribe(ruleSet rbg2p.RuleSet, orth string) transResult {\n\ttranses, err := ruleSet.Apply(orth)\n\tif err != nil {\n\t\tl.Printf(\"Couldn't transcribe '%s' : %s\", orth, err)\n\t\treturn transResult{orth: orth, transes: transes, result: false}\n\t}\n\treturn transResult{orth: orth, transes: transes, result: true}\n}\n\nvar removeBoundariesRE = regexp.MustCompile(`[.!~] *`)\nvar removeStressRE = regexp.MustCompile(`[%\"] *`)\nvar removeStress *bool\n\nfunc cleanTransForDiff(t string) string {\n\tvar res = t\n\tres = removeBoundariesRE.ReplaceAllString(res, \"\")\n\tif *removeStress {\n\t\tres = removeStressRE.ReplaceAllString(res, \"\")\n\t}\n\t\/\/res = strings.Replace(res, \"'\", \"\", -1)\n\treturn res\n}\n\nfunc cleanTransForIJDiff(t string) string {\n\tvar res = t\n\tres = strings.Replace(res, \" i \", \" j \", -1)\n\treturn res\n}\n\nfunc compareForDiff(old []string, new []string) (string, bool) {\n\tfor i, s := range old {\n\t\told[i] = cleanTransForDiff(s)\n\t}\n\tfor i, s := range new {\n\t\tnew[i] = cleanTransForDiff(s)\n\t}\n\t\/\/ var oldIJ = []string{}\n\t\/\/ var newIJ = []string{}\n\t\/\/ for _, s := range old {\n\t\/\/ \toldIJ = append(oldIJ, cleanTransForIJDiff(s))\n\t\/\/ }\n\t\/\/ for _, s := range new {\n\t\/\/ \tnewIJ = append(newIJ, cleanTransForIJDiff(s))\n\t\/\/ }\n\tif reflect.DeepEqual(old, new) {\n\t\treturn \"ALL EQ\", true\n\t} else if old[0] == new[0] {\n\t\treturn \"#1 EQ\", false\n\t\t\/\/ } else if reflect.DeepEqual(oldIJ, newIJ) {\n\t\t\/\/ \treturn \"ALL EQ IJ\", false\n\t\t\/\/ } else if oldIJ[0] == newIJ[0] {\n\t\t\/\/ \treturn \"#1 EQ IJ\", false\n\t} else {\n\t\treturn \"DIFF\", false\n\t}\n}\n\nfunc main() {\n\n\tvar f = flag.NewFlagSet(os.Args[0], flag.ContinueOnError)\n\tvar debug = f.Bool(\"debug\", false, \"print extra debug info (default: false)\")\n\tvar force = f.Bool(\"force\", false, \"print transcriptions even if errors are found (default: false)\")\n\tvar column = f.Int(\"column\", 0, \"only convert specified column (default: first field)\")\n\tvar quiet = f.Bool(\"quiet\", false, \"inhibit warnings (default: false)\")\n\tvar test = f.Bool(\"test\", false, \"test g2p against input file; orth <tab> trans (default: false)\")\n\tremoveStress = f.Bool(\"testremovestress\", false, \"remove stress when comparing using the -test switch (default: false)\")\n\tvar ssFile = f.String(\"symbolset\", \"\", \"use specified symbol set file for validating the symbols in the g2p rule set (default: none; overrides the g2p rule file's symbolset, if any)\")\n\tvar help = f.Bool(\"help\", false, \"print help message\")\n\n\tvar usage = `go run g2p.go <FLAGS> <G2P RULE FILE> <WORDS (FILES OR LIST OF WORDS)> (optional)\n\nFLAGS:\n   -force      bool    print transcriptions even if errors are found (default: false)\n   -debug      bool    print extra debug info (default: false)\n   -column     string  only convert specified column (default: first field)\n   -quiet      bool    inhibit warnings (default: false)\n   -test       bool    test g2p against input file; orth <tab> trans (default: false)\n   -testremovestress bool remove stress when comparing using the -test switch (default: false)\n   -symbolset  string  use specified symbol set file for validating the symbols in the g2p rule set (default: none)\n   -help       bool    print help message`\n\n\tf.Usage = func() {\n\t\tl.Printf(usage)\n\t}\n\n\tvar args = os.Args\n\tif strings.HasSuffix(args[0], \"g2p\") {\n\t\targs = args[1:] \/\/ remove first argument if it's the program name\n\t}\n\terr := f.Parse(args)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\targs = f.Args()\n\n\tif *help {\n\t\tl.Println(usage)\n\t\tos.Exit(1)\n\t}\n\n\tif len(args) < 1 {\n\t\tl.Println(usage)\n\t\tos.Exit(1)\n\t}\n\n\trbg2p.Debug = *debug\n\n\tg2pFile := args[0]\n\truleSet, err := rbg2p.LoadFile(g2pFile)\n\tif err != nil {\n\t\tl.Printf(\"couldn't load rule file %s : %s\", g2pFile, err)\n\t\tos.Exit(1)\n\t}\n\n\tif *ssFile != \"\" {\n\t\tphonemeSet, err := rbg2p.LoadPhonemeSetFile(*ssFile, ruleSet.PhonemeDelimiter)\n\t\tif err != nil {\n\t\t\tl.Printf(\"couldn't load symbol set : %s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\truleSet.PhonemeSet = phonemeSet\n\t}\n\n\thaltingError := false\n\tresult := ruleSet.Test()\n\tfor _, e := range result.Errors {\n\t\tl.Printf(\"ERROR: %v\\n\", e)\n\t}\n\tl.Printf(\"%d ERROR(S) FOR %s\\n\", len(result.Errors), g2pFile)\n\tif !*quiet {\n\t\tfor _, e := range result.Warnings {\n\t\t\tl.Printf(\"WARNING: %v\\n\", e)\n\t\t}\n\t}\n\tl.Printf(\"%d WARNING(S) FOR %s\\n\", len(result.Warnings), g2pFile)\n\tif len(result.Errors) > 0 {\n\t\thaltingError = true\n\t}\n\tif len(result.FailedTests) > 0 {\n\t\tfor _, e := range result.FailedTests {\n\t\t\tl.Printf(\"FAILED TEST: %v\\n\", e)\n\t\t}\n\t\tl.Printf(\"%d OF %d TESTS FAILED FOR %s\\n\", len(result.FailedTests), len(ruleSet.Tests), g2pFile)\n\t\thaltingError = true\n\t} else {\n\t\tl.Printf(\"ALL %d TESTS PASSED FOR %s\\n\", len(ruleSet.Tests), g2pFile)\n\t}\n\n\tif haltingError && !*force {\n\t\tos.Exit(1)\n\t}\n\n\tnTotal := 0\n\tnErrs := 0\n\tnTrans := 0\n\tnTests := 0\n\ttestRes := make(map[string]int)\n\tif *test {\n\t\tfmt.Println(\"ORTH\\tNEW TRANSES\\tOLD TRANSES\\tDIFFTAG\\t(DIFF)?\")\n\t}\n\tvar processString = func(s string) {\n\t\tnTotal = nTotal + 1\n\t\tfs := strings.Split(s, \"\\t\")\n\t\to := fs[*column]\n\t\tres := transcribe(ruleSet, o)\n\t\tif res.result || *force {\n\t\t\tnTrans = nTrans + 1\n\t\t\tif *test {\n\t\t\t\trefTranses := fs[(*column + 1):]\n\t\t\t\tnTests++\n\t\t\t\tinfo, _ := compareForDiff(res.transes, refTranses)\n\t\t\t\ttestRes[info]++\n\t\t\t\toutFs := []string{res.orth, strings.Join(res.transes, \" # \"), strings.Join(refTranses, \"#\"), info}\n\t\t\t\tif info == \"DIFF\" {\n\t\t\t\t\tdmp := diffmatchpatch.New()\n\t\t\t\t\tdiffs := dmp.DiffMain(outFs[1], outFs[2], false)\n\t\t\t\t\tdiffsOnly := []diffmatchpatch.Diff{}\n\t\t\t\t\tdiffsOnlyText := []string{}\n\t\t\t\t\tfor _, d := range diffs {\n\t\t\t\t\t\tif d.Type != diffmatchpatch.DiffEqual {\n\t\t\t\t\t\t\tdiffsOnly = append(diffsOnly, d)\n\t\t\t\t\t\t\tdiffsOnlyText = append(diffsOnlyText, d.Text)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\toutFs = append(outFs, dmp.DiffPrettyText(diffs))\n\t\t\t\t\toutFs = append(outFs, fmt.Sprintf(\"%v\", diffsOnly))\n\t\t\t\t\toutFs = append(outFs, strings.Join(diffsOnlyText, \"|\"))\n\t\t\t\t}\n\n\t\t\t\tfmt.Println(strings.Join(outFs, \"\\t\"))\n\t\t\t} else {\n\t\t\t\tprint(s, res.orth, res.transes)\n\t\t\t}\n\t\t}\n\t\tif !res.result {\n\t\t\tnErrs = nErrs + 1\n\t\t}\n\t}\n\n\tif len(args) > 1 {\n\t\tfor i := 1; i < len(args); i++ {\n\t\t\ts := args[i]\n\t\t\tif _, err := os.Stat(s); os.IsNotExist(err) {\n\t\t\t\tprocessString(s)\n\t\t\t\t\/\/ nTotal = nTotal + 1\n\t\t\t\t\/\/ res := transcribe(ruleSet, s)\n\t\t\t\t\/\/ if res.result || *force {\n\t\t\t\t\/\/ \tnTrans = nTrans + 1\n\t\t\t\t\/\/ \tfmt.Printf(\"%s\\t%s\\n\", s, strings.Join(res.transes, \"\\t\"))\n\t\t\t\t\/\/ }\n\t\t\t\t\/\/ if !res.result {\n\t\t\t\t\/\/ \tnErrs = nErrs + 1\n\t\t\t\t\/\/ }\n\t\t\t} else {\n\t\t\t\tfh, err := os.Open(filepath.Clean(s))\n\t\t\t\tif err != nil {\n\t\t\t\t\tl.Println(err)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t\tdefer fh.Close()\n\t\t\t\tsc := bufio.NewScanner(fh)\n\t\t\t\tfor sc.Scan() {\n\t\t\t\t\tif err := sc.Err(); err != nil {\n\t\t\t\t\t\tl.Println(err)\n\t\t\t\t\t\tos.Exit(1)\n\t\t\t\t\t}\n\t\t\t\t\tline := sc.Text()\n\t\t\t\t\tif strings.TrimSpace(line) == \"\" {\n\t\t\t\t\t\tl.Println(\"Skipping empty line\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif strings.HasPrefix(strings.TrimSpace(line), \"#\") {\n\t\t\t\t\t\tl.Println(\"Skipping line \" + line)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tprocessString(line)\n\t\t\t\t\t\/\/ \tnTotal = nTotal + 1\n\t\t\t\t\t\/\/ \tfs := strings.Split(line, \"\\t\")\n\t\t\t\t\t\/\/ \to, refTranses := fs[0], fs[1:]\n\t\t\t\t\t\/\/ \tres := transcribe(ruleSet, o)\n\t\t\t\t\t\/\/ \tif res.result || *force {\n\t\t\t\t\t\/\/ \t\tnTrans = nTrans + 1\n\t\t\t\t\t\/\/ \t\tif *test {\n\t\t\t\t\t\/\/ \t\t\tnTests++\n\t\t\t\t\t\/\/ \t\t\tinfo, _ := compareForDiff(res.transes, refTranses)\n\t\t\t\t\t\/\/ \t\t\ttestRes[info]++\n\t\t\t\t\t\/\/ \t\t\toutFs := []string{res.orth, strings.Join(res.transes, \" # \"), strings.Join(refTranses, \"#\"), info}\n\t\t\t\t\t\/\/ \t\t\tif info == \"DIFF\" {\n\t\t\t\t\t\/\/ \t\t\t\tdmp := diffmatchpatch.New()\n\t\t\t\t\t\/\/ \t\t\t\tdiffs := dmp.DiffMain(outFs[1], outFs[2], false)\n\t\t\t\t\t\/\/ \t\t\t\tdiffsOnly := []diffmatchpatch.Diff{}\n\t\t\t\t\t\/\/ \t\t\t\tdiffsOnlyText := []string{}\n\t\t\t\t\t\/\/ \t\t\t\tfor _, d := range diffs {\n\t\t\t\t\t\/\/ \t\t\t\t\tif d.Type != diffmatchpatch.DiffEqual {\n\t\t\t\t\t\/\/ \t\t\t\t\t\tdiffsOnly = append(diffsOnly, d)\n\t\t\t\t\t\/\/ \t\t\t\t\t\tdiffsOnlyText = append(diffsOnlyText, d.Text)\n\t\t\t\t\t\/\/ \t\t\t\t\t}\n\t\t\t\t\t\/\/ \t\t\t\t}\n\t\t\t\t\t\/\/ \t\t\t\toutFs = append(outFs, dmp.DiffPrettyText(diffs))\n\t\t\t\t\t\/\/ \t\t\t\toutFs = append(outFs, fmt.Sprintf(\"%v\", diffsOnly))\n\t\t\t\t\t\/\/ \t\t\t\toutFs = append(outFs, strings.Join(diffsOnlyText, \"|\"))\n\t\t\t\t\t\/\/ \t\t\t}\n\n\t\t\t\t\t\/\/ \t\t\tfmt.Println(strings.Join(outFs, \"\\t\"))\n\t\t\t\t\t\/\/ \t\t} else {\n\t\t\t\t\t\/\/ \t\t\tprint(res.orth, res.transes)\n\t\t\t\t\t\/\/ \t\t}\n\t\t\t\t\t\/\/ \t}\n\t\t\t\t\t\/\/ \tif !res.result {\n\t\t\t\t\t\/\/ \t\tnErrs = nErrs + 1\n\t\t\t\t\t\/\/ \t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfmt.Fprintf(os.Stderr, \"Reading input from stdin...\\n\")\n\t\tscanner := bufio.NewScanner(os.Stdin)\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif strings.TrimSpace(line) == \"\" {\n\t\t\t\tl.Println(\"Skipping empty line\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.HasPrefix(strings.TrimSpace(line), \"#\") {\n\t\t\t\tl.Println(\"Skipping line \" + line)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tprocessString(line)\n\t\t}\n\t}\n\tl.Printf(\"%-18s: % 7d\", \"TOTAL INPUT\", nTotal)\n\tl.Printf(\"%-18s: % 7d\", \"ERRORS\", nErrs)\n\tl.Printf(\"%-18s: % 7d\", \"TRANSCRIBED\", nTrans)\n\tif *test {\n\t\tl.Printf(\"%-18s: % 7d\", \"TESTED\", nTests)\n\t\tvar keys []string\n\t\tfor k := range testRes {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Strings(keys)\n\t\tfor _, tag := range keys {\n\t\t\tfreq := testRes[tag]\n\t\t\ts := \" > TEST \" + tag\n\t\t\tl.Printf(\"%-18s: % 7d\", s, freq)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"github.com\/open-falcon\/falcon-plus\/g\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar Monitor = &cobra.Command{\n\tUse:   \"monitor [Module ...]\",\n\tShort: \"Display an Open-Falcon module's log\",\n\tLong: `\nDisplay the log of the specified Open-Falcon module.\nA module represents a single node in a cluster.\nModules:\n  ` + strings.Join(g.AllModulesInOrder, \" \"),\n\tRunE: monitor,\n}\n\nfunc checkMonReq(name string) error {\n\tif !g.HasModule(name) {\n\t\treturn fmt.Errorf(\"%s doesn't exist\", name)\n\t}\n\n\tif !g.HasLogfile(name) {\n\t\tr := g.Rel(g.Cfg(name))\n\t\treturn fmt.Errorf(\"expect logfile: %s\", r)\n\t}\n\n\treturn nil\n}\n\nfunc monitor(c *cobra.Command, args []string) error {\n\tif len(args) < 1 {\n\t\treturn c.Usage()\n\t}\n\tvar tailArgs []string = []string{\"-f\"}\n\tfor _,moduleName := range args {\n\t\tif err := checkMonReq(moduleName); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttailArgs = append(tailArgs, g.LogPath(moduleName))\n\t}\n\tcmd := exec.Command(\"tail\", tailArgs...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}\n<commit_msg>code fmt check error fix<commit_after>package cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"github.com\/open-falcon\/falcon-plus\/g\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar Monitor = &cobra.Command{\n\tUse:   \"monitor [Module ...]\",\n\tShort: \"Display an Open-Falcon module's log\",\n\tLong: `\nDisplay the log of the specified Open-Falcon module.\nA module represents a single node in a cluster.\nModules:\n  ` + strings.Join(g.AllModulesInOrder, \" \"),\n\tRunE: monitor,\n}\n\nfunc checkMonReq(name string) error {\n\tif !g.HasModule(name) {\n\t\treturn fmt.Errorf(\"%s doesn't exist\", name)\n\t}\n\n\tif !g.HasLogfile(name) {\n\t\tr := g.Rel(g.Cfg(name))\n\t\treturn fmt.Errorf(\"expect logfile: %s\", r)\n\t}\n\n\treturn nil\n}\n\nfunc monitor(c *cobra.Command, args []string) error {\n\tif len(args) < 1 {\n\t\treturn c.Usage()\n\t}\n\tvar tailArgs []string = []string{\"-f\"}\n\tfor _, moduleName := range args {\n\t\tif err := checkMonReq(moduleName); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttailArgs = append(tailArgs, g.LogPath(moduleName))\n\t}\n\tcmd := exec.Command(\"tail\", tailArgs...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd.Run()\n}\n<|endoftext|>"}
{"text":"<commit_before>package metric\n\nimport (\n\t\"fmt\"\n\t\"github.com\/Knetic\/govaluate\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/soniah\/gosnmp\"\n\t\"github.com\/toni-moreno\/snmpcollector\/pkg\/config\"\n\t\"github.com\/toni-moreno\/snmpcollector\/pkg\/data\/measurement\/filter\"\n\t\"github.com\/toni-moreno\/snmpcollector\/pkg\/data\/snmp\"\n\t\"math\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar (\n\tconfDir string              \/\/Needed to get File Filters data\n\tdbc     *config.DatabaseCfg \/\/Needed to get Custom Filter  data\n)\n\n\/\/ SetConfDir  enable load File Filters from anywhere in the our FS.\nfunc SetConfDir(dir string) {\n\tconfDir = dir\n}\n\n\/\/ SetDB load database config to load data if needed (used in filters)\nfunc SetDB(db *config.DatabaseCfg) {\n\tdbc = db\n}\n\nconst (\n\tNeverReport     = 0\n\tAlwaysReport    = 1\n\tOnNonZeroReport = 2\n\tOnChangedReport = 3\n)\n\n\/\/SnmpMetric type to metric runtime\ntype SnmpMetric struct {\n\tcfg         *config.SnmpMetricCfg\n\tID          string\n\tCookedValue interface{}\n\tCurValue    interface{}\n\tLastValue   interface{}\n\tCurTime     time.Time\n\tLastTime    time.Time\n\tElapsedTime float64\n\tCompute     func(arg ...interface{})                `json:\"-\"`\n\tScale       func()                                  `json:\"-\"`\n\tSetRawData  func(pdu gosnmp.SnmpPDU, now time.Time) `json:\"-\"`\n\tRealOID     string\n\tReport      int \/\/if false this metric won't be sent to the ouput buffer (is just taken as a coomputed input for other metrics)\n\t\/\/for STRINGPARSER\n\tre   *regexp.Regexp\n\texpr *govaluate.EvaluableExpression\n\t\/\/for CONDITIONEVAL\n\tcondflt filter.Filter\n\t\/\/ Logger\n\tlog *logrus.Logger\n}\n\n\/\/ GetDataSrcType get needed data\nfunc (s *SnmpMetric) GetDataSrcType() string {\n\treturn s.cfg.DataSrcType\n}\n\n\/\/ PrintDebugCfg helps users get data about metric configuration\nfunc (s *SnmpMetric) PrintDebugCfg() {\n\ts.log.Debugf(\"DEBUG METRIC  CONFIG %+v\", s.cfg)\n}\n\n\/\/ IsTag needed to generate Influx measurements\nfunc (s *SnmpMetric) IsTag() bool {\n\treturn s.cfg.IsTag\n}\n\n\/\/ GetFieldName  needed to generate Influx measurements\nfunc (s *SnmpMetric) GetFieldName() string {\n\treturn s.cfg.FieldName\n}\n\n\/\/ New constructor\nfunc New(c *config.SnmpMetricCfg) (*SnmpMetric, error) {\n\tmetric := &SnmpMetric{}\n\terr := metric.Init(c)\n\treturn metric, err\n}\n\nfunc NewWithLog(c *config.SnmpMetricCfg, l *logrus.Logger) (*SnmpMetric, error) {\n\tmetric := &SnmpMetric{log: l}\n\terr := metric.Init(c)\n\treturn metric, err\n}\n\nfunc (s *SnmpMetric) SetLogger(l *logrus.Logger) {\n\ts.log = l\n}\n\nfunc (s *SnmpMetric) Init(c *config.SnmpMetricCfg) error {\n\tif c == nil {\n\t\treturn fmt.Errorf(\"Error on initialice device, configuration struct is nil\")\n\t}\n\ts.cfg = c\n\ts.RealOID = c.BaseOID\n\ts.ID = s.cfg.ID\n\tif s.cfg.Scale != 0.0 || s.cfg.Shift != 0.0 {\n\t\ts.Scale = func() {\n\t\t\ts.CookedValue = (s.cfg.Scale * float64(s.CookedValue.(float64))) + s.cfg.Shift\n\t\t}\n\t} else {\n\t\ts.Scale = func() {\n\t\t}\n\t}\n\tswitch s.cfg.DataSrcType {\n\tcase \"CONDITIONEVAL\":\n\t\t\/\/select\n\t\tcond, err := dbc.GetOidConditionCfgByID(s.cfg.ExtraData)\n\t\tif err != nil {\n\t\t\ts.log.Errorf(\"Error getting CONDITIONEVAL [id: %s ] data : %s\", s.cfg.ExtraData, err)\n\t\t}\n\t\t\/\/get Regexp\n\t\ts.condflt = filter.NewOidFilter(cond.OIDCond, cond.CondType, cond.CondValue, s.log)\n\n\t\ts.Compute = func(arg ...interface{}) {\n\t\t\t\/\/walk := arg[0].(func(string, gosnmp.WalkFunc) error)\n\t\t\t\/\/err := s.condflt.Init(walk)\n\t\t\ts.condflt.Init(arg...)\n\t\t\ts.condflt.Update()\n\t\t\ts.CookedValue = s.condflt.Count()\n\t\t\ts.CurTime = time.Now()\n\t\t\ts.Scale()\n\t\t}\n\t\t\/\/Sign\n\t\t\/\/set Process Data\n\tcase \"TIMETICKS\": \/\/Cooked TimeTicks\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\tval := snmp.PduVal2Int64(pdu)\n\t\t\ts.CookedValue = float64(val \/ 100) \/\/now data in secoonds\n\t\t\ts.CurTime = now\n\t\t\ts.Scale()\n\t\t}\n\n\t\t\/\/Signed Integers\n\tcase \"INTEGER\", \"Integer32\":\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\tval := snmp.PduVal2Int64(pdu)\n\t\t\ts.CookedValue = float64(val)\n\t\t\ts.CurTime = now\n\t\t\ts.Scale()\n\t\t}\n\t\t\/\/Unsigned Integers\n\tcase \"Counter32\", \"Gauge32\", \"Counter64\", \"TimeTicks\", \"UInteger32\", \"Unsigned32\":\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\tval := snmp.PduVal2UInt64(pdu)\n\t\t\ts.CookedValue = float64(val)\n\t\t\ts.CurTime = now\n\t\t\ts.Scale()\n\t\t}\n\tcase \"COUNTER32\": \/\/Increment computed\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\t\/\/first time only set values and reassign itself to the complete method this will avoi to send invalid data\n\t\t\tval := snmp.PduVal2UInt64(pdu)\n\t\t\ts.CurValue = val\n\t\t\ts.CurTime = now\n\t\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\t\tval := snmp.PduVal2UInt64(pdu)\n\t\t\t\ts.LastTime = s.CurTime\n\t\t\t\ts.LastValue = s.CurValue\n\t\t\t\ts.CurValue = val\n\t\t\t\ts.CurTime = now\n\t\t\t\ts.Compute()\n\t\t\t\ts.Scale()\n\t\t\t}\n\t\t}\n\t\tif s.cfg.GetRate == true {\n\t\t\ts.Compute = func(arg ...interface{}) {\n\t\t\t\ts.ElapsedTime = s.CurTime.Sub(s.LastTime).Seconds()\n\t\t\t\tif s.CurValue.(uint64) < s.LastValue.(uint64) {\n\t\t\t\t\ts.CookedValue = float64(math.MaxInt32-s.LastValue.(uint64)+s.CurValue.(uint64)) \/ s.ElapsedTime\n\t\t\t\t} else {\n\t\t\t\t\ts.CookedValue = float64(s.CurValue.(uint64)-s.LastValue.(uint64)) \/ s.ElapsedTime\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\ts.Compute = func(arg ...interface{}) {\n\t\t\t\ts.ElapsedTime = s.CurTime.Sub(s.LastTime).Seconds()\n\t\t\t\tif s.CurValue.(uint64) < s.LastValue.(uint64) {\n\t\t\t\t\ts.CookedValue = float64(math.MaxInt32 - s.LastValue.(uint64) + s.CurValue.(uint64))\n\t\t\t\t} else {\n\t\t\t\t\ts.CookedValue = float64(s.CurValue.(uint64) - s.LastValue.(uint64))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase \"COUNTER64\": \/\/Increment computed\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\t\/\/log.Debugf(\"========================================>COUNTER64: first time :%s \", s.RealOID)\n\t\t\t\/\/first time only set values and reassign itself to the complete method\n\t\t\tval := snmp.PduVal2UInt64(pdu)\n\t\t\ts.CurValue = val\n\t\t\ts.CurTime = now\n\t\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\t\t\/\/log.Debugf(\"========================================>COUNTER64: the other time:%s\", s.RealOID)\n\t\t\t\tval := snmp.PduVal2UInt64(pdu)\n\t\t\t\ts.LastTime = s.CurTime\n\t\t\t\ts.LastValue = s.CurValue\n\t\t\t\ts.CurValue = val\n\t\t\t\ts.CurTime = now\n\t\t\t\ts.Compute()\n\t\t\t\ts.Scale()\n\t\t\t}\n\t\t}\n\t\tif s.cfg.GetRate == true {\n\t\t\ts.Compute = func(arg ...interface{}) {\n\t\t\t\ts.ElapsedTime = s.CurTime.Sub(s.LastTime).Seconds()\n\t\t\t\t\/\/duration := s.CurTime.Sub(s.LastTime)\n\t\t\t\tif s.CurValue.(uint64) < s.LastValue.(uint64) {\n\t\t\t\t\ts.CookedValue = float64(math.MaxInt64-s.LastValue.(uint64)+s.CurValue.(uint64)) \/ s.ElapsedTime\n\t\t\t\t} else {\n\t\t\t\t\ts.CookedValue = float64(s.CurValue.(uint64)-s.LastValue.(uint64)) \/ s.ElapsedTime\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\ts.Compute = func(arg ...interface{}) {\n\t\t\t\ts.ElapsedTime = s.CurTime.Sub(s.LastTime).Seconds()\n\t\t\t\tif s.CurValue.(uint64) < s.LastValue.(uint64) {\n\t\t\t\t\ts.CookedValue = float64(math.MaxInt64 - s.LastValue.(uint64) + s.CurValue.(uint64))\n\t\t\t\t} else {\n\t\t\t\t\ts.CookedValue = float64(s.CurValue.(uint64) - s.LastValue.(uint64))\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\tcase \"OCTETSTRING\":\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\ts.CookedValue = snmp.PduVal2str(pdu)\n\t\t\ts.CurTime = now\n\t\t}\n\tcase \"IpAddress\":\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\ts.CookedValue, _ = snmp.PduVal2IPaddr(pdu)\n\t\t\ts.CurTime = now\n\t\t}\n\tcase \"HWADDR\":\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\ts.CookedValue, _ = snmp.PduVal2Hwaddr(pdu)\n\t\t\ts.CurTime = now\n\t\t}\n\tcase \"STRINGPARSER\":\n\t\t\/\/get Regexp\n\t\tre, err := regexp.Compile(s.cfg.ExtraData)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error on initialice STRINGPARSER, invalind Regular Expression : %s\", s.cfg.ExtraData)\n\t\t}\n\t\ts.re = re\n\t\t\/\/set Process Data\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\tstr := snmp.PduVal2str(pdu)\n\t\t\tretarray := s.re.FindStringSubmatch(str)\n\t\t\tif len(retarray) < 2 {\n\t\t\t\ts.log.Warnf(\"Error for metric [%s] parsing REGEXG [%s] on string [%s] without capturing group\", s.cfg.ID, s.cfg.ExtraData, str)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/retarray[0] contains full string\n\t\t\tif len(retarray[1]) == 0 {\n\t\t\t\ts.log.Warnf(\"Error for metric [%s] parsing REGEXG [%s] on string [%s] cause  void capturing group\", s.cfg.ID, s.cfg.ExtraData, str)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvalue, err := strconv.ParseFloat(retarray[1], 64)\n\t\t\tif err != nil {\n\t\t\t\ts.log.Warnf(\"Error parsing float for metric %s : error: %s\", s.cfg.ID, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\ts.CookedValue = value\n\t\t\ts.CurTime = now\n\t\t\ts.Scale()\n\t\t}\n\tcase \"STRINGEVAL\":\n\n\t\texpression, err := govaluate.NewEvaluableExpression(s.cfg.ExtraData)\n\t\tif err != nil {\n\t\t\ts.log.Errorf(\"Error on initialice STRINGEVAL, evaluation : %s : ERROR : %s\", s.cfg.ExtraData, err)\n\t\t\treturn err\n\t\t}\n\t\ts.expr = expression\n\t\t\/\/set Process Data\n\t\ts.Compute = func(arg ...interface{}) {\n\t\t\t\/\/parameters := make(map[string]interface{})\n\t\t\tparameters := arg[0].(map[string]interface{})\n\t\t\tresult, err := s.expr.Evaluate(parameters)\n\t\t\tif err != nil {\n\t\t\t\ts.log.Errorf(\"Error in metric %s On EVAL string: %s : ERROR : %s\", s.cfg.ID, s.cfg.ExtraData, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/Influxdb has not support for NaN,Inf values\n\t\t\t\/\/https:\/\/github.com\/influxdata\/influxdb\/issues\/4089\n\t\t\tswitch v := result.(type) {\n\t\t\tcase float64:\n\t\t\t\tif math.IsNaN(v) || math.IsInf(v, 0) {\n\t\t\t\t\ts.log.Warnf(\"Warning in metric %s On EVAL string: %s : Value is not a valid Floating Pint (NaN\/Inf) : %f\", s.cfg.ID, s.cfg.ExtraData, v)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\ts.CookedValue = result\n\t\t\ts.CurTime = time.Now()\n\t\t\ts.Scale()\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>fix bad counter limits<commit_after>package metric\n\nimport (\n\t\"fmt\"\n\t\"github.com\/Knetic\/govaluate\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/soniah\/gosnmp\"\n\t\"github.com\/toni-moreno\/snmpcollector\/pkg\/config\"\n\t\"github.com\/toni-moreno\/snmpcollector\/pkg\/data\/measurement\/filter\"\n\t\"github.com\/toni-moreno\/snmpcollector\/pkg\/data\/snmp\"\n\t\"math\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar (\n\tconfDir string              \/\/Needed to get File Filters data\n\tdbc     *config.DatabaseCfg \/\/Needed to get Custom Filter  data\n)\n\n\/\/ SetConfDir  enable load File Filters from anywhere in the our FS.\nfunc SetConfDir(dir string) {\n\tconfDir = dir\n}\n\n\/\/ SetDB load database config to load data if needed (used in filters)\nfunc SetDB(db *config.DatabaseCfg) {\n\tdbc = db\n}\n\nconst (\n\tNeverReport     = 0\n\tAlwaysReport    = 1\n\tOnNonZeroReport = 2\n\tOnChangedReport = 3\n)\n\n\/\/SnmpMetric type to metric runtime\ntype SnmpMetric struct {\n\tcfg         *config.SnmpMetricCfg\n\tID          string\n\tCookedValue interface{}\n\tCurValue    interface{}\n\tLastValue   interface{}\n\tCurTime     time.Time\n\tLastTime    time.Time\n\tElapsedTime float64\n\tCompute     func(arg ...interface{})                `json:\"-\"`\n\tScale       func()                                  `json:\"-\"`\n\tSetRawData  func(pdu gosnmp.SnmpPDU, now time.Time) `json:\"-\"`\n\tRealOID     string\n\tReport      int \/\/if false this metric won't be sent to the ouput buffer (is just taken as a coomputed input for other metrics)\n\t\/\/for STRINGPARSER\n\tre   *regexp.Regexp\n\texpr *govaluate.EvaluableExpression\n\t\/\/for CONDITIONEVAL\n\tcondflt filter.Filter\n\t\/\/ Logger\n\tlog *logrus.Logger\n}\n\n\/\/ GetDataSrcType get needed data\nfunc (s *SnmpMetric) GetDataSrcType() string {\n\treturn s.cfg.DataSrcType\n}\n\n\/\/ PrintDebugCfg helps users get data about metric configuration\nfunc (s *SnmpMetric) PrintDebugCfg() {\n\ts.log.Debugf(\"DEBUG METRIC  CONFIG %+v\", s.cfg)\n}\n\n\/\/ IsTag needed to generate Influx measurements\nfunc (s *SnmpMetric) IsTag() bool {\n\treturn s.cfg.IsTag\n}\n\n\/\/ GetFieldName  needed to generate Influx measurements\nfunc (s *SnmpMetric) GetFieldName() string {\n\treturn s.cfg.FieldName\n}\n\n\/\/ New constructor\nfunc New(c *config.SnmpMetricCfg) (*SnmpMetric, error) {\n\tmetric := &SnmpMetric{}\n\terr := metric.Init(c)\n\treturn metric, err\n}\n\nfunc NewWithLog(c *config.SnmpMetricCfg, l *logrus.Logger) (*SnmpMetric, error) {\n\tmetric := &SnmpMetric{log: l}\n\terr := metric.Init(c)\n\treturn metric, err\n}\n\nfunc (s *SnmpMetric) SetLogger(l *logrus.Logger) {\n\ts.log = l\n}\n\nfunc (s *SnmpMetric) Init(c *config.SnmpMetricCfg) error {\n\tif c == nil {\n\t\treturn fmt.Errorf(\"Error on initialice device, configuration struct is nil\")\n\t}\n\ts.cfg = c\n\ts.RealOID = c.BaseOID\n\ts.ID = s.cfg.ID\n\tif s.cfg.Scale != 0.0 || s.cfg.Shift != 0.0 {\n\t\ts.Scale = func() {\n\t\t\ts.CookedValue = (s.cfg.Scale * float64(s.CookedValue.(float64))) + s.cfg.Shift\n\t\t}\n\t} else {\n\t\ts.Scale = func() {\n\t\t}\n\t}\n\tswitch s.cfg.DataSrcType {\n\tcase \"CONDITIONEVAL\":\n\t\t\/\/select\n\t\tcond, err := dbc.GetOidConditionCfgByID(s.cfg.ExtraData)\n\t\tif err != nil {\n\t\t\ts.log.Errorf(\"Error getting CONDITIONEVAL [id: %s ] data : %s\", s.cfg.ExtraData, err)\n\t\t}\n\t\t\/\/get Regexp\n\t\ts.condflt = filter.NewOidFilter(cond.OIDCond, cond.CondType, cond.CondValue, s.log)\n\n\t\ts.Compute = func(arg ...interface{}) {\n\t\t\ts.condflt.Init(arg...)\n\t\t\ts.condflt.Update()\n\t\t\ts.CookedValue = s.condflt.Count()\n\t\t\ts.CurTime = time.Now()\n\t\t\ts.Scale()\n\t\t}\n\t\t\/\/Sign\n\t\t\/\/set Process Data\n\tcase \"TIMETICKS\": \/\/Cooked TimeTicks\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\tval := snmp.PduVal2Int64(pdu)\n\t\t\ts.CookedValue = float64(val \/ 100) \/\/now data in secoonds\n\t\t\ts.CurTime = now\n\t\t\ts.Scale()\n\t\t}\n\n\t\t\/\/Signed Integers\n\tcase \"INTEGER\", \"Integer32\":\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\tval := snmp.PduVal2Int64(pdu)\n\t\t\ts.CookedValue = float64(val)\n\t\t\ts.CurTime = now\n\t\t\ts.Scale()\n\t\t}\n\t\t\/\/Unsigned Integers\n\tcase \"Counter32\", \"Gauge32\", \"Counter64\", \"TimeTicks\", \"UInteger32\", \"Unsigned32\":\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\tval := snmp.PduVal2UInt64(pdu)\n\t\t\ts.CookedValue = float64(val)\n\t\t\ts.CurTime = now\n\t\t\ts.Scale()\n\t\t}\n\tcase \"COUNTER32\": \/\/Increment computed\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\t\/\/first time only set values and reassign itself to the complete method this will avoi to send invalid data\n\t\t\tval := snmp.PduVal2UInt64(pdu)\n\t\t\ts.CurValue = val\n\t\t\ts.CurTime = now\n\t\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\t\tval := snmp.PduVal2UInt64(pdu)\n\t\t\t\ts.LastTime = s.CurTime\n\t\t\t\ts.LastValue = s.CurValue\n\t\t\t\ts.CurValue = val\n\t\t\t\ts.CurTime = now\n\t\t\t\ts.Compute()\n\t\t\t\ts.Scale()\n\t\t\t}\n\t\t}\n\t\tif s.cfg.GetRate == true {\n\t\t\ts.Compute = func(arg ...interface{}) {\n\t\t\t\ts.ElapsedTime = s.CurTime.Sub(s.LastTime).Seconds()\n\t\t\t\tif s.CurValue.(uint64) < s.LastValue.(uint64) {\n\t\t\t\t\ts.CookedValue = float64(math.MaxUint32-s.LastValue.(uint64)+s.CurValue.(uint64)) \/ s.ElapsedTime\n\t\t\t\t} else {\n\t\t\t\t\ts.CookedValue = float64(s.CurValue.(uint64)-s.LastValue.(uint64)) \/ s.ElapsedTime\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\ts.Compute = func(arg ...interface{}) {\n\t\t\t\ts.ElapsedTime = s.CurTime.Sub(s.LastTime).Seconds()\n\t\t\t\tif s.CurValue.(uint64) < s.LastValue.(uint64) {\n\t\t\t\t\ts.CookedValue = float64(math.MaxUint32 - s.LastValue.(uint64) + s.CurValue.(uint64))\n\t\t\t\t} else {\n\t\t\t\t\ts.CookedValue = float64(s.CurValue.(uint64) - s.LastValue.(uint64))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tcase \"COUNTER64\": \/\/Increment computed\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\t\/\/log.Debugf(\"========================================>COUNTER64: first time :%s \", s.RealOID)\n\t\t\t\/\/first time only set values and reassign itself to the complete method\n\t\t\tval := snmp.PduVal2UInt64(pdu)\n\t\t\ts.CurValue = val\n\t\t\ts.CurTime = now\n\t\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\t\t\/\/log.Debugf(\"========================================>COUNTER64: the other time:%s\", s.RealOID)\n\t\t\t\tval := snmp.PduVal2UInt64(pdu)\n\t\t\t\ts.LastTime = s.CurTime\n\t\t\t\ts.LastValue = s.CurValue\n\t\t\t\ts.CurValue = val\n\t\t\t\ts.CurTime = now\n\t\t\t\ts.Compute()\n\t\t\t\ts.Scale()\n\t\t\t}\n\t\t}\n\t\tif s.cfg.GetRate == true {\n\t\t\ts.Compute = func(arg ...interface{}) {\n\t\t\t\ts.ElapsedTime = s.CurTime.Sub(s.LastTime).Seconds()\n\t\t\t\t\/\/duration := s.CurTime.Sub(s.LastTime)\n\t\t\t\tif s.CurValue.(uint64) < s.LastValue.(uint64) {\n\t\t\t\t\ts.CookedValue = float64(math.MaxUint64-s.LastValue.(uint64)+s.CurValue.(uint64)) \/ s.ElapsedTime\n\t\t\t\t} else {\n\t\t\t\t\ts.CookedValue = float64(s.CurValue.(uint64)-s.LastValue.(uint64)) \/ s.ElapsedTime\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\ts.Compute = func(arg ...interface{}) {\n\t\t\t\ts.ElapsedTime = s.CurTime.Sub(s.LastTime).Seconds()\n\t\t\t\tif s.CurValue.(uint64) < s.LastValue.(uint64) {\n\t\t\t\t\ts.CookedValue = float64(math.MaxUint64 - s.LastValue.(uint64) + s.CurValue.(uint64))\n\t\t\t\t} else {\n\t\t\t\t\ts.CookedValue = float64(s.CurValue.(uint64) - s.LastValue.(uint64))\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\tcase \"OCTETSTRING\":\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\ts.CookedValue = snmp.PduVal2str(pdu)\n\t\t\ts.CurTime = now\n\t\t}\n\tcase \"IpAddress\":\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\ts.CookedValue, _ = snmp.PduVal2IPaddr(pdu)\n\t\t\ts.CurTime = now\n\t\t}\n\tcase \"HWADDR\":\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\ts.CookedValue, _ = snmp.PduVal2Hwaddr(pdu)\n\t\t\ts.CurTime = now\n\t\t}\n\tcase \"STRINGPARSER\":\n\t\t\/\/get Regexp\n\t\tre, err := regexp.Compile(s.cfg.ExtraData)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error on initialice STRINGPARSER, invalind Regular Expression : %s\", s.cfg.ExtraData)\n\t\t}\n\t\ts.re = re\n\t\t\/\/set Process Data\n\t\ts.SetRawData = func(pdu gosnmp.SnmpPDU, now time.Time) {\n\t\t\tstr := snmp.PduVal2str(pdu)\n\t\t\tretarray := s.re.FindStringSubmatch(str)\n\t\t\tif len(retarray) < 2 {\n\t\t\t\ts.log.Warnf(\"Error for metric [%s] parsing REGEXG [%s] on string [%s] without capturing group\", s.cfg.ID, s.cfg.ExtraData, str)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/retarray[0] contains full string\n\t\t\tif len(retarray[1]) == 0 {\n\t\t\t\ts.log.Warnf(\"Error for metric [%s] parsing REGEXG [%s] on string [%s] cause  void capturing group\", s.cfg.ID, s.cfg.ExtraData, str)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvalue, err := strconv.ParseFloat(retarray[1], 64)\n\t\t\tif err != nil {\n\t\t\t\ts.log.Warnf(\"Error parsing float for metric %s : error: %s\", s.cfg.ID, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\ts.CookedValue = value\n\t\t\ts.CurTime = now\n\t\t\ts.Scale()\n\t\t}\n\tcase \"STRINGEVAL\":\n\n\t\texpression, err := govaluate.NewEvaluableExpression(s.cfg.ExtraData)\n\t\tif err != nil {\n\t\t\ts.log.Errorf(\"Error on initialice STRINGEVAL, evaluation : %s : ERROR : %s\", s.cfg.ExtraData, err)\n\t\t\treturn err\n\t\t}\n\t\ts.expr = expression\n\t\t\/\/set Process Data\n\t\ts.Compute = func(arg ...interface{}) {\n\t\t\t\/\/parameters := make(map[string]interface{})\n\t\t\tparameters := arg[0].(map[string]interface{})\n\t\t\tresult, err := s.expr.Evaluate(parameters)\n\t\t\tif err != nil {\n\t\t\t\ts.log.Errorf(\"Error in metric %s On EVAL string: %s : ERROR : %s\", s.cfg.ID, s.cfg.ExtraData, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/Influxdb has not support for NaN,Inf values\n\t\t\t\/\/https:\/\/github.com\/influxdata\/influxdb\/issues\/4089\n\t\t\tswitch v := result.(type) {\n\t\t\tcase float64:\n\t\t\t\tif math.IsNaN(v) || math.IsInf(v, 0) {\n\t\t\t\t\ts.log.Warnf(\"Warning in metric %s On EVAL string: %s : Value is not a valid Floating Pint (NaN\/Inf) : %f\", s.cfg.ID, s.cfg.ExtraData, v)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\ts.CookedValue = result\n\t\t\ts.CurTime = time.Now()\n\t\t\ts.Scale()\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package compute\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n)\n\n\/\/ Tag represents a tag applied to an asset.\ntype Tag struct {\n\tName  string `json:\"tagKeyName\"`\n\tValue string `json:\"tagKeyValue\"`\n}\n\n\/\/ TagDetail represents detailed information about a tag applied to an asset.\ntype TagDetail struct {\n\tAssetType        string `json:\"assetType\"`\n\tAssetID          string `json:\"assetId\"`\n\tAssetName        string `json:\"assetName\"`\n\tDataCenterID     string `json:\"datacenterId\"`\n\tTagKeyID         string `json:\"tagKeyId\"`\n\tName             string `json:\"tagKeyName\"`\n\tValue            string `json:\"value\"`\n\tIsValueRequired  bool   `json:\"valueRequired\"`\n\tDisplayOnReports bool   `json:\"displayOnReport\"`\n}\n\n\/\/ TagDetails represents a page of TagDetail results.\ntype TagDetails struct {\n\tItems []TagDetail\n\n\tPagedResult\n}\n\n\/\/ Request body when applying tags to an asset.\ntype applyTags struct {\n\tAssetType string `json:\"assetType\"`\n\tAssetID   string `json:\"assetId\"`\n\tTags      []Tag  `json:\"tag\"`\n}\n\n\/\/ Request body when removing tags from an asset.\ntype removeTags struct {\n\tAssetType string   `json:\"assetType\"`\n\tAssetID   string   `json:\"assetId\"`\n\tTagNames  []string `json:\"tagKeyName\"`\n}\n\n\/\/ TagKey represents a key for asset tags.\ntype TagKey struct {\n\tID string `json:\"id\"`\n\n\ttagKey\n}\n\n\/\/ TagKeys represents a page of TagKey results.\ntype TagKeys struct {\n\tItems []TagKey\n\n\tPagedResult\n}\n\n\/\/ Common fields for a tag key.\ntype tagKey struct {\n\tName             string `json:\"name\"`\n\tDescription      string `json:\"description\"`\n\tIsValueRequired  bool   `json:\"valueRequired\"`\n\tDisplayOnReports bool   `json:\"displayOnReport\"`\n}\n\n\/\/ Request body for deleting a tag key.\ntype deleteTagKey struct {\n\tID string `json:\"id\"`\n}\n\n\/\/ GetAssetTags gets all tags applied to the specified asset.\nfunc (client *Client) GetAssetTags(assetID string, assetType string, paging *PagingInfo) (tags *TagDetails, err error) {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tag\/tag?assetId=%s&assetType=%s\", organizationID, assetID, assetType)\n\tif paging != nil {\n\t\trequestURI += fmt.Sprintf(\"&pageNumber=%d&pageSize=%d\", paging.PageNumber, paging.PageSize)\n\t}\n\trequest, err := client.newRequestV22(requestURI, http.MethodGet, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif statusCode != http.StatusOK {\n\t\tvar apiResponse *APIResponseV2\n\n\t\tapiResponse, err = readAPIResponseAsJSON(responseBody, statusCode)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, apiResponse.ToError(\"Request failed with status code %d (%s): %s\", statusCode, apiResponse.ResponseCode, apiResponse.Message)\n\t}\n\n\ttags = &TagDetails{}\n\terr = json.Unmarshal(responseBody, tags)\n\n\treturn tags, err\n}\n\n\/\/ ApplyAssetTags applies the specified tags to an asset.\nfunc (client *Client) ApplyAssetTags(assetID string, assetType string, tags ...Tag) (response *APIResponseV2, err error) {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tag\/applyTags\", organizationID)\n\trequest, err := client.newRequestV22(requestURI, http.MethodPost, &applyTags{\n\t\tAssetID:   assetID,\n\t\tAssetType: assetType,\n\t\tTags:      tags,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn readAPIResponseAsJSON(responseBody, statusCode)\n}\n\n\/\/ RemoveAssetTags removes the specified tags from an asset.\nfunc (client *Client) RemoveAssetTags(assetID string, assetType string, tagNames ...string) (response *APIResponseV2, err error) {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tag\/removeTags\", organizationID)\n\trequest, err := client.newRequestV22(requestURI, http.MethodPost, &removeTags{\n\t\tAssetID:   assetID,\n\t\tAssetType: assetType,\n\t\tTagNames:  tagNames,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn readAPIResponseAsJSON(responseBody, statusCode)\n}\n\n\/\/ GetTagKey retrieves the tag key with the specified Id.\n\/\/ Returns nil if no tag key is found with the specified Id.\nfunc (client *Client) GetTagKey(id string) (tagKey *TagKey, err error) {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tags\/tagKey\/%s\", organizationID, id)\n\trequest, err := client.newRequestV22(requestURI, http.MethodGet, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif statusCode != http.StatusOK {\n\t\tvar apiResponse *APIResponseV2\n\n\t\tapiResponse, err = readAPIResponseAsJSON(responseBody, statusCode)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif apiResponse.ResponseCode == ResponseCodeResourceNotFound {\n\t\t\treturn nil, nil \/\/ Not an error, but was not found.\n\t\t}\n\n\t\treturn nil, apiResponse.ToError(\"Request to retrieve tag key '%s' failed with status code %d (%s): %s\", id, statusCode, apiResponse.ResponseCode, apiResponse.Message)\n\t}\n\n\ttagKey = &TagKey{}\n\terr = json.Unmarshal(responseBody, tagKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tagKey, nil\n}\n\n\/\/ ListTagKeys lists all tag keys that apply to the specified network domain.\nfunc (client *Client) ListTagKeys(pageNumber int, pageSize int) (tagKeys *TagKeys, err error) {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tag\/tagKey?orderBy=name&pageNumber=%d&pageSize=%d\", organizationID, pageNumber, pageSize)\n\trequest, err := client.newRequestV22(requestURI, http.MethodGet, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif statusCode != http.StatusOK {\n\t\tvar apiResponse *APIResponseV2\n\n\t\tapiResponse, err = readAPIResponseAsJSON(responseBody, statusCode)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, apiResponse.ToError(\"Request to list tag keys failed with status code %d (%s): %s\", statusCode, apiResponse.ResponseCode, apiResponse.Message)\n\t}\n\n\ttagKeys = &TagKeys{}\n\terr = json.Unmarshal(responseBody, tagKeys)\n\n\treturn tagKeys, err\n}\n\n\/\/ CreateTagKey creates a new tag key.\nfunc (client *Client) CreateTagKey(name string, description string, isValueRequired bool, displayOnReports bool) (tagKeyID string, err error) {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tag\/createTagKey\", organizationID)\n\trequest, err := client.newRequestV22(requestURI, http.MethodPost, &tagKey{\n\t\tName:             name,\n\t\tDescription:      description,\n\t\tIsValueRequired:  isValueRequired,\n\t\tDisplayOnReports: displayOnReports,\n\t})\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tapiResponse, err := readAPIResponseAsJSON(responseBody, statusCode)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif apiResponse.ResponseCode != ResponseCodeOK {\n\t\treturn \"\", apiResponse.ToError(\"Request to create tag key '%s' failed with unexpected status code %d (%s): %s\", name, statusCode, apiResponse.ResponseCode, apiResponse.Message)\n\t}\n\n\t\/\/ Expected: \"info\" { \"name\": \"tagKeyId\", \"value\": \"the-Id-of-the-new-tag-key\" }\n\tif len(apiResponse.FieldMessages) != 1 || apiResponse.FieldMessages[0].FieldName != \"tagKeyId\" {\n\t\treturn \"\", apiResponse.ToError(\"Received an unexpected response (missing 'tagKeyId') with status code %d (%s): %s\", statusCode, apiResponse.ResponseCode, apiResponse.Message)\n\t}\n\n\treturn apiResponse.FieldMessages[0].Message, nil\n}\n\n\/\/ DeleteTagKey deletes the specified TagKey rule.\nfunc (client *Client) DeleteTagKey(id string) error {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tag\/deleteTagKey\", organizationID)\n\trequest, err := client.newRequestV22(requestURI, http.MethodPost,\n\t\t&deleteTagKey{id},\n\t)\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tapiResponse, err := readAPIResponseAsJSON(responseBody, statusCode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif apiResponse.ResponseCode != ResponseCodeOK {\n\t\treturn apiResponse.ToError(\"Request to delete tag key '%s' failed with unexpected status code %d (%s): %s\", id, statusCode, apiResponse.ResponseCode, apiResponse.Message)\n\t}\n\n\treturn nil\n}\n<commit_msg>Fix incorrect field name for tag value.<commit_after>package compute\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n)\n\n\/\/ Tag represents a tag applied to an asset.\ntype Tag struct {\n\tName  string `json:\"tagKeyName\"`\n\tValue string `json:\"value\"`\n}\n\n\/\/ TagDetail represents detailed information about a tag applied to an asset.\ntype TagDetail struct {\n\tAssetType        string `json:\"assetType\"`\n\tAssetID          string `json:\"assetId\"`\n\tAssetName        string `json:\"assetName\"`\n\tDataCenterID     string `json:\"datacenterId\"`\n\tTagKeyID         string `json:\"tagKeyId\"`\n\tName             string `json:\"tagKeyName\"`\n\tValue            string `json:\"value\"`\n\tIsValueRequired  bool   `json:\"valueRequired\"`\n\tDisplayOnReports bool   `json:\"displayOnReport\"`\n}\n\n\/\/ TagDetails represents a page of TagDetail results.\ntype TagDetails struct {\n\tItems []TagDetail\n\n\tPagedResult\n}\n\n\/\/ Request body when applying tags to an asset.\ntype applyTags struct {\n\tAssetType string `json:\"assetType\"`\n\tAssetID   string `json:\"assetId\"`\n\tTags      []Tag  `json:\"tag\"`\n}\n\n\/\/ Request body when removing tags from an asset.\ntype removeTags struct {\n\tAssetType string   `json:\"assetType\"`\n\tAssetID   string   `json:\"assetId\"`\n\tTagNames  []string `json:\"tagKeyName\"`\n}\n\n\/\/ TagKey represents a key for asset tags.\ntype TagKey struct {\n\tID string `json:\"id\"`\n\n\ttagKey\n}\n\n\/\/ TagKeys represents a page of TagKey results.\ntype TagKeys struct {\n\tItems []TagKey\n\n\tPagedResult\n}\n\n\/\/ Common fields for a tag key.\ntype tagKey struct {\n\tName             string `json:\"name\"`\n\tDescription      string `json:\"description\"`\n\tIsValueRequired  bool   `json:\"valueRequired\"`\n\tDisplayOnReports bool   `json:\"displayOnReport\"`\n}\n\n\/\/ Request body for deleting a tag key.\ntype deleteTagKey struct {\n\tID string `json:\"id\"`\n}\n\n\/\/ GetAssetTags gets all tags applied to the specified asset.\nfunc (client *Client) GetAssetTags(assetID string, assetType string, paging *PagingInfo) (tags *TagDetails, err error) {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tag\/tag?assetId=%s&assetType=%s\", organizationID, assetID, assetType)\n\tif paging != nil {\n\t\trequestURI += fmt.Sprintf(\"&pageNumber=%d&pageSize=%d\", paging.PageNumber, paging.PageSize)\n\t}\n\trequest, err := client.newRequestV22(requestURI, http.MethodGet, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif statusCode != http.StatusOK {\n\t\tvar apiResponse *APIResponseV2\n\n\t\tapiResponse, err = readAPIResponseAsJSON(responseBody, statusCode)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, apiResponse.ToError(\"Request failed with status code %d (%s): %s\", statusCode, apiResponse.ResponseCode, apiResponse.Message)\n\t}\n\n\ttags = &TagDetails{}\n\terr = json.Unmarshal(responseBody, tags)\n\n\treturn tags, err\n}\n\n\/\/ ApplyAssetTags applies the specified tags to an asset.\nfunc (client *Client) ApplyAssetTags(assetID string, assetType string, tags ...Tag) (response *APIResponseV2, err error) {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tag\/applyTags\", organizationID)\n\trequest, err := client.newRequestV22(requestURI, http.MethodPost, &applyTags{\n\t\tAssetID:   assetID,\n\t\tAssetType: assetType,\n\t\tTags:      tags,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn readAPIResponseAsJSON(responseBody, statusCode)\n}\n\n\/\/ RemoveAssetTags removes the specified tags from an asset.\nfunc (client *Client) RemoveAssetTags(assetID string, assetType string, tagNames ...string) (response *APIResponseV2, err error) {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tag\/removeTags\", organizationID)\n\trequest, err := client.newRequestV22(requestURI, http.MethodPost, &removeTags{\n\t\tAssetID:   assetID,\n\t\tAssetType: assetType,\n\t\tTagNames:  tagNames,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn readAPIResponseAsJSON(responseBody, statusCode)\n}\n\n\/\/ GetTagKey retrieves the tag key with the specified Id.\n\/\/ Returns nil if no tag key is found with the specified Id.\nfunc (client *Client) GetTagKey(id string) (tagKey *TagKey, err error) {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tags\/tagKey\/%s\", organizationID, id)\n\trequest, err := client.newRequestV22(requestURI, http.MethodGet, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif statusCode != http.StatusOK {\n\t\tvar apiResponse *APIResponseV2\n\n\t\tapiResponse, err = readAPIResponseAsJSON(responseBody, statusCode)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif apiResponse.ResponseCode == ResponseCodeResourceNotFound {\n\t\t\treturn nil, nil \/\/ Not an error, but was not found.\n\t\t}\n\n\t\treturn nil, apiResponse.ToError(\"Request to retrieve tag key '%s' failed with status code %d (%s): %s\", id, statusCode, apiResponse.ResponseCode, apiResponse.Message)\n\t}\n\n\ttagKey = &TagKey{}\n\terr = json.Unmarshal(responseBody, tagKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn tagKey, nil\n}\n\n\/\/ ListTagKeys lists all tag keys that apply to the specified network domain.\nfunc (client *Client) ListTagKeys(pageNumber int, pageSize int) (tagKeys *TagKeys, err error) {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tag\/tagKey?orderBy=name&pageNumber=%d&pageSize=%d\", organizationID, pageNumber, pageSize)\n\trequest, err := client.newRequestV22(requestURI, http.MethodGet, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif statusCode != http.StatusOK {\n\t\tvar apiResponse *APIResponseV2\n\n\t\tapiResponse, err = readAPIResponseAsJSON(responseBody, statusCode)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn nil, apiResponse.ToError(\"Request to list tag keys failed with status code %d (%s): %s\", statusCode, apiResponse.ResponseCode, apiResponse.Message)\n\t}\n\n\ttagKeys = &TagKeys{}\n\terr = json.Unmarshal(responseBody, tagKeys)\n\n\treturn tagKeys, err\n}\n\n\/\/ CreateTagKey creates a new tag key.\nfunc (client *Client) CreateTagKey(name string, description string, isValueRequired bool, displayOnReports bool) (tagKeyID string, err error) {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tag\/createTagKey\", organizationID)\n\trequest, err := client.newRequestV22(requestURI, http.MethodPost, &tagKey{\n\t\tName:             name,\n\t\tDescription:      description,\n\t\tIsValueRequired:  isValueRequired,\n\t\tDisplayOnReports: displayOnReports,\n\t})\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tapiResponse, err := readAPIResponseAsJSON(responseBody, statusCode)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif apiResponse.ResponseCode != ResponseCodeOK {\n\t\treturn \"\", apiResponse.ToError(\"Request to create tag key '%s' failed with unexpected status code %d (%s): %s\", name, statusCode, apiResponse.ResponseCode, apiResponse.Message)\n\t}\n\n\t\/\/ Expected: \"info\" { \"name\": \"tagKeyId\", \"value\": \"the-Id-of-the-new-tag-key\" }\n\tif len(apiResponse.FieldMessages) != 1 || apiResponse.FieldMessages[0].FieldName != \"tagKeyId\" {\n\t\treturn \"\", apiResponse.ToError(\"Received an unexpected response (missing 'tagKeyId') with status code %d (%s): %s\", statusCode, apiResponse.ResponseCode, apiResponse.Message)\n\t}\n\n\treturn apiResponse.FieldMessages[0].Message, nil\n}\n\n\/\/ DeleteTagKey deletes the specified TagKey rule.\nfunc (client *Client) DeleteTagKey(id string) error {\n\torganizationID, err := client.getOrganizationID()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trequestURI := fmt.Sprintf(\"%s\/tag\/deleteTagKey\", organizationID)\n\trequest, err := client.newRequestV22(requestURI, http.MethodPost,\n\t\t&deleteTagKey{id},\n\t)\n\tresponseBody, statusCode, err := client.executeRequest(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tapiResponse, err := readAPIResponseAsJSON(responseBody, statusCode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif apiResponse.ResponseCode != ResponseCodeOK {\n\t\treturn apiResponse.ToError(\"Request to delete tag key '%s' failed with unexpected status code %d (%s): %s\", id, statusCode, apiResponse.ResponseCode, apiResponse.Message)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package eventer\n\nimport (\n\t\"github.com\/appscode\/go\/log\"\n\tcore \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/kubernetes\/scheme\"\n\t\"k8s.io\/client-go\/tools\/record\"\n)\n\nconst (\n\tEventReasonCreating                string = \"Creating\"\n\tEventReasonPausing                 string = \"Pausing\"\n\tEventReasonWipingOut               string = \"WipingOut\"\n\tEventReasonFailedToCreate          string = \"Failed\"\n\tEventReasonFailedToPause           string = \"Failed\"\n\tEventReasonFailedToDelete          string = \"Failed\"\n\tEventReasonFailedToWipeOut         string = \"Failed\"\n\tEventReasonFailedToGet             string = \"Failed\"\n\tEventReasonFailedToInitialize      string = \"Failed\"\n\tEventReasonFailedToList            string = \"Failed\"\n\tEventReasonFailedToResume          string = \"Failed\"\n\tEventReasonFailedToSchedule        string = \"Failed\"\n\tEventReasonFailedToStart           string = \"Failed\"\n\tEventReasonFailedToUpdate          string = \"Failed\"\n\tEventReasonFailedToAddMonitor      string = \"Failed\"\n\tEventReasonFailedToDeleteMonitor   string = \"Failed\"\n\tEventReasonFailedToUpdateMonitor   string = \"Failed\"\n\tEventReasonIgnoredSnapshot         string = \"IgnoredSnapshot\"\n\tEventReasonInitializing            string = \"Initializing\"\n\tEventReasonInvalid                 string = \"Invalid\"\n\tEventReasonInvalidUpdate           string = \"InvalidUpdate\"\n\tEventReasonResuming                string = \"Resuming\"\n\tEventReasonSnapshotFailed          string = \"SnapshotFailed\"\n\tEventReasonStarting                string = \"Starting\"\n\tEventReasonSuccessfulCreate        string = \"SuccessfulCreate\"\n\tEventReasonSuccessfulPause         string = \"SuccessfulPause\"\n\tEventReasonSuccessfulMonitorAdd    string = \"SuccessfulMonitorAdd\"\n\tEventReasonSuccessfulMonitorDelete string = \"SuccessfulMonitorDelete\"\n\tEventReasonSuccessfulMonitorUpdate string = \"SuccessfulMonitorUpdate\"\n\tEventReasonSuccessfulResume        string = \"SuccessfulResume\"\n\tEventReasonSuccessfulWipeOut       string = \"SuccessfulWipeOut\"\n\tEventReasonSuccessfulSnapshot      string = \"SuccessfulSnapshot\"\n\tEventReasonSuccessfulValidate      string = \"SuccessfulValidate\"\n\tEventReasonSuccessfulInitialize    string = \"SuccessfulInitialize\"\n)\n\nfunc NewEventRecorder(client kubernetes.Interface, component string) record.EventRecorder {\n\t\/\/ Event Broadcaster\n\tbroadcaster := record.NewBroadcaster()\n\tbroadcaster.StartEventWatcher(\n\t\tfunc(event *core.Event) {\n\t\t\tif _, err := client.Core().Events(event.Namespace).Create(event); err != nil {\n\t\t\t\tlog.Errorln(err)\n\t\t\t}\n\t\t},\n\t)\n\n\treturn broadcaster.NewRecorder(scheme.Scheme, core.EventSource{Component: component})\n}\n<commit_msg>Add Patch Event-Type (#168)<commit_after>package eventer\n\nimport (\n\t\"github.com\/appscode\/go\/log\"\n\tcore \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/kubernetes\/scheme\"\n\t\"k8s.io\/client-go\/tools\/record\"\n)\n\nconst (\n\tEventReasonCreating                string = \"Creating\"\n\tEventReasonPausing                 string = \"Pausing\"\n\tEventReasonWipingOut               string = \"WipingOut\"\n\tEventReasonFailedToCreate          string = \"Failed\"\n\tEventReasonFailedToPause           string = \"Failed\"\n\tEventReasonFailedToDelete          string = \"Failed\"\n\tEventReasonFailedToWipeOut         string = \"Failed\"\n\tEventReasonFailedToGet             string = \"Failed\"\n\tEventReasonFailedToInitialize      string = \"Failed\"\n\tEventReasonFailedToList            string = \"Failed\"\n\tEventReasonFailedToResume          string = \"Failed\"\n\tEventReasonFailedToSchedule        string = \"Failed\"\n\tEventReasonFailedToStart           string = \"Failed\"\n\tEventReasonFailedToUpdate          string = \"Failed\"\n\tEventReasonFailedToAddMonitor      string = \"Failed\"\n\tEventReasonFailedToDeleteMonitor   string = \"Failed\"\n\tEventReasonFailedToUpdateMonitor   string = \"Failed\"\n\tEventReasonIgnoredSnapshot         string = \"IgnoredSnapshot\"\n\tEventReasonInitializing            string = \"Initializing\"\n\tEventReasonInvalid                 string = \"Invalid\"\n\tEventReasonInvalidUpdate           string = \"InvalidUpdate\"\n\tEventReasonResuming                string = \"Resuming\"\n\tEventReasonSnapshotFailed          string = \"SnapshotFailed\"\n\tEventReasonStarting                string = \"Starting\"\n\tEventReasonSuccessful              string = \"Successful\"\n\tEventReasonSuccessfulCreate        string = \"SuccessfulCreate\"\n\tEventReasonSuccessfulPause         string = \"SuccessfulPause\"\n\tEventReasonSuccessfulMonitorAdd    string = \"SuccessfulMonitorAdd\"\n\tEventReasonSuccessfulMonitorDelete string = \"SuccessfulMonitorDelete\"\n\tEventReasonSuccessfulMonitorUpdate string = \"SuccessfulMonitorUpdate\"\n\tEventReasonSuccessfulResume        string = \"SuccessfulResume\"\n\tEventReasonSuccessfulWipeOut       string = \"SuccessfulWipeOut\"\n\tEventReasonSuccessfulSnapshot      string = \"SuccessfulSnapshot\"\n\tEventReasonSuccessfulValidate      string = \"SuccessfulValidate\"\n\tEventReasonSuccessfulInitialize    string = \"SuccessfulInitialize\"\n)\n\nfunc NewEventRecorder(client kubernetes.Interface, component string) record.EventRecorder {\n\t\/\/ Event Broadcaster\n\tbroadcaster := record.NewBroadcaster()\n\tbroadcaster.StartEventWatcher(\n\t\tfunc(event *core.Event) {\n\t\t\tif _, err := client.Core().Events(event.Namespace).Create(event); err != nil {\n\t\t\t\tlog.Errorln(err)\n\t\t\t}\n\t\t},\n\t)\n\n\treturn broadcaster.NewRecorder(scheme.Scheme, core.EventSource{Component: component})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage sysctl\n\nimport (\n\t\"fmt\"\n\n\tv1helper \"k8s.io\/kubernetes\/pkg\/api\/v1\/helper\"\n\t\"k8s.io\/kubernetes\/pkg\/kubelet\/container\"\n\t\"k8s.io\/kubernetes\/pkg\/kubelet\/lifecycle\"\n)\n\nconst (\n\tUnsupportedReason = \"SysctlUnsupported\"\n\t\/\/ CRI uses semver-compatible API version, while docker does not\n\t\/\/ (e.g., 1.24). Append the version with a \".0\".\n\tdockerMinimumAPIVersion = \"1.24.0\"\n\n\tdockerTypeName = \"docker\"\n)\n\n\/\/ TODO: The admission logic in this file is runtime-dependent. It should be\n\/\/ changed to be generic and CRI-compatible.\n\ntype runtimeAdmitHandler struct {\n\tresult lifecycle.PodAdmitResult\n}\n\nvar _ lifecycle.PodAdmitHandler = &runtimeAdmitHandler{}\n\n\/\/ NewRuntimeAdmitHandler returns a sysctlRuntimeAdmitHandler which checks whether\n\/\/ the given runtime support sysctls.\nfunc NewRuntimeAdmitHandler(runtime container.Runtime) (*runtimeAdmitHandler, error) {\n\tif runtime.Type() == dockerTypeName {\n\t\tv, err := runtime.APIVersion()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get runtime version: %v\", err)\n\t\t}\n\n\t\t\/\/ only Docker >= 1.12 supports sysctls\n\t\tc, err := v.Compare(dockerMinimumAPIVersion)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to compare Docker version for sysctl support: %v\", err)\n\t\t}\n\t\tif c >= 0 {\n\t\t\treturn &runtimeAdmitHandler{\n\t\t\t\tresult: lifecycle.PodAdmitResult{\n\t\t\t\t\tAdmit: true,\n\t\t\t\t},\n\t\t\t}, nil\n\t\t}\n\t\treturn &runtimeAdmitHandler{\n\t\t\tresult: lifecycle.PodAdmitResult{\n\t\t\t\tAdmit:   false,\n\t\t\t\tReason:  UnsupportedReason,\n\t\t\t\tMessage: \"Docker before 1.12 does not support sysctls\",\n\t\t\t},\n\t\t}, nil\n\t}\n\n\t\/\/ for other runtimes like rkt sysctls are not supported\n\treturn &runtimeAdmitHandler{\n\t\tresult: lifecycle.PodAdmitResult{\n\t\t\tAdmit:   false,\n\t\t\tReason:  UnsupportedReason,\n\t\t\tMessage: fmt.Sprintf(\"runtime %v does not support sysctls\", runtime.Type()),\n\t\t},\n\t}, nil\n}\n\n\/\/ Admit checks whether the runtime supports sysctls.\nfunc (w *runtimeAdmitHandler) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult {\n\tsysctls, unsafeSysctls, err := v1helper.SysctlsFromPodAnnotations(attrs.Pod.Annotations)\n\tif err != nil {\n\t\treturn lifecycle.PodAdmitResult{\n\t\t\tAdmit:   false,\n\t\t\tReason:  AnnotationInvalidReason,\n\t\t\tMessage: fmt.Sprintf(\"invalid sysctl annotation: %v\", err),\n\t\t}\n\t}\n\n\tif len(sysctls)+len(unsafeSysctls) > 0 {\n\t\treturn w.result\n\t}\n\n\treturn lifecycle.PodAdmitResult{\n\t\tAdmit: true,\n\t}\n}\n<commit_msg>Admit sysctls for other runtime.<commit_after>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage sysctl\n\nimport (\n\t\"fmt\"\n\n\tv1helper \"k8s.io\/kubernetes\/pkg\/api\/v1\/helper\"\n\t\"k8s.io\/kubernetes\/pkg\/kubelet\/container\"\n\t\"k8s.io\/kubernetes\/pkg\/kubelet\/lifecycle\"\n)\n\nconst (\n\tUnsupportedReason = \"SysctlUnsupported\"\n\t\/\/ CRI uses semver-compatible API version, while docker does not\n\t\/\/ (e.g., 1.24). Append the version with a \".0\".\n\tdockerMinimumAPIVersion = \"1.24.0\"\n\n\tdockerTypeName = \"docker\"\n\trktTypeName    = \"rkt\"\n)\n\n\/\/ TODO: The admission logic in this file is runtime-dependent. It should be\n\/\/ changed to be generic and CRI-compatible.\n\ntype runtimeAdmitHandler struct {\n\tresult lifecycle.PodAdmitResult\n}\n\nvar _ lifecycle.PodAdmitHandler = &runtimeAdmitHandler{}\n\n\/\/ NewRuntimeAdmitHandler returns a sysctlRuntimeAdmitHandler which checks whether\n\/\/ the given runtime support sysctls.\nfunc NewRuntimeAdmitHandler(runtime container.Runtime) (*runtimeAdmitHandler, error) {\n\tswitch runtime.Type() {\n\tcase dockerTypeName:\n\t\tv, err := runtime.APIVersion()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get runtime version: %v\", err)\n\t\t}\n\n\t\t\/\/ only Docker >= 1.12 supports sysctls\n\t\tc, err := v.Compare(dockerMinimumAPIVersion)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to compare Docker version for sysctl support: %v\", err)\n\t\t}\n\t\tif c >= 0 {\n\t\t\treturn &runtimeAdmitHandler{\n\t\t\t\tresult: lifecycle.PodAdmitResult{\n\t\t\t\t\tAdmit: true,\n\t\t\t\t},\n\t\t\t}, nil\n\t\t}\n\t\treturn &runtimeAdmitHandler{\n\t\t\tresult: lifecycle.PodAdmitResult{\n\t\t\t\tAdmit:   false,\n\t\t\t\tReason:  UnsupportedReason,\n\t\t\t\tMessage: \"Docker before 1.12 does not support sysctls\",\n\t\t\t},\n\t\t}, nil\n\tcase rktTypeName:\n\t\treturn &runtimeAdmitHandler{\n\t\t\tresult: lifecycle.PodAdmitResult{\n\t\t\t\tAdmit:   false,\n\t\t\t\tReason:  UnsupportedReason,\n\t\t\t\tMessage: \"Rkt does not support sysctls\",\n\t\t\t},\n\t\t}, nil\n\tdefault:\n\t\t\/\/ Return admit for other runtimes.\n\t\treturn &runtimeAdmitHandler{\n\t\t\tresult: lifecycle.PodAdmitResult{\n\t\t\t\tAdmit: true,\n\t\t\t},\n\t\t}, nil\n\t}\n}\n\n\/\/ Admit checks whether the runtime supports sysctls.\nfunc (w *runtimeAdmitHandler) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult {\n\tsysctls, unsafeSysctls, err := v1helper.SysctlsFromPodAnnotations(attrs.Pod.Annotations)\n\tif err != nil {\n\t\treturn lifecycle.PodAdmitResult{\n\t\t\tAdmit:   false,\n\t\t\tReason:  AnnotationInvalidReason,\n\t\t\tMessage: fmt.Sprintf(\"invalid sysctl annotation: %v\", err),\n\t\t}\n\t}\n\n\tif len(sysctls)+len(unsafeSysctls) > 0 {\n\t\treturn w.result\n\t}\n\n\treturn lifecycle.PodAdmitResult{\n\t\tAdmit: true,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package resolver\n\nimport (\n\t\"crypto\/rand\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\n\t\"nimona.io\/pkg\/context\"\n\t\"nimona.io\/pkg\/crypto\"\n\t\"nimona.io\/pkg\/localpeer\"\n\t\"nimona.io\/pkg\/network\"\n\t\"nimona.io\/pkg\/object\"\n\t\"nimona.io\/pkg\/peer\"\n)\n\nfunc TestResolver_TwoPeersCanFindEachOther(t *testing.T) {\n\t_, k0, kc0, n0, ctx0 := newPeer(t, \"peer0\")\n\n\td0 := New(\n\t\tctx0,\n\t\tn0,\n\t)\n\n\tba := []*peer.Peer{\n\t\t{\n\t\t\tAddresses: n0.LocalPeer().GetAddresses(),\n\t\t\tMetadata: object.Metadata{\n\t\t\t\tOwner: kc0.GetPrimaryPeerKey().PublicKey(),\n\t\t\t},\n\t\t},\n\t}\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t_, k1, _, n1, ctx1 := newPeer(t, \"peer1\")\n\n\td1 := New(\n\t\tctx1,\n\t\tn1,\n\t\tWithBoostrapPeers(ba),\n\t)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\tctx := context.New(\n\t\tcontext.WithCorrelationID(\"req1\"),\n\t\tcontext.WithTimeout(time.Second),\n\t)\n\n\tpeersChan, err := d1.Lookup(ctx, LookupByOwner(k0.PublicKey()))\n\n\tpeers := gatherPeers(peersChan)\n\trequire.NoError(t, err)\n\trequire.Len(t, peers, 1)\n\trequire.ElementsMatch(t, n0.LocalPeer().GetAddresses(), peers[0].Addresses)\n\n\tctxR2 := context.New(\n\t\tcontext.WithCorrelationID(\"req2\"),\n\t\tcontext.WithTimeout(time.Second),\n\t)\n\tpeersChan, err = d0.Lookup(ctxR2, LookupByOwner(k1.PublicKey()))\n\tpeers = gatherPeers(peersChan)\n\trequire.NoError(t, err)\n\trequire.Len(t, peers, 1)\n\trequire.Equal(t, n1.LocalPeer().GetAddresses(), peers[0].Addresses)\n}\n\nfunc TestResolver_TwoPeersAndOneBootstrapCanFindEachOther(t *testing.T) {\n\t_, k0, kc0, n0, ctx0 := newPeer(t, \"peer0\")\n\n\t\/\/ bootstrap node\n\tNew(ctx0, n0)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t_, k1, _, n1, ctx1 := newPeer(t, \"peer1\")\n\t_, k2, _, n2, ctx2 := newPeer(t, \"peer2\")\n\n\t\/\/ bootstrap address\n\tba := []*peer.Peer{\n\t\t{\n\t\t\tAddresses: n0.LocalPeer().GetAddresses(),\n\t\t\tMetadata: object.Metadata{\n\t\t\t\tOwner: kc0.GetPrimaryPeerKey().PublicKey(),\n\t\t\t},\n\t\t},\n\t}\n\n\t\/\/ node 1\n\td1 := New(\n\t\tctx1,\n\t\tn1,\n\t\tWithBoostrapPeers(ba),\n\t)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t\/\/ node 2\n\td2 := New(\n\t\tctx2,\n\t\tn2,\n\t\tWithBoostrapPeers(ba),\n\t)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t\/\/ find bootstrap from node1\n\tctx := context.New(\n\t\tcontext.WithCorrelationID(\"req1\"),\n\t\tcontext.WithTimeout(time.Second*2),\n\t)\n\tpeersChan, err := d1.Lookup(ctx, LookupByOwner(k0.PublicKey()))\n\tpeers := gatherPeers(peersChan)\n\trequire.NoError(t, err)\n\trequire.Len(t, peers, 1)\n\trequire.ElementsMatch(t, n0.LocalPeer().GetAddresses(), peers[0].Addresses)\n\n\t\/\/ find node 1 from node 2\n\tctx = context.New(\n\t\tcontext.WithCorrelationID(\"req2\"),\n\t\tcontext.WithTimeout(time.Second*2),\n\t)\n\tpeersChan, err = d2.Lookup(ctx, LookupByOwner(k1.PublicKey()))\n\tpeers = gatherPeers(peersChan)\n\trequire.NoError(t, err)\n\trequire.Len(t, peers, 1)\n\trequire.ElementsMatch(t, n1.LocalPeer().GetAddresses(), peers[0].Addresses)\n\n\t\/\/ find node 2 from node 1\n\tctx = context.New(\n\t\tcontext.WithCorrelationID(\"req3\"),\n\t\tcontext.WithTimeout(time.Second*2),\n\t)\n\n\tpeersChan, err = d1.Lookup(ctx, LookupByOwner(k2.PublicKey()))\n\tpeers = gatherPeers(peersChan)\n\trequire.NoError(t, err)\n\trequire.Len(t, peers, 1)\n\trequire.ElementsMatch(t, n2.LocalPeer().GetAddresses(), peers[0].Addresses)\n}\n\nfunc TestResolver_TwoPeersAndOneBootstrapCanProvide(t *testing.T) {\n\t_, k0, kc0, n0, ctx0 := newPeer(t, \"peer0\")\n\t_, k1, kc1, n1, ctx1 := newPeer(t, \"peer1\")\n\t_, k2, _, n2, ctx2 := newPeer(t, \"peer2\")\n\n\t\/\/ make peer 1 a provider\n\ttoken := make([]byte, 32)\n\trand.Read(token) \/\/ nolint: errcheck\n\tch := object.Hash(\"foo\")\n\tkc1.PutContentHashes(ch)\n\n\t\/\/ print peer info\n\tfmt.Println(\"0\", k0.PublicKey(), n0.LocalPeer().GetAddresses())\n\tfmt.Println(\"1\", k1.PublicKey(), n1.LocalPeer().GetAddresses())\n\tfmt.Println(\"2\", k2.PublicKey(), n2.LocalPeer().GetAddresses())\n\n\t\/\/ bootstrap peer\n\td0 := New(\n\t\tctx0,\n\t\tn0,\n\t)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t\/\/ bootstrap address\n\tba := []*peer.Peer{\n\t\t{\n\t\t\tAddresses: n0.LocalPeer().GetAddresses(),\n\t\t\tMetadata: object.Metadata{\n\t\t\t\tOwner: kc0.GetPrimaryPeerKey().PublicKey(),\n\t\t\t},\n\t\t},\n\t}\n\n\t\/\/ peer 1\n\tNew(\n\t\tctx1,\n\t\tn1,\n\t\tWithBoostrapPeers(ba),\n\t)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t\/\/ peer 2\n\td2 := New(\n\t\tctx2,\n\t\tn2,\n\t\tWithBoostrapPeers(ba),\n\t)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t\/\/ find peer 1 from peer 2\n\tctx := context.New(\n\t\tcontext.WithCorrelationID(\"req1\"),\n\t\tcontext.WithTimeout(time.Second),\n\t)\n\tprovidersChan, err := d2.Lookup(ctx, LookupByContentHash(ch))\n\trequire.NoError(t, err)\n\tproviders := gatherPeers(providersChan)\n\trequire.Len(t, providers, 1)\n\trequire.Equal(t, k1.PublicKey(), providers[0].PublicKey())\n\n\t\/\/ find peer 1 from bootstrap\n\tctx = context.New(\n\t\tcontext.WithCorrelationID(\"req2\"),\n\t\tcontext.WithTimeout(time.Second*2),\n\t)\n\tprovidersChan, err = d0.Lookup(ctx, LookupByContentHash(ch))\n\trequire.NoError(t, err)\n\tproviders = gatherPeers(providersChan)\n\trequire.Len(t, providers, 1)\n\trequire.Equal(t, k1.PublicKey(), providers[0].PublicKey())\n}\n\n\/\/ nolint: gocritic\nfunc newPeer(\n\tt *testing.T,\n\tname string,\n) (\n\tcrypto.PrivateKey,\n\tcrypto.PrivateKey,\n\tlocalpeer.LocalPeer,\n\tnetwork.Network,\n\tcontext.Context,\n) {\n\tctx := context.New(context.WithCorrelationID(name))\n\n\t\/\/ identity key\n\topk, err := crypto.GenerateEd25519PrivateKey()\n\tassert.NoError(t, err)\n\n\t\/\/ peer key\n\tpk, err := crypto.GenerateEd25519PrivateKey()\n\tassert.NoError(t, err)\n\n\t\/\/ peer certificate\n\tc, err := object.NewCertificate(\n\t\tpk.PublicKey(),\n\t\topk,\n\t)\n\trequire.NoError(t, err)\n\n\tkc := localpeer.New()\n\tkc.PutPrimaryPeerKey(pk)\n\tkc.PutPrimaryIdentityKey(opk)\n\tkc.PutCertificate(c)\n\n\tn := network.New(\n\t\tctx,\n\t\tnetwork.WithLocalPeer(kc),\n\t)\n\n\t_, err = n.Listen(ctx, \"127.0.0.1:0\", network.ListenOnLocalIPs)\n\trequire.NoError(t, err)\n\n\treturn opk, pk, kc, n, ctx\n}\n\nfunc gatherPeers(p <-chan *peer.Peer) []*peer.Peer {\n\tps := []*peer.Peer{}\n\tfor p := range p {\n\t\tp := p\n\t\tps = append(ps, p)\n\t}\n\treturn peer.Unique(ps)\n}\n<commit_msg>fix(resolver): fix flaky TwoPeersCanFindEachOther test<commit_after>package resolver\n\nimport (\n\t\"crypto\/rand\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\n\t\"nimona.io\/pkg\/context\"\n\t\"nimona.io\/pkg\/crypto\"\n\t\"nimona.io\/pkg\/localpeer\"\n\t\"nimona.io\/pkg\/network\"\n\t\"nimona.io\/pkg\/object\"\n\t\"nimona.io\/pkg\/peer\"\n)\n\nfunc TestResolver_TwoPeersCanFindEachOther(t *testing.T) {\n\t_, k0, kc0, n0, ctx0 := newPeer(t, \"peer0\")\n\n\td0 := New(\n\t\tctx0,\n\t\tn0,\n\t)\n\n\tba := []*peer.Peer{\n\t\t{\n\t\t\tAddresses: n0.LocalPeer().GetAddresses(),\n\t\t\tMetadata: object.Metadata{\n\t\t\t\tOwner: kc0.GetPrimaryPeerKey().PublicKey(),\n\t\t\t},\n\t\t},\n\t}\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t_, k1, _, n1, ctx1 := newPeer(t, \"peer1\")\n\n\td1 := New(\n\t\tctx1,\n\t\tn1,\n\t\tWithBoostrapPeers(ba),\n\t)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\tctx := context.New(\n\t\tcontext.WithCorrelationID(\"req1\"),\n\t\tcontext.WithTimeout(time.Second),\n\t)\n\n\tpeersChan, err := d1.Lookup(ctx, LookupByOwner(k0.PublicKey()))\n\n\tpeers := gatherPeers(peersChan)\n\trequire.NoError(t, err)\n\trequire.Len(t, peers, 1)\n\trequire.ElementsMatch(t, n0.LocalPeer().GetAddresses(), peers[0].Addresses)\n\n\tctxR2 := context.New(\n\t\tcontext.WithCorrelationID(\"req2\"),\n\t\tcontext.WithTimeout(time.Second),\n\t)\n\tpeersChan, err = d0.Lookup(ctxR2, LookupByOwner(k1.PublicKey()))\n\tpeers = gatherPeers(peersChan)\n\trequire.NoError(t, err)\n\trequire.Len(t, peers, 1)\n\trequire.ElementsMatch(t, n1.LocalPeer().GetAddresses(), peers[0].Addresses)\n}\n\nfunc TestResolver_TwoPeersAndOneBootstrapCanFindEachOther(t *testing.T) {\n\t_, k0, kc0, n0, ctx0 := newPeer(t, \"peer0\")\n\n\t\/\/ bootstrap node\n\tNew(ctx0, n0)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t_, k1, _, n1, ctx1 := newPeer(t, \"peer1\")\n\t_, k2, _, n2, ctx2 := newPeer(t, \"peer2\")\n\n\t\/\/ bootstrap address\n\tba := []*peer.Peer{\n\t\t{\n\t\t\tAddresses: n0.LocalPeer().GetAddresses(),\n\t\t\tMetadata: object.Metadata{\n\t\t\t\tOwner: kc0.GetPrimaryPeerKey().PublicKey(),\n\t\t\t},\n\t\t},\n\t}\n\n\t\/\/ node 1\n\td1 := New(\n\t\tctx1,\n\t\tn1,\n\t\tWithBoostrapPeers(ba),\n\t)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t\/\/ node 2\n\td2 := New(\n\t\tctx2,\n\t\tn2,\n\t\tWithBoostrapPeers(ba),\n\t)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t\/\/ find bootstrap from node1\n\tctx := context.New(\n\t\tcontext.WithCorrelationID(\"req1\"),\n\t\tcontext.WithTimeout(time.Second*2),\n\t)\n\tpeersChan, err := d1.Lookup(ctx, LookupByOwner(k0.PublicKey()))\n\tpeers := gatherPeers(peersChan)\n\trequire.NoError(t, err)\n\trequire.Len(t, peers, 1)\n\trequire.ElementsMatch(t, n0.LocalPeer().GetAddresses(), peers[0].Addresses)\n\n\t\/\/ find node 1 from node 2\n\tctx = context.New(\n\t\tcontext.WithCorrelationID(\"req2\"),\n\t\tcontext.WithTimeout(time.Second*2),\n\t)\n\tpeersChan, err = d2.Lookup(ctx, LookupByOwner(k1.PublicKey()))\n\tpeers = gatherPeers(peersChan)\n\trequire.NoError(t, err)\n\trequire.Len(t, peers, 1)\n\trequire.ElementsMatch(t, n1.LocalPeer().GetAddresses(), peers[0].Addresses)\n\n\t\/\/ find node 2 from node 1\n\tctx = context.New(\n\t\tcontext.WithCorrelationID(\"req3\"),\n\t\tcontext.WithTimeout(time.Second*2),\n\t)\n\n\tpeersChan, err = d1.Lookup(ctx, LookupByOwner(k2.PublicKey()))\n\tpeers = gatherPeers(peersChan)\n\trequire.NoError(t, err)\n\trequire.Len(t, peers, 1)\n\trequire.ElementsMatch(t, n2.LocalPeer().GetAddresses(), peers[0].Addresses)\n}\n\nfunc TestResolver_TwoPeersAndOneBootstrapCanProvide(t *testing.T) {\n\t_, k0, kc0, n0, ctx0 := newPeer(t, \"peer0\")\n\t_, k1, kc1, n1, ctx1 := newPeer(t, \"peer1\")\n\t_, k2, _, n2, ctx2 := newPeer(t, \"peer2\")\n\n\t\/\/ make peer 1 a provider\n\ttoken := make([]byte, 32)\n\trand.Read(token) \/\/ nolint: errcheck\n\tch := object.Hash(\"foo\")\n\tkc1.PutContentHashes(ch)\n\n\t\/\/ print peer info\n\tfmt.Println(\"0\", k0.PublicKey(), n0.LocalPeer().GetAddresses())\n\tfmt.Println(\"1\", k1.PublicKey(), n1.LocalPeer().GetAddresses())\n\tfmt.Println(\"2\", k2.PublicKey(), n2.LocalPeer().GetAddresses())\n\n\t\/\/ bootstrap peer\n\td0 := New(\n\t\tctx0,\n\t\tn0,\n\t)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t\/\/ bootstrap address\n\tba := []*peer.Peer{\n\t\t{\n\t\t\tAddresses: n0.LocalPeer().GetAddresses(),\n\t\t\tMetadata: object.Metadata{\n\t\t\t\tOwner: kc0.GetPrimaryPeerKey().PublicKey(),\n\t\t\t},\n\t\t},\n\t}\n\n\t\/\/ peer 1\n\tNew(\n\t\tctx1,\n\t\tn1,\n\t\tWithBoostrapPeers(ba),\n\t)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t\/\/ peer 2\n\td2 := New(\n\t\tctx2,\n\t\tn2,\n\t\tWithBoostrapPeers(ba),\n\t)\n\n\ttime.Sleep(time.Millisecond * 100)\n\n\t\/\/ find peer 1 from peer 2\n\tctx := context.New(\n\t\tcontext.WithCorrelationID(\"req1\"),\n\t\tcontext.WithTimeout(time.Second),\n\t)\n\tprovidersChan, err := d2.Lookup(ctx, LookupByContentHash(ch))\n\trequire.NoError(t, err)\n\tproviders := gatherPeers(providersChan)\n\trequire.Len(t, providers, 1)\n\trequire.Equal(t, k1.PublicKey(), providers[0].PublicKey())\n\n\t\/\/ find peer 1 from bootstrap\n\tctx = context.New(\n\t\tcontext.WithCorrelationID(\"req2\"),\n\t\tcontext.WithTimeout(time.Second*2),\n\t)\n\tprovidersChan, err = d0.Lookup(ctx, LookupByContentHash(ch))\n\trequire.NoError(t, err)\n\tproviders = gatherPeers(providersChan)\n\trequire.Len(t, providers, 1)\n\trequire.Equal(t, k1.PublicKey(), providers[0].PublicKey())\n}\n\n\/\/ nolint: gocritic\nfunc newPeer(\n\tt *testing.T,\n\tname string,\n) (\n\tcrypto.PrivateKey,\n\tcrypto.PrivateKey,\n\tlocalpeer.LocalPeer,\n\tnetwork.Network,\n\tcontext.Context,\n) {\n\tctx := context.New(context.WithCorrelationID(name))\n\n\t\/\/ identity key\n\topk, err := crypto.GenerateEd25519PrivateKey()\n\tassert.NoError(t, err)\n\n\t\/\/ peer key\n\tpk, err := crypto.GenerateEd25519PrivateKey()\n\tassert.NoError(t, err)\n\n\t\/\/ peer certificate\n\tc, err := object.NewCertificate(\n\t\tpk.PublicKey(),\n\t\topk,\n\t)\n\trequire.NoError(t, err)\n\n\tkc := localpeer.New()\n\tkc.PutPrimaryPeerKey(pk)\n\tkc.PutPrimaryIdentityKey(opk)\n\tkc.PutCertificate(c)\n\n\tn := network.New(\n\t\tctx,\n\t\tnetwork.WithLocalPeer(kc),\n\t)\n\n\t_, err = n.Listen(ctx, \"127.0.0.1:0\", network.ListenOnLocalIPs)\n\trequire.NoError(t, err)\n\n\treturn opk, pk, kc, n, ctx\n}\n\nfunc gatherPeers(p <-chan *peer.Peer) []*peer.Peer {\n\tps := []*peer.Peer{}\n\tfor p := range p {\n\t\tp := p\n\t\tps = append(ps, p)\n\t}\n\treturn peer.Unique(ps)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage api\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io\/api\/core\/v1\"\n\tpolicyv1 \"k8s.io\/api\/policy\/v1beta1\"\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n\n\tarbcorev1 \"github.com\/kubernetes-incubator\/kube-arbitrator\/pkg\/apis\/scheduling\/v1alpha1\"\n\t\"github.com\/kubernetes-incubator\/kube-arbitrator\/pkg\/apis\/utils\"\n)\n\ntype TaskID types.UID\n\ntype TaskInfo struct {\n\tUID TaskID\n\tJob JobID\n\n\tName      string\n\tNamespace string\n\n\tResreq *Resource\n\n\tNodeName string\n\tStatus   TaskStatus\n\tPriority int32\n\n\tPod *v1.Pod\n}\n\nfunc getJobID(pod *v1.Pod) JobID {\n\tif len(pod.Annotations) != 0 {\n\t\tif gn, found := pod.Annotations[arbcorev1.GroupNameAnnotationKey]; found && len(gn) != 0 {\n\t\t\t\/\/ Make sure Pod and PodGroup belong to the same namespace.\n\t\t\tjobID := fmt.Sprintf(\"%s\/%s\", pod.Namespace, gn)\n\t\t\treturn JobID(jobID)\n\t\t}\n\t}\n\treturn JobID(utils.GetController(pod))\n}\n\nfunc NewTaskInfo(pod *v1.Pod) *TaskInfo {\n\treq := EmptyResource()\n\n\t\/\/ TODO(k82cn): also includes initContainers' resource.\n\tfor _, c := range pod.Spec.Containers {\n\t\treq.Add(NewResource(c.Resources.Requests))\n\t}\n\n\tti := &TaskInfo{\n\t\tUID:       TaskID(pod.UID),\n\t\tJob:       getJobID(pod),\n\t\tName:      pod.Name,\n\t\tNamespace: pod.Namespace,\n\t\tNodeName:  pod.Spec.NodeName,\n\t\tStatus:    getTaskStatus(pod),\n\t\tPriority:  1,\n\n\t\tPod:    pod,\n\t\tResreq: req,\n\t}\n\n\tif pod.Spec.Priority != nil {\n\t\tti.Priority = *pod.Spec.Priority\n\t}\n\n\treturn ti\n}\n\nfunc (ti *TaskInfo) Clone() *TaskInfo {\n\treturn &TaskInfo{\n\t\tUID:       ti.UID,\n\t\tJob:       ti.Job,\n\t\tName:      ti.Name,\n\t\tNamespace: ti.Namespace,\n\t\tNodeName:  ti.NodeName,\n\t\tStatus:    ti.Status,\n\t\tPriority:  ti.Priority,\n\t\tPod:       ti.Pod,\n\t\tResreq:    ti.Resreq.Clone(),\n\t}\n}\n\nfunc (ti TaskInfo) String() string {\n\treturn fmt.Sprintf(\"Task (%v:%v\/%v): job %v, status %v, pri %v, resreq %v\",\n\t\tti.UID, ti.Namespace, ti.Name, ti.Job, ti.Status, ti.Priority, ti.Resreq)\n}\n\n\/\/ JobID is the type of JobInfo's ID.\ntype JobID types.UID\n\ntype tasksMap map[TaskID]*TaskInfo\n\ntype JobInfo struct {\n\tUID JobID\n\n\tName      string\n\tNamespace string\n\n\tQueue QueueID\n\n\tPriority int\n\n\tNodeSelector map[string]string\n\tMinAvailable int32\n\n\t\/\/ All tasks of the Job.\n\tTaskStatusIndex map[TaskStatus]tasksMap\n\tTasks           tasksMap\n\n\tAllocated    *Resource\n\tTotalRequest *Resource\n\n\tPodGroup *arbcorev1.PodGroup\n\n\t\/\/ TODO(k82cn): keep backward compatbility, removed it when v1alpha1 finalized.\n\tPDB *policyv1.PodDisruptionBudget\n}\n\nfunc NewJobInfo(uid JobID) *JobInfo {\n\treturn &JobInfo{\n\t\tUID: uid,\n\n\t\tMinAvailable: 0,\n\t\tNodeSelector: make(map[string]string),\n\n\t\tAllocated:    EmptyResource(),\n\t\tTotalRequest: EmptyResource(),\n\n\t\tTaskStatusIndex: map[TaskStatus]tasksMap{},\n\t\tTasks:           tasksMap{},\n\t}\n}\n\nfunc (ji *JobInfo) UnsetPodGroup() {\n\tji.PodGroup = nil\n}\n\nfunc (ji *JobInfo) SetPodGroup(pg *arbcorev1.PodGroup) {\n\tji.Name = pg.Name\n\tji.Namespace = pg.Namespace\n\tji.MinAvailable = pg.Spec.NumMember\n\n\tif len(pg.Spec.Queue) == 0 {\n\t\tji.Queue = QueueID(pg.Namespace)\n\t} else {\n\t\tji.Queue = QueueID(pg.Spec.Queue)\n\t}\n\n\tji.PodGroup = pg\n}\n\nfunc (ji *JobInfo) SetPDB(pdb *policyv1.PodDisruptionBudget) {\n\tji.Name = pdb.Name\n\tji.MinAvailable = pdb.Spec.MinAvailable.IntVal\n\tji.Namespace = pdb.Namespace\n\tji.Queue = QueueID(pdb.Namespace)\n\n\tji.PDB = pbd\n}\n\nfunc (ji *JobInfo) UnsetPDB() {\n\tji.PDB = nil\n}\n\nfunc (ji *JobInfo) GetTasks(statuses ...TaskStatus) []*TaskInfo {\n\tvar res []*TaskInfo\n\n\tfor _, status := range statuses {\n\t\tif tasks, found := ji.TaskStatusIndex[status]; found {\n\t\t\tfor _, task := range tasks {\n\t\t\t\tres = append(res, task.Clone())\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}\n\nfunc (ji *JobInfo) addTaskIndex(ti *TaskInfo) {\n\tif _, found := ji.TaskStatusIndex[ti.Status]; !found {\n\t\tji.TaskStatusIndex[ti.Status] = tasksMap{}\n\t}\n\n\tji.TaskStatusIndex[ti.Status][ti.UID] = ti\n}\n\nfunc (ji *JobInfo) AddTaskInfo(ti *TaskInfo) {\n\tji.Tasks[ti.UID] = ti\n\tji.addTaskIndex(ti)\n\n\tji.TotalRequest.Add(ti.Resreq)\n\n\tif AllocatedStatus(ti.Status) {\n\t\tji.Allocated.Add(ti.Resreq)\n\t}\n}\n\nfunc (ji *JobInfo) UpdateTaskStatus(task *TaskInfo, status TaskStatus) error {\n\tif err := validateStatusUpdate(task.Status, status); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Remove the task from the task list firstly\n\tji.DeleteTaskInfo(task)\n\n\t\/\/ Update task's status to the target status\n\ttask.Status = status\n\tji.AddTaskInfo(task)\n\n\treturn nil\n}\n\nfunc (ji *JobInfo) deleteTaskIndex(ti *TaskInfo) {\n\tif tasks, found := ji.TaskStatusIndex[ti.Status]; found {\n\t\tdelete(tasks, ti.UID)\n\n\t\tif len(tasks) == 0 {\n\t\t\tdelete(ji.TaskStatusIndex, ti.Status)\n\t\t}\n\t}\n}\n\nfunc (ji *JobInfo) DeleteTaskInfo(ti *TaskInfo) error {\n\tif task, found := ji.Tasks[ti.UID]; found {\n\t\tji.TotalRequest.Sub(task.Resreq)\n\n\t\tif AllocatedStatus(task.Status) {\n\t\t\tji.Allocated.Sub(task.Resreq)\n\t\t}\n\n\t\tdelete(ji.Tasks, task.UID)\n\n\t\tji.deleteTaskIndex(task)\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"failed to find task <%v\/%v> in job <%v\/%v>\",\n\t\tti.Namespace, ti.Name, ji.Namespace, ji.Name)\n}\n\nfunc (ji *JobInfo) Clone() *JobInfo {\n\tinfo := &JobInfo{\n\t\tUID:       ji.UID,\n\t\tName:      ji.Name,\n\t\tNamespace: ji.Namespace,\n\t\tQueue:     ji.Queue,\n\n\t\tMinAvailable: ji.MinAvailable,\n\t\tNodeSelector: map[string]string{},\n\t\tAllocated:    ji.Allocated.Clone(),\n\t\tTotalRequest: ji.TotalRequest.Clone(),\n\n\t\tPDB:      ji.PDB,\n\t\tPodGroup: ji.PodGroup,\n\n\t\tTaskStatusIndex: map[TaskStatus]tasksMap{},\n\t\tTasks:           tasksMap{},\n\t}\n\n\tfor k, v := range ji.NodeSelector {\n\t\tinfo.NodeSelector[k] = v\n\t}\n\n\tfor _, task := range ji.Tasks {\n\t\tinfo.AddTaskInfo(task.Clone())\n\t}\n\n\treturn info\n}\n\nfunc (ji JobInfo) String() string {\n\tres := \"\"\n\n\ti := 0\n\tfor _, task := range ji.Tasks {\n\t\tres = res + fmt.Sprintf(\"\\n\\t %d: %v\", i, task)\n\t\ti++\n\t}\n\n\treturn fmt.Sprintf(\"Job (%v): name %v, minAvailable %d\", ji.UID, ji.Name, ji.MinAvailable) + res\n}\n<commit_msg>fix typos<commit_after>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage api\n\nimport (\n\t\"fmt\"\n\n\t\"k8s.io\/api\/core\/v1\"\n\tpolicyv1 \"k8s.io\/api\/policy\/v1beta1\"\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n\n\tarbcorev1 \"github.com\/kubernetes-incubator\/kube-arbitrator\/pkg\/apis\/scheduling\/v1alpha1\"\n\t\"github.com\/kubernetes-incubator\/kube-arbitrator\/pkg\/apis\/utils\"\n)\n\ntype TaskID types.UID\n\ntype TaskInfo struct {\n\tUID TaskID\n\tJob JobID\n\n\tName      string\n\tNamespace string\n\n\tResreq *Resource\n\n\tNodeName string\n\tStatus   TaskStatus\n\tPriority int32\n\n\tPod *v1.Pod\n}\n\nfunc getJobID(pod *v1.Pod) JobID {\n\tif len(pod.Annotations) != 0 {\n\t\tif gn, found := pod.Annotations[arbcorev1.GroupNameAnnotationKey]; found && len(gn) != 0 {\n\t\t\t\/\/ Make sure Pod and PodGroup belong to the same namespace.\n\t\t\tjobID := fmt.Sprintf(\"%s\/%s\", pod.Namespace, gn)\n\t\t\treturn JobID(jobID)\n\t\t}\n\t}\n\treturn JobID(utils.GetController(pod))\n}\n\nfunc NewTaskInfo(pod *v1.Pod) *TaskInfo {\n\treq := EmptyResource()\n\n\t\/\/ TODO(k82cn): also includes initContainers' resource.\n\tfor _, c := range pod.Spec.Containers {\n\t\treq.Add(NewResource(c.Resources.Requests))\n\t}\n\n\tti := &TaskInfo{\n\t\tUID:       TaskID(pod.UID),\n\t\tJob:       getJobID(pod),\n\t\tName:      pod.Name,\n\t\tNamespace: pod.Namespace,\n\t\tNodeName:  pod.Spec.NodeName,\n\t\tStatus:    getTaskStatus(pod),\n\t\tPriority:  1,\n\n\t\tPod:    pod,\n\t\tResreq: req,\n\t}\n\n\tif pod.Spec.Priority != nil {\n\t\tti.Priority = *pod.Spec.Priority\n\t}\n\n\treturn ti\n}\n\nfunc (ti *TaskInfo) Clone() *TaskInfo {\n\treturn &TaskInfo{\n\t\tUID:       ti.UID,\n\t\tJob:       ti.Job,\n\t\tName:      ti.Name,\n\t\tNamespace: ti.Namespace,\n\t\tNodeName:  ti.NodeName,\n\t\tStatus:    ti.Status,\n\t\tPriority:  ti.Priority,\n\t\tPod:       ti.Pod,\n\t\tResreq:    ti.Resreq.Clone(),\n\t}\n}\n\nfunc (ti TaskInfo) String() string {\n\treturn fmt.Sprintf(\"Task (%v:%v\/%v): job %v, status %v, pri %v, resreq %v\",\n\t\tti.UID, ti.Namespace, ti.Name, ti.Job, ti.Status, ti.Priority, ti.Resreq)\n}\n\n\/\/ JobID is the type of JobInfo's ID.\ntype JobID types.UID\n\ntype tasksMap map[TaskID]*TaskInfo\n\ntype JobInfo struct {\n\tUID JobID\n\n\tName      string\n\tNamespace string\n\n\tQueue QueueID\n\n\tPriority int\n\n\tNodeSelector map[string]string\n\tMinAvailable int32\n\n\t\/\/ All tasks of the Job.\n\tTaskStatusIndex map[TaskStatus]tasksMap\n\tTasks           tasksMap\n\n\tAllocated    *Resource\n\tTotalRequest *Resource\n\n\tPodGroup *arbcorev1.PodGroup\n\n\t\/\/ TODO(k82cn): keep backward compatbility, removed it when v1alpha1 finalized.\n\tPDB *policyv1.PodDisruptionBudget\n}\n\nfunc NewJobInfo(uid JobID) *JobInfo {\n\treturn &JobInfo{\n\t\tUID: uid,\n\n\t\tMinAvailable: 0,\n\t\tNodeSelector: make(map[string]string),\n\n\t\tAllocated:    EmptyResource(),\n\t\tTotalRequest: EmptyResource(),\n\n\t\tTaskStatusIndex: map[TaskStatus]tasksMap{},\n\t\tTasks:           tasksMap{},\n\t}\n}\n\nfunc (ji *JobInfo) UnsetPodGroup() {\n\tji.PodGroup = nil\n}\n\nfunc (ji *JobInfo) SetPodGroup(pg *arbcorev1.PodGroup) {\n\tji.Name = pg.Name\n\tji.Namespace = pg.Namespace\n\tji.MinAvailable = pg.Spec.NumMember\n\n\tif len(pg.Spec.Queue) == 0 {\n\t\tji.Queue = QueueID(pg.Namespace)\n\t} else {\n\t\tji.Queue = QueueID(pg.Spec.Queue)\n\t}\n\n\tji.PodGroup = pg\n}\n\nfunc (ji *JobInfo) SetPDB(pdb *policyv1.PodDisruptionBudget) {\n\tji.Name = pdb.Name\n\tji.MinAvailable = pdb.Spec.MinAvailable.IntVal\n\tji.Namespace = pdb.Namespace\n\tji.Queue = QueueID(pdb.Namespace)\n\n\tji.PDB = pdb\n}\n\nfunc (ji *JobInfo) UnsetPDB() {\n\tji.PDB = nil\n}\n\nfunc (ji *JobInfo) GetTasks(statuses ...TaskStatus) []*TaskInfo {\n\tvar res []*TaskInfo\n\n\tfor _, status := range statuses {\n\t\tif tasks, found := ji.TaskStatusIndex[status]; found {\n\t\t\tfor _, task := range tasks {\n\t\t\t\tres = append(res, task.Clone())\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res\n}\n\nfunc (ji *JobInfo) addTaskIndex(ti *TaskInfo) {\n\tif _, found := ji.TaskStatusIndex[ti.Status]; !found {\n\t\tji.TaskStatusIndex[ti.Status] = tasksMap{}\n\t}\n\n\tji.TaskStatusIndex[ti.Status][ti.UID] = ti\n}\n\nfunc (ji *JobInfo) AddTaskInfo(ti *TaskInfo) {\n\tji.Tasks[ti.UID] = ti\n\tji.addTaskIndex(ti)\n\n\tji.TotalRequest.Add(ti.Resreq)\n\n\tif AllocatedStatus(ti.Status) {\n\t\tji.Allocated.Add(ti.Resreq)\n\t}\n}\n\nfunc (ji *JobInfo) UpdateTaskStatus(task *TaskInfo, status TaskStatus) error {\n\tif err := validateStatusUpdate(task.Status, status); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Remove the task from the task list firstly\n\tji.DeleteTaskInfo(task)\n\n\t\/\/ Update task's status to the target status\n\ttask.Status = status\n\tji.AddTaskInfo(task)\n\n\treturn nil\n}\n\nfunc (ji *JobInfo) deleteTaskIndex(ti *TaskInfo) {\n\tif tasks, found := ji.TaskStatusIndex[ti.Status]; found {\n\t\tdelete(tasks, ti.UID)\n\n\t\tif len(tasks) == 0 {\n\t\t\tdelete(ji.TaskStatusIndex, ti.Status)\n\t\t}\n\t}\n}\n\nfunc (ji *JobInfo) DeleteTaskInfo(ti *TaskInfo) error {\n\tif task, found := ji.Tasks[ti.UID]; found {\n\t\tji.TotalRequest.Sub(task.Resreq)\n\n\t\tif AllocatedStatus(task.Status) {\n\t\t\tji.Allocated.Sub(task.Resreq)\n\t\t}\n\n\t\tdelete(ji.Tasks, task.UID)\n\n\t\tji.deleteTaskIndex(task)\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"failed to find task <%v\/%v> in job <%v\/%v>\",\n\t\tti.Namespace, ti.Name, ji.Namespace, ji.Name)\n}\n\nfunc (ji *JobInfo) Clone() *JobInfo {\n\tinfo := &JobInfo{\n\t\tUID:       ji.UID,\n\t\tName:      ji.Name,\n\t\tNamespace: ji.Namespace,\n\t\tQueue:     ji.Queue,\n\n\t\tMinAvailable: ji.MinAvailable,\n\t\tNodeSelector: map[string]string{},\n\t\tAllocated:    ji.Allocated.Clone(),\n\t\tTotalRequest: ji.TotalRequest.Clone(),\n\n\t\tPDB:      ji.PDB,\n\t\tPodGroup: ji.PodGroup,\n\n\t\tTaskStatusIndex: map[TaskStatus]tasksMap{},\n\t\tTasks:           tasksMap{},\n\t}\n\n\tfor k, v := range ji.NodeSelector {\n\t\tinfo.NodeSelector[k] = v\n\t}\n\n\tfor _, task := range ji.Tasks {\n\t\tinfo.AddTaskInfo(task.Clone())\n\t}\n\n\treturn info\n}\n\nfunc (ji JobInfo) String() string {\n\tres := \"\"\n\n\ti := 0\n\tfor _, task := range ji.Tasks {\n\t\tres = res + fmt.Sprintf(\"\\n\\t %d: %v\", i, task)\n\t\ti++\n\t}\n\n\treturn fmt.Sprintf(\"Job (%v): name %v, minAvailable %d\", ji.UID, ji.Name, ji.MinAvailable) + res\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage kaniko\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/constants\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/docker\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/kubernetes\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/schema\/v1alpha2\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/util\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\nfunc RunKanikoBuild(ctx context.Context, out io.Writer, artifact *v1alpha2.Artifact, cfg *v1alpha2.KanikoBuild) (string, error) {\n\tdockerfilePath := artifact.DockerArtifact.DockerfilePath\n\n\tinitialTag := util.RandomID()\n\ttarName := \"context.tar.gz\" \/\/ TODO(r2d4): until this is configurable upstream\n\tif err := docker.UploadContextToGCS(ctx, dockerfilePath, artifact.Workspace, cfg.GCSBucket, tarName); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"uploading tar to gcs\")\n\t}\n\n\tclient, err := kubernetes.GetClientset()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"\")\n\t}\n\n\timageList := kubernetes.NewImageList()\n\timageList.Add(constants.DefaultKanikoImage)\n\n\tlogger := kubernetes.NewLogAggregator(out, imageList, kubernetes.NewColorPicker([]*v1alpha2.Artifact{artifact}))\n\tif err := logger.Start(ctx); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"starting log streamer\")\n\t}\n\timageDst := fmt.Sprintf(\"%s:%s\", artifact.ImageName, initialTag)\n\tp, err := client.CoreV1().Pods(cfg.Namespace).Create(&v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName:      \"kaniko\",\n\t\t\tLabels:    map[string]string{\"skaffold-kaniko\": \"skaffold-kaniko\"},\n\t\t\tNamespace: cfg.Namespace,\n\t\t},\n\t\tSpec: v1.PodSpec{\n\t\t\tContainers: []v1.Container{\n\t\t\t\t{\n\t\t\t\t\tName:            \"kaniko\",\n\t\t\t\t\tImage:           constants.DefaultKanikoImage,\n\t\t\t\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\t\t\t\tArgs: []string{\n\t\t\t\t\t\tfmt.Sprintf(\"--dockerfile=%s\", dockerfilePath),\n\t\t\t\t\t\tfmt.Sprintf(\"--bucket=%s\", cfg.GCSBucket),\n\t\t\t\t\t\tfmt.Sprintf(\"--destination=%s\", imageDst),\n\t\t\t\t\t\tfmt.Sprintf(\"-v=%s\", logrus.GetLevel().String()),\n\t\t\t\t\t},\n\t\t\t\t\tVolumeMounts: []v1.VolumeMount{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:      constants.DefaultKanikoSecretName,\n\t\t\t\t\t\t\tMountPath: \"\/secret\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tEnv: []v1.EnvVar{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:  \"GOOGLE_APPLICATION_CREDENTIALS\",\n\t\t\t\t\t\t\tValue: \"\/secret\/kaniko-secret\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumes: []v1.Volume{\n\t\t\t\t{\n\t\t\t\t\tName: constants.DefaultKanikoSecretName,\n\t\t\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\t\t\tSecret: &v1.SecretVolumeSource{\n\t\t\t\t\t\t\tSecretName: cfg.PullSecretName,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tRestartPolicy: v1.RestartPolicyNever,\n\t\t},\n\t})\n\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"creating kaniko pod\")\n\t}\n\n\tdefer func() {\n\t\timageList.Remove(constants.DefaultKanikoImage)\n\t\tif err := client.CoreV1().Pods(cfg.Namespace).Delete(p.Name, &metav1.DeleteOptions{\n\t\t\tGracePeriodSeconds: new(int64),\n\t\t}); err != nil {\n\t\t\tlogrus.Fatalf(\"deleting pod: %s\", err)\n\t\t}\n\t}()\n\n\tif err := kubernetes.WaitForPodComplete(client.CoreV1().Pods(cfg.Namespace), p.Name); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"waiting for pod to complete\")\n\t}\n\n\treturn imageDst, nil\n}\n<commit_msg>Generate pod name<commit_after>\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage kaniko\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/constants\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/docker\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/kubernetes\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/schema\/v1alpha2\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/util\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\nfunc RunKanikoBuild(ctx context.Context, out io.Writer, artifact *v1alpha2.Artifact, cfg *v1alpha2.KanikoBuild) (string, error) {\n\tdockerfilePath := artifact.DockerArtifact.DockerfilePath\n\n\tinitialTag := util.RandomID()\n\ttarName := \"context.tar.gz\" \/\/ TODO(r2d4): until this is configurable upstream\n\tif err := docker.UploadContextToGCS(ctx, dockerfilePath, artifact.Workspace, cfg.GCSBucket, tarName); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"uploading tar to gcs\")\n\t}\n\n\tclient, err := kubernetes.GetClientset()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"\")\n\t}\n\n\timageList := kubernetes.NewImageList()\n\timageList.Add(constants.DefaultKanikoImage)\n\n\tlogger := kubernetes.NewLogAggregator(out, imageList, kubernetes.NewColorPicker([]*v1alpha2.Artifact{artifact}))\n\tif err := logger.Start(ctx); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"starting log streamer\")\n\t}\n\timageDst := fmt.Sprintf(\"%s:%s\", artifact.ImageName, initialTag)\n\tp, err := client.CoreV1().Pods(cfg.Namespace).Create(&v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tGenerateName: \"kaniko\",\n\t\t\tLabels:       map[string]string{\"skaffold-kaniko\": \"skaffold-kaniko\"},\n\t\t\tNamespace:    cfg.Namespace,\n\t\t},\n\t\tSpec: v1.PodSpec{\n\t\t\tContainers: []v1.Container{\n\t\t\t\t{\n\t\t\t\t\tName:            \"kaniko\",\n\t\t\t\t\tImage:           constants.DefaultKanikoImage,\n\t\t\t\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\t\t\t\tArgs: []string{\n\t\t\t\t\t\tfmt.Sprintf(\"--dockerfile=%s\", dockerfilePath),\n\t\t\t\t\t\tfmt.Sprintf(\"--bucket=%s\", cfg.GCSBucket),\n\t\t\t\t\t\tfmt.Sprintf(\"--destination=%s\", imageDst),\n\t\t\t\t\t\tfmt.Sprintf(\"-v=%s\", logrus.GetLevel().String()),\n\t\t\t\t\t},\n\t\t\t\t\tVolumeMounts: []v1.VolumeMount{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:      constants.DefaultKanikoSecretName,\n\t\t\t\t\t\t\tMountPath: \"\/secret\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tEnv: []v1.EnvVar{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:  \"GOOGLE_APPLICATION_CREDENTIALS\",\n\t\t\t\t\t\t\tValue: \"\/secret\/kaniko-secret\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumes: []v1.Volume{\n\t\t\t\t{\n\t\t\t\t\tName: constants.DefaultKanikoSecretName,\n\t\t\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\t\t\tSecret: &v1.SecretVolumeSource{\n\t\t\t\t\t\t\tSecretName: cfg.PullSecretName,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tRestartPolicy: v1.RestartPolicyNever,\n\t\t},\n\t})\n\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"creating kaniko pod\")\n\t}\n\n\tdefer func() {\n\t\timageList.Remove(constants.DefaultKanikoImage)\n\t\tif err := client.CoreV1().Pods(cfg.Namespace).Delete(p.Name, &metav1.DeleteOptions{\n\t\t\tGracePeriodSeconds: new(int64),\n\t\t}); err != nil {\n\t\t\tlogrus.Fatalf(\"deleting pod: %s\", err)\n\t\t}\n\t}()\n\n\tif err := kubernetes.WaitForPodComplete(client.CoreV1().Pods(cfg.Namespace), p.Name); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"waiting for pod to complete\")\n\t}\n\n\treturn imageDst, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package proxy is a transparent proxy built on the go-micro\/server\npackage proxy\n\n<commit_msg>Add proxy interface<commit_after>\/\/ Package proxy is a transparent proxy built on the go-micro\/server\npackage proxy\n\nimport (\n\t\"context\"\n\n\t\"github.com\/micro\/go-micro\/init\"\n\t\"github.com\/micro\/go-micro\/server\"\n)\n\n\/\/ Proxy can be used as a proxy server for go-micro services\ntype Proxy interface {\n\tinit.Options\n\t\/\/ ServeRequest will serve a request\n\tServeRequest(context.Context, Request, Response) error\n\t\/\/ run the proxy\n\tRun() error\n}\n<|endoftext|>"}
{"text":"<commit_before>package proxy\n\nimport (\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"os\"\n\t\"regexp\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/docker\/docker\/pkg\/tlsconfig\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/rancher\/websocket-proxy\/k8s\"\n\t\"github.com\/rancher\/websocket-proxy\/proxy\/apiinterceptor\"\n\t\"github.com\/rancher\/websocket-proxy\/proxy\/proxyprotocol\"\n\tproxyTls \"github.com\/rancher\/websocket-proxy\/proxy\/tls\"\n)\n\nvar slashRegex = regexp.MustCompile(\"[\/]{2,}\")\n\ntype Starter struct {\n\tBackendPaths       []string\n\tFrontendPaths      []string\n\tFrontendHTTPPaths  []string\n\tStatsPaths         []string\n\tCattleProxyPaths   []string\n\tCattleWSProxyPaths []string\n\tConfig             *Config\n}\n\nfunc (s *Starter) StartProxy() error {\n\tswitcher := NewSwitcher(s.Config)\n\n\tbackendMultiplexers := make(map[string]*multiplexer)\n\tbpm := &backendProxyManager{\n\t\tmultiplexers: backendMultiplexers,\n\t\tmu:           &sync.RWMutex{},\n\t}\n\n\tfrontendHandler := switcher.Wrap(&FrontendHandler{\n\t\tbackend:         bpm,\n\t\tparsedPublicKey: s.Config.PublicKey,\n\t})\n\n\tstatsHandler := switcher.Wrap(&StatsHandler{\n\t\tbackend:         bpm,\n\t\tparsedPublicKey: s.Config.PublicKey,\n\t})\n\n\tbackendHandler := switcher.Wrap(&BackendHandler{\n\t\tproxyManager:    bpm,\n\t\tparsedPublicKey: s.Config.PublicKey,\n\t})\n\n\tfrontendHTTPHandler := switcher.Wrap(&FrontendHTTPHandler{\n\t\tFrontendHandler: FrontendHandler{\n\t\t\tbackend:         bpm,\n\t\t\tparsedPublicKey: s.Config.PublicKey,\n\t\t},\n\t\tHTTPSPorts:  s.Config.ProxyProtoHTTPSPorts,\n\t\tTokenLookup: NewTokenLookup(s.Config.CattleAddr),\n\t})\n\n\tcattleProxy, cattleWsProxy, err := newCattleProxies(s.Config)\n\tif err != nil {\n\t\tlog.Fatalf(\"Couldn't create cattle proxies: %v\", err)\n\t}\n\n\trouter := mux.NewRouter()\n\n\trouter.HandleFunc(\"\/version\", k8s.Version)\n\trouter.HandleFunc(\"\/swaggerapi\/api\/v1\", k8s.Swagger)\n\n\tfor _, p := range s.BackendPaths {\n\t\trouter.Handle(p, backendHandler).Methods(\"GET\")\n\t}\n\tfor _, p := range s.FrontendPaths {\n\t\trouter.Handle(p, frontendHandler).Methods(\"GET\")\n\t}\n\tfor _, p := range s.FrontendHTTPPaths {\n\t\trouter.Handle(p, frontendHTTPHandler).Methods(\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\")\n\t}\n\tfor _, p := range s.StatsPaths {\n\t\trouter.Handle(p, statsHandler).Methods(\"GET\")\n\t}\n\n\tif s.Config.CattleAddr != \"\" {\n\t\tfor _, p := range s.CattleWSProxyPaths {\n\t\t\trouter.Handle(p, cattleWsProxy)\n\t\t}\n\n\t\tfor _, p := range s.CattleProxyPaths {\n\t\t\trouter.Handle(p, cattleProxy)\n\t\t}\n\t}\n\n\tif s.Config.ParentPid != 0 {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tprocess, err := os.FindProcess(s.Config.ParentPid)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"Failed to find process: %s\\n\", err)\n\t\t\t\t} else {\n\t\t\t\t\terr := process.Signal(syscall.Signal(0))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Parent process went away. Shutting down.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttime.Sleep(time.Millisecond * 250)\n\t\t\t}\n\t\t}()\n\t}\n\n\tpcRouter := &pathCleaner{\n\t\trouter: router,\n\t}\n\n\tswarmHandler := &SwarmHandler{\n\t\tFrontendHandler: frontendHTTPHandler,\n\t\tDefaultHandler:  pcRouter,\n\t}\n\n\tserver := &http.Server{\n\t\tHandler:   swarmHandler,\n\t\tAddr:      s.Config.ListenAddr,\n\t\tConnState: proxyprotocol.StateCleanup,\n\t}\n\n\tlistener, err := net.Listen(\"tcp\", s.Config.ListenAddr)\n\tif err != nil {\n\t\tlog.Fatalf(\"Couldn't create listener: %s\\n\", err)\n\t}\n\n\tlistener = &proxyprotocol.Listener{listener}\n\n\tif s.Config.TLSListenAddr != \"\" {\n\t\ttlsConfig, err := s.setupTLS()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif s.Config.TLSListenAddr == s.Config.ListenAddr {\n\t\t\tlistener = &proxyTls.SplitListener{\n\t\t\t\tListener: listener,\n\t\t\t\tConfig:   tlsConfig,\n\t\t\t}\n\t\t} else {\n\t\t\ttlsListener, err := net.Listen(\"tcp\", s.Config.TLSListenAddr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttlsListener = &proxyprotocol.Listener{tlsListener}\n\t\t\tgo func() {\n\t\t\t\tdefer listener.Close()\n\t\t\t\tlog.Error(server.Serve(tls.NewListener(tlsListener, tlsConfig)))\n\t\t\t}()\n\t\t}\n\t}\n\n\terr = server.Serve(listener)\n\treturn err\n}\n\nfunc (s *Starter) setupTLS() (*tls.Config, error) {\n\tif s.Config.CattleAccessKey == \"\" {\n\t\treturn nil, fmt.Errorf(\"No access key supplied to download cert\")\n\t}\n\n\tcerts, err := s.Config.GetCerts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsCert, err := tls.X509KeyPair(certs.Cert, certs.Key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientCas := x509.NewCertPool()\n\tif !clientCas.AppendCertsFromPEM(certs.CA) {\n\t\treturn nil, err\n\t}\n\n\ttlsConfig := tlsconfig.ServerDefault()\n\ttlsConfig.ClientAuth = tls.VerifyClientCertIfGiven\n\ttlsConfig.ClientCAs = clientCas\n\ttlsConfig.Certificates = []tls.Certificate{tlsCert}\n\n\treturn tlsConfig, nil\n}\n\ntype pathCleaner struct {\n\trouter *mux.Router\n}\n\nfunc (p *pathCleaner) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tif cleanedPath := p.cleanPath(req.URL.Path); cleanedPath != req.URL.Path {\n\t\treq.URL.Path = cleanedPath\n\t\treq.URL.Scheme = \"http\"\n\t}\n\tp.router.ServeHTTP(rw, req)\n}\n\nfunc (p *pathCleaner) cleanPath(path string) string {\n\treturn slashRegex.ReplaceAllString(path, \"\/\")\n}\n\nfunc newWSProxy(config *Config) http.Handler {\n\tcattleAddr := config.CattleAddr\n\tdirector := func(req *http.Request) {\n\t\treq.URL.Scheme = \"http\"\n\t\treq.URL.Host = cattleAddr\n\t}\n\n\tcattleProxy := &httputil.ReverseProxy{\n\t\tDirector:      director,\n\t\tFlushInterval: time.Millisecond * 100,\n\t}\n\n\treverseProxy := &proxyProtocolConverter{\n\t\tp:          cattleProxy,\n\t\thttpsPorts: config.ProxyProtoHTTPSPorts,\n\t}\n\n\twsProxy := &cattleWSProxy{\n\t\treverseProxy: reverseProxy,\n\t\tcattleAddr:   cattleAddr,\n\t}\n\n\treturn wsProxy\n}\n\nfunc newCattleProxies(config *Config) (*proxyProtocolConverter, *cattleWSProxy, error) {\n\tcattleAddr := config.CattleAddr\n\n\tapiProxyHandler, err := apiinterceptor.NewInterceptor(config.APIInterceptorConfigFile, cattleAddr)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"Couldn't create API interceptor\")\n\t}\n\n\treverseProxy := &proxyProtocolConverter{\n\t\thttpsPorts: config.ProxyProtoHTTPSPorts,\n\t\tp:          apiProxyHandler,\n\t}\n\n\twsProxy := &cattleWSProxy{\n\t\treverseProxy: reverseProxy,\n\t\tcattleAddr:   cattleAddr,\n\t}\n\n\treturn reverseProxy, wsProxy, nil\n}\n\ntype proxyProtocolConverter struct {\n\thttpsPorts map[int]bool\n\tp          http.Handler\n}\n\nfunc (h *proxyProtocolConverter) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tproxyprotocol.AddHeaders(req, h.httpsPorts)\n\th.p.ServeHTTP(rw, req)\n}\n\ntype cattleWSProxy struct {\n\treverseProxy *proxyProtocolConverter\n\tcattleAddr   string\n}\n\nfunc (h *cattleWSProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tif len(req.Header.Get(\"Upgrade\")) > 0 {\n\t\tproxyprotocol.AddHeaders(req, h.reverseProxy.httpsPorts)\n\t\th.serveWebsocket(rw, req)\n\t} else {\n\t\th.reverseProxy.ServeHTTP(rw, req)\n\t}\n}\n\nfunc (h *cattleWSProxy) serveWebsocket(rw http.ResponseWriter, req *http.Request) {\n\t\/\/ Inspired by https:\/\/groups.google.com\/forum\/#!searchin\/golang-nuts\/httputil.ReverseProxy$20$2B$20websockets\/golang-nuts\/KBx9pDlvFOc\/01vn1qUyVdwJ\n\ttarget := h.cattleAddr\n\td, err := net.Dial(\"tcp\", target)\n\tif err != nil {\n\t\tlog.WithField(\"error\", err).Error(\"Error dialing websocket backend.\")\n\t\thttp.Error(rw, \"Unable to establish websocket connection: can't dial.\", 500)\n\t\treturn\n\t}\n\thj, ok := rw.(http.Hijacker)\n\tif !ok {\n\t\thttp.Error(rw, \"Unable to establish websocket connection: no hijacker.\", 500)\n\t\treturn\n\t}\n\tnc, _, err := hj.Hijack()\n\tif err != nil {\n\t\tlog.WithField(\"error\", err).Error(\"Hijack error.\")\n\t\thttp.Error(rw, \"Unable to establish websocket connection: can't hijack.\", 500)\n\t\treturn\n\t}\n\tdefer nc.Close()\n\tdefer d.Close()\n\n\terr = req.Write(d)\n\tif err != nil {\n\t\tlog.WithField(\"error\", err).Error(\"Error copying request to target.\")\n\t\treturn\n\t}\n\n\terrc := make(chan error, 2)\n\tcp := func(dst io.Writer, src io.Reader) {\n\t\t_, err := io.Copy(dst, src)\n\t\terrc <- err\n\t}\n\tgo cp(d, nc)\n\tgo cp(nc, d)\n\t<-errc\n}\n<commit_msg>Support HEAD in http proxy<commit_after>package proxy\n\nimport (\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"os\"\n\t\"regexp\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/docker\/docker\/pkg\/tlsconfig\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/rancher\/websocket-proxy\/k8s\"\n\t\"github.com\/rancher\/websocket-proxy\/proxy\/apiinterceptor\"\n\t\"github.com\/rancher\/websocket-proxy\/proxy\/proxyprotocol\"\n\tproxyTls \"github.com\/rancher\/websocket-proxy\/proxy\/tls\"\n)\n\nvar slashRegex = regexp.MustCompile(\"[\/]{2,}\")\n\ntype Starter struct {\n\tBackendPaths       []string\n\tFrontendPaths      []string\n\tFrontendHTTPPaths  []string\n\tStatsPaths         []string\n\tCattleProxyPaths   []string\n\tCattleWSProxyPaths []string\n\tConfig             *Config\n}\n\nfunc (s *Starter) StartProxy() error {\n\tswitcher := NewSwitcher(s.Config)\n\n\tbackendMultiplexers := make(map[string]*multiplexer)\n\tbpm := &backendProxyManager{\n\t\tmultiplexers: backendMultiplexers,\n\t\tmu:           &sync.RWMutex{},\n\t}\n\n\tfrontendHandler := switcher.Wrap(&FrontendHandler{\n\t\tbackend:         bpm,\n\t\tparsedPublicKey: s.Config.PublicKey,\n\t})\n\n\tstatsHandler := switcher.Wrap(&StatsHandler{\n\t\tbackend:         bpm,\n\t\tparsedPublicKey: s.Config.PublicKey,\n\t})\n\n\tbackendHandler := switcher.Wrap(&BackendHandler{\n\t\tproxyManager:    bpm,\n\t\tparsedPublicKey: s.Config.PublicKey,\n\t})\n\n\tfrontendHTTPHandler := switcher.Wrap(&FrontendHTTPHandler{\n\t\tFrontendHandler: FrontendHandler{\n\t\t\tbackend:         bpm,\n\t\t\tparsedPublicKey: s.Config.PublicKey,\n\t\t},\n\t\tHTTPSPorts:  s.Config.ProxyProtoHTTPSPorts,\n\t\tTokenLookup: NewTokenLookup(s.Config.CattleAddr),\n\t})\n\n\tcattleProxy, cattleWsProxy, err := newCattleProxies(s.Config)\n\tif err != nil {\n\t\tlog.Fatalf(\"Couldn't create cattle proxies: %v\", err)\n\t}\n\n\trouter := mux.NewRouter()\n\n\trouter.HandleFunc(\"\/version\", k8s.Version)\n\trouter.HandleFunc(\"\/swaggerapi\/api\/v1\", k8s.Swagger)\n\n\tfor _, p := range s.BackendPaths {\n\t\trouter.Handle(p, backendHandler).Methods(\"GET\")\n\t}\n\tfor _, p := range s.FrontendPaths {\n\t\trouter.Handle(p, frontendHandler).Methods(\"GET\")\n\t}\n\tfor _, p := range s.FrontendHTTPPaths {\n\t\trouter.Handle(p, frontendHTTPHandler).Methods(\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"HEAD\")\n\t}\n\tfor _, p := range s.StatsPaths {\n\t\trouter.Handle(p, statsHandler).Methods(\"GET\")\n\t}\n\n\tif s.Config.CattleAddr != \"\" {\n\t\tfor _, p := range s.CattleWSProxyPaths {\n\t\t\trouter.Handle(p, cattleWsProxy)\n\t\t}\n\n\t\tfor _, p := range s.CattleProxyPaths {\n\t\t\trouter.Handle(p, cattleProxy)\n\t\t}\n\t}\n\n\tif s.Config.ParentPid != 0 {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tprocess, err := os.FindProcess(s.Config.ParentPid)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"Failed to find process: %s\\n\", err)\n\t\t\t\t} else {\n\t\t\t\t\terr := process.Signal(syscall.Signal(0))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Parent process went away. Shutting down.\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttime.Sleep(time.Millisecond * 250)\n\t\t\t}\n\t\t}()\n\t}\n\n\tpcRouter := &pathCleaner{\n\t\trouter: router,\n\t}\n\n\tswarmHandler := &SwarmHandler{\n\t\tFrontendHandler: frontendHTTPHandler,\n\t\tDefaultHandler:  pcRouter,\n\t}\n\n\tserver := &http.Server{\n\t\tHandler:   swarmHandler,\n\t\tAddr:      s.Config.ListenAddr,\n\t\tConnState: proxyprotocol.StateCleanup,\n\t}\n\n\tlistener, err := net.Listen(\"tcp\", s.Config.ListenAddr)\n\tif err != nil {\n\t\tlog.Fatalf(\"Couldn't create listener: %s\\n\", err)\n\t}\n\n\tlistener = &proxyprotocol.Listener{listener}\n\n\tif s.Config.TLSListenAddr != \"\" {\n\t\ttlsConfig, err := s.setupTLS()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif s.Config.TLSListenAddr == s.Config.ListenAddr {\n\t\t\tlistener = &proxyTls.SplitListener{\n\t\t\t\tListener: listener,\n\t\t\t\tConfig:   tlsConfig,\n\t\t\t}\n\t\t} else {\n\t\t\ttlsListener, err := net.Listen(\"tcp\", s.Config.TLSListenAddr)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttlsListener = &proxyprotocol.Listener{tlsListener}\n\t\t\tgo func() {\n\t\t\t\tdefer listener.Close()\n\t\t\t\tlog.Error(server.Serve(tls.NewListener(tlsListener, tlsConfig)))\n\t\t\t}()\n\t\t}\n\t}\n\n\terr = server.Serve(listener)\n\treturn err\n}\n\nfunc (s *Starter) setupTLS() (*tls.Config, error) {\n\tif s.Config.CattleAccessKey == \"\" {\n\t\treturn nil, fmt.Errorf(\"No access key supplied to download cert\")\n\t}\n\n\tcerts, err := s.Config.GetCerts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsCert, err := tls.X509KeyPair(certs.Cert, certs.Key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientCas := x509.NewCertPool()\n\tif !clientCas.AppendCertsFromPEM(certs.CA) {\n\t\treturn nil, err\n\t}\n\n\ttlsConfig := tlsconfig.ServerDefault()\n\ttlsConfig.ClientAuth = tls.VerifyClientCertIfGiven\n\ttlsConfig.ClientCAs = clientCas\n\ttlsConfig.Certificates = []tls.Certificate{tlsCert}\n\n\treturn tlsConfig, nil\n}\n\ntype pathCleaner struct {\n\trouter *mux.Router\n}\n\nfunc (p *pathCleaner) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tif cleanedPath := p.cleanPath(req.URL.Path); cleanedPath != req.URL.Path {\n\t\treq.URL.Path = cleanedPath\n\t\treq.URL.Scheme = \"http\"\n\t}\n\tp.router.ServeHTTP(rw, req)\n}\n\nfunc (p *pathCleaner) cleanPath(path string) string {\n\treturn slashRegex.ReplaceAllString(path, \"\/\")\n}\n\nfunc newWSProxy(config *Config) http.Handler {\n\tcattleAddr := config.CattleAddr\n\tdirector := func(req *http.Request) {\n\t\treq.URL.Scheme = \"http\"\n\t\treq.URL.Host = cattleAddr\n\t}\n\n\tcattleProxy := &httputil.ReverseProxy{\n\t\tDirector:      director,\n\t\tFlushInterval: time.Millisecond * 100,\n\t}\n\n\treverseProxy := &proxyProtocolConverter{\n\t\tp:          cattleProxy,\n\t\thttpsPorts: config.ProxyProtoHTTPSPorts,\n\t}\n\n\twsProxy := &cattleWSProxy{\n\t\treverseProxy: reverseProxy,\n\t\tcattleAddr:   cattleAddr,\n\t}\n\n\treturn wsProxy\n}\n\nfunc newCattleProxies(config *Config) (*proxyProtocolConverter, *cattleWSProxy, error) {\n\tcattleAddr := config.CattleAddr\n\n\tapiProxyHandler, err := apiinterceptor.NewInterceptor(config.APIInterceptorConfigFile, cattleAddr)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"Couldn't create API interceptor\")\n\t}\n\n\treverseProxy := &proxyProtocolConverter{\n\t\thttpsPorts: config.ProxyProtoHTTPSPorts,\n\t\tp:          apiProxyHandler,\n\t}\n\n\twsProxy := &cattleWSProxy{\n\t\treverseProxy: reverseProxy,\n\t\tcattleAddr:   cattleAddr,\n\t}\n\n\treturn reverseProxy, wsProxy, nil\n}\n\ntype proxyProtocolConverter struct {\n\thttpsPorts map[int]bool\n\tp          http.Handler\n}\n\nfunc (h *proxyProtocolConverter) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tproxyprotocol.AddHeaders(req, h.httpsPorts)\n\th.p.ServeHTTP(rw, req)\n}\n\ntype cattleWSProxy struct {\n\treverseProxy *proxyProtocolConverter\n\tcattleAddr   string\n}\n\nfunc (h *cattleWSProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {\n\tif len(req.Header.Get(\"Upgrade\")) > 0 {\n\t\tproxyprotocol.AddHeaders(req, h.reverseProxy.httpsPorts)\n\t\th.serveWebsocket(rw, req)\n\t} else {\n\t\th.reverseProxy.ServeHTTP(rw, req)\n\t}\n}\n\nfunc (h *cattleWSProxy) serveWebsocket(rw http.ResponseWriter, req *http.Request) {\n\t\/\/ Inspired by https:\/\/groups.google.com\/forum\/#!searchin\/golang-nuts\/httputil.ReverseProxy$20$2B$20websockets\/golang-nuts\/KBx9pDlvFOc\/01vn1qUyVdwJ\n\ttarget := h.cattleAddr\n\td, err := net.Dial(\"tcp\", target)\n\tif err != nil {\n\t\tlog.WithField(\"error\", err).Error(\"Error dialing websocket backend.\")\n\t\thttp.Error(rw, \"Unable to establish websocket connection: can't dial.\", 500)\n\t\treturn\n\t}\n\thj, ok := rw.(http.Hijacker)\n\tif !ok {\n\t\thttp.Error(rw, \"Unable to establish websocket connection: no hijacker.\", 500)\n\t\treturn\n\t}\n\tnc, _, err := hj.Hijack()\n\tif err != nil {\n\t\tlog.WithField(\"error\", err).Error(\"Hijack error.\")\n\t\thttp.Error(rw, \"Unable to establish websocket connection: can't hijack.\", 500)\n\t\treturn\n\t}\n\tdefer nc.Close()\n\tdefer d.Close()\n\n\terr = req.Write(d)\n\tif err != nil {\n\t\tlog.WithField(\"error\", err).Error(\"Error copying request to target.\")\n\t\treturn\n\t}\n\n\terrc := make(chan error, 2)\n\tcp := func(dst io.Writer, src io.Reader) {\n\t\t_, err := io.Copy(dst, src)\n\t\terrc <- err\n\t}\n\tgo cp(d, nc)\n\tgo cp(nc, d)\n\t<-errc\n}\n<|endoftext|>"}
{"text":"<commit_before>package proxy\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\n\t\"github.com\/andystanton\/proxybastard\/util\"\n\t\"github.com\/deckarep\/golang-set\"\n)\n\nfunc addToMap(frequencyMap map[string]int, value string) map[string]int {\n\tif len(strings.TrimSpace(value)) > 0 {\n\t\tif _, ok := frequencyMap[value]; !ok {\n\t\t\tfrequencyMap[value] = 0\n\t\t}\n\t\tfrequencyMap[value] = frequencyMap[value] + 1\n\t}\n\treturn frequencyMap\n}\n\nfunc awaitInput(prompt string, pattern string, prefix string) string {\n\tvar matched string\n\tvar found bool\n\tfmt.Printf(\"%s%s\\n\", prefix, prompt)\n\tfmt.Printf(\"%s> \", prefix)\n\tfor i := 0; i < 3; i++ {\n\t\treader := bufio.NewReader(os.Stdin)\n\t\ttext, _ := reader.ReadString('\\n')\n\t\trPattern := regexp.MustCompile(pattern)\n\n\t\tif result := strings.TrimSpace(text); rPattern.MatchString(result) {\n\t\t\tmatched = result\n\t\t\tfound = true\n\t\t\tbreak\n\t\t} else if i < 2 {\n\t\t\tlog.Printf(\"%sThat doesn't look right - try again...\\n\", prefix)\n\t\t\tlog.Println()\n\t\t\tfmt.Printf(\"%s%s\\n\", prefix, prompt)\n\t\t\tfmt.Printf(\"%s> \", prefix)\n\t\t} else {\n\t\t\tlog.Println()\n\t\t\tlog.Print(\"Three failed attempts - aborting!\")\n\t\t}\n\t}\n\tif !found {\n\t\tos.Exit(1)\n\t}\n\treturn matched\n}\n\nfunc awaitFileInput(prompt string, prefix string) string {\n\tvar matched string\n\tvar found bool\n\tfmt.Printf(\"%s%s\\n\", prefix, prompt)\n\tfmt.Printf(\"%s> \", prefix)\n\tfor i := 0; i < 3; i++ {\n\t\treader := bufio.NewReader(os.Stdin)\n\t\ttext, _ := reader.ReadString('\\n')\n\t\tif file := util.SanitisePath(strings.TrimSpace(text)); util.FileExists(file) {\n\t\t\tmatched = file\n\t\t\tfound = true\n\t\t\tbreak\n\t\t} else if i < 2 {\n\t\t\tlog.Printf(\"%sThat doesn't look right - try again...\\n\", prefix)\n\t\t\tlog.Println()\n\t\t\tfmt.Printf(\"%s%s\\n\", prefix, prompt)\n\t\t\tfmt.Printf(\"%s> \", prefix)\n\t\t} else {\n\t\t\tlog.Println()\n\t\t\tlog.Print(\"Three failed attempts - aborting!\")\n\t\t}\n\t}\n\tif !found {\n\t\tos.Exit(1)\n\t}\n\treturn matched\n}\n\n\/\/ Setup presents the user with setup options.\nfunc Setup(version string, acceptDefaults bool) {\n\tsuggestedConfiguration := suggestConfiguration()\n\tactualConfiguration := Configuration{}\n\tactualConfiguration.Version = version\n\treadyToWrite := false\n\n\tif acceptDefaults {\n\t\tactualConfiguration = suggestedConfiguration\n\t\treadyToWrite = true\n\t} else {\n\t\thttpProxySet := false\n\t\tif len(suggestedConfiguration.ProxyHost) > 0 {\n\t\t\tmessage := fmt.Sprintf(\"Use suggested http proxy %s:%s? [Yn]\", suggestedConfiguration.ProxyHost, suggestedConfiguration.ProxyPort)\n\t\t\tinput := awaitInput(message, \"(y|n|^$)\", \"\")\n\t\t\thttpProxySet = strings.EqualFold(input, \"y\") || strings.EqualFold(input, \"\")\n\t\t\tactualConfiguration.ProxyHost = suggestedConfiguration.ProxyHost\n\t\t\tactualConfiguration.ProxyPort = suggestedConfiguration.ProxyPort\n\t\t\tfmt.Println()\n\t\t}\n\n\t\tif !httpProxySet {\n\t\t\tproxyHostPattern := \"(?:https?:\/\/)?(.+):(\\\\d+)\"\n\t\t\tproxyHostRegexp := regexp.MustCompile(proxyHostPattern)\n\t\t\tmatches := proxyHostRegexp.FindStringSubmatch(awaitInput(\"Please enter an http proxy e.g. http:\/\/proxybastard:1234\", proxyHostPattern, \"\"))\n\t\t\tactualConfiguration.ProxyHost = fmt.Sprintf(\"http:\/\/%s\", matches[1])\n\t\t\tactualConfiguration.ProxyPort = matches[2]\n\t\t\thttpProxySet = true\n\t\t\tfmt.Println()\n\t\t}\n\n\t\tsocksProxySet := false\n\t\tif len(suggestedConfiguration.SOCKSProxyHost) > 0 {\n\t\t\tmessage := fmt.Sprintf(\"Use suggested SOCKS proxy %s:%s? [Yn]\", suggestedConfiguration.SOCKSProxyHost, suggestedConfiguration.SOCKSProxyPort)\n\t\t\tinput := awaitInput(message, \"(y|n|^$)\", \"\")\n\t\t\tsocksProxySet = strings.EqualFold(input, \"y\") || strings.EqualFold(input, \"\")\n\t\t\tactualConfiguration.SOCKSProxyHost = suggestedConfiguration.SOCKSProxyHost\n\t\t\tactualConfiguration.SOCKSProxyPort = suggestedConfiguration.SOCKSProxyPort\n\t\t\tfmt.Println()\n\t\t}\n\n\t\tif !socksProxySet {\n\t\t\tsocksHostPattern := \"(?:(.+):(\\\\d+)|^$)\"\n\t\t\tsockHostRegexp := regexp.MustCompile(socksHostPattern)\n\t\t\tmatches := sockHostRegexp.FindStringSubmatch(awaitInput(\"Please enter a SOCKS proxy or press return for none e.g. socks.proxybastard:1234\", socksHostPattern, \"\"))\n\t\t\tif len(matches) > 0 {\n\t\t\t\tsocksProxySet = true\n\t\t\t\tactualConfiguration.SOCKSProxyHost = matches[1]\n\t\t\t\tactualConfiguration.SOCKSProxyPort = matches[2]\n\t\t\t}\n\t\t\tfmt.Println()\n\t\t}\n\n\t\tif suggestedConfiguration.Targets != nil {\n\t\t\ttargetsField := reflect.Indirect(reflect.ValueOf(suggestedConfiguration.Targets))\n\t\t\tfor i := 0; i < targetsField.NumField(); i++ {\n\t\t\t\tfieldName := targetsField.Type().Field(i).Name\n\n\t\t\t\t\/\/ valueForFieldRequired := false\n\t\t\t\tif !util.InterfaceIsZero(targetsField.Field(i).Interface()) {\n\t\t\t\t\ttargetField := reflect.Indirect(reflect.ValueOf(targetsField.Field(i).Interface()))\n\n\t\t\t\t\t\/\/ step 1 - go simple and ask if user wants suggested config\n\t\t\t\t\tmessage := fmt.Sprintf(\"Found %s! Use suggested configuration? [Yn]\", fieldName)\n\t\t\t\t\tinput := awaitInput(message, \"(y|n|^$)\", \"\")\n\t\t\t\t\tconfigurationSet := strings.EqualFold(input, \"y\") || strings.EqualFold(input, \"\")\n\n\t\t\t\t\tif configurationSet {\n\t\t\t\t\t\t\/\/ great! put the suggested config in the actual config\n\t\t\t\t\t\tif actualConfiguration.Targets == nil {\n\t\t\t\t\t\t\tactualConfiguration.Targets = &TargetsConfiguration{}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tactualField := reflect.Indirect(reflect.ValueOf(actualConfiguration.Targets)).FieldByName(fieldName)\n\t\t\t\t\t\tactualField.Set(reflect.ValueOf(targetsField.Field(i).Interface()))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Println()\n\n\t\t\t\t\t\tmessage := fmt.Sprintf(\"Enable %s? [Yn]\", fieldName)\n\t\t\t\t\t\tinput := awaitInput(message, \"(y|n|^$)\", \"  \")\n\t\t\t\t\t\tif strings.EqualFold(input, \"y\") || strings.EqualFold(input, \"\") {\n\t\t\t\t\t\t\tif actualConfiguration.Targets == nil {\n\t\t\t\t\t\t\t\tactualConfiguration.Targets = &TargetsConfiguration{}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tactualField := reflect.New(reflect.TypeOf(targetField.Interface())).Interface()\n\t\t\t\t\t\t\treflect.Indirect(reflect.ValueOf(actualField)).FieldByName(\"Enabled\").Set(reflect.ValueOf(true))\n\t\t\t\t\t\t\tfmt.Println()\n\n\t\t\t\t\t\t\tif util.ValueHasField(targetField, \"Files\") {\n\t\t\t\t\t\t\t\tfieldFiles := targetField.FieldByName(\"Files\").Interface().([]string)\n\t\t\t\t\t\t\t\tmessage := fmt.Sprintf(\"Use suggested file %s? [Yn]\", strings.Join(fieldFiles, \", \"))\n\t\t\t\t\t\t\t\tinput := awaitInput(message, \"(y|n|^$)\", \"  \")\n\t\t\t\t\t\t\t\tif strings.EqualFold(input, \"y\") || strings.EqualFold(input, \"\") {\n\t\t\t\t\t\t\t\t\treflect.Indirect(reflect.ValueOf(actualField)).FieldByName(\"Files\").Set(reflect.ValueOf(fieldFiles))\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tfmt.Println()\n\t\t\t\t\t\t\t\t\tmessage := fmt.Sprintf(\"Enter the path to a valid %s configuration file\", fieldName)\n\t\t\t\t\t\t\t\t\tinput := awaitFileInput(message, \"  \")\n\t\t\t\t\t\t\t\t\treflect.Indirect(reflect.ValueOf(actualField)).FieldByName(\"Files\").Set(reflect.ValueOf([]string{input}))\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif util.ValueHasMethod(targetField, \"CustomPrompt\") {\n\t\t\t\t\t\t\t\tcustomMethod := targetField.MethodByName(\"CustomPrompt\")\n\t\t\t\t\t\t\t\tactualField = customMethod.Call([]reflect.Value{})[0].Interface()\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treflect.Indirect(reflect.ValueOf(actualConfiguration.Targets)).FieldByName(fieldName).Set(reflect.ValueOf(actualField))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Println()\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"Suggested config does not contain \" + fieldName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tw := tabwriter.NewWriter(os.Stdout, 20, 0, 1, ' ', 0)\n\n\t\tfmt.Fprintln(w, \"Settings\")\n\t\tfmt.Fprintln(w, \"================================================================\")\n\t\tfmt.Fprintln(w, \"HTTP Proxy\")\n\t\tfmt.Fprintf(w, \" - Host\\t : %s\\n\", actualConfiguration.ProxyHost)\n\t\tfmt.Fprintf(w, \" - Port\\t : %s\\n\", actualConfiguration.ProxyPort)\n\n\t\tif len(actualConfiguration.SOCKSProxyHost) > 0 {\n\t\t\tfmt.Fprintln(w)\n\t\t\tfmt.Fprintln(w, \"SOCKS Proxy\")\n\t\t\tfmt.Fprintf(w, \" - Host\\t : %s\\n\", actualConfiguration.SOCKSProxyHost)\n\t\t\tfmt.Fprintf(w, \" - Port\\t : %s\\n\", actualConfiguration.SOCKSProxyPort)\n\t\t}\n\t\tfmt.Fprintln(w, \"================================================================\")\n\t\tfmt.Fprintln(w)\n\n\t\tif actualConfiguration.Targets != nil {\n\t\t\ttargetsField := reflect.Indirect(reflect.ValueOf(actualConfiguration.Targets))\n\n\t\t\tfor i := 0; i < targetsField.NumField(); i++ {\n\t\t\t\tfieldName := targetsField.Type().Field(i).Name\n\n\t\t\t\tif !util.InterfaceIsZero(targetsField.Field(i).Interface()) {\n\t\t\t\t\ttargetField := reflect.Indirect(reflect.ValueOf(targetsField.Field(i).Interface()))\n\t\t\t\t\twithConfig, _ := targetField.Interface().(WithConfig)\n\t\t\t\t\tfmt.Fprintln(w, fieldName)\n\t\t\t\t\tfmt.Fprintf(w, \" - Enabled\\t : %v\\n\", withConfig.isEnabled())\n\n\t\t\t\t\tif util.ValueHasField(targetField, \"Files\") {\n\t\t\t\t\t\tfieldFiles := targetField.FieldByName(\"Files\").Interface().([]string)\n\t\t\t\t\t\tnewFiles := []string{}\n\t\t\t\t\t\tfor _, file := range fieldFiles {\n\t\t\t\t\t\t\tnewFiles = append(newFiles, util.UnsanitisePath(file))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfmt.Fprintf(w, \" - Files\\t : %s\\n\", strings.Join(newFiles, \",\"))\n\t\t\t\t\t}\n\n\t\t\t\t\tif util.ValueHasMethod(targetField, \"CustomFields\") {\n\t\t\t\t\t\tcustomMethod := targetField.MethodByName(\"CustomFields\")\n\t\t\t\t\t\textraFields := customMethod.Call([]reflect.Value{})[0].Interface().(map[string]string)\n\t\t\t\t\t\tfor k, v := range extraFields {\n\t\t\t\t\t\t\tfmt.Fprintf(w, \" - %s\\t : %s\\n\", k, v)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Fprintln(w)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfmt.Fprintln(w, \"================================================================\")\n\t\tfmt.Fprintln(w)\n\t\tw.Flush()\n\n\t\tinput := awaitInput(\"Write these settings to ~\/.proxybastard\/config.json? [Yn]\", \"(y|n|^$)\", \"\")\n\t\tfmt.Println()\n\t\treadyToWrite = strings.EqualFold(input, \"y\") || strings.EqualFold(input, \"\")\n\t}\n\n\t\/\/ marshalled, err := json.MarshalIndent(actualConfiguration, \"\", \"    \")\n\t\/\/ if err != nil {\n\t\/\/ \tlog.Fatal(err)\n\t\/\/ }\n\t\/\/ fmt.Printf(\"%s\\n\\n\", string(marshalled))\n\tif readyToWrite {\n\t\tfmt.Println(\"Done\")\n\t} else {\n\t\tfmt.Println(\"kthx\")\n\t}\n}\n\nfunc getHighestFrequency(frequencyMap map[string]int) string {\n\tvar highestValue int\n\tvar mostFrequentKey string\n\n\tkeys := []string{}\n\tfor key := range frequencyMap {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, key := range keys {\n\t\tif value := frequencyMap[key]; value > highestValue {\n\t\t\thighestValue = value\n\t\t\tmostFrequentKey = key\n\t\t}\n\t}\n\treturn mostFrequentKey\n}\n\nfunc suggestConfiguration() Configuration {\n\tvar suggestedConfiguration Configuration\n\n\tsuggestedProxyHosts := make(map[string]int)\n\tsuggestedProxyPorts := make(map[string]int)\n\tsuggestedSOCKSProxyHosts := make(map[string]int)\n\tsuggestedSOCKSProxyPorts := make(map[string]int)\n\tsuggestedNonProxyHosts := mapset.NewSet()\n\n\ttargetsField := reflect.Indirect(reflect.ValueOf(&TargetsConfiguration{}))\n\tfor i := 0; i < targetsField.NumField(); i++ {\n\n\t\tconfigurationField := reflect.New(reflect.TypeOf(targetsField.Field(i).Interface()).Elem()).Interface()\n\t\twithConfig, hasConfig := configurationField.(WithConfig)\n\t\tif hasConfig {\n\t\t\tfieldName := targetsField.Type().Field(i).Name\n\n\t\t\tif suggestedItemConfiguration := withConfig.suggestConfiguration(); suggestedItemConfiguration != nil {\n\t\t\t\tif suggestedConfiguration.Targets == nil {\n\t\t\t\t\tsuggestedConfiguration.Targets = &TargetsConfiguration{}\n\t\t\t\t}\n\n\t\t\t\taddToMap(suggestedProxyHosts, util.SanitiseHTTPProxyURL(suggestedItemConfiguration.ProxyHost))\n\t\t\t\taddToMap(suggestedProxyPorts, suggestedItemConfiguration.ProxyPort)\n\t\t\t\taddToMap(suggestedSOCKSProxyHosts, suggestedItemConfiguration.SOCKSProxyHost)\n\t\t\t\taddToMap(suggestedSOCKSProxyPorts, suggestedItemConfiguration.SOCKSProxyPort)\n\n\t\t\t\tfor _, nonProxyHost := range suggestedItemConfiguration.NonProxyHosts {\n\t\t\t\t\tsuggestedNonProxyHosts.Add(nonProxyHost)\n\t\t\t\t}\n\n\t\t\t\ttargetsField := reflect.Indirect(reflect.ValueOf(suggestedConfiguration.Targets))\n\t\t\t\ttargetsFieldSuggested := reflect.Indirect(reflect.ValueOf(suggestedItemConfiguration.Targets))\n\n\t\t\t\ttargetsField.FieldByName(fieldName).Set(targetsFieldSuggested.FieldByName(fieldName))\n\t\t\t}\n\t\t}\n\t}\n\n\tsuggestedConfiguration.ProxyHost = getHighestFrequency(suggestedProxyHosts)\n\tsuggestedConfiguration.ProxyPort = getHighestFrequency(suggestedProxyPorts)\n\tsuggestedConfiguration.SOCKSProxyHost = getHighestFrequency(suggestedSOCKSProxyHosts)\n\tsuggestedConfiguration.SOCKSProxyPort = getHighestFrequency(suggestedSOCKSProxyPorts)\n\tfor suggestedNonProxyHost := range suggestedNonProxyHosts.Iter() {\n\t\tsuggestedConfiguration.NonProxyHosts = append(suggestedConfiguration.NonProxyHosts, suggestedNonProxyHost.(string))\n\t}\n\n\treturn suggestedConfiguration\n}\n<commit_msg>write config to file<commit_after>package proxy\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\n\t\"github.com\/andystanton\/proxybastard\/util\"\n\t\"github.com\/deckarep\/golang-set\"\n)\n\nfunc addToMap(frequencyMap map[string]int, value string) map[string]int {\n\tif len(strings.TrimSpace(value)) > 0 {\n\t\tif _, ok := frequencyMap[value]; !ok {\n\t\t\tfrequencyMap[value] = 0\n\t\t}\n\t\tfrequencyMap[value] = frequencyMap[value] + 1\n\t}\n\treturn frequencyMap\n}\n\nfunc awaitInput(prompt string, pattern string, prefix string) string {\n\tvar matched string\n\tvar found bool\n\tfmt.Printf(\"%s%s\\n\", prefix, prompt)\n\tfmt.Printf(\"%s> \", prefix)\n\tfor i := 0; i < 3; i++ {\n\t\treader := bufio.NewReader(os.Stdin)\n\t\ttext, _ := reader.ReadString('\\n')\n\t\trPattern := regexp.MustCompile(pattern)\n\n\t\tif result := strings.TrimSpace(text); rPattern.MatchString(result) {\n\t\t\tmatched = result\n\t\t\tfound = true\n\t\t\tbreak\n\t\t} else if i < 2 {\n\t\t\tlog.Printf(\"%sThat doesn't look right - try again...\\n\", prefix)\n\t\t\tlog.Println()\n\t\t\tfmt.Printf(\"%s%s\\n\", prefix, prompt)\n\t\t\tfmt.Printf(\"%s> \", prefix)\n\t\t} else {\n\t\t\tlog.Println()\n\t\t\tlog.Print(\"Three failed attempts - aborting!\")\n\t\t}\n\t}\n\tif !found {\n\t\tos.Exit(1)\n\t}\n\treturn matched\n}\n\nfunc awaitFileInput(prompt string, prefix string) string {\n\tvar matched string\n\tvar found bool\n\tfmt.Printf(\"%s%s\\n\", prefix, prompt)\n\tfmt.Printf(\"%s> \", prefix)\n\tfor i := 0; i < 3; i++ {\n\t\treader := bufio.NewReader(os.Stdin)\n\t\ttext, _ := reader.ReadString('\\n')\n\t\tif file := util.SanitisePath(strings.TrimSpace(text)); util.FileExists(file) {\n\t\t\tmatched = file\n\t\t\tfound = true\n\t\t\tbreak\n\t\t} else if i < 2 {\n\t\t\tlog.Printf(\"%sThat doesn't look right - try again...\\n\", prefix)\n\t\t\tlog.Println()\n\t\t\tfmt.Printf(\"%s%s\\n\", prefix, prompt)\n\t\t\tfmt.Printf(\"%s> \", prefix)\n\t\t} else {\n\t\t\tlog.Println()\n\t\t\tlog.Print(\"Three failed attempts - aborting!\")\n\t\t}\n\t}\n\tif !found {\n\t\tos.Exit(1)\n\t}\n\treturn matched\n}\n\n\/\/ Setup presents the user with setup options.\nfunc Setup(version string, acceptDefaults bool) {\n\tsuggestedConfiguration := suggestConfiguration()\n\tactualConfiguration := Configuration{}\n\tactualConfiguration.Version = version\n\treadyToWrite := false\n\n\tif acceptDefaults {\n\t\tactualConfiguration = suggestedConfiguration\n\t\treadyToWrite = true\n\t} else {\n\t\thttpProxySet := false\n\t\tif len(suggestedConfiguration.ProxyHost) > 0 {\n\t\t\tmessage := fmt.Sprintf(\"Use suggested http proxy %s:%s? [Yn]\", suggestedConfiguration.ProxyHost, suggestedConfiguration.ProxyPort)\n\t\t\tinput := awaitInput(message, \"(y|n|^$)\", \"\")\n\t\t\thttpProxySet = strings.EqualFold(input, \"y\") || strings.EqualFold(input, \"\")\n\t\t\tactualConfiguration.ProxyHost = suggestedConfiguration.ProxyHost\n\t\t\tactualConfiguration.ProxyPort = suggestedConfiguration.ProxyPort\n\t\t\tfmt.Println()\n\t\t}\n\n\t\tif !httpProxySet {\n\t\t\tproxyHostPattern := \"(?:https?:\/\/)?(.+):(\\\\d+)\"\n\t\t\tproxyHostRegexp := regexp.MustCompile(proxyHostPattern)\n\t\t\tmatches := proxyHostRegexp.FindStringSubmatch(awaitInput(\"Please enter an http proxy e.g. http:\/\/proxybastard:1234\", proxyHostPattern, \"\"))\n\t\t\tactualConfiguration.ProxyHost = fmt.Sprintf(\"http:\/\/%s\", matches[1])\n\t\t\tactualConfiguration.ProxyPort = matches[2]\n\t\t\thttpProxySet = true\n\t\t\tfmt.Println()\n\t\t}\n\n\t\tsocksProxySet := false\n\t\tif len(suggestedConfiguration.SOCKSProxyHost) > 0 {\n\t\t\tmessage := fmt.Sprintf(\"Use suggested SOCKS proxy %s:%s? [Yn]\", suggestedConfiguration.SOCKSProxyHost, suggestedConfiguration.SOCKSProxyPort)\n\t\t\tinput := awaitInput(message, \"(y|n|^$)\", \"\")\n\t\t\tsocksProxySet = strings.EqualFold(input, \"y\") || strings.EqualFold(input, \"\")\n\t\t\tactualConfiguration.SOCKSProxyHost = suggestedConfiguration.SOCKSProxyHost\n\t\t\tactualConfiguration.SOCKSProxyPort = suggestedConfiguration.SOCKSProxyPort\n\t\t\tfmt.Println()\n\t\t}\n\n\t\tif !socksProxySet {\n\t\t\tsocksHostPattern := \"(?:(.+):(\\\\d+)|^$)\"\n\t\t\tsockHostRegexp := regexp.MustCompile(socksHostPattern)\n\t\t\tmatches := sockHostRegexp.FindStringSubmatch(awaitInput(\"Please enter a SOCKS proxy or press return for none e.g. socks.proxybastard:1234\", socksHostPattern, \"\"))\n\t\t\tif len(matches) > 0 {\n\t\t\t\tsocksProxySet = true\n\t\t\t\tactualConfiguration.SOCKSProxyHost = matches[1]\n\t\t\t\tactualConfiguration.SOCKSProxyPort = matches[2]\n\t\t\t}\n\t\t\tfmt.Println()\n\t\t}\n\n\t\tif suggestedConfiguration.Targets != nil {\n\t\t\ttargetsField := reflect.Indirect(reflect.ValueOf(suggestedConfiguration.Targets))\n\t\t\tfor i := 0; i < targetsField.NumField(); i++ {\n\t\t\t\tfieldName := targetsField.Type().Field(i).Name\n\n\t\t\t\t\/\/ valueForFieldRequired := false\n\t\t\t\tif !util.InterfaceIsZero(targetsField.Field(i).Interface()) {\n\t\t\t\t\ttargetField := reflect.Indirect(reflect.ValueOf(targetsField.Field(i).Interface()))\n\n\t\t\t\t\t\/\/ step 1 - go simple and ask if user wants suggested config\n\t\t\t\t\tmessage := fmt.Sprintf(\"Found %s! Use suggested configuration? [Yn]\", fieldName)\n\t\t\t\t\tinput := awaitInput(message, \"(y|n|^$)\", \"\")\n\t\t\t\t\tconfigurationSet := strings.EqualFold(input, \"y\") || strings.EqualFold(input, \"\")\n\n\t\t\t\t\tif configurationSet {\n\t\t\t\t\t\t\/\/ great! put the suggested config in the actual config\n\t\t\t\t\t\tif actualConfiguration.Targets == nil {\n\t\t\t\t\t\t\tactualConfiguration.Targets = &TargetsConfiguration{}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tactualField := reflect.Indirect(reflect.ValueOf(actualConfiguration.Targets)).FieldByName(fieldName)\n\t\t\t\t\t\tactualField.Set(reflect.ValueOf(targetsField.Field(i).Interface()))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Println()\n\n\t\t\t\t\t\tmessage := fmt.Sprintf(\"Enable %s? [Yn]\", fieldName)\n\t\t\t\t\t\tinput := awaitInput(message, \"(y|n|^$)\", \"  \")\n\t\t\t\t\t\tif strings.EqualFold(input, \"y\") || strings.EqualFold(input, \"\") {\n\t\t\t\t\t\t\tif actualConfiguration.Targets == nil {\n\t\t\t\t\t\t\t\tactualConfiguration.Targets = &TargetsConfiguration{}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tactualField := reflect.New(reflect.TypeOf(targetField.Interface())).Interface()\n\t\t\t\t\t\t\treflect.Indirect(reflect.ValueOf(actualField)).FieldByName(\"Enabled\").Set(reflect.ValueOf(true))\n\t\t\t\t\t\t\tfmt.Println()\n\n\t\t\t\t\t\t\tif util.ValueHasField(targetField, \"Files\") {\n\t\t\t\t\t\t\t\tfieldFiles := targetField.FieldByName(\"Files\").Interface().([]string)\n\t\t\t\t\t\t\t\tmessage := fmt.Sprintf(\"Use suggested file %s? [Yn]\", strings.Join(fieldFiles, \", \"))\n\t\t\t\t\t\t\t\tinput := awaitInput(message, \"(y|n|^$)\", \"  \")\n\t\t\t\t\t\t\t\tif strings.EqualFold(input, \"y\") || strings.EqualFold(input, \"\") {\n\t\t\t\t\t\t\t\t\treflect.Indirect(reflect.ValueOf(actualField)).FieldByName(\"Files\").Set(reflect.ValueOf(fieldFiles))\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tfmt.Println()\n\t\t\t\t\t\t\t\t\tmessage := fmt.Sprintf(\"Enter the path to a valid %s configuration file\", fieldName)\n\t\t\t\t\t\t\t\t\tinput := awaitFileInput(message, \"  \")\n\t\t\t\t\t\t\t\t\treflect.Indirect(reflect.ValueOf(actualField)).FieldByName(\"Files\").Set(reflect.ValueOf([]string{input}))\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif util.ValueHasMethod(targetField, \"CustomPrompt\") {\n\t\t\t\t\t\t\t\tcustomMethod := targetField.MethodByName(\"CustomPrompt\")\n\t\t\t\t\t\t\t\tactualField = customMethod.Call([]reflect.Value{})[0].Interface()\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\treflect.Indirect(reflect.ValueOf(actualConfiguration.Targets)).FieldByName(fieldName).Set(reflect.ValueOf(actualField))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Println()\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"Suggested config does not contain \" + fieldName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tw := tabwriter.NewWriter(os.Stdout, 20, 0, 1, ' ', 0)\n\n\t\tfmt.Fprintln(w, \"Settings\")\n\t\tfmt.Fprintln(w, \"================================================================\")\n\t\tfmt.Fprintln(w, \"HTTP Proxy\")\n\t\tfmt.Fprintf(w, \" - Host\\t : %s\\n\", actualConfiguration.ProxyHost)\n\t\tfmt.Fprintf(w, \" - Port\\t : %s\\n\", actualConfiguration.ProxyPort)\n\n\t\tif len(actualConfiguration.SOCKSProxyHost) > 0 {\n\t\t\tfmt.Fprintln(w)\n\t\t\tfmt.Fprintln(w, \"SOCKS Proxy\")\n\t\t\tfmt.Fprintf(w, \" - Host\\t : %s\\n\", actualConfiguration.SOCKSProxyHost)\n\t\t\tfmt.Fprintf(w, \" - Port\\t : %s\\n\", actualConfiguration.SOCKSProxyPort)\n\t\t}\n\t\tfmt.Fprintln(w, \"================================================================\")\n\t\tfmt.Fprintln(w)\n\n\t\tif actualConfiguration.Targets != nil {\n\t\t\ttargetsField := reflect.Indirect(reflect.ValueOf(actualConfiguration.Targets))\n\n\t\t\tfor i := 0; i < targetsField.NumField(); i++ {\n\t\t\t\tfieldName := targetsField.Type().Field(i).Name\n\n\t\t\t\tif !util.InterfaceIsZero(targetsField.Field(i).Interface()) {\n\t\t\t\t\ttargetField := reflect.Indirect(reflect.ValueOf(targetsField.Field(i).Interface()))\n\t\t\t\t\twithConfig, _ := targetField.Interface().(WithConfig)\n\t\t\t\t\tfmt.Fprintln(w, fieldName)\n\t\t\t\t\tfmt.Fprintf(w, \" - Enabled\\t : %v\\n\", withConfig.isEnabled())\n\n\t\t\t\t\tif util.ValueHasField(targetField, \"Files\") {\n\t\t\t\t\t\tfieldFiles := targetField.FieldByName(\"Files\").Interface().([]string)\n\t\t\t\t\t\tnewFiles := []string{}\n\t\t\t\t\t\tfor _, file := range fieldFiles {\n\t\t\t\t\t\t\tnewFiles = append(newFiles, util.UnsanitisePath(file))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfmt.Fprintf(w, \" - Files\\t : %s\\n\", strings.Join(newFiles, \",\"))\n\t\t\t\t\t}\n\n\t\t\t\t\tif util.ValueHasMethod(targetField, \"CustomFields\") {\n\t\t\t\t\t\tcustomMethod := targetField.MethodByName(\"CustomFields\")\n\t\t\t\t\t\textraFields := customMethod.Call([]reflect.Value{})[0].Interface().(map[string]string)\n\t\t\t\t\t\tfor k, v := range extraFields {\n\t\t\t\t\t\t\tfmt.Fprintf(w, \" - %s\\t : %s\\n\", k, v)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Fprintln(w)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfmt.Fprintln(w, \"================================================================\")\n\t\tfmt.Fprintln(w)\n\t\tw.Flush()\n\n\t\tinput := awaitInput(\"Write these settings to ~\/.proxybastard\/config.json? [Yn]\", \"(y|n|^$)\", \"\")\n\t\tfmt.Println()\n\t\treadyToWrite = strings.EqualFold(input, \"y\") || strings.EqualFold(input, \"\")\n\t}\n\n\tmarshalled, err := json.MarshalIndent(actualConfiguration, \"\", \"    \")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ fmt.Printf(\"%s\\n\\n\", string(marshalled))\n\tif readyToWrite {\n\t\tutil.WriteSliceToFile(util.SanitisePath(\"~\/.proxybastard\/config.json\"), strings.Split(string(marshalled), \"\\n\"))\n\t\tfmt.Println(\"Done\")\n\t} else {\n\t\tfmt.Println(\"kthx\")\n\t}\n}\n\nfunc getHighestFrequency(frequencyMap map[string]int) string {\n\tvar highestValue int\n\tvar mostFrequentKey string\n\n\tkeys := []string{}\n\tfor key := range frequencyMap {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Strings(keys)\n\n\tfor _, key := range keys {\n\t\tif value := frequencyMap[key]; value > highestValue {\n\t\t\thighestValue = value\n\t\t\tmostFrequentKey = key\n\t\t}\n\t}\n\treturn mostFrequentKey\n}\n\nfunc suggestConfiguration() Configuration {\n\tvar suggestedConfiguration Configuration\n\n\tsuggestedProxyHosts := make(map[string]int)\n\tsuggestedProxyPorts := make(map[string]int)\n\tsuggestedSOCKSProxyHosts := make(map[string]int)\n\tsuggestedSOCKSProxyPorts := make(map[string]int)\n\tsuggestedNonProxyHosts := mapset.NewSet()\n\n\ttargetsField := reflect.Indirect(reflect.ValueOf(&TargetsConfiguration{}))\n\tfor i := 0; i < targetsField.NumField(); i++ {\n\n\t\tconfigurationField := reflect.New(reflect.TypeOf(targetsField.Field(i).Interface()).Elem()).Interface()\n\t\twithConfig, hasConfig := configurationField.(WithConfig)\n\t\tif hasConfig {\n\t\t\tfieldName := targetsField.Type().Field(i).Name\n\n\t\t\tif suggestedItemConfiguration := withConfig.suggestConfiguration(); suggestedItemConfiguration != nil {\n\t\t\t\tif suggestedConfiguration.Targets == nil {\n\t\t\t\t\tsuggestedConfiguration.Targets = &TargetsConfiguration{}\n\t\t\t\t}\n\n\t\t\t\taddToMap(suggestedProxyHosts, util.SanitiseHTTPProxyURL(suggestedItemConfiguration.ProxyHost))\n\t\t\t\taddToMap(suggestedProxyPorts, suggestedItemConfiguration.ProxyPort)\n\t\t\t\taddToMap(suggestedSOCKSProxyHosts, suggestedItemConfiguration.SOCKSProxyHost)\n\t\t\t\taddToMap(suggestedSOCKSProxyPorts, suggestedItemConfiguration.SOCKSProxyPort)\n\n\t\t\t\tfor _, nonProxyHost := range suggestedItemConfiguration.NonProxyHosts {\n\t\t\t\t\tsuggestedNonProxyHosts.Add(nonProxyHost)\n\t\t\t\t}\n\n\t\t\t\ttargetsField := reflect.Indirect(reflect.ValueOf(suggestedConfiguration.Targets))\n\t\t\t\ttargetsFieldSuggested := reflect.Indirect(reflect.ValueOf(suggestedItemConfiguration.Targets))\n\n\t\t\t\ttargetsField.FieldByName(fieldName).Set(targetsFieldSuggested.FieldByName(fieldName))\n\t\t\t}\n\t\t}\n\t}\n\n\tsuggestedConfiguration.ProxyHost = getHighestFrequency(suggestedProxyHosts)\n\tsuggestedConfiguration.ProxyPort = getHighestFrequency(suggestedProxyPorts)\n\tsuggestedConfiguration.SOCKSProxyHost = getHighestFrequency(suggestedSOCKSProxyHosts)\n\tsuggestedConfiguration.SOCKSProxyPort = getHighestFrequency(suggestedSOCKSProxyPorts)\n\tfor suggestedNonProxyHost := range suggestedNonProxyHosts.Iter() {\n\t\tsuggestedConfiguration.NonProxyHosts = append(suggestedConfiguration.NonProxyHosts, suggestedNonProxyHost.(string))\n\t}\n\n\treturn suggestedConfiguration\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 syzkaller project authors. All rights reserved.\n\/\/ Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\n\t\"github.com\/google\/syzkaller\/pkg\/csource\"\n\t\"github.com\/google\/syzkaller\/pkg\/log\"\n\t\"github.com\/google\/syzkaller\/pkg\/mgrconfig\"\n\t\"github.com\/google\/syzkaller\/pkg\/osutil\"\n\t\"github.com\/google\/syzkaller\/pkg\/report\"\n\t\"github.com\/google\/syzkaller\/pkg\/repro\"\n\t\"github.com\/google\/syzkaller\/prog\"\n\t\"github.com\/google\/syzkaller\/vm\"\n)\n\nvar (\n\tflagConfig = flag.String(\"config\", \"\", \"manager configuration file (manager.cfg)\")\n\tflagCount  = flag.Int(\"count\", 0, \"number of VMs to use (overrides config count param)\")\n\tflagDebug  = flag.Bool(\"debug\", false, \"print debug output\")\n)\n\nfunc main() {\n\tos.Args = append(append([]string{}, os.Args[0], \"-v=10\"), os.Args[1:]...)\n\tflag.Parse()\n\tif len(flag.Args()) != 1 || flagConfig == nil {\n\t\tlog.Fatalf(\"usage: syz-repro -config=manager.cfg execution.log\")\n\t}\n\tcfg, err := mgrconfig.LoadFile(*flagConfig)\n\tif err != nil {\n\t\tlog.Fatalf(\"%v: %v\", *flagConfig, err)\n\t}\n\tlogFile := flag.Args()[0]\n\tdata, err := ioutil.ReadFile(logFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to open log file %v: %v\", logFile, err)\n\t}\n\tif _, err := prog.GetTarget(cfg.TargetOS, cfg.TargetArch); err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n\tvmPool, err := vm.Create(cfg, *flagDebug)\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n\tvmCount := vmPool.Count()\n\tif *flagCount > 0 && *flagCount < vmCount {\n\t\tvmCount = *flagCount\n\t}\n\tif vmCount > 4 {\n\t\tvmCount = 4\n\t}\n\tvmIndexes := make([]int, vmCount)\n\tfor i := range vmIndexes {\n\t\tvmIndexes[i] = i\n\t}\n\treporter, err := report.NewReporter(cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n\tosutil.HandleInterrupts(vm.Shutdown)\n\n\tres, stats, err := repro.Run(data, cfg, reporter, vmPool, vmIndexes)\n\tif err != nil {\n\t\tlog.Logf(0, \"reproduction failed: %v\", err)\n\t}\n\tif stats != nil {\n\t\tfmt.Printf(\"Extracting prog: %v\\n\", stats.ExtractProgTime)\n\t\tfmt.Printf(\"Minimizing prog: %v\\n\", stats.MinimizeProgTime)\n\t\tfmt.Printf(\"Simplifying prog options: %v\\n\", stats.SimplifyProgTime)\n\t\tfmt.Printf(\"Extracting C: %v\\n\", stats.ExtractCTime)\n\t\tfmt.Printf(\"Simplifying C: %v\\n\", stats.SimplifyCTime)\n\t}\n\tif res == nil {\n\t\treturn\n\t}\n\n\tfmt.Printf(\"opts: %+v crepro: %v\\n\\n\", res.Opts, res.CRepro)\n\tfmt.Printf(\"%s\\n\", res.Prog.Serialize())\n\tif res.CRepro {\n\t\tsrc, err := csource.Write(res.Prog, res.Opts)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to generate C repro: %v\", err)\n\t\t}\n\t\tif formatted, err := csource.Format(src); err == nil {\n\t\t\tsrc = formatted\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", src)\n\t}\n}\n<commit_msg>Review<commit_after>\/\/ Copyright 2015 syzkaller project authors. All rights reserved.\n\/\/ Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\n\t\"github.com\/google\/syzkaller\/pkg\/csource\"\n\t\"github.com\/google\/syzkaller\/pkg\/log\"\n\t\"github.com\/google\/syzkaller\/pkg\/mgrconfig\"\n\t\"github.com\/google\/syzkaller\/pkg\/osutil\"\n\t\"github.com\/google\/syzkaller\/pkg\/report\"\n\t\"github.com\/google\/syzkaller\/pkg\/repro\"\n\t\"github.com\/google\/syzkaller\/prog\"\n\t\"github.com\/google\/syzkaller\/vm\"\n)\n\nvar (\n\tflagConfig = flag.String(\"config\", \"\", \"manager configuration file (manager.cfg)\")\n\tflagCount  = flag.Int(\"count\", 0, \"number of VMs to use (overrides config count param)\")\n\tflagDebug  = flag.Bool(\"debug\", false, \"print debug output\")\n)\n\nfunc main() {\n\tos.Args = append(append([]string{}, os.Args[0], \"-v=10\"), os.Args[1:]...)\n\tflag.Parse()\n\tif len(flag.Args()) != 1 || *flagConfig == \"\" {\n\t\tlog.Fatalf(\"usage: syz-repro -config=manager.cfg execution.log\")\n\t}\n\tcfg, err := mgrconfig.LoadFile(*flagConfig)\n\tif err != nil {\n\t\tlog.Fatalf(\"%v: %v\", *flagConfig, err)\n\t}\n\tlogFile := flag.Args()[0]\n\tdata, err := ioutil.ReadFile(logFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to open log file %v: %v\", logFile, err)\n\t}\n\tif _, err := prog.GetTarget(cfg.TargetOS, cfg.TargetArch); err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n\tvmPool, err := vm.Create(cfg, *flagDebug)\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n\tvmCount := vmPool.Count()\n\tif *flagCount > 0 && *flagCount < vmCount {\n\t\tvmCount = *flagCount\n\t}\n\tif vmCount > 4 {\n\t\tvmCount = 4\n\t}\n\tvmIndexes := make([]int, vmCount)\n\tfor i := range vmIndexes {\n\t\tvmIndexes[i] = i\n\t}\n\treporter, err := report.NewReporter(cfg)\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n\tosutil.HandleInterrupts(vm.Shutdown)\n\n\tres, stats, err := repro.Run(data, cfg, reporter, vmPool, vmIndexes)\n\tif err != nil {\n\t\tlog.Logf(0, \"reproduction failed: %v\", err)\n\t}\n\tif stats != nil {\n\t\tfmt.Printf(\"Extracting prog: %v\\n\", stats.ExtractProgTime)\n\t\tfmt.Printf(\"Minimizing prog: %v\\n\", stats.MinimizeProgTime)\n\t\tfmt.Printf(\"Simplifying prog options: %v\\n\", stats.SimplifyProgTime)\n\t\tfmt.Printf(\"Extracting C: %v\\n\", stats.ExtractCTime)\n\t\tfmt.Printf(\"Simplifying C: %v\\n\", stats.SimplifyCTime)\n\t}\n\tif res == nil {\n\t\treturn\n\t}\n\n\tfmt.Printf(\"opts: %+v crepro: %v\\n\\n\", res.Opts, res.CRepro)\n\tfmt.Printf(\"%s\\n\", res.Prog.Serialize())\n\tif res.CRepro {\n\t\tsrc, err := csource.Write(res.Prog, res.Opts)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to generate C repro: %v\", err)\n\t\t}\n\t\tif formatted, err := csource.Format(src); err == nil {\n\t\t\tsrc = formatted\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", src)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright 2017 IBM Corp.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage block_device_utils_test\n\nimport (\n    \"github.com\/IBM\/ubiquity\/remote\/mounter\/block_device_utils\"\n    \"github.com\/IBM\/ubiquity\/fakes\"\n    \"github.com\/IBM\/ubiquity\/utils\"\n    \"github.com\/IBM\/ubiquity\/utils\/logs\"\n    . \"github.com\/onsi\/gomega\"\n    . \"github.com\/onsi\/ginkgo\"\n    \"testing\"\n    \"errors\"\n    \"fmt\"\n    \"io\/ioutil\"\n)\n\nvar _ = Describe(\"block_device_utils_test\", func() {\n    var (\n        fakeExec      *fakes.FakeExecutor\n        bdUtils       block_device_utils.BlockDeviceUtils\n        err           error\n        cmdErr        error = errors.New(\"command error\")\n    )\n\n    BeforeEach(func() {\n        fakeExec = new(fakes.FakeExecutor)\n        bdUtils = block_device_utils.NewBlockDeviceUtilsWithExecutor(fakeExec)\n    })\n\n    Context(\".Rescan\", func() {\n        It(\"Rescan ISCSI calls 'sudo iscsiadm -m session --rescan'\", func() {\n            err = bdUtils.Rescan(block_device_utils.ISCSI)\n            Expect(err).ToNot(HaveOccurred())\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"iscsiadm\", \"-m\", \"session\", \"--rescan\"}))\n        })\n        It(\"Rescan SCSI calls 'sudo rescan-scsi-bus -r'\", func() {\n            err = bdUtils.Rescan(block_device_utils.SCSI)\n            Expect(err).ToNot(HaveOccurred())\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"rescan-scsi-bus\", \"-r\"}))\n        })\n        It(\"Rescan ISCSI fails if iscsiadm command missing\", func() {\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.Rescan(block_device_utils.ISCSI)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(0))\n            Expect(fakeExec.IsExecutableCallCount()).To(Equal(1))\n            Expect(fakeExec.IsExecutableArgsForCall(0)).To(Equal(\"iscsiadm\"))\n        })\n        It(\"Rescan SCSI fails if rescan-scsi-bus command missing\", func() {\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.Rescan(block_device_utils.SCSI)\n            Expect(err).To(HaveOccurred())\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(0))\n            Expect(fakeExec.IsExecutableCallCount()).To(Equal(2))\n            Expect(fakeExec.IsExecutableArgsForCall(0)).To(Equal(\"rescan-scsi-bus\"))\n            Expect(fakeExec.IsExecutableArgsForCall(1)).To(Equal(\"rescan-scsi-bus.sh\"))\n        })\n        It(\"Rescan ISCSI fails if iscsiadm execution fails\", func() {\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.Rescan(block_device_utils.ISCSI)\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"Rescan SCSI fails if rescan-scsi-bus execution fails\", func() {\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.Rescan(block_device_utils.SCSI)\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"Rescan fails if unknown protocol\", func() {\n            err = bdUtils.Rescan(2)\n            Expect(err).To(HaveOccurred())\n        })\n    })\n    Context(\".ReloadMultipath\", func() {\n        It(\"ReloadMultipath calls multipath command\", func() {\n            err = bdUtils.ReloadMultipath()\n            Expect(err).ToNot(HaveOccurred())\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"multipath\", \"-r\"}))\n        })\n        It(\"ReloadMultipath fails if multipath command is missing\", func() {\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.ReloadMultipath()\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"ReloadMultipath fails if multipath command fails\", func() {\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.ReloadMultipath()\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n    })\n    Context(\".Discover\", func() {\n        It(\"Discover returns path for volume\", func() {\n            volumeId := \"volume-id\"\n            result := \"mpath\"\n            fakeExec.ExecuteReturns([]byte(fmt.Sprintf(\"%s (%s) dm-1\", result, volumeId)), nil)\n            mpath, err := bdUtils.Discover(volumeId)\n            Expect(err).ToNot(HaveOccurred())\n            Expect(mpath).To(Equal(\"\/dev\/mapper\/\" + result))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"multipath\", \"-ll\"}))\n        })\n        It(\"Discover fails if multipath command is missing\", func() {\n            volumeId := \"volume-id\"\n            fakeExec.IsExecutableReturns(cmdErr)\n            _, err := bdUtils.Discover(volumeId)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"Discover fails if multipath -ll command fails\", func() {\n            volumeId := \"volume-id\"\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            _, err := bdUtils.Discover(volumeId)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"Discover fails if volume not found\", func() {\n            volumeId := \"volume-id\"\n            fakeExec.ExecuteReturns([]byte(fmt.Sprintf(\n                \"mpath (other-volume-1) dm-1\\nmpath (other-volume-2) dm-2\")), nil)\n            _, err := bdUtils.Discover(volumeId)\n            Expect(err).To(HaveOccurred())\n        })\n    })\n    Context(\".Cleanup\", func() {\n        It(\"Cleanup calls dmsetup and multipath\", func() {\n            mpath := \"mpath\"\n            err = bdUtils.Cleanup(mpath)\n            Expect(err).ToNot(HaveOccurred())\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(2))\n            cmd1, args1 := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd1).To(Equal(\"sudo\"))\n            Expect(args1).To(Equal([]string{\"dmsetup\", \"message\", mpath, \"0\", \"fail_if_no_path\"}))\n            cmd2, args2 := fakeExec.ExecuteArgsForCall(1)\n            Expect(cmd2).To(Equal(\"sudo\"))\n            Expect(args2).To(Equal([]string{\"multipath\", \"-f\", mpath}))\n        })\n        It(\"Cleanup fails if dmsetup command missing\", func() {\n            mpath := \"mpath\"\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.Cleanup(mpath)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"Cleanup fails if dmsetup command fails\", func() {\n            mpath := \"mpath\"\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.Cleanup(mpath)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"Cleanup fails if multipath command missing\", func() {\n            mpath := \"\/dev\/mapper\/mpath\"\n            fakeExec.IsExecutableReturnsOnCall(1, cmdErr)\n            err = bdUtils.Cleanup(mpath)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n            Expect(fakeExec.IsExecutableCallCount()).To(Equal(2))\n        })\n        It(\"Cleanup fails if multipath command fails\", func() {\n            mpath := \"mpath\"\n            fakeExec.ExecuteReturnsOnCall(1, []byte{}, cmdErr)\n            err = bdUtils.Cleanup(mpath)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n    })\n    Context(\".CheckFs\", func() {\n        It(\"CheckFs detects exiting filesystem on device\", func() {\n            mpath := \"mpath\"\n            fakeExec.ExecuteReturns([]byte{}, nil)\n            fs, err := bdUtils.CheckFs(mpath)\n            Expect(err).ToNot(HaveOccurred())\n            Expect(fs).To(Equal(false))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"blkid\", mpath}))\n        })\n        It(\"CheckFs detects empty device\", func() {\n            err = ioutil.WriteFile(\"\/tmp\/tst.sh\", []byte(\"exit 2\"), 0777)\n            Expect(err).ToNot(HaveOccurred())\n            executor := utils.NewExecutor()\n            _, exitErr2 := executor.Execute(\"sh\", []string{\"\/tmp\/tst.sh\"})\n            Expect(exitErr2).To(HaveOccurred())\n            mpath := \"mpath\"\n            fakeExec.ExecuteReturns([]byte{}, exitErr2)\n            fs, err := bdUtils.CheckFs(mpath)\n            Expect(err).ToNot(HaveOccurred())\n            Expect(fs).To(Equal(true))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"blkid\", mpath}))\n        })\n        It(\"CheckFs fails if blkid missing\", func() {\n            mpath := \"mpath\"\n            fakeExec.IsExecutableReturns(cmdErr)\n            _, err = bdUtils.CheckFs(mpath)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"CheckFs fails if blkid fails\", func() {\n            mpath := \"mpath\"\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            _, err := bdUtils.CheckFs(mpath)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n    })\n    Context(\".MakeFs\", func() {\n        It(\"MakeFs creates fs by type\", func() {\n            mpath := \"mpath\"\n            fstype := \"fstype\"\n            err = bdUtils.MakeFs(mpath, fstype)\n            Expect(err).To(Not(HaveOccurred()))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"mkfs\", \"-t\", fstype, mpath}))\n        })\n        It(\"MakeFs fails if mkfs missing\", func() {\n            mpath := \"mpath\"\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.MakeFs(mpath, \"\")\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"MakeFs fails if mkfs command fails\", func() {\n            mpath := \"mpath\"\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.MakeFs(mpath, \"\")\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n    })\n    Context(\".MountFs\", func() {\n        It(\"MountFs succeeds\", func() {\n            mpath := \"mpath\"\n            mpoint := \"mpoint\"\n            err = bdUtils.MountFs(mpath, mpoint)\n            Expect(err).To(Not(HaveOccurred()))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"mount\", mpath, mpoint}))\n        })\n        It(\"MountFs fails if mount command missing\", func() {\n            mpath := \"mpath\"\n            mpoint := \"mpoint\"\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.MountFs(mpath, mpoint)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"MountFs fails if mount command fails\", func() {\n            mpath := \"mpath\"\n            mpoint := \"mpoint\"\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.MountFs(mpath, mpoint)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n\n    })\n    Context(\".UmountFs\", func() {\n        It(\"UmountFs succeeds\", func() {\n            mpoint := \"mpoint\"\n            err = bdUtils.UmountFs(mpoint)\n            Expect(err).To(Not(HaveOccurred()))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"umount\", mpoint}))\n        })\n        It(\"UmountFs fails if umount command missing\", func() {\n            mpoint := \"mpoint\"\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.UmountFs(mpoint)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"UmountFs fails if umount command fails\", func() {\n            mpoint := \"mpoint\"\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.UmountFs(mpoint)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n    })\n})\n\n\nfunc TestGetBlockDeviceUtils(t *testing.T) {\n    RegisterFailHandler(Fail)\n    defer logs.InitStdoutLogger(logs.DEBUG)()\n    RunSpecs(t, \"BlockDeviceUtils Test Suite\")\n}\n<commit_msg>improve tests coverage for block_device_utils<commit_after>\/**\n * Copyright 2017 IBM Corp.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage block_device_utils_test\n\nimport (\n    \"github.com\/IBM\/ubiquity\/remote\/mounter\/block_device_utils\"\n    \"github.com\/IBM\/ubiquity\/fakes\"\n    \"github.com\/IBM\/ubiquity\/utils\"\n    \"github.com\/IBM\/ubiquity\/utils\/logs\"\n    . \"github.com\/onsi\/gomega\"\n    . \"github.com\/onsi\/ginkgo\"\n    \"testing\"\n    \"errors\"\n    \"fmt\"\n    \"io\/ioutil\"\n)\n\nvar _ = Describe(\"block_device_utils_test\", func() {\n    var (\n        fakeExec      *fakes.FakeExecutor\n        bdUtils       block_device_utils.BlockDeviceUtils\n        err           error\n        cmdErr        error = errors.New(\"command error\")\n    )\n\n    BeforeEach(func() {\n        fakeExec = new(fakes.FakeExecutor)\n        bdUtils = block_device_utils.NewBlockDeviceUtilsWithExecutor(fakeExec)\n    })\n\n    Context(\".Rescan\", func() {\n        It(\"Rescan ISCSI calls 'sudo iscsiadm -m session --rescan'\", func() {\n            err = bdUtils.Rescan(block_device_utils.ISCSI)\n            Expect(err).ToNot(HaveOccurred())\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"iscsiadm\", \"-m\", \"session\", \"--rescan\"}))\n        })\n        It(\"Rescan SCSI calls 'sudo rescan-scsi-bus -r'\", func() {\n            err = bdUtils.Rescan(block_device_utils.SCSI)\n            Expect(err).ToNot(HaveOccurred())\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"rescan-scsi-bus\", \"-r\"}))\n        })\n        It(\"Rescan ISCSI fails if iscsiadm command missing\", func() {\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.Rescan(block_device_utils.ISCSI)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(0))\n            Expect(fakeExec.IsExecutableCallCount()).To(Equal(1))\n            Expect(fakeExec.IsExecutableArgsForCall(0)).To(Equal(\"iscsiadm\"))\n        })\n        It(\"Rescan SCSI fails if rescan-scsi-bus command missing\", func() {\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.Rescan(block_device_utils.SCSI)\n            Expect(err).To(HaveOccurred())\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(0))\n            Expect(fakeExec.IsExecutableCallCount()).To(Equal(2))\n            Expect(fakeExec.IsExecutableArgsForCall(0)).To(Equal(\"rescan-scsi-bus\"))\n            Expect(fakeExec.IsExecutableArgsForCall(1)).To(Equal(\"rescan-scsi-bus.sh\"))\n        })\n        It(\"Rescan ISCSI fails if iscsiadm execution fails\", func() {\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.Rescan(block_device_utils.ISCSI)\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"Rescan SCSI fails if rescan-scsi-bus execution fails\", func() {\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.Rescan(block_device_utils.SCSI)\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"Rescan fails if unknown protocol\", func() {\n            err = bdUtils.Rescan(2)\n            Expect(err).To(HaveOccurred())\n        })\n    })\n    Context(\".ReloadMultipath\", func() {\n        It(\"ReloadMultipath calls multipath command\", func() {\n            err = bdUtils.ReloadMultipath()\n            Expect(err).ToNot(HaveOccurred())\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"multipath\", \"-r\"}))\n        })\n        It(\"ReloadMultipath fails if multipath command is missing\", func() {\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.ReloadMultipath()\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"ReloadMultipath fails if multipath command fails\", func() {\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.ReloadMultipath()\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n    })\n    Context(\".Discover\", func() {\n        It(\"Discover returns path for volume\", func() {\n            volumeId := \"volume-id\"\n            result := \"mpath\"\n            fakeExec.ExecuteReturns([]byte(fmt.Sprintf(\"%s (%s) dm-1\", result, volumeId)), nil)\n            mpath, err := bdUtils.Discover(volumeId)\n            Expect(err).ToNot(HaveOccurred())\n            Expect(mpath).To(Equal(\"\/dev\/mapper\/\" + result))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"multipath\", \"-ll\"}))\n        })\n        It(\"Discover fails if multipath command is missing\", func() {\n            volumeId := \"volume-id\"\n            fakeExec.IsExecutableReturns(cmdErr)\n            _, err := bdUtils.Discover(volumeId)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"Discover fails if multipath -ll command fails\", func() {\n            volumeId := \"volume-id\"\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            _, err := bdUtils.Discover(volumeId)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"Discover fails if stat fails\", func() {\n            volumeId := \"volume-id\"\n            result := \"mpath\"\n            fakeExec.ExecuteReturns([]byte(fmt.Sprintf(\"%s (%s) dm-1\", result, volumeId)), nil)\n            fakeExec.StatReturns(nil, cmdErr)\n            _, err := bdUtils.Discover(volumeId)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"Discover fails if volume not found\", func() {\n            volumeId := \"volume-id\"\n            fakeExec.ExecuteReturns([]byte(fmt.Sprintf(\n                \"mpath (other-volume-1) dm-1\\nmpath (other-volume-2) dm-2\")), nil)\n            _, err := bdUtils.Discover(volumeId)\n            Expect(err).To(HaveOccurred())\n        })\n    })\n    Context(\".Cleanup\", func() {\n        It(\"Cleanup calls dmsetup and multipath\", func() {\n            mpath := \"mpath\"\n            err = bdUtils.Cleanup(mpath)\n            Expect(err).ToNot(HaveOccurred())\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(2))\n            cmd1, args1 := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd1).To(Equal(\"sudo\"))\n            Expect(args1).To(Equal([]string{\"dmsetup\", \"message\", mpath, \"0\", \"fail_if_no_path\"}))\n            cmd2, args2 := fakeExec.ExecuteArgsForCall(1)\n            Expect(cmd2).To(Equal(\"sudo\"))\n            Expect(args2).To(Equal([]string{\"multipath\", \"-f\", mpath}))\n        })\n        It(\"Cleanup fails if dmsetup command missing\", func() {\n            mpath := \"mpath\"\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.Cleanup(mpath)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"Cleanup fails if dmsetup command fails\", func() {\n            mpath := \"mpath\"\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.Cleanup(mpath)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"Cleanup fails if multipath command missing\", func() {\n            mpath := \"\/dev\/mapper\/mpath\"\n            fakeExec.IsExecutableReturnsOnCall(1, cmdErr)\n            err = bdUtils.Cleanup(mpath)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n            Expect(fakeExec.IsExecutableCallCount()).To(Equal(2))\n        })\n        It(\"Cleanup fails if multipath command fails\", func() {\n            mpath := \"mpath\"\n            fakeExec.ExecuteReturnsOnCall(1, []byte{}, cmdErr)\n            err = bdUtils.Cleanup(mpath)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n    })\n    Context(\".CheckFs\", func() {\n        It(\"CheckFs detects exiting filesystem on device\", func() {\n            mpath := \"mpath\"\n            fakeExec.ExecuteReturns([]byte{}, nil)\n            fs, err := bdUtils.CheckFs(mpath)\n            Expect(err).ToNot(HaveOccurred())\n            Expect(fs).To(Equal(false))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"blkid\", mpath}))\n        })\n        It(\"CheckFs detects empty device\", func() {\n            err = ioutil.WriteFile(\"\/tmp\/tst.sh\", []byte(\"exit 2\"), 0777)\n            Expect(err).ToNot(HaveOccurred())\n            executor := utils.NewExecutor()\n            _, exitErr2 := executor.Execute(\"sh\", []string{\"\/tmp\/tst.sh\"})\n            Expect(exitErr2).To(HaveOccurred())\n            mpath := \"mpath\"\n            fakeExec.ExecuteReturns([]byte{}, exitErr2)\n            fs, err := bdUtils.CheckFs(mpath)\n            Expect(err).ToNot(HaveOccurred())\n            Expect(fs).To(Equal(true))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"blkid\", mpath}))\n        })\n        It(\"CheckFs fails if blkid missing\", func() {\n            mpath := \"mpath\"\n            fakeExec.IsExecutableReturns(cmdErr)\n            _, err = bdUtils.CheckFs(mpath)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"CheckFs fails if blkid fails\", func() {\n            mpath := \"mpath\"\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            _, err := bdUtils.CheckFs(mpath)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n    })\n    Context(\".MakeFs\", func() {\n        It(\"MakeFs creates fs by type\", func() {\n            mpath := \"mpath\"\n            fstype := \"fstype\"\n            err = bdUtils.MakeFs(mpath, fstype)\n            Expect(err).To(Not(HaveOccurred()))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"mkfs\", \"-t\", fstype, mpath}))\n        })\n        It(\"MakeFs fails if mkfs missing\", func() {\n            mpath := \"mpath\"\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.MakeFs(mpath, \"\")\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"MakeFs fails if mkfs command fails\", func() {\n            mpath := \"mpath\"\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.MakeFs(mpath, \"\")\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n    })\n    Context(\".MountFs\", func() {\n        It(\"MountFs succeeds\", func() {\n            mpath := \"mpath\"\n            mpoint := \"mpoint\"\n            err = bdUtils.MountFs(mpath, mpoint)\n            Expect(err).To(Not(HaveOccurred()))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"mount\", mpath, mpoint}))\n        })\n        It(\"MountFs fails if mount command missing\", func() {\n            mpath := \"mpath\"\n            mpoint := \"mpoint\"\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.MountFs(mpath, mpoint)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"MountFs fails if mount command fails\", func() {\n            mpath := \"mpath\"\n            mpoint := \"mpoint\"\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.MountFs(mpath, mpoint)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n\n    })\n    Context(\".UmountFs\", func() {\n        It(\"UmountFs succeeds\", func() {\n            mpoint := \"mpoint\"\n            err = bdUtils.UmountFs(mpoint)\n            Expect(err).To(Not(HaveOccurred()))\n            Expect(fakeExec.ExecuteCallCount()).To(Equal(1))\n            cmd, args := fakeExec.ExecuteArgsForCall(0)\n            Expect(cmd).To(Equal(\"sudo\"))\n            Expect(args).To(Equal([]string{\"umount\", mpoint}))\n        })\n        It(\"UmountFs fails if umount command missing\", func() {\n            mpoint := \"mpoint\"\n            fakeExec.IsExecutableReturns(cmdErr)\n            err = bdUtils.UmountFs(mpoint)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n        It(\"UmountFs fails if umount command fails\", func() {\n            mpoint := \"mpoint\"\n            fakeExec.ExecuteReturns([]byte{}, cmdErr)\n            err = bdUtils.UmountFs(mpoint)\n            Expect(err).To(HaveOccurred())\n            Expect(err.Error()).To(MatchRegexp(cmdErr.Error()))\n        })\n    })\n})\n\n\nfunc TestGetBlockDeviceUtils(t *testing.T) {\n    RegisterFailHandler(Fail)\n    defer logs.InitStdoutLogger(logs.DEBUG)()\n    RunSpecs(t, \"BlockDeviceUtils Test Suite\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (C) 2015 Red Hat, Inc.\n *\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\n *\/\n\npackage probes\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"gopkg.in\/fsnotify.v1\"\n\n\t\"github.com\/skydive-project\/skydive\/common\"\n\t\"github.com\/skydive-project\/skydive\/config\"\n\t\"github.com\/skydive-project\/skydive\/logging\"\n\t\"github.com\/skydive-project\/skydive\/topology\/graph\"\n\t\"github.com\/vishvananda\/netns\"\n)\n\ntype NetNSProbe struct {\n\tsync.RWMutex\n\n\tGraph       *graph.Graph\n\tRoot        *graph.Node\n\tnsnlProbes  map[string]*NetNsNetLinkTopoUpdater\n\tpathToNetNS map[string]*NetNs\n\trunPath     string\n\trootNsDev   uint64\n}\n\ntype NetNs struct {\n\tpath string\n\tdev  uint64\n\tino  uint64\n}\n\ntype NetNsNetLinkTopoUpdater struct {\n\tsync.RWMutex\n\tGraph    *graph.Graph\n\tRoot     *graph.Node\n\tnlProbe  *NetLinkProbe\n\tuseCount int\n}\n\nfunc getNetNSName(path string) string {\n\ts := strings.Split(path, \"\/\")\n\treturn s[len(s)-1]\n}\n\nfunc (ns *NetNs) String() string {\n\treturn fmt.Sprintf(\"%d,%d\", ns.dev, ns.ino)\n}\n\nfunc (nu *NetNsNetLinkTopoUpdater) Run(ns *NetNs) {\n\tlogging.GetLogger().Debugf(\"Starting NetLinkTopoUpdater for NetNS: %s\", ns.path)\n\n\t\/* start a netlinks updater inside this namespace *\/\n\tnu.Lock()\n\tnu.nlProbe = NewNetLinkProbe(nu.Graph, nu.Root)\n\tnu.Unlock()\n\n\t\/* NOTE(safchain) don't Start just Run, need to keep it alive for the time life of the netns\n\t * and there is no need to have a new goroutine here\n\t *\/\n\tnu.nlProbe.Run(ns.path)\n\n\tnu.Lock()\n\tnu.nlProbe = nil\n\tnu.Unlock()\n\n\tlogging.GetLogger().Debugf(\"NetLinkTopoUpdater stopped for NetNS: %s\", ns.path)\n}\n\nfunc (nu *NetNsNetLinkTopoUpdater) Start(ns *NetNs) {\n\tgo nu.Run(ns)\n}\n\nfunc (nu *NetNsNetLinkTopoUpdater) Stop() {\n\tnu.Lock()\n\tif nu.nlProbe != nil {\n\t\tnu.nlProbe.Stop()\n\t}\n\tnu.Unlock()\n}\n\nfunc NewNetNsNetLinkTopoUpdater(g *graph.Graph, n *graph.Node) *NetNsNetLinkTopoUpdater {\n\treturn &NetNsNetLinkTopoUpdater{\n\t\tGraph:    g,\n\t\tRoot:     n,\n\t\tuseCount: 1,\n\t}\n}\n\nfunc (u *NetNSProbe) Register(path string, extraMetadata graph.Metadata) *graph.Node {\n\tlogging.GetLogger().Debugf(\"Register Network Namespace: %s\", path)\n\n\t\/\/ When a new network namespace has been seen by inotify, the path to\n\t\/\/ the namespace may still be a regular file, not a bind mount to the\n\t\/\/ file in \/proc\/<pid>\/tasks\/<tid>\/ns\/net yet, so we wait a bit for the\n\t\/\/ bind mount to be set up\n\tvar newns *NetNs\n\terr := common.Retry(func() error {\n\t\tvar stats syscall.Stat_t\n\t\tfd, err := syscall.Open(path, syscall.O_RDONLY, 0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = syscall.Fstat(fd, &stats)\n\t\tsyscall.Close(fd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif stats.Dev != u.rootNsDev {\n\t\t\treturn fmt.Errorf(\"%s does not seem to be a valid namespace\", path)\n\t\t}\n\n\t\tnewns = &NetNs{path: path, dev: stats.Dev, ino: stats.Ino}\n\t\treturn nil\n\t}, 10, time.Millisecond*20)\n\n\tif err != nil {\n\t\tlogging.GetLogger().Errorf(\"Could not register namespace: %s\", err.Error())\n\t\treturn nil\n\t}\n\n\t_, ok := u.pathToNetNS[path]\n\tif !ok {\n\t\tu.pathToNetNS[path] = newns\n\t}\n\n\tu.Lock()\n\tdefer u.Unlock()\n\n\tnsString := newns.String()\n\tprobe, ok := u.nsnlProbes[nsString]\n\tif ok {\n\t\tprobe.useCount++\n\t\tlogging.GetLogger().Debugf(\"Increasing counter for namespace %s to %d\", nsString, probe.useCount)\n\t\treturn probe.Root\n\t}\n\n\tu.Graph.Lock()\n\tdefer u.Graph.Unlock()\n\n\tlogging.GetLogger().Debugf(\"Network Namespace added: %s\", nsString)\n\tmetadata := graph.Metadata{\"Name\": getNetNSName(path), \"Type\": \"netns\", \"Path\": path}\n\tif extraMetadata != nil {\n\t\tfor k, v := range extraMetadata {\n\t\t\tmetadata[k] = v\n\t\t}\n\t}\n\tn := u.Graph.NewNode(graph.GenID(), metadata)\n\tu.Graph.Link(u.Root, n, graph.Metadata{\"RelationType\": \"ownership\"})\n\n\tnu := NewNetNsNetLinkTopoUpdater(u.Graph, n)\n\tnu.Start(newns)\n\n\tu.nsnlProbes[nsString] = nu\n\n\treturn n\n}\n\nfunc (u *NetNSProbe) Unregister(path string) {\n\tlogging.GetLogger().Debugf(\"Unregister Network Namespace: %s\", path)\n\n\tns, ok := u.pathToNetNS[path]\n\tif !ok {\n\t\treturn\n\t}\n\n\tu.Lock()\n\tdefer u.Unlock()\n\n\tdelete(u.pathToNetNS, path)\n\tnsString := ns.String()\n\tnu, ok := u.nsnlProbes[nsString]\n\tif !ok {\n\t\tlogging.GetLogger().Debugf(\"No existing Network Namespace found: %s (%s)\", nsString)\n\t\treturn\n\t}\n\n\tif nu.useCount > 1 {\n\t\tnu.useCount--\n\t\tlogging.GetLogger().Debugf(\"Decremented counter for namespace %s to %d\", nsString, nu.useCount)\n\t\treturn\n\t}\n\n\tnu.Stop()\n\tlogging.GetLogger().Debugf(\"Network Namespace deleted: %s\", nsString)\n\n\tu.Graph.Lock()\n\tdefer u.Graph.Unlock()\n\n\tchildren := nu.Graph.LookupChildren(nu.Root, graph.Metadata{}, graph.Metadata{})\n\tfor _, child := range children {\n\t\tu.Graph.DelNode(child)\n\t}\n\tu.Graph.DelNode(nu.Root)\n\n\tdelete(u.nsnlProbes, nsString)\n}\n\nfunc (u *NetNSProbe) initialize() {\n\tfiles, _ := ioutil.ReadDir(u.runPath)\n\tfor _, f := range files {\n\t\tu.Register(u.runPath+\"\/\"+f.Name(), nil)\n\t}\n}\n\nfunc (u *NetNSProbe) start() {\n\t\/\/ wait for the path creation\n\tfor {\n\t\t_, err := os.Stat(u.runPath)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlogging.GetLogger().Errorf(\"Unable to create a new Watcher: %s\", err.Error())\n\t\treturn\n\t}\n\n\terr = watcher.Add(u.runPath)\n\tif err != nil {\n\t\tlogging.GetLogger().Errorf(\"Unable to Watch %s: %s\", u.runPath, err.Error())\n\t\treturn\n\t}\n\n\tu.initialize()\n\tlogging.GetLogger().Debugf(\"NetNSProbe initialized\")\n\n\tfor {\n\t\tselect {\n\t\tcase ev := <-watcher.Events:\n\t\t\tif ev.Op&fsnotify.Create == fsnotify.Create {\n\t\t\t\tu.Register(ev.Name, nil)\n\t\t\t}\n\t\t\tif ev.Op&fsnotify.Remove == fsnotify.Remove {\n\t\t\t\tu.Unregister(ev.Name)\n\t\t\t}\n\n\t\tcase err := <-watcher.Errors:\n\t\t\tlogging.GetLogger().Errorf(\"Error while watching network namespace: %s\", err.Error())\n\t\t}\n\t}\n}\n\nfunc (u *NetNSProbe) Start() {\n\tgo u.start()\n}\n\nfunc (u *NetNSProbe) Stop() {\n\tu.Lock()\n\tdefer u.Unlock()\n\n\tfor _, probe := range u.nsnlProbes {\n\t\tprobe.Stop()\n\t}\n}\n\nfunc NewNetNSProbe(g *graph.Graph, n *graph.Node, runPath ...string) (*NetNSProbe, error) {\n\tif uid := os.Geteuid(); uid != 0 {\n\t\treturn nil, errors.New(\"NetNS probe has to be run as root\")\n\t}\n\n\tpath := \"\/var\/run\/netns\"\n\tif len(runPath) > 0 && runPath[0] != \"\" {\n\t\tpath = runPath[0]\n\t}\n\n\trootNs, err := netns.Get()\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to get root namespace\")\n\t}\n\tdefer rootNs.Close()\n\n\tvar stats syscall.Stat_t\n\tif err := syscall.Fstat(int(rootNs), &stats); err != nil {\n\t\treturn nil, errors.New(\"Failed to stat root namespace\")\n\t}\n\n\treturn &NetNSProbe{\n\t\tGraph:       g,\n\t\tRoot:        n,\n\t\tnsnlProbes:  make(map[string]*NetNsNetLinkTopoUpdater),\n\t\tpathToNetNS: make(map[string]*NetNs),\n\t\trunPath:     path,\n\t\trootNsDev:   stats.Dev,\n\t}, nil\n}\n\nfunc NewNetNSProbeFromConfig(g *graph.Graph, n *graph.Node) (*NetNSProbe, error) {\n\tpath := config.GetConfig().GetString(\"netns.run_path\")\n\treturn NewNetNSProbe(g, n, path)\n}\n<commit_msg>netns: speed up stop of netns probe<commit_after>\/*\n * Copyright (C) 2015 Red Hat, Inc.\n *\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\n *\/\n\npackage probes\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"gopkg.in\/fsnotify.v1\"\n\n\t\"github.com\/skydive-project\/skydive\/common\"\n\t\"github.com\/skydive-project\/skydive\/config\"\n\t\"github.com\/skydive-project\/skydive\/logging\"\n\t\"github.com\/skydive-project\/skydive\/topology\/graph\"\n\t\"github.com\/vishvananda\/netns\"\n)\n\ntype NetNSProbe struct {\n\tsync.RWMutex\n\n\tGraph       *graph.Graph\n\tRoot        *graph.Node\n\tnsnlProbes  map[string]*NetNsNetLinkTopoUpdater\n\tpathToNetNS map[string]*NetNs\n\trunPath     string\n\trootNsDev   uint64\n}\n\ntype NetNs struct {\n\tpath string\n\tdev  uint64\n\tino  uint64\n}\n\ntype NetNsNetLinkTopoUpdater struct {\n\tsync.RWMutex\n\tGraph    *graph.Graph\n\tRoot     *graph.Node\n\tnlProbe  *NetLinkProbe\n\tuseCount int\n}\n\nfunc getNetNSName(path string) string {\n\ts := strings.Split(path, \"\/\")\n\treturn s[len(s)-1]\n}\n\nfunc (ns *NetNs) String() string {\n\treturn fmt.Sprintf(\"%d,%d\", ns.dev, ns.ino)\n}\n\nfunc (nu *NetNsNetLinkTopoUpdater) Run(ns *NetNs) {\n\tlogging.GetLogger().Debugf(\"Starting NetLinkTopoUpdater for NetNS: %s\", ns.path)\n\n\t\/* start a netlinks updater inside this namespace *\/\n\tnu.Lock()\n\tnu.nlProbe = NewNetLinkProbe(nu.Graph, nu.Root)\n\tnu.Unlock()\n\n\t\/* NOTE(safchain) don't Start just Run, need to keep it alive for the time life of the netns\n\t * and there is no need to have a new goroutine here\n\t *\/\n\tnu.nlProbe.Run(ns.path)\n\n\tnu.Lock()\n\tnu.nlProbe = nil\n\tnu.Unlock()\n\n\tlogging.GetLogger().Debugf(\"NetLinkTopoUpdater stopped for NetNS: %s\", ns.path)\n}\n\nfunc (nu *NetNsNetLinkTopoUpdater) Start(ns *NetNs) {\n\tgo nu.Run(ns)\n}\n\nfunc (nu *NetNsNetLinkTopoUpdater) Stop() {\n\tnu.Lock()\n\tif nu.nlProbe != nil {\n\t\tnu.nlProbe.Stop()\n\t}\n\tnu.Unlock()\n}\n\nfunc NewNetNsNetLinkTopoUpdater(g *graph.Graph, n *graph.Node) *NetNsNetLinkTopoUpdater {\n\treturn &NetNsNetLinkTopoUpdater{\n\t\tGraph:    g,\n\t\tRoot:     n,\n\t\tuseCount: 1,\n\t}\n}\n\nfunc (u *NetNSProbe) Register(path string, extraMetadata graph.Metadata) *graph.Node {\n\tlogging.GetLogger().Debugf(\"Register Network Namespace: %s\", path)\n\n\t\/\/ When a new network namespace has been seen by inotify, the path to\n\t\/\/ the namespace may still be a regular file, not a bind mount to the\n\t\/\/ file in \/proc\/<pid>\/tasks\/<tid>\/ns\/net yet, so we wait a bit for the\n\t\/\/ bind mount to be set up\n\tvar newns *NetNs\n\terr := common.Retry(func() error {\n\t\tvar stats syscall.Stat_t\n\t\tfd, err := syscall.Open(path, syscall.O_RDONLY, 0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = syscall.Fstat(fd, &stats)\n\t\tsyscall.Close(fd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif stats.Dev != u.rootNsDev {\n\t\t\treturn fmt.Errorf(\"%s does not seem to be a valid namespace\", path)\n\t\t}\n\n\t\tnewns = &NetNs{path: path, dev: stats.Dev, ino: stats.Ino}\n\t\treturn nil\n\t}, 10, time.Millisecond*20)\n\n\tif err != nil {\n\t\tlogging.GetLogger().Errorf(\"Could not register namespace: %s\", err.Error())\n\t\treturn nil\n\t}\n\n\t_, ok := u.pathToNetNS[path]\n\tif !ok {\n\t\tu.pathToNetNS[path] = newns\n\t}\n\n\tu.Lock()\n\tdefer u.Unlock()\n\n\tnsString := newns.String()\n\tprobe, ok := u.nsnlProbes[nsString]\n\tif ok {\n\t\tprobe.useCount++\n\t\tlogging.GetLogger().Debugf(\"Increasing counter for namespace %s to %d\", nsString, probe.useCount)\n\t\treturn probe.Root\n\t}\n\n\tu.Graph.Lock()\n\tdefer u.Graph.Unlock()\n\n\tlogging.GetLogger().Debugf(\"Network Namespace added: %s\", nsString)\n\tmetadata := graph.Metadata{\"Name\": getNetNSName(path), \"Type\": \"netns\", \"Path\": path}\n\tif extraMetadata != nil {\n\t\tfor k, v := range extraMetadata {\n\t\t\tmetadata[k] = v\n\t\t}\n\t}\n\tn := u.Graph.NewNode(graph.GenID(), metadata)\n\tu.Graph.Link(u.Root, n, graph.Metadata{\"RelationType\": \"ownership\"})\n\n\tnu := NewNetNsNetLinkTopoUpdater(u.Graph, n)\n\tnu.Start(newns)\n\n\tu.nsnlProbes[nsString] = nu\n\n\treturn n\n}\n\nfunc (u *NetNSProbe) Unregister(path string) {\n\tlogging.GetLogger().Debugf(\"Unregister Network Namespace: %s\", path)\n\n\tns, ok := u.pathToNetNS[path]\n\tif !ok {\n\t\treturn\n\t}\n\n\tu.Lock()\n\tdefer u.Unlock()\n\n\tdelete(u.pathToNetNS, path)\n\tnsString := ns.String()\n\tnu, ok := u.nsnlProbes[nsString]\n\tif !ok {\n\t\tlogging.GetLogger().Debugf(\"No existing Network Namespace found: %s (%s)\", nsString)\n\t\treturn\n\t}\n\n\tif nu.useCount > 1 {\n\t\tnu.useCount--\n\t\tlogging.GetLogger().Debugf(\"Decremented counter for namespace %s to %d\", nsString, nu.useCount)\n\t\treturn\n\t}\n\n\tnu.Stop()\n\tlogging.GetLogger().Debugf(\"Network Namespace deleted: %s\", nsString)\n\n\tu.Graph.Lock()\n\tdefer u.Graph.Unlock()\n\n\tchildren := nu.Graph.LookupChildren(nu.Root, graph.Metadata{}, graph.Metadata{})\n\tfor _, child := range children {\n\t\tu.Graph.DelNode(child)\n\t}\n\tu.Graph.DelNode(nu.Root)\n\n\tdelete(u.nsnlProbes, nsString)\n}\n\nfunc (u *NetNSProbe) initialize() {\n\tfiles, _ := ioutil.ReadDir(u.runPath)\n\tfor _, f := range files {\n\t\tu.Register(u.runPath+\"\/\"+f.Name(), nil)\n\t}\n}\n\nfunc (u *NetNSProbe) start() {\n\t\/\/ wait for the path creation\n\tfor {\n\t\t_, err := os.Stat(u.runPath)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlogging.GetLogger().Errorf(\"Unable to create a new Watcher: %s\", err.Error())\n\t\treturn\n\t}\n\n\terr = watcher.Add(u.runPath)\n\tif err != nil {\n\t\tlogging.GetLogger().Errorf(\"Unable to Watch %s: %s\", u.runPath, err.Error())\n\t\treturn\n\t}\n\n\tu.initialize()\n\tlogging.GetLogger().Debugf(\"NetNSProbe initialized\")\n\n\tfor {\n\t\tselect {\n\t\tcase ev := <-watcher.Events:\n\t\t\tif ev.Op&fsnotify.Create == fsnotify.Create {\n\t\t\t\tu.Register(ev.Name, nil)\n\t\t\t}\n\t\t\tif ev.Op&fsnotify.Remove == fsnotify.Remove {\n\t\t\t\tu.Unregister(ev.Name)\n\t\t\t}\n\n\t\tcase err := <-watcher.Errors:\n\t\t\tlogging.GetLogger().Errorf(\"Error while watching network namespace: %s\", err.Error())\n\t\t}\n\t}\n}\n\nfunc (u *NetNSProbe) Start() {\n\tgo u.start()\n}\n\nfunc (u *NetNSProbe) Stop() {\n\tu.Lock()\n\tdefer u.Unlock()\n\n\tvar wg sync.WaitGroup\n\tfor _, probe := range u.nsnlProbes {\n\t\twg.Add(1)\n\t\tgo func(nl *NetNsNetLinkTopoUpdater) {\n\t\t\tnl.Stop()\n\t\t\twg.Done()\n\t\t}(probe)\n\t}\n\twg.Wait()\n}\n\nfunc NewNetNSProbe(g *graph.Graph, n *graph.Node, runPath ...string) (*NetNSProbe, error) {\n\tif uid := os.Geteuid(); uid != 0 {\n\t\treturn nil, errors.New(\"NetNS probe has to be run as root\")\n\t}\n\n\tpath := \"\/var\/run\/netns\"\n\tif len(runPath) > 0 && runPath[0] != \"\" {\n\t\tpath = runPath[0]\n\t}\n\n\trootNs, err := netns.Get()\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to get root namespace\")\n\t}\n\tdefer rootNs.Close()\n\n\tvar stats syscall.Stat_t\n\tif err := syscall.Fstat(int(rootNs), &stats); err != nil {\n\t\treturn nil, errors.New(\"Failed to stat root namespace\")\n\t}\n\n\treturn &NetNSProbe{\n\t\tGraph:       g,\n\t\tRoot:        n,\n\t\tnsnlProbes:  make(map[string]*NetNsNetLinkTopoUpdater),\n\t\tpathToNetNS: make(map[string]*NetNs),\n\t\trunPath:     path,\n\t\trootNsDev:   stats.Dev,\n\t}, nil\n}\n\nfunc NewNetNSProbeFromConfig(g *graph.Graph, n *graph.Node) (*NetNSProbe, error) {\n\tpath := config.GetConfig().GetString(\"netns.run_path\")\n\treturn NewNetNSProbe(g, n, path)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Google, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package config provides variables used in configuring the behavior of the app.\npackage config\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"golang.org\/x\/oauth2\/google\"\n)\n\nconst (\n\t\/\/ GCRCredHelperClientID is the client_id to be used when performing the\n\t\/\/ OAuth2 Authorization Code grant flow.\n\t\/\/ See https:\/\/developers.google.com\/identity\/protocols\/OAuth2InstalledApp\n\tGCRCredHelperClientID = \"99426463878-o7n0bshgue20tdpm25q4at0vs2mr4utq.apps.googleusercontent.com\"\n\n\t\/\/ GCRCredHelperClientNotSoSecret is the client_secret to be used when\n\t\/\/ performing the OAuth2 Authorization Code grant flow.\n\t\/\/ See https:\/\/developers.google.com\/identity\/protocols\/OAuth2InstalledApp\n\tGCRCredHelperClientNotSoSecret = \"HpVi8cnKx8AAkddzaNrSWmS8\"\n\n\t\/\/ From http:\/\/semver.org\/\n\t\/\/ MAJOR version when you make incompatible API changes,\n\t\/\/ MINOR version when you add functionality in a backwards-compatible manner, and\n\t\/\/ PATCH version when you make backwards-compatible bug fixes.\n\n\t\/\/ MajorVersion is the credential helper's major version number.\n\tMajorVersion = 2\n\t\/\/ MinorVersion is the credential helper's minor version number.\n\tMinorVersion = 0\n\t\/\/ PatchVersion is the credential helper's patch version number.\n\tPatchVersion = 4\n)\n\n\/\/ DefaultGCRRegistries contains the list of default registries to authenticate for.\nvar DefaultGCRRegistries = [...]string{\n\t\"gcr.io\",\n\t\"us.gcr.io\",\n\t\"eu.gcr.io\",\n\t\"asia.gcr.io\",\n\t\"marketplace.gcr.io\",\n}\n\n\/\/ DefaultARRegistries contains the list of default registries for Artifact\n\/\/ Registry.  If the --include-artifact-registry flag is supplied then these\n\/\/ are added in addition to the GCR Registries.\nvar DefaultARRegistries = [...]string{\n\t\"northamerica-northeast1-docker.pkg.dev\",\n\t\"northamerica-northeast2-docker.pkg.dev\", \"us-central1-docker.pkg.dev\",\n\t\"us-east1-docker.pkg.dev\", \"us-east4-docker.pkg.dev\",\n\t\"us-west2-docker.pkg.dev\", \"us-west1-docker.pkg.dev\",\n\t\"us-west3-docker.pkg.dev\", \"us-west4-docker.pkg.dev\",\n\t\"southamerica-east1-docker.pkg.dev\", \"southamerica-west1-docker.pkg.dev\",\n\t\"europe-central2-docker.pkg.dev\", \"europe-north1-docker.pkg.dev\",\n\t\"europe-west1-docker.pkg.dev\", \"europe-west2-docker.pkg.dev\",\n\t\"europe-west3-docker.pkg.dev\", \"europe-west4-docker.pkg.dev\",\n\t\"europe-west6-docker.pkg.dev\", \"asia-east1-docker.pkg.dev\",\n\t\"asia-east2-docker.pkg.dev\", \"asia-northeast1-docker.pkg.dev\",\n\t\"asia-northeast2-docker.pkg.dev\", \"asia-northeast3-docker.pkg.dev\",\n\t\"asia-south1-docker.pkg.dev\", \"asia-south2-docker.pkg.dev\",\n\t\"asia-southeast1-docker.pkg.dev\", \"asia-southeast2-docker.pkg.dev\",\n\t\"australia-southeast1-docker.pkg.dev\", \"australia-southeast2-docker.pkg.dev\",\n\t\"asia-docker.pkg.dev\", \"europe-docker.pkg.dev\", \"us-docker.pkg.dev\",\n}\n\n\/\/ SupportedGCRTokenSources maps config keys to plain english explanations for\n\/\/ where the helper should search for a GCR access token.\nvar SupportedGCRTokenSources = map[string]string{\n\t\"env\":    \"Application default credentials or GCE\/AppEngine metadata.\",\n\t\"gcloud\": \"'gcloud auth print-access-token'\",\n\t\"store\":  \"The file store maintained by the credential helper.\",\n}\n\n\/\/ GCROAuth2Endpoint describes the oauth2.Endpoint to be used when\n\/\/ authenticating a GCR user.\nvar GCROAuth2Endpoint = google.Endpoint\n\n\/\/ GCRScopes is\/are the OAuth2 scope(s) to request during access_token creation.\nvar GCRScopes = []string{\"https:\/\/www.googleapis.com\/auth\/cloud-platform\"}\n\n\/\/ OAuthHTTPContext is the HTTP context to use when performing OAuth2 calls.\nvar OAuthHTTPContext = context.Background()\n\n\/\/ GcrOAuth2Username is the Basic auth username accompanying Docker requests to GCR.\nvar GcrOAuth2Username = fmt.Sprintf(\"_dcgcr_%d_%d_%d_token\", MajorVersion, MinorVersion, PatchVersion)\n<commit_msg>do not add Toronto\/Santiago regions which are not being turned up for another couple months<commit_after>\/\/ Copyright 2016 Google, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package config provides variables used in configuring the behavior of the app.\npackage config\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"golang.org\/x\/oauth2\/google\"\n)\n\nconst (\n\t\/\/ GCRCredHelperClientID is the client_id to be used when performing the\n\t\/\/ OAuth2 Authorization Code grant flow.\n\t\/\/ See https:\/\/developers.google.com\/identity\/protocols\/OAuth2InstalledApp\n\tGCRCredHelperClientID = \"99426463878-o7n0bshgue20tdpm25q4at0vs2mr4utq.apps.googleusercontent.com\"\n\n\t\/\/ GCRCredHelperClientNotSoSecret is the client_secret to be used when\n\t\/\/ performing the OAuth2 Authorization Code grant flow.\n\t\/\/ See https:\/\/developers.google.com\/identity\/protocols\/OAuth2InstalledApp\n\tGCRCredHelperClientNotSoSecret = \"HpVi8cnKx8AAkddzaNrSWmS8\"\n\n\t\/\/ From http:\/\/semver.org\/\n\t\/\/ MAJOR version when you make incompatible API changes,\n\t\/\/ MINOR version when you add functionality in a backwards-compatible manner, and\n\t\/\/ PATCH version when you make backwards-compatible bug fixes.\n\n\t\/\/ MajorVersion is the credential helper's major version number.\n\tMajorVersion = 2\n\t\/\/ MinorVersion is the credential helper's minor version number.\n\tMinorVersion = 0\n\t\/\/ PatchVersion is the credential helper's patch version number.\n\tPatchVersion = 4\n)\n\n\/\/ DefaultGCRRegistries contains the list of default registries to authenticate for.\nvar DefaultGCRRegistries = [...]string{\n\t\"gcr.io\",\n\t\"us.gcr.io\",\n\t\"eu.gcr.io\",\n\t\"asia.gcr.io\",\n\t\"marketplace.gcr.io\",\n}\n\n\/\/ DefaultARRegistries contains the list of default registries for Artifact\n\/\/ Registry.  If the --include-artifact-registry flag is supplied then these\n\/\/ are added in addition to the GCR Registries.\nvar DefaultARRegistries = [...]string{\n\t\"northamerica-northeast1-docker.pkg.dev\", \"us-central1-docker.pkg.dev\",\n\t\"us-east1-docker.pkg.dev\", \"us-east4-docker.pkg.dev\",\n\t\"us-west2-docker.pkg.dev\", \"us-west1-docker.pkg.dev\",\n\t\"us-west3-docker.pkg.dev\", \"us-west4-docker.pkg.dev\",\n\t\"southamerica-east1-docker.pkg.dev\", \"europe-central2-docker.pkg.dev\",\n\t\"europe-north1-docker.pkg.dev\", \"europe-west1-docker.pkg.dev\",\n\t\"europe-west2-docker.pkg.dev\", \"europe-west3-docker.pkg.dev\",\n\t\"europe-west4-docker.pkg.dev\", \"europe-west5-docker.pkg.dev\",\n\t\"europe-west6-docker.pkg.dev\", \"asia-east1-docker.pkg.dev\",\n\t\"asia-east2-docker.pkg.dev\", \"asia-northeast1-docker.pkg.dev\",\n\t\"asia-northeast2-docker.pkg.dev\", \"asia-northeast3-docker.pkg.dev\",\n\t\"asia-south1-docker.pkg.dev\", \"asia-south2-docker.pkg.dev\",\n\t\"asia-southeast1-docker.pkg.dev\", \"asia-southeast2-docker.pkg.dev\",\n\t\"australia-southeast1-docker.pkg.dev\", \"australia-southeast2-docker.pkg.dev\",\n\t\"asia-docker.pkg.dev\", \"europe-docker.pkg.dev\", \"us-docker.pkg.dev\",\n}\n\n\/\/ SupportedGCRTokenSources maps config keys to plain english explanations for\n\/\/ where the helper should search for a GCR access token.\nvar SupportedGCRTokenSources = map[string]string{\n\t\"env\":    \"Application default credentials or GCE\/AppEngine metadata.\",\n\t\"gcloud\": \"'gcloud auth print-access-token'\",\n\t\"store\":  \"The file store maintained by the credential helper.\",\n}\n\n\/\/ GCROAuth2Endpoint describes the oauth2.Endpoint to be used when\n\/\/ authenticating a GCR user.\nvar GCROAuth2Endpoint = google.Endpoint\n\n\/\/ GCRScopes is\/are the OAuth2 scope(s) to request during access_token creation.\nvar GCRScopes = []string{\"https:\/\/www.googleapis.com\/auth\/cloud-platform\"}\n\n\/\/ OAuthHTTPContext is the HTTP context to use when performing OAuth2 calls.\nvar OAuthHTTPContext = context.Background()\n\n\/\/ GcrOAuth2Username is the Basic auth username accompanying Docker requests to GCR.\nvar GcrOAuth2Username = fmt.Sprintf(\"_dcgcr_%d_%d_%d_token\", MajorVersion, MinorVersion, PatchVersion)\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"sort\"\n\t\"time\"\n\n\t. \"github.com\/bytbox\/go-mail\"\n)\n\ntype Threaded struct {\n\tMessage\n\tParent   *Threaded\n\tChildren []*Threaded\n\n\tparId    []string\n}\n\nfunc (tm *Threaded) addChild(c *Threaded) {\n\ttm.Children = append(tm.Children, c)\n}\n\nfunc (tm *Threaded) modified() time.Time {\n\td := tm.Date\n\tfor _, c := range tm.Children {\n\t\tif d.Before(c.Date) {\n\t\t\td = c.Date\n\t\t}\n\t}\n\treturn d\n}\n\nfunc (tm *Threaded) Root() *Threaded {\n\tif tm.Parent == nil {\n\t\treturn tm\n\t}\n\treturn tm.Parent.Root()\n}\n\ntype Sortable []*Threaded\n\nfunc (s Sortable) Len() int {\n\treturn len(s)\n}\n\nfunc (s Sortable) Less(i, j int) bool {\n\treturn s[i].Date.Before(s[j].Date)\n}\n\nfunc (s Sortable) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\nfunc Thread(msgs []Message) ([]*Threaded, []*Threaded) {\n\ttmap := map[string]*Threaded{}\n\tfor _, msg := range msgs {\n\t\tmid := msg.MessageId\n\t\ttm := &Threaded{msg, nil, nil, nil}\n\t\t\/\/ we just use the first parent\n\t\tif len(msg.References) > 0 {\n\t\t\ttm.parId = msg.References\n\t\t}\n\t\ttmap[mid] = tm\n\t}\n\n\tfor _, tm := range tmap {\n\t\tif tm.parId != nil {\n\t\t\t\/\/ The parent should be set using the last id we have\n\t\t\t\/\/ registered.\n\t\t\tfor _, id := range tm.parId {\n\t\t\t\tp, ok := tmap[id]\n\t\t\t\tif ok {\n\t\t\t\t\ttm.Parent = p\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tm.Parent != nil {\n\t\t\t\ttm.Parent.addChild(tm)\n\t\t\t}\n\t\t}\n\t}\n\n\tall := []*Threaded{}\n\n\tthreaded := []*Threaded{}\n\tfor _, tm := range tmap {\n\t\tif tm.Parent == nil {\n\t\t\tthreaded = append(threaded, tm)\n\t\t}\n\t\tall = append(all, tm)\n\t}\n\n\tsort.Sort(Sortable(threaded))\n\treturn all, threaded\n}\n<commit_msg>Sorting \/everything<commit_after>package main\n\nimport (\n\t\"sort\"\n\t\"time\"\n\n\t. \"github.com\/bytbox\/go-mail\"\n)\n\ntype Threaded struct {\n\tMessage\n\tParent   *Threaded\n\tChildren []*Threaded\n\n\tparId    []string\n}\n\nfunc (tm *Threaded) addChild(c *Threaded) {\n\ttm.Children = append(tm.Children, c)\n}\n\nfunc (tm *Threaded) modified() time.Time {\n\td := tm.Date\n\tfor _, c := range tm.Children {\n\t\tif d.Before(c.Date) {\n\t\t\td = c.Date\n\t\t}\n\t}\n\treturn d\n}\n\nfunc (tm *Threaded) Root() *Threaded {\n\tif tm.Parent == nil {\n\t\treturn tm\n\t}\n\treturn tm.Parent.Root()\n}\n\ntype sortable []*Threaded\n\nfunc (s sortable) Len() int {\n\treturn len(s)\n}\n\nfunc (s sortable) Less(i, j int) bool {\n\treturn s[i].Date.Before(s[j].Date)\n}\n\nfunc (s sortable) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\nfunc Thread(msgs []Message) ([]*Threaded, []*Threaded) {\n\ttmap := map[string]*Threaded{}\n\tfor _, msg := range msgs {\n\t\tmid := msg.MessageId\n\t\ttm := &Threaded{msg, nil, nil, nil}\n\t\t\/\/ we just use the first parent\n\t\tif len(msg.References) > 0 {\n\t\t\ttm.parId = msg.References\n\t\t}\n\t\ttmap[mid] = tm\n\t}\n\n\tfor _, tm := range tmap {\n\t\tif tm.parId != nil {\n\t\t\t\/\/ The parent should be set using the last id we have\n\t\t\t\/\/ registered.\n\t\t\tfor _, id := range tm.parId {\n\t\t\t\tp, ok := tmap[id]\n\t\t\t\tif ok {\n\t\t\t\t\ttm.Parent = p\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tm.Parent != nil {\n\t\t\t\ttm.Parent.addChild(tm)\n\t\t\t}\n\t\t}\n\t}\n\n\tall := []*Threaded{}\n\n\tthreaded := []*Threaded{}\n\tfor _, tm := range tmap {\n\t\tif tm.Parent == nil {\n\t\t\tthreaded = append(threaded, tm)\n\t\t}\n\t\tall = append(all, tm)\n\t\tsort.Sort(sortable(tm.Children))\n\t}\n\n\tsort.Sort(sortable(threaded))\n\treturn all, threaded\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/qpliu\/qrencode-go\/qrencode\"\n\t\"fmt\"\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/mattn\/go-colorable\"\n\t\"io\/ioutil\"\n\t\"os\"\n\n\t\"github.com\/fumiyas\/qrc\/lib\"\n\t\"github.com\/fumiyas\/go-tty\"\n)\n\ntype cmdOptions struct {\n\tHelp    bool `short:\"h\" long:\"help\" description:\"show this help message\"`\n\tInverse bool `short:\"i\" long:\"invert\" description:\"invert color\"`\n}\n\nfunc showHelp() {\n\tconst v = `Usage: qrc [OPTIONS] [TEXT]\n\nOptions:\n  -h, --help\n    Show this help message\n  -i, --invert\n    Invert color\n\nText examples:\n  http:\/\/www.example.jp\/\n  MAILTO:foobar@example.jp\n  WIFI:S:myssid;T:WPA;P:pass123;;\n`\n\n\tos.Stderr.Write([]byte(v))\n}\n\nfunc pErr(format string, a ...interface{}) {\n\tfmt.Fprint(os.Stdout, os.Args[0], \": \")\n\tfmt.Fprintf(os.Stdout, format, a...)\n}\n\nfunc main() {\n\tret := 0\n\tdefer func() { os.Exit(ret) }()\n\n\topts := &cmdOptions{}\n\toptsParser := flags.NewParser(opts, flags.PrintErrors)\n\targs, err := optsParser.Parse()\n\tif err != nil || len(args) > 1 {\n\t\tshowHelp()\n\t\tret = 1\n\t\treturn\n\t}\n\tif opts.Help {\n\t\tshowHelp()\n\t\treturn\n\t}\n\n\tvar text string\n\tif len(args) == 1 {\n\t\ttext = args[0]\n\t} else {\n\t\ttext_bytes, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tpErr(\"read from stdin failed: %v\\n\", err)\n\t\t\tret = 1\n\t\t\treturn\n\t\t}\n\t\ttext = string(text_bytes)\n\t}\n\n\tgrid, err := qrencode.Encode(text, qrencode.ECLevelL)\n\n\tda1, err := tty.GetDeviceAttributes1(os.Stdout)\n\tif err == nil && da1[tty.DA1_SIXEL] {\n\t\tqrc.PrintSixel(os.Stdout, grid, opts.Inverse)\n\t} else {\n\t\tstdout := colorable.NewColorableStdout()\n\t\tqrc.PrintAA(stdout, grid, opts.Inverse)\n\t}\n}\n<commit_msg>Catch an error from qrencode.Encode()<commit_after>package main\n\nimport (\n\t\"github.com\/qpliu\/qrencode-go\/qrencode\"\n\t\"fmt\"\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/mattn\/go-colorable\"\n\t\"io\/ioutil\"\n\t\"os\"\n\n\t\"github.com\/fumiyas\/qrc\/lib\"\n\t\"github.com\/fumiyas\/go-tty\"\n)\n\ntype cmdOptions struct {\n\tHelp    bool `short:\"h\" long:\"help\" description:\"show this help message\"`\n\tInverse bool `short:\"i\" long:\"invert\" description:\"invert color\"`\n}\n\nfunc showHelp() {\n\tconst v = `Usage: qrc [OPTIONS] [TEXT]\n\nOptions:\n  -h, --help\n    Show this help message\n  -i, --invert\n    Invert color\n\nText examples:\n  http:\/\/www.example.jp\/\n  MAILTO:foobar@example.jp\n  WIFI:S:myssid;T:WPA;P:pass123;;\n`\n\n\tos.Stderr.Write([]byte(v))\n}\n\nfunc pErr(format string, a ...interface{}) {\n\tfmt.Fprint(os.Stdout, os.Args[0], \": \")\n\tfmt.Fprintf(os.Stdout, format, a...)\n}\n\nfunc main() {\n\tret := 0\n\tdefer func() { os.Exit(ret) }()\n\n\topts := &cmdOptions{}\n\toptsParser := flags.NewParser(opts, flags.PrintErrors)\n\targs, err := optsParser.Parse()\n\tif err != nil || len(args) > 1 {\n\t\tshowHelp()\n\t\tret = 1\n\t\treturn\n\t}\n\tif opts.Help {\n\t\tshowHelp()\n\t\treturn\n\t}\n\n\tvar text string\n\tif len(args) == 1 {\n\t\ttext = args[0]\n\t} else {\n\t\ttext_bytes, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tpErr(\"read from stdin failed: %v\\n\", err)\n\t\t\tret = 1\n\t\t\treturn\n\t\t}\n\t\ttext = string(text_bytes)\n\t}\n\n\tgrid, err := qrencode.Encode(text, qrencode.ECLevelL)\n\tif err != nil {\n\t\tpErr(\"encode failed: %v\\n\", err)\n\t\tret = 1\n\t\treturn\n\t}\n\n\tda1, err := tty.GetDeviceAttributes1(os.Stdout)\n\tif err == nil && da1[tty.DA1_SIXEL] {\n\t\tqrc.PrintSixel(os.Stdout, grid, opts.Inverse)\n\t} else {\n\t\tstdout := colorable.NewColorableStdout()\n\t\tqrc.PrintAA(stdout, grid, opts.Inverse)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package rcd\n\nimport (\n\t\"archive\/zip\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/rclone\/rclone\/cmd\"\n\t\"github.com\/rclone\/rclone\/fs\"\n\t\"github.com\/rclone\/rclone\/fs\/config\"\n\t\"github.com\/rclone\/rclone\/fs\/rc\/rcflags\"\n\t\"github.com\/rclone\/rclone\/fs\/rc\/rcserver\"\n\t\"github.com\/rclone\/rclone\/lib\/errors\"\n\t\"github.com\/rclone\/rclone\/lib\/random\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nfunc init() {\n\tcmd.Root.AddCommand(commandDefinition)\n}\n\nvar commandDefinition = &cobra.Command{\n\tUse:   \"rcd <path to files to serve>*\",\n\tShort: `Run rclone listening to remote control commands only.`,\n\tLong: `\nThis runs rclone so that it only listens to remote control commands.\n\nThis is useful if you are controlling rclone via the rc API.\n\nIf you pass in a path to a directory, rclone will serve that directory\nfor GET requests on the URL passed in.  It will also open the URL in\nthe browser when rclone is run.\n\nSee the [rc documentation](\/rc\/) for more info on the rc flags.\n`,\n\tRun: func(command *cobra.Command, args []string) {\n\t\tcmd.CheckArgs(0, 1, command, args)\n\t\tif rcflags.Opt.Enabled {\n\t\t\tlog.Fatalf(\"Don't supply --rc flag when using rcd\")\n\t\t}\n\n\t\t\/\/ Start the rc\n\t\trcflags.Opt.Enabled = true\n\t\tif len(args) > 0 {\n\t\t\trcflags.Opt.Files = args[0]\n\t\t}\n\n\t\tif rcflags.Opt.WebUI {\n\t\t\tif err := checkRelease(rcflags.Opt.WebGUIUpdate); err != nil {\n\t\t\t\tlog.Fatalf(\"Error while fetching the latest release of rclone-webui-react %v\", err)\n\t\t\t}\n\t\t\tif rcflags.Opt.NoAuth {\n\t\t\t\trcflags.Opt.NoAuth = false\n\t\t\t\tfs.Infof(nil, \"Cannot run web-gui without authentication, using default auth\")\n\t\t\t}\n\t\t\tif rcflags.Opt.HTTPOptions.BasicUser == \"\" {\n\t\t\t\trcflags.Opt.HTTPOptions.BasicUser = \"gui\"\n\t\t\t\tfs.Infof(nil, \"Using default username: %s \\n\", rcflags.Opt.HTTPOptions.BasicUser)\n\t\t\t}\n\t\t\tif rcflags.Opt.HTTPOptions.BasicPass == \"\" {\n\t\t\t\trandomPass, err := random.Password(128)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"Failed to make password: %v\", err)\n\t\t\t\t}\n\t\t\t\trcflags.Opt.HTTPOptions.BasicPass = randomPass\n\t\t\t\tfs.Infof(nil, \"No password specified. Using random password: %s \\n\", randomPass)\n\t\t\t}\n\t\t\trcflags.Opt.Serve = true\n\t\t}\n\n\t\ts, err := rcserver.Start(&rcflags.Opt)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to start remote control: %v\", err)\n\t\t}\n\t\tif s == nil {\n\t\t\tlog.Fatal(\"rc server not configured\")\n\t\t}\n\n\t\ts.Wait()\n\t},\n}\n\n\/\/checkRelease is a helper function to download and setup latest release of rclone-webui-react\nfunc checkRelease(shouldUpdate bool) (err error) {\n\tcachePath := filepath.Join(config.CacheDir, \"webgui\")\n\textractPath := filepath.Join(cachePath, \"current\")\n\toldUpdateExists := exists(extractPath)\n\n\t\/\/ if the old file exists does not exist or forced update is enforced.\n\t\/\/ TODO: Add hashing to check integrity of the previous update.\n\tif !oldUpdateExists || shouldUpdate {\n\t\t\/\/ Get the latest release details\n\t\tWebUIURL, tag, size, err := getLatestReleaseURL()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tzipName := tag + \".zip\"\n\t\tzipPath := filepath.Join(cachePath, zipName)\n\n\t\tif !exists(cachePath) {\n\t\t\tif err := os.MkdirAll(cachePath, 0755); err != nil {\n\t\t\t\tfs.Logf(nil, \"Error creating cache directory: %s\", cachePath)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tfs.Logf(nil, \"A new release for gui is present at \"+WebUIURL)\n\t\tfs.Logf(nil, \"Downloading webgui binary. Please wait. [Size: %s, Path :  %s]\\n\", strconv.Itoa(size), zipPath)\n\n\t\t\/\/ download the zip from latest url\n\t\terr = downloadFile(zipPath, WebUIURL)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = os.RemoveAll(extractPath)\n\t\tif err != nil {\n\t\t\tfs.Logf(nil, \"No previous downloads to remove\")\n\t\t}\n\t\tfs.Logf(nil, \"Unzipping\")\n\t\terr = unzip(zipPath, extractPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t} else {\n\t\tfs.Logf(nil, \"Required files exist. Skipping download\")\n\t}\n\treturn nil\n}\n\n\/\/ getLatestReleaseURL returns the latest release details of the rclone-webui-react\nfunc getLatestReleaseURL() (string, string, int, error) {\n\tresp, err := http.Get(rcflags.Opt.WebGUIFetchURL)\n\tif err != nil {\n\t\treturn \"\", \"\", 0, errors.New(\"Error getting latest release of rclone-webui\")\n\t}\n\tresults := gitHubRequest{}\n\tif err := json.NewDecoder(resp.Body).Decode(&results); err != nil {\n\t\treturn \"\", \"\", 0, errors.New(\"Could not decode results from http request\")\n\t}\n\n\tres := results.Assets[0].BrowserDownloadURL\n\ttag := results.TagName\n\tsize := results.Assets[0].Size\n\t\/\/fmt.Println( \"URL:\" + res)\n\n\treturn res, tag, size, nil\n\n}\n\n\/\/ downloadFile is a helper function to download a file from url to the filepath\nfunc downloadFile(filepath string, url string) error {\n\n\t\/\/ Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fs.CheckClose(resp.Body, &err)\n\n\t\/\/ Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fs.CheckClose(out, &err)\n\n\t\/\/ Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}\n\n\/\/ unzip is a helper function to unzip a file specified in src to path dest\nfunc unzip(src, dest string) (err error) {\n\tr, err := zip.OpenReader(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fs.CheckClose(r, &err)\n\n\tif err := os.MkdirAll(dest, 0755); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Closure to address file descriptors issue with all the deferred .Close() methods\n\textractAndWriteFile := func(f *zip.File) error {\n\t\trc, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer fs.CheckClose(rc, &err)\n\n\t\tpath := filepath.Join(dest, f.Name)\n\n\t\tif f.FileInfo().IsDir() {\n\t\t\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tf, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer fs.CheckClose(f, &err)\n\n\t\t\t_, err = io.Copy(f, rc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tfor _, f := range r.File {\n\t\terr := extractAndWriteFile(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ exists returns whether the given file or directory exists\nfunc exists(path string) bool {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ gitHubRequest Maps the GitHub API request to structure\ntype gitHubRequest struct {\n\tURL string `json:\"url\"`\n\n\tPrerelease  bool      `json:\"prerelease\"`\n\tCreatedAt   time.Time `json:\"created_at\"`\n\tPublishedAt time.Time `json:\"published_at\"`\n\tTagName     string    `json:\"tag_name\"`\n\tAssets      []struct {\n\t\tURL                string    `json:\"url\"`\n\t\tID                 int       `json:\"id\"`\n\t\tNodeID             string    `json:\"node_id\"`\n\t\tName               string    `json:\"name\"`\n\t\tLabel              string    `json:\"label\"`\n\t\tContentType        string    `json:\"content_type\"`\n\t\tState              string    `json:\"state\"`\n\t\tSize               int       `json:\"size\"`\n\t\tDownloadCount      int       `json:\"download_count\"`\n\t\tCreatedAt          time.Time `json:\"created_at\"`\n\t\tUpdatedAt          time.Time `json:\"updated_at\"`\n\t\tBrowserDownloadURL string    `json:\"browser_download_url\"`\n\t} `json:\"assets\"`\n\tTarballURL string `json:\"tarball_url\"`\n\tZipballURL string `json:\"zipball_url\"`\n\tBody       string `json:\"body\"`\n}\n<commit_msg>cmd\/rcd: Address ZipSlip vulnerability<commit_after>package rcd\n\nimport (\n\t\"archive\/zip\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/rclone\/rclone\/cmd\"\n\t\"github.com\/rclone\/rclone\/fs\"\n\t\"github.com\/rclone\/rclone\/fs\/config\"\n\t\"github.com\/rclone\/rclone\/fs\/rc\/rcflags\"\n\t\"github.com\/rclone\/rclone\/fs\/rc\/rcserver\"\n\t\"github.com\/rclone\/rclone\/lib\/errors\"\n\t\"github.com\/rclone\/rclone\/lib\/random\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nfunc init() {\n\tcmd.Root.AddCommand(commandDefinition)\n}\n\nvar commandDefinition = &cobra.Command{\n\tUse:   \"rcd <path to files to serve>*\",\n\tShort: `Run rclone listening to remote control commands only.`,\n\tLong: `\nThis runs rclone so that it only listens to remote control commands.\n\nThis is useful if you are controlling rclone via the rc API.\n\nIf you pass in a path to a directory, rclone will serve that directory\nfor GET requests on the URL passed in.  It will also open the URL in\nthe browser when rclone is run.\n\nSee the [rc documentation](\/rc\/) for more info on the rc flags.\n`,\n\tRun: func(command *cobra.Command, args []string) {\n\t\tcmd.CheckArgs(0, 1, command, args)\n\t\tif rcflags.Opt.Enabled {\n\t\t\tlog.Fatalf(\"Don't supply --rc flag when using rcd\")\n\t\t}\n\n\t\t\/\/ Start the rc\n\t\trcflags.Opt.Enabled = true\n\t\tif len(args) > 0 {\n\t\t\trcflags.Opt.Files = args[0]\n\t\t}\n\n\t\tif rcflags.Opt.WebUI {\n\t\t\tif err := checkRelease(rcflags.Opt.WebGUIUpdate); err != nil {\n\t\t\t\tlog.Fatalf(\"Error while fetching the latest release of rclone-webui-react %v\", err)\n\t\t\t}\n\t\t\tif rcflags.Opt.NoAuth {\n\t\t\t\trcflags.Opt.NoAuth = false\n\t\t\t\tfs.Infof(nil, \"Cannot run web-gui without authentication, using default auth\")\n\t\t\t}\n\t\t\tif rcflags.Opt.HTTPOptions.BasicUser == \"\" {\n\t\t\t\trcflags.Opt.HTTPOptions.BasicUser = \"gui\"\n\t\t\t\tfs.Infof(nil, \"Using default username: %s \\n\", rcflags.Opt.HTTPOptions.BasicUser)\n\t\t\t}\n\t\t\tif rcflags.Opt.HTTPOptions.BasicPass == \"\" {\n\t\t\t\trandomPass, err := random.Password(128)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"Failed to make password: %v\", err)\n\t\t\t\t}\n\t\t\t\trcflags.Opt.HTTPOptions.BasicPass = randomPass\n\t\t\t\tfs.Infof(nil, \"No password specified. Using random password: %s \\n\", randomPass)\n\t\t\t}\n\t\t\trcflags.Opt.Serve = true\n\t\t}\n\n\t\ts, err := rcserver.Start(&rcflags.Opt)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to start remote control: %v\", err)\n\t\t}\n\t\tif s == nil {\n\t\t\tlog.Fatal(\"rc server not configured\")\n\t\t}\n\n\t\ts.Wait()\n\t},\n}\n\n\/\/checkRelease is a helper function to download and setup latest release of rclone-webui-react\nfunc checkRelease(shouldUpdate bool) (err error) {\n\tcachePath := filepath.Join(config.CacheDir, \"webgui\")\n\textractPath := filepath.Join(cachePath, \"current\")\n\toldUpdateExists := exists(extractPath)\n\n\t\/\/ if the old file exists does not exist or forced update is enforced.\n\t\/\/ TODO: Add hashing to check integrity of the previous update.\n\tif !oldUpdateExists || shouldUpdate {\n\t\t\/\/ Get the latest release details\n\t\tWebUIURL, tag, size, err := getLatestReleaseURL()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tzipName := tag + \".zip\"\n\t\tzipPath := filepath.Join(cachePath, zipName)\n\n\t\tif !exists(cachePath) {\n\t\t\tif err := os.MkdirAll(cachePath, 0755); err != nil {\n\t\t\t\tfs.Logf(nil, \"Error creating cache directory: %s\", cachePath)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tfs.Logf(nil, \"A new release for gui is present at \"+WebUIURL)\n\t\tfs.Logf(nil, \"Downloading webgui binary. Please wait. [Size: %s, Path :  %s]\\n\", strconv.Itoa(size), zipPath)\n\n\t\t\/\/ download the zip from latest url\n\t\terr = downloadFile(zipPath, WebUIURL)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = os.RemoveAll(extractPath)\n\t\tif err != nil {\n\t\t\tfs.Logf(nil, \"No previous downloads to remove\")\n\t\t}\n\t\tfs.Logf(nil, \"Unzipping\")\n\t\terr = unzip(zipPath, extractPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t} else {\n\t\tfs.Logf(nil, \"Required files exist. Skipping download\")\n\t}\n\treturn nil\n}\n\n\/\/ getLatestReleaseURL returns the latest release details of the rclone-webui-react\nfunc getLatestReleaseURL() (string, string, int, error) {\n\tresp, err := http.Get(rcflags.Opt.WebGUIFetchURL)\n\tif err != nil {\n\t\treturn \"\", \"\", 0, errors.New(\"Error getting latest release of rclone-webui\")\n\t}\n\tresults := gitHubRequest{}\n\tif err := json.NewDecoder(resp.Body).Decode(&results); err != nil {\n\t\treturn \"\", \"\", 0, errors.New(\"Could not decode results from http request\")\n\t}\n\n\tres := results.Assets[0].BrowserDownloadURL\n\ttag := results.TagName\n\tsize := results.Assets[0].Size\n\t\/\/fmt.Println( \"URL:\" + res)\n\n\treturn res, tag, size, nil\n\n}\n\n\/\/ downloadFile is a helper function to download a file from url to the filepath\nfunc downloadFile(filepath string, url string) error {\n\n\t\/\/ Get the data\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fs.CheckClose(resp.Body, &err)\n\n\t\/\/ Create the file\n\tout, err := os.Create(filepath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fs.CheckClose(out, &err)\n\n\t\/\/ Write the body to file\n\t_, err = io.Copy(out, resp.Body)\n\treturn err\n}\n\n\/\/ unzip is a helper function to unzip a file specified in src to path dest\nfunc unzip(src, dest string) (err error) {\n\tdest = filepath.Clean(dest) + string(os.PathSeparator)\n\n\tr, err := zip.OpenReader(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fs.CheckClose(r, &err)\n\n\tif err := os.MkdirAll(dest, 0755); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Closure to address file descriptors issue with all the deferred .Close() methods\n\textractAndWriteFile := func(f *zip.File) error {\n\t\tpath := filepath.Join(dest, f.Name)\n\t\t\/\/ Check for Zip Slip: https:\/\/github.com\/rclone\/rclone\/issues\/3529\n\t\tif !strings.HasPrefix(path, dest) {\n\t\t\treturn fmt.Errorf(\"%s: illegal file path\", path)\n\t\t}\n\n\t\trc, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer fs.CheckClose(rc, &err)\n\n\t\tif f.FileInfo().IsDir() {\n\t\t\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tf, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer fs.CheckClose(f, &err)\n\n\t\t\t_, err = io.Copy(f, rc)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tfor _, f := range r.File {\n\t\terr := extractAndWriteFile(f)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ exists returns whether the given file or directory exists\nfunc exists(path string) bool {\n\t_, err := os.Stat(path)\n\tif err == nil {\n\t\treturn true\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ gitHubRequest Maps the GitHub API request to structure\ntype gitHubRequest struct {\n\tURL string `json:\"url\"`\n\n\tPrerelease  bool      `json:\"prerelease\"`\n\tCreatedAt   time.Time `json:\"created_at\"`\n\tPublishedAt time.Time `json:\"published_at\"`\n\tTagName     string    `json:\"tag_name\"`\n\tAssets      []struct {\n\t\tURL                string    `json:\"url\"`\n\t\tID                 int       `json:\"id\"`\n\t\tNodeID             string    `json:\"node_id\"`\n\t\tName               string    `json:\"name\"`\n\t\tLabel              string    `json:\"label\"`\n\t\tContentType        string    `json:\"content_type\"`\n\t\tState              string    `json:\"state\"`\n\t\tSize               int       `json:\"size\"`\n\t\tDownloadCount      int       `json:\"download_count\"`\n\t\tCreatedAt          time.Time `json:\"created_at\"`\n\t\tUpdatedAt          time.Time `json:\"updated_at\"`\n\t\tBrowserDownloadURL string    `json:\"browser_download_url\"`\n\t} `json:\"assets\"`\n\tTarballURL string `json:\"tarball_url\"`\n\tZipballURL string `json:\"zipball_url\"`\n\tBody       string `json:\"body\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tBuildVersion     = \"unknown\"\n\tBuildDate        = \"unknown\"\n\tBuildHash        = \"unknown\"\n\tBuildEnvironment = \"unknown\"\n)\n\nfunc NewVersionCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"version\",\n\t\tShort: \"shows version of this application\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Printf(\"version:     %s\\n\", BuildVersion)\n\t\t\tfmt.Printf(\"build date:  %s\\n\", BuildDate)\n\t\t\tfmt.Printf(\"scm hash:    %s\\n\", BuildHash)\n\t\t\tfmt.Printf(\"environment: %s\\n\", BuildEnvironment)\n\t\t},\n\t}\n\n\treturn cmd\n}\n<commit_msg>add go version to version command (#800)<commit_after>package cmd\n\nimport (\n\t\"fmt\"\n\t\"runtime\/debug\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tBuildVersion     = \"unknown\"\n\tBuildDate        = \"unknown\"\n\tBuildHash        = \"unknown\"\n\tBuildEnvironment = \"unknown\"\n)\n\nfunc NewVersionCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"version\",\n\t\tShort: \"shows version of this application\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Printf(\"version:     %s\\n\", BuildVersion)\n\t\t\tfmt.Printf(\"build date:  %s\\n\", BuildDate)\n\t\t\tfmt.Printf(\"scm hash:    %s\\n\", BuildHash)\n\t\t\tfmt.Printf(\"environment: %s\\n\", BuildEnvironment)\n\n\t\t\tbi, ok := debug.ReadBuildInfo()\n\t\t\tif ok && bi != nil {\n\t\t\t\tfmt.Printf(\"go version:  %s\\n\", bi.GoVersion)\n\t\t\t}\n\t\t},\n\t}\n\n\treturn cmd\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2022 ezbuy & LITB Team\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar CommitHash string\n\nfunc version(commit string) string {\n\tif commit == \"\" {\n\t\treturn fmt.Sprintf(\"ezorm v%d.%d.%d\", vMajor, vMinor, vPatch)\n\t}\n\treturn fmt.Sprintf(\"ezorm v%d.%d.%d-%s\", vMajor, vMinor, vPatch, commit)\n}\n\nconst (\n\tvMajor = 2\n\tvMinor = 5\n\tvPatch = 5\n)\n\n\/\/ versionCmd represents the version command\nvar versionCmd = &cobra.Command{\n\tUse:   \"version\",\n\tShort: \"EzOrm 版本信息\",\n\tLong:  `EzOrm 版本信息`,\n\tRun: func(_ *cobra.Command, _ []string) {\n\t\tfmt.Fprintln(os.Stdout, version(CommitHash))\n\t},\n}\n\nfunc init() {\n\tRootCmd.AddCommand(versionCmd)\n}\n<commit_msg>cmd: bump version to 2.5.6<commit_after>\/\/ Copyright © 2022 ezbuy & LITB Team\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar CommitHash string\n\nfunc version(commit string) string {\n\tif commit == \"\" {\n\t\treturn fmt.Sprintf(\"ezorm v%d.%d.%d\", vMajor, vMinor, vPatch)\n\t}\n\treturn fmt.Sprintf(\"ezorm v%d.%d.%d-%s\", vMajor, vMinor, vPatch, commit)\n}\n\nconst (\n\tvMajor = 2\n\tvMinor = 5\n\tvPatch = 6\n)\n\n\/\/ versionCmd represents the version command\nvar versionCmd = &cobra.Command{\n\tUse:   \"version\",\n\tShort: \"EzOrm 版本信息\",\n\tLong:  `EzOrm 版本信息`,\n\tRun: func(_ *cobra.Command, _ []string) {\n\t\tfmt.Fprintln(os.Stdout, version(CommitHash))\n\t},\n}\n\nfunc init() {\n\tRootCmd.AddCommand(versionCmd)\n}\n<|endoftext|>"}
{"text":"<commit_before>package acidic\n\ntype TransactionAggregate struct {\n\tmessages MessageContainer\n}\n\nfunc NewTransactionAggregate(messages MessageContainer) *TransactionAggregate {\n\treturn &TransactionAggregate{\n\t\tmessages: messages,\n\t}\n}\n\nfunc (this *TransactionAggregate) Handle(message interface{}) error {\n\tswitch message := message.(type) {\n\n\tcase StoreItemCommand:\n\t\treturn this.handleStoreItem(message)\n\tcase ItemStoredEvent:\n\t\treturn this.handleItemStored(message)\n\tcase ItemStoreFailedEvent:\n\t\treturn this.handleItemStoreFailed(message)\n\n\tcase DeleteItemCommand:\n\t\treturn this.handleDeleteItem(message)\n\tcase ItemDeletedEvent:\n\t\treturn this.handleItemDeleted(message)\n\tcase ItemDeleteFailedEvent:\n\t\treturn this.handleItemDeleteFailed(message)\n\n\tcase CommitTransactionCommand:\n\t\treturn this.handleCommitTransaction(message)\n\tcase TransactionCommittedEvent:\n\t\treturn this.handleTransactionCommitted(message)\n\n\tcase TransactionFailedEvent:\n\t\treturn this.handleTransactionFailed(message)\n\n\tcase AbortTransactionCommand:\n\t\treturn this.handleAbortTransaction(message)\n\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (this *TransactionAggregate) handleStoreItem(message StoreItemCommand) error {\n\treturn nil\n}\nfunc (this *TransactionAggregate) handleItemStored(message ItemStoredEvent) error {\n\treturn nil\n}\nfunc (this *TransactionAggregate) handleItemStoreFailed(message ItemStoreFailedEvent) error {\n\treturn nil\n}\n\nfunc (this *TransactionAggregate) handleDeleteItem(message DeleteItemCommand) error {\n\treturn nil\n}\nfunc (this *TransactionAggregate) handleItemDeleted(message ItemDeletedEvent) error {\n\treturn nil\n}\nfunc (this *TransactionAggregate) handleItemDeleteFailed(message ItemDeleteFailedEvent) error {\n\treturn nil\n}\n\nfunc (this *TransactionAggregate) handleCommitTransaction(message CommitTransactionCommand) error {\n\treturn nil\n}\nfunc (this *TransactionAggregate) handleTransactionCommitted(message TransactionCommittedEvent) error {\n\treturn nil\n}\n\nfunc (this *TransactionAggregate) handleTransactionFailed(message TransactionFailedEvent) error {\n\treturn nil\n}\n\nfunc (this *TransactionAggregate) handleAbortTransaction(message AbortTransactionCommand) error {\n\treturn nil\n}\n\nfunc (this *TransactionAggregate) Replay(message interface{}) {\n\t\/\/ for this project, we won't be event sourcing, but this is here to indicate a minor breakthrough in how events\n\t\/\/ both internal and external--are processed.\n\tthis.apply(message)\n}\nfunc (this *TransactionAggregate) raise(message interface{}) {\n\tthis.messages.Add(message)\n\tthis.apply(message)\n}\nfunc (this *TransactionAggregate) apply(message interface{}) {\n\tswitch message := message.(type) {\n\n\tcase TransactionStartedEvent:\n\t\tthis.applyTransactionStarted(message)\n\n\tcase StoringItemEvent:\n\t\tthis.applyStoringItem(message)\n\tcase ItemStoredEvent:\n\t\tthis.applyItemStored(message)\n\tcase ItemStoreFailedEvent:\n\t\tthis.applyItemStoreFailed(message)\n\n\tcase DeletingItemEvent:\n\t\tthis.applyDeletingItem(message)\n\tcase ItemDeletedEvent:\n\t\tthis.applyItemDeleted(message)\n\tcase ItemDeleteFailedEvent:\n\t\tthis.applyItemDeleteFailed(message)\n\n\tcase TransactionCommittingEvent:\n\t\tthis.applyTransactionCommitting(message)\n\tcase TransactionCommittedEvent:\n\t\tthis.applyTransactionCommitted(message)\n\n\tcase TransactionFailedEvent:\n\t\tthis.applyTransactionFailed(message)\n\n\tcase TransactionAbortedEvent:\n\t\tthis.applyTransactionAborted(message)\n\tcase TransactionAbortFailedEvent:\n\t\tthis.applyTransactionAbortFailed(message)\n\t}\n}\n\nfunc (this *TransactionAggregate) applyTransactionStarted(message TransactionStartedEvent) {\n}\n\nfunc (this *TransactionAggregate) applyStoringItem(message StoringItemEvent) {\n}\nfunc (this *TransactionAggregate) applyItemStored(message ItemStoredEvent) {\n}\nfunc (this *TransactionAggregate) applyItemStoreFailed(message ItemStoreFailedEvent) {\n}\n\nfunc (this *TransactionAggregate) applyDeletingItem(message DeletingItemEvent) {\n}\nfunc (this *TransactionAggregate) applyItemDeleted(message ItemDeletedEvent) {\n}\nfunc (this *TransactionAggregate) applyItemDeleteFailed(message ItemDeleteFailedEvent) {\n}\n\nfunc (this *TransactionAggregate) applyTransactionCommitting(message TransactionCommittingEvent) {\n}\nfunc (this *TransactionAggregate) applyTransactionCommitted(message TransactionCommittedEvent) {\n}\n\nfunc (this *TransactionAggregate) applyTransactionFailed(message TransactionFailedEvent) {\n}\n\nfunc (this *TransactionAggregate) applyTransactionAborted(message TransactionAbortedEvent) {\n}\nfunc (this *TransactionAggregate) applyTransactionAbortFailed(message TransactionAbortFailedEvent) {\n}\n<commit_msg>Renamed internal message container.<commit_after>package acidic\n\ntype TransactionAggregate struct {\n\traised MessageContainer\n}\n\nfunc NewTransactionAggregate(raised MessageContainer) *TransactionAggregate {\n\treturn &TransactionAggregate{\n\t\traised: raised,\n\t}\n}\n\nfunc (this *TransactionAggregate) Handle(message interface{}) error {\n\tswitch message := message.(type) {\n\n\tcase StoreItemCommand:\n\t\treturn this.handleStoreItem(message)\n\tcase ItemStoredEvent:\n\t\treturn this.handleItemStored(message)\n\tcase ItemStoreFailedEvent:\n\t\treturn this.handleItemStoreFailed(message)\n\n\tcase DeleteItemCommand:\n\t\treturn this.handleDeleteItem(message)\n\tcase ItemDeletedEvent:\n\t\treturn this.handleItemDeleted(message)\n\tcase ItemDeleteFailedEvent:\n\t\treturn this.handleItemDeleteFailed(message)\n\n\tcase CommitTransactionCommand:\n\t\treturn this.handleCommitTransaction(message)\n\tcase TransactionCommittedEvent:\n\t\treturn this.handleTransactionCommitted(message)\n\n\tcase TransactionFailedEvent:\n\t\treturn this.handleTransactionFailed(message)\n\n\tcase AbortTransactionCommand:\n\t\treturn this.handleAbortTransaction(message)\n\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (this *TransactionAggregate) handleStoreItem(message StoreItemCommand) error {\n\treturn nil\n}\nfunc (this *TransactionAggregate) handleItemStored(message ItemStoredEvent) error {\n\treturn nil\n}\nfunc (this *TransactionAggregate) handleItemStoreFailed(message ItemStoreFailedEvent) error {\n\treturn nil\n}\n\nfunc (this *TransactionAggregate) handleDeleteItem(message DeleteItemCommand) error {\n\treturn nil\n}\nfunc (this *TransactionAggregate) handleItemDeleted(message ItemDeletedEvent) error {\n\treturn nil\n}\nfunc (this *TransactionAggregate) handleItemDeleteFailed(message ItemDeleteFailedEvent) error {\n\treturn nil\n}\n\nfunc (this *TransactionAggregate) handleCommitTransaction(message CommitTransactionCommand) error {\n\treturn nil\n}\nfunc (this *TransactionAggregate) handleTransactionCommitted(message TransactionCommittedEvent) error {\n\treturn nil\n}\n\nfunc (this *TransactionAggregate) handleTransactionFailed(message TransactionFailedEvent) error {\n\treturn nil\n}\n\nfunc (this *TransactionAggregate) handleAbortTransaction(message AbortTransactionCommand) error {\n\treturn nil\n}\n\nfunc (this *TransactionAggregate) Replay(message interface{}) {\n\t\/\/ for this project, we won't be event sourcing, but this is here to indicate a minor breakthrough in how events\n\t\/\/ both internal and external--are processed.\n\tthis.apply(message)\n}\nfunc (this *TransactionAggregate) raise(message interface{}) {\n\tthis.raised.Add(message)\n\tthis.apply(message)\n}\nfunc (this *TransactionAggregate) apply(message interface{}) {\n\tswitch message := message.(type) {\n\n\tcase TransactionStartedEvent:\n\t\tthis.applyTransactionStarted(message)\n\n\tcase StoringItemEvent:\n\t\tthis.applyStoringItem(message)\n\tcase ItemStoredEvent:\n\t\tthis.applyItemStored(message)\n\tcase ItemStoreFailedEvent:\n\t\tthis.applyItemStoreFailed(message)\n\n\tcase DeletingItemEvent:\n\t\tthis.applyDeletingItem(message)\n\tcase ItemDeletedEvent:\n\t\tthis.applyItemDeleted(message)\n\tcase ItemDeleteFailedEvent:\n\t\tthis.applyItemDeleteFailed(message)\n\n\tcase TransactionCommittingEvent:\n\t\tthis.applyTransactionCommitting(message)\n\tcase TransactionCommittedEvent:\n\t\tthis.applyTransactionCommitted(message)\n\n\tcase TransactionFailedEvent:\n\t\tthis.applyTransactionFailed(message)\n\n\tcase TransactionAbortedEvent:\n\t\tthis.applyTransactionAborted(message)\n\tcase TransactionAbortFailedEvent:\n\t\tthis.applyTransactionAbortFailed(message)\n\t}\n}\n\nfunc (this *TransactionAggregate) applyTransactionStarted(message TransactionStartedEvent) {\n}\n\nfunc (this *TransactionAggregate) applyStoringItem(message StoringItemEvent) {\n}\nfunc (this *TransactionAggregate) applyItemStored(message ItemStoredEvent) {\n}\nfunc (this *TransactionAggregate) applyItemStoreFailed(message ItemStoreFailedEvent) {\n}\n\nfunc (this *TransactionAggregate) applyDeletingItem(message DeletingItemEvent) {\n}\nfunc (this *TransactionAggregate) applyItemDeleted(message ItemDeletedEvent) {\n}\nfunc (this *TransactionAggregate) applyItemDeleteFailed(message ItemDeleteFailedEvent) {\n}\n\nfunc (this *TransactionAggregate) applyTransactionCommitting(message TransactionCommittingEvent) {\n}\nfunc (this *TransactionAggregate) applyTransactionCommitted(message TransactionCommittedEvent) {\n}\n\nfunc (this *TransactionAggregate) applyTransactionFailed(message TransactionFailedEvent) {\n}\n\nfunc (this *TransactionAggregate) applyTransactionAborted(message TransactionAbortedEvent) {\n}\nfunc (this *TransactionAggregate) applyTransactionAbortFailed(message TransactionAbortFailedEvent) {\n}\n<|endoftext|>"}
{"text":"<commit_before>package grpc\n\nimport (\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/quan-xie\/tuba\/util\/xtime\"\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/keepalive\"\n\t\"google.golang.org\/grpc\/reflection\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype ServerConfig struct {\n\tNetwork           string\n\tAddr              string\n\tTimeout           xtime.Duration\n\tIdleTimeout       xtime.Duration\n\tMaxLifeTime       xtime.Duration\n\tForceCloseWait    xtime.Duration\n\tKeepAliveInterval xtime.Duration\n\tKeepAliveTimeout  xtime.Duration\n\tLogFlag           int8\n}\n\ntype Server struct {\n\tconf  *ServerConfig\n\tmutex sync.RWMutex\n\n\tserver      *grpc.Server\n\tinterceptor []grpc.UnaryServerInterceptor\n}\n\nfunc NewServer(c *ServerConfig, opts ...grpc.ServerOption) (s *Server, err error) {\n\ts = &Server{}\n\tif err := s.configuration(c); err != nil {\n\t\tpanic(\"grpc config error\")\n\t}\n\tkp := grpc.KeepaliveParams(keepalive.ServerParameters{\n\t\tMaxConnectionIdle:     0,\n\t\tMaxConnectionAge:      0,\n\t\tMaxConnectionAgeGrace: 0,\n\t\tTime:                  0,\n\t\tTimeout:               0,\n\t})\n\topts = append(opts, kp)\n\ts.server = grpc.NewServer(opts...)\n\treturn\n}\n\nfunc (s *Server) Start() (err error) {\n\tlistener, err := net.Listen(\"tcp\", s.conf.Addr)\n\tif err != nil {\n\t\terr = errors.WithStack(err)\n\t\treturn\n\t}\n\treflection.Register(s.server)\n\treturn s.Serve(listener)\n}\n\nfunc (s *Server) Use(interceptors ...grpc.UnaryServerInterceptor) *Server {\n\ts.interceptor = append(s.interceptor, interceptors...)\n\treturn s\n}\n\nfunc (s *Server) Serve(lis net.Listener) error {\n\treturn s.server.Serve(lis)\n}\n\nfunc (s *Server) Server() *grpc.Server {\n\treturn s.server\n}\n\nfunc (s *Server) configuration(c *ServerConfig) (err error) {\n\tif c.Addr == \"\" {\n\t\tc.Addr = \"0.0.0.0:9000\"\n\t}\n\tif c.Network == \"\" {\n\t\tc.Network = \"tcp\"\n\t}\n\tif c.Timeout <= 0 {\n\t\tc.Timeout = xtime.Duration(time.Second)\n\t}\n\tif c.IdleTimeout <= 0 {\n\t\tc.IdleTimeout = xtime.Duration(time.Second * 60)\n\t}\n\tif c.MaxLifeTime <= 0 {\n\t\tc.MaxLifeTime = xtime.Duration(time.Hour * 2)\n\t}\n\tif c.ForceCloseWait <= 0 {\n\t\tc.ForceCloseWait = xtime.Duration(time.Second * 20)\n\t}\n\tif c.KeepAliveInterval <= 0 {\n\t\tc.KeepAliveInterval = xtime.Duration(time.Second * 60)\n\t}\n\tif c.KeepAliveTimeout <= 0 {\n\t\tc.KeepAliveTimeout = xtime.Duration(time.Second * 20)\n\t}\n\ts.mutex.Lock()\n\ts.conf = c\n\ts.mutex.Unlock()\n\treturn\n}\n<commit_msg>update grpc server<commit_after>package grpc\n\nimport (\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/quan-xie\/tuba\/log\"\n\t\"github.com\/quan-xie\/tuba\/util\/xtime\"\n\txgprc \"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/keepalive\"\n\t\"google.golang.org\/grpc\/reflection\"\n)\n\ntype ServerConfig struct {\n\tNetwork           string\n\tAddr              string\n\tTimeout           xtime.Duration\n\tIdleTimeout       xtime.Duration\n\tMaxLifeTime       xtime.Duration\n\tForceCloseWait    xtime.Duration\n\tKeepAliveInterval xtime.Duration\n\tKeepAliveTimeout  xtime.Duration\n\tLogFlag           int8\n}\n\ntype Server struct {\n\tconf  *ServerConfig\n\tmutex sync.RWMutex\n\n\tserver      *xgprc.Server\n\tinterceptor []xgprc.UnaryServerInterceptor\n}\n\nfunc NewServer(c *ServerConfig, opts ...xgprc.ServerOption) (s *Server, err error) {\n\ts = &Server{}\n\tif err := s.configuration(c); err != nil {\n\t\tpanic(\"grpc config error\")\n\t}\n\tkp := xgprc.KeepaliveParams(keepalive.ServerParameters{\n\t\tMaxConnectionIdle:     0,\n\t\tMaxConnectionAge:      0,\n\t\tMaxConnectionAgeGrace: 0,\n\t\tTime:                  0,\n\t\tTimeout:               0,\n\t})\n\topts = append(opts, kp)\n\ts.server = xgprc.NewServer(opts...)\n\treturn\n}\n\nfunc (s *Server) Start() {\n\tvar err error\n\tl, err := net.Listen(\"tcp\", s.conf.Addr)\n\tif err != nil {\n\t\terr = errors.WithStack(err)\n\t\tlog.Fatalf(\"failed to net Listen: %v\", err)\n\t\treturn\n\t}\n\treflection.Register(s.server)\n\tgo func() {\n\t\tlog.Infof(\"grpc server succeed listening at %v\", l.Addr())\n\t\tif err := s.server.Serve(l); err != nil {\n\t\t\terr = errors.WithStack(err)\n\t\t\tlog.Fatalf(\"failed to serve: %v\", err)\n\t\t}\n\t}()\n}\n\nfunc (s *Server) Stop() {\n\ts.server.Stop()\n}\n\nfunc (s *Server) Use(interceptors ...xgprc.UnaryServerInterceptor) *Server {\n\ts.interceptor = append(s.interceptor, interceptors...)\n\treturn s\n}\n\nfunc (s *Server) Serve(lis net.Listener) error {\n\treturn s.server.Serve(lis)\n}\n\nfunc (s *Server) Server() *xgprc.Server {\n\treturn s.server\n}\n\nfunc (s *Server) configuration(c *ServerConfig) (err error) {\n\tif c.Addr == \"\" {\n\t\tc.Addr = \"0.0.0.0:9000\"\n\t}\n\tif c.Network == \"\" {\n\t\tc.Network = \"tcp\"\n\t}\n\tif c.Timeout <= 0 {\n\t\tc.Timeout = xtime.Duration(time.Second)\n\t}\n\tif c.IdleTimeout <= 0 {\n\t\tc.IdleTimeout = xtime.Duration(time.Second * 60)\n\t}\n\tif c.MaxLifeTime <= 0 {\n\t\tc.MaxLifeTime = xtime.Duration(time.Hour * 2)\n\t}\n\tif c.ForceCloseWait <= 0 {\n\t\tc.ForceCloseWait = xtime.Duration(time.Second * 20)\n\t}\n\tif c.KeepAliveInterval <= 0 {\n\t\tc.KeepAliveInterval = xtime.Duration(time.Second * 60)\n\t}\n\tif c.KeepAliveTimeout <= 0 {\n\t\tc.KeepAliveTimeout = xtime.Duration(time.Second * 20)\n\t}\n\ts.mutex.Lock()\n\ts.conf = c\n\ts.mutex.Unlock()\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ command\/run.go\n\/\/\n\/\/ Copyright (c) 2016-2017 Junpei Kawamoto\n\/\/\n\/\/ This software is released under the MIT License.\n\/\/\n\/\/ http:\/\/opensource.org\/licenses\/mit-license.php\n\/\/\n\npackage command\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\n\tcolorable \"github.com\/mattn\/go-colorable\"\n\tgitconfig \"github.com\/tcnksm\/go-gitconfig\"\n\t\"github.com\/ttacon\/chalk\"\n\t\"github.com\/urfave\/cli\"\n)\n\n\/\/ SourceArchive defines a name of source archive file.\nconst SourceArchive = \"source.tar.gz\"\n\n\/\/ RunOpt defines a option parameter for run function.\ntype RunOpt struct {\n\t\/\/ Same options as DockerfileOpt.\n\t*DockerfileOpt\n\t\/\/ Travis configuration file.\n\tFilename string\n\t\/\/ Container name.\n\tName string\n\t\/\/ Runtime version to which only versions matching will be run.\n\tVersion string\n\t\/\/ Image tag.\n\tTag string\n\t\/\/ Max processors to be used.\n\tProcessors int\n\t\/\/ If true, logging information to be stored to files.\n\tOutputLog bool\n\t\/\/ If true, not using cache during buidling a docker image.\n\tNoCache bool\n\t\/\/ If true, omit printing color codes.\n\tNoColor bool\n\t\/\/ Printed on the header.\n\tTitle string\n}\n\n\/\/ Run implements the action of this command.\nfunc Run(c *cli.Context) error {\n\n\topt := RunOpt{\n\t\tDockerfileOpt: &DockerfileOpt{\n\t\t\tBaseImage:  c.String(\"base\"),\n\t\t\tAptProxy:   c.String(\"apt-proxy\"),\n\t\t\tPypiProxy:  c.String(\"pypi-proxy\"),\n\t\t\tHTTPProxy:  c.String(\"http-proxy\"),\n\t\t\tHTTPSProxy: c.String(\"https-proxy\"),\n\t\t\tNoProxy:    c.String(\"no-proxy\"),\n\t\t},\n\t\tFilename:   c.Args().First(),\n\t\tName:       c.String(\"name\"),\n\t\tVersion:    c.String(\"select\"),\n\t\tTag:        c.String(\"tag\"),\n\t\tProcessors: c.Int(\"max-processors\"),\n\t\tOutputLog:  c.Bool(\"log\"),\n\t\tNoCache:    c.Bool(\"no-cache\"),\n\t\tNoColor:    c.Bool(\"no-color\"),\n\t\tTitle:      fmt.Sprintf(\"%v %v\", c.App.Name, c.App.Version),\n\t}\n\tif err := run(&opt); err != nil {\n\t\treturn cli.NewExitError(err.Error(), 1)\n\t}\n\treturn nil\n}\n\nfunc run(opt *RunOpt) (err error) {\n\n\t\/\/ Prepare to be canceled.\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, os.Interrupt, os.Kill, syscall.SIGQUIT)\n\tgo func() {\n\t\t<-sig\n\t\tcancel()\n\t}()\n\n\t\/\/ Prepare interface.\n\tdisplay, ctx, err := NewDisplay(ctx, opt.Title, opt.Processors)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer display.Close()\n\tlogger := display.Header.Logger\n\n\tvar stdout io.Writer\n\tif opt.NoColor {\n\t\tstdout = colorable.NewNonColorable(os.Stdout)\n\t\tlogger = colorable.NewNonColorable(logger)\n\t\tcli.ErrWriter = colorable.NewNonColorable(cli.ErrWriter)\n\t} else {\n\t\tstdout = colorable.NewColorableStdout()\n\t}\n\n\t\/\/ Load a Travis's script file.\n\tif opt.Filename == \"\" {\n\t\topt.Filename = \".travis.yml\"\n\t}\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Loading .travis.yml\"))\n\n\ttravis, err := NewTravisFromFile(opt.Filename)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Get repository information.\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Checking repository information\"))\n\torigin, err := gitconfig.OriginURL()\n\tif err != nil {\n\t\treturn\n\t}\n\topt.Repository = getRepository(origin)\n\n\t\/\/ Set up the tag name of the container image.\n\tif opt.Tag == \"\" {\n\t\topt.Tag = fmt.Sprintf(\"loci\/%s\", strings.ToLower(path.Base(opt.Repository)))\n\t}\n\n\t\/\/ Prepare docker images.\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Preparing docker images for sandbox containers\"))\n\terr = PrepareBaseImage(ctx, opt.BaseImage, logger)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Archive source files.\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Archiving source code\"))\n\ttempDir := filepath.Join(os.TempDir(), opt.Tag)\n\tif err = os.MkdirAll(tempDir, 0777); err != nil {\n\t\treturn\n\t}\n\tdefer os.RemoveAll(tempDir)\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = Archive(ctx, pwd, filepath.Join(tempDir, SourceArchive)); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Create Dockerfile.\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Creating Dockerfile\"))\n\tdocker, err := Dockerfile(travis, opt.DockerfileOpt, SourceArchive)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = ioutil.WriteFile(filepath.Join(tempDir, \"Dockerfile\"), docker, 0644); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Create entrypoint.sh.\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Creating entrypoint.sh\"))\n\tentry, err := Entrypoint(travis)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = ioutil.WriteFile(filepath.Join(tempDir, \"entrypoint.sh\"), entry, 0644); err != nil {\n\t\treturn\n\t}\n\n\targset, err := travis.ArgumentSet(logger)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Start testing with goroutines.\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Building sandbox images and running tests\"))\n\tvar i int\n\tvar wg sync.WaitGroup\n\tsemaphore := make(chan struct{}, opt.Processors)\n\terrs := NewErrorSet()\n\tfor version, set := range argset {\n\n\t\tif opt.Version != \"\" && version != opt.Version {\n\t\t\tcontinue\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func(version string, set [][]string) (err error) {\n\t\t\tsemaphore <- struct{}{}\n\t\t\tdefer func() {\n\t\t\t\t<-semaphore\n\t\t\t\twg.Done()\n\t\t\t}()\n\n\t\t\t\/\/ Build a container image.\n\t\t\tsec := display.AddSection(fmt.Sprintf(\"Building a docker image for %v\", version))\n\t\t\tdefer display.DeleteSection(sec)\n\n\t\t\tvar output io.Writer\n\t\t\twriter := sec.Writer()\n\t\t\tdefer writer.Close()\n\t\t\toutput = writer\n\t\t\tif opt.NoColor {\n\t\t\t\toutput = colorable.NewNonColorable(output)\n\t\t\t}\n\n\t\t\tif opt.OutputLog {\n\t\t\t\tvar fp *os.File\n\t\t\t\tfp, err = os.OpenFile(fmt.Sprintf(\"loci-build-%v.log\", version), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrs.Add(version, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tdefer fp.Close()\n\t\t\t\toutput = io.MultiWriter(output, colorable.NewColorable(fp))\n\t\t\t}\n\n\t\t\ttag := fmt.Sprintf(\"%v\/%v\", opt.Tag, version)\n\t\t\terr = Build(ctx, tempDir, tag, version, opt.NoCache, output)\n\t\t\tif err == context.Canceled {\n\t\t\t\terrs.Add(\"\", err)\n\t\t\t\treturn\n\t\t\t} else if err != nil {\n\t\t\t\tmsg := fmt.Sprintf(chalk.Red.Color(\"Faild to build a docker image for %v\"), version)\n\t\t\t\terrs.Add(\n\t\t\t\t\tversion,\n\t\t\t\t\tfmt.Errorf(\"%v\\n%v\\n%v\\n\", msg, err.Error(), sec.String()))\n\t\t\t\tfmt.Fprintln(logger, msg)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Fprintln(logger, chalk.Green.Color(fmt.Sprintf(\"Built a docker image for %v\", version)))\n\n\t\t\tfor _, envs := range set {\n\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func(envs []string) {\n\t\t\t\t\tsemaphore <- struct{}{}\n\t\t\t\t\tdefer func() {\n\t\t\t\t\t\t<-semaphore\n\t\t\t\t\t\twg.Done()\n\t\t\t\t\t}()\n\n\t\t\t\t\t\/\/ Run tests in a sandbox.\n\t\t\t\t\tsec := display.AddSection(fmt.Sprintf(\"Running tests (%v: %v)\", version, envs))\n\t\t\t\t\tdefer display.DeleteSection(sec)\n\n\t\t\t\t\tvar output io.Writer\n\t\t\t\t\twriter := sec.Writer()\n\t\t\t\t\tdefer writer.Close()\n\t\t\t\t\toutput = writer\n\t\t\t\t\tif opt.NoColor {\n\t\t\t\t\t\toutput = colorable.NewNonColorable(output)\n\t\t\t\t\t}\n\n\t\t\t\t\tif opt.OutputLog {\n\t\t\t\t\t\tvar fp *os.File\n\t\t\t\t\t\tfp, err = os.OpenFile(\n\t\t\t\t\t\t\tfmt.Sprintf(\"loci-%v.log\", strings.Join(append([]string{version}, envs...), \"-\")),\n\t\t\t\t\t\t\tos.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrs.Add(fmt.Sprintf(\"%v:%v\", version, envs), err)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer fp.Close()\n\t\t\t\t\t\toutput = io.MultiWriter(output, colorable.NewColorable(fp))\n\t\t\t\t\t}\n\n\t\t\t\t\tname := opt.Name\n\t\t\t\t\tif name != \"\" {\n\t\t\t\t\t\ti++\n\t\t\t\t\t\tname = fmt.Sprintf(\"%s-%d\", name, i)\n\t\t\t\t\t}\n\n\t\t\t\t\terr = Start(ctx, tag, name, envs, output)\n\t\t\t\t\tif err == context.Canceled {\n\t\t\t\t\t\terrs.Add(\"\", err)\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\terrs.Add(fmt.Sprintf(\"%v:%v\", version, envs), fmt.Errorf(\"%s\\n%s\", chalk.Red.Color(err.Error()), sec.String()))\n\t\t\t\t\t\tfmt.Fprintln(logger, chalk.Red.Color(fmt.Sprintf(\"Failed tests (%v: %v) \", version, envs)))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Fprintln(logger, chalk.Green.Color(fmt.Sprintf(\"Passed tests (%v: %v) \", version, envs)))\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\n\t\t\t\t}(envs)\n\n\t\t\t}\n\n\t\t\treturn\n\n\t\t}(version, set)\n\n\t}\n\n\twg.Wait()\n\terr = display.Close()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif errs.Size() == 0 {\n\t\tfmt.Fprintln(stdout, chalk.Green.Color(\"All tests have been passed.\"))\n\t} else {\n\t\terrList := errs.GetList()\n\t\tif errList[0] == context.Canceled {\n\t\t\terr = cli.NewExitError(\"canceled\", 1)\n\t\t} else {\n\t\t\terr = cli.NewMultiError(errList...)\n\t\t}\n\t}\n\treturn\n\n}\n\n\/\/ getRepository returns the repository path from a given remote URL of\n\/\/ origin repository. The repository path consists of a URL without\n\/\/ sheme, user name, password, and .git suffix.\nfunc getRepository(origin string) (res string) {\n\n\tswitch {\n\tcase strings.Contains(origin, \"@\"):\n\t\tres = strings.Replace(strings.Split(origin, \"@\")[1], \":\", \"\/\", 1)\n\tcase strings.HasPrefix(origin, \"http:\/\/\"):\n\t\tres = origin[len(\"http:\/\/\"):]\n\tcase strings.HasPrefix(origin, \"https:\/\/\"):\n\t\tres = origin[len(\"https:\/\/\"):]\n\tdefault:\n\t\tres = strings.Replace(origin, \":\", \"\/\", 1)\n\t}\n\tif strings.HasSuffix(res, \".git\") {\n\t\tres = res[:len(res)-len(\".git\")]\n\t}\n\n\treturn\n\n}\n<commit_msg>Output log messages even if tests are canceled but some of them are failed.<commit_after>\/\/\n\/\/ command\/run.go\n\/\/\n\/\/ Copyright (c) 2016-2017 Junpei Kawamoto\n\/\/\n\/\/ This software is released under the MIT License.\n\/\/\n\/\/ http:\/\/opensource.org\/licenses\/mit-license.php\n\/\/\n\npackage command\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\n\tcolorable \"github.com\/mattn\/go-colorable\"\n\tgitconfig \"github.com\/tcnksm\/go-gitconfig\"\n\t\"github.com\/ttacon\/chalk\"\n\t\"github.com\/urfave\/cli\"\n)\n\n\/\/ SourceArchive defines a name of source archive file.\nconst SourceArchive = \"source.tar.gz\"\n\n\/\/ RunOpt defines a option parameter for run function.\ntype RunOpt struct {\n\t\/\/ Same options as DockerfileOpt.\n\t*DockerfileOpt\n\t\/\/ Travis configuration file.\n\tFilename string\n\t\/\/ Container name.\n\tName string\n\t\/\/ Runtime version to which only versions matching will be run.\n\tVersion string\n\t\/\/ Image tag.\n\tTag string\n\t\/\/ Max processors to be used.\n\tProcessors int\n\t\/\/ If true, logging information to be stored to files.\n\tOutputLog bool\n\t\/\/ If true, not using cache during buidling a docker image.\n\tNoCache bool\n\t\/\/ If true, omit printing color codes.\n\tNoColor bool\n\t\/\/ Printed on the header.\n\tTitle string\n}\n\n\/\/ Run implements the action of this command.\nfunc Run(c *cli.Context) error {\n\n\topt := RunOpt{\n\t\tDockerfileOpt: &DockerfileOpt{\n\t\t\tBaseImage:  c.String(\"base\"),\n\t\t\tAptProxy:   c.String(\"apt-proxy\"),\n\t\t\tPypiProxy:  c.String(\"pypi-proxy\"),\n\t\t\tHTTPProxy:  c.String(\"http-proxy\"),\n\t\t\tHTTPSProxy: c.String(\"https-proxy\"),\n\t\t\tNoProxy:    c.String(\"no-proxy\"),\n\t\t},\n\t\tFilename:   c.Args().First(),\n\t\tName:       c.String(\"name\"),\n\t\tVersion:    c.String(\"select\"),\n\t\tTag:        c.String(\"tag\"),\n\t\tProcessors: c.Int(\"max-processors\"),\n\t\tOutputLog:  c.Bool(\"log\"),\n\t\tNoCache:    c.Bool(\"no-cache\"),\n\t\tNoColor:    c.Bool(\"no-color\"),\n\t\tTitle:      fmt.Sprintf(\"%v %v\", c.App.Name, c.App.Version),\n\t}\n\tif err := run(&opt); err != nil {\n\t\treturn cli.NewExitError(err.Error(), 1)\n\t}\n\treturn nil\n}\n\nfunc run(opt *RunOpt) (err error) {\n\n\t\/\/ Prepare to be canceled.\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\tsig := make(chan os.Signal, 1)\n\tsignal.Notify(sig, os.Interrupt, os.Kill, syscall.SIGQUIT)\n\tgo func() {\n\t\t<-sig\n\t\tcancel()\n\t}()\n\n\t\/\/ Prepare interface.\n\tdisplay, ctx, err := NewDisplay(ctx, opt.Title, opt.Processors)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer display.Close()\n\tlogger := display.Header.Logger\n\n\tvar stdout io.Writer\n\tif opt.NoColor {\n\t\tstdout = colorable.NewNonColorable(os.Stdout)\n\t\tlogger = colorable.NewNonColorable(logger)\n\t\tcli.ErrWriter = colorable.NewNonColorable(cli.ErrWriter)\n\t} else {\n\t\tstdout = colorable.NewColorableStdout()\n\t}\n\n\t\/\/ Load a Travis's script file.\n\tif opt.Filename == \"\" {\n\t\topt.Filename = \".travis.yml\"\n\t}\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Loading .travis.yml\"))\n\n\ttravis, err := NewTravisFromFile(opt.Filename)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Get repository information.\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Checking repository information\"))\n\torigin, err := gitconfig.OriginURL()\n\tif err != nil {\n\t\treturn\n\t}\n\topt.Repository = getRepository(origin)\n\n\t\/\/ Set up the tag name of the container image.\n\tif opt.Tag == \"\" {\n\t\topt.Tag = fmt.Sprintf(\"loci\/%s\", strings.ToLower(path.Base(opt.Repository)))\n\t}\n\n\t\/\/ Prepare docker images.\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Preparing docker images for sandbox containers\"))\n\terr = PrepareBaseImage(ctx, opt.BaseImage, logger)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Archive source files.\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Archiving source code\"))\n\ttempDir := filepath.Join(os.TempDir(), opt.Tag)\n\tif err = os.MkdirAll(tempDir, 0777); err != nil {\n\t\treturn\n\t}\n\tdefer os.RemoveAll(tempDir)\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = Archive(ctx, pwd, filepath.Join(tempDir, SourceArchive)); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Create Dockerfile.\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Creating Dockerfile\"))\n\tdocker, err := Dockerfile(travis, opt.DockerfileOpt, SourceArchive)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = ioutil.WriteFile(filepath.Join(tempDir, \"Dockerfile\"), docker, 0644); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Create entrypoint.sh.\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Creating entrypoint.sh\"))\n\tentry, err := Entrypoint(travis)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = ioutil.WriteFile(filepath.Join(tempDir, \"entrypoint.sh\"), entry, 0644); err != nil {\n\t\treturn\n\t}\n\n\targset, err := travis.ArgumentSet(logger)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Start testing with goroutines.\n\tfmt.Fprintln(logger, chalk.Cyan.Color(\"Building sandbox images and running tests\"))\n\tvar i int\n\tvar wg sync.WaitGroup\n\tsemaphore := make(chan struct{}, opt.Processors)\n\terrs := NewErrorSet()\n\tfor version, set := range argset {\n\n\t\tif opt.Version != \"\" && version != opt.Version {\n\t\t\tcontinue\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func(version string, set [][]string) (err error) {\n\t\t\tsemaphore <- struct{}{}\n\t\t\tdefer func() {\n\t\t\t\t<-semaphore\n\t\t\t\twg.Done()\n\t\t\t}()\n\n\t\t\t\/\/ Build a container image.\n\t\t\tsec := display.AddSection(fmt.Sprintf(\"Building a docker image for %v\", version))\n\t\t\tdefer display.DeleteSection(sec)\n\n\t\t\tvar output io.Writer\n\t\t\twriter := sec.Writer()\n\t\t\tdefer writer.Close()\n\t\t\toutput = writer\n\t\t\tif opt.NoColor {\n\t\t\t\toutput = colorable.NewNonColorable(output)\n\t\t\t}\n\n\t\t\tif opt.OutputLog {\n\t\t\t\tvar fp *os.File\n\t\t\t\tfp, err = os.OpenFile(fmt.Sprintf(\"loci-build-%v.log\", version), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrs.Add(version, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tdefer fp.Close()\n\t\t\t\toutput = io.MultiWriter(output, colorable.NewColorable(fp))\n\t\t\t}\n\n\t\t\ttag := fmt.Sprintf(\"%v\/%v\", opt.Tag, version)\n\t\t\terr = Build(ctx, tempDir, tag, version, opt.NoCache, output)\n\t\t\tif err == context.Canceled {\n\t\t\t\terrs.Add(\"\", err)\n\t\t\t\treturn\n\t\t\t} else if err != nil {\n\t\t\t\tmsg := fmt.Sprintf(chalk.Red.Color(\"Faild to build a docker image for %v\"), version)\n\t\t\t\terrs.Add(\n\t\t\t\t\tversion,\n\t\t\t\t\tfmt.Errorf(\"%v\\n%v\\n%v\\n\", msg, err.Error(), sec.String()))\n\t\t\t\tfmt.Fprintln(logger, msg)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Fprintln(logger, chalk.Green.Color(fmt.Sprintf(\"Built a docker image for %v\", version)))\n\n\t\t\tfor _, envs := range set {\n\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func(envs []string) {\n\t\t\t\t\tsemaphore <- struct{}{}\n\t\t\t\t\tdefer func() {\n\t\t\t\t\t\t<-semaphore\n\t\t\t\t\t\twg.Done()\n\t\t\t\t\t}()\n\n\t\t\t\t\t\/\/ Run tests in a sandbox.\n\t\t\t\t\tsec := display.AddSection(fmt.Sprintf(\"Running tests (%v: %v)\", version, envs))\n\t\t\t\t\tdefer display.DeleteSection(sec)\n\n\t\t\t\t\tvar output io.Writer\n\t\t\t\t\twriter := sec.Writer()\n\t\t\t\t\tdefer writer.Close()\n\t\t\t\t\toutput = writer\n\t\t\t\t\tif opt.NoColor {\n\t\t\t\t\t\toutput = colorable.NewNonColorable(output)\n\t\t\t\t\t}\n\n\t\t\t\t\tif opt.OutputLog {\n\t\t\t\t\t\tvar fp *os.File\n\t\t\t\t\t\tfp, err = os.OpenFile(\n\t\t\t\t\t\t\tfmt.Sprintf(\"loci-%v.log\", strings.Join(append([]string{version}, envs...), \"-\")),\n\t\t\t\t\t\t\tos.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrs.Add(fmt.Sprintf(\"%v:%v\", version, envs), err)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer fp.Close()\n\t\t\t\t\t\toutput = io.MultiWriter(output, colorable.NewColorable(fp))\n\t\t\t\t\t}\n\n\t\t\t\t\tname := opt.Name\n\t\t\t\t\tif name != \"\" {\n\t\t\t\t\t\ti++\n\t\t\t\t\t\tname = fmt.Sprintf(\"%s-%d\", name, i)\n\t\t\t\t\t}\n\n\t\t\t\t\terr = Start(ctx, tag, name, envs, output)\n\t\t\t\t\tif err == context.Canceled {\n\t\t\t\t\t\terrs.Add(\"\", err)\n\t\t\t\t\t} else if err != nil {\n\t\t\t\t\t\terrs.Add(fmt.Sprintf(\"%v:%v\", version, envs), fmt.Errorf(\"%s\\n%s\", chalk.Red.Color(err.Error()), sec.String()))\n\t\t\t\t\t\tfmt.Fprintln(logger, chalk.Red.Color(fmt.Sprintf(\"Failed tests (%v: %v) \", version, envs)))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Fprintln(logger, chalk.Green.Color(fmt.Sprintf(\"Passed tests (%v: %v) \", version, envs)))\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\n\t\t\t\t}(envs)\n\n\t\t\t}\n\n\t\t\treturn\n\n\t\t}(version, set)\n\n\t}\n\n\twg.Wait()\n\terr = display.Close()\n\tif err != nil {\n\t\terrs.Add(\"\", err)\n\t}\n\n\tif errs.Size() == 0 {\n\t\tfmt.Fprintln(stdout, chalk.Green.Color(\"All tests have been passed.\"))\n\t} else {\n\t\terrList := errs.GetList()\n\t\terr = cli.NewMultiError(errList...)\n\t}\n\treturn\n\n}\n\n\/\/ getRepository returns the repository path from a given remote URL of\n\/\/ origin repository. The repository path consists of a URL without\n\/\/ sheme, user name, password, and .git suffix.\nfunc getRepository(origin string) (res string) {\n\n\tswitch {\n\tcase strings.Contains(origin, \"@\"):\n\t\tres = strings.Replace(strings.Split(origin, \"@\")[1], \":\", \"\/\", 1)\n\tcase strings.HasPrefix(origin, \"http:\/\/\"):\n\t\tres = origin[len(\"http:\/\/\"):]\n\tcase strings.HasPrefix(origin, \"https:\/\/\"):\n\t\tres = origin[len(\"https:\/\/\"):]\n\tdefault:\n\t\tres = strings.Replace(origin, \":\", \"\/\", 1)\n\t}\n\tif strings.HasSuffix(res, \".git\") {\n\t\tres = res[:len(res)-len(\".git\")]\n\t}\n\n\treturn\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package command\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/mitchellh\/cli\"\n)\n\n\/\/ BuildCommand is a Command implementation that generates Packer templates\n\/\/ from named Builds.\ntype RunCommand struct {\n\tUi cli.Ui\n}\n\nfunc (c *RunCommand) Help() string {\n\thelpText := `\n    Usage: rancher Run [options]\n\n        Generates Packer templates. At minimum, this command needs to be run\n        with at least one RunList name. \n\n            rancher run example1\n\n        The above command generates Packer templates from all of the Rancher\n\tBuilds that have been specified within the RunList 'example1'.\n\n    Options:\n\n        -log-level=info         Log level for Rancher.\n`\n\treturn strings.TrimSpace(helpText)\n}\n\nfunc (c *RunCommand) Run(args []string) int {\n\tvar logLevel string\n\n\tcmdFlags := flag.NewFlagSet(\"run\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { c.Ui.Output(c.Help()) }\n\tcmdFlags.StringVar(&logLevel, \"log-level\", \"INFO\", \"log level\")\n\n\tfmt.Printf(\"%+v\\n\", args)\n\n\treturn 0\n\n}\n\nfunc (c *RunCommand) Synopsis() string {\n\treturn \"Create Packer templates from the Rancher Build templates specified in the passed RunList.\"\n}\n<commit_msg>updated run command info<commit_after>package command\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/mitchellh\/cli\"\n)\n\n\/\/ BuildCommand is a Command implementation that generates Packer templates\n\/\/ from named Builds.\ntype RunCommand struct {\n\tUi cli.Ui\n}\n\nfunc (c *RunCommand) Help() string {\n\thelpText := `\n    Usage: rancher Run <BuildList names...>\n\n        Generates Packer templates. At minimum, this command needs to be run\n        with at least one BuildList name. Multiple BuildList names can be\n\tspecified by using a space separated list.\n\n            rancher run example1\n\n        The above command generates Packer templates from all of the Rancher\n\tBuilds that have been specified within the RunList 'example1'.\n`\n\treturn strings.TrimSpace(helpText)\n}\n\nfunc (c *RunCommand) Run(args []string) int {\n\tvar logLevel string\n\n\tcmdFlags := flag.NewFlagSet(\"run\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { c.Ui.Output(c.Help()) }\n\tcmdFlags.StringVar(&logLevel, \"log-level\", \"INFO\", \"log level\")\n\n\tfmt.Printf(\"%+v\\n\", args)\n\n\treturn 0\n\n}\n\nfunc (c *RunCommand) Synopsis() string {\n\treturn \"Create Packer templates from the Rancher Build templates specified in the passed BuildList(s).\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package commands\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/olekukonko\/tablewriter\"\n\tdocker \"github.com\/yungsang\/dockerclient\"\n)\n\nfunc CommandPs(ctx *cli.Context) {\n\tclient, err := docker.NewDockerClient(ctx.GlobalString(\"host\"), nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar filters = \"\"\n\tif ctx.Bool(\"latest\") {\n\t\tfilters += \"&limit=1\"\n\t}\n\tif ctx.Bool(\"size\") {\n\t\tfilters += \"&size=1\"\n\t}\n\n\tcontainers, err := client.ListContainers(ctx.Bool(\"all\"), ctx.Bool(\"size\"), filters)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif ctx.Bool(\"quiet\") {\n\t\tfor _, container := range containers {\n\t\t\tfmt.Println(Truncate(container.Id, 12))\n\t\t}\n\t\treturn\n\t}\n\n\ttrimNamePrefix := func(ss []string) []string {\n\t\tfor i, s := range ss {\n\t\t\tss[i] = strings.TrimPrefix(s, \"\/\")\n\t\t}\n\t\treturn ss\n\t}\n\n\tformatPorts := func(ports []docker.Port) string {\n\t\tresult := []string{}\n\t\tfor _, p := range ports {\n\t\t\tresult = append(result, fmt.Sprintf(\"%s:%d->%d\/%s\",\n\t\t\t\tp.IP, p.PublicPort, p.PrivatePort, p.Type))\n\t\t}\n\t\treturn strings.Join(result, \", \")\n\t}\n\n\tvar items [][]string\n\tfor _, container := range containers {\n\t\tout := []string{\n\t\t\tTruncate(container.Id, 12),\n\t\t\tstrings.Join(trimNamePrefix(container.Names), \", \"),\n\t\t\tcontainer.Image,\n\t\t\tTruncate(container.Command, 20),\n\t\t\tFormatDateTime(time.Unix(container.Created, 0)),\n\t\t\tcontainer.Status,\n\t\t\tformatPorts(container.Ports),\n\t\t}\n\t\tif ctx.Bool(\"size\") {\n\t\t\tout = append(out, fmt.Sprintf(\"%.4g MB\", float64(container.SizeRw)\/1000000.0))\n\t\t}\n\t\titems = append(items, out)\n\t}\n\n\tvar header = []string{\n\t\t\"ID\",\n\t\t\"Names\",\n\t\t\"Image\",\n\t\t\"Command\",\n\t\t\"Created\",\n\t\t\"Status\",\n\t\t\"Ports\",\n\t}\n\tif ctx.Bool(\"size\") {\n\t\theader = append(header, \"Size\")\n\t}\n\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetHeader(header)\n\ttable.SetBorder(false)\n\ttable.AppendBulk(items)\n\ttable.Render()\n}\n<commit_msg>Revise a header<commit_after>package commands\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/olekukonko\/tablewriter\"\n\tdocker \"github.com\/yungsang\/dockerclient\"\n)\n\nfunc CommandPs(ctx *cli.Context) {\n\tclient, err := docker.NewDockerClient(ctx.GlobalString(\"host\"), nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar filters = \"\"\n\tif ctx.Bool(\"latest\") {\n\t\tfilters += \"&limit=1\"\n\t}\n\tif ctx.Bool(\"size\") {\n\t\tfilters += \"&size=1\"\n\t}\n\n\tcontainers, err := client.ListContainers(ctx.Bool(\"all\"), ctx.Bool(\"size\"), filters)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif ctx.Bool(\"quiet\") {\n\t\tfor _, container := range containers {\n\t\t\tfmt.Println(Truncate(container.Id, 12))\n\t\t}\n\t\treturn\n\t}\n\n\ttrimNamePrefix := func(ss []string) []string {\n\t\tfor i, s := range ss {\n\t\t\tss[i] = strings.TrimPrefix(s, \"\/\")\n\t\t}\n\t\treturn ss\n\t}\n\n\tformatPorts := func(ports []docker.Port) string {\n\t\tresult := []string{}\n\t\tfor _, p := range ports {\n\t\t\tresult = append(result, fmt.Sprintf(\"%s:%d->%d\/%s\",\n\t\t\t\tp.IP, p.PublicPort, p.PrivatePort, p.Type))\n\t\t}\n\t\treturn strings.Join(result, \", \")\n\t}\n\n\tvar items [][]string\n\tfor _, container := range containers {\n\t\tout := []string{\n\t\t\tTruncate(container.Id, 12),\n\t\t\tstrings.Join(trimNamePrefix(container.Names), \", \"),\n\t\t\tcontainer.Image,\n\t\t\tTruncate(container.Command, 20),\n\t\t\tFormatDateTime(time.Unix(container.Created, 0)),\n\t\t\tcontainer.Status,\n\t\t\tformatPorts(container.Ports),\n\t\t}\n\t\tif ctx.Bool(\"size\") {\n\t\t\tout = append(out, fmt.Sprintf(\"%.4g MB\", float64(container.SizeRw)\/1000000.0))\n\t\t}\n\t\titems = append(items, out)\n\t}\n\n\tvar header = []string{\n\t\t\"ID\",\n\t\t\"Names\",\n\t\t\"Image\",\n\t\t\"Command\",\n\t\t\"Created at\",\n\t\t\"Status\",\n\t\t\"Ports\",\n\t}\n\tif ctx.Bool(\"size\") {\n\t\theader = append(header, \"Size\")\n\t}\n\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetHeader(header)\n\ttable.SetBorder(false)\n\ttable.AppendBulk(items)\n\ttable.Render()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Andreas Koch. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage orchestrator\n\nimport (\n\t\"allmark.io\/modules\/model\"\n\t\"allmark.io\/modules\/web\/view\/viewmodel\"\n\t\"fmt\"\n)\n\ntype FeedOrchestrator struct {\n\t*Orchestrator\n}\n\nfunc (orchestrator *FeedOrchestrator) GetRootEntry(baseUrl string) viewmodel.FeedEntry {\n\n\trootItem := orchestrator.rootItem()\n\tif rootItem == nil {\n\t\torchestrator.logger.Fatal(\"No root item found.\")\n\t}\n\n\treturn orchestrator.createFeedEntryModel(baseUrl, rootItem)\n}\n\nfunc (orchestrator *FeedOrchestrator) GetEntries(baseUrl string, itemsPerPage, page int) (entries []viewmodel.FeedEntry, found bool) {\n\n\t\/\/ validate page number\n\tif page < 1 {\n\t\torchestrator.logger.Fatal(\"Invalid page number (%v).\", page)\n\t}\n\n\trootItem := orchestrator.rootItem()\n\tif rootItem == nil {\n\t\torchestrator.logger.Fatal(\"No root item found\")\n\t}\n\n\tfeedEntries := make([]viewmodel.FeedEntry, 0)\n\n\tlatestItems, found := pagedItems(orchestrator.getLatestItems(rootItem.Route()), itemsPerPage, page)\n\tif !found {\n\t\treturn feedEntries, false\n\t}\n\n\tfor _, item := range latestItems {\n\t\tfeedEntries = append(feedEntries, orchestrator.createFeedEntryModel(baseUrl, item))\n\t}\n\n\treturn feedEntries, true\n}\n\nfunc (orchestrator *FeedOrchestrator) createFeedEntryModel(baseUrl string, item *model.Item) viewmodel.FeedEntry {\n\n\taddressPrefix := fmt.Sprintf(\"%s\/\", baseUrl)\n\tpathProvider := orchestrator.absolutePather(addressPrefix)\n\n\t\/\/ item location\n\tlocation := pathProvider.Path(item.Route().Value())\n\n\t\/\/ content\n\tcontent, err := orchestrator.converter.Convert(orchestrator.getItemByAlias, pathProvider, item)\n\tif err != nil {\n\t\tcontent = err.Error()\n\t}\n\n\t\/\/ creation date\n\tcreationDate := item.MetaData.CreationDate.Format(\"2006-01-02\")\n\n\treturn viewmodel.FeedEntry{\n\t\tTitle:       item.Title,\n\t\tDescription: content,\n\t\tLink:        location,\n\t\tPubDate:     creationDate,\n\t}\n}\n<commit_msg>Bug Fix \"RSS Feed Entry Urls are Malformed\": Use the correct path provider for rss feed item content.<commit_after>\/\/ Copyright 2014 Andreas Koch. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage orchestrator\n\nimport (\n\t\"allmark.io\/modules\/model\"\n\t\"allmark.io\/modules\/web\/view\/viewmodel\"\n\t\"fmt\"\n)\n\ntype FeedOrchestrator struct {\n\t*Orchestrator\n}\n\nfunc (orchestrator *FeedOrchestrator) GetRootEntry(baseUrl string) viewmodel.FeedEntry {\n\n\trootItem := orchestrator.rootItem()\n\tif rootItem == nil {\n\t\torchestrator.logger.Fatal(\"No root item found.\")\n\t}\n\n\treturn orchestrator.createFeedEntryModel(baseUrl, rootItem)\n}\n\nfunc (orchestrator *FeedOrchestrator) GetEntries(baseUrl string, itemsPerPage, page int) (entries []viewmodel.FeedEntry, found bool) {\n\n\t\/\/ validate page number\n\tif page < 1 {\n\t\torchestrator.logger.Fatal(\"Invalid page number (%v).\", page)\n\t}\n\n\trootItem := orchestrator.rootItem()\n\tif rootItem == nil {\n\t\torchestrator.logger.Fatal(\"No root item found\")\n\t}\n\n\tfeedEntries := make([]viewmodel.FeedEntry, 0)\n\n\tlatestItems, found := pagedItems(orchestrator.getLatestItems(rootItem.Route()), itemsPerPage, page)\n\tif !found {\n\t\treturn feedEntries, false\n\t}\n\n\tfor _, item := range latestItems {\n\t\tfeedEntries = append(feedEntries, orchestrator.createFeedEntryModel(baseUrl, item))\n\t}\n\n\treturn feedEntries, true\n}\n\nfunc (orchestrator *FeedOrchestrator) createFeedEntryModel(baseUrl string, item *model.Item) viewmodel.FeedEntry {\n\n\titemPathProvider := orchestrator.absolutePather(fmt.Sprintf(\"%s\/\", baseUrl))\n\titemContentPathProvider := orchestrator.absolutePather(fmt.Sprintf(\"%s\/%s\/\", baseUrl, item.Route().Value()))\n\n\t\/\/ item location\n\tlocation := itemPathProvider.Path(item.Route().Value())\n\n\t\/\/ content\n\tcontent, err := orchestrator.converter.Convert(orchestrator.getItemByAlias, itemContentPathProvider, item)\n\tif err != nil {\n\t\tcontent = err.Error()\n\t}\n\n\t\/\/ creation date\n\tcreationDate := item.MetaData.CreationDate.Format(\"2006-01-02\")\n\n\treturn viewmodel.FeedEntry{\n\t\tTitle:       item.Title,\n\t\tDescription: content,\n\t\tLink:        location,\n\t\tPubDate:     creationDate,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package dns\n\nimport (\n\t\/\/ \"fmt\"\n\n\t\"github.com\/jcelliott\/lumber\"\n\n\t\"github.com\/nanobox-io\/nanobox\/models\"\n\t\"github.com\/nanobox-io\/nanobox\/processors\/server\"\n\t\"github.com\/nanobox-io\/nanobox\/util\"\n\t\"github.com\/nanobox-io\/nanobox\/util\/display\"\n\t\"github.com\/nanobox-io\/nanobox\/util\/dns\"\n)\n\nvar AppSetup func(envModel *models.Env, appModel *models.App, name string) error\n\n\/\/ Add adds a dns entry to the local hosts file\nfunc Add(envModel *models.Env, appModel *models.App, name string) error {\n\n\tif err := AppSetup(envModel, appModel, appModel.Name); err != nil {\n\t\treturn util.ErrorAppend(err, \"failed to setup app\")\n\t}\n\n\t\/\/ fetch the IP\n\t\/\/ env in dev is used in the dev container\n\t\/\/ env in sim is used for portal\n\tenvIP := appModel.LocalIPs[\"env\"]\n\n\t\/\/ generate the dns entry\n\tentry := dns.Entry(envIP, name, appModel.ID)\n\n\t\/\/ short-circuit if this entry already exists\n\tif dns.Exists(entry) {\n\t\treturn nil\n\t}\n\n\t\/\/ make sure the server is running since it will do the dns addition\n\tif err := server.Setup(); err != nil {\n\t\treturn util.ErrorAppend(err, \"failed to setup server\")\n\t}\n\n\t\/\/ add the entry\n\tif err := dns.Add(entry); err != nil {\n\t\tlumber.Error(\"dns:Add:dns.Add(%s): %s\", entry, err.Error())\n\t\treturn util.ErrorAppend(err, \"unable to add dns entry\")\n\t}\n\n\tdisplay.Info(\"\\n%s %s added\\n\", display.TaskComplete, name)\n\n\treturn nil\n}\n<commit_msg>Issue a warning about .dev TLDs<commit_after>package dns\n\nimport (\n\t\/\/ \"fmt\"\n\n\t\"github.com\/jcelliott\/lumber\"\n\n\t\"github.com\/nanobox-io\/nanobox\/models\"\n\t\"github.com\/nanobox-io\/nanobox\/processors\/server\"\n\t\"github.com\/nanobox-io\/nanobox\/util\"\n\t\"github.com\/nanobox-io\/nanobox\/util\/display\"\n\t\"github.com\/nanobox-io\/nanobox\/util\/dns\"\n)\n\nvar AppSetup func(envModel *models.Env, appModel *models.App, name string) error\n\n\/\/ Add adds a dns entry to the local hosts file\nfunc Add(envModel *models.Env, appModel *models.App, name string) error {\n\n\tif err := AppSetup(envModel, appModel, appModel.Name); err != nil {\n\t\treturn util.ErrorAppend(err, \"failed to setup app\")\n\t}\n\n\t\/\/ fetch the IP\n\t\/\/ env in dev is used in the dev container\n\t\/\/ env in sim is used for portal\n\tenvIP := appModel.LocalIPs[\"env\"]\n\n\t\/\/ generate the dns entry\n\tentry := dns.Entry(envIP, name, appModel.ID)\n\n\t\/\/ short-circuit if this entry already exists\n\tif dns.Exists(entry) {\n\t\treturn nil\n\t}\n\n\t\/\/ make sure the server is running since it will do the dns addition\n\tif err := server.Setup(); err != nil {\n\t\treturn util.ErrorAppend(err, \"failed to setup server\")\n\t}\n\n\t\/\/ issue a warning about `.dev` being unusable with Chrome\n\tif name[len(name)-4:] == \".dev\" {\n\t\ttld := appModel.DisplayName()\n\t\tif tld == \"dry-run\" {\n\t\t\ttld = \"test\"\n\t\t}\n\n\t\tdisplay.Warn(\"\\nGoogle has been locking down use of the .dev TLD, and your app may not be accessible with this domain.\\nTry using %s.%s instead\\n\", name[0:len(name)-4], tld)\n\t}\n\n\t\/\/ add the entry\n\tif err := dns.Add(entry); err != nil {\n\t\tlumber.Error(\"dns:Add:dns.Add(%s): %s\", entry, err.Error())\n\t\treturn util.ErrorAppend(err, \"unable to add dns entry\")\n\t}\n\n\tdisplay.Info(\"\\n%s %s added\\n\", display.TaskComplete, name)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"sync\"\n\t\"syscall\"\n)\n\nimport \"git.torproject.org\/pluggable-transports\/goptlib.git\"\n\nconst ptMethodName = \"meek\"\n\nvar ptInfo pt.ClientInfo\n\n\/\/ When a connection handler starts, +1 is written to this channel; when it\n\/\/ ends, -1 is written.\nvar handlerChan = make(chan int)\n\nfunc copyLoop(a, b net.Conn) {\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\n\tgo func() {\n\t\tio.Copy(b, a)\n\t\twg.Done()\n\t}()\n\tgo func() {\n\t\tio.Copy(a, b)\n\t\twg.Done()\n\t}()\n\n\twg.Wait()\n}\n\nfunc handler(conn *pt.SocksConn) error {\n\thandlerChan <- 1\n\tdefer func() {\n\t\thandlerChan <- -1\n\t}()\n\n\tdefer conn.Close()\n\tremote, err := net.Dial(\"tcp\", conn.Req.Target)\n\tif err != nil {\n\t\tconn.Reject()\n\t\treturn err\n\t}\n\tdefer remote.Close()\n\terr = conn.Grant(remote.RemoteAddr().(*net.TCPAddr))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcopyLoop(conn, remote)\n\n\treturn nil\n}\n\nfunc acceptLoop(ln *pt.SocksListener) error {\n\tdefer ln.Close()\n\tfor {\n\t\tconn, err := ln.AcceptSocks()\n\t\tif err != nil {\n\t\t\tif e, ok := err.(net.Error); ok && !e.Temporary() {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tgo handler(conn)\n\t}\n}\n\nfunc main() {\n\tvar err error\n\n\tptInfo, err = pt.ClientSetup([]string{ptMethodName})\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tlisteners := make([]net.Listener, 0)\n\tfor _, methodName := range ptInfo.MethodNames {\n\t\tswitch methodName {\n\t\tcase ptMethodName:\n\t\t\tln, err := pt.ListenSocks(\"tcp\", \"127.0.0.1:0\")\n\t\t\tif err != nil {\n\t\t\t\tpt.CmethodError(methodName, err.Error())\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tgo acceptLoop(ln)\n\t\t\tpt.Cmethod(methodName, ln.Version(), ln.Addr())\n\t\t\tlisteners = append(listeners, ln)\n\t\tdefault:\n\t\t\tpt.CmethodError(methodName, \"no such method\")\n\t\t}\n\t}\n\tpt.CmethodsDone()\n\n\tvar numHandlers int = 0\n\tvar sig os.Signal\n\tsigChan := make(chan os.Signal, 1)\n\tsignal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)\n\n\t\/\/ wait for first signal\n\tsig = nil\n\tfor sig == nil {\n\t\tselect {\n\t\tcase n := <-handlerChan:\n\t\t\tnumHandlers += n\n\t\tcase sig = <-sigChan:\n\t\t}\n\t}\n\tfor _, ln := range listeners {\n\t\tln.Close()\n\t}\n\n\tif sig == syscall.SIGTERM {\n\t\treturn\n\t}\n\n\t\/\/ wait for second signal or no more handlers\n\tsig = nil\n\tfor sig == nil && numHandlers != 0 {\n\t\tselect {\n\t\tcase n := <-handlerChan:\n\t\t\tnumHandlers += n\n\t\tcase sig = <-sigChan:\n\t\t}\n\t}\n}\n<commit_msg>Add --log option.<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"sync\"\n\t\"syscall\"\n)\n\nimport \"git.torproject.org\/pluggable-transports\/goptlib.git\"\n\nconst ptMethodName = \"meek\"\n\nvar ptInfo pt.ClientInfo\n\n\/\/ When a connection handler starts, +1 is written to this channel; when it\n\/\/ ends, -1 is written.\nvar handlerChan = make(chan int)\n\nfunc copyLoop(a, b net.Conn) {\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\n\tgo func() {\n\t\tio.Copy(b, a)\n\t\twg.Done()\n\t}()\n\tgo func() {\n\t\tio.Copy(a, b)\n\t\twg.Done()\n\t}()\n\n\twg.Wait()\n}\n\nfunc handler(conn *pt.SocksConn) error {\n\thandlerChan <- 1\n\tdefer func() {\n\t\thandlerChan <- -1\n\t}()\n\n\tdefer conn.Close()\n\tremote, err := net.Dial(\"tcp\", conn.Req.Target)\n\tif err != nil {\n\t\tconn.Reject()\n\t\treturn err\n\t}\n\tdefer remote.Close()\n\terr = conn.Grant(remote.RemoteAddr().(*net.TCPAddr))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcopyLoop(conn, remote)\n\n\treturn nil\n}\n\nfunc acceptLoop(ln *pt.SocksListener) error {\n\tdefer ln.Close()\n\tfor {\n\t\tconn, err := ln.AcceptSocks()\n\t\tif err != nil {\n\t\t\tif e, ok := err.(net.Error); ok && !e.Temporary() {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tgo handler(conn)\n\t}\n}\n\nfunc main() {\n\tvar logFilename string\n\n\tflag.StringVar(&logFilename, \"log\", \"\", \"name of log file\")\n\tflag.Parse()\n\n\tif logFilename != \"\" {\n\t\tf, err := os.OpenFile(logFilename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"error opening log file: %s\", err)\n\t\t}\n\t\tdefer f.Close()\n\t\tlog.SetOutput(f)\n\t}\n\n\tvar err error\n\tptInfo, err = pt.ClientSetup([]string{ptMethodName})\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tlisteners := make([]net.Listener, 0)\n\tfor _, methodName := range ptInfo.MethodNames {\n\t\tswitch methodName {\n\t\tcase ptMethodName:\n\t\t\tln, err := pt.ListenSocks(\"tcp\", \"127.0.0.1:0\")\n\t\t\tif err != nil {\n\t\t\t\tpt.CmethodError(methodName, err.Error())\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tgo acceptLoop(ln)\n\t\t\tpt.Cmethod(methodName, ln.Version(), ln.Addr())\n\t\t\tlisteners = append(listeners, ln)\n\t\tdefault:\n\t\t\tpt.CmethodError(methodName, \"no such method\")\n\t\t}\n\t}\n\tpt.CmethodsDone()\n\n\tvar numHandlers int = 0\n\tvar sig os.Signal\n\tsigChan := make(chan os.Signal, 1)\n\tsignal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)\n\n\t\/\/ wait for first signal\n\tsig = nil\n\tfor sig == nil {\n\t\tselect {\n\t\tcase n := <-handlerChan:\n\t\t\tnumHandlers += n\n\t\tcase sig = <-sigChan:\n\t\t}\n\t}\n\tfor _, ln := range listeners {\n\t\tln.Close()\n\t}\n\n\tif sig == syscall.SIGTERM {\n\t\treturn\n\t}\n\n\t\/\/ wait for second signal or no more handlers\n\tsig = nil\n\tfor sig == nil && numHandlers != 0 {\n\t\tselect {\n\t\tcase n := <-handlerChan:\n\t\t\tnumHandlers += n\n\t\tcase sig = <-sigChan:\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Andreas Koch. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage filesystem\n\nimport (\n\t\"fmt\"\n\t\"github.com\/andreaskoch\/allmark2\/common\/logger\"\n\t\"github.com\/andreaskoch\/allmark2\/common\/route\"\n\t\"github.com\/andreaskoch\/go-fswatch\"\n)\n\ntype updateHubCallbacks map[string]func() fswatch.Watcher\ntype updateHubWatchers map[string]fswatch.Watcher\n\ntype watcherRegistry map[string]updateHubWatchers\ntype callbackRegistry map[string]updateHubCallbacks\n\nfunc newUpdateHub(logger logger.Logger) *UpdateHub {\n\treturn &UpdateHub{\n\t\tlogger: logger,\n\n\t\tcallbacks: make(callbackRegistry),\n\t\twatchers:  make(watcherRegistry),\n\t}\n}\n\ntype UpdateHub struct {\n\tlogger logger.Logger\n\n\tcallbacks callbackRegistry\n\twatchers  watcherRegistry\n}\n\nfunc (hub *UpdateHub) StartWatching(route route.Route) {\n\n\thub.logger.Debug(\"# folder watchers: %v\", fswatch.NumberOfFolderWatchers())\n\n\thub.logger.Debug(fmt.Sprintf(\"Starting callbacks for route %q\", route.String()))\n\n\tfor callbackType, callback := range hub.callbacks[routeToKey(route)] {\n\t\thub.logger.Debug(fmt.Sprintf(\"Starting callback %q for route %q\", callbackType, route.String()))\n\n\t\t\/\/ execute the callback\n\t\twatcher := callback()\n\n\t\tif watchers, exists := hub.watchers[routeToKey(route)]; !exists {\n\t\t\twatchers := make(updateHubWatchers)\n\t\t\twatchers[callbackType] = watcher\n\t\t\thub.watchers[routeToKey(route)] = watchers\n\t\t} else {\n\t\t\twatchers[callbackType] = watcher\n\t\t\thub.watchers[routeToKey(route)] = watchers\n\t\t}\n\t}\n}\n\nfunc (hub *UpdateHub) StopWatching(route route.Route) {\n\n\thub.logger.Debug(fmt.Sprintf(\"Stopping callbacks for route %q\", route.String()))\n\n\twatchers, exists := hub.watchers[routeToKey(route)]\n\tif !exists {\n\t\thub.logger.Debug(\"There is no running watcher for route %q\", route.String())\n\t\treturn\n\t}\n\n\tfor callbackType, watcher := range watchers {\n\t\thub.logger.Debug(\"Stopping watcher %q for route %q\", callbackType, route.String())\n\t\tif watcher != nil {\n\t\t\twatcher.Stop()\n\t\t}\n\t}\n\n}\n\nfunc (hub *UpdateHub) Detach(route route.Route) {\n\thub.logger.Debug(\"Detaching callbacks %q for route %q\", route.String())\n\thub.StopWatching(route)\n\tdelete(hub.watchers, route.Value())\n}\n\nfunc (hub *UpdateHub) Attach(route route.Route, callbackType string, callback func() fswatch.Watcher) {\n\thub.logger.Debug(\"Attaching callback %q for route %q\", callbackType, route.String())\n\n\tif callbacks, exists := hub.callbacks[routeToKey(route)]; !exists {\n\n\t\t\/\/ create a new callback map\n\t\tcallbacks := make(updateHubCallbacks)\n\n\t\t\/\/ attach the callback\n\t\tcallbacks[callbackType] = callback\n\n\t\thub.callbacks[routeToKey(route)] = callbacks\n\t} else {\n\n\t\t\/\/ attach the callback\n\t\tcallbacks[callbackType] = callback\n\n\t}\n}\n\nfunc routeToKey(route route.Route) string {\n\treturn route.Value()\n}\n<commit_msg>Still not working<commit_after>\/\/ Copyright 2013 Andreas Koch. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage filesystem\n\nimport (\n\t\"fmt\"\n\t\"github.com\/andreaskoch\/allmark2\/common\/logger\"\n\t\"github.com\/andreaskoch\/allmark2\/common\/route\"\n\t\"github.com\/andreaskoch\/go-fswatch\"\n)\n\ntype updateHubCallbacks map[string]func() fswatch.Watcher\ntype updateHubWatchers map[string]fswatch.Watcher\n\ntype watcherRegistry map[string]updateHubWatchers\ntype callbackRegistry map[string]updateHubCallbacks\n\nfunc newUpdateHub(logger logger.Logger) *UpdateHub {\n\treturn &UpdateHub{\n\t\tlogger: logger,\n\n\t\tcallbacks: make(callbackRegistry),\n\t\twatchers:  make(watcherRegistry),\n\t}\n}\n\ntype UpdateHub struct {\n\tlogger logger.Logger\n\n\tcallbacks callbackRegistry\n\twatchers  watcherRegistry\n}\n\nfunc (hub *UpdateHub) StartWatching(route route.Route) {\n\n\thub.logger.Debug(\"# folder watchers: %v\", fswatch.NumberOfFolderWatchers())\n\n\thub.logger.Debug(fmt.Sprintf(\"Starting callbacks for route %q\", route.String()))\n\n\tfor callbackType, callback := range hub.callbacks[routeToKey(route)] {\n\n\t\tif hub.watcherExists(route, callbackType) {\n\t\t\thub.logger.Debug(fmt.Sprintf(\"Callback %q for route %q is already running\", callbackType, route.String()))\n\t\t\tcontinue\n\t\t}\n\n\t\thub.logger.Debug(fmt.Sprintf(\"Starting callback %q for route %q\", callbackType, route.String()))\n\n\t\t\/\/ execute the callback\n\t\twatcher := callback()\n\n\t\tif watchers, exists := hub.watchers[routeToKey(route)]; !exists {\n\t\t\twatchers := make(updateHubWatchers)\n\t\t\twatchers[callbackType] = watcher\n\t\t\thub.watchers[routeToKey(route)] = watchers\n\t\t} else {\n\t\t\twatchers[callbackType] = watcher\n\t\t\thub.watchers[routeToKey(route)] = watchers\n\t\t}\n\t}\n}\n\nfunc (hub *UpdateHub) StopWatching(route route.Route) {\n\n\thub.logger.Debug(fmt.Sprintf(\"Stopping callbacks for route %q\", route.String()))\n\n\twatchers, exists := hub.watchers[routeToKey(route)]\n\tif !exists {\n\t\thub.logger.Debug(\"There is no running watcher for route %q\", route.String())\n\t\treturn\n\t}\n\n\tfor callbackType, _ := range watchers {\n\t\thub.stopWatcher(route, callbackType)\n\t}\n\n}\n\nfunc (hub *UpdateHub) Detach(route route.Route) {\n\thub.logger.Debug(\"Detaching callbacks %q for route %q\", route.String())\n\thub.StopWatching(route)\n\tdelete(hub.watchers, route.Value())\n}\n\nfunc (hub *UpdateHub) Attach(route route.Route, callbackType string, callback func() fswatch.Watcher) {\n\thub.logger.Debug(\"Attaching callback %q for route %q\", callbackType, route.String())\n\n\tif callbacks, exists := hub.callbacks[routeToKey(route)]; !exists {\n\n\t\t\/\/ create a new callback map\n\t\tcallbacks := make(updateHubCallbacks)\n\n\t\t\/\/ attach the callback\n\t\tcallbacks[callbackType] = callback\n\n\t\thub.callbacks[routeToKey(route)] = callbacks\n\t} else {\n\n\t\t\/\/ stop any existing callbacks\n\t\thub.stopWatcher(route, callbackType)\n\n\t\t\/\/ attach the callback\n\t\tcallbacks[callbackType] = callback\n\n\t}\n}\n\nfunc (hub *UpdateHub) watcherExists(route route.Route, callbackType string) bool {\n\twatchers, exists := hub.watchers[routeToKey(route)]\n\tif !exists {\n\t\treturn false\n\t}\n\n\t_, watcherExists := watchers[callbackType]\n\treturn watcherExists\n}\n\nfunc (hub *UpdateHub) stopWatcher(route route.Route, callbackType string) {\n\n\thub.logger.Debug(fmt.Sprintf(\"Stopping callbacks for route %q\", route.String()))\n\n\twatchers, exists := hub.watchers[routeToKey(route)]\n\tif !exists {\n\t\thub.logger.Debug(\"There is no running watcher for route %q\", route.String())\n\t\treturn\n\t}\n\n\tif watcher, exists := watchers[callbackType]; exists {\n\t\thub.logger.Debug(\"Stopping watcher %q for route %q\", callbackType, route.String())\n\t\twatcher.Stop()\n\t}\n\n}\n\nfunc routeToKey(route route.Route) string {\n\treturn route.Value()\n}\n<|endoftext|>"}
{"text":"<commit_before>package tuikit\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"time\"\n\n\ttermbox \"github.com\/nsf\/termbox-go\"\n\t\"github.com\/nsf\/tulib\"\n\tlog \"github.com\/sgeb\/go-sglog\"\n)\n\ntype Painter interface {\n\tPaintTo(buffer *tulib.Buffer, rect tulib.Rect) error\n\tSetPaintSubscriber(cb func())\n}\n\ntype Responder interface {\n\t\/\/ HandleEvent should set Event.Handled to true if it was\n\t\/\/ handled so that the main loop knows to ignores it\n\tHandleEvent(*Event)\n\tSetCursorPainter(cb func(Point))\n}\n\ntype Event struct {\n\t*termbox.Event\n\tHandled bool\n}\n\nvar (\n\trootPainter    Painter\n\trootBuffer     tulib.Buffer\n\tfirstResponder Responder\n\n\t\/\/ Event polling channel\n\tEvents chan Event = make(chan Event, 20)\n\n\t\/\/ Controls event polling\n\tinternalEvents chan termbox.Event = make(chan termbox.Event, 20)\n\tstopPolling    chan struct{}      = make(chan struct{}, 1)\n\n\t\/\/ Lock on screen drawing\n\tmutex sync.Mutex\n\n\tfpsCounter    *FpsCounter\n\tlastPaintTime time.Time\n\tframesSkipped uint64\n)\n\nfunc Init() error {\n\terr := termbox.Init()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not init terminal: %v\", err)\n\t}\n\n\terr = clearWithDefaultColors()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not clear terminal: %v\", err)\n\t}\n\ttermbox.SetInputMode(termbox.InputAlt)\n\thideCursor()\n\n\tinternalEventProxying()\n\tStartEventPolling()\n\n\tfpsCounter = NewFpsCounter(time.Second)\n\tgo func() {\n\t\tfor fps := range fpsCounter.Fps {\n\t\t\tlog.Debug.Printf(\"FPS: %v (%v frames skipped)\", fps, framesSkipped)\n\t\t\tframesSkipped = 0\n\t\t}\n\t}()\n\n\treturn nil\n}\n\nfunc internalEventProxying() {\n\tgo func() {\n\t\tfor {\n\t\t\ttbEvent := <-internalEvents\n\t\t\tev := Event{Event: &tbEvent, Handled: false}\n\n\t\t\tswitch {\n\t\t\tcase ev.Type == termbox.EventResize:\n\t\t\t\tlog.Debug.Println(\"Received Resize event, clearing screen \" +\n\t\t\t\t\t\"and setting new size\")\n\t\t\t\tclearWithDefaultColors()\n\t\t\t\tpaintForced()\n\t\t\t\tev.Handled = true\n\t\t\tcase ev.Type == termbox.EventKey && firstResponder != nil:\n\t\t\t\tfirstResponder.HandleEvent(&ev)\n\t\t\t}\n\n\t\t\tEvents <- ev\n\t\t}\n\t}()\n}\n\nfunc StartEventPolling() {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-stopPolling:\n\t\t\t\treturn\n\t\t\tcase internalEvents <- termbox.PollEvent():\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc StopEventPolling() {\n\tstopPolling <- struct{}{}\n}\n\nfunc SetPainter(p Painter) {\n\trootPainter = p\n}\n\nfunc SetFirstResponder(eh Responder) {\n\tif firstResponder != nil {\n\t\tfirstResponder.SetCursorPainter(nil)\n\t}\n\tif eh != nil {\n\t\teh.SetCursorPainter(func(pos Point) { setCursor(pos) })\n\t}\n\tfirstResponder = eh\n}\n\nfunc Paint() error {\n\tif time.Now().Sub(lastPaintTime) < time.Second\/10 {\n\t\tframesSkipped++\n\t\treturn fmt.Errorf(\"Above 10 FPS, skipping frame\")\n\t}\n\n\treturn paintForced()\n}\n\nfunc paintForced() error {\n\terr := rootPainter.PaintTo(&rootBuffer, rootBuffer.Rect)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif firstResponder == nil {\n\t\thideCursor()\n\t}\n\n\terr = flush()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfpsCounter.Ticks <- struct{}{}\n\tlastPaintTime = time.Now()\n\n\treturn nil\n}\n\nfunc Sync() error {\n\tmutex.Lock()\n\terr := termbox.Sync()\n\tmutex.Unlock()\n\treturn err\n}\n\nfunc clearRect(buffer *tulib.Buffer, rect tulib.Rect) {\n\tbuffer.Fill(rect, termbox.Cell{Ch: ' '})\n}\n\nfunc clearWithDefaultColors() error {\n\treturn clear(termbox.ColorDefault, termbox.ColorDefault)\n}\n\nfunc clear(fg, bg termbox.Attribute) error {\n\tmutex.Lock()\n\terr := termbox.Clear(fg, bg)\n\tmutex.Unlock()\n\tupdateRootBuffer()\n\treturn err\n}\n\nfunc updateRootBuffer() {\n\tmutex.Lock()\n\trootBuffer = tulib.TermboxBuffer()\n\tmutex.Unlock()\n}\n\nfunc hideCursor() {\n\t\/\/ Probably a bug: Cursor must be set to valid position before hiding\n\tsetCursor(PointZero)\n\ttermbox.HideCursor()\n}\n\nfunc setCursor(p Point) {\n\ttermbox.SetCursor(p.X, p.Y)\n}\n\nfunc flush() error {\n\tmutex.Lock()\n\terr := termbox.Flush()\n\tmutex.Unlock()\n\tupdateRootBuffer()\n\treturn err\n}\n\nfunc Close() {\n\tmutex.Lock()\n\ttermbox.Close()\n\tmutex.Unlock()\n}\n<commit_msg>Optimizations based on profiling<commit_after>package tuikit\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"time\"\n\n\ttermbox \"github.com\/nsf\/termbox-go\"\n\t\"github.com\/nsf\/tulib\"\n\tlog \"github.com\/sgeb\/go-sglog\"\n)\n\ntype Painter interface {\n\tPaintTo(buffer *tulib.Buffer, rect tulib.Rect) error\n\tSetPaintSubscriber(cb func())\n}\n\ntype Responder interface {\n\t\/\/ HandleEvent should set Event.Handled to true if it was\n\t\/\/ handled so that the main loop knows to ignores it\n\tHandleEvent(*Event)\n\tSetCursorPainter(cb func(Point))\n}\n\ntype Event struct {\n\t*termbox.Event\n\tHandled bool\n}\n\nconst (\n\tMaxFps = 10\n)\n\nvar (\n\trootPainter    Painter\n\trootBuffer     tulib.Buffer\n\tfirstResponder Responder\n\n\t\/\/ Event polling channel\n\tEvents chan Event = make(chan Event, 20)\n\n\t\/\/ Controls event polling\n\tinternalEvents chan termbox.Event = make(chan termbox.Event, 20)\n\tstopPolling    chan struct{}      = make(chan struct{}, 1)\n\n\t\/\/ Lock on screen drawing\n\tmutex sync.Mutex\n\n\tfpsCounter    *FpsCounter\n\tpaintTimeT0   time.Time\n\tpaintTimeT1   time.Time\n\tframesSkipped uint64\n\terrFrameSkip  = fmt.Errorf(\"Above %v FPS, skipping frame\", MaxFps)\n)\n\nfunc Init() error {\n\terr := termbox.Init()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not init terminal: %v\", err)\n\t}\n\n\terr = clearWithDefaultColors()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not clear terminal: %v\", err)\n\t}\n\ttermbox.SetInputMode(termbox.InputAlt)\n\thideCursor()\n\n\tinternalEventProxying()\n\tStartEventPolling()\n\n\tfpsCounter = NewFpsCounter(time.Second)\n\tgo func() {\n\t\tfor fps := range fpsCounter.Fps {\n\t\t\tlog.Debug.Printf(\"FPS: %v (%v frames skipped)\", fps, framesSkipped)\n\t\t\tframesSkipped = 0\n\t\t}\n\t}()\n\n\treturn nil\n}\n\nfunc internalEventProxying() {\n\tgo func() {\n\t\tfor {\n\t\t\ttbEvent := <-internalEvents\n\t\t\tev := Event{Event: &tbEvent, Handled: false}\n\n\t\t\tswitch {\n\t\t\tcase ev.Type == termbox.EventResize:\n\t\t\t\tlog.Debug.Println(\"Received Resize event, clearing screen \" +\n\t\t\t\t\t\"and setting new size\")\n\t\t\t\tclearWithDefaultColors()\n\t\t\t\tpaintForced()\n\t\t\t\tev.Handled = true\n\t\t\tcase ev.Type == termbox.EventKey && firstResponder != nil:\n\t\t\t\tfirstResponder.HandleEvent(&ev)\n\t\t\t}\n\n\t\t\tEvents <- ev\n\t\t}\n\t}()\n}\n\nfunc StartEventPolling() {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-stopPolling:\n\t\t\t\treturn\n\t\t\tcase internalEvents <- termbox.PollEvent():\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc StopEventPolling() {\n\tstopPolling <- struct{}{}\n}\n\nfunc SetPainter(p Painter) {\n\trootPainter = p\n}\n\nfunc SetFirstResponder(eh Responder) {\n\tif firstResponder != nil {\n\t\tfirstResponder.SetCursorPainter(nil)\n\t}\n\tif eh != nil {\n\t\teh.SetCursorPainter(func(pos Point) { setCursor(pos) })\n\t}\n\tfirstResponder = eh\n}\n\nfunc Paint() error {\n\tpaintTimeT1 = time.Now()\n\tif paintTimeT1.Sub(paintTimeT0) < time.Second\/MaxFps {\n\t\tframesSkipped++\n\t\treturn errFrameSkip\n\t}\n\n\treturn paintForced()\n}\n\nfunc paintForced() error {\n\terr := rootPainter.PaintTo(&rootBuffer, rootBuffer.Rect)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif firstResponder == nil {\n\t\thideCursor()\n\t}\n\n\terr = flush()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfpsCounter.Ticks <- struct{}{}\n\tpaintTimeT0 = paintTimeT1\n\n\treturn nil\n}\n\nfunc Sync() error {\n\tmutex.Lock()\n\terr := termbox.Sync()\n\tmutex.Unlock()\n\treturn err\n}\n\nfunc clearRect(buffer *tulib.Buffer, rect tulib.Rect) {\n\tbuffer.Fill(rect, termbox.Cell{Ch: ' '})\n}\n\nfunc clearWithDefaultColors() error {\n\treturn clear(termbox.ColorDefault, termbox.ColorDefault)\n}\n\nfunc clear(fg, bg termbox.Attribute) error {\n\tmutex.Lock()\n\terr := termbox.Clear(fg, bg)\n\tmutex.Unlock()\n\tupdateRootBuffer()\n\treturn err\n}\n\nfunc updateRootBuffer() {\n\tmutex.Lock()\n\trootBuffer = tulib.TermboxBuffer()\n\tmutex.Unlock()\n}\n\nfunc hideCursor() {\n\t\/\/ Probably a bug: Cursor must be set to valid position before hiding\n\tsetCursor(PointZero)\n\ttermbox.HideCursor()\n}\n\nfunc setCursor(p Point) {\n\ttermbox.SetCursor(p.X, p.Y)\n}\n\nfunc flush() error {\n\tmutex.Lock()\n\terr := termbox.Flush()\n\tmutex.Unlock()\n\tupdateRootBuffer()\n\treturn err\n}\n\nfunc Close() {\n\tmutex.Lock()\n\ttermbox.Close()\n\tmutex.Unlock()\n}\n<|endoftext|>"}
{"text":"<commit_before>package parse\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"path\"\n\t\"reflect\"\n)\n\ntype updateTypeT int\n\nconst (\n\topSet updateTypeT = iota\n\topIncr\n\topDelete\n\topAdd\n\topAddUnique\n\topRemove\n\topAddRelation\n\topRemoveRelation\n)\n\nfunc (u updateTypeT) String() string {\n\tswitch u {\n\tcase opSet:\n\t\treturn \"Set\"\n\tcase opIncr:\n\t\treturn \"Increment\"\n\tcase opDelete:\n\t\treturn \"Delete\"\n\tcase opAdd:\n\t\treturn \"Add\"\n\tcase opAddUnique:\n\t\treturn \"AddUnique\"\n\tcase opRemove:\n\t\treturn \"Remove\"\n\tcase opAddRelation:\n\t\treturn \"AddRelation\"\n\tcase opRemoveRelation:\n\t\treturn \"RemoveRelation\"\n\t}\n\n\treturn \"Unknown\"\n}\n\nfunc (u updateTypeT) argKey() string {\n\tswitch u {\n\tcase opIncr:\n\t\treturn \"amount\"\n\tcase opAdd, opAddUnique, opRemove, opAddRelation, opRemoveRelation:\n\t\treturn \"objects\"\n\t}\n\n\treturn \"unknown\"\n}\n\ntype updateOpT struct {\n\tUpdateType updateTypeT\n\tValue      interface{}\n}\n\nfunc (u updateOpT) MarshalJSON() ([]byte, error) {\n\tswitch u.UpdateType {\n\tcase opSet:\n\t\treturn json.Marshal(u.Value)\n\tcase opDelete:\n\t\treturn json.Marshal(map[string]interface{}{\n\t\t\t\"__op\": u.UpdateType.String(),\n\t\t})\n\tdefault:\n\t\treturn json.Marshal(map[string]interface{}{\n\t\t\t\"__op\":                u.UpdateType.String(),\n\t\t\tu.UpdateType.argKey(): u.Value,\n\t\t})\n\t}\n}\n\ntype Update interface {\n\n\t\/\/Set the field specified by f to the value of v\n\tSet(f string, v interface{}) Update\n\n\t\/\/ Increment the field specified by f by the amount specified by v.\n\t\/\/ v should be a numeric type\n\tIncrement(f string, v interface{}) Update\n\n\t\/\/ Delete the field specified by f from the instance being updated\n\tDelete(f string) Update\n\n\t\/\/ Append the values provided to the Array field specified by f. This operation\n\t\/\/ is atomic\n\tAdd(f string, vs ...interface{}) Update\n\n\t\/\/ Add any values provided that were not alread present to the Array field\n\t\/\/ specified by f. This operation is atomic\n\tAddUnique(f string, vs ...interface{}) Update\n\n\t\/\/ Remove the provided values from the array field specified by f\n\tRemove(f string, vs ...interface{}) Update\n\n\t\/\/ Update the ACL on the given object\n\tSetACL(a ACL) Update\n\n\t\/\/ Use the Master Key for this update request\n\tUseMasterKey() Update\n\n\t\/\/ Execute this update. This method also updates the proper fields\n\t\/\/ on the provided value with their repective new values\n\tExecute() error\n\n\trequestT\n}\n\ntype updateT struct {\n\tinst               interface{}\n\tvalues             map[string]updateOpT\n\tshouldUseMasterKey bool\n\tcurrentSession     *sessionT\n}\n\n\/\/ Create a new update request for the Parse object represented by v.\n\/\/\n\/\/ Note: v should be a pointer to a struct whose name represents a Parse class,\n\/\/ or that implements the ClassName method\nfunc NewUpdate(v interface{}) (Update, error) {\n\trv := reflect.ValueOf(v)\n\tif rv.Kind() != reflect.Ptr || rv.IsNil() {\n\t\treturn nil, errors.New(\"v must be a non-nil pointer\")\n\t}\n\n\treturn &updateT{\n\t\tinst:   v,\n\t\tvalues: map[string]updateOpT{},\n\t}, nil\n}\n\nfunc (u *updateT) Set(f string, v interface{}) Update {\n\tu.values[f] = updateOpT{UpdateType: opSet, Value: encodeForRequest(v)}\n\treturn u\n}\n\nfunc (u *updateT) Increment(f string, v interface{}) Update {\n\tu.values[f] = updateOpT{UpdateType: opIncr, Value: v}\n\treturn u\n}\n\nfunc (u *updateT) Delete(f string) Update {\n\tu.values[f] = updateOpT{UpdateType: opDelete}\n\treturn u\n}\n\nfunc (u *updateT) Add(f string, vs ...interface{}) Update {\n\tu.values[f] = updateOpT{UpdateType: opAdd, Value: vs}\n\treturn u\n}\n\nfunc (u *updateT) AddUnique(f string, vs ...interface{}) Update {\n\tu.values[f] = updateOpT{UpdateType: opAddUnique, Value: vs}\n\treturn u\n}\n\nfunc (u *updateT) Remove(f string, vs ...interface{}) Update {\n\tu.values[f] = updateOpT{UpdateType: opRemove, Value: vs}\n\treturn u\n}\n\nfunc (u *updateT) SetACL(a ACL) Update {\n\tu.values[\"ACL\"] = updateOpT{UpdateType: opSet, Value: a}\n\treturn u\n}\n\nfunc (u *updateT) Execute() (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = r.(error)\n\t\t}\n\t}()\n\n\trv := reflect.ValueOf(u.inst)\n\trvi := reflect.Indirect(rv)\n\tfieldMap := getFieldNameMap(rv)\n\n\tfor k, v := range u.values {\n\t\tvar fname string\n\t\tif fn, ok := fieldMap[k]; ok {\n\t\t\tfname = fn\n\t\t} else {\n\t\t\tfname = k\n\t\t}\n\n\t\tfname = firstToUpper(fname)\n\n\t\tdv := reflect.ValueOf(v.Value)\n\t\tdvi := reflect.Indirect(dv)\n\n\t\tif fv := rvi.FieldByName(fname); fv.IsValid() {\n\t\t\tfvi := reflect.Indirect(fv)\n\n\t\t\tswitch v.UpdateType {\n\t\t\tcase opSet:\n\t\t\t\tvar tmp reflect.Value\n\t\t\t\tif fv.Kind() == reflect.Ptr {\n\t\t\t\t\ttmp = fv\n\t\t\t\t} else {\n\t\t\t\t\ttmp = fv.Addr()\n\t\t\t\t}\n\t\t\t\tif err := populateValue(tmp.Interface(), v.Value); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tcase opIncr:\n\t\t\t\tswitch fvi.Kind() {\n\t\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t\t\tif dvi.Type().ConvertibleTo(fvi.Type()) {\n\t\t\t\t\t\tcurrent := fvi.Int()\n\t\t\t\t\t\tamount := dvi.Convert(fvi.Type()).Int()\n\t\t\t\t\t\tcurrent += amount\n\t\t\t\t\t\tfvi.Set(reflect.ValueOf(current).Convert(fvi.Type()))\n\t\t\t\t\t}\n\t\t\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\t\tif dvi.Type().ConvertibleTo(fvi.Type()) {\n\t\t\t\t\t\tcurrent := fvi.Uint()\n\t\t\t\t\t\tamount := dvi.Convert(fvi.Type()).Uint()\n\t\t\t\t\t\tcurrent += amount\n\t\t\t\t\t\tfvi.Set(reflect.ValueOf(current).Convert(fvi.Type()))\n\t\t\t\t\t}\n\t\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\t\tif dvi.Type().ConvertibleTo(fvi.Type()) {\n\t\t\t\t\t\tcurrent := fvi.Float()\n\t\t\t\t\t\tamount := dvi.Convert(fvi.Type()).Float()\n\t\t\t\t\t\tcurrent += amount\n\t\t\t\t\t\tfvi.Set(reflect.ValueOf(current).Convert(fvi.Type()))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase opDelete:\n\t\t\t\tfv.Set(reflect.Zero(fv.Type()))\n\t\t\t}\n\t\t}\n\t}\n\tif b, err := defaultClient.doRequest(u); err != nil {\n\t\treturn err\n\t} else {\n\t\treturn handleResponse(b, u.inst)\n\t}\n}\n\nfunc (u *updateT) UseMasterKey() Update {\n\tu.shouldUseMasterKey = true\n\treturn u\n}\n\nfunc (u *updateT) method() string {\n\treturn \"PUT\"\n}\n\nfunc (u *updateT) endpoint() (string, error) {\n\t_url := url.URL{}\n\tp := getEndpointBase(u.inst)\n\n\trv := reflect.ValueOf(u.inst)\n\trvi := reflect.Indirect(rv)\n\tif f := rvi.FieldByName(\"Id\"); f.IsValid() {\n\t\tif s, ok := f.Interface().(string); ok {\n\t\t\tp = path.Join(p, s)\n\t\t} else {\n\t\t\treturn \"\", fmt.Errorf(\"Id field should be a string, received type %s\", f.Type())\n\t\t}\n\t} else {\n\t\treturn \"\", fmt.Errorf(\"can not update value - type has no Id field\")\n\t}\n\n\t_url.Scheme = \"https\"\n\t_url.Host = parseHost\n\t_url.Path = p\n\n\treturn _url.String(), nil\n}\n\nfunc (u *updateT) body() (string, error) {\n\tb, err := json.Marshal(u.values)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(b), nil\n}\n\nfunc (u *updateT) useMasterKey() bool {\n\treturn u.shouldUseMasterKey\n}\n\nfunc (u *updateT) session() *sessionT {\n\treturn u.currentSession\n}\n\nfunc (u *updateT) contentType() string {\n\treturn \"application\/json\"\n}\n<commit_msg>support liking facebook account with existing account<commit_after>package parse\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"path\"\n\t\"reflect\"\n)\n\ntype updateTypeT int\n\nconst (\n\topSet updateTypeT = iota\n\topIncr\n\topDelete\n\topAdd\n\topAddUnique\n\topRemove\n\topAddRelation\n\topRemoveRelation\n)\n\nfunc (u updateTypeT) String() string {\n\tswitch u {\n\tcase opSet:\n\t\treturn \"Set\"\n\tcase opIncr:\n\t\treturn \"Increment\"\n\tcase opDelete:\n\t\treturn \"Delete\"\n\tcase opAdd:\n\t\treturn \"Add\"\n\tcase opAddUnique:\n\t\treturn \"AddUnique\"\n\tcase opRemove:\n\t\treturn \"Remove\"\n\tcase opAddRelation:\n\t\treturn \"AddRelation\"\n\tcase opRemoveRelation:\n\t\treturn \"RemoveRelation\"\n\t}\n\n\treturn \"Unknown\"\n}\n\nfunc (u updateTypeT) argKey() string {\n\tswitch u {\n\tcase opIncr:\n\t\treturn \"amount\"\n\tcase opAdd, opAddUnique, opRemove, opAddRelation, opRemoveRelation:\n\t\treturn \"objects\"\n\t}\n\n\treturn \"unknown\"\n}\n\ntype updateOpT struct {\n\tUpdateType updateTypeT\n\tValue      interface{}\n}\n\nfunc (u updateOpT) MarshalJSON() ([]byte, error) {\n\tswitch u.UpdateType {\n\tcase opSet:\n\t\treturn json.Marshal(u.Value)\n\tcase opDelete:\n\t\treturn json.Marshal(map[string]interface{}{\n\t\t\t\"__op\": u.UpdateType.String(),\n\t\t})\n\tdefault:\n\t\treturn json.Marshal(map[string]interface{}{\n\t\t\t\"__op\":                u.UpdateType.String(),\n\t\t\tu.UpdateType.argKey(): u.Value,\n\t\t})\n\t}\n}\n\ntype Update interface {\n\n\t\/\/Set the field specified by f to the value of v\n\tSet(f string, v interface{}) Update\n\n\t\/\/ Increment the field specified by f by the amount specified by v.\n\t\/\/ v should be a numeric type\n\tIncrement(f string, v interface{}) Update\n\n\t\/\/ Delete the field specified by f from the instance being updated\n\tDelete(f string) Update\n\n\t\/\/ Append the values provided to the Array field specified by f. This operation\n\t\/\/ is atomic\n\tAdd(f string, vs ...interface{}) Update\n\n\t\/\/ Add any values provided that were not alread present to the Array field\n\t\/\/ specified by f. This operation is atomic\n\tAddUnique(f string, vs ...interface{}) Update\n\n\t\/\/ Remove the provided values from the array field specified by f\n\tRemove(f string, vs ...interface{}) Update\n\n\t\/\/ Update the ACL on the given object\n\tSetACL(a ACL) Update\n\n\t\/\/ Use the Master Key for this update request\n\tUseMasterKey() Update\n\n\t\/\/ Execute this update. This method also updates the proper fields\n\t\/\/ on the provided value with their repective new values\n\tExecute() error\n\n\trequestT\n}\n\ntype updateT struct {\n\tinst               interface{}\n\tvalues             map[string]updateOpT\n\tshouldUseMasterKey bool\n\tcurrentSession     *sessionT\n}\n\n\/\/ Create a new update request for the Parse object represented by v.\n\/\/\n\/\/ Note: v should be a pointer to a struct whose name represents a Parse class,\n\/\/ or that implements the ClassName method\nfunc NewUpdate(v interface{}) (Update, error) {\n\trv := reflect.ValueOf(v)\n\tif rv.Kind() != reflect.Ptr || rv.IsNil() {\n\t\treturn nil, errors.New(\"v must be a non-nil pointer\")\n\t}\n\n\treturn &updateT{\n\t\tinst:   v,\n\t\tvalues: map[string]updateOpT{},\n\t}, nil\n}\n\nfunc (u *updateT) Set(f string, v interface{}) Update {\n\tu.values[f] = updateOpT{UpdateType: opSet, Value: encodeForRequest(v)}\n\treturn u\n}\n\nfunc (u *updateT) Increment(f string, v interface{}) Update {\n\tu.values[f] = updateOpT{UpdateType: opIncr, Value: v}\n\treturn u\n}\n\nfunc (u *updateT) Delete(f string) Update {\n\tu.values[f] = updateOpT{UpdateType: opDelete}\n\treturn u\n}\n\nfunc (u *updateT) Add(f string, vs ...interface{}) Update {\n\tu.values[f] = updateOpT{UpdateType: opAdd, Value: vs}\n\treturn u\n}\n\nfunc (u *updateT) AddUnique(f string, vs ...interface{}) Update {\n\tu.values[f] = updateOpT{UpdateType: opAddUnique, Value: vs}\n\treturn u\n}\n\nfunc (u *updateT) Remove(f string, vs ...interface{}) Update {\n\tu.values[f] = updateOpT{UpdateType: opRemove, Value: vs}\n\treturn u\n}\n\nfunc (u *updateT) SetACL(a ACL) Update {\n\tu.values[\"ACL\"] = updateOpT{UpdateType: opSet, Value: a}\n\treturn u\n}\n\nfunc (u *updateT) Execute() (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = r.(error)\n\t\t}\n\t}()\n\n\trv := reflect.ValueOf(u.inst)\n\trvi := reflect.Indirect(rv)\n\tfieldMap := getFieldNameMap(rv)\n\n\tfor k, v := range u.values {\n\t\tvar fname string\n\t\tif fn, ok := fieldMap[k]; ok {\n\t\t\tfname = fn\n\t\t} else {\n\t\t\tfname = k\n\t\t}\n\n\t\tfname = firstToUpper(fname)\n\n\t\tdv := reflect.ValueOf(v.Value)\n\t\tdvi := reflect.Indirect(dv)\n\n\t\tif fv := rvi.FieldByName(fname); fv.IsValid() {\n\t\t\tfvi := reflect.Indirect(fv)\n\n\t\t\tswitch v.UpdateType {\n\t\t\tcase opSet:\n\t\t\t\tvar tmp reflect.Value\n\t\t\t\tif fv.Kind() == reflect.Ptr {\n\t\t\t\t\ttmp = fv\n\t\t\t\t} else {\n\t\t\t\t\ttmp = fv.Addr()\n\t\t\t\t}\n\t\t\t\tif err := populateValue(tmp.Interface(), v.Value); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tcase opIncr:\n\t\t\t\tswitch fvi.Kind() {\n\t\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t\t\tif dvi.Type().ConvertibleTo(fvi.Type()) {\n\t\t\t\t\t\tcurrent := fvi.Int()\n\t\t\t\t\t\tamount := dvi.Convert(fvi.Type()).Int()\n\t\t\t\t\t\tcurrent += amount\n\t\t\t\t\t\tfvi.Set(reflect.ValueOf(current).Convert(fvi.Type()))\n\t\t\t\t\t}\n\t\t\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\t\tif dvi.Type().ConvertibleTo(fvi.Type()) {\n\t\t\t\t\t\tcurrent := fvi.Uint()\n\t\t\t\t\t\tamount := dvi.Convert(fvi.Type()).Uint()\n\t\t\t\t\t\tcurrent += amount\n\t\t\t\t\t\tfvi.Set(reflect.ValueOf(current).Convert(fvi.Type()))\n\t\t\t\t\t}\n\t\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\t\tif dvi.Type().ConvertibleTo(fvi.Type()) {\n\t\t\t\t\t\tcurrent := fvi.Float()\n\t\t\t\t\t\tamount := dvi.Convert(fvi.Type()).Float()\n\t\t\t\t\t\tcurrent += amount\n\t\t\t\t\t\tfvi.Set(reflect.ValueOf(current).Convert(fvi.Type()))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase opDelete:\n\t\t\t\tfv.Set(reflect.Zero(fv.Type()))\n\t\t\t}\n\t\t}\n\t}\n\tif b, err := defaultClient.doRequest(u); err != nil {\n\t\treturn err\n\t} else {\n\t\treturn handleResponse(b, u.inst)\n\t}\n}\n\nfunc (u *updateT) UseMasterKey() Update {\n\tu.shouldUseMasterKey = true\n\treturn u\n}\n\nfunc (u *updateT) method() string {\n\treturn \"PUT\"\n}\n\nfunc (u *updateT) endpoint() (string, error) {\n\t_url := url.URL{}\n\tp := getEndpointBase(u.inst)\n\n\trv := reflect.ValueOf(u.inst)\n\trvi := reflect.Indirect(rv)\n\tif f := rvi.FieldByName(\"Id\"); f.IsValid() {\n\t\tif s, ok := f.Interface().(string); ok {\n\t\t\tp = path.Join(p, s)\n\t\t} else {\n\t\t\treturn \"\", fmt.Errorf(\"Id field should be a string, received type %s\", f.Type())\n\t\t}\n\t} else {\n\t\treturn \"\", fmt.Errorf(\"can not update value - type has no Id field\")\n\t}\n\n\t_url.Scheme = \"https\"\n\t_url.Host = parseHost\n\t_url.Path = p\n\n\treturn _url.String(), nil\n}\n\nfunc (u *updateT) body() (string, error) {\n\tb, err := json.Marshal(u.values)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(b), nil\n}\n\nfunc (u *updateT) useMasterKey() bool {\n\treturn u.shouldUseMasterKey\n}\n\nfunc (u *updateT) session() *sessionT {\n\treturn u.currentSession\n}\n\nfunc (u *updateT) contentType() string {\n\treturn \"application\/json\"\n}\n\nfunc LinkFacebookAccount(u *User, a *FacebookAuthData) error {\n\tif u.Id == \"\" {\n\t\treturn errors.New(\"user Id field must not be empty\")\n\t}\n\n\tup, _ := NewUpdate(u)\n\tup.Set(\"authData\", AuthData{Facebook: a})\n\tup.UseMasterKey()\n\treturn up.Execute()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/sha1\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com\/heroku\/heroku-cli\/Godeps\/_workspace\/src\/github.com\/dickeyxxx\/golock\"\n\t\"github.com\/heroku\/heroku-cli\/Godeps\/_workspace\/src\/github.com\/franela\/goreq\"\n\t\"github.com\/heroku\/heroku-cli\/gode\"\n)\n\nvar updateTopic = &Topic{\n\tName:        \"update\",\n\tDescription: \"update heroku-cli\",\n}\n\nvar updateCmd = &Command{\n\tTopic:       \"update\",\n\tHidden:      true,\n\tDescription: \"updates heroku-cli\",\n\tArgs:        []Arg{{Name: \"channel\", Optional: true}},\n\tFlags:       []Flag{{Name: \"background\", Hidden: true}},\n\tRun: func(ctx *Context) {\n\t\tchannel := ctx.Args.(map[string]string)[\"channel\"]\n\t\tif channel == \"\" {\n\t\t\tchannel = Channel\n\t\t}\n\t\tt := \"foreground\"\n\t\tif ctx.Flags[\"background\"] == true {\n\t\t\tt = \"background\"\n\t\t}\n\t\tUpdate(channel, t)\n\t},\n}\n\nvar binPath string\nvar updateLockPath = filepath.Join(AppDir(), \"updating.lock\")\nvar autoupdateFile = filepath.Join(AppDir(), \"autoupdate\")\n\nfunc init() {\n\tbinPath = os.Args[0]\n}\n\n\/\/ Update updates the CLI and plugins\nfunc Update(channel string, t string) {\n\tDebugln(\"running \" + version() + \" from \" + binPath)\n\tif !IsUpdateNeeded(t) {\n\t\treturn\n\t}\n\tdone := make(chan bool)\n\tgo func() {\n\t\ttouchAutoupdateFile()\n\t\tupdateCLI(channel)\n\t\tupdateNode()\n\t\tupdatePlugins()\n\t\tdone <- true\n\t}()\n\tselect {\n\tcase <-time.After(time.Second * 300):\n\t\tErrln(\"Timed out while updating\")\n\tcase <-done:\n\t}\n}\n\nfunc updatePlugins() {\n\tplugins := PluginNamesNotSymlinked()\n\tif len(plugins) == 0 {\n\t\treturn\n\t}\n\tErr(\"Updating plugins... \")\n\tpackages, err := gode.OutdatedPackages(plugins...)\n\tPrintError(err, true)\n\tif len(packages) > 0 {\n\t\tfor name, version := range packages {\n\t\t\tlockPlugin(name)\n\t\t\tPrintError(gode.InstallPackages(name+\"@\"+version), true)\n\t\t\tplugin, err := ParsePlugin(name)\n\t\t\tPrintError(err, true)\n\t\t\tAddPluginsToCache(plugin)\n\t\t\tunlockPlugin(name)\n\t\t}\n\t\tErrf(\"done. Updated %d %s.\\n\", len(packages), plural(\"package\", len(packages)))\n\t} else {\n\t\tErrln(\"no plugins to update.\")\n\t}\n}\n\nfunc updateCLI(channel string) {\n\tif channel == \"?\" {\n\t\t\/\/ do not update dev version\n\t\treturn\n\t}\n\tmanifest, err := getUpdateManifest(channel)\n\tif err != nil {\n\t\tWarn(\"Error updating CLI\")\n\t\tPrintError(err, false)\n\t\treturn\n\t}\n\tif manifest.Version == Version && manifest.Channel == Channel {\n\t\treturn\n\t}\n\tLogIfError(golock.Lock(updateLockPath))\n\tdefer golock.Unlock(updateLockPath)\n\tErrf(\"Updating Heroku v4 CLI to %s (%s)... \", manifest.Version, manifest.Channel)\n\tbuild := manifest.Builds[runtime.GOOS][runtime.GOARCH]\n\t\/\/ on windows we can't remove an existing file or remove the running binary\n\t\/\/ so we download the file to binName.new\n\t\/\/ move the running binary to binName.old (deleting any existing file first)\n\t\/\/ rename the downloaded file to binName\n\tif err := downloadBin(binPath+\".new\", build.URL); err != nil {\n\t\tpanic(err)\n\t}\n\tif fileSha1(binPath+\".new\") != build.Sha1 {\n\t\tpanic(\"SHA mismatch\")\n\t}\n\tos.Remove(binPath + \".old\")\n\tos.Rename(binPath, binPath+\".old\")\n\tif err := os.Rename(binPath+\".new\", binPath); err != nil {\n\t\tpanic(err)\n\t}\n\tos.Remove(binPath + \".old\")\n\tErrln(\"done\")\n\tclearAutoupdateFile() \/\/ force full update\n\treexec()              \/\/ reexec to finish updating with new code\n}\n\n\/\/ IsUpdateNeeded checks if an update is available\nfunc IsUpdateNeeded(t string) bool {\n\tf, err := os.Stat(autoupdateFile)\n\tif err != nil {\n\t\treturn true\n\t}\n\tif t == \"background\" {\n\t\treturn time.Since(f.ModTime()) > 4*time.Hour\n\t} else if t == \"block\" {\n\t\treturn time.Since(f.ModTime()) > 2160*time.Hour \/\/ 90 days\n\t}\n\treturn true\n}\n\nfunc touchAutoupdateFile() {\n\tout, err := os.OpenFile(autoupdateFile, os.O_WRONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tout.WriteString(time.Now().String())\n}\n\n\/\/ forces a full update on the next run\nfunc clearAutoupdateFile() {\n\tPrintError(os.Remove(autoupdateFile), true)\n}\n\ntype manifest struct {\n\tChannel, Version string\n\tBuilds           map[string]map[string]struct {\n\t\tURL, Sha1 string\n\t}\n}\n\nfunc getUpdateManifest(channel string) (*manifest, error) {\n\tres, err := goreq.Request{\n\t\tUri:       \"https:\/\/cli-assets.heroku.com\/\" + channel + \"\/manifest.json\",\n\t\tShowDebug: debugging,\n\t}.Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar m manifest\n\tres.Body.FromJsonTo(&m)\n\treturn &m, nil\n}\n\nfunc downloadBin(path, url string) error {\n\tout, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\tres, err := goreq.Request{\n\t\tUri:       url + \".gz\",\n\t\tShowDebug: debugging,\n\t}.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif res.StatusCode != 200 {\n\t\tb, _ := res.Body.ToString()\n\t\treturn errors.New(b)\n\t}\n\tdefer res.Body.Close()\n\t_, err = io.Copy(out, res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn out.Close()\n}\n\nfunc fileSha1(path string) string {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn fmt.Sprintf(\"%x\", sha1.Sum(data))\n}\n\n\/\/ TriggerBackgroundUpdate will trigger an update to the client in the background\nfunc TriggerBackgroundUpdate() {\n\tif IsUpdateNeeded(\"background\") {\n\t\texec.Command(binPath, \"update\", \"--background\").Start()\n\t}\n}\n\n\/\/ restarts the CLI with the same arguments\nfunc reexec() {\n\tDebugln(\"reexecing new CLI...\")\n\tcmd := exec.Command(binPath, os.Args[1:]...)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tos.Exit(getExitCode(cmd.Run()))\n}\n<commit_msg>ensure lockfile is unlocked after updating<commit_after>package main\n\nimport (\n\t\"crypto\/sha1\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com\/heroku\/heroku-cli\/Godeps\/_workspace\/src\/github.com\/dickeyxxx\/golock\"\n\t\"github.com\/heroku\/heroku-cli\/Godeps\/_workspace\/src\/github.com\/franela\/goreq\"\n\t\"github.com\/heroku\/heroku-cli\/gode\"\n)\n\nvar updateTopic = &Topic{\n\tName:        \"update\",\n\tDescription: \"update heroku-cli\",\n}\n\nvar updateCmd = &Command{\n\tTopic:       \"update\",\n\tHidden:      true,\n\tDescription: \"updates heroku-cli\",\n\tArgs:        []Arg{{Name: \"channel\", Optional: true}},\n\tFlags:       []Flag{{Name: \"background\", Hidden: true}},\n\tRun: func(ctx *Context) {\n\t\tchannel := ctx.Args.(map[string]string)[\"channel\"]\n\t\tif channel == \"\" {\n\t\t\tchannel = Channel\n\t\t}\n\t\tt := \"foreground\"\n\t\tif ctx.Flags[\"background\"] == true {\n\t\t\tt = \"background\"\n\t\t}\n\t\tUpdate(channel, t)\n\t},\n}\n\nvar binPath string\nvar updateLockPath = filepath.Join(AppDir(), \"updating.lock\")\nvar autoupdateFile = filepath.Join(AppDir(), \"autoupdate\")\n\nfunc init() {\n\tbinPath = os.Args[0]\n}\n\n\/\/ Update updates the CLI and plugins\nfunc Update(channel string, t string) {\n\tDebugln(\"running \" + version() + \" from \" + binPath)\n\tif !IsUpdateNeeded(t) {\n\t\treturn\n\t}\n\tdone := make(chan bool)\n\tgo func() {\n\t\ttouchAutoupdateFile()\n\t\tupdateCLI(channel)\n\t\tupdateNode()\n\t\tupdatePlugins()\n\t\tdone <- true\n\t}()\n\tselect {\n\tcase <-time.After(time.Second * 300):\n\t\tErrln(\"Timed out while updating\")\n\tcase <-done:\n\t}\n}\n\nfunc updatePlugins() {\n\tplugins := PluginNamesNotSymlinked()\n\tif len(plugins) == 0 {\n\t\treturn\n\t}\n\tErr(\"Updating plugins... \")\n\tpackages, err := gode.OutdatedPackages(plugins...)\n\tPrintError(err, true)\n\tif len(packages) > 0 {\n\t\tfor name, version := range packages {\n\t\t\tlockPlugin(name)\n\t\t\tPrintError(gode.InstallPackages(name+\"@\"+version), true)\n\t\t\tplugin, err := ParsePlugin(name)\n\t\t\tPrintError(err, true)\n\t\t\tAddPluginsToCache(plugin)\n\t\t\tunlockPlugin(name)\n\t\t}\n\t\tErrf(\"done. Updated %d %s.\\n\", len(packages), plural(\"package\", len(packages)))\n\t} else {\n\t\tErrln(\"no plugins to update.\")\n\t}\n}\n\nfunc updateCLI(channel string) {\n\tif channel == \"?\" {\n\t\t\/\/ do not update dev version\n\t\treturn\n\t}\n\tmanifest, err := getUpdateManifest(channel)\n\tif err != nil {\n\t\tWarn(\"Error updating CLI\")\n\t\tPrintError(err, false)\n\t\treturn\n\t}\n\tif manifest.Version == Version && manifest.Channel == Channel {\n\t\treturn\n\t}\n\tLogIfError(golock.Lock(updateLockPath))\n\tunlock := func() {\n\t\tgolock.Unlock(updateLockPath)\n\t}\n\tdefer unlock()\n\tErrf(\"Updating Heroku v4 CLI to %s (%s)... \", manifest.Version, manifest.Channel)\n\tbuild := manifest.Builds[runtime.GOOS][runtime.GOARCH]\n\t\/\/ on windows we can't remove an existing file or remove the running binary\n\t\/\/ so we download the file to binName.new\n\t\/\/ move the running binary to binName.old (deleting any existing file first)\n\t\/\/ rename the downloaded file to binName\n\tif err := downloadBin(binPath+\".new\", build.URL); err != nil {\n\t\tpanic(err)\n\t}\n\tif fileSha1(binPath+\".new\") != build.Sha1 {\n\t\tpanic(\"SHA mismatch\")\n\t}\n\tos.Remove(binPath + \".old\")\n\tos.Rename(binPath, binPath+\".old\")\n\tif err := os.Rename(binPath+\".new\", binPath); err != nil {\n\t\tpanic(err)\n\t}\n\tos.Remove(binPath + \".old\")\n\tErrln(\"done\")\n\tunlock()\n\tclearAutoupdateFile() \/\/ force full update\n\treexec()              \/\/ reexec to finish updating with new code\n}\n\n\/\/ IsUpdateNeeded checks if an update is available\nfunc IsUpdateNeeded(t string) bool {\n\tf, err := os.Stat(autoupdateFile)\n\tif err != nil {\n\t\treturn true\n\t}\n\tif t == \"background\" {\n\t\treturn time.Since(f.ModTime()) > 4*time.Hour\n\t} else if t == \"block\" {\n\t\treturn time.Since(f.ModTime()) > 2160*time.Hour \/\/ 90 days\n\t}\n\treturn true\n}\n\nfunc touchAutoupdateFile() {\n\tout, err := os.OpenFile(autoupdateFile, os.O_WRONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tout.WriteString(time.Now().String())\n}\n\n\/\/ forces a full update on the next run\nfunc clearAutoupdateFile() {\n\tPrintError(os.Remove(autoupdateFile), true)\n}\n\ntype manifest struct {\n\tChannel, Version string\n\tBuilds           map[string]map[string]struct {\n\t\tURL, Sha1 string\n\t}\n}\n\nfunc getUpdateManifest(channel string) (*manifest, error) {\n\tres, err := goreq.Request{\n\t\tUri:       \"https:\/\/cli-assets.heroku.com\/\" + channel + \"\/manifest.json\",\n\t\tShowDebug: debugging,\n\t}.Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar m manifest\n\tres.Body.FromJsonTo(&m)\n\treturn &m, nil\n}\n\nfunc downloadBin(path, url string) error {\n\tout, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\tres, err := goreq.Request{\n\t\tUri:       url + \".gz\",\n\t\tShowDebug: debugging,\n\t}.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif res.StatusCode != 200 {\n\t\tb, _ := res.Body.ToString()\n\t\treturn errors.New(b)\n\t}\n\tdefer res.Body.Close()\n\t_, err = io.Copy(out, res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn out.Close()\n}\n\nfunc fileSha1(path string) string {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn fmt.Sprintf(\"%x\", sha1.Sum(data))\n}\n\n\/\/ TriggerBackgroundUpdate will trigger an update to the client in the background\nfunc TriggerBackgroundUpdate() {\n\tif IsUpdateNeeded(\"background\") {\n\t\texec.Command(binPath, \"update\", \"--background\").Start()\n\t}\n}\n\n\/\/ restarts the CLI with the same arguments\nfunc reexec() {\n\tDebugln(\"reexecing new CLI...\")\n\tcmd := exec.Command(binPath, os.Args[1:]...)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tos.Exit(getExitCode(cmd.Run()))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"crypto\/sha256\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/kr\/binarydist\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"time\"\n)\n\nconst (\n\tupcktimePath = \"cktime\"\n\tplat         = runtime.GOOS + \"-\" + runtime.GOARCH\n)\n\nconst devValidTime = 7 * 24 * time.Hour\n\n\/\/ Update protocol.\n\/\/\n\/\/   GET hk.heroku.com\/hk-current-linux-amd64.json\n\/\/\n\/\/   200 ok\n\/\/   {\n\/\/       \"Version\": \"2\",\n\/\/       \"Sha256\": \"...\" \/\/ base64\n\/\/   }\n\/\/\n\/\/ then\n\/\/\n\/\/   GET hkpatch.s3.amazonaws.com\/hk-1-linux-amd64-to-2\n\/\/\n\/\/   200 ok\n\/\/   [bsdiff data]\n\/\/\n\/\/ or\n\/\/\n\/\/   GET hkdist.s3.amazonaws.com\/hk-2-linux-amd64.gz\n\/\/\n\/\/   200 ok\n\/\/   [gzipped executable data]\ntype Updater struct {\n\thkURL   string\n\tbinURL  string\n\tdiffURL string\n\tdir     string\n\tinfo    struct {\n\t\tVersion   string\n\t\tSha256 []byte\n\t}\n}\n\nfunc (u *Updater) run() {\n\tos.MkdirAll(u.dir, 0777)\n\tif u.wantUpdate() {\n\t\tl := exec.Command(\"logger\", \"-thk\")\n\t\tc := exec.Command(\"hk\", \"update\")\n\t\tif w, err := l.StdinPipe(); err == nil && l.Start() == nil {\n\t\t\tc.Stdout = w\n\t\t\tc.Stderr = w\n\t\t}\n\t\tc.Start()\n\t}\n}\n\nfunc (u *Updater) wantUpdate() bool {\n\tpath := u.dir + upcktimePath\n\tif Version == \"dev\" || readTime(path).After(time.Now()) {\n\t\treturn false\n\t}\n\twait := 24*time.Hour + randDuration(24*time.Hour)\n\treturn writeTime(path, time.Now().Add(wait))\n}\n\nfunc (u *Updater) update() error {\n\tfilename := \"hk\"\n\tif runtime.GOOS == \"windows\" {\n\t\tfilename += \".exe\"\n\t}\n\tpath, err := exec.LookPath(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\told, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = u.fetchInfo()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif u.info.Version == Version {\n\t\treturn nil\n\t}\n\tbin, err := u.fetchAndApplyPatch(old)\n\tif err != nil {\n\t\tbin, err = u.fetchBin()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\th := sha256.New()\n\th.Write(bin)\n\tif !bytes.Equal(h.Sum(nil), u.info.Sha256) {\n\t\treturn errors.New(\"new file hash mismatch after patch\")\n\t}\n\treturn install(old.Name(), bin)\n}\n\nfunc (u *Updater) fetchInfo() error {\n\tr, err := fetch(u.hkURL + \"hk-current-\" + plat + \".json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\terr = json.NewDecoder(r).Decode(&u.info)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(u.info.Sha256) != sha256.Size {\n\t\treturn errors.New(\"bad cmd hash in info\")\n\t}\n\treturn nil\n}\n\nfunc (u *Updater) fetchAndApplyPatch(old io.Reader) ([]byte, error) {\n\tr, err := fetch(u.diffURL + slug(Version) + \"-to-\" + u.info.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Close()\n\tvar buf bytes.Buffer\n\terr = binarydist.Patch(old, &buf, r)\n\treturn buf.Bytes(), err\n}\n\nfunc (u *Updater) fetchBin() ([]byte, error) {\n\tr, err := fetch(u.binURL + slug(u.info.Version) + \".gz\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Close()\n\tbuf := new(bytes.Buffer)\n\tgz, err := gzip.NewReader(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err = io.Copy(buf, gz); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\nfunc install(name string, p []byte) error {\n\texecDir := filepath.Dir(name)\n\tpart := filepath.Join(execDir, \"hk.part\")\n\terr := ioutil.WriteFile(part, p, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.Remove(part)\n\n\t\/\/ move the existing executable to a new file in the same directory\n\toldExecPath := fmt.Sprintf(\"%s.old\", name)\n\terr = os.Rename(name, oldExecPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ move the new executable in to become the new program\n\terr = os.Rename(part, name)\n\n\tif err != nil {\n\t\t\/\/ copy unsuccessful\n\t\terrRecover := os.Rename(oldExecPath, name)\n\t\tif errRecover != nil {\n\t\t\treturn errRecover\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t\/\/ copy successful, remove the old binary\n\t\t_ = os.Remove(oldExecPath)\n\t}\n\n\treturn nil\n}\n\n\/\/ returns a random duration in [0,n).\nfunc randDuration(n time.Duration) time.Duration {\n\treturn time.Duration(rand.Int63n(int64(n)))\n}\n\nfunc slug(ver string) string {\n\treturn \"hk-\" + ver + \"-\" + plat\n}\n\nfunc fetch(url string) (io.ReadCloser, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"bad http status from %s: %v\", url, resp.Status)\n\t}\n\treturn resp.Body, nil\n}\n\nfunc readTime(path string) time.Time {\n\tp, err := ioutil.ReadFile(path)\n\tif os.IsNotExist(err) {\n\t\treturn time.Time{}\n\t}\n\tif err != nil {\n\t\treturn time.Now().Add(1000 * time.Hour)\n\t}\n\tt, err := time.Parse(time.RFC3339, string(p))\n\tif err != nil {\n\t\treturn time.Now().Add(1000 * time.Hour)\n\t}\n\treturn t\n}\n\nfunc writeTime(path string, t time.Time) bool {\n\treturn ioutil.WriteFile(path, []byte(t.Format(time.RFC3339)), 0644) == nil\n}\n<commit_msg>always return original error after install failure<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"crypto\/sha256\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/kr\/binarydist\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"time\"\n)\n\nconst (\n\tupcktimePath = \"cktime\"\n\tplat         = runtime.GOOS + \"-\" + runtime.GOARCH\n)\n\nconst devValidTime = 7 * 24 * time.Hour\n\n\/\/ Update protocol.\n\/\/\n\/\/   GET hk.heroku.com\/hk-current-linux-amd64.json\n\/\/\n\/\/   200 ok\n\/\/   {\n\/\/       \"Version\": \"2\",\n\/\/       \"Sha256\": \"...\" \/\/ base64\n\/\/   }\n\/\/\n\/\/ then\n\/\/\n\/\/   GET hkpatch.s3.amazonaws.com\/hk-1-linux-amd64-to-2\n\/\/\n\/\/   200 ok\n\/\/   [bsdiff data]\n\/\/\n\/\/ or\n\/\/\n\/\/   GET hkdist.s3.amazonaws.com\/hk-2-linux-amd64.gz\n\/\/\n\/\/   200 ok\n\/\/   [gzipped executable data]\ntype Updater struct {\n\thkURL   string\n\tbinURL  string\n\tdiffURL string\n\tdir     string\n\tinfo    struct {\n\t\tVersion   string\n\t\tSha256 []byte\n\t}\n}\n\nfunc (u *Updater) run() {\n\tos.MkdirAll(u.dir, 0777)\n\tif u.wantUpdate() {\n\t\tl := exec.Command(\"logger\", \"-thk\")\n\t\tc := exec.Command(\"hk\", \"update\")\n\t\tif w, err := l.StdinPipe(); err == nil && l.Start() == nil {\n\t\t\tc.Stdout = w\n\t\t\tc.Stderr = w\n\t\t}\n\t\tc.Start()\n\t}\n}\n\nfunc (u *Updater) wantUpdate() bool {\n\tpath := u.dir + upcktimePath\n\tif Version == \"dev\" || readTime(path).After(time.Now()) {\n\t\treturn false\n\t}\n\twait := 24*time.Hour + randDuration(24*time.Hour)\n\treturn writeTime(path, time.Now().Add(wait))\n}\n\nfunc (u *Updater) update() error {\n\tfilename := \"hk\"\n\tif runtime.GOOS == \"windows\" {\n\t\tfilename += \".exe\"\n\t}\n\tpath, err := exec.LookPath(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\told, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = u.fetchInfo()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif u.info.Version == Version {\n\t\treturn nil\n\t}\n\tbin, err := u.fetchAndApplyPatch(old)\n\tif err != nil {\n\t\tbin, err = u.fetchBin()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\th := sha256.New()\n\th.Write(bin)\n\tif !bytes.Equal(h.Sum(nil), u.info.Sha256) {\n\t\treturn errors.New(\"new file hash mismatch after patch\")\n\t}\n\treturn install(old.Name(), bin)\n}\n\nfunc (u *Updater) fetchInfo() error {\n\tr, err := fetch(u.hkURL + \"hk-current-\" + plat + \".json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\terr = json.NewDecoder(r).Decode(&u.info)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(u.info.Sha256) != sha256.Size {\n\t\treturn errors.New(\"bad cmd hash in info\")\n\t}\n\treturn nil\n}\n\nfunc (u *Updater) fetchAndApplyPatch(old io.Reader) ([]byte, error) {\n\tr, err := fetch(u.diffURL + slug(Version) + \"-to-\" + u.info.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Close()\n\tvar buf bytes.Buffer\n\terr = binarydist.Patch(old, &buf, r)\n\treturn buf.Bytes(), err\n}\n\nfunc (u *Updater) fetchBin() ([]byte, error) {\n\tr, err := fetch(u.binURL + slug(u.info.Version) + \".gz\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Close()\n\tbuf := new(bytes.Buffer)\n\tgz, err := gzip.NewReader(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err = io.Copy(buf, gz); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\nfunc install(name string, p []byte) error {\n\texecDir := filepath.Dir(name)\n\tpart := filepath.Join(execDir, \"hk.part\")\n\terr := ioutil.WriteFile(part, p, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.Remove(part)\n\n\t\/\/ move the existing executable to a new file in the same directory\n\toldExecPath := fmt.Sprintf(\"%s.old\", name)\n\terr = os.Rename(name, oldExecPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ move the new executable in to become the new program\n\terr = os.Rename(part, name)\n\n\tif err != nil {\n\t\t\/\/ copy unsuccessful\n\t\t_ := os.Rename(oldExecPath, name)\n\t\treturn err\n\t} else {\n\t\t\/\/ copy successful, remove the old binary\n\t\t_ = os.Remove(oldExecPath)\n\t}\n\n\treturn nil\n}\n\n\/\/ returns a random duration in [0,n).\nfunc randDuration(n time.Duration) time.Duration {\n\treturn time.Duration(rand.Int63n(int64(n)))\n}\n\nfunc slug(ver string) string {\n\treturn \"hk-\" + ver + \"-\" + plat\n}\n\nfunc fetch(url string) (io.ReadCloser, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"bad http status from %s: %v\", url, resp.Status)\n\t}\n\treturn resp.Body, nil\n}\n\nfunc readTime(path string) time.Time {\n\tp, err := ioutil.ReadFile(path)\n\tif os.IsNotExist(err) {\n\t\treturn time.Time{}\n\t}\n\tif err != nil {\n\t\treturn time.Now().Add(1000 * time.Hour)\n\t}\n\tt, err := time.Parse(time.RFC3339, string(p))\n\tif err != nil {\n\t\treturn time.Now().Add(1000 * time.Hour)\n\t}\n\treturn t\n}\n\nfunc writeTime(path string, t time.Time) bool {\n\treturn ioutil.WriteFile(path, []byte(t.Format(time.RFC3339)), 0644) == nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/sha1\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/dickeyxxx\/golock\"\n\t\"github.com\/franela\/goreq\"\n\t\"github.com\/heroku\/heroku-cli\/gode\"\n\t\"github.com\/kardianos\/osext\"\n\t\"github.com\/ulikunitz\/xz\"\n)\n\nvar updateTopic = &Topic{\n\tName:        \"update\",\n\tDescription: \"update heroku-cli\",\n}\n\nvar updateCmd = &Command{\n\tTopic:            \"update\",\n\tHidden:           true,\n\tDescription:      \"updates heroku-cli\",\n\tDisableAnalytics: true,\n\tArgs:             []Arg{{Name: \"channel\", Optional: true}},\n\tFlags:            []Flag{{Name: \"background\", Hidden: true}},\n\tRun: func(ctx *Context) {\n\t\tchannel := ctx.Args.(map[string]string)[\"channel\"]\n\t\tif channel == \"\" {\n\t\t\tchannel = Channel\n\t\t}\n\t\tt := \"foreground\"\n\t\tif ctx.Flags[\"background\"] == true {\n\t\t\tt = \"background\"\n\t\t}\n\t\tUpdate(channel, t)\n\t},\n}\n\nvar binPath string\nvar updateLockPath = filepath.Join(AppDir(), \"updating.lock\")\nvar autoupdateFile = filepath.Join(AppDir(), \"autoupdate\")\nvar tmpPath = filepath.Join(AppDir(), \"tmp\")\n\nfunc init() {\n\tbinPath, _ = osext.Executable()\n}\n\n\/\/ Update updates the CLI and plugins\nfunc Update(channel string, t string) {\n\tif !IsUpdateNeeded(t) {\n\t\treturn\n\t}\n\ttouchAutoupdateFile()\n\tSubmitAnalytics()\n\tupdateCLI(channel)\n\tSetupNode()\n\tSetupBuiltinPlugins()\n\tupdatePlugins()\n\ttruncateErrorLog()\n\tcleanTmpDir()\n}\n\nfunc updatePlugins() {\n\taction(\"heroku-cli: Updating plugins\", \"\", func() {\n\t\tplugins := PluginNamesNotSymlinked()\n\t\tif len(plugins) == 0 {\n\t\t\treturn\n\t\t}\n\t\tpackages, err := gode.OutdatedPackages(plugins...)\n\t\tWarnIfError(err)\n\t\tif len(packages) > 0 {\n\t\t\tfor name, version := range packages {\n\t\t\t\tlockPlugin(name)\n\t\t\t\tWarnIfError(gode.InstallPackages(name + \"@\" + version))\n\t\t\t\tplugin, err := ParsePlugin(name)\n\t\t\t\tWarnIfError(err)\n\t\t\t\tAddPluginsToCache(plugin)\n\t\t\t\tunlockPlugin(name)\n\t\t\t}\n\t\t\tErrf(\" done. Updated %d %s.\\n\", len(packages), plural(\"package\", len(packages)))\n\t\t} else {\n\t\t\tErrln(\" no plugins to update.\")\n\t\t}\n\t})\n}\n\nfunc updateCLI(channel string) {\n\tif channel == \"?\" {\n\t\t\/\/ do not update dev version\n\t\treturn\n\t}\n\tmanifest, err := getUpdateManifest(channel)\n\tif err != nil {\n\t\tWarn(\"Error updating CLI\")\n\t\tWarnIfError(err)\n\t\treturn\n\t}\n\tif manifest.Version == Version && manifest.Channel == Channel {\n\t\treturn\n\t}\n\tlocked, err := golock.IsLocked(updateLockPath)\n\tLogIfError(err)\n\tif locked {\n\t\tWarn(\"Update in progress\")\n\t\treturn\n\t}\n\tLogIfError(golock.Lock(updateLockPath))\n\tunlock := func() {\n\t\tgolock.Unlock(updateLockPath)\n\t}\n\tdefer unlock()\n\tmsg := fmt.Sprintf(\"heroku-cli: Updating to %s\", manifest.Version)\n\tif manifest.Channel != \"master\" {\n\t\tmsg = fmt.Sprintf(\"%s (%s)\", msg, manifest.Channel)\n\t}\n\taction(msg, \"done\", func() {\n\t\tbuild := manifest.Builds[runtime.GOOS][runtime.GOARCH]\n\t\t\/\/ on windows we can't remove an existing file or remove the running binary\n\t\t\/\/ so we download the file to binName.new\n\t\t\/\/ move the running binary to binName.old (deleting any existing file first)\n\t\t\/\/ rename the downloaded file to binName\n\t\ttmpBinPathNew := binPath + \".new\"\n\t\ttmpBinPathOld := binPath + \".old\"\n\t\tif err := downloadBin(tmpBinPathNew, build.URL); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif fileSha1(tmpBinPathNew) != build.Sha1 {\n\t\t\tpanic(\"SHA mismatch\")\n\t\t}\n\t\tos.Remove(tmpBinPathOld)\n\t\tos.Rename(binPath, tmpBinPathOld)\n\t\tif err := os.Rename(tmpBinPathNew, binPath); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tos.Remove(tmpBinPathOld)\n\t\tunlock()\n\t\tclearAutoupdateFile() \/\/ force full update\n\t})\n\treexec() \/\/ reexec to finish updating with new code\n}\n\n\/\/ IsUpdateNeeded checks if an update is available\nfunc IsUpdateNeeded(t string) bool {\n\tf, err := os.Stat(autoupdateFile)\n\tif err != nil {\n\t\treturn true\n\t}\n\tif t == \"background\" {\n\t\treturn time.Since(f.ModTime()) > 4*time.Hour\n\t} else if t == \"block\" {\n\t\treturn time.Since(f.ModTime()) > 2160*time.Hour \/\/ 90 days\n\t}\n\treturn true\n}\n\nfunc touchAutoupdateFile() {\n\tout, err := os.OpenFile(autoupdateFile, os.O_WRONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tout.WriteString(time.Now().String())\n\tout.Close()\n}\n\n\/\/ forces a full update on the next run\nfunc clearAutoupdateFile() {\n\tWarnIfError(os.Remove(autoupdateFile))\n}\n\ntype manifest struct {\n\tChannel, Version string\n\tBuilds           map[string]map[string]struct {\n\t\tURL, Sha1 string\n\t}\n}\n\nfunc getUpdateManifest(channel string) (*manifest, error) {\n\tres, err := goreq.Request{\n\t\tUri:       \"https:\/\/cli-assets.heroku.com\/\" + channel + \"\/manifest.json\",\n\t\tTimeout:   30 * time.Minute,\n\t\tShowDebug: debugging,\n\t}.Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar m manifest\n\tres.Body.FromJsonTo(&m)\n\treturn &m, nil\n}\n\nfunc downloadBin(path, url string) error {\n\tout, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\tres, err := goreq.Request{\n\t\tUri:       url + \".xz\",\n\t\tTimeout:   30 * time.Minute,\n\t\tShowDebug: debugging,\n\t}.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif res.StatusCode != 200 {\n\t\tb, _ := res.Body.ToString()\n\t\treturn errors.New(b)\n\t}\n\tdefer res.Body.Close()\n\tuncompressed, err := xz.NewReader(res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(out, uncompressed)\n\treturn err\n}\n\nfunc fileSha1(path string) string {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn fmt.Sprintf(\"%x\", sha1.Sum(data))\n}\n\n\/\/ TriggerBackgroundUpdate will trigger an update to the client in the background\nfunc TriggerBackgroundUpdate() {\n\twg.Add(1)\n\tgo func() {\n\t\twg.Done()\n\t\tif IsUpdateNeeded(\"background\") {\n\t\t\texec.Command(binPath, \"update\", \"--background\").Start()\n\t\t}\n\t}()\n}\n\n\/\/ restarts the CLI with the same arguments\nfunc reexec() {\n\tDebugln(\"reexecing new CLI...\")\n\tcmd := exec.Command(binPath, os.Args[1:]...)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tExit(getExitCode(cmd.Run()))\n}\n\nfunc truncateErrorLog() {\n\tDebugln(\"truncating error log...\")\n\tbody, err := ioutil.ReadFile(ErrLogPath)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\tWarnIfError(err)\n\t\t}\n\t\treturn\n\t}\n\tlines := strings.Split(string(body), \"\\n\")\n\tlines = lines[maxint(len(lines)-1000, 0) : len(lines)-1]\n\terr = ioutil.WriteFile(ErrLogPath, []byte(strings.Join(lines, \"\\n\")+\"\\n\"), 0644)\n\tWarnIfError(err)\n}\n\nfunc maxint(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc cleanTmpDir() {\n\tDebugln(\"cleaning up tmp dirs...\")\n\tdirs, err := ioutil.ReadDir(tmpPath)\n\tif err != nil {\n\t\tWarnIfError(err)\n\t\treturn\n\t}\n\tfor _, dir := range dirs {\n\t\tif time.Since(dir.ModTime()) > 24*time.Hour {\n\t\t\tpath := filepath.Join(tmpPath, dir.Name())\n\t\t\tDebugln(\"deleting \" + path)\n\t\t\tWarnIfError(os.RemoveAll(path))\n\t\t}\n\t}\n}\n<commit_msg>submit analytis after updating plugin versions<commit_after>package main\n\nimport (\n\t\"crypto\/sha1\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/dickeyxxx\/golock\"\n\t\"github.com\/franela\/goreq\"\n\t\"github.com\/heroku\/heroku-cli\/gode\"\n\t\"github.com\/kardianos\/osext\"\n\t\"github.com\/ulikunitz\/xz\"\n)\n\nvar updateTopic = &Topic{\n\tName:        \"update\",\n\tDescription: \"update heroku-cli\",\n}\n\nvar updateCmd = &Command{\n\tTopic:            \"update\",\n\tHidden:           true,\n\tDescription:      \"updates heroku-cli\",\n\tDisableAnalytics: true,\n\tArgs:             []Arg{{Name: \"channel\", Optional: true}},\n\tFlags:            []Flag{{Name: \"background\", Hidden: true}},\n\tRun: func(ctx *Context) {\n\t\tchannel := ctx.Args.(map[string]string)[\"channel\"]\n\t\tif channel == \"\" {\n\t\t\tchannel = Channel\n\t\t}\n\t\tt := \"foreground\"\n\t\tif ctx.Flags[\"background\"] == true {\n\t\t\tt = \"background\"\n\t\t}\n\t\tUpdate(channel, t)\n\t},\n}\n\nvar binPath string\nvar updateLockPath = filepath.Join(AppDir(), \"updating.lock\")\nvar autoupdateFile = filepath.Join(AppDir(), \"autoupdate\")\nvar tmpPath = filepath.Join(AppDir(), \"tmp\")\n\nfunc init() {\n\tbinPath, _ = osext.Executable()\n}\n\n\/\/ Update updates the CLI and plugins\nfunc Update(channel string, t string) {\n\tif !IsUpdateNeeded(t) {\n\t\treturn\n\t}\n\ttouchAutoupdateFile()\n\tupdateCLI(channel)\n\tSetupNode()\n\tSetupBuiltinPlugins()\n\tupdatePlugins()\n\tSubmitAnalytics()\n\ttruncateErrorLog()\n\tcleanTmpDir()\n}\n\nfunc updatePlugins() {\n\taction(\"heroku-cli: Updating plugins\", \"\", func() {\n\t\tplugins := PluginNamesNotSymlinked()\n\t\tif len(plugins) == 0 {\n\t\t\treturn\n\t\t}\n\t\tpackages, err := gode.OutdatedPackages(plugins...)\n\t\tWarnIfError(err)\n\t\tif len(packages) > 0 {\n\t\t\tfor name, version := range packages {\n\t\t\t\tlockPlugin(name)\n\t\t\t\tWarnIfError(gode.InstallPackages(name + \"@\" + version))\n\t\t\t\tplugin, err := ParsePlugin(name)\n\t\t\t\tWarnIfError(err)\n\t\t\t\tAddPluginsToCache(plugin)\n\t\t\t\tunlockPlugin(name)\n\t\t\t}\n\t\t\tErrf(\" done. Updated %d %s.\\n\", len(packages), plural(\"package\", len(packages)))\n\t\t} else {\n\t\t\tErrln(\" no plugins to update.\")\n\t\t}\n\t})\n}\n\nfunc updateCLI(channel string) {\n\tif channel == \"?\" {\n\t\t\/\/ do not update dev version\n\t\treturn\n\t}\n\tmanifest, err := getUpdateManifest(channel)\n\tif err != nil {\n\t\tWarn(\"Error updating CLI\")\n\t\tWarnIfError(err)\n\t\treturn\n\t}\n\tif manifest.Version == Version && manifest.Channel == Channel {\n\t\treturn\n\t}\n\tlocked, err := golock.IsLocked(updateLockPath)\n\tLogIfError(err)\n\tif locked {\n\t\tWarn(\"Update in progress\")\n\t\treturn\n\t}\n\tLogIfError(golock.Lock(updateLockPath))\n\tunlock := func() {\n\t\tgolock.Unlock(updateLockPath)\n\t}\n\tdefer unlock()\n\tmsg := fmt.Sprintf(\"heroku-cli: Updating to %s\", manifest.Version)\n\tif manifest.Channel != \"master\" {\n\t\tmsg = fmt.Sprintf(\"%s (%s)\", msg, manifest.Channel)\n\t}\n\taction(msg, \"done\", func() {\n\t\tbuild := manifest.Builds[runtime.GOOS][runtime.GOARCH]\n\t\t\/\/ on windows we can't remove an existing file or remove the running binary\n\t\t\/\/ so we download the file to binName.new\n\t\t\/\/ move the running binary to binName.old (deleting any existing file first)\n\t\t\/\/ rename the downloaded file to binName\n\t\ttmpBinPathNew := binPath + \".new\"\n\t\ttmpBinPathOld := binPath + \".old\"\n\t\tif err := downloadBin(tmpBinPathNew, build.URL); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif fileSha1(tmpBinPathNew) != build.Sha1 {\n\t\t\tpanic(\"SHA mismatch\")\n\t\t}\n\t\tos.Remove(tmpBinPathOld)\n\t\tos.Rename(binPath, tmpBinPathOld)\n\t\tif err := os.Rename(tmpBinPathNew, binPath); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tos.Remove(tmpBinPathOld)\n\t\tunlock()\n\t\tclearAutoupdateFile() \/\/ force full update\n\t})\n\treexec() \/\/ reexec to finish updating with new code\n}\n\n\/\/ IsUpdateNeeded checks if an update is available\nfunc IsUpdateNeeded(t string) bool {\n\tf, err := os.Stat(autoupdateFile)\n\tif err != nil {\n\t\treturn true\n\t}\n\tif t == \"background\" {\n\t\treturn time.Since(f.ModTime()) > 4*time.Hour\n\t} else if t == \"block\" {\n\t\treturn time.Since(f.ModTime()) > 2160*time.Hour \/\/ 90 days\n\t}\n\treturn true\n}\n\nfunc touchAutoupdateFile() {\n\tout, err := os.OpenFile(autoupdateFile, os.O_WRONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tout.WriteString(time.Now().String())\n\tout.Close()\n}\n\n\/\/ forces a full update on the next run\nfunc clearAutoupdateFile() {\n\tWarnIfError(os.Remove(autoupdateFile))\n}\n\ntype manifest struct {\n\tChannel, Version string\n\tBuilds           map[string]map[string]struct {\n\t\tURL, Sha1 string\n\t}\n}\n\nfunc getUpdateManifest(channel string) (*manifest, error) {\n\tres, err := goreq.Request{\n\t\tUri:       \"https:\/\/cli-assets.heroku.com\/\" + channel + \"\/manifest.json\",\n\t\tTimeout:   30 * time.Minute,\n\t\tShowDebug: debugging,\n\t}.Do()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar m manifest\n\tres.Body.FromJsonTo(&m)\n\treturn &m, nil\n}\n\nfunc downloadBin(path, url string) error {\n\tout, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer out.Close()\n\tres, err := goreq.Request{\n\t\tUri:       url + \".xz\",\n\t\tTimeout:   30 * time.Minute,\n\t\tShowDebug: debugging,\n\t}.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif res.StatusCode != 200 {\n\t\tb, _ := res.Body.ToString()\n\t\treturn errors.New(b)\n\t}\n\tdefer res.Body.Close()\n\tuncompressed, err := xz.NewReader(res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = io.Copy(out, uncompressed)\n\treturn err\n}\n\nfunc fileSha1(path string) string {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn fmt.Sprintf(\"%x\", sha1.Sum(data))\n}\n\n\/\/ TriggerBackgroundUpdate will trigger an update to the client in the background\nfunc TriggerBackgroundUpdate() {\n\twg.Add(1)\n\tgo func() {\n\t\twg.Done()\n\t\tif IsUpdateNeeded(\"background\") {\n\t\t\texec.Command(binPath, \"update\", \"--background\").Start()\n\t\t}\n\t}()\n}\n\n\/\/ restarts the CLI with the same arguments\nfunc reexec() {\n\tDebugln(\"reexecing new CLI...\")\n\tcmd := exec.Command(binPath, os.Args[1:]...)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tExit(getExitCode(cmd.Run()))\n}\n\nfunc truncateErrorLog() {\n\tDebugln(\"truncating error log...\")\n\tbody, err := ioutil.ReadFile(ErrLogPath)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\tWarnIfError(err)\n\t\t}\n\t\treturn\n\t}\n\tlines := strings.Split(string(body), \"\\n\")\n\tlines = lines[maxint(len(lines)-1000, 0) : len(lines)-1]\n\terr = ioutil.WriteFile(ErrLogPath, []byte(strings.Join(lines, \"\\n\")+\"\\n\"), 0644)\n\tWarnIfError(err)\n}\n\nfunc maxint(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc cleanTmpDir() {\n\tDebugln(\"cleaning up tmp dirs...\")\n\tdirs, err := ioutil.ReadDir(tmpPath)\n\tif err != nil {\n\t\tWarnIfError(err)\n\t\treturn\n\t}\n\tfor _, dir := range dirs {\n\t\tif time.Since(dir.ModTime()) > 24*time.Hour {\n\t\t\tpath := filepath.Join(tmpPath, dir.Name())\n\t\t\tDebugln(\"deleting \" + path)\n\t\t\tWarnIfError(os.RemoveAll(path))\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gorillaws\n\nimport (\n\t\"encoding\/binary\"\n\t\"github.com\/davyxu\/cellnet\"\n\t\"github.com\/davyxu\/cellnet\/codec\"\n\t\"github.com\/gorilla\/websocket\"\n)\n\nconst (\n\tMsgIDSize = 2 \/\/ uint16\n)\n\ntype WSMessageTransmitter struct {\n}\n\nfunc (WSMessageTransmitter) OnRecvMessage(ses cellnet.Session) (msg interface{}, err error) {\n\n\tconn, ok := ses.Raw().(*websocket.Conn)\n\n\t\/\/ 转换错误，或者连接已经关闭时退出\n\tif !ok || conn == nil {\n\t\treturn nil, nil\n\t}\n\n\tvar messageType int\n\tvar raw []byte\n\tmessageType, raw, err = conn.ReadMessage()\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tswitch messageType {\n\tcase websocket.BinaryMessage:\n\t\tmsgID := binary.LittleEndian.Uint16(raw)\n\t\tmsgData := raw[MsgIDSize:]\n\n\t\tmsg, _, err = codec.DecodeMessage(int(msgID), msgData)\n\t}\n\n\treturn\n}\n\nfunc (WSMessageTransmitter) OnSendMessage(ses cellnet.Session, msg interface{}) error {\n\n\tconn, ok := ses.Raw().(*websocket.Conn)\n\n\t\/\/ 转换错误，或者连接已经关闭时退出\n\tif !ok || conn == nil {\n\t\treturn nil\n\t}\n\n\tvar (\n\t\tmsgData []byte\n\t\tmsgID   int\n\t)\n\n\tswitch m := msg.(type) {\n\tcase *cellnet.RawPacket: \/\/ 发裸包\n\t\tmsgData = m.MsgData\n\t\tmsgID = m.MsgID\n\tdefault: \/\/ 发普通编码包\n\t\tvar err error\n\t\tvar meta *cellnet.MessageMeta\n\n\t\t\/\/ 将用户数据转换为字节数组和消息ID\n\t\tmsgData, meta, err = codec.EncodeMessage(msg, nil)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmsgID = meta.ID\n\t}\n\n\tpkt := make([]byte, MsgIDSize+len(msgData))\n\tbinary.LittleEndian.PutUint16(pkt, uint16(msgID))\n\tcopy(pkt[MsgIDSize:], msgData)\n\n\tconn.WriteMessage(websocket.BinaryMessage, pkt)\n\n\treturn nil\n}\n<commit_msg>修复websocket输入封包小于消息号需要数据大小时导致的崩溃#63<commit_after>package gorillaws\n\nimport (\n\t\"encoding\/binary\"\n\t\"github.com\/davyxu\/cellnet\"\n\t\"github.com\/davyxu\/cellnet\/codec\"\n\t\"github.com\/davyxu\/cellnet\/util\"\n\t\"github.com\/gorilla\/websocket\"\n)\n\nconst (\n\tMsgIDSize = 2 \/\/ uint16\n)\n\ntype WSMessageTransmitter struct {\n}\n\nfunc (WSMessageTransmitter) OnRecvMessage(ses cellnet.Session) (msg interface{}, err error) {\n\n\tconn, ok := ses.Raw().(*websocket.Conn)\n\n\t\/\/ 转换错误，或者连接已经关闭时退出\n\tif !ok || conn == nil {\n\t\treturn nil, nil\n\t}\n\n\tvar messageType int\n\tvar raw []byte\n\tmessageType, raw, err = conn.ReadMessage()\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(raw) < MsgIDSize {\n\t\treturn nil, util.ErrMinPacket\n\t}\n\n\tswitch messageType {\n\tcase websocket.BinaryMessage:\n\t\tmsgID := binary.LittleEndian.Uint16(raw)\n\t\tmsgData := raw[MsgIDSize:]\n\n\t\tmsg, _, err = codec.DecodeMessage(int(msgID), msgData)\n\t}\n\n\treturn\n}\n\nfunc (WSMessageTransmitter) OnSendMessage(ses cellnet.Session, msg interface{}) error {\n\n\tconn, ok := ses.Raw().(*websocket.Conn)\n\n\t\/\/ 转换错误，或者连接已经关闭时退出\n\tif !ok || conn == nil {\n\t\treturn nil\n\t}\n\n\tvar (\n\t\tmsgData []byte\n\t\tmsgID   int\n\t)\n\n\tswitch m := msg.(type) {\n\tcase *cellnet.RawPacket: \/\/ 发裸包\n\t\tmsgData = m.MsgData\n\t\tmsgID = m.MsgID\n\tdefault: \/\/ 发普通编码包\n\t\tvar err error\n\t\tvar meta *cellnet.MessageMeta\n\n\t\t\/\/ 将用户数据转换为字节数组和消息ID\n\t\tmsgData, meta, err = codec.EncodeMessage(msg, nil)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmsgID = meta.ID\n\t}\n\n\tpkt := make([]byte, MsgIDSize+len(msgData))\n\tbinary.LittleEndian.PutUint16(pkt, uint16(msgID))\n\tcopy(pkt[MsgIDSize:], msgData)\n\n\tconn.WriteMessage(websocket.BinaryMessage, pkt)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package processors\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/rehabstudio\/oneill\/oneill\"\n)\n\nconst (\n\tnginxTemplate string = `\n        upstream {{.Subdomain}} {\n          server localhost:{{.Port}};\n        }\n\n        server {\n          listen *:80;\n          server_name {{.Subdomain}}.{{.ServingDomain}};\n          return 301 https:\/\/$server_name$request_uri;\n        }\n\n        server {\n          listen 443;\n          server_name {{.Subdomain}}.{{.ServingDomain}};\n\n          ssl on;\n          ssl_certificate \/etc\/ssl\/certs\/labs-server.crt;\n          ssl_certificate_key \/etc\/ssl\/private\/labs-server.pem;\n          ssl_protocols TLSv1 TLSv1.1 TLSv1.2;\n          ssl_session_timeout 5m;\n          ssl_session_cache shared:SSL:5m;\n\n          client_max_body_size 0; # disable any limits to avoid HTTP 413 for large image uploads\n\n          # required to avoid HTTP 411: see Issue #1486 (https:\/\/github.com\/docker\/docker\/issues\/1486)\n          chunked_transfer_encoding on;\n\n          location \/ {\n            proxy_pass                       http:\/\/{{.Subdomain}};\n            proxy_set_header  Host           $http_host;   # required for docker client's sake\n            proxy_set_header  X-Real-IP      $remote_addr; # pass on real client's IP\n            proxy_read_timeout               900;\n          }\n\n        }\n`\n)\n\nfunc ensureFreshOutputDir() {\n\toneill.LogDebug(\"Recreating empty configuration directory\")\n\toutDir := oneill.Config.NginxConfigDirectory\n\terr := os.RemoveAll(outDir)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = os.Mkdir(outDir, 0755)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc reloadNginxConfig() error {\n\trunCmd := exec.Command(\"service\", \"nginx\", \"reload\")\n\treturn runCmd.Run()\n}\n\ntype templateContext struct {\n\tSubdomain     string\n\tServingDomain string\n\tPort          int64\n}\n\nfunc writeTemplateToDisk(siteConfig *oneill.SiteConfig, container docker.APIContainers) {\n\ttmpl, err := template.New(\"nginx-config\").Parse(nginxTemplate)\n\tif err != nil {\n\t\toneill.LogWarning(fmt.Sprintf(\"Unable to load nginx config template: %s\", siteConfig.Subdomain))\n\t\treturn\n\t}\n\n\tvar b bytes.Buffer\n\tcontext := templateContext{\n\t\tSubdomain:     siteConfig.Subdomain,\n\t\tServingDomain: oneill.Config.ServingDomain,\n\t\tPort:          container.Ports[0].PublicPort,\n\t}\n\terr = tmpl.Execute(&b, context)\n\tif err != nil {\n\t\toneill.LogWarning(fmt.Sprintf(\"Unable to execute nginx config template: %s\", siteConfig.Subdomain))\n\t\treturn\n\t}\n\toutDir := oneill.Config.NginxConfigDirectory\n\toutFile := path.Join(outDir, fmt.Sprintf(\"%s.conf\", siteConfig.Subdomain))\n\terr = ioutil.WriteFile(outFile, b.Bytes(), 0644)\n\tif err != nil {\n\t\toneill.LogWarning(fmt.Sprintf(\"Unable to write nginx config template: %s\", siteConfig.Subdomain))\n\t\treturn\n\t}\n}\n\nfunc ConfigureNginx(siteConfigs []*oneill.SiteConfig) []*oneill.SiteConfig {\n\toneill.LogInfo(\"## Configuring Nginx\")\n\n\tensureFreshOutputDir()\n\n\tfor _, sc := range siteConfigs {\n\t\tfor _, container := range oneill.ListContainers() {\n\t\t\tcontainerName := strings.TrimPrefix(container.Names[0], \"\/\")\n\t\t\tif containerName == sc.Subdomain {\n\t\t\t\twriteTemplateToDisk(sc, container)\n\t\t\t\toneill.LogDebug(fmt.Sprintf(\"Configured nginx proxy for container: %s\", sc.Subdomain))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif err := reloadNginxConfig(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn siteConfigs\n}\n<commit_msg>don't panic when unable to reload nginx config<commit_after>package processors\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/rehabstudio\/oneill\/oneill\"\n)\n\nconst (\n\tnginxTemplate string = `\n        upstream {{.Subdomain}} {\n          server localhost:{{.Port}};\n        }\n\n        server {\n          listen *:80;\n          server_name {{.Subdomain}}.{{.ServingDomain}};\n          return 301 https:\/\/$server_name$request_uri;\n        }\n\n        server {\n          listen 443;\n          server_name {{.Subdomain}}.{{.ServingDomain}};\n\n          ssl on;\n          ssl_certificate \/etc\/ssl\/certs\/labs-server.crt;\n          ssl_certificate_key \/etc\/ssl\/private\/labs-server.pem;\n          ssl_protocols TLSv1 TLSv1.1 TLSv1.2;\n          ssl_session_timeout 5m;\n          ssl_session_cache shared:SSL:5m;\n\n          client_max_body_size 0; # disable any limits to avoid HTTP 413 for large image uploads\n\n          # required to avoid HTTP 411: see Issue #1486 (https:\/\/github.com\/docker\/docker\/issues\/1486)\n          chunked_transfer_encoding on;\n\n          location \/ {\n            proxy_pass                       http:\/\/{{.Subdomain}};\n            proxy_set_header  Host           $http_host;   # required for docker client's sake\n            proxy_set_header  X-Real-IP      $remote_addr; # pass on real client's IP\n            proxy_read_timeout               900;\n          }\n\n        }\n`\n)\n\nfunc ensureFreshOutputDir() {\n\toneill.LogDebug(\"Recreating empty configuration directory\")\n\toutDir := oneill.Config.NginxConfigDirectory\n\terr := os.RemoveAll(outDir)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = os.Mkdir(outDir, 0755)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc reloadNginxConfig() error {\n\trunCmd := exec.Command(\"service\", \"nginx\", \"reload\")\n\treturn runCmd.Run()\n}\n\ntype templateContext struct {\n\tSubdomain     string\n\tServingDomain string\n\tPort          int64\n}\n\nfunc writeTemplateToDisk(siteConfig *oneill.SiteConfig, container docker.APIContainers) {\n\ttmpl, err := template.New(\"nginx-config\").Parse(nginxTemplate)\n\tif err != nil {\n\t\toneill.LogWarning(fmt.Sprintf(\"Unable to load nginx config template: %s\", siteConfig.Subdomain))\n\t\treturn\n\t}\n\n\tvar b bytes.Buffer\n\tcontext := templateContext{\n\t\tSubdomain:     siteConfig.Subdomain,\n\t\tServingDomain: oneill.Config.ServingDomain,\n\t\tPort:          container.Ports[0].PublicPort,\n\t}\n\terr = tmpl.Execute(&b, context)\n\tif err != nil {\n\t\toneill.LogWarning(fmt.Sprintf(\"Unable to execute nginx config template: %s\", siteConfig.Subdomain))\n\t\treturn\n\t}\n\toutDir := oneill.Config.NginxConfigDirectory\n\toutFile := path.Join(outDir, fmt.Sprintf(\"%s.conf\", siteConfig.Subdomain))\n\terr = ioutil.WriteFile(outFile, b.Bytes(), 0644)\n\tif err != nil {\n\t\toneill.LogWarning(fmt.Sprintf(\"Unable to write nginx config template: %s\", siteConfig.Subdomain))\n\t\treturn\n\t}\n}\n\nfunc ConfigureNginx(siteConfigs []*oneill.SiteConfig) []*oneill.SiteConfig {\n\toneill.LogInfo(\"## Configuring Nginx\")\n\n\tensureFreshOutputDir()\n\n\tfor _, sc := range siteConfigs {\n\t\tfor _, container := range oneill.ListContainers() {\n\t\t\tcontainerName := strings.TrimPrefix(container.Names[0], \"\/\")\n\t\t\tif containerName == sc.Subdomain {\n\t\t\t\twriteTemplateToDisk(sc, container)\n\t\t\t\toneill.LogDebug(fmt.Sprintf(\"Configured nginx proxy for container: %s\", sc.Subdomain))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif err := reloadNginxConfig(); err != nil {\n\t\toneill.LogWarning(\"Unable to reload nginx configuration\")\n\t\treturn siteConfigs\n\t}\n\toneill.LogDebug(\"Reloaded nginx configuration\")\n\treturn siteConfigs\n}\n<|endoftext|>"}
{"text":"<commit_before>package processors\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/rehabstudio\/oneill\/oneill\"\n)\n\nconst (\n\tnginxTemplate string = `\n        upstream {{.Subdomain}} {\n          server localhost:{{.Port}};\n        }\n\n        server {\n          listen *:80;\n          server_name {{.Subdomain}}.{{.ServingDomain}};\n          return 301 https:\/\/$server_name$request_uri;\n        }\n\n        server {\n          listen 443;\n          server_name {{.Subdomain}}.{{.ServingDomain}};\n\n          ssl on;\n          ssl_certificate \/etc\/ssl\/certs\/labs-server.crt;\n          ssl_certificate_key \/etc\/ssl\/private\/labs-server.pem;\n          ssl_protocols TLSv1 TLSv1.1 TLSv1.2;\n          ssl_session_timeout 5m;\n          ssl_session_cache shared:SSL:5m;\n\n          client_max_body_size 0; # disable any limits to avoid HTTP 413 for large image uploads\n\n          # required to avoid HTTP 411: see Issue #1486 (https:\/\/github.com\/docker\/docker\/issues\/1486)\n          chunked_transfer_encoding on;\n\n          location \/ {\n            proxy_pass                       http:\/\/{{.Subdomain}};\n            proxy_set_header  Host           $http_host;   # required for docker client's sake\n            proxy_set_header  X-Real-IP      $remote_addr; # pass on real client's IP\n            proxy_read_timeout               900;\n          }\n\n        }\n`\n)\n\nfunc ensureFreshOutputDir() {\n\toneill.LogDebug(\"Recreating empty configuration directory\")\n\toutDir := oneill.Config.NginxConfigDirectory\n\terr := os.RemoveAll(outDir)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = os.Mkdir(outDir, 0755)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc reloadNginxConfig() error {\n\trunCmd := exec.Command(\"service\", \"nginx\", \"reload\")\n\treturn runCmd.Run()\n}\n\ntype templateContext struct {\n\tSubdomain     string\n\tServingDomain string\n\tPort          int64\n}\n\nfunc writeTemplateToDisk(siteConfig *oneill.SiteConfig, container docker.APIContainers) {\n\ttmpl, err := template.New(\"nginx-config\").Parse(nginxTemplate)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvar b bytes.Buffer\n\tcontext := templateContext{\n\t\tSubdomain:     siteConfig.Subdomain,\n\t\tServingDomain: oneill.Config.ServingDomain,\n\t\tPort:          container.Ports[0].PublicPort,\n\t}\n\terr = tmpl.Execute(&b, context)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\toutDir := oneill.Config.NginxConfigDirectory\n\toutFile := path.Join(outDir, fmt.Sprintf(\"%s.conf\", siteConfig.Subdomain))\n\terr = ioutil.WriteFile(outFile, b.Bytes(), 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc ConfigureNginx(siteConfigs []*oneill.SiteConfig) []*oneill.SiteConfig {\n\toneill.LogInfo(\"## Configuring Nginx\")\n\n\tensureFreshOutputDir()\n\n\tfor _, sc := range siteConfigs {\n\t\tfor _, container := range oneill.ListContainers() {\n\t\t\tcontainerName := strings.TrimPrefix(container.Names[0], \"\/\")\n\t\t\tif containerName == sc.Subdomain {\n\t\t\t\twriteTemplateToDisk(sc, container)\n\t\t\t\toneill.LogDebug(fmt.Sprintf(\"Configured nginx proxy for container: %s\", sc.Subdomain))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif err := reloadNginxConfig(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn siteConfigs\n}\n<commit_msg>don't panic when unable to write nginx config file<commit_after>package processors\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/rehabstudio\/oneill\/oneill\"\n)\n\nconst (\n\tnginxTemplate string = `\n        upstream {{.Subdomain}} {\n          server localhost:{{.Port}};\n        }\n\n        server {\n          listen *:80;\n          server_name {{.Subdomain}}.{{.ServingDomain}};\n          return 301 https:\/\/$server_name$request_uri;\n        }\n\n        server {\n          listen 443;\n          server_name {{.Subdomain}}.{{.ServingDomain}};\n\n          ssl on;\n          ssl_certificate \/etc\/ssl\/certs\/labs-server.crt;\n          ssl_certificate_key \/etc\/ssl\/private\/labs-server.pem;\n          ssl_protocols TLSv1 TLSv1.1 TLSv1.2;\n          ssl_session_timeout 5m;\n          ssl_session_cache shared:SSL:5m;\n\n          client_max_body_size 0; # disable any limits to avoid HTTP 413 for large image uploads\n\n          # required to avoid HTTP 411: see Issue #1486 (https:\/\/github.com\/docker\/docker\/issues\/1486)\n          chunked_transfer_encoding on;\n\n          location \/ {\n            proxy_pass                       http:\/\/{{.Subdomain}};\n            proxy_set_header  Host           $http_host;   # required for docker client's sake\n            proxy_set_header  X-Real-IP      $remote_addr; # pass on real client's IP\n            proxy_read_timeout               900;\n          }\n\n        }\n`\n)\n\nfunc ensureFreshOutputDir() {\n\toneill.LogDebug(\"Recreating empty configuration directory\")\n\toutDir := oneill.Config.NginxConfigDirectory\n\terr := os.RemoveAll(outDir)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = os.Mkdir(outDir, 0755)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc reloadNginxConfig() error {\n\trunCmd := exec.Command(\"service\", \"nginx\", \"reload\")\n\treturn runCmd.Run()\n}\n\ntype templateContext struct {\n\tSubdomain     string\n\tServingDomain string\n\tPort          int64\n}\n\nfunc writeTemplateToDisk(siteConfig *oneill.SiteConfig, container docker.APIContainers) {\n\ttmpl, err := template.New(\"nginx-config\").Parse(nginxTemplate)\n\tif err != nil {\n\t\toneill.LogWarning(fmt.Sprintf(\"Unable to load nginx config template: %s\", siteConfig.Subdomain))\n\t\treturn\n\t}\n\n\tvar b bytes.Buffer\n\tcontext := templateContext{\n\t\tSubdomain:     siteConfig.Subdomain,\n\t\tServingDomain: oneill.Config.ServingDomain,\n\t\tPort:          container.Ports[0].PublicPort,\n\t}\n\terr = tmpl.Execute(&b, context)\n\tif err != nil {\n\t\toneill.LogWarning(fmt.Sprintf(\"Unable to execute nginx config template: %s\", siteConfig.Subdomain))\n\t\treturn\n\t}\n\toutDir := oneill.Config.NginxConfigDirectory\n\toutFile := path.Join(outDir, fmt.Sprintf(\"%s.conf\", siteConfig.Subdomain))\n\terr = ioutil.WriteFile(outFile, b.Bytes(), 0644)\n\tif err != nil {\n\t\toneill.LogWarning(fmt.Sprintf(\"Unable to write nginx config template: %s\", siteConfig.Subdomain))\n\t\treturn\n\t}\n}\n\nfunc ConfigureNginx(siteConfigs []*oneill.SiteConfig) []*oneill.SiteConfig {\n\toneill.LogInfo(\"## Configuring Nginx\")\n\n\tensureFreshOutputDir()\n\n\tfor _, sc := range siteConfigs {\n\t\tfor _, container := range oneill.ListContainers() {\n\t\t\tcontainerName := strings.TrimPrefix(container.Names[0], \"\/\")\n\t\t\tif containerName == sc.Subdomain {\n\t\t\t\twriteTemplateToDisk(sc, container)\n\t\t\t\toneill.LogDebug(fmt.Sprintf(\"Configured nginx proxy for container: %s\", sc.Subdomain))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif err := reloadNginxConfig(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn siteConfigs\n}\n<|endoftext|>"}
{"text":"<commit_before>package flux\n\nimport (\n\t\"log\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\n\/\/WaitInterface defines the flux.Wait interface method definitions\ntype WaitInterface interface {\n\tAdd()\n\tDone()\n\tCount() int\n\tFlush()\n\tThen() ActionInterface\n}\n\n\/\/ResetTimer runs a timer and performs an action\ntype ResetTimer struct {\n\treset    chan struct{}\n\tkill     chan struct{}\n\tduration time.Duration\n\tdo       *sync.Once\n\tinit     func()\n\tdone     func()\n\tstate    int64\n}\n\n\/\/NewResetTimer returns a new reset timer\nfunc NewResetTimer(init func(), done func(), d time.Duration) *ResetTimer {\n\trs := &ResetTimer{\n\t\treset:    make(chan struct{}),\n\t\tkill:     make(chan struct{}),\n\t\tduration: d,\n\t\tdo:       new(sync.Once),\n\t\tinit:     init,\n\t\tdone:     done,\n\t\tstate:    1,\n\t}\n\n\trs.init()\n\trs.handle()\n\treturn rs\n}\n\n\/\/Add reset the timer threshold\nfunc (r *ResetTimer) Add() {\n\tif r.do == nil {\n\t\treturn\n\t}\n\n\tstate := atomic.LoadInt64(&r.state)\n\tif state <= 0 {\n\t\tatomic.StoreInt64(&r.state, 1)\n\t\tr.init()\n\t\tr.handle()\n\t} else {\n\t\tr.reset <- struct{}{}\n\t}\n}\n\n\/\/Close closes this timer\nfunc (r *ResetTimer) Close() {\n\tdefer func() { r.do = nil }()\n\tr.do.Do(func() {\n\t\tclose(r.kill)\n\t\tclose(r.reset)\n\t})\n}\n\nfunc (r *ResetTimer) makeTime() <-chan time.Time {\n\treturn time.After(r.duration)\n}\n\nfunc (r *ResetTimer) handle() {\n\tgo func() {\n\t\tthreshold := r.makeTime()\n\tresetloop:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-r.reset:\n\t\t\t\tthreshold = r.makeTime()\n\t\t\tcase <-threshold:\n\t\t\t\tatomic.StoreInt64(&r.state, 0)\n\t\t\t\tr.done()\n\t\t\t\tbreak resetloop\n\t\t\tcase <-r.kill:\n\t\t\t\tatomic.StoreInt64(&r.state, 0)\n\t\t\t\tbreak resetloop\n\t\t\t}\n\t\t}\n\n\t}()\n}\n\n\/\/SwitchInterface defines a flux.Switch interface method definition\ntype SwitchInterface interface {\n\tSwitch()\n\tIsOn() bool\n\tWhenOn() ActionInterface\n\tWhenOff() ActionInterface\n}\n\n\/\/WaitGen is a nice way of creating regenerative timers for use\n\/\/wait timers are once timers, once they are clocked out they are of no more use,to allow their nature which has its benefits we get to create WaitGen that generates a new once once a wait gen is over\ntype WaitGen struct {\n\tcurrent WaitInterface\n\tgen     func() WaitInterface\n}\n\n\/\/Make returns a new WaitInterface or returns the current once\nfunc (w *WaitGen) Make() WaitInterface {\n\tif w.current != nil {\n\t\treturn w.current\n\t}\n\twt := w.gen()\n\twt.Then().WhenOnly(func(_ interface{}) {\n\t\tw.current = nil\n\t})\n\treturn wt\n}\n\n\/\/NewTimeWaitGen returns a wait generator making a timewaiter\nfunc NewTimeWaitGen(steps int, ms time.Duration, init func(WaitInterface)) *WaitGen {\n\treturn &WaitGen{\n\t\tnil,\n\t\tfunc() WaitInterface {\n\t\t\tnt := NewTimeWait(steps, ms)\n\t\t\tinit(nt)\n\t\t\treturn nt\n\t\t},\n\t}\n}\n\n\/\/NewSimpleWaitGen returns a wait generator making a timewaiter\nfunc NewSimpleWaitGen(init func(WaitInterface)) *WaitGen {\n\treturn &WaitGen{\n\t\tnil,\n\t\tfunc() WaitInterface {\n\t\t\tnt := NewWait()\n\t\t\tinit(nt)\n\t\t\treturn nt\n\t\t},\n\t}\n}\n\n\/\/baseWait defines the base wait structure for all waiters\ntype baseWait struct {\n\taction ActionInterface\n}\n\n\/\/Then returns an ActionInterface which gets fullfilled when this wait\n\/\/counter reaches zero\nfunc (w *baseWait) Then() ActionInterface {\n\treturn w.action.Wrap()\n}\n\nfunc newBaseWait() *baseWait {\n\treturn &baseWait{NewAction()}\n}\n\n\/\/TimeWait defines a time lock waiter\ntype TimeWait struct {\n\t*baseWait\n\tcloser chan struct{}\n\thits   int64\n\tmax    int\n\tms     time.Duration\n\tdoonce *sync.Once\n}\n\n\/\/NewTimeWait returns a new timer wait locker\n\/\/You specifiy two arguments:\n\/\/max int: the maximum number of time you want to check for idleness\n\/\/duration time.Duration: the time to check for each idle times and reduce\n\/\/until zero is reached then close\n\/\/eg. to do a 15seconds check for idleness\n\/\/NewTimeWait(15,time.Duration(1)*time.Second)\n\/\/eg. to do a 25 maximum check before closing per minute\n\/\/NewTimeWait(15,time.Duration(1)*time.Minute)\nfunc NewTimeWait(max int, duration time.Duration) *TimeWait {\n\n\ttm := &TimeWait{\n\t\tnewBaseWait(),\n\t\tmake(chan struct{}),\n\t\tint64(max),\n\t\tmax,\n\t\tduration,\n\t\tnew(sync.Once),\n\t}\n\n\t\/\/ tm.Add()\n\tgo tm.handle()\n\n\treturn tm\n}\n\n\/\/handle effects the necessary time process for checking and reducing the\n\/\/time checker for each duration of time,till the Waiter is done\nfunc (w *TimeWait) handle() {\n\tvar state int64\n\tatomic.StoreInt64(&state, 0)\n\n\tgo func() {\n\t\t<-w.closer\n\t\tatomic.StoreInt64(&state, 1)\n\t}()\n\n\tfor {\n\t\ttime.Sleep(w.ms)\n\n\t\tbit := atomic.LoadInt64(&state)\n\t\tif bit > 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tw.Done()\n\t}\n}\n\n\/\/Flush drops the lock count and forces immediate unlocking of the wait\nfunc (w *TimeWait) Flush() {\n\tw.doonce.Do(func() {\n\t\tclose(w.closer)\n\t\tw.action.Fullfill(0)\n\t\tatomic.StoreInt64(&w.hits, 0)\n\t})\n}\n\n\/\/Count returns the total left count to completed before unlock\nfunc (w *TimeWait) Count() int {\n\treturn int(atomic.LoadInt64(&w.hits))\n}\n\n\/\/Add increments the lock state to the lock counter unless its already unlocked\nfunc (w *TimeWait) Add() {\n\tif w.Count() < 0 || w.Count() >= w.max {\n\t\treturn\n\t}\n\n\tatomic.AddInt64(&w.hits, 1)\n}\n\n\/\/Done decrements the totalcount of this waitlocker by 1 until its below zero\n\/\/and fullfills with the 0 value\nfunc (w *TimeWait) Done() {\n\thits := atomic.LoadInt64(&w.hits)\n\n\tif hits < 0 {\n\t\treturn\n\t}\n\n\tnewhit := atomic.AddInt64(&w.hits, -1)\n\tlog.Printf(\"TimeWait: Count Down now %d before %d!\", newhit, hits)\n\tif int(newhit) <= 0 {\n\t\tw.Flush()\n\t\tlog.Printf(\"TimeWait: Count Down Finished!\")\n\t}\n}\n\n\/\/Wait implements the WiatInterface for creating a wait lock which\n\/\/waits until the lock lockcount is finished then executes a action\n\/\/can only be used once, that is ,once the wait counter is -1,you cant add\n\/\/to it anymore\ntype Wait struct {\n\t*baseWait\n\ttotalCount int64\n}\n\n\/\/NewWait returns a new Wait instance for the WaitInterface\nfunc NewWait() WaitInterface {\n\treturn &Wait{newBaseWait(), int64(0)}\n}\n\n\/\/Flush drops the lock count and forces immediate unlocking of the wait\nfunc (w *Wait) Flush() {\n\tcurr := int(atomic.LoadInt64(&w.totalCount))\n\tif curr < 0 {\n\t\treturn\n\t}\n\n\tatomic.StoreInt64(&w.totalCount, 0)\n\tw.Done()\n}\n\n\/\/Count returns the total left count to completed before unlock\nfunc (w *Wait) Count() int {\n\treturn int(atomic.LoadInt64(&w.totalCount))\n}\n\n\/\/Add increments the lock state to the lock counter unless its already unlocked\nfunc (w *Wait) Add() {\n\tcurr := atomic.LoadInt64(&w.totalCount)\n\n\tif curr < 0 {\n\t\treturn\n\t}\n\n\tatomic.AddInt64(&w.totalCount, 1)\n}\n\n\/\/Done decrements the totalcount of this waitlocker by 1 until its below zero\n\/\/and fullfills with the 0 value\nfunc (w *Wait) Done() {\n\tcurr := atomic.LoadInt64(&w.totalCount)\n\n\tif curr < 0 {\n\t\treturn\n\t}\n\n\tnc := atomic.AddInt64(&w.totalCount, -1)\n\t\/\/ log.Printf(\"Wait: Count Down now %d before %d\", nc, curr)\n\n\tif int(nc) <= 0 {\n\t\tw.action.Fullfill(0)\n\t}\n}\n<commit_msg>adding resettimer<commit_after>package flux\n\nimport (\n\t\"log\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\n\/\/WaitInterface defines the flux.Wait interface method definitions\ntype WaitInterface interface {\n\tAdd()\n\tDone()\n\tCount() int\n\tFlush()\n\tThen() ActionInterface\n}\n\n\/\/ResetTimer runs a timer and performs an action\ntype ResetTimer struct {\n\treset    chan struct{}\n\tkill     chan struct{}\n\tduration time.Duration\n\tdo       *sync.Once\n\tinit     func()\n\tdone     func()\n\tstate    int64\n}\n\n\/\/NewResetTimer returns a new reset timer\nfunc NewResetTimer(init func(), done func(), d time.Duration) *ResetTimer {\n\trs := &ResetTimer{\n\t\treset:    make(chan struct{}),\n\t\tkill:     make(chan struct{}),\n\t\tduration: d,\n\t\tdo:       new(sync.Once),\n\t\tinit:     init,\n\t\tdone:     done,\n\t\tstate:    1,\n\t}\n\n\trs.init()\n\trs.handle()\n\treturn rs\n}\n\n\/\/Add reset the timer threshold\nfunc (r *ResetTimer) Add() {\n\tif r.do == nil {\n\t\treturn\n\t}\n\n\tstate := atomic.LoadInt64(&r.state)\n\tif state <= 0 {\n\t\tatomic.StoreInt64(&r.state, 1)\n\t\tr.init()\n\t\tr.handle()\n\t} else {\n\t\tr.reset <- struct{}{}\n\t}\n}\n\n\/\/Close closes this timer\nfunc (r *ResetTimer) Close() {\n\tdefer func() { r.do = nil }()\n\tr.do.Do(func() {\n\t\tclose(r.kill)\n\t\tclose(r.reset)\n\t})\n}\n\nfunc (r *ResetTimer) makeTime() <-chan time.Time {\n\treturn time.After(r.duration)\n}\n\nfunc (r *ResetTimer) handle() {\n\tgo func() {\n\t\tthreshold := r.makeTime()\n\tresetloop:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-r.reset:\n\t\t\t\tthreshold = r.makeTime()\n\t\t\tcase <-threshold:\n\t\t\t\tatomic.StoreInt64(&r.state, 0)\n\t\t\t\tr.done()\n\t\t\t\tbreak resetloop\n\t\t\tcase <-r.kill:\n\t\t\t\tatomic.StoreInt64(&r.state, 0)\n\t\t\t\tr.done()\n\t\t\t\tbreak resetloop\n\t\t\t}\n\t\t}\n\n\t}()\n}\n\n\/\/SwitchInterface defines a flux.Switch interface method definition\ntype SwitchInterface interface {\n\tSwitch()\n\tIsOn() bool\n\tWhenOn() ActionInterface\n\tWhenOff() ActionInterface\n}\n\n\/\/WaitGen is a nice way of creating regenerative timers for use\n\/\/wait timers are once timers, once they are clocked out they are of no more use,to allow their nature which has its benefits we get to create WaitGen that generates a new once once a wait gen is over\ntype WaitGen struct {\n\tcurrent WaitInterface\n\tgen     func() WaitInterface\n}\n\n\/\/Make returns a new WaitInterface or returns the current once\nfunc (w *WaitGen) Make() WaitInterface {\n\tif w.current != nil {\n\t\treturn w.current\n\t}\n\twt := w.gen()\n\twt.Then().WhenOnly(func(_ interface{}) {\n\t\tw.current = nil\n\t})\n\treturn wt\n}\n\n\/\/NewTimeWaitGen returns a wait generator making a timewaiter\nfunc NewTimeWaitGen(steps int, ms time.Duration, init func(WaitInterface)) *WaitGen {\n\treturn &WaitGen{\n\t\tnil,\n\t\tfunc() WaitInterface {\n\t\t\tnt := NewTimeWait(steps, ms)\n\t\t\tinit(nt)\n\t\t\treturn nt\n\t\t},\n\t}\n}\n\n\/\/NewSimpleWaitGen returns a wait generator making a timewaiter\nfunc NewSimpleWaitGen(init func(WaitInterface)) *WaitGen {\n\treturn &WaitGen{\n\t\tnil,\n\t\tfunc() WaitInterface {\n\t\t\tnt := NewWait()\n\t\t\tinit(nt)\n\t\t\treturn nt\n\t\t},\n\t}\n}\n\n\/\/baseWait defines the base wait structure for all waiters\ntype baseWait struct {\n\taction ActionInterface\n}\n\n\/\/Then returns an ActionInterface which gets fullfilled when this wait\n\/\/counter reaches zero\nfunc (w *baseWait) Then() ActionInterface {\n\treturn w.action.Wrap()\n}\n\nfunc newBaseWait() *baseWait {\n\treturn &baseWait{NewAction()}\n}\n\n\/\/TimeWait defines a time lock waiter\ntype TimeWait struct {\n\t*baseWait\n\tcloser chan struct{}\n\thits   int64\n\tmax    int\n\tms     time.Duration\n\tdoonce *sync.Once\n}\n\n\/\/NewTimeWait returns a new timer wait locker\n\/\/You specifiy two arguments:\n\/\/max int: the maximum number of time you want to check for idleness\n\/\/duration time.Duration: the time to check for each idle times and reduce\n\/\/until zero is reached then close\n\/\/eg. to do a 15seconds check for idleness\n\/\/NewTimeWait(15,time.Duration(1)*time.Second)\n\/\/eg. to do a 25 maximum check before closing per minute\n\/\/NewTimeWait(15,time.Duration(1)*time.Minute)\nfunc NewTimeWait(max int, duration time.Duration) *TimeWait {\n\n\ttm := &TimeWait{\n\t\tnewBaseWait(),\n\t\tmake(chan struct{}),\n\t\tint64(max),\n\t\tmax,\n\t\tduration,\n\t\tnew(sync.Once),\n\t}\n\n\t\/\/ tm.Add()\n\tgo tm.handle()\n\n\treturn tm\n}\n\n\/\/handle effects the necessary time process for checking and reducing the\n\/\/time checker for each duration of time,till the Waiter is done\nfunc (w *TimeWait) handle() {\n\tvar state int64\n\tatomic.StoreInt64(&state, 0)\n\n\tgo func() {\n\t\t<-w.closer\n\t\tatomic.StoreInt64(&state, 1)\n\t}()\n\n\tfor {\n\t\ttime.Sleep(w.ms)\n\n\t\tbit := atomic.LoadInt64(&state)\n\t\tif bit > 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tw.Done()\n\t}\n}\n\n\/\/Flush drops the lock count and forces immediate unlocking of the wait\nfunc (w *TimeWait) Flush() {\n\tw.doonce.Do(func() {\n\t\tclose(w.closer)\n\t\tw.action.Fullfill(0)\n\t\tatomic.StoreInt64(&w.hits, 0)\n\t})\n}\n\n\/\/Count returns the total left count to completed before unlock\nfunc (w *TimeWait) Count() int {\n\treturn int(atomic.LoadInt64(&w.hits))\n}\n\n\/\/Add increments the lock state to the lock counter unless its already unlocked\nfunc (w *TimeWait) Add() {\n\tif w.Count() < 0 || w.Count() >= w.max {\n\t\treturn\n\t}\n\n\tatomic.AddInt64(&w.hits, 1)\n}\n\n\/\/Done decrements the totalcount of this waitlocker by 1 until its below zero\n\/\/and fullfills with the 0 value\nfunc (w *TimeWait) Done() {\n\thits := atomic.LoadInt64(&w.hits)\n\n\tif hits < 0 {\n\t\treturn\n\t}\n\n\tnewhit := atomic.AddInt64(&w.hits, -1)\n\tlog.Printf(\"TimeWait: Count Down now %d before %d!\", newhit, hits)\n\tif int(newhit) <= 0 {\n\t\tw.Flush()\n\t\tlog.Printf(\"TimeWait: Count Down Finished!\")\n\t}\n}\n\n\/\/Wait implements the WiatInterface for creating a wait lock which\n\/\/waits until the lock lockcount is finished then executes a action\n\/\/can only be used once, that is ,once the wait counter is -1,you cant add\n\/\/to it anymore\ntype Wait struct {\n\t*baseWait\n\ttotalCount int64\n}\n\n\/\/NewWait returns a new Wait instance for the WaitInterface\nfunc NewWait() WaitInterface {\n\treturn &Wait{newBaseWait(), int64(0)}\n}\n\n\/\/Flush drops the lock count and forces immediate unlocking of the wait\nfunc (w *Wait) Flush() {\n\tcurr := int(atomic.LoadInt64(&w.totalCount))\n\tif curr < 0 {\n\t\treturn\n\t}\n\n\tatomic.StoreInt64(&w.totalCount, 0)\n\tw.Done()\n}\n\n\/\/Count returns the total left count to completed before unlock\nfunc (w *Wait) Count() int {\n\treturn int(atomic.LoadInt64(&w.totalCount))\n}\n\n\/\/Add increments the lock state to the lock counter unless its already unlocked\nfunc (w *Wait) Add() {\n\tcurr := atomic.LoadInt64(&w.totalCount)\n\n\tif curr < 0 {\n\t\treturn\n\t}\n\n\tatomic.AddInt64(&w.totalCount, 1)\n}\n\n\/\/Done decrements the totalcount of this waitlocker by 1 until its below zero\n\/\/and fullfills with the 0 value\nfunc (w *Wait) Done() {\n\tcurr := atomic.LoadInt64(&w.totalCount)\n\n\tif curr < 0 {\n\t\treturn\n\t}\n\n\tnc := atomic.AddInt64(&w.totalCount, -1)\n\t\/\/ log.Printf(\"Wait: Count Down now %d before %d\", nc, curr)\n\n\tif int(nc) <= 0 {\n\t\tw.action.Fullfill(0)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ worker.go - mixnet client worker\n\/\/ Copyright (C) 2018, 2019  David Stainton\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\npackage client\n\nimport (\n\t\"errors\"\n\t\"math\"\n\t\"time\"\n\n\t\"github.com\/katzenpost\/client\/constants\"\n\tcConstants \"github.com\/katzenpost\/client\/constants\"\n\t\"github.com\/katzenpost\/client\/utils\"\n\t\"github.com\/katzenpost\/core\/crypto\/rand\"\n\t\"github.com\/katzenpost\/core\/pki\"\n\tmrand \"math\/rand\"\n)\n\ntype workerOp interface{}\n\ntype opConnStatusChanged struct {\n\tisConnected bool\n}\n\ntype opNewDocument struct {\n\tdoc *pki.Document\n}\n\nfunc (s *Session) connStatusChange(op opConnStatusChanged) bool {\n\tisConnected := op.isConnected\n\tif isConnected {\n\t\ts.onlineAt = time.Now()\n\n\t\tskew := s.minclient.ClockSkew()\n\t\tabsSkew := skew\n\t\tif absSkew < 0 {\n\t\t\tabsSkew = -absSkew\n\t\t}\n\t\tif absSkew > constants.TimeSkewWarnDelta {\n\t\t\t\/\/ Should this do more than just warn?  Should this\n\t\t\t\/\/ use skewed time?  I don't know.\n\t\t\ts.log.Warningf(\"The observed time difference between the host and provider clocks is '%v'. Correct your system time.\", skew)\n\t\t} else {\n\t\t\ts.log.Debugf(\"Clock skew vs provider: %v\", skew)\n\t\t}\n\t}\n\treturn isConnected\n}\n\nfunc (s *Session) worker() {\n\tconst maxDuration = math.MaxInt64\n\tmRng := rand.NewMath()\n\t\/\/ The PKI doc should be cached since we've\n\t\/\/ already waited until we received it.\n\tdoc := s.minclient.CurrentDocument()\n\tif doc == nil {\n\t\ts.fatalErrCh <- errors.New(\"aborting, PKI doc is nil\")\n\t\treturn\n\t}\n\n\t\/\/ get the initial loop services if decoy traffic is enabled\n\tvar loopServices []utils.ServiceDescriptor\n\tif !s.cfg.Debug.DisableDecoyTraffic {\n\t\tloopServices = utils.FindServices(cConstants.LoopService, doc)\n\t\tif len(loopServices) == 0 {\n\t\t\ts.fatalErrCh <- errors.New(\"failure to get loop service\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ LambdaP timer setup\n\tlambdaP := doc.LambdaP\n\tlambdaPMsec := uint64(rand.Exp(mRng, lambdaP))\n\tif lambdaPMsec > doc.LambdaPMaxDelay {\n\t\tlambdaPMsec = doc.LambdaPMaxDelay\n\t}\n\tlambdaPInterval := time.Duration(lambdaPMsec) * time.Millisecond\n\tlambdaPTimer := time.NewTimer(lambdaPInterval)\n\tdefer lambdaPTimer.Stop()\n\n\t\/\/ LambdaL timer setup\n\tlambdaL := doc.LambdaL\n\tlambdaLMsec := uint64(rand.Exp(mRng, lambdaL))\n\tif lambdaLMsec > doc.LambdaLMaxDelay {\n\t\tlambdaLMsec = doc.LambdaLMaxDelay\n\t}\n\tlambdaLInterval := time.Duration(lambdaLMsec) * time.Millisecond\n\tlambdaLTimer := time.NewTimer(lambdaLInterval)\n\tdefer lambdaLTimer.Stop()\n\n\t\/\/ LambdaD timer setup\n\tlambdaD := doc.LambdaD\n\tlambdaDMsec := uint64(rand.Exp(mRng, lambdaD))\n\tif lambdaDMsec > doc.LambdaDMaxDelay {\n\t\tlambdaDMsec = doc.LambdaDMaxDelay\n\t}\n\tlambdaDInterval := time.Duration(lambdaDMsec) * time.Millisecond\n\tlambdaDTimer := time.NewTimer(lambdaDInterval)\n\tdefer lambdaDTimer.Stop()\n\n\tdefer s.log.Debug(\"session worker halted\")\n\n\tisConnected := false\n\tmustResetAllTimers := false\n\tfor {\n\t\tvar lambdaPFired bool\n\t\tvar lambdaLFired bool\n\t\tvar lambdaDFired bool\n\t\tvar loopSvc *utils.ServiceDescriptor\n\t\tvar qo workerOp\n\n\t\tselect {\n\t\tcase <-s.HaltCh():\n\t\t\ts.log.Debugf(\"Session worker terminating gracefully.\")\n\t\t\treturn\n\t\tcase <-lambdaPTimer.C:\n\t\t\tlambdaPFired = true\n\t\tcase <-lambdaLTimer.C:\n\t\t\tlambdaLFired = true\n\t\tcase <-lambdaDTimer.C:\n\t\t\tlambdaDFired = true\n\t\tcase qo = <-s.opCh:\n\t\t}\n\n\t\tif qo != nil {\n\t\t\tswitch op := qo.(type) {\n\t\t\tcase opConnStatusChanged:\n\t\t\t\tnewConnectedStatus := s.connStatusChange(op)\n\t\t\t\tisConnected = newConnectedStatus\n\t\t\t\tmustResetAllTimers = true\n\t\t\tcase opNewDocument:\n\t\t\t\terr := s.isDocValid(op.doc)\n\t\t\t\tif err != nil {\n\t\t\t\t\ts.fatalErrCh <- err\n\t\t\t\t}\n\n\t\t\t\tdoc = op.doc\n\t\t\t\ts.setPollIntervalFromDoc(doc)\n\t\t\t\tlambdaP = doc.LambdaP\n\t\t\t\tlambdaL = doc.LambdaL\n\t\t\t\tlambdaD = doc.LambdaD\n\n\t\t\t\t\/\/ update the loop service descriptors\n\t\t\t\tloopServices = utils.FindServices(cConstants.LoopService, doc)\n\t\t\t\tif len(loopServices) == 0 {\n\t\t\t\t\ts.fatalErrCh <- errors.New(\"failure to get loop service\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tmustResetAllTimers = true\n\t\t\tdefault:\n\t\t\t\ts.log.Warningf(\"BUG: Worker received nonsensical op: %T\", op)\n\t\t\t} \/\/ end of switch\n\t\t} else {\n\t\t\tif isConnected {\n\t\t\t\t\/\/ select a loop service endpoint\n\t\t\t\tif !s.cfg.Debug.DisableDecoyTraffic {\n\t\t\t\t\tloopSvc = &loopServices[mrand.Intn(len(loopServices))]\n\t\t\t\t}\n\t\t\t\tif lambdaPFired {\n\t\t\t\t\ts.sendFromQueueOrDecoy(loopSvc)\n\t\t\t\t} else if lambdaLFired && !s.cfg.Debug.DisableDecoyTraffic {\n\t\t\t\t\ts.sendLoopDecoy(loopSvc)\n\t\t\t\t} else if lambdaDFired && !s.cfg.Debug.DisableDecoyTraffic {\n\t\t\t\t\tloopSvc = &loopServices[mrand.Intn(len(loopServices))]\n\t\t\t\t\ts.sendDropDecoy(loopSvc)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif isConnected {\n\t\t\tlambdaPMsec := uint64(rand.Exp(mRng, lambdaP))\n\t\t\tif lambdaPMsec > doc.LambdaPMaxDelay {\n\t\t\t\tlambdaPMsec = doc.LambdaPMaxDelay\n\t\t\t}\n\t\t\tlambdaPInterval = time.Duration(lambdaPMsec) * time.Millisecond\n\t\t\tlambdaLMsec := uint64(rand.Exp(mRng, lambdaL))\n\t\t\tif lambdaLMsec > doc.LambdaLMaxDelay {\n\t\t\t\tlambdaLMsec = doc.LambdaLMaxDelay\n\t\t\t}\n\t\t\tlambdaLInterval = time.Duration(lambdaLMsec) * time.Millisecond\n\t\t\tlambdaDMsec := uint64(rand.Exp(mRng, lambdaD))\n\t\t\tif lambdaDMsec > doc.LambdaDMaxDelay {\n\t\t\t\tlambdaDMsec = doc.LambdaDMaxDelay\n\t\t\t}\n\t\t\tlambdaDInterval = time.Duration(lambdaDMsec) * time.Millisecond\n\t\t} else {\n\t\t\tlambdaLInterval = time.Duration(maxDuration)\n\t\t\tlambdaPInterval = time.Duration(maxDuration)\n\t\t\tlambdaDInterval = time.Duration(maxDuration)\n\t\t}\n\n\t\tif mustResetAllTimers {\n\t\t\tlambdaPTimer.Reset(lambdaPInterval)\n\t\t\tlambdaLTimer.Reset(lambdaLInterval)\n\t\t\tlambdaDTimer.Reset(lambdaDInterval)\n\t\t\tmustResetAllTimers = false\n\t\t} else {\n\t\t\t\/\/ reset only the timer that fired\n\t\t\tif lambdaPFired {\n\t\t\t\tlambdaPTimer.Reset(lambdaPInterval)\n\t\t\t}\n\t\t\tif lambdaLFired {\n\t\t\t\tlambdaLTimer.Reset(lambdaLInterval)\n\t\t\t}\n\t\t\tif lambdaDFired {\n\t\t\t\tlambdaDTimer.Reset(lambdaDInterval)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ NOTREACHED\n}\n\nfunc (s *Session) sendFromQueueOrDecoy(loopSvc *utils.ServiceDescriptor) {\n\t\/\/ Attempt to send user data first, if any exists.\n\t\/\/ Otherwise send a drop decoy message.\n\t_, err := s.egressQueue.Peek()\n\tif err == nil {\n\t\ts.sendNext()\n\t} else if !s.cfg.Debug.DisableDecoyTraffic {\n\t\ts.sendDropDecoy(loopSvc)\n\t}\n}\n\nfunc (s *Session) isDocValid(doc *pki.Document) error {\n\tfor _, provider := range doc.Providers {\n\t\t_, ok := provider.Kaetzchen[constants.LoopService]\n\t\tif !ok {\n\t\t\treturn errors.New(\"found a Provider which does not have the loop service\")\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *Session) setPollIntervalFromDoc(doc *pki.Document) {\n\tslopFactor := 0.8\n\tpollProviderMsec := time.Duration((1.0 \/ (doc.LambdaP + doc.LambdaL)) * slopFactor * float64(time.Millisecond))\n\ts.log.Debugf(\"onDocument(): setting PollInterval to %s\", pollProviderMsec)\n\ts.minclient.SetPollInterval(pollProviderMsec)\n}\n<commit_msg>send loops not drops for receiver unobservability<commit_after>\/\/ worker.go - mixnet client worker\n\/\/ Copyright (C) 2018, 2019  David Stainton\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\npackage client\n\nimport (\n\t\"errors\"\n\t\"math\"\n\t\"time\"\n\n\t\"github.com\/katzenpost\/client\/constants\"\n\tcConstants \"github.com\/katzenpost\/client\/constants\"\n\t\"github.com\/katzenpost\/client\/utils\"\n\t\"github.com\/katzenpost\/core\/crypto\/rand\"\n\t\"github.com\/katzenpost\/core\/pki\"\n\tmrand \"math\/rand\"\n)\n\ntype workerOp interface{}\n\ntype opConnStatusChanged struct {\n\tisConnected bool\n}\n\ntype opNewDocument struct {\n\tdoc *pki.Document\n}\n\nfunc (s *Session) connStatusChange(op opConnStatusChanged) bool {\n\tisConnected := op.isConnected\n\tif isConnected {\n\t\ts.onlineAt = time.Now()\n\n\t\tskew := s.minclient.ClockSkew()\n\t\tabsSkew := skew\n\t\tif absSkew < 0 {\n\t\t\tabsSkew = -absSkew\n\t\t}\n\t\tif absSkew > constants.TimeSkewWarnDelta {\n\t\t\t\/\/ Should this do more than just warn?  Should this\n\t\t\t\/\/ use skewed time?  I don't know.\n\t\t\ts.log.Warningf(\"The observed time difference between the host and provider clocks is '%v'. Correct your system time.\", skew)\n\t\t} else {\n\t\t\ts.log.Debugf(\"Clock skew vs provider: %v\", skew)\n\t\t}\n\t}\n\treturn isConnected\n}\n\nfunc (s *Session) worker() {\n\tconst maxDuration = math.MaxInt64\n\tmRng := rand.NewMath()\n\t\/\/ The PKI doc should be cached since we've\n\t\/\/ already waited until we received it.\n\tdoc := s.minclient.CurrentDocument()\n\tif doc == nil {\n\t\ts.fatalErrCh <- errors.New(\"aborting, PKI doc is nil\")\n\t\treturn\n\t}\n\n\t\/\/ get the initial loop services if decoy traffic is enabled\n\tvar loopServices []utils.ServiceDescriptor\n\tif !s.cfg.Debug.DisableDecoyTraffic {\n\t\tloopServices = utils.FindServices(cConstants.LoopService, doc)\n\t\tif len(loopServices) == 0 {\n\t\t\ts.fatalErrCh <- errors.New(\"failure to get loop service\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ LambdaP timer setup\n\tlambdaP := doc.LambdaP\n\tlambdaPMsec := uint64(rand.Exp(mRng, lambdaP))\n\tif lambdaPMsec > doc.LambdaPMaxDelay {\n\t\tlambdaPMsec = doc.LambdaPMaxDelay\n\t}\n\tlambdaPInterval := time.Duration(lambdaPMsec) * time.Millisecond\n\tlambdaPTimer := time.NewTimer(lambdaPInterval)\n\tdefer lambdaPTimer.Stop()\n\n\t\/\/ LambdaL timer setup\n\tlambdaL := doc.LambdaL\n\tlambdaLMsec := uint64(rand.Exp(mRng, lambdaL))\n\tif lambdaLMsec > doc.LambdaLMaxDelay {\n\t\tlambdaLMsec = doc.LambdaLMaxDelay\n\t}\n\tlambdaLInterval := time.Duration(lambdaLMsec) * time.Millisecond\n\tlambdaLTimer := time.NewTimer(lambdaLInterval)\n\tdefer lambdaLTimer.Stop()\n\n\t\/\/ LambdaD timer setup\n\tlambdaD := doc.LambdaD\n\tlambdaDMsec := uint64(rand.Exp(mRng, lambdaD))\n\tif lambdaDMsec > doc.LambdaDMaxDelay {\n\t\tlambdaDMsec = doc.LambdaDMaxDelay\n\t}\n\tlambdaDInterval := time.Duration(lambdaDMsec) * time.Millisecond\n\tlambdaDTimer := time.NewTimer(lambdaDInterval)\n\tdefer lambdaDTimer.Stop()\n\n\tdefer s.log.Debug(\"session worker halted\")\n\n\tisConnected := false\n\tmustResetAllTimers := false\n\tfor {\n\t\tvar lambdaPFired bool\n\t\tvar lambdaLFired bool\n\t\tvar lambdaDFired bool\n\t\tvar loopSvc *utils.ServiceDescriptor\n\t\tvar qo workerOp\n\n\t\tselect {\n\t\tcase <-s.HaltCh():\n\t\t\ts.log.Debugf(\"Session worker terminating gracefully.\")\n\t\t\treturn\n\t\tcase <-lambdaPTimer.C:\n\t\t\tlambdaPFired = true\n\t\tcase <-lambdaLTimer.C:\n\t\t\tlambdaLFired = true\n\t\tcase <-lambdaDTimer.C:\n\t\t\tlambdaDFired = true\n\t\tcase qo = <-s.opCh:\n\t\t}\n\n\t\tif qo != nil {\n\t\t\tswitch op := qo.(type) {\n\t\t\tcase opConnStatusChanged:\n\t\t\t\tnewConnectedStatus := s.connStatusChange(op)\n\t\t\t\tisConnected = newConnectedStatus\n\t\t\t\tmustResetAllTimers = true\n\t\t\tcase opNewDocument:\n\t\t\t\terr := s.isDocValid(op.doc)\n\t\t\t\tif err != nil {\n\t\t\t\t\ts.fatalErrCh <- err\n\t\t\t\t}\n\n\t\t\t\tdoc = op.doc\n\t\t\t\ts.setPollIntervalFromDoc(doc)\n\t\t\t\tlambdaP = doc.LambdaP\n\t\t\t\tlambdaL = doc.LambdaL\n\t\t\t\tlambdaD = doc.LambdaD\n\n\t\t\t\t\/\/ update the loop service descriptors\n\t\t\t\tloopServices = utils.FindServices(cConstants.LoopService, doc)\n\t\t\t\tif len(loopServices) == 0 {\n\t\t\t\t\ts.fatalErrCh <- errors.New(\"failure to get loop service\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tmustResetAllTimers = true\n\t\t\tdefault:\n\t\t\t\ts.log.Warningf(\"BUG: Worker received nonsensical op: %T\", op)\n\t\t\t} \/\/ end of switch\n\t\t} else {\n\t\t\tif isConnected {\n\t\t\t\t\/\/ select a loop service endpoint\n\t\t\t\tif !s.cfg.Debug.DisableDecoyTraffic {\n\t\t\t\t\tloopSvc = &loopServices[mrand.Intn(len(loopServices))]\n\t\t\t\t}\n\t\t\t\tif lambdaPFired {\n\t\t\t\t\ts.sendFromQueueOrDecoy(loopSvc)\n\t\t\t\t} else if lambdaLFired && !s.cfg.Debug.DisableDecoyTraffic {\n\t\t\t\t\ts.sendLoopDecoy(loopSvc)\n\t\t\t\t} else if lambdaDFired && !s.cfg.Debug.DisableDecoyTraffic {\n\t\t\t\t\ts.sendDropDecoy(loopSvc)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif isConnected {\n\t\t\tlambdaPMsec := uint64(rand.Exp(mRng, lambdaP))\n\t\t\tif lambdaPMsec > doc.LambdaPMaxDelay {\n\t\t\t\tlambdaPMsec = doc.LambdaPMaxDelay\n\t\t\t}\n\t\t\tlambdaPInterval = time.Duration(lambdaPMsec) * time.Millisecond\n\t\t\tlambdaLMsec := uint64(rand.Exp(mRng, lambdaL))\n\t\t\tif lambdaLMsec > doc.LambdaLMaxDelay {\n\t\t\t\tlambdaLMsec = doc.LambdaLMaxDelay\n\t\t\t}\n\t\t\tlambdaLInterval = time.Duration(lambdaLMsec) * time.Millisecond\n\t\t\tlambdaDMsec := uint64(rand.Exp(mRng, lambdaD))\n\t\t\tif lambdaDMsec > doc.LambdaDMaxDelay {\n\t\t\t\tlambdaDMsec = doc.LambdaDMaxDelay\n\t\t\t}\n\t\t\tlambdaDInterval = time.Duration(lambdaDMsec) * time.Millisecond\n\t\t} else {\n\t\t\tlambdaLInterval = time.Duration(maxDuration)\n\t\t\tlambdaPInterval = time.Duration(maxDuration)\n\t\t\tlambdaDInterval = time.Duration(maxDuration)\n\t\t}\n\n\t\tif mustResetAllTimers {\n\t\t\tlambdaPTimer.Reset(lambdaPInterval)\n\t\t\tlambdaLTimer.Reset(lambdaLInterval)\n\t\t\tlambdaDTimer.Reset(lambdaDInterval)\n\t\t\tmustResetAllTimers = false\n\t\t} else {\n\t\t\t\/\/ reset only the timer that fired\n\t\t\tif lambdaPFired {\n\t\t\t\tlambdaPTimer.Reset(lambdaPInterval)\n\t\t\t}\n\t\t\tif lambdaLFired {\n\t\t\t\tlambdaLTimer.Reset(lambdaLInterval)\n\t\t\t}\n\t\t\tif lambdaDFired {\n\t\t\t\tlambdaDTimer.Reset(lambdaDInterval)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ NOTREACHED\n}\n\nfunc (s *Session) sendFromQueueOrDecoy(loopSvc *utils.ServiceDescriptor) {\n\t\/\/ Attempt to send user data first, if any exists.\n\t\/\/ Otherwise send a drop decoy message.\n\t_, err := s.egressQueue.Peek()\n\tif err == nil {\n\t\ts.sendNext()\n\t} else if !s.cfg.Debug.DisableDecoyTraffic {\n\t\ts.sendLoopDecoy(loopSvc)\n\t}\n}\n\nfunc (s *Session) isDocValid(doc *pki.Document) error {\n\tfor _, provider := range doc.Providers {\n\t\t_, ok := provider.Kaetzchen[constants.LoopService]\n\t\tif !ok {\n\t\t\treturn errors.New(\"found a Provider which does not have the loop service\")\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *Session) setPollIntervalFromDoc(doc *pki.Document) {\n\tslopFactor := 0.8\n\tpollProviderMsec := time.Duration((1.0 \/ (doc.LambdaP + doc.LambdaL)) * slopFactor * float64(time.Millisecond))\n\ts.log.Debugf(\"onDocument(): setting PollInterval to %s\", pollProviderMsec)\n\ts.minclient.SetPollInterval(pollProviderMsec)\n}\n<|endoftext|>"}
{"text":"<commit_before>package lights\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\n\/\/ WorkerFunc handles incoming string messages returning an error if the\n\/\/ message could not be handled.\ntype WorkerFunc func(message string) error\n\n\/\/ Worker takes care of the common nsq worker tasks that all message\n\/\/ driven agents must carry out. The worker takes care of bootstrapping\n\/\/ the system, and automatically configures nsq according to the current\n\/\/ environment.\ntype Worker struct {\n\tagent string\n}\n\n\/\/ NewWorker creates a new worker ready for configuration. Call Start() on\n\/\/ the worker to begin processing messages. Returns an error if there was a\n\/\/ problem creating the worker. If an ID is provided the worker will use it,\n\/\/ otherwise an ID will automatically be generated using lights.NewID().\nfunc NewWorker(agent string) (*Worker, error) {\n\tw := &Worker{agent: agent}\n\tport := w.agentPort(agent)\n\tif len(port) == 0 {\n\t\treturn nil, errors.New(\"Agent \" + agent + \" not supported\")\n\t}\n\treturn w, nil\n}\n\n\/\/ Start begins processing commands blocking the thread.\nfunc (w *Worker) Start() error {\n\treturn http.ListenAndServe(\":\"+w.agentPort(w.agent), nil)\n}\n\n\/\/ Consumer creates a new API command Consumer for the worker.\nfunc (w *Worker) Consumer(handler WorkerFunc) error {\n\thttp.HandleFunc(\"\/command\", func(resp http.ResponseWriter, r *http.Request) {\n\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\tif w.errorFree(err, resp) {\n\t\t\terr = handler(string(body))\n\t\t\tif w.errorFree(err, resp) {\n\t\t\t\tio.WriteString(resp, \"OK\")\n\t\t\t}\n\t\t}\n\t})\n\treturn nil\n}\n\n\/\/ Send transmits a message to an agent.\nfunc (w *Worker) Send(agent, message string) {\n\turl := \"http:\/\/127.0.0.1:\" + w.agentPort(agent)\n\tlog.Println(\"->\", agent, message)\n\tresp, err := http.Post(url, \"text\/plain\", strings.NewReader(message))\n\tif err != nil {\n\t\tlog.Println(\"Error sending message\", agent, message, err)\n\t} else {\n\t\tresp.Body.Close()\n\t}\n}\n\n\/\/ errorFree will respond correctly to clients when an error occurs.\n\/\/ Returns true if there was an error for easy handling.\nfunc (w *Worker) errorFree(err error, resp http.ResponseWriter) bool {\n\tif err == nil {\n\t\treturn true\n\t}\n\tresp.WriteHeader(http.StatusInternalServerError)\n\tio.WriteString(resp, err.Error())\n\treturn false\n}\n\n\/\/ agentPort looks up the correct port for an agent by name.\nfunc (w *Worker) agentPort(agent string) string {\n\tswitch agent {\n\tcase \"gateway\":\n\t\treturn \"8001\"\n\tcase \"controller\":\n\t\treturn \"8002\"\n\tcase \"gatekeeper\":\n\t\treturn \"8003\"\n\tcase \"scheduler\":\n\t\treturn \"8004\"\n\tcase \"updater\":\n\t\treturn \"8005\"\n\tdefault:\n\t\t\/\/ Default is the gateway agent\n\t\treturn \"\"\n\t}\n}\n<commit_msg>Fix command URL error, greatly expanded debug log output<commit_after>package lights\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\n\/\/ WorkerFunc handles incoming string messages returning an error if the\n\/\/ message could not be handled.\ntype WorkerFunc func(message string) error\n\n\/\/ Worker takes care of the common nsq worker tasks that all message\n\/\/ driven agents must carry out. The worker takes care of bootstrapping\n\/\/ the system, and automatically configures nsq according to the current\n\/\/ environment.\ntype Worker struct {\n\tagent string\n}\n\n\/\/ NewWorker creates a new worker ready for configuration. Call Start() on\n\/\/ the worker to begin processing messages. Returns an error if there was a\n\/\/ problem creating the worker. If an ID is provided the worker will use it,\n\/\/ otherwise an ID will automatically be generated using lights.NewID().\nfunc NewWorker(agent string) (*Worker, error) {\n\tw := &Worker{agent: agent}\n\tport := w.agentPort(agent)\n\tif len(port) == 0 {\n\t\treturn nil, errors.New(\"Agent \" + agent + \" not supported\")\n\t}\n\treturn w, nil\n}\n\n\/\/ Start begins processing commands blocking the thread.\nfunc (w *Worker) Start() error {\n\thost := \":\" + w.agentPort(w.agent)\n\tlog.Println(\"Listening for HTTP API\", host)\n\treturn http.ListenAndServe(host, nil)\n}\n\n\/\/ Consumer creates a new API command Consumer for the worker.\nfunc (w *Worker) Consumer(handler WorkerFunc) error {\n\thttp.HandleFunc(\"\/command\", func(resp http.ResponseWriter, r *http.Request) {\n\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\tlog.Println(\"<-\", string(body))\n\t\tif w.errorFree(err, resp) {\n\t\t\terr = handler(string(body))\n\t\t\tif w.errorFree(err, resp) {\n\t\t\t\tio.WriteString(resp, \"OK\")\n\t\t\t}\n\t\t}\n\t})\n\treturn nil\n}\n\n\/\/ Send transmits a message to an agent.\nfunc (w *Worker) Send(agent, message string) {\n\turl := \"http:\/\/127.0.0.1:\" + w.agentPort(agent) + \"\/command\"\n\tlog.Println(\"->\", agent, message)\n\tresp, err := http.Post(url, \"text\/plain\", strings.NewReader(message))\n\tif err != nil {\n\t\tlog.Println(\"Error sending message\", agent, message, err)\n\t} else {\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error reading response body\", err)\n\t\t} else {\n\t\t\tlog.Println(\"  \", string(body))\n\t\t}\n\t\tresp.Body.Close()\n\t}\n}\n\n\/\/ errorFree will respond correctly to clients when an error occurs.\n\/\/ Returns true if there was an error for easy handling.\nfunc (w *Worker) errorFree(err error, resp http.ResponseWriter) bool {\n\tif err == nil {\n\t\treturn true\n\t}\n\tresp.WriteHeader(http.StatusInternalServerError)\n\tio.WriteString(resp, err.Error())\n\treturn false\n}\n\n\/\/ agentPort looks up the correct port for an agent by name.\nfunc (w *Worker) agentPort(agent string) string {\n\tswitch agent {\n\tcase \"gateway\":\n\t\treturn \"8001\"\n\tcase \"controller\":\n\t\treturn \"8002\"\n\tcase \"gatekeeper\":\n\t\treturn \"8003\"\n\tcase \"scheduler\":\n\t\treturn \"8004\"\n\tcase \"updater\":\n\t\treturn \"8005\"\n\tdefault:\n\t\t\/\/ Default is the gateway agent\n\t\treturn \"\"\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package speed\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/performancecopilot\/speed\/bytebuffer\"\n)\n\n\/\/ byte lengths of different components in an mmv file\nconst (\n\tHeaderLength         = 40\n\tTocLength            = 16\n\tMetricLength         = 104\n\tValueLength          = 32\n\tInstanceLength       = 80\n\tInstanceDomainLength = 32\n\tStringBlockLength    = 256\n)\n\n\/\/ Writer defines the interface of a MMV file writer's properties\ntype Writer interface {\n\tio.Writer\n\tRegistry() Registry \/\/ a writer must contain a registry of metrics and instance domains\n\tStart() error       \/\/ writes an mmv file\n}\n\nfunc mmvFileLocation(name string) (string, error) {\n\tif strings.ContainsRune(name, os.PathSeparator) {\n\t\treturn \"\", errors.New(\"name cannot have path separator\")\n\t}\n\n\ttdir, present := Config[\"PCP_TMP_DIR\"]\n\tvar loc string\n\tif present {\n\t\tloc = path.Join(RootPath, tdir)\n\t} else {\n\t\tloc = os.TempDir()\n\t}\n\n\treturn path.Join(loc, \"mmv\", name), nil\n}\n\n\/\/ PCPClusterIDBitLength is the bit length of the cluster id\n\/\/ for a set of PCP metrics\nconst PCPClusterIDBitLength = 12\n\n\/\/ MMVFlag represents an enumerated type to represent mmv flag values\ntype MMVFlag int\n\n\/\/ values for MMVFlag\nconst (\n\tNoPrefixFlag MMVFlag = 1 << iota\n\tProcessFlag\n\tSentinelFlag\n)\n\n\/\/go:generate stringer -type=MMVFlag\n\n\/\/ PCPWriter implements a writer that can write PCP compatible MMV files\ntype PCPWriter struct {\n\tsync.Mutex\n\tloc       string       \/\/ absolute location of the mmv file\n\tclusterID uint32       \/\/ cluster identifier for the writer\n\tflag      MMVFlag      \/\/ write flag\n\tr         *PCPRegistry \/\/ current registry\n}\n\n\/\/ NewPCPWriter initializes a new PCPWriter object\nfunc NewPCPWriter(name string, flag MMVFlag) (*PCPWriter, error) {\n\tfileLocation, err := mmvFileLocation(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &PCPWriter{\n\t\tloc:       fileLocation,\n\t\tr:         NewPCPRegistry(),\n\t\tclusterID: getHash(name, PCPClusterIDBitLength),\n\t\tflag:      flag,\n\t}, nil\n}\n\n\/\/ Registry returns a writer's registry\nfunc (w *PCPWriter) Registry() Registry {\n\tw.Lock()\n\tdefer w.Unlock()\n\treturn w.r\n}\n\nfunc (w *PCPWriter) tocCount() int {\n\tans := 2\n\n\tif w.Registry().InstanceCount() > 0 {\n\t\tans += 2\n\t}\n\n\treturn ans\n}\n\n\/\/ Length returns the byte length of data in the mmv file written by the current writer\nfunc (w *PCPWriter) Length() int {\n\tw.Lock()\n\tdefer w.Unlock()\n\n\treturn HeaderLength +\n\t\t(w.tocCount() * TocLength) +\n\t\t(w.Registry().InstanceCount() * InstanceLength) +\n\t\t(w.Registry().InstanceDomainCount() * InstanceDomainLength) +\n\t\t(w.Registry().MetricCount() * (MetricLength + ValueLength))\n}\n\nfunc (w *PCPWriter) initializeOffsets() {\n\tindomoffset := HeaderLength + TocLength*w.tocCount()\n\tinstanceoffset := indomoffset + InstanceDomainLength*w.r.InstanceDomainCount()\n\tmetricsoffset := instanceoffset + InstanceLength*w.r.InstanceCount()\n\tvaluesoffset := metricsoffset + MetricLength*w.r.MetricCount()\n\n\tw.r.indomoffset = indomoffset\n\tw.r.instanceoffset = instanceoffset\n\tw.r.metricsoffset = metricsoffset\n\tw.r.valuesoffset = valuesoffset\n\n\tfor _, indom := range w.r.instanceDomains {\n\t\tindom.SetOffset(indomoffset)\n\t\tindom.instanceOffset = instanceoffset\n\t\tindomoffset += InstanceDomainLength\n\n\t\tfor _, i := range indom.instances {\n\t\t\ti.SetOffset(instanceoffset)\n\t\t\tinstanceoffset += InstanceLength\n\t\t}\n\t}\n\n\tfor _, metric := range w.r.metrics {\n\t\tmetric.desc.SetOffset(metricsoffset)\n\t\tmetricsoffset += MetricLength\n\t\tmetric.SetOffset(valuesoffset)\n\t\tvaluesoffset += ValueLength\n\t}\n\n\t\/\/ TODO: string offsets\n}\n\nfunc (w *PCPWriter) writeHeaderBlock(buffer bytebuffer.Buffer) (gen2offset int, generation int64) {\n\t\/\/ tag\n\tbuffer.WriteString(\"MMV\")\n\n\t\/\/ version\n\tbuffer.WriteUint32(1)\n\n\t\/\/ generation\n\tgeneration = time.Now().Unix()\n\tbuffer.WriteInt64(generation)\n\n\tgen2offset = buffer.Pos()\n\n\tbuffer.WriteInt64(0)\n\n\t\/\/ tocCount\n\tbuffer.WriteInt(w.tocCount())\n\n\t\/\/ flag mask\n\tbuffer.WriteInt(int(w.flag))\n\n\t\/\/ process identifier\n\tbuffer.WriteInt(os.Getpid())\n\n\t\/\/ cluster identifier\n\tbuffer.WriteUint32(w.clusterID)\n\n\treturn\n}\n\nfunc (w *PCPWriter) writeTocBlock(buffer bytebuffer.Buffer) {\n\ttocpos := HeaderLength\n\n\t\/\/ instance domains toc\n\tif w.Registry().InstanceDomainCount() > 0 {\n\t\tbuffer.SetPos(tocpos)\n\t\tbuffer.WriteInt(1) \/\/ Instance Domain identifier\n\t\tbuffer.WriteInt(w.Registry().InstanceDomainCount())\n\t\tbuffer.WriteUint64(uint64(w.r.indomoffset))\n\t\ttocpos += TocLength\n\t}\n\n\t\/\/ instances toc\n\tif w.Registry().InstanceCount() > 0 {\n\t\tbuffer.SetPos(tocpos)\n\t\tbuffer.WriteInt(2) \/\/ Instance identifier\n\t\tbuffer.WriteInt(w.Registry().InstanceCount())\n\t\tbuffer.WriteUint64(uint64(w.r.instanceoffset))\n\t\ttocpos += TocLength\n\t}\n\n\tmetricsoffset, valuesoffset := w.r.metricsoffset, w.r.valuesoffset\n\tif w.Registry().MetricCount() == 0 {\n\t\tmetricsoffset, valuesoffset = 0, 0\n\t}\n\n\t\/\/ metrics and values toc\n\tbuffer.SetPos(tocpos)\n\tbuffer.WriteInt(3) \/\/ Metrics identifier\n\tbuffer.WriteInt(w.Registry().MetricCount())\n\tbuffer.WriteUint64(uint64(metricsoffset))\n\ttocpos += TocLength\n\n\tbuffer.SetPos(tocpos)\n\tbuffer.WriteInt(4) \/\/ Values identifier\n\tbuffer.WriteInt(w.Registry().MetricCount())\n\tbuffer.WriteUint64(uint64(valuesoffset))\n\ttocpos += TocLength\n\n\t\/\/ TODO: strings toc\n}\n\nfunc (w *PCPWriter) writeInstanceAndInstanceDomainBlock(buffer bytebuffer.Buffer) {\n\tfor _, indom := range w.r.instanceDomains {\n\t\tbuffer.SetPos(indom.Offset())\n\t\tbuffer.WriteUint32(indom.ID())\n\t\tbuffer.WriteInt(indom.InstanceCount())\n\t\tbuffer.WriteInt64(int64(indom.instanceOffset))\n\t\t\/\/ TODO: write indom string descriptions offsets\n\n\t\tfor _, i := range indom.instances {\n\t\t\tbuffer.SetPos(i.Offset())\n\t\t\tbuffer.WriteInt64(int64(indom.Offset()))\n\t\t\tbuffer.WriteInt(0)\n\t\t\tbuffer.WriteUint32(i.id)\n\t\t\tbuffer.WriteString(i.name)\n\t\t}\n\t}\n}\n\nconst (\n\tMetricNameLimit = 63\n\tDataValueLength = 16\n)\n\nfunc (w *PCPWriter) writeMetricDesc(desc *MetricDesc, buffer bytebuffer.Buffer) {\n\tpos := desc.Offset()\n\tbuffer.SetPos(pos)\n\n\tbuffer.WriteString(desc.name)\n\tbuffer.Write([]byte{0})\n\tbuffer.SetPos(pos + MetricNameLimit + 1)\n\tbuffer.WriteUint32(desc.id)\n\tbuffer.WriteInt32(int32(desc.t))\n\tbuffer.WriteInt32(int32(desc.sem))\n\tbuffer.WriteInt32(int32(desc.u)) \/\/ TODO: fix this\n\tif desc.indom != nil {\n\t\tbuffer.WriteUint32(desc.indom.ID())\n\t} else {\n\t\tbuffer.WriteInt32(-1)\n\t}\n\tbuffer.WriteInt(0)\n\t\/\/ TODO: write string descriptions\n}\n\nfunc (w *PCPWriter) writeMetricVal(m *PCPMetric, buffer bytebuffer.Buffer) {\n\tpos := m.Offset()\n\tbuffer.SetPos(pos)\n\n\tswitch m.desc.t {\n\tcase Int32Type:\n\t\tbuffer.WriteInt32(m.val.(int32))\n\tcase Int64Type:\n\t\tbuffer.WriteInt64(m.val.(int64))\n\tcase Uint32Type:\n\t\tbuffer.WriteUint32(m.val.(uint32))\n\tcase Uint64Type:\n\t\tbuffer.WriteUint64(m.val.(uint64))\n\t}\n\n\tbuffer.SetPos(pos + DataValueLength)\n\tbuffer.WriteInt64(int64(m.desc.Offset()))\n\tbuffer.WriteInt64(int64(m.desc.indom.(*PCPInstanceDomain).instanceOffset))\n}\n\nfunc (w *PCPWriter) writeMetricsAndValuesBlock(buffer bytebuffer.Buffer) {\n\tfor _, metric := range w.r.metrics {\n\t\tw.writeMetricDesc(metric.desc, buffer)\n\t\tw.writeMetricVal(metric, buffer)\n\t}\n}\n\n\/\/ fillData will fill a byte slice with the mmv file\n\/\/ data as long as something doesn't go wrong\nfunc (w *PCPWriter) fillData(buffer bytebuffer.Buffer) error {\n\tgen2offset, generation := w.writeHeaderBlock(buffer)\n\tw.writeTocBlock(buffer)\n\tw.writeInstanceAndInstanceDomainBlock(buffer)\n\tw.writeMetricsAndValuesBlock(buffer)\n\t\/\/ TODO: write strings block\n\n\tbuffer.SetPos(gen2offset)\n\tbuffer.WriteUint64(uint64(generation))\n\n\treturn nil\n}\n<commit_msg>writer: add Start and Write to write simple files<commit_after>package speed\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/performancecopilot\/speed\/bytebuffer\"\n)\n\n\/\/ byte lengths of different components in an mmv file\nconst (\n\tHeaderLength         = 40\n\tTocLength            = 16\n\tMetricLength         = 104\n\tValueLength          = 32\n\tInstanceLength       = 80\n\tInstanceDomainLength = 32\n\tStringBlockLength    = 256\n)\n\n\/\/ Writer defines the interface of a MMV file writer's properties\ntype Writer interface {\n\tio.Writer\n\tRegistry() Registry \/\/ a writer must contain a registry of metrics and instance domains\n\tStart() error       \/\/ writes an mmv file\n}\n\nfunc mmvFileLocation(name string) (string, error) {\n\tif strings.ContainsRune(name, os.PathSeparator) {\n\t\treturn \"\", errors.New(\"name cannot have path separator\")\n\t}\n\n\ttdir, present := Config[\"PCP_TMP_DIR\"]\n\tvar loc string\n\tif present {\n\t\tloc = path.Join(RootPath, tdir)\n\t} else {\n\t\tloc = os.TempDir()\n\t}\n\n\treturn path.Join(loc, \"mmv\", name), nil\n}\n\n\/\/ PCPClusterIDBitLength is the bit length of the cluster id\n\/\/ for a set of PCP metrics\nconst PCPClusterIDBitLength = 12\n\n\/\/ MMVFlag represents an enumerated type to represent mmv flag values\ntype MMVFlag int\n\n\/\/ values for MMVFlag\nconst (\n\tNoPrefixFlag MMVFlag = 1 << iota\n\tProcessFlag\n\tSentinelFlag\n)\n\n\/\/go:generate stringer -type=MMVFlag\n\n\/\/ PCPWriter implements a writer that can write PCP compatible MMV files\ntype PCPWriter struct {\n\tloc       string       \/\/ absolute location of the mmv file\n\tclusterID uint32       \/\/ cluster identifier for the writer\n\tflag      MMVFlag      \/\/ write flag\n\tr         *PCPRegistry \/\/ current registry\n}\n\n\/\/ NewPCPWriter initializes a new PCPWriter object\nfunc NewPCPWriter(name string, flag MMVFlag) (*PCPWriter, error) {\n\tfileLocation, err := mmvFileLocation(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &PCPWriter{\n\t\tloc:       fileLocation,\n\t\tr:         NewPCPRegistry(),\n\t\tclusterID: getHash(name, PCPClusterIDBitLength),\n\t\tflag:      flag,\n\t}, nil\n}\n\n\/\/ Registry returns a writer's registry\nfunc (w *PCPWriter) Registry() Registry {\n\treturn w.r\n}\n\nfunc (w *PCPWriter) tocCount() int {\n\tans := 2\n\n\tif w.Registry().InstanceCount() > 0 {\n\t\tans += 2\n\t}\n\n\treturn ans\n}\n\n\/\/ Length returns the byte length of data in the mmv file written by the current writer\nfunc (w *PCPWriter) Length() int {\n\treturn HeaderLength +\n\t\t(w.tocCount() * TocLength) +\n\t\t(w.Registry().InstanceCount() * InstanceLength) +\n\t\t(w.Registry().InstanceDomainCount() * InstanceDomainLength) +\n\t\t(w.Registry().MetricCount() * (MetricLength + ValueLength))\n}\n\nfunc (w *PCPWriter) initializeOffsets() {\n\tindomoffset := HeaderLength + TocLength*w.tocCount()\n\tinstanceoffset := indomoffset + InstanceDomainLength*w.r.InstanceDomainCount()\n\tmetricsoffset := instanceoffset + InstanceLength*w.r.InstanceCount()\n\tvaluesoffset := metricsoffset + MetricLength*w.r.MetricCount()\n\n\tw.r.indomoffset = indomoffset\n\tw.r.instanceoffset = instanceoffset\n\tw.r.metricsoffset = metricsoffset\n\tw.r.valuesoffset = valuesoffset\n\n\tfor _, indom := range w.r.instanceDomains {\n\t\tindom.SetOffset(indomoffset)\n\t\tindom.instanceOffset = instanceoffset\n\t\tindomoffset += InstanceDomainLength\n\n\t\tfor _, i := range indom.instances {\n\t\t\ti.SetOffset(instanceoffset)\n\t\t\tinstanceoffset += InstanceLength\n\t\t}\n\t}\n\n\tfor _, metric := range w.r.metrics {\n\t\tmetric.desc.SetOffset(metricsoffset)\n\t\tmetricsoffset += MetricLength\n\t\tmetric.SetOffset(valuesoffset)\n\t\tvaluesoffset += ValueLength\n\t}\n\n\t\/\/ TODO: string offsets\n}\n\nfunc (w *PCPWriter) writeHeaderBlock(buffer bytebuffer.Buffer) (gen2offset int, generation int64) {\n\t\/\/ tag\n\tbuffer.WriteString(\"MMV\")\n\tbuffer.SetPos(buffer.Pos() + 1) \/\/ extra null byte is needed and \\0 isn't a valid escape character in go\n\n\t\/\/ version\n\tbuffer.WriteUint32(1)\n\n\t\/\/ generation\n\tgeneration = time.Now().Unix()\n\tbuffer.WriteInt64(generation)\n\n\tgen2offset = buffer.Pos()\n\n\tbuffer.WriteInt64(0)\n\n\t\/\/ tocCount\n\tbuffer.WriteInt(w.tocCount())\n\n\t\/\/ flag mask\n\tbuffer.WriteInt(int(w.flag))\n\n\t\/\/ process identifier\n\tbuffer.WriteInt(os.Getpid())\n\n\t\/\/ cluster identifier\n\tbuffer.WriteUint32(w.clusterID)\n\n\treturn\n}\n\nfunc (w *PCPWriter) writeTocBlock(buffer bytebuffer.Buffer) {\n\ttocpos := HeaderLength\n\n\t\/\/ instance domains toc\n\tif w.Registry().InstanceDomainCount() > 0 {\n\t\tbuffer.SetPos(tocpos)\n\t\tbuffer.WriteInt(1) \/\/ Instance Domain identifier\n\t\tbuffer.WriteInt(w.Registry().InstanceDomainCount())\n\t\tbuffer.WriteUint64(uint64(w.r.indomoffset))\n\t\ttocpos += TocLength\n\t}\n\n\t\/\/ instances toc\n\tif w.Registry().InstanceCount() > 0 {\n\t\tbuffer.SetPos(tocpos)\n\t\tbuffer.WriteInt(2) \/\/ Instance identifier\n\t\tbuffer.WriteInt(w.Registry().InstanceCount())\n\t\tbuffer.WriteUint64(uint64(w.r.instanceoffset))\n\t\ttocpos += TocLength\n\t}\n\n\tmetricsoffset, valuesoffset := w.r.metricsoffset, w.r.valuesoffset\n\tif w.Registry().MetricCount() == 0 {\n\t\tmetricsoffset, valuesoffset = 0, 0\n\t}\n\n\t\/\/ metrics and values toc\n\tbuffer.SetPos(tocpos)\n\tbuffer.WriteInt(3) \/\/ Metrics identifier\n\tbuffer.WriteInt(w.Registry().MetricCount())\n\tbuffer.WriteUint64(uint64(metricsoffset))\n\ttocpos += TocLength\n\n\tbuffer.SetPos(tocpos)\n\tbuffer.WriteInt(4) \/\/ Values identifier\n\tbuffer.WriteInt(w.Registry().MetricCount())\n\tbuffer.WriteUint64(uint64(valuesoffset))\n\ttocpos += TocLength\n\n\t\/\/ TODO: strings toc\n}\n\nfunc (w *PCPWriter) writeInstanceAndInstanceDomainBlock(buffer bytebuffer.Buffer) {\n\tfor _, indom := range w.r.instanceDomains {\n\t\tbuffer.SetPos(indom.Offset())\n\t\tbuffer.WriteUint32(indom.ID())\n\t\tbuffer.WriteInt(indom.InstanceCount())\n\t\tbuffer.WriteInt64(int64(indom.instanceOffset))\n\t\t\/\/ TODO: write indom string descriptions offsets\n\n\t\tfor _, i := range indom.instances {\n\t\t\tbuffer.SetPos(i.Offset())\n\t\t\tbuffer.WriteInt64(int64(indom.Offset()))\n\t\t\tbuffer.WriteInt(0)\n\t\t\tbuffer.WriteUint32(i.id)\n\t\t\tbuffer.WriteString(i.name)\n\t\t}\n\t}\n}\n\nconst (\n\tMetricNameLimit = 63\n\tDataValueLength = 16\n)\n\nfunc (w *PCPWriter) writeMetricDesc(desc *MetricDesc, buffer bytebuffer.Buffer) {\n\tpos := desc.Offset()\n\tbuffer.SetPos(pos)\n\n\tbuffer.WriteString(desc.name)\n\tbuffer.Write([]byte{0})\n\tbuffer.SetPos(pos + MetricNameLimit + 1)\n\tbuffer.WriteUint32(desc.id)\n\tbuffer.WriteInt32(int32(desc.t))\n\tbuffer.WriteInt32(int32(desc.sem))\n\tbuffer.WriteInt32(int32(desc.u)) \/\/ TODO: fix this\n\tif desc.indom != nil {\n\t\tbuffer.WriteUint32(desc.indom.ID())\n\t} else {\n\t\tbuffer.WriteInt32(-1)\n\t}\n\tbuffer.WriteInt(0)\n\t\/\/ TODO: write string descriptions\n}\n\nfunc (w *PCPWriter) writeMetricVal(m *PCPMetric, buffer bytebuffer.Buffer) {\n\tpos := m.Offset()\n\tbuffer.SetPos(pos)\n\n\tswitch m.desc.t {\n\tcase Int32Type:\n\t\tbuffer.WriteInt32(m.val.(int32))\n\tcase Int64Type:\n\t\tbuffer.WriteInt64(m.val.(int64))\n\tcase Uint32Type:\n\t\tbuffer.WriteUint32(m.val.(uint32))\n\tcase Uint64Type:\n\t\tbuffer.WriteUint64(m.val.(uint64))\n\t}\n\n\tbuffer.SetPos(pos + DataValueLength)\n\tbuffer.WriteInt64(int64(m.desc.Offset()))\n\tbuffer.WriteInt64(int64(m.desc.indom.(*PCPInstanceDomain).instanceOffset))\n}\n\nfunc (w *PCPWriter) writeMetricsAndValuesBlock(buffer bytebuffer.Buffer) {\n\tfor _, metric := range w.r.metrics {\n\t\tw.writeMetricDesc(metric.desc, buffer)\n\t\tw.writeMetricVal(metric, buffer)\n\t}\n}\n\n\/\/ fillData will fill a byte slice with the mmv file\n\/\/ data as long as something doesn't go wrong\nfunc (w *PCPWriter) fillData(buffer bytebuffer.Buffer) error {\n\tgen2offset, generation := w.writeHeaderBlock(buffer)\n\tw.writeTocBlock(buffer)\n\tw.writeInstanceAndInstanceDomainBlock(buffer)\n\tw.writeMetricsAndValuesBlock(buffer)\n\t\/\/ TODO: write strings block\n\n\tbuffer.SetPos(gen2offset)\n\tbuffer.WriteUint64(uint64(generation))\n\n\treturn nil\n}\n\nfunc (w *PCPWriter) Write(data []byte) (int, error) {\n\tf, err := os.Create(w.loc)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn f.Write(data)\n}\n\n\/\/ Start dumps existing registry data\nfunc (w *PCPWriter) Start() {\n\tl := w.Length()\n\n\tw.initializeOffsets()\n\tbuffer := bytebuffer.NewByteBuffer(l)\n\tw.fillData(buffer)\n\n\tw.Write(buffer.Buffer())\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* \nCopyright (c) 2013 Blake Smith <blakesmith0@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\npackage ar\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"strconv\"\n)\n\nvar (\n\tErrWriteTooLong    = errors.New(\"ar: write too long\")\n)\n\n\/\/ Writer provides sequential writing of an ar archive.\n\/\/ An ar archive is sequence of header file pairs\n\/\/ Call WriteHeader to begin writing a new file, then call Write to supply the file's data\n\/\/\n\/\/ Example:\n\/\/ archive := ar.NewWriter(writer)\n\/\/ archive.WriteGlobalHeader()\n\/\/ header := new(ar.Header)\n\/\/ header.Size = 15 \/\/ bytes\n\/\/ if err := archive.WriteHeader(header); err != nil {\n\/\/ \treturn err\n\/\/ }\n\/\/ io.Copy(archive, data)\ntype Writer struct {\n\tw io.Writer\n\tnb int64 \/\/ number of unwritten bytes for the current file entry\n}\n\n\/\/ Create a new ar writer that writes to w\nfunc NewWriter(w io.Writer) *Writer { return &Writer{w: w} }\n\nfunc (aw *Writer) numeric(b []byte, x int64) {\n\ts := strconv.FormatInt(x, 10)\n\tfor len(s) < len(b) {\n\t\ts = s + \" \"\n\t}\n\tcopy(b, []byte(s))\n}\n\nfunc (aw *Writer) octal(b []byte, x int64) {\n\ts := \"100\" + strconv.FormatInt(x, 8)\n\tfor len(s) < len(b) {\n\t\ts = s + \" \"\n\t}\n\tcopy(b, []byte(s))\n}\n\nfunc (aw *Writer) string(b []byte, str string) {\n\ts := str\n\tfor len(s) < len(b) {\n\t\ts = s + \" \"\n\t}\n\tcopy(b, []byte(s))\n}\n\n\/\/ Writes to the current entry in the ar archive\n\/\/ Returns ErrWriteTooLong if more than header.Size\n\/\/ bytes are written after a call to WriteHeader\nfunc (aw *Writer) Write(b []byte) (n int, err error) {\n\tif int64(len(b)) > aw.nb {\n\t\tb = b[0:aw.nb]\n\t\terr = ErrWriteTooLong\n\t}\n\tn, werr := aw.w.Write(b)\n\taw.nb -= int64(n)\n\tif werr != nil {\n\t\treturn n, werr\n\t}\n\n\tif len(b)%2 == 1 { \/\/ data size must be aligned to an even byte\n\t\tn2, _ := aw.w.Write([]byte{'\\n'})\n\t\treturn n+n2, err\n\t}\n\n\treturn\n}\n\nfunc (aw *Writer) WriteGlobalHeader() error {\n\t_, err := aw.w.Write([]byte(GLOBAL_HEADER))\n\treturn err\n}\n\n\/\/ Writes the header to the underlying writer and prepares\n\/\/ to receive the file payload\nfunc (aw *Writer) WriteHeader(hdr *Header) error {\n\taw.nb = int64(hdr.Size)\n\theader := make([]byte, HEADER_BYTE_SIZE)\n\ts := slicer(header)\n\n\taw.string(s.next(16), hdr.Name)\n\taw.numeric(s.next(12), hdr.ModTime.Unix())\n\taw.numeric(s.next(6), int64(hdr.Uid))\n\taw.numeric(s.next(6), int64(hdr.Gid))\n\taw.octal(s.next(8), hdr.Mode)\n\taw.numeric(s.next(10), hdr.Size)\n\taw.string(s.next(2), \"`\\n\")\n\n\t_, err := aw.w.Write(header)\n\n\treturn err\n}\n<commit_msg>Fix for the io.Writer interface.<commit_after>\/*\nCopyright (c) 2013 Blake Smith <blakesmith0@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\npackage ar\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"strconv\"\n)\n\nvar (\n\tErrWriteTooLong = errors.New(\"ar: write too long\")\n)\n\n\/\/ Writer provides sequential writing of an ar archive.\n\/\/ An ar archive is sequence of header file pairs\n\/\/ Call WriteHeader to begin writing a new file, then call Write to supply the file's data\n\/\/\n\/\/ Example:\n\/\/ archive := ar.NewWriter(writer)\n\/\/ archive.WriteGlobalHeader()\n\/\/ header := new(ar.Header)\n\/\/ header.Size = 15 \/\/ bytes\n\/\/ if err := archive.WriteHeader(header); err != nil {\n\/\/ \treturn err\n\/\/ }\n\/\/ io.Copy(archive, data)\ntype Writer struct {\n\tw  io.Writer\n\tnb int64 \/\/ number of unwritten bytes for the current file entry\n}\n\n\/\/ Create a new ar writer that writes to w\nfunc NewWriter(w io.Writer) *Writer { return &Writer{w: w} }\n\nfunc (aw *Writer) numeric(b []byte, x int64) {\n\ts := strconv.FormatInt(x, 10)\n\tfor len(s) < len(b) {\n\t\ts = s + \" \"\n\t}\n\tcopy(b, []byte(s))\n}\n\nfunc (aw *Writer) octal(b []byte, x int64) {\n\ts := \"100\" + strconv.FormatInt(x, 8)\n\tfor len(s) < len(b) {\n\t\ts = s + \" \"\n\t}\n\tcopy(b, []byte(s))\n}\n\nfunc (aw *Writer) string(b []byte, str string) {\n\ts := str\n\tfor len(s) < len(b) {\n\t\ts = s + \" \"\n\t}\n\tcopy(b, []byte(s))\n}\n\n\/\/ Writes to the current entry in the ar archive\n\/\/ Returns ErrWriteTooLong if more than header.Size\n\/\/ bytes are written after a call to WriteHeader\nfunc (aw *Writer) Write(b []byte) (n int, err error) {\n\tif int64(len(b)) > aw.nb {\n\t\tb = b[0:aw.nb]\n\t\terr = ErrWriteTooLong\n\t}\n\tn, werr := aw.w.Write(b)\n\taw.nb -= int64(n)\n\tif werr != nil {\n\t\treturn n, werr\n\t}\n\n\tif len(b)%2 == 1 { \/\/ data size must be aligned to an even byte\n\t\tif _, err := aw.w.Write([]byte{'\\n'}); err != nil {\n\t\t\t\/\/ Return n although we actually wrote n+1 bytes.\n\t\t\t\/\/ This is to make io.Copy() to work correctly.\n\t\t\treturn n, err\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (aw *Writer) WriteGlobalHeader() error {\n\t_, err := aw.w.Write([]byte(GLOBAL_HEADER))\n\treturn err\n}\n\n\/\/ Writes the header to the underlying writer and prepares\n\/\/ to receive the file payload\nfunc (aw *Writer) WriteHeader(hdr *Header) error {\n\taw.nb = int64(hdr.Size)\n\theader := make([]byte, HEADER_BYTE_SIZE)\n\ts := slicer(header)\n\n\taw.string(s.next(16), hdr.Name)\n\taw.numeric(s.next(12), hdr.ModTime.Unix())\n\taw.numeric(s.next(6), int64(hdr.Uid))\n\taw.numeric(s.next(6), int64(hdr.Gid))\n\taw.octal(s.next(8), hdr.Mode)\n\taw.numeric(s.next(10), hdr.Size)\n\taw.string(s.next(2), \"`\\n\")\n\n\t_, err := aw.w.Write(header)\n\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"io\"\n\t\"log\"\n)\n\ntype writer struct {\n\twriters []io.Writer\n\tWchan   chan string\n}\n\nfunc NewWriter() *writer {\n\twriter := &writer{}\n\twriter.Wchan = make(chan string)\n\n\tgo func() {\n\t\tselect {\n\t\tcase str := <-writer.Wchan:\n\t\t\twriter.write(str)\n\t\t}\n\t}()\n\treturn writer\n}\n\nfunc (w *writer) write(str string) {\n\tlog.Println(\"Writing msg:\", str)\n\tfor _, writer := range w.writers {\n\t\tif _, err := writer.Write([]byte(str)); err != nil {\n\t\t\tlog.Println(\"Could not write str to writer:\", err)\n\t\t}\n\t}\n}\n\nfunc (w *writer) AddWriter(writer io.Writer) {\n\tw.writers = append(w.writers, writer)\n}\n<commit_msg>Don't write empty strings<commit_after>package main\n\nimport (\n\t\"io\"\n\t\"log\"\n)\n\ntype writer struct {\n\twriters []io.Writer\n\tWchan   chan string\n}\n\nfunc NewWriter() *writer {\n\twriter := &writer{}\n\twriter.Wchan = make(chan string)\n\n\tgo func() {\n\t\tselect {\n\t\tcase str := <-writer.Wchan:\n\t\t\twriter.write(str)\n\t\t}\n\t}()\n\treturn writer\n}\n\nfunc (w *writer) write(str string) {\n\tif str == \"\" {\n\t\treturn\n\t}\n\tlog.Println(\"Writing msg:\", str)\n\tfor _, writer := range w.writers {\n\t\tif _, err := writer.Write([]byte(str)); err != nil {\n\t\t\tlog.Println(\"Could not write str to writer:\", err)\n\t\t}\n\t}\n}\n\nfunc (w *writer) AddWriter(writer io.Writer) {\n\tw.writers = append(w.writers, writer)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Mark Nevill. All Rights Reserved.\n\/\/ See LICENSE for licensing terms.\n\npackage http_prometheus\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/mwitkow\/go-httpwares\/tags\"\n)\n\ntype meta struct {\n\tname, handler, method, host, path string\n}\n\nfunc reqMeta(req *http.Request, opts *options, inbound bool) *meta {\n\tm := &meta{name: opts.name}\n\tif m.name == \"\" && inbound {\n\t\tv := http_ctxtags.ExtractInbound(req).Values()[http_ctxtags.TagForCallService]\n\t\tm.name, _ = v.(string)\n\t}\n\tif m.name == \"\" && !inbound {\n\t\tv := http_ctxtags.ExtractOutbound(req).Values()[http_ctxtags.TagForCallService]\n\t\tm.name, _ = v.(string)\n\t}\n\tif inbound {\n\t\tv := http_ctxtags.ExtractInbound(req).Values()[http_ctxtags.TagForHandlerName]\n\t\thname, _ := v.(string)\n\t\tif hname != \"\" {\n\t\t\tv := http_ctxtags.ExtractInbound(req).Values()[http_ctxtags.TagForHandlerGroup]\n\t\t\thgroup, _ := v.(string)\n\t\t\tif hgroup == \"\" {\n\t\t\t\thgroup = \"unknown\"\n\t\t\t}\n\t\t\tm.handler = hgroup + \".\" + hname\n\t\t}\n\t}\n\tif opts.hosts {\n\t\tm.host = req.URL.Host\n\t\tif m.host == \"\" {\n\t\t\tm.host = req.Host\n\t\t}\n\t}\n\tif opts.paths {\n\t\tm.path = req.URL.Path\n\t}\n\treturn m\n}\n<commit_msg>Extract tag-based metric labels for both in and outbound requests. (#28)<commit_after>\/\/ Copyright 2017 Mark Nevill. All Rights Reserved.\n\/\/ See LICENSE for licensing terms.\n\npackage http_prometheus\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/mwitkow\/go-httpwares\/tags\"\n)\n\ntype meta struct {\n\tname, handler, method, host, path string\n}\n\nfunc reqMeta(req *http.Request, opts *options, inbound bool) *meta {\n\tm := &meta{name: opts.name}\n\n\tvar tags map[string]interface{}\n\tif inbound {\n\t\ttags = http_ctxtags.ExtractInbound(req).Values()\n\t} else {\n\t\ttags = http_ctxtags.ExtractOutbound(req).Values()\n\t}\n\tvar v interface{}\n\tif m.name == \"\" {\n\t\tv, _ = tags[http_ctxtags.TagForCallService]\n\t\tm.name, _ = v.(string)\n\t}\n\tv, _ = tags[http_ctxtags.TagForHandlerName]\n\thname, _ := v.(string)\n\tif hname != \"\" {\n\t\tv, _ = tags[http_ctxtags.TagForHandlerGroup]\n\t\thgroup, _ := v.(string)\n\t\tif hgroup == \"\" {\n\t\t\thgroup = \"unknown\"\n\t\t}\n\t\tm.handler = hgroup + \".\" + hname\n\t}\n\n\tif opts.hosts {\n\t\tm.host = req.URL.Host\n\t\tif m.host == \"\" {\n\t\t\tm.host = req.Host\n\t\t}\n\t}\n\tif opts.paths {\n\t\tm.path = req.URL.Path\n\t}\n\treturn m\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2020 The Decred developers\n\/\/ Use of this source code is governed by an ISC\n\/\/ license that can be found in the LICENSE file.\n\npackage secp256k1\n\n\/\/ References:\n\/\/   [SECG]: Recommended Elliptic Curve Domain Parameters\n\/\/     https:\/\/www.secg.org\/sec2-v2.pdf\n\/\/\n\/\/   [GECC]: Guide to Elliptic Curve Cryptography (Hankerson, Menezes, Vanstone)\n\nimport (\n\t\"crypto\/ecdsa\"\n\t\"crypto\/elliptic\"\n\t\"math\/big\"\n\t\"sync\"\n)\n\n\/\/ CurveParams contains the parameters for the secp256k1 curve.\ntype CurveParams struct {\n\t*elliptic.CurveParams\n\tH int \/\/ cofactor of the curve.\n\n\t\/\/ byteSize is simply the bit size \/ 8 and is provided for convenience\n\t\/\/ since it is calculated repeatedly.\n\tbyteSize int\n}\n\n\/\/ Curve parameters taken from [SECG] section 2.4.1.\nvar curveParams = CurveParams{\n\tCurveParams: &elliptic.CurveParams{\n\t\tP:       fromHex(\"fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f\"),\n\t\tN:       fromHex(\"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141\"),\n\t\tB:       fromHex(\"0000000000000000000000000000000000000000000000000000000000000007\"),\n\t\tGx:      fromHex(\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\"),\n\t\tGy:      fromHex(\"483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8\"),\n\t\tBitSize: 256,\n\t},\n\tH: 1,\n\n\t\/\/ Provided for convenience since this gets computed repeatedly.\n\tbyteSize: 256 \/ 8,\n}\n\n\/\/ Params returns the secp256k1 curve parameters for convenience.\nfunc Params() *CurveParams {\n\treturn &curveParams\n}\n\n\/\/ KoblitzCurve provides an implementation for secp256k1 that fits the ECC Curve\n\/\/ interface from crypto\/elliptic.\ntype KoblitzCurve struct {\n\t*CurveParams\n\n\t\/\/ bytePoints\n\tbytePoints *[32][256][3]fieldVal\n}\n\n\/\/ bigAffineToJacobian takes an affine point (x, y) as big integers and converts\n\/\/ it to Jacobian point with Z=1.\nfunc bigAffineToJacobian(x, y *big.Int, result *jacobianPoint) {\n\tresult.x.SetByteSlice(x.Bytes())\n\tresult.y.SetByteSlice(y.Bytes())\n\tresult.z.SetInt(1)\n}\n\n\/\/ jacobianToBigAffine takes a Jacobian point (x, y, z) as field values and\n\/\/ converts it to an affine point as big integers.\nfunc jacobianToBigAffine(point *jacobianPoint) (*big.Int, *big.Int) {\n\tpoint.ToAffine()\n\n\t\/\/ Convert the field values for the now affine point to big.Ints.\n\tx3, y3 := new(big.Int), new(big.Int)\n\tx3.SetBytes(point.x.Bytes()[:])\n\ty3.SetBytes(point.y.Bytes()[:])\n\treturn x3, y3\n}\n\n\/\/ Params returns the parameters for the curve.\n\/\/\n\/\/ This is part of the elliptic.Curve interface implementation.\nfunc (curve *KoblitzCurve) Params() *elliptic.CurveParams {\n\treturn curve.CurveParams.CurveParams\n}\n\n\/\/ IsOnCurve returns whether or not the affine point (x,y) is on the curve.\n\/\/\n\/\/ This is part of the elliptic.Curve interface implementation.  This function\n\/\/ differs from the crypto\/elliptic algorithm since a = 0 not -3.\nfunc (curve *KoblitzCurve) IsOnCurve(x, y *big.Int) bool {\n\t\/\/ Convert big ints to a Jacobian point for faster arithmetic.\n\tvar point jacobianPoint\n\tbigAffineToJacobian(x, y, &point)\n\treturn isOnCurve(&point.x, &point.y)\n}\n\n\/\/ Add returns the sum of (x1,y1) and (x2,y2).\n\/\/\n\/\/ This is part of the elliptic.Curve interface implementation.\nfunc (curve *KoblitzCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) {\n\t\/\/ A point at infinity is the identity according to the group law for\n\t\/\/ elliptic curve cryptography.  Thus, ∞ + P = P and P + ∞ = P.\n\tif x1.Sign() == 0 && y1.Sign() == 0 {\n\t\treturn x2, y2\n\t}\n\tif x2.Sign() == 0 && y2.Sign() == 0 {\n\t\treturn x1, y1\n\t}\n\n\t\/\/ Convert the affine coordinates from big integers to Jacobian points,\n\t\/\/ do the point addition in Jacobian projective space, and convert the\n\t\/\/ Jacobian point back to affine big.Ints.\n\tvar p1, p2, result jacobianPoint\n\tbigAffineToJacobian(x1, y1, &p1)\n\tbigAffineToJacobian(x2, y2, &p2)\n\taddJacobian(&p1, &p2, &result)\n\treturn jacobianToBigAffine(&result)\n}\n\n\/\/ Double returns 2*(x1,y1).\n\/\/\n\/\/ This is part of the elliptic.Curve interface implementation.\nfunc (curve *KoblitzCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) {\n\tif y1.Sign() == 0 {\n\t\treturn new(big.Int), new(big.Int)\n\t}\n\n\t\/\/ Convert the affine coordinates from big integers to Jacobian points,\n\t\/\/ do the point doubling in Jacobian projective space, and convert the\n\t\/\/ Jacobian point back to affine big.Ints.\n\tvar point, result jacobianPoint\n\tbigAffineToJacobian(x1, y1, &point)\n\tdoubleJacobian(&point, &result)\n\treturn jacobianToBigAffine(&result)\n}\n\n\/\/ moduloReduce reduces k from more than 32 bytes to 32 bytes and under.  This\n\/\/ is done by doing a simple modulo curve.N.  We can do this since G^N = 1 and\n\/\/ thus any other valid point on the elliptic curve has the same order.\nfunc moduloReduce(k []byte) []byte {\n\t\/\/ Since the order of G is curve.N, we can use a much smaller number by\n\t\/\/ doing modulo curve.N\n\tif len(k) > curveParams.byteSize {\n\t\ttmpK := new(big.Int).SetBytes(k)\n\t\ttmpK.Mod(tmpK, curveParams.N)\n\t\treturn tmpK.Bytes()\n\t}\n\n\treturn k\n}\n\n\/\/ ScalarMult returns k*(Bx, By) where k is a big endian integer.\n\/\/\n\/\/ This is part of the elliptic.Curve interface implementation.\nfunc (curve *KoblitzCurve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) {\n\t\/\/ Convert the affine coordinates from big integers to Jacobian points,\n\t\/\/ do the multiplication in Jacobian projective space, and convert the\n\t\/\/ Jacobian point back to affine big.Ints.\n\tvar kModN ModNScalar\n\tkModN.SetByteSlice(moduloReduce(k))\n\tvar point, result jacobianPoint\n\tbigAffineToJacobian(Bx, By, &point)\n\tscalarMultJacobian(&kModN, &point, &result)\n\treturn jacobianToBigAffine(&result)\n}\n\n\/\/ ScalarBaseMult returns k*G where G is the base point of the group and k is a\n\/\/ big endian integer.\n\/\/\n\/\/ This is part of the elliptic.Curve interface implementation.\nfunc (curve *KoblitzCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) {\n\t\/\/ Perform the multiplication and convert the Jacobian point back to affine\n\t\/\/ big.Ints.\n\tvar kModN ModNScalar\n\tkModN.SetByteSlice(moduloReduce(k))\n\tvar result jacobianPoint\n\tscalarBaseMultJacobian(&kModN, &result)\n\treturn jacobianToBigAffine(&result)\n}\n\n\/\/ ToECDSA returns the public key as a *ecdsa.PublicKey.\nfunc (p PublicKey) ToECDSA() *ecdsa.PublicKey {\n\treturn &ecdsa.PublicKey{\n\t\tCurve: S256(),\n\t\tX:     p.x,\n\t\tY:     p.y,\n\t}\n}\n\n\/\/ ToECDSA returns the private key as a *ecdsa.PrivateKey.\nfunc (p *PrivateKey) ToECDSA() *ecdsa.PrivateKey {\n\tprivKeyBytes := p.key.Bytes()\n\tvar result jacobianPoint\n\tscalarBaseMultJacobian(&p.key, &result)\n\tx, y := jacobianToBigAffine(&result)\n\tnewPrivKey := &ecdsa.PrivateKey{\n\t\tPublicKey: ecdsa.PublicKey{\n\t\t\tCurve: S256(),\n\t\t\tX:     x,\n\t\t\tY:     y,\n\t\t},\n\t\tD: new(big.Int).SetBytes(privKeyBytes[:]),\n\t}\n\tzeroArray32(&privKeyBytes)\n\treturn newPrivKey\n}\n\n\/\/ fromHex converts the passed hex string into a big integer pointer and will\n\/\/ panic is there is an error.  This is only provided for the hard-coded\n\/\/ constants so errors in the source code can bet detected. It will only (and\n\/\/ must only) be called for initialization purposes.\nfunc fromHex(s string) *big.Int {\n\tr, ok := new(big.Int).SetString(s, 16)\n\tif !ok {\n\t\tpanic(\"invalid hex in source file: \" + s)\n\t}\n\treturn r\n}\n\nvar initonce sync.Once\nvar secp256k1 KoblitzCurve\n\nfunc initAll() {\n\tinitS256()\n}\n\nfunc initS256() {\n\tsecp256k1.CurveParams = &curveParams\n\n\t\/\/ Deserialize and set the pre-computed table used to accelerate scalar\n\t\/\/ base multiplication.  This is hard-coded data, so any errors are\n\t\/\/ panics because it means something is wrong in the source code.\n\tif err := loadBytePoints(); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ S256 returns a Curve which implements secp256k1.\nfunc S256() *KoblitzCurve {\n\tinitonce.Do(initAll)\n\treturn &secp256k1\n}\n<commit_msg>secp256k1: Improve exported curve params.<commit_after>\/\/ Copyright 2020 The Decred developers\n\/\/ Use of this source code is governed by an ISC\n\/\/ license that can be found in the LICENSE file.\n\npackage secp256k1\n\n\/\/ References:\n\/\/   [SECG]: Recommended Elliptic Curve Domain Parameters\n\/\/     https:\/\/www.secg.org\/sec2-v2.pdf\n\/\/\n\/\/   [GECC]: Guide to Elliptic Curve Cryptography (Hankerson, Menezes, Vanstone)\n\nimport (\n\t\"crypto\/ecdsa\"\n\t\"crypto\/elliptic\"\n\t\"math\/big\"\n\t\"sync\"\n)\n\n\/\/ CurveParams contains the parameters for the secp256k1 curve.\ntype CurveParams struct {\n\t\/\/ P is the prime used in the secp256k1 field.\n\tP *big.Int\n\n\t\/\/ N is the order of the secp256k1 curve group generated by the base point.\n\tN *big.Int\n\n\t\/\/ Gx and Gy are the x and y coordinate of the base point, respectively.\n\tGx, Gy *big.Int\n\n\t\/\/ BitSize is the size of the underlying secp256k1 field in bits.\n\tBitSize int\n\n\t\/\/ H is the cofactor of the secp256k1 curve.\n\tH int\n\n\t\/\/ ByteSize is simply the bit size \/ 8 and is provided for convenience\n\t\/\/ since it is calculated repeatedly.\n\tByteSize int\n}\n\n\/\/ Curve parameters taken from [SECG] section 2.4.1.\nvar curveParams = CurveParams{\n\tP:        fromHex(\"fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f\"),\n\tN:        fromHex(\"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141\"),\n\tGx:       fromHex(\"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798\"),\n\tGy:       fromHex(\"483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8\"),\n\tBitSize:  256,\n\tH:        1,\n\tByteSize: 256 \/ 8,\n}\n\n\/\/ Params returns the secp256k1 curve parameters for convenience.\nfunc Params() *CurveParams {\n\treturn &curveParams\n}\n\n\/\/ KoblitzCurve provides an implementation for secp256k1 that fits the ECC Curve\n\/\/ interface from crypto\/elliptic.\ntype KoblitzCurve struct {\n\t*elliptic.CurveParams\n\n\t\/\/ bytePoints\n\tbytePoints *[32][256][3]fieldVal\n}\n\n\/\/ bigAffineToJacobian takes an affine point (x, y) as big integers and converts\n\/\/ it to Jacobian point with Z=1.\nfunc bigAffineToJacobian(x, y *big.Int, result *jacobianPoint) {\n\tresult.x.SetByteSlice(x.Bytes())\n\tresult.y.SetByteSlice(y.Bytes())\n\tresult.z.SetInt(1)\n}\n\n\/\/ jacobianToBigAffine takes a Jacobian point (x, y, z) as field values and\n\/\/ converts it to an affine point as big integers.\nfunc jacobianToBigAffine(point *jacobianPoint) (*big.Int, *big.Int) {\n\tpoint.ToAffine()\n\n\t\/\/ Convert the field values for the now affine point to big.Ints.\n\tx3, y3 := new(big.Int), new(big.Int)\n\tx3.SetBytes(point.x.Bytes()[:])\n\ty3.SetBytes(point.y.Bytes()[:])\n\treturn x3, y3\n}\n\n\/\/ Params returns the parameters for the curve.\n\/\/\n\/\/ This is part of the elliptic.Curve interface implementation.\nfunc (curve *KoblitzCurve) Params() *elliptic.CurveParams {\n\treturn curve.CurveParams\n}\n\n\/\/ IsOnCurve returns whether or not the affine point (x,y) is on the curve.\n\/\/\n\/\/ This is part of the elliptic.Curve interface implementation.  This function\n\/\/ differs from the crypto\/elliptic algorithm since a = 0 not -3.\nfunc (curve *KoblitzCurve) IsOnCurve(x, y *big.Int) bool {\n\t\/\/ Convert big ints to a Jacobian point for faster arithmetic.\n\tvar point jacobianPoint\n\tbigAffineToJacobian(x, y, &point)\n\treturn isOnCurve(&point.x, &point.y)\n}\n\n\/\/ Add returns the sum of (x1,y1) and (x2,y2).\n\/\/\n\/\/ This is part of the elliptic.Curve interface implementation.\nfunc (curve *KoblitzCurve) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) {\n\t\/\/ A point at infinity is the identity according to the group law for\n\t\/\/ elliptic curve cryptography.  Thus, ∞ + P = P and P + ∞ = P.\n\tif x1.Sign() == 0 && y1.Sign() == 0 {\n\t\treturn x2, y2\n\t}\n\tif x2.Sign() == 0 && y2.Sign() == 0 {\n\t\treturn x1, y1\n\t}\n\n\t\/\/ Convert the affine coordinates from big integers to Jacobian points,\n\t\/\/ do the point addition in Jacobian projective space, and convert the\n\t\/\/ Jacobian point back to affine big.Ints.\n\tvar p1, p2, result jacobianPoint\n\tbigAffineToJacobian(x1, y1, &p1)\n\tbigAffineToJacobian(x2, y2, &p2)\n\taddJacobian(&p1, &p2, &result)\n\treturn jacobianToBigAffine(&result)\n}\n\n\/\/ Double returns 2*(x1,y1).\n\/\/\n\/\/ This is part of the elliptic.Curve interface implementation.\nfunc (curve *KoblitzCurve) Double(x1, y1 *big.Int) (*big.Int, *big.Int) {\n\tif y1.Sign() == 0 {\n\t\treturn new(big.Int), new(big.Int)\n\t}\n\n\t\/\/ Convert the affine coordinates from big integers to Jacobian points,\n\t\/\/ do the point doubling in Jacobian projective space, and convert the\n\t\/\/ Jacobian point back to affine big.Ints.\n\tvar point, result jacobianPoint\n\tbigAffineToJacobian(x1, y1, &point)\n\tdoubleJacobian(&point, &result)\n\treturn jacobianToBigAffine(&result)\n}\n\n\/\/ moduloReduce reduces k from more than 32 bytes to 32 bytes and under.  This\n\/\/ is done by doing a simple modulo curve.N.  We can do this since G^N = 1 and\n\/\/ thus any other valid point on the elliptic curve has the same order.\nfunc moduloReduce(k []byte) []byte {\n\t\/\/ Since the order of G is curve.N, we can use a much smaller number by\n\t\/\/ doing modulo curve.N\n\tif len(k) > curveParams.ByteSize {\n\t\ttmpK := new(big.Int).SetBytes(k)\n\t\ttmpK.Mod(tmpK, curveParams.N)\n\t\treturn tmpK.Bytes()\n\t}\n\n\treturn k\n}\n\n\/\/ ScalarMult returns k*(Bx, By) where k is a big endian integer.\n\/\/\n\/\/ This is part of the elliptic.Curve interface implementation.\nfunc (curve *KoblitzCurve) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) {\n\t\/\/ Convert the affine coordinates from big integers to Jacobian points,\n\t\/\/ do the multiplication in Jacobian projective space, and convert the\n\t\/\/ Jacobian point back to affine big.Ints.\n\tvar kModN ModNScalar\n\tkModN.SetByteSlice(moduloReduce(k))\n\tvar point, result jacobianPoint\n\tbigAffineToJacobian(Bx, By, &point)\n\tscalarMultJacobian(&kModN, &point, &result)\n\treturn jacobianToBigAffine(&result)\n}\n\n\/\/ ScalarBaseMult returns k*G where G is the base point of the group and k is a\n\/\/ big endian integer.\n\/\/\n\/\/ This is part of the elliptic.Curve interface implementation.\nfunc (curve *KoblitzCurve) ScalarBaseMult(k []byte) (*big.Int, *big.Int) {\n\t\/\/ Perform the multiplication and convert the Jacobian point back to affine\n\t\/\/ big.Ints.\n\tvar kModN ModNScalar\n\tkModN.SetByteSlice(moduloReduce(k))\n\tvar result jacobianPoint\n\tscalarBaseMultJacobian(&kModN, &result)\n\treturn jacobianToBigAffine(&result)\n}\n\n\/\/ ToECDSA returns the public key as a *ecdsa.PublicKey.\nfunc (p PublicKey) ToECDSA() *ecdsa.PublicKey {\n\treturn &ecdsa.PublicKey{\n\t\tCurve: S256(),\n\t\tX:     p.x,\n\t\tY:     p.y,\n\t}\n}\n\n\/\/ ToECDSA returns the private key as a *ecdsa.PrivateKey.\nfunc (p *PrivateKey) ToECDSA() *ecdsa.PrivateKey {\n\tprivKeyBytes := p.key.Bytes()\n\tvar result jacobianPoint\n\tscalarBaseMultJacobian(&p.key, &result)\n\tx, y := jacobianToBigAffine(&result)\n\tnewPrivKey := &ecdsa.PrivateKey{\n\t\tPublicKey: ecdsa.PublicKey{\n\t\t\tCurve: S256(),\n\t\t\tX:     x,\n\t\t\tY:     y,\n\t\t},\n\t\tD: new(big.Int).SetBytes(privKeyBytes[:]),\n\t}\n\tzeroArray32(&privKeyBytes)\n\treturn newPrivKey\n}\n\n\/\/ fromHex converts the passed hex string into a big integer pointer and will\n\/\/ panic is there is an error.  This is only provided for the hard-coded\n\/\/ constants so errors in the source code can bet detected. It will only (and\n\/\/ must only) be called for initialization purposes.\nfunc fromHex(s string) *big.Int {\n\tr, ok := new(big.Int).SetString(s, 16)\n\tif !ok {\n\t\tpanic(\"invalid hex in source file: \" + s)\n\t}\n\treturn r\n}\n\nvar (\n\t\/\/ initonce is used to initialize the global secp256k1 koblitz curve instance\n\t\/\/ dynamically upon first access.\n\tinitonce sync.Once\n\n\t\/\/ secp256k1 is a global instance of the KoblitzCurve implementation which\n\t\/\/ in turn embeds and implements elliptic.CurveParams.\n\tsecp256k1 KoblitzCurve\n)\n\n\/\/ initS256 initializes the global secp256k1 instance that gets returned by the\n\/\/ S256 function which provides access to the fields and methods provided by\n\/\/ elliptic.CurveParms.\nfunc initS256() {\n\t\/\/ Curve parameters taken from [SECG] section 2.4.1.\n\tsecp256k1.CurveParams = &elliptic.CurveParams{\n\t\tP:       curveParams.P,\n\t\tN:       curveParams.N,\n\t\tB:       fromHex(\"0000000000000000000000000000000000000000000000000000000000000007\"),\n\t\tGx:      curveParams.Gx,\n\t\tGy:      curveParams.Gy,\n\t\tBitSize: curveParams.BitSize,\n\t\tName:    \"secp256k1\",\n\t}\n\n\t\/\/ Deserialize and set the pre-computed table used to accelerate scalar\n\t\/\/ base multiplication.  This is hard-coded data, so any errors are\n\t\/\/ panics because it means something is wrong in the source code.\n\tif err := loadBytePoints(); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ S256 returns a Curve which implements secp256k1.\nfunc S256() *KoblitzCurve {\n\tinitonce.Do(initS256)\n\treturn &secp256k1\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 Google Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ Package unimplemented provides a convenience type to stub out unimplemented\n\/\/ gNMI RPCs.\npackage unimplemented\n\nimport (\n\t\"context\"\n\t\"google.golang.org\/grpc\/codes\"\n\t\"google.golang.org\/grpc\"\n\n\tpb \"github.com\/openconfig\/gnmi\/proto\/gnmi\"\n)\n\n\/\/ Server is a type that can be embedded anonymously in a gNMI server to stub\n\/\/ out all RPCs that are not implemented with a proper return code.\ntype Server struct{}\n\n\/\/ Capabilities satisfies the gNMI service definition.\nfunc (*Server) Capabilities(context.Context, *pb.CapabilityRequest) (*pb.CapabilityResponse, error) {\n\treturn nil, grpc.Errorf(codes.Unimplemented, \"Unimplemented\")\n}\n\n\/\/ Get satisfies the gNMI service definition.\nfunc (*Server) Get(context.Context, *pb.GetRequest) (*pb.GetResponse, error) {\n\treturn nil, grpc.Errorf(codes.Unimplemented, \"Unimplemented\")\n}\n\n\/\/ Set satisfies the gNMI service definition.\nfunc (*Server) Set(context.Context, *pb.SetRequest) (*pb.SetResponse, error) {\n\treturn nil, grpc.Errorf(codes.Unimplemented, \"Unimplemented\")\n}\n\n\/\/ Subscribe satisfies the gNMI service defintion.\nfunc (s *Server) Subscribe(stream pb.GNMI_SubscribeServer) error {\n\treturn grpc.Errorf(codes.Unimplemented, \"Unimplemented\")\n}\n<commit_msg>Add an unimplemented gNMI client to use in unit tests<commit_after>\/*\nCopyright 2017 Google Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ Package unimplemented provides a convenience type to stub out unimplemented\n\/\/ gNMI RPCs.\npackage unimplemented\n\nimport (\n\t\"context\"\n\t\"google.golang.org\/grpc\/codes\"\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/status\"\n\n\tpb \"github.com\/openconfig\/gnmi\/proto\/gnmi\"\n)\n\n\/\/ Server is a type that can be embedded anonymously in a gNMI server to stub\n\/\/ out all RPCs that are not implemented with a proper return code.\ntype Server struct{}\n\n\/\/ Capabilities satisfies the gNMI service definition.\nfunc (*Server) Capabilities(context.Context, *pb.CapabilityRequest) (*pb.CapabilityResponse, error) {\n\treturn nil, status.Errorf(codes.Unimplemented, \"Unimplemented\")\n}\n\n\/\/ Get satisfies the gNMI service definition.\nfunc (*Server) Get(context.Context, *pb.GetRequest) (*pb.GetResponse, error) {\n\treturn nil, status.Errorf(codes.Unimplemented, \"Unimplemented\")\n}\n\n\/\/ Set satisfies the gNMI service definition.\nfunc (*Server) Set(context.Context, *pb.SetRequest) (*pb.SetResponse, error) {\n\treturn nil, status.Errorf(codes.Unimplemented, \"Unimplemented\")\n}\n\n\/\/ Subscribe satisfies the gNMI service definition.\nfunc (s *Server) Subscribe(stream pb.GNMI_SubscribeServer) error {\n\treturn status.Errorf(codes.Unimplemented, \"Unimplemented\")\n}\n\n\/\/ Client is a type that can be embedded anonymously in a gNMI client to stub\n\/\/ out all RPCs that are not implemented with a proper return code.\ntype Client struct{}\n\n\/\/ Capabilities satisfies the gNMI client definition.\nfunc (*Client) Capabilities(ctx context.Context, in *pb.CapabilityRequest, opts ...grpc.CallOption) (*pb.CapabilityResponse, error) {\n\treturn nil, status.Errorf(codes.Unimplemented, \"Unimplemented\")\n}\n\n\/\/ Get satisfies the gNMI client definition.\nfunc (*Client) Get(ctx context.Context, in *pb.GetRequest, opts ...grpc.CallOption) (*pb.GetResponse, error) {\n\treturn nil, status.Errorf(codes.Unimplemented, \"Unimplemented\")\n}\n\n\/\/ Set satisfies the gNMI client definition.\nfunc (*Client) Set(ctx context.Context, in *pb.SetRequest, opts ...grpc.CallOption) (*pb.SetResponse, error) {\n\treturn nil, status.Errorf(codes.Unimplemented, \"Unimplemented\")\n}\n\n\/\/ Subscribe satisfies the gNMI client definition.\nfunc (*Client) Subscribe(ctx context.Context, opts ...grpc.CallOption) (pb.GNMI_SubscribeClient, error) {\n\treturn nil, status.Errorf(codes.Unimplemented, \"Unimplemented\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package resize\n\nimport (\n\t\"image\"\n\t\"testing\"\n)\n\nfunc Test_MakeSizeSpec(t *testing.T) {\n\n\tss := MakeSizeSpec(\"100s\")\n\tif ss.IsFull() {\n\t\tt.Error(\"thinks it is full-size\")\n\t}\n\tif !ss.IsSquare() { \n\t\tt.Error(\"not square\") \n\t}\n\tif ss.Width() != 100 { \n\t\tt.Error(\"not 100 wide\") \n\t}\n\tif ss.Height() != 100 {\n\t\tt.Error(\"not 100 high\")\n\t}\n\n\tss2 := MakeSizeSpec(\"100w\")\n\tif ss2.IsFull() {\n\t\tt.Error(\"thinks it is full-size\")\n\t}\n\tif ss2.IsSquare() { \n\t\tt.Error(\"think's it is square\") \n\t}\n\tif ss2.Width() != 100 { \n\t\tt.Error(\"not 100 wide\") \n\t}\n\tif ss2.Height() != -1 {\n\t\tt.Error(\"not -1 high\")\n\t}\n\n\tss3 := MakeSizeSpec(\"100h\")\n\tif ss3.IsFull() {\n\t\tt.Error(\"thinks it is full-size\")\n\t}\n\tif ss3.IsSquare() { \n\t\tt.Error(\"think's it is square\") \n\t}\n\tif ss3.Width() != -1 { \n\t\tt.Error(\"not -1 wide\") \n\t}\n\tif ss3.Height() != 100 {\n\t\tt.Error(\"not 100 high\")\n\t}\n\n\tss4 := MakeSizeSpec(\"100h200w\")\n\tif ss4.IsFull() {\n\t\tt.Error(\"thinks it is full-size\")\n\t}\n\tif ss4.IsSquare() { \n\t\tt.Error(\"think's it is square\") \n\t}\n\tif ss4.Width() != 200 { \n\t\tt.Error(\"not 200 wide\") \n\t}\n\tif ss4.Height() != 100 {\n\t\tt.Error(\"not 100 high\")\n\t}\n\n\tss5 := MakeSizeSpec(\"100w200h\")\n\tif ss5.IsFull() {\n\t\tt.Error(\"thinks it is full-size\")\n\t}\n\tif ss5.IsSquare() { \n\t\tt.Error(\"think's it is square\") \n\t}\n\tif ss5.Width() != 100 { \n\t\tt.Error(\"not 100 wide\") \n\t}\n\tif ss5.Height() != 200 {\n\t\tt.Error(\"not 200 high\")\n\t}\n\n\tss6 := MakeSizeSpec(\"full\")\n\tif !ss6.IsFull() {\n\t\tt.Error(\"not full-size\")\n\t}\n\tif ss6.IsSquare() { \n\t\tt.Error(\"not square\") \n\t}\n\tif ss6.Width() != -1 { \n\t\tt.Error(\"width set on full\") \n\t}\n\tif ss6.Height() != -1 {\n\t\tt.Error(\"height set on full\")\n\t}\n\n}\n\nfunc Test_ToRect(t *testing.T) {\n\tfull_sized := MakeSizeSpec(\"full\")\n\tsquare_sized := MakeSizeSpec(\"100s\")\n\twidth_constrained := MakeSizeSpec(\"100w\")\n\theight_constrained := MakeSizeSpec(\"100h\")\n\theight_and_width_constrained_wh := MakeSizeSpec(\"200w100h\")\n\theight_and_width_constrained_hw := MakeSizeSpec(\"200h100w\")\n\twider_than_tall := image.Rect(0,0,1000,500)\n\ttaller_than_wide := image.Rect(0,0,500,1000)\n\tsquare_image := image.Rect(0,0,1000,1000)\n\n\n\t\/\/ full-size should be no-op\n\tresults := full_sized.ToRect(square_image)\n\tif results.Dx() != square_image.Dx() {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results.Dy() != square_image.Dy() {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ square == square\n\tresults2 := square_sized.ToRect(square_image)\n\tif results2.Dx() != square_image.Dx() {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results2.Dy() != square_image.Dy() {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ square != square (wider than taller)\n\tresults3 := square_sized.ToRect(wider_than_tall)\n\tif results3.Dx() != 500 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results3.Dy() != 500 {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ square != square (taller than wider)\n\tresults4 := square_sized.ToRect(taller_than_wide)\n\tif results4.Dx() != 500 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results4.Dy() != 500 {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ width constrained square image\n\tresults5 := width_constrained.ToRect(square_image)\n\tif results5.Dx() != 1000 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results5.Dy() != 1000 {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ width constrained wider than tall\n\tresults6 := width_constrained.ToRect(wider_than_tall)\n\tif results6.Dx() != 1000 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results6.Dy() != 500 {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ width constrained taller than wide\n\tresults7 := width_constrained.ToRect(taller_than_wide)\n\tif results7.Dx() != 500 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results7.Dy() != 1000 {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ height constrained square image\n\tresults8 := height_constrained.ToRect(square_image)\n\tif results8.Dx() != 1000 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results8.Dy() != 1000 {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ height constrained wider than tall\n\tresults9 := height_constrained.ToRect(wider_than_tall)\n\tif results9.Dx() != 1000 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results9.Dy() != 500 {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ height constrained taller than wide\n\tresults10 := height_constrained.ToRect(taller_than_wide)\n\tif results10.Dx() != 500 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results10.Dy() != 1000 {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ height and width constrained (w>h) square\n\tresults11 := height_and_width_constrained_wh.ToRect(square_image)\n\tif results11.Dx() != 1000 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results11.Dy() != 500 {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ height and width constrained (w>h) taller than wide\n\tresults12 := height_and_width_constrained_wh.ToRect(taller_than_wide)\n\tif results12.Dx() != 500 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results12.Dy() != 250 {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ height and width constrained (w>h) wider than tall\n\tresults13 := height_and_width_constrained_wh.ToRect(wider_than_tall)\n\tif results13.Dx() != 500 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results13.Dy() != 1000 {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ height and width constrained (h>w) square\n\tresults14 := height_and_width_constrained_hw.ToRect(square_image)\n\tif results14.Dx() != 500 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results14.Dy() != 1000 {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ height and width constrained (h>w) taller than wide\n\tresults15 := height_and_width_constrained_hw.ToRect(taller_than_wide)\n\tif results15.Dx() != 500 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results15.Dy() != 1000 {\n\t\tt.Error(\"bad height\")\n\t}\n\n\t\/\/ height and width constrained (h>w) wider than tall\n\tresults16 := height_and_width_constrained_hw.ToRect(wider_than_tall)\n\tif results16.Dx() != 500 {\n\t\tt.Error(\"bad width\")\n\t}\n\tif results16.Dy() != 1000 {\n\t\tt.Error(\"bad height\")\n\t}\n\n}\n<commit_msg>more DRY tests<commit_after>package resize\n\nimport (\n\t\"image\"\n\t\"testing\"\n)\n\nfunc Test_MakeSizeSpec(t *testing.T) {\n\n\tss := MakeSizeSpec(\"100s\")\n\tif ss.IsFull() {\n\t\tt.Error(\"thinks it is full-size\")\n\t}\n\tif !ss.IsSquare() { \n\t\tt.Error(\"not square\") \n\t}\n\tif ss.Width() != 100 { \n\t\tt.Error(\"not 100 wide\") \n\t}\n\tif ss.Height() != 100 {\n\t\tt.Error(\"not 100 high\")\n\t}\n\n\tss2 := MakeSizeSpec(\"100w\")\n\tif ss2.IsFull() {\n\t\tt.Error(\"thinks it is full-size\")\n\t}\n\tif ss2.IsSquare() { \n\t\tt.Error(\"think's it is square\") \n\t}\n\tif ss2.Width() != 100 { \n\t\tt.Error(\"not 100 wide\") \n\t}\n\tif ss2.Height() != -1 {\n\t\tt.Error(\"not -1 high\")\n\t}\n\n\tss3 := MakeSizeSpec(\"100h\")\n\tif ss3.IsFull() {\n\t\tt.Error(\"thinks it is full-size\")\n\t}\n\tif ss3.IsSquare() { \n\t\tt.Error(\"think's it is square\") \n\t}\n\tif ss3.Width() != -1 { \n\t\tt.Error(\"not -1 wide\") \n\t}\n\tif ss3.Height() != 100 {\n\t\tt.Error(\"not 100 high\")\n\t}\n\n\tss4 := MakeSizeSpec(\"100h200w\")\n\tif ss4.IsFull() {\n\t\tt.Error(\"thinks it is full-size\")\n\t}\n\tif ss4.IsSquare() { \n\t\tt.Error(\"think's it is square\") \n\t}\n\tif ss4.Width() != 200 { \n\t\tt.Error(\"not 200 wide\") \n\t}\n\tif ss4.Height() != 100 {\n\t\tt.Error(\"not 100 high\")\n\t}\n\n\tss5 := MakeSizeSpec(\"100w200h\")\n\tif ss5.IsFull() {\n\t\tt.Error(\"thinks it is full-size\")\n\t}\n\tif ss5.IsSquare() { \n\t\tt.Error(\"think's it is square\") \n\t}\n\tif ss5.Width() != 100 { \n\t\tt.Error(\"not 100 wide\") \n\t}\n\tif ss5.Height() != 200 {\n\t\tt.Error(\"not 200 high\")\n\t}\n\n\tss6 := MakeSizeSpec(\"full\")\n\tif !ss6.IsFull() {\n\t\tt.Error(\"not full-size\")\n\t}\n\tif ss6.IsSquare() { \n\t\tt.Error(\"not square\") \n\t}\n\tif ss6.Width() != -1 { \n\t\tt.Error(\"width set on full\") \n\t}\n\tif ss6.Height() != -1 {\n\t\tt.Error(\"height set on full\")\n\t}\n\n}\n\ntype toRectTestCase struct {\n\tLabel string\n\tSizeSpec *sizeSpec\n\tRect image.Rectangle\n\tExpectedWidth int\n\tExpectedHeight int\n}\n\nfunc Test_ToRect(t *testing.T) {\n\tfull_sized := MakeSizeSpec(\"full\")\n\tsquare_sized := MakeSizeSpec(\"100s\")\n\twidth_constrained := MakeSizeSpec(\"100w\")\n\theight_constrained := MakeSizeSpec(\"100h\")\n\theight_and_width_constrained_wh := MakeSizeSpec(\"200w100h\")\n\theight_and_width_constrained_hw := MakeSizeSpec(\"200h100w\")\n\twider_than_tall := image.Rect(0,0,1000,500)\n\ttaller_than_wide := image.Rect(0,0,500,1000)\n\tsquare_image := image.Rect(0,0,1000,1000)\n\n\tcases := []toRectTestCase{\n\t\t{\n\t\tLabel: \"full-sized should be no-op\",\n\t\tSizeSpec: full_sized,\n\t\tRect: square_image,\n\t\tExpectedWidth: square_image.Dx(),\n\t\tExpectedHeight: square_image.Dy(),\n\t\t},\n\n\t\t{\n\t\tLabel: \"square == square\",\n\t\tSizeSpec: square_sized,\n\t\tRect: square_image,\n\t\tExpectedWidth: square_image.Dx(),\n\t\tExpectedHeight: square_image.Dy(),\n\t\t},\n\n\t\t{\n\t\tLabel: \"square != square (wider than taller)\",\n\t\tSizeSpec: square_sized,\n\t\tRect: wider_than_tall,\n\t\tExpectedWidth: 500,\n\t\tExpectedHeight: 500,\n\t\t},\n\n\t\t{\n\t\tLabel: \"square != square (taller than wide)\",\n\t\tSizeSpec: square_sized,\n\t\tRect: taller_than_wide,\n\t\tExpectedWidth: 500,\n\t\tExpectedHeight: 500,\n\t\t},\n\n\t\t{\n\t\tLabel: \"width constrained square image\",\n\t\tSizeSpec: width_constrained,\n\t\tRect: square_image,\n\t\tExpectedWidth: 1000,\n\t\tExpectedHeight: 1000,\n\t\t},\n\n\t\t{\n\t\tLabel: \"width constrained wider than tall\",\n\t\tSizeSpec: width_constrained,\n\t\tRect: wider_than_tall,\n\t\tExpectedWidth: 1000,\n\t\tExpectedHeight: 500,\n\t\t},\n\n\t\t{\n\t\tLabel: \"width constrained taller than wide\",\n\t\tSizeSpec: width_constrained,\n\t\tRect: taller_than_wide,\n\t\tExpectedWidth: 500,\n\t\tExpectedHeight: 1000,\n\t\t},\n\n\t\t{\n\t\tLabel: \"height constrained square image\",\n\t\tSizeSpec: height_constrained,\n\t\tRect: square_image,\n\t\tExpectedWidth: 1000,\n\t\tExpectedHeight: 1000,\n\t\t},\n\n\t\t{\n\t\tLabel: \"height constrained wider than tall\",\n\t\tSizeSpec: height_constrained,\n\t\tRect: wider_than_tall,\n\t\tExpectedWidth: 1000,\n\t\tExpectedHeight: 500,\n\t\t},\n\n\t\t{\n\t\tLabel: \"height constrained taller than wide\",\n\t\tSizeSpec: height_constrained,\n\t\tRect: taller_than_wide,\n\t\tExpectedWidth: 500,\n\t\tExpectedHeight: 1000,\n\t\t},\n\n\t\t{\n\t\tLabel: \"height and width constrained (w>h) square\",\n\t\tSizeSpec: height_and_width_constrained_wh,\n\t\tRect: square_image,\n\t\tExpectedWidth: 1000,\n\t\tExpectedHeight: 500,\n\t\t},\n\n\t\t{\n\t\tLabel: \"height and width constrained (w>h) taller than wide\",\n\t\tSizeSpec: height_and_width_constrained_wh,\n\t\tRect: taller_than_wide,\n\t\tExpectedWidth: 500,\n\t\tExpectedHeight: 250,\n\t\t},\n\n\t\t{\n\t\tLabel: \"height and width constrained (w>h) wider than tall\",\n\t\tSizeSpec: height_and_width_constrained_wh,\n\t\tRect: wider_than_tall,\n\t\tExpectedWidth: 500,\n\t\tExpectedHeight: 1000,\n\t\t},\n\n\t\t{\n\t\tLabel: \"height and width constrained (h>w) square\",\n\t\tSizeSpec: height_and_width_constrained_hw,\n\t\tRect: square_image,\n\t\tExpectedWidth: 500,\n\t\tExpectedHeight: 1000,\n\t\t},\n\n\t\t{\n\t\tLabel: \"height and width constrained (h>w) taller than wide\",\n\t\tSizeSpec: height_and_width_constrained_hw,\n\t\tRect: taller_than_wide,\n\t\tExpectedWidth: 500,\n\t\tExpectedHeight: 1000,\n\t\t},\n\n\t\t{\n\t\tLabel: \"height and width constrained (h>w) wider than tall\",\n\t\tSizeSpec: height_and_width_constrained_hw,\n\t\tRect: wider_than_tall,\n\t\tExpectedWidth: 500,\n\t\tExpectedHeight: 1000,\n\t\t},\n\n\t}\n\n\tfor i := range cases {\n\t\tc := cases[i]\n\t\tr := c.SizeSpec.ToRect(c.Rect)\n\t\tif r.Dx() != c.ExpectedWidth {\n\t\t\tt.Error(c.Label, \"-- bad width\",r.Dx(),\" expected\",c.ExpectedWidth)\n\t\t}\n\t\tif r.Dy() != c.ExpectedHeight {\n\t\t\tt.Error(c.Label, \"-- bad height\",r.Dy(),\" expected\",c.ExpectedHeight)\n\t\t}\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package resources\n\nimport (\n    \"github.com\/orc\/db\"\n    \"github.com\/orc\/mvc\/controllers\"\n    \"github.com\/orc\/mvc\/models\"\n    \"io\/ioutil\"\n    \"math\/rand\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nconst USER_COUNT = 20\n\nvar base = new(models.ModelManager)\n\nfunc random(min, max int) int {\n    rand.Seed(int64(time.Now().Second()))\n    return rand.Intn(max-min) + min\n}\n\nfunc addDate(d, m, y int) string {\n    return strconv.Itoa(d) + \"-\" + strconv.Itoa(m) + \"-\" + strconv.Itoa(y)\n}\n\nfunc addTime(h, m, s int) string {\n    return strconv.Itoa(h) + \":\" + strconv.Itoa(m) + \":\" + strconv.Itoa(s)\n}\n\nfunc Load() {\n    loadUsers()\n    loadEvents()\n    loadEventTypes()\n    loadForms()\n    loadParamTypes()\n}\n\nfunc loadUsers() {\n    base := new(controllers.BaseController)\n    for i := 0; i < USER_COUNT; i++ {\n        rand.Seed(int64(i))\n        result, reg_id := base.Handler().HandleRegister_(\"user\"+strconv.Itoa(i), \"secret\"+strconv.Itoa(i), \"user\")\n        if result == \"ok\" {\n            eventsRegs := controllers.GetModel(\"events_regs\")\n            eventsRegs.LoadModelData(map[string]interface{}{\"reg_id\": reg_id, \"event_id\": 1})\n            db.QueryInsert_(eventsRegs, \"\")\n        }\n    }\n    result, reg_id := base.Handler().HandleRegister_(\"admin\", \"password\", \"admin\")\n    if result == \"ok\" {\n        eventsRegs := controllers.GetModel(\"events_regs\")\n        eventsRegs.LoadModelData(map[string]interface{}{\"reg_id\": reg_id, \"event_id\": 1})\n        db.QueryInsert_(eventsRegs, \"\")\n    }\n}\n\nfunc loadEvents() {\n    eventNames, _ := ioutil.ReadFile(\".\/resources\/event-name\")\n    subjectNames, _ := ioutil.ReadFile(\".\/resources\/subject-name\")\n    eventNameSource := strings.Split(string(eventNames), \"\\n\")\n    subjectNameSource := strings.Split(string(subjectNames), \"\\n\")\n    for i := 0; i < len(eventNameSource); i++ {\n        rand.Seed(int64(i))\n        eventName := strings.TrimSpace(eventNameSource[rand.Intn(len(eventNameSource))])\n        eventName += \" по дисциплине \"\n        eventName += \"\\\"\" + strings.TrimSpace(subjectNameSource[rand.Intn(len(subjectNameSource))]) + \"\\\"\"\n        dateStart := addDate(random(1894, 2014), random(1, 12), random(1, 28))\n        dateFinish := addDate(random(1894, 2014), random(1, 12), random(1, 28))\n        time := addTime(random(0, 11), random(1, 60), random(1, 60))\n        params := []interface{}{eventName, dateStart, dateFinish, time, \"\"}\n        entity := base.Events()\n        db.QueryInsert(\"events\", entity.GetColumnSlice(1), params, \"\")\n    }\n}\n\nfunc loadEventTypes() {\n    eventTypeNames, _ := ioutil.ReadFile(\".\/resources\/event-type-name\")\n    eventTypeNamesSourse := strings.Split(string(eventTypeNames), \"\\n\")\n    topicality := []bool{true, false}\n    for i := 0; i < len(eventTypeNamesSourse); i++ {\n        \/\/rand.Seed(int64(i))\n        eventTypeName := strings.TrimSpace(eventTypeNamesSourse[i])\n        params := []interface{}{eventTypeName, \"\", topicality[rand.Intn(2)]}\n        entity := base.EventTypes()\n        db.QueryInsert(\"event_types\", entity.GetColumnSlice(1), params, \"\")\n    }\n}\n\nfunc loadForms() {\n    formNames, _ := ioutil.ReadFile(\".\/resources\/form-name\")\n    formNamesSourse := strings.Split(string(formNames), \"\\n\")\n    for i := 0; i < len(formNamesSourse); i++ {\n        formName := strings.TrimSpace(formNamesSourse[i])\n        entity := base.Forms()\n        db.QueryInsert(\"forms\", entity.GetColumnSlice(1), []interface{}{formName}, \"\")\n    }\n}\n\nfunc loadParamTypes() {\n    paramTypesNames, _ := ioutil.ReadFile(\".\/resources\/param-type-name\")\n    paramTypesSourse := strings.Split(string(paramTypesNames), \"\\n\")\n    for i := 0; i < len(paramTypesSourse); i++ {\n        paramType := strings.TrimSpace(paramTypesSourse[i])\n        entity := base.ParamTypes()\n        db.QueryInsert(\"param_types\", entity.GetColumnSlice(1), []interface{}{paramType}, \"\")\n    }\n}\n<commit_msg>loadData: fix inserts<commit_after>package resources\n\nimport (\n    \"github.com\/orc\/db\"\n    \"github.com\/orc\/mvc\/controllers\"\n    \"github.com\/orc\/mvc\/models\"\n    \"io\/ioutil\"\n    \"math\/rand\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\nconst USER_COUNT = 20\n\nvar base = new(models.ModelManager)\n\nfunc random(min, max int) int {\n    rand.Seed(int64(time.Now().Second()))\n    return rand.Intn(max-min) + min\n}\n\nfunc addDate(d, m, y int) string {\n    return strconv.Itoa(d) + \"-\" + strconv.Itoa(m) + \"-\" + strconv.Itoa(y)\n}\n\nfunc addTime(h, m, s int) string {\n    return strconv.Itoa(h) + \":\" + strconv.Itoa(m) + \":\" + strconv.Itoa(s)\n}\n\nfunc Load() {\n    loadUsers()\n    loadEvents()\n    loadEventTypes()\n    loadForms()\n    loadParamTypes()\n}\n\nfunc loadUsers() {\n    base := new(controllers.BaseController)\n    for i := 0; i < USER_COUNT; i++ {\n        rand.Seed(int64(i))\n        result, reg_id := base.Handler().HandleRegister_(\"user\"+strconv.Itoa(i), \"secret\"+strconv.Itoa(i), \"user\")\n        if result == \"ok\" {\n            eventsRegs := controllers.GetModel(\"events_regs\")\n            eventsRegs.LoadModelData(map[string]interface{}{\"reg_id\": reg_id, \"event_id\": 1})\n            db.QueryInsert_(eventsRegs, \"\")\n        }\n    }\n    result, reg_id := base.Handler().HandleRegister_(\"admin\", \"password\", \"admin\")\n    if result == \"ok\" {\n        eventsRegs := controllers.GetModel(\"events_regs\")\n        eventsRegs.LoadModelData(map[string]interface{}{\"reg_id\": reg_id, \"event_id\": 1})\n        db.QueryInsert_(eventsRegs, \"\")\n    }\n}\n\nfunc loadEvents() {\n    eventNames, _ := ioutil.ReadFile(\".\/resources\/event-name\")\n    subjectNames, _ := ioutil.ReadFile(\".\/resources\/subject-name\")\n    eventNameSource := strings.Split(string(eventNames), \"\\n\")\n    subjectNameSource := strings.Split(string(subjectNames), \"\\n\")\n    for i := 0; i < len(eventNameSource); i++ {\n        rand.Seed(int64(i))\n        eventName := strings.TrimSpace(eventNameSource[rand.Intn(len(eventNameSource))])\n        eventName += \" по дисциплине \"\n        eventName += \"\\\"\" + strings.TrimSpace(subjectNameSource[rand.Intn(len(subjectNameSource))]) + \"\\\"\"\n        dateStart := addDate(random(1894, 2014), random(1, 12), random(1, 28))\n        dateFinish := addDate(random(1894, 2014), random(1, 12), random(1, 28))\n        time := addTime(random(0, 11), random(1, 60), random(1, 60))\n        params := map[string]interface{}{\"name\": eventName, \"data_start\": dateStart, \"date_finish\": dateFinish, \"time\": time, \"url\": \"\"}\n        entity := base.Events()\n        entity.LoadModelData(params)\n        db.QueryInsert_(entity, \"\")\n    }\n}\n\nfunc loadEventTypes() {\n    eventTypeNames, _ := ioutil.ReadFile(\".\/resources\/event-type-name\")\n    eventTypeNamesSourse := strings.Split(string(eventTypeNames), \"\\n\")\n    topicality := []bool{true, false}\n    for i := 0; i < len(eventTypeNamesSourse); i++ {\n        \/\/rand.Seed(int64(i))\n        eventTypeName := strings.TrimSpace(eventTypeNamesSourse[i])\n        params := map[string]interface{}{\"name\": eventTypeName, \"description\": \"\", \"topicality\": topicality[rand.Intn(2)]}\n        entity := base.EventTypes()\n        entity.LoadModelData(params)\n        db.QueryInsert_(entity, \"\")\n    }\n}\n\nfunc loadForms() {\n    formNames, _ := ioutil.ReadFile(\".\/resources\/form-name\")\n    formNamesSourse := strings.Split(string(formNames), \"\\n\")\n    for i := 0; i < len(formNamesSourse); i++ {\n        formName := strings.TrimSpace(formNamesSourse[i])\n        entity := base.Forms()\n        entity.LoadModelData(map[string]interface{}{\"name\": formName})\n        db.QueryInsert_(entity, \"\")\n    }\n}\n\nfunc loadParamTypes() {\n    paramTypesNames, _ := ioutil.ReadFile(\".\/resources\/param-type-name\")\n    paramTypesSourse := strings.Split(string(paramTypesNames), \"\\n\")\n    for i := 0; i < len(paramTypesSourse); i++ {\n        paramType := strings.TrimSpace(paramTypesSourse[i])\n        entity := base.ParamTypes()\n        entity.LoadModelData(map[string]interface{}{\"name\": paramType})\n        db.QueryInsert_(entity, \"\")\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/jmoiron\/sqlx\"\n\t\"github.com\/lib\/pq\"\n)\n\nfunc sqlInterface(\n\trootAccount *Account,\n\ttransactions []*Transaction,\n) {\n\n\tdbDir := filepath.Join(os.TempDir(), fmt.Sprintf(\"keep-%d\", rand.Int63()))\n\tif out, err := exec.Command(\"initdb\", \"-D\", dbDir).CombinedOutput(); err != nil {\n\t\tfail(\"%v: %s\", err, out)\n\t}\n\tpt(\"db dir: %s\\n\", dbDir)\n\tdefer exec.Command(\"rm\", \"-rf\", dbDir).Run()\n\n\tport := 10000 + rand.Intn(50000)\n\tconf := `\n\t\tport = ` + fmt.Sprintf(\"%d\", port) + `\n\t`\n\tif err := ioutil.WriteFile(filepath.Join(dbDir, \"postgresql.conf\"), []byte(conf), 0644); err != nil {\n\t\tfail(\"%v\", err)\n\t}\n\tc := exec.Command(\"postgres\", \"-D\", dbDir)\n\tc.SysProcAttr = &syscall.SysProcAttr{\n\t\tSetpgid: true,\n\t}\n\tif err := c.Start(); err != nil {\n\t\tfail(\"%v\", err)\n\t}\n\tdefer syscall.Kill(-c.Process.Pid, syscall.SIGKILL)\n\ttime.Sleep(time.Second)\n\tpt(\"db started\\n\")\n\n\tdb, err := sqlx.Open(\"postgres\", fmt.Sprintf(\"postgres:\/\/localhost:%d\/postgres?sslmode=disable\", port))\n\tif err != nil {\n\t\tfail(\"%v\", err)\n\t}\n\tdefer db.Close()\n\ttx := db.MustBegin()\n\tif _, err := tx.Exec(`\n\t\tCREATE TABLE entries (\n\t\t\tid bigserial primary key,\n\t\t\ttransaction bigint,\n\t\t\ttransaction_description text,\n\t\t\tdate timestamp with time zone,\n\t\t\taccount text[],\n\t\t\tcurrency text,\n\t\t\tamount numeric,\n\t\t\tdescription text\n\t\t)\n\t\t`,\n\t); err != nil {\n\t\tfail(\"%v\", err)\n\t}\n\tfor _, view := range views {\n\t\tif _, err := tx.Exec(view); err != nil {\n\t\t\tfail(\"%v\", err)\n\t\t}\n\t}\n\tfor tid, transaction := range transactions {\n\t\tfor _, entry := range transaction.Entries {\n\t\t\tif _, err := tx.Exec(`\n\t\t\t\tINSERT INTO entries\n\t\t\t\t(\n\t\t\t\t\ttransaction, transaction_description,\n\t\t\t\t\tdate, account, currency, amount, description\n\t\t\t\t)\n\t\t\t\tVALUES (\n\t\t\t\t\t$1, $2,\n\t\t\t\t\t$3, $4, $5, $6::numeric, $7\n\t\t\t\t)\n\t\t\t\t`,\n\t\t\t\ttid,\n\t\t\t\ttransaction.Description,\n\t\t\t\tentry.Time,\n\t\t\t\tfunc() (ret pq.StringArray) {\n\t\t\t\t\tacc := entry.Account\n\t\t\t\t\tfor acc != rootAccount {\n\t\t\t\t\t\tret = append(ret, acc.Name)\n\t\t\t\t\t\tacc = acc.Parent\n\t\t\t\t\t}\n\t\t\t\t\tfor i := len(ret)\/2 - 1; i >= 0; i-- {\n\t\t\t\t\t\tj := len(ret) - 1 - i\n\t\t\t\t\t\tret[i], ret[j] = ret[j], ret[i]\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}(),\n\t\t\t\tentry.Currency,\n\t\t\t\tentry.Amount.FloatString(3),\n\t\t\t\tentry.Description,\n\t\t\t); err != nil {\n\t\t\t\tfail(\"%v\", err)\n\t\t\t}\n\t\t}\n\t}\n\tif err := tx.Commit(); err != nil {\n\t\tfail(\"%v\", err)\n\t}\n\tpt(\"data loaded\\n\")\n\n\tsigs := make(chan os.Signal)\n\tgo func() {\n\t\tfor {\n\t\t\t<-sigs\n\t\t}\n\t}()\n\tsignal.Notify(sigs, os.Interrupt)\n\n\tpsql := exec.Command(\"psql\", fmt.Sprintf(\"postgres:\/\/localhost:%d\/postgres\", port))\n\tpsql.Stdout = os.Stdout\n\tpsql.Stdin = os.Stdin\n\tpsql.Stderr = os.Stderr\n\tif err := psql.Run(); err != nil {\n\t\tfail(\"%v\", err)\n\t}\n}\n\nvar views = []string{\n\t\/\/ props\n\t`\n\tcreate view props as \n\tselect distinct on (date, transaction)\n\tdate, transaction_description\n\tfrom entries\n\twhere account[1] = '支出'\n\tand account[2] in (\n\t\t'数码',\n\t\t'物品',\n\t\t'衣物服饰',\n\t\t'消耗品',\n\t\t'保健品',\n\t\t'书籍',\n\t\t'药物',\n\t\t'性用品'\n\t)\n\torder by date desc, transaction\n\t`,\n\n\t\/\/ consumables\n\t`\n\tcreate view consumables as \n\tselect distinct on (date, transaction)\n\tdate, transaction_description\n\tfrom entries\n\twhere account[1] = '支出'\n\tand account[2] in (\n\t\t'饮食',\n\t\t'消耗品',\n\t\t'药物',\n\t\t'保健品'\n\t)\n\torder by date desc, transaction\n\t`,\n\n\t\/\/ monthly\n\t`\n\tcreate view monthly as \n\tselect \n\n\tto_char(date_trunc('month', date), 'YYYY-MM') as month,\n\n\tCOALESCE(\n\t\t'支出' || currency || (sum(amount) filter (where account[1] = '支出'))::numeric(20,2)::text \n\t\t|| E'：\\n'\n\t\t|| (\n\t\t\tselect string_agg(\n\t\t\t\tcurrency || amount::numeric(20,2)::text || ' ' || account,\n\t\t\t\tE'\\n'\n\t\t\t\torder by amount desc\n\t\t\t) from (\n\t\t\t\tselect account[2] as account, currency, sum(amount) as amount\n\t\t\t\tfrom unnest(\n\t\t\t\t\tarray_agg(id) filter (where account[1] = '支出')\n\t\t\t\t) as id\n\t\t\t\tjoin entries e2 using (id)\n\t\t\t\tgroup by account[2], currency\n\t\t\t) t0\n\t\t),\n\t\t'-'\n\t) || E'\\n' as expenses,\n\n\tCOALESCE(\n\t\t'收入' || currency || (sum(amount) filter (where account[1] = '收入'))::numeric(20,2)::text \n\t\t|| E'：\\n'\n\t\t|| (\n\t\t\tselect string_agg(\n\t\t\t\tcurrency || amount::numeric(20, 2)::text || ' ' || account,\n\t\t\t\tE'\\n'\n\t\t\t\torder by amount asc\n\t\t\t) from (\n\t\t\t\tselect account[2] as account, currency, sum(amount) as amount\n\t\t\t\tfrom unnest(\n\t\t\t\t\tarray_agg(id) filter (where account[1] = '收入')\n\t\t\t\t) as id\n\t\t\t\tjoin entries e2 using (id)\n\t\t\t\tgroup by account[2], currency\n\t\t\t) t0\n\t\t),\n\t\t'-'\n\t) || E'\\n' as income,\n\n\tCOALESCE(\n\t\t'净资产' || currency || (\n\t\t\t-sum(amount) filter (where account[1] = '收入')\n\t\t\t-\n\t\t\tsum(amount) filter (where account[1] = '支出')\n\t\t)::numeric(20,2)::text,\n\t\t'-'\n\t) || E'\\n' as net_income,\n\n\tCOALESCE(\n\t\tE'资产：\\n' || (\n\t\t\tselect string_agg(\n\t\t\t\tcurrency \n\t\t\t\t|| amount::numeric(20, 2)::text || ' ' || account\n\t\t\t\t|| E'\\n'\n\t\t\t\t|| '= 增' || pos_amount::numeric(20, 2)::text\n\t\t\t\t|| ' 减' || neg_amount::numeric(20, 2)::text,\n\t\t\t\tE'\\n'\n\t\t\t\torder by amount desc\n\t\t\t) from (\n\t\t\t\tselect account[2] as account, currency, sum(amount) as amount,\n\t\t\t\tCOALESCE(sum(amount) filter (where amount >= 0), 0) as pos_amount,\n\t\t\t\tCOALESCE(-sum(amount) filter (where amount < 0), 0) as neg_amount\n\t\t\t\tfrom unnest(\n\t\t\t\t\tarray_agg(id) filter (where account[1] = '资产')\n\t\t\t\t) as id\n\t\t\t\tjoin entries e2 using (id)\n\t\t\t\tgroup by account[2], currency\n\t\t\t) t0\n\t\t),\n\t\t'-'\n\t) || E'\\n' as equity,\n\n\tCOALESCE(\n\t\tE'负债：\\n' || (\n\t\t\tselect string_agg(\n\t\t\t\tcurrency \n\t\t\t\t|| amount::numeric(20, 2)::text || ' ' || account\n\t\t\t\t|| E'\\n'\n\t\t\t\t|| '= 还' || pos_amount::numeric(20, 2)::text\n\t\t\t\t|| ' 借' || neg_amount::numeric(20, 2)::text,\n\t\t\t\tE'\\n'\n\t\t\t\torder by amount asc\n\t\t\t) from (\n\t\t\t\tselect account[2] as account, currency, sum(amount) as amount,\n\t\t\t\tCOALESCE(sum(amount) filter (where amount >= 0), 0) as pos_amount,\n\t\t\t\tCOALESCE(-sum(amount) filter (where amount < 0), 0) as neg_amount\n\t\t\t\tfrom unnest(\n\t\t\t\t\tarray_agg(id) filter (where account[1] = '负债')\n\t\t\t\t) as id\n\t\t\t\tjoin entries e2 using (id)\n\t\t\t\tgroup by account[2], currency\n\t\t\t) t0\n\t\t),\n\t\t'-'\n\t) || E'\\n' as liability\n\n\tfrom\n\tentries\n\n\tgroup by date_trunc('month', date), currency\n\torder by month desc, currency asc\n\t`,\n\n\t\/\/ this year expenses\n\t`\n\tcreate view this_year_expenses as\n\tselect \n\tcurrency, sum(amount), account[2], \n\tjsonb_pretty(jsonb_agg(\n\t\t\tto_char(date, 'YYYY-MM-DD') \n\t\t\t|| ' ' \n\t\t\t|| currency \n\t\t\t|| amount::numeric(10,2)\n\t\t\t|| ' ' \n\t\t\t|| transaction_description \n\t\t\torder by amount desc, date desc\n\t)) \n\tfrom entries\n\twhere extract(year from date) = extract(year from now())\n\tand account[1] = '支出' \n\tgroup by account[2],currency \n\torder by sum desc\n\t`,\n\n\t\/\/\n}\n<commit_msg>add generic interval statistics views<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/jmoiron\/sqlx\"\n\t\"github.com\/lib\/pq\"\n)\n\nfunc sqlInterface(\n\trootAccount *Account,\n\ttransactions []*Transaction,\n) {\n\n\tdbDir := filepath.Join(os.TempDir(), fmt.Sprintf(\"keep-%d\", rand.Int63()))\n\tif out, err := exec.Command(\"initdb\", \"-D\", dbDir).CombinedOutput(); err != nil {\n\t\tfail(\"%v: %s\", err, out)\n\t}\n\tpt(\"db dir: %s\\n\", dbDir)\n\tdefer exec.Command(\"rm\", \"-rf\", dbDir).Run()\n\n\tport := 10000 + rand.Intn(50000)\n\tconf := `\n\t\tport = ` + fmt.Sprintf(\"%d\", port) + `\n\t`\n\tif err := ioutil.WriteFile(filepath.Join(dbDir, \"postgresql.conf\"), []byte(conf), 0644); err != nil {\n\t\tfail(\"%v\", err)\n\t}\n\tc := exec.Command(\"postgres\", \"-D\", dbDir)\n\tc.SysProcAttr = &syscall.SysProcAttr{\n\t\tSetpgid: true,\n\t}\n\tif err := c.Start(); err != nil {\n\t\tfail(\"%v\", err)\n\t}\n\tdefer syscall.Kill(-c.Process.Pid, syscall.SIGKILL)\n\ttime.Sleep(time.Second)\n\tpt(\"db started\\n\")\n\n\tdb, err := sqlx.Open(\"postgres\", fmt.Sprintf(\"postgres:\/\/localhost:%d\/postgres?sslmode=disable\", port))\n\tif err != nil {\n\t\tfail(\"%v\", err)\n\t}\n\tdefer db.Close()\n\ttx := db.MustBegin()\n\tif _, err := tx.Exec(`\n\t\tCREATE TABLE entries (\n\t\t\tid bigserial primary key,\n\t\t\ttransaction bigint,\n\t\t\ttransaction_description text,\n\t\t\tdate timestamp with time zone,\n\t\t\taccount text[],\n\t\t\tcurrency text,\n\t\t\tamount numeric,\n\t\t\tdescription text\n\t\t)\n\t\t`,\n\t); err != nil {\n\t\tfail(\"%v\", err)\n\t}\n\tfor _, view := range views {\n\t\tif _, err := tx.Exec(view); err != nil {\n\t\t\tfail(\"%v\", err)\n\t\t}\n\t}\n\tfor tid, transaction := range transactions {\n\t\tfor _, entry := range transaction.Entries {\n\t\t\tif _, err := tx.Exec(`\n\t\t\t\tINSERT INTO entries\n\t\t\t\t(\n\t\t\t\t\ttransaction, transaction_description,\n\t\t\t\t\tdate, account, currency, amount, description\n\t\t\t\t)\n\t\t\t\tVALUES (\n\t\t\t\t\t$1, $2,\n\t\t\t\t\t$3, $4, $5, $6::numeric, $7\n\t\t\t\t)\n\t\t\t\t`,\n\t\t\t\ttid,\n\t\t\t\ttransaction.Description,\n\t\t\t\tentry.Time,\n\t\t\t\tfunc() (ret pq.StringArray) {\n\t\t\t\t\tacc := entry.Account\n\t\t\t\t\tfor acc != rootAccount {\n\t\t\t\t\t\tret = append(ret, acc.Name)\n\t\t\t\t\t\tacc = acc.Parent\n\t\t\t\t\t}\n\t\t\t\t\tfor i := len(ret)\/2 - 1; i >= 0; i-- {\n\t\t\t\t\t\tj := len(ret) - 1 - i\n\t\t\t\t\t\tret[i], ret[j] = ret[j], ret[i]\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}(),\n\t\t\t\tentry.Currency,\n\t\t\t\tentry.Amount.FloatString(3),\n\t\t\t\tentry.Description,\n\t\t\t); err != nil {\n\t\t\t\tfail(\"%v\", err)\n\t\t\t}\n\t\t}\n\t}\n\tif err := tx.Commit(); err != nil {\n\t\tfail(\"%v\", err)\n\t}\n\tpt(\"data loaded\\n\")\n\n\tsigs := make(chan os.Signal)\n\tgo func() {\n\t\tfor {\n\t\t\t<-sigs\n\t\t}\n\t}()\n\tsignal.Notify(sigs, os.Interrupt)\n\n\tpsql := exec.Command(\"psql\", fmt.Sprintf(\"postgres:\/\/localhost:%d\/postgres\", port))\n\tpsql.Stdout = os.Stdout\n\tpsql.Stdin = os.Stdin\n\tpsql.Stderr = os.Stderr\n\tif err := psql.Run(); err != nil {\n\t\tfail(\"%v\", err)\n\t}\n}\n\nvar views = []string{\n\t\/\/ props\n\t`\n\tcreate view props as \n\tselect distinct on (date, transaction)\n\tdate, transaction_description\n\tfrom entries\n\twhere account[1] = '支出'\n\tand account[2] in (\n\t\t'数码',\n\t\t'物品',\n\t\t'衣物服饰',\n\t\t'消耗品',\n\t\t'保健品',\n\t\t'书籍',\n\t\t'药物',\n\t\t'性用品'\n\t)\n\torder by date desc, transaction\n\t`,\n\n\t\/\/ consumables\n\t`\n\tcreate view consumables as \n\tselect distinct on (date, transaction)\n\tdate, transaction_description\n\tfrom entries\n\twhere account[1] = '支出'\n\tand account[2] in (\n\t\t'饮食',\n\t\t'消耗品',\n\t\t'药物',\n\t\t'保健品'\n\t)\n\torder by date desc, transaction\n\t`,\n\n\t\/\/ monthly\n\t\"create view monthly as\" + intervalStat(\"date_trunc('month', date)\"),\n\n\t\/\/ yearly\n\t\"create view yearly as\" + intervalStat(\"date_trunc('year', date)\"),\n\n\t\/\/ seasonally\n\t\"create view seasonally as\" + intervalStat(\"date_trunc('year', date) + interval '3 month' * (extract(month from date)::int \/ 3)\"),\n\n\t\/\/ this year expenses\n\t`\n\tcreate view this_year_expenses as\n\tselect \n\tcurrency, sum(amount), account[2], \n\tjsonb_pretty(jsonb_agg(\n\t\t\tto_char(date, 'YYYY-MM-DD') \n\t\t\t|| ' ' \n\t\t\t|| currency \n\t\t\t|| amount::numeric(10,2)\n\t\t\t|| ' ' \n\t\t\t|| transaction_description \n\t\t\torder by amount desc, date desc\n\t)) \n\tfrom entries\n\twhere extract(year from date) = extract(year from now())\n\tand account[1] = '支出' \n\tgroup by account[2],currency \n\torder by sum desc\n\t`,\n\n\t\/\/\n}\n\nfunc intervalStat(groupBy string) string {\n\treturn `\n\tselect \n\tto_char(` + groupBy + `, 'YYYY-MM') as span,\n\n\tCOALESCE(\n\t\t'支出' || currency || (sum(amount) filter (where account[1] = '支出'))::numeric(20,2)::text \n\t\t|| E'：\\n'\n\t\t|| (\n\t\t\tselect string_agg(\n\t\t\t\tcurrency || amount::numeric(20,2)::text || ' ' || account,\n\t\t\t\tE'\\n'\n\t\t\t\torder by amount desc\n\t\t\t) from (\n\t\t\t\tselect account[2] as account, currency, sum(amount) as amount\n\t\t\t\tfrom unnest(\n\t\t\t\t\tarray_agg(id) filter (where account[1] = '支出')\n\t\t\t\t) as id\n\t\t\t\tjoin entries e2 using (id)\n\t\t\t\tgroup by account[2], currency\n\t\t\t) t0\n\t\t),\n\t\t'-'\n\t) || E'\\n' as expenses,\n\n\tCOALESCE(\n\t\t'收入' || currency || (sum(amount) filter (where account[1] = '收入'))::numeric(20,2)::text \n\t\t|| E'：\\n'\n\t\t|| (\n\t\t\tselect string_agg(\n\t\t\t\tcurrency || amount::numeric(20, 2)::text || ' ' || account,\n\t\t\t\tE'\\n'\n\t\t\t\torder by amount asc\n\t\t\t) from (\n\t\t\t\tselect account[2] as account, currency, sum(amount) as amount\n\t\t\t\tfrom unnest(\n\t\t\t\t\tarray_agg(id) filter (where account[1] = '收入')\n\t\t\t\t) as id\n\t\t\t\tjoin entries e2 using (id)\n\t\t\t\tgroup by account[2], currency\n\t\t\t) t0\n\t\t),\n\t\t'-'\n\t) || E'\\n' as income,\n\n\tCOALESCE(\n\t\t'净资产' || currency || (\n\t\t\t-sum(amount) filter (where account[1] = '收入')\n\t\t\t-\n\t\t\tsum(amount) filter (where account[1] = '支出')\n\t\t)::numeric(20,2)::text,\n\t\t'-'\n\t) || E'\\n' as net_income,\n\n\tCOALESCE(\n\t\tE'资产：\\n' || (\n\t\t\tselect string_agg(\n\t\t\t\tcurrency \n\t\t\t\t|| amount::numeric(20, 2)::text || ' ' || account\n\t\t\t\t|| E'\\n'\n\t\t\t\t|| '= 增' || pos_amount::numeric(20, 2)::text\n\t\t\t\t|| ' 减' || neg_amount::numeric(20, 2)::text,\n\t\t\t\tE'\\n'\n\t\t\t\torder by amount desc\n\t\t\t) from (\n\t\t\t\tselect account[2] as account, currency, sum(amount) as amount,\n\t\t\t\tCOALESCE(sum(amount) filter (where amount >= 0), 0) as pos_amount,\n\t\t\t\tCOALESCE(-sum(amount) filter (where amount < 0), 0) as neg_amount\n\t\t\t\tfrom unnest(\n\t\t\t\t\tarray_agg(id) filter (where account[1] = '资产')\n\t\t\t\t) as id\n\t\t\t\tjoin entries e2 using (id)\n\t\t\t\tgroup by account[2], currency\n\t\t\t) t0\n\t\t),\n\t\t'-'\n\t) || E'\\n' as equity,\n\n\tCOALESCE(\n\t\tE'负债：\\n' || (\n\t\t\tselect string_agg(\n\t\t\t\tcurrency \n\t\t\t\t|| amount::numeric(20, 2)::text || ' ' || account\n\t\t\t\t|| E'\\n'\n\t\t\t\t|| '= 还' || pos_amount::numeric(20, 2)::text\n\t\t\t\t|| ' 借' || neg_amount::numeric(20, 2)::text,\n\t\t\t\tE'\\n'\n\t\t\t\torder by amount asc\n\t\t\t) from (\n\t\t\t\tselect account[2] as account, currency, sum(amount) as amount,\n\t\t\t\tCOALESCE(sum(amount) filter (where amount >= 0), 0) as pos_amount,\n\t\t\t\tCOALESCE(-sum(amount) filter (where amount < 0), 0) as neg_amount\n\t\t\t\tfrom unnest(\n\t\t\t\t\tarray_agg(id) filter (where account[1] = '负债')\n\t\t\t\t) as id\n\t\t\t\tjoin entries e2 using (id)\n\t\t\t\tgroup by account[2], currency\n\t\t\t) t0\n\t\t),\n\t\t'-'\n\t) || E'\\n' as liability\n\n\tfrom\n\tentries\n\n\tgroup by ` + groupBy + `, currency\n\torder by span desc, currency asc\n\t`\n}\n<|endoftext|>"}
{"text":"<commit_before>package sup\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"os\/user\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"golang.org\/x\/crypto\/ssh\"\n\t\"golang.org\/x\/crypto\/ssh\/agent\"\n)\n\n\/\/ Client is a wrapper over the SSH connection\/sessions.\ntype SSHClient struct {\n\tConn         *ssh.Client\n\tSess         *ssh.Session\n\tUser         string\n\tHost         string\n\tRemoteStdin  io.WriteCloser\n\tRemoteStdout io.Reader\n\tRemoteStderr io.Reader\n\tConnOpened   bool\n\tSessOpened   bool\n\tRunning      bool\n\tEnv          string \/\/export FOO=\"bar\"; export BAR=\"baz\";\n}\n\ntype ErrConnect struct {\n\tUser   string\n\tHost   string\n\tReason string\n}\n\nfunc (e ErrConnect) Error() string {\n\treturn fmt.Sprintf(`Connect(\"%v@%v\"): %v`, e.User, e.Host, e.Reason)\n}\n\n\/\/ parseHost parses and normalizes <user>@<host:port> from a given string.\nfunc (c *SSHClient) parseHost(host string) error {\n\tc.Host = host\n\n\t\/\/ Remove extra \"ssh:\/\/\" schema\n\tif len(c.Host) > 6 && c.Host[:6] == \"ssh:\/\/\" {\n\t\tc.Host = c.Host[6:]\n\t}\n\n\tif at := strings.Index(c.Host, \"@\"); at != -1 {\n\t\tc.User = c.Host[:at]\n\t\tc.Host = c.Host[at+1:]\n\t}\n\n\t\/\/ Add default user, if not set\n\tif c.User == \"\" {\n\t\tu, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.User = u.Username\n\t}\n\n\tif strings.Index(c.Host, \"\/\") != -1 {\n\t\treturn ErrConnect{c.User, c.Host, \"unexpected slash in the host URL\"}\n\t}\n\n\t\/\/ Add default port, if not set\n\tif strings.Index(c.Host, \":\") == -1 {\n\t\tc.Host += \":22\"\n\t}\n\n\treturn nil\n}\n\nvar initAuthMethodOnce sync.Once\nvar authMethod ssh.AuthMethod\n\n\/\/ initAuthMethod initiates SSH authentication method.\nfunc initAuthMethod() {\n\tvar signers []ssh.Signer\n\n\t\/\/ If there's a running SSH Agent, try to use its Private keys.\n\tsock, err := net.Dial(\"unix\", os.Getenv(\"SSH_AUTH_SOCK\"))\n\tif err == nil {\n\t\tagent := agent.NewClient(sock)\n\t\tsigners, _ = agent.Signers()\n\t}\n\n\t\/\/ Try to read user's SSH private keys form the standard paths.\n\tfiles := []string{\n\t\tos.Getenv(\"HOME\") + \"\/.ssh\/id_rsa\",\n\t\tos.Getenv(\"HOME\") + \"\/.ssh\/id_dsa\",\n\t}\n\tfor _, file := range files {\n\t\tdata, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tsigner, err := ssh.ParsePrivateKey(data)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tsigners = append(signers, signer)\n\n\t}\n\tauthMethod = ssh.PublicKeys(signers...)\n}\n\n\/\/ SSHDialFunc can dial an ssh server and return a client\ntype SSHDialFunc func(net, addr string, config *ssh.ClientConfig) (*ssh.Client, error)\n\n\/\/ Connect creates SSH connection to a specified host.\n\/\/ It expects the host of the form \"[ssh:\/\/]host[:port]\".\nfunc (c *SSHClient) Connect(host string) error {\n\treturn c.ConnectWith(host, ssh.Dial)\n}\n\n\/\/ ConnectWith creates a SSH connection to a specified host. It will use dialer to establish the\n\/\/ connection.\n\/\/ TODO: Split Signers to its own method.\nfunc (c *SSHClient) ConnectWith(host string, dialer SSHDialFunc) error {\n\n\tfmt.Println(\"connecting\", host)\n\n\tif c.ConnOpened {\n\t\treturn fmt.Errorf(\"Already connected\")\n\t}\n\n\tinitAuthMethodOnce.Do(initAuthMethod)\n\n\terr := c.parseHost(host)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: c.User,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tauthMethod,\n\t\t},\n\t}\n\n\tc.Conn, err = dialer(\"tcp\", c.Host, config)\n\tif err != nil {\n\t\treturn ErrConnect{c.User, c.Host, err.Error()}\n\t}\n\n\tc.ConnOpened = true\n\n\treturn nil\n}\n\n\/\/ Run runs the task.Run command remotely on c.Host.\nfunc (c *SSHClient) Run(task *Task) error {\n\tif c.Running {\n\t\treturn fmt.Errorf(\"Session already running\")\n\t}\n\tif c.SessOpened {\n\t\treturn fmt.Errorf(\"Session already connected\")\n\t}\n\n\tsess, err := c.Conn.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.RemoteStdin, err = sess.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.RemoteStdout, err = sess.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.RemoteStderr, err = sess.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Sess = sess\n\tc.SessOpened = true\n\n\t\/\/ Start the remote command.\n\tif err := c.Sess.Start(c.Env + \"set -x;\" + task.Run); err != nil {\n\t\treturn ErrTask{task, err.Error()}\n\t}\n\n\tc.Running = true\n\treturn nil\n}\n\n\/\/ Wait waits until the remote command finishes and exits.\n\/\/ It closes the SSH session.\nfunc (c *SSHClient) Wait() error {\n\tif !c.Running {\n\t\treturn fmt.Errorf(\"Trying to wait on stopped session\")\n\t}\n\n\terr := c.Sess.Wait()\n\tc.Sess.Close()\n\tc.Running = false\n\tc.SessOpened = false\n\n\treturn err\n}\n\n\/\/ DialThrough will create a new connection from the ssh server sc is connected to. DialThrough is an SSHDialer.\nfunc (sc *SSHClient) DialThrough(net, addr string, config *ssh.ClientConfig) (*ssh.Client, error) {\n\tfmt.Println(\"Dialing\", net, addr)\n\tconn, err := sc.Conn.Dial(net, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, chans, reqs, err := ssh.NewClientConn(conn, addr, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ssh.NewClient(c, chans, reqs), nil\n\n}\n\n\/\/ Close closes the underlying SSH connection and session.\nfunc (c *SSHClient) Close() error {\n\tif c.SessOpened {\n\t\tc.Sess.Close()\n\t\tc.SessOpened = false\n\t}\n\tif !c.ConnOpened {\n\t\treturn fmt.Errorf(\"Trying to close the already closed connection\")\n\t}\n\n\terr := c.Conn.Close()\n\tc.ConnOpened = false\n\tc.Running = false\n\n\treturn err\n}\n\nfunc (c *SSHClient) Prefix() string {\n\treturn c.User + \"@\" + c.Host\n}\n\nfunc (c *SSHClient) Write(p []byte) (n int, err error) {\n\treturn c.RemoteStdin.Write(p)\n}\n\nfunc (c *SSHClient) WriteClose() error {\n\treturn c.RemoteStdin.Close()\n}\n<commit_msg>clean out debug prints<commit_after>package sup\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"os\/user\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"golang.org\/x\/crypto\/ssh\"\n\t\"golang.org\/x\/crypto\/ssh\/agent\"\n)\n\n\/\/ Client is a wrapper over the SSH connection\/sessions.\ntype SSHClient struct {\n\tConn         *ssh.Client\n\tSess         *ssh.Session\n\tUser         string\n\tHost         string\n\tRemoteStdin  io.WriteCloser\n\tRemoteStdout io.Reader\n\tRemoteStderr io.Reader\n\tConnOpened   bool\n\tSessOpened   bool\n\tRunning      bool\n\tEnv          string \/\/export FOO=\"bar\"; export BAR=\"baz\";\n}\n\ntype ErrConnect struct {\n\tUser   string\n\tHost   string\n\tReason string\n}\n\nfunc (e ErrConnect) Error() string {\n\treturn fmt.Sprintf(`Connect(\"%v@%v\"): %v`, e.User, e.Host, e.Reason)\n}\n\n\/\/ parseHost parses and normalizes <user>@<host:port> from a given string.\nfunc (c *SSHClient) parseHost(host string) error {\n\tc.Host = host\n\n\t\/\/ Remove extra \"ssh:\/\/\" schema\n\tif len(c.Host) > 6 && c.Host[:6] == \"ssh:\/\/\" {\n\t\tc.Host = c.Host[6:]\n\t}\n\n\tif at := strings.Index(c.Host, \"@\"); at != -1 {\n\t\tc.User = c.Host[:at]\n\t\tc.Host = c.Host[at+1:]\n\t}\n\n\t\/\/ Add default user, if not set\n\tif c.User == \"\" {\n\t\tu, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.User = u.Username\n\t}\n\n\tif strings.Index(c.Host, \"\/\") != -1 {\n\t\treturn ErrConnect{c.User, c.Host, \"unexpected slash in the host URL\"}\n\t}\n\n\t\/\/ Add default port, if not set\n\tif strings.Index(c.Host, \":\") == -1 {\n\t\tc.Host += \":22\"\n\t}\n\n\treturn nil\n}\n\nvar initAuthMethodOnce sync.Once\nvar authMethod ssh.AuthMethod\n\n\/\/ initAuthMethod initiates SSH authentication method.\nfunc initAuthMethod() {\n\tvar signers []ssh.Signer\n\n\t\/\/ If there's a running SSH Agent, try to use its Private keys.\n\tsock, err := net.Dial(\"unix\", os.Getenv(\"SSH_AUTH_SOCK\"))\n\tif err == nil {\n\t\tagent := agent.NewClient(sock)\n\t\tsigners, _ = agent.Signers()\n\t}\n\n\t\/\/ Try to read user's SSH private keys form the standard paths.\n\tfiles := []string{\n\t\tos.Getenv(\"HOME\") + \"\/.ssh\/id_rsa\",\n\t\tos.Getenv(\"HOME\") + \"\/.ssh\/id_dsa\",\n\t}\n\tfor _, file := range files {\n\t\tdata, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tsigner, err := ssh.ParsePrivateKey(data)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tsigners = append(signers, signer)\n\n\t}\n\tauthMethod = ssh.PublicKeys(signers...)\n}\n\n\/\/ SSHDialFunc can dial an ssh server and return a client\ntype SSHDialFunc func(net, addr string, config *ssh.ClientConfig) (*ssh.Client, error)\n\n\/\/ Connect creates SSH connection to a specified host.\n\/\/ It expects the host of the form \"[ssh:\/\/]host[:port]\".\nfunc (c *SSHClient) Connect(host string) error {\n\treturn c.ConnectWith(host, ssh.Dial)\n}\n\n\/\/ ConnectWith creates a SSH connection to a specified host. It will use dialer to establish the\n\/\/ connection.\n\/\/ TODO: Split Signers to its own method.\nfunc (c *SSHClient) ConnectWith(host string, dialer SSHDialFunc) error {\n\n\tif c.ConnOpened {\n\t\treturn fmt.Errorf(\"Already connected\")\n\t}\n\n\tinitAuthMethodOnce.Do(initAuthMethod)\n\n\terr := c.parseHost(host)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig := &ssh.ClientConfig{\n\t\tUser: c.User,\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tauthMethod,\n\t\t},\n\t}\n\n\tc.Conn, err = dialer(\"tcp\", c.Host, config)\n\tif err != nil {\n\t\treturn ErrConnect{c.User, c.Host, err.Error()}\n\t}\n\n\tc.ConnOpened = true\n\n\treturn nil\n}\n\n\/\/ Run runs the task.Run command remotely on c.Host.\nfunc (c *SSHClient) Run(task *Task) error {\n\tif c.Running {\n\t\treturn fmt.Errorf(\"Session already running\")\n\t}\n\tif c.SessOpened {\n\t\treturn fmt.Errorf(\"Session already connected\")\n\t}\n\n\tsess, err := c.Conn.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.RemoteStdin, err = sess.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.RemoteStdout, err = sess.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.RemoteStderr, err = sess.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Sess = sess\n\tc.SessOpened = true\n\n\t\/\/ Start the remote command.\n\tif err := c.Sess.Start(c.Env + \"set -x;\" + task.Run); err != nil {\n\t\treturn ErrTask{task, err.Error()}\n\t}\n\n\tc.Running = true\n\treturn nil\n}\n\n\/\/ Wait waits until the remote command finishes and exits.\n\/\/ It closes the SSH session.\nfunc (c *SSHClient) Wait() error {\n\tif !c.Running {\n\t\treturn fmt.Errorf(\"Trying to wait on stopped session\")\n\t}\n\n\terr := c.Sess.Wait()\n\tc.Sess.Close()\n\tc.Running = false\n\tc.SessOpened = false\n\n\treturn err\n}\n\n\/\/ DialThrough will create a new connection from the ssh server sc is connected to. DialThrough is an SSHDialer.\nfunc (sc *SSHClient) DialThrough(net, addr string, config *ssh.ClientConfig) (*ssh.Client, error) {\n\tconn, err := sc.Conn.Dial(net, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, chans, reqs, err := ssh.NewClientConn(conn, addr, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ssh.NewClient(c, chans, reqs), nil\n\n}\n\n\/\/ Close closes the underlying SSH connection and session.\nfunc (c *SSHClient) Close() error {\n\tif c.SessOpened {\n\t\tc.Sess.Close()\n\t\tc.SessOpened = false\n\t}\n\tif !c.ConnOpened {\n\t\treturn fmt.Errorf(\"Trying to close the already closed connection\")\n\t}\n\n\terr := c.Conn.Close()\n\tc.ConnOpened = false\n\tc.Running = false\n\n\treturn err\n}\n\nfunc (c *SSHClient) Prefix() string {\n\treturn c.User + \"@\" + c.Host\n}\n\nfunc (c *SSHClient) Write(p []byte) (n int, err error) {\n\treturn c.RemoteStdin.Write(p)\n}\n\nfunc (c *SSHClient) WriteClose() error {\n\treturn c.RemoteStdin.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 go-dockerclient authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/\n\/\/ The content is borrowed from Docker's own source code to provide a simple\n\/\/ tls based dialer\n\npackage docker\n\nimport (\n\t\"crypto\/tls\"\n\t\"errors\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype tlsClientCon struct {\n\t*tls.Conn\n\trawConn net.Conn\n}\n\nfunc (c *tlsClientCon) CloseWrite() error {\n\t\/\/ Go standard tls.Conn doesn't provide the CloseWrite() method so we do it\n\t\/\/ on its underlying connection.\n\tif cwc, ok := c.rawConn.(interface {\n\t\tCloseWrite() error\n\t}); ok {\n\t\treturn cwc.CloseWrite()\n\t}\n\treturn nil\n}\n\nfunc tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) {\n\t\/\/ We want the Timeout and Deadline values from dialer to cover the\n\t\/\/ whole process: TCP connection and TLS handshake. This means that we\n\t\/\/ also need to start our own timers now.\n\ttimeout := dialer.Timeout\n\n\tif !dialer.Deadline.IsZero() {\n\t\tdeadlineTimeout := time.Until(dialer.Deadline)\n\t\tif timeout == 0 || deadlineTimeout < timeout {\n\t\t\ttimeout = deadlineTimeout\n\t\t}\n\t}\n\n\tvar errChannel chan error\n\n\tif timeout != 0 {\n\t\terrChannel = make(chan error, 2)\n\t\ttime.AfterFunc(timeout, func() {\n\t\t\terrChannel <- errors.New(\"\")\n\t\t})\n\t}\n\n\trawConn, err := dialer.Dial(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcolonPos := strings.LastIndex(addr, \":\")\n\tif colonPos == -1 {\n\t\tcolonPos = len(addr)\n\t}\n\thostname := addr[:colonPos]\n\n\t\/\/ If no ServerName is set, infer the ServerName\n\t\/\/ from the hostname we're connecting to.\n\tif config.ServerName == \"\" {\n\t\t\/\/ Make a copy to avoid polluting argument or default.\n\t\tconfig = copyTLSConfig(config)\n\t\tconfig.ServerName = hostname\n\t}\n\n\tconn := tls.Client(rawConn, config)\n\n\tif timeout == 0 {\n\t\terr = conn.Handshake()\n\t} else {\n\t\tgo func() {\n\t\t\terrChannel <- conn.Handshake()\n\t\t}()\n\n\t\terr = <-errChannel\n\t}\n\n\tif err != nil {\n\t\trawConn.Close()\n\t\treturn nil, err\n\t}\n\n\t\/\/ This is Docker difference with standard's crypto\/tls package: returned a\n\t\/\/ wrapper which holds both the TLS and raw connections.\n\treturn &tlsClientCon{conn, rawConn}, nil\n}\n\n\/\/ this exists to silent an error message in go vet\nfunc copyTLSConfig(cfg *tls.Config) *tls.Config {\n\treturn &tls.Config{\n\t\tCertificates:             cfg.Certificates,\n\t\tCipherSuites:             cfg.CipherSuites,\n\t\tClientAuth:               cfg.ClientAuth,\n\t\tClientCAs:                cfg.ClientCAs,\n\t\tClientSessionCache:       cfg.ClientSessionCache,\n\t\tCurvePreferences:         cfg.CurvePreferences,\n\t\tInsecureSkipVerify:       cfg.InsecureSkipVerify, \/\/nolint:gosec\n\t\tMaxVersion:               cfg.MaxVersion,\n\t\tMinVersion:               cfg.MinVersion,\n\t\tNameToCertificate:        cfg.NameToCertificate,\n\t\tNextProtos:               cfg.NextProtos,\n\t\tPreferServerCipherSuites: cfg.PreferServerCipherSuites,\n\t\tRand:                     cfg.Rand,\n\t\tRootCAs:                  cfg.RootCAs,\n\t\tServerName:               cfg.ServerName,\n\t\tSessionTicketKey:         cfg.SessionTicketKey,\n\t\tSessionTicketsDisabled:   cfg.SessionTicketsDisabled,\n\t}\n}\n<commit_msg>tls: drop NameToCertificate<commit_after>\/\/ Copyright 2014 go-dockerclient authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/\n\/\/ The content is borrowed from Docker's own source code to provide a simple\n\/\/ tls based dialer\n\npackage docker\n\nimport (\n\t\"crypto\/tls\"\n\t\"errors\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype tlsClientCon struct {\n\t*tls.Conn\n\trawConn net.Conn\n}\n\nfunc (c *tlsClientCon) CloseWrite() error {\n\t\/\/ Go standard tls.Conn doesn't provide the CloseWrite() method so we do it\n\t\/\/ on its underlying connection.\n\tif cwc, ok := c.rawConn.(interface {\n\t\tCloseWrite() error\n\t}); ok {\n\t\treturn cwc.CloseWrite()\n\t}\n\treturn nil\n}\n\nfunc tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) {\n\t\/\/ We want the Timeout and Deadline values from dialer to cover the\n\t\/\/ whole process: TCP connection and TLS handshake. This means that we\n\t\/\/ also need to start our own timers now.\n\ttimeout := dialer.Timeout\n\n\tif !dialer.Deadline.IsZero() {\n\t\tdeadlineTimeout := time.Until(dialer.Deadline)\n\t\tif timeout == 0 || deadlineTimeout < timeout {\n\t\t\ttimeout = deadlineTimeout\n\t\t}\n\t}\n\n\tvar errChannel chan error\n\n\tif timeout != 0 {\n\t\terrChannel = make(chan error, 2)\n\t\ttime.AfterFunc(timeout, func() {\n\t\t\terrChannel <- errors.New(\"\")\n\t\t})\n\t}\n\n\trawConn, err := dialer.Dial(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcolonPos := strings.LastIndex(addr, \":\")\n\tif colonPos == -1 {\n\t\tcolonPos = len(addr)\n\t}\n\thostname := addr[:colonPos]\n\n\t\/\/ If no ServerName is set, infer the ServerName\n\t\/\/ from the hostname we're connecting to.\n\tif config.ServerName == \"\" {\n\t\t\/\/ Make a copy to avoid polluting argument or default.\n\t\tconfig = copyTLSConfig(config)\n\t\tconfig.ServerName = hostname\n\t}\n\n\tconn := tls.Client(rawConn, config)\n\n\tif timeout == 0 {\n\t\terr = conn.Handshake()\n\t} else {\n\t\tgo func() {\n\t\t\terrChannel <- conn.Handshake()\n\t\t}()\n\n\t\terr = <-errChannel\n\t}\n\n\tif err != nil {\n\t\trawConn.Close()\n\t\treturn nil, err\n\t}\n\n\t\/\/ This is Docker difference with standard's crypto\/tls package: returned a\n\t\/\/ wrapper which holds both the TLS and raw connections.\n\treturn &tlsClientCon{conn, rawConn}, nil\n}\n\n\/\/ this exists to silent an error message in go vet\nfunc copyTLSConfig(cfg *tls.Config) *tls.Config {\n\treturn &tls.Config{\n\t\tCertificates:             cfg.Certificates,\n\t\tCipherSuites:             cfg.CipherSuites,\n\t\tClientAuth:               cfg.ClientAuth,\n\t\tClientCAs:                cfg.ClientCAs,\n\t\tClientSessionCache:       cfg.ClientSessionCache,\n\t\tCurvePreferences:         cfg.CurvePreferences,\n\t\tInsecureSkipVerify:       cfg.InsecureSkipVerify, \/\/nolint:gosec\n\t\tMaxVersion:               cfg.MaxVersion,\n\t\tMinVersion:               cfg.MinVersion,\n\t\tNextProtos:               cfg.NextProtos,\n\t\tPreferServerCipherSuites: cfg.PreferServerCipherSuites,\n\t\tRand:                     cfg.Rand,\n\t\tRootCAs:                  cfg.RootCAs,\n\t\tServerName:               cfg.ServerName,\n\t\tSessionTicketKey:         cfg.SessionTicketKey,\n\t\tSessionTicketsDisabled:   cfg.SessionTicketsDisabled,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package tty\n\nimport (\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc Open() (*TTY, error) {\n\treturn open()\n}\n\nfunc (tty *TTY) Buffered() bool {\n\treturn tty.buffered()\n}\n\nfunc (tty *TTY) ReadRune() (rune, error) {\n\treturn tty.readRune()\n}\n\nfunc (tty *TTY) Close() error {\n\treturn tty.close()\n}\n\nfunc (tty *TTY) Size() (int, int, error) {\n\treturn tty.size()\n}\n\nfunc (tty *TTY) Input() *os.File {\n\treturn tty.input()\n}\n\nfunc (tty *TTY) Output() *os.File {\n\treturn tty.output()\n}\n\nfunc (tty *TTY) readPassword() (string, error) {\n\trs := []rune{}\nloop:\n\tfor {\n\t\tr, err := tty.readRune()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tswitch r {\n\t\tcase 13:\n\t\t\tbreak loop\n\t\tcase 8:\n\t\t\tif len(rs) > 0 {\n\t\t\t\trs = rs[:len(rs)-1]\n\t\t\t\ttty.Output().WriteString(\"\\b \\b\")\n\t\t\t}\n\t\tdefault:\n\t\t\tif unicode.IsPrint(r) {\n\t\t\t\trs = append(rs, r)\n\t\t\t\ttty.Output().WriteString(\"*\")\n\t\t\t}\n\t\t}\n\t}\n\treturn string(rs), nil\n}\n\nfunc (tty *TTY) ReadPassword() (string, error) {\n\tdefer tty.Output().WriteString(\"\\n\")\n\treturn tty.readPassword()\n}\n\nfunc (tty *TTY) ReadPasswordClear() (string, error) {\n\ts, err := tty.readPassword()\n\ttty.Output().WriteString(\n\t\tstrings.Repeat(\"\\b\", len(s)) +\n\t\t\tstrings.Repeat(\" \", len(s)) +\n\t\t\tstrings.Repeat(\"\\b\", len(s)))\n\treturn s, err\n}\n<commit_msg>Add ReadString<commit_after>package tty\n\nimport (\n\t\"os\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc Open() (*TTY, error) {\n\treturn open()\n}\n\nfunc (tty *TTY) Buffered() bool {\n\treturn tty.buffered()\n}\n\nfunc (tty *TTY) ReadRune() (rune, error) {\n\treturn tty.readRune()\n}\n\nfunc (tty *TTY) Close() error {\n\treturn tty.close()\n}\n\nfunc (tty *TTY) Size() (int, int, error) {\n\treturn tty.size()\n}\n\nfunc (tty *TTY) Input() *os.File {\n\treturn tty.input()\n}\n\nfunc (tty *TTY) Output() *os.File {\n\treturn tty.output()\n}\n\nfunc (tty *TTY) readString(isPassword bool) (string, error) {\n\trs := []rune{}\nloop:\n\tfor {\n\t\tr, err := tty.readRune()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tswitch r {\n\t\tcase 13:\n\t\t\tbreak loop\n\t\tcase 8:\n\t\t\tif len(rs) > 0 {\n\t\t\t\trs = rs[:len(rs)-1]\n\t\t\t\ttty.Output().WriteString(\"\\b \\b\")\n\t\t\t}\n\t\tdefault:\n\t\t\tif unicode.IsPrint(r) {\n\t\t\t\trs = append(rs, r)\n\t\t\t\tif isPassword {\n\t\t\t\t\ttty.Output().WriteString(\"*\")\n\t\t\t\t} else {\n\t\t\t\t\ttty.Output().WriteString(string(r))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn string(rs), nil\n}\n\nfunc (tty *TTY) ReadString() (string, error) {\n\tdefer tty.Output().WriteString(\"\\n\")\n\treturn tty.readString(false)\n}\n\nfunc (tty *TTY) ReadPassword() (string, error) {\n\tdefer tty.Output().WriteString(\"\\n\")\n\treturn tty.readString(true)\n}\n\nfunc (tty *TTY) ReadPasswordClear() (string, error) {\n\ts, err := tty.readString(true)\n\ttty.Output().WriteString(\n\t\tstrings.Repeat(\"\\b\", len(s)) +\n\t\t\tstrings.Repeat(\" \", len(s)) +\n\t\t\tstrings.Repeat(\"\\b\", len(s)))\n\treturn s, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package ranksel provides a bit vector\n\/\/ that can answer rank and select queries.\npackage ranksel\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"unsafe\"\n\n\t\"github.com\/robskie\/bit\"\n)\n\n\/\/ Options determines the size of the rank and\n\/\/ select sampling block. Lower values translates\n\/\/ to faster operations but results in larger size.\ntype Options struct {\n\t\/\/ Sr is the rank sampling block size.\n\t\/\/ This represents the number of bits in\n\t\/\/ each rank sampling block. Default is 1024.\n\tSr int\n\n\t\/\/ Ss is the select sampling block size.\n\t\/\/ This represents the number of 1s in each\n\t\/\/ select sampling block. Default is 8192.\n\tSs int\n}\n\n\/\/ NewOptions creates an Options\n\/\/ object with default values.\nfunc NewOptions() *Options {\n\treturn &Options{1024, 8192}\n}\n\n\/\/ BitVector is a bitmap with added data structure described by G. Navarro and\n\/\/ E. Providel's `A Structure for Plain Bitmaps: Combined Sampling` in \"Fast,\n\/\/ Small, Simple Rank\/Select on Bitmaps\" with some minor modifications.\n\/\/\n\/\/ See http:\/\/dcc.uchile.cl\/~gnavarro\/ps\/sea12.1.pdf for more details.\ntype BitVector struct {\n\tbits *bit.Array\n\n\t\/\/ ranks[i] is the number of 1s\n\t\/\/ from 0 to index (i*sr)-1\n\tranks []int\n\n\t\/\/ indices[i] points to the\n\t\/\/ beginning of the uint64 (LSB)\n\t\/\/ that contains the (i*ss)+1th\n\t\/\/ set bit.\n\tindices []int\n\n\tpopcount int\n\n\topts *Options\n}\n\n\/\/ NewBitVector creates a new BitVector.\nfunc NewBitVector(opts *Options) *BitVector {\n\tif opts == nil {\n\t\topts = NewOptions()\n\t}\n\n\tb := bit.NewArray(0)\n\trs := make([]int, 1)\n\tidx := make([]int, 1)\n\n\treturn &BitVector{\n\t\tbits:    b,\n\t\tranks:   rs,\n\t\tindices: idx,\n\t\topts:    opts,\n\t}\n}\n\n\/\/ Add appends the bits given its size to the vector.\nfunc (v *BitVector) Add(bits uint64, size int) {\n\tif size <= 0 || size > 64 {\n\t\tpanic(\"ranksel: bit size must be in range [1,64]\")\n\t}\n\n\t\/\/ Add bits\n\tv.bits.Add(bits, size)\n\tvlength := v.bits.Len()\n\n\t\/\/ Increment popcount\n\tpopcnt := bit.PopCount(bits)\n\tv.popcount += popcnt\n\n\t\/\/ Update rank sampling\n\tlenranks := len(v.ranks)\n\toverflow := vlength - (lenranks * v.opts.Sr)\n\tif overflow > 0 {\n\t\tv.ranks = append(v.ranks, 0)\n\n\t\trank := bit.Rank(bits, size-overflow-1)\n\t\tv.ranks[lenranks] = v.popcount - popcnt + rank\n\t}\n\n\t\/\/ Update select sampling\n\tlenidx := len(v.indices)\n\toverflow = v.popcount - (lenidx * v.opts.Ss)\n\tif overflow > 0 {\n\t\tv.indices = append(v.indices, 0)\n\n\t\tsel := bit.Select(bits, popcnt-overflow+1)\n\t\tv.indices[lenidx] = (vlength - size + sel) & ^0x3F\n\t}\n}\n\n\/\/ Get returns the uint64 representation of\n\/\/ bits starting from index idx given the bit size.\nfunc (v *BitVector) Get(idx, size int) uint64 {\n\treturn v.bits.Get(idx, size)\n}\n\n\/\/ Bit returns the bit value at index i.\nfunc (v *BitVector) Bit(i int) uint {\n\tif i >= v.bits.Len() {\n\t\tpanic(\"ranksel: index out of range\")\n\t}\n\n\tvbits := v.bits.Bits()\n\tif vbits[i>>6]&(1<<uint(i&63)) != 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\n\/\/ Rank1 counts the number of 1s from\n\/\/ the beginning up to the ith index.\nfunc (v *BitVector) Rank1(i int) int {\n\tif i >= v.bits.Len() {\n\t\tpanic(\"ranksel: index out of range\")\n\t}\n\n\tj := i \/ v.opts.Sr\n\tip := (j * v.opts.Sr) >> 6\n\trank := v.ranks[j]\n\n\taidx := i & 63\n\tbidx := i >> 6\n\tvbits := v.bits.Bits()\n\tfor _, b := range vbits[ip:bidx] {\n\t\trank += bit.PopCount(b)\n\t}\n\n\treturn rank + bit.Rank(vbits[bidx], aidx)\n}\n\n\/\/ Rank0 counts the number of 0s from\n\/\/ the beginning up to the ith index.\nfunc (v *BitVector) Rank0(i int) int {\n\treturn i - v.Rank1(i) + 1\n}\n\n\/\/ Select1 returns the index of the ith set bit.\n\/\/ Panics if i is zero or greater than the number\n\/\/ of set bits.\nfunc (v *BitVector) Select1(i int) int {\n\tif i > v.popcount {\n\t\tpanic(\"ranksel: input exceeds number of 1s\")\n\t} else if i == 0 {\n\t\tpanic(\"ranksel: input must be greater than 0\")\n\t}\n\n\tj := (i - 1) \/ v.opts.Ss\n\tq := v.indices[j] \/ v.opts.Sr\n\n\tk := 0\n\tr := 0\n\trq := v.ranks[q:]\n\tfor k, r = range rq {\n\t\tif r >= i {\n\t\t\tk--\n\t\t\tbreak\n\t\t}\n\t}\n\n\tidx := 0\n\trank := rq[k]\n\tvbits := v.bits.Bits()\n\taidx := ((q + k) * v.opts.Sr) >> 6\n\tfor ii, b := range vbits[aidx:] {\n\t\trank += bit.PopCount(b)\n\n\t\tif rank >= i {\n\t\t\toverflow := rank - i\n\t\t\tpopcnt := bit.PopCount(b)\n\n\t\t\tidx = (aidx + ii) << 6\n\t\t\tidx += bit.Select(b, popcnt-overflow)\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn idx\n}\n\n\/\/ Select0 returns the index of the ith zero. Panics\n\/\/ if i is zero or greater than the number of zeroes.\n\/\/ This is slower than Select1 in most cases.\nfunc (v *BitVector) Select0(i int) int {\n\tif i > (v.bits.Len() - v.popcount) {\n\t\tpanic(\"ranksel: input exceeds number of 0s\")\n\t} else if i == 0 {\n\t\tpanic(\"ranksel: input must be greater than 0\")\n\t}\n\n\t\/\/ Do a binary search on the rank samples to find\n\t\/\/ the largest rank sample that is less than i.\n\t\/\/ From https:\/\/en.wikipedia.org\/wiki\/Binary_search_algorithm\n\timin := 1\n\timax := len(v.ranks) - 1\n\tfor imin < imax {\n\t\timid := imin + ((imax - imin) >> 1)\n\n\t\trmid0 := (imid * v.opts.Sr) - v.ranks[imid]\n\t\tif rmid0 < i {\n\t\t\timin = imid + 1\n\t\t} else {\n\t\t\timax = imid\n\t\t}\n\t}\n\timin--\n\n\tidx := 0\n\tvbits := v.bits.Bits()\n\taidx := (imin * v.opts.Sr) >> 6\n\trank0 := (imin * v.opts.Sr) - v.ranks[imin]\n\tfor ii, b := range vbits[aidx:] {\n\t\tb = ^b\n\t\trank0 += bit.PopCount(b)\n\n\t\tif rank0 >= i {\n\t\t\toverflow := rank0 - i\n\t\t\tpopcnt := bit.PopCount(b)\n\n\t\t\tidx = (aidx + ii) << 6\n\t\t\tidx += bit.Select(b, popcnt-overflow)\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn idx\n}\n\n\/\/ GobEncode encodes this vector into gob streams.\nfunc (v *BitVector) GobEncode() ([]byte, error) {\n\tbuf := &bytes.Buffer{}\n\tenc := gob.NewEncoder(buf)\n\n\tenc.Encode(v.bits)\n\tenc.Encode(v.ranks)\n\tenc.Encode(v.indices)\n\tenc.Encode(v.popcount)\n\tenc.Encode(v.opts)\n\n\treturn buf.Bytes(), nil\n}\n\n\/\/ GobDecode populates this vector from gob streams.\nfunc (v *BitVector) GobDecode(data []byte) error {\n\tbuf := bytes.NewReader(data)\n\tdec := gob.NewDecoder(buf)\n\n\tdec.Decode(v.bits)\n\tdec.Decode(&v.ranks)\n\tdec.Decode(&v.indices)\n\tdec.Decode(&v.popcount)\n\tdec.Decode(v.opts)\n\n\treturn nil\n}\n\n\/\/ Len returns the number of bits stored.\nfunc (v *BitVector) Len() int {\n\treturn v.bits.Len()\n}\n\n\/\/ PopCount returns the total number of 1s.\nfunc (v *BitVector) PopCount() int {\n\treturn v.popcount\n}\n\n\/\/ Size returns the vector size in bytes.\nfunc (v *BitVector) Size() int {\n\tsizeofInt := int(unsafe.Sizeof(int(0)))\n\n\tsize := v.bits.Size()\n\tsize += len(v.ranks) * sizeofInt\n\tsize += len(v.indices) * sizeofInt\n\n\treturn size\n}\n\n\/\/ String returns a hexadecimal\n\/\/ string representation of the vector.\nfunc (v *BitVector) String() string {\n\treturn v.bits.String()\n}\n<commit_msg>Added error checks in gob encode\/decode methods<commit_after>\/\/ Package ranksel provides a bit vector\n\/\/ that can answer rank and select queries.\npackage ranksel\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"unsafe\"\n\n\t\"github.com\/robskie\/bit\"\n)\n\n\/\/ Options determines the size of the rank and\n\/\/ select sampling block. Lower values translates\n\/\/ to faster operations but results in larger size.\ntype Options struct {\n\t\/\/ Sr is the rank sampling block size.\n\t\/\/ This represents the number of bits in\n\t\/\/ each rank sampling block. Default is 1024.\n\tSr int\n\n\t\/\/ Ss is the select sampling block size.\n\t\/\/ This represents the number of 1s in each\n\t\/\/ select sampling block. Default is 8192.\n\tSs int\n}\n\n\/\/ NewOptions creates an Options\n\/\/ object with default values.\nfunc NewOptions() *Options {\n\treturn &Options{1024, 8192}\n}\n\n\/\/ BitVector is a bitmap with added data structure described by G. Navarro and\n\/\/ E. Providel's `A Structure for Plain Bitmaps: Combined Sampling` in \"Fast,\n\/\/ Small, Simple Rank\/Select on Bitmaps\" with some minor modifications.\n\/\/\n\/\/ See http:\/\/dcc.uchile.cl\/~gnavarro\/ps\/sea12.1.pdf for more details.\ntype BitVector struct {\n\tbits *bit.Array\n\n\t\/\/ ranks[i] is the number of 1s\n\t\/\/ from 0 to index (i*sr)-1\n\tranks []int\n\n\t\/\/ indices[i] points to the\n\t\/\/ beginning of the uint64 (LSB)\n\t\/\/ that contains the (i*ss)+1th\n\t\/\/ set bit.\n\tindices []int\n\n\tpopcount int\n\n\topts *Options\n}\n\n\/\/ NewBitVector creates a new BitVector.\nfunc NewBitVector(opts *Options) *BitVector {\n\tif opts == nil {\n\t\topts = NewOptions()\n\t}\n\n\tb := bit.NewArray(0)\n\trs := make([]int, 1)\n\tidx := make([]int, 1)\n\n\treturn &BitVector{\n\t\tbits:    b,\n\t\tranks:   rs,\n\t\tindices: idx,\n\t\topts:    opts,\n\t}\n}\n\n\/\/ Add appends the bits given its size to the vector.\nfunc (v *BitVector) Add(bits uint64, size int) {\n\tif size <= 0 || size > 64 {\n\t\tpanic(\"ranksel: bit size must be in range [1,64]\")\n\t}\n\n\t\/\/ Add bits\n\tv.bits.Add(bits, size)\n\tvlength := v.bits.Len()\n\n\t\/\/ Increment popcount\n\tpopcnt := bit.PopCount(bits)\n\tv.popcount += popcnt\n\n\t\/\/ Update rank sampling\n\tlenranks := len(v.ranks)\n\toverflow := vlength - (lenranks * v.opts.Sr)\n\tif overflow > 0 {\n\t\tv.ranks = append(v.ranks, 0)\n\n\t\trank := bit.Rank(bits, size-overflow-1)\n\t\tv.ranks[lenranks] = v.popcount - popcnt + rank\n\t}\n\n\t\/\/ Update select sampling\n\tlenidx := len(v.indices)\n\toverflow = v.popcount - (lenidx * v.opts.Ss)\n\tif overflow > 0 {\n\t\tv.indices = append(v.indices, 0)\n\n\t\tsel := bit.Select(bits, popcnt-overflow+1)\n\t\tv.indices[lenidx] = (vlength - size + sel) & ^0x3F\n\t}\n}\n\n\/\/ Get returns the uint64 representation of\n\/\/ bits starting from index idx given the bit size.\nfunc (v *BitVector) Get(idx, size int) uint64 {\n\treturn v.bits.Get(idx, size)\n}\n\n\/\/ Bit returns the bit value at index i.\nfunc (v *BitVector) Bit(i int) uint {\n\tif i >= v.bits.Len() {\n\t\tpanic(\"ranksel: index out of range\")\n\t}\n\n\tvbits := v.bits.Bits()\n\tif vbits[i>>6]&(1<<uint(i&63)) != 0 {\n\t\treturn 1\n\t}\n\treturn 0\n}\n\n\/\/ Rank1 counts the number of 1s from\n\/\/ the beginning up to the ith index.\nfunc (v *BitVector) Rank1(i int) int {\n\tif i >= v.bits.Len() {\n\t\tpanic(\"ranksel: index out of range\")\n\t}\n\n\tj := i \/ v.opts.Sr\n\tip := (j * v.opts.Sr) >> 6\n\trank := v.ranks[j]\n\n\taidx := i & 63\n\tbidx := i >> 6\n\tvbits := v.bits.Bits()\n\tfor _, b := range vbits[ip:bidx] {\n\t\trank += bit.PopCount(b)\n\t}\n\n\treturn rank + bit.Rank(vbits[bidx], aidx)\n}\n\n\/\/ Rank0 counts the number of 0s from\n\/\/ the beginning up to the ith index.\nfunc (v *BitVector) Rank0(i int) int {\n\treturn i - v.Rank1(i) + 1\n}\n\n\/\/ Select1 returns the index of the ith set bit.\n\/\/ Panics if i is zero or greater than the number\n\/\/ of set bits.\nfunc (v *BitVector) Select1(i int) int {\n\tif i > v.popcount {\n\t\tpanic(\"ranksel: input exceeds number of 1s\")\n\t} else if i == 0 {\n\t\tpanic(\"ranksel: input must be greater than 0\")\n\t}\n\n\tj := (i - 1) \/ v.opts.Ss\n\tq := v.indices[j] \/ v.opts.Sr\n\n\tk := 0\n\tr := 0\n\trq := v.ranks[q:]\n\tfor k, r = range rq {\n\t\tif r >= i {\n\t\t\tk--\n\t\t\tbreak\n\t\t}\n\t}\n\n\tidx := 0\n\trank := rq[k]\n\tvbits := v.bits.Bits()\n\taidx := ((q + k) * v.opts.Sr) >> 6\n\tfor ii, b := range vbits[aidx:] {\n\t\trank += bit.PopCount(b)\n\n\t\tif rank >= i {\n\t\t\toverflow := rank - i\n\t\t\tpopcnt := bit.PopCount(b)\n\n\t\t\tidx = (aidx + ii) << 6\n\t\t\tidx += bit.Select(b, popcnt-overflow)\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn idx\n}\n\n\/\/ Select0 returns the index of the ith zero. Panics\n\/\/ if i is zero or greater than the number of zeroes.\n\/\/ This is slower than Select1 in most cases.\nfunc (v *BitVector) Select0(i int) int {\n\tif i > (v.bits.Len() - v.popcount) {\n\t\tpanic(\"ranksel: input exceeds number of 0s\")\n\t} else if i == 0 {\n\t\tpanic(\"ranksel: input must be greater than 0\")\n\t}\n\n\t\/\/ Do a binary search on the rank samples to find\n\t\/\/ the largest rank sample that is less than i.\n\t\/\/ From https:\/\/en.wikipedia.org\/wiki\/Binary_search_algorithm\n\timin := 1\n\timax := len(v.ranks) - 1\n\tfor imin < imax {\n\t\timid := imin + ((imax - imin) >> 1)\n\n\t\trmid0 := (imid * v.opts.Sr) - v.ranks[imid]\n\t\tif rmid0 < i {\n\t\t\timin = imid + 1\n\t\t} else {\n\t\t\timax = imid\n\t\t}\n\t}\n\timin--\n\n\tidx := 0\n\tvbits := v.bits.Bits()\n\taidx := (imin * v.opts.Sr) >> 6\n\trank0 := (imin * v.opts.Sr) - v.ranks[imin]\n\tfor ii, b := range vbits[aidx:] {\n\t\tb = ^b\n\t\trank0 += bit.PopCount(b)\n\n\t\tif rank0 >= i {\n\t\t\toverflow := rank0 - i\n\t\t\tpopcnt := bit.PopCount(b)\n\n\t\t\tidx = (aidx + ii) << 6\n\t\t\tidx += bit.Select(b, popcnt-overflow)\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn idx\n}\n\nfunc checkErr(err ...error) error {\n\tfor _, e := range err {\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ GobEncode encodes this vector into gob streams.\nfunc (v *BitVector) GobEncode() ([]byte, error) {\n\tbuf := &bytes.Buffer{}\n\tenc := gob.NewEncoder(buf)\n\n\terr := checkErr(\n\t\tenc.Encode(v.bits),\n\t\tenc.Encode(v.ranks),\n\t\tenc.Encode(v.indices),\n\t\tenc.Encode(v.popcount),\n\t\tenc.Encode(v.opts),\n\t)\n\n\tif err != nil {\n\t\terr = fmt.Errorf(\"ranksel: encode failed (%v)\", err)\n\t}\n\n\treturn buf.Bytes(), err\n}\n\n\/\/ GobDecode populates this vector from gob streams.\nfunc (v *BitVector) GobDecode(data []byte) error {\n\tbuf := bytes.NewReader(data)\n\tdec := gob.NewDecoder(buf)\n\n\tv.opts = NewOptions()\n\tv.bits = bit.NewArray(0)\n\terr := checkErr(\n\t\tdec.Decode(v.bits),\n\t\tdec.Decode(&v.ranks),\n\t\tdec.Decode(&v.indices),\n\t\tdec.Decode(&v.popcount),\n\t\tdec.Decode(v.opts),\n\t)\n\n\tif err != nil {\n\t\terr = fmt.Errorf(\"ranksel: decode failed (%v)\", err)\n\t}\n\n\treturn err\n}\n\n\/\/ Len returns the number of bits stored.\nfunc (v *BitVector) Len() int {\n\treturn v.bits.Len()\n}\n\n\/\/ PopCount returns the total number of 1s.\nfunc (v *BitVector) PopCount() int {\n\treturn v.popcount\n}\n\n\/\/ Size returns the vector size in bytes.\nfunc (v *BitVector) Size() int {\n\tsizeofInt := int(unsafe.Sizeof(int(0)))\n\n\tsize := v.bits.Size()\n\tsize += len(v.ranks) * sizeofInt\n\tsize += len(v.indices) * sizeofInt\n\n\treturn size\n}\n\n\/\/ String returns a hexadecimal\n\/\/ string representation of the vector.\nfunc (v *BitVector) String() string {\n\treturn v.bits.String()\n}\n<|endoftext|>"}
{"text":"<commit_before>package gogadgets\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/cswank\/rex\"\n)\n\ntype Server struct {\n\thost        string\n\tmaster      string\n\tisMaster    bool\n\tport        int\n\tprefix      string\n\tlg          Logger\n\texternal    chan Message\n\tinternal    chan Message\n\tid          string\n\tupdates     map[string]Message\n\tseen        map[string]time.Time\n\tstatusLock  sync.Mutex\n\tseenLock    sync.Mutex\n\tclientsLock sync.Mutex\n\tclients     map[string]string\n}\n\nfunc NewServer(host, master string, port int, lg Logger) *Server {\n\tvar isMaster bool\n\tclients := map[string]string{}\n\tif master == \"\" {\n\t\tisMaster = true\n\t} else {\n\t\tclients = map[string]string{\n\t\t\tmaster: \"\",\n\t\t}\n\t}\n\treturn &Server{\n\t\tmaster:   master,\n\t\thost:     host,\n\t\tisMaster: isMaster,\n\t\tport:     port,\n\t\tlg:       lg,\n\t\tupdates:  map[string]Message{},\n\t\tid:       \"server\",\n\t\texternal: make(chan Message),\n\t\tseen:     map[string]time.Time{},\n\t\tclients:  clients,\n\t}\n}\n\nfunc (s *Server) Start(i <-chan Message, o chan<- Message) {\n\tif !s.isMaster {\n\t\tgo s.register()\n\t}\n\tgo s.startServer()\n\tgo s.cleanup()\n\n\tfor {\n\t\tselect {\n\t\tcase msg := <-i:\n\t\t\tif (msg.Type == UPDATE || msg.Type == METHODUPDATE) && s.isMaster {\n\t\t\t\ts.statusLock.Lock()\n\t\t\t\ts.updates[msg.Sender] = msg\n\t\t\t\ts.statusLock.Unlock()\n\t\t\t}\n\t\t\tif !s.isSeen(msg) {\n\t\t\t\ts.send(msg)\n\t\t\t}\n\t\tcase msg := <-s.external:\n\t\t\ts.setSeen(msg)\n\t\t\to <- msg\n\t\t\tif s.isMaster && msg.Sender == \"client\" {\n\t\t\t\ts.send(msg)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (s *Server) send(msg Message) {\n\ts.clientsLock.Lock()\n\tfor host, token := range s.clients {\n\t\tgo s.doSend(host, msg, token)\n\t}\n\ts.clientsLock.Unlock()\n}\n\nfunc (s *Server) doSend(host string, msg Message, token string) {\n\tmsg.Host = s.host\n\tvar buf bytes.Buffer\n\tenc := json.NewEncoder(&buf)\n\tenc.Encode(msg)\n\treq, err := http.NewRequest(\"POST\", host, &buf)\n\ts.clientsLock.Lock()\n\tdefer s.clientsLock.Unlock()\n\tif err != nil {\n\t\tdelete(s.clients, host)\n\t\tlog.Printf(\"error posting to quimby host: %s, err: %v\\n\", host, err)\n\t\treturn\n\t}\n\tif len(token) > 0 {\n\t\treq.Header.Add(\"Authorization\", token)\n\t}\n\tr, err := http.DefaultClient.Do(req)\n\tif r != nil {\n\t\tr.Body.Close()\n\t}\n\n\tif err != nil || r.StatusCode != http.StatusOK {\n\t\tdelete(s.clients, host)\n\t}\n}\n\nfunc (s *Server) setSeen(msg Message) {\n\ts.seenLock.Lock()\n\ts.seen[msg.UUID] = time.Now()\n\ts.seenLock.Unlock()\n}\n\nfunc (s *Server) isSeen(msg Message) bool {\n\ts.seenLock.Lock()\n\t_, ok := s.seen[msg.UUID]\n\ts.seenLock.Unlock()\n\treturn ok\n}\n\nfunc (s *Server) cleanup() {\n\tfor {\n\t\ttime.Sleep(60 * time.Second)\n\t\tnow := time.Now()\n\t\ts.seenLock.Lock()\n\t\tfor k, v := range s.seen {\n\t\t\tif v.Sub(now) > 10*time.Second {\n\t\t\t\tdelete(s.seen, k)\n\t\t\t}\n\t\t}\n\t\ts.seenLock.Unlock()\n\t}\n}\n\nfunc (s *Server) GetUID() string {\n\treturn s.id\n}\n\nfunc (s *Server) GetDirection() string {\n\treturn \"na\"\n}\n\nfunc (s *Server) startServer() {\n\tr := rex.New(\"main\")\n\tr.Get(\"\/gadgets\", http.HandlerFunc(s.status))\n\tr.Get(\"\/gadgets\/values\", http.HandlerFunc(s.values))\n\tr.Get(\"\/gadgets\/locations\/{location}\/devices\/{device}\/status\", http.HandlerFunc(s.deviceValue))\n\tr.Put(\"\/gadgets\", http.HandlerFunc(s.update))\n\tr.Post(\"\/gadgets\", http.HandlerFunc(s.update))\n\tif s.isMaster {\n\t\tr.Post(\"\/clients\", http.HandlerFunc(s.setClient))\n\t\tr.Get(\"\/clients\", http.HandlerFunc(s.getClients))\n\t\tr.Delete(\"\/clients\", http.HandlerFunc(s.removeClient))\n\t}\n\n\ts.lg.Printf(\"listening on 0.0.0.0:%d\\n\", s.port)\n\terr := http.ListenAndServe(fmt.Sprintf(\":%d\", s.port), r)\n\tif err != nil {\n\t\ts.lg.Fatal(err)\n\t}\n}\n\nfunc (s *Server) getClients(w http.ResponseWriter, r *http.Request) {\n\tenc := json.NewEncoder(w)\n\ts.clientsLock.Lock()\n\tif err := enc.Encode(s.clients); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n\ts.clientsLock.Unlock()\n}\n\nfunc (s *Server) setClient(w http.ResponseWriter, r *http.Request) {\n\tvar a map[string]string\n\tdec := json.NewDecoder(r.Body)\n\terr := dec.Decode(&a)\n\tif err != nil || len(a[\"address\"]) == 0 || len(a[\"token\"]) == 0 {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\ts.clientsLock.Lock()\n\ts.clients[a[\"address\"]] = a[\"token\"]\n\ts.clientsLock.Unlock()\n}\n\nfunc (s *Server) removeClient(w http.ResponseWriter, r *http.Request) {\n\ts.clientsLock.Lock()\n\tdelete(s.clients, r.URL.Host)\n\ts.clientsLock.Unlock()\n}\n\nfunc (s *Server) status(w http.ResponseWriter, r *http.Request) {\n\tenc := json.NewEncoder(w)\n\ts.statusLock.Lock()\n\tif err := enc.Encode(s.updates); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlg.Println(err)\n\t}\n\ts.statusLock.Unlock()\n}\n\nfunc (s *Server) deviceValue(w http.ResponseWriter, r *http.Request) {\n\tvars := rex.Vars(r, \"main\")\n\tk := fmt.Sprintf(\"%s %s\", vars[\"location\"], vars[\"device\"])\n\ts.statusLock.Lock()\n\tm, ok := s.updates[k]\n\ts.statusLock.Unlock()\n\tif !ok {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\tenc := json.NewEncoder(w)\n\tif err := enc.Encode(m.Value); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n}\n\nfunc (s *Server) values(w http.ResponseWriter, r *http.Request) {\n\tenc := json.NewEncoder(w)\n\ts.statusLock.Lock()\n\tv := map[string]map[string]Value{}\n\n\tfor _, msg := range s.updates {\n\t\tl, ok := v[msg.Location]\n\t\tif !ok {\n\t\t\tl = map[string]Value{}\n\t\t}\n\t\tl[msg.Name] = msg.Value\n\t\tv[msg.Location] = l\n\t}\n\ts.statusLock.Unlock()\n\tif err := enc.Encode(v); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlg.Println(err)\n\t}\n}\n\nfunc (s *Server) update(w http.ResponseWriter, r *http.Request) {\n\tvar msg Message\n\tdec := json.NewDecoder(r.Body)\n\tif err := dec.Decode(&msg); err != nil {\n\t\tlg.Println(err)\n\t\treturn\n\t}\n\tif msg.UUID == \"\" {\n\t\tmsg.UUID = GetUUID()\n\t}\n\ts.external <- msg\n}\n\n\/\/\nfunc (s *Server) register() {\n\tvar tries int\n\taddr := fmt.Sprintf(\"%s\/clients\", s.master)\n\ta := map[string]string{\"address\": fmt.Sprintf(\"%s\/gadgets\", s.host), \"token\": \"n\/a\"}\n\tfor {\n\t\tbuf := &bytes.Buffer{}\n\t\tenc := json.NewEncoder(buf)\n\t\tenc.Encode(&a)\n\t\tr, err := http.Post(addr, \"application\/json\", buf)\n\t\tif err == nil && r.StatusCode == http.StatusOK {\n\t\t\treturn\n\t\t}\n\t\ttries = increment(tries)\n\t\ttime.Sleep(time.Duration(tries) * 100 * time.Millisecond)\n\t}\n}\n\nfunc increment(i int) int {\n\tif i == 100 {\n\t\treturn i\n\t}\n\treturn i + 1\n}\n<commit_msg>discard request body<commit_after>package gogadgets\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/cswank\/rex\"\n)\n\ntype Server struct {\n\thost        string\n\tmaster      string\n\tisMaster    bool\n\tport        int\n\tprefix      string\n\tlg          Logger\n\texternal    chan Message\n\tinternal    chan Message\n\tid          string\n\tupdates     map[string]Message\n\tseen        map[string]time.Time\n\tstatusLock  sync.Mutex\n\tseenLock    sync.Mutex\n\tclientsLock sync.Mutex\n\tclients     map[string]string\n}\n\nfunc NewServer(host, master string, port int, lg Logger) *Server {\n\tvar isMaster bool\n\tclients := map[string]string{}\n\tif master == \"\" {\n\t\tisMaster = true\n\t} else {\n\t\tclients = map[string]string{\n\t\t\tmaster: \"\",\n\t\t}\n\t}\n\treturn &Server{\n\t\tmaster:   master,\n\t\thost:     host,\n\t\tisMaster: isMaster,\n\t\tport:     port,\n\t\tlg:       lg,\n\t\tupdates:  map[string]Message{},\n\t\tid:       \"server\",\n\t\texternal: make(chan Message),\n\t\tseen:     map[string]time.Time{},\n\t\tclients:  clients,\n\t}\n}\n\nfunc (s *Server) Start(i <-chan Message, o chan<- Message) {\n\tif !s.isMaster {\n\t\tgo s.register()\n\t}\n\tgo s.startServer()\n\tgo s.cleanup()\n\n\tfor {\n\t\tselect {\n\t\tcase msg := <-i:\n\t\t\tif (msg.Type == UPDATE || msg.Type == METHODUPDATE) && s.isMaster {\n\t\t\t\ts.statusLock.Lock()\n\t\t\t\ts.updates[msg.Sender] = msg\n\t\t\t\ts.statusLock.Unlock()\n\t\t\t}\n\t\t\tif !s.isSeen(msg) {\n\t\t\t\ts.send(msg)\n\t\t\t}\n\t\tcase msg := <-s.external:\n\t\t\ts.setSeen(msg)\n\t\t\to <- msg\n\t\t\tif s.isMaster && msg.Sender == \"client\" {\n\t\t\t\ts.send(msg)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (s *Server) send(msg Message) {\n\ts.clientsLock.Lock()\n\tfor host, token := range s.clients {\n\t\tgo s.doSend(host, msg, token)\n\t}\n\ts.clientsLock.Unlock()\n}\n\nfunc (s *Server) doSend(host string, msg Message, token string) {\n\tmsg.Host = s.host\n\tvar buf bytes.Buffer\n\tenc := json.NewEncoder(&buf)\n\tenc.Encode(msg)\n\treq, err := http.NewRequest(\"POST\", host, &buf)\n\ts.clientsLock.Lock()\n\tdefer s.clientsLock.Unlock()\n\tif err != nil {\n\t\tdelete(s.clients, host)\n\t\tlog.Printf(\"error posting to quimby host: %s, err: %v\\n\", host, err)\n\t\treturn\n\t}\n\tif len(token) > 0 {\n\t\treq.Header.Add(\"Authorization\", token)\n\t}\n\tr, err := http.DefaultClient.Do(req)\n\tif r != nil {\n\t\tr.Body.Close()\n\t}\n\n\tif err != nil || r.StatusCode != http.StatusOK {\n\t\tdelete(s.clients, host)\n\t}\n}\n\nfunc (s *Server) setSeen(msg Message) {\n\ts.seenLock.Lock()\n\ts.seen[msg.UUID] = time.Now()\n\ts.seenLock.Unlock()\n}\n\nfunc (s *Server) isSeen(msg Message) bool {\n\ts.seenLock.Lock()\n\t_, ok := s.seen[msg.UUID]\n\ts.seenLock.Unlock()\n\treturn ok\n}\n\nfunc (s *Server) cleanup() {\n\tfor {\n\t\ttime.Sleep(60 * time.Second)\n\t\tnow := time.Now()\n\t\ts.seenLock.Lock()\n\t\tfor k, v := range s.seen {\n\t\t\tif v.Sub(now) > 10*time.Second {\n\t\t\t\tdelete(s.seen, k)\n\t\t\t}\n\t\t}\n\t\ts.seenLock.Unlock()\n\t}\n}\n\nfunc (s *Server) GetUID() string {\n\treturn s.id\n}\n\nfunc (s *Server) GetDirection() string {\n\treturn \"na\"\n}\n\nfunc (s *Server) startServer() {\n\tr := rex.New(\"main\")\n\tr.Get(\"\/gadgets\", http.HandlerFunc(s.status))\n\tr.Get(\"\/gadgets\/values\", http.HandlerFunc(s.values))\n\tr.Get(\"\/gadgets\/locations\/{location}\/devices\/{device}\/status\", http.HandlerFunc(s.deviceValue))\n\tr.Put(\"\/gadgets\", http.HandlerFunc(s.update))\n\tr.Post(\"\/gadgets\", http.HandlerFunc(s.update))\n\tif s.isMaster {\n\t\tr.Post(\"\/clients\", http.HandlerFunc(s.setClient))\n\t\tr.Get(\"\/clients\", http.HandlerFunc(s.getClients))\n\t\tr.Delete(\"\/clients\", http.HandlerFunc(s.removeClient))\n\t}\n\n\ts.lg.Printf(\"listening on 0.0.0.0:%d\\n\", s.port)\n\terr := http.ListenAndServe(fmt.Sprintf(\":%d\", s.port), r)\n\tif err != nil {\n\t\ts.lg.Fatal(err)\n\t}\n}\n\nfunc (s *Server) getClients(w http.ResponseWriter, r *http.Request) {\n\tenc := json.NewEncoder(w)\n\ts.clientsLock.Lock()\n\tif err := enc.Encode(s.clients); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n\ts.clientsLock.Unlock()\n}\n\nfunc (s *Server) setClient(w http.ResponseWriter, r *http.Request) {\n\tvar a map[string]string\n\tdec := json.NewDecoder(r.Body)\n\terr := dec.Decode(&a)\n\tif err != nil || len(a[\"address\"]) == 0 || len(a[\"token\"]) == 0 {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\ts.clientsLock.Lock()\n\ts.clients[a[\"address\"]] = a[\"token\"]\n\ts.clientsLock.Unlock()\n}\n\nfunc (s *Server) removeClient(w http.ResponseWriter, r *http.Request) {\n\ts.clientsLock.Lock()\n\tdelete(s.clients, r.URL.Host)\n\ts.clientsLock.Unlock()\n}\n\nfunc (s *Server) status(w http.ResponseWriter, r *http.Request) {\n\tenc := json.NewEncoder(w)\n\ts.statusLock.Lock()\n\tif err := enc.Encode(s.updates); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlg.Println(err)\n\t}\n\ts.statusLock.Unlock()\n}\n\nfunc (s *Server) deviceValue(w http.ResponseWriter, r *http.Request) {\n\tvars := rex.Vars(r, \"main\")\n\tk := fmt.Sprintf(\"%s %s\", vars[\"location\"], vars[\"device\"])\n\ts.statusLock.Lock()\n\tm, ok := s.updates[k]\n\ts.statusLock.Unlock()\n\tif !ok {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\tenc := json.NewEncoder(w)\n\tif err := enc.Encode(m.Value); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n}\n\nfunc (s *Server) values(w http.ResponseWriter, r *http.Request) {\n\tenc := json.NewEncoder(w)\n\ts.statusLock.Lock()\n\tv := map[string]map[string]Value{}\n\n\tfor _, msg := range s.updates {\n\t\tl, ok := v[msg.Location]\n\t\tif !ok {\n\t\t\tl = map[string]Value{}\n\t\t}\n\t\tl[msg.Name] = msg.Value\n\t\tv[msg.Location] = l\n\t}\n\ts.statusLock.Unlock()\n\tif err := enc.Encode(v); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlg.Println(err)\n\t}\n}\n\nfunc (s *Server) update(w http.ResponseWriter, r *http.Request) {\n\tvar msg Message\n\tdec := json.NewDecoder(r.Body)\n\tif err := dec.Decode(&msg); err != nil {\n\t\tlg.Println(err)\n\t\treturn\n\t}\n\tif msg.UUID == \"\" {\n\t\tmsg.UUID = GetUUID()\n\t}\n\ts.external <- msg\n}\n\n\/\/\nfunc (s *Server) register() {\n\tvar tries int\n\taddr := fmt.Sprintf(\"%s\/clients\", s.master)\n\ta := map[string]string{\"address\": fmt.Sprintf(\"%s\/gadgets\", s.host), \"token\": \"n\/a\"}\n\tfor {\n\t\tbuf := &bytes.Buffer{}\n\t\tenc := json.NewEncoder(buf)\n\t\tenc.Encode(&a)\n\t\tr, err := http.Post(addr, \"application\/json\", buf)\n\t\tif err == nil && r.StatusCode == http.StatusOK {\n\t\t\treturn\n\t\t}\n\t\ttries = increment(tries)\n\t\ttime.Sleep(time.Duration(tries) * 100 * time.Millisecond)\n\t}\n}\n\nfunc increment(i int) int {\n\tif i == 100 {\n\t\treturn i\n\t}\n\treturn i + 1\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/smartystreets\/goconvey\/reporting\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc parsePackageResults(raw string) *PackageResult {\n\tparser := newOutputParser(raw)\n\treturn parser.Parse()\n}\n\nfunc newOutputParser(raw string) *outputParser {\n\tself := &outputParser{}\n\tself.raw = strings.TrimSpace(raw)\n\tself.lines = strings.Split(self.raw, \"\\n\")\n\tself.result = &PackageResult{}\n\tself.tests = []*TestResult{}\n\tself.result.TestResults = []TestResult{}\n\treturn self\n}\n\nfunc (self *outputParser) Parse() *PackageResult {\n\tself.gatherTestFunctionsAndMetadata()\n\tself.parseTestFunctions()\n\tself.attachTestFunctionsToResult()\n\treturn self.result\n}\n\nfunc (self *outputParser) gatherTestFunctionsAndMetadata() {\n\tfor _, self.line = range self.lines {\n\t\tself.processNextLine()\n\t}\n}\nfunc (self *outputParser) processNextLine() {\n\tif isNewTest(self.line) {\n\t\tself.registerTestFunction()\n\n\t} else if isTestResult(self.line) {\n\t\tself.recordTestMetadata()\n\n\t} else if isPackageReport(self.line) {\n\t\tself.recordPackageMetadata()\n\n\t} else {\n\t\tself.saveLineForParsingLater()\n\t}\n}\n\nfunc isNewTest(line string) bool {\n\treturn strings.HasPrefix(line, \"=== \")\n}\nfunc isTestResult(line string) bool {\n\treturn strings.HasPrefix(line, \"--- \")\n}\nfunc isPackageReport(line string) bool {\n\treturn (strings.HasPrefix(line, \"FAIL\") ||\n\t\tstrings.HasPrefix(line, \"exit status\") ||\n\t\tstrings.HasPrefix(line, \"PASS\") ||\n\t\tstrings.HasPrefix(line, \"ok  \\t\"))\n}\n\nfunc (self *outputParser) registerTestFunction() {\n\tself.test = &TestResult{}\n\tself.test.Stories = []reporting.ScopeResult{}\n\tself.test.rawLines = []string{}\n\tself.test.TestName = self.line[len(\"=== RUN \"):]\n\tself.tests = append(self.tests, self.test)\n}\nfunc (self *outputParser) recordTestMetadata() {\n\tself.test.Passed = strings.HasPrefix(self.line, \"--- PASS: \")\n\tself.test.Elapsed = parseTestFunctionDuration(self.line)\n}\nfunc (self *outputParser) saveLineForParsingLater() {\n\tself.line = strings.TrimSpace(self.line)\n\tself.line = strings.Replace(self.line, \"\\u0009\", \"\\t\", -1)\n\tself.test.rawLines = append(self.test.rawLines, self.line)\n}\nfunc (self *outputParser) recordPackageMetadata() {\n\tif strings.HasPrefix(self.line, \"FAIL\\t\") {\n\t\tself.parseLastLine()\n\t\tself.result.Passed = false\n\t} else if strings.HasPrefix(self.line, \"ok  \\t\") {\n\t\tself.parseLastLine()\n\t\tself.result.Passed = true\n\t}\n}\nfunc (self *outputParser) parseLastLine() {\n\tfields := strings.Split(self.line, \"\\t\")\n\tself.result.PackageName = strings.TrimSpace(fields[1])\n\tself.result.Elapsed = parseDurationInSeconds(fields[2], 3)\n}\n\nfunc (self *outputParser) parseTestFunctions() {\n\tfor _, self.test = range self.tests {\n\t\tif len(self.test.rawLines) == 0 {\n\t\t\tcontinue\n\t\t} else if isJson(self.test.rawLines[0]) {\n\t\t\tself.deserializeScopes()\n\t\t} else {\n\t\t\tself.parseGoTestMessage()\n\t\t}\n\t}\n}\nfunc isJson(line string) bool {\n\treturn strings.HasPrefix(line, \"{\")\n}\nfunc (self *outputParser) deserializeScopes() {\n\t\/\/ TODO: clean up!\n\trawJson := strings.Join(self.test.rawLines, \"\")\n\tvar scopes []reporting.ScopeResult\n\tif strings.HasSuffix(rawJson, \",\") { \/\/ Shouldn't need this...\n\t\trawJson = rawJson[:len(rawJson)-1]\n\t}\n\trawJson = \"[\" + rawJson + \"]\"\n\terr := json.Unmarshal([]byte(rawJson), &scopes)\n\tif err != nil {\n\t\tfmt.Println(err) \/\/ panic?\n\t}\n\tself.test.Stories = scopes\n}\nfunc (self *outputParser) parseGoTestMessage() {\n\t\/\/ TODO: clean up!\n\tif strings.HasPrefix(self.test.rawLines[0], \"panic: \") {\n\t\tfor i, line := range self.test.rawLines {\n\t\t\tif strings.HasPrefix(line, \"goroutine\") && strings.Contains(line, \"[running]\") {\n\t\t\t\tmetaLine := self.test.rawLines[i+4]\n\t\t\t\tfields := strings.Split(metaLine, \" \")\n\t\t\t\tfileAndLine := strings.Split(fields[0], \":\")\n\t\t\t\tself.test.File = fileAndLine[0]\n\t\t\t\tself.test.Line, _ = strconv.Atoi(fileAndLine[1])\n\t\t\t}\n\t\t\tif strings.Contains(line, \"+\") || (i > 0 && strings.Contains(line, \"panic: \")) {\n\t\t\t\tself.test.rawLines[i] = \"\\t\" + line\n\t\t\t}\n\t\t}\n\t\tself.test.Error = strings.Join(self.test.rawLines, \"\\n\")\n\t} else {\n\t\tlineFields := self.test.rawLines[0]\n\t\tfields := strings.Split(lineFields, \":\")\n\t\tself.test.File = strings.TrimSpace(fields[0])\n\t\tself.test.Line, _ = strconv.Atoi(fields[1])\n\t\tself.test.Message = strings.TrimSpace(fields[2])\n\t\tif len(self.test.rawLines) > 1 {\n\t\t\tadditionalLines := strings.Join(self.test.rawLines[1:], \"\\n\")\n\t\t\tself.test.Message = self.test.Message + \"\\n\" + additionalLines\n\t\t}\n\t}\n}\n\nfunc (self *outputParser) attachTestFunctionsToResult() {\n\tfor _, test := range self.tests {\n\t\ttest.rawLines = []string{}\n\t\tself.result.TestResults = append(self.result.TestResults, *test)\n\t}\n}\n\ntype outputParser struct {\n\traw    string\n\tlines  []string\n\tresult *PackageResult\n\ttests  []*TestResult\n\n\t\/\/ place holders for loops\n\tline string\n\ttest *TestResult\n}\n\ntype PackageResult struct {\n\tPackageName string\n\tElapsed     float64\n\tPassed      bool\n\tTestResults []TestResult\n}\n\ntype TestResult struct {\n\tTestName string\n\tElapsed  float64\n\tPassed   bool\n\tFile     string\n\tLine     int\n\tMessage  string\n\tError    string\n\tStories  []reporting.ScopeResult\n\n\trawLines []string\n}\n<commit_msg>Accounting for package with no test files.<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/smartystreets\/goconvey\/reporting\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc parsePackageResults(raw string) *PackageResult {\n\tparser := newOutputParser(raw)\n\treturn parser.Parse()\n}\n\nfunc newOutputParser(raw string) *outputParser {\n\tself := &outputParser{}\n\tself.raw = strings.TrimSpace(raw)\n\tself.lines = strings.Split(self.raw, \"\\n\")\n\tself.result = &PackageResult{}\n\tself.tests = []*TestResult{}\n\tself.result.TestResults = []TestResult{}\n\treturn self\n}\n\nfunc (self *outputParser) Parse() *PackageResult {\n\tself.gatherTestFunctionsAndMetadata()\n\tself.parseTestFunctions()\n\tself.attachTestFunctionsToResult()\n\treturn self.result\n}\n\nfunc (self *outputParser) gatherTestFunctionsAndMetadata() {\n\tfor _, self.line = range self.lines {\n\t\tself.processNextLine()\n\t}\n}\nfunc (self *outputParser) processNextLine() {\n\tif noTestsRun(self.line) {\n\t\tself.recordEmptyPackage()\n\n\t} else if isNewTest(self.line) {\n\t\tself.registerTestFunction()\n\n\t} else if isTestResult(self.line) {\n\t\tself.recordTestMetadata()\n\n\t} else if isPackageReport(self.line) {\n\t\tself.recordPackageMetadata()\n\n\t} else {\n\t\tself.saveLineForParsingLater()\n\t}\n}\n\nfunc noTestsRun(line string) bool {\n\t\/\/ TEST INPUT:\n\t\/\/ ?   \tpkg.smartystreets.net\/liveaddress-zipapi\t[no test files]\n\treturn strings.HasPrefix(line, \"?\") && strings.Contains(line, \"[no test files]\")\n}\n\nfunc isNewTest(line string) bool {\n\treturn strings.HasPrefix(line, \"=== \")\n}\nfunc isTestResult(line string) bool {\n\treturn strings.HasPrefix(line, \"--- \")\n}\nfunc isPackageReport(line string) bool {\n\treturn (strings.HasPrefix(line, \"FAIL\") ||\n\t\tstrings.HasPrefix(line, \"exit status\") ||\n\t\tstrings.HasPrefix(line, \"PASS\") ||\n\t\tstrings.HasPrefix(line, \"ok  \\t\"))\n}\n\nfunc (self *outputParser) recordEmptyPackage() {\n\tfields := strings.Split(self.line, \"\\t\")\n\tself.result.PackageName = fields[1]\n}\n\nfunc (self *outputParser) registerTestFunction() {\n\tself.test = &TestResult{}\n\tself.test.Stories = []reporting.ScopeResult{}\n\tself.test.rawLines = []string{}\n\tself.test.TestName = self.line[len(\"=== RUN \"):]\n\tself.tests = append(self.tests, self.test)\n}\nfunc (self *outputParser) recordTestMetadata() {\n\tself.test.Passed = strings.HasPrefix(self.line, \"--- PASS: \")\n\tself.test.Elapsed = parseTestFunctionDuration(self.line)\n}\nfunc (self *outputParser) saveLineForParsingLater() {\n\tself.line = strings.TrimSpace(self.line)\n\tself.line = strings.Replace(self.line, \"\\u0009\", \"\\t\", -1)\n\tself.test.rawLines = append(self.test.rawLines, self.line)\n}\nfunc (self *outputParser) recordPackageMetadata() {\n\tif strings.HasPrefix(self.line, \"FAIL\\t\") {\n\t\tself.parseLastLine()\n\t\tself.result.Passed = false\n\t} else if strings.HasPrefix(self.line, \"ok  \\t\") {\n\t\tself.parseLastLine()\n\t\tself.result.Passed = true\n\t}\n}\nfunc (self *outputParser) parseLastLine() {\n\tfields := strings.Split(self.line, \"\\t\")\n\tself.result.PackageName = strings.TrimSpace(fields[1])\n\tself.result.Elapsed = parseDurationInSeconds(fields[2], 3)\n}\n\nfunc (self *outputParser) parseTestFunctions() {\n\tfor _, self.test = range self.tests {\n\t\tif len(self.test.rawLines) == 0 {\n\t\t\tcontinue\n\t\t} else if isJson(self.test.rawLines[0]) {\n\t\t\tself.deserializeScopes()\n\t\t} else {\n\t\t\tself.parseGoTestMessage()\n\t\t}\n\t}\n}\nfunc isJson(line string) bool {\n\treturn strings.HasPrefix(line, \"{\")\n}\nfunc (self *outputParser) deserializeScopes() {\n\t\/\/ TODO: clean up!\n\trawJson := strings.Join(self.test.rawLines, \"\")\n\tvar scopes []reporting.ScopeResult\n\tif strings.HasSuffix(rawJson, \",\") { \/\/ Shouldn't need this...\n\t\trawJson = rawJson[:len(rawJson)-1]\n\t}\n\trawJson = \"[\" + rawJson + \"]\"\n\terr := json.Unmarshal([]byte(rawJson), &scopes)\n\tif err != nil {\n\t\tfmt.Println(err) \/\/ panic?\n\t}\n\tself.test.Stories = scopes\n}\nfunc (self *outputParser) parseGoTestMessage() {\n\t\/\/ TODO: clean up!\n\tif strings.HasPrefix(self.test.rawLines[0], \"panic: \") {\n\t\tfor i, line := range self.test.rawLines {\n\t\t\tif strings.HasPrefix(line, \"goroutine\") && strings.Contains(line, \"[running]\") {\n\t\t\t\tmetaLine := self.test.rawLines[i+4]\n\t\t\t\tfields := strings.Split(metaLine, \" \")\n\t\t\t\tfileAndLine := strings.Split(fields[0], \":\")\n\t\t\t\tself.test.File = fileAndLine[0]\n\t\t\t\tself.test.Line, _ = strconv.Atoi(fileAndLine[1])\n\t\t\t}\n\t\t\tif strings.Contains(line, \"+\") || (i > 0 && strings.Contains(line, \"panic: \")) {\n\t\t\t\tself.test.rawLines[i] = \"\\t\" + line\n\t\t\t}\n\t\t}\n\t\tself.test.Error = strings.Join(self.test.rawLines, \"\\n\")\n\t} else {\n\t\tlineFields := self.test.rawLines[0]\n\t\tfields := strings.Split(lineFields, \":\")\n\t\tself.test.File = strings.TrimSpace(fields[0])\n\t\tself.test.Line, _ = strconv.Atoi(fields[1])\n\t\tself.test.Message = strings.TrimSpace(fields[2])\n\t\tif len(self.test.rawLines) > 1 {\n\t\t\tadditionalLines := strings.Join(self.test.rawLines[1:], \"\\n\")\n\t\t\tself.test.Message = self.test.Message + \"\\n\" + additionalLines\n\t\t}\n\t}\n}\n\nfunc (self *outputParser) attachTestFunctionsToResult() {\n\tfor _, test := range self.tests {\n\t\ttest.rawLines = []string{}\n\t\tself.result.TestResults = append(self.result.TestResults, *test)\n\t}\n}\n\ntype outputParser struct {\n\traw    string\n\tlines  []string\n\tresult *PackageResult\n\ttests  []*TestResult\n\n\t\/\/ place holders for loops\n\tline string\n\ttest *TestResult\n}\n\ntype PackageResult struct {\n\tPackageName string\n\tElapsed     float64\n\tPassed      bool\n\tTestResults []TestResult\n}\n\ntype TestResult struct {\n\tTestName string\n\tElapsed  float64\n\tPassed   bool\n\tFile     string\n\tLine     int\n\tMessage  string\n\tError    string\n\tStories  []reporting.ScopeResult\n\n\trawLines []string\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package grpc supports network connections to GRPC servers.\n\/\/ This package is not intended for use by end developers. Use the\n\/\/ google.golang.org\/api\/option package to configure API clients.\npackage grpc\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"go.opencensus.io\/plugin\/ocgrpc\"\n\t\"golang.org\/x\/oauth2\"\n\t\"google.golang.org\/api\/internal\"\n\t\"google.golang.org\/api\/option\"\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/credentials\"\n\tgrpcgoogle \"google.golang.org\/grpc\/credentials\/google\"\n\t\"google.golang.org\/grpc\/credentials\/oauth\"\n\n\t\/\/ Install grpclb, which is required for direct path.\n\t_ \"google.golang.org\/grpc\/balancer\/grpclb\"\n)\n\n\/\/ Set at init time by dial_appengine.go. If nil, we're not on App Engine.\nvar appengineDialerHook func(context.Context) grpc.DialOption\n\n\/\/ Dial returns a GRPC connection for use communicating with a Google cloud\n\/\/ service, configured with the given ClientOptions.\nfunc Dial(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) {\n\treturn dial(ctx, false, opts)\n}\n\n\/\/ DialInsecure returns an insecure GRPC connection for use communicating\n\/\/ with fake or mock Google cloud service implementations, such as emulators.\n\/\/ The connection is configured with the given ClientOptions.\nfunc DialInsecure(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) {\n\treturn dial(ctx, true, opts)\n}\n\nfunc dial(ctx context.Context, insecure bool, opts []option.ClientOption) (*grpc.ClientConn, error) {\n\tvar o internal.DialSettings\n\tfor _, opt := range opts {\n\t\topt.Apply(&o)\n\t}\n\tif err := o.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tif o.HTTPClient != nil {\n\t\treturn nil, errors.New(\"unsupported HTTP client specified\")\n\t}\n\tif o.GRPCConn != nil {\n\t\treturn o.GRPCConn, nil\n\t}\n\tvar grpcOpts []grpc.DialOption\n\tif insecure {\n\t\tgrpcOpts = []grpc.DialOption{grpc.WithInsecure()}\n\t} else if !o.NoAuth {\n\t\tif o.APIKey != \"\" {\n\t\t\tlog.Print(\"API keys are not supported for gRPC APIs. Remove the WithAPIKey option from your client-creating call.\")\n\t\t}\n\t\tcreds, err := internal.Creds(ctx, &o)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ Attempt Direct Path only if:\n\t\t\/\/ * The endpoint is a host:port (or dns:\/\/\/host:port).\n\t\t\/\/ * Credentials are obtained via GCE metadata server, using the default\n\t\t\/\/   service account.\n\t\t\/\/ * Opted in via GOOGLE_CLOUD_ENABLE_DIRECT_PATH environment variable.\n\t\t\/\/   For example, GOOGLE_CLOUD_ENABLE_DIRECT_PATH=spanner,pubsub\n\t\tif isDirectPathEnabled(o.Endpoint) && isTokenSourceDirectPathCompatible(creds.TokenSource) {\n\t\t\tif !strings.HasPrefix(o.Endpoint, \"dns:\/\/\/\") {\n\t\t\t\to.Endpoint = \"dns:\/\/\/\" + o.Endpoint\n\t\t\t}\n\t\t\tgrpcOpts = []grpc.DialOption{\n\t\t\t\tgrpc.WithCredentialsBundle(\n\t\t\t\t\tgrpcgoogle.NewComputeEngineCredentials(),\n\t\t\t\t),\n\t\t\t}\n\t\t\t\/\/ TODO(cbro): add support for system parameters (quota project, request reason) via chained interceptor.\n\t\t} else {\n\t\t\tgrpcOpts = []grpc.DialOption{\n\t\t\t\tgrpc.WithPerRPCCredentials(grpcTokenSource{\n\t\t\t\t\tTokenSource:   oauth.TokenSource{creds.TokenSource},\n\t\t\t\t\tquotaProject:  o.QuotaProject,\n\t\t\t\t\trequestReason: o.RequestReason,\n\t\t\t\t}),\n\t\t\t\tgrpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, \"\")),\n\t\t\t}\n\t\t}\n\t}\n\tif appengineDialerHook != nil {\n\t\t\/\/ Use the Socket API on App Engine.\n\t\tgrpcOpts = append(grpcOpts, appengineDialerHook(ctx))\n\t}\n\t\/\/ Add tracing, but before the other options, so that clients can override the\n\t\/\/ gRPC stats handler.\n\t\/\/ This assumes that gRPC options are processed in order, left to right.\n\tgrpcOpts = addOCStatsHandler(grpcOpts)\n\tgrpcOpts = append(grpcOpts, o.GRPCDialOpts...)\n\tif o.UserAgent != \"\" {\n\t\tgrpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent))\n\t}\n\treturn grpc.DialContext(ctx, o.Endpoint, grpcOpts...)\n}\n\nfunc addOCStatsHandler(opts []grpc.DialOption) []grpc.DialOption {\n\treturn append(opts, grpc.WithStatsHandler(&ocgrpc.ClientHandler{}))\n}\n\n\/\/ grpcTokenSource supplies PerRPCCredentials from an oauth.TokenSource.\ntype grpcTokenSource struct {\n\toauth.TokenSource\n\n\t\/\/ Additional metadata attached as headers.\n\tquotaProject  string\n\trequestReason string\n}\n\n\/\/ GetRequestMetadata gets the request metadata as a map from a grpcTokenSource.\nfunc (ts grpcTokenSource) GetRequestMetadata(ctx context.Context, uri ...string) (\n\tmap[string]string, error) {\n\tmetadata, err := ts.TokenSource.GetRequestMetadata(ctx, uri...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Attach system parameters into the metadata\n\tif ts.quotaProject != \"\" {\n\t\tmetadata[\"X-goog-user-project\"] = ts.quotaProject\n\t}\n\tif ts.requestReason != \"\" {\n\t\tmetadata[\"X-goog-request-reason\"] = ts.requestReason\n\t}\n\treturn metadata, nil\n}\n\nfunc isTokenSourceDirectPathCompatible(ts oauth2.TokenSource) bool {\n\tif ts == nil {\n\t\treturn false\n\t}\n\ttok, err := ts.Token()\n\tif err != nil {\n\t\treturn false\n\t}\n\tif tok == nil {\n\t\treturn false\n\t}\n\tif source, _ := tok.Extra(\"oauth2.google.tokenSource\").(string); source != \"compute-metadata\" {\n\t\treturn false\n\t}\n\tif acct, _ := tok.Extra(\"oauth2.google.serviceAccount\").(string); acct != \"default\" {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc isDirectPathEnabled(endpoint string) bool {\n\t\/\/ Only host:port is supported, not other schemes (e.g., \"tcp:\/\/\" or \"unix:\/\/\").\n\t\/\/ Also don't try direct path if the user has chosen an alternate name resolver\n\t\/\/ (i.e., via \":\/\/\/\" prefix).\n\t\/\/\n\t\/\/ TODO(cbro): once gRPC has introspectible options, check the user hasn't\n\t\/\/ provided a custom dialer in gRPC options.\n\tif strings.Contains(endpoint, \":\/\/\") && !strings.HasPrefix(endpoint, \"dns:\/\/\/\") {\n\t\treturn false\n\t}\n\n\t\/\/ Only try direct path if the user has opted in via the environment variable.\n\twhitelist := strings.Split(os.Getenv(\"GOOGLE_CLOUD_ENABLE_DIRECT_PATH\"), \",\")\n\tfor _, api := range whitelist {\n\t\tif strings.Contains(endpoint, api) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>transport\/grpc: Fix check of GOOGLE_CLOUD_ENABLE_DIRECT_PATH<commit_after>\/\/ Copyright 2015 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package grpc supports network connections to GRPC servers.\n\/\/ This package is not intended for use by end developers. Use the\n\/\/ google.golang.org\/api\/option package to configure API clients.\npackage grpc\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"go.opencensus.io\/plugin\/ocgrpc\"\n\t\"golang.org\/x\/oauth2\"\n\t\"google.golang.org\/api\/internal\"\n\t\"google.golang.org\/api\/option\"\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/credentials\"\n\tgrpcgoogle \"google.golang.org\/grpc\/credentials\/google\"\n\t\"google.golang.org\/grpc\/credentials\/oauth\"\n\n\t\/\/ Install grpclb, which is required for direct path.\n\t_ \"google.golang.org\/grpc\/balancer\/grpclb\"\n)\n\n\/\/ Set at init time by dial_appengine.go. If nil, we're not on App Engine.\nvar appengineDialerHook func(context.Context) grpc.DialOption\n\n\/\/ Dial returns a GRPC connection for use communicating with a Google cloud\n\/\/ service, configured with the given ClientOptions.\nfunc Dial(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) {\n\treturn dial(ctx, false, opts)\n}\n\n\/\/ DialInsecure returns an insecure GRPC connection for use communicating\n\/\/ with fake or mock Google cloud service implementations, such as emulators.\n\/\/ The connection is configured with the given ClientOptions.\nfunc DialInsecure(ctx context.Context, opts ...option.ClientOption) (*grpc.ClientConn, error) {\n\treturn dial(ctx, true, opts)\n}\n\nfunc dial(ctx context.Context, insecure bool, opts []option.ClientOption) (*grpc.ClientConn, error) {\n\tvar o internal.DialSettings\n\tfor _, opt := range opts {\n\t\topt.Apply(&o)\n\t}\n\tif err := o.Validate(); err != nil {\n\t\treturn nil, err\n\t}\n\tif o.HTTPClient != nil {\n\t\treturn nil, errors.New(\"unsupported HTTP client specified\")\n\t}\n\tif o.GRPCConn != nil {\n\t\treturn o.GRPCConn, nil\n\t}\n\tvar grpcOpts []grpc.DialOption\n\tif insecure {\n\t\tgrpcOpts = []grpc.DialOption{grpc.WithInsecure()}\n\t} else if !o.NoAuth {\n\t\tif o.APIKey != \"\" {\n\t\t\tlog.Print(\"API keys are not supported for gRPC APIs. Remove the WithAPIKey option from your client-creating call.\")\n\t\t}\n\t\tcreds, err := internal.Creds(ctx, &o)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ Attempt Direct Path only if:\n\t\t\/\/ * The endpoint is a host:port (or dns:\/\/\/host:port).\n\t\t\/\/ * Credentials are obtained via GCE metadata server, using the default\n\t\t\/\/   service account.\n\t\t\/\/ * Opted in via GOOGLE_CLOUD_ENABLE_DIRECT_PATH environment variable.\n\t\t\/\/   For example, GOOGLE_CLOUD_ENABLE_DIRECT_PATH=spanner,pubsub\n\t\tif isDirectPathEnabled(o.Endpoint) && isTokenSourceDirectPathCompatible(creds.TokenSource) {\n\t\t\tif !strings.HasPrefix(o.Endpoint, \"dns:\/\/\/\") {\n\t\t\t\to.Endpoint = \"dns:\/\/\/\" + o.Endpoint\n\t\t\t}\n\t\t\tgrpcOpts = []grpc.DialOption{\n\t\t\t\tgrpc.WithCredentialsBundle(\n\t\t\t\t\tgrpcgoogle.NewComputeEngineCredentials(),\n\t\t\t\t),\n\t\t\t}\n\t\t\t\/\/ TODO(cbro): add support for system parameters (quota project, request reason) via chained interceptor.\n\t\t} else {\n\t\t\tgrpcOpts = []grpc.DialOption{\n\t\t\t\tgrpc.WithPerRPCCredentials(grpcTokenSource{\n\t\t\t\t\tTokenSource:   oauth.TokenSource{creds.TokenSource},\n\t\t\t\t\tquotaProject:  o.QuotaProject,\n\t\t\t\t\trequestReason: o.RequestReason,\n\t\t\t\t}),\n\t\t\t\tgrpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, \"\")),\n\t\t\t}\n\t\t}\n\t}\n\tif appengineDialerHook != nil {\n\t\t\/\/ Use the Socket API on App Engine.\n\t\tgrpcOpts = append(grpcOpts, appengineDialerHook(ctx))\n\t}\n\t\/\/ Add tracing, but before the other options, so that clients can override the\n\t\/\/ gRPC stats handler.\n\t\/\/ This assumes that gRPC options are processed in order, left to right.\n\tgrpcOpts = addOCStatsHandler(grpcOpts)\n\tgrpcOpts = append(grpcOpts, o.GRPCDialOpts...)\n\tif o.UserAgent != \"\" {\n\t\tgrpcOpts = append(grpcOpts, grpc.WithUserAgent(o.UserAgent))\n\t}\n\treturn grpc.DialContext(ctx, o.Endpoint, grpcOpts...)\n}\n\nfunc addOCStatsHandler(opts []grpc.DialOption) []grpc.DialOption {\n\treturn append(opts, grpc.WithStatsHandler(&ocgrpc.ClientHandler{}))\n}\n\n\/\/ grpcTokenSource supplies PerRPCCredentials from an oauth.TokenSource.\ntype grpcTokenSource struct {\n\toauth.TokenSource\n\n\t\/\/ Additional metadata attached as headers.\n\tquotaProject  string\n\trequestReason string\n}\n\n\/\/ GetRequestMetadata gets the request metadata as a map from a grpcTokenSource.\nfunc (ts grpcTokenSource) GetRequestMetadata(ctx context.Context, uri ...string) (\n\tmap[string]string, error) {\n\tmetadata, err := ts.TokenSource.GetRequestMetadata(ctx, uri...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Attach system parameters into the metadata\n\tif ts.quotaProject != \"\" {\n\t\tmetadata[\"X-goog-user-project\"] = ts.quotaProject\n\t}\n\tif ts.requestReason != \"\" {\n\t\tmetadata[\"X-goog-request-reason\"] = ts.requestReason\n\t}\n\treturn metadata, nil\n}\n\nfunc isTokenSourceDirectPathCompatible(ts oauth2.TokenSource) bool {\n\tif ts == nil {\n\t\treturn false\n\t}\n\ttok, err := ts.Token()\n\tif err != nil {\n\t\treturn false\n\t}\n\tif tok == nil {\n\t\treturn false\n\t}\n\tif source, _ := tok.Extra(\"oauth2.google.tokenSource\").(string); source != \"compute-metadata\" {\n\t\treturn false\n\t}\n\tif acct, _ := tok.Extra(\"oauth2.google.serviceAccount\").(string); acct != \"default\" {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc isDirectPathEnabled(endpoint string) bool {\n\t\/\/ Only host:port is supported, not other schemes (e.g., \"tcp:\/\/\" or \"unix:\/\/\").\n\t\/\/ Also don't try direct path if the user has chosen an alternate name resolver\n\t\/\/ (i.e., via \":\/\/\/\" prefix).\n\t\/\/\n\t\/\/ TODO(cbro): once gRPC has introspectible options, check the user hasn't\n\t\/\/ provided a custom dialer in gRPC options.\n\tif strings.Contains(endpoint, \":\/\/\") && !strings.HasPrefix(endpoint, \"dns:\/\/\/\") {\n\t\treturn false\n\t}\n\n\t\/\/ Only try direct path if the user has opted in via the environment variable.\n\twhitelist := strings.Split(os.Getenv(\"GOOGLE_CLOUD_ENABLE_DIRECT_PATH\"), \",\")\n\tfor _, api := range whitelist {\n\t\t\/\/ Ignore empty string since an empty env variable splits into [\"\"]\n\t\tif api != \"\" && strings.Contains(endpoint, api) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Monax Industries Limited\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage client\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/tendermint\/go-rpc\/client\"\n\t\"github.com\/tendermint\/go-wire\"\n\n\t\"github.com\/monax\/eris-db\/logging\"\n\t\"github.com\/monax\/eris-db\/logging\/loggers\"\n\tctypes \"github.com\/monax\/eris-db\/rpc\/tendermint\/core\/types\"\n\t\"github.com\/monax\/eris-db\/txs\"\n)\n\nconst (\n\tMaxCommitWaitTimeSeconds = 10\n)\n\ntype Confirmation struct {\n\tBlockHash []byte\n\tEvent     txs.EventData\n\tException error\n\tError     error\n}\n\n\/\/ NOTE [ben] Compiler check to ensure erisNodeClient successfully implements\n\/\/ eris-db\/client.NodeClient\nvar _ NodeWebsocketClient = (*erisNodeWebsocketClient)(nil)\n\ntype erisNodeWebsocketClient struct {\n\t\/\/ TODO: assert no memory leak on closing with open websocket\n\ttendermintWebsocket *rpcclient.WSClient\n\tlogger              loggers.InfoTraceLogger\n}\n\n\/\/ Subscribe to an eventid\nfunc (erisNodeWebsocketClient *erisNodeWebsocketClient) Subscribe(eventid string) error {\n\t\/\/ TODO we can in the background listen to the subscription id and remember it to ease unsubscribing later.\n\treturn erisNodeWebsocketClient.tendermintWebsocket.Subscribe(eventid)\n}\n\n\/\/ Unsubscribe from an eventid\nfunc (erisNodeWebsocketClient *erisNodeWebsocketClient) Unsubscribe(subscriptionId string) error {\n\treturn erisNodeWebsocketClient.tendermintWebsocket.Unsubscribe(subscriptionId)\n}\n\n\/\/ Returns a channel that will receive a confirmation with a result or the exception that\n\/\/ has been confirmed; or an error is returned and the confirmation channel is nil.\nfunc (erisNodeWebsocketClient *erisNodeWebsocketClient) WaitForConfirmation(tx txs.Tx, chainId string, inputAddr []byte) (chan Confirmation, error) {\n\t\/\/ check no errors are reported on the websocket\n\tif err := erisNodeWebsocketClient.assertNoErrors(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Setup the confirmation channel to be returned\n\tconfirmationChannel := make(chan Confirmation, 1)\n\tvar latestBlockHash []byte\n\n\teid := txs.EventStringAccInput(inputAddr)\n\tif err := erisNodeWebsocketClient.tendermintWebsocket.Subscribe(eid); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error subscribing to AccInput event (%s): %v\", eid, err)\n\t}\n\tif err := erisNodeWebsocketClient.tendermintWebsocket.Subscribe(txs.EventStringNewBlock()); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error subscribing to NewBlock event: %v\", err)\n\t}\n\t\/\/ Read the incoming events\n\tgo func() {\n\t\tvar err error\n\t\tfor {\n\t\t\tresultBytes := <-erisNodeWebsocketClient.tendermintWebsocket.ResultsCh\n\t\t\tresult := new(ctypes.ErisDBResult)\n\t\t\tif wire.ReadJSONPtr(result, resultBytes, &err); err != nil {\n\t\t\t\t\/\/ keep calm and carry on\n\t\t\t\tlogging.InfoMsg(erisNodeWebsocketClient.logger, \"Failed to unmarshal json bytes for websocket event\",\n\t\t\t\t\t\"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsubscription, ok := (*result).(*ctypes.ResultSubscribe)\n\t\t\tif ok {\n\t\t\t\t\/\/ Received confirmation of subscription to event streams\n\t\t\t\t\/\/ TODO: collect subscription IDs, push into channel and on completion\n\t\t\t\t\/\/ unsubscribe\n\t\t\t\tlogging.InfoMsg(erisNodeWebsocketClient.logger, \"Received confirmation for event\",\n\t\t\t\t\t\"event\", subscription.Event,\n\t\t\t\t\t\"subscription_id\", subscription.SubscriptionId)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tevent, ok := (*result).(*ctypes.ResultEvent)\n\t\t\tif !ok {\n\t\t\t\t\/\/ keep calm and carry on\n\t\t\t\tlogging.InfoMsg(erisNodeWebsocketClient.logger, \"Failed to cast to ResultEvent for websocket event\",\n\t\t\t\t\t\"event\", event.Event)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ NOTE: [ben] hotfix on 0.16.1 because NewBlock events looks to arrive late\n\t\t\t\/\/ both in tests; so we now miss events;  This check is safely removed because\n\t\t\t\/\/ for CallTx on checking the transaction the EVM is not run and no false positive event\n\t\t\t\/\/ is sent; neither is this check a good check for that.\n\n\t\t\t\/\/ blockData, ok := event.Data.(txs.EventDataNewBlock)\n\t\t\t\/\/ if ok {\n\t\t\t\/\/ \tlatestBlockHash = blockData.Block.Hash()\n\t\t\t\/\/ \tlogging.TraceMsg(erisNodeWebsocketClient.logger, \"Registered new block\",\n\t\t\t\/\/ \t\t\"block\", blockData.Block,\n\t\t\t\/\/ \t\t\"latest_block_hash\", latestBlockHash,\n\t\t\t\/\/ \t)\n\t\t\t\/\/ \tcontinue\n\t\t\t\/\/ }\n\n\t\t\t\/\/ we don't accept events unless they came after a new block (ie. in)\n\t\t\tif latestBlockHash == nil {\n\t\t\t\tlogging.InfoMsg(erisNodeWebsocketClient.logger, \"First block has not been registered so ignoring event\",\n\t\t\t\t\t\"event\", event.Event)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif event.Event != eid {\n\t\t\t\tlogging.InfoMsg(erisNodeWebsocketClient.logger, \"Received unsolicited event\",\n\t\t\t\t\t\"event_received\", event.Event,\n\t\t\t\t\t\"event_expected\", eid)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdata, ok := event.Data.(txs.EventDataTx)\n\t\t\tif !ok {\n\t\t\t\t\/\/ We are on the lookout for EventDataTx\n\t\t\t\tconfirmationChannel <- Confirmation{\n\t\t\t\t\tBlockHash: latestBlockHash,\n\t\t\t\t\tEvent:     nil,\n\t\t\t\t\tException: fmt.Errorf(\"response error: expected result.Data to be *types.EventDataTx\"),\n\t\t\t\t\tError:     nil,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !bytes.Equal(txs.TxHash(chainId, data.Tx), txs.TxHash(chainId, tx)) {\n\t\t\t\tlogging.TraceMsg(erisNodeWebsocketClient.logger, \"Received different event\",\n\t\t\t\t\t\/\/ TODO: consider re-implementing TxID again, or other more clear debug\n\t\t\t\t\t\"received transaction event\", txs.TxHash(chainId, data.Tx))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif data.Exception != \"\" {\n\t\t\t\tconfirmationChannel <- Confirmation{\n\t\t\t\t\tBlockHash: latestBlockHash,\n\t\t\t\t\tEvent:     &data,\n\t\t\t\t\tException: fmt.Errorf(\"Transaction confirmed with exception:\", data.Exception),\n\t\t\t\t\tError:     nil,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ success, return the full event and blockhash and exit go-routine\n\t\t\tconfirmationChannel <- Confirmation{\n\t\t\t\tBlockHash: latestBlockHash,\n\t\t\t\tEvent:     &data,\n\t\t\t\tException: nil,\n\t\t\t\tError:     nil,\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t}()\n\n\t\/\/ TODO: [ben] this is a draft implementation as resources on time.After can not be\n\t\/\/ recovered before the timeout.  Close-down timeout at success properly.\n\ttimeout := time.After(time.Duration(MaxCommitWaitTimeSeconds) * time.Second)\n\n\tgo func() {\n\t\t<-timeout\n\t\tconfirmationChannel <- Confirmation{\n\t\t\tBlockHash: nil,\n\t\t\tEvent:     nil,\n\t\t\tException: nil,\n\t\t\tError:     fmt.Errorf(\"timed out waiting for event\"),\n\t\t}\n\t\treturn\n\t}()\n\treturn confirmationChannel, nil\n}\n\nfunc (erisNodeWebsocketClient *erisNodeWebsocketClient) Close() {\n\tif erisNodeWebsocketClient.tendermintWebsocket != nil {\n\t\terisNodeWebsocketClient.tendermintWebsocket.Stop()\n\t}\n}\n\nfunc (erisNodeWebsocketClient *erisNodeWebsocketClient) assertNoErrors() error {\n\tif erisNodeWebsocketClient.tendermintWebsocket != nil {\n\t\tselect {\n\t\tcase err := <-erisNodeWebsocketClient.tendermintWebsocket.ErrorsCh:\n\t\t\treturn err\n\t\tdefault:\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"Eris-client has no websocket initialised.\")\n\t}\n}\n<commit_msg>client: correct yesterdays hotfix for event confirmation<commit_after>\/\/ Copyright 2017 Monax Industries Limited\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage client\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/tendermint\/go-rpc\/client\"\n\t\"github.com\/tendermint\/go-wire\"\n\n\t\"github.com\/monax\/eris-db\/logging\"\n\t\"github.com\/monax\/eris-db\/logging\/loggers\"\n\tctypes \"github.com\/monax\/eris-db\/rpc\/tendermint\/core\/types\"\n\t\"github.com\/monax\/eris-db\/txs\"\n)\n\nconst (\n\tMaxCommitWaitTimeSeconds = 10\n)\n\ntype Confirmation struct {\n\tBlockHash []byte\n\tEvent     txs.EventData\n\tException error\n\tError     error\n}\n\n\/\/ NOTE [ben] Compiler check to ensure erisNodeClient successfully implements\n\/\/ eris-db\/client.NodeClient\nvar _ NodeWebsocketClient = (*erisNodeWebsocketClient)(nil)\n\ntype erisNodeWebsocketClient struct {\n\t\/\/ TODO: assert no memory leak on closing with open websocket\n\ttendermintWebsocket *rpcclient.WSClient\n\tlogger              loggers.InfoTraceLogger\n}\n\n\/\/ Subscribe to an eventid\nfunc (erisNodeWebsocketClient *erisNodeWebsocketClient) Subscribe(eventid string) error {\n\t\/\/ TODO we can in the background listen to the subscription id and remember it to ease unsubscribing later.\n\treturn erisNodeWebsocketClient.tendermintWebsocket.Subscribe(eventid)\n}\n\n\/\/ Unsubscribe from an eventid\nfunc (erisNodeWebsocketClient *erisNodeWebsocketClient) Unsubscribe(subscriptionId string) error {\n\treturn erisNodeWebsocketClient.tendermintWebsocket.Unsubscribe(subscriptionId)\n}\n\n\/\/ Returns a channel that will receive a confirmation with a result or the exception that\n\/\/ has been confirmed; or an error is returned and the confirmation channel is nil.\nfunc (erisNodeWebsocketClient *erisNodeWebsocketClient) WaitForConfirmation(tx txs.Tx, chainId string, inputAddr []byte) (chan Confirmation, error) {\n\t\/\/ check no errors are reported on the websocket\n\tif err := erisNodeWebsocketClient.assertNoErrors(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Setup the confirmation channel to be returned\n\tconfirmationChannel := make(chan Confirmation, 1)\n\tvar latestBlockHash []byte\n\n\teid := txs.EventStringAccInput(inputAddr)\n\tif err := erisNodeWebsocketClient.tendermintWebsocket.Subscribe(eid); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error subscribing to AccInput event (%s): %v\", eid, err)\n\t}\n\tif err := erisNodeWebsocketClient.tendermintWebsocket.Subscribe(txs.EventStringNewBlock()); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error subscribing to NewBlock event: %v\", err)\n\t}\n\t\/\/ Read the incoming events\n\tgo func() {\n\t\tvar err error\n\t\tfor {\n\t\t\tresultBytes := <-erisNodeWebsocketClient.tendermintWebsocket.ResultsCh\n\t\t\tresult := new(ctypes.ErisDBResult)\n\t\t\tif wire.ReadJSONPtr(result, resultBytes, &err); err != nil {\n\t\t\t\t\/\/ keep calm and carry on\n\t\t\t\tlogging.InfoMsg(erisNodeWebsocketClient.logger, \"Failed to unmarshal json bytes for websocket event\",\n\t\t\t\t\t\"error\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsubscription, ok := (*result).(*ctypes.ResultSubscribe)\n\t\t\tif ok {\n\t\t\t\t\/\/ Received confirmation of subscription to event streams\n\t\t\t\t\/\/ TODO: collect subscription IDs, push into channel and on completion\n\t\t\t\t\/\/ unsubscribe\n\t\t\t\tlogging.InfoMsg(erisNodeWebsocketClient.logger, \"Received confirmation for event\",\n\t\t\t\t\t\"event\", subscription.Event,\n\t\t\t\t\t\"subscription_id\", subscription.SubscriptionId)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tevent, ok := (*result).(*ctypes.ResultEvent)\n\t\t\tif !ok {\n\t\t\t\t\/\/ keep calm and carry on\n\t\t\t\tlogging.InfoMsg(erisNodeWebsocketClient.logger, \"Failed to cast to ResultEvent for websocket event\",\n\t\t\t\t\t\"event\", event.Event)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tblockData, ok := event.Data.(txs.EventDataNewBlock)\n\t\t\tif ok {\n\t\t\t\tlatestBlockHash = blockData.Block.Hash()\n\t\t\t\tlogging.TraceMsg(erisNodeWebsocketClient.logger, \"Registered new block\",\n\t\t\t\t\t\"block\", blockData.Block,\n\t\t\t\t\t\"latest_block_hash\", latestBlockHash,\n\t\t\t\t)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ NOTE: [ben] hotfix on 0.16.1 because NewBlock events to arrive seemingly late\n\t\t\t\/\/ we now miss events because of this redundant check;  This check is safely removed\n\t\t\t\/\/ because for CallTx on checking the transaction is not run in the EVM and no false\n\t\t\t\/\/ positive event can be sent; neither is this check a good check for that.\n\n\t\t\t\/\/ we don't accept events unless they came after a new block (ie. in)\n\t\t\t\/\/ if latestBlockHash == nil {\n\t\t\t\/\/ \tlogging.InfoMsg(erisNodeWebsocketClient.logger, \"First block has not been registered so ignoring event\",\n\t\t\t\/\/ \t\t\"event\", event.Event)\n\t\t\t\/\/ \tcontinue\n\t\t\t\/\/ }\n\n\t\t\tif event.Event != eid {\n\t\t\t\tlogging.InfoMsg(erisNodeWebsocketClient.logger, \"Received unsolicited event\",\n\t\t\t\t\t\"event_received\", event.Event,\n\t\t\t\t\t\"event_expected\", eid)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdata, ok := event.Data.(txs.EventDataTx)\n\t\t\tif !ok {\n\t\t\t\t\/\/ We are on the lookout for EventDataTx\n\t\t\t\tconfirmationChannel <- Confirmation{\n\t\t\t\t\tBlockHash: latestBlockHash,\n\t\t\t\t\tEvent:     nil,\n\t\t\t\t\tException: fmt.Errorf(\"response error: expected result.Data to be *types.EventDataTx\"),\n\t\t\t\t\tError:     nil,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !bytes.Equal(txs.TxHash(chainId, data.Tx), txs.TxHash(chainId, tx)) {\n\t\t\t\tlogging.TraceMsg(erisNodeWebsocketClient.logger, \"Received different event\",\n\t\t\t\t\t\/\/ TODO: consider re-implementing TxID again, or other more clear debug\n\t\t\t\t\t\"received transaction event\", txs.TxHash(chainId, data.Tx))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif data.Exception != \"\" {\n\t\t\t\tconfirmationChannel <- Confirmation{\n\t\t\t\t\tBlockHash: latestBlockHash,\n\t\t\t\t\tEvent:     &data,\n\t\t\t\t\tException: fmt.Errorf(\"Transaction confirmed with exception:\", data.Exception),\n\t\t\t\t\tError:     nil,\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ success, return the full event and blockhash and exit go-routine\n\t\t\tconfirmationChannel <- Confirmation{\n\t\t\t\tBlockHash: latestBlockHash,\n\t\t\t\tEvent:     &data,\n\t\t\t\tException: nil,\n\t\t\t\tError:     nil,\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t}()\n\n\t\/\/ TODO: [ben] this is a draft implementation as resources on time.After can not be\n\t\/\/ recovered before the timeout.  Close-down timeout at success properly.\n\ttimeout := time.After(time.Duration(MaxCommitWaitTimeSeconds) * time.Second)\n\n\tgo func() {\n\t\t<-timeout\n\t\tconfirmationChannel <- Confirmation{\n\t\t\tBlockHash: nil,\n\t\t\tEvent:     nil,\n\t\t\tException: nil,\n\t\t\tError:     fmt.Errorf(\"timed out waiting for event\"),\n\t\t}\n\t\treturn\n\t}()\n\treturn confirmationChannel, nil\n}\n\nfunc (erisNodeWebsocketClient *erisNodeWebsocketClient) Close() {\n\tif erisNodeWebsocketClient.tendermintWebsocket != nil {\n\t\terisNodeWebsocketClient.tendermintWebsocket.Stop()\n\t}\n}\n\nfunc (erisNodeWebsocketClient *erisNodeWebsocketClient) assertNoErrors() error {\n\tif erisNodeWebsocketClient.tendermintWebsocket != nil {\n\t\tselect {\n\t\tcase err := <-erisNodeWebsocketClient.tendermintWebsocket.ErrorsCh:\n\t\t\treturn err\n\t\tdefault:\n\t\t\treturn nil\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"Eris-client has no websocket initialised.\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package accessors\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/kellydunn\/golang-geo\"\n)\n\nconst nearbyEnemyCap = 100\n\n\/\/ Returns an array of all loot locations and values to plot on the map in iOS\nfunc (ag *AccessorGroup) DumpDatabase(userLatitude float64, userLongitude float64, radius float64) (string, error) {\n\tcurrentEnemyCount, err := ag.CountNearbyEnemies(userLatitude, userLongitude, radius)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tif currentEnemyCount < nearbyEnemyCap {\n\t\t\/\/ Add enemies\n\t\tag.AddEnemies(userLatitude, userLongitude, radius, currentEnemyCount, nearbyEnemyCap)\n\t}\n\n\trows, err := ag.DB.Query(\"SELECT * FROM enemies\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tdefer rows.Close()\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tcount := len(columns)\n\ttableData := make([]map[string]string, 0)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\n\tfor rows.Next() {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\n\t\trows.Scan(valuePtrs...)\n\t\tentry := make(map[string]string)\n\n\t\tfor i, col := range columns {\n\t\t\tval := values[i]\n\t\t\tif val != nil {\n\t\t\t\tentry[col] = fmt.Sprintf(\"%s\", string(val.([]byte))) \/\/ Save the data as a string\n\t\t\t}\n\t\t}\n\n\t\tif len(entry[\"latitude\"]) > 0 && len(entry[\"latitude\"]) > 0 { \/\/ Make sure we don't have bad data\n\t\t\tlatitude, err := strconv.ParseFloat(entry[\"latitude\"], 64)\n\t\t\tif err == nil {\n\t\t\t\tlongitude, err := strconv.ParseFloat(entry[\"longitude\"], 64)\n\t\t\t\tif err == nil {\n\t\t\t\t\tif WithinRadius(latitude, longitude, userLatitude, userLongitude, radius) { \/\/ Only return enemies that are close to the player\n\t\t\t\t\t\ttableData = append(tableData, entry)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Panic(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\tjsonData, err := json.Marshal(tableData)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn string(jsonData), nil\n}\n\nfunc (ag *AccessorGroup) CountNearbyEnemies(userLatitude float64, userLongitude float64, radius float64) (int, error) {\n\tenemyCount := 0\n\n\trows, err := ag.DB.Query(\"SELECT * FROM enemies\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tdefer rows.Close()\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tcount := len(columns)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\n\tfor rows.Next() {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\n\t\trows.Scan(valuePtrs...)\n\t\tentry := make(map[string]string)\n\n\t\tfor i, col := range columns {\n\t\t\tval := values[i]\n\t\t\tif val != nil {\n\t\t\t\tentry[col] = fmt.Sprintf(\"%s\", string(val.([]byte))) \/\/ Save the data as a string\n\t\t\t}\n\t\t}\n\n\t\tif len(entry[\"latitude\"]) > 0 && len(entry[\"latitude\"]) > 0 { \/\/ Make sure we don't have bad data\n\t\t\tlatitude, err := strconv.ParseFloat(entry[\"latitude\"], 64)\n\t\t\tif err == nil {\n\t\t\t\tlongitude, err := strconv.ParseFloat(entry[\"longitude\"], 64)\n\t\t\t\tif err == nil {\n\t\t\t\t\tif WithinRadius(latitude, longitude, userLatitude, userLongitude, radius) { \/\/ Only return enemies that are close to the player\n\t\t\t\t\t\tenemyCount++\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Panic(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn enemyCount, nil\n}\n\nfunc WithinRadius(lat1 float64, lon1 float64, lat2 float64, lon2 float64, radius float64) bool {\n\tp := geo.NewPoint(lat1, lon1)\n\tp2 := geo.NewPoint(lat2, lon2)\n\n\tdist := p.GreatCircleDistance(p2) \/\/ Find the great circle distance between points\n\n\tif dist < radius { \/\/ Return whether we're inside the radius or not\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\nfunc (ag *AccessorGroup) AddEnemies(userLatitude float64, userLongitude float64, radius float64, currentEnemyCount int, enemyCap int) {\n\titerations := enemyCap - currentEnemyCount\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tfor i := 0; i < iterations; i++ {\n\t\tw := radius \/ 111 * math.Sqrt(rand.Float64())\n\t\tt := 2 * math.Pi * rand.Float64()\n\t\tx := w * math.Cos(t)\n\t\ty := w * math.Sin(t)\n\n\t\trandomLatitude := userLatitude + x\n\t\trandomLongitude := userLongitude + y\n\n\t\t_, err := ag.DB.Exec(\"INSERT INTO enemies (latitude, longitude) VALUES (?,?)\", randomLatitude, randomLongitude)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t}\n}\n<commit_msg>Increasing the enemy limit<commit_after>package accessors\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/kellydunn\/golang-geo\"\n)\n\nconst nearbyEnemyCap = 300\n\n\/\/ Returns an array of all loot locations and values to plot on the map in iOS\nfunc (ag *AccessorGroup) DumpDatabase(userLatitude float64, userLongitude float64, radius float64) (string, error) {\n\tcurrentEnemyCount, err := ag.CountNearbyEnemies(userLatitude, userLongitude, radius)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tif currentEnemyCount < nearbyEnemyCap {\n\t\t\/\/ Add enemies\n\t\tag.AddEnemies(userLatitude, userLongitude, radius, currentEnemyCount, nearbyEnemyCap)\n\t}\n\n\trows, err := ag.DB.Query(\"SELECT * FROM enemies\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tdefer rows.Close()\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tcount := len(columns)\n\ttableData := make([]map[string]string, 0)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\n\tfor rows.Next() {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\n\t\trows.Scan(valuePtrs...)\n\t\tentry := make(map[string]string)\n\n\t\tfor i, col := range columns {\n\t\t\tval := values[i]\n\t\t\tif val != nil {\n\t\t\t\tentry[col] = fmt.Sprintf(\"%s\", string(val.([]byte))) \/\/ Save the data as a string\n\t\t\t}\n\t\t}\n\n\t\tif len(entry[\"latitude\"]) > 0 && len(entry[\"latitude\"]) > 0 { \/\/ Make sure we don't have bad data\n\t\t\tlatitude, err := strconv.ParseFloat(entry[\"latitude\"], 64)\n\t\t\tif err == nil {\n\t\t\t\tlongitude, err := strconv.ParseFloat(entry[\"longitude\"], 64)\n\t\t\t\tif err == nil {\n\t\t\t\t\tif WithinRadius(latitude, longitude, userLatitude, userLongitude, radius) { \/\/ Only return enemies that are close to the player\n\t\t\t\t\t\ttableData = append(tableData, entry)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Panic(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\tjsonData, err := json.Marshal(tableData)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn string(jsonData), nil\n}\n\nfunc (ag *AccessorGroup) CountNearbyEnemies(userLatitude float64, userLongitude float64, radius float64) (int, error) {\n\tenemyCount := 0\n\n\trows, err := ag.DB.Query(\"SELECT * FROM enemies\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tdefer rows.Close()\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tcount := len(columns)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\n\tfor rows.Next() {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\n\t\trows.Scan(valuePtrs...)\n\t\tentry := make(map[string]string)\n\n\t\tfor i, col := range columns {\n\t\t\tval := values[i]\n\t\t\tif val != nil {\n\t\t\t\tentry[col] = fmt.Sprintf(\"%s\", string(val.([]byte))) \/\/ Save the data as a string\n\t\t\t}\n\t\t}\n\n\t\tif len(entry[\"latitude\"]) > 0 && len(entry[\"latitude\"]) > 0 { \/\/ Make sure we don't have bad data\n\t\t\tlatitude, err := strconv.ParseFloat(entry[\"latitude\"], 64)\n\t\t\tif err == nil {\n\t\t\t\tlongitude, err := strconv.ParseFloat(entry[\"longitude\"], 64)\n\t\t\t\tif err == nil {\n\t\t\t\t\tif WithinRadius(latitude, longitude, userLatitude, userLongitude, radius) { \/\/ Only return enemies that are close to the player\n\t\t\t\t\t\tenemyCount++\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Panic(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn enemyCount, nil\n}\n\nfunc WithinRadius(lat1 float64, lon1 float64, lat2 float64, lon2 float64, radius float64) bool {\n\tp := geo.NewPoint(lat1, lon1)\n\tp2 := geo.NewPoint(lat2, lon2)\n\n\tdist := p.GreatCircleDistance(p2) \/\/ Find the great circle distance between points\n\n\tif dist < radius { \/\/ Return whether we're inside the radius or not\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\nfunc (ag *AccessorGroup) AddEnemies(userLatitude float64, userLongitude float64, radius float64, currentEnemyCount int, enemyCap int) {\n\titerations := enemyCap - currentEnemyCount\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tfor i := 0; i < iterations; i++ {\n\t\tw := radius \/ 111 * math.Sqrt(rand.Float64())\n\t\tt := 2 * math.Pi * rand.Float64()\n\t\tx := w * math.Cos(t)\n\t\ty := w * math.Sin(t)\n\n\t\trandomLatitude := userLatitude + x\n\t\trandomLongitude := userLongitude + y\n\n\t\t_, err := ag.DB.Exec(\"INSERT INTO enemies (latitude, longitude) VALUES (?,?)\", randomLatitude, randomLongitude)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package action_test\n\nimport (\n\t\"errors\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\n\t. \"github.com\/cloudfoundry\/bosh-softlayer-cpi\/action\"\n\n\tfakevm \"github.com\/cloudfoundry\/bosh-softlayer-cpi\/softlayer\/vm\/fakes\"\n)\n\nvar _ = Describe(\"HasVM\", func() {\n\tvar (\n\t\tvmFinder *fakevm.FakeFinder\n\t\taction   HasVMAction\n\t)\n\n\tBeforeEach(func() {\n\t\tvmFinder = &fakevm.FakeFinder{}\n\t\taction = NewHasVM(vmFinder)\n\t})\n\n\tDescribe(\"Run\", func() {\n\t\tContext(\"when VM is found with given CID\", func() {\n\t\t\tIt(\"returns true without error\", func() {\n\t\t\t\tvmFinder.FindFound = true\n\t\t\t\tvmFinder.FindVM = fakevm.NewFakeVM(1234)\n\n\t\t\t\tfound, err := action.Run(1234)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\tExpect(found).To(BeTrue())\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when VM is not found with given CID\", func() {\n\t\t\tIt(\"returns false without error\", func() {\n\t\t\t\tvmFinder.FindFound = false\n\n\t\t\t\tfound, err := action.Run(1234)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\tExpect(found).To(BeFalse())\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when VM finding fails\", func() {\n\t\t\tIt(\"returns error\", func() {\n\t\t\t\tvmFinder.FindFound = false\n\t\t\t\tvmFinder.FindErr = errors.New(\"fake-find-err\")\n\n\t\t\t\tfound, err := action.Run(1234)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\tExpect(found).To(BeFalse())\n\t\t\t})\n\t\t})\n\t})\n})\n<commit_msg>updated test context of has_vm_test.go<commit_after>package action_test\n\nimport (\n\t\"errors\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\n\t. \"github.com\/cloudfoundry\/bosh-softlayer-cpi\/action\"\n\n\tfakevm \"github.com\/cloudfoundry\/bosh-softlayer-cpi\/softlayer\/vm\/fakes\"\n)\n\nvar _ = Describe(\"HasVM\", func() {\n\tvar (\n\t\tvmFinder *fakevm.FakeFinder\n\t\taction   HasVMAction\n\t)\n\n\tBeforeEach(func() {\n\t\tvmFinder = &fakevm.FakeFinder{}\n\t\taction = NewHasVM(vmFinder)\n\t})\n\n\tDescribe(\"Run\", func() {\n\t\tContext(\"when VM is found with given CID\", func() {\n\t\t\tIt(\"returns true without error\", func() {\n\t\t\t\tvmFinder.FindFound = true\n\t\t\t\tvmFinder.FindVM = fakevm.NewFakeVM(1234)\n\n\t\t\t\tfound, err := action.Run(1234)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\tExpect(found).To(BeTrue())\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when VM is not found with given CID\", func() {\n\t\t\tIt(\"returns false without error\", func() {\n\t\t\t\tvmFinder.FindFound = false\n\n\t\t\t\tfound, err := action.Run(1234)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\tExpect(found).To(BeFalse())\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when VM finding fails\", func() {\n\t\t\tIt(\"returns false without error\", func() {\n\t\t\t\tvmFinder.FindFound = false\n\t\t\t\tvmFinder.FindErr = errors.New(\"fake-find-err\")\n\n\t\t\t\tfound, err := action.Run(1234)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\tExpect(found).To(BeFalse())\n\t\t\t})\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage scheduling\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"sync\"\n\n\t\"k8s.io\/klog\/v2\"\n\n\tv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n)\n\n\/\/ AssumeCache is a cache on top of the informer that allows for updating\n\/\/ objects outside of informer events and also restoring the informer\n\/\/ cache's version of the object.  Objects are assumed to be\n\/\/ Kubernetes API objects that implement meta.Interface\ntype AssumeCache interface {\n\t\/\/ Assume updates the object in-memory only\n\tAssume(obj interface{}) error\n\n\t\/\/ Restore the informer cache's version of the object\n\tRestore(objName string)\n\n\t\/\/ Get the object by name\n\tGet(objName string) (interface{}, error)\n\n\t\/\/ Get the API object by name\n\tGetAPIObj(objName string) (interface{}, error)\n\n\t\/\/ List all the objects in the cache\n\tList(indexObj interface{}) []interface{}\n}\n\ntype errWrongType struct {\n\ttypeName string\n\tobject   interface{}\n}\n\nfunc (e *errWrongType) Error() string {\n\treturn fmt.Sprintf(\"could not convert object to type %v: %+v\", e.typeName, e.object)\n}\n\ntype errNotFound struct {\n\ttypeName   string\n\tobjectName string\n}\n\nfunc (e *errNotFound) Error() string {\n\treturn fmt.Sprintf(\"could not find %v %q\", e.typeName, e.objectName)\n}\n\ntype errObjectName struct {\n\tdetailedErr error\n}\n\nfunc (e *errObjectName) Error() string {\n\treturn fmt.Sprintf(\"failed to get object name: %v\", e.detailedErr)\n}\n\n\/\/ assumeCache stores two pointers to represent a single object:\n\/\/ * The pointer to the informer object.\n\/\/ * The pointer to the latest object, which could be the same as\n\/\/   the informer object, or an in-memory object.\n\/\/\n\/\/ An informer update always overrides the latest object pointer.\n\/\/\n\/\/ Assume() only updates the latest object pointer.\n\/\/ Restore() sets the latest object pointer back to the informer object.\n\/\/ Get\/List() always returns the latest object pointer.\ntype assumeCache struct {\n\t\/\/ Synchronizes updates to store\n\trwMutex sync.RWMutex\n\n\t\/\/ describes the object stored\n\tdescription string\n\n\t\/\/ Stores objInfo pointers\n\tstore cache.Indexer\n\n\t\/\/ Index function for object\n\tindexFunc cache.IndexFunc\n\tindexName string\n}\n\ntype objInfo struct {\n\t\/\/ name of the object\n\tname string\n\n\t\/\/ Latest version of object could be cached-only or from informer\n\tlatestObj interface{}\n\n\t\/\/ Latest object from informer\n\tapiObj interface{}\n}\n\nfunc objInfoKeyFunc(obj interface{}) (string, error) {\n\tobjInfo, ok := obj.(*objInfo)\n\tif !ok {\n\t\treturn \"\", &errWrongType{\"objInfo\", obj}\n\t}\n\treturn objInfo.name, nil\n}\n\nfunc (c *assumeCache) objInfoIndexFunc(obj interface{}) ([]string, error) {\n\tobjInfo, ok := obj.(*objInfo)\n\tif !ok {\n\t\treturn []string{\"\"}, &errWrongType{\"objInfo\", obj}\n\t}\n\treturn c.indexFunc(objInfo.latestObj)\n}\n\n\/\/ NewAssumeCache creates an assume cache for general objects.\nfunc NewAssumeCache(informer cache.SharedIndexInformer, description, indexName string, indexFunc cache.IndexFunc) AssumeCache {\n\tc := &assumeCache{\n\t\tdescription: description,\n\t\tindexFunc:   indexFunc,\n\t\tindexName:   indexName,\n\t}\n\tindexers := cache.Indexers{}\n\tif indexName != \"\" && indexFunc != nil {\n\t\tindexers[indexName] = c.objInfoIndexFunc\n\t}\n\tc.store = cache.NewIndexer(objInfoKeyFunc, indexers)\n\n\t\/\/ Unit tests don't use informers\n\tif informer != nil {\n\t\tinformer.AddEventHandler(\n\t\t\tcache.ResourceEventHandlerFuncs{\n\t\t\t\tAddFunc:    c.add,\n\t\t\t\tUpdateFunc: c.update,\n\t\t\t\tDeleteFunc: c.delete,\n\t\t\t},\n\t\t)\n\t}\n\treturn c\n}\n\nfunc (c *assumeCache) add(obj interface{}) {\n\tif obj == nil {\n\t\treturn\n\t}\n\n\tname, err := cache.MetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\tklog.Errorf(\"add failed: %v\", &errObjectName{err})\n\t\treturn\n\t}\n\n\tc.rwMutex.Lock()\n\tdefer c.rwMutex.Unlock()\n\n\tif objInfo, _ := c.getObjInfo(name); objInfo != nil {\n\t\tnewVersion, err := c.getObjVersion(name, obj)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"add: couldn't get object version: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tstoredVersion, err := c.getObjVersion(name, objInfo.latestObj)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"add: couldn't get stored object version: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Only update object if version is newer.\n\t\t\/\/ This is so we don't override assumed objects due to informer resync.\n\t\tif newVersion <= storedVersion {\n\t\t\tklog.V(10).Infof(\"Skip adding %v %v to assume cache because version %v is not newer than %v\", c.description, name, newVersion, storedVersion)\n\t\t\treturn\n\t\t}\n\t}\n\n\tobjInfo := &objInfo{name: name, latestObj: obj, apiObj: obj}\n\tif err = c.store.Update(objInfo); err != nil {\n\t\tklog.Warningf(\"got error when updating stored object : %v\", err)\n\t} else {\n\t\tklog.V(10).Infof(\"Adding %v %v to assume cache: %+v \", c.description, name, obj)\n\t}\n}\n\nfunc (c *assumeCache) update(oldObj interface{}, newObj interface{}) {\n\tc.add(newObj)\n}\n\nfunc (c *assumeCache) delete(obj interface{}) {\n\tif obj == nil {\n\t\treturn\n\t}\n\n\tname, err := cache.MetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\tklog.Errorf(\"delete failed: %v\", &errObjectName{err})\n\t\treturn\n\t}\n\n\tc.rwMutex.Lock()\n\tdefer c.rwMutex.Unlock()\n\n\tobjInfo := &objInfo{name: name}\n\terr = c.store.Delete(objInfo)\n\tif err != nil {\n\t\tklog.Errorf(\"delete: failed to delete %v %v: %v\", c.description, name, err)\n\t}\n}\n\nfunc (c *assumeCache) getObjVersion(name string, obj interface{}) (int64, error) {\n\tobjAccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\tobjResourceVersion, err := strconv.ParseInt(objAccessor.GetResourceVersion(), 10, 64)\n\tif err != nil {\n\t\treturn -1, fmt.Errorf(\"error parsing ResourceVersion %q for %v %q: %s\", objAccessor.GetResourceVersion(), c.description, name, err)\n\t}\n\treturn objResourceVersion, nil\n}\n\nfunc (c *assumeCache) getObjInfo(name string) (*objInfo, error) {\n\tobj, ok, err := c.store.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !ok {\n\t\treturn nil, &errNotFound{c.description, name}\n\t}\n\n\tobjInfo, ok := obj.(*objInfo)\n\tif !ok {\n\t\treturn nil, &errWrongType{\"objInfo\", obj}\n\t}\n\treturn objInfo, nil\n}\n\nfunc (c *assumeCache) Get(objName string) (interface{}, error) {\n\tc.rwMutex.RLock()\n\tdefer c.rwMutex.RUnlock()\n\n\tobjInfo, err := c.getObjInfo(objName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn objInfo.latestObj, nil\n}\n\nfunc (c *assumeCache) GetAPIObj(objName string) (interface{}, error) {\n\tc.rwMutex.RLock()\n\tdefer c.rwMutex.RUnlock()\n\n\tobjInfo, err := c.getObjInfo(objName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn objInfo.apiObj, nil\n}\n\nfunc (c *assumeCache) List(indexObj interface{}) []interface{} {\n\tc.rwMutex.RLock()\n\tdefer c.rwMutex.RUnlock()\n\n\tallObjs := []interface{}{}\n\tobjs, err := c.store.Index(c.indexName, &objInfo{latestObj: indexObj})\n\tif err != nil {\n\t\tklog.Errorf(\"list index error: %v\", err)\n\t\treturn nil\n\t}\n\n\tfor _, obj := range objs {\n\t\tobjInfo, ok := obj.(*objInfo)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"list error: %v\", &errWrongType{\"objInfo\", obj})\n\t\t\tcontinue\n\t\t}\n\t\tallObjs = append(allObjs, objInfo.latestObj)\n\t}\n\treturn allObjs\n}\n\nfunc (c *assumeCache) Assume(obj interface{}) error {\n\tname, err := cache.MetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\treturn &errObjectName{err}\n\t}\n\n\tc.rwMutex.Lock()\n\tdefer c.rwMutex.Unlock()\n\n\tobjInfo, err := c.getObjInfo(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewVersion, err := c.getObjVersion(name, obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstoredVersion, err := c.getObjVersion(name, objInfo.latestObj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif newVersion < storedVersion {\n\t\treturn fmt.Errorf(\"%v %q is out of sync (stored: %d, assume: %d)\", c.description, name, storedVersion, newVersion)\n\t}\n\n\t\/\/ Only update the cached object\n\tobjInfo.latestObj = obj\n\tklog.V(4).Infof(\"Assumed %v %q, version %v\", c.description, name, newVersion)\n\treturn nil\n}\n\nfunc (c *assumeCache) Restore(objName string) {\n\tc.rwMutex.Lock()\n\tdefer c.rwMutex.Unlock()\n\n\tobjInfo, err := c.getObjInfo(objName)\n\tif err != nil {\n\t\t\/\/ This could be expected if object got deleted\n\t\tklog.V(5).Infof(\"Restore %v %q warning: %v\", c.description, objName, err)\n\t} else {\n\t\tobjInfo.latestObj = objInfo.apiObj\n\t\tklog.V(4).Infof(\"Restored %v %q\", c.description, objName)\n\t}\n}\n\n\/\/ PVAssumeCache is a AssumeCache for PersistentVolume objects\ntype PVAssumeCache interface {\n\tAssumeCache\n\n\tGetPV(pvName string) (*v1.PersistentVolume, error)\n\tGetAPIPV(pvName string) (*v1.PersistentVolume, error)\n\tListPVs(storageClassName string) []*v1.PersistentVolume\n}\n\ntype pvAssumeCache struct {\n\tAssumeCache\n}\n\nfunc pvStorageClassIndexFunc(obj interface{}) ([]string, error) {\n\tif pv, ok := obj.(*v1.PersistentVolume); ok {\n\t\treturn []string{pv.Spec.StorageClassName}, nil\n\t}\n\treturn []string{\"\"}, fmt.Errorf(\"object is not a v1.PersistentVolume: %v\", obj)\n}\n\n\/\/ NewPVAssumeCache creates a PV assume cache.\nfunc NewPVAssumeCache(informer cache.SharedIndexInformer) PVAssumeCache {\n\treturn &pvAssumeCache{NewAssumeCache(informer, \"v1.PersistentVolume\", \"storageclass\", pvStorageClassIndexFunc)}\n}\n\nfunc (c *pvAssumeCache) GetPV(pvName string) (*v1.PersistentVolume, error) {\n\tobj, err := c.Get(pvName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpv, ok := obj.(*v1.PersistentVolume)\n\tif !ok {\n\t\treturn nil, &errWrongType{\"v1.PersistentVolume\", obj}\n\t}\n\treturn pv, nil\n}\n\nfunc (c *pvAssumeCache) GetAPIPV(pvName string) (*v1.PersistentVolume, error) {\n\tobj, err := c.GetAPIObj(pvName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpv, ok := obj.(*v1.PersistentVolume)\n\tif !ok {\n\t\treturn nil, &errWrongType{\"v1.PersistentVolume\", obj}\n\t}\n\treturn pv, nil\n}\n\nfunc (c *pvAssumeCache) ListPVs(storageClassName string) []*v1.PersistentVolume {\n\tobjs := c.List(&v1.PersistentVolume{\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tStorageClassName: storageClassName,\n\t\t},\n\t})\n\tpvs := []*v1.PersistentVolume{}\n\tfor _, obj := range objs {\n\t\tpv, ok := obj.(*v1.PersistentVolume)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"ListPVs: %v\", &errWrongType{\"v1.PersistentVolume\", obj})\n\t\t\tcontinue\n\t\t}\n\t\tpvs = append(pvs, pv)\n\t}\n\treturn pvs\n}\n\n\/\/ PVCAssumeCache is a AssumeCache for PersistentVolumeClaim objects\ntype PVCAssumeCache interface {\n\tAssumeCache\n\n\t\/\/ GetPVC returns the PVC from the cache with given pvcKey.\n\t\/\/ pvcKey is the result of MetaNamespaceKeyFunc on PVC obj\n\tGetPVC(pvcKey string) (*v1.PersistentVolumeClaim, error)\n\tGetAPIPVC(pvcKey string) (*v1.PersistentVolumeClaim, error)\n}\n\ntype pvcAssumeCache struct {\n\tAssumeCache\n}\n\n\/\/ NewPVCAssumeCache creates a PVC assume cache.\nfunc NewPVCAssumeCache(informer cache.SharedIndexInformer) PVCAssumeCache {\n\treturn &pvcAssumeCache{NewAssumeCache(informer, \"v1.PersistentVolumeClaim\", \"\", nil)}\n}\n\nfunc (c *pvcAssumeCache) GetPVC(pvcKey string) (*v1.PersistentVolumeClaim, error) {\n\tobj, err := c.Get(pvcKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpvc, ok := obj.(*v1.PersistentVolumeClaim)\n\tif !ok {\n\t\treturn nil, &errWrongType{\"v1.PersistentVolumeClaim\", obj}\n\t}\n\treturn pvc, nil\n}\n\nfunc (c *pvcAssumeCache) GetAPIPVC(pvcKey string) (*v1.PersistentVolumeClaim, error) {\n\tobj, err := c.GetAPIObj(pvcKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpvc, ok := obj.(*v1.PersistentVolumeClaim)\n\tif !ok {\n\t\treturn nil, &errWrongType{\"v1.PersistentVolumeClaim\", obj}\n\t}\n\treturn pvc, nil\n}\n<commit_msg>Use v1helper.GetPersistentVolumeClass for compatibility<commit_after>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage scheduling\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"sync\"\n\n\t\"k8s.io\/klog\/v2\"\n\n\tv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n\tv1helper \"k8s.io\/kubernetes\/pkg\/apis\/core\/v1\/helper\"\n)\n\n\/\/ AssumeCache is a cache on top of the informer that allows for updating\n\/\/ objects outside of informer events and also restoring the informer\n\/\/ cache's version of the object.  Objects are assumed to be\n\/\/ Kubernetes API objects that implement meta.Interface\ntype AssumeCache interface {\n\t\/\/ Assume updates the object in-memory only\n\tAssume(obj interface{}) error\n\n\t\/\/ Restore the informer cache's version of the object\n\tRestore(objName string)\n\n\t\/\/ Get the object by name\n\tGet(objName string) (interface{}, error)\n\n\t\/\/ Get the API object by name\n\tGetAPIObj(objName string) (interface{}, error)\n\n\t\/\/ List all the objects in the cache\n\tList(indexObj interface{}) []interface{}\n}\n\ntype errWrongType struct {\n\ttypeName string\n\tobject   interface{}\n}\n\nfunc (e *errWrongType) Error() string {\n\treturn fmt.Sprintf(\"could not convert object to type %v: %+v\", e.typeName, e.object)\n}\n\ntype errNotFound struct {\n\ttypeName   string\n\tobjectName string\n}\n\nfunc (e *errNotFound) Error() string {\n\treturn fmt.Sprintf(\"could not find %v %q\", e.typeName, e.objectName)\n}\n\ntype errObjectName struct {\n\tdetailedErr error\n}\n\nfunc (e *errObjectName) Error() string {\n\treturn fmt.Sprintf(\"failed to get object name: %v\", e.detailedErr)\n}\n\n\/\/ assumeCache stores two pointers to represent a single object:\n\/\/ * The pointer to the informer object.\n\/\/ * The pointer to the latest object, which could be the same as\n\/\/   the informer object, or an in-memory object.\n\/\/\n\/\/ An informer update always overrides the latest object pointer.\n\/\/\n\/\/ Assume() only updates the latest object pointer.\n\/\/ Restore() sets the latest object pointer back to the informer object.\n\/\/ Get\/List() always returns the latest object pointer.\ntype assumeCache struct {\n\t\/\/ Synchronizes updates to store\n\trwMutex sync.RWMutex\n\n\t\/\/ describes the object stored\n\tdescription string\n\n\t\/\/ Stores objInfo pointers\n\tstore cache.Indexer\n\n\t\/\/ Index function for object\n\tindexFunc cache.IndexFunc\n\tindexName string\n}\n\ntype objInfo struct {\n\t\/\/ name of the object\n\tname string\n\n\t\/\/ Latest version of object could be cached-only or from informer\n\tlatestObj interface{}\n\n\t\/\/ Latest object from informer\n\tapiObj interface{}\n}\n\nfunc objInfoKeyFunc(obj interface{}) (string, error) {\n\tobjInfo, ok := obj.(*objInfo)\n\tif !ok {\n\t\treturn \"\", &errWrongType{\"objInfo\", obj}\n\t}\n\treturn objInfo.name, nil\n}\n\nfunc (c *assumeCache) objInfoIndexFunc(obj interface{}) ([]string, error) {\n\tobjInfo, ok := obj.(*objInfo)\n\tif !ok {\n\t\treturn []string{\"\"}, &errWrongType{\"objInfo\", obj}\n\t}\n\treturn c.indexFunc(objInfo.latestObj)\n}\n\n\/\/ NewAssumeCache creates an assume cache for general objects.\nfunc NewAssumeCache(informer cache.SharedIndexInformer, description, indexName string, indexFunc cache.IndexFunc) AssumeCache {\n\tc := &assumeCache{\n\t\tdescription: description,\n\t\tindexFunc:   indexFunc,\n\t\tindexName:   indexName,\n\t}\n\tindexers := cache.Indexers{}\n\tif indexName != \"\" && indexFunc != nil {\n\t\tindexers[indexName] = c.objInfoIndexFunc\n\t}\n\tc.store = cache.NewIndexer(objInfoKeyFunc, indexers)\n\n\t\/\/ Unit tests don't use informers\n\tif informer != nil {\n\t\tinformer.AddEventHandler(\n\t\t\tcache.ResourceEventHandlerFuncs{\n\t\t\t\tAddFunc:    c.add,\n\t\t\t\tUpdateFunc: c.update,\n\t\t\t\tDeleteFunc: c.delete,\n\t\t\t},\n\t\t)\n\t}\n\treturn c\n}\n\nfunc (c *assumeCache) add(obj interface{}) {\n\tif obj == nil {\n\t\treturn\n\t}\n\n\tname, err := cache.MetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\tklog.Errorf(\"add failed: %v\", &errObjectName{err})\n\t\treturn\n\t}\n\n\tc.rwMutex.Lock()\n\tdefer c.rwMutex.Unlock()\n\n\tif objInfo, _ := c.getObjInfo(name); objInfo != nil {\n\t\tnewVersion, err := c.getObjVersion(name, obj)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"add: couldn't get object version: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tstoredVersion, err := c.getObjVersion(name, objInfo.latestObj)\n\t\tif err != nil {\n\t\t\tklog.Errorf(\"add: couldn't get stored object version: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Only update object if version is newer.\n\t\t\/\/ This is so we don't override assumed objects due to informer resync.\n\t\tif newVersion <= storedVersion {\n\t\t\tklog.V(10).Infof(\"Skip adding %v %v to assume cache because version %v is not newer than %v\", c.description, name, newVersion, storedVersion)\n\t\t\treturn\n\t\t}\n\t}\n\n\tobjInfo := &objInfo{name: name, latestObj: obj, apiObj: obj}\n\tif err = c.store.Update(objInfo); err != nil {\n\t\tklog.Warningf(\"got error when updating stored object : %v\", err)\n\t} else {\n\t\tklog.V(10).Infof(\"Adding %v %v to assume cache: %+v \", c.description, name, obj)\n\t}\n}\n\nfunc (c *assumeCache) update(oldObj interface{}, newObj interface{}) {\n\tc.add(newObj)\n}\n\nfunc (c *assumeCache) delete(obj interface{}) {\n\tif obj == nil {\n\t\treturn\n\t}\n\n\tname, err := cache.MetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\tklog.Errorf(\"delete failed: %v\", &errObjectName{err})\n\t\treturn\n\t}\n\n\tc.rwMutex.Lock()\n\tdefer c.rwMutex.Unlock()\n\n\tobjInfo := &objInfo{name: name}\n\terr = c.store.Delete(objInfo)\n\tif err != nil {\n\t\tklog.Errorf(\"delete: failed to delete %v %v: %v\", c.description, name, err)\n\t}\n}\n\nfunc (c *assumeCache) getObjVersion(name string, obj interface{}) (int64, error) {\n\tobjAccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\tobjResourceVersion, err := strconv.ParseInt(objAccessor.GetResourceVersion(), 10, 64)\n\tif err != nil {\n\t\treturn -1, fmt.Errorf(\"error parsing ResourceVersion %q for %v %q: %s\", objAccessor.GetResourceVersion(), c.description, name, err)\n\t}\n\treturn objResourceVersion, nil\n}\n\nfunc (c *assumeCache) getObjInfo(name string) (*objInfo, error) {\n\tobj, ok, err := c.store.GetByKey(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !ok {\n\t\treturn nil, &errNotFound{c.description, name}\n\t}\n\n\tobjInfo, ok := obj.(*objInfo)\n\tif !ok {\n\t\treturn nil, &errWrongType{\"objInfo\", obj}\n\t}\n\treturn objInfo, nil\n}\n\nfunc (c *assumeCache) Get(objName string) (interface{}, error) {\n\tc.rwMutex.RLock()\n\tdefer c.rwMutex.RUnlock()\n\n\tobjInfo, err := c.getObjInfo(objName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn objInfo.latestObj, nil\n}\n\nfunc (c *assumeCache) GetAPIObj(objName string) (interface{}, error) {\n\tc.rwMutex.RLock()\n\tdefer c.rwMutex.RUnlock()\n\n\tobjInfo, err := c.getObjInfo(objName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn objInfo.apiObj, nil\n}\n\nfunc (c *assumeCache) List(indexObj interface{}) []interface{} {\n\tc.rwMutex.RLock()\n\tdefer c.rwMutex.RUnlock()\n\n\tallObjs := []interface{}{}\n\tobjs, err := c.store.Index(c.indexName, &objInfo{latestObj: indexObj})\n\tif err != nil {\n\t\tklog.Errorf(\"list index error: %v\", err)\n\t\treturn nil\n\t}\n\n\tfor _, obj := range objs {\n\t\tobjInfo, ok := obj.(*objInfo)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"list error: %v\", &errWrongType{\"objInfo\", obj})\n\t\t\tcontinue\n\t\t}\n\t\tallObjs = append(allObjs, objInfo.latestObj)\n\t}\n\treturn allObjs\n}\n\nfunc (c *assumeCache) Assume(obj interface{}) error {\n\tname, err := cache.MetaNamespaceKeyFunc(obj)\n\tif err != nil {\n\t\treturn &errObjectName{err}\n\t}\n\n\tc.rwMutex.Lock()\n\tdefer c.rwMutex.Unlock()\n\n\tobjInfo, err := c.getObjInfo(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewVersion, err := c.getObjVersion(name, obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstoredVersion, err := c.getObjVersion(name, objInfo.latestObj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif newVersion < storedVersion {\n\t\treturn fmt.Errorf(\"%v %q is out of sync (stored: %d, assume: %d)\", c.description, name, storedVersion, newVersion)\n\t}\n\n\t\/\/ Only update the cached object\n\tobjInfo.latestObj = obj\n\tklog.V(4).Infof(\"Assumed %v %q, version %v\", c.description, name, newVersion)\n\treturn nil\n}\n\nfunc (c *assumeCache) Restore(objName string) {\n\tc.rwMutex.Lock()\n\tdefer c.rwMutex.Unlock()\n\n\tobjInfo, err := c.getObjInfo(objName)\n\tif err != nil {\n\t\t\/\/ This could be expected if object got deleted\n\t\tklog.V(5).Infof(\"Restore %v %q warning: %v\", c.description, objName, err)\n\t} else {\n\t\tobjInfo.latestObj = objInfo.apiObj\n\t\tklog.V(4).Infof(\"Restored %v %q\", c.description, objName)\n\t}\n}\n\n\/\/ PVAssumeCache is a AssumeCache for PersistentVolume objects\ntype PVAssumeCache interface {\n\tAssumeCache\n\n\tGetPV(pvName string) (*v1.PersistentVolume, error)\n\tGetAPIPV(pvName string) (*v1.PersistentVolume, error)\n\tListPVs(storageClassName string) []*v1.PersistentVolume\n}\n\ntype pvAssumeCache struct {\n\tAssumeCache\n}\n\nfunc pvStorageClassIndexFunc(obj interface{}) ([]string, error) {\n\tif pv, ok := obj.(*v1.PersistentVolume); ok {\n\t\treturn []string{v1helper.GetPersistentVolumeClass(pv)}, nil\n\t}\n\treturn []string{\"\"}, fmt.Errorf(\"object is not a v1.PersistentVolume: %v\", obj)\n}\n\n\/\/ NewPVAssumeCache creates a PV assume cache.\nfunc NewPVAssumeCache(informer cache.SharedIndexInformer) PVAssumeCache {\n\treturn &pvAssumeCache{NewAssumeCache(informer, \"v1.PersistentVolume\", \"storageclass\", pvStorageClassIndexFunc)}\n}\n\nfunc (c *pvAssumeCache) GetPV(pvName string) (*v1.PersistentVolume, error) {\n\tobj, err := c.Get(pvName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpv, ok := obj.(*v1.PersistentVolume)\n\tif !ok {\n\t\treturn nil, &errWrongType{\"v1.PersistentVolume\", obj}\n\t}\n\treturn pv, nil\n}\n\nfunc (c *pvAssumeCache) GetAPIPV(pvName string) (*v1.PersistentVolume, error) {\n\tobj, err := c.GetAPIObj(pvName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpv, ok := obj.(*v1.PersistentVolume)\n\tif !ok {\n\t\treturn nil, &errWrongType{\"v1.PersistentVolume\", obj}\n\t}\n\treturn pv, nil\n}\n\nfunc (c *pvAssumeCache) ListPVs(storageClassName string) []*v1.PersistentVolume {\n\tobjs := c.List(&v1.PersistentVolume{\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tStorageClassName: storageClassName,\n\t\t},\n\t})\n\tpvs := []*v1.PersistentVolume{}\n\tfor _, obj := range objs {\n\t\tpv, ok := obj.(*v1.PersistentVolume)\n\t\tif !ok {\n\t\t\tklog.Errorf(\"ListPVs: %v\", &errWrongType{\"v1.PersistentVolume\", obj})\n\t\t\tcontinue\n\t\t}\n\t\tpvs = append(pvs, pv)\n\t}\n\treturn pvs\n}\n\n\/\/ PVCAssumeCache is a AssumeCache for PersistentVolumeClaim objects\ntype PVCAssumeCache interface {\n\tAssumeCache\n\n\t\/\/ GetPVC returns the PVC from the cache with given pvcKey.\n\t\/\/ pvcKey is the result of MetaNamespaceKeyFunc on PVC obj\n\tGetPVC(pvcKey string) (*v1.PersistentVolumeClaim, error)\n\tGetAPIPVC(pvcKey string) (*v1.PersistentVolumeClaim, error)\n}\n\ntype pvcAssumeCache struct {\n\tAssumeCache\n}\n\n\/\/ NewPVCAssumeCache creates a PVC assume cache.\nfunc NewPVCAssumeCache(informer cache.SharedIndexInformer) PVCAssumeCache {\n\treturn &pvcAssumeCache{NewAssumeCache(informer, \"v1.PersistentVolumeClaim\", \"\", nil)}\n}\n\nfunc (c *pvcAssumeCache) GetPVC(pvcKey string) (*v1.PersistentVolumeClaim, error) {\n\tobj, err := c.Get(pvcKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpvc, ok := obj.(*v1.PersistentVolumeClaim)\n\tif !ok {\n\t\treturn nil, &errWrongType{\"v1.PersistentVolumeClaim\", obj}\n\t}\n\treturn pvc, nil\n}\n\nfunc (c *pvcAssumeCache) GetAPIPVC(pvcKey string) (*v1.PersistentVolumeClaim, error) {\n\tobj, err := c.GetAPIObj(pvcKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpvc, ok := obj.(*v1.PersistentVolumeClaim)\n\tif !ok {\n\t\treturn nil, &errWrongType{\"v1.PersistentVolumeClaim\", obj}\n\t}\n\treturn pvc, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package view\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/ywzjackal\/goweb\"\n)\n\nvar (\n\t\/\/ TemplateSuffix is template suffix -.-\n\tTemplateSuffix = \".html\"\n\t\/\/ TemplatePosition is template position path -.-\n\tTemplatePosition = \"\" \/\/\".\/templates\"\n\t\/\/ html.template delims attributes of left\n\tDelimsLeft = \"{{\"\n\t\/\/ html.template delims attributes of right\n\tDelimsRight = \"}}\"\n\t\/\/ views map container\n\tviews = make(map[string]goweb.View)\n\t\/\/ never mind! -.-\n\trootTemplate = template.New(\"\")\n\t\/\/\n\tTemplateFuncs = template.FuncMap{\n\t\t\"httpStatusText\": http.StatusText,\n\t}\n)\n\n\/\/ Initialize buildin view components\nfunc init() {\n\tRegisterView(\"html\", &viewHtml{})\n\tRegisterView(\"json\", &viewJson{})\n\tRegisterView(\"\", &view{})\n\t\/\/\n\t\/\/\tReloadTemplates()\n}\n\n\/\/ ReloadTemplates, you know what it will do. `.`\nfunc ReloadTemplates() {\n\tif TemplatePosition == \"\" {\n\t\tpanic(\"Please set `goweb.TemplatePosition to path of templates directory!`\")\n\t}\n\trootTemplate = template.New(\"\").Funcs(TemplateFuncs)\n\trootTemplate = template.Must(rootTemplate.Delims(DelimsLeft, DelimsRight).\n\t\tParseGlob(TemplatePosition + \"\/*\"))\n}\n\n\/\/ RegisterView should be called by custom view component in 'package file init() function'\n\/\/ will panic when register with duplicate name.\n\/\/\n\/\/ RegisterView 应该在用户引用的自定义视图组件的包文件的init（）函数中调用以注册新的视图组件\n\/\/ 如果出现panic，说明视图组件的名字被重复注册\nfunc RegisterView(name string, view goweb.View) {\n\tif _, ok := views[strings.ToLower(name)]; ok {\n\t\tpanic(\"Register view `\" + name + \"` duplicate!\")\n\t}\n\tviews[strings.ToLower(name)] = view\n}\n\nfunc GetView(name string) goweb.View {\n\tv, exist := views[name]\n\tif exist {\n\t\treturn v\n\t}\n\treturn nil\n}\n\ntype view struct {\n\tgoweb.View\n}\n\ntype ViewHtml interface {\n\tgoweb.View\n}\n\ntype ViewJson interface {\n\tgoweb.View\n}\n\ntype viewHtml struct {\n\tViewHtml\n\t*view\n\t\/\/\n\treq *http.Request\n}\n\ntype viewJson struct {\n\tViewJson\n\t*view\n}\n\nfunc (v *view) Render(c goweb.Controller, args ...interface{}) goweb.WebError {\n\t\/\/\traw := []byte(fmt.Sprintf(\"% +v, % +v\", c, args))\n\t\/\/\t_, err := c.Context().ResponseWriter().Write(raw)\n\t\/\/\tif err != nil {\n\t\/\/\t\treturn goweb.NewWebError(500, err.Error())\n\t\/\/\t}\n\treturn nil\n}\n\nfunc (v *viewHtml) Render(c goweb.Controller, args ...interface{}) (err goweb.WebError) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tc.Context().ResponseWriter().Write([]byte(fmt.Sprintf(\"%v\", r)))\n\t\t}\n\t}()\n\tvar (\n\t\tname = strings.ToLower(c.Context().Request().URL.Path)\n\t)\n\tif goweb.Debug {\n\t\tReloadTemplates()\n\t}\n\tbuffer := bytes.Buffer{}\n\twriter := bufio.NewWriter(&buffer)\n\tswitch len(args) {\n\tcase 0:\n\t\te := rootTemplate.ExecuteTemplate(writer, name, c)\n\t\tif e != nil {\n\t\t\treturn goweb.NewWebError(500, e.Error())\n\t\t}\n\tcase 1:\n\t\tname, ok := args[0].(string)\n\t\tif !ok {\n\t\t\treturn goweb.NewWebError(500, \"invalid view template name:%+v,need string\", args[0])\n\t\t}\n\t\te := rootTemplate.ExecuteTemplate(writer, name, c)\n\t\tif e != nil {\n\t\t\treturn goweb.NewWebError(500, e.Error())\n\t\t}\n\tdefault:\n\t\te := rootTemplate.ExecuteTemplate(writer, name, c)\n\t\tif e != nil {\n\t\t\treturn goweb.NewWebError(500, e.Error())\n\t\t}\n\t}\n\twriter.Flush()\n\tc.Context().ResponseWriter().Header().Add(\"Cache-Control\", \"no-store, must-revalidate\")\n\tc.Context().ResponseWriter().Header().Add(\"Pragma\", \"no-cache\")\n\tc.Context().ResponseWriter().Write(buffer.Bytes())\n\treturn err\n}\n\nfunc (v *viewJson) Render(c goweb.Controller, args ...interface{}) goweb.WebError {\n\tif len(args) == 0 {\n\t\tb, err := json.MarshalIndent(c, \"\", \" \")\n\t\tif err != nil {\n\t\t\treturn goweb.NewWebError(500, err.Error())\n\t\t}\n\t\tc.Context().ResponseWriter().Header().Add(\"Cache-Control\", \"no-store, must-revalidate\")\n\t\tc.Context().ResponseWriter().Header().Add(\"Pragma\", \"no-cache\")\n\t\t_, err = c.Context().ResponseWriter().Write(b)\n\t} else {\n\t\tb, err := json.MarshalIndent(args, \"\", \" \")\n\t\tif err != nil {\n\t\t\treturn goweb.NewWebError(500, err.Error())\n\t\t}\n\t\tc.Context().ResponseWriter().Header().Add(\"Cache-Control\", \"no-store, must-revalidate\")\n\t\tc.Context().ResponseWriter().Header().Add(\"Pragma\", \"no-cache\")\n\t\t_, err = c.Context().ResponseWriter().Write(b)\n\t}\n\treturn nil\n}\n<commit_msg>Fix json view render always as array Signed-off-by: jackal <ywzjackal@163.com><commit_after>package view\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/ywzjackal\/goweb\"\n)\n\nvar (\n\t\/\/ TemplateSuffix is template suffix -.-\n\tTemplateSuffix = \".html\"\n\t\/\/ TemplatePosition is template position path -.-\n\tTemplatePosition = \"\" \/\/\".\/templates\"\n\t\/\/ html.template delims attributes of left\n\tDelimsLeft = \"{{\"\n\t\/\/ html.template delims attributes of right\n\tDelimsRight = \"}}\"\n\t\/\/ views map container\n\tviews = make(map[string]goweb.View)\n\t\/\/ never mind! -.-\n\trootTemplate = template.New(\"\")\n\t\/\/\n\tTemplateFuncs = template.FuncMap{\n\t\t\"httpStatusText\": http.StatusText,\n\t}\n)\n\n\/\/ Initialize buildin view components\nfunc init() {\n\tRegisterView(\"html\", &viewHtml{})\n\tRegisterView(\"json\", &viewJson{})\n\tRegisterView(\"\", &view{})\n\t\/\/\n\t\/\/\tReloadTemplates()\n}\n\n\/\/ ReloadTemplates, you know what it will do. `.`\nfunc ReloadTemplates() {\n\tif TemplatePosition == \"\" {\n\t\tpanic(\"Please set `goweb.TemplatePosition to path of templates directory!`\")\n\t}\n\trootTemplate = template.New(\"\").Funcs(TemplateFuncs)\n\trootTemplate = template.Must(rootTemplate.Delims(DelimsLeft, DelimsRight).\n\t\tParseGlob(TemplatePosition + \"\/*\"))\n}\n\n\/\/ RegisterView should be called by custom view component in 'package file init() function'\n\/\/ will panic when register with duplicate name.\n\/\/\n\/\/ RegisterView 应该在用户引用的自定义视图组件的包文件的init（）函数中调用以注册新的视图组件\n\/\/ 如果出现panic，说明视图组件的名字被重复注册\nfunc RegisterView(name string, view goweb.View) {\n\tif _, ok := views[strings.ToLower(name)]; ok {\n\t\tpanic(\"Register view `\" + name + \"` duplicate!\")\n\t}\n\tviews[strings.ToLower(name)] = view\n}\n\nfunc GetView(name string) goweb.View {\n\tv, exist := views[name]\n\tif exist {\n\t\treturn v\n\t}\n\treturn nil\n}\n\ntype view struct {\n\tgoweb.View\n}\n\ntype ViewHtml interface {\n\tgoweb.View\n}\n\ntype ViewJson interface {\n\tgoweb.View\n}\n\ntype viewHtml struct {\n\tViewHtml\n\t*view\n\t\/\/\n\treq *http.Request\n}\n\ntype viewJson struct {\n\tViewJson\n\t*view\n}\n\nfunc (v *view) Render(c goweb.Controller, args ...interface{}) goweb.WebError {\n\t\/\/\traw := []byte(fmt.Sprintf(\"% +v, % +v\", c, args))\n\t\/\/\t_, err := c.Context().ResponseWriter().Write(raw)\n\t\/\/\tif err != nil {\n\t\/\/\t\treturn goweb.NewWebError(500, err.Error())\n\t\/\/\t}\n\treturn nil\n}\n\nfunc (v *viewHtml) Render(c goweb.Controller, args ...interface{}) (err goweb.WebError) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tc.Context().ResponseWriter().Write([]byte(fmt.Sprintf(\"%v\", r)))\n\t\t}\n\t}()\n\tvar (\n\t\tname = strings.ToLower(c.Context().Request().URL.Path)\n\t)\n\tif goweb.Debug {\n\t\tReloadTemplates()\n\t}\n\tbuffer := bytes.Buffer{}\n\twriter := bufio.NewWriter(&buffer)\n\tswitch len(args) {\n\tcase 0:\n\t\te := rootTemplate.ExecuteTemplate(writer, name, c)\n\t\tif e != nil {\n\t\t\treturn goweb.NewWebError(500, e.Error())\n\t\t}\n\tcase 1:\n\t\tname, ok := args[0].(string)\n\t\tif !ok {\n\t\t\treturn goweb.NewWebError(500, \"invalid view template name:%+v,need string\", args[0])\n\t\t}\n\t\te := rootTemplate.ExecuteTemplate(writer, name, c)\n\t\tif e != nil {\n\t\t\treturn goweb.NewWebError(500, e.Error())\n\t\t}\n\tdefault:\n\t\te := rootTemplate.ExecuteTemplate(writer, name, c)\n\t\tif e != nil {\n\t\t\treturn goweb.NewWebError(500, e.Error())\n\t\t}\n\t}\n\twriter.Flush()\n\tc.Context().ResponseWriter().Header().Add(\"Cache-Control\", \"no-store, must-revalidate\")\n\tc.Context().ResponseWriter().Header().Add(\"Pragma\", \"no-cache\")\n\tc.Context().ResponseWriter().Write(buffer.Bytes())\n\treturn err\n}\n\nfunc (v *viewJson) Render(c goweb.Controller, args ...interface{}) goweb.WebError {\n\tvar (\n\t\tb   []byte = nil\n\t\terr error  = nil\n\t)\n\tswitch len(args) {\n\tcase 0:\n\t\tb, err = json.MarshalIndent(c, \"\", \" \")\n\tcase 1:\n\t\tb, err = json.MarshalIndent(args[0], \"\", \" \")\n\tdefault:\n\t\tb, err = json.MarshalIndent(args, \"\", \" \")\n\t}\n\tif err != nil {\n\t\treturn goweb.NewWebError(500, err.Error())\n\t}\n\tc.Context().ResponseWriter().Header().Add(\"Cache-Control\", \"no-store, must-revalidate\")\n\tc.Context().ResponseWriter().Header().Add(\"Pragma\", \"no-cache\")\n\t_, err = c.Context().ResponseWriter().Write(b)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package actor\n\nimport (\n\t\"sync\"\n)\n\ntype eventStream struct {\n\tsync.RWMutex\n\tsubscriptions []*Subscription\n}\n\nvar (\n\tEventStream = &eventStream{}\n)\n\n\/\/ SubscriberFunc is the signature of an EventStream subscriber function\ntype SubscriberFunc func(msg interface{})\n\ntype Predicate func(msg interface{}) bool\n\n\/\/ Subscription is returned from the Subscribe function.\n\/\/\n\/\/ This value and can be passed to Unsubscribe when the observer is no longer interested in receiving messages\ntype Subscription struct {\n\ti  int\n\tfn SubscriberFunc\n\tp  Predicate\n}\n\n\/\/ WithPredicate sets a predicate to filter messages passed to the subscriber\nfunc (s *Subscription) WithPredicate(p Predicate) *Subscription {\n\ts.p = p\n\treturn s\n}\n\nfunc (es *eventStream) Subscribe(fn SubscriberFunc) *Subscription {\n\tes.Lock()\n\tsub := &Subscription{\n\t\ti:  len(es.subscriptions),\n\t\tfn: fn,\n\t}\n\tes.subscriptions = append(es.subscriptions, sub)\n\tes.Unlock()\n\treturn sub\n}\n\nfunc (es *eventStream) SubscribePID(pid *PID) *Subscription {\n\treturn es.Subscribe(pid.Tell)\n}\n\nfunc (es *eventStream) Unsubscribe(sub *Subscription) {\n\tif sub.i == -1 {\n\t\treturn\n\t}\n\n\tes.Lock()\n\ti := sub.i\n\tl := len(es.subscriptions) - 1\n\n\tes.subscriptions[i] = es.subscriptions[l]\n\tes.subscriptions[i].i = i\n\tes.subscriptions[l] = nil\n\tes.subscriptions = es.subscriptions[:l]\n\tsub.i = -1\n\n\t\/\/ TODO(SGC): implement resizing\n\tif len(es.subscriptions) == 0 {\n\t\tes.subscriptions = nil\n\t}\n\n\tes.Unlock()\n}\n\nfunc (es *eventStream) Publish(message interface{}) {\n\tes.RLock()\n\tdefer es.RUnlock()\n\n\tfor _, s := range es.subscriptions {\n\t\tif s.p == nil || s.p(message) {\n\t\t\ts.fn(message)\n\t\t}\n\t}\n}\n<commit_msg>serialize modification of predicate<commit_after>package actor\n\nimport (\n\t\"sync\"\n)\n\ntype eventStream struct {\n\tsync.RWMutex\n\tsubscriptions []*Subscription\n}\n\nvar (\n\tEventStream = &eventStream{}\n)\n\n\/\/ SubscriberFunc is the signature of an EventStream subscriber function\ntype SubscriberFunc func(msg interface{})\n\n\/\/ Predicate is a function used to filter messages before being forwarded to a SubscriberFunc\ntype Predicate func(msg interface{}) bool\n\n\/\/ Subscription is returned from the Subscribe function.\n\/\/\n\/\/ This value and can be passed to Unsubscribe when the observer is no longer interested in receiving messages\ntype Subscription struct {\n\tes *eventStream\n\ti  int\n\tfn SubscriberFunc\n\tp  Predicate\n}\n\n\/\/ WithPredicate sets a predicate to filter messages passed to the subscriber\nfunc (s *Subscription) WithPredicate(p Predicate) *Subscription {\n\ts.es.Lock()\n\ts.p = p\n\ts.es.Unlock()\n\treturn s\n}\n\nfunc (es *eventStream) Subscribe(fn SubscriberFunc) *Subscription {\n\tes.Lock()\n\tsub := &Subscription{\n\t\tes: es,\n\t\ti:  len(es.subscriptions),\n\t\tfn: fn,\n\t}\n\tes.subscriptions = append(es.subscriptions, sub)\n\tes.Unlock()\n\treturn sub\n}\n\nfunc (es *eventStream) SubscribePID(pid *PID) *Subscription {\n\treturn es.Subscribe(pid.Tell)\n}\n\nfunc (es *eventStream) Unsubscribe(sub *Subscription) {\n\tif sub.i == -1 {\n\t\treturn\n\t}\n\n\tes.Lock()\n\ti := sub.i\n\tl := len(es.subscriptions) - 1\n\n\tes.subscriptions[i] = es.subscriptions[l]\n\tes.subscriptions[i].i = i\n\tes.subscriptions[l] = nil\n\tes.subscriptions = es.subscriptions[:l]\n\tsub.i = -1\n\n\t\/\/ TODO(SGC): implement resizing\n\tif len(es.subscriptions) == 0 {\n\t\tes.subscriptions = nil\n\t}\n\n\tes.Unlock()\n}\n\nfunc (es *eventStream) Publish(message interface{}) {\n\tes.RLock()\n\tdefer es.RUnlock()\n\n\tfor _, s := range es.subscriptions {\n\t\tif s.p == nil || s.p(message) {\n\t\t\ts.fn(message)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package root\n\nimport (\n\t\"fmt\"\n\t\"github.com\/Aptomi\/aptomi\/cmd\/aptomictl\/endpoints\"\n\t\"github.com\/Aptomi\/aptomi\/cmd\/aptomictl\/policy\"\n\t\"github.com\/Aptomi\/aptomi\/cmd\/aptomictl\/revision\"\n\t\"github.com\/Aptomi\/aptomi\/cmd\/common\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/config\"\n\t\"github.com\/mitchellh\/go-homedir\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n\t\"path\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ EnvPrefix is the prefix for all environment variables used by aptomictl\n\tEnvPrefix = \"APTOMICTL\"\n)\n\nvar (\n\t\/\/ Config is the global instance of the client config\n\tConfig = &config.Client{}\n\n\t\/\/ Command is the main (root) cobra command for aptomictl\n\tCommand = &cobra.Command{\n\t\tUse:   \"aptomictl\",\n\t\tShort: \"aptomictl controls Aptomi\",\n\t\tLong:  \"aptomictl controls Aptomi\",\n\n\t\tPersistentPreRun: preRun,\n\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\t\/\/ fall back on default help if no args\/flags are passed\n\t\t\tcmd.HelpFunc()(cmd, args)\n\t\t},\n\t}\n)\n\nfunc init() {\n\tviper.SetEnvPrefix(EnvPrefix)\n\n\tcommon.AddDefaultFlags(Command, EnvPrefix)\n\n\tcommon.AddStringFlag(Command, \"auth.username\", \"username\", \"u\", \"\", EnvPrefix+\"_USERNAME\", \"Username\")\n\tcommon.AddDurationFlag(Command, \"http.timeout\", \"timeout\", \"\", 15*time.Second, EnvPrefix+\"_TIMEOUT\", \"HTTP Timeout\")\n\n\t\/\/ Add sub commands\n\tCommand.AddCommand(\n\t\tcommon.Version,\n\t\tendpoints.NewCommand(Config),\n\t\tpolicy.NewCommand(Config),\n\t\trevision.NewCommand(Config),\n\t)\n}\n\nfunc preRun(command *cobra.Command, args []string) {\n\terr := common.ReadConfig(viper.GetViper(), Config, defaultConfigDir())\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"error while loading config: %s\", err))\n\t}\n}\n\nfunc defaultConfigDir() string {\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"can't find home dir: %s\", err))\n\t}\n\n\treturn path.Join(home, \".aptomi\")\n}\n<commit_msg>Add --output\/-o flag for setting desired output format for aptomictl<commit_after>package root\n\nimport (\n\t\"fmt\"\n\t\"github.com\/Aptomi\/aptomi\/cmd\/aptomictl\/endpoints\"\n\t\"github.com\/Aptomi\/aptomi\/cmd\/aptomictl\/policy\"\n\t\"github.com\/Aptomi\/aptomi\/cmd\/aptomictl\/revision\"\n\t\"github.com\/Aptomi\/aptomi\/cmd\/common\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/config\"\n\t\"github.com\/mitchellh\/go-homedir\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n\t\"path\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ EnvPrefix is the prefix for all environment variables used by aptomictl\n\tEnvPrefix = \"APTOMICTL\"\n)\n\nvar (\n\t\/\/ Config is the global instance of the client config\n\tConfig = &config.Client{}\n\n\t\/\/ Command is the main (root) cobra command for aptomictl\n\tCommand = &cobra.Command{\n\t\tUse:   \"aptomictl\",\n\t\tShort: \"aptomictl controls Aptomi\",\n\t\tLong:  \"aptomictl controls Aptomi\",\n\n\t\tPersistentPreRun: preRun,\n\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\t\/\/ fall back on default help if no args\/flags are passed\n\t\t\tcmd.HelpFunc()(cmd, args)\n\t\t},\n\t}\n)\n\nfunc init() {\n\tviper.SetEnvPrefix(EnvPrefix)\n\n\tcommon.AddDefaultFlags(Command, EnvPrefix)\n\n\tcommon.AddStringFlag(Command, \"output\", \"output\", \"o\", \"text\", EnvPrefix+\"_OUTPUT\", \"Output format. One of: text (default), json, yaml\")\n\n\tcommon.AddStringFlag(Command, \"auth.username\", \"username\", \"u\", \"\", EnvPrefix+\"_USERNAME\", \"Username\")\n\tcommon.AddDurationFlag(Command, \"http.timeout\", \"timeout\", \"\", 15*time.Second, EnvPrefix+\"_TIMEOUT\", \"HTTP Timeout\")\n\n\t\/\/ Add sub commands\n\tCommand.AddCommand(\n\t\tcommon.Version,\n\t\tendpoints.NewCommand(Config),\n\t\tpolicy.NewCommand(Config),\n\t\trevision.NewCommand(Config),\n\t)\n}\n\nfunc preRun(command *cobra.Command, args []string) {\n\terr := common.ReadConfig(viper.GetViper(), Config, defaultConfigDir())\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"error while loading config: %s\", err))\n\t}\n}\n\nfunc defaultConfigDir() string {\n\thome, err := homedir.Dir()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"can't find home dir: %s\", err))\n\t}\n\n\treturn path.Join(home, \".aptomi\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 The Jetstack cert-manager contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage renew\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cobra\"\n\tcorev1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/cli-runtime\/pkg\/genericclioptions\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\tcmdutil \"k8s.io\/kubectl\/pkg\/cmd\/util\"\n\n\tapiutil \"github.com\/jetstack\/cert-manager\/pkg\/api\/util\"\n\tcmapi \"github.com\/jetstack\/cert-manager\/pkg\/apis\/certmanager\/v1alpha2\"\n\tcmmeta \"github.com\/jetstack\/cert-manager\/pkg\/apis\/meta\/v1\"\n\tcmclient \"github.com\/jetstack\/cert-manager\/pkg\/client\/clientset\/versioned\"\n)\n\n\/\/ Options is a struct to support version command\ntype Options struct {\n\t\/\/ The Namespace that the Certificate to be renewed resided in\n\tNamespace string\n\n\tLabelSelector string\n\n\tAll  bool\n\tWait bool\n\n\tAllNamespaces bool\n\n\tPollTime time.Duration\n\tTimeout  time.Duration\n\n\tgenericclioptions.IOStreams\n}\n\n\/\/ NewOptions returns initialized Options\nfunc NewOptions(ioStreams genericclioptions.IOStreams) *Options {\n\treturn &Options{\n\t\tIOStreams: ioStreams,\n\t}\n}\n\n\/\/ NewCmdRenew returns a cobra command for renewing Certificates\nfunc NewCmdRenew(ioStreams genericclioptions.IOStreams, factory cmdutil.Factory) *cobra.Command {\n\to := NewOptions(ioStreams)\n\n\tcmd := &cobra.Command{\n\t\tUse:   \"renew\",\n\t\tShort: \"Mark a Certificate for manual renewal\",\n\t\tLong:  \"Mark a Certificate for manual renewal\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(factory, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate(cmd, args))\n\t\t\tcmdutil.CheckErr(o.Run(factory, cmd, args))\n\t\t},\n\t}\n\n\tcmd.Flags().StringVarP(&o.LabelSelector, \"selector\", \"l\", o.LabelSelector, \"Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)\")\n\tcmd.Flags().BoolVarP(&o.AllNamespaces, \"all-namespaces\", \"A\", o.AllNamespaces, \"If present, wait for Certificates across all namespaces to become ready. Namespace in current context is ignored even if specified with --namespace.\")\n\tcmd.Flags().BoolVar(&o.All, \"all\", o.All, \"Renew all Certificates in the given Namespace, or all namespaces with --all-namespaces enabled.\")\n\tcmd.Flags().BoolVarP(&o.Wait, \"wait\", \"w\", o.Wait, \"Wait for all Certificates to become ready once being marked for renewal.\")\n\tcmd.Flags().DurationVar(&o.PollTime, \"poll-time\", time.Second*2, \"Poll period between checking Certificates to become ready. Used in conjunction with --wait.\")\n\tcmd.Flags().DurationVar(&o.Timeout, \"timeout\", 0, \"The length of time to wait before ending watch, zero means never. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h).\")\n\n\treturn cmd\n}\n\n\/\/ Validate validates the provided options\nfunc (o *Options) Validate(cmd *cobra.Command, args []string) error {\n\tif len(o.LabelSelector) > 0 && len(args) > 0 {\n\t\treturn errors.New(\"cannot specify Certificate arguments as well as label selectors\")\n\t}\n\n\tif o.All && len(args) > 0 {\n\t\treturn errors.New(\"cannot specify Certificate arguments as well as --all flag\")\n\t}\n\n\tif o.All && len(o.LabelSelector) > 0 {\n\t\treturn errors.New(\"cannot specify label selector as well as --all flag\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Complete takes the command arguments and factory and infers any remaining options.\nfunc (o *Options) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Run executes version command\nfunc (o *Options) Run(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\trestConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmClient, err := cmclient.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnss := []corev1.Namespace{{ObjectMeta: metav1.ObjectMeta{Name: o.Namespace}}}\n\n\t\/\/ TODO: handle network context\n\n\tif o.AllNamespaces {\n\t\tkubeClient, err := kubernetes.NewForConfig(restConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnsList, err := kubeClient.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnss = nsList.Items\n\t}\n\n\tvar crts []cmapi.Certificate\n\tfor _, ns := range nss {\n\t\tswitch {\n\t\tcase o.All:\n\t\t\tcrtsList, err := cmClient.CertmanagerV1alpha2().Certificates(ns.Name).List(context.TODO(), metav1.ListOptions{})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcrts = append(crts, crtsList.Items...)\n\n\t\tcase len(o.LabelSelector) > 0:\n\t\t\tcrtsList, err := cmClient.CertmanagerV1alpha2().Certificates(ns.Name).List(context.TODO(), metav1.ListOptions{\n\t\t\t\tLabelSelector: o.LabelSelector,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcrts = append(crts, crtsList.Items...)\n\n\t\tdefault:\n\t\t\tfor _, crtName := range args {\n\t\t\t\tcrt, err := cmClient.CertmanagerV1alpha2().Certificates(ns.Name).Get(context.TODO(), crtName, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tcrts = append(crts, *crt)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(crts) == 0 {\n\t\tif o.AllNamespaces {\n\t\t\tfmt.Fprintln(o.ErrOut, \"No Certificates found\")\n\t\t} else {\n\t\t\tfmt.Fprintf(o.ErrOut, \"No Certificates found in %s namespace.\\n\", o.Namespace)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tfor _, crt := range crts {\n\t\tif err := o.renewCertificate(cmClient, &crt); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif o.Wait {\n\t\tif err := o.waitCertificatesReady(cmClient, crts); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Fprintf(o.Out, \"%d Certificates successfully renewed\\n\", len(crts))\n\t}\n\n\treturn nil\n}\n\nfunc (o *Options) renewCertificate(cmClient *cmclient.Clientset, crt *cmapi.Certificate) error {\n\tapiutil.SetCertificateCondition(crt, cmapi.CertificateConditionIssuing, cmmeta.ConditionTrue, \"ManuallyTriggered\", \"Certificate re-issuance manually triggered\")\n\t_, err := cmClient.CertmanagerV1alpha2().Certificates(crt.Namespace).UpdateStatus(context.TODO(), crt, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to trigger issuance of Certificate %s\/%s: %v\", crt.Namespace, crt.Name, err)\n\t}\n\tfmt.Fprintf(o.Out, \"Manually triggered issuance of Certificate %s\/%s\\n\", crt.Namespace, crt.Name)\n\treturn nil\n}\n\nfunc (o *Options) waitCertificatesReady(cmClient *cmclient.Clientset, crts []cmapi.Certificate) error {\n\t\/\/ TODO: start poll time after all get requests?\n\tticker := time.NewTicker(o.PollTime)\n\tdefer ticker.Stop()\n\n\tctx := context.TODO()\n\n\tif o.Timeout > 0 {\n\t\tvar cancel func()\n\t\tctx, cancel = context.WithTimeout(ctx, o.Timeout)\n\t\tdefer cancel()\n\t}\n\n\tfor {\n\t\tlenReady := 0\n\n\t\tfor _, crt := range crts {\n\t\t\tcrt, err := cmClient.CertmanagerV1alpha2().Certificates(crt.Namespace).Get(context.TODO(), crt.Name, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\t\/\/ TODO: handle certificate no longer existing?\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif cond := apiutil.GetCertificateCondition(crt, cmapi.CertificateConditionIssuing); cond != nil && cond.Status == cmmeta.ConditionTrue {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif cond := apiutil.GetCertificateCondition(crt, cmapi.CertificateConditionReady); cond != nil && cond.Status == cmmeta.ConditionTrue {\n\t\t\t\tlenReady++\n\t\t\t}\n\t\t}\n\n\t\tif lenReady == len(crts) {\n\t\t\treturn nil\n\t\t}\n\n\t\tfmt.Fprintf(o.Out, \"Currently %d Certificates out of %d are ready...\\n\", lenReady, len(crts))\n\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tcontinue\n\t\tcase <-ctx.Done():\n\t\t\treturn fmt.Errorf(\"%d Certificates failed to become ready in time\", len(crts)-lenReady)\n\t\t}\n\t}\n}\n<commit_msg>All ctl renew -A and -l options together<commit_after>\/*\nCopyright 2020 The Jetstack cert-manager contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage renew\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cobra\"\n\tcorev1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/cli-runtime\/pkg\/genericclioptions\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\tcmdutil \"k8s.io\/kubectl\/pkg\/cmd\/util\"\n\n\tapiutil \"github.com\/jetstack\/cert-manager\/pkg\/api\/util\"\n\tcmapi \"github.com\/jetstack\/cert-manager\/pkg\/apis\/certmanager\/v1alpha2\"\n\tcmmeta \"github.com\/jetstack\/cert-manager\/pkg\/apis\/meta\/v1\"\n\tcmclient \"github.com\/jetstack\/cert-manager\/pkg\/client\/clientset\/versioned\"\n)\n\n\/\/ Options is a struct to support renew command\ntype Options struct {\n\t\/\/ The Namespace that the Certificate to be renewed resided in\n\tNamespace string\n\n\tLabelSelector string\n\n\tAll  bool\n\tWait bool\n\n\tAllNamespaces bool\n\n\tPollTime time.Duration\n\tTimeout  time.Duration\n\n\tgenericclioptions.IOStreams\n}\n\n\/\/ NewOptions returns initialized Options\nfunc NewOptions(ioStreams genericclioptions.IOStreams) *Options {\n\treturn &Options{\n\t\tIOStreams: ioStreams,\n\t}\n}\n\n\/\/ NewCmdRenew returns a cobra command for renewing Certificates\nfunc NewCmdRenew(ioStreams genericclioptions.IOStreams, factory cmdutil.Factory) *cobra.Command {\n\to := NewOptions(ioStreams)\n\n\tcmd := &cobra.Command{\n\t\tUse:   \"renew\",\n\t\tShort: \"Mark a Certificate for manual renewal\",\n\t\tLong:  \"Mark a Certificate for manual renewal\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(o.Complete(factory, cmd, args))\n\t\t\tcmdutil.CheckErr(o.Validate(cmd, args))\n\t\t\tcmdutil.CheckErr(o.Run(factory, cmd, args))\n\t\t},\n\t}\n\n\tcmd.Flags().StringVarP(&o.LabelSelector, \"selector\", \"l\", o.LabelSelector, \"Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)\")\n\tcmd.Flags().BoolVarP(&o.AllNamespaces, \"all-namespaces\", \"A\", o.AllNamespaces, \"If present, wait for Certificates across all namespaces to become ready. Namespace in current context is ignored even if specified with --namespace.\")\n\tcmd.Flags().BoolVar(&o.All, \"all\", o.All, \"Renew all Certificates in the given Namespace, or all namespaces with --all-namespaces enabled.\")\n\tcmd.Flags().BoolVarP(&o.Wait, \"wait\", \"w\", o.Wait, \"Wait for all Certificates to become ready once being marked for renewal.\")\n\tcmd.Flags().DurationVar(&o.PollTime, \"poll-time\", time.Second*2, \"Poll period between checking Certificates to become ready. Used in conjunction with --wait.\")\n\tcmd.Flags().DurationVar(&o.Timeout, \"timeout\", 0, \"The length of time to wait before ending watch, zero means never. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h).\")\n\n\treturn cmd\n}\n\n\/\/ Validate validates the provided options\nfunc (o *Options) Validate(cmd *cobra.Command, args []string) error {\n\tif len(o.LabelSelector) > 0 && len(args) > 0 {\n\t\treturn errors.New(\"cannot specify Certificate arguments as well as label selectors\")\n\t}\n\n\tif o.All && len(args) > 0 {\n\t\treturn errors.New(\"cannot specify Certificate arguments as well as --all flag\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Complete takes the command arguments and factory and infers any remaining options.\nfunc (o *Options) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\tvar err error\n\to.Namespace, _, err = f.ToRawKubeConfigLoader().Namespace()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Run executes renew command\nfunc (o *Options) Run(f cmdutil.Factory, cmd *cobra.Command, args []string) error {\n\trestConfig, err := f.ToRESTConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmClient, err := cmclient.NewForConfig(restConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnss := []corev1.Namespace{{ObjectMeta: metav1.ObjectMeta{Name: o.Namespace}}}\n\n\t\/\/ TODO: handle network context\n\n\tif o.AllNamespaces {\n\t\tkubeClient, err := kubernetes.NewForConfig(restConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnsList, err := kubeClient.CoreV1().Namespaces().List(context.TODO(), metav1.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnss = nsList.Items\n\t}\n\n\tvar crts []cmapi.Certificate\n\tfor _, ns := range nss {\n\t\tswitch {\n\t\tcase o.All, len(o.LabelSelector) > 0:\n\t\t\tcrtsList, err := cmClient.CertmanagerV1alpha2().Certificates(ns.Name).List(context.TODO(), metav1.ListOptions{\n\t\t\t\tLabelSelector: o.LabelSelector,\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcrts = append(crts, crtsList.Items...)\n\n\t\tdefault:\n\t\t\tfor _, crtName := range args {\n\t\t\t\tcrt, err := cmClient.CertmanagerV1alpha2().Certificates(ns.Name).Get(context.TODO(), crtName, metav1.GetOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tcrts = append(crts, *crt)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(crts) == 0 {\n\t\tif o.AllNamespaces {\n\t\t\tfmt.Fprintln(o.ErrOut, \"No Certificates found\")\n\t\t} else {\n\t\t\tfmt.Fprintf(o.ErrOut, \"No Certificates found in %s namespace.\\n\", o.Namespace)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tfor _, crt := range crts {\n\t\tif err := o.renewCertificate(cmClient, &crt); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif o.Wait {\n\t\tif err := o.waitCertificatesReady(cmClient, crts); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Fprintf(o.Out, \"%d Certificates successfully renewed\\n\", len(crts))\n\t}\n\n\treturn nil\n}\n\nfunc (o *Options) renewCertificate(cmClient *cmclient.Clientset, crt *cmapi.Certificate) error {\n\tapiutil.SetCertificateCondition(crt, cmapi.CertificateConditionIssuing, cmmeta.ConditionTrue, \"ManuallyTriggered\", \"Certificate re-issuance manually triggered\")\n\t_, err := cmClient.CertmanagerV1alpha2().Certificates(crt.Namespace).UpdateStatus(context.TODO(), crt, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to trigger issuance of Certificate %s\/%s: %v\", crt.Namespace, crt.Name, err)\n\t}\n\tfmt.Fprintf(o.Out, \"Manually triggered issuance of Certificate %s\/%s\\n\", crt.Namespace, crt.Name)\n\treturn nil\n}\n\nfunc (o *Options) waitCertificatesReady(cmClient *cmclient.Clientset, crts []cmapi.Certificate) error {\n\t\/\/ TODO: start poll time after all get requests?\n\tticker := time.NewTicker(o.PollTime)\n\tdefer ticker.Stop()\n\n\tctx := context.TODO()\n\n\tif o.Timeout > 0 {\n\t\tvar cancel func()\n\t\tctx, cancel = context.WithTimeout(ctx, o.Timeout)\n\t\tdefer cancel()\n\t}\n\n\tfor {\n\t\tlenReady := 0\n\n\t\tfor _, crt := range crts {\n\t\t\tcrt, err := cmClient.CertmanagerV1alpha2().Certificates(crt.Namespace).Get(context.TODO(), crt.Name, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\t\/\/ TODO: handle certificate no longer existing?\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif cond := apiutil.GetCertificateCondition(crt, cmapi.CertificateConditionIssuing); cond != nil && cond.Status == cmmeta.ConditionTrue {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif cond := apiutil.GetCertificateCondition(crt, cmapi.CertificateConditionReady); cond != nil && cond.Status == cmmeta.ConditionTrue {\n\t\t\t\tlenReady++\n\t\t\t}\n\t\t}\n\n\t\tif lenReady == len(crts) {\n\t\t\treturn nil\n\t\t}\n\n\t\tfmt.Fprintf(o.Out, \"Currently %d Certificates out of %d are ready...\\n\", lenReady, len(crts))\n\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tcontinue\n\t\tcase <-ctx.Done():\n\t\t\treturn fmt.Errorf(\"%d Certificates failed to become ready in time\", len(crts)-lenReady)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/datawire\/ambassador\/pkg\/k8s\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nfunc aesInstallCmd() *cobra.Command {\n\tres := &cobra.Command{\n\t\tUse:   \"install\",\n\t\tShort: \"Install the Ambassador Edge Stack in your cluster\",\n\t\tArgs:  cobra.ExactArgs(0),\n\t\tRunE:  aesInstall,\n\t}\n\t_ = res.Flags().StringP(\n\t\t\"context\", \"c\", \"\",\n\t\t\"The Kubernetes context to use. Defaults to the current kubectl context.\",\n\t)\n\t_ = res.Flags().StringP(\n\t\t\"namespace\", \"n\", \"\",\n\t\t\"The Kubernetes namespace to use. Defaults to kubectl's default for the context.\",\n\t)\n\n\treturn res\n}\n\nfunc aesInstall(cmd *cobra.Command, args []string) error {\n\tmetrics := NewMetrics()\n\t_ = metrics.Report(\"install\")\n\n\t\/\/ Display version information\n\tfmt.Printf(\"-> Installing the Ambassador Edge Stack %s\\n\", Version)\n\n\t\/\/ Attempt to talk to the specified cluster\n\tcontext, _ := cmd.Flags().GetString(\"context\")\n\tnamespace, _ := cmd.Flags().GetString(\"namespace\")\n\tkubeinfo := k8s.NewKubeInfo(\"\", context, namespace)\n\ti := &Installer{\n\t\tkubeinfo,\n\t}\n\tif err := i.ShowKubectl(\"cluster-info\", \"cluster-info\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := i.ShowKubectl(\"install CRDs\", \"apply\", \"-f\", \"https:\/\/www.getambassador.io\/yaml\/aes-crds.yaml\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := i.ShowKubectl(\"wait for CRDs\", \"wait\", \"--for\", \"condition=established\", \"--timeout=90s\", \"crd\", \"-lproduct=aes\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := i.ShowKubectl(\"install AES\", \"apply\", \"-f\", \"https:\/\/www.getambassador.io\/yaml\/aes.yaml\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := i.ShowKubectl(\"wait for AES\", \"-n\", \"ambassador\", \"wait\", \"--for\", \"condition=available\", \"--timeout=90s\", \"deploy\", \"-lproduct=aes\"); err != nil {\n\t\treturn err\n\t}\n\n\t_ = metrics.Report(\"deploy\") \/\/ TODO: Send cluster type and Helm version\n\n\tipAddress := \"\"\n\tfor {\n\t\tvar err error\n\t\tipAddress, err = i.CaptureKubectl(\"get IP address\", \"get\", \"-n\", \"ambassador\", \"service\", \"ambassador\", \"-o\", `go-template={{range .status.loadBalancer.ingress}}{{print .ip \"\\n\"}}{{end}}`)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tipAddress = strings.TrimSpace(ipAddress)\n\t\tif ipAddress != \"\" {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(250 * time.Millisecond) \/\/ FIXME: Time out at some point...\n\t}\n\n\tfmt.Println(\"Your IP address is\", ipAddress)\n\n\t\/\/ Send a request to acquire a DNS name for this cluster's IP address\n\tregURL := \"https:\/\/metriton.datawire.io\/beta\/register-domain\"\n\temailAddress := \"ark3+eci@datawire.io\"\n\tbuf := new(bytes.Buffer)\n\t_ = json.NewEncoder(buf).Encode(registration{emailAddress, ipAddress})\n\tresp, err := http.Post(regURL, \"application\/json\", buf)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"acquire DNS name (post)\")\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"acquire DNS name (read body)\")\n\t}\n\n\tif resp.StatusCode == 200 {\n\t\thostname := string(content)\n\t\tfmt.Println(\"-> Acquiring DNS name\", hostname)\n\n\t\t\/\/ Wait for DNS to propagate. This tries to avoid waiting for a ten\n\t\t\/\/ minute error backoff if the ACME registration races ahead of the DNS\n\t\t\/\/ name appearing for LetsEncrypt.\n\t\tfor {\n\t\t\tconn, err := net.Dial(\"tcp\", hostname+\":443\")\n\t\t\tif err == nil {\n\t\t\t\tconn.Close()\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t\/\/ fmt.Printf(\"Waiting for DNS: %#v\\n\", err)\n\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t}\n\t\tfmt.Println(\"-> Automatically configuring TLS\")\n\t\tfmt.Println(\"Please enter an email address. We'll use this email address to notify you prior to domain and certification expiration [None]:\", emailAddress)\n\t\tfmt.Println(\"FIXME: let the user enter an address\")\n\t\t\/\/ Create a Host resource\n\t\thostResource := fmt.Sprintf(hostManifest, hostname, namespace, hostname, emailAddress)\n\t\tkargs, err := i.kubeinfo.GetKubectlArray(\"apply\", \"-f\", \"-\")\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"cluster access for install AES\")\n\t\t}\n\t\tfmt.Println(\"\\n$ kubectl apply -f - < [Host Resource]\")\n\t\tcmd := exec.Command(\"kubectl\", kargs...)\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\tcmd.Stdin = strings.NewReader(hostResource)\n\t\tif err := cmd.Run(); err != nil {\n\t\t\treturn errors.Wrap(err, \"install AES\")\n\t\t}\n\n\t\tfmt.Println(\"\\n-> Obtaining a TLS certificate from Let's Encrypt\")\n\n\t\tfor {\n\t\t\tstate, err := i.CaptureKubectl(\"get Host state\", \"get\", \"host\", hostname, \"-o\", \"go-template={{.status.state}}\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif state == \"Ready\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(500 * time.Millisecond) \/\/ FIXME: Time out at some point...\n\t\t\t\/\/ FIXME: Do something smart for state == \"Error\"\n\t\t}\n\n\t\t_ = metrics.Report(\"cert_provisioned\")\n\t\tfmt.Println(\"-> TLS configured successfully\")\n\t\tif err := i.ShowKubectl(\"show Host\", \"get\", \"host\", hostname); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ TODO: Open browser (do edgectl login)\n\n\t} else {\n\t\tfmt.Println(\"-> Failed to create a DNS name\", content)\n\t\t\/\/   if reachable from host (e.g., k3s, special case for Minikube?)\n\t\t\/\/     open a browser window to http...\n\t\t\/\/   else\n\t\t\/\/     suggest port-forward to reach policy console?\n\t}\n\n\t_ = metrics.Report(\"aes_health_good\") \/\/ or aes_health_bad TODO: Send cluster's install_id and AES version\n\n\treturn nil\n}\n\ntype Installer struct {\n\tkubeinfo *k8s.KubeInfo\n}\n\n\/\/ Kubernetes Cluster\n\nfunc (i *Installer) ShowKubectl(name string, args ...string) error {\n\tkargs, err := i.kubeinfo.GetKubectlArray(args...)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"cluster access for %s\", name)\n\t}\n\tfmt.Printf(\"\\n$ kubectl %s\\n\", strings.Join(kargs, \" \"))\n\tcmd := exec.Command(\"kubectl\", kargs...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn errors.Wrap(err, name)\n\t}\n\treturn nil\n}\n\nfunc (i *Installer) CaptureKubectl(name string, args ...string) (res string, err error) {\n\tres = \"\"\n\tkargs, err := i.kubeinfo.GetKubectlArray(args...)\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"cluster access for %s\", name)\n\t\treturn\n\t}\n\tfmt.Printf(\"\\n$ kubectl %s\\n\", strings.Join(kargs, \" \"))\n\tcmd := exec.Command(\"kubectl\", kargs...)\n\tcmd.Stderr = nil\n\tresAsBytes, err := cmd.Output()\n\tif err != nil {\n\t\tif ee, ok := err.(*exec.ExitError); ok {\n\t\t\tfmt.Println(ee.Stderr)\n\t\t}\n\t\terr = errors.Wrap(err, name)\n\t}\n\tres = string(resAsBytes)\n\treturn\n}\n\n\/\/ DNS Registration\n\ntype registration struct {\n\tEmail string\n\tIp    string\n}\n\n\/\/ Metrics\n\ntype Metrics struct {\n\tInstallID string\n}\n\nfunc NewMetrics() *Metrics {\n\t\/\/ TODO: Read or create an installation ID\n\treturn nil\n}\n\nfunc (m *Metrics) Report(eventName string) error {\n\tfmt.Println(\"-> [Metrics]\", eventName)\n\treturn nil\n}\n\nconst hostManifest = `\napiVersion: getambassador.io\/v2\nkind: Host\nmetadata:\n  name: %s\n  namespace: %s\nspec:\n  hostname: %s\n  acmeProvider:\n    email: %s\n`\n<commit_msg>Call login from install<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/datawire\/ambassador\/pkg\/k8s\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nfunc aesInstallCmd() *cobra.Command {\n\tres := &cobra.Command{\n\t\tUse:   \"install\",\n\t\tShort: \"Install the Ambassador Edge Stack in your cluster\",\n\t\tArgs:  cobra.ExactArgs(0),\n\t\tRunE:  aesInstall,\n\t}\n\t_ = res.Flags().StringP(\n\t\t\"context\", \"c\", \"\",\n\t\t\"The Kubernetes context to use. Defaults to the current kubectl context.\",\n\t)\n\t_ = res.Flags().StringP(\n\t\t\"namespace\", \"n\", \"\",\n\t\t\"The Kubernetes namespace to use. Defaults to kubectl's default for the context.\",\n\t)\n\n\treturn res\n}\n\nfunc aesInstall(cmd *cobra.Command, args []string) error {\n\tmetrics := NewMetrics()\n\t_ = metrics.Report(\"install\")\n\n\t\/\/ Display version information\n\tfmt.Printf(\"-> Installing the Ambassador Edge Stack %s\\n\", Version)\n\n\t\/\/ Attempt to talk to the specified cluster\n\tcontext, _ := cmd.Flags().GetString(\"context\")\n\tnamespace, _ := cmd.Flags().GetString(\"namespace\")\n\tkubeinfo := k8s.NewKubeInfo(\"\", context, namespace)\n\ti := &Installer{\n\t\tkubeinfo,\n\t}\n\tif err := i.ShowKubectl(\"cluster-info\", \"cluster-info\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := i.ShowKubectl(\"install CRDs\", \"apply\", \"-f\", \"https:\/\/www.getambassador.io\/yaml\/aes-crds.yaml\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := i.ShowKubectl(\"wait for CRDs\", \"wait\", \"--for\", \"condition=established\", \"--timeout=90s\", \"crd\", \"-lproduct=aes\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := i.ShowKubectl(\"install AES\", \"apply\", \"-f\", \"https:\/\/www.getambassador.io\/yaml\/aes.yaml\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := i.ShowKubectl(\"wait for AES\", \"-n\", \"ambassador\", \"wait\", \"--for\", \"condition=available\", \"--timeout=90s\", \"deploy\", \"-lproduct=aes\"); err != nil {\n\t\treturn err\n\t}\n\n\t_ = metrics.Report(\"deploy\") \/\/ TODO: Send cluster type and Helm version\n\n\tipAddress := \"\"\n\tfor {\n\t\tvar err error\n\t\tipAddress, err = i.CaptureKubectl(\"get IP address\", \"get\", \"-n\", \"ambassador\", \"service\", \"ambassador\", \"-o\", `go-template={{range .status.loadBalancer.ingress}}{{print .ip \"\\n\"}}{{end}}`)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tipAddress = strings.TrimSpace(ipAddress)\n\t\tif ipAddress != \"\" {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(250 * time.Millisecond) \/\/ FIXME: Time out at some point...\n\t}\n\n\tfmt.Println(\"Your IP address is\", ipAddress)\n\n\t\/\/ Send a request to acquire a DNS name for this cluster's IP address\n\tregURL := \"https:\/\/metriton.datawire.io\/beta\/register-domain\"\n\temailAddress := \"ark3+eci@datawire.io\"\n\tbuf := new(bytes.Buffer)\n\t_ = json.NewEncoder(buf).Encode(registration{emailAddress, ipAddress})\n\tresp, err := http.Post(regURL, \"application\/json\", buf)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"acquire DNS name (post)\")\n\t}\n\tcontent, err := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"acquire DNS name (read body)\")\n\t}\n\n\tif resp.StatusCode == 200 {\n\t\thostname := string(content)\n\t\tfmt.Println(\"-> Acquiring DNS name\", hostname)\n\n\t\t\/\/ Wait for DNS to propagate. This tries to avoid waiting for a ten\n\t\t\/\/ minute error backoff if the ACME registration races ahead of the DNS\n\t\t\/\/ name appearing for LetsEncrypt.\n\t\tfor {\n\t\t\tconn, err := net.Dial(\"tcp\", hostname+\":443\")\n\t\t\tif err == nil {\n\t\t\t\tconn.Close()\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t\/\/ fmt.Printf(\"Waiting for DNS: %#v\\n\", err)\n\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t}\n\t\tfmt.Println(\"-> Automatically configuring TLS\")\n\t\tfmt.Println(\"Please enter an email address. We'll use this email address to notify you prior to domain and certification expiration [None]:\", emailAddress)\n\t\tfmt.Println(\"FIXME: let the user enter an address\")\n\t\t\/\/ Create a Host resource\n\t\thostResource := fmt.Sprintf(hostManifest, hostname, namespace, hostname, emailAddress)\n\t\tkargs, err := i.kubeinfo.GetKubectlArray(\"apply\", \"-f\", \"-\")\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"cluster access for install AES\")\n\t\t}\n\t\tfmt.Println(\"\\n$ kubectl apply -f - < [Host Resource]\")\n\t\tcmd := exec.Command(\"kubectl\", kargs...)\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\tcmd.Stdin = strings.NewReader(hostResource)\n\t\tif err := cmd.Run(); err != nil {\n\t\t\treturn errors.Wrap(err, \"install AES\")\n\t\t}\n\n\t\tfmt.Println(\"\\n-> Obtaining a TLS certificate from Let's Encrypt\")\n\n\t\tfor {\n\t\t\tstate, err := i.CaptureKubectl(\"get Host state\", \"get\", \"host\", hostname, \"-o\", \"go-template={{.status.state}}\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif state == \"Ready\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(500 * time.Millisecond) \/\/ FIXME: Time out at some point...\n\t\t\t\/\/ FIXME: Do something smart for state == \"Error\"\n\t\t}\n\n\t\t_ = metrics.Report(\"cert_provisioned\")\n\t\tfmt.Println(\"-> TLS configured successfully\")\n\t\tif err := i.ShowKubectl(\"show Host\", \"get\", \"host\", hostname); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Open a browser window to the Edge Policy Console\n\t\tif err := do_login(kubeinfo, context, \"ambassador\", hostname, false, false); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t} else {\n\t\tfmt.Println(\"-> Failed to create a DNS name\", content)\n\t\t\/\/   if reachable from host (e.g., k3s, special case for Minikube?)\n\t\t\/\/     open a browser window to http...\n\t\t\/\/   else\n\t\t\/\/     suggest port-forward to reach policy console?\n\t}\n\n\t_ = metrics.Report(\"aes_health_good\") \/\/ or aes_health_bad TODO: Send cluster's install_id and AES version\n\n\treturn nil\n}\n\ntype Installer struct {\n\tkubeinfo *k8s.KubeInfo\n}\n\n\/\/ Kubernetes Cluster\n\nfunc (i *Installer) ShowKubectl(name string, args ...string) error {\n\tkargs, err := i.kubeinfo.GetKubectlArray(args...)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"cluster access for %s\", name)\n\t}\n\tfmt.Printf(\"\\n$ kubectl %s\\n\", strings.Join(kargs, \" \"))\n\tcmd := exec.Command(\"kubectl\", kargs...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn errors.Wrap(err, name)\n\t}\n\treturn nil\n}\n\nfunc (i *Installer) CaptureKubectl(name string, args ...string) (res string, err error) {\n\tres = \"\"\n\tkargs, err := i.kubeinfo.GetKubectlArray(args...)\n\tif err != nil {\n\t\terr = errors.Wrapf(err, \"cluster access for %s\", name)\n\t\treturn\n\t}\n\tfmt.Printf(\"\\n$ kubectl %s\\n\", strings.Join(kargs, \" \"))\n\tcmd := exec.Command(\"kubectl\", kargs...)\n\tcmd.Stderr = nil\n\tresAsBytes, err := cmd.Output()\n\tif err != nil {\n\t\tif ee, ok := err.(*exec.ExitError); ok {\n\t\t\tfmt.Println(ee.Stderr)\n\t\t}\n\t\terr = errors.Wrap(err, name)\n\t}\n\tres = string(resAsBytes)\n\treturn\n}\n\n\/\/ DNS Registration\n\ntype registration struct {\n\tEmail string\n\tIp    string\n}\n\n\/\/ Metrics\n\ntype Metrics struct {\n\tInstallID string\n}\n\nfunc NewMetrics() *Metrics {\n\t\/\/ TODO: Read or create an installation ID\n\treturn nil\n}\n\nfunc (m *Metrics) Report(eventName string) error {\n\tfmt.Println(\"-> [Metrics]\", eventName)\n\treturn nil\n}\n\nconst hostManifest = `\napiVersion: getambassador.io\/v2\nkind: Host\nmetadata:\n  name: %s\n  namespace: %s\nspec:\n  hostname: %s\n  acmeProvider:\n    email: %s\n`\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t_ \"go\/importer\"\n\t\"go\/scanner\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"golang.org\/x\/tools\/imports\"\n\n\t\"sourcegraph.com\/sqs\/goreturns\/returns\"\n\t\"github.com\/klauspost\/asmfmt\"\n)\n\nvar (\n\t\/\/ main operation modes\n\tlist   = flag.Bool(\"l\", false, \"list files whose formatting differs from goreturns's\")\n\twrite  = flag.Bool(\"w\", false, \"write result to (source) file instead of stdout\")\n\tdoDiff = flag.Bool(\"d\", false, \"display diffs instead of rewriting files\")\n\n\tgoimports = flag.Bool(\"i\", true, \"run goimports on the file prior to processing\")\n\n\toptions  = &returns.Options{}\n\texitCode = 0\n)\n\nfunc init() {\n\tflag.BoolVar(&options.PrintErrors, \"p\", false, \"print non-fatal typechecking errors to stderr\")\n\tflag.BoolVar(&options.AllErrors, \"e\", false, \"report all errors (not just the first 10 on different lines)\")\n}\n\nfunc report(err error) {\n\tscanner.PrintError(os.Stderr, err)\n\texitCode = 2\n}\n\nfunc usage() {\n\tfmt.Fprintf(os.Stderr, \"usage: goreturns [flags] [path ...]\\n\")\n\tflag.PrintDefaults()\n\tfmt.Fprintf(os.Stderr, \"(this version includes asmfmt)\\n\")\n\tos.Exit(2)\n}\n\nfunc isGoFile(f os.FileInfo) bool {\n\t\/\/ ignore non-Go files\n\tname := f.Name()\n\treturn !f.IsDir() && !strings.HasPrefix(name, \".\") && strings.HasSuffix(name, \".go\")\n}\n\nfunc isAsmFile(f os.FileInfo) bool {\n\t\/\/ ignore non-Asm files\n\tname := f.Name()\n\treturn !f.IsDir() && !strings.HasPrefix(name, \".\") && strings.HasSuffix(name, \".s\")\n}\n\nfunc processGoFile(pkgDir, filename string, in io.Reader, out io.Writer, stdin bool) error {\n\topt := options\n\tif stdin {\n\t\tnopt := *options\n\t\tnopt.Fragment = true\n\t\topt = &nopt\n\t}\n\n\tif in == nil {\n\t\tf, err := os.Open(filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tin = f\n\t}\n\n\tsrc, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar res = src \/\/ This holds the result of processing so far.\n\n\tif *goimports {\n\t\tvar err error\n\t\tres, err = imports.Process(filename, res, &imports.Options{\n\t\t\tFragment:  opt.Fragment,\n\t\t\tAllErrors: opt.AllErrors,\n\t\t\tComments:  true,\n\t\t\tTabIndent: true,\n\t\t\tTabWidth:  8,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tres, err = returns.Process(pkgDir, filename, res, opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !bytes.Equal(src, res) {\n\t\t\/\/ formatting has changed\n\t\tif *list {\n\t\t\tfmt.Fprintln(out, filename)\n\t\t}\n\t\tif *write {\n\t\t\terr = ioutil.WriteFile(filename, res, 0)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif *doDiff {\n\t\t\tdata, err := diff(src, res)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"computing diff: %s\", err)\n\t\t\t}\n\t\t\tfmt.Printf(\"diff %s gofmt\/%s\\n\", filename, filename)\n\t\t\tout.Write(data)\n\t\t}\n\t}\n\n\tif !*list && !*write && !*doDiff {\n\t\t_, err = out.Write(res)\n\t}\n\n\treturn err\n}\n\n\/\/ If in == nil, the source is the contents of the file with the given filename.\nfunc processAsmFile(filename string, in io.Reader, out io.Writer, stdin bool) error {\n\tif in == nil {\n\t\tf, err := os.Open(filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tin = f\n\t}\n\n\tsrc, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := asmfmt.Format(bytes.NewBuffer(src))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !bytes.Equal(src, res) {\n\t\t\/\/ formatting has changed\n\t\tif *list {\n\t\t\tfmt.Fprintln(out, filename)\n\t\t}\n\t\tif *write {\n\t\t\terr = ioutil.WriteFile(filename, res, 0644)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif *doDiff {\n\t\t\tdata, err := diff(src, res)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"computing diff: %s\", err)\n\t\t\t}\n\t\t\tfmt.Printf(\"diff %s asmfmt\/%s\\n\", filename, filename)\n\t\t\tout.Write(data)\n\t\t}\n\t}\n\n\tif !*list && !*write && !*doDiff {\n\t\t_, err = out.Write(res)\n\t}\n\n\treturn err\n}\n\nfunc visitFile(path string, f os.FileInfo, err error) error {\n\tif err == nil && isGoFile(f) {\n\t\terr = processGoFile(filepath.Dir(path), path, nil, os.Stdout, false)\n\t} else if err == nil && isAsmFile(f) {\n\t\terr = processAsmFile(path, nil, os.Stdout, false)\n\t}\n\tif err != nil {\n\t\treport(err)\n\t}\n\treturn nil\n}\n\nfunc walkDir(path string) {\n\tfilepath.Walk(path, visitFile)\n}\n\nfunc main() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\t\/\/ call gofmtMain in a separate function\n\t\/\/ so that it can use defer and have them\n\t\/\/ run before the exit.\n\tgofmtMain()\n\tos.Exit(exitCode)\n}\n\nfunc gofmtMain() {\n\tflag.Usage = usage\n\tflag.Parse()\n\n\tif flag.NArg() == 0 {\n\t\tif err := processGoFile(\"\", \"<standard input>\", os.Stdin, os.Stdout, true); err != nil {\n\t\t\treport(err)\n\t\t}\n\t\treturn\n\t}\n\n\tfor i := 0; i < flag.NArg(); i++ {\n\t\tpath := flag.Arg(i)\n\t\tswitch dir, err := os.Stat(path); {\n\t\tcase err != nil:\n\t\t\treport(err)\n\t\tcase dir.IsDir():\n\t\t\twalkDir(path)\n\t\tdefault:\n\t\t\tif err := visitFile(path, dir, nil); err != nil {\n\t\t\t\treport(err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc diff(b1, b2 []byte) (data []byte, err error) {\n\tf1, err := ioutil.TempFile(\"\", \"gofmt\")\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer os.Remove(f1.Name())\n\tdefer f1.Close()\n\n\tf2, err := ioutil.TempFile(\"\", \"gofmt\")\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer os.Remove(f2.Name())\n\tdefer f2.Close()\n\n\tf1.Write(b1)\n\tf2.Write(b2)\n\n\tdata, err = exec.Command(\"diff\", \"-u\", f1.Name(), f2.Name()).CombinedOutput()\n\tif len(data) > 0 {\n\t\t\/\/ diff exits with a non-zero status when the files don't match.\n\t\t\/\/ Ignore that failure as long as we get output.\n\t\terr = nil\n\t}\n\treturn\n}\n<commit_msg>Fix imports.<commit_after>\/\/ Copyright 2013 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t_ \"go\/importer\"\n\t\"go\/scanner\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com\/klauspost\/asmfmt\"\n\t\"golang.org\/x\/tools\/imports\"\n\t\"sourcegraph.com\/sqs\/goreturns\/returns\"\n)\n\nvar (\n\t\/\/ main operation modes\n\tlist   = flag.Bool(\"l\", false, \"list files whose formatting differs from goreturns's\")\n\twrite  = flag.Bool(\"w\", false, \"write result to (source) file instead of stdout\")\n\tdoDiff = flag.Bool(\"d\", false, \"display diffs instead of rewriting files\")\n\n\tgoimports = flag.Bool(\"i\", true, \"run goimports on the file prior to processing\")\n\n\toptions  = &returns.Options{}\n\texitCode = 0\n)\n\nfunc init() {\n\tflag.BoolVar(&options.PrintErrors, \"p\", false, \"print non-fatal typechecking errors to stderr\")\n\tflag.BoolVar(&options.AllErrors, \"e\", false, \"report all errors (not just the first 10 on different lines)\")\n}\n\nfunc report(err error) {\n\tscanner.PrintError(os.Stderr, err)\n\texitCode = 2\n}\n\nfunc usage() {\n\tfmt.Fprintf(os.Stderr, \"usage: goreturns [flags] [path ...]\\n\")\n\tflag.PrintDefaults()\n\tfmt.Fprintf(os.Stderr, \"(this version includes asmfmt)\\n\")\n\tos.Exit(2)\n}\n\nfunc isGoFile(f os.FileInfo) bool {\n\t\/\/ ignore non-Go files\n\tname := f.Name()\n\treturn !f.IsDir() && !strings.HasPrefix(name, \".\") && strings.HasSuffix(name, \".go\")\n}\n\nfunc isAsmFile(f os.FileInfo) bool {\n\t\/\/ ignore non-Asm files\n\tname := f.Name()\n\treturn !f.IsDir() && !strings.HasPrefix(name, \".\") && strings.HasSuffix(name, \".s\")\n}\n\nfunc processGoFile(pkgDir, filename string, in io.Reader, out io.Writer, stdin bool) error {\n\topt := options\n\tif stdin {\n\t\tnopt := *options\n\t\tnopt.Fragment = true\n\t\topt = &nopt\n\t}\n\n\tif in == nil {\n\t\tf, err := os.Open(filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tin = f\n\t}\n\n\tsrc, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar res = src \/\/ This holds the result of processing so far.\n\n\tif *goimports {\n\t\tvar err error\n\t\tres, err = imports.Process(filename, res, &imports.Options{\n\t\t\tFragment:  opt.Fragment,\n\t\t\tAllErrors: opt.AllErrors,\n\t\t\tComments:  true,\n\t\t\tTabIndent: true,\n\t\t\tTabWidth:  8,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tres, err = returns.Process(pkgDir, filename, res, opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !bytes.Equal(src, res) {\n\t\t\/\/ formatting has changed\n\t\tif *list {\n\t\t\tfmt.Fprintln(out, filename)\n\t\t}\n\t\tif *write {\n\t\t\terr = ioutil.WriteFile(filename, res, 0)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif *doDiff {\n\t\t\tdata, err := diff(src, res)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"computing diff: %s\", err)\n\t\t\t}\n\t\t\tfmt.Printf(\"diff %s gofmt\/%s\\n\", filename, filename)\n\t\t\tout.Write(data)\n\t\t}\n\t}\n\n\tif !*list && !*write && !*doDiff {\n\t\t_, err = out.Write(res)\n\t}\n\n\treturn err\n}\n\n\/\/ If in == nil, the source is the contents of the file with the given filename.\nfunc processAsmFile(filename string, in io.Reader, out io.Writer, stdin bool) error {\n\tif in == nil {\n\t\tf, err := os.Open(filename)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\tin = f\n\t}\n\n\tsrc, err := ioutil.ReadAll(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := asmfmt.Format(bytes.NewBuffer(src))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !bytes.Equal(src, res) {\n\t\t\/\/ formatting has changed\n\t\tif *list {\n\t\t\tfmt.Fprintln(out, filename)\n\t\t}\n\t\tif *write {\n\t\t\terr = ioutil.WriteFile(filename, res, 0644)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif *doDiff {\n\t\t\tdata, err := diff(src, res)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"computing diff: %s\", err)\n\t\t\t}\n\t\t\tfmt.Printf(\"diff %s asmfmt\/%s\\n\", filename, filename)\n\t\t\tout.Write(data)\n\t\t}\n\t}\n\n\tif !*list && !*write && !*doDiff {\n\t\t_, err = out.Write(res)\n\t}\n\n\treturn err\n}\n\nfunc visitFile(path string, f os.FileInfo, err error) error {\n\tif err == nil && isGoFile(f) {\n\t\terr = processGoFile(filepath.Dir(path), path, nil, os.Stdout, false)\n\t} else if err == nil && isAsmFile(f) {\n\t\terr = processAsmFile(path, nil, os.Stdout, false)\n\t}\n\tif err != nil {\n\t\treport(err)\n\t}\n\treturn nil\n}\n\nfunc walkDir(path string) {\n\tfilepath.Walk(path, visitFile)\n}\n\nfunc main() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\t\/\/ call gofmtMain in a separate function\n\t\/\/ so that it can use defer and have them\n\t\/\/ run before the exit.\n\tgofmtMain()\n\tos.Exit(exitCode)\n}\n\nfunc gofmtMain() {\n\tflag.Usage = usage\n\tflag.Parse()\n\n\tif flag.NArg() == 0 {\n\t\tif err := processGoFile(\"\", \"<standard input>\", os.Stdin, os.Stdout, true); err != nil {\n\t\t\treport(err)\n\t\t}\n\t\treturn\n\t}\n\n\tfor i := 0; i < flag.NArg(); i++ {\n\t\tpath := flag.Arg(i)\n\t\tswitch dir, err := os.Stat(path); {\n\t\tcase err != nil:\n\t\t\treport(err)\n\t\tcase dir.IsDir():\n\t\t\twalkDir(path)\n\t\tdefault:\n\t\t\tif err := visitFile(path, dir, nil); err != nil {\n\t\t\t\treport(err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc diff(b1, b2 []byte) (data []byte, err error) {\n\tf1, err := ioutil.TempFile(\"\", \"gofmt\")\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer os.Remove(f1.Name())\n\tdefer f1.Close()\n\n\tf2, err := ioutil.TempFile(\"\", \"gofmt\")\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer os.Remove(f2.Name())\n\tdefer f2.Close()\n\n\tf1.Write(b1)\n\tf2.Write(b2)\n\n\tdata, err = exec.Command(\"diff\", \"-u\", f1.Name(), f2.Name()).CombinedOutput()\n\tif len(data) > 0 {\n\t\t\/\/ diff exits with a non-zero status when the files don't match.\n\t\t\/\/ Ignore that failure as long as we get output.\n\t\terr = nil\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package community\n\nconst (\n\t\/\/ GetRepoEndpoint is a string representation of the current endpoint for getting repo\n\tGetRepoEndpoint = `v1\/repo\/getRepo`\n\t\/\/ SearchRepoEndpoint is a string representation of the current endpoint for searching repo\n\tSearchRepoEndpoint = `v1\/repo\/search`\n)\n\n\/\/ Repo is a representation of a github repo and corresponding metrics about\n\/\/ that repo pulled from github\ntype Repo struct {\n\tName       string   `json:\"name\" xml:\"name\"`\n\tURL        string   `json:\"url\" xml:\"url\"`\n\tCommitters int      `json:\"committers\" xml:\"committers\"`\n\tConfidence float64  `json:\"confidence\" xml:\"confidence\"`\n\tOldNames   []string `json:\"old_names\" xml:\"old_names\"`\n\tStars      int      `json:\"stars\" xml:\"stars\"`\n}\n<commit_msg>Adding fields for repo dates<commit_after>package community\n\nimport \"time\"\n\nconst (\n\t\/\/ GetRepoEndpoint is a string representation of the current endpoint for getting repo\n\tGetRepoEndpoint = `v1\/repo\/getRepo`\n\t\/\/ SearchRepoEndpoint is a string representation of the current endpoint for searching repo\n\tSearchRepoEndpoint = `v1\/repo\/search`\n)\n\n\/\/ Repo is a representation of a github repo and corresponding metrics about\n\/\/ that repo pulled from github\ntype Repo struct {\n\tName        string    `json:\"name\" xml:\"name\"`\n\tURL         string    `json:\"url\" xml:\"url\"`\n\tCommitters  int       `json:\"committers\" xml:\"committers\"`\n\tConfidence  float64   `json:\"confidence\" xml:\"confidence\"`\n\tOldNames    []string  `json:\"old_names\" xml:\"old_names\"`\n\tStars       int       `json:\"stars\" xml:\"stars\"`\n\tCommittedAt time.Time `json:\"committed_at\" xml:\"committed_at\"`\n\tUpdatedAt   time.Time `json:\"updated_at\" xml:\"updated_at\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage backups\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/juju\/cmd\"\n\t\"github.com\/juju\/errors\"\n\n\t\"github.com\/juju\/juju\/cmd\/modelcmd\"\n)\n\nconst removeDoc = `\nremove-backup removes a backup from remote storage.\n`\n\n\/\/ NewRemoveCommand returns a command used to remove a\n\/\/ backup from remote storage.\nfunc NewRemoveCommand() cmd.Command {\n\treturn modelcmd.Wrap(&removeCommand{})\n}\n\ntype removeCommand struct {\n\tCommandBase\n\t\/\/ ID refers to the backup to be removed.\n\tID string\n}\n\n\/\/ Info implements Command.Info.\nfunc (c *removeCommand) Info() *cmd.Info {\n\treturn &cmd.Info{\n\t\tName:    \"remove-backup\",\n\t\tArgs:    \"<ID>\",\n\t\tPurpose: \"Remove the spcified backup from remote storage.\",\n\t\tDoc:     removeDoc,\n\t}\n}\n\n\/\/ Init implements Command.Init.\nfunc (c *removeCommand) Init(args []string) error {\n\tif len(args) == 0 {\n\t\treturn errors.New(\"missing ID\")\n\t}\n\tid, args := args[0], args[1:]\n\tif err := cmd.CheckEmpty(args); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tc.ID = id\n\treturn nil\n}\n\n\/\/ Run implements Command.Run.\nfunc (c *removeCommand) Run(ctx *cmd.Context) error {\n\tif c.Log != nil {\n\t\tif err := c.Log.Start(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tclient, err := c.NewAPIClient()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tdefer client.Close()\n\n\terr = client.Remove(c.ID)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\toutput := fmt.Sprintf(\"successfully removed: %v\\n\", c.ID)\n\tctx.Stdout.Write([]byte(output))\n\treturn nil\n}\n<commit_msg>Fix typo in help.<commit_after>\/\/ Copyright 2014 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage backups\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/juju\/cmd\"\n\t\"github.com\/juju\/errors\"\n\n\t\"github.com\/juju\/juju\/cmd\/modelcmd\"\n)\n\nconst removeDoc = `\nremove-backup removes a backup from remote storage.\n`\n\n\/\/ NewRemoveCommand returns a command used to remove a\n\/\/ backup from remote storage.\nfunc NewRemoveCommand() cmd.Command {\n\treturn modelcmd.Wrap(&removeCommand{})\n}\n\ntype removeCommand struct {\n\tCommandBase\n\t\/\/ ID refers to the backup to be removed.\n\tID string\n}\n\n\/\/ Info implements Command.Info.\nfunc (c *removeCommand) Info() *cmd.Info {\n\treturn &cmd.Info{\n\t\tName:    \"remove-backup\",\n\t\tArgs:    \"<ID>\",\n\t\tPurpose: \"Remove the specified backup from remote storage.\",\n\t\tDoc:     removeDoc,\n\t}\n}\n\n\/\/ Init implements Command.Init.\nfunc (c *removeCommand) Init(args []string) error {\n\tif len(args) == 0 {\n\t\treturn errors.New(\"missing ID\")\n\t}\n\tid, args := args[0], args[1:]\n\tif err := cmd.CheckEmpty(args); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tc.ID = id\n\treturn nil\n}\n\n\/\/ Run implements Command.Run.\nfunc (c *removeCommand) Run(ctx *cmd.Context) error {\n\tif c.Log != nil {\n\t\tif err := c.Log.Start(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tclient, err := c.NewAPIClient()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tdefer client.Close()\n\n\terr = client.Remove(c.ID)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\toutput := fmt.Sprintf(\"successfully removed: %v\\n\", c.ID)\n\tctx.Stdout.Write([]byte(output))\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package community\n\nimport (\n\t\"time\"\n)\n\nconst (\n\t\/\/ GetRepoEndpoint is a string representation of the current endpoint for getting repo\n\tGetRepoEndpoint = `v1\/repo\/getRepo`\n\t\/\/ GetReposInCommonEndpoint is a string representation of the current endpoint for getting repos\n\tGetReposInCommonEndpoint = `\/v1\/repo\/getReposInCommon`\n\t\/\/ GetReposForActorEndpoint is a string representation of the current endpoint for getting repos\n\tGetReposForActorEndpoint = `v1\/repo\/getReposForActor`\n\t\/\/ SearchRepoEndpoint is a string representation of the current endpoint for searching repo\n\tSearchRepoEndpoint = `v1\/repo\/search`\n)\n\n\/\/ Repo is a representation of a github repo and corresponding metrics about\n\/\/ that repo pulled from github\ntype Repo struct {\n\tID            string     `json:\"id\" xml:\"id\"`\n\tName          string     `json:\"name\" xml:\"name\"`\n\tURL           string     `json:\"url\" xml:\"url\"`\n\tCommitters    int        `json:\"committers\" xml:\"committers\"`\n\tTotalActors   int        `json:\"total_actors,omitempty\" xml:\"total_actors,omitempty\"`\n\tConfidence    float64    `json:\"confidence\" xml:\"confidence\"`\n\tOldNames      []string   `json:\"old_names\" xml:\"old_names\"`\n\tDefaultBranch string     `json:\"default_branch,omitempty\" xml:\"default_branch,omitempty\"`\n\tMasterBranch  string     `json:\"master_branch,omitempty\" xml:\"master_branch,omitempty\"`\n\tStars         int        `json:\"stars\" xml:\"stars\"`\n\tCommittedAt   time.Time  `json:\"committed_at\" xml:\"committed_at\"`\n\tUpdatedAt     time.Time  `json:\"updated_at\" xml:\"updated_at\"`\n\tCreatedAt     *time.Time `json:\"created_at\" xml:\"created_at\"`\n}\n\n\/\/ Metrics is a set of data points that represents the measure of a softwares\n\/\/ community health\ntype Metrics struct {\n\tID                              string          `json:\"id\" xml:\"id\"`\n\tName                            string          `json:\"name\" xml:\"name\"`\n\tCommitters                      int             `json:\"committers\" xml:\"committers\"`\n\tTotalActors                     int             `json:\"total_actors,omitempty\" xml:\"total_actors,omitempty\"`\n\tCommittersMonthlyCount          *[]MonthlyCount `json:\"committers_monthly_count\" xml:\"committers_monthly_count\"`\n\tReleasesTotalCount              *int            `json:\"releases_total_count\" xml:\"releases_total_count\"`\n\tReleasesMonthlyCount            *[]MonthlyCount `json:\"releases_monthly_count\" xml:\"releases_monthly_count\"`\n\tReleasesLastAt                  *time.Time      `json:\"releases_last_at\" xml:\"releases_last_at\"`\n\tPullRequestsTotalCount          *int            `json:\"pull_requests_total_count\" xml:\"pull_requests_total_count\"`\n\tPullRequestsLastAt              *time.Time      `json:\"pull_requests_last_at\" xml:\"pull_requests_last_at\"`\n\tPullRequestsMonthlyCount        *[]MonthlyCount `json:\"pull_requests_monthly_count\" xml:\"pull_requests_monthly_count\"`\n\tIssuesLastAt                    *time.Time      `json:\"issues_last_at\" xml:\"issues_last_at\"`\n\tIssuesOpenMonthlyCount          *[]MonthlyCount `json:\"issues_open_monthly_count\" xml:\"issues_open_monthly_count\"`\n\tIssuesClosedMonthlyCount        *[]MonthlyCount `json:\"issues_closed_monthly_count\" xml:\"issues_closed_monthly_count\"`\n\tIssuesClosedMttrMonthly         *[]MonthlyMttr  `json:\"issues_closed_mttr_monthly\" xml:\"issues_closed_mttr_monthly\"`\n\tIssuesClosedMttr                *int            `json:\"issues_closed_mttr\" xml:\"issues_closed_mttr\"`\n\tCommitsTotalCount               *int            `json:\"commits_total_count\" xml:\"commits_total_count\"`\n\tCommitsMonthlyCount             *[]MonthlyCount `json:\"commits_monthly_count\" xml:\"commits_monthly_count\"`\n\tActorsMonthlyCount              *[]MonthlyCount `json:\"actors_monthly_count\" xml:\"actors_monthly_count\"`\n\tActionsTotalCount               *int            `json:\"actions_total_count\" xml:\"actions_total_count\"`\n\tActionsLastAt                   *time.Time      `json:\"actions_last_at\" xml:\"actions_last_at\"`\n\tActionsFirstAt                  *time.Time      `json:\"actions_first_at\" xml:\"actions_first_at\"`\n\tActionsMonthlyCount             *[]MonthlyCount `json:\"actions_monthly_count\" xml:\"actions_monthly_count\"`\n\tContributingActorsTotalCount    *int            `json:\"contributing_actors_total_count\" xml:\"contributing_actors_total_count\"`\n\tContributingActorsMonthlyCount  *[]MonthlyCount `json:\"contributing_actors_monthly_count\" xml:\"contributing_actors_monthly_count\"`\n\tContributingActionsTotalCount   *int            `json:\"contributing_actions_total_count\" xml:\"contributing_actions_total_count\"`\n\tContributingActionsLastAt       *time.Time      `json:\"contributing_actions_last_at\" xml:\"contributing_actions_last_at\"`\n\tContributingActionsMonthlyCount *[]MonthlyCount `json:\"contributing_actions_monthly_count\" xml:\"contributing_actions_monthly_count\"`\n\tNewActorsMonthlyCount           *[]MonthlyCount `json:\"new_actors_monthly_count\" xml:\"new_actors_monthly_count\"`\n\tMedianWorkingHour               *int            `json:\"median_working_hour\" xml:\"median_working_hour\"`\n\tEOLRearFailingDaysCount         *int            `json:\"eol_rear_failing_months_count\" xml:\"eol_rear_failing_months_count\"`\n}\n\n\/\/ MonthlyCount defines the data needed for month and count\ntype MonthlyCount struct {\n\tMonth string `json:\"month\" xml:\"month\"`\n\tCount int    `json:\"count\" xml:\"count\"`\n}\n\n\/\/ MonthlyMttr defines the data needed for month and mttr\ntype MonthlyMttr struct {\n\tMonth string  `json:\"month\" xml:\"month\"`\n\tMttr  float32 `json:\"mttr\" xml:\"mttr\"`\n}\n<commit_msg>Fix type for mtty<commit_after>package community\n\nimport (\n\t\"time\"\n)\n\nconst (\n\t\/\/ GetRepoEndpoint is a string representation of the current endpoint for getting repo\n\tGetRepoEndpoint = `v1\/repo\/getRepo`\n\t\/\/ GetReposInCommonEndpoint is a string representation of the current endpoint for getting repos\n\tGetReposInCommonEndpoint = `\/v1\/repo\/getReposInCommon`\n\t\/\/ GetReposForActorEndpoint is a string representation of the current endpoint for getting repos\n\tGetReposForActorEndpoint = `v1\/repo\/getReposForActor`\n\t\/\/ SearchRepoEndpoint is a string representation of the current endpoint for searching repo\n\tSearchRepoEndpoint = `v1\/repo\/search`\n)\n\n\/\/ Repo is a representation of a github repo and corresponding metrics about\n\/\/ that repo pulled from github\ntype Repo struct {\n\tID            string     `json:\"id\" xml:\"id\"`\n\tName          string     `json:\"name\" xml:\"name\"`\n\tURL           string     `json:\"url\" xml:\"url\"`\n\tCommitters    int        `json:\"committers\" xml:\"committers\"`\n\tTotalActors   int        `json:\"total_actors,omitempty\" xml:\"total_actors,omitempty\"`\n\tConfidence    float64    `json:\"confidence\" xml:\"confidence\"`\n\tOldNames      []string   `json:\"old_names\" xml:\"old_names\"`\n\tDefaultBranch string     `json:\"default_branch,omitempty\" xml:\"default_branch,omitempty\"`\n\tMasterBranch  string     `json:\"master_branch,omitempty\" xml:\"master_branch,omitempty\"`\n\tStars         int        `json:\"stars\" xml:\"stars\"`\n\tCommittedAt   time.Time  `json:\"committed_at\" xml:\"committed_at\"`\n\tUpdatedAt     time.Time  `json:\"updated_at\" xml:\"updated_at\"`\n\tCreatedAt     *time.Time `json:\"created_at\" xml:\"created_at\"`\n}\n\n\/\/ Metrics is a set of data points that represents the measure of a softwares\n\/\/ community health\ntype Metrics struct {\n\tID                              string          `json:\"id\" xml:\"id\"`\n\tName                            string          `json:\"name\" xml:\"name\"`\n\tCommitters                      int             `json:\"committers\" xml:\"committers\"`\n\tTotalActors                     int             `json:\"total_actors,omitempty\" xml:\"total_actors,omitempty\"`\n\tCommittersMonthlyCount          *[]MonthlyCount `json:\"committers_monthly_count\" xml:\"committers_monthly_count\"`\n\tReleasesTotalCount              *int            `json:\"releases_total_count\" xml:\"releases_total_count\"`\n\tReleasesMonthlyCount            *[]MonthlyCount `json:\"releases_monthly_count\" xml:\"releases_monthly_count\"`\n\tReleasesLastAt                  *time.Time      `json:\"releases_last_at\" xml:\"releases_last_at\"`\n\tPullRequestsTotalCount          *int            `json:\"pull_requests_total_count\" xml:\"pull_requests_total_count\"`\n\tPullRequestsLastAt              *time.Time      `json:\"pull_requests_last_at\" xml:\"pull_requests_last_at\"`\n\tPullRequestsMonthlyCount        *[]MonthlyCount `json:\"pull_requests_monthly_count\" xml:\"pull_requests_monthly_count\"`\n\tIssuesLastAt                    *time.Time      `json:\"issues_last_at\" xml:\"issues_last_at\"`\n\tIssuesOpenMonthlyCount          *[]MonthlyCount `json:\"issues_open_monthly_count\" xml:\"issues_open_monthly_count\"`\n\tIssuesClosedMonthlyCount        *[]MonthlyCount `json:\"issues_closed_monthly_count\" xml:\"issues_closed_monthly_count\"`\n\tIssuesClosedMttrMonthly         *[]MonthlyMttr  `json:\"issues_closed_mttr_monthly\" xml:\"issues_closed_mttr_monthly\"`\n\tIssuesClosedMttr                *float64        `json:\"issues_closed_mttr\" xml:\"issues_closed_mttr\"`\n\tCommitsTotalCount               *int            `json:\"commits_total_count\" xml:\"commits_total_count\"`\n\tCommitsMonthlyCount             *[]MonthlyCount `json:\"commits_monthly_count\" xml:\"commits_monthly_count\"`\n\tActorsMonthlyCount              *[]MonthlyCount `json:\"actors_monthly_count\" xml:\"actors_monthly_count\"`\n\tActionsTotalCount               *int            `json:\"actions_total_count\" xml:\"actions_total_count\"`\n\tActionsLastAt                   *time.Time      `json:\"actions_last_at\" xml:\"actions_last_at\"`\n\tActionsFirstAt                  *time.Time      `json:\"actions_first_at\" xml:\"actions_first_at\"`\n\tActionsMonthlyCount             *[]MonthlyCount `json:\"actions_monthly_count\" xml:\"actions_monthly_count\"`\n\tContributingActorsTotalCount    *int            `json:\"contributing_actors_total_count\" xml:\"contributing_actors_total_count\"`\n\tContributingActorsMonthlyCount  *[]MonthlyCount `json:\"contributing_actors_monthly_count\" xml:\"contributing_actors_monthly_count\"`\n\tContributingActionsTotalCount   *int            `json:\"contributing_actions_total_count\" xml:\"contributing_actions_total_count\"`\n\tContributingActionsLastAt       *time.Time      `json:\"contributing_actions_last_at\" xml:\"contributing_actions_last_at\"`\n\tContributingActionsMonthlyCount *[]MonthlyCount `json:\"contributing_actions_monthly_count\" xml:\"contributing_actions_monthly_count\"`\n\tNewActorsMonthlyCount           *[]MonthlyCount `json:\"new_actors_monthly_count\" xml:\"new_actors_monthly_count\"`\n\tMedianWorkingHour               *int            `json:\"median_working_hour\" xml:\"median_working_hour\"`\n\tEOLRearFailingDaysCount         *int            `json:\"eol_rear_failing_months_count\" xml:\"eol_rear_failing_months_count\"`\n}\n\n\/\/ MonthlyCount defines the data needed for month and count\ntype MonthlyCount struct {\n\tMonth string `json:\"month\" xml:\"month\"`\n\tCount int    `json:\"count\" xml:\"count\"`\n}\n\n\/\/ MonthlyMttr defines the data needed for month and mttr\ntype MonthlyMttr struct {\n\tMonth string  `json:\"month\" xml:\"month\"`\n\tMttr  float32 `json:\"mttr\" xml:\"mttr\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage anago\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/cobra\"\n\n\t\"k8s.io\/release\/pkg\/build\"\n\t\"k8s.io\/release\/pkg\/release\"\n)\n\n\/\/ pushCmd represents the subcommand for `krel anago push`\nvar pushCmd = &cobra.Command{\n\tUse:   \"push\",\n\tShort: \"Push release artifacts into the Google Cloud\",\n\tLong: `krel anago push\n\nThis subcommand can be used to push the release artifacts to the Google Cloud. \nIt's only indented to be used from anago, which means the command might be\nremoved in future releases again when anago goes end of life.\n`,\n\tSilenceUsage:  true,\n\tSilenceErrors: true,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn errors.Wrap(runPush(pushOpts), \"run krel anago push\")\n\t},\n}\n\nvar (\n\tpushOpts     = &build.Options{}\n\trunStage     bool\n\trunRelease   bool\n\tbuildVersion string\n)\n\nfunc init() {\n\tpushCmd.PersistentFlags().BoolVar(\n\t\t&runStage,\n\t\t\"stage\",\n\t\tfalse,\n\t\t\"run in stage mode\",\n\t)\n\n\tpushCmd.PersistentFlags().BoolVar(\n\t\t&runRelease,\n\t\t\"release\",\n\t\tfalse,\n\t\t\"run in release mode\",\n\t)\n\n\tpushCmd.PersistentFlags().StringVar(\n\t\t&pushOpts.Version,\n\t\t\"version\",\n\t\t\"\",\n\t\t\"version to be used\",\n\t)\n\n\tpushCmd.PersistentFlags().StringVar(\n\t\t&pushOpts.BuildDir,\n\t\t\"build-dir\",\n\t\t\"\",\n\t\t\"build artifact directory of the release\",\n\t)\n\n\tpushCmd.PersistentFlags().StringVar(\n\t\t&pushOpts.Bucket,\n\t\t\"bucket\",\n\t\t\"\",\n\t\t\"GCS bucket to be used\",\n\t)\n\n\tpushCmd.PersistentFlags().StringVar(\n\t\t&pushOpts.Registry,\n\t\t\"container-registry\",\n\t\t\"\",\n\t\t\"Container image registry to be used\",\n\t)\n\n\tpushCmd.PersistentFlags().StringVar(\n\t\t&buildVersion,\n\t\t\"build-version\",\n\t\t\"\",\n\t\t\"Build version from Jenkins (only used when --release specified)\",\n\t)\n\n\tpushOpts.AllowDup = true\n\tpushOpts.ValidateRemoteImageDigests = true\n\n\tAnagoCmd.AddCommand(pushCmd)\n}\n\nfunc runPush(opts *build.Options) error {\n\tbuildInstance := build.NewInstance(opts)\n\tif err := buildInstance.CheckReleaseBucket(); err != nil {\n\t\treturn errors.Wrap(err, \"check release bucket access\")\n\t}\n\n\tif runStage {\n\t\treturn runPushStage(buildInstance, opts)\n\t} else if runRelease {\n\t\treturn runPushRelease(buildInstance, opts)\n\t}\n\n\treturn errors.New(\"neither --stage nor --release provided\")\n}\n\nfunc runPushStage(\n\tbuildInstance *build.Instance,\n\topts *build.Options,\n) error {\n\tworkDir := os.Getenv(\"GOPATH\")\n\tif workDir == \"\" {\n\t\treturn errors.New(\"GOPATH is not set\")\n\t}\n\n\t\/\/ Stage the local source tree\n\tif err := buildInstance.StageLocalSourceTree(workDir, buildVersion); err != nil {\n\t\treturn errors.Wrap(err, \"staging local source tree\")\n\t}\n\n\t\/\/ Stage local artifacts and write checksums\n\tif err := buildInstance.StageLocalArtifacts(); err != nil {\n\t\treturn errors.Wrap(err, \"staging local artifacts\")\n\t}\n\tgcsPath := filepath.Join(\"stage\", buildVersion, opts.Version)\n\n\t\/\/ Push gcs-stage to GCS\n\tif err := buildInstance.PushReleaseArtifacts(\n\t\tfilepath.Join(opts.BuildDir, release.GCSStagePath, opts.Version),\n\t\tfilepath.Join(gcsPath, release.GCSStagePath, opts.Version),\n\t); err != nil {\n\t\treturn errors.Wrap(err, \"pushing release artifacts\")\n\t}\n\n\t\/\/ Push container release-images to GCS\n\tif err := buildInstance.PushReleaseArtifacts(\n\t\tfilepath.Join(opts.BuildDir, release.ImagesPath),\n\t\tfilepath.Join(gcsPath, release.ImagesPath),\n\t); err != nil {\n\t\treturn errors.Wrap(err, \"pushing release artifacts\")\n\t}\n\n\t\/\/ Push container images into registry\n\tif err := buildInstance.PushContainerImages(); err != nil {\n\t\treturn errors.Wrap(err, \"pushing container images\")\n\t}\n\n\treturn nil\n}\n\nfunc runPushRelease(\n\tbuildInstance *build.Instance,\n\topts *build.Options,\n) error {\n\tif err := buildInstance.CopyStagedFromGCS(opts.Bucket, buildVersion); err != nil {\n\t\treturn errors.Wrap(err, \"copy staged from GCS\")\n\t}\n\n\t\/\/ In an official nomock release, we want to ensure that container images\n\t\/\/ have been promoted from staging to production, so we do the image\n\t\/\/ manifest validation against production instead of staging.\n\ttargetRegistry := opts.Registry\n\tif targetRegistry == release.GCRIOPathStaging {\n\t\ttargetRegistry = release.GCRIOPathProd\n\t}\n\t\/\/ Image promotion has been done on nomock stage, verify that the images\n\t\/\/ are available.\n\tif err := release.NewImages().Validate(\n\t\ttargetRegistry, opts.Version, opts.BuildDir,\n\t); err != nil {\n\t\treturn errors.Wrap(err, \"validate container images\")\n\t}\n\n\tif err := release.NewPublisher().PublishVersion(\n\t\t\"release\", opts.Version, opts.BuildDir, opts.Bucket, \"\", nil, false, false,\n\t); err != nil {\n\t\treturn errors.Wrap(err, \"publish release\")\n\t}\n\treturn nil\n}\n<commit_msg>Add GCS bucket to release artifacts push<commit_after>\/*\nCopyright 2020 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage anago\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/cobra\"\n\n\t\"k8s.io\/release\/pkg\/build\"\n\t\"k8s.io\/release\/pkg\/release\"\n)\n\n\/\/ pushCmd represents the subcommand for `krel anago push`\nvar pushCmd = &cobra.Command{\n\tUse:   \"push\",\n\tShort: \"Push release artifacts into the Google Cloud\",\n\tLong: `krel anago push\n\nThis subcommand can be used to push the release artifacts to the Google Cloud. \nIt's only indented to be used from anago, which means the command might be\nremoved in future releases again when anago goes end of life.\n`,\n\tSilenceUsage:  true,\n\tSilenceErrors: true,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn errors.Wrap(runPush(pushOpts), \"run krel anago push\")\n\t},\n}\n\nvar (\n\tpushOpts     = &build.Options{}\n\trunStage     bool\n\trunRelease   bool\n\tbuildVersion string\n)\n\nfunc init() {\n\tpushCmd.PersistentFlags().BoolVar(\n\t\t&runStage,\n\t\t\"stage\",\n\t\tfalse,\n\t\t\"run in stage mode\",\n\t)\n\n\tpushCmd.PersistentFlags().BoolVar(\n\t\t&runRelease,\n\t\t\"release\",\n\t\tfalse,\n\t\t\"run in release mode\",\n\t)\n\n\tpushCmd.PersistentFlags().StringVar(\n\t\t&pushOpts.Version,\n\t\t\"version\",\n\t\t\"\",\n\t\t\"version to be used\",\n\t)\n\n\tpushCmd.PersistentFlags().StringVar(\n\t\t&pushOpts.BuildDir,\n\t\t\"build-dir\",\n\t\t\"\",\n\t\t\"build artifact directory of the release\",\n\t)\n\n\tpushCmd.PersistentFlags().StringVar(\n\t\t&pushOpts.Bucket,\n\t\t\"bucket\",\n\t\t\"\",\n\t\t\"GCS bucket to be used\",\n\t)\n\n\tpushCmd.PersistentFlags().StringVar(\n\t\t&pushOpts.Registry,\n\t\t\"container-registry\",\n\t\t\"\",\n\t\t\"Container image registry to be used\",\n\t)\n\n\tpushCmd.PersistentFlags().StringVar(\n\t\t&buildVersion,\n\t\t\"build-version\",\n\t\t\"\",\n\t\t\"Build version from Jenkins (only used when --release specified)\",\n\t)\n\n\tpushOpts.AllowDup = true\n\tpushOpts.ValidateRemoteImageDigests = true\n\n\tAnagoCmd.AddCommand(pushCmd)\n}\n\nfunc runPush(opts *build.Options) error {\n\tbuildInstance := build.NewInstance(opts)\n\tif err := buildInstance.CheckReleaseBucket(); err != nil {\n\t\treturn errors.Wrap(err, \"check release bucket access\")\n\t}\n\n\tif runStage {\n\t\treturn runPushStage(buildInstance, opts)\n\t} else if runRelease {\n\t\treturn runPushRelease(buildInstance, opts)\n\t}\n\n\treturn errors.New(\"neither --stage nor --release provided\")\n}\n\nfunc runPushStage(\n\tbuildInstance *build.Instance,\n\topts *build.Options,\n) error {\n\tworkDir := os.Getenv(\"GOPATH\")\n\tif workDir == \"\" {\n\t\treturn errors.New(\"GOPATH is not set\")\n\t}\n\n\t\/\/ Stage the local source tree\n\tif err := buildInstance.StageLocalSourceTree(workDir, buildVersion); err != nil {\n\t\treturn errors.Wrap(err, \"staging local source tree\")\n\t}\n\n\t\/\/ Stage local artifacts and write checksums\n\tif err := buildInstance.StageLocalArtifacts(); err != nil {\n\t\treturn errors.Wrap(err, \"staging local artifacts\")\n\t}\n\tgcsPath := filepath.Join(opts.Bucket, \"stage\", buildVersion, opts.Version)\n\n\t\/\/ Push gcs-stage to GCS\n\tif err := buildInstance.PushReleaseArtifacts(\n\t\tfilepath.Join(opts.BuildDir, release.GCSStagePath, opts.Version),\n\t\tfilepath.Join(gcsPath, release.GCSStagePath, opts.Version),\n\t); err != nil {\n\t\treturn errors.Wrap(err, \"pushing release artifacts\")\n\t}\n\n\t\/\/ Push container release-images to GCS\n\tif err := buildInstance.PushReleaseArtifacts(\n\t\tfilepath.Join(opts.BuildDir, release.ImagesPath),\n\t\tfilepath.Join(gcsPath, release.ImagesPath),\n\t); err != nil {\n\t\treturn errors.Wrap(err, \"pushing release artifacts\")\n\t}\n\n\t\/\/ Push container images into registry\n\tif err := buildInstance.PushContainerImages(); err != nil {\n\t\treturn errors.Wrap(err, \"pushing container images\")\n\t}\n\n\treturn nil\n}\n\nfunc runPushRelease(\n\tbuildInstance *build.Instance,\n\topts *build.Options,\n) error {\n\tif err := buildInstance.CopyStagedFromGCS(opts.Bucket, buildVersion); err != nil {\n\t\treturn errors.Wrap(err, \"copy staged from GCS\")\n\t}\n\n\t\/\/ In an official nomock release, we want to ensure that container images\n\t\/\/ have been promoted from staging to production, so we do the image\n\t\/\/ manifest validation against production instead of staging.\n\ttargetRegistry := opts.Registry\n\tif targetRegistry == release.GCRIOPathStaging {\n\t\ttargetRegistry = release.GCRIOPathProd\n\t}\n\t\/\/ Image promotion has been done on nomock stage, verify that the images\n\t\/\/ are available.\n\tif err := release.NewImages().Validate(\n\t\ttargetRegistry, opts.Version, opts.BuildDir,\n\t); err != nil {\n\t\treturn errors.Wrap(err, \"validate container images\")\n\t}\n\n\tif err := release.NewPublisher().PublishVersion(\n\t\t\"release\", opts.Version, opts.BuildDir, opts.Bucket, \"\", nil, false, false,\n\t); err != nil {\n\t\treturn errors.Wrap(err, \"publish release\")\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright (c) 2019 VMware, Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage simulator\n\nimport (\n\t\"context\"\n\t\"reflect\"\n\n\t\"github.com\/google\/uuid\"\n\t\"github.com\/vmware\/govmomi\/cns\"\n\t\"github.com\/vmware\/govmomi\/cns\/methods\"\n\tcnstypes \"github.com\/vmware\/govmomi\/cns\/types\"\n\t\"github.com\/vmware\/govmomi\/simulator\"\n\t\"github.com\/vmware\/govmomi\/vim25\/soap\"\n\tvim25types \"github.com\/vmware\/govmomi\/vim25\/types\"\n)\n\nfunc New() *simulator.Registry {\n\tr := simulator.NewRegistry()\n\tr.Namespace = cns.Namespace\n\tr.Path = cns.Path\n\n\tr.Put(&CnsVolumeManager{\n\t\tManagedObjectReference: cns.CnsVolumeManagerInstance,\n\t\tvolumes:                make(map[vim25types.ManagedObjectReference]map[cnstypes.CnsVolumeId]*cnstypes.CnsVolume),\n\t\tattachments:            make(map[cnstypes.CnsVolumeId]vim25types.ManagedObjectReference),\n\t})\n\n\treturn r\n}\n\ntype CnsVolumeManager struct {\n\tvim25types.ManagedObjectReference\n\tvolumes     map[vim25types.ManagedObjectReference]map[cnstypes.CnsVolumeId]*cnstypes.CnsVolume\n\tattachments map[cnstypes.CnsVolumeId]vim25types.ManagedObjectReference\n}\n\nconst simulatorDiskUUID = \"6000c298595bf4575739e9105b2c0c2d\"\n\nfunc (m *CnsVolumeManager) CnsCreateVolume(ctx context.Context, req *cnstypes.CnsCreateVolume) soap.HasFault {\n\ttask := simulator.CreateTask(m, \"CnsCreateVolume\", func(*simulator.Task) (vim25types.AnyType, vim25types.BaseMethodFault) {\n\t\tif len(req.CreateSpecs) == 0 {\n\t\t\treturn nil, &vim25types.InvalidArgument{InvalidProperty: \"CnsVolumeCreateSpec\"}\n\t\t}\n\n\t\toperationResult := []cnstypes.BaseCnsVolumeOperationResult{}\n\t\tfor _, createSpec := range req.CreateSpecs {\n\t\t\tstaticProvisionedSpec, ok := interface{}(createSpec.BackingObjectDetails).(*cnstypes.CnsBlockBackingDetails)\n\t\t\tif ok && staticProvisionedSpec.BackingDiskId != \"\" {\n\t\t\t\tdatastore := simulator.Map.Any(\"Datastore\").(*simulator.Datastore)\n\t\t\t\tvolumes, ok := m.volumes[datastore.Self]\n\t\t\t\tif !ok {\n\t\t\t\t\tvolumes = make(map[cnstypes.CnsVolumeId]*cnstypes.CnsVolume)\n\t\t\t\t\tm.volumes[datastore.Self] = volumes\n\t\t\t\t}\n\t\t\t\tnewVolume := &cnstypes.CnsVolume{\n\t\t\t\t\tVolumeId: cnstypes.CnsVolumeId{\n\t\t\t\t\t\tId: interface{}(createSpec.BackingObjectDetails).(*cnstypes.CnsBlockBackingDetails).BackingDiskId,\n\t\t\t\t\t},\n\t\t\t\t\tName:                         createSpec.Name,\n\t\t\t\t\tVolumeType:                   createSpec.VolumeType,\n\t\t\t\t\tDatastoreUrl:                 datastore.Info.GetDatastoreInfo().Url,\n\t\t\t\t\tMetadata:                     createSpec.Metadata,\n\t\t\t\t\tBackingObjectDetails:         createSpec.BackingObjectDetails.(cnstypes.BaseCnsBackingObjectDetails).GetCnsBackingObjectDetails(),\n\t\t\t\t\tComplianceStatus:             \"Simulator Compliance Status\",\n\t\t\t\t\tDatastoreAccessibilityStatus: \"Simulator Datastore Accessibility Status\",\n\t\t\t\t}\n\n\t\t\t\tvolumes[newVolume.VolumeId] = newVolume\n\t\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\tVolumeId: newVolume.VolumeId,\n\t\t\t\t})\n\n\t\t\t} else {\n\t\t\t\tfor _, datastoreRef := range createSpec.Datastores {\n\t\t\t\t\tdatastore := simulator.Map.Get(datastoreRef).(*simulator.Datastore)\n\n\t\t\t\t\tvolumes, ok := m.volumes[datastore.Self]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tvolumes = make(map[cnstypes.CnsVolumeId]*cnstypes.CnsVolume)\n\t\t\t\t\t\tm.volumes[datastore.Self] = volumes\n\n\t\t\t\t\t}\n\n\t\t\t\t\tvar policyId string\n\t\t\t\t\tif createSpec.Profile != nil && createSpec.Profile[0] != nil &&\n\t\t\t\t\t\treflect.TypeOf(createSpec.Profile[0]) == reflect.TypeOf(&vim25types.VirtualMachineDefinedProfileSpec{}) {\n\t\t\t\t\t\tpolicyId = interface{}(createSpec.Profile[0]).(*vim25types.VirtualMachineDefinedProfileSpec).ProfileId\n\t\t\t\t\t}\n\n\t\t\t\t\tnewVolume := &cnstypes.CnsVolume{\n\t\t\t\t\t\tVolumeId: cnstypes.CnsVolumeId{\n\t\t\t\t\t\t\tId: uuid.New().String(),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tName:                         createSpec.Name,\n\t\t\t\t\t\tVolumeType:                   createSpec.VolumeType,\n\t\t\t\t\t\tDatastoreUrl:                 datastore.Info.GetDatastoreInfo().Url,\n\t\t\t\t\t\tMetadata:                     createSpec.Metadata,\n\t\t\t\t\t\tBackingObjectDetails:         createSpec.BackingObjectDetails.(cnstypes.BaseCnsBackingObjectDetails).GetCnsBackingObjectDetails(),\n\t\t\t\t\t\tComplianceStatus:             \"Simulator Compliance Status\",\n\t\t\t\t\t\tDatastoreAccessibilityStatus: \"Simulator Datastore Accessibility Status\",\n\t\t\t\t\t\tStoragePolicyId:              policyId,\n\t\t\t\t\t}\n\n\t\t\t\t\tvolumes[newVolume.VolumeId] = newVolume\n\t\t\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\t\tVolumeId: newVolume.VolumeId,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn &cnstypes.CnsVolumeOperationBatchResult{\n\t\t\tVolumeResults: operationResult,\n\t\t}, nil\n\t})\n\n\treturn &methods.CnsCreateVolumeBody{\n\t\tRes: &cnstypes.CnsCreateVolumeResponse{\n\t\t\tReturnval: task.Run(),\n\t\t},\n\t}\n}\n\n\/\/ CnsQueryVolume simulates the query volumes implementation for CNSQuery API\nfunc (m *CnsVolumeManager) CnsQueryVolume(ctx context.Context, req *cnstypes.CnsQueryVolume) soap.HasFault {\n\tretVolumes := []cnstypes.CnsVolume{}\n\treqVolumeIds := make(map[string]bool)\n\tisQueryFilter := false\n\n\tif req.Filter.VolumeIds != nil {\n\t\tisQueryFilter = true\n\t}\n\t\/\/ Create map of requested volume Ids in query request\n\tfor _, volumeID := range req.Filter.VolumeIds {\n\t\treqVolumeIds[volumeID.Id] = true\n\t}\n\n\tfor _, dsVolumes := range m.volumes {\n\t\tfor _, volume := range dsVolumes {\n\t\t\tif isQueryFilter {\n\t\t\t\tif _, ok := reqVolumeIds[volume.VolumeId.Id]; ok {\n\t\t\t\t\tretVolumes = append(retVolumes, *volume)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tretVolumes = append(retVolumes, *volume)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &methods.CnsQueryVolumeBody{\n\t\tRes: &cnstypes.CnsQueryVolumeResponse{\n\t\t\tReturnval: cnstypes.CnsQueryResult{\n\t\t\t\tVolumes: retVolumes,\n\t\t\t\tCursor:  cnstypes.CnsCursor{},\n\t\t\t},\n\t\t},\n\t}\n}\n\n\/\/ CnsQueryAllVolume simulates the query volumes implementation for CNSQueryAll API\nfunc (m *CnsVolumeManager) CnsQueryAllVolume(ctx context.Context, req *cnstypes.CnsQueryAllVolume) soap.HasFault {\n\tretVolumes := []cnstypes.CnsVolume{}\n\treqVolumeIds := make(map[string]bool)\n\tisQueryFilter := false\n\n\tif req.Filter.VolumeIds != nil {\n\t\tisQueryFilter = true\n\t}\n\t\/\/ Create map of requested volume Ids in query request\n\tfor _, volumeID := range req.Filter.VolumeIds {\n\t\treqVolumeIds[volumeID.Id] = true\n\t}\n\n\tfor _, dsVolumes := range m.volumes {\n\t\tfor _, volume := range dsVolumes {\n\t\t\tif isQueryFilter {\n\t\t\t\tif _, ok := reqVolumeIds[volume.VolumeId.Id]; ok {\n\t\t\t\t\tretVolumes = append(retVolumes, *volume)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tretVolumes = append(retVolumes, *volume)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &methods.CnsQueryAllVolumeBody{\n\t\tRes: &cnstypes.CnsQueryAllVolumeResponse{\n\t\t\tReturnval: cnstypes.CnsQueryResult{\n\t\t\t\tVolumes: retVolumes,\n\t\t\t\tCursor:  cnstypes.CnsCursor{},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (m *CnsVolumeManager) CnsDeleteVolume(ctx context.Context, req *cnstypes.CnsDeleteVolume) soap.HasFault {\n\ttask := simulator.CreateTask(m, \"CnsDeleteVolume\", func(*simulator.Task) (vim25types.AnyType, vim25types.BaseMethodFault) {\n\t\toperationResult := []cnstypes.BaseCnsVolumeOperationResult{}\n\t\tfor _, volumeId := range req.VolumeIds {\n\t\t\tfor ds, dsVolumes := range m.volumes {\n\t\t\t\tvolume := dsVolumes[volumeId]\n\t\t\t\tif volume != nil {\n\t\t\t\t\tdelete(m.volumes[ds], volumeId)\n\t\t\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\t\tVolumeId: volumeId,\n\t\t\t\t\t})\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn &cnstypes.CnsVolumeOperationBatchResult{\n\t\t\tVolumeResults: operationResult,\n\t\t}, nil\n\t})\n\n\treturn &methods.CnsDeleteVolumeBody{\n\t\tRes: &cnstypes.CnsDeleteVolumeResponse{\n\t\t\tReturnval: task.Run(),\n\t\t},\n\t}\n}\n\n\/\/ CnsUpdateVolumeMetadata simulates UpdateVolumeMetadata call for simulated vc\nfunc (m *CnsVolumeManager) CnsUpdateVolumeMetadata(ctx context.Context, req *cnstypes.CnsUpdateVolumeMetadata) soap.HasFault {\n\ttask := simulator.CreateTask(m, \"CnsUpdateVolumeMetadata\", func(*simulator.Task) (vim25types.AnyType, vim25types.BaseMethodFault) {\n\t\tif len(req.UpdateSpecs) == 0 {\n\t\t\treturn nil, &vim25types.InvalidArgument{InvalidProperty: \"CnsUpdateVolumeMetadataSpec\"}\n\t\t}\n\t\toperationResult := []cnstypes.BaseCnsVolumeOperationResult{}\n\t\tfor _, updateSpecs := range req.UpdateSpecs {\n\t\t\tfor _, dsVolumes := range m.volumes {\n\t\t\t\tfor id, volume := range dsVolumes {\n\t\t\t\t\tif id.Id == updateSpecs.VolumeId.Id {\n\t\t\t\t\t\tvolume.Metadata.EntityMetadata = updateSpecs.Metadata.EntityMetadata\n\t\t\t\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\t\t\tVolumeId: volume.VolumeId,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\treturn &cnstypes.CnsVolumeOperationBatchResult{\n\t\t\tVolumeResults: operationResult,\n\t\t}, nil\n\t})\n\treturn &methods.CnsUpdateVolumeBody{\n\t\tRes: &cnstypes.CnsUpdateVolumeMetadataResponse{\n\t\t\tReturnval: task.Run(),\n\t\t},\n\t}\n}\n\n\/\/ CnsAttachVolume simulates AttachVolume call for simulated vc\nfunc (m *CnsVolumeManager) CnsAttachVolume(ctx context.Context, req *cnstypes.CnsAttachVolume) soap.HasFault {\n\ttask := simulator.CreateTask(m, \"CnsAttachVolume\", func(task *simulator.Task) (vim25types.AnyType, vim25types.BaseMethodFault) {\n\t\tif len(req.AttachSpecs) == 0 {\n\t\t\treturn nil, &vim25types.InvalidArgument{InvalidProperty: \"CnsAttachVolumeSpec\"}\n\t\t}\n\t\toperationResult := []cnstypes.BaseCnsVolumeOperationResult{}\n\t\tfor _, attachSpec := range req.AttachSpecs {\n\t\t\tnode := simulator.Map.Get(attachSpec.Vm).(*simulator.VirtualMachine)\n\t\t\tif _, ok := m.attachments[attachSpec.VolumeId]; !ok {\n\t\t\t\tm.attachments[attachSpec.VolumeId] = node.Self\n\t\t\t} else {\n\t\t\t\treturn nil, &vim25types.ResourceInUse{\n\t\t\t\t\tName: attachSpec.VolumeId.Id,\n\t\t\t\t}\n\t\t\t}\n\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeAttachResult{\n\t\t\t\tCnsVolumeOperationResult: cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\tVolumeId: attachSpec.VolumeId,\n\t\t\t\t},\n\t\t\t\tDiskUUID: simulatorDiskUUID,\n\t\t\t})\n\t\t}\n\n\t\treturn &cnstypes.CnsVolumeOperationBatchResult{\n\t\t\tVolumeResults: operationResult,\n\t\t}, nil\n\t})\n\n\treturn &methods.CnsAttachVolumeBody{\n\t\tRes: &cnstypes.CnsAttachVolumeResponse{\n\t\t\tReturnval: task.Run(),\n\t\t},\n\t}\n}\n\n\/\/ CnsDetachVolume simulates DetachVolume call for simulated vc\nfunc (m *CnsVolumeManager) CnsDetachVolume(ctx context.Context, req *cnstypes.CnsDetachVolume) soap.HasFault {\n\ttask := simulator.CreateTask(m, \"CnsDetachVolume\", func(*simulator.Task) (vim25types.AnyType, vim25types.BaseMethodFault) {\n\t\tif len(req.DetachSpecs) == 0 {\n\t\t\treturn nil, &vim25types.InvalidArgument{InvalidProperty: \"CnsDetachVolumeSpec\"}\n\t\t}\n\t\toperationResult := []cnstypes.BaseCnsVolumeOperationResult{}\n\t\tfor _, detachSpec := range req.DetachSpecs {\n\t\t\tif _, ok := m.attachments[detachSpec.VolumeId]; ok {\n\t\t\t\tdelete(m.attachments, detachSpec.VolumeId)\n\t\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\tVolumeId: detachSpec.VolumeId,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\treturn nil, &vim25types.InvalidArgument{\n\t\t\t\t\tInvalidProperty: detachSpec.VolumeId.Id,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn &cnstypes.CnsVolumeOperationBatchResult{\n\t\t\tVolumeResults: operationResult,\n\t\t}, nil\n\t})\n\treturn &methods.CnsDetachVolumeBody{\n\t\tRes: &cnstypes.CnsDetachVolumeResponse{\n\t\t\tReturnval: task.Run(),\n\t\t},\n\t}\n}\n\n\/\/ CnsExtendVolume simulates ExtendVolume call for simulated vc\nfunc (m *CnsVolumeManager) CnsExtendVolume(ctx context.Context, req *cnstypes.CnsExtendVolume) soap.HasFault {\n\ttask := simulator.CreateTask(m, \"CnsExtendVolume\", func(task *simulator.Task) (vim25types.AnyType, vim25types.BaseMethodFault) {\n\t\tif len(req.ExtendSpecs) == 0 {\n\t\t\treturn nil, &vim25types.InvalidArgument{InvalidProperty: \"CnsExtendVolumeSpec\"}\n\t\t}\n\t\toperationResult := []cnstypes.BaseCnsVolumeOperationResult{}\n\n\t\tfor _, extendSpecs := range req.ExtendSpecs {\n\t\t\tfor _, dsVolumes := range m.volumes {\n\t\t\t\tfor id, volume := range dsVolumes {\n\t\t\t\t\tif id.Id == extendSpecs.VolumeId.Id {\n\t\t\t\t\t\tvolume.BackingObjectDetails = &cnstypes.CnsBackingObjectDetails{\n\t\t\t\t\t\t\tCapacityInMb: extendSpecs.CapacityInMb,\n\t\t\t\t\t\t}\n\t\t\t\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\t\t\tVolumeId: volume.VolumeId,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn &cnstypes.CnsVolumeOperationBatchResult{\n\t\t\tVolumeResults: operationResult,\n\t\t}, nil\n\t})\n\n\treturn &methods.CnsExtendVolumeBody{\n\t\tRes: &cnstypes.CnsExtendVolumeResponse{\n\t\t\tReturnval: task.Run(),\n\t\t},\n\t}\n}\n<commit_msg>Add logic to return default HealthStatus in CnsCreateVolume.<commit_after>\/*\nCopyright (c) 2019 VMware, Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage simulator\n\nimport (\n\t\"context\"\n\t\"reflect\"\n\n\t\"github.com\/google\/uuid\"\n\t\"github.com\/vmware\/govmomi\/cns\"\n\t\"github.com\/vmware\/govmomi\/cns\/methods\"\n\tcnstypes \"github.com\/vmware\/govmomi\/cns\/types\"\n\tpbmtypes \"github.com\/vmware\/govmomi\/pbm\/types\"\n\t\"github.com\/vmware\/govmomi\/simulator\"\n\t\"github.com\/vmware\/govmomi\/vim25\/soap\"\n\tvim25types \"github.com\/vmware\/govmomi\/vim25\/types\"\n)\n\nfunc New() *simulator.Registry {\n\tr := simulator.NewRegistry()\n\tr.Namespace = cns.Namespace\n\tr.Path = cns.Path\n\n\tr.Put(&CnsVolumeManager{\n\t\tManagedObjectReference: cns.CnsVolumeManagerInstance,\n\t\tvolumes:                make(map[vim25types.ManagedObjectReference]map[cnstypes.CnsVolumeId]*cnstypes.CnsVolume),\n\t\tattachments:            make(map[cnstypes.CnsVolumeId]vim25types.ManagedObjectReference),\n\t})\n\n\treturn r\n}\n\ntype CnsVolumeManager struct {\n\tvim25types.ManagedObjectReference\n\tvolumes     map[vim25types.ManagedObjectReference]map[cnstypes.CnsVolumeId]*cnstypes.CnsVolume\n\tattachments map[cnstypes.CnsVolumeId]vim25types.ManagedObjectReference\n}\n\nconst simulatorDiskUUID = \"6000c298595bf4575739e9105b2c0c2d\"\n\nfunc (m *CnsVolumeManager) CnsCreateVolume(ctx context.Context, req *cnstypes.CnsCreateVolume) soap.HasFault {\n\ttask := simulator.CreateTask(m, \"CnsCreateVolume\", func(*simulator.Task) (vim25types.AnyType, vim25types.BaseMethodFault) {\n\t\tif len(req.CreateSpecs) == 0 {\n\t\t\treturn nil, &vim25types.InvalidArgument{InvalidProperty: \"CnsVolumeCreateSpec\"}\n\t\t}\n\n\t\toperationResult := []cnstypes.BaseCnsVolumeOperationResult{}\n\t\tfor _, createSpec := range req.CreateSpecs {\n\t\t\tstaticProvisionedSpec, ok := interface{}(createSpec.BackingObjectDetails).(*cnstypes.CnsBlockBackingDetails)\n\t\t\tif ok && staticProvisionedSpec.BackingDiskId != \"\" {\n\t\t\t\tdatastore := simulator.Map.Any(\"Datastore\").(*simulator.Datastore)\n\t\t\t\tvolumes, ok := m.volumes[datastore.Self]\n\t\t\t\tif !ok {\n\t\t\t\t\tvolumes = make(map[cnstypes.CnsVolumeId]*cnstypes.CnsVolume)\n\t\t\t\t\tm.volumes[datastore.Self] = volumes\n\t\t\t\t}\n\t\t\t\tnewVolume := &cnstypes.CnsVolume{\n\t\t\t\t\tVolumeId: cnstypes.CnsVolumeId{\n\t\t\t\t\t\tId: interface{}(createSpec.BackingObjectDetails).(*cnstypes.CnsBlockBackingDetails).BackingDiskId,\n\t\t\t\t\t},\n\t\t\t\t\tName:                         createSpec.Name,\n\t\t\t\t\tVolumeType:                   createSpec.VolumeType,\n\t\t\t\t\tDatastoreUrl:                 datastore.Info.GetDatastoreInfo().Url,\n\t\t\t\t\tMetadata:                     createSpec.Metadata,\n\t\t\t\t\tBackingObjectDetails:         createSpec.BackingObjectDetails.(cnstypes.BaseCnsBackingObjectDetails).GetCnsBackingObjectDetails(),\n\t\t\t\t\tComplianceStatus:             \"Simulator Compliance Status\",\n\t\t\t\t\tDatastoreAccessibilityStatus: \"Simulator Datastore Accessibility Status\",\n\t\t\t\t\tHealthStatus:                 string(pbmtypes.PbmHealthStatusForEntityGreen),\n\t\t\t\t}\n\n\t\t\t\tvolumes[newVolume.VolumeId] = newVolume\n\t\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\tVolumeId: newVolume.VolumeId,\n\t\t\t\t})\n\n\t\t\t} else {\n\t\t\t\tfor _, datastoreRef := range createSpec.Datastores {\n\t\t\t\t\tdatastore := simulator.Map.Get(datastoreRef).(*simulator.Datastore)\n\n\t\t\t\t\tvolumes, ok := m.volumes[datastore.Self]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tvolumes = make(map[cnstypes.CnsVolumeId]*cnstypes.CnsVolume)\n\t\t\t\t\t\tm.volumes[datastore.Self] = volumes\n\n\t\t\t\t\t}\n\n\t\t\t\t\tvar policyId string\n\t\t\t\t\tif createSpec.Profile != nil && createSpec.Profile[0] != nil &&\n\t\t\t\t\t\treflect.TypeOf(createSpec.Profile[0]) == reflect.TypeOf(&vim25types.VirtualMachineDefinedProfileSpec{}) {\n\t\t\t\t\t\tpolicyId = interface{}(createSpec.Profile[0]).(*vim25types.VirtualMachineDefinedProfileSpec).ProfileId\n\t\t\t\t\t}\n\n\t\t\t\t\tnewVolume := &cnstypes.CnsVolume{\n\t\t\t\t\t\tVolumeId: cnstypes.CnsVolumeId{\n\t\t\t\t\t\t\tId: uuid.New().String(),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tName:                         createSpec.Name,\n\t\t\t\t\t\tVolumeType:                   createSpec.VolumeType,\n\t\t\t\t\t\tDatastoreUrl:                 datastore.Info.GetDatastoreInfo().Url,\n\t\t\t\t\t\tMetadata:                     createSpec.Metadata,\n\t\t\t\t\t\tBackingObjectDetails:         createSpec.BackingObjectDetails.(cnstypes.BaseCnsBackingObjectDetails).GetCnsBackingObjectDetails(),\n\t\t\t\t\t\tComplianceStatus:             \"Simulator Compliance Status\",\n\t\t\t\t\t\tDatastoreAccessibilityStatus: \"Simulator Datastore Accessibility Status\",\n\t\t\t\t\t\tHealthStatus:                 string(pbmtypes.PbmHealthStatusForEntityGreen),\n\t\t\t\t\t\tStoragePolicyId:              policyId,\n\t\t\t\t\t}\n\n\t\t\t\t\tvolumes[newVolume.VolumeId] = newVolume\n\t\t\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\t\tVolumeId: newVolume.VolumeId,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn &cnstypes.CnsVolumeOperationBatchResult{\n\t\t\tVolumeResults: operationResult,\n\t\t}, nil\n\t})\n\n\treturn &methods.CnsCreateVolumeBody{\n\t\tRes: &cnstypes.CnsCreateVolumeResponse{\n\t\t\tReturnval: task.Run(),\n\t\t},\n\t}\n}\n\n\/\/ CnsQueryVolume simulates the query volumes implementation for CNSQuery API\nfunc (m *CnsVolumeManager) CnsQueryVolume(ctx context.Context, req *cnstypes.CnsQueryVolume) soap.HasFault {\n\tretVolumes := []cnstypes.CnsVolume{}\n\treqVolumeIds := make(map[string]bool)\n\tisQueryFilter := false\n\n\tif req.Filter.VolumeIds != nil {\n\t\tisQueryFilter = true\n\t}\n\t\/\/ Create map of requested volume Ids in query request\n\tfor _, volumeID := range req.Filter.VolumeIds {\n\t\treqVolumeIds[volumeID.Id] = true\n\t}\n\n\tfor _, dsVolumes := range m.volumes {\n\t\tfor _, volume := range dsVolumes {\n\t\t\tif isQueryFilter {\n\t\t\t\tif _, ok := reqVolumeIds[volume.VolumeId.Id]; ok {\n\t\t\t\t\tretVolumes = append(retVolumes, *volume)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tretVolumes = append(retVolumes, *volume)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &methods.CnsQueryVolumeBody{\n\t\tRes: &cnstypes.CnsQueryVolumeResponse{\n\t\t\tReturnval: cnstypes.CnsQueryResult{\n\t\t\t\tVolumes: retVolumes,\n\t\t\t\tCursor:  cnstypes.CnsCursor{},\n\t\t\t},\n\t\t},\n\t}\n}\n\n\/\/ CnsQueryAllVolume simulates the query volumes implementation for CNSQueryAll API\nfunc (m *CnsVolumeManager) CnsQueryAllVolume(ctx context.Context, req *cnstypes.CnsQueryAllVolume) soap.HasFault {\n\tretVolumes := []cnstypes.CnsVolume{}\n\treqVolumeIds := make(map[string]bool)\n\tisQueryFilter := false\n\n\tif req.Filter.VolumeIds != nil {\n\t\tisQueryFilter = true\n\t}\n\t\/\/ Create map of requested volume Ids in query request\n\tfor _, volumeID := range req.Filter.VolumeIds {\n\t\treqVolumeIds[volumeID.Id] = true\n\t}\n\n\tfor _, dsVolumes := range m.volumes {\n\t\tfor _, volume := range dsVolumes {\n\t\t\tif isQueryFilter {\n\t\t\t\tif _, ok := reqVolumeIds[volume.VolumeId.Id]; ok {\n\t\t\t\t\tretVolumes = append(retVolumes, *volume)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tretVolumes = append(retVolumes, *volume)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &methods.CnsQueryAllVolumeBody{\n\t\tRes: &cnstypes.CnsQueryAllVolumeResponse{\n\t\t\tReturnval: cnstypes.CnsQueryResult{\n\t\t\t\tVolumes: retVolumes,\n\t\t\t\tCursor:  cnstypes.CnsCursor{},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (m *CnsVolumeManager) CnsDeleteVolume(ctx context.Context, req *cnstypes.CnsDeleteVolume) soap.HasFault {\n\ttask := simulator.CreateTask(m, \"CnsDeleteVolume\", func(*simulator.Task) (vim25types.AnyType, vim25types.BaseMethodFault) {\n\t\toperationResult := []cnstypes.BaseCnsVolumeOperationResult{}\n\t\tfor _, volumeId := range req.VolumeIds {\n\t\t\tfor ds, dsVolumes := range m.volumes {\n\t\t\t\tvolume := dsVolumes[volumeId]\n\t\t\t\tif volume != nil {\n\t\t\t\t\tdelete(m.volumes[ds], volumeId)\n\t\t\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\t\tVolumeId: volumeId,\n\t\t\t\t\t})\n\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn &cnstypes.CnsVolumeOperationBatchResult{\n\t\t\tVolumeResults: operationResult,\n\t\t}, nil\n\t})\n\n\treturn &methods.CnsDeleteVolumeBody{\n\t\tRes: &cnstypes.CnsDeleteVolumeResponse{\n\t\t\tReturnval: task.Run(),\n\t\t},\n\t}\n}\n\n\/\/ CnsUpdateVolumeMetadata simulates UpdateVolumeMetadata call for simulated vc\nfunc (m *CnsVolumeManager) CnsUpdateVolumeMetadata(ctx context.Context, req *cnstypes.CnsUpdateVolumeMetadata) soap.HasFault {\n\ttask := simulator.CreateTask(m, \"CnsUpdateVolumeMetadata\", func(*simulator.Task) (vim25types.AnyType, vim25types.BaseMethodFault) {\n\t\tif len(req.UpdateSpecs) == 0 {\n\t\t\treturn nil, &vim25types.InvalidArgument{InvalidProperty: \"CnsUpdateVolumeMetadataSpec\"}\n\t\t}\n\t\toperationResult := []cnstypes.BaseCnsVolumeOperationResult{}\n\t\tfor _, updateSpecs := range req.UpdateSpecs {\n\t\t\tfor _, dsVolumes := range m.volumes {\n\t\t\t\tfor id, volume := range dsVolumes {\n\t\t\t\t\tif id.Id == updateSpecs.VolumeId.Id {\n\t\t\t\t\t\tvolume.Metadata.EntityMetadata = updateSpecs.Metadata.EntityMetadata\n\t\t\t\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\t\t\tVolumeId: volume.VolumeId,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\treturn &cnstypes.CnsVolumeOperationBatchResult{\n\t\t\tVolumeResults: operationResult,\n\t\t}, nil\n\t})\n\treturn &methods.CnsUpdateVolumeBody{\n\t\tRes: &cnstypes.CnsUpdateVolumeMetadataResponse{\n\t\t\tReturnval: task.Run(),\n\t\t},\n\t}\n}\n\n\/\/ CnsAttachVolume simulates AttachVolume call for simulated vc\nfunc (m *CnsVolumeManager) CnsAttachVolume(ctx context.Context, req *cnstypes.CnsAttachVolume) soap.HasFault {\n\ttask := simulator.CreateTask(m, \"CnsAttachVolume\", func(task *simulator.Task) (vim25types.AnyType, vim25types.BaseMethodFault) {\n\t\tif len(req.AttachSpecs) == 0 {\n\t\t\treturn nil, &vim25types.InvalidArgument{InvalidProperty: \"CnsAttachVolumeSpec\"}\n\t\t}\n\t\toperationResult := []cnstypes.BaseCnsVolumeOperationResult{}\n\t\tfor _, attachSpec := range req.AttachSpecs {\n\t\t\tnode := simulator.Map.Get(attachSpec.Vm).(*simulator.VirtualMachine)\n\t\t\tif _, ok := m.attachments[attachSpec.VolumeId]; !ok {\n\t\t\t\tm.attachments[attachSpec.VolumeId] = node.Self\n\t\t\t} else {\n\t\t\t\treturn nil, &vim25types.ResourceInUse{\n\t\t\t\t\tName: attachSpec.VolumeId.Id,\n\t\t\t\t}\n\t\t\t}\n\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeAttachResult{\n\t\t\t\tCnsVolumeOperationResult: cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\tVolumeId: attachSpec.VolumeId,\n\t\t\t\t},\n\t\t\t\tDiskUUID: simulatorDiskUUID,\n\t\t\t})\n\t\t}\n\n\t\treturn &cnstypes.CnsVolumeOperationBatchResult{\n\t\t\tVolumeResults: operationResult,\n\t\t}, nil\n\t})\n\n\treturn &methods.CnsAttachVolumeBody{\n\t\tRes: &cnstypes.CnsAttachVolumeResponse{\n\t\t\tReturnval: task.Run(),\n\t\t},\n\t}\n}\n\n\/\/ CnsDetachVolume simulates DetachVolume call for simulated vc\nfunc (m *CnsVolumeManager) CnsDetachVolume(ctx context.Context, req *cnstypes.CnsDetachVolume) soap.HasFault {\n\ttask := simulator.CreateTask(m, \"CnsDetachVolume\", func(*simulator.Task) (vim25types.AnyType, vim25types.BaseMethodFault) {\n\t\tif len(req.DetachSpecs) == 0 {\n\t\t\treturn nil, &vim25types.InvalidArgument{InvalidProperty: \"CnsDetachVolumeSpec\"}\n\t\t}\n\t\toperationResult := []cnstypes.BaseCnsVolumeOperationResult{}\n\t\tfor _, detachSpec := range req.DetachSpecs {\n\t\t\tif _, ok := m.attachments[detachSpec.VolumeId]; ok {\n\t\t\t\tdelete(m.attachments, detachSpec.VolumeId)\n\t\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\tVolumeId: detachSpec.VolumeId,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\treturn nil, &vim25types.InvalidArgument{\n\t\t\t\t\tInvalidProperty: detachSpec.VolumeId.Id,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn &cnstypes.CnsVolumeOperationBatchResult{\n\t\t\tVolumeResults: operationResult,\n\t\t}, nil\n\t})\n\treturn &methods.CnsDetachVolumeBody{\n\t\tRes: &cnstypes.CnsDetachVolumeResponse{\n\t\t\tReturnval: task.Run(),\n\t\t},\n\t}\n}\n\n\/\/ CnsExtendVolume simulates ExtendVolume call for simulated vc\nfunc (m *CnsVolumeManager) CnsExtendVolume(ctx context.Context, req *cnstypes.CnsExtendVolume) soap.HasFault {\n\ttask := simulator.CreateTask(m, \"CnsExtendVolume\", func(task *simulator.Task) (vim25types.AnyType, vim25types.BaseMethodFault) {\n\t\tif len(req.ExtendSpecs) == 0 {\n\t\t\treturn nil, &vim25types.InvalidArgument{InvalidProperty: \"CnsExtendVolumeSpec\"}\n\t\t}\n\t\toperationResult := []cnstypes.BaseCnsVolumeOperationResult{}\n\n\t\tfor _, extendSpecs := range req.ExtendSpecs {\n\t\t\tfor _, dsVolumes := range m.volumes {\n\t\t\t\tfor id, volume := range dsVolumes {\n\t\t\t\t\tif id.Id == extendSpecs.VolumeId.Id {\n\t\t\t\t\t\tvolume.BackingObjectDetails = &cnstypes.CnsBackingObjectDetails{\n\t\t\t\t\t\t\tCapacityInMb: extendSpecs.CapacityInMb,\n\t\t\t\t\t\t}\n\t\t\t\t\t\toperationResult = append(operationResult, &cnstypes.CnsVolumeOperationResult{\n\t\t\t\t\t\t\tVolumeId: volume.VolumeId,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn &cnstypes.CnsVolumeOperationBatchResult{\n\t\t\tVolumeResults: operationResult,\n\t\t}, nil\n\t})\n\n\treturn &methods.CnsExtendVolumeBody{\n\t\tRes: &cnstypes.CnsExtendVolumeResponse{\n\t\t\tReturnval: task.Run(),\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nxslate is an extremely powerful template engine, based on Perl5's Text::Xslate\nmodule. Xslate uses a virtual machine to execute pre-compiled template bytecode,\nwhich gives its flexibility while maitaining a very fast execution speed.\n\nNote that RenderString() DOES NOT CACHE THE GENERATED BYTECODE. This has\nsignificant effect on performance if you repeatedly call the same template\n\n*\/\npackage xslate\n\nimport (\n  \"errors\"\n  \"fmt\"\n  \"io\/ioutil\"\n  \"os\"\n  \"reflect\"\n\n  \"github.com\/lestrrat\/go-xslate\/compiler\"\n  \"github.com\/lestrrat\/go-xslate\/loader\"\n  \"github.com\/lestrrat\/go-xslate\/parser\"\n  \"github.com\/lestrrat\/go-xslate\/parser\/tterse\"\n  \"github.com\/lestrrat\/go-xslate\/vm\"\n)\n\ntype Vars vm.Vars\ntype Xslate struct {\n  Flags    int32\n  Vm       *vm.VM\n  Compiler compiler.Compiler\n  Parser   parser.Parser\n  Loader   loader.ByteCodeLoader\n  \/\/ XXX Need to make syntax pluggable\n}\n\ntype ConfigureArgs interface {\n  Get(string) (interface {}, bool)\n}\n\ntype Args map[string]interface {}\n\nfunc DefaultCompiler(tx *Xslate, args Args) error {\n  tx.Compiler = compiler.New()\n  return nil\n}\n\nfunc DefaultParser(tx *Xslate, args Args) error {\n  tx.Parser = tterse.New()\n  return nil\n}\n\nfunc DefaultLoader(tx *Xslate, args Args) error {\n  var tmp interface {}\n  tmp, ok := args.Get(\"CacheDir\")\n  if !ok {\n    tmp, _ = ioutil.TempDir(\"\", \"go-xslate-cache-\")\n  }\n  cacheDir := tmp.(string)\n\n  tmp, ok = args.Get(\"LoadPaths\")\n  if !ok {\n    cwd, _ := os.Getwd()\n    tmp = []string { cwd }\n  }\n  paths := tmp.([]string)\n\n  cache, err := loader.NewFileCache(cacheDir)\n  if err != nil {\n    return err\n  }\n  fileloader, err := loader.NewFileTemplateLoader(paths)\n  if err != nil {\n    return err\n  }\n  tx.Loader = loader.NewCachedByteCodeLoader(cache, fileloader, tx.Parser, tx.Compiler)\n  return nil\n}\n\nfunc DefaultVm(tx *Xslate, args Args) error {\n  tx.Vm = vm.NewVM()\n  tx.Vm.Loader = tx.Loader\n  return nil\n}\n\nfunc (args Args) Get(key string) (interface {}, bool) {\n  ret, ok := args[key]\n  return ret, ok\n}\n\nfunc (tx *Xslate) configureGeneric(configuror interface {}, args Args) error {\n  ref := reflect.ValueOf(configuror)\n  switch ref.Type().Kind() {\n  case reflect.Func:\n    \/\/ If this is a function, it better take our Xslate instance as the\n    \/\/ sole argument, and initialize it as it pleases\n    if ref.Type().NumIn() != 2 && (ref.Type().In(0).Name() != \"Xslate\" || ref.Type().In(1).Name() != \"Args\") {\n      panic(fmt.Sprintf(`Expected function initializer \"func (tx *Xslate \", but instead of %s`, ref.Type))\n    }\n    cb := configuror.(func(*Xslate, Args) error)\n    err := cb(tx, args)\n    return err\n  }\n  return errors.New(\"Bad configurator\")\n}\n\nfunc (tx *Xslate) Configure(args ConfigureArgs) error {\n  \/\/ The compiler currently does not have any configurable options, but\n  \/\/ one may want to replace the entire compiler struct\n  defaults := map[string]func(*Xslate, Args) error {\n    \"Compiler\": DefaultCompiler,\n    \"Parser\":   DefaultParser,\n    \"Loader\":   DefaultLoader,\n    \"Vm\":       DefaultVm,\n  }\n\n  for _, key := range []string { \"Parser\", \"Compiler\", \"Loader\", \"Vm\" } {\n    configKey := \"Configure\" + key\n    configuror, ok := args.Get(configKey);\n    if !ok {\n      configuror = defaults[key]\n    }\n\n    args, ok := args.Get(key)\n    if !ok {\n      args = Args {}\n    }\n\n    err := tx.configureGeneric(configuror, args.(Args))\n    if err != nil {\n      return err\n    }\n  }\n\n  return nil\n}\n\nfunc New(args ...Args) (*Xslate, error) {\n  tx := &Xslate {}\n\n  \/\/ We jump through hoops because there are A LOT of configuration options\n  \/\/ but most of them only need to use the default values\n  if len(args) <= 0 {\n    args = []Args { Args {} }\n  }\n  err := tx.Configure(args[0])\n  if err != nil {\n    return nil, err\n  }\n  return tx, nil\n}\n\nfunc (tx *Xslate) DumpAST(b bool) {\n  tx.Loader.DumpAST(b)\n}\n\nfunc (tx *Xslate) DumpByteCode(b bool) {\n  tx.Loader.DumpByteCode(b)\n}\n\nfunc (x *Xslate) Render(name string, vars Vars) (string, error) {\n  bc, err := x.Loader.Load(name)\n  if err != nil {\n    return \"\", err\n  }\n  x.Vm.Run(bc, vm.Vars(vars))\n  str, err := x.Vm.OutputString()\n  return str, err\n}\n\nfunc (x *Xslate) RenderString(template string, vars Vars) (string, error) {\n  bc, err := x.Loader.LoadString(template)\n  x.Vm.Run(bc, vm.Vars(vars))\n  str, err := x.Vm.OutputString()\n  return str, err\n}\n<commit_msg>slight code optimization<commit_after>\/*\nxslate is an extremely powerful template engine, based on Perl5's Text::Xslate\nmodule. Xslate uses a virtual machine to execute pre-compiled template bytecode,\nwhich gives its flexibility while maitaining a very fast execution speed.\n\nNote that RenderString() DOES NOT CACHE THE GENERATED BYTECODE. This has\nsignificant effect on performance if you repeatedly call the same template\n\n*\/\npackage xslate\n\nimport (\n  \"errors\"\n  \"fmt\"\n  \"io\/ioutil\"\n  \"os\"\n  \"reflect\"\n\n  \"github.com\/lestrrat\/go-xslate\/compiler\"\n  \"github.com\/lestrrat\/go-xslate\/loader\"\n  \"github.com\/lestrrat\/go-xslate\/parser\"\n  \"github.com\/lestrrat\/go-xslate\/parser\/tterse\"\n  \"github.com\/lestrrat\/go-xslate\/vm\"\n)\n\ntype Vars vm.Vars\ntype Xslate struct {\n  Flags    int32\n  Vm       *vm.VM\n  Compiler compiler.Compiler\n  Parser   parser.Parser\n  Loader   loader.ByteCodeLoader\n  \/\/ XXX Need to make syntax pluggable\n}\n\ntype ConfigureArgs interface {\n  Get(string) (interface {}, bool)\n}\n\ntype Args map[string]interface {}\n\nfunc DefaultCompiler(tx *Xslate, args Args) error {\n  tx.Compiler = compiler.New()\n  return nil\n}\n\nfunc DefaultParser(tx *Xslate, args Args) error {\n  tx.Parser = tterse.New()\n  return nil\n}\n\nfunc DefaultLoader(tx *Xslate, args Args) error {\n  var tmp interface {}\n  tmp, ok := args.Get(\"CacheDir\")\n  if !ok {\n    tmp, _ = ioutil.TempDir(\"\", \"go-xslate-cache-\")\n  }\n  cacheDir := tmp.(string)\n\n  tmp, ok = args.Get(\"LoadPaths\")\n  if !ok {\n    cwd, _ := os.Getwd()\n    tmp = []string { cwd }\n  }\n  paths := tmp.([]string)\n\n  cache, err := loader.NewFileCache(cacheDir)\n  if err != nil {\n    return err\n  }\n  fileloader, err := loader.NewFileTemplateLoader(paths)\n  if err != nil {\n    return err\n  }\n  tx.Loader = loader.NewCachedByteCodeLoader(cache, fileloader, tx.Parser, tx.Compiler)\n  return nil\n}\n\nfunc DefaultVm(tx *Xslate, args Args) error {\n  tx.Vm = vm.NewVM()\n  tx.Vm.Loader = tx.Loader\n  return nil\n}\n\nfunc (args Args) Get(key string) (interface {}, bool) {\n  ret, ok := args[key]\n  return ret, ok\n}\n\nfunc (tx *Xslate) configureGeneric(configuror interface {}, args Args) error {\n  ref := reflect.ValueOf(configuror)\n  switch ref.Type().Kind() {\n  case reflect.Func:\n    \/\/ If this is a function, it better take our Xslate instance as the\n    \/\/ sole argument, and initialize it as it pleases\n    if ref.Type().NumIn() != 2 && (ref.Type().In(0).Name() != \"Xslate\" || ref.Type().In(1).Name() != \"Args\") {\n      panic(fmt.Sprintf(`Expected function initializer \"func (tx *Xslate \", but instead of %s`, ref.Type))\n    }\n    cb := configuror.(func(*Xslate, Args) error)\n    err := cb(tx, args)\n    return err\n  }\n  return errors.New(\"Bad configurator\")\n}\n\nfunc (tx *Xslate) Configure(args ConfigureArgs) error {\n  \/\/ The compiler currently does not have any configurable options, but\n  \/\/ one may want to replace the entire compiler struct\n  defaults := map[string]func(*Xslate, Args) error {\n    \"Compiler\": DefaultCompiler,\n    \"Parser\":   DefaultParser,\n    \"Loader\":   DefaultLoader,\n    \"Vm\":       DefaultVm,\n  }\n\n  for _, key := range []string { \"Parser\", \"Compiler\", \"Loader\", \"Vm\" } {\n    configKey := \"Configure\" + key\n    configuror, ok := args.Get(configKey);\n    if !ok {\n      configuror = defaults[key]\n    }\n\n    args, ok := args.Get(key)\n    if !ok {\n      args = Args {}\n    }\n\n    err := tx.configureGeneric(configuror, args.(Args))\n    if err != nil {\n      return err\n    }\n  }\n\n  return nil\n}\n\nfunc New(args ...Args) (*Xslate, error) {\n  tx := &Xslate {}\n\n  \/\/ We jump through hoops because there are A LOT of configuration options\n  \/\/ but most of them only need to use the default values\n  if len(args) <= 0 {\n    args = []Args { Args {} }\n  }\n  err := tx.Configure(args[0])\n  if err != nil {\n    return nil, err\n  }\n  return tx, nil\n}\n\nfunc (tx *Xslate) DumpAST(b bool) {\n  tx.Loader.DumpAST(b)\n}\n\nfunc (tx *Xslate) DumpByteCode(b bool) {\n  tx.Loader.DumpByteCode(b)\n}\n\nfunc (x *Xslate) Render(name string, vars Vars) (string, error) {\n  bc, err := x.Loader.Load(name)\n  if err != nil {\n    return \"\", err\n  }\n  x.Vm.Run(bc, vm.Vars(vars))\n  return x.Vm.OutputString()\n}\n\nfunc (x *Xslate) RenderString(template string, vars Vars) (string, error) {\n  bc, err := x.Loader.LoadString(template)\n  if err != nil {\n    return \"\", err\n  }\n\n  x.Vm.Run(bc, vm.Vars(vars))\n  return x.Vm.OutputString()\n}\n<|endoftext|>"}
{"text":"<commit_before>package wait\n\nimport \"time\"\n\nfunc New(d time.Duration) (waiter <-chan time.Time, done func()) {\n\twait := make(chan time.Time)\n\tstop := make(chan struct{})\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase wait <- time.Now():\n\t\t\t\ttime.Sleep(d)\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn wait, func() {\n\t\tclose(stop)\n\t}\n}\n<commit_msg>Remove dead code<commit_after><|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"html\"\n\t\"html\/template\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar addr = flag.String(\"addr\", \":4089\", \"Server address\")\nvar timeout = flag.Duration(\"timeout\", 5*time.Second, \"Timeout for HTTP GETs\")\nvar conditionsInterval = flag.Duration(\"conditions_interval\", 10*time.Minute, \"Interval between updating conditions\")\nvar siteMapUrl = flag.String(\"site_map_url\", \"http:\/\/magicseaweed.com\/site-map.php\", \"URL of the site map\")\nvar conditionsFilePath = flag.String(\"conditions_file\", \"conditions.json\", \"Path to file with conditions cache\")\nvar conditionsPeriod = flag.Duration(\"conditions_period\", 10*time.Second, \"How often to save the conditions file\")\nvar help = flag.Bool(\"h\", false, \"Show help message\")\n\nfunc main() {\n\tflag.Parse()\n\tif *help {\n\t\tflag.Usage()\n\t\tos.Exit(0)\n\t}\n\tloadConditionsFile()\n\thttp.HandleFunc(\"\/\", handleRoot)\n\thttp.HandleFunc(\"\/errors\", handleErrors)\n\tgo keepConditionsUpdated()\n\tlog.Printf(\"Listening on %s\", *addr)\n\tlog.Fatal(http.ListenAndServe(*addr, nil))\n}\n\nvar head = template.HTML(`\n\t<head>\n\t\t<title>Waveguide<\/title>\n\t\t<style>\n\t\t\tbody {\n\t\t\t\tfont-family: monospace;\n\t\t\t}\n\t\t\ttable {\n\t\t\t\tborder-collapse: separate;\n\t\t\t\tfont-size: 12pt;\n\t\t\t}\n\t\t\tth {\n\t\t\t\ttext-align: left;\n\t\t\t}\n\t\t\tth, td {\n\t\t\t\tpadding: 0 1em 0.5ex 0;\n\t\t\t}\n\t\t<\/style>\n\t<\/head>\n`)\n\nvar errsTmpl = template.Must(template.New(\"errs\").Parse(`\n<html>\n{{.Head}}\n\t<body>\n\t\t<b>Errors<\/b>:\n\t\t<table>\n\t\t\t{{range .Errs}}\n\t\t\t<tr>\n\t\t\t\t<td><a href=\"http:\/\/magicseaweed.com{{.Loc.MagicSeaweedPath}}\">{{.Loc.HTMLName}}<\/a><\/td>\n\t\t\t\t<td>{{.Err}}<\/td>\n\t\t\t<\/tr>\n\t\t\t{{end}}\n\t\t<\/table>\n\t<\/body>\n<\/html>\n`))\n\nvar tmpl = template.Must(template.New(\"main\").Parse(`\n<html>\n{{.Head}}\n\t<body>\n\t\t{{if .Conds}}\n\t\t<table>\n\t\t\t<thead>\n\t\t\t\t<th>Location<\/th>\n\t\t\t\t<th>Conditions<\/th>\n\t\t\t\t<th>Wave Height<\/th>\n\t\t\t<\/thead>\n\t\t\t<tbody>\n\t\t\t\t{{range .Conds}}\n\t\t\t\t<tr>\n\t\t\t\t\t<td><a href=\"http:\/\/magicseaweed.com{{.Loc.MagicSeaweedPath}}\">{{.Loc.HTMLName}}<\/a><\/td>\n\t\t\t\t\t<td>{{.Stars}}<\/td>\n\t\t\t\t\t<td>{{.Details}}<\/td>\n\t\t\t\t<\/tr>\n\t\t\t\t{{end}}\n\t\t\t<\/tbody>\n\t\t<\/table>\n\t\t{{end}}\n\t<\/body>\n<\/html>\n`))\n\ntype Location struct {\n\tName             string\n\tMagicSeaweedPath string\n}\n\nfunc (loc *Location) HTMLName() template.HTML {\n\treturn template.HTML(loc.Name)\n}\n\ntype Conditions struct {\n\tLoc     *Location\n\tRating  int\n\tDetails string\n}\n\ntype Error struct {\n\tLoc *Location\n\tErr error\n}\n\nfunc handleErrors(w http.ResponseWriter, r *http.Request) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tdata := struct {\n\t\tErrs []*Error\n\t\tHead template.HTML\n\t}{\n\t\tErrs: errs,\n\t\tHead: head,\n\t}\n\terr := errsTmpl.Execute(w, data)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to execute template. %v\", err)\n\t}\n}\n\nfunc handleRoot(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Sort conditions by rating and name.\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tconds2 := make([]*Conditions, 0, len(conds))\n\tfor _, c := range conds {\n\t\tconds2 = append(conds2, c)\n\t}\n\tsort.Sort(ByRating(conds2))\n\n\t\/\/ Render the results.\n\tdata := struct {\n\t\tConds []*Conditions\n\t\tHead  template.HTML\n\t}{Conds: conds2, Head: head}\n\terr := tmpl.Execute(w, data)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to execute template. %v\", err)\n\t}\n}\n\nfunc updateConditionsAllLocations() {\n\tclient := &http.Client{Timeout: *timeout}\n\n\t\/\/ Gather locations.\n\tlog.Printf(\"Fetching %s\", *siteMapUrl)\n\tresp, err := client.Get(*siteMapUrl)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to get site map. %v\", err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to read response body of site map. %v\", err)\n\t}\n\treportMatches := reportRx.FindAll(body, -1)\n\tfor _, match := range reportMatches {\n\t\tpath := string(match)\n\t\tname, err := surfReportPathToName(path)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to convert surf report path to name. %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\t_, ok := locations[name]\n\t\tif !ok {\n\t\t\tlog.Printf(\"Got new location: %s: %s\", name, path)\n\t\t}\n\t\tloc := &Location{\n\t\t\tName:             name,\n\t\t\tMagicSeaweedPath: path,\n\t\t}\n\t\tlocations[name] = loc\n\t}\n\tlog.Printf(\"Found %d reports\", len(reportMatches))\n\tlog.Printf(\"New number of locations: %d\", len(locations))\n\n\t\/\/ Gather conditions and errors.\n\tmu.Lock()\n\terrs = make([]*Error, 0, len(locations))\n\tmu.Unlock()\n\tfor _, loc := range locations {\n\t\tcond, err := loc.GetConditions(client)\n\t\tif err != nil {\n\t\t\tmu.Lock()\n\t\t\te := &Error{\n\t\t\t\tLoc: loc,\n\t\t\t\tErr: err,\n\t\t\t}\n\t\t\terrs = append(errs, e)\n\t\t\tmu.Unlock()\n\t\t\tcontinue\n\t\t}\n\t\tmu.Lock()\n\t\tconds[loc.Name] = cond\n\t\tmu.Unlock()\n\t\tsaveConditionsFile()\n\t}\n}\n\nvar srpTailRx = regexp.MustCompile(`-Surf-Report\/\\d+\/`)\n\nfunc surfReportPathToName(srp string) (string, error) {\n\ts := srpTailRx.ReplaceAllString(srp, \"\")\n\ts, err := url.PathUnescape(s)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to unescape path in surfReportPathToName(%q). %v\", srp, err)\n\t}\n\ts = html.UnescapeString(s)\n\ts = s[1:] \/\/ Remove leading \/\n\ts = strings.Replace(s, \"-\", \" \", -1)\n\treturn s, nil\n}\n\nfunc loadConditionsFile() {\n\tf, err := os.Open(*conditionsFilePath)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to open conditions file %s. %v. That's okay.\", *conditionsFilePath, err)\n\t\treturn\n\t}\n\tcontents, err := ioutil.ReadAll(f)\n\terr = json.Unmarshal(contents, &conds)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to unmarshall the conditions map. %v\", err)\n\t\tos.Exit(1)\n\t}\n\tlog.Printf(\"Loaded conditions file %s\", *conditionsFilePath)\n}\n\nfunc saveConditionsFile() {\n\tf, err := os.Create(*conditionsFilePath)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to open conditions file %s for writing. %v\", *conditionsFilePath)\n\t\treturn\n\t}\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tcontents, err := json.Marshal(conds)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to marshal conditions. %v\", conds)\n\t\treturn\n\t}\n\tf.Write(contents)\n\tf.Close()\n\tlog.Printf(\"Saved conditions file %s\", *conditionsFilePath)\n}\n\nvar locations = make(map[string]*Location)\nvar mu sync.Mutex \/\/ for conds and errs\nvar conds = make(map[string]*Conditions)\nvar errs []*Error\n\ntype ByRating []*Conditions\n\nfunc (r ByRating) Len() int      { return len(r) }\nfunc (r ByRating) Swap(i, j int) { r[i], r[j] = r[j], r[i] }\nfunc (r ByRating) Less(i, j int) bool {\n\tci := r[i]\n\tcj := r[j]\n\tif ci.Rating == cj.Rating {\n\t\treturn ci.Loc.Name < cj.Loc.Name\n\t}\n\treturn ci.Rating > cj.Rating\n}\n\nvar starSectionRx = regexp.MustCompile(`<ul class=\"rating rating-large clearfix\">.*?<\/ul>`)\nvar starRx = regexp.MustCompile(`<li class=\"active\"> *<i class=\"glyphicon glyphicon-star\"><\/i> *<\/li>`)\nvar heightRx = regexp.MustCompile(`(\\d+(?:-\\d+)?)<small>ft`)\nvar reportRx = regexp.MustCompile(`\/[^\"\/]+-Surf-Report\/\\d+\/`)\n\nfunc (loc *Location) GetConditions(client *http.Client) (*Conditions, error) {\n\turl := \"http:\/\/magicseaweed.com\" + loc.MagicSeaweedPath\n\tlog.Printf(\"Fetching %s\", url)\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to read body. %v\", err)\n\t}\n\trating := countTopStars(body)\n\thMatch := heightRx.FindSubmatch(body)\n\tif len(hMatch) != 2 {\n\t\treturn nil, fmt.Errorf(\"Wave height regex failed.\")\n\t}\n\tdetails := fmt.Sprintf(\"%s ft\", hMatch[1])\n\tcond := &Conditions{\n\t\tLoc:     loc,\n\t\tRating:  rating,\n\t\tDetails: details,\n\t}\n\treturn cond, nil\n}\n\n\/\/ countTopStars returns the number of stars in the first rating section on the page.\nfunc countTopStars(body []byte) int {\n\tstarSection := starSectionRx.Find(body)\n\tfoundStars := starRx.FindAll(starSection, -1)\n\treturn len(foundStars)\n}\n\nfunc (c *Conditions) Stars() string {\n\trunes := make([]rune, 0, 5)\n\tfor i := 0; i < c.Rating; i++ {\n\t\trunes = append(runes, '★')\n\t}\n\tfor i := 0; i < 5-c.Rating; i++ {\n\t\trunes = append(runes, '☆')\n\t}\n\treturn string(runes)\n}\n\nfunc keepConditionsUpdated() {\n\tupdateConditionsAllLocations()\n\ttick := time.Tick(*conditionsInterval)\n\tfor {\n\t\t<-tick\n\t\tupdateConditionsAllLocations()\n\t}\n}\n<commit_msg>Move some code around.<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"html\"\n\t\"html\/template\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar addr = flag.String(\"addr\", \":4089\", \"Server address\")\nvar timeout = flag.Duration(\"timeout\", 5*time.Second, \"Timeout for HTTP GETs\")\nvar conditionsInterval = flag.Duration(\"conditions_interval\", 10*time.Minute, \"Interval between updating conditions\")\nvar siteMapUrl = flag.String(\"site_map_url\", \"http:\/\/magicseaweed.com\/site-map.php\", \"URL of the site map\")\nvar conditionsFilePath = flag.String(\"conditions_file\", \"conditions.json\", \"Path to file with conditions cache\")\nvar conditionsPeriod = flag.Duration(\"conditions_period\", 10*time.Second, \"How often to save the conditions file\")\nvar help = flag.Bool(\"h\", false, \"Show help message\")\n\nfunc main() {\n\tflag.Parse()\n\tif *help {\n\t\tflag.Usage()\n\t\tos.Exit(0)\n\t}\n\tloadConditionsFile()\n\thttp.HandleFunc(\"\/\", handleRoot)\n\thttp.HandleFunc(\"\/errors\", handleErrors)\n\tgo keepConditionsUpdated()\n\tlog.Printf(\"Listening on %s\", *addr)\n\tlog.Fatal(http.ListenAndServe(*addr, nil))\n}\n\nvar head = template.HTML(`\n\t<head>\n\t\t<title>Waveguide<\/title>\n\t\t<style>\n\t\t\tbody {\n\t\t\t\tfont-family: monospace;\n\t\t\t}\n\t\t\ttable {\n\t\t\t\tborder-collapse: separate;\n\t\t\t\tfont-size: 12pt;\n\t\t\t}\n\t\t\tth {\n\t\t\t\ttext-align: left;\n\t\t\t}\n\t\t\tth, td {\n\t\t\t\tpadding: 0 1em 0.5ex 0;\n\t\t\t}\n\t\t<\/style>\n\t<\/head>\n`)\n\nvar errsTmpl = template.Must(template.New(\"errs\").Parse(`\n<html>\n{{.Head}}\n\t<body>\n\t\t<b>Errors<\/b>:\n\t\t<table>\n\t\t\t{{range .Errs}}\n\t\t\t<tr>\n\t\t\t\t<td><a href=\"http:\/\/magicseaweed.com{{.Loc.MagicSeaweedPath}}\">{{.Loc.HTMLName}}<\/a><\/td>\n\t\t\t\t<td>{{.Err}}<\/td>\n\t\t\t<\/tr>\n\t\t\t{{end}}\n\t\t<\/table>\n\t<\/body>\n<\/html>\n`))\n\nvar tmpl = template.Must(template.New(\"main\").Parse(`\n<html>\n{{.Head}}\n\t<body>\n\t\t{{if .Conds}}\n\t\t<table>\n\t\t\t<thead>\n\t\t\t\t<th>Location<\/th>\n\t\t\t\t<th>Conditions<\/th>\n\t\t\t\t<th>Wave Height<\/th>\n\t\t\t<\/thead>\n\t\t\t<tbody>\n\t\t\t\t{{range .Conds}}\n\t\t\t\t<tr>\n\t\t\t\t\t<td><a href=\"http:\/\/magicseaweed.com{{.Loc.MagicSeaweedPath}}\">{{.Loc.HTMLName}}<\/a><\/td>\n\t\t\t\t\t<td>{{.Stars}}<\/td>\n\t\t\t\t\t<td>{{.Details}}<\/td>\n\t\t\t\t<\/tr>\n\t\t\t\t{{end}}\n\t\t\t<\/tbody>\n\t\t<\/table>\n\t\t{{end}}\n\t<\/body>\n<\/html>\n`))\n\ntype Location struct {\n\tName             string\n\tMagicSeaweedPath string\n}\n\nfunc (loc *Location) HTMLName() template.HTML {\n\treturn template.HTML(loc.Name)\n}\n\ntype Conditions struct {\n\tLoc     *Location\n\tRating  int\n\tDetails string\n}\n\ntype Error struct {\n\tLoc *Location\n\tErr error\n}\n\nfunc handleErrors(w http.ResponseWriter, r *http.Request) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tdata := struct {\n\t\tErrs []*Error\n\t\tHead template.HTML\n\t}{\n\t\tErrs: errs,\n\t\tHead: head,\n\t}\n\terr := errsTmpl.Execute(w, data)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to execute template. %v\", err)\n\t}\n}\n\nfunc handleRoot(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Sort conditions by rating and name.\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tconds2 := make([]*Conditions, 0, len(conds))\n\tfor _, c := range conds {\n\t\tconds2 = append(conds2, c)\n\t}\n\tsort.Sort(ByRating(conds2))\n\n\t\/\/ Render the results.\n\tdata := struct {\n\t\tConds []*Conditions\n\t\tHead  template.HTML\n\t}{Conds: conds2, Head: head}\n\terr := tmpl.Execute(w, data)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to execute template. %v\", err)\n\t}\n}\n\nfunc updateConditionsAllLocations() {\n\tclient := &http.Client{Timeout: *timeout}\n\n\t\/\/ Gather locations.\n\tlog.Printf(\"Fetching %s\", *siteMapUrl)\n\tresp, err := client.Get(*siteMapUrl)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to get site map. %v\", err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to read response body of site map. %v\", err)\n\t}\n\treportMatches := reportRx.FindAll(body, -1)\n\tfor _, match := range reportMatches {\n\t\tpath := string(match)\n\t\tname, err := surfReportPathToName(path)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to convert surf report path to name. %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\t_, ok := locations[name]\n\t\tif !ok {\n\t\t\tlog.Printf(\"Got new location: %s: %s\", name, path)\n\t\t}\n\t\tloc := &Location{\n\t\t\tName:             name,\n\t\t\tMagicSeaweedPath: path,\n\t\t}\n\t\tlocations[name] = loc\n\t}\n\tlog.Printf(\"Found %d reports\", len(reportMatches))\n\tlog.Printf(\"New number of locations: %d\", len(locations))\n\n\t\/\/ Gather conditions and errors.\n\tmu.Lock()\n\terrs = make([]*Error, 0, len(locations))\n\tmu.Unlock()\n\tfor _, loc := range locations {\n\t\tcond, err := loc.GetConditions(client)\n\t\tif err != nil {\n\t\t\tmu.Lock()\n\t\t\te := &Error{\n\t\t\t\tLoc: loc,\n\t\t\t\tErr: err,\n\t\t\t}\n\t\t\terrs = append(errs, e)\n\t\t\tmu.Unlock()\n\t\t\tcontinue\n\t\t}\n\t\tmu.Lock()\n\t\tconds[loc.Name] = cond\n\t\tmu.Unlock()\n\t\tsaveConditionsFile()\n\t}\n}\n\nfunc loadConditionsFile() {\n\tf, err := os.Open(*conditionsFilePath)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to open conditions file %s. %v. That's okay.\", *conditionsFilePath, err)\n\t\treturn\n\t}\n\tcontents, err := ioutil.ReadAll(f)\n\terr = json.Unmarshal(contents, &conds)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to unmarshall the conditions map. %v\", err)\n\t\tos.Exit(1)\n\t}\n\tlog.Printf(\"Loaded conditions file %s\", *conditionsFilePath)\n}\n\nfunc saveConditionsFile() {\n\tf, err := os.Create(*conditionsFilePath)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to open conditions file %s for writing. %v\", *conditionsFilePath)\n\t\treturn\n\t}\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tcontents, err := json.Marshal(conds)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to marshal conditions. %v\", conds)\n\t\treturn\n\t}\n\tf.Write(contents)\n\tf.Close()\n\tlog.Printf(\"Saved conditions file %s\", *conditionsFilePath)\n}\n\nvar locations = make(map[string]*Location)\nvar mu sync.Mutex \/\/ for conds and errs\nvar conds = make(map[string]*Conditions)\nvar errs []*Error\n\ntype ByRating []*Conditions\n\nfunc (r ByRating) Len() int      { return len(r) }\nfunc (r ByRating) Swap(i, j int) { r[i], r[j] = r[j], r[i] }\nfunc (r ByRating) Less(i, j int) bool {\n\tci := r[i]\n\tcj := r[j]\n\tif ci.Rating == cj.Rating {\n\t\treturn ci.Loc.Name < cj.Loc.Name\n\t}\n\treturn ci.Rating > cj.Rating\n}\n\nvar starSectionRx = regexp.MustCompile(`<ul class=\"rating rating-large clearfix\">.*?<\/ul>`)\nvar starRx = regexp.MustCompile(`<li class=\"active\"> *<i class=\"glyphicon glyphicon-star\"><\/i> *<\/li>`)\nvar heightRx = regexp.MustCompile(`(\\d+(?:-\\d+)?)<small>ft`)\nvar reportRx = regexp.MustCompile(`\/[^\"\/]+-Surf-Report\/\\d+\/`)\nvar srpTailRx = regexp.MustCompile(`-Surf-Report\/\\d+\/`)\n\nfunc surfReportPathToName(srp string) (string, error) {\n\ts := srpTailRx.ReplaceAllString(srp, \"\")\n\ts, err := url.PathUnescape(s)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Failed to unescape path in surfReportPathToName(%q). %v\", srp, err)\n\t}\n\ts = html.UnescapeString(s)\n\ts = s[1:] \/\/ Remove leading \/\n\ts = strings.Replace(s, \"-\", \" \", -1)\n\treturn s, nil\n}\n\nfunc (loc *Location) GetConditions(client *http.Client) (*Conditions, error) {\n\turl := \"http:\/\/magicseaweed.com\" + loc.MagicSeaweedPath\n\tlog.Printf(\"Fetching %s\", url)\n\tresp, err := client.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to read body. %v\", err)\n\t}\n\trating := countTopStars(body)\n\thMatch := heightRx.FindSubmatch(body)\n\tif len(hMatch) != 2 {\n\t\treturn nil, fmt.Errorf(\"Wave height regex failed.\")\n\t}\n\tdetails := fmt.Sprintf(\"%s ft\", hMatch[1])\n\tcond := &Conditions{\n\t\tLoc:     loc,\n\t\tRating:  rating,\n\t\tDetails: details,\n\t}\n\treturn cond, nil\n}\n\n\/\/ countTopStars returns the number of stars in the first rating section on the page.\nfunc countTopStars(body []byte) int {\n\tstarSection := starSectionRx.Find(body)\n\tfoundStars := starRx.FindAll(starSection, -1)\n\treturn len(foundStars)\n}\n\nfunc (c *Conditions) Stars() string {\n\trunes := make([]rune, 0, 5)\n\tfor i := 0; i < c.Rating; i++ {\n\t\trunes = append(runes, '★')\n\t}\n\tfor i := 0; i < 5-c.Rating; i++ {\n\t\trunes = append(runes, '☆')\n\t}\n\treturn string(runes)\n}\n\nfunc keepConditionsUpdated() {\n\tupdateConditionsAllLocations()\n\ttick := time.Tick(*conditionsInterval)\n\tfor {\n\t\t<-tick\n\t\tupdateConditionsAllLocations()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 tsuru-autoscale authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage web\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/ajg\/form\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/tsuru\/tsuru-autoscale\/action\"\n\t\"github.com\/tsuru\/tsuru-autoscale\/alarm\"\n\t\"github.com\/tsuru\/tsuru-autoscale\/datasource\"\n)\n\nfunc alarmHandler(w http.ResponseWriter, r *http.Request) error {\n\ta, err := alarm.FindAlarmBy(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn render(w, \"web\/templates\/alarm\/list.html\", a)\n}\n\nfunc alarmDetailHandler(w http.ResponseWriter, r *http.Request) error {\n\tvars := mux.Vars(r)\n\ta, err := alarm.FindAlarmByName(vars[\"name\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\tds, err := datasource.FindBy(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tactions, err := action.All()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontext := struct {\n\t\tDataSources []datasource.DataSource\n\t\tActions     []action.Action\n\t\tAlarm       *alarm.Alarm\n\t}{\n\t\tds,\n\t\tactions,\n\t\ta,\n\t}\n\treturn render(w, \"web\/templates\/alarm\/detail.html\", context)\n}\n\nfunc alarmAdd(w http.ResponseWriter, r *http.Request) error {\n\tif r.Method == http.MethodPost {\n\t\terr := r.ParseForm()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tds := []string{}\n\t\tfor _, d := range r.Form[\"datasources\"] {\n\t\t\tds = append(ds, d)\n\t\t}\n\t\tr.Form.Del(\"datasources\")\n\t\tenvs := map[string]string{}\n\t\tfor i := range r.Form[\"key\"] {\n\t\t\tif r.Form[\"key\"][i] != \"\" {\n\t\t\t\tenvs[r.Form[\"key\"][i]] = r.Form[\"value\"][i]\n\t\t\t}\n\t\t}\n\t\tr.Form.Del(\"key\")\n\t\tr.Form.Del(\"value\")\n\t\tactions := []string{}\n\t\tfor _, a := range r.Form[\"actions\"] {\n\t\t\tactions = append(actions, a)\n\t\t}\n\t\tr.Form.Del(\"actions\")\n\t\tvar a alarm.Alarm\n\t\td := form.NewDecoder(nil)\n\t\td.IgnoreCase(true)\n\t\td.IgnoreUnknownKeys(true)\n\t\terr = d.DecodeValues(&a, r.Form)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ta.DataSources = ds\n\t\ta.Actions = actions\n\t\ta.Envs = envs\n\t\terr = alarm.NewAlarm(&a)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttp.Redirect(w, r, \"\/web\/alarm\", 302)\n\t\treturn nil\n\t}\n\tds, err := datasource.FindBy(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tactions, err := action.All()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontext := struct {\n\t\tDataSources []datasource.DataSource\n\t\tActions     []action.Action\n\t}{\n\t\tds,\n\t\tactions,\n\t}\n\treturn render(w, \"web\/templates\/alarm\/add.html\", context)\n}\n\nfunc alarmRemove(w http.ResponseWriter, r *http.Request) error {\n\tvars := mux.Vars(r)\n\ta, err := alarm.FindAlarmByName(vars[\"name\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = alarm.RemoveAlarm(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttp.Redirect(w, r, \"\/web\/alarm\", 302)\n\treturn nil\n}\n\nfunc alarmEnable(w http.ResponseWriter, r *http.Request) error {\n\tvars := mux.Vars(r)\n\ta, err := alarm.FindAlarmByName(vars[\"name\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = alarm.Enable(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttp.Redirect(w, r, fmt.Sprintf(\"\/web\/alarm\/%s\", vars[\"name\"]), 302)\n\treturn nil\n}\n\nfunc alarmDisable(w http.ResponseWriter, r *http.Request) error {\n\tvars := mux.Vars(r)\n\ta, err := alarm.FindAlarmByName(vars[\"name\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = alarm.Disable(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttp.Redirect(w, r, fmt.Sprintf(\"\/web\/alarm\/%s\", vars[\"name\"]), 302)\n\treturn nil\n}\n\nfunc alarmEdit(w http.ResponseWriter, r *http.Request) error {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\treturn err\n\t}\n\tds := []string{}\n\tfor _, d := range r.Form[\"datasources\"] {\n\t\tds = append(ds, d)\n\t}\n\tr.Form.Del(\"datasources\")\n\tenvs := map[string]string{}\n\tfor i := range r.Form[\"key\"] {\n\t\tif r.Form[\"key\"][i] != \"\" {\n\t\t\tenvs[r.Form[\"key\"][i]] = r.Form[\"value\"][i]\n\t\t}\n\t}\n\tr.Form.Del(\"key\")\n\tr.Form.Del(\"value\")\n\tactions := []string{}\n\tfor _, a := range r.Form[\"actions\"] {\n\t\tactions = append(actions, a)\n\t}\n\tr.Form.Del(\"actions\")\n\td := form.NewDecoder(nil)\n\td.IgnoreCase(true)\n\td.IgnoreUnknownKeys(true)\n\tvar a alarm.Alarm\n\terr = d.DecodeValues(&a, r.Form)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.DataSources = ds\n\ta.Actions = actions\n\ta.Envs = envs\n\toldAlarm, err := alarm.FindAlarmByName(a.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.Instance = oldAlarm.Instance\n\terr = alarm.UpdateAlarm(&a)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttp.Redirect(w, r, \"\/web\/alarm\", 302)\n\treturn nil\n}\n<commit_msg>web\/alarm: edit redirect to the alarm page<commit_after>\/\/ Copyright 2016 tsuru-autoscale authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage web\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/ajg\/form\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/tsuru\/tsuru-autoscale\/action\"\n\t\"github.com\/tsuru\/tsuru-autoscale\/alarm\"\n\t\"github.com\/tsuru\/tsuru-autoscale\/datasource\"\n)\n\nfunc alarmHandler(w http.ResponseWriter, r *http.Request) error {\n\ta, err := alarm.FindAlarmBy(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn render(w, \"web\/templates\/alarm\/list.html\", a)\n}\n\nfunc alarmDetailHandler(w http.ResponseWriter, r *http.Request) error {\n\tvars := mux.Vars(r)\n\ta, err := alarm.FindAlarmByName(vars[\"name\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\tds, err := datasource.FindBy(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tactions, err := action.All()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontext := struct {\n\t\tDataSources []datasource.DataSource\n\t\tActions     []action.Action\n\t\tAlarm       *alarm.Alarm\n\t}{\n\t\tds,\n\t\tactions,\n\t\ta,\n\t}\n\treturn render(w, \"web\/templates\/alarm\/detail.html\", context)\n}\n\nfunc alarmAdd(w http.ResponseWriter, r *http.Request) error {\n\tif r.Method == http.MethodPost {\n\t\terr := r.ParseForm()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tds := []string{}\n\t\tfor _, d := range r.Form[\"datasources\"] {\n\t\t\tds = append(ds, d)\n\t\t}\n\t\tr.Form.Del(\"datasources\")\n\t\tenvs := map[string]string{}\n\t\tfor i := range r.Form[\"key\"] {\n\t\t\tif r.Form[\"key\"][i] != \"\" {\n\t\t\t\tenvs[r.Form[\"key\"][i]] = r.Form[\"value\"][i]\n\t\t\t}\n\t\t}\n\t\tr.Form.Del(\"key\")\n\t\tr.Form.Del(\"value\")\n\t\tactions := []string{}\n\t\tfor _, a := range r.Form[\"actions\"] {\n\t\t\tactions = append(actions, a)\n\t\t}\n\t\tr.Form.Del(\"actions\")\n\t\tvar a alarm.Alarm\n\t\td := form.NewDecoder(nil)\n\t\td.IgnoreCase(true)\n\t\td.IgnoreUnknownKeys(true)\n\t\terr = d.DecodeValues(&a, r.Form)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ta.DataSources = ds\n\t\ta.Actions = actions\n\t\ta.Envs = envs\n\t\terr = alarm.NewAlarm(&a)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttp.Redirect(w, r, \"\/web\/alarm\", 302)\n\t\treturn nil\n\t}\n\tds, err := datasource.FindBy(nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tactions, err := action.All()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontext := struct {\n\t\tDataSources []datasource.DataSource\n\t\tActions     []action.Action\n\t}{\n\t\tds,\n\t\tactions,\n\t}\n\treturn render(w, \"web\/templates\/alarm\/add.html\", context)\n}\n\nfunc alarmRemove(w http.ResponseWriter, r *http.Request) error {\n\tvars := mux.Vars(r)\n\ta, err := alarm.FindAlarmByName(vars[\"name\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = alarm.RemoveAlarm(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttp.Redirect(w, r, \"\/web\/alarm\", 302)\n\treturn nil\n}\n\nfunc alarmEnable(w http.ResponseWriter, r *http.Request) error {\n\tvars := mux.Vars(r)\n\ta, err := alarm.FindAlarmByName(vars[\"name\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = alarm.Enable(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttp.Redirect(w, r, fmt.Sprintf(\"\/web\/alarm\/%s\", vars[\"name\"]), 302)\n\treturn nil\n}\n\nfunc alarmDisable(w http.ResponseWriter, r *http.Request) error {\n\tvars := mux.Vars(r)\n\ta, err := alarm.FindAlarmByName(vars[\"name\"])\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = alarm.Disable(a)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttp.Redirect(w, r, fmt.Sprintf(\"\/web\/alarm\/%s\", vars[\"name\"]), 302)\n\treturn nil\n}\n\nfunc alarmEdit(w http.ResponseWriter, r *http.Request) error {\n\terr := r.ParseForm()\n\tif err != nil {\n\t\treturn err\n\t}\n\tds := []string{}\n\tfor _, d := range r.Form[\"datasources\"] {\n\t\tds = append(ds, d)\n\t}\n\tr.Form.Del(\"datasources\")\n\tenvs := map[string]string{}\n\tfor i := range r.Form[\"key\"] {\n\t\tif r.Form[\"key\"][i] != \"\" {\n\t\t\tenvs[r.Form[\"key\"][i]] = r.Form[\"value\"][i]\n\t\t}\n\t}\n\tr.Form.Del(\"key\")\n\tr.Form.Del(\"value\")\n\tactions := []string{}\n\tfor _, a := range r.Form[\"actions\"] {\n\t\tactions = append(actions, a)\n\t}\n\tr.Form.Del(\"actions\")\n\td := form.NewDecoder(nil)\n\td.IgnoreCase(true)\n\td.IgnoreUnknownKeys(true)\n\tvar a alarm.Alarm\n\terr = d.DecodeValues(&a, r.Form)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.DataSources = ds\n\ta.Actions = actions\n\ta.Envs = envs\n\toldAlarm, err := alarm.FindAlarmByName(a.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.Instance = oldAlarm.Instance\n\terr = alarm.UpdateAlarm(&a)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu := fmt.Sprintf(\"\/web\/alarm\/%s\", a.Name)\n\thttp.Redirect(w, r, u, 302)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\/pkg\/config\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\/pkg\/require\"\n\tdeploycmds \"github.com\/pachyderm\/pachyderm\/src\/server\/pkg\/deploy\/cmds\"\n\tapi \"k8s.io\/kubernetes\/pkg\/api\/v1\"\n)\n\nfunc TestMetricsNormalDeployment(t *testing.T) {\n\t\/\/ Run deploy normally, should see METRICS=true\n\ttestDeploy(t, false, false, true)\n}\n\nfunc TestMetricsNormalDeploymentNoMetricsFlagSet(t *testing.T) {\n\t\/\/ Run deploy normally, should see METRICS=true\n\ttestDeploy(t, false, true, false)\n}\n\nfunc TestMetricsDevDeployment(t *testing.T) {\n\t\/\/ Run deploy w dev flag, should see METRICS=false\n\ttestDeploy(t, true, false, false)\n}\n\nfunc TestMetricsDevDeploymentNoMetricsFlagSet(t *testing.T) {\n\t\/\/ Run deploy w dev flag, should see METRICS=false\n\ttestDeploy(t, true, true, false)\n}\n\nfunc testDeploy(t *testing.T, devFlag bool, noMetrics bool, expectedEnvValue bool) {\n\n\t\/\/ Setup user config prior to test\n\t\/\/ So that stdout only contains JSON no warnings\n\t_, err := config.Read()\n\trequire.NoError(t, err)\n\n\tfmt.Printf(\"running testDeploy: dev %v, nometrics %v, expectedval %v\\n\", devFlag, noMetrics, expectedEnvValue)\n\told := os.Stdout\n\tr, w, _ := os.Pipe()\n\tos.Stdout = w\n\n\tos.Args = []string{\n\t\t\"deploy\",\n\t\t\"local\",\n\t\t\"--dry-run\",\n\t\tfmt.Sprintf(\"-d=%v\", devFlag),\n\t}\n\t\/\/ the noMetrics flag is defined globally, so is undefined on just this command\n\t\/\/ but we can pass it in directly to the command:\n\terr = deploycmds.DeployCmd(!noMetrics).Execute()\n\trequire.NoError(t, err)\n\trequire.NoError(t, w.Close())\n\t\/\/ restore stdout\n\tos.Stdout = old\n\n\tb := make([]byte, 100000)\n\tn, err := r.Read(b)\n\tb = b[0:n]\n\tjsonReader := bytes.NewBuffer(b)\n\tfmt.Printf(\"got result [%v]\\n\", string(b))\n\n\tdecoder := json.NewDecoder(jsonReader)\n\tfoundPachdManifest := false\n\t\/\/ Loop through generated manifest until we find a\n\t\/\/ ReplicationController (limit of 100 makes sure test\n\t\/\/ fails quickly if there is no RC)\n\tfor i := 0; i < 100; i++ {\n\t\tvar manifest *api.ReplicationController\n\t\terr = decoder.Decode(&manifest)\n\t\tif err == io.EOF {\n\t\t\tfmt.Printf(\"got EOF\\n\")\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\t\/\/ Not a replication controller\n\t\t\tfmt.Printf(\"Got error decoding: %v\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\trequire.NoError(t, err)\n\t\tfmt.Printf(\"this manifest obj: %v\\n\", manifest)\n\t\tfmt.Printf(\"this name: %v\\n\", manifest.ObjectMeta.Name)\n\t\tfmt.Printf(\"this kind: %v\\n\\n\", manifest.Kind)\n\t\tif manifest.ObjectMeta.Name == \"pachd\" && manifest.Kind == \"ReplicationController\" {\n\t\t\tfoundPachdManifest = true\n\t\t\texpectedMetricEnvVar := api.EnvVar{\n\t\t\t\tName:  \"METRICS\",\n\t\t\t\tValue: fmt.Sprintf(\"%v\", expectedEnvValue),\n\t\t\t}\n\t\t\tvar env []interface{}\n\t\t\trequire.Equal(t, 1, len(manifest.Spec.Template.Spec.Containers))\n\t\t\tfor _, value := range manifest.Spec.Template.Spec.Containers[0].Env {\n\t\t\t\tenv = append(env, value)\n\t\t\t}\n\t\t\trequire.OneOfEquals(t, interface{}(expectedMetricEnvVar), env)\n\t\t}\n\t}\n\trequire.Equal(t, true, foundPachdManifest)\n}\n<commit_msg>Remove debug statements<commit_after>package cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\/pkg\/config\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\/pkg\/require\"\n\tdeploycmds \"github.com\/pachyderm\/pachyderm\/src\/server\/pkg\/deploy\/cmds\"\n\tapi \"k8s.io\/kubernetes\/pkg\/api\/v1\"\n)\n\nfunc TestMetricsNormalDeployment(t *testing.T) {\n\t\/\/ Run deploy normally, should see METRICS=true\n\ttestDeploy(t, false, false, true)\n}\n\nfunc TestMetricsNormalDeploymentNoMetricsFlagSet(t *testing.T) {\n\t\/\/ Run deploy normally, should see METRICS=true\n\ttestDeploy(t, false, true, false)\n}\n\nfunc TestMetricsDevDeployment(t *testing.T) {\n\t\/\/ Run deploy w dev flag, should see METRICS=false\n\ttestDeploy(t, true, false, false)\n}\n\nfunc TestMetricsDevDeploymentNoMetricsFlagSet(t *testing.T) {\n\t\/\/ Run deploy w dev flag, should see METRICS=false\n\ttestDeploy(t, true, true, false)\n}\n\nfunc testDeploy(t *testing.T, devFlag bool, noMetrics bool, expectedEnvValue bool) {\n\n\t\/\/ Setup user config prior to test\n\t\/\/ So that stdout only contains JSON no warnings\n\t_, err := config.Read()\n\trequire.NoError(t, err)\n\n\told := os.Stdout\n\tr, w, _ := os.Pipe()\n\tos.Stdout = w\n\n\tos.Args = []string{\n\t\t\"deploy\",\n\t\t\"local\",\n\t\t\"--dry-run\",\n\t\tfmt.Sprintf(\"-d=%v\", devFlag),\n\t}\n\t\/\/ the noMetrics flag is defined globally, so is undefined on just this command\n\t\/\/ but we can pass it in directly to the command:\n\terr = deploycmds.DeployCmd(!noMetrics).Execute()\n\trequire.NoError(t, err)\n\trequire.NoError(t, w.Close())\n\t\/\/ restore stdout\n\tos.Stdout = old\n\n\tdecoder := json.NewDecoder(r)\n\tfoundPachdManifest := false\n\t\/\/ Loop through generated manifest until we find a\n\t\/\/ ReplicationController (limit of 100 makes sure test\n\t\/\/ fails quickly if there is no RC)\n\tfor i := 0; i < 100; i++ {\n\t\tvar manifest *api.ReplicationController\n\t\terr = decoder.Decode(&manifest)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\t\/\/ Not a replication controller\n\t\t\tcontinue\n\t\t}\n\t\trequire.NoError(t, err)\n\t\tif manifest.ObjectMeta.Name == \"pachd\" && manifest.Kind == \"ReplicationController\" {\n\t\t\tfoundPachdManifest = true\n\t\t\texpectedMetricEnvVar := api.EnvVar{\n\t\t\t\tName:  \"METRICS\",\n\t\t\t\tValue: fmt.Sprintf(\"%v\", expectedEnvValue),\n\t\t\t}\n\t\t\tvar env []interface{}\n\t\t\trequire.Equal(t, 1, len(manifest.Spec.Template.Spec.Containers))\n\t\t\tfor _, value := range manifest.Spec.Template.Spec.Containers[0].Env {\n\t\t\t\tenv = append(env, value)\n\t\t\t}\n\t\t\trequire.OneOfEquals(t, interface{}(expectedMetricEnvVar), env)\n\t\t}\n\t}\n\trequire.Equal(t, true, foundPachdManifest)\n}\n<|endoftext|>"}
{"text":"<commit_before>package query\n\nimport \"strings\"\n\n\/\/ Token represents a lexical token.\ntype Token int\n\nconst (\n\tILLEGAL Token = iota \/\/ Illegal tokens\n\tEOF                  \/\/ End-of-file\n\tWS                   \/\/ Whitespace\n\tCOLON                \/\/ ;\n\n\t\/\/ Search terms\n\tSTRING \/\/ search fields terms\n\n\tkeywordBeg\n\n\tAND \/\/ AND boolean\n\tOR  \/\/ OR boolean\n\tNOT \/\/ NOT boolean\n\n\tkeywordEnd\n\n\tLPAREN \/\/ (\n\tRPAREN \/\/ )\n\n)\n\nvar tokens = [...]string{\n\tILLEGAL: \"ILLEGAL\",\n\tEOF:     \"EOF\",\n\tWS:      \"WS\",\n\tCOLON:   \":\",\n\n\tAND: \"AND\",\n\tOR:  \"OR\",\n\tNOT: \"NOT\",\n\n\tLPAREN: \"(\",\n\tRPAREN: \")\",\n}\n\nvar keywords map[string]Token\n\nfunc init() {\n\tkeywords = make(map[string]Token)\n\tfor tok := keywordBeg + 1; tok < keywordEnd; tok++ {\n\t\tkeywords[strings.ToLower(tokens[tok])] = tok\n\t}\n\tfor _, tok := range []Token{AND, OR} {\n\t\tkeywords[strings.ToLower(tokens[tok])] = tok\n\t}\n}\n\nfunc (t Token) isOperator() bool {\n\treturn t == AND || t == OR || t == NOT\n}\n\n\/\/ String returns the string representation of the token.\nfunc (t Token) String() string {\n\tif t >= 0 && t < Token(len(tokens)) {\n\t\treturn tokens[t]\n\t}\n\treturn \"\"\n}\n\n\/\/ Precedence returns the operator precedence of the binary operator token.\nfunc (t Token) Precedence() int {\n\tswitch t {\n\tcase OR:\n\t\treturn 1\n\tcase AND:\n\t\treturn 2\n\tcase NOT:\n\t\treturn 3\n\t}\n\treturn 0\n}\n\n\/\/ Lookup returns the token associated with a given string.\nfunc Lookup(ident string) (Token, bool) {\n\tif tok, ok := keywords[strings.ToLower(ident)]; ok {\n\t\treturn tok, true\n\t}\n\treturn ILLEGAL, false\n}\n\n\/\/ tokstr returns a literal if provided, otherwise returns the token string.\nfunc tokstr(t Token, lit string) string {\n\tif lit != \"\" {\n\t\treturn lit\n\t}\n\treturn t.String()\n}\n<commit_msg>Minor linting<commit_after>package query\n\nimport \"strings\"\n\n\/\/ Token represents a lexical token.\ntype Token int\n\nconst (\n\tILLEGAL Token = iota \/\/ Illegal tokens\n\tEOF                  \/\/ End-of-file\n\tWS                   \/\/ Whitespace\n\tCOLON                \/\/ ;\n\n\t\/\/ STRING represents search terms\n\tSTRING \/\/ search fields terms\n\n\tkeywordBeg\n\n\tAND \/\/ AND boolean\n\tOR  \/\/ OR boolean\n\tNOT \/\/ NOT boolean\n\n\tkeywordEnd\n\n\tLPAREN \/\/ (\n\tRPAREN \/\/ )\n\n)\n\nvar tokens = [...]string{\n\tILLEGAL: \"ILLEGAL\",\n\tEOF:     \"EOF\",\n\tWS:      \"WS\",\n\tCOLON:   \":\",\n\n\tAND: \"AND\",\n\tOR:  \"OR\",\n\tNOT: \"NOT\",\n\n\tLPAREN: \"(\",\n\tRPAREN: \")\",\n}\n\nvar keywords map[string]Token\n\nfunc init() {\n\tkeywords = make(map[string]Token)\n\tfor tok := keywordBeg + 1; tok < keywordEnd; tok++ {\n\t\tkeywords[strings.ToLower(tokens[tok])] = tok\n\t}\n\tfor _, tok := range []Token{AND, OR} {\n\t\tkeywords[strings.ToLower(tokens[tok])] = tok\n\t}\n}\n\nfunc (t Token) isOperator() bool {\n\treturn t == AND || t == OR || t == NOT\n}\n\n\/\/ String returns the string representation of the token.\nfunc (t Token) String() string {\n\tif t >= 0 && t < Token(len(tokens)) {\n\t\treturn tokens[t]\n\t}\n\treturn \"\"\n}\n\n\/\/ Precedence returns the operator precedence of the binary operator token.\nfunc (t Token) Precedence() int {\n\tswitch t {\n\tcase OR:\n\t\treturn 1\n\tcase AND:\n\t\treturn 2\n\tcase NOT:\n\t\treturn 3\n\t}\n\treturn 0\n}\n\n\/\/ Lookup returns the token associated with a given string.\nfunc Lookup(ident string) (Token, bool) {\n\tif tok, ok := keywords[strings.ToLower(ident)]; ok {\n\t\treturn tok, true\n\t}\n\treturn ILLEGAL, false\n}\n\n\/\/ tokstr returns a literal if provided, otherwise returns the token string.\nfunc tokstr(t Token, lit string) string {\n\tif lit != \"\" {\n\t\treturn lit\n\t}\n\treturn t.String()\n}\n<|endoftext|>"}
{"text":"<commit_before>package queue\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/satori\/go.uuid\"\n)\n\n\/\/ Local implements Interface as an in-memory queue.\n\/\/\n\/\/ No guarantees are made about performance or efficiency.\ntype Local struct {\n\tqueue         []string\n\tqueueMutex    *sync.Mutex\n\tmessages      map[string][]byte\n\tmessagesMutex *sync.RWMutex\n\treceived      map[string]*time.Timer\n\treceivedMutex *sync.RWMutex\n}\n\n\/\/ NewLocal initializes and returns a Local in-memory queue.\nfunc NewLocal() *Local {\n\treturn &Local{\n\t\tqueue:         []string{},\n\t\tqueueMutex:    &sync.Mutex{},\n\t\tmessages:      map[string][]byte{},\n\t\tmessagesMutex: &sync.RWMutex{},\n\t\treceived:      map[string]*time.Timer{},\n\t\treceivedMutex: &sync.RWMutex{},\n\t}\n}\n\n\/\/ SendMessage adds a message to the end of the queue.\nfunc (l *Local) SendMessage(message []byte) error {\n\tvar id string\n\tl.messagesMutex.Lock()\n\t\/\/ make sure id is truly unique; usually this loop should always finish\n\t\/\/ after the first iteration, but better to be safe than sorry\n\tfor {\n\t\tid = uuid.NewV4().String()\n\t\tif _, ok := l.messages[id]; !ok {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.messages[id] = message\n\tl.messagesMutex.Unlock()\n\tl.queueMutex.Lock()\n\tl.queue = append(l.queue, id)\n\tl.queueMutex.Unlock()\n\treturn nil\n}\n\n\/\/ ReceiveMessage receives a message from the head of the queue.\n\/\/\n\/\/ A timeout of 0 (or less) will cause the message to be removed from the queue\n\/\/ immediately.\n\/\/\n\/\/ A positive timeout will cause the message to appear back at the head of the\n\/\/ queue once the timeout expires. The returned id should be passed to DeleteMessage\n\/\/ once the message is processed to remove it from the queue.\nfunc (l *Local) ReceiveMessage(timeout time.Duration) (id string, message []byte, err error) {\n\tl.queueMutex.Lock()\n\tif len(l.queue) == 0 {\n\t\terr = ErrNoMessages\n\t\tl.queueMutex.Unlock()\n\t\treturn\n\t}\n\tl.messagesMutex.RLock()\n\t\/\/ skip\/remove any messages that ended up back in the queue after a timeout\n\t\/\/ but were subsequently deleted\n\tfor {\n\t\tid, l.queue = l.queue[0], l.queue[1:]\n\t\tvar ok bool\n\t\tif message, ok = l.messages[id]; ok {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.messagesMutex.RUnlock()\n\tl.queueMutex.Unlock()\n\n\tif timeout < 1 {\n\t\t\/\/ delete the message immediately; no need to set timer\n\t\tl.messagesMutex.Lock()\n\t\tdelete(l.messages, id)\n\t\tl.messagesMutex.Unlock()\n\t\treturn\n\t}\n\n\tl.receivedMutex.Lock()\n\tl.received[id] = time.AfterFunc(timeout, func() {\n\t\tl.queueMutex.Lock()\n\t\tl.queue = append([]string{id}, l.queue...)\n\t\tl.queueMutex.Unlock()\n\n\t\tl.receivedMutex.Lock()\n\t\tdelete(l.received, id)\n\t\tl.receivedMutex.Unlock()\n\t})\n\tl.receivedMutex.Unlock()\n\n\treturn\n}\n\n\/\/ DeleteMessage removes the message with the passed id from the queue. An invalid\n\/\/ id (or one for a message that has already been deleted) results in a no-op.\nfunc (l *Local) DeleteMessage(id string) error {\n\tl.receivedMutex.Lock()\n\ttimer, ok := l.received[id]\n\tif ok {\n\t\ttimer.Stop()\n\t\tdelete(l.received, id)\n\t}\n\tl.receivedMutex.Unlock()\n\tl.messagesMutex.Lock()\n\tdelete(l.messages, id)\n\tl.messagesMutex.Unlock()\n\treturn nil\n}\n<commit_msg>Queue: Handle timer corner case<commit_after>package queue\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/satori\/go.uuid\"\n)\n\n\/\/ Local implements Interface as an in-memory queue.\n\/\/\n\/\/ No guarantees are made about performance or efficiency.\ntype Local struct {\n\tqueue         []string\n\tqueueMutex    *sync.Mutex\n\tmessages      map[string][]byte\n\tmessagesMutex *sync.RWMutex\n\treceived      map[string]*time.Timer\n\treceivedMutex *sync.RWMutex\n}\n\n\/\/ NewLocal initializes and returns a Local in-memory queue.\nfunc NewLocal() *Local {\n\treturn &Local{\n\t\tqueue:         []string{},\n\t\tqueueMutex:    &sync.Mutex{},\n\t\tmessages:      map[string][]byte{},\n\t\tmessagesMutex: &sync.RWMutex{},\n\t\treceived:      map[string]*time.Timer{},\n\t\treceivedMutex: &sync.RWMutex{},\n\t}\n}\n\n\/\/ SendMessage adds a message to the end of the queue.\nfunc (l *Local) SendMessage(message []byte) error {\n\tvar id string\n\tl.messagesMutex.Lock()\n\t\/\/ make sure id is truly unique; usually this loop should always finish\n\t\/\/ after the first iteration, but better to be safe than sorry\n\tfor {\n\t\tid = uuid.NewV4().String()\n\t\tif _, ok := l.messages[id]; !ok {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.messages[id] = message\n\tl.messagesMutex.Unlock()\n\tl.queueMutex.Lock()\n\tl.queue = append(l.queue, id)\n\tl.queueMutex.Unlock()\n\treturn nil\n}\n\n\/\/ ReceiveMessage receives a message from the head of the queue.\n\/\/\n\/\/ A timeout of 0 (or less) will cause the message to be removed from the queue\n\/\/ immediately.\n\/\/\n\/\/ A positive timeout will cause the message to appear back at the head of the\n\/\/ queue once the timeout expires. The returned id should be passed to DeleteMessage\n\/\/ once the message is processed to remove it from the queue.\nfunc (l *Local) ReceiveMessage(timeout time.Duration) (id string, message []byte, err error) {\n\tl.queueMutex.Lock()\n\tif len(l.queue) == 0 {\n\t\terr = ErrNoMessages\n\t\tl.queueMutex.Unlock()\n\t\treturn\n\t}\n\tl.messagesMutex.RLock()\n\t\/\/ skip\/remove any messages that ended up back in the queue after a timeout\n\t\/\/ but were subsequently deleted\n\tfor {\n\t\tid, l.queue = l.queue[0], l.queue[1:]\n\t\tvar ok bool\n\t\tif message, ok = l.messages[id]; ok {\n\t\t\tbreak\n\t\t}\n\t}\n\tl.messagesMutex.RUnlock()\n\tl.queueMutex.Unlock()\n\n\tif timeout < 1 {\n\t\t\/\/ delete the message immediately; no need to set timer\n\t\tl.messagesMutex.Lock()\n\t\tdelete(l.messages, id)\n\t\tl.messagesMutex.Unlock()\n\t\treturn\n\t}\n\n\tl.receivedMutex.Lock()\n\tl.received[id] = time.AfterFunc(timeout, func() {\n\t\tl.queueMutex.Lock()\n\t\tl.queue = append([]string{id}, l.queue...)\n\t\tl.queueMutex.Unlock()\n\n\t\tl.receivedMutex.Lock()\n\t\tdelete(l.received, id)\n\t\tl.receivedMutex.Unlock()\n\t})\n\tl.receivedMutex.Unlock()\n\n\treturn\n}\n\n\/\/ DeleteMessage removes the message with the passed id from the queue. An invalid\n\/\/ id (or one for a message that has already been deleted) results in a no-op.\nfunc (l *Local) DeleteMessage(id string) error {\n\tl.receivedMutex.Lock()\n\ttimer, ok := l.received[id]\n\tif ok {\n\t\tif !timer.Stop() {\n\t\t\tselect {\n\t\t\tcase <-timer.C:\n\t\t\tdefault:\n\t\t\t}\n\t\t}\n\t\tdelete(l.received, id)\n\t}\n\tl.receivedMutex.Unlock()\n\n\tl.messagesMutex.Lock()\n\tdelete(l.messages, id)\n\tl.messagesMutex.Unlock()\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package v2\n\nimport (\n\t\"os\"\n\n\t\"code.cloudfoundry.org\/cli\/cf\/cmd\"\n\t\"code.cloudfoundry.org\/cli\/command\"\n\t\"code.cloudfoundry.org\/cli\/command\/flag\"\n)\n\ntype PushCommand struct {\n\tAppPorts             string                      `long:\"app-ports\" description:\"Comma delimited list of ports the application may listen on\" hidden:\"true\"` \/\/TODO: Custom AppPorts flag\n\tBuildpackName        string                      `short:\"b\" description:\"Custom buildpack by name (e.g. my-buildpack) or Git URL (e.g. 'https:\/\/github.com\/cloudfoundry\/java-buildpack.git') or Git URL with a branch or tag (e.g. 'https:\/\/github.com\/cloudfoundry\/java-buildpack.git#v3.3.0' for 'v3.3.0' tag). To use built-in buildpacks only, specify 'default' or 'null'\"`\n\tStartupCommand       string                      `short:\"c\" description:\"Startup command, set to null to reset to default start command\"`\n\tDomain               string                      `short:\"d\" description:\"Domain (e.g. example.com)\"`\n\tDockerImage          string                      `long:\"docker-image\" short:\"o\" description:\"Docker-image to be used (e.g. user\/docker-image-name)\"`\n\tDockerUsername       string                      `long:\"docker-username\" description:\"Repository username; used with password from environment variable CF_DOCKER_PASSWORD\"`\n\tPathToManifest       flag.PathWithExistenceCheck `short:\"f\" description:\"Path to manifest\"`\n\tHealthCheckType      flag.HealthCheckType        `long:\"health-check-type\" short:\"u\" description:\"Application health check type (Default: 'port', 'none' accepted for 'process', 'http' implies endpoint '\/')\"`\n\tHostname             string                      `long:\"hostname\" short:\"n\" description:\"Hostname (e.g. my-subdomain)\"`\n\tNumInstances         int                         `short:\"i\" description:\"Number of instances\"`\n\tDiskLimit            string                      `short:\"k\" description:\"Disk limit (e.g. 256M, 1024M, 1G)\"`\n\tMemoryLimit          string                      `short:\"m\" description:\"Memory limit (e.g. 256M, 1024M, 1G)\"`\n\tNoHostname           bool                        `long:\"no-hostname\" description:\"Map the root domain to this app\"`\n\tNoManifest           bool                        `long:\"no-manifest\" description:\"Ignore manifest file\"`\n\tNoRoute              bool                        `long:\"no-route\" description:\"Do not map a route to this app and remove routes from previous pushes of this app\"`\n\tNoStart              bool                        `long:\"no-start\" description:\"Do not start an app after pushing\"`\n\tDirectoryPath        flag.PathWithExistenceCheck `short:\"p\" description:\"Path to app directory or to a zip file of the contents of the app directory\"`\n\tRandomRoute          bool                        `long:\"random-route\" description:\"Create a random route for this app\"`\n\tRoutePath            string                      `long:\"route-path\" description:\"Path for the route\"`\n\tStack                string                      `short:\"s\" description:\"Stack to use (a stack is a pre-built file system, including an operating system, that can run apps)\"`\n\tApplicationStartTime int                         `short:\"t\" description:\"Time (in seconds) allowed to elapse between starting up an app and the first healthy response from the app\"`\n\tusage                interface{}                 `usage:\"cf push APP_NAME [-b BUILDPACK_NAME] [-c COMMAND] [-f MANIFEST_PATH | --no-manifest] [--no-start]\\n   [-i NUM_INSTANCES] [-k DISK] [-m MEMORY] [-p PATH] [-s STACK] [-t HEALTH_TIMEOUT] [-u (process | port | http)]\\n   [--no-route | --random-route | --hostname HOST | --no-hostname] [-d DOMAIN] [--route-path ROUTE_PATH]\\n\\n   cf push APP_NAME --docker-image [REGISTRY_HOST:PORT\/]IMAGE[:TAG] [--docker-username USERNAME]\\n   [-c COMMAND] [-f MANIFEST_PATH | --no-manifest] [--no-start]\\n   [-i NUM_INSTANCES] [-k DISK] [-m MEMORY] [-t HEALTH_TIMEOUT] [-u (process | port | http)]\\n   [--no-route | --random-route | --hostname HOST | --no-hostname] [-d DOMAIN] [--route-path ROUTE_PATH]\\n\\n   cf push -f MANIFEST_WITH_MULTIPLE_APPS_PATH [--no-start]\"`\n\tenvCFStagingTimeout  interface{}                 `environmentName:\"CF_STAGING_TIMEOUT\" environmentDescription:\"Max wait time for buildpack staging, in minutes\" environmentDefault:\"15\"`\n\tenvCFStartupTimeout  interface{}                 `environmentName:\"CF_STARTUP_TIMEOUT\" environmentDescription:\"Max wait time for app instance startup, in minutes\" environmentDefault:\"5\"`\n\tdockerPassword       interface{}                 `environmentName:\"CF_DOCKER_PASSWORD\" environmentDescription:\"Password used for private docker repository\"`\n\trelatedCommands      interface{}                 `related_commands:\"apps, create-app-manifest, logs, ssh, start\"`\n}\n\nfunc (_ PushCommand) Setup(config command.Config, ui command.UI) error {\n\treturn nil\n}\n\nfunc (_ PushCommand) Execute(args []string) error {\n\tcmd.Main(os.Getenv(\"CF_TRACE\"), os.Args)\n\treturn nil\n}\n<commit_msg>added RequiredArgs  AppName to PushCommmand struct<commit_after>package v2\n\nimport (\n\t\"os\"\n\n\t\"code.cloudfoundry.org\/cli\/cf\/cmd\"\n\t\"code.cloudfoundry.org\/cli\/command\"\n\t\"code.cloudfoundry.org\/cli\/command\/flag\"\n)\n\ntype PushCommand struct {\n\tRequiredArgs         flag.AppName                `positional-args:\"yes\"`\n\tAppPorts             string                      `long:\"app-ports\" description:\"Comma delimited list of ports the application may listen on\" hidden:\"true\"` \/\/TODO: Custom AppPorts flag\n\tBuildpackName        string                      `short:\"b\" description:\"Custom buildpack by name (e.g. my-buildpack) or Git URL (e.g. 'https:\/\/github.com\/cloudfoundry\/java-buildpack.git') or Git URL with a branch or tag (e.g. 'https:\/\/github.com\/cloudfoundry\/java-buildpack.git#v3.3.0' for 'v3.3.0' tag). To use built-in buildpacks only, specify 'default' or 'null'\"`\n\tStartupCommand       string                      `short:\"c\" description:\"Startup command, set to null to reset to default start command\"`\n\tDomain               string                      `short:\"d\" description:\"Domain (e.g. example.com)\"`\n\tDockerImage          string                      `long:\"docker-image\" short:\"o\" description:\"Docker-image to be used (e.g. user\/docker-image-name)\"`\n\tDockerUsername       string                      `long:\"docker-username\" description:\"Repository username; used with password from environment variable CF_DOCKER_PASSWORD\"`\n\tPathToManifest       flag.PathWithExistenceCheck `short:\"f\" description:\"Path to manifest\"`\n\tHealthCheckType      flag.HealthCheckType        `long:\"health-check-type\" short:\"u\" description:\"Application health check type (Default: 'port', 'none' accepted for 'process', 'http' implies endpoint '\/')\"`\n\tHostname             string                      `long:\"hostname\" short:\"n\" description:\"Hostname (e.g. my-subdomain)\"`\n\tNumInstances         int                         `short:\"i\" description:\"Number of instances\"`\n\tDiskLimit            string                      `short:\"k\" description:\"Disk limit (e.g. 256M, 1024M, 1G)\"`\n\tMemoryLimit          string                      `short:\"m\" description:\"Memory limit (e.g. 256M, 1024M, 1G)\"`\n\tNoHostname           bool                        `long:\"no-hostname\" description:\"Map the root domain to this app\"`\n\tNoManifest           bool                        `long:\"no-manifest\" description:\"Ignore manifest file\"`\n\tNoRoute              bool                        `long:\"no-route\" description:\"Do not map a route to this app and remove routes from previous pushes of this app\"`\n\tNoStart              bool                        `long:\"no-start\" description:\"Do not start an app after pushing\"`\n\tDirectoryPath        flag.PathWithExistenceCheck `short:\"p\" description:\"Path to app directory or to a zip file of the contents of the app directory\"`\n\tRandomRoute          bool                        `long:\"random-route\" description:\"Create a random route for this app\"`\n\tRoutePath            string                      `long:\"route-path\" description:\"Path for the route\"`\n\tStack                string                      `short:\"s\" description:\"Stack to use (a stack is a pre-built file system, including an operating system, that can run apps)\"`\n\tApplicationStartTime int                         `short:\"t\" description:\"Time (in seconds) allowed to elapse between starting up an app and the first healthy response from the app\"`\n\tusage                interface{}                 `usage:\"cf push APP_NAME [-b BUILDPACK_NAME] [-c COMMAND] [-f MANIFEST_PATH | --no-manifest] [--no-start]\\n   [-i NUM_INSTANCES] [-k DISK] [-m MEMORY] [-p PATH] [-s STACK] [-t HEALTH_TIMEOUT] [-u (process | port | http)]\\n   [--no-route | --random-route | --hostname HOST | --no-hostname] [-d DOMAIN] [--route-path ROUTE_PATH]\\n\\n   cf push APP_NAME --docker-image [REGISTRY_HOST:PORT\/]IMAGE[:TAG] [--docker-username USERNAME]\\n   [-c COMMAND] [-f MANIFEST_PATH | --no-manifest] [--no-start]\\n   [-i NUM_INSTANCES] [-k DISK] [-m MEMORY] [-t HEALTH_TIMEOUT] [-u (process | port | http)]\\n   [--no-route | --random-route | --hostname HOST | --no-hostname] [-d DOMAIN] [--route-path ROUTE_PATH]\\n\\n   cf push -f MANIFEST_WITH_MULTIPLE_APPS_PATH [--no-start]\"`\n\tenvCFStagingTimeout  interface{}                 `environmentName:\"CF_STAGING_TIMEOUT\" environmentDescription:\"Max wait time for buildpack staging, in minutes\" environmentDefault:\"15\"`\n\tenvCFStartupTimeout  interface{}                 `environmentName:\"CF_STARTUP_TIMEOUT\" environmentDescription:\"Max wait time for app instance startup, in minutes\" environmentDefault:\"5\"`\n\tdockerPassword       interface{}                 `environmentName:\"CF_DOCKER_PASSWORD\" environmentDescription:\"Password used for private docker repository\"`\n\trelatedCommands      interface{}                 `related_commands:\"apps, create-app-manifest, logs, ssh, start\"`\n}\n\nfunc (_ PushCommand) Setup(config command.Config, ui command.UI) error {\n\treturn nil\n}\n\nfunc (_ PushCommand) Execute(args []string) error {\n\tcmd.Main(os.Getenv(\"CF_TRACE\"), os.Args)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package activitystreams provides all the basic ActivityStreams\n\/\/ implementation needed for Write.as.\npackage activitystreams\n\nimport (\n\t\"time\"\n)\n\nconst (\n\tNamespace = \"https:\/\/www.w3.org\/ns\/activitystreams\"\n\ttoPublic  = \"https:\/\/www.w3.org\/ns\/activitystreams#Public\"\n)\n\nvar Extensions = map[string]string{\n\t\"sc\":              \"http:\/\/schema.org#\",\n\t\"commentsEnabled\": \"sc:Boolean\",\n}\n\n\/\/ Activity describes actions that have either already occurred, are in the\n\/\/ process of occurring, or may occur in the future.\ntype Activity struct {\n\tBaseObject\n\tActor     string    `json:\"actor\"`\n\tPublished time.Time `json:\"published,omitempty\"`\n\tTo        []string  `json:\"to,omitempty\"`\n\tCC        []string  `json:\"cc,omitempty\"`\n\tObject    *Object   `json:\"object\"`\n}\n\ntype FollowActivity struct {\n\tBaseObject\n\tActor     string    `json:\"actor\"`\n\tPublished time.Time `json:\"published,omitempty\"`\n\tTo        []string  `json:\"to,omitempty\"`\n\tCC        []string  `json:\"cc,omitempty\"`\n\tObject    string    `json:\"object\"`\n}\n\n\/\/ NewCreateActivity builds a basic Create activity that includes the given\n\/\/ Object and the Object's AttributedTo property as the Actor.\nfunc NewCreateActivity(o *Object) *Activity {\n\ta := Activity{\n\t\tBaseObject: BaseObject{\n\t\t\tContext: []interface{}{\n\t\t\t\tNamespace,\n\t\t\t\tExtensions,\n\t\t\t},\n\t\t\tID:   o.ID,\n\t\t\tType: \"Create\",\n\t\t},\n\t\tActor:     o.AttributedTo,\n\t\tObject:    o,\n\t\tPublished: o.Published,\n\t}\n\treturn &a\n}\n\n\/\/ NewUpdateActivity builds a basic Update activity that includes the given\n\/\/ Object and the Object's AttributedTo property as the Actor.\nfunc NewUpdateActivity(o *Object) *Activity {\n\ta := Activity{\n\t\tBaseObject: BaseObject{\n\t\t\tContext: []interface{}{\n\t\t\t\tNamespace,\n\t\t\t\tExtensions,\n\t\t\t},\n\t\t\tID:   o.ID,\n\t\t\tType: \"Update\",\n\t\t},\n\t\tActor:     o.AttributedTo,\n\t\tObject:    o,\n\t\tPublished: o.Published,\n\t}\n\treturn &a\n}\n\n\/\/ NewDeleteActivity builds a basic Delete activity that includes the given\n\/\/ Object and the Object's AttributedTo property as the Actor.\nfunc NewDeleteActivity(o *Object) *Activity {\n\ta := Activity{\n\t\tBaseObject: BaseObject{\n\t\t\tContext: []interface{}{\n\t\t\t\tNamespace,\n\t\t\t},\n\t\t\tID:   o.ID,\n\t\t\tType: \"Delete\",\n\t\t},\n\t\tActor:  o.AttributedTo,\n\t\tObject: o,\n\t}\n\treturn &a\n}\n\n\/\/ NewFollowActivity builds a basic Follow activity.\nfunc NewFollowActivity(actorIRI, followeeIRI string) *FollowActivity {\n\ta := FollowActivity{\n\t\tBaseObject: BaseObject{\n\t\t\tContext: []interface{}{\n\t\t\t\tNamespace,\n\t\t\t},\n\t\t\tType: \"Follow\",\n\t\t},\n\t\tActor:  actorIRI,\n\t\tObject: followeeIRI,\n\t}\n\treturn &a\n}\n\n\/\/ Object is the primary base type for the Activity Streams vocabulary.\ntype Object struct {\n\tBaseObject\n\tPublished    time.Time         `json:\"published\"`\n\tSummary      *string           `json:\"summary,omitempty\"`\n\tInReplyTo    *string           `json:\"inReplyTo\"`\n\tURL          string            `json:\"url\"`\n\tAttributedTo string            `json:\"attributedTo\"`\n\tTo           []string          `json:\"to\"`\n\tCC           []string          `json:\"cc,omitempty\"`\n\tName         string            `json:\"name,omitempty\"`\n\tContent      string            `json:\"content\"`\n\tContentMap   map[string]string `json:\"contentMap,omitempty\"`\n\tTag          []Tag             `json:\"tag\"`\n\n\t\/\/ Extensions\n\tCommentsEnabled bool `json:\"commentsEnabled\"`\n}\n\n\/\/ NewNoteObject creates a basic Note object that includes the public\n\/\/ namespace in IRIs it's addressed to.\nfunc NewNoteObject() *Object {\n\to := Object{\n\t\tBaseObject: BaseObject{\n\t\t\tType: \"Note\",\n\t\t},\n\t\tTo: []string{\n\t\t\ttoPublic,\n\t\t},\n\t}\n\treturn &o\n}\n\n\/\/ NewArticleObject creates a basic Article object that includes the public\n\/\/ namespace in IRIs it's addressed to.\nfunc NewArticleObject() *Object {\n\to := Object{\n\t\tBaseObject: BaseObject{\n\t\t\tType: \"Article\",\n\t\t},\n\t\tTo: []string{\n\t\t\ttoPublic,\n\t\t},\n\t}\n\treturn &o\n}\n<commit_msg>Remove commentsEnabled AP extension<commit_after>\/\/ Package activitystreams provides all the basic ActivityStreams\n\/\/ implementation needed for Write.as.\npackage activitystreams\n\nimport (\n\t\"time\"\n)\n\nconst (\n\tNamespace = \"https:\/\/www.w3.org\/ns\/activitystreams\"\n\ttoPublic  = \"https:\/\/www.w3.org\/ns\/activitystreams#Public\"\n)\n\nvar Extensions = map[string]string{}\n\n\/\/ Activity describes actions that have either already occurred, are in the\n\/\/ process of occurring, or may occur in the future.\ntype Activity struct {\n\tBaseObject\n\tActor     string    `json:\"actor\"`\n\tPublished time.Time `json:\"published,omitempty\"`\n\tTo        []string  `json:\"to,omitempty\"`\n\tCC        []string  `json:\"cc,omitempty\"`\n\tObject    *Object   `json:\"object\"`\n}\n\ntype FollowActivity struct {\n\tBaseObject\n\tActor     string    `json:\"actor\"`\n\tPublished time.Time `json:\"published,omitempty\"`\n\tTo        []string  `json:\"to,omitempty\"`\n\tCC        []string  `json:\"cc,omitempty\"`\n\tObject    string    `json:\"object\"`\n}\n\n\/\/ NewCreateActivity builds a basic Create activity that includes the given\n\/\/ Object and the Object's AttributedTo property as the Actor.\nfunc NewCreateActivity(o *Object) *Activity {\n\ta := Activity{\n\t\tBaseObject: BaseObject{\n\t\t\tContext: []interface{}{\n\t\t\t\tNamespace,\n\t\t\t\tExtensions,\n\t\t\t},\n\t\t\tID:   o.ID,\n\t\t\tType: \"Create\",\n\t\t},\n\t\tActor:     o.AttributedTo,\n\t\tObject:    o,\n\t\tPublished: o.Published,\n\t}\n\treturn &a\n}\n\n\/\/ NewUpdateActivity builds a basic Update activity that includes the given\n\/\/ Object and the Object's AttributedTo property as the Actor.\nfunc NewUpdateActivity(o *Object) *Activity {\n\ta := Activity{\n\t\tBaseObject: BaseObject{\n\t\t\tContext: []interface{}{\n\t\t\t\tNamespace,\n\t\t\t\tExtensions,\n\t\t\t},\n\t\t\tID:   o.ID,\n\t\t\tType: \"Update\",\n\t\t},\n\t\tActor:     o.AttributedTo,\n\t\tObject:    o,\n\t\tPublished: o.Published,\n\t}\n\treturn &a\n}\n\n\/\/ NewDeleteActivity builds a basic Delete activity that includes the given\n\/\/ Object and the Object's AttributedTo property as the Actor.\nfunc NewDeleteActivity(o *Object) *Activity {\n\ta := Activity{\n\t\tBaseObject: BaseObject{\n\t\t\tContext: []interface{}{\n\t\t\t\tNamespace,\n\t\t\t},\n\t\t\tID:   o.ID,\n\t\t\tType: \"Delete\",\n\t\t},\n\t\tActor:  o.AttributedTo,\n\t\tObject: o,\n\t}\n\treturn &a\n}\n\n\/\/ NewFollowActivity builds a basic Follow activity.\nfunc NewFollowActivity(actorIRI, followeeIRI string) *FollowActivity {\n\ta := FollowActivity{\n\t\tBaseObject: BaseObject{\n\t\t\tContext: []interface{}{\n\t\t\t\tNamespace,\n\t\t\t},\n\t\t\tType: \"Follow\",\n\t\t},\n\t\tActor:  actorIRI,\n\t\tObject: followeeIRI,\n\t}\n\treturn &a\n}\n\n\/\/ Object is the primary base type for the Activity Streams vocabulary.\ntype Object struct {\n\tBaseObject\n\tPublished    time.Time         `json:\"published\"`\n\tSummary      *string           `json:\"summary,omitempty\"`\n\tInReplyTo    *string           `json:\"inReplyTo\"`\n\tURL          string            `json:\"url\"`\n\tAttributedTo string            `json:\"attributedTo\"`\n\tTo           []string          `json:\"to\"`\n\tCC           []string          `json:\"cc,omitempty\"`\n\tName         string            `json:\"name,omitempty\"`\n\tContent      string            `json:\"content\"`\n\tContentMap   map[string]string `json:\"contentMap,omitempty\"`\n\tTag          []Tag             `json:\"tag\"`\n\n\t\/\/ Extensions\n\t\/\/ NOTE: add extensions here\n}\n\n\/\/ NewNoteObject creates a basic Note object that includes the public\n\/\/ namespace in IRIs it's addressed to.\nfunc NewNoteObject() *Object {\n\to := Object{\n\t\tBaseObject: BaseObject{\n\t\t\tType: \"Note\",\n\t\t},\n\t\tTo: []string{\n\t\t\ttoPublic,\n\t\t},\n\t}\n\treturn &o\n}\n\n\/\/ NewArticleObject creates a basic Article object that includes the public\n\/\/ namespace in IRIs it's addressed to.\nfunc NewArticleObject() *Object {\n\to := Object{\n\t\tBaseObject: BaseObject{\n\t\t\tType: \"Article\",\n\t\t},\n\t\tTo: []string{\n\t\t\ttoPublic,\n\t\t},\n\t}\n\treturn &o\n}\n<|endoftext|>"}
{"text":"<commit_before>package slack\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"net\/url\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/websocket\"\n)\n\nconst (\n\tEV_MESSAGE = iota\n\tEV_USER_TYPING\n)\n\ntype SlackWS struct {\n\tconn      *websocket.Conn\n\tmessageId int\n\tmutex     sync.Mutex\n\tSlack\n}\n\nvar portMapping = map[string]string{\"ws\": \"80\", \"wss\": \"443\"}\n\nfunc fixUrlPort(orig string) (string, error) {\n\turlObj, err := url.ParseRequestURI(orig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t_, _, err = net.SplitHostPort(urlObj.Host)\n\tif err != nil {\n\t\treturn urlObj.Scheme + \":\/\/\" + urlObj.Host + \":\" + portMapping[urlObj.Scheme] + urlObj.Path, nil\n\t}\n\treturn orig, nil\n}\n\nfunc (api *Slack) StartRTM(protocol, origin string) (*SlackWS, error) {\n\tresponse := &infoResponseFull{}\n\terr := parseResponse(\"rtm.start\", url.Values{\"token\": {api.config.token}}, response, api.debug)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !response.Ok {\n\t\treturn nil, errors.New(response.Error)\n\t}\n\tapi.info = response.Info\n\t\/\/ websocket.Dial does not accept url without the port (yet)\n\t\/\/ Fixed by: https:\/\/github.com\/golang\/net\/commit\/5058c78c3627b31e484a81463acd51c7cecc06f3\n\t\/\/ but slack returns the address with no port, so we have to fix it\n\tapi.info.Url, err = fixUrlPort(api.info.Url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tapi.config.protocol, api.config.origin = protocol, origin\n\twsApi := &SlackWS{Slack: *api}\n\twsApi.conn, err = websocket.Dial(api.info.Url, api.config.protocol, api.config.origin)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn wsApi, nil\n}\n\nfunc (api *SlackWS) Ping() error {\n\tapi.mutex.Lock()\n\tdefer api.mutex.Unlock()\n\tapi.messageId++\n\tmsg := &Ping{Id: api.messageId, Type: \"ping\"}\n\tif err := websocket.JSON.Send(api.conn, msg); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (api *SlackWS) Keepalive(interval time.Duration) {\n\tticker := time.NewTicker(interval)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif err := api.Ping(); err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (api *SlackWS) SendMessage(msg OutgoingMessage) error {\n\tif err := websocket.JSON.Send(api.conn, msg); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (api *SlackWS) HandleIncomingEvents(ch *chan SlackEvent) {\n\tevent := json.RawMessage{}\n\tfor {\n\t\tif err := websocket.JSON.Receive(api.conn, &event); err == io.EOF {\n\t\t\t\/\/log.Println(\"Derpi derp, should we destroy conn and start over?\")\n\t\t\t\/\/if err = api.StartRTM(); err != nil {\n\t\t\t\/\/\tlog.Fatal(err)\n\t\t\t\/\/}\n\t\t\t\/\/ should we reconnect here?\n\t\t\tif !api.conn.IsClientConn() {\n\t\t\t\tapi.conn, err = websocket.Dial(api.info.Url, api.config.protocol, api.config.origin)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Panic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ XXX: check for timeout and implement exponential backoff\n\t\t} else if err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\tif len(event) == 0 {\n\t\t\tlog.Println(\"Event Empty. WTF?\")\n\t\t} else {\n\t\t\tif api.debug {\n\t\t\t\tlog.Println(string(event[:]))\n\t\t\t}\n\t\t\thandleEvent(ch, event)\n\t\t}\n\t\ttime.Sleep(time.Millisecond * 500)\n\t}\n}\n\nfunc handleEvent(ch *chan SlackEvent, event json.RawMessage) {\n\tem := Event{}\n\terr := json.Unmarshal(event, &em)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tswitch em.Type {\n\tcase \"\":\n\t\t\/\/ try ok\n\t\tack := AckMessage{}\n\t\tif err = json.Unmarshal(event, &ack); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif ack.Ok {\n\t\t\tlog.Printf(\"Received an ok for: %d\", ack.ReplyTo)\n\t\t} else {\n\t\t\tlog.Println(event)\n\t\t\tlog.Println(\"XXX: ?\")\n\t\t}\n\tcase \"hello\":\n\t\treturn\n\tcase \"pong\":\n\t\t\/\/ XXX: Eventually check to which ping this matched with\n\t\t\/\/      Allows us to have stats about latency and what not\n\t\treturn\n\tcase \"presence_change\":\n\t\t\/\/log.Printf(\"`%s is %s`\\n\", info.GetUserById(event.PUserId).Name, event.Presence)\n\tcase \"message\":\n\t\thandleMessage(ch, event)\n\tcase \"channel_marked\":\n\t\tlog.Printf(\"XXX: To implement %s\", em)\n\tcase \"user_typing\":\n\t\thandleUserTyping(ch, event)\n\tdefault:\n\t\tlog.Println(\"XXX: \" + string(event))\n\t}\n}\n\nfunc handleUserTyping(ch *chan SlackEvent, event json.RawMessage) {\n\tmsg := UserTyping{}\n\tif err := json.Unmarshal(event, &msg); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t*ch <- SlackEvent{Type: EV_USER_TYPING, Data: msg}\n}\n\nfunc handleMessage(ch *chan SlackEvent, event json.RawMessage) {\n\tmsg := Message{}\n\terr := json.Unmarshal(event, &msg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t*ch <- SlackEvent{Type: EV_MESSAGE, Data: msg}\n}\n<commit_msg>Adjust SendMessage to take a pointer.<commit_after>package slack\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"net\/url\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/websocket\"\n)\n\nconst (\n\tEV_MESSAGE = iota\n\tEV_USER_TYPING\n)\n\ntype SlackWS struct {\n\tconn      *websocket.Conn\n\tmessageId int\n\tmutex     sync.Mutex\n\tSlack\n}\n\nvar portMapping = map[string]string{\"ws\": \"80\", \"wss\": \"443\"}\n\nfunc fixUrlPort(orig string) (string, error) {\n\turlObj, err := url.ParseRequestURI(orig)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t_, _, err = net.SplitHostPort(urlObj.Host)\n\tif err != nil {\n\t\treturn urlObj.Scheme + \":\/\/\" + urlObj.Host + \":\" + portMapping[urlObj.Scheme] + urlObj.Path, nil\n\t}\n\treturn orig, nil\n}\n\nfunc (api *Slack) StartRTM(protocol, origin string) (*SlackWS, error) {\n\tresponse := &infoResponseFull{}\n\terr := parseResponse(\"rtm.start\", url.Values{\"token\": {api.config.token}}, response, api.debug)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !response.Ok {\n\t\treturn nil, errors.New(response.Error)\n\t}\n\tapi.info = response.Info\n\t\/\/ websocket.Dial does not accept url without the port (yet)\n\t\/\/ Fixed by: https:\/\/github.com\/golang\/net\/commit\/5058c78c3627b31e484a81463acd51c7cecc06f3\n\t\/\/ but slack returns the address with no port, so we have to fix it\n\tapi.info.Url, err = fixUrlPort(api.info.Url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tapi.config.protocol, api.config.origin = protocol, origin\n\twsApi := &SlackWS{Slack: *api}\n\twsApi.conn, err = websocket.Dial(api.info.Url, api.config.protocol, api.config.origin)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn wsApi, nil\n}\n\nfunc (api *SlackWS) Ping() error {\n\tapi.mutex.Lock()\n\tdefer api.mutex.Unlock()\n\tapi.messageId++\n\tmsg := &Ping{Id: api.messageId, Type: \"ping\"}\n\tif err := websocket.JSON.Send(api.conn, msg); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (api *SlackWS) Keepalive(interval time.Duration) {\n\tticker := time.NewTicker(interval)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif err := api.Ping(); err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (api *SlackWS) SendMessage(msg *OutgoingMessage) error {\n\tif msg == nil {\n\t\treturn fmt.Errorf(\"Can't send a nil message\")\n\t}\n\n\tif err := websocket.JSON.Send(api.conn, *msg); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (api *SlackWS) HandleIncomingEvents(ch *chan SlackEvent) {\n\tevent := json.RawMessage{}\n\tfor {\n\t\tif err := websocket.JSON.Receive(api.conn, &event); err == io.EOF {\n\t\t\t\/\/log.Println(\"Derpi derp, should we destroy conn and start over?\")\n\t\t\t\/\/if err = api.StartRTM(); err != nil {\n\t\t\t\/\/\tlog.Fatal(err)\n\t\t\t\/\/}\n\t\t\t\/\/ should we reconnect here?\n\t\t\tif !api.conn.IsClientConn() {\n\t\t\t\tapi.conn, err = websocket.Dial(api.info.Url, api.config.protocol, api.config.origin)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Panic(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ XXX: check for timeout and implement exponential backoff\n\t\t} else if err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\tif len(event) == 0 {\n\t\t\tlog.Println(\"Event Empty. WTF?\")\n\t\t} else {\n\t\t\tif api.debug {\n\t\t\t\tlog.Println(string(event[:]))\n\t\t\t}\n\t\t\thandleEvent(ch, event)\n\t\t}\n\t\ttime.Sleep(time.Millisecond * 500)\n\t}\n}\n\nfunc handleEvent(ch *chan SlackEvent, event json.RawMessage) {\n\tem := Event{}\n\terr := json.Unmarshal(event, &em)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tswitch em.Type {\n\tcase \"\":\n\t\t\/\/ try ok\n\t\tack := AckMessage{}\n\t\tif err = json.Unmarshal(event, &ack); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif ack.Ok {\n\t\t\tlog.Printf(\"Received an ok for: %d\", ack.ReplyTo)\n\t\t} else {\n\t\t\tlog.Println(event)\n\t\t\tlog.Println(\"XXX: ?\")\n\t\t}\n\tcase \"hello\":\n\t\treturn\n\tcase \"pong\":\n\t\t\/\/ XXX: Eventually check to which ping this matched with\n\t\t\/\/      Allows us to have stats about latency and what not\n\t\treturn\n\tcase \"presence_change\":\n\t\t\/\/log.Printf(\"`%s is %s`\\n\", info.GetUserById(event.PUserId).Name, event.Presence)\n\tcase \"message\":\n\t\thandleMessage(ch, event)\n\tcase \"channel_marked\":\n\t\tlog.Printf(\"XXX: To implement %s\", em)\n\tcase \"user_typing\":\n\t\thandleUserTyping(ch, event)\n\tdefault:\n\t\tlog.Println(\"XXX: \" + string(event))\n\t}\n}\n\nfunc handleUserTyping(ch *chan SlackEvent, event json.RawMessage) {\n\tmsg := UserTyping{}\n\tif err := json.Unmarshal(event, &msg); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t*ch <- SlackEvent{Type: EV_USER_TYPING, Data: msg}\n}\n\nfunc handleMessage(ch *chan SlackEvent, event json.RawMessage) {\n\tmsg := Message{}\n\terr := json.Unmarshal(event, &msg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t*ch <- SlackEvent{Type: EV_MESSAGE, Data: msg}\n}\n<|endoftext|>"}
{"text":"<commit_before>package net\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\ntype JSONMapRequest map[string]interface{}\n\nfunc (json *JSONMapRequest) String() string {\n\treturn fmt.Sprintf(\"%#v\", *json)\n}\n\ntype JSONArrayRequest []interface{}\n\nfunc (json *JSONArrayRequest) String() string {\n\treturn fmt.Sprintf(\"%#v\", *json)\n}\n\nfunc bytesToInterface(jsonBytes []byte) (interface{}, error) {\n\tmapResult := &JSONMapRequest{}\n\terr := json.Unmarshal(jsonBytes, mapResult)\n\tif err == nil {\n\t\treturn mapResult, err\n\t}\n\n\tarrayResult := &JSONArrayRequest{}\n\terr = json.Unmarshal(jsonBytes, arrayResult)\n\treturn arrayResult, err\n}\n\nfunc RequestBodyMatcher(expectedBodyString string) RequestMatcher {\n\treturn func(request *http.Request) {\n\t\tbodyBytes, err := ioutil.ReadAll(request.Body)\n\t\tif err != nil {\n\t\t\tFail(fmt.Sprintf(\"Error reading request body: %s\", err))\n\t\t}\n\n\t\tactualBody, err := bytesToInterface(bodyBytes)\n\t\tif err != nil {\n\t\t\tFail(fmt.Sprintf(\"Error unmarshalling request\", err.Error()))\n\t\t}\n\n\t\texpectedBody, err := bytesToInterface([]byte(expectedBodyString))\n\t\tif err != nil {\n\t\t\tFail(fmt.Sprintf(\"Error unmarshalling expected json\", err.Error()))\n\t\t}\n\n\t\tExpect(expectedBody).To(Equal(actualBody), \"\\nEXPECTED: %s\\nACTUAL: %s\", expectedBody, actualBody)\n\t\tExpect(request.Header.Get(\"content-type\")).To(Equal(\"application\/json\"), \"Content Type was not application\/json.\")\n\t}\n}\n\nfunc RequestBodyMatcherWithContentType(expectedBody, expectedContentType string) RequestMatcher {\n\treturn func(request *http.Request) {\n\t\tbodyBytes, err := ioutil.ReadAll(request.Body)\n\t\tif err != nil {\n\t\t\tFail(fmt.Sprintf(\"Error reading request body: %s\", err))\n\t\t}\n\n\t\tactualBody := string(bodyBytes)\n\t\tExpect(RemoveWhiteSpaceFromBody(actualBody)).To(Equal(RemoveWhiteSpaceFromBody(expectedBody)), \"Body did not match.\")\n\n\t\tactualContentType := request.Header.Get(\"content-type\")\n\t\tExpect(actualContentType).To(Equal(expectedContentType), \"Content Type did not match.\")\n\t}\n}\n\nfunc RemoveWhiteSpaceFromBody(body string) string {\n\tbody = strings.Replace(body, \" \", \"\", -1)\n\tbody = strings.Replace(body, \"\\n\", \"\", -1)\n\tbody = strings.Replace(body, \"\\r\", \"\", -1)\n\tbody = strings.Replace(body, \"\\t\", \"\", -1)\n\treturn body\n}\n<commit_msg>GinkgoRecover() in goroutines<commit_after>package net\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\ntype JSONMapRequest map[string]interface{}\n\nfunc (json *JSONMapRequest) String() string {\n\treturn fmt.Sprintf(\"%#v\", *json)\n}\n\ntype JSONArrayRequest []interface{}\n\nfunc (json *JSONArrayRequest) String() string {\n\treturn fmt.Sprintf(\"%#v\", *json)\n}\n\nfunc bytesToInterface(jsonBytes []byte) (interface{}, error) {\n\tmapResult := &JSONMapRequest{}\n\terr := json.Unmarshal(jsonBytes, mapResult)\n\tif err == nil {\n\t\treturn mapResult, err\n\t}\n\n\tarrayResult := &JSONArrayRequest{}\n\terr = json.Unmarshal(jsonBytes, arrayResult)\n\treturn arrayResult, err\n}\n\nfunc RequestBodyMatcher(expectedBodyString string) RequestMatcher {\n\treturn func(request *http.Request) {\n\t\tdefer GinkgoRecover()\n\t\tbodyBytes, err := ioutil.ReadAll(request.Body)\n\t\tif err != nil {\n\t\t\tFail(fmt.Sprintf(\"Error reading request body: %s\", err))\n\t\t}\n\n\t\tactualBody, err := bytesToInterface(bodyBytes)\n\t\tif err != nil {\n\t\t\tFail(fmt.Sprintf(\"Error unmarshalling request\", err.Error()))\n\t\t}\n\n\t\texpectedBody, err := bytesToInterface([]byte(expectedBodyString))\n\t\tif err != nil {\n\t\t\tFail(fmt.Sprintf(\"Error unmarshalling expected json\", err.Error()))\n\t\t}\n\n\t\tExpect(expectedBody).To(Equal(actualBody), \"\\nEXPECTED: %s\\nACTUAL: %s\", expectedBody, actualBody)\n\t\tExpect(request.Header.Get(\"content-type\")).To(Equal(\"application\/json\"), \"Content Type was not application\/json.\")\n\t}\n}\n\nfunc RequestBodyMatcherWithContentType(expectedBody, expectedContentType string) RequestMatcher {\n\treturn func(request *http.Request) {\n\t\tdefer GinkgoRecover()\n\t\tbodyBytes, err := ioutil.ReadAll(request.Body)\n\t\tif err != nil {\n\t\t\tFail(fmt.Sprintf(\"Error reading request body: %s\", err))\n\t\t}\n\n\t\tactualBody := string(bodyBytes)\n\t\tExpect(RemoveWhiteSpaceFromBody(actualBody)).To(Equal(RemoveWhiteSpaceFromBody(expectedBody)), \"Body did not match.\")\n\n\t\tactualContentType := request.Header.Get(\"content-type\")\n\t\tExpect(actualContentType).To(Equal(expectedContentType), \"Content Type did not match.\")\n\t}\n}\n\nfunc RemoveWhiteSpaceFromBody(body string) string {\n\tbody = strings.Replace(body, \" \", \"\", -1)\n\tbody = strings.Replace(body, \"\\n\", \"\", -1)\n\tbody = strings.Replace(body, \"\\r\", \"\", -1)\n\tbody = strings.Replace(body, \"\\t\", \"\", -1)\n\treturn body\n}\n<|endoftext|>"}
{"text":"<commit_before>package yenc\n\nimport (\n\t\"bytes\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestDecoder(t *testing.T) {\n\tencoded, err := os.Open(\".\/test\/00000005.ntx\")\n\n\tif err != nil {\n\t\tt.Fatalf(\"could not begin test: ntx file not readable\")\n\t}\n\n\tunencoded, err := ioutil.ReadFile(\".\/test\/testfile.txt\")\n\n\tif err != nil {\n\t\tt.Fatalf(\"could not read unencoded test file\")\n\t}\n\n\tdecBytes, err := ioutil.ReadAll(NewReader(encoded))\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error reading decoded bytes: %v\", err)\n\t}\n\n\tif !bytes.Equal(decBytes, unencoded) {\n\t\tfmt.Println(hex.Dump(decBytes))\n\n\t\tdiff := getDiff(unencoded, decBytes)\n\t\tt.Errorf(\"Decoded bytes did not equal unencoded bytes. Diff was %d long; dec was %d long\", len(diff), len(decBytes))\n\t}\n}\n\nfunc BenchmarkDecoder(b *testing.B) {\n\tencoded, err := os.Open(\".\/test\/00000005.ntx\")\n\n\tif err != nil {\n\t\tb.Fatalf(\"could not begin test: ntx file not readable\")\n\t}\n\n\tbs, err := ioutil.ReadAll(encoded)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tbuf := bytes.NewBuffer(bs)\n\n\tempty := make([]byte, 2<<20)\n\n\tb.SetBytes(int64(len(bs)))\n\n\tfor i := 0; i < b.N; i++ {\n\t\tNewReader(buf).Read(empty)\n\t}\n}\n\nfunc getDiff(b1, b2 []byte) []byte {\n\tb1c := make([]byte, len(b1))\n\tcopy(b1c, b1)\n\n\tb2c := make([]byte, len(b2))\n\tcopy(b2c, b2)\n\n\tfor len(b1c) > 0 && len(b2c) > 0 && b1c[0] == b2c[0] {\n\t\tb1c = b1c[1:]\n\t\tb2c = b2c[1:]\n\t}\n\n\tif len(b1c) > 0 {\n\t\treturn b1c\n\t}\n\n\treturn b2c\n}\n<commit_msg>Make benchmark show actual performance and report errors<commit_after>package yenc\n\nimport (\n\t\"bytes\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestDecoder(t *testing.T) {\n\tencoded, err := os.Open(\".\/test\/00000005.ntx\")\n\n\tif err != nil {\n\t\tt.Fatalf(\"could not begin test: ntx file not readable\")\n\t}\n\n\tunencoded, err := ioutil.ReadFile(\".\/test\/testfile.txt\")\n\n\tif err != nil {\n\t\tt.Fatalf(\"could not read unencoded test file\")\n\t}\n\n\tdecBytes, err := ioutil.ReadAll(NewReader(encoded))\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error reading decoded bytes: %v\", err)\n\t}\n\n\tif !bytes.Equal(decBytes, unencoded) {\n\t\tfmt.Println(hex.Dump(decBytes))\n\n\t\tdiff := getDiff(unencoded, decBytes)\n\t\tt.Errorf(\"Decoded bytes did not equal unencoded bytes. Diff was %d long; dec was %d long\", len(diff), len(decBytes))\n\t}\n}\n\nfunc BenchmarkDecoder(b *testing.B) {\n\tencoded, err := ioutil.ReadFile(\".\/test\/00000005.ntx\")\n\n\tif err != nil {\n\t\tb.Fatalf(\"could not begin test: ntx file not readable\")\n\t}\n\n\tempty := make([]byte, 2<<20)\n\n\tb.SetBytes(int64(len(encoded)))\n\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\tbuf := bytes.NewReader(encoded)\n\t\t\tn, err := NewReader(buf).Read(empty)\n\n\t\t\tif err != nil && err != io.EOF {\n\t\t\t\tb.Fatal(err)\n\t\t\t}\n\t\t\tif n == 0 {\n\t\t\t\tb.Fatal(\"Didn't read anything\")\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc getDiff(b1, b2 []byte) []byte {\n\tb1c := make([]byte, len(b1))\n\tcopy(b1c, b1)\n\n\tb2c := make([]byte, len(b2))\n\tcopy(b2c, b2)\n\n\tfor len(b1c) > 0 && len(b2c) > 0 && b1c[0] == b2c[0] {\n\t\tb1c = b1c[1:]\n\t\tb2c = b2c[1:]\n\t}\n\n\tif len(b1c) > 0 {\n\t\treturn b1c\n\t}\n\n\treturn b2c\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build all integration\n\npackage gocql\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"sort\"\n\t\"gopkg.in\/inf.v0\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype WikiPage struct {\n\tTitle       string\n\tRevId       UUID\n\tBody        string\n\tViews       int64\n\tProtected   bool\n\tModified    time.Time\n\tRating      *inf.Dec\n\tTags        []string\n\tAttachments map[string]WikiAttachment\n}\n\ntype WikiAttachment []byte\n\nvar wikiTestData = []*WikiPage{\n\t&WikiPage{\n\t\tTitle:    \"Frontpage\",\n\t\tRevId:    TimeUUID(),\n\t\tBody:     \"Welcome to this wiki page!\",\n\t\tRating:   inf.NewDec(131, 3),\n\t\tModified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC),\n\t\tTags:     []string{\"start\", \"important\", \"test\"},\n\t\tAttachments: map[string]WikiAttachment{\n\t\t\t\"logo\":    WikiAttachment(\"\\x00company logo\\x00\"),\n\t\t\t\"favicon\": WikiAttachment(\"favicon.ico\"),\n\t\t},\n\t},\n\t&WikiPage{\n\t\tTitle:    \"Foobar\",\n\t\tRevId:    TimeUUID(),\n\t\tBody:     \"foo::Foo f = new foo::Foo(foo::Foo::INIT);\",\n\t\tModified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC),\n\t},\n}\n\ntype WikiTest struct {\n\tsession *Session\n\ttb      testing.TB\n}\n\nfunc (w *WikiTest) CreateSchema() {\n\n\tif err := w.session.Query(`DROP TABLE wiki_page`).Exec(); err != nil && err.Error() != \"unconfigured columnfamily wiki_page\" {\n\t\tw.tb.Fatal(\"CreateSchema:\", err)\n\t}\n\terr := createTable(w.session, `CREATE TABLE wiki_page (\n\t\t\ttitle       varchar,\n\t\t\trevid       timeuuid,\n\t\t\tbody        varchar,\n\t\t\tviews       bigint,\n\t\t\tprotected   boolean,\n\t\t\tmodified    timestamp,\n\t\t\trating      decimal,\n\t\t\ttags        set<varchar>,\n\t\t\tattachments map<varchar, blob>,\n\t\t\tPRIMARY KEY (title, revid)\n\t\t)`)\n\tif *clusterSize > 1 {\n\t\t\/\/ wait for table definition to propogate\n\t\ttime.Sleep(250 * time.Millisecond)\n\t}\n\tif err != nil {\n\t\tw.tb.Fatal(\"CreateSchema:\", err)\n\t}\n}\n\nfunc (w *WikiTest) CreatePages(n int) {\n\tvar page WikiPage\n\tt0 := time.Now()\n\tfor i := 0; i < n; i++ {\n\t\tpage.Title = fmt.Sprintf(\"generated_%d\", (i&16)+1)\n\t\tpage.Modified = t0.Add(time.Duration(i-n) * time.Minute)\n\t\tpage.RevId = UUIDFromTime(page.Modified)\n\t\tpage.Body = fmt.Sprintf(\"text %d\", i)\n\t\tif err := w.InsertPage(&page); err != nil {\n\t\t\tw.tb.Error(\"CreatePages:\", err)\n\t\t}\n\t}\n}\n\nfunc (w *WikiTest) InsertPage(page *WikiPage) error {\n\treturn w.session.Query(`INSERT INTO wiki_page\n\t\t(title, revid, body, views, protected, modified, rating, tags, attachments)\n\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n\t\tpage.Title, page.RevId, page.Body, page.Views, page.Protected,\n\t\tpage.Modified, page.Rating, page.Tags, page.Attachments).Exec()\n}\n\nfunc (w *WikiTest) SelectPage(page *WikiPage, title string, revid UUID) error {\n\treturn w.session.Query(`SELECT title, revid, body, views, protected,\n\t\tmodified,tags, attachments, rating\n\t\tFROM wiki_page WHERE title = ? AND revid = ? LIMIT 1`,\n\t\ttitle, revid).Scan(&page.Title, &page.RevId,\n\t\t&page.Body, &page.Views, &page.Protected, &page.Modified, &page.Tags,\n\t\t&page.Attachments, &page.Rating)\n}\n\nfunc (w *WikiTest) GetPageCount() int {\n\tvar count int\n\tif err := w.session.Query(`SELECT COUNT(*) FROM wiki_page`).Scan(&count); err != nil {\n\t\tw.tb.Error(\"GetPageCount\", err)\n\t}\n\treturn count\n}\n\nfunc TestWikiCreateSchema(t *testing.T) {\n\tsession := createSession(t)\n\tdefer session.Close()\n\n\tw := WikiTest{session, t}\n\tw.CreateSchema()\n}\n\nfunc BenchmarkWikiCreateSchema(b *testing.B) {\n\tb.StopTimer()\n\tsession := createSession(b)\n\tdefer func() {\n\t\tb.StopTimer()\n\t\tsession.Close()\n\t}()\n\tw := WikiTest{session, b}\n\tb.StartTimer()\n\n\tfor i := 0; i < b.N; i++ {\n\t\tw.CreateSchema()\n\t}\n}\n\nfunc TestWikiCreatePages(t *testing.T) {\n\tsession := createSession(t)\n\tdefer session.Close()\n\n\tw := WikiTest{session, t}\n\tw.CreateSchema()\n\tnumPages := 5\n\tw.CreatePages(numPages)\n\tif count := w.GetPageCount(); count != numPages {\n\t\tt.Errorf(\"expected %d pages, got %d pages.\", numPages, count)\n\t}\n}\n\nfunc BenchmarkWikiCreatePages(b *testing.B) {\n\tb.StopTimer()\n\tsession := createSession(b)\n\tdefer func() {\n\t\tb.StopTimer()\n\t\tsession.Close()\n\t}()\n\tw := WikiTest{session, b}\n\tw.CreateSchema()\n\tb.StartTimer()\n\n\tw.CreatePages(b.N)\n}\n\nfunc BenchmarkWikiSelectAllPages(b *testing.B) {\n\tb.StopTimer()\n\tsession := createSession(b)\n\tdefer func() {\n\t\tb.StopTimer()\n\t\tsession.Close()\n\t}()\n\tw := WikiTest{session, b}\n\tw.CreateSchema()\n\tw.CreatePages(100)\n\tb.StartTimer()\n\n\tvar page WikiPage\n\tfor i := 0; i < b.N; i++ {\n\t\titer := session.Query(`SELECT title, revid, body, views, protected,\n\t\t\tmodified, tags, attachments, rating\n\t\t\tFROM wiki_page`).Iter()\n\t\tfor iter.Scan(&page.Title, &page.RevId, &page.Body, &page.Views,\n\t\t\t&page.Protected, &page.Modified, &page.Tags, &page.Attachments,\n\t\t\t&page.Rating) {\n\t\t\t\/\/ pass\n\t\t}\n\t\tif err := iter.Close(); err != nil {\n\t\t\tb.Error(err)\n\t\t}\n\t}\n}\n\nfunc BenchmarkWikiSelectSinglePage(b *testing.B) {\n\tb.StopTimer()\n\tsession := createSession(b)\n\tdefer func() {\n\t\tb.StopTimer()\n\t\tsession.Close()\n\t}()\n\tw := WikiTest{session, b}\n\tw.CreateSchema()\n\tpages := make([]WikiPage, 100)\n\tw.CreatePages(len(pages))\n\titer := session.Query(`SELECT title, revid FROM wiki_page`).Iter()\n\tfor i := 0; i < len(pages); i++ {\n\t\tif !iter.Scan(&pages[i].Title, &pages[i].RevId) {\n\t\t\tpages = pages[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\tif err := iter.Close(); err != nil {\n\t\tb.Error(err)\n\t}\n\tb.StartTimer()\n\n\tvar page WikiPage\n\tfor i := 0; i < b.N; i++ {\n\t\tp := &pages[i%len(pages)]\n\t\tif err := w.SelectPage(&page, p.Title, p.RevId); err != nil {\n\t\t\tb.Error(err)\n\t\t}\n\t}\n}\n\nfunc BenchmarkWikiSelectPageCount(b *testing.B) {\n\tb.StopTimer()\n\tsession := createSession(b)\n\tdefer func() {\n\t\tb.StopTimer()\n\t\tsession.Close()\n\t}()\n\tw := WikiTest{session, b}\n\tw.CreateSchema()\n\tnumPages := 10\n\tw.CreatePages(numPages)\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tif count := w.GetPageCount(); count != numPages {\n\t\t\tb.Errorf(\"expected %d pages, got %d pages.\", numPages, count)\n\t\t}\n\t}\n}\n\nfunc TestWikiTypicalCRUD(t *testing.T) {\n\tsession := createSession(t)\n\tdefer session.Close()\n\n\tw := WikiTest{session, t}\n\tw.CreateSchema()\n\tfor _, page := range wikiTestData {\n\t\tif err := w.InsertPage(page); err != nil {\n\t\t\tt.Error(\"InsertPage:\", err)\n\t\t}\n\t}\n\tif count := w.GetPageCount(); count != len(wikiTestData) {\n\t\tt.Errorf(\"count: expected %d, got %d\\n\", len(wikiTestData), count)\n\t}\n\tfor _, original := range wikiTestData {\n\t\tpage := new(WikiPage)\n\t\tif err := w.SelectPage(page, original.Title, original.RevId); err != nil {\n\t\t\tt.Error(\"SelectPage:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tsort.Sort(sort.StringSlice(page.Tags))\n\t\tsort.Sort(sort.StringSlice(original.Tags))\n\t\tif !reflect.DeepEqual(page, original) {\n\t\t\tt.Errorf(\"page: expected %#v, got %#v\\n\", original, page)\n\t\t}\n\t}\n}\n<commit_msg>Run each wiki test in its own table<commit_after>\/\/ +build all integration\n\npackage gocql\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"sort\"\n\t\"testing\"\n\t\"time\"\n\n\t\"gopkg.in\/inf.v0\"\n)\n\ntype WikiPage struct {\n\tTitle       string\n\tRevId       UUID\n\tBody        string\n\tViews       int64\n\tProtected   bool\n\tModified    time.Time\n\tRating      *inf.Dec\n\tTags        []string\n\tAttachments map[string]WikiAttachment\n}\n\ntype WikiAttachment []byte\n\nvar wikiTestData = []*WikiPage{\n\t&WikiPage{\n\t\tTitle:    \"Frontpage\",\n\t\tRevId:    TimeUUID(),\n\t\tBody:     \"Welcome to this wiki page!\",\n\t\tRating:   inf.NewDec(131, 3),\n\t\tModified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC),\n\t\tTags:     []string{\"start\", \"important\", \"test\"},\n\t\tAttachments: map[string]WikiAttachment{\n\t\t\t\"logo\":    WikiAttachment(\"\\x00company logo\\x00\"),\n\t\t\t\"favicon\": WikiAttachment(\"favicon.ico\"),\n\t\t},\n\t},\n\t&WikiPage{\n\t\tTitle:    \"Foobar\",\n\t\tRevId:    TimeUUID(),\n\t\tBody:     \"foo::Foo f = new foo::Foo(foo::Foo::INIT);\",\n\t\tModified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC),\n\t},\n}\n\ntype WikiTest struct {\n\tsession *Session\n\ttb      testing.TB\n\n\ttable string\n}\n\nfunc CreateSchema(session *Session, tb testing.TB, table string) *WikiTest {\n\ttable = \"wiki_\" + table\n\tif err := session.Query(fmt.Sprintf(\"DROP TABLE IF EXISTS %s\", table)).Exec(); err != nil {\n\t\ttb.Fatal(\"CreateSchema:\", err)\n\t}\n\n\terr := createTable(session, fmt.Sprintf(`CREATE TABLE %s (\n\t\t\ttitle       varchar,\n\t\t\trevid       timeuuid,\n\t\t\tbody        varchar,\n\t\t\tviews       bigint,\n\t\t\tprotected   boolean,\n\t\t\tmodified    timestamp,\n\t\t\trating      decimal,\n\t\t\ttags        set<varchar>,\n\t\t\tattachments map<varchar, blob>,\n\t\t\tPRIMARY KEY (title, revid)\n\t\t)`, table))\n\n\tif err != nil {\n\t\ttb.Fatal(\"CreateSchema:\", err)\n\t}\n\n\treturn &WikiTest{\n\t\tsession: session,\n\t\ttb:      tb,\n\t\ttable:   table,\n\t}\n}\n\nfunc (w *WikiTest) CreatePages(n int) {\n\tvar page WikiPage\n\tt0 := time.Now()\n\tfor i := 0; i < n; i++ {\n\t\tpage.Title = fmt.Sprintf(\"generated_%d\", (i&16)+1)\n\t\tpage.Modified = t0.Add(time.Duration(i-n) * time.Minute)\n\t\tpage.RevId = UUIDFromTime(page.Modified)\n\t\tpage.Body = fmt.Sprintf(\"text %d\", i)\n\t\tif err := w.InsertPage(&page); err != nil {\n\t\t\tw.tb.Error(\"CreatePages:\", err)\n\t\t}\n\t}\n}\n\nfunc (w *WikiTest) InsertPage(page *WikiPage) error {\n\treturn w.session.Query(fmt.Sprintf(`INSERT INTO %s\n\t\t(title, revid, body, views, protected, modified, rating, tags, attachments)\n\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, w.table),\n\t\tpage.Title, page.RevId, page.Body, page.Views, page.Protected,\n\t\tpage.Modified, page.Rating, page.Tags, page.Attachments).Exec()\n}\n\nfunc (w *WikiTest) SelectPage(page *WikiPage, title string, revid UUID) error {\n\treturn w.session.Query(fmt.Sprintf(`SELECT title, revid, body, views, protected,\n\t\tmodified,tags, attachments, rating\n\t\tFROM %s WHERE title = ? AND revid = ? LIMIT 1`, w.table),\n\t\ttitle, revid).Scan(&page.Title, &page.RevId,\n\t\t&page.Body, &page.Views, &page.Protected, &page.Modified, &page.Tags,\n\t\t&page.Attachments, &page.Rating)\n}\n\nfunc (w *WikiTest) GetPageCount() int {\n\tvar count int\n\tif err := w.session.Query(fmt.Sprintf(`SELECT COUNT(*) FROM %s`, w.table)).Scan(&count); err != nil {\n\t\tw.tb.Error(\"GetPageCount\", err)\n\t}\n\treturn count\n}\n\nfunc TestWikiCreateSchema(t *testing.T) {\n\tsession := createSession(t)\n\tdefer session.Close()\n\n\tCreateSchema(session, t, \"create\")\n}\n\nfunc BenchmarkWikiCreateSchema(b *testing.B) {\n\tb.StopTimer()\n\tsession := createSession(b)\n\tdefer func() {\n\t\tb.StopTimer()\n\t\tsession.Close()\n\t}()\n\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tCreateSchema(session, b, \"bench_create\")\n\t}\n}\n\nfunc TestWikiCreatePages(t *testing.T) {\n\tsession := createSession(t)\n\tdefer session.Close()\n\n\tw := CreateSchema(session, t, \"create_pages\")\n\n\tnumPages := 5\n\tw.CreatePages(numPages)\n\tif count := w.GetPageCount(); count != numPages {\n\t\tt.Errorf(\"expected %d pages, got %d pages.\", numPages, count)\n\t}\n}\n\nfunc BenchmarkWikiCreatePages(b *testing.B) {\n\tb.StopTimer()\n\tsession := createSession(b)\n\tdefer func() {\n\t\tb.StopTimer()\n\t\tsession.Close()\n\t}()\n\n\tw := CreateSchema(session, b, \"bench_create_pages\")\n\n\tb.StartTimer()\n\n\tw.CreatePages(b.N)\n}\n\nfunc BenchmarkWikiSelectAllPages(b *testing.B) {\n\tb.StopTimer()\n\tsession := createSession(b)\n\tdefer func() {\n\t\tb.StopTimer()\n\t\tsession.Close()\n\t}()\n\tw := CreateSchema(session, b, \"bench_select_all\")\n\n\tw.CreatePages(100)\n\tb.StartTimer()\n\n\tvar page WikiPage\n\tfor i := 0; i < b.N; i++ {\n\t\titer := session.Query(fmt.Sprintf(`SELECT title, revid, body, views, protected,\n\t\t\tmodified, tags, attachments, rating\n\t\t\tFROM %s`, w.table)).Iter()\n\t\tfor iter.Scan(&page.Title, &page.RevId, &page.Body, &page.Views,\n\t\t\t&page.Protected, &page.Modified, &page.Tags, &page.Attachments,\n\t\t\t&page.Rating) {\n\t\t\t\/\/ pass\n\t\t}\n\t\tif err := iter.Close(); err != nil {\n\t\t\tb.Error(err)\n\t\t}\n\t}\n}\n\nfunc BenchmarkWikiSelectSinglePage(b *testing.B) {\n\tb.StopTimer()\n\tsession := createSession(b)\n\tdefer func() {\n\t\tb.StopTimer()\n\t\tsession.Close()\n\t}()\n\tw := CreateSchema(session, b, \"bench_select_single\")\n\tpages := make([]WikiPage, 100)\n\tw.CreatePages(len(pages))\n\titer := session.Query(fmt.Sprintf(`SELECT title, revid FROM %s`, w.table)).Iter()\n\tfor i := 0; i < len(pages); i++ {\n\t\tif !iter.Scan(&pages[i].Title, &pages[i].RevId) {\n\t\t\tpages = pages[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\tif err := iter.Close(); err != nil {\n\t\tb.Error(err)\n\t}\n\tb.StartTimer()\n\n\tvar page WikiPage\n\tfor i := 0; i < b.N; i++ {\n\t\tp := &pages[i%len(pages)]\n\t\tif err := w.SelectPage(&page, p.Title, p.RevId); err != nil {\n\t\t\tb.Error(err)\n\t\t}\n\t}\n}\n\nfunc BenchmarkWikiSelectPageCount(b *testing.B) {\n\tb.StopTimer()\n\tsession := createSession(b)\n\tdefer func() {\n\t\tb.StopTimer()\n\t\tsession.Close()\n\t}()\n\n\tw := CreateSchema(session, b, \"bench_page_count\")\n\tconst numPages = 10\n\tw.CreatePages(numPages)\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tif count := w.GetPageCount(); count != numPages {\n\t\t\tb.Errorf(\"expected %d pages, got %d pages.\", numPages, count)\n\t\t}\n\t}\n}\n\nfunc TestWikiTypicalCRUD(t *testing.T) {\n\tsession := createSession(t)\n\tdefer session.Close()\n\n\tw := CreateSchema(session, t, \"crud\")\n\n\tfor _, page := range wikiTestData {\n\t\tif err := w.InsertPage(page); err != nil {\n\t\t\tt.Error(\"InsertPage:\", err)\n\t\t}\n\t}\n\tif count := w.GetPageCount(); count != len(wikiTestData) {\n\t\tt.Errorf(\"count: expected %d, got %d\\n\", len(wikiTestData), count)\n\t}\n\tfor _, original := range wikiTestData {\n\t\tpage := new(WikiPage)\n\t\tif err := w.SelectPage(page, original.Title, original.RevId); err != nil {\n\t\t\tt.Error(\"SelectPage:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tsort.Sort(sort.StringSlice(page.Tags))\n\t\tsort.Sort(sort.StringSlice(original.Tags))\n\t\tif !reflect.DeepEqual(page, original) {\n\t\t\tt.Errorf(\"page: expected %#v, got %#v\\n\", original, page)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package govaluate\n\nimport (\n  \"testing\"\n)\n\n\/*\n  Contains test cases for all the expression examples given in the README.\n  While all of the functionality for these cases should be covered in other tests,\n  this is really just a sanity check.\n*\/\n\nfunc TestBasicEvaluation(test *testing.T) {\n\n  expression, _ := NewEvaluableExpression(\"10 > 0\");\n\tresult, _ := expression.Evaluate(nil);\n\n  if(result != true) {\n    test.Logf(\"Expected 'true', got '%v'\\n\", result)\n    test.Fail()\n  }\n}\n\nfunc TestParameterEvaluation(test *testing.T) {\n\n  expression, _ := NewEvaluableExpression(\"foo > 0\");\n\n\tparameters := make(map[string]interface{}, 8)\n\tparameters[\"foo\"] = -1;\n\n\tresult, _ := expression.Evaluate(parameters);\n\n  if(result != false) {\n    test.Logf(\"Expected 'false', got '%v'\\n\", result)\n    test.Fail()\n  }\n}\n\nfunc TestModifierEvaluation(test *testing.T) {\n\n  expression, _ := NewEvaluableExpression(\"(requests_made * requests_succeeded \/ 100) >= 90\");\n\n\tparameters := make(map[string]interface{}, 8)\n\tparameters[\"requests_made\"] = 100;\n\tparameters[\"requests_succeeded\"] = 80;\n\n\tresult, _ := expression.Evaluate(parameters);\n\n  if(result != false) {\n    test.Logf(\"Expected 'false', got '%v'\\n\", result)\n    test.Fail()\n  }\n}\n\nfunc TestStringEvaluation(test *testing.T) {\n\n  expression, _ := NewEvaluableExpression(\"http_response_body == 'service is ok'\");\n\n\tparameters := make(map[string]interface{}, 8)\n\tparameters[\"http_response_body\"] = \"service is ok\";\n\n\tresult, _ := expression.Evaluate(parameters);\n\n  if(result != true) {\n    test.Logf(\"Expected 'false', got '%v'\\n\", result)\n    test.Fail()\n  }\n}\n\nfunc TestFloatEvaluation(test *testing.T) {\n\n  expression, _ := NewEvaluableExpression(\"(mem_used \/ total_mem) * 100\");\n\n\tparameters := make(map[string]interface{}, 8)\n\tparameters[\"total_mem\"] = 1024;\n\tparameters[\"mem_used\"] = 512;\n\n\tresult, _ := expression.Evaluate(parameters);\n\n  if(result != 50.0) {\n    test.Logf(\"Expected '50.0', got '%v'\\n\", result)\n    test.Fail()\n  }\n}\n\nfunc TestDateComparison(test *testing.T) {\n\n  expression, _ := NewEvaluableExpression(\"'2014-01-02' > '2014-01-01 23:59:59'\");\n\tresult, _ := expression.Evaluate(nil);\n\n  if(result != true) {\n    test.Logf(\"Expected 'true', got '%v'\\n\", result)\n    test.Fail()\n  }\n}\n\nfunc TestMultipleEvaluation(test *testing.T) {\n  expression, _ := NewEvaluableExpression(\"response_time <= 100\");\n\tparameters := make(map[string]interface{}, 8)\n\n\tfor i := 0; i < 64; i++ {\n\t\tparameters[\"response_time\"] = i\n\t\tresult, _ := expression.Evaluate(parameters)\n\n    if(result != true) {\n      test.Logf(\"Expected 'true', got '%v'\\n\", result)\n      test.Fail()\n    }\n\t}\n}\n<commit_msg>Moved comment, so as to not associate it with any specific test<commit_after>package govaluate\n\n\/*\n  Contains test cases for all the expression examples given in the README.\n  While all of the functionality for these cases should be covered in other tests,\n  this is really just a sanity check.\n*\/\nimport (\n  \"testing\"\n)\n\nfunc TestBasicEvaluation(test *testing.T) {\n\n  expression, _ := NewEvaluableExpression(\"10 > 0\");\n\tresult, _ := expression.Evaluate(nil);\n\n  if(result != true) {\n    test.Logf(\"Expected 'true', got '%v'\\n\", result)\n    test.Fail()\n  }\n}\n\nfunc TestParameterEvaluation(test *testing.T) {\n\n  expression, _ := NewEvaluableExpression(\"foo > 0\");\n\n\tparameters := make(map[string]interface{}, 8)\n\tparameters[\"foo\"] = -1;\n\n\tresult, _ := expression.Evaluate(parameters);\n\n  if(result != false) {\n    test.Logf(\"Expected 'false', got '%v'\\n\", result)\n    test.Fail()\n  }\n}\n\nfunc TestModifierEvaluation(test *testing.T) {\n\n  expression, _ := NewEvaluableExpression(\"(requests_made * requests_succeeded \/ 100) >= 90\");\n\n\tparameters := make(map[string]interface{}, 8)\n\tparameters[\"requests_made\"] = 100;\n\tparameters[\"requests_succeeded\"] = 80;\n\n\tresult, _ := expression.Evaluate(parameters);\n\n  if(result != false) {\n    test.Logf(\"Expected 'false', got '%v'\\n\", result)\n    test.Fail()\n  }\n}\n\nfunc TestStringEvaluation(test *testing.T) {\n\n  expression, _ := NewEvaluableExpression(\"http_response_body == 'service is ok'\");\n\n\tparameters := make(map[string]interface{}, 8)\n\tparameters[\"http_response_body\"] = \"service is ok\";\n\n\tresult, _ := expression.Evaluate(parameters);\n\n  if(result != true) {\n    test.Logf(\"Expected 'false', got '%v'\\n\", result)\n    test.Fail()\n  }\n}\n\nfunc TestFloatEvaluation(test *testing.T) {\n\n  expression, _ := NewEvaluableExpression(\"(mem_used \/ total_mem) * 100\");\n\n\tparameters := make(map[string]interface{}, 8)\n\tparameters[\"total_mem\"] = 1024;\n\tparameters[\"mem_used\"] = 512;\n\n\tresult, _ := expression.Evaluate(parameters);\n\n  if(result != 50.0) {\n    test.Logf(\"Expected '50.0', got '%v'\\n\", result)\n    test.Fail()\n  }\n}\n\nfunc TestDateComparison(test *testing.T) {\n\n  expression, _ := NewEvaluableExpression(\"'2014-01-02' > '2014-01-01 23:59:59'\");\n\tresult, _ := expression.Evaluate(nil);\n\n  if(result != true) {\n    test.Logf(\"Expected 'true', got '%v'\\n\", result)\n    test.Fail()\n  }\n}\n\nfunc TestMultipleEvaluation(test *testing.T) {\n  expression, _ := NewEvaluableExpression(\"response_time <= 100\");\n\tparameters := make(map[string]interface{}, 8)\n\n\tfor i := 0; i < 64; i++ {\n\t\tparameters[\"response_time\"] = i\n\t\tresult, _ := expression.Evaluate(parameters)\n\n    if(result != true) {\n      test.Logf(\"Expected 'true', got '%v'\\n\", result)\n      test.Fail()\n    }\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package wini\n\nimport (\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"testing\"\n\n\t\"github.com\/bmizerany\/assert\"\n)\n\nfunc Test1(t *testing.T) {\n\n\tfilename := filepath.Join(getTestDataDir(t), \"ini_parser_testfile.ini\")\n\tini := New()\n\terr := ini.ParseFile(filename)\n\tassert.Equal(t, nil, err)\n\n\tv, ok := ini.Get(\"mid\")\n\tassert.Equal(t, v, \"ac9219aa5232c4e519ae5fcb4d77ae5b\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"product\")\n\tassert.Equal(t, v, \"ppp\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"combo\")\n\tassert.Equal(t, v, \"ccc\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"aa\")\n\tassert.Equal(t, v, \"bb\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"axxxa\")\n\tassert.Equal(t, v, \"\")\n\tassert.Equal(t, ok, false)\n\n\tm, ok := ini.GetKvmap(\"\")\n\tassert.Equal(t, len(m), 6)\n\tassert.Equal(t, ok, true)\n\n\tn, ok := ini.GetKvmap(\"n\")\n\tassert.Equal(t, len(n), 0)\n\tassert.Equal(t, ok, false)\n\n\tsss, ok := ini.GetKvmap(\"sss\")\n\tassert.Equal(t, len(sss), 2)\n\tassert.Equal(t, ok, true)\n\tv, ok = ini.SectionGet(\"sss\", \"aa\")\n\tassert.Equal(t, v, \"bb\")\n\tassert.Equal(t, ok, true)\n\tv, ok = ini.SectionGet(\"sss\", \"appext\")\n\tassert.Equal(t, v, \"ab=cd\")\n\tassert.Equal(t, ok, true)\n}\n\nfunc TestUft8(t *testing.T) {\n\t\/*\n\t\ttitle=百度搜索_ipad2\n\t\turl=http:\/\/www.baidu.com\/s?bs=ipad&f=8&rsv_bp=1&wd=ipad2&inputT=397\n\t\turl_md5=5844a75423cd3372e1997360bd110a25\n\t\trefer=http:\/\/www.google.com\n\t\tanchor_text= google\n\t\tret_form = json\n\t\t ret_start = 0\n\t\t ret_limit =    50\n\t\tpage_info   =  0,0,50,1,0,20\n\t\tlocal=0\n\t\tmid=c4ca4238a0b923820dcc509a6f75849b\n\t\tproduct=test\n\t\tcombo=test\n\t\tversion=1.0.0.1\n\t\tdebug=1\n\t\tencoding=1\n\n\t*\/\n\n\tfilename := filepath.Join(getTestDataDir(t), \"utf8.ini\")\n\tini := New()\n\terr := ini.ParseFile(filename)\n\tassert.Equal(t, nil, err)\n\n\tv, ok := ini.Get(\"title\")\n\tassert.Equal(t, v, \"百度搜索_ipad2\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"url_md5\")\n\tassert.Equal(t, v, \"5844a75423cd3372e1997360bd110a25\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"ret_form\")\n\tassert.Equal(t, v, \"json\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"ret_start\")\n\tassert.Equal(t, v, \"0\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"ret_limit\")\n\tassert.Equal(t, v, \"50\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"axxxa\")\n\tassert.Equal(t, v, \"\")\n\tassert.Equal(t, ok, false)\n\n\tm, ok := ini.GetKvmap(\"\")\n\tassert.Equal(t, len(m), 16)\n\tassert.Equal(t, ok, true)\n\n\tn, ok := ini.GetKvmap(\"n\")\n\tassert.Equal(t, len(n), 0)\n\tassert.Equal(t, ok, false)\n}\n\nfunc TestErrorFormat(t *testing.T) {\n\tfilename := filepath.Join(getTestDataDir(t), \"error.ini\")\n\tini := New()\n\terr := ini.ParseFile(filename)\n\tassert.NotEqual(t, nil, err)\n}\n\nfunc TestMemoryData1(t *testing.T) {\n\traw := []byte(\"a:av||b:bv||c:cv||||d:dv||||||\")\n\tini := New()\n\terr := ini.Parse(raw, \"|\", \":\")\n\tassert.Equal(t, nil, err)\n\n\tv, ok := ini.Get(\"a\")\n\tassert.Equal(t, v, \"av\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"b\")\n\tassert.Equal(t, v, \"bv\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"c\")\n\tassert.Equal(t, v, \"cv\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"d\")\n\tassert.Equal(t, v, \"dv\")\n\tassert.Equal(t, ok, true)\n\n\tm, ok := ini.GetKvmap(\"\")\n\tassert.Equal(t, len(m), 4)\n\tassert.Equal(t, ok, true)\n\n\tn, ok := ini.GetKvmap(\"n\")\n\tassert.Equal(t, len(n), 0)\n\tassert.Equal(t, ok, false)\n}\n\nfunc TestMemoryData2(t *testing.T) {\n\traw := []byte(\"a:av||b:bv||c:cv||||d:dv||||||\")\n\tini := New()\n\terr := ini.Parse(raw, \"||\", \":\") \/\/ DIFFERENT with TestMemoryData1. use \"||\" instead of \"|\"\n\tassert.Equal(t, nil, err)\n\n\tv, ok := ini.Get(\"a\")\n\tassert.Equal(t, v, \"av\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"b\")\n\tassert.Equal(t, v, \"bv\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"c\")\n\tassert.Equal(t, v, \"cv\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"d\")\n\tassert.Equal(t, v, \"dv\")\n\tassert.Equal(t, ok, true)\n\n\tm, ok := ini.GetKvmap(\"\")\n\tassert.Equal(t, len(m), 4)\n\tassert.Equal(t, ok, true)\n\n\tn, ok := ini.GetKvmap(\"n\")\n\tassert.Equal(t, len(n), 0)\n\tassert.Equal(t, ok, false)\n}\n\nfunc TestMemoryData3(t *testing.T) {\n\traw := []byte(\"@|@|@|@|@|@|  a:av  @| b : bv @| c:cv  @|@|d:  dv@|@|@|@|@|@|@|\")\n\tini := New()\n\terr := ini.Parse(raw, \"@|\", \":\")\n\tassert.Equal(t, nil, err)\n\n\tv, ok := ini.Get(\"a\")\n\tassert.Equal(t, v, \"av\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"b\")\n\tassert.Equal(t, v, \"bv\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"c\")\n\tassert.Equal(t, v, \"cv\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"d\")\n\tassert.Equal(t, v, \"dv\")\n\tassert.Equal(t, ok, true)\n\n\tm, ok := ini.GetKvmap(\"\")\n\tassert.Equal(t, len(m), 4)\n\tassert.Equal(t, ok, true)\n\n\tn, ok := ini.GetKvmap(\"n\")\n\tassert.Equal(t, len(n), 0)\n\tassert.Equal(t, ok, false)\n}\n\nfunc getTestDataDir(t *testing.T) string {\n\tvar file string\n\tvar ok bool\n\t_, file, _, ok = runtime.Caller(0)\n\tassert.Equal(t, ok, true)\n\n\tcurdir := filepath.Dir(file)\n\treturn filepath.Join(curdir, \"test\/data\")\n}\n<commit_msg>Add invalid INI format unit test case<commit_after>package wini\n\nimport (\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"testing\"\n\n\t\"github.com\/bmizerany\/assert\"\n)\n\nfunc Test1(t *testing.T) {\n\n\tfilename := filepath.Join(getTestDataDir(t), \"ini_parser_testfile.ini\")\n\tini := New()\n\terr := ini.ParseFile(filename)\n\tassert.Equal(t, nil, err)\n\n\tv, ok := ini.Get(\"mid\")\n\tassert.Equal(t, v, \"ac9219aa5232c4e519ae5fcb4d77ae5b\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"product\")\n\tassert.Equal(t, v, \"ppp\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"combo\")\n\tassert.Equal(t, v, \"ccc\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"aa\")\n\tassert.Equal(t, v, \"bb\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"axxxa\")\n\tassert.Equal(t, v, \"\")\n\tassert.Equal(t, ok, false)\n\n\tm, ok := ini.GetKvmap(\"\")\n\tassert.Equal(t, len(m), 6)\n\tassert.Equal(t, ok, true)\n\n\tn, ok := ini.GetKvmap(\"n\")\n\tassert.Equal(t, len(n), 0)\n\tassert.Equal(t, ok, false)\n\n\tsss, ok := ini.GetKvmap(\"sss\")\n\tassert.Equal(t, len(sss), 2)\n\tassert.Equal(t, ok, true)\n\tv, ok = ini.SectionGet(\"sss\", \"aa\")\n\tassert.Equal(t, v, \"bb\")\n\tassert.Equal(t, ok, true)\n\tv, ok = ini.SectionGet(\"sss\", \"appext\")\n\tassert.Equal(t, v, \"ab=cd\")\n\tassert.Equal(t, ok, true)\n}\n\nfunc TestUft8(t *testing.T) {\n\t\/*\n\t\ttitle=百度搜索_ipad2\n\t\turl=http:\/\/www.baidu.com\/s?bs=ipad&f=8&rsv_bp=1&wd=ipad2&inputT=397\n\t\turl_md5=5844a75423cd3372e1997360bd110a25\n\t\trefer=http:\/\/www.google.com\n\t\tanchor_text= google\n\t\tret_form = json\n\t\t ret_start = 0\n\t\t ret_limit =    50\n\t\tpage_info   =  0,0,50,1,0,20\n\t\tlocal=0\n\t\tmid=c4ca4238a0b923820dcc509a6f75849b\n\t\tproduct=test\n\t\tcombo=test\n\t\tversion=1.0.0.1\n\t\tdebug=1\n\t\tencoding=1\n\n\t*\/\n\n\tfilename := filepath.Join(getTestDataDir(t), \"utf8.ini\")\n\tini := New()\n\terr := ini.ParseFile(filename)\n\tassert.Equal(t, nil, err)\n\n\tv, ok := ini.Get(\"title\")\n\tassert.Equal(t, v, \"百度搜索_ipad2\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"url_md5\")\n\tassert.Equal(t, v, \"5844a75423cd3372e1997360bd110a25\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"ret_form\")\n\tassert.Equal(t, v, \"json\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"ret_start\")\n\tassert.Equal(t, v, \"0\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"ret_limit\")\n\tassert.Equal(t, v, \"50\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"axxxa\")\n\tassert.Equal(t, v, \"\")\n\tassert.Equal(t, ok, false)\n\n\tm, ok := ini.GetKvmap(\"\")\n\tassert.Equal(t, len(m), 16)\n\tassert.Equal(t, ok, true)\n\n\tn, ok := ini.GetKvmap(\"n\")\n\tassert.Equal(t, len(n), 0)\n\tassert.Equal(t, ok, false)\n}\n\nfunc TestErrorFormat(t *testing.T) {\n\tfilename := filepath.Join(getTestDataDir(t), \"error.ini\")\n\tini := New()\n\terr := ini.ParseFile(filename)\n\tassert.NotEqual(t, nil, err)\n}\n\nfunc TestMemoryData1(t *testing.T) {\n\traw := []byte(\"a:av||b:bv||c:cv||||d:dv||||||\")\n\tini := New()\n\terr := ini.Parse(raw, \"|\", \":\")\n\tassert.Equal(t, nil, err)\n\n\tv, ok := ini.Get(\"a\")\n\tassert.Equal(t, v, \"av\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"b\")\n\tassert.Equal(t, v, \"bv\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"c\")\n\tassert.Equal(t, v, \"cv\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"d\")\n\tassert.Equal(t, v, \"dv\")\n\tassert.Equal(t, ok, true)\n\n\tm, ok := ini.GetKvmap(\"\")\n\tassert.Equal(t, len(m), 4)\n\tassert.Equal(t, ok, true)\n\n\tn, ok := ini.GetKvmap(\"n\")\n\tassert.Equal(t, len(n), 0)\n\tassert.Equal(t, ok, false)\n}\n\nfunc TestMemoryData2(t *testing.T) {\n\traw := []byte(\"a:av||b:bv||c:cv||||d:dv||||||\")\n\tini := New()\n\terr := ini.Parse(raw, \"||\", \":\") \/\/ DIFFERENT with TestMemoryData1. use \"||\" instead of \"|\"\n\tassert.Equal(t, nil, err)\n\n\tv, ok := ini.Get(\"a\")\n\tassert.Equal(t, v, \"av\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"b\")\n\tassert.Equal(t, v, \"bv\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"c\")\n\tassert.Equal(t, v, \"cv\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"d\")\n\tassert.Equal(t, v, \"dv\")\n\tassert.Equal(t, ok, true)\n\n\tm, ok := ini.GetKvmap(\"\")\n\tassert.Equal(t, len(m), 4)\n\tassert.Equal(t, ok, true)\n\n\tn, ok := ini.GetKvmap(\"n\")\n\tassert.Equal(t, len(n), 0)\n\tassert.Equal(t, ok, false)\n}\n\nfunc TestMemoryData3(t *testing.T) {\n\traw := []byte(\"@|@|@|@|@|@|  a:av  @| b : bv @| c:cv  @|@|d:  dv@|@|@|@|@|@|@|\")\n\tini := New()\n\terr := ini.Parse(raw, \"@|\", \":\")\n\tassert.Equal(t, nil, err)\n\n\tv, ok := ini.Get(\"a\")\n\tassert.Equal(t, v, \"av\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"b\")\n\tassert.Equal(t, v, \"bv\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"c\")\n\tassert.Equal(t, v, \"cv\")\n\tassert.Equal(t, ok, true)\n\n\tv, ok = ini.Get(\"d\")\n\tassert.Equal(t, v, \"dv\")\n\tassert.Equal(t, ok, true)\n\n\tm, ok := ini.GetKvmap(\"\")\n\tassert.Equal(t, len(m), 4)\n\tassert.Equal(t, ok, true)\n\n\tn, ok := ini.GetKvmap(\"n\")\n\tassert.Equal(t, len(n), 0)\n\tassert.Equal(t, ok, false)\n}\n\nfunc TestMemoryData4(t *testing.T) {\n\traw := []byte(\"@|@|@|@|@|@|  a:av  @| b : bv @| c:cv  @|@|d:  dv@|@|@|@|@|@|@|\")\n\tini := New()\n\terr := ini.Parse(raw, \"@\", \":\")\n\tassert.NotEqual(t, nil, err)\n\n\terr = ini.Parse(raw, \"@|\", \":\")\n\tassert.Equal(t, nil, err)\n}\n\nfunc getTestDataDir(t *testing.T) string {\n\tvar file string\n\tvar ok bool\n\t_, file, _, ok = runtime.Caller(0)\n\tassert.Equal(t, ok, true)\n\n\tcurdir := filepath.Dir(file)\n\treturn filepath.Join(curdir, \"test\/data\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package klient provides an instance and abstraction to a remote klient kite.\n\/\/ It is used to easily call methods of a klient kite\npackage klient\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/koding\/kite\"\n\t\"github.com\/koding\/kite\/protocol\"\n\t\"github.com\/koding\/logging\"\n)\n\nvar ErrDialingFailed = errors.New(\"Dialing klient failed.\")\n\n\/\/ KlientPool represents a pool of connected klients\ntype KlientPool struct {\n\tkite    *kite.Kite\n\tklients map[string]*Klient\n\tlog     logging.Logger\n\tsync.Mutex\n}\n\ntype Usage struct {\n\t\/\/ InactiveDuration reports the minimum duration since the latest activity.\n\tInactiveDuration time.Duration `json:\"inactive_duration\"`\n}\n\n\/\/ Klient represents a remote klient instance\ntype Klient struct {\n\tclient   *kite.Client\n\tkite     *kite.Kite\n\tUsername string\n}\n\nfunc NewPool(k *kite.Kite) *KlientPool {\n\treturn &KlientPool{\n\t\tkite:    k,\n\t\tklients: make(map[string]*Klient),\n\t\tlog:     logging.NewLogger(\"klientpool\"),\n\t}\n}\n\n\/\/ Get returns a ready to use and connected klient from the pool.\nfunc (k *KlientPool) Get(queryString string) (*Klient, error) {\n\tvar klient *Klient\n\tvar ok bool\n\tvar err error\n\n\tk.Lock()\n\tdefer k.Unlock()\n\n\tklient, ok = k.klients[queryString]\n\tif !ok {\n\t\tklient, err = Connect(k.kite, queryString)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tk.log.Info(\"creating new klient connection to %s\", queryString)\n\t\tk.klients[queryString] = klient\n\n\t\t\/\/ remove from the pool if we loose the connection\n\t\tklient.client.OnDisconnect(func() {\n\t\t\tk.log.Info(\"klient %s disconnected. removing from the pool\", queryString)\n\t\t\tk.Delete(queryString)\n\t\t\tklient.Close()\n\t\t})\n\t} else {\n\t\tk.log.Debug(\"fetching already connected klient (%s) from pool\", queryString)\n\t}\n\n\treturn klient, nil\n}\n\n\/\/ Delete removes the klient with the given queryString from the pool\nfunc (k *KlientPool) Delete(queryString string) {\n\tk.Lock()\n\tdefer k.Unlock()\n\n\tdelete(k.klients, queryString)\n}\n\n\/\/ Exists checks whether the given queryString exists in Kontrol or not\nfunc Exists(k *kite.Kite, queryString string) error {\n\tquery, err := protocol.KiteFromString(queryString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.Log.Debug(\"Querying for Klient: %s\", queryString)\n\n\t\/\/ an error indicates a non existing klient or another error.\n\t_, err = k.GetKites(query.Query())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Connect returns a new connected klient instance to the given queryString. The\n\/\/ klient is ready to use. It's connected and needs to be closed once the task\n\/\/ is finished with it.\nfunc Connect(k *kite.Kite, queryString string) (*Klient, error) {\n\treturn ConnectTimeout(k, queryString, 0)\n}\n\n\/\/ ConnectTimeout returns a new connected klient instance to the given\n\/\/ queryString. The klient is ready to use. It's tries to connect for the given\n\/\/ timeout duration\nfunc ConnectTimeout(k *kite.Kite, queryString string, t time.Duration) (*Klient, error) {\n\tquery, err := protocol.KiteFromString(queryString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tk.Log.Debug(\"Querying for Klient: %s\", queryString)\n\n\tkites, err := k.GetKites(query.Query())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tremoteKite := kites[0]\n\tremoteKite.ReadBufferSize = 512\n\tremoteKite.WriteBufferSize = 512\n\tif err := remoteKite.DialTimeout(t); err != nil {\n\t\treturn nil, ErrDialingFailed\n\t}\n\n\t\/\/ klient connection is ready now\n\treturn &Klient{\n\t\tkite:     k,\n\t\tclient:   remoteKite,\n\t\tUsername: remoteKite.Username,\n\t}, nil\n}\n\nfunc NewWithTimeout(k *kite.Kite, queryString string, t time.Duration) (*Klient, error) {\n\ttimeout := time.After(t)\n\n\tk.Log.Debug(\"Querying for Klient: %s\", queryString)\n\tfor {\n\t\tselect {\n\t\tcase <-time.Tick(time.Second * 2):\n\t\t\tif klient, err := Connect(k, queryString); err == nil {\n\t\t\t\treturn klient, nil\n\t\t\t}\n\n\t\tcase <-timeout:\n\t\t\treturn nil, ErrDialingFailed\n\t\t}\n\t}\n}\n\nfunc (k *Klient) Close() {\n\tk.client.Close()\n}\n\n\/\/ Usage calls the usage method of remote and get's the result back\nfunc (k *Klient) Usage() (*Usage, error) {\n\tresp, err := k.client.Tell(\"klient.usage\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar usg *Usage\n\tif err := resp.Unmarshal(&usg); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn usg, nil\n}\n\n\/\/ Ping checks if the given klient response with \"pong\" to the \"ping\" we send.\n\/\/ A nil error means a successfull pong result.\nfunc (k *Klient) Ping() error {\n\tresp, err := k.client.TellWithTimeout(\"kite.ping\", 10*time.Second)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tout, err := resp.String()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif out == \"pong\" {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"wrong response %s\", out)\n}\n<commit_msg>Kloud\/Klient: export client in Klient struct<commit_after>\/\/ Package klient provides an instance and abstraction to a remote klient kite.\n\/\/ It is used to easily call methods of a klient kite\npackage klient\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/koding\/kite\"\n\t\"github.com\/koding\/kite\/protocol\"\n\t\"github.com\/koding\/logging\"\n)\n\nvar ErrDialingFailed = errors.New(\"Dialing klient failed.\")\n\n\/\/ KlientPool represents a pool of connected klients\ntype KlientPool struct {\n\tkite    *kite.Kite\n\tklients map[string]*Klient\n\tlog     logging.Logger\n\tsync.Mutex\n}\n\ntype Usage struct {\n\t\/\/ InactiveDuration reports the minimum duration since the latest activity.\n\tInactiveDuration time.Duration `json:\"inactive_duration\"`\n}\n\n\/\/ Klient represents a remote klient instance\ntype Klient struct {\n\tclient   *kite.Client\n\tkite     *kite.Kite\n\tUsername string\n}\n\nfunc NewPool(k *kite.Kite) *KlientPool {\n\treturn &KlientPool{\n\t\tkite:    k,\n\t\tklients: make(map[string]*Klient),\n\t\tlog:     logging.NewLogger(\"klientpool\"),\n\t}\n}\n\n\/\/ Get returns a ready to use and connected klient from the pool.\nfunc (k *KlientPool) Get(queryString string) (*Klient, error) {\n\tvar klient *Klient\n\tvar ok bool\n\tvar err error\n\n\tk.Lock()\n\tdefer k.Unlock()\n\n\tklient, ok = k.klients[queryString]\n\tif !ok {\n\t\tklient, err = Connect(k.kite, queryString)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tk.log.Info(\"creating new klient connection to %s\", queryString)\n\t\tk.klients[queryString] = klient\n\n\t\t\/\/ remove from the pool if we loose the connection\n\t\tklient.client.OnDisconnect(func() {\n\t\t\tk.log.Info(\"klient %s disconnected. removing from the pool\", queryString)\n\t\t\tk.Delete(queryString)\n\t\t\tklient.Close()\n\t\t})\n\t} else {\n\t\tk.log.Debug(\"fetching already connected klient (%s) from pool\", queryString)\n\t}\n\n\treturn klient, nil\n}\n\n\/\/ Delete removes the klient with the given queryString from the pool\nfunc (k *KlientPool) Delete(queryString string) {\n\tk.Lock()\n\tdefer k.Unlock()\n\n\tdelete(k.klients, queryString)\n}\n\n\/\/ Exists checks whether the given queryString exists in Kontrol or not\nfunc Exists(k *kite.Kite, queryString string) error {\n\tquery, err := protocol.KiteFromString(queryString)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.Log.Debug(\"Querying for Klient: %s\", queryString)\n\n\t\/\/ an error indicates a non existing klient or another error.\n\t_, err = k.GetKites(query.Query())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Connect returns a new connected klient instance to the given queryString. The\n\/\/ klient is ready to use. It's connected and needs to be closed once the task\n\/\/ is finished with it.\nfunc Connect(k *kite.Kite, queryString string) (*Klient, error) {\n\treturn ConnectTimeout(k, queryString, 0)\n}\n\n\/\/ ConnectTimeout returns a new connected klient instance to the given\n\/\/ queryString. The klient is ready to use. It's tries to connect for the given\n\/\/ timeout duration\nfunc ConnectTimeout(k *kite.Kite, queryString string, t time.Duration) (*Klient, error) {\n\tquery, err := protocol.KiteFromString(queryString)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tk.Log.Debug(\"Querying for Klient: %s\", queryString)\n\n\tkites, err := k.GetKites(query.Query())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tremoteKite := kites[0]\n\tremoteKite.ReadBufferSize = 512\n\tremoteKite.WriteBufferSize = 512\n\tif err := remoteKite.DialTimeout(t); err != nil {\n\t\treturn nil, ErrDialingFailed\n\t}\n\n\t\/\/ klient connection is ready now\n\treturn &Klient{\n\t\tkite:     k,\n\t\tclient:   remoteKite,\n\t\tUsername: remoteKite.Username,\n\t}, nil\n}\n\nfunc NewWithTimeout(k *kite.Kite, queryString string, t time.Duration) (*Klient, error) {\n\ttimeout := time.After(t)\n\n\tk.Log.Debug(\"Querying for Klient: %s\", queryString)\n\tfor {\n\t\tselect {\n\t\tcase <-time.Tick(time.Second * 2):\n\t\t\tif klient, err := Connect(k, queryString); err == nil {\n\t\t\t\treturn klient, nil\n\t\t\t}\n\n\t\tcase <-timeout:\n\t\t\treturn nil, ErrDialingFailed\n\t\t}\n\t}\n}\n\nfunc (k *Klient) Client() *kite.Client {\n\treturn k.client\n}\n\nfunc (k *Klient) Close() {\n\tk.client.Close()\n}\n\n\/\/ Usage calls the usage method of remote and get's the result back\nfunc (k *Klient) Usage() (*Usage, error) {\n\tresp, err := k.client.Tell(\"klient.usage\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar usg *Usage\n\tif err := resp.Unmarshal(&usg); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn usg, nil\n}\n\n\/\/ Ping checks if the given klient response with \"pong\" to the \"ping\" we send.\n\/\/ A nil error means a successfull pong result.\nfunc (k *Klient) Ping() error {\n\tresp, err := k.client.TellWithTimeout(\"kite.ping\", 10*time.Second)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tout, err := resp.String()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif out == \"pong\" {\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"wrong response %s\", out)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ The goapp command implements a simple App Engine app to demonstrate how to\n\/\/ use the Service Control API v2 for admission control. For more information,\n\/\/ see https:\/\/cloud.google.com\/service-infrastructure\/docs\/admission-control.\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\/\/ WARNING:`go get google.golang.org\/api\/servicecontrol\/v2\" may take\n\t\/\/ 30 minutes or longer, depending on your network speed.\n\t\"google.golang.org\/api\/servicecontrol\/v2\"\n)\n\n\/\/ Check calls Service Control API v2 for admission control.\n\/\/ Name specifies the target resource name. Permission specifies\n\/\/ the required permission on the target resource.\nfunc check(w http.ResponseWriter, r *http.Request, name string, permission string) (string, error) {\n\tclient, err := servicecontrol.NewService(r.Context())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t\/\/ Construct CheckRequest from the incoming HTTP request.\n\t\/\/ The code assumes the incoming request processed by App Engine ingress.\n\tcheckRequest := &servicecontrol.CheckRequest{\n\t\tServiceConfigId: \"latest\",\n\t\tAttributes: &servicecontrol.AttributeContext{\n\t\t\tOrigin: &servicecontrol.Peer{\n\t\t\t\tIp: r.Header.Get(\"x-appengine-user-ip\"),\n\t\t\t},\n\t\t\tApi: &servicecontrol.Api{\n\t\t\t\tService:   \"endpointsapis.appspot.com\",\n\t\t\t\tOperation: \"google.example.endpointsapis.v1.Workspaces.GetWorkspace\",\n\t\t\t\tVersion:   \"v1\",\n\t\t\t\tProtocol:  r.Header.Get(\"x-forwarded-proto\"),\n\t\t\t},\n\t\t\tRequest: &servicecontrol.Request{\n\t\t\t\tId:     r.Header.Get(\"x-appengine-request-log-id\"),\n\t\t\t\tTime:   time.Now().UTC().Format(time.RFC3339),\n\t\t\t\tMethod: r.Method,\n\t\t\t\tScheme: r.Header.Get(\"x-forwarded-proto\"),\n\t\t\t\tHost:   r.Host,\n\t\t\t\tPath:   r.URL.Path,\n\t\t\t\tHeaders: map[string]string{\n\t\t\t\t\t\"authorization\": r.Header.Get(\"authorization\"),\n\t\t\t\t\t\"user-agent\":    r.Header.Get(\"user-agent\"),\n\t\t\t\t\t\"origin\":        r.Header.Get(\"origin\"),\n\t\t\t\t\t\"referer\":       r.Header.Get(\"referer\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tResources: []*servicecontrol.ResourceInfo{\n\t\t\t{\n\t\t\t\tName:       name,\n\t\t\t\tType:       \"endpointsapis.appspot.com\/Workspace\",\n\t\t\t\tPermission: permission,\n\t\t\t},\n\t\t},\n\t}\n\tresponse, err := client.Services.Check(\"endpointsapis.appspot.com\", checkRequest).Do()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tresponseJSON, err := response.MarshalJSON()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(responseJSON), nil\n}\n\nfunc admission(w http.ResponseWriter, r *http.Request) (string, error) {\n\t\/\/ Split the request path.\n\tsegments := strings.Split(r.URL.Path, \"\/\")\n\n\t\/\/ The request path must match \"\/v1\/projects\/*\/locations\/*\/workspaces\/*\" or\n\t\/\/ \"\/v1\/projects\/*\/locations\/*\/workspaces\". They correspond to the\n\t\/\/ GetWorkspace() and ListWorkspaces() methods defined in ..\/v1\/workspace.proto.\n\tif segments[0] != \"\" || segments[1] != \"v1\" || segments[2] != \"projects\" || segments[4] != \"locations\" || segments[6] != \"workspaces\" || len(segments) > 8 {\n\t\treturn \"\", errors.New(\"Resource '\" + r.URL.Path + \"' not found.\")\n\t}\n\t\/\/ Skip prefix \"\/v1\/\".\n\tresource := r.URL.Path[4:]\n\tpermission := \"endpointsapis.appspot.com\/workspaces.list\"\n\tif len(segments) == 8 {\n\t\tpermission = \"endpointsapis.appspot.com\/workspaces.get\"\n\t}\n\treturn check(w, r, resource, permission)\n}\n\nfunc indexHandler(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Perform admission control.\n\tresult, err := admission(w, r)\n\n\t\/\/ Print the admission control result.\n\tif err != nil {\n\t\tfmt.Fprintln(w, \"Error:\")\n\t\tfmt.Fprintln(w, err.Error())\n\t} else {\n\t\tfmt.Fprintln(w, \"CheckResponse:\")\n\t\tfmt.Fprintln(w, result)\n\t}\n\n\t\/\/ Print all environment variables.\n\tfmt.Fprintln(w, \"Environments:\")\n\tfmt.Fprintln(w, strings.Join(os.Environ(), \"\\n\"))\n\n\t\/\/ Print all request headers.\n\tfmt.Fprintln(w, \"Headers:\")\n\tfor key, values := range r.Header {\n\t\tfor _, value := range values {\n\t\t\tfmt.Fprintf(w, \"%v: %v\\n\", key, value)\n\t\t}\n\t}\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", indexHandler)\n\n\tport := os.Getenv(\"PORT\")\n\n\tlog.Printf(\"Listen and serve on port %s\", port)\n\tif err := http.ListenAndServe(\":\"+port, nil); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>feat: Integrate with Report v2 in the go app for the Example API.<commit_after>\/\/ The goapp command implements a simple App Engine app to demonstrate how to\n\/\/ use the Service Control API v2 for admission control. For more information,\n\/\/ see https:\/\/cloud.google.com\/service-infrastructure\/docs\/admission-control.\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\/\/ WARNING:`go get google.golang.org\/api\/servicecontrol\/v2\" may take\n\t\/\/ 30 minutes or longer, depending on your network speed.\n\t\"google.golang.org\/api\/servicecontrol\/v2\"\n)\n\n\/\/ Check calls Service Control API v2 for admission control.\n\/\/ Name specifies the target resource name. Permission specifies\n\/\/ the required permission on the target resource. Received\n\/\/ specifies the timestamp when the request is received.\nfunc check(w http.ResponseWriter, r *http.Request, name string, permission string, received time.Time, client *servicecontrol.Service) (string, error) {\n\t\/\/ Construct CheckRequest from the incoming HTTP request.\n\t\/\/ The code assumes the incoming request processed by App Engine ingress.\n\treq := &servicecontrol.CheckRequest{\n\t\tServiceConfigId: \"latest\",\n\t\tAttributes: &servicecontrol.AttributeContext{\n\t\t\tOrigin: &servicecontrol.Peer{\n\t\t\t\tIp: r.Header.Get(\"x-appengine-user-ip\"),\n\t\t\t},\n\t\t\tApi: &servicecontrol.Api{\n\t\t\t\tService:   \"endpointsapis.appspot.com\",\n\t\t\t\tOperation: \"google.example.endpointsapis.v1.Workspaces.GetWorkspace\",\n\t\t\t\tVersion:   \"v1\",\n\t\t\t\tProtocol:  r.Header.Get(\"x-forwarded-proto\"),\n\t\t\t},\n\t\t\tRequest: &servicecontrol.Request{\n\t\t\t\tId:     r.Header.Get(\"x-appengine-request-log-id\"),\n\t\t\t\tTime:   received.UTC().Format(time.RFC3339),\n\t\t\t\tMethod: r.Method,\n\t\t\t\tScheme: r.Header.Get(\"x-forwarded-proto\"),\n\t\t\t\tHost:   r.Host,\n\t\t\t\tPath:   r.URL.Path,\n\t\t\t\tHeaders: map[string]string{\n\t\t\t\t\t\"authorization\": r.Header.Get(\"authorization\"),\n\t\t\t\t\t\"user-agent\":    r.Header.Get(\"user-agent\"),\n\t\t\t\t\t\"origin\":        r.Header.Get(\"origin\"),\n\t\t\t\t\t\"referer\":       r.Header.Get(\"referer\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\tResource: &servicecontrol.Resource{\n\t\t\t\tName: name,\n\t\t\t},\n\t\t},\n\t\tResources: []*servicecontrol.ResourceInfo{\n\t\t\t{\n\t\t\t\tName:       name,\n\t\t\t\tType:       \"endpointsapis.appspot.com\/Workspace\",\n\t\t\t\tPermission: permission,\n\t\t\t},\n\t\t},\n\t}\n\tresp, err := client.Services.Check(\"endpointsapis.appspot.com\", req).Do()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tjson, err := resp.MarshalJSON()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(json), nil\n}\n\n\/\/ Report calls Service Control API v2 for telemetry reporting.\n\/\/ Name specifies the target resource name. ResponseCode specifies\n\/\/ the response code returned to user. Received specifies the\n\/\/ timestamp when the request is received.\nfunc report(w http.ResponseWriter, r *http.Request, name string, responseCode int64, received time.Time, client *servicecontrol.Service) (string, error) {\n\t\/\/ Construct ReportRequest from the incoming HTTP request.\n\t\/\/ The code assumes the incoming request processed by App Engine ingress.\n\treq := &servicecontrol.ReportRequest{\n\t\tServiceConfigId: \"latest\",\n\t\tOperations: []*servicecontrol.AttributeContext{\n\t\t\t{\n\t\t\t\tApi: &servicecontrol.Api{\n\t\t\t\t\tService:   \"endpointsapis.appspot.com\",\n\t\t\t\t\tOperation: \"google.example.endpointsapis.v1.Workspaces.GetWorkspace\",\n\t\t\t\t\tVersion:   \"v1\",\n\t\t\t\t\tProtocol:  r.Header.Get(\"x-forwarded-proto\"),\n\t\t\t\t},\n\t\t\t\tRequest: &servicecontrol.Request{\n\t\t\t\t\tSize: r.ContentLength,\n\t\t\t\t\tTime: received.UTC().Format(time.RFC3339),\n\t\t\t\t},\n\t\t\t\tResponse: &servicecontrol.Response{\n\t\t\t\t\tTime: time.Now().UTC().Format(time.RFC3339),\n\t\t\t\t\tCode: responseCode,\n\t\t\t\t\tHeaders: map[string]string{\n\t\t\t\t\t\t\"x-backend-latency\": \"0.007\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tDestination: &servicecontrol.Peer{\n\t\t\t\t\tRegionCode: \"us-central1\",\n\t\t\t\t},\n\t\t\t\tResource: &servicecontrol.Resource{\n\t\t\t\t\tName: name,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\t_, err := client.Services.Report(\"endpointsapis.appspot.com\", req).Do()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn \"{}\", nil\n}\n\n\/\/ Parse processes the request path and extract the resource name and\n\/\/ permissions.\nfunc parse(r *http.Request) (string, string, error) {\n\t\/\/ Split the request path.\n\tsegments := strings.Split(r.URL.Path, \"\/\")\n\n\t\/\/ The request path must match \"\/v1\/projects\/*\/locations\/*\/workspaces\/*\" or\n\t\/\/ \"\/v1\/projects\/*\/locations\/*\/workspaces\". They correspond to the\n\t\/\/ GetWorkspace() and ListWorkspaces() methods defined in ..\/v1\/workspace.proto.\n\tif segments[0] != \"\" || segments[1] != \"v1\" || segments[2] != \"projects\" || segments[4] != \"locations\" || segments[6] != \"workspaces\" || len(segments) > 8 {\n\t\treturn \"\", \"\", errors.New(\"Resource '\" + r.URL.Path + \"' not found.\")\n\t}\n\n\t\/\/ Skip prefix \"\/v1\/\".\n\tresource := r.URL.Path[4:]\n\tpermission := \"endpointsapis.appspot.com\/workspaces.list\"\n\tif len(segments) == 8 {\n\t\tpermission = \"endpointsapis.appspot.com\/workspaces.get\"\n\t}\n\treturn resource, permission, nil\n}\n\nfunc indexHandler(w http.ResponseWriter, r *http.Request) {\n\treceived := time.Now()\n\n\t\/\/ Create a client for Service Control API v2.\n\tclient, err := servicecontrol.NewService(r.Context())\n\tif err != nil {\n\t\tfmt.Fprintln(w, \"Error:\")\n\t\tfmt.Fprintln(w, err.Error())\n\t\treturn\n\t}\n\n\tresource, permission, err := parse(r)\n\tif err != nil {\n\t\tfmt.Fprintln(w, \"Error:\")\n\t\tfmt.Fprintln(w, err.Error())\n\t\treturn\n\t}\n\n\t\/\/ Perform admission control.\n\tresult, err := check(w, r, resource, permission, received, client)\n\n\tvar responseCode int64 = 200\n\t\/\/ Print the admission control result.\n\tif err != nil {\n\t\tfmt.Fprintln(w, \"Error:\")\n\t\tfmt.Fprintln(w, err.Error())\n\t\tresponseCode = 403\n\t} else {\n\t\tfmt.Fprintln(w, \"CheckResponse:\")\n\t\tfmt.Fprintln(w, result)\n\t}\n\n\t\/\/ Print all environment variables.\n\tfmt.Fprintln(w, \"Environments:\")\n\tfmt.Fprintln(w, strings.Join(os.Environ(), \"\\n\"))\n\n\t\/\/ Print all request headers.\n\tfmt.Fprintln(w, \"Headers:\")\n\tfor key, values := range r.Header {\n\t\tfor _, value := range values {\n\t\t\tfmt.Fprintf(w, \"%v: %v\\n\", key, value)\n\t\t}\n\t}\n\n\t\/\/ Perform telemetry report.\n\treport(w, r, resource, responseCode, received, client)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", indexHandler)\n\n\tport := os.Getenv(\"PORT\")\n\n\tlog.Printf(\"Listen and serve on port %s\", port)\n\tif err := http.ListenAndServe(\":\"+port, nil); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package postgres\n\nimport (\n\t\"fmt\"\n\t\"github.com\/rbastic\/dyndao\/schema\"\n\tsg \"github.com\/rbastic\/dyndao\/sqlgen\"\n\t\"strings\"\n)\n\nfunc CreateTable(g *sg.SQLBuilder, s *schema.Schema, table string) (string, error) {\n\treturn g.CoreCreateTable(g, s, table, false)\n}\n\nvar (\n\tidentityStr = \"SERIAL PRIMARY KEY\"\n)\n\nfunc RenderCreateColumn(sg *sg.SQLBuilder, t *schema.Table, f *schema.Column) string {\n\tdataType := strings.ToUpper(f.DBType)\n\n\tnotNull := \"\"\n\tidentity := \"\"\n\tunique := \"\"\n\n\tif f.IsIdentity {\n\t\tidentity = identityStr\n\t}\n\tif f.AllowNull {\n\t\tnotNull = \"NULL\"\n\t} else {\n\t\tnotNull = \"NOT NULL\"\n\t}\n\n\tdataType = mapType(dataType)\n\n\tif f.Length > 0 {\n\t\tdataType = fmt.Sprintf(\"%s(%d)\", dataType, f.Length)\n\t}\n\n\tif f.IsUnique {\n\t\tunique = \"UNIQUE\"\n\t}\n\n\tif f.IsIdentity {\n\t\treturn strings.Join([]string{f.Name, identity, notNull, unique}, \" \")\n\t}\n\treturn strings.Join([]string{f.Name, dataType, identity, notNull, unique}, \" \")\n}\n\nfunc mapType(s string) string {\n\tswitch s {\n\tcase \"number\":\n\t\tfallthrough\n\tcase \"NUMBER\":\n\t\tfallthrough\n\tcase \"integer\":\n\t\tfallthrough\n\tcase \"INTEGER\":\n\t\treturn \"INT\"\n\tcase \"BLOB\":\n\t\tfallthrough\n\tcase \"CLOB\":\n\t\treturn \"TEXT\"\n\tcase \"FLOAT\":\n\t\treturn \"FLOAT\"\n\tcase \"json\":\n\t\tfallthrough\n\tcase \"JSON\":\n\t\t\/\/ NOTE: We use JSONB behind the scenes for performance.\n\t\treturn \"JSONB\"\n\tdefault:\n\t\treturn s\n\t}\n}\n<commit_msg>mark this area with a comment to revisit it<commit_after>package postgres\n\nimport (\n\t\"fmt\"\n\t\"github.com\/rbastic\/dyndao\/schema\"\n\tsg \"github.com\/rbastic\/dyndao\/sqlgen\"\n\t\"strings\"\n)\n\nfunc CreateTable(g *sg.SQLBuilder, s *schema.Schema, table string) (string, error) {\n\treturn g.CoreCreateTable(g, s, table, false)\n}\n\nvar (\n\tidentityStr = \"SERIAL PRIMARY KEY\"\n)\n\nfunc RenderCreateColumn(sg *sg.SQLBuilder, t *schema.Table, f *schema.Column) string {\n\tdataType := strings.ToUpper(f.DBType)\n\n\tnotNull := \"\"\n\tidentity := \"\"\n\tunique := \"\"\n\n\tif f.IsIdentity {\n\t\tidentity = identityStr\n\t}\n\tif f.AllowNull {\n\t\tnotNull = \"NULL\"\n\t} else {\n\t\tnotNull = \"NOT NULL\"\n\t}\n\n\tdataType = mapType(dataType)\n\n\tif f.Length > 0 {\n\t\tdataType = fmt.Sprintf(\"%s(%d)\", dataType, f.Length)\n\t}\n\n\tif f.IsUnique {\n\t\tunique = \"UNIQUE\"\n\t}\n\n\tif f.IsIdentity {\n\t\treturn strings.Join([]string{f.Name, identity, notNull, unique}, \" \")\n\t}\n\treturn strings.Join([]string{f.Name, dataType, identity, notNull, unique}, \" \")\n}\n\nfunc mapType(s string) string {\n\tswitch s {\n\tcase \"number\":\n\t\tfallthrough\n\tcase \"NUMBER\":\n\t\tfallthrough\n\tcase \"integer\":\n\t\tfallthrough\n\tcase \"INTEGER\":\n\t\treturn \"INT\"\n\tcase \"BLOB\":\n\t\tfallthrough\n\tcase \"CLOB\":\n\t\treturn \"TEXT\"\n\tcase \"FLOAT\":\n\t\treturn \"FLOAT\"\n\tcase \"json\":\n\t\tfallthrough\n\tcase \"JSON\":\n\t\t\/\/ NOTE: We use JSONB behind the scenes for performance.\n\t\t\/\/ TODO FIXME Not sure I actually want to make this decision at this stage...\n\t\t\/\/ It's a user decision, not a package decision.\n\t\treturn \"JSONB\"\n\tdefault:\n\t\treturn s\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package dns\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ Parse the $GENERATE statement as used in BIND9 zones.\n\/\/ See http:\/\/www.zytrax.com\/books\/dns\/ch8\/generate.html for instance.\n\/\/ We are called after '$GENERATE '. After which we expect:\n\/\/ * the range (12-24\/2)\n\/\/ * lhs (ownername)\n\/\/ * [[ttl][class]]\n\/\/ * type\n\/\/ * rhs (rdata)\nfunc generate(l lex, c chan lex, t chan Token, o string) string {\n\tstep := 1\n\tif i := strings.IndexAny(l.token, \"\/\"); i != -1 {\n\t\tif i+1 == len(l.token) {\n\t\t\treturn \"bad step in $GENERATE range\"\n\t\t}\n\t\tif s, e := strconv.Atoi(l.token[i+1:]); e != nil {\n\t\t\treturn \"bad step in $GENERATE range\"\n\t\t} else {\n\t\t\tif s < 0 {\n\t\t\t\treturn \"bad step in $GENERATE range\"\n\t\t\t}\n\t\t\tstep = s\n\t\t}\n\t\tl.token = l.token[:i]\n\t}\n\tsx := strings.SplitN(l.token, \"-\", 2)\n\tif len(sx) != 2 {\n\t\treturn \"bad start\/stop in $GENERATE range\"\n\t}\n\tstart, err := strconv.Atoi(sx[0])\n\tif err != nil {\n\t\treturn \"bad start in $GENERATE range\"\n\t}\n\tend, err := strconv.Atoi(sx[1])\n\tif err != nil {\n\t\treturn \"bad end in $GENERATE range\"\n\t}\n\tif end < 0 || start < 0 || end <= start {\n\t\treturn \"bad range in $GENERATE range\"\n\t}\n\n\t<-c \/\/ _BLANK\n\t\/\/ Create a complete new string, which we then parse again.\n\ts := \"\"\nBuildRR:\n\tl = <-c\n\tif l.value != _NEWLINE && l.value != _EOF {\n\t\ts += l.token\n\t\tgoto BuildRR\n\t}\n\tfor i := start; i <= end; i += step {\n\t\tescape := false\n\t\tdom := \"\"\n\t\t\/\/ Defaults\n\t\tmod := \"%d\"\n\t\toffset := 0\n\t\tvar err error\n\t\t\/\/ Build the domain name.\n\t\tfor j := 0; j < len(s); j++ { \/\/ No 'range' because we need to jump around\n\t\t\tswitch s[j] {\n\t\t\tcase '\\\\':\n\t\t\t\tif escape {\n\t\t\t\t\tdom += \"\\\\\"\n\t\t\t\t\tescape = false\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tescape = true\n\t\t\tcase '$':\n\t\t\t\tmod = \"%d\"\n\t\t\t\toffset = 0\n\t\t\t\tif escape {\n\t\t\t\t\tdom += \"$\"\n\t\t\t\t\tescape = false\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tescape = false\n\t\t\t\tif j+1 >= len(s) { \/\/ End of the string\n\t\t\t\t\tdom += fmt.Sprintf(mod, i+offset)\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tif s[j+1] == '$' {\n\t\t\t\t\t\tdom += \"$\"\n\t\t\t\t\t\tj++\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ Search for { and }\n\t\t\t\tif s[j+1] == '{' { \/\/ Modifier block\n\t\t\t\t\tsep := strings.Index(s[j+2:], \"}\")\n\t\t\t\t\tif sep == -1 {\n\t\t\t\t\t\treturn \"bad modifier in $GENERATE\"\n\t\t\t\t\t}\n\t\t\t\t\t\/\/println(\"checking\", s[j+2:j+2+sep])\n\t\t\t\t\tmod, offset, err = modToPrintf(s[j+2 : j+2+sep])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn \"bad modifier in $GENERATE\"\n\t\t\t\t\t}\n\t\t\t\t\tj += 2 + sep \/\/ Jump to it\n\t\t\t\t}\n\t\t\t\t\/\/println(\"mod\", mod)\n\t\t\t\tdom += fmt.Sprintf(mod, i+offset)\n\t\t\tdefault:\n\t\t\t\tif escape { \/\/ Pretty useless here\n\t\t\t\t\tescape = false\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdom += string(s[j])\n\t\t\t}\n\t\t}\n\t\t\/\/ Re-parse the RR and send it on the current channel t\n\t\trx, err := NewRR(\"$ORIGIN \" + o + \"\\n\" + dom)\n\t\tif err != nil {\n\t\t\treturn err.(*ParseError).err\n\t\t}\n\t\tt <- Token{RR: rx}\n\t}\n\treturn \"\"\n}\n\n\/\/ Convert a $GENERATE modifier 0,0,d to something Printf can deal with.\nfunc modToPrintf(s string) (string, int, error) {\n\txs := strings.SplitN(s, \",\", 3)\n\tif len(xs) != 3 {\n\t\treturn \"\", 0, nil \/\/ make error\n\t}\n\t\/\/ xs[0] is offset, xs[1] is width, xs[2] is base\n\tif xs[2] != \"o\" && xs[2] != \"d\" && xs[2] != \"x\" && xs[2] != \"X\" {\n\t\treturn \"\", 0, nil \/\/ make error\n\t}\n\toffset, err := strconv.Atoi(xs[0])\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\twidth, err := strconv.Atoi(xs[1])\n\tif err != nil {\n\t\treturn \"\", offset, err\n\t}\n\tprintf := \"%\"\n\tswitch {\n\tcase width < 0:\n\t\treturn \"\", offset, nil \/\/ make error\n\tcase width == 0:\n\t\tprintf += xs[1]\n\tdefault:\n\t\tprintf += \"0\" + xs[1]\n\t}\n\tprintf += xs[2]\n\treturn printf, offset, nil\n}\n<commit_msg>Fix the error reporting<commit_after>package dns\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ Parse the $GENERATE statement as used in BIND9 zones.\n\/\/ See http:\/\/www.zytrax.com\/books\/dns\/ch8\/generate.html for instance.\n\/\/ We are called after '$GENERATE '. After which we expect:\n\/\/ * the range (12-24\/2)\n\/\/ * lhs (ownername)\n\/\/ * [[ttl][class]]\n\/\/ * type\n\/\/ * rhs (rdata)\nfunc generate(l lex, c chan lex, t chan Token, o string) string {\n\tstep := 1\n\tif i := strings.IndexAny(l.token, \"\/\"); i != -1 {\n\t\tif i+1 == len(l.token) {\n\t\t\treturn \"bad step in $GENERATE range\"\n\t\t}\n\t\tif s, e := strconv.Atoi(l.token[i+1:]); e != nil {\n\t\t\treturn \"bad step in $GENERATE range\"\n\t\t} else {\n\t\t\tif s < 0 {\n\t\t\t\treturn \"bad step in $GENERATE range\"\n\t\t\t}\n\t\t\tstep = s\n\t\t}\n\t\tl.token = l.token[:i]\n\t}\n\tsx := strings.SplitN(l.token, \"-\", 2)\n\tif len(sx) != 2 {\n\t\treturn \"bad start-stop in $GENERATE range\"\n\t}\n\tstart, err := strconv.Atoi(sx[0])\n\tif err != nil {\n\t\treturn \"bad start in $GENERATE range\"\n\t}\n\tend, err := strconv.Atoi(sx[1])\n\tif err != nil {\n\t\treturn \"bad stop in $GENERATE range\"\n\t}\n\tif end < 0 || start < 0 || end <= start {\n\t\treturn \"bad range in $GENERATE range\"\n\t}\n\n\t<-c \/\/ _BLANK\n\t\/\/ Create a complete new string, which we then parse again.\n\ts := \"\"\nBuildRR:\n\tl = <-c\n\tif l.value != _NEWLINE && l.value != _EOF {\n\t\ts += l.token\n\t\tgoto BuildRR\n\t}\n\tfor i := start; i <= end; i += step {\n\t\tvar (\n\t\t\tescape bool\n\t\t\tdom string\n\t\t\tmod string\n\t\t\toffset int\n\t\t\terr error\n\t\t)\n\n\t\tfor j := 0; j < len(s); j++ { \/\/ No 'range' because we need to jump around\n\t\t\tswitch s[j] {\n\t\t\tcase '\\\\':\n\t\t\t\tif escape {\n\t\t\t\t\tdom += \"\\\\\"\n\t\t\t\t\tescape = false\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tescape = true\n\t\t\tcase '$':\n\t\t\t\tmod = \"%d\"\n\t\t\t\toffset = 0\n\t\t\t\tif escape {\n\t\t\t\t\tdom += \"$\"\n\t\t\t\t\tescape = false\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tescape = false\n\t\t\t\tif j+1 >= len(s) { \/\/ End of the string\n\t\t\t\t\tdom += fmt.Sprintf(mod, i+offset)\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tif s[j+1] == '$' {\n\t\t\t\t\t\tdom += \"$\"\n\t\t\t\t\t\tj++\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ Search for { and }\n\t\t\t\tif s[j+1] == '{' { \/\/ Modifier block\n\t\t\t\t\tsep := strings.Index(s[j+2:], \"}\")\n\t\t\t\t\tif sep == -1 {\n\t\t\t\t\t\treturn \"bad modifier in $GENERATE\"\n\t\t\t\t\t}\n\t\t\t\t\t\/\/println(\"checking\", s[j+2:j+2+sep])\n\t\t\t\t\tmod, offset, err = modToPrintf(s[j+2 : j+2+sep])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn \"bad modifier in $GENERATE\"\n\t\t\t\t\t}\n\t\t\t\t\tj += 2 + sep \/\/ Jump to it\n\t\t\t\t}\n\t\t\t\t\/\/println(\"mod\", mod)\n\t\t\t\tdom += fmt.Sprintf(mod, i+offset)\n\t\t\tdefault:\n\t\t\t\tif escape { \/\/ Pretty useless here\n\t\t\t\t\tescape = false\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdom += string(s[j])\n\t\t\t}\n\t\t}\n\t\t\/\/ Re-parse the RR and send it on the current channel t\n\t\trx, err := NewRR(\"$ORIGIN \" + o + \"\\n\" + dom)\n\t\tif err != nil {\n\t\t\treturn err.(*ParseError).err\n\t\t}\n\t\tt <- Token{RR: rx}\n\t}\n\treturn \"\"\n}\n\n\/\/ Convert a $GENERATE modifier 0,0,d to something Printf can deal with.\nfunc modToPrintf(s string) (string, int, error) {\n\txs := strings.SplitN(s, \",\", 3)\n\tif len(xs) != 3 {\n\t\treturn \"\", 0, errors.New(\"fubar\")\n\t}\n\t\/\/ xs[0] is offset, xs[1] is width, xs[2] is base\n\tif xs[2] != \"o\" && xs[2] != \"d\" && xs[2] != \"x\" && xs[2] != \"X\" {\n\t\treturn \"\", 0, errors.New(\"fubar\")\n\t}\n\toffset, err := strconv.Atoi(xs[0])\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\twidth, err := strconv.Atoi(xs[1])\n\tif err != nil {\n\t\treturn \"\", offset, err\n\t}\n\tprintf := \"%\"\n\tswitch {\n\tcase width < 0:\n\t\treturn \"\", offset, errors.New(\"fubar\")\n\tcase width == 0:\n\t\tprintf += xs[1]\n\tdefault:\n\t\tprintf += \"0\" + xs[1]\n\t}\n\tprintf += xs[2]\n\treturn printf, offset, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package controller\n\nimport (\n\t\"fmt\"\n\tmongomodels \"koding\/db\/models\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"socialapi\/models\"\n)\n\nfunc (mwc *Controller) migrateAllTags() error {\n\to := modelhelper.Options{\n\t\tSort: \"meta.createdAt\",\n\t}\n\ts := modelhelper.Selector{\n\t\t\"socialApiChannelId\": modelhelper.Selector{\"$exists\": false},\n\t}\n\terrCount := 0\n\n\thandleError := func(t *mongomodels.Tag, err error) {\n\t\tmwc.log.Error(\"an error occured for %s: %s\", t.Id.Hex(), err)\n\t\terrCount++\n\t}\n\n\tfor {\n\t\to.Skip = errCount\n\t\ttag, err := modelhelper.GetTag(s, o)\n\t\tif err != nil {\n\t\t\tif err == modelhelper.ErrNotFound {\n\t\t\t\tmwc.log.Notice(\"Tag migration completed with %d errors\", errCount)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"tag cannot be fetched: %s\", err)\n\t\t}\n\t\tc, err := createTagChannel(tag)\n\t\tif err != nil {\n\t\t\thandleError(tag, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := completeTagMigration(tag, c); err != nil {\n\t\t\thandleError(tag, err)\n\t\t\tcontinue\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc createTagChannel(t *mongomodels.Tag) (*models.Channel, error) {\n\tcreatorId, err := fetchTagCreatorId(t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := models.NewChannel()\n\tc.CreatorId = creatorId\n\tc.Name = t.Slug\n\tc.GroupName = t.Group \/\/ create group if needed\n\t\/\/ = t.Category \"user-tag\", \"system tag\" mevzusu ama bug isi hala var mi bilmiyorum\n\tc.Purpose = \"Channel for \" + c.Name + \" topic\"\n\tc.TypeConstant = models.Channel_TYPE_TOPIC\n\tc.PrivacyConstant = models.Channel_PRIVACY_PRIVATE\n\tc.CreatedAt = t.Meta.CreatedAt\n\tc.UpdatedAt = t.Meta.ModifiedAt\n\tif err := c.CreateRaw(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n\nfunc fetchTagCreatorId(t *mongomodels.Tag) (int64, error) {\n\ts := modelhelper.Selector{\n\t\t\"sourceId\": t.Id,\n\t\t\"as\":       \"related\",\n\t}\n\tr, err := modelhelper.GetRelationship(s)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"Tag creator cannot be fetched: %s\", err)\n\t}\n\ta := models.NewAccount()\n\ta.OldId = r.TargetId.Hex()\n\n\tif err := a.FetchOrCreate(); err != nil {\n\t\treturn 0, fmt.Errorf(\"Tag creator cannot be created: %s\", err)\n\t}\n\n\treturn a.Id, nil\n}\n\nfunc (mwc *Controller) createTagFollowers(t *mongomodels.Tag, channelId int64) error {\n\n\treturn modelhelper.UpdateTag(tag)\n}\n<commit_msg>Migration: Tag follower migrator is added<commit_after>package controller\n\nimport (\n\t\"fmt\"\n\tmongomodels \"koding\/db\/models\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"socialapi\/models\"\n\n\t\"github.com\/jinzhu\/gorm\"\n)\n\nfunc (mwc *Controller) migrateAllTags() error {\n\to := modelhelper.Options{\n\t\tSort: \"meta.createdAt\",\n\t}\n\ts := modelhelper.Selector{\n\t\t\"socialApiChannelId\": modelhelper.Selector{\"$exists\": false},\n\t}\n\terrCount := 0\n\n\thandleError := func(t *mongomodels.Tag, err error) {\n\t\tmwc.log.Error(\"an error occured for tag %s: %s\", t.Id.Hex(), err)\n\t\terrCount++\n\t}\n\n\tfor {\n\t\to.Skip = errCount\n\t\ttag, err := modelhelper.GetTag(s, o)\n\t\tif err != nil {\n\t\t\tif err == modelhelper.ErrNotFound {\n\t\t\t\tmwc.log.Notice(\"Tag migration completed with %d errors\", errCount)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"tag cannot be fetched: %s\", err)\n\t\t}\n\t\tchannelId, err := createTagChannel(tag)\n\t\tif err != nil {\n\t\t\thandleError(tag, err)\n\t\t\tcontinue\n\t\t}\n\t\tif err := mwc.createTagFollowers(tag, channelId); err != nil {\n\t\t\thandleError(tag, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := completeTagMigration(tag, channelId); err != nil {\n\t\t\thandleError(tag, err)\n\t\t\tcontinue\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc createTagChannel(t *mongomodels.Tag) (int64, error) {\n\tcreatorId, err := fetchTagCreatorId(t)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tc := models.NewChannel()\n\n\tchannelId, err := c.FetchChannelIdByNameAndGroupName(t.Slug, t.Group)\n\tif err == nil {\n\t\treturn channelId, nil\n\t}\n\tif err != gorm.RecordNotFound {\n\t\treturn 0, err\n\t}\n\n\tc.CreatorId = creatorId\n\tc.Name = t.Slug\n\tc.GroupName = t.Group \/\/ create group if needed\n\tc.Purpose = \"Channel for \" + c.Name + \" topic\"\n\tc.TypeConstant = models.Channel_TYPE_TOPIC\n\tc.PrivacyConstant = models.Channel_PRIVACY_PRIVATE\n\tc.CreatedAt = t.Meta.CreatedAt\n\tc.UpdatedAt = t.Meta.ModifiedAt\n\tif err := c.CreateRaw(); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn c.Id, nil\n}\n\nfunc fetchTagCreatorId(t *mongomodels.Tag) (int64, error) {\n\ts := modelhelper.Selector{\n\t\t\"sourceId\": t.Id,\n\t\t\"as\":       \"related\",\n\t}\n\tr, err := modelhelper.GetRelationship(s)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"Tag creator cannot be fetched: %s\", err)\n\t}\n\ta := models.NewAccount()\n\ta.OldId = r.TargetId.Hex()\n\n\tif err := a.FetchOrCreate(); err != nil {\n\t\treturn 0, fmt.Errorf(\"Tag creator cannot be created: %s\", err)\n\t}\n\n\treturn a.Id, nil\n}\n\nfunc (mwc *Controller) createTagFollowers(t *mongomodels.Tag, channelId int64) error {\n\ts := modelhelper.Selector{\n\t\t\"sourceId\":   t.Id,\n\t\t\"as\":         \"follower\",\n\t\t\"targetName\": \"JAccount\",\n\t}\n\titer := modelhelper.GetRelationshipIter(s)\n\tdefer iter.Close()\n\tvar r mongomodels.Relationship\n\tfor iter.Next(&r) {\n\t\tif r.MigrationStatus == \"Completed\" {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ fetch follower\n\t\ta := models.NewAccount()\n\t\ta.OldId = r.TargetId.Hex()\n\t\terr := a.FetchOrCreate()\n\t\tif err != nil {\n\t\t\tmwc.log.Error(\"Tag follower cannot be fetched: %s\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tcp := models.NewChannelParticipant()\n\t\tcp.ChannelId = channelId\n\t\tcp.AccountId = a.Id\n\t\tcp.StatusConstant = models.ChannelParticipant_STATUS_ACTIVE\n\t\tcp.LastSeenAt = r.TimeStamp\n\t\tcp.UpdatedAt = r.TimeStamp\n\t\tcp.CreatedAt = r.TimeStamp\n\t\tif err := cp.CreateRaw(); err != nil {\n\t\t\tmwc.log.Error(\"Tag follower cannot be created: %s\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tr.MigrationStatus = \"Completed\"\n\t\tif err := modelhelper.UpdateRelationship(&r); err != nil {\n\t\t\tmwc.log.Error(\"Tag follower cannot be flagged as migrated: %s\", err)\n\t\t}\n\t}\n\n\treturn iter.Err()\n}\n\nfunc completeTagMigration(tag *mongomodels.Tag, channelId int64) error {\n\ttag.SocialApiChannelId = channelId\n\n\treturn modelhelper.UpdateTag(tag)\n}\n<|endoftext|>"}
{"text":"<commit_before>package filesys\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/seaweedfs\/fuse\"\n\t\"github.com\/seaweedfs\/fuse\/fs\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/filer2\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/filer_pb\"\n)\n\ntype FileHandle struct {\n\t\/\/ cache file has been written to\n\tdirtyPages  *ContinuousDirtyPages\n\tcontentType string\n\thandle      uint64\n\n\tf         *File\n\tRequestId fuse.RequestID \/\/ unique ID for request\n\tNodeId    fuse.NodeID    \/\/ file or directory the request is about\n\tUid       uint32         \/\/ user ID of process making request\n\tGid       uint32         \/\/ group ID of process making request\n\n}\n\nfunc newFileHandle(file *File, uid, gid uint32) *FileHandle {\n\tfh := &FileHandle{\n\t\tf:          file,\n\t\tdirtyPages: newDirtyPages(file),\n\t\tUid:        uid,\n\t\tGid:        gid,\n\t}\n\tif fh.f.entry != nil {\n\t\tfh.f.entry.Attributes.FileSize = filer2.FileSize(fh.f.entry)\n\t}\n\treturn fh\n}\n\nvar _ = fs.Handle(&FileHandle{})\n\n\/\/ var _ = fs.HandleReadAller(&FileHandle{})\nvar _ = fs.HandleReader(&FileHandle{})\nvar _ = fs.HandleFlusher(&FileHandle{})\nvar _ = fs.HandleWriter(&FileHandle{})\nvar _ = fs.HandleReleaser(&FileHandle{})\n\nfunc (fh *FileHandle) Read(ctx context.Context, req *fuse.ReadRequest, resp *fuse.ReadResponse) error {\n\n\tglog.V(4).Infof(\"%s read fh %d: [%d,%d) size %d resp.Data len=%d cap=%d\", fh.f.fullpath(), fh.handle, req.Offset, req.Offset+int64(req.Size), req.Size, len(resp.Data), cap(resp.Data))\n\n\tbuff := resp.Data[:cap(resp.Data)]\n\tif req.Size > cap(resp.Data) {\n\t\t\/\/ should not happen\n\t\tbuff = make([]byte, req.Size)\n\t}\n\n\ttotalRead, err := fh.readFromChunks(buff, req.Offset)\n\tif err == nil {\n\t\tmaxStop := fh.readFromDirtyPages(buff, req.Offset)\n\t\ttotalRead = max(maxStop - req.Offset, totalRead)\n\t}\n\n\ttotalRead = min(int64(len(buff)), totalRead)\n\tresp.Data = buff[:totalRead]\n\n\tif err != nil {\n\t\tglog.Errorf(\"file handle read %s: %v\", fh.f.fullpath(), err)\n\t\treturn fuse.EIO\n\t}\n\n\treturn err\n}\n\nfunc (fh *FileHandle) readFromDirtyPages(buff []byte, startOffset int64) (maxStop int64) {\n\treturn fh.dirtyPages.ReadDirtyData(buff, startOffset)\n}\n\nfunc (fh *FileHandle) readFromChunks(buff []byte, offset int64) (int64, error) {\n\n\tfileSize := int64(filer2.FileSize(fh.f.entry))\n\n\tif fileSize == 0 {\n\t\tglog.V(1).Infof(\"empty fh %v\", fh.f.fullpath())\n\t\treturn 0, io.EOF\n\t}\n\n\tvar chunkResolveErr error\n\tif fh.f.entryViewCache == nil {\n\t\tfh.f.entryViewCache, chunkResolveErr = filer2.NonOverlappingVisibleIntervals(filer2.LookupFn(fh.f.wfs), fh.f.entry.Chunks)\n\t\tif chunkResolveErr != nil {\n\t\t\treturn 0, fmt.Errorf(\"fail to resolve chunk manifest: %v\", chunkResolveErr)\n\t\t}\n\t\tfh.f.reader = nil\n\t}\n\n\tif fh.f.reader == nil {\n\t\tchunkViews := filer2.ViewFromVisibleIntervals(fh.f.entryViewCache, 0, math.MaxInt32)\n\t\tfh.f.reader = filer2.NewChunkReaderAtFromClient(fh.f.wfs, chunkViews, fh.f.wfs.chunkCache, fileSize)\n\t}\n\n\ttotalRead, err := fh.f.reader.ReadAt(buff, offset)\n\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\n\tif err != nil {\n\t\tglog.Errorf(\"file handle read %s: %v\", fh.f.fullpath(), err)\n\t}\n\n\t\/\/ glog.V(0).Infof(\"file handle read %s [%d,%d] %d : %v\", fh.f.fullpath(), offset, offset+int64(totalRead), totalRead, err)\n\n\treturn int64(totalRead), err\n}\n\n\/\/ Write to the file handle\nfunc (fh *FileHandle) Write(ctx context.Context, req *fuse.WriteRequest, resp *fuse.WriteResponse) error {\n\n\t\/\/ write the request to volume servers\n\tdata := make([]byte, len(req.Data))\n\tcopy(data, req.Data)\n\n\tfh.f.entry.Attributes.FileSize = uint64(max(req.Offset+int64(len(data)), int64(fh.f.entry.Attributes.FileSize)))\n\tglog.V(5).Infof(\"%v write [%d,%d)\", fh.f.fullpath(), req.Offset, req.Offset+int64(len(req.Data)))\n\n\tchunks, err := fh.dirtyPages.AddPage(req.Offset, data)\n\tif err != nil {\n\t\tglog.Errorf(\"%v write fh %d: [%d,%d): %v\", fh.f.fullpath(), fh.handle, req.Offset, req.Offset+int64(len(data)), err)\n\t\treturn fuse.EIO\n\t}\n\n\tresp.Size = len(data)\n\n\tif req.Offset == 0 {\n\t\t\/\/ detect mime type\n\t\tfh.contentType = http.DetectContentType(data)\n\t\tfh.f.dirtyMetadata = true\n\t}\n\n\tif len(chunks) > 0 {\n\n\t\tfh.f.addChunks(chunks)\n\n\t\tfh.f.dirtyMetadata = true\n\t}\n\n\treturn nil\n}\n\nfunc (fh *FileHandle) Release(ctx context.Context, req *fuse.ReleaseRequest) error {\n\n\tglog.V(4).Infof(\"Release %v fh %d\", fh.f.fullpath(), fh.handle)\n\n\tfh.f.isOpen--\n\n\tif fh.f.isOpen <= 0 {\n\t\tfh.dirtyPages.releaseResource()\n\t\tfh.f.wfs.ReleaseHandle(fh.f.fullpath(), fuse.HandleID(fh.handle))\n\t}\n\tfh.f.entryViewCache = nil\n\tfh.f.reader = nil\n\n\treturn nil\n}\n\nfunc (fh *FileHandle) Flush(ctx context.Context, req *fuse.FlushRequest) error {\n\t\/\/ fflush works at fh level\n\t\/\/ send the data to the OS\n\tglog.V(5).Infof(\"Flush %s fh %d %v\", fh.f.fullpath(), fh.handle, req)\n\n\tchunks, err := fh.dirtyPages.FlushToStorage()\n\tif err != nil {\n\t\tglog.Errorf(\"flush %s: %v\", fh.f.fullpath(), err)\n\t\treturn fuse.EIO\n\t}\n\n\tif len(chunks) > 0 {\n\t\tfh.f.addChunks(chunks)\n\t\tfh.f.dirtyMetadata = true\n\t}\n\n\tif !fh.f.dirtyMetadata {\n\t\treturn nil\n\t}\n\n\terr = fh.f.wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {\n\n\t\tif fh.f.entry.Attributes != nil {\n\t\t\tfh.f.entry.Attributes.Mime = fh.contentType\n\t\t\tif fh.f.entry.Attributes.Uid == 0 {\n\t\t\t\tfh.f.entry.Attributes.Uid = req.Uid\n\t\t\t}\n\t\t\tif fh.f.entry.Attributes.Gid == 0 {\n\t\t\t\tfh.f.entry.Attributes.Gid = req.Gid\n\t\t\t}\n\t\t\tif fh.f.entry.Attributes.Crtime == 0 {\n\t\t\t\tfh.f.entry.Attributes.Crtime = time.Now().Unix()\n\t\t\t}\n\t\t\tfh.f.entry.Attributes.Mtime = time.Now().Unix()\n\t\t\tfh.f.entry.Attributes.FileMode = uint32(os.FileMode(fh.f.entry.Attributes.FileMode) &^ fh.f.wfs.option.Umask)\n\t\t\tfh.f.entry.Attributes.Collection = fh.dirtyPages.collection\n\t\t\tfh.f.entry.Attributes.Replication = fh.dirtyPages.replication\n\t\t}\n\n\t\trequest := &filer_pb.CreateEntryRequest{\n\t\t\tDirectory: fh.f.dir.FullPath(),\n\t\t\tEntry:     fh.f.entry,\n\t\t}\n\n\t\tglog.V(4).Infof(\"%s set chunks: %v\", fh.f.fullpath(), len(fh.f.entry.Chunks))\n\t\tfor i, chunk := range fh.f.entry.Chunks {\n\t\t\tglog.V(4).Infof(\"%s chunks %d: %v [%d,%d)\", fh.f.fullpath(), i, chunk.GetFileIdString(), chunk.Offset, chunk.Offset+int64(chunk.Size))\n\t\t}\n\n\t\tchunks, garbages := filer2.CompactFileChunks(filer2.LookupFn(fh.f.wfs), fh.f.entry.Chunks)\n\t\tchunks, manifestErr := filer2.MaybeManifestize(fh.f.wfs.saveDataAsChunk(fh.f.dir.FullPath()), chunks)\n\t\tif manifestErr != nil {\n\t\t\t\/\/ not good, but should be ok\n\t\t\tglog.V(0).Infof(\"MaybeManifestize: %v\", manifestErr)\n\t\t}\n\t\tfh.f.entry.Chunks = chunks\n\t\t\/\/ fh.f.entryViewCache = nil\n\n\t\t\/\/ special handling of one chunk md5\n\t\tif len(chunks) == 1 {\n\t\t}\n\n\t\tif err := filer_pb.CreateEntry(client, request); err != nil {\n\t\t\tglog.Errorf(\"fh flush create %s: %v\", fh.f.fullpath(), err)\n\t\t\treturn fmt.Errorf(\"fh flush create %s: %v\", fh.f.fullpath(), err)\n\t\t}\n\n\t\tfh.f.wfs.metaCache.InsertEntry(context.Background(), filer2.FromPbEntry(request.Directory, request.Entry))\n\n\t\tfh.f.wfs.deleteFileChunks(garbages)\n\t\tfor i, chunk := range garbages {\n\t\t\tglog.V(4).Infof(\"garbage %s chunks %d: %v [%d,%d)\", fh.f.fullpath(), i, chunk.GetFileIdString(), chunk.Offset, chunk.Offset+int64(chunk.Size))\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err == nil {\n\t\tfh.f.dirtyMetadata = false\n\t}\n\n\tif err != nil {\n\t\tglog.Errorf(\"%v fh %d flush: %v\", fh.f.fullpath(), fh.handle, err)\n\t\treturn fuse.EIO\n\t}\n\n\treturn nil\n}\n<commit_msg>report error first<commit_after>package filesys\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/seaweedfs\/fuse\"\n\t\"github.com\/seaweedfs\/fuse\/fs\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/filer2\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/filer_pb\"\n)\n\ntype FileHandle struct {\n\t\/\/ cache file has been written to\n\tdirtyPages  *ContinuousDirtyPages\n\tcontentType string\n\thandle      uint64\n\n\tf         *File\n\tRequestId fuse.RequestID \/\/ unique ID for request\n\tNodeId    fuse.NodeID    \/\/ file or directory the request is about\n\tUid       uint32         \/\/ user ID of process making request\n\tGid       uint32         \/\/ group ID of process making request\n\n}\n\nfunc newFileHandle(file *File, uid, gid uint32) *FileHandle {\n\tfh := &FileHandle{\n\t\tf:          file,\n\t\tdirtyPages: newDirtyPages(file),\n\t\tUid:        uid,\n\t\tGid:        gid,\n\t}\n\tif fh.f.entry != nil {\n\t\tfh.f.entry.Attributes.FileSize = filer2.FileSize(fh.f.entry)\n\t}\n\treturn fh\n}\n\nvar _ = fs.Handle(&FileHandle{})\n\n\/\/ var _ = fs.HandleReadAller(&FileHandle{})\nvar _ = fs.HandleReader(&FileHandle{})\nvar _ = fs.HandleFlusher(&FileHandle{})\nvar _ = fs.HandleWriter(&FileHandle{})\nvar _ = fs.HandleReleaser(&FileHandle{})\n\nfunc (fh *FileHandle) Read(ctx context.Context, req *fuse.ReadRequest, resp *fuse.ReadResponse) error {\n\n\tglog.V(4).Infof(\"%s read fh %d: [%d,%d) size %d resp.Data len=%d cap=%d\", fh.f.fullpath(), fh.handle, req.Offset, req.Offset+int64(req.Size), req.Size, len(resp.Data), cap(resp.Data))\n\n\tbuff := resp.Data[:cap(resp.Data)]\n\tif req.Size > cap(resp.Data) {\n\t\t\/\/ should not happen\n\t\tbuff = make([]byte, req.Size)\n\t}\n\n\ttotalRead, err := fh.readFromChunks(buff, req.Offset)\n\tif err == nil {\n\t\tmaxStop := fh.readFromDirtyPages(buff, req.Offset)\n\t\ttotalRead = max(maxStop - req.Offset, totalRead)\n\t}\n\n\tif err != nil {\n\t\tglog.Errorf(\"file handle read %s: %v\", fh.f.fullpath(), err)\n\t\treturn fuse.EIO\n\t}\n\n\ttotalRead = min(int64(len(buff)), totalRead)\n\tresp.Data = buff[:totalRead]\n\n\treturn err\n}\n\nfunc (fh *FileHandle) readFromDirtyPages(buff []byte, startOffset int64) (maxStop int64) {\n\treturn fh.dirtyPages.ReadDirtyData(buff, startOffset)\n}\n\nfunc (fh *FileHandle) readFromChunks(buff []byte, offset int64) (int64, error) {\n\n\tfileSize := int64(filer2.FileSize(fh.f.entry))\n\n\tif fileSize == 0 {\n\t\tglog.V(1).Infof(\"empty fh %v\", fh.f.fullpath())\n\t\treturn 0, io.EOF\n\t}\n\n\tvar chunkResolveErr error\n\tif fh.f.entryViewCache == nil {\n\t\tfh.f.entryViewCache, chunkResolveErr = filer2.NonOverlappingVisibleIntervals(filer2.LookupFn(fh.f.wfs), fh.f.entry.Chunks)\n\t\tif chunkResolveErr != nil {\n\t\t\treturn 0, fmt.Errorf(\"fail to resolve chunk manifest: %v\", chunkResolveErr)\n\t\t}\n\t\tfh.f.reader = nil\n\t}\n\n\tif fh.f.reader == nil {\n\t\tchunkViews := filer2.ViewFromVisibleIntervals(fh.f.entryViewCache, 0, math.MaxInt32)\n\t\tfh.f.reader = filer2.NewChunkReaderAtFromClient(fh.f.wfs, chunkViews, fh.f.wfs.chunkCache, fileSize)\n\t}\n\n\ttotalRead, err := fh.f.reader.ReadAt(buff, offset)\n\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\n\tif err != nil {\n\t\tglog.Errorf(\"file handle read %s: %v\", fh.f.fullpath(), err)\n\t}\n\n\t\/\/ glog.V(0).Infof(\"file handle read %s [%d,%d] %d : %v\", fh.f.fullpath(), offset, offset+int64(totalRead), totalRead, err)\n\n\treturn int64(totalRead), err\n}\n\n\/\/ Write to the file handle\nfunc (fh *FileHandle) Write(ctx context.Context, req *fuse.WriteRequest, resp *fuse.WriteResponse) error {\n\n\t\/\/ write the request to volume servers\n\tdata := make([]byte, len(req.Data))\n\tcopy(data, req.Data)\n\n\tfh.f.entry.Attributes.FileSize = uint64(max(req.Offset+int64(len(data)), int64(fh.f.entry.Attributes.FileSize)))\n\tglog.V(5).Infof(\"%v write [%d,%d)\", fh.f.fullpath(), req.Offset, req.Offset+int64(len(req.Data)))\n\n\tchunks, err := fh.dirtyPages.AddPage(req.Offset, data)\n\tif err != nil {\n\t\tglog.Errorf(\"%v write fh %d: [%d,%d): %v\", fh.f.fullpath(), fh.handle, req.Offset, req.Offset+int64(len(data)), err)\n\t\treturn fuse.EIO\n\t}\n\n\tresp.Size = len(data)\n\n\tif req.Offset == 0 {\n\t\t\/\/ detect mime type\n\t\tfh.contentType = http.DetectContentType(data)\n\t\tfh.f.dirtyMetadata = true\n\t}\n\n\tif len(chunks) > 0 {\n\n\t\tfh.f.addChunks(chunks)\n\n\t\tfh.f.dirtyMetadata = true\n\t}\n\n\treturn nil\n}\n\nfunc (fh *FileHandle) Release(ctx context.Context, req *fuse.ReleaseRequest) error {\n\n\tglog.V(4).Infof(\"Release %v fh %d\", fh.f.fullpath(), fh.handle)\n\n\tfh.f.isOpen--\n\n\tif fh.f.isOpen <= 0 {\n\t\tfh.dirtyPages.releaseResource()\n\t\tfh.f.wfs.ReleaseHandle(fh.f.fullpath(), fuse.HandleID(fh.handle))\n\t}\n\tfh.f.entryViewCache = nil\n\tfh.f.reader = nil\n\n\treturn nil\n}\n\nfunc (fh *FileHandle) Flush(ctx context.Context, req *fuse.FlushRequest) error {\n\t\/\/ fflush works at fh level\n\t\/\/ send the data to the OS\n\tglog.V(5).Infof(\"Flush %s fh %d %v\", fh.f.fullpath(), fh.handle, req)\n\n\tchunks, err := fh.dirtyPages.FlushToStorage()\n\tif err != nil {\n\t\tglog.Errorf(\"flush %s: %v\", fh.f.fullpath(), err)\n\t\treturn fuse.EIO\n\t}\n\n\tif len(chunks) > 0 {\n\t\tfh.f.addChunks(chunks)\n\t\tfh.f.dirtyMetadata = true\n\t}\n\n\tif !fh.f.dirtyMetadata {\n\t\treturn nil\n\t}\n\n\terr = fh.f.wfs.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {\n\n\t\tif fh.f.entry.Attributes != nil {\n\t\t\tfh.f.entry.Attributes.Mime = fh.contentType\n\t\t\tif fh.f.entry.Attributes.Uid == 0 {\n\t\t\t\tfh.f.entry.Attributes.Uid = req.Uid\n\t\t\t}\n\t\t\tif fh.f.entry.Attributes.Gid == 0 {\n\t\t\t\tfh.f.entry.Attributes.Gid = req.Gid\n\t\t\t}\n\t\t\tif fh.f.entry.Attributes.Crtime == 0 {\n\t\t\t\tfh.f.entry.Attributes.Crtime = time.Now().Unix()\n\t\t\t}\n\t\t\tfh.f.entry.Attributes.Mtime = time.Now().Unix()\n\t\t\tfh.f.entry.Attributes.FileMode = uint32(os.FileMode(fh.f.entry.Attributes.FileMode) &^ fh.f.wfs.option.Umask)\n\t\t\tfh.f.entry.Attributes.Collection = fh.dirtyPages.collection\n\t\t\tfh.f.entry.Attributes.Replication = fh.dirtyPages.replication\n\t\t}\n\n\t\trequest := &filer_pb.CreateEntryRequest{\n\t\t\tDirectory: fh.f.dir.FullPath(),\n\t\t\tEntry:     fh.f.entry,\n\t\t}\n\n\t\tglog.V(4).Infof(\"%s set chunks: %v\", fh.f.fullpath(), len(fh.f.entry.Chunks))\n\t\tfor i, chunk := range fh.f.entry.Chunks {\n\t\t\tglog.V(4).Infof(\"%s chunks %d: %v [%d,%d)\", fh.f.fullpath(), i, chunk.GetFileIdString(), chunk.Offset, chunk.Offset+int64(chunk.Size))\n\t\t}\n\n\t\tchunks, garbages := filer2.CompactFileChunks(filer2.LookupFn(fh.f.wfs), fh.f.entry.Chunks)\n\t\tchunks, manifestErr := filer2.MaybeManifestize(fh.f.wfs.saveDataAsChunk(fh.f.dir.FullPath()), chunks)\n\t\tif manifestErr != nil {\n\t\t\t\/\/ not good, but should be ok\n\t\t\tglog.V(0).Infof(\"MaybeManifestize: %v\", manifestErr)\n\t\t}\n\t\tfh.f.entry.Chunks = chunks\n\t\t\/\/ fh.f.entryViewCache = nil\n\n\t\t\/\/ special handling of one chunk md5\n\t\tif len(chunks) == 1 {\n\t\t}\n\n\t\tif err := filer_pb.CreateEntry(client, request); err != nil {\n\t\t\tglog.Errorf(\"fh flush create %s: %v\", fh.f.fullpath(), err)\n\t\t\treturn fmt.Errorf(\"fh flush create %s: %v\", fh.f.fullpath(), err)\n\t\t}\n\n\t\tfh.f.wfs.metaCache.InsertEntry(context.Background(), filer2.FromPbEntry(request.Directory, request.Entry))\n\n\t\tfh.f.wfs.deleteFileChunks(garbages)\n\t\tfor i, chunk := range garbages {\n\t\t\tglog.V(4).Infof(\"garbage %s chunks %d: %v [%d,%d)\", fh.f.fullpath(), i, chunk.GetFileIdString(), chunk.Offset, chunk.Offset+int64(chunk.Size))\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err == nil {\n\t\tfh.f.dirtyMetadata = false\n\t}\n\n\tif err != nil {\n\t\tglog.Errorf(\"%v fh %d flush: %v\", fh.f.fullpath(), fh.handle, err)\n\t\treturn fuse.EIO\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package whirlytubes\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"net\"\n\t\"regexp\"\n)\n\ntype Address interface {\n\tSend(string) error\n\tReceive() (string, error)\n\tVerify() (bool, error)\n}\n\ntype TcpAddress struct {\n\tAddr string\n\tCnxn net.TCPConn\n}\n\nfunc (addr TcpAddress) Verify() (b bool, err error) {\n\tb, err = regexp.MatchString(\".*:.*\", addr.Addr) \/\/fix connection for address, store connection in address\n\treturn\n}\n\nfunc (addr TcpAddress) Send(msg string) (err error) {\n\tconn, err := net.Dial(\"tcp\", addr.Addr)\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = fmt.Fprint(conn, msg) \/\/add writing capabilities\n}\n\nfunc (addr TcpAddress) Receive() (msg string, err error) {\n\tconn, err := net.Dial(\"tcp\", addr.Addr)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tmsg, err := bufio.NewReader(conn).ReadString('\\n')\n\treturn\n}\n<commit_msg>added init function for addresses<commit_after>package whirlytubes\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"net\"\n\t\"regexp\"\n)\n\ntype Address interface {\n\tSend(string) error\n\tReceive() (string, error)\n\tverify() (bool, error)\n\tInit(string) error\n}\n\ntype TcpAddress struct {\n\tAddr string\n\tCnxn net.TCPConn\n}\n\nfunc (addr TcpAddress) verify() (b bool, err error) {\n\tb, err = regexp.MatchString(\".*:.*\", addr.Addr) \/\/fix connection for address, store connection in address\n\treturn\n}\n\nfunc (addr TcpAddress) Init(a string) error {\n\taddr.Addr = a\n\tb, err := addr.verify()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !b {\n\t\taddr.Addr = nil\n\t\treturn fmt.Errorf(\"Address Initialization: malformed address: %s\\n\\tshould be I.P.add.ress:port\\n\", a)\n\t}\n\treturn nil\n}\nfunc (addr TcpAddress) Send(msg string) (err error) {\n\tconn, err := net.Dial(\"tcp\", addr.Addr)\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = fmt.Fprint(conn, msg) \/\/add writing capabilities\n}\n\nfunc (addr TcpAddress) Receive() (msg string, err error) {\n\tconn, err := net.Dial(\"tcp\", addr.Addr)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tmsg, err := bufio.NewReader(conn).ReadString('\\n')\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Marking experiment failed when suggestion fails (#773)<commit_after><|endoftext|>"}
{"text":"<commit_before>package healthsyncer\n\nimport (\n\t\"context\"\n\t\"reflect\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/rancher\/norman\/condition\"\n\tv32 \"github.com\/rancher\/rancher\/pkg\/apis\/management.cattle.io\/v3\"\n\tcorev1 \"github.com\/rancher\/rancher\/pkg\/generated\/norman\/core\/v1\"\n\tv3 \"github.com\/rancher\/rancher\/pkg\/generated\/norman\/management.cattle.io\/v3\"\n\t\"github.com\/rancher\/rancher\/pkg\/types\/config\"\n\t\"github.com\/rancher\/wrangler\/pkg\/ticker\"\n\t\"github.com\/sirupsen\/logrus\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tapierrors \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/client-go\/kubernetes\"\n)\n\nconst (\n\tsyncInterval = 15 * time.Second\n)\n\ntype ClusterControllerLifecycle interface {\n\tStop(cluster *v3.Cluster)\n}\n\ntype HealthSyncer struct {\n\tctx               context.Context\n\tclusterName       string\n\tclusterLister     v3.ClusterLister\n\tclusters          v3.ClusterInterface\n\tcomponentStatuses corev1.ComponentStatusInterface\n\tnamespaces        corev1.NamespaceInterface\n\tk8s               kubernetes.Interface\n}\n\nfunc Register(ctx context.Context, workload *config.UserContext) {\n\th := &HealthSyncer{\n\t\tctx:               ctx,\n\t\tclusterName:       workload.ClusterName,\n\t\tclusterLister:     workload.Management.Management.Clusters(\"\").Controller().Lister(),\n\t\tclusters:          workload.Management.Management.Clusters(\"\"),\n\t\tcomponentStatuses: workload.Core.ComponentStatuses(\"\"),\n\t\tnamespaces:        workload.Core.Namespaces(\"\"),\n\t\tk8s:               workload.K8sClient,\n\t}\n\n\tgo h.syncHealth(ctx, syncInterval)\n}\n\nfunc (h *HealthSyncer) syncHealth(ctx context.Context, syncHealth time.Duration) {\n\tfor range ticker.Context(ctx, syncHealth) {\n\t\terr := h.updateClusterHealth()\n\t\tif err != nil && !apierrors.IsConflict(err) {\n\t\t\tlogrus.Error(err)\n\t\t}\n\t}\n}\n\nfunc (h *HealthSyncer) getComponentStatus(cluster *v3.Cluster) error {\n\tctx, cancel := context.WithTimeout(h.ctx, 5*time.Second)\n\tdefer cancel()\n\n\t\/\/ Prior to k8s v1.14, we only needed to list the ComponentStatuses from the user cluster.\n\t\/\/ As of k8s v1.14, kubeapi returns a successful ComponentStatuses response even if etcd is not available.\n\t\/\/ To work around this, now we try to get a namespace from the API, even if not found, it means the API is up.\n\tif _, err := h.k8s.CoreV1().Namespaces().Get(ctx, \"kube-system\", metav1.GetOptions{}); err != nil && !apierrors.IsNotFound(err) {\n\t\treturn condition.Error(\"ComponentStatsFetchingFailure\", errors.Wrap(err, \"Failed to communicate with API server\"))\n\t}\n\n\tcses, err := h.componentStatuses.List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn condition.Error(\"ComponentStatsFetchingFailure\", errors.Wrap(err, \"Failed to communicate with API server\"))\n\t}\n\tcluster.Status.ComponentStatuses = []v32.ClusterComponentStatus{}\n\tfor _, cs := range cses.Items {\n\t\tclusterCS := convertToClusterComponentStatus(&cs)\n\t\tcluster.Status.ComponentStatuses = append(cluster.Status.ComponentStatuses, *clusterCS)\n\t}\n\tsort.Slice(cluster.Status.ComponentStatuses, func(i, j int) bool {\n\t\treturn cluster.Status.ComponentStatuses[i].Name < cluster.Status.ComponentStatuses[j].Name\n\t})\n\treturn nil\n}\n\nfunc (h *HealthSyncer) updateClusterHealth() error {\n\toldCluster, err := h.getCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcluster := oldCluster.DeepCopy()\n\tif !v32.ClusterConditionProvisioned.IsTrue(cluster) {\n\t\tlogrus.Debugf(\"Skip updating cluster health - cluster [%s] not provisioned yet\", h.clusterName)\n\t\treturn nil\n\t}\n\n\tnewObj, err := v32.ClusterConditionReady.Do(cluster, func() (runtime.Object, error) {\n\t\tfor i := 0; ; i++ {\n\t\t\terr := h.getComponentStatus(cluster)\n\t\t\tif err == nil || i > 1 {\n\t\t\t\treturn cluster, errors.Wrap(err, \"cluster health check failed\")\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-h.ctx.Done():\n\t\t\t\treturn cluster, err\n\t\t\tcase <-time.After(5 * time.Second):\n\t\t\t}\n\t\t}\n\t})\n\n\tif err == nil {\n\t\tv32.ClusterConditionWaiting.True(newObj)\n\t\tv32.ClusterConditionWaiting.Message(newObj, \"\")\n\t}\n\n\tif !reflect.DeepEqual(oldCluster, newObj) {\n\t\tif _, err := h.clusters.Update(newObj.(*v3.Cluster)); err != nil {\n\t\t\treturn errors.Wrapf(err, \"[updateClusterHealth] Failed to update cluster [%s]\", cluster.Name)\n\t\t}\n\t}\n\n\t\/\/ Purposefully not return error.  This is so when the cluster goes unavailable we don't just keep failing\n\t\/\/ which will essentially keep the controller alive forever, instead of shutting down.\n\treturn nil\n}\n\nfunc (h *HealthSyncer) getCluster() (*v3.Cluster, error) {\n\treturn h.clusterLister.Get(\"\", h.clusterName)\n}\n\nfunc convertToClusterComponentStatus(cs *v1.ComponentStatus) *v32.ClusterComponentStatus {\n\treturn &v32.ClusterComponentStatus{\n\t\tName:       cs.Name,\n\t\tConditions: cs.Conditions,\n\t}\n}\n<commit_msg>Update error message to be more explicit<commit_after>package healthsyncer\n\nimport (\n\t\"context\"\n\t\"reflect\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/rancher\/norman\/condition\"\n\tv32 \"github.com\/rancher\/rancher\/pkg\/apis\/management.cattle.io\/v3\"\n\tcorev1 \"github.com\/rancher\/rancher\/pkg\/generated\/norman\/core\/v1\"\n\tv3 \"github.com\/rancher\/rancher\/pkg\/generated\/norman\/management.cattle.io\/v3\"\n\t\"github.com\/rancher\/rancher\/pkg\/types\/config\"\n\t\"github.com\/rancher\/wrangler\/pkg\/ticker\"\n\t\"github.com\/sirupsen\/logrus\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tapierrors \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/client-go\/kubernetes\"\n)\n\nconst (\n\tsyncInterval = 15 * time.Second\n)\n\ntype ClusterControllerLifecycle interface {\n\tStop(cluster *v3.Cluster)\n}\n\ntype HealthSyncer struct {\n\tctx               context.Context\n\tclusterName       string\n\tclusterLister     v3.ClusterLister\n\tclusters          v3.ClusterInterface\n\tcomponentStatuses corev1.ComponentStatusInterface\n\tnamespaces        corev1.NamespaceInterface\n\tk8s               kubernetes.Interface\n}\n\nfunc Register(ctx context.Context, workload *config.UserContext) {\n\th := &HealthSyncer{\n\t\tctx:               ctx,\n\t\tclusterName:       workload.ClusterName,\n\t\tclusterLister:     workload.Management.Management.Clusters(\"\").Controller().Lister(),\n\t\tclusters:          workload.Management.Management.Clusters(\"\"),\n\t\tcomponentStatuses: workload.Core.ComponentStatuses(\"\"),\n\t\tnamespaces:        workload.Core.Namespaces(\"\"),\n\t\tk8s:               workload.K8sClient,\n\t}\n\n\tgo h.syncHealth(ctx, syncInterval)\n}\n\nfunc (h *HealthSyncer) syncHealth(ctx context.Context, syncHealth time.Duration) {\n\tfor range ticker.Context(ctx, syncHealth) {\n\t\terr := h.updateClusterHealth()\n\t\tif err != nil && !apierrors.IsConflict(err) {\n\t\t\tlogrus.Error(err)\n\t\t}\n\t}\n}\n\nfunc (h *HealthSyncer) getComponentStatus(cluster *v3.Cluster) error {\n\tctx, cancel := context.WithTimeout(h.ctx, 5*time.Second)\n\tdefer cancel()\n\n\t\/\/ Prior to k8s v1.14, we only needed to list the ComponentStatuses from the user cluster.\n\t\/\/ As of k8s v1.14, kubeapi returns a successful ComponentStatuses response even if etcd is not available.\n\t\/\/ To work around this, now we try to get a namespace from the API, even if not found, it means the API is up.\n\tif _, err := h.k8s.CoreV1().Namespaces().Get(ctx, \"kube-system\", metav1.GetOptions{}); err != nil && !apierrors.IsNotFound(err) {\n\t\treturn condition.Error(\"ComponentStatsFetchingFailure\", errors.Wrap(err, \"Failed to communicate with API server during namespace check\"))\n\t}\n\n\tcses, err := h.componentStatuses.List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn condition.Error(\"ComponentStatsFetchingFailure\", errors.Wrap(err, \"Failed to communicate with API server\"))\n\t}\n\tcluster.Status.ComponentStatuses = []v32.ClusterComponentStatus{}\n\tfor _, cs := range cses.Items {\n\t\tclusterCS := convertToClusterComponentStatus(&cs)\n\t\tcluster.Status.ComponentStatuses = append(cluster.Status.ComponentStatuses, *clusterCS)\n\t}\n\tsort.Slice(cluster.Status.ComponentStatuses, func(i, j int) bool {\n\t\treturn cluster.Status.ComponentStatuses[i].Name < cluster.Status.ComponentStatuses[j].Name\n\t})\n\treturn nil\n}\n\nfunc (h *HealthSyncer) updateClusterHealth() error {\n\toldCluster, err := h.getCluster()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcluster := oldCluster.DeepCopy()\n\tif !v32.ClusterConditionProvisioned.IsTrue(cluster) {\n\t\tlogrus.Debugf(\"Skip updating cluster health - cluster [%s] not provisioned yet\", h.clusterName)\n\t\treturn nil\n\t}\n\n\tnewObj, err := v32.ClusterConditionReady.Do(cluster, func() (runtime.Object, error) {\n\t\tfor i := 0; ; i++ {\n\t\t\terr := h.getComponentStatus(cluster)\n\t\t\tif err == nil || i > 1 {\n\t\t\t\treturn cluster, errors.Wrap(err, \"cluster health check failed\")\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase <-h.ctx.Done():\n\t\t\t\treturn cluster, err\n\t\t\tcase <-time.After(5 * time.Second):\n\t\t\t}\n\t\t}\n\t})\n\n\tif err == nil {\n\t\tv32.ClusterConditionWaiting.True(newObj)\n\t\tv32.ClusterConditionWaiting.Message(newObj, \"\")\n\t}\n\n\tif !reflect.DeepEqual(oldCluster, newObj) {\n\t\tif _, err := h.clusters.Update(newObj.(*v3.Cluster)); err != nil {\n\t\t\treturn errors.Wrapf(err, \"[updateClusterHealth] Failed to update cluster [%s]\", cluster.Name)\n\t\t}\n\t}\n\n\t\/\/ Purposefully not return error.  This is so when the cluster goes unavailable we don't just keep failing\n\t\/\/ which will essentially keep the controller alive forever, instead of shutting down.\n\treturn nil\n}\n\nfunc (h *HealthSyncer) getCluster() (*v3.Cluster, error) {\n\treturn h.clusterLister.Get(\"\", h.clusterName)\n}\n\nfunc convertToClusterComponentStatus(cs *v1.ComponentStatus) *v32.ClusterComponentStatus {\n\treturn &v32.ClusterComponentStatus{\n\t\tName:       cs.Name,\n\t\tConditions: cs.Conditions,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"os\"\n)\n\n\/\/ TODO Comment it to make it understandable\n\/\/ Mention the spec at https:\/\/github.com\/composer\/satis\/blob\/master\/res\/satis-schema.json\n\/\/ and why we don't implement it here (we are running repositories code only)\n\n\/\/ Satis reflects the a Satis configuration file.\ntype Satis struct {\n\t\/\/ config is the configuration provider object that has read the satis configuration file\n\tconfig Provider\n\t\/\/ List of repositories\n\trepositories map[string]SatisRepository\n}\n\n\/\/ SatisRepository reflects a single repository entry in satis `repositories` section\ntype SatisRepository struct {\n\t\/\/ Type is the repository type, like `git` or `svn`\n\tType string `json:\"type\"`\n\t\/\/ URL is the URL of the repository that contains packages\n\tURL string `json:\"url\"`\n}\n\n\/\/ NewSatis will create a new satis configuration object.\n\/\/ If no configuration is given, an error will be returned.\nfunc NewSatis(c Provider) (*Satis, error) {\n\tif c == nil {\n\t\treturn nil, errors.New(\"No conifguration provider applied\")\n\t}\n\n\t\/\/ Read initial repositories\n\trepositories := []SatisRepository{}\n\tif v := c.Get(\"repositories\").(*json.RawMessage); v != nil {\n\t\terr := json.Unmarshal(*v, &repositories)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Deduplicate the repositories\n\tm := map[string]SatisRepository{}\n\tfor _, v := range repositories {\n\t\tm[v.URL] = v\n\t}\n\n\ts := &Satis{\n\t\tconfig:       c,\n\t\trepositories: m,\n\t}\n\treturn s, nil\n}\n\nfunc (s *Satis) AddRepository(u string) {\n\tr := SatisRepository{\n\t\tType: \"git\",\n\t\tURL:  u,\n\t}\n\n\ts.repositories[r.URL] = r\n}\n\nfunc (s *Satis) AddRepositories(u ...string) {\n\tfor _, r := range u {\n\t\ts.AddRepository(r)\n\t}\n}\n\nfunc (s *Satis) WriteFile(filename string, perm os.FileMode) error {\n\tcontentMap := s.config.GetContentMap()\n\tm := make(map[string]*json.RawMessage, len(contentMap))\n\tfor k, v := range contentMap {\n\t\tt := v.(json.RawMessage)\n\t\tm[k] = &t\n\t}\n\n\trepositories := s.GetRepositoriesAsSlice()\n\trawRepositories, err := json.MarshalIndent(&repositories, \"\", \"    \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tjsonRepositories := json.RawMessage(rawRepositories)\n\tm[\"repositories\"] = &jsonRepositories\n\n\tb, err := json.MarshalIndent(&m, \"\", \"    \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(filename, b, perm)\n}\n\nfunc (s *Satis) GetRepositoriesAsSlice() []SatisRepository {\n\tc := make([]SatisRepository, 0, len(s.repositories))\n\tfor _, value := range s.repositories {\n\t\tc = append(c, value)\n\t}\n\n\treturn c\n}\n<commit_msg>Add comment about viper PR to write a file<commit_after>package config\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"os\"\n)\n\n\/\/ TODO Comment it to make it understandable\n\/\/ Mention the spec at https:\/\/github.com\/composer\/satis\/blob\/master\/res\/satis-schema.json\n\/\/ and why we don't implement it here (we are running repositories code only)\n\n\/\/ Satis reflects the a Satis configuration file.\ntype Satis struct {\n\t\/\/ config is the configuration provider object that has read the satis configuration file\n\tconfig Provider\n\t\/\/ List of repositories\n\trepositories map[string]SatisRepository\n}\n\n\/\/ SatisRepository reflects a single repository entry in satis `repositories` section\ntype SatisRepository struct {\n\t\/\/ Type is the repository type, like `git` or `svn`\n\tType string `json:\"type\"`\n\t\/\/ URL is the URL of the repository that contains packages\n\tURL string `json:\"url\"`\n}\n\n\/\/ NewSatis will create a new satis configuration object.\n\/\/ If no configuration is given, an error will be returned.\nfunc NewSatis(c Provider) (*Satis, error) {\n\tif c == nil {\n\t\treturn nil, errors.New(\"No conifguration provider applied\")\n\t}\n\n\t\/\/ Read initial repositories\n\trepositories := []SatisRepository{}\n\tif v := c.Get(\"repositories\").(*json.RawMessage); v != nil {\n\t\terr := json.Unmarshal(*v, &repositories)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Deduplicate the repositories\n\tm := map[string]SatisRepository{}\n\tfor _, v := range repositories {\n\t\tm[v.URL] = v\n\t}\n\n\ts := &Satis{\n\t\tconfig:       c,\n\t\trepositories: m,\n\t}\n\treturn s, nil\n}\n\nfunc (s *Satis) AddRepository(u string) {\n\tr := SatisRepository{\n\t\tType: \"git\",\n\t\tURL:  u,\n\t}\n\n\ts.repositories[r.URL] = r\n}\n\nfunc (s *Satis) AddRepositories(u ...string) {\n\tfor _, r := range u {\n\t\ts.AddRepository(r)\n\t}\n}\n\n\nfunc (s *Satis) WriteFile(filename string, perm os.FileMode) error {\n\n\t\/\/ We maintain the Satis configuration file on our own.\n\t\/\/ This is not managed by viper.\n\t\/\/ Maybe it make sense to switch this in feature.\n\t\/\/ Viper is not able to write configuration files (yet).\n\t\/\/ A PR is available for this. See https:\/\/github.com\/spf13\/viper\/pull\/287\n\n\tcontentMap := s.config.GetContentMap()\n\tm := make(map[string]*json.RawMessage, len(contentMap))\n\tfor k, v := range contentMap {\n\t\tt := v.(json.RawMessage)\n\t\tm[k] = &t\n\t}\n\n\trepositories := s.GetRepositoriesAsSlice()\n\trawRepositories, err := json.MarshalIndent(&repositories, \"\", \"    \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tjsonRepositories := json.RawMessage(rawRepositories)\n\tm[\"repositories\"] = &jsonRepositories\n\n\tb, err := json.MarshalIndent(&m, \"\", \"    \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(filename, b, perm)\n}\n\nfunc (s *Satis) GetRepositoriesAsSlice() []SatisRepository {\n\tc := make([]SatisRepository, 0, len(s.repositories))\n\tfor _, value := range s.repositories {\n\t\tc = append(c, value)\n\t}\n\n\treturn c\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/terraform\/flatmap\"\n\t\"github.com\/hashicorp\/terraform\/helper\/diff\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n\t\"github.com\/mitchellh\/goamz\/ec2\"\n)\n\nfunc resource_aws_instance_create(\n\ts *terraform.ResourceState,\n\td *terraform.ResourceDiff,\n\tmeta interface{}) (*terraform.ResourceState, error) {\n\tp := meta.(*ResourceProvider)\n\tec2conn := p.ec2conn\n\n\t\/\/ Merge the diff into the state so that we have all the attributes\n\t\/\/ properly.\n\trs := s.MergeDiff(d)\n\tdelete(rs.Attributes, \"source_dest_check\")\n\n\t\/\/ Figure out user data\n\tuserData := \"\"\n\tif attr, ok := d.Attributes[\"user_data\"]; ok {\n\t\tuserData = attr.NewExtra.(string)\n\t}\n\n\t\/\/ Build the creation struct\n\trunOpts := &ec2.RunInstances{\n\t\tImageId:      rs.Attributes[\"ami\"],\n\t\tInstanceType: rs.Attributes[\"instance_type\"],\n\t\tKeyName:      rs.Attributes[\"key_name\"],\n\t\tSubnetId:     rs.Attributes[\"subnet_id\"],\n\t\tUserData:     []byte(userData),\n\t}\n\tif raw := flatmap.Expand(rs.Attributes, \"security_groups\"); raw != nil {\n\t\tif sgs, ok := raw.([]interface{}); ok {\n\t\t\tfor _, sg := range sgs {\n\t\t\t\tstr, ok := sg.(string)\n\t\t\t\tif !ok {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tvar g ec2.SecurityGroup\n\t\t\t\tif runOpts.SubnetId != \"\" {\n\t\t\t\t\tg.Id = str\n\t\t\t\t} else {\n\t\t\t\t\tg.Name = str\n\t\t\t\t}\n\n\t\t\t\trunOpts.SecurityGroups = append(runOpts.SecurityGroups, g)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Create the instance\n\tlog.Printf(\"[DEBUG] Run configuration: %#v\", runOpts)\n\trunResp, err := ec2conn.RunInstances(runOpts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error launching source instance: %s\", err)\n\t}\n\n\tinstance := &runResp.Instances[0]\n\tlog.Printf(\"[INFO] Instance ID: %s\", instance.InstanceId)\n\n\t\/\/ Store the resulting ID so we can look this up later\n\trs.ID = instance.InstanceId\n\n\t\/\/ Wait for the instance to become running so we can get some attributes\n\t\/\/ that aren't available until later.\n\tlog.Printf(\n\t\t\"[DEBUG] Waiting for instance (%s) to become running\",\n\t\tinstance.InstanceId)\n\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:    []string{\"pending\"},\n\t\tTarget:     \"running\",\n\t\tRefresh:    InstanceStateRefreshFunc(ec2conn, instance.InstanceId),\n\t\tTimeout:    10 * time.Minute,\n\t\tDelay:      10 * time.Second,\n\t\tMinTimeout: 3 * time.Second,\n\t}\n\n\tinstanceRaw, err := stateConf.WaitForState()\n\n\tif err != nil {\n\t\treturn rs, fmt.Errorf(\n\t\t\t\"Error waiting for instance (%s) to become ready: %s\",\n\t\t\tinstance.InstanceId, err)\n\t}\n\n\tinstance = instanceRaw.(*ec2.Instance)\n\n\t\/\/ Initialize the connection info\n\trs.ConnInfo[\"type\"] = \"ssh\"\n\trs.ConnInfo[\"host\"] = instance.PublicIpAddress\n\n\t\/\/ Set our attributes\n\trs, err = resource_aws_instance_update_state(rs, instance)\n\tif err != nil {\n\t\treturn rs, err\n\t}\n\n\t\/\/ Update if we need to\n\treturn resource_aws_instance_update(rs, d, meta)\n}\n\nfunc resource_aws_instance_update(\n\ts *terraform.ResourceState,\n\td *terraform.ResourceDiff,\n\tmeta interface{}) (*terraform.ResourceState, error) {\n\tp := meta.(*ResourceProvider)\n\tec2conn := p.ec2conn\n\trs := s.MergeDiff(d)\n\n\tmodify := false\n\topts := new(ec2.ModifyInstance)\n\n\tif attr, ok := d.Attributes[\"source_dest_check\"]; ok {\n\t\tmodify = true\n\t\topts.SourceDestCheck = attr.New != \"\" && attr.New != \"false\"\n\t\topts.SetSourceDestCheck = true\n\t\trs.Attributes[\"source_dest_check\"] = strconv.FormatBool(\n\t\t\topts.SourceDestCheck)\n\t}\n\n\tif modify {\n\t\tlog.Printf(\"[INFO] Modifing instance %s: %#v\", s.ID, opts)\n\t\tif _, err := ec2conn.ModifyInstance(s.ID, opts); err != nil {\n\t\t\treturn s, err\n\t\t}\n\n\t\t\/\/ TODO(mitchellh): wait for the attributes we modified to\n\t\t\/\/ persist the change...\n\t}\n\n\treturn rs, nil\n}\n\nfunc resource_aws_instance_destroy(\n\ts *terraform.ResourceState,\n\tmeta interface{}) error {\n\tp := meta.(*ResourceProvider)\n\tec2conn := p.ec2conn\n\n\tlog.Printf(\"[INFO] Terminating instance: %s\", s.ID)\n\tif _, err := ec2conn.TerminateInstances([]string{s.ID}); err != nil {\n\t\treturn fmt.Errorf(\"Error terminating instance: %s\", err)\n\t}\n\n\tlog.Printf(\n\t\t\"[DEBUG] Waiting for instance (%s) to become terminated\",\n\t\ts.ID)\n\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:    []string{\"pending\", \"running\", \"shutting-down\", \"stopped\", \"stopping\"},\n\t\tTarget:     \"terminated\",\n\t\tRefresh:    InstanceStateRefreshFunc(ec2conn, s.ID),\n\t\tTimeout:    10 * time.Minute,\n\t\tDelay:      10 * time.Second,\n\t\tMinTimeout: 3 * time.Second,\n\t}\n\n\t_, err := stateConf.WaitForState()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"Error waiting for instance (%s) to terminate: %s\",\n\t\t\ts.ID, err)\n\t}\n\n\treturn nil\n}\n\nfunc resource_aws_instance_diff(\n\ts *terraform.ResourceState,\n\tc *terraform.ResourceConfig,\n\tmeta interface{}) (*terraform.ResourceDiff, error) {\n\tb := &diff.ResourceBuilder{\n\t\tAttrs: map[string]diff.AttrType{\n\t\t\t\"ami\":               diff.AttrTypeCreate,\n\t\t\t\"availability_zone\": diff.AttrTypeCreate,\n\t\t\t\"instance_type\":     diff.AttrTypeCreate,\n\t\t\t\"key_name\":          diff.AttrTypeCreate,\n\t\t\t\"security_groups\":   diff.AttrTypeCreate,\n\t\t\t\"subnet_id\":         diff.AttrTypeCreate,\n\t\t\t\"source_dest_check\": diff.AttrTypeUpdate,\n\t\t\t\"user_data\":         diff.AttrTypeCreate,\n\t\t},\n\n\t\tComputedAttrs: []string{\n\t\t\t\"availability_zone\",\n\t\t\t\"key_name\",\n\t\t\t\"public_dns\",\n\t\t\t\"public_ip\",\n\t\t\t\"private_dns\",\n\t\t\t\"private_ip\",\n\t\t\t\"security_groups\",\n\t\t\t\"subnet_id\",\n\t\t},\n\n\t\tPreProcess: map[string]diff.PreProcessFunc{\n\t\t\t\"user_data\": func(v string) string {\n\t\t\t\thash := sha1.Sum([]byte(v))\n\t\t\t\treturn hex.EncodeToString(hash[:])\n\t\t\t},\n\t\t},\n\t}\n\n\treturn b.Diff(s, c)\n}\n\nfunc resource_aws_instance_refresh(\n\ts *terraform.ResourceState,\n\tmeta interface{}) (*terraform.ResourceState, error) {\n\tp := meta.(*ResourceProvider)\n\tec2conn := p.ec2conn\n\n\tresp, err := ec2conn.Instances([]string{s.ID}, ec2.NewFilter())\n\tif err != nil {\n\t\t\/\/ If the instance was not found, return nil so that we can show\n\t\t\/\/ that the instance is gone.\n\t\tif ec2err, ok := err.(*ec2.Error); ok && ec2err.Code == \"InvalidInstanceID.NotFound\" {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\t\/\/ Some other error, report it\n\t\treturn s, err\n\t}\n\n\t\/\/ If nothing was found, then return no state\n\tif len(resp.Reservations) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tinstance := &resp.Reservations[0].Instances[0]\n\n\t\/\/ If the instance is terminated, then it is gone\n\tif instance.State.Name == \"terminated\" {\n\t\treturn nil, nil\n\t}\n\n\treturn resource_aws_instance_update_state(s, instance)\n}\n\nfunc resource_aws_instance_update_state(\n\ts *terraform.ResourceState,\n\tinstance *ec2.Instance) (*terraform.ResourceState, error) {\n\ts.Attributes[\"availability_zone\"] = instance.AvailZone\n\ts.Attributes[\"key_name\"] = instance.KeyName\n\ts.Attributes[\"public_dns\"] = instance.DNSName\n\ts.Attributes[\"public_ip\"] = instance.PublicIpAddress\n\ts.Attributes[\"private_dns\"] = instance.PrivateDNSName\n\ts.Attributes[\"private_ip\"] = instance.PrivateIpAddress\n\ts.Attributes[\"subnet_id\"] = instance.SubnetId\n\ts.Dependencies = nil\n\n\t\/\/ Extract the existing security groups\n\tuseID := false\n\tif raw := flatmap.Expand(s.Attributes, \"security_groups\"); raw != nil {\n\t\tif sgs, ok := raw.([]interface{}); ok {\n\t\t\tfor _, sg := range sgs {\n\t\t\t\tstr, ok := sg.(string)\n\t\t\t\tif !ok {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif strings.Contains(str, \"sg-\") {\n\t\t\t\t\tuseID = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Build up the security groups\n\tsgs := make([]string, len(instance.SecurityGroups))\n\tfor i, sg := range instance.SecurityGroups {\n\t\tif instance.SubnetId != \"\" && useID {\n\t\t\tsgs[i] = sg.Id\n\t\t} else {\n\t\t\tsgs[i] = sg.Name\n\t\t}\n\n\t\ts.Dependencies = append(s.Dependencies,\n\t\t\tterraform.ResourceDependency{ID: sg.Id},\n\t\t)\n\t}\n\tflatmap.Map(s.Attributes).Merge(flatmap.Flatten(map[string]interface{}{\n\t\t\"security_groups\": sgs,\n\t}))\n\n\tif instance.SubnetId != \"\" {\n\t\ts.Dependencies = append(s.Dependencies,\n\t\t\tterraform.ResourceDependency{ID: instance.SubnetId},\n\t\t)\n\t}\n\n\treturn s, nil\n}\n\n\/\/ InstanceStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch\n\/\/ an EC2 instance.\nfunc InstanceStateRefreshFunc(conn *ec2.EC2, instanceID string) resource.StateRefreshFunc {\n\treturn func() (interface{}, string, error) {\n\t\tresp, err := conn.Instances([]string{instanceID}, ec2.NewFilter())\n\t\tif err != nil {\n\t\t\tif ec2err, ok := err.(*ec2.Error); ok && ec2err.Code == \"InvalidInstanceID.NotFound\" {\n\t\t\t\t\/\/ Set this to nil as if we didn't find anything.\n\t\t\t\tresp = nil\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Error on InstanceStateRefresh: %s\", err)\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\t\t}\n\n\t\tif resp == nil || len(resp.Reservations) == 0 || len(resp.Reservations[0].Instances) == 0 {\n\t\t\t\/\/ Sometimes AWS just has consistency issues and doesn't see\n\t\t\t\/\/ our instance yet. Return an empty state.\n\t\t\treturn nil, \"\", nil\n\t\t}\n\n\t\ti := &resp.Reservations[0].Instances[0]\n\t\treturn i, i.State.Name, nil\n\t}\n}\n<commit_msg>provider\/aws: More strict check<commit_after>package aws\n\nimport (\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/terraform\/flatmap\"\n\t\"github.com\/hashicorp\/terraform\/helper\/diff\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n\t\"github.com\/mitchellh\/goamz\/ec2\"\n)\n\nfunc resource_aws_instance_create(\n\ts *terraform.ResourceState,\n\td *terraform.ResourceDiff,\n\tmeta interface{}) (*terraform.ResourceState, error) {\n\tp := meta.(*ResourceProvider)\n\tec2conn := p.ec2conn\n\n\t\/\/ Merge the diff into the state so that we have all the attributes\n\t\/\/ properly.\n\trs := s.MergeDiff(d)\n\tdelete(rs.Attributes, \"source_dest_check\")\n\n\t\/\/ Figure out user data\n\tuserData := \"\"\n\tif attr, ok := d.Attributes[\"user_data\"]; ok {\n\t\tuserData = attr.NewExtra.(string)\n\t}\n\n\t\/\/ Build the creation struct\n\trunOpts := &ec2.RunInstances{\n\t\tImageId:      rs.Attributes[\"ami\"],\n\t\tInstanceType: rs.Attributes[\"instance_type\"],\n\t\tKeyName:      rs.Attributes[\"key_name\"],\n\t\tSubnetId:     rs.Attributes[\"subnet_id\"],\n\t\tUserData:     []byte(userData),\n\t}\n\tif raw := flatmap.Expand(rs.Attributes, \"security_groups\"); raw != nil {\n\t\tif sgs, ok := raw.([]interface{}); ok {\n\t\t\tfor _, sg := range sgs {\n\t\t\t\tstr, ok := sg.(string)\n\t\t\t\tif !ok {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tvar g ec2.SecurityGroup\n\t\t\t\tif runOpts.SubnetId != \"\" {\n\t\t\t\t\tg.Id = str\n\t\t\t\t} else {\n\t\t\t\t\tg.Name = str\n\t\t\t\t}\n\n\t\t\t\trunOpts.SecurityGroups = append(runOpts.SecurityGroups, g)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Create the instance\n\tlog.Printf(\"[DEBUG] Run configuration: %#v\", runOpts)\n\trunResp, err := ec2conn.RunInstances(runOpts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error launching source instance: %s\", err)\n\t}\n\n\tinstance := &runResp.Instances[0]\n\tlog.Printf(\"[INFO] Instance ID: %s\", instance.InstanceId)\n\n\t\/\/ Store the resulting ID so we can look this up later\n\trs.ID = instance.InstanceId\n\n\t\/\/ Wait for the instance to become running so we can get some attributes\n\t\/\/ that aren't available until later.\n\tlog.Printf(\n\t\t\"[DEBUG] Waiting for instance (%s) to become running\",\n\t\tinstance.InstanceId)\n\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:    []string{\"pending\"},\n\t\tTarget:     \"running\",\n\t\tRefresh:    InstanceStateRefreshFunc(ec2conn, instance.InstanceId),\n\t\tTimeout:    10 * time.Minute,\n\t\tDelay:      10 * time.Second,\n\t\tMinTimeout: 3 * time.Second,\n\t}\n\n\tinstanceRaw, err := stateConf.WaitForState()\n\n\tif err != nil {\n\t\treturn rs, fmt.Errorf(\n\t\t\t\"Error waiting for instance (%s) to become ready: %s\",\n\t\t\tinstance.InstanceId, err)\n\t}\n\n\tinstance = instanceRaw.(*ec2.Instance)\n\n\t\/\/ Initialize the connection info\n\trs.ConnInfo[\"type\"] = \"ssh\"\n\trs.ConnInfo[\"host\"] = instance.PublicIpAddress\n\n\t\/\/ Set our attributes\n\trs, err = resource_aws_instance_update_state(rs, instance)\n\tif err != nil {\n\t\treturn rs, err\n\t}\n\n\t\/\/ Update if we need to\n\treturn resource_aws_instance_update(rs, d, meta)\n}\n\nfunc resource_aws_instance_update(\n\ts *terraform.ResourceState,\n\td *terraform.ResourceDiff,\n\tmeta interface{}) (*terraform.ResourceState, error) {\n\tp := meta.(*ResourceProvider)\n\tec2conn := p.ec2conn\n\trs := s.MergeDiff(d)\n\n\tmodify := false\n\topts := new(ec2.ModifyInstance)\n\n\tif attr, ok := d.Attributes[\"source_dest_check\"]; ok {\n\t\tmodify = true\n\t\topts.SourceDestCheck = attr.New != \"\" && attr.New != \"false\"\n\t\topts.SetSourceDestCheck = true\n\t\trs.Attributes[\"source_dest_check\"] = strconv.FormatBool(\n\t\t\topts.SourceDestCheck)\n\t}\n\n\tif modify {\n\t\tlog.Printf(\"[INFO] Modifing instance %s: %#v\", s.ID, opts)\n\t\tif _, err := ec2conn.ModifyInstance(s.ID, opts); err != nil {\n\t\t\treturn s, err\n\t\t}\n\n\t\t\/\/ TODO(mitchellh): wait for the attributes we modified to\n\t\t\/\/ persist the change...\n\t}\n\n\treturn rs, nil\n}\n\nfunc resource_aws_instance_destroy(\n\ts *terraform.ResourceState,\n\tmeta interface{}) error {\n\tp := meta.(*ResourceProvider)\n\tec2conn := p.ec2conn\n\n\tlog.Printf(\"[INFO] Terminating instance: %s\", s.ID)\n\tif _, err := ec2conn.TerminateInstances([]string{s.ID}); err != nil {\n\t\treturn fmt.Errorf(\"Error terminating instance: %s\", err)\n\t}\n\n\tlog.Printf(\n\t\t\"[DEBUG] Waiting for instance (%s) to become terminated\",\n\t\ts.ID)\n\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:    []string{\"pending\", \"running\", \"shutting-down\", \"stopped\", \"stopping\"},\n\t\tTarget:     \"terminated\",\n\t\tRefresh:    InstanceStateRefreshFunc(ec2conn, s.ID),\n\t\tTimeout:    10 * time.Minute,\n\t\tDelay:      10 * time.Second,\n\t\tMinTimeout: 3 * time.Second,\n\t}\n\n\t_, err := stateConf.WaitForState()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"Error waiting for instance (%s) to terminate: %s\",\n\t\t\ts.ID, err)\n\t}\n\n\treturn nil\n}\n\nfunc resource_aws_instance_diff(\n\ts *terraform.ResourceState,\n\tc *terraform.ResourceConfig,\n\tmeta interface{}) (*terraform.ResourceDiff, error) {\n\tb := &diff.ResourceBuilder{\n\t\tAttrs: map[string]diff.AttrType{\n\t\t\t\"ami\":               diff.AttrTypeCreate,\n\t\t\t\"availability_zone\": diff.AttrTypeCreate,\n\t\t\t\"instance_type\":     diff.AttrTypeCreate,\n\t\t\t\"key_name\":          diff.AttrTypeCreate,\n\t\t\t\"security_groups\":   diff.AttrTypeCreate,\n\t\t\t\"subnet_id\":         diff.AttrTypeCreate,\n\t\t\t\"source_dest_check\": diff.AttrTypeUpdate,\n\t\t\t\"user_data\":         diff.AttrTypeCreate,\n\t\t},\n\n\t\tComputedAttrs: []string{\n\t\t\t\"availability_zone\",\n\t\t\t\"key_name\",\n\t\t\t\"public_dns\",\n\t\t\t\"public_ip\",\n\t\t\t\"private_dns\",\n\t\t\t\"private_ip\",\n\t\t\t\"security_groups\",\n\t\t\t\"subnet_id\",\n\t\t},\n\n\t\tPreProcess: map[string]diff.PreProcessFunc{\n\t\t\t\"user_data\": func(v string) string {\n\t\t\t\thash := sha1.Sum([]byte(v))\n\t\t\t\treturn hex.EncodeToString(hash[:])\n\t\t\t},\n\t\t},\n\t}\n\n\treturn b.Diff(s, c)\n}\n\nfunc resource_aws_instance_refresh(\n\ts *terraform.ResourceState,\n\tmeta interface{}) (*terraform.ResourceState, error) {\n\tp := meta.(*ResourceProvider)\n\tec2conn := p.ec2conn\n\n\tresp, err := ec2conn.Instances([]string{s.ID}, ec2.NewFilter())\n\tif err != nil {\n\t\t\/\/ If the instance was not found, return nil so that we can show\n\t\t\/\/ that the instance is gone.\n\t\tif ec2err, ok := err.(*ec2.Error); ok && ec2err.Code == \"InvalidInstanceID.NotFound\" {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\t\/\/ Some other error, report it\n\t\treturn s, err\n\t}\n\n\t\/\/ If nothing was found, then return no state\n\tif len(resp.Reservations) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tinstance := &resp.Reservations[0].Instances[0]\n\n\t\/\/ If the instance is terminated, then it is gone\n\tif instance.State.Name == \"terminated\" {\n\t\treturn nil, nil\n\t}\n\n\treturn resource_aws_instance_update_state(s, instance)\n}\n\nfunc resource_aws_instance_update_state(\n\ts *terraform.ResourceState,\n\tinstance *ec2.Instance) (*terraform.ResourceState, error) {\n\ts.Attributes[\"availability_zone\"] = instance.AvailZone\n\ts.Attributes[\"key_name\"] = instance.KeyName\n\ts.Attributes[\"public_dns\"] = instance.DNSName\n\ts.Attributes[\"public_ip\"] = instance.PublicIpAddress\n\ts.Attributes[\"private_dns\"] = instance.PrivateDNSName\n\ts.Attributes[\"private_ip\"] = instance.PrivateIpAddress\n\ts.Attributes[\"subnet_id\"] = instance.SubnetId\n\ts.Dependencies = nil\n\n\t\/\/ Extract the existing security groups\n\tuseID := false\n\tif raw := flatmap.Expand(s.Attributes, \"security_groups\"); raw != nil {\n\t\tif sgs, ok := raw.([]interface{}); ok {\n\t\t\tfor _, sg := range sgs {\n\t\t\t\tstr, ok := sg.(string)\n\t\t\t\tif !ok {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif strings.HasPrefix(str, \"sg-\") {\n\t\t\t\t\tuseID = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Build up the security groups\n\tsgs := make([]string, len(instance.SecurityGroups))\n\tfor i, sg := range instance.SecurityGroups {\n\t\tif instance.SubnetId != \"\" && useID {\n\t\t\tsgs[i] = sg.Id\n\t\t} else {\n\t\t\tsgs[i] = sg.Name\n\t\t}\n\n\t\ts.Dependencies = append(s.Dependencies,\n\t\t\tterraform.ResourceDependency{ID: sg.Id},\n\t\t)\n\t}\n\tflatmap.Map(s.Attributes).Merge(flatmap.Flatten(map[string]interface{}{\n\t\t\"security_groups\": sgs,\n\t}))\n\n\tif instance.SubnetId != \"\" {\n\t\ts.Dependencies = append(s.Dependencies,\n\t\t\tterraform.ResourceDependency{ID: instance.SubnetId},\n\t\t)\n\t}\n\n\treturn s, nil\n}\n\n\/\/ InstanceStateRefreshFunc returns a resource.StateRefreshFunc that is used to watch\n\/\/ an EC2 instance.\nfunc InstanceStateRefreshFunc(conn *ec2.EC2, instanceID string) resource.StateRefreshFunc {\n\treturn func() (interface{}, string, error) {\n\t\tresp, err := conn.Instances([]string{instanceID}, ec2.NewFilter())\n\t\tif err != nil {\n\t\t\tif ec2err, ok := err.(*ec2.Error); ok && ec2err.Code == \"InvalidInstanceID.NotFound\" {\n\t\t\t\t\/\/ Set this to nil as if we didn't find anything.\n\t\t\t\tresp = nil\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Error on InstanceStateRefresh: %s\", err)\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\t\t}\n\n\t\tif resp == nil || len(resp.Reservations) == 0 || len(resp.Reservations[0].Instances) == 0 {\n\t\t\t\/\/ Sometimes AWS just has consistency issues and doesn't see\n\t\t\t\/\/ our instance yet. Return an empty state.\n\t\t\treturn nil, \"\", nil\n\t\t}\n\n\t\ti := &resp.Reservations[0].Instances[0]\n\t\treturn i, i.State.Name, nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2018-2019 The Decred developers\n\/\/ Use of this source code is governed by an ISC\n\/\/ license that can be found in the LICENSE file.\n\npackage txscript\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"testing\"\n\n\t\"github.com\/btcsuite\/btcd\/wire\"\n)\n\nvar (\n\t\/\/ manyInputsBenchTx is a transaction that contains a lot of inputs which is\n\t\/\/ useful for benchmarking signature hash calculation.\n\tmanyInputsBenchTx wire.MsgTx\n\n\t\/\/ A mock previous output script to use in the signing benchmark.\n\tprevOutScript = hexToBytes(\"a914f5916158e3e2c4551c1796708db8367207ed13bb87\")\n)\n\nfunc init() {\n\t\/\/ tx 620f57c92cf05a7f7e7f7d28255d5f7089437bc48e34dcfebf7751d08b7fb8f5\n\ttxHex, err := ioutil.ReadFile(\"data\/many_inputs_tx.hex\")\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"unable to read benchmark tx file: %v\", err))\n\t}\n\n\ttxBytes := hexToBytes(string(txHex))\n\terr = manyInputsBenchTx.Deserialize(bytes.NewReader(txBytes))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ BenchmarkCalcSigHash benchmarks how long it takes to calculate the signature\n\/\/ hashes for all inputs of a transaction with many inputs.\nfunc BenchmarkCalcSigHash(b *testing.B) {\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tfor j := 0; j < len(manyInputsBenchTx.TxIn); j++ {\n\t\t\t_, err := CalcSignatureHash(prevOutScript, SigHashAll,\n\t\t\t\t&manyInputsBenchTx, j)\n\t\t\tif err != nil {\n\t\t\t\tb.Fatalf(\"failed to calc signature hash: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkCalcWitnessSigHash benchmarks how long it takes to calculate the\n\/\/ witness signature hashes for all inputs of a transaction with many inputs.\nfunc BenchmarkCalcWitnessSigHash(b *testing.B) {\n\tsigHashes := NewTxSigHashes(&manyInputsBenchTx)\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tfor j := 0; j < len(manyInputsBenchTx.TxIn); j++ {\n\t\t\t_, err := CalcWitnessSigHash(\n\t\t\t\tprevOutScript, sigHashes, SigHashAll,\n\t\t\t\t&manyInputsBenchTx, j, 5,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tb.Fatalf(\"failed to calc signature hash: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ genComplexScript returns a script comprised of half as many opcodes as the\n\/\/ maximum allowed followed by as many max size data pushes fit without\n\/\/ exceeding the max allowed script size.\nfunc genComplexScript() ([]byte, error) {\n\tvar scriptLen int\n\tbuilder := NewScriptBuilder()\n\tfor i := 0; i < MaxOpsPerScript\/2; i++ {\n\t\tbuilder.AddOp(OP_TRUE)\n\t\tscriptLen++\n\t}\n\tmaxData := bytes.Repeat([]byte{0x02}, MaxScriptElementSize)\n\tfor i := 0; i < (MaxScriptSize-scriptLen)\/(MaxScriptElementSize+3); i++ {\n\t\tbuilder.AddData(maxData)\n\t}\n\treturn builder.Script()\n}\n\n\/\/ BenchmarkScriptParsing benchmarks how long it takes to parse a very large\n\/\/ script.\nfunc BenchmarkScriptParsing(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tconst scriptVersion = 0\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\ttokenizer := MakeScriptTokenizer(scriptVersion, script)\n\t\tfor tokenizer.Next() {\n\t\t\t_ = tokenizer.Opcode()\n\t\t\t_ = tokenizer.Data()\n\t\t\t_ = tokenizer.ByteIndex()\n\t\t}\n\t\tif err := tokenizer.Err(); err != nil {\n\t\t\tb.Fatalf(\"failed to parse script: %v\", err)\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkDisasmString benchmarks how long it takes to disassemble a very\n\/\/ large script.\nfunc BenchmarkDisasmString(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_, err := DisasmString(script)\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"failed to disasm script: %v\", err)\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkIsPubKeyScript benchmarks how long it takes to analyze a very large\n\/\/ script to determine if it is a standard pay-to-pubkey script.\nfunc BenchmarkIsPubKeyScript(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = IsPayToPubKey(script)\n\t}\n}\n\n\/\/ BenchmarkIsPubKeyHashScript benchmarks how long it takes to analyze a very\n\/\/ large script to determine if it is a standard pay-to-pubkey-hash script.\nfunc BenchmarkIsPubKeyHashScript(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = IsPayToPubKeyHash(script)\n\t}\n}\n\n\/\/ BenchmarkIsPayToScriptHash benchmarks how long it takes IsPayToScriptHash to\n\/\/ analyze a very large script.\nfunc BenchmarkIsPayToScriptHash(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = IsPayToScriptHash(script)\n\t}\n}\n\n\/\/ BenchmarkIsMultisigScriptLarge benchmarks how long it takes IsMultisigScript\n\/\/ to analyze a very large script.\nfunc BenchmarkIsMultisigScriptLarge(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tisMultisig, err := IsMultisigScript(script)\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"unexpected err: %v\", err)\n\t\t}\n\t\tif isMultisig {\n\t\t\tb.Fatalf(\"script should NOT be reported as mutisig script\")\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkIsMultisigScript benchmarks how long it takes IsMultisigScript to\n\/\/ analyze a 1-of-2 multisig public key script.\nfunc BenchmarkIsMultisigScript(b *testing.B) {\n\tmultisigShortForm := \"1 \" +\n\t\t\"DATA_33 \" +\n\t\t\"0x030478aaaa2be30772f1e69e581610f1840b3cf2fe7228ee0281cd599e5746f81e \" +\n\t\t\"DATA_33 \" +\n\t\t\"0x0284f4d078b236a9ff91661f8ffbe012737cd3507566f30fd97d25f2b23539f3cd \" +\n\t\t\"2 CHECKMULTISIG\"\n\tpkScript := mustParseShortForm(multisigShortForm)\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tisMultisig, err := IsMultisigScript(pkScript)\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"unexpected err: %v\", err)\n\t\t}\n\t\tif !isMultisig {\n\t\t\tb.Fatalf(\"script should be reported as a mutisig script\")\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkIsMultisigSigScript benchmarks how long it takes IsMultisigSigScript\n\/\/ to analyze a very large script.\nfunc BenchmarkIsMultisigSigScriptLarge(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tif IsMultisigSigScript(script) {\n\t\t\tb.Fatalf(\"script should NOT be reported as mutisig sig script\")\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkIsMultisigSigScript benchmarks how long it takes IsMultisigSigScript\n\/\/ to analyze both a 1-of-2 multisig public key script (which should be false)\n\/\/ and a signature script comprised of a pay-to-script-hash 1-of-2 multisig\n\/\/ redeem script (which should be true).\nfunc BenchmarkIsMultisigSigScript(b *testing.B) {\n\tmultisigShortForm := \"1 \" +\n\t\t\"DATA_33 \" +\n\t\t\"0x030478aaaa2be30772f1e69e581610f1840b3cf2fe7228ee0281cd599e5746f81e \" +\n\t\t\"DATA_33 \" +\n\t\t\"0x0284f4d078b236a9ff91661f8ffbe012737cd3507566f30fd97d25f2b23539f3cd \" +\n\t\t\"2 CHECKMULTISIG\"\n\tpkScript := mustParseShortForm(multisigShortForm)\n\n\tsigHex := \"0x304402205795c3ab6ba11331eeac757bf1fc9c34bef0c7e1a9c8bd5eebb8\" +\n\t\t\"82f3b79c5838022001e0ab7b4c7662e4522dc5fa479e4b4133fa88c6a53d895dc1d5\" +\n\t\t\"2eddc7bbcf2801 \"\n\tsigScript := mustParseShortForm(\"DATA_71 \" + sigHex + \"DATA_71 \" +\n\t\tmultisigShortForm)\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tif IsMultisigSigScript(pkScript) {\n\t\t\tb.Fatalf(\"script should NOT be reported as mutisig sig script\")\n\t\t}\n\t\tif !IsMultisigSigScript(sigScript) {\n\t\t\tb.Fatalf(\"script should be reported as a mutisig sig script\")\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkIsPushOnlyScript benchmarks how long it takes IsPushOnlyScript to\n\/\/ analyze a very large script.\nfunc BenchmarkIsPushOnlyScript(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = IsPushOnlyScript(script)\n\t}\n}\n<commit_msg>txscript: Add benchmark IsPayToWitnessPubkeyHash<commit_after>\/\/ Copyright (c) 2018-2019 The Decred developers\n\/\/ Use of this source code is governed by an ISC\n\/\/ license that can be found in the LICENSE file.\n\npackage txscript\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"testing\"\n\n\t\"github.com\/btcsuite\/btcd\/wire\"\n)\n\nvar (\n\t\/\/ manyInputsBenchTx is a transaction that contains a lot of inputs which is\n\t\/\/ useful for benchmarking signature hash calculation.\n\tmanyInputsBenchTx wire.MsgTx\n\n\t\/\/ A mock previous output script to use in the signing benchmark.\n\tprevOutScript = hexToBytes(\"a914f5916158e3e2c4551c1796708db8367207ed13bb87\")\n)\n\nfunc init() {\n\t\/\/ tx 620f57c92cf05a7f7e7f7d28255d5f7089437bc48e34dcfebf7751d08b7fb8f5\n\ttxHex, err := ioutil.ReadFile(\"data\/many_inputs_tx.hex\")\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"unable to read benchmark tx file: %v\", err))\n\t}\n\n\ttxBytes := hexToBytes(string(txHex))\n\terr = manyInputsBenchTx.Deserialize(bytes.NewReader(txBytes))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ BenchmarkCalcSigHash benchmarks how long it takes to calculate the signature\n\/\/ hashes for all inputs of a transaction with many inputs.\nfunc BenchmarkCalcSigHash(b *testing.B) {\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tfor j := 0; j < len(manyInputsBenchTx.TxIn); j++ {\n\t\t\t_, err := CalcSignatureHash(prevOutScript, SigHashAll,\n\t\t\t\t&manyInputsBenchTx, j)\n\t\t\tif err != nil {\n\t\t\t\tb.Fatalf(\"failed to calc signature hash: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkCalcWitnessSigHash benchmarks how long it takes to calculate the\n\/\/ witness signature hashes for all inputs of a transaction with many inputs.\nfunc BenchmarkCalcWitnessSigHash(b *testing.B) {\n\tsigHashes := NewTxSigHashes(&manyInputsBenchTx)\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tfor j := 0; j < len(manyInputsBenchTx.TxIn); j++ {\n\t\t\t_, err := CalcWitnessSigHash(\n\t\t\t\tprevOutScript, sigHashes, SigHashAll,\n\t\t\t\t&manyInputsBenchTx, j, 5,\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tb.Fatalf(\"failed to calc signature hash: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ genComplexScript returns a script comprised of half as many opcodes as the\n\/\/ maximum allowed followed by as many max size data pushes fit without\n\/\/ exceeding the max allowed script size.\nfunc genComplexScript() ([]byte, error) {\n\tvar scriptLen int\n\tbuilder := NewScriptBuilder()\n\tfor i := 0; i < MaxOpsPerScript\/2; i++ {\n\t\tbuilder.AddOp(OP_TRUE)\n\t\tscriptLen++\n\t}\n\tmaxData := bytes.Repeat([]byte{0x02}, MaxScriptElementSize)\n\tfor i := 0; i < (MaxScriptSize-scriptLen)\/(MaxScriptElementSize+3); i++ {\n\t\tbuilder.AddData(maxData)\n\t}\n\treturn builder.Script()\n}\n\n\/\/ BenchmarkScriptParsing benchmarks how long it takes to parse a very large\n\/\/ script.\nfunc BenchmarkScriptParsing(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tconst scriptVersion = 0\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\ttokenizer := MakeScriptTokenizer(scriptVersion, script)\n\t\tfor tokenizer.Next() {\n\t\t\t_ = tokenizer.Opcode()\n\t\t\t_ = tokenizer.Data()\n\t\t\t_ = tokenizer.ByteIndex()\n\t\t}\n\t\tif err := tokenizer.Err(); err != nil {\n\t\t\tb.Fatalf(\"failed to parse script: %v\", err)\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkDisasmString benchmarks how long it takes to disassemble a very\n\/\/ large script.\nfunc BenchmarkDisasmString(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_, err := DisasmString(script)\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"failed to disasm script: %v\", err)\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkIsPubKeyScript benchmarks how long it takes to analyze a very large\n\/\/ script to determine if it is a standard pay-to-pubkey script.\nfunc BenchmarkIsPubKeyScript(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = IsPayToPubKey(script)\n\t}\n}\n\n\/\/ BenchmarkIsPubKeyHashScript benchmarks how long it takes to analyze a very\n\/\/ large script to determine if it is a standard pay-to-pubkey-hash script.\nfunc BenchmarkIsPubKeyHashScript(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = IsPayToPubKeyHash(script)\n\t}\n}\n\n\/\/ BenchmarkIsPayToScriptHash benchmarks how long it takes IsPayToScriptHash to\n\/\/ analyze a very large script.\nfunc BenchmarkIsPayToScriptHash(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = IsPayToScriptHash(script)\n\t}\n}\n\n\/\/ BenchmarkIsMultisigScriptLarge benchmarks how long it takes IsMultisigScript\n\/\/ to analyze a very large script.\nfunc BenchmarkIsMultisigScriptLarge(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tisMultisig, err := IsMultisigScript(script)\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"unexpected err: %v\", err)\n\t\t}\n\t\tif isMultisig {\n\t\t\tb.Fatalf(\"script should NOT be reported as mutisig script\")\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkIsMultisigScript benchmarks how long it takes IsMultisigScript to\n\/\/ analyze a 1-of-2 multisig public key script.\nfunc BenchmarkIsMultisigScript(b *testing.B) {\n\tmultisigShortForm := \"1 \" +\n\t\t\"DATA_33 \" +\n\t\t\"0x030478aaaa2be30772f1e69e581610f1840b3cf2fe7228ee0281cd599e5746f81e \" +\n\t\t\"DATA_33 \" +\n\t\t\"0x0284f4d078b236a9ff91661f8ffbe012737cd3507566f30fd97d25f2b23539f3cd \" +\n\t\t\"2 CHECKMULTISIG\"\n\tpkScript := mustParseShortForm(multisigShortForm)\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tisMultisig, err := IsMultisigScript(pkScript)\n\t\tif err != nil {\n\t\t\tb.Fatalf(\"unexpected err: %v\", err)\n\t\t}\n\t\tif !isMultisig {\n\t\t\tb.Fatalf(\"script should be reported as a mutisig script\")\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkIsMultisigSigScript benchmarks how long it takes IsMultisigSigScript\n\/\/ to analyze a very large script.\nfunc BenchmarkIsMultisigSigScriptLarge(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tif IsMultisigSigScript(script) {\n\t\t\tb.Fatalf(\"script should NOT be reported as mutisig sig script\")\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkIsMultisigSigScript benchmarks how long it takes IsMultisigSigScript\n\/\/ to analyze both a 1-of-2 multisig public key script (which should be false)\n\/\/ and a signature script comprised of a pay-to-script-hash 1-of-2 multisig\n\/\/ redeem script (which should be true).\nfunc BenchmarkIsMultisigSigScript(b *testing.B) {\n\tmultisigShortForm := \"1 \" +\n\t\t\"DATA_33 \" +\n\t\t\"0x030478aaaa2be30772f1e69e581610f1840b3cf2fe7228ee0281cd599e5746f81e \" +\n\t\t\"DATA_33 \" +\n\t\t\"0x0284f4d078b236a9ff91661f8ffbe012737cd3507566f30fd97d25f2b23539f3cd \" +\n\t\t\"2 CHECKMULTISIG\"\n\tpkScript := mustParseShortForm(multisigShortForm)\n\n\tsigHex := \"0x304402205795c3ab6ba11331eeac757bf1fc9c34bef0c7e1a9c8bd5eebb8\" +\n\t\t\"82f3b79c5838022001e0ab7b4c7662e4522dc5fa479e4b4133fa88c6a53d895dc1d5\" +\n\t\t\"2eddc7bbcf2801 \"\n\tsigScript := mustParseShortForm(\"DATA_71 \" + sigHex + \"DATA_71 \" +\n\t\tmultisigShortForm)\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\tif IsMultisigSigScript(pkScript) {\n\t\t\tb.Fatalf(\"script should NOT be reported as mutisig sig script\")\n\t\t}\n\t\tif !IsMultisigSigScript(sigScript) {\n\t\t\tb.Fatalf(\"script should be reported as a mutisig sig script\")\n\t\t}\n\t}\n}\n\n\/\/ BenchmarkIsPushOnlyScript benchmarks how long it takes IsPushOnlyScript to\n\/\/ analyze a very large script.\nfunc BenchmarkIsPushOnlyScript(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = IsPushOnlyScript(script)\n\t}\n}\n\n\/\/ BenchmarkIsWitnessPubKeyHash benchmarks how long it takes to analyze a very\n\/\/ large script to determine if it is a standard witness pubkey hash script.\nfunc BenchmarkIsWitnessPubKeyHash(b *testing.B) {\n\tscript, err := genComplexScript()\n\tif err != nil {\n\t\tb.Fatalf(\"failed to create benchmark script: %v\", err)\n\t}\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor i := 0; i < b.N; i++ {\n\t\t_ = IsPayToWitnessPubKeyHash(script)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package archiver makes it super easy to create and open .zip,\n\/\/ .tar.gz, and .tar.bz2 files.\npackage archiver\n\nimport (\n\t\"archive\/zip\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\/\/ Zip creates a .zip file in the location zipPath containing\n\/\/ the contents of files listed in filePaths. File paths\n\/\/ can be those of regular files or directories. Regular\n\/\/ files are stored at the 'root' of the archive, and\n\/\/ directories are recursively added.\n\/\/\n\/\/ Files with an extension for formats that are already\n\/\/ compressed will be stored only, not compressed.\nfunc Zip(zipPath string, filePaths []string) error {\n\tout, err := os.Create(zipPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating %s: %v\", zipPath, err)\n\t}\n\tdefer out.Close()\n\n\tw := zip.NewWriter(out)\n\tfor _, fpath := range filePaths {\n\t\terr = zipFile(w, fpath)\n\t\tif err != nil {\n\t\t\tw.Close()\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn w.Close()\n}\n\nfunc zipFile(w *zip.Writer, source string) error {\n\tsourceInfo, err := os.Stat(source)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: stat: %v\", source, err)\n\t}\n\n\tvar baseDir string\n\tif sourceInfo.IsDir() {\n\t\tbaseDir = filepath.Base(source)\n\t}\n\n\treturn filepath.Walk(source, func(fpath string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"walking to %s: %v\", fpath, err)\n\t\t}\n\n\t\theader, err := zip.FileInfoHeader(info)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s: getting header: %v\", fpath, err)\n\t\t}\n\n\t\tif baseDir != \"\" {\n\t\t\theader.Name = filepath.Join(baseDir, strings.TrimPrefix(fpath, source))\n\t\t}\n\n\t\tif info.IsDir() {\n\t\t\theader.Name += \"\/\"\n\t\t\theader.Method = zip.Store\n\t\t} else {\n\t\t\text := strings.ToLower(path.Ext(header.Name))\n\t\t\tif _, ok := CompressedFormats[ext]; ok {\n\t\t\t\theader.Method = zip.Store\n\t\t\t} else {\n\t\t\t\theader.Method = zip.Deflate\n\t\t\t}\n\t\t}\n\n\t\twriter, err := w.CreateHeader(header)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s: making header: %v\", fpath, err)\n\t\t}\n\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tif header.Mode().IsRegular() {\n\t\t\tfile, err := os.Open(fpath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s: opening: %v\", fpath, err)\n\t\t\t}\n\t\t\tdefer file.Close()\n\n\t\t\t_, err = io.CopyN(writer, file, info.Size())\n\t\t\tif err != nil && err != io.EOF {\n\t\t\t\treturn fmt.Errorf(\"%s: copying contents: %v\", fpath, err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\n\/\/ Unzip unzips the .zip file at source into destination.\nfunc Unzip(source, destination string) error {\n\tr, err := zip.OpenReader(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\n\tfor _, zf := range r.File {\n\t\tif err := unzipFile(zf, destination); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc unzipFile(zf *zip.File, destination string) error {\n\tif strings.HasSuffix(zf.Name, \"\/\") {\n\t\treturn mkdir(filepath.Join(destination, zf.Name))\n\t}\n\n\trc, err := zf.Open()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: open compressed file: %v\", zf.Name, err)\n\t}\n\tdefer rc.Close()\n\n\treturn writeNewFile(filepath.Join(destination, zf.Name), rc, zf.FileInfo().Mode())\n}\n\nfunc writeNewFile(fpath string, in io.Reader, fm os.FileMode) error {\n\terr := os.MkdirAll(filepath.Dir(fpath), 0755)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: making directory for file: %v\", fpath, err)\n\t}\n\n\tout, err := os.Create(fpath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: creating new file: %v\", fpath, err)\n\t}\n\tdefer out.Close()\n\n\terr = out.Chmod(fm)\n\tif err != nil && runtime.GOOS != \"windows\" {\n\t\treturn fmt.Errorf(\"%s: changing file mode: %v\", fpath, err)\n\t}\n\n\t_, err = io.Copy(out, in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: writing file: %v\", fpath, err)\n\t}\n\treturn nil\n}\n\nfunc writeNewSymbolicLink(fpath string, target string) error {\n\terr := os.MkdirAll(filepath.Dir(fpath), 0755)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: making directory for file: %v\", fpath, err)\n\t}\n\n\terr = os.Symlink(target, fpath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: making symbolic link for: %v\", fpath, err)\n\t}\n\n\treturn nil\n}\n\nfunc mkdir(dirPath string) error {\n\terr := os.MkdirAll(dirPath, 0755)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: making directory: %v\", dirPath, err)\n\t}\n\treturn nil\n}\n\n\/\/ CompressedFormats is a (non-exhaustive) set of lowercased\n\/\/ file extensions for formats that are typically already\n\/\/ compressed. Compressing already-compressed files often\n\/\/ results in a larger file, so when possible, we check this\n\/\/ set to avoid that.\nvar CompressedFormats = map[string]struct{}{\n\t\".7z\":   {},\n\t\".avi\":  {},\n\t\".bz2\":  {},\n\t\".cab\":  {},\n\t\".gif\":  {},\n\t\".gz\":   {},\n\t\".jar\":  {},\n\t\".jpeg\": {},\n\t\".jpg\":  {},\n\t\".lz\":   {},\n\t\".lzma\": {},\n\t\".mov\":  {},\n\t\".mp3\":  {},\n\t\".mp4\":  {},\n\t\".mpeg\": {},\n\t\".mpg\":  {},\n\t\".png\":  {},\n\t\".rar\":  {},\n\t\".tgz\":  {},\n\t\".xz\":   {},\n\t\".zip\":  {},\n\t\".zipx\": {},\n}\n\ntype (\n\t\/\/ CompressFunc is a function that makes an archive.\n\tCompressFunc func(string, []string) error\n\n\t\/\/ DecompressFunc is a function that extracts an archive.\n\tDecompressFunc func(string, string) error\n)\n<commit_msg>Use path.Join when setting zip.FileHeader.Name.<commit_after>\/\/ Package archiver makes it super easy to create and open .zip,\n\/\/ .tar.gz, and .tar.bz2 files.\npackage archiver\n\nimport (\n\t\"archive\/zip\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\/\/ Zip creates a .zip file in the location zipPath containing\n\/\/ the contents of files listed in filePaths. File paths\n\/\/ can be those of regular files or directories. Regular\n\/\/ files are stored at the 'root' of the archive, and\n\/\/ directories are recursively added.\n\/\/\n\/\/ Files with an extension for formats that are already\n\/\/ compressed will be stored only, not compressed.\nfunc Zip(zipPath string, filePaths []string) error {\n\tout, err := os.Create(zipPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating %s: %v\", zipPath, err)\n\t}\n\tdefer out.Close()\n\n\tw := zip.NewWriter(out)\n\tfor _, fpath := range filePaths {\n\t\terr = zipFile(w, fpath)\n\t\tif err != nil {\n\t\t\tw.Close()\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn w.Close()\n}\n\nfunc zipFile(w *zip.Writer, source string) error {\n\tsourceInfo, err := os.Stat(source)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: stat: %v\", source, err)\n\t}\n\n\tvar baseDir string\n\tif sourceInfo.IsDir() {\n\t\tbaseDir = filepath.Base(source)\n\t}\n\n\treturn filepath.Walk(source, func(fpath string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"walking to %s: %v\", fpath, err)\n\t\t}\n\n\t\theader, err := zip.FileInfoHeader(info)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s: getting header: %v\", fpath, err)\n\t\t}\n\n\t\tif baseDir != \"\" {\n\t\t\theader.Name = path.Join(baseDir, strings.TrimPrefix(fpath, source))\n\t\t}\n\n\t\tif info.IsDir() {\n\t\t\theader.Name += \"\/\"\n\t\t\theader.Method = zip.Store\n\t\t} else {\n\t\t\text := strings.ToLower(path.Ext(header.Name))\n\t\t\tif _, ok := CompressedFormats[ext]; ok {\n\t\t\t\theader.Method = zip.Store\n\t\t\t} else {\n\t\t\t\theader.Method = zip.Deflate\n\t\t\t}\n\t\t}\n\n\t\twriter, err := w.CreateHeader(header)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s: making header: %v\", fpath, err)\n\t\t}\n\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tif header.Mode().IsRegular() {\n\t\t\tfile, err := os.Open(fpath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%s: opening: %v\", fpath, err)\n\t\t\t}\n\t\t\tdefer file.Close()\n\n\t\t\t_, err = io.CopyN(writer, file, info.Size())\n\t\t\tif err != nil && err != io.EOF {\n\t\t\t\treturn fmt.Errorf(\"%s: copying contents: %v\", fpath, err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\n\/\/ Unzip unzips the .zip file at source into destination.\nfunc Unzip(source, destination string) error {\n\tr, err := zip.OpenReader(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\n\tfor _, zf := range r.File {\n\t\tif err := unzipFile(zf, destination); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc unzipFile(zf *zip.File, destination string) error {\n\tif strings.HasSuffix(zf.Name, \"\/\") {\n\t\treturn mkdir(filepath.Join(destination, zf.Name))\n\t}\n\n\trc, err := zf.Open()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: open compressed file: %v\", zf.Name, err)\n\t}\n\tdefer rc.Close()\n\n\treturn writeNewFile(filepath.Join(destination, zf.Name), rc, zf.FileInfo().Mode())\n}\n\nfunc writeNewFile(fpath string, in io.Reader, fm os.FileMode) error {\n\terr := os.MkdirAll(filepath.Dir(fpath), 0755)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: making directory for file: %v\", fpath, err)\n\t}\n\n\tout, err := os.Create(fpath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: creating new file: %v\", fpath, err)\n\t}\n\tdefer out.Close()\n\n\terr = out.Chmod(fm)\n\tif err != nil && runtime.GOOS != \"windows\" {\n\t\treturn fmt.Errorf(\"%s: changing file mode: %v\", fpath, err)\n\t}\n\n\t_, err = io.Copy(out, in)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: writing file: %v\", fpath, err)\n\t}\n\treturn nil\n}\n\nfunc writeNewSymbolicLink(fpath string, target string) error {\n\terr := os.MkdirAll(filepath.Dir(fpath), 0755)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: making directory for file: %v\", fpath, err)\n\t}\n\n\terr = os.Symlink(target, fpath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: making symbolic link for: %v\", fpath, err)\n\t}\n\n\treturn nil\n}\n\nfunc mkdir(dirPath string) error {\n\terr := os.MkdirAll(dirPath, 0755)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: making directory: %v\", dirPath, err)\n\t}\n\treturn nil\n}\n\n\/\/ CompressedFormats is a (non-exhaustive) set of lowercased\n\/\/ file extensions for formats that are typically already\n\/\/ compressed. Compressing already-compressed files often\n\/\/ results in a larger file, so when possible, we check this\n\/\/ set to avoid that.\nvar CompressedFormats = map[string]struct{}{\n\t\".7z\":   {},\n\t\".avi\":  {},\n\t\".bz2\":  {},\n\t\".cab\":  {},\n\t\".gif\":  {},\n\t\".gz\":   {},\n\t\".jar\":  {},\n\t\".jpeg\": {},\n\t\".jpg\":  {},\n\t\".lz\":   {},\n\t\".lzma\": {},\n\t\".mov\":  {},\n\t\".mp3\":  {},\n\t\".mp4\":  {},\n\t\".mpeg\": {},\n\t\".mpg\":  {},\n\t\".png\":  {},\n\t\".rar\":  {},\n\t\".tgz\":  {},\n\t\".xz\":   {},\n\t\".zip\":  {},\n\t\".zipx\": {},\n}\n\ntype (\n\t\/\/ CompressFunc is a function that makes an archive.\n\tCompressFunc func(string, []string) error\n\n\t\/\/ DecompressFunc is a function that extracts an archive.\n\tDecompressFunc func(string, string) error\n)\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package zmq provides ZeroMQ bindings for Go.\npackage zmq\n\n\/*\n\n#cgo LDFLAGS: -lzmq\n\n#include <zmq.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int my_errno() {\n\treturn errno;\n}\n\n*\/\nimport \"C\"\n\nimport (\n\t\"errors\"\n\t\"unsafe\"\n)\n\nvar (\n\t\/\/ ErrTerminated is returned when a socket's context has been closed.\n\tErrTerminated = errors.New(\"zmq context has been terminated\")\n\t\/\/ ErrTimeout is returned when an operation times out or a non-blocking operation cannot run immediately.\n\tErrTimeout     = errors.New(\"zmq timeout\")\n\tErrInterrupted = errors.New(\"system call interrupted\")\n)\n\ntype SocketType int\n\nconst (\n\tReq    SocketType = C.ZMQ_REQ\n\tRep               = C.ZMQ_REP\n\tDealer            = C.ZMQ_DEALER\n\tRouter            = C.ZMQ_ROUTER\n\tPub               = C.ZMQ_PUB\n\tSub               = C.ZMQ_SUB\n\tXPub              = C.ZMQ_XPUB\n\tXSub              = C.ZMQ_XSUB\n\tPush              = C.ZMQ_PUSH\n\tPull              = C.ZMQ_PULL\n\tPair              = C.ZMQ_PAIR\n)\n\ntype DeviceType int\n\nconst (\n\tQueue     DeviceType = C.ZMQ_QUEUE\n\tForwarder            = C.ZMQ_FORWARDER\n\tStreamer             = C.ZMQ_STREAMER\n)\n\n\/* Context *\/\n\n\/\/ A Context manages multiple Sockets. Contexts are thread-safe.\ntype Context struct {\n\tctx unsafe.Pointer\n}\n\n\/\/ Creates a new Context with the given number of dedicated IO threads.\nfunc NewContextThreads(nthreads int) (ctx *Context, err error) {\n\tptr := C.zmq_init(C.int(nthreads))\n\tif ptr == nil {\n\t\treturn nil, zmqerr()\n\t}\n\treturn &Context{ptr}, nil\n}\n\n\/\/ Creates a new Context with the default number of IO threads (one).\nfunc NewContext() (*Context, error) {\n\treturn NewContextThreads(1)\n}\n\n\/\/ Closes the Context. Close will block until all related Sockets are closed, and all pending messages are either\n\/\/ physically transferred to the network or the socket's linger period expires.\nfunc (c *Context) Close() {\n\tfor {\n\t\tr := C.zmq_term(c.ctx)\n\t\tif r == -1 {\n\t\t\tif C.my_errno() == C.EINTR {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpanic(zmqerr())\n\t\t}\n\t\tbreak\n\t}\n}\n\n\/\/ Creates a new Socket of the specified type.\nfunc (c *Context) Socket(socktype SocketType) (sock *Socket, err error) {\n\tptr := C.zmq_socket(c.ctx, C.int(socktype))\n\tif ptr == nil {\n\t\treturn nil, zmqerr()\n\t}\n\tsock = &Socket{\n\t\tctx:  c,\n\t\tsock: ptr,\n\t}\n\treturn\n}\n\n\/* Socket *\/\n\n\/\/ A ZeroMQ Socket.\ntype Socket struct {\n\tctx  *Context\n\tsock unsafe.Pointer\n}\n\n\/\/ Closes the socket.\nfunc (s *Socket) Close() {\n\tC.zmq_close(s.sock)\n}\n\n\/\/ Binds the socket to the specified local endpoint address.\nfunc (s *Socket) Bind(endpoint string) (err error) {\n\tcstr := C.CString(endpoint)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tr := C.zmq_bind(s.sock, cstr)\n\tif r == -1 {\n\t\terr = zmqerr()\n\t}\n\treturn\n}\n\n\/\/ Connects the socket to the specified remote endpoint.\nfunc (s *Socket) Connect(endpoint string) (err error) {\n\tcstr := C.CString(endpoint)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tr := C.zmq_connect(s.sock, cstr)\n\tif r == -1 {\n\t\terr = zmqerr()\n\t}\n\treturn\n}\n\n\/\/ Sends a single message part. The `more` flag is used to specify whether this is the last part of the message (false),\n\/\/ or if there are more parts to follow (true). SendPart is fairly low-level, and usually Send will be the preferred\n\/\/ method to use.\nfunc (s *Socket) SendPart(part []byte, more bool) (err error) {\n\tfor {\n\t\terr = nil\n\t\tvar msg C.zmq_msg_t\n\t\ttoMsg(&msg, part)\n\t\tflags := C.int(0)\n\t\tif more {\n\t\t\tflags = C.ZMQ_SNDMORE\n\t\t}\n\t\tr := C.zmq_msg_send(&msg, s.sock, flags)\n\t\tif r == -1 {\n\t\t\terr = zmqerr()\n\t\t}\n\t\tC.zmq_msg_close(&msg)\n\t\tif err != ErrInterrupted {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ Sends a message containing a number of parts.\nfunc (s *Socket) Send(parts [][]byte) (err error) {\n\tfor _, part := range parts[:len(parts)-1] {\n\t\tif err = s.SendPart(part, true); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn s.SendPart(parts[len(parts)-1], false)\n}\n\n\/\/ Receives a single part along with a boolean flag (more) indicating whether more parts of the same message follow\n\/\/ (true), or this is the last part of the message (false). As with Send\/SendPart, this is fairly low-level and Recv\n\/\/ should generally be used instead.\nfunc (s *Socket) RecvPart() (part []byte, more bool, err error) {\n\tvar msg C.zmq_msg_t\n\tC.zmq_msg_init(&msg)\n\tfor {\n\t\terr = nil\n\t\tr := C.zmq_msg_recv(&msg, s.sock, 0)\n\t\tif r == -1 {\n\t\t\terr = zmqerr()\n\t\t}\n\t\tif err != ErrInterrupted {\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\tC.zmq_msg_close(&msg)\n\t\treturn\n\t}\n\tpart = fromMsg(&msg)\n\t\/\/ Check for more parts\n\tmore = (s.getInt(C.ZMQ_RCVMORE) != 0)\n\treturn\n}\n\n\/\/ Receives a multi-part message.\nfunc (s *Socket) Recv() (parts [][]byte, err error) {\n\tparts = make([][]byte, 0)\n\tfor more := true; more; {\n\t\tvar part []byte\n\t\tif part, more, err = s.RecvPart(); err != nil {\n\t\t\treturn\n\t\t}\n\t\tparts = append(parts, part)\n\t}\n\treturn\n}\n\n\/\/ Subscribe sets up a filter for incoming messages on Sub sockets.\nfunc (s *Socket) Subscribe(filter []byte) {\n\ts.setBinary(C.ZMQ_SUBSCRIBE, filter)\n}\n\n\/\/ Unsubscribes from a filter on a Sub socket.\nfunc (s *Socket) Unsubscribe(filter []byte) {\n\ts.setBinary(C.ZMQ_UNSUBSCRIBE, filter)\n}\n\n\/* Device *\/\n\n\/\/ Creates and runs a ZeroMQ Device. See zmq_device(3) for more details.\nfunc Device(deviceType DeviceType, frontend, backend *Socket) {\n\tC.zmq_device(C.int(deviceType), frontend.sock, backend.sock)\n}\n\n\/* Utilities *\/\n\nfunc zmqerr() error {\n\teno := C.my_errno()\n\tswitch eno {\n\tcase C.ETERM:\n\t\treturn ErrTerminated\n\tcase C.EAGAIN:\n\t\treturn ErrTimeout\n\tcase C.EINTR:\n\t\treturn ErrInterrupted\n\t}\n\tstr := C.GoString(C.zmq_strerror(eno))\n\treturn errors.New(str)\n}\n\nfunc toMsg(msg *C.zmq_msg_t, data []byte) {\n\tC.zmq_msg_init_size(msg, C.size_t(len(data)))\n\tif len(data) > 0 {\n\t\tC.memcpy(C.zmq_msg_data(msg), unsafe.Pointer(&data[0]), C.size_t(len(data)))\n\t}\n}\nfunc fromMsg(msg *C.zmq_msg_t) []byte {\n\tdefer C.zmq_msg_close(msg)\n\treturn C.GoBytes(C.zmq_msg_data(msg), C.int(C.zmq_msg_size(msg)))\n}\n<commit_msg>Added the global context<commit_after>\/\/ Package zmq provides ZeroMQ bindings for Go.\npackage zmq\n\n\/*\n\n#cgo LDFLAGS: -lzmq\n\n#include <zmq.h>\n#include <stdlib.h>\n#include <string.h>\n\nstatic int my_errno() {\n\treturn errno;\n}\n\n*\/\nimport \"C\"\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\t\"unsafe\"\n)\n\nvar (\n\t\/\/ ErrTerminated is returned when a socket's context has been closed.\n\tErrTerminated = errors.New(\"zmq context has been terminated\")\n\t\/\/ ErrTimeout is returned when an operation times out or a non-blocking operation cannot run immediately.\n\tErrTimeout     = errors.New(\"zmq timeout\")\n\tErrInterrupted = errors.New(\"system call interrupted\")\n)\n\ntype SocketType int\n\nconst (\n\tReq    SocketType = C.ZMQ_REQ\n\tRep               = C.ZMQ_REP\n\tDealer            = C.ZMQ_DEALER\n\tRouter            = C.ZMQ_ROUTER\n\tPub               = C.ZMQ_PUB\n\tSub               = C.ZMQ_SUB\n\tXPub              = C.ZMQ_XPUB\n\tXSub              = C.ZMQ_XSUB\n\tPush              = C.ZMQ_PUSH\n\tPull              = C.ZMQ_PULL\n\tPair              = C.ZMQ_PAIR\n)\n\ntype DeviceType int\n\nconst (\n\tQueue     DeviceType = C.ZMQ_QUEUE\n\tForwarder            = C.ZMQ_FORWARDER\n\tStreamer             = C.ZMQ_STREAMER\n)\n\n\/* Context *\/\n\n\/\/ A Context manages multiple Sockets. Contexts are thread-safe.\ntype Context struct {\n\tctx unsafe.Pointer\n}\n\n\/\/ Creates a new Context with the given number of dedicated IO threads.\nfunc NewContextThreads(nthreads int) (ctx *Context, err error) {\n\tptr := C.zmq_init(C.int(nthreads))\n\tif ptr == nil {\n\t\treturn nil, zmqerr()\n\t}\n\treturn &Context{ptr}, nil\n}\n\n\/\/ Creates a new Context with the default number of IO threads (one).\nfunc NewContext() (*Context, error) {\n\treturn NewContextThreads(1)\n}\n\n\/\/ Closes the Context. Close will block until all related Sockets are closed, and all pending messages are either\n\/\/ physically transferred to the network or the socket's linger period expires.\nfunc (c *Context) Close() {\n\tfor {\n\t\tr := C.zmq_term(c.ctx)\n\t\tif r == -1 {\n\t\t\tif C.my_errno() == C.EINTR {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpanic(zmqerr())\n\t\t}\n\t\tbreak\n\t}\n}\n\n\/\/ Creates a new Socket of the specified type.\nfunc (c *Context) Socket(socktype SocketType) (sock *Socket, err error) {\n\tptr := C.zmq_socket(c.ctx, C.int(socktype))\n\tif ptr == nil {\n\t\treturn nil, zmqerr()\n\t}\n\tsock = &Socket{\n\t\tctx:  c,\n\t\tsock: ptr,\n\t}\n\tsock.SetLinger(0)\n\treturn\n}\n\n\/* Global context *\/\n\nvar (\n\tglobalCtx  *Context = nil\n\tglobalLock sync.Mutex\n)\n\n\/\/ Returns the default Context. Note that the context will not be created until\n\/\/ the first call to DefaultContext.\nfunc DefaultContext() *Context {\n\tglobalLock.Lock()\n\tdefer globalLock.Unlock()\n\tif globalCtx == nil {\n\t\tvar err error\n\t\tif globalCtx, err = NewContext(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\treturn globalCtx\n}\n\n\/\/ Creates a new socket using the default context (see DefaultContext).\nfunc NewSocket(socktype SocketType) (*Socket, error) {\n\treturn DefaultContext().Socket(socktype)\n}\n\n\/* Socket *\/\n\n\/\/ A ZeroMQ Socket.\ntype Socket struct {\n\tctx  *Context\n\tsock unsafe.Pointer\n}\n\n\/\/ Closes the socket.\nfunc (s *Socket) Close() {\n\tC.zmq_close(s.sock)\n}\n\n\/\/ Binds the socket to the specified local endpoint address.\nfunc (s *Socket) Bind(endpoint string) (err error) {\n\tcstr := C.CString(endpoint)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tr := C.zmq_bind(s.sock, cstr)\n\tif r == -1 {\n\t\terr = zmqerr()\n\t}\n\treturn\n}\n\n\/\/ Connects the socket to the specified remote endpoint.\nfunc (s *Socket) Connect(endpoint string) (err error) {\n\tcstr := C.CString(endpoint)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tr := C.zmq_connect(s.sock, cstr)\n\tif r == -1 {\n\t\terr = zmqerr()\n\t}\n\treturn\n}\n\n\/\/ Sends a single message part. The `more` flag is used to specify whether this is the last part of the message (false),\n\/\/ or if there are more parts to follow (true). SendPart is fairly low-level, and usually Send will be the preferred\n\/\/ method to use.\nfunc (s *Socket) SendPart(part []byte, more bool) (err error) {\n\tfor {\n\t\terr = nil\n\t\tvar msg C.zmq_msg_t\n\t\ttoMsg(&msg, part)\n\t\tflags := C.int(0)\n\t\tif more {\n\t\t\tflags = C.ZMQ_SNDMORE\n\t\t}\n\t\tr := C.zmq_msg_send(&msg, s.sock, flags)\n\t\tif r == -1 {\n\t\t\terr = zmqerr()\n\t\t}\n\t\tC.zmq_msg_close(&msg)\n\t\tif err != ErrInterrupted {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ Sends a message containing a number of parts.\nfunc (s *Socket) Send(parts [][]byte) (err error) {\n\tfor _, part := range parts[:len(parts)-1] {\n\t\tif err = s.SendPart(part, true); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn s.SendPart(parts[len(parts)-1], false)\n}\n\n\/\/ Receives a single part along with a boolean flag (more) indicating whether more parts of the same message follow\n\/\/ (true), or this is the last part of the message (false). As with Send\/SendPart, this is fairly low-level and Recv\n\/\/ should generally be used instead.\nfunc (s *Socket) RecvPart() (part []byte, more bool, err error) {\n\tvar msg C.zmq_msg_t\n\tC.zmq_msg_init(&msg)\n\tfor {\n\t\terr = nil\n\t\tr := C.zmq_msg_recv(&msg, s.sock, 0)\n\t\tif r == -1 {\n\t\t\terr = zmqerr()\n\t\t}\n\t\tif err != ErrInterrupted {\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\tC.zmq_msg_close(&msg)\n\t\treturn\n\t}\n\tpart = fromMsg(&msg)\n\t\/\/ Check for more parts\n\tmore = (s.getInt(C.ZMQ_RCVMORE) != 0)\n\treturn\n}\n\n\/\/ Receives a multi-part message.\nfunc (s *Socket) Recv() (parts [][]byte, err error) {\n\tparts = make([][]byte, 0)\n\tfor more := true; more; {\n\t\tvar part []byte\n\t\tif part, more, err = s.RecvPart(); err != nil {\n\t\t\treturn\n\t\t}\n\t\tparts = append(parts, part)\n\t}\n\treturn\n}\n\n\/\/ Subscribe sets up a filter for incoming messages on Sub sockets.\nfunc (s *Socket) Subscribe(filter []byte) {\n\ts.setBinary(C.ZMQ_SUBSCRIBE, filter)\n}\n\n\/\/ Unsubscribes from a filter on a Sub socket.\nfunc (s *Socket) Unsubscribe(filter []byte) {\n\ts.setBinary(C.ZMQ_UNSUBSCRIBE, filter)\n}\n\n\/* Device *\/\n\n\/\/ Creates and runs a ZeroMQ Device. See zmq_device(3) for more details.\nfunc Device(deviceType DeviceType, frontend, backend *Socket) {\n\tC.zmq_device(C.int(deviceType), frontend.sock, backend.sock)\n}\n\n\/* Utilities *\/\n\nfunc zmqerr() error {\n\teno := C.my_errno()\n\tswitch eno {\n\tcase C.ETERM:\n\t\treturn ErrTerminated\n\tcase C.EAGAIN:\n\t\treturn ErrTimeout\n\tcase C.EINTR:\n\t\treturn ErrInterrupted\n\t}\n\tstr := C.GoString(C.zmq_strerror(eno))\n\treturn errors.New(str)\n}\n\nfunc toMsg(msg *C.zmq_msg_t, data []byte) {\n\tC.zmq_msg_init_size(msg, C.size_t(len(data)))\n\tif len(data) > 0 {\n\t\tC.memcpy(C.zmq_msg_data(msg), unsafe.Pointer(&data[0]), C.size_t(len(data)))\n\t}\n}\nfunc fromMsg(msg *C.zmq_msg_t) []byte {\n\tdefer C.zmq_msg_close(msg)\n\treturn C.GoBytes(C.zmq_msg_data(msg), C.int(C.zmq_msg_size(msg)))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Note on file organization:  tests are invoked in sequence by Go test\n * harness and that fact is used here to affirm a set of assumptions as\n * we test the constructs.  As assumptions are affirmed, they are noted\n * in comments below.  So, do not change the order of the tests.\n *\/\n\npackage contextual\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\/\/ ============================================================================\n\/\/ testing: contextual.context\n\/\/ ============================================================================\n\n\/\/ NOP - just feedback for test runs. std. per each construct\nfunc TestContextStructStart_NOP(t *testing.T) {\n\tfmt.Println(\"contextual.context\")\n}\n\n\/\/ helper\ntype emptyStruct struct{}\n\n\/\/ helper\nfunc mixedTypeValueSet() []interface{} {\n\tnum := 10\n\tstr := emptyStruct{}\n\tptr := &emptyStruct{}\n\tch := make(chan emptyStruct)\n\tfn := func() {} \/\/ func() is \"uncomparable type\" oh, well.\n\tpfn := &fn\n\ttxt := \"hello there\"\n\n\treturn []interface{}{\n\t\tnum, str, ptr, ch \/*fn,*\/, pfn, txt,\n\t}\n\n}\n\n\/\/ helper\nfunc genericUniqueIndexNames(n int) []string {\n\tvar names []string = make([]string, n)\n\tvar sanitycheck = make(map[string]int)\n\n\tfor i := 0; i < n; i++ {\n\t\tnames[i] = fmt.Sprintf(\"value[%d]\", i)\n\t\tsanitycheck[names[i]] = i\n\t}\n\t\/\/ make sure names are indeed unique\n\tif len(sanitycheck) != len(names) {\n\t\tpanic(\"genericUniqueIndexNames\")\n\t}\n\n\treturn names\n}\n\n\/* --- CHECK a1 ---------------------------------------------------------------\n *  a1: correct construction and intial state\n *\n * tests for correct construction and initialization of contexts, and asserts\n * on input params of the associated functions.\n * - Context#Size()    \/\/ on init\n * - Context#IsEmpty() \/\/ on init\n *\n * assumptions:\n * - none\n *\/\n\nfunc TestNewContext(t *testing.T) {\n\tvar ctx Context = NewContext()\n\tif ctx == nil {\n\t\tt.Fatalf(\"NewContext returned nil ref\")\n\t}\n\n\tfmt.Println(\"\\tcreate root context\")\n}\n\nfunc TestNewContextChild(t *testing.T) {\n\trootCtx := NewContext()\n\n\tctx, e := ChildContext(rootCtx)\n\tif e != nil {\n\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t}\n\tif ctx == nil {\n\t\tt.Fatalf(\"ChildContext returned nil ref\")\n\t}\n\tctx, e = ChildContext(nil)\n\tif e == nil {\n\t\tt.Fatalf(\"Expecting error on ChildContext(nil)\")\n\t}\n\n\tfmt.Println(\"\\tcreate child context\")\n}\n\nfunc TestNewContextInit(t *testing.T) {\n\tctx := NewContext()\n\tif ctx.IsEmpty() != true {\n\t\tt.Fatalf(\"New Context#IsEmpty returned false\")\n\t}\n\tif ctx.Size() != 0 {\n\t\tt.Fatalf(\"New Context#Size returned non-zero\")\n\t}\n\n\tfmt.Println(\"\\ttest context init - root\")\n}\n\nfunc TestNewContextChildInit(t *testing.T) {\n\trootCtx := NewContext()\n\n\tctx, _ := ChildContext(rootCtx)\n\tif ctx.IsEmpty() != true {\n\t\tt.Fatalf(\"New child Context#IsEmpty returned false\")\n\t}\n\tif ctx.Size() != 0 {\n\t\tt.Fatalf(\"New child Context#Size returned non-zero\")\n\t}\n\n\tfmt.Println(\"\\ttest context init - child\")\n}\n\n\/* --- CONFIRMED a1 ----------------------------------------------------------*\/\n\n\/* --- CHECK a2 ---------------------------------------------------------------\n * - a2: correct parent\/child order and IsRoot\n *\n * tests for parent child relationship and correct behavior for\n * Context#IsRoot()\n *\n * assumptions:\n * - a1\n *\/\n\n\/\/ tests contextual.context's compliance with Context#IsRoot()\nfunc TestIsRoot(t *testing.T) {\n\t\/\/ a1 - don't bother with error\/nil checks\n\trootCtx := NewContext()\n\tif rootCtx.IsRoot() != true {\n\t\tt.Fatalf(\"IsRoot() for a root context must return true\")\n\t}\n\tif ctx, _ := ChildContext(rootCtx); ctx.IsRoot() {\n\t\tt.Fatalf(\"IsRoot() for a child context must return false\")\n\t}\n\n\tfmt.Println(\"\\tContext#IsRoot()\")\n}\n\n\/* --- CONFIRMED a2 ----------------------------------------------------------*\/\n\n\/* --- CHECK a3 ---------------------------------------------------------------\n * - a3: correct basic ops for a single (root) context\n *\n * tests for correct behavior of the following Context methods:\n * - Context#Bind()\n * - Context#Lookup()\n * - Context#Size()    \/\/ post init\n * - Context#IsEmpty() \/\/ post init\n * - Context#Unbind()\n * - Context#Rebind()\n * assumptions:\n * - a1\n * - a2\n *\/\n\n\/\/ Confirm spec compliance for faults\n\/\/ {Lookup, LookupN, Bind, Unbind}\nfunc TestContextSpecdError(t *testing.T) {\n\t\/\/ setup\n\tctx := NewContext()\n\n\t\/\/ Lookup()\n\n\t\/\/ test specified errors for Lookup\n\t\/\/  NilNameError <= zero-value names are not allowed\n\tif _, e := ctx.Lookup(\"\"); e == nil {\n\t\tt.Fatalf(\"Lookup(nil) expected error: %s\", NilNameError)\n\t}\n\tv, e := ctx.Lookup(\"no-such-binding\")\n\tif e != nil {\n\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t}\n\tif v != nil {\n\t\tt.Fatalf(\"Lookup(\\\"\\\") - expected:%v got:%v\", nil, v)\n\t}\n\n\t\/\/ LookupN()\n\n\t\/\/  NilNameError <= nil names are not allowed\n\t\/\/  NegativeNArgError <= n is negative\n\tif _, e := ctx.LookupN(\"\", 0); e == nil {\n\t\tt.Fatalf(\"Lookup(nil) expected error: %s\", NilNameError)\n\t}\n\tv, e = ctx.LookupN(\"no-such-binding\", 0)\n\tif e != nil {\n\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t}\n\tif v != nil {\n\t\tt.Fatalf(\"Lookup(\\\"\\\") - expected:%v got:%v\", nil, v)\n\t}\n\n\t\/\/ Bind()\n\n\t\/\/ test specified errors for Bind\n\t\/\/  NilNameError <= zero-value names are not allowed\n\t\/\/  NilValueError <= nil values are not allowed\n\t\/\/  AlreadyBoundError <= a value is already bound to the name\n\tif e := ctx.Bind(\"\", \"some value\"); e == nil {\n\t\tt.Fatalf(\"Bind(\\\"\\\") expected error: %s\", NilNameError)\n\t}\n\tif e := ctx.Bind(\"some key\", nil); e == nil {\n\t\tt.Fatalf(\"Bind(\\\"\\\") expected error: %s\", NilValueError)\n\t}\n\n\t\/\/ Unbind()\n\n\t\/\/ test specified errors for Unbind\n\t\/\/  NilNameError <= zero-value names are not allowed\n\t\/\/  NoSuchBindingError <= no values are bound to the name\n\twat, e := ctx.Unbind(\"\")\n\tif e == nil {\n\t\tt.Fatalf(\"Unbind(\\\"\\\") expected error: %s\", NilNameError)\n\t}\n\tif wat != nil {\n\t\tt.Fatalf(\"Unexpected value on faulted return: %s\", wat)\n\t}\n\twat, e = ctx.Unbind(\"some key\")\n\tif e == nil {\n\t\tt.Fatalf(\"Unbind(\\\"\\\") expected error: %s\", NoSuchBindingError)\n\t}\n\tif wat != nil {\n\t\tt.Fatalf(\"Unexpected value on faulted return: %s\", wat)\n\t}\n\n\t\/\/ Rebind()\n\n\t\/\/ test specified errors for Rebind\n\t\/\/  NoSuchBinding <= no values were bound to the name\n\t\/\/  NilNameError <= zero-value names are not allowed\n\t\/\/  NilValueError <= nil values are not allowed\n\twat, e = ctx.Rebind(\"\", \"some value\")\n\tif e == nil {\n\t\tt.Fatalf(\"Rebind(\\\"\\\", v) expected error: %s\", NilNameError)\n\t}\n\tif wat != nil {\n\t\tt.Fatalf(\"Unexpected value on faulted return: %s\", wat)\n\t}\n\twat, e = ctx.Rebind(\"some key\", \"some value\")\n\tif e == nil {\n\t\tt.Fatalf(\"Rebind(\\\"\\\", v) expected error: %s\", NoSuchBindingError)\n\t}\n\tif wat != nil {\n\t\tt.Fatalf(\"Unexpected value on faulted return: %s\", wat)\n\t}\n\tif wat, e = ctx.Rebind(\"doesn't matter\", nil); e == nil {\n\t\tt.Fatalf(\"Rebind (nil) expected error: %s\", NilValueError)\n\t}\n}\n\nfunc TestSingleContext(t *testing.T) {\n\t\/\/ setup\n\tctx := NewContext()\n\tvalues := mixedTypeValueSet()\n\tnames := genericUniqueIndexNames(len(values))\n\n\t\/\/ Bind()\n\n\tfor i, name := range names {\n\t\tvalue := values[i]\n\t\tif e := ctx.Bind(name, value); e != nil {\n\t\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t\t}\n\t}\n\n\t\/\/ Lookup()\n\n\tfor i, name := range names {\n\t\texpv := values[i]\n\t\tv, e := ctx.Lookup(name)\n\t\tif e != nil {\n\t\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t\t}\n\t\tif v != expv {\n\t\t\tt.Fatalf(\"Lookup(%s) - expected:%s got:%s\", name, expv, v)\n\t\t}\n\t}\n\n\t\/\/ IsEmpty()\n\n\tif b := ctx.IsEmpty(); b {\n\t\tt.Fatalf(\"IsEmpty() - expected:%s got:%s\", false, b)\n\t}\n\n\t\/\/ Size()\n\n\tif n := ctx.Size(); n != len(names) {\n\t\tt.Fatalf(\"Size() - expected:%s got:%s\", len(names), n)\n\t}\n\n\t\/\/ Unbind()\n\n\tfor i, name := range names {\n\t\texpv := values[i]\n\t\tv, e := ctx.Unbind(name)\n\t\tif e != nil {\n\t\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t\t}\n\t\tif v != expv {\n\t\t\tt.Fatalf(\"Unbind(%s) - expected:%s got:%s\", name, expv, v)\n\t\t}\n\t}\n\t\/\/ confirm Size and IsEmpty\n\tif !ctx.IsEmpty() {\n\t\tt.Fatalf(\"IsEmpty() returned true\")\n\t}\n\tif ctx.Size() != 0 {\n\t\tt.Fatalf(\"Size() returned non-zero\")\n\t}\n\n\t\/\/ Rebind()\n\tctx.Bind(names[0], values[0]) \/\/ setup\n\toldv, e := ctx.Rebind(names[0], \"on the rebound\")\n\tif e != nil {\n\t\tt.Fatalf(\"unexpected error: %s\", e)\n\t}\n\tif oldv != values[0] {\n\t\tt.Fatalf(\"Rebind() old value - expected:%v got:%v\", values[0], oldv)\n\t}\n\n\tfmt.Println(\"\\tContext compliance - root\")\n}\n\n\/* --- CONFIRMED a3 ----------------------------------------------------------*\/\n\n\/* --- CHECK a4 ---------------------------------------------------------------\n * - a4: correct basic ops for context hierarchy\n *\n * tests for correct behavior of the following Context methods:\n * - Context#Bind()\n * - Context#Lookup()\n * - Context#Size()    \/\/ post init\n * - Context#IsEmpty() \/\/ post init\n * - Context#Unbind()\n * - Context#Rebind()\n * assumptions:\n * - a1\n * - a2\n * - a3\n *\/\n\nfunc TestContextHierarchy(t *testing.T) {\n\t\/\/ setup\n\t\/\/\tctx := NewContext()\n\t\/\/\tchild1, _ := ChildContext(ctx)\n\t\/\/\tchild1_1, _ := ChildContext(child1)\n\t\/\/\tchild2, _ := ChildContext(ctx)\n\t\/\/\n\t\/\/\tvalues := mixedTypeValueSet()\n\t\/\/\tnames := genericUniqueIndexNames(len(values))\n}\n\n\/* --- CONFIRMED a4 ----------------------------------------------------------*\/\n<commit_msg>WIP - tests<commit_after>\/* Note on file organization:  tests are invoked in sequence by Go test\n * harness and that fact is used here to affirm a set of assumptions as\n * we test the constructs.  As assumptions are affirmed, they are noted\n * in comments below.  So, do not change the order of the tests.\n *\/\n\npackage contextual\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\n\/\/ ============================================================================\n\/\/ testing: contextual.context\n\/\/ ============================================================================\n\n\/\/ NOP - just feedback for test runs. std. per each construct\nfunc TestContextStructStart_NOP(t *testing.T) {\n\tfmt.Println(\"contextual.context\")\n}\n\n\/\/ helper\ntype emptyStruct struct{}\n\n\/\/ helper\nfunc mixedTypeValueSet() []interface{} {\n\tnum := 10\n\tstr := emptyStruct{}\n\tptr := &emptyStruct{}\n\tch := make(chan emptyStruct)\n\tfn := func() {} \/\/ func() is \"uncomparable type\" oh, well.\n\tpfn := &fn\n\ttxt := \"hello there\"\n\n\treturn []interface{}{\n\t\tnum, str, ptr, ch \/*fn,*\/, pfn, txt,\n\t}\n\n}\n\n\/\/ helper\nfunc genericUniqueIndexNames(n int) []string {\n\tvar names []string = make([]string, n)\n\tvar sanitycheck = make(map[string]int)\n\n\tfor i := 0; i < n; i++ {\n\t\tnames[i] = fmt.Sprintf(\"value[%d]\", i)\n\t\tsanitycheck[names[i]] = i\n\t}\n\t\/\/ make sure names are indeed unique\n\tif len(sanitycheck) != len(names) {\n\t\tpanic(\"genericUniqueIndexNames\")\n\t}\n\n\treturn names\n}\n\n\/* --- CHECK a1 ---------------------------------------------------------------\n *  a1: correct construction and intial state\n *\n * tests for correct construction and initialization of contexts, and asserts\n * on input params of the associated functions.\n * - Context#Size()    \/\/ on init\n * - Context#IsEmpty() \/\/ on init\n *\n * assumptions:\n * - none\n *\/\n\nfunc TestNewContext(t *testing.T) {\n\tvar ctx Context = NewContext()\n\tif ctx == nil {\n\t\tt.Fatalf(\"NewContext returned nil ref\")\n\t}\n\n\tfmt.Println(\"\\tcreate root context\")\n}\n\nfunc TestNewContextChild(t *testing.T) {\n\trootCtx := NewContext()\n\n\tctx, e := ChildContext(rootCtx)\n\tif e != nil {\n\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t}\n\tif ctx == nil {\n\t\tt.Fatalf(\"ChildContext returned nil ref\")\n\t}\n\tctx, e = ChildContext(nil)\n\tif e == nil {\n\t\tt.Fatalf(\"Expecting error on ChildContext(nil)\")\n\t}\n\n\tfmt.Println(\"\\tcreate child context\")\n}\n\nfunc TestNewContextInit(t *testing.T) {\n\tctx := NewContext()\n\tif ctx.IsEmpty() != true {\n\t\tt.Fatalf(\"New Context#IsEmpty returned false\")\n\t}\n\tif ctx.Size() != 0 {\n\t\tt.Fatalf(\"New Context#Size returned non-zero\")\n\t}\n\n\tfmt.Println(\"\\ttest context init - root\")\n}\n\nfunc TestNewContextChildInit(t *testing.T) {\n\trootCtx := NewContext()\n\n\tctx, _ := ChildContext(rootCtx)\n\tif ctx.IsEmpty() != true {\n\t\tt.Fatalf(\"New child Context#IsEmpty returned false\")\n\t}\n\tif ctx.Size() != 0 {\n\t\tt.Fatalf(\"New child Context#Size returned non-zero\")\n\t}\n\n\tfmt.Println(\"\\ttest context init - child\")\n}\n\n\/* --- CONFIRMED a1 ----------------------------------------------------------*\/\n\n\/* --- CHECK a2 ---------------------------------------------------------------\n * - a2: correct parent\/child order and IsRoot\n *\n * tests for parent child relationship and correct behavior for\n * Context#IsRoot()\n *\n * assumptions:\n * - a1\n *\/\n\n\/\/ tests contextual.context's compliance with Context#IsRoot()\nfunc TestIsRoot(t *testing.T) {\n\t\/\/ a1 - don't bother with error\/nil checks\n\trootCtx := NewContext()\n\tif rootCtx.IsRoot() != true {\n\t\tt.Fatalf(\"IsRoot() for a root context must return true\")\n\t}\n\tif ctx, _ := ChildContext(rootCtx); ctx.IsRoot() {\n\t\tt.Fatalf(\"IsRoot() for a child context must return false\")\n\t}\n\n\tfmt.Println(\"\\tContext#IsRoot()\")\n}\n\n\/* --- CONFIRMED a2 ----------------------------------------------------------*\/\n\n\/* --- CHECK a3 ---------------------------------------------------------------\n * - a3: correct basic ops for a single (root) context\n *\n * tests for correct behavior of the following Context methods:\n * - Context#Bind()\n * - Context#Lookup()\n * - Context#Size()    \/\/ post init\n * - Context#IsEmpty() \/\/ post init\n * - Context#Unbind()\n * - Context#Rebind()\n * assumptions:\n * - a1\n * - a2\n *\/\n\n\/\/ Confirm spec compliance for faults\n\/\/ {Lookup, LookupN, Bind, Unbind}\nfunc TestContextSpecdError(t *testing.T) {\n\t\/\/ setup\n\tctx := NewContext()\n\n\t\/\/ Lookup()\n\n\t\/\/ test specified errors for Lookup\n\t\/\/  NilNameError <= zero-value names are not allowed\n\tif _, e := ctx.Lookup(\"\"); e == nil {\n\t\tt.Fatalf(\"Lookup(nil) expected error: %s\", NilNameError)\n\t}\n\tv, e := ctx.Lookup(\"no-such-binding\")\n\tif e != nil {\n\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t}\n\tif v != nil {\n\t\tt.Fatalf(\"Lookup(\\\"\\\") - expected:%v got:%v\", nil, v)\n\t}\n\n\t\/\/ LookupN()\n\n\t\/\/  NilNameError <= nil names are not allowed\n\t\/\/  NegativeNArgError <= n is negative\n\tif _, e := ctx.LookupN(\"\", 0); e == nil {\n\t\tt.Fatalf(\"Lookup(nil) expected error: %s\", NilNameError)\n\t}\n\tv, e = ctx.LookupN(\"no-such-binding\", 0)\n\tif e != nil {\n\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t}\n\tif v != nil {\n\t\tt.Fatalf(\"Lookup(\\\"\\\") - expected:%v got:%v\", nil, v)\n\t}\n\n\t\/\/ Bind()\n\n\t\/\/ test specified errors for Bind\n\t\/\/  NilNameError <= zero-value names are not allowed\n\t\/\/  NilValueError <= nil values are not allowed\n\t\/\/  AlreadyBoundError <= a value is already bound to the name\n\tif e := ctx.Bind(\"\", \"some value\"); e == nil {\n\t\tt.Fatalf(\"Bind(\\\"\\\") expected error: %s\", NilNameError)\n\t}\n\tif e := ctx.Bind(\"some key\", nil); e == nil {\n\t\tt.Fatalf(\"Bind(\\\"\\\") expected error: %s\", NilValueError)\n\t}\n\n\t\/\/ Unbind()\n\n\t\/\/ test specified errors for Unbind\n\t\/\/  NilNameError <= zero-value names are not allowed\n\t\/\/  NoSuchBindingError <= no values are bound to the name\n\twat, e := ctx.Unbind(\"\")\n\tif e == nil {\n\t\tt.Fatalf(\"Unbind(\\\"\\\") expected error: %s\", NilNameError)\n\t}\n\tif wat != nil {\n\t\tt.Fatalf(\"Unexpected value on faulted return: %s\", wat)\n\t}\n\twat, e = ctx.Unbind(\"some key\")\n\tif e == nil {\n\t\tt.Fatalf(\"Unbind(\\\"\\\") expected error: %s\", NoSuchBindingError)\n\t}\n\tif wat != nil {\n\t\tt.Fatalf(\"Unexpected value on faulted return: %s\", wat)\n\t}\n\n\t\/\/ Rebind()\n\n\t\/\/ test specified errors for Rebind\n\t\/\/  NoSuchBinding <= no values were bound to the name\n\t\/\/  NilNameError <= zero-value names are not allowed\n\t\/\/  NilValueError <= nil values are not allowed\n\twat, e = ctx.Rebind(\"\", \"some value\")\n\tif e == nil {\n\t\tt.Fatalf(\"Rebind(\\\"\\\", v) expected error: %s\", NilNameError)\n\t}\n\tif wat != nil {\n\t\tt.Fatalf(\"Unexpected value on faulted return: %s\", wat)\n\t}\n\twat, e = ctx.Rebind(\"some key\", \"some value\")\n\tif e == nil {\n\t\tt.Fatalf(\"Rebind(\\\"\\\", v) expected error: %s\", NoSuchBindingError)\n\t}\n\tif wat != nil {\n\t\tt.Fatalf(\"Unexpected value on faulted return: %s\", wat)\n\t}\n\tif wat, e = ctx.Rebind(\"doesn't matter\", nil); e == nil {\n\t\tt.Fatalf(\"Rebind (nil) expected error: %s\", NilValueError)\n\t}\n}\n\nfunc TestSingleContext(t *testing.T) {\n\t\/\/ setup\n\tctx := NewContext()\n\tvalues := mixedTypeValueSet()\n\tnames := genericUniqueIndexNames(len(values))\n\n\t\/\/ Bind()\n\n\tfor i, name := range names {\n\t\tvalue := values[i]\n\t\tif e := ctx.Bind(name, value); e != nil {\n\t\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t\t}\n\t}\n\n\t\/\/ Lookup()\n\n\tfor i, name := range names {\n\t\texpv := values[i]\n\t\tv, e := ctx.Lookup(name)\n\t\tif e != nil {\n\t\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t\t}\n\t\tif v != expv {\n\t\t\tt.Fatalf(\"Lookup(%s) - expected:%s got:%s\", name, expv, v)\n\t\t}\n\t}\n\n\t\/\/ IsEmpty()\n\n\tif b := ctx.IsEmpty(); b {\n\t\tt.Fatalf(\"IsEmpty() - expected:%s got:%s\", false, b)\n\t}\n\n\t\/\/ Size()\n\n\tif n := ctx.Size(); n != len(names) {\n\t\tt.Fatalf(\"Size() - expected:%s got:%s\", len(names), n)\n\t}\n\n\t\/\/ Unbind()\n\n\tfor i, name := range names {\n\t\texpv := values[i]\n\t\tv, e := ctx.Unbind(name)\n\t\tif e != nil {\n\t\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t\t}\n\t\tif v != expv {\n\t\t\tt.Fatalf(\"Unbind(%s) - expected:%s got:%s\", name, expv, v)\n\t\t}\n\t}\n\t\/\/ confirm Size and IsEmpty\n\tif !ctx.IsEmpty() {\n\t\tt.Fatalf(\"IsEmpty() returned true\")\n\t}\n\tif ctx.Size() != 0 {\n\t\tt.Fatalf(\"Size() returned non-zero\")\n\t}\n\n\t\/\/ Rebind()\n\tctx.Bind(names[0], values[0]) \/\/ setup\n\toldv, e := ctx.Rebind(names[0], \"on the rebound\")\n\tif e != nil {\n\t\tt.Fatalf(\"unexpected error: %s\", e)\n\t}\n\tif oldv != values[0] {\n\t\tt.Fatalf(\"Rebind() old value - expected:%v got:%v\", values[0], oldv)\n\t}\n\n\tfmt.Println(\"\\tContext compliance - root\")\n}\n\n\/* --- CONFIRMED a3 ----------------------------------------------------------*\/\n\n\/* --- CHECK a4 ---------------------------------------------------------------\n * - a4: correct basic ops for context hierarchy\n *\n * tests for correct behavior of the following Context methods:\n * - Context#Bind()\n * - Context#Lookup()\n * - Context#LookupN()\n * - Context#Size()    \/\/ post init\n * - Context#IsEmpty() \/\/ post init\n * - Context#Unbind()\n * - Context#Rebind()\n * assumptions:\n * - a1\n * - a2\n * - a3\n *\/\n\nfunc TestContextHierarchy(t *testing.T) {\n\t\/\/\tsetup\n\tcr := NewContext()\n\tc1, _ := ChildContext(cr)\n\tc2, _ := ChildContext(cr)\n\tc1_1, _ := ChildContext(c1)\n\tc1_2, _ := ChildContext(c1)\n\tc2_1, _ := ChildContext(c2)\n\tc1_1_1, _ := ChildContext(c1_1)\n\n\tchildren := []Context{c1, c2, c1_1, c1_2, c2_1, c1_1_1}\n\tchildrenL1 := []Context{c1, c2}\n\tchildrenL2 := []Context{c1_1, c1_2, c2_1}\n\tchildrenL3 := []Context{c1_1_1}\n\tlevels := [][]Context{childrenL1, childrenL2, childrenL3}\n\n\tvalues := mixedTypeValueSet()\n\tnames := genericUniqueIndexNames(len(values))\n\n\t\/\/ Bind, Lookup, LookupN\n\n\tcr.Bind(names[0], values[0]) \/\/ setup - a single binding in root\n\n\t\/\/ basic lookup, IsEmpty, and Size for children\n\t\/\/ all should see binding in root\n\t\/\/ size for all is 1, non-empty\n\tfor i, ctx := range children {\n\t\tv, e := ctx.Lookup(names[0])\n\t\tif e != nil {\n\t\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t\t}\n\t\tif v != values[0] {\n\t\t\tt.Fatalf(\"for children[%d] - Lookup(%s) - expected:%v got:%v\", i, names[0], v)\n\t\t}\n\t\tif ctx.IsEmpty() {\n\t\t\tt.Fatalf(\"for children[%d] - IsEmpty(%s) - expected:false\", i)\n\t\t}\n\t\tif s := ctx.Size(); s != 1 {\n\t\t\tt.Fatalf(\"for children[%d] - IsEmpty(%s) - expected:%d, got:%d\", i, 1, s)\n\t\t}\n\t}\n\n\t\/\/ limited lookup with N step up\n\t\/\/ N = 0 : none\n\t\/\/ N = 1 : L1\n\t\/\/ N = 2 : L1, L2\n\t\/\/ N = 3 : L1, L2, L3\n\tvar n int\n\tfor l := 0; l < len(levels); l++ {\n\t\tfor i, ctx := range levels[l] {\n\t\t\t\/\/ all should see\n\t\t\tv, e := ctx.LookupN(names[0], l+1)\n\t\t\tif e != nil {\n\t\t\t\tt.Fatalf(\"Unexpected error: %s\", e)\n\t\t\t}\n\t\t\tif v != values[0] {\n\t\t\t\tt.Fatalf(\"l[%d] i[%d] n[%d]- Lookup(%s) - expected:%v got:%v\", l, i, n, names[0], v)\n\t\t\t}\n\t\t\t\/\/ none should see\n\t\t\tv, _ = ctx.LookupN(names[0], l)\n\t\t\tif v != nil {\n\t\t\t\tt.Fatalf(\"l[%d] i[%d] n[%d]- Lookup(%s) - expected:%v got:%v\", l, i, n, nil, v)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/* --- CONFIRMED a4 ----------------------------------------------------------*\/\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage git\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n\t\"sync\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\tutilpointer \"k8s.io\/utils\/pointer\"\n)\n\n\/\/ ClientFactory knows how to create clientFactory for repos\ntype ClientFactory interface {\n\t\/\/ ClientFromDir creates a client that operates on a repo that has already\n\t\/\/ been cloned to the given directory.\n\tClientFromDir(org, repo, dir string) (RepoClient, error)\n\t\/\/ ClientFor creates a client that operates on a new clone of the repo.\n\tClientFor(org, repo string) (RepoClient, error)\n\n\t\/\/ Clean removes the caches used to generate clients\n\tClean() error\n}\n\n\/\/ RepoClient exposes interactions with a git repo\ntype RepoClient interface {\n\tPublisher\n\tInteractor\n}\n\ntype repoClient struct {\n\tpublisher\n\tinteractor\n}\n\ntype ClientFactoryOpts struct {\n\t\/\/ Host, defaults to \"github.com\" if unset\n\tHost string\n\t\/\/ UseSSH, defaults to false\n\tUseSSH *bool\n\t\/\/ The directory in which the cache should be\n\t\/\/ created. Defaults to the \"\/var\/tmp\" on\n\t\/\/ Linux and os.TempDir otherwise\n\tCacheDirBase *string\n\t\/\/ If unset, publishing action will error\n\tUsername LoginGetter\n\t\/\/ If unset, publishing action will error\n\tToken TokenGetter\n\t\/\/ The git user to use.\n\tGitUser GitUserGetter\n\t\/\/ The censor to use. Not needed for anonymous\n\t\/\/ actions.\n\tCensor Censor\n}\n\n\/\/ Apply allows to use a ClientFactoryOpts as Opt\nfunc (cfo *ClientFactoryOpts) Apply(target *ClientFactoryOpts) {\n\tif cfo.Host != \"\" {\n\t\ttarget.Host = cfo.Host\n\t}\n\tif cfo.UseSSH != nil {\n\t\ttarget.UseSSH = cfo.UseSSH\n\t}\n\tif cfo.CacheDirBase != nil {\n\t\ttarget.CacheDirBase = cfo.CacheDirBase\n\t}\n\tif cfo.Token != nil {\n\t\ttarget.Token = cfo.Token\n\t}\n\tif cfo.GitUser != nil {\n\t\ttarget.Token = cfo.Token\n\t}\n\tif cfo.Censor != nil {\n\t\ttarget.Censor = cfo.Censor\n\t}\n}\n\n\/\/ ClientFactoryOpts allows to manipulate the options for a ClientFactory\ntype ClientFactoryOpt func(*ClientFactoryOpts)\n\nfunc defaultClientFactoryOpts(cfo *ClientFactoryOpts) {\n\tif cfo.Host == \"\" {\n\t\tcfo.Host = \"github.com\"\n\t}\n\tif cfo.CacheDirBase == nil {\n\t\tswitch runtime.GOOS {\n\t\tcase \"linux\":\n\t\t\tcfo.CacheDirBase = utilpointer.StringPtr(\"\/var\/tmp\")\n\t\tdefault:\n\t\t\tcfo.CacheDirBase = utilpointer.StringPtr(\"\")\n\t\t}\n\t}\n\tif cfo.Censor == nil {\n\t\tcfo.Censor = func(in []byte) []byte { return in }\n\t}\n}\n\n\/\/ NewClientFactory allows for the creation of repository clients. It uses github.com\n\/\/ without authentication by default.\nfunc NewClientFactory(opts ...ClientFactoryOpt) (ClientFactory, error) {\n\to := ClientFactoryOpts{}\n\tdefaultClientFactoryOpts(&o)\n\tfor _, opt := range opts {\n\t\topt(&o)\n\t}\n\n\tcacheDir, err := ioutil.TempDir(*o.CacheDirBase, \"gitcache\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar remotes RemoteResolverFactory\n\tif o.UseSSH != nil && *o.UseSSH {\n\t\tremotes = &sshRemoteResolverFactory{\n\t\t\thost:     o.Host,\n\t\t\tusername: o.Username,\n\t\t}\n\t} else {\n\t\tremotes = &httpResolverFactory{\n\t\t\thost:     o.Host,\n\t\t\tusername: o.Username,\n\t\t\ttoken:    o.Token,\n\t\t}\n\t}\n\treturn &clientFactory{\n\t\tcacheDir:     cacheDir,\n\t\tcacheDirBase: *o.CacheDirBase,\n\t\tremotes:      remotes,\n\t\tgitUser:      o.GitUser,\n\t\tcensor:       o.Censor,\n\t\tmasterLock:   &sync.Mutex{},\n\t\trepoLocks:    map[string]*sync.Mutex{},\n\t\tlogger:       logrus.WithField(\"client\", \"git\"),\n\t}, nil\n}\n\n\/\/ NewLocalClientFactory allows for the creation of repository clients\n\/\/ based on a local filepath remote for testing\nfunc NewLocalClientFactory(baseDir string, gitUser GitUserGetter, censor Censor) (ClientFactory, error) {\n\tcacheDir, err := ioutil.TempDir(\"\", \"gitcache\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &clientFactory{\n\t\tcacheDir:   cacheDir,\n\t\tremotes:    &pathResolverFactory{baseDir: baseDir},\n\t\tgitUser:    gitUser,\n\t\tcensor:     censor,\n\t\tmasterLock: &sync.Mutex{},\n\t\trepoLocks:  map[string]*sync.Mutex{},\n\t\tlogger:     logrus.WithField(\"client\", \"git\"),\n\t}, nil\n}\n\ntype clientFactory struct {\n\tremotes RemoteResolverFactory\n\tgitUser GitUserGetter\n\tcensor  Censor\n\tlogger  *logrus.Entry\n\n\t\/\/ cacheDir is the root under which cached clones of repos are created\n\tcacheDir string\n\t\/\/ cacheDirBase is the basedir under which create tempdirs\n\tcacheDirBase string\n\t\/\/ masterLock guards mutations to the repoLocks records\n\tmasterLock *sync.Mutex\n\t\/\/ repoLocks guard mutating access to subdirectories under the cacheDir\n\trepoLocks map[string]*sync.Mutex\n}\n\n\/\/ bootstrapClients returns a repository client and cloner for a dir.\nfunc (c *clientFactory) bootstrapClients(org, repo, dir string) (cacher, cloner, RepoClient, error) {\n\tif dir == \"\" {\n\t\tworkdir, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tdir = workdir\n\t}\n\tlogger := c.logger.WithFields(logrus.Fields{\"org\": org, \"repo\": repo})\n\tlogger.WithField(\"dir\", dir).Debug(\"Creating a pre-initialized client.\")\n\texecutor, err := NewCensoringExecutor(dir, c.censor, logger)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tclient := &repoClient{\n\t\tpublisher: publisher{\n\t\t\tremote:   c.remotes.PublishRemote(org, repo),\n\t\t\texecutor: executor,\n\t\t\tinfo:     c.gitUser,\n\t\t},\n\t\tinteractor: interactor{\n\t\t\tdir:      dir,\n\t\t\tremote:   c.remotes.CentralRemote(org, repo),\n\t\t\texecutor: executor,\n\t\t\tlogger:   logger,\n\t\t},\n\t}\n\treturn client, client, client, nil\n}\n\n\/\/ ClientFromDir returns a repository client for a directory that's already initialized with content.\n\/\/ If the directory isn't specified, the current working directory is used.\nfunc (c *clientFactory) ClientFromDir(org, repo, dir string) (RepoClient, error) {\n\t_, _, client, err := c.bootstrapClients(org, repo, dir)\n\treturn client, err\n}\n\n\/\/ ClientFor returns a repository client for the specified repository.\n\/\/ This function may take a long time if it is the first time cloning the repo.\n\/\/ In that case, it must do a full git mirror clone. For large repos, this can\n\/\/ take a while. Once that is done, it will do a git fetch instead of a clone,\n\/\/ which will usually take at most a few seconds.\nfunc (c *clientFactory) ClientFor(org, repo string) (RepoClient, error) {\n\tcacheDir := path.Join(c.cacheDir, org, repo)\n\tc.logger.WithFields(logrus.Fields{\"org\": org, \"repo\": repo, \"dir\": cacheDir}).Debug(\"Creating a client from the cache.\")\n\tcacheClientCacher, _, _, err := c.bootstrapClients(org, repo, cacheDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trepoDir, err := ioutil.TempDir(c.cacheDirBase, \"gitrepo\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, repoClientCloner, repoClient, err := c.bootstrapClients(org, repo, repoDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.masterLock.Lock()\n\tif _, exists := c.repoLocks[cacheDir]; !exists {\n\t\tc.repoLocks[cacheDir] = &sync.Mutex{}\n\t}\n\tc.masterLock.Unlock()\n\tc.repoLocks[cacheDir].Lock()\n\tdefer c.repoLocks[cacheDir].Unlock()\n\tif _, err := os.Stat(cacheDir); os.IsNotExist(err) {\n\t\t\/\/ we have not yet cloned this repo, we need to do a full clone\n\t\tif err := os.MkdirAll(cacheDir, os.ModePerm); err != nil && !os.IsExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := cacheClientCacher.MirrorClone(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else if err != nil {\n\t\t\/\/ something unexpected happened\n\t\treturn nil, err\n\t} else {\n\t\t\/\/ we have cloned the repo previously, but will refresh it\n\t\tif err := cacheClientCacher.RemoteUpdate(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ initialize the new derivative repo from the cache\n\tif err := repoClientCloner.Clone(cacheDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn repoClient, nil\n}\n\n\/\/ Clean removes the caches used to generate clients\nfunc (c *clientFactory) Clean() error {\n\treturn os.RemoveAll(c.cacheDir)\n}\n<commit_msg>GitV2: Be able to recover from a failled mirror clone<commit_after>\/*\nCopyright 2019 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage git\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n\t\"sync\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\tutilpointer \"k8s.io\/utils\/pointer\"\n)\n\n\/\/ ClientFactory knows how to create clientFactory for repos\ntype ClientFactory interface {\n\t\/\/ ClientFromDir creates a client that operates on a repo that has already\n\t\/\/ been cloned to the given directory.\n\tClientFromDir(org, repo, dir string) (RepoClient, error)\n\t\/\/ ClientFor creates a client that operates on a new clone of the repo.\n\tClientFor(org, repo string) (RepoClient, error)\n\n\t\/\/ Clean removes the caches used to generate clients\n\tClean() error\n}\n\n\/\/ RepoClient exposes interactions with a git repo\ntype RepoClient interface {\n\tPublisher\n\tInteractor\n}\n\ntype repoClient struct {\n\tpublisher\n\tinteractor\n}\n\ntype ClientFactoryOpts struct {\n\t\/\/ Host, defaults to \"github.com\" if unset\n\tHost string\n\t\/\/ UseSSH, defaults to false\n\tUseSSH *bool\n\t\/\/ The directory in which the cache should be\n\t\/\/ created. Defaults to the \"\/var\/tmp\" on\n\t\/\/ Linux and os.TempDir otherwise\n\tCacheDirBase *string\n\t\/\/ If unset, publishing action will error\n\tUsername LoginGetter\n\t\/\/ If unset, publishing action will error\n\tToken TokenGetter\n\t\/\/ The git user to use.\n\tGitUser GitUserGetter\n\t\/\/ The censor to use. Not needed for anonymous\n\t\/\/ actions.\n\tCensor Censor\n}\n\n\/\/ Apply allows to use a ClientFactoryOpts as Opt\nfunc (cfo *ClientFactoryOpts) Apply(target *ClientFactoryOpts) {\n\tif cfo.Host != \"\" {\n\t\ttarget.Host = cfo.Host\n\t}\n\tif cfo.UseSSH != nil {\n\t\ttarget.UseSSH = cfo.UseSSH\n\t}\n\tif cfo.CacheDirBase != nil {\n\t\ttarget.CacheDirBase = cfo.CacheDirBase\n\t}\n\tif cfo.Token != nil {\n\t\ttarget.Token = cfo.Token\n\t}\n\tif cfo.GitUser != nil {\n\t\ttarget.Token = cfo.Token\n\t}\n\tif cfo.Censor != nil {\n\t\ttarget.Censor = cfo.Censor\n\t}\n}\n\n\/\/ ClientFactoryOpts allows to manipulate the options for a ClientFactory\ntype ClientFactoryOpt func(*ClientFactoryOpts)\n\nfunc defaultClientFactoryOpts(cfo *ClientFactoryOpts) {\n\tif cfo.Host == \"\" {\n\t\tcfo.Host = \"github.com\"\n\t}\n\tif cfo.CacheDirBase == nil {\n\t\tswitch runtime.GOOS {\n\t\tcase \"linux\":\n\t\t\tcfo.CacheDirBase = utilpointer.StringPtr(\"\/var\/tmp\")\n\t\tdefault:\n\t\t\tcfo.CacheDirBase = utilpointer.StringPtr(\"\")\n\t\t}\n\t}\n\tif cfo.Censor == nil {\n\t\tcfo.Censor = func(in []byte) []byte { return in }\n\t}\n}\n\n\/\/ NewClientFactory allows for the creation of repository clients. It uses github.com\n\/\/ without authentication by default.\nfunc NewClientFactory(opts ...ClientFactoryOpt) (ClientFactory, error) {\n\to := ClientFactoryOpts{}\n\tdefaultClientFactoryOpts(&o)\n\tfor _, opt := range opts {\n\t\topt(&o)\n\t}\n\n\tcacheDir, err := ioutil.TempDir(*o.CacheDirBase, \"gitcache\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar remotes RemoteResolverFactory\n\tif o.UseSSH != nil && *o.UseSSH {\n\t\tremotes = &sshRemoteResolverFactory{\n\t\t\thost:     o.Host,\n\t\t\tusername: o.Username,\n\t\t}\n\t} else {\n\t\tremotes = &httpResolverFactory{\n\t\t\thost:     o.Host,\n\t\t\tusername: o.Username,\n\t\t\ttoken:    o.Token,\n\t\t}\n\t}\n\treturn &clientFactory{\n\t\tcacheDir:     cacheDir,\n\t\tcacheDirBase: *o.CacheDirBase,\n\t\tremotes:      remotes,\n\t\tgitUser:      o.GitUser,\n\t\tcensor:       o.Censor,\n\t\tmasterLock:   &sync.Mutex{},\n\t\trepoLocks:    map[string]*sync.Mutex{},\n\t\tlogger:       logrus.WithField(\"client\", \"git\"),\n\t}, nil\n}\n\n\/\/ NewLocalClientFactory allows for the creation of repository clients\n\/\/ based on a local filepath remote for testing\nfunc NewLocalClientFactory(baseDir string, gitUser GitUserGetter, censor Censor) (ClientFactory, error) {\n\tcacheDir, err := ioutil.TempDir(\"\", \"gitcache\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &clientFactory{\n\t\tcacheDir:   cacheDir,\n\t\tremotes:    &pathResolverFactory{baseDir: baseDir},\n\t\tgitUser:    gitUser,\n\t\tcensor:     censor,\n\t\tmasterLock: &sync.Mutex{},\n\t\trepoLocks:  map[string]*sync.Mutex{},\n\t\tlogger:     logrus.WithField(\"client\", \"git\"),\n\t}, nil\n}\n\ntype clientFactory struct {\n\tremotes RemoteResolverFactory\n\tgitUser GitUserGetter\n\tcensor  Censor\n\tlogger  *logrus.Entry\n\n\t\/\/ cacheDir is the root under which cached clones of repos are created\n\tcacheDir string\n\t\/\/ cacheDirBase is the basedir under which create tempdirs\n\tcacheDirBase string\n\t\/\/ masterLock guards mutations to the repoLocks records\n\tmasterLock *sync.Mutex\n\t\/\/ repoLocks guard mutating access to subdirectories under the cacheDir\n\trepoLocks map[string]*sync.Mutex\n}\n\n\/\/ bootstrapClients returns a repository client and cloner for a dir.\nfunc (c *clientFactory) bootstrapClients(org, repo, dir string) (cacher, cloner, RepoClient, error) {\n\tif dir == \"\" {\n\t\tworkdir, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tdir = workdir\n\t}\n\tlogger := c.logger.WithFields(logrus.Fields{\"org\": org, \"repo\": repo})\n\tlogger.WithField(\"dir\", dir).Debug(\"Creating a pre-initialized client.\")\n\texecutor, err := NewCensoringExecutor(dir, c.censor, logger)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\tclient := &repoClient{\n\t\tpublisher: publisher{\n\t\t\tremote:   c.remotes.PublishRemote(org, repo),\n\t\t\texecutor: executor,\n\t\t\tinfo:     c.gitUser,\n\t\t},\n\t\tinteractor: interactor{\n\t\t\tdir:      dir,\n\t\t\tremote:   c.remotes.CentralRemote(org, repo),\n\t\t\texecutor: executor,\n\t\t\tlogger:   logger,\n\t\t},\n\t}\n\treturn client, client, client, nil\n}\n\n\/\/ ClientFromDir returns a repository client for a directory that's already initialized with content.\n\/\/ If the directory isn't specified, the current working directory is used.\nfunc (c *clientFactory) ClientFromDir(org, repo, dir string) (RepoClient, error) {\n\t_, _, client, err := c.bootstrapClients(org, repo, dir)\n\treturn client, err\n}\n\n\/\/ ClientFor returns a repository client for the specified repository.\n\/\/ This function may take a long time if it is the first time cloning the repo.\n\/\/ In that case, it must do a full git mirror clone. For large repos, this can\n\/\/ take a while. Once that is done, it will do a git fetch instead of a clone,\n\/\/ which will usually take at most a few seconds.\nfunc (c *clientFactory) ClientFor(org, repo string) (RepoClient, error) {\n\tcacheDir := path.Join(c.cacheDir, org, repo)\n\tc.logger.WithFields(logrus.Fields{\"org\": org, \"repo\": repo, \"dir\": cacheDir}).Debug(\"Creating a client from the cache.\")\n\tcacheClientCacher, _, _, err := c.bootstrapClients(org, repo, cacheDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trepoDir, err := ioutil.TempDir(c.cacheDirBase, \"gitrepo\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, repoClientCloner, repoClient, err := c.bootstrapClients(org, repo, repoDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.masterLock.Lock()\n\tif _, exists := c.repoLocks[cacheDir]; !exists {\n\t\tc.repoLocks[cacheDir] = &sync.Mutex{}\n\t}\n\tc.masterLock.Unlock()\n\tc.repoLocks[cacheDir].Lock()\n\tdefer c.repoLocks[cacheDir].Unlock()\n\tif _, err := os.Stat(path.Join(cacheDir, \"HEAD\")); os.IsNotExist(err) {\n\t\t\/\/ we have not yet cloned this repo, we need to do a full clone\n\t\tif err := os.MkdirAll(cacheDir, os.ModePerm); err != nil && !os.IsExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := cacheClientCacher.MirrorClone(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else if err != nil {\n\t\t\/\/ something unexpected happened\n\t\treturn nil, err\n\t} else {\n\t\t\/\/ we have cloned the repo previously, but will refresh it\n\t\tif err := cacheClientCacher.RemoteUpdate(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ initialize the new derivative repo from the cache\n\tif err := repoClientCloner.Clone(cacheDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn repoClient, nil\n}\n\n\/\/ Clean removes the caches used to generate clients\nfunc (c *clientFactory) Clean() error {\n\treturn os.RemoveAll(c.cacheDir)\n}\n<|endoftext|>"}
{"text":"<commit_before>package bitsmanager\n\nimport (\n\t\"crypto\/tls\"\n\t\"github.com\/orange-cloudfoundry\/terraform-provider-cloudfoundry\/common\"\n\t\"net\/http\"\n\t\"time\"\n)\n\ntype HttpHandler struct {\n\tSkipInsecureSSL bool\n}\n\nfunc (h HttpHandler) GetZipFile(path string) (FileHandler, error) {\n\tclient := h.makeHttpClient()\n\tcleanFunc := func() error {\n\t\treturn nil\n\t}\n\tresp, err := client.Get(path)\n\tif err != nil {\n\t\treturn FileHandler{}, err\n\t}\n\treturn FileHandler{\n\t\tZipFile: resp.Body,\n\t\tSize:    resp.ContentLength,\n\t\tClean:   cleanFunc,\n\t}, nil\n}\nfunc (h HttpHandler) Detect(path string) bool {\n\treturn common.IsWebURL(path) && IsZipFile(path)\n}\nfunc (h HttpHandler) makeHttpClient() *http.Client {\n\ttr := &http.Transport{\n\t\tProxy:           http.ProxyFromEnvironment,\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: h.SkipInsecureSSL},\n\t}\n\treturn &http.Client{\n\t\tTransport: tr,\n\t\tTimeout:   2 * time.Second,\n\t}\n}\nfunc (h HttpHandler) GetSha1File(path string) (string, error) {\n\tclient := h.makeHttpClient()\n\treq, err := http.NewRequest(\"GET\", path, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\treturn GetSha1FromReader(resp.Body)\n}\n<commit_msg>fix http handler for bits manager, timeout was set to 2 seconds...<commit_after>package bitsmanager\n\nimport (\n\t\"crypto\/tls\"\n\t\"github.com\/orange-cloudfoundry\/terraform-provider-cloudfoundry\/common\"\n\t\"net\/http\"\n)\n\ntype HttpHandler struct {\n\tSkipInsecureSSL bool\n}\n\nfunc (h HttpHandler) GetZipFile(path string) (FileHandler, error) {\n\tclient := h.makeHttpClient()\n\tcleanFunc := func() error {\n\t\treturn nil\n\t}\n\tresp, err := client.Get(path)\n\tif err != nil {\n\t\treturn FileHandler{}, err\n\t}\n\treturn FileHandler{\n\t\tZipFile: resp.Body,\n\t\tSize:    resp.ContentLength,\n\t\tClean:   cleanFunc,\n\t}, nil\n}\nfunc (h HttpHandler) Detect(path string) bool {\n\treturn common.IsWebURL(path) && IsZipFile(path)\n}\nfunc (h HttpHandler) makeHttpClient() *http.Client {\n\ttr := &http.Transport{\n\t\tProxy:           http.ProxyFromEnvironment,\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: h.SkipInsecureSSL},\n\t}\n\treturn &http.Client{\n\t\tTransport: tr,\n\t\tTimeout:   0,\n\t}\n}\nfunc (h HttpHandler) GetSha1File(path string) (string, error) {\n\tclient := h.makeHttpClient()\n\treq, err := http.NewRequest(\"GET\", path, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\treturn GetSha1FromReader(resp.Body)\n}\n<|endoftext|>"}
{"text":"<commit_before>package core\n\n\/\/ transfer2go implementation of Central Catalog\n\/\/ Author: Valentin Kuznetsov <vkuznet@gmail.com>\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ CC reprents isntance of CentralCatalog\nvar CC CentralCatalog\n\n\/\/ CentralCatalog represent structure of Central Catalog\n\/\/ it is represneted by list of tables where each table contains list of records\ntype CentralCatalog struct {\n\tPath string `json:\"path\"` \/\/ path to central catalog\n}\n\nfunc findLatestSnapshot(path, table string) string {\n\tvar year, month, day, unix int\n\tfiles, _ := ioutil.ReadDir(path)\n\tfor _, f := range files {\n\t\tv, _ := strconv.Atoi(f.Name())\n\t\tif v > year {\n\t\t\tyear = v\n\t\t}\n\t}\n\tfiles, _ = ioutil.ReadDir(fmt.Sprintf(\"%s\/%d\", path, year))\n\tfor _, f := range files {\n\t\tv, _ := strconv.Atoi(f.Name())\n\t\tif v > month {\n\t\t\tmonth = v\n\t\t}\n\t}\n\tfiles, _ = ioutil.ReadDir(fmt.Sprintf(\"%s\/%d\/%d\", path, year, month))\n\tfor _, f := range files {\n\t\tv, _ := strconv.Atoi(f.Name())\n\t\tif v > day {\n\t\t\tday = v\n\t\t}\n\t}\n\tfiles, _ = ioutil.ReadDir(fmt.Sprintf(\"%s\/%d\/%d\/%d\", path, year, month, day))\n\tfor _, f := range files {\n\t\tv, _ := strconv.Atoi(f.Name())\n\t\tif v > unix {\n\t\t\tunix = v\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%s\/%d\/%d\/%d\/%d\/%s\", path, year, month, day, unix, table)\n}\n\n\/\/ Get method gets records from Central Catalog for a given table\nfunc (c *CentralCatalog) Get(table string) ([]byte, error) {\n\tif c.Path == \"\" {\n\t\treturn []byte{}, nil\n\t}\n\n\tfname := findLatestSnapshot(c.Path, table)\n\tdata, err := ioutil.ReadFile(fname)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"File\": fname,\n\t\t\t\"Err\":  err,\n\t\t}).Error(\"CentralCatalog unable to read table\")\n\t\treturn []byte{}, err\n\t}\n\treturn data, nil\n}\n\n\/\/ Put method puts given table-records into Central Catalog\nfunc (c *CentralCatalog) Put(table string, records []string) error {\n\tif c.Path == \"\" {\n\t\treturn nil\n\t}\n\tt := time.Now()\n\tpath := fmt.Sprintf(\"%s\/%d\/%d\/%d\/%d\", c.Path, t.Year(), t.Month(), t.Day(), t.Unix())\n\terr := os.MkdirAll(path, os.ModePerm)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"Dir\": path,\n\t\t\t\"Err\": err,\n\t\t}).Error(\"CentralCatalog unable to create directory\")\n\t\treturn err\n\t}\n\tfname := fmt.Sprintf(\"%s\/%s\", path, table)\n\tfile, err := os.Create(fname)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"File\": fname,\n\t\t\t\"Err\":  err,\n\t\t}).Error(\"CentralCatalog unable to create file\")\n\t\treturn err\n\t}\n\tfor _, v := range records {\n\t\t_, err := file.WriteString(v + \"\\n\")\n\t\tif err != nil {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"File\":   fname,\n\t\t\t\t\"Record\": v,\n\t\t\t\t\"Err\":    err,\n\t\t\t}).Error(\"CentralCatalog unable to write record\")\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Change log to logs<commit_after>package core\n\n\/\/ transfer2go implementation of Central Catalog\n\/\/ Author: Valentin Kuznetsov <vkuznet@gmail.com>\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n\n\tlogs \"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ CC reprents isntance of CentralCatalog\nvar CC CentralCatalog\n\n\/\/ CentralCatalog represent structure of Central Catalog\n\/\/ it is represneted by list of tables where each table contains list of records\ntype CentralCatalog struct {\n\tPath string `json:\"path\"` \/\/ path to central catalog\n}\n\nfunc findLatestSnapshot(path, table string) string {\n\tvar year, month, day, unix int\n\tfiles, _ := ioutil.ReadDir(path)\n\tfor _, f := range files {\n\t\tv, _ := strconv.Atoi(f.Name())\n\t\tif v > year {\n\t\t\tyear = v\n\t\t}\n\t}\n\tfiles, _ = ioutil.ReadDir(fmt.Sprintf(\"%s\/%d\", path, year))\n\tfor _, f := range files {\n\t\tv, _ := strconv.Atoi(f.Name())\n\t\tif v > month {\n\t\t\tmonth = v\n\t\t}\n\t}\n\tfiles, _ = ioutil.ReadDir(fmt.Sprintf(\"%s\/%d\/%d\", path, year, month))\n\tfor _, f := range files {\n\t\tv, _ := strconv.Atoi(f.Name())\n\t\tif v > day {\n\t\t\tday = v\n\t\t}\n\t}\n\tfiles, _ = ioutil.ReadDir(fmt.Sprintf(\"%s\/%d\/%d\/%d\", path, year, month, day))\n\tfor _, f := range files {\n\t\tv, _ := strconv.Atoi(f.Name())\n\t\tif v > unix {\n\t\t\tunix = v\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"%s\/%d\/%d\/%d\/%d\/%s\", path, year, month, day, unix, table)\n}\n\n\/\/ Get method gets records from Central Catalog for a given table\nfunc (c *CentralCatalog) Get(table string) ([]byte, error) {\n\tif c.Path == \"\" {\n\t\treturn []byte{}, nil\n\t}\n\n\tfname := findLatestSnapshot(c.Path, table)\n\tdata, err := ioutil.ReadFile(fname)\n\tif err != nil {\n\t\tlogs.WithFields(logs.Fields{\n\t\t\t\"File\": fname,\n\t\t\t\"Err\":  err,\n\t\t}).Error(\"CentralCatalog unable to read table\")\n\t\treturn []byte{}, err\n\t}\n\treturn data, nil\n}\n\n\/\/ Put method puts given table-records into Central Catalog\nfunc (c *CentralCatalog) Put(table string, records []string) error {\n\tif c.Path == \"\" {\n\t\treturn nil\n\t}\n\tt := time.Now()\n\tpath := fmt.Sprintf(\"%s\/%d\/%d\/%d\/%d\", c.Path, t.Year(), t.Month(), t.Day(), t.Unix())\n\terr := os.MkdirAll(path, os.ModePerm)\n\tif err != nil {\n\t\tlogs.WithFields(logs.Fields{\n\t\t\t\"Dir\": path,\n\t\t\t\"Err\": err,\n\t\t}).Error(\"CentralCatalog unable to create directory\")\n\t\treturn err\n\t}\n\tfname := fmt.Sprintf(\"%s\/%s\", path, table)\n\tfile, err := os.Create(fname)\n\tdefer file.Close()\n\tif err != nil {\n\t\tlogs.WithFields(logs.Fields{\n\t\t\t\"File\": fname,\n\t\t\t\"Err\":  err,\n\t\t}).Error(\"CentralCatalog unable to create file\")\n\t\treturn err\n\t}\n\tfor _, v := range records {\n\t\t_, err := file.WriteString(v + \"\\n\")\n\t\tif err != nil {\n\t\t\tlogs.WithFields(logs.Fields{\n\t\t\t\t\"File\":   fname,\n\t\t\t\t\"Record\": v,\n\t\t\t\t\"Err\":    err,\n\t\t\t}).Error(\"CentralCatalog unable to write record\")\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/bobziuchkovski\/writ\"\n\t\"github.com\/jkomoros\/boardgame\/boardgame-util\/lib\/build\/api\"\n\t\"github.com\/jkomoros\/boardgame\/boardgame-util\/lib\/build\/static\"\n\t\"github.com\/jkomoros\/boardgame\/boardgame-util\/lib\/config\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Serve struct {\n\tbaseSubCommand\n\n\tStorage string\n\n\tPort       string\n\tStaticPort string\n\tProd       bool\n\n\tOfflineDevMode bool\n}\n\nfunc (s *Serve) Run(p writ.Path, positional []string) {\n\n\tc := s.Base().GetConfig(false)\n\n\tif s.OfflineDevMode {\n\t\tc.AddOverride(config.EnableOfflineDevMode())\n\t}\n\n\tmode := c.Dev\n\n\tif s.Prod {\n\t\tmode = c.Prod\n\t}\n\n\tdir := s.Base().NewTempDir(\"temp_serve_\")\n\n\tstorage := effectiveStorageType(s.Base(), mode, s.Storage)\n\n\tpkgs, err := mode.AllGamePackages()\n\n\tif err != nil {\n\t\ts.Base().errAndQuit(\"Not all game packages were valid: \" + err.Error())\n\t}\n\n\tapiOptions := &api.Options{}\n\n\tif s.OfflineDevMode {\n\t\tapiOptions.OverrideOfflineDevMode = true\n\t}\n\n\tfmt.Println(\"Creating temporary binary\")\n\tapiPath, err := api.Build(dir, pkgs, storage, apiOptions)\n\n\tif err != nil {\n\t\ts.Base().errAndQuit(\"Couldn't create api: \" + err.Error())\n\t}\n\n\tfmt.Println(\"Creating temporary static assets folder\")\n\t\/\/TODO: should we allow you to pass CopyFiles? I don't know why you'd want\n\t\/\/to given this is a temp dir.\n\t_, err = static.Build(dir, pkgs, c.Client(s.Prod), s.Prod, false, mode.OfflineDevMode)\n\n\tif err != nil {\n\t\ts.Base().errAndQuit(\"Couldn't create static directory: \" + err.Error())\n\t}\n\n\tstaticPort := mode.DefaultStaticPort\n\n\tif s.StaticPort != \"\" {\n\t\tstaticPort = s.StaticPort\n\t}\n\n\tgo func() {\n\t\tfmt.Println(\"Starting up asset server at \" + staticPort)\n\t\tif err := static.Server(dir, staticPort); err != nil {\n\t\t\t\/\/TODO: when this happens we should quit the whole program\n\t\t\tfmt.Println(\"ERROR: couldn't start static server: \" + err.Error())\n\t\t}\n\t}()\n\n\t\/\/TODO: simple serving of staticPath here. Do we need a new parameter for\n\t\/\/default static serving port?\n\n\tport := mode.DefaultPort\n\n\tif s.Port != \"\" {\n\t\tport = s.Port\n\t}\n\n\t\/\/cmd will be run as though it's in this directory, which is where\n\t\/\/config.json is.\n\tcmd := exec.Command(apiPath)\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\tcmd.Env = append(os.Environ(), \"PORT=\"+port)\n\n\terr = cmd.Start()\n\n\tif err == nil {\n\t\ttopLine := \"************************************************************************\"\n\n\t\t\/\/Cheat and wait to print the message until later\n\t\ttime.Sleep(time.Second * 2)\n\n\t\tfmt.Println(\" \")\n\t\tfmt.Println(topLine)\n\t\tfor i := 0; i < 2; i++ {\n\t\t\tfmt.Println(\"*\")\n\t\t}\n\t\tfmt.Println(\"*     Server running. Open 'http:\/\/localhost:\" + staticPort + \"' in your browser\")\n\t\tfor i := 0; i < 2; i++ {\n\t\t\tfmt.Println(\"*\")\n\t\t}\n\t\tfmt.Println(topLine)\n\t\tfmt.Println(\" \")\n\n\t\terr = cmd.Wait()\n\t}\n\n\tif err != nil {\n\t\texitErr, ok := err.(*exec.ExitError)\n\t\tif !ok {\n\t\t\ts.Base().errAndQuit(\"Couldn't cast exiterror\")\n\t\t}\n\n\t\t\/\/Programs that are signaled and who responded to it before us (the\n\t\t\/\/parent) did (which is a race) will have Exited() false, whereas a\n\t\t\/\/program that errored and quit on its own should have true. Only the\n\t\t\/\/latter is an err; calling errAndQuit not in an error could prevent\n\t\t\/\/our own clean shutdown from happening.\n\t\tif exitErr.ProcessState.Exited() {\n\t\t\ts.Base().errAndQuit(\"Error running command: \" + err.Error())\n\t\t}\n\t}\n}\n\nfunc (s *Serve) Name() string {\n\treturn \"serve\"\n}\n\nfunc (s *Serve) Description() string {\n\treturn \"Creates and runs a local development server based on config.json\"\n}\n\nfunc (s *Serve) WritOptions() []*writ.Option {\n\treturn []*writ.Option{\n\t\t{\n\t\t\tNames:       []string{\"storage\", \"s\"},\n\t\t\tDecoder:     writ.NewOptionDecoder(&s.Storage),\n\t\t\tDescription: \"Which storage subsystem to use. One of {\" + strings.Join(api.ValidStorageTypeStrings(), \",\") + \"}. If not provided, falls back on the DefaultStorageType from config, or as a final fallback just the deafult storage type.\",\n\t\t},\n\t\t{\n\t\t\tNames:       []string{\"port\", \"p\"},\n\t\t\tDecoder:     writ.NewOptionDecoder(&s.Port),\n\t\t\tDescription: \"Port to use for the api server, overriding value in config.json's DefaultPort\",\n\t\t},\n\t\t{\n\t\t\tNames:       []string{\"static-port\"},\n\t\t\tDecoder:     writ.NewOptionDecoder(&s.StaticPort),\n\t\t\tDescription: \"Port to use for the static file server, overridig value in config.json's DefaultStaticPort\",\n\t\t},\n\t\t{\n\t\t\tNames:       []string{\"prod\"},\n\t\t\tDescription: \"If provided, will created bundled build directory for static resources.\",\n\t\t\tDecoder:     writ.NewFlagDecoder(&s.Prod),\n\t\t\tFlag:        true,\n\t\t},\n\t\t{\n\t\t\tNames:       []string{\"offline-dev-mode\"},\n\t\t\tDescription: \"If provided, will override OfflineDevMode to true, no matter what is in config. The effect of this is that the webapp won't make any calls to anything but localhost, allowing development on for example a plane. This is generally the best way to enable offline dev mode.\",\n\t\t\tDecoder:     writ.NewFlagDecoder(&s.OfflineDevMode),\n\t\t\tFlag:        true,\n\t\t},\n\t}\n}\n<commit_msg>Refactor cmd_serve so that we can use it for golden. Part of #648. Part of #667.<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/bobziuchkovski\/writ\"\n\t\"github.com\/jkomoros\/boardgame\/boardgame-util\/lib\/build\/api\"\n\t\"github.com\/jkomoros\/boardgame\/boardgame-util\/lib\/build\/static\"\n\t\"github.com\/jkomoros\/boardgame\/boardgame-util\/lib\/config\"\n\t\"github.com\/jkomoros\/boardgame\/boardgame-util\/lib\/gamepkg\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Serve struct {\n\tbaseSubCommand\n\n\tStorage string\n\n\tPort       string\n\tStaticPort string\n\tProd       bool\n\n\tOfflineDevMode bool\n}\n\nfunc doServe(base *BoardgameUtil, pkgs []*gamepkg.Pkg, offlineDevMode bool, prod bool, storageArg string, staticPort string, port string) {\n\n\tc := base.GetConfig(false)\n\n\tif offlineDevMode {\n\t\tc.AddOverride(config.EnableOfflineDevMode())\n\t}\n\n\tmode := c.Dev\n\n\tif prod {\n\t\tmode = c.Prod\n\t}\n\n\tstorage := effectiveStorageType(base, mode, storageArg)\n\n\tdir := base.NewTempDir(\"temp_serve_\")\n\n\tif pkgs == nil {\n\t\tvar err error\n\t\tpkgs, err = mode.AllGamePackages()\n\n\t\tif err != nil {\n\t\t\tbase.errAndQuit(\"Not all game packages were valid: \" + err.Error())\n\t\t}\n\t}\n\n\tapiOptions := &api.Options{}\n\n\tif offlineDevMode {\n\t\tapiOptions.OverrideOfflineDevMode = true\n\t}\n\n\tfmt.Println(\"Creating temporary binary\")\n\tapiPath, err := api.Build(dir, pkgs, storage, apiOptions)\n\n\tif err != nil {\n\t\tbase.errAndQuit(\"Couldn't create api: \" + err.Error())\n\t}\n\n\tfmt.Println(\"Creating temporary static assets folder\")\n\t\/\/TODO: should we allow you to pass CopyFiles? I don't know why you'd want\n\t\/\/to given this is a temp dir.\n\t_, err = static.Build(dir, pkgs, c.Client(prod), prod, false, mode.OfflineDevMode)\n\n\tif err != nil {\n\t\tbase.errAndQuit(\"Couldn't create static directory: \" + err.Error())\n\t}\n\n\tif staticPort == \"\" {\n\t\tstaticPort = mode.DefaultStaticPort\n\t}\n\n\tgo func() {\n\t\tfmt.Println(\"Starting up asset server at \" + staticPort)\n\t\tif err := static.Server(dir, staticPort); err != nil {\n\t\t\t\/\/TODO: when this happens we should quit the whole program\n\t\t\tfmt.Println(\"ERROR: couldn't start static server: \" + err.Error())\n\t\t}\n\t}()\n\n\t\/\/TODO: simple serving of staticPath here. Do we need a new parameter for\n\t\/\/default static serving port?\n\n\tif port == \"\" {\n\t\tport = mode.DefaultPort\n\t}\n\n\t\/\/cmd will be run as though it's in this directory, which is where\n\t\/\/config.json is.\n\tcmd := exec.Command(apiPath)\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\tcmd.Env = append(os.Environ(), \"PORT=\"+port)\n\n\terr = cmd.Start()\n\n\tif err == nil {\n\t\ttopLine := \"************************************************************************\"\n\n\t\t\/\/Cheat and wait to print the message until later\n\t\ttime.Sleep(time.Second * 2)\n\n\t\tfmt.Println(\" \")\n\t\tfmt.Println(topLine)\n\t\tfor i := 0; i < 2; i++ {\n\t\t\tfmt.Println(\"*\")\n\t\t}\n\t\tfmt.Println(\"*     Server running. Open 'http:\/\/localhost:\" + staticPort + \"' in your browser\")\n\t\tfor i := 0; i < 2; i++ {\n\t\t\tfmt.Println(\"*\")\n\t\t}\n\t\tfmt.Println(topLine)\n\t\tfmt.Println(\" \")\n\n\t\terr = cmd.Wait()\n\t}\n\n\tif err != nil {\n\t\texitErr, ok := err.(*exec.ExitError)\n\t\tif !ok {\n\t\t\tbase.errAndQuit(\"Couldn't cast exiterror\")\n\t\t}\n\n\t\t\/\/Programs that are signaled and who responded to it before us (the\n\t\t\/\/parent) did (which is a race) will have Exited() false, whereas a\n\t\t\/\/program that errored and quit on its own should have true. Only the\n\t\t\/\/latter is an err; calling errAndQuit not in an error could prevent\n\t\t\/\/our own clean shutdown from happening.\n\t\tif exitErr.ProcessState.Exited() {\n\t\t\tbase.errAndQuit(\"Error running command: \" + err.Error())\n\t\t}\n\t}\n}\n\nfunc (s *Serve) Run(p writ.Path, positional []string) {\n\t\/\/Pass nil options ot use mode.Games\n\tdoServe(s.Base(), nil, s.OfflineDevMode, s.Prod, s.Storage, s.StaticPort, s.Port)\n}\n\nfunc (s *Serve) Name() string {\n\treturn \"serve\"\n}\n\nfunc (s *Serve) Description() string {\n\treturn \"Creates and runs a local development server based on config.json\"\n}\n\nfunc (s *Serve) WritOptions() []*writ.Option {\n\treturn []*writ.Option{\n\t\t{\n\t\t\tNames:       []string{\"storage\", \"s\"},\n\t\t\tDecoder:     writ.NewOptionDecoder(&s.Storage),\n\t\t\tDescription: \"Which storage subsystem to use. One of {\" + strings.Join(api.ValidStorageTypeStrings(), \",\") + \"}. If not provided, falls back on the DefaultStorageType from config, or as a final fallback just the deafult storage type.\",\n\t\t},\n\t\t{\n\t\t\tNames:       []string{\"port\", \"p\"},\n\t\t\tDecoder:     writ.NewOptionDecoder(&s.Port),\n\t\t\tDescription: \"Port to use for the api server, overriding value in config.json's DefaultPort\",\n\t\t},\n\t\t{\n\t\t\tNames:       []string{\"static-port\"},\n\t\t\tDecoder:     writ.NewOptionDecoder(&s.StaticPort),\n\t\t\tDescription: \"Port to use for the static file server, overridig value in config.json's DefaultStaticPort\",\n\t\t},\n\t\t{\n\t\t\tNames:       []string{\"prod\"},\n\t\t\tDescription: \"If provided, will created bundled build directory for static resources.\",\n\t\t\tDecoder:     writ.NewFlagDecoder(&s.Prod),\n\t\t\tFlag:        true,\n\t\t},\n\t\t{\n\t\t\tNames:       []string{\"offline-dev-mode\"},\n\t\t\tDescription: \"If provided, will override OfflineDevMode to true, no matter what is in config. The effect of this is that the webapp won't make any calls to anything but localhost, allowing development on for example a plane. This is generally the best way to enable offline dev mode.\",\n\t\t\tDecoder:     writ.NewFlagDecoder(&s.OfflineDevMode),\n\t\t\tFlag:        true,\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage runtimeobjects\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\tappsv1 \"k8s.io\/api\/apps\/v1\"\n\tbatch \"k8s.io\/api\/batch\/v1\"\n\tcorev1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/equality\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\/unstructured\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/framework\/client\"\n)\n\n\/\/ ListRuntimeObjectsForKind returns objects of given kind that satisfy given namespace, labelSelector and fieldSelector.\n\/\/ TODO: using dynamic interface rather than clientset interface\nfunc ListRuntimeObjectsForKind(c clientset.Interface, kind, namespace, labelSelector, fieldSelector string) ([]runtime.Object, error) {\n\tvar runtimeObjectsList []runtime.Object\n\tvar listFunc func() error\n\tlistOpts := metav1.ListOptions{\n\t\tLabelSelector: labelSelector,\n\t\tFieldSelector: fieldSelector,\n\t}\n\tswitch kind {\n\tcase \"ReplicationController\":\n\t\tlistFunc = func() error {\n\t\t\tlist, err := c.CoreV1().ReplicationControllers(namespace).List(listOpts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\truntimeObjectsList = make([]runtime.Object, len(list.Items))\n\t\t\tfor i := range list.Items {\n\t\t\t\truntimeObjectsList[i] = &list.Items[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\tcase \"ReplicaSet\":\n\t\tlistFunc = func() error {\n\t\t\tlist, err := c.AppsV1().ReplicaSets(namespace).List(listOpts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\truntimeObjectsList = make([]runtime.Object, len(list.Items))\n\t\t\tfor i := range list.Items {\n\t\t\t\truntimeObjectsList[i] = &list.Items[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\tcase \"Deployment\":\n\t\tlistFunc = func() error {\n\t\t\tlist, err := c.AppsV1().Deployments(namespace).List(listOpts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\truntimeObjectsList = make([]runtime.Object, len(list.Items))\n\t\t\tfor i := range list.Items {\n\t\t\t\truntimeObjectsList[i] = &list.Items[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\tcase \"DaemonSet\":\n\t\tlistFunc = func() error {\n\t\t\tlist, err := c.AppsV1().DaemonSets(namespace).List(listOpts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\truntimeObjectsList = make([]runtime.Object, len(list.Items))\n\t\t\tfor i := range list.Items {\n\t\t\t\truntimeObjectsList[i] = &list.Items[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\tcase \"Job\":\n\t\tlistFunc = func() error {\n\t\t\tlist, err := c.BatchV1().Jobs(namespace).List(listOpts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\truntimeObjectsList = make([]runtime.Object, len(list.Items))\n\t\t\tfor i := range list.Items {\n\t\t\t\truntimeObjectsList[i] = &list.Items[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported kind when getting runtime object: %v\", kind)\n\t}\n\n\tif err := client.RetryWithExponentialBackOff(client.RetryFunction(listFunc)); err != nil {\n\t\treturn nil, err\n\t}\n\treturn runtimeObjectsList, nil\n}\n\n\/\/ GetNameFromRuntimeObject returns name of given runtime object.\nfunc GetNameFromRuntimeObject(obj runtime.Object) (string, error) {\n\tswitch typed := obj.(type) {\n\tcase *unstructured.Unstructured:\n\t\treturn typed.GetName(), nil\n\tdefault:\n\t\tmetaObjectAccessor, ok := obj.(metav1.ObjectMetaAccessor)\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"unsupported kind when getting name: %v\", obj)\n\t\t}\n\t\treturn metaObjectAccessor.GetObjectMeta().GetName(), nil\n\t}\n}\n\n\/\/ GetResourceVersionFromRuntimeObject returns resource version of given runtime object.\nfunc GetResourceVersionFromRuntimeObject(obj runtime.Object) (uint64, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"accessor error: %v\", err)\n\t}\n\tversion := accessor.GetResourceVersion()\n\tif len(version) == 0 {\n\t\treturn 0, nil\n\t}\n\treturn strconv.ParseUint(version, 10, 64)\n}\n\n\/\/ GetNamespaceFromRuntimeObject returns namespace of given runtime object.\nfunc GetNamespaceFromRuntimeObject(obj runtime.Object) (string, error) {\n\tswitch typed := obj.(type) {\n\tcase *unstructured.Unstructured:\n\t\treturn typed.GetNamespace(), nil\n\tdefault:\n\t\tmetaObjectAccessor, ok := obj.(metav1.ObjectMetaAccessor)\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"unsupported kind when getting namespace: %v\", obj)\n\t\t}\n\t\treturn metaObjectAccessor.GetObjectMeta().GetNamespace(), nil\n\t}\n}\n\n\/\/ GetSelectorFromRuntimeObject returns selector of given runtime object.\nfunc GetSelectorFromRuntimeObject(obj runtime.Object) (labels.Selector, error) {\n\tswitch typed := obj.(type) {\n\tcase *unstructured.Unstructured:\n\t\treturn getSelectorFromUnstrutured(typed)\n\tcase *corev1.ReplicationController:\n\t\treturn labels.SelectorFromSet(typed.Spec.Selector), nil\n\tcase *appsv1.ReplicaSet:\n\t\treturn metav1.LabelSelectorAsSelector(typed.Spec.Selector)\n\tcase *appsv1.Deployment:\n\t\treturn metav1.LabelSelectorAsSelector(typed.Spec.Selector)\n\tcase *appsv1.DaemonSet:\n\t\treturn metav1.LabelSelectorAsSelector(typed.Spec.Selector)\n\tcase *batch.Job:\n\t\treturn metav1.LabelSelectorAsSelector(typed.Spec.Selector)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported kind when getting selector: %v\", obj)\n\t}\n}\n\n\/\/ Note: This function assumes each controller has field Spec.Selector.\n\/\/ Moreover, Spec.Selector should be *metav1.LabelSelector, except for RelicationController.\nfunc getSelectorFromUnstrutured(obj *unstructured.Unstructured) (labels.Selector, error) {\n\tspec, err := getSpecFromUnstrutured(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch obj.GetKind() {\n\tcase \"ReplicationController\":\n\t\tselectorMap, found, err := unstructured.NestedStringMap(spec, \"selector\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"try to selector failed, %v\", err)\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"try to selector failed, field selector not found\")\n\t\t}\n\t\treturn labels.SelectorFromSet(selectorMap), nil\n\tdefault:\n\t\tselectorMap, found, err := unstructured.NestedMap(spec, \"selector\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"try to selector failed, %v\", err)\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"try to selector failed, field selector not found\")\n\t\t}\n\t\tvar selector metav1.LabelSelector\n\t\terr = runtime.DefaultUnstructuredConverter.FromUnstructured(selectorMap, &selector)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"try to selector failed, %v\", err)\n\t\t}\n\t\treturn metav1.LabelSelectorAsSelector(&selector)\n\t}\n}\n\n\/\/ GetSpecFromRuntimeObject returns spec of given runtime object.\nfunc GetSpecFromRuntimeObject(obj runtime.Object) (interface{}, error) {\n\tif obj == nil {\n\t\treturn nil, nil\n\t}\n\tswitch typed := obj.(type) {\n\tcase *unstructured.Unstructured:\n\t\treturn getSpecFromUnstrutured(typed)\n\tcase *corev1.ReplicationController:\n\t\treturn typed.Spec, nil\n\tcase *appsv1.ReplicaSet:\n\t\treturn typed.Spec, nil\n\tcase *appsv1.Deployment:\n\t\treturn typed.Spec, nil\n\tcase *appsv1.DaemonSet:\n\t\treturn typed.Spec, nil\n\tcase *batch.Job:\n\t\treturn typed.Spec, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported kind when getting spec: %v\", obj)\n\t}\n}\n\n\/\/ Note: This function assumes each controller has field Spec.\nfunc getSpecFromUnstrutured(obj *unstructured.Unstructured) (map[string]interface{}, error) {\n\tspec, ok, err := unstructured.NestedMap(obj.UnstructuredContent(), \"spec\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"try to acquire spec failed, %v\", err)\n\t}\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"try to acquire spec failed, no field spec for obj %s\", obj.GetName())\n\t}\n\treturn spec, nil\n}\n\n\/\/ GetReplicasFromRuntimeObject returns replicas number from given runtime object.\nfunc GetReplicasFromRuntimeObject(obj runtime.Object) (int32, error) {\n\tif obj == nil {\n\t\treturn 0, nil\n\t}\n\tswitch typed := obj.(type) {\n\tcase *unstructured.Unstructured:\n\t\treturn getReplicasFromUnstrutured(typed)\n\tcase *corev1.ReplicationController:\n\t\tif typed.Spec.Replicas != nil {\n\t\t\treturn *typed.Spec.Replicas, nil\n\t\t}\n\t\treturn 0, nil\n\tcase *appsv1.ReplicaSet:\n\t\tif typed.Spec.Replicas != nil {\n\t\t\treturn *typed.Spec.Replicas, nil\n\t\t}\n\t\treturn 0, nil\n\tcase *appsv1.Deployment:\n\t\tif typed.Spec.Replicas != nil {\n\t\t\treturn *typed.Spec.Replicas, nil\n\t\t}\n\t\treturn 0, nil\n\tcase *appsv1.DaemonSet:\n\t\treturn 0, nil\n\tcase *batch.Job:\n\t\tif typed.Spec.Parallelism != nil {\n\t\t\treturn *typed.Spec.Parallelism, nil\n\t\t}\n\t\treturn 0, nil\n\tdefault:\n\t\treturn -1, fmt.Errorf(\"unsupported kind when getting number of replicas: %v\", obj)\n\t}\n}\n\n\/\/ Note: This function assumes each controller has field Spec.Replicas, except Daemonset and Job.\nfunc getReplicasFromUnstrutured(obj *unstructured.Unstructured) (int32, error) {\n\tspec, err := getSpecFromUnstrutured(obj)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\treturn tryAcquireReplicasFromUnstructuredSpec(spec, obj.GetKind())\n}\n\nfunc tryAcquireReplicasFromUnstructuredSpec(spec map[string]interface{}, kind string) (int32, error) {\n\tswitch kind {\n\tcase \"DaemonSet\":\n\t\treturn 0, nil\n\tcase \"Job\":\n\t\treplicas, found, err := unstructured.NestedInt64(spec, \"parallelism\")\n\t\tif err != nil {\n\t\t\treturn -1, fmt.Errorf(\"try to acquire job parallelism failed, %v\", err)\n\t\t}\n\t\tif !found {\n\t\t\treturn 0, nil\n\t\t}\n\t\treturn int32(replicas), nil\n\tdefault:\n\t\treplicas, found, err := unstructured.NestedInt64(spec, \"replicas\")\n\t\tif err != nil {\n\t\t\treturn -1, fmt.Errorf(\"try to acquire replicas failed, %v\", err)\n\t\t}\n\t\tif !found {\n\t\t\treturn 0, nil\n\t\t}\n\t\treturn int32(replicas), nil\n\t}\n}\n\n\/\/ IsEqualRuntimeObjectsSpec returns true if given runtime objects have identical specs.\nfunc IsEqualRuntimeObjectsSpec(runtimeObj1, runtimeObj2 runtime.Object) (bool, error) {\n\truntimeObj1Spec, err := GetSpecFromRuntimeObject(runtimeObj1)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\truntimeObj2Spec, err := GetSpecFromRuntimeObject(runtimeObj2)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn equality.Semantic.DeepEqual(runtimeObj1Spec, runtimeObj2Spec), nil\n}\n\n\/\/ CreateMetaNamespaceKey returns meta key (namespace\/name) for given runtime object.\nfunc CreateMetaNamespaceKey(obj runtime.Object) (string, error) {\n\tnamespace, err := GetNamespaceFromRuntimeObject(obj)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"retrieving namespace error: %v\", err)\n\t}\n\tname, err := GetNameFromRuntimeObject(obj)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"retrieving name error: %v\", err)\n\t}\n\treturn namespace + \"\/\" + name, nil\n}\n<commit_msg>Support StatefulSets in runtimeobjects.go<commit_after>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage runtimeobjects\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\tappsv1 \"k8s.io\/api\/apps\/v1\"\n\tbatch \"k8s.io\/api\/batch\/v1\"\n\tcorev1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/equality\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\/unstructured\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/framework\/client\"\n)\n\n\/\/ ListRuntimeObjectsForKind returns objects of given kind that satisfy given namespace, labelSelector and fieldSelector.\n\/\/ TODO: using dynamic interface rather than clientset interface\nfunc ListRuntimeObjectsForKind(c clientset.Interface, kind, namespace, labelSelector, fieldSelector string) ([]runtime.Object, error) {\n\tvar runtimeObjectsList []runtime.Object\n\tvar listFunc func() error\n\tlistOpts := metav1.ListOptions{\n\t\tLabelSelector: labelSelector,\n\t\tFieldSelector: fieldSelector,\n\t}\n\tswitch kind {\n\tcase \"ReplicationController\":\n\t\tlistFunc = func() error {\n\t\t\tlist, err := c.CoreV1().ReplicationControllers(namespace).List(listOpts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\truntimeObjectsList = make([]runtime.Object, len(list.Items))\n\t\t\tfor i := range list.Items {\n\t\t\t\truntimeObjectsList[i] = &list.Items[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\tcase \"ReplicaSet\":\n\t\tlistFunc = func() error {\n\t\t\tlist, err := c.AppsV1().ReplicaSets(namespace).List(listOpts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\truntimeObjectsList = make([]runtime.Object, len(list.Items))\n\t\t\tfor i := range list.Items {\n\t\t\t\truntimeObjectsList[i] = &list.Items[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\tcase \"Deployment\":\n\t\tlistFunc = func() error {\n\t\t\tlist, err := c.AppsV1().Deployments(namespace).List(listOpts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\truntimeObjectsList = make([]runtime.Object, len(list.Items))\n\t\t\tfor i := range list.Items {\n\t\t\t\truntimeObjectsList[i] = &list.Items[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\tcase \"StatefulSet\":\n\t\tlistFunc = func() error {\n\t\t\tlist, err := c.AppsV1().StatefulSets(namespace).List(listOpts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\truntimeObjectsList = make([]runtime.Object, len(list.Items))\n\t\t\tfor i := range list.Items {\n\t\t\t\truntimeObjectsList[i] = &list.Items[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\tcase \"DaemonSet\":\n\t\tlistFunc = func() error {\n\t\t\tlist, err := c.AppsV1().DaemonSets(namespace).List(listOpts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\truntimeObjectsList = make([]runtime.Object, len(list.Items))\n\t\t\tfor i := range list.Items {\n\t\t\t\truntimeObjectsList[i] = &list.Items[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\tcase \"Job\":\n\t\tlistFunc = func() error {\n\t\t\tlist, err := c.BatchV1().Jobs(namespace).List(listOpts)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\truntimeObjectsList = make([]runtime.Object, len(list.Items))\n\t\t\tfor i := range list.Items {\n\t\t\t\truntimeObjectsList[i] = &list.Items[i]\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported kind when getting runtime object: %v\", kind)\n\t}\n\n\tif err := client.RetryWithExponentialBackOff(client.RetryFunction(listFunc)); err != nil {\n\t\treturn nil, err\n\t}\n\treturn runtimeObjectsList, nil\n}\n\n\/\/ GetNameFromRuntimeObject returns name of given runtime object.\nfunc GetNameFromRuntimeObject(obj runtime.Object) (string, error) {\n\tswitch typed := obj.(type) {\n\tcase *unstructured.Unstructured:\n\t\treturn typed.GetName(), nil\n\tdefault:\n\t\tmetaObjectAccessor, ok := obj.(metav1.ObjectMetaAccessor)\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"unsupported kind when getting name: %v\", obj)\n\t\t}\n\t\treturn metaObjectAccessor.GetObjectMeta().GetName(), nil\n\t}\n}\n\n\/\/ GetResourceVersionFromRuntimeObject returns resource version of given runtime object.\nfunc GetResourceVersionFromRuntimeObject(obj runtime.Object) (uint64, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"accessor error: %v\", err)\n\t}\n\tversion := accessor.GetResourceVersion()\n\tif len(version) == 0 {\n\t\treturn 0, nil\n\t}\n\treturn strconv.ParseUint(version, 10, 64)\n}\n\n\/\/ GetNamespaceFromRuntimeObject returns namespace of given runtime object.\nfunc GetNamespaceFromRuntimeObject(obj runtime.Object) (string, error) {\n\tswitch typed := obj.(type) {\n\tcase *unstructured.Unstructured:\n\t\treturn typed.GetNamespace(), nil\n\tdefault:\n\t\tmetaObjectAccessor, ok := obj.(metav1.ObjectMetaAccessor)\n\t\tif !ok {\n\t\t\treturn \"\", fmt.Errorf(\"unsupported kind when getting namespace: %v\", obj)\n\t\t}\n\t\treturn metaObjectAccessor.GetObjectMeta().GetNamespace(), nil\n\t}\n}\n\n\/\/ GetSelectorFromRuntimeObject returns selector of given runtime object.\nfunc GetSelectorFromRuntimeObject(obj runtime.Object) (labels.Selector, error) {\n\tswitch typed := obj.(type) {\n\tcase *unstructured.Unstructured:\n\t\treturn getSelectorFromUnstrutured(typed)\n\tcase *corev1.ReplicationController:\n\t\treturn labels.SelectorFromSet(typed.Spec.Selector), nil\n\tcase *appsv1.ReplicaSet:\n\t\treturn metav1.LabelSelectorAsSelector(typed.Spec.Selector)\n\tcase *appsv1.Deployment:\n\t\treturn metav1.LabelSelectorAsSelector(typed.Spec.Selector)\n\tcase *appsv1.StatefulSet:\n\t\treturn metav1.LabelSelectorAsSelector(typed.Spec.Selector)\n\tcase *appsv1.DaemonSet:\n\t\treturn metav1.LabelSelectorAsSelector(typed.Spec.Selector)\n\tcase *batch.Job:\n\t\treturn metav1.LabelSelectorAsSelector(typed.Spec.Selector)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported kind when getting selector: %v\", obj)\n\t}\n}\n\n\/\/ Note: This function assumes each controller has field Spec.Selector.\n\/\/ Moreover, Spec.Selector should be *metav1.LabelSelector, except for RelicationController.\nfunc getSelectorFromUnstrutured(obj *unstructured.Unstructured) (labels.Selector, error) {\n\tspec, err := getSpecFromUnstrutured(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tswitch obj.GetKind() {\n\tcase \"ReplicationController\":\n\t\tselectorMap, found, err := unstructured.NestedStringMap(spec, \"selector\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"try to selector failed, %v\", err)\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"try to selector failed, field selector not found\")\n\t\t}\n\t\treturn labels.SelectorFromSet(selectorMap), nil\n\tdefault:\n\t\tselectorMap, found, err := unstructured.NestedMap(spec, \"selector\")\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"try to selector failed, %v\", err)\n\t\t}\n\t\tif !found {\n\t\t\treturn nil, fmt.Errorf(\"try to selector failed, field selector not found\")\n\t\t}\n\t\tvar selector metav1.LabelSelector\n\t\terr = runtime.DefaultUnstructuredConverter.FromUnstructured(selectorMap, &selector)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"try to selector failed, %v\", err)\n\t\t}\n\t\treturn metav1.LabelSelectorAsSelector(&selector)\n\t}\n}\n\n\/\/ GetSpecFromRuntimeObject returns spec of given runtime object.\nfunc GetSpecFromRuntimeObject(obj runtime.Object) (interface{}, error) {\n\tif obj == nil {\n\t\treturn nil, nil\n\t}\n\tswitch typed := obj.(type) {\n\tcase *unstructured.Unstructured:\n\t\treturn getSpecFromUnstrutured(typed)\n\tcase *corev1.ReplicationController:\n\t\treturn typed.Spec, nil\n\tcase *appsv1.ReplicaSet:\n\t\treturn typed.Spec, nil\n\tcase *appsv1.Deployment:\n\t\treturn typed.Spec, nil\n\tcase *appsv1.StatefulSet:\n\t\treturn typed.Spec, nil\n\tcase *appsv1.DaemonSet:\n\t\treturn typed.Spec, nil\n\tcase *batch.Job:\n\t\treturn typed.Spec, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported kind when getting spec: %v\", obj)\n\t}\n}\n\n\/\/ Note: This function assumes each controller has field Spec.\nfunc getSpecFromUnstrutured(obj *unstructured.Unstructured) (map[string]interface{}, error) {\n\tspec, ok, err := unstructured.NestedMap(obj.UnstructuredContent(), \"spec\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"try to acquire spec failed, %v\", err)\n\t}\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"try to acquire spec failed, no field spec for obj %s\", obj.GetName())\n\t}\n\treturn spec, nil\n}\n\n\/\/ GetReplicasFromRuntimeObject returns replicas number from given runtime object.\nfunc GetReplicasFromRuntimeObject(obj runtime.Object) (int32, error) {\n\tif obj == nil {\n\t\treturn 0, nil\n\t}\n\tswitch typed := obj.(type) {\n\tcase *unstructured.Unstructured:\n\t\treturn getReplicasFromUnstrutured(typed)\n\tcase *corev1.ReplicationController:\n\t\tif typed.Spec.Replicas != nil {\n\t\t\treturn *typed.Spec.Replicas, nil\n\t\t}\n\t\treturn 0, nil\n\tcase *appsv1.ReplicaSet:\n\t\tif typed.Spec.Replicas != nil {\n\t\t\treturn *typed.Spec.Replicas, nil\n\t\t}\n\t\treturn 0, nil\n\tcase *appsv1.Deployment:\n\t\tif typed.Spec.Replicas != nil {\n\t\t\treturn *typed.Spec.Replicas, nil\n\t\t}\n\t\treturn 0, nil\n\tcase *appsv1.StatefulSet:\n\t\tif typed.Spec.Replicas != nil {\n\t\t\treturn *typed.Spec.Replicas, nil\n\t\t}\n\t\treturn 0, nil\n\tcase *appsv1.DaemonSet:\n\t\treturn 0, nil\n\tcase *batch.Job:\n\t\tif typed.Spec.Parallelism != nil {\n\t\t\treturn *typed.Spec.Parallelism, nil\n\t\t}\n\t\treturn 0, nil\n\tdefault:\n\t\treturn -1, fmt.Errorf(\"unsupported kind when getting number of replicas: %v\", obj)\n\t}\n}\n\n\/\/ Note: This function assumes each controller has field Spec.Replicas, except Daemonset and Job.\nfunc getReplicasFromUnstrutured(obj *unstructured.Unstructured) (int32, error) {\n\tspec, err := getSpecFromUnstrutured(obj)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\treturn tryAcquireReplicasFromUnstructuredSpec(spec, obj.GetKind())\n}\n\nfunc tryAcquireReplicasFromUnstructuredSpec(spec map[string]interface{}, kind string) (int32, error) {\n\tswitch kind {\n\tcase \"DaemonSet\":\n\t\treturn 0, nil\n\tcase \"Job\":\n\t\treplicas, found, err := unstructured.NestedInt64(spec, \"parallelism\")\n\t\tif err != nil {\n\t\t\treturn -1, fmt.Errorf(\"try to acquire job parallelism failed, %v\", err)\n\t\t}\n\t\tif !found {\n\t\t\treturn 0, nil\n\t\t}\n\t\treturn int32(replicas), nil\n\tdefault:\n\t\treplicas, found, err := unstructured.NestedInt64(spec, \"replicas\")\n\t\tif err != nil {\n\t\t\treturn -1, fmt.Errorf(\"try to acquire replicas failed, %v\", err)\n\t\t}\n\t\tif !found {\n\t\t\treturn 0, nil\n\t\t}\n\t\treturn int32(replicas), nil\n\t}\n}\n\n\/\/ IsEqualRuntimeObjectsSpec returns true if given runtime objects have identical specs.\nfunc IsEqualRuntimeObjectsSpec(runtimeObj1, runtimeObj2 runtime.Object) (bool, error) {\n\truntimeObj1Spec, err := GetSpecFromRuntimeObject(runtimeObj1)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\truntimeObj2Spec, err := GetSpecFromRuntimeObject(runtimeObj2)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn equality.Semantic.DeepEqual(runtimeObj1Spec, runtimeObj2Spec), nil\n}\n\n\/\/ CreateMetaNamespaceKey returns meta key (namespace\/name) for given runtime object.\nfunc CreateMetaNamespaceKey(obj runtime.Object) (string, error) {\n\tnamespace, err := GetNamespaceFromRuntimeObject(obj)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"retrieving namespace error: %v\", err)\n\t}\n\tname, err := GetNameFromRuntimeObject(obj)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"retrieving name error: %v\", err)\n\t}\n\treturn namespace + \"\/\" + name, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/exec\"\n\n\t\"github.com\/flynn\/flynn\/Godeps\/_workspace\/src\/github.com\/flynn\/go-docopt\"\n\t\"github.com\/flynn\/flynn\/pkg\/cliutil\"\n)\n\nvar defaultRegistry = \"registry.hub.docker.com\"\n\nfunc run(cmd *exec.Cmd) {\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc upload(args *docopt.Args) {\n\ttag := args.String[\"<tag>\"]\n\tif tag == \"\" {\n\t\ttag = \"latest\"\n\t}\n\n\tvar manifest map[string]string\n\tif err := cliutil.DecodeJSONArg(args.String[\"<manifest>\"], &manifest); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor image, id := range manifest {\n\t\tu, err := url.Parse(image)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tvar tagged string\n\t\tif u.Host == defaultRegistry {\n\t\t\ttagged = u.Path[1:] + \":\" + tag\n\t\t} else {\n\t\t\ttagged = u.Host + u.Path + \":\" + tag\n\t\t}\n\n\t\trun(exec.Command(\"docker\", \"tag\", id, tagged))\n\t\tfmt.Println(\"Tagged\", tagged)\n\n\t\tfmt.Printf(\"Uploading %s...\\n\", tagged)\n\t\trun(exec.Command(\"docker\", \"push\", tagged))\n\t}\n}\n<commit_msg>util\/release: Adding --force to docker tag command<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/exec\"\n\n\t\"github.com\/flynn\/flynn\/Godeps\/_workspace\/src\/github.com\/flynn\/go-docopt\"\n\t\"github.com\/flynn\/flynn\/pkg\/cliutil\"\n)\n\nvar defaultRegistry = \"registry.hub.docker.com\"\n\nfunc run(cmd *exec.Cmd) {\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc upload(args *docopt.Args) {\n\ttag := args.String[\"<tag>\"]\n\tif tag == \"\" {\n\t\ttag = \"latest\"\n\t}\n\n\tvar manifest map[string]string\n\tif err := cliutil.DecodeJSONArg(args.String[\"<manifest>\"], &manifest); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor image, id := range manifest {\n\t\tu, err := url.Parse(image)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tvar tagged string\n\t\tif u.Host == defaultRegistry {\n\t\t\ttagged = u.Path[1:] + \":\" + tag\n\t\t} else {\n\t\t\ttagged = u.Host + u.Path + \":\" + tag\n\t\t}\n\n\t\trun(exec.Command(\"docker\", \"tag\", \"--force\", id, tagged))\n\t\tfmt.Println(\"Tagged\", tagged)\n\n\t\tfmt.Printf(\"Uploading %s...\\n\", tagged)\n\t\trun(exec.Command(\"docker\", \"push\", tagged))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package device\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode\/utf8\"\n\n\t\"github.com\/gorilla\/websocket\"\n\t\"github.com\/jochenvg\/go-udev\"\n\t\"github.com\/tarm\/serial\"\n)\n\nvar modemCommands = struct {\n\tIMEI, IMSI string\n}{\n\t\"AT+GSN\", \"AT+CIMI\",\n}\nvar upgrader = websocket.Upgrader{}\n\ntype Message struct {\n\tType string                 `json:\"type\"`\n\tData map[string]interface{} `json:\"data\"`\n}\n\n\/\/ Manager manages devices that are plugged into the system. It supports auto\n\/\/ detection of devices.\n\/\/\n\/\/ Serial ports are opened each for a device, and a clean API for communicating\n\/\/ is provided via Read, Write and Flush methods.\n\/\/\n\/\/ The devices are monitored via udev, and any changes that requires reloading\n\/\/ of the  ports are handled by reloading the ports to the devices.\n\/\/\n\/\/ This is safe to use concurrently in multiple goroutines\ntype Manager struct {\n\tdevices map[string]serial.Config\n\tmodems  map[string]*Modem\n\tmu      sync.RWMutex\n\tmonitor *udev.Monitor\n\tdone    chan struct{}\n\tstop    chan struct{}\n\tevents  chan *Message\n}\n\n\/\/ New returns a new Manager instance\nfunc New() *Manager {\n\treturn &Manager{\n\t\tdevices: make(map[string]serial.Config),\n\t\tmodems:  make(map[string]*Modem),\n\t\tdone:    make(chan struct{}),\n\t\tstop:    make(chan struct{}),\n\t\tevents:  make(chan *Message),\n\t}\n}\n\n\/\/ Init initializes the manager. This involves creating a new goroutine to watch\n\/\/ over the changes detected by udev for any device interaction with the system.\n\/\/\n\/\/ The only interesting device actions are add and reomove for adding and\n\/\/ removing devices respctively.\nfunc (m *Manager) Init() {\n\tu := udev.Udev{}\n\tmonitor := u.NewMonitorFromNetlink(\"udev\")\n\tmonitor.FilterAddMatchTag(\"systemd\")\n\tdevCh, err := monitor.DeviceChan(m.done)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tm.monitor = monitor\n\tgo func() {\n\tstop:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase d := <-devCh:\n\t\t\t\tdpath := filepath.Join(\"\/dev\", filepath.Base(d.Devpath()))\n\t\t\t\tswitch d.Action() {\n\t\t\t\tcase \"add\":\n\t\t\t\t\tfmt.Println(\" add \", dpath)\n\t\t\t\t\tm.AddDevice(d)\n\t\t\t\t\tfmt.Println(\" done adding \", dpath)\n\t\t\t\tcase \"remove\":\n\t\t\t\t\tfmt.Println(\" removed device \" + dpath)\n\t\t\t\t\tm.RemoveDevice(dpath)\n\t\t\t\t}\n\t\t\tcase quit := <-m.stop:\n\t\t\t\tm.done <- quit\n\t\t\t\tbreak stop\n\t\t\t}\n\t\t}\n\t}()\n\n}\n\n\/\/ AddDevice adds device name to the manager\n\/\/\n\/\/ WARNING: The way modems are picked is a hack. It asserts that the modem with\n\/\/ the lowest tty number is the control modem( Which I'm not so sure is always\n\/\/ correct).\n\/\/\n\/\/ TODO: comeup with a proper way to identify modems\nfunc (m *Manager) AddDevice(d *udev.Device) error {\n\terr := m.addDevice(d)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.Symlink()\n}\nfunc (m *Manager) addDevice(d *udev.Device) error {\n\tname := filepath.Join(\"\/dev\", filepath.Base(d.Devpath()))\n\tcfg := serial.Config{Name: name, Baud: 9600, ReadTimeout: 10 * time.Second}\n\tconn := &Conn{device: cfg}\n\tif strings.Contains(name, \"ttyUSB\") {\n\t\tfmt.Println(\"checking modem\")\n\t\tmodem, err := newModem(conn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println(\"found \", *modem)\n\t\tif mm, ok := m.getModem(modem.IMEI); ok {\n\t\t\tn1, err := getttyNum(mm.Path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tn2, err := getttyNum(modem.Path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif n1 > n2 {\n\t\t\t\tm.setModem(modem)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tm.setModem(modem)\n\t}\n\treturn nil\n}\n\nfunc (m *Manager) Symlink() error {\n\tfmt.Println(\"SYMLINKING\")\n\tfor _, v := range m.modems {\n\t\terr := v.Symlink()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\" ERROR %v\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *Manager) setModem(mod *Modem) {\n\tfmt.Println(\"SETTING UP \" + mod.IMEI)\n\tm.mu.Lock()\n\tm.modems[mod.IMEI] = mod\n\tm.mu.Unlock()\n}\n\nfunc (m *Manager) getModem(imei string) (*Modem, bool) {\n\tm.mu.RLock()\n\tmod, ok := m.modems[imei]\n\tm.mu.RUnlock()\n\treturn mod, ok\n}\n\nfunc getttyNum(tty string) (int, error) {\n\tb := filepath.Base(tty)\n\tb = strings.TrimPrefix(b, \"ttyUSB\")\n\treturn strconv.Atoi(b)\n}\n\n\/\/ List serves the list of current devices. The list wont cover all devices ,\n\/\/ only the significant ones( modems for now)\nfunc (m *Manager) List(w http.ResponseWriter, r *http.Request) {\n\tm.mu.RLock()\n\tjson.NewEncoder(w).Encode(m.modems)\n\tm.mu.RUnlock()\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n}\n\n\/\/ RunComand runs commands to the exposed devices over serial ports\nfunc (m *Manager) RunCommand(w http.ResponseWriter, r *http.Request) {\n}\n\n\/\/ RemoveDevice removes device name from the manager\nfunc (m *Manager) RemoveDevice(name string) error {\n\treturn nil\n}\n\ntype Modem struct {\n\tIMEI         string `json:\"imei\"`\n\tIMSI         string `json:\"imsi\"`\n\tManufacturer string `json:\"manufacturer\"`\n\tPath         string `json:\"tty\"`\n\tconn         *Conn\n}\n\n\/\/ Symlink adds symlink to the  modem. The symlink links the tty to the IMEI\n\/\/ number of the modem.\nfunc (m *Modem) Symlink() error {\n\tnewLink := (fmt.Sprintf(\"\/dev\/%s\", m.IMEI))\n\terr := syscall.Unlink(newLink)\n\tif err != nil {\n\t\tfmt.Printf(\" ERROR %v \\n\", err)\n\t}\n\treturn os.Symlink(m.Path, newLink)\n}\n\nfunc newModem(c *Conn) (*Modem, error) {\n\tm := &Modem{}\n\tich := time.After(10 * time.Second)\nSTOP:\n\tfor {\n\t\tselect {\n\t\tcase <-ich:\n\t\t\tbreak STOP\n\t\tdefault:\n\t\t\timei, err := c.Run(modemCommands.IMEI)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ti, err := cleanResult(imei)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tim := string(i)\n\t\t\tif !isNumber(im) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tm.IMEI = im\n\t\t\tbreak STOP\n\t\t}\n\t}\n\tif m.IMEI == \"\" {\n\t\treturn nil, errors.New(\"no imei\")\n\t}\n\t\/\/ we make sure we obtain the sim card information.\n\tvar wg sync.WaitGroup\n\tdone := time.After(20 * time.Second)\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\tEND:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-done:\n\t\t\t\tfmt.Println(\"Timed out\")\n\t\t\t\tbreak END\n\t\t\tdefault:\n\t\t\t\timsi, err := c.Run(\"AT+CIMI\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ts, err := cleanResult(imsi)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tss := string(s)\n\t\t\t\tif !isNumber(ss) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif m.IMEI == ss {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfmt.Println(string(s))\n\t\t\t\tm.IMSI = ss\n\t\t\t\tbreak END\n\t\t\t}\n\t\t}\n\t}()\n\twg.Wait()\n\tif m.IMSI == \"\" {\n\t\treturn nil, errors.New(\" can't find IMSI\")\n\t}\n\tm.conn = c\n\tm.Path = c.device.Name\n\treturn m, nil\n}\n\nfunc isNumber(src string) bool {\n\tfor _, v := range src {\n\t\tif !unicode.IsDigit(v) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (m *Manager) reload() {\n\tfor _, v := range m.devices {\n\t\tconn := &Conn{device: v}\n\t\tmodem, err := newModem(conn)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Println(*modem)\n\t\tm.modems[modem.IMEI] = modem\n\t}\n}\n\nfunc cleanResult(src []byte) ([]byte, error) {\n\ti := bytes.Index(src, []byte(\"OK\"))\n\tif i == -1 {\n\t\treturn nil, errors.New(\"not okay\")\n\t}\n\tns := bytes.TrimSpace(src[:i])\n\tch, _ := utf8.DecodeRune(ns)\n\tif unicode.IsLetter(ch) {\n\t\tat := bytes.Index(ns, []byte(\"AT\"))\n\t\tif at != -1 {\n\t\t\ti := bytes.IndexRune(ns[at:], '\\r')\n\t\t\tif i > 0 {\n\t\t\t\treturn bytes.TrimSpace(ns[at+i:]), nil\n\t\t\t}\n\t\t}\n\t}\n\treturn ns, nil\n}\n\n\/\/Close shuts down the device manager. This makes sure the udev monitor is\n\/\/closed and all goroutines are properly exited.\nfunc (m *Manager) Close() {\n\tm.stop <- struct{}{}\n}\n\nfunc reader(ws *websocket.Conn) {\n\tdefer ws.Close()\n\tfor {\n\t\t_, _, err := ws.ReadMessage()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}\n\n\/\/ Updates is websocket http handler for sending updates about the devices\n\/\/ plugged into the system in real time.\nfunc (m *Manager) Updates(w http.ResponseWriter, r *http.Request) {\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tif _, ok := err.(websocket.HandshakeError); !ok {\n\t\t\tlog.Println(err)\n\t\t}\n\t\treturn\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase ev := <-m.events:\n\t\t\t\t_ = ws.WriteJSON(ev)\n\t\t\t}\n\t\t}\n\t}()\n\treader(ws)\n}\n\n\/\/ Conn is a device serial connection\ntype Conn struct {\n\tdevice serial.Config\n\timei   string\n\tport   *serial.Port\n\tisOpen bool\n}\n\n\/\/ Open opens a serial port to the undelying device\nfunc (c *Conn) Open() error {\n\tp, err := serial.OpenPort(&c.device)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.port = p\n\tc.isOpen = true\n\treturn nil\n}\n\n\/\/ Close closes the port helt by *Conn.\nfunc (c *Conn) Close() error {\n\tif c.isOpen {\n\t\treturn c.port.Close()\n\t}\n\treturn nil\n}\n\n\/\/ Write wites b to the serieal port\nfunc (c *Conn) Write(b []byte) (int, error) {\n\treturn c.port.Write(b)\n}\n\n\/\/ Read reads from serial port\nfunc (c *Conn) Read(b []byte) (int, error) {\n\treturn c.port.Read(b)\n}\n\n\/\/ Exec sends the command over serial port and rrturns the response. If the port\n\/\/ is closed it is opened  before sending the command.\nfunc (c *Conn) Exec(cmd string) ([]byte, error) {\n\tif !c.isOpen {\n\t\terr := c.Open()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t_, err := c.Write([]byte(cmd))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := make([]byte, 128)\n\t_, err = c.Read(buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !bytes.Contains(buf, []byte(\"OK\")) {\n\t\treturn nil, errors.New(\"command \" + string(cmd) + \" xeite without OK\" + \" got \" + string(buf))\n\t}\n\t_ = c.port.Flush()\n\t_ = c.port.Close()\n\tc.isOpen = false\n\treturn buf, nil\n}\n\n\/\/ Run helper for Exec that adds \\r to the command\nfunc (c *Conn) Run(cmd string) ([]byte, error) {\n\treturn c.Exec(fmt.Sprintf(\"%s \\r\", cmd))\n}\n<commit_msg>Symlink already initialized modems<commit_after>package device\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\t\"unicode\"\n\t\"unicode\/utf8\"\n\n\t\"github.com\/gorilla\/websocket\"\n\t\"github.com\/jochenvg\/go-udev\"\n\t\"github.com\/tarm\/serial\"\n)\n\nvar modemCommands = struct {\n\tIMEI, IMSI string\n}{\n\t\"AT+GSN\", \"AT+CIMI\",\n}\nvar upgrader = websocket.Upgrader{}\n\ntype Message struct {\n\tType string                 `json:\"type\"`\n\tData map[string]interface{} `json:\"data\"`\n}\n\n\/\/ Manager manages devices that are plugged into the system. It supports auto\n\/\/ detection of devices.\n\/\/\n\/\/ Serial ports are opened each for a device, and a clean API for communicating\n\/\/ is provided via Read, Write and Flush methods.\n\/\/\n\/\/ The devices are monitored via udev, and any changes that requires reloading\n\/\/ of the  ports are handled by reloading the ports to the devices.\n\/\/\n\/\/ This is safe to use concurrently in multiple goroutines\ntype Manager struct {\n\tdevices map[string]serial.Config\n\tmodems  map[string]*Modem\n\tmu      sync.RWMutex\n\tmonitor *udev.Monitor\n\tdone    chan struct{}\n\tstop    chan struct{}\n\tevents  chan *Message\n}\n\n\/\/ New returns a new Manager instance\nfunc New() *Manager {\n\treturn &Manager{\n\t\tdevices: make(map[string]serial.Config),\n\t\tmodems:  make(map[string]*Modem),\n\t\tdone:    make(chan struct{}),\n\t\tstop:    make(chan struct{}),\n\t\tevents:  make(chan *Message),\n\t}\n}\n\n\/\/ Init initializes the manager. This involves creating a new goroutine to watch\n\/\/ over the changes detected by udev for any device interaction with the system.\n\/\/\n\/\/ The only interesting device actions are add and reomove for adding and\n\/\/ removing devices respctively.\nfunc (m *Manager) Init() {\n\tm.startup()\n\tu := udev.Udev{}\n\tmonitor := u.NewMonitorFromNetlink(\"udev\")\n\tmonitor.FilterAddMatchTag(\"systemd\")\n\tdevCh, err := monitor.DeviceChan(m.done)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tm.monitor = monitor\n\tgo func() {\n\tstop:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase d := <-devCh:\n\t\t\t\tdpath := filepath.Join(\"\/dev\", filepath.Base(d.Devpath()))\n\t\t\t\tswitch d.Action() {\n\t\t\t\tcase \"add\":\n\t\t\t\t\tfmt.Println(\" add \", dpath)\n\t\t\t\t\tm.AddDevice(d)\n\t\t\t\t\tfmt.Println(\" done adding \", dpath)\n\t\t\t\tcase \"remove\":\n\t\t\t\t\tfmt.Println(\" removed device \" + dpath)\n\t\t\t\t\tm.RemoveDevice(dpath)\n\t\t\t\t}\n\t\t\tcase quit := <-m.stop:\n\t\t\t\tm.done <- quit\n\t\t\t\tbreak stop\n\t\t\t}\n\t\t}\n\t}()\n\n}\n\nfunc (m *Manager) startup() {\n\tu := udev.Udev{}\n\te := u.NewEnumerate()\n\te.AddMatchIsInitialized()\n\te.AddMatchTag(\"systemd\")\n\tdevices, _ := e.Devices()\n\tfor i := 0; i < len(devices); i++ {\n\t\tdevice := devices[i]\n\t\tm.AddDevice(device)\n\t}\n}\n\n\/\/ AddDevice adds device name to the manager\n\/\/\n\/\/ WARNING: The way modems are picked is a hack. It asserts that the modem with\n\/\/ the lowest tty number is the control modem( Which I'm not so sure is always\n\/\/ correct).\n\/\/\n\/\/ TODO: comeup with a proper way to identify modems\nfunc (m *Manager) AddDevice(d *udev.Device) error {\n\terr := m.addDevice(d)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn m.Symlink()\n}\nfunc (m *Manager) addDevice(d *udev.Device) error {\n\tname := filepath.Join(\"\/dev\", filepath.Base(d.Devpath()))\n\tcfg := serial.Config{Name: name, Baud: 9600, ReadTimeout: 10 * time.Second}\n\tconn := &Conn{device: cfg}\n\tif strings.Contains(name, \"ttyUSB\") {\n\t\tfmt.Println(\"checking modem\")\n\t\tmodem, err := newModem(conn)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println(\"found \", *modem)\n\t\tif mm, ok := m.getModem(modem.IMEI); ok {\n\t\t\tn1, err := getttyNum(mm.Path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tn2, err := getttyNum(modem.Path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif n1 > n2 {\n\t\t\t\tm.setModem(modem)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tm.setModem(modem)\n\t}\n\treturn nil\n}\n\nfunc (m *Manager) Symlink() error {\n\tfmt.Println(\"SYMLINKING\")\n\tfor _, v := range m.modems {\n\t\terr := v.Symlink()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\" ERROR %v\\n\", err)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Println(\"SYMLINKING SUCCESS \" + v.IMEI)\n\t}\n\treturn nil\n}\n\nfunc (m *Manager) setModem(mod *Modem) {\n\tfmt.Println(\"SETTING UP \" + mod.IMEI)\n\tm.mu.Lock()\n\tm.modems[mod.IMEI] = mod\n\tm.mu.Unlock()\n}\n\nfunc (m *Manager) getModem(imei string) (*Modem, bool) {\n\tm.mu.RLock()\n\tmod, ok := m.modems[imei]\n\tm.mu.RUnlock()\n\treturn mod, ok\n}\n\nfunc getttyNum(tty string) (int, error) {\n\tb := filepath.Base(tty)\n\tb = strings.TrimPrefix(b, \"ttyUSB\")\n\treturn strconv.Atoi(b)\n}\n\n\/\/ List serves the list of current devices. The list wont cover all devices ,\n\/\/ only the significant ones( modems for now)\nfunc (m *Manager) List(w http.ResponseWriter, r *http.Request) {\n\tm.mu.RLock()\n\tjson.NewEncoder(w).Encode(m.modems)\n\tm.mu.RUnlock()\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n}\n\n\/\/ RunComand runs commands to the exposed devices over serial ports\nfunc (m *Manager) RunCommand(w http.ResponseWriter, r *http.Request) {\n}\n\n\/\/ RemoveDevice removes device name from the manager\nfunc (m *Manager) RemoveDevice(name string) error {\n\treturn nil\n}\n\ntype Modem struct {\n\tIMEI         string `json:\"imei\"`\n\tIMSI         string `json:\"imsi\"`\n\tManufacturer string `json:\"manufacturer\"`\n\tPath         string `json:\"tty\"`\n\tconn         *Conn\n}\n\n\/\/ Symlink adds symlink to the  modem. The symlink links the tty to the IMEI\n\/\/ number of the modem.\nfunc (m *Modem) Symlink() error {\n\tnewLink := (fmt.Sprintf(\"\/dev\/%s\", m.IMEI))\n\terr := syscall.Unlink(newLink)\n\tif err != nil {\n\t\tfmt.Printf(\" ERROR %v \\n\", err)\n\t}\n\treturn os.Symlink(m.Path, newLink)\n}\n\nfunc newModem(c *Conn) (*Modem, error) {\n\tm := &Modem{}\n\tich := time.After(10 * time.Second)\nSTOP:\n\tfor {\n\t\tselect {\n\t\tcase <-ich:\n\t\t\tbreak STOP\n\t\tdefault:\n\t\t\timei, err := c.Run(modemCommands.IMEI)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ti, err := cleanResult(imei)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tim := string(i)\n\t\t\tif !isNumber(im) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tm.IMEI = im\n\t\t\tbreak STOP\n\t\t}\n\t}\n\tif m.IMEI == \"\" {\n\t\treturn nil, errors.New(\"no imei\")\n\t}\n\t\/\/ we make sure we obtain the sim card information.\n\tvar wg sync.WaitGroup\n\tdone := time.After(20 * time.Second)\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\tEND:\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-done:\n\t\t\t\tfmt.Println(\"Timed out\")\n\t\t\t\tbreak END\n\t\t\tdefault:\n\t\t\t\timsi, err := c.Run(\"AT+CIMI\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ts, err := cleanResult(imsi)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tss := string(s)\n\t\t\t\tif !isNumber(ss) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif m.IMEI == ss {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfmt.Println(string(s))\n\t\t\t\tm.IMSI = ss\n\t\t\t\tbreak END\n\t\t\t}\n\t\t}\n\t}()\n\twg.Wait()\n\tif m.IMSI == \"\" {\n\t\treturn nil, errors.New(\" can't find IMSI\")\n\t}\n\tm.conn = c\n\tm.Path = c.device.Name\n\treturn m, nil\n}\n\nfunc isNumber(src string) bool {\n\tfor _, v := range src {\n\t\tif !unicode.IsDigit(v) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (m *Manager) reload() {\n\tfor _, v := range m.devices {\n\t\tconn := &Conn{device: v}\n\t\tmodem, err := newModem(conn)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Println(*modem)\n\t\tm.modems[modem.IMEI] = modem\n\t}\n}\n\nfunc cleanResult(src []byte) ([]byte, error) {\n\ti := bytes.Index(src, []byte(\"OK\"))\n\tif i == -1 {\n\t\treturn nil, errors.New(\"not okay\")\n\t}\n\tns := bytes.TrimSpace(src[:i])\n\tch, _ := utf8.DecodeRune(ns)\n\tif unicode.IsLetter(ch) {\n\t\tat := bytes.Index(ns, []byte(\"AT\"))\n\t\tif at != -1 {\n\t\t\ti := bytes.IndexRune(ns[at:], '\\r')\n\t\t\tif i > 0 {\n\t\t\t\treturn bytes.TrimSpace(ns[at+i:]), nil\n\t\t\t}\n\t\t}\n\t}\n\treturn ns, nil\n}\n\n\/\/Close shuts down the device manager. This makes sure the udev monitor is\n\/\/closed and all goroutines are properly exited.\nfunc (m *Manager) Close() {\n\tm.stop <- struct{}{}\n}\n\nfunc reader(ws *websocket.Conn) {\n\tdefer ws.Close()\n\tfor {\n\t\t_, _, err := ws.ReadMessage()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t}\n}\n\n\/\/ Updates is websocket http handler for sending updates about the devices\n\/\/ plugged into the system in real time.\nfunc (m *Manager) Updates(w http.ResponseWriter, r *http.Request) {\n\tws, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\tif _, ok := err.(websocket.HandshakeError); !ok {\n\t\t\tlog.Println(err)\n\t\t}\n\t\treturn\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase ev := <-m.events:\n\t\t\t\t_ = ws.WriteJSON(ev)\n\t\t\t}\n\t\t}\n\t}()\n\treader(ws)\n}\n\n\/\/ Conn is a device serial connection\ntype Conn struct {\n\tdevice serial.Config\n\timei   string\n\tport   *serial.Port\n\tisOpen bool\n}\n\n\/\/ Open opens a serial port to the undelying device\nfunc (c *Conn) Open() error {\n\tp, err := serial.OpenPort(&c.device)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.port = p\n\tc.isOpen = true\n\treturn nil\n}\n\n\/\/ Close closes the port helt by *Conn.\nfunc (c *Conn) Close() error {\n\tif c.isOpen {\n\t\treturn c.port.Close()\n\t}\n\treturn nil\n}\n\n\/\/ Write wites b to the serieal port\nfunc (c *Conn) Write(b []byte) (int, error) {\n\treturn c.port.Write(b)\n}\n\n\/\/ Read reads from serial port\nfunc (c *Conn) Read(b []byte) (int, error) {\n\treturn c.port.Read(b)\n}\n\n\/\/ Exec sends the command over serial port and rrturns the response. If the port\n\/\/ is closed it is opened  before sending the command.\nfunc (c *Conn) Exec(cmd string) ([]byte, error) {\n\tif !c.isOpen {\n\t\terr := c.Open()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t_, err := c.Write([]byte(cmd))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf := make([]byte, 128)\n\t_, err = c.Read(buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !bytes.Contains(buf, []byte(\"OK\")) {\n\t\treturn nil, errors.New(\"command \" + string(cmd) + \" xeite without OK\" + \" got \" + string(buf))\n\t}\n\t_ = c.port.Flush()\n\t_ = c.port.Close()\n\tc.isOpen = false\n\treturn buf, nil\n}\n\n\/\/ Run helper for Exec that adds \\r to the command\nfunc (c *Conn) Run(cmd string) ([]byte, error) {\n\treturn c.Exec(fmt.Sprintf(\"%s \\r\", cmd))\n}\n<|endoftext|>"}
{"text":"<commit_before>package device\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ deviceError exposes the basic error metadata\ntype deviceError struct {\n\tid  ID\n\tkey Key\n}\n\nfunc (e *deviceError) ID() ID {\n\treturn e.id\n}\n\nfunc (e *deviceError) Key() Key {\n\treturn e.key\n}\n\n\/\/ ClosedError indicates that an operation was attempted on\n\/\/ a closed device that is not allowed, e.g. sending a message\ntype ClosedError struct {\n\tdeviceError\n}\n\nfunc (e *ClosedError) Error() string {\n\treturn fmt.Sprintf(\"Device [%s] with key [%s] is closed\", e.id, e.key)\n}\n\nfunc NewClosedError(id ID, key Key) *ClosedError {\n\treturn &ClosedError{\n\t\tdeviceError{\n\t\t\tid:  id,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\n\/\/ BusyError indicates that a device's message queue is full\ntype BusyError struct {\n\tdeviceError\n}\n\nfunc (e *BusyError) Error() string {\n\treturn fmt.Sprintf(\"Device [%s] with key [%s] is busy\", e.id, e.key)\n}\n\nfunc NewBusyError(id ID, key Key) *BusyError {\n\treturn &BusyError{\n\t\tdeviceError{\n\t\t\tid:  id,\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\ntype MissingIDError struct {\n\tdeviceError\n}\n\nfunc (e *MissingIDError) Error() string {\n\treturn fmt.Sprintf(\"No device exists with id [%s]\", e.id)\n}\n\nfunc NewMissingIDError(id ID) *MissingIDError {\n\treturn &MissingIDError{\n\t\tdeviceError{\n\t\t\tid: id,\n\t\t},\n\t}\n}\n\ntype MissingKeyError struct {\n\tdeviceError\n}\n\nfunc (e *MissingKeyError) Error() string {\n\treturn fmt.Sprintf(\"No device exists with key [%s]\", e.key)\n}\n\nfunc NewMissingKeyError(key Key) *MissingKeyError {\n\treturn &MissingKeyError{\n\t\tdeviceError{\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n\ntype DuplicateKeyError struct {\n\tdeviceError\n}\n\nfunc (e *DuplicateKeyError) Error() string {\n\treturn fmt.Sprintf(\"Duplicate key [%s]\", e.key)\n}\n\nfunc NewDuplicateKeyError(key Key) *DuplicateKeyError {\n\treturn &DuplicateKeyError{\n\t\tdeviceError{\n\t\t\tkey: key,\n\t\t},\n\t}\n}\n<commit_msg>Normalized the errors into fewer types<commit_after>package device\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ DeviceError is the common interface implemented by all error objects\n\/\/ which carry device-related metadata\ntype DeviceError interface {\n\terror\n\tID() ID\n\tKey() Key\n}\n\n\/\/ deviceError exposes the basic error metadata\ntype deviceError struct {\n\tid   ID\n\tkey  Key\n\ttext string\n}\n\nfunc (e *deviceError) ID() ID {\n\treturn e.id\n}\n\nfunc (e *deviceError) Key() Key {\n\treturn e.key\n}\n\nfunc (e *deviceError) Error() string {\n\treturn e.text\n}\n\nfunc newDeviceError(id ID, key Key, message string) DeviceError {\n\treturn &deviceError{\n\t\tid:   id,\n\t\tkey:  key,\n\t\ttext: fmt.Sprintf(\"Device [id=%s, key=%s]: %s\", id, key, message),\n\t}\n}\n\nfunc NewClosedError(id ID, key Key) DeviceError {\n\treturn newDeviceError(id, key, \"closed\")\n}\n\nfunc NewBusyError(id ID, key Key) DeviceError {\n\treturn newDeviceError(id, key, \"busy\")\n}\n\nfunc NewMissingIDError(id ID) DeviceError {\n\treturn newDeviceError(id, invalidKey, \"ID does not exist\")\n}\n\nfunc NewMissingKeyError(key Key) DeviceError {\n\treturn newDeviceError(invalidID, key, \"Key does not exist\")\n}\n\nfunc NewDuplicateKeyError(key Key) DeviceError {\n\treturn newDeviceError(invalidID, key, \"duplicate key\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014-2015 Chadev. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport \"testing\"\n\nfunc TestGetMeetupEvents(t *testing.T) {\n\t_, err := getTalkDetails()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n<commit_msg>Fix tests on Travis CI<commit_after>\/\/ Copyright 2014-2015 Chadev. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestGetMeetupEvents(t *testing.T) {\n\tif os.Getenv(\"CHADEV_MEETUP\") == \"\" {\n\t\tt.Skip(\"no meetup API key set, skipping test\")\n\t}\n\n\t_, err := getTalkDetails()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package btelegram\n\nimport (\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/42wim\/matterbridge\/bridge\"\n\t\"github.com\/42wim\/matterbridge\/bridge\/config\"\n\t\"github.com\/42wim\/matterbridge\/bridge\/helper\"\n\t\"github.com\/go-telegram-bot-api\/telegram-bot-api\"\n)\n\ntype Btelegram struct {\n\tc *tgbotapi.BotAPI\n\t*config.BridgeConfig\n\tavatarMap map[string]string \/\/ keep cache of userid and avatar sha\n}\n\nfunc New(cfg *config.BridgeConfig) bridge.Bridger {\n\treturn &Btelegram{BridgeConfig: cfg, avatarMap: make(map[string]string)}\n}\n\nfunc (b *Btelegram) Connect() error {\n\tvar err error\n\tb.Log.Info(\"Connecting\")\n\tb.c, err = tgbotapi.NewBotAPI(b.Config.Token)\n\tif err != nil {\n\t\tb.Log.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tu := tgbotapi.NewUpdate(0)\n\tu.Timeout = 60\n\tupdates, err := b.c.GetUpdatesChan(u)\n\tif err != nil {\n\t\tb.Log.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tb.Log.Info(\"Connection succeeded\")\n\tgo b.handleRecv(updates)\n\treturn nil\n}\n\nfunc (b *Btelegram) Disconnect() error {\n\treturn nil\n}\n\nfunc (b *Btelegram) JoinChannel(channel config.ChannelInfo) error {\n\treturn nil\n}\n\nfunc (b *Btelegram) Send(msg config.Message) (string, error) {\n\tb.Log.Debugf(\"=> Receiving %#v\", msg)\n\n\t\/\/ get the chatid\n\tchatid, err := strconv.ParseInt(msg.Channel, 10, 64)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t\/\/ map the file SHA to our user (caches the avatar)\n\tif msg.Event == config.EVENT_AVATAR_DOWNLOAD {\n\t\treturn b.cacheAvatar(&msg)\n\t}\n\n\tif b.Config.MessageFormat == \"HTML\" {\n\t\tmsg.Text = makeHTML(msg.Text)\n\t}\n\n\t\/\/ Delete message\n\tif msg.Event == config.EVENT_MSG_DELETE {\n\t\tif msg.ID == \"\" {\n\t\t\treturn \"\", nil\n\t\t}\n\t\tmsgid, err := strconv.Atoi(msg.ID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t_, err = b.c.DeleteMessage(tgbotapi.DeleteMessageConfig{ChatID: chatid, MessageID: msgid})\n\t\treturn \"\", err\n\t}\n\n\t\/\/ Upload a file if it exists\n\tif msg.Extra != nil {\n\t\tfor _, rmsg := range helper.HandleExtra(&msg, b.General) {\n\t\t\tb.sendMessage(chatid, rmsg.Username+rmsg.Text)\n\t\t}\n\t\t\/\/ check if we have files to upload (from slack, telegram or mattermost)\n\t\tif len(msg.Extra[\"file\"]) > 0 {\n\t\t\tb.handleUploadFile(&msg, chatid)\n\t\t}\n\t}\n\n\t\/\/ edit the message if we have a msg ID\n\tif msg.ID != \"\" {\n\t\tmsgid, err := strconv.Atoi(msg.ID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tm := tgbotapi.NewEditMessageText(chatid, msgid, msg.Username+msg.Text)\n\t\tif b.Config.MessageFormat == \"HTML\" {\n\t\t\tb.Log.Debug(\"Using mode HTML\")\n\t\t\tm.ParseMode = tgbotapi.ModeHTML\n\t\t}\n\t\tif b.Config.MessageFormat == \"Markdown\" {\n\t\t\tb.Log.Debug(\"Using mode markdown\")\n\t\t\tm.ParseMode = tgbotapi.ModeMarkdown\n\t\t}\n\t\t_, err = b.c.Send(m)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn \"\", nil\n\t}\n\n\t\/\/ Post normal message\n\treturn b.sendMessage(chatid, msg.Username+msg.Text)\n}\n\nfunc (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {\n\tfor update := range updates {\n\t\tb.Log.Debugf(\"== Receiving event: %#v\", update.Message)\n\n\t\tif update.Message == nil && update.ChannelPost == nil {\n\t\t\tb.Log.Error(\"Getting nil messages, this shouldn't happen.\")\n\t\t\tcontinue\n\t\t}\n\n\t\tvar message *tgbotapi.Message\n\n\t\trmsg := config.Message{Account: b.Account, Extra: make(map[string][]interface{})}\n\n\t\t\/\/ handle channels\n\t\tif update.ChannelPost != nil {\n\t\t\tmessage = update.ChannelPost\n\t\t}\n\n\t\t\/\/ edited channel message\n\t\tif update.EditedChannelPost != nil && !b.Config.EditDisable {\n\t\t\tmessage = update.EditedChannelPost\n\t\t\trmsg.Text = rmsg.Text + message.Text + b.Config.EditSuffix\n\t\t}\n\n\t\t\/\/ handle groups\n\t\tif update.Message != nil {\n\t\t\tmessage = update.Message\n\t\t}\n\n\t\t\/\/ edited group message\n\t\tif update.EditedMessage != nil && !b.Config.EditDisable {\n\t\t\tmessage = update.EditedMessage\n\t\t\trmsg.Text = rmsg.Text + message.Text + b.Config.EditSuffix\n\t\t}\n\n\t\t\/\/ set the ID's from the channel or group message\n\t\trmsg.ID = strconv.Itoa(message.MessageID)\n\t\trmsg.UserID = strconv.Itoa(message.From.ID)\n\t\trmsg.Channel = strconv.FormatInt(message.Chat.ID, 10)\n\n\t\t\/\/ handle username\n\t\tif message.From != nil {\n\t\t\tif b.Config.UseFirstName {\n\t\t\t\trmsg.Username = message.From.FirstName\n\t\t\t}\n\t\t\tif rmsg.Username == \"\" {\n\t\t\t\trmsg.Username = message.From.UserName\n\t\t\t\tif rmsg.Username == \"\" {\n\t\t\t\t\trmsg.Username = message.From.FirstName\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ only download avatars if we have a place to upload them (configured mediaserver)\n\t\t\tif b.General.MediaServerUpload != \"\" {\n\t\t\t\tb.handleDownloadAvatar(message.From.ID, rmsg.Channel)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ if we really didn't find a username, set it to unknown\n\t\tif rmsg.Username == \"\" {\n\t\t\trmsg.Username = \"unknown\"\n\t\t}\n\n\t\t\/\/ handle any downloads\n\t\terr := b.handleDownload(message, &rmsg)\n\t\tif err != nil {\n\t\t\tb.Log.Errorf(\"download failed: %s\", err)\n\t\t}\n\n\t\t\/\/ handle forwarded messages\n\t\tif message.ForwardFrom != nil {\n\t\t\tusernameForward := \"\"\n\t\t\tif b.Config.UseFirstName {\n\t\t\t\tusernameForward = message.ForwardFrom.FirstName\n\t\t\t}\n\t\t\tif usernameForward == \"\" {\n\t\t\t\tusernameForward = message.ForwardFrom.UserName\n\t\t\t\tif usernameForward == \"\" {\n\t\t\t\t\tusernameForward = message.ForwardFrom.FirstName\n\t\t\t\t}\n\t\t\t}\n\t\t\tif usernameForward == \"\" {\n\t\t\t\tusernameForward = \"unknown\"\n\t\t\t}\n\t\t\trmsg.Text = \"Forwarded from \" + usernameForward + \": \" + rmsg.Text\n\t\t}\n\n\t\t\/\/ quote the previous message\n\t\tif message.ReplyToMessage != nil {\n\t\t\tusernameReply := \"\"\n\t\t\tif message.ReplyToMessage.From != nil {\n\t\t\t\tif b.Config.UseFirstName {\n\t\t\t\t\tusernameReply = message.ReplyToMessage.From.FirstName\n\t\t\t\t}\n\t\t\t\tif usernameReply == \"\" {\n\t\t\t\t\tusernameReply = message.ReplyToMessage.From.UserName\n\t\t\t\t\tif usernameReply == \"\" {\n\t\t\t\t\t\tusernameReply = message.ReplyToMessage.From.FirstName\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif usernameReply == \"\" {\n\t\t\t\tusernameReply = \"unknown\"\n\t\t\t}\n\t\t\trmsg.Text = rmsg.Text + \" (re @\" + usernameReply + \":\" + message.ReplyToMessage.Text + \")\"\n\t\t}\n\n\t\tif rmsg.Text != \"\" || len(rmsg.Extra) > 0 {\n\t\t\trmsg.Avatar = helper.GetAvatar(b.avatarMap, strconv.Itoa(message.From.ID), b.General)\n\n\t\t\tb.Log.Debugf(\"<= Sending message from %s on %s to gateway\", rmsg.Username, b.Account)\n\t\t\tb.Log.Debugf(\"<= Message is %#v\", rmsg)\n\t\t\tb.Remote <- rmsg\n\t\t}\n\t}\n}\n\nfunc (b *Btelegram) getFileDirectURL(id string) string {\n\tres, err := b.c.GetFileDirectURL(id)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn res\n}\n\n\/\/ handleDownloadAvatar downloads the avatar of userid from channel\n\/\/ sends a EVENT_AVATAR_DOWNLOAD message to the gateway if successful.\n\/\/ logs an error message if it fails\nfunc (b *Btelegram) handleDownloadAvatar(userid int, channel string) {\n\trmsg := config.Message{Username: \"system\", Text: \"avatar\", Channel: channel, Account: b.Account, UserID: strconv.Itoa(userid), Event: config.EVENT_AVATAR_DOWNLOAD, Extra: make(map[string][]interface{})}\n\tif _, ok := b.avatarMap[strconv.Itoa(userid)]; !ok {\n\t\tphotos, err := b.c.GetUserProfilePhotos(tgbotapi.UserProfilePhotosConfig{UserID: userid, Limit: 1})\n\t\tif err != nil {\n\t\t\tb.Log.Errorf(\"Userprofile download failed for %#v %s\", userid, err)\n\t\t}\n\n\t\tif len(photos.Photos) > 0 {\n\t\t\tphoto := photos.Photos[0][0]\n\t\t\turl := b.getFileDirectURL(photo.FileID)\n\t\t\tname := strconv.Itoa(userid) + \".png\"\n\t\t\tb.Log.Debugf(\"trying to download %#v fileid %#v with size %#v\", name, photo.FileID, photo.FileSize)\n\n\t\t\terr := helper.HandleDownloadSize(b.Log, &rmsg, name, int64(photo.FileSize), b.General)\n\t\t\tif err != nil {\n\t\t\t\tb.Log.Error(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdata, err := helper.DownloadFile(url)\n\t\t\tif err != nil {\n\t\t\t\tb.Log.Errorf(\"download %s failed %#v\", url, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\thelper.HandleDownloadData(b.Log, &rmsg, name, rmsg.Text, \"\", data, b.General)\n\t\t\tb.Remote <- rmsg\n\t\t}\n\t}\n}\n\n\/\/ handleDownloadFile handles file download\nfunc (b *Btelegram) handleDownload(message *tgbotapi.Message, rmsg *config.Message) error {\n\tsize := 0\n\tvar url, name, text string\n\n\tif message.Sticker != nil {\n\t\tv := message.Sticker\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\turlPart := strings.Split(url, \"\/\")\n\t\tname = urlPart[len(urlPart)-1]\n\t\tif !strings.HasSuffix(name, \".webp\") {\n\t\t\tname = name + \".webp\"\n\t\t}\n\t\ttext = \" \" + url\n\t}\n\tif message.Video != nil {\n\t\tv := message.Video\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\turlPart := strings.Split(url, \"\/\")\n\t\tname = urlPart[len(urlPart)-1]\n\t\ttext = \" \" + url\n\t}\n\tif message.Photo != nil {\n\t\tphotos := *message.Photo\n\t\tsize = photos[len(photos)-1].FileSize\n\t\turl = b.getFileDirectURL(photos[len(photos)-1].FileID)\n\t\turlPart := strings.Split(url, \"\/\")\n\t\tname = urlPart[len(urlPart)-1]\n\t\ttext = \" \" + url\n\t}\n\tif message.Document != nil {\n\t\tv := message.Document\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\tname = v.FileName\n\t\ttext = \" \" + v.FileName + \" : \" + url\n\t}\n\tif message.Voice != nil {\n\t\tv := message.Voice\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\turlPart := strings.Split(url, \"\/\")\n\t\tname = urlPart[len(urlPart)-1]\n\t\ttext = \" \" + url\n\t\tif !strings.HasSuffix(name, \".ogg\") {\n\t\t\tname = name + \".ogg\"\n\t\t}\n\t}\n\tif message.Audio != nil {\n\t\tv := message.Audio\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\turlPart := strings.Split(url, \"\/\")\n\t\tname = urlPart[len(urlPart)-1]\n\t\ttext = \" \" + url\n\t}\n\t\/\/ if name is empty we didn't match a thing to download\n\tif name == \"\" {\n\t\treturn nil\n\t}\n\t\/\/ use the URL instead of native upload\n\tif b.Config.UseInsecureURL {\n\t\tb.Log.Debugf(\"Setting message text to :%s\", text)\n\t\trmsg.Text = rmsg.Text + text\n\t\treturn nil\n\t}\n\t\/\/ if we have a file attached, download it (in memory) and put a pointer to it in msg.Extra\n\terr := helper.HandleDownloadSize(b.Log, rmsg, name, int64(size), b.General)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata, err := helper.DownloadFile(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\thelper.HandleDownloadData(b.Log, rmsg, name, message.Caption, \"\", data, b.General)\n\treturn nil\n}\n\n\/\/ handleUploadFile handles native upload of files\nfunc (b *Btelegram) handleUploadFile(msg *config.Message, chatid int64) (string, error) {\n\tvar c tgbotapi.Chattable\n\tfor _, f := range msg.Extra[\"file\"] {\n\t\tfi := f.(config.FileInfo)\n\t\tfile := tgbotapi.FileBytes{fi.Name, *fi.Data}\n\t\tre := regexp.MustCompile(\".(jpg|png)$\")\n\t\tif re.MatchString(fi.Name) {\n\t\t\tc = tgbotapi.NewPhotoUpload(chatid, file)\n\t\t} else {\n\t\t\tc = tgbotapi.NewDocumentUpload(chatid, file)\n\t\t}\n\t\t_, err := b.c.Send(c)\n\t\tif err != nil {\n\t\t\tb.Log.Errorf(\"file upload failed: %#v\", err)\n\t\t}\n\t\tif fi.Comment != \"\" {\n\t\t\tb.sendMessage(chatid, msg.Username+fi.Comment)\n\t\t}\n\t}\n\treturn \"\", nil\n}\n\nfunc (b *Btelegram) sendMessage(chatid int64, text string) (string, error) {\n\tm := tgbotapi.NewMessage(chatid, text)\n\tif b.Config.MessageFormat == \"HTML\" {\n\t\tb.Log.Debug(\"Using mode HTML\")\n\t\tm.ParseMode = tgbotapi.ModeHTML\n\t}\n\tif b.Config.MessageFormat == \"Markdown\" {\n\t\tb.Log.Debug(\"Using mode markdown\")\n\t\tm.ParseMode = tgbotapi.ModeMarkdown\n\t}\n\tres, err := b.c.Send(m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strconv.Itoa(res.MessageID), nil\n}\n\nfunc (b *Btelegram) cacheAvatar(msg *config.Message) (string, error) {\n\tfi := msg.Extra[\"file\"][0].(config.FileInfo)\n\t\/* if we have a sha we have successfully uploaded the file to the media server,\n\tso we can now cache the sha *\/\n\tif fi.SHA != \"\" {\n\t\tb.Log.Debugf(\"Added %s to %s in avatarMap\", fi.SHA, msg.UserID)\n\t\tb.avatarMap[msg.UserID] = fi.SHA\n\t}\n\treturn \"\", nil\n}\n<commit_msg>Escape html on username (telegram). Closes #378<commit_after>package btelegram\n\nimport (\n\t\"html\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/42wim\/matterbridge\/bridge\"\n\t\"github.com\/42wim\/matterbridge\/bridge\/config\"\n\t\"github.com\/42wim\/matterbridge\/bridge\/helper\"\n\t\"github.com\/go-telegram-bot-api\/telegram-bot-api\"\n)\n\ntype Btelegram struct {\n\tc *tgbotapi.BotAPI\n\t*config.BridgeConfig\n\tavatarMap map[string]string \/\/ keep cache of userid and avatar sha\n}\n\nfunc New(cfg *config.BridgeConfig) bridge.Bridger {\n\treturn &Btelegram{BridgeConfig: cfg, avatarMap: make(map[string]string)}\n}\n\nfunc (b *Btelegram) Connect() error {\n\tvar err error\n\tb.Log.Info(\"Connecting\")\n\tb.c, err = tgbotapi.NewBotAPI(b.Config.Token)\n\tif err != nil {\n\t\tb.Log.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tu := tgbotapi.NewUpdate(0)\n\tu.Timeout = 60\n\tupdates, err := b.c.GetUpdatesChan(u)\n\tif err != nil {\n\t\tb.Log.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tb.Log.Info(\"Connection succeeded\")\n\tgo b.handleRecv(updates)\n\treturn nil\n}\n\nfunc (b *Btelegram) Disconnect() error {\n\treturn nil\n}\n\nfunc (b *Btelegram) JoinChannel(channel config.ChannelInfo) error {\n\treturn nil\n}\n\nfunc (b *Btelegram) Send(msg config.Message) (string, error) {\n\tb.Log.Debugf(\"=> Receiving %#v\", msg)\n\n\t\/\/ get the chatid\n\tchatid, err := strconv.ParseInt(msg.Channel, 10, 64)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t\/\/ map the file SHA to our user (caches the avatar)\n\tif msg.Event == config.EVENT_AVATAR_DOWNLOAD {\n\t\treturn b.cacheAvatar(&msg)\n\t}\n\n\tif b.Config.MessageFormat == \"HTML\" {\n\t\tmsg.Text = makeHTML(msg.Text)\n\t}\n\n\t\/\/ Delete message\n\tif msg.Event == config.EVENT_MSG_DELETE {\n\t\tif msg.ID == \"\" {\n\t\t\treturn \"\", nil\n\t\t}\n\t\tmsgid, err := strconv.Atoi(msg.ID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t_, err = b.c.DeleteMessage(tgbotapi.DeleteMessageConfig{ChatID: chatid, MessageID: msgid})\n\t\treturn \"\", err\n\t}\n\n\t\/\/ Upload a file if it exists\n\tif msg.Extra != nil {\n\t\tfor _, rmsg := range helper.HandleExtra(&msg, b.General) {\n\t\t\tb.sendMessage(chatid, rmsg.Username, rmsg.Text)\n\t\t}\n\t\t\/\/ check if we have files to upload (from slack, telegram or mattermost)\n\t\tif len(msg.Extra[\"file\"]) > 0 {\n\t\t\tb.handleUploadFile(&msg, chatid)\n\t\t}\n\t}\n\n\t\/\/ edit the message if we have a msg ID\n\tif msg.ID != \"\" {\n\t\tmsgid, err := strconv.Atoi(msg.ID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tm := tgbotapi.NewEditMessageText(chatid, msgid, msg.Username+msg.Text)\n\t\tif b.Config.MessageFormat == \"HTML\" {\n\t\t\tb.Log.Debug(\"Using mode HTML\")\n\t\t\tm.ParseMode = tgbotapi.ModeHTML\n\t\t}\n\t\tif b.Config.MessageFormat == \"Markdown\" {\n\t\t\tb.Log.Debug(\"Using mode markdown\")\n\t\t\tm.ParseMode = tgbotapi.ModeMarkdown\n\t\t}\n\t\t_, err = b.c.Send(m)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn \"\", nil\n\t}\n\n\t\/\/ Post normal message\n\treturn b.sendMessage(chatid, msg.Username, msg.Text)\n}\n\nfunc (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {\n\tfor update := range updates {\n\t\tb.Log.Debugf(\"== Receiving event: %#v\", update.Message)\n\n\t\tif update.Message == nil && update.ChannelPost == nil {\n\t\t\tb.Log.Error(\"Getting nil messages, this shouldn't happen.\")\n\t\t\tcontinue\n\t\t}\n\n\t\tvar message *tgbotapi.Message\n\n\t\trmsg := config.Message{Account: b.Account, Extra: make(map[string][]interface{})}\n\n\t\t\/\/ handle channels\n\t\tif update.ChannelPost != nil {\n\t\t\tmessage = update.ChannelPost\n\t\t}\n\n\t\t\/\/ edited channel message\n\t\tif update.EditedChannelPost != nil && !b.Config.EditDisable {\n\t\t\tmessage = update.EditedChannelPost\n\t\t\trmsg.Text = rmsg.Text + message.Text + b.Config.EditSuffix\n\t\t}\n\n\t\t\/\/ handle groups\n\t\tif update.Message != nil {\n\t\t\tmessage = update.Message\n\t\t}\n\n\t\t\/\/ edited group message\n\t\tif update.EditedMessage != nil && !b.Config.EditDisable {\n\t\t\tmessage = update.EditedMessage\n\t\t\trmsg.Text = rmsg.Text + message.Text + b.Config.EditSuffix\n\t\t}\n\n\t\t\/\/ set the ID's from the channel or group message\n\t\trmsg.ID = strconv.Itoa(message.MessageID)\n\t\trmsg.UserID = strconv.Itoa(message.From.ID)\n\t\trmsg.Channel = strconv.FormatInt(message.Chat.ID, 10)\n\n\t\t\/\/ handle username\n\t\tif message.From != nil {\n\t\t\tif b.Config.UseFirstName {\n\t\t\t\trmsg.Username = message.From.FirstName\n\t\t\t}\n\t\t\tif rmsg.Username == \"\" {\n\t\t\t\trmsg.Username = message.From.UserName\n\t\t\t\tif rmsg.Username == \"\" {\n\t\t\t\t\trmsg.Username = message.From.FirstName\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ only download avatars if we have a place to upload them (configured mediaserver)\n\t\t\tif b.General.MediaServerUpload != \"\" {\n\t\t\t\tb.handleDownloadAvatar(message.From.ID, rmsg.Channel)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ if we really didn't find a username, set it to unknown\n\t\tif rmsg.Username == \"\" {\n\t\t\trmsg.Username = \"unknown\"\n\t\t}\n\n\t\t\/\/ handle any downloads\n\t\terr := b.handleDownload(message, &rmsg)\n\t\tif err != nil {\n\t\t\tb.Log.Errorf(\"download failed: %s\", err)\n\t\t}\n\n\t\t\/\/ handle forwarded messages\n\t\tif message.ForwardFrom != nil {\n\t\t\tusernameForward := \"\"\n\t\t\tif b.Config.UseFirstName {\n\t\t\t\tusernameForward = message.ForwardFrom.FirstName\n\t\t\t}\n\t\t\tif usernameForward == \"\" {\n\t\t\t\tusernameForward = message.ForwardFrom.UserName\n\t\t\t\tif usernameForward == \"\" {\n\t\t\t\t\tusernameForward = message.ForwardFrom.FirstName\n\t\t\t\t}\n\t\t\t}\n\t\t\tif usernameForward == \"\" {\n\t\t\t\tusernameForward = \"unknown\"\n\t\t\t}\n\t\t\trmsg.Text = \"Forwarded from \" + usernameForward + \": \" + rmsg.Text\n\t\t}\n\n\t\t\/\/ quote the previous message\n\t\tif message.ReplyToMessage != nil {\n\t\t\tusernameReply := \"\"\n\t\t\tif message.ReplyToMessage.From != nil {\n\t\t\t\tif b.Config.UseFirstName {\n\t\t\t\t\tusernameReply = message.ReplyToMessage.From.FirstName\n\t\t\t\t}\n\t\t\t\tif usernameReply == \"\" {\n\t\t\t\t\tusernameReply = message.ReplyToMessage.From.UserName\n\t\t\t\t\tif usernameReply == \"\" {\n\t\t\t\t\t\tusernameReply = message.ReplyToMessage.From.FirstName\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif usernameReply == \"\" {\n\t\t\t\tusernameReply = \"unknown\"\n\t\t\t}\n\t\t\trmsg.Text = rmsg.Text + \" (re @\" + usernameReply + \":\" + message.ReplyToMessage.Text + \")\"\n\t\t}\n\n\t\tif rmsg.Text != \"\" || len(rmsg.Extra) > 0 {\n\t\t\trmsg.Avatar = helper.GetAvatar(b.avatarMap, strconv.Itoa(message.From.ID), b.General)\n\n\t\t\tb.Log.Debugf(\"<= Sending message from %s on %s to gateway\", rmsg.Username, b.Account)\n\t\t\tb.Log.Debugf(\"<= Message is %#v\", rmsg)\n\t\t\tb.Remote <- rmsg\n\t\t}\n\t}\n}\n\nfunc (b *Btelegram) getFileDirectURL(id string) string {\n\tres, err := b.c.GetFileDirectURL(id)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn res\n}\n\n\/\/ handleDownloadAvatar downloads the avatar of userid from channel\n\/\/ sends a EVENT_AVATAR_DOWNLOAD message to the gateway if successful.\n\/\/ logs an error message if it fails\nfunc (b *Btelegram) handleDownloadAvatar(userid int, channel string) {\n\trmsg := config.Message{Username: \"system\", Text: \"avatar\", Channel: channel, Account: b.Account, UserID: strconv.Itoa(userid), Event: config.EVENT_AVATAR_DOWNLOAD, Extra: make(map[string][]interface{})}\n\tif _, ok := b.avatarMap[strconv.Itoa(userid)]; !ok {\n\t\tphotos, err := b.c.GetUserProfilePhotos(tgbotapi.UserProfilePhotosConfig{UserID: userid, Limit: 1})\n\t\tif err != nil {\n\t\t\tb.Log.Errorf(\"Userprofile download failed for %#v %s\", userid, err)\n\t\t}\n\n\t\tif len(photos.Photos) > 0 {\n\t\t\tphoto := photos.Photos[0][0]\n\t\t\turl := b.getFileDirectURL(photo.FileID)\n\t\t\tname := strconv.Itoa(userid) + \".png\"\n\t\t\tb.Log.Debugf(\"trying to download %#v fileid %#v with size %#v\", name, photo.FileID, photo.FileSize)\n\n\t\t\terr := helper.HandleDownloadSize(b.Log, &rmsg, name, int64(photo.FileSize), b.General)\n\t\t\tif err != nil {\n\t\t\t\tb.Log.Error(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdata, err := helper.DownloadFile(url)\n\t\t\tif err != nil {\n\t\t\t\tb.Log.Errorf(\"download %s failed %#v\", url, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\thelper.HandleDownloadData(b.Log, &rmsg, name, rmsg.Text, \"\", data, b.General)\n\t\t\tb.Remote <- rmsg\n\t\t}\n\t}\n}\n\n\/\/ handleDownloadFile handles file download\nfunc (b *Btelegram) handleDownload(message *tgbotapi.Message, rmsg *config.Message) error {\n\tsize := 0\n\tvar url, name, text string\n\n\tif message.Sticker != nil {\n\t\tv := message.Sticker\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\turlPart := strings.Split(url, \"\/\")\n\t\tname = urlPart[len(urlPart)-1]\n\t\tif !strings.HasSuffix(name, \".webp\") {\n\t\t\tname = name + \".webp\"\n\t\t}\n\t\ttext = \" \" + url\n\t}\n\tif message.Video != nil {\n\t\tv := message.Video\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\turlPart := strings.Split(url, \"\/\")\n\t\tname = urlPart[len(urlPart)-1]\n\t\ttext = \" \" + url\n\t}\n\tif message.Photo != nil {\n\t\tphotos := *message.Photo\n\t\tsize = photos[len(photos)-1].FileSize\n\t\turl = b.getFileDirectURL(photos[len(photos)-1].FileID)\n\t\turlPart := strings.Split(url, \"\/\")\n\t\tname = urlPart[len(urlPart)-1]\n\t\ttext = \" \" + url\n\t}\n\tif message.Document != nil {\n\t\tv := message.Document\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\tname = v.FileName\n\t\ttext = \" \" + v.FileName + \" : \" + url\n\t}\n\tif message.Voice != nil {\n\t\tv := message.Voice\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\turlPart := strings.Split(url, \"\/\")\n\t\tname = urlPart[len(urlPart)-1]\n\t\ttext = \" \" + url\n\t\tif !strings.HasSuffix(name, \".ogg\") {\n\t\t\tname = name + \".ogg\"\n\t\t}\n\t}\n\tif message.Audio != nil {\n\t\tv := message.Audio\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\turlPart := strings.Split(url, \"\/\")\n\t\tname = urlPart[len(urlPart)-1]\n\t\ttext = \" \" + url\n\t}\n\t\/\/ if name is empty we didn't match a thing to download\n\tif name == \"\" {\n\t\treturn nil\n\t}\n\t\/\/ use the URL instead of native upload\n\tif b.Config.UseInsecureURL {\n\t\tb.Log.Debugf(\"Setting message text to :%s\", text)\n\t\trmsg.Text = rmsg.Text + text\n\t\treturn nil\n\t}\n\t\/\/ if we have a file attached, download it (in memory) and put a pointer to it in msg.Extra\n\terr := helper.HandleDownloadSize(b.Log, rmsg, name, int64(size), b.General)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdata, err := helper.DownloadFile(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\thelper.HandleDownloadData(b.Log, rmsg, name, message.Caption, \"\", data, b.General)\n\treturn nil\n}\n\n\/\/ handleUploadFile handles native upload of files\nfunc (b *Btelegram) handleUploadFile(msg *config.Message, chatid int64) (string, error) {\n\tvar c tgbotapi.Chattable\n\tfor _, f := range msg.Extra[\"file\"] {\n\t\tfi := f.(config.FileInfo)\n\t\tfile := tgbotapi.FileBytes{fi.Name, *fi.Data}\n\t\tre := regexp.MustCompile(\".(jpg|png)$\")\n\t\tif re.MatchString(fi.Name) {\n\t\t\tc = tgbotapi.NewPhotoUpload(chatid, file)\n\t\t} else {\n\t\t\tc = tgbotapi.NewDocumentUpload(chatid, file)\n\t\t}\n\t\t_, err := b.c.Send(c)\n\t\tif err != nil {\n\t\t\tb.Log.Errorf(\"file upload failed: %#v\", err)\n\t\t}\n\t\tif fi.Comment != \"\" {\n\t\t\tb.sendMessage(chatid, msg.Username, fi.Comment)\n\t\t}\n\t}\n\treturn \"\", nil\n}\n\nfunc (b *Btelegram) sendMessage(chatid int64, username, text string) (string, error) {\n\tm := tgbotapi.NewMessage(chatid, \"\")\n\tm.Text = username + text\n\tif b.Config.MessageFormat == \"HTML\" {\n\t\tb.Log.Debug(\"Using mode HTML\")\n\t\tusername = html.EscapeString(username)\n\t\tm.Text = username + text\n\t\tm.ParseMode = tgbotapi.ModeHTML\n\t}\n\tif b.Config.MessageFormat == \"Markdown\" {\n\t\tb.Log.Debug(\"Using mode markdown\")\n\t\tm.ParseMode = tgbotapi.ModeMarkdown\n\t}\n\tres, err := b.c.Send(m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strconv.Itoa(res.MessageID), nil\n}\n\nfunc (b *Btelegram) cacheAvatar(msg *config.Message) (string, error) {\n\tfi := msg.Extra[\"file\"][0].(config.FileInfo)\n\t\/* if we have a sha we have successfully uploaded the file to the media server,\n\tso we can now cache the sha *\/\n\tif fi.SHA != \"\" {\n\t\tb.Log.Debugf(\"Added %s to %s in avatarMap\", fi.SHA, msg.UserID)\n\t\tb.avatarMap[msg.UserID] = fi.SHA\n\t}\n\treturn \"\", nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package btelegram\n\nimport (\n\t\"strconv\"\n\n\t\"github.com\/42wim\/matterbridge\/bridge\/config\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/go-telegram-bot-api\/telegram-bot-api\"\n)\n\ntype Btelegram struct {\n\tc       *tgbotapi.BotAPI\n\tConfig  *config.Protocol\n\tRemote  chan config.Message\n\tAccount string\n}\n\nvar flog *log.Entry\nvar protocol = \"telegram\"\n\nfunc init() {\n\tflog = log.WithFields(log.Fields{\"module\": protocol})\n}\n\nfunc New(cfg config.Protocol, account string, c chan config.Message) *Btelegram {\n\tb := &Btelegram{}\n\tb.Config = &cfg\n\tb.Remote = c\n\tb.Account = account\n\treturn b\n}\n\nfunc (b *Btelegram) Connect() error {\n\tvar err error\n\tflog.Info(\"Connecting\")\n\tb.c, err = tgbotapi.NewBotAPI(b.Config.Token)\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tupdates, err := b.c.GetUpdatesChan(tgbotapi.NewUpdate(0))\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tflog.Info(\"Connection succeeded\")\n\tgo b.handleRecv(updates)\n\treturn nil\n}\n\nfunc (b *Btelegram) Disconnect() error {\n\treturn nil\n\n}\n\nfunc (b *Btelegram) JoinChannel(channel config.ChannelInfo) error {\n\treturn nil\n}\n\nfunc (b *Btelegram) Send(msg config.Message) (string, error) {\n\tflog.Debugf(\"Receiving %#v\", msg)\n\tchatid, err := strconv.ParseInt(msg.Channel, 10, 64)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif b.Config.MessageFormat == \"HTML\" {\n\t\tmsg.Text = makeHTML(msg.Text)\n\t}\n\n\tif msg.Event == config.EVENT_MSG_DELETE {\n\t\tif msg.ID == \"\" {\n\t\t\treturn \"\", nil\n\t\t}\n\t\tmsgid, err := strconv.Atoi(msg.ID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t_, err = b.c.DeleteMessage(tgbotapi.DeleteMessageConfig{ChatID: chatid, MessageID: msgid})\n\t\treturn \"\", err\n\t}\n\n\t\/\/ edit the message if we have a msg ID\n\tif msg.ID != \"\" {\n\t\tmsgid, err := strconv.Atoi(msg.ID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tm := tgbotapi.NewEditMessageText(chatid, msgid, msg.Username+msg.Text)\n\t\t_, err = b.c.Send(m)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn \"\", nil\n\t}\n\n\tm := tgbotapi.NewMessage(chatid, msg.Username+msg.Text)\n\tif b.Config.MessageFormat == \"HTML\" {\n\t\tm.ParseMode = tgbotapi.ModeHTML\n\t}\n\tres, err := b.c.Send(m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strconv.Itoa(res.MessageID), nil\n\n}\n\nfunc (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {\n\tfor update := range updates {\n\t\tflog.Debugf(\"Receiving from telegram: %#v\", update.Message)\n\t\tvar message *tgbotapi.Message\n\t\tusername := \"\"\n\t\tchannel := \"\"\n\t\ttext := \"\"\n\t\t\/\/ handle channels\n\t\tif update.ChannelPost != nil {\n\t\t\tmessage = update.ChannelPost\n\t\t}\n\t\tif update.EditedChannelPost != nil && !b.Config.EditDisable {\n\t\t\tmessage = update.EditedChannelPost\n\t\t\tmessage.Text = message.Text + b.Config.EditSuffix\n\t\t}\n\t\t\/\/ handle groups\n\t\tif update.Message != nil {\n\t\t\tmessage = update.Message\n\t\t}\n\t\tif update.EditedMessage != nil && !b.Config.EditDisable {\n\t\t\tmessage = update.EditedMessage\n\t\t\tmessage.Text = message.Text + b.Config.EditSuffix\n\t\t}\n\t\tif message.From != nil {\n\t\t\tif b.Config.UseFirstName {\n\t\t\t\tusername = message.From.FirstName\n\t\t\t}\n\t\t\tif username == \"\" {\n\t\t\t\tusername = message.From.UserName\n\t\t\t\tif username == \"\" {\n\t\t\t\t\tusername = message.From.FirstName\n\t\t\t\t}\n\t\t\t}\n\t\t\ttext = message.Text\n\t\t\tchannel = strconv.FormatInt(message.Chat.ID, 10)\n\t\t}\n\n\t\tif username == \"\" {\n\t\t\tusername = \"unknown\"\n\t\t}\n\t\tif message.Sticker != nil && b.Config.UseInsecureURL {\n\t\t\ttext = text + \" \" + b.getFileDirectURL(message.Sticker.FileID)\n\t\t}\n\t\tif message.Video != nil && b.Config.UseInsecureURL {\n\t\t\ttext = text + \" \" + b.getFileDirectURL(message.Video.FileID)\n\t\t}\n\t\tif message.Photo != nil && b.Config.UseInsecureURL {\n\t\t\tphotos := *message.Photo\n\t\t\t\/\/ last photo is the biggest\n\t\t\ttext = text + \" \" + b.getFileDirectURL(photos[len(photos)-1].FileID)\n\t\t}\n\t\tif message.Document != nil && b.Config.UseInsecureURL {\n\t\t\ttext = text + \" \" + message.Document.FileName + \" : \" + b.getFileDirectURL(message.Document.FileID)\n\t\t}\n\n\t\t\/\/ quote the previous message\n\t\tif message.ReplyToMessage != nil {\n\t\t\tusernameReply := \"\"\n\t\t\tif message.ReplyToMessage.From != nil {\n\t\t\t\tif b.Config.UseFirstName {\n\t\t\t\t\tusernameReply = message.ReplyToMessage.From.FirstName\n\t\t\t\t}\n\t\t\t\tif usernameReply == \"\" {\n\t\t\t\t\tusernameReply = message.ReplyToMessage.From.UserName\n\t\t\t\t\tif usernameReply == \"\" {\n\t\t\t\t\t\tusernameReply = message.ReplyToMessage.From.FirstName\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif usernameReply == \"\" {\n\t\t\t\tusernameReply = \"unknown\"\n\t\t\t}\n\t\t\ttext = text + \" (re @\" + usernameReply + \":\" + message.ReplyToMessage.Text + \")\"\n\t\t}\n\n\t\tif text != \"\" {\n\t\t\tflog.Debugf(\"Sending message from %s on %s to gateway\", username, b.Account)\n\t\t\tmsg := config.Message{Username: username, Text: text, Channel: channel, Account: b.Account, UserID: strconv.Itoa(message.From.ID), ID: strconv.Itoa(message.MessageID)}\n\t\t\tflog.Debugf(\"Message is %#v\", msg)\n\t\t\tb.Remote <- msg\n\t\t}\n\t}\n}\n\nfunc (b *Btelegram) getFileDirectURL(id string) string {\n\tres, err := b.c.GetFileDirectURL(id)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn res\n}\n<commit_msg>Download files from telegram and reupload to supported bridges (telegram). #278<commit_after>package btelegram\n\nimport (\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"github.com\/42wim\/matterbridge\/bridge\/config\"\n\t\"github.com\/42wim\/matterbridge\/bridge\/helper\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/go-telegram-bot-api\/telegram-bot-api\"\n)\n\ntype Btelegram struct {\n\tc       *tgbotapi.BotAPI\n\tConfig  *config.Protocol\n\tRemote  chan config.Message\n\tAccount string\n}\n\nvar flog *log.Entry\nvar protocol = \"telegram\"\n\nfunc init() {\n\tflog = log.WithFields(log.Fields{\"module\": protocol})\n}\n\nfunc New(cfg config.Protocol, account string, c chan config.Message) *Btelegram {\n\tb := &Btelegram{}\n\tb.Config = &cfg\n\tb.Remote = c\n\tb.Account = account\n\treturn b\n}\n\nfunc (b *Btelegram) Connect() error {\n\tvar err error\n\tflog.Info(\"Connecting\")\n\tb.c, err = tgbotapi.NewBotAPI(b.Config.Token)\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tupdates, err := b.c.GetUpdatesChan(tgbotapi.NewUpdate(0))\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tflog.Info(\"Connection succeeded\")\n\tgo b.handleRecv(updates)\n\treturn nil\n}\n\nfunc (b *Btelegram) Disconnect() error {\n\treturn nil\n\n}\n\nfunc (b *Btelegram) JoinChannel(channel config.ChannelInfo) error {\n\treturn nil\n}\n\nfunc (b *Btelegram) Send(msg config.Message) (string, error) {\n\tflog.Debugf(\"Receiving %#v\", msg)\n\tchatid, err := strconv.ParseInt(msg.Channel, 10, 64)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif b.Config.MessageFormat == \"HTML\" {\n\t\tmsg.Text = makeHTML(msg.Text)\n\t}\n\n\tif msg.Event == config.EVENT_MSG_DELETE {\n\t\tif msg.ID == \"\" {\n\t\t\treturn \"\", nil\n\t\t}\n\t\tmsgid, err := strconv.Atoi(msg.ID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t_, err = b.c.DeleteMessage(tgbotapi.DeleteMessageConfig{ChatID: chatid, MessageID: msgid})\n\t\treturn \"\", err\n\t}\n\n\t\/\/ edit the message if we have a msg ID\n\tif msg.ID != \"\" {\n\t\tmsgid, err := strconv.Atoi(msg.ID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tm := tgbotapi.NewEditMessageText(chatid, msgid, msg.Username+msg.Text)\n\t\t_, err = b.c.Send(m)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn \"\", nil\n\t}\n\n\tif msg.Extra != nil {\n\t\t\/\/ check if we have files to upload (from slack, telegram or mattermost)\n\t\tif len(msg.Extra[\"file\"]) > 0 {\n\t\t\tvar c tgbotapi.Chattable\n\t\t\tfor _, f := range msg.Extra[\"file\"] {\n\t\t\t\tfi := f.(config.FileInfo)\n\t\t\t\tfile := tgbotapi.FileBytes{fi.Name, *fi.Data}\n\t\t\t\tre := regexp.MustCompile(\".(jpg|png)$\")\n\t\t\t\tif re.MatchString(fi.Name) {\n\t\t\t\t\tc = tgbotapi.NewPhotoUpload(chatid, file)\n\t\t\t\t} else {\n\t\t\t\t\tc = tgbotapi.NewDocumentUpload(chatid, file)\n\t\t\t\t}\n\t\t\t\t_, err := b.c.Send(c)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"file upload failed: %#v\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tm := tgbotapi.NewMessage(chatid, msg.Username+msg.Text)\n\tif b.Config.MessageFormat == \"HTML\" {\n\t\tm.ParseMode = tgbotapi.ModeHTML\n\t}\n\tres, err := b.c.Send(m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strconv.Itoa(res.MessageID), nil\n\n}\n\nfunc (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {\n\tfor update := range updates {\n\t\tflog.Debugf(\"Receiving from telegram: %#v\", update.Message)\n\t\tvar message *tgbotapi.Message\n\t\tusername := \"\"\n\t\tchannel := \"\"\n\t\ttext := \"\"\n\n\t\tfmsg := config.Message{Extra: make(map[string][]interface{})}\n\n\t\t\/\/ handle channels\n\t\tif update.ChannelPost != nil {\n\t\t\tmessage = update.ChannelPost\n\t\t}\n\t\tif update.EditedChannelPost != nil && !b.Config.EditDisable {\n\t\t\tmessage = update.EditedChannelPost\n\t\t\tmessage.Text = message.Text + b.Config.EditSuffix\n\t\t}\n\t\t\/\/ handle groups\n\t\tif update.Message != nil {\n\t\t\tmessage = update.Message\n\t\t}\n\t\tif update.EditedMessage != nil && !b.Config.EditDisable {\n\t\t\tmessage = update.EditedMessage\n\t\t\tmessage.Text = message.Text + b.Config.EditSuffix\n\t\t}\n\t\tif message.From != nil {\n\t\t\tif b.Config.UseFirstName {\n\t\t\t\tusername = message.From.FirstName\n\t\t\t}\n\t\t\tif username == \"\" {\n\t\t\t\tusername = message.From.UserName\n\t\t\t\tif username == \"\" {\n\t\t\t\t\tusername = message.From.FirstName\n\t\t\t\t}\n\t\t\t}\n\t\t\ttext = message.Text\n\t\t\tchannel = strconv.FormatInt(message.Chat.ID, 10)\n\t\t}\n\n\t\tif username == \"\" {\n\t\t\tusername = \"unknown\"\n\t\t}\n\t\tif message.Sticker != nil {\n\t\t\tb.handleDownload(message.Sticker, &fmsg)\n\t\t}\n\t\tif message.Video != nil {\n\t\t\tb.handleDownload(message.Video, &fmsg)\n\t\t}\n\t\tif message.Photo != nil && b.Config.UseInsecureURL {\n\t\t\tb.handleDownload(message.Photo, &fmsg)\n\t\t}\n\t\tif message.Document != nil && b.Config.UseInsecureURL {\n\t\t\tb.handleDownload(message.Sticker, &fmsg)\n\t\t\ttext = text + \" \" + message.Document.FileName + \" : \" + b.getFileDirectURL(message.Document.FileID)\n\t\t}\n\n\t\t\/\/ quote the previous message\n\t\tif message.ReplyToMessage != nil {\n\t\t\tusernameReply := \"\"\n\t\t\tif message.ReplyToMessage.From != nil {\n\t\t\t\tif b.Config.UseFirstName {\n\t\t\t\t\tusernameReply = message.ReplyToMessage.From.FirstName\n\t\t\t\t}\n\t\t\t\tif usernameReply == \"\" {\n\t\t\t\t\tusernameReply = message.ReplyToMessage.From.UserName\n\t\t\t\t\tif usernameReply == \"\" {\n\t\t\t\t\t\tusernameReply = message.ReplyToMessage.From.FirstName\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif usernameReply == \"\" {\n\t\t\t\tusernameReply = \"unknown\"\n\t\t\t}\n\t\t\ttext = text + \" (re @\" + usernameReply + \":\" + message.ReplyToMessage.Text + \")\"\n\t\t}\n\n\t\tif text != \"\" || len(fmsg.Extra) > 0 {\n\t\t\tflog.Debugf(\"Sending message from %s on %s to gateway\", username, b.Account)\n\t\t\tmsg := config.Message{Username: username, Text: text, Channel: channel, Account: b.Account, UserID: strconv.Itoa(message.From.ID), ID: strconv.Itoa(message.MessageID)}\n\t\t\tflog.Debugf(\"Message is %#v\", msg)\n\t\t\tb.Remote <- msg\n\t\t}\n\t}\n}\n\nfunc (b *Btelegram) getFileDirectURL(id string) string {\n\tres, err := b.c.GetFileDirectURL(id)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn res\n}\n\nfunc (b *Btelegram) handleDownload(file interface{}, msg *config.Message) {\n\tsize := 0\n\turl := \"\"\n\tname := \"\"\n\ttext := \"\"\n\tswitch v := file.(type) {\n\tcase *tgbotapi.Sticker:\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\tname = \"sticker\"\n\t\ttext = \" \" + url\n\tcase *tgbotapi.Video:\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\tname = \"video\"\n\t\ttext = \" \" + url\n\tcase *[]tgbotapi.PhotoSize:\n\t\tphotos := *v\n\t\tsize = photos[len(photos)-1].FileSize\n\t\turl = b.getFileDirectURL(photos[len(photos)-1].FileID)\n\t\tname = \"photo\"\n\t\ttext = \" \" + url\n\tcase *tgbotapi.Document:\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\tname = v.FileName\n\t\ttext = \" \" + v.FileName + \" : \" + url\n\t}\n\tif b.Config.UseInsecureURL {\n\t\tmsg.Text = text\n\t\treturn\n\t}\n\t\/\/ if we have a file attached, download it (in memory) and put a pointer to it in msg.Extra\n\t\/\/ limit to 1MB for now\n\tif size <= 1000000 {\n\t\tdata, err := helper.DownloadFile(url)\n\t\tif err != nil {\n\t\t\tflog.Errorf(\"download %s failed %#v\", url, err)\n\t\t} else {\n\t\t\tmsg.Extra[\"file\"] = append(msg.Extra[\"file\"], config.FileInfo{Name: name, Data: data})\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Matthew Collins\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage biome\n\nvar byId [256]*Type\n\n\/\/ Biomes\nvar (\n\t\/\/ Snowy\n\tFrozenOcean        = newBiome(10, 0.0, 0.5)\n\tFrozenRiver        = newBiome(11, 0.0, 0.5)\n\tIcePlains          = newBiome(12, 0.0, 0.5)\n\tIcePlainsSpikes    = newBiome(140, 0.0, 0.5)\n\tColdBeach          = newBiome(26, 0.05, 0.3)\n\tColdTaiga          = newBiome(30, 0.0, 0.4)\n\tColdTaigaMountains = newBiome(158, 0.0, 0.4)\n\t\/\/ Cold\n\tExtremeHills              = newBiome(3, 0.2, 0.3)\n\tExtremeHillsMountains     = newBiome(131, 0.2, 0.3)\n\tTaiga                     = newBiome(5, 0.25, 0.8)\n\tTaigaM                    = newBiome(133, 0.25, 0.8)\n\tTheEnd                    = newBiome(9, 0.5, 0.5)\n\tMegaTaiga                 = newBiome(32, 0.3, 0.8)\n\tMegaSpruceTaiga           = newBiome(160, 0.5, 0.5)\n\tExtremeHillsPlus          = newBiome(34, 0.2, 0.3)\n\tExtremeHillsPlusMountains = newBiome(162, 0.2, 0.3)\n\tStoneBeach                = newBiome(25, 0.2, 0.3)\n\t\/\/ Medium\/Lush\n\tPlains                = newBiome(1, 0.5, 0.5)\n\tSunflowerPlains       = newBiome(129, 0.5, 0.5)\n\tForest                = newBiome(4, 0.5, 0.5)\n\tFlowerForest          = newBiome(132, 0.5, 0.5)\n\tSwampland             = newBiome(6, 0.8, 0.9)\n\tSwamplandMountains    = newBiome(134, 0.8, 0.9)\n\tRiver                 = newBiome(7, 0.5, 0.5)\n\tMushroomIsland        = newBiome(14, 0.9, 1.0)\n\tMushroomISlandShore   = newBiome(15, 0.9, 1.0)\n\tBeach                 = newBiome(16, 0.8, 0.4)\n\tJungle                = newBiome(21, 0.95, 0.8)\n\tJungleMountains       = newBiome(149, 0.95, 0.9)\n\tJungleEdge            = newBiome(23, 0.95, 0.8)\n\tJungleEdgeMountains   = newBiome(151, 0.95, 0.8)\n\tBirchForest           = newBiome(27, 0.5, 0.5)\n\tBirchForestMountains  = newBiome(155, 0.5, 0.5)\n\tRoofedForest          = newBiome(29, 0.5, 0.5)\n\tRoofedForestMountains = newBiome(157, 0.5, 0.5)\n\t\/\/ Dry\/Warm\n\tDesert                     = newBiome(2, 1.0, 0.0)\n\tDesertMountain             = newBiome(130, 1.0, 0.0)\n\tHell                       = newBiome(8, 1.0, 0.0)\n\tSavanna                    = newBiome(35, 1.0, 0.0)\n\tSavannaMountains           = newBiome(163, 1.0, 0.0)\n\tMesa                       = newBiome(37, 0.5, 0.5)\n\tMesaBryce                  = newBiome(165, 0.5, 0.5)\n\tSavannaPlateau             = newBiome(36, 1.0, 0.0)\n\tMesaPlateauForest          = newBiome(38, 0.5, 0.5)\n\tMesaPlateau                = newBiome(39, 0.5, 0.5)\n\tSavannaPlateauMountains    = newBiome(164, 1.0, 0.0)\n\tMesaPlateauForestMountains = newBiome(166, 0.5, 0.5)\n\tMesaPlateauMountains       = newBiome(167, 0.5, 0.5)\n\t\/\/ Neutral\n\tOcean                     = newBiome(0, 0.5, 0.5)\n\tDeepOcean                 = newBiome(24, 0.5, 0.5)\n\tIceMountains              = newBiome(13, 0.0, 0.5)\n\tDesertHills               = newBiome(17, 1.0, 0.0)\n\tForestHills               = newBiome(18, 0.45, 0.3)\n\tTaigaHills                = newBiome(19, 0.25, 0.8)\n\tJungleHills               = newBiome(22, 0.95, 0.9)\n\tBirchForestHills          = newBiome(28, 0.5, 0.5)\n\tColdTaigaHills            = newBiome(31, 0.5, 0.5)\n\tMegaTaigaHills            = newBiome(33, 0.3, 0.8)\n\tBirchForestHillsMountains = newBiome(156, 0.5, 0.5)\n\tMegaSpruceTaigaHills      = newBiome(161, 0.5, 0.5)\n\t\/\/ Custom\n\tInvalid = newBiome(255, 0.0, 0.0)\n)\n\nfunc ById(id byte) *Type {\n\treturn byId[id]\n}\n\ntype Type struct {\n\tID                    int\n\tTemperature, Moisture float64\n\tColorIndex            int\n}\n\nfunc newBiome(id int, temperature, moisture float64) *Type {\n\tb := &Type{\n\t\tID:          id,\n\t\tTemperature: temperature,\n\t\tMoisture:    moisture * temperature,\n\t}\n\tbx := int((1.0 - temperature) * 255.0)\n\tby := int((1.0 - moisture) * 255.0)\n\tb.ColorIndex = bx | (by << 8)\n\tbyId[id] = b\n\treturn b\n}\n\nfunc init() {\n\tfor i := range byId {\n\t\tif byId[i] == nil {\n\t\t\tbyId[i] = Invalid\n\t\t}\n\t}\n}\n<commit_msg>world\/biome: fix all biomes' values and fix the color index computing<commit_after>\/\/ Copyright 2015 Matthew Collins\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage biome\n\nvar byId [256]*Type\n\n\/\/ Biomes\nvar (\n\tOcean               = newBiome(0, 0.5, 0.5)\n\tPlains              = newBiome(1, 0.8, 0.4)\n\tDesert              = newBiome(2, 2.0, 0.0)\n\tExtremeHills        = newBiome(3, 0.2, 0.3)\n\tForest              = newBiome(4, 0.7, 0.8)\n\tTaiga               = newBiome(5, 0.05, 0.8)\n\tSwampland           = newBiome(6, 0.8, 0.9)\n\tRiver               = newBiome(7, 0.5, 0.5)\n\tHell                = newBiome(8, 2.0, 0.0)\n\tTheEnd              = newBiome(9, 0.5, 0.5)\n\tFrozenOcean         = newBiome(10, 0.0, 0.5)\n\tFrozenRiver         = newBiome(11, 0.0, 0.5)\n\tIcePlains           = newBiome(12, 0.0, 0.5)\n\tIceMountains        = newBiome(13, 0.0, 0.5)\n\tMushroomIsland      = newBiome(14, 0.9, 1.0)\n\tMushroomISlandShore = newBiome(15, 0.9, 1.0)\n\tBeach               = newBiome(16, 0.8, 0.4)\n\tDesertHills         = newBiome(17, 2.0, 0.0)\n\tForestHills         = newBiome(18, 0.7, 0.8)\n\tTaigaHills          = newBiome(19, 0.2, 0.7)\n\tExtremeHillsEdge    = newBiome(20, 0.2, 0.3)\n\tJungle              = newBiome(21, 1.2, 0.9)\n\tJungleHills         = newBiome(22, 1.2, 0.9)\n\tJungleEdge          = newBiome(23, 0.95, 0.8)\n\tDeepOcean           = newBiome(24, 0.5, 0.5)\n\tStoneBeach          = newBiome(25, 0.2, 0.3)\n\tColdBeach           = newBiome(26, 0.05, 0.3)\n\tBirchForest         = newBiome(27, 0.6, 0.6)\n\tBirchForestHills    = newBiome(28, 0.6, 0.6)\n\tRoofedForest        = newBiome(29, 0.7, 0.8)\n\tColdTaiga           = newBiome(30, -0.5, 0.4)\n\tColdTaigaHills      = newBiome(31, -0.5, 0.4)\n\tMegaTaiga           = newBiome(32, 0.3, 0.8)\n\tMegaTaigaHills      = newBiome(33, 0.3, 0.8)\n\tExtremeHillsPlus    = newBiome(34, 0.2, 0.3)\n\tSavanna             = newBiome(35, 1.2, 0.0)\n\tSavannaPlateau      = newBiome(36, 1.0, 0.0)\n\tMesa                = newBiome(37, 2.0, 0.0)\n\tMesaPlateauForest   = newBiome(38, 2.0, 0.0)\n\tMesaPlateau         = newBiome(39, 2.0, 0.0)\n\n\tSunflowerPlains            = newBiome(129, 0.8, 0.4)\n\tDesertMountain             = newBiome(130, 2.0, 0.0)\n\tExtremeHillsMountains      = newBiome(131, 0.2, 0.3)\n\tFlowerForest               = newBiome(132, 0.7, 0.8)\n\tTaigaM                     = newBiome(133, 0.05, 0.8)\n\tSwamplandMountains         = newBiome(134, 0.8, 0.9)\n\tIcePlainsSpikes            = newBiome(140, 0.0, 0.5)\n\tJungleMountains            = newBiome(149, 1.2, 0.9)\n\tJungleEdgeMountains        = newBiome(151, 0.95, 0.8)\n\tBirchForestMountains       = newBiome(155, 0.6, 0.6)\n\tBirchForestHillsMountains  = newBiome(156, 0.6, 0.6)\n\tRoofedForestMountains      = newBiome(157, 0.7, 0.8)\n\tColdTaigaMountains         = newBiome(158, -0.5, 0.4)\n\tMegaSpruceTaiga            = newBiome(160, 0.25, 0.8)\n\tMegaSpruceTaigaHills       = newBiome(161, 0.3, 0.8)\n\tExtremeHillsPlusMountains  = newBiome(162, 0.2, 0.3)\n\tSavannaMountains           = newBiome(163, 1.2, 0.0)\n\tSavannaPlateauMountains    = newBiome(164, 1.0, 0.0)\n\tMesaBryce                  = newBiome(165, 2.0, 0.0)\n\tMesaPlateauForestMountains = newBiome(166, 2.0, 0.0)\n\tMesaPlateauMountains       = newBiome(167, 2.0, 0.0)\n\t\/\/\n\tInvalid = newBiome(255, 0.0, 0.0)\n)\n\nfunc ById(id byte) *Type {\n\tif val := byId[id]; val != nil {\n\t\treturn val\n\t}\n\treturn Invalid\n}\n\ntype Type struct {\n\tID                    int\n\tTemperature, Moisture float64\n\tColorIndex            int\n}\n\nfunc newBiome(id int, temperature, moisture float64) *Type {\n\tb := &Type{\n\t\tID:          id,\n\t\tTemperature: clamp(temperature, 0, 1),\n\t\tMoisture:    clamp(moisture, 0, 1),\n\t}\n\tb.Moisture *= b.Temperature\n\tbx := int((1.0 - b.Temperature) * 255.0)\n\tby := int((1.0 - b.Moisture) * 255.0)\n\tb.ColorIndex = bx | (by << 8)\n\tbyId[id] = b\n\treturn b\n}\n\nfunc clamp(x, l, h float64) float64 {\n\tif x < l {\n\t\treturn l\n\t}\n\tif x > h {\n\t\treturn h\n\t}\n\treturn x\n}\n\nfunc init() {\n\tfor i := range byId {\n\t\tif byId[i] == nil {\n\t\t\tbyId[i] = Invalid\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package core\n\n\/\/ transfer2go data core module, request implementation\n\/\/ Author: Valentin Kuznetsov <vkuznet@gmail.com>\n\nimport (\n\t\"bytes\"\n\t\"container\/heap\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/vkuznet\/transfer2go\/utils\"\n)\n\n\/\/ AgentStatus data type\ntype AgentStatus struct {\n\tUrl       string            `json:\"url\"`      \/\/ agent url\n\tName      string            `json:\"name\"`     \/\/ agent name or alias\n\tTimeStamp int64             `json:\"ts\"`       \/\/ time stamp\n\tCatalog   string            `json:\"catalog\"`  \/\/ underlying TFC catalog\n\tProtocol  string            `json:\"protocol\"` \/\/ underlying transfer protocol\n\tBackend   string            `json:\"backend\"`  \/\/ underlying transfer backend\n\tTool      string            `json:\"tool\"`     \/\/ underlying transfer tool, e.g. xrdcp\n\tToolOpts  string            `json:\"toolopts\"` \/\/ options for backend tool\n\tAgents    map[string]string `json:\"agents\"`   \/\/ list of known agents\n\tAddrs     []string          `json:\"addrs\"`    \/\/ list of all IP addresses\n\tMetrics   map[string]int64  `json:\"metrics\"`  \/\/ agent metrics\n}\n\n\/\/ Processor is an object who process' given task\n\/\/ The logic of the Processor should be implemented.\ntype Processor struct {\n}\n\n\/\/ Request interface defines a task process\ntype Request interface {\n\tProcess(*TransferRequest) error\n}\n\n\/\/ RequestFunc is a function type that implements the Request interface\ntype RequestFunc func(*TransferRequest) error\n\n\/\/ Decorator wraps a request with extra behavior\ntype Decorator func(Request) Request\n\n\/\/ DefaultProcessor is a default processor instance\nvar DefaultProcessor = &Processor{}\n\n\/\/ String provides string representation of given agent status\nfunc (a *AgentStatus) String() string {\n\treturn fmt.Sprintf(\"<Agent name=%s url=%s catalog=%s protocol=%s backend=%s tool=%s toolOpts=%s agents=%v addrs=%v metrics(%v)>\", a.Name, a.Url, a.Catalog, a.Protocol, a.Backend, a.Tool, a.ToolOpts, a.Agents, a.Addrs, a.Metrics)\n}\n\n\/\/ Process defines execution process for a given task\nfunc (e *Processor) Process(t *TransferRequest) error {\n\treturn nil\n}\n\n\/\/ Process is a method of TransferRequest\nfunc (f RequestFunc) Process(t *TransferRequest) error {\n\treturn f(t)\n}\n\n\/\/ filleTransferRequest creates HTTP request to transfer a given file name\n\/\/ https:\/\/matt.aimonetti.net\/posts\/2013\/07\/01\/golang-multipart-file-upload-example\/\nfunc fileTransferRequest(c CatalogEntry, tr *TransferRequest) (*http.Request, error) {\n\tfile, err := os.Open(c.Pfn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\tbody := &bytes.Buffer{}\n\twriter := multipart.NewWriter(body)\n\tpart, err := writer.CreateFormFile(\"data\", filepath.Base(c.Pfn))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = io.Copy(part, file)\n\terr = writer.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\turl := fmt.Sprintf(\"%s\/upload\", tr.DstUrl)\n\treq, err := http.NewRequest(\"POST\", url, body)\n\treq.Header.Set(\"Content-Type\", writer.FormDataContentType())\n\treq.Header.Set(\"Pfn\", c.Pfn)\n\treq.Header.Set(\"Lfn\", c.Lfn)\n\treq.Header.Set(\"Bytes\", fmt.Sprintf(\"%d\", c.Bytes))\n\treq.Header.Set(\"Hash\", c.Hash)\n\treq.Header.Set(\"Src\", tr.SrcAlias)\n\treq.Header.Set(\"Dst\", tr.DstAlias)\n\treturn req, err\n}\n\n\/\/ helper function to perform transfer via HTTP protocol\nfunc httpTransfer(c CatalogEntry, t *TransferRequest) (string, error) {\n\t\/\/ create file transfer request\n\trequest, err := fileTransferRequest(c, t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tclient := utils.HttpClient()\n\tresp, err := client.Do(request)\n\tdefer resp.Body.Close()\n\n\tvar r CatalogEntry\n\terr = json.NewDecoder(resp.Body).Decode(&r)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn r.Pfn, nil\n}\n\n\/\/ Store returns a Decorator that stores request\nfunc Store() Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\tt.Id = time.Now().Unix()\n\t\t\titem := &Item{\n\t\t\t\tValue:    *t,\n\t\t\t\tpriority: t.Priority,\n\t\t\t}\n\t\t\tfmt.Println(*t)\n\t\t\terr := TFC.InsertRequest(*t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\theap.Push(&RequestQueue, item)\n\t\t\t}\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"Request\": t,\n\t\t\t}).Println(\"Request Saved\")\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Delete returns a Decorator that deletes request from heap\nfunc Delete() Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\t\/\/ Delete request from PriorityQueue. The complexity is O(n) where n = heap.Len()\n\t\t\tindex := -1\n\t\t\tvar err error\n\n\t\t\tfor _, item := range RequestQueue {\n\t\t\t\tif item.Value.Id == t.Id {\n\t\t\t\t\tindex = item.index\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif index < RequestQueue.Len() && index >= 0 {\n\t\t\t\terr = TFC.UpdateRequest(t.Id, \"deleted\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Status = \"error\"\n\t\t\t\t\treturn err\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ TODO: May be we need to add lock over here.\n\t\t\t\t\theap.Remove(&RequestQueue, index)\n\t\t\t\t\tt.Status = \"deleted\"\n\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\"Request\": t,\n\t\t\t\t\t}).Println(\"Request Deleted\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tt.Status = \"error\"\n\t\t\t\terr = errors.New(\"Can't find request in heap\")\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Transfer returns a Decorator that performs request transfers by pull model\nfunc PullTransfer() Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"Request\": t.String(),\n\t\t\t}).Println(\"Request Transfer\")\n\t\t\t\/\/ obtain information about source and destination agents\n\t\t\turl := fmt.Sprintf(\"%s\/status\", t.DstUrl)\n\t\t\tresp := utils.FetchResponse(url, []byte{})\n\t\t\tif resp.Error != nil {\n\t\t\t\treturn resp.Error\n\t\t\t}\n\t\t\tvar dstAgent AgentStatus\n\t\t\terr := json.Unmarshal(resp.Data, &dstAgent)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\turl = fmt.Sprintf(\"%s\/status\", t.SrcUrl)\n\t\t\tresp = utils.FetchResponse(url, []byte{})\n\t\t\tif resp.Error != nil {\n\t\t\t\treturn resp.Error\n\t\t\t}\n\t\t\tvar srcAgent AgentStatus\n\t\t\terr = json.Unmarshal(resp.Data, &srcAgent)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t\/\/ if both are up then send acknowledge message to destination on \/pullack url.\n\t\t\tbody, err := json.Marshal(t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\turl = fmt.Sprintf(\"%s\/pull\", t.DstUrl)\n\t\t\tresp = utils.FetchResponse(url, body)\n\t\t\t\/\/ check return status code\n\t\t\tif resp.StatusCode != 200 {\n\t\t\t\treturn fmt.Errorf(\"Response %s, error=%s\", resp.Status, string(resp.Data))\n\t\t\t}\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Transfer returns a Decorator that performs request transfers\nfunc PushTransfer() Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"Request\": t.String(),\n\t\t\t}).Println(\"Request Transfer\")\n\t\t\tvar records []CatalogEntry\n\t\t\t\/\/ Consider those requests which are failed in previous iteration.\n\t\t\t\/\/ If it is nil then request must be passing through first iteration.\n\t\t\tif t.FailedRecords != nil {\n\t\t\t\trecords = t.FailedRecords\n\t\t\t} else {\n\t\t\t\trecords = TFC.Records(*t)\n\t\t\t}\n\t\t\tif len(records) == 0 {\n\t\t\t\t\/\/ file does not exists in TFC, nothing to do, return immediately\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"TransferRequest\": t,\n\t\t\t\t}).Warn(\"Does not match anything in TFC of this agent\\n\", t)\n\t\t\t\treturn r.Process(t)\n\t\t\t}\n\t\t\t\/\/ obtain information about source and destination agents\n\t\t\turl := fmt.Sprintf(\"%s\/status\", t.DstUrl)\n\t\t\tresp := utils.FetchResponse(url, []byte{})\n\t\t\tif resp.Error != nil {\n\t\t\t\treturn resp.Error\n\t\t\t}\n\t\t\tvar dstAgent AgentStatus\n\t\t\terr := json.Unmarshal(resp.Data, &dstAgent)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\turl = fmt.Sprintf(\"%s\/status\", t.SrcUrl)\n\t\t\tresp = utils.FetchResponse(url, []byte{})\n\t\t\tif resp.Error != nil {\n\t\t\t\treturn resp.Error\n\t\t\t}\n\t\t\tvar srcAgent AgentStatus\n\t\t\terr = json.Unmarshal(resp.Data, &srcAgent)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ TODO: I need to implement bulk transfer for all files in found records\n\t\t\t\/\/ so far I loop over them individually and transfer one by one\n\t\t\tvar trRecords []CatalogEntry \/\/ list of successfully transferred records\n\t\t\tvar failedRecords []CatalogEntry\n\t\t\t\/\/ Overwrite the previous error status\n\t\t\tt.Status = \"\"\n\t\t\tfor _, rec := range records {\n\n\t\t\t\ttime0 := time.Now().Unix()\n\n\t\t\t\tAgentMetrics.Bytes.Inc(rec.Bytes)\n\n\t\t\t\t\/\/ if protocol is not given use default one: HTTP\n\t\t\t\tvar rpfn string \/\/ remote PFN\n\t\t\t\tif srcAgent.Protocol == \"\" || srcAgent.Protocol == \"http\" {\n\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\"dstAgent\": dstAgent.String(),\n\t\t\t\t\t}).Println(\"Transfer via HTTP protocol to\", dstAgent.String())\n\t\t\t\t\trpfn, err = httpTransfer(rec, t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\t\"TransferRequest\": t.String(),\n\t\t\t\t\t\t\t\"Record\":          rec.String(),\n\t\t\t\t\t\t\t\"Err\":             err,\n\t\t\t\t\t\t}).Error(\"Transfer\", rec.String(), t.String(), err)\n\t\t\t\t\t\tt.Status = err.Error()\n\t\t\t\t\t\tfailedRecords = append(failedRecords, rec)\n\t\t\t\t\t\tcontinue \/\/ if we fail on single record we continue with others\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ construct remote PFN by using destination agent backend and record LFN\n\t\t\t\t\trpfn = fmt.Sprintf(\"%s%s\", dstAgent.Backend, rec.Lfn)\n\t\t\t\t\t\/\/ perform transfer with the help of backend tool\n\t\t\t\t\tvar cmd *exec.Cmd\n\t\t\t\t\tif srcAgent.ToolOpts == \"\" {\n\t\t\t\t\t\tcmd = exec.Command(srcAgent.Tool, rec.Pfn, rpfn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcmd = exec.Command(srcAgent.Tool, srcAgent.ToolOpts, rec.Pfn, rpfn)\n\t\t\t\t\t}\n\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\"Command\": cmd,\n\t\t\t\t\t}).Println(\"Transfer command\")\n\t\t\t\t\terr = cmd.Run()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\t\"Tool\":         srcAgent.Tool,\n\t\t\t\t\t\t\t\"Tool options\": srcAgent.ToolOpts,\n\t\t\t\t\t\t\t\"PFN\":          rec.Pfn,\n\t\t\t\t\t\t\t\"Remote PFN\":   rpfn,\n\t\t\t\t\t\t\t\"Err\":          err,\n\t\t\t\t\t\t}).Error(\"Transfer\")\n\t\t\t\t\t\tt.Status = err.Error()\n\t\t\t\t\t\tfailedRecords = append(failedRecords, rec)\n\t\t\t\t\t\tcontinue \/\/ if we fail on single record we continue with others\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tr := CatalogEntry{Dataset: rec.Dataset, Block: rec.Block, Lfn: rec.Lfn, Pfn: rpfn, Bytes: rec.Bytes, Hash: rec.Hash, TransferTime: (time.Now().Unix() - time0), Timestamp: time.Now().Unix()}\n\t\t\t\ttrRecords = append(trRecords, r)\n\n\t\t\t\t\/\/ record how much we transferred\n\t\t\t\tAgentMetrics.TotalBytes.Inc(r.Bytes) \/\/ keep growing\n\t\t\t\tAgentMetrics.Total.Inc(1)            \/\/ keep growing\n\t\t\t\tAgentMetrics.Bytes.Dec(rec.Bytes)    \/\/ decrement since we're done\n\n\t\t\t}\n\t\t\t\/\/ Add entry for remote TFC after transfer is completed\n\t\t\turl = fmt.Sprintf(\"%s\/tfc\", t.DstUrl)\n\t\t\td, e := json.Marshal(trRecords)\n\t\t\tif e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\t\tresp = utils.FetchResponse(url, d) \/\/ POST request\n\t\t\tif resp.Error != nil {\n\t\t\t\treturn resp.Error\n\t\t\t}\n\t\t\tt.FailedRecords = failedRecords\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Logging returns a Decorator that logs client requests\nfunc Logging(l *log.Logger) Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\tl.Println(\"TransferRequest\", t)\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Pause returns a Decorator that pauses request for a given time interval\nfunc Pause(interval time.Duration) Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\tif interval > 0 {\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"Request\":  t,\n\t\t\t\t\t\"Interval\": interval,\n\t\t\t\t}).Println(\"TransferRequest is paused by\")\n\t\t\t\ttime.Sleep(interval)\n\t\t\t}\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Tracer returns a Decorator that traces given request\nfunc Tracer() Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"TransferRequest\": t,\n\t\t\t}).Println(\"Trace\")\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Decorate decorates a Request r with all given Decorators\nfunc Decorate(r Request, ds ...Decorator) Request {\n\tdecorated := r\n\tfor _, decorate := range ds {\n\t\tdecorated = decorate(decorated)\n\t}\n\treturn decorated\n}\n<commit_msg>Do chunck wise transfer<commit_after>package core\n\n\/\/ transfer2go data core module, request implementation\n\/\/ Author: Valentin Kuznetsov <vkuznet@gmail.com>\n\nimport (\n\t\"container\/heap\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/vkuznet\/transfer2go\/utils\"\n)\n\n\/\/ AgentStatus data type\ntype AgentStatus struct {\n\tUrl       string            `json:\"url\"`      \/\/ agent url\n\tName      string            `json:\"name\"`     \/\/ agent name or alias\n\tTimeStamp int64             `json:\"ts\"`       \/\/ time stamp\n\tCatalog   string            `json:\"catalog\"`  \/\/ underlying TFC catalog\n\tProtocol  string            `json:\"protocol\"` \/\/ underlying transfer protocol\n\tBackend   string            `json:\"backend\"`  \/\/ underlying transfer backend\n\tTool      string            `json:\"tool\"`     \/\/ underlying transfer tool, e.g. xrdcp\n\tToolOpts  string            `json:\"toolopts\"` \/\/ options for backend tool\n\tAgents    map[string]string `json:\"agents\"`   \/\/ list of known agents\n\tAddrs     []string          `json:\"addrs\"`    \/\/ list of all IP addresses\n\tMetrics   map[string]int64  `json:\"metrics\"`  \/\/ agent metrics\n}\n\n\/\/ Processor is an object who process' given task\n\/\/ The logic of the Processor should be implemented.\ntype Processor struct {\n}\n\n\/\/ Request interface defines a task process\ntype Request interface {\n\tProcess(*TransferRequest) error\n}\n\n\/\/ RequestFunc is a function type that implements the Request interface\ntype RequestFunc func(*TransferRequest) error\n\n\/\/ Decorator wraps a request with extra behavior\ntype Decorator func(Request) Request\n\n\/\/ DefaultProcessor is a default processor instance\nvar DefaultProcessor = &Processor{}\n\n\/\/ String provides string representation of given agent status\nfunc (a *AgentStatus) String() string {\n\treturn fmt.Sprintf(\"<Agent name=%s url=%s catalog=%s protocol=%s backend=%s tool=%s toolOpts=%s agents=%v addrs=%v metrics(%v)>\", a.Name, a.Url, a.Catalog, a.Protocol, a.Backend, a.Tool, a.ToolOpts, a.Agents, a.Addrs, a.Metrics)\n}\n\n\/\/ Process defines execution process for a given task\nfunc (e *Processor) Process(t *TransferRequest) error {\n\treturn nil\n}\n\n\/\/ Process is a method of TransferRequest\nfunc (f RequestFunc) Process(t *TransferRequest) error {\n\treturn f(t)\n}\n\n\/\/ filleTransferRequest creates HTTP request to transfer a given file name\n\/\/ https:\/\/matt.aimonetti.net\/posts\/2013\/07\/01\/golang-multipart-file-upload-example\/\nfunc fileTransferRequest(c CatalogEntry, tr *TransferRequest) (*http.Response, error) {\n\tfile, err := os.Open(c.Pfn)\n\tdefer file.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpipeOut, pipeIn := io.Pipe()\n\twriter := multipart.NewWriter(pipeIn)\n\t\/\/ do the request concurrently\n\tvar resp *http.Response\n\tdone := make(chan error)\n\tgo func() {\n\t\t\/\/ prepare request\n\t\turl := fmt.Sprintf(\"%s\/upload\", tr.DstUrl)\n\t\treq, err := http.NewRequest(\"POST\", url, pipeOut)\n\t\tif err != nil {\n\t\t\tdone <- err\n\t\t\treturn\n\t\t}\n\n\t\treq.Header.Set(\"Content-Type\", writer.FormDataContentType())\n\t\treq.Header.Set(\"Pfn\", c.Pfn)\n\t\treq.Header.Set(\"Lfn\", c.Lfn)\n\t\treq.Header.Set(\"Bytes\", fmt.Sprintf(\"%d\", c.Bytes))\n\t\treq.Header.Set(\"Hash\", c.Hash)\n\t\treq.Header.Set(\"Src\", tr.SrcAlias)\n\t\treq.Header.Set(\"Dst\", tr.DstAlias)\n\t\treq.Header.Set(\"Content-Type\", writer.FormDataContentType())\n\t\tclient := utils.HttpClient()\n\t\tresp, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tdone <- err\n\t\t\treturn\n\t\t}\n\n\t\tdone <- nil\n\t}()\n\n\tpart, err := writer.CreateFormFile(\"data\", filepath.Base(c.Pfn))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = io.Copy(part, file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = writer.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = pipeIn.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\n\terr = <-done\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}\n\n\/\/ helper function to perform transfer via HTTP protocol\nfunc httpTransfer(c CatalogEntry, t *TransferRequest) (string, error) {\n\t\/\/ create file transfer request\n\tresp, err := fileTransferRequest(c, t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar r CatalogEntry\n\terr = json.NewDecoder(resp.Body).Decode(&r)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn r.Pfn, nil\n}\n\n\/\/ Store returns a Decorator that stores request\nfunc Store() Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\tt.Id = time.Now().Unix()\n\t\t\titem := &Item{\n\t\t\t\tValue:    *t,\n\t\t\t\tpriority: t.Priority,\n\t\t\t}\n\t\t\tfmt.Println(*t)\n\t\t\terr := TFC.InsertRequest(*t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\theap.Push(&RequestQueue, item)\n\t\t\t}\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"Request\": t,\n\t\t\t}).Println(\"Request Saved\")\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Delete returns a Decorator that deletes request from heap\nfunc Delete() Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\t\/\/ Delete request from PriorityQueue. The complexity is O(n) where n = heap.Len()\n\t\t\tindex := -1\n\t\t\tvar err error\n\n\t\t\tfor _, item := range RequestQueue {\n\t\t\t\tif item.Value.Id == t.Id {\n\t\t\t\t\tindex = item.index\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif index < RequestQueue.Len() && index >= 0 {\n\t\t\t\terr = TFC.UpdateRequest(t.Id, \"deleted\")\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Status = \"error\"\n\t\t\t\t\treturn err\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ TODO: May be we need to add lock over here.\n\t\t\t\t\theap.Remove(&RequestQueue, index)\n\t\t\t\t\tt.Status = \"deleted\"\n\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\"Request\": t,\n\t\t\t\t\t}).Println(\"Request Deleted\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tt.Status = \"error\"\n\t\t\t\terr = errors.New(\"Can't find request in heap\")\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Transfer returns a Decorator that performs request transfers by pull model\nfunc PullTransfer() Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"Request\": t.String(),\n\t\t\t}).Println(\"Request Transfer\")\n\t\t\t\/\/ obtain information about source and destination agents\n\t\t\turl := fmt.Sprintf(\"%s\/status\", t.DstUrl)\n\t\t\tresp := utils.FetchResponse(url, []byte{})\n\t\t\tif resp.Error != nil {\n\t\t\t\treturn resp.Error\n\t\t\t}\n\t\t\tvar dstAgent AgentStatus\n\t\t\terr := json.Unmarshal(resp.Data, &dstAgent)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\turl = fmt.Sprintf(\"%s\/status\", t.SrcUrl)\n\t\t\tresp = utils.FetchResponse(url, []byte{})\n\t\t\tif resp.Error != nil {\n\t\t\t\treturn resp.Error\n\t\t\t}\n\t\t\tvar srcAgent AgentStatus\n\t\t\terr = json.Unmarshal(resp.Data, &srcAgent)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t\/\/ if both are up then send acknowledge message to destination on \/pullack url.\n\t\t\tbody, err := json.Marshal(t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\turl = fmt.Sprintf(\"%s\/pull\", t.DstUrl)\n\t\t\tresp = utils.FetchResponse(url, body)\n\t\t\t\/\/ check return status code\n\t\t\tif resp.StatusCode != 200 {\n\t\t\t\treturn fmt.Errorf(\"Response %s, error=%s\", resp.Status, string(resp.Data))\n\t\t\t}\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Transfer returns a Decorator that performs request transfers\nfunc PushTransfer() Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"Request\": t.String(),\n\t\t\t}).Println(\"Request Transfer\")\n\t\t\tvar records []CatalogEntry\n\t\t\t\/\/ Consider those requests which are failed in previous iteration.\n\t\t\t\/\/ If it is nil then request must be passing through first iteration.\n\t\t\tif t.FailedRecords != nil {\n\t\t\t\trecords = t.FailedRecords\n\t\t\t} else {\n\t\t\t\trecords = TFC.Records(*t)\n\t\t\t}\n\t\t\tif len(records) == 0 {\n\t\t\t\t\/\/ file does not exists in TFC, nothing to do, return immediately\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"TransferRequest\": t,\n\t\t\t\t}).Warn(\"Does not match anything in TFC of this agent\\n\", t)\n\t\t\t\treturn r.Process(t)\n\t\t\t}\n\t\t\t\/\/ obtain information about source and destination agents\n\t\t\turl := fmt.Sprintf(\"%s\/status\", t.DstUrl)\n\t\t\tresp := utils.FetchResponse(url, []byte{})\n\t\t\tif resp.Error != nil {\n\t\t\t\treturn resp.Error\n\t\t\t}\n\t\t\tvar dstAgent AgentStatus\n\t\t\terr := json.Unmarshal(resp.Data, &dstAgent)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\turl = fmt.Sprintf(\"%s\/status\", t.SrcUrl)\n\t\t\tresp = utils.FetchResponse(url, []byte{})\n\t\t\tif resp.Error != nil {\n\t\t\t\treturn resp.Error\n\t\t\t}\n\t\t\tvar srcAgent AgentStatus\n\t\t\terr = json.Unmarshal(resp.Data, &srcAgent)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ TODO: I need to implement bulk transfer for all files in found records\n\t\t\t\/\/ so far I loop over them individually and transfer one by one\n\t\t\tvar trRecords []CatalogEntry \/\/ list of successfully transferred records\n\t\t\tvar failedRecords []CatalogEntry\n\t\t\t\/\/ Overwrite the previous error status\n\t\t\tt.Status = \"\"\n\t\t\tfor _, rec := range records {\n\n\t\t\t\ttime0 := time.Now().Unix()\n\n\t\t\t\tAgentMetrics.Bytes.Inc(rec.Bytes)\n\n\t\t\t\t\/\/ if protocol is not given use default one: HTTP\n\t\t\t\tvar rpfn string \/\/ remote PFN\n\t\t\t\tif srcAgent.Protocol == \"\" || srcAgent.Protocol == \"http\" {\n\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\"dstAgent\": dstAgent.String(),\n\t\t\t\t\t}).Println(\"Transfer via HTTP protocol to\", dstAgent.String())\n\t\t\t\t\trpfn, err = httpTransfer(rec, t)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\t\"TransferRequest\": t.String(),\n\t\t\t\t\t\t\t\"Record\":          rec.String(),\n\t\t\t\t\t\t\t\"Err\":             err,\n\t\t\t\t\t\t}).Error(\"Transfer\", rec.String(), t.String(), err)\n\t\t\t\t\t\tt.Status = err.Error()\n\t\t\t\t\t\tfailedRecords = append(failedRecords, rec)\n\t\t\t\t\t\tcontinue \/\/ if we fail on single record we continue with others\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ construct remote PFN by using destination agent backend and record LFN\n\t\t\t\t\trpfn = fmt.Sprintf(\"%s%s\", dstAgent.Backend, rec.Lfn)\n\t\t\t\t\t\/\/ perform transfer with the help of backend tool\n\t\t\t\t\tvar cmd *exec.Cmd\n\t\t\t\t\tif srcAgent.ToolOpts == \"\" {\n\t\t\t\t\t\tcmd = exec.Command(srcAgent.Tool, rec.Pfn, rpfn)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcmd = exec.Command(srcAgent.Tool, srcAgent.ToolOpts, rec.Pfn, rpfn)\n\t\t\t\t\t}\n\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\"Command\": cmd,\n\t\t\t\t\t}).Println(\"Transfer command\")\n\t\t\t\t\terr = cmd.Run()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\t\"Tool\":         srcAgent.Tool,\n\t\t\t\t\t\t\t\"Tool options\": srcAgent.ToolOpts,\n\t\t\t\t\t\t\t\"PFN\":          rec.Pfn,\n\t\t\t\t\t\t\t\"Remote PFN\":   rpfn,\n\t\t\t\t\t\t\t\"Err\":          err,\n\t\t\t\t\t\t}).Error(\"Transfer\")\n\t\t\t\t\t\tt.Status = err.Error()\n\t\t\t\t\t\tfailedRecords = append(failedRecords, rec)\n\t\t\t\t\t\tcontinue \/\/ if we fail on single record we continue with others\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tr := CatalogEntry{Dataset: rec.Dataset, Block: rec.Block, Lfn: rec.Lfn, Pfn: rpfn, Bytes: rec.Bytes, Hash: rec.Hash, TransferTime: (time.Now().Unix() - time0), Timestamp: time.Now().Unix()}\n\t\t\t\ttrRecords = append(trRecords, r)\n\n\t\t\t\t\/\/ record how much we transferred\n\t\t\t\tAgentMetrics.TotalBytes.Inc(r.Bytes) \/\/ keep growing\n\t\t\t\tAgentMetrics.Total.Inc(1)            \/\/ keep growing\n\t\t\t\tAgentMetrics.Bytes.Dec(rec.Bytes)    \/\/ decrement since we're done\n\n\t\t\t}\n\t\t\t\/\/ Add entry for remote TFC after transfer is completed\n\t\t\turl = fmt.Sprintf(\"%s\/tfc\", t.DstUrl)\n\t\t\td, e := json.Marshal(trRecords)\n\t\t\tif e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\t\tresp = utils.FetchResponse(url, d) \/\/ POST request\n\t\t\tif resp.Error != nil {\n\t\t\t\treturn resp.Error\n\t\t\t}\n\t\t\tt.FailedRecords = failedRecords\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Logging returns a Decorator that logs client requests\nfunc Logging(l *log.Logger) Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\tl.Println(\"TransferRequest\", t)\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Pause returns a Decorator that pauses request for a given time interval\nfunc Pause(interval time.Duration) Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\tif interval > 0 {\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"Request\":  t,\n\t\t\t\t\t\"Interval\": interval,\n\t\t\t\t}).Println(\"TransferRequest is paused by\")\n\t\t\t\ttime.Sleep(interval)\n\t\t\t}\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Tracer returns a Decorator that traces given request\nfunc Tracer() Decorator {\n\treturn func(r Request) Request {\n\t\treturn RequestFunc(func(t *TransferRequest) error {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"TransferRequest\": t,\n\t\t\t}).Println(\"Trace\")\n\t\t\treturn r.Process(t)\n\t\t})\n\t}\n}\n\n\/\/ Decorate decorates a Request r with all given Decorators\nfunc Decorate(r Request, ds ...Decorator) Request {\n\tdecorated := r\n\tfor _, decorate := range ds {\n\t\tdecorated = decorate(decorated)\n\t}\n\treturn decorated\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2020 DSR Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage types\n\nimport (\n\t\"encoding\/json\"\n\n\tsdk \"github.com\/cosmos\/cosmos-sdk\/types\"\n\tsdkerrors \"github.com\/cosmos\/cosmos-sdk\/types\/errors\"\n\tauthtypes \"github.com\/cosmos\/cosmos-sdk\/x\/auth\/types\"\n)\n\n\/*\n\tAccount Role\n*\/\n\ntype AccountRole string\n\nconst (\n\tVendor              AccountRole = \"Vendor\"\n\tCertificationCenter AccountRole = \"CertificationCenter\"\n\tTrustee             AccountRole = \"Trustee\"\n\tNodeAdmin           AccountRole = \"NodeAdmin\"\n)\n\nvar Roles = AccountRoles{Vendor, CertificationCenter, Trustee, NodeAdmin}\n\nfunc (role AccountRole) Validate() error {\n\tfor _, r := range Roles {\n\t\tif role == r {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, \"Invalid Account Role: %v. Supported roles: [%v]\", role, Roles)\n}\n\n\/*\n\tList of Account Roles\n*\/\n\ntype AccountRoles []AccountRole\n\n\/*\n\tAccount\n*\/\n\ntype DCLAccountI interface {\n\tauthtypes.AccountI\n\n\tGetRoles() []AccountRole\n\tGetVendorID() int32\n\tGetApprovals() []*Grant\n}\n\n\/\/ NewAccount creates a new Account object.\nfunc NewAccount(ba *authtypes.BaseAccount, roles AccountRoles, approvals []*Grant, vendorID int32) *Account {\n\treturn &Account{\n\t\tBaseAccount: ba,\n\t\tRoles:       roles,\n\t\tApprovals:   approvals,\n\t\tVendorID:    vendorID,\n\t}\n}\n\n\/\/ Validate checks for errors on the vesting and module account parameters.\nfunc (acc Account) Validate() error {\n\terr := acc.BaseAccount.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, role := range acc.Roles {\n\t\tif err := role.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ If creating an account with Vendor Role, we need to have a associated VendorID\n\tif acc.HasRole(Vendor) && acc.VendorID <= 0 {\n\t\treturn ErrMissingVendorIDForVendorAccount()\n\t}\n\n\treturn nil\n}\n\nfunc (acc Account) GetRoles() []AccountRole {\n\treturn acc.Roles\n}\n\nfunc (acc Account) GetApprovals() []*Grant {\n\treturn acc.Approvals\n}\n\nfunc (acc Account) GetVendorID() int32 {\n\treturn acc.VendorID\n}\n\nfunc (acc Account) HasRole(targetRole AccountRole) bool {\n\tfor _, role := range acc.Roles {\n\t\tif role == targetRole {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (acc Account) String() string {\n\tout, _ := acc.MarshalYAML()\n\treturn out.(string)\n}\n\n\/*\n\tPending Account\n*\/\n\n\/\/ NewPendingAccount creates a new PendingAccount object.\nfunc NewPendingAccount(acc *Account, approval sdk.AccAddress, info string, time int64) *PendingAccount {\n\tpendingAccount := &PendingAccount{\n\t\tAccount: acc,\n\t}\n\n\tpendingAccount.Approvals = []*Grant{\n\t\t{\n\t\t\tAddress: approval.String(),\n\t\t\tTime:    time,\n\t\t\tInfo:    info,\n\t\t},\n\t}\n\n\treturn pendingAccount\n}\n\nfunc (acc PendingAccount) HasApprovalFrom(address sdk.AccAddress) bool {\n\taddrStr := address.String()\n\tfor _, approval := range acc.Approvals {\n\t\tif approval.Address == addrStr {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/*\n\tPending Account Revocation\n*\/\n\n\/\/ NewPendingAccountRevocation creates a new PendingAccountRevocation object.\nfunc NewPendingAccountRevocation(address sdk.AccAddress,\n\tinfo string, time int64, approval sdk.AccAddress) PendingAccountRevocation {\n\tpendingAccountRevocation := PendingAccountRevocation{\n\t\tAddress: address.String(),\n\t}\n\tpendingAccountRevocation.Approvals = []*Grant{\n\t\t{\n\t\t\tAddress: approval.String(),\n\t\t\tTime:    time,\n\t\t\tInfo:    info,\n\t\t},\n\t}\n\treturn pendingAccountRevocation\n}\n\n\/\/ String implements fmt.Stringer.\nfunc (revoc PendingAccountRevocation) String() string {\n\tbytes, err := json.Marshal(revoc)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn string(bytes)\n}\n\n\/\/ Validate checks for errors on the vesting and module account parameters.\nfunc (revoc PendingAccountRevocation) Validate() error {\n\tif revoc.Address == \"\" {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest,\n\t\t\t\"Invalid Pending Account Revocation: Value: %s. Error: Missing Address\", revoc.Address,\n\t\t)\n\t}\n\n\treturn nil\n}\n\nfunc (revoc PendingAccountRevocation) HasRevocationFrom(address sdk.AccAddress) bool {\n\taddrStr := address.String()\n\tfor _, approvals := range revoc.Approvals {\n\t\tif approvals.Address == addrStr {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n<commit_msg>Add function for creating a new object type of RevokedAccount<commit_after>\/\/ Copyright 2020 DSR Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage types\n\nimport (\n\t\"encoding\/json\"\n\n\tsdk \"github.com\/cosmos\/cosmos-sdk\/types\"\n\tsdkerrors \"github.com\/cosmos\/cosmos-sdk\/types\/errors\"\n\tauthtypes \"github.com\/cosmos\/cosmos-sdk\/x\/auth\/types\"\n)\n\n\/*\n\tAccount Role\n*\/\n\ntype AccountRole string\n\nconst (\n\tVendor              AccountRole = \"Vendor\"\n\tCertificationCenter AccountRole = \"CertificationCenter\"\n\tTrustee             AccountRole = \"Trustee\"\n\tNodeAdmin           AccountRole = \"NodeAdmin\"\n)\n\nvar Roles = AccountRoles{Vendor, CertificationCenter, Trustee, NodeAdmin}\n\nfunc (role AccountRole) Validate() error {\n\tfor _, r := range Roles {\n\t\tif role == r {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, \"Invalid Account Role: %v. Supported roles: [%v]\", role, Roles)\n}\n\n\/*\n\tList of Account Roles\n*\/\n\ntype AccountRoles []AccountRole\n\n\/*\n\tAccount\n*\/\n\ntype DCLAccountI interface {\n\tauthtypes.AccountI\n\n\tGetRoles() []AccountRole\n\tGetVendorID() int32\n\tGetApprovals() []*Grant\n}\n\n\/\/ NewAccount creates a new Account object.\nfunc NewAccount(ba *authtypes.BaseAccount, roles AccountRoles, approvals []*Grant, vendorID int32) *Account {\n\treturn &Account{\n\t\tBaseAccount: ba,\n\t\tRoles:       roles,\n\t\tApprovals:   approvals,\n\t\tVendorID:    vendorID,\n\t}\n}\n\n\/\/ Validate checks for errors on the vesting and module account parameters.\nfunc (acc Account) Validate() error {\n\terr := acc.BaseAccount.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, role := range acc.Roles {\n\t\tif err := role.Validate(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ If creating an account with Vendor Role, we need to have a associated VendorID\n\tif acc.HasRole(Vendor) && acc.VendorID <= 0 {\n\t\treturn ErrMissingVendorIDForVendorAccount()\n\t}\n\n\treturn nil\n}\n\nfunc (acc Account) GetRoles() []AccountRole {\n\treturn acc.Roles\n}\n\nfunc (acc Account) GetApprovals() []*Grant {\n\treturn acc.Approvals\n}\n\nfunc (acc Account) GetVendorID() int32 {\n\treturn acc.VendorID\n}\n\nfunc (acc Account) HasRole(targetRole AccountRole) bool {\n\tfor _, role := range acc.Roles {\n\t\tif role == targetRole {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (acc Account) String() string {\n\tout, _ := acc.MarshalYAML()\n\treturn out.(string)\n}\n\n\/*\n\tPending Account\n*\/\n\n\/\/ NewPendingAccount creates a new PendingAccount object.\nfunc NewPendingAccount(acc *Account, approval sdk.AccAddress, info string, time int64) *PendingAccount {\n\tpendingAccount := &PendingAccount{\n\t\tAccount: acc,\n\t}\n\n\tpendingAccount.Approvals = []*Grant{\n\t\t{\n\t\t\tAddress: approval.String(),\n\t\t\tTime:    time,\n\t\t\tInfo:    info,\n\t\t},\n\t}\n\n\treturn pendingAccount\n}\n\nfunc (acc PendingAccount) HasApprovalFrom(address sdk.AccAddress) bool {\n\taddrStr := address.String()\n\tfor _, approval := range acc.Approvals {\n\t\tif approval.Address == addrStr {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/*\n\tPending Account Revocation\n*\/\n\n\/\/ NewPendingAccountRevocation creates a new PendingAccountRevocation object.\nfunc NewPendingAccountRevocation(address sdk.AccAddress,\n\tinfo string, time int64, approval sdk.AccAddress) PendingAccountRevocation {\n\tpendingAccountRevocation := PendingAccountRevocation{\n\t\tAddress: address.String(),\n\t}\n\tpendingAccountRevocation.Approvals = []*Grant{\n\t\t{\n\t\t\tAddress: approval.String(),\n\t\t\tTime:    time,\n\t\t\tInfo:    info,\n\t\t},\n\t}\n\treturn pendingAccountRevocation\n}\n\n\/\/ NewRevokedAccount creates a new RevokedAccount object\nfunc NewRevokedAccount(acc *Account, approvals []*Grant, info string, time int64) *RevokedAccount {\n\trevokedAccount := &RevokedAccount{\n\t\tAccount: acc,\n\t}\n\n\trevokedAccount.RevokeApprovals = approvals\n\n\treturn revokedAccount\n}\n\n\/\/ String implements fmt.Stringer.\nfunc (revoc PendingAccountRevocation) String() string {\n\tbytes, err := json.Marshal(revoc)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn string(bytes)\n}\n\n\/\/ Validate checks for errors on the vesting and module account parameters.\nfunc (revoc PendingAccountRevocation) Validate() error {\n\tif revoc.Address == \"\" {\n\t\treturn sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest,\n\t\t\t\"Invalid Pending Account Revocation: Value: %s. Error: Missing Address\", revoc.Address,\n\t\t)\n\t}\n\n\treturn nil\n}\n\nfunc (revoc PendingAccountRevocation) HasRevocationFrom(address sdk.AccAddress) bool {\n\taddrStr := address.String()\n\tfor _, approvals := range revoc.Approvals {\n\t\tif approvals.Address == addrStr {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage manual\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\tgc \"launchpad.net\/gocheck\"\n\n\tenvtesting \"launchpad.net\/juju-core\/environs\/testing\"\n\t\"launchpad.net\/juju-core\/instance\"\n\t\"launchpad.net\/juju-core\/juju\/testing\"\n\t\"launchpad.net\/juju-core\/state\/api\/params\"\n\tjc \"launchpad.net\/juju-core\/testing\/checkers\"\n\t\"launchpad.net\/juju-core\/version\"\n)\n\ntype provisionerSuite struct {\n\ttesting.JujuConnSuite\n}\n\nvar _ = gc.Suite(&provisionerSuite{})\n\nfunc (s *provisionerSuite) getArgs(c *gc.C) ProvisionMachineArgs {\n\thostname, err := os.Hostname()\n\tc.Assert(err, gc.IsNil)\n\treturn ProvisionMachineArgs{\n\t\tHost:    hostname,\n\t\tEnvName: \"dummyenv\",\n\t}\n}\n\nfunc (s *provisionerSuite) TestProvisionMachine(c *gc.C) {\n\tconst series = \"precise\"\n\tconst arch = \"amd64\"\n\n\targs := s.getArgs(c)\n\thostname := args.Host\n\targs.Host = \"ubuntu@\" + args.Host\n\n\tenvtesting.RemoveTools(c, s.Conn.Environ.Storage())\n\tdefer fakeSSH{\n\t\tSeries: series, Arch: arch, SkipProvisionAgent: true,\n\t}.install(c).Restore()\n\t\/\/ Attempt to provision a machine with no tools available, expect it to fail.\n\tmachineId, err := ProvisionMachine(args)\n\tc.Assert(err, jc.Satisfies, params.IsCodeNotFound)\n\tc.Assert(machineId, gc.Equals, \"\")\n\n\tcfg := s.Conn.Environ.Config()\n\tnumber, ok := cfg.AgentVersion()\n\tc.Assert(ok, jc.IsTrue)\n\tbinVersion := version.Binary{number, series, arch}\n\tenvtesting.AssertUploadFakeToolsVersions(c, s.Conn.Environ.Storage(), binVersion)\n\n\tfor i, errorCode := range []int{255, 0} {\n\t\tc.Logf(\"test %d: code %d\", i, errorCode)\n\t\tdefer fakeSSH{\n\t\t\tSeries: series,\n\t\t\tArch:   arch,\n\t\t\tProvisionAgentExitCode: errorCode,\n\t\t}.install(c).Restore()\n\t\tmachineId, err = ProvisionMachine(args)\n\t\tif errorCode != 0 {\n\t\t\tc.Assert(err, gc.ErrorMatches, fmt.Sprintf(\"exit status %d\", errorCode))\n\t\t\tc.Assert(machineId, gc.Equals, \"\")\n\t\t} else {\n\t\t\tc.Assert(err, gc.IsNil)\n\t\t\tc.Assert(machineId, gc.Not(gc.Equals), \"\")\n\t\t\t\/\/ machine ID will be incremented. Even though we failed and the\n\t\t\t\/\/ machine is removed, the ID is not reused.\n\t\t\tc.Assert(machineId, gc.Equals, fmt.Sprint(i+1))\n\t\t\tm, err := s.State.Machine(machineId)\n\t\t\tc.Assert(err, gc.IsNil)\n\t\t\tinstanceId, err := m.InstanceId()\n\t\t\tc.Assert(err, gc.IsNil)\n\t\t\tc.Assert(instanceId, gc.Equals, instance.Id(\"manual:\"+hostname))\n\t\t}\n\t}\n\n\t\/\/ Attempting to provision a machine twice should fail. We effect\n\t\/\/ this by checking for existing juju upstart configurations.\n\tdefer installFakeSSH(c, \"\", \"\/etc\/init\/jujud-machine-0.conf\", 0)()\n\t_, err = ProvisionMachine(args)\n\tc.Assert(err, gc.Equals, ErrProvisioned)\n\tdefer installFakeSSH(c, \"\", \"\/etc\/init\/jujud-machine-0.conf\", 255)()\n\t_, err = ProvisionMachine(args)\n\tc.Assert(err, gc.ErrorMatches, \"error checking if provisioned: exit status 255\")\n}\n<commit_msg>[r=axwalk] environs\/manual: add test for API\/State info<commit_after>\/\/ Copyright 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage manual\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\tgc \"launchpad.net\/gocheck\"\n\n\tenvtesting \"launchpad.net\/juju-core\/environs\/testing\"\n\t\"launchpad.net\/juju-core\/instance\"\n\t\"launchpad.net\/juju-core\/juju\/testing\"\n\t\"launchpad.net\/juju-core\/state\"\n\t\"launchpad.net\/juju-core\/state\/api\/params\"\n\tjc \"launchpad.net\/juju-core\/testing\/checkers\"\n\t\"launchpad.net\/juju-core\/version\"\n)\n\ntype provisionerSuite struct {\n\ttesting.JujuConnSuite\n}\n\nvar _ = gc.Suite(&provisionerSuite{})\n\nfunc (s *provisionerSuite) getArgs(c *gc.C) ProvisionMachineArgs {\n\thostname, err := os.Hostname()\n\tc.Assert(err, gc.IsNil)\n\treturn ProvisionMachineArgs{\n\t\tHost:    hostname,\n\t\tEnvName: \"dummyenv\",\n\t}\n}\n\nfunc (s *provisionerSuite) TestProvisionMachine(c *gc.C) {\n\tconst series = \"precise\"\n\tconst arch = \"amd64\"\n\n\targs := s.getArgs(c)\n\thostname := args.Host\n\targs.Host = \"ubuntu@\" + args.Host\n\n\tenvtesting.RemoveTools(c, s.Conn.Environ.Storage())\n\tdefer fakeSSH{\n\t\tSeries: series, Arch: arch, SkipProvisionAgent: true,\n\t}.install(c).Restore()\n\t\/\/ Attempt to provision a machine with no tools available, expect it to fail.\n\tmachineId, err := ProvisionMachine(args)\n\tc.Assert(err, jc.Satisfies, params.IsCodeNotFound)\n\tc.Assert(machineId, gc.Equals, \"\")\n\n\tcfg := s.Conn.Environ.Config()\n\tnumber, ok := cfg.AgentVersion()\n\tc.Assert(ok, jc.IsTrue)\n\tbinVersion := version.Binary{number, series, arch}\n\tenvtesting.AssertUploadFakeToolsVersions(c, s.Conn.Environ.Storage(), binVersion)\n\n\tfor i, errorCode := range []int{255, 0} {\n\t\tc.Logf(\"test %d: code %d\", i, errorCode)\n\t\tdefer fakeSSH{\n\t\t\tSeries: series,\n\t\t\tArch:   arch,\n\t\t\tProvisionAgentExitCode: errorCode,\n\t\t}.install(c).Restore()\n\t\tmachineId, err = ProvisionMachine(args)\n\t\tif errorCode != 0 {\n\t\t\tc.Assert(err, gc.ErrorMatches, fmt.Sprintf(\"exit status %d\", errorCode))\n\t\t\tc.Assert(machineId, gc.Equals, \"\")\n\t\t} else {\n\t\t\tc.Assert(err, gc.IsNil)\n\t\t\tc.Assert(machineId, gc.Not(gc.Equals), \"\")\n\t\t\t\/\/ machine ID will be incremented. Even though we failed and the\n\t\t\t\/\/ machine is removed, the ID is not reused.\n\t\t\tc.Assert(machineId, gc.Equals, fmt.Sprint(i+1))\n\t\t\tm, err := s.State.Machine(machineId)\n\t\t\tc.Assert(err, gc.IsNil)\n\t\t\tinstanceId, err := m.InstanceId()\n\t\t\tc.Assert(err, gc.IsNil)\n\t\t\tc.Assert(instanceId, gc.Equals, instance.Id(\"manual:\"+hostname))\n\t\t}\n\t}\n\n\t\/\/ Attempting to provision a machine twice should fail. We effect\n\t\/\/ this by checking for existing juju upstart configurations.\n\tdefer installFakeSSH(c, \"\", \"\/etc\/init\/jujud-machine-0.conf\", 0)()\n\t_, err = ProvisionMachine(args)\n\tc.Assert(err, gc.Equals, ErrProvisioned)\n\tdefer installFakeSSH(c, \"\", \"\/etc\/init\/jujud-machine-0.conf\", 255)()\n\t_, err = ProvisionMachine(args)\n\tc.Assert(err, gc.ErrorMatches, \"error checking if provisioned: exit status 255\")\n}\n\nfunc (s *provisionerSuite) TestCreateMachineConfig(c *gc.C) {\n\tconst series = \"precise\"\n\tconst arch = \"amd64\"\n\tdefer fakeSSH{Series: series, Arch: arch}.install(c).Restore()\n\tmachineId, err := ProvisionMachine(s.getArgs(c))\n\tc.Assert(err, gc.IsNil)\n\n\t\/\/ Now check what we would've configured it with.\n\tclient := s.APIConn.State.Client()\n\tmcfg, err := createMachineConfig(client, machineId, series, arch, state.BootstrapNonce, \"\/var\/lib\/juju\")\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(mcfg, gc.NotNil)\n\tc.Assert(mcfg.APIInfo, gc.NotNil)\n\tc.Assert(mcfg.StateInfo, gc.NotNil)\n\n\tstateInfo, apiInfo, err := s.APIConn.Environ.StateInfo()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(mcfg.APIInfo.Addrs, gc.DeepEquals, apiInfo.Addrs)\n\tc.Assert(mcfg.StateInfo.Addrs, gc.DeepEquals, stateInfo.Addrs)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Written in Go 2015 by Eric Lagergren (contact@ericlagergren.com)\n   Written in C 2014 by Sebastiano Vigna (vigna@acm.org) and\n   Kenji Rikitake (kenji.rikitake@acm.org).\n\nTo the extent possible under law, the author has dedicated all copyright\nand related and neighboring rights to this software to the public domain\nworldwide. This software is distributed without any warranty.\n\nSee <http:\/\/creativecommons.org\/publicdomain\/zero\/1.0\/>. *\/\npackage prng\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/binary\"\n\t\"io\"\n)\n\n\/\/ Guarenteed to be fair using a dice roll.\nconst randSeed = 16256612229375771919\n\ntype XORShift interface {\n\tNext() uint64\n\tSeed()\n}\n\n\/\/ randUint reads from the OS' crypto PRNG and uses its output\n\/\/ to create a slice of uint64s with the given lenght, n.\nfunc randUint(n int) []uint64 {\n\ts := make([]uint64, n)\n\n\t\/\/ Fill the array the user gave us but make sure there aren't any zeros.\n\tfor i := 0; i < n; i++ {\n\t\ts[i] = randomNonZero()\n\t}\n\n\treturn s\n}\n\n\/\/ randomNonZero fetches 8 bytes from the OS' CSPRNG and returns it as\n\/\/ a non-zero uint64. Will panic if it can't read from rand.Reader.\nfunc randomNonZero() uint64 {\n\tbuf := make([]byte, 8)\n\tn, err := io.ReadFull(rand.Reader, buf)\n\tif err != nil || n != 8 {\n\t\tpanic(\"Unable to fully read from rand.Reader\")\n\t}\n\tu, x := binary.Uvarint(buf)\n\tif u == 0 || x == 0 || x < 0 {\n\t\treturn randomNonZero()\n\t}\n\treturn u\n}\n\n\/\/ fillWithXOR fills a slice using a xorshift64 generator, using a\n\/\/ determined starting state (a large prime).\nfunc fillWithXOR(n int) []uint64 {\n\ts := make([]uint64, n)\n\tr := new(Shift64Star)\n\tr.x = randSeed\n\tfor i := range s {\n\t\ts[i] = r.Next()\n\t}\n\treturn s\n}\n\n\/\/ genState generates a starting state using Go's 'crypto\/rand'\n\/\/ package. The state will be a 64-bit prime. It'll panic if\n\/\/ rand.Prime returns an error.\nfunc genState() uint64 {\n\tprime, err := rand.Prime(rand.Reader, 64)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn prime.Uint64()\n}\n\nconst uint58mask uint64 = (1 << 58) - 1\n\n\/\/ Shift116Plus is a variant of xorshift128+ for dynamic languages, such\n\/\/ as Erlang, that can use only 58 bits of a 64-bit integer. Only the lower\n\/\/ 58 bits of each state word are valid (the upper six are zeroes).\n\/\/\n\/\/ This generator passes BigCrush without systematic failures, but due to\n\/\/ the relatively short period it is acceptable only for applications with\n\/\/ a mild amount of parallelism; otherwise, use a xorshift1024* generator.\n\/\/\n\/\/ The state must be seeded so that the lower 58 bits of s[ 0 ] and s[ 1 ]\n\/\/ are not all zeroes. If you have a nonzero 64-bit seed, we suggest to\n\/\/ pass it twice through MurmurHash3's avalanching function and take the\n\/\/ lower 58 bits, taking care that they are not all zeroes (you can apply\n\/\/ the avalanching function again if this happens).\ntype Shift116Plus struct {\n\tstate [2]uint64\n}\n\nfunc (s *Shift116Plus) Next() uint64 {\n\ts0 := s.state[1]\n\ts1 := s.state[0]\n\ts.state[0] = s0\n\ts1 ^= (s1 << 24) & uint58mask \/\/ a\n\ts.state[1] = (s1 ^ s0 ^ (s1 >> 11) ^ (s0 >> 41))\n\treturn (((s.state[1]) + s0) & uint58mask) \/\/ b, c\n}\n\nfunc (s *Shift116Plus) Seed() {\n\tcopy(s.state[:], randUint(cap(s.state)))\n}\n\n\/\/ Shift128Plus is the fastest generator passing BigCrush without\n\/\/ systematic failures, but due to the relatively short period it is\n\/\/ acceptable only for applications with a mild amount of parallelism;\n\/\/ otherwise, use a xorshift1024* generator.\n\/\/\n\/\/ The state must be seeded so that it is not everywhere zero. If you have\n\/\/ a nonzero 64-bit seed, we suggest to pass it twice through\n\/\/ MurmurHash3's avalanching function.\ntype Shift128Plus struct {\n\tstate [2]uint64\n}\n\nfunc (s *Shift128Plus) Next() uint64 {\n\ts0 := s.state[1]\n\ts1 := s.state[0]\n\ts.state[0] = s0\n\ts1 ^= s1 << 23 \/\/ a\n\ts.state[1] = (s1 ^ s0 ^ (s1 >> 17) ^ (s0 >> 26))\n\treturn (s.state[1]) + s0 \/\/ b, c\n}\n\nfunc (s *Shift128Plus) Seed() {\n\tcopy(s.state[:], randUint(cap(s.state)))\n}\n\n\/\/ Shift1024Star is a fast, top-quality generator. If 1024 bits of state are\n\/\/ too much, try a xorshift128+ or generator.\n\/\/\n\/\/ The state must be seeded so that it is not everywhere zero. If you have\n\/\/ a 64-bit seed,  we suggest to seed a xorshift64* generator and use its\n\/\/ output to fill s.\ntype Shift1024Star struct {\n\tstate [16]uint64\n\tp     int\n}\n\nfunc (s *Shift1024Star) Next() uint64 {\n\ts0 := s.state[s.p]\n\ts.p = (s.p + 1) & 15\n\ts1 := s.state[s.p]\n\ts1 ^= s1 << 31\n\ts1 ^= s1 >> 11\n\ts0 ^= s0 >> 30\n\ts.state[s.p] = s0 ^ s1\n\treturn s.state[s.p] * 1181783497276652981\n}\n\nfunc (s *Shift1024Star) Seed() {\n\tcopy(s.state[:], fillWithXOR(cap(s.state)))\n\ts.p = 0\n}\n\n\/\/ Shift40956 is usable, but we suggest you use a\n\/\/ xorshift1024* generator.\n\/\/\n\/\/ The state must be seeded so that it is not everywhere zero. If you have\n\/\/ a 64-bit seed,  we suggest to seed a xorshift64* generator and use its\n\/\/ output to fill s.\ntype Shift4096Star struct {\n\tstate [64]uint64\n\tp     int\n}\n\nfunc (s *Shift4096Star) Next() uint64 {\n\ts0 := s.state[s.p]\n\ts.p = (s.p + 1) & 63\n\ts1 := s.state[s.p]\n\ts1 ^= s1 << 25 \/\/ a\n\ts1 ^= s1 >> 3  \/\/ b\n\ts0 ^= s0 >> 49 \/\/ c\n\ts.state[s.p] = s0 ^ s1\n\treturn (s.state[s.p]) * 8372773778140471301\n}\n\nfunc (s *Shift4096Star) Seed() {\n\tcopy(s.state[:], fillWithXOR(cap(s.state)))\n\ts.p = 0\n}\n\n\/\/ Shift64Star is a fast, good generator if you're short on memory, but\n\/\/ otherwise we rather suggest to use a xorshift128+ or xorshift1024*\n\/\/ (for a very long period) generator.\ntype Shift64Star struct {\n\tx uint64 \/\/ state\n}\n\nfunc (s *Shift64Star) Next() uint64 {\n\ts.x ^= s.x >> 12 \/\/ a\n\ts.x ^= s.x << 25 \/\/ b\n\ts.x ^= s.x >> 27 \/\/ c\n\treturn s.x * 2685821657736338717\n}\n\nfunc (s *Shift64Star) Seed() {\n\ts.x = genState()\n}\n<commit_msg>better seeding<commit_after>\/*\n   Written in Go 2015 by Eric Lagergren (contact@ericlagergren.com)\n   Written in C 2014 by Sebastiano Vigna (vigna@acm.org) and\n   Kenji Rikitake (kenji.rikitake@acm.org).\n\nTo the extent possible under law, the author has dedicated all copyright\nand related and neighboring rights to this software to the public domain\nworldwide. This software is distributed without any warranty.\n\nSee <http:\/\/creativecommons.org\/publicdomain\/zero\/1.0\/>. *\/\npackage prng\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/binary\"\n\t\"io\"\n)\n\ntype XORShift interface {\n\tNext() uint64\n\tSeed()\n}\n\n\/\/ randUint reads from the OS' crypto PRNG and uses its output\n\/\/ to create a slice of uint64s with the given lenght, n.\nfunc randUint(n int) []uint64 {\n\ts := make([]uint64, n)\n\n\t\/\/ Fill the array the user gave us but make sure there aren't any zeros.\n\tfor i := 0; i < n; i++ {\n\t\ts[i] = randomNonZero()\n\t}\n\n\treturn s\n}\n\n\/\/ randomNonZero fetches 8 bytes from the OS' CSPRNG and returns it as\n\/\/ a non-zero uint64. Will panic if it can't read from rand.Reader.\nfunc randomNonZero() uint64 {\n\tbuf := make([]byte, 8)\n\tn, err := io.ReadFull(rand.Reader, buf)\n\tif err != nil || n != 8 {\n\t\tpanic(\"Unable to fully read from rand.Reader\")\n\t}\n\tu, x := binary.Uvarint(buf)\n\tif u == 0 || x == 0 || x < 0 {\n\t\treturn randomNonZero()\n\t}\n\treturn u\n}\n\n\/\/ genState generates a starting state using Go's 'crypto\/rand'\n\/\/ package. The state will be a 64-bit prime. It'll panic if\n\/\/ rand.Prime returns an error.\nfunc genState() uint64 {\n\tprime, err := rand.Prime(rand.Reader, 64)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn prime.Uint64()\n}\n\nconst uint58mask uint64 = (1 << 58) - 1\n\n\/\/ Shift116Plus is a variant of xorshift128+ for dynamic languages, such\n\/\/ as Erlang, that can use only 58 bits of a 64-bit integer. Only the lower\n\/\/ 58 bits of each state word are valid (the upper six are zeroes).\n\/\/\n\/\/ This generator passes BigCrush without systematic failures, but due to\n\/\/ the relatively short period it is acceptable only for applications with\n\/\/ a mild amount of parallelism; otherwise, use a xorshift1024* generator.\n\/\/\n\/\/ The state must be seeded so that the lower 58 bits of s[ 0 ] and s[ 1 ]\n\/\/ are not all zeroes. If you have a nonzero 64-bit seed, we suggest to\n\/\/ pass it twice through MurmurHash3's avalanching function and take the\n\/\/ lower 58 bits, taking care that they are not all zeroes (you can apply\n\/\/ the avalanching function again if this happens).\ntype Shift116Plus struct {\n\tstate [2]uint64\n}\n\nfunc (s *Shift116Plus) Next() uint64 {\n\ts0 := s.state[1]\n\ts1 := s.state[0]\n\ts.state[0] = s0\n\ts1 ^= (s1 << 24) & uint58mask \/\/ a\n\ts.state[1] = (s1 ^ s0 ^ (s1 >> 11) ^ (s0 >> 41))\n\treturn (((s.state[1]) + s0) & uint58mask) \/\/ b, c\n}\n\nfunc (s *Shift116Plus) Seed() {\n\tcopy(s.state[:], randUint(cap(s.state)))\n}\n\n\/\/ Shift128Plus is the fastest generator passing BigCrush without\n\/\/ systematic failures, but due to the relatively short period it is\n\/\/ acceptable only for applications with a mild amount of parallelism;\n\/\/ otherwise, use a xorshift1024* generator.\n\/\/\n\/\/ The state must be seeded so that it is not everywhere zero. If you have\n\/\/ a nonzero 64-bit seed, we suggest to pass it twice through\n\/\/ MurmurHash3's avalanching function.\ntype Shift128Plus struct {\n\tstate [2]uint64\n}\n\nfunc (s *Shift128Plus) Next() uint64 {\n\ts0 := s.state[1]\n\ts1 := s.state[0]\n\ts.state[0] = s0\n\ts1 ^= s1 << 23 \/\/ a\n\ts.state[1] = (s1 ^ s0 ^ (s1 >> 17) ^ (s0 >> 26))\n\treturn (s.state[1]) + s0 \/\/ b, c\n}\n\nfunc (s *Shift128Plus) Seed() {\n\tcopy(s.state[:], randUint(cap(s.state)))\n}\n\n\/\/ Shift1024Star is a fast, top-quality generator. If 1024 bits of state are\n\/\/ too much, try a xorshift128+ or generator.\n\/\/\n\/\/ The state must be seeded so that it is not everywhere zero. If you have\n\/\/ a 64-bit seed,  we suggest to seed a xorshift64* generator and use its\n\/\/ output to fill s.\ntype Shift1024Star struct {\n\tstate [16]uint64\n\tp     int\n}\n\nfunc (s *Shift1024Star) Next() uint64 {\n\ts0 := s.state[s.p]\n\ts.p = (s.p + 1) & 15\n\ts1 := s.state[s.p]\n\ts1 ^= s1 << 31\n\ts1 ^= s1 >> 11\n\ts0 ^= s0 >> 30\n\ts.state[s.p] = s0 ^ s1\n\treturn s.state[s.p] * 1181783497276652981\n}\n\nfunc (s *Shift1024Star) Seed() {\n\tcopy(s.state[:], randUint(cap(s.state)))\n\ts.p = 0\n}\n\n\/\/ Shift40956 is usable, but we suggest you use a\n\/\/ xorshift1024* generator.\n\/\/\n\/\/ The state must be seeded so that it is not everywhere zero. If you have\n\/\/ a 64-bit seed,  we suggest to seed a xorshift64* generator and use its\n\/\/ output to fill s.\ntype Shift4096Star struct {\n\tstate [64]uint64\n\tp     int\n}\n\nfunc (s *Shift4096Star) Next() uint64 {\n\ts0 := s.state[s.p]\n\ts.p = (s.p + 1) & 63\n\ts1 := s.state[s.p]\n\ts1 ^= s1 << 25 \/\/ a\n\ts1 ^= s1 >> 3  \/\/ b\n\ts0 ^= s0 >> 49 \/\/ c\n\ts.state[s.p] = s0 ^ s1\n\treturn (s.state[s.p]) * 8372773778140471301\n}\n\nfunc (s *Shift4096Star) Seed() {\n\tcopy(s.state[:], randUint(cap(s.state)))\n\ts.p = 0\n}\n\n\/\/ Shift64Star is a fast, good generator if you're short on memory, but\n\/\/ otherwise we rather suggest to use a xorshift128+ or xorshift1024*\n\/\/ (for a very long period) generator.\ntype Shift64Star struct {\n\tx uint64 \/\/ state\n}\n\nfunc (s *Shift64Star) Next() uint64 {\n\ts.x ^= s.x >> 12 \/\/ a\n\ts.x ^= s.x << 25 \/\/ b\n\ts.x ^= s.x >> 27 \/\/ c\n\treturn s.x * 2685821657736338717\n}\n\nfunc (s *Shift64Star) Seed() {\n\ts.x = genState()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\tMQTT \"git.eclipse.org\/gitroot\/paho\/org.eclipse.paho.mqtt.golang.git\"\n\t\"github.com\/PandoCloud\/pando-cloud\/pkg\/protocol\"\n\t\"github.com\/PandoCloud\/pando-cloud\/pkg\/tlv\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tcommonCmdGetStatus = uint16(65528)\n)\n\n\/\/ device register args\ntype DeviceRegisterArgs struct {\n\tProductKey string `json:\"product_key\"  binding:\"required\"`\n\tDeviceCode string `json:\"device_code\"  binding:\"required\"`\n\tVersion    string `json:\"version\"  binding:\"required\"`\n}\n\n\/\/ device authentication args\ntype DeviceAuthArgs struct {\n\tDeviceId     int64  `json:\"device_id\" binding:\"required\"`\n\tDeviceSecret string `json:\"device_secret\" binding:\"required\"`\n\tProtocol     string `json:\"protocol\" binding:\"required\"`\n}\n\n\/\/ common response fields\ntype Common struct {\n\tCode    int    `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\n\/\/ device register response data field\ntype DeviceRegisterData struct {\n\tDeviceId         int64  `json:\"device_id\"`\n\tDeviceSecret     string `json:\"device_secret\"`\n\tDeviceKey        string `json:\"device_key\"`\n\tDeviceIdentifier string `json:\"device_identifier\"`\n}\n\n\/\/ device register response\ntype DeviceRegisterResponse struct {\n\tCommon\n\tData DeviceRegisterData `json:\"data\"`\n}\n\n\/\/ device auth response data field\ntype DeviceAuthData struct {\n\tAccessToken string `json:\"access_token\"`\n\tAccessAddr  string `json:\"access_addr\"`\n}\n\n\/\/ device auth response\ntype DeviceAuthResponse struct {\n\tCommon\n\tData DeviceAuthData `json:\"data\"`\n}\n\ntype Device struct {\n\t\/\/ API URL\n\tUrl string\n\n\t\/\/ basic info\n\tProductKey string\n\tDeviceCode string\n\tVersion    string\n\n\t\/\/ private things\n\tid      int64\n\tsecrect string\n\ttoken   []byte\n\taccess  string\n}\n\nfunc NewDevice(url string, productkey string, code string, version string) *Device {\n\n\treturn &Device{\n\t\tUrl:        url,\n\t\tProductKey: productkey,\n\t\tDeviceCode: code,\n\t\tVersion:    version,\n\t}\n}\n\nfunc (d *Device) DoRegister() error {\n\targs := DeviceRegisterArgs{\n\t\tProductKey: d.ProductKey,\n\t\tDeviceCode: d.DeviceCode,\n\t\tVersion:    d.Version,\n\t}\n\tregUrl := fmt.Sprintf(\"%v%v\", d.Url, \"\/v1\/devices\/registration\")\n\trequest, err := json.Marshal(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjsonresp, err := SendHttpRequest(regUrl, string(request), \"POST\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresponse := DeviceRegisterResponse{}\n\terr = json.Unmarshal(jsonresp, &response)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = CheckHttpsCode(response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.id = response.Data.DeviceId\n\td.secrect = response.Data.DeviceSecret\n\n\treturn nil\n}\n\nfunc (d *Device) DoLogin() error {\n\targs := DeviceAuthArgs{\n\t\tDeviceId:     d.id,\n\t\tDeviceSecret: d.secrect,\n\t\tProtocol:     \"mqtt\",\n\t}\n\tregUrl := fmt.Sprintf(\"%v%v\", d.Url, \"\/v1\/devices\/authentication\")\n\trequest, err := json.Marshal(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjsonresp, err := SendHttpRequest(regUrl, string(request), \"POST\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresponse := DeviceAuthResponse{}\n\terr = json.Unmarshal(jsonresp, &response)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = CheckHttpsCode(response)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ ecode hex\n\thtoken, err := hex.DecodeString(response.Data.AccessToken)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.token = htoken\n\td.access = response.Data.AccessAddr\n\n\treturn nil\n}\n\nfunc (d *Device) reportStatus(client *MQTT.Client) {\n\n\tpayloadHead := protocol.DataHead{\n\t\tFlag:      0,\n\t\tTimestamp: uint64(time.Now().Unix() * 1000),\n\t}\n\tparam := []interface{}{uint8(1)}\n\tparams, err := tlv.MakeTLVs(param)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tsub := protocol.SubData{\n\t\tHead: protocol.SubDataHead{\n\t\t\tSubDeviceid: uint16(1),\n\t\t\tPropertyNum: uint16(1),\n\t\t\tParamsCount: uint16(len(params)),\n\t\t},\n\t\tParams: params,\n\t}\n\n\tstatus := protocol.Data{\n\t\tHead:    payloadHead,\n\t\tSubData: []protocol.SubData{},\n\t}\n\n\tstatus.SubData = append(status.SubData, sub)\n\n\tpayload, err := status.Marshal()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tdeviceid := fmt.Sprint(\"%x\", d.id)\n\tclient.Publish(deviceid+\"\/d\", 1, false, payload)\n\n}\n\nfunc (d *Device) statusHandler(client *MQTT.Client, msg MQTT.Message) {\n\tstatus := protocol.Data{}\n\n\terr := status.UnMarshal(msg.Payload())\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfmt.Println(\"device receiving status set : \")\n\n\tfor _, one := range status.SubData {\n\t\tfmt.Println(\"subdeviceid : \", one.Head.SubDeviceid)\n\t\tfmt.Println(\"no : \", one.Head.PropertyNum)\n\t\tfmt.Println(\"params : \", one.Params)\n\t}\n}\n\nfunc (d *Device) commandHandler(client *MQTT.Client, msg MQTT.Message) {\n\tcmd := protocol.Command{}\n\n\terr := cmd.UnMarshal(msg.Payload())\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tswitch cmd.Head.No {\n\tcase commonCmdGetStatus:\n\t\td.reportStatus(client)\n\tdefault:\n\t\tfmt.Println(\"unsuported command : %v\", cmd.Head.No)\n\t}\n}\n\nfunc (d *Device) messageHandler(client *MQTT.Client, msg MQTT.Message) {\n\tfmt.Printf(\"TOPIC: %s\\n\", msg.Topic())\n\tfmt.Printf(\"MSG: %x\\n\", msg.Payload())\n\ttopicPieces := strings.Split(msg.Topic(), \"\/\")\n\tclientid := topicPieces[0]\n\tmsgtype := topicPieces[1]\n\tfmt.Println(clientid, msgtype)\n\n\tswitch msgtype {\n\tcase \"c\":\n\t\td.commandHandler(client, msg)\n\tcase \"s\":\n\t\td.statusHandler(client, msg)\n\tdefault:\n\t\tfmt.Println(\"unsuported message type :\", msgtype)\n\t}\n}\n\nfunc (d *Device) DoAccess() error {\n\tlogger := log.New(os.Stdout, \"\", log.LstdFlags)\n\tMQTT.ERROR = logger\n\tMQTT.CRITICAL = logger\n\tMQTT.WARN = logger\n\tMQTT.DEBUG = logger\n\n\t\/\/create a ClientOptions struct setting the broker address, clientid, turn\n\t\/\/off trace output and set the default message handler\n\topts := MQTT.NewClientOptions().AddBroker(\"tls:\/\/\" + d.access)\n\tclientid := fmt.Sprintf(\"%x\", d.id)\n\topts.SetClientID(clientid)\n\topts.SetUsername(clientid) \/\/ clientid as username\n\topts.SetPassword(hex.EncodeToString(d.token))\n\topts.SetKeepAlive(30 * time.Second)\n\topts.SetDefaultPublishHandler(d.messageHandler)\n\topts.SetTLSConfig(&tls.Config{Certificates: nil, InsecureSkipVerify: true})\n\n\t\/\/create and start a client using the above ClientOptions\n\tc := MQTT.NewClient(opts)\n\tif token := c.Connect(); token.Wait() && token.Error() != nil {\n\t\treturn token.Error()\n\t}\n\n\t\/\/ we just pause here to wait for messages\n\t<-make(chan int)\n\n\tdefer c.Disconnect(250)\n\n\treturn nil\n}\n<commit_msg>fix test device topic mismatch bug.<commit_after>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"encoding\/hex\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\tMQTT \"git.eclipse.org\/gitroot\/paho\/org.eclipse.paho.mqtt.golang.git\"\n\t\"github.com\/PandoCloud\/pando-cloud\/pkg\/protocol\"\n\t\"github.com\/PandoCloud\/pando-cloud\/pkg\/tlv\"\n\t\"log\"\n\t\"os\"\n\t\"time\"\n)\n\nconst (\n\tcommonCmdGetStatus = uint16(65528)\n)\n\n\/\/ device register args\ntype DeviceRegisterArgs struct {\n\tProductKey string `json:\"product_key\"  binding:\"required\"`\n\tDeviceCode string `json:\"device_code\"  binding:\"required\"`\n\tVersion    string `json:\"version\"  binding:\"required\"`\n}\n\n\/\/ device authentication args\ntype DeviceAuthArgs struct {\n\tDeviceId     int64  `json:\"device_id\" binding:\"required\"`\n\tDeviceSecret string `json:\"device_secret\" binding:\"required\"`\n\tProtocol     string `json:\"protocol\" binding:\"required\"`\n}\n\n\/\/ common response fields\ntype Common struct {\n\tCode    int    `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\n\/\/ device register response data field\ntype DeviceRegisterData struct {\n\tDeviceId         int64  `json:\"device_id\"`\n\tDeviceSecret     string `json:\"device_secret\"`\n\tDeviceKey        string `json:\"device_key\"`\n\tDeviceIdentifier string `json:\"device_identifier\"`\n}\n\n\/\/ device register response\ntype DeviceRegisterResponse struct {\n\tCommon\n\tData DeviceRegisterData `json:\"data\"`\n}\n\n\/\/ device auth response data field\ntype DeviceAuthData struct {\n\tAccessToken string `json:\"access_token\"`\n\tAccessAddr  string `json:\"access_addr\"`\n}\n\n\/\/ device auth response\ntype DeviceAuthResponse struct {\n\tCommon\n\tData DeviceAuthData `json:\"data\"`\n}\n\ntype Device struct {\n\t\/\/ API URL\n\tUrl string\n\n\t\/\/ basic info\n\tProductKey string\n\tDeviceCode string\n\tVersion    string\n\n\t\/\/ private things\n\tid      int64\n\tsecrect string\n\ttoken   []byte\n\taccess  string\n}\n\nfunc NewDevice(url string, productkey string, code string, version string) *Device {\n\n\treturn &Device{\n\t\tUrl:        url,\n\t\tProductKey: productkey,\n\t\tDeviceCode: code,\n\t\tVersion:    version,\n\t}\n}\n\nfunc (d *Device) DoRegister() error {\n\targs := DeviceRegisterArgs{\n\t\tProductKey: d.ProductKey,\n\t\tDeviceCode: d.DeviceCode,\n\t\tVersion:    d.Version,\n\t}\n\tregUrl := fmt.Sprintf(\"%v%v\", d.Url, \"\/v1\/devices\/registration\")\n\trequest, err := json.Marshal(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjsonresp, err := SendHttpRequest(regUrl, string(request), \"POST\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresponse := DeviceRegisterResponse{}\n\terr = json.Unmarshal(jsonresp, &response)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = CheckHttpsCode(response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td.id = response.Data.DeviceId\n\td.secrect = response.Data.DeviceSecret\n\n\treturn nil\n}\n\nfunc (d *Device) DoLogin() error {\n\targs := DeviceAuthArgs{\n\t\tDeviceId:     d.id,\n\t\tDeviceSecret: d.secrect,\n\t\tProtocol:     \"mqtt\",\n\t}\n\tregUrl := fmt.Sprintf(\"%v%v\", d.Url, \"\/v1\/devices\/authentication\")\n\trequest, err := json.Marshal(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjsonresp, err := SendHttpRequest(regUrl, string(request), \"POST\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresponse := DeviceAuthResponse{}\n\terr = json.Unmarshal(jsonresp, &response)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = CheckHttpsCode(response)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ ecode hex\n\thtoken, err := hex.DecodeString(response.Data.AccessToken)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.token = htoken\n\td.access = response.Data.AccessAddr\n\n\treturn nil\n}\n\nfunc (d *Device) reportStatus(client *MQTT.Client) {\n\n\tpayloadHead := protocol.DataHead{\n\t\tFlag:      0,\n\t\tTimestamp: uint64(time.Now().Unix() * 1000),\n\t}\n\tparam := []interface{}{uint8(1)}\n\tparams, err := tlv.MakeTLVs(param)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tsub := protocol.SubData{\n\t\tHead: protocol.SubDataHead{\n\t\t\tSubDeviceid: uint16(1),\n\t\t\tPropertyNum: uint16(1),\n\t\t\tParamsCount: uint16(len(params)),\n\t\t},\n\t\tParams: params,\n\t}\n\n\tstatus := protocol.Data{\n\t\tHead:    payloadHead,\n\t\tSubData: []protocol.SubData{},\n\t}\n\n\tstatus.SubData = append(status.SubData, sub)\n\n\tpayload, err := status.Marshal()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tclient.Publish(\"d\", 1, false, payload)\n\n}\n\nfunc (d *Device) statusHandler(client *MQTT.Client, msg MQTT.Message) {\n\tstatus := protocol.Data{}\n\n\terr := status.UnMarshal(msg.Payload())\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfmt.Println(\"device receiving status set : \")\n\n\tfor _, one := range status.SubData {\n\t\tfmt.Println(\"subdeviceid : \", one.Head.SubDeviceid)\n\t\tfmt.Println(\"no : \", one.Head.PropertyNum)\n\t\tfmt.Println(\"params : \", one.Params)\n\t}\n}\n\nfunc (d *Device) commandHandler(client *MQTT.Client, msg MQTT.Message) {\n\tcmd := protocol.Command{}\n\n\terr := cmd.UnMarshal(msg.Payload())\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tswitch cmd.Head.No {\n\tcase commonCmdGetStatus:\n\t\td.reportStatus(client)\n\tdefault:\n\t\tfmt.Println(\"unsuported command : %v\", cmd.Head.No)\n\t}\n}\n\nfunc (d *Device) messageHandler(client *MQTT.Client, msg MQTT.Message) {\n\tfmt.Printf(\"TOPIC: %s\\n\", msg.Topic())\n\tfmt.Printf(\"MSG: %x\\n\", msg.Payload())\n\tmsgtype := msg.Topic()\n\tfmt.Println(msgtype)\n\n\tswitch msgtype {\n\tcase \"c\":\n\t\td.commandHandler(client, msg)\n\tcase \"s\":\n\t\td.statusHandler(client, msg)\n\tdefault:\n\t\tfmt.Println(\"unsuported message type :\", msgtype)\n\t}\n}\n\nfunc (d *Device) DoAccess() error {\n\tlogger := log.New(os.Stdout, \"\", log.LstdFlags)\n\tMQTT.ERROR = logger\n\tMQTT.CRITICAL = logger\n\tMQTT.WARN = logger\n\tMQTT.DEBUG = logger\n\n\t\/\/create a ClientOptions struct setting the broker address, clientid, turn\n\t\/\/off trace output and set the default message handler\n\topts := MQTT.NewClientOptions().AddBroker(\"tls:\/\/\" + d.access)\n\tclientid := fmt.Sprintf(\"%x\", d.id)\n\topts.SetClientID(clientid)\n\topts.SetUsername(clientid) \/\/ clientid as username\n\topts.SetPassword(hex.EncodeToString(d.token))\n\topts.SetKeepAlive(30 * time.Second)\n\topts.SetDefaultPublishHandler(d.messageHandler)\n\topts.SetTLSConfig(&tls.Config{Certificates: nil, InsecureSkipVerify: true})\n\n\t\/\/create and start a client using the above ClientOptions\n\tc := MQTT.NewClient(opts)\n\tif token := c.Connect(); token.Wait() && token.Error() != nil {\n\t\treturn token.Error()\n\t}\n\n\t\/\/ we just pause here to wait for messages\n\t<-make(chan int)\n\n\tdefer c.Disconnect(250)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"cuckood\"\n\t\"cuckood\/cucache\/text\"\n\t\"encoding\/binary\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\/pprof\"\n\t\"strconv\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\tgomem \"github.com\/dustin\/gomemcached\"\n)\n\nvar c cuckoo.Cuckoo\n\nfunc main() {\n\tcpuprofile := flag.String(\"cpuprofile\", \"\", \"CPU profile output file\")\n\tflag.Parse()\n\n\tc = cuckoo.New()\n\n\tvar pf *os.File\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, os.Interrupt, syscall.SIGABRT)\n\tgo func() {\n\t\tfor s := range sigs {\n\t\t\tif pf != nil {\n\t\t\t\tpprof.StopCPUProfile()\n\t\t\t\terr := pf.Close()\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"could not end cpu profile:\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif s == os.Interrupt {\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar err error\n\tif cpuprofile != nil && *cpuprofile != \"\" {\n\t\tfmt.Println(\"starting CPU profiling\")\n\t\tpf, err = os.Create(*cpuprofile)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"could not create CPU profile file %v: %v\\n\", *cpuprofile, err)\n\t\t\treturn\n\t\t}\n\t\terr = pprof.StartCPUProfile(pf)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"could not start CPU profiling: %v\\n\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tln, err := net.Listen(\"tcp\", \":11211\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor {\n\t\t\tconn, err := ln.Accept()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgo handleConnection(conn)\n\t\t}\n\t}()\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tln, err := net.ListenPacket(\"udp\", \":11211\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor {\n\t\t\tb := make([]byte, 0, 10240)\n\t\t\t_, addr, err := ln.ReadFrom(b)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgo replyTo(b, addr.(*net.UDPAddr))\n\t\t}\n\t}()\n\twg.Wait()\n}\n\nfunc wtf(req gomem.MCRequest, v cuckoo.MemopRes) {\n\tpanic(fmt.Sprintf(\"unexpected result when handling %v: %v\\n\", req.Opcode, v))\n}\n\nfunc tm(i uint32) (t time.Time) {\n\tif i == 0 {\n\t\treturn\n\t}\n\n\tif i < 60*60*24*30 {\n\t\tt = time.Now().Add(time.Duration(i) * time.Second)\n\t} else {\n\t\tt = time.Unix(int64(i), 0)\n\t}\n\treturn\n}\n\nfunc deal(in_ io.Reader, out io.Writer) {\n\tvar getq []*gomem.MCResponse\n\n\tin := bufio.NewReader(in_)\n\tfor {\n\t\tb, err := in.Peek(1)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ TODO print error\n\t\t\treturn\n\t\t}\n\n\t\tisbinary := true\n\t\tvar req gomem.MCRequest\n\t\tvar res gomem.MCResponse\n\t\tif b[0] == gomem.REQ_MAGIC {\n\t\t\t_, err := req.Receive(in, nil)\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t\/\/ TODO: print error\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tres.Opaque = req.Opaque\n\t\t} else {\n\t\t\t\/\/ text protocol fallback\n\t\t\tcmd, err := in.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t\/\/ TODO: print error\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\treq, err = text.ToMCRequest(cmd, in)\n\t\t\tisbinary = false\n\t\t}\n\n\t\tswitch req.Opcode {\n\t\tcase gomem.GET, gomem.GETQ, gomem.GETK, gomem.GETKQ:\n\t\t\tres.Status = gomem.KEY_ENOENT\n\t\t\tv, ok := c.Get(req.Key)\n\t\t\tif ok {\n\t\t\t\tres.Status = gomem.SUCCESS\n\t\t\t\tres.Extras = make([]byte, 4)\n\t\t\t\tbinary.BigEndian.PutUint32(res.Extras, v.Flags)\n\t\t\t\tres.Cas = v.Casid\n\t\t\t\tres.Body = v.Bytes\n\n\t\t\t\tif req.Opcode == gomem.GETK || req.Opcode == gomem.GETKQ {\n\t\t\t\t\tres.Key = req.Key\n\t\t\t\t}\n\t\t\t}\n\t\tcase gomem.SET, gomem.SETQ,\n\t\t\tgomem.ADD, gomem.ADDQ,\n\t\t\tgomem.REPLACE, gomem.REPLACEQ:\n\n\t\t\tflags := binary.BigEndian.Uint32(req.Extras[0:4])\n\t\t\texpiry := tm(binary.BigEndian.Uint32(req.Extras[4:8]))\n\t\t\tvar v cuckoo.MemopRes\n\t\t\tswitch req.Opcode {\n\t\t\tcase gomem.SET, gomem.SETQ:\n\t\t\t\tif req.Cas == 0 {\n\t\t\t\t\tv = c.Set(req.Key, req.Body, flags, expiry)\n\t\t\t\t} else {\n\t\t\t\t\tv = c.CAS(req.Key, req.Body, flags, expiry, req.Cas)\n\t\t\t\t}\n\t\t\tcase gomem.ADD, gomem.ADDQ:\n\t\t\t\tv = c.Add(req.Key, req.Body, flags, expiry)\n\t\t\tcase gomem.REPLACE, gomem.REPLACEQ:\n\t\t\t\tif req.Cas == 0 {\n\t\t\t\t\tv = c.Replace(req.Key, req.Body, flags, expiry)\n\t\t\t\t} else {\n\t\t\t\t\tv = c.CAS(req.Key, req.Body, flags, expiry, req.Cas)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch v.T {\n\t\t\tcase cuckoo.STORED:\n\t\t\t\tres.Status = gomem.SUCCESS\n\t\t\t\tres.Cas = v.V.(uint64)\n\t\t\tcase cuckoo.NOT_STORED:\n\t\t\t\tres.Status = gomem.NOT_STORED\n\t\t\tcase cuckoo.NOT_FOUND:\n\t\t\t\tres.Status = gomem.KEY_ENOENT\n\t\t\tcase cuckoo.EXISTS:\n\t\t\t\tres.Status = gomem.KEY_EEXISTS\n\t\t\tcase cuckoo.SERVER_ERROR:\n\t\t\t\tres.Status = gomem.ENOMEM\n\t\t\t\tfmt.Println(v.V.(error))\n\t\t\tdefault:\n\t\t\t\twtf(req, v)\n\t\t\t}\n\t\tcase gomem.DELETE, gomem.DELETEQ:\n\t\t\tv := c.Delete(req.Key, req.Cas)\n\n\t\t\tswitch v.T {\n\t\t\tcase cuckoo.STORED:\n\t\t\t\tres.Status = gomem.SUCCESS\n\t\t\tcase cuckoo.NOT_FOUND:\n\t\t\t\tres.Status = gomem.KEY_ENOENT\n\t\t\tcase cuckoo.EXISTS:\n\t\t\t\tres.Status = gomem.KEY_EEXISTS\n\t\t\tdefault:\n\t\t\t\twtf(req, v)\n\t\t\t}\n\t\tcase gomem.INCREMENT, gomem.INCREMENTQ,\n\t\t\tgomem.DECREMENT, gomem.DECREMENTQ:\n\n\t\t\tby := binary.BigEndian.Uint64(req.Extras[0:8])\n\t\t\tdef := binary.BigEndian.Uint64(req.Extras[8:16])\n\t\t\texp := tm(binary.BigEndian.Uint32(req.Extras[16:20]))\n\n\t\t\tif binary.BigEndian.Uint32(req.Extras[16:20]) == 0xffffffff {\n\t\t\t\texp = time.Unix(math.MaxInt64, 0)\n\t\t\t}\n\n\t\t\tvar v cuckoo.MemopRes\n\t\t\tif req.Opcode == gomem.INCREMENT || req.Opcode == gomem.INCREMENTQ {\n\t\t\t\tv = c.Incr(req.Key, by, def, exp)\n\t\t\t} else {\n\t\t\t\tv = c.Decr(req.Key, by, def, exp)\n\t\t\t}\n\n\t\t\tswitch v.T {\n\t\t\tcase cuckoo.STORED:\n\t\t\t\tres.Status = gomem.SUCCESS\n\t\t\t\tcv := v.V.(cuckoo.CasVal)\n\t\t\t\tres.Cas = cv.Casid\n\t\t\t\tres.Body = make([]byte, 8)\n\t\t\t\tbinary.BigEndian.PutUint64(res.Body, cv.NewVal)\n\t\t\tcase cuckoo.CLIENT_ERROR:\n\t\t\t\tres.Status = gomem.DELTA_BADVAL\n\t\t\tcase cuckoo.NOT_FOUND:\n\t\t\t\tres.Status = gomem.KEY_ENOENT\n\t\t\tdefault:\n\t\t\t\twtf(req, v)\n\t\t\t}\n\t\tcase gomem.QUIT, gomem.QUITQ:\n\t\t\treturn\n\t\tcase gomem.FLUSH, gomem.FLUSHQ:\n\t\t\t\/\/ TODO: handle optional \"now\" argument\n\t\t\t\/\/ TODO: this is probably terrible\n\t\t\tc = cuckoo.New()\n\t\t\tres.Status = gomem.SUCCESS\n\t\tcase gomem.NOOP:\n\t\t\tres.Status = gomem.SUCCESS\n\t\tcase gomem.VERSION:\n\t\t\tres.Status = gomem.SUCCESS\n\t\t\t\/\/ TODO: res.Body =\n\t\tcase gomem.APPEND, gomem.APPENDQ,\n\t\t\tgomem.PREPEND, gomem.PREPENDQ:\n\n\t\t\tvar v cuckoo.MemopRes\n\t\t\tswitch req.Opcode {\n\t\t\tcase gomem.APPEND, gomem.APPENDQ:\n\t\t\t\tv = c.Append(req.Key, req.Body, req.Cas)\n\t\t\tcase gomem.PREPEND, gomem.PREPENDQ:\n\t\t\t\tv = c.Prepend(req.Key, req.Body, req.Cas)\n\t\t\t}\n\n\t\t\tswitch v.T {\n\t\t\tcase cuckoo.STORED:\n\t\t\t\tres.Status = gomem.SUCCESS\n\t\t\tcase cuckoo.EXISTS:\n\t\t\t\tres.Status = gomem.KEY_EEXISTS\n\t\t\tcase cuckoo.NOT_FOUND:\n\t\t\t\tres.Status = gomem.KEY_ENOENT\n\t\t\tdefault:\n\t\t\t\twtf(req, v)\n\t\t\t}\n\t\tdefault:\n\t\t\tres.Status = gomem.UNKNOWN_COMMAND\n\t\t}\n\n\t\tif req.Opcode.IsQuiet() && res.Status == gomem.SUCCESS {\n\t\t\tif req.Opcode == gomem.GETQ || req.Opcode == gomem.GETKQ {\n\t\t\t\tgetq = append(getq, &res)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif (req.Opcode == gomem.GETQ || req.Opcode == gomem.GETKQ) && res.Status == gomem.KEY_ENOENT {\n\t\t\t\/\/ no warning on cache miss\n\t\t\tcontinue\n\t\t}\n\n\t\tif res.Status != gomem.SUCCESS {\n\t\t\tif !(res.Status == gomem.KEY_ENOENT && (req.Opcode == gomem.GET || req.Opcode == gomem.GETK)) {\n\t\t\t\tfmt.Println(req.Opcode, res.Status)\n\t\t\t}\n\t\t}\n\n\t\tif isbinary {\n\t\t\t\/\/ \"The getq command is both mum on cache miss and quiet,\n\t\t\t\/\/ holding its response until a non-quiet command is issued.\"\n\t\t\tif !req.Opcode.IsQuiet() && len(getq) != 0 {\n\t\t\t\t\/\/ flush quieted get replies\n\t\t\t\tfor _, r := range getq {\n\t\t\t\t\tr.Transmit(out)\n\t\t\t\t}\n\t\t\t\tgetq = getq[:0]\n\t\t\t}\n\n\t\t\tres.Transmit(out)\n\t\t\tcontinue\n\t\t}\n\n\t\tif req.Opcode.IsQuiet() && res.Status == gomem.SUCCESS && req.Opcode != gomem.GET {\n\t\t\t\/\/ there is absolutely no reason to reply here\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ TODO: return when writes fail\n\t\tswitch res.Status {\n\t\tcase gomem.SUCCESS:\n\t\t\tswitch req.Opcode {\n\t\t\tcase gomem.GET, gomem.GETQ:\n\t\t\t\tflags := binary.BigEndian.Uint32(res.Extras[0:4])\n\t\t\t\tout.Write([]byte(fmt.Sprintf(\"VALUE %s %d %d %d\\r\\n\", req.Key, flags, len(res.Body), res.Cas)))\n\t\t\t\tout.Write(res.Body)\n\t\t\t\tout.Write([]byte{'\\r', '\\n'})\n\t\t\t\tout.Write([]byte(\"END\\r\\n\"))\n\t\t\tcase gomem.SET, gomem.ADD, gomem.REPLACE:\n\t\t\t\tout.Write([]byte(\"STORED\\r\\n\"))\n\t\t\tcase gomem.DELETE:\n\t\t\t\tout.Write([]byte(\"DELETED\\r\\n\"))\n\t\t\tcase gomem.INCREMENT, gomem.DECREMENT:\n\t\t\t\tv := binary.BigEndian.Uint64(res.Body)\n\t\t\t\tout.Write([]byte(strconv.FormatUint(v, 10) + \"\\r\\n\"))\n\t\t\t}\n\t\tcase gomem.KEY_ENOENT:\n\t\t\tout.Write([]byte(\"NOT_FOUND\\r\\n\"))\n\t\tcase gomem.KEY_EEXISTS:\n\t\t\tout.Write([]byte(\"EXISTS\\r\\n\"))\n\t\tcase gomem.NOT_STORED:\n\t\t\tout.Write([]byte(\"NOT_STORED\\r\\n\"))\n\t\tcase gomem.ENOMEM:\n\t\t\tout.Write([]byte(\"SERVER_ERROR no space for new entry\\r\\n\"))\n\t\tcase gomem.DELTA_BADVAL:\n\t\t\tout.Write([]byte(\"CLIENT_ERROR incr\/decr on non-numeric field\\r\\n\"))\n\t\tcase gomem.UNKNOWN_COMMAND:\n\t\t\tout.Write([]byte(\"ERROR\\r\\n\"))\n\t\t}\n\t}\n}\n\nfunc replyTo(in []byte, to *net.UDPAddr) {\n\tu, err := net.ListenPacket(\"udp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tdefer u.Close()\n\n\tvar o bytes.Buffer\n\tdeal(bytes.NewBuffer(in), &o)\n\t_, err = u.WriteTo(o.Bytes(), to)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n\nfunc handleConnection(c net.Conn) {\n\tdeal(c, c)\n\tc.Close()\n}\n<commit_msg>Return req opcode in res<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"cuckood\"\n\t\"cuckood\/cucache\/text\"\n\t\"encoding\/binary\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\/pprof\"\n\t\"strconv\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\tgomem \"github.com\/dustin\/gomemcached\"\n)\n\nvar c cuckoo.Cuckoo\n\nfunc main() {\n\tcpuprofile := flag.String(\"cpuprofile\", \"\", \"CPU profile output file\")\n\tflag.Parse()\n\n\tc = cuckoo.New()\n\n\tvar pf *os.File\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, os.Interrupt, syscall.SIGABRT)\n\tgo func() {\n\t\tfor s := range sigs {\n\t\t\tif pf != nil {\n\t\t\t\tpprof.StopCPUProfile()\n\t\t\t\terr := pf.Close()\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"could not end cpu profile:\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif s == os.Interrupt {\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar err error\n\tif cpuprofile != nil && *cpuprofile != \"\" {\n\t\tfmt.Println(\"starting CPU profiling\")\n\t\tpf, err = os.Create(*cpuprofile)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"could not create CPU profile file %v: %v\\n\", *cpuprofile, err)\n\t\t\treturn\n\t\t}\n\t\terr = pprof.StartCPUProfile(pf)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"could not start CPU profiling: %v\\n\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tln, err := net.Listen(\"tcp\", \":11211\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor {\n\t\t\tconn, err := ln.Accept()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgo handleConnection(conn)\n\t\t}\n\t}()\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tln, err := net.ListenPacket(\"udp\", \":11211\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfor {\n\t\t\tb := make([]byte, 0, 10240)\n\t\t\t_, addr, err := ln.ReadFrom(b)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgo replyTo(b, addr.(*net.UDPAddr))\n\t\t}\n\t}()\n\twg.Wait()\n}\n\nfunc wtf(req gomem.MCRequest, v cuckoo.MemopRes) {\n\tpanic(fmt.Sprintf(\"unexpected result when handling %v: %v\\n\", req.Opcode, v))\n}\n\nfunc tm(i uint32) (t time.Time) {\n\tif i == 0 {\n\t\treturn\n\t}\n\n\tif i < 60*60*24*30 {\n\t\tt = time.Now().Add(time.Duration(i) * time.Second)\n\t} else {\n\t\tt = time.Unix(int64(i), 0)\n\t}\n\treturn\n}\n\nfunc deal(in_ io.Reader, out io.Writer) {\n\tvar getq []*gomem.MCResponse\n\n\tin := bufio.NewReader(in_)\n\tfor {\n\t\tb, err := in.Peek(1)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ TODO print error\n\t\t\treturn\n\t\t}\n\n\t\tisbinary := true\n\t\tvar req gomem.MCRequest\n\t\tvar res gomem.MCResponse\n\t\tif b[0] == gomem.REQ_MAGIC {\n\t\t\t_, err := req.Receive(in, nil)\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t\/\/ TODO: print error\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tres.Opaque = req.Opaque\n\t\t} else {\n\t\t\t\/\/ text protocol fallback\n\t\t\tcmd, err := in.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t\/\/ TODO: print error\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\treq, err = text.ToMCRequest(cmd, in)\n\t\t\tisbinary = false\n\t\t}\n\t\tres.Opcode = req.Opcode\n\n\t\tswitch req.Opcode {\n\t\tcase gomem.GET, gomem.GETQ, gomem.GETK, gomem.GETKQ:\n\t\t\tres.Status = gomem.KEY_ENOENT\n\t\t\tv, ok := c.Get(req.Key)\n\t\t\tif ok {\n\t\t\t\tres.Status = gomem.SUCCESS\n\t\t\t\tres.Extras = make([]byte, 4)\n\t\t\t\tbinary.BigEndian.PutUint32(res.Extras, v.Flags)\n\t\t\t\tres.Cas = v.Casid\n\t\t\t\tres.Body = v.Bytes\n\n\t\t\t\tif req.Opcode == gomem.GETK || req.Opcode == gomem.GETKQ {\n\t\t\t\t\tres.Key = req.Key\n\t\t\t\t}\n\t\t\t}\n\t\tcase gomem.SET, gomem.SETQ,\n\t\t\tgomem.ADD, gomem.ADDQ,\n\t\t\tgomem.REPLACE, gomem.REPLACEQ:\n\n\t\t\tflags := binary.BigEndian.Uint32(req.Extras[0:4])\n\t\t\texpiry := tm(binary.BigEndian.Uint32(req.Extras[4:8]))\n\t\t\tvar v cuckoo.MemopRes\n\t\t\tswitch req.Opcode {\n\t\t\tcase gomem.SET, gomem.SETQ:\n\t\t\t\tif req.Cas == 0 {\n\t\t\t\t\tv = c.Set(req.Key, req.Body, flags, expiry)\n\t\t\t\t} else {\n\t\t\t\t\tv = c.CAS(req.Key, req.Body, flags, expiry, req.Cas)\n\t\t\t\t}\n\t\t\tcase gomem.ADD, gomem.ADDQ:\n\t\t\t\tv = c.Add(req.Key, req.Body, flags, expiry)\n\t\t\tcase gomem.REPLACE, gomem.REPLACEQ:\n\t\t\t\tif req.Cas == 0 {\n\t\t\t\t\tv = c.Replace(req.Key, req.Body, flags, expiry)\n\t\t\t\t} else {\n\t\t\t\t\tv = c.CAS(req.Key, req.Body, flags, expiry, req.Cas)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch v.T {\n\t\t\tcase cuckoo.STORED:\n\t\t\t\tres.Status = gomem.SUCCESS\n\t\t\t\tres.Cas = v.V.(uint64)\n\t\t\tcase cuckoo.NOT_STORED:\n\t\t\t\tres.Status = gomem.NOT_STORED\n\t\t\tcase cuckoo.NOT_FOUND:\n\t\t\t\tres.Status = gomem.KEY_ENOENT\n\t\t\tcase cuckoo.EXISTS:\n\t\t\t\tres.Status = gomem.KEY_EEXISTS\n\t\t\tcase cuckoo.SERVER_ERROR:\n\t\t\t\tres.Status = gomem.ENOMEM\n\t\t\t\tfmt.Println(v.V.(error))\n\t\t\tdefault:\n\t\t\t\twtf(req, v)\n\t\t\t}\n\t\tcase gomem.DELETE, gomem.DELETEQ:\n\t\t\tv := c.Delete(req.Key, req.Cas)\n\n\t\t\tswitch v.T {\n\t\t\tcase cuckoo.STORED:\n\t\t\t\tres.Status = gomem.SUCCESS\n\t\t\tcase cuckoo.NOT_FOUND:\n\t\t\t\tres.Status = gomem.KEY_ENOENT\n\t\t\tcase cuckoo.EXISTS:\n\t\t\t\tres.Status = gomem.KEY_EEXISTS\n\t\t\tdefault:\n\t\t\t\twtf(req, v)\n\t\t\t}\n\t\tcase gomem.INCREMENT, gomem.INCREMENTQ,\n\t\t\tgomem.DECREMENT, gomem.DECREMENTQ:\n\n\t\t\tby := binary.BigEndian.Uint64(req.Extras[0:8])\n\t\t\tdef := binary.BigEndian.Uint64(req.Extras[8:16])\n\t\t\texp := tm(binary.BigEndian.Uint32(req.Extras[16:20]))\n\n\t\t\tif binary.BigEndian.Uint32(req.Extras[16:20]) == 0xffffffff {\n\t\t\t\texp = time.Unix(math.MaxInt64, 0)\n\t\t\t}\n\n\t\t\tvar v cuckoo.MemopRes\n\t\t\tif req.Opcode == gomem.INCREMENT || req.Opcode == gomem.INCREMENTQ {\n\t\t\t\tv = c.Incr(req.Key, by, def, exp)\n\t\t\t} else {\n\t\t\t\tv = c.Decr(req.Key, by, def, exp)\n\t\t\t}\n\n\t\t\tswitch v.T {\n\t\t\tcase cuckoo.STORED:\n\t\t\t\tres.Status = gomem.SUCCESS\n\t\t\t\tcv := v.V.(cuckoo.CasVal)\n\t\t\t\tres.Cas = cv.Casid\n\t\t\t\tres.Body = make([]byte, 8)\n\t\t\t\tbinary.BigEndian.PutUint64(res.Body, cv.NewVal)\n\t\t\tcase cuckoo.CLIENT_ERROR:\n\t\t\t\tres.Status = gomem.DELTA_BADVAL\n\t\t\tcase cuckoo.NOT_FOUND:\n\t\t\t\tres.Status = gomem.KEY_ENOENT\n\t\t\tdefault:\n\t\t\t\twtf(req, v)\n\t\t\t}\n\t\tcase gomem.QUIT, gomem.QUITQ:\n\t\t\treturn\n\t\tcase gomem.FLUSH, gomem.FLUSHQ:\n\t\t\t\/\/ TODO: handle optional \"now\" argument\n\t\t\t\/\/ TODO: this is probably terrible\n\t\t\tc = cuckoo.New()\n\t\t\tres.Status = gomem.SUCCESS\n\t\tcase gomem.NOOP:\n\t\t\tres.Status = gomem.SUCCESS\n\t\tcase gomem.VERSION:\n\t\t\tres.Status = gomem.SUCCESS\n\t\t\t\/\/ TODO: res.Body =\n\t\tcase gomem.APPEND, gomem.APPENDQ,\n\t\t\tgomem.PREPEND, gomem.PREPENDQ:\n\n\t\t\tvar v cuckoo.MemopRes\n\t\t\tswitch req.Opcode {\n\t\t\tcase gomem.APPEND, gomem.APPENDQ:\n\t\t\t\tv = c.Append(req.Key, req.Body, req.Cas)\n\t\t\tcase gomem.PREPEND, gomem.PREPENDQ:\n\t\t\t\tv = c.Prepend(req.Key, req.Body, req.Cas)\n\t\t\t}\n\n\t\t\tswitch v.T {\n\t\t\tcase cuckoo.STORED:\n\t\t\t\tres.Status = gomem.SUCCESS\n\t\t\tcase cuckoo.EXISTS:\n\t\t\t\tres.Status = gomem.KEY_EEXISTS\n\t\t\tcase cuckoo.NOT_FOUND:\n\t\t\t\tres.Status = gomem.KEY_ENOENT\n\t\t\tdefault:\n\t\t\t\twtf(req, v)\n\t\t\t}\n\t\tdefault:\n\t\t\tres.Status = gomem.UNKNOWN_COMMAND\n\t\t}\n\n\t\tif req.Opcode.IsQuiet() && res.Status == gomem.SUCCESS {\n\t\t\tif req.Opcode == gomem.GETQ || req.Opcode == gomem.GETKQ {\n\t\t\t\tgetq = append(getq, &res)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif (req.Opcode == gomem.GETQ || req.Opcode == gomem.GETKQ) && res.Status == gomem.KEY_ENOENT {\n\t\t\t\/\/ no warning on cache miss\n\t\t\tcontinue\n\t\t}\n\n\t\tif res.Status != gomem.SUCCESS {\n\t\t\tif !(res.Status == gomem.KEY_ENOENT && (req.Opcode == gomem.GET || req.Opcode == gomem.GETK)) {\n\t\t\t\tfmt.Println(req.Opcode, res.Status)\n\t\t\t}\n\t\t}\n\n\t\tif isbinary {\n\t\t\t\/\/ \"The getq command is both mum on cache miss and quiet,\n\t\t\t\/\/ holding its response until a non-quiet command is issued.\"\n\t\t\tif !req.Opcode.IsQuiet() && len(getq) != 0 {\n\t\t\t\t\/\/ flush quieted get replies\n\t\t\t\tfor _, r := range getq {\n\t\t\t\t\tr.Transmit(out)\n\t\t\t\t}\n\t\t\t\tgetq = getq[:0]\n\t\t\t}\n\n\t\t\tres.Transmit(out)\n\t\t\tcontinue\n\t\t}\n\n\t\tif req.Opcode.IsQuiet() && res.Status == gomem.SUCCESS && req.Opcode != gomem.GET {\n\t\t\t\/\/ there is absolutely no reason to reply here\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ TODO: return when writes fail\n\t\tswitch res.Status {\n\t\tcase gomem.SUCCESS:\n\t\t\tswitch req.Opcode {\n\t\t\tcase gomem.GET, gomem.GETQ:\n\t\t\t\tflags := binary.BigEndian.Uint32(res.Extras[0:4])\n\t\t\t\tout.Write([]byte(fmt.Sprintf(\"VALUE %s %d %d %d\\r\\n\", req.Key, flags, len(res.Body), res.Cas)))\n\t\t\t\tout.Write(res.Body)\n\t\t\t\tout.Write([]byte{'\\r', '\\n'})\n\t\t\t\tout.Write([]byte(\"END\\r\\n\"))\n\t\t\tcase gomem.SET, gomem.ADD, gomem.REPLACE:\n\t\t\t\tout.Write([]byte(\"STORED\\r\\n\"))\n\t\t\tcase gomem.DELETE:\n\t\t\t\tout.Write([]byte(\"DELETED\\r\\n\"))\n\t\t\tcase gomem.INCREMENT, gomem.DECREMENT:\n\t\t\t\tv := binary.BigEndian.Uint64(res.Body)\n\t\t\t\tout.Write([]byte(strconv.FormatUint(v, 10) + \"\\r\\n\"))\n\t\t\t}\n\t\tcase gomem.KEY_ENOENT:\n\t\t\tout.Write([]byte(\"NOT_FOUND\\r\\n\"))\n\t\tcase gomem.KEY_EEXISTS:\n\t\t\tout.Write([]byte(\"EXISTS\\r\\n\"))\n\t\tcase gomem.NOT_STORED:\n\t\t\tout.Write([]byte(\"NOT_STORED\\r\\n\"))\n\t\tcase gomem.ENOMEM:\n\t\t\tout.Write([]byte(\"SERVER_ERROR no space for new entry\\r\\n\"))\n\t\tcase gomem.DELTA_BADVAL:\n\t\t\tout.Write([]byte(\"CLIENT_ERROR incr\/decr on non-numeric field\\r\\n\"))\n\t\tcase gomem.UNKNOWN_COMMAND:\n\t\t\tout.Write([]byte(\"ERROR\\r\\n\"))\n\t\t}\n\t}\n}\n\nfunc replyTo(in []byte, to *net.UDPAddr) {\n\tu, err := net.ListenPacket(\"udp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tdefer u.Close()\n\n\tvar o bytes.Buffer\n\tdeal(bytes.NewBuffer(in), &o)\n\t_, err = u.WriteTo(o.Bytes(), to)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n\nfunc handleConnection(c net.Conn) {\n\tdeal(c, c)\n\tc.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build selenium\n\n\/*\n * Copyright (C) 2017 Red Hat, Inc.\n *\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\n *\/\n\npackage tests\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/tebeka\/selenium\"\n\n\tgclient \"github.com\/skydive-project\/skydive\/cmd\/client\"\n\tshttp \"github.com\/skydive-project\/skydive\/http\"\n\t\"github.com\/skydive-project\/skydive\/tests\/helper\"\n)\n\nfunc TestSelenium(t *testing.T) {\n\tgopath := os.Getenv(\"GOPATH\")\n\ttopology := gopath + \"\/src\/github.com\/skydive-project\/skydive\/scripts\/simple.sh\"\n\n\tsetupCmds := []helper.Cmd{\n\t\t{fmt.Sprintf(\"%s start 124.65.54.42\/24 124.65.54.43\/24\", topology), true},\n\t\t{\"sudo docker pull elgalu\/selenium\", true},\n\t\t{\"sudo docker run -d --name=grid -p 4444:24444 -p 5900:25900 -e --shm-size=1g elgalu\/selenium\", true},\n\t\t{\"docker exec grid wait_all_done 30s\", true},\n\t}\n\n\ttearDownCmds := []helper.Cmd{\n\t\t{fmt.Sprintf(\"%s stop\", topology), true},\n\t\t{\"sudo docker exec grid stop\", true},\n\t\t{\"sudo docker stop grid\", true},\n\t\t{\"sudo docker rm grid\", true},\n\t}\n\n\thelper.ExecCmds(t, setupCmds...)\n\tdefer helper.ExecCmds(t, tearDownCmds...)\n\n\tcaps := selenium.Capabilities{\"browserName\": \"chrome\"}\n\twebdriver, err := selenium.NewRemote(caps, \"http:\/\/127.0.0.1:4444\/wd\/hub\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer webdriver.Quit()\n\n\tipaddr, err := getIPv4Addr()\n\tif err != nil {\n\t\tt.Fatal(\"Not able to find Analayzer addr: %v\", err)\n\t}\n\n\tif err := webdriver.Get(\"http:\/\/\" + ipaddr + \":8082\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttime.Sleep(5 * time.Second)\n\n\tstartCapture := func(wd selenium.WebDriver) error {\n\t\tcaptureTab, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='Captures']\")\n\t\tif err != nil || captureTab == nil {\n\t\t\treturn fmt.Errorf(\"Not found capture tab: %v\", err)\n\t\t}\n\t\tif err := captureTab.Click(); err != nil {\n\t\t\treturn fmt.Errorf(\"%v\", err)\n\t\t}\n\t\tcreateBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='create-capture']\")\n\t\tif err != nil || createBtn == nil {\n\t\t\treturn fmt.Errorf(\"Not found create button : %v\", err)\n\t\t}\n\t\tif err := createBtn.Click(); err != nil {\n\t\t\treturn fmt.Errorf(\"%v\", err)\n\t\t}\n\t\ttime.Sleep(2 * time.Second)\n\n\t\tgremlinRdoBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='by-gremlin']\")\n\t\tif err != nil || gremlinRdoBtn == nil {\n\t\t\treturn fmt.Errorf(\"Not found gremlin expression radio button: %v\", err)\n\t\t}\n\t\tif err := gremlinRdoBtn.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tqueryTxtBox, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='capture-query']\")\n\t\tif err != nil || queryTxtBox == nil {\n\t\t\treturn fmt.Errorf(\"Not found Query text box: %v\", err)\n\t\t}\n\t\tif err := queryTxtBox.Clear(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := queryTxtBox.SendKeys(\"G.V().Has('Name', 'br-int', 'Type', 'ovsbridge')\"); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tstartBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='start-capture']\")\n\t\tif err != nil || startBtn == nil {\n\t\t\treturn fmt.Errorf(\"Not found start button: %v\", err)\n\t\t}\n\t\tif err := startBtn.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttime.Sleep(3 * time.Second)\n\n\t\t\/\/check capture created with the given query\n\t\tcaptures, err := wd.FindElements(selenium.ByClassName, \"query\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar foundCapture bool\n\t\tfor _, capture := range captures {\n\t\t\tif txt, _ := capture.Text(); txt == \"G.V().Has('Name', 'br-int', 'Type', 'ovsbridge')\" {\n\t\t\t\tfoundCapture = true\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\t\tif !foundCapture {\n\t\t\treturn fmt.Errorf(\"Capture not found in the list\")\n\t\t}\n\t\treturn nil\n\n\t}\n\n\tinjectPacket := func(wd selenium.WebDriver) error {\n\t\tgeneratorTab, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='Generator']\")\n\t\tif err != nil || generatorTab == nil {\n\t\t\treturn fmt.Errorf(\"Generator tab not found: %v\", err)\n\t\t}\n\t\tif err := generatorTab.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinjectSrc, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='inject-src']\/input\")\n\t\tif err != nil || injectSrc == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := injectSrc.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tauthOptions := &shttp.AuthenticationOpts{}\n\t\tgh := gclient.NewGremlinQueryHelper(authOptions)\n\n\t\tnode1, err := gh.GetNode(\"G.V().Has('Name', 'eth0', 'IPV4', Contains('124.65.54.42\/24')).HasKey('TID')\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnode2, err := gh.GetNode(\"G.V().Has('Name', 'eth0', 'IPV4', Contains('124.65.54.43\/24')).HasKey('TID')\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttid1, _ := node1.GetFieldString(\"TID\")\n\t\ttid2, _ := node2.GetFieldString(\"TID\")\n\n\t\tsrcNode, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@tid='\"+tid1+\"']\")\n\t\tif err != nil || srcNode == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := srcNode.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinjectDst, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='inject-dst']\/input\")\n\t\tif err != nil || injectDst == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := injectDst.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdstNode, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@tid='\"+tid2+\"']\")\n\t\tif err != nil || dstNode == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := dstNode.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinjectBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='inject']\")\n\t\tif err != nil || injectBtn == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif err := injectBtn.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar alertMsg selenium.WebElement\n\t\tfor i := 1; i <= 10; i++ {\n\t\t\talertMsg, err = wd.FindElement(selenium.ByClassName, \"alert-success\")\n\t\t\tif err != nil {\n\t\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tif alertMsg == nil {\n\t\t\treturn fmt.Errorf(\"No success alert msg.\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := startCapture(webdriver); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := injectPacket(webdriver); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n}\n\nfunc getIPv4Addr() (string, error) {\n\tifaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, iface := range ifaces {\n\t\t\/\/neglect interfaces which are down\n\t\tif iface.Flags&net.FlagUp == 0 {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/neglect loopback interface\n\t\tif iface.Flags&net.FlagLoopback != 0 {\n\t\t\tcontinue\n\t\t}\n\t\taddrs, err := iface.Addrs()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tfor _, addr := range addrs {\n\t\t\tvar ip net.IP\n\t\t\tswitch t := addr.(type) {\n\t\t\tcase *net.IPNet:\n\t\t\t\tip = t.IP\n\t\t\tcase *net.IPAddr:\n\t\t\t\tip = t.IP\n\t\t\t}\n\t\t\tif ip == nil || ip.IsLoopback() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tip = ip.To4()\n\t\t\tif ip != nil {\n\t\t\t\treturn ip.String(), nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"No IP found\")\n}\n<commit_msg>test: selenium test to verify flows<commit_after>\/\/ +build selenium\n\n\/*\n * Copyright (C) 2017 Red Hat, Inc.\n *\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\n *\/\n\npackage tests\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/tebeka\/selenium\"\n\n\tgclient \"github.com\/skydive-project\/skydive\/cmd\/client\"\n\tshttp \"github.com\/skydive-project\/skydive\/http\"\n\t\"github.com\/skydive-project\/skydive\/tests\/helper\"\n)\n\nfunc TestSelenium(t *testing.T) {\n\tgopath := os.Getenv(\"GOPATH\")\n\ttopology := gopath + \"\/src\/github.com\/skydive-project\/skydive\/scripts\/simple.sh\"\n\n\tsetupCmds := []helper.Cmd{\n\t\t{fmt.Sprintf(\"%s start 124.65.54.42\/24 124.65.54.43\/24\", topology), true},\n\t\t{\"sudo docker pull elgalu\/selenium\", true},\n\t\t{\"sudo docker run -d --name=grid -p 4444:24444 -p 5900:25900 -e --shm-size=1g elgalu\/selenium\", true},\n\t\t{\"docker exec grid wait_all_done 30s\", true},\n\t}\n\n\ttearDownCmds := []helper.Cmd{\n\t\t{fmt.Sprintf(\"%s stop\", topology), true},\n\t\t{\"sudo docker exec grid stop\", true},\n\t\t{\"sudo docker stop grid\", true},\n\t\t{\"sudo docker rm grid\", true},\n\t}\n\n\thelper.ExecCmds(t, setupCmds...)\n\tdefer helper.ExecCmds(t, tearDownCmds...)\n\n\tcaps := selenium.Capabilities{\"browserName\": \"chrome\"}\n\twebdriver, err := selenium.NewRemote(caps, \"http:\/\/127.0.0.1:4444\/wd\/hub\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer webdriver.Quit()\n\n\tipaddr, err := getIPv4Addr()\n\tif err != nil {\n\t\tt.Fatal(\"Not able to find Analayzer addr: %v\", err)\n\t}\n\n\tif err := webdriver.Get(\"http:\/\/\" + ipaddr + \":8082\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttime.Sleep(5 * time.Second)\n\n\tstartCapture := func(wd selenium.WebDriver) error {\n\t\tcaptureTab, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='Captures']\")\n\t\tif err != nil || captureTab == nil {\n\t\t\treturn fmt.Errorf(\"Not found capture tab: %v\", err)\n\t\t}\n\t\tif err := captureTab.Click(); err != nil {\n\t\t\treturn fmt.Errorf(\"%v\", err)\n\t\t}\n\t\tcreateBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='create-capture']\")\n\t\tif err != nil || createBtn == nil {\n\t\t\treturn fmt.Errorf(\"Not found create button : %v\", err)\n\t\t}\n\t\tif err := createBtn.Click(); err != nil {\n\t\t\treturn fmt.Errorf(\"%v\", err)\n\t\t}\n\t\ttime.Sleep(2 * time.Second)\n\n\t\tgremlinRdoBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='by-gremlin']\")\n\t\tif err != nil || gremlinRdoBtn == nil {\n\t\t\treturn fmt.Errorf(\"Not found gremlin expression radio button: %v\", err)\n\t\t}\n\t\tif err := gremlinRdoBtn.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tqueryTxtBox, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='capture-query']\")\n\t\tif err != nil || queryTxtBox == nil {\n\t\t\treturn fmt.Errorf(\"Not found Query text box: %v\", err)\n\t\t}\n\t\tif err := queryTxtBox.Clear(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := queryTxtBox.SendKeys(\"G.V().Has('Name', 'br-int', 'Type', 'ovsbridge')\"); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tstartBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='start-capture']\")\n\t\tif err != nil || startBtn == nil {\n\t\t\treturn fmt.Errorf(\"Not found start button: %v\", err)\n\t\t}\n\t\tif err := startBtn.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttime.Sleep(3 * time.Second)\n\n\t\t\/\/check capture created with the given query\n\t\tcaptures, err := wd.FindElements(selenium.ByClassName, \"query\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar foundCapture bool\n\t\tfor _, capture := range captures {\n\t\t\tif txt, _ := capture.Text(); txt == \"G.V().Has('Name', 'br-int', 'Type', 'ovsbridge')\" {\n\t\t\t\tfoundCapture = true\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t}\n\t\tif !foundCapture {\n\t\t\treturn fmt.Errorf(\"Capture not found in the list\")\n\t\t}\n\t\treturn nil\n\n\t}\n\n\tinjectPacket := func(wd selenium.WebDriver) error {\n\t\tgeneratorTab, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='Generator']\")\n\t\tif err != nil || generatorTab == nil {\n\t\t\treturn fmt.Errorf(\"Generator tab not found: %v\", err)\n\t\t}\n\t\tif err := generatorTab.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinjectSrc, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='inject-src']\/input\")\n\t\tif err != nil || injectSrc == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := injectSrc.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tauthOptions := &shttp.AuthenticationOpts{}\n\t\tgh := gclient.NewGremlinQueryHelper(authOptions)\n\n\t\tnode1, err := gh.GetNode(\"G.V().Has('Name', 'eth0', 'IPV4', Contains('124.65.54.42\/24')).HasKey('TID')\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnode2, err := gh.GetNode(\"G.V().Has('Name', 'eth0', 'IPV4', Contains('124.65.54.43\/24')).HasKey('TID')\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttid1, _ := node1.GetFieldString(\"TID\")\n\t\ttid2, _ := node2.GetFieldString(\"TID\")\n\n\t\tsrcNode, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@tid='\"+tid1+\"']\")\n\t\tif err != nil || srcNode == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := srcNode.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinjectDst, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='inject-dst']\/input\")\n\t\tif err != nil || injectDst == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := injectDst.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdstNode, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@tid='\"+tid2+\"']\")\n\t\tif err != nil || dstNode == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := dstNode.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tinjectBtn, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='inject']\")\n\t\tif err != nil || injectBtn == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif err := injectBtn.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar alertMsg selenium.WebElement\n\t\tfor i := 1; i <= 10; i++ {\n\t\t\talertMsg, err = wd.FindElement(selenium.ByClassName, \"alert-success\")\n\t\t\tif err != nil {\n\t\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tif alertMsg != nil {\n\t\t\tcloseBtn, _ := alertMsg.FindElement(selenium.ByClassName, \"close\")\n\t\t\tif closeBtn != nil {\n\t\t\t\tcloseBtn.Click()\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"No success alert msg.\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tverifyFlows := func(wd selenium.WebDriver) error {\n\t\ttime.Sleep(3 * time.Second)\n\n\t\tflowsTab, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='Flows']\")\n\t\tif err != nil || flowsTab == nil {\n\t\t\treturn fmt.Errorf(\"Flows tab not found: %v\", err)\n\t\t}\n\t\tif err := flowsTab.Click(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tflowQuery, err := wd.FindElement(selenium.ByXPATH, \".\/\/*[@id='flow-table-query']\")\n\t\tif err != nil || flowQuery == nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := flowQuery.Clear(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tquery := \"G.Flows().Has('Network.A', '124.65.54.42', 'Network.B', '124.65.54.43')\"\n\t\tif err := flowQuery.SendKeys(query); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\n\t\tflowRow, err := wd.FindElement(selenium.ByClassName, \"flow-row\")\n\t\tif err != nil || flowRow == nil {\n\t\t\treturn err\n\t\t}\n\t\trowData, err := flowRow.FindElements(selenium.ByTagName, \"td\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(rowData) != 7 {\n\t\t\treturn fmt.Errorf(\"By default 7 rows should be return\")\n\t\t}\n\t\ttxt, err := rowData[1].Text()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif txt != \"124.65.54.42\" {\n\t\t\tfmt.Errorf(\"Network.A should be '124.65.54.42' but got: %s\", txt)\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := startCapture(webdriver); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := injectPacket(webdriver); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := verifyFlows(webdriver); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc getIPv4Addr() (string, error) {\n\tifaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, iface := range ifaces {\n\t\t\/\/neglect interfaces which are down\n\t\tif iface.Flags&net.FlagUp == 0 {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/neglect loopback interface\n\t\tif iface.Flags&net.FlagLoopback != 0 {\n\t\t\tcontinue\n\t\t}\n\t\taddrs, err := iface.Addrs()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tfor _, addr := range addrs {\n\t\t\tvar ip net.IP\n\t\t\tswitch t := addr.(type) {\n\t\t\tcase *net.IPNet:\n\t\t\t\tip = t.IP\n\t\t\tcase *net.IPAddr:\n\t\t\t\tip = t.IP\n\t\t\t}\n\t\t\tif ip == nil || ip.IsLoopback() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tip = ip.To4()\n\t\t\tif ip != nil {\n\t\t\t\treturn ip.String(), nil\n\t\t\t}\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"No IP found\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is part of the KubeVirt project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * Copyright 2018 Red Hat, Inc.\n *\n *\/\n\npackage tests_test\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/resource\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/rand\"\n\n\t\"kubevirt.io\/client-go\/kubecli\"\n\t\"kubevirt.io\/kubevirt\/tests\"\n\tvmsgen \"kubevirt.io\/kubevirt\/tools\/vms-generator\/utils\"\n)\n\nconst (\n\tdefaultNamePrefix = \"testvm-\"\n\tdefaultCPUCores   = \"2\"\n\tdefaultMemory     = \"2Gi\"\n)\n\nvar _ = Describe(\"Templates\", func() {\n\ttests.FlagParse()\n\n\tvirtClient, err := kubecli.GetKubevirtClient()\n\ttests.PanicOnError(err)\n\n\tvar (\n\t\ttemplateParams map[string]string\n\t\tworkDir        string\n\t\ttemplateFile   string\n\t\tvmName         string\n\t)\n\n\tBeforeEach(func() {\n\t\ttests.SkipIfNoCmd(\"oc\")\n\t\ttests.BeforeTestCleanup()\n\t\tSetDefaultEventuallyTimeout(120 * time.Second)\n\t\tSetDefaultEventuallyPollingInterval(2 * time.Second)\n\n\t\tworkDir, err = ioutil.TempDir(\"\", tests.TempDirPrefix+\"-\")\n\t\tExpect(err).ToNot(HaveOccurred())\n\t})\n\n\tAfterEach(func() {\n\t\tif workDir != \"\" {\n\t\t\terr := os.RemoveAll(workDir)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tworkDir = \"\"\n\t\t}\n\t})\n\n\tDescribe(\"Creating VM from Template\", func() {\n\n\t\tAssertTestSetupSuccess := func() func() {\n\t\t\treturn func() {\n\t\t\t\ttemplateParams = map[string]string{\n\t\t\t\t\t\"NAME\":      defaultNamePrefix + rand.String(12),\n\t\t\t\t\t\"CPU_CORES\": defaultCPUCores,\n\t\t\t\t\t\"MEMORY\":    defaultMemory,\n\t\t\t\t}\n\t\t\t\ttemplateFile = \"\"\n\t\t\t\tExpectWithOffset(1, templateParams).To(HaveKeyWithValue(\"NAME\", Not(BeEmpty())), \"invalid NAME parameter: VirtualMachine name cannot be empty string\")\n\t\t\t\tExpectWithOffset(1, templateParams).To(HaveKeyWithValue(\"CPU_CORES\", MatchRegexp(`^[0-9]+$`)), \"invalid CPU_CORES parameter: %q is not unsigned integer\", templateParams[\"CPU_CORES\"])\n\t\t\t\tExpectWithOffset(1, templateParams).To(HaveKeyWithValue(\"MEMORY\", MatchRegexp(`^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$`)), \"invalid MEMORY parameter: %q is not valid quantity\", templateParams[\"MEMORY\"])\n\t\t\t\tvmName = templateParams[\"NAME\"]\n\t\t\t\tvm, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\tExpectWithOffset(1, errors.IsNotFound(err) || vm.ObjectMeta.DeletionTimestamp != nil).To(BeTrue(), \"invalid NAME parameter: VirtualMachine %q already exists\", vmName)\n\t\t\t}\n\t\t}\n\n\t\tAssertTemplateSetupSuccess := func(template *vmsgen.Template, params map[string]string) func() {\n\t\t\treturn func() {\n\t\t\t\tExpectWithOffset(1, template).NotTo(BeNil(), \"template object was not provided\")\n\t\t\t\tBy(\"Creating the Template JSON file\")\n\t\t\t\tvar err error\n\t\t\t\ttemplateFile, err = tests.GenerateTemplateJson(template, workDir)\n\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed to write template JSON file: %v\", err)\n\t\t\t\tExpectWithOffset(1, templateFile).To(BeAnExistingFile(), \"template JSON file %q was not created\", templateFile)\n\n\t\t\t\tif params != nil {\n\t\t\t\t\tBy(\"Validating template parameters\")\n\t\t\t\t\tfor param, value := range params {\n\t\t\t\t\t\tswitch param {\n\t\t\t\t\t\tcase \"NAME\":\n\t\t\t\t\t\t\tExpectWithOffset(1, value).NotTo(BeEmpty(), \"invalid NAME parameter: VirtualMachine name cannot be empty string\")\n\t\t\t\t\t\t\tvmName = value\n\t\t\t\t\t\t\tvm, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\t\t\t\tExpectWithOffset(1, errors.IsNotFound(err) || vm.ObjectMeta.DeletionTimestamp != nil).To(BeTrue(), \"invalid NAME parameter: VirtualMachine %q already exists\", vmName)\n\t\t\t\t\t\tcase \"CPU_CORES\":\n\t\t\t\t\t\t\tExpectWithOffset(1, templateParams).To(HaveKeyWithValue(\"CPU_CORES\", MatchRegexp(`^[0-9]+$`)), \"invalid CPU_CORES parameter: %q is not unsigned integer\", templateParams[\"CPU_CORES\"])\n\t\t\t\t\t\tcase \"MEMORY\":\n\t\t\t\t\t\t\tExpectWithOffset(1, templateParams).To(HaveKeyWithValue(\"MEMORY\", MatchRegexp(`^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$`)), \"invalid MEMORY parameter: %q is not valid quantity\", templateParams[\"MEMORY\"])\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttemplateParams[param] = value\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tAssertTestCleanupSuccess := func() func() {\n\t\t\treturn func() {\n\t\t\t\tif vm, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{}); err == nil && vm.ObjectMeta.DeletionTimestamp == nil {\n\t\t\t\t\tBy(\"Deleting the VirtualMachine\")\n\t\t\t\t\tExpectWithOffset(1, virtClient.VirtualMachine(tests.NamespaceTestDefault).Delete(vmName, &metav1.DeleteOptions{})).To(Succeed(), \"failed to delete VirtualMachine %q: %v\", vmName, err)\n\t\t\t\t\tEventuallyWithOffset(1, func() bool {\n\t\t\t\t\t\tobj, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\t\t\treturn errors.IsNotFound(err) || obj.ObjectMeta.DeletionTimestamp != nil\n\t\t\t\t\t}).Should(BeTrue(), \"VirtualMachine %q still exists and the deletion timestamp was not set\", vmName)\n\t\t\t\t}\n\t\t\t\tif templateFile != \"\" {\n\t\t\t\t\tif _, err := os.Stat(templateFile); !os.IsNotExist(err) {\n\t\t\t\t\t\tBy(\"Deleting template JSON file\")\n\t\t\t\t\t\tExpectWithOffset(1, os.RemoveAll(filepath.Dir(templateFile))).To(Succeed(), \"failed to remove template JSON file %q: %v\", templateFile, err)\n\t\t\t\t\t\tExpectWithOffset(1, templateFile).NotTo(BeAnExistingFile(), \"template JSON file %q was not removed\", templateFile)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tAssertVMCreationSuccess := func() func() {\n\t\t\treturn func() {\n\t\t\t\tBy(\"Creating VirtualMachine from Template via oc command\")\n\t\t\t\tocProcessCommand := []string{\"oc\", \"process\", \"-f\", templateFile}\n\t\t\t\tfor param, value := range templateParams {\n\t\t\t\t\tocProcessCommand = append(ocProcessCommand, \"-p\", fmt.Sprintf(\"%s=%s\", param, value))\n\t\t\t\t}\n\t\t\t\tout, stderr, err := tests.RunCommandPipe(ocProcessCommand, []string{\"oc\", \"create\", \"-f\", \"-\"})\n\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed to create VirtualMachine %q via command \\\"%s | oc create -f -\\\": %s: %v\", vmName, strings.Join(ocProcessCommand, \" \"), out+stderr, err)\n\t\t\t\tExpectWithOffset(1, out).To(MatchRegexp(`\"?%s\"? created\\n`, vmName), \"command \\\"%s | oc create -f -\\\" did not print expected message: %s\", strings.Join(ocProcessCommand, \" \"), out+stderr)\n\t\t\t\tBy(\"Checking if the VirtualMachine exists\")\n\t\t\t\tEventuallyWithOffset(1, func() error {\n\t\t\t\t\t_, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\t\treturn err\n\t\t\t\t}).Should(Succeed(), \"VirtualMachine %q still does not exist\", vmName)\n\t\t\t}\n\t\t}\n\n\t\tAssertVMCreationFailure := func() func() {\n\t\t\treturn func() {\n\t\t\t\tBy(\"Creating VirtualMachine from Template via oc command\")\n\t\t\t\tocProcessCommand := []string{\"oc\", \"process\", \"-f\", templateFile}\n\t\t\t\tfor param, value := range templateParams {\n\t\t\t\t\tocProcessCommand = append(ocProcessCommand, \"-p\", fmt.Sprintf(\"%s=%s\", param, value))\n\t\t\t\t}\n\t\t\t\tout, stderr, err := tests.RunCommandPipe(ocProcessCommand, []string{\"oc\", \"create\", \"-f\", \"-\"})\n\t\t\t\tExpectWithOffset(1, err).To(HaveOccurred(), \"creation of VirtualMachine %q via command \\\"%s | oc create -f -\\\" succeeded: %s: %v\", vmName, strings.Join(ocProcessCommand, \" \"), out+stderr, err)\n\t\t\t}\n\t\t}\n\n\t\tAssertVMDeletionSuccess := func() func() {\n\t\t\treturn func() {\n\t\t\t\tBy(\"Deleting the VirtualMachine via oc command\")\n\t\t\t\tout, stderr, err := tests.RunCommand(\"oc\", \"delete\", \"vm\", vmName)\n\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed to delete VirtualMachine via command \\\"oc delete vm %s\\\": %s: %v\", vmName, out+stderr, err)\n\t\t\t\tExpectWithOffset(1, out).To(MatchRegexp(`\"?%s\"? deleted\\n`, vmName), \"command \\\"oc delete vm %s\\\" did not print expected message: %s\", vmName, out)\n\n\t\t\t\tBy(\"Checking if the VM does not exist anymore\")\n\t\t\t\tEventuallyWithOffset(1, func() bool {\n\t\t\t\t\tvm, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\t\treturn errors.IsNotFound(err) || vm.ObjectMeta.DeletionTimestamp != nil\n\t\t\t\t}).Should(BeTrue(), \"the VirtualMachine %q still exists and deletion timestamp was not set\", vmName)\n\t\t\t}\n\t\t}\n\n\t\tAssertVMDeletionFailure := func() func() {\n\t\t\treturn func() {\n\t\t\t\tBy(\"Deleting the VirtualMachine via oc command\")\n\t\t\t\tout, stderr, err := tests.RunCommand(\"oc\", \"delete\", \"vm\", vmName)\n\t\t\t\tExpectWithOffset(1, err).To(HaveOccurred(), \"failed to delete VirtualMachine via command \\\"oc delete vm %s\\\": %s: %v\", vmName, out+stderr, err)\n\t\t\t}\n\t\t}\n\n\t\tAssertVMStartSuccess := func(command string) func() {\n\t\t\treturn func() {\n\t\t\t\tswitch command {\n\t\t\t\tcase \"oc\":\n\t\t\t\t\tBy(\"Starting VirtualMachine via oc command\")\n\t\t\t\t\tpatch := `{\"spec\":{\"running\":true}}`\n\t\t\t\t\tout, stderr, err := tests.RunCommand(\"oc\", \"patch\", \"vm\", vmName, \"--type=merge\", \"-p\", patch)\n\t\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed schedule VirtualMachine %q start via command \\\"oc patch vm %s --type=merge -p '%s'\\\": %s: %v\", vmName, vmName, patch, out+stderr, err)\n\t\t\t\t\tExpectWithOffset(1, out).To(MatchRegexp(`\"?%s\"? patched\\n`, vmName), \"command \\\"oc patch vm %s --type=merge -p '%s'\\\" did not print expected message: %s\", vmName, patch, out+stderr)\n\n\t\t\t\tcase \"virtctl\":\n\t\t\t\t\tBy(\"Starting VirtualMachine via virtctl command\")\n\t\t\t\t\tout, stderr, err := tests.RunCommand(\"virtctl\", \"start\", vmName)\n\t\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed to schedule VirtualMachine %q start via command \\\"virtctl start %s\\\": %s: %v\", vmName, vmName, out+stderr, err)\n\t\t\t\t\tExpectWithOffset(1, out).To(ContainSubstring(\"%s was scheduled to start\\n\", vmName), \"command \\\"virtctl start %s\\\" did not print expected message: %s\", vmName, out+stderr)\n\t\t\t\t}\n\n\t\t\t\tBy(\"Checking if the VirtualMachineInstance was created\")\n\t\t\t\tEventuallyWithOffset(1, func() error {\n\t\t\t\t\t_, err := virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\t\treturn err\n\t\t\t\t}).Should(Succeed(), \"the VirtualMachineInstance %q still does not exist\", vmName)\n\n\t\t\t\tBy(\"Checking if the VirtualMachine has status ready\")\n\t\t\t\tEventuallyWithOffset(1, func() bool {\n\t\t\t\t\tvm, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed to fetch VirtualMachine %q: %v\", vmName, err)\n\t\t\t\t\treturn vm.Status.Ready\n\t\t\t\t}).Should(BeTrue(), \"VirtualMachine %q still does not have status ready\", vmName)\n\n\t\t\t\tBy(\"Checking if the VirtualMachineInstance specs match Template parameters\")\n\t\t\t\tvmi, err := virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed to fetch VirtualMachine %q: %v\", vmName, err)\n\t\t\t\tvmiCPUCores := vmi.Spec.Domain.CPU.Cores\n\t\t\t\ttemplateParamCPUCores, err := strconv.ParseUint(templateParams[\"CPU_CORES\"], 10, 32)\n\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"cannot parse CPU_CORES parameter: value %q: %v\", templateParams[\"CPU_CORES\"], err)\n\t\t\t\tExpectWithOffset(1, vmiCPUCores).To(Equal(uint32(templateParamCPUCores)), \"VirtualMachineInstance CPU cores (%d) does not match CPU_CORES parameter value: %s\", vmiCPUCores, templateParams[\"CPU_CORES\"])\n\t\t\t\tvmiMemory := vmi.Spec.Domain.Resources.Requests[\"memory\"]\n\t\t\t\ttemplateParamMemory, err := resource.ParseQuantity(templateParams[\"MEMORY\"])\n\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"cannot parse MEMORY parameter: value %q: %v\", templateParams[\"MEMORY\"], err)\n\t\t\t\tExpectWithOffset(1, vmiMemory).To(Equal(templateParamMemory), \"VirtualMachineInstance memory (%s) does not match MEMORY parameter value: %s\", vmiMemory.String(), templateParams[\"MEMORY\"])\n\t\t\t}\n\t\t}\n\n\t\tAssertTemplateTestSuccess := func() {\n\t\t\tIt(\"[test_id:3292]should succeed to create VirtualMachine via oc command\", AssertVMCreationSuccess())\n\t\t\tIt(\"[test_id:3293]should fail to delete VirtualMachine via oc command\", AssertVMDeletionFailure())\n\n\t\t\tWhen(\"the VirtualMachine was created\", func() {\n\t\t\t\tBeforeEach(AssertVMCreationSuccess())\n\t\t\t\tIt(\"[test_id:3294]should succeed to start the VirtualMachine via oc command\", AssertVMStartSuccess(\"oc\"))\n\t\t\t\tIt(\"[test_id:3295]should succeed to delete VirtualMachine via oc command\", AssertVMDeletionSuccess())\n\t\t\t\tIt(\"[test_id:3308]should fail to create the same VirtualMachine via oc command\", AssertVMCreationFailure())\n\t\t\t})\n\t\t}\n\n\t\tBeforeEach(AssertTestSetupSuccess())\n\n\t\tAfterEach(AssertTestCleanupSuccess())\n\n\t\tFContext(\"with Fedora Template\", func() {\n\t\t\tBeforeEach(AssertTemplateSetupSuccess(vmsgen.GetTemplateFedoraWithContainerDisk(tests.ContainerDiskFor(tests.ContainerDiskFedora)), nil))\n\n\t\t\tAssertTemplateTestSuccess()\n\t\t})\n\n\t\tContext(\"[rfe_id:273][crit:medium][vendor:cnv-qe@redhat.com][level:component]with RHEL Template\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\ttests.SkipIfNoRhelImage(virtClient)\n\t\t\t\tAssertTemplateSetupSuccess(vmsgen.GetTestTemplateRHEL7(), nil)()\n\t\t\t})\n\n\t\t\tAssertTemplateTestSuccess()\n\t\t})\n\t})\n})\n<commit_msg>Removed test focus<commit_after>\/*\n * This file is part of the KubeVirt project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * Copyright 2018 Red Hat, Inc.\n *\n *\/\n\npackage tests_test\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/resource\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/rand\"\n\n\t\"kubevirt.io\/client-go\/kubecli\"\n\t\"kubevirt.io\/kubevirt\/tests\"\n\tvmsgen \"kubevirt.io\/kubevirt\/tools\/vms-generator\/utils\"\n)\n\nconst (\n\tdefaultNamePrefix = \"testvm-\"\n\tdefaultCPUCores   = \"2\"\n\tdefaultMemory     = \"2Gi\"\n)\n\nvar _ = Describe(\"Templates\", func() {\n\ttests.FlagParse()\n\n\tvirtClient, err := kubecli.GetKubevirtClient()\n\ttests.PanicOnError(err)\n\n\tvar (\n\t\ttemplateParams map[string]string\n\t\tworkDir        string\n\t\ttemplateFile   string\n\t\tvmName         string\n\t)\n\n\tBeforeEach(func() {\n\t\ttests.SkipIfNoCmd(\"oc\")\n\t\ttests.BeforeTestCleanup()\n\t\tSetDefaultEventuallyTimeout(120 * time.Second)\n\t\tSetDefaultEventuallyPollingInterval(2 * time.Second)\n\n\t\tworkDir, err = ioutil.TempDir(\"\", tests.TempDirPrefix+\"-\")\n\t\tExpect(err).ToNot(HaveOccurred())\n\t})\n\n\tAfterEach(func() {\n\t\tif workDir != \"\" {\n\t\t\terr := os.RemoveAll(workDir)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tworkDir = \"\"\n\t\t}\n\t})\n\n\tDescribe(\"Creating VM from Template\", func() {\n\n\t\tAssertTestSetupSuccess := func() func() {\n\t\t\treturn func() {\n\t\t\t\ttemplateParams = map[string]string{\n\t\t\t\t\t\"NAME\":      defaultNamePrefix + rand.String(12),\n\t\t\t\t\t\"CPU_CORES\": defaultCPUCores,\n\t\t\t\t\t\"MEMORY\":    defaultMemory,\n\t\t\t\t}\n\t\t\t\ttemplateFile = \"\"\n\t\t\t\tExpectWithOffset(1, templateParams).To(HaveKeyWithValue(\"NAME\", Not(BeEmpty())), \"invalid NAME parameter: VirtualMachine name cannot be empty string\")\n\t\t\t\tExpectWithOffset(1, templateParams).To(HaveKeyWithValue(\"CPU_CORES\", MatchRegexp(`^[0-9]+$`)), \"invalid CPU_CORES parameter: %q is not unsigned integer\", templateParams[\"CPU_CORES\"])\n\t\t\t\tExpectWithOffset(1, templateParams).To(HaveKeyWithValue(\"MEMORY\", MatchRegexp(`^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$`)), \"invalid MEMORY parameter: %q is not valid quantity\", templateParams[\"MEMORY\"])\n\t\t\t\tvmName = templateParams[\"NAME\"]\n\t\t\t\tvm, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\tExpectWithOffset(1, errors.IsNotFound(err) || vm.ObjectMeta.DeletionTimestamp != nil).To(BeTrue(), \"invalid NAME parameter: VirtualMachine %q already exists\", vmName)\n\t\t\t}\n\t\t}\n\n\t\tAssertTemplateSetupSuccess := func(template *vmsgen.Template, params map[string]string) func() {\n\t\t\treturn func() {\n\t\t\t\tExpectWithOffset(1, template).NotTo(BeNil(), \"template object was not provided\")\n\t\t\t\tBy(\"Creating the Template JSON file\")\n\t\t\t\tvar err error\n\t\t\t\ttemplateFile, err = tests.GenerateTemplateJson(template, workDir)\n\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed to write template JSON file: %v\", err)\n\t\t\t\tExpectWithOffset(1, templateFile).To(BeAnExistingFile(), \"template JSON file %q was not created\", templateFile)\n\n\t\t\t\tif params != nil {\n\t\t\t\t\tBy(\"Validating template parameters\")\n\t\t\t\t\tfor param, value := range params {\n\t\t\t\t\t\tswitch param {\n\t\t\t\t\t\tcase \"NAME\":\n\t\t\t\t\t\t\tExpectWithOffset(1, value).NotTo(BeEmpty(), \"invalid NAME parameter: VirtualMachine name cannot be empty string\")\n\t\t\t\t\t\t\tvmName = value\n\t\t\t\t\t\t\tvm, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\t\t\t\tExpectWithOffset(1, errors.IsNotFound(err) || vm.ObjectMeta.DeletionTimestamp != nil).To(BeTrue(), \"invalid NAME parameter: VirtualMachine %q already exists\", vmName)\n\t\t\t\t\t\tcase \"CPU_CORES\":\n\t\t\t\t\t\t\tExpectWithOffset(1, templateParams).To(HaveKeyWithValue(\"CPU_CORES\", MatchRegexp(`^[0-9]+$`)), \"invalid CPU_CORES parameter: %q is not unsigned integer\", templateParams[\"CPU_CORES\"])\n\t\t\t\t\t\tcase \"MEMORY\":\n\t\t\t\t\t\t\tExpectWithOffset(1, templateParams).To(HaveKeyWithValue(\"MEMORY\", MatchRegexp(`^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$`)), \"invalid MEMORY parameter: %q is not valid quantity\", templateParams[\"MEMORY\"])\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttemplateParams[param] = value\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tAssertTestCleanupSuccess := func() func() {\n\t\t\treturn func() {\n\t\t\t\tif vm, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{}); err == nil && vm.ObjectMeta.DeletionTimestamp == nil {\n\t\t\t\t\tBy(\"Deleting the VirtualMachine\")\n\t\t\t\t\tExpectWithOffset(1, virtClient.VirtualMachine(tests.NamespaceTestDefault).Delete(vmName, &metav1.DeleteOptions{})).To(Succeed(), \"failed to delete VirtualMachine %q: %v\", vmName, err)\n\t\t\t\t\tEventuallyWithOffset(1, func() bool {\n\t\t\t\t\t\tobj, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\t\t\treturn errors.IsNotFound(err) || obj.ObjectMeta.DeletionTimestamp != nil\n\t\t\t\t\t}).Should(BeTrue(), \"VirtualMachine %q still exists and the deletion timestamp was not set\", vmName)\n\t\t\t\t}\n\t\t\t\tif templateFile != \"\" {\n\t\t\t\t\tif _, err := os.Stat(templateFile); !os.IsNotExist(err) {\n\t\t\t\t\t\tBy(\"Deleting template JSON file\")\n\t\t\t\t\t\tExpectWithOffset(1, os.RemoveAll(filepath.Dir(templateFile))).To(Succeed(), \"failed to remove template JSON file %q: %v\", templateFile, err)\n\t\t\t\t\t\tExpectWithOffset(1, templateFile).NotTo(BeAnExistingFile(), \"template JSON file %q was not removed\", templateFile)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tAssertVMCreationSuccess := func() func() {\n\t\t\treturn func() {\n\t\t\t\tBy(\"Creating VirtualMachine from Template via oc command\")\n\t\t\t\tocProcessCommand := []string{\"oc\", \"process\", \"-f\", templateFile}\n\t\t\t\tfor param, value := range templateParams {\n\t\t\t\t\tocProcessCommand = append(ocProcessCommand, \"-p\", fmt.Sprintf(\"%s=%s\", param, value))\n\t\t\t\t}\n\t\t\t\tout, stderr, err := tests.RunCommandPipe(ocProcessCommand, []string{\"oc\", \"create\", \"-f\", \"-\"})\n\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed to create VirtualMachine %q via command \\\"%s | oc create -f -\\\": %s: %v\", vmName, strings.Join(ocProcessCommand, \" \"), out+stderr, err)\n\t\t\t\tExpectWithOffset(1, out).To(MatchRegexp(`\"?%s\"? created\\n`, vmName), \"command \\\"%s | oc create -f -\\\" did not print expected message: %s\", strings.Join(ocProcessCommand, \" \"), out+stderr)\n\t\t\t\tBy(\"Checking if the VirtualMachine exists\")\n\t\t\t\tEventuallyWithOffset(1, func() error {\n\t\t\t\t\t_, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\t\treturn err\n\t\t\t\t}).Should(Succeed(), \"VirtualMachine %q still does not exist\", vmName)\n\t\t\t}\n\t\t}\n\n\t\tAssertVMCreationFailure := func() func() {\n\t\t\treturn func() {\n\t\t\t\tBy(\"Creating VirtualMachine from Template via oc command\")\n\t\t\t\tocProcessCommand := []string{\"oc\", \"process\", \"-f\", templateFile}\n\t\t\t\tfor param, value := range templateParams {\n\t\t\t\t\tocProcessCommand = append(ocProcessCommand, \"-p\", fmt.Sprintf(\"%s=%s\", param, value))\n\t\t\t\t}\n\t\t\t\tout, stderr, err := tests.RunCommandPipe(ocProcessCommand, []string{\"oc\", \"create\", \"-f\", \"-\"})\n\t\t\t\tExpectWithOffset(1, err).To(HaveOccurred(), \"creation of VirtualMachine %q via command \\\"%s | oc create -f -\\\" succeeded: %s: %v\", vmName, strings.Join(ocProcessCommand, \" \"), out+stderr, err)\n\t\t\t}\n\t\t}\n\n\t\tAssertVMDeletionSuccess := func() func() {\n\t\t\treturn func() {\n\t\t\t\tBy(\"Deleting the VirtualMachine via oc command\")\n\t\t\t\tout, stderr, err := tests.RunCommand(\"oc\", \"delete\", \"vm\", vmName)\n\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed to delete VirtualMachine via command \\\"oc delete vm %s\\\": %s: %v\", vmName, out+stderr, err)\n\t\t\t\tExpectWithOffset(1, out).To(MatchRegexp(`\"?%s\"? deleted\\n`, vmName), \"command \\\"oc delete vm %s\\\" did not print expected message: %s\", vmName, out)\n\n\t\t\t\tBy(\"Checking if the VM does not exist anymore\")\n\t\t\t\tEventuallyWithOffset(1, func() bool {\n\t\t\t\t\tvm, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\t\treturn errors.IsNotFound(err) || vm.ObjectMeta.DeletionTimestamp != nil\n\t\t\t\t}).Should(BeTrue(), \"the VirtualMachine %q still exists and deletion timestamp was not set\", vmName)\n\t\t\t}\n\t\t}\n\n\t\tAssertVMDeletionFailure := func() func() {\n\t\t\treturn func() {\n\t\t\t\tBy(\"Deleting the VirtualMachine via oc command\")\n\t\t\t\tout, stderr, err := tests.RunCommand(\"oc\", \"delete\", \"vm\", vmName)\n\t\t\t\tExpectWithOffset(1, err).To(HaveOccurred(), \"failed to delete VirtualMachine via command \\\"oc delete vm %s\\\": %s: %v\", vmName, out+stderr, err)\n\t\t\t}\n\t\t}\n\n\t\tAssertVMStartSuccess := func(command string) func() {\n\t\t\treturn func() {\n\t\t\t\tswitch command {\n\t\t\t\tcase \"oc\":\n\t\t\t\t\tBy(\"Starting VirtualMachine via oc command\")\n\t\t\t\t\tpatch := `{\"spec\":{\"running\":true}}`\n\t\t\t\t\tout, stderr, err := tests.RunCommand(\"oc\", \"patch\", \"vm\", vmName, \"--type=merge\", \"-p\", patch)\n\t\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed schedule VirtualMachine %q start via command \\\"oc patch vm %s --type=merge -p '%s'\\\": %s: %v\", vmName, vmName, patch, out+stderr, err)\n\t\t\t\t\tExpectWithOffset(1, out).To(MatchRegexp(`\"?%s\"? patched\\n`, vmName), \"command \\\"oc patch vm %s --type=merge -p '%s'\\\" did not print expected message: %s\", vmName, patch, out+stderr)\n\n\t\t\t\tcase \"virtctl\":\n\t\t\t\t\tBy(\"Starting VirtualMachine via virtctl command\")\n\t\t\t\t\tout, stderr, err := tests.RunCommand(\"virtctl\", \"start\", vmName)\n\t\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed to schedule VirtualMachine %q start via command \\\"virtctl start %s\\\": %s: %v\", vmName, vmName, out+stderr, err)\n\t\t\t\t\tExpectWithOffset(1, out).To(ContainSubstring(\"%s was scheduled to start\\n\", vmName), \"command \\\"virtctl start %s\\\" did not print expected message: %s\", vmName, out+stderr)\n\t\t\t\t}\n\n\t\t\t\tBy(\"Checking if the VirtualMachineInstance was created\")\n\t\t\t\tEventuallyWithOffset(1, func() error {\n\t\t\t\t\t_, err := virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\t\treturn err\n\t\t\t\t}).Should(Succeed(), \"the VirtualMachineInstance %q still does not exist\", vmName)\n\n\t\t\t\tBy(\"Checking if the VirtualMachine has status ready\")\n\t\t\t\tEventuallyWithOffset(1, func() bool {\n\t\t\t\t\tvm, err := virtClient.VirtualMachine(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed to fetch VirtualMachine %q: %v\", vmName, err)\n\t\t\t\t\treturn vm.Status.Ready\n\t\t\t\t}).Should(BeTrue(), \"VirtualMachine %q still does not have status ready\", vmName)\n\n\t\t\t\tBy(\"Checking if the VirtualMachineInstance specs match Template parameters\")\n\t\t\t\tvmi, err := virtClient.VirtualMachineInstance(tests.NamespaceTestDefault).Get(vmName, &metav1.GetOptions{})\n\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"failed to fetch VirtualMachine %q: %v\", vmName, err)\n\t\t\t\tvmiCPUCores := vmi.Spec.Domain.CPU.Cores\n\t\t\t\ttemplateParamCPUCores, err := strconv.ParseUint(templateParams[\"CPU_CORES\"], 10, 32)\n\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"cannot parse CPU_CORES parameter: value %q: %v\", templateParams[\"CPU_CORES\"], err)\n\t\t\t\tExpectWithOffset(1, vmiCPUCores).To(Equal(uint32(templateParamCPUCores)), \"VirtualMachineInstance CPU cores (%d) does not match CPU_CORES parameter value: %s\", vmiCPUCores, templateParams[\"CPU_CORES\"])\n\t\t\t\tvmiMemory := vmi.Spec.Domain.Resources.Requests[\"memory\"]\n\t\t\t\ttemplateParamMemory, err := resource.ParseQuantity(templateParams[\"MEMORY\"])\n\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"cannot parse MEMORY parameter: value %q: %v\", templateParams[\"MEMORY\"], err)\n\t\t\t\tExpectWithOffset(1, vmiMemory).To(Equal(templateParamMemory), \"VirtualMachineInstance memory (%s) does not match MEMORY parameter value: %s\", vmiMemory.String(), templateParams[\"MEMORY\"])\n\t\t\t}\n\t\t}\n\n\t\tAssertTemplateTestSuccess := func() {\n\t\t\tIt(\"[test_id:3292]should succeed to create VirtualMachine via oc command\", AssertVMCreationSuccess())\n\t\t\tIt(\"[test_id:3293]should fail to delete VirtualMachine via oc command\", AssertVMDeletionFailure())\n\n\t\t\tWhen(\"the VirtualMachine was created\", func() {\n\t\t\t\tBeforeEach(AssertVMCreationSuccess())\n\t\t\t\tIt(\"[test_id:3294]should succeed to start the VirtualMachine via oc command\", AssertVMStartSuccess(\"oc\"))\n\t\t\t\tIt(\"[test_id:3295]should succeed to delete VirtualMachine via oc command\", AssertVMDeletionSuccess())\n\t\t\t\tIt(\"[test_id:3308]should fail to create the same VirtualMachine via oc command\", AssertVMCreationFailure())\n\t\t\t})\n\t\t}\n\n\t\tBeforeEach(AssertTestSetupSuccess())\n\n\t\tAfterEach(AssertTestCleanupSuccess())\n\n\t\tContext(\"with Fedora Template\", func() {\n\t\t\tBeforeEach(AssertTemplateSetupSuccess(vmsgen.GetTemplateFedoraWithContainerDisk(tests.ContainerDiskFor(tests.ContainerDiskFedora)), nil))\n\n\t\t\tAssertTemplateTestSuccess()\n\t\t})\n\n\t\tContext(\"[rfe_id:273][crit:medium][vendor:cnv-qe@redhat.com][level:component]with RHEL Template\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\ttests.SkipIfNoRhelImage(virtClient)\n\t\t\t\tAssertTemplateSetupSuccess(vmsgen.GetTestTemplateRHEL7(), nil)()\n\t\t\t})\n\n\t\t\tAssertTemplateTestSuccess()\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n    \"bufio\"\n    \"os\"\n    \"fmt\"\n    \"io\/ioutil\"\n    \"net\/http\"\n    \"strings\"\n    \"encoding\/json\"\n    \"strconv\"\n)\n\nconst delim = '\\n'\n\nfunc check(e error) {\n    if e != nil {\n        panic(e)\n    }\n}\n\nfunc main() {\n\n  var token string = os.Getenv(\"GH_TOKEN_ALLI\") \/\/ env var name\n  var home string = os.Getenv(\"HOME\") \/\/ env var name\n\n  if token == \"\" {\n    fmt.Printf(\"No token found! Using highly rate-limited public access.\\n\")\n  } else {\n    fmt.Printf(\"Yay! Using authentication token!\\n\")\n  }\n\n  r := bufio.NewReader(os.Stdin)\n\n  var username string\n  saved_username, err := ioutil.ReadFile(home + \"\/.alli\")\n\n  if string(saved_username) == \"\" {\n    print(\"Enter Github username: \")\n    username, err = r.ReadString(delim)\n    username = strings.TrimSpace(username)\n    check(err)\n\n    fmt.Printf(\"Would you like to save %s as the default? (y\/n): \", username)\n    response, err := r.ReadString(delim)\n    check(err)\n    if response == \"y\\n\" {\n      \/\/ write username to save\n      d1 := []byte(username)\n      ioutil.WriteFile(home + \"\/.alli\", d1, 0644)\n    }\n  } else {\n    username = strings.TrimSpace(string(saved_username))\n    fmt.Printf(\"Using saved username: %s\\n\", username)\n  }\n\n  client := &http.Client{}\n  var anotherPage bool = true\n  pageNum := 1\n  for anotherPage {\n    req, _ := http.NewRequest(\"GET\", \"https:\/\/api.github.com\/users\/\" + username + \"\/repos?per_page=100&page=\" + strconv.Itoa(pageNum), nil)\n    req.Header.Set(\"Accept\", \"application\/vnd.github.v3+json\")\n\n    if token != \"\" {\n      req.SetBasicAuth(token, \"x-oauth-basic\") \/\/ user, password\n    }\n\n    repos, err := client.Do(req)\n    check(err)\n\n    defer repos.Body.Close()\n    contents, err := ioutil.ReadAll(repos.Body);\n    check(err)\n\n    byt := []byte(contents)\n\n    var f interface{}\n    err = json.Unmarshal(byt, &f)\n    check(err)\n\n    array := f.([]interface {})\n    pageNum++\n    if(len(array) == 100) {\n      anotherPage = true\n    } else {\n      anotherPage = false\n    }\n\n    println()\n\n    for i := range array {\n      repo := array[i].(map[string]interface {})\n      var countFloat float64 = repo[\"open_issues_count\"].(float64)\n      var countInt int = int(countFloat)\n      if(countInt != 0) {\n        var name string = repo[\"full_name\"].(string)\n        fmt.Printf(\"%s\\n\", name)\n\n        req, _ = http.NewRequest(\"GET\", \"https:\/\/api.github.com\/repos\/\" + name + \"\/issues?state=open\", nil)\n        req.Header.Set(\"Accept\", \"application\/vnd.github.v3+json\")\n        if token != \"\" {\n          req.SetBasicAuth(token, \"x-oauth-basic\") \/\/ user, password\n        }\n        issues, err := client.Do(req)\n        check(err)\n\n        defer issues.Body.Close()\n        iss, err := ioutil.ReadAll(issues.Body);\n        check(err)\n\n        byt = [] byte(iss)\n        var g interface{}\n        err = json.Unmarshal(byt, &g)\n        check(err)\n\n        issue_array := g.([]interface {})\n\n        for j := range issue_array {\n          issue := issue_array[j].(map[string]interface {})\n          var number int = int(issue[\"number\"].(float64))\n          var title string = issue[\"title\"].(string)\n          fmt.Printf(\"#%d %s\\n\", number, title)\n        }\n        fmt.Printf(\"\\n\");\n      }\n    }\n  }\n}\n<commit_msg>Go fmt<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst delim = '\\n'\n\nfunc check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\nfunc main() {\n\n\tvar token string = os.Getenv(\"GH_TOKEN_ALLI\") \/\/ env var name\n\tvar home string = os.Getenv(\"HOME\")           \/\/ env var name\n\n\tif token == \"\" {\n\t\tfmt.Printf(\"No token found! Using highly rate-limited public access.\\n\")\n\t} else {\n\t\tfmt.Printf(\"Yay! Using authentication token!\\n\")\n\t}\n\n\tr := bufio.NewReader(os.Stdin)\n\n\tvar username string\n\tsaved_username, err := ioutil.ReadFile(home + \"\/.alli\")\n\n\tif string(saved_username) == \"\" {\n\t\tprint(\"Enter Github username: \")\n\t\tusername, err = r.ReadString(delim)\n\t\tusername = strings.TrimSpace(username)\n\t\tcheck(err)\n\n\t\tfmt.Printf(\"Would you like to save %s as the default? (y\/n): \", username)\n\t\tresponse, err := r.ReadString(delim)\n\t\tcheck(err)\n\t\tif response == \"y\\n\" {\n\t\t\t\/\/ write username to save\n\t\t\td1 := []byte(username)\n\t\t\tioutil.WriteFile(home+\"\/.alli\", d1, 0644)\n\t\t}\n\t} else {\n\t\tusername = strings.TrimSpace(string(saved_username))\n\t\tfmt.Printf(\"Using saved username: %s\\n\", username)\n\t}\n\n\tclient := &http.Client{}\n\tvar anotherPage bool = true\n\tpageNum := 1\n\tfor anotherPage {\n\t\treq, _ := http.NewRequest(\"GET\", \"https:\/\/api.github.com\/users\/\"+username+\"\/repos?per_page=100&page=\"+strconv.Itoa(pageNum), nil)\n\t\treq.Header.Set(\"Accept\", \"application\/vnd.github.v3+json\")\n\n\t\tif token != \"\" {\n\t\t\treq.SetBasicAuth(token, \"x-oauth-basic\") \/\/ user, password\n\t\t}\n\n\t\trepos, err := client.Do(req)\n\t\tcheck(err)\n\n\t\tdefer repos.Body.Close()\n\t\tcontents, err := ioutil.ReadAll(repos.Body)\n\t\tcheck(err)\n\n\t\tbyt := []byte(contents)\n\n\t\tvar f interface{}\n\t\terr = json.Unmarshal(byt, &f)\n\t\tcheck(err)\n\n\t\tarray := f.([]interface{})\n\t\tpageNum++\n\t\tif len(array) == 100 {\n\t\t\tanotherPage = true\n\t\t} else {\n\t\t\tanotherPage = false\n\t\t}\n\n\t\tprintln()\n\n\t\tfor i := range array {\n\t\t\trepo := array[i].(map[string]interface{})\n\t\t\tvar countFloat float64 = repo[\"open_issues_count\"].(float64)\n\t\t\tvar countInt int = int(countFloat)\n\t\t\tif countInt != 0 {\n\t\t\t\tvar name string = repo[\"full_name\"].(string)\n\t\t\t\tfmt.Printf(\"%s\\n\", name)\n\n\t\t\t\treq, _ = http.NewRequest(\"GET\", \"https:\/\/api.github.com\/repos\/\"+name+\"\/issues?state=open\", nil)\n\t\t\t\treq.Header.Set(\"Accept\", \"application\/vnd.github.v3+json\")\n\t\t\t\tif token != \"\" {\n\t\t\t\t\treq.SetBasicAuth(token, \"x-oauth-basic\") \/\/ user, password\n\t\t\t\t}\n\t\t\t\tissues, err := client.Do(req)\n\t\t\t\tcheck(err)\n\n\t\t\t\tdefer issues.Body.Close()\n\t\t\t\tiss, err := ioutil.ReadAll(issues.Body)\n\t\t\t\tcheck(err)\n\n\t\t\t\tbyt = []byte(iss)\n\t\t\t\tvar g interface{}\n\t\t\t\terr = json.Unmarshal(byt, &g)\n\t\t\t\tcheck(err)\n\n\t\t\t\tissue_array := g.([]interface{})\n\n\t\t\t\tfor j := range issue_array {\n\t\t\t\t\tissue := issue_array[j].(map[string]interface{})\n\t\t\t\t\tvar number int = int(issue[\"number\"].(float64))\n\t\t\t\t\tvar title string = issue[\"title\"].(string)\n\t\t\t\t\tfmt.Printf(\"#%d %s\\n\", number, title)\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"\\n\")\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2020 Docker, Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage volume\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/hashicorp\/go-multierror\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/docker\/compose-cli\/aci\"\n\t\"github.com\/docker\/compose-cli\/api\/client\"\n\t\"github.com\/docker\/compose-cli\/progress\"\n)\n\n\/\/ ACICommand manage volumes\nfunc ACICommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"volume\",\n\t\tShort: \"Manages volumes\",\n\t}\n\n\tcmd.AddCommand(\n\t\tcreateVolume(),\n\t\tlistVolume(),\n\t\trmVolume(),\n\t)\n\treturn cmd\n}\n\nfunc createVolume() *cobra.Command {\n\taciOpts := aci.VolumeCreateOptions{}\n\tcmd := &cobra.Command{\n\t\tUse:   \"create\",\n\t\tShort: \"Creates an Azure file share to use as ACI volume.\",\n\t\tArgs:  cobra.ExactArgs(0),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx := cmd.Context()\n\t\t\tc, err := client.New(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = progress.Run(ctx, func(ctx context.Context) error {\n\t\t\t\tif _, err := c.VolumeService().Create(ctx, aciOpts); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfmt.Println(aci.VolumeID(aciOpts.Account, aciOpts.Fileshare))\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcmd.Flags().StringVar(&aciOpts.Account, \"storage-account\", \"\", \"Storage account name\")\n\tcmd.Flags().StringVar(&aciOpts.Fileshare, \"fileshare\", \"\", \"Fileshare name\")\n\treturn cmd\n}\n\nfunc rmVolume() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"rm [OPTIONS] VOLUME [VOLUME...]\",\n\t\tShort: \"Remove one or more volumes.\",\n\t\tArgs:  cobra.MinimumNArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tc, err := client.New(cmd.Context())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvar errs *multierror.Error\n\t\t\tfor _, id := range args {\n\t\t\t\terr = c.VolumeService().Delete(cmd.Context(), id, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrs = multierror.Append(errs, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfmt.Println(id)\n\t\t\t}\n\t\t\tif errs != nil {\n\t\t\t\terrs.ErrorFormat = formatErrors\n\t\t\t}\n\t\t\treturn errs.ErrorOrNil()\n\t\t},\n\t}\n\treturn cmd\n}\n\nfunc formatErrors(errs []error) string {\n\tmessages := make([]string, len(errs))\n\tfor i, err := range errs {\n\t\tmessages[i] = \"Error: \" + err.Error()\n\t}\n\treturn strings.Join(messages, \"\\n\")\n}\n<commit_msg>ACI Volume create flags are required<commit_after>\/*\n   Copyright 2020 Docker, Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage volume\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/hashicorp\/go-multierror\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/docker\/compose-cli\/aci\"\n\t\"github.com\/docker\/compose-cli\/api\/client\"\n\t\"github.com\/docker\/compose-cli\/progress\"\n)\n\n\/\/ ACICommand manage volumes\nfunc ACICommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"volume\",\n\t\tShort: \"Manages volumes\",\n\t}\n\n\tcmd.AddCommand(\n\t\tcreateVolume(),\n\t\tlistVolume(),\n\t\trmVolume(),\n\t)\n\treturn cmd\n}\n\nfunc createVolume() *cobra.Command {\n\taciOpts := aci.VolumeCreateOptions{}\n\tcmd := &cobra.Command{\n\t\tUse:   \"create --storage-account ACCOUNT --fileshare FILESHARE\",\n\t\tShort: \"Creates an Azure file share to use as ACI volume.\",\n\t\tArgs:  cobra.ExactArgs(0),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tctx := cmd.Context()\n\t\t\tc, err := client.New(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = progress.Run(ctx, func(ctx context.Context) error {\n\t\t\t\tif _, err := c.VolumeService().Create(ctx, aciOpts); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfmt.Println(aci.VolumeID(aciOpts.Account, aciOpts.Fileshare))\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcmd.Flags().StringVar(&aciOpts.Account, \"storage-account\", \"\", \"Storage account name\")\n\tcmd.Flags().StringVar(&aciOpts.Fileshare, \"fileshare\", \"\", \"Fileshare name\")\n\t_ = cmd.MarkFlagRequired(\"fileshare\")\n\t_ = cmd.MarkFlagRequired(\"storage-account\")\n\treturn cmd\n}\n\nfunc rmVolume() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"rm [OPTIONS] VOLUME [VOLUME...]\",\n\t\tShort: \"Remove one or more volumes.\",\n\t\tArgs:  cobra.MinimumNArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tc, err := client.New(cmd.Context())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvar errs *multierror.Error\n\t\t\tfor _, id := range args {\n\t\t\t\terr = c.VolumeService().Delete(cmd.Context(), id, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrs = multierror.Append(errs, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfmt.Println(id)\n\t\t\t}\n\t\t\tif errs != nil {\n\t\t\t\terrs.ErrorFormat = formatErrors\n\t\t\t}\n\t\t\treturn errs.ErrorOrNil()\n\t\t},\n\t}\n\treturn cmd\n}\n\nfunc formatErrors(errs []error) string {\n\tmessages := make([]string, len(errs))\n\tfor i, err := range errs {\n\t\tmessages[i] = \"Error: \" + err.Error()\n\t}\n\treturn strings.Join(messages, \"\\n\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"github.com\/gtfierro\/cs262-project\/common\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/tinylib\/msgp\/msgp\"\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype BrokerConnection struct {\n\t\/\/ Handling the connection to the local broker\n\t\/\/ the IP:Port of the local broker we talk to\n\tBrokerAddress    *net.TCPAddr\n\tbrokerConn       *net.TCPConn\n\tbrokerEncoder    *msgp.Writer\n\tbrokerEncodeLock sync.Mutex\n\n\t\/\/ the IP:Port of the coordinator that we fall back to\n\tCoordinatorAddress *net.TCPAddr\n\tcoordConn          *net.TCPConn\n\tcoordEncoder       *msgp.Writer\n\tcoordEncodeLock    sync.Mutex\n\n\t\/\/ signals on this channel when it is done\n\tStop       chan bool\n\tbrokerDead bool\n\n\tconnectCallback func()\n\tmsgHandler      func(common.Sendable)\n}\n\nfunc (bc *BrokerConnection) initialize(connectCallback func(), msgHandler func(common.Sendable), cfg *Config) (err error) {\n\tbc.brokerDead = true\n\tbc.connectCallback = connectCallback\n\tbc.msgHandler = msgHandler\n\tbc.Stop = make(chan bool)\n\n\tif bc.BrokerAddress, err = net.ResolveTCPAddr(\"tcp\", cfg.BrokerAddress); err != nil {\n\t\treturn\n\t}\n\n\tif err = bc.connectBroker(bc.BrokerAddress); err != nil {\n\t\treturn\n\t}\n\n\tbc.CoordinatorAddress, err = net.ResolveTCPAddr(\"tcp\", cfg.CoordinatorAddress)\n\treturn\n}\n\nfunc (bc *BrokerConnection) Start() {\n\tgo bc.listen()\n\tbc.connectCallback()\n}\n\n\/\/ after the duration expires, stop the client by signalling on c.Stop\nfunc (bc *BrokerConnection) StopIn(d time.Duration) {\n\tgo func(c *BrokerConnection) {\n\t\ttime.Sleep(d)\n\t\tc.Stop <- true\n\t}(bc)\n}\n\nfunc (bc *BrokerConnection) listen() {\n\treader := msgp.NewReader(net.Conn(bc.brokerConn))\n\tfor {\n\t\tif bc.brokerDead {\n\t\t\treturn\n\t\t}\n\t\tmsg, err := common.MessageFromDecoderMsgp(reader)\n\t\tif err == io.EOF {\n\t\t\tlog.Warn(\"connection closed. Do failover\")\n\t\t\tbc.doFailover()\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Warn(errors.Wrap(err, \"Could not decode message\"))\n\t\t}\n\n\t\tbc.msgHandler(msg)\n\t}\n}\n\n\/\/ This function should contact the coordinator to get the new broker\nfunc (bc *BrokerConnection) configureNewBroker(m *common.BrokerAssignmentMessage) {\n\tvar err error\n\tbc.BrokerAddress, err = net.ResolveTCPAddr(\"tcp\", m.ClientBrokerAddr)\n\tif err != nil {\n\t\tlog.Critical(errors.Wrap(err, \"Could not resolve local broker address\"))\n\t}\n\tif err = bc.connectBroker(bc.BrokerAddress); err != nil {\n\t\tlog.Critical(errors.Wrap(err, \"Could not connect to local broker\"))\n\t}\n\t\/\/ send our subscription once we're back\n\tbc.connectCallback()\n\tgo bc.listen()\n}\n\nfunc (bc *BrokerConnection) connectBroker(address *net.TCPAddr) error {\n\tvar err error\n\tif bc.brokerConn, err = net.DialTCP(\"tcp\", nil, address); err != nil {\n\t\treturn errors.Wrap(err, \"Could not dial broker\")\n\t}\n\tbc.brokerEncodeLock.Lock()\n\tbc.brokerEncoder = msgp.NewWriter(bc.brokerConn)\n\tbc.brokerEncodeLock.Unlock()\n\tbc.brokerDead = false\n\treturn nil\n}\n\n\/\/ Sends message to the currently configured broker\nfunc (bc *BrokerConnection) sendBroker(m common.Sendable) error {\n\tbc.brokerEncodeLock.Lock()\n\tdefer bc.brokerEncodeLock.Unlock()\n\tif err := m.Encode(bc.brokerEncoder); err != nil {\n\t\treturn errors.Wrap(err, \"Could not encode message\")\n\t}\n\tif err := bc.brokerEncoder.Flush(); err != nil {\n\t\treturn errors.Wrap(err, \"Could not send message to broker\")\n\t}\n\treturn nil\n}\n\n\/\/ This should be triggered when we can no longer contact our local broker. In this\n\/\/ case, we sent a BrokerRequestMessage to the coordinator\nfunc (bc *BrokerConnection) doFailover() {\n\tbc.brokerDead = true\n\t\/\/ establish the coordinator connection\n\tbc.connectCoordinator()\n\t\/\/ prepare the BrokerRequestMessage\n\tbrm := &common.BrokerRequestMessage{\n\t\tLocalBrokerAddr: bc.BrokerAddress.String(),\n\t\tIsPublisher:     false,                                  \/\/ TODO\n\t\tUUID:            \"392c1b18-0c37-11e6-b352-1002b58053c7\", \/\/ TODO\n\t}\n\t\/\/ loop until we can contact the coordinator\n\terr := bc.sendCoordinator(brm)\n\tfor err != nil {\n\t\ttime.Sleep(1)\n\t\terr = bc.sendCoordinator(brm)\n\t}\n}\n\n\/\/ Loop until we can finally connect to the coordinator.\n\/\/ This blocks indefinitely until it is successful\nfunc (bc *BrokerConnection) connectCoordinator() {\n\tvar (\n\t\terr      error\n\t\twaitTime = 1 * time.Second\n\t\tmaxWait  = 30 * time.Second\n\t)\n\tbc.coordConn, err = net.DialTCP(\"tcp\", nil, bc.CoordinatorAddress)\n\tfor err != nil {\n\t\tlog.Warningf(\"Retrying coordinator connection to %v with delay %v\", bc.CoordinatorAddress, waitTime)\n\t\ttime.Sleep(waitTime)\n\t\twaitTime *= 2\n\t\tif waitTime > maxWait {\n\t\t\twaitTime = maxWait\n\t\t}\n\t\tbc.coordConn, err = net.DialTCP(\"tcp\", nil, bc.CoordinatorAddress)\n\t}\n\tlog.Debug(\"Connected to coordinator\")\n\tgo bc.listenCoordinator()\n\tbc.coordEncoder = msgp.NewWriter(bc.coordConn)\n}\n\nfunc (bc *BrokerConnection) listenCoordinator() {\n\tif bc.coordConn == nil {\n\t\treturn\n\t}\n\treader := msgp.NewReader(net.Conn(bc.coordConn))\n\tfor {\n\t\tmsg, err := common.MessageFromDecoderMsgp(reader)\n\t\tif err == io.EOF {\n\t\t\tlog.Warn(\"connection closed. Do failover\")\n\t\t\tbc.doFailover()\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Warn(errors.Wrap(err, \"Could not decode message\"))\n\t\t}\n\n\t\tlog.Infof(\"Got %T message %v from coordinator\", msg, msg)\n\t\tswitch m := msg.(type) {\n\t\tcase *common.BrokerAssignmentMessage:\n\t\t\tbc.configureNewBroker(m)\n\t\t\tbc.coordConn.Close()\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Infof(\"Got %T message %v from coordinator\", m, m)\n\t\t}\n\t}\n}\n\nfunc (bc *BrokerConnection) sendCoordinator(m common.Sendable) error {\n\tbc.coordEncodeLock.Lock()\n\tif err := m.Encode(bc.coordEncoder); err != nil {\n\t\tbc.coordEncodeLock.Unlock()\n\t\treturn errors.Wrap(err, \"Could not encode message\")\n\t}\n\tif err := bc.coordEncoder.Flush(); err != nil {\n\t\tbc.coordEncodeLock.Unlock()\n\t\tbc.connectCoordinator()\n\t\treturn errors.Wrap(err, \"Could not send message to coordinator\")\n\t}\n\tbc.coordEncodeLock.Unlock()\n\treturn nil\n}\n<commit_msg>Fix issue with host names<commit_after>package client\n\nimport (\n\t\"github.com\/gtfierro\/cs262-project\/common\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/tinylib\/msgp\/msgp\"\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype BrokerConnection struct {\n\t\/\/ Handling the connection to the local broker\n\t\/\/ the IP:Port of the local broker we talk to\n\tBrokerAddrStr    string\n\tBrokerAddress    *net.TCPAddr\n\tbrokerConn       *net.TCPConn\n\tbrokerEncoder    *msgp.Writer\n\tbrokerEncodeLock sync.Mutex\n\n\t\/\/ the IP:Port of the coordinator that we fall back to\n\tCoordinatorAddress *net.TCPAddr\n\tcoordConn          *net.TCPConn\n\tcoordEncoder       *msgp.Writer\n\tcoordEncodeLock    sync.Mutex\n\n\t\/\/ signals on this channel when it is done\n\tStop       chan bool\n\tbrokerDead bool\n\n\tconnectCallback func()\n\tmsgHandler      func(common.Sendable)\n}\n\nfunc (bc *BrokerConnection) initialize(connectCallback func(), msgHandler func(common.Sendable), cfg *Config) (err error) {\n\tbc.brokerDead = true\n\tbc.connectCallback = connectCallback\n\tbc.msgHandler = msgHandler\n\tbc.Stop = make(chan bool)\n\tbc.BrokerAddrStr = cfg.BrokerAddress\n\n\tif bc.BrokerAddress, err = net.ResolveTCPAddr(\"tcp\", cfg.BrokerAddress); err != nil {\n\t\treturn\n\t}\n\n\tif err = bc.connectBroker(bc.BrokerAddress); err != nil {\n\t\treturn\n\t}\n\n\tbc.CoordinatorAddress, err = net.ResolveTCPAddr(\"tcp\", cfg.CoordinatorAddress)\n\treturn\n}\n\nfunc (bc *BrokerConnection) Start() {\n\tgo bc.listen()\n\tbc.connectCallback()\n}\n\n\/\/ after the duration expires, stop the client by signalling on c.Stop\nfunc (bc *BrokerConnection) StopIn(d time.Duration) {\n\tgo func(c *BrokerConnection) {\n\t\ttime.Sleep(d)\n\t\tc.Stop <- true\n\t}(bc)\n}\n\nfunc (bc *BrokerConnection) listen() {\n\treader := msgp.NewReader(net.Conn(bc.brokerConn))\n\tfor {\n\t\tif bc.brokerDead {\n\t\t\treturn\n\t\t}\n\t\tmsg, err := common.MessageFromDecoderMsgp(reader)\n\t\tif err == io.EOF {\n\t\t\tlog.Warn(\"connection closed. Do failover\")\n\t\t\tbc.doFailover()\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Warn(errors.Wrap(err, \"Could not decode message\"))\n\t\t}\n\n\t\tbc.msgHandler(msg)\n\t}\n}\n\n\/\/ This function should contact the coordinator to get the new broker\nfunc (bc *BrokerConnection) configureNewBroker(m *common.BrokerAssignmentMessage) {\n\tvar err error\n\tbc.BrokerAddress, err = net.ResolveTCPAddr(\"tcp\", m.ClientBrokerAddr)\n\tif err != nil {\n\t\tlog.Critical(errors.Wrap(err, \"Could not resolve local broker address\"))\n\t}\n\tif err = bc.connectBroker(bc.BrokerAddress); err != nil {\n\t\tlog.Critical(errors.Wrap(err, \"Could not connect to local broker\"))\n\t}\n\t\/\/ send our subscription once we're back\n\tbc.connectCallback()\n\tgo bc.listen()\n}\n\nfunc (bc *BrokerConnection) connectBroker(address *net.TCPAddr) error {\n\tvar err error\n\tif bc.brokerConn, err = net.DialTCP(\"tcp\", nil, address); err != nil {\n\t\treturn errors.Wrap(err, \"Could not dial broker\")\n\t}\n\tbc.brokerEncodeLock.Lock()\n\tbc.brokerEncoder = msgp.NewWriter(bc.brokerConn)\n\tbc.brokerEncodeLock.Unlock()\n\tbc.brokerDead = false\n\treturn nil\n}\n\n\/\/ Sends message to the currently configured broker\nfunc (bc *BrokerConnection) sendBroker(m common.Sendable) error {\n\tbc.brokerEncodeLock.Lock()\n\tdefer bc.brokerEncodeLock.Unlock()\n\tif err := m.Encode(bc.brokerEncoder); err != nil {\n\t\treturn errors.Wrap(err, \"Could not encode message\")\n\t}\n\tif err := bc.brokerEncoder.Flush(); err != nil {\n\t\treturn errors.Wrap(err, \"Could not send message to broker\")\n\t}\n\treturn nil\n}\n\n\/\/ This should be triggered when we can no longer contact our local broker. In this\n\/\/ case, we sent a BrokerRequestMessage to the coordinator\nfunc (bc *BrokerConnection) doFailover() {\n\tbc.brokerDead = true\n\t\/\/ establish the coordinator connection\n\tbc.connectCoordinator()\n\t\/\/ prepare the BrokerRequestMessage\n\tbrm := &common.BrokerRequestMessage{\n\t\tLocalBrokerAddr: bc.BrokerAddrStr,\n\t\tIsPublisher:     false,                                  \/\/ TODO\n\t\tUUID:            \"392c1b18-0c37-11e6-b352-1002b58053c7\", \/\/ TODO\n\t}\n\t\/\/ loop until we can contact the coordinator\n\terr := bc.sendCoordinator(brm)\n\tfor err != nil {\n\t\ttime.Sleep(1)\n\t\terr = bc.sendCoordinator(brm)\n\t}\n}\n\n\/\/ Loop until we can finally connect to the coordinator.\n\/\/ This blocks indefinitely until it is successful\nfunc (bc *BrokerConnection) connectCoordinator() {\n\tvar (\n\t\terr      error\n\t\twaitTime = 1 * time.Second\n\t\tmaxWait  = 30 * time.Second\n\t)\n\tbc.coordConn, err = net.DialTCP(\"tcp\", nil, bc.CoordinatorAddress)\n\tfor err != nil {\n\t\tlog.Warningf(\"Retrying coordinator connection to %v with delay %v\", bc.CoordinatorAddress, waitTime)\n\t\ttime.Sleep(waitTime)\n\t\twaitTime *= 2\n\t\tif waitTime > maxWait {\n\t\t\twaitTime = maxWait\n\t\t}\n\t\tbc.coordConn, err = net.DialTCP(\"tcp\", nil, bc.CoordinatorAddress)\n\t}\n\tlog.Debug(\"Connected to coordinator\")\n\tgo bc.listenCoordinator()\n\tbc.coordEncoder = msgp.NewWriter(bc.coordConn)\n}\n\nfunc (bc *BrokerConnection) listenCoordinator() {\n\tif bc.coordConn == nil {\n\t\treturn\n\t}\n\treader := msgp.NewReader(net.Conn(bc.coordConn))\n\tfor {\n\t\tmsg, err := common.MessageFromDecoderMsgp(reader)\n\t\tif err == io.EOF {\n\t\t\tlog.Warn(\"connection closed. Do failover\")\n\t\t\tbc.doFailover()\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Warn(errors.Wrap(err, \"Could not decode message\"))\n\t\t}\n\n\t\tlog.Infof(\"Got %T message %v from coordinator\", msg, msg)\n\t\tswitch m := msg.(type) {\n\t\tcase *common.BrokerAssignmentMessage:\n\t\t\tbc.configureNewBroker(m)\n\t\t\tbc.coordConn.Close()\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Infof(\"Got %T message %v from coordinator\", m, m)\n\t\t}\n\t}\n}\n\nfunc (bc *BrokerConnection) sendCoordinator(m common.Sendable) error {\n\tbc.coordEncodeLock.Lock()\n\tif err := m.Encode(bc.coordEncoder); err != nil {\n\t\tbc.coordEncodeLock.Unlock()\n\t\treturn errors.Wrap(err, \"Could not encode message\")\n\t}\n\tif err := bc.coordEncoder.Flush(); err != nil {\n\t\tbc.coordEncodeLock.Unlock()\n\t\tbc.connectCoordinator()\n\t\treturn errors.Wrap(err, \"Could not send message to coordinator\")\n\t}\n\tbc.coordEncodeLock.Unlock()\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The LUCI Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/maruel\/subcommands\"\n)\n\nfunc cmdCheck() *subcommands.Command {\n\treturn &subcommands.Command{\n\t\tUsageLine: \"check <options>\",\n\t\tShortDesc: \"checks that all the inputs are present and generates .isolated\",\n\t\tLongDesc:  \"\",\n\t\tCommandRun: func() subcommands.CommandRun {\n\t\t\tc := checkRun{}\n\t\t\tc.commonFlags.Init()\n\t\t\tc.isolateFlags.Init(&c.Flags)\n\t\t\treturn &c\n\t\t},\n\t}\n}\n\ntype checkRun struct {\n\tcommonFlags\n\tisolateFlags\n}\n\nfunc (c *checkRun) Parse(a subcommands.Application, args []string) error {\n\tif err := c.commonFlags.Parse(); err != nil {\n\t\treturn err\n\t}\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := c.isolateFlags.Parse(cwd, RequireIsolatedFile|RequireIsolateFile); err != nil {\n\t\treturn err\n\t}\n\tif len(args) != 0 {\n\t\treturn errors.New(\"position arguments not expected\")\n\t}\n\treturn nil\n}\n\nfunc (c *checkRun) main(a subcommands.Application, args []string) error {\n\tif !c.defaultFlags.Quiet {\n\t\tfmt.Printf(\"Isolate:   %s\\n\", c.Isolate)\n\t\tfmt.Printf(\"Isolated:  %s\\n\", c.Isolated)\n\t\tfmt.Printf(\"Blacklist: %s\\n\", c.Blacklist)\n\t\tfmt.Printf(\"Config:    %s\\n\", c.ConfigVariables)\n\t\tfmt.Printf(\"Path:      %s\\n\", c.PathVariables)\n\t\tfmt.Printf(\"Extra:     %s\\n\", c.ExtraVariables)\n\t}\n\treturn errors.New(\"TODO\")\n}\n\nfunc (c *checkRun) Run(a subcommands.Application, args []string, _ subcommands.Env) int {\n\tif err := c.Parse(a, args); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tcl, err := c.defaultFlags.StartTracing()\n\tif err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tdefer cl.Close()\n\tif err := c.main(a, args); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\treturn 0\n}\n<commit_msg>isolate: implement check<commit_after>\/\/ Copyright 2015 The LUCI Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/maruel\/subcommands\"\n\t\"go.chromium.org\/luci\/client\/isolate\"\n\t\"go.chromium.org\/luci\/common\/errors\"\n)\n\nfunc cmdCheck() *subcommands.Command {\n\treturn &subcommands.Command{\n\t\tUsageLine: \"check <options>\",\n\t\tShortDesc: \"checks that all the inputs are present\",\n\t\tLongDesc:  \"\",\n\t\tCommandRun: func() subcommands.CommandRun {\n\t\t\tc := checkRun{}\n\t\t\tc.commonFlags.Init()\n\t\t\tc.isolateFlags.Init(&c.Flags)\n\t\t\treturn &c\n\t\t},\n\t}\n}\n\ntype checkRun struct {\n\tcommonFlags\n\tisolateFlags\n}\n\nfunc (c *checkRun) Parse(a subcommands.Application, args []string) error {\n\tif err := c.commonFlags.Parse(); err != nil {\n\t\treturn err\n\t}\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := c.isolateFlags.Parse(cwd, RequireIsolatedFile|RequireIsolateFile); err != nil {\n\t\treturn err\n\t}\n\tif len(args) != 0 {\n\t\treturn errors.Reason(\"position arguments not expected\").Err()\n\t}\n\treturn nil\n}\n\nfunc (c *checkRun) main(a subcommands.Application, args []string) error {\n\tif !c.defaultFlags.Quiet {\n\t\tfmt.Printf(\"Isolate:   %s\\n\", c.Isolate)\n\t\tfmt.Printf(\"Isolated:  %s\\n\", c.Isolated)\n\t\tfmt.Printf(\"Blacklist: %s\\n\", c.Blacklist)\n\t\tfmt.Printf(\"Config:    %s\\n\", c.ConfigVariables)\n\t\tfmt.Printf(\"Path:      %s\\n\", c.PathVariables)\n\t\tfmt.Printf(\"Extra:     %s\\n\", c.ExtraVariables)\n\t}\n\n\tdeps, _, _, err := isolate.ProcessIsolate(&c.ArchiveOptions)\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"failed to process isolate\").Err()\n\t}\n\n\tfor _, dep := range deps {\n\t\t_, err := os.Stat(dep)\n\t\tif err != nil {\n\t\t\treturn errors.Annotate(err, \"failed to stat input file: %s\", dep).Err()\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (c *checkRun) Run(a subcommands.Application, args []string, _ subcommands.Env) int {\n\tif err := c.Parse(a, args); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tcl, err := c.defaultFlags.StartTracing()\n\tif err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tdefer cl.Close()\n\tif err := c.main(a, args); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\treturn 0\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 The LUCI Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\n\t\"google.golang.org\/api\/googleapi\"\n\n\t\"github.com\/maruel\/subcommands\"\n\n\t\"go.chromium.org\/luci\/auth\"\n\t\"go.chromium.org\/luci\/common\/api\/swarming\/swarming\/v1\"\n\t\"go.chromium.org\/luci\/common\/errors\"\n\t\"go.chromium.org\/luci\/common\/flag\"\n\t\"go.chromium.org\/luci\/common\/system\/signals\"\n)\n\nfunc cmdBots(defaultAuthOpts auth.Options) *subcommands.Command {\n\treturn &subcommands.Command{\n\t\tUsageLine: \"bots <options>\",\n\t\tShortDesc: \"lists bots\",\n\t\tLongDesc:  \"List bots matching the given options.\",\n\t\tCommandRun: func() subcommands.CommandRun {\n\t\t\tr := &botsRun{}\n\t\t\tr.Init(defaultAuthOpts)\n\t\t\treturn r\n\t\t},\n\t}\n}\n\ntype botsRun struct {\n\tcommonFlags\n\toutfile string\n\tmp      bool\n\tnomp    bool\n\tfields  []googleapi.Field\n}\n\nfunc (b *botsRun) Init(defaultAuthOpts auth.Options) {\n\tb.commonFlags.Init(defaultAuthOpts)\n\n\tb.Flags.StringVar(&b.outfile, \"json\", \"\", \"Path to output JSON results. Implies quiet.\")\n\tb.Flags.BoolVar(&b.mp, \"mp\", false, \"Only fetch Machine Provider bots.\")\n\tb.Flags.BoolVar(&b.nomp, \"nomp\", false, \"Exclude Machine Provider bots.\")\n\tb.Flags.Var(flag.FieldSlice(&b.fields), \"field\", \"Fields to include in a partial response. May be repeated.\")\n}\n\nfunc (b *botsRun) Parse() error {\n\tif err := b.commonFlags.Parse(); err != nil {\n\t\treturn err\n\t}\n\tif b.mp && b.nomp {\n\t\treturn errors.Reason(\"at most one of -mp and -nomp must be specified\").Err()\n\t}\n\tif b.defaultFlags.Quiet && b.outfile == \"\" {\n\t\treturn errors.Reason(\"specify -json when using -quiet\").Err()\n\t}\n\tif b.outfile != \"\" {\n\t\tb.defaultFlags.Quiet = true\n\t}\n\treturn nil\n}\n\nfunc (b *botsRun) main(a subcommands.Application) error {\n\tctx, cancel := context.WithCancel(b.defaultFlags.MakeLoggingContext(os.Stderr))\n\tsignals.HandleInterrupt(cancel)\n\tclient, err := b.createAuthClient(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts, err := swarming.New(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.BasePath = b.commonFlags.serverURL + \"\/_ah\/api\/swarming\/v1\/\"\n\tcall := s.Bots.List()\n\tif b.mp {\n\t\tcall.IsMp(\"TRUE\")\n\t} else if b.nomp {\n\t\tcall.IsMp(\"FALSE\")\n\t}\n\t\/\/ If no fields are specified, all fields will be returned. If any fields are\n\t\/\/ specified, ensure the cursor is specified so we can get subsequent pages.\n\tif len(b.fields) > 0 {\n\t\tb.fields = append(b.fields, \"cursor\")\n\t}\n\tcall.Fields(b.fields...)\n\t\/\/ Keep calling as long as there's a cursor indicating more bots to list.\n\t\/\/ Create an empty array, so that if saved to b.outfile, it's an empty list,\n\t\/\/ not null.\n\tbots := []*swarming.SwarmingRpcsBotInfo{}\n\tfor {\n\t\tresult, err := call.Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbots = append(bots, result.Items...)\n\t\tif result.Cursor == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tcall.Cursor(result.Cursor)\n\t}\n\tif !b.defaultFlags.Quiet {\n\t\tj, err := json.MarshalIndent(bots, \"\", \" \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", j)\n\t}\n\tif b.outfile != \"\" {\n\t\tj, err := json.Marshal(bots)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := ioutil.WriteFile(b.outfile, j, 0644); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (b *botsRun) Run(a subcommands.Application, args []string, _ subcommands.Env) int {\n\tif err := b.Parse(); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tcl, err := b.defaultFlags.StartTracing()\n\tif err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tdefer cl.Close()\n\tif err := b.main(a); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\treturn 0\n}\n<commit_msg>swarming: add dimension flag to bots subcommand<commit_after>\/\/ Copyright 2018 The LUCI Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\n\t\"google.golang.org\/api\/googleapi\"\n\n\t\"github.com\/maruel\/subcommands\"\n\n\t\"go.chromium.org\/luci\/auth\"\n\t\"go.chromium.org\/luci\/common\/api\/swarming\/swarming\/v1\"\n\t\"go.chromium.org\/luci\/common\/errors\"\n\t\"go.chromium.org\/luci\/common\/flag\"\n\t\"go.chromium.org\/luci\/common\/flag\/stringmapflag\"\n\t\"go.chromium.org\/luci\/common\/system\/signals\"\n)\n\nfunc cmdBots(defaultAuthOpts auth.Options) *subcommands.Command {\n\treturn &subcommands.Command{\n\t\tUsageLine: \"bots <options>\",\n\t\tShortDesc: \"lists bots\",\n\t\tLongDesc:  \"List bots matching the given options.\",\n\t\tCommandRun: func() subcommands.CommandRun {\n\t\t\tr := &botsRun{}\n\t\t\tr.Init(defaultAuthOpts)\n\t\t\treturn r\n\t\t},\n\t}\n}\n\ntype botsRun struct {\n\tcommonFlags\n\toutfile    string\n\tmp         bool\n\tnomp       bool\n\tdimensions stringmapflag.Value\n\tfields     []googleapi.Field\n}\n\nfunc (b *botsRun) Init(defaultAuthOpts auth.Options) {\n\tb.commonFlags.Init(defaultAuthOpts)\n\n\tb.Flags.StringVar(&b.outfile, \"json\", \"\", \"Path to output JSON results. Implies quiet.\")\n\tb.Flags.BoolVar(&b.mp, \"mp\", false, \"Only fetch Machine Provider bots.\")\n\tb.Flags.BoolVar(&b.nomp, \"nomp\", false, \"Exclude Machine Provider bots.\")\n\tb.Flags.Var(&b.dimensions, \"dimension\", \"Dimension to select the right kind of bot. In the form of `key=value`\")\n\tb.Flags.Var(flag.FieldSlice(&b.fields), \"field\", \"Fields to include in a partial response. May be repeated.\")\n\n}\n\nfunc (b *botsRun) Parse() error {\n\tif err := b.commonFlags.Parse(); err != nil {\n\t\treturn err\n\t}\n\tif b.mp && b.nomp {\n\t\treturn errors.Reason(\"at most one of -mp and -nomp must be specified\").Err()\n\t}\n\tif b.defaultFlags.Quiet && b.outfile == \"\" {\n\t\treturn errors.Reason(\"specify -json when using -quiet\").Err()\n\t}\n\tif b.outfile != \"\" {\n\t\tb.defaultFlags.Quiet = true\n\t}\n\treturn nil\n}\n\nfunc (b *botsRun) main(a subcommands.Application) error {\n\tctx, cancel := context.WithCancel(b.defaultFlags.MakeLoggingContext(os.Stderr))\n\tsignals.HandleInterrupt(cancel)\n\tclient, err := b.createAuthClient(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts, err := swarming.New(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.BasePath = b.commonFlags.serverURL + \"\/_ah\/api\/swarming\/v1\/\"\n\tcall := s.Bots.List()\n\tif b.mp {\n\t\tcall.IsMp(\"TRUE\")\n\t} else if b.nomp {\n\t\tcall.IsMp(\"FALSE\")\n\t}\n\n\tvar dims []string\n\tfor k, v := range b.dimensions {\n\t\tdims = append(dims, k+\":\"+v)\n\t}\n\tcall.Dimensions(dims...)\n\n\t\/\/ If no fields are specified, all fields will be returned. If any fields are\n\t\/\/ specified, ensure the cursor is specified so we can get subsequent pages.\n\tif len(b.fields) > 0 {\n\t\tb.fields = append(b.fields, \"cursor\")\n\t}\n\tcall.Fields(b.fields...)\n\t\/\/ Keep calling as long as there's a cursor indicating more bots to list.\n\t\/\/ Create an empty array, so that if saved to b.outfile, it's an empty list,\n\t\/\/ not null.\n\tbots := []*swarming.SwarmingRpcsBotInfo{}\n\tfor {\n\t\tresult, err := call.Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tbots = append(bots, result.Items...)\n\t\tif result.Cursor == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tcall.Cursor(result.Cursor)\n\t}\n\tif !b.defaultFlags.Quiet {\n\t\tj, err := json.MarshalIndent(bots, \"\", \" \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", j)\n\t}\n\tif b.outfile != \"\" {\n\t\tj, err := json.Marshal(bots)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := ioutil.WriteFile(b.outfile, j, 0644); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (b *botsRun) Run(a subcommands.Application, args []string, _ subcommands.Env) int {\n\tif err := b.Parse(); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tcl, err := b.defaultFlags.StartTracing()\n\tif err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tdefer cl.Close()\n\tif err := b.main(a); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\treturn 0\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build integrationTest\n\npackage esvector\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/elastic\/go-elasticsearch\/v5\"\n\t\"github.com\/semi-technologies\/weaviate\/entities\/models\"\n\t\"github.com\/semi-technologies\/weaviate\/entities\/schema\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\n\/\/ this is not a test suite in itself, but it makes sure that other test suites\n\/\/ which depend no a specific caching state are run sequentially in a specific\n\/\/ order, so that they don't interefere with each other\n\nfunc Test_OrchestrateCaching(t *testing.T) {\n\n\t\/\/ requires caching to be stopped initially, starts caching at some point in\n\t\/\/ the test suite, stops caching in the end to clean up\n\ttestEsVectorCache(t)\n\n\tclient, err := elasticsearch.NewClient(elasticsearch.Config{\n\t\tAddresses: []string{\"http:\/\/localhost:9201\"},\n\t})\n\trequire.Nil(t, err)\n\tschemaGetter := &fakeSchemaGetter{schema: parkingGaragesSchema()}\n\tlogger := logrus.New()\n\trepo := NewRepo(client, logger, schemaGetter, 2)\n\twaitForEsToBeReady(t, repo)\n\trequestCounter := &testCounter{}\n\trepo.requestCounter = requestCounter\n\tmigrator := NewMigrator(repo)\n\n\t\/\/ cache indexing not started yet, as the below test suite asserts on both state\n\tt.Run(\"test multiple cross ref types\", testMultipleCrossRefTypes(repo, migrator))\n\n\t\/\/ cache indexing has since been started in the previous test suite\n\tt.Run(\"filtering on refprops\", testFilteringOnRefProps(repo))\n\n\tt.Run(\"updating cached ref props\", testUpdatingCachedRefProps(repo, parkingGaragesSchema()))\n\n\t\/\/ explicitly stop cache indexing to clean up\n\trepo.StopCacheIndexing()\n}\n\nfunc parkingGaragesSchema() schema.Schema {\n\treturn schema.Schema{\n\t\tThings: &models.Schema{\n\t\t\tClasses: []*models.Class{\n\t\t\t\t&models.Class{\n\t\t\t\t\tClass: \"MultiRefParkingGarage\",\n\t\t\t\t\tProperties: []*models.Property{\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"name\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeString)},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"location\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeGeoCoordinates)},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&models.Class{\n\t\t\t\t\tClass: \"MultiRefParkingLot\",\n\t\t\t\t\tProperties: []*models.Property{\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"name\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeString)},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&models.Class{\n\t\t\t\t\tClass: \"MultiRefCar\",\n\t\t\t\t\tProperties: []*models.Property{\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"name\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeString)},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"parkedAt\",\n\t\t\t\t\t\t\tDataType: []string{\"MultiRefParkingGarage\", \"MultiRefParkingLot\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&models.Class{\n\t\t\t\t\tClass: \"MultiRefDriver\",\n\t\t\t\t\tProperties: []*models.Property{\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"name\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeString)},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"drives\",\n\t\t\t\t\t\t\tDataType: []string{\"MultiRefCar\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&models.Class{\n\t\t\t\t\tClass: \"MultiRefPerson\",\n\t\t\t\t\tProperties: []*models.Property{\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"name\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeString)},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"friendsWith\",\n\t\t\t\t\t\t\tDataType: []string{\"MultiRefDriver\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&models.Class{\n\t\t\t\t\tClass: \"MultiRefSociety\",\n\t\t\t\t\tProperties: []*models.Property{\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"name\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeString)},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"hasMembers\",\n\t\t\t\t\t\t\tDataType: []string{\"MultiRefPerson\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n<commit_msg>🤖 bleep bloop => auto updated Weaviate<commit_after>\/\/                           _       _\n\/\/ __      _____  __ ___   ___  __ _| |_ ___\n\/\/ \\ \\ \/\\ \/ \/ _ \\\/ _` \\ \\ \/ \/ |\/ _` | __\/ _ \\\n\/\/  \\ V  V \/  __\/ (_| |\\ V \/| | (_| | ||  __\/\n\/\/   \\_\/\\_\/ \\___|\\__,_| \\_\/ |_|\\__,_|\\__\\___|\n\/\/\n\/\/  Copyright © 2016 - 2019 SeMI Holding B.V. (registered @ Dutch Chamber of Commerce no 75221632). All rights reserved.\n\/\/  LICENSE WEAVIATE OPEN SOURCE: https:\/\/www.semi.technology\/playbook\/playbook\/contract-weaviate-OSS.html\n\/\/  LICENSE WEAVIATE ENTERPRISE: https:\/\/www.semi.technology\/playbook\/contract-weaviate-enterprise.html\n\/\/  CONCEPT: Bob van Luijt (@bobvanluijt)\n\/\/  CONTACT: hello@semi.technology\n\/\/\n\n\/\/ +build integrationTest\n\npackage esvector\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/elastic\/go-elasticsearch\/v5\"\n\t\"github.com\/semi-technologies\/weaviate\/entities\/models\"\n\t\"github.com\/semi-technologies\/weaviate\/entities\/schema\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\n\/\/ this is not a test suite in itself, but it makes sure that other test suites\n\/\/ which depend no a specific caching state are run sequentially in a specific\n\/\/ order, so that they don't interefere with each other\n\nfunc Test_OrchestrateCaching(t *testing.T) {\n\n\t\/\/ requires caching to be stopped initially, starts caching at some point in\n\t\/\/ the test suite, stops caching in the end to clean up\n\ttestEsVectorCache(t)\n\n\tclient, err := elasticsearch.NewClient(elasticsearch.Config{\n\t\tAddresses: []string{\"http:\/\/localhost:9201\"},\n\t})\n\trequire.Nil(t, err)\n\tschemaGetter := &fakeSchemaGetter{schema: parkingGaragesSchema()}\n\tlogger := logrus.New()\n\trepo := NewRepo(client, logger, schemaGetter, 2)\n\twaitForEsToBeReady(t, repo)\n\trequestCounter := &testCounter{}\n\trepo.requestCounter = requestCounter\n\tmigrator := NewMigrator(repo)\n\n\t\/\/ cache indexing not started yet, as the below test suite asserts on both state\n\tt.Run(\"test multiple cross ref types\", testMultipleCrossRefTypes(repo, migrator))\n\n\t\/\/ cache indexing has since been started in the previous test suite\n\tt.Run(\"filtering on refprops\", testFilteringOnRefProps(repo))\n\n\tt.Run(\"updating cached ref props\", testUpdatingCachedRefProps(repo, parkingGaragesSchema()))\n\n\t\/\/ explicitly stop cache indexing to clean up\n\trepo.StopCacheIndexing()\n}\n\nfunc parkingGaragesSchema() schema.Schema {\n\treturn schema.Schema{\n\t\tThings: &models.Schema{\n\t\t\tClasses: []*models.Class{\n\t\t\t\t&models.Class{\n\t\t\t\t\tClass: \"MultiRefParkingGarage\",\n\t\t\t\t\tProperties: []*models.Property{\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"name\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeString)},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"location\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeGeoCoordinates)},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&models.Class{\n\t\t\t\t\tClass: \"MultiRefParkingLot\",\n\t\t\t\t\tProperties: []*models.Property{\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"name\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeString)},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&models.Class{\n\t\t\t\t\tClass: \"MultiRefCar\",\n\t\t\t\t\tProperties: []*models.Property{\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"name\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeString)},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"parkedAt\",\n\t\t\t\t\t\t\tDataType: []string{\"MultiRefParkingGarage\", \"MultiRefParkingLot\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&models.Class{\n\t\t\t\t\tClass: \"MultiRefDriver\",\n\t\t\t\t\tProperties: []*models.Property{\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"name\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeString)},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"drives\",\n\t\t\t\t\t\t\tDataType: []string{\"MultiRefCar\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&models.Class{\n\t\t\t\t\tClass: \"MultiRefPerson\",\n\t\t\t\t\tProperties: []*models.Property{\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"name\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeString)},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"friendsWith\",\n\t\t\t\t\t\t\tDataType: []string{\"MultiRefDriver\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t&models.Class{\n\t\t\t\t\tClass: \"MultiRefSociety\",\n\t\t\t\t\tProperties: []*models.Property{\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"name\",\n\t\t\t\t\t\t\tDataType: []string{string(schema.DataTypeString)},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t&models.Property{\n\t\t\t\t\t\t\tName:     \"hasMembers\",\n\t\t\t\t\t\t\tDataType: []string{\"MultiRefPerson\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package onedriveclient\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/koofr\/go-httpclient\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"time\"\n)\n\nconst (\n\tInvalidGrantError = \"invalid_grant\"\n)\n\ntype RefreshResp struct {\n\tExpiresIn    int64  `json:\"expires_in\"`\n\tAccessToken  string `json:\"access_token\"`\n\tRefreshToken string `json:\"refresh_token\"`\n}\n\ntype RefreshRespError struct {\n\tError            string `json:\"error\"`\n\tErrorDescription string `json:\"error_description\"`\n}\n\ntype OneDriveAuth struct {\n\tClientId     string\n\tClientSecret string\n\tRedirectUri  string\n\tAccessToken  string\n\tRefreshToken string\n\tExpiresAt    time.Time\n}\n\nfunc (a *OneDriveAuth) ValidToken() (token string, err error) {\n\tif time.Now().Unix() > a.ExpiresAt.Unix() {\n\t\tdata := url.Values{}\n\t\tdata.Set(\"grant_type\", \"refresh_token\")\n\t\tdata.Set(\"client_id\", a.ClientId)\n\t\tdata.Set(\"client_secret\", a.ClientSecret)\n\t\tdata.Set(\"redirect_uri\", a.RedirectUri)\n\t\tdata.Set(\"refresh_token\", a.RefreshToken)\n\n\t\tvar respVal RefreshResp\n\n\t\t_, err = httpclient.DefaultClient.Request(&httpclient.RequestData{\n\t\t\tMethod:         \"POST\",\n\t\t\tFullURL:        \"https:\/\/login.live.com\/oauth20_token.srf\",\n\t\t\tExpectedStatus: []int{http.StatusOK},\n\t\t\tReqEncoding:    httpclient.EncodingForm,\n\t\t\tReqValue:       data,\n\t\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\t\tRespValue:      &respVal,\n\t\t})\n\n\t\tif err != nil {\n\t\t\terr = HandleError(err)\n\n\t\t\tif ode, ok := IsOneDriveError(err); ok {\n\t\t\t\trefreshErr := &RefreshRespError{}\n\t\t\t\tif jsonErr := json.Unmarshal([]byte(ode.Err.Message), &refreshErr); jsonErr == nil {\n\t\t\t\t\tode.Err.Code = refreshErr.Error\n\t\t\t\t\tode.Err.Message = refreshErr.ErrorDescription\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn \"\", err\n\t\t}\n\n\t\ta.AccessToken = respVal.AccessToken\n\t\ta.RefreshToken = respVal.RefreshToken\n\t\ta.ExpiresAt = time.Now().Add(time.Duration(respVal.ExpiresIn) * time.Second)\n\t}\n\n\ttoken = a.AccessToken\n\n\treturn token, nil\n}\n<commit_msg>Add refresh token callback<commit_after>package onedriveclient\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/koofr\/go-httpclient\"\n)\n\nconst (\n\tInvalidGrantError = \"invalid_grant\"\n)\n\ntype RefreshResp struct {\n\tExpiresIn    int64  `json:\"expires_in\"`\n\tAccessToken  string `json:\"access_token\"`\n\tRefreshToken string `json:\"refresh_token\"`\n}\n\ntype RefreshRespError struct {\n\tError            string `json:\"error\"`\n\tErrorDescription string `json:\"error_description\"`\n}\n\ntype OneDriveAuth struct {\n\tClientId       string\n\tClientSecret   string\n\tRedirectUri    string\n\tAccessToken    string\n\tRefreshToken   string\n\tExpiresAt      time.Time\n\tOnTokenRefresh func()\n\n\tmutex sync.Mutex\n}\n\nfunc (a *OneDriveAuth) ValidToken() (token string, err error) {\n\tif time.Now().Unix() > a.ExpiresAt.Unix() {\n\t\terr = a.UpdateRefreshToken()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\ttoken = a.AccessToken\n\n\treturn token, nil\n}\n\nfunc (a *OneDriveAuth) UpdateRefreshToken() (err error) {\n\ta.mutex.Lock()\n\tdefer a.mutex.Unlock()\n\n\tdata := url.Values{}\n\tdata.Set(\"grant_type\", \"refresh_token\")\n\tdata.Set(\"client_id\", a.ClientId)\n\tdata.Set(\"client_secret\", a.ClientSecret)\n\tdata.Set(\"redirect_uri\", a.RedirectUri)\n\tdata.Set(\"refresh_token\", a.RefreshToken)\n\n\tvar respVal RefreshResp\n\n\t_, err = httpclient.DefaultClient.Request(&httpclient.RequestData{\n\t\tMethod:         \"POST\",\n\t\tFullURL:        \"https:\/\/login.live.com\/oauth20_token.srf\",\n\t\tExpectedStatus: []int{http.StatusOK},\n\t\tReqEncoding:    httpclient.EncodingForm,\n\t\tReqValue:       data,\n\t\tRespEncoding:   httpclient.EncodingJSON,\n\t\tRespValue:      &respVal,\n\t})\n\n\tif err != nil {\n\t\terr = HandleError(err)\n\n\t\tif ode, ok := IsOneDriveError(err); ok {\n\t\t\trefreshErr := &RefreshRespError{}\n\t\t\tif jsonErr := json.Unmarshal([]byte(ode.Err.Message), &refreshErr); jsonErr == nil {\n\t\t\t\tode.Err.Code = refreshErr.Error\n\t\t\t\tode.Err.Message = refreshErr.ErrorDescription\n\t\t\t}\n\t\t}\n\n\t\treturn err\n\t}\n\n\ta.AccessToken = respVal.AccessToken\n\ta.RefreshToken = respVal.RefreshToken\n\ta.ExpiresAt = time.Now().Add(time.Duration(respVal.ExpiresIn) * time.Second)\n\n\tif a.OnTokenRefresh != nil {\n\t\ta.OnTokenRefresh()\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package ginAuth\n\n\/\/ this package is a secure cookie authentication middleware for the the Gin Web Framework\n\/\/ https:\/\/github.com\/gin-gonic\/gin\n\nimport (\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/astaxie\/beego\/config\"\n\t\"github.com\/gorilla\/securecookie\"\n\t\"time\"\n\t\"strconv\"\n\t\"strings\"\n\t\"crypto\/md5\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"io\"\n\t\"net\/http\"\n)\n\nconst VERSION = \"0.0.1\"\n\n\/\/ set our global package variables\nvar (\n\tCookieName string                       \/\/ the name of the cookie that will be used, default: \"token\"\n\tConfigPath string                       \/\/ path to config file, default: \"\"\n\tConfigType string                       \/\/ type of config file, default: \"ini\"\n\tPrefix string                           \/\/ the key in ctx.Keys[] to use, default: \"\"\n\tHashKey []byte                          \/\/ hash key for securecookie\n\tBlockKey []byte                         \/\/ block key for securecookie\n\tExpiration int64                        \/\/ time until the cookie expires in seconds, default: 604800\n\tUnauthorized func(ctx *gin.Context)     \/\/ function called if user is not authorized\n\tAuthorized func(ctx *gin.Context)       \/\/ function called if user is authorized\n\tSecureCookie *securecookie.SecureCookie \/\/ global secure cookie object\n)\n\nfunc init() {\n\n\tConfigPath = \"\"\n\tConfigType = \"ini\"\n\tCookieName = \"token\"\n\tPrefix = \"\"\n\tExpiration = 604800 \/\/ 7 days\n\n}\n\n\/\/ gin middleware handler\n\/\/ call this on your groups that require authentication\nfunc Use(ctx *gin.Context) {\n\n\terr := Check(ctx)\n\n\tif err == nil {\n\n\t\tloggedIn, _ := ctx.Get(Prefix + \"loggedIn\")\n\n\t\tif loggedIn == true {\n\n\t\t\tif Authorized != nil {\n\t\t\t\tAuthorized(ctx)\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tif Unauthorized != nil {\n\t\t\t\tUnauthorized(ctx)\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}\n\n\/\/ this function loads your specified configuration file and it's values\nfunc LoadConfig() error {\n\n\tif ConfigPath != \"\" {\n\t\tconf, err := config.NewConfig(ConfigType, ConfigPath)\n\t\tif err != nil {\n\n\t\t\treturn err\n\t\t}\n\n\t\tif cookiename := conf.String(\"cookiename\"); cookiename != \"\" {\n\t\t\tCookieName = cookiename\n\t\t}\n\n\t\tif prefix := conf.String(\"prefix\"); prefix != \"\" {\n\t\t\tPrefix = prefix\n\t\t}\n\n\t\tif hashkey := conf.String(\"hashkey\"); hashkey != \"\" {\n\n\t\t\tval, err := hex.DecodeString(hashkey)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tHashKey = val\n\t\t}\n\n\t\tif blockkey := conf.String(\"blockkey\"); blockkey != \"\" {\n\n\t\t\tval, err := hex.DecodeString(blockkey)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tBlockKey = val\n\n\t\t}\n\n\t\tif expiration := conf.String(\"expiration\"); expiration != \"\" {\n\n\t\t\tval, err := strconv.ParseInt(expiration, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tExpiration = val\n\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ a private function that simply saves the log in status of the user to the current context\nfunc saveLogin(ctx *gin.Context, status bool) {\n\tctx.Set(Prefix+\"loggedIn\", status)\n}\n\n\/\/ a private function that returns the ip from the current request\nfunc ip(ctx *gin.Context) string {\n\treturn strings.Split(ctx.Req.RemoteAddr, \":\")[0]\n}\n\n\/\/ checks for our token cookie, decodes it, and determines if it is valid\n\/\/ the encrypted cookie data set in Login() will be set to the current context as well\nfunc Check(ctx *gin.Context) error {\n\n\t\/\/ get the encrypted cookie value\n\tcookie, err := ctx.Req.Cookie(CookieName)\n\n\tif err == nil {\n\n\t\tdata := make(map[string]string)\n\n\t\tSecureCookie = securecookie.New(HashKey, BlockKey)\n\t\tif err := SecureCookie.Decode(CookieName, cookie.Value, &data); err == nil {\n\n\t\t\t\/\/ save the login cookie data to the context\n\t\t\tctx.Set(Prefix+\"cookieData\", data)\n\n\t\t\thash := hashHeader(ctx)\n\n\t\t\texpiration, err := strconv.ParseInt(data[\"expiration\"], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif hash == data[\"hash\"] && ip(ctx) == data[\"ip\"] && time.Now().Before(time.Unix(expiration, 0)) {\n\n\t\t\t\tsaveLogin(ctx, true)\n\n\t\t\t} else {\n\t\t\t\t\/\/call the full logout because it'll remove the cookie as well\n\t\t\t\tLogout(ctx)\n\t\t\t}\n\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\n\/\/ handles the login process\n\/\/ the first param is a map of strings that will be added to the cookie data before encryption and will be\n\/\/ able to be recovered when Check() is called\nfunc Login(ctx *gin.Context, extra map[string]string) error {\n\n\tdata := make(map[string]string)\n\n\tfor key, value := range extra {\n\n\t\tif key == \"ip\" || key == \"hash\" || key == \"experation\" {\n\t\t\treturn errors.New(\"The key '\" + key + \"' is reserved.\")\n\t\t}\n\n\t\tdata[key] = value\n\t}\n\n\t\/\/ our current time + our expiration time, converted to a unix time stamp\n\tdata[\"expiration\"] = strconv.FormatInt(time.Now().Add(time.Duration(Expiration)*time.Second).Unix(), 10)\n\tdata[\"ip\"] = ip(ctx)\n\tdata[\"hash\"] = hashHeader(ctx)\n\n\t\/\/ encode our cookie data securely\n\tSecureCookie = securecookie.New(HashKey, BlockKey)\n\tif encoded, err := SecureCookie.Encode(CookieName, data); err == nil {\n\n\t\t\/\/set our cookie\n\t\tcookie := http.Cookie{Name: CookieName, Value: encoded, Path: \"\/\", MaxAge: int(Expiration)}\n\t\thttp.SetCookie(ctx.Writer, &cookie)\n\n\t} else {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ removes our token cookie, sets the context to: not logged in\nfunc Logout(ctx *gin.Context) {\n\n\tcookie := http.Cookie{Name: CookieName, Path: \"\/\", MaxAge: -1}\n\thttp.SetCookie(ctx.Writer, &cookie)\n\tsaveLogin(ctx, false)\n\n}\n\n\/\/ this function returns and md5 hash (string) for a few common request headers\nfunc hashHeader(ctx *gin.Context) string {\n\n\th := md5.New()\n\n\tio.WriteString(h, ctx.Req.Header.Get(\"User-Agent\"))\n\tio.WriteString(h, ctx.Req.Header.Get(\"Accept-Encoding\"))\n\tio.WriteString(h, ctx.Req.Header.Get(\"Accept-Language\"))\n\tio.WriteString(h, ctx.Req.Header.Get(\"Host\"))\n\n\treturn hex.EncodeToString(h.Sum(nil))\n\n}\n<commit_msg>removed certain headers that where either useless or causing issues in chrome<commit_after>package ginAuth\n\n\/\/ this package is a secure cookie authentication middleware for the the Gin Web Framework\n\/\/ https:\/\/github.com\/gin-gonic\/gin\n\nimport (\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/astaxie\/beego\/config\"\n\t\"github.com\/gorilla\/securecookie\"\n\t\"time\"\n\t\"strconv\"\n\t\"strings\"\n\t\"crypto\/md5\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"io\"\n\t\"net\/http\"\n)\n\nconst VERSION = \"0.0.1\"\n\n\/\/ set our global package variables\nvar (\n\tCookieName string                       \/\/ the name of the cookie that will be used, default: \"token\"\n\tConfigPath string                       \/\/ path to config file, default: \"\"\n\tConfigType string                       \/\/ type of config file, default: \"ini\"\n\tPrefix string                           \/\/ the key in ctx.Keys[] to use, default: \"\"\n\tHashKey []byte                          \/\/ hash key for securecookie\n\tBlockKey []byte                         \/\/ block key for securecookie\n\tExpiration int64                        \/\/ time until the cookie expires in seconds, default: 604800\n\tUnauthorized func(ctx *gin.Context)     \/\/ function called if user is not authorized\n\tAuthorized func(ctx *gin.Context)       \/\/ function called if user is authorized\n\tSecureCookie *securecookie.SecureCookie \/\/ global secure cookie object\n)\n\nfunc init() {\n\n\tConfigPath = \"\"\n\tConfigType = \"ini\"\n\tCookieName = \"token\"\n\tPrefix = \"\"\n\tExpiration = 604800 \/\/ 7 days\n\n}\n\n\/\/ gin middleware handler\n\/\/ call this on your groups that require authentication\nfunc Use(ctx *gin.Context) {\n\n\terr := Check(ctx)\n\n\tif err == nil {\n\n\t\tloggedIn, _ := ctx.Get(Prefix + \"loggedIn\")\n\n\t\tif loggedIn == true {\n\n\t\t\tif Authorized != nil {\n\t\t\t\tAuthorized(ctx)\n\t\t\t}\n\n\t\t} else {\n\n\t\t\tif Unauthorized != nil {\n\t\t\t\tUnauthorized(ctx)\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}\n\n\/\/ this function loads your specified configuration file and it's values\nfunc LoadConfig() error {\n\n\tif ConfigPath != \"\" {\n\t\tconf, err := config.NewConfig(ConfigType, ConfigPath)\n\t\tif err != nil {\n\n\t\t\treturn err\n\t\t}\n\n\t\tif cookiename := conf.String(\"cookiename\"); cookiename != \"\" {\n\t\t\tCookieName = cookiename\n\t\t}\n\n\t\tif prefix := conf.String(\"prefix\"); prefix != \"\" {\n\t\t\tPrefix = prefix\n\t\t}\n\n\t\tif hashkey := conf.String(\"hashkey\"); hashkey != \"\" {\n\n\t\t\tval, err := hex.DecodeString(hashkey)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tHashKey = val\n\t\t}\n\n\t\tif blockkey := conf.String(\"blockkey\"); blockkey != \"\" {\n\n\t\t\tval, err := hex.DecodeString(blockkey)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tBlockKey = val\n\n\t\t}\n\n\t\tif expiration := conf.String(\"expiration\"); expiration != \"\" {\n\n\t\t\tval, err := strconv.ParseInt(expiration, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tExpiration = val\n\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ a private function that simply saves the log in status of the user to the current context\nfunc saveLogin(ctx *gin.Context, status bool) {\n\tctx.Set(Prefix+\"loggedIn\", status)\n}\n\n\/\/ a private function that returns the ip from the current request\nfunc ip(ctx *gin.Context) string {\n\treturn strings.Split(ctx.Req.RemoteAddr, \":\")[0]\n}\n\n\/\/ checks for our token cookie, decodes it, and determines if it is valid\n\/\/ the encrypted cookie data set in Login() will be set to the current context as well\nfunc Check(ctx *gin.Context) error {\n\n\t\/\/ get the encrypted cookie value\n\tcookie, err := ctx.Req.Cookie(CookieName)\n\n\tif err == nil {\n\n\t\tdata := make(map[string]string)\n\n\t\tSecureCookie = securecookie.New(HashKey, BlockKey)\n\t\tif err := SecureCookie.Decode(CookieName, cookie.Value, &data); err == nil {\n\n\t\t\t\/\/ save the login cookie data to the context\n\t\t\tctx.Set(Prefix+\"cookieData\", data)\n\n\t\t\thash := hashHeader(ctx)\n\n\t\t\texpiration, err := strconv.ParseInt(data[\"expiration\"], 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif hash == data[\"hash\"] && ip(ctx) == data[\"ip\"] && time.Now().Before(time.Unix(expiration, 0)) {\n\n\t\t\t\tsaveLogin(ctx, true)\n\n\t\t\t} else {\n\t\t\t\t\/\/call the full logout because it'll remove the cookie as well\n\t\t\t\tLogout(ctx)\n\t\t\t}\n\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\n\/\/ handles the login process\n\/\/ the first param is a map of strings that will be added to the cookie data before encryption and will be\n\/\/ able to be recovered when Check() is called\nfunc Login(ctx *gin.Context, extra map[string]string) error {\n\n\tdata := make(map[string]string)\n\n\tfor key, value := range extra {\n\n\t\tif key == \"ip\" || key == \"hash\" || key == \"experation\" {\n\t\t\treturn errors.New(\"The key '\" + key + \"' is reserved.\")\n\t\t}\n\n\t\tdata[key] = value\n\t}\n\n\t\/\/ our current time + our expiration time, converted to a unix time stamp\n\tdata[\"expiration\"] = strconv.FormatInt(time.Now().Add(time.Duration(Expiration)*time.Second).Unix(), 10)\n\tdata[\"ip\"] = ip(ctx)\n\tdata[\"hash\"] = hashHeader(ctx)\n\n\t\/\/ encode our cookie data securely\n\tSecureCookie = securecookie.New(HashKey, BlockKey)\n\tif encoded, err := SecureCookie.Encode(CookieName, data); err == nil {\n\n\t\t\/\/set our cookie\n\t\tcookie := http.Cookie{Name: CookieName, Value: encoded, Path: \"\/\", MaxAge: int(Expiration)}\n\t\thttp.SetCookie(ctx.Writer, &cookie)\n\n\t} else {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ removes our token cookie, sets the context to: not logged in\nfunc Logout(ctx *gin.Context) {\n\n\tcookie := http.Cookie{Name: CookieName, Path: \"\/\", MaxAge: -1}\n\thttp.SetCookie(ctx.Writer, &cookie)\n\tsaveLogin(ctx, false)\n\n}\n\n\/\/ this function returns and md5 hash (string) for a few common request headers\nfunc hashHeader(ctx *gin.Context) string {\n\n\th := md5.New()\n\n\tio.WriteString(h, ctx.Req.Header.Get(\"User-Agent\"))\n\tio.WriteString(h, ctx.Req.Header.Get(\"Accept-Language\"))\n\n\treturn hex.EncodeToString(h.Sum(nil))\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package qtypes\n\nimport (\n\t\"time\"\n)\n\nconst (\n\tversion = \"0.3.1\"\n)\n\ntype Base struct {\n\tBaseVersion string\n\tTime\t\ttime.Time\n\tSourceID\tint\n\tSourcePath\t[]string\n}\n\nfunc NewBase(src string) Base {\n\treturn NewTimedBase(src, time.Now())\n}\n\nfunc NewTimedBase(src string, t time.Time) Base {\n\treturn Base {\n\t\tBaseVersion: version,\n\t\tTime: t,\n\t\tSourceID: 0,\n\t\tSourcePath: []string{src},\n\t}\n}\n\nfunc (b *Base) GetTimeRFC() string {\n\treturn b.Time.Format(\"2006-01-02T15:04:05.999999-07:00\")\n}\n\nfunc (b *Base) GetTimeUnix() int64 {\n\treturn b.Time.Unix()\n}\n\nfunc (b *Base) GetTimeUnixNano() int64 {\n\treturn b.Time.UnixNano()\n}\n\nfunc (b *Base) AppendSource(src string) {\n\tb.SourcePath = append(b.SourcePath, src)\n}\n\nfunc (b *Base) IsLastSource(src string) bool {\n\treturn b.SourcePath[len(b.SourcePath)-1] == src\n}\n\nfunc (b *Base) InputsMatch(inputs []string) bool {\n\tfor _, inp := range inputs {\n\t\tif b.IsLastSource(inp) {\n\t\t\treturn true\n\t\t}\n\n\t}\n\treturn false\n}<commit_msg>add SourceSuccess to Base<commit_after>package qtypes\n\nimport (\n\t\"time\"\n)\n\nconst (\n\tversion = \"0.3.1\"\n)\n\ntype Base struct {\n\tBaseVersion string\n\tTime\t\t\ttime.Time\n\tSourceID\t\tint\n\tSourcePath\t\t[]string\n\tSourceSuccess \tbool\n}\n\nfunc NewBase(src string) Base {\n\treturn NewTimedBase(src, time.Now())\n}\n\nfunc NewTimedBase(src string, t time.Time) Base {\n\treturn Base {\n\t\tBaseVersion: version,\n\t\tTime: t,\n\t\tSourceID: 0,\n\t\tSourcePath: []string{src},\n\t\tSourceSuccess: true,\n\t}\n}\n\nfunc (b *Base) GetTimeRFC() string {\n\treturn b.Time.Format(\"2006-01-02T15:04:05.999999-07:00\")\n}\n\nfunc (b *Base) GetTimeUnix() int64 {\n\treturn b.Time.Unix()\n}\n\nfunc (b *Base) GetTimeUnixNano() int64 {\n\treturn b.Time.UnixNano()\n}\n\nfunc (b *Base) AppendSource(src string) {\n\tb.SourcePath = append(b.SourcePath, src)\n}\n\nfunc (b *Base) IsLastSource(src string) bool {\n\treturn b.SourcePath[len(b.SourcePath)-1] == src\n}\n\nfunc (b *Base) InputsMatch(inputs []string) bool {\n\tfor _, inp := range inputs {\n\t\tif b.IsLastSource(inp) {\n\t\t\treturn true\n\t\t}\n\n\t}\n\treturn false\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Beam is a protocol and library for service-oriented communication,\n\/\/ with an emphasis on real-world patterns, simplicity and not reinventing the wheel.\n\/\/\n\/\/ See http:\/\/github.com\/dotcloud\/beam.\n\/\/\n\/\/ github.com\/dotcloud\/beam\/common holds functions and data structures common to the\n\/\/ client and server implementations. It is typically not used directly by external\n\/\/ programs.\n\npackage beam\n\nimport (\n\t_ \"github.com\/dotcloud\/go-redis-server\"\n\t\"io\"\n)\n\n\ntype DB interface {\n\n}\n\ntype Streamer interface {\n\t\/\/ OpenRead returns a read-only interface to receive data on the stream <name>.\n\t\/\/ If the stream hasn't been open for read access before, it is advertised as such to the peer.\n\tOpenRead(name string) io.Reader\n\n\t\/\/ ReadFrom opens a read-only interface on the stream <name>, and copies data\n\t\/\/ to that interface from <src> until EOF or error.\n\t\/\/ The return value n is the number of bytes read.\n\t\/\/ Any error encountered during the write is also returned.\n\tReadFrom(src io.Reader, name string) (int64, error)\n\n\t\/\/ OpenWrite returns a write-only interface to send data on the stream <name>.\n\t\/\/ If the stream hasn't been open for write access before, it is advertised as such to the peer.\n\tOpenWrite(name string) io.Writer\n\n\t\/\/ WriteTo opens a write-only interface on the stream <name>, and copies data\n\t\/\/ from that interface to <dst> until there's no more data to write or when an error occurs.\n\t\/\/ The return value n is the number of bytes written.\n\t\/\/ Any error encountered during the write is also returned.\n\tWriteTo(dst io.Writer, name string) (int64, error)\n\n\t\/\/ OpenReadWrite returns a read-write interface to send and receive on the stream <name>.\n\t\/\/ If the stream hasn't been open for read or write access before, it is advertised as such to the peer.\n\tOpenReadWrite(name string) io.ReadWriter\n\n\t\/\/ Close closes the stream <name>. All future reads will return io.EOF, and writes will return\n\t\/\/ io.ErrClosedPipe\n\tClose(name string)\n}\n<commit_msg>Streamer.Shutdown: graceful shutdown of a job's streams after cleanly draining them.<commit_after>\/\/ Beam is a protocol and library for service-oriented communication,\n\/\/ with an emphasis on real-world patterns, simplicity and not reinventing the wheel.\n\/\/\n\/\/ See http:\/\/github.com\/dotcloud\/beam.\n\/\/\n\/\/ github.com\/dotcloud\/beam\/common holds functions and data structures common to the\n\/\/ client and server implementations. It is typically not used directly by external\n\/\/ programs.\n\npackage beam\n\nimport (\n\t_ \"github.com\/dotcloud\/go-redis-server\"\n\t\"io\"\n)\n\n\ntype DB interface {\n\n}\n\ntype Streamer interface {\n\t\/\/ OpenRead returns a read-only interface to receive data on the stream <name>.\n\t\/\/ If the stream hasn't been open for read access before, it is advertised as such to the peer.\n\tOpenRead(name string) io.Reader\n\n\t\/\/ ReadFrom opens a read-only interface on the stream <name>, and copies data\n\t\/\/ to that interface from <src> until EOF or error.\n\t\/\/ The return value n is the number of bytes read.\n\t\/\/ Any error encountered during the write is also returned.\n\tReadFrom(src io.Reader, name string) (int64, error)\n\n\t\/\/ OpenWrite returns a write-only interface to send data on the stream <name>.\n\t\/\/ If the stream hasn't been open for write access before, it is advertised as such to the peer.\n\tOpenWrite(name string) io.Writer\n\n\t\/\/ WriteTo opens a write-only interface on the stream <name>, and copies data\n\t\/\/ from that interface to <dst> until there's no more data to write or when an error occurs.\n\t\/\/ The return value n is the number of bytes written.\n\t\/\/ Any error encountered during the write is also returned.\n\tWriteTo(dst io.Writer, name string) (int64, error)\n\n\t\/\/ OpenReadWrite returns a read-write interface to send and receive on the stream <name>.\n\t\/\/ If the stream hasn't been open for read or write access before, it is advertised as such to the peer.\n\tOpenReadWrite(name string) io.ReadWriter\n\n\t\/\/ Close closes the stream <name>. All future reads will return io.EOF, and writes will return\n\t\/\/ io.ErrClosedPipe\n\tClose(name string)\n\n\t\/\/ Shutdown waits until all streams with read access are closed and\n\t\/\/ all WriteTo and ReadFrom operations are completed,\n\t\/\/ then it stops accepting remote messages for its streams,\n\t\/\/ then it returns.\n\tShutdown() error\n}\n<|endoftext|>"}
{"text":"<commit_before>package libp2ptls\n\nimport (\n\t\"crypto\/ecdsa\"\n\t\"crypto\/elliptic\"\n\t\"crypto\/rand\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"crypto\/x509\/pkix\"\n\t\"encoding\/asn1\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\/big\"\n\t\"time\"\n\n\t\"golang.org\/x\/sys\/cpu\"\n\n\tic \"github.com\/libp2p\/go-libp2p-core\/crypto\"\n\t\"github.com\/libp2p\/go-libp2p-core\/peer\"\n)\n\nconst certValidityPeriod = 100 * 365 * 24 * time.Hour \/\/ ~100 years\nconst certificatePrefix = \"libp2p-tls-handshake:\"\nconst alpn string = \"libp2p\"\n\nvar extensionID = getPrefixedExtensionID([]int{1, 1})\nvar extensionCritical bool \/\/ so we can mark the extension critical in tests\n\ntype signedKey struct {\n\tPubKey    []byte\n\tSignature []byte\n}\n\n\/\/ Identity is used to secure connections\ntype Identity struct {\n\tconfig tls.Config\n}\n\n\/\/ NewIdentity creates a new identity\nfunc NewIdentity(privKey ic.PrivKey) (*Identity, error) {\n\tcert, err := keyToCertificate(privKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Identity{\n\t\tconfig: tls.Config{\n\t\t\tMinVersion:               tls.VersionTLS13,\n\t\t\tPreferServerCipherSuites: preferServerCipherSuites(),\n\t\t\tInsecureSkipVerify:       true, \/\/ This is not insecure here. We will verify the cert chain ourselves.\n\t\t\tClientAuth:               tls.RequireAnyClientCert,\n\t\t\tCertificates:             []tls.Certificate{*cert},\n\t\t\tVerifyPeerCertificate: func(_ [][]byte, _ [][]*x509.Certificate) error {\n\t\t\t\tpanic(\"tls config not specialized for peer\")\n\t\t\t},\n\t\t\tNextProtos:             []string{alpn},\n\t\t\tSessionTicketsDisabled: true,\n\t\t},\n\t}, nil\n}\n\n\/\/ ConfigForPeer creates a new single-use tls.Config that verifies the peer's\n\/\/ certificate chain and returns the peer's public key via the channel. If the\n\/\/ peer ID is empty, the returned config will accept any peer.\n\/\/\n\/\/ It should be used to create a new tls.Config before securing either an\n\/\/ incoming or outgoing connection.\nfunc (i *Identity) ConfigForPeer(remote peer.ID) (*tls.Config, <-chan ic.PubKey) {\n\tkeyCh := make(chan ic.PubKey, 1)\n\t\/\/ We need to check the peer ID in the VerifyPeerCertificate callback.\n\t\/\/ The tls.Config it is also used for listening, and we might also have concurrent dials.\n\t\/\/ Clone it so we can check for the specific peer ID we're dialing here.\n\tconf := i.config.Clone()\n\t\/\/ We're using InsecureSkipVerify, so the verifiedChains parameter will always be empty.\n\t\/\/ We need to parse the certificates ourselves from the raw certs.\n\tconf.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {\n\t\tdefer close(keyCh)\n\n\t\tchain := make([]*x509.Certificate, len(rawCerts))\n\t\tfor i := 0; i < len(rawCerts); i++ {\n\t\t\tcert, err := x509.ParseCertificate(rawCerts[i])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tchain[i] = cert\n\t\t}\n\n\t\tpubKey, err := PubKeyFromCertChain(chain)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif remote != \"\" && !remote.MatchesPublicKey(pubKey) {\n\t\t\tpeerID, err := peer.IDFromPublicKey(pubKey)\n\t\t\tif err != nil {\n\t\t\t\tpeerID = peer.ID(fmt.Sprintf(\"(not determined: %s)\", err.Error()))\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"peer IDs don't match: expected %s, got %s\", remote, peerID)\n\t\t}\n\t\tkeyCh <- pubKey\n\t\treturn nil\n\t}\n\treturn conf, keyCh\n}\n\n\/\/ PubKeyFromCertChain verifies the certificate chain and extract the remote's public key.\nfunc PubKeyFromCertChain(chain []*x509.Certificate) (ic.PubKey, error) {\n\tif len(chain) != 1 {\n\t\treturn nil, errors.New(\"expected one certificates in the chain\")\n\t}\n\tcert := chain[0]\n\tpool := x509.NewCertPool()\n\tpool.AddCert(cert)\n\tvar found bool\n\tvar keyExt pkix.Extension\n\t\/\/ find the libp2p key extension, skipping all unknown extensions\n\tfor _, ext := range cert.Extensions {\n\t\tif extensionIDEqual(ext.Id, extensionID) {\n\t\t\tkeyExt = ext\n\t\t\tfound = true\n\t\t\tfor i, oident := range cert.UnhandledCriticalExtensions {\n\t\t\t\tif oident.Equal(ext.Id) {\n\t\t\t\t\t\/\/ delete the extension from UnhandledCriticalExtensions\n\t\t\t\t\tcert.UnhandledCriticalExtensions = append(cert.UnhandledCriticalExtensions[:i], cert.UnhandledCriticalExtensions[i+1:]...)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn nil, errors.New(\"expected certificate to contain the key extension\")\n\t}\n\tif _, err := cert.Verify(x509.VerifyOptions{Roots: pool}); err != nil {\n\t\t\/\/ If we return an x509 error here, it will be sent on the wire.\n\t\t\/\/ Wrap the error to avoid that.\n\t\treturn nil, fmt.Errorf(\"certificate verification failed: %s\", err)\n\t}\n\n\tvar sk signedKey\n\tif _, err := asn1.Unmarshal(keyExt.Value, &sk); err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshalling signed certificate failed: %s\", err)\n\t}\n\tpubKey, err := ic.UnmarshalPublicKey(sk.PubKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshalling public key failed: %s\", err)\n\t}\n\tcertKeyPub, err := x509.MarshalPKIXPublicKey(cert.PublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvalid, err := pubKey.Verify(append([]byte(certificatePrefix), certKeyPub...), sk.Signature)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"signature verification failed: %s\", err)\n\t}\n\tif !valid {\n\t\treturn nil, errors.New(\"signature invalid\")\n\t}\n\treturn pubKey, nil\n}\n\nfunc keyToCertificate(sk ic.PrivKey) (*tls.Certificate, error) {\n\tcertKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkeyBytes, err := ic.MarshalPublicKey(sk.GetPublic())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcertKeyPub, err := x509.MarshalPKIXPublicKey(certKey.Public())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsignature, err := sk.Sign(append([]byte(certificatePrefix), certKeyPub...))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvalue, err := asn1.Marshal(signedKey{\n\t\tPubKey:    keyBytes,\n\t\tSignature: signature,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbigNum := big.NewInt(1 << 62)\n\tsn, err := rand.Int(rand.Reader, bigNum)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsubjectSN, err := rand.Int(rand.Reader, bigNum)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttmpl := &x509.Certificate{\n\t\tSerialNumber: sn,\n\t\tNotBefore:    time.Time{},\n\t\tNotAfter:     time.Now().Add(certValidityPeriod),\n\t\t\/\/ According to RFC 3280, the issuer field must be set,\n\t\t\/\/ see https:\/\/datatracker.ietf.org\/doc\/html\/rfc3280#section-4.1.2.4.\n\t\tSubject: pkix.Name{SerialNumber: subjectSN.String()},\n\t\t\/\/ after calling CreateCertificate, these will end up in Certificate.Extensions\n\t\tExtraExtensions: []pkix.Extension{\n\t\t\t{Id: extensionID, Critical: extensionCritical, Value: value},\n\t\t},\n\t}\n\tcertDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, certKey.Public(), certKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &tls.Certificate{\n\t\tCertificate: [][]byte{certDER},\n\t\tPrivateKey:  certKey,\n\t}, nil\n}\n\n\/\/ We want nodes without AES hardware (e.g. ARM) support to always use ChaCha.\n\/\/ Only if both nodes have AES hardware support (e.g. x86), AES should be used.\n\/\/ x86->x86: AES, ARM->x86: ChaCha, x86->ARM: ChaCha and ARM->ARM: Chacha\n\/\/ This function returns true if we don't have AES hardware support, and false otherwise.\n\/\/ Thus, ARM servers will always use their own cipher suite preferences (ChaCha first),\n\/\/ and x86 servers will aways use the client's cipher suite preferences.\nfunc preferServerCipherSuites() bool {\n\t\/\/ Copied from the Go TLS implementation.\n\n\t\/\/ Check the cpu flags for each platform that has optimized GCM implementations.\n\t\/\/ Worst case, these variables will just all be false.\n\tvar (\n\t\thasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ\n\t\thasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL\n\t\t\/\/ Keep in sync with crypto\/aes\/cipher_s390x.go.\n\t\thasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)\n\n\t\thasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X\n\t)\n\treturn !hasGCMAsm\n}\n<commit_msg>set an actual NotBefore time on the certificate<commit_after>package libp2ptls\n\nimport (\n\t\"crypto\/ecdsa\"\n\t\"crypto\/elliptic\"\n\t\"crypto\/rand\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"crypto\/x509\/pkix\"\n\t\"encoding\/asn1\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\/big\"\n\t\"time\"\n\n\t\"golang.org\/x\/sys\/cpu\"\n\n\tic \"github.com\/libp2p\/go-libp2p-core\/crypto\"\n\t\"github.com\/libp2p\/go-libp2p-core\/peer\"\n)\n\nconst certValidityPeriod = 100 * 365 * 24 * time.Hour \/\/ ~100 years\nconst certificatePrefix = \"libp2p-tls-handshake:\"\nconst alpn string = \"libp2p\"\n\nvar extensionID = getPrefixedExtensionID([]int{1, 1})\nvar extensionCritical bool \/\/ so we can mark the extension critical in tests\n\ntype signedKey struct {\n\tPubKey    []byte\n\tSignature []byte\n}\n\n\/\/ Identity is used to secure connections\ntype Identity struct {\n\tconfig tls.Config\n}\n\n\/\/ NewIdentity creates a new identity\nfunc NewIdentity(privKey ic.PrivKey) (*Identity, error) {\n\tcert, err := keyToCertificate(privKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Identity{\n\t\tconfig: tls.Config{\n\t\t\tMinVersion:               tls.VersionTLS13,\n\t\t\tPreferServerCipherSuites: preferServerCipherSuites(),\n\t\t\tInsecureSkipVerify:       true, \/\/ This is not insecure here. We will verify the cert chain ourselves.\n\t\t\tClientAuth:               tls.RequireAnyClientCert,\n\t\t\tCertificates:             []tls.Certificate{*cert},\n\t\t\tVerifyPeerCertificate: func(_ [][]byte, _ [][]*x509.Certificate) error {\n\t\t\t\tpanic(\"tls config not specialized for peer\")\n\t\t\t},\n\t\t\tNextProtos:             []string{alpn},\n\t\t\tSessionTicketsDisabled: true,\n\t\t},\n\t}, nil\n}\n\n\/\/ ConfigForPeer creates a new single-use tls.Config that verifies the peer's\n\/\/ certificate chain and returns the peer's public key via the channel. If the\n\/\/ peer ID is empty, the returned config will accept any peer.\n\/\/\n\/\/ It should be used to create a new tls.Config before securing either an\n\/\/ incoming or outgoing connection.\nfunc (i *Identity) ConfigForPeer(remote peer.ID) (*tls.Config, <-chan ic.PubKey) {\n\tkeyCh := make(chan ic.PubKey, 1)\n\t\/\/ We need to check the peer ID in the VerifyPeerCertificate callback.\n\t\/\/ The tls.Config it is also used for listening, and we might also have concurrent dials.\n\t\/\/ Clone it so we can check for the specific peer ID we're dialing here.\n\tconf := i.config.Clone()\n\t\/\/ We're using InsecureSkipVerify, so the verifiedChains parameter will always be empty.\n\t\/\/ We need to parse the certificates ourselves from the raw certs.\n\tconf.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error {\n\t\tdefer close(keyCh)\n\n\t\tchain := make([]*x509.Certificate, len(rawCerts))\n\t\tfor i := 0; i < len(rawCerts); i++ {\n\t\t\tcert, err := x509.ParseCertificate(rawCerts[i])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tchain[i] = cert\n\t\t}\n\n\t\tpubKey, err := PubKeyFromCertChain(chain)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif remote != \"\" && !remote.MatchesPublicKey(pubKey) {\n\t\t\tpeerID, err := peer.IDFromPublicKey(pubKey)\n\t\t\tif err != nil {\n\t\t\t\tpeerID = peer.ID(fmt.Sprintf(\"(not determined: %s)\", err.Error()))\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"peer IDs don't match: expected %s, got %s\", remote, peerID)\n\t\t}\n\t\tkeyCh <- pubKey\n\t\treturn nil\n\t}\n\treturn conf, keyCh\n}\n\n\/\/ PubKeyFromCertChain verifies the certificate chain and extract the remote's public key.\nfunc PubKeyFromCertChain(chain []*x509.Certificate) (ic.PubKey, error) {\n\tif len(chain) != 1 {\n\t\treturn nil, errors.New(\"expected one certificates in the chain\")\n\t}\n\tcert := chain[0]\n\tpool := x509.NewCertPool()\n\tpool.AddCert(cert)\n\tvar found bool\n\tvar keyExt pkix.Extension\n\t\/\/ find the libp2p key extension, skipping all unknown extensions\n\tfor _, ext := range cert.Extensions {\n\t\tif extensionIDEqual(ext.Id, extensionID) {\n\t\t\tkeyExt = ext\n\t\t\tfound = true\n\t\t\tfor i, oident := range cert.UnhandledCriticalExtensions {\n\t\t\t\tif oident.Equal(ext.Id) {\n\t\t\t\t\t\/\/ delete the extension from UnhandledCriticalExtensions\n\t\t\t\t\tcert.UnhandledCriticalExtensions = append(cert.UnhandledCriticalExtensions[:i], cert.UnhandledCriticalExtensions[i+1:]...)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn nil, errors.New(\"expected certificate to contain the key extension\")\n\t}\n\tif _, err := cert.Verify(x509.VerifyOptions{Roots: pool}); err != nil {\n\t\t\/\/ If we return an x509 error here, it will be sent on the wire.\n\t\t\/\/ Wrap the error to avoid that.\n\t\treturn nil, fmt.Errorf(\"certificate verification failed: %s\", err)\n\t}\n\n\tvar sk signedKey\n\tif _, err := asn1.Unmarshal(keyExt.Value, &sk); err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshalling signed certificate failed: %s\", err)\n\t}\n\tpubKey, err := ic.UnmarshalPublicKey(sk.PubKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unmarshalling public key failed: %s\", err)\n\t}\n\tcertKeyPub, err := x509.MarshalPKIXPublicKey(cert.PublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvalid, err := pubKey.Verify(append([]byte(certificatePrefix), certKeyPub...), sk.Signature)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"signature verification failed: %s\", err)\n\t}\n\tif !valid {\n\t\treturn nil, errors.New(\"signature invalid\")\n\t}\n\treturn pubKey, nil\n}\n\nfunc keyToCertificate(sk ic.PrivKey) (*tls.Certificate, error) {\n\tcertKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkeyBytes, err := ic.MarshalPublicKey(sk.GetPublic())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcertKeyPub, err := x509.MarshalPKIXPublicKey(certKey.Public())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsignature, err := sk.Sign(append([]byte(certificatePrefix), certKeyPub...))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvalue, err := asn1.Marshal(signedKey{\n\t\tPubKey:    keyBytes,\n\t\tSignature: signature,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbigNum := big.NewInt(1 << 62)\n\tsn, err := rand.Int(rand.Reader, bigNum)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsubjectSN, err := rand.Int(rand.Reader, bigNum)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttmpl := &x509.Certificate{\n\t\tSerialNumber: sn,\n\t\tNotBefore:    time.Now().Add(-time.Hour),\n\t\tNotAfter:     time.Now().Add(certValidityPeriod),\n\t\t\/\/ According to RFC 3280, the issuer field must be set,\n\t\t\/\/ see https:\/\/datatracker.ietf.org\/doc\/html\/rfc3280#section-4.1.2.4.\n\t\tSubject: pkix.Name{SerialNumber: subjectSN.String()},\n\t\t\/\/ after calling CreateCertificate, these will end up in Certificate.Extensions\n\t\tExtraExtensions: []pkix.Extension{\n\t\t\t{Id: extensionID, Critical: extensionCritical, Value: value},\n\t\t},\n\t}\n\tcertDER, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, certKey.Public(), certKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &tls.Certificate{\n\t\tCertificate: [][]byte{certDER},\n\t\tPrivateKey:  certKey,\n\t}, nil\n}\n\n\/\/ We want nodes without AES hardware (e.g. ARM) support to always use ChaCha.\n\/\/ Only if both nodes have AES hardware support (e.g. x86), AES should be used.\n\/\/ x86->x86: AES, ARM->x86: ChaCha, x86->ARM: ChaCha and ARM->ARM: Chacha\n\/\/ This function returns true if we don't have AES hardware support, and false otherwise.\n\/\/ Thus, ARM servers will always use their own cipher suite preferences (ChaCha first),\n\/\/ and x86 servers will aways use the client's cipher suite preferences.\nfunc preferServerCipherSuites() bool {\n\t\/\/ Copied from the Go TLS implementation.\n\n\t\/\/ Check the cpu flags for each platform that has optimized GCM implementations.\n\t\/\/ Worst case, these variables will just all be false.\n\tvar (\n\t\thasGCMAsmAMD64 = cpu.X86.HasAES && cpu.X86.HasPCLMULQDQ\n\t\thasGCMAsmARM64 = cpu.ARM64.HasAES && cpu.ARM64.HasPMULL\n\t\t\/\/ Keep in sync with crypto\/aes\/cipher_s390x.go.\n\t\thasGCMAsmS390X = cpu.S390X.HasAES && cpu.S390X.HasAESCBC && cpu.S390X.HasAESCTR && (cpu.S390X.HasGHASH || cpu.S390X.HasAESGCM)\n\n\t\thasGCMAsm = hasGCMAsmAMD64 || hasGCMAsmARM64 || hasGCMAsmS390X\n\t)\n\treturn !hasGCMAsm\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package ioconn allows any combination of an io.Reader, io.Writer and io.Closer to become a net.Conn\npackage ioconn\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\n\/\/ CloserFunc is a func that implements the io.Closer interface allowing a\n\/\/ closure or other function to be io.Closer\ntype CloserFunc func() error\n\n\/\/ Close simply calls the CloserFunc func\nfunc (c CloserFunc) Close() error {\n\treturn c()\n}\n\n\/\/ FileAddr is a net.Addr that represents a file. Should be a full path\ntype FileAddr string\n\n\/\/ Network always returns \"file\"\nfunc (f FileAddr) Network() string {\n\treturn \"file\"\n}\n\n\/\/ String returns file:\/\/path\nfunc (f FileAddr) String() string {\n\treturn \"file:\/\/\" + string(f)\n}\n\n\/\/ Addr is a simple implementation of the net.Addr interface\ntype Addr struct {\n\tNet, Str string\n}\n\n\/\/ Network returns the Net string\nfunc (a Addr) Network() string {\n\treturn a.Net\n}\n\n\/\/ String returns the Str string\nfunc (a Addr) String() string {\n\treturn a.Str\n}\n\n\/\/ Conn implements a net.Conn\ntype Conn struct {\n\tio.Reader\n\tio.Writer\n\tio.Closer\n\tLocal, Remote net.Addr\n}\n\n\/\/ LocalAddr returns the Local Address\nfunc (c Conn) LocalAddr() net.Addr {\n\treturn c.Local\n}\n\n\/\/ RemoteAddr returns the Remote Address\nfunc (c Conn) RemoteAddr() net.Addr {\n\treturn c.Remote\n}\n\n\/\/ SetDeadline is unimplemented and always returns an error\nfunc (Conn) SetDeadline(time.Time) error {\n\treturn ErrUnimplemented\n}\n\n\/\/ SetReadDeadline is unimplemented and always returns an error\nfunc (Conn) SetReadDeadline(time.Time) error {\n\treturn ErrUnimplemented\n}\n\n\/\/ SetWriteDeadline is unimplemented and always returns an error\nfunc (Conn) SetWriteDeadline(time.Time) error {\n\treturn ErrUnimplemented\n}\n\n\/\/ Errors\nvar ErrUnimplemented = errors.New(\"not implmented\")\n<commit_msg>Added simple timeout implementation<commit_after>\/\/ Package ioconn allows any combination of an io.Reader, io.Writer and io.Closer to become a net.Conn\npackage ioconn\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\n\/\/ CloserFunc is a func that implements the io.Closer interface allowing a\n\/\/ closure or other function to be io.Closer\ntype CloserFunc func() error\n\n\/\/ Close simply calls the CloserFunc func\nfunc (c CloserFunc) Close() error {\n\treturn c()\n}\n\n\/\/ FileAddr is a net.Addr that represents a file. Should be a full path\ntype FileAddr string\n\n\/\/ Network always returns \"file\"\nfunc (f FileAddr) Network() string {\n\treturn \"file\"\n}\n\n\/\/ String returns file:\/\/path\nfunc (f FileAddr) String() string {\n\treturn \"file:\/\/\" + string(f)\n}\n\n\/\/ Addr is a simple implementation of the net.Addr interface\ntype Addr struct {\n\tNet, Str string\n}\n\n\/\/ Network returns the Net string\nfunc (a Addr) Network() string {\n\treturn a.Net\n}\n\n\/\/ String returns the Str string\nfunc (a Addr) String() string {\n\treturn a.Str\n}\n\n\/\/ Conn implements a net.Conn\ntype Conn struct {\n\tio.Reader\n\tio.Writer\n\tio.Closer\n\tLocal, Remote               net.Addr\n\tReadDeadline, WriteDeadline time.Time\n}\n\n\/\/ Read implements the io.Reader interface\nfunc (c *Conn) Read(p []byte) (int, error) {\n\tif time.Now().After(c.ReadDeadline) {\n\t\treturn 0, ErrTimeout\n\t}\n\treturn c.Reader.Read(p)\n}\n\n\/\/ Write implements the io.Writer interface\nfunc (c *Conn) Write(p []byte) (int, error) {\n\tif time.Now().After(c.WriteDeadline) {\n\t\treturn 0, ErrTimeout\n\t}\n\treturn c.Writer.Write(p)\n}\n\n\/\/ LocalAddr returns the Local Address\nfunc (c *Conn) LocalAddr() net.Addr {\n\treturn c.Local\n}\n\n\/\/ RemoteAddr returns the Remote Address\nfunc (c *Conn) RemoteAddr() net.Addr {\n\treturn c.Remote\n}\n\n\/\/ SetDeadline is unimplemented and always returns an error\nfunc (c *Conn) SetDeadline(t time.Time) error {\n\tc.ReadDeadline = t\n\tc.WriteDeadline = t\n\treturn nil\n}\n\n\/\/ SetReadDeadline is unimplemented and always returns an error\nfunc (c *Conn) SetReadDeadline(t time.Time) error {\n\tc.ReadDeadline = t\n\treturn nil\n}\n\n\/\/ SetWriteDeadline is unimplemented and always returns an error\nfunc (c *Conn) SetWriteDeadline(t time.Time) error {\n\tc.WriteDeadline = t\n\treturn nil\n}\n\n\/\/ Timeout Error\nvar ErrTimeout = errors.New(\"timeout occurred\")\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage params\n\nimport \"github.com\/juju\/juju\/storage\"\n\n\/\/ MachineBlockDevices holds a machine tag and the block devices present\n\/\/ on that machine.\ntype MachineBlockDevices struct {\n\tMachine      string                `json:\"machine\"`\n\tBlockDevices []storage.BlockDevice `json:\"blockdevices,omitempty\"`\n}\n\n\/\/ SetMachineBlockDevices holds the arguments for recording the block\n\/\/ devices present on a set of machines.\ntype SetMachineBlockDevices struct {\n\tMachineBlockDevices []MachineBlockDevices `json:\"machineblockdevices\"`\n}\n\n\/\/ BlockDeviceResult holds the result of an API call to retrieve details\n\/\/ of a block device.\ntype BlockDeviceResult struct {\n\tResult storage.BlockDevice `json:\"result\"`\n\tError  *Error              `json:\"error,omitempty\"`\n}\n\n\/\/ BlockDeviceResults holds the result of an API call to retrieve details\n\/\/ of multiple block devices.\ntype BlockDeviceResults struct {\n\tResults []BlockDeviceResult `json:\"results,omitempty\"`\n}\n\n\/\/ BlockDevicesResult holds the result of an API call to retrieve details\n\/\/ of all block devices relating to some entity.\ntype BlockDevicesResult struct {\n\tResult []storage.BlockDevice `json:\"result\"`\n\tError  *Error                `json:\"error,omitempty\"`\n}\n\n\/\/ BlockDevicseResults holds the result of an API call to retrieve details\n\/\/ of all block devices relating to some entities.\ntype BlockDevicesResults struct {\n\tResults []BlockDevicesResult `json:\"results,omitempty\"`\n}\n\n\/\/ StorageInstance describes a storage instance.\ntype StorageInstance struct {\n\tStorageTag string\n\tOwnerTag   string\n\tKind       StorageKind\n}\n\n\/\/ StorageKind is the kind of a storage instance.\ntype StorageKind int\n\nconst (\n\tStorageKindUnknown StorageKind = iota\n\tStorageKindBlock\n\tStorageKindFilesystem\n)\n\nfunc (k *StorageKind) String() string {\n\tswitch *k {\n\tcase StorageKindBlock:\n\t\treturn \"block\"\n\tcase StorageKindFilesystem:\n\t\treturn \"file system\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\n\/\/ StorageInstanceResult holds the result of an API call to retrieve details\n\/\/ of a storage instance.\ntype StorageInstanceResult struct {\n\tResult StorageInstance `json:\"result\"`\n\tError  *Error          `json:\"error,omitempty\"`\n}\n\n\/\/ StorageInstanceResults holds the result of an API call to retrieve details\n\/\/ of multiple storage instances.\ntype StorageInstanceResults struct {\n\tResults []StorageInstanceResult `json:\"results,omitempty\"`\n}\n\n\/\/ StorageAttachment describes a unit's attached storage instance.\ntype StorageAttachment struct {\n\tStorageTag string\n\tOwnerTag   string\n\tUnitTag    string\n\n\tKind     StorageKind\n\tLocation string\n\tLife     Life\n}\n\n\/\/ StorageAttachmentId identifies a storage attachment by the tags of the\n\/\/ related unit and storage instance.\ntype StorageAttachmentId struct {\n\tStorageTag string `json:\"storagetag\"`\n\tUnitTag    string `json:\"unittag\"`\n}\n\n\/\/ StorageAttachmentIds holds a set of storage attachment identifiers.\ntype StorageAttachmentIds struct {\n\tIds []StorageAttachmentId `json:\"ids\"`\n}\n\n\/\/ StorageAttachmentsResult holds the result of an API call to retrieve details\n\/\/ of a unit's attached storage instances.\ntype StorageAttachmentsResult struct {\n\tResult []StorageAttachment `json:\"result\"`\n\tError  *Error              `json:\"error,omitempty\"`\n}\n\n\/\/ StorageAttachmentsResults holds the result of an API call to retrieve details\n\/\/ of multiple units' attached storage instances.\ntype StorageAttachmentsResults struct {\n\tResults []StorageAttachmentsResult `json:\"results,omitempty\"`\n}\n\n\/\/ StorageAttachmentResult holds the result of an API call to retrieve details\n\/\/ of a storage attachment.\ntype StorageAttachmentResult struct {\n\tResult StorageAttachment `json:\"result\"`\n\tError  *Error            `json:\"error,omitempty\"`\n}\n\n\/\/ StorageAttachmentResults holds the result of an API call to retrieve details\n\/\/ of multiple storage attachments.\ntype StorageAttachmentResults struct {\n\tResults []StorageAttachmentResult `json:\"results,omitempty\"`\n}\n\n\/\/ Volume describes a storage volume in the environment.\ntype Volume struct {\n\tVolumeTag string `json:\"volumetag\"`\n\tVolumeId  string `json:\"volumeid\"`\n\tSerial    string `json:\"serial\"`\n\t\/\/ Size is the size of the volume in MiB.\n\tSize uint64 `json:\"size\"`\n}\n\n\/\/ VolumeAttachmentId identifies a volume attachment by the tags of the\n\/\/ related machine and volume.\ntype VolumeAttachmentId struct {\n\tVolumeTag  string `json:\"volumetag\"`\n\tMachineTag string `json:\"machinetag\"`\n}\n\n\/\/ VolumeAttachmentIds holds a set of volume attachment identifiers.\ntype VolumeAttachmentIds struct {\n\tIds []VolumeAttachmentId `json:\"ids\"`\n}\n\n\/\/ VolumeAttachment describes a volume attachment.\ntype VolumeAttachment struct {\n\tVolumeTag  string `json:\"volumetag\"`\n\tMachineTag string `json:\"machinetag\"`\n\tDeviceName string `json:\"devicename,omitempty\"`\n}\n\n\/\/ VolumeParams holds the parameters for creating a storage volume.\ntype VolumeParams struct {\n\tVolumeTag  string                 `json:\"volumetag\"`\n\tSize       uint64                 `json:\"size\"`\n\tProvider   string                 `json:\"provider\"`\n\tAttributes map[string]interface{} `json:\"attributes,omitempty\"`\n\n\t\/\/ Machine is the tag of the machine that the volume should\n\t\/\/ be initially attached to, if any.\n\tMachineTag string `json:\"machinetag,omitempty\"`\n}\n\n\/\/ VolumePreparationInfo holds the information regarding preparing\n\/\/ a storage volume for use.\ntype VolumePreparationInfo struct {\n\tNeedsFilesystem bool   `json:\"needsfilesystem\"`\n\tDevicePath      string `json:\"devicepath\"`\n}\n\n\/\/ VolumePreparationInfoResult holds a singular VolumePreparationInfo\n\/\/ result, or an error.\ntype VolumePreparationInfoResult struct {\n\tResult VolumePreparationInfo `json:\"result\"`\n\tError  *Error                `json:\"error,omitempty\"`\n}\n\n\/\/ VolumePreparationInfoResult holds a set of VolumePreparationInfoResults.\ntype VolumePreparationInfoResults struct {\n\tResults []VolumePreparationInfoResult `json:\"results,omitempty\"`\n}\n\n\/\/ VolumeAttachmentsResult holds the volume attachments for a single\n\/\/ machine, or an error.\ntype VolumeAttachmentsResult struct {\n\tAttachments []VolumeAttachment `json:\"attachments,omitempty\"`\n\tError       *Error             `json:\"error,omitempty\"`\n}\n\n\/\/ VolumeAttachmensResult holds a set of VolumeAttachmentsResults for\n\/\/ a set of machines.\ntype VolumeAttachmentsResults struct {\n\tResults []VolumeAttachmentsResult `json:\"results,omitempty\"`\n}\n\n\/\/ StorageInfo holds information about storage.\ntype StorageInfo struct {\n\t\/\/ StorageTag holds tag for this storage.\n\tStorageTag string `json:\"storagetag\"`\n\t\/\/ OwnerTag holds tag for the owner of this storage, unit or service.\n\tOwnerTag string `json:\"ownertag\"`\n\t\/\/ Kind holds what kind of storage this instance is.\n\tKind StorageKind `json:\"kind\"`\n\t\/\/ Attached explicitly states if this instance is attached.\n\t\/\/ Having this information on the struct allows to\n\t\/\/ have this logic in one place rather than deducing it\n\t\/\/ every time this instance is used.\n\tAttached bool `json:\"attached\"`\n\t\/\/ UnitTag holds tag for unit for attached instances.\n\tUnitTag string `json:\"unittag,omitempty\"`\n\t\/\/ Location holds location for provisioned attached instances.\n\tLocation string `json:\"location,omitempty\"`\n\t\/\/ Provisioned explicitly states if this instance is provisioned.\n\t\/\/ Having this information on the struct allows to\n\t\/\/ have this logic in one place rather than deducing it\n\t\/\/ every time this instance is used.\n\tProvisioned bool `json:\"provisioned,omitempty\"`\n}\n\n\/\/ StorageShowResult holds information about a storage instance\n\/\/ or error related to its retrieval.\ntype StorageShowResult struct {\n\tResult StorageInfo `json:\"result,omitempty\"`\n\tError  *Error      `json:\"error,omitempty\"`\n}\n\n\/\/ StorageShowResults holds a collection of storage instances.\ntype StorageShowResults struct {\n\tResults []StorageShowResult `json:\"results,omitempty\"`\n}\n<commit_msg>Changed json optionality for some properties.<commit_after>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage params\n\nimport \"github.com\/juju\/juju\/storage\"\n\n\/\/ MachineBlockDevices holds a machine tag and the block devices present\n\/\/ on that machine.\ntype MachineBlockDevices struct {\n\tMachine      string                `json:\"machine\"`\n\tBlockDevices []storage.BlockDevice `json:\"blockdevices,omitempty\"`\n}\n\n\/\/ SetMachineBlockDevices holds the arguments for recording the block\n\/\/ devices present on a set of machines.\ntype SetMachineBlockDevices struct {\n\tMachineBlockDevices []MachineBlockDevices `json:\"machineblockdevices\"`\n}\n\n\/\/ BlockDeviceResult holds the result of an API call to retrieve details\n\/\/ of a block device.\ntype BlockDeviceResult struct {\n\tResult storage.BlockDevice `json:\"result\"`\n\tError  *Error              `json:\"error,omitempty\"`\n}\n\n\/\/ BlockDeviceResults holds the result of an API call to retrieve details\n\/\/ of multiple block devices.\ntype BlockDeviceResults struct {\n\tResults []BlockDeviceResult `json:\"results,omitempty\"`\n}\n\n\/\/ BlockDevicesResult holds the result of an API call to retrieve details\n\/\/ of all block devices relating to some entity.\ntype BlockDevicesResult struct {\n\tResult []storage.BlockDevice `json:\"result\"`\n\tError  *Error                `json:\"error,omitempty\"`\n}\n\n\/\/ BlockDevicseResults holds the result of an API call to retrieve details\n\/\/ of all block devices relating to some entities.\ntype BlockDevicesResults struct {\n\tResults []BlockDevicesResult `json:\"results,omitempty\"`\n}\n\n\/\/ StorageInstance describes a storage instance.\ntype StorageInstance struct {\n\tStorageTag string\n\tOwnerTag   string\n\tKind       StorageKind\n}\n\n\/\/ StorageKind is the kind of a storage instance.\ntype StorageKind int\n\nconst (\n\tStorageKindUnknown StorageKind = iota\n\tStorageKindBlock\n\tStorageKindFilesystem\n)\n\nfunc (k *StorageKind) String() string {\n\tswitch *k {\n\tcase StorageKindBlock:\n\t\treturn \"block\"\n\tcase StorageKindFilesystem:\n\t\treturn \"file system\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\n\/\/ StorageInstanceResult holds the result of an API call to retrieve details\n\/\/ of a storage instance.\ntype StorageInstanceResult struct {\n\tResult StorageInstance `json:\"result\"`\n\tError  *Error          `json:\"error,omitempty\"`\n}\n\n\/\/ StorageInstanceResults holds the result of an API call to retrieve details\n\/\/ of multiple storage instances.\ntype StorageInstanceResults struct {\n\tResults []StorageInstanceResult `json:\"results,omitempty\"`\n}\n\n\/\/ StorageAttachment describes a unit's attached storage instance.\ntype StorageAttachment struct {\n\tStorageTag string\n\tOwnerTag   string\n\tUnitTag    string\n\n\tKind     StorageKind\n\tLocation string\n\tLife     Life\n}\n\n\/\/ StorageAttachmentId identifies a storage attachment by the tags of the\n\/\/ related unit and storage instance.\ntype StorageAttachmentId struct {\n\tStorageTag string `json:\"storagetag\"`\n\tUnitTag    string `json:\"unittag\"`\n}\n\n\/\/ StorageAttachmentIds holds a set of storage attachment identifiers.\ntype StorageAttachmentIds struct {\n\tIds []StorageAttachmentId `json:\"ids\"`\n}\n\n\/\/ StorageAttachmentsResult holds the result of an API call to retrieve details\n\/\/ of a unit's attached storage instances.\ntype StorageAttachmentsResult struct {\n\tResult []StorageAttachment `json:\"result\"`\n\tError  *Error              `json:\"error,omitempty\"`\n}\n\n\/\/ StorageAttachmentsResults holds the result of an API call to retrieve details\n\/\/ of multiple units' attached storage instances.\ntype StorageAttachmentsResults struct {\n\tResults []StorageAttachmentsResult `json:\"results,omitempty\"`\n}\n\n\/\/ StorageAttachmentResult holds the result of an API call to retrieve details\n\/\/ of a storage attachment.\ntype StorageAttachmentResult struct {\n\tResult StorageAttachment `json:\"result\"`\n\tError  *Error            `json:\"error,omitempty\"`\n}\n\n\/\/ StorageAttachmentResults holds the result of an API call to retrieve details\n\/\/ of multiple storage attachments.\ntype StorageAttachmentResults struct {\n\tResults []StorageAttachmentResult `json:\"results,omitempty\"`\n}\n\n\/\/ Volume describes a storage volume in the environment.\ntype Volume struct {\n\tVolumeTag string `json:\"volumetag\"`\n\tVolumeId  string `json:\"volumeid\"`\n\tSerial    string `json:\"serial\"`\n\t\/\/ Size is the size of the volume in MiB.\n\tSize uint64 `json:\"size\"`\n}\n\n\/\/ VolumeAttachmentId identifies a volume attachment by the tags of the\n\/\/ related machine and volume.\ntype VolumeAttachmentId struct {\n\tVolumeTag  string `json:\"volumetag\"`\n\tMachineTag string `json:\"machinetag\"`\n}\n\n\/\/ VolumeAttachmentIds holds a set of volume attachment identifiers.\ntype VolumeAttachmentIds struct {\n\tIds []VolumeAttachmentId `json:\"ids\"`\n}\n\n\/\/ VolumeAttachment describes a volume attachment.\ntype VolumeAttachment struct {\n\tVolumeTag  string `json:\"volumetag\"`\n\tMachineTag string `json:\"machinetag\"`\n\tDeviceName string `json:\"devicename,omitempty\"`\n}\n\n\/\/ VolumeParams holds the parameters for creating a storage volume.\ntype VolumeParams struct {\n\tVolumeTag  string                 `json:\"volumetag\"`\n\tSize       uint64                 `json:\"size\"`\n\tProvider   string                 `json:\"provider\"`\n\tAttributes map[string]interface{} `json:\"attributes,omitempty\"`\n\n\t\/\/ Machine is the tag of the machine that the volume should\n\t\/\/ be initially attached to, if any.\n\tMachineTag string `json:\"machinetag,omitempty\"`\n}\n\n\/\/ VolumePreparationInfo holds the information regarding preparing\n\/\/ a storage volume for use.\ntype VolumePreparationInfo struct {\n\tNeedsFilesystem bool   `json:\"needsfilesystem\"`\n\tDevicePath      string `json:\"devicepath\"`\n}\n\n\/\/ VolumePreparationInfoResult holds a singular VolumePreparationInfo\n\/\/ result, or an error.\ntype VolumePreparationInfoResult struct {\n\tResult VolumePreparationInfo `json:\"result\"`\n\tError  *Error                `json:\"error,omitempty\"`\n}\n\n\/\/ VolumePreparationInfoResult holds a set of VolumePreparationInfoResults.\ntype VolumePreparationInfoResults struct {\n\tResults []VolumePreparationInfoResult `json:\"results,omitempty\"`\n}\n\n\/\/ VolumeAttachmentsResult holds the volume attachments for a single\n\/\/ machine, or an error.\ntype VolumeAttachmentsResult struct {\n\tAttachments []VolumeAttachment `json:\"attachments,omitempty\"`\n\tError       *Error             `json:\"error,omitempty\"`\n}\n\n\/\/ VolumeAttachmensResult holds a set of VolumeAttachmentsResults for\n\/\/ a set of machines.\ntype VolumeAttachmentsResults struct {\n\tResults []VolumeAttachmentsResult `json:\"results,omitempty\"`\n}\n\n\/\/ StorageInfo holds information about storage.\ntype StorageInfo struct {\n\t\/\/ StorageTag holds tag for this storage.\n\tStorageTag string `json:\"storagetag\"`\n\t\/\/ OwnerTag holds tag for the owner of this storage, unit or service.\n\tOwnerTag string `json:\"ownertag\"`\n\t\/\/ Kind holds what kind of storage this instance is.\n\tKind StorageKind `json:\"kind\"`\n\t\/\/ Attached explicitly states if this instance is attached.\n\t\/\/ Having this information on the struct allows to\n\t\/\/ have this logic in one place rather than deducing it\n\t\/\/ every time this instance is used.\n\tAttached bool `json:\"attached\"`\n\t\/\/ UnitTag holds tag for unit for attached instances.\n\tUnitTag string `json:\"unittag,omitempty\"`\n\t\/\/ Location holds location for provisioned attached instances.\n\tLocation string `json:\"location,omitempty\"`\n\t\/\/ Provisioned explicitly states if this instance is provisioned.\n\t\/\/ Having this information on the struct allows to\n\t\/\/ have this logic in one place rather than deducing it\n\t\/\/ every time this instance is used.\n\tProvisioned bool `json:\"provisioned\"`\n}\n\n\/\/ StorageShowResult holds information about a storage instance\n\/\/ or error related to its retrieval.\ntype StorageShowResult struct {\n\tResult StorageInfo `json:\"result\"`\n\tError  *Error      `json:\"error,omitempty\"`\n}\n\n\/\/ StorageShowResults holds a collection of storage instances.\ntype StorageShowResults struct {\n\tResults []StorageShowResult `json:\"results,omitempty\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"archive\/zip\"\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"image\"\n\t\"image\/gif\"\n\t\"image\/jpeg\"\n\t\"image\/png\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"strings\"\n\n\t\"github.com\/beevik\/etree\"\n\tzglob \"github.com\/mattn\/go-zglob\"\n\t\"github.com\/nfnt\/resize\"\n\t\"golang.org\/x\/tools\/godoc\/vfs\/zipfs\"\n)\n\n\/\/ Series represents a book series\ntype Series struct {\n\tName  string  `json:\"name,omitempty\"`\n\tID    string  `json:\"id,omitempty\"`\n\tIndex float64 `json:\"index,omitempty\"`\n}\n\n\/\/ Book represents a book\ntype Book struct {\n\tID          string    `json:\"id\"`\n\tTitle       string    `json:\"title\"`\n\tAuthor      string    `json:\"author,omitempty\"`\n\tAuthorID    string    `json:\"authorid\"`\n\tPublisher   string    `json:\"publisher,omitempty\"`\n\tDescription string    `json:\"description,omitempty\"`\n\tSeries      Series    `json:\"series,omitempty\"`\n\tFilepath    string    `json:\"filepath\"`\n\tHasCover    bool      `json:\"hascover\"`\n\tModTime     time.Time `json:\"modtime,omitempty\"`\n\tFileType    string    `json:\"filetype,omitempty\"`\n}\n\n\/\/ NewBookFromFile creates a book object from a file\nfunc NewBookFromFile(path, coverpath string) (*Book, error) {\n\tbook := new(Book)\n\tbook.Title = filepath.Base(path)\n\tbook.Filepath = path\n\tbook.FileType = strings.ToLower(strings.Replace(filepath.Ext(path), \".\", \"\", -1))\n\n\tif file, err := os.Stat(path); err == nil {\n\t\tbook.ModTime = file.ModTime()\n\t}\n\n\tprocessed := false\n\n\tswitch ft := book.FileType; ft {\n\tcase \"epub\":\n\t\tzr, err := zip.OpenReader(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tzfs := zipfs.New(zr, \"epub\")\n\n\t\trsk, err := zfs.Open(\"\/META-INF\/container.xml\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer rsk.Close()\n\t\tcontainer := etree.NewDocument()\n\t\t_, err = container.ReadFrom(rsk)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trootfile := \"\"\n\t\tfor _, e := range container.FindElements(\"\/\/rootfiles\/rootfile[@full-path]\") {\n\t\t\trootfile = e.SelectAttrValue(\"full-path\", \"\")\n\t\t}\n\t\tif rootfile == \"\" {\n\t\t\treturn nil, errors.New(\"Cannot parse container\")\n\t\t}\n\n\t\trrsk, err := zfs.Open(\"\/\" + rootfile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer rrsk.Close()\n\t\topfdir := filepath.Dir(rootfile)\n\t\topf := etree.NewDocument()\n\t\t_, err = opf.ReadFrom(rrsk)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbook.Title = filepath.Base(path)\n\t\tfor _, e := range opf.FindElements(\"\/\/title\") {\n\t\t\tbook.Title = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/creator\") {\n\t\t\tbook.Author = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/publisher\") {\n\t\t\tbook.Publisher = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/description\") {\n\t\t\tbook.Description = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/meta[@name='calibre:series']\") {\n\t\t\tbook.Series.Name = e.SelectAttrValue(\"content\", \"\")\n\t\t\tseriesid := sha1.New()\n\t\t\tio.WriteString(seriesid, book.Series.Name)\n\t\t\tbook.Series.ID = hex.EncodeToString(seriesid.Sum(nil))[:10]\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/meta[@name='calibre:series_index']\") {\n\t\t\ti, err := strconv.ParseFloat(e.SelectAttrValue(\"content\", \"0\"), 64)\n\t\t\tif err == nil {\n\t\t\t\tbook.Series.Index = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tid := sha1.New()\n\t\tio.WriteString(id, book.Author)\n\t\tbook.AuthorID = hex.EncodeToString(id.Sum(nil))[:10]\n\t\tio.WriteString(id, book.Series.Name)\n\t\tio.WriteString(id, book.Title)\n\t\tbook.ID = hex.EncodeToString(id.Sum(nil))[:10]\n\n\t\tfor _, e := range opf.FindElements(\"\/\/meta[@name='cover']\") {\n\t\t\tcoverid := e.SelectAttrValue(\"content\", \"\")\n\t\t\tif coverid != \"\" {\n\t\t\t\tfor _, f := range opf.FindElements(\"\/\/[@id='\" + coverid + \"']\") {\n\t\t\t\t\tcover := f.SelectAttrValue(\"href\", \"\")\n\t\t\t\t\tif cover != \"\" {\n\t\t\t\t\t\tcr, err := zfs.Open(\"\/\" + opfdir + \"\/\" + cover)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer cr.Close()\n\n\t\t\t\t\t\text := filepath.Ext(cover)\n\t\t\t\t\t\tif ext == \".jpeg\" {\n\t\t\t\t\t\t\text = \".jpg\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcpath := filepath.Join(coverpath, book.ID+\".jpg\")\n\t\t\t\t\t\tthumbpath := filepath.Join(coverpath, book.ID+\"_thumb\"+\".jpg\")\n\n\t\t\t\t\t\tvar img image.Image\n\n\t\t\t\t\t\tswitch ext {\n\t\t\t\t\t\tcase \".jpg\":\n\t\t\t\t\t\t\timg, err = jpeg.Decode(cr)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \".gif\":\n\t\t\t\t\t\t\timg, err = gif.Decode(cr)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \".png\":\n\t\t\t\t\t\t\timg, err = png.Decode(cr)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcoverfile, err := os.Create(cpath)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer coverfile.Close()\n\t\t\t\t\t\terr = jpeg.Encode(coverfile, img, nil)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/ Better quality: thumb := resize.Resize(200, 0, img, resize.Lanczos2)\n\t\t\t\t\t\tthumb := resize.Resize(200, 0, img, resize.Bicubic)\n\t\t\t\t\t\tthumbfile, err := os.Create(thumbpath)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer thumbfile.Close()\n\t\t\t\t\t\terr = jpeg.Encode(thumbfile, thumb, nil)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbook.HasCover = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tprocessed = true\n\t}\n\n\tif !processed {\n\t\treturn nil, fmt.Errorf(\"Unknown filetype: %s\", book.FileType)\n\t}\n\n\treturn book, nil\n}\n\n\/\/ BookList is a slice of books\ntype BookList []Book\n\n\/\/ NewBookListFromDir creates a BookList from the books in a dir. It will still return if there are errors indexing some of the books.\nfunc NewBookListFromDir(path, coverdir string, printlog bool) (*BookList, error) {\n\tmatches, err := zglob.Glob(filepath.Join(path, \"\/**\/*.epub\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar books BookList\n\tfor i, filename := range matches {\n\t\tif printlog {\n\t\t\tlog.Printf(\"%.f%% Indexing %s\\n\", float64(i)\/float64(len(matches))*100, filename)\n\t\t}\n\t\tbook, err := NewBookFromFile(filename, coverdir)\n\t\tif err != nil {\n\t\t\tif printlog {\n\t\t\t\tlog.Printf(\"Error indexing %s: %s\\n\", filename, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tbooks = append(books, *book)\n\t}\n\treturn &books, nil\n}\n<commit_msg>Added initial PDF support<commit_after>package main\n\nimport (\n\t\"archive\/zip\"\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"image\"\n\t\"image\/gif\"\n\t\"image\/jpeg\"\n\t\"image\/png\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"strings\"\n\n\t\"github.com\/beevik\/etree\"\n\tzglob \"github.com\/mattn\/go-zglob\"\n\t\"github.com\/nfnt\/resize\"\n\t\"golang.org\/x\/tools\/godoc\/vfs\/zipfs\"\n)\n\n\/\/ Series represents a book series\ntype Series struct {\n\tName  string  `json:\"name,omitempty\"`\n\tID    string  `json:\"id,omitempty\"`\n\tIndex float64 `json:\"index,omitempty\"`\n}\n\n\/\/ Book represents a book\ntype Book struct {\n\tID          string    `json:\"id\"`\n\tTitle       string    `json:\"title\"`\n\tAuthor      string    `json:\"author,omitempty\"`\n\tAuthorID    string    `json:\"authorid\"`\n\tPublisher   string    `json:\"publisher,omitempty\"`\n\tDescription string    `json:\"description,omitempty\"`\n\tSeries      Series    `json:\"series,omitempty\"`\n\tFilepath    string    `json:\"filepath\"`\n\tHasCover    bool      `json:\"hascover\"`\n\tModTime     time.Time `json:\"modtime,omitempty\"`\n\tFileType    string    `json:\"filetype,omitempty\"`\n}\n\n\/\/ NewBookFromFile creates a book object from a file\nfunc NewBookFromFile(path, coverpath string) (*Book, error) {\n\tbook := new(Book)\n\tbook.Title = filepath.Base(path)\n\tbook.Filepath = path\n\tbook.FileType = strings.ToLower(strings.Replace(filepath.Ext(path), \".\", \"\", -1))\n\n\tif file, err := os.Stat(path); err == nil {\n\t\tbook.ModTime = file.ModTime()\n\t}\n\n\tprocessed := false\n\n\tswitch ft := book.FileType; ft {\n\tcase \"pdf\":\n\t\tbook.Title = filepath.Base(path)\n\n\t\tid := sha1.New()\n\t\tio.WriteString(id, book.Author)\n\t\tbook.AuthorID = hex.EncodeToString(id.Sum(nil))[:10]\n\t\tio.WriteString(id, book.Series.Name)\n\t\tio.WriteString(id, book.Title)\n\t\tbook.ID = hex.EncodeToString(id.Sum(nil))[:10]\n\n\t\tprocessed = true\n\tcase \"epub\":\n\t\tzr, err := zip.OpenReader(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tzfs := zipfs.New(zr, \"epub\")\n\n\t\trsk, err := zfs.Open(\"\/META-INF\/container.xml\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer rsk.Close()\n\t\tcontainer := etree.NewDocument()\n\t\t_, err = container.ReadFrom(rsk)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trootfile := \"\"\n\t\tfor _, e := range container.FindElements(\"\/\/rootfiles\/rootfile[@full-path]\") {\n\t\t\trootfile = e.SelectAttrValue(\"full-path\", \"\")\n\t\t}\n\t\tif rootfile == \"\" {\n\t\t\treturn nil, errors.New(\"Cannot parse container\")\n\t\t}\n\n\t\trrsk, err := zfs.Open(\"\/\" + rootfile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer rrsk.Close()\n\t\topfdir := filepath.Dir(rootfile)\n\t\topf := etree.NewDocument()\n\t\t_, err = opf.ReadFrom(rrsk)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbook.Title = filepath.Base(path)\n\t\tfor _, e := range opf.FindElements(\"\/\/title\") {\n\t\t\tbook.Title = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/creator\") {\n\t\t\tbook.Author = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/publisher\") {\n\t\t\tbook.Publisher = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/description\") {\n\t\t\tbook.Description = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/meta[@name='calibre:series']\") {\n\t\t\tbook.Series.Name = e.SelectAttrValue(\"content\", \"\")\n\t\t\tseriesid := sha1.New()\n\t\t\tio.WriteString(seriesid, book.Series.Name)\n\t\t\tbook.Series.ID = hex.EncodeToString(seriesid.Sum(nil))[:10]\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/meta[@name='calibre:series_index']\") {\n\t\t\ti, err := strconv.ParseFloat(e.SelectAttrValue(\"content\", \"0\"), 64)\n\t\t\tif err == nil {\n\t\t\t\tbook.Series.Index = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tid := sha1.New()\n\t\tio.WriteString(id, book.Author)\n\t\tbook.AuthorID = hex.EncodeToString(id.Sum(nil))[:10]\n\t\tio.WriteString(id, book.Series.Name)\n\t\tio.WriteString(id, book.Title)\n\t\tbook.ID = hex.EncodeToString(id.Sum(nil))[:10]\n\n\t\tfor _, e := range opf.FindElements(\"\/\/meta[@name='cover']\") {\n\t\t\tcoverid := e.SelectAttrValue(\"content\", \"\")\n\t\t\tif coverid != \"\" {\n\t\t\t\tfor _, f := range opf.FindElements(\"\/\/[@id='\" + coverid + \"']\") {\n\t\t\t\t\tcover := f.SelectAttrValue(\"href\", \"\")\n\t\t\t\t\tif cover != \"\" {\n\t\t\t\t\t\tcr, err := zfs.Open(\"\/\" + opfdir + \"\/\" + cover)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer cr.Close()\n\n\t\t\t\t\t\text := filepath.Ext(cover)\n\t\t\t\t\t\tif ext == \".jpeg\" {\n\t\t\t\t\t\t\text = \".jpg\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcpath := filepath.Join(coverpath, book.ID+\".jpg\")\n\t\t\t\t\t\tthumbpath := filepath.Join(coverpath, book.ID+\"_thumb\"+\".jpg\")\n\n\t\t\t\t\t\tvar img image.Image\n\n\t\t\t\t\t\tswitch ext {\n\t\t\t\t\t\tcase \".jpg\":\n\t\t\t\t\t\t\timg, err = jpeg.Decode(cr)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \".gif\":\n\t\t\t\t\t\t\timg, err = gif.Decode(cr)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \".png\":\n\t\t\t\t\t\t\timg, err = png.Decode(cr)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcoverfile, err := os.Create(cpath)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer coverfile.Close()\n\t\t\t\t\t\terr = jpeg.Encode(coverfile, img, nil)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/ Better quality: thumb := resize.Resize(200, 0, img, resize.Lanczos2)\n\t\t\t\t\t\tthumb := resize.Resize(200, 0, img, resize.Bicubic)\n\t\t\t\t\t\tthumbfile, err := os.Create(thumbpath)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer thumbfile.Close()\n\t\t\t\t\t\terr = jpeg.Encode(thumbfile, thumb, nil)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbook.HasCover = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tprocessed = true\n\t}\n\n\tif !processed {\n\t\treturn nil, fmt.Errorf(\"Unknown filetype: %s\", book.FileType)\n\t}\n\n\treturn book, nil\n}\n\n\/\/ BookList is a slice of books\ntype BookList []Book\n\n\/\/ NewBookListFromDir creates a BookList from the books in a dir. It will still return if there are errors indexing some of the books.\nfunc NewBookListFromDir(path, coverdir string, printlog bool) (*BookList, error) {\n\tmatches, err := zglob.Glob(filepath.Join(path, \"\/**\/*.epub\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpdfmatches, err := zglob.Glob(filepath.Join(path, \"\/**\/*.pdf\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmatches = append(matches, pdfmatches...)\n\n\tvar books BookList\n\tfor i, filename := range matches {\n\t\tif printlog {\n\t\t\tlog.Printf(\"%.f%% Indexing %s\\n\", float64(i)\/float64(len(matches))*100, filename)\n\t\t}\n\t\tbook, err := NewBookFromFile(filename, coverdir)\n\t\tif err != nil {\n\t\t\tif printlog {\n\t\t\t\tlog.Printf(\"Error indexing %s: %s\\n\", filename, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tbooks = append(books, *book)\n\t}\n\treturn &books, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"archive\/zip\"\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"image\"\n\t\"image\/gif\"\n\t\"image\/jpeg\"\n\t\"image\/png\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"strings\"\n\n\t\"github.com\/beevik\/etree\"\n\tzglob \"github.com\/mattn\/go-zglob\"\n\t\"github.com\/nfnt\/resize\"\n\t\"golang.org\/x\/tools\/godoc\/vfs\/zipfs\"\n)\n\n\/\/ Series represents a book series\ntype Series struct {\n\tName  string  `json:\"name,omitempty\"`\n\tID    string  `json:\"id,omitempty\"`\n\tIndex float64 `json:\"index,omitempty\"`\n}\n\n\/\/ Book represents a book\ntype Book struct {\n\tID          string    `json:\"id\"`\n\tTitle       string    `json:\"title\"`\n\tAuthor      string    `json:\"author,omitempty\"`\n\tAuthorID    string    `json:\"authorid\"`\n\tPublisher   string    `json:\"publisher,omitempty\"`\n\tDescription string    `json:\"description,omitempty\"`\n\tSeries      Series    `json:\"series,omitempty\"`\n\tFilepath    string    `json:\"filepath\"`\n\tHasCover    bool      `json:\"hascover\"`\n\tModTime     time.Time `json:\"modtime,omitempty\"`\n\tFileType    string    `json:\"filetype,omitempty\"`\n}\n\n\/\/ NewBookFromFile creates a book object from a file\nfunc NewBookFromFile(path, coverpath string) (bk *Book, err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tbk = nil\n\t\t\terr = fmt.Errorf(\"Unknown error parsing book. Skipping. Error: %s\", r)\n\t\t}\n\t}()\n\n\tbook := new(Book)\n\tbook.Title = filepath.Base(path)\n\tbook.Filepath = path\n\tbook.FileType = strings.ToLower(strings.Replace(filepath.Ext(path), \".\", \"\", -1))\n\n\tif file, err := os.Stat(path); err == nil {\n\t\tbook.ModTime = file.ModTime()\n\t}\n\n\tswitch ft := book.FileType; ft {\n\tcase \"pdf\":\n\t\tbook.Title = filepath.Base(path)\n\n\t\tm, err := GetPDFMeta(path)\n\t\tif err == nil {\n\t\t\tbook.Title = m.Title\n\t\t\tbook.Author = m.Author\n\t\t}\n\n\t\tid := sha1.New()\n\t\tio.WriteString(id, book.Author)\n\t\tbook.AuthorID = hex.EncodeToString(id.Sum(nil))[:10]\n\t\tio.WriteString(id, book.Series.Name)\n\t\tio.WriteString(id, book.Title)\n\t\tbook.ID = hex.EncodeToString(id.Sum(nil))[:10]\n\tcase \"epub\":\n\t\tzr, err := zip.OpenReader(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tzfs := zipfs.New(zr, \"epub\")\n\n\t\trsk, err := zfs.Open(\"\/META-INF\/container.xml\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer rsk.Close()\n\t\tcontainer := etree.NewDocument()\n\t\t_, err = container.ReadFrom(rsk)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trootfile := \"\"\n\t\tfor _, e := range container.FindElements(\"\/\/rootfiles\/rootfile[@full-path]\") {\n\t\t\trootfile = e.SelectAttrValue(\"full-path\", \"\")\n\t\t}\n\t\tif rootfile == \"\" {\n\t\t\treturn nil, errors.New(\"Cannot parse container\")\n\t\t}\n\n\t\trrsk, err := zfs.Open(\"\/\" + rootfile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer rrsk.Close()\n\t\topfdir := filepath.Dir(rootfile)\n\t\topf := etree.NewDocument()\n\t\t_, err = opf.ReadFrom(rrsk)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbook.Title = filepath.Base(path)\n\t\tfor _, e := range opf.FindElements(\"\/\/title\") {\n\t\t\tbook.Title = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/creator\") {\n\t\t\tbook.Author = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/publisher\") {\n\t\t\tbook.Publisher = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/description\") {\n\t\t\tbook.Description = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/meta[@name='calibre:series']\") {\n\t\t\tbook.Series.Name = e.SelectAttrValue(\"content\", \"\")\n\t\t\tseriesid := sha1.New()\n\t\t\tio.WriteString(seriesid, book.Series.Name)\n\t\t\tbook.Series.ID = hex.EncodeToString(seriesid.Sum(nil))[:10]\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/meta[@name='calibre:series_index']\") {\n\t\t\ti, err := strconv.ParseFloat(e.SelectAttrValue(\"content\", \"0\"), 64)\n\t\t\tif err == nil {\n\t\t\t\tbook.Series.Index = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tid := sha1.New()\n\t\tio.WriteString(id, book.Author)\n\t\tbook.AuthorID = hex.EncodeToString(id.Sum(nil))[:10]\n\t\tio.WriteString(id, book.Series.Name)\n\t\tio.WriteString(id, book.Title)\n\t\tbook.ID = hex.EncodeToString(id.Sum(nil))[:10]\n\n\t\tfor _, e := range opf.FindElements(\"\/\/meta[@name='cover']\") {\n\t\t\tcoverid := e.SelectAttrValue(\"content\", \"\")\n\t\t\tif coverid != \"\" {\n\t\t\t\tfor _, f := range opf.FindElements(\"\/\/[@id='\" + coverid + \"']\") {\n\t\t\t\t\tcover := f.SelectAttrValue(\"href\", \"\")\n\t\t\t\t\tif cover != \"\" {\n\t\t\t\t\t\tcr, err := zfs.Open(\"\/\" + opfdir + \"\/\" + cover)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer cr.Close()\n\n\t\t\t\t\t\text := filepath.Ext(cover)\n\t\t\t\t\t\tif ext == \".jpeg\" {\n\t\t\t\t\t\t\text = \".jpg\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcpath := filepath.Join(coverpath, book.ID+\".jpg\")\n\t\t\t\t\t\tthumbpath := filepath.Join(coverpath, book.ID+\"_thumb\"+\".jpg\")\n\n\t\t\t\t\t\tvar img image.Image\n\n\t\t\t\t\t\tswitch ext {\n\t\t\t\t\t\tcase \".jpg\":\n\t\t\t\t\t\t\timg, err = jpeg.Decode(cr)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \".gif\":\n\t\t\t\t\t\t\timg, err = gif.Decode(cr)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \".png\":\n\t\t\t\t\t\t\timg, err = png.Decode(cr)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcoverfile, err := os.Create(cpath)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer coverfile.Close()\n\t\t\t\t\t\terr = jpeg.Encode(coverfile, img, nil)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/ Better quality: thumb := resize.Resize(200, 0, img, resize.Lanczos2)\n\t\t\t\t\t\tthumb := resize.Resize(200, 0, img, resize.Bicubic)\n\t\t\t\t\t\tthumbfile, err := os.Create(thumbpath)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer thumbfile.Close()\n\t\t\t\t\t\terr = jpeg.Encode(thumbfile, thumb, nil)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbook.HasCover = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown filetype: %s\", book.FileType)\n\t}\n\n\treturn book, nil\n}\n\n\/\/ BookList is a slice of books\ntype BookList []Book\n\n\/\/ NewBookListFromDir creates a BookList from the books in a dir. It will still return if there are errors indexing some of the books.\nfunc NewBookListFromDir(path, coverdir string, printlog bool) (*BookList, error) {\n\tmatches, err := zglob.Glob(filepath.Join(path, \"\/**\/*.epub\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpdfmatches, err := zglob.Glob(filepath.Join(path, \"\/**\/*.pdf\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmatches = append(matches, pdfmatches...)\n\n\tvar books BookList\n\tfor i, filename := range matches {\n\t\tif printlog {\n\t\t\tlog.Printf(\"%.f%% Indexing %s\\n\", float64(i)\/float64(len(matches))*100, filename)\n\t\t}\n\t\tbook, err := NewBookFromFile(filename, coverdir)\n\t\tif err != nil {\n\t\t\tif printlog {\n\t\t\t\tlog.Printf(\"Error indexing %s: %s\\n\", filename, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tbooks = append(books, *book)\n\t}\n\treturn &books, nil\n}\n<commit_msg>Reduce memory usage<commit_after>package main\n\nimport (\n\t\"archive\/zip\"\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"image\"\n\t\"image\/gif\"\n\t\"image\/jpeg\"\n\t\"image\/png\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\/debug\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"strings\"\n\n\t\"github.com\/beevik\/etree\"\n\tzglob \"github.com\/mattn\/go-zglob\"\n\t\"github.com\/nfnt\/resize\"\n\t\"golang.org\/x\/tools\/godoc\/vfs\/zipfs\"\n)\n\n\/\/ Series represents a book series\ntype Series struct {\n\tName  string  `json:\"name,omitempty\"`\n\tID    string  `json:\"id,omitempty\"`\n\tIndex float64 `json:\"index,omitempty\"`\n}\n\n\/\/ Book represents a book\ntype Book struct {\n\tID          string    `json:\"id\"`\n\tTitle       string    `json:\"title\"`\n\tAuthor      string    `json:\"author,omitempty\"`\n\tAuthorID    string    `json:\"authorid\"`\n\tPublisher   string    `json:\"publisher,omitempty\"`\n\tDescription string    `json:\"description,omitempty\"`\n\tSeries      Series    `json:\"series,omitempty\"`\n\tFilepath    string    `json:\"filepath\"`\n\tHasCover    bool      `json:\"hascover\"`\n\tModTime     time.Time `json:\"modtime,omitempty\"`\n\tFileType    string    `json:\"filetype,omitempty\"`\n}\n\n\/\/ NewBookFromFile creates a book object from a file\nfunc NewBookFromFile(path, coverpath string) (bk *Book, err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tbk = nil\n\t\t\terr = fmt.Errorf(\"Unknown error parsing book. Skipping. Error: %s\", r)\n\t\t}\n\t}()\n\n\tbook := new(Book)\n\tbook.Title = filepath.Base(path)\n\tbook.Filepath = path\n\tbook.FileType = strings.ToLower(strings.Replace(filepath.Ext(path), \".\", \"\", -1))\n\n\tif file, err := os.Stat(path); err == nil {\n\t\tbook.ModTime = file.ModTime()\n\t}\n\n\tswitch ft := book.FileType; ft {\n\tcase \"pdf\":\n\t\tbook.Title = filepath.Base(path)\n\n\t\tm, err := GetPDFMeta(path)\n\t\tif err == nil {\n\t\t\tbook.Title = m.Title\n\t\t\tbook.Author = m.Author\n\t\t}\n\n\t\tid := sha1.New()\n\t\tio.WriteString(id, book.Author)\n\t\tbook.AuthorID = hex.EncodeToString(id.Sum(nil))[:10]\n\t\tio.WriteString(id, book.Series.Name)\n\t\tio.WriteString(id, book.Title)\n\t\tbook.ID = hex.EncodeToString(id.Sum(nil))[:10]\n\tcase \"epub\":\n\t\tzr, err := zip.OpenReader(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tzfs := zipfs.New(zr, \"epub\")\n\n\t\trsk, err := zfs.Open(\"\/META-INF\/container.xml\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer rsk.Close()\n\t\tcontainer := etree.NewDocument()\n\t\t_, err = container.ReadFrom(rsk)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trootfile := \"\"\n\t\tfor _, e := range container.FindElements(\"\/\/rootfiles\/rootfile[@full-path]\") {\n\t\t\trootfile = e.SelectAttrValue(\"full-path\", \"\")\n\t\t}\n\t\tif rootfile == \"\" {\n\t\t\treturn nil, errors.New(\"Cannot parse container\")\n\t\t}\n\n\t\trrsk, err := zfs.Open(\"\/\" + rootfile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer rrsk.Close()\n\t\topfdir := filepath.Dir(rootfile)\n\t\topf := etree.NewDocument()\n\t\t_, err = opf.ReadFrom(rrsk)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbook.Title = filepath.Base(path)\n\t\tfor _, e := range opf.FindElements(\"\/\/title\") {\n\t\t\tbook.Title = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/creator\") {\n\t\t\tbook.Author = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/publisher\") {\n\t\t\tbook.Publisher = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/description\") {\n\t\t\tbook.Description = e.Text()\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/meta[@name='calibre:series']\") {\n\t\t\tbook.Series.Name = e.SelectAttrValue(\"content\", \"\")\n\t\t\tseriesid := sha1.New()\n\t\t\tio.WriteString(seriesid, book.Series.Name)\n\t\t\tbook.Series.ID = hex.EncodeToString(seriesid.Sum(nil))[:10]\n\t\t\tbreak\n\t\t}\n\t\tfor _, e := range opf.FindElements(\"\/\/meta[@name='calibre:series_index']\") {\n\t\t\ti, err := strconv.ParseFloat(e.SelectAttrValue(\"content\", \"0\"), 64)\n\t\t\tif err == nil {\n\t\t\t\tbook.Series.Index = i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tid := sha1.New()\n\t\tio.WriteString(id, book.Author)\n\t\tbook.AuthorID = hex.EncodeToString(id.Sum(nil))[:10]\n\t\tio.WriteString(id, book.Series.Name)\n\t\tio.WriteString(id, book.Title)\n\t\tbook.ID = hex.EncodeToString(id.Sum(nil))[:10]\n\n\t\tfor _, e := range opf.FindElements(\"\/\/meta[@name='cover']\") {\n\t\t\tcoverid := e.SelectAttrValue(\"content\", \"\")\n\t\t\tif coverid != \"\" {\n\t\t\t\tfor _, f := range opf.FindElements(\"\/\/[@id='\" + coverid + \"']\") {\n\t\t\t\t\tcover := f.SelectAttrValue(\"href\", \"\")\n\t\t\t\t\tif cover != \"\" {\n\t\t\t\t\t\tcr, err := zfs.Open(\"\/\" + opfdir + \"\/\" + cover)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer cr.Close()\n\n\t\t\t\t\t\text := filepath.Ext(cover)\n\t\t\t\t\t\tif ext == \".jpeg\" {\n\t\t\t\t\t\t\text = \".jpg\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcpath := filepath.Join(coverpath, book.ID+\".jpg\")\n\t\t\t\t\t\tthumbpath := filepath.Join(coverpath, book.ID+\"_thumb\"+\".jpg\")\n\n\t\t\t\t\t\tvar img image.Image\n\n\t\t\t\t\t\tswitch ext {\n\t\t\t\t\t\tcase \".jpg\":\n\t\t\t\t\t\t\timg, err = jpeg.Decode(cr)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \".gif\":\n\t\t\t\t\t\t\timg, err = gif.Decode(cr)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \".png\":\n\t\t\t\t\t\t\timg, err = png.Decode(cr)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcoverfile, err := os.Create(cpath)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer coverfile.Close()\n\t\t\t\t\t\terr = jpeg.Encode(coverfile, img, nil)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/ Better quality: thumb := resize.Resize(200, 0, img, resize.Lanczos2)\n\t\t\t\t\t\tthumb := resize.Resize(200, 0, img, resize.Bicubic)\n\t\t\t\t\t\tthumbfile, err := os.Create(thumbpath)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefer thumbfile.Close()\n\t\t\t\t\t\terr = jpeg.Encode(thumbfile, thumb, nil)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbook.HasCover = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown filetype: %s\", book.FileType)\n\t}\n\n\treturn book, nil\n}\n\n\/\/ BookList is a slice of books\ntype BookList []Book\n\n\/\/ NewBookListFromDir creates a BookList from the books in a dir. It will still return if there are errors indexing some of the books.\nfunc NewBookListFromDir(path, coverdir string, printlog bool) (*BookList, error) {\n\tmatches, err := zglob.Glob(filepath.Join(path, \"\/**\/*.epub\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpdfmatches, err := zglob.Glob(filepath.Join(path, \"\/**\/*.pdf\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmatches = append(matches, pdfmatches...)\n\n\tvar books BookList\n\tfor i, filename := range matches {\n\t\tif printlog {\n\t\t\tlog.Printf(\"%.f%% Indexing %s\\n\", float64(i)\/float64(len(matches))*100, filename)\n\t\t}\n\t\tbook, err := NewBookFromFile(filename, coverdir)\n\t\tif err != nil {\n\t\t\tif printlog {\n\t\t\t\tlog.Printf(\"Error indexing %s: %s\\n\", filename, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tbooks = append(books, *book)\n\t}\n\tdebug.FreeOSMemory()\n\treturn &books, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package gofakeit\n\nimport \"math\/rand\"\n\nfunc Bool() bool {\n\tif rand.Intn(2) == 1 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n<commit_msg>bool - added description comment.<commit_after>package gofakeit\n\nimport \"math\/rand\"\n\n\/\/ Generate Random Boolean value\nfunc Bool() bool {\n\tif rand.Intn(2) == 1 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package mainline\n\nimport (\n\t\"math\/rand\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"go.uber.org\/zap\"\n)\n\ntype IndexingService struct {\n\t\/\/ Private\n\tprotocol      *Protocol\n\tstarted       bool\n\tinterval      time.Duration\n\teventHandlers IndexingServiceEventHandlers\n\n\tnodeID []byte\n\t\/\/ []byte type would be a much better fit for the keys but unfortunately (and quite\n\t\/\/ understandably) slices cannot be used as keys (since they are not hashable), and using arrays\n\t\/\/ (or even the conversion between each other) is a pain; hence map[string]net.UDPAddr\n\t\/\/                                                                  ^~~~~~\n\troutingTable      map[string]*net.UDPAddr\n\troutingTableMutex *sync.Mutex\n\tmaxNeighbors      uint\n\n\tcounter          uint16\n\tgetPeersRequests map[[2]byte][20]byte \/\/ GetPeersQuery.`t` -> infohash\n}\n\ntype IndexingServiceEventHandlers struct {\n\tOnResult func(IndexingResult)\n}\n\ntype IndexingResult struct {\n\tinfoHash  [20]byte\n\tpeerAddrs []net.TCPAddr\n}\n\nfunc (ir IndexingResult) InfoHash() [20]byte {\n\treturn ir.infoHash\n}\n\nfunc (ir IndexingResult) PeerAddrs() []net.TCPAddr {\n\treturn ir.peerAddrs\n}\n\nfunc NewIndexingService(laddr string, interval time.Duration, maxNeighbors uint, eventHandlers IndexingServiceEventHandlers) *IndexingService {\n\tservice := new(IndexingService)\n\tservice.interval = interval\n\tservice.protocol = NewProtocol(\n\t\tladdr,\n\t\tProtocolEventHandlers{\n\t\t\tOnFindNodeResponse:         service.onFindNodeResponse,\n\t\t\tOnGetPeersResponse:         service.onGetPeersResponse,\n\t\t\tOnSampleInfohashesResponse: service.onSampleInfohashesResponse,\n\t\t},\n\t)\n\tservice.nodeID = make([]byte, 20)\n\tservice.routingTable = make(map[string]*net.UDPAddr)\n\tservice.routingTableMutex = new(sync.Mutex)\n\tservice.maxNeighbors = maxNeighbors\n\tservice.eventHandlers = eventHandlers\n\n\tservice.getPeersRequests = make(map[[2]byte][20]byte)\n\n\treturn service\n}\n\nfunc (is *IndexingService) Start() {\n\tif is.started {\n\t\tzap.L().Panic(\"Attempting to Start() a mainline\/IndexingService that has been already started! (Programmer error.)\")\n\t}\n\tis.started = true\n\n\tis.protocol.Start()\n\tgo is.index()\n\n\tzap.L().Info(\"Indexing Service started!\")\n}\n\nfunc (is *IndexingService) Terminate() {\n\tis.protocol.Terminate()\n}\n\nfunc (is *IndexingService) index() {\n\tfor range time.Tick(is.interval) {\n\t\tis.routingTableMutex.Lock()\n\t\tif len(is.routingTable) == 0 {\n\t\t\tis.bootstrap()\n\t\t} else {\n\t\t\tzap.L().Info(\"Latest status:\", zap.Int(\"n\", len(is.routingTable)),\n\t\t\t\tzap.Uint(\"maxNeighbors\", is.maxNeighbors))\n\t\t\t\/\/TODO\n\t\t\tis.findNeighbors()\n\t\t\tis.routingTable = make(map[string]*net.UDPAddr)\n\t\t}\n\t\tis.routingTableMutex.Unlock()\n\t}\n}\n\nfunc (is *IndexingService) bootstrap() {\n\tbootstrappingNodes := []string{\n\t\t\"router.bittorrent.com:6881\",\n\t\t\"dht.transmissionbt.com:6881\",\n\t\t\"dht.libtorrent.org:25401\",\n\t}\n\n\tzap.L().Info(\"Bootstrapping as routing table is empty...\")\n\tfor _, node := range bootstrappingNodes {\n\t\ttarget := make([]byte, 20)\n\t\t_, err := rand.Read(target)\n\t\tif err != nil {\n\t\t\tzap.L().Panic(\"Could NOT generate random bytes during bootstrapping!\")\n\t\t}\n\n\t\taddr, err := net.ResolveUDPAddr(\"udp\", node)\n\t\tif err != nil {\n\t\t\tzap.L().Error(\"Could NOT resolve (UDP) address of the bootstrapping node!\",\n\t\t\t\tzap.String(\"node\", node))\n\t\t\tcontinue\n\t\t}\n\n\t\tis.protocol.SendMessage(NewFindNodeQuery(is.nodeID, target), addr)\n\t}\n}\n\nfunc (is *IndexingService) findNeighbors() {\n\ttarget := make([]byte, 20)\n\tfor _, addr := range is.routingTable {\n\t\t_, err := rand.Read(target)\n\t\tif err != nil {\n\t\t\tzap.L().Panic(\"Could NOT generate random bytes during bootstrapping!\")\n\t\t}\n\n\t\tis.protocol.SendMessage(\n\t\t\tNewSampleInfohashesQuery(is.nodeID, []byte(\"aa\"), target),\n\t\t\taddr,\n\t\t)\n\t}\n}\n\nfunc (is *IndexingService) onFindNodeResponse(response *Message, addr *net.UDPAddr) {\n\tis.routingTableMutex.Lock()\n\tdefer is.routingTableMutex.Unlock()\n\n\tfor _, node := range response.R.Nodes {\n\t\tif uint(len(is.routingTable)) >= is.maxNeighbors {\n\t\t\tbreak\n\t\t}\n\t\tif node.Addr.Port == 0 { \/\/ Ignore nodes who \"use\" port 0.\n\t\t\tcontinue\n\t\t}\n\n\t\tis.routingTable[string(node.ID)] = &node.Addr\n\n\t\ttarget := make([]byte, 20)\n\t\t_, err := rand.Read(target)\n\t\tif err != nil {\n\t\t\tzap.L().Panic(\"Could NOT generate random bytes!\")\n\t\t}\n\t\tis.protocol.SendMessage(\n\t\t\tNewSampleInfohashesQuery(is.nodeID, []byte(\"aa\"), target),\n\t\t\t&node.Addr,\n\t\t)\n\t}\n}\n\nfunc (is *IndexingService) onGetPeersResponse(msg *Message, addr *net.UDPAddr) {\n\tvar t [2]byte\n\tcopy(t[:], msg.T)\n\n\tinfoHash := is.getPeersRequests[t]\n\t\/\/ We got a response, so free the key!\n\tdelete(is.getPeersRequests, t)\n\n\t\/\/ BEP 51 specifies that\n\t\/\/     The new sample_infohashes remote procedure call requests that a remote node return a string of multiple\n\t\/\/     concatenated infohashes (20 bytes each) FOR WHICH IT HOLDS GET_PEERS VALUES.\n\t\/\/                                                                          ^^^^^^\n\t\/\/ So theoretically we should never hit the case where `values` is empty, but c'est la vie.\n\tif len(msg.R.Values) == 0 {\n\t\treturn\n\t}\n\n\tpeerAddrs := make([]net.TCPAddr, 0)\n\tfor _, peer := range msg.R.Values {\n\t\tif peer.Port == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tpeerAddrs = append(peerAddrs, net.TCPAddr{\n\t\t\tIP:   peer.IP,\n\t\t\tPort: peer.Port,\n\t\t})\n\t}\n\n\tis.eventHandlers.OnResult(IndexingResult{\n\t\tinfoHash:  infoHash,\n\t\tpeerAddrs: peerAddrs,\n\t})\n}\n\nfunc (is *IndexingService) onSampleInfohashesResponse(msg *Message, addr *net.UDPAddr) {\n\t\/\/ request samples\n\tfor i := 0; i < len(msg.R.Samples)\/20; i++ {\n\t\tvar infoHash [20]byte\n\t\tcopy(infoHash[:], msg.R.Samples[i:(i+1)*20])\n\n\t\tmsg := NewGetPeersQuery(is.nodeID, infoHash[:])\n\t\tt := uint16BE(is.counter)\n\t\tmsg.T = t[:]\n\n\t\tis.protocol.SendMessage(msg, addr)\n\n\t\tis.getPeersRequests[t] = infoHash\n\t\tis.counter++\n\t}\n\n\t\/\/ iterate\n\tfor _, node := range msg.R.Nodes {\n\t\tif uint(len(is.routingTable)) >= is.maxNeighbors {\n\t\t\tbreak\n\t\t}\n\t\tif node.Addr.Port == 0 { \/\/ Ignore nodes who \"use\" port 0.\n\t\t\tcontinue\n\t\t}\n\t\tis.routingTable[string(node.ID)] = &node.Addr\n\n\t\t\/\/ TODO\n\t\t\/*\n\t\t\ttarget := make([]byte, 20)\n\t\t\t_, err := rand.Read(target)\n\t\t\tif err != nil {\n\t\t\t\tzap.L().Panic(\"Could NOT generate random bytes!\")\n\t\t\t}\n\t\t\tis.protocol.SendMessage(\n\t\t\t\tNewSampleInfohashesQuery(is.nodeID, []byte(\"aa\"), target),\n\t\t\t\t&node.Addr,\n\t\t\t)\n\t\t*\/\n\t}\n}\n\nfunc uint16BE(v uint16) (b [2]byte) {\n\tb[0] = byte(v >> 8)\n\tb[1] = byte(v)\n\treturn\n}\n<commit_msg>fixed concurrency on routingTable map<commit_after>package mainline\n\nimport (\n\t\"math\/rand\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"go.uber.org\/zap\"\n)\n\ntype IndexingService struct {\n\t\/\/ Private\n\tprotocol      *Protocol\n\tstarted       bool\n\tinterval      time.Duration\n\teventHandlers IndexingServiceEventHandlers\n\n\tnodeID []byte\n\t\/\/ []byte type would be a much better fit for the keys but unfortunately (and quite\n\t\/\/ understandably) slices cannot be used as keys (since they are not hashable), and using arrays\n\t\/\/ (or even the conversion between each other) is a pain; hence map[string]net.UDPAddr\n\t\/\/                                                                  ^~~~~~\n\troutingTable      map[string]*net.UDPAddr\n\troutingTableMutex sync.RWMutex\n\tmaxNeighbors      uint\n\n\tcounter          uint16\n\tgetPeersRequests map[[2]byte][20]byte \/\/ GetPeersQuery.`t` -> infohash\n}\n\ntype IndexingServiceEventHandlers struct {\n\tOnResult func(IndexingResult)\n}\n\ntype IndexingResult struct {\n\tinfoHash  [20]byte\n\tpeerAddrs []net.TCPAddr\n}\n\nfunc (ir IndexingResult) InfoHash() [20]byte {\n\treturn ir.infoHash\n}\n\nfunc (ir IndexingResult) PeerAddrs() []net.TCPAddr {\n\treturn ir.peerAddrs\n}\n\nfunc NewIndexingService(laddr string, interval time.Duration, maxNeighbors uint, eventHandlers IndexingServiceEventHandlers) *IndexingService {\n\tservice := new(IndexingService)\n\tservice.interval = interval\n\tservice.protocol = NewProtocol(\n\t\tladdr,\n\t\tProtocolEventHandlers{\n\t\t\tOnFindNodeResponse:         service.onFindNodeResponse,\n\t\t\tOnGetPeersResponse:         service.onGetPeersResponse,\n\t\t\tOnSampleInfohashesResponse: service.onSampleInfohashesResponse,\n\t\t},\n\t)\n\tservice.nodeID = make([]byte, 20)\n\tservice.routingTable = make(map[string]*net.UDPAddr)\n\tservice.maxNeighbors = maxNeighbors\n\tservice.eventHandlers = eventHandlers\n\n\tservice.getPeersRequests = make(map[[2]byte][20]byte)\n\n\treturn service\n}\n\nfunc (is *IndexingService) Start() {\n\tif is.started {\n\t\tzap.L().Panic(\"Attempting to Start() a mainline\/IndexingService that has been already started! (Programmer error.)\")\n\t}\n\tis.started = true\n\n\tis.protocol.Start()\n\tgo is.index()\n\n\tzap.L().Info(\"Indexing Service started!\")\n}\n\nfunc (is *IndexingService) Terminate() {\n\tis.protocol.Terminate()\n}\n\nfunc (is *IndexingService) index() {\n\tfor range time.Tick(is.interval) {\n\t\tis.routingTableMutex.RLock()\n\t\troutingTableLen := len(is.routingTable)\n\t\tis.routingTableMutex.RUnlock()\n\t\tif routingTableLen == 0 {\n\t\t\tis.bootstrap()\n\t\t} else {\n\t\t\tzap.L().Info(\"Latest status:\", zap.Int(\"n\", routingTableLen),\n\t\t\t\tzap.Uint(\"maxNeighbors\", is.maxNeighbors))\n\t\t\t\/\/TODO\n\t\t\tis.findNeighbors()\n\t\t\tis.routingTableMutex.Lock()\n\t\t\tis.routingTable = make(map[string]*net.UDPAddr)\n\t\t\tis.routingTableMutex.Unlock()\n\t\t}\n\t}\n}\n\nfunc (is *IndexingService) bootstrap() {\n\tbootstrappingNodes := []string{\n\t\t\"router.bittorrent.com:6881\",\n\t\t\"dht.transmissionbt.com:6881\",\n\t\t\"dht.libtorrent.org:25401\",\n\t}\n\n\tzap.L().Info(\"Bootstrapping as routing table is empty...\")\n\tfor _, node := range bootstrappingNodes {\n\t\ttarget := make([]byte, 20)\n\t\t_, err := rand.Read(target)\n\t\tif err != nil {\n\t\t\tzap.L().Panic(\"Could NOT generate random bytes during bootstrapping!\")\n\t\t}\n\n\t\taddr, err := net.ResolveUDPAddr(\"udp\", node)\n\t\tif err != nil {\n\t\t\tzap.L().Error(\"Could NOT resolve (UDP) address of the bootstrapping node!\",\n\t\t\t\tzap.String(\"node\", node))\n\t\t\tcontinue\n\t\t}\n\n\t\tis.protocol.SendMessage(NewFindNodeQuery(is.nodeID, target), addr)\n\t}\n}\n\nfunc (is *IndexingService) findNeighbors() {\n\ttarget := make([]byte, 20)\n\n\t\/*\n\t\tWe could just RLock and defer RUnlock here, but that would mean that each response that we get could not Lock\n\t\tthe table because we are sending. So we would basically make read and write NOT concurrent.\n\t\tA better approach would be to get all addresses to send in a slice and then work on that, releasing the main map.\n\t*\/\n\tis.routingTableMutex.RLock()\n\taddressesToSend := make([]*net.UDPAddr, 0, len(is.routingTable))\n\tfor _, addr := range is.routingTable {\n\t\taddressesToSend = append(addressesToSend, addr)\n\t}\n\tis.routingTableMutex.RUnlock()\n\n\tfor _, addr := range addressesToSend {\n\t\t_, err := rand.Read(target)\n\t\tif err != nil {\n\t\t\tzap.L().Panic(\"Could NOT generate random bytes during bootstrapping!\")\n\t\t}\n\n\t\tis.protocol.SendMessage(\n\t\t\tNewSampleInfohashesQuery(is.nodeID, []byte(\"aa\"), target),\n\t\t\taddr,\n\t\t)\n\t}\n}\n\nfunc (is *IndexingService) onFindNodeResponse(response *Message, addr *net.UDPAddr) {\n\tis.routingTableMutex.Lock()\n\tdefer is.routingTableMutex.Unlock()\n\n\tfor _, node := range response.R.Nodes {\n\t\tif uint(len(is.routingTable)) >= is.maxNeighbors {\n\t\t\tbreak\n\t\t}\n\t\tif node.Addr.Port == 0 { \/\/ Ignore nodes who \"use\" port 0.\n\t\t\tcontinue\n\t\t}\n\n\t\tis.routingTable[string(node.ID)] = &node.Addr\n\n\t\ttarget := make([]byte, 20)\n\t\t_, err := rand.Read(target)\n\t\tif err != nil {\n\t\t\tzap.L().Panic(\"Could NOT generate random bytes!\")\n\t\t}\n\t\tis.protocol.SendMessage(\n\t\t\tNewSampleInfohashesQuery(is.nodeID, []byte(\"aa\"), target),\n\t\t\t&node.Addr,\n\t\t)\n\t}\n}\n\nfunc (is *IndexingService) onGetPeersResponse(msg *Message, addr *net.UDPAddr) {\n\tvar t [2]byte\n\tcopy(t[:], msg.T)\n\n\tinfoHash := is.getPeersRequests[t]\n\t\/\/ We got a response, so free the key!\n\tdelete(is.getPeersRequests, t)\n\n\t\/\/ BEP 51 specifies that\n\t\/\/     The new sample_infohashes remote procedure call requests that a remote node return a string of multiple\n\t\/\/     concatenated infohashes (20 bytes each) FOR WHICH IT HOLDS GET_PEERS VALUES.\n\t\/\/                                                                          ^^^^^^\n\t\/\/ So theoretically we should never hit the case where `values` is empty, but c'est la vie.\n\tif len(msg.R.Values) == 0 {\n\t\treturn\n\t}\n\n\tpeerAddrs := make([]net.TCPAddr, 0)\n\tfor _, peer := range msg.R.Values {\n\t\tif peer.Port == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tpeerAddrs = append(peerAddrs, net.TCPAddr{\n\t\t\tIP:   peer.IP,\n\t\t\tPort: peer.Port,\n\t\t})\n\t}\n\n\tis.eventHandlers.OnResult(IndexingResult{\n\t\tinfoHash:  infoHash,\n\t\tpeerAddrs: peerAddrs,\n\t})\n}\n\nfunc (is *IndexingService) onSampleInfohashesResponse(msg *Message, addr *net.UDPAddr) {\n\t\/\/ request samples\n\tfor i := 0; i < len(msg.R.Samples)\/20; i++ {\n\t\tvar infoHash [20]byte\n\t\tcopy(infoHash[:], msg.R.Samples[i:(i+1)*20])\n\n\t\tmsg := NewGetPeersQuery(is.nodeID, infoHash[:])\n\t\tt := uint16BE(is.counter)\n\t\tmsg.T = t[:]\n\n\t\tis.protocol.SendMessage(msg, addr)\n\n\t\tis.getPeersRequests[t] = infoHash\n\t\tis.counter++\n\t}\n\n\t\/\/ iterate\n\tis.routingTableMutex.Lock()\n\tdefer is.routingTableMutex.Unlock()\n\tfor _, node := range msg.R.Nodes {\n\t\tif uint(len(is.routingTable)) >= is.maxNeighbors {\n\t\t\tbreak\n\t\t}\n\t\tif node.Addr.Port == 0 { \/\/ Ignore nodes who \"use\" port 0.\n\t\t\tcontinue\n\t\t}\n\t\tis.routingTable[string(node.ID)] = &node.Addr\n\n\t\t\/\/ TODO\n\t\t\/*\n\t\t\ttarget := make([]byte, 20)\n\t\t\t_, err := rand.Read(target)\n\t\t\tif err != nil {\n\t\t\t\tzap.L().Panic(\"Could NOT generate random bytes!\")\n\t\t\t}\n\t\t\tis.protocol.SendMessage(\n\t\t\t\tNewSampleInfohashesQuery(is.nodeID, []byte(\"aa\"), target),\n\t\t\t\t&node.Addr,\n\t\t\t)\n\t\t*\/\n\t}\n}\n\nfunc uint16BE(v uint16) (b [2]byte) {\n\tb[0] = byte(v >> 8)\n\tb[1] = byte(v)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package q\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/garyburd\/redigo\/redis\"\n)\n\n\/\/ A RedisStore stores all records data into redis\ntype RedisStore struct {\n\tname string\n\tpool *redis.Pool\n}\n\n\/\/ RedisDataStore configures the queue with a redis data store\nfunc RedisDataStore(name string, pool *redis.Pool) func(q *Queue) error {\n\treturn DataStore(&RedisStore{name, pool})\n}\n\nfunc (r *RedisStore) queue() string {\n\treturn fmt.Sprintf(\"q:%s:queue\", r.name)\n}\n\nfunc (r *RedisStore) workingQueue() string {\n\treturn fmt.Sprintf(\"q:%s:queue:working\", r.name)\n}\n\n\/\/ Store add the provided data to the in-memory array\nfunc (r *RedisStore) Store(d []byte) error {\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\t_, err := conn.Do(\"LPUSH\", r.queue(), d)\n\treturn err\n}\n\n\/\/ Retrieve pops the latest data from the in-memory array\nfunc (r *RedisStore) Retrieve() ([]byte, error) {\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\td, err := redis.Bytes(conn.Do(\"RPOPLPUSH\", r.queue(), r.workingQueue()))\n\tif err == redis.ErrNil {\n\t\terr = nil\n\t}\n\treturn d, err\n}\n\n\/\/ Finish marks a task as finished\nfunc (r *RedisStore) Finish(d []byte) error {\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\t_, err := conn.Do(\"LREM\", r.workingQueue(), 0, d)\n\treturn err\n}\n\n\/\/ Length returns the number of elements in the in-memory array\nfunc (r *RedisStore) Length() (int, error) {\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\treturn redis.Int(conn.Do(\"LLEN\", r.queue()))\n}\n\n\/\/ WorkingLength returns the number of elements currently being processed\nfunc (r *RedisStore) WorkingLength() (int, error) {\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\treturn redis.Int(conn.Do(\"LLEN\", r.workingQueue()))\n}\n<commit_msg>setup an expiring lock key for working jobs<commit_after>package q\n\nimport (\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\n\t\"github.com\/garyburd\/redigo\/redis\"\n)\n\nconst (\n\tlockDuration = 60 \/\/ seconds\n)\n\n\/\/ A RedisStore stores all records data into redis\ntype RedisStore struct {\n\tname string\n\tpool *redis.Pool\n}\n\n\/\/ RedisDataStore configures the queue with a redis data store\nfunc RedisDataStore(name string, pool *redis.Pool) func(q *Queue) error {\n\treturn DataStore(&RedisStore{name, pool})\n}\n\nfunc (r *RedisStore) queue() string {\n\treturn fmt.Sprintf(\"q:%s:queue\", r.name)\n}\n\nfunc (r *RedisStore) workingQueue() string {\n\treturn fmt.Sprintf(\"q:%s:queue:working\", r.name)\n}\n\nfunc (r *RedisStore) lockKey(d []byte) string {\n\th := sha256.New()\n\th.Write(d)\n\n\treturn fmt.Sprintf(\"q:%s:lock:%s\", r.name, h.Sum(nil))\n}\n\n\/\/ Store add the provided data to the in-memory array\nfunc (r *RedisStore) Store(d []byte) error {\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\t_, err := conn.Do(\"LPUSH\", r.queue(), d)\n\treturn err\n}\n\n\/\/ Retrieve pops the latest data from the in-memory array\nfunc (r *RedisStore) Retrieve() ([]byte, error) {\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\td, err := redis.Bytes(conn.Do(\"RPOPLPUSH\", r.queue(), r.workingQueue()))\n\tif err == redis.ErrNil {\n\t\terr = nil\n\t}\n\n\t_, err = conn.Do(\"SETEX\", r.lockKey(d), lockDuration, d)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn d, err\n}\n\n\/\/ Finish marks a task as finished\nfunc (r *RedisStore) Finish(d []byte) error {\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\tconn.Send(\"MULTI\")\n\tconn.Send(\"LREM\", r.workingQueue(), 0, d)\n\tconn.Send(\"DEL\", r.lockKey(d))\n\t_, err := conn.Do(\"EXEC\")\n\n\treturn err\n}\n\n\/\/ Length returns the number of elements in the in-memory array\nfunc (r *RedisStore) Length() (int, error) {\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\treturn redis.Int(conn.Do(\"LLEN\", r.queue()))\n}\n\n\/\/ WorkingLength returns the number of elements currently being processed\nfunc (r *RedisStore) WorkingLength() (int, error) {\n\tconn := r.pool.Get()\n\tdefer conn.Close()\n\n\treturn redis.Int(conn.Do(\"LLEN\", r.workingQueue()))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2015 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n\/\/ package pointer provides helper method to quickly define pointer from basic go types\npackage pointer\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ String creates a pointer to a string from a string value\nfunc String(v string) *string {\n\tp := new(string)\n\t*p = v\n\treturn p\n}\n\n\/\/ Int creates a pointer to an int from an int value\nfunc Int(v int) *int {\n\tp := new(int)\n\t*p = v\n\treturn p\n}\n\n\/\/ Uint creates a pointer to an unsigned int from an unsigned int value\nfunc Uint(v uint) *uint {\n\tp := new(uint)\n\t*p = v\n\treturn p\n}\n\n\/\/ Float64 creates a pointer to a float64 from a float64 value\nfunc Float64(v float64) *float64 {\n\tp := new(float64)\n\t*p = v\n\treturn p\n}\n\n\/\/ Bool creates a pointer to a boolean from a boolean value\nfunc Bool(v bool) *bool {\n\tp := new(bool)\n\t*p = v\n\treturn p\n}\n\n\/\/ Time creates a pointer to a time.Time from a time.Time value\nfunc Time(v time.Time) *time.Time {\n\tp := new(time.Time)\n\t*p = v\n\treturn p\n}\n\n\/\/ DumpStruct prints the content of a struct of pointers\nfunc DumpPStruct(s interface{}) {\n\tv := reflect.ValueOf(s)\n\n\tif v.Kind() != reflect.Struct {\n\t\tfmt.Printf(\"Unable to dump: Not a struct.\")\n\t\treturn\n\t}\n\n\tfor k := 0; k < v.NumField(); k += 1 {\n\t\tname := v.Type().Field(k).Name\n\t\tif name[0] == strings.ToLower(name)[0] { \/\/ Unexported field\n\t\t\tcontinue\n\t\t}\n\t\ti := v.Field(k).Interface()\n\t\tfmt.Printf(\"%v: \", v.Type().Field(k).Name)\n\n\t\tswitch t := i.(type) {\n\t\tcase *bool:\n\t\t\tif t == nil {\n\t\t\t\tfmt.Printf(\"nil\\n\")\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%+v\\n\", *t)\n\t\t\t}\n\t\tcase *int:\n\t\t\tif t == nil {\n\t\t\t\tfmt.Printf(\"nil\\n\")\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%+v\\n\", *t)\n\t\t\t}\n\t\tcase *uint:\n\t\t\tif t == nil {\n\t\t\t\tfmt.Printf(\"nil\\n\")\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%+v\\n\", *t)\n\t\t\t}\n\t\tcase *string:\n\t\t\tif t == nil {\n\t\t\t\tfmt.Printf(\"nil\\n\")\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%+v\\n\", *t)\n\t\t\t}\n\t\tcase *float64:\n\t\t\tif t == nil {\n\t\t\t\tfmt.Printf(\"nil\\n\")\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%+v\\n\", *t)\n\t\t\t}\n\t\tcase *time.Time:\n\t\t\tif t == nil {\n\t\t\t\tfmt.Printf(\"nil\\n\")\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%+v\\n\", *t)\n\t\t\t}\n\t\tdefault:\n\t\t\tfmt.Printf(\"unknown\\n\")\n\t\t}\n\t}\n}\n<commit_msg>[broker] Make pointer.DumpPStruct() more flexible.<commit_after>\/\/ Copyright © 2015 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n\/\/ package pointer provides helper method to quickly define pointer from basic go types\npackage pointer\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ String creates a pointer to a string from a string value\nfunc String(v string) *string {\n\tp := new(string)\n\t*p = v\n\treturn p\n}\n\n\/\/ Int creates a pointer to an int from an int value\nfunc Int(v int) *int {\n\tp := new(int)\n\t*p = v\n\treturn p\n}\n\n\/\/ Uint creates a pointer to an unsigned int from an unsigned int value\nfunc Uint(v uint) *uint {\n\tp := new(uint)\n\t*p = v\n\treturn p\n}\n\n\/\/ Float64 creates a pointer to a float64 from a float64 value\nfunc Float64(v float64) *float64 {\n\tp := new(float64)\n\t*p = v\n\treturn p\n}\n\n\/\/ Bool creates a pointer to a boolean from a boolean value\nfunc Bool(v bool) *bool {\n\tp := new(bool)\n\t*p = v\n\treturn p\n}\n\n\/\/ Time creates a pointer to a time.Time from a time.Time value\nfunc Time(v time.Time) *time.Time {\n\tp := new(time.Time)\n\t*p = v\n\treturn p\n}\n\n\/\/ DumpStruct prints the content of a struct of pointers\nfunc DumpPStruct(s interface{}, multiline bool) string {\n\tv := reflect.ValueOf(s)\n\n\tif v.Kind() != reflect.Struct {\n\t\treturn \"Not a struct\"\n\t}\n\n\tnl := \", \"\n\tstr := \"{ \"\n\tif multiline {\n\t\tnl = \"\\n\\t\"\n\t\tstr += nl\n\t}\n\n\tfor k := 0; k < v.NumField(); k += 1 {\n\t\tname := v.Type().Field(k).Name\n\t\tif name[0] == strings.ToLower(name)[0] { \/\/ Unexported field\n\t\t\tcontinue\n\t\t}\n\t\ti := v.Field(k).Interface()\n\t\tkey := fmt.Sprintf(\"%v\", v.Type().Field(k).Name)\n\n\t\tswitch t := i.(type) {\n\t\tcase *bool:\n\t\t\tif t != nil {\n\t\t\t\tstr += fmt.Sprintf(\"%s: %+v%s\", key, *t, nl)\n\t\t\t}\n\t\tcase *int:\n\t\t\tif t != nil {\n\t\t\t\tstr += fmt.Sprintf(\"%s: %+v%s\", key, *t, nl)\n\t\t\t}\n\t\tcase *uint:\n\t\t\tif t != nil {\n\t\t\t\tstr += fmt.Sprintf(\"%s: %+v%s\", key, *t, nl)\n\t\t\t}\n\t\tcase *string:\n\t\t\tif t != nil {\n\t\t\t\tstr += fmt.Sprintf(\"%s: %+v%s\", key, *t, nl)\n\t\t\t}\n\t\tcase *float64:\n\t\t\tif t != nil {\n\t\t\t\tstr += fmt.Sprintf(\"%s: %+v%s\", key, *t, nl)\n\t\t\t}\n\t\tcase *time.Time:\n\t\t\tif t != nil {\n\t\t\t\tstr += fmt.Sprintf(\"%s: %+v%s\", key, *t, nl)\n\t\t\t}\n\t\tdefault:\n\t\t\tstr += fmt.Sprintf(\"%s: unknown%s\", key, nl)\n\t\t}\n\t}\n\n\tstr = str[:len(str)-2]\n\tif multiline {\n\t\tstr += \"\\n}\"\n\t} else {\n\t\tstr += \" }\"\n\t}\n\treturn str\n}\n<|endoftext|>"}
{"text":"<commit_before>package db\n\nimport (\n\t\"time\"\n\n\t\"github.com\/couchbaselabs\/go-couchbase\"\n\n\t\"github.com\/couchbaselabs\/sync_gateway\/base\"\n)\n\n\/\/ Unmarshaled JSON structure for \"changes\" view results\ntype channelsViewResult struct {\n\tTotalRows int `json:\"total_rows\"`\n\tRows      []channelsViewRow\n\tErrors    []couchbase.ViewError\n}\n\n\/\/ One \"changes\" row in a channelsViewResult\ntype channelsViewRow struct {\n\tID    string\n\tKey   []interface{} \/\/ Actually [channelName, sequence]\n\tValue struct {\n\t\tRev   string\n\t\tFlags uint8\n\t}\n}\n\n\/\/ Queries the 'channels' view to get a range of sequences of a single channel as LogEntries.\nfunc (dbc *DatabaseContext) getChangesInChannelFromView(\n\tchannelName string, endSeq uint64, options ChangesOptions) (LogEntries, error) {\n\tstart := time.Now()\n\t\/\/ Query the view:\n\toptMap := changesViewOptions(channelName, endSeq, options)\n\tbase.LogTo(\"Cache\", \"  Querying 'channels' view for %q (start=#%d, end=#%d, limit=%d)\", channelName, options.Since.Seq+1, endSeq, options.Limit)\n\tvres := channelsViewResult{}\n\terr := dbc.Bucket.ViewCustom(\"sync_gateway\", \"channels\", optMap, &vres)\n\tif err != nil {\n\t\tbase.Log(\"Error from 'channels' view: %v\", err)\n\t\treturn nil, err\n\t} else if len(vres.Rows) == 0 {\n\t\tbase.LogTo(\"Cache\", \"    Got no rows from view for %q\", channelName)\n\t\treturn nil, nil\n\t}\n\n\t\/\/ Convert the output to LogEntries:\n\tentries := make(LogEntries, 0, len(vres.Rows))\n\tfor _, row := range vres.Rows {\n\t\tentry := &LogEntry{\n\t\t\tSequence:     uint64(row.Key[1].(float64)),\n\t\t\tDocID:        row.ID,\n\t\t\tRevID:        row.Value.Rev,\n\t\t\tFlags:        row.Value.Flags,\n\t\t\tTimeReceived: time.Now(),\n\t\t}\n\t\t\/\/ base.LogTo(\"Cache\", \"  Got view sequence #%d (%q \/ %q)\", entry.Sequence, entry.DocID, entry.RevID)\n\t\tentries = append(entries, entry)\n\t}\n\n\tbase.LogTo(\"Cache\", \"    Got %d rows from view for %q: #%d ... #%d\",\n\t\tlen(entries), channelName, entries[0].Sequence, entries[len(entries)-1].Sequence)\n\tif elapsed := time.Since(start); elapsed > 200*time.Millisecond {\n\t\tbase.Log(\"changes_view: Query took %v to return %d rows, options = %#v\",\n\t\t\telapsed, len(entries), optMap)\n\t}\n\tchangeCacheExpvars.Add(\"view_queries\", 1)\n\treturn entries, nil\n}\n\nfunc changesViewOptions(channelName string, endSeq uint64, options ChangesOptions) Body {\n\tendKey := []interface{}{channelName, endSeq}\n\tif endSeq == 0 {\n\t\tendKey[1] = map[string]interface{}{} \/\/ infinity\n\t}\n\toptMap := Body{\n\t\t\"stale\":    false,\n\t\t\"startkey\": []interface{}{channelName, options.Since.Seq + 1},\n\t\t\"endkey\":   endKey,\n\t}\n\tif options.Limit > 0 {\n\t\toptMap[\"limit\"] = options.Limit\n\t}\n\treturn optMap\n}\n<commit_msg>Ensure all required revisions are queried from view<commit_after>package db\n\nimport (\n\t\"time\"\n\n\t\"github.com\/couchbaselabs\/go-couchbase\"\n\n\t\"github.com\/couchbaselabs\/sync_gateway\/base\"\n)\n\n\/\/ Unmarshaled JSON structure for \"changes\" view results\ntype channelsViewResult struct {\n\tTotalRows int `json:\"total_rows\"`\n\tRows      []channelsViewRow\n\tErrors    []couchbase.ViewError\n}\n\n\/\/ One \"changes\" row in a channelsViewResult\ntype channelsViewRow struct {\n\tID    string\n\tKey   []interface{} \/\/ Actually [channelName, sequence]\n\tValue struct {\n\t\tRev   string\n\t\tFlags uint8\n\t}\n}\n\n\/\/ Queries the 'channels' view to get a range of sequences of a single channel as LogEntries.\nfunc (dbc *DatabaseContext) getChangesInChannelFromView(\n\tchannelName string, endSeq uint64, options ChangesOptions) (LogEntries, error) {\n\tstart := time.Now()\n\t\/\/ Query the view:\n\toptions.Limit = 0\n\toptMap := changesViewOptions(channelName, endSeq, options)\n\tbase.LogTo(\"Cache\", \"  Querying 'channels' view for %q (start=#%d, end=#%d, limit=%d)\", channelName, options.Since.Seq+1, endSeq, options.Limit)\n\tvres := channelsViewResult{}\n\terr := dbc.Bucket.ViewCustom(\"sync_gateway\", \"channels\", optMap, &vres)\n\tif err != nil {\n\t\tbase.Log(\"Error from 'channels' view: %v\", err)\n\t\treturn nil, err\n\t} else if len(vres.Rows) == 0 {\n\t\tbase.LogTo(\"Cache\", \"    Got no rows from view for %q\", channelName)\n\t\treturn nil, nil\n\t}\n\n\t\/\/ Convert the output to LogEntries:\n\tentries := make(LogEntries, 0, len(vres.Rows))\n\tfor _, row := range vres.Rows {\n\t\tentry := &LogEntry{\n\t\t\tSequence:     uint64(row.Key[1].(float64)),\n\t\t\tDocID:        row.ID,\n\t\t\tRevID:        row.Value.Rev,\n\t\t\tFlags:        row.Value.Flags,\n\t\t\tTimeReceived: time.Now(),\n\t\t}\n\t\t\/\/ base.LogTo(\"Cache\", \"  Got view sequence #%d (%q \/ %q)\", entry.Sequence, entry.DocID, entry.RevID)\n\t\tentries = append(entries, entry)\n\t}\n\n\tbase.LogTo(\"Cache\", \"    Got %d rows from view for %q: #%d ... #%d\",\n\t\tlen(entries), channelName, entries[0].Sequence, entries[len(entries)-1].Sequence)\n\tif elapsed := time.Since(start); elapsed > 200*time.Millisecond {\n\t\tbase.Log(\"changes_view: Query took %v to return %d rows, options = %#v\",\n\t\t\telapsed, len(entries), optMap)\n\t}\n\tchangeCacheExpvars.Add(\"view_queries\", 1)\n\treturn entries, nil\n}\n\nfunc changesViewOptions(channelName string, endSeq uint64, options ChangesOptions) Body {\n\tendKey := []interface{}{channelName, endSeq}\n\tif endSeq == 0 {\n\t\tendKey[1] = map[string]interface{}{} \/\/ infinity\n\t}\n\toptMap := Body{\n\t\t\"stale\":    false,\n\t\t\"startkey\": []interface{}{channelName, options.Since.Seq + 1},\n\t\t\"endkey\":   endKey,\n\t}\n\tif options.Limit > 0 {\n\t\toptMap[\"limit\"] = options.Limit\n\t}\n\treturn optMap\n}\n<|endoftext|>"}
{"text":"<commit_before>package logging\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/getlantern\/go-loggly\"\n\t\"github.com\/getlantern\/golog\"\n\t\"github.com\/getlantern\/testify\/assert\"\n)\n\nfunc TestLoggly(t *testing.T) {\n\tvar buf bytes.Buffer\n\tvar result map[string]interface{}\n\tloggly := loggly.New(\"token not required\")\n\tloggly.Writer = &buf\n\tlw := logglyErrorWriter{client: loggly}\n\tgolog.SetOutputs(lw, nil)\n\tlog := golog.LoggerFor(\"test\")\n\n\tlog.Error(\"\")\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"test\", result[\"locationInfo\"])\n\t\tassert.Equal(t, \"\", result[\"message\"], \"empty message should be logged as is\")\n\t}\n\n\tbuf.Reset()\n\tlog.Error(\"short message\")\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"test\", result[\"locationInfo\"])\n\t\tassert.Equal(t, \"short message\", result[\"message\"], \"short message should be logged as is\")\n\t}\n\n\tbuf.Reset()\n\tlog.Error(\"message with: reason\")\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"test\", result[\"locationInfo\"])\n\t\tassert.Equal(t, \"message with: reason\", result[\"message\"], \"message should be last 2 chunks\")\n\t}\n\n\tbuf.Reset()\n\tlog.Error(\"deep reason: message with: reason\")\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"test\", result[\"locationInfo\"])\n\t\tassert.Equal(t, \"message with: reason\", result[\"message\"], \"message should be last 2 chunks\")\n\t}\n\n\tbuf.Reset()\n\tlog.Error(\"deep reason: an url https:\/\/a.com in message: reason\")\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"an url https:\/\/a.com in message: reason\", result[\"message\"], \"should not truncate url\")\n\t}\n\n\tbuf.Reset()\n\tlog.Error(\"deep reason: an url 127.0.0.1:8787 in message: reason\")\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"test\", result[\"locationInfo\"])\n\t\tassert.Equal(t, \"an url 127.0.0.1:8787 in message: reason\", result[\"message\"], \"should not truncate url\")\n\t}\n\n\tbuf.Reset()\n\tlongMsg := \"message with: really l\" + strings.Repeat(\"o\", 100) + \"ng reason\"\n\tlog.Error(longMsg)\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"test\", result[\"locationInfo\"])\n\t\tassert.Equal(t, longMsg, result[\"message\"], \"should not truncate long messages as it's unlikely to happen\")\n\t}\n}\n<commit_msg>fix logging test<commit_after>package logging\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/getlantern\/go-loggly\"\n\t\"github.com\/getlantern\/golog\"\n\t\"github.com\/getlantern\/testify\/assert\"\n)\n\nfunc TestLoggly(t *testing.T) {\n\tvar buf bytes.Buffer\n\tvar result map[string]interface{}\n\tloggly := loggly.New(\"token not required\")\n\tloggly.Writer = &buf\n\tlw := logglyErrorWriter{client: loggly}\n\tgolog.SetOutputs(lw, nil)\n\tlog := golog.LoggerFor(\"test\")\n\n\tlog.Error(\"\")\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"test\", result[\"locationInfo\"])\n\t\tassert.Regexp(t, regexp.MustCompile(\"logging_test.go:([0-9]+)\"), result[\"message\"])\n\t}\n\n\tbuf.Reset()\n\tlog.Error(\"short message\")\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"test\", result[\"locationInfo\"])\n\t\tassert.Regexp(t, regexp.MustCompile(\"logging_test.go:([0-9]+) short message\"), result[\"message\"])\n\t}\n\n\tbuf.Reset()\n\tlog.Error(\"message with: reason\")\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"test\", result[\"locationInfo\"])\n\t\tassert.Regexp(t, \"logging_test.go:([0-9]+) message with: reason\", result[\"message\"])\n\t}\n\n\tbuf.Reset()\n\tlog.Error(\"deep reason: message with: reason\")\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"test\", result[\"locationInfo\"])\n\t\tassert.Equal(t, \"message with: reason\", result[\"message\"], \"message should be last 2 chunks\")\n\t}\n\n\tbuf.Reset()\n\tlog.Error(\"deep reason: an url https:\/\/a.com in message: reason\")\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"an url https:\/\/a.com in message: reason\", result[\"message\"], \"should not truncate url\")\n\t}\n\n\tbuf.Reset()\n\tlog.Error(\"deep reason: an url 127.0.0.1:8787 in message: reason\")\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"test\", result[\"locationInfo\"])\n\t\tassert.Equal(t, \"an url 127.0.0.1:8787 in message: reason\", result[\"message\"], \"should not truncate url\")\n\t}\n\n\tbuf.Reset()\n\tlongMsg := \"message with: really l\" + strings.Repeat(\"o\", 100) + \"ng reason\"\n\tlog.Error(longMsg)\n\tif assert.NoError(t, json.Unmarshal(buf.Bytes(), &result), \"Unmarshal error\") {\n\t\tassert.Equal(t, \"test\", result[\"locationInfo\"])\n\t\tassert.Regexp(t, regexp.MustCompile(\"logging_test.go:([0-9]+) \"+longMsg), result[\"message\"])\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Vector Creations Ltd\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage config\n\nimport (\n\t\"github.com\/matrix-org\/dendrite\/mediaapi\/types\"\n\t\"github.com\/matrix-org\/gomatrixserverlib\"\n)\n\n\/\/ MediaAPI contains the config information necessary to spin up a mediaapi process.\ntype MediaAPI struct {\n\t\/\/ The name of the server. This is usually the domain name, e.g 'matrix.org', 'localhost'.\n\tServerName gomatrixserverlib.ServerName `yaml:\"server_name\"`\n\t\/\/ The absolute base path to where media files will be stored.\n\tAbsBasePath types.Path `yaml:\"abs_base_path\"`\n\t\/\/ The maximum file size in bytes that is allowed to be stored on this server.\n\t\/\/ Note that remote files larger than this can still be proxied to a client, they will just not be cached.\n\t\/\/ Note: if MaxFileSizeBytes is set to 0, the size is unlimited.\n\tMaxFileSizeBytes types.FileSizeBytes `yaml:\"max_file_size_bytes\"`\n\t\/\/ The postgres connection config for connecting to the database e.g a postgres:\/\/ URI\n\tDataSource string `yaml:\"database\"`\n}\n<commit_msg>mediaapi\/config: Remove obsolete proxying comment and add default comment<commit_after>\/\/ Copyright 2017 Vector Creations Ltd\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage config\n\nimport (\n\t\"github.com\/matrix-org\/dendrite\/mediaapi\/types\"\n\t\"github.com\/matrix-org\/gomatrixserverlib\"\n)\n\n\/\/ MediaAPI contains the config information necessary to spin up a mediaapi process.\ntype MediaAPI struct {\n\t\/\/ The name of the server. This is usually the domain name, e.g 'matrix.org', 'localhost'.\n\tServerName gomatrixserverlib.ServerName `yaml:\"server_name\"`\n\t\/\/ The absolute base path to where media files will be stored.\n\tAbsBasePath types.Path `yaml:\"abs_base_path\"`\n\t\/\/ The maximum file size in bytes that is allowed to be stored on this server.\n\t\/\/ Note: if MaxFileSizeBytes is set to 0, the size is unlimited.\n\t\/\/ Note: if max_file_size_bytes is not set, it will default to 10485760 (10MB)\n\tMaxFileSizeBytes types.FileSizeBytes `yaml:\"max_file_size_bytes\"`\n\t\/\/ The postgres connection config for connecting to the database e.g a postgres:\/\/ URI\n\tDataSource string `yaml:\"database\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Provides a redis storage adapter for storing and retrieving Watches.\n *\/\n\npackage msWatchStorage\n\nimport (\n\t\/\/ Utilities\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strconv\"\n\n\t\/\/ Redis.\n\t\"github.com\/mediocregopher\/radix.v2\/redis\"\n\n\t\/\/ Internal dependencies.\n\tcommon \"github.com\/krystalcode\/go-mantis-shrimp\/watches\/common\"\n\twrapper \"github.com\/krystalcode\/go-mantis-shrimp\/watches\/wrapper\"\n)\n\n\/**\n * Redis storage provider.\n *\/\n\n\/\/ Redis implements the Storage interface, allowing to use Redis as a Storage\n\/\/ engine.\ntype Redis struct {\n\tdsn    string\n\tclient *redis.Client\n}\n\n\/\/ Get implements Storage.Get(). It retrieves from Storage and returns the Watch\n\/\/ for the given ID.\nfunc (storage Redis) Get(_id int) common.Watch {\n\tif storage.client == nil {\n\t\tpanic(\"The Redis client has not been initialized yet.\")\n\t}\n\n\tkey := redisKey(_id)\n\n\tr := storage.client.Cmd(\"GET\", key)\n\tif r.Err != nil {\n\t\tpanic(r.Err)\n\t}\n\n\tjsonWatch, err := r.Bytes()\n\t\/\/ If an error happens here, it should be because there is no value for this\n\t\/\/ key. It could be the case that the data is corrupted or the wrong data is\n\t\/\/ stored, we should see how to handle this later.\n\t\/\/ @I Handle edge cases when deserializing json in Redis\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t\/\/ Create and initialize a Watch object based on the given JSON object.\n\twatch, err := wrapper.Create(jsonWatch)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn watch\n}\n\n\/\/ Set implements Storage.Set(). It stores the given Watch object to the Redis\n\/\/ Storage.\nfunc (storage Redis) Set(watch common.Watch) int {\n\t\/\/ @I Consider using hashmaps instead of json values\n\t\/\/ @I Investigate risk of a Watch overriding another due to race conditions when\n\t\/\/    creating them\n\n\tif storage.client == nil {\n\t\tpanic(\"The Redis client has not been initialized yet.\")\n\t}\n\n\t\/\/ We'll be storing a WatchWrapper which contains the Watch type as well.\n\twrapper, err := wrapper.Wrapper(watch)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjsonWatch, err := json.Marshal(wrapper)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Generate an ID, store the Watch, and update the Watches index set.\n\t_id := storage.generateID()\n\tkey := redisKey(_id)\n\terr = storage.client.Cmd(\"SET\", key, jsonWatch).Err\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = storage.client.Cmd(\"ZADD\", \"watches\", _id, key).Err\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn _id\n}\n\n\/\/ generateID generates an ID for a new Watch by incrementing the last known\n\/\/ Watch ID.\nfunc (storage Redis) generateID() int {\n\t\/\/ Get the last ID that exists on the Watches index set, so that we can generate\n\t\/\/ the next one.\n\tr, err := storage.client.Cmd(\"ZREVRANGE\", \"watches\", 0, 0, \"WITHSCORES\").List()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ If there are no watches yet, start with ID 1.\n\tif len(r) == 0 {\n\t\treturn 1\n\t}\n\n\t_id, err := strconv.Atoi(r[1])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn _id + 1\n}\n\n\/\/ NewRedisStorage implements the StorageFactory function type. It initiates a\n\/\/ connection to the Redis database defined in the given configuration, and it\n\/\/ returns the Storage engine object.\nvar NewRedisStorage = func(config map[string]string) (Storage, error) {\n\tdsn, ok := config[\"STORAGE_REDIS_DSN\"]\n\tif !ok {\n\t\terr := fmt.Errorf(\n\t\t\t\"the \\\"%s\\\" configuration option is required for the Redis storage\",\n\t\t\t\"STORAGE_REDIS_DSN\",\n\t\t)\n\t\treturn nil, err\n\t}\n\n\tclient, err := redis.Dial(\"tcp\", dsn)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"failed to connect to Redis: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tstorage := Redis{\n\t\tdsn:    dsn,\n\t\tclient: client,\n\t}\n\n\treturn storage, nil\n}\n\n\/**\n * For internal use.\n *\/\n\n\/\/ Generate a Redis key for the given Watch ID.\nfunc redisKey(_id int) string {\n\treturn \"watch:\" + strconv.Itoa(_id)\n}\n<commit_msg>ms_watches_storage Added Issue for improving error handling<commit_after>\/**\n * Provides a redis storage adapter for storing and retrieving Watches.\n *\/\n\npackage msWatchStorage\n\nimport (\n\t\/\/ Utilities\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strconv\"\n\n\t\/\/ Redis.\n\t\"github.com\/mediocregopher\/radix.v2\/redis\"\n\n\t\/\/ Internal dependencies.\n\tcommon \"github.com\/krystalcode\/go-mantis-shrimp\/watches\/common\"\n\twrapper \"github.com\/krystalcode\/go-mantis-shrimp\/watches\/wrapper\"\n)\n\n\/**\n * Redis storage provider.\n *\/\n\n\/\/ Redis implements the Storage interface, allowing to use Redis as a Storage\n\/\/ engine.\ntype Redis struct {\n\tdsn    string\n\tclient *redis.Client\n}\n\n\/\/ Get implements Storage.Get(). It retrieves from Storage and returns the Watch\n\/\/ for the given ID.\nfunc (storage Redis) Get(_id int) common.Watch {\n\t\/\/ @I Delegate error handling to the caller in Storage API functions\n\n\tif storage.client == nil {\n\t\tpanic(\"The Redis client has not been initialized yet.\")\n\t}\n\n\tkey := redisKey(_id)\n\n\tr := storage.client.Cmd(\"GET\", key)\n\tif r.Err != nil {\n\t\tpanic(r.Err)\n\t}\n\n\tjsonWatch, err := r.Bytes()\n\t\/\/ If an error happens here, it should be because there is no value for this\n\t\/\/ key. It could be the case that the data is corrupted or the wrong data is\n\t\/\/ stored, we should see how to handle this later.\n\t\/\/ @I Handle edge cases when deserializing json in Redis\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\t\/\/ Create and initialize a Watch object based on the given JSON object.\n\twatch, err := wrapper.Create(jsonWatch)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn watch\n}\n\n\/\/ Set implements Storage.Set(). It stores the given Watch object to the Redis\n\/\/ Storage.\nfunc (storage Redis) Set(watch common.Watch) int {\n\t\/\/ @I Consider using hashmaps instead of json values\n\t\/\/ @I Investigate risk of a Watch overriding another due to race conditions when\n\t\/\/    creating them\n\n\tif storage.client == nil {\n\t\tpanic(\"The Redis client has not been initialized yet.\")\n\t}\n\n\t\/\/ We'll be storing a WatchWrapper which contains the Watch type as well.\n\twrapper, err := wrapper.Wrapper(watch)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjsonWatch, err := json.Marshal(wrapper)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Generate an ID, store the Watch, and update the Watches index set.\n\t_id := storage.generateID()\n\tkey := redisKey(_id)\n\terr = storage.client.Cmd(\"SET\", key, jsonWatch).Err\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\terr = storage.client.Cmd(\"ZADD\", \"watches\", _id, key).Err\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn _id\n}\n\n\/\/ generateID generates an ID for a new Watch by incrementing the last known\n\/\/ Watch ID.\nfunc (storage Redis) generateID() int {\n\t\/\/ Get the last ID that exists on the Watches index set, so that we can generate\n\t\/\/ the next one.\n\tr, err := storage.client.Cmd(\"ZREVRANGE\", \"watches\", 0, 0, \"WITHSCORES\").List()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ If there are no watches yet, start with ID 1.\n\tif len(r) == 0 {\n\t\treturn 1\n\t}\n\n\t_id, err := strconv.Atoi(r[1])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn _id + 1\n}\n\n\/\/ NewRedisStorage implements the StorageFactory function type. It initiates a\n\/\/ connection to the Redis database defined in the given configuration, and it\n\/\/ returns the Storage engine object.\nvar NewRedisStorage = func(config map[string]string) (Storage, error) {\n\tdsn, ok := config[\"STORAGE_REDIS_DSN\"]\n\tif !ok {\n\t\terr := fmt.Errorf(\n\t\t\t\"the \\\"%s\\\" configuration option is required for the Redis storage\",\n\t\t\t\"STORAGE_REDIS_DSN\",\n\t\t)\n\t\treturn nil, err\n\t}\n\n\tclient, err := redis.Dial(\"tcp\", dsn)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"failed to connect to Redis: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tstorage := Redis{\n\t\tdsn:    dsn,\n\t\tclient: client,\n\t}\n\n\treturn storage, nil\n}\n\n\/**\n * For internal use.\n *\/\n\n\/\/ Generate a Redis key for the given Watch ID.\nfunc redisKey(_id int) string {\n\treturn \"watch:\" + strconv.Itoa(_id)\n}\n<|endoftext|>"}
{"text":"<commit_before>package dragonfly\n\nimport (\n\t\/\/\"fmt\"\n\t\"os\"\n)\n\ntype Job struct {\n\tSteps []Step\n\tTemp  *os.File\n}\n\nfunc (job *Job) Apply() (*os.File, error) {\n\tfileChan := make(chan *os.File)\n\terrChan := make(chan error)\n\tdefer close(fileChan)\n\tdefer close(errChan)\n\n\tvar (\n\t\ttemp *os.File\n\t\terr  error\n\t)\n\n\tgo job.Steps[0].Fetch(fileChan, errChan)\n\n\tselect {\n\tcase err = <-errChan:\n\t\treturn nil, err\n\tcase temp = <-fileChan:\n\t\t\/\/defer temp.Close()\n\t\t\/\/defer os.Remove(temp.Name())\n\t}\n\n\tgo job.Steps[1].Process(temp, fileChan, errChan)\n\tselect {\n\tcase err = <-errChan:\n\t\treturn nil, err\n\tcase temp = <-fileChan:\n\t\t\/\/defer temp.Close()\n\t\t\/\/defer os.Remove(temp.Name())\n\t}\n\n\treturn temp, err\n}\n<commit_msg>buffered channels yield a happier family<commit_after>package dragonfly\n\nimport (\n\t\/\/\"fmt\"\n\t\"os\"\n)\n\ntype Job struct {\n\tSteps []Step\n\tTemp  *os.File\n}\n\nfunc (job *Job) Apply() (*os.File, error) {\n\tfileChan := make(chan *os.File, 1)\n\terrChan := make(chan error, 1)\n\tdefer close(fileChan)\n\tdefer close(errChan)\n\n\tvar (\n\t\ttemp *os.File\n\t\terr  error\n\t)\n\n\tgo job.Steps[0].Fetch(fileChan, errChan)\n\n\tselect {\n\tcase err = <-errChan:\n\t\treturn nil, err\n\tcase temp = <-fileChan:\n\t\t\/\/defer temp.Close()\n\t\t\/\/defer os.Remove(temp.Name())\n\t}\n\n\tgo job.Steps[1].Process(temp, fileChan, errChan)\n\tselect {\n\tcase err = <-errChan:\n\t\treturn nil, err\n\tcase temp = <-fileChan:\n\t\t\/\/defer temp.Close()\n\t\t\/\/defer os.Remove(temp.Name())\n\t}\n\n\treturn temp, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package dragonfly\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n)\n\ntype Step interface {\n\tApply(in chan *os.File) (out chan *os.File, errChan chan error)\n\t\/\/Args    []string\n\t\/\/Command string\n}\n\ntype Job struct {\n\tSteps []Step\n\tTemp  *os.File\n}\n\nfunc (job *Job) Apply() (temp *os.File, err error) {\n\tblarrr := make(chan *os.File)\n\tclose(blarrr)\n\tseed1, errChan := job.Steps[0].Apply(blarrr)\n\tseed2, errChan2 := job.Steps[1].Apply(seed1)\n\t\/\/blarrr <- temp\n\n\tselect {\n\t\/\/case err = <-errChan:\n\n\tcase err = <-errChan:\n\t\tfmt.Println(\"errr\")\n\t\tfmt.Println(err)\n\n\t\tif err == nil {\n\t\t\ttemp = <-seed2\n\t\t}\n\n\tcase err = <-errChan2:\n\t\tfmt.Println(\"errr2\")\n\t\tfmt.Println(err)\n\t\tif err == nil {\n\t\t\ttemp = <-seed2\n\t\t}\n\tcase temp = <-seed2:\n\t\tfmt.Println(\"seed\")\n\t\tfmt.Println(\"tmp\")\n\n\t}\n\n\treturn\n\n}\n\ntype stepApplication func(temp *os.File) (*os.File, error)\n\nfunc applyStepPipeline(in chan *os.File, step stepApplication) (out chan *os.File, errChan chan error) {\n\tout = make(chan *os.File)\n\terrChan = make(chan error)\n\n\tgo func() {\n\t\tprev := <-in\n\t\tdefer close(out)\n\t\tdefer close(errChan)\n\n\t\tcontent, err := step(prev)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tout <- content\n\t}()\n\n\treturn out, errChan\n}\n\ntype FetchFileStep struct {\n\tArgs    []string\n\tCommand string\n}\n\ntype ResizeStep struct {\n\tArgs    []string\n\tCommand string\n}\n\nfunc (step ResizeStep) Apply(in chan *os.File) (out chan *os.File, errChan chan error) {\n\treturn applyStepPipeline(in, func(temp *os.File) (newTemp *os.File, err error) {\n\t\tformat := step.Args[1]\n\t\treturn step.resize(temp, format)\n\t})\n}\n\nfunc (step ResizeStep) resize(image *os.File, format string) (*os.File, error) {\n\tbinary, err := exec.LookPath(\"convert\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttempPrefix := \"godragonfly\" + format\n\tresized, err := ioutil.TempFile(os.TempDir(), tempPrefix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif image == nil {\n\t\treturn nil, err\n\t}\n\n\targs := []string{\n\t\timage.Name(),\n\t\t\"-resize\", format,\n\t\tresized.Name(),\n\t}\n\n\tcmd := exec.Command(binary, args...)\n\tcmd.Run()\n\n\treturn resized, err\n}\n\nfunc (step FetchFileStep) Apply(in chan *os.File) (out chan *os.File, errChan chan error) {\n\treturn applyStepPipeline(in, func(_ *os.File) (temp *os.File, err error) {\n\t\tfilename := step.Args[0]\n\t\treturn fechFile(filename)\n\t\t\/\/return nil, errors.New(\"please don't stop the music\")\n\t})\n}\n\nfunc fechFile(filename string) (*os.File, error) {\n\tcontent, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttemp, err := ioutil.TempFile(os.TempDir(), \"godragonfly\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = temp.Write(content)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn temp, err\n}\n<commit_msg>clear up variable names<commit_after>package dragonfly\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n)\n\ntype Step interface {\n\tApply(in chan *os.File) (out chan *os.File, errChan chan error)\n\t\/\/Args    []string\n\t\/\/Command string\n}\n\ntype Job struct {\n\tSteps []Step\n\tTemp  *os.File\n}\n\nfunc (job *Job) Apply() (temp *os.File, err error) {\n\n\thead := make(chan *os.File)\n\ttail, errChan := job.Steps[0].Apply(head)\n\ttail, errChan2 := job.Steps[1].Apply(tail)\n\n\tclose(head)\n\n\tselect {\n\n\tcase err = <-errChan:\n\t\tfmt.Println(\"errr\")\n\t\tfmt.Println(err)\n\n\t\tif err == nil {\n\t\t\ttemp = <-tail\n\t\t}\n\n\tcase err = <-errChan2:\n\t\tfmt.Println(\"errr2\")\n\t\tfmt.Println(err)\n\t\tif err == nil {\n\t\t\ttemp = <-tail\n\t\t}\n\tcase temp = <-tail:\n\t\tfmt.Println(\"seed\")\n\t\tfmt.Println(\"tmp\")\n\n\t}\n\n\treturn\n\n}\n\ntype stepApplication func(temp *os.File) (*os.File, error)\n\nfunc applyStepPipeline(in chan *os.File, step stepApplication) (out chan *os.File, errChan chan error) {\n\tout = make(chan *os.File)\n\terrChan = make(chan error)\n\n\tgo func() {\n\t\tprev := <-in\n\t\tdefer close(out)\n\t\tdefer close(errChan)\n\n\t\tcontent, err := step(prev)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tout <- content\n\t}()\n\n\treturn out, errChan\n}\n\ntype FetchFileStep struct {\n\tArgs    []string\n\tCommand string\n}\n\ntype ResizeStep struct {\n\tArgs    []string\n\tCommand string\n}\n\nfunc (step ResizeStep) Apply(in chan *os.File) (out chan *os.File, errChan chan error) {\n\treturn applyStepPipeline(in, func(temp *os.File) (newTemp *os.File, err error) {\n\t\tformat := step.Args[1]\n\t\treturn step.resize(temp, format)\n\t})\n}\n\nfunc (step ResizeStep) resize(image *os.File, format string) (*os.File, error) {\n\tbinary, err := exec.LookPath(\"convert\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttempPrefix := \"godragonfly\" + format\n\tresized, err := ioutil.TempFile(os.TempDir(), tempPrefix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif image == nil {\n\t\treturn nil, err\n\t}\n\n\targs := []string{\n\t\timage.Name(),\n\t\t\"-resize\", format,\n\t\tresized.Name(),\n\t}\n\n\tcmd := exec.Command(binary, args...)\n\tcmd.Run()\n\n\treturn resized, err\n}\n\nfunc (step FetchFileStep) Apply(in chan *os.File) (out chan *os.File, errChan chan error) {\n\treturn applyStepPipeline(in, func(_ *os.File) (temp *os.File, err error) {\n\t\tfilename := step.Args[0]\n\t\treturn fechFile(filename)\n\t\t\/\/return nil, errors.New(\"please don't stop the music\")\n\t})\n}\n\nfunc fechFile(filename string) (*os.File, error) {\n\tcontent, err := ioutil.ReadFile(filename)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttemp, err := ioutil.TempFile(os.TempDir(), \"godragonfly\")\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = temp.Write(content)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn temp, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package driver\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com\/Spirals-Team\/docker-machine-driver-g5k\/api\"\n\n\t\"github.com\/docker\/machine\/libmachine\/drivers\"\n\t\"github.com\/docker\/machine\/libmachine\/log\"\n\t\"github.com\/docker\/machine\/libmachine\/mcnflag\"\n\t\"github.com\/docker\/machine\/libmachine\/ssh\"\n\t\"github.com\/docker\/machine\/libmachine\/state\"\n\tgossh \"golang.org\/x\/crypto\/ssh\"\n)\n\n\/\/ g5kReferenceEnvironment is the name of the reference environment automatically deployed on the node by Grid'5000\nconst g5kReferenceEnvironmentName string = \"debian9-x64-std\"\n\n\/\/ Driver parameters\ntype Driver struct {\n\t*drivers.BaseDriver\n\n\tG5kAPI                 *api.Client\n\tG5kJobID               int\n\tG5kUsername            string\n\tG5kPassword            string\n\tG5kSite                string\n\tG5kWalltime            string\n\tG5kImage               string\n\tG5kResourceProperties  string\n\tG5kHostToProvision     string\n\tG5kSkipVpnChecks       bool\n\tG5kReuseRefEnvironment bool\n\tG5kJobQueue            string\n\tEphemeralSSHKeyPair    *ssh.KeyPair\n\tExternalSSHPublicKeys  []string\n}\n\n\/\/ NewDriver creates and returns a new instance of the driver\nfunc NewDriver() *Driver {\n\treturn &Driver{\n\t\tBaseDriver: &drivers.BaseDriver{\n\t\t\tSSHUser: drivers.DefaultSSHUser,\n\t\t\tSSHPort: drivers.DefaultSSHPort,\n\t\t},\n\t}\n}\n\n\/\/ DriverName returns the name of the driver\nfunc (d *Driver) DriverName() string {\n\treturn \"g5k\"\n}\n\n\/\/ GetCreateFlags add command line flags to configure the driver\nfunc (d *Driver) GetCreateFlags() []mcnflag.Flag {\n\treturn []mcnflag.Flag{\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_USERNAME\",\n\t\t\tName:   \"g5k-username\",\n\t\t\tUsage:  \"Your Grid5000 account username\",\n\t\t\tValue:  \"\",\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_PASSWORD\",\n\t\t\tName:   \"g5k-password\",\n\t\t\tUsage:  \"Your Grid5000 account password\",\n\t\t\tValue:  \"\",\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_SITE\",\n\t\t\tName:   \"g5k-site\",\n\t\t\tUsage:  \"Site to reserve the resources on\",\n\t\t\tValue:  \"\",\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_WALLTIME\",\n\t\t\tName:   \"g5k-walltime\",\n\t\t\tUsage:  \"Machine's lifetime (HH:MM:SS)\",\n\t\t\tValue:  \"1:00:00\",\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_IMAGE\",\n\t\t\tName:   \"g5k-image\",\n\t\t\tUsage:  \"Name of the image (environment) to deploy on the node\",\n\t\t\tValue:  g5kReferenceEnvironmentName,\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_RESOURCE_PROPERTIES\",\n\t\t\tName:   \"g5k-resource-properties\",\n\t\t\tUsage:  \"Resource selection with OAR properties (SQL format)\",\n\t\t\tValue:  \"\",\n\t\t},\n\n\t\tmcnflag.IntFlag{\n\t\t\tEnvVar: \"G5K_USE_JOB_RESERVATION\",\n\t\t\tName:   \"g5k-use-job-reservation\",\n\t\t\tUsage:  \"Job ID to use (need to be an already existing job ID, because job reservation will be skipped)\",\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_HOST_TO_PROVISION\",\n\t\t\tName:   \"g5k-host-to-provision\",\n\t\t\tUsage:  \"Host to provision (host need to be already deployed, because deployment step will be skipped)\",\n\t\t\tValue:  \"\",\n\t\t},\n\n\t\tmcnflag.BoolFlag{\n\t\t\tEnvVar: \"G5K_SKIP_VPN_CHECKS\",\n\t\t\tName:   \"g5k-skip-vpn-checks\",\n\t\t\tUsage:  \"Skip the VPN client connection and DNS configuration checks (for particular use case only, you should not enable this flag in normal use)\",\n\t\t},\n\n\t\tmcnflag.BoolFlag{\n\t\t\tEnvVar: \"G5K_REUSE_REF_ENVIRONMENT\",\n\t\t\tName:   \"g5k-reuse-ref-environment\",\n\t\t\tUsage:  \"Reuse the Grid'5000 reference environment instead of re-deploying the node (it saves a lot of time)\",\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_JOB_QUEUE\",\n\t\t\tName:   \"g5k-job-queue\",\n\t\t\tUsage:  \"Specify the job queue (default or production only, besteffort is NOT supported)\",\n\t\t\tValue:  \"default\",\n\t\t},\n\n\t\tmcnflag.StringSliceFlag{\n\t\t\tEnvVar: \"G5K_EXTERNAL_SSH_PUBLIC_KEYS\",\n\t\t\tName:   \"g5k-external-ssh-public-keys\",\n\t\t\tUsage:  \"Additional SSH public key(s) allowed to connect to the node (in authorized_keys format)\",\n\t\t\tValue:  []string{},\n\t\t},\n\t}\n}\n\n\/\/ SetConfigFromFlags configure the driver from the command line arguments\nfunc (d *Driver) SetConfigFromFlags(opts drivers.DriverOptions) error {\n\td.G5kUsername = opts.String(\"g5k-username\")\n\td.G5kPassword = opts.String(\"g5k-password\")\n\td.G5kSite = opts.String(\"g5k-site\")\n\td.G5kWalltime = opts.String(\"g5k-walltime\")\n\td.G5kImage = opts.String(\"g5k-image\")\n\td.G5kResourceProperties = opts.String(\"g5k-resource-properties\")\n\td.G5kJobID = opts.Int(\"g5k-use-job-reservation\")\n\td.G5kHostToProvision = opts.String(\"g5k-host-to-provision\")\n\td.G5kSkipVpnChecks = opts.Bool(\"g5k-skip-vpn-checks\")\n\td.G5kReuseRefEnvironment = opts.Bool(\"g5k-reuse-ref-environment\")\n\td.G5kJobQueue = opts.String(\"g5k-job-queue\")\n\td.ExternalSSHPublicKeys = opts.StringSlice(\"g5k-external-ssh-public-keys\")\n\n\t\/\/ Docker Swarm\n\td.BaseDriver.SetSwarmConfigFromFlags(opts)\n\n\t\/\/ username is required\n\tif d.G5kUsername == \"\" {\n\t\treturn fmt.Errorf(\"You must give your Grid5000 account username\")\n\t}\n\n\t\/\/ password is required\n\tif d.G5kPassword == \"\" {\n\t\treturn fmt.Errorf(\"You must give your Grid5000 account password\")\n\t}\n\n\t\/\/ site is required\n\tif d.G5kSite == \"\" {\n\t\treturn fmt.Errorf(\"You must give the site you want to reserve the resources on\")\n\t}\n\n\tif d.G5kReuseRefEnvironment && d.G5kImage != g5kReferenceEnvironmentName {\n\t\treturn fmt.Errorf(\"You have to choose between reusing the reference environment or redeploying the node with another image\")\n\t}\n\n\t\/\/ warn if user disable VPN check\n\tif d.G5kSkipVpnChecks {\n\t\tlog.Warn(\"VPN client connection and DNS configuration checks are disabled\")\n\t}\n\n\t\/\/ we cannot use the besteffort queue with docker-machine\n\tif d.G5kJobQueue == \"besteffort\" {\n\t\treturn fmt.Errorf(\"The besteffort queue is not supported\")\n\t}\n\n\treturn nil\n}\n\n\/\/ GetIP returns the ip\nfunc (d *Driver) GetIP() (string, error) {\n\treturn d.BaseDriver.GetIP()\n}\n\n\/\/ GetMachineName returns the machine name\nfunc (d *Driver) GetMachineName() string {\n\treturn d.BaseDriver.GetMachineName()\n}\n\n\/\/ GetSSHHostname returns the machine hostname\nfunc (d *Driver) GetSSHHostname() (string, error) {\n\treturn d.GetIP()\n}\n\n\/\/ GetSSHKeyPath returns the ssh private key path\nfunc (d *Driver) GetSSHKeyPath() string {\n\treturn d.BaseDriver.GetSSHKeyPath()\n}\n\n\/\/ GetSSHPort returns the ssh port\nfunc (d *Driver) GetSSHPort() (int, error) {\n\treturn d.BaseDriver.GetSSHPort()\n}\n\n\/\/ GetSSHUsername returns the ssh user name\nfunc (d *Driver) GetSSHUsername() string {\n\treturn d.BaseDriver.GetSSHUsername()\n}\n\n\/\/ GetURL returns the URL of the docker daemon\nfunc (d *Driver) GetURL() (string, error) {\n\t\/\/ get IP address\n\tip, err := d.GetIP()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t\/\/ format URL 'tcp:\/\/host:2376'\n\treturn fmt.Sprintf(\"tcp:\/\/%s\", net.JoinHostPort(ip, \"2376\")), nil\n}\n\n\/\/ GetState returns the state of the node\nfunc (d *Driver) GetState() (state.State, error) {\n\t\/\/ get job state from API\n\tstatus, err := d.G5kAPI.GetJobState(d.G5kJobID)\n\tif err != nil {\n\t\treturn state.Error, err\n\t}\n\n\tswitch status {\n\tcase \"waiting\":\n\t\treturn state.Starting, nil\n\tcase \"launching\":\n\t\treturn state.Starting, nil\n\tcase \"running\":\n\t\treturn state.Running, nil\n\tcase \"hold\":\n\t\treturn state.Stopped, nil\n\tcase \"error\":\n\t\treturn state.Error, nil\n\tcase \"terminated\":\n\t\treturn state.Stopped, nil\n\tdefault:\n\t\treturn state.None, nil\n\t}\n}\n\n\/\/ PreCreateCheck check parameters and submit the job to Grid5000\nfunc (d *Driver) PreCreateCheck() (err error) {\n\t\/\/ check VPN connection if enabled\n\tif !d.G5kSkipVpnChecks {\n\t\tif err := CheckVpnConnection(d.G5kSite); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ create API client\n\td.G5kAPI = api.NewClient(d.G5kUsername, d.G5kPassword, d.G5kSite)\n\n\t\/\/ check format of external SSH public keys\n\tfor _, externalSSHPubKey := range d.ExternalSSHPublicKeys {\n\t\t_, _, _, _, err := gossh.ParseAuthorizedKey([]byte(externalSSHPubKey))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"The external SSH public key '%s' is invalid: %s\", externalSSHPubKey, err.Error())\n\t\t}\n\t}\n\n\t\/\/ check if a SSH key pair is available\n\tif d.EphemeralSSHKeyPair == nil {\n\t\t\/\/ generate a new SSH key pair\n\t\td.EphemeralSSHKeyPair, err = ssh.NewKeyPair()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error when generating a new SSH key pair: %s\", err.Error())\n\t\t}\n\t}\n\n\t\/\/ submit new job reservation\n\tif err := d.submitNewJobReservation(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ submit new deployment\n\treturn d.submitNewDeployment()\n}\n\n\/\/ Create copy ssh key in docker-machine dir and set the node IP\nfunc (d *Driver) Create() (err error) {\n\t\/\/ provisionning only mode\n\tif d.G5kHostToProvision != \"\" {\n\t\t\/\/ use provided hostname\n\t\td.BaseDriver.IPAddress = d.G5kHostToProvision\n\t} else {\n\t\t\/\/ get hostname from API\n\t\tjob, err := d.G5kAPI.GetJob(d.G5kJobID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.BaseDriver.IPAddress = job.Nodes[0]\n\t}\n\n\t\/\/ copy ephemeral SSH key pair to machine directory\n\tif err := d.EphemeralSSHKeyPair.WriteToFile(d.GetSSHKeyPath(), d.GetSSHKeyPath()+\".pub\"); err != nil {\n\t\treturn fmt.Errorf(\"Error when copying SSH key pair to machine directory: %s\", err.Error())\n\t}\n\n\treturn nil\n}\n\n\/\/ Remove delete the resources reservation\nfunc (d *Driver) Remove() error {\n\tlog.Infof(\"Killing job... (id: '%d')\", d.G5kJobID)\n\n\t\/\/ send kill job command to API\n\td.G5kAPI.KillJob(d.G5kJobID)\n\n\treturn nil\n}\n\n\/\/ Kill don't do anything\nfunc (d *Driver) Kill() error {\n\treturn fmt.Errorf(\"The 'kill' operation is not supported on Grid'5000\")\n}\n\n\/\/ Start don't do anything\nfunc (d *Driver) Start() error {\n\treturn fmt.Errorf(\"The 'start' operation is not supported on Grid'5000\")\n}\n\n\/\/ Stop don't do anything\nfunc (d *Driver) Stop() error {\n\treturn fmt.Errorf(\"The 'stop' operation is not supported on Grid'5000\")\n}\n\n\/\/ Restart don't do anything\nfunc (d *Driver) Restart() error {\n\treturn fmt.Errorf(\"The 'restart' operation is not supported on Grid'5000\")\n}\n<commit_msg>feat: Rework driver<commit_after>package driver\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com\/docker\/machine\/libmachine\/mcnutils\"\n\n\t\"github.com\/Spirals-Team\/docker-machine-driver-g5k\/api\"\n\n\t\"github.com\/docker\/machine\/libmachine\/drivers\"\n\t\"github.com\/docker\/machine\/libmachine\/log\"\n\t\"github.com\/docker\/machine\/libmachine\/mcnflag\"\n\t\"github.com\/docker\/machine\/libmachine\/state\"\n\tgossh \"golang.org\/x\/crypto\/ssh\"\n)\n\n\/\/ g5kReferenceEnvironment is the name of the reference environment automatically deployed on the node by Grid'5000\nconst g5kReferenceEnvironmentName string = \"debian9-x64-std\"\n\n\/\/ Driver parameters\ntype Driver struct {\n\t*drivers.BaseDriver\n\n\tG5kAPI                 *api.Client\n\tG5kJobID               int\n\tG5kUsername            string\n\tG5kPassword            string\n\tG5kSite                string\n\tG5kWalltime            string\n\tG5kImage               string\n\tG5kResourceProperties  string\n\tG5kSkipVpnChecks       bool\n\tG5kReuseRefEnvironment bool\n\tG5kJobQueue            string\n\tG5kJobStartTime        string\n\tDriverSSHPublicKey     string\n\tExternalSSHPublicKeys  []string\n}\n\n\/\/ NewDriver creates and returns a new instance of the driver\nfunc NewDriver() *Driver {\n\treturn &Driver{\n\t\tBaseDriver: &drivers.BaseDriver{\n\t\t\tSSHUser: drivers.DefaultSSHUser,\n\t\t\tSSHPort: drivers.DefaultSSHPort,\n\t\t},\n\t}\n}\n\n\/\/ DriverName returns the name of the driver\nfunc (d *Driver) DriverName() string {\n\treturn \"g5k\"\n}\n\n\/\/ GetCreateFlags add command line flags to configure the driver\nfunc (d *Driver) GetCreateFlags() []mcnflag.Flag {\n\treturn []mcnflag.Flag{\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_USERNAME\",\n\t\t\tName:   \"g5k-username\",\n\t\t\tUsage:  \"Your Grid5000 account username\",\n\t\t\tValue:  \"\",\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_PASSWORD\",\n\t\t\tName:   \"g5k-password\",\n\t\t\tUsage:  \"Your Grid5000 account password\",\n\t\t\tValue:  \"\",\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_SITE\",\n\t\t\tName:   \"g5k-site\",\n\t\t\tUsage:  \"Site to reserve the resources on\",\n\t\t\tValue:  \"\",\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_WALLTIME\",\n\t\t\tName:   \"g5k-walltime\",\n\t\t\tUsage:  \"Machine's lifetime (HH:MM:SS)\",\n\t\t\tValue:  \"1:00:00\",\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_IMAGE\",\n\t\t\tName:   \"g5k-image\",\n\t\t\tUsage:  \"Name of the image (environment) to deploy on the node\",\n\t\t\tValue:  g5kReferenceEnvironmentName,\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_RESOURCE_PROPERTIES\",\n\t\t\tName:   \"g5k-resource-properties\",\n\t\t\tUsage:  \"Resource selection with OAR properties (SQL format)\",\n\t\t\tValue:  \"\",\n\t\t},\n\n\t\tmcnflag.BoolFlag{\n\t\t\tEnvVar: \"G5K_SKIP_VPN_CHECKS\",\n\t\t\tName:   \"g5k-skip-vpn-checks\",\n\t\t\tUsage:  \"Skip the VPN client connection and DNS configuration checks (for particular use case only, you should not enable this flag in normal use)\",\n\t\t},\n\n\t\tmcnflag.BoolFlag{\n\t\t\tEnvVar: \"G5K_REUSE_REF_ENVIRONMENT\",\n\t\t\tName:   \"g5k-reuse-ref-environment\",\n\t\t\tUsage:  \"Reuse the Grid'5000 reference environment instead of re-deploying the node (it saves a lot of time)\",\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_JOB_QUEUE\",\n\t\t\tName:   \"g5k-job-queue\",\n\t\t\tUsage:  \"Specify the job queue (default or production only, besteffort is NOT supported)\",\n\t\t\tValue:  \"default\",\n\t\t},\n\n\t\tmcnflag.StringFlag{\n\t\t\tEnvVar: \"G5K_MAKE_JOB_RESERVATION\",\n\t\t\tName:   \"g5k-make-job-reservation\",\n\t\t\tUsage:  \"Request a job start time\/date reservation instead of a submission. The date format is 'YYYY-MM-DD HH:MM:SS' or a UNIX timestamp\",\n\t\t},\n\n\t\tmcnflag.IntFlag{\n\t\t\tEnvVar: \"G5K_USE_JOB_RESERVATION\",\n\t\t\tName:   \"g5k-use-job-reservation\",\n\t\t\tUsage:  \"Job reservation ID to use (need to be a job of 'deploy' type and in the 'running' state)\",\n\t\t},\n\n\t\tmcnflag.StringSliceFlag{\n\t\t\tEnvVar: \"G5K_EXTERNAL_SSH_PUBLIC_KEYS\",\n\t\t\tName:   \"g5k-external-ssh-public-keys\",\n\t\t\tUsage:  \"Additional SSH public key(s) allowed to connect to the node (in authorized_keys format)\",\n\t\t\tValue:  []string{},\n\t\t},\n\t}\n}\n\n\/\/ SetConfigFromFlags configure the driver from the command line arguments\nfunc (d *Driver) SetConfigFromFlags(opts drivers.DriverOptions) error {\n\td.G5kUsername = opts.String(\"g5k-username\")\n\td.G5kPassword = opts.String(\"g5k-password\")\n\td.G5kSite = opts.String(\"g5k-site\")\n\td.G5kWalltime = opts.String(\"g5k-walltime\")\n\td.G5kImage = opts.String(\"g5k-image\")\n\td.G5kResourceProperties = opts.String(\"g5k-resource-properties\")\n\td.G5kSkipVpnChecks = opts.Bool(\"g5k-skip-vpn-checks\")\n\td.G5kReuseRefEnvironment = opts.Bool(\"g5k-reuse-ref-environment\")\n\td.G5kJobQueue = opts.String(\"g5k-job-queue\")\n\td.G5kJobStartTime = opts.String(\"g5k-make-job-reservation\")\n\td.G5kJobID = opts.Int(\"g5k-use-job-reservation\")\n\td.ExternalSSHPublicKeys = opts.StringSlice(\"g5k-external-ssh-public-keys\")\n\n\t\/\/ Docker Swarm\n\td.BaseDriver.SetSwarmConfigFromFlags(opts)\n\n\t\/\/ username is required\n\tif d.G5kUsername == \"\" {\n\t\treturn fmt.Errorf(\"You must give your Grid5000 account username\")\n\t}\n\n\t\/\/ password is required\n\tif d.G5kPassword == \"\" {\n\t\treturn fmt.Errorf(\"You must give your Grid5000 account password\")\n\t}\n\n\t\/\/ site is required\n\tif d.G5kSite == \"\" {\n\t\treturn fmt.Errorf(\"You must give the site you want to reserve the resources on\")\n\t}\n\n\t\/\/ contradictory use of parameters: providing an image to deploy while trying to reuse the reference environment\n\tif d.G5kReuseRefEnvironment && d.G5kImage != g5kReferenceEnvironmentName {\n\t\treturn fmt.Errorf(\"You have to choose between reusing the reference environment or redeploying the node with another image\")\n\t}\n\n\t\/\/ we cannot reuse the reference environment when the job is of type 'deploy'\n\tif d.G5kReuseRefEnvironment && (d.G5kJobStartTime != \"\" || d.G5kJobID != 0) {\n\t\treturn fmt.Errorf(\"Reusing the Grid'5000 reference environment on a job reservation is not supported\")\n\t}\n\n\t\/\/ warn if user disable VPN check\n\tif d.G5kSkipVpnChecks {\n\t\tlog.Warn(\"VPN client connection and DNS configuration checks are disabled\")\n\t}\n\n\t\/\/ we cannot use the besteffort queue with docker-machine\n\tif d.G5kJobQueue == \"besteffort\" {\n\t\treturn fmt.Errorf(\"The besteffort queue is not supported\")\n\t}\n\n\treturn nil\n}\n\n\/\/ GetIP returns the ip\nfunc (d *Driver) GetIP() (string, error) {\n\treturn d.BaseDriver.GetIP()\n}\n\n\/\/ GetMachineName returns the machine name\nfunc (d *Driver) GetMachineName() string {\n\treturn d.BaseDriver.GetMachineName()\n}\n\n\/\/ GetSSHHostname returns the machine hostname\nfunc (d *Driver) GetSSHHostname() (string, error) {\n\treturn d.GetIP()\n}\n\n\/\/ GetSSHKeyPath returns the ssh private key path\nfunc (d *Driver) GetSSHKeyPath() string {\n\treturn d.BaseDriver.GetSSHKeyPath()\n}\n\n\/\/ GetSSHPort returns the ssh port\nfunc (d *Driver) GetSSHPort() (int, error) {\n\treturn d.BaseDriver.GetSSHPort()\n}\n\n\/\/ GetSSHUsername returns the ssh user name\nfunc (d *Driver) GetSSHUsername() string {\n\treturn d.BaseDriver.GetSSHUsername()\n}\n\n\/\/ GetURL returns the URL of the docker daemon\nfunc (d *Driver) GetURL() (string, error) {\n\t\/\/ get IP address\n\tip, err := d.GetIP()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t\/\/ format URL 'tcp:\/\/host:2376'\n\treturn fmt.Sprintf(\"tcp:\/\/%s\", net.JoinHostPort(ip, \"2376\")), nil\n}\n\n\/\/ GetState returns the state of the node\nfunc (d *Driver) GetState() (state.State, error) {\n\t\/\/ get job state from API\n\tstatus, err := d.G5kAPI.GetJobState(d.G5kJobID)\n\tif err != nil {\n\t\treturn state.Error, err\n\t}\n\n\tswitch status {\n\tcase \"waiting\":\n\t\treturn state.Starting, nil\n\tcase \"launching\":\n\t\treturn state.Starting, nil\n\tcase \"running\":\n\t\treturn state.Running, nil\n\tcase \"hold\":\n\t\treturn state.Stopped, nil\n\tcase \"error\":\n\t\treturn state.Error, nil\n\tcase \"terminated\":\n\t\treturn state.Stopped, nil\n\tdefault:\n\t\treturn state.None, nil\n\t}\n}\n\n\/\/ PreCreateCheck check parameters and submit the job to Grid5000\nfunc (d *Driver) PreCreateCheck() error {\n\t\/\/ prepare the driver store dir\n\tif err := d.prepareDriverStoreDirectory(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ check VPN connection if enabled\n\tif !d.G5kSkipVpnChecks {\n\t\tif err := d.checkVpnConnection(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ create API client\n\td.G5kAPI = api.NewClient(d.G5kUsername, d.G5kPassword, d.G5kSite)\n\n\t\/\/ load driver SSH public key\n\tif err := d.loadDriverSSHPublicKey(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ check format of external SSH public keys\n\tfor _, externalSSHPubKey := range d.ExternalSSHPublicKeys {\n\t\t_, _, _, _, err := gossh.ParseAuthorizedKey([]byte(externalSSHPubKey))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"The external SSH public key '%s' is invalid: %s\", externalSSHPubKey, err.Error())\n\t\t}\n\t}\n\n\t\/\/ skip the job submission\/reservation if a job ID is provided\n\tif d.G5kJobID == 0 {\n\t\tif d.G5kJobStartTime == \"\" {\n\t\t\t\/\/ make a job submission: the resources will be reserved for immediate use\n\t\t\tif err := d.makeJobSubmission(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ make a job reservation: the resources will be reserved for a defined date\/time\n\t\t\tif err := d.makeJobReservation(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ stop the machine creation\n\t\t\treturn fmt.Errorf(\"The job reservation have been successfully sent. Don't forget to save the Job ID to create the machine when the resources are available\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Create wait for the job to be running, deploy the OS image and copy the ssh keys\nfunc (d *Driver) Create() error {\n\t\/\/ wait for job to be in 'running' state\n\tif err := d.waitUntilJobIsReady(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ get node hostname from API\n\tjob, err := d.G5kAPI.GetJob(d.G5kJobID)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.BaseDriver.IPAddress = job.Nodes[0]\n\n\t\/\/ deploy OS image to the node\n\tif err := d.deployImageToNode(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ copy driver SSH key pair to machine directory\n\tif err := mcnutils.CopyFile(d.getDriverSSHKeyPath(), d.GetSSHKeyPath()); err != nil {\n\t\treturn err\n\t}\n\tif err := mcnutils.CopyFile(d.getDriverSSHKeyPath()+\".pub\", d.GetSSHKeyPath()+\".pub\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Remove delete the resources reservation\nfunc (d *Driver) Remove() error {\n\tlog.Infof(\"Killing job... (id: '%d')\", d.G5kJobID)\n\n\t\/\/ send kill job command to API\n\td.G5kAPI.KillJob(d.G5kJobID)\n\n\treturn nil\n}\n\n\/\/ Kill don't do anything\nfunc (d *Driver) Kill() error {\n\treturn fmt.Errorf(\"The 'kill' operation is not supported on Grid'5000\")\n}\n\n\/\/ Start don't do anything\nfunc (d *Driver) Start() error {\n\treturn fmt.Errorf(\"The 'start' operation is not supported on Grid'5000\")\n}\n\n\/\/ Stop don't do anything\nfunc (d *Driver) Stop() error {\n\treturn fmt.Errorf(\"The 'stop' operation is not supported on Grid'5000\")\n}\n\n\/\/ Restart don't do anything\nfunc (d *Driver) Restart() error {\n\treturn fmt.Errorf(\"The 'restart' operation is not supported on Grid'5000\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2014 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage testing\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"k8s.io\/utils\/clock\"\n)\n\nvar (\n\t_ = clock.Clock(&FakeClock{})\n\t_ = clock.Clock(&IntervalClock{})\n)\n\n\/\/ FakeClock implements clock.Clock, but returns an arbitrary time.\ntype FakeClock struct {\n\tlock sync.RWMutex\n\ttime time.Time\n\n\t\/\/ waiters are waiting for the fake time to pass their specified time\n\twaiters []*fakeClockWaiter\n}\n\ntype fakeClockWaiter struct {\n\ttargetTime    time.Time\n\tstepInterval  time.Duration\n\tskipIfBlocked bool\n\tdestChan      chan time.Time\n\tfired         bool\n}\n\nfunc NewFakeClock(t time.Time) *FakeClock {\n\treturn &FakeClock{\n\t\ttime: t,\n\t}\n}\n\n\/\/ Now returns f's time.\nfunc (f *FakeClock) Now() time.Time {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\treturn f.time\n}\n\n\/\/ Since returns time since the time in f.\nfunc (f *FakeClock) Since(ts time.Time) time.Duration {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\treturn f.time.Sub(ts)\n}\n\n\/\/ Fake version of time.After(d).\nfunc (f *FakeClock) After(d time.Duration) <-chan time.Time {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tstopTime := f.time.Add(d)\n\tch := make(chan time.Time, 1) \/\/ Don't block!\n\tf.waiters = append(f.waiters, &fakeClockWaiter{\n\t\ttargetTime: stopTime,\n\t\tdestChan:   ch,\n\t})\n\treturn ch\n}\n\n\/\/ Fake version of time.NewTimer(d).\nfunc (f *FakeClock) NewTimer(d time.Duration) clock.Timer {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tstopTime := f.time.Add(d)\n\tch := make(chan time.Time, 1) \/\/ Don't block!\n\ttimer := &fakeTimer{\n\t\tfakeClock: f,\n\t\twaiter: fakeClockWaiter{\n\t\t\ttargetTime: stopTime,\n\t\t\tdestChan:   ch,\n\t\t},\n\t}\n\tf.waiters = append(f.waiters, &timer.waiter)\n\treturn timer\n}\n\nfunc (f *FakeClock) Tick(d time.Duration) <-chan time.Time {\n\tif d <= 0 {\n\t\treturn nil\n\t}\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\ttickTime := f.time.Add(d)\n\tch := make(chan time.Time, 1) \/\/ hold one tick\n\tf.waiters = append(f.waiters, &fakeClockWaiter{\n\t\ttargetTime:    tickTime,\n\t\tstepInterval:  d,\n\t\tskipIfBlocked: true,\n\t\tdestChan:      ch,\n\t})\n\n\treturn ch\n}\n\n\/\/ Move clock by Duration, notify anyone that's called After, Tick, or NewTimer\nfunc (f *FakeClock) Step(d time.Duration) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.setTimeLocked(f.time.Add(d))\n}\n\n\/\/ Sets the time.\nfunc (f *FakeClock) SetTime(t time.Time) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.setTimeLocked(t)\n}\n\n\/\/ Actually changes the time and checks any waiters. f must be write-locked.\nfunc (f *FakeClock) setTimeLocked(t time.Time) {\n\tf.time = t\n\tnewWaiters := make([]*fakeClockWaiter, 0, len(f.waiters))\n\tfor i := range f.waiters {\n\t\tw := f.waiters[i]\n\t\tif !w.targetTime.After(t) {\n\n\t\t\tif w.skipIfBlocked {\n\t\t\t\tselect {\n\t\t\t\tcase w.destChan <- t:\n\t\t\t\t\tw.fired = true\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tw.destChan <- t\n\t\t\t\tw.fired = true\n\t\t\t}\n\n\t\t\tif w.stepInterval > 0 {\n\t\t\t\tfor !w.targetTime.After(t) {\n\t\t\t\t\tw.targetTime = w.targetTime.Add(w.stepInterval)\n\t\t\t\t}\n\t\t\t\tnewWaiters = append(newWaiters, w)\n\t\t\t}\n\n\t\t} else {\n\t\t\tnewWaiters = append(newWaiters, f.waiters[i])\n\t\t}\n\t}\n\tf.waiters = newWaiters\n}\n\n\/\/ Returns true if After has been called on f but not yet satisfied (so you can\n\/\/ write race-free tests).\nfunc (f *FakeClock) HasWaiters() bool {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\treturn len(f.waiters) > 0\n}\n\nfunc (f *FakeClock) Sleep(d time.Duration) {\n\tf.Step(d)\n}\n\n\/\/ IntervalClock implements clock.Clock, but each invocation of Now steps the clock forward the specified duration\ntype IntervalClock struct {\n\tTime     time.Time\n\tDuration time.Duration\n}\n\n\/\/ Now returns i's time.\nfunc (i *IntervalClock) Now() time.Time {\n\ti.Time = i.Time.Add(i.Duration)\n\treturn i.Time\n}\n\n\/\/ Since returns time since the time in i.\nfunc (i *IntervalClock) Since(ts time.Time) time.Duration {\n\treturn i.Time.Sub(ts)\n}\n\n\/\/ Unimplemented, will panic.\n\/\/ TODO: make interval clock use FakeClock so this can be implemented.\nfunc (*IntervalClock) After(d time.Duration) <-chan time.Time {\n\tpanic(\"IntervalClock doesn't implement After\")\n}\n\n\/\/ Unimplemented, will panic.\n\/\/ TODO: make interval clock use FakeClock so this can be implemented.\nfunc (*IntervalClock) NewTimer(d time.Duration) clock.Timer {\n\tpanic(\"IntervalClock doesn't implement NewTimer\")\n}\n\n\/\/ Unimplemented, will panic.\n\/\/ TODO: make interval clock use FakeClock so this can be implemented.\nfunc (*IntervalClock) Tick(d time.Duration) <-chan time.Time {\n\tpanic(\"IntervalClock doesn't implement Tick\")\n}\n\nfunc (*IntervalClock) Sleep(d time.Duration) {\n\tpanic(\"IntervalClock doesn't implement Sleep\")\n}\n\nvar _ = clock.Timer(&fakeTimer{})\n\n\/\/ fakeTimer implements clock.Timer based on a FakeClock.\ntype fakeTimer struct {\n\tfakeClock *FakeClock\n\twaiter    fakeClockWaiter\n}\n\n\/\/ C returns the channel that notifies when this timer has fired.\nfunc (f *fakeTimer) C() <-chan time.Time {\n\treturn f.waiter.destChan\n}\n\n\/\/ Stop stops the timer and returns true if the timer has not yet fired, or false otherwise.\nfunc (f *fakeTimer) Stop() bool {\n\tf.fakeClock.lock.Lock()\n\tdefer f.fakeClock.lock.Unlock()\n\n\tnewWaiters := make([]*fakeClockWaiter, 0, len(f.fakeClock.waiters))\n\tfor i := range f.fakeClock.waiters {\n\t\tw := f.fakeClock.waiters[i]\n\t\tif w != &f.waiter {\n\t\t\tnewWaiters = append(newWaiters, w)\n\t\t}\n\t}\n\n\tf.fakeClock.waiters = newWaiters\n\n\treturn !f.waiter.fired\n}\n\n\/\/ Reset resets the timer to the fake clock's \"now\" + d. It returns true if the timer has not yet\n\/\/ fired, or false otherwise.\nfunc (f *fakeTimer) Reset(d time.Duration) bool {\n\tf.fakeClock.lock.Lock()\n\tdefer f.fakeClock.lock.Unlock()\n\n\tactive := !f.waiter.fired\n\n\tf.waiter.fired = false\n\tf.waiter.targetTime = f.fakeClock.time.Add(d)\n\n\tvar isWaiting bool\n\tfor i := range f.fakeClock.waiters {\n\t\tw := f.fakeClock.waiters[i]\n\t\tif w == &f.waiter {\n\t\t\tisWaiting = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !isWaiting {\n\t\tf.fakeClock.waiters = append(f.fakeClock.waiters, &f.waiter)\n\t}\n\n\treturn active\n}\n<commit_msg>clock\/testing: improve doc comments<commit_after>\/*\nCopyright 2014 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage testing\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"k8s.io\/utils\/clock\"\n)\n\nvar (\n\t_ = clock.Clock(&FakeClock{})\n\t_ = clock.Clock(&IntervalClock{})\n)\n\n\/\/ FakeClock implements clock.Clock, but returns an arbitrary time.\ntype FakeClock struct {\n\tlock sync.RWMutex\n\ttime time.Time\n\n\t\/\/ waiters are waiting for the fake time to pass their specified time\n\twaiters []*fakeClockWaiter\n}\n\ntype fakeClockWaiter struct {\n\ttargetTime    time.Time\n\tstepInterval  time.Duration\n\tskipIfBlocked bool\n\tdestChan      chan time.Time\n\tfired         bool\n}\n\n\/\/ NewFakeClock constructs a fake clock set to the provided time.\nfunc NewFakeClock(t time.Time) *FakeClock {\n\treturn &FakeClock{\n\t\ttime: t,\n\t}\n}\n\n\/\/ Now returns f's time.\nfunc (f *FakeClock) Now() time.Time {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\treturn f.time\n}\n\n\/\/ Since returns time since the time in f.\nfunc (f *FakeClock) Since(ts time.Time) time.Duration {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\treturn f.time.Sub(ts)\n}\n\n\/\/ After is the fake version of time.After(d).\nfunc (f *FakeClock) After(d time.Duration) <-chan time.Time {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tstopTime := f.time.Add(d)\n\tch := make(chan time.Time, 1) \/\/ Don't block!\n\tf.waiters = append(f.waiters, &fakeClockWaiter{\n\t\ttargetTime: stopTime,\n\t\tdestChan:   ch,\n\t})\n\treturn ch\n}\n\n\/\/ NewTimer constructs a fake timer, akin to time.NewTimer(d).\nfunc (f *FakeClock) NewTimer(d time.Duration) clock.Timer {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tstopTime := f.time.Add(d)\n\tch := make(chan time.Time, 1) \/\/ Don't block!\n\ttimer := &fakeTimer{\n\t\tfakeClock: f,\n\t\twaiter: fakeClockWaiter{\n\t\t\ttargetTime: stopTime,\n\t\t\tdestChan:   ch,\n\t\t},\n\t}\n\tf.waiters = append(f.waiters, &timer.waiter)\n\treturn timer\n}\n\n\/\/ Tick constructs a fake ticker, akin to time.Tick\nfunc (f *FakeClock) Tick(d time.Duration) <-chan time.Time {\n\tif d <= 0 {\n\t\treturn nil\n\t}\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\ttickTime := f.time.Add(d)\n\tch := make(chan time.Time, 1) \/\/ hold one tick\n\tf.waiters = append(f.waiters, &fakeClockWaiter{\n\t\ttargetTime:    tickTime,\n\t\tstepInterval:  d,\n\t\tskipIfBlocked: true,\n\t\tdestChan:      ch,\n\t})\n\n\treturn ch\n}\n\n\/\/ Step moves the clock by Duration and notifies anyone that's called After,\n\/\/ Tick, or NewTimer.\nfunc (f *FakeClock) Step(d time.Duration) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.setTimeLocked(f.time.Add(d))\n}\n\n\/\/ SetTime sets the time.\nfunc (f *FakeClock) SetTime(t time.Time) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.setTimeLocked(t)\n}\n\n\/\/ Actually changes the time and checks any waiters. f must be write-locked.\nfunc (f *FakeClock) setTimeLocked(t time.Time) {\n\tf.time = t\n\tnewWaiters := make([]*fakeClockWaiter, 0, len(f.waiters))\n\tfor i := range f.waiters {\n\t\tw := f.waiters[i]\n\t\tif !w.targetTime.After(t) {\n\n\t\t\tif w.skipIfBlocked {\n\t\t\t\tselect {\n\t\t\t\tcase w.destChan <- t:\n\t\t\t\t\tw.fired = true\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tw.destChan <- t\n\t\t\t\tw.fired = true\n\t\t\t}\n\n\t\t\tif w.stepInterval > 0 {\n\t\t\t\tfor !w.targetTime.After(t) {\n\t\t\t\t\tw.targetTime = w.targetTime.Add(w.stepInterval)\n\t\t\t\t}\n\t\t\t\tnewWaiters = append(newWaiters, w)\n\t\t\t}\n\n\t\t} else {\n\t\t\tnewWaiters = append(newWaiters, f.waiters[i])\n\t\t}\n\t}\n\tf.waiters = newWaiters\n}\n\n\/\/ HasWaiters returns true if After has been called on f but not yet satisfied (so you can\n\/\/ write race-free tests).\nfunc (f *FakeClock) HasWaiters() bool {\n\tf.lock.RLock()\n\tdefer f.lock.RUnlock()\n\treturn len(f.waiters) > 0\n}\n\n\/\/ Sleep is akin to time.Sleep\nfunc (f *FakeClock) Sleep(d time.Duration) {\n\tf.Step(d)\n}\n\n\/\/ IntervalClock implements clock.Clock, but each invocation of Now steps the clock forward the specified duration\ntype IntervalClock struct {\n\tTime     time.Time\n\tDuration time.Duration\n}\n\n\/\/ Now returns i's time.\nfunc (i *IntervalClock) Now() time.Time {\n\ti.Time = i.Time.Add(i.Duration)\n\treturn i.Time\n}\n\n\/\/ Since returns time since the time in i.\nfunc (i *IntervalClock) Since(ts time.Time) time.Duration {\n\treturn i.Time.Sub(ts)\n}\n\n\/\/ After is unimplemented, will panic.\n\/\/ TODO: make interval clock use FakeClock so this can be implemented.\nfunc (*IntervalClock) After(d time.Duration) <-chan time.Time {\n\tpanic(\"IntervalClock doesn't implement After\")\n}\n\n\/\/ NewTimer is unimplemented, will panic.\n\/\/ TODO: make interval clock use FakeClock so this can be implemented.\nfunc (*IntervalClock) NewTimer(d time.Duration) clock.Timer {\n\tpanic(\"IntervalClock doesn't implement NewTimer\")\n}\n\n\/\/ Tick is unimplemented, will panic.\n\/\/ TODO: make interval clock use FakeClock so this can be implemented.\nfunc (*IntervalClock) Tick(d time.Duration) <-chan time.Time {\n\tpanic(\"IntervalClock doesn't implement Tick\")\n}\n\n\/\/ Sleep is unimplemented, will panic.\nfunc (*IntervalClock) Sleep(d time.Duration) {\n\tpanic(\"IntervalClock doesn't implement Sleep\")\n}\n\nvar _ = clock.Timer(&fakeTimer{})\n\n\/\/ fakeTimer implements clock.Timer based on a FakeClock.\ntype fakeTimer struct {\n\tfakeClock *FakeClock\n\twaiter    fakeClockWaiter\n}\n\n\/\/ C returns the channel that notifies when this timer has fired.\nfunc (f *fakeTimer) C() <-chan time.Time {\n\treturn f.waiter.destChan\n}\n\n\/\/ Stop stops the timer and returns true if the timer has not yet fired, or false otherwise.\nfunc (f *fakeTimer) Stop() bool {\n\tf.fakeClock.lock.Lock()\n\tdefer f.fakeClock.lock.Unlock()\n\n\tnewWaiters := make([]*fakeClockWaiter, 0, len(f.fakeClock.waiters))\n\tfor i := range f.fakeClock.waiters {\n\t\tw := f.fakeClock.waiters[i]\n\t\tif w != &f.waiter {\n\t\t\tnewWaiters = append(newWaiters, w)\n\t\t}\n\t}\n\n\tf.fakeClock.waiters = newWaiters\n\n\treturn !f.waiter.fired\n}\n\n\/\/ Reset resets the timer to the fake clock's \"now\" + d. It returns true if the timer has not yet\n\/\/ fired, or false otherwise.\nfunc (f *fakeTimer) Reset(d time.Duration) bool {\n\tf.fakeClock.lock.Lock()\n\tdefer f.fakeClock.lock.Unlock()\n\n\tactive := !f.waiter.fired\n\n\tf.waiter.fired = false\n\tf.waiter.targetTime = f.fakeClock.time.Add(d)\n\n\tvar isWaiting bool\n\tfor i := range f.fakeClock.waiters {\n\t\tw := f.fakeClock.waiters[i]\n\t\tif w == &f.waiter {\n\t\t\tisWaiting = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !isWaiting {\n\t\tf.fakeClock.waiters = append(f.fakeClock.waiters, &f.waiter)\n\t}\n\n\treturn active\n}\n<|endoftext|>"}
{"text":"<commit_before>package js\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/robertkrimen\/otto\"\n\t\"strconv\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\ntype JSAPI struct {\n\tvu *VU\n}\n\nfunc (a JSAPI) Sleep(secs float64) {\n\ttime.Sleep(time.Duration(secs * float64(time.Second)))\n}\n\nfunc (a JSAPI) Log(level int, msg string, args []otto.Value) {\n\tfields := make(log.Fields, len(args))\n\tfor i, arg := range args {\n\t\tif arg.IsObject() {\n\t\t\tobj := arg.Object()\n\t\t\tfor _, key := range obj.Keys() {\n\t\t\t\tv, err := obj.Get(key)\n\t\t\t\tif err != nil {\n\t\t\t\t\tthrow(a.vu.vm, err)\n\t\t\t\t}\n\t\t\t\tfields[key] = v.String()\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tfields[\"arg\"+strconv.FormatInt(int64(i), 10)] = arg.String()\n\t}\n\n\tentry := log.WithFields(fields)\n\tswitch level {\n\tcase 0:\n\t\tentry.Debug(msg)\n\tcase 1:\n\t\tentry.Info(msg)\n\tcase 2:\n\t\tentry.Warn(msg)\n\tcase 3:\n\t\tentry.Error(msg)\n\t}\n}\n\nfunc (a JSAPI) DoGroup(call otto.FunctionCall) otto.Value {\n\tname := call.Argument(0).String()\n\tgroup, ok := a.vu.group.Group(name, &(a.vu.runner.groupIDCounter))\n\tif !ok {\n\t\ta.vu.runner.groupsMutex.Lock()\n\t\ta.vu.runner.Groups = append(a.vu.runner.Groups, group)\n\t\ta.vu.runner.groupsMutex.Unlock()\n\t}\n\ta.vu.group = group\n\tdefer func() { a.vu.group = group.Parent }()\n\n\tfn := call.Argument(1)\n\tif !fn.IsFunction() {\n\t\tpanic(call.Otto.MakeSyntaxError(\"fn must be a function\"))\n\t}\n\n\tval, err := fn.Call(call.This)\n\tif err != nil {\n\t\tthrow(call.Otto, err)\n\t}\n\n\tif val.IsUndefined() {\n\t\treturn otto.TrueValue()\n\t}\n\treturn val\n}\n\nfunc (a JSAPI) DoCheck(call otto.FunctionCall) otto.Value {\n\tif len(call.ArgumentList) < 2 {\n\t\treturn otto.UndefinedValue()\n\t}\n\n\tsuccess := true\n\targ0 := call.Argument(0)\n\tfor _, v := range call.ArgumentList[1:] {\n\t\tobj := v.Object()\n\t\tif obj == nil {\n\t\t\tpanic(call.Otto.MakeTypeError(\"checks must be objects\"))\n\t\t}\n\t\tfor _, name := range obj.Keys() {\n\t\t\tval, err := obj.Get(name)\n\t\t\tif err != nil {\n\t\t\t\tthrow(call.Otto, err)\n\t\t\t}\n\n\t\t\tresult, err := Check(val, arg0)\n\t\t\tif err != nil {\n\t\t\t\tthrow(call.Otto, err)\n\t\t\t}\n\n\t\t\tcheck, ok := a.vu.group.Check(name, &(a.vu.runner.checkIDCounter))\n\t\t\tif !ok {\n\t\t\t\ta.vu.runner.checksMutex.Lock()\n\t\t\t\ta.vu.runner.Checks = append(a.vu.runner.Checks, check)\n\t\t\t\ta.vu.runner.checksMutex.Unlock()\n\t\t\t}\n\n\t\t\tif result {\n\t\t\t\tatomic.AddInt64(&(check.Passes), 1)\n\t\t\t} else {\n\t\t\t\tatomic.AddInt64(&(check.Fails), 1)\n\t\t\t\tsuccess = false\n\t\t\t}\n\t\t}\n\t}\n\n\tif !success {\n\t\ta.vu.Taint = true\n\t\treturn otto.FalseValue()\n\t}\n\treturn otto.TrueValue()\n}\n\nfunc (a JSAPI) Taint() {\n\ta.vu.Taint = true\n}\n\nfunc (a JSAPI) ElapsedMs() int64 {\n\treturn int64(time.Since(a.vu.started) * time.Millisecond)\n}\n<commit_msg>[fix] this should be a float<commit_after>package js\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/robertkrimen\/otto\"\n\t\"strconv\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\ntype JSAPI struct {\n\tvu *VU\n}\n\nfunc (a JSAPI) Sleep(secs float64) {\n\ttime.Sleep(time.Duration(secs * float64(time.Second)))\n}\n\nfunc (a JSAPI) Log(level int, msg string, args []otto.Value) {\n\tfields := make(log.Fields, len(args))\n\tfor i, arg := range args {\n\t\tif arg.IsObject() {\n\t\t\tobj := arg.Object()\n\t\t\tfor _, key := range obj.Keys() {\n\t\t\t\tv, err := obj.Get(key)\n\t\t\t\tif err != nil {\n\t\t\t\t\tthrow(a.vu.vm, err)\n\t\t\t\t}\n\t\t\t\tfields[key] = v.String()\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tfields[\"arg\"+strconv.FormatInt(int64(i), 10)] = arg.String()\n\t}\n\n\tentry := log.WithFields(fields)\n\tswitch level {\n\tcase 0:\n\t\tentry.Debug(msg)\n\tcase 1:\n\t\tentry.Info(msg)\n\tcase 2:\n\t\tentry.Warn(msg)\n\tcase 3:\n\t\tentry.Error(msg)\n\t}\n}\n\nfunc (a JSAPI) DoGroup(call otto.FunctionCall) otto.Value {\n\tname := call.Argument(0).String()\n\tgroup, ok := a.vu.group.Group(name, &(a.vu.runner.groupIDCounter))\n\tif !ok {\n\t\ta.vu.runner.groupsMutex.Lock()\n\t\ta.vu.runner.Groups = append(a.vu.runner.Groups, group)\n\t\ta.vu.runner.groupsMutex.Unlock()\n\t}\n\ta.vu.group = group\n\tdefer func() { a.vu.group = group.Parent }()\n\n\tfn := call.Argument(1)\n\tif !fn.IsFunction() {\n\t\tpanic(call.Otto.MakeSyntaxError(\"fn must be a function\"))\n\t}\n\n\tval, err := fn.Call(call.This)\n\tif err != nil {\n\t\tthrow(call.Otto, err)\n\t}\n\n\tif val.IsUndefined() {\n\t\treturn otto.TrueValue()\n\t}\n\treturn val\n}\n\nfunc (a JSAPI) DoCheck(call otto.FunctionCall) otto.Value {\n\tif len(call.ArgumentList) < 2 {\n\t\treturn otto.UndefinedValue()\n\t}\n\n\tsuccess := true\n\targ0 := call.Argument(0)\n\tfor _, v := range call.ArgumentList[1:] {\n\t\tobj := v.Object()\n\t\tif obj == nil {\n\t\t\tpanic(call.Otto.MakeTypeError(\"checks must be objects\"))\n\t\t}\n\t\tfor _, name := range obj.Keys() {\n\t\t\tval, err := obj.Get(name)\n\t\t\tif err != nil {\n\t\t\t\tthrow(call.Otto, err)\n\t\t\t}\n\n\t\t\tresult, err := Check(val, arg0)\n\t\t\tif err != nil {\n\t\t\t\tthrow(call.Otto, err)\n\t\t\t}\n\n\t\t\tcheck, ok := a.vu.group.Check(name, &(a.vu.runner.checkIDCounter))\n\t\t\tif !ok {\n\t\t\t\ta.vu.runner.checksMutex.Lock()\n\t\t\t\ta.vu.runner.Checks = append(a.vu.runner.Checks, check)\n\t\t\t\ta.vu.runner.checksMutex.Unlock()\n\t\t\t}\n\n\t\t\tif result {\n\t\t\t\tatomic.AddInt64(&(check.Passes), 1)\n\t\t\t} else {\n\t\t\t\tatomic.AddInt64(&(check.Fails), 1)\n\t\t\t\tsuccess = false\n\t\t\t}\n\t\t}\n\t}\n\n\tif !success {\n\t\ta.vu.Taint = true\n\t\treturn otto.FalseValue()\n\t}\n\treturn otto.TrueValue()\n}\n\nfunc (a JSAPI) Taint() {\n\ta.vu.Taint = true\n}\n\nfunc (a JSAPI) ElapsedMs() float64 {\n\treturn float64(time.Since(a.vu.started)) * float64(time.Millisecond)\n}\n<|endoftext|>"}
{"text":"<commit_before>package clog\n\nimport (\n  \"fmt\"\n  \"github.com\/wsxiaoys\/terminal\/color\"\n  \"io\"\n  \"log\"\n  \"os\"\n  \/\/\"sync\"\n)\n\nvar std = log.New(os.Stderr, \"\", log.LstdFlags)\n\n\/\/var std_mu synx.Mutex\n\n\/\/ SetOutput sets the output destination for the standard logger.\nfunc SetOutput(w io.Writer) {\n  \/\/std_mu.Lock()\n  \/\/defer std_mu.Unlock()\n  \/\/std.out = w\n  std = log.New(w, \"\", log.LstdFlags)\n}\n\n\/\/ Flags returns the output flags for the standard logger.\nfunc Flags() int {\n  return std.Flags()\n}\n\n\/\/ SetFlags sets the output flags for the standard logger.\nfunc SetFlags(flag int) {\n  std.SetFlags(flag)\n}\n\n\/\/ Prefix returns the output prefix for the standard logger.\nfunc Prefix() string {\n  return std.Prefix()\n}\n\n\/\/ SetPrefix sets the output prefix for the standard logger.\nfunc SetPrefix(prefix string) {\n  std.SetPrefix(prefix)\n}\n\n\/\/ These functions write to the standard logger.\n\n\/\/ Print calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Print.\nfunc Print(v ...interface{}) {\n  std.Output(2, color.Sprint(v...))\n}\n\n\/\/ Printf calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Printf.\nfunc Printf(format string, v ...interface{}) {\n  std.Output(2, color.Sprintf(format, v...))\n}\n\n\/\/ Println calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Println.\nfunc Println(v ...interface{}) {\n  std.Output(2, color.Sprint(fmt.Sprintln(v...)))\n}\n\n\/\/ Fatal is equivalent to Print() followed by a call to os.Exit(1).\nfunc Fatal(v ...interface{}) {\n  std.Output(2, color.Sprint(v...))\n  os.Exit(1)\n}\n\n\/\/ Fatalf is equivalent to Printf() followed by a call to os.Exit(1).\nfunc Fatalf(format string, v ...interface{}) {\n  std.Output(2, color.Sprintf(format, v...))\n  os.Exit(1)\n}\n\n\/\/ Fatalln is equivalent to Println() followed by a call to os.Exit(1).\nfunc Fatalln(v ...interface{}) {\n  std.Output(2, color.Sprint(fmt.Sprintln(v...)))\n  os.Exit(1)\n}\n\n\/\/ Panic is equivalent to Print() followed by a call to panic().\nfunc Panic(v ...interface{}) {\n  s := color.Sprint(v...)\n  std.Output(2, s)\n  panic(s)\n}\n\n\/\/ Panicf is equivalent to Printf() followed by a call to panic().\nfunc Panicf(format string, v ...interface{}) {\n  s := color.Sprintf(format, v...)\n  std.Output(2, s)\n  panic(s)\n}\n\n\/\/ Panicln is equivalent to Println() followed by a call to panic().\nfunc Panicln(v ...interface{}) {\n  s := color.Sprint(fmt.Sprintln(v...))\n  std.Output(2, s)\n  panic(s)\n}\n<commit_msg>Added log.Lshortfile to the flags.<commit_after>package clog\n\nimport (\n  \"fmt\"\n  \"github.com\/wsxiaoys\/terminal\/color\"\n  \"io\"\n  \"log\"\n  \"os\"\n  \/\/\"sync\"\n)\n\nvar std = log.New(os.Stderr, \"\", log.LstdFlags|log.Lshortfile)\n\n\/\/var std_mu synx.Mutex\n\n\/\/ SetOutput sets the output destination for the standard logger.\nfunc SetOutput(w io.Writer) {\n  \/\/std_mu.Lock()\n  \/\/defer std_mu.Unlock()\n  \/\/std.out = w\n  std = log.New(w, \"\", log.LstdFlags|log.Lshortfile)\n}\n\n\/\/ Flags returns the output flags for the standard logger.\nfunc Flags() int {\n  return std.Flags()\n}\n\n\/\/ SetFlags sets the output flags for the standard logger.\nfunc SetFlags(flag int) {\n  std.SetFlags(flag)\n}\n\n\/\/ Prefix returns the output prefix for the standard logger.\nfunc Prefix() string {\n  return std.Prefix()\n}\n\n\/\/ SetPrefix sets the output prefix for the standard logger.\nfunc SetPrefix(prefix string) {\n  std.SetPrefix(prefix)\n}\n\n\/\/ These functions write to the standard logger.\n\n\/\/ Print calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Print.\nfunc Print(v ...interface{}) {\n  std.Output(2, color.Sprint(v...))\n}\n\n\/\/ Printf calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Printf.\nfunc Printf(format string, v ...interface{}) {\n  std.Output(2, color.Sprintf(format, v...))\n}\n\n\/\/ Println calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Println.\nfunc Println(v ...interface{}) {\n  std.Output(2, color.Sprint(fmt.Sprintln(v...)))\n}\n\n\/\/ Fatal is equivalent to Print() followed by a call to os.Exit(1).\nfunc Fatal(v ...interface{}) {\n  std.Output(2, color.Sprint(v...))\n  os.Exit(1)\n}\n\n\/\/ Fatalf is equivalent to Printf() followed by a call to os.Exit(1).\nfunc Fatalf(format string, v ...interface{}) {\n  std.Output(2, color.Sprintf(format, v...))\n  os.Exit(1)\n}\n\n\/\/ Fatalln is equivalent to Println() followed by a call to os.Exit(1).\nfunc Fatalln(v ...interface{}) {\n  std.Output(2, color.Sprint(fmt.Sprintln(v...)))\n  os.Exit(1)\n}\n\n\/\/ Panic is equivalent to Print() followed by a call to panic().\nfunc Panic(v ...interface{}) {\n  s := color.Sprint(v...)\n  std.Output(2, s)\n  panic(s)\n}\n\n\/\/ Panicf is equivalent to Printf() followed by a call to panic().\nfunc Panicf(format string, v ...interface{}) {\n  s := color.Sprintf(format, v...)\n  std.Output(2, s)\n  panic(s)\n}\n\n\/\/ Panicln is equivalent to Println() followed by a call to panic().\nfunc Panicln(v ...interface{}) {\n  s := color.Sprint(fmt.Sprintln(v...))\n  std.Output(2, s)\n  panic(s)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The Jetstack cert-manager contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage app\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com\/go-logr\/logr\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n\t\"golang.org\/x\/sync\/errgroup\"\n\t_ \"k8s.io\/client-go\/plugin\/pkg\/client\/auth\"\n\tctrl \"sigs.k8s.io\/controller-runtime\"\n\n\t\"github.com\/jetstack\/cert-manager\/pkg\/api\"\n\t\"github.com\/jetstack\/cert-manager\/pkg\/controller\/cainjector\"\n\tlogf \"github.com\/jetstack\/cert-manager\/pkg\/logs\"\n\t\"github.com\/jetstack\/cert-manager\/pkg\/util\"\n)\n\ntype InjectorControllerOptions struct {\n\tNamespace               string\n\tLeaderElect             bool\n\tLeaderElectionNamespace string\n\n\tStdOut io.Writer\n\tStdErr io.Writer\n\n\t\/\/ logger to be used by this controller\n\tlog logr.Logger\n}\n\nfunc (o *InjectorControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(&o.Namespace, \"namespace\", \"\", \"\"+\n\t\t\"If set, this limits the scope of cainjector to a single namespace. \"+\n\t\t\"If set, cainjector will not update resources with certificates outside of the \"+\n\t\t\"configured namespace.\")\n\tfs.BoolVar(&o.LeaderElect, \"leader-elect\", true, \"\"+\n\t\t\"If true, cainjector will perform leader election between instances to ensure no more \"+\n\t\t\"than one instance of cainjector operates at a time\")\n\tfs.StringVar(&o.LeaderElectionNamespace, \"leader-election-namespace\", \"\", \"\"+\n\t\t\"Namespace used to perform leader election (defaults to controller's namespace). \"+\n\t\t\"Only used if leader election is enabled\")\n}\n\nfunc NewInjectorControllerOptions(out, errOut io.Writer) *InjectorControllerOptions {\n\to := &InjectorControllerOptions{\n\t\tStdOut: out,\n\t\tStdErr: errOut,\n\t}\n\n\treturn o\n}\n\n\/\/ NewCommandStartInjectorController is a CLI handler for starting cert-manager\nfunc NewCommandStartInjectorController(ctx context.Context, out, errOut io.Writer) *cobra.Command {\n\to := NewInjectorControllerOptions(out, errOut)\n\n\tcmd := &cobra.Command{\n\t\tUse:   \"ca-injector\",\n\t\tShort: fmt.Sprintf(\"CA Injection Controller for Kubernetes (%s) (%s)\", util.AppVersion, util.AppGitCommit),\n\t\tLong: `\ncert-manager CA injector is a Kubernetes addon to automate the injection of CA data into\nwebhooks and APIServices from cert-manager certificates.\n\nIt will ensure that annotated webhooks and API services always have the correct\nCA data from the referenced certificates, which can then be used to serve API\nservers and webhook servers.`,\n\n\t\t\/\/ TODO: Refactor this function from this package\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\to.log = logf.Log.WithName(\"ca-injector\")\n\n\t\t\tlogf.V(logf.InfoLevel).InfoS(\"starting\", \"version\", util.AppVersion, \"revision\", util.AppGitCommit)\n\t\t\treturn o.RunInjectorController(ctx)\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\to.AddFlags(flags)\n\n\treturn cmd\n}\n\nfunc (o InjectorControllerOptions) RunInjectorController(ctx context.Context) error {\n\tmgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{\n\t\tScheme:                  api.Scheme,\n\t\tNamespace:               o.Namespace,\n\t\tLeaderElection:          o.LeaderElect,\n\t\tLeaderElectionNamespace: o.LeaderElectionNamespace,\n\t\tLeaderElectionID:        \"cert-manager-cainjector-leader-election\",\n\t\tMetricsBindAddress:      \"0\",\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating manager: %v\", err)\n\t}\n\n\tg, gctx := errgroup.WithContext(ctx)\n\n\tg.Go(func() (err error) {\n\t\tdefer func() {\n\t\t\to.log.Error(err, \"manager goroutine exited\")\n\t\t}()\n\n\t\tif err = mgr.Start(gctx.Done()); err != nil {\n\t\t\treturn fmt.Errorf(\"error running manager: %v\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\t<-mgr.Elected()\n\n\tg.Go(func() (err error) {\n\t\tfor {\n\t\t\terr = cainjector.RegisterCertificateBased(gctx, mgr)\n\t\t\tif err == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\to.log.Error(err, \"Error registering certificate based controllers. Retrying after 5 seconds.\")\n\t\t\tselect {\n\t\t\tcase <-time.After(time.Second * 5):\n\t\t\tcase <-gctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t})\n\n\tg.Go(func() (err error) {\n\t\tif err = cainjector.RegisterSecretBased(gctx, mgr); err != nil {\n\t\t\treturn fmt.Errorf(\"error registering secret controller: %v\", err)\n\t\t}\n\t\treturn\n\t})\n\n\treturn g.Wait()\n}\n<commit_msg>Avoid launching controller goroutines during shutdown of unelected<commit_after>\/*\nCopyright 2019 The Jetstack cert-manager contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage app\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com\/go-logr\/logr\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n\t\"golang.org\/x\/sync\/errgroup\"\n\t_ \"k8s.io\/client-go\/plugin\/pkg\/client\/auth\"\n\tctrl \"sigs.k8s.io\/controller-runtime\"\n\n\t\"github.com\/jetstack\/cert-manager\/pkg\/api\"\n\t\"github.com\/jetstack\/cert-manager\/pkg\/controller\/cainjector\"\n\tlogf \"github.com\/jetstack\/cert-manager\/pkg\/logs\"\n\t\"github.com\/jetstack\/cert-manager\/pkg\/util\"\n)\n\ntype InjectorControllerOptions struct {\n\tNamespace               string\n\tLeaderElect             bool\n\tLeaderElectionNamespace string\n\n\tStdOut io.Writer\n\tStdErr io.Writer\n\n\t\/\/ logger to be used by this controller\n\tlog logr.Logger\n}\n\nfunc (o *InjectorControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(&o.Namespace, \"namespace\", \"\", \"\"+\n\t\t\"If set, this limits the scope of cainjector to a single namespace. \"+\n\t\t\"If set, cainjector will not update resources with certificates outside of the \"+\n\t\t\"configured namespace.\")\n\tfs.BoolVar(&o.LeaderElect, \"leader-elect\", true, \"\"+\n\t\t\"If true, cainjector will perform leader election between instances to ensure no more \"+\n\t\t\"than one instance of cainjector operates at a time\")\n\tfs.StringVar(&o.LeaderElectionNamespace, \"leader-election-namespace\", \"\", \"\"+\n\t\t\"Namespace used to perform leader election (defaults to controller's namespace). \"+\n\t\t\"Only used if leader election is enabled\")\n}\n\nfunc NewInjectorControllerOptions(out, errOut io.Writer) *InjectorControllerOptions {\n\to := &InjectorControllerOptions{\n\t\tStdOut: out,\n\t\tStdErr: errOut,\n\t}\n\n\treturn o\n}\n\n\/\/ NewCommandStartInjectorController is a CLI handler for starting cert-manager\nfunc NewCommandStartInjectorController(ctx context.Context, out, errOut io.Writer) *cobra.Command {\n\to := NewInjectorControllerOptions(out, errOut)\n\n\tcmd := &cobra.Command{\n\t\tUse:   \"ca-injector\",\n\t\tShort: fmt.Sprintf(\"CA Injection Controller for Kubernetes (%s) (%s)\", util.AppVersion, util.AppGitCommit),\n\t\tLong: `\ncert-manager CA injector is a Kubernetes addon to automate the injection of CA data into\nwebhooks and APIServices from cert-manager certificates.\n\nIt will ensure that annotated webhooks and API services always have the correct\nCA data from the referenced certificates, which can then be used to serve API\nservers and webhook servers.`,\n\n\t\t\/\/ TODO: Refactor this function from this package\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\to.log = logf.Log.WithName(\"ca-injector\")\n\n\t\t\tlogf.V(logf.InfoLevel).InfoS(\"starting\", \"version\", util.AppVersion, \"revision\", util.AppGitCommit)\n\t\t\treturn o.RunInjectorController(ctx)\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\to.AddFlags(flags)\n\n\treturn cmd\n}\n\nfunc (o InjectorControllerOptions) RunInjectorController(ctx context.Context) error {\n\tmgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{\n\t\tScheme:                  api.Scheme,\n\t\tNamespace:               o.Namespace,\n\t\tLeaderElection:          o.LeaderElect,\n\t\tLeaderElectionNamespace: o.LeaderElectionNamespace,\n\t\tLeaderElectionID:        \"cert-manager-cainjector-leader-election\",\n\t\tMetricsBindAddress:      \"0\",\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error creating manager: %v\", err)\n\t}\n\n\tg, gctx := errgroup.WithContext(ctx)\n\n\tg.Go(func() (err error) {\n\t\tdefer func() {\n\t\t\to.log.Error(err, \"manager goroutine exited\")\n\t\t}()\n\n\t\tif err = mgr.Start(gctx.Done()); err != nil {\n\t\t\treturn fmt.Errorf(\"error running manager: %v\", err)\n\t\t}\n\t\treturn nil\n\t})\n\n\t\/\/ Don't launch the controllers unless we have been elected leader\n\t<-mgr.Elected()\n\n\t\/\/ Exit early if the Elected channel gets closed because we are shutting down.\n\tselect {\n\tcase <-gctx.Done():\n\t\treturn g.Wait()\n\tdefault:\n\t}\n\n\tg.Go(func() (err error) {\n\t\tfor {\n\t\t\terr = cainjector.RegisterCertificateBased(gctx, mgr)\n\t\t\tif err == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\to.log.Error(err, \"Error registering certificate based controllers. Retrying after 5 seconds.\")\n\t\t\tselect {\n\t\t\tcase <-time.After(time.Second * 5):\n\t\t\tcase <-gctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t})\n\n\tg.Go(func() (err error) {\n\t\tif err = cainjector.RegisterSecretBased(gctx, mgr); err != nil {\n\t\t\treturn fmt.Errorf(\"error registering secret controller: %v\", err)\n\t\t}\n\t\treturn\n\t})\n\n\treturn g.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>package control\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/rancher\/os\/cmd\/cloudinitexecute\"\n\t\"github.com\/rancher\/os\/compose\"\n\t\"github.com\/rancher\/os\/config\"\n\t\"github.com\/rancher\/os\/config\/cmdline\"\n\t\"github.com\/rancher\/os\/log\"\n\t\"github.com\/rancher\/os\/util\"\n)\n\nconst (\n\tconsoleDone = \"\/run\/console-done\"\n\tdockerHome  = \"\/home\/docker\"\n\tgettyCmd    = \"\/sbin\/agetty\"\n\trancherHome = \"\/home\/rancher\"\n\tstartScript = \"\/opt\/rancher\/bin\/start.sh\"\n)\n\ntype symlink struct {\n\toldname, newname string\n}\n\nfunc ConsoleInitMain() {\n\tif err := consoleInitFunc(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc consoleInitAction(c *cli.Context) error {\n\treturn consoleInitFunc()\n}\n\nfunc createHomeDir(homedir string, uid, gid int) {\n\tif _, err := os.Stat(homedir); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(homedir, 0755); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\tif err := os.Chown(homedir, uid, gid); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n}\n\nfunc consoleInitFunc() error {\n\tcfg := config.LoadConfig()\n\n\t\/\/ Now that we're booted, stop writing debug messages to the console\n\tcmd := exec.Command(\"sudo\", \"dmesg\", \"--console-off\")\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tcreateHomeDir(rancherHome, 1100, 1100)\n\tcreateHomeDir(dockerHome, 1101, 1101)\n\n\tpassword := cmdline.GetCmdline(\"rancher.password\")\n\tif password != \"\" {\n\t\tcmd := exec.Command(\"chpasswd\")\n\t\tcmd.Stdin = strings.NewReader(fmt.Sprint(\"rancher:\", password))\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\n\t\tcmd = exec.Command(\"bash\", \"-c\", `sed -E -i 's\/(rancher:.*:).*(:.*:.*:.*:.*:.*:.*)$\/\\1\\2\/' \/etc\/shadow`)\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n\n\tif err := setupSSH(cfg); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tif err := writeRespawn(\"rancher\", cfg.Rancher.SSH.Daemon, false); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tif err := modifySshdConfig(cfg); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tp, err := compose.GetProject(cfg, false, true)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\t\/\/ check the multi engine service & generate the multi engine script\n\tfor _, key := range p.ServiceConfigs.Keys() {\n\t\tserviceConfig, ok := p.ServiceConfigs.Get(key)\n\t\tif !ok {\n\t\t\tlog.Errorf(\"Failed to get service config from the project\")\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := serviceConfig.Labels[config.UserDockerLabel]; ok {\n\t\t\terr = util.GenerateDindEngineScript(serviceConfig.Labels[config.UserDockerLabel])\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed to generate engine script: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, link := range []symlink{\n\t\t{\"\/var\/lib\/rancher\/engine\/docker\", \"\/usr\/bin\/docker\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/docker-init\", \"\/usr\/bin\/docker-init\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/docker-containerd\", \"\/usr\/bin\/docker-containerd\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/docker-containerd-ctr\", \"\/usr\/bin\/docker-containerd-ctr\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/docker-containerd-shim\", \"\/usr\/bin\/docker-containerd-shim\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/dockerd\", \"\/usr\/bin\/dockerd\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/docker-proxy\", \"\/usr\/bin\/docker-proxy\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/docker-runc\", \"\/usr\/bin\/docker-runc\"},\n\t\t{\"\/usr\/share\/ros\/os-release\", \"\/usr\/lib\/os-release\"},\n\t\t{\"\/usr\/share\/ros\/os-release\", \"\/etc\/os-release\"},\n\t} {\n\t\tsyscall.Unlink(link.newname)\n\t\tif err := os.Symlink(link.oldname, link.newname); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n\n\t\/\/ font backslashes need to be escaped for when issue is output! (but not the others..)\n\tif err := ioutil.WriteFile(\"\/etc\/issue\", []byte(config.Banner), 0644); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\t\/\/ write out a profile.d file for the proxy settings.\n\t\/\/ maybe write these on the host and bindmount into everywhere?\n\tproxyLines := []string{}\n\tfor _, k := range []string{\"http_proxy\", \"HTTP_PROXY\", \"https_proxy\", \"HTTPS_PROXY\", \"no_proxy\", \"NO_PROXY\"} {\n\t\tif v, ok := cfg.Rancher.Environment[k]; ok {\n\t\t\tproxyLines = append(proxyLines, fmt.Sprintf(\"export %s=%s\", k, v))\n\t\t}\n\t}\n\n\tif len(proxyLines) > 0 {\n\t\tproxyString := strings.Join(proxyLines, \"\\n\")\n\t\tproxyString = fmt.Sprintf(\"#!\/bin\/sh\\n%s\\n\", proxyString)\n\t\tif err := ioutil.WriteFile(\"\/etc\/profile.d\/proxy.sh\", []byte(proxyString), 0755); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n\n\t\/\/ write out a profile.d file for the PATH settings.\n\tpathLines := []string{}\n\tfor _, k := range []string{\"PATH\", \"path\"} {\n\t\tif v, ok := cfg.Rancher.Environment[k]; ok {\n\t\t\tfor _, p := range strings.Split(v, \",\") {\n\t\t\t\tpathLines = append(pathLines, fmt.Sprintf(\"export PATH=$PATH:%s\", strings.TrimSpace(p)))\n\t\t\t}\n\t\t}\n\t}\n\tif len(pathLines) > 0 {\n\t\tpathString := strings.Join(pathLines, \"\\n\")\n\t\tpathString = fmt.Sprintf(\"#!\/bin\/sh\\n%s\\n\", pathString)\n\t\tif err := ioutil.WriteFile(\"\/etc\/profile.d\/path.sh\", []byte(pathString), 0755); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n\n\tcmd = exec.Command(\"bash\", \"-c\", `echo $(\/sbin\/ifconfig | grep -B1 \"inet addr\" |awk '{ if ( $1 == \"inet\" ) { print $2 } else if ( $2 == \"Link\" ) { printf \"%s:\" ,$1 } }' |awk -F: '{ print $1 \": \" $3}') >> \/etc\/issue`)\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tcloudinitexecute.ApplyConsole(cfg)\n\n\tif err := util.RunScript(config.CloudConfigScriptFile); err != nil {\n\t\tlog.Error(err)\n\t}\n\tif err := util.RunScript(startScript); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tif err := ioutil.WriteFile(consoleDone, []byte(CurrentConsole()), 0644); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tif err := util.RunScript(\"\/etc\/rc.local\"); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tos.Setenv(\"TERM\", \"linux\")\n\n\trespawnBinPath, err := exec.LookPath(\"respawn\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn syscall.Exec(respawnBinPath, []string{\"respawn\", \"-f\", \"\/etc\/respawn.conf\"}, os.Environ())\n}\n\nfunc generateRespawnConf(cmdline, user string, sshd, recovery bool) string {\n\tvar respawnConf bytes.Buffer\n\n\tautologinBin := \"\/usr\/bin\/autologin\"\n\tif recovery {\n\t\tautologinBin = \"\/usr\/bin\/recovery\"\n\t}\n\n\tfor i := 1; i < 7; i++ {\n\t\ttty := fmt.Sprintf(\"tty%d\", i)\n\n\t\trespawnConf.WriteString(gettyCmd)\n\t\tif strings.Contains(cmdline, fmt.Sprintf(\"rancher.autologin=%s\", tty)) {\n\t\t\trespawnConf.WriteString(fmt.Sprintf(\" -n -l %s -o %s:tty%d\", autologinBin, user, i))\n\t\t}\n\t\trespawnConf.WriteString(fmt.Sprintf(\" --noclear %s linux\\n\", tty))\n\t}\n\n\tfor _, tty := range []string{\"ttyS0\", \"ttyS1\", \"ttyS2\", \"ttyS3\", \"ttyAMA0\"} {\n\t\tif !strings.Contains(cmdline, fmt.Sprintf(\"console=%s\", tty)) {\n\t\t\tcontinue\n\t\t}\n\n\t\trespawnConf.WriteString(gettyCmd)\n\t\tif strings.Contains(cmdline, fmt.Sprintf(\"rancher.autologin=%s\", tty)) {\n\t\t\trespawnConf.WriteString(fmt.Sprintf(\" -n -l %s -o %s:%s\", autologinBin, user, tty))\n\t\t}\n\t\trespawnConf.WriteString(fmt.Sprintf(\" %s\\n\", tty))\n\t}\n\n\tif sshd {\n\t\trespawnConf.WriteString(\"\/usr\/sbin\/sshd -D\")\n\t}\n\n\treturn respawnConf.String()\n}\n\nfunc writeRespawn(user string, sshd, recovery bool) error {\n\tcmdline, err := ioutil.ReadFile(\"\/proc\/cmdline\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trespawn := generateRespawnConf(string(cmdline), user, sshd, recovery)\n\n\tfiles, err := ioutil.ReadDir(\"\/etc\/respawn.conf.d\")\n\tif err == nil {\n\t\tfor _, f := range files {\n\t\t\tp := path.Join(\"\/etc\/respawn.conf.d\", f.Name())\n\t\t\tcontent, err := ioutil.ReadFile(p)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed to read %s: %v\", p, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trespawn += fmt.Sprintf(\"\\n%s\", string(content))\n\t\t}\n\t} else if !os.IsNotExist(err) {\n\t\tlog.Error(err)\n\t}\n\n\treturn ioutil.WriteFile(\"\/etc\/respawn.conf\", []byte(respawn), 0644)\n}\n\nfunc modifySshdConfig(cfg *config.CloudConfig) error {\n\tsshdConfig, err := ioutil.ReadFile(\"\/etc\/ssh\/sshd_config\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tsshdConfigString := string(sshdConfig)\n\n\tmodifiedLines := []string{\n\t\t\"UseDNS no\",\n\t\t\"PermitRootLogin no\",\n\t\t\"ServerKeyBits 2048\",\n\t\t\"AllowGroups docker\",\n\t}\n\n\tif cfg.Rancher.SSH.Port > 0 && cfg.Rancher.SSH.Port < 65355 {\n\t\tmodifiedLines = append(modifiedLines, fmt.Sprintf(\"Port %d\", cfg.Rancher.SSH.Port))\n\t}\n\tif cfg.Rancher.SSH.ListenAddress != \"\" {\n\t\tmodifiedLines = append(modifiedLines, fmt.Sprintf(\"ListenAddress %s\", cfg.Rancher.SSH.ListenAddress))\n\t}\n\n\tfor _, item := range modifiedLines {\n\t\tmatch, err := regexp.Match(\"^\"+item, sshdConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !match {\n\t\t\tsshdConfigString += fmt.Sprintf(\"%s\\n\", item)\n\t\t}\n\t}\n\n\treturn ioutil.WriteFile(\"\/etc\/ssh\/sshd_config\", []byte(sshdConfigString), 0644)\n}\n\nfunc setupSSH(cfg *config.CloudConfig) error {\n\tfor _, keyType := range []string{\"rsa\", \"dsa\", \"ecdsa\", \"ed25519\"} {\n\t\toutputFile := fmt.Sprintf(\"\/etc\/ssh\/ssh_host_%s_key\", keyType)\n\t\toutputFilePub := fmt.Sprintf(\"\/etc\/ssh\/ssh_host_%s_key.pub\", keyType)\n\n\t\tif _, err := os.Stat(outputFile); err == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tsaved, savedExists := cfg.Rancher.SSH.Keys[keyType]\n\t\tpub, pubExists := cfg.Rancher.SSH.Keys[keyType+\"-pub\"]\n\n\t\tif savedExists && pubExists {\n\t\t\t\/\/ TODO check permissions\n\t\t\tif err := util.WriteFileAtomic(outputFile, []byte(saved), 0600); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := util.WriteFileAtomic(outputFilePub, []byte(pub), 0600); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tcmd := exec.Command(\"bash\", \"-c\", fmt.Sprintf(\"ssh-keygen -f %s -N '' -t %s\", outputFile, keyType))\n\t\tif err := cmd.Run(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsavedBytes, err := ioutil.ReadFile(outputFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpubBytes, err := ioutil.ReadFile(outputFilePub)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tconfig.Set(fmt.Sprintf(\"rancher.ssh.keys.%s\", keyType), string(savedBytes))\n\t\tconfig.Set(fmt.Sprintf(\"rancher.ssh.keys.%s-pub\", keyType), string(pubBytes))\n\t}\n\n\treturn os.MkdirAll(\"\/var\/run\/sshd\", 0644)\n}\n<commit_msg>Add systemd cgroup directory<commit_after>package control\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"golang.org\/x\/sys\/unix\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/rancher\/os\/cmd\/cloudinitexecute\"\n\t\"github.com\/rancher\/os\/compose\"\n\t\"github.com\/rancher\/os\/config\"\n\t\"github.com\/rancher\/os\/config\/cmdline\"\n\t\"github.com\/rancher\/os\/log\"\n\t\"github.com\/rancher\/os\/util\"\n)\n\nconst (\n\tconsoleDone = \"\/run\/console-done\"\n\tdockerHome  = \"\/home\/docker\"\n\tgettyCmd    = \"\/sbin\/agetty\"\n\trancherHome = \"\/home\/rancher\"\n\tstartScript = \"\/opt\/rancher\/bin\/start.sh\"\n)\n\ntype symlink struct {\n\toldname, newname string\n}\n\nfunc ConsoleInitMain() {\n\tif err := consoleInitFunc(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc consoleInitAction(c *cli.Context) error {\n\treturn consoleInitFunc()\n}\n\nfunc createHomeDir(homedir string, uid, gid int) {\n\tif _, err := os.Stat(homedir); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(homedir, 0755); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\tif err := os.Chown(homedir, uid, gid); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n}\n\nfunc consoleInitFunc() error {\n\tcfg := config.LoadConfig()\n\n\t\/\/ Now that we're booted, stop writing debug messages to the console\n\tcmd := exec.Command(\"sudo\", \"dmesg\", \"--console-off\")\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tcreateHomeDir(rancherHome, 1100, 1100)\n\tcreateHomeDir(dockerHome, 1101, 1101)\n\n\tpassword := cmdline.GetCmdline(\"rancher.password\")\n\tif password != \"\" {\n\t\tcmd := exec.Command(\"chpasswd\")\n\t\tcmd.Stdin = strings.NewReader(fmt.Sprint(\"rancher:\", password))\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\n\t\tcmd = exec.Command(\"bash\", \"-c\", `sed -E -i 's\/(rancher:.*:).*(:.*:.*:.*:.*:.*:.*)$\/\\1\\2\/' \/etc\/shadow`)\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n\n\tif err := setupSSH(cfg); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tif err := writeRespawn(\"rancher\", cfg.Rancher.SSH.Daemon, false); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tif err := modifySshdConfig(cfg); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tp, err := compose.GetProject(cfg, false, true)\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\n\t\/\/ check the multi engine service & generate the multi engine script\n\tfor _, key := range p.ServiceConfigs.Keys() {\n\t\tserviceConfig, ok := p.ServiceConfigs.Get(key)\n\t\tif !ok {\n\t\t\tlog.Errorf(\"Failed to get service config from the project\")\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := serviceConfig.Labels[config.UserDockerLabel]; ok {\n\t\t\terr = util.GenerateDindEngineScript(serviceConfig.Labels[config.UserDockerLabel])\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed to generate engine script: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, link := range []symlink{\n\t\t{\"\/var\/lib\/rancher\/engine\/docker\", \"\/usr\/bin\/docker\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/docker-init\", \"\/usr\/bin\/docker-init\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/docker-containerd\", \"\/usr\/bin\/docker-containerd\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/docker-containerd-ctr\", \"\/usr\/bin\/docker-containerd-ctr\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/docker-containerd-shim\", \"\/usr\/bin\/docker-containerd-shim\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/dockerd\", \"\/usr\/bin\/dockerd\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/docker-proxy\", \"\/usr\/bin\/docker-proxy\"},\n\t\t{\"\/var\/lib\/rancher\/engine\/docker-runc\", \"\/usr\/bin\/docker-runc\"},\n\t\t{\"\/usr\/share\/ros\/os-release\", \"\/usr\/lib\/os-release\"},\n\t\t{\"\/usr\/share\/ros\/os-release\", \"\/etc\/os-release\"},\n\t} {\n\t\tsyscall.Unlink(link.newname)\n\t\tif err := os.Symlink(link.oldname, link.newname); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n\n\t\/\/ mount systemd cgroups\n\tif err := os.MkdirAll(\"\/sys\/fs\/cgroup\/systemd\", 0555); err != nil {\n\t\tlog.Error(err)\n\t}\n\tif err := unix.Mount(\"cgroup\", \"\/sys\/fs\/cgroup\/systemd\", \"cgroup\", 0, \"none,name=systemd\"); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\t\/\/ font backslashes need to be escaped for when issue is output! (but not the others..)\n\tif err := ioutil.WriteFile(\"\/etc\/issue\", []byte(config.Banner), 0644); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\t\/\/ write out a profile.d file for the proxy settings.\n\t\/\/ maybe write these on the host and bindmount into everywhere?\n\tproxyLines := []string{}\n\tfor _, k := range []string{\"http_proxy\", \"HTTP_PROXY\", \"https_proxy\", \"HTTPS_PROXY\", \"no_proxy\", \"NO_PROXY\"} {\n\t\tif v, ok := cfg.Rancher.Environment[k]; ok {\n\t\t\tproxyLines = append(proxyLines, fmt.Sprintf(\"export %s=%s\", k, v))\n\t\t}\n\t}\n\n\tif len(proxyLines) > 0 {\n\t\tproxyString := strings.Join(proxyLines, \"\\n\")\n\t\tproxyString = fmt.Sprintf(\"#!\/bin\/sh\\n%s\\n\", proxyString)\n\t\tif err := ioutil.WriteFile(\"\/etc\/profile.d\/proxy.sh\", []byte(proxyString), 0755); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n\n\t\/\/ write out a profile.d file for the PATH settings.\n\tpathLines := []string{}\n\tfor _, k := range []string{\"PATH\", \"path\"} {\n\t\tif v, ok := cfg.Rancher.Environment[k]; ok {\n\t\t\tfor _, p := range strings.Split(v, \",\") {\n\t\t\t\tpathLines = append(pathLines, fmt.Sprintf(\"export PATH=$PATH:%s\", strings.TrimSpace(p)))\n\t\t\t}\n\t\t}\n\t}\n\tif len(pathLines) > 0 {\n\t\tpathString := strings.Join(pathLines, \"\\n\")\n\t\tpathString = fmt.Sprintf(\"#!\/bin\/sh\\n%s\\n\", pathString)\n\t\tif err := ioutil.WriteFile(\"\/etc\/profile.d\/path.sh\", []byte(pathString), 0755); err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}\n\n\tcmd = exec.Command(\"bash\", \"-c\", `echo $(\/sbin\/ifconfig | grep -B1 \"inet addr\" |awk '{ if ( $1 == \"inet\" ) { print $2 } else if ( $2 == \"Link\" ) { printf \"%s:\" ,$1 } }' |awk -F: '{ print $1 \": \" $3}') >> \/etc\/issue`)\n\tif err := cmd.Run(); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tcloudinitexecute.ApplyConsole(cfg)\n\n\tif err := util.RunScript(config.CloudConfigScriptFile); err != nil {\n\t\tlog.Error(err)\n\t}\n\tif err := util.RunScript(startScript); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tif err := ioutil.WriteFile(consoleDone, []byte(CurrentConsole()), 0644); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tif err := util.RunScript(\"\/etc\/rc.local\"); err != nil {\n\t\tlog.Error(err)\n\t}\n\n\tos.Setenv(\"TERM\", \"linux\")\n\n\trespawnBinPath, err := exec.LookPath(\"respawn\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn syscall.Exec(respawnBinPath, []string{\"respawn\", \"-f\", \"\/etc\/respawn.conf\"}, os.Environ())\n}\n\nfunc generateRespawnConf(cmdline, user string, sshd, recovery bool) string {\n\tvar respawnConf bytes.Buffer\n\n\tautologinBin := \"\/usr\/bin\/autologin\"\n\tif recovery {\n\t\tautologinBin = \"\/usr\/bin\/recovery\"\n\t}\n\n\tfor i := 1; i < 7; i++ {\n\t\ttty := fmt.Sprintf(\"tty%d\", i)\n\n\t\trespawnConf.WriteString(gettyCmd)\n\t\tif strings.Contains(cmdline, fmt.Sprintf(\"rancher.autologin=%s\", tty)) {\n\t\t\trespawnConf.WriteString(fmt.Sprintf(\" -n -l %s -o %s:tty%d\", autologinBin, user, i))\n\t\t}\n\t\trespawnConf.WriteString(fmt.Sprintf(\" --noclear %s linux\\n\", tty))\n\t}\n\n\tfor _, tty := range []string{\"ttyS0\", \"ttyS1\", \"ttyS2\", \"ttyS3\", \"ttyAMA0\"} {\n\t\tif !strings.Contains(cmdline, fmt.Sprintf(\"console=%s\", tty)) {\n\t\t\tcontinue\n\t\t}\n\n\t\trespawnConf.WriteString(gettyCmd)\n\t\tif strings.Contains(cmdline, fmt.Sprintf(\"rancher.autologin=%s\", tty)) {\n\t\t\trespawnConf.WriteString(fmt.Sprintf(\" -n -l %s -o %s:%s\", autologinBin, user, tty))\n\t\t}\n\t\trespawnConf.WriteString(fmt.Sprintf(\" %s\\n\", tty))\n\t}\n\n\tif sshd {\n\t\trespawnConf.WriteString(\"\/usr\/sbin\/sshd -D\")\n\t}\n\n\treturn respawnConf.String()\n}\n\nfunc writeRespawn(user string, sshd, recovery bool) error {\n\tcmdline, err := ioutil.ReadFile(\"\/proc\/cmdline\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trespawn := generateRespawnConf(string(cmdline), user, sshd, recovery)\n\n\tfiles, err := ioutil.ReadDir(\"\/etc\/respawn.conf.d\")\n\tif err == nil {\n\t\tfor _, f := range files {\n\t\t\tp := path.Join(\"\/etc\/respawn.conf.d\", f.Name())\n\t\t\tcontent, err := ioutil.ReadFile(p)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed to read %s: %v\", p, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trespawn += fmt.Sprintf(\"\\n%s\", string(content))\n\t\t}\n\t} else if !os.IsNotExist(err) {\n\t\tlog.Error(err)\n\t}\n\n\treturn ioutil.WriteFile(\"\/etc\/respawn.conf\", []byte(respawn), 0644)\n}\n\nfunc modifySshdConfig(cfg *config.CloudConfig) error {\n\tsshdConfig, err := ioutil.ReadFile(\"\/etc\/ssh\/sshd_config\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tsshdConfigString := string(sshdConfig)\n\n\tmodifiedLines := []string{\n\t\t\"UseDNS no\",\n\t\t\"PermitRootLogin no\",\n\t\t\"ServerKeyBits 2048\",\n\t\t\"AllowGroups docker\",\n\t}\n\n\tif cfg.Rancher.SSH.Port > 0 && cfg.Rancher.SSH.Port < 65355 {\n\t\tmodifiedLines = append(modifiedLines, fmt.Sprintf(\"Port %d\", cfg.Rancher.SSH.Port))\n\t}\n\tif cfg.Rancher.SSH.ListenAddress != \"\" {\n\t\tmodifiedLines = append(modifiedLines, fmt.Sprintf(\"ListenAddress %s\", cfg.Rancher.SSH.ListenAddress))\n\t}\n\n\tfor _, item := range modifiedLines {\n\t\tmatch, err := regexp.Match(\"^\"+item, sshdConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !match {\n\t\t\tsshdConfigString += fmt.Sprintf(\"%s\\n\", item)\n\t\t}\n\t}\n\n\treturn ioutil.WriteFile(\"\/etc\/ssh\/sshd_config\", []byte(sshdConfigString), 0644)\n}\n\nfunc setupSSH(cfg *config.CloudConfig) error {\n\tfor _, keyType := range []string{\"rsa\", \"dsa\", \"ecdsa\", \"ed25519\"} {\n\t\toutputFile := fmt.Sprintf(\"\/etc\/ssh\/ssh_host_%s_key\", keyType)\n\t\toutputFilePub := fmt.Sprintf(\"\/etc\/ssh\/ssh_host_%s_key.pub\", keyType)\n\n\t\tif _, err := os.Stat(outputFile); err == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tsaved, savedExists := cfg.Rancher.SSH.Keys[keyType]\n\t\tpub, pubExists := cfg.Rancher.SSH.Keys[keyType+\"-pub\"]\n\n\t\tif savedExists && pubExists {\n\t\t\t\/\/ TODO check permissions\n\t\t\tif err := util.WriteFileAtomic(outputFile, []byte(saved), 0600); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := util.WriteFileAtomic(outputFilePub, []byte(pub), 0600); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tcmd := exec.Command(\"bash\", \"-c\", fmt.Sprintf(\"ssh-keygen -f %s -N '' -t %s\", outputFile, keyType))\n\t\tif err := cmd.Run(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsavedBytes, err := ioutil.ReadFile(outputFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpubBytes, err := ioutil.ReadFile(outputFilePub)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tconfig.Set(fmt.Sprintf(\"rancher.ssh.keys.%s\", keyType), string(savedBytes))\n\t\tconfig.Set(fmt.Sprintf(\"rancher.ssh.keys.%s-pub\", keyType), string(pubBytes))\n\t}\n\n\treturn os.MkdirAll(\"\/var\/run\/sshd\", 0644)\n}\n<|endoftext|>"}
{"text":"<commit_before>package sftp\n\nimport (\n\t\"encoding\"\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ conn implements a bidirectional channel on which client and server\n\/\/ connections are multiplexed.\ntype conn struct {\n\tio.Reader\n\tio.WriteCloser\n\tsync.Mutex \/\/ used to serialise writes to sendPacket\n}\n\nfunc (c *conn) recvPacket() (uint8, []byte, error) {\n\treturn recvPacket(c)\n}\n\nfunc (c *conn) sendPacket(m encoding.BinaryMarshaler) error {\n\tc.Lock()\n\tdefer c.Unlock()\n\treturn sendPacket(c, m)\n}\n\ntype clientConn struct {\n\tconn\n\twg         sync.WaitGroup\n\tsync.Mutex                          \/\/ protects inflight\n\tinflight   map[uint32]chan<- result \/\/ outstanding requests\n}\n\n\/\/ Close closes the SFTP session.\nfunc (c *clientConn) Close() error {\n\tdefer c.wg.Wait()\n\treturn c.conn.Close()\n}\n\nfunc (c *clientConn) loop() {\n\tdefer c.wg.Done()\n\terr := c.recv()\n\tif err != nil {\n\t\tc.broadcastErr(err)\n\t}\n}\n\n\/\/ recv continuously reads from the server and forwards responses to the\n\/\/ appropriate channel.\nfunc (c *clientConn) recv() error {\n\tdefer c.conn.Close()\n\tfor {\n\t\ttyp, data, err := c.recvPacket()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsid, _ := unmarshalUint32(data)\n\t\tc.Lock()\n\t\tch, ok := c.inflight[sid]\n\t\tdelete(c.inflight, sid)\n\t\tc.Unlock()\n\t\tif !ok {\n\t\t\t\/\/ This is an unexpected occurrence. Send the error\n\t\t\t\/\/ back to all listeners so that they terminate\n\t\t\t\/\/ gracefully.\n\t\t\treturn errors.Errorf(\"sid: %v not fond\", sid)\n\t\t}\n\t\tch <- result{typ: typ, data: data}\n\t}\n}\n\n\/\/ result captures the result of receiving the a packet from the server\ntype result struct {\n\ttyp  byte\n\tdata []byte\n\terr  error\n}\n\ntype idmarshaler interface {\n\tid() uint32\n\tencoding.BinaryMarshaler\n}\n\nfunc (c *clientConn) sendPacket(p idmarshaler) (byte, []byte, error) {\n\tch := make(chan result, 1)\n\tc.dispatchRequest(ch, p)\n\ts := <-ch\n\treturn s.typ, s.data, s.err\n}\n\nfunc (c *clientConn) dispatchRequest(ch chan<- result, p idmarshaler) {\n\tc.Lock()\n\tc.inflight[p.id()] = ch\n\tif err := c.conn.sendPacket(p); err != nil {\n\t\tdelete(c.inflight, p.id())\n\t\tch <- result{err: err}\n\t}\n\tc.Unlock()\n}\n\n\/\/ broadcastErr sends an error to all goroutines waiting for a response.\nfunc (c *clientConn) broadcastErr(err error) {\n\tc.Lock()\n\tlisteners := make([]chan<- result, 0, len(c.inflight))\n\tfor _, ch := range c.inflight {\n\t\tlisteners = append(listeners, ch)\n\t}\n\tc.Unlock()\n\tfor _, ch := range listeners {\n\t\tch <- result{err: err}\n\t}\n}\n\ntype serverConn struct {\n\tconn\n}\n\nfunc (s *serverConn) sendError(p id, err error) error {\n\treturn s.sendPacket(statusFromError(p, err))\n}\n<commit_msg>add lock on connection close to prevent race<commit_after>package sftp\n\nimport (\n\t\"encoding\"\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ conn implements a bidirectional channel on which client and server\n\/\/ connections are multiplexed.\ntype conn struct {\n\tio.Reader\n\tio.WriteCloser\n\tsync.Mutex \/\/ used to serialise writes to sendPacket\n}\n\nfunc (c *conn) recvPacket() (uint8, []byte, error) {\n\treturn recvPacket(c)\n}\n\nfunc (c *conn) sendPacket(m encoding.BinaryMarshaler) error {\n\tc.Lock()\n\tdefer c.Unlock()\n\treturn sendPacket(c, m)\n}\n\ntype clientConn struct {\n\tconn\n\twg         sync.WaitGroup\n\tsync.Mutex                          \/\/ protects inflight\n\tinflight   map[uint32]chan<- result \/\/ outstanding requests\n}\n\n\/\/ Close closes the SFTP session.\nfunc (c *clientConn) Close() error {\n\tdefer c.wg.Wait()\n\treturn c.conn.Close()\n}\n\nfunc (c *clientConn) loop() {\n\tdefer c.wg.Done()\n\terr := c.recv()\n\tif err != nil {\n\t\tc.broadcastErr(err)\n\t}\n}\n\n\/\/ recv continuously reads from the server and forwards responses to the\n\/\/ appropriate channel.\nfunc (c *clientConn) recv() error {\n\tdefer func() {\n\t\tc.Lock()\n\t\tc.conn.Close()\n\t\tc.Unlock()\n\t}()\n\tfor {\n\t\ttyp, data, err := c.recvPacket()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsid, _ := unmarshalUint32(data)\n\t\tc.Lock()\n\t\tch, ok := c.inflight[sid]\n\t\tdelete(c.inflight, sid)\n\t\tc.Unlock()\n\t\tif !ok {\n\t\t\t\/\/ This is an unexpected occurrence. Send the error\n\t\t\t\/\/ back to all listeners so that they terminate\n\t\t\t\/\/ gracefully.\n\t\t\treturn errors.Errorf(\"sid: %v not fond\", sid)\n\t\t}\n\t\tch <- result{typ: typ, data: data}\n\t}\n}\n\n\/\/ result captures the result of receiving the a packet from the server\ntype result struct {\n\ttyp  byte\n\tdata []byte\n\terr  error\n}\n\ntype idmarshaler interface {\n\tid() uint32\n\tencoding.BinaryMarshaler\n}\n\nfunc (c *clientConn) sendPacket(p idmarshaler) (byte, []byte, error) {\n\tch := make(chan result, 1)\n\tc.dispatchRequest(ch, p)\n\ts := <-ch\n\treturn s.typ, s.data, s.err\n}\n\nfunc (c *clientConn) dispatchRequest(ch chan<- result, p idmarshaler) {\n\tc.Lock()\n\tc.inflight[p.id()] = ch\n\tif err := c.conn.sendPacket(p); err != nil {\n\t\tdelete(c.inflight, p.id())\n\t\tch <- result{err: err}\n\t}\n\tc.Unlock()\n}\n\n\/\/ broadcastErr sends an error to all goroutines waiting for a response.\nfunc (c *clientConn) broadcastErr(err error) {\n\tc.Lock()\n\tlisteners := make([]chan<- result, 0, len(c.inflight))\n\tfor _, ch := range c.inflight {\n\t\tlisteners = append(listeners, ch)\n\t}\n\tc.Unlock()\n\tfor _, ch := range listeners {\n\t\tch <- result{err: err}\n\t}\n}\n\ntype serverConn struct {\n\tconn\n}\n\nfunc (s *serverConn) sendError(p id, err error) error {\n\treturn s.sendPacket(statusFromError(p, err))\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Calculating distance. Loading the file one record at a time using flags. Also, the code is in the main.go so far just to make it easier for now<commit_after>package main\n\nimport (\n\t\"encoding\/csv\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math\"\n\t\"os\"\n\t\"strconv\"\n\n\tflags \"github.com\/jessevdk\/go-flags\"\n)\n\n\/\/ Reaading the path using a commeand-line flag (the returned value is a pointer)\n\/\/var pathFlag = flag.String(\"path\", \"\", \"Path of CSV file\")\nvar opts struct {\n\tPath string `short:\"p\" long:\"path\" description:\"Path of the CSV file\" required:\"true\"`\n}\n\nfunc init() {\n\t\/\/ Adding the option for a shart flag for path also\n\t\/\/flag.StringVar(pathFlag, \"p\", \"\", \"Path of CSV file\")\n}\n\nfunc main() {\n\t_, err := flags.Parse(&opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Setup reader\n\tcsvIn, err := os.Open(opts.Path)\n\tif err != nil {\n\t\t\/\/ Checking if error is os.PathError and giving a more friendly message.\n\t\t\/\/ Just to show the conpect of type assertion here\n\t\tif _, ok := err.(*os.PathError); ok {\n\t\t\tlog.Fatal(\"File not found. Please verify if the file is the provided path.\")\n\t\t}\n\t\tlog.Fatal(err)\n\t}\n\tr := csv.NewReader(csvIn)\n\tfor {\n\t\trec, err := r.Read()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\t\/\/ Checking if record is a string or a number, if it is a string\n\t\t\/\/ means we are on the first row and we move to the next one\n\t\tif _, err := strconv.Atoi(rec[0]); err != nil {\n\t\t\trec, err = r.Read()\n\t\t}\n\n\t\t\/\/ Getting lat and long values\n\t\tid := rec[0]\n\t\tlat := rec[1]\n\t\tlong := rec[2]\n\t\tlatFloat, err := strconv.ParseFloat(lat, 64)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Record, error: %v, %v\", lat, err)\n\t\t}\n\t\tlongFloat, err := strconv.ParseFloat(long, 64)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Record, error: %v, %v\", long, err)\n\t\t}\n\n\t\t\/\/ calculate scores; THIS EXTERNAL METHOD CANNOT BE CHANGED\n\t\tdistance := Distance(51.925146, 4.478617, latFloat, longFloat)\n\t\tfmt.Printf(\"%v: %f\\n\", id, distance)\n\t}\n\n\t\/\/fmt.Println(Distance(51.925146, 4.478617, 37.1768672, -3.60897))\n}\n\n\/\/ Haversin(0) function\nfunc haversin(theta float64) float64 {\n\treturn math.Pow(math.Sin(theta\/2), 2)\n}\n\n\/\/ Distance function returns the distance (in meters) between two points of\n\/\/ a given longitude and latitude relatively accurately (using a spherical\n\/\/ approximation of the Earth) through the Haversin Distance Formula for\n\/\/ great arc distance on a pshere with accuracy for small distances\n\/\/ Point coordinates are supplied in degrees and converted into radius.\nfunc Distance(lat1, lon1, lat2, lon2 float64) float64 {\n\t\/\/ Converting to radians\n\tvar la1, lo1, la2, lo2, r float64\n\tla1 = lat1 * math.Pi \/ 180\n\tlo1 = lon1 * math.Pi \/ 180\n\tla2 = lat2 * math.Pi \/ 180\n\tlo2 = lon2 * math.Pi \/ 180\n\n\tr = 6378100 \/\/ Earth radius in Meters\n\n\t\/\/ Calculating\n\th := haversin(la2-la1) + math.Cos(la1)*math.Cos(la2)*haversin(lo2-lo1)\n\n\treturn 2 * r * math.Asin(math.Sqrt(h))\n}\n<|endoftext|>"}
{"text":"<commit_before>package\tgearman \/\/ import \"github.com\/nathanaelle\/gearman\"\n\nimport\t(\n\t\"io\"\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n\t\"sync\/atomic\"\n)\n\n\ntype\t(\n\tConn\tinterface {\n\t\tio.Writer\n\t\tio.Reader\n\t\tio.Closer\n\t\tSetReadDeadline(time.Time)\n\t\tSetWriteDeadline(time.Time)\n\t\tRedial()\n\t\tString() string\n\t\tCounterAdd(int32)\n\t\tIsZeroCounter() bool\n\t}\n\n\tnetConn\tstruct {\n\t\tclosed\t\tint32\n\t\tcounter\t\tint32\n\t\tnetwork,address string\n\t\tconn\t\tatomic.Value\n\t}\n)\n\n\nfunc NetConn(network,address string) Conn {\n \tnc := &netConn{\n\t\tnetwork:\tnetwork,\n\t\taddress:\taddress,\n\t}\n\n\treturn nc\n}\n\n\nfunc (nc *netConn)Close() error {\n\tif !nc.isNotClosed() {\n\t\treturn nil\n\t}\n\tatomic.AddInt32(&nc.closed, 1)\n\tconn := nc.nc()\n\tif conn != nil {\n\t\treturn\tconn.Close()\n\t}\n\treturn\tnil\n}\n\n\nfunc (nc *netConn)String() string {\n\treturn\tfmt.Sprintf(\"%s[%s]\", nc.network, nc.address)\n}\n\nfunc (nc *netConn)Redial() {\n\tvar err error\n\tconn := nc.nc()\n\tif conn != nil {\n\t\tconn.Close()\n\t}\n\n\tif nc.isNotClosed() {\n\t\tconn,err = net.Dial(nc.network, nc.address)\n\t\tnc.conn.Store(conn)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"!>\t%v\",err)\n\t\t\ttime.Sleep(500*time.Millisecond)\n\t\t}\n\t}\n}\n\n\nfunc (nc *netConn)Read(b []byte) (int, error) {\n\treturn\tnc.nc().Read(b)\n}\n\nfunc (nc *netConn)SetReadDeadline(t time.Time) {\n\tnc.nc().SetReadDeadline(t)\n}\n\nfunc (nc *netConn)SetWriteDeadline(t time.Time) {\n\tnc.nc().SetWriteDeadline(t)\n}\n\n\nfunc (nc *netConn)Write(b []byte) (int, error) {\n\treturn\tnc.nc().Write(b)\n}\n\nfunc (nc *netConn)CounterAdd(d int32) {\n\tatomic.AddInt32(&nc.counter, d)\n}\n\nfunc (nc *netConn)IsZeroCounter() bool {\n\treturn\tatomic.LoadInt32(&nc.counter) == 0\n}\n\nfunc (nc *netConn)isNotClosed() bool {\n\treturn\tatomic.LoadInt32(&nc.closed) == 0\n}\n\nfunc (nc *netConn)nc() net.Conn {\n\tc := nc.conn.Load()\n\tif c == nil {\n\t\treturn\tnil\n\t}\n\n\treturn\tc.(net.Conn)\n}\n<commit_msg>ugly patch to possible panic issue<commit_after>package\tgearman \/\/ import \"github.com\/nathanaelle\/gearman\"\n\nimport\t(\n\t\"io\"\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n\t\"sync\/atomic\"\n)\n\n\ntype\t(\n\tConn\tinterface {\n\t\tio.Writer\n\t\tio.Reader\n\t\tio.Closer\n\t\tSetReadDeadline(time.Time)\n\t\tSetWriteDeadline(time.Time)\n\t\tRedial()\n\t\tString() string\n\t\tCounterAdd(int32)\n\t\tIsZeroCounter() bool\n\t}\n\n\tnetConn\tstruct {\n\t\tclosed\t\tint32\n\t\tcounter\t\tint32\n\t\tnetwork,address string\n\t\tconn\t\tatomic.Value\n\t}\n)\n\n\nfunc NetConn(network,address string) Conn {\n \tnc := &netConn{\n\t\tnetwork:\tnetwork,\n\t\taddress:\taddress,\n\t}\n\n\treturn nc\n}\n\n\nfunc (nc *netConn)Close() error {\n\tif !nc.isNotClosed() {\n\t\treturn nil\n\t}\n\tatomic.AddInt32(&nc.closed, 1)\n\tconn := nc.nc()\n\tif conn != nil {\n\t\treturn\tconn.Close()\n\t}\n\treturn\tnil\n}\n\n\nfunc (nc *netConn)String() string {\n\treturn\tfmt.Sprintf(\"%s[%s]\", nc.network, nc.address)\n}\n\nfunc (nc *netConn)Redial() {\n\tvar err error\n\tconn := nc.nc()\n\tif conn != nil {\n\t\tconn.Close()\n\t}\n\n\tif nc.isNotClosed() {\n\t\tconn,err = net.Dial(nc.network, nc.address)\n\t\tif conn != nil {\n\t\t\tnc.conn.Store(conn)\n\t\t}\n\t\tif err != nil {\n\t\t\ttime.Sleep(500*time.Millisecond)\n\t\t}\n\t}\n}\n\n\nfunc (nc *netConn)Read(b []byte) (int, error) {\n\treturn\tnc.nc().Read(b)\n}\n\nfunc (nc *netConn)SetReadDeadline(t time.Time) {\n\tnc.nc().SetReadDeadline(t)\n}\n\nfunc (nc *netConn)SetWriteDeadline(t time.Time) {\n\tnc.nc().SetWriteDeadline(t)\n}\n\n\nfunc (nc *netConn)Write(b []byte) (int, error) {\n\treturn\tnc.nc().Write(b)\n}\n\nfunc (nc *netConn)CounterAdd(d int32) {\n\tatomic.AddInt32(&nc.counter, d)\n}\n\nfunc (nc *netConn)IsZeroCounter() bool {\n\treturn\tatomic.LoadInt32(&nc.counter) == 0\n}\n\nfunc (nc *netConn)isNotClosed() bool {\n\treturn\tatomic.LoadInt32(&nc.closed) == 0\n}\n\nfunc (nc *netConn)nc() net.Conn {\n\tc := nc.conn.Load()\n\tif c == nil {\n\t\treturn\tnil\n\t}\n\n\treturn\tc.(net.Conn)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n Copyright 2020 The GoPlus Authors (goplus.org)\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n\/\/ Package build implements the ``gop build'' command.\npackage build\n\nimport (\n\t\"fmt\"\n\t\"go\/token\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/goplus\/gop\/cl\"\n\t\"github.com\/goplus\/gop\/cmd\/internal\/base\"\n\t\"github.com\/goplus\/gop\/cmd\/internal\/work\"\n\t\"github.com\/goplus\/gop\/exec\/bytecode\"\n\t\"github.com\/qiniu\/x\/log\"\n)\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Cmd - gop build\nvar Cmd = &base.Command{\n\tUsageLine: \"gop build [-v] [-o output] <gopSrcDir|gopSrcFile>\",\n\tShort:     \"Build go+ files and execute go build command\",\n}\n\nvar (\n\tflagBuildOutput string\n\tflagVerbose     bool\n\tflag            = &Cmd.Flag\n)\n\nfunc init() {\n\tflag.StringVar(&flagBuildOutput, \"o\", \"\", \"go build output file\")\n\tflag.BoolVar(&flagVerbose, \"v\", false, \"print the names of packages as they are compiled.\")\n\tCmd.Run = runCmd\n}\n\nfunc runCmd(cmd *base.Command, args []string) {\n\tflag.Parse(args)\n\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to build: %v\", err)\n\t}\n\n\tpaths := flag.Args()\n\tif len(paths) == 0 {\n\t\tpaths = append(paths, \".\")\n\t}\n\n\tcl.CallBuiltinOp = bytecode.CallBuiltinOp\n\tlog.SetFlags(log.Ldefault &^ log.LstdFlags)\n\n\tfset := token.NewFileSet()\n\tpkgs, errs := work.LoadPackages(fset, paths)\n\tif len(errs) > 0 {\n\t\tlog.Fatalf(\"load packages error: %v\\n\", errs)\n\t}\n\tfor _, pkg := range pkgs {\n\t\terr := work.GenGoPkg(fset, pkg.Pkg, pkg.Dir)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"generate go package error: %v\\n\", err)\n\t\t}\n\t\tvar target string\n\t\tif flagBuildOutput != \"\" {\n\t\t\ttarget = filepath.Join(dir, flagBuildOutput)\n\t\t} else {\n\t\t\ttarget = pkg.Target\n\t\t}\n\t\terr = work.GoBuild(pkg.Dir, target)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"go build error: %v\\n\", err)\n\t\t}\n\t\tif flagVerbose {\n\t\t\tfmt.Printf(\"gop build %v\\n\", target)\n\t\t}\n\t}\n}\n<commit_msg>gop build verbose<commit_after>\/*\n Copyright 2020 The GoPlus Authors (goplus.org)\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n\/\/ Package build implements the ``gop build'' command.\npackage build\n\nimport (\n\t\"fmt\"\n\t\"go\/token\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/goplus\/gop\/cl\"\n\t\"github.com\/goplus\/gop\/cmd\/internal\/base\"\n\t\"github.com\/goplus\/gop\/cmd\/internal\/work\"\n\t\"github.com\/goplus\/gop\/exec\/bytecode\"\n\t\"github.com\/qiniu\/x\/log\"\n)\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Cmd - gop build\nvar Cmd = &base.Command{\n\tUsageLine: \"gop build [-v] [-o output] <gopSrcDir|gopSrcFile>\",\n\tShort:     \"Build go+ files and execute go build command\",\n}\n\nvar (\n\tflagBuildOutput string\n\tflagVerbose     bool\n\tflag            = &Cmd.Flag\n)\n\nfunc init() {\n\tflag.StringVar(&flagBuildOutput, \"o\", \"\", \"go build output file\")\n\tflag.BoolVar(&flagVerbose, \"v\", false, \"print the names of packages as they are compiled.\")\n\tCmd.Run = runCmd\n}\n\nfunc runCmd(cmd *base.Command, args []string) {\n\tflag.Parse(args)\n\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to build: %v\", err)\n\t}\n\n\tpaths := flag.Args()\n\tif len(paths) == 0 {\n\t\tpaths = append(paths, \".\")\n\t}\n\n\tcl.CallBuiltinOp = bytecode.CallBuiltinOp\n\tlog.SetFlags(log.Ldefault &^ log.LstdFlags)\n\n\tfset := token.NewFileSet()\n\tpkgs, errs := work.LoadPackages(fset, paths)\n\tif len(errs) > 0 {\n\t\tlog.Fatalf(\"load packages error: %v\\n\", errs)\n\t}\n\tfor _, pkg := range pkgs {\n\t\terr := work.GenGoPkg(fset, pkg.Pkg, pkg.Dir)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"generate go package error: %v\\n\", err)\n\t\t}\n\t\tvar target string\n\t\tif flagBuildOutput != \"\" {\n\t\t\ttarget = filepath.Join(dir, flagBuildOutput)\n\t\t} else {\n\t\t\ttarget = filepath.Join(pkg.Dir, pkg.Target)\n\t\t}\n\t\terr = work.GoBuild(pkg.Dir, target)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"go build error: %v\\n\", err)\n\t\t}\n\t\tif flagVerbose && pkg.Name == \"main\" {\n\t\t\tfmt.Println(target)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cmd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\tcmdutil \"github.com\/GoogleContainerTools\/skaffold\/cmd\/skaffold\/app\/cmd\/util\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/config\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/constants\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/update\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/version\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n)\n\nvar (\n\topts      = &config.SkaffoldOptions{}\n\tv         string\n\toverwrite bool\n\n\tupdateMsg = make(chan string)\n)\n\nvar rootCmd = &cobra.Command{\n\tUse:   \"skaffold\",\n\tShort: \"A tool that facilitates continuous development for Kubernetes applications.\",\n}\n\nfunc NewSkaffoldCommand(out, err io.Writer) *cobra.Command {\n\trootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {\n\t\tif err := SetUpLogs(err, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t\trootCmd.SilenceUsage = true\n\t\tlogrus.Infof(\"Skaffold %+v\", version.Get())\n\t\tgo func() {\n\t\t\tif err := updateCheck(updateMsg); err != nil {\n\t\t\t\tlogrus.Infof(\"update check failed: %s\", err)\n\t\t\t}\n\t\t}()\n\t\treturn nil\n\t}\n\n\trootCmd.PersistentPostRun = func(cmd *cobra.Command, args []string) {\n\t\tselect {\n\t\tcase msg := <-updateMsg:\n\t\t\tfmt.Fprintf(out, \"%s\\n\", msg)\n\t\tdefault:\n\t\t}\n\t}\n\n\trootCmd.SilenceErrors = true\n\trootCmd.AddCommand(NewCmdCompletion(out))\n\trootCmd.AddCommand(NewCmdVersion(out))\n\trootCmd.AddCommand(NewCmdRun(out))\n\trootCmd.AddCommand(NewCmdDev(out))\n\trootCmd.AddCommand(NewCmdBuild(out))\n\trootCmd.AddCommand(NewCmdDeploy(out))\n\trootCmd.AddCommand(NewCmdDelete(out))\n\trootCmd.AddCommand(NewCmdFix(out))\n\trootCmd.AddCommand(NewCmdConfig(out))\n\n\trootCmd.PersistentFlags().StringVarP(&v, \"verbosity\", \"v\", constants.DefaultLogLevel.String(), \"Log level (debug, info, warn, error, fatal, panic\")\n\n\tsetFlagsFromEnvVariables(rootCmd.Commands())\n\n\treturn rootCmd\n}\n\nfunc updateCheck(ch chan string) error {\n\tif !update.IsUpdateCheckEnabled() {\n\t\tlogrus.Debugf(\"Update check not enabled, skipping.\")\n\t\treturn nil\n\t}\n\tcurrent, err := version.ParseVersion(version.Get().Version)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"parsing current semver, skipping update check\")\n\t}\n\tlatest, err := update.GetLatestVersion(context.Background())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting latest version\")\n\t}\n\tif latest.GT(current) {\n\t\tch <- fmt.Sprintf(\"There is a new version (%s) of skaffold available. Download it at %s\\n\", latest, constants.LatestDownloadURL)\n\t}\n\treturn nil\n}\n\n\/\/ Each flag can also be set with an env variable whose name starts with `SKAFFOLD_`.\nfunc setFlagsFromEnvVariables(commands []*cobra.Command) {\n\tfor _, cmd := range commands {\n\t\tcmd.Flags().VisitAll(func(f *pflag.Flag) {\n\t\t\t\/\/ special case for backward compatibility.\n\t\t\tif f.Name == \"namespace\" {\n\t\t\t\tif val, present := os.LookupEnv(\"SKAFFOLD_DEPLOY_NAMESPACE\"); present {\n\t\t\t\t\tlogrus.Warnln(\"Using SKAFFOLD_DEPLOY_NAMESPACE env variable is deprecated. Please use SKAFFOLD_NAMESPACE instead.\")\n\t\t\t\t\tcmd.Flags().Set(f.Name, val)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tenvVar := fmt.Sprintf(\"SKAFFOLD_%s\", strings.Replace(strings.ToUpper(f.Name), \"-\", \"_\", -1))\n\t\t\tif val, present := os.LookupEnv(envVar); present {\n\t\t\t\tcmd.Flags().Set(f.Name, val)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc AddDevFlags(cmd *cobra.Command) {\n\tcmd.Flags().BoolVar(&opts.Cleanup, \"cleanup\", true, \"Delete deployments after dev mode is interrupted\")\n\tcmd.Flags().StringArrayVarP(&opts.Watch, \"watch-image\", \"w\", nil, \"Choose which artifacts to watch. Artifacts with image names that contain the expression will be watched only. Default is to watch sources for all artifacts.\")\n}\n\nfunc AddRunDeployFlags(cmd *cobra.Command) {\n\tcmd.Flags().BoolVar(&opts.Tail, \"tail\", false, \"Stream logs from deployed objects\")\n}\n\nfunc AddRunDevFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&opts.ConfigurationFile, \"filename\", \"f\", \"skaffold.yaml\", \"Filename or URL to the pipeline file\")\n\tcmd.Flags().BoolVar(&opts.Notification, \"toot\", false, \"Emit a terminal beep after the deploy is complete\")\n\tcmd.Flags().StringArrayVarP(&opts.Profiles, \"profile\", \"p\", nil, \"Activate profiles by name\")\n\tcmd.Flags().StringVarP(&opts.Namespace, \"namespace\", \"n\", \"\", \"Run Helm deployments in the specified namespace\")\n}\n\nfunc AddFixFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&opts.ConfigurationFile, \"filename\", \"f\", \"skaffold.yaml\", \"Filename or URL to the pipeline file\")\n\tcmd.Flags().BoolVar(&overwrite, \"overwrite\", false, \"Overwrite original config with fixed config\")\n}\n\nfunc SetUpLogs(out io.Writer, level string) error {\n\tlogrus.SetOutput(out)\n\tlvl, err := logrus.ParseLevel(v)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"parsing log level\")\n\t}\n\tlogrus.SetLevel(lvl)\n\treturn nil\n}\n\nfunc readConfiguration(opts *config.SkaffoldOptions) (*config.SkaffoldConfig, error) {\n\tconfig, err := cmdutil.ParseConfig(opts.ConfigurationFile)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"parsing skaffold config\")\n\t}\n\terr = config.ApplyProfiles(opts.Profiles)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"applying profiles\")\n\t}\n\treturn config, nil\n}\n<commit_msg>update check respected quiet flag<commit_after>\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cmd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\tcmdutil \"github.com\/GoogleContainerTools\/skaffold\/cmd\/skaffold\/app\/cmd\/util\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/config\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/constants\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/update\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/version\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n)\n\nvar (\n\topts      = &config.SkaffoldOptions{}\n\tv         string\n\toverwrite bool\n\n\tupdateMsg = make(chan string)\n)\n\nvar rootCmd = &cobra.Command{\n\tUse:   \"skaffold\",\n\tShort: \"A tool that facilitates continuous development for Kubernetes applications.\",\n}\n\nfunc NewSkaffoldCommand(out, err io.Writer) *cobra.Command {\n\trootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {\n\t\tif err := SetUpLogs(err, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t\trootCmd.SilenceUsage = true\n\t\tlogrus.Infof(\"Skaffold %+v\", version.Get())\n\t\tgo func() {\n\t\t\tif err := updateCheck(updateMsg); err != nil {\n\t\t\t\tlogrus.Infof(\"update check failed: %s\", err)\n\t\t\t}\n\t\t}()\n\t\treturn nil\n\t}\n\n\trootCmd.PersistentPostRun = func(cmd *cobra.Command, args []string) {\n\t\tselect {\n\t\tcase msg := <-updateMsg:\n\t\t\tfmt.Fprintf(out, \"%s\\n\", msg)\n\t\tdefault:\n\t\t}\n\t}\n\n\trootCmd.SilenceErrors = true\n\trootCmd.AddCommand(NewCmdCompletion(out))\n\trootCmd.AddCommand(NewCmdVersion(out))\n\trootCmd.AddCommand(NewCmdRun(out))\n\trootCmd.AddCommand(NewCmdDev(out))\n\trootCmd.AddCommand(NewCmdBuild(out))\n\trootCmd.AddCommand(NewCmdDeploy(out))\n\trootCmd.AddCommand(NewCmdDelete(out))\n\trootCmd.AddCommand(NewCmdFix(out))\n\trootCmd.AddCommand(NewCmdConfig(out))\n\n\trootCmd.PersistentFlags().StringVarP(&v, \"verbosity\", \"v\", constants.DefaultLogLevel.String(), \"Log level (debug, info, warn, error, fatal, panic\")\n\n\tsetFlagsFromEnvVariables(rootCmd.Commands())\n\n\treturn rootCmd\n}\n\nfunc updateCheck(ch chan string) error {\n\tif quietFlag {\n\t\tlogrus.Debugf(\"Update check is disabled because of quiet mode\")\n\t\treturn nil\n\t}\n\tif !update.IsUpdateCheckEnabled() {\n\t\tlogrus.Debugf(\"Update check not enabled, skipping.\")\n\t\treturn nil\n\t}\n\tcurrent, err := version.ParseVersion(version.Get().Version)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"parsing current semver, skipping update check\")\n\t}\n\tlatest, err := update.GetLatestVersion(context.Background())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting latest version\")\n\t}\n\tif latest.GT(current) {\n\t\tch <- fmt.Sprintf(\"There is a new version (%s) of skaffold available. Download it at %s\\n\", latest, constants.LatestDownloadURL)\n\t}\n\treturn nil\n}\n\n\/\/ Each flag can also be set with an env variable whose name starts with `SKAFFOLD_`.\nfunc setFlagsFromEnvVariables(commands []*cobra.Command) {\n\tfor _, cmd := range commands {\n\t\tcmd.Flags().VisitAll(func(f *pflag.Flag) {\n\t\t\t\/\/ special case for backward compatibility.\n\t\t\tif f.Name == \"namespace\" {\n\t\t\t\tif val, present := os.LookupEnv(\"SKAFFOLD_DEPLOY_NAMESPACE\"); present {\n\t\t\t\t\tlogrus.Warnln(\"Using SKAFFOLD_DEPLOY_NAMESPACE env variable is deprecated. Please use SKAFFOLD_NAMESPACE instead.\")\n\t\t\t\t\tcmd.Flags().Set(f.Name, val)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tenvVar := fmt.Sprintf(\"SKAFFOLD_%s\", strings.Replace(strings.ToUpper(f.Name), \"-\", \"_\", -1))\n\t\t\tif val, present := os.LookupEnv(envVar); present {\n\t\t\t\tcmd.Flags().Set(f.Name, val)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc AddDevFlags(cmd *cobra.Command) {\n\tcmd.Flags().BoolVar(&opts.Cleanup, \"cleanup\", true, \"Delete deployments after dev mode is interrupted\")\n\tcmd.Flags().StringArrayVarP(&opts.Watch, \"watch-image\", \"w\", nil, \"Choose which artifacts to watch. Artifacts with image names that contain the expression will be watched only. Default is to watch sources for all artifacts.\")\n}\n\nfunc AddRunDeployFlags(cmd *cobra.Command) {\n\tcmd.Flags().BoolVar(&opts.Tail, \"tail\", false, \"Stream logs from deployed objects\")\n}\n\nfunc AddRunDevFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&opts.ConfigurationFile, \"filename\", \"f\", \"skaffold.yaml\", \"Filename or URL to the pipeline file\")\n\tcmd.Flags().BoolVar(&opts.Notification, \"toot\", false, \"Emit a terminal beep after the deploy is complete\")\n\tcmd.Flags().StringArrayVarP(&opts.Profiles, \"profile\", \"p\", nil, \"Activate profiles by name\")\n\tcmd.Flags().StringVarP(&opts.Namespace, \"namespace\", \"n\", \"\", \"Run Helm deployments in the specified namespace\")\n}\n\nfunc AddFixFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&opts.ConfigurationFile, \"filename\", \"f\", \"skaffold.yaml\", \"Filename or URL to the pipeline file\")\n\tcmd.Flags().BoolVar(&overwrite, \"overwrite\", false, \"Overwrite original config with fixed config\")\n}\n\nfunc SetUpLogs(out io.Writer, level string) error {\n\tlogrus.SetOutput(out)\n\tlvl, err := logrus.ParseLevel(v)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"parsing log level\")\n\t}\n\tlogrus.SetLevel(lvl)\n\treturn nil\n}\n\nfunc readConfiguration(opts *config.SkaffoldOptions) (*config.SkaffoldConfig, error) {\n\tconfig, err := cmdutil.ParseConfig(opts.ConfigurationFile)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"parsing skaffold config\")\n\t}\n\terr = config.ApplyProfiles(opts.Profiles)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"applying profiles\")\n\t}\n\treturn config, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/containers\/buildah\/pkg\/unshare\"\n\t\"github.com\/containers\/image\/storage\"\n\t\"github.com\/containers\/image\/transports\/alltransports\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/syndtr\/gocapability\/capability\"\n)\n\nvar neededCapabilities = []capability.Cap{\n\tcapability.CAP_CHOWN,\n\tcapability.CAP_DAC_OVERRIDE,\n\tcapability.CAP_FOWNER,\n\tcapability.CAP_FSETID,\n\tcapability.CAP_MKNOD,\n\tcapability.CAP_SETFCAP,\n}\n\nfunc maybeReexec() error {\n\t\/\/ With Skopeo we need only the subset of the root capabilities necessary\n\t\/\/ for pulling an image to the storage.  Do not attempt to create a namespace\n\t\/\/ if we already have the capabilities we need.\n\tcapabilities, err := capability.NewPid(0)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error reading the current capabilities sets\")\n\t}\n\tfor _, cap := range neededCapabilities {\n\t\tif !capabilities.Get(capability.EFFECTIVE, cap) {\n\t\t\t\/\/ We miss a capability we need, create a user namespaces\n\t\t\tunshare.MaybeReexecUsingUserNamespace(true)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc reexecIfNecessaryForImages(imageNames ...string) error {\n\t\/\/ Check if container-storage are used before doing unshare\n\tfor _, imageName := range imageNames {\n\t\tif alltransports.TransportFromImageName(imageName).Name() == storage.Transport.Name() {\n\t\t\treturn maybeReexec()\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Skopeo crashes on any invalid transport<commit_after>package main\n\nimport (\n\t\"github.com\/containers\/buildah\/pkg\/unshare\"\n\t\"github.com\/containers\/image\/storage\"\n\t\"github.com\/containers\/image\/transports\/alltransports\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/syndtr\/gocapability\/capability\"\n)\n\nvar neededCapabilities = []capability.Cap{\n\tcapability.CAP_CHOWN,\n\tcapability.CAP_DAC_OVERRIDE,\n\tcapability.CAP_FOWNER,\n\tcapability.CAP_FSETID,\n\tcapability.CAP_MKNOD,\n\tcapability.CAP_SETFCAP,\n}\n\nfunc maybeReexec() error {\n\t\/\/ With Skopeo we need only the subset of the root capabilities necessary\n\t\/\/ for pulling an image to the storage.  Do not attempt to create a namespace\n\t\/\/ if we already have the capabilities we need.\n\tcapabilities, err := capability.NewPid(0)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"error reading the current capabilities sets\")\n\t}\n\tfor _, cap := range neededCapabilities {\n\t\tif !capabilities.Get(capability.EFFECTIVE, cap) {\n\t\t\t\/\/ We miss a capability we need, create a user namespaces\n\t\t\tunshare.MaybeReexecUsingUserNamespace(true)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc reexecIfNecessaryForImages(imageNames ...string) error {\n\t\/\/ Check if container-storage are used before doing unshare\n\tfor _, imageName := range imageNames {\n\t\ttransport := alltransports.TransportFromImageName(imageName)\n\t\tif transport != nil && transport.Name() == storage.Transport.Name() {\n\t\t\treturn maybeReexec()\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Supports Windows, Linux, Mac, and Raspberry Pi\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"crypto\"\n\t\"crypto\/rsa\"\n\t\"crypto\/sha256\"\n\t\"crypto\/x509\"\n\t\"encoding\/hex\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/arduino\/arduino-create-agent\/utilities\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/googollee\/go-socket.io\"\n)\n\ntype connection struct {\n\t\/\/ The websocket connection.\n\tws socketio.Socket\n\n\t\/\/ Buffered channel of outbound messages.\n\tsend     chan []byte\n\tincoming chan []byte\n}\n\nfunc (c *connection) writer() {\n\tfor message := range c.send {\n\t\terr := c.ws.Emit(\"message\", string(message))\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n\/\/ WsServer overrides socket.io server to set the CORS\ntype WsServer struct {\n\tServer *socketio.Server\n}\n\nfunc (s *WsServer) ServeHTTP(c *gin.Context) {\n\ts.Server.ServeHTTP(c.Writer, c.Request)\n}\n\ntype AdditionalFile struct {\n\tHex      []byte `json:\"hex\"`\n\tFilename string `json:\"filename\"`\n}\n\n\/\/ Upload contains the data to upload a sketch onto a board\ntype Upload struct {\n\tPort        string           `json:\"port\"`\n\tBoard       string           `json:\"board\"`\n\tRewrite     string           `json:\"rewrite\"`\n\tCommandline string           `json:\"commandline\"`\n\tSignature   string           `json:\"signature\"`\n\tExtra       boardExtraInfo   `json:\"extra\"`\n\tHex         []byte           `json:\"hex\"`\n\tFilename    string           `json:\"filename\"`\n\tExtraFiles  []AdditionalFile `json:\"extrafiles\"`\n}\n\nfunc uploadHandler(c *gin.Context) {\n\tdata := new(Upload)\n\tc.BindJSON(data)\n\n\tlog.Printf(\"%+v\", data)\n\n\tif data.Port == \"\" {\n\t\tc.String(http.StatusBadRequest, \"port is required\")\n\t\treturn\n\t}\n\n\tif data.Board == \"\" {\n\t\tc.String(http.StatusBadRequest, \"board is required\")\n\t\tlog.Error(\"board is required\")\n\t\treturn\n\t}\n\n\tif data.Extra.Network == false {\n\t\tif data.Signature == \"\" {\n\t\t\tc.String(http.StatusBadRequest, \"signature is required\")\n\t\t\treturn\n\t\t}\n\n\t\tif data.Commandline == \"\" {\n\t\t\tc.String(http.StatusBadRequest, \"commandline is required for local board\")\n\t\t\treturn\n\t\t}\n\n\t\terr := verifyCommandLine(data.Commandline, data.Signature)\n\n\t\tif err != nil {\n\t\t\tc.String(http.StatusBadRequest, \"signature is invalid\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tbuffer := bytes.NewBuffer(data.Hex)\n\n\tfilePath, err := utilities.SaveFileonTempDir(data.Filename, buffer)\n\tif err != nil {\n\t\tc.String(http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tfor _, extraFile := range data.ExtraFiles {\n\t\tioutil.WriteFile(filepath.Join(filepath.Dir(filePath), extraFile.Filename), extraFile.Hex, 0644)\n\t}\n\n\tif data.Rewrite != \"\" {\n\t\tdata.Board = data.Rewrite\n\t}\n\n\tgo spProgramRW(data.Port, data.Board, filePath, data.Commandline, data.Extra)\n\n\tc.String(http.StatusAccepted, \"\")\n}\n\nfunc verifyCommandLine(input string, signature string) error {\n\tsign, _ := hex.DecodeString(signature)\n\tblock, _ := pem.Decode([]byte(*signatureKey))\n\tif block == nil {\n\t\treturn errors.New(\"invalid key\")\n\t}\n\tkey, err := x509.ParsePKIXPublicKey(block.Bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\trsaKey := key.(*rsa.PublicKey)\n\th := sha256.New()\n\th.Write([]byte(input))\n\td := h.Sum(nil)\n\treturn rsa.VerifyPKCS1v15(rsaKey, crypto.SHA256, d, sign)\n}\n\nfunc wsHandler() *WsServer {\n\tserver, err := socketio.NewServer(nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tserver.On(\"connection\", func(so socketio.Socket) {\n\t\tc := &connection{send: make(chan []byte, 256*10), ws: so}\n\t\th.register <- c\n\t\tso.On(\"command\", func(message string) {\n\t\t\th.broadcast <- []byte(message)\n\t\t})\n\n\t\tso.On(\"disconnection\", func() {\n\t\t\th.unregister <- c\n\t\t})\n\t\tgo c.writer()\n\t})\n\tserver.On(\"error\", func(so socketio.Socket, err error) {\n\t\tlog.Println(\"error:\", err)\n\t})\n\n\twrapper := WsServer{\n\t\tServer: server,\n\t}\n\n\treturn &wrapper\n}\n<commit_msg>Add debug messages to understand what's going wrong with the zero upload<commit_after>\/\/ Supports Windows, Linux, Mac, and Raspberry Pi\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"crypto\"\n\t\"crypto\/rsa\"\n\t\"crypto\/sha256\"\n\t\"crypto\/x509\"\n\t\"encoding\/hex\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/arduino\/arduino-create-agent\/utilities\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/googollee\/go-socket.io\"\n)\n\ntype connection struct {\n\t\/\/ The websocket connection.\n\tws socketio.Socket\n\n\t\/\/ Buffered channel of outbound messages.\n\tsend     chan []byte\n\tincoming chan []byte\n}\n\nfunc (c *connection) writer() {\n\tfor message := range c.send {\n\t\terr := c.ws.Emit(\"message\", string(message))\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n\/\/ WsServer overrides socket.io server to set the CORS\ntype WsServer struct {\n\tServer *socketio.Server\n}\n\nfunc (s *WsServer) ServeHTTP(c *gin.Context) {\n\ts.Server.ServeHTTP(c.Writer, c.Request)\n}\n\ntype AdditionalFile struct {\n\tHex      []byte `json:\"hex\"`\n\tFilename string `json:\"filename\"`\n}\n\n\/\/ Upload contains the data to upload a sketch onto a board\ntype Upload struct {\n\tPort        string           `json:\"port\"`\n\tBoard       string           `json:\"board\"`\n\tRewrite     string           `json:\"rewrite\"`\n\tCommandline string           `json:\"commandline\"`\n\tSignature   string           `json:\"signature\"`\n\tExtra       boardExtraInfo   `json:\"extra\"`\n\tHex         []byte           `json:\"hex\"`\n\tFilename    string           `json:\"filename\"`\n\tExtraFiles  []AdditionalFile `json:\"extrafiles\"`\n}\n\nfunc uploadHandler(c *gin.Context) {\n\tdata := new(Upload)\n\tc.BindJSON(data)\n\n\tlog.Printf(\"%+v\", data)\n\n\tif data.Port == \"\" {\n\t\tc.String(http.StatusBadRequest, \"port is required\")\n\t\treturn\n\t}\n\n\tif data.Board == \"\" {\n\t\tc.String(http.StatusBadRequest, \"board is required\")\n\t\tlog.Error(\"board is required\")\n\t\treturn\n\t}\n\n\tif data.Extra.Network == false {\n\t\tif data.Signature == \"\" {\n\t\t\tc.String(http.StatusBadRequest, \"signature is required\")\n\t\t\treturn\n\t\t}\n\n\t\tif data.Commandline == \"\" {\n\t\t\tc.String(http.StatusBadRequest, \"commandline is required for local board\")\n\t\t\treturn\n\t\t}\n\n\t\terr := verifyCommandLine(data.Commandline, data.Signature)\n\n\t\tif err != nil {\n\t\t\tc.String(http.StatusBadRequest, \"signature is invalid\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tbuffer := bytes.NewBuffer(data.Hex)\n\n\tfilePath, err := utilities.SaveFileonTempDir(data.Filename, buffer)\n\tif err != nil {\n\t\tc.String(http.StatusBadRequest, err.Error())\n\t\treturn\n\t}\n\n\tfor _, extraFile := range data.ExtraFiles {\n\t\tpath := filepath.Join(filepath.Dir(filePath), extraFile.Filename)\n\t\tlog.Printf(\"Saving %s on %s\", extraFile.Filename, path)\n\t\terr := ioutil.WriteFile(path, extraFile.Hex, 0644)\n\t\tif err != nil {\n\t\t\tlog.Printf(err.Error())\n\t\t}\n\t}\n\n\tif data.Rewrite != \"\" {\n\t\tdata.Board = data.Rewrite\n\t}\n\n\tgo spProgramRW(data.Port, data.Board, filePath, data.Commandline, data.Extra)\n\n\tc.String(http.StatusAccepted, \"\")\n}\n\nfunc verifyCommandLine(input string, signature string) error {\n\tsign, _ := hex.DecodeString(signature)\n\tblock, _ := pem.Decode([]byte(*signatureKey))\n\tif block == nil {\n\t\treturn errors.New(\"invalid key\")\n\t}\n\tkey, err := x509.ParsePKIXPublicKey(block.Bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\trsaKey := key.(*rsa.PublicKey)\n\th := sha256.New()\n\th.Write([]byte(input))\n\td := h.Sum(nil)\n\treturn rsa.VerifyPKCS1v15(rsaKey, crypto.SHA256, d, sign)\n}\n\nfunc wsHandler() *WsServer {\n\tserver, err := socketio.NewServer(nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tserver.On(\"connection\", func(so socketio.Socket) {\n\t\tc := &connection{send: make(chan []byte, 256*10), ws: so}\n\t\th.register <- c\n\t\tso.On(\"command\", func(message string) {\n\t\t\th.broadcast <- []byte(message)\n\t\t})\n\n\t\tso.On(\"disconnection\", func() {\n\t\t\th.unregister <- c\n\t\t})\n\t\tgo c.writer()\n\t})\n\tserver.On(\"error\", func(so socketio.Socket, err error) {\n\t\tlog.Println(\"error:\", err)\n\t})\n\n\twrapper := WsServer{\n\t\tServer: server,\n\t}\n\n\treturn &wrapper\n}\n<|endoftext|>"}
{"text":"<commit_before>package fwk\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\ntype statuscode int\n\nfunc (sc statuscode) Error() string {\n\treturn fmt.Sprintf(\"fwk: error code [%d]\", int(sc))\n}\n\ntype Context interface {\n\tId() int64      \/\/ id of this context (e.g. entry number or some kind of event number)\n\tSlot() int      \/\/ slot number in the pool of event sequences\n\tStore() Store   \/\/ data store corresponding to the id+slot\n\tMsg() MsgStream \/\/ messaging for this context (id+slot)\n}\n\ntype Component interface {\n\tType() string \/\/ Type of the component (ex: \"github.com\/go-hep\/fads.MomentumSmearing\")\n\tName() string \/\/ Name of the component (ex: \"MyPropagator\")\n}\n\ntype ComponentMgr interface {\n\tComponent(n string) Component\n\tHasComponent(n string) bool\n\tComponents() []Component\n\tNew(t, n string) (Component, error)\n}\n\ntype Task interface {\n\tComponent\n\n\tStartTask(ctx Context) error\n\tProcess(ctx Context) error\n\tStopTask(ctx Context) error\n}\n\ntype TaskMgr interface {\n\tAddTask(tsk Task) error\n\tDelTask(tsk Task) error\n\tHasTask(n string) bool\n\tGetTask(n string) Task\n\tTasks() []Task\n}\n\ntype Configurer interface {\n\tComponent\n\tConfigure(ctx Context) error\n}\n\ntype Svc interface {\n\tComponent\n\n\tStartSvc(ctx Context) error\n\tStopSvc(ctx Context) error\n}\n\ntype SvcMgr interface {\n\tAddSvc(svc Svc) error\n\tDelSvc(svc Svc) error\n\tHasSvc(n string) bool\n\tGetSvc(n string) Svc\n\tSvcs() []Svc\n}\n\ntype App interface {\n\tComponent\n\tComponentMgr\n\tSvcMgr\n\tTaskMgr\n\tPropMgr\n\tPortMgr\n\n\tRun() error\n\n\tMsg() MsgStream\n}\n\ntype PropMgr interface {\n\tDeclProp(c Component, name string, ptr interface{}) error\n\tSetProp(c Component, name string, value interface{}) error\n\tGetProp(c Component, name string) (interface{}, error)\n\tHasProp(c Component, name string) bool\n}\n\ntype Property interface {\n\tDeclProp(name string, ptr interface{}) error\n\tSetProp(name string, value interface{}) error\n\tGetProp(name string) (interface{}, error)\n}\n\ntype Store interface {\n\tGet(key string) (interface{}, error)\n\tPut(key string, value interface{}) error\n\tHas(key string) bool\n}\n\n\/\/ Port holds the name and type of a data item in a store\ntype Port struct {\n\tName string\n\tType reflect.Type\n}\n\n\/\/ DeclPorter is the interface to declare input\/output ports for the data flow.\ntype DeclPorter interface {\n\tDeclInPort(name string, t reflect.Type) error\n\tDeclOutPort(name string, t reflect.Type) error\n}\n\n\/\/ PortMgr is the interface to manage input\/output ports for the data flow\ntype PortMgr interface {\n\tDeclInPort(c Component, name string, t reflect.Type) error\n\tDeclOutPort(c Component, name string, t reflect.Type) error\n}\n\ntype Level int\n\nconst (\n\t\/\/LvlVerbose Level = -20\n\tLvlDebug   Level = -10\n\tLvlInfo    Level = 0\n\tLvlWarning Level = 10\n\tLvlError   Level = 20\n)\n\nfunc (lvl Level) msgstring() string {\n\tswitch lvl {\n\tcase LvlDebug:\n\t\treturn \"DBG \"\n\tcase LvlInfo:\n\t\treturn \"INFO\"\n\tcase LvlWarning:\n\t\treturn \"WARN\"\n\tcase LvlError:\n\t\treturn \"ERR \"\n\t}\n\tpanic(Errorf(\"fwk.Level: invalid fwk.Level value [%d]\", int(lvl)))\n}\n\nfunc (lvl Level) String() string {\n\tswitch lvl {\n\tcase LvlDebug:\n\t\treturn \"DEBUG\"\n\tcase LvlInfo:\n\t\treturn \"INFO\"\n\tcase LvlWarning:\n\t\treturn \"WARN\"\n\tcase LvlError:\n\t\treturn \"ERROR\"\n\t}\n\tpanic(Errorf(\"fwk.Level: invalid fwk.Level value [%d]\", int(lvl)))\n}\n\ntype MsgStream interface {\n\tDebugf(format string, a ...interface{}) (int, error)\n\tInfof(format string, a ...interface{}) (int, error)\n\tWarnf(format string, a ...interface{}) (int, error)\n\tErrorf(format string, a ...interface{}) (int, error)\n\n\tMsg(lvl Level, format string, a ...interface{}) (int, error)\n}\n\n\/\/ Deleter prepares values to be GC-reclaimed\ntype Deleter interface {\n\tDelete() error\n}\n\n\/\/ EOF\n<commit_msg>core: doc for Component<commit_after>package fwk\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\ntype statuscode int\n\nfunc (sc statuscode) Error() string {\n\treturn fmt.Sprintf(\"fwk: error code [%d]\", int(sc))\n}\n\ntype Context interface {\n\tId() int64      \/\/ id of this context (e.g. entry number or some kind of event number)\n\tSlot() int      \/\/ slot number in the pool of event sequences\n\tStore() Store   \/\/ data store corresponding to the id+slot\n\tMsg() MsgStream \/\/ messaging for this context (id+slot)\n}\n\n\/\/ Component is the interface satisfied by all values in fwk.\n\/\/\n\/\/ A component can be asked for:\n\/\/ its Type() (ex: \"github.com\/go-hep\/fads.MomentumSmearing\")\n\/\/ its Name() (ex: \"MyPropagator\")\ntype Component interface {\n\tType() string \/\/ Type of the component (ex: \"github.com\/go-hep\/fads.MomentumSmearing\")\n\tName() string \/\/ Name of the component (ex: \"MyPropagator\")\n}\n\ntype ComponentMgr interface {\n\tComponent(n string) Component\n\tHasComponent(n string) bool\n\tComponents() []Component\n\tNew(t, n string) (Component, error)\n}\n\ntype Task interface {\n\tComponent\n\n\tStartTask(ctx Context) error\n\tProcess(ctx Context) error\n\tStopTask(ctx Context) error\n}\n\ntype TaskMgr interface {\n\tAddTask(tsk Task) error\n\tDelTask(tsk Task) error\n\tHasTask(n string) bool\n\tGetTask(n string) Task\n\tTasks() []Task\n}\n\ntype Configurer interface {\n\tComponent\n\tConfigure(ctx Context) error\n}\n\ntype Svc interface {\n\tComponent\n\n\tStartSvc(ctx Context) error\n\tStopSvc(ctx Context) error\n}\n\ntype SvcMgr interface {\n\tAddSvc(svc Svc) error\n\tDelSvc(svc Svc) error\n\tHasSvc(n string) bool\n\tGetSvc(n string) Svc\n\tSvcs() []Svc\n}\n\ntype App interface {\n\tComponent\n\tComponentMgr\n\tSvcMgr\n\tTaskMgr\n\tPropMgr\n\tPortMgr\n\n\tRun() error\n\n\tMsg() MsgStream\n}\n\ntype PropMgr interface {\n\tDeclProp(c Component, name string, ptr interface{}) error\n\tSetProp(c Component, name string, value interface{}) error\n\tGetProp(c Component, name string) (interface{}, error)\n\tHasProp(c Component, name string) bool\n}\n\ntype Property interface {\n\tDeclProp(name string, ptr interface{}) error\n\tSetProp(name string, value interface{}) error\n\tGetProp(name string) (interface{}, error)\n}\n\ntype Store interface {\n\tGet(key string) (interface{}, error)\n\tPut(key string, value interface{}) error\n\tHas(key string) bool\n}\n\n\/\/ Port holds the name and type of a data item in a store\ntype Port struct {\n\tName string\n\tType reflect.Type\n}\n\n\/\/ DeclPorter is the interface to declare input\/output ports for the data flow.\ntype DeclPorter interface {\n\tDeclInPort(name string, t reflect.Type) error\n\tDeclOutPort(name string, t reflect.Type) error\n}\n\n\/\/ PortMgr is the interface to manage input\/output ports for the data flow\ntype PortMgr interface {\n\tDeclInPort(c Component, name string, t reflect.Type) error\n\tDeclOutPort(c Component, name string, t reflect.Type) error\n}\n\ntype Level int\n\nconst (\n\t\/\/LvlVerbose Level = -20\n\tLvlDebug   Level = -10\n\tLvlInfo    Level = 0\n\tLvlWarning Level = 10\n\tLvlError   Level = 20\n)\n\nfunc (lvl Level) msgstring() string {\n\tswitch lvl {\n\tcase LvlDebug:\n\t\treturn \"DBG \"\n\tcase LvlInfo:\n\t\treturn \"INFO\"\n\tcase LvlWarning:\n\t\treturn \"WARN\"\n\tcase LvlError:\n\t\treturn \"ERR \"\n\t}\n\tpanic(Errorf(\"fwk.Level: invalid fwk.Level value [%d]\", int(lvl)))\n}\n\nfunc (lvl Level) String() string {\n\tswitch lvl {\n\tcase LvlDebug:\n\t\treturn \"DEBUG\"\n\tcase LvlInfo:\n\t\treturn \"INFO\"\n\tcase LvlWarning:\n\t\treturn \"WARN\"\n\tcase LvlError:\n\t\treturn \"ERROR\"\n\t}\n\tpanic(Errorf(\"fwk.Level: invalid fwk.Level value [%d]\", int(lvl)))\n}\n\ntype MsgStream interface {\n\tDebugf(format string, a ...interface{}) (int, error)\n\tInfof(format string, a ...interface{}) (int, error)\n\tWarnf(format string, a ...interface{}) (int, error)\n\tErrorf(format string, a ...interface{}) (int, error)\n\n\tMsg(lvl Level, format string, a ...interface{}) (int, error)\n}\n\n\/\/ Deleter prepares values to be GC-reclaimed\ntype Deleter interface {\n\tDelete() error\n}\n\n\/\/ EOF\n<|endoftext|>"}
{"text":"<commit_before>package godatai18n\n\nimport (\n\t\"database\/sql\/driver\"\n\t\"encoding\/json\"\n\t\"golang.org\/x\/net\/context\"\n\t\"golang.org\/x\/text\/language\"\n\t\"reflect\"\n)\n\n\/\/ Use struct field with this type to store translations\n\/\/ e.g. Translations{\"en\": map[string]string{\"name\": \"John\"}}\ntype Translations map[string]map[string]string\n\nfunc (m *Translations) Scan(value interface{}) error {\n\treturn json.Unmarshal(value.([]byte), m)\n}\n\nfunc (m Translations) Value() (driver.Value, error) {\n\tb, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn string(b), nil\n}\n\nfunc translateField(field reflect.Value, name string, translations Translations, targetLanguages []language.Tag) {\n\tlangs := []language.Tag{}\n\tenFound := false\n\tfor lang, tr := range translations {\n\t\t_, ok := tr[name]\n\t\tif ok {\n\t\t\t\/\/ First language in langs will be fallback option for matcher\n\t\t\t\/\/ but map order is not stable,\n\t\t\t\/\/ so we need to move en to front, if it's available\n\t\t\tif lang == \"en\" {\n\t\t\t\tenFound = true\n\t\t\t} else {\n\t\t\t\tlangs = append(langs, language.Make(lang))\n\t\t\t}\n\t\t}\n\t}\n\tif enFound {\n\t\tlangs = append([]language.Tag{language.Make(\"en\")}, langs...)\n\t}\n\n\teffectiveLang, _, _ := language.NewMatcher(langs).Match(targetLanguages...)\n\tfield.SetString(translations[effectiveLang.String()][name])\n}\n\nfunc TranslateOne(ctx context.Context, target interface{}) {\n\tmeta := metas.getStructMeta(target)\n\tif len(meta.fields) == 0 {\n\t\treturn\n\t}\n\n\tstructValue := reflect.ValueOf(target)\n\tif structValue.Kind() == reflect.Ptr {\n\t\tstructValue = structValue.Elem()\n\t}\n\n\ttranslations, ok := structValue.FieldByName(\"Translations\").Interface().(Translations)\n\tif !ok || len(translations) == 0 {\n\t\treturn\n\t}\n\n\ttargetLanguages, ok := FromContext(ctx)\n\tif !ok || len(targetLanguages) == 0 {\n\t\ttargetLanguages = []language.Tag{language.English}\n\t}\n\n\tfor _, trF := range meta.fields {\n\t\tf := structValue.FieldByName(trF.name)\n\t\tif f.IsValid() && f.CanSet() && f.Kind() == reflect.String {\n\t\t\ttranslateField(f, trF.key, translations, targetLanguages)\n\t\t}\n\t}\n}\n\nfunc TranslateMany(ctx context.Context, targets interface{}) {\n\tv := reflect.ValueOf(targets)\n\n\tfor i := 0; i < v.Len(); i++ {\n\t\tTranslateOne(ctx, v.Index(i).Interface())\n\t}\n}\n<commit_msg>Speedup by caching matchers (-95% time)<commit_after>package godatai18n\n\nimport (\n\t\"database\/sql\/driver\"\n\t\"encoding\/json\"\n\t\"golang.org\/x\/net\/context\"\n\t\"golang.org\/x\/text\/language\"\n\t\"reflect\"\n\t\"sync\"\n)\n\n\/\/ Use struct field with this type to store translations\n\/\/ e.g. Translations{\"en\": map[string]string{\"name\": \"John\"}}\ntype Translations map[string]map[string]string\n\nfunc (m *Translations) Scan(value interface{}) error {\n\treturn json.Unmarshal(value.([]byte), m)\n}\n\nfunc (m Translations) Value() (driver.Value, error) {\n\tb, err := json.Marshal(m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn string(b), nil\n}\n\nvar matchers = map[string]language.Matcher{}\nvar matchersMutex sync.RWMutex\n\nfunc getMatcher(fieldName string, translations Translations) language.Matcher {\n\tlangs := []language.Tag{}\n\tenFound := false\n\tfor lang, tr := range translations {\n\t\t_, ok := tr[fieldName]\n\t\tif ok {\n\t\t\t\/\/ First language in langs will be fallback option for matcher\n\t\t\t\/\/ but map order is not stable,\n\t\t\t\/\/ so we need to move en to front, if it's available\n\t\t\tif lang == \"en\" {\n\t\t\t\tenFound = true\n\t\t\t} else {\n\t\t\t\tlangs = append(langs, language.Make(lang))\n\t\t\t}\n\t\t}\n\t}\n\tif enFound {\n\t\tlangs = append([]language.Tag{language.Make(\"en\")}, langs...)\n\t}\n\n\tlangsKey := \"\"\n\tfor _, lang := range langs {\n\t\tlangsKey += lang.String()\n\t}\n\n\tmatchersMutex.RLock()\n\tmatcher, ok := matchers[langsKey]\n\tmatchersMutex.RUnlock()\n\n\tif ok {\n\t\treturn matcher\n\t}\n\n\tmatcher = language.NewMatcher(langs)\n\n\tmatchersMutex.Lock()\n\tmatchers[langsKey] = matcher\n\tmatchersMutex.Unlock()\n\n\treturn matcher\n}\n\nfunc translateField(field reflect.Value, fieldName string, translations Translations, targetLanguages []language.Tag) {\n\tmatcher := getMatcher(fieldName, translations)\n\teffectiveLang, _, _ := matcher.Match(targetLanguages...)\n\tfield.SetString(translations[effectiveLang.String()][fieldName])\n}\n\nfunc TranslateOne(ctx context.Context, target interface{}) {\n\tmeta := metas.getStructMeta(target)\n\tif len(meta.fields) == 0 {\n\t\treturn\n\t}\n\n\tstructValue := reflect.ValueOf(target)\n\tif structValue.Kind() == reflect.Ptr {\n\t\tstructValue = structValue.Elem()\n\t}\n\n\ttranslations, ok := structValue.FieldByName(\"Translations\").Interface().(Translations)\n\tif !ok || len(translations) == 0 {\n\t\treturn\n\t}\n\n\ttargetLanguages, ok := FromContext(ctx)\n\tif !ok || len(targetLanguages) == 0 {\n\t\ttargetLanguages = []language.Tag{language.English}\n\t}\n\n\tfor _, trF := range meta.fields {\n\t\tf := structValue.FieldByName(trF.name)\n\t\tif f.IsValid() && f.CanSet() && f.Kind() == reflect.String {\n\t\t\ttranslateField(f, trF.key, translations, targetLanguages)\n\t\t}\n\t}\n}\n\nfunc TranslateMany(ctx context.Context, targets interface{}) {\n\tv := reflect.ValueOf(targets)\n\n\tfor i := 0; i < v.Len(); i++ {\n\t\tTranslateOne(ctx, v.Index(i).Interface())\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package kraken\n\nimport (\n\t\"errors\"\n\t\"io\"\n\n\t\"code.google.com\/p\/go.crypto\/ssh\"\n)\n\nvar ErrNoMoreCommands = errors.New(\"No More Commands\")\n\ntype jobStatus int\n\nconst (\n\tJOB_NO_MORE_COMMANDS jobStatus = iota\n\tJOB_REMOTE_CONNECTION_CLOSED\n)\n\n\/\/ Commander will receive terminal output and be asked what to do next\n\/\/ by calling NextCommand until ErrNoMoreCommands is returned.\ntype Commander interface {\n\tNextCommand() ([]byte, error)\n\tio.Writer\n}\n\ntype Job struct {\n\tsshclient  sshClient\n\tcommander  Commander\n\tstatusChan chan jobStatus\n}\n\nfunc NewJob(addr string, conf *ssh.ClientConfig, c Commander) *Job {\n\tjob := Job{}\n\tjob.sshclient = sshClient{address: addr, config: conf}\n\tjob.commander = c\n\treturn &job\n}\n\n\/\/ Start connects using the provided SSH details and reads\/writes\n\/\/ data over the connection. It also returns a channel to read\n\/\/ job status messages from.\nfunc (job *Job) Start() (<-chan jobStatus, error) {\n\tif err := job.sshclient.Connect(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := job.startCommandLoop(); err != nil {\n\t\treturn nil, err\n\t}\n\tjob.statusChan = make(chan jobStatus)\n\treturn job.statusChan, nil\n}\n\nfunc (job *Job) startCommandLoop() error {\n\tgo func() {\n\t\tbuffer := make([]byte, 100)\n\t\tfor n, err := job.sshclient.Read(buffer); err == nil || n > 0; n, err = job.sshclient.Read(buffer) {\n\t\t\t_, cerr := job.commander.Write(buffer[:n])\n\t\t\tif cerr != nil {\n\t\t\t\tprint(cerr)\n\t\t\t}\n\t\t}\n\t\tjob.statusChan <- JOB_REMOTE_CONNECTION_CLOSED\n\t}()\n\tgo func() {\n\t\tfor command, err := job.commander.NextCommand(); err != ErrNoMoreCommands; command, err = job.commander.NextCommand() {\n\t\t\tjob.sshclient.Write(command)\n\t\t}\n\t\tjob.statusChan <- JOB_NO_MORE_COMMANDS\n\t}()\n\treturn nil\n}\n\n\/\/ Complete is used to tell the job that it can perform cleanup\n\/\/ like closing the shh connection.\nfunc (job *Job) Complete() error {\n\treturn job.sshclient.Close()\n}\n<commit_msg>Temporary solution<commit_after>package kraken\n\nimport (\n\t\"errors\"\n\t\"io\"\n\n\t\"code.google.com\/p\/go.crypto\/ssh\"\n)\n\nvar ErrNoMoreCommands = errors.New(\"No More Commands\")\n\ntype jobStatus int\n\nconst (\n\tJOB_NO_MORE_COMMANDS jobStatus = iota\n\tJOB_REMOTE_CONNECTION_CLOSED\n)\n\n\/\/ Commander will receive terminal output and be asked what to do next\n\/\/ by calling NextCommand until ErrNoMoreCommands is returned.\ntype Commander interface {\n\tNextCommand() ([]byte, error)\n\tio.Writer\n}\n\ntype Job struct {\n\tsshclient  sshClient\n\tcommander  Commander\n\tstatusChan chan jobStatus\n}\n\nfunc NewJob(addr string, conf *ssh.ClientConfig, c Commander) *Job {\n\tjob := Job{}\n\tjob.sshclient = sshClient{address: addr, config: conf}\n\tjob.commander = c\n\treturn &job\n}\n\n\/\/ Start connects using the provided SSH details and reads\/writes\n\/\/ data over the connection. It also returns a channel to read\n\/\/ job status messages from.\nfunc (job *Job) Start() (<-chan jobStatus, error) {\n\tif err := job.sshclient.Connect(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := job.startCommandLoop(); err != nil {\n\t\treturn nil, err\n\t}\n\tjob.statusChan = make(chan jobStatus)\n\treturn job.statusChan, nil\n}\n\nfunc (job *Job) startCommandLoop() error {\n\tgo func() {\n\t\tbuffer := make([]byte, 100)\n\t\tfor n, err := job.sshclient.Read(buffer); err == nil || n > 0; n, err = job.sshclient.Read(buffer) {\n\t\t\t_, cerr := job.commander.Write(buffer[:n])\n\t\t\tif cerr != nil {\n\t\t\t\tprint(cerr)\n\t\t\t}\n\t\t}\n\t\tjob.statusChan <- JOB_REMOTE_CONNECTION_CLOSED\n\t}()\n\tgo func() {\n\t\tfor command, err := job.commander.NextCommand(); err != ErrNoMoreCommands; command, err = job.commander.NextCommand() {\n\t\t\tjob.sshclient.Write(command)\n\t\t}\n\t\tjob.statusChan <- JOB_NO_MORE_COMMANDS\n\t}()\n\treturn nil\n}\n\n\/\/ Complete is used to tell the job that it can perform cleanup\n\/\/ like closing the shh connection.\nfunc (job *Job) Complete() error {\n\tdefer close(job.statusChan)\n\treturn job.sshclient.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>package schema\n\nimport (\n\t\"math\"\n\t\"testing\"\n\n\t\"github.com\/matryer\/is\"\n)\n\nconst notBareNumber = false\n\nfunc TestCastNumber(t *testing.T) {\n\tt.Run(\"Success\", func(t *testing.T) {\n\t\tdata := []struct {\n\t\t\tdesc   string\n\t\t\tnumber string\n\t\t\twant   float64\n\t\t\tdc     string\n\t\t\tgc     string\n\t\t\tbn     bool\n\t\t}{\n\t\t\t{\"Positive_WithSignal\", \"+10.10\", 10.10, defaultDecimalChar, defaultGroupChar, defaultBareNumber},\n\t\t\t{\"Positive_WithoutSignal\", \"10.10\", 10.10, defaultDecimalChar, defaultGroupChar, defaultBareNumber},\n\t\t\t{\"Negative\", \"-10.10\", -10.10, defaultDecimalChar, defaultGroupChar, defaultBareNumber},\n\t\t\t{\"BareNumber\", \"€95\", 95, defaultDecimalChar, defaultGroupChar, notBareNumber},\n\t\t\t{\"BareNumber_TrailingAtBeginning\", \"€95\", 95, defaultDecimalChar, defaultGroupChar, notBareNumber},\n\t\t\t{\"BareNumber_TrailingAtBeginningSpace\", \"EUR 95\", 95, defaultDecimalChar, defaultGroupChar, notBareNumber},\n\t\t\t{\"BareNumber_TrailingAtEnd\", \"95%\", 95, defaultDecimalChar, defaultGroupChar, notBareNumber},\n\t\t\t{\"BareNumber_TrailingAtEndSpace\", \"95 %\", 95, defaultDecimalChar, defaultGroupChar, notBareNumber},\n\t\t\t{\"GroupChar\", \"100,000\", 100000, defaultDecimalChar, defaultGroupChar, defaultBareNumber},\n\t\t\t{\"DecimalChar\", \"95;10\", 95.10, \";\", defaultGroupChar, defaultBareNumber},\n\t\t\t{\"Mix\", \"EUR 95;10\", 95.10, \";\", \";\", notBareNumber},\n\t\t}\n\t\tfor _, d := range data {\n\t\t\tt.Run(d.desc, func(t *testing.T) {\n\t\t\t\tis := is.New(t)\n\t\t\t\tgot, err := castNumber(d.dc, d.gc, d.bn, d.number, Constraints{})\n\t\t\t\tis.NoErr(err)\n\t\t\t\tis.Equal(d.want, got)\n\t\t\t})\n\t\t}\n\t})\n\tt.Run(\"NaN\", func(t *testing.T) {\n\t\tis := is.New(t)\n\t\tgot, err := castNumber(defaultDecimalChar, defaultGroupChar, defaultBareNumber, \"NaN\", Constraints{})\n\t\tis.NoErr(err)\n\t\tis.True(math.IsNaN(got))\n\t})\n\tt.Run(\"INF\", func(t *testing.T) {\n\t\tis := is.New(t)\n\t\tgot, err := castNumber(defaultDecimalChar, defaultGroupChar, defaultBareNumber, \"INF\", Constraints{})\n\t\tis.NoErr(err)\n\t\tis.True(math.IsInf(got, 1))\n\t})\n\tt.Run(\"NegativeINF\", func(t *testing.T) {\n\t\tis := is.New(t)\n\t\tgot, err := castNumber(defaultDecimalChar, defaultGroupChar, defaultBareNumber, \"-INF\", Constraints{})\n\t\tis.NoErr(err)\n\t\tis.True(math.IsInf(got, -1))\n\t})\n\tt.Run(\"ValidMaximum\", func(t *testing.T) {\n\t\tis := is.New(t)\n\t\t_, err := castNumber(defaultDecimalChar, defaultGroupChar, defaultBareNumber, \"2\", Constraints{Maximum: \"2\"})\n\t\tis.NoErr(err)\n\t})\n\tt.Run(\"ValidMinimum\", func(t *testing.T) {\n\t\tis := is.New(t)\n\t\t_, err := castNumber(defaultDecimalChar, defaultGroupChar, defaultBareNumber, \"2\", Constraints{Minimum: \"2\"})\n\t\tis.NoErr(err)\n\t})\n\tt.Run(\"Error\", func(t *testing.T) {\n\t\tdata := []struct {\n\t\t\tdesc        string\n\t\t\tnumber      string\n\t\t\tdc          string\n\t\t\tgc          string\n\t\t\tbn          bool\n\t\t\tconstraints Constraints\n\t\t}{\n\t\t\t{\"InvalidNumberToStrip_TooManyNumbers\", \"+10.10++10\", defaultDecimalChar, defaultGroupChar, notBareNumber, Constraints{}},\n\t\t\t{\"NumBiggerThanMaximum\", \"3\", defaultDecimalChar, defaultGroupChar, notBareNumber, Constraints{Maximum: \"2\"}},\n\t\t\t{\"InvalidMaximum\", \"1\", defaultDecimalChar, defaultGroupChar, notBareNumber, Constraints{Maximum: \"boo\"}},\n\t\t\t{\"NumSmallerThanMinimum\", \"1\", defaultDecimalChar, defaultGroupChar, notBareNumber, Constraints{Minimum: \"2\"}},\n\t\t\t{\"InvalidMinimum\", \"1\", defaultDecimalChar, defaultGroupChar, notBareNumber, Constraints{Minimum: \"boo\"}},\n\t\t}\n\t\tfor _, d := range data {\n\t\t\tt.Run(d.desc, func(t *testing.T) {\n\t\t\t\tis := is.New(t)\n\t\t\t\t_, err := castNumber(defaultDecimalChar, defaultGroupChar, defaultBareNumber, d.number, d.constraints)\n\t\t\t\tis.True(err != nil)\n\t\t\t})\n\t\t}\n\t})\n}\n<commit_msg>Add default decimal test cases.<commit_after>package schema\n\nimport (\n\t\"math\"\n\t\"testing\"\n\n\t\"github.com\/matryer\/is\"\n)\n\nconst notBareNumber = false\n\nfunc TestCastNumber(t *testing.T) {\n\tt.Run(\"Success\", func(t *testing.T) {\n\t\tdata := []struct {\n\t\t\tdesc   string\n\t\t\tnumber string\n\t\t\twant   float64\n\t\t\tdc     string\n\t\t\tgc     string\n\t\t\tbn     bool\n\t\t}{\n\t\t\t{\"Positive_WithSignal\", \"+10.10\", 10.10, defaultDecimalChar, defaultGroupChar, defaultBareNumber},\n\t\t\t{\"Positive_WithoutSignal\", \"10.10\", 10.10, defaultDecimalChar, defaultGroupChar, defaultBareNumber},\n\t\t\t{\"Negative\", \"-10.10\", -10.10, defaultDecimalChar, defaultGroupChar, defaultBareNumber},\n\t\t\t{\"BareNumber\", \"€95\", 95, defaultDecimalChar, defaultGroupChar, notBareNumber},\n\t\t\t{\"BareNumber_TrailingAtBeginning\", \"€95\", 95, defaultDecimalChar, defaultGroupChar, notBareNumber},\n\t\t\t{\"BareNumber_TrailingAtBeginningSpace\", \"EUR 95\", 95, defaultDecimalChar, defaultGroupChar, notBareNumber},\n\t\t\t{\"BareNumber_TrailingAtEnd\", \"95%\", 95, defaultDecimalChar, defaultGroupChar, notBareNumber},\n\t\t\t{\"BareNumber_TrailingAtEndSpace\", \"95 %\", 95, defaultDecimalChar, defaultGroupChar, notBareNumber},\n\t\t\t{\"GroupChar\", \"100,000\", 100000, defaultDecimalChar, defaultGroupChar, defaultBareNumber},\n\t\t\t{\"DecimalChar\", \"95;10\", 95.10, \";\", defaultGroupChar, defaultBareNumber},\n\t\t\t{\"DecimalCharDefault\", \"95.10\", 95.10, \"\", defaultGroupChar, defaultBareNumber},\n\t\t\t{\"Mix\", \"EUR 95;10\", 95.10, \";\", \";\", notBareNumber},\n\t\t}\n\t\tfor _, d := range data {\n\t\t\tt.Run(d.desc, func(t *testing.T) {\n\t\t\t\tis := is.New(t)\n\t\t\t\tgot, err := castNumber(d.dc, d.gc, d.bn, d.number, Constraints{})\n\t\t\t\tis.NoErr(err)\n\t\t\t\tis.Equal(d.want, got)\n\t\t\t})\n\t\t}\n\t})\n\tt.Run(\"NaN\", func(t *testing.T) {\n\t\tis := is.New(t)\n\t\tgot, err := castNumber(defaultDecimalChar, defaultGroupChar, defaultBareNumber, \"NaN\", Constraints{})\n\t\tis.NoErr(err)\n\t\tis.True(math.IsNaN(got))\n\t})\n\tt.Run(\"INF\", func(t *testing.T) {\n\t\tis := is.New(t)\n\t\tgot, err := castNumber(defaultDecimalChar, defaultGroupChar, defaultBareNumber, \"INF\", Constraints{})\n\t\tis.NoErr(err)\n\t\tis.True(math.IsInf(got, 1))\n\t})\n\tt.Run(\"NegativeINF\", func(t *testing.T) {\n\t\tis := is.New(t)\n\t\tgot, err := castNumber(defaultDecimalChar, defaultGroupChar, defaultBareNumber, \"-INF\", Constraints{})\n\t\tis.NoErr(err)\n\t\tis.True(math.IsInf(got, -1))\n\t})\n\tt.Run(\"ValidMaximum\", func(t *testing.T) {\n\t\tis := is.New(t)\n\t\t_, err := castNumber(defaultDecimalChar, defaultGroupChar, defaultBareNumber, \"2\", Constraints{Maximum: \"2\"})\n\t\tis.NoErr(err)\n\t})\n\tt.Run(\"ValidMinimum\", func(t *testing.T) {\n\t\tis := is.New(t)\n\t\t_, err := castNumber(defaultDecimalChar, defaultGroupChar, defaultBareNumber, \"2\", Constraints{Minimum: \"2\"})\n\t\tis.NoErr(err)\n\t})\n\tt.Run(\"Error\", func(t *testing.T) {\n\t\tdata := []struct {\n\t\t\tdesc        string\n\t\t\tnumber      string\n\t\t\tdc          string\n\t\t\tgc          string\n\t\t\tbn          bool\n\t\t\tconstraints Constraints\n\t\t}{\n\t\t\t{\"InvalidNumberToStrip_TooManyNumbers\", \"+10.10++10\", defaultDecimalChar, defaultGroupChar, notBareNumber, Constraints{}},\n\t\t\t{\"NumBiggerThanMaximum\", \"3\", defaultDecimalChar, defaultGroupChar, notBareNumber, Constraints{Maximum: \"2\"}},\n\t\t\t{\"InvalidMaximum\", \"1\", defaultDecimalChar, defaultGroupChar, notBareNumber, Constraints{Maximum: \"boo\"}},\n\t\t\t{\"NumSmallerThanMinimum\", \"1\", defaultDecimalChar, defaultGroupChar, notBareNumber, Constraints{Minimum: \"2\"}},\n\t\t\t{\"InvalidMinimum\", \"1\", defaultDecimalChar, defaultGroupChar, notBareNumber, Constraints{Minimum: \"boo\"}},\n\t\t\t{\"DecimalCharDefault\", \"95;10\", \"\", defaultGroupChar, defaultBareNumber, Constraints{}},\n\t\t}\n\t\tfor _, d := range data {\n\t\t\tt.Run(d.desc, func(t *testing.T) {\n\t\t\t\tis := is.New(t)\n\t\t\t\t_, err := castNumber(defaultDecimalChar, defaultGroupChar, defaultBareNumber, d.number, d.constraints)\n\t\t\t\tis.True(err != nil)\n\t\t\t})\n\t\t}\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package schema\n\nimport \"testing\"\n\n\/\/ To be in par with the python library.\nfunc TestDecodeString_URIMustRequireScheme(t *testing.T) {\n\tif _, err := decodeString(stringURI, \"google.com\", Constraints{}); err == nil {\n\t\tt.Errorf(\"want:err got:nil\")\n\t}\n}\n\nfunc TestDecodeString_InvalidUUIDVersion(t *testing.T) {\n\t\/\/ This is a uuid3: namespace DNS and python.org.\n\tif _, err := decodeString(stringUUID, \"6fa459ea-ee8a-3ca4-894e-db77e160355e\", Constraints{}); err == nil {\n\t\tt.Errorf(\"want:err got:nil\")\n\t}\n}\n\nfunc TestDecodeString_ErrorCheckingConstraints(t *testing.T) {\n\tdata := []struct {\n\t\tdesc        string\n\t\tvalue       string\n\t\tformat      string\n\t\tconstraints Constraints\n\t}{\n\t\t{\"InvalidMinLength_UUID\", \"6fa459ea-ee8a-3ca4-894e-db77e160355e\", stringUUID, Constraints{MinLength: 100}},\n\t\t{\"InvalidMinLength_Email\", \"foo@bar.com\", stringEmail, Constraints{MinLength: 100}},\n\t\t{\"InvalidMinLength_URI\", \"http:\/\/google.com\", stringURI, Constraints{MinLength: 100}},\n\t\t{\"InvalidMaxLength_UUID\", \"6fa459ea-ee8a-3ca4-894e-db77e160355e\", stringUUID, Constraints{MaxLength: 1}},\n\t\t{\"InvalidMaxLength_Email\", \"foo@bar.com\", stringEmail, Constraints{MaxLength: 1}},\n\t\t{\"InvalidMaxLength_URI\", \"http:\/\/google.com\", stringURI, Constraints{MaxLength: 1}},\n\t\t{\"InvalidPattern_UUID\", \"6fa459ea-ee8a-3ca4-894e-db77e160355e\", stringUUID, Constraints{Pattern: \"^[0-9a-f]{1}-.*\"}},\n\t\t{\"InvalidPattern_Email\", \"foo@bar.com\", stringEmail, Constraints{Pattern: \"[0-9].*\"}},\n\t\t{\"InvalidPattern_URI\", \"http:\/\/google.com\", stringURI, Constraints{Pattern: \"^\/\/.*\"}},\n\t}\n\tfor _, d := range data {\n\t\tt.Run(d.desc, func(t *testing.T) {\n\t\t\tif _, err := decodeString(d.format, d.value, d.constraints); err == nil {\n\t\t\t\tt.Fatalf(\"err want:err got:nil\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDecodeString_Success(t *testing.T) {\n\tvar data = []struct {\n\t\tdesc        string\n\t\tvalue       string\n\t\tformat      string\n\t\tconstraints Constraints\n\t}{\n\t\t{\"URI\", \"http:\/\/google.com\", stringURI, Constraints{MinLength: 1, Pattern: \"^http:\/\/.*\"}},\n\t\t{\"Email\", \"foo@bar.com\", stringEmail, Constraints{MinLength: 1, Pattern: \".*@.*\"}},\n\t\t{\"UUID\", \"C56A4180-65AA-42EC-A945-5FD21DEC0538\", stringUUID, Constraints{MinLength: 36, MaxLength: 36, Pattern: \"[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{8}\"}},\n\t}\n\tfor _, d := range data {\n\t\tt.Run(d.desc, func(t *testing.T) {\n\t\t\tv, err := decodeString(d.format, d.value, d.constraints)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"want:nil got:%q\", err)\n\t\t\t}\n\t\t\tif v != d.value {\n\t\t\t\tt.Errorf(\"want:%s got:%s\", d.value, v)\n\t\t\t}\n\t\t})\n\t}\n}\n<commit_msg>add testing for invalid pattern of regexp<commit_after>package schema\n\nimport \"testing\"\n\n\/\/ To be in par with the python library.\nfunc TestDecodeString_URIMustRequireScheme(t *testing.T) {\n\tif _, err := decodeString(stringURI, \"google.com\", Constraints{}); err == nil {\n\t\tt.Errorf(\"want:err got:nil\")\n\t}\n}\n\nfunc TestDecodeString_InvalidUUIDVersion(t *testing.T) {\n\t\/\/ This is a uuid3: namespace DNS and python.org.\n\tif _, err := decodeString(stringUUID, \"6fa459ea-ee8a-3ca4-894e-db77e160355e\", Constraints{}); err == nil {\n\t\tt.Errorf(\"want:err got:nil\")\n\t}\n}\n\nfunc TestDecodeString_ErrorCheckingConstraints(t *testing.T) {\n\tdata := []struct {\n\t\tdesc        string\n\t\tvalue       string\n\t\tformat      string\n\t\tconstraints Constraints\n\t}{\n\t\t{\"InvalidMinLength_UUID\", \"6fa459ea-ee8a-3ca4-894e-db77e160355e\", stringUUID, Constraints{MinLength: 100}},\n\t\t{\"InvalidMinLength_Email\", \"foo@bar.com\", stringEmail, Constraints{MinLength: 100}},\n\t\t{\"InvalidMinLength_URI\", \"http:\/\/google.com\", stringURI, Constraints{MinLength: 100}},\n\t\t{\"InvalidMaxLength_UUID\", \"6fa459ea-ee8a-3ca4-894e-db77e160355e\", stringUUID, Constraints{MaxLength: 1}},\n\t\t{\"InvalidMaxLength_Email\", \"foo@bar.com\", stringEmail, Constraints{MaxLength: 1}},\n\t\t{\"InvalidMaxLength_URI\", \"http:\/\/google.com\", stringURI, Constraints{MaxLength: 1}},\n\t\t{\"InvalidPattern_UUID\", \"6fa459ea-ee8a-3ca4-894e-db77e160355e\", stringUUID, Constraints{Pattern: \"^[0-9a-f]{1}-.*\"}},\n\t\t{\"InvalidPattern_Email\", \"foo@bar.com\", stringEmail, Constraints{Pattern: \"[0-9].*\"}},\n\t\t{\"InvalidPattern_URI\", \"http:\/\/google.com\", stringURI, Constraints{Pattern: \"^\/\/.*\"}},\n\t\t{\"InvalidPattern\", \"http:\/\/google.com\", stringURI, Constraints{Pattern: \"\\\\\"}},\n\t}\n\tfor _, d := range data {\n\t\tt.Run(d.desc, func(t *testing.T) {\n\t\t\tif _, err := decodeString(d.format, d.value, d.constraints); err == nil {\n\t\t\t\tt.Fatalf(\"err want:err got:nil\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDecodeString_Success(t *testing.T) {\n\tvar data = []struct {\n\t\tdesc        string\n\t\tvalue       string\n\t\tformat      string\n\t\tconstraints Constraints\n\t}{\n\t\t{\"URI\", \"http:\/\/google.com\", stringURI, Constraints{MinLength: 1, Pattern: \"^http:\/\/.*\"}},\n\t\t{\"Email\", \"foo@bar.com\", stringEmail, Constraints{MinLength: 1, Pattern: \".*@.*\"}},\n\t\t{\"UUID\", \"C56A4180-65AA-42EC-A945-5FD21DEC0538\", stringUUID, Constraints{MinLength: 36, MaxLength: 36, Pattern: \"[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{8}\"}},\n\t}\n\tfor _, d := range data {\n\t\tt.Run(d.desc, func(t *testing.T) {\n\t\t\tv, err := decodeString(d.format, d.value, d.constraints)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"want:nil got:%q\", err)\n\t\t\t}\n\t\t\tif v != d.value {\n\t\t\t\tt.Errorf(\"want:%s got:%s\", d.value, v)\n\t\t\t}\n\t\t})\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"net\/rpc\"\n\t\"net\/rpc\/jsonrpc\"\n\n\t\"github.com\/gopherjs\/gopherjs\/js\"\n\t\"github.com\/gopherjs\/websocket\"\n)\n\nvar jrpc *rpc.Client\n\nfunc rpcInit() error {\n\tconn, err := websocket.Dial(\"ws:\/\/\" + js.Global.Get(\"location\").Get(\"host\").String() + \"\/rpc\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tcloseOnExit(conn)\n\tjrpc = jsonrpc.NewClient(conn)\n\treturn nil\n}\n\nfunc ServerName() (string, error) {\n\tvar name string\n\terr := jrpc.Call(\"Server.Name\", nil, &name)\n\treturn name, err\n}\n\ntype Server struct {\n\tName string\n}\n\nfunc ServerList() ([]Server, error) {\n\tvar list []Server\n\terr := jrpc.Call(\"Server.List\", nil, &list)\n\treturn list, err\n}\n<commit_msg>Added MapList<commit_after>package main\n\nimport (\n\t\"net\/rpc\"\n\t\"net\/rpc\/jsonrpc\"\n\n\t\"github.com\/gopherjs\/gopherjs\/js\"\n\t\"github.com\/gopherjs\/websocket\"\n)\n\nvar jrpc *rpc.Client\n\nfunc rpcInit() error {\n\tconn, err := websocket.Dial(\"ws:\/\/\" + js.Global.Get(\"location\").Get(\"host\").String() + \"\/rpc\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tcloseOnExit(conn)\n\tjrpc = jsonrpc.NewClient(conn)\n\treturn nil\n}\n\nfunc ServerName() (string, error) {\n\tvar name string\n\terr := jrpc.Call(\"Server.Name\", nil, &name)\n\treturn name, err\n}\n\ntype Server struct {\n\tName string\n}\n\nfunc ServerList() ([]Server, error) {\n\tvar list []Server\n\terr := jrpc.Call(\"Server.List\", nil, &list)\n\treturn list, err\n}\n\ntype Map struct {\n\tName string\n}\n\nfunc MapList() ([]Map, error) {\n\tvar list []Server\n\terr := jrpc.Call(\"Server.Maps\", nil, &list)\n\treturn list, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The etcd Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage command\n\nimport (\n\t\"encoding\/binary\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"time\"\n\n\t\"github.com\/coreos\/etcd\/client\"\n\tetcdErr \"github.com\/coreos\/etcd\/error\"\n\t\"github.com\/coreos\/etcd\/etcdserver\"\n\tpb \"github.com\/coreos\/etcd\/etcdserver\/etcdserverpb\"\n\t\"github.com\/coreos\/etcd\/mvcc\"\n\t\"github.com\/coreos\/etcd\/mvcc\/backend\"\n\t\"github.com\/coreos\/etcd\/mvcc\/mvccpb\"\n\t\"github.com\/coreos\/etcd\/pkg\/pbutil\"\n\t\"github.com\/coreos\/etcd\/raft\/raftpb\"\n\t\"github.com\/coreos\/etcd\/snap\"\n\t\"github.com\/coreos\/etcd\/store\"\n\t\"github.com\/coreos\/etcd\/wal\"\n\t\"github.com\/coreos\/etcd\/wal\/walpb\"\n\t\"github.com\/gogo\/protobuf\/proto\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tmigrateDatadir     string\n\tmigrateWALdir      string\n\tmigrateTransformer string\n)\n\n\/\/ NewMigrateCommand returns the cobra command for \"migrate\".\nfunc NewMigrateCommand() *cobra.Command {\n\tmc := &cobra.Command{\n\t\tUse:   \"migrate\",\n\t\tShort: \"Migrates keys in a v2 store to a mvcc store\",\n\t\tRun:   migrateCommandFunc,\n\t}\n\n\tmc.Flags().StringVar(&migrateDatadir, \"data-dir\", \"\", \"Path to the data directory\")\n\tmc.Flags().StringVar(&migrateWALdir, \"wal-dir\", \"\", \"Path to the WAL directory\")\n\tmc.Flags().StringVar(&migrateTransformer, \"transformer\", \"\", \"Path to the user-provided transformer program\")\n\treturn mc\n}\n\nfunc migrateCommandFunc(cmd *cobra.Command, args []string) {\n\tvar (\n\t\twriter io.WriteCloser\n\t\treader io.ReadCloser\n\t\terrc   chan error\n\t)\n\tif migrateTransformer != \"\" {\n\t\twriter, reader, errc = startTransformer()\n\t} else {\n\t\tfmt.Println(\"using default transformer\")\n\t\twriter, reader, errc = defaultTransformer()\n\t}\n\n\tst := rebuildStoreV2()\n\tbe := prepareBackend()\n\tdefer be.Close()\n\n\tmaxIndexc := make(chan uint64, 1)\n\tgo func() {\n\t\tmaxIndexc <- writeStore(writer, st)\n\t\twriter.Close()\n\t}()\n\n\treadKeys(reader, be)\n\tmvcc.UpdateConsistentIndex(be, <-maxIndexc)\n\terr := <-errc\n\tif err != nil {\n\t\tfmt.Println(\"failed to transform keys\")\n\t\tExitWithError(ExitError, err)\n\t}\n\n\tfmt.Println(\"finished transforming keys\")\n}\n\nfunc prepareBackend() backend.Backend {\n\tdbpath := path.Join(migrateDatadir, \"member\", \"snap\", \"db\")\n\tbe := backend.New(dbpath, time.Second, 10000)\n\ttx := be.BatchTx()\n\ttx.Lock()\n\ttx.UnsafeCreateBucket([]byte(\"key\"))\n\ttx.UnsafeCreateBucket([]byte(\"meta\"))\n\ttx.Unlock()\n\treturn be\n}\n\nfunc rebuildStoreV2() store.Store {\n\twaldir := migrateWALdir\n\tif len(waldir) == 0 {\n\t\twaldir = path.Join(migrateDatadir, \"member\", \"wal\")\n\t}\n\tsnapdir := path.Join(migrateDatadir, \"member\", \"snap\")\n\n\tss := snap.New(snapdir)\n\tsnapshot, err := ss.Load()\n\tif err != nil && err != snap.ErrNoSnapshot {\n\t\tExitWithError(ExitError, err)\n\t}\n\n\tvar walsnap walpb.Snapshot\n\tif snapshot != nil {\n\t\twalsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term\n\t}\n\n\tw, err := wal.OpenForRead(waldir, walsnap)\n\tif err != nil {\n\t\tExitWithError(ExitError, err)\n\t}\n\tdefer w.Close()\n\n\t_, _, ents, err := w.ReadAll()\n\tif err != nil {\n\t\tExitWithError(ExitError, err)\n\t}\n\n\tst := store.New()\n\tif snapshot != nil {\n\t\terr := st.Recovery(snapshot.Data)\n\t\tif err != nil {\n\t\t\tExitWithError(ExitError, err)\n\t\t}\n\t}\n\n\tapplier := etcdserver.NewApplierV2(st, nil)\n\tfor _, ent := range ents {\n\t\tif ent.Type != raftpb.EntryNormal {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar raftReq pb.InternalRaftRequest\n\t\tif !pbutil.MaybeUnmarshal(&raftReq, ent.Data) { \/\/ backward compatible\n\t\t\tvar r pb.Request\n\t\t\tpbutil.MustUnmarshal(&r, ent.Data)\n\t\t\tapplyRequest(&r, applier)\n\t\t} else {\n\t\t\tif raftReq.V2 != nil {\n\t\t\t\treq := raftReq.V2\n\t\t\t\tapplyRequest(req, applier)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn st\n}\n\nfunc applyRequest(r *pb.Request, applyV2 etcdserver.ApplierV2) {\n\ttoTTLOptions(r)\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tapplyV2.Post(r)\n\tcase \"PUT\":\n\t\tapplyV2.Put(r)\n\tcase \"DELETE\":\n\t\tapplyV2.Delete(r)\n\tcase \"QGET\":\n\t\tapplyV2.QGet(r)\n\tcase \"SYNC\":\n\t\tapplyV2.Sync(r)\n\tdefault:\n\t\tpanic(\"unknown command\")\n\t}\n}\n\nfunc toTTLOptions(r *pb.Request) store.TTLOptionSet {\n\trefresh, _ := pbutil.GetBool(r.Refresh)\n\tttlOptions := store.TTLOptionSet{Refresh: refresh}\n\tif r.Expiration != 0 {\n\t\tttlOptions.ExpireTime = time.Unix(0, r.Expiration)\n\t}\n\treturn ttlOptions\n}\n\nfunc writeStore(w io.Writer, st store.Store) uint64 {\n\tall, err := st.Get(\"\/1\", true, true)\n\tif err != nil {\n\t\tif eerr, ok := err.(*etcdErr.Error); ok && eerr.ErrorCode == etcdErr.EcodeKeyNotFound {\n\t\t\tfmt.Println(\"no v2 keys to migrate\")\n\t\t\tos.Exit(0)\n\t\t}\n\t\tExitWithError(ExitError, err)\n\t}\n\treturn writeKeys(w, all.Node)\n}\n\nfunc writeKeys(w io.Writer, n *store.NodeExtern) uint64 {\n\tmaxIndex := n.ModifiedIndex\n\n\tnodes := n.Nodes\n\t\/\/ remove store v2 bucket prefix\n\tn.Key = n.Key[2:]\n\tif n.Key == \"\" {\n\t\tn.Key = \"\/\"\n\t}\n\tif n.Dir {\n\t\tn.Nodes = nil\n\t}\n\tb, err := json.Marshal(n)\n\tif err != nil {\n\t\tExitWithError(ExitError, err)\n\t}\n\tfmt.Fprintf(w, string(b))\n\tfor _, nn := range nodes {\n\t\tmax := writeKeys(w, nn)\n\t\tif max > maxIndex {\n\t\t\tmaxIndex = max\n\t\t}\n\t}\n\treturn maxIndex\n}\n\nfunc readKeys(r io.Reader, be backend.Backend) error {\n\tfor {\n\t\tlength64, err := readInt64(r)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\tbuf := make([]byte, int(length64))\n\t\tif _, err = io.ReadFull(r, buf); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar kv mvccpb.KeyValue\n\t\terr = proto.Unmarshal(buf, &kv)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmvcc.WriteKV(be, kv)\n\t}\n}\n\nfunc readInt64(r io.Reader) (int64, error) {\n\tvar n int64\n\terr := binary.Read(r, binary.LittleEndian, &n)\n\treturn n, err\n}\n\nfunc startTransformer() (io.WriteCloser, io.ReadCloser, chan error) {\n\tcmd := exec.Command(migrateTransformer)\n\tcmd.Stderr = os.Stderr\n\n\twriter, err := cmd.StdinPipe()\n\tif err != nil {\n\t\tExitWithError(ExitError, err)\n\t}\n\n\treader, rerr := cmd.StdoutPipe()\n\tif rerr != nil {\n\t\tExitWithError(ExitError, rerr)\n\t}\n\n\tif err := cmd.Start(); err != nil {\n\t\tExitWithError(ExitError, err)\n\t}\n\n\terrc := make(chan error, 1)\n\n\tgo func() {\n\t\terrc <- cmd.Wait()\n\t}()\n\n\treturn writer, reader, errc\n}\n\nfunc defaultTransformer() (io.WriteCloser, io.ReadCloser, chan error) {\n\t\/\/ transformer decodes v2 keys from sr\n\tsr, sw := io.Pipe()\n\t\/\/ transformer encodes v3 keys into dw\n\tdr, dw := io.Pipe()\n\n\tdecoder := json.NewDecoder(sr)\n\n\terrc := make(chan error, 1)\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\tsr.Close()\n\t\t\tdw.Close()\n\t\t}()\n\n\t\tfor decoder.More() {\n\t\t\tnode := &client.Node{}\n\t\t\tif err := decoder.Decode(node); err != nil {\n\t\t\t\terrc <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tkv := transform(node)\n\t\t\tif kv == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdata, err := proto.Marshal(kv)\n\t\t\tif err != nil {\n\t\t\t\terrc <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tbuf := make([]byte, 8)\n\t\t\tbinary.LittleEndian.PutUint64(buf, uint64(len(data)))\n\t\t\tif _, err := dw.Write(buf); err != nil {\n\t\t\t\terrc <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif _, err := dw.Write(data); err != nil {\n\t\t\t\terrc <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\terrc <- nil\n\t}()\n\n\treturn sw, dr, errc\n}\n\nfunc transform(n *client.Node) *mvccpb.KeyValue {\n\tconst unKnownVersion = 1\n\tif n.Dir {\n\t\treturn nil\n\t}\n\tkv := &mvccpb.KeyValue{\n\t\tKey:            []byte(n.Key),\n\t\tValue:          []byte(n.Value),\n\t\tCreateRevision: int64(n.CreatedIndex),\n\t\tModRevision:    int64(n.ModifiedIndex),\n\t\tVersion:        unKnownVersion,\n\t}\n\treturn kv\n}\n<commit_msg>etcdctl: fix migrate in outputing client.Node to json<commit_after>\/\/ Copyright 2016 The etcd Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage command\n\nimport (\n\t\"encoding\/binary\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"time\"\n\n\t\"github.com\/coreos\/etcd\/client\"\n\tetcdErr \"github.com\/coreos\/etcd\/error\"\n\t\"github.com\/coreos\/etcd\/etcdserver\"\n\tpb \"github.com\/coreos\/etcd\/etcdserver\/etcdserverpb\"\n\t\"github.com\/coreos\/etcd\/mvcc\"\n\t\"github.com\/coreos\/etcd\/mvcc\/backend\"\n\t\"github.com\/coreos\/etcd\/mvcc\/mvccpb\"\n\t\"github.com\/coreos\/etcd\/pkg\/pbutil\"\n\t\"github.com\/coreos\/etcd\/raft\/raftpb\"\n\t\"github.com\/coreos\/etcd\/snap\"\n\t\"github.com\/coreos\/etcd\/store\"\n\t\"github.com\/coreos\/etcd\/wal\"\n\t\"github.com\/coreos\/etcd\/wal\/walpb\"\n\t\"github.com\/gogo\/protobuf\/proto\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tmigrateDatadir     string\n\tmigrateWALdir      string\n\tmigrateTransformer string\n)\n\n\/\/ NewMigrateCommand returns the cobra command for \"migrate\".\nfunc NewMigrateCommand() *cobra.Command {\n\tmc := &cobra.Command{\n\t\tUse:   \"migrate\",\n\t\tShort: \"Migrates keys in a v2 store to a mvcc store\",\n\t\tRun:   migrateCommandFunc,\n\t}\n\n\tmc.Flags().StringVar(&migrateDatadir, \"data-dir\", \"\", \"Path to the data directory\")\n\tmc.Flags().StringVar(&migrateWALdir, \"wal-dir\", \"\", \"Path to the WAL directory\")\n\tmc.Flags().StringVar(&migrateTransformer, \"transformer\", \"\", \"Path to the user-provided transformer program\")\n\treturn mc\n}\n\nfunc migrateCommandFunc(cmd *cobra.Command, args []string) {\n\tvar (\n\t\twriter io.WriteCloser\n\t\treader io.ReadCloser\n\t\terrc   chan error\n\t)\n\tif migrateTransformer != \"\" {\n\t\twriter, reader, errc = startTransformer()\n\t} else {\n\t\tfmt.Println(\"using default transformer\")\n\t\twriter, reader, errc = defaultTransformer()\n\t}\n\n\tst := rebuildStoreV2()\n\tbe := prepareBackend()\n\tdefer be.Close()\n\n\tmaxIndexc := make(chan uint64, 1)\n\tgo func() {\n\t\tmaxIndexc <- writeStore(writer, st)\n\t\twriter.Close()\n\t}()\n\n\treadKeys(reader, be)\n\tmvcc.UpdateConsistentIndex(be, <-maxIndexc)\n\terr := <-errc\n\tif err != nil {\n\t\tfmt.Println(\"failed to transform keys\")\n\t\tExitWithError(ExitError, err)\n\t}\n\n\tfmt.Println(\"finished transforming keys\")\n}\n\nfunc prepareBackend() backend.Backend {\n\tdbpath := path.Join(migrateDatadir, \"member\", \"snap\", \"db\")\n\tbe := backend.New(dbpath, time.Second, 10000)\n\ttx := be.BatchTx()\n\ttx.Lock()\n\ttx.UnsafeCreateBucket([]byte(\"key\"))\n\ttx.UnsafeCreateBucket([]byte(\"meta\"))\n\ttx.Unlock()\n\treturn be\n}\n\nfunc rebuildStoreV2() store.Store {\n\twaldir := migrateWALdir\n\tif len(waldir) == 0 {\n\t\twaldir = path.Join(migrateDatadir, \"member\", \"wal\")\n\t}\n\tsnapdir := path.Join(migrateDatadir, \"member\", \"snap\")\n\n\tss := snap.New(snapdir)\n\tsnapshot, err := ss.Load()\n\tif err != nil && err != snap.ErrNoSnapshot {\n\t\tExitWithError(ExitError, err)\n\t}\n\n\tvar walsnap walpb.Snapshot\n\tif snapshot != nil {\n\t\twalsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term\n\t}\n\n\tw, err := wal.OpenForRead(waldir, walsnap)\n\tif err != nil {\n\t\tExitWithError(ExitError, err)\n\t}\n\tdefer w.Close()\n\n\t_, _, ents, err := w.ReadAll()\n\tif err != nil {\n\t\tExitWithError(ExitError, err)\n\t}\n\n\tst := store.New()\n\tif snapshot != nil {\n\t\terr := st.Recovery(snapshot.Data)\n\t\tif err != nil {\n\t\t\tExitWithError(ExitError, err)\n\t\t}\n\t}\n\n\tapplier := etcdserver.NewApplierV2(st, nil)\n\tfor _, ent := range ents {\n\t\tif ent.Type != raftpb.EntryNormal {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar raftReq pb.InternalRaftRequest\n\t\tif !pbutil.MaybeUnmarshal(&raftReq, ent.Data) { \/\/ backward compatible\n\t\t\tvar r pb.Request\n\t\t\tpbutil.MustUnmarshal(&r, ent.Data)\n\t\t\tapplyRequest(&r, applier)\n\t\t} else {\n\t\t\tif raftReq.V2 != nil {\n\t\t\t\treq := raftReq.V2\n\t\t\t\tapplyRequest(req, applier)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn st\n}\n\nfunc applyRequest(r *pb.Request, applyV2 etcdserver.ApplierV2) {\n\ttoTTLOptions(r)\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tapplyV2.Post(r)\n\tcase \"PUT\":\n\t\tapplyV2.Put(r)\n\tcase \"DELETE\":\n\t\tapplyV2.Delete(r)\n\tcase \"QGET\":\n\t\tapplyV2.QGet(r)\n\tcase \"SYNC\":\n\t\tapplyV2.Sync(r)\n\tdefault:\n\t\tpanic(\"unknown command\")\n\t}\n}\n\nfunc toTTLOptions(r *pb.Request) store.TTLOptionSet {\n\trefresh, _ := pbutil.GetBool(r.Refresh)\n\tttlOptions := store.TTLOptionSet{Refresh: refresh}\n\tif r.Expiration != 0 {\n\t\tttlOptions.ExpireTime = time.Unix(0, r.Expiration)\n\t}\n\treturn ttlOptions\n}\n\nfunc writeStore(w io.Writer, st store.Store) uint64 {\n\tall, err := st.Get(\"\/1\", true, true)\n\tif err != nil {\n\t\tif eerr, ok := err.(*etcdErr.Error); ok && eerr.ErrorCode == etcdErr.EcodeKeyNotFound {\n\t\t\tfmt.Println(\"no v2 keys to migrate\")\n\t\t\tos.Exit(0)\n\t\t}\n\t\tExitWithError(ExitError, err)\n\t}\n\treturn writeKeys(w, all.Node)\n}\n\nfunc writeKeys(w io.Writer, n *store.NodeExtern) uint64 {\n\tmaxIndex := n.ModifiedIndex\n\n\tnodes := n.Nodes\n\t\/\/ remove store v2 bucket prefix\n\tn.Key = n.Key[2:]\n\tif n.Key == \"\" {\n\t\tn.Key = \"\/\"\n\t}\n\tif n.Dir {\n\t\tn.Nodes = nil\n\t}\n\tb, err := json.Marshal(n)\n\tif err != nil {\n\t\tExitWithError(ExitError, err)\n\t}\n\tfmt.Fprint(w, string(b))\n\tfor _, nn := range nodes {\n\t\tmax := writeKeys(w, nn)\n\t\tif max > maxIndex {\n\t\t\tmaxIndex = max\n\t\t}\n\t}\n\treturn maxIndex\n}\n\nfunc readKeys(r io.Reader, be backend.Backend) error {\n\tfor {\n\t\tlength64, err := readInt64(r)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\tbuf := make([]byte, int(length64))\n\t\tif _, err = io.ReadFull(r, buf); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar kv mvccpb.KeyValue\n\t\terr = proto.Unmarshal(buf, &kv)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tmvcc.WriteKV(be, kv)\n\t}\n}\n\nfunc readInt64(r io.Reader) (int64, error) {\n\tvar n int64\n\terr := binary.Read(r, binary.LittleEndian, &n)\n\treturn n, err\n}\n\nfunc startTransformer() (io.WriteCloser, io.ReadCloser, chan error) {\n\tcmd := exec.Command(migrateTransformer)\n\tcmd.Stderr = os.Stderr\n\n\twriter, err := cmd.StdinPipe()\n\tif err != nil {\n\t\tExitWithError(ExitError, err)\n\t}\n\n\treader, rerr := cmd.StdoutPipe()\n\tif rerr != nil {\n\t\tExitWithError(ExitError, rerr)\n\t}\n\n\tif err := cmd.Start(); err != nil {\n\t\tExitWithError(ExitError, err)\n\t}\n\n\terrc := make(chan error, 1)\n\n\tgo func() {\n\t\terrc <- cmd.Wait()\n\t}()\n\n\treturn writer, reader, errc\n}\n\nfunc defaultTransformer() (io.WriteCloser, io.ReadCloser, chan error) {\n\t\/\/ transformer decodes v2 keys from sr\n\tsr, sw := io.Pipe()\n\t\/\/ transformer encodes v3 keys into dw\n\tdr, dw := io.Pipe()\n\n\tdecoder := json.NewDecoder(sr)\n\n\terrc := make(chan error, 1)\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\tsr.Close()\n\t\t\tdw.Close()\n\t\t}()\n\n\t\tfor decoder.More() {\n\t\t\tnode := &client.Node{}\n\t\t\tif err := decoder.Decode(node); err != nil {\n\t\t\t\terrc <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tkv := transform(node)\n\t\t\tif kv == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdata, err := proto.Marshal(kv)\n\t\t\tif err != nil {\n\t\t\t\terrc <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tbuf := make([]byte, 8)\n\t\t\tbinary.LittleEndian.PutUint64(buf, uint64(len(data)))\n\t\t\tif _, err := dw.Write(buf); err != nil {\n\t\t\t\terrc <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif _, err := dw.Write(data); err != nil {\n\t\t\t\terrc <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\terrc <- nil\n\t}()\n\n\treturn sw, dr, errc\n}\n\nfunc transform(n *client.Node) *mvccpb.KeyValue {\n\tconst unKnownVersion = 1\n\tif n.Dir {\n\t\treturn nil\n\t}\n\tkv := &mvccpb.KeyValue{\n\t\tKey:            []byte(n.Key),\n\t\tValue:          []byte(n.Value),\n\t\tCreateRevision: int64(n.CreatedIndex),\n\t\tModRevision:    int64(n.ModifiedIndex),\n\t\tVersion:        unKnownVersion,\n\t}\n\treturn kv\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Andreas Koch. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage themefiles\n\nconst ScreenCss = `\nhtml {\n    font-size: 100%;\n    overflow-y: scroll;\n    -webkit-text-size-adjust: 100%;\n    -ms-text-size-adjust: 100%;\n}\n\nbody {\n    color: #444;\n    font-family: Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', \"Hiragino Sans GB\", \"STXihei\", \"微软雅黑\", serif;\n    font-size: 12px;\n    line-height: 1.5em;\n    background: #fefefe;\n    width: 75%;\n    margin: 10px auto;\n    padding: 1em;\n    outline: 1300px solid #FAFAFA;\n}\n\nbody>nav {\n    font-size: 0.8em;\n}\n\nbody>nav>ul.breadcrumb {\n    list-style: none;\n    margin: 0;\n    padding: 0;\n}\n\nbody>nav>ul.breadcrumb>li {\n    display: inline;\n}\n\nbody>nav>ul.breadcrumb>li:after {\n    content: \">\";\n}\n\nbody>nav>ul.breadcrumb>li:last-child:after {\n    content: \"\";\n}\n\na {\n    color: #0645ad;\n    text-decoration: none;\n}\n\na:visited {\n    color: #0b0080;\n}\n\na:hover {\n    color: #06e;\n}\n\na:active {\n    color: #faa700;\n}\n\na:focus {\n    outline: thin dotted;\n}\n\na:hover, a:active {\n    outline: 0;\n}\n\nspan.backtick {\n    border: 1px solid #EAEAEA;\n    border-radius: 3px;\n    background: #F8F8F8;\n    padding: 0 3px 0 3px;\n}\n\n::-moz-selection {\n    background: rgba(255,255,0,0.3);\n    color: #000;\n}\n\n::selection {\n    background: rgba(255,255,0,0.3);\n    color: #000;\n}\n\na::-moz-selection {\n    background: rgba(255,255,0,0.3);\n    color: #0645ad;\n}\n\na::selection {\n    background: rgba(255,255,0,0.3);\n    color: #0645ad;\n}\n\np {\n    margin: 1em 0;\n}\n\nimg {\n    max-width: 100%;\n}\n\nh1,h2,h3,h4,h5,h6 {\n    font-weight: normal;\n    color: #111;\n    line-height: 1em;\n}\n\nh4,h5,h6 {\n    font-weight: bold;\n}\n\nh1 {\n    font-size: 2.5em;\n    margin: 0 0 15px 0;\n}\n\nh2 {\n    font-size: 2em;\n    border-bottom: 1px solid silver;\n    padding-bottom: 5px;\n}\n\nh3 {\n    font-size: 1.5em;\n}\n\nh4 {\n    font-size: 1.2em;\n}\n\nh5 {\n    font-size: 1em;\n}\n\nh6 {\n    font-size: 0.9em;\n}\n\nblockquote {\n    color: #666666;\n    margin: 0;\n    padding-left: 3em;\n    border-left: 0.5em #EEE solid;\n}\n\nhr {\n    display: block;\n    height: 2px;\n    border: 0;\n    border-top: 1px solid #aaa;\n    border-bottom: 1px solid #eee;\n    margin: 1em 0;\n    padding: 0;\n}\n\npre , code, kbd, samp {\n    color: #000;\n    font-family: monospace;\n    font-size: 0.88em;\n    border-radius: 3px;\n    background-color: #F8F8F8;\n    border: 1px solid #CCC;\n}\n\npre {\n    white-space: pre;\n    white-space: pre-wrap;\n    word-wrap: break-word;\n    padding: 5px 12px;\n}\n\npre code {\n    border: 0px !important;\n    padding: 0;\n}\n\ncode {\n    padding: 0 3px 0 3px;\n}\n\nb, strong {\n    font-weight: bold;\n}\n\ndfn {\n    font-style: italic;\n}\n\nins {\n    background: #ff9;\n    color: #000;\n    text-decoration: none;\n}\n\nmark {\n    background: #ff0;\n    color: #000;\n    font-style: italic;\n    font-weight: bold;\n}\n\nsub, sup {\n    font-size: 75%;\n    line-height: 0;\n    position: relative;\n    vertical-align: baseline;\n}\n\nsup {\n    top: -0.5em;\n}\n\nsub {\n    bottom: -0.25em;\n}\n\nul, ol {\n    margin: 1em 0;\n    padding: 0 0 0 2em;\n}\n\nli p:last-child {\n    margin: 0;\n}\n\ndd {\n    margin: 0 0 0 2em;\n}\n\nimg {\n    border: 0;\n    -ms-interpolation-mode: bicubic;\n    vertical-align: middle;\n}\n\ntable {\n    border-collapse: collapse;\n    border-spacing: 0;\n}\n\ntd {\n    vertical-align: top;\n}\n\narticle>.description {\n    font-size: 1.2em;\n}\n\n.subentries {\n    list-style: none;\n    padding: 5px 0 5px 0;\n    margin: 0 0 0 15px;\n}\n\n.subentries>.subentry {\n    margin: 0 0 15px 0;\n}\n\n.subentries>.subentry:nth-child(odd) {\n    background-color:#eee;\n}\n\n.subentries>.subentry:nth-child(even) {\n    background-color:transparent;\n}\n\n.imagegallery>h1 {\n    font-size: 1.2em;\n}\n\n.imagegallery ol {\n    list-style: none;\n    margin-left: 0;\n}\n\n.filelinks>h1 {\n    font-size: 1.2em;\n}\n\n.filelinks ol {\n    margin-left: 0;\n}\n\n.collection>h1 {\n    font-size: 1.2em;\n}\n\n.csv {\n    margin: 20px 0 0 20px;\n    overflow: auto;\n}\n\n.csv>h1 {\n    font-size: 1.2em;\n}\n\n.csv>table\n{\n    font-family: \"Lucida Sans Unicode\", \"Lucida Grande\", Sans-Serif;\n    font-size: 1.0em;\n    margin: 10px 45px 10px 45px;\n    text-align: left;\n    border-collapse: collapse;\n    border: 1px solid #69c;\n}\n\n.csv>table thead\n{\n    padding: 12px 17px 12px 17px;\n    font-weight: normal;\n    font-size: 1.2em;\n    color: #039;\n    border-bottom: 1px dashed #69c;\n}\n\n.csv>table td\n{\n    padding: 7px 17px 7px 17px;\n    color: #669;\n}\n\n.csv>table tbody tr:hover td\n{\n    color: #339;\n    background: #d0dafd;\n}\n\n.pdf {\n    width: 80%;\n    max-height: 80%;\n}\n\n.pdf>h1 {\n    font-size: 1.2em;\n}\n\n.pdf .metadata {\n    float: left;\n    font-size: 1.0em;\n    margin: 0 15px 0 0;\n}\n\n.pdf .metadata .entry {\n    margin: 0 0 10px 0;\n}\n\n.pdf .previewarea {\n    display: block;\n    overflow: auto;\n    box-shadow: 0 0 10px #000000;\n}\n\n.pdf .previewarea canvas {\n    float: none;\n}\n\n.video>h1 {\n    font-size: 1.2em;\n}\n\n.audio>h1 {\n    font-size: 1.2em;\n}\n\n.presentation nav {\n    float: left;\n    margin: 25px 0 15px 0;\n    width: 100%;\n    text-align: center;\n}\n\n.presentation nav .controls {\n    float: left;\n}\n\n.presentation nav .pager {\n    display: inline;\n    cursor: default;\n}\n\n.presentation nav .jumper {\n    float: right;\n}\n\n.presentation .content {\n    clear: left;\n}\n\n.presentation .slide {\n    float: none;\n    box-shadow: 0 0 10px #000000;\n    padding: 10px;\n}\n\n@media only screen and (max-width: 480px) {\n    body {\n        font-size: 12px;\n        width: 95%;\n    }\n\n    .presentation nav {\n        margin: 25px 0 15px 0;\n        width: 100%;\n    }    \n\n    .presentation nav .pager {\n        float: right;\n    }    \n\n    .presentation nav .jumper {\n        display: none;\n    }    \n}\n\n@media only screen and (min-width: 480px) {\n    body {\n        font-size: 14px;\n        width: 95%;\n    }\n}\n\n@media only screen and (min-width: 768px) {\n    body {\n        font-size: 16px;\n        width: 95%;\n    }\n}\n\n@media only screen and (min-width: 1024px) {\n    body {\n        font-size: 16px;\n        width: 75%;\n    }\n}`\n<commit_msg> Updated the screen.css of the default theme to increase the min height for presentation slides<commit_after>\/\/ Copyright 2013 Andreas Koch. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage themefiles\n\nconst ScreenCss = `\nhtml {\n    height: 100%;\n    font-size: 100%;\n    overflow-y: scroll;\n    -webkit-text-size-adjust: 100%;\n    -ms-text-size-adjust: 100%;\n}\n\nbody {\n    color: #444;\n    font-family: Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', \"Hiragino Sans GB\", \"STXihei\", \"微软雅黑\", serif;\n    font-size: 12px;\n    line-height: 1.5em;\n    background: #fefefe;\n    width: 75%;\n    height: 100%;\n    margin: 10px auto;\n    padding: 1em;\n    outline: 1300px solid #FAFAFA;\n}\n\nbody>nav {\n    font-size: 0.8em;\n}\n\nbody>nav>ul.breadcrumb {\n    list-style: none;\n    margin: 0;\n    padding: 0;\n}\n\nbody>nav>ul.breadcrumb>li {\n    display: inline;\n}\n\nbody>nav>ul.breadcrumb>li:after {\n    content: \">\";\n}\n\nbody>nav>ul.breadcrumb>li:last-child:after {\n    content: \"\";\n}\n\na {\n    color: #0645ad;\n    text-decoration: none;\n}\n\na:visited {\n    color: #0b0080;\n}\n\na:hover {\n    color: #06e;\n}\n\na:active {\n    color: #faa700;\n}\n\na:focus {\n    outline: thin dotted;\n}\n\na:hover, a:active {\n    outline: 0;\n}\n\nspan.backtick {\n    border: 1px solid #EAEAEA;\n    border-radius: 3px;\n    background: #F8F8F8;\n    padding: 0 3px 0 3px;\n}\n\n::-moz-selection {\n    background: rgba(255,255,0,0.3);\n    color: #000;\n}\n\n::selection {\n    background: rgba(255,255,0,0.3);\n    color: #000;\n}\n\na::-moz-selection {\n    background: rgba(255,255,0,0.3);\n    color: #0645ad;\n}\n\na::selection {\n    background: rgba(255,255,0,0.3);\n    color: #0645ad;\n}\n\np {\n    margin: 1em 0;\n}\n\nimg {\n    max-width: 100%;\n}\n\nh1,h2,h3,h4,h5,h6 {\n    font-weight: normal;\n    color: #111;\n    line-height: 1em;\n}\n\nh4,h5,h6 {\n    font-weight: bold;\n}\n\nh1 {\n    font-size: 2.5em;\n    margin: 0 0 15px 0;\n}\n\nh2 {\n    font-size: 2em;\n    border-bottom: 1px solid silver;\n    padding-bottom: 5px;\n}\n\nh3 {\n    font-size: 1.5em;\n}\n\nh4 {\n    font-size: 1.2em;\n}\n\nh5 {\n    font-size: 1em;\n}\n\nh6 {\n    font-size: 0.9em;\n}\n\nblockquote {\n    color: #666666;\n    margin: 0;\n    padding-left: 3em;\n    border-left: 0.5em #EEE solid;\n}\n\nhr {\n    display: block;\n    height: 2px;\n    border: 0;\n    border-top: 1px solid #aaa;\n    border-bottom: 1px solid #eee;\n    margin: 1em 0;\n    padding: 0;\n}\n\npre , code, kbd, samp {\n    color: #000;\n    font-family: monospace;\n    font-size: 0.88em;\n    border-radius: 3px;\n    background-color: #F8F8F8;\n    border: 1px solid #CCC;\n}\n\npre {\n    white-space: pre;\n    white-space: pre-wrap;\n    word-wrap: break-word;\n    padding: 5px 12px;\n}\n\npre code {\n    border: 0px !important;\n    padding: 0;\n}\n\ncode {\n    padding: 0 3px 0 3px;\n}\n\nb, strong {\n    font-weight: bold;\n}\n\ndfn {\n    font-style: italic;\n}\n\nins {\n    background: #ff9;\n    color: #000;\n    text-decoration: none;\n}\n\nmark {\n    background: #ff0;\n    color: #000;\n    font-style: italic;\n    font-weight: bold;\n}\n\nsub, sup {\n    font-size: 75%;\n    line-height: 0;\n    position: relative;\n    vertical-align: baseline;\n}\n\nsup {\n    top: -0.5em;\n}\n\nsub {\n    bottom: -0.25em;\n}\n\nul, ol {\n    margin: 1em 0;\n    padding: 0 0 0 2em;\n}\n\nli p:last-child {\n    margin: 0;\n}\n\ndd {\n    margin: 0 0 0 2em;\n}\n\nimg {\n    border: 0;\n    -ms-interpolation-mode: bicubic;\n    vertical-align: middle;\n}\n\ntable {\n    border-collapse: collapse;\n    border-spacing: 0;\n}\n\ntd {\n    vertical-align: top;\n}\n\narticle>.description {\n    font-size: 1.2em;\n}\n\n.subentries {\n    list-style: none;\n    padding: 5px 0 5px 0;\n    margin: 0 0 0 15px;\n}\n\n.subentries>.subentry {\n    margin: 0 0 15px 0;\n}\n\n.subentries>.subentry:nth-child(odd) {\n    background-color:#eee;\n}\n\n.subentries>.subentry:nth-child(even) {\n    background-color:transparent;\n}\n\n.imagegallery>h1 {\n    font-size: 1.2em;\n}\n\n.imagegallery ol {\n    list-style: none;\n    margin-left: 0;\n}\n\n.filelinks>h1 {\n    font-size: 1.2em;\n}\n\n.filelinks ol {\n    margin-left: 0;\n}\n\n.collection>h1 {\n    font-size: 1.2em;\n}\n\n.csv {\n    margin: 20px 0 0 20px;\n    overflow: auto;\n}\n\n.csv>h1 {\n    font-size: 1.2em;\n}\n\n.csv>table\n{\n    font-family: \"Lucida Sans Unicode\", \"Lucida Grande\", Sans-Serif;\n    font-size: 1.0em;\n    margin: 10px 45px 10px 45px;\n    text-align: left;\n    border-collapse: collapse;\n    border: 1px solid #69c;\n}\n\n.csv>table thead\n{\n    padding: 12px 17px 12px 17px;\n    font-weight: normal;\n    font-size: 1.2em;\n    color: #039;\n    border-bottom: 1px dashed #69c;\n}\n\n.csv>table td\n{\n    padding: 7px 17px 7px 17px;\n    color: #669;\n}\n\n.csv>table tbody tr:hover td\n{\n    color: #339;\n    background: #d0dafd;\n}\n\n.pdf {\n    width: 80%;\n    max-height: 80%;\n}\n\n.pdf>h1 {\n    font-size: 1.2em;\n}\n\n.pdf .metadata {\n    float: left;\n    font-size: 1.0em;\n    margin: 0 15px 0 0;\n}\n\n.pdf .metadata .entry {\n    margin: 0 0 10px 0;\n}\n\n.pdf .previewarea {\n    display: block;\n    overflow: auto;\n    box-shadow: 0 0 10px #000000;\n}\n\n.pdf .previewarea canvas {\n    float: none;\n}\n\n.video>h1 {\n    font-size: 1.2em;\n}\n\n.audio>h1 {\n    font-size: 1.2em;\n}\n\n.presentation nav {\n    float: left;\n    margin: 25px 0 15px 0;\n    width: 100%;\n    text-align: center;\n}\n\n.presentation nav .controls {\n    float: left;\n}\n\n.presentation nav .pager {\n    display: inline;\n    cursor: default;\n}\n\n.presentation nav .jumper {\n    float: right;\n}\n\n.presentation .content {\n    clear: left;\n}\n\n.presentation .slide {\n    float: none;\n    box-shadow: 0 0 10px #000000;\n    padding: 10px;\n}\n\n@media only screen and (max-height: 500px) {\n    .presentation .slide {\n        min-height: 220px;\n    }\n}\n\n@media only screen and (min-height: 500px) {\n    .presentation .slide {\n        min-height: 320px;\n    }\n}\n\n@media only screen and (min-height: 600px) {\n    .presentation .slide {\n        min-height: 420px;\n    }\n}\n\n@media only screen and (min-height: 768px) {\n    .presentation .slide {\n        min-height: 520px;\n    }\n}\n\n@media only screen and (max-width: 480px) {\n    body {\n        font-size: 12px;\n        width: 95%;\n    }\n\n    .presentation nav {\n        margin: 25px 0 15px 0;\n        width: 100%;\n    }    \n\n    .presentation nav .pager {\n        float: right;\n    }    \n\n    .presentation nav .jumper {\n        display: none;\n    }    \n}\n\n@media only screen and (min-width: 480px) {\n    body {\n        font-size: 14px;\n        width: 95%;\n    }\n}\n\n@media only screen and (min-width: 768px) {\n    body {\n        font-size: 16px;\n        width: 95%;\n    }\n}\n\n@media only screen and (min-width: 1024px) {\n    body {\n        font-size: 16px;\n        width: 75%;\n    }\n}`\n<|endoftext|>"}
{"text":"<commit_before>package editor\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/elpinal\/coco3\/screen\"\n)\n\ntype search struct {\n\tstreamSet\n\t*editor\n\n\tbasic *basic\n}\n\nfunc newSearch(s streamSet, e *editor) *search {\n\treturn &search{\n\t\tstreamSet: s,\n\t\teditor:    e,\n\t\tbasic:     &basic{},\n\t}\n}\n\nfunc (se *search) Mode() mode {\n\treturn modeSearch\n}\n\nfunc (se *search) Position() int {\n\treturn se.basic.pos + 1\n}\n\nfunc (se *search) Runes() []rune {\n\treturn se.buf\n}\n\nfunc (se *search) Message() []rune {\n\treturn append([]rune{'\/'}, se.basic.buf...)\n}\n\nfunc (se *search) Highlight() *screen.Hi {\n\treturn nil\n}\n\nfunc (se *search) Run() (end continuity, next mode, err error) {\n\tnext = modeSearch\n\tr, _, err := se.in.ReadRune()\n\tif err != nil {\n\t\treturn end, next, err\n\t}\n\tswitch r {\n\tcase CharCtrlM, CharCtrlJ:\n\tcase CharEscape, CharCtrlC:\n\t\treturn end, modeNormal, err\n\tcase CharBackspace, CharCtrlH:\n\t\tif len(se.basic.buf) == 0 {\n\t\t\tnext = modeNormal\n\t\t\treturn\n\t\t}\n\t\tse.basic.delete(se.basic.pos-1, se.basic.pos)\n\tcase CharCtrlB:\n\t\tse.basic.move(0)\n\tcase CharCtrlE:\n\t\tse.basic.move(len(se.basic.buf))\n\tcase CharCtrlU:\n\t\tse.basic.delete(0, se.basic.pos)\n\tcase CharCtrlW:\n\t\t\/\/ FIXME: It's redundant.\n\t\ted := newEditor()\n\t\ted.pos = se.basic.pos\n\t\ted.buf = se.basic.buf\n\t\tpos := ed.pos\n\t\ted.wordBackward()\n\t\tse.basic.delete(pos, ed.pos)\n\t\treturn\n\tdefault:\n\t\tse.basic.insert([]rune{r}, se.basic.pos)\n\t}\n\tif r != CharCtrlM && r != CharCtrlJ {\n\t\treturn\n\t}\n\tnext = modeNormal\n\ts := string(se.basic.buf)\n\tif s == \"\" {\n\t\treturn\n\t}\n\ti, err := se.search(s)\n\tif err != nil {\n\t\treturn end, next, err\n\t}\n\tse.move(i)\n\treturn\n}\n\nfunc (se *search) search(s string) (int, error) {\n\ti := strings.Index(string(se.buf[se.pos:]), s)\n\tif i < 0 {\n\t\treturn 0, fmt.Errorf(\"pattern not found: %q\", s)\n\t}\n\treturn i+se.pos, nil\n}\n<commit_msg>Search first text after cursor<commit_after>package editor\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/elpinal\/coco3\/screen\"\n)\n\ntype search struct {\n\tstreamSet\n\t*editor\n\n\tbasic *basic\n}\n\nfunc newSearch(s streamSet, e *editor) *search {\n\treturn &search{\n\t\tstreamSet: s,\n\t\teditor:    e,\n\t\tbasic:     &basic{},\n\t}\n}\n\nfunc (se *search) Mode() mode {\n\treturn modeSearch\n}\n\nfunc (se *search) Position() int {\n\treturn se.basic.pos + 1\n}\n\nfunc (se *search) Runes() []rune {\n\treturn se.buf\n}\n\nfunc (se *search) Message() []rune {\n\treturn append([]rune{'\/'}, se.basic.buf...)\n}\n\nfunc (se *search) Highlight() *screen.Hi {\n\treturn nil\n}\n\nfunc (se *search) Run() (end continuity, next mode, err error) {\n\tnext = modeSearch\n\tr, _, err := se.in.ReadRune()\n\tif err != nil {\n\t\treturn end, next, err\n\t}\n\tswitch r {\n\tcase CharCtrlM, CharCtrlJ:\n\tcase CharEscape, CharCtrlC:\n\t\treturn end, modeNormal, err\n\tcase CharBackspace, CharCtrlH:\n\t\tif len(se.basic.buf) == 0 {\n\t\t\tnext = modeNormal\n\t\t\treturn\n\t\t}\n\t\tse.basic.delete(se.basic.pos-1, se.basic.pos)\n\tcase CharCtrlB:\n\t\tse.basic.move(0)\n\tcase CharCtrlE:\n\t\tse.basic.move(len(se.basic.buf))\n\tcase CharCtrlU:\n\t\tse.basic.delete(0, se.basic.pos)\n\tcase CharCtrlW:\n\t\t\/\/ FIXME: It's redundant.\n\t\ted := newEditor()\n\t\ted.pos = se.basic.pos\n\t\ted.buf = se.basic.buf\n\t\tpos := ed.pos\n\t\ted.wordBackward()\n\t\tse.basic.delete(pos, ed.pos)\n\t\treturn\n\tdefault:\n\t\tse.basic.insert([]rune{r}, se.basic.pos)\n\t}\n\tif r != CharCtrlM && r != CharCtrlJ {\n\t\treturn\n\t}\n\tnext = modeNormal\n\ts := string(se.basic.buf)\n\tif s == \"\" {\n\t\treturn\n\t}\n\ti, err := se.search(s)\n\tif err != nil {\n\t\treturn end, next, err\n\t}\n\tse.move(i)\n\treturn\n}\n\nfunc (se *search) search(s string) (int, error) {\n\ti := strings.Index(string(se.slice(se.pos+1, len(se.buf))), s)\n\tif i < 0 {\n\t\treturn 0, fmt.Errorf(\"pattern not found: %q\", s)\n\t}\n\treturn i + se.pos + 1, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build windows\npackage main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/binary\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\t\"unsafe\"\n\n\t\"github.com\/go-ole\/go-ole\"\n\t\"github.com\/moutend\/go-wca\"\n)\n\nvar version = \"latest\"\nvar revision = \"latest\"\n\ntype WAVEFormat struct {\n\tFormatTag      uint16\n\tChannels       uint16\n\tSamplesPerSec  uint32\n\tAvgBytesPerSec uint32\n\tBlockAlign     uint16\n\tBitsPerSample  uint16\n\tDataSize       uint32\n\tRawData        []byte\n}\n\nfunc (v *WAVEFormat) Bytes() (output []byte) {\n\tbuf := new(bytes.Buffer)\n\n\tbinary.Write(buf, binary.BigEndian, []byte(\"RIFF\"))\n\tbinary.Write(buf, binary.LittleEndian, uint32(v.DataSize+36)) \/\/ Header size is 44 byte, so 44 - 8 = 36\n\tbinary.Write(buf, binary.BigEndian, []byte(\"WAVEfmt \"))\n\tbinary.Write(buf, binary.LittleEndian, uint32(16)) \/\/ 16 (0x10000000) for PCM\n\tbinary.Write(buf, binary.LittleEndian, uint16(1))  \/\/ 1 (0x0001) for PCM\n\tbinary.Write(buf, binary.LittleEndian, v.Channels)\n\tbinary.Write(buf, binary.LittleEndian, v.SamplesPerSec)\n\tbinary.Write(buf, binary.LittleEndian, v.AvgBytesPerSec)\n\tbinary.Write(buf, binary.LittleEndian, v.BlockAlign)\n\tbinary.Write(buf, binary.LittleEndian, v.BitsPerSample)\n\tbinary.Write(buf, binary.BigEndian, []byte(\"data\"))\n\tbinary.Write(buf, binary.LittleEndian, v.DataSize)\n\tbinary.Write(buf, binary.LittleEndian, v.RawData)\n\n\treturn buf.Bytes()\n}\n\ntype DurationFlag struct {\n\tValue time.Duration\n}\n\nfunc (f *DurationFlag) Set(value string) (err error) {\n\tvar sec float64\n\n\tif sec, err = strconv.ParseFloat(value, 64); err != nil {\n\t\treturn\n\t}\n\tf.Value = time.Duration(sec * float64(time.Second))\n\treturn\n}\n\nfunc (f *DurationFlag) String() string {\n\treturn f.Value.String()\n}\n\ntype FilenameFlag struct {\n\tValue string\n}\n\nfunc (f *FilenameFlag) Set(value string) (err error) {\n\tif !strings.HasSuffix(value, \".wav\") {\n\t\terr = fmt.Errorf(\"specify WAVE audio file (*.wav)\")\n\t\treturn\n\t}\n\tf.Value = value\n\treturn\n}\n\nfunc (f *FilenameFlag) String() string {\n\treturn f.Value\n}\n\nfunc main() {\n\tvar err error\n\tif err = run(os.Args); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc run(args []string) (err error) {\n\tvar durationFlag DurationFlag\n\tvar filenameFlag FilenameFlag\n\tvar versionFlag bool\n\tvar audio *WAVEFormat\n\n\tf := flag.NewFlagSet(args[0], flag.ExitOnError)\n\tf.Var(&durationFlag, \"duration\", \"Specify recording duration in second\")\n\tf.Var(&durationFlag, \"d\", \"Alias of --duration\")\n\tf.Var(&filenameFlag, \"output\", \"file name\")\n\tf.Var(&filenameFlag, \"o\", \"Alias of --output\")\n\tf.BoolVar(&versionFlag, \"version\", false, \"Show version\")\n\tf.Parse(args[1:])\n\n\tif versionFlag {\n\t\tfmt.Printf(\"%s-%s\\n\", version, revision)\n\t\treturn\n\t}\n\tif filenameFlag.Value == \"\" {\n\t\treturn\n\t}\n\n\tsignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(signalChan, os.Interrupt)\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tgo func() {\n\t\tselect {\n\t\tcase <-signalChan:\n\t\t\tfmt.Println(\"Interrupted by SIGINT\")\n\t\t\tcancel()\n\t\t}\n\t\treturn\n\t}()\n\n\tif audio, err = captureSharedTimerDriven(ctx, durationFlag.Value); err != nil {\n\t\treturn\n\t}\n\tif err = ioutil.WriteFile(filenameFlag.Value, audio.Bytes(), 0644); err != nil {\n\t\treturn\n\t}\n\tfmt.Println(\"Successfully done\")\n\treturn\n}\n\nfunc captureSharedTimerDriven(ctx context.Context, duration time.Duration) (audio *WAVEFormat, err error) {\n\tif err = ole.CoInitializeEx(0, ole.COINIT_APARTMENTTHREADED); err != nil {\n\t\treturn\n\t}\n\tdefer ole.CoUninitialize()\n\n\tvar mmde *wca.IMMDeviceEnumerator\n\tif err = wca.CoCreateInstance(wca.CLSID_MMDeviceEnumerator, 0, wca.CLSCTX_ALL, wca.IID_IMMDeviceEnumerator, &mmde); err != nil {\n\t\treturn\n\t}\n\tdefer mmde.Release()\n\n\tvar mmd *wca.IMMDevice\n\tif err = mmde.GetDefaultAudioEndpoint(wca.ECapture, wca.EConsole, &mmd); err != nil {\n\t\treturn\n\t}\n\tdefer mmd.Release()\n\n\tvar ps *wca.IPropertyStore\n\tif err = mmd.OpenPropertyStore(wca.STGM_READ, &ps); err != nil {\n\t\treturn\n\t}\n\tdefer ps.Release()\n\n\tvar pv wca.PROPVARIANT\n\tif err = ps.GetValue(&wca.PKEY_Device_FriendlyName, &pv); err != nil {\n\t\treturn\n\t}\n\tfmt.Printf(\"Capturing audio from: %s\\n\", pv.String())\n\n\tvar ac *wca.IAudioClient\n\tif err = mmd.Activate(wca.IID_IAudioClient, wca.CLSCTX_ALL, nil, &ac); err != nil {\n\t\treturn\n\t}\n\tdefer ac.Release()\n\n\tvar wfx *wca.WAVEFORMATEX\n\tif err = ac.GetMixFormat(&wfx); err != nil {\n\t\treturn\n\t}\n\tdefer ole.CoTaskMemFree(uintptr(unsafe.Pointer(wfx)))\n\n\twfx.WFormatTag = 1\n\twfx.WBitsPerSample = 16\n\twfx.NSamplesPerSec = 44100\n\twfx.NBlockAlign = (wfx.WBitsPerSample \/ 8) * wfx.NChannels\n\twfx.NAvgBytesPerSec = wfx.NSamplesPerSec * uint32(wfx.NBlockAlign)\n\twfx.CbSize = 0\n\n\taudio = &WAVEFormat{}\n\taudio.Channels = wfx.NChannels\n\taudio.SamplesPerSec = wfx.NSamplesPerSec\n\taudio.AvgBytesPerSec = wfx.NAvgBytesPerSec\n\taudio.BlockAlign = wfx.NBlockAlign\n\taudio.BitsPerSample = wfx.WBitsPerSample\n\n\tfmt.Println(\"--------\")\n\tfmt.Printf(\"Format: PCM %d bit signed integer\\n\", wfx.WBitsPerSample)\n\tfmt.Printf(\"Rate: %d Hz\\n\", wfx.NSamplesPerSec)\n\tfmt.Printf(\"Channels: %d\\n\", wfx.NChannels)\n\tfmt.Println(\"--------\")\n\n\tvar defaultPeriod wca.REFERENCE_TIME\n\tvar minimumPeriod wca.REFERENCE_TIME\n\tvar capturingPeriod time.Duration\n\tif err = ac.GetDevicePeriod(&defaultPeriod, &minimumPeriod); err != nil {\n\t\treturn\n\t}\n\tcapturingPeriod = time.Duration(int(defaultPeriod) * 100)\n\tfmt.Printf(\"Default capturing period: %d ms\\n\", capturingPeriod\/time.Millisecond)\n\n\tif err = ac.Initialize(wca.AUDCLNT_SHAREMODE_SHARED, 0, wca.REFERENCE_TIME(200*10000), 0, wfx, nil); err != nil {\n\t\treturn\n\t}\n\n\tvar bufferFrameSize uint32\n\tif err = ac.GetBufferSize(&bufferFrameSize); err != nil {\n\t\treturn\n\t}\n\tfmt.Printf(\"Allocated buffer size: %d\\n\", bufferFrameSize)\n\n\tvar acc *wca.IAudioCaptureClient\n\tif err = ac.GetService(wca.IID_IAudioCaptureClient, &acc); err != nil {\n\t\treturn\n\t}\n\tdefer acc.Release()\n\n\tif err = ac.Start(); err != nil {\n\t\treturn\n\t}\n\tfmt.Println(\"Start capturing audio with shared-timer-driven mode\")\n\tif duration <= 0 {\n\t\tfmt.Println(\"Press Ctrl-C to stop capturing\")\n\t}\n\ttime.Sleep(capturingPeriod)\n\n\tvar isCapturing bool = true\n\tvar currentDuration time.Duration\n\tvar b *byte\n\tvar data *byte\n\tvar availableFrameSize uint32\n\tvar flags uint32\n\tvar devicePosition uint64\n\tvar qcpPosition uint64\n\tvar padding uint32\n\n\tfor {\n\t\tif !isCapturing {\n\t\t\tbreak\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tisCapturing = false\n\t\t\tbreak\n\t\tdefault:\n\t\t\tcurrentDuration = time.Duration(float64(audio.DataSize) \/ float64(audio.BitsPerSample\/8) \/ float64(audio.Channels) \/ float64(audio.SamplesPerSec) * float64(time.Second))\n\t\t\tif duration != 0 && currentDuration > duration {\n\t\t\t\tisCapturing = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err = acc.GetBuffer(&data, &availableFrameSize, &flags, &devicePosition, &qcpPosition); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif availableFrameSize == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tstart := unsafe.Pointer(data)\n\t\t\tlim := int(availableFrameSize) * int(wfx.NBlockAlign)\n\n\t\t\tfor n := 0; n < lim; n++ {\n\t\t\t\tb = (*byte)(unsafe.Pointer(uintptr(start) + uintptr(n)))\n\t\t\t\taudio.RawData = append(audio.RawData, *b)\n\t\t\t}\n\t\t\taudio.DataSize += uint32(lim)\n\t\t\tif err = ac.GetCurrentPadding(&padding); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttime.Sleep(capturingPeriod)\n\t\t\tif err = acc.ReleaseBuffer(availableFrameSize); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println(\"Stop capturing\")\n\tif err = ac.Stop(); err != nil {\n\t\treturn\n\t}\n\treturn\n}\n<commit_msg>Refactor<commit_after>\/\/ +build windows\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\t\"unsafe\"\n\n\t\"github.com\/go-ole\/go-ole\"\n\t\"github.com\/moutend\/go-wav\"\n\t\"github.com\/moutend\/go-wca\"\n)\n\nvar version = \"latest\"\nvar revision = \"latest\"\n\ntype DurationFlag struct {\n\tValue time.Duration\n}\n\nfunc (f *DurationFlag) Set(value string) (err error) {\n\tvar sec float64\n\n\tif sec, err = strconv.ParseFloat(value, 64); err != nil {\n\t\treturn\n\t}\n\tf.Value = time.Duration(sec * float64(time.Second))\n\treturn\n}\n\nfunc (f *DurationFlag) String() string {\n\treturn f.Value.String()\n}\n\ntype FilenameFlag struct {\n\tValue string\n}\n\nfunc (f *FilenameFlag) Set(value string) (err error) {\n\tif !strings.HasSuffix(value, \".wav\") {\n\t\terr = fmt.Errorf(\"specify WAVE audio file (*.wav)\")\n\t\treturn\n\t}\n\tf.Value = value\n\treturn\n}\n\nfunc (f *FilenameFlag) String() string {\n\treturn f.Value\n}\n\nfunc main() {\n\tvar err error\n\tif err = run(os.Args); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc run(args []string) (err error) {\n\tvar durationFlag DurationFlag\n\tvar file []byte\n\tvar filenameFlag FilenameFlag\n\tvar versionFlag bool\n\tvar audio *wav.File\n\n\tf := flag.NewFlagSet(args[0], flag.ExitOnError)\n\tf.Var(&durationFlag, \"duration\", \"Specify recording duration in second\")\n\tf.Var(&durationFlag, \"d\", \"Alias of --duration\")\n\tf.Var(&filenameFlag, \"output\", \"file name\")\n\tf.Var(&filenameFlag, \"o\", \"Alias of --output\")\n\tf.BoolVar(&versionFlag, \"version\", false, \"Show version\")\n\tf.Parse(args[1:])\n\n\tif versionFlag {\n\t\tfmt.Printf(\"%s-%s\\n\", version, revision)\n\t\treturn\n\t}\n\tif filenameFlag.Value == \"\" {\n\t\treturn\n\t}\n\n\tsignalChan := make(chan os.Signal, 1)\n\tsignal.Notify(signalChan, os.Interrupt)\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tgo func() {\n\t\tselect {\n\t\tcase <-signalChan:\n\t\t\tfmt.Println(\"Interrupted by SIGINT\")\n\t\t\tcancel()\n\t\t}\n\t\treturn\n\t}()\n\n\tif audio, err = captureSharedTimerDriven(ctx, durationFlag.Value); err != nil {\n\t\treturn\n\t}\n\tif file, err = wav.Marshal(audio); err != nil {\n\t\treturn\n\t}\n\tif err = ioutil.WriteFile(filenameFlag.Value, file, 0644); err != nil {\n\t\treturn\n\t}\n\tfmt.Println(\"Successfully done\")\n\treturn\n}\n\nfunc captureSharedTimerDriven(ctx context.Context, duration time.Duration) (audio *wav.File, err error) {\n\tif err = ole.CoInitializeEx(0, ole.COINIT_APARTMENTTHREADED); err != nil {\n\t\treturn\n\t}\n\tdefer ole.CoUninitialize()\n\n\tvar mmde *wca.IMMDeviceEnumerator\n\tif err = wca.CoCreateInstance(wca.CLSID_MMDeviceEnumerator, 0, wca.CLSCTX_ALL, wca.IID_IMMDeviceEnumerator, &mmde); err != nil {\n\t\treturn\n\t}\n\tdefer mmde.Release()\n\n\tvar mmd *wca.IMMDevice\n\tif err = mmde.GetDefaultAudioEndpoint(wca.ECapture, wca.EConsole, &mmd); err != nil {\n\t\treturn\n\t}\n\tdefer mmd.Release()\n\n\tvar ps *wca.IPropertyStore\n\tif err = mmd.OpenPropertyStore(wca.STGM_READ, &ps); err != nil {\n\t\treturn\n\t}\n\tdefer ps.Release()\n\n\tvar pv wca.PROPVARIANT\n\tif err = ps.GetValue(&wca.PKEY_Device_FriendlyName, &pv); err != nil {\n\t\treturn\n\t}\n\tfmt.Printf(\"Capturing audio from: %s\\n\", pv.String())\n\n\tvar ac *wca.IAudioClient\n\tif err = mmd.Activate(wca.IID_IAudioClient, wca.CLSCTX_ALL, nil, &ac); err != nil {\n\t\treturn\n\t}\n\tdefer ac.Release()\n\n\tvar wfx *wca.WAVEFORMATEX\n\tif err = ac.GetMixFormat(&wfx); err != nil {\n\t\treturn\n\t}\n\tdefer ole.CoTaskMemFree(uintptr(unsafe.Pointer(wfx)))\n\n\twfx.WFormatTag = 1\n\twfx.NBlockAlign = (wfx.WBitsPerSample \/ 8) * wfx.NChannels\n\twfx.NAvgBytesPerSec = wfx.NSamplesPerSec * uint32(wfx.NBlockAlign)\n\twfx.CbSize = 0\n\n\tif audio, err = wav.New(int(wfx.NSamplesPerSec), int(wfx.WBitsPerSample), int(wfx.NChannels)); err != nil {\n\t\treturn\n\t}\n\n\tfmt.Println(\"--------\")\n\tfmt.Printf(\"Format: PCM %d bit signed integer\\n\", int(wfx.WBitsPerSample))\n\tfmt.Printf(\"Rate: %d Hz\\n\", wfx.NSamplesPerSec)\n\tfmt.Printf(\"Channels: %d\\n\", wfx.NChannels)\n\tfmt.Println(\"--------\")\n\n\tvar defaultPeriod wca.REFERENCE_TIME\n\tvar minimumPeriod wca.REFERENCE_TIME\n\tvar latency time.Duration\n\tif err = ac.GetDevicePeriod(&defaultPeriod, &minimumPeriod); err != nil {\n\t\treturn\n\t}\n\tlatency = time.Duration(int(defaultPeriod) * 100)\n\n\tfmt.Println(\"Default period: \", defaultPeriod)\n\tfmt.Println(\"Minimum period: \", minimumPeriod)\n\tfmt.Println(\"Latency: \", latency)\n\n\tif err = ac.Initialize(wca.AUDCLNT_SHAREMODE_SHARED, 0, defaultPeriod, 0, wfx, nil); err != nil {\n\t\treturn\n\t}\n\n\tvar bufferFrameSize uint32\n\tif err = ac.GetBufferSize(&bufferFrameSize); err != nil {\n\t\treturn\n\t}\n\tfmt.Printf(\"Allocated buffer size: %d\\n\", bufferFrameSize)\n\n\tvar acc *wca.IAudioCaptureClient\n\tif err = ac.GetService(wca.IID_IAudioCaptureClient, &acc); err != nil {\n\t\treturn\n\t}\n\tdefer acc.Release()\n\n\tif err = ac.Start(); err != nil {\n\t\treturn\n\t}\n\tfmt.Println(\"Start capturing with shared timer driven mode\")\n\tif duration <= 0 {\n\t\tfmt.Println(\"Press Ctrl-C to stop capturing\")\n\t}\n\n\tvar output = []byte{}\n\tvar offset int\n\tvar isCapturing bool = true\n\tvar currentDuration time.Duration\n\tvar b *byte\n\tvar data *byte\n\tvar availableFrameSize uint32\n\tvar flags uint32\n\tvar devicePosition uint64\n\tvar qcpPosition uint64\n\n\ttime.Sleep(latency)\n\n\tfor {\n\t\tif !isCapturing {\n\t\t\tbreak\n\t\t}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tisCapturing = false\n\t\t\tbreak\n\t\tdefault:\n\t\t\t\/\/ Wait for buffering.\n\t\t\ttime.Sleep(latency \/ 2)\n\n\t\t\tcurrentDuration = time.Duration(float64(offset) \/ float64(wfx.WBitsPerSample\/8) \/ float64(wfx.NChannels) \/ float64(wfx.NSamplesPerSec) * float64(time.Second))\n\t\t\tif duration != 0 && currentDuration > duration {\n\t\t\t\tisCapturing = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err = acc.GetBuffer(&data, &availableFrameSize, &flags, &devicePosition, &qcpPosition); err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif availableFrameSize == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tstart := unsafe.Pointer(data)\n\t\t\tlim := int(availableFrameSize) * int(wfx.NBlockAlign)\n\t\t\tbuf := make([]byte, lim)\n\n\t\t\tfor n := 0; n < lim; n++ {\n\t\t\t\tb = (*byte)(unsafe.Pointer(uintptr(start) + uintptr(n)))\n\t\t\t\tbuf[n] = *b\n\t\t\t}\n\t\t\toffset += lim\n\t\t\toutput = append(output, buf...)\n\n\t\t\tif err = acc.ReleaseBuffer(availableFrameSize); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tio.Copy(audio, bytes.NewBuffer(output))\n\n\tfmt.Println(\"Stop capturing\")\n\tif err = ac.Stop(); err != nil {\n\t\treturn\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The LUCI Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.chromium.org\/luci\/common\/clock\"\n\t\"go.chromium.org\/luci\/common\/data\/rand\/mathrand\"\n\t\"go.chromium.org\/luci\/common\/errors\"\n\t\"go.chromium.org\/luci\/common\/gcloud\/gs\"\n\t\"go.chromium.org\/luci\/common\/logging\"\n\tlog \"go.chromium.org\/luci\/common\/logging\"\n\t\"go.chromium.org\/luci\/common\/retry\"\n\t\"go.chromium.org\/luci\/common\/retry\/transient\"\n\t\"go.chromium.org\/luci\/common\/sync\/dispatcher\"\n\t\"go.chromium.org\/luci\/common\/sync\/dispatcher\/buffer\"\n\t\"go.chromium.org\/luci\/common\/tsmon\/distribution\"\n\t\"go.chromium.org\/luci\/common\/tsmon\/field\"\n\t\"go.chromium.org\/luci\/common\/tsmon\/metric\"\n\tmontypes \"go.chromium.org\/luci\/common\/tsmon\/types\"\n\t\"go.chromium.org\/luci\/hardcoded\/chromeinfra\"\n\t\"golang.org\/x\/time\/rate\"\n\n\tlogdog \"go.chromium.org\/luci\/logdog\/api\/endpoints\/coordinator\/services\/v1\"\n\t\"go.chromium.org\/luci\/logdog\/server\/archivist\"\n\t\"go.chromium.org\/luci\/logdog\/server\/bundleServicesClient\"\n\t\"go.chromium.org\/luci\/logdog\/server\/service\"\n)\n\nvar (\n\terrInvalidConfig = errors.New(\"invalid configuration\")\n\terrNoWorkToDo    = errors.New(\"no work to do\")\n\n\tleaseRetryParams = func() retry.Iterator {\n\t\treturn &retry.ExponentialBackoff{\n\t\t\tLimited: retry.Limited{\n\t\t\t\tDelay:   time.Second,\n\t\t\t\tRetries: -1,\n\t\t\t},\n\t\t\tMultiplier: 1.25,\n\t\t\tMaxDelay:   time.Minute * 10,\n\t\t}\n\t}\n\n\tackChannelOptions = &dispatcher.Options{\n\t\tQPSLimit: rate.NewLimiter(1, 1), \/\/ 1 QPS max rate\n\t\tBuffer: buffer.Options{\n\t\t\tMaxLeases:     10,\n\t\t\tBatchSize:     500,\n\t\t\tBatchDuration: 10 * time.Minute,\n\t\t\tFullBehavior: &buffer.BlockNewItems{\n\t\t\t\tMaxItems: 10 * 500,\n\t\t\t},\n\t\t\tRetry: func() retry.Iterator {\n\t\t\t\treturn &retry.ExponentialBackoff{\n\t\t\t\t\tLimited: retry.Limited{\n\t\t\t\t\t\tDelay:   time.Second,\n\t\t\t\t\t\tRetries: 10,\n\t\t\t\t\t},\n\t\t\t\t\tMultiplier: 1.25,\n\t\t\t\t\tMaxDelay:   time.Minute * 10,\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t}\n\n\tmkJobChannelOptions = func(maxWorkers int) *dispatcher.Options {\n\t\treturn &dispatcher.Options{\n\t\t\tBuffer: buffer.Options{\n\t\t\t\tMaxLeases: maxWorkers,\n\t\t\t\tBatchSize: 1,\n\t\t\t\tFullBehavior: &buffer.BlockNewItems{\n\t\t\t\t\tMaxItems: 2 * maxWorkers,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\t\/\/ maxSleepTime is the max amount of time to sleep in-between errors, in seconds.\n\tmaxSleepTime = 32\n\n\t\/\/ tsTaskProcessingTime measures the amount of time spent processing a single\n\t\/\/ task.\n\t\/\/\n\t\/\/ The \"consumed\" field is true if the underlying task was consumed and\n\t\/\/ false if it was not.\n\ttsTaskProcessingTime = metric.NewCumulativeDistribution(\"logdog\/archivist\/task_processing_time_ms_ng\",\n\t\t\"The amount of time (in milliseconds) that a single task takes to process in the new pipeline.\",\n\t\t&montypes.MetricMetadata{Units: montypes.Milliseconds},\n\t\tdistribution.DefaultBucketer,\n\t\tfield.Bool(\"consumed\"))\n\n\ttsLoopCycleTime = metric.NewCumulativeDistribution(\"logdog\/archivist\/loop_cycle_time_ms\",\n\t\t\"The amount of time a single batch of leases takes to process.\",\n\t\t&montypes.MetricMetadata{Units: montypes.Milliseconds},\n\t\tdistribution.DefaultBucketer)\n\n\ttsLeaseCount = metric.NewCounter(\"logdog\/archivist\/tasks_leased\",\n\t\t\"Number of tasks leased.\",\n\t\tnil)\n\n\ttsNackCount = metric.NewCounter(\"logdog\/archivist\/tasks_not_acked\",\n\t\t\"Number of tasks leased but failed.\",\n\t\tnil)\n\n\ttsAckCount = metric.NewCounter(\"logdog\/archivist\/tasks_acked\",\n\t\t\"Number of tasks successfully completed and acked.\",\n\t\tnil)\n)\n\n\/\/ application is the Archivist application state.\ntype application struct {\n\tservice.Service\n\n\tmaxConcurrentTasks int\n}\n\n\/\/ runForever runs the archivist loop forever.\nfunc runForever(ctx context.Context, taskConcurrency int, ar archivist.Archivist) {\n\ttype archiveJob struct {\n\t\tdeadline time.Time\n\t\ttask     *logdog.ArchiveTask\n\t}\n\n\tackChan, err := dispatcher.NewChannel(ctx, ackChannelOptions, func(batch *buffer.Batch) error {\n\t\tvar req *logdog.DeleteRequest\n\t\tif batch.Meta != nil {\n\t\t\treq = batch.Meta.(*logdog.DeleteRequest)\n\t\t} else {\n\t\t\ttasks := make([]*logdog.ArchiveTask, len(batch.Data))\n\t\t\tfor i, datum := range batch.Data {\n\t\t\t\ttasks[i] = datum.(*logdog.ArchiveTask)\n\t\t\t\tbatch.Data[i] = nil\n\t\t\t}\n\t\t\treq = &logdog.DeleteRequest{Tasks: tasks}\n\t\t\tbatch.Meta = req\n\t\t}\n\t\t_, err := ar.Service.DeleteArchiveTasks(ctx, req)\n\t\treturn transient.Tag.Apply(err)\n\t})\n\tif err != nil {\n\t\tpanic(err) \/\/ only occurs if Options is invalid\n\t}\n\tdefer func() {\n\t\tlogging.Infof(ctx, \"draining ACK channel\")\n\t\tackChan.CloseAndDrain(ctx)\n\t\tlogging.Infof(ctx, \"ACK channel drained\")\n\t}()\n\n\tjobChanOpts := mkJobChannelOptions(taskConcurrency)\n\tjobChan, err := dispatcher.NewChannel(ctx, jobChanOpts, func(data *buffer.Batch) error {\n\t\tjob := data.Data[0].(*archiveJob)\n\n\t\tnc, cancel := context.WithDeadline(ctx, job.deadline)\n\t\tdefer cancel()\n\n\t\tstartTime := clock.Now(ctx)\n\t\terr := ar.ArchiveTask(nc, job.task)\n\t\tduration := clock.Now(ctx).Sub(startTime)\n\t\ttsTaskProcessingTime.Add(ctx, float64(duration.Nanoseconds())\/1000000, err == nil)\n\n\t\tif err == nil {\n\t\t\tselect {\n\t\t\tcase ackChan.C <- job:\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlogging.Errorf(ctx, \"Failed to ACK task %v due to context: %s\", job.task, ctx.Err())\n\t\t\t}\n\t\t} else {\n\t\t\tlogging.Errorf(ctx, \"Failed to archive task %v: %s\", job.task, err)\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tpanic(err) \/\/ only occurs if Options is invalid\n\t}\n\tdefer func() {\n\t\tlogging.Infof(ctx, \"Job channel draining\")\n\t\tjobChan.CloseAndDrain(ctx)\n\t\tlogging.Infof(ctx, \"Job channel drained\")\n\t}()\n\n\t\/\/ now we spin forever, pushing items into jobChan.\n\tsleepTime := 1\n\tvar previousCycle time.Time\n\tfor ctx.Err() == nil {\n\t\tloopParams := grabLoopParams()\n\t\treq := loopParams.mkRequest(ctx)\n\n\t\tvar tasks *logdog.LeaseResponse\n\t\tvar deadline time.Time\n\n\t\tlogging.Infof(ctx, \"Leasing max %d tasks for %s\", loopParams.batchSize, loopParams.deadline)\n\t\terr := retry.Retry(ctx, leaseRetryParams, func() (err error) {\n\t\t\tdeadline = clock.Now(ctx).Add(loop.deadline)\n\t\t\ttasks, err = ar.Service.LeaseArchiveTasks(ctx, req)\n\t\t\treturn\n\t\t}, retry.LogCallback(ctx, \"LeaseArchiveTasks\"))\n\t\tif ctx.Err() != nil && err != nil {\n\t\t\tpanic(\"impossible: infinite retry stopped: \" + err.Error())\n\t\t}\n\n\t\tif !previousCycle.IsZero() {\n\t\t\tnow := clock.Now(ctx)\n\t\t\ttsLoopCycleTime.Add(ctx, float64(now.Sub(previousCycle).Nanoseconds()\/1000000))\n\t\t\tpreviousCycle = now\n\t\t}\n\n\t\tif len(tasks.Tasks) == 0 {\n\t\t\tsleepTime *= 2\n\t\t\tif sleepTime > maxSleepTime {\n\t\t\t\tsleepTime = maxSleepTime\n\t\t\t}\n\t\t\tlogging.Infof(ctx, \"no work to do, sleeping for %d seconds\", sleepTime)\n\t\t\tclock.Sleep(ctx, time.Duration(sleepTime)*time.Second)\n\t\t\tpreviousCycle = time.Time{}\n\t\t\tcontinue\n\t\t} else {\n\t\t\tsleepTime = 1\n\t\t}\n\n\t\tfor _, task := range tasks.Tasks {\n\t\t\tselect {\n\t\t\tcase jobChan.C <- &archiveJob{deadline, task}:\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlogging.Infof(ctx, \"lease thread got context err: %s\", ctx.Err())\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tlogging.Infof(ctx, \"runForever no longer running forever: ctx.Err() == %s\", ctx.Err())\n}\n\n\/\/ run is the main execution function.\nfunc (a *application) runArchivist(c context.Context) error {\n\tcfg := a.ServiceConfig()\n\n\tcoordCfg, acfg := cfg.GetCoordinator(), cfg.GetArchivist()\n\tswitch {\n\tcase coordCfg == nil:\n\t\tfallthrough\n\n\tcase acfg == nil:\n\t\treturn errors.New(\"missing required config: archivist\")\n\tcase acfg.GsStagingBucket == \"\":\n\t\treturn errors.New(\"missing required config: archivist.gs_staging_bucket\")\n\t}\n\n\t\/\/ Initialize our Storage.\n\tst, err := a.IntermediateStorage(c, true)\n\tif err != nil {\n\t\tlog.WithError(err).Errorf(c, \"Failed to get storage instance.\")\n\t\treturn err\n\t}\n\tdefer st.Close()\n\n\t\/\/ Defines our Google Storage client project scoped factory.\n\tgsClientFactory := func(ctx context.Context, project string) (gs.Client, error) {\n\t\tgsClient, err := a.GSClient(ctx, project)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Errorf(c, \"Failed to get Google Storage client.\")\n\t\t\treturn nil, err\n\t\t}\n\t\treturn gsClient, nil\n\t}\n\n\t\/\/ Initialize a Coordinator client that bundles requests together.\n\tcoordClient := &bundleServicesClient.Client{\n\t\tServicesClient:       a.Coordinator(),\n\t\tDelayThreshold:       time.Second,\n\t\tBundleCountThreshold: 100,\n\t}\n\tdefer coordClient.Flush()\n\n\tar := archivist.Archivist{\n\t\tService:         coordClient,\n\t\tSettingsLoader:  a.GetSettingsLoader(acfg),\n\t\tStorage:         st,\n\t\tGSClientFactory: gsClientFactory,\n\t}\n\n\t\/\/ Application shutdown will now operate by stopping the Iterator.\n\tc, cancelFunc := context.WithCancel(c)\n\tdefer cancelFunc()\n\n\t\/\/ Application shutdown will now operate by cancelling the Archivist's\n\t\/\/ shutdown Context.\n\ta.SetShutdownFunc(cancelFunc)\n\n\t\/\/ Load our settings and update them periodically.\n\tfetchLoopParams(c)\n\tgo loopParamsUpdater(c)\n\n\trunForever(c, a.maxConcurrentTasks, ar)\n\n\treturn nil\n}\n\n\/\/ Entry point.\nfunc main() {\n\tmathrand.SeedRandomly()\n\ta := application{\n\t\tService: service.Service{\n\t\t\tName:               \"archivist\",\n\t\t\tDefaultAuthOptions: chromeinfra.DefaultAuthOptions(),\n\t\t},\n\t}\n\ta.Flags.IntVar(&a.maxConcurrentTasks, \"max-concurrent-tasks\", 1,\n\t\t\"Maximum number of archive tasks to process concurrently. \"+\n\t\t\t\"Pass 0 to set infinite limit.\")\n\ta.Run(context.Background(), a.runArchivist)\n}\n<commit_msg>[logdog] Fix typesafety issue.<commit_after>\/\/ Copyright 2016 The LUCI Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.chromium.org\/luci\/common\/clock\"\n\t\"go.chromium.org\/luci\/common\/data\/rand\/mathrand\"\n\t\"go.chromium.org\/luci\/common\/errors\"\n\t\"go.chromium.org\/luci\/common\/gcloud\/gs\"\n\t\"go.chromium.org\/luci\/common\/logging\"\n\tlog \"go.chromium.org\/luci\/common\/logging\"\n\t\"go.chromium.org\/luci\/common\/retry\"\n\t\"go.chromium.org\/luci\/common\/retry\/transient\"\n\t\"go.chromium.org\/luci\/common\/sync\/dispatcher\"\n\t\"go.chromium.org\/luci\/common\/sync\/dispatcher\/buffer\"\n\t\"go.chromium.org\/luci\/common\/tsmon\/distribution\"\n\t\"go.chromium.org\/luci\/common\/tsmon\/field\"\n\t\"go.chromium.org\/luci\/common\/tsmon\/metric\"\n\tmontypes \"go.chromium.org\/luci\/common\/tsmon\/types\"\n\t\"go.chromium.org\/luci\/hardcoded\/chromeinfra\"\n\t\"golang.org\/x\/time\/rate\"\n\n\tlogdog \"go.chromium.org\/luci\/logdog\/api\/endpoints\/coordinator\/services\/v1\"\n\t\"go.chromium.org\/luci\/logdog\/server\/archivist\"\n\t\"go.chromium.org\/luci\/logdog\/server\/bundleServicesClient\"\n\t\"go.chromium.org\/luci\/logdog\/server\/service\"\n)\n\nvar (\n\terrInvalidConfig = errors.New(\"invalid configuration\")\n\terrNoWorkToDo    = errors.New(\"no work to do\")\n\n\tleaseRetryParams = func() retry.Iterator {\n\t\treturn &retry.ExponentialBackoff{\n\t\t\tLimited: retry.Limited{\n\t\t\t\tDelay:   time.Second,\n\t\t\t\tRetries: -1,\n\t\t\t},\n\t\t\tMultiplier: 1.25,\n\t\t\tMaxDelay:   time.Minute * 10,\n\t\t}\n\t}\n\n\tackChannelOptions = &dispatcher.Options{\n\t\tQPSLimit: rate.NewLimiter(1, 1), \/\/ 1 QPS max rate\n\t\tBuffer: buffer.Options{\n\t\t\tMaxLeases:     10,\n\t\t\tBatchSize:     500,\n\t\t\tBatchDuration: 10 * time.Minute,\n\t\t\tFullBehavior: &buffer.BlockNewItems{\n\t\t\t\tMaxItems: 10 * 500,\n\t\t\t},\n\t\t\tRetry: func() retry.Iterator {\n\t\t\t\treturn &retry.ExponentialBackoff{\n\t\t\t\t\tLimited: retry.Limited{\n\t\t\t\t\t\tDelay:   time.Second,\n\t\t\t\t\t\tRetries: 10,\n\t\t\t\t\t},\n\t\t\t\t\tMultiplier: 1.25,\n\t\t\t\t\tMaxDelay:   time.Minute * 10,\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t}\n\n\tmkJobChannelOptions = func(maxWorkers int) *dispatcher.Options {\n\t\treturn &dispatcher.Options{\n\t\t\tBuffer: buffer.Options{\n\t\t\t\tMaxLeases: maxWorkers,\n\t\t\t\tBatchSize: 1,\n\t\t\t\tFullBehavior: &buffer.BlockNewItems{\n\t\t\t\t\tMaxItems: 2 * maxWorkers,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\t\/\/ maxSleepTime is the max amount of time to sleep in-between errors, in seconds.\n\tmaxSleepTime = 32\n\n\t\/\/ tsTaskProcessingTime measures the amount of time spent processing a single\n\t\/\/ task.\n\t\/\/\n\t\/\/ The \"consumed\" field is true if the underlying task was consumed and\n\t\/\/ false if it was not.\n\ttsTaskProcessingTime = metric.NewCumulativeDistribution(\"logdog\/archivist\/task_processing_time_ms_ng\",\n\t\t\"The amount of time (in milliseconds) that a single task takes to process in the new pipeline.\",\n\t\t&montypes.MetricMetadata{Units: montypes.Milliseconds},\n\t\tdistribution.DefaultBucketer,\n\t\tfield.Bool(\"consumed\"))\n\n\ttsLoopCycleTime = metric.NewCumulativeDistribution(\"logdog\/archivist\/loop_cycle_time_ms\",\n\t\t\"The amount of time a single batch of leases takes to process.\",\n\t\t&montypes.MetricMetadata{Units: montypes.Milliseconds},\n\t\tdistribution.DefaultBucketer)\n\n\ttsLeaseCount = metric.NewCounter(\"logdog\/archivist\/tasks_leased\",\n\t\t\"Number of tasks leased.\",\n\t\tnil)\n\n\ttsNackCount = metric.NewCounter(\"logdog\/archivist\/tasks_not_acked\",\n\t\t\"Number of tasks leased but failed.\",\n\t\tnil)\n\n\ttsAckCount = metric.NewCounter(\"logdog\/archivist\/tasks_acked\",\n\t\t\"Number of tasks successfully completed and acked.\",\n\t\tnil)\n)\n\n\/\/ application is the Archivist application state.\ntype application struct {\n\tservice.Service\n\n\tmaxConcurrentTasks int\n}\n\n\/\/ runForever runs the archivist loop forever.\nfunc runForever(ctx context.Context, taskConcurrency int, ar archivist.Archivist) {\n\ttype archiveJob struct {\n\t\tdeadline time.Time\n\t\ttask     *logdog.ArchiveTask\n\t}\n\n\tackChan, err := dispatcher.NewChannel(ctx, ackChannelOptions, func(batch *buffer.Batch) error {\n\t\tvar req *logdog.DeleteRequest\n\t\tif batch.Meta != nil {\n\t\t\treq = batch.Meta.(*logdog.DeleteRequest)\n\t\t} else {\n\t\t\ttasks := make([]*logdog.ArchiveTask, len(batch.Data))\n\t\t\tfor i, datum := range batch.Data {\n\t\t\t\ttasks[i] = datum.(*logdog.ArchiveTask)\n\t\t\t\tbatch.Data[i] = nil\n\t\t\t}\n\t\t\treq = &logdog.DeleteRequest{Tasks: tasks}\n\t\t\tbatch.Meta = req\n\t\t}\n\t\t_, err := ar.Service.DeleteArchiveTasks(ctx, req)\n\t\treturn transient.Tag.Apply(err)\n\t})\n\tif err != nil {\n\t\tpanic(err) \/\/ only occurs if Options is invalid\n\t}\n\tdefer func() {\n\t\tlogging.Infof(ctx, \"draining ACK channel\")\n\t\tackChan.CloseAndDrain(ctx)\n\t\tlogging.Infof(ctx, \"ACK channel drained\")\n\t}()\n\n\tjobChanOpts := mkJobChannelOptions(taskConcurrency)\n\tjobChan, err := dispatcher.NewChannel(ctx, jobChanOpts, func(data *buffer.Batch) error {\n\t\tjob := data.Data[0].(*archiveJob)\n\n\t\tnc, cancel := context.WithDeadline(ctx, job.deadline)\n\t\tdefer cancel()\n\n\t\tstartTime := clock.Now(ctx)\n\t\terr := ar.ArchiveTask(nc, job.task)\n\t\tduration := clock.Now(ctx).Sub(startTime)\n\t\ttsTaskProcessingTime.Add(ctx, float64(duration.Nanoseconds())\/1000000, err == nil)\n\n\t\tif err == nil {\n\t\t\tselect {\n\t\t\tcase ackChan.C <- job.task:\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlogging.Errorf(ctx, \"Failed to ACK task %v due to context: %s\", job.task, ctx.Err())\n\t\t\t}\n\t\t} else {\n\t\t\tlogging.Errorf(ctx, \"Failed to archive task %v: %s\", job.task, err)\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tpanic(err) \/\/ only occurs if Options is invalid\n\t}\n\tdefer func() {\n\t\tlogging.Infof(ctx, \"Job channel draining\")\n\t\tjobChan.CloseAndDrain(ctx)\n\t\tlogging.Infof(ctx, \"Job channel drained\")\n\t}()\n\n\t\/\/ now we spin forever, pushing items into jobChan.\n\tsleepTime := 1\n\tvar previousCycle time.Time\n\tfor ctx.Err() == nil {\n\t\tloopParams := grabLoopParams()\n\t\treq := loopParams.mkRequest(ctx)\n\n\t\tvar tasks *logdog.LeaseResponse\n\t\tvar deadline time.Time\n\n\t\tlogging.Infof(ctx, \"Leasing max %d tasks for %s\", loopParams.batchSize, loopParams.deadline)\n\t\terr := retry.Retry(ctx, leaseRetryParams, func() (err error) {\n\t\t\tdeadline = clock.Now(ctx).Add(loop.deadline)\n\t\t\ttasks, err = ar.Service.LeaseArchiveTasks(ctx, req)\n\t\t\treturn\n\t\t}, retry.LogCallback(ctx, \"LeaseArchiveTasks\"))\n\t\tif ctx.Err() != nil && err != nil {\n\t\t\tpanic(\"impossible: infinite retry stopped: \" + err.Error())\n\t\t}\n\n\t\tif !previousCycle.IsZero() {\n\t\t\tnow := clock.Now(ctx)\n\t\t\ttsLoopCycleTime.Add(ctx, float64(now.Sub(previousCycle).Nanoseconds()\/1000000))\n\t\t\tpreviousCycle = now\n\t\t}\n\n\t\tif len(tasks.Tasks) == 0 {\n\t\t\tsleepTime *= 2\n\t\t\tif sleepTime > maxSleepTime {\n\t\t\t\tsleepTime = maxSleepTime\n\t\t\t}\n\t\t\tlogging.Infof(ctx, \"no work to do, sleeping for %d seconds\", sleepTime)\n\t\t\tclock.Sleep(ctx, time.Duration(sleepTime)*time.Second)\n\t\t\tpreviousCycle = time.Time{}\n\t\t\tcontinue\n\t\t} else {\n\t\t\tsleepTime = 1\n\t\t}\n\n\t\tfor _, task := range tasks.Tasks {\n\t\t\tselect {\n\t\t\tcase jobChan.C <- &archiveJob{deadline, task}:\n\t\t\tcase <-ctx.Done():\n\t\t\t\tlogging.Infof(ctx, \"lease thread got context err: %s\", ctx.Err())\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tlogging.Infof(ctx, \"runForever no longer running forever: ctx.Err() == %s\", ctx.Err())\n}\n\n\/\/ run is the main execution function.\nfunc (a *application) runArchivist(c context.Context) error {\n\tcfg := a.ServiceConfig()\n\n\tcoordCfg, acfg := cfg.GetCoordinator(), cfg.GetArchivist()\n\tswitch {\n\tcase coordCfg == nil:\n\t\tfallthrough\n\n\tcase acfg == nil:\n\t\treturn errors.New(\"missing required config: archivist\")\n\tcase acfg.GsStagingBucket == \"\":\n\t\treturn errors.New(\"missing required config: archivist.gs_staging_bucket\")\n\t}\n\n\t\/\/ Initialize our Storage.\n\tst, err := a.IntermediateStorage(c, true)\n\tif err != nil {\n\t\tlog.WithError(err).Errorf(c, \"Failed to get storage instance.\")\n\t\treturn err\n\t}\n\tdefer st.Close()\n\n\t\/\/ Defines our Google Storage client project scoped factory.\n\tgsClientFactory := func(ctx context.Context, project string) (gs.Client, error) {\n\t\tgsClient, err := a.GSClient(ctx, project)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Errorf(c, \"Failed to get Google Storage client.\")\n\t\t\treturn nil, err\n\t\t}\n\t\treturn gsClient, nil\n\t}\n\n\t\/\/ Initialize a Coordinator client that bundles requests together.\n\tcoordClient := &bundleServicesClient.Client{\n\t\tServicesClient:       a.Coordinator(),\n\t\tDelayThreshold:       time.Second,\n\t\tBundleCountThreshold: 100,\n\t}\n\tdefer coordClient.Flush()\n\n\tar := archivist.Archivist{\n\t\tService:         coordClient,\n\t\tSettingsLoader:  a.GetSettingsLoader(acfg),\n\t\tStorage:         st,\n\t\tGSClientFactory: gsClientFactory,\n\t}\n\n\t\/\/ Application shutdown will now operate by stopping the Iterator.\n\tc, cancelFunc := context.WithCancel(c)\n\tdefer cancelFunc()\n\n\t\/\/ Application shutdown will now operate by cancelling the Archivist's\n\t\/\/ shutdown Context.\n\ta.SetShutdownFunc(cancelFunc)\n\n\t\/\/ Load our settings and update them periodically.\n\tfetchLoopParams(c)\n\tgo loopParamsUpdater(c)\n\n\trunForever(c, a.maxConcurrentTasks, ar)\n\n\treturn nil\n}\n\n\/\/ Entry point.\nfunc main() {\n\tmathrand.SeedRandomly()\n\ta := application{\n\t\tService: service.Service{\n\t\t\tName:               \"archivist\",\n\t\t\tDefaultAuthOptions: chromeinfra.DefaultAuthOptions(),\n\t\t},\n\t}\n\ta.Flags.IntVar(&a.maxConcurrentTasks, \"max-concurrent-tasks\", 1,\n\t\t\"Maximum number of archive tasks to process concurrently. \"+\n\t\t\t\"Pass 0 to set infinite limit.\")\n\ta.Run(context.Background(), a.runArchivist)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build noos\n\npackage syscall\n\nimport (\n\t\"bits\"\n\t\"internal\"\n\t\"unsafe\"\n)\n\nconst (\n\tNEWTASK    = internal.NEWTASK\n\tKILLTASK   = internal.KILLTASK\n\tTASKUNLOCK = internal.TASKUNLOCK\n\tMAXTASKS   = iota\n\tSCHEDNEXT\n\tEVENTWAIT\n\tSETSYSTIM\n\tNANOSEC\n\tSETALARM\n\tSETAT\n\tSETIRQENA\n\tSETIRQPRIO\n\tSETIRQHANDLER\n\tIRQSTATUS\n\tTRIGGERIRQ\n\tSETPRIVLEVEL\n\tDEBUGOUT\n)\n\n\/\/ NewTask creates new task that starts execute f. If lock is true tasker stops\n\/\/ scheduling current task and waits until new task will call TaskUnlock. When\n\/\/ success it returns TID of new task.\nfunc NewTask(f func(), lock bool) (int, Errno) {\n\ttid, e := internal.Syscall2(NEWTASK, ftou(f), uintptr(bits.One(lock)))\n\treturn int(tid), Errno(e)\n}\n\n\/\/ KillTask kills task with specified tid. tid == 0 means current task.\nfunc KillTask(tid int) Errno {\n\t_, e := internal.Syscall1(KILLTASK, uintptr(tid))\n\treturn Errno(e)\n}\n\n\/\/ TaskUnlock can be used when task was created with lock option. It informs\n\/\/ tasker that now it can safely run parent task.\nfunc TaskUnlock() {\n\tinternal.Syscall0(TASKUNLOCK)\n}\n\n\/\/ MaxTasks: see rtos package.\nfunc MaxTasks() int {\n\tn, _ := internal.Syscall0(MAXTASKS)\n\treturn int(n)\n}\n\n\/\/ SchedYield causes the calling task to relinquish the CPU.\nfunc SchedYield() {\n\tinternal.Syscall0(SCHEDNEXT)\n}\n\n\/\/ SchedNext informs tasker that it need to schedule next ready to run task.\n\/\/ It is safe to call SchedNext from interrupt handler.\nfunc SchedNext() {\n\tschedNext()\n}\n\n\/\/ SetSysTimer registers two functions that the runtime uses to communicate with\n\/\/ the system timer.\n\/\/\n\/\/ Nanosec is used to implement Nanosec system call. It should return the\n\/\/ monotonic time in nanoseconds (typically the time of system timer run).\n\/\/\n\/\/ SetWakeUp is called by scheduler to ask system timer to wake it up at time t\n\/\/ (using SchedNext function). T can be a monotonic time in nanoseconds or -1\n\/\/ if the scheduler does not want to be woken. System timer must guarantee that\n\/\/ it will wake up the scheduler at t or after t. Additional awakenings before\n\/\/ and after t are acceptable but not recommended. Ticking timer simply wakes up\n\/\/ the scheduler with a constant period and its setWakeUp function does nothing.\n\/\/ Tickless timer schould wake up the scheduler only once, at t or just after t.\nfunc SetSysTimer(nanosec func() int64, setWakeUp func(t int64)) {\n\tinternal.Syscall2(SETSYSTIM, fr64tou(nanosec), f64tou(setWakeUp))\n}\n\n\/\/ Nanosec: see rtos package.\nfunc Nanosec() int64 {\n\treturn internal.Syscall0r64(NANOSEC)\n}\n\n\/\/ SetAlarm asks the runtime to send Alarm event at t. T is only a hint for the\n\/\/ runtime, because it can send alarm at any time: before t, at t and after t.\n\/\/ Typically, task use SetAlarm in conjunction with Alarm.Wait and Nanosec.\nfunc SetAlarm(t int64) {\n\tinternal.Syscall1i64(SETALARM, t)\n}\n\n\/\/ SetAt works like SetAlarm but additionaly sets task local variable, used to\n\/\/ implement internal.TimeChan.\nfunc SetAt(t int64) {\n\tinternal.Syscall1i64(SETAT, t)\n}\n\n\/\/ TimeChan returns channel that can be used to wait for time set using\n\/\/ SetAt. TimeChan is used mainly for deadline\/timeout in select statements.\nfunc TimeChan() <-chan int64 {\n\tch := &internal.TimeChan\n\treturn *(*<-chan int64)(unsafe.Pointer(&ch))\n}\n\n\/\/ SetIRQEna enables or disables irq.\nfunc SetIRQEna(irq int, ena bool) Errno {\n\t_, e := internal.Syscall2(SETIRQENA, uintptr(irq), uintptr(bits.One(ena)))\n\treturn Errno(e)\n}\n\n\/\/ SetIRQPrio sets priority for irq.\nfunc SetIRQPrio(irq, prio int) Errno {\n\t_, err := internal.Syscall2(SETIRQPRIO, uintptr(irq), uintptr(prio))\n\treturn Errno(err)\n}\n\n\/\/ SetIRQHandler: see rtos package.\nfunc SetIRQHandler(irq int, f func()) Errno {\n\t_, e := internal.Syscall2(SETIRQHANDLER, uintptr(irq), ftou(f))\n\treturn Errno(e)\n}\n\n\/\/ IRQStatus: ee rtos package.\nfunc IRQStatus(irq int) (int, Errno) {\n\ts, e := internal.Syscall1(IRQSTATUS, uintptr(irq))\n\treturn int(s), Errno(e)\n}\n\n\/\/ TriggerIRQ: see rtos package.\nfunc TriggerIRQ(irq int) Errno {\n\t_, e := internal.Syscall1(IRQSTATUS, uintptr(irq))\n\treturn Errno(e)\n}\n\n\/\/ SetPrivLevel: see rtos package.\nfunc SetPrivLevel(n int) (int, Errno) {\n\told, e := internal.Syscall1(SETPRIVLEVEL, uintptr(n))\n\treturn int(old), Errno(e)\n}\n\n\/\/ DebugOutString allows write debug message.\nfunc DebugOutString(port int, s string) (int, Errno) {\n\tp := (*internal.String)(unsafe.Pointer(&s))\n\tn, e := internal.Syscall3(DEBUGOUT, uintptr(port), p.Addr, p.Len)\n\treturn int(n), Errno(e)\n}\n\n\/\/ DebugOut allows write debug message.\nfunc DebugOut(port int, b []byte) (int, Errno) {\n\treturn DebugOutString(port, *(*string)(unsafe.Pointer(&b)))\n}\n<commit_msg>syscall: Fix bug in TriggerIRQ.<commit_after>\/\/ +build noos\n\npackage syscall\n\nimport (\n\t\"bits\"\n\t\"internal\"\n\t\"unsafe\"\n)\n\nconst (\n\tNEWTASK    = internal.NEWTASK\n\tKILLTASK   = internal.KILLTASK\n\tTASKUNLOCK = internal.TASKUNLOCK\n\tMAXTASKS   = iota\n\tSCHEDNEXT\n\tEVENTWAIT\n\tSETSYSTIM\n\tNANOSEC\n\tSETALARM\n\tSETAT\n\tSETIRQENA\n\tSETIRQPRIO\n\tSETIRQHANDLER\n\tIRQSTATUS\n\tTRIGGERIRQ\n\tSETPRIVLEVEL\n\tDEBUGOUT\n)\n\n\/\/ NewTask creates new task that starts execute f. If lock is true tasker stops\n\/\/ scheduling current task and waits until new task will call TaskUnlock. When\n\/\/ success it returns TID of new task.\nfunc NewTask(f func(), lock bool) (int, Errno) {\n\ttid, e := internal.Syscall2(NEWTASK, ftou(f), uintptr(bits.One(lock)))\n\treturn int(tid), Errno(e)\n}\n\n\/\/ KillTask kills task with specified tid. tid == 0 means current task.\nfunc KillTask(tid int) Errno {\n\t_, e := internal.Syscall1(KILLTASK, uintptr(tid))\n\treturn Errno(e)\n}\n\n\/\/ TaskUnlock can be used when task was created with lock option. It informs\n\/\/ tasker that now it can safely run parent task.\nfunc TaskUnlock() {\n\tinternal.Syscall0(TASKUNLOCK)\n}\n\n\/\/ MaxTasks: see rtos package.\nfunc MaxTasks() int {\n\tn, _ := internal.Syscall0(MAXTASKS)\n\treturn int(n)\n}\n\n\/\/ SchedYield causes the calling task to relinquish the CPU.\nfunc SchedYield() {\n\tinternal.Syscall0(SCHEDNEXT)\n}\n\n\/\/ SchedNext informs tasker that it need to schedule next ready to run task.\n\/\/ It is safe to call SchedNext from interrupt handler.\nfunc SchedNext() {\n\tschedNext()\n}\n\n\/\/ SetSysTimer registers two functions that the runtime uses to communicate with\n\/\/ the system timer.\n\/\/\n\/\/ Nanosec is used to implement Nanosec system call. It should return the\n\/\/ monotonic time in nanoseconds (typically the time of system timer run).\n\/\/\n\/\/ SetWakeUp is called by scheduler to ask system timer to wake it up at time t\n\/\/ (using SchedNext function). T can be a monotonic time in nanoseconds or -1\n\/\/ if the scheduler does not want to be woken. System timer must guarantee that\n\/\/ it will wake up the scheduler at t or after t. Additional awakenings before\n\/\/ and after t are acceptable but not recommended. Ticking timer simply wakes up\n\/\/ the scheduler with a constant period and its setWakeUp function does nothing.\n\/\/ Tickless timer schould wake up the scheduler only once, at t or just after t.\nfunc SetSysTimer(nanosec func() int64, setWakeUp func(t int64)) {\n\tinternal.Syscall2(SETSYSTIM, fr64tou(nanosec), f64tou(setWakeUp))\n}\n\n\/\/ Nanosec: see rtos package.\nfunc Nanosec() int64 {\n\treturn internal.Syscall0r64(NANOSEC)\n}\n\n\/\/ SetAlarm asks the runtime to send Alarm event at t. T is only a hint for the\n\/\/ runtime, because it can send alarm at any time: before t, at t and after t.\n\/\/ Typically, task use SetAlarm in conjunction with Alarm.Wait and Nanosec.\nfunc SetAlarm(t int64) {\n\tinternal.Syscall1i64(SETALARM, t)\n}\n\n\/\/ SetAt works like SetAlarm but additionaly sets task local variable, used to\n\/\/ implement internal.TimeChan.\nfunc SetAt(t int64) {\n\tinternal.Syscall1i64(SETAT, t)\n}\n\n\/\/ TimeChan returns channel that can be used to wait for time set using\n\/\/ SetAt. TimeChan is used mainly for deadline\/timeout in select statements.\nfunc TimeChan() <-chan int64 {\n\tch := &internal.TimeChan\n\treturn *(*<-chan int64)(unsafe.Pointer(&ch))\n}\n\n\/\/ SetIRQEna enables or disables irq.\nfunc SetIRQEna(irq int, ena bool) Errno {\n\t_, e := internal.Syscall2(SETIRQENA, uintptr(irq), uintptr(bits.One(ena)))\n\treturn Errno(e)\n}\n\n\/\/ SetIRQPrio sets priority for irq.\nfunc SetIRQPrio(irq, prio int) Errno {\n\t_, err := internal.Syscall2(SETIRQPRIO, uintptr(irq), uintptr(prio))\n\treturn Errno(err)\n}\n\n\/\/ SetIRQHandler: see rtos package.\nfunc SetIRQHandler(irq int, f func()) Errno {\n\t_, e := internal.Syscall2(SETIRQHANDLER, uintptr(irq), ftou(f))\n\treturn Errno(e)\n}\n\n\/\/ IRQStatus: ee rtos package.\nfunc IRQStatus(irq int) (int, Errno) {\n\ts, e := internal.Syscall1(IRQSTATUS, uintptr(irq))\n\treturn int(s), Errno(e)\n}\n\n\/\/ TriggerIRQ: see rtos package.\nfunc TriggerIRQ(irq int) Errno {\n\t_, e := internal.Syscall1(TRIGGERIRQ, uintptr(irq))\n\treturn Errno(e)\n}\n\n\/\/ SetPrivLevel: see rtos package.\nfunc SetPrivLevel(n int) (int, Errno) {\n\told, e := internal.Syscall1(SETPRIVLEVEL, uintptr(n))\n\treturn int(old), Errno(e)\n}\n\n\/\/ DebugOutString allows write debug message.\nfunc DebugOutString(port int, s string) (int, Errno) {\n\tp := (*internal.String)(unsafe.Pointer(&s))\n\tn, e := internal.Syscall3(DEBUGOUT, uintptr(port), p.Addr, p.Len)\n\treturn int(n), Errno(e)\n}\n\n\/\/ DebugOut allows write debug message.\nfunc DebugOut(port int, b []byte) (int, Errno) {\n\treturn DebugOutString(port, *(*string)(unsafe.Pointer(&b)))\n}\n<|endoftext|>"}
{"text":"<commit_before>package kafka\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/json-iterator\/go\"\n\n\t\"github.com\/qiniu\/log\"\n\n\t\"github.com\/qiniu\/logkit\/conf\"\n\t\"github.com\/qiniu\/logkit\/sender\"\n\t. \"github.com\/qiniu\/logkit\/utils\/models\"\n)\n\nvar _ sender.SkipDeepCopySender = &Sender{}\n\ntype Sender struct {\n\tname  string\n\thosts []string\n\ttopic []string\n\tcfg   *sarama.Config\n\n\tlastError error \/\/用于防止所有的错误都被 kafka熔断的错误提示刷掉\n\tproducer  sarama.SyncProducer\n}\n\nvar (\n\tcompressionModes = map[string]sarama.CompressionCodec{\n\t\tsender.KeyKafkaCompressionNone:   sarama.CompressionNone,\n\t\tsender.KeyKafkaCompressionGzip:   sarama.CompressionGZIP,\n\t\tsender.KeyKafkaCompressionSnappy: sarama.CompressionSnappy,\n\t}\n)\n\nfunc init() {\n\tsender.RegisterConstructor(sender.TypeKafka, NewSender)\n}\n\n\/\/ kafka sender\nfunc NewSender(conf conf.MapConf) (kafkaSender sender.Sender, err error) {\n\thosts, err := conf.GetStringList(sender.KeyKafkaHost)\n\tif err != nil {\n\t\treturn\n\t}\n\ttopic, err := conf.GetStringList(sender.KeyKafkaTopic)\n\tif err != nil {\n\t\treturn\n\t}\n\ttopic, err = ExtractField(topic)\n\tif err != nil {\n\t\treturn\n\t}\n\thostName, err := os.Hostname()\n\tif err != nil {\n\t\thostName = \"getHostnameErr:\" + err.Error()\n\t\terr = nil\n\t}\n\tclientID, _ := conf.GetStringOr(sender.KeyKafkaClientId, hostName)\n\t\/\/num, _ := conf.GetIntOr(KeyKafkaFlushNum, 200)\n\t\/\/frequency, _ := conf.GetIntOr(KeyKafkaFlushFrequency, 5)\n\tretryMax, _ := conf.GetIntOr(sender.KeyKafkaRetryMax, 3)\n\tcompression, _ := conf.GetStringOr(sender.KeyKafkaCompression, sender.KeyKafkaCompressionNone)\n\ttimeout, _ := conf.GetStringOr(sender.KeyKafkaTimeout, \"30s\")\n\tkeepAlive, _ := conf.GetStringOr(sender.KeyKafkaKeepAlive, \"0\")\n\tmaxMessageBytes, _ := conf.GetIntOr(sender.KeyMaxMessageBytes, 4*1024*1024)\n\n\tname, _ := conf.GetStringOr(sender.KeyName, fmt.Sprintf(\"kafkaSender:(kafkaUrl:%s,topic:%s)\", hosts, topic))\n\tcfg := sarama.NewConfig()\n\tcfg.Producer.Return.Successes = true\n\tcfg.Producer.Return.Errors = true\n\t\/\/cfg.Producer.Return.Successes = false\n\t\/\/cfg.Producer.Return.Errors = false\n\t\/\/客户端ID\n\tcfg.ClientID = clientID\n\t\/\/批量发送条数\n\t\/\/cfg.Producer.Flush.Messages = num\n\t\/\/批量发送间隔\n\t\/\/cfg.Producer.Flush.Frequency =  time.Duration(frequency) * time.Second\n\tcfg.Producer.Retry.Max = retryMax\n\tcompressionMode, ok := compressionModes[strings.ToLower(compression)]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unknown compression mode: '%v'\", compression)\n\t}\n\tcfg.Producer.Compression = compressionMode\n\tcfg.Net.DialTimeout, err = time.ParseDuration(timeout)\n\tif err != nil {\n\t\treturn\n\t}\n\tcfg.Net.KeepAlive, err = time.ParseDuration(keepAlive)\n\tif err != nil {\n\t\treturn\n\t}\n\tcfg.Producer.MaxMessageBytes = maxMessageBytes\n\n\tproducer, err := sarama.NewSyncProducer(hosts, cfg)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tkafkaSender = newSender(name, hosts, topic, cfg, producer)\n\treturn\n}\n\nfunc newSender(name string, hosts []string, topic []string, cfg *sarama.Config, producer sarama.SyncProducer) (k *Sender) {\n\tk = &Sender{\n\t\tname:     name,\n\t\thosts:    hosts,\n\t\ttopic:    topic,\n\t\tcfg:      cfg,\n\t\tproducer: producer,\n\t}\n\treturn\n}\n\nfunc (this *Sender) Name() string {\n\treturn this.name\n}\n\nfunc (this *Sender) Send(data []Data) error {\n\tproducer := this.producer\n\tvar msgs []*sarama.ProducerMessage\n\tss := &StatsError{}\n\tvar lastErr error\n\tfor _, doc := range data {\n\t\tmessage, err := this.getEventMessage(doc)\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"Dropping event: %v\", err)\n\t\t\tss.AddErrors()\n\t\t\tlastErr = err\n\t\t\tcontinue\n\t\t}\n\t\tmsgs = append(msgs, message)\n\t}\n\terr := producer.SendMessages(msgs)\n\tif err != nil {\n\t\tss.AddErrorsNum(len(msgs))\n\t\tif pde, ok := err.(sarama.ProducerErrors); ok {\n\t\t\tvar allcir = true\n\t\t\tfor _, v := range pde {\n\t\t\t\t\/\/对于熔断的错误提示，没有任何帮助，过滤掉\n\t\t\t\tif strings.Contains(v.Error(), \"circuit breaker is open\") {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tallcir = false\n\t\t\t\tss.ErrorDetail = fmt.Errorf(\"%v detail: %v\", ss.ErrorDetail, v.Error())\n\t\t\t\tthis.lastError = v\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif allcir {\n\t\t\t\tss.ErrorDetail = fmt.Errorf(\"%v, all error is circuit breaker is open , last error %v\", err, this.lastError)\n\t\t\t}\n\t\t} else {\n\t\t\tss.ErrorDetail = err\n\t\t}\n\t\treturn ss\n\t}\n\tss.AddSuccessNum(len(msgs))\n\tif lastErr != nil {\n\t\tss.LastError = lastErr.Error()\n\t\treturn ss\n\t}\n\t\/\/本次发送成功, lastError 置为 nil\n\tthis.lastError = nil\n\treturn ss\n}\n\nfunc (kf *Sender) getEventMessage(event map[string]interface{}) (pm *sarama.ProducerMessage, err error) {\n\tvar topic string\n\tif len(kf.topic) == 2 {\n\t\tif event[kf.topic[0]] == nil || event[kf.topic[0]] == \"\" {\n\t\t\ttopic = kf.topic[1]\n\t\t} else {\n\t\t\tif mytopic, ok := event[kf.topic[0]].(string); ok {\n\t\t\t\ttopic = mytopic\n\t\t\t} else {\n\t\t\t\ttopic = kf.topic[1]\n\t\t\t}\n\t\t}\n\t} else {\n\t\ttopic = kf.topic[0]\n\t}\n\tvalue, err := jsoniter.Marshal(event)\n\tif err != nil {\n\t\treturn\n\t}\n\tpm = &sarama.ProducerMessage{\n\t\tTopic: topic,\n\t\tValue: sarama.StringEncoder(string(value)),\n\t}\n\treturn\n}\n\nfunc (this *Sender) Close() (err error) {\n\tlog.Infof(\"kafka sender was closed\")\n\tthis.producer.Close()\n\tthis.producer = nil\n\treturn nil\n}\n\nfunc (_ *Sender) SkipDeepCopy() bool { return true }\n<commit_msg>kafka sender unpack message with binary when sender error is message too large<commit_after>package kafka\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/json-iterator\/go\"\n\n\t\"github.com\/qiniu\/log\"\n\t\"github.com\/qiniu\/pandora-go-sdk\/base\/reqerr\"\n\n\t\"github.com\/qiniu\/logkit\/conf\"\n\t\"github.com\/qiniu\/logkit\/sender\"\n\t. \"github.com\/qiniu\/logkit\/utils\/models\"\n)\n\nvar _ sender.SkipDeepCopySender = &Sender{}\n\ntype Sender struct {\n\tname  string\n\thosts []string\n\ttopic []string\n\tcfg   *sarama.Config\n\n\tlastError error \/\/用于防止所有的错误都被 kafka熔断的错误提示刷掉\n\tproducer  sarama.SyncProducer\n}\n\nvar (\n\tcompressionModes = map[string]sarama.CompressionCodec{\n\t\tsender.KeyKafkaCompressionNone:   sarama.CompressionNone,\n\t\tsender.KeyKafkaCompressionGzip:   sarama.CompressionGZIP,\n\t\tsender.KeyKafkaCompressionSnappy: sarama.CompressionSnappy,\n\t}\n)\n\nfunc init() {\n\tsender.RegisterConstructor(sender.TypeKafka, NewSender)\n}\n\n\/\/ kafka sender\nfunc NewSender(conf conf.MapConf) (kafkaSender sender.Sender, err error) {\n\thosts, err := conf.GetStringList(sender.KeyKafkaHost)\n\tif err != nil {\n\t\treturn\n\t}\n\ttopic, err := conf.GetStringList(sender.KeyKafkaTopic)\n\tif err != nil {\n\t\treturn\n\t}\n\ttopic, err = ExtractField(topic)\n\tif err != nil {\n\t\treturn\n\t}\n\thostName, err := os.Hostname()\n\tif err != nil {\n\t\thostName = \"getHostnameErr:\" + err.Error()\n\t\terr = nil\n\t}\n\tclientID, _ := conf.GetStringOr(sender.KeyKafkaClientId, hostName)\n\t\/\/num, _ := conf.GetIntOr(KeyKafkaFlushNum, 200)\n\t\/\/frequency, _ := conf.GetIntOr(KeyKafkaFlushFrequency, 5)\n\tretryMax, _ := conf.GetIntOr(sender.KeyKafkaRetryMax, 3)\n\tcompression, _ := conf.GetStringOr(sender.KeyKafkaCompression, sender.KeyKafkaCompressionNone)\n\ttimeout, _ := conf.GetStringOr(sender.KeyKafkaTimeout, \"30s\")\n\tkeepAlive, _ := conf.GetStringOr(sender.KeyKafkaKeepAlive, \"0\")\n\tmaxMessageBytes, _ := conf.GetIntOr(sender.KeyMaxMessageBytes, 4*1024*1024)\n\n\tname, _ := conf.GetStringOr(sender.KeyName, fmt.Sprintf(\"kafkaSender:(kafkaUrl:%s,topic:%s)\", hosts, topic))\n\tcfg := sarama.NewConfig()\n\tcfg.Producer.Return.Successes = true\n\tcfg.Producer.Return.Errors = true\n\t\/\/cfg.Producer.Return.Successes = false\n\t\/\/cfg.Producer.Return.Errors = false\n\t\/\/客户端ID\n\tcfg.ClientID = clientID\n\t\/\/批量发送条数\n\t\/\/cfg.Producer.Flush.Messages = num\n\t\/\/批量发送间隔\n\t\/\/cfg.Producer.Flush.Frequency =  time.Duration(frequency) * time.Second\n\tcfg.Producer.Retry.Max = retryMax\n\tcompressionMode, ok := compressionModes[strings.ToLower(compression)]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unknown compression mode: '%v'\", compression)\n\t}\n\tcfg.Producer.Compression = compressionMode\n\tcfg.Net.DialTimeout, err = time.ParseDuration(timeout)\n\tif err != nil {\n\t\treturn\n\t}\n\tcfg.Net.KeepAlive, err = time.ParseDuration(keepAlive)\n\tif err != nil {\n\t\treturn\n\t}\n\tcfg.Producer.MaxMessageBytes = maxMessageBytes\n\n\tproducer, err := sarama.NewSyncProducer(hosts, cfg)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tkafkaSender = newSender(name, hosts, topic, cfg, producer)\n\treturn\n}\n\nfunc newSender(name string, hosts []string, topic []string, cfg *sarama.Config, producer sarama.SyncProducer) (k *Sender) {\n\tk = &Sender{\n\t\tname:     name,\n\t\thosts:    hosts,\n\t\ttopic:    topic,\n\t\tcfg:      cfg,\n\t\tproducer: producer,\n\t}\n\treturn\n}\n\nfunc (this *Sender) Name() string {\n\treturn this.name\n}\n\nfunc (this *Sender) Send(data []Data) error {\n\tproducer := this.producer\n\tvar msgs []*sarama.ProducerMessage\n\tss := &StatsError{}\n\tvar lastErr error\n\tfor _, doc := range data {\n\t\tmessage, err := this.getEventMessage(doc)\n\t\tif err != nil {\n\t\t\tlog.Debugf(\"Dropping event: %v\", err)\n\t\t\tss.AddErrors()\n\t\t\tlastErr = err\n\t\t\tcontinue\n\t\t}\n\t\tmsgs = append(msgs, message)\n\t}\n\terr := producer.SendMessages(msgs)\n\tif err != nil {\n\t\tss.AddErrorsNum(len(msgs))\n\t\tif pde, ok := err.(sarama.ProducerErrors); ok {\n\t\t\tvar allcir = true\n\t\t\tfor _, v := range pde {\n\t\t\t\t\/\/对于熔断的错误提示，没有任何帮助，过滤掉\n\t\t\t\tif strings.Contains(v.Error(), \"circuit breaker is open\") {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tallcir = false\n\t\t\t\tss.ErrorDetail = fmt.Errorf(\"%v detail: %v\", ss.ErrorDetail, v.Error())\n\t\t\t\tthis.lastError = v\n\t\t\t\t\/\/发送错误为message too large时，启用二分策略重新发送\n\t\t\t\tif v.Err == sarama.ErrMessageSizeTooLarge {\n\t\t\t\t\tss.ErrorDetail = reqerr.NewSendError(\"Sender[Kafka]:Message was too large, server rejected it to avoid allocation error\", sender.ConvertDatasBack(data), reqerr.TypeBinaryUnpack)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif allcir {\n\t\t\t\tss.ErrorDetail = fmt.Errorf(\"%v, all error is circuit breaker is open , last error %v\", err, this.lastError)\n\t\t\t}\n\t\t} else {\n\t\t\tss.ErrorDetail = err\n\t\t}\n\t\treturn ss\n\t}\n\tss.AddSuccessNum(len(msgs))\n\tif lastErr != nil {\n\t\tss.LastError = lastErr.Error()\n\t\treturn ss\n\t}\n\t\/\/本次发送成功, lastError 置为 nil\n\tthis.lastError = nil\n\treturn ss\n}\n\nfunc (kf *Sender) getEventMessage(event map[string]interface{}) (pm *sarama.ProducerMessage, err error) {\n\tvar topic string\n\tif len(kf.topic) == 2 {\n\t\tif event[kf.topic[0]] == nil || event[kf.topic[0]] == \"\" {\n\t\t\ttopic = kf.topic[1]\n\t\t} else {\n\t\t\tif mytopic, ok := event[kf.topic[0]].(string); ok {\n\t\t\t\ttopic = mytopic\n\t\t\t} else {\n\t\t\t\ttopic = kf.topic[1]\n\t\t\t}\n\t\t}\n\t} else {\n\t\ttopic = kf.topic[0]\n\t}\n\tvalue, err := jsoniter.Marshal(event)\n\tif err != nil {\n\t\treturn\n\t}\n\tpm = &sarama.ProducerMessage{\n\t\tTopic: topic,\n\t\tValue: sarama.StringEncoder(string(value)),\n\t}\n\treturn\n}\n\nfunc (this *Sender) Close() (err error) {\n\tlog.Infof(\"kafka sender was closed\")\n\tthis.producer.Close()\n\tthis.producer = nil\n\treturn nil\n}\n\nfunc (_ *Sender) SkipDeepCopy() bool { return true }\n<|endoftext|>"}
{"text":"<commit_before>package agent\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/jrallison\/go-workers\"\n\t\"github.com\/pborman\/uuid\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ Agent runs codeflow and collects data based on the given config\ntype Agent struct {\n\tQueueing   bool\n\tEvents     chan Event\n\tTestEvents chan Event\n\tShutdown   chan struct{}\n\tPlugins    []*RunningPlugin\n}\n\n\/\/ NewAgent returns an Agent struct based off the given Config\nfunc NewAgent() (*Agent, error) {\n\tif len(viper.GetStringMap(\"plugins\")) == 0 {\n\t\tlog.Fatalf(\"Error: no plugins found, did you provide a valid config file?\")\n\t}\n\n\tagent := &Agent{}\n\n\t\/\/ channel shared between all plugin threads for accumulating events\n\tagent.Events = make(chan Event, 10000)\n\n\t\/\/ channel shared between all plugin threads to trigger shutdown\n\tagent.Shutdown = make(chan struct{})\n\n\tif err := agent.LoadPlugins(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn agent, nil\n}\n\n\/\/ NewTestAgent returns an Agent struct based off the given Config\nfunc NewTestAgent(config []byte) (*Agent, error) {\n\tvar err error\n\tvar agent *Agent\n\n\tviper.SetConfigType(\"yaml\")\n\tviper.ReadConfig(bytes.NewBuffer(config))\n\n\tif agent, err = NewAgent(); err != nil {\n\t\tlog.Fatalf(\"Error while initializing agent: %v\", err)\n\t}\n\n\tagent.TestEvents = make(chan Event, 10000)\n\tagent.Queueing = false\n\n\treturn agent, nil\n}\n\nfunc (a *Agent) LoadPlugins() error {\n\tvar err error\n\n\tep := viper.GetString(\"run\")\n\trunPlugins := strings.Split(strings.Trim(ep, \"[]\"), \",\")\n\tfor name := range viper.GetStringMap(\"plugins\") {\n\t\tif err = a.addPlugin(name); err != nil {\n\t\t\treturn fmt.Errorf(\"Error parsing %s, %s\", name, err)\n\t\t}\n\t\tif ep == \"\" || SliceContains(name, runPlugins) {\n\t\t\tif err = a.enablePlugin(name); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error parsing %s, %s\", name, err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Returns a list of strings of the configured plugins.\nfunc (a *Agent) PluginNames() []string {\n\tvar name []string\n\tfor key, _ := range viper.GetStringMap(\"plugins\") {\n\t\tname = append(name, key)\n\t}\n\treturn name\n}\n\nfunc (a *Agent) addPlugin(name string) error {\n\tif len(a.PluginNames()) > 0 && !SliceContains(name, a.PluginNames()) {\n\t\treturn nil\n\t}\n\n\tcreator, ok := PluginRegistry[name]\n\tif !ok {\n\t\treturn fmt.Errorf(\"Undefined but requested Plugin: %s\", name)\n\t}\n\tplugin := creator()\n\n\tviper.UnmarshalKey(fmt.Sprint(\"plugins.\", name), plugin)\n\n\twork := func(message *workers.Msg) {\n\t\te, _ := json.Marshal(message.Args())\n\t\tevent := Event{}\n\t\tjson.Unmarshal([]byte(e), &event)\n\t\tif err := MapPayload(event.PayloadModel, &event); err != nil {\n\t\t\tevent.Error = fmt.Errorf(\"PayloadModel not found: %s. Did you add it to ApiRegistry?\", event.PayloadModel)\n\t\t}\n\n\t\t\/\/ For debugging purposes\n\t\tevent.Dump()\n\n\t\tplugin.Process(event)\n\t}\n\n\trp := &RunningPlugin{\n\t\tName:    name,\n\t\tPlugin:  plugin,\n\t\tWork:    work,\n\t\tEnabled: false,\n\t\tWorkers: viper.GetInt(\"plugins.\" + name + \".workers\"),\n\t}\n\n\ta.Plugins = append(a.Plugins, rp)\n\n\treturn nil\n}\n\nfunc (a *Agent) enablePlugin(name string) error {\n\tif len(a.PluginNames()) > 0 && !SliceContains(name, a.PluginNames()) {\n\t\treturn nil\n\t}\n\n\tfor _, rp := range a.Plugins {\n\t\tif rp.Name == name {\n\t\t\trp.Enabled = true\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ flusher monitors the events plugin channel and schedules them to correct queues\nfunc (a *Agent) flusher() {\n\tfor {\n\t\tselect {\n\t\tcase <-a.Shutdown:\n\t\t\tlog.Println(\"Hang on, flushing any cached metrics before shutdown\")\n\t\t\treturn\n\t\tcase e := <-a.Events:\n\t\t\tev_handled := false\n\n\t\t\tfor _, plugin := range a.Plugins {\n\t\t\t\tif plugin.Workers > 0 {\n\t\t\t\t\tsubscribedTo := plugin.Plugin.Subscribe()\n\t\t\t\t\tif SliceContains(e.PayloadModel, subscribedTo) || SliceContains(e.Name, subscribedTo) {\n\t\t\t\t\t\tev_handled = true\n\t\t\t\t\t\tif a.Queueing {\n\t\t\t\t\t\t\tlog.Printf(\"Enqueue event %v for %v\\n\", e.Name, plugin.Name)\n\t\t\t\t\t\t\tworkers.Enqueue(plugin.Name, \"Event\", e)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tplugin.Plugin.Process(e)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif a.TestEvents != nil {\n\t\t\t\ta.TestEvents <- e\n\t\t\t} else if !ev_handled {\n\t\t\t\tlog.Printf(\"Event not handled by any plugin: %s\\n\", e.Name)\n\t\t\t\te.Dump()\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Run runs the agent daemon\nfunc (a *Agent) Run() error {\n\tvar wg sync.WaitGroup\n\n\tif a.Queueing {\n\t\tworkers.Middleware = workers.NewMiddleware(\n\t\t\t&workers.MiddlewareRetry{},\n\t\t\t&workers.MiddlewareStats{},\n\t\t)\n\n\t\tworkers.Configure(map[string]string{\n\t\t\t\"server\":   viper.GetString(\"redis.server\"),\n\t\t\t\"database\": viper.GetString(\"redis.database\"),\n\t\t\t\"pool\":     viper.GetString(\"redis.pool\"),\n\t\t\t\"process\":  uuid.New(),\n\t\t})\n\t}\n\n\tfor _, plugin := range a.Plugins {\n\t\tif !plugin.Enabled {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Start service of any Plugins\n\t\tswitch p := plugin.Plugin.(type) {\n\t\tcase Plugin:\n\t\t\tif err := p.Start(a.Events); err != nil {\n\t\t\t\tlog.Printf(\"Service for plugin %s failed to start, exiting\\n%s\\n\",\n\t\t\t\t\tplugin.Name, err.Error())\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer p.Stop()\n\n\t\t\tif a.Queueing {\n\t\t\t\tworkers.Process(plugin.Name, plugin.Work, viper.GetInt(\"plugins.\"+plugin.Name+\".workers\"))\n\t\t\t}\n\t\t}\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ta.flusher()\n\t}()\n\n\tif a.Queueing {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tworkers.Run()\n\t\t\ta.Stop()\n\t\t}()\n\n\t\t\/\/wg.Add(1)\n\t\t\/\/go func() {\n\t\t\/\/\tdefer wg.Done()\n\t\t\/\/\tworkers.StatsServer(8080)\n\t\t\/\/}()\n\t}\n\n\twg.Wait()\n\treturn nil\n}\n\n\/\/ Shutdown the agent daemon\nfunc (a *Agent) Stop() {\n\tclose(a.Shutdown)\n}\n\n\/\/ GetTestEvent listens and returns requested event\nfunc (a *Agent) GetTestEvent(name string, timeout time.Duration) Event {\n\t\/\/ timeout in the case that we don't get requested event\n\ttimer := time.NewTimer(time.Second * timeout)\n\tgo func() {\n\t\t<-timer.C\n\t\ta.Stop()\n\t\tlog.Fatalf(\"Timer expired waiting for event: %v\", name)\n\t}()\n\n\tfor e := range a.TestEvents {\n\t\tif e.Name == name {\n\t\t\ttimer.Stop()\n\t\t\treturn e\n\t\t}\n\t}\n\n\treturn Event{}\n}\n<commit_msg>Fix agent run plugins<commit_after>package agent\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/jrallison\/go-workers\"\n\t\"github.com\/pborman\/uuid\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ Agent runs codeflow and collects data based on the given config\ntype Agent struct {\n\tQueueing   bool\n\tEvents     chan Event\n\tTestEvents chan Event\n\tShutdown   chan struct{}\n\tPlugins    []*RunningPlugin\n}\n\n\/\/ NewAgent returns an Agent struct based off the given Config\nfunc NewAgent() (*Agent, error) {\n\tif len(viper.GetStringMap(\"plugins\")) == 0 {\n\t\tlog.Fatalf(\"Error: no plugins found, did you provide a valid config file?\")\n\t}\n\n\tagent := &Agent{}\n\n\t\/\/ channel shared between all plugin threads for accumulating events\n\tagent.Events = make(chan Event, 10000)\n\n\t\/\/ channel shared between all plugin threads to trigger shutdown\n\tagent.Shutdown = make(chan struct{})\n\n\tif err := agent.LoadPlugins(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn agent, nil\n}\n\n\/\/ NewTestAgent returns an Agent struct based off the given Config\nfunc NewTestAgent(config []byte) (*Agent, error) {\n\tvar err error\n\tvar agent *Agent\n\n\tviper.SetConfigType(\"yaml\")\n\tviper.ReadConfig(bytes.NewBuffer(config))\n\n\tif agent, err = NewAgent(); err != nil {\n\t\tlog.Fatalf(\"Error while initializing agent: %v\", err)\n\t}\n\n\tagent.TestEvents = make(chan Event, 10000)\n\tagent.Queueing = false\n\n\treturn agent, nil\n}\n\nfunc (a *Agent) LoadPlugins() error {\n\tvar err error\n\n\trunPlugins := viper.GetStringSlice(\"run\")\n\tfor name := range viper.GetStringMap(\"plugins\") {\n\t\tif err = a.addPlugin(name); err != nil {\n\t\t\treturn fmt.Errorf(\"Error parsing %s, %s\", name, err)\n\t\t}\n\t\tif len(runPlugins) == 0 || SliceContains(name, runPlugins) {\n\t\t\tif err = a.enablePlugin(name); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error parsing %s, %s\", name, err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Returns a list of strings of the configured plugins.\nfunc (a *Agent) PluginNames() []string {\n\tvar name []string\n\tfor key, _ := range viper.GetStringMap(\"plugins\") {\n\t\tname = append(name, key)\n\t}\n\treturn name\n}\n\nfunc (a *Agent) addPlugin(name string) error {\n\tif len(a.PluginNames()) > 0 && !SliceContains(name, a.PluginNames()) {\n\t\treturn nil\n\t}\n\n\tcreator, ok := PluginRegistry[name]\n\tif !ok {\n\t\treturn fmt.Errorf(\"Undefined but requested Plugin: %s\", name)\n\t}\n\tplugin := creator()\n\n\tviper.UnmarshalKey(fmt.Sprint(\"plugins.\", name), plugin)\n\n\twork := func(message *workers.Msg) {\n\t\te, _ := json.Marshal(message.Args())\n\t\tevent := Event{}\n\t\tjson.Unmarshal([]byte(e), &event)\n\t\tif err := MapPayload(event.PayloadModel, &event); err != nil {\n\t\t\tevent.Error = fmt.Errorf(\"PayloadModel not found: %s. Did you add it to ApiRegistry?\", event.PayloadModel)\n\t\t}\n\n\t\t\/\/ For debugging purposes\n\t\tevent.Dump()\n\n\t\tplugin.Process(event)\n\t}\n\n\trp := &RunningPlugin{\n\t\tName:    name,\n\t\tPlugin:  plugin,\n\t\tWork:    work,\n\t\tEnabled: false,\n\t\tWorkers: viper.GetInt(\"plugins.\" + name + \".workers\"),\n\t}\n\n\ta.Plugins = append(a.Plugins, rp)\n\n\treturn nil\n}\n\nfunc (a *Agent) enablePlugin(name string) error {\n\tif len(a.PluginNames()) > 0 && !SliceContains(name, a.PluginNames()) {\n\t\treturn nil\n\t}\n\n\tfor _, rp := range a.Plugins {\n\t\tif rp.Name == name {\n\t\t\trp.Enabled = true\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ flusher monitors the events plugin channel and schedules them to correct queues\nfunc (a *Agent) flusher() {\n\tfor {\n\t\tselect {\n\t\tcase <-a.Shutdown:\n\t\t\tlog.Println(\"Hang on, flushing any cached metrics before shutdown\")\n\t\t\treturn\n\t\tcase e := <-a.Events:\n\t\t\tev_handled := false\n\n\t\t\tfor _, plugin := range a.Plugins {\n\t\t\t\tif plugin.Workers > 0 {\n\t\t\t\t\tsubscribedTo := plugin.Plugin.Subscribe()\n\t\t\t\t\tif SliceContains(e.PayloadModel, subscribedTo) || SliceContains(e.Name, subscribedTo) {\n\t\t\t\t\t\tev_handled = true\n\t\t\t\t\t\tif a.Queueing {\n\t\t\t\t\t\t\tlog.Printf(\"Enqueue event %v for %v\\n\", e.Name, plugin.Name)\n\t\t\t\t\t\t\tworkers.Enqueue(plugin.Name, \"Event\", e)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tplugin.Plugin.Process(e)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif a.TestEvents != nil {\n\t\t\t\ta.TestEvents <- e\n\t\t\t} else if !ev_handled {\n\t\t\t\tlog.Printf(\"Event not handled by any plugin: %s\\n\", e.Name)\n\t\t\t\te.Dump()\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Run runs the agent daemon\nfunc (a *Agent) Run() error {\n\tvar wg sync.WaitGroup\n\n\tif a.Queueing {\n\t\tworkers.Middleware = workers.NewMiddleware(\n\t\t\t&workers.MiddlewareRetry{},\n\t\t\t&workers.MiddlewareStats{},\n\t\t)\n\n\t\tworkers.Configure(map[string]string{\n\t\t\t\"server\":   viper.GetString(\"redis.server\"),\n\t\t\t\"database\": viper.GetString(\"redis.database\"),\n\t\t\t\"pool\":     viper.GetString(\"redis.pool\"),\n\t\t\t\"process\":  uuid.New(),\n\t\t})\n\t}\n\n\tfor _, plugin := range a.Plugins {\n\t\tif !plugin.Enabled {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Start service of any Plugins\n\t\tswitch p := plugin.Plugin.(type) {\n\t\tcase Plugin:\n\t\t\tif err := p.Start(a.Events); err != nil {\n\t\t\t\tlog.Printf(\"Service for plugin %s failed to start, exiting\\n%s\\n\",\n\t\t\t\t\tplugin.Name, err.Error())\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer p.Stop()\n\n\t\t\tif a.Queueing {\n\t\t\t\tworkers.Process(plugin.Name, plugin.Work, viper.GetInt(\"plugins.\"+plugin.Name+\".workers\"))\n\t\t\t}\n\t\t}\n\t}\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ta.flusher()\n\t}()\n\n\tif a.Queueing {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tworkers.Run()\n\t\t\ta.Stop()\n\t\t}()\n\n\t\t\/\/wg.Add(1)\n\t\t\/\/go func() {\n\t\t\/\/\tdefer wg.Done()\n\t\t\/\/\tworkers.StatsServer(8080)\n\t\t\/\/}()\n\t}\n\n\twg.Wait()\n\treturn nil\n}\n\n\/\/ Shutdown the agent daemon\nfunc (a *Agent) Stop() {\n\tclose(a.Shutdown)\n}\n\n\/\/ GetTestEvent listens and returns requested event\nfunc (a *Agent) GetTestEvent(name string, timeout time.Duration) Event {\n\t\/\/ timeout in the case that we don't get requested event\n\ttimer := time.NewTimer(time.Second * timeout)\n\tgo func() {\n\t\t<-timer.C\n\t\ta.Stop()\n\t\tlog.Fatalf(\"Timer expired waiting for event: %v\", name)\n\t}()\n\n\tfor e := range a.TestEvents {\n\t\tif e.Name == name {\n\t\t\ttimer.Stop()\n\t\t\treturn e\n\t\t}\n\t}\n\n\treturn Event{}\n}\n<|endoftext|>"}
{"text":"<commit_before>package server\n\nimport (\n\t\"errors\"\n\t\"github.com\/itsankoff\/gotcha\/common\"\n\t\"log\"\n)\n\n\/\/ Store for all authenticated outputs\n\/\/ Main facility to send a message to the remote user\ntype OutputStore struct {\n\toutputs map[string]chan<- *common.Message\n}\n\nfunc NewOutputStore() *OutputStore {\n\tout := &OutputStore{\n\t\toutputs: make(map[string]chan<- *common.Message),\n\t}\n\n\treturn out\n}\n\n\/\/ AddOutput adds user output in the store by id\nfunc (store *OutputStore) AddOutput(id string,\n\toutput chan<- *common.Message) error {\n\t_, ok := store.outputs[id]\n\tif ok {\n\t\treturn errors.New(\"Output for already exists for id \" + id)\n\t}\n\n\tstore.outputs[id] = output\n\tlog.Println(\"Add output in store\", id)\n\treturn nil\n}\n\n\/\/ RemoveOutput removes user output from the store by id\nfunc (store *OutputStore) RemoveOutput(id string) error {\n\t_, ok := store.outputs[id]\n\tif ok {\n\t\tdelete(store.outputs, id)\n\t\tlog.Println(\"Remove output from store\", id)\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"Failed to remove output from store \" + id)\n}\n\n\/\/ GetOutput returns a user output from the store by id\nfunc (store OutputStore) GetOutput(id string) chan<- *common.Message {\n\toutput, ok := store.outputs[id]\n\tif ok {\n\t\treturn output\n\t}\n\n\tlog.Println(\"Failed to get output for id\", id)\n\treturn nil\n}\n\n\/\/ Send sends a message to user's output\nfunc (store OutputStore) Send(msg *common.Message) {\n\toutput := store.GetOutput(msg.To())\n\tif output != nil {\n\t\toutput <- msg\n\t} else {\n\t\tlog.Println(\"Failed to send message\", msg)\n\t}\n}\n<commit_msg>* Add more comments<commit_after>package server\n\nimport (\n\t\"errors\"\n\t\"github.com\/itsankoff\/gotcha\/common\"\n\t\"log\"\n)\n\n\/\/ Store for all authenticated outputs. Main facility to send messages to remote\n\/\/ users\ntype OutputStore struct {\n\toutputs map[string]chan<- *common.Message\n}\n\n\/\/ NewOutputStore returns a valid store.\nfunc NewOutputStore() *OutputStore {\n\tout := &OutputStore{\n\t\toutputs: make(map[string]chan<- *common.Message),\n\t}\n\n\treturn out\n}\n\n\/\/ AddOutput adds user output in the store by id\nfunc (store *OutputStore) AddOutput(id string,\n\toutput chan<- *common.Message) error {\n\t_, ok := store.outputs[id]\n\tif ok {\n\t\treturn errors.New(\"Output for already exists for id \" + id)\n\t}\n\n\tstore.outputs[id] = output\n\tlog.Println(\"Add output in store\", id)\n\treturn nil\n}\n\n\/\/ RemoveOutput removes user output from the store by id\nfunc (store *OutputStore) RemoveOutput(id string) error {\n\t_, ok := store.outputs[id]\n\tif ok {\n\t\tdelete(store.outputs, id)\n\t\tlog.Println(\"Remove output from store\", id)\n\t\treturn nil\n\t}\n\n\treturn errors.New(\"Failed to remove output from store \" + id)\n}\n\n\/\/ GetOutput returns a user output from the store by id\nfunc (store OutputStore) GetOutput(id string) chan<- *common.Message {\n\toutput, ok := store.outputs[id]\n\tif ok {\n\t\treturn output\n\t}\n\n\tlog.Println(\"Failed to get output for id\", id)\n\treturn nil\n}\n\n\/\/ Send sends a message to user's output\nfunc (store OutputStore) Send(msg *common.Message) {\n\toutput := store.GetOutput(msg.To())\n\tif output != nil {\n\t\toutput <- msg\n\t} else {\n\t\tlog.Println(\"Failed to send message\", msg)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package server\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com\/fatih\/color\"\n)\n\nvar warn = color.New(color.FgYellow).Add(color.Bold).Println\n\nfunc procTestResponse(res *http.Response, t *testing.T, expectedCode int) {\n\tbody, err := ioutil.ReadAll(res.Body)\n\tres.Body.Close()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tfmt.Println(string(body) + \"\\n\")\n\tif res.StatusCode != expectedCode {\n\t\tt.Error(res.Request.Method + \": \" + res.Request.URL.Path + \" returned \" + strconv.Itoa(res.StatusCode) + \". Expected \" + strconv.Itoa(expectedCode) + \".\")\n\t\treturn\n\t}\n\tif res.StatusCode == 204 {\n\t\treturn\n\t}\n\tif res.StatusCode == 404 {\n\t\treturn\n\t}\n\tvar marsh interface{}\n\terr = json.Unmarshal(body, &marsh)\n\tif err != nil {\n\t\tt.Error(errors.New(res.Request.Method + \": failed to unmarshal response from \" + res.Request.URL.Path + \". Status code was: \" + strconv.Itoa(res.StatusCode)))\n\t}\n\t_, err = json.MarshalIndent(marsh, \"\", \"  \")\n\tif err != nil {\n\t\tt.Error(\"failed to Marshal\")\n\t}\n}\n\nfunc TestEndpoints(t *testing.T) {\n\n\ts := NewServer()\n\tr := s.NewRouter()\n\tserver := httptest.NewServer(r)\n\tdefer server.Close()\n\n\t\/\/ a few closures to save time below\n\tget := func(endpoint string, expectedCode int) {\n\t\tres, err := http.Get(server.URL + endpoint)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tprocTestResponse(res, t, expectedCode)\n\t}\n\n\tpost := func(endpoint, msg string, expectedCode int) {\n\t\tres, err := http.Post(server.URL+endpoint, \"application\/json\", bytes.NewBuffer([]byte(msg)))\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tprocTestResponse(res, t, expectedCode)\n\t}\n\n\tput := func(endpoint, msg string, expectedCode int) {\n\t\treq, err := http.NewRequest(\"PUT\", server.URL+endpoint, bytes.NewBuffer([]byte(msg)))\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tc := &http.Client{}\n\t\tres, err := c.Do(req)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tprocTestResponse(res, t, expectedCode)\n\t}\n\n\tdel := func(endpoint string, expectedCode int) {\n\t\treq, err := http.NewRequest(\"DELETE\", server.URL+endpoint, nil)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tc := &http.Client{}\n\t\tres, err := c.Do(req)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tprocTestResponse(res, t, expectedCode)\n\t}\n\n\t\/\/ set up a group (1)\n\tpost(\"\/groups\", `{\"parent\":0}`, 200)\n\n\t\/\/ set up a + block (2)\n\tpost(\"\/blocks\", `{\"type\":\"+\",\"parent\":1}`, 200)\n\n\t\/\/ label group 1\n\tput(\"\/groups\/1\/label\", `\"The Best Group Ever\"`, 204)\n\n\t\/\/ label the plus block\n\tput(\"\/blocks\/2\/label\", `\"my bestest adder\"`, 204)\n\n\t\/\/ move the plus block\n\tput(\"\/blocks\/2\/position\", `{\"x\":10,\"y\":10}`, 204)\n\n\t\/\/ get all the groups\n\tget(\"\/groups\", 200)\n\n\t\/\/ get group 1\n\tget(\"\/groups\/1\", 200)\n\n\t\/\/ move group 1\n\tput(\"\/groups\/1\/position\", `{\"x\":20,\"y\":20}`, 204)\n\n\t\/\/ get all the blocks\n\tget(\"\/blocks\", 200)\n\n\t\/\/ get the + block\n\tget(\"\/blocks\/2\", 200)\n\n\t\/\/ make a delay block (3)\n\tpost(\"\/blocks\", `{\"type\":\"delay\", \"parent\":1}`, 200)\n\n\t\/\/ set the delay's value\n\tput(\"\/blocks\/3\/routes\/1\", `{\"data\":\"1s\"}`, 204)\n\n\t\/\/ make a log block (4)\n\tpost(\"\/blocks\", `{\"type\":\"log\", \"parent\":1}`, 200)\n\n\t\/\/ connect the + block to the delay block (5)\n\tpost(\"\/connections\", `{\"from\":{\"id\":2, \"route\":0}, \"to\":{\"id\":3, \"route\":0}}`, 200)\n\n\t\/\/ connect the delay block to the log block (6)\n\tpost(\"\/connections\", `{\"from\":{\"id\":3, \"route\":0}, \"to\":{\"id\":4, \"route\":0}}`, 200)\n\n\t\/\/ set the value of the plus inputs\n\tput(\"\/blocks\/2\/routes\/0\", `{\"data\":1}`, 204)\n\tput(\"\/blocks\/2\/routes\/1\", `{\"data\":1}`, 204)\n\n\t\/\/ make a set block (7)\n\tpost(\"\/blocks\", `{\"type\":\"set\", \"parent\":1}`, 200)\n\n\t\/\/ disconnect the log block from the delay block\n\tdel(\"\/connections\/6\", 204)\n\n\t\/\/ connect the set block to the log block and delay block (8) (9)\n\tpost(\"\/connections\", `{\"from\":{\"id\":7, \"route\":0}, \"to\":{\"id\":4, \"route\":0}}`, 200)\n\tpost(\"\/connections\", `{\"from\":{\"id\":3, \"route\":0}, \"to\":{\"id\":7, \"route\":1}}`, 200)\n\n\t\/\/ list connections\n\tget(\"\/connections\", 200)\n\t\/\/ describe connection 8\n\tget(\"\/connections\/8\", 200)\n\n\t\/\/ set the value of the set key\n\tput(\"\/blocks\/7\/routes\/0\", `{\"data\":\"myResult\"}`, 204)\n\n\t\/\/ move log block to root group\n\tput(\"\/groups\/0\/children\/4\", \"\", 204)\n\t\/\/ move + block to root group (we will generate some errors with this later)\n\tput(\"\/groups\/0\/children\/2\", \"\", 204)\n\n\t\/\/ create a keyvalue source (10)\n\tpost(\"\/sources\", `{\"type\":\"key_value\"}`, 200)\n\n\t\/\/ get the keyvalue source\n\tget(\"\/sources\/10\", 200)\n\n\t\/\/ make a stream source (11)\n\tpost(\"\/sources\", `{\"type\":\"stream\"}`, 200)\n\n\t\/\/ change a parameter in the stream\n\tput(\"\/sources\/11\/params\", `{\"topic\":\"test\"}`, 204)\n\n\t\/\/ get all the sources\n\tget(\"\/sources\", 200)\n\n\t\/\/ make a key value get block (12)\n\tpost(\"\/blocks\", `{\"type\":\"kvGet\"}`, 200)\n\n\t\/\/ link the key value get block to the key value source (13)\n\tpost(\"\/links\", `{\"source\":{\"id\":10},\"block\":{\"id\":12}}`, 200)\n\n\t\/\/ list the links\n\tget(\"\/links\", 200)\n\n\t\/\/ this doesn't exist yet - TODO use case?\n\t\/\/ get the link\n\t\/\/ get(\"\/links\/13\", 200)\n\n\t\/\/ delete the link\n\tdel(\"\/links\/13\", 204)\n\n\t\/\/ delete the keyvalue store\n\tdel(\"\/sources\/10\", 204)\n\n\t\/\/ export the pattern\n\tget(\"\/groups\/0\/export\", 200)\n\n\t\/\/ import a pattern\n\tpattern := `{\"blocks\":[{\"label\":\"\",\"type\":\"delay\",\"id\":3,\"inputs\":[{\"name\":\"passthrough\",\"value\":null},{\"name\":\"duration\",\"value\":{\"data\":\"1s\"}}],\"outputs\":[{\"name\":\"passthrough\"}],\"position\":{\"x\":0,\"y\":0}},{\"label\":\"\",\"type\":\"set\",\"id\":7,\"inputs\":[{\"name\":\"key\",\"value\":{\"data\":\"myResult\"}},{\"name\":\"value\",\"value\":null}],\"outputs\":[{\"name\":\"object\"}],\"position\":{\"x\":0,\"y\":0}},{\"label\":\"\",\"type\":\"log\",\"id\":4,\"inputs\":[{\"name\":\"log\",\"value\":null}],\"outputs\":[],\"position\":{\"x\":0,\"y\":0}},{\"label\":\"my bestest adder\",\"type\":\"+\",\"id\":2,\"inputs\":[{\"name\":\"addend\",\"value\":{\"data\":1}},{\"name\":\"addend\",\"value\":{\"data\":1}}],\"outputs\":[{\"name\":\"sum\"}],\"position\":{\"x\":10,\"y\":10}},{\"label\":\"\",\"type\":\"kvGet\",\"id\":12,\"inputs\":[{\"name\":\"key\",\"value\":null}],\"outputs\":[{\"name\":\"value\"}],\"position\":{\"x\":0,\"y\":0}}],\"connections\":[{\"from\":{\"id\":2,\"route\":0},\"to\":{\"id\":3,\"route\":0},\"id\":5},{\"from\":{\"id\":7,\"route\":0},\"to\":{\"id\":4,\"route\":0},\"id\":8},{\"from\":{\"id\":3,\"route\":0},\"to\":{\"id\":7,\"route\":1},\"id\":9}],\"groups\":[{\"id\":0,\"label\":\"root\",\"children\":[1,4,2,11,12],\"position\":{\"x\":0,\"y\":0}},{\"id\":1,\"label\":\"The Best Group Ever\",\"children\":[3,7],\"position\":{\"x\":20,\"y\":20}}],\"sources\":[{\"label\":\"\",\"type\":\"stream\",\"id\":11,\"position\":{\"x\":0,\"y\":0},\"params\":{\"channel\":\"\",\"lookupdAddr\":\"\",\"maxInFlight\":\"10\",\"topic\":\"\"}}],\"links\":null}`\n\tpost(\"\/groups\/1\/import\", pattern, 204)\n\n\t\/\/ delete the log block\n\tdel(\"\/blocks\/4\", 204)\n\n\t\/\/ delete group 1\n\tdel(\"\/groups\/1\", 204)\n\n\t\/\/ get the blocks library\n\tget(\"\/blocks\/library\", 200)\n\n\t\/\/ get the blocks library\n\tget(\"\/sources\/library\", 200)\n\n\t\/\/ generate some errors\n\tdel(\"\/groups\/1\", 400)                                                                 \/\/ delete a group we've already deleted\n\tdel(\"\/groups\/\", 404)                                                                  \/\/ delete unspecified group\n\tdel(\"\/blocks\/246\", 400)                                                               \/\/ delete an unknown block\n\tpost(\"\/groups\/1\/import\", \"{}\", 400)                                                   \/\/ import empty\n\tpost(\"\/groups\/1\/import\", \"{bla}\", 400)                                                \/\/ import malformed\n\tget(\"\/groups\/6\/export\", 400)                                                          \/\/ export an unknown group\n\tpost(\"\/sources\", `{\"type\":\"GodHead\"}`, 400)                                           \/\/ create an unknown source\n\tget(\"\/sources\/45\", 400)                                                               \/\/ get an unknown source\n\tpost(\"\/links\", `{\"from\":100,\"block\":12}`, 400)                                        \/\/ link to an unknown source\n\tpost(\"\/links\", `{\"from\":10,\"block\":120}`, 400)                                        \/\/ link to an unknown block\n\tget(\"\/links\/450\", 404)                                                                \/\/ get an unknown link\n\tput(\"\/groups\/8\/children\/4\", \"\", 400)                                                  \/\/ modify an unknown group\n\tput(\"\/groups\/0\/children\/34\", \"\", 400)                                                 \/\/ move an unknown block to group 0\n\tput(\"\/blocks\/2\/routes\/0\", `{bobo}`, 400)                                              \/\/ set the + block's route using malformed json\n\tpost(\"\/groups\", `{\"parent\":10}`, 400)                                                 \/\/ create a group with an unknown parent\n\tpost(\"\/groups\", `{\"parent\"10}`, 400)                                                  \/\/ create a group with malformed JSON\n\tpost(\"\/blocks\", `{\"type\":\"invalid\", \"parent\":0}`, 400)                                \/\/ create a block of invalid type\n\tpost(\"\/blocks\", `{\"type\"lid\", \"parent\":1}`, 400)                                      \/\/ create a block with malformed json\n\tpost(\"\/blocks\", `{\"type\":\"latch\", \"parent\":10}`, 400)                                 \/\/ create a block witha group that doesn't exist\n\tpost(\"\/connections\", `{\"from\":{\"id\":700, \"route\":0}, \"to\":{\"id\":2, \"route\":0}}`, 400) \/\/connect unknown source\n\tpost(\"\/connections\", `{\"from\":{\"id\":2, \"route\":0}, \"to\":{\"id\":200, \"route\":0}}`, 400) \/\/connect unknown target\n\tpost(\"\/connections\", `{\"from\":{\"i:0}, \"ta200, \"route\":0}}`, 400)                      \/\/connect with malformed json\n\tpost(\"\/connections\", `{}`, 400)                                                       \/\/connect with empty json\n\tpost(\"\/connections\", \"\", 400)                                                         \/\/connect with empty string\n\tdel(\"\/connections\/289\", 400)                                                          \/\/delete unknown connection\n\tdel(\"\/connections\/\", 404)                                                             \/\/delete unspecified connection\n\tdel(\"\/connections\/invalid\", 400)                                                      \/\/delete malformed connection\n}\n<commit_msg>fixing test<commit_after>package server\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com\/fatih\/color\"\n)\n\nvar warn = color.New(color.FgYellow).Add(color.Bold).Println\n\nfunc procTestResponse(res *http.Response, t *testing.T, expectedCode int) {\n\tbody, err := ioutil.ReadAll(res.Body)\n\tres.Body.Close()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tfmt.Println(string(body) + \"\\n\")\n\tif res.StatusCode != expectedCode {\n\t\tt.Error(res.Request.Method + \": \" + res.Request.URL.Path + \" returned \" + strconv.Itoa(res.StatusCode) + \". Expected \" + strconv.Itoa(expectedCode) + \".\")\n\t\treturn\n\t}\n\tif res.StatusCode == 204 {\n\t\treturn\n\t}\n\tif res.StatusCode == 404 {\n\t\treturn\n\t}\n\tvar marsh interface{}\n\terr = json.Unmarshal(body, &marsh)\n\tif err != nil {\n\t\tt.Error(errors.New(res.Request.Method + \": failed to unmarshal response from \" + res.Request.URL.Path + \". Status code was: \" + strconv.Itoa(res.StatusCode)))\n\t}\n\t_, err = json.MarshalIndent(marsh, \"\", \"  \")\n\tif err != nil {\n\t\tt.Error(\"failed to Marshal\")\n\t}\n}\n\nfunc TestEndpoints(t *testing.T) {\n\n\ts := NewServer()\n\tr := s.NewRouter()\n\tserver := httptest.NewServer(r)\n\tdefer server.Close()\n\n\t\/\/ a few closures to save time below\n\tget := func(endpoint string, expectedCode int) {\n\t\tres, err := http.Get(server.URL + endpoint)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tprocTestResponse(res, t, expectedCode)\n\t}\n\n\tpost := func(endpoint, msg string, expectedCode int) {\n\t\tres, err := http.Post(server.URL+endpoint, \"application\/json\", bytes.NewBuffer([]byte(msg)))\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tprocTestResponse(res, t, expectedCode)\n\t}\n\n\tput := func(endpoint, msg string, expectedCode int) {\n\t\treq, err := http.NewRequest(\"PUT\", server.URL+endpoint, bytes.NewBuffer([]byte(msg)))\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tc := &http.Client{}\n\t\tres, err := c.Do(req)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tprocTestResponse(res, t, expectedCode)\n\t}\n\n\tdel := func(endpoint string, expectedCode int) {\n\t\treq, err := http.NewRequest(\"DELETE\", server.URL+endpoint, nil)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tc := &http.Client{}\n\t\tres, err := c.Do(req)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tprocTestResponse(res, t, expectedCode)\n\t}\n\n\t\/\/ set up a group (1)\n\tpost(\"\/groups\", `{\"parent\":0}`, 200)\n\n\t\/\/ set up a + block (2)\n\tpost(\"\/blocks\", `{\"type\":\"+\",\"parent\":1}`, 200)\n\n\t\/\/ label group 1\n\tput(\"\/groups\/1\/label\", `\"The Best Group Ever\"`, 204)\n\n\t\/\/ label the plus block\n\tput(\"\/blocks\/2\/label\", `\"my bestest adder\"`, 204)\n\n\t\/\/ move the plus block\n\tput(\"\/blocks\/2\/position\", `{\"x\":10,\"y\":10}`, 204)\n\n\t\/\/ get all the groups\n\tget(\"\/groups\", 200)\n\n\t\/\/ get group 1\n\tget(\"\/groups\/1\", 200)\n\n\t\/\/ move group 1\n\tput(\"\/groups\/1\/position\", `{\"x\":20,\"y\":20}`, 204)\n\n\t\/\/ get all the blocks\n\tget(\"\/blocks\", 200)\n\n\t\/\/ get the + block\n\tget(\"\/blocks\/2\", 200)\n\n\t\/\/ make a delay block (3)\n\tpost(\"\/blocks\", `{\"type\":\"delay\", \"parent\":1}`, 200)\n\n\t\/\/ set the delay's value\n\tput(\"\/blocks\/3\/routes\/1\", `{\"data\":\"1s\"}`, 204)\n\n\t\/\/ make a log block (4)\n\tpost(\"\/blocks\", `{\"type\":\"log\", \"parent\":1}`, 200)\n\n\t\/\/ connect the + block to the delay block (5)\n\tpost(\"\/connections\", `{\"from\":{\"id\":2, \"route\":0}, \"to\":{\"id\":3, \"route\":0}}`, 200)\n\n\t\/\/ connect the delay block to the log block (6)\n\tpost(\"\/connections\", `{\"from\":{\"id\":3, \"route\":0}, \"to\":{\"id\":4, \"route\":0}}`, 200)\n\n\t\/\/ set the value of the plus inputs\n\tput(\"\/blocks\/2\/routes\/0\", `{\"data\":1}`, 204)\n\tput(\"\/blocks\/2\/routes\/1\", `{\"data\":1}`, 204)\n\n\t\/\/ make a set block (7)\n\tpost(\"\/blocks\", `{\"type\":\"set\", \"parent\":1}`, 200)\n\n\t\/\/ disconnect the log block from the delay block\n\tdel(\"\/connections\/6\", 204)\n\n\t\/\/ connect the set block to the log block and delay block (8) (9)\n\tpost(\"\/connections\", `{\"from\":{\"id\":7, \"route\":0}, \"to\":{\"id\":4, \"route\":0}}`, 200)\n\tpost(\"\/connections\", `{\"from\":{\"id\":3, \"route\":0}, \"to\":{\"id\":7, \"route\":1}}`, 200)\n\n\t\/\/ list connections\n\tget(\"\/connections\", 200)\n\t\/\/ describe connection 8\n\tget(\"\/connections\/8\", 200)\n\n\t\/\/ set the value of the set key\n\tput(\"\/blocks\/7\/routes\/0\", `{\"data\":\"myResult\"}`, 204)\n\n\t\/\/ move log block to root group\n\tput(\"\/groups\/0\/children\/4\", \"\", 204)\n\t\/\/ move + block to root group (we will generate some errors with this later)\n\tput(\"\/groups\/0\/children\/2\", \"\", 204)\n\n\t\/\/ create a keyvalue source (10)\n\tpost(\"\/sources\", `{\"type\":\"key_value\"}`, 200)\n\n\t\/\/ get the keyvalue source\n\tget(\"\/sources\/10\", 200)\n\n\t\/\/ make a stream source (11)\n\tpost(\"\/sources\", `{\"type\":\"stream\"}`, 200)\n\n\t\/\/ change a parameter in the stream\n\tput(\"\/sources\/11\/params\", `{\"topic\":\"test\"}`, 204)\n\n\t\/\/ get all the sources\n\tget(\"\/sources\", 200)\n\n\t\/\/ make a key value get block (12)\n\tpost(\"\/blocks\", `{\"type\":\"kvGet\"}`, 200)\n\n\t\/\/ link the key value get block to the key value source (13)\n\tpost(\"\/links\", `{\"source\":{\"id\":10},\"block\":{\"id\":12}}`, 200)\n\n\t\/\/ list the links\n\tget(\"\/links\", 200)\n\n\t\/\/ this doesn't exist yet - TODO use case?\n\t\/\/ get the link\n\t\/\/ get(\"\/links\/13\", 200)\n\n\t\/\/ delete the link\n\tdel(\"\/links\/13\", 204)\n\n\t\/\/ delete the keyvalue store\n\tdel(\"\/sources\/10\", 204)\n\n\t\/\/ export the pattern\n\tget(\"\/groups\/0\/export\", 200)\n\n\t\/\/ import a pattern\n\tpattern := `{\"blocks\":[{\"label\":\"\",\"type\":\"delay\",\"id\":3,\"inputs\":[{\"name\":\"passthrough\",\"value\":null},{\"name\":\"duration\",\"value\":{\"data\":\"1s\"}}],\"outputs\":[{\"name\":\"passthrough\"}],\"position\":{\"x\":0,\"y\":0}},{\"label\":\"\",\"type\":\"set\",\"id\":7,\"inputs\":[{\"name\":\"key\",\"value\":{\"data\":\"myResult\"}},{\"name\":\"value\",\"value\":null}],\"outputs\":[{\"name\":\"object\"}],\"position\":{\"x\":0,\"y\":0}},{\"label\":\"\",\"type\":\"log\",\"id\":4,\"inputs\":[{\"name\":\"log\",\"value\":null}],\"outputs\":[],\"position\":{\"x\":0,\"y\":0}},{\"label\":\"my bestest adder\",\"type\":\"+\",\"id\":2,\"inputs\":[{\"name\":\"addend\",\"value\":{\"data\":1}},{\"name\":\"addend\",\"value\":{\"data\":1}}],\"outputs\":[{\"name\":\"sum\"}],\"position\":{\"x\":10,\"y\":10}},{\"label\":\"\",\"type\":\"kvGet\",\"id\":12,\"inputs\":[{\"name\":\"key\",\"value\":null}],\"outputs\":[{\"name\":\"value\"}],\"position\":{\"x\":0,\"y\":0}}],\"connections\":[{\"from\":{\"id\":2,\"route\":0},\"to\":{\"id\":3,\"route\":0},\"id\":5},{\"from\":{\"id\":7,\"route\":0},\"to\":{\"id\":4,\"route\":0},\"id\":8},{\"from\":{\"id\":3,\"route\":0},\"to\":{\"id\":7,\"route\":1},\"id\":9}],\"groups\":[{\"id\":0,\"label\":\"root\",\"children\":[1,4,2,11,12],\"position\":{\"x\":0,\"y\":0}},{\"id\":1,\"label\":\"The Best Group Ever\",\"children\":[3,7],\"position\":{\"x\":20,\"y\":20}}],\"sources\":[{\"label\":\"\",\"type\":\"stream\",\"id\":11,\"position\":{\"x\":0,\"y\":0},\"params\":{\"channel\":\"\",\"lookupdAddr\":\"\",\"maxInFlight\":\"10\",\"topic\":\"\"}}],\"links\":null}`\n\tpost(\"\/groups\/1\/import\", pattern, 200)\n\n\t\/\/ delete the log block\n\tdel(\"\/blocks\/4\", 204)\n\n\t\/\/ delete group 1\n\tdel(\"\/groups\/1\", 204)\n\n\t\/\/ get the blocks library\n\tget(\"\/blocks\/library\", 200)\n\n\t\/\/ get the blocks library\n\tget(\"\/sources\/library\", 200)\n\n\t\/\/ generate some errors\n\tdel(\"\/groups\/1\", 400)                                                                 \/\/ delete a group we've already deleted\n\tdel(\"\/groups\/\", 404)                                                                  \/\/ delete unspecified group\n\tdel(\"\/blocks\/246\", 400)                                                               \/\/ delete an unknown block\n\tpost(\"\/groups\/1\/import\", \"{}\", 400)                                                   \/\/ import empty\n\tpost(\"\/groups\/1\/import\", \"{bla}\", 400)                                                \/\/ import malformed\n\tget(\"\/groups\/6\/export\", 400)                                                          \/\/ export an unknown group\n\tpost(\"\/sources\", `{\"type\":\"GodHead\"}`, 400)                                           \/\/ create an unknown source\n\tget(\"\/sources\/45\", 400)                                                               \/\/ get an unknown source\n\tpost(\"\/links\", `{\"from\":100,\"block\":12}`, 400)                                        \/\/ link to an unknown source\n\tpost(\"\/links\", `{\"from\":10,\"block\":120}`, 400)                                        \/\/ link to an unknown block\n\tget(\"\/links\/450\", 404)                                                                \/\/ get an unknown link\n\tput(\"\/groups\/8\/children\/4\", \"\", 400)                                                  \/\/ modify an unknown group\n\tput(\"\/groups\/0\/children\/34\", \"\", 400)                                                 \/\/ move an unknown block to group 0\n\tput(\"\/blocks\/2\/routes\/0\", `{bobo}`, 400)                                              \/\/ set the + block's route using malformed json\n\tpost(\"\/groups\", `{\"parent\":10}`, 400)                                                 \/\/ create a group with an unknown parent\n\tpost(\"\/groups\", `{\"parent\"10}`, 400)                                                  \/\/ create a group with malformed JSON\n\tpost(\"\/blocks\", `{\"type\":\"invalid\", \"parent\":0}`, 400)                                \/\/ create a block of invalid type\n\tpost(\"\/blocks\", `{\"type\"lid\", \"parent\":1}`, 400)                                      \/\/ create a block with malformed json\n\tpost(\"\/blocks\", `{\"type\":\"latch\", \"parent\":10}`, 400)                                 \/\/ create a block witha group that doesn't exist\n\tpost(\"\/connections\", `{\"from\":{\"id\":700, \"route\":0}, \"to\":{\"id\":2, \"route\":0}}`, 400) \/\/connect unknown source\n\tpost(\"\/connections\", `{\"from\":{\"id\":2, \"route\":0}, \"to\":{\"id\":200, \"route\":0}}`, 400) \/\/connect unknown target\n\tpost(\"\/connections\", `{\"from\":{\"i:0}, \"ta200, \"route\":0}}`, 400)                      \/\/connect with malformed json\n\tpost(\"\/connections\", `{}`, 400)                                                       \/\/connect with empty json\n\tpost(\"\/connections\", \"\", 400)                                                         \/\/connect with empty string\n\tdel(\"\/connections\/289\", 400)                                                          \/\/delete unknown connection\n\tdel(\"\/connections\/\", 404)                                                             \/\/delete unspecified connection\n\tdel(\"\/connections\/invalid\", 400)                                                      \/\/delete malformed connection\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage subnets_test\n\nimport (\n\tstdtesting \"testing\"\n\n\t\"github.com\/juju\/juju\/testing\"\n)\n\n\/\/ TestAll is the main test function for this package\nfunc TestAll(t *stdtesting.T) {\n\ttesting.MgoTestPackage(t)\n}\n<commit_msg>Not using Mongo, so shouldn't use MgoTestPackage.<commit_after>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage subnets_test\n\nimport (\n\t\"testing\"\n\n\tgc \"gopkg.in\/check.v1\"\n)\n\n\/\/ TestAll is the main test function for this package\nfunc TestAll(t *testing.T) {\n\tgc.TestingT(t)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage ssa\n\nimport (\n\t\"cmd\/internal\/src\"\n)\n\n\/\/ findlive returns the reachable blocks and live values in f.\n\/\/ The caller should call f.retDeadcodeLive(live) when it is done with it.\nfunc findlive(f *Func) (reachable []bool, live []bool) {\n\treachable = ReachableBlocks(f)\n\tvar order []*Value\n\tlive, order = liveValues(f, reachable)\n\tf.retDeadcodeLiveOrderStmts(order)\n\treturn\n}\n\n\/\/ ReachableBlocks returns the reachable blocks in f.\nfunc ReachableBlocks(f *Func) []bool {\n\treachable := make([]bool, f.NumBlocks())\n\treachable[f.Entry.ID] = true\n\tp := make([]*Block, 0, 64) \/\/ stack-like worklist\n\tp = append(p, f.Entry)\n\tfor len(p) > 0 {\n\t\t\/\/ Pop a reachable block\n\t\tb := p[len(p)-1]\n\t\tp = p[:len(p)-1]\n\t\t\/\/ Mark successors as reachable\n\t\ts := b.Succs\n\t\tif b.Kind == BlockFirst {\n\t\t\ts = s[:1]\n\t\t}\n\t\tfor _, e := range s {\n\t\t\tc := e.b\n\t\t\tif int(c.ID) >= len(reachable) {\n\t\t\t\tf.Fatalf(\"block %s >= f.NumBlocks()=%d?\", c, len(reachable))\n\t\t\t}\n\t\t\tif !reachable[c.ID] {\n\t\t\t\treachable[c.ID] = true\n\t\t\t\tp = append(p, c) \/\/ push\n\t\t\t}\n\t\t}\n\t}\n\treturn reachable\n}\n\n\/\/ liveValues returns the live values in f and a list of values that are eligible\n\/\/ to be statements in reversed data flow order.\n\/\/ The second result is used to help conserve statement boundaries for debugging.\n\/\/ reachable is a map from block ID to whether the block is reachable.\n\/\/ The caller should call f.retDeadcodeLive(live) and f.retDeadcodeLiveOrderStmts(liveOrderStmts)\n\/\/ when they are done with the return values.\nfunc liveValues(f *Func, reachable []bool) (live []bool, liveOrderStmts []*Value) {\n\tlive = f.newDeadcodeLive()\n\tif cap(live) < f.NumValues() {\n\t\tlive = make([]bool, f.NumValues())\n\t} else {\n\t\tlive = live[:f.NumValues()]\n\t\tfor i := range live {\n\t\t\tlive[i] = false\n\t\t}\n\t}\n\n\tliveOrderStmts = f.newDeadcodeLiveOrderStmts()\n\tliveOrderStmts = liveOrderStmts[:0]\n\n\t\/\/ After regalloc, consider all values to be live.\n\t\/\/ See the comment at the top of regalloc.go and in deadcode for details.\n\tif f.RegAlloc != nil {\n\t\tfor i := range live {\n\t\t\tlive[i] = true\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ Record all the inline indexes we need\n\tvar liveInlIdx map[int]bool\n\tpt := f.Config.ctxt.PosTable\n\tfor _, b := range f.Blocks {\n\t\tfor _, v := range b.Values {\n\t\t\ti := pt.Pos(v.Pos).Base().InliningIndex()\n\t\t\tif i < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif liveInlIdx == nil {\n\t\t\t\tliveInlIdx = map[int]bool{}\n\t\t\t}\n\t\t\tliveInlIdx[i] = true\n\t\t}\n\t\ti := pt.Pos(b.Pos).Base().InliningIndex()\n\t\tif i < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif liveInlIdx == nil {\n\t\t\tliveInlIdx = map[int]bool{}\n\t\t}\n\t\tliveInlIdx[i] = true\n\t}\n\n\t\/\/ Find all live values\n\tq := f.Cache.deadcode.q[:0]\n\tdefer func() { f.Cache.deadcode.q = q }()\n\n\t\/\/ Starting set: all control values of reachable blocks are live.\n\t\/\/ Calls are live (because callee can observe the memory state).\n\tfor _, b := range f.Blocks {\n\t\tif !reachable[b.ID] {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, v := range b.ControlValues() {\n\t\t\tif !live[v.ID] {\n\t\t\t\tlive[v.ID] = true\n\t\t\t\tq = append(q, v)\n\t\t\t\tif v.Pos.IsStmt() != src.PosNotStmt {\n\t\t\t\t\tliveOrderStmts = append(liveOrderStmts, v)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor _, v := range b.Values {\n\t\t\tif (opcodeTable[v.Op].call || opcodeTable[v.Op].hasSideEffects) && !live[v.ID] {\n\t\t\t\tlive[v.ID] = true\n\t\t\t\tq = append(q, v)\n\t\t\t\tif v.Pos.IsStmt() != src.PosNotStmt {\n\t\t\t\t\tliveOrderStmts = append(liveOrderStmts, v)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif v.Type.IsVoid() && !live[v.ID] {\n\t\t\t\t\/\/ The only Void ops are nil checks and inline marks.  We must keep these.\n\t\t\t\tif v.Op == OpInlMark && !liveInlIdx[int(v.AuxInt)] {\n\t\t\t\t\t\/\/ We don't need marks for bodies that\n\t\t\t\t\t\/\/ have been completely optimized away.\n\t\t\t\t\t\/\/ TODO: save marks only for bodies which\n\t\t\t\t\t\/\/ have a faulting instruction or a call?\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlive[v.ID] = true\n\t\t\t\tq = append(q, v)\n\t\t\t\tif v.Pos.IsStmt() != src.PosNotStmt {\n\t\t\t\t\tliveOrderStmts = append(liveOrderStmts, v)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Compute transitive closure of live values.\n\tfor len(q) > 0 {\n\t\t\/\/ pop a reachable value\n\t\tv := q[len(q)-1]\n\t\tq = q[:len(q)-1]\n\t\tfor i, x := range v.Args {\n\t\t\tif v.Op == OpPhi && !reachable[v.Block.Preds[i].b.ID] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !live[x.ID] {\n\t\t\t\tlive[x.ID] = true\n\t\t\t\tq = append(q, x) \/\/ push\n\t\t\t\tif x.Pos.IsStmt() != src.PosNotStmt {\n\t\t\t\t\tliveOrderStmts = append(liveOrderStmts, x)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ deadcode removes dead code from f.\nfunc deadcode(f *Func) {\n\t\/\/ deadcode after regalloc is forbidden for now. Regalloc\n\t\/\/ doesn't quite generate legal SSA which will lead to some\n\t\/\/ required moves being eliminated. See the comment at the\n\t\/\/ top of regalloc.go for details.\n\tif f.RegAlloc != nil {\n\t\tf.Fatalf(\"deadcode after regalloc\")\n\t}\n\n\t\/\/ Find reachable blocks.\n\treachable := ReachableBlocks(f)\n\n\t\/\/ Get rid of edges from dead to live code.\n\tfor _, b := range f.Blocks {\n\t\tif reachable[b.ID] {\n\t\t\tcontinue\n\t\t}\n\t\tfor i := 0; i < len(b.Succs); {\n\t\t\te := b.Succs[i]\n\t\t\tif reachable[e.b.ID] {\n\t\t\t\tb.removeEdge(i)\n\t\t\t} else {\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Get rid of dead edges from live code.\n\tfor _, b := range f.Blocks {\n\t\tif !reachable[b.ID] {\n\t\t\tcontinue\n\t\t}\n\t\tif b.Kind != BlockFirst {\n\t\t\tcontinue\n\t\t}\n\t\tb.removeEdge(1)\n\t\tb.Kind = BlockPlain\n\t\tb.Likely = BranchUnknown\n\t}\n\n\t\/\/ Splice out any copies introduced during dead block removal.\n\tcopyelim(f)\n\n\t\/\/ Find live values.\n\tlive, order := liveValues(f, reachable)\n\tdefer f.retDeadcodeLive(live)\n\tdefer f.retDeadcodeLiveOrderStmts(order)\n\n\t\/\/ Remove dead & duplicate entries from namedValues map.\n\ts := f.newSparseSet(f.NumValues())\n\tdefer f.retSparseSet(s)\n\ti := 0\n\tfor _, name := range f.Names {\n\t\tj := 0\n\t\ts.clear()\n\t\tvalues := f.NamedValues[name]\n\t\tfor _, v := range values {\n\t\t\tif live[v.ID] && !s.contains(v.ID) {\n\t\t\t\tvalues[j] = v\n\t\t\t\tj++\n\t\t\t\ts.add(v.ID)\n\t\t\t}\n\t\t}\n\t\tif j == 0 {\n\t\t\tdelete(f.NamedValues, name)\n\t\t} else {\n\t\t\tf.Names[i] = name\n\t\t\ti++\n\t\t\tfor k := len(values) - 1; k >= j; k-- {\n\t\t\t\tvalues[k] = nil\n\t\t\t}\n\t\t\tf.NamedValues[name] = values[:j]\n\t\t}\n\t}\n\tfor k := len(f.Names) - 1; k >= i; k-- {\n\t\tf.Names[k] = LocalSlot{}\n\t}\n\tf.Names = f.Names[:i]\n\n\tpendingLines := f.cachedLineStarts \/\/ Holds statement boundaries that need to be moved to a new value\/block\n\tpendingLines.clear()\n\n\t\/\/ Unlink values and conserve statement boundaries\n\tfor i, b := range f.Blocks {\n\t\tif !reachable[b.ID] {\n\t\t\t\/\/ TODO what if control is statement boundary? Too late here.\n\t\t\tb.ResetControls()\n\t\t}\n\t\tfor _, v := range b.Values {\n\t\t\tif !live[v.ID] {\n\t\t\t\tv.resetArgs()\n\t\t\t\tif v.Pos.IsStmt() == src.PosIsStmt && reachable[b.ID] {\n\t\t\t\t\tpendingLines.set(v.Pos, int32(i)) \/\/ TODO could be more than one pos for a line\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Find new homes for lost lines -- require earliest in data flow with same line that is also in same block\n\tfor i := len(order) - 1; i >= 0; i-- {\n\t\tw := order[i]\n\t\tif j := pendingLines.get(w.Pos); j > -1 && f.Blocks[j] == w.Block {\n\t\t\tw.Pos = w.Pos.WithIsStmt()\n\t\t\tpendingLines.remove(w.Pos)\n\t\t}\n\t}\n\n\t\/\/ Any boundary that failed to match a live value can move to a block end\n\tpendingLines.foreachEntry(func(j int32, l uint, bi int32) {\n\t\tb := f.Blocks[bi]\n\t\tif b.Pos.Line() == l && b.Pos.FileIndex() == j {\n\t\t\tb.Pos = b.Pos.WithIsStmt()\n\t\t}\n\t})\n\n\t\/\/ Remove dead values from blocks' value list. Return dead\n\t\/\/ values to the allocator.\n\tfor _, b := range f.Blocks {\n\t\ti := 0\n\t\tfor _, v := range b.Values {\n\t\t\tif live[v.ID] {\n\t\t\t\tb.Values[i] = v\n\t\t\t\ti++\n\t\t\t} else {\n\t\t\t\tf.freeValue(v)\n\t\t\t}\n\t\t}\n\t\t\/\/ aid GC\n\t\ttail := b.Values[i:]\n\t\tfor j := range tail {\n\t\t\ttail[j] = nil\n\t\t}\n\t\tb.Values = b.Values[:i]\n\t}\n\n\t\/\/ Remove dead blocks from WBLoads list.\n\ti = 0\n\tfor _, b := range f.WBLoads {\n\t\tif reachable[b.ID] {\n\t\t\tf.WBLoads[i] = b\n\t\t\ti++\n\t\t}\n\t}\n\tfor j := i; j < len(f.WBLoads); j++ {\n\t\tf.WBLoads[j] = nil\n\t}\n\tf.WBLoads = f.WBLoads[:i]\n\n\t\/\/ Remove unreachable blocks. Return dead blocks to allocator.\n\ti = 0\n\tfor _, b := range f.Blocks {\n\t\tif reachable[b.ID] {\n\t\t\tf.Blocks[i] = b\n\t\t\ti++\n\t\t} else {\n\t\t\tif len(b.Values) > 0 {\n\t\t\t\tb.Fatalf(\"live values in unreachable block %v: %v\", b, b.Values)\n\t\t\t}\n\t\t\tf.freeBlock(b)\n\t\t}\n\t}\n\t\/\/ zero remainder to help GC\n\ttail := f.Blocks[i:]\n\tfor j := range tail {\n\t\ttail[j] = nil\n\t}\n\tf.Blocks = f.Blocks[:i]\n}\n\n\/\/ removeEdge removes the i'th outgoing edge from b (and\n\/\/ the corresponding incoming edge from b.Succs[i].b).\nfunc (b *Block) removeEdge(i int) {\n\te := b.Succs[i]\n\tc := e.b\n\tj := e.i\n\n\t\/\/ Adjust b.Succs\n\tb.removeSucc(i)\n\n\t\/\/ Adjust c.Preds\n\tc.removePred(j)\n\n\t\/\/ Remove phi args from c's phis.\n\tn := len(c.Preds)\n\tfor _, v := range c.Values {\n\t\tif v.Op != OpPhi {\n\t\t\tcontinue\n\t\t}\n\t\tv.Args[j].Uses--\n\t\tv.Args[j] = v.Args[n]\n\t\tv.Args[n] = nil\n\t\tv.Args = v.Args[:n]\n\t\tphielimValue(v)\n\t\t\/\/ Note: this is trickier than it looks. Replacing\n\t\t\/\/ a Phi with a Copy can in general cause problems because\n\t\t\/\/ Phi and Copy don't have exactly the same semantics.\n\t\t\/\/ Phi arguments always come from a predecessor block,\n\t\t\/\/ whereas copies don't. This matters in loops like:\n\t\t\/\/ 1: x = (Phi y)\n\t\t\/\/    y = (Add x 1)\n\t\t\/\/    goto 1\n\t\t\/\/ If we replace Phi->Copy, we get\n\t\t\/\/ 1: x = (Copy y)\n\t\t\/\/    y = (Add x 1)\n\t\t\/\/    goto 1\n\t\t\/\/ (Phi y) refers to the *previous* value of y, whereas\n\t\t\/\/ (Copy y) refers to the *current* value of y.\n\t\t\/\/ The modified code has a cycle and the scheduler\n\t\t\/\/ will barf on it.\n\t\t\/\/\n\t\t\/\/ Fortunately, this situation can only happen for dead\n\t\t\/\/ code loops. We know the code we're working with is\n\t\t\/\/ not dead, so we're ok.\n\t\t\/\/ Proof: If we have a potential bad cycle, we have a\n\t\t\/\/ situation like this:\n\t\t\/\/   x = (Phi z)\n\t\t\/\/   y = (op1 x ...)\n\t\t\/\/   z = (op2 y ...)\n\t\t\/\/ Where opX are not Phi ops. But such a situation\n\t\t\/\/ implies a cycle in the dominator graph. In the\n\t\t\/\/ example, x.Block dominates y.Block, y.Block dominates\n\t\t\/\/ z.Block, and z.Block dominates x.Block (treating\n\t\t\/\/ \"dominates\" as reflexive).  Cycles in the dominator\n\t\t\/\/ graph can only happen in an unreachable cycle.\n\t}\n}\n<commit_msg>cmd\/compile: use optimized slice zeroing in deadcode<commit_after>\/\/ Copyright 2015 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage ssa\n\nimport (\n\t\"cmd\/internal\/src\"\n)\n\n\/\/ findlive returns the reachable blocks and live values in f.\n\/\/ The caller should call f.retDeadcodeLive(live) when it is done with it.\nfunc findlive(f *Func) (reachable []bool, live []bool) {\n\treachable = ReachableBlocks(f)\n\tvar order []*Value\n\tlive, order = liveValues(f, reachable)\n\tf.retDeadcodeLiveOrderStmts(order)\n\treturn\n}\n\n\/\/ ReachableBlocks returns the reachable blocks in f.\nfunc ReachableBlocks(f *Func) []bool {\n\treachable := make([]bool, f.NumBlocks())\n\treachable[f.Entry.ID] = true\n\tp := make([]*Block, 0, 64) \/\/ stack-like worklist\n\tp = append(p, f.Entry)\n\tfor len(p) > 0 {\n\t\t\/\/ Pop a reachable block\n\t\tb := p[len(p)-1]\n\t\tp = p[:len(p)-1]\n\t\t\/\/ Mark successors as reachable\n\t\ts := b.Succs\n\t\tif b.Kind == BlockFirst {\n\t\t\ts = s[:1]\n\t\t}\n\t\tfor _, e := range s {\n\t\t\tc := e.b\n\t\t\tif int(c.ID) >= len(reachable) {\n\t\t\t\tf.Fatalf(\"block %s >= f.NumBlocks()=%d?\", c, len(reachable))\n\t\t\t}\n\t\t\tif !reachable[c.ID] {\n\t\t\t\treachable[c.ID] = true\n\t\t\t\tp = append(p, c) \/\/ push\n\t\t\t}\n\t\t}\n\t}\n\treturn reachable\n}\n\n\/\/ liveValues returns the live values in f and a list of values that are eligible\n\/\/ to be statements in reversed data flow order.\n\/\/ The second result is used to help conserve statement boundaries for debugging.\n\/\/ reachable is a map from block ID to whether the block is reachable.\n\/\/ The caller should call f.retDeadcodeLive(live) and f.retDeadcodeLiveOrderStmts(liveOrderStmts)\n\/\/ when they are done with the return values.\nfunc liveValues(f *Func, reachable []bool) (live []bool, liveOrderStmts []*Value) {\n\tlive = f.newDeadcodeLive()\n\tif cap(live) < f.NumValues() {\n\t\tlive = make([]bool, f.NumValues())\n\t} else {\n\t\tlive = live[:f.NumValues()]\n\t\tfor i := range live {\n\t\t\tlive[i] = false\n\t\t}\n\t}\n\n\tliveOrderStmts = f.newDeadcodeLiveOrderStmts()\n\tliveOrderStmts = liveOrderStmts[:0]\n\n\t\/\/ After regalloc, consider all values to be live.\n\t\/\/ See the comment at the top of regalloc.go and in deadcode for details.\n\tif f.RegAlloc != nil {\n\t\tfor i := range live {\n\t\t\tlive[i] = true\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ Record all the inline indexes we need\n\tvar liveInlIdx map[int]bool\n\tpt := f.Config.ctxt.PosTable\n\tfor _, b := range f.Blocks {\n\t\tfor _, v := range b.Values {\n\t\t\ti := pt.Pos(v.Pos).Base().InliningIndex()\n\t\t\tif i < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif liveInlIdx == nil {\n\t\t\t\tliveInlIdx = map[int]bool{}\n\t\t\t}\n\t\t\tliveInlIdx[i] = true\n\t\t}\n\t\ti := pt.Pos(b.Pos).Base().InliningIndex()\n\t\tif i < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif liveInlIdx == nil {\n\t\t\tliveInlIdx = map[int]bool{}\n\t\t}\n\t\tliveInlIdx[i] = true\n\t}\n\n\t\/\/ Find all live values\n\tq := f.Cache.deadcode.q[:0]\n\tdefer func() { f.Cache.deadcode.q = q }()\n\n\t\/\/ Starting set: all control values of reachable blocks are live.\n\t\/\/ Calls are live (because callee can observe the memory state).\n\tfor _, b := range f.Blocks {\n\t\tif !reachable[b.ID] {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, v := range b.ControlValues() {\n\t\t\tif !live[v.ID] {\n\t\t\t\tlive[v.ID] = true\n\t\t\t\tq = append(q, v)\n\t\t\t\tif v.Pos.IsStmt() != src.PosNotStmt {\n\t\t\t\t\tliveOrderStmts = append(liveOrderStmts, v)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor _, v := range b.Values {\n\t\t\tif (opcodeTable[v.Op].call || opcodeTable[v.Op].hasSideEffects) && !live[v.ID] {\n\t\t\t\tlive[v.ID] = true\n\t\t\t\tq = append(q, v)\n\t\t\t\tif v.Pos.IsStmt() != src.PosNotStmt {\n\t\t\t\t\tliveOrderStmts = append(liveOrderStmts, v)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif v.Type.IsVoid() && !live[v.ID] {\n\t\t\t\t\/\/ The only Void ops are nil checks and inline marks.  We must keep these.\n\t\t\t\tif v.Op == OpInlMark && !liveInlIdx[int(v.AuxInt)] {\n\t\t\t\t\t\/\/ We don't need marks for bodies that\n\t\t\t\t\t\/\/ have been completely optimized away.\n\t\t\t\t\t\/\/ TODO: save marks only for bodies which\n\t\t\t\t\t\/\/ have a faulting instruction or a call?\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlive[v.ID] = true\n\t\t\t\tq = append(q, v)\n\t\t\t\tif v.Pos.IsStmt() != src.PosNotStmt {\n\t\t\t\t\tliveOrderStmts = append(liveOrderStmts, v)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Compute transitive closure of live values.\n\tfor len(q) > 0 {\n\t\t\/\/ pop a reachable value\n\t\tv := q[len(q)-1]\n\t\tq = q[:len(q)-1]\n\t\tfor i, x := range v.Args {\n\t\t\tif v.Op == OpPhi && !reachable[v.Block.Preds[i].b.ID] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !live[x.ID] {\n\t\t\t\tlive[x.ID] = true\n\t\t\t\tq = append(q, x) \/\/ push\n\t\t\t\tif x.Pos.IsStmt() != src.PosNotStmt {\n\t\t\t\t\tliveOrderStmts = append(liveOrderStmts, x)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ deadcode removes dead code from f.\nfunc deadcode(f *Func) {\n\t\/\/ deadcode after regalloc is forbidden for now. Regalloc\n\t\/\/ doesn't quite generate legal SSA which will lead to some\n\t\/\/ required moves being eliminated. See the comment at the\n\t\/\/ top of regalloc.go for details.\n\tif f.RegAlloc != nil {\n\t\tf.Fatalf(\"deadcode after regalloc\")\n\t}\n\n\t\/\/ Find reachable blocks.\n\treachable := ReachableBlocks(f)\n\n\t\/\/ Get rid of edges from dead to live code.\n\tfor _, b := range f.Blocks {\n\t\tif reachable[b.ID] {\n\t\t\tcontinue\n\t\t}\n\t\tfor i := 0; i < len(b.Succs); {\n\t\t\te := b.Succs[i]\n\t\t\tif reachable[e.b.ID] {\n\t\t\t\tb.removeEdge(i)\n\t\t\t} else {\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Get rid of dead edges from live code.\n\tfor _, b := range f.Blocks {\n\t\tif !reachable[b.ID] {\n\t\t\tcontinue\n\t\t}\n\t\tif b.Kind != BlockFirst {\n\t\t\tcontinue\n\t\t}\n\t\tb.removeEdge(1)\n\t\tb.Kind = BlockPlain\n\t\tb.Likely = BranchUnknown\n\t}\n\n\t\/\/ Splice out any copies introduced during dead block removal.\n\tcopyelim(f)\n\n\t\/\/ Find live values.\n\tlive, order := liveValues(f, reachable)\n\tdefer f.retDeadcodeLive(live)\n\tdefer f.retDeadcodeLiveOrderStmts(order)\n\n\t\/\/ Remove dead & duplicate entries from namedValues map.\n\ts := f.newSparseSet(f.NumValues())\n\tdefer f.retSparseSet(s)\n\ti := 0\n\tfor _, name := range f.Names {\n\t\tj := 0\n\t\ts.clear()\n\t\tvalues := f.NamedValues[name]\n\t\tfor _, v := range values {\n\t\t\tif live[v.ID] && !s.contains(v.ID) {\n\t\t\t\tvalues[j] = v\n\t\t\t\tj++\n\t\t\t\ts.add(v.ID)\n\t\t\t}\n\t\t}\n\t\tif j == 0 {\n\t\t\tdelete(f.NamedValues, name)\n\t\t} else {\n\t\t\tf.Names[i] = name\n\t\t\ti++\n\t\t\tfor k := len(values) - 1; k >= j; k-- {\n\t\t\t\tvalues[k] = nil\n\t\t\t}\n\t\t\tf.NamedValues[name] = values[:j]\n\t\t}\n\t}\n\tclearNames := f.Names[i:]\n\tfor j := range clearNames {\n\t\tclearNames[j] = LocalSlot{}\n\t}\n\tf.Names = f.Names[:i]\n\n\tpendingLines := f.cachedLineStarts \/\/ Holds statement boundaries that need to be moved to a new value\/block\n\tpendingLines.clear()\n\n\t\/\/ Unlink values and conserve statement boundaries\n\tfor i, b := range f.Blocks {\n\t\tif !reachable[b.ID] {\n\t\t\t\/\/ TODO what if control is statement boundary? Too late here.\n\t\t\tb.ResetControls()\n\t\t}\n\t\tfor _, v := range b.Values {\n\t\t\tif !live[v.ID] {\n\t\t\t\tv.resetArgs()\n\t\t\t\tif v.Pos.IsStmt() == src.PosIsStmt && reachable[b.ID] {\n\t\t\t\t\tpendingLines.set(v.Pos, int32(i)) \/\/ TODO could be more than one pos for a line\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Find new homes for lost lines -- require earliest in data flow with same line that is also in same block\n\tfor i := len(order) - 1; i >= 0; i-- {\n\t\tw := order[i]\n\t\tif j := pendingLines.get(w.Pos); j > -1 && f.Blocks[j] == w.Block {\n\t\t\tw.Pos = w.Pos.WithIsStmt()\n\t\t\tpendingLines.remove(w.Pos)\n\t\t}\n\t}\n\n\t\/\/ Any boundary that failed to match a live value can move to a block end\n\tpendingLines.foreachEntry(func(j int32, l uint, bi int32) {\n\t\tb := f.Blocks[bi]\n\t\tif b.Pos.Line() == l && b.Pos.FileIndex() == j {\n\t\t\tb.Pos = b.Pos.WithIsStmt()\n\t\t}\n\t})\n\n\t\/\/ Remove dead values from blocks' value list. Return dead\n\t\/\/ values to the allocator.\n\tfor _, b := range f.Blocks {\n\t\ti := 0\n\t\tfor _, v := range b.Values {\n\t\t\tif live[v.ID] {\n\t\t\t\tb.Values[i] = v\n\t\t\t\ti++\n\t\t\t} else {\n\t\t\t\tf.freeValue(v)\n\t\t\t}\n\t\t}\n\t\t\/\/ aid GC\n\t\ttail := b.Values[i:]\n\t\tfor j := range tail {\n\t\t\ttail[j] = nil\n\t\t}\n\t\tb.Values = b.Values[:i]\n\t}\n\n\t\/\/ Remove dead blocks from WBLoads list.\n\ti = 0\n\tfor _, b := range f.WBLoads {\n\t\tif reachable[b.ID] {\n\t\t\tf.WBLoads[i] = b\n\t\t\ti++\n\t\t}\n\t}\n\tclearWBLoads := f.WBLoads[i:]\n\tfor j := range clearWBLoads {\n\t\tclearWBLoads[j] = nil\n\t}\n\tf.WBLoads = f.WBLoads[:i]\n\n\t\/\/ Remove unreachable blocks. Return dead blocks to allocator.\n\ti = 0\n\tfor _, b := range f.Blocks {\n\t\tif reachable[b.ID] {\n\t\t\tf.Blocks[i] = b\n\t\t\ti++\n\t\t} else {\n\t\t\tif len(b.Values) > 0 {\n\t\t\t\tb.Fatalf(\"live values in unreachable block %v: %v\", b, b.Values)\n\t\t\t}\n\t\t\tf.freeBlock(b)\n\t\t}\n\t}\n\t\/\/ zero remainder to help GC\n\ttail := f.Blocks[i:]\n\tfor j := range tail {\n\t\ttail[j] = nil\n\t}\n\tf.Blocks = f.Blocks[:i]\n}\n\n\/\/ removeEdge removes the i'th outgoing edge from b (and\n\/\/ the corresponding incoming edge from b.Succs[i].b).\nfunc (b *Block) removeEdge(i int) {\n\te := b.Succs[i]\n\tc := e.b\n\tj := e.i\n\n\t\/\/ Adjust b.Succs\n\tb.removeSucc(i)\n\n\t\/\/ Adjust c.Preds\n\tc.removePred(j)\n\n\t\/\/ Remove phi args from c's phis.\n\tn := len(c.Preds)\n\tfor _, v := range c.Values {\n\t\tif v.Op != OpPhi {\n\t\t\tcontinue\n\t\t}\n\t\tv.Args[j].Uses--\n\t\tv.Args[j] = v.Args[n]\n\t\tv.Args[n] = nil\n\t\tv.Args = v.Args[:n]\n\t\tphielimValue(v)\n\t\t\/\/ Note: this is trickier than it looks. Replacing\n\t\t\/\/ a Phi with a Copy can in general cause problems because\n\t\t\/\/ Phi and Copy don't have exactly the same semantics.\n\t\t\/\/ Phi arguments always come from a predecessor block,\n\t\t\/\/ whereas copies don't. This matters in loops like:\n\t\t\/\/ 1: x = (Phi y)\n\t\t\/\/    y = (Add x 1)\n\t\t\/\/    goto 1\n\t\t\/\/ If we replace Phi->Copy, we get\n\t\t\/\/ 1: x = (Copy y)\n\t\t\/\/    y = (Add x 1)\n\t\t\/\/    goto 1\n\t\t\/\/ (Phi y) refers to the *previous* value of y, whereas\n\t\t\/\/ (Copy y) refers to the *current* value of y.\n\t\t\/\/ The modified code has a cycle and the scheduler\n\t\t\/\/ will barf on it.\n\t\t\/\/\n\t\t\/\/ Fortunately, this situation can only happen for dead\n\t\t\/\/ code loops. We know the code we're working with is\n\t\t\/\/ not dead, so we're ok.\n\t\t\/\/ Proof: If we have a potential bad cycle, we have a\n\t\t\/\/ situation like this:\n\t\t\/\/   x = (Phi z)\n\t\t\/\/   y = (op1 x ...)\n\t\t\/\/   z = (op2 y ...)\n\t\t\/\/ Where opX are not Phi ops. But such a situation\n\t\t\/\/ implies a cycle in the dominator graph. In the\n\t\t\/\/ example, x.Block dominates y.Block, y.Block dominates\n\t\t\/\/ z.Block, and z.Block dominates x.Block (treating\n\t\t\/\/ \"dominates\" as reflexive).  Cycles in the dominator\n\t\t\/\/ graph can only happen in an unreachable cycle.\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package monitor\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/shirou\/gopsutil\/v3\/cpu\"\n\t\"github.com\/shirou\/gopsutil\/v3\/disk\"\n\t\"github.com\/shirou\/gopsutil\/v3\/host\"\n\t\"github.com\/shirou\/gopsutil\/v3\/load\"\n\t\"github.com\/shirou\/gopsutil\/v3\/mem\"\n\t\"github.com\/shirou\/gopsutil\/v3\/net\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/api\/dbx_auth\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/api\/dbx_conn\"\n\tmo_path2 \"github.com\/watermint\/toolbox\/domain\/dropbox\/model\/mo_path\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/model\/mo_time\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/service\/sv_file_content\"\n\t\"github.com\/watermint\/toolbox\/essentials\/file\/es_filepath\"\n\t\"github.com\/watermint\/toolbox\/essentials\/file\/es_gzip\"\n\t\"github.com\/watermint\/toolbox\/essentials\/log\/esl\"\n\t\"github.com\/watermint\/toolbox\/essentials\/model\/mo_int\"\n\t\"github.com\/watermint\/toolbox\/essentials\/model\/mo_path\"\n\t\"github.com\/watermint\/toolbox\/infra\/app\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_control\"\n\t\"github.com\/watermint\/toolbox\/infra\/recipe\/rc_exec\"\n\t\"github.com\/watermint\/toolbox\/infra\/recipe\/rc_recipe\"\n\t\"github.com\/watermint\/toolbox\/quality\/infra\/qt_file\"\n\t\"github.com\/watermint\/toolbox\/quality\/recipe\/qtr_endtoend\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tmonitorFilePrefix = \"tbx-monitor-\"\n)\n\ntype Client struct {\n\tDataPath        mo_path.FileSystemPath\n\tSyncPath        mo_path2.DropboxPath\n\tPeer            dbx_conn.ConnScopedIndividual\n\tName            string\n\tMonitorInterval mo_int.RangeInt\n\tSyncInterval    mo_int.RangeInt\n\tMonitorEnd      mo_time.TimeOptional\n\tDisplay         bool\n\n\tsentErrors       map[string]bool\n\tcurrentJournal   *os.File\n\tcurrentPath      string\n\tcurrentStart     time.Time\n\tcurrentDeadline  time.Time\n\trotateInProgress bool\n}\n\nfunc (z *Client) Preset() {\n\tz.MonitorInterval.SetRange(1, 86400, 10)\n\tz.SyncInterval.SetRange(10, 86400, 3600)\n\tz.sentErrors = make(map[string]bool)\n\tz.Peer.SetScopes(\n\t\tdbx_auth.ScopeFilesContentWrite,\n\t)\n}\nfunc (z *Client) sendError(c app_control.Control, eventType string, err error) {\n\tif _, ok := z.sentErrors[eventType]; ok {\n\t\treturn\n\t}\n\tl := c.Log()\n\tl.Warn(\"Unable to retrieve event data\", esl.String(\"type\", eventType), esl.Error(err))\n\tz.sentErrors[eventType] = true\n}\n\nfunc (z *Client) openJournal(c app_control.Control) error {\n\tl := c.Log()\n\tif z.currentJournal != nil {\n\t\treturn nil\n\t}\n\tname := monitorFilePrefix + es_filepath.Escape(z.Name) + \"-\" + strconv.FormatInt(time.Now().Unix(), 16) + \".log\"\n\tpath := filepath.Join(z.DataPath.Path(), name)\n\tl = l.With(esl.String(\"path\", path))\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\tl.Debug(\"Unable to create the log file\", esl.Error(err))\n\t\treturn err\n\t}\n\tz.currentJournal = f\n\tz.currentPath = path\n\tz.currentStart = time.Now()\n\tz.currentDeadline = z.currentStart.Add(time.Duration(z.SyncInterval.Value()) * time.Second)\n\tl.Debug(\"Journal created\", esl.Time(\"deadline\", z.currentDeadline))\n\treturn nil\n}\n\nfunc (z *Client) syncJournal(c app_control.Control) error {\n\tl := c.Log()\n\tif err := z.currentJournal.Close(); err != nil {\n\t\tl.Debug(\"Unable to close\", esl.Error(err))\n\t}\n\tif _, err := es_gzip.Compress(z.currentPath); err != nil {\n\t\tl.Debug(\"Unable to compress\", esl.Error(err))\n\t\treturn err\n\t}\n\tz.currentJournal = nil\n\tz.currentPath = \"\"\n\n\tfiles, err := os.ReadDir(z.DataPath.Path())\n\tif err != nil {\n\t\tl.Debug(\"Unable to read directory entry\")\n\t\treturn err\n\t}\n\n\tsv := sv_file_content.NewUpload(z.Peer.Client())\n\tbasePath := z.SyncPath.ChildPath(es_filepath.Escape(z.Name), z.currentStart.Format(\"2006-01\"), z.currentStart.Format(\"2006-01-02\"))\n\tfor _, f := range files {\n\t\tif !strings.HasPrefix(f.Name(), monitorFilePrefix) {\n\t\t\tcontinue\n\t\t}\n\t\tfp := filepath.Join(z.DataPath.Path(), f.Name())\n\t\tl.Info(\"Syncing journal file\", esl.String(\"name\", f.Name()))\n\t\tentry, err := sv.Add(basePath, fp)\n\t\tif err != nil {\n\t\t\tl.Debug(\"Unable to upload\", esl.Error(err))\n\t\t\treturn err\n\t\t}\n\t\tl.Debug(\"Upload completed\", esl.Any(\"entry\", entry))\n\t\t_ = os.Remove(fp)\n\t}\n\treturn nil\n}\n\nfunc (z *Client) sendEvent(c app_control.Control, eventType string, data interface{}) {\n\tev := Event{\n\t\tTime: time.Now().Format(time.RFC3339),\n\t\tType: eventType,\n\t\tData: data,\n\t}\n\tevs, err := json.Marshal(&ev)\n\tif err != nil {\n\t\tz.sendError(c, eventType, err)\n\t\treturn\n\t}\n\tif z.Display {\n\t\tc.Log().Info(\"event\", esl.Any(\"data\", ev))\n\t}\n\n\tif z.currentJournal != nil {\n\t\t_, err0 := z.currentJournal.Write(evs)\n\t\t_, err1 := z.currentJournal.Write([]byte(\"\\n\"))\n\n\t\tif z.rotateInProgress {\n\t\t\treturn\n\t\t}\n\n\t\tif err0 == nil && err1 == nil && z.currentDeadline.Before(time.Now()) {\n\t\t\tz.rotateInProgress = true\n\t\t\tif err := z.syncJournal(c); err != nil {\n\t\t\t\tz.sendError(c, eventType, err)\n\t\t\t}\n\t\t\tif err := z.openJournal(c); err != nil {\n\t\t\t\tz.sendError(c, eventType, err)\n\t\t\t}\n\t\t\tz.headEvents(c)\n\t\t\tz.rotateInProgress = false\n\t\t}\n\t}\n}\n\nfunc (z *Client) headEventCpuInfo(c app_control.Control) {\n\tcpuInfo, err := cpu.Info()\n\tif err != nil {\n\t\tz.sendError(c, EventCpuInfo, err)\n\t\treturn\n\t}\n\tz.sendEvent(c, EventCpuInfo, cpuInfo)\n}\n\nfunc (z *Client) eventCpuTime(c app_control.Control) {\n\tstat, err := cpu.Times(true)\n\tif err != nil {\n\t\tz.sendError(c, EventCpuTime, err)\n\t\treturn\n\t}\n\tz.sendEvent(c, EventCpuTime, stat)\n}\n\nfunc (z *Client) eventCpuPercent(c app_control.Control) {\n\tstat, err := cpu.Percent(0, true)\n\tif err != nil {\n\t\tz.sendError(c, EventCpuPercent, err)\n\t\treturn\n\t}\n\tz.sendEvent(c, EventCpuPercent, stat)\n}\n\nfunc (z *Client) headEventHostInfo(c app_control.Control) {\n\thostInfo, err := host.Info()\n\tif err != nil {\n\t\tz.sendError(c, EventHostInfo, err)\n\t\treturn\n\t}\n\tz.sendEvent(c, EventHostInfo, hostInfo)\n}\n\nfunc (z *Client) headEventDiskPartition(c app_control.Control) {\n\tinfo, err := disk.Partitions(true)\n\tif err != nil {\n\t\tz.sendError(c, EventDiskPartition, err)\n\t\treturn\n\t}\n\tz.sendEvent(c, EventDiskPartition, info)\n}\n\nfunc (z *Client) eventDiskUsage(c app_control.Control) {\n\tpartitions, err := disk.Partitions(true)\n\tif err != nil {\n\t\tz.sendError(c, EventDiskUsage, err)\n\t\treturn\n\t}\n\tfor _, p := range partitions {\n\t\tusage, err := disk.Usage(p.Mountpoint)\n\t\tif err != nil {\n\t\t\tz.sendError(c, EventDiskUsage, err)\n\t\t\tcontinue\n\t\t}\n\t\tz.sendEvent(c, EventDiskUsage, usage)\n\t}\n}\n\nfunc (z *Client) eventLoadAverage(c app_control.Control) {\n\tla, err := load.Avg()\n\tif err != nil {\n\t\tz.sendError(c, EventLoadAverage, err)\n\t\treturn\n\t}\n\tz.sendEvent(c, EventLoadAverage, la)\n}\n\nfunc (z *Client) eventMemoryStat(c app_control.Control) {\n\tvm, err := mem.VirtualMemory()\n\tif err != nil {\n\t\tz.sendError(c, EventMemoryStat, err)\n\t\treturn\n\t}\n\tz.sendEvent(c, EventMemoryStat, vm)\n}\n\nfunc (z *Client) eventNetIO(c app_control.Control) {\n\tstats, err := net.IOCounters(true)\n\tif err != nil {\n\t\tz.sendError(c, EventNetIO, err)\n\t\treturn\n\t}\n\tz.sendEvent(c, EventNetIO, stats)\n}\n\nfunc (z *Client) eventNetProtocol(c app_control.Control) {\n\tstats, err := net.ProtoCounters([]string{})\n\tif err != nil {\n\t\tz.sendError(c, EventNetProtocol, err)\n\t\treturn\n\t}\n\tz.sendEvent(c, EventNetProtocol, stats)\n}\n\nfunc (z *Client) headEventMonitorInfo(c app_control.Control) {\n\tvar userUserName, userDisplayName, userUid string\n\tif usr, err := user.Current(); err == nil {\n\t\tuserUserName = usr.Username\n\t\tuserDisplayName = usr.Name\n\t\tuserUid = usr.Uid\n\t}\n\n\tz.sendEvent(c, EventMonitorInfo, struct {\n\t\tAppVersion      string `json:\"app_version\"`\n\t\tMonitorName     string `json:\"monitor_name\"`\n\t\tIntervalMonitor int    `json:\"interval_monitor\"`\n\t\tIntervalSync    int    `json:\"interval_sync\"`\n\t\tUserDisplayName string `json:\"user_display_name\"`\n\t\tUserUid         string `json:\"user_uid\"`\n\t\tUserName        string `json:\"user_name\"`\n\t}{\n\t\tAppVersion:      app.BuildId,\n\t\tMonitorName:     z.Name,\n\t\tIntervalMonitor: z.MonitorInterval.Value(),\n\t\tIntervalSync:    z.SyncInterval.Value(),\n\t\tUserDisplayName: userDisplayName,\n\t\tUserUid:         userUid,\n\t\tUserName:        userUserName,\n\t})\n}\n\nfunc (z *Client) headEvents(c app_control.Control) {\n\tz.headEventMonitorInfo(c)\n\tz.headEventCpuInfo(c)\n\tz.headEventHostInfo(c)\n\tz.headEventDiskPartition(c)\n}\n\nfunc (z *Client) Exec(c app_control.Control) error {\n\tl := c.Log()\n\tif err := os.MkdirAll(z.DataPath.Path(), 0755); err != nil {\n\t\treturn err\n\t}\n\tif err := z.openJournal(c); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Head events\n\tz.headEvents(c)\n\n\t\/\/ Periodical events\n\tfor {\n\t\tz.eventCpuPercent(c)\n\t\tz.eventCpuTime(c)\n\t\tz.eventDiskUsage(c)\n\t\tz.eventLoadAverage(c)\n\t\tz.eventMemoryStat(c)\n\t\tz.eventNetIO(c)\n\t\tz.eventNetProtocol(c)\n\n\t\tif !z.MonitorEnd.IsZero() && z.MonitorEnd.Time().Before(time.Now()) {\n\t\t\treturn z.syncJournal(c)\n\t\t}\n\t\ttime.Sleep(time.Duration(z.MonitorInterval.Value()) * time.Second)\n\t\tl.Info(\"Monitor\", esl.Time(\"t\", time.Now()))\n\t}\n}\n\nfunc (z *Client) Test(c app_control.Control) error {\n\tf, err := qt_file.MakeTestFolder(\"monitor\", false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = os.RemoveAll(f)\n\t}()\n\n\treturn rc_exec.ExecMock(c, &Client{}, func(r rc_recipe.Recipe) {\n\t\tm := r.(*Client)\n\t\tm.Name = \"mango\"\n\t\tm.DataPath = mo_path.NewFileSystemPath(f)\n\t\tm.SyncPath = qtr_endtoend.NewTestDropboxFolderPath(\"monitor\")\n\t\tm.MonitorEnd = mo_time.NewOptional(time.Now())\n\t})\n}\n<commit_msg>fix #650 : head events in every files<commit_after>package monitor\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/shirou\/gopsutil\/v3\/cpu\"\n\t\"github.com\/shirou\/gopsutil\/v3\/disk\"\n\t\"github.com\/shirou\/gopsutil\/v3\/host\"\n\t\"github.com\/shirou\/gopsutil\/v3\/load\"\n\t\"github.com\/shirou\/gopsutil\/v3\/mem\"\n\t\"github.com\/shirou\/gopsutil\/v3\/net\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/api\/dbx_auth\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/api\/dbx_conn\"\n\tmo_path2 \"github.com\/watermint\/toolbox\/domain\/dropbox\/model\/mo_path\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/model\/mo_time\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/service\/sv_file_content\"\n\t\"github.com\/watermint\/toolbox\/essentials\/file\/es_filepath\"\n\t\"github.com\/watermint\/toolbox\/essentials\/file\/es_gzip\"\n\t\"github.com\/watermint\/toolbox\/essentials\/log\/esl\"\n\t\"github.com\/watermint\/toolbox\/essentials\/model\/mo_int\"\n\t\"github.com\/watermint\/toolbox\/essentials\/model\/mo_path\"\n\t\"github.com\/watermint\/toolbox\/infra\/app\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_control\"\n\t\"github.com\/watermint\/toolbox\/infra\/recipe\/rc_exec\"\n\t\"github.com\/watermint\/toolbox\/infra\/recipe\/rc_recipe\"\n\t\"github.com\/watermint\/toolbox\/quality\/infra\/qt_file\"\n\t\"github.com\/watermint\/toolbox\/quality\/recipe\/qtr_endtoend\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tmonitorFilePrefix = \"tbx-monitor-\"\n)\n\ntype Client struct {\n\tDataPath        mo_path.FileSystemPath\n\tSyncPath        mo_path2.DropboxPath\n\tPeer            dbx_conn.ConnScopedIndividual\n\tName            string\n\tMonitorInterval mo_int.RangeInt\n\tSyncInterval    mo_int.RangeInt\n\tMonitorEnd      mo_time.TimeOptional\n\tDisplay         bool\n\n\tsentErrors       map[string]int64 \/\/ eventType -> num error sent\n\tsentCount        map[string]int64 \/\/ eventType -> num event sent\n\tcurrentJournal   *os.File\n\tcurrentPath      string\n\tcurrentStart     time.Time\n\tcurrentDeadline  time.Time\n\trotateInProgress bool\n}\n\nfunc (z *Client) Preset() {\n\tz.MonitorInterval.SetRange(1, 86400, 10)\n\tz.SyncInterval.SetRange(10, 86400, 3600)\n\tz.sentErrors = make(map[string]int64)\n\tz.sentCount = make(map[string]int64)\n\tz.Peer.SetScopes(\n\t\tdbx_auth.ScopeFilesContentWrite,\n\t)\n}\nfunc (z *Client) sendError(c app_control.Control, eventType string, err error) {\n\tif n, ok := z.sentErrors[eventType]; ok {\n\t\tz.sentErrors[eventType] = n + 1\n\t\treturn\n\t}\n\tl := c.Log()\n\tl.Warn(\"Unable to retrieve event data\", esl.String(\"type\", eventType), esl.Error(err))\n\tz.sentErrors[eventType] = 1\n}\n\nfunc (z *Client) openJournal(c app_control.Control) error {\n\tl := c.Log()\n\tif z.currentJournal != nil {\n\t\treturn nil\n\t}\n\tname := monitorFilePrefix + es_filepath.Escape(z.Name) + \"-\" + fmt.Sprintf(\"%08x\", time.Now().Unix()) + \".log\"\n\tpath := filepath.Join(z.DataPath.Path(), name)\n\tl = l.With(esl.String(\"path\", path))\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\tl.Debug(\"Unable to create the log file\", esl.Error(err))\n\t\treturn err\n\t}\n\tz.currentJournal = f\n\tz.currentPath = path\n\tz.currentStart = time.Now()\n\tz.currentDeadline = z.currentStart.Add(time.Duration(z.SyncInterval.Value()) * time.Second)\n\tl.Debug(\"Journal created\", esl.Time(\"deadline\", z.currentDeadline))\n\treturn nil\n}\n\nfunc (z *Client) syncJournal(c app_control.Control) error {\n\tl := c.Log()\n\tif err := z.currentJournal.Close(); err != nil {\n\t\tl.Debug(\"Unable to close\", esl.Error(err))\n\t}\n\tif _, err := es_gzip.Compress(z.currentPath); err != nil {\n\t\tl.Debug(\"Unable to compress\", esl.Error(err))\n\t\treturn err\n\t}\n\tz.currentJournal = nil\n\tz.currentPath = \"\"\n\n\tfiles, err := os.ReadDir(z.DataPath.Path())\n\tif err != nil {\n\t\tl.Debug(\"Unable to read directory entry\")\n\t\treturn err\n\t}\n\n\tsv := sv_file_content.NewUpload(z.Peer.Client())\n\tbasePath := z.SyncPath.ChildPath(es_filepath.Escape(z.Name), z.currentStart.Format(\"2006-01\"), z.currentStart.Format(\"2006-01-02\"))\n\tfor _, f := range files {\n\t\tif !strings.HasPrefix(f.Name(), monitorFilePrefix) {\n\t\t\tcontinue\n\t\t}\n\t\tfp := filepath.Join(z.DataPath.Path(), f.Name())\n\t\tl.Info(\"Syncing journal file\", esl.String(\"name\", f.Name()))\n\t\tentry, err := sv.Add(basePath, fp)\n\t\tif err != nil {\n\t\t\tl.Debug(\"Unable to upload\", esl.Error(err))\n\t\t\treturn err\n\t\t}\n\t\tl.Debug(\"Upload completed\", esl.Any(\"entry\", entry))\n\t\t_ = os.Remove(fp)\n\t}\n\treturn nil\n}\n\nfunc (z *Client) sendEvent(c app_control.Control, eventType string, data interface{}) {\n\tev := Event{\n\t\tTime: time.Now().Format(time.RFC3339),\n\t\tType: eventType,\n\t\tData: data,\n\t}\n\tevs, err := json.Marshal(&ev)\n\tif err != nil {\n\t\tz.sendError(c, eventType, err)\n\t\treturn\n\t}\n\tif z.Display {\n\t\tc.Log().Info(\"event\", esl.Any(\"data\", ev))\n\t}\n\n\tif z.currentJournal != nil {\n\t\t_, err0 := z.currentJournal.Write(evs)\n\t\t_, err1 := z.currentJournal.Write([]byte(\"\\n\"))\n\n\t\tif z.rotateInProgress {\n\t\t\treturn\n\t\t}\n\n\t\tif err0 == nil && err1 == nil && z.currentDeadline.Before(time.Now()) {\n\t\t\tz.rotateInProgress = true\n\t\t\tif err := z.syncJournal(c); err != nil {\n\t\t\t\tz.sendError(c, eventType, err)\n\t\t\t}\n\t\t\tif err := z.openJournal(c); err != nil {\n\t\t\t\tz.sendError(c, eventType, err)\n\t\t\t}\n\t\t\tz.headEvents(c)\n\t\t\tz.rotateInProgress = false\n\t\t}\n\t}\n\n\tif ns, ok := z.sentCount[eventType]; ok {\n\t\tz.sentCount[eventType] = ns + 1\n\t} else {\n\t\tz.sentCount[eventType] = 1\n\t}\n}\n\nfunc (z *Client) shouldAbort(eventType string) bool {\n\tif ne, oke := z.sentErrors[eventType]; oke {\n\t\tif ns, okc := z.sentCount[eventType]; okc {\n\t\t\t\/\/ Abort when three more errors without success\n\t\t\tif 2 < ne && ns < 1 {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (z *Client) handleEvent(c app_control.Control, eventType string, f func() (data interface{}, err error)) {\n\tif z.shouldAbort(eventType) {\n\t\treturn\n\t}\n\n\tdata, err := f()\n\tif err != nil {\n\t\tz.sendError(c, eventType, err)\n\t} else {\n\t\tz.sendEvent(c, eventType, data)\n\t}\n}\n\nfunc (z *Client) headEventCpuInfo(c app_control.Control) {\n\tz.handleEvent(c, EventCpuInfo, func() (data interface{}, err error) {\n\t\treturn cpu.Info()\n\t})\n}\n\nfunc (z *Client) eventCpuTime(c app_control.Control) {\n\tz.handleEvent(c, EventCpuTime, func() (data interface{}, err error) {\n\t\treturn cpu.Times(true)\n\t})\n}\n\nfunc (z *Client) eventCpuPercent(c app_control.Control) {\n\tz.handleEvent(c, EventCpuPercent, func() (data interface{}, err error) {\n\t\treturn cpu.Percent(0, true)\n\t})\n}\n\nfunc (z *Client) headEventHostInfo(c app_control.Control) {\n\tz.handleEvent(c, EventHostInfo, func() (data interface{}, err error) {\n\t\treturn host.Info()\n\t})\n}\n\nfunc (z *Client) headEventDiskPartition(c app_control.Control) {\n\tz.handleEvent(c, EventDiskPartition, func() (data interface{}, err error) {\n\t\treturn disk.Partitions(true)\n\t})\n}\n\nfunc (z *Client) eventDiskUsage(c app_control.Control) {\n\tif z.shouldAbort(EventDiskUsage) {\n\t\treturn\n\t}\n\n\tpartitions, err := disk.Partitions(true)\n\tif err != nil {\n\t\tz.sendError(c, EventDiskUsage, err)\n\t\treturn\n\t}\n\tfor _, p := range partitions {\n\t\tusage, err := disk.Usage(p.Mountpoint)\n\t\tif err != nil {\n\t\t\tz.sendError(c, EventDiskUsage, err)\n\t\t\tcontinue\n\t\t}\n\t\tz.sendEvent(c, EventDiskUsage, usage)\n\t}\n}\n\nfunc (z *Client) eventLoadAverage(c app_control.Control) {\n\tz.handleEvent(c, EventLoadAverage, func() (data interface{}, err error) {\n\t\treturn load.Avg()\n\t})\n}\n\nfunc (z *Client) eventMemoryStat(c app_control.Control) {\n\tz.handleEvent(c, EventMemoryStat, func() (data interface{}, err error) {\n\t\treturn mem.VirtualMemory()\n\t})\n}\n\nfunc (z *Client) eventNetIO(c app_control.Control) {\n\tz.handleEvent(c, EventNetIO, func() (data interface{}, err error) {\n\t\treturn net.IOCounters(true)\n\t})\n}\n\nfunc (z *Client) eventNetProtocol(c app_control.Control) {\n\tz.handleEvent(c, EventNetProtocol, func() (data interface{}, err error) {\n\t\treturn net.ProtoCounters([]string{})\n\t})\n}\n\nfunc (z *Client) headEventMonitorInfo(c app_control.Control) {\n\tvar userUserName, userDisplayName, userUid string\n\tif usr, err := user.Current(); err == nil {\n\t\tuserUserName = usr.Username\n\t\tuserDisplayName = usr.Name\n\t\tuserUid = usr.Uid\n\t}\n\n\tz.sendEvent(c, EventMonitorInfo, struct {\n\t\tAppVersion      string `json:\"app_version\"`\n\t\tMonitorName     string `json:\"monitor_name\"`\n\t\tIntervalMonitor int    `json:\"interval_monitor\"`\n\t\tIntervalSync    int    `json:\"interval_sync\"`\n\t\tUserDisplayName string `json:\"user_display_name\"`\n\t\tUserUid         string `json:\"user_uid\"`\n\t\tUserName        string `json:\"user_name\"`\n\t}{\n\t\tAppVersion:      app.BuildId,\n\t\tMonitorName:     z.Name,\n\t\tIntervalMonitor: z.MonitorInterval.Value(),\n\t\tIntervalSync:    z.SyncInterval.Value(),\n\t\tUserDisplayName: userDisplayName,\n\t\tUserUid:         userUid,\n\t\tUserName:        userUserName,\n\t})\n}\n\nfunc (z *Client) headEvents(c app_control.Control) {\n\tz.headEventMonitorInfo(c)\n\tz.headEventCpuInfo(c)\n\tz.headEventHostInfo(c)\n\tz.headEventDiskPartition(c)\n}\n\nfunc (z *Client) Exec(c app_control.Control) error {\n\tl := c.Log()\n\tif err := os.MkdirAll(z.DataPath.Path(), 0755); err != nil {\n\t\treturn err\n\t}\n\tif err := z.openJournal(c); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Head events\n\tz.headEvents(c)\n\n\t\/\/ Periodical events\n\tfor {\n\t\tz.eventCpuPercent(c)\n\t\tz.eventCpuTime(c)\n\t\tz.eventDiskUsage(c)\n\t\tz.eventLoadAverage(c)\n\t\tz.eventMemoryStat(c)\n\t\tz.eventNetIO(c)\n\t\tz.eventNetProtocol(c)\n\n\t\tif !z.MonitorEnd.IsZero() && z.MonitorEnd.Time().Before(time.Now()) {\n\t\t\treturn z.syncJournal(c)\n\t\t}\n\t\ttime.Sleep(time.Duration(z.MonitorInterval.Value()) * time.Second)\n\t\tl.Info(\"Monitor\", esl.Time(\"t\", time.Now()))\n\t}\n}\n\nfunc (z *Client) Test(c app_control.Control) error {\n\tf, err := qt_file.MakeTestFolder(\"monitor\", false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\t_ = os.RemoveAll(f)\n\t}()\n\n\treturn rc_exec.ExecMock(c, &Client{}, func(r rc_recipe.Recipe) {\n\t\tm := r.(*Client)\n\t\tm.Name = \"mango\"\n\t\tm.DataPath = mo_path.NewFileSystemPath(f)\n\t\tm.SyncPath = qtr_endtoend.NewTestDropboxFolderPath(\"monitor\")\n\t\tm.MonitorEnd = mo_time.NewOptional(time.Now())\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 The Grafeas Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage testutil\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/golang\/protobuf\/ptypes\"\n\t\"github.com\/golang\/protobuf\/ptypes\/any\"\n\tpb \"github.com\/grafeas\/grafeas\/v1alpha1\/proto\"\n\topspb \"google.golang.org\/genproto\/googleapis\/longrunning\"\n)\n\nfunc Occurrence(pID, noteName string) *pb.Occurrence {\n\treturn &pb.Occurrence{\n\t\tName:        fmt.Sprintf(\"projects\/%s\/occurrences\/134\", pID),\n\t\tResourceUrl: \"gcr.io\/foo\/bar\",\n\t\tNoteName:    noteName,\n\t\tKind:        pb.Note_PACKAGE_VULNERABILITY,\n\t\tDetails: &pb.Occurrence_VulnerabilityDetails{\n\t\t\tVulnerabilityDetails: &pb.VulnerabilityType_VulnerabilityDetails{\n\t\t\t\tSeverity:  pb.VulnerabilityType_HIGH,\n\t\t\t\tCvssScore: 7.5,\n\t\t\t\tPackageIssue: []*pb.VulnerabilityType_PackageIssue{\n\t\t\t\t\t&pb.VulnerabilityType_PackageIssue{\n\t\t\t\t\t\tSeverityName: \"HIGH\",\n\t\t\t\t\t\tAffectedLocation: &pb.VulnerabilityType_VulnerabilityLocation{\n\t\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:8\",\n\t\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\t\tVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\t\tName:     \"52.1\",\n\t\t\t\t\t\t\t\tRevision: \"8+deb8u3\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFixedLocation: &pb.VulnerabilityType_VulnerabilityLocation{\n\t\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:8\",\n\t\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\t\tVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\t\tName:     \"52.1\",\n\t\t\t\t\t\t\t\tRevision: \"8+deb8u4\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc Note(pID string) *pb.Note {\n\treturn &pb.Note{\n\t\tName:             fmt.Sprintf(\"projects\/%s\/notes\/CVE-1999-0710\", pID),\n\t\tShortDescription: \"CVE-2014-9911\",\n\t\tLongDescription:  \"NIST vectors: AV:N\/AC:L\/Au:N\/C:P\/I:P\",\n\t\tKind:             pb.Note_PACKAGE_VULNERABILITY,\n\t\tNoteType: &pb.Note_VulnerabilityType{\n\t\t\t&pb.VulnerabilityType{\n\t\t\t\tCvssScore: 7.5,\n\t\t\t\tSeverity:  pb.VulnerabilityType_HIGH,\n\t\t\t\tDetails: []*pb.VulnerabilityType_Detail{\n\t\t\t\t\t&pb.VulnerabilityType_Detail{\n\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:7\",\n\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\tDescription: \"Stack-based buffer overflow in the ures_getByKeyWithFallback function in \" +\n\t\t\t\t\t\t\t\"common\/uresbund.cpp in International Components for Unicode (ICU) before 54.1 for C\/C++ allows \" +\n\t\t\t\t\t\t\t\"remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted uloc_getDisplayName call.\",\n\t\t\t\t\t\tMinAffectedVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\tKind: pb.VulnerabilityType_Version_MINIMUM,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSeverityName: \"HIGH\",\n\n\t\t\t\t\t\tFixedLocation: &pb.VulnerabilityType_VulnerabilityLocation{\n\t\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:7\",\n\t\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\t\tVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\t\tName:     \"4.8.1.1\",\n\t\t\t\t\t\t\t\tRevision: \"12+deb7u6\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t&pb.VulnerabilityType_Detail{\n\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:8\",\n\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\tDescription: \"Stack-based buffer overflow in the ures_getByKeyWithFallback function in \" +\n\t\t\t\t\t\t\t\"common\/uresbund.cpp in International Components for Unicode (ICU) before 54.1 for C\/C++ allows \" +\n\t\t\t\t\t\t\t\"remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted uloc_getDisplayName call.\",\n\t\t\t\t\t\tMinAffectedVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\tKind: pb.VulnerabilityType_Version_MINIMUM,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSeverityName: \"HIGH\",\n\n\t\t\t\t\t\tFixedLocation: &pb.VulnerabilityType_VulnerabilityLocation{\n\t\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:8\",\n\t\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\t\tVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\t\tName:     \"52.1\",\n\t\t\t\t\t\t\t\tRevision: \"8+deb8u4\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t&pb.VulnerabilityType_Detail{\n\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:9\",\n\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\tDescription: \"Stack-based buffer overflow in the ures_getByKeyWithFallback function in \" +\n\t\t\t\t\t\t\t\"common\/uresbund.cpp in International Components for Unicode (ICU) before 54.1 for C\/C++ allows \" +\n\t\t\t\t\t\t\t\"remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted uloc_getDisplayName call.\",\n\t\t\t\t\t\tMinAffectedVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\tKind: pb.VulnerabilityType_Version_MINIMUM,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSeverityName: \"HIGH\",\n\n\t\t\t\t\t\tFixedLocation: &pb.VulnerabilityType_VulnerabilityLocation{\n\t\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:9\",\n\t\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\t\tVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\t\tName:     \"55.1\",\n\t\t\t\t\t\t\t\tRevision: \"3\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t&pb.VulnerabilityType_Detail{\n\t\t\t\t\t\tCpeUri:  \"cpe:\/o:canonical:ubuntu_linux:14.04\",\n\t\t\t\t\t\tPackage: \"andriod\",\n\t\t\t\t\t\tDescription: \"Stack-based buffer overflow in the ures_getByKeyWithFallback function in \" +\n\t\t\t\t\t\t\t\"common\/uresbund.cpp in International Components for Unicode (ICU) before 54.1 for C\/C++ allows \" +\n\t\t\t\t\t\t\t\"remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted uloc_getDisplayName call.\",\n\t\t\t\t\t\tMinAffectedVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\tKind: pb.VulnerabilityType_Version_MINIMUM,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSeverityName: \"MEDIUM\",\n\n\t\t\t\t\t\tFixedLocation: &pb.VulnerabilityType_VulnerabilityLocation{\n\t\t\t\t\t\t\tCpeUri:  \"cpe:\/o:canonical:ubuntu_linux:14.04\",\n\t\t\t\t\t\t\tPackage: \"andriod\",\n\t\t\t\t\t\t\tVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\t\tKind: pb.VulnerabilityType_Version_MAXIMUM,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tRelatedUrl: []*pb.Note_RelatedUrl{\n\t\t\t&pb.Note_RelatedUrl{\n\t\t\t\tUrl:   \"https:\/\/security-tracker.debian.org\/tracker\/CVE-2014-9911\",\n\t\t\t\tLabel: \"More Info\",\n\t\t\t},\n\t\t\t&pb.Note_RelatedUrl{\n\t\t\t\tUrl:   \"http:\/\/people.ubuntu.com\/~ubuntu-security\/cve\/CVE-2014-9911\",\n\t\t\t\tLabel: \"More Info\",\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc Operation(pID string) *opspb.Operation {\n\tmd := &pb.OperationMetadata{CreateTime: ptypes.TimestampNow()}\n\tbytes, err := proto.Marshal(md)\n\tif err != nil {\n\t\tlog.Printf(\"Error parsing bytes: %v\", err)\n\t\treturn nil\n\t}\n\treturn &opspb.Operation{\n\t\tName:     fmt.Sprintf(\"projects\/%s\/operations\/foo\", pID),\n\t\tMetadata: &any.Any{Value: bytes},\n\t\tDone:     false,\n\t}\n}\n<commit_msg>Fix misspelling of 'android'<commit_after>\/\/ Copyright 2017 The Grafeas Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage testutil\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/golang\/protobuf\/ptypes\"\n\t\"github.com\/golang\/protobuf\/ptypes\/any\"\n\tpb \"github.com\/grafeas\/grafeas\/v1alpha1\/proto\"\n\topspb \"google.golang.org\/genproto\/googleapis\/longrunning\"\n)\n\nfunc Occurrence(pID, noteName string) *pb.Occurrence {\n\treturn &pb.Occurrence{\n\t\tName:        fmt.Sprintf(\"projects\/%s\/occurrences\/134\", pID),\n\t\tResourceUrl: \"gcr.io\/foo\/bar\",\n\t\tNoteName:    noteName,\n\t\tKind:        pb.Note_PACKAGE_VULNERABILITY,\n\t\tDetails: &pb.Occurrence_VulnerabilityDetails{\n\t\t\tVulnerabilityDetails: &pb.VulnerabilityType_VulnerabilityDetails{\n\t\t\t\tSeverity:  pb.VulnerabilityType_HIGH,\n\t\t\t\tCvssScore: 7.5,\n\t\t\t\tPackageIssue: []*pb.VulnerabilityType_PackageIssue{\n\t\t\t\t\t&pb.VulnerabilityType_PackageIssue{\n\t\t\t\t\t\tSeverityName: \"HIGH\",\n\t\t\t\t\t\tAffectedLocation: &pb.VulnerabilityType_VulnerabilityLocation{\n\t\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:8\",\n\t\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\t\tVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\t\tName:     \"52.1\",\n\t\t\t\t\t\t\t\tRevision: \"8+deb8u3\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFixedLocation: &pb.VulnerabilityType_VulnerabilityLocation{\n\t\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:8\",\n\t\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\t\tVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\t\tName:     \"52.1\",\n\t\t\t\t\t\t\t\tRevision: \"8+deb8u4\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc Note(pID string) *pb.Note {\n\treturn &pb.Note{\n\t\tName:             fmt.Sprintf(\"projects\/%s\/notes\/CVE-1999-0710\", pID),\n\t\tShortDescription: \"CVE-2014-9911\",\n\t\tLongDescription:  \"NIST vectors: AV:N\/AC:L\/Au:N\/C:P\/I:P\",\n\t\tKind:             pb.Note_PACKAGE_VULNERABILITY,\n\t\tNoteType: &pb.Note_VulnerabilityType{\n\t\t\t&pb.VulnerabilityType{\n\t\t\t\tCvssScore: 7.5,\n\t\t\t\tSeverity:  pb.VulnerabilityType_HIGH,\n\t\t\t\tDetails: []*pb.VulnerabilityType_Detail{\n\t\t\t\t\t&pb.VulnerabilityType_Detail{\n\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:7\",\n\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\tDescription: \"Stack-based buffer overflow in the ures_getByKeyWithFallback function in \" +\n\t\t\t\t\t\t\t\"common\/uresbund.cpp in International Components for Unicode (ICU) before 54.1 for C\/C++ allows \" +\n\t\t\t\t\t\t\t\"remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted uloc_getDisplayName call.\",\n\t\t\t\t\t\tMinAffectedVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\tKind: pb.VulnerabilityType_Version_MINIMUM,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSeverityName: \"HIGH\",\n\n\t\t\t\t\t\tFixedLocation: &pb.VulnerabilityType_VulnerabilityLocation{\n\t\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:7\",\n\t\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\t\tVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\t\tName:     \"4.8.1.1\",\n\t\t\t\t\t\t\t\tRevision: \"12+deb7u6\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t&pb.VulnerabilityType_Detail{\n\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:8\",\n\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\tDescription: \"Stack-based buffer overflow in the ures_getByKeyWithFallback function in \" +\n\t\t\t\t\t\t\t\"common\/uresbund.cpp in International Components for Unicode (ICU) before 54.1 for C\/C++ allows \" +\n\t\t\t\t\t\t\t\"remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted uloc_getDisplayName call.\",\n\t\t\t\t\t\tMinAffectedVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\tKind: pb.VulnerabilityType_Version_MINIMUM,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSeverityName: \"HIGH\",\n\n\t\t\t\t\t\tFixedLocation: &pb.VulnerabilityType_VulnerabilityLocation{\n\t\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:8\",\n\t\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\t\tVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\t\tName:     \"52.1\",\n\t\t\t\t\t\t\t\tRevision: \"8+deb8u4\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t&pb.VulnerabilityType_Detail{\n\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:9\",\n\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\tDescription: \"Stack-based buffer overflow in the ures_getByKeyWithFallback function in \" +\n\t\t\t\t\t\t\t\"common\/uresbund.cpp in International Components for Unicode (ICU) before 54.1 for C\/C++ allows \" +\n\t\t\t\t\t\t\t\"remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted uloc_getDisplayName call.\",\n\t\t\t\t\t\tMinAffectedVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\tKind: pb.VulnerabilityType_Version_MINIMUM,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSeverityName: \"HIGH\",\n\n\t\t\t\t\t\tFixedLocation: &pb.VulnerabilityType_VulnerabilityLocation{\n\t\t\t\t\t\t\tCpeUri:  \"cpe:\/o:debian:debian_linux:9\",\n\t\t\t\t\t\t\tPackage: \"icu\",\n\t\t\t\t\t\t\tVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\t\tName:     \"55.1\",\n\t\t\t\t\t\t\t\tRevision: \"3\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t&pb.VulnerabilityType_Detail{\n\t\t\t\t\t\tCpeUri:  \"cpe:\/o:canonical:ubuntu_linux:14.04\",\n\t\t\t\t\t\tPackage: \"android\",\n\t\t\t\t\t\tDescription: \"Stack-based buffer overflow in the ures_getByKeyWithFallback function in \" +\n\t\t\t\t\t\t\t\"common\/uresbund.cpp in International Components for Unicode (ICU) before 54.1 for C\/C++ allows \" +\n\t\t\t\t\t\t\t\"remote attackers to cause a denial of service or possibly have unspecified other impact via a crafted uloc_getDisplayName call.\",\n\t\t\t\t\t\tMinAffectedVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\tKind: pb.VulnerabilityType_Version_MINIMUM,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tSeverityName: \"MEDIUM\",\n\n\t\t\t\t\t\tFixedLocation: &pb.VulnerabilityType_VulnerabilityLocation{\n\t\t\t\t\t\t\tCpeUri:  \"cpe:\/o:canonical:ubuntu_linux:14.04\",\n\t\t\t\t\t\t\tPackage: \"android\",\n\t\t\t\t\t\t\tVersion: &pb.VulnerabilityType_Version{\n\t\t\t\t\t\t\t\tKind: pb.VulnerabilityType_Version_MAXIMUM,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tRelatedUrl: []*pb.Note_RelatedUrl{\n\t\t\t&pb.Note_RelatedUrl{\n\t\t\t\tUrl:   \"https:\/\/security-tracker.debian.org\/tracker\/CVE-2014-9911\",\n\t\t\t\tLabel: \"More Info\",\n\t\t\t},\n\t\t\t&pb.Note_RelatedUrl{\n\t\t\t\tUrl:   \"http:\/\/people.ubuntu.com\/~ubuntu-security\/cve\/CVE-2014-9911\",\n\t\t\t\tLabel: \"More Info\",\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc Operation(pID string) *opspb.Operation {\n\tmd := &pb.OperationMetadata{CreateTime: ptypes.TimestampNow()}\n\tbytes, err := proto.Marshal(md)\n\tif err != nil {\n\t\tlog.Printf(\"Error parsing bytes: %v\", err)\n\t\treturn nil\n\t}\n\treturn &opspb.Operation{\n\t\tName:     fmt.Sprintf(\"projects\/%s\/operations\/foo\", pID),\n\t\tMetadata: &any.Any{Value: bytes},\n\t\tDone:     false,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package replication\n\nimport (\n\t\"errors\"\n\t\"time\"\n)\n\nvar (\n\tErrGetEventTimeout = errors.New(\"Get event timeout, try get later\")\n\tErrNeedSyncAgain   = errors.New(\"Last sync error or closed, try sync and get event again\")\n\tErrSyncClosed      = errors.New(\"Sync was closed\")\n)\n\ntype BinlogStreamer struct {\n\tch  chan *BinlogEvent\n\tech chan error\n\terr error\n}\n\nfunc (s *BinlogStreamer) GetEvent() (*BinlogEvent, error) {\n\t\/\/ we use a very very long timeout here\n\treturn s.GetEventTimeout(time.Second * 3600 * 24 * 30)\n}\n\n\/\/ if timeout, ErrGetEventTimeout will returns\nfunc (s *BinlogStreamer) GetEventTimeout(d time.Duration) (*BinlogEvent, error) {\n\tif s.err != nil {\n\t\treturn nil, ErrNeedSyncAgain\n\t}\n\n\tselect {\n\tcase c := <-s.ch:\n\t\treturn c, nil\n\tcase s.err = <-s.ech:\n\t\treturn nil, s.err\n\tcase <-time.After(d):\n\t\treturn nil, ErrGetEventTimeout\n\t}\n}\n\nfunc (s *BinlogStreamer) close() {\n\ts.closeWithError(ErrSyncClosed)\n}\n\nfunc (s *BinlogStreamer) closeWithError(err error) {\n\tif err == nil {\n\t\terr = ErrSyncClosed\n\t}\n\tselect {\n\tcase s.ech <- err:\n\tdefault:\n\t}\n}\n\nfunc newBinlogStreamer() *BinlogStreamer {\n\ts := new(BinlogStreamer)\n\n\ts.ch = make(chan *BinlogEvent, 1024)\n\ts.ech = make(chan error, 4)\n\n\treturn s\n}\n<commit_msg>set timeout to 1s to avoid memory leak<commit_after>package replication\n\nimport (\n\t\"errors\"\n\t\"time\"\n)\n\nvar (\n\tErrGetEventTimeout = errors.New(\"Get event timeout, try get later\")\n\tErrNeedSyncAgain   = errors.New(\"Last sync error or closed, try sync and get event again\")\n\tErrSyncClosed      = errors.New(\"Sync was closed\")\n)\n\ntype BinlogStreamer struct {\n\tch  chan *BinlogEvent\n\tech chan error\n\terr error\n}\n\nfunc (s *BinlogStreamer) GetEvent() (*BinlogEvent, error) {\n\t\/\/ we use a very very long timeout here\n\treturn s.GetEventTimeout(time.Second * 1)\n}\n\n\/\/ if timeout, ErrGetEventTimeout will returns\nfunc (s *BinlogStreamer) GetEventTimeout(d time.Duration) (*BinlogEvent, error) {\n\tif s.err != nil {\n\t\treturn nil, ErrNeedSyncAgain\n\t}\n\n\tselect {\n\tcase c := <-s.ch:\n\t\treturn c, nil\n\tcase s.err = <-s.ech:\n\t\treturn nil, s.err\n\tcase <-time.After(d):\n\t\treturn nil, ErrGetEventTimeout\n\t}\n}\n\nfunc (s *BinlogStreamer) close() {\n\ts.closeWithError(ErrSyncClosed)\n}\n\nfunc (s *BinlogStreamer) closeWithError(err error) {\n\tif err == nil {\n\t\terr = ErrSyncClosed\n\t}\n\tselect {\n\tcase s.ech <- err:\n\tdefault:\n\t}\n}\n\nfunc newBinlogStreamer() *BinlogStreamer {\n\ts := new(BinlogStreamer)\n\n\ts.ch = make(chan *BinlogEvent, 1024)\n\ts.ech = make(chan error, 4)\n\n\treturn s\n}\n<|endoftext|>"}
{"text":"<commit_before>package content\n\nimport (\n\t\"encoding\/json\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com\/Financial-Times\/neo-utils-go\/neoutils\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/jmcvetta\/neoism\"\n)\n\nvar uuidExtractRegex = regexp.MustCompile(\".*\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$\")\n\n\/\/ CypherDriver - CypherDriver\ntype service struct {\n\tconn neoutils.NeoConnection\n}\n\n\/\/NewCypherDriver instantiate driver\nfunc NewCypherContentService(cypherRunner neoutils.NeoConnection) service {\n\treturn service{cypherRunner}\n}\n\n\/\/Initialise ensure constraint on content uuid\nfunc (cd service) Initialise() error {\n\n\treturn cd.conn.EnsureConstraints(map[string]string{\n\t\t\"Content\": \"uuid\"})\n}\n\n\/\/ Check - Feeds into the Healthcheck and checks whether we can connect to Neo and that the datastore isn't empty\nfunc (pcd service) Check() error {\n\treturn neoutils.Check(pcd.conn)\n}\n\n\/\/ Read - reads a content given a UUID\nfunc (pcd service) Read(uuid string) (interface{}, bool, error) {\n\tresults := []struct {\n\t\tcontent\n\t}{}\n\n\tquery := &neoism.CypherQuery{\n\t\tStatement: `MATCH (n:Content {uuid:{uuid}})\n\t\t\treturn n.uuid as uuid, n.title as title, n.publishedDate as publishedDate`,\n\t\tParameters: map[string]interface{}{\n\t\t\t\"uuid\": uuid,\n\t\t},\n\t\tResult: &results,\n\t}\n\n\terr := pcd.conn.CypherBatch([]*neoism.CypherQuery{query})\n\n\tif err != nil {\n\t\treturn content{}, false, err\n\t}\n\n\tif len(results) == 0 {\n\t\treturn content{}, false, nil\n\t}\n\n\tresult := results[0]\n\n\tcontentItem := content{\n\t\tUUID:          result.UUID,\n\t\tTitle:         result.Title,\n\t\tPublishedDate: result.PublishedDate,\n\t}\n\treturn contentItem, true, nil\n}\n\n\/\/Write - Writes a content node\nfunc (pcd service) Write(thing interface{}) error {\n\tc := thing.(content)\n\n\t\/\/ Only Articles have a body\n\tif c.Body == \"\" {\n\t\tlog.Infof(\"There is no body with this content item therefore assuming is it not an Article: %v\", c.UUID)\n\t\treturn nil\n\t}\n\n\tparams := map[string]interface{}{\n\t\t\"uuid\": c.UUID,\n\t}\n\n\tif c.Title != \"\" {\n\t\tparams[\"title\"] = c.Title\n\t\tparams[\"prefLabel\"] = c.Title\n\t}\n\n\tif c.PublishedDate != \"\" {\n\t\tparams[\"publishedDate\"] = c.PublishedDate\n\t\tdatetimeEpoch, err := time.Parse(time.RFC3339, c.PublishedDate)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tparams[\"publishedDateEpoch\"] = datetimeEpoch.Unix()\n\t}\n\n\tstatement := `MERGE (n:Thing {uuid: {uuid}})\n\t\t      set n={allprops}\n\t\t      set n :Content`\n\n\treturn pcd.conn.CypherBatch(\n\t\t[]*neoism.CypherQuery{\n\t\t\t{\n\t\t\t\tStatement: statement,\n\t\t\t\tParameters: map[string]interface{}{\n\t\t\t\t\t\"uuid\":     c.UUID,\n\t\t\t\t\t\"allprops\": params,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n}\n\n\/\/Delete - Deletes a content\nfunc (pcd service) Delete(uuid string) (bool, error) {\n\tclearNode := &neoism.CypherQuery{\n\t\tStatement: `\n\t\t\tMATCH (p:Thing {uuid: {uuid}})\n\t\t\tREMOVE p:Content\n\t\t\tSET p={props}\n\t\t`,\n\t\tParameters: map[string]interface{}{\n\t\t\t\"uuid\": uuid,\n\t\t\t\"props\": map[string]interface{}{\n\t\t\t\t\"uuid\": uuid,\n\t\t\t},\n\t\t},\n\t\tIncludeStats: true,\n\t}\n\n\tremoveNodeIfUnused := &neoism.CypherQuery{\n\t\tStatement: `\n\t\t\tMATCH (p:Thing {uuid: {uuid}})\n\t\t\tOPTIONAL MATCH (p)-[a]-(x)\n\t\t\tWITH p, count(a) AS relCount\n\t\t\tWHERE relCount = 0\n\t\t\tDELETE p\n\t\t`,\n\t\tParameters: map[string]interface{}{\n\t\t\t\"uuid\": uuid,\n\t\t},\n\t}\n\n\terr := pcd.conn.CypherBatch([]*neoism.CypherQuery{clearNode, removeNodeIfUnused})\n\n\ts1, err := clearNode.Stats()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tvar deleted bool\n\tif s1.ContainsUpdates && s1.LabelsRemoved > 0 {\n\t\tdeleted = true\n\t}\n\n\treturn deleted, err\n}\n\n\/\/ DecodeJSON - Decodes JSON into content\nfunc (pcd service) DecodeJSON(dec *json.Decoder) (interface{}, string, error) {\n\tc := content{}\n\terr := dec.Decode(&c)\n\treturn c, c.UUID, err\n\n}\n\n\/\/ Count - Returns a count of the number of content in this Neo instance\nfunc (pcd service) Count() (int, error) {\n\n\tresults := []struct {\n\t\tCount int `json:\"c\"`\n\t}{}\n\n\tquery := &neoism.CypherQuery{\n\t\tStatement: `MATCH (n:Content) return count(n) as c`,\n\t\tResult:    &results,\n\t}\n\n\terr := pcd.conn.CypherBatch([]*neoism.CypherQuery{query})\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn results[0].Count, nil\n}\n\n<commit_msg>Removed inline in return statement<commit_after>package content\n\nimport (\n\t\"encoding\/json\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com\/Financial-Times\/neo-utils-go\/neoutils\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/jmcvetta\/neoism\"\n)\n\nvar uuidExtractRegex = regexp.MustCompile(\".*\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$\")\n\n\/\/ CypherDriver - CypherDriver\ntype service struct {\n\tconn neoutils.NeoConnection\n}\n\n\/\/NewCypherDriver instantiate driver\nfunc NewCypherContentService(cypherRunner neoutils.NeoConnection) service {\n\treturn service{cypherRunner}\n}\n\n\/\/Initialise ensure constraint on content uuid\nfunc (cd service) Initialise() error {\n\n\treturn cd.conn.EnsureConstraints(map[string]string{\n\t\t\"Content\": \"uuid\"})\n}\n\n\/\/ Check - Feeds into the Healthcheck and checks whether we can connect to Neo and that the datastore isn't empty\nfunc (pcd service) Check() error {\n\treturn neoutils.Check(pcd.conn)\n}\n\n\/\/ Read - reads a content given a UUID\nfunc (pcd service) Read(uuid string) (interface{}, bool, error) {\n\tresults := []struct {\n\t\tcontent\n\t}{}\n\n\tquery := &neoism.CypherQuery{\n\t\tStatement: `MATCH (n:Content {uuid:{uuid}})\n\t\t\treturn n.uuid as uuid, n.title as title, n.publishedDate as publishedDate`,\n\t\tParameters: map[string]interface{}{\n\t\t\t\"uuid\": uuid,\n\t\t},\n\t\tResult: &results,\n\t}\n\n\terr := pcd.conn.CypherBatch([]*neoism.CypherQuery{query})\n\n\tif err != nil {\n\t\treturn content{}, false, err\n\t}\n\n\tif len(results) == 0 {\n\t\treturn content{}, false, nil\n\t}\n\n\tresult := results[0]\n\n\tcontentItem := content{\n\t\tUUID:          result.UUID,\n\t\tTitle:         result.Title,\n\t\tPublishedDate: result.PublishedDate,\n\t}\n\treturn contentItem, true, nil\n}\n\n\/\/Write - Writes a content node\nfunc (pcd service) Write(thing interface{}) error {\n\tc := thing.(content)\n\n\t\/\/ Only Articles have a body\n\tif c.Body == \"\" {\n\t\tlog.Infof(\"There is no body with this content item therefore assuming is it not an Article: %v\", c.UUID)\n\t\treturn nil\n\t}\n\n\tparams := map[string]interface{}{\n\t\t\"uuid\": c.UUID,\n\t}\n\n\tif c.Title != \"\" {\n\t\tparams[\"title\"] = c.Title\n\t\tparams[\"prefLabel\"] = c.Title\n\t}\n\n\tif c.PublishedDate != \"\" {\n\t\tparams[\"publishedDate\"] = c.PublishedDate\n\t\tdatetimeEpoch, err := time.Parse(time.RFC3339, c.PublishedDate)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tparams[\"publishedDateEpoch\"] = datetimeEpoch.Unix()\n\t}\n\n\tstatement := `MERGE (n:Thing {uuid: {uuid}})\n\t\t      set n={allprops}\n\t\t      set n :Content`\n\n\twriteContentQuery := &neoism.CypherQuery{\n\t\tStatement: statement,\n\t\tParameters: map[string]interface{}{\n\t\t\t\"uuid\":     c.UUID,\n\t\t\t\"allprops\": params,\n\t\t},\n\t}\n\n\treturn pcd.conn.CypherBatch([]*neoism.CypherQuery{writeContentQuery})\n}\n\n\/\/Delete - Deletes a content\nfunc (pcd service) Delete(uuid string) (bool, error) {\n\tclearNode := &neoism.CypherQuery{\n\t\tStatement: `\n\t\t\tMATCH (p:Thing {uuid: {uuid}})\n\t\t\tREMOVE p:Content\n\t\t\tSET p={props}\n\t\t`,\n\t\tParameters: map[string]interface{}{\n\t\t\t\"uuid\": uuid,\n\t\t\t\"props\": map[string]interface{}{\n\t\t\t\t\"uuid\": uuid,\n\t\t\t},\n\t\t},\n\t\tIncludeStats: true,\n\t}\n\n\tremoveNodeIfUnused := &neoism.CypherQuery{\n\t\tStatement: `\n\t\t\tMATCH (p:Thing {uuid: {uuid}})\n\t\t\tOPTIONAL MATCH (p)-[a]-(x)\n\t\t\tWITH p, count(a) AS relCount\n\t\t\tWHERE relCount = 0\n\t\t\tDELETE p\n\t\t`,\n\t\tParameters: map[string]interface{}{\n\t\t\t\"uuid\": uuid,\n\t\t},\n\t}\n\n\terr := pcd.conn.CypherBatch([]*neoism.CypherQuery{clearNode, removeNodeIfUnused})\n\n\ts1, err := clearNode.Stats()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tvar deleted bool\n\tif s1.ContainsUpdates && s1.LabelsRemoved > 0 {\n\t\tdeleted = true\n\t}\n\n\treturn deleted, err\n}\n\n\/\/ DecodeJSON - Decodes JSON into content\nfunc (pcd service) DecodeJSON(dec *json.Decoder) (interface{}, string, error) {\n\tc := content{}\n\terr := dec.Decode(&c)\n\treturn c, c.UUID, err\n\n}\n\n\/\/ Count - Returns a count of the number of content in this Neo instance\nfunc (pcd service) Count() (int, error) {\n\n\tresults := []struct {\n\t\tCount int `json:\"c\"`\n\t}{}\n\n\tquery := &neoism.CypherQuery{\n\t\tStatement: `MATCH (n:Content) return count(n) as c`,\n\t\tResult:    &results,\n\t}\n\n\terr := pcd.conn.CypherBatch([]*neoism.CypherQuery{query})\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn results[0].Count, nil\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package marathon\n\nimport (\n\t\"fmt\"\n\t\/\/\"log\"\n\t\"time\"\n\n\t\"github.com\/Banno\/go-marathon\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n\n\t\"testing\"\n)\n\nconst testAccCheckMarathonAppConfig_basic = `\nresource \"marathon_app\" \"app-create-example\" {\n\tname = \"\/app-create-example\"\n\n\tcmd = \"env && python3 -m http.server $PORT0\"\n\t\n\tcontainer {\n\t\ttype = \"DOCKER\"\n\t\tdocker {\n\t\t\timage = \"python:3\"\n                }\n\t}\n\n\tcpus = \"0.01\"\n\tinstances = 1\n\tmem = 100\n\n}\n`\n\nconst testAccCheckMarathonAppConfig_update = `\nresource \"marathon_app\" \"app-create-example\" {\n\tname = \"\/app-create-example\"\n\n\tcmd = \"env && python3 -m http.server $PORT0\"\n\t\n\tcontainer {\n\t\ttype = \"DOCKER\"\n\t\tdocker {\n\t\t\timage = \"python:3\"\n                }\n\t}\n\n\tcpus = \"0.01\"\n\tinstances = 2\n\tmem = 100\n\n}\n`\n\nfunc TestAccMarathonApp_basic(t *testing.T) {\n\n\tvar a marathon.App\n\n\ttestCheckCreate := func(app *marathon.App) resource.TestCheckFunc {\n\t\treturn func(s *terraform.State) error {\n\t\t\tif a.Version == \"\" {\n\t\t\t\treturn fmt.Errorf(\"Didn't return a version so something is broken: %#v\", app)\n\t\t\t}\n\t\t\tif a.Instances != 1 {\n\t\t\t\treturn fmt.Errorf(\"Wrong number of instances %#v\", app)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\ttestCheckUpdate := func(app *marathon.App) resource.TestCheckFunc {\n\t\treturn func(s *terraform.State) error {\n\t\t\tif a.Instances != 2 {\n\t\t\t\treturn fmt.Errorf(\"Wrong number of instances %#v\", app)\n\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:  func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\t\/\/\t\tCheckDestroy: testAccCheckMarathonAppDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccCheckMarathonAppConfig_basic,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccReadApp(\"marathon_app.app-create-example\", &a),\n\t\t\t\t\ttestCheckCreate(&a),\n\t\t\t\t),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccCheckMarathonAppConfig_update,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccReadApp(\"marathon_app.app-create-example\", &a),\n\t\t\t\t\ttestCheckUpdate(&a),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccReadApp(name string, app *marathon.App) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[name]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"marathon_app resource not found: %s\", name)\n\t\t}\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"marathon_app resource id not set correctly: %s\", name)\n\t\t}\n\n\t\t\/\/log.Printf(\"=== testAccContainerExists: rs ===\\n%#v\\n\", rs)\n\n\t\tclient := testAccProvider.Meta().(*marathon.Client)\n\n\t\tappRead, _ := client.AppRead(rs.Primary.Attributes[\"name\"])\n\n\t\t\/\/\t\tlog.Printf(\"=== testAccContainerExists: appRead ===\\n%#v\\n\", appRead)\n\n\t\ttime.Sleep(5000 * time.Millisecond)\n\n\t\t*app = *appRead\n\n\t\treturn nil\n\t}\n}\n\n\/*\nTODO: prove that this works\n\nfunc testAccCheckMarathonAppDestroy(s *terraform.State) error {\n\tclient := testAccProvider.Meta().(*marathon.Client)\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"marathon_app\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tclient.AppRead(\"\/test\")\n\n\t\t\/\/ make sure that it's properly destroyed\n\t}\n\n\treturn nil\n}\n*\/\n<commit_msg>Confirm deletion test passes now<commit_after>package marathon\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/Banno\/go-marathon\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n\n\t\"testing\"\n)\n\nconst testAccCheckMarathonAppConfig_basic = `\nresource \"marathon_app\" \"app-create-example\" {\n\tname = \"\/app-create-example\"\n\n\tcmd = \"env && python3 -m http.server $PORT0\"\n\t\n\tcontainer {\n\t\ttype = \"DOCKER\"\n\t\tdocker {\n\t\t\timage = \"python:3\"\n                }\n\t}\n\n\tcpus = \"0.01\"\n\tinstances = 1\n\tmem = 100\n\n}\n`\n\nconst testAccCheckMarathonAppConfig_update = `\nresource \"marathon_app\" \"app-create-example\" {\n\tname = \"\/app-create-example\"\n\n\tcmd = \"env && python3 -m http.server $PORT0\"\n\t\n\tcontainer {\n\t\ttype = \"DOCKER\"\n\t\tdocker {\n\t\t\timage = \"python:3\"\n                }\n\t}\n\n\tcpus = \"0.01\"\n\tinstances = 2\n\tmem = 100\n\n}\n`\n\nfunc TestAccMarathonApp_basic(t *testing.T) {\n\n\tvar a marathon.App\n\n\ttestCheckCreate := func(app *marathon.App) resource.TestCheckFunc {\n\t\treturn func(s *terraform.State) error {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tif a.Version == \"\" {\n\t\t\t\treturn fmt.Errorf(\"Didn't return a version so something is broken: %#v\", app)\n\t\t\t}\n\t\t\tif a.Instances != 1 {\n\t\t\t\treturn fmt.Errorf(\"AppCreate: Wrong number of instances %#v\", app)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\ttestCheckUpdate := func(app *marathon.App) resource.TestCheckFunc {\n\t\treturn func(s *terraform.State) error {\n\t\t\tif a.Instances != 2 {\n\t\t\t\treturn fmt.Errorf(\"AppUpdate: Wrong number of instances %#v\", app)\n\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckMarathonAppDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccCheckMarathonAppConfig_basic,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccReadApp(\"marathon_app.app-create-example\", &a),\n\t\t\t\t\ttestCheckCreate(&a),\n\t\t\t\t),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccCheckMarathonAppConfig_update,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccReadApp(\"marathon_app.app-create-example\", &a),\n\t\t\t\t\ttestCheckUpdate(&a),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccReadApp(name string, app *marathon.App) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[name]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"marathon_app resource not found: %s\", name)\n\t\t}\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"marathon_app resource id not set correctly: %s\", name)\n\t\t}\n\n\t\t\/\/log.Printf(\"=== testAccContainerExists: rs ===\\n%#v\\n\", rs)\n\n\t\tclient := testAccProvider.Meta().(*marathon.Client)\n\n\t\tappRead, _ := client.AppRead(rs.Primary.Attributes[\"name\"])\n\n\t\t\/\/\t\tlog.Printf(\"=== testAccContainerExists: appRead ===\\n%#v\\n\", appRead)\n\n\t\ttime.Sleep(5000 * time.Millisecond)\n\n\t\t*app = *appRead\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckMarathonAppDestroy(s *terraform.State) error {\n\n\tclient := testAccProvider.Meta().(*marathon.Client)\n\n\t_, err := client.AppRead(\"\/app-create-example\")\n\tif err == nil {\n\t\treturn fmt.Errorf(\"App not deleted! %#v\", err)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/docker\/docker\/api\/types\"\n\tflag \"github.com\/docker\/docker\/pkg\/mflag\"\n)\n\n\/\/ CmdInspect displays low-level information on one or more containers or images.\n\/\/\n\/\/ Usage: docker inspect [OPTIONS] CONTAINER|IMAGE [CONTAINER|IMAGE...]\n\nfunc (cli *DockerCli) CmdInspect(args ...string) error {\n\tcmd := cli.Subcmd(\"inspect\", \"CONTAINER|IMAGE [CONTAINER|IMAGE...]\", \"Return low-level information on a container or image\", true)\n\ttmplStr := cmd.String([]string{\"f\", \"#format\", \"-format\"}, \"\", \"Format the output using the given go template\")\n\tcmd.Require(flag.Min, 1)\n\n\tcmd.ParseFlags(args, true)\n\n\tvar tmpl *template.Template\n\tif *tmplStr != \"\" {\n\t\tvar err error\n\t\tif tmpl, err = template.New(\"\").Funcs(funcMap).Parse(*tmplStr); err != nil {\n\t\t\tfmt.Fprintf(cli.err, \"Template parsing error: %v\\n\", err)\n\t\t\treturn StatusError{StatusCode: 64,\n\t\t\t\tStatus: \"Template parsing error: \" + err.Error()}\n\t\t}\n\t}\n\n\tindented := new(bytes.Buffer)\n\tindented.WriteByte('[')\n\tstatus := 0\n\tisImage := false\n\n\tfor _, name := range cmd.Args() {\n\t\tobj, _, err := readBody(cli.call(\"GET\", \"\/containers\/\"+name+\"\/json\", nil, nil))\n\t\tif err != nil {\n\t\t\tobj, _, err = readBody(cli.call(\"GET\", \"\/images\/\"+name+\"\/json\", nil, nil))\n\t\t\tisImage = true\n\t\t\tif err != nil {\n\t\t\t\tif strings.Contains(err.Error(), \"No such\") {\n\t\t\t\t\tfmt.Fprintf(cli.err, \"Error: No such image or container: %s\\n\", name)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(cli.err, \"%s\", err)\n\t\t\t\t}\n\t\t\t\tstatus = 1\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif tmpl == nil {\n\t\t\tif err = json.Indent(indented, obj, \"\", \"    \"); err != nil {\n\t\t\t\tfmt.Fprintf(cli.err, \"%s\\n\", err)\n\t\t\t\tstatus = 1\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tdec := json.NewDecoder(bytes.NewReader(obj))\n\n\t\t\tif isImage {\n\t\t\t\tinspPtr := types.ImageInspect{}\n\t\t\t\tif err := dec.Decode(&inspPtr); err != nil {\n\t\t\t\t\tfmt.Fprintf(cli.err, \"%s\\n\", err)\n\t\t\t\t\tstatus = 1\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err := tmpl.Execute(cli.out, inspPtr); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tinspPtr := types.ContainerJSON{}\n\t\t\t\tif err := dec.Decode(&inspPtr); err != nil {\n\t\t\t\t\tfmt.Fprintf(cli.err, \"%s\\n\", err)\n\t\t\t\t\tstatus = 1\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err := tmpl.Execute(cli.out, inspPtr); err != nil {\n\t\t\t\t\treturn err\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tcli.out.Write([]byte{'\\n'})\n\t\t}\n\t\tindented.WriteString(\",\")\n\t}\n\n\tif indented.Len() > 1 {\n\t\t\/\/ Remove trailing ','\n\t\tindented.Truncate(indented.Len() - 1)\n\t}\n\tindented.WriteString(\"]\\n\")\n\n\tif tmpl == nil {\n\t\tif _, err := io.Copy(cli.out, indented); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif status != 0 {\n\t\treturn StatusError{StatusCode: status}\n\t}\n\treturn nil\n}\n<commit_msg>fix a minor inspect format issue<commit_after>package client\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/docker\/docker\/api\/types\"\n\tflag \"github.com\/docker\/docker\/pkg\/mflag\"\n)\n\n\/\/ CmdInspect displays low-level information on one or more containers or images.\n\/\/\n\/\/ Usage: docker inspect [OPTIONS] CONTAINER|IMAGE [CONTAINER|IMAGE...]\n\nfunc (cli *DockerCli) CmdInspect(args ...string) error {\n\tcmd := cli.Subcmd(\"inspect\", \"CONTAINER|IMAGE [CONTAINER|IMAGE...]\", \"Return low-level information on a container or image\", true)\n\ttmplStr := cmd.String([]string{\"f\", \"#format\", \"-format\"}, \"\", \"Format the output using the given go template\")\n\tcmd.Require(flag.Min, 1)\n\n\tcmd.ParseFlags(args, true)\n\n\tvar tmpl *template.Template\n\tif *tmplStr != \"\" {\n\t\tvar err error\n\t\tif tmpl, err = template.New(\"\").Funcs(funcMap).Parse(*tmplStr); err != nil {\n\t\t\tfmt.Fprintf(cli.err, \"Template parsing error: %v\\n\", err)\n\t\t\treturn StatusError{StatusCode: 64,\n\t\t\t\tStatus: \"Template parsing error: \" + err.Error()}\n\t\t}\n\t}\n\n\tindented := new(bytes.Buffer)\n\tindented.WriteString(\"[\\n\")\n\tstatus := 0\n\tisImage := false\n\n\tfor _, name := range cmd.Args() {\n\t\tobj, _, err := readBody(cli.call(\"GET\", \"\/containers\/\"+name+\"\/json\", nil, nil))\n\t\tif err != nil {\n\t\t\tobj, _, err = readBody(cli.call(\"GET\", \"\/images\/\"+name+\"\/json\", nil, nil))\n\t\t\tisImage = true\n\t\t\tif err != nil {\n\t\t\t\tif strings.Contains(err.Error(), \"No such\") {\n\t\t\t\t\tfmt.Fprintf(cli.err, \"Error: No such image or container: %s\\n\", name)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Fprintf(cli.err, \"%s\", err)\n\t\t\t\t}\n\t\t\t\tstatus = 1\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif tmpl == nil {\n\t\t\tif err = json.Indent(indented, obj, \"\", \"    \"); err != nil {\n\t\t\t\tfmt.Fprintf(cli.err, \"%s\\n\", err)\n\t\t\t\tstatus = 1\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tdec := json.NewDecoder(bytes.NewReader(obj))\n\n\t\t\tif isImage {\n\t\t\t\tinspPtr := types.ImageInspect{}\n\t\t\t\tif err := dec.Decode(&inspPtr); err != nil {\n\t\t\t\t\tfmt.Fprintf(cli.err, \"%s\\n\", err)\n\t\t\t\t\tstatus = 1\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err := tmpl.Execute(cli.out, inspPtr); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tinspPtr := types.ContainerJSON{}\n\t\t\t\tif err := dec.Decode(&inspPtr); err != nil {\n\t\t\t\t\tfmt.Fprintf(cli.err, \"%s\\n\", err)\n\t\t\t\t\tstatus = 1\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err := tmpl.Execute(cli.out, inspPtr); err != nil {\n\t\t\t\t\treturn err\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tcli.out.Write([]byte{'\\n'})\n\t\t}\n\t\tindented.WriteString(\",\")\n\t}\n\n\tif indented.Len() > 1 {\n\t\t\/\/ Remove trailing ','\n\t\tindented.Truncate(indented.Len() - 1)\n\t}\n\tindented.WriteString(\"]\\n\")\n\n\tif tmpl == nil {\n\t\tif _, err := io.Copy(cli.out, indented); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif status != 0 {\n\t\treturn StatusError{StatusCode: status}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tmaxRetryDuration = 5 * time.Minute\n)\n\n\/\/ Request is contructed iteratively by the client and finally dispatched.\n\/\/ A REST endpoint is accessed with the following convention:\n\/\/ base_url\/<version>\/<resource>\/[<instance>]\ntype Request struct {\n\tclient      *http.Client\n\tversion     string\n\tverb        string\n\tpath        string\n\tbase        *url.URL\n\tparams      url.Values\n\theaders     http.Header\n\tresource    string\n\tinstance    string\n\terr         error\n\tbody        []byte\n\treq         *http.Request\n\tresp        *http.Response\n\ttimeout     time.Duration\n\tauthstring  string\n\taccesstoken string\n}\n\n\/\/ Response is a representation of HTTP response received from the server.\ntype Response struct {\n\tstatus     string\n\tstatusCode int\n\terr        error\n\tbody       []byte\n}\n\n\/\/ Status upon error, attempts to parse the body of a response into a meaningful status.\ntype Status struct {\n\tMessage   string\n\tErrorCode int\n}\n\n\/\/ NewRequest instance\nfunc NewRequest(client *http.Client, base *url.URL, verb string, version string, authstring, userAgent string) *Request {\n\tr := &Request{\n\t\tclient:     client,\n\t\tverb:       verb,\n\t\tbase:       base,\n\t\tpath:       base.Path,\n\t\tversion:    version,\n\t\tauthstring: authstring,\n\t}\n\tr.SetHeader(\"User-Agent\", userAgent)\n\treturn r\n}\n\nfunc checkExists(mustExist string, before string) error {\n\tif len(mustExist) == 0 {\n\t\treturn fmt.Errorf(\"%q should be set before setting %q\", mustExist, before)\n\t}\n\treturn nil\n}\n\nfunc checkSet(name string, s *string, newval string) error {\n\tif len(*s) != 0 {\n\t\treturn fmt.Errorf(\"%q already set to %q, cannot change to %q\",\n\t\t\tname, *s, newval)\n\t}\n\t*s = newval\n\treturn nil\n}\n\n\/\/ Resource specifies the resource to be accessed.\nfunc (r *Request) Resource(resource string) *Request {\n\tif r.err == nil {\n\t\tr.err = checkSet(\"resource\", &r.resource, resource)\n\t}\n\treturn r\n}\n\n\/\/ Instance specifies the instance of the resource to be accessed.\nfunc (r *Request) Instance(instance string) *Request {\n\tif r.err == nil {\n\t\tr.err = checkExists(\"resource\", \"instance\")\n\t\tif r.err == nil {\n\t\t\tr.err = checkSet(\"instance\", &r.instance, instance)\n\t\t}\n\t}\n\treturn r\n}\n\n\/\/ UsePath use the specified path and don't build up a request.\nfunc (r *Request) UsePath(path string) *Request {\n\tif r.err == nil {\n\t\tr.err = checkSet(\"path\", &r.path, path)\n\t}\n\treturn r\n}\n\n\/\/ QueryOption adds specified options to query.\nfunc (r *Request) QueryOption(key string, value string) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tif r.params == nil {\n\t\tr.params = make(url.Values)\n\t}\n\tr.params.Add(string(key), value)\n\treturn r\n}\n\n\/\/ QueryOptionLabel adds specified label to query.\nfunc (r *Request) QueryOptionLabel(key string, labels map[string]string) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tif b, err := json.Marshal(labels); err != nil {\n\t\tr.err = err\n\t} else {\n\t\tif r.params == nil {\n\t\t\tr.params = make(url.Values)\n\t\t}\n\t\tr.params.Add(string(key), string(b))\n\t}\n\treturn r\n}\n\n\/\/ SetHeader adds specified header values to query.\nfunc (r *Request) SetHeader(key, value string) *Request {\n\tif r.headers == nil {\n\t\tr.headers = http.Header{}\n\t}\n\tr.headers.Set(key, value)\n\treturn r\n}\n\n\/\/ Timeout makes the request use the given duration as a timeout. Sets the \"timeout\"\n\/\/ parameter.\nfunc (r *Request) Timeout(d time.Duration) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tr.timeout = d\n\treturn r\n}\n\n\/\/ Body sets the request Body.\nfunc (r *Request) Body(v interface{}) *Request {\n\tvar err error\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tr.body, err = json.Marshal(v)\n\tif err != nil {\n\t\tr.err = err\n\t\treturn r\n\t}\n\treturn r\n}\n\n\/\/ URL returns the current working URL.\nfunc (r *Request) URL() *url.URL {\n\tu := *r.base\n\tp := r.path\n\n\tif len(r.version) != 0 {\n\t\tp = path.Join(p, strings.ToLower(r.version))\n\t}\n\tif len(r.resource) != 0 {\n\t\tp = path.Join(p, strings.ToLower(r.resource))\n\t\tif len(r.instance) != 0 {\n\t\t\tp = path.Join(p, r.instance)\n\t\t}\n\t}\n\n\tu.Path = p\n\n\tquery := url.Values{}\n\tfor key, values := range r.params {\n\t\tfor _, value := range values {\n\t\t\tquery.Add(key, value)\n\t\t}\n\t}\n\tif r.timeout != 0 {\n\t\tquery.Set(\"timeout\", r.timeout.String())\n\t}\n\tu.RawQuery = query.Encode()\n\treturn &u\n}\n\n\/\/ headerVal for key as an int. Return false if header is not present or valid.\nfunc headerVal(key string, resp *http.Response) (int, bool) {\n\tif h := resp.Header.Get(key); len(h) > 0 {\n\t\tif i, err := strconv.Atoi(h); err == nil {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn 0, false\n}\n\nfunc parseHTTPStatus(resp *http.Response, body []byte) error {\n\tif resp.StatusCode >= http.StatusOK &&\n\t\tresp.StatusCode <= http.StatusPartialContent {\n\t\t\/\/ Status is good and HTTP status is good, everything is good\n\t\treturn nil\n\t}\n\n\t\/\/ Get error from body if any\n\tif len(string(body)) != 0 {\n\t\treturn errors.New(string(body))\n\t}\n\n\t\/\/ If no error was in the body, return a generic one\n\treturn fmt.Errorf(\"HTTP error %d\", resp.StatusCode)\n}\n\n\/\/ Do executes the request and returns a Response.\n\/\/ Do executes the request and returns a Response.\nfunc (r *Request) Do() *Response {\n\tvar (\n\t\terr  error\n\t\treq  *http.Request\n\t\tresp *http.Response\n\t\turl  string\n\t\tbody []byte\n\t)\n\n\tif r.err != nil {\n\t\treturn &Response{err: r.err}\n\t}\n\turl = r.URL().String()\n\treq, err = http.NewRequest(r.verb, url, bytes.NewBuffer(r.body))\n\tif err != nil {\n\t\treturn &Response{err: err}\n\t}\n\tif r.headers == nil {\n\t\tr.headers = http.Header{}\n\t}\n\n\treq.Header = r.headers\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\treq.Header.Set(\"Date\", time.Now().String())\n\n\tif len(r.authstring) > 0 {\n\t\treq.Header.Set(\"Authorization\", \"Basic \"+r.authstring)\n\t}\n\n\tif len(r.accesstoken) > 0 {\n\t\treq.Header.Set(\"Access-Token\", r.accesstoken)\n\t}\n\n\tstart := time.Now()\n\tfor {\n\t\tif resp, err = r.client.Do(req); err != nil {\n\t\t\treturn &Response{err: err}\n\t\t}\n\n\t\tif time.Since(start) >= maxRetryDuration ||\n\t\t\tresp.StatusCode != http.StatusServiceUnavailable {\n\t\t\t\/\/ Server needs to set this header along with returning a 503\n\t\t\tbreak\n\t\t}\n\t\thandleServiceUnavailable(resp)\n\t}\n\n\tif resp.Body != nil {\n\t\tdefer resp.Body.Close()\n\t\tif body, err = ioutil.ReadAll(resp.Body); err != nil {\n\t\t\treturn &Response{err: err}\n\t\t}\n\t}\n\n\treturn &Response{\n\t\tstatus:     resp.Status,\n\t\tstatusCode: resp.StatusCode,\n\t\tbody:       body,\n\t\terr:        parseHTTPStatus(resp, body),\n\t}\n}\n\nfunc handleServiceUnavailable(resp *http.Response) {\n\tvar duration = time.Duration(1 * time.Second)\n\tif len(resp.Header[\"Retry-After\"]) > 0 {\n\t\tif retryafter, err := strconv.Atoi(resp.Header[\"Retry-After\"][0]); err == nil {\n\t\t\tduration = time.Duration(retryafter) * time.Second\n\t\t}\n\t}\n\n\ttime.Sleep(duration)\n}\n\n\/\/ Body return http body, valid only if there is no error\nfunc (r Response) Body() ([]byte, error) {\n\treturn r.body, r.err\n}\n\n\/\/ StatusCode HTTP status code returned.\nfunc (r Response) StatusCode() int {\n\treturn r.statusCode\n}\n\n\/\/ Unmarshal result into obj\nfunc (r Response) Unmarshal(v interface{}) error {\n\tif r.err != nil {\n\t\treturn r.err\n\t}\n\treturn json.Unmarshal(r.body, v)\n}\n\n\/\/ Error executing the request.\nfunc (r Response) Error() error {\n\treturn r.err\n}\n\n\/\/ FormatError formats the error\nfunc (r Response) FormatError() error {\n\tif len(r.body) == 0 {\n\t\treturn fmt.Errorf(\"Error: %v\", r.err)\n\t}\n\treturn fmt.Errorf(\"HTTP-%d: %s\", r.statusCode, string(r.body))\n}\n\nfunc digest(method string, path string) string {\n\tnow := time.Now().String()\n\n\ts1 := rand.NewSource(time.Now().UnixNano())\n\tr1 := rand.New(s1)\n\n\tnonce := r1.Intn(10)\n\n\treturn method + \"+\" + path + \"+\" + now + \"+\" + strconv.Itoa(nonce)\n}\n<commit_msg>Don't print HTTP status in error message<commit_after>package client\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tmaxRetryDuration = 5 * time.Minute\n)\n\n\/\/ Request is contructed iteratively by the client and finally dispatched.\n\/\/ A REST endpoint is accessed with the following convention:\n\/\/ base_url\/<version>\/<resource>\/[<instance>]\ntype Request struct {\n\tclient      *http.Client\n\tversion     string\n\tverb        string\n\tpath        string\n\tbase        *url.URL\n\tparams      url.Values\n\theaders     http.Header\n\tresource    string\n\tinstance    string\n\terr         error\n\tbody        []byte\n\treq         *http.Request\n\tresp        *http.Response\n\ttimeout     time.Duration\n\tauthstring  string\n\taccesstoken string\n}\n\n\/\/ Response is a representation of HTTP response received from the server.\ntype Response struct {\n\tstatus     string\n\tstatusCode int\n\terr        error\n\tbody       []byte\n}\n\n\/\/ Status upon error, attempts to parse the body of a response into a meaningful status.\ntype Status struct {\n\tMessage   string\n\tErrorCode int\n}\n\n\/\/ NewRequest instance\nfunc NewRequest(client *http.Client, base *url.URL, verb string, version string, authstring, userAgent string) *Request {\n\tr := &Request{\n\t\tclient:     client,\n\t\tverb:       verb,\n\t\tbase:       base,\n\t\tpath:       base.Path,\n\t\tversion:    version,\n\t\tauthstring: authstring,\n\t}\n\tr.SetHeader(\"User-Agent\", userAgent)\n\treturn r\n}\n\nfunc checkExists(mustExist string, before string) error {\n\tif len(mustExist) == 0 {\n\t\treturn fmt.Errorf(\"%q should be set before setting %q\", mustExist, before)\n\t}\n\treturn nil\n}\n\nfunc checkSet(name string, s *string, newval string) error {\n\tif len(*s) != 0 {\n\t\treturn fmt.Errorf(\"%q already set to %q, cannot change to %q\",\n\t\t\tname, *s, newval)\n\t}\n\t*s = newval\n\treturn nil\n}\n\n\/\/ Resource specifies the resource to be accessed.\nfunc (r *Request) Resource(resource string) *Request {\n\tif r.err == nil {\n\t\tr.err = checkSet(\"resource\", &r.resource, resource)\n\t}\n\treturn r\n}\n\n\/\/ Instance specifies the instance of the resource to be accessed.\nfunc (r *Request) Instance(instance string) *Request {\n\tif r.err == nil {\n\t\tr.err = checkExists(\"resource\", \"instance\")\n\t\tif r.err == nil {\n\t\t\tr.err = checkSet(\"instance\", &r.instance, instance)\n\t\t}\n\t}\n\treturn r\n}\n\n\/\/ UsePath use the specified path and don't build up a request.\nfunc (r *Request) UsePath(path string) *Request {\n\tif r.err == nil {\n\t\tr.err = checkSet(\"path\", &r.path, path)\n\t}\n\treturn r\n}\n\n\/\/ QueryOption adds specified options to query.\nfunc (r *Request) QueryOption(key string, value string) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tif r.params == nil {\n\t\tr.params = make(url.Values)\n\t}\n\tr.params.Add(string(key), value)\n\treturn r\n}\n\n\/\/ QueryOptionLabel adds specified label to query.\nfunc (r *Request) QueryOptionLabel(key string, labels map[string]string) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tif b, err := json.Marshal(labels); err != nil {\n\t\tr.err = err\n\t} else {\n\t\tif r.params == nil {\n\t\t\tr.params = make(url.Values)\n\t\t}\n\t\tr.params.Add(string(key), string(b))\n\t}\n\treturn r\n}\n\n\/\/ SetHeader adds specified header values to query.\nfunc (r *Request) SetHeader(key, value string) *Request {\n\tif r.headers == nil {\n\t\tr.headers = http.Header{}\n\t}\n\tr.headers.Set(key, value)\n\treturn r\n}\n\n\/\/ Timeout makes the request use the given duration as a timeout. Sets the \"timeout\"\n\/\/ parameter.\nfunc (r *Request) Timeout(d time.Duration) *Request {\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tr.timeout = d\n\treturn r\n}\n\n\/\/ Body sets the request Body.\nfunc (r *Request) Body(v interface{}) *Request {\n\tvar err error\n\tif r.err != nil {\n\t\treturn r\n\t}\n\tr.body, err = json.Marshal(v)\n\tif err != nil {\n\t\tr.err = err\n\t\treturn r\n\t}\n\treturn r\n}\n\n\/\/ URL returns the current working URL.\nfunc (r *Request) URL() *url.URL {\n\tu := *r.base\n\tp := r.path\n\n\tif len(r.version) != 0 {\n\t\tp = path.Join(p, strings.ToLower(r.version))\n\t}\n\tif len(r.resource) != 0 {\n\t\tp = path.Join(p, strings.ToLower(r.resource))\n\t\tif len(r.instance) != 0 {\n\t\t\tp = path.Join(p, r.instance)\n\t\t}\n\t}\n\n\tu.Path = p\n\n\tquery := url.Values{}\n\tfor key, values := range r.params {\n\t\tfor _, value := range values {\n\t\t\tquery.Add(key, value)\n\t\t}\n\t}\n\tif r.timeout != 0 {\n\t\tquery.Set(\"timeout\", r.timeout.String())\n\t}\n\tu.RawQuery = query.Encode()\n\treturn &u\n}\n\n\/\/ headerVal for key as an int. Return false if header is not present or valid.\nfunc headerVal(key string, resp *http.Response) (int, bool) {\n\tif h := resp.Header.Get(key); len(h) > 0 {\n\t\tif i, err := strconv.Atoi(h); err == nil {\n\t\t\treturn i, true\n\t\t}\n\t}\n\treturn 0, false\n}\n\nfunc parseHTTPStatus(resp *http.Response, body []byte) error {\n\tif resp.StatusCode >= http.StatusOK &&\n\t\tresp.StatusCode <= http.StatusPartialContent {\n\t\t\/\/ Status is good and HTTP status is good, everything is good\n\t\treturn nil\n\t}\n\n\t\/\/ Get error from body if any\n\tif len(string(body)) != 0 {\n\t\treturn errors.New(string(body))\n\t}\n\n\t\/\/ If no error was in the body, return a generic one\n\treturn fmt.Errorf(\"HTTP error %d\", resp.StatusCode)\n}\n\n\/\/ Do executes the request and returns a Response.\n\/\/ Do executes the request and returns a Response.\nfunc (r *Request) Do() *Response {\n\tvar (\n\t\terr  error\n\t\treq  *http.Request\n\t\tresp *http.Response\n\t\turl  string\n\t\tbody []byte\n\t)\n\n\tif r.err != nil {\n\t\treturn &Response{err: r.err}\n\t}\n\turl = r.URL().String()\n\treq, err = http.NewRequest(r.verb, url, bytes.NewBuffer(r.body))\n\tif err != nil {\n\t\treturn &Response{err: err}\n\t}\n\tif r.headers == nil {\n\t\tr.headers = http.Header{}\n\t}\n\n\treq.Header = r.headers\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\treq.Header.Set(\"Date\", time.Now().String())\n\n\tif len(r.authstring) > 0 {\n\t\treq.Header.Set(\"Authorization\", \"Basic \"+r.authstring)\n\t}\n\n\tif len(r.accesstoken) > 0 {\n\t\treq.Header.Set(\"Access-Token\", r.accesstoken)\n\t}\n\n\tstart := time.Now()\n\tfor {\n\t\tif resp, err = r.client.Do(req); err != nil {\n\t\t\treturn &Response{err: err}\n\t\t}\n\n\t\tif time.Since(start) >= maxRetryDuration ||\n\t\t\tresp.StatusCode != http.StatusServiceUnavailable {\n\t\t\t\/\/ Server needs to set this header along with returning a 503\n\t\t\tbreak\n\t\t}\n\t\thandleServiceUnavailable(resp)\n\t}\n\n\tif resp.Body != nil {\n\t\tdefer resp.Body.Close()\n\t\tif body, err = ioutil.ReadAll(resp.Body); err != nil {\n\t\t\treturn &Response{err: err}\n\t\t}\n\t}\n\n\treturn &Response{\n\t\tstatus:     resp.Status,\n\t\tstatusCode: resp.StatusCode,\n\t\tbody:       body,\n\t\terr:        parseHTTPStatus(resp, body),\n\t}\n}\n\nfunc handleServiceUnavailable(resp *http.Response) {\n\tvar duration = time.Duration(1 * time.Second)\n\tif len(resp.Header[\"Retry-After\"]) > 0 {\n\t\tif retryafter, err := strconv.Atoi(resp.Header[\"Retry-After\"][0]); err == nil {\n\t\t\tduration = time.Duration(retryafter) * time.Second\n\t\t}\n\t}\n\n\ttime.Sleep(duration)\n}\n\n\/\/ Body return http body, valid only if there is no error\nfunc (r Response) Body() ([]byte, error) {\n\treturn r.body, r.err\n}\n\n\/\/ StatusCode HTTP status code returned.\nfunc (r Response) StatusCode() int {\n\treturn r.statusCode\n}\n\n\/\/ Unmarshal result into obj\nfunc (r Response) Unmarshal(v interface{}) error {\n\tif r.err != nil {\n\t\treturn r.err\n\t}\n\treturn json.Unmarshal(r.body, v)\n}\n\n\/\/ Error executing the request.\nfunc (r Response) Error() error {\n\treturn r.err\n}\n\n\/\/ FormatError formats the error\nfunc (r Response) FormatError() error {\n\tif len(r.body) == 0 {\n\t\treturn fmt.Errorf(\"Error: %v\", r.err)\n\t}\n\treturn fmt.Errorf(\"%v\", strings.TrimSpace(string(r.body)))\n}\n\nfunc digest(method string, path string) string {\n\tnow := time.Now().String()\n\n\ts1 := rand.NewSource(time.Now().UnixNano())\n\tr1 := rand.New(s1)\n\n\tnonce := r1.Intn(10)\n\n\treturn method + \"+\" + path + \"+\" + now + \"+\" + strconv.Itoa(nonce)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ NOTE: Subject to change, do not rely on this package from outside git-lfs source\npackage api\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"github.com\/git-lfs\/git-lfs\/auth\"\n\t\"github.com\/git-lfs\/git-lfs\/config\"\n\t\"github.com\/git-lfs\/git-lfs\/httputil\"\n)\n\nvar (\n\t\/\/ ErrNoOperationGiven is an error which is returned when no operation\n\t\/\/ is provided in a RequestSchema object.\n\tErrNoOperationGiven = errors.New(\"lfs\/api: no operation provided in schema\")\n)\n\n\/\/ HttpLifecycle serves as the default implementation of the Lifecycle interface\n\/\/ for HTTP requests. Internally, it leverages the *http.Client type to execute\n\/\/ HTTP requests against a root *url.URL, as given in `NewHttpLifecycle`.\ntype HttpLifecycle struct {\n\tcfg *config.Configuration\n}\n\nvar _ Lifecycle = new(HttpLifecycle)\n\n\/\/ NewHttpLifecycle initializes a new instance of the *HttpLifecycle type with a\n\/\/ new *http.Client, and the given root (see above).\n\/\/ Passing a nil Configuration will use the global config\nfunc NewHttpLifecycle(cfg *config.Configuration) *HttpLifecycle {\n\tif cfg == nil {\n\t\tcfg = config.Config\n\t}\n\treturn &HttpLifecycle{\n\t\tcfg: cfg,\n\t}\n}\n\n\/\/ Build implements the Lifecycle.Build function.\n\/\/\n\/\/ HttpLifecycle in particular, builds an absolute path by parsing and then\n\/\/ relativizing the `schema.Path` with respsect to the `HttpLifecycle.root`. If\n\/\/ there was an error in determining this URL, then that error will be returned,\n\/\/\n\/\/ After this is complete, a body is attached to the request if the\n\/\/ schema contained one. If a body was present, and there an error occurred while\n\/\/ serializing it into JSON, then that error will be returned and the\n\/\/ *http.Request will not be generated.\n\/\/\n\/\/ In all cases, credentials are attached to the HTTP request as described in\n\/\/ the `auth` package (see github.com\/git-lfs\/git-lfs\/auth#GetCreds).\n\/\/\n\/\/ Finally, all of these components are combined together and the resulting\n\/\/ request is returned.\nfunc (l *HttpLifecycle) Build(schema *RequestSchema) (*http.Request, error) {\n\tpath, err := l.absolutePath(schema.Operation, schema.Path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := l.body(schema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(schema.Method, path.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err = auth.GetCreds(l.cfg, req); err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.URL.RawQuery = l.queryParameters(schema).Encode()\n\n\treturn req, nil\n}\n\n\/\/ Execute implements the Lifecycle.Execute function.\n\/\/\n\/\/ Internally, the *http.Client is used to execute the underlying *http.Request.\n\/\/ If the client returned an error corresponding to a failure to make the\n\/\/ request, then that error will be returned immediately, and the response is\n\/\/ guaranteed not to be serialized.\n\/\/\n\/\/ Once the response has been gathered from the server, it is unmarshled into\n\/\/ the given `into interface{}` which is identical to the one provided in the\n\/\/ original RequestSchema. If an error occured while decoding, then that error\n\/\/ is returned.\n\/\/\n\/\/ Otherwise, the api.Response is returned, along with no error, signaling that\n\/\/ the request completed successfully.\nfunc (l *HttpLifecycle) Execute(req *http.Request, into interface{}) (Response, error) {\n\tresp, err := httputil.DoHttpRequestWithRedirects(l.cfg, req, []*http.Request{}, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ TODO(taylor): check status >=500, handle content type, return error,\n\t\/\/ halt immediately.\n\n\tif into != nil {\n\t\tdecoder := json.NewDecoder(resp.Body)\n\t\tif err = decoder.Decode(into); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn WrapHttpResponse(resp), nil\n}\n\n\/\/ Cleanup implements the Lifecycle.Cleanup function by closing the Body\n\/\/ attached to the response.\nfunc (l *HttpLifecycle) Cleanup(resp Response) error {\n\treturn resp.Body().Close()\n}\n\n\/\/ absolutePath returns the absolute path made by combining a given relative\n\/\/ path with the root URL of the endpoint corresponding to the given operation.\n\/\/\n\/\/ If there was an error in parsing the relative path, then that error will be\n\/\/ returned.\nfunc (l *HttpLifecycle) absolutePath(operation Operation, path string) (*url.URL, error) {\n\tif len(operation) == 0 {\n\t\treturn nil, ErrNoOperationGiven\n\t}\n\n\troot, err := url.Parse(l.cfg.Endpoint(string(operation)).Url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trel, err := url.Parse(path)\n\tif err != nil {\n\t\treturn nil, err\n\n\t}\n\n\treturn root.ResolveReference(rel), nil\n}\n\n\/\/ body returns an io.Reader which reads out a JSON-encoded copy of the payload\n\/\/ attached to a given *RequestSchema, if it is present. If no body is present\n\/\/ in the request, then nil is returned instead.\n\/\/\n\/\/ If an error was encountered while attempting to marshal the body, then that\n\/\/ will be returned instead, along with a nil io.Reader.\nfunc (l *HttpLifecycle) body(schema *RequestSchema) (io.ReadCloser, error) {\n\tif schema.Body == nil {\n\t\treturn nil, nil\n\t}\n\n\tbody, err := json.Marshal(schema.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ioutil.NopCloser(bytes.NewReader(body)), nil\n}\n\n\/\/ queryParameters returns a url.Values containing all of the provided query\n\/\/ parameters as given in the *RequestSchema. If no query parameters were given,\n\/\/ then an empty url.Values is returned instead.\nfunc (l *HttpLifecycle) queryParameters(schema *RequestSchema) url.Values {\n\tvals := url.Values{}\n\tif schema.Query != nil {\n\t\tfor k, v := range schema.Query {\n\t\t\tvals.Add(k, v)\n\t\t}\n\t}\n\n\treturn vals\n}\n<commit_msg>api: simpler path join<commit_after>\/\/ NOTE: Subject to change, do not rely on this package from outside git-lfs source\npackage api\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"path\"\n\n\t\"github.com\/git-lfs\/git-lfs\/auth\"\n\t\"github.com\/git-lfs\/git-lfs\/config\"\n\t\"github.com\/git-lfs\/git-lfs\/httputil\"\n)\n\nvar (\n\t\/\/ ErrNoOperationGiven is an error which is returned when no operation\n\t\/\/ is provided in a RequestSchema object.\n\tErrNoOperationGiven = errors.New(\"lfs\/api: no operation provided in schema\")\n)\n\n\/\/ HttpLifecycle serves as the default implementation of the Lifecycle interface\n\/\/ for HTTP requests. Internally, it leverages the *http.Client type to execute\n\/\/ HTTP requests against a root *url.URL, as given in `NewHttpLifecycle`.\ntype HttpLifecycle struct {\n\tcfg *config.Configuration\n}\n\nvar _ Lifecycle = new(HttpLifecycle)\n\n\/\/ NewHttpLifecycle initializes a new instance of the *HttpLifecycle type with a\n\/\/ new *http.Client, and the given root (see above).\n\/\/ Passing a nil Configuration will use the global config\nfunc NewHttpLifecycle(cfg *config.Configuration) *HttpLifecycle {\n\tif cfg == nil {\n\t\tcfg = config.Config\n\t}\n\treturn &HttpLifecycle{\n\t\tcfg: cfg,\n\t}\n}\n\n\/\/ Build implements the Lifecycle.Build function.\n\/\/\n\/\/ HttpLifecycle in particular, builds an absolute path by parsing and then\n\/\/ relativizing the `schema.Path` with respsect to the `HttpLifecycle.root`. If\n\/\/ there was an error in determining this URL, then that error will be returned,\n\/\/\n\/\/ After this is complete, a body is attached to the request if the\n\/\/ schema contained one. If a body was present, and there an error occurred while\n\/\/ serializing it into JSON, then that error will be returned and the\n\/\/ *http.Request will not be generated.\n\/\/\n\/\/ In all cases, credentials are attached to the HTTP request as described in\n\/\/ the `auth` package (see github.com\/git-lfs\/git-lfs\/auth#GetCreds).\n\/\/\n\/\/ Finally, all of these components are combined together and the resulting\n\/\/ request is returned.\nfunc (l *HttpLifecycle) Build(schema *RequestSchema) (*http.Request, error) {\n\tpath, err := l.absolutePath(schema.Operation, schema.Path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := l.body(schema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(schema.Method, path.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err = auth.GetCreds(l.cfg, req); err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.URL.RawQuery = l.queryParameters(schema).Encode()\n\n\treturn req, nil\n}\n\n\/\/ Execute implements the Lifecycle.Execute function.\n\/\/\n\/\/ Internally, the *http.Client is used to execute the underlying *http.Request.\n\/\/ If the client returned an error corresponding to a failure to make the\n\/\/ request, then that error will be returned immediately, and the response is\n\/\/ guaranteed not to be serialized.\n\/\/\n\/\/ Once the response has been gathered from the server, it is unmarshled into\n\/\/ the given `into interface{}` which is identical to the one provided in the\n\/\/ original RequestSchema. If an error occured while decoding, then that error\n\/\/ is returned.\n\/\/\n\/\/ Otherwise, the api.Response is returned, along with no error, signaling that\n\/\/ the request completed successfully.\nfunc (l *HttpLifecycle) Execute(req *http.Request, into interface{}) (Response, error) {\n\tresp, err := httputil.DoHttpRequestWithRedirects(l.cfg, req, []*http.Request{}, true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ TODO(taylor): check status >=500, handle content type, return error,\n\t\/\/ halt immediately.\n\n\tif into != nil {\n\t\tdecoder := json.NewDecoder(resp.Body)\n\t\tif err = decoder.Decode(into); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn WrapHttpResponse(resp), nil\n}\n\n\/\/ Cleanup implements the Lifecycle.Cleanup function by closing the Body\n\/\/ attached to the response.\nfunc (l *HttpLifecycle) Cleanup(resp Response) error {\n\treturn resp.Body().Close()\n}\n\n\/\/ absolutePath returns the absolute path made by combining a given relative\n\/\/ path with the root URL of the endpoint corresponding to the given operation.\n\/\/\n\/\/ If there was an error in parsing the relative path, then that error will be\n\/\/ returned.\nfunc (l *HttpLifecycle) absolutePath(operation Operation, relpath string) (*url.URL, error) {\n\tif len(operation) == 0 {\n\t\treturn nil, ErrNoOperationGiven\n\t}\n\n\troot, err := url.Parse(l.cfg.Endpoint(string(operation)).Url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\troot.Path = path.Join(root.Path, relpath)\n\treturn root, nil\n}\n\n\/\/ body returns an io.Reader which reads out a JSON-encoded copy of the payload\n\/\/ attached to a given *RequestSchema, if it is present. If no body is present\n\/\/ in the request, then nil is returned instead.\n\/\/\n\/\/ If an error was encountered while attempting to marshal the body, then that\n\/\/ will be returned instead, along with a nil io.Reader.\nfunc (l *HttpLifecycle) body(schema *RequestSchema) (io.ReadCloser, error) {\n\tif schema.Body == nil {\n\t\treturn nil, nil\n\t}\n\n\tbody, err := json.Marshal(schema.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ioutil.NopCloser(bytes.NewReader(body)), nil\n}\n\n\/\/ queryParameters returns a url.Values containing all of the provided query\n\/\/ parameters as given in the *RequestSchema. If no query parameters were given,\n\/\/ then an empty url.Values is returned instead.\nfunc (l *HttpLifecycle) queryParameters(schema *RequestSchema) url.Values {\n\tvals := url.Values{}\n\tif schema.Query != nil {\n\t\tfor k, v := range schema.Query {\n\t\t\tvals.Add(k, v)\n\t\t}\n\t}\n\n\treturn vals\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Data functions *\/\n\n\/*\n * Copyright (c) 2013, Jeremy Bingham (<jbingham@gmail.com>)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage main\n\nimport (\n\t\"net\/http\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/ctdk\/goiardi\/data_bag\"\n\t\"github.com\/ctdk\/goiardi\/util\"\n)\n\nfunc data_handler(w http.ResponseWriter, r *http.Request){\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\n\tpath_array := SplitPath(r.URL.Path)\n\n\tdb_response := make(map[string]interface{})\n\tif len(path_array) == 1 {\n\t\t\/* Either a list of data bags, or a POST to create a new one *\/\n\t\tswitch r.Method {\n\t\t\tcase \"GET\":\n\t\t\t\t\/* The list *\/\n\t\t\t\tdb_list := data_bag.GetList()\n\t\t\t\tfor _, k := range db_list {\n\t\t\t\t\titem_url := fmt.Sprintf(\"\/data\/%s\", k)\n\t\t\t\t\tdb_response[k] = util.CustomURL(item_url)\n\t\t\t\t}\n\t\t\tcase \"POST\":\n\t\t\t\tdb_data, jerr := ParseObjJson(r.Body)\n\t\t\t\tif jerr != nil {\n\t\t\t\t\tJsonErrorReport(w, r, jerr.Error(), http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t\/* check that the name exists *\/\n\t\t\t\tswitch t := db_data[\"name\"].(type) {\n\t\t\t\t\tcase string:\n\t\t\t\t\t\tif t == \"\" {\n\t\t\t\t\t\t\tJsonErrorReport(w, r, \"Field 'name' missing\", http.StatusBadRequest)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tJsonErrorReport(w, r, \"Field 'name' missing\", http.StatusBadRequest)\n\t\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tchef_dbag, _ := data_bag.Get(db_data[\"name\"].(string))\n\t\t\t\tif chef_dbag != nil {\n\t\t\t\t\thttperr := fmt.Errorf(\"Data bag %s already exists.\", db_data[\"name\"].(string))\n\t\t\t\t\tJsonErrorReport(w, r, httperr.Error(), http.StatusConflict)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tchef_dbag, nerr := data_bag.New(db_data[\"name\"].(string))\n\t\t\t\tif nerr != nil {\n\t\t\t\t\tJsonErrorReport(w, r, nerr.Error(), nerr.Status())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tchef_dbag.Save()\n\t\t\t\tdb_response[\"uri\"] = util.ObjURL(chef_dbag)\n\t\t\t\tw.WriteHeader(http.StatusCreated)\n\t\t\tdefault:\n\t\t\t\t\/* The chef-pedant spec wants this response for\n\t\t\t\t * some reason. Mix it up, I guess. *\/\n\t\t\t\tJsonErrorReport(w, r, \"GET, PUT\", http.StatusMethodNotAllowed)\n\t\t\t\treturn\n\t\t}\n\t} else { \n\t\tdb_name := path_array[1]\n\n\t\t\/* chef-pedant is unhappy about not reporting the HTTP status\n\t\t * as 404 by fetching the data bag before we see if the method\n\t\t * is allowed, so do a quick check for that here. *\/\n\t\tif (len(path_array) == 2  && r.Method == \"PUT\") || (len(path_array) == 3 && r.Method == \"POST\"){\n\t\t\tJsonErrorReport(w, r, \"Method not allowed\", http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\t\tchef_dbag, err := data_bag.Get(db_name)\n\t\tif err != nil {\n\t\t\tvar err_msg string\n\t\t\tstatus := err.Status()\n\t\t\tif r.Method == \"POST\" {\n\t\t\t\t\/* Posts get a special snowflake message *\/\n\t\t\t\terr_msg = fmt.Sprintf(\"No data bag '%s' could be found. Please create this data bag before adding items to it.\", db_name)\n\t\t\t} else {\n\t\t\t\tif len(path_array) == 3 {\n\t\t\t\t\t\/* This is nuts. *\/\n\t\t\t\t\tif r.Method == \"DELETE\" {\n\t\t\t\t\t\terr_msg = fmt.Sprintf(\"Cannot load data bag %s item %s\", db_name, path_array[2])\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr_msg = fmt.Sprintf(\"Cannot load data bag item %s for data bag %s\", path_array[2], db_name)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\terr_msg = err.Error()\n\t\t\t\t}\n\t\t\t}\n\t\t\tJsonErrorReport(w, r, err_msg, status)\n\t\t\treturn\n\t\t}\n\t\tif len(path_array) == 2 {\n\t\t\t\/* getting list of data bag items and creating data bag\n\t\t\t * items. *\/\n\t\t\tswitch r.Method {\n\t\t\t\tcase \"GET\":\n\t\t\t\t\tfor k, _ := range chef_dbag.DataBagItems {\n\t\t\t\t\t\tdb_response[k] = util.CustomObjURL(chef_dbag, k)\n\t\t\t\t\t}\n\t\t\t\tcase \"DELETE\":\n\t\t\t\t\t\/* The chef API docs don't say anything\n\t\t\t\t\t * about this existing, but it does,\n\t\t\t\t\t * and without it you can't delete data\n\t\t\t\t\t * bags at all. *\/\n\t\t\t\t\tdb_response[\"chef_type\"] = \"data_bag\"\n\t\t\t\t\tdb_response[\"json_class\"] = \"Chef::DataBag\"\n\t\t\t\t\tdb_response[\"name\"] = chef_dbag.Name\n\t\t\t\t\terr := chef_dbag.Delete()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tJsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\tcase \"POST\":\n\t\t\t\t\traw_data := data_bag.RawDataBagJson(r.Body)\n\t\t\t\t\tdbitem, nerr := chef_dbag.NewDBItem(raw_data)\n\t\t\t\t\tif nerr != nil {\n\t\t\t\t\t\tJsonErrorReport(w, r, nerr.Error(), nerr.Status())\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t\/* The data bag return values are all\n\t\t\t\t\t * kinds of weird. Sometimes it sends\n\t\t\t\t\t * just the raw data, sometimes it sends\n\t\t\t\t\t * the whole object, sometimes a special\n\t\t\t\t\t * snowflake version. Ugh. *\/\n\t\t\t\t\tdb_response = dbitem.RawData\n\t\t\t\t\t\/\/db_response[\"data_bag\"] = dbitem.DataBagName\n\t\t\t\t\t\/\/db_response[\"chef_type\"] = dbitem.ChefType\n\t\t\t\t\tw.WriteHeader(http.StatusCreated)\n\t\t\t\tdefault:\n\t\t\t\t\tJsonErrorReport(w, r, \"GET, DELETE, POST\", http.StatusMethodNotAllowed)\n\t\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t\/* getting, editing, and deleting existing data bag items. *\/\n\t\t\tdb_item_name := path_array[2]\n\t\t\tif _, ok := chef_dbag.DataBagItems[db_item_name]; !ok {\n\t\t\t\tvar httperr string\n\t\t\t\tif r.Method != \"DELETE\" {\n\t\t\t\t\thttperr = fmt.Sprintf(\"Cannot load data bag item %s for data bag %s\", db_item_name, chef_dbag.Name)\n\t\t\t\t} else {\n\t\t\t\t\thttperr = fmt.Sprintf(\"Cannot load data bag %s item %s\", chef_dbag.Name, db_item_name)\n\t\t\t\t}\n\t\t\t\tJsonErrorReport(w, r, httperr, http.StatusNotFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tswitch r.Method {\n\t\t\t\tcase \"GET\":\n\t\t\t\t\tdb_response = chef_dbag.DataBagItems[db_item_name].RawData\n\t\t\t\tcase \"DELETE\":\n\t\t\t\t\tdbi := chef_dbag.DataBagItems[db_item_name]\n\t\t\t\t\t\/* Gotta short circuit this *\/\n\t\t\t\t\tenc := json.NewEncoder(w)\n\t\t\t\t\tif err := enc.Encode(&dbi); err != nil {\n\t\t\t\t\t\tJsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\terr := chef_dbag.DeleteDBItem(db_item_name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tJsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\tcase \"PUT\":\n\t\t\t\t\traw_data := data_bag.RawDataBagJson(r.Body)\n\t\t\t\t\tdbitem, err := chef_dbag.UpdateDBItem(db_item_name, raw_data)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tJsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t\/* Another weird data bag item response\n\t\t\t\t\t * which isn't at all unusual. *\/\n\t\t\t\t\tdb_response = dbitem.RawData\n\t\t\t\t\tdb_response[\"data_bag\"] = dbitem.DataBagName\n\t\t\t\t\tdb_response[\"chef_type\"] = dbitem.ChefType\n\t\t\t\t\tdb_response[\"id\"] = db_item_name\n\t\t\t\tdefault:\n\t\t\t\t\tJsonErrorReport(w, r, \"GET, DELETE, PUT\", http.StatusMethodNotAllowed)\n\t\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tenc := json.NewEncoder(w)\n\tif err := enc.Encode(&db_response); err != nil {\n\t\tJsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\n\n<commit_msg>Data Bag tests now passing except for perms, max allowed size payloads still being touchy, and some really picky 'method not allowed' tests.<commit_after>\/* Data functions *\/\n\n\/*\n * Copyright (c) 2013, Jeremy Bingham (<jbingham@gmail.com>)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage main\n\nimport (\n\t\"net\/http\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/ctdk\/goiardi\/data_bag\"\n\t\"github.com\/ctdk\/goiardi\/util\"\n)\n\nfunc data_handler(w http.ResponseWriter, r *http.Request){\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\n\tpath_array := SplitPath(r.URL.Path)\n\n\tdb_response := make(map[string]interface{})\n\tif len(path_array) == 1 {\n\t\t\/* Either a list of data bags, or a POST to create a new one *\/\n\t\tswitch r.Method {\n\t\t\tcase \"GET\":\n\t\t\t\t\/* The list *\/\n\t\t\t\tdb_list := data_bag.GetList()\n\t\t\t\tfor _, k := range db_list {\n\t\t\t\t\titem_url := fmt.Sprintf(\"\/data\/%s\", k)\n\t\t\t\t\tdb_response[k] = util.CustomURL(item_url)\n\t\t\t\t}\n\t\t\tcase \"POST\":\n\t\t\t\tdb_data, jerr := ParseObjJson(r.Body)\n\t\t\t\tif jerr != nil {\n\t\t\t\t\tJsonErrorReport(w, r, jerr.Error(), http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t\/* check that the name exists *\/\n\t\t\t\tswitch t := db_data[\"name\"].(type) {\n\t\t\t\t\tcase string:\n\t\t\t\t\t\tif t == \"\" {\n\t\t\t\t\t\t\tJsonErrorReport(w, r, \"Field 'name' missing\", http.StatusBadRequest)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tJsonErrorReport(w, r, \"Field 'name' missing\", http.StatusBadRequest)\n\t\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tchef_dbag, _ := data_bag.Get(db_data[\"name\"].(string))\n\t\t\t\tif chef_dbag != nil {\n\t\t\t\t\thttperr := fmt.Errorf(\"Data bag %s already exists.\", db_data[\"name\"].(string))\n\t\t\t\t\tJsonErrorReport(w, r, httperr.Error(), http.StatusConflict)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tchef_dbag, nerr := data_bag.New(db_data[\"name\"].(string))\n\t\t\t\tif nerr != nil {\n\t\t\t\t\tJsonErrorReport(w, r, nerr.Error(), nerr.Status())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tchef_dbag.Save()\n\t\t\t\tdb_response[\"uri\"] = util.ObjURL(chef_dbag)\n\t\t\t\tw.WriteHeader(http.StatusCreated)\n\t\t\tdefault:\n\t\t\t\t\/* The chef-pedant spec wants this response for\n\t\t\t\t * some reason. Mix it up, I guess. *\/\n\t\t\t\tJsonErrorReport(w, r, \"GET, PUT\", http.StatusMethodNotAllowed)\n\t\t\t\treturn\n\t\t}\n\t} else { \n\t\tdb_name := path_array[1]\n\n\t\t\/* chef-pedant is unhappy about not reporting the HTTP status\n\t\t * as 404 by fetching the data bag before we see if the method\n\t\t * is allowed, so do a quick check for that here. *\/\n\t\tif (len(path_array) == 2  && r.Method == \"PUT\") || (len(path_array) == 3 && r.Method == \"POST\"){\n\t\t\tJsonErrorReport(w, r, \"Method not allowed\", http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\t\tchef_dbag, err := data_bag.Get(db_name)\n\t\tif err != nil {\n\t\t\tvar err_msg string\n\t\t\tstatus := err.Status()\n\t\t\tif r.Method == \"POST\" {\n\t\t\t\t\/* Posts get a special snowflake message *\/\n\t\t\t\terr_msg = fmt.Sprintf(\"No data bag '%s' could be found. Please create this data bag before adding items to it.\", db_name)\n\t\t\t} else {\n\t\t\t\tif len(path_array) == 3 {\n\t\t\t\t\t\/* This is nuts. *\/\n\t\t\t\t\tif r.Method == \"DELETE\" {\n\t\t\t\t\t\terr_msg = fmt.Sprintf(\"Cannot load data bag %s item %s\", db_name, path_array[2])\n\t\t\t\t\t} else {\n\t\t\t\t\t\terr_msg = fmt.Sprintf(\"Cannot load data bag item %s for data bag %s\", path_array[2], db_name)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\terr_msg = err.Error()\n\t\t\t\t}\n\t\t\t}\n\t\t\tJsonErrorReport(w, r, err_msg, status)\n\t\t\treturn\n\t\t}\n\t\tif len(path_array) == 2 {\n\t\t\t\/* getting list of data bag items and creating data bag\n\t\t\t * items. *\/\n\t\t\tswitch r.Method {\n\t\t\t\tcase \"GET\":\n\t\t\t\t\tfor k, _ := range chef_dbag.DataBagItems {\n\t\t\t\t\t\tdb_response[k] = util.CustomObjURL(chef_dbag, k)\n\t\t\t\t\t}\n\t\t\t\tcase \"DELETE\":\n\t\t\t\t\t\/* The chef API docs don't say anything\n\t\t\t\t\t * about this existing, but it does,\n\t\t\t\t\t * and without it you can't delete data\n\t\t\t\t\t * bags at all. *\/\n\t\t\t\t\tdb_response[\"chef_type\"] = \"data_bag\"\n\t\t\t\t\tdb_response[\"json_class\"] = \"Chef::DataBag\"\n\t\t\t\t\tdb_response[\"name\"] = chef_dbag.Name\n\t\t\t\t\terr := chef_dbag.Delete()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tJsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\tcase \"POST\":\n\t\t\t\t\traw_data := data_bag.RawDataBagJson(r.Body)\n\t\t\t\t\tdbitem, nerr := chef_dbag.NewDBItem(raw_data)\n\t\t\t\t\tif nerr != nil {\n\t\t\t\t\t\tJsonErrorReport(w, r, nerr.Error(), nerr.Status())\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t\/* The data bag return values are all\n\t\t\t\t\t * kinds of weird. Sometimes it sends\n\t\t\t\t\t * just the raw data, sometimes it sends\n\t\t\t\t\t * the whole object, sometimes a special\n\t\t\t\t\t * snowflake version. Ugh. Have to loop\n\t\t\t\t\t * through to avoid updating the pointer\n\t\t\t\t\t * in the cache by just assigning\n\t\t\t\t\t * dbitem.RawData to db_response. Urk.\n\t\t\t\t\t *\/\n\t\t\t\t\tfor k, v := range dbitem.RawData {\n\t\t\t\t\t\tdb_response[k] = v\n\t\t\t\t\t}\n\t\t\t\t\tdb_response[\"data_bag\"] = dbitem.DataBagName\n\t\t\t\t\tdb_response[\"chef_type\"] = dbitem.ChefType\n\t\t\t\t\tw.WriteHeader(http.StatusCreated)\n\t\t\t\tdefault:\n\t\t\t\t\tJsonErrorReport(w, r, \"GET, DELETE, POST\", http.StatusMethodNotAllowed)\n\t\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\t\/* getting, editing, and deleting existing data bag items. *\/\n\t\t\tdb_item_name := path_array[2]\n\t\t\tif _, ok := chef_dbag.DataBagItems[db_item_name]; !ok {\n\t\t\t\tvar httperr string\n\t\t\t\tif r.Method != \"DELETE\" {\n\t\t\t\t\thttperr = fmt.Sprintf(\"Cannot load data bag item %s for data bag %s\", db_item_name, chef_dbag.Name)\n\t\t\t\t} else {\n\t\t\t\t\thttperr = fmt.Sprintf(\"Cannot load data bag %s item %s\", chef_dbag.Name, db_item_name)\n\t\t\t\t}\n\t\t\t\tJsonErrorReport(w, r, httperr, http.StatusNotFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tswitch r.Method {\n\t\t\t\tcase \"GET\":\n\t\t\t\t\tdb_response = chef_dbag.DataBagItems[db_item_name].RawData\n\t\t\t\tcase \"DELETE\":\n\t\t\t\t\tdbi := chef_dbag.DataBagItems[db_item_name]\n\t\t\t\t\t\/* Gotta short circuit this *\/\n\t\t\t\t\tenc := json.NewEncoder(w)\n\t\t\t\t\tif err := enc.Encode(&dbi); err != nil {\n\t\t\t\t\t\tJsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\terr := chef_dbag.DeleteDBItem(db_item_name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tJsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\tcase \"PUT\":\n\t\t\t\t\traw_data := data_bag.RawDataBagJson(r.Body)\n\t\t\t\t\tif raw_id, ok := raw_data[\"id\"]; ok {\n\t\t\t\t\t\tswitch raw_id := raw_id.(type) {\n\t\t\t\t\t\t\tcase string:\n\t\t\t\t\t\t\t\tif raw_id != db_item_name {\n\t\t\t\t\t\t\t\t\tJsonErrorReport(w, r, \"DataBagItem name mismatch.\", http.StatusBadRequest)\n\t\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tJsonErrorReport(w, r, \"Bad request\", http.StatusBadRequest)\n\t\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdbitem, err := chef_dbag.UpdateDBItem(db_item_name, raw_data)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tJsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\t\/* Another weird data bag item response\n\t\t\t\t\t * which isn't at all unusual. *\/\n\t\t\t\t\tfor k, v := range dbitem.RawData {\n\t\t\t\t\t\tdb_response[k] = v\n\t\t\t\t\t}\n\t\t\t\t\tdb_response[\"data_bag\"] = dbitem.DataBagName\n\t\t\t\t\tdb_response[\"chef_type\"] = dbitem.ChefType\n\t\t\t\t\tdb_response[\"id\"] = db_item_name\n\t\t\t\tdefault:\n\t\t\t\t\tJsonErrorReport(w, r, \"GET, DELETE, PUT\", http.StatusMethodNotAllowed)\n\t\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tenc := json.NewEncoder(w)\n\tif err := enc.Encode(&db_response); err != nil {\n\t\tJsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t}\n}\n\n\n<|endoftext|>"}
{"text":"<commit_before>package server\n\nimport (\n\t\"expvar\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/http\/pprof\"\n\n\t\"github.com\/gin-gonic\/gin\"\n)\n\n\/\/ Replicated from expvar.go as not public.\nfunc expVars(w http.ResponseWriter, r *http.Request) {\n\tfirst := true\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tfmt.Fprintf(w, \"{\\n\")\n\texpvar.Do(func(kv expvar.KeyValue) {\n\t\tif !first {\n\t\t\tfmt.Fprintf(w, \",\\n\")\n\t\t}\n\t\tfirst = false\n\t\tfmt.Fprintf(w, \"%q: %s\", kv.Key, kv.Value)\n\t})\n\tfmt.Fprintf(w, \"\\n}\\n\")\n}\n\nfunc profilerSetup(router *gin.Engine, path string) {\n\tengine := router.Group(path)\n\tengine.Any(\"\/vars\", gin.WrapF(expVars))\n\tengine.Any(\"\/pprof\/\", gin.WrapF(pprof.Index))\n\tengine.Any(\"\/pprof\/cmdline\", gin.WrapF(pprof.Cmdline))\n\tengine.Any(\"\/pprof\/profile\", gin.WrapF(pprof.Profile))\n\tengine.Any(\"\/pprof\/symbol\", gin.WrapF(pprof.Symbol))\n\tengine.Any(\"\/pprof\/block\", gin.WrapF(pprof.Handler(\"block\").ServeHTTP))\n\tengine.Any(\"\/pprof\/heap\", gin.WrapF(pprof.Handler(\"heap\").ServeHTTP))\n\tengine.Any(\"\/pprof\/goroutine\", gin.WrapF(pprof.Handler(\"goroutine\").ServeHTTP))\n\tengine.Any(\"\/pprof\/threadcreate\", gin.WrapF(pprof.Handler(\"threadcreate\").ServeHTTP))\n}\n<commit_msg>Remove replicated expvar handler (#805)<commit_after>package server\n\nimport (\n\t\"expvar\"\n\t\"net\/http\/pprof\"\n\n\t\"github.com\/gin-gonic\/gin\"\n)\n\nfunc profilerSetup(router *gin.Engine, path string) {\n\tengine := router.Group(path)\n\tengine.Any(\"\/vars\", gin.WrapF(expvar.Handler().ServeHTTP))\n\tengine.Any(\"\/pprof\/\", gin.WrapF(pprof.Index))\n\tengine.Any(\"\/pprof\/cmdline\", gin.WrapF(pprof.Cmdline))\n\tengine.Any(\"\/pprof\/profile\", gin.WrapF(pprof.Profile))\n\tengine.Any(\"\/pprof\/symbol\", gin.WrapF(pprof.Symbol))\n\tengine.Any(\"\/pprof\/block\", gin.WrapF(pprof.Handler(\"block\").ServeHTTP))\n\tengine.Any(\"\/pprof\/heap\", gin.WrapF(pprof.Handler(\"heap\").ServeHTTP))\n\tengine.Any(\"\/pprof\/goroutine\", gin.WrapF(pprof.Handler(\"goroutine\").ServeHTTP))\n\tengine.Any(\"\/pprof\/threadcreate\", gin.WrapF(pprof.Handler(\"threadcreate\").ServeHTTP))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ JSON Data Storage\npackage golb\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"time\"\n)\n\ntype Comment struct {\n\tDate    time.Time\n\tName    string\n\tEmail   string\n\tURL     string\n\tComment string\n\tEnabled bool\n}\n\ntype Article struct {\n\tDate     time.Time\n\tTitle    string\n\tSlug     string\n\tBody     string\n\tTags     []string\n\tEnabled  bool\n\tAuthor   string\n\tComments []Comment\n}\n\ntype Data struct {\n\tArticles []Article\n\tName     string\n}\n\nfunc Open(name string) *Data {\n\td := new(Data)\n\td.Name = name\n\treturn d\n}\n\nfunc (d *Data) Read() error {\n\tdata, err := ioutil.ReadFile(d.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, &d.Articles)\n}\n\nfunc (d *Data) Write() error {\n\tdata, err := json.MarshalIndent(d.Articles, \"\", \"\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(d.Name, data, 0644)\n}\n<commit_msg>add findarticle<commit_after>\/\/ JSON Data Storage\npackage golb\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"time\"\n)\n\ntype Comment struct {\n\tDate    time.Time\n\tName    string\n\tEmail   string\n\tURL     string\n\tComment string\n\tEnabled bool\n}\n\ntype Article struct {\n\tDate     time.Time\n\tTitle    string\n\tSlug     string\n\tBody     string\n\tTags     []string\n\tEnabled  bool\n\tAuthor   string\n\tComments []Comment\n}\n\ntype Data struct {\n\tArticles []Article\n\tName     string\n}\n\nfunc Open(name string) *Data {\n\td := new(Data)\n\td.Name = name\n\treturn d\n}\n\nfunc (d *Data) Read() error {\n\tdata, err := ioutil.ReadFile(d.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn json.Unmarshal(data, &d.Articles)\n}\n\nfunc (d *Data) Write() error {\n\tdata, err := json.MarshalIndent(d.Articles, \"\", \"\t\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(d.Name, data, 0644)\n}\n\nfunc (d *Data) FindArticle(slug string) (Article, error) {\n\tfor _, a := range d.Articles {\n\t\tif a.Slug == slug {\n\t\t\treturn a, nil\n\t\t}\n\t}\n\treturn Article{}, errors.New(\"not found\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package userController\n\nimport (\n\t\"net\/http\"\n\t\"strconv\"\n\n\t\"github.com\/NyaaPantsu\/nyaa\/controllers\/router\"\n\t\"github.com\/NyaaPantsu\/nyaa\/models\/users\"\n\t\"github.com\/gin-gonic\/gin\"\n)\n\n\/\/ UserFollowHandler : Controller to follow\/unfollow users, need user id to follow\nfunc UserFollowHandler(c *gin.Context) {\n\tvar followAction string\n\tid, _ := strconv.ParseUint(c.Param(\"id\"), 10, 32)\n\tcurrentUser := router.GetUser(c)\n\tuser, _, errorUser := users.FindForAdmin(uint(id))\n\tif errorUser == nil && user.ID > 0 {\n\t\tif !currentUser.IsFollower(uint(id)) {\n\t\t\tfollowAction = \"followed\"\n\t\t\tcurrentUser.SetFollow(user)\n\t\t} else {\n\t\t\tfollowAction = \"unfollowed\"\n\t\t\tcurrentUser.RemoveFollow(user)\n\t\t}\n\t}\n\turl := \"\/user\/\" + strconv.Itoa(int(user.ID)) + \"\/\" + user.Username + \"?\" + followAction\n\tif c.Query(\"id\") != \"\" {\n\t\turl = \"\/view\/\" + c.Query(\"id\") + \"?\" + followAction\n\t}\n\tc.Redirect(http.StatusSeeOther, url)\n}\n<commit_msg>Update follow.go<commit_after>package userController\n\nimport (\n\t\"net\/http\"\n\t\"strconv\"\n\n\t\"github.com\/NyaaPantsu\/nyaa\/controllers\/router\"\n\t\"github.com\/NyaaPantsu\/nyaa\/models\/users\"\n\t\"github.com\/gin-gonic\/gin\"\n)\n\n\/\/ UserFollowHandler : Controller to follow\/unfollow users, need user id to follow\nfunc UserFollowHandler(c *gin.Context) {\n\tvar followAction string\n\tid, _ := strconv.ParseUint(c.Param(\"id\"), 10, 32)\n\tcurrentUser := router.GetUser(c)\n\tuser, _, errorUser := users.FindForAdmin(uint(id))\n\tif errorUser == nil && user.ID > 0 {\n\t\tif !currentUser.IsFollower(uint(id)) {\n\t\t\tfollowAction = \"followed\"\n\t\t\tcurrentUser.SetFollow(user)\n\t\t} else {\n\t\t\tfollowAction = \"unfollowed\"\n\t\t\tcurrentUser.RemoveFollow(user)\n\t\t}\n\t}\n\turl := \"\/user\/\" + strconv.Itoa(int(user.ID)) + \"\/\" + user.Username + \"?\" + followAction\n\tif c.Query(\"id\") != \"\" {\n\t\turl = \"\/view\/\" + c.Query(\"id\") + \"?\" + followAction\n\t}\n\tif currentUser.ID == 0 {\n\t\turl = \"\/login\"\n\t}\n\tc.Redirect(http.StatusSeeOther, url)\n}\n<|endoftext|>"}
{"text":"<commit_before>package chroot\n\nimport (\n\t\"context\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/Azure\/azure-sdk-for-go\/services\/compute\/mgmt\/2019-07-01\/compute\"\n\t\"github.com\/Azure\/go-autorest\/autorest\"\n\t\"github.com\/hashicorp\/packer\/builder\/azure\/common\/client\"\n\t\"github.com\/hashicorp\/packer\/helper\/multistep\"\n)\n\nfunc TestStepResolvePlatformImageVersion_Run(t *testing.T) {\n\n\tpi := &StepResolvePlatformImageVersion{\n\t\tPlatformImage: &client.PlatformImage{\n\t\t\tVersion: \"latest\",\n\t\t}}\n\n\tm := compute.NewVirtualMachineImagesClient(\"subscriptionId\")\n\tm.Sender = autorest.SenderFunc(func(r *http.Request) (*http.Response, error) {\n\t\tif !strings.Contains(r.URL.String(), \"%24orderby=name+desc\") {\n\t\t\tt.Errorf(\"Expected url to use odata based sorting, but got %q\", r.URL.String())\n\t\t}\n\t\treturn &http.Response{\n\t\t\tRequest: r,\n\t\t\tBody: ioutil.NopCloser(strings.NewReader(\n\t\t\t\t`[\n\t\t\t\t\t{\"name\":\"1.2.3\"},\n\t\t\t\t\t{\"name\":\"4.5.6\"}\n\t\t\t\t]`)),\n\t\t\tStatusCode: 200,\n\t\t}, nil\n\t})\n\n\tstate := new(multistep.BasicStateBag)\n\tstate.Put(\"azureclient\", &client.AzureClientSetMock{\n\t\tVirtualMachineImagesClientMock: client.VirtualMachineImagesClient{m},\n\t})\n\n\tui, getErrs := testUI()\n\tstate.Put(\"ui\", ui)\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\tgot := pi.Run(ctx, state)\n\tif got != multistep.ActionContinue {\n\t\tt.Errorf(\"Expected 'continue', but got %q\", got)\n\t}\n\n\tif pi.PlatformImage.Version != \"1.2.3\" {\n\t\tt.Errorf(\"Expected version '1.2.3', but got %q\", pi.PlatformImage.Version)\n\t}\n\n\t_ = getErrs\n}\n<commit_msg>Remove lint<commit_after>package chroot\n\nimport (\n\t\"context\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/Azure\/azure-sdk-for-go\/services\/compute\/mgmt\/2019-07-01\/compute\"\n\t\"github.com\/Azure\/go-autorest\/autorest\"\n\t\"github.com\/hashicorp\/packer\/builder\/azure\/common\/client\"\n\t\"github.com\/hashicorp\/packer\/helper\/multistep\"\n)\n\nfunc TestStepResolvePlatformImageVersion_Run(t *testing.T) {\n\n\tpi := &StepResolvePlatformImageVersion{\n\t\tPlatformImage: &client.PlatformImage{\n\t\t\tVersion: \"latest\",\n\t\t}}\n\n\tm := compute.NewVirtualMachineImagesClient(\"subscriptionId\")\n\tm.Sender = autorest.SenderFunc(func(r *http.Request) (*http.Response, error) {\n\t\tif !strings.Contains(r.URL.String(), \"%24orderby=name+desc\") {\n\t\t\tt.Errorf(\"Expected url to use odata based sorting, but got %q\", r.URL.String())\n\t\t}\n\t\treturn &http.Response{\n\t\t\tRequest: r,\n\t\t\tBody: ioutil.NopCloser(strings.NewReader(\n\t\t\t\t`[\n\t\t\t\t\t{\"name\":\"1.2.3\"},\n\t\t\t\t\t{\"name\":\"4.5.6\"}\n\t\t\t\t]`)),\n\t\t\tStatusCode: 200,\n\t\t}, nil\n\t})\n\n\tstate := new(multistep.BasicStateBag)\n\tstate.Put(\"azureclient\", &client.AzureClientSetMock{\n\t\tVirtualMachineImagesClientMock: client.VirtualMachineImagesClient{\n\t\t\tVirtualMachineImagesClientAPI: m}})\n\n\tui, getErrs := testUI()\n\tstate.Put(\"ui\", ui)\n\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\n\tgot := pi.Run(ctx, state)\n\tif got != multistep.ActionContinue {\n\t\tt.Errorf(\"Expected 'continue', but got %q\", got)\n\t}\n\n\tif pi.PlatformImage.Version != \"1.2.3\" {\n\t\tt.Errorf(\"Expected version '1.2.3', but got %q\", pi.PlatformImage.Version)\n\t}\n\n\t_ = getErrs\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2017 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package arena implements a memory arena.\npackage arena\n\nimport (\n\t\"context\"\n\t\"unsafe\"\n\n\t\"github.com\/google\/gapid\/core\/context\/keys\"\n)\n\n\/\/ #cgo LDFLAGS: -lcc-core -lcc-arena -lstdc++\n\/\/\n\/\/ #include \"core\/memory\/arena\/cc\/arena.h\"\nimport \"C\"\n\n\/\/ Arena is a native memory allocator that owns each of the allocations made by\n\/\/ Allocate() and Reallocate(). If there are any outstanding allocations when\n\/\/ the Arena is disposed then these allocations are automatically freed.\n\/\/ Because the memory is allocated outside of the Go environment it is important\n\/\/ to explicity free unused memory - either by calling Free() or calling\n\/\/ Dispose() on the Arena.\n\/\/ Failing to Dispose() the arena will leak memory.\ntype Arena struct{ Pointer unsafe.Pointer }\n\n\/\/ New constructs a new arena.\n\/\/ You must call Dispose to free the arena object and any arena-owned\n\/\/ allocations.\nfunc New() Arena {\n\treturn Arena{Pointer: unsafe.Pointer(C.arena_create())}\n}\n\n\/\/ Dispose destructs and frees the arena and all arena-owned allocations.\nfunc (a Arena) Dispose() {\n\ta.assertNotNil()\n\tC.arena_destroy((*C.arena)(a.Pointer))\n}\n\n\/\/ Allocate returns a pointer to a new arena-owned, contiguous block of memory\n\/\/ of the specified size and alignment.\nfunc (a Arena) Allocate(size, alignment int) unsafe.Pointer {\n\ta.assertNotNil()\n\treturn C.arena_alloc((*C.arena)(a.Pointer), C.uint32_t(size), C.uint32_t(alignment))\n}\n\n\/\/ Reallocate reallocates the memory at ptr to the new size and alignment.\n\/\/ ptr must have been allocated from this arena.\nfunc (a Arena) Reallocate(ptr unsafe.Pointer, size, alignment int) unsafe.Pointer {\n\ta.assertNotNil()\n\treturn C.arena_realloc((*C.arena)(a.Pointer), ptr, C.uint32_t(size), C.uint32_t(alignment))\n}\n\n\/\/ Free releases the memory at ptr, which must have been previously allocated by\n\/\/ this arena.\nfunc (a Arena) Free(ptr unsafe.Pointer) {\n\ta.assertNotNil()\n\tC.arena_free((*C.arena)(a.Pointer), ptr)\n}\n\n\/\/ Stats holds statistics of an Arena.\ntype Stats struct {\n\tNumAllocations    int\n\tNumBytesAllocated int\n}\n\n\/\/ Stats returns statistics of the current state of the Arena.\nfunc (a Arena) Stats() Stats {\n\tvar numAllocs, numBytes C.size_t\n\ta.assertNotNil()\n\tC.arena_stats((*C.arena)(a.Pointer), &numAllocs, &numBytes)\n\treturn Stats{int(numAllocs), int(numBytes)}\n}\n\nfunc (a Arena) assertNotNil() {\n\tif a.Pointer == nil {\n\t\tpanic(\"nil arena\")\n\t}\n}\n\n\/\/ Offsetable is used as an anonymous field of types that require a current\n\/\/ offset value.\ntype Offsetable struct{ Offset int }\n\n\/\/ AlignUp rounds-up the current offset so that is is a multiple of n.\nfunc (o *Offsetable) AlignUp(n int) {\n\tpad := n - o.Offset%n\n\tif pad == n {\n\t\treturn\n\t}\n\to.Offset += pad\n}\n\n\/\/ Writer provides methods to help allocate and populate a native buffer with\n\/\/ data. Use Arena.Writer() to construct.\ntype Writer struct {\n\tOffsetable \/\/ The current write-offset in bytes.\n\tarena      Arena\n\tsize       int\n\talignment  int\n\tbase       unsafe.Pointer\n\tfrozen     bool\n}\n\n\/\/ NewWriter returns a new Writer to a new arena allocated buffer of the initial\n\/\/ size. The native buffer may grow if the writer exceeds the size of the\n\/\/ buffer. The buffer will always be of the specified alignment in memory.\n\/\/ The once the native buffer is no longer needed, the pointer returned by\n\/\/ Pointer() should be passed to Arena.Free().\nfunc (a Arena) NewWriter(size, alignment int) *Writer {\n\tbase := a.Allocate(size, alignment)\n\treturn &Writer{\n\t\tarena:     a,\n\t\tsize:      size,\n\t\talignment: alignment,\n\t\tbase:      base,\n\t}\n}\n\n\/\/ Reset sets the write offset back to the start of the buffer and unfreezes\n\/\/ the writer. This allows for efficient reuse of the writer's native buffer.\nfunc (w *Writer) Reset() {\n\tw.Offset = 0\n\tw.frozen = false\n}\n\n\/\/ Pointer returns the base address of the native buffer for the writer.\n\/\/ Calling Pointer() freezes the writer - once called no more writes to the\n\/\/ buffer can be made, unless Reset() is called. Freezing attempts to reduce the\n\/\/ chance of the stale pointer being used after a buffer reallocation.\nfunc (w *Writer) Pointer() unsafe.Pointer {\n\tw.frozen = true\n\treturn w.base\n}\n\n\/\/ Write copies size bytes from src to the current writer's write offset.\n\/\/ If there is not enough space in the buffer for the write, then the buffer\n\/\/ is grown via reallocation.\n\/\/ Upon returning, the write offset is incremented by size bytes.\nfunc (w *Writer) Write(src unsafe.Pointer, size int) {\n\tif w.frozen {\n\t\tpanic(\"Cannot write to Writer after calling Pointer()\")\n\t}\n\tif needed := w.Offset + size; needed > w.size {\n\t\tsize := w.size\n\t\tfor needed > size {\n\t\t\tsize *= 2 \/\/ TODO: Snugger fit?\n\t\t}\n\t\tw.base = w.arena.Reallocate(w.base, size, w.alignment)\n\t\tw.size = size\n\t}\n\tdst := uintptr(w.base) + uintptr(w.Offset)\n\tfor i := 0; i < size; i++ {\n\t\tdst := (*byte)(unsafe.Pointer(dst + uintptr(i)))\n\t\tsrc := (*byte)(unsafe.Pointer(uintptr(src) + uintptr(i)))\n\t\t*dst = *src\n\t}\n\tw.Offset += size\n}\n\n\/\/ Reader provides the Read method to read native buffer data.\n\/\/ Use NewReader() to construct.\ntype Reader struct {\n\tOffsetable \/\/ The current read-offset in bytes.\n\tbase       unsafe.Pointer\n}\n\n\/\/ NewReader returns a new Reader to the native-buffer starting at ptr.\nfunc NewReader(ptr unsafe.Pointer) *Reader {\n\treturn &Reader{base: ptr}\n}\n\n\/\/ Read copies size bytes from the current read offset to dst.\n\/\/ Upon returning, the read offset is incremented by size bytes.\nfunc (r *Reader) Read(dst unsafe.Pointer, size int) {\n\tsrc := uintptr(r.base) + uintptr(r.Offset)\n\tfor i := 0; i < size; i++ {\n\t\tsrc := (*byte)(unsafe.Pointer(src + uintptr(i)))\n\t\tdst := (*byte)(unsafe.Pointer(uintptr(dst) + uintptr(i)))\n\t\t*dst = *src\n\t}\n\tr.Offset += size\n}\n<commit_msg>core\/memory\/arena: Add context Get() Put() functions.<commit_after>\/\/ Copyright (C) 2017 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package arena implements a memory arena.\npackage arena\n\nimport (\n\t\"context\"\n\t\"unsafe\"\n\n\t\"github.com\/google\/gapid\/core\/context\/keys\"\n)\n\n\/\/ #cgo LDFLAGS: -lcc-core -lcc-arena -lstdc++\n\/\/\n\/\/ #include \"core\/memory\/arena\/cc\/arena.h\"\nimport \"C\"\n\n\/\/ Arena is a native memory allocator that owns each of the allocations made by\n\/\/ Allocate() and Reallocate(). If there are any outstanding allocations when\n\/\/ the Arena is disposed then these allocations are automatically freed.\n\/\/ Because the memory is allocated outside of the Go environment it is important\n\/\/ to explicity free unused memory - either by calling Free() or calling\n\/\/ Dispose() on the Arena.\n\/\/ Failing to Dispose() the arena will leak memory.\ntype Arena struct{ Pointer unsafe.Pointer }\n\n\/\/ New constructs a new arena.\n\/\/ You must call Dispose to free the arena object and any arena-owned\n\/\/ allocations.\nfunc New() Arena {\n\treturn Arena{Pointer: unsafe.Pointer(C.arena_create())}\n}\n\n\/\/ Dispose destructs and frees the arena and all arena-owned allocations.\nfunc (a Arena) Dispose() {\n\ta.assertNotNil()\n\tC.arena_destroy((*C.arena)(a.Pointer))\n}\n\n\/\/ Allocate returns a pointer to a new arena-owned, contiguous block of memory\n\/\/ of the specified size and alignment.\nfunc (a Arena) Allocate(size, alignment int) unsafe.Pointer {\n\ta.assertNotNil()\n\treturn C.arena_alloc((*C.arena)(a.Pointer), C.uint32_t(size), C.uint32_t(alignment))\n}\n\n\/\/ Reallocate reallocates the memory at ptr to the new size and alignment.\n\/\/ ptr must have been allocated from this arena.\nfunc (a Arena) Reallocate(ptr unsafe.Pointer, size, alignment int) unsafe.Pointer {\n\ta.assertNotNil()\n\treturn C.arena_realloc((*C.arena)(a.Pointer), ptr, C.uint32_t(size), C.uint32_t(alignment))\n}\n\n\/\/ Free releases the memory at ptr, which must have been previously allocated by\n\/\/ this arena.\nfunc (a Arena) Free(ptr unsafe.Pointer) {\n\ta.assertNotNil()\n\tC.arena_free((*C.arena)(a.Pointer), ptr)\n}\n\n\/\/ Stats holds statistics of an Arena.\ntype Stats struct {\n\tNumAllocations    int\n\tNumBytesAllocated int\n}\n\n\/\/ Stats returns statistics of the current state of the Arena.\nfunc (a Arena) Stats() Stats {\n\tvar numAllocs, numBytes C.size_t\n\ta.assertNotNil()\n\tC.arena_stats((*C.arena)(a.Pointer), &numAllocs, &numBytes)\n\treturn Stats{int(numAllocs), int(numBytes)}\n}\n\nfunc (a Arena) assertNotNil() {\n\tif a.Pointer == nil {\n\t\tpanic(\"nil arena\")\n\t}\n}\n\ntype arenaKeyTy string\n\nconst arenaKey = arenaKeyTy(\"arena\")\n\n\/\/ Get returns the Arena attached to the given context.\nfunc Get(ctx context.Context) Arena {\n\tif val := ctx.Value(arenaKey); val != nil {\n\t\treturn val.(Arena)\n\t}\n\tpanic(\"arena missing from context\")\n}\n\n\/\/ Put amends a Context by attaching a Arena reference to it.\nfunc Put(ctx context.Context, d Arena) context.Context {\n\tif val := ctx.Value(arenaKey); val != nil {\n\t\tpanic(\"Context already holds an arena\")\n\t}\n\treturn keys.WithValue(ctx, arenaKey, d)\n}\n\n\/\/ Offsetable is used as an anonymous field of types that require a current\n\/\/ offset value.\ntype Offsetable struct{ Offset int }\n\n\/\/ AlignUp rounds-up the current offset so that is is a multiple of n.\nfunc (o *Offsetable) AlignUp(n int) {\n\tpad := n - o.Offset%n\n\tif pad == n {\n\t\treturn\n\t}\n\to.Offset += pad\n}\n\n\/\/ Writer provides methods to help allocate and populate a native buffer with\n\/\/ data. Use Arena.Writer() to construct.\ntype Writer struct {\n\tOffsetable \/\/ The current write-offset in bytes.\n\tarena      Arena\n\tsize       int\n\talignment  int\n\tbase       unsafe.Pointer\n\tfrozen     bool\n}\n\n\/\/ NewWriter returns a new Writer to a new arena allocated buffer of the initial\n\/\/ size. The native buffer may grow if the writer exceeds the size of the\n\/\/ buffer. The buffer will always be of the specified alignment in memory.\n\/\/ The once the native buffer is no longer needed, the pointer returned by\n\/\/ Pointer() should be passed to Arena.Free().\nfunc (a Arena) NewWriter(size, alignment int) *Writer {\n\tbase := a.Allocate(size, alignment)\n\treturn &Writer{\n\t\tarena:     a,\n\t\tsize:      size,\n\t\talignment: alignment,\n\t\tbase:      base,\n\t}\n}\n\n\/\/ Reset sets the write offset back to the start of the buffer and unfreezes\n\/\/ the writer. This allows for efficient reuse of the writer's native buffer.\nfunc (w *Writer) Reset() {\n\tw.Offset = 0\n\tw.frozen = false\n}\n\n\/\/ Pointer returns the base address of the native buffer for the writer.\n\/\/ Calling Pointer() freezes the writer - once called no more writes to the\n\/\/ buffer can be made, unless Reset() is called. Freezing attempts to reduce the\n\/\/ chance of the stale pointer being used after a buffer reallocation.\nfunc (w *Writer) Pointer() unsafe.Pointer {\n\tw.frozen = true\n\treturn w.base\n}\n\n\/\/ Write copies size bytes from src to the current writer's write offset.\n\/\/ If there is not enough space in the buffer for the write, then the buffer\n\/\/ is grown via reallocation.\n\/\/ Upon returning, the write offset is incremented by size bytes.\nfunc (w *Writer) Write(src unsafe.Pointer, size int) {\n\tif w.frozen {\n\t\tpanic(\"Cannot write to Writer after calling Pointer()\")\n\t}\n\tif needed := w.Offset + size; needed > w.size {\n\t\tsize := w.size\n\t\tfor needed > size {\n\t\t\tsize *= 2 \/\/ TODO: Snugger fit?\n\t\t}\n\t\tw.base = w.arena.Reallocate(w.base, size, w.alignment)\n\t\tw.size = size\n\t}\n\tdst := uintptr(w.base) + uintptr(w.Offset)\n\tfor i := 0; i < size; i++ {\n\t\tdst := (*byte)(unsafe.Pointer(dst + uintptr(i)))\n\t\tsrc := (*byte)(unsafe.Pointer(uintptr(src) + uintptr(i)))\n\t\t*dst = *src\n\t}\n\tw.Offset += size\n}\n\n\/\/ Reader provides the Read method to read native buffer data.\n\/\/ Use NewReader() to construct.\ntype Reader struct {\n\tOffsetable \/\/ The current read-offset in bytes.\n\tbase       unsafe.Pointer\n}\n\n\/\/ NewReader returns a new Reader to the native-buffer starting at ptr.\nfunc NewReader(ptr unsafe.Pointer) *Reader {\n\treturn &Reader{base: ptr}\n}\n\n\/\/ Read copies size bytes from the current read offset to dst.\n\/\/ Upon returning, the read offset is incremented by size bytes.\nfunc (r *Reader) Read(dst unsafe.Pointer, size int) {\n\tsrc := uintptr(r.base) + uintptr(r.Offset)\n\tfor i := 0; i < size; i++ {\n\t\tsrc := (*byte)(unsafe.Pointer(src + uintptr(i)))\n\t\tdst := (*byte)(unsafe.Pointer(uintptr(dst) + uintptr(i)))\n\t\t*dst = *src\n\t}\n\tr.Offset += size\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage options\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/spf13\/pflag\"\n\n\tcsrsigningconfig \"k8s.io\/kubernetes\/pkg\/controller\/certificates\/signer\/config\"\n)\n\n\/\/ CSRSigningControllerOptions holds the CSRSigningController options.\ntype CSRSigningControllerOptions struct {\n\t*csrsigningconfig.CSRSigningControllerConfiguration\n}\n\n\/\/ AddFlags adds flags related to CSRSigningController for controller manager to the specified FlagSet.\nfunc (o *CSRSigningControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.StringVar(&o.ClusterSigningCertFile, \"cluster-signing-cert-file\", o.ClusterSigningCertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue cluster-scoped certificates.  If specified, no more specific --cluster-signing-* flag may be specified.\")\n\tfs.StringVar(&o.ClusterSigningKeyFile, \"cluster-signing-key-file\", o.ClusterSigningKeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign cluster-scoped certificates.  If specified, no more specific --cluster-signing-* flag may be specified.\")\n\tfs.StringVar(&o.KubeletServingSignerConfiguration.CertFile, \"cluster-signing-kubelet-serving-cert-file\", o.KubeletServingSignerConfiguration.CertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue certificates for the kubernetes.io\/kubelet-serving signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.KubeletServingSignerConfiguration.KeyFile, \"cluster-signing-kubelet-serving-key-file\", o.KubeletServingSignerConfiguration.KeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign certificates for the kubernetes.io\/kubelet-serving signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.KubeletClientSignerConfiguration.CertFile, \"cluster-signing-kubelet-client-cert-file\", o.KubeletClientSignerConfiguration.CertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue certificates for the kubernetes.io\/kube-apiserver-client-kubelet signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.KubeletClientSignerConfiguration.KeyFile, \"cluster-signing-kubelet-client-key-file\", o.KubeletClientSignerConfiguration.KeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign certificates for the kubernetes.io\/kube-apiserver-client-kubelet signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.KubeAPIServerClientSignerConfiguration.CertFile, \"cluster-signing-kube-apiserver-client-cert-file\", o.KubeAPIServerClientSignerConfiguration.CertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue certificates for the kubernetes.io\/kube-apiserver-client signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.KubeAPIServerClientSignerConfiguration.KeyFile, \"cluster-signing-kube-apiserver-client-key-file\", o.KubeAPIServerClientSignerConfiguration.KeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign certificates for the kubernetes.io\/kube-apiserver-client signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.LegacyUnknownSignerConfiguration.CertFile, \"cluster-signing-legacy-unknown-cert-file\", o.LegacyUnknownSignerConfiguration.CertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue certificates for the kubernetes.io\/legacy-unknown signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.LegacyUnknownSignerConfiguration.KeyFile, \"cluster-signing-legacy-unknown-key-file\", o.LegacyUnknownSignerConfiguration.KeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign certificates for the kubernetes.io\/legacy-unknown signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.DurationVar(&o.ClusterSigningDuration.Duration, \"cluster-signing-duration\", o.ClusterSigningDuration.Duration, \"The max length of duration signed certificates will be given.  Individual CSRs may request shorter certs by setting spec.expirationSeconds.\")\n\tfs.DurationVar(&o.ClusterSigningDuration.Duration, \"experimental-cluster-signing-duration\", o.ClusterSigningDuration.Duration, \"The max length of duration signed certificates will be given.  Individual CSRs may request shorter certs by setting spec.expirationSeconds.\")\n\tfs.MarkDeprecated(\"experimental-cluster-signing-duration\", \"use --cluster-signing-duration\")\n}\n\n\/\/ ApplyTo fills up CSRSigningController config with options.\nfunc (o *CSRSigningControllerOptions) ApplyTo(cfg *csrsigningconfig.CSRSigningControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ClusterSigningCertFile = o.ClusterSigningCertFile\n\tcfg.ClusterSigningKeyFile = o.ClusterSigningKeyFile\n\tcfg.KubeletServingSignerConfiguration = o.KubeletServingSignerConfiguration\n\tcfg.KubeletClientSignerConfiguration = o.KubeletClientSignerConfiguration\n\tcfg.KubeAPIServerClientSignerConfiguration = o.KubeAPIServerClientSignerConfiguration\n\tcfg.LegacyUnknownSignerConfiguration = o.LegacyUnknownSignerConfiguration\n\tcfg.ClusterSigningDuration = o.ClusterSigningDuration\n\n\treturn nil\n}\n\n\/\/ Validate checks validation of CSRSigningControllerOptions.\nfunc (o *CSRSigningControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\tif err := csrSigningFilesValid(o.KubeletServingSignerConfiguration); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%q: %v\", \"cluster-signing-kubelet-serving\", err))\n\t}\n\tif err := csrSigningFilesValid(o.KubeletClientSignerConfiguration); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%q: %v\", \"cluster-signing-kube-apiserver-client\", err))\n\t}\n\tif err := csrSigningFilesValid(o.KubeAPIServerClientSignerConfiguration); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%q: %v\", \"cluster-signing-kube-apiserver\", err))\n\t}\n\tif err := csrSigningFilesValid(o.LegacyUnknownSignerConfiguration); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%q: %v\", \"cluster-signing-legacy-unknown\", err))\n\t}\n\n\tsingleSigningFile := len(o.ClusterSigningCertFile) > 0 || len(o.ClusterSigningKeyFile) > 0\n\tanySpecificFilesSet := len(o.KubeletServingSignerConfiguration.CertFile) > 0 || len(o.KubeletServingSignerConfiguration.KeyFile) > 0 ||\n\t\tlen(o.KubeletClientSignerConfiguration.CertFile) > 0 || len(o.KubeletClientSignerConfiguration.KeyFile) > 0 ||\n\t\tlen(o.KubeAPIServerClientSignerConfiguration.CertFile) > 0 || len(o.KubeAPIServerClientSignerConfiguration.KeyFile) > 0 ||\n\t\tlen(o.LegacyUnknownSignerConfiguration.CertFile) > 0 || len(o.LegacyUnknownSignerConfiguration.KeyFile) > 0\n\tif singleSigningFile && anySpecificFilesSet {\n\t\terrs = append(errs, fmt.Errorf(\"cannot specify --cluster-signing-{cert,key}-file and other --cluster-signing-*-file flags at the same time\"))\n\t}\n\n\treturn errs\n}\n\n\/\/ both must be specified or both must be empty\nfunc csrSigningFilesValid(config csrsigningconfig.CSRSigningConfiguration) error {\n\tswitch {\n\tcase (len(config.CertFile) == 0) && (len(config.KeyFile) == 0):\n\t\treturn nil\n\tcase (len(config.CertFile) != 0) && (len(config.KeyFile) != 0):\n\t\treturn nil\n\tcase (len(config.CertFile) == 0) && (len(config.KeyFile) != 0):\n\t\treturn fmt.Errorf(\"cannot specify key without cert\")\n\tcase (len(config.CertFile) != 0) && (len(config.KeyFile) == 0):\n\t\treturn fmt.Errorf(\"cannot specify cert without key\")\n\t}\n\n\treturn fmt.Errorf(\"math broke\")\n}\n<commit_msg>kube-controller-manager: Remove the deprecated `--experimental-cluster-signing-duration` flag<commit_after>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage options\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/spf13\/pflag\"\n\n\tcsrsigningconfig \"k8s.io\/kubernetes\/pkg\/controller\/certificates\/signer\/config\"\n)\n\n\/\/ CSRSigningControllerOptions holds the CSRSigningController options.\ntype CSRSigningControllerOptions struct {\n\t*csrsigningconfig.CSRSigningControllerConfiguration\n}\n\n\/\/ AddFlags adds flags related to CSRSigningController for controller manager to the specified FlagSet.\nfunc (o *CSRSigningControllerOptions) AddFlags(fs *pflag.FlagSet) {\n\tif o == nil {\n\t\treturn\n\t}\n\n\tfs.StringVar(&o.ClusterSigningCertFile, \"cluster-signing-cert-file\", o.ClusterSigningCertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue cluster-scoped certificates.  If specified, no more specific --cluster-signing-* flag may be specified.\")\n\tfs.StringVar(&o.ClusterSigningKeyFile, \"cluster-signing-key-file\", o.ClusterSigningKeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign cluster-scoped certificates.  If specified, no more specific --cluster-signing-* flag may be specified.\")\n\tfs.StringVar(&o.KubeletServingSignerConfiguration.CertFile, \"cluster-signing-kubelet-serving-cert-file\", o.KubeletServingSignerConfiguration.CertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue certificates for the kubernetes.io\/kubelet-serving signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.KubeletServingSignerConfiguration.KeyFile, \"cluster-signing-kubelet-serving-key-file\", o.KubeletServingSignerConfiguration.KeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign certificates for the kubernetes.io\/kubelet-serving signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.KubeletClientSignerConfiguration.CertFile, \"cluster-signing-kubelet-client-cert-file\", o.KubeletClientSignerConfiguration.CertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue certificates for the kubernetes.io\/kube-apiserver-client-kubelet signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.KubeletClientSignerConfiguration.KeyFile, \"cluster-signing-kubelet-client-key-file\", o.KubeletClientSignerConfiguration.KeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign certificates for the kubernetes.io\/kube-apiserver-client-kubelet signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.KubeAPIServerClientSignerConfiguration.CertFile, \"cluster-signing-kube-apiserver-client-cert-file\", o.KubeAPIServerClientSignerConfiguration.CertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue certificates for the kubernetes.io\/kube-apiserver-client signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.KubeAPIServerClientSignerConfiguration.KeyFile, \"cluster-signing-kube-apiserver-client-key-file\", o.KubeAPIServerClientSignerConfiguration.KeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign certificates for the kubernetes.io\/kube-apiserver-client signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.LegacyUnknownSignerConfiguration.CertFile, \"cluster-signing-legacy-unknown-cert-file\", o.LegacyUnknownSignerConfiguration.CertFile, \"Filename containing a PEM-encoded X509 CA certificate used to issue certificates for the kubernetes.io\/legacy-unknown signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.StringVar(&o.LegacyUnknownSignerConfiguration.KeyFile, \"cluster-signing-legacy-unknown-key-file\", o.LegacyUnknownSignerConfiguration.KeyFile, \"Filename containing a PEM-encoded RSA or ECDSA private key used to sign certificates for the kubernetes.io\/legacy-unknown signer.  If specified, --cluster-signing-{cert,key}-file must not be set.\")\n\tfs.DurationVar(&o.ClusterSigningDuration.Duration, \"cluster-signing-duration\", o.ClusterSigningDuration.Duration, \"The max length of duration signed certificates will be given.  Individual CSRs may request shorter certs by setting spec.expirationSeconds.\")\n}\n\n\/\/ ApplyTo fills up CSRSigningController config with options.\nfunc (o *CSRSigningControllerOptions) ApplyTo(cfg *csrsigningconfig.CSRSigningControllerConfiguration) error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\tcfg.ClusterSigningCertFile = o.ClusterSigningCertFile\n\tcfg.ClusterSigningKeyFile = o.ClusterSigningKeyFile\n\tcfg.KubeletServingSignerConfiguration = o.KubeletServingSignerConfiguration\n\tcfg.KubeletClientSignerConfiguration = o.KubeletClientSignerConfiguration\n\tcfg.KubeAPIServerClientSignerConfiguration = o.KubeAPIServerClientSignerConfiguration\n\tcfg.LegacyUnknownSignerConfiguration = o.LegacyUnknownSignerConfiguration\n\tcfg.ClusterSigningDuration = o.ClusterSigningDuration\n\n\treturn nil\n}\n\n\/\/ Validate checks validation of CSRSigningControllerOptions.\nfunc (o *CSRSigningControllerOptions) Validate() []error {\n\tif o == nil {\n\t\treturn nil\n\t}\n\n\terrs := []error{}\n\tif err := csrSigningFilesValid(o.KubeletServingSignerConfiguration); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%q: %v\", \"cluster-signing-kubelet-serving\", err))\n\t}\n\tif err := csrSigningFilesValid(o.KubeletClientSignerConfiguration); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%q: %v\", \"cluster-signing-kube-apiserver-client\", err))\n\t}\n\tif err := csrSigningFilesValid(o.KubeAPIServerClientSignerConfiguration); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%q: %v\", \"cluster-signing-kube-apiserver\", err))\n\t}\n\tif err := csrSigningFilesValid(o.LegacyUnknownSignerConfiguration); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"%q: %v\", \"cluster-signing-legacy-unknown\", err))\n\t}\n\n\tsingleSigningFile := len(o.ClusterSigningCertFile) > 0 || len(o.ClusterSigningKeyFile) > 0\n\tanySpecificFilesSet := len(o.KubeletServingSignerConfiguration.CertFile) > 0 || len(o.KubeletServingSignerConfiguration.KeyFile) > 0 ||\n\t\tlen(o.KubeletClientSignerConfiguration.CertFile) > 0 || len(o.KubeletClientSignerConfiguration.KeyFile) > 0 ||\n\t\tlen(o.KubeAPIServerClientSignerConfiguration.CertFile) > 0 || len(o.KubeAPIServerClientSignerConfiguration.KeyFile) > 0 ||\n\t\tlen(o.LegacyUnknownSignerConfiguration.CertFile) > 0 || len(o.LegacyUnknownSignerConfiguration.KeyFile) > 0\n\tif singleSigningFile && anySpecificFilesSet {\n\t\terrs = append(errs, fmt.Errorf(\"cannot specify --cluster-signing-{cert,key}-file and other --cluster-signing-*-file flags at the same time\"))\n\t}\n\n\treturn errs\n}\n\n\/\/ both must be specified or both must be empty\nfunc csrSigningFilesValid(config csrsigningconfig.CSRSigningConfiguration) error {\n\tswitch {\n\tcase (len(config.CertFile) == 0) && (len(config.KeyFile) == 0):\n\t\treturn nil\n\tcase (len(config.CertFile) != 0) && (len(config.KeyFile) != 0):\n\t\treturn nil\n\tcase (len(config.CertFile) == 0) && (len(config.KeyFile) != 0):\n\t\treturn fmt.Errorf(\"cannot specify key without cert\")\n\tcase (len(config.CertFile) != 0) && (len(config.KeyFile) == 0):\n\t\treturn fmt.Errorf(\"cannot specify cert without key\")\n\t}\n\n\treturn fmt.Errorf(\"math broke\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\n\nGotest is an automated testing tool for Go packages.\n\nNormally a Go package is compiled without its test files.  Gotest is a\ntool that recompiles the package whose source is in the current\ndirectory, along with any files whose names match the pattern\n\"[^.]*_test.go\".  Functions in the test source named TestXXX (where\nXXX is any alphanumeric string not starting with a lower case letter)\nwill be run when the binary is executed.  Gotest requires that the\npackage have a standard package Makefile, one that includes\ngo\/src\/Make.pkg.\n\nThe test functions are run in the order they appear in the source.\nThey should have the signature,\n\n\tfunc TestXXX(t *testing.T) { ... }\n\nBenchmark functions can be written as well; they will be run only when\nthe -test.bench flag is provided.  Benchmarks should have the\nsignature,\n\n\tfunc BenchmarkXXX(b *testing.B) { ... }\n\nSee the documentation of the testing package for more information.\n\nBy default, gotest needs no arguments.  It compiles all the .go files\nin the directory, including tests, and runs the tests.  If file names\nare given (with flag -file=test.go, one per extra test source file),\nonly those test files are added to the package.  (The non-test files\nare always compiled.)\n\nThe package is built in a special subdirectory so it does not\ninterfere with the non-test installation.\n\nUsage:\n\tgotest [-file a.go -file b.go ...] [-c] [-x] [args for test binary]\n\nThe flags specific to gotest are:\n\t-c         Compile the test binary but do not run it.\n\t-file a.go Use only the tests in the source file a.go.\n\t           Multiple -file flags may be provided.\n\t-x         Print each subcommand gotest executes.\n\nEverything else on the command line is passed to the test binary.\n\nThe resulting test binary, called (for amd64) 6.out, has several flags.\n\nUsage:\n\t6.out [-test.v] [-test.run pattern] [-test.bench pattern] \\\n\t\t[-test.cpuprofile=cpu.out] \\\n\t\t[-test.memprofile=mem.out] [-test.memprofilerate=1] \\\n\t\t[-test.timeout=10] [-test.short] \\\n\t\t[-test.benchtime=3] [-test.cpu=1,2,3,4]\n\nThe -test.v flag causes the tests to be logged as they run.  The\n-test.run flag causes only those tests whose names match the regular\nexpression pattern to be run.  By default all tests are run silently.\n\nIf all specified tests pass, 6.out prints the word PASS and exits with\na 0 exit code.  If any tests fail, it prints error details, the word\nFAIL, and exits with a non-zero code.  The -test.bench flag is\nanalogous to the -test.run flag, but applies to benchmarks.  No\nbenchmarks run by default.\n\nThe -test.cpuprofile flag causes the testing software to write a CPU\nprofile to the specified file before exiting.\n\nThe -test.memprofile flag causes the testing software to write a\nmemory profile to the specified file when all tests are complete.  The\n-test.memprofilerate flag enables more precise (and expensive)\nprofiles by setting runtime.MemProfileRate; run\n\tgodoc runtime MemProfileRate\nfor details.  The defaults are no memory profile and the standard\nsetting of MemProfileRate.  The memory profile records a sampling of\nthe memory in use at the end of the test.  To profile all memory\nallocations, use -test.memprofilerate=1 to sample every byte and set\nthe environment variable GOGC=off to disable the garbage collector,\nprovided the test can run in the available memory without garbage\ncollection.\n\nUse -test.run or -test.bench to limit profiling to a particular test\nor benchmark.\n\nThe -test.short flag tells long-running tests to shorten their run\ntime.  It is off by default but set by all.bash so installations of\nthe Go tree can do a sanity check but not spend time running\nexhaustive tests.\n\nThe -test.timeout flag sets a timeout for the test in seconds.  If the\ntest runs for longer than that, it will panic, dumping a stack trace\nof all existing goroutines.\n\nThe -test.benchtime flag specifies the number of seconds to run each benchmark.\nThe default is one second.\n\nThe -test.cpu flag specifies a list of GOMAXPROCS values for which\nthe tests or benchmarks are executed.  The default is the current\nvalue of GOMAXPROCS.\n\nFor convenience, each of these -test.X flags of the test binary is\nalso available as the flag -X in gotest itself.  Flags not listed here\nare unaffected.  For instance, the command\n\tgotest -x -v -cpuprofile=prof.out -dir=testdata -update -file x_test.go\nwill compile the test binary using x_test.go and then run it as\n\t6.out -test.v -test.cpuprofile=prof.out -dir=testdata -update\n\n*\/\npackage documentation\n<commit_msg>gotest: document -test.parallel<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/*\n\nGotest is an automated testing tool for Go packages.\n\nNormally a Go package is compiled without its test files.  Gotest is a\ntool that recompiles the package whose source is in the current\ndirectory, along with any files whose names match the pattern\n\"[^.]*_test.go\".  Functions in the test source named TestXXX (where\nXXX is any alphanumeric string not starting with a lower case letter)\nwill be run when the binary is executed.  Gotest requires that the\npackage have a standard package Makefile, one that includes\ngo\/src\/Make.pkg.\n\nThe test functions are run in the order they appear in the source.\nThey should have the signature,\n\n\tfunc TestXXX(t *testing.T) { ... }\n\nBenchmark functions can be written as well; they will be run only when\nthe -test.bench flag is provided.  Benchmarks should have the\nsignature,\n\n\tfunc BenchmarkXXX(b *testing.B) { ... }\n\nSee the documentation of the testing package for more information.\n\nBy default, gotest needs no arguments.  It compiles all the .go files\nin the directory, including tests, and runs the tests.  If file names\nare given (with flag -file=test.go, one per extra test source file),\nonly those test files are added to the package.  (The non-test files\nare always compiled.)\n\nThe package is built in a special subdirectory so it does not\ninterfere with the non-test installation.\n\nUsage:\n\tgotest [-file a.go -file b.go ...] [-c] [-x] [args for test binary]\n\nThe flags specific to gotest are:\n\t-c         Compile the test binary but do not run it.\n\t-file a.go Use only the tests in the source file a.go.\n\t           Multiple -file flags may be provided.\n\t-x         Print each subcommand gotest executes.\n\nEverything else on the command line is passed to the test binary.\n\nThe resulting test binary, called (for amd64) 6.out, has several flags.\n\nUsage:\n\t6.out [-test.v] [-test.run pattern] [-test.bench pattern] \\\n\t\t[-test.cpuprofile=cpu.out] \\\n\t\t[-test.memprofile=mem.out] [-test.memprofilerate=1] \\\n\t\t[-test.parallel=0] \\\n\t\t[-test.timeout=10] [-test.short] \\\n\t\t[-test.benchtime=3] [-test.cpu=1,2,3,4]\n\nThe -test.v flag causes the tests to be logged as they run.  The\n-test.run flag causes only those tests whose names match the regular\nexpression pattern to be run.  By default all tests are run silently.\n\nIf all specified tests pass, 6.out prints the word PASS and exits with\na 0 exit code.  If any tests fail, it prints error details, the word\nFAIL, and exits with a non-zero code.  The -test.bench flag is\nanalogous to the -test.run flag, but applies to benchmarks.  No\nbenchmarks run by default.\n\nThe -test.cpuprofile flag causes the testing software to write a CPU\nprofile to the specified file before exiting.\n\nThe -test.memprofile flag causes the testing software to write a\nmemory profile to the specified file when all tests are complete.  The\n-test.memprofilerate flag enables more precise (and expensive)\nprofiles by setting runtime.MemProfileRate; run\n\tgodoc runtime MemProfileRate\nfor details.  The defaults are no memory profile and the standard\nsetting of MemProfileRate.  The memory profile records a sampling of\nthe memory in use at the end of the test.  To profile all memory\nallocations, use -test.memprofilerate=1 to sample every byte and set\nthe environment variable GOGC=off to disable the garbage collector,\nprovided the test can run in the available memory without garbage\ncollection.\n\nUse -test.run or -test.bench to limit profiling to a particular test\nor benchmark.\n\nThe -test.parallel flag allows parallel execution of Test functions\nthat call test.Parallel.  The value of the flag is the maximum number\nof tests to run simultaneously; by default, parallelism is disabled.\n\nThe -test.short flag tells long-running tests to shorten their run\ntime.  It is off by default but set by all.bash so installations of\nthe Go tree can do a sanity check but not spend time running\nexhaustive tests.\n\nThe -test.timeout flag sets a timeout for the test in seconds.  If the\ntest runs for longer than that, it will panic, dumping a stack trace\nof all existing goroutines.\n\nThe -test.benchtime flag specifies the number of seconds to run each benchmark.\nThe default is one second.\n\nThe -test.cpu flag specifies a list of GOMAXPROCS values for which\nthe tests or benchmarks are executed.  The default is the current\nvalue of GOMAXPROCS.\n\nFor convenience, each of these -test.X flags of the test binary is\nalso available as the flag -X in gotest itself.  Flags not listed here\nare unaffected.  For instance, the command\n\tgotest -x -v -cpuprofile=prof.out -dir=testdata -update -file x_test.go\nwill compile the test binary using x_test.go and then run it as\n\t6.out -test.v -test.cpuprofile=prof.out -dir=testdata -update\n\n*\/\npackage documentation\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *\n * Copyright 2014, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n\/\/ Package credentials implements various credentials supported by gRPC library,\n\/\/ which encapsulate all the state needed by a client to authenticate with a\n\/\/ server and make various assertions, e.g., about the client's identity, role,\n\/\/ or whether it is authorized to make a particular call.\npackage credentials \/\/ import \"google.golang.org\/grpc\/credentials\"\n\nimport (\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"strings\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar (\n\t\/\/ alpnProtoStr are the specified application level protocols for gRPC.\n\talpnProtoStr = []string{\"h2\"}\n)\n\n\/\/ PerRPCCredentials defines the common interface for the credentials which need to\n\/\/ attach security information to every RPC (e.g., oauth2).\ntype PerRPCCredentials interface {\n\t\/\/ GetRequestMetadata gets the current request metadata, refreshing\n\t\/\/ tokens if required. This should be called by the transport layer on\n\t\/\/ each request, and the data should be populated in headers or other\n\t\/\/ context. uri is the URI of the entry point for the request. When\n\t\/\/ supported by the underlying implementation, ctx can be used for\n\t\/\/ timeout and cancellation.\n\t\/\/ TODO(zhaoq): Define the set of the qualified keys instead of leaving\n\t\/\/ it as an arbitrary string.\n\tGetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)\n\t\/\/ RequireTransportSecurity indicates whether the credentials requires\n\t\/\/ transport security.\n\tRequireTransportSecurity() bool\n}\n\n\/\/ ProtocolInfo provides information regarding the gRPC wire protocol version,\n\/\/ security protocol, security protocol version in use, server name, etc.\ntype ProtocolInfo struct {\n\t\/\/ ProtocolVersion is the gRPC wire protocol version.\n\tProtocolVersion string\n\t\/\/ SecurityProtocol is the security protocol in use.\n\tSecurityProtocol string\n\t\/\/ SecurityVersion is the security protocol version.\n\tSecurityVersion string\n\t\/\/ ServerName is the user-configured server name.\n\tServerName string\n}\n\n\/\/ AuthInfo defines the common interface for the auth information the users are interested in.\ntype AuthInfo interface {\n\tAuthType() string\n}\n\nvar (\n\t\/\/ ErrConnDispatched indicates that rawConn has been dispatched out of gRPC\n\t\/\/ and the caller should not close rawConn.\n\tErrConnDispatched = errors.New(\"credentials: rawConn is dispatched out of gRPC\")\n)\n\n\/\/ TransportCredentials defines the common interface for all the live gRPC wire\n\/\/ protocols and supported transport security protocols (e.g., TLS, SSL).\ntype TransportCredentials interface {\n\t\/\/ ClientHandshake does the authentication handshake specified by the corresponding\n\t\/\/ authentication protocol on rawConn for clients. It returns the authenticated\n\t\/\/ connection and the corresponding auth information about the connection.\n\t\/\/ Implementations must use the provided context to implement timely cancellation.\n\tClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error)\n\t\/\/ ServerHandshake does the authentication handshake for servers. It returns\n\t\/\/ the authenticated connection and the corresponding auth information about\n\t\/\/ the connection.\n\tServerHandshake(net.Conn) (net.Conn, AuthInfo, error)\n\t\/\/ Info provides the ProtocolInfo of this TransportCredentials.\n\tInfo() ProtocolInfo\n\t\/\/ Clone makes a copy of this TransportCredentials.\n\tClone() TransportCredentials\n\t\/\/ OverrideServerName overrides the server name used to verify the hostname on the returned certificates from the server.\n\t\/\/ gRPC internals also use it to override the virtual hosting name if it is set.\n\t\/\/ It must be called before dialing. Currently, this is only used by grpclb.\n\tOverrideServerName(string) error\n}\n\n\/\/ TLSInfo contains the auth information for a TLS authenticated connection.\n\/\/ It implements the AuthInfo interface.\ntype TLSInfo struct {\n\tState tls.ConnectionState\n}\n\n\/\/ AuthType returns the type of TLSInfo as a string.\nfunc (t TLSInfo) AuthType() string {\n\treturn \"tls\"\n}\n\n\/\/ tlsCreds is the credentials required for authenticating a connection using TLS.\ntype tlsCreds struct {\n\t\/\/ TLS configuration\n\tconfig *tls.Config\n}\n\nfunc (c tlsCreds) Info() ProtocolInfo {\n\treturn ProtocolInfo{\n\t\tSecurityProtocol: \"tls\",\n\t\tSecurityVersion:  \"1.2\",\n\t\tServerName:       c.config.ServerName,\n\t}\n}\n\nfunc (c *tlsCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) {\n\t\/\/ use local cfg to avoid clobbering ServerName if using multiple endpoints\n\tcfg := cloneTLSConfig(c.config)\n\tif cfg.ServerName == \"\" {\n\t\tcolonPos := strings.LastIndex(addr, \":\")\n\t\tif colonPos == -1 {\n\t\t\tcolonPos = len(addr)\n\t\t}\n\t\tcfg.ServerName = addr[:colonPos]\n\t}\n\tconn := tls.Client(rawConn, cfg)\n\terrChannel := make(chan error, 1)\n\tgo func() {\n\t\terrChannel <- conn.Handshake()\n\t}()\n\tselect {\n\tcase err := <-errChannel:\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\tcase <-ctx.Done():\n\t\treturn nil, nil, ctx.Err()\n\t}\n\treturn conn, TLSInfo{conn.ConnectionState()}, nil\n}\n\nfunc (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) {\n\tconn := tls.Server(rawConn, c.config)\n\tif err := conn.Handshake(); err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn conn, TLSInfo{conn.ConnectionState()}, nil\n}\n\nfunc (c *tlsCreds) Clone() TransportCredentials {\n\treturn NewTLS(c.config)\n}\n\nfunc (c *tlsCreds) OverrideServerName(serverNameOverride string) error {\n\tc.config.ServerName = serverNameOverride\n\treturn nil\n}\n\n\/\/ NewTLS uses c to construct a TransportCredentials based on TLS.\nfunc NewTLS(c *tls.Config) TransportCredentials {\n\ttc := &tlsCreds{cloneTLSConfig(c)}\n\ttc.config.NextProtos = alpnProtoStr\n\treturn tc\n}\n\n\/\/ NewClientTLSFromCert constructs a TLS from the input certificate for client.\n\/\/ serverNameOverride is for testing only. If set to a non empty string,\n\/\/ it will override the virtual host name of authority (e.g. :authority header field) in requests.\nfunc NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials {\n\treturn NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp})\n}\n\n\/\/ NewClientTLSFromFile constructs a TLS from the input certificate file for client.\n\/\/ serverNameOverride is for testing only. If set to a non empty string,\n\/\/ it will override the virtual host name of authority (e.g. :authority header field) in requests.\nfunc NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) {\n\tb, err := ioutil.ReadFile(certFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcp := x509.NewCertPool()\n\tif !cp.AppendCertsFromPEM(b) {\n\t\treturn nil, fmt.Errorf(\"credentials: failed to append certificates\")\n\t}\n\treturn NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil\n}\n\n\/\/ NewServerTLSFromCert constructs a TLS from the input certificate for server.\nfunc NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials {\n\treturn NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}})\n}\n\n\/\/ NewServerTLSFromFile constructs a TLS from the input certificate file and key\n\/\/ file for server.\nfunc NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) {\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil\n}\n<commit_msg>add document to ClientHandshake about returning temporary error (#1125)<commit_after>\/*\n *\n * Copyright 2014, Google Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n *     * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n *     * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n\/\/ Package credentials implements various credentials supported by gRPC library,\n\/\/ which encapsulate all the state needed by a client to authenticate with a\n\/\/ server and make various assertions, e.g., about the client's identity, role,\n\/\/ or whether it is authorized to make a particular call.\npackage credentials \/\/ import \"google.golang.org\/grpc\/credentials\"\n\nimport (\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"strings\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar (\n\t\/\/ alpnProtoStr are the specified application level protocols for gRPC.\n\talpnProtoStr = []string{\"h2\"}\n)\n\n\/\/ PerRPCCredentials defines the common interface for the credentials which need to\n\/\/ attach security information to every RPC (e.g., oauth2).\ntype PerRPCCredentials interface {\n\t\/\/ GetRequestMetadata gets the current request metadata, refreshing\n\t\/\/ tokens if required. This should be called by the transport layer on\n\t\/\/ each request, and the data should be populated in headers or other\n\t\/\/ context. uri is the URI of the entry point for the request. When\n\t\/\/ supported by the underlying implementation, ctx can be used for\n\t\/\/ timeout and cancellation.\n\t\/\/ TODO(zhaoq): Define the set of the qualified keys instead of leaving\n\t\/\/ it as an arbitrary string.\n\tGetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)\n\t\/\/ RequireTransportSecurity indicates whether the credentials requires\n\t\/\/ transport security.\n\tRequireTransportSecurity() bool\n}\n\n\/\/ ProtocolInfo provides information regarding the gRPC wire protocol version,\n\/\/ security protocol, security protocol version in use, server name, etc.\ntype ProtocolInfo struct {\n\t\/\/ ProtocolVersion is the gRPC wire protocol version.\n\tProtocolVersion string\n\t\/\/ SecurityProtocol is the security protocol in use.\n\tSecurityProtocol string\n\t\/\/ SecurityVersion is the security protocol version.\n\tSecurityVersion string\n\t\/\/ ServerName is the user-configured server name.\n\tServerName string\n}\n\n\/\/ AuthInfo defines the common interface for the auth information the users are interested in.\ntype AuthInfo interface {\n\tAuthType() string\n}\n\nvar (\n\t\/\/ ErrConnDispatched indicates that rawConn has been dispatched out of gRPC\n\t\/\/ and the caller should not close rawConn.\n\tErrConnDispatched = errors.New(\"credentials: rawConn is dispatched out of gRPC\")\n)\n\n\/\/ TransportCredentials defines the common interface for all the live gRPC wire\n\/\/ protocols and supported transport security protocols (e.g., TLS, SSL).\ntype TransportCredentials interface {\n\t\/\/ ClientHandshake does the authentication handshake specified by the corresponding\n\t\/\/ authentication protocol on rawConn for clients. It returns the authenticated\n\t\/\/ connection and the corresponding auth information about the connection.\n\t\/\/ Implementations must use the provided context to implement timely cancellation.\n\t\/\/ gRPC will try to reconnect if the error returned is a temporary error\n\t\/\/ (io.EOF, context.DeadlineExceeded or err.Temporary() == true).\n\t\/\/ If the returned error is a wrapper error, implementations should make sure that\n\t\/\/ the error implements Temporary() to have the correct retry behaviors.\n\tClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error)\n\t\/\/ ServerHandshake does the authentication handshake for servers. It returns\n\t\/\/ the authenticated connection and the corresponding auth information about\n\t\/\/ the connection.\n\tServerHandshake(net.Conn) (net.Conn, AuthInfo, error)\n\t\/\/ Info provides the ProtocolInfo of this TransportCredentials.\n\tInfo() ProtocolInfo\n\t\/\/ Clone makes a copy of this TransportCredentials.\n\tClone() TransportCredentials\n\t\/\/ OverrideServerName overrides the server name used to verify the hostname on the returned certificates from the server.\n\t\/\/ gRPC internals also use it to override the virtual hosting name if it is set.\n\t\/\/ It must be called before dialing. Currently, this is only used by grpclb.\n\tOverrideServerName(string) error\n}\n\n\/\/ TLSInfo contains the auth information for a TLS authenticated connection.\n\/\/ It implements the AuthInfo interface.\ntype TLSInfo struct {\n\tState tls.ConnectionState\n}\n\n\/\/ AuthType returns the type of TLSInfo as a string.\nfunc (t TLSInfo) AuthType() string {\n\treturn \"tls\"\n}\n\n\/\/ tlsCreds is the credentials required for authenticating a connection using TLS.\ntype tlsCreds struct {\n\t\/\/ TLS configuration\n\tconfig *tls.Config\n}\n\nfunc (c tlsCreds) Info() ProtocolInfo {\n\treturn ProtocolInfo{\n\t\tSecurityProtocol: \"tls\",\n\t\tSecurityVersion:  \"1.2\",\n\t\tServerName:       c.config.ServerName,\n\t}\n}\n\nfunc (c *tlsCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) {\n\t\/\/ use local cfg to avoid clobbering ServerName if using multiple endpoints\n\tcfg := cloneTLSConfig(c.config)\n\tif cfg.ServerName == \"\" {\n\t\tcolonPos := strings.LastIndex(addr, \":\")\n\t\tif colonPos == -1 {\n\t\t\tcolonPos = len(addr)\n\t\t}\n\t\tcfg.ServerName = addr[:colonPos]\n\t}\n\tconn := tls.Client(rawConn, cfg)\n\terrChannel := make(chan error, 1)\n\tgo func() {\n\t\terrChannel <- conn.Handshake()\n\t}()\n\tselect {\n\tcase err := <-errChannel:\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\tcase <-ctx.Done():\n\t\treturn nil, nil, ctx.Err()\n\t}\n\treturn conn, TLSInfo{conn.ConnectionState()}, nil\n}\n\nfunc (c *tlsCreds) ServerHandshake(rawConn net.Conn) (net.Conn, AuthInfo, error) {\n\tconn := tls.Server(rawConn, c.config)\n\tif err := conn.Handshake(); err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn conn, TLSInfo{conn.ConnectionState()}, nil\n}\n\nfunc (c *tlsCreds) Clone() TransportCredentials {\n\treturn NewTLS(c.config)\n}\n\nfunc (c *tlsCreds) OverrideServerName(serverNameOverride string) error {\n\tc.config.ServerName = serverNameOverride\n\treturn nil\n}\n\n\/\/ NewTLS uses c to construct a TransportCredentials based on TLS.\nfunc NewTLS(c *tls.Config) TransportCredentials {\n\ttc := &tlsCreds{cloneTLSConfig(c)}\n\ttc.config.NextProtos = alpnProtoStr\n\treturn tc\n}\n\n\/\/ NewClientTLSFromCert constructs a TLS from the input certificate for client.\n\/\/ serverNameOverride is for testing only. If set to a non empty string,\n\/\/ it will override the virtual host name of authority (e.g. :authority header field) in requests.\nfunc NewClientTLSFromCert(cp *x509.CertPool, serverNameOverride string) TransportCredentials {\n\treturn NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp})\n}\n\n\/\/ NewClientTLSFromFile constructs a TLS from the input certificate file for client.\n\/\/ serverNameOverride is for testing only. If set to a non empty string,\n\/\/ it will override the virtual host name of authority (e.g. :authority header field) in requests.\nfunc NewClientTLSFromFile(certFile, serverNameOverride string) (TransportCredentials, error) {\n\tb, err := ioutil.ReadFile(certFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcp := x509.NewCertPool()\n\tif !cp.AppendCertsFromPEM(b) {\n\t\treturn nil, fmt.Errorf(\"credentials: failed to append certificates\")\n\t}\n\treturn NewTLS(&tls.Config{ServerName: serverNameOverride, RootCAs: cp}), nil\n}\n\n\/\/ NewServerTLSFromCert constructs a TLS from the input certificate for server.\nfunc NewServerTLSFromCert(cert *tls.Certificate) TransportCredentials {\n\treturn NewTLS(&tls.Config{Certificates: []tls.Certificate{*cert}})\n}\n\n\/\/ NewServerTLSFromFile constructs a TLS from the input certificate file and key\n\/\/ file for server.\nfunc NewServerTLSFromFile(certFile, keyFile string) (TransportCredentials, error) {\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}}), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package credentials provides credentials management for Kerberos 5 authentication.\npackage credentials\n\nimport (\n\t\"github.com\/hashicorp\/go-uuid\"\n\t\"gopkg.in\/jcmturner\/gokrb5.v2\/iana\/nametype\"\n\t\"gopkg.in\/jcmturner\/gokrb5.v2\/keytab\"\n\t\"gopkg.in\/jcmturner\/gokrb5.v2\/types\"\n\t\"time\"\n\t\"strings\"\n)\n\nconst (\n\t\/\/ AttributeKeyADCredentials assigned number for AD credentials.\n\tAttributeKeyADCredentials = 1\n)\n\n\/\/ Credentials struct for a user.\n\/\/ Contains either a keytab, password or both.\n\/\/ Keytabs are used over passwords if both are defined.\ntype Credentials struct {\n\tUsername        string\n\tdisplayName     string\n\tRealm           string\n\tCName           types.PrincipalName\n\tKeytab          keytab.Keytab\n\tPassword        string\n\tAttributes      map[int]interface{}\n\tauthenticated   bool\n\thuman           bool\n\tauthTime        time.Time\n\tgroupMembership map[string]bool\n\tsessionID       string\n}\n\n\/\/ ADCredentials contains information obtained from the PAC.\ntype ADCredentials struct {\n\tEffectiveName       string\n\tFullName            string\n\tUserID              int\n\tPrimaryGroupID      int\n\tLogOnTime           time.Time\n\tLogOffTime          time.Time\n\tPasswordLastSet     time.Time\n\tGroupMembershipSIDs []string\n\tLogonDomainName     string\n\tLogonDomainID       string\n\tLogonServer         string\n}\n\n\/\/ NewCredentials creates a new Credentials instance.\nfunc NewCredentials(username string, realm string) Credentials {\n\tuid, err := uuid.GenerateUUID()\n\tif err != nil {\n\t\tuid = \"00unique-sess-ions-uuid-unavailable0\"\n\t}\n\treturn Credentials{\n\t\tUsername:    username,\n\t\tdisplayName: username,\n\t\tRealm:       realm,\n\t\tCName: types.PrincipalName{\n\t\t\tNameType:   nametype.KRB_NT_PRINCIPAL,\n\t\t\tNameString: strings.Split(username, \"\/\"),\n\t\t},\n\t\tKeytab:     keytab.NewKeytab(),\n\t\tAttributes: make(map[int]interface{}),\n\t\tsessionID:  uid,\n\t}\n}\n\n\/\/ NewCredentialsFromPrincipal creates a new Credentials instance with the user details provides as a PrincipalName type.\nfunc NewCredentialsFromPrincipal(cname types.PrincipalName, realm string) Credentials {\n\tuid, err := uuid.GenerateUUID()\n\tif err != nil {\n\t\tuid = \"00unique-sess-ions-uuid-unavailable0\"\n\t}\n\treturn Credentials{\n\t\tUsername:        cname.GetPrincipalNameString(),\n\t\tdisplayName:     cname.GetPrincipalNameString(),\n\t\tRealm:           realm,\n\t\tCName:           cname,\n\t\tKeytab:          keytab.NewKeytab(),\n\t\tAttributes:      make(map[int]interface{}),\n\t\tgroupMembership: make(map[string]bool),\n\t\tsessionID:       uid,\n\t}\n}\n\n\/\/ WithKeytab sets the Keytab in the Credentials struct.\nfunc (c *Credentials) WithKeytab(kt keytab.Keytab) *Credentials {\n\tc.Keytab = kt\n\treturn c\n}\n\n\/\/ WithPassword sets the password in the Credentials struct.\nfunc (c *Credentials) WithPassword(password string) *Credentials {\n\tc.Password = password\n\treturn c\n}\n\n\/\/ HasKeytab queries if the Credentials has a keytab defined.\nfunc (c *Credentials) HasKeytab() bool {\n\tif len(c.Keytab.Entries) > 0 {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ HasPassword queries if the Credentials has a password defined.\nfunc (c *Credentials) HasPassword() bool {\n\tif c.Password != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ SetADCredentials adds ADCredentials attributes to the credentials\nfunc (c *Credentials) SetADCredentials(a ADCredentials) {\n\tc.Attributes[AttributeKeyADCredentials] = a\n\tif a.FullName != \"\" {\n\t\tc.SetDisplayName(a.FullName)\n\t}\n\tif a.EffectiveName != \"\" {\n\t\tc.SetUserName(a.EffectiveName)\n\t}\n\tif a.LogonDomainName != \"\" {\n\t\tc.SetDomain(a.LogonDomainName)\n\t}\n\tfor i := range a.GroupMembershipSIDs {\n\t\tc.AddAuthzAttribute(a.GroupMembershipSIDs[i])\n\t}\n}\n\n\/\/ Methods to implement goidentity.Identity interface\n\n\/\/ UserName returns the credential's username.\nfunc (c *Credentials) UserName() string {\n\treturn c.Username\n}\n\n\/\/ SetUserName sets the username value on the credential.\nfunc (c *Credentials) SetUserName(s string) {\n\tc.Username = s\n}\n\n\/\/ Domain returns the credential's domain.\nfunc (c *Credentials) Domain() string {\n\treturn c.Realm\n}\n\n\/\/ SetDomain sets the domain value on the credential.\nfunc (c *Credentials) SetDomain(s string) {\n\tc.Realm = s\n}\n\n\/\/ DisplayName returns the credential's display name.\nfunc (c *Credentials) DisplayName() string {\n\treturn c.displayName\n}\n\n\/\/ SetDisplayName sets the display name value on the credential.\nfunc (c *Credentials) SetDisplayName(s string) {\n\tc.displayName = s\n}\n\n\/\/ Human returns if the  credential represents a human or not.\nfunc (c *Credentials) Human() bool {\n\treturn c.human\n}\n\n\/\/ SetHuman sets the credential as human.\nfunc (c *Credentials) SetHuman(b bool) {\n\tc.human = b\n}\n\n\/\/ AuthTime returns the time the credential was authenticated.\nfunc (c *Credentials) AuthTime() time.Time {\n\treturn c.authTime\n}\n\n\/\/ SetAuthTime sets the time the credential was authenticated.\nfunc (c *Credentials) SetAuthTime(t time.Time) {\n\tc.authTime = t\n}\n\n\/\/ AuthzAttributes returns the credentials authorizing attributes.\nfunc (c *Credentials) AuthzAttributes() []string {\n\ts := make([]string, len(c.groupMembership))\n\ti := 0\n\tfor a := range c.groupMembership {\n\t\ts[i] = a\n\t\ti++\n\t}\n\treturn s\n}\n\n\/\/ Authenticated indicates if the credential has been successfully authenticated or not.\nfunc (c *Credentials) Authenticated() bool {\n\treturn c.authenticated\n}\n\n\/\/ SetAuthenticated sets the credential as having been successfully authenticated.\nfunc (c *Credentials) SetAuthenticated(b bool) {\n\tc.authenticated = b\n}\n\n\/\/ AddAuthzAttribute adds an authorization attribute to the credential.\nfunc (c *Credentials) AddAuthzAttribute(a string) {\n\tc.groupMembership[a] = true\n}\n\n\/\/ RemoveAuthzAttribute removes an authorization attribute from the credential.\nfunc (c *Credentials) RemoveAuthzAttribute(a string) {\n\tif _, ok := c.groupMembership[a]; !ok {\n\t\treturn\n\t}\n\tdelete(c.groupMembership, a)\n}\n\n\/\/ EnableAuthzAttribute toggles an authorization attribute to an enabled state on the credential.\nfunc (c *Credentials) EnableAuthzAttribute(a string) {\n\tif enabled, ok := c.groupMembership[a]; ok && !enabled {\n\t\tc.groupMembership[a] = true\n\t}\n}\n\n\/\/ DisableAuthzAttribute toggles an authorization attribute to a disabled state on the credential.\nfunc (c *Credentials) DisableAuthzAttribute(a string) {\n\tif enabled, ok := c.groupMembership[a]; ok && enabled {\n\t\tc.groupMembership[a] = false\n\t}\n}\n\n\/\/ Authorized indicates if the credential has the specified authorizing attribute.\nfunc (c *Credentials) Authorized(a string) bool {\n\tif enabled, ok := c.groupMembership[a]; ok && enabled {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ SessionID returns the credential's session ID.\nfunc (c *Credentials) SessionID() string {\n\treturn c.sessionID\n}\n<commit_msg>gofmt<commit_after>\/\/ Package credentials provides credentials management for Kerberos 5 authentication.\npackage credentials\n\nimport (\n\t\"github.com\/hashicorp\/go-uuid\"\n\t\"gopkg.in\/jcmturner\/gokrb5.v2\/iana\/nametype\"\n\t\"gopkg.in\/jcmturner\/gokrb5.v2\/keytab\"\n\t\"gopkg.in\/jcmturner\/gokrb5.v2\/types\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ AttributeKeyADCredentials assigned number for AD credentials.\n\tAttributeKeyADCredentials = 1\n)\n\n\/\/ Credentials struct for a user.\n\/\/ Contains either a keytab, password or both.\n\/\/ Keytabs are used over passwords if both are defined.\ntype Credentials struct {\n\tUsername        string\n\tdisplayName     string\n\tRealm           string\n\tCName           types.PrincipalName\n\tKeytab          keytab.Keytab\n\tPassword        string\n\tAttributes      map[int]interface{}\n\tauthenticated   bool\n\thuman           bool\n\tauthTime        time.Time\n\tgroupMembership map[string]bool\n\tsessionID       string\n}\n\n\/\/ ADCredentials contains information obtained from the PAC.\ntype ADCredentials struct {\n\tEffectiveName       string\n\tFullName            string\n\tUserID              int\n\tPrimaryGroupID      int\n\tLogOnTime           time.Time\n\tLogOffTime          time.Time\n\tPasswordLastSet     time.Time\n\tGroupMembershipSIDs []string\n\tLogonDomainName     string\n\tLogonDomainID       string\n\tLogonServer         string\n}\n\n\/\/ NewCredentials creates a new Credentials instance.\nfunc NewCredentials(username string, realm string) Credentials {\n\tuid, err := uuid.GenerateUUID()\n\tif err != nil {\n\t\tuid = \"00unique-sess-ions-uuid-unavailable0\"\n\t}\n\treturn Credentials{\n\t\tUsername:    username,\n\t\tdisplayName: username,\n\t\tRealm:       realm,\n\t\tCName: types.PrincipalName{\n\t\t\tNameType:   nametype.KRB_NT_PRINCIPAL,\n\t\t\tNameString: strings.Split(username, \"\/\"),\n\t\t},\n\t\tKeytab:     keytab.NewKeytab(),\n\t\tAttributes: make(map[int]interface{}),\n\t\tsessionID:  uid,\n\t}\n}\n\n\/\/ NewCredentialsFromPrincipal creates a new Credentials instance with the user details provides as a PrincipalName type.\nfunc NewCredentialsFromPrincipal(cname types.PrincipalName, realm string) Credentials {\n\tuid, err := uuid.GenerateUUID()\n\tif err != nil {\n\t\tuid = \"00unique-sess-ions-uuid-unavailable0\"\n\t}\n\treturn Credentials{\n\t\tUsername:        cname.GetPrincipalNameString(),\n\t\tdisplayName:     cname.GetPrincipalNameString(),\n\t\tRealm:           realm,\n\t\tCName:           cname,\n\t\tKeytab:          keytab.NewKeytab(),\n\t\tAttributes:      make(map[int]interface{}),\n\t\tgroupMembership: make(map[string]bool),\n\t\tsessionID:       uid,\n\t}\n}\n\n\/\/ WithKeytab sets the Keytab in the Credentials struct.\nfunc (c *Credentials) WithKeytab(kt keytab.Keytab) *Credentials {\n\tc.Keytab = kt\n\treturn c\n}\n\n\/\/ WithPassword sets the password in the Credentials struct.\nfunc (c *Credentials) WithPassword(password string) *Credentials {\n\tc.Password = password\n\treturn c\n}\n\n\/\/ HasKeytab queries if the Credentials has a keytab defined.\nfunc (c *Credentials) HasKeytab() bool {\n\tif len(c.Keytab.Entries) > 0 {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ HasPassword queries if the Credentials has a password defined.\nfunc (c *Credentials) HasPassword() bool {\n\tif c.Password != \"\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ SetADCredentials adds ADCredentials attributes to the credentials\nfunc (c *Credentials) SetADCredentials(a ADCredentials) {\n\tc.Attributes[AttributeKeyADCredentials] = a\n\tif a.FullName != \"\" {\n\t\tc.SetDisplayName(a.FullName)\n\t}\n\tif a.EffectiveName != \"\" {\n\t\tc.SetUserName(a.EffectiveName)\n\t}\n\tif a.LogonDomainName != \"\" {\n\t\tc.SetDomain(a.LogonDomainName)\n\t}\n\tfor i := range a.GroupMembershipSIDs {\n\t\tc.AddAuthzAttribute(a.GroupMembershipSIDs[i])\n\t}\n}\n\n\/\/ Methods to implement goidentity.Identity interface\n\n\/\/ UserName returns the credential's username.\nfunc (c *Credentials) UserName() string {\n\treturn c.Username\n}\n\n\/\/ SetUserName sets the username value on the credential.\nfunc (c *Credentials) SetUserName(s string) {\n\tc.Username = s\n}\n\n\/\/ Domain returns the credential's domain.\nfunc (c *Credentials) Domain() string {\n\treturn c.Realm\n}\n\n\/\/ SetDomain sets the domain value on the credential.\nfunc (c *Credentials) SetDomain(s string) {\n\tc.Realm = s\n}\n\n\/\/ DisplayName returns the credential's display name.\nfunc (c *Credentials) DisplayName() string {\n\treturn c.displayName\n}\n\n\/\/ SetDisplayName sets the display name value on the credential.\nfunc (c *Credentials) SetDisplayName(s string) {\n\tc.displayName = s\n}\n\n\/\/ Human returns if the  credential represents a human or not.\nfunc (c *Credentials) Human() bool {\n\treturn c.human\n}\n\n\/\/ SetHuman sets the credential as human.\nfunc (c *Credentials) SetHuman(b bool) {\n\tc.human = b\n}\n\n\/\/ AuthTime returns the time the credential was authenticated.\nfunc (c *Credentials) AuthTime() time.Time {\n\treturn c.authTime\n}\n\n\/\/ SetAuthTime sets the time the credential was authenticated.\nfunc (c *Credentials) SetAuthTime(t time.Time) {\n\tc.authTime = t\n}\n\n\/\/ AuthzAttributes returns the credentials authorizing attributes.\nfunc (c *Credentials) AuthzAttributes() []string {\n\ts := make([]string, len(c.groupMembership))\n\ti := 0\n\tfor a := range c.groupMembership {\n\t\ts[i] = a\n\t\ti++\n\t}\n\treturn s\n}\n\n\/\/ Authenticated indicates if the credential has been successfully authenticated or not.\nfunc (c *Credentials) Authenticated() bool {\n\treturn c.authenticated\n}\n\n\/\/ SetAuthenticated sets the credential as having been successfully authenticated.\nfunc (c *Credentials) SetAuthenticated(b bool) {\n\tc.authenticated = b\n}\n\n\/\/ AddAuthzAttribute adds an authorization attribute to the credential.\nfunc (c *Credentials) AddAuthzAttribute(a string) {\n\tc.groupMembership[a] = true\n}\n\n\/\/ RemoveAuthzAttribute removes an authorization attribute from the credential.\nfunc (c *Credentials) RemoveAuthzAttribute(a string) {\n\tif _, ok := c.groupMembership[a]; !ok {\n\t\treturn\n\t}\n\tdelete(c.groupMembership, a)\n}\n\n\/\/ EnableAuthzAttribute toggles an authorization attribute to an enabled state on the credential.\nfunc (c *Credentials) EnableAuthzAttribute(a string) {\n\tif enabled, ok := c.groupMembership[a]; ok && !enabled {\n\t\tc.groupMembership[a] = true\n\t}\n}\n\n\/\/ DisableAuthzAttribute toggles an authorization attribute to a disabled state on the credential.\nfunc (c *Credentials) DisableAuthzAttribute(a string) {\n\tif enabled, ok := c.groupMembership[a]; ok && enabled {\n\t\tc.groupMembership[a] = false\n\t}\n}\n\n\/\/ Authorized indicates if the credential has the specified authorizing attribute.\nfunc (c *Credentials) Authorized(a string) bool {\n\tif enabled, ok := c.groupMembership[a]; ok && enabled {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ SessionID returns the credential's session ID.\nfunc (c *Credentials) SessionID() string {\n\treturn c.sessionID\n}\n<|endoftext|>"}
{"text":"<commit_before>package redisc\n\nimport (\n\t\"net\"\n\t\"strconv\"\n\t\"sync\/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/PuerkitoBio\/juggler\/internal\/redistest\"\n\t\"github.com\/PuerkitoBio\/juggler\/internal\/redistest\/resp\"\n\t\"github.com\/garyburd\/redigo\/redis\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc TestRetryConnAsk(t *testing.T) {\n\tvar s *redistest.MockServer\n\tvar asking int32\n\n\ts = redistest.StartMockServer(t, func(cmd string, args ...string) interface{} {\n\t\tswitch cmd {\n\t\tcase \"CLUSTER\":\n\t\t\taddr, port, _ := net.SplitHostPort(s.Addr)\n\t\t\tnPort, _ := strconv.Atoi(port)\n\t\t\treturn resp.Array{\n\t\t\t\tresp.Array{int64(0), int64(16383), resp.Array{addr, int64(nPort)}},\n\t\t\t}\n\t\tcase \"GET\":\n\t\t\tif atomic.LoadInt32(&asking) == 0 {\n\t\t\t\treturn resp.Error(\"ASK 1234 \" + s.Addr)\n\t\t\t}\n\t\t\treturn \"ok\"\n\t\tcase \"ASKING\":\n\t\t\tatomic.AddInt32(&asking, 1)\n\t\t\treturn nil\n\t\t}\n\n\t\treturn resp.Error(\"unexpected command \" + cmd)\n\t})\n\tdefer s.Close()\n\n\tc := &Cluster{\n\t\tStartupNodes: []string{s.Addr},\n\t}\n\tdefer c.Close()\n\trequire.NoError(t, c.Refresh(), \"Refresh\")\n\n\tconn := c.Get()\n\tdefer conn.Close()\n\n\t_, err := conn.Do(\"GET\", \"x\")\n\tif assert.Error(t, err, \"GET without retry\") {\n\t\tre := ParseRedir(err)\n\t\tif assert.NotNil(t, re, \"ParseRedir\") {\n\t\t\tassert.Equal(t, \"ASK\", re.Type, \"ASK\")\n\t\t}\n\t}\n\n\trc, err := RetryConn(conn, 3, time.Second)\n\trequire.NoError(t, err, \"RetryConn\")\n\tv, err := rc.Do(\"GET\", \"x\")\n\tif assert.NoError(t, err, \"GET with retry\") {\n\t\tassert.Equal(t, []byte(\"ok\"), v, \"expected result\")\n\t}\n}\n\nfunc TestRetryConnTryAgain(t *testing.T) {\n\tvar s *redistest.MockServer\n\tvar tryagain int32\n\n\ts = redistest.StartMockServer(t, func(cmd string, args ...string) interface{} {\n\t\tswitch cmd {\n\t\tcase \"CLUSTER\":\n\t\t\taddr, port, _ := net.SplitHostPort(s.Addr)\n\t\t\tnPort, _ := strconv.Atoi(port)\n\t\t\treturn resp.Array{\n\t\t\t\tresp.Array{int64(0), int64(16383), resp.Array{addr, int64(nPort)}},\n\t\t\t}\n\t\tcase \"GET\":\n\t\t\tif atomic.LoadInt32(&tryagain) < 2 {\n\t\t\t\tatomic.AddInt32(&tryagain, 1)\n\t\t\t\treturn resp.Error(\"TRYAGAIN\")\n\t\t\t}\n\t\t\treturn \"ok\"\n\t\t}\n\t\treturn resp.Error(\"unexpected command \" + cmd)\n\t})\n\tdefer s.Close()\n\n\tc := &Cluster{\n\t\tStartupNodes: []string{s.Addr},\n\t}\n\tdefer c.Close()\n\trequire.NoError(t, c.Refresh(), \"Refresh\")\n\n\tconn := c.Get()\n\tdefer conn.Close()\n\n\t_, err := conn.Do(\"GET\", \"x\")\n\tif assert.Error(t, err, \"GET without retry\") {\n\t\tassert.True(t, IsTryAgain(err), \"IsTryAgain\")\n\t}\n\n\trc, err := RetryConn(conn, 3, 1*time.Millisecond)\n\trequire.NoError(t, err, \"RetryConn\")\n\tv, err := rc.Do(\"GET\", \"x\")\n\tif assert.NoError(t, err, \"GET with retry\") {\n\t\tassert.Equal(t, []byte(\"ok\"), v, \"expected result\")\n\t}\n}\n\nfunc TestRetryConnErrs(t *testing.T) {\n\tc := &Cluster{\n\t\tStartupNodes: []string{\":6379\"},\n\t}\n\tconn := c.Get()\n\trequire.NoError(t, conn.Close(), \"Close\")\n\n\trc, err := RetryConn(conn, 3, time.Second)\n\trequire.NoError(t, err, \"RetryConn\")\n\t_, err = rc.Do(\"A\")\n\tassert.Error(t, err, \"Do after Close\")\n\tassert.Error(t, rc.Err(), \"Err after Close\")\n\tassert.Error(t, rc.Flush(), \"Flush\")\n\t_, err = rc.Receive()\n\tassert.Error(t, err, \"Receive\")\n\tassert.Error(t, rc.Send(\"A\"), \"Send\")\n\tassert.Error(t, rc.Close(), \"Close after Close\")\n\n\t_, err = RetryConn(rc, 3, time.Second) \/\/ RetryConn, but conn is not a *Conn\n\tassert.Error(t, err, \"RetryConn with a non-*Conn\")\n}\n\nfunc TestRetryConnTooManyAttempts(t *testing.T) {\n\tfn, ports := redistest.StartCluster(t, nil)\n\tdefer fn()\n\n\tfor i, p := range ports {\n\t\tports[i] = \":\" + p\n\t}\n\tc := &Cluster{\n\t\tStartupNodes: ports,\n\t\tDialOptions:  []redis.DialOption{redis.DialConnectTimeout(2 * time.Second)},\n\t}\n\trequire.NoError(t, c.Refresh(), \"Refresh\")\n\n\t\/\/ create a connection and bind to key \"a\"\n\tconn := c.Get()\n\tdefer conn.Close()\n\trequire.NoError(t, conn.(*Conn).Bind(\"a\"), \"Bind\")\n\n\t\/\/ wrap it in a RetryConn with a single attempt allowed\n\trc, err := RetryConn(conn, 1, 100*time.Millisecond)\n\trequire.NoError(t, err, \"RetryConn\")\n\n\t_, err = rc.Do(\"SET\", \"b\", \"x\")\n\tif assert.Error(t, err, \"SET b\") {\n\t\tassert.Contains(t, err.Error(), \"too many attempts\")\n\t}\n}\n\nfunc TestRetryConnMoved(t *testing.T) {\n\tfn, ports := redistest.StartCluster(t, nil)\n\tdefer fn()\n\n\tfor i, p := range ports {\n\t\tports[i] = \":\" + p\n\t}\n\tc := &Cluster{\n\t\tStartupNodes: ports,\n\t\tDialOptions:  []redis.DialOption{redis.DialConnectTimeout(2 * time.Second)},\n\t}\n\trequire.NoError(t, c.Refresh(), \"Refresh\")\n\n\t\/\/ create a connection and bind to key \"a\"\n\tconn := c.Get()\n\tdefer conn.Close()\n\trequire.NoError(t, conn.(*Conn).Bind(\"a\"), \"Bind\")\n\n\t\/\/ cluster's mapping for \"a\" should be 15495, \"b\" is 3300, check that\n\t\/\/ the MOVED did update the mapping of \"b\", and did not touch \"a\"\n\tc.mu.Lock()\n\taddrA := c.mapping[15495]\n\taddrB := c.mapping[3300]\n\tc.mapping[3300] = \"x\"\n\tc.mu.Unlock()\n\n\t\/\/ set key \"b\", which is on a different node (generates a MOVED) - this is NOT a RetryConn\n\t_, err := conn.Do(\"SET\", \"b\", \"x\")\n\tif assert.Error(t, err, \"SET b\") {\n\t\tre := ParseRedir(err)\n\t\tif assert.NotNil(t, re, \"ParseRedir\") {\n\t\t\tassert.Equal(t, \"MOVED\", re.Type, \"Redir type\")\n\t\t}\n\t}\n\n\t\/\/ cluster updated its mapping even though it did not follow the redirection\n\tc.mu.Lock()\n\tassert.Equal(t, addrA, c.mapping[15495], \"Addr A\")\n\tassert.Equal(t, addrB, c.mapping[3300], \"Sentinel value B\")\n\tc.mapping[3300] = \"x\"\n\tc.mu.Unlock()\n\n\t\/\/ now wrap it in a RetryConn\n\trc, err := RetryConn(conn, 3, 100*time.Millisecond)\n\trequire.NoError(t, err, \"RetryConn\")\n\n\t_, err = rc.Do(\"SET\", \"b\", \"x\")\n\tassert.NoError(t, err, \"SET b\")\n\n\t\/\/ the cluster should've updated its mapping\n\tc.mu.Lock()\n\tassert.Equal(t, addrA, c.mapping[15495], \"Addr A\")\n\tassert.Equal(t, addrB, c.mapping[3300], \"Addr B\")\n\tc.mu.Unlock()\n\n\tv, err := redis.String(rc.Do(\"GET\", \"b\"))\n\tif assert.NoError(t, err, \"GET b\") {\n\t\tassert.Equal(t, \"x\", v, \"GET value\")\n\t}\n}\n<commit_msg>redisc: fix govet for composite literal<commit_after>package redisc\n\nimport (\n\t\"net\"\n\t\"strconv\"\n\t\"sync\/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/PuerkitoBio\/juggler\/internal\/redistest\"\n\t\"github.com\/PuerkitoBio\/juggler\/internal\/redistest\/resp\"\n\t\"github.com\/garyburd\/redigo\/redis\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc TestRetryConnAsk(t *testing.T) {\n\tvar s *redistest.MockServer\n\tvar asking int32\n\n\ts = redistest.StartMockServer(t, func(cmd string, args ...string) interface{} {\n\t\tswitch cmd {\n\t\tcase \"CLUSTER\":\n\t\t\taddr, port, _ := net.SplitHostPort(s.Addr)\n\t\t\tnPort, _ := strconv.Atoi(port)\n\t\t\treturn resp.Array{\n\t\t\t\t0: resp.Array{0: int64(0), 1: int64(16383), 2: resp.Array{0: addr, 1: int64(nPort)}},\n\t\t\t}\n\t\tcase \"GET\":\n\t\t\tif atomic.LoadInt32(&asking) == 0 {\n\t\t\t\treturn resp.Error(\"ASK 1234 \" + s.Addr)\n\t\t\t}\n\t\t\treturn \"ok\"\n\t\tcase \"ASKING\":\n\t\t\tatomic.AddInt32(&asking, 1)\n\t\t\treturn nil\n\t\t}\n\n\t\treturn resp.Error(\"unexpected command \" + cmd)\n\t})\n\tdefer s.Close()\n\n\tc := &Cluster{\n\t\tStartupNodes: []string{s.Addr},\n\t}\n\tdefer c.Close()\n\trequire.NoError(t, c.Refresh(), \"Refresh\")\n\n\tconn := c.Get()\n\tdefer conn.Close()\n\n\t_, err := conn.Do(\"GET\", \"x\")\n\tif assert.Error(t, err, \"GET without retry\") {\n\t\tre := ParseRedir(err)\n\t\tif assert.NotNil(t, re, \"ParseRedir\") {\n\t\t\tassert.Equal(t, \"ASK\", re.Type, \"ASK\")\n\t\t}\n\t}\n\n\trc, err := RetryConn(conn, 3, time.Second)\n\trequire.NoError(t, err, \"RetryConn\")\n\tv, err := rc.Do(\"GET\", \"x\")\n\tif assert.NoError(t, err, \"GET with retry\") {\n\t\tassert.Equal(t, []byte(\"ok\"), v, \"expected result\")\n\t}\n}\n\nfunc TestRetryConnTryAgain(t *testing.T) {\n\tvar s *redistest.MockServer\n\tvar tryagain int32\n\n\ts = redistest.StartMockServer(t, func(cmd string, args ...string) interface{} {\n\t\tswitch cmd {\n\t\tcase \"CLUSTER\":\n\t\t\taddr, port, _ := net.SplitHostPort(s.Addr)\n\t\t\tnPort, _ := strconv.Atoi(port)\n\t\t\treturn resp.Array{\n\t\t\t\t0: resp.Array{0: int64(0), 1: int64(16383), 2: resp.Array{0: addr, 1: int64(nPort)}},\n\t\t\t}\n\t\tcase \"GET\":\n\t\t\tif atomic.LoadInt32(&tryagain) < 2 {\n\t\t\t\tatomic.AddInt32(&tryagain, 1)\n\t\t\t\treturn resp.Error(\"TRYAGAIN\")\n\t\t\t}\n\t\t\treturn \"ok\"\n\t\t}\n\t\treturn resp.Error(\"unexpected command \" + cmd)\n\t})\n\tdefer s.Close()\n\n\tc := &Cluster{\n\t\tStartupNodes: []string{s.Addr},\n\t}\n\tdefer c.Close()\n\trequire.NoError(t, c.Refresh(), \"Refresh\")\n\n\tconn := c.Get()\n\tdefer conn.Close()\n\n\t_, err := conn.Do(\"GET\", \"x\")\n\tif assert.Error(t, err, \"GET without retry\") {\n\t\tassert.True(t, IsTryAgain(err), \"IsTryAgain\")\n\t}\n\n\trc, err := RetryConn(conn, 3, 1*time.Millisecond)\n\trequire.NoError(t, err, \"RetryConn\")\n\tv, err := rc.Do(\"GET\", \"x\")\n\tif assert.NoError(t, err, \"GET with retry\") {\n\t\tassert.Equal(t, []byte(\"ok\"), v, \"expected result\")\n\t}\n}\n\nfunc TestRetryConnErrs(t *testing.T) {\n\tc := &Cluster{\n\t\tStartupNodes: []string{\":6379\"},\n\t}\n\tconn := c.Get()\n\trequire.NoError(t, conn.Close(), \"Close\")\n\n\trc, err := RetryConn(conn, 3, time.Second)\n\trequire.NoError(t, err, \"RetryConn\")\n\t_, err = rc.Do(\"A\")\n\tassert.Error(t, err, \"Do after Close\")\n\tassert.Error(t, rc.Err(), \"Err after Close\")\n\tassert.Error(t, rc.Flush(), \"Flush\")\n\t_, err = rc.Receive()\n\tassert.Error(t, err, \"Receive\")\n\tassert.Error(t, rc.Send(\"A\"), \"Send\")\n\tassert.Error(t, rc.Close(), \"Close after Close\")\n\n\t_, err = RetryConn(rc, 3, time.Second) \/\/ RetryConn, but conn is not a *Conn\n\tassert.Error(t, err, \"RetryConn with a non-*Conn\")\n}\n\nfunc TestRetryConnTooManyAttempts(t *testing.T) {\n\tfn, ports := redistest.StartCluster(t, nil)\n\tdefer fn()\n\n\tfor i, p := range ports {\n\t\tports[i] = \":\" + p\n\t}\n\tc := &Cluster{\n\t\tStartupNodes: ports,\n\t\tDialOptions:  []redis.DialOption{redis.DialConnectTimeout(2 * time.Second)},\n\t}\n\trequire.NoError(t, c.Refresh(), \"Refresh\")\n\n\t\/\/ create a connection and bind to key \"a\"\n\tconn := c.Get()\n\tdefer conn.Close()\n\trequire.NoError(t, conn.(*Conn).Bind(\"a\"), \"Bind\")\n\n\t\/\/ wrap it in a RetryConn with a single attempt allowed\n\trc, err := RetryConn(conn, 1, 100*time.Millisecond)\n\trequire.NoError(t, err, \"RetryConn\")\n\n\t_, err = rc.Do(\"SET\", \"b\", \"x\")\n\tif assert.Error(t, err, \"SET b\") {\n\t\tassert.Contains(t, err.Error(), \"too many attempts\")\n\t}\n}\n\nfunc TestRetryConnMoved(t *testing.T) {\n\tfn, ports := redistest.StartCluster(t, nil)\n\tdefer fn()\n\n\tfor i, p := range ports {\n\t\tports[i] = \":\" + p\n\t}\n\tc := &Cluster{\n\t\tStartupNodes: ports,\n\t\tDialOptions:  []redis.DialOption{redis.DialConnectTimeout(2 * time.Second)},\n\t}\n\trequire.NoError(t, c.Refresh(), \"Refresh\")\n\n\t\/\/ create a connection and bind to key \"a\"\n\tconn := c.Get()\n\tdefer conn.Close()\n\trequire.NoError(t, conn.(*Conn).Bind(\"a\"), \"Bind\")\n\n\t\/\/ cluster's mapping for \"a\" should be 15495, \"b\" is 3300, check that\n\t\/\/ the MOVED did update the mapping of \"b\", and did not touch \"a\"\n\tc.mu.Lock()\n\taddrA := c.mapping[15495]\n\taddrB := c.mapping[3300]\n\tc.mapping[3300] = \"x\"\n\tc.mu.Unlock()\n\n\t\/\/ set key \"b\", which is on a different node (generates a MOVED) - this is NOT a RetryConn\n\t_, err := conn.Do(\"SET\", \"b\", \"x\")\n\tif assert.Error(t, err, \"SET b\") {\n\t\tre := ParseRedir(err)\n\t\tif assert.NotNil(t, re, \"ParseRedir\") {\n\t\t\tassert.Equal(t, \"MOVED\", re.Type, \"Redir type\")\n\t\t}\n\t}\n\n\t\/\/ cluster updated its mapping even though it did not follow the redirection\n\tc.mu.Lock()\n\tassert.Equal(t, addrA, c.mapping[15495], \"Addr A\")\n\tassert.Equal(t, addrB, c.mapping[3300], \"Sentinel value B\")\n\tc.mapping[3300] = \"x\"\n\tc.mu.Unlock()\n\n\t\/\/ now wrap it in a RetryConn\n\trc, err := RetryConn(conn, 3, 100*time.Millisecond)\n\trequire.NoError(t, err, \"RetryConn\")\n\n\t_, err = rc.Do(\"SET\", \"b\", \"x\")\n\tassert.NoError(t, err, \"SET b\")\n\n\t\/\/ the cluster should've updated its mapping\n\tc.mu.Lock()\n\tassert.Equal(t, addrA, c.mapping[15495], \"Addr A\")\n\tassert.Equal(t, addrB, c.mapping[3300], \"Addr B\")\n\tc.mu.Unlock()\n\n\tv, err := redis.String(rc.Do(\"GET\", \"b\"))\n\tif assert.NoError(t, err, \"GET b\") {\n\t\tassert.Equal(t, \"x\", v, \"GET value\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package docker\n\nimport (\n\t\"context\"\n\t\"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/client\"\n\t\"github.com\/pterodactyl\/wings\/api\"\n\t\"github.com\/pterodactyl\/wings\/environment\"\n\t\"github.com\/pterodactyl\/wings\/events\"\n\t\"github.com\/pterodactyl\/wings\/system\"\n\t\"io\"\n\t\"sync\"\n)\n\ntype Metadata struct {\n\tImage string\n\tStop  api.ProcessStopConfiguration\n}\n\n\/\/ Ensure that the Docker environment is always implementing all of the methods\n\/\/ from the base environment interface.\nvar _ environment.ProcessEnvironment = (*Environment)(nil)\n\ntype Environment struct {\n\tmu      sync.RWMutex\n\teventMu sync.Mutex\n\n\t\/\/ The public identifier for this environment. In this case it is the Docker container\n\t\/\/ name that will be used for all instances created under it.\n\tId string\n\n\t\/\/ The environment configuration.\n\tConfiguration *environment.Configuration\n\n\tmeta *Metadata\n\n\t\/\/ The Docker client being used for this instance.\n\tclient *client.Client\n\n\t\/\/ Controls the hijacked response stream which exists only when we're attached to\n\t\/\/ the running container instance.\n\tstream *types.HijackedResponse\n\n\t\/\/ Holds the stats stream used by the polling commands so that we can easily close it out.\n\tstats io.ReadCloser\n\n\temitter *events.EventBus\n\n\t\/\/ Tracks the environment state.\n\tst *system.AtomicString\n}\n\n\/\/ Creates a new base Docker environment. The ID passed through will be the ID that is used to\n\/\/ reference the container from here on out. This should be unique per-server (we use the UUID\n\/\/ by default). The container does not need to exist at this point.\nfunc New(id string, m *Metadata, c *environment.Configuration) (*Environment, error) {\n\tcli, err := environment.DockerClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\te := &Environment{\n\t\tId:            id,\n\t\tConfiguration: c,\n\t\tmeta:          m,\n\t\tclient:        cli,\n\t\tst:            system.NewAtomicString(environment.ProcessOfflineState),\n\t}\n\n\treturn e, nil\n}\n\nfunc (e *Environment) Type() string {\n\treturn \"docker\"\n}\n\n\/\/ Set if this process is currently attached to the process.\nfunc (e *Environment) SetStream(s *types.HijackedResponse) {\n\te.mu.Lock()\n\te.stream = s\n\te.mu.Unlock()\n}\n\n\/\/ Determine if the this process is currently attached to the container.\nfunc (e *Environment) IsAttached() bool {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\n\treturn e.stream != nil\n}\n\nfunc (e *Environment) Events() *events.EventBus {\n\te.eventMu.Lock()\n\tdefer e.eventMu.Unlock()\n\n\tif e.emitter == nil {\n\t\te.emitter = events.New()\n\t}\n\n\treturn e.emitter\n}\n\n\/\/ Determines if the container exists in this environment. The ID passed through should be the\n\/\/ server UUID since containers are created utilizing the server UUID as the name and docker\n\/\/ will work fine when using the container name as the lookup parameter in addition to the longer\n\/\/ ID auto-assigned when the container is created.\nfunc (e *Environment) Exists() (bool, error) {\n\t_, err := e.client.ContainerInspect(context.Background(), e.Id)\n\n\tif err != nil {\n\t\t\/\/ If this error is because the container instance wasn't found via Docker we\n\t\t\/\/ can safely ignore the error and just return false.\n\t\tif client.IsErrNotFound(err) {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}\n\n\/\/ Determines if the server's docker container is currently running. If there is no container\n\/\/ present, an error will be raised (since this shouldn't be a case that ever happens under\n\/\/ correctly developed circumstances).\n\/\/\n\/\/ You can confirm if the instance wasn't found by using client.IsErrNotFound from the Docker\n\/\/ API.\n\/\/\n\/\/ @see docker\/client\/errors.go\nfunc (e *Environment) IsRunning() (bool, error) {\n\tc, err := e.client.ContainerInspect(context.Background(), e.Id)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn c.State.Running, nil\n}\n\n\/\/ Determine the container exit state and return the exit code and whether or not\n\/\/ the container was killed by the OOM killer.\nfunc (e *Environment) ExitState() (uint32, bool, error) {\n\tc, err := e.client.ContainerInspect(context.Background(), e.Id)\n\tif err != nil {\n\t\t\/\/ I'm not entirely sure how this can happen to be honest. I tried deleting a\n\t\t\/\/ container _while_ a server was running and wings gracefully saw the crash and\n\t\t\/\/ created a new container for it.\n\t\t\/\/\n\t\t\/\/ However, someone reported an error in Discord about this scenario happening,\n\t\t\/\/ so I guess this should prevent it? They didn't tell me how they caused it though\n\t\t\/\/ so that's a mystery that will have to go unsolved.\n\t\t\/\/\n\t\t\/\/ @see https:\/\/github.com\/pterodactyl\/panel\/issues\/2003\n\t\tif client.IsErrNotFound(err) {\n\t\t\treturn 1, false, nil\n\t\t}\n\n\t\treturn 0, false, err\n\t}\n\n\treturn uint32(c.State.ExitCode), c.State.OOMKilled, nil\n}\n\n\/\/ Returns the environment configuration allowing a process to make modifications of the\n\/\/ environment on the fly.\nfunc (e *Environment) Config() *environment.Configuration {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\n\treturn e.Configuration\n}\n\n\/\/ Sets the stop configuration for the environment.\nfunc (e *Environment) SetStopConfiguration(c api.ProcessStopConfiguration) {\n\te.mu.Lock()\n\te.meta.Stop = c\n\te.mu.Unlock()\n}\n\nfunc (e *Environment) SetImage(i string) {\n\te.mu.Lock()\n\te.meta.Image = i\n\te.mu.Unlock()\n}\n<commit_msg>Use sync.Once here to instantiate the event handler<commit_after>package docker\n\nimport (\n\t\"context\"\n\t\"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/client\"\n\t\"github.com\/pterodactyl\/wings\/api\"\n\t\"github.com\/pterodactyl\/wings\/environment\"\n\t\"github.com\/pterodactyl\/wings\/events\"\n\t\"github.com\/pterodactyl\/wings\/system\"\n\t\"io\"\n\t\"sync\"\n)\n\ntype Metadata struct {\n\tImage string\n\tStop  api.ProcessStopConfiguration\n}\n\n\/\/ Ensure that the Docker environment is always implementing all of the methods\n\/\/ from the base environment interface.\nvar _ environment.ProcessEnvironment = (*Environment)(nil)\n\ntype Environment struct {\n\tmu      sync.RWMutex\n\teventMu sync.Once\n\n\t\/\/ The public identifier for this environment. In this case it is the Docker container\n\t\/\/ name that will be used for all instances created under it.\n\tId string\n\n\t\/\/ The environment configuration.\n\tConfiguration *environment.Configuration\n\n\tmeta *Metadata\n\n\t\/\/ The Docker client being used for this instance.\n\tclient *client.Client\n\n\t\/\/ Controls the hijacked response stream which exists only when we're attached to\n\t\/\/ the running container instance.\n\tstream *types.HijackedResponse\n\n\t\/\/ Holds the stats stream used by the polling commands so that we can easily close it out.\n\tstats io.ReadCloser\n\n\temitter *events.EventBus\n\n\t\/\/ Tracks the environment state.\n\tst *system.AtomicString\n}\n\n\/\/ Creates a new base Docker environment. The ID passed through will be the ID that is used to\n\/\/ reference the container from here on out. This should be unique per-server (we use the UUID\n\/\/ by default). The container does not need to exist at this point.\nfunc New(id string, m *Metadata, c *environment.Configuration) (*Environment, error) {\n\tcli, err := environment.DockerClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\te := &Environment{\n\t\tId:            id,\n\t\tConfiguration: c,\n\t\tmeta:          m,\n\t\tclient:        cli,\n\t\tst:            system.NewAtomicString(environment.ProcessOfflineState),\n\t}\n\n\treturn e, nil\n}\n\nfunc (e *Environment) Type() string {\n\treturn \"docker\"\n}\n\n\/\/ Set if this process is currently attached to the process.\nfunc (e *Environment) SetStream(s *types.HijackedResponse) {\n\te.mu.Lock()\n\te.stream = s\n\te.mu.Unlock()\n}\n\n\/\/ Determine if the this process is currently attached to the container.\nfunc (e *Environment) IsAttached() bool {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\n\treturn e.stream != nil\n}\n\nfunc (e *Environment) Events() *events.EventBus {\n\te.eventMu.Do(func() {\n\t\te.emitter = events.New()\n\t})\n\treturn e.emitter\n}\n\n\/\/ Determines if the container exists in this environment. The ID passed through should be the\n\/\/ server UUID since containers are created utilizing the server UUID as the name and docker\n\/\/ will work fine when using the container name as the lookup parameter in addition to the longer\n\/\/ ID auto-assigned when the container is created.\nfunc (e *Environment) Exists() (bool, error) {\n\t_, err := e.client.ContainerInspect(context.Background(), e.Id)\n\n\tif err != nil {\n\t\t\/\/ If this error is because the container instance wasn't found via Docker we\n\t\t\/\/ can safely ignore the error and just return false.\n\t\tif client.IsErrNotFound(err) {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}\n\n\/\/ Determines if the server's docker container is currently running. If there is no container\n\/\/ present, an error will be raised (since this shouldn't be a case that ever happens under\n\/\/ correctly developed circumstances).\n\/\/\n\/\/ You can confirm if the instance wasn't found by using client.IsErrNotFound from the Docker\n\/\/ API.\n\/\/\n\/\/ @see docker\/client\/errors.go\nfunc (e *Environment) IsRunning() (bool, error) {\n\tc, err := e.client.ContainerInspect(context.Background(), e.Id)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn c.State.Running, nil\n}\n\n\/\/ Determine the container exit state and return the exit code and whether or not\n\/\/ the container was killed by the OOM killer.\nfunc (e *Environment) ExitState() (uint32, bool, error) {\n\tc, err := e.client.ContainerInspect(context.Background(), e.Id)\n\tif err != nil {\n\t\t\/\/ I'm not entirely sure how this can happen to be honest. I tried deleting a\n\t\t\/\/ container _while_ a server was running and wings gracefully saw the crash and\n\t\t\/\/ created a new container for it.\n\t\t\/\/\n\t\t\/\/ However, someone reported an error in Discord about this scenario happening,\n\t\t\/\/ so I guess this should prevent it? They didn't tell me how they caused it though\n\t\t\/\/ so that's a mystery that will have to go unsolved.\n\t\t\/\/\n\t\t\/\/ @see https:\/\/github.com\/pterodactyl\/panel\/issues\/2003\n\t\tif client.IsErrNotFound(err) {\n\t\t\treturn 1, false, nil\n\t\t}\n\n\t\treturn 0, false, err\n\t}\n\n\treturn uint32(c.State.ExitCode), c.State.OOMKilled, nil\n}\n\n\/\/ Returns the environment configuration allowing a process to make modifications of the\n\/\/ environment on the fly.\nfunc (e *Environment) Config() *environment.Configuration {\n\te.mu.RLock()\n\tdefer e.mu.RUnlock()\n\n\treturn e.Configuration\n}\n\n\/\/ Sets the stop configuration for the environment.\nfunc (e *Environment) SetStopConfiguration(c api.ProcessStopConfiguration) {\n\te.mu.Lock()\n\te.meta.Stop = c\n\te.mu.Unlock()\n}\n\nfunc (e *Environment) SetImage(i string) {\n\te.mu.Lock()\n\te.meta.Image = i\n\te.mu.Unlock()\n}\n<|endoftext|>"}
{"text":"<commit_before>package registry\n\nimport (\n\t\"github.com\/dotcloud\/docker\/auth\"\n\t\"github.com\/dotcloud\/docker\/utils\"\n\t\"strings\"\n\t\"testing\"\n)\n\nvar (\n\tIMAGE_ID = \"42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d\"\n\tTOKEN    = []string{\"fake-token\"}\n\tREPO     = \"foo42\/bar\"\n)\n\nfunc spawnTestRegistry(t *testing.T) *Registry {\n\tauthConfig := &auth.AuthConfig{}\n\tr, err := NewRegistry(authConfig, utils.NewHTTPRequestFactory(), makeURL(\"\/v1\/\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn r\n}\n\nfunc TestPingRegistryEndpoint(t *testing.T) {\n\terr := pingRegistryEndpoint(makeURL(\"\/v1\/\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestGetRemoteHistory(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\thist, err := r.GetRemoteHistory(IMAGE_ID, makeURL(\"\/v1\/\"), TOKEN)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassertEqual(t, len(hist), 2, \"Expected 2 images in history\")\n\tassertEqual(t, hist[0], IMAGE_ID, \"Expected \"+IMAGE_ID+\"as first ancestry\")\n\tassertEqual(t, hist[1], \"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20\",\n\t\t\"Unexpected second ancestry\")\n}\n\nfunc TestLookupRemoteImage(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\tfound := r.LookupRemoteImage(IMAGE_ID, makeURL(\"\/v1\/\"), TOKEN)\n\tassertEqual(t, found, true, \"Expected remote lookup to succeed\")\n\tfound = r.LookupRemoteImage(\"abcdef\", makeURL(\"\/v1\/\"), TOKEN)\n\tassertEqual(t, found, false, \"Expected remote lookup to fail\")\n}\n\nfunc TestGetRemoteImageJSON(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\tjson, size, err := r.GetRemoteImageJSON(IMAGE_ID, makeURL(\"\/v1\/\"), TOKEN)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassertEqual(t, size, 154, \"Expected size 154\")\n\tif len(json) <= 0 {\n\t\tt.Fatal(\"Expected non-empty json\")\n\t}\n\n\t_, _, err = r.GetRemoteImageJSON(\"abcdef\", makeURL(\"\/v1\/\"), TOKEN)\n\tif err == nil {\n\t\tt.Fatal(\"Expected image not found error\")\n\t}\n}\n\nfunc TestGetRemoteImageLayer(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\tdata, err := r.GetRemoteImageLayer(IMAGE_ID, makeURL(\"\/v1\/\"), TOKEN)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif data == nil {\n\t\tt.Fatal(\"Expected non-nil data result\")\n\t}\n\n\t_, err = r.GetRemoteImageLayer(\"abcdef\", makeURL(\"\/v1\/\"), TOKEN)\n\tif err == nil {\n\t\tt.Fatal(\"Expected image not found error\")\n\t}\n}\n\nfunc TestGetRemoteTags(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\ttags, err := r.GetRemoteTags([]string{makeURL(\"\/v1\/\")}, REPO, TOKEN)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassertEqual(t, len(tags), 1, \"Expected one tag\")\n\tassertEqual(t, tags[\"latest\"], IMAGE_ID, \"Expected tag latest to map to \"+IMAGE_ID)\n\n\t_, err = r.GetRemoteTags([]string{makeURL(\"\/v1\/\")}, \"foo42\/baz\", TOKEN)\n\tif err == nil {\n\t\tt.Fatal(\"Expected error when fetching tags for bogus repo\")\n\t}\n}\n\nfunc TestGetRepositoryData(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\tdata, err := r.GetRepositoryData(\"foo42\/bar\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassertEqual(t, len(data.ImgList), 2, \"Expected 2 images in ImgList\")\n\tassertEqual(t, len(data.Endpoints), 1, \"Expected one endpoint in Endpoints\")\n}\n\nfunc TestPushImageJSONRegistry(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\timgData := &ImgData{\n\t\tID:       \"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20\",\n\t\tChecksum: \"sha256:1ac330d56e05eef6d438586545ceff7550d3bdcb6b19961f12c5ba714ee1bb37\",\n\t}\n\n\terr := r.PushImageJSONRegistry(imgData, []byte{0x42, 0xdf, 0x0}, makeURL(\"\/v1\/\"), TOKEN)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestPushImageLayerRegistry(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\tlayer := strings.NewReader(\"\")\n\t_, err := r.PushImageLayerRegistry(IMAGE_ID, layer, makeURL(\"\/v1\/\"), TOKEN, []byte{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestResolveRepositoryName(t *testing.T) {\n\t_, _, err := ResolveRepositoryName(\"https:\/\/github.com\/dotcloud\/docker\")\n\tassertEqual(t, err, ErrInvalidRepositoryName, \"Expected error invalid repo name\")\n\tep, repo, err := ResolveRepositoryName(\"fooo\/bar\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassertEqual(t, ep, auth.IndexServerAddress(), \"Expected endpoint to be index server address\")\n\tassertEqual(t, repo, \"fooo\/bar\", \"Expected resolved repo to be foo\/bar\")\n\n\tu := makeURL(\"\")[7:]\n\tep, repo, err = ResolveRepositoryName(u + \"\/private\/moonbase\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassertEqual(t, ep, \"http:\/\/\"+u+\"\/v1\/\", \"Expected endpoint to be \"+u)\n\tassertEqual(t, repo, \"private\/moonbase\", \"Expected endpoint to be private\/moonbase\")\n}\n\nfunc TestPushRegistryTag(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\terr := r.PushRegistryTag(\"foo42\/bar\", IMAGE_ID, \"stable\", makeURL(\"\/v1\/\"), TOKEN)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestPushImageJSONIndex(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\timgData := []*ImgData{\n\t\t{\n\t\t\tID:       \"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20\",\n\t\t\tChecksum: \"sha256:1ac330d56e05eef6d438586545ceff7550d3bdcb6b19961f12c5ba714ee1bb37\",\n\t\t},\n\t\t{\n\t\t\tID:       \"42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d\",\n\t\t\tChecksum: \"sha256:bea7bf2e4bacd479344b737328db47b18880d09096e6674165533aa994f5e9f2\",\n\t\t},\n\t}\n\trepoData, err := r.PushImageJSONIndex(\"foo42\/bar\", imgData, false, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif repoData == nil {\n\t\tt.Fatal(\"Expected RepositoryData object\")\n\t}\n\trepoData, err = r.PushImageJSONIndex(\"foo42\/bar\", imgData, true, []string{r.indexEndpoint})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif repoData == nil {\n\t\tt.Fatal(\"Expected RepositoryData object\")\n\t}\n}\n\nfunc TestSearchRepositories(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\tresults, err := r.SearchRepositories(\"supercalifragilisticepsialidocious\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif results == nil {\n\t\tt.Fatal(\"Expected non-nil SearchResults object\")\n\t}\n\tassertEqual(t, results.NumResults, 0, \"Expected 0 search results\")\n}\n\nfunc TestValidRepositoryName(t *testing.T) {\n\tif err := validateRepositoryName(\"docker\/docker\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := validateRepositoryName(\"docker\/Docker\"); err == nil {\n\t\tt.Log(\"Repository name should be invalid\")\n\t\tt.Fail()\n\t}\n}\n<commit_msg>Fixed registry unit tests<commit_after>package registry\n\nimport (\n\t\"github.com\/dotcloud\/docker\/auth\"\n\t\"github.com\/dotcloud\/docker\/utils\"\n\t\"strings\"\n\t\"testing\"\n)\n\nvar (\n\tIMAGE_ID = \"42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d\"\n\tTOKEN    = []string{\"fake-token\"}\n\tREPO     = \"foo42\/bar\"\n)\n\nfunc spawnTestRegistry(t *testing.T) *Registry {\n\tauthConfig := &auth.AuthConfig{}\n\tr, err := NewRegistry(authConfig, utils.NewHTTPRequestFactory(), makeURL(\"\/v1\/\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn r\n}\n\nfunc TestPingRegistryEndpoint(t *testing.T) {\n\tstandalone, err := pingRegistryEndpoint(makeURL(\"\/v1\/\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassertEqual(t, standalone, true, \"Expected standalone to be true (default)\")\n}\n\nfunc TestGetRemoteHistory(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\thist, err := r.GetRemoteHistory(IMAGE_ID, makeURL(\"\/v1\/\"), TOKEN)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassertEqual(t, len(hist), 2, \"Expected 2 images in history\")\n\tassertEqual(t, hist[0], IMAGE_ID, \"Expected \"+IMAGE_ID+\"as first ancestry\")\n\tassertEqual(t, hist[1], \"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20\",\n\t\t\"Unexpected second ancestry\")\n}\n\nfunc TestLookupRemoteImage(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\tfound := r.LookupRemoteImage(IMAGE_ID, makeURL(\"\/v1\/\"), TOKEN)\n\tassertEqual(t, found, true, \"Expected remote lookup to succeed\")\n\tfound = r.LookupRemoteImage(\"abcdef\", makeURL(\"\/v1\/\"), TOKEN)\n\tassertEqual(t, found, false, \"Expected remote lookup to fail\")\n}\n\nfunc TestGetRemoteImageJSON(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\tjson, size, err := r.GetRemoteImageJSON(IMAGE_ID, makeURL(\"\/v1\/\"), TOKEN)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassertEqual(t, size, 154, \"Expected size 154\")\n\tif len(json) <= 0 {\n\t\tt.Fatal(\"Expected non-empty json\")\n\t}\n\n\t_, _, err = r.GetRemoteImageJSON(\"abcdef\", makeURL(\"\/v1\/\"), TOKEN)\n\tif err == nil {\n\t\tt.Fatal(\"Expected image not found error\")\n\t}\n}\n\nfunc TestGetRemoteImageLayer(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\tdata, err := r.GetRemoteImageLayer(IMAGE_ID, makeURL(\"\/v1\/\"), TOKEN)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif data == nil {\n\t\tt.Fatal(\"Expected non-nil data result\")\n\t}\n\n\t_, err = r.GetRemoteImageLayer(\"abcdef\", makeURL(\"\/v1\/\"), TOKEN)\n\tif err == nil {\n\t\tt.Fatal(\"Expected image not found error\")\n\t}\n}\n\nfunc TestGetRemoteTags(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\ttags, err := r.GetRemoteTags([]string{makeURL(\"\/v1\/\")}, REPO, TOKEN)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassertEqual(t, len(tags), 1, \"Expected one tag\")\n\tassertEqual(t, tags[\"latest\"], IMAGE_ID, \"Expected tag latest to map to \"+IMAGE_ID)\n\n\t_, err = r.GetRemoteTags([]string{makeURL(\"\/v1\/\")}, \"foo42\/baz\", TOKEN)\n\tif err == nil {\n\t\tt.Fatal(\"Expected error when fetching tags for bogus repo\")\n\t}\n}\n\nfunc TestGetRepositoryData(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\tdata, err := r.GetRepositoryData(\"foo42\/bar\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassertEqual(t, len(data.ImgList), 2, \"Expected 2 images in ImgList\")\n\tassertEqual(t, len(data.Endpoints), 1, \"Expected one endpoint in Endpoints\")\n}\n\nfunc TestPushImageJSONRegistry(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\timgData := &ImgData{\n\t\tID:       \"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20\",\n\t\tChecksum: \"sha256:1ac330d56e05eef6d438586545ceff7550d3bdcb6b19961f12c5ba714ee1bb37\",\n\t}\n\n\terr := r.PushImageJSONRegistry(imgData, []byte{0x42, 0xdf, 0x0}, makeURL(\"\/v1\/\"), TOKEN)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestPushImageLayerRegistry(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\tlayer := strings.NewReader(\"\")\n\t_, err := r.PushImageLayerRegistry(IMAGE_ID, layer, makeURL(\"\/v1\/\"), TOKEN, []byte{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestResolveRepositoryName(t *testing.T) {\n\t_, _, err := ResolveRepositoryName(\"https:\/\/github.com\/dotcloud\/docker\")\n\tassertEqual(t, err, ErrInvalidRepositoryName, \"Expected error invalid repo name\")\n\tep, repo, err := ResolveRepositoryName(\"fooo\/bar\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassertEqual(t, ep, auth.IndexServerAddress(), \"Expected endpoint to be index server address\")\n\tassertEqual(t, repo, \"fooo\/bar\", \"Expected resolved repo to be foo\/bar\")\n\n\tu := makeURL(\"\")[7:]\n\tep, repo, err = ResolveRepositoryName(u + \"\/private\/moonbase\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tassertEqual(t, ep, \"http:\/\/\"+u+\"\/v1\/\", \"Expected endpoint to be \"+u)\n\tassertEqual(t, repo, \"private\/moonbase\", \"Expected endpoint to be private\/moonbase\")\n}\n\nfunc TestPushRegistryTag(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\terr := r.PushRegistryTag(\"foo42\/bar\", IMAGE_ID, \"stable\", makeURL(\"\/v1\/\"), TOKEN)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestPushImageJSONIndex(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\timgData := []*ImgData{\n\t\t{\n\t\t\tID:       \"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20\",\n\t\t\tChecksum: \"sha256:1ac330d56e05eef6d438586545ceff7550d3bdcb6b19961f12c5ba714ee1bb37\",\n\t\t},\n\t\t{\n\t\t\tID:       \"42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d\",\n\t\t\tChecksum: \"sha256:bea7bf2e4bacd479344b737328db47b18880d09096e6674165533aa994f5e9f2\",\n\t\t},\n\t}\n\trepoData, err := r.PushImageJSONIndex(\"foo42\/bar\", imgData, false, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif repoData == nil {\n\t\tt.Fatal(\"Expected RepositoryData object\")\n\t}\n\trepoData, err = r.PushImageJSONIndex(\"foo42\/bar\", imgData, true, []string{r.indexEndpoint})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif repoData == nil {\n\t\tt.Fatal(\"Expected RepositoryData object\")\n\t}\n}\n\nfunc TestSearchRepositories(t *testing.T) {\n\tr := spawnTestRegistry(t)\n\tresults, err := r.SearchRepositories(\"supercalifragilisticepsialidocious\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif results == nil {\n\t\tt.Fatal(\"Expected non-nil SearchResults object\")\n\t}\n\tassertEqual(t, results.NumResults, 0, \"Expected 0 search results\")\n}\n\nfunc TestValidRepositoryName(t *testing.T) {\n\tif err := validateRepositoryName(\"docker\/docker\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := validateRepositoryName(\"docker\/Docker\"); err == nil {\n\t\tt.Log(\"Repository name should be invalid\")\n\t\tt.Fail()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package requesttree\n\nimport (\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/mondough\/mercury\"\n\tterrors \"github.com\/mondough\/typhon\/errors\"\n)\n\nconst (\n\tparentIdHeader = \"Parent-Request-ID\"\n\treqIdCtxKey    = \"Request-ID\"\n\n\tcurrentServiceHeader  = \"Current-Service\"\n\tcurrentEndpointHeader = \"Current-Endpoint\"\n\toriginServiceHeader   = \"Origin-Service\"\n\toriginEndpointHeader  = \"Origin-Endpoint\"\n)\n\ntype requestTreeMiddleware struct{}\n\nfunc (m requestTreeMiddleware) ProcessClientRequest(req mercury.Request) mercury.Request {\n\tif req.Headers()[parentIdHeader] == \"\" { \/\/ Don't overwrite an exiting header\n\t\tif parentId, ok := req.Context().Value(reqIdCtxKey).(string); ok && parentId != \"\" {\n\t\t\treq.SetHeader(parentIdHeader, parentId)\n\t\t}\n\t}\n\n\t\/\/ Pass through the current service and endpoint as the origin of this request\n\tif svc, ok := req.Value(currentServiceHeader).(string); ok {\n\t\treq.SetHeader(originServiceHeader, svc)\n\t}\n\tif ept, ok := req.Value(currentEndpointHeader).(string); ok {\n\t\treq.SetHeader(originEndpointHeader, ept)\n\t}\n\n\treturn req\n}\n\nfunc (m requestTreeMiddleware) ProcessClientResponse(rsp mercury.Response, ctx context.Context) mercury.Response {\n\treturn rsp\n}\n\nfunc (m requestTreeMiddleware) ProcessClientError(err *terrors.Error, ctx context.Context) {}\n\nfunc (m requestTreeMiddleware) ProcessServerRequest(req mercury.Request) (mercury.Request, mercury.Response) {\n\treq.SetContext(context.WithValue(req.Context(), reqIdCtxKey, req.Id()))\n\tif v := req.Headers()[parentIdHeader]; v != \"\" {\n\t\treq.SetContext(context.WithValue(req.Context(), parentIdCtxKey, v))\n\t}\n\n\t\/\/ Set the current service and endpoint into the context\n\treq.SetContext(context.WithValue(req.Context(), currentServiceHeader, req.Service()))\n\treq.SetContext(context.WithValue(req.Context(), currentEndpointHeader, req.Endpoint()))\n\n\t\/\/ Set the originator into the context\n\treq.SetContext(context.WithValue(req.Context(), originServiceHeader, req.Headers()[originServiceHeader]))\n\treq.SetContext(context.WithValue(req.Context(), originEndpointHeader, req.Headers()[originEndpointHeader]))\n\n\treturn req, nil\n}\n\nfunc (m requestTreeMiddleware) ProcessServerResponse(rsp mercury.Response, ctx context.Context) mercury.Response {\n\tif v, ok := ctx.Value(parentIdCtxKey).(string); ok && v != \"\" && rsp != nil {\n\t\trsp.SetHeader(parentIdHeader, v)\n\t}\n\treturn rsp\n}\n\nfunc Middleware() requestTreeMiddleware {\n\treturn requestTreeMiddleware{}\n}\n<commit_msg>Add extractors to pull service and endpoint from a context<commit_after>package requesttree\n\nimport (\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/mondough\/mercury\"\n\tterrors \"github.com\/mondough\/typhon\/errors\"\n)\n\nconst (\n\tparentIdHeader = \"Parent-Request-ID\"\n\treqIdCtxKey    = \"Request-ID\"\n\n\tcurrentServiceHeader  = \"Current-Service\"\n\tcurrentEndpointHeader = \"Current-Endpoint\"\n\toriginServiceHeader   = \"Origin-Service\"\n\toriginEndpointHeader  = \"Origin-Endpoint\"\n)\n\ntype requestTreeMiddleware struct{}\n\nfunc (m requestTreeMiddleware) ProcessClientRequest(req mercury.Request) mercury.Request {\n\tif req.Headers()[parentIdHeader] == \"\" { \/\/ Don't overwrite an exiting header\n\t\tif parentId, ok := req.Context().Value(reqIdCtxKey).(string); ok && parentId != \"\" {\n\t\t\treq.SetHeader(parentIdHeader, parentId)\n\t\t}\n\t}\n\n\t\/\/ Pass through the current service and endpoint as the origin of this request\n\tif svc, ok := req.Value(currentServiceHeader).(string); ok {\n\t\treq.SetHeader(originServiceHeader, svc)\n\t}\n\tif ept, ok := req.Value(currentEndpointHeader).(string); ok {\n\t\treq.SetHeader(originEndpointHeader, ept)\n\t}\n\n\treturn req\n}\n\nfunc (m requestTreeMiddleware) ProcessClientResponse(rsp mercury.Response, ctx context.Context) mercury.Response {\n\treturn rsp\n}\n\nfunc (m requestTreeMiddleware) ProcessClientError(err *terrors.Error, ctx context.Context) {}\n\nfunc (m requestTreeMiddleware) ProcessServerRequest(req mercury.Request) (mercury.Request, mercury.Response) {\n\treq.SetContext(context.WithValue(req.Context(), reqIdCtxKey, req.Id()))\n\tif v := req.Headers()[parentIdHeader]; v != \"\" {\n\t\treq.SetContext(context.WithValue(req.Context(), parentIdCtxKey, v))\n\t}\n\n\t\/\/ Set the current service and endpoint into the context\n\treq.SetContext(context.WithValue(req.Context(), currentServiceHeader, req.Service()))\n\treq.SetContext(context.WithValue(req.Context(), currentEndpointHeader, req.Endpoint()))\n\n\t\/\/ Set the originator into the context\n\treq.SetContext(context.WithValue(req.Context(), originServiceHeader, req.Headers()[originServiceHeader]))\n\treq.SetContext(context.WithValue(req.Context(), originEndpointHeader, req.Headers()[originEndpointHeader]))\n\n\treturn req, nil\n}\n\nfunc (m requestTreeMiddleware) ProcessServerResponse(rsp mercury.Response, ctx context.Context) mercury.Response {\n\tif v, ok := ctx.Value(parentIdCtxKey).(string); ok && v != \"\" && rsp != nil {\n\t\trsp.SetHeader(parentIdHeader, v)\n\t}\n\treturn rsp\n}\n\nfunc Middleware() requestTreeMiddleware {\n\treturn requestTreeMiddleware{}\n}\n\n\/\/ OriginServiceFor returns the originating service for this context\nfunc OriginServiceFor(ctx context.Context) string {\n\tif s, ok := ctx.Value(originServiceHeader).(string); ok {\n\t\treturn s\n\t}\n\treturn \"\"\n}\n\n\/\/ OriginEndpointFor returns the originating endpoint for this context\nfunc OriginEndpointFor(ctx context.Context) string {\n\tif e, ok := ctx.Value(originEndpointHeader).(string); ok {\n\t\treturn e\n\t}\n\treturn \"\"\n}\n\n\/\/ CurrentServiceFor returns the current service that this context is executing within\nfunc CurrentServiceFor(ctx context.Context) string {\n\tif s, ok := ctx.Value(currentServiceHeader).(string); ok {\n\t\treturn s\n\t}\n\treturn \"\"\n}\n\n\/\/ CurrentEndpointFor returns the current endpoint that this context is executing within\nfunc CurrentEndpointFor(ctx context.Context) string {\n\tif e, ok := ctx.Value(currentEndpointHeader).(string); ok {\n\t\treturn e\n\t}\n\treturn \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\n\t\"github.com\/awslabs\/aws-sdk-go\/aws\"\n\t\"github.com\/awslabs\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/awslabs\/aws-sdk-go\/service\/s3\"\n)\n\nfunc resourceAwsS3Bucket() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsS3BucketCreate,\n\t\tRead:   resourceAwsS3BucketRead,\n\t\tUpdate: resourceAwsS3BucketUpdate,\n\t\tDelete: resourceAwsS3BucketDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"bucket\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"acl\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tDefault:  \"private\",\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"policy\": &schema.Schema{\n\t\t\t\tType:      schema.TypeString,\n\t\t\t\tOptional:  true,\n\t\t\t\tStateFunc: normalizeJson,\n\t\t\t},\n\n\t\t\t\"website\": &schema.Schema{\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"index_document\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"error_document\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"redirect_all_requests_to\": &schema.Schema{\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tConflictsWith: []string{\n\t\t\t\t\t\t\t\t\"website.0.index_document\",\n\t\t\t\t\t\t\t\t\"website.0.error_document\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"hosted_zone_id\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"region\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"website_endpoint\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsS3BucketCreate(d *schema.ResourceData, meta interface{}) error {\n\ts3conn := meta.(*AWSClient).s3conn\n\tawsRegion := meta.(*AWSClient).region\n\n\t\/\/ Get the bucket and acl\n\tbucket := d.Get(\"bucket\").(string)\n\tacl := d.Get(\"acl\").(string)\n\n\tlog.Printf(\"[DEBUG] S3 bucket create: %s, ACL: %s\", bucket, acl)\n\n\treq := &s3.CreateBucketInput{\n\t\tBucket: aws.String(bucket),\n\t\tACL:    aws.String(acl),\n\t}\n\n\t\/\/ Special case us-east-1 region and do not set the LocationConstraint.\n\t\/\/ See \"Request Elements: http:\/\/docs.aws.amazon.com\/AmazonS3\/latest\/API\/RESTBucketPUT.html\n\tif awsRegion != \"us-east-1\" {\n\t\treq.CreateBucketConfiguration = &s3.CreateBucketConfiguration{\n\t\t\tLocationConstraint: aws.String(awsRegion),\n\t\t}\n\t}\n\n\t_, err := s3conn.CreateBucket(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating S3 bucket: %s\", err)\n\t}\n\n\t\/\/ Assign the bucket name as the resource ID\n\td.SetId(bucket)\n\n\treturn resourceAwsS3BucketUpdate(d, meta)\n}\n\nfunc resourceAwsS3BucketUpdate(d *schema.ResourceData, meta interface{}) error {\n\ts3conn := meta.(*AWSClient).s3conn\n\tif err := setTagsS3(s3conn, d); err != nil {\n\t\treturn err\n\t}\n\n\tif d.HasChange(\"policy\") {\n\t\tif err := resourceAwsS3BucketPolicyUpdate(s3conn, d); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif d.HasChange(\"website\") {\n\t\tif err := resourceAwsS3BucketWebsiteUpdate(s3conn, d); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn resourceAwsS3BucketRead(d, meta)\n}\n\nfunc resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error {\n\ts3conn := meta.(*AWSClient).s3conn\n\n\tvar err error\n\t_, err = s3conn.HeadBucket(&s3.HeadBucketInput{\n\t\tBucket: aws.String(d.Id()),\n\t})\n\tif err != nil {\n\t\tif awsError, ok := err.(awserr.RequestFailure); ok && awsError.StatusCode() == 404 {\n\t\t\td.SetId(\"\")\n\t\t} else {\n\t\t\t\/\/ some of the AWS SDK's errors can be empty strings, so let's add\n\t\t\t\/\/ some additional context.\n\t\t\treturn fmt.Errorf(\"error reading S3 bucket \\\"%s\\\": %s\", d.Id(), err)\n\t\t}\n\t}\n\n\t\/\/ Read the policy\n\tpol, err := s3conn.GetBucketPolicy(&s3.GetBucketPolicyInput{\n\t\tBucket: aws.String(d.Id()),\n\t})\n\tlog.Printf(\"[DEBUG] S3 bucket: %s, read policy: %v\", d.Id(), pol)\n\tif err != nil {\n\t\tif err := d.Set(\"policy\", \"\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif v := pol.Policy; v == nil {\n\t\t\tif err := d.Set(\"policy\", \"\"); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else if err := d.Set(\"policy\", normalizeJson(*v)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Read the website configuration\n\tws, err := s3conn.GetBucketWebsite(&s3.GetBucketWebsiteInput{\n\t\tBucket: aws.String(d.Id()),\n\t})\n\tvar websites []map[string]interface{}\n\tif err == nil {\n\t\tw := make(map[string]interface{})\n\n\t\tif v := ws.IndexDocument; v != nil {\n\t\t\tw[\"index_document\"] = *v.Suffix\n\t\t}\n\n\t\tif v := ws.ErrorDocument; v != nil {\n\t\t\tw[\"error_document\"] = *v.Key\n\t\t}\n\n\t\tif v := ws.RedirectAllRequestsTo; v != nil {\n\t\t\tw[\"redirect_all_requests_to\"] = *v.HostName\n\t\t}\n\n\t\twebsites = append(websites, w)\n\t}\n\tif err := d.Set(\"website\", websites); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Add the region as an attribute\n\tlocation, err := s3conn.GetBucketLocation(\n\t\t&s3.GetBucketLocationInput{\n\t\t\tBucket: aws.String(d.Id()),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar region string\n\tif location.LocationConstraint != nil {\n\t\tregion = *location.LocationConstraint\n\t}\n\tregion = normalizeRegion(region)\n\tif err := d.Set(\"region\", region); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Add the hosted zone ID for this bucket's region as an attribute\n\thostedZoneID := HostedZoneIDForRegion(region)\n\tif err := d.Set(\"hosted_zone_id\", hostedZoneID); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Add website_endpoint as an attribute\n\tendpoint, err := websiteEndpoint(s3conn, d)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := d.Set(\"website_endpoint\", endpoint); err != nil {\n\t\treturn err\n\t}\n\n\ttagSet, err := getTagSetS3(s3conn, d.Id())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.Set(\"tags\", tagsToMapS3(tagSet)); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsS3BucketDelete(d *schema.ResourceData, meta interface{}) error {\n\ts3conn := meta.(*AWSClient).s3conn\n\n\tlog.Printf(\"[DEBUG] S3 Delete Bucket: %s\", d.Id())\n\t_, err := s3conn.DeleteBucket(&s3.DeleteBucketInput{\n\t\tBucket: aws.String(d.Id()),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc resourceAwsS3BucketPolicyUpdate(s3conn *s3.S3, d *schema.ResourceData) error {\n\tbucket := d.Get(\"bucket\").(string)\n\tpolicy := d.Get(\"policy\").(string)\n\n\tif policy != \"\" {\n\t\tlog.Printf(\"[DEBUG] S3 bucket: %s, put policy: %s\", bucket, policy)\n\n\t\t_, err := s3conn.PutBucketPolicy(&s3.PutBucketPolicyInput{\n\t\t\tBucket: aws.String(bucket),\n\t\t\tPolicy: aws.String(policy),\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error putting S3 policy: %s\", err)\n\t\t}\n\t} else {\n\t\tlog.Printf(\"[DEBUG] S3 bucket: %s, delete policy: %s\", bucket, policy)\n\t\t_, err := s3conn.DeleteBucketPolicy(&s3.DeleteBucketPolicyInput{\n\t\t\tBucket: aws.String(bucket),\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error deleting S3 policy: %s\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsS3BucketWebsiteUpdate(s3conn *s3.S3, d *schema.ResourceData) error {\n\tws := d.Get(\"website\").([]interface{})\n\n\tif len(ws) == 1 {\n\t\tw := ws[0].(map[string]interface{})\n\t\treturn resourceAwsS3BucketWebsitePut(s3conn, d, w)\n\t} else if len(ws) == 0 {\n\t\treturn resourceAwsS3BucketWebsiteDelete(s3conn, d)\n\t} else {\n\t\treturn fmt.Errorf(\"Cannot specify more than one website.\")\n\t}\n}\n\nfunc resourceAwsS3BucketWebsitePut(s3conn *s3.S3, d *schema.ResourceData, website map[string]interface{}) error {\n\tbucket := d.Get(\"bucket\").(string)\n\n\tindexDocument := website[\"index_document\"].(string)\n\terrorDocument := website[\"error_document\"].(string)\n\tredirectAllRequestsTo := website[\"redirect_all_requests_to\"].(string)\n\n\tif indexDocument == \"\" && redirectAllRequestsTo == \"\" {\n\t\treturn fmt.Errorf(\"Must specify either index_document or redirect_all_requests_to.\")\n\t}\n\n\twebsiteConfiguration := &s3.WebsiteConfiguration{}\n\n\tif indexDocument != \"\" {\n\t\twebsiteConfiguration.IndexDocument = &s3.IndexDocument{Suffix: aws.String(indexDocument)}\n\t}\n\n\tif errorDocument != \"\" {\n\t\twebsiteConfiguration.ErrorDocument = &s3.ErrorDocument{Key: aws.String(errorDocument)}\n\t}\n\n\tif redirectAllRequestsTo != \"\" {\n\t\twebsiteConfiguration.RedirectAllRequestsTo = &s3.RedirectAllRequestsTo{HostName: aws.String(redirectAllRequestsTo)}\n\t}\n\n\tputInput := &s3.PutBucketWebsiteInput{\n\t\tBucket:               aws.String(bucket),\n\t\tWebsiteConfiguration: websiteConfiguration,\n\t}\n\n\tlog.Printf(\"[DEBUG] S3 put bucket website: %#v\", putInput)\n\n\t_, err := s3conn.PutBucketWebsite(putInput)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error putting S3 website: %s\", err)\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsS3BucketWebsiteDelete(s3conn *s3.S3, d *schema.ResourceData) error {\n\tbucket := d.Get(\"bucket\").(string)\n\tdeleteInput := &s3.DeleteBucketWebsiteInput{Bucket: aws.String(bucket)}\n\n\tlog.Printf(\"[DEBUG] S3 delete bucket website: %#v\", deleteInput)\n\n\t_, err := s3conn.DeleteBucketWebsite(deleteInput)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting S3 website: %s\", err)\n\t}\n\n\treturn nil\n}\n\nfunc websiteEndpoint(s3conn *s3.S3, d *schema.ResourceData) (string, error) {\n\t\/\/ If the bucket doesn't have a website configuration, return an empty\n\t\/\/ endpoint\n\tif _, ok := d.GetOk(\"website\"); !ok {\n\t\treturn \"\", nil\n\t}\n\n\tbucket := d.Get(\"bucket\").(string)\n\n\t\/\/ Lookup the region for this bucket\n\tlocation, err := s3conn.GetBucketLocation(\n\t\t&s3.GetBucketLocationInput{\n\t\t\tBucket: aws.String(bucket),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar region string\n\tif location.LocationConstraint != nil {\n\t\tregion = *location.LocationConstraint\n\t}\n\n\treturn WebsiteEndpointUrl(bucket, region), nil\n}\n\nfunc WebsiteEndpointUrl(bucket string, region string) string {\n\tregion = normalizeRegion(region)\n\treturn fmt.Sprintf(\"%s.s3-website-%s.amazonaws.com\", bucket, region)\n}\n\nfunc normalizeJson(jsonString interface{}) string {\n\tif jsonString == nil {\n\t\treturn \"\"\n\t}\n\tj := make(map[string]interface{})\n\terr := json.Unmarshal([]byte(jsonString.(string)), &j)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error parsing JSON: %s\", err)\n\t}\n\tb, _ := json.Marshal(j)\n\treturn string(b[:])\n}\n\nfunc normalizeRegion(region string) string {\n\t\/\/ Default to us-east-1 if the bucket doesn't have a region:\n\t\/\/ http:\/\/docs.aws.amazon.com\/AmazonS3\/latest\/API\/RESTBucketGETlocation.html\n\tif region == \"\" {\n\t\tregion = \"us-east-1\"\n\t}\n\n\treturn region\n}\n<commit_msg>added force_destroy argument to s3 bucket provider<commit_after>package aws\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\n\t\"github.com\/awslabs\/aws-sdk-go\/aws\"\n\t\"github.com\/awslabs\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/awslabs\/aws-sdk-go\/service\/s3\"\n)\n\nfunc resourceAwsS3Bucket() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsS3BucketCreate,\n\t\tRead:   resourceAwsS3BucketRead,\n\t\tUpdate: resourceAwsS3BucketUpdate,\n\t\tDelete: resourceAwsS3BucketDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"bucket\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"acl\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tDefault:  \"private\",\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"policy\": &schema.Schema{\n\t\t\t\tType:      schema.TypeString,\n\t\t\t\tOptional:  true,\n\t\t\t\tStateFunc: normalizeJson,\n\t\t\t},\n\n\t\t\t\"website\": &schema.Schema{\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"index_document\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"error_document\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"redirect_all_requests_to\": &schema.Schema{\n\t\t\t\t\t\t\tType: schema.TypeString,\n\t\t\t\t\t\t\tConflictsWith: []string{\n\t\t\t\t\t\t\t\t\"website.0.index_document\",\n\t\t\t\t\t\t\t\t\"website.0.error_document\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"hosted_zone_id\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"region\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"website_endpoint\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t},\n\n\t\t\t\"tags\": tagsSchema(),\n\n\t\t\t\"force_destroy\": &schema.Schema{\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault:  false,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceAwsS3BucketCreate(d *schema.ResourceData, meta interface{}) error {\n\ts3conn := meta.(*AWSClient).s3conn\n\tawsRegion := meta.(*AWSClient).region\n\n\t\/\/ Get the bucket and acl\n\tbucket := d.Get(\"bucket\").(string)\n\tacl := d.Get(\"acl\").(string)\n\n\tlog.Printf(\"[DEBUG] S3 bucket create: %s, ACL: %s\", bucket, acl)\n\n\treq := &s3.CreateBucketInput{\n\t\tBucket: aws.String(bucket),\n\t\tACL:    aws.String(acl),\n\t}\n\n\t\/\/ Special case us-east-1 region and do not set the LocationConstraint.\n\t\/\/ See \"Request Elements: http:\/\/docs.aws.amazon.com\/AmazonS3\/latest\/API\/RESTBucketPUT.html\n\tif awsRegion != \"us-east-1\" {\n\t\treq.CreateBucketConfiguration = &s3.CreateBucketConfiguration{\n\t\t\tLocationConstraint: aws.String(awsRegion),\n\t\t}\n\t}\n\n\t_, err := s3conn.CreateBucket(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating S3 bucket: %s\", err)\n\t}\n\n\t\/\/ Assign the bucket name as the resource ID\n\td.SetId(bucket)\n\n\treturn resourceAwsS3BucketUpdate(d, meta)\n}\n\nfunc resourceAwsS3BucketUpdate(d *schema.ResourceData, meta interface{}) error {\n\ts3conn := meta.(*AWSClient).s3conn\n\tif err := setTagsS3(s3conn, d); err != nil {\n\t\treturn err\n\t}\n\n\tif d.HasChange(\"policy\") {\n\t\tif err := resourceAwsS3BucketPolicyUpdate(s3conn, d); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif d.HasChange(\"website\") {\n\t\tif err := resourceAwsS3BucketWebsiteUpdate(s3conn, d); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn resourceAwsS3BucketRead(d, meta)\n}\n\nfunc resourceAwsS3BucketRead(d *schema.ResourceData, meta interface{}) error {\n\ts3conn := meta.(*AWSClient).s3conn\n\n\tvar err error\n\t_, err = s3conn.HeadBucket(&s3.HeadBucketInput{\n\t\tBucket: aws.String(d.Id()),\n\t})\n\tif err != nil {\n\t\tif awsError, ok := err.(awserr.RequestFailure); ok && awsError.StatusCode() == 404 {\n\t\t\td.SetId(\"\")\n\t\t} else {\n\t\t\t\/\/ some of the AWS SDK's errors can be empty strings, so let's add\n\t\t\t\/\/ some additional context.\n\t\t\treturn fmt.Errorf(\"error reading S3 bucket \\\"%s\\\": %s\", d.Id(), err)\n\t\t}\n\t}\n\n\t\/\/ Read the policy\n\tpol, err := s3conn.GetBucketPolicy(&s3.GetBucketPolicyInput{\n\t\tBucket: aws.String(d.Id()),\n\t})\n\tlog.Printf(\"[DEBUG] S3 bucket: %s, read policy: %v\", d.Id(), pol)\n\tif err != nil {\n\t\tif err := d.Set(\"policy\", \"\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif v := pol.Policy; v == nil {\n\t\t\tif err := d.Set(\"policy\", \"\"); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else if err := d.Set(\"policy\", normalizeJson(*v)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Read the website configuration\n\tws, err := s3conn.GetBucketWebsite(&s3.GetBucketWebsiteInput{\n\t\tBucket: aws.String(d.Id()),\n\t})\n\tvar websites []map[string]interface{}\n\tif err == nil {\n\t\tw := make(map[string]interface{})\n\n\t\tif v := ws.IndexDocument; v != nil {\n\t\t\tw[\"index_document\"] = *v.Suffix\n\t\t}\n\n\t\tif v := ws.ErrorDocument; v != nil {\n\t\t\tw[\"error_document\"] = *v.Key\n\t\t}\n\n\t\tif v := ws.RedirectAllRequestsTo; v != nil {\n\t\t\tw[\"redirect_all_requests_to\"] = *v.HostName\n\t\t}\n\n\t\twebsites = append(websites, w)\n\t}\n\tif err := d.Set(\"website\", websites); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Add the region as an attribute\n\tlocation, err := s3conn.GetBucketLocation(\n\t\t&s3.GetBucketLocationInput{\n\t\t\tBucket: aws.String(d.Id()),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar region string\n\tif location.LocationConstraint != nil {\n\t\tregion = *location.LocationConstraint\n\t}\n\tregion = normalizeRegion(region)\n\tif err := d.Set(\"region\", region); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Add the hosted zone ID for this bucket's region as an attribute\n\thostedZoneID := HostedZoneIDForRegion(region)\n\tif err := d.Set(\"hosted_zone_id\", hostedZoneID); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Add website_endpoint as an attribute\n\tendpoint, err := websiteEndpoint(s3conn, d)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := d.Set(\"website_endpoint\", endpoint); err != nil {\n\t\treturn err\n\t}\n\n\ttagSet, err := getTagSetS3(s3conn, d.Id())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.Set(\"tags\", tagsToMapS3(tagSet)); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsS3BucketDelete(d *schema.ResourceData, meta interface{}) error {\n\ts3conn := meta.(*AWSClient).s3conn\n\n\tlog.Printf(\"[DEBUG] S3 Delete Bucket: %s\", d.Id())\n\t_, err := s3conn.DeleteBucket(&s3.DeleteBucketInput{\n\t\tBucket: aws.String(d.Id()),\n\t})\n\tif err != nil {\n\t\tec2err, ok := err.(awserr.Error)\n\t\tif ok && ec2err.Code() == \"BucketNotEmpty\" {\n\t\t\tif d.Get(\"force_destroy\").(bool) {\n\t\t\t\t\/\/ bucket may have things delete them\n\t\t\t\tlog.Printf(\"[DEBUG] S3 Bucket attempting to forceDestroy %+v\", err)\n\n\t\t\t\tbucket := d.Get(\"bucket\").(string)\n\t\t\t\tresp, err := s3conn.ListObjects(\n\t\t\t\t\t&s3.ListObjectsInput{\n\t\t\t\t\t\tBucket: aws.String(bucket),\n\t\t\t\t\t},\n\t\t\t\t)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Error S3 Bucket list Objects err: %s\", err)\n\t\t\t\t}\n\n\t\t\t\tobjectsToDelete := make([]*s3.ObjectIdentifier, len(resp.Contents))\n\t\t\t\tfor i, v := range resp.Contents {\n\t\t\t\t\tobjectsToDelete[i] = &s3.ObjectIdentifier{\n\t\t\t\t\t\tKey: v.Key,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t_, err = s3conn.DeleteObjects(\n\t\t\t\t\t&s3.DeleteObjectsInput{\n\t\t\t\t\t\tBucket: aws.String(bucket),\n\t\t\t\t\t\tDelete: &s3.Delete{\n\t\t\t\t\t\t\tObjects: objectsToDelete,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Error S3 Bucket force_destroy error deleting: %s\", err)\n\t\t\t\t}\n\n\t\t\t\t\/\/ this line recurses until all objects are deleted or an error is returned\n\t\t\t\treturn resourceAwsS3BucketDelete(d, meta)\n\t\t\t}\n\t\t}\n\t\treturn fmt.Errorf(\"Error deleting S3 Bucket: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc resourceAwsS3BucketPolicyUpdate(s3conn *s3.S3, d *schema.ResourceData) error {\n\tbucket := d.Get(\"bucket\").(string)\n\tpolicy := d.Get(\"policy\").(string)\n\n\tif policy != \"\" {\n\t\tlog.Printf(\"[DEBUG] S3 bucket: %s, put policy: %s\", bucket, policy)\n\n\t\t_, err := s3conn.PutBucketPolicy(&s3.PutBucketPolicyInput{\n\t\t\tBucket: aws.String(bucket),\n\t\t\tPolicy: aws.String(policy),\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error putting S3 policy: %s\", err)\n\t\t}\n\t} else {\n\t\tlog.Printf(\"[DEBUG] S3 bucket: %s, delete policy: %s\", bucket, policy)\n\t\t_, err := s3conn.DeleteBucketPolicy(&s3.DeleteBucketPolicyInput{\n\t\t\tBucket: aws.String(bucket),\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error deleting S3 policy: %s\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsS3BucketWebsiteUpdate(s3conn *s3.S3, d *schema.ResourceData) error {\n\tws := d.Get(\"website\").([]interface{})\n\n\tif len(ws) == 1 {\n\t\tw := ws[0].(map[string]interface{})\n\t\treturn resourceAwsS3BucketWebsitePut(s3conn, d, w)\n\t} else if len(ws) == 0 {\n\t\treturn resourceAwsS3BucketWebsiteDelete(s3conn, d)\n\t} else {\n\t\treturn fmt.Errorf(\"Cannot specify more than one website.\")\n\t}\n}\n\nfunc resourceAwsS3BucketWebsitePut(s3conn *s3.S3, d *schema.ResourceData, website map[string]interface{}) error {\n\tbucket := d.Get(\"bucket\").(string)\n\n\tindexDocument := website[\"index_document\"].(string)\n\terrorDocument := website[\"error_document\"].(string)\n\tredirectAllRequestsTo := website[\"redirect_all_requests_to\"].(string)\n\n\tif indexDocument == \"\" && redirectAllRequestsTo == \"\" {\n\t\treturn fmt.Errorf(\"Must specify either index_document or redirect_all_requests_to.\")\n\t}\n\n\twebsiteConfiguration := &s3.WebsiteConfiguration{}\n\n\tif indexDocument != \"\" {\n\t\twebsiteConfiguration.IndexDocument = &s3.IndexDocument{Suffix: aws.String(indexDocument)}\n\t}\n\n\tif errorDocument != \"\" {\n\t\twebsiteConfiguration.ErrorDocument = &s3.ErrorDocument{Key: aws.String(errorDocument)}\n\t}\n\n\tif redirectAllRequestsTo != \"\" {\n\t\twebsiteConfiguration.RedirectAllRequestsTo = &s3.RedirectAllRequestsTo{HostName: aws.String(redirectAllRequestsTo)}\n\t}\n\n\tputInput := &s3.PutBucketWebsiteInput{\n\t\tBucket:               aws.String(bucket),\n\t\tWebsiteConfiguration: websiteConfiguration,\n\t}\n\n\tlog.Printf(\"[DEBUG] S3 put bucket website: %#v\", putInput)\n\n\t_, err := s3conn.PutBucketWebsite(putInput)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error putting S3 website: %s\", err)\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsS3BucketWebsiteDelete(s3conn *s3.S3, d *schema.ResourceData) error {\n\tbucket := d.Get(\"bucket\").(string)\n\tdeleteInput := &s3.DeleteBucketWebsiteInput{Bucket: aws.String(bucket)}\n\n\tlog.Printf(\"[DEBUG] S3 delete bucket website: %#v\", deleteInput)\n\n\t_, err := s3conn.DeleteBucketWebsite(deleteInput)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting S3 website: %s\", err)\n\t}\n\n\treturn nil\n}\n\nfunc websiteEndpoint(s3conn *s3.S3, d *schema.ResourceData) (string, error) {\n\t\/\/ If the bucket doesn't have a website configuration, return an empty\n\t\/\/ endpoint\n\tif _, ok := d.GetOk(\"website\"); !ok {\n\t\treturn \"\", nil\n\t}\n\n\tbucket := d.Get(\"bucket\").(string)\n\n\t\/\/ Lookup the region for this bucket\n\tlocation, err := s3conn.GetBucketLocation(\n\t\t&s3.GetBucketLocationInput{\n\t\t\tBucket: aws.String(bucket),\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvar region string\n\tif location.LocationConstraint != nil {\n\t\tregion = *location.LocationConstraint\n\t}\n\n\treturn WebsiteEndpointUrl(bucket, region), nil\n}\n\nfunc WebsiteEndpointUrl(bucket string, region string) string {\n\tregion = normalizeRegion(region)\n\treturn fmt.Sprintf(\"%s.s3-website-%s.amazonaws.com\", bucket, region)\n}\n\nfunc normalizeJson(jsonString interface{}) string {\n\tif jsonString == nil {\n\t\treturn \"\"\n\t}\n\tj := make(map[string]interface{})\n\terr := json.Unmarshal([]byte(jsonString.(string)), &j)\n\tif err != nil {\n\t\treturn fmt.Sprintf(\"Error parsing JSON: %s\", err)\n\t}\n\tb, _ := json.Marshal(j)\n\treturn string(b[:])\n}\n\nfunc normalizeRegion(region string) string {\n\t\/\/ Default to us-east-1 if the bucket doesn't have a region:\n\t\/\/ http:\/\/docs.aws.amazon.com\/AmazonS3\/latest\/API\/RESTBucketGETlocation.html\n\tif region == \"\" {\n\t\tregion = \"us-east-1\"\n\t}\n\n\treturn region\n}\n<|endoftext|>"}
{"text":"<commit_before>package popularpost\n\nimport (\n\t\"fmt\"\n\t\"socialapi\/config\"\n\t\"socialapi\/models\"\n\t\"time\"\n\n\t\"github.com\/jinzhu\/now\"\n\t\"github.com\/koding\/logging\"\n\t\"github.com\/koding\/redis\"\n\t\"github.com\/streadway\/amqp\"\n)\n\nvar (\n\tPopularPostKeyName = \"popularpost\"\n\tKeyExistsRegistry  = map[string]bool{}\n)\n\ntype Controller struct {\n\tlog   logging.Logger\n\tredis *redis.RedisSession\n}\n\nfunc (t *Controller) DefaultErrHandler(delivery amqp.Delivery, err error) bool {\n\tif delivery.Redelivered {\n\t\tt.log.Error(\"Redelivered message gave error again, putting to maintenance queue\", err)\n\t\tdelivery.Ack(false)\n\t\treturn true\n\t}\n\n\tt.log.Error(\"an error occured putting message back to queue\", err)\n\tdelivery.Nack(false, true)\n\treturn false\n}\n\nfunc New(log logging.Logger, redis *redis.RedisSession) *Controller {\n\treturn &Controller{\n\t\tlog:   log,\n\t\tredis: redis,\n\t}\n}\n\nfunc (f *Controller) InteractionSaved(i *models.Interaction) error {\n\treturn f.handleInteraction(1, i)\n}\n\nfunc (f *Controller) InteractionDeleted(i *models.Interaction) error {\n\treturn f.handleInteraction(-1, i)\n}\n\nfunc (f *Controller) handleInteraction(incrementCount int, i *models.Interaction) error {\n\tcm, err := models.ChannelMessageById(i.MessageId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc, err := models.ChannelById(cm.InitialChannelId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif notEligibleForPopularPost(c, cm) {\n\t\tf.log.Error(fmt.Sprintf(\"Not eligible Interaction Id:%d\", i.Id))\n\t\treturn nil\n\t}\n\n\tkeyname := &KeyName{\n\t\tGroupName: c.GroupName, ChannelName: c.Name,\n\t\tTime: cm.CreatedAt,\n\t}\n\n\terr = f.saveToDailyBucket(keyname, incrementCount, i.MessageId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = f.saveToSevenDayBucket(keyname, incrementCount, i.MessageId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (f *Controller) saveToDailyBucket(k *KeyName, inc int, id int64) error {\n\tkey := k.Today()\n\n\t_, err := f.redis.SortedSetIncrBy(key, inc, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tscore, err := f.redis.SortedSetScore(key, id)\n\tif score <= 0 {\n\t\t_, err := f.redis.SortedSetRem(key, id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn err\n}\n\nfunc (f *Controller) saveToSevenDayBucket(k *KeyName, inc int, id int64) error {\n\tkey := k.Weekly()\n\n\t_, ok := KeyExistsRegistry[key]\n\tif !ok {\n\t\texists := f.redis.Exists(key)\n\t\tif !exists {\n\t\t\terr := f.createSevenDayBucket(k)\n\t\t\treturn err\n\t\t}\n\n\t\tKeyExistsRegistry[key] = true\n\t}\n\n\t_, err := f.redis.SortedSetIncrBy(key, inc, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tscore, err := f.redis.SortedSetScore(key, id)\n\tif score <= 0 {\n\t\t_, err := f.redis.SortedSetRem(key, id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (f *Controller) createSevenDayBucket(k *KeyName) error {\n\tkeys, weights := []interface{}{}, []interface{}{}\n\n\tfrom := getStartOfDay(k.Time)\n\taggregate := \"SUM\"\n\n\tfor i := 0; i <= 6; i++ {\n\t\tcurrentDate := getDaysAgo(from, i)\n\t\tkeys = append(keys, k.Before(currentDate))\n\n\t\t\/\/ add by 1 to prevent divide by 0 errors\n\t\tweight := float64(i + 1)\n\t\tweights = append(weights, float64(1\/weight))\n\t}\n\n\t_, err := f.redis.SortedSetsUnion(k.Weekly(), keys, weights, aggregate)\n\n\treturn err\n}\n\nfunc PopularPostKey(groupName, channelName string, current time.Time) string {\n\tname := KeyName{\n\t\tGroupName: groupName, ChannelName: channelName,\n\t\tTime: current.UTC(),\n\t}\n\n\treturn name.Weekly()\n}\n\n\/\/----------------------------------------------------------\n\/\/ KeyName\n\/\/----------------------------------------------------------\n\ntype KeyName struct {\n\tGroupName, ChannelName string\n\tTime                   time.Time\n}\n\nfunc (k *KeyName) Today() string {\n\treturn k.do(getStartOfDay(k.Time))\n}\n\nfunc (k *KeyName) Before(t time.Time) string {\n\treturn k.do(t)\n}\n\nfunc (k *KeyName) Weekly() string {\n\tcurrent := getStartOfDay(k.Time.UTC())\n\tsevenDaysAgo := getDaysAgo(current, 7).UTC().Unix()\n\n\treturn fmt.Sprintf(\"%s-%d\", k.do(current), sevenDaysAgo)\n}\n\nfunc (k *KeyName) do(t time.Time) string {\n\treturn fmt.Sprintf(\"%s:%s:%s:%s:%d\",\n\t\tconfig.MustGet().Environment, k.GroupName, PopularPostKeyName,\n\t\tk.ChannelName, t.UTC().Unix(),\n\t)\n}\n\n\/\/----------------------------------------------------------\n\/\/ helpers\n\/\/----------------------------------------------------------\n\nfunc notEligibleForPopularPost(c *models.Channel, cm *models.ChannelMessage) bool {\n\tif c.MetaBits.Is(models.Troll) {\n\t\treturn true\n\t}\n\n\tif c.PrivacyConstant != models.Channel_PRIVACY_PUBLIC {\n\t\treturn true\n\t}\n\n\tif cm.MetaBits.Is(models.Troll) {\n\t\treturn true\n\t}\n\n\tif cm.TypeConstant != models.ChannelMessage_TYPE_POST {\n\t\treturn true\n\t}\n\n\tif createdMoreThan7DaysAgo(cm.CreatedAt) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/----------------------------------------------------------\n\/\/ Time helpers\n\/\/----------------------------------------------------------\n\nfunc createdMoreThan7DaysAgo(t time.Time) bool {\n\tt = t.UTC()\n\tdelta := time.Now().Sub(t)\n\n\treturn delta.Hours()\/24 > 7\n}\n\nfunc getStartOfDay(t time.Time) time.Time {\n\tt = t.UTC()\n\treturn now.New(t).BeginningOfDay()\n}\n\nfunc getDaysAgo(t time.Time, days int) time.Time {\n\tt = t.UTC()\n\tdaysAgo := -time.Hour * 24 * time.Duration(days)\n\n\treturn t.Add(daysAgo)\n}\n\n\/\/----------------------------------------------------------\nfunc (t *Controller) CreateKeyAtStartOfDay(groupName, channelName string) {\n\tendOfDay := now.EndOfDay().UTC()\n\tdifference := time.Now().UTC().Sub(endOfDay)\n\n\t<-time.After(difference)\n\n\tkeyname := &KeyName{\n\t\tGroupName: groupName, ChannelName: channelName,\n\t\tTime: time.Now().UTC(),\n\t}\n\n\tt.createSevenDayBucket(keyname)\n}\n\nfunc (t *Controller) ResetRegistry() {\n\tKeyExistsRegistry = map[string]bool{}\n}\n<commit_msg>popularpost: minor bug fix<commit_after>package popularpost\n\nimport (\n\t\"fmt\"\n\t\"socialapi\/config\"\n\t\"socialapi\/models\"\n\t\"time\"\n\n\t\"github.com\/jinzhu\/now\"\n\t\"github.com\/koding\/logging\"\n\t\"github.com\/koding\/redis\"\n\t\"github.com\/streadway\/amqp\"\n)\n\nvar (\n\tPopularPostKeyName = \"popularpost\"\n\tKeyExistsRegistry  = map[string]bool{}\n)\n\ntype Controller struct {\n\tlog   logging.Logger\n\tredis *redis.RedisSession\n}\n\nfunc (t *Controller) DefaultErrHandler(delivery amqp.Delivery, err error) bool {\n\tif delivery.Redelivered {\n\t\tt.log.Error(\"Redelivered message gave error again, putting to maintenance queue\", err)\n\t\tdelivery.Ack(false)\n\t\treturn true\n\t}\n\n\tt.log.Error(\"an error occured putting message back to queue\", err)\n\tdelivery.Nack(false, true)\n\treturn false\n}\n\nfunc New(log logging.Logger, redis *redis.RedisSession) *Controller {\n\treturn &Controller{\n\t\tlog:   log,\n\t\tredis: redis,\n\t}\n}\n\nfunc (f *Controller) InteractionSaved(i *models.Interaction) error {\n\treturn f.handleInteraction(1, i)\n}\n\nfunc (f *Controller) InteractionDeleted(i *models.Interaction) error {\n\treturn f.handleInteraction(-1, i)\n}\n\nfunc (f *Controller) handleInteraction(incrementCount int, i *models.Interaction) error {\n\tcm, err := models.ChannelMessageById(i.MessageId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc, err := models.ChannelById(cm.InitialChannelId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif notEligibleForPopularPost(c, cm) {\n\t\tf.log.Error(fmt.Sprintf(\"Not eligible Interaction Id:%d\", i.Id))\n\t\treturn nil\n\t}\n\n\tkeyname := &KeyName{\n\t\tGroupName: c.GroupName, ChannelName: c.Name,\n\t\tTime: cm.CreatedAt,\n\t}\n\n\terr = f.saveToDailyBucket(keyname, incrementCount, i.MessageId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = f.saveToSevenDayBucket(keyname, incrementCount, i.MessageId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (f *Controller) saveToDailyBucket(k *KeyName, inc int, id int64) error {\n\tkey := k.Today()\n\n\t_, err := f.redis.SortedSetIncrBy(key, inc, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tscore, err := f.redis.SortedSetScore(key, id)\n\tif score <= 0 {\n\t\t_, err := f.redis.SortedSetRem(key, id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn err\n}\n\nfunc (f *Controller) saveToSevenDayBucket(k *KeyName, inc int, id int64) error {\n\tkey := k.Weekly()\n\n\t_, ok := KeyExistsRegistry[key]\n\tif !ok {\n\t\texists := f.redis.Exists(key)\n\t\tif !exists {\n\t\t\terr := f.createSevenDayBucket(k)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tKeyExistsRegistry[key] = true\n\n\t\treturn nil\n\t}\n\n\t_, err := f.redis.SortedSetIncrBy(key, inc, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tscore, err := f.redis.SortedSetScore(key, id)\n\tif score <= 0 {\n\t\t_, err := f.redis.SortedSetRem(key, id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (f *Controller) createSevenDayBucket(k *KeyName) error {\n\tkeys, weights := []interface{}{}, []interface{}{}\n\n\tfrom := getStartOfDay(k.Time)\n\taggregate := \"SUM\"\n\n\tfor i := 0; i <= 6; i++ {\n\t\tcurrentDate := getDaysAgo(from, i)\n\t\tkeys = append(keys, k.Before(currentDate))\n\n\t\t\/\/ add by 1 to prevent divide by 0 errors\n\t\tweight := float64(i + 1)\n\t\tweights = append(weights, float64(1\/weight))\n\t}\n\n\t_, err := f.redis.SortedSetsUnion(k.Weekly(), keys, weights, aggregate)\n\n\treturn err\n}\n\nfunc PopularPostKey(groupName, channelName string, current time.Time) string {\n\tname := KeyName{\n\t\tGroupName: groupName, ChannelName: channelName,\n\t\tTime: current.UTC(),\n\t}\n\n\treturn name.Weekly()\n}\n\n\/\/----------------------------------------------------------\n\/\/ KeyName\n\/\/----------------------------------------------------------\n\ntype KeyName struct {\n\tGroupName, ChannelName string\n\tTime                   time.Time\n}\n\nfunc (k *KeyName) Today() string {\n\treturn k.do(getStartOfDay(k.Time))\n}\n\nfunc (k *KeyName) Before(t time.Time) string {\n\treturn k.do(t)\n}\n\nfunc (k *KeyName) Weekly() string {\n\tcurrent := getStartOfDay(k.Time.UTC())\n\tsevenDaysAgo := getDaysAgo(current, 7).UTC().Unix()\n\n\treturn fmt.Sprintf(\"%s-%d\", k.do(current), sevenDaysAgo)\n}\n\nfunc (k *KeyName) do(t time.Time) string {\n\treturn fmt.Sprintf(\"%s:%s:%s:%s:%d\",\n\t\tconfig.MustGet().Environment, k.GroupName, PopularPostKeyName,\n\t\tk.ChannelName, t.UTC().Unix(),\n\t)\n}\n\n\/\/----------------------------------------------------------\n\/\/ helpers\n\/\/----------------------------------------------------------\n\nfunc notEligibleForPopularPost(c *models.Channel, cm *models.ChannelMessage) bool {\n\tif c.MetaBits.Is(models.Troll) {\n\t\treturn true\n\t}\n\n\tif c.PrivacyConstant != models.Channel_PRIVACY_PUBLIC {\n\t\treturn true\n\t}\n\n\tif cm.MetaBits.Is(models.Troll) {\n\t\treturn true\n\t}\n\n\tif cm.TypeConstant != models.ChannelMessage_TYPE_POST {\n\t\treturn true\n\t}\n\n\tif createdMoreThan7DaysAgo(cm.CreatedAt) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/----------------------------------------------------------\n\/\/ Time helpers\n\/\/----------------------------------------------------------\n\nfunc createdMoreThan7DaysAgo(t time.Time) bool {\n\tt = t.UTC()\n\tdelta := time.Now().Sub(t)\n\n\treturn delta.Hours()\/24 > 7\n}\n\nfunc getStartOfDay(t time.Time) time.Time {\n\tt = t.UTC()\n\treturn now.New(t).BeginningOfDay()\n}\n\nfunc getDaysAgo(t time.Time, days int) time.Time {\n\tt = t.UTC()\n\tdaysAgo := -time.Hour * 24 * time.Duration(days)\n\n\treturn t.Add(daysAgo)\n}\n\n\/\/----------------------------------------------------------\nfunc (t *Controller) CreateKeyAtStartOfDay(groupName, channelName string) {\n\tendOfDay := now.EndOfDay().UTC()\n\tdifference := time.Now().UTC().Sub(endOfDay)\n\n\t<-time.After(difference)\n\n\tkeyname := &KeyName{\n\t\tGroupName: groupName, ChannelName: channelName,\n\t\tTime: time.Now().UTC(),\n\t}\n\n\tt.createSevenDayBucket(keyname)\n}\n\nfunc (t *Controller) ResetRegistry() {\n\tKeyExistsRegistry = map[string]bool{}\n}\n<|endoftext|>"}
{"text":"<commit_before>package prelude\n\nconst Prelude = prelude + types + numeric + goroutines + jsmapping\n\nconst prelude = `Error.stackTraceLimit = -1;\n\nvar $global, $module;\nif (typeof window !== \"undefined\") { \/* web page *\/\n  $global = window;\n} else if (typeof self !== \"undefined\") { \/* web worker *\/\n  $global = self;\n} else if (typeof global !== \"undefined\") { \/* Node.js *\/\n  $global = global;\n  $global.require = require;\n} else {\n  console.log(\"warning: no global object found\");\n}\nif (typeof module !== \"undefined\") {\n  $module = module;\n}\n\nvar $packages = {}, $reflect, $idCounter = 0;\nvar $keys = function(m) { return m ? Object.keys(m) : []; };\nvar $min = Math.min;\nvar $mod = function(x, y) { return x % y; };\nvar $parseInt = parseInt;\nvar $parseFloat = function(f) {\n  if (f.constructor === Number) {\n    return f;\n  }\n  return parseFloat(f);\n};\n\nvar $mapArray = function(array, f) {\n  var newArray = new array.constructor(array.length), i;\n  for (i = 0; i < array.length; i++) {\n    newArray[i] = f(array[i]);\n  }\n  return newArray;\n};\n\nvar $methodVal = function(recv, name) {\n  var vals = recv.$methodVals || {};\n  recv.$methodVals = vals; \/* noop for primitives *\/\n  var f = vals[name];\n  if (f !== undefined) {\n    return f;\n  }\n  var method = recv[name];\n  f = function() {\n    $stackDepthOffset--;\n    try {\n      return method.apply(recv, arguments);\n    } finally {\n      $stackDepthOffset++;\n    }\n  };\n  vals[name] = f;\n  return f;\n};\n\nvar $methodExpr = function(method) {\n  if (method.$expr === undefined) {\n    method.$expr = function() {\n      $stackDepthOffset--;\n      try {\n        return Function.call.apply(method, arguments);\n      } finally {\n        $stackDepthOffset++;\n      }\n    };\n  }\n  return method.$expr;\n};\n\nvar $subslice = function(slice, low, high, max) {\n  if (low < 0 || high < low || max < high || high > slice.$capacity || max > slice.$capacity) {\n    $throwRuntimeError(\"slice bounds out of range\");\n  }\n  var s = new slice.constructor(slice.$array);\n  s.$offset = slice.$offset + low;\n  s.$length = slice.$length - low;\n  s.$capacity = slice.$capacity - low;\n  if (high !== undefined) {\n    s.$length = high - low;\n  }\n  if (max !== undefined) {\n    s.$capacity = max - low;\n  }\n  return s;\n};\n\nvar $sliceToArray = function(slice) {\n  if (slice.$length === 0) {\n    return [];\n  }\n  if (slice.$array.constructor !== Array) {\n    return slice.$array.subarray(slice.$offset, slice.$offset + slice.$length);\n  }\n  return slice.$array.slice(slice.$offset, slice.$offset + slice.$length);\n};\n\nvar $decodeRune = function(str, pos) {\n  var c0 = str.charCodeAt(pos);\n\n  if (c0 < 0x80) {\n    return [c0, 1];\n  }\n\n  if (c0 !== c0 || c0 < 0xC0) {\n    return [0xFFFD, 1];\n  }\n\n  var c1 = str.charCodeAt(pos + 1);\n  if (c1 !== c1 || c1 < 0x80 || 0xC0 <= c1) {\n    return [0xFFFD, 1];\n  }\n\n  if (c0 < 0xE0) {\n    var r = (c0 & 0x1F) << 6 | (c1 & 0x3F);\n    if (r <= 0x7F) {\n      return [0xFFFD, 1];\n    }\n    return [r, 2];\n  }\n\n  var c2 = str.charCodeAt(pos + 2);\n  if (c2 !== c2 || c2 < 0x80 || 0xC0 <= c2) {\n    return [0xFFFD, 1];\n  }\n\n  if (c0 < 0xF0) {\n    var r = (c0 & 0x0F) << 12 | (c1 & 0x3F) << 6 | (c2 & 0x3F);\n    if (r <= 0x7FF) {\n      return [0xFFFD, 1];\n    }\n    if (0xD800 <= r && r <= 0xDFFF) {\n      return [0xFFFD, 1];\n    }\n    return [r, 3];\n  }\n\n  var c3 = str.charCodeAt(pos + 3);\n  if (c3 !== c3 || c3 < 0x80 || 0xC0 <= c3) {\n    return [0xFFFD, 1];\n  }\n\n  if (c0 < 0xF8) {\n    var r = (c0 & 0x07) << 18 | (c1 & 0x3F) << 12 | (c2 & 0x3F) << 6 | (c3 & 0x3F);\n    if (r <= 0xFFFF || 0x10FFFF < r) {\n      return [0xFFFD, 1];\n    }\n    return [r, 4];\n  }\n\n  return [0xFFFD, 1];\n};\n\nvar $encodeRune = function(r) {\n  if (r < 0 || r > 0x10FFFF || (0xD800 <= r && r <= 0xDFFF)) {\n    r = 0xFFFD;\n  }\n  if (r <= 0x7F) {\n    return String.fromCharCode(r);\n  }\n  if (r <= 0x7FF) {\n    return String.fromCharCode(0xC0 | r >> 6, 0x80 | (r & 0x3F));\n  }\n  if (r <= 0xFFFF) {\n    return String.fromCharCode(0xE0 | r >> 12, 0x80 | (r >> 6 & 0x3F), 0x80 | (r & 0x3F));\n  }\n  return String.fromCharCode(0xF0 | r >> 18, 0x80 | (r >> 12 & 0x3F), 0x80 | (r >> 6 & 0x3F), 0x80 | (r & 0x3F));\n};\n\nvar $stringToBytes = function(str) {\n  var array = new Uint8Array(str.length), i;\n  for (i = 0; i < str.length; i++) {\n    array[i] = str.charCodeAt(i);\n  }\n  return array;\n};\n\nvar $bytesToString = function(slice) {\n  if (slice.$length === 0) {\n    return \"\";\n  }\n  var str = \"\", i;\n  for (i = 0; i < slice.$length; i += 10000) {\n    str += String.fromCharCode.apply(null, slice.$array.subarray(slice.$offset + i, slice.$offset + Math.min(slice.$length, i + 10000)));\n  }\n  return str;\n};\n\nvar $stringToRunes = function(str) {\n  var array = new Int32Array(str.length);\n  var rune, i, j = 0;\n  for (i = 0; i < str.length; i += rune[1], j++) {\n    rune = $decodeRune(str, i);\n    array[j] = rune[0];\n  }\n  return array.subarray(0, j);\n};\n\nvar $runesToString = function(slice) {\n  if (slice.$length === 0) {\n    return \"\";\n  }\n  var str = \"\", i;\n  for (i = 0; i < slice.$length; i++) {\n    str += $encodeRune(slice.$array[slice.$offset + i]);\n  }\n  return str;\n};\n\nvar $copyString = function(dst, src) {\n  var n = Math.min(src.length, dst.$length), i;\n  for (i = 0; i < n; i++) {\n    dst.$array[dst.$offset + i] = src.charCodeAt(i);\n  }\n  return n;\n};\n\nvar $copySlice = function(dst, src) {\n  var n = Math.min(src.$length, dst.$length), i;\n  $internalCopy(dst.$array, src.$array, dst.$offset, src.$offset, n, dst.constructor.elem);\n  return n;\n};\n\nvar $copy = function(dst, src, type) {\n  var i;\n  switch (type.kind) {\n  case \"Array\":\n    $internalCopy(dst, src, 0, 0, src.length, type.elem);\n    return true;\n  case \"Struct\":\n    for (i = 0; i < type.fields.length; i++) {\n      var field = type.fields[i];\n      var name = field[0];\n      if (!$copy(dst[name], src[name], field[3])) {\n        dst[name] = src[name];\n      }\n    }\n    return true;\n  default:\n    return false;\n  }\n};\n\nvar $internalCopy = function(dst, src, dstOffset, srcOffset, n, elem) {\n  var i;\n  if (n === 0) {\n    return;\n  }\n\n  if (src.subarray) {\n    dst.set(src.subarray(srcOffset, srcOffset + n), dstOffset);\n    return;\n  }\n\n  switch (elem.kind) {\n  case \"Array\":\n  case \"Struct\":\n    for (i = 0; i < n; i++) {\n      $copy(dst[dstOffset + i], src[srcOffset + i], elem);\n    }\n    return;\n  }\n\n  for (i = 0; i < n; i++) {\n    dst[dstOffset + i] = src[srcOffset + i];\n  }\n};\n\nvar $clone = function(src, type) {\n  var clone = type.zero();\n  $copy(clone, src, type);\n  return clone;\n};\n\nvar $append = function(slice) {\n  return $internalAppend(slice, arguments, 1, arguments.length - 1);\n};\n\nvar $appendSlice = function(slice, toAppend) {\n  return $internalAppend(slice, toAppend.$array, toAppend.$offset, toAppend.$length);\n};\n\nvar $internalAppend = function(slice, array, offset, length) {\n  if (length === 0) {\n    return slice;\n  }\n\n  var newArray = slice.$array;\n  var newOffset = slice.$offset;\n  var newLength = slice.$length + length;\n  var newCapacity = slice.$capacity;\n\n  if (newLength > newCapacity) {\n    newOffset = 0;\n    newCapacity = Math.max(newLength, slice.$capacity < 1024 ? slice.$capacity * 2 : Math.floor(slice.$capacity * 5 \/ 4));\n\n    if (slice.$array.constructor === Array) {\n      newArray = slice.$array.slice(slice.$offset, slice.$offset + slice.$length);\n      newArray.length = newCapacity;\n      var zero = slice.constructor.elem.zero, i;\n      for (i = slice.$length; i < newCapacity; i++) {\n        newArray[i] = zero();\n      }\n    } else {\n      newArray = new slice.$array.constructor(newCapacity);\n      newArray.set(slice.$array.subarray(slice.$offset, slice.$offset + slice.$length));\n    }\n  }\n\n  $internalCopy(newArray, array, newOffset + slice.$length, offset, length, slice.constructor.elem);\n\n  var newSlice = new slice.constructor(newArray);\n  newSlice.$offset = newOffset;\n  newSlice.$length = newLength;\n  newSlice.$capacity = newCapacity;\n  return newSlice;\n};\n\nvar $equal = function(a, b, type) {\n  if (a === b) {\n    return true;\n  }\n  var i;\n  switch (type.kind) {\n  case \"Float32\":\n    return $float32IsEqual(a, b);\n  case \"Complex64\":\n    return $float32IsEqual(a.$real, b.$real) && $float32IsEqual(a.$imag, b.$imag);\n  case \"Complex128\":\n    return a.$real === b.$real && a.$imag === b.$imag;\n  case \"Int64\":\n  case \"Uint64\":\n    return a.$high === b.$high && a.$low === b.$low;\n  case \"Ptr\":\n    if (a.constructor.Struct) {\n      return false;\n    }\n    return $pointerIsEqual(a, b);\n  case \"Array\":\n    if (a.length != b.length) {\n      return false;\n    }\n    var i;\n    for (i = 0; i < a.length; i++) {\n      if (!$equal(a[i], b[i], type.elem)) {\n        return false;\n      }\n    }\n    return true;\n  case \"Struct\":\n    for (i = 0; i < type.fields.length; i++) {\n      var field = type.fields[i];\n      var name = field[0];\n      if (!$equal(a[name], b[name], field[3])) {\n        return false;\n      }\n    }\n    return true;\n  default:\n    return false;\n  }\n};\n\nvar $interfaceIsEqual = function(a, b) {\n  if (a === null || b === null || a === undefined || b === undefined || a.constructor !== b.constructor) {\n    return a === b;\n  }\n  switch (a.constructor.kind) {\n  case \"Func\":\n  case \"Map\":\n  case \"Slice\":\n  case \"Struct\":\n    $throwRuntimeError(\"comparing uncomparable type \" + a.constructor.string);\n  case undefined: \/* js.Object *\/\n    return a === b;\n  default:\n    return $equal(a.$val, b.$val, a.constructor);\n  }\n};\n\nvar $float32IsEqual = function(a, b) {\n  if (a === b) {\n    return true;\n  }\n  if (a === 0 || b === 0 || a === 1\/0 || b === 1\/0 || a === -1\/0 || b === -1\/0 || a !== a || b !== b) {\n    return false;\n  }\n  var math = $packages[\"math\"];\n  return math !== undefined && math.Float32bits(a) === math.Float32bits(b);\n};\n\nvar $sliceIsEqual = function(a, ai, b, bi) {\n  return a.$array === b.$array && a.$offset + ai === b.$offset + bi;\n};\n\nvar $pointerIsEqual = function(a, b) {\n  if (a === b) {\n    return true;\n  }\n  if (a.$get === $throwNilPointerError || b.$get === $throwNilPointerError) {\n    return a.$get === $throwNilPointerError && b.$get === $throwNilPointerError;\n  }\n  var old = a.$get();\n  var dummy = new Object();\n  a.$set(dummy);\n  var equal = b.$get() === dummy;\n  a.$set(old);\n  return equal;\n};\n`\n<commit_msg>fixed Error.stackTraceLimit (fixes #100)<commit_after>package prelude\n\nconst Prelude = prelude + types + numeric + goroutines + jsmapping\n\nconst prelude = `Error.stackTraceLimit = Infinity;\n\nvar $global, $module;\nif (typeof window !== \"undefined\") { \/* web page *\/\n  $global = window;\n} else if (typeof self !== \"undefined\") { \/* web worker *\/\n  $global = self;\n} else if (typeof global !== \"undefined\") { \/* Node.js *\/\n  $global = global;\n  $global.require = require;\n} else {\n  console.log(\"warning: no global object found\");\n}\nif (typeof module !== \"undefined\") {\n  $module = module;\n}\n\nvar $packages = {}, $reflect, $idCounter = 0;\nvar $keys = function(m) { return m ? Object.keys(m) : []; };\nvar $min = Math.min;\nvar $mod = function(x, y) { return x % y; };\nvar $parseInt = parseInt;\nvar $parseFloat = function(f) {\n  if (f.constructor === Number) {\n    return f;\n  }\n  return parseFloat(f);\n};\n\nvar $mapArray = function(array, f) {\n  var newArray = new array.constructor(array.length), i;\n  for (i = 0; i < array.length; i++) {\n    newArray[i] = f(array[i]);\n  }\n  return newArray;\n};\n\nvar $methodVal = function(recv, name) {\n  var vals = recv.$methodVals || {};\n  recv.$methodVals = vals; \/* noop for primitives *\/\n  var f = vals[name];\n  if (f !== undefined) {\n    return f;\n  }\n  var method = recv[name];\n  f = function() {\n    $stackDepthOffset--;\n    try {\n      return method.apply(recv, arguments);\n    } finally {\n      $stackDepthOffset++;\n    }\n  };\n  vals[name] = f;\n  return f;\n};\n\nvar $methodExpr = function(method) {\n  if (method.$expr === undefined) {\n    method.$expr = function() {\n      $stackDepthOffset--;\n      try {\n        return Function.call.apply(method, arguments);\n      } finally {\n        $stackDepthOffset++;\n      }\n    };\n  }\n  return method.$expr;\n};\n\nvar $subslice = function(slice, low, high, max) {\n  if (low < 0 || high < low || max < high || high > slice.$capacity || max > slice.$capacity) {\n    $throwRuntimeError(\"slice bounds out of range\");\n  }\n  var s = new slice.constructor(slice.$array);\n  s.$offset = slice.$offset + low;\n  s.$length = slice.$length - low;\n  s.$capacity = slice.$capacity - low;\n  if (high !== undefined) {\n    s.$length = high - low;\n  }\n  if (max !== undefined) {\n    s.$capacity = max - low;\n  }\n  return s;\n};\n\nvar $sliceToArray = function(slice) {\n  if (slice.$length === 0) {\n    return [];\n  }\n  if (slice.$array.constructor !== Array) {\n    return slice.$array.subarray(slice.$offset, slice.$offset + slice.$length);\n  }\n  return slice.$array.slice(slice.$offset, slice.$offset + slice.$length);\n};\n\nvar $decodeRune = function(str, pos) {\n  var c0 = str.charCodeAt(pos);\n\n  if (c0 < 0x80) {\n    return [c0, 1];\n  }\n\n  if (c0 !== c0 || c0 < 0xC0) {\n    return [0xFFFD, 1];\n  }\n\n  var c1 = str.charCodeAt(pos + 1);\n  if (c1 !== c1 || c1 < 0x80 || 0xC0 <= c1) {\n    return [0xFFFD, 1];\n  }\n\n  if (c0 < 0xE0) {\n    var r = (c0 & 0x1F) << 6 | (c1 & 0x3F);\n    if (r <= 0x7F) {\n      return [0xFFFD, 1];\n    }\n    return [r, 2];\n  }\n\n  var c2 = str.charCodeAt(pos + 2);\n  if (c2 !== c2 || c2 < 0x80 || 0xC0 <= c2) {\n    return [0xFFFD, 1];\n  }\n\n  if (c0 < 0xF0) {\n    var r = (c0 & 0x0F) << 12 | (c1 & 0x3F) << 6 | (c2 & 0x3F);\n    if (r <= 0x7FF) {\n      return [0xFFFD, 1];\n    }\n    if (0xD800 <= r && r <= 0xDFFF) {\n      return [0xFFFD, 1];\n    }\n    return [r, 3];\n  }\n\n  var c3 = str.charCodeAt(pos + 3);\n  if (c3 !== c3 || c3 < 0x80 || 0xC0 <= c3) {\n    return [0xFFFD, 1];\n  }\n\n  if (c0 < 0xF8) {\n    var r = (c0 & 0x07) << 18 | (c1 & 0x3F) << 12 | (c2 & 0x3F) << 6 | (c3 & 0x3F);\n    if (r <= 0xFFFF || 0x10FFFF < r) {\n      return [0xFFFD, 1];\n    }\n    return [r, 4];\n  }\n\n  return [0xFFFD, 1];\n};\n\nvar $encodeRune = function(r) {\n  if (r < 0 || r > 0x10FFFF || (0xD800 <= r && r <= 0xDFFF)) {\n    r = 0xFFFD;\n  }\n  if (r <= 0x7F) {\n    return String.fromCharCode(r);\n  }\n  if (r <= 0x7FF) {\n    return String.fromCharCode(0xC0 | r >> 6, 0x80 | (r & 0x3F));\n  }\n  if (r <= 0xFFFF) {\n    return String.fromCharCode(0xE0 | r >> 12, 0x80 | (r >> 6 & 0x3F), 0x80 | (r & 0x3F));\n  }\n  return String.fromCharCode(0xF0 | r >> 18, 0x80 | (r >> 12 & 0x3F), 0x80 | (r >> 6 & 0x3F), 0x80 | (r & 0x3F));\n};\n\nvar $stringToBytes = function(str) {\n  var array = new Uint8Array(str.length), i;\n  for (i = 0; i < str.length; i++) {\n    array[i] = str.charCodeAt(i);\n  }\n  return array;\n};\n\nvar $bytesToString = function(slice) {\n  if (slice.$length === 0) {\n    return \"\";\n  }\n  var str = \"\", i;\n  for (i = 0; i < slice.$length; i += 10000) {\n    str += String.fromCharCode.apply(null, slice.$array.subarray(slice.$offset + i, slice.$offset + Math.min(slice.$length, i + 10000)));\n  }\n  return str;\n};\n\nvar $stringToRunes = function(str) {\n  var array = new Int32Array(str.length);\n  var rune, i, j = 0;\n  for (i = 0; i < str.length; i += rune[1], j++) {\n    rune = $decodeRune(str, i);\n    array[j] = rune[0];\n  }\n  return array.subarray(0, j);\n};\n\nvar $runesToString = function(slice) {\n  if (slice.$length === 0) {\n    return \"\";\n  }\n  var str = \"\", i;\n  for (i = 0; i < slice.$length; i++) {\n    str += $encodeRune(slice.$array[slice.$offset + i]);\n  }\n  return str;\n};\n\nvar $copyString = function(dst, src) {\n  var n = Math.min(src.length, dst.$length), i;\n  for (i = 0; i < n; i++) {\n    dst.$array[dst.$offset + i] = src.charCodeAt(i);\n  }\n  return n;\n};\n\nvar $copySlice = function(dst, src) {\n  var n = Math.min(src.$length, dst.$length), i;\n  $internalCopy(dst.$array, src.$array, dst.$offset, src.$offset, n, dst.constructor.elem);\n  return n;\n};\n\nvar $copy = function(dst, src, type) {\n  var i;\n  switch (type.kind) {\n  case \"Array\":\n    $internalCopy(dst, src, 0, 0, src.length, type.elem);\n    return true;\n  case \"Struct\":\n    for (i = 0; i < type.fields.length; i++) {\n      var field = type.fields[i];\n      var name = field[0];\n      if (!$copy(dst[name], src[name], field[3])) {\n        dst[name] = src[name];\n      }\n    }\n    return true;\n  default:\n    return false;\n  }\n};\n\nvar $internalCopy = function(dst, src, dstOffset, srcOffset, n, elem) {\n  var i;\n  if (n === 0) {\n    return;\n  }\n\n  if (src.subarray) {\n    dst.set(src.subarray(srcOffset, srcOffset + n), dstOffset);\n    return;\n  }\n\n  switch (elem.kind) {\n  case \"Array\":\n  case \"Struct\":\n    for (i = 0; i < n; i++) {\n      $copy(dst[dstOffset + i], src[srcOffset + i], elem);\n    }\n    return;\n  }\n\n  for (i = 0; i < n; i++) {\n    dst[dstOffset + i] = src[srcOffset + i];\n  }\n};\n\nvar $clone = function(src, type) {\n  var clone = type.zero();\n  $copy(clone, src, type);\n  return clone;\n};\n\nvar $append = function(slice) {\n  return $internalAppend(slice, arguments, 1, arguments.length - 1);\n};\n\nvar $appendSlice = function(slice, toAppend) {\n  return $internalAppend(slice, toAppend.$array, toAppend.$offset, toAppend.$length);\n};\n\nvar $internalAppend = function(slice, array, offset, length) {\n  if (length === 0) {\n    return slice;\n  }\n\n  var newArray = slice.$array;\n  var newOffset = slice.$offset;\n  var newLength = slice.$length + length;\n  var newCapacity = slice.$capacity;\n\n  if (newLength > newCapacity) {\n    newOffset = 0;\n    newCapacity = Math.max(newLength, slice.$capacity < 1024 ? slice.$capacity * 2 : Math.floor(slice.$capacity * 5 \/ 4));\n\n    if (slice.$array.constructor === Array) {\n      newArray = slice.$array.slice(slice.$offset, slice.$offset + slice.$length);\n      newArray.length = newCapacity;\n      var zero = slice.constructor.elem.zero, i;\n      for (i = slice.$length; i < newCapacity; i++) {\n        newArray[i] = zero();\n      }\n    } else {\n      newArray = new slice.$array.constructor(newCapacity);\n      newArray.set(slice.$array.subarray(slice.$offset, slice.$offset + slice.$length));\n    }\n  }\n\n  $internalCopy(newArray, array, newOffset + slice.$length, offset, length, slice.constructor.elem);\n\n  var newSlice = new slice.constructor(newArray);\n  newSlice.$offset = newOffset;\n  newSlice.$length = newLength;\n  newSlice.$capacity = newCapacity;\n  return newSlice;\n};\n\nvar $equal = function(a, b, type) {\n  if (a === b) {\n    return true;\n  }\n  var i;\n  switch (type.kind) {\n  case \"Float32\":\n    return $float32IsEqual(a, b);\n  case \"Complex64\":\n    return $float32IsEqual(a.$real, b.$real) && $float32IsEqual(a.$imag, b.$imag);\n  case \"Complex128\":\n    return a.$real === b.$real && a.$imag === b.$imag;\n  case \"Int64\":\n  case \"Uint64\":\n    return a.$high === b.$high && a.$low === b.$low;\n  case \"Ptr\":\n    if (a.constructor.Struct) {\n      return false;\n    }\n    return $pointerIsEqual(a, b);\n  case \"Array\":\n    if (a.length != b.length) {\n      return false;\n    }\n    var i;\n    for (i = 0; i < a.length; i++) {\n      if (!$equal(a[i], b[i], type.elem)) {\n        return false;\n      }\n    }\n    return true;\n  case \"Struct\":\n    for (i = 0; i < type.fields.length; i++) {\n      var field = type.fields[i];\n      var name = field[0];\n      if (!$equal(a[name], b[name], field[3])) {\n        return false;\n      }\n    }\n    return true;\n  default:\n    return false;\n  }\n};\n\nvar $interfaceIsEqual = function(a, b) {\n  if (a === null || b === null || a === undefined || b === undefined || a.constructor !== b.constructor) {\n    return a === b;\n  }\n  switch (a.constructor.kind) {\n  case \"Func\":\n  case \"Map\":\n  case \"Slice\":\n  case \"Struct\":\n    $throwRuntimeError(\"comparing uncomparable type \" + a.constructor.string);\n  case undefined: \/* js.Object *\/\n    return a === b;\n  default:\n    return $equal(a.$val, b.$val, a.constructor);\n  }\n};\n\nvar $float32IsEqual = function(a, b) {\n  if (a === b) {\n    return true;\n  }\n  if (a === 0 || b === 0 || a === 1\/0 || b === 1\/0 || a === -1\/0 || b === -1\/0 || a !== a || b !== b) {\n    return false;\n  }\n  var math = $packages[\"math\"];\n  return math !== undefined && math.Float32bits(a) === math.Float32bits(b);\n};\n\nvar $sliceIsEqual = function(a, ai, b, bi) {\n  return a.$array === b.$array && a.$offset + ai === b.$offset + bi;\n};\n\nvar $pointerIsEqual = function(a, b) {\n  if (a === b) {\n    return true;\n  }\n  if (a.$get === $throwNilPointerError || b.$get === $throwNilPointerError) {\n    return a.$get === $throwNilPointerError && b.$get === $throwNilPointerError;\n  }\n  var old = a.$get();\n  var dummy = new Object();\n  a.$set(dummy);\n  var equal = b.$get() === dummy;\n  a.$set(old);\n  return equal;\n};\n`\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright The OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage component\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\n\t\"go.opentelemetry.io\/collector\/component\/componenterror\"\n\t\"go.opentelemetry.io\/collector\/config\"\n\t\"go.opentelemetry.io\/collector\/consumer\"\n\t\"go.opentelemetry.io\/collector\/internal\/internalinterface\"\n)\n\nvar _ ProcessorFactory = (*TestProcessorFactory)(nil)\n\ntype TestProcessorFactory struct {\n\tinternalinterface.BaseInternal\n\tname string\n}\n\n\/\/ Type gets the type of the Processor config created by this factory.\nfunc (f *TestProcessorFactory) Type() config.Type {\n\treturn config.Type(f.name)\n}\n\n\/\/ CreateDefaultConfig creates the default configuration for the Processor.\nfunc (f *TestProcessorFactory) CreateDefaultConfig() config.Processor {\n\treturn nil\n}\n\n\/\/ CreateTracesProcessor default implemented as not supported data type.\nfunc (f *TestProcessorFactory) CreateTracesProcessor(context.Context, ProcessorCreateSettings, config.Processor, consumer.Traces) (TracesProcessor, error) {\n\treturn nil, componenterror.ErrDataTypeIsNotSupported\n}\n\n\/\/ CreateMetricsProcessor default implemented as not supported data type.\nfunc (f *TestProcessorFactory) CreateMetricsProcessor(context.Context, ProcessorCreateSettings, config.Processor, consumer.Metrics) (MetricsProcessor, error) {\n\treturn nil, componenterror.ErrDataTypeIsNotSupported\n}\n\n\/\/ CreateLogsProcessor default implemented as not supported data type.\nfunc (f *TestProcessorFactory) CreateLogsProcessor(context.Context, ProcessorCreateSettings, config.Processor, consumer.Logs) (LogsProcessor, error) {\n\treturn nil, componenterror.ErrDataTypeIsNotSupported\n}\n\nfunc TestMakeProcessorFactoryMap(t *testing.T) {\n\ttype testCase struct {\n\t\tin  []ProcessorFactory\n\t\tout map[config.Type]ProcessorFactory\n\t}\n\n\ttestCases := []testCase{\n\t\t{\n\t\t\tin: []ProcessorFactory{\n\t\t\t\t&TestProcessorFactory{name: \"p1\"},\n\t\t\t\t&TestProcessorFactory{name: \"p2\"},\n\t\t\t},\n\t\t\tout: map[config.Type]ProcessorFactory{\n\t\t\t\t\"p1\": &TestProcessorFactory{name: \"p1\"},\n\t\t\t\t\"p2\": &TestProcessorFactory{name: \"p2\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tin: []ProcessorFactory{\n\t\t\t\t&TestProcessorFactory{name: \"p1\"},\n\t\t\t\t&TestProcessorFactory{name: \"p1\"},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, c := range testCases {\n\t\tout, err := MakeProcessorFactoryMap(c.in...)\n\t\tif c.out == nil {\n\t\t\tassert.Error(t, err)\n\t\t\tcontinue\n\t\t}\n\t\tassert.NoError(t, err)\n\t\tassert.Equal(t, c.out, out)\n\t}\n}\n<commit_msg>[component] Embed nil ProcessorFactory (#4336)<commit_after>\/\/ Copyright The OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage component\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\n\t\"go.opentelemetry.io\/collector\/config\"\n)\n\nvar _ ProcessorFactory = (*TestProcessorFactory)(nil)\n\ntype TestProcessorFactory struct {\n\tProcessorFactory\n\tname string\n}\n\n\/\/ Type gets the type of the Processor config created by this factory.\nfunc (f *TestProcessorFactory) Type() config.Type {\n\treturn config.Type(f.name)\n}\n\nfunc TestMakeProcessorFactoryMap(t *testing.T) {\n\ttype testCase struct {\n\t\tin  []ProcessorFactory\n\t\tout map[config.Type]ProcessorFactory\n\t}\n\n\ttestCases := []testCase{\n\t\t{\n\t\t\tin: []ProcessorFactory{\n\t\t\t\t&TestProcessorFactory{name: \"p1\"},\n\t\t\t\t&TestProcessorFactory{name: \"p2\"},\n\t\t\t},\n\t\t\tout: map[config.Type]ProcessorFactory{\n\t\t\t\t\"p1\": &TestProcessorFactory{name: \"p1\"},\n\t\t\t\t\"p2\": &TestProcessorFactory{name: \"p2\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tin: []ProcessorFactory{\n\t\t\t\t&TestProcessorFactory{name: \"p1\"},\n\t\t\t\t&TestProcessorFactory{name: \"p1\"},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, c := range testCases {\n\t\tout, err := MakeProcessorFactoryMap(c.in...)\n\t\tif c.out == nil {\n\t\t\tassert.Error(t, err)\n\t\t\tcontinue\n\t\t}\n\t\tassert.NoError(t, err)\n\t\tassert.Equal(t, c.out, out)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package acceptance_test\n\nimport (\n\t\"cf-pusher\/cf_cli_adapter\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"os\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/cf\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"policy cleanup\", func() {\n\tvar (\n\t\tappA, appB, appC string\n\t\torgName          string\n\t\tspaceName        string\n\t\tcfCli            *cf_cli_adapter.Adapter\n\t)\n\n\tBeforeEach(func() {\n\t\tappA = fmt.Sprintf(\"appA-%d\", rand.Int31())\n\t\tappB = fmt.Sprintf(\"appB-%d\", rand.Int31())\n\t\tappC = fmt.Sprintf(\"appC-%d\", rand.Int31())\n\n\t\tcfCli = &cf_cli_adapter.Adapter{\n\t\t\tCfCliPath: \"cf\",\n\t\t}\n\t\tAuthAsAdmin()\n\n\t\torgName = \"cleanup-org\"\n\t\tExpect(cfCli.CreateOrg(orgName)).To(Succeed())\n\t\tExpect(cfCli.TargetOrg(orgName)).To(Succeed())\n\n\t\tspaceName = \"cleanup-space\"\n\t\tExpect(cfCli.CreateSpace(spaceName)).To(Succeed())\n\t\tExpect(cfCli.TargetSpace(spaceName)).To(Succeed())\n\n\t\tpushProxy(appA)\n\t\tpushProxy(appB)\n\t\tpushProxy(appC)\n\t})\n\n\tAfterEach(func() {\n\t\tExpect(cf.Cf(\"delete-org\", orgName, \"-f\").Wait(Timeout_Push)).To(gexec.Exit(0))\n\t})\n\n\tDescribe(\"policies\/cleanup endpoint\", func() {\n\t\tIt(\"returns stale policies for deleted apps\", func() {\n\t\t\tBy(\"creating policies for all apps\")\n\t\t\tExpect(cfCli.AllowAccess(appA, appB, 1234, \"tcp\")).To(Succeed())\n\t\t\tExpect(cfCli.AllowAccess(appB, appC, 1234, \"tcp\")).To(Succeed())\n\t\t\tExpect(cfCli.AllowAccess(appC, appA, 1234, \"tcp\")).To(Succeed())\n\n\t\t\tappAGuid, err := cfCli.AppGuid(appA)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\tappCGuid, err := cfCli.AppGuid(appC)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\tBy(\"get all policies\")\n\t\t\tallPolicies, err := cfCli.Curl(\"GET\", \"\/networking\/v0\/external\/policies\", \"\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tExpect(string(allPolicies)).Should(ContainSubstring(appCGuid))\n\t\t\tExpect(string(allPolicies)).Should(ContainSubstring(appAGuid))\n\n\t\t\tBy(\"deleting appC\")\n\t\t\tExpect(cfCli.Delete(appC)).To(Succeed())\n\n\t\t\tBy(\"checking for stale policies\")\n\t\t\tstalePolicies, err := cfCli.Curl(\"POST\", \"\/networking\/v0\/external\/policies\/cleanup\", \"\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tfmt.Println(string(stalePolicies))\n\n\t\t\ttmpfile, err := ioutil.TempFile(\"\", \"stalepolicies\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tdefer os.Remove(tmpfile.Name())\n\n\t\t\t_, err = tmpfile.Write(stalePolicies)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tExpect(tmpfile.Close()).To(Succeed())\n\n\t\t\tBy(\"delete stale policies\")\n\t\t\t_, err = cfCli.Curl(\"DELETE\", \"\/networking\/v0\/external\/policies\", tmpfile.Name())\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\tBy(\"get all policies\")\n\t\t\tallPolicies, err = cfCli.Curl(\"GET\", \"\/networking\/v0\/external\/policies\", \"\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tExpect(string(allPolicies)).ShouldNot(ContainSubstring(appCGuid))\n\t\t\tExpect(string(allPolicies)).Should(ContainSubstring(appAGuid))\n\t\t})\n\t})\n})\n<commit_msg>Consistent verb tense in policy cleanup messages<commit_after>package acceptance_test\n\nimport (\n\t\"cf-pusher\/cf_cli_adapter\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"os\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/cf\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"policy cleanup\", func() {\n\tvar (\n\t\tappA, appB, appC string\n\t\torgName          string\n\t\tspaceName        string\n\t\tcfCli            *cf_cli_adapter.Adapter\n\t)\n\n\tBeforeEach(func() {\n\t\tappA = fmt.Sprintf(\"appA-%d\", rand.Int31())\n\t\tappB = fmt.Sprintf(\"appB-%d\", rand.Int31())\n\t\tappC = fmt.Sprintf(\"appC-%d\", rand.Int31())\n\n\t\tcfCli = &cf_cli_adapter.Adapter{\n\t\t\tCfCliPath: \"cf\",\n\t\t}\n\t\tAuthAsAdmin()\n\n\t\torgName = \"cleanup-org\"\n\t\tExpect(cfCli.CreateOrg(orgName)).To(Succeed())\n\t\tExpect(cfCli.TargetOrg(orgName)).To(Succeed())\n\n\t\tspaceName = \"cleanup-space\"\n\t\tExpect(cfCli.CreateSpace(spaceName)).To(Succeed())\n\t\tExpect(cfCli.TargetSpace(spaceName)).To(Succeed())\n\n\t\tpushProxy(appA)\n\t\tpushProxy(appB)\n\t\tpushProxy(appC)\n\t})\n\n\tAfterEach(func() {\n\t\tExpect(cf.Cf(\"delete-org\", orgName, \"-f\").Wait(Timeout_Push)).To(gexec.Exit(0))\n\t})\n\n\tDescribe(\"policies\/cleanup endpoint\", func() {\n\t\tIt(\"returns stale policies for deleted apps\", func() {\n\t\t\tBy(\"creating policies for all apps\")\n\t\t\tExpect(cfCli.AllowAccess(appA, appB, 1234, \"tcp\")).To(Succeed())\n\t\t\tExpect(cfCli.AllowAccess(appB, appC, 1234, \"tcp\")).To(Succeed())\n\t\t\tExpect(cfCli.AllowAccess(appC, appA, 1234, \"tcp\")).To(Succeed())\n\n\t\t\tappAGuid, err := cfCli.AppGuid(appA)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\tappCGuid, err := cfCli.AppGuid(appC)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\tBy(\"getting all policies\")\n\t\t\tallPolicies, err := cfCli.Curl(\"GET\", \"\/networking\/v0\/external\/policies\", \"\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tExpect(string(allPolicies)).Should(ContainSubstring(appCGuid))\n\t\t\tExpect(string(allPolicies)).Should(ContainSubstring(appAGuid))\n\n\t\t\tBy(\"deleting appC\")\n\t\t\tExpect(cfCli.Delete(appC)).To(Succeed())\n\n\t\t\tBy(\"checking for stale policies\")\n\t\t\tstalePolicies, err := cfCli.Curl(\"POST\", \"\/networking\/v0\/external\/policies\/cleanup\", \"\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tfmt.Println(string(stalePolicies))\n\n\t\t\ttmpfile, err := ioutil.TempFile(\"\", \"stalepolicies\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tdefer os.Remove(tmpfile.Name())\n\n\t\t\t_, err = tmpfile.Write(stalePolicies)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tExpect(tmpfile.Close()).To(Succeed())\n\n\t\t\tBy(\"deleting stale policies\")\n\t\t\t_, err = cfCli.Curl(\"DELETE\", \"\/networking\/v0\/external\/policies\", tmpfile.Name())\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\tBy(\"getting all policies\")\n\t\t\tallPolicies, err = cfCli.Curl(\"GET\", \"\/networking\/v0\/external\/policies\", \"\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tExpect(string(allPolicies)).ShouldNot(ContainSubstring(appCGuid))\n\t\t\tExpect(string(allPolicies)).Should(ContainSubstring(appAGuid))\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @author\t\tAeneas Rekkas <aeneas+oss@aeneas.io>\n * @copyright \t2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>\n * @license \tApache-2.0\n *\n *\/\n\npackage compose\n\nimport (\n\t\"crypto\/rsa\"\n\n\t\"github.com\/ory\/fosite\/handler\/oauth2\"\n\t\"github.com\/ory\/fosite\/handler\/openid\"\n\t\"github.com\/ory\/fosite\/token\/hmac\"\n\t\"github.com\/ory\/fosite\/token\/jwt\"\n)\n\ntype CommonStrategy struct {\n\toauth2.CoreStrategy\n\topenid.OpenIDConnectTokenStrategy\n\tjwt.JWTStrategy\n}\n\nfunc NewOAuth2HMACStrategy(config *Config, secret []byte, rotatedSecrets [][]byte) *oauth2.HMACSHAStrategy {\n\treturn &oauth2.HMACSHAStrategy{\n\t\tEnigma: &hmac.HMACStrategy{\n\t\t\tGlobalSecret:         secret,\n\t\t\tRotatedGlobalSecrets: rotatedSecrets,\n\t\t\tTokenEntropy:         config.GetTokenEntropy(),\n\t\t},\n\t\tAccessTokenLifespan:   config.GetAccessTokenLifespan(),\n\t\tAuthorizeCodeLifespan: config.GetAuthorizeCodeLifespan(),\n\t\tRefreshTokenLifespan:  config.GetRefreshTokenLifespan(),\n\t}\n}\n\nfunc NewOAuth2JWTStrategy(key *rsa.PrivateKey, strategy *oauth2.HMACSHAStrategy) *oauth2.DefaultJWTStrategy {\n\treturn &oauth2.DefaultJWTStrategy{\n\t\tJWTStrategy: &jwt.RS256JWTStrategy{\n\t\t\tPrivateKey: key,\n\t\t},\n\t\tHMACSHAStrategy: strategy,\n\t}\n}\n\nfunc NewOpenIDConnectStrategy(config *Config, key *rsa.PrivateKey) *openid.DefaultStrategy {\n\treturn &openid.DefaultStrategy{\n\t\tJWTStrategy: &jwt.RS256JWTStrategy{\n\t\t\tPrivateKey: key,\n\t\t},\n\t\tExpiry: config.GetIDTokenLifespan(),\n\t\tIssuer: config.IDTokenIssuer,\n\t}\n}\n<commit_msg>feat: new factory with default issuer for JWT tokens (#444)<commit_after>\/*\n * Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @author\t\tAeneas Rekkas <aeneas+oss@aeneas.io>\n * @copyright \t2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>\n * @license \tApache-2.0\n *\n *\/\n\npackage compose\n\nimport (\n\t\"crypto\/rsa\"\n\n\t\"github.com\/ory\/fosite\/handler\/oauth2\"\n\t\"github.com\/ory\/fosite\/handler\/openid\"\n\t\"github.com\/ory\/fosite\/token\/hmac\"\n\t\"github.com\/ory\/fosite\/token\/jwt\"\n)\n\ntype CommonStrategy struct {\n\toauth2.CoreStrategy\n\topenid.OpenIDConnectTokenStrategy\n\tjwt.JWTStrategy\n}\n\nfunc NewOAuth2HMACStrategy(config *Config, secret []byte, rotatedSecrets [][]byte) *oauth2.HMACSHAStrategy {\n\treturn &oauth2.HMACSHAStrategy{\n\t\tEnigma: &hmac.HMACStrategy{\n\t\t\tGlobalSecret:         secret,\n\t\t\tRotatedGlobalSecrets: rotatedSecrets,\n\t\t\tTokenEntropy:         config.GetTokenEntropy(),\n\t\t},\n\t\tAccessTokenLifespan:   config.GetAccessTokenLifespan(),\n\t\tAuthorizeCodeLifespan: config.GetAuthorizeCodeLifespan(),\n\t\tRefreshTokenLifespan:  config.GetRefreshTokenLifespan(),\n\t}\n}\n\nfunc NewOAuth2JWTStrategy(key *rsa.PrivateKey, strategy *oauth2.HMACSHAStrategy) *oauth2.DefaultJWTStrategy {\n\treturn &oauth2.DefaultJWTStrategy{\n\t\tJWTStrategy: &jwt.RS256JWTStrategy{\n\t\t\tPrivateKey: key,\n\t\t},\n\t\tHMACSHAStrategy: strategy,\n\t}\n}\n\nfunc NewOAuth2JWTStrategyWithIssuer(key *rsa.PrivateKey, strategy *oauth2.HMACSHAStrategy, issuer string) *oauth2.DefaultJWTStrategy {\n\treturn &oauth2.DefaultJWTStrategy{\n\t\tJWTStrategy: &jwt.RS256JWTStrategy{\n\t\t\tPrivateKey: key,\n\t\t},\n\t\tHMACSHAStrategy: strategy,\n\t\tIssuer: issuer,\n\t}\n}\n\nfunc NewOpenIDConnectStrategy(config *Config, key *rsa.PrivateKey) *openid.DefaultStrategy {\n\treturn &openid.DefaultStrategy{\n\t\tJWTStrategy: &jwt.RS256JWTStrategy{\n\t\t\tPrivateKey: key,\n\t\t},\n\t\tExpiry: config.GetIDTokenLifespan(),\n\t\tIssuer: config.IDTokenIssuer,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/hwaf\/hwaf\/hlib\"\n)\n\n\/\/ map of pkgname -> libname\n\/\/  if empty => ignore dep.\nvar g_pkg_map = map[string]string{\n\t\"AtlasCLHEP\":         \"CLHEP\",\n\t\"AtlasCOOL\":          \"COOL\",\n\t\"AtlasCORAL\":         \"CORAL\",\n\t\"AtlasCxxPolicy\":     \"\",\n\t\"AtlasFortranPolicy\": \"\",\n\t\"AtlasPOOL\":          \"POOL\",\n\t\"AtlasPython\":        \"python\",\n\t\"AtlasROOT\":          \"ROOT\",\n\t\"AtlasReflex\":        \"Reflex\",\n\t\"AtlasPolicy\":        \"\",\n\t\"ExternalPolicy\":     \"\",\n\t\"GaudiInterface\":     \"GaudiKernel\",\n}\n\nfunc find_tgt(wscript *hlib.Wscript_t, name string) (int, *hlib.Target_t) {\n\twbld := &wscript.Build\n\tfor i := range wbld.Targets {\n\t\tif wbld.Targets[i].Name == name {\n\t\t\treturn i, &wbld.Targets[i]\n\t\t}\n\t}\n\treturn -1, nil\n}\n\nfunc use_list(wscript *hlib.Wscript_t) []string {\n\tuses := []string{}\n\tfor _, dep := range wscript.Package.Deps {\n\t\tpkg := filepath.Base(dep.Name)\n\t\tuse_pkg, ok := g_pkg_map[pkg]\n\t\tif !ok {\n\t\t\tuse_pkg = pkg\n\t\t}\n\t\tif use_pkg != \"\" {\n\t\t\tuses = append(uses, use_pkg)\n\t\t}\n\t}\n\treturn uses\n}\n\nfunc cmt_arg_map(args []string) map[string]string {\n\to := make(map[string]string, len(args))\n\tfor _, v := range args {\n\t\tidx := strings.Index(v, \"=\")\n\t\tif idx < 0 {\n\t\t\tpanic(fmt.Errorf(\"cmt2yml: could not find '=' in string [%s]\", v))\n\t\t}\n\t\tif idx < 1 {\n\t\t\tpanic(fmt.Errorf(\"cmt2yml: malformed string [%s]\", v))\n\t\t}\n\t\tkk := v[:idx]\n\t\tvv := v[idx+1:]\n\t\tif vv == \"\" {\n\t\t\tpanic(fmt.Errorf(\"cmt2yml: malformed string [%s]\", v))\n\t\t}\n\t\tif vv[0] == '\"' {\n\t\t\tvv = vv[1:]\n\t\t}\n\t\tif strings.HasPrefix(vv, \"..\/\") {\n\t\t\tvv = vv[len(\"..\/\"):]\n\t\t}\n\t\to[kk] = vv\n\t}\n\treturn o\n}\n\nfunc cnv_atlas_library(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tlibname := \"\"\n\tswitch len(x.Args) {\n\tcase 0:\n\t\t\/\/ installed_library pattern\n\t\tlibname = filepath.Base(wscript.Package.Name)\n\tdefault:\n\t\t\/\/ named_installed_library pattern\n\t\tmargs := cmt_arg_map(x.Args)\n\t\tlibname = margs[\"library\"]\n\t}\n\tif libname == \"\" {\n\t\treturn fmt.Errorf(\n\t\t\t\"cmt2yml: empty atlas_library name (package=%s, args=%v)\",\n\t\t\twscript.Package.Name,\n\t\t\tx.Args,\n\t\t)\n\t}\n\titgt, tgt := find_tgt(wscript, libname)\n\tif itgt < 0 {\n\t\twscript.Build.Targets = append(\n\t\t\twscript.Build.Targets,\n\t\t\thlib.Target_t{Name: libname},\n\t\t)\n\t\titgt, tgt = find_tgt(wscript, libname)\n\t}\n\ttgt.Features = []string{\"atlas_library\"}\n\tuses := use_list(wscript)\n\tif len(uses) > 0 {\n\t\ttgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", uses)}\n\t}\n\n\t\/\/fmt.Printf(\">>> [%v] \\n\", *tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_component_library(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tlibname := \"\"\n\tswitch len(x.Args) {\n\tcase 0:\n\t\t\/\/ component_library pattern\n\t\tlibname = filepath.Base(wscript.Package.Name)\n\tdefault:\n\t\t\/\/ named_component_library pattern\n\t\tmargs := cmt_arg_map(x.Args)\n\t\tlibname = margs[\"library\"]\n\t}\n\tif libname == \"\" {\n\t\treturn fmt.Errorf(\n\t\t\t\"cmt2yml: empty atlas_component name (package=%s, args=%v)\",\n\t\t\twscript.Package.Name,\n\t\t\tx.Args,\n\t\t)\n\t}\n\titgt, tgt := find_tgt(wscript, libname)\n\tif itgt < 0 {\n\t\twscript.Build.Targets = append(\n\t\t\twscript.Build.Targets,\n\t\t\thlib.Target_t{Name: libname},\n\t\t)\n\t\titgt, tgt = find_tgt(wscript, libname)\n\t}\n\ttgt.Features = []string{\"atlas_component\"}\n\tuses := use_list(wscript)\n\tif len(uses) > 0 {\n\t\ttgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", uses)}\n\t}\n\n\t\/\/fmt.Printf(\">>> component [%v]...\\n\", *tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_dual_use_library(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tlibname := \"\"\n\tswitch len(x.Args) {\n\tcase 0:\n\t\t\/\/ dual_use_library pattern\n\t\tlibname = filepath.Base(wscript.Package.Name)\n\tdefault:\n\t\t\/\/ named_dual_use_library pattern\n\t\tmargs := cmt_arg_map(x.Args)\n\t\tif _, ok := margs[\"library\"]; ok {\n\t\t\tlibname = margs[\"library\"]\n\t\t} else {\n\t\t\tlibname = filepath.Base(wscript.Package.Name)\n\t\t}\n\n\t}\n\tif libname == \"\" {\n\t\treturn fmt.Errorf(\n\t\t\t\"cmt2yml: empty atlas_dual_use_library name (package=%s, args=%v)\",\n\t\t\twscript.Package.Name,\n\t\t\tx.Args,\n\t\t)\n\t}\n\titgt, tgt := find_tgt(wscript, libname)\n\tif itgt < 0 {\n\t\twscript.Build.Targets = append(\n\t\t\twscript.Build.Targets,\n\t\t\thlib.Target_t{Name: libname},\n\t\t)\n\t\titgt, tgt = find_tgt(wscript, libname)\n\t}\n\ttgt.Features = []string{\"atlas_dual_use_library\"}\n\tuses := use_list(wscript)\n\tif len(uses) > 0 {\n\t\ttgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", uses)}\n\t}\n\n\tfmt.Printf(\">>> [%v] \\n\", *tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_tpcnv_library(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tlibname := \"\"\n\tswitch len(x.Args) {\n\tcase 0:\n\t\t\/\/ tpcnv_library pattern\n\t\tlibname = filepath.Base(wscript.Package.Name)\n\tdefault:\n\t\t\/\/ named_tpcnv_library pattern\n\t\tmargs := cmt_arg_map(x.Args)\n\t\tlibname = margs[\"name\"]\n\t}\n\tif libname == \"\" {\n\t\treturn fmt.Errorf(\n\t\t\t\"cmt2yml: empty atlas_tpcnv name (package=%s, args=%v)\",\n\t\t\twscript.Package.Name,\n\t\t\tx.Args,\n\t\t)\n\t}\n\titgt, tgt := find_tgt(wscript, libname)\n\tif itgt < 0 {\n\t\twscript.Build.Targets = append(\n\t\t\twscript.Build.Targets,\n\t\t\thlib.Target_t{Name: libname},\n\t\t)\n\t\titgt, tgt = find_tgt(wscript, libname)\n\t}\n\ttgt.Features = []string{\"atlas_tpcnv\"}\n\tuses := use_list(wscript)\n\tif len(uses) > 0 {\n\t\ttgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", uses)}\n\t}\n\n\tfmt.Printf(\">>> [%v] \\n\", *tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_install_joboptions(wscript *hlib.Wscript_t, stmt Stmt) error {\n\t\/\/x := stmt.(*ApplyPattern)\n\t\/\/fmt.Printf(\">>> [%s] \\n\", x.Name)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\ttgt := hlib.Target_t{Name: pkgname + \"-install-jobos\"}\n\ttgt.Features = []string{\"atlas_install_joboptions\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\n\t\t\"jobos\",\n\t\t[]string{\"share\/*.py\", \"share\/*.txt\"},\n\t)}\n\twscript.Build.Targets = append(wscript.Build.Targets, tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_install_python_modules(wscript *hlib.Wscript_t, stmt Stmt) error {\n\t\/\/x := stmt.(*ApplyPattern)\n\t\/\/fmt.Printf(\">>> [%s] \\n\", x.Name)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\ttgt := hlib.Target_t{Name: pkgname + \"-install-py\"}\n\ttgt.Features = []string{\"atlas_install_python_modules\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\n\t\t\"python-files\",\n\t\t[]string{\"python\/*.py\"},\n\t)}\n\twscript.Build.Targets = append(wscript.Build.Targets, tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_install_scripts(wscript *hlib.Wscript_t, stmt Stmt) error {\n\t\/\/x := stmt.(*ApplyPattern)\n\t\/\/fmt.Printf(\">>> [%s] \\n\", x.Name)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\ttgt := hlib.Target_t{Name: pkgname + \"-install-scripts\"}\n\ttgt.Features = []string{\"atlas_install_scripts\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\n\t\t\"script-files\",\n\t\t[]string{\"scripts\/*\"},\n\t)}\n\twscript.Build.Targets = append(wscript.Build.Targets, tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_install_xmls(wscript *hlib.Wscript_t, stmt Stmt) error {\n\t\/\/x := stmt.(*ApplyPattern)\n\t\/\/fmt.Printf(\">>> [%s] \\n\", x.Name)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\ttgt := hlib.Target_t{Name: pkgname + \"-install-xmls\"}\n\ttgt.Features = []string{\"atlas_install_xmls\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\n\t\t\"xml-files\",\n\t\t[]string{\"xml\/*\"},\n\t)}\n\twscript.Build.Targets = append(wscript.Build.Targets, tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_install_data(wscript *hlib.Wscript_t, stmt Stmt) error {\n\t\/\/x := stmt.(*ApplyPattern)\n\t\/\/fmt.Printf(\">>> [%s] \\n\", x.Name)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\ttgt := hlib.Target_t{Name: pkgname + \"-install-data\"}\n\ttgt.Features = []string{\"atlas_install_data\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\n\t\t\"data-files\",\n\t\t[]string{\"data\/*\"},\n\t)}\n\twscript.Build.Targets = append(wscript.Build.Targets, tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_install_java(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tfmt.Printf(\">>> [%s] \\n\", x.Name)\n\treturn nil\n}\n\nfunc cnv_atlas_dictionary(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tmargs := cmt_arg_map(x.Args)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\tlibname := margs[\"dict\"] + \"Dict\"\n\tselfile := pkgname + \"\/\" + margs[\"selectionfile\"]\n\thdrfile := margs[\"headerfiles\"]\n\n\titgt, tgt := find_tgt(wscript, libname)\n\tif itgt < 0 {\n\t\twscript.Build.Targets = append(\n\t\t\twscript.Build.Targets,\n\t\t\thlib.Target_t{Name: libname},\n\t\t)\n\t\titgt, tgt = find_tgt(wscript, libname)\n\t}\n\ttgt.Features = []string{\"atlas_dictionary\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\"source\", []string{hdrfile})}\n\tif tgt.KwArgs == nil {\n\t\ttgt.KwArgs = make(map[string][]hlib.Value)\n\t}\n\ttgt.KwArgs[\"selection_file\"] = []hlib.Value{hlib.DefaultValue(\"selfile\", []string{selfile})}\n\t\/\/tgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", use_list(wscript))}\n\tuses := use_list(wscript)\n\tif len(uses) > 0 {\n\t\ttgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", uses)}\n\t}\n\tfmt.Printf(\">>> %v\\n\", *tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_unittest(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tmargs := cmt_arg_map(x.Args)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\tname := margs[\"unit_test\"]\n\ttgtname := fmt.Sprintf(\"%s-test-%s\", pkgname, name)\n\textra := margs[\"extrapatterns\"]\n\tsource := fmt.Sprintf(\"test\/%s_test.cxx\", name)\n\n\titgt, tgt := find_tgt(wscript, tgtname)\n\tif itgt < 0 {\n\t\twscript.Build.Targets = append(\n\t\t\twscript.Build.Targets,\n\t\t\thlib.Target_t{Name: tgtname},\n\t\t)\n\t\titgt, tgt = find_tgt(wscript, tgtname)\n\t}\n\ttgt.Features = []string{\"atlas_unittest\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\"source\", []string{source})}\n\tif tgt.KwArgs == nil {\n\t\ttgt.KwArgs = make(map[string][]hlib.Value)\n\t}\n\tif extra != \"\" {\n\t\ttgt.KwArgs[\"extrapatterns\"] = []hlib.Value{\n\t\t\thlib.DefaultValue(\"extrapatterns\", []string{extra}),\n\t\t}\n\t}\n\t\/\/tgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", use_list(wscript))}\n\tuses := use_list(wscript)\n\tif len(uses) > 0 {\n\t\ttgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", uses)}\n\t}\n\tfmt.Printf(\">>> %v\\n\", *tgt)\n\treturn nil\n}\n\n\/\/ EOF\n<commit_msg>cnv: less verbose<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/hwaf\/hwaf\/hlib\"\n)\n\n\/\/ map of pkgname -> libname\n\/\/  if empty => ignore dep.\nvar g_pkg_map = map[string]string{\n\t\"AtlasCLHEP\":         \"CLHEP\",\n\t\"AtlasCOOL\":          \"COOL\",\n\t\"AtlasCORAL\":         \"CORAL\",\n\t\"AtlasCxxPolicy\":     \"\",\n\t\"AtlasFortranPolicy\": \"\",\n\t\"AtlasPOOL\":          \"POOL\",\n\t\"AtlasPython\":        \"python\",\n\t\"AtlasROOT\":          \"ROOT\",\n\t\"AtlasReflex\":        \"Reflex\",\n\t\"AtlasPolicy\":        \"\",\n\t\"ExternalPolicy\":     \"\",\n\t\"GaudiInterface\":     \"GaudiKernel\",\n}\n\nfunc find_tgt(wscript *hlib.Wscript_t, name string) (int, *hlib.Target_t) {\n\twbld := &wscript.Build\n\tfor i := range wbld.Targets {\n\t\tif wbld.Targets[i].Name == name {\n\t\t\treturn i, &wbld.Targets[i]\n\t\t}\n\t}\n\treturn -1, nil\n}\n\nfunc use_list(wscript *hlib.Wscript_t) []string {\n\tuses := []string{}\n\tfor _, dep := range wscript.Package.Deps {\n\t\tpkg := filepath.Base(dep.Name)\n\t\tuse_pkg, ok := g_pkg_map[pkg]\n\t\tif !ok {\n\t\t\tuse_pkg = pkg\n\t\t}\n\t\tif use_pkg != \"\" {\n\t\t\tuses = append(uses, use_pkg)\n\t\t}\n\t}\n\treturn uses\n}\n\nfunc cmt_arg_map(args []string) map[string]string {\n\to := make(map[string]string, len(args))\n\tfor _, v := range args {\n\t\tidx := strings.Index(v, \"=\")\n\t\tif idx < 0 {\n\t\t\tpanic(fmt.Errorf(\"cmt2yml: could not find '=' in string [%s]\", v))\n\t\t}\n\t\tif idx < 1 {\n\t\t\tpanic(fmt.Errorf(\"cmt2yml: malformed string [%s]\", v))\n\t\t}\n\t\tkk := v[:idx]\n\t\tvv := v[idx+1:]\n\t\tif vv == \"\" {\n\t\t\tpanic(fmt.Errorf(\"cmt2yml: malformed string [%s]\", v))\n\t\t}\n\t\tif vv[0] == '\"' {\n\t\t\tvv = vv[1:]\n\t\t}\n\t\tif strings.HasPrefix(vv, \"..\/\") {\n\t\t\tvv = vv[len(\"..\/\"):]\n\t\t}\n\t\to[kk] = vv\n\t}\n\treturn o\n}\n\nfunc cnv_atlas_library(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tlibname := \"\"\n\tswitch len(x.Args) {\n\tcase 0:\n\t\t\/\/ installed_library pattern\n\t\tlibname = filepath.Base(wscript.Package.Name)\n\tdefault:\n\t\t\/\/ named_installed_library pattern\n\t\tmargs := cmt_arg_map(x.Args)\n\t\tlibname = margs[\"library\"]\n\t}\n\tif libname == \"\" {\n\t\treturn fmt.Errorf(\n\t\t\t\"cmt2yml: empty atlas_library name (package=%s, args=%v)\",\n\t\t\twscript.Package.Name,\n\t\t\tx.Args,\n\t\t)\n\t}\n\titgt, tgt := find_tgt(wscript, libname)\n\tif itgt < 0 {\n\t\twscript.Build.Targets = append(\n\t\t\twscript.Build.Targets,\n\t\t\thlib.Target_t{Name: libname},\n\t\t)\n\t\titgt, tgt = find_tgt(wscript, libname)\n\t}\n\ttgt.Features = []string{\"atlas_library\"}\n\tuses := use_list(wscript)\n\tif len(uses) > 0 {\n\t\ttgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", uses)}\n\t}\n\n\t\/\/fmt.Printf(\">>> [%v] \\n\", *tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_component_library(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tlibname := \"\"\n\tswitch len(x.Args) {\n\tcase 0:\n\t\t\/\/ component_library pattern\n\t\tlibname = filepath.Base(wscript.Package.Name)\n\tdefault:\n\t\t\/\/ named_component_library pattern\n\t\tmargs := cmt_arg_map(x.Args)\n\t\tlibname = margs[\"library\"]\n\t}\n\tif libname == \"\" {\n\t\treturn fmt.Errorf(\n\t\t\t\"cmt2yml: empty atlas_component name (package=%s, args=%v)\",\n\t\t\twscript.Package.Name,\n\t\t\tx.Args,\n\t\t)\n\t}\n\titgt, tgt := find_tgt(wscript, libname)\n\tif itgt < 0 {\n\t\twscript.Build.Targets = append(\n\t\t\twscript.Build.Targets,\n\t\t\thlib.Target_t{Name: libname},\n\t\t)\n\t\titgt, tgt = find_tgt(wscript, libname)\n\t}\n\ttgt.Features = []string{\"atlas_component\"}\n\tuses := use_list(wscript)\n\tif len(uses) > 0 {\n\t\ttgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", uses)}\n\t}\n\n\t\/\/fmt.Printf(\">>> component [%v]...\\n\", *tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_dual_use_library(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tlibname := \"\"\n\tswitch len(x.Args) {\n\tcase 0:\n\t\t\/\/ dual_use_library pattern\n\t\tlibname = filepath.Base(wscript.Package.Name)\n\tdefault:\n\t\t\/\/ named_dual_use_library pattern\n\t\tmargs := cmt_arg_map(x.Args)\n\t\tif _, ok := margs[\"library\"]; ok {\n\t\t\tlibname = margs[\"library\"]\n\t\t} else {\n\t\t\tlibname = filepath.Base(wscript.Package.Name)\n\t\t}\n\n\t}\n\tif libname == \"\" {\n\t\treturn fmt.Errorf(\n\t\t\t\"cmt2yml: empty atlas_dual_use_library name (package=%s, args=%v)\",\n\t\t\twscript.Package.Name,\n\t\t\tx.Args,\n\t\t)\n\t}\n\titgt, tgt := find_tgt(wscript, libname)\n\tif itgt < 0 {\n\t\twscript.Build.Targets = append(\n\t\t\twscript.Build.Targets,\n\t\t\thlib.Target_t{Name: libname},\n\t\t)\n\t\titgt, tgt = find_tgt(wscript, libname)\n\t}\n\ttgt.Features = []string{\"atlas_dual_use_library\"}\n\tuses := use_list(wscript)\n\tif len(uses) > 0 {\n\t\ttgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", uses)}\n\t}\n\n\t\/\/fmt.Printf(\">>> [%v] \\n\", *tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_tpcnv_library(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tlibname := \"\"\n\tswitch len(x.Args) {\n\tcase 0:\n\t\t\/\/ tpcnv_library pattern\n\t\tlibname = filepath.Base(wscript.Package.Name)\n\tdefault:\n\t\t\/\/ named_tpcnv_library pattern\n\t\tmargs := cmt_arg_map(x.Args)\n\t\tlibname = margs[\"name\"]\n\t}\n\tif libname == \"\" {\n\t\treturn fmt.Errorf(\n\t\t\t\"cmt2yml: empty atlas_tpcnv name (package=%s, args=%v)\",\n\t\t\twscript.Package.Name,\n\t\t\tx.Args,\n\t\t)\n\t}\n\titgt, tgt := find_tgt(wscript, libname)\n\tif itgt < 0 {\n\t\twscript.Build.Targets = append(\n\t\t\twscript.Build.Targets,\n\t\t\thlib.Target_t{Name: libname},\n\t\t)\n\t\titgt, tgt = find_tgt(wscript, libname)\n\t}\n\ttgt.Features = []string{\"atlas_tpcnv\"}\n\tuses := use_list(wscript)\n\tif len(uses) > 0 {\n\t\ttgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", uses)}\n\t}\n\n\t\/\/fmt.Printf(\">>> [%v] \\n\", *tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_install_joboptions(wscript *hlib.Wscript_t, stmt Stmt) error {\n\t\/\/x := stmt.(*ApplyPattern)\n\t\/\/fmt.Printf(\">>> [%s] \\n\", x.Name)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\ttgt := hlib.Target_t{Name: pkgname + \"-install-jobos\"}\n\ttgt.Features = []string{\"atlas_install_joboptions\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\n\t\t\"jobos\",\n\t\t[]string{\"share\/*.py\", \"share\/*.txt\"},\n\t)}\n\twscript.Build.Targets = append(wscript.Build.Targets, tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_install_python_modules(wscript *hlib.Wscript_t, stmt Stmt) error {\n\t\/\/x := stmt.(*ApplyPattern)\n\t\/\/fmt.Printf(\">>> [%s] \\n\", x.Name)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\ttgt := hlib.Target_t{Name: pkgname + \"-install-py\"}\n\ttgt.Features = []string{\"atlas_install_python_modules\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\n\t\t\"python-files\",\n\t\t[]string{\"python\/*.py\"},\n\t)}\n\twscript.Build.Targets = append(wscript.Build.Targets, tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_install_scripts(wscript *hlib.Wscript_t, stmt Stmt) error {\n\t\/\/x := stmt.(*ApplyPattern)\n\t\/\/fmt.Printf(\">>> [%s] \\n\", x.Name)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\ttgt := hlib.Target_t{Name: pkgname + \"-install-scripts\"}\n\ttgt.Features = []string{\"atlas_install_scripts\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\n\t\t\"script-files\",\n\t\t[]string{\"scripts\/*\"},\n\t)}\n\twscript.Build.Targets = append(wscript.Build.Targets, tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_install_xmls(wscript *hlib.Wscript_t, stmt Stmt) error {\n\t\/\/x := stmt.(*ApplyPattern)\n\t\/\/fmt.Printf(\">>> [%s] \\n\", x.Name)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\ttgt := hlib.Target_t{Name: pkgname + \"-install-xmls\"}\n\ttgt.Features = []string{\"atlas_install_xmls\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\n\t\t\"xml-files\",\n\t\t[]string{\"xml\/*\"},\n\t)}\n\twscript.Build.Targets = append(wscript.Build.Targets, tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_install_data(wscript *hlib.Wscript_t, stmt Stmt) error {\n\t\/\/x := stmt.(*ApplyPattern)\n\t\/\/fmt.Printf(\">>> [%s] \\n\", x.Name)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\ttgt := hlib.Target_t{Name: pkgname + \"-install-data\"}\n\ttgt.Features = []string{\"atlas_install_data\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\n\t\t\"data-files\",\n\t\t[]string{\"data\/*\"},\n\t)}\n\twscript.Build.Targets = append(wscript.Build.Targets, tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_install_java(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tfmt.Printf(\">>> [%s] \\n\", x.Name)\n\treturn nil\n}\n\nfunc cnv_atlas_dictionary(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tmargs := cmt_arg_map(x.Args)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\tlibname := margs[\"dict\"] + \"Dict\"\n\tselfile := pkgname + \"\/\" + margs[\"selectionfile\"]\n\thdrfile := margs[\"headerfiles\"]\n\n\titgt, tgt := find_tgt(wscript, libname)\n\tif itgt < 0 {\n\t\twscript.Build.Targets = append(\n\t\t\twscript.Build.Targets,\n\t\t\thlib.Target_t{Name: libname},\n\t\t)\n\t\titgt, tgt = find_tgt(wscript, libname)\n\t}\n\ttgt.Features = []string{\"atlas_dictionary\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\"source\", []string{hdrfile})}\n\tif tgt.KwArgs == nil {\n\t\ttgt.KwArgs = make(map[string][]hlib.Value)\n\t}\n\ttgt.KwArgs[\"selection_file\"] = []hlib.Value{hlib.DefaultValue(\"selfile\", []string{selfile})}\n\t\/\/tgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", use_list(wscript))}\n\tuses := use_list(wscript)\n\tif len(uses) > 0 {\n\t\ttgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", uses)}\n\t}\n\t\/\/fmt.Printf(\">>> %v\\n\", *tgt)\n\treturn nil\n}\n\nfunc cnv_atlas_unittest(wscript *hlib.Wscript_t, stmt Stmt) error {\n\tx := stmt.(*ApplyPattern)\n\tmargs := cmt_arg_map(x.Args)\n\tpkgname := filepath.Base(wscript.Package.Name)\n\tname := margs[\"unit_test\"]\n\ttgtname := fmt.Sprintf(\"%s-test-%s\", pkgname, name)\n\textra := margs[\"extrapatterns\"]\n\tsource := fmt.Sprintf(\"test\/%s_test.cxx\", name)\n\n\titgt, tgt := find_tgt(wscript, tgtname)\n\tif itgt < 0 {\n\t\twscript.Build.Targets = append(\n\t\t\twscript.Build.Targets,\n\t\t\thlib.Target_t{Name: tgtname},\n\t\t)\n\t\titgt, tgt = find_tgt(wscript, tgtname)\n\t}\n\ttgt.Features = []string{\"atlas_unittest\"}\n\ttgt.Source = []hlib.Value{hlib.DefaultValue(\"source\", []string{source})}\n\tif tgt.KwArgs == nil {\n\t\ttgt.KwArgs = make(map[string][]hlib.Value)\n\t}\n\tif extra != \"\" {\n\t\ttgt.KwArgs[\"extrapatterns\"] = []hlib.Value{\n\t\t\thlib.DefaultValue(\"extrapatterns\", []string{extra}),\n\t\t}\n\t}\n\t\/\/tgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", use_list(wscript))}\n\tuses := use_list(wscript)\n\tif len(uses) > 0 {\n\t\ttgt.Use = []hlib.Value{hlib.DefaultValue(\"uses\", uses)}\n\t}\n\t\/\/fmt.Printf(\">>> %v\\n\", *tgt)\n\treturn nil\n}\n\n\/\/ EOF\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage azure\n\nimport (\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"launchpad.net\/juju-core\/environs\"\n\t\"launchpad.net\/juju-core\/environs\/config\"\n\t\"launchpad.net\/juju-core\/instance\"\n\t\"launchpad.net\/loggo\"\n)\n\n\/\/ Register the Azure provider with Juju.\nfunc init() {\n\tenvirons.RegisterProvider(\"azure\", azureEnvironProvider{})\n}\n\n\/\/ Logger for the Azure provider.\nvar logger = loggo.GetLogger(\"juju.environs.azure\")\n\ntype azureEnvironProvider struct{}\n\n\/\/ azureEnvironProvider implements EnvironProvider.\nvar _ environs.EnvironProvider = (*azureEnvironProvider)(nil)\n\n\/\/ Open is specified in the EnvironProvider interface.\nfunc (prov azureEnvironProvider) Open(cfg *config.Config) (environs.Environ, error) {\n\tlogger.Debugf(\"opening environment %q.\", cfg.Name())\n\tenviron, err := NewEnviron(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn environ, nil\n}\n\n\/\/ PublicAddress is specified in the EnvironProvider interface.\nfunc (prov azureEnvironProvider) PublicAddress() (string, error) {\n\tconfig, err := parseWALAConfig()\n\tif err != nil {\n\t\tlogger.Errorf(\"error parsing Windows Azure Linux Agent config file (%q): %v\", _WALAConfigPath, err)\n\t\treturn \"\", err\n\t}\n\treturn config.getDeploymentFQDN(), nil\n}\n\n\/\/ PrivateAddress is specified in the EnvironProvider interface.\nfunc (prov azureEnvironProvider) PrivateAddress() (string, error) {\n\t\/\/ This returns the instance's *public* address for now.\n\t\/\/ We need to figure out how to do instance-to-instance\n\t\/\/ communication using the private IP before we can use the Azure\n\t\/\/ private address.\n\treturn prov.PublicAddress()\n\t\/*\n\t\tconfig, err := parseWALAConfig()\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"error parsing Windows Azure Linux Agent config file (%q): %v\", _WALAConfigPath, err)\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn config.getInternalIP(), nil\n\t*\/\n}\n\n\/\/ InstanceId is specified in the EnvironProvider interface.\nfunc (prov azureEnvironProvider) InstanceId() (instance.Id, error) {\n\tconfig, err := parseWALAConfig()\n\tif err != nil {\n\t\tlogger.Errorf(\"error parsing WALA config file (%q): %v\", _WALAConfigPath, err)\n\t\treturn instance.Id(\"\"), err\n\t}\n\treturn instance.Id(config.getDeploymentName()), nil\n}\n\n\/\/ The XML Windows Azure Linux Agent (WALA) is the agent which runs on all\n\/\/ the Linux Azure VMs.  The hostname of the VM is the service name and the\n\/\/ juju instanceId is (by design), the deployment's name.\n\/\/\n\/\/ See https:\/\/github.com\/windows-azure\/walinuxagent for more details.\n\/\/\n\/\/ Here is an example content of such a config file:\n\/\/ <?xml version=\"1.0\" encoding=\"utf-8\"?>\n\/\/ <SharedConfig version=\"1.0.0.0\" goalStateIncarnation=\"1\">\n\/\/   <Deployment name=\"b6de4c4c7d4a49c39270e0c57481fd9b\" guid=\"{495985a8-8e5a-49aa-826f-d1f7f51045b6}\" incarnation=\"0\">\n\/\/    <Service name=\"gwaclmachineex95rsek\" guid=\"{00000000-0000-0000-0000-000000000000}\" \/>\n\/\/    <ServiceInstance name=\"b6de4c4c7d4a49c39270e0c57481fd9b.0\" guid=\"{9806cac7-e566-42b8-9ecb-de8da8f69893}\" \/>\n\/\/  [...]\n\/\/  <Instances>\n\/\/    <Instance id=\"gwaclroleldc1o5p\" address=\"10.76.200.59\">\n\/\/      [...]\n\/\/    <\/Instance>\n\/\/  <\/Instances>\n\/\/  <\/Deployment>\n\/\/ <\/SharedConfig>\n\n\/\/ Structures used to parse the XML Windows Azure Linux Agent (WALA)\n\/\/ configuration file.\n\ntype WALASharedConfig struct {\n\tXMLName    xml.Name       `xml:\"SharedConfig\"`\n\tDeployment WALADeployment `xml:\"Deployment\"`\n\tInstances  []WALAInstance `xml:\"Instances>Instance\"`\n}\n\n\/\/ getDeploymentName returns the deployment name referenced by the\n\/\/ configuration.\n\/\/ Confusingly, this is stored in the 'name' attribute of the 'Service'\n\/\/ element.\nfunc (config *WALASharedConfig) getDeploymentName() string {\n\treturn config.Deployment.Service.Name\n}\n\n\/\/ getDeploymentFQDN returns the FQDN of this deployment.\n\/\/ The hostname is taken from the 'name' attribute of the 'Deployment' element\n\/\/ and the domain name is Azure's domain name: 'cloudapp.net'.\nfunc (config *WALASharedConfig) getDeploymentFQDN() string {\n\treturn fmt.Sprintf(\"%s.cloudapp.net\", config.Deployment.Name)\n}\n\n\/\/ getInternalIP returns the internal IP for this deployment.\n\/\/ The internalIP is the internal IP of the only instance in this deployment.\nfunc (config *WALASharedConfig) getInternalIP() string {\n\treturn config.Instances[0].Address\n}\n\ntype WALADeployment struct {\n\tName    string                `xml:\"name,attr\"`\n\tService WALADeploymentService `xml:\"Service\"`\n}\n\ntype WALADeploymentService struct {\n\tName string `xml:\"name,attr\"`\n}\n\ntype WALAInstance struct {\n\tAddress string `xml:\"address,attr\"`\n}\n\n\/\/ Path to the WALA configuration file.\nvar _WALAConfigPath = \"\/var\/lib\/waagent\/SharedConfig.xml\"\n\nfunc parseWALAConfig() (*WALASharedConfig, error) {\n\tdata, err := ioutil.ReadFile(_WALAConfigPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig := &WALASharedConfig{}\n\terr = xml.Unmarshal(data, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn config, nil\n}\n<commit_msg>Add comment.<commit_after>\/\/ Copyright 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage azure\n\nimport (\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"launchpad.net\/juju-core\/environs\"\n\t\"launchpad.net\/juju-core\/environs\/config\"\n\t\"launchpad.net\/juju-core\/instance\"\n\t\"launchpad.net\/loggo\"\n)\n\n\/\/ Register the Azure provider with Juju.\nfunc init() {\n\tenvirons.RegisterProvider(\"azure\", azureEnvironProvider{})\n}\n\n\/\/ Logger for the Azure provider.\nvar logger = loggo.GetLogger(\"juju.environs.azure\")\n\ntype azureEnvironProvider struct{}\n\n\/\/ azureEnvironProvider implements EnvironProvider.\nvar _ environs.EnvironProvider = (*azureEnvironProvider)(nil)\n\n\/\/ Open is specified in the EnvironProvider interface.\nfunc (prov azureEnvironProvider) Open(cfg *config.Config) (environs.Environ, error) {\n\tlogger.Debugf(\"opening environment %q.\", cfg.Name())\n\t\/\/ We can't return NewEnviron(cfg) directly here because otherwise,\n\t\/\/ when err is not nil, we end up with a non-nil returned environ and\n\t\/\/ this breaks the loop in cmd\/jujud\/upgrade.go:run() (see\n\t\/\/ http:\/\/golang.org\/doc\/faq#nil_error for the gory details).\n\tenviron, err := NewEnviron(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn environ, nil\n}\n\n\/\/ PublicAddress is specified in the EnvironProvider interface.\nfunc (prov azureEnvironProvider) PublicAddress() (string, error) {\n\tconfig, err := parseWALAConfig()\n\tif err != nil {\n\t\tlogger.Errorf(\"error parsing Windows Azure Linux Agent config file (%q): %v\", _WALAConfigPath, err)\n\t\treturn \"\", err\n\t}\n\treturn config.getDeploymentFQDN(), nil\n}\n\n\/\/ PrivateAddress is specified in the EnvironProvider interface.\nfunc (prov azureEnvironProvider) PrivateAddress() (string, error) {\n\t\/\/ This returns the instance's *public* address for now.\n\t\/\/ We need to figure out how to do instance-to-instance\n\t\/\/ communication using the private IP before we can use the Azure\n\t\/\/ private address.\n\treturn prov.PublicAddress()\n\t\/*\n\t\tconfig, err := parseWALAConfig()\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"error parsing Windows Azure Linux Agent config file (%q): %v\", _WALAConfigPath, err)\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn config.getInternalIP(), nil\n\t*\/\n}\n\n\/\/ InstanceId is specified in the EnvironProvider interface.\nfunc (prov azureEnvironProvider) InstanceId() (instance.Id, error) {\n\tconfig, err := parseWALAConfig()\n\tif err != nil {\n\t\tlogger.Errorf(\"error parsing WALA config file (%q): %v\", _WALAConfigPath, err)\n\t\treturn instance.Id(\"\"), err\n\t}\n\treturn instance.Id(config.getDeploymentName()), nil\n}\n\n\/\/ The XML Windows Azure Linux Agent (WALA) is the agent which runs on all\n\/\/ the Linux Azure VMs.  The hostname of the VM is the service name and the\n\/\/ juju instanceId is (by design), the deployment's name.\n\/\/\n\/\/ See https:\/\/github.com\/windows-azure\/walinuxagent for more details.\n\/\/\n\/\/ Here is an example content of such a config file:\n\/\/ <?xml version=\"1.0\" encoding=\"utf-8\"?>\n\/\/ <SharedConfig version=\"1.0.0.0\" goalStateIncarnation=\"1\">\n\/\/   <Deployment name=\"b6de4c4c7d4a49c39270e0c57481fd9b\" guid=\"{495985a8-8e5a-49aa-826f-d1f7f51045b6}\" incarnation=\"0\">\n\/\/    <Service name=\"gwaclmachineex95rsek\" guid=\"{00000000-0000-0000-0000-000000000000}\" \/>\n\/\/    <ServiceInstance name=\"b6de4c4c7d4a49c39270e0c57481fd9b.0\" guid=\"{9806cac7-e566-42b8-9ecb-de8da8f69893}\" \/>\n\/\/  [...]\n\/\/  <Instances>\n\/\/    <Instance id=\"gwaclroleldc1o5p\" address=\"10.76.200.59\">\n\/\/      [...]\n\/\/    <\/Instance>\n\/\/  <\/Instances>\n\/\/  <\/Deployment>\n\/\/ <\/SharedConfig>\n\n\/\/ Structures used to parse the XML Windows Azure Linux Agent (WALA)\n\/\/ configuration file.\n\ntype WALASharedConfig struct {\n\tXMLName    xml.Name       `xml:\"SharedConfig\"`\n\tDeployment WALADeployment `xml:\"Deployment\"`\n\tInstances  []WALAInstance `xml:\"Instances>Instance\"`\n}\n\n\/\/ getDeploymentName returns the deployment name referenced by the\n\/\/ configuration.\n\/\/ Confusingly, this is stored in the 'name' attribute of the 'Service'\n\/\/ element.\nfunc (config *WALASharedConfig) getDeploymentName() string {\n\treturn config.Deployment.Service.Name\n}\n\n\/\/ getDeploymentFQDN returns the FQDN of this deployment.\n\/\/ The hostname is taken from the 'name' attribute of the 'Deployment' element\n\/\/ and the domain name is Azure's domain name: 'cloudapp.net'.\nfunc (config *WALASharedConfig) getDeploymentFQDN() string {\n\treturn fmt.Sprintf(\"%s.cloudapp.net\", config.Deployment.Name)\n}\n\n\/\/ getInternalIP returns the internal IP for this deployment.\n\/\/ The internalIP is the internal IP of the only instance in this deployment.\nfunc (config *WALASharedConfig) getInternalIP() string {\n\treturn config.Instances[0].Address\n}\n\ntype WALADeployment struct {\n\tName    string                `xml:\"name,attr\"`\n\tService WALADeploymentService `xml:\"Service\"`\n}\n\ntype WALADeploymentService struct {\n\tName string `xml:\"name,attr\"`\n}\n\ntype WALAInstance struct {\n\tAddress string `xml:\"address,attr\"`\n}\n\n\/\/ Path to the WALA configuration file.\nvar _WALAConfigPath = \"\/var\/lib\/waagent\/SharedConfig.xml\"\n\nfunc parseWALAConfig() (*WALASharedConfig, error) {\n\tdata, err := ioutil.ReadFile(_WALAConfigPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig := &WALASharedConfig{}\n\terr = xml.Unmarshal(data, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn config, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package app\n\nimport (\n\t\"testing\"\n\n\tfxdebug \"github.com\/goph\/fxt\/debug\"\n\tfxlog \"github.com\/goph\/fxt\/log\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc TestNewLoggerConfig(t *testing.T) {\n\tconfig := Config{\n\t\tEnvironment: \"production\",\n\t\tLogFormat:   \"logfmt\",\n\t\tDebug:       false,\n\t}\n\n\texpected := fxlog.NewConfig()\n\texpected.Format = fxlog.LogfmtFormat\n\texpected.Debug = config.Debug\n\texpected.Context = []interface{}{\n\t\t\"environment\", config.Environment,\n\t\t\"service\", ServiceName,\n\t\t\"tag\", LogTag,\n\t}\n\n\tactual, err := NewLoggerConfig(config)\n\trequire.NoError(t, err)\n\tassert.Equal(t, expected, actual)\n}\n\nfunc TestNewDebugConfig(t *testing.T) {\n\ttests := map[string]struct{\n\t\tconfig Config\n\t\texpected *fxdebug.Config\n\t}{\n\t\t\"production\": {\n\t\t\tConfig{\n\t\t\t\tEnvironment: \"production\",\n\t\t\t\tDebug:       false,\n\t\t\t\tDebugAddr:   \":10000\",\n\t\t\t},\n\t\t\t&fxdebug.Config{\n\t\t\t\tNetwork: \"tcp\",\n\t\t\t\tAddr:    \":10000\",\n\t\t\t\tDebug:   false,\n\t\t\t},\n\t\t},\n\t\t\"development\": {\n\t\t\tConfig{\n\t\t\t\tEnvironment: \"development\",\n\t\t\t\tDebug:       true,\n\t\t\t\tDebugAddr:   \":10000\",\n\t\t\t},\n\t\t\t&fxdebug.Config{\n\t\t\t\tNetwork: \"tcp\",\n\t\t\t\tAddr:    \"127.0.0.1:10000\",\n\t\t\t\tDebug:   true,\n\t\t\t},\n\t\t},\n\t\t\"development_with_interface_specified\": {\n\t\t\tConfig{\n\t\t\t\tEnvironment: \"development\",\n\t\t\t\tDebug:       true,\n\t\t\t\tDebugAddr:   \"192.168.0.2:10000\",\n\t\t\t},\n\t\t\t&fxdebug.Config{\n\t\t\t\tNetwork: \"tcp\",\n\t\t\t\tAddr:    \"192.168.0.2:10000\",\n\t\t\t\tDebug:   true,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor name, test := range tests {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tactual := NewDebugConfig(test.config)\n\t\t\tassert.Equal(t, test.expected, actual)\n\t\t})\n\t}\n\n}\n<commit_msg>Fix cs<commit_after>package app\n\nimport (\n\t\"testing\"\n\n\tfxdebug \"github.com\/goph\/fxt\/debug\"\n\tfxlog \"github.com\/goph\/fxt\/log\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc TestNewLoggerConfig(t *testing.T) {\n\tconfig := Config{\n\t\tEnvironment: \"production\",\n\t\tLogFormat:   \"logfmt\",\n\t\tDebug:       false,\n\t}\n\n\texpected := fxlog.NewConfig()\n\texpected.Format = fxlog.LogfmtFormat\n\texpected.Debug = config.Debug\n\texpected.Context = []interface{}{\n\t\t\"environment\", config.Environment,\n\t\t\"service\", ServiceName,\n\t\t\"tag\", LogTag,\n\t}\n\n\tactual, err := NewLoggerConfig(config)\n\trequire.NoError(t, err)\n\tassert.Equal(t, expected, actual)\n}\n\nfunc TestNewDebugConfig(t *testing.T) {\n\ttests := map[string]struct {\n\t\tconfig   Config\n\t\texpected *fxdebug.Config\n\t}{\n\t\t\"production\": {\n\t\t\tConfig{\n\t\t\t\tEnvironment: \"production\",\n\t\t\t\tDebug:       false,\n\t\t\t\tDebugAddr:   \":10000\",\n\t\t\t},\n\t\t\t&fxdebug.Config{\n\t\t\t\tNetwork: \"tcp\",\n\t\t\t\tAddr:    \":10000\",\n\t\t\t\tDebug:   false,\n\t\t\t},\n\t\t},\n\t\t\"development\": {\n\t\t\tConfig{\n\t\t\t\tEnvironment: \"development\",\n\t\t\t\tDebug:       true,\n\t\t\t\tDebugAddr:   \":10000\",\n\t\t\t},\n\t\t\t&fxdebug.Config{\n\t\t\t\tNetwork: \"tcp\",\n\t\t\t\tAddr:    \"127.0.0.1:10000\",\n\t\t\t\tDebug:   true,\n\t\t\t},\n\t\t},\n\t\t\"development_with_interface_specified\": {\n\t\t\tConfig{\n\t\t\t\tEnvironment: \"development\",\n\t\t\t\tDebug:       true,\n\t\t\t\tDebugAddr:   \"192.168.0.2:10000\",\n\t\t\t},\n\t\t\t&fxdebug.Config{\n\t\t\t\tNetwork: \"tcp\",\n\t\t\t\tAddr:    \"192.168.0.2:10000\",\n\t\t\t\tDebug:   true,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor name, test := range tests {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tactual := NewDebugConfig(test.config)\n\t\t\tassert.Equal(t, test.expected, actual)\n\t\t})\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package container\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/docker\/engine-api\/types\/blkiodev\"\n\t\"github.com\/docker\/engine-api\/types\/strslice\"\n\t\"github.com\/docker\/go-connections\/nat\"\n\t\"github.com\/docker\/go-units\"\n)\n\n\/\/ NetworkMode represents the container network stack.\ntype NetworkMode string\n\n\/\/ IsolationLevel represents the isolation level of a container. The supported\n\/\/ values are platform specific\ntype IsolationLevel string\n\n\/\/ IsDefault indicates the default isolation level of a container. On Linux this\n\/\/ is the native driver. On Windows, this is a Windows Server Container.\nfunc (i IsolationLevel) IsDefault() bool {\n\treturn strings.ToLower(string(i)) == \"default\" || string(i) == \"\"\n}\n\n\/\/ IpcMode represents the container ipc stack.\ntype IpcMode string\n\n\/\/ IsPrivate indicates whether the container uses it's private ipc stack.\nfunc (n IpcMode) IsPrivate() bool {\n\treturn !(n.IsHost() || n.IsContainer())\n}\n\n\/\/ IsHost indicates whether the container uses the host's ipc stack.\nfunc (n IpcMode) IsHost() bool {\n\treturn n == \"host\"\n}\n\n\/\/ IsContainer indicates whether the container uses a container's ipc stack.\nfunc (n IpcMode) IsContainer() bool {\n\tparts := strings.SplitN(string(n), \":\", 2)\n\treturn len(parts) > 1 && parts[0] == \"container\"\n}\n\n\/\/ Valid indicates whether the ipc stack is valid.\nfunc (n IpcMode) Valid() bool {\n\tparts := strings.Split(string(n), \":\")\n\tswitch mode := parts[0]; mode {\n\tcase \"\", \"host\":\n\tcase \"container\":\n\t\tif len(parts) != 2 || parts[1] == \"\" {\n\t\t\treturn false\n\t\t}\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ Container returns the name of the container ipc stack is going to be used.\nfunc (n IpcMode) Container() string {\n\tparts := strings.SplitN(string(n), \":\", 2)\n\tif len(parts) > 1 {\n\t\treturn parts[1]\n\t}\n\treturn \"\"\n}\n\n\/\/ UTSMode represents the UTS namespace of the container.\ntype UTSMode string\n\n\/\/ IsPrivate indicates whether the container uses it's private UTS namespace.\nfunc (n UTSMode) IsPrivate() bool {\n\treturn !(n.IsHost())\n}\n\n\/\/ IsHost indicates whether the container uses the host's UTS namespace.\nfunc (n UTSMode) IsHost() bool {\n\treturn n == \"host\"\n}\n\n\/\/ Valid indicates whether the UTS namespace is valid.\nfunc (n UTSMode) Valid() bool {\n\tparts := strings.Split(string(n), \":\")\n\tswitch mode := parts[0]; mode {\n\tcase \"\", \"host\":\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ PidMode represents the pid stack of the container.\ntype PidMode string\n\n\/\/ IsPrivate indicates whether the container uses it's private pid stack.\nfunc (n PidMode) IsPrivate() bool {\n\treturn !(n.IsHost())\n}\n\n\/\/ IsHost indicates whether the container uses the host's pid stack.\nfunc (n PidMode) IsHost() bool {\n\treturn n == \"host\"\n}\n\n\/\/ Valid indicates whether the pid stack is valid.\nfunc (n PidMode) Valid() bool {\n\tparts := strings.Split(string(n), \":\")\n\tswitch mode := parts[0]; mode {\n\tcase \"\", \"host\":\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ DeviceMapping represents the device mapping between the host and the container.\ntype DeviceMapping struct {\n\tPathOnHost        string\n\tPathInContainer   string\n\tCgroupPermissions string\n}\n\n\/\/ RestartPolicy represents the restart policies of the container.\ntype RestartPolicy struct {\n\tName              string\n\tMaximumRetryCount int\n}\n\n\/\/ IsNone indicates whether the container has the \"no\" restart policy.\n\/\/ This means the container will not automatically restart when exiting.\nfunc (rp *RestartPolicy) IsNone() bool {\n\treturn rp.Name == \"no\"\n}\n\n\/\/ IsAlways indicates whether the container has the \"always\" restart policy.\n\/\/ This means the container will automatically restart regardless of the exit status.\nfunc (rp *RestartPolicy) IsAlways() bool {\n\treturn rp.Name == \"always\"\n}\n\n\/\/ IsOnFailure indicates whether the container has the \"on-failure\" restart policy.\n\/\/ This means the contain will automatically restart of exiting with a non-zero exit status.\nfunc (rp *RestartPolicy) IsOnFailure() bool {\n\treturn rp.Name == \"on-failure\"\n}\n\n\/\/ IsUnlessStopped indicates whether the container has the\n\/\/ \"unless-stopped\" restart policy. This means the container will\n\/\/ automatically restart unless user has put it to stopped state.\nfunc (rp *RestartPolicy) IsUnlessStopped() bool {\n\treturn rp.Name == \"unless-stopped\"\n}\n\n\/\/ IsSame compares two RestartPolicy to see if they are the same\nfunc (rp *RestartPolicy) IsSame(tp *RestartPolicy) bool {\n\treturn rp.Name == tp.Name && rp.MaximumRetryCount == tp.MaximumRetryCount\n}\n\n\/\/ LogConfig represents the logging configuration of the container.\ntype LogConfig struct {\n\tType   string\n\tConfig map[string]string\n}\n\n\/\/ Resources contains container's resources (cgroups config, ulimits...)\ntype Resources struct {\n\t\/\/ Applicable to all platforms\n\tCPUShares int64 `json:\"CpuShares\"` \/\/ CPU shares (relative weight vs. other containers)\n\n\t\/\/ Applicable to UNIX platforms\n\tCgroupParent         string \/\/ Parent cgroup.\n\tBlkioWeight          uint16 \/\/ Block IO weight (relative weight vs. other containers)\n\tBlkioWeightDevice    []*blkiodev.WeightDevice\n\tBlkioDeviceReadBps   []*blkiodev.ThrottleDevice\n\tBlkioDeviceWriteBps  []*blkiodev.ThrottleDevice\n\tBlkioDeviceReadIOps  []*blkiodev.ThrottleDevice\n\tBlkioDeviceWriteIOps []*blkiodev.ThrottleDevice\n\tCPUPeriod            int64           `json:\"CpuPeriod\"` \/\/ CPU CFS (Completely Fair Scheduler) period\n\tCPUQuota             int64           `json:\"CpuQuota\"`  \/\/ CPU CFS (Completely Fair Scheduler) quota\n\tCpusetCpus           string          \/\/ CpusetCpus 0-2, 0,1\n\tCpusetMems           string          \/\/ CpusetMems 0-2, 0,1\n\tDevices              []DeviceMapping \/\/ List of devices to map inside the container\n\tKernelMemory         int64           \/\/ Kernel memory limit (in bytes)\n\tMemory               int64           \/\/ Memory limit (in bytes)\n\tMemoryReservation    int64           \/\/ Memory soft limit (in bytes)\n\tMemorySwap           int64           \/\/ Total memory usage (memory + swap); set `-1` to disable swap\n\tMemorySwappiness     *int64          \/\/ Tuning container memory swappiness behaviour\n\tOomKillDisable       *bool           \/\/ Whether to disable OOM Killer or not\n\tPidsLimit            int64           \/\/ Setting pids limit for a container\n\tUlimits              []*units.Ulimit \/\/ List of ulimits to be set in the container\n}\n\n\/\/ UpdateConfig holds the mutable attributes of a Container.\n\/\/ Those attributes can be updated at runtime.\ntype UpdateConfig struct {\n\t\/\/ Contains container's resources (cgroups, ulimits)\n\tResources\n\tRestartPolicy RestartPolicy\n}\n\n\/\/ HostConfig the non-portable Config structure of a container.\n\/\/ Here, \"non-portable\" means \"dependent of the host we are running on\".\n\/\/ Portable information *should* appear in Config.\ntype HostConfig struct {\n\t\/\/ Applicable to all platforms\n\tBinds           []string      \/\/ List of volume bindings for this container\n\tContainerIDFile string        \/\/ File (path) where the containerId is written\n\tLogConfig       LogConfig     \/\/ Configuration of the logs for this container\n\tNetworkMode     NetworkMode   \/\/ Network mode to use for the container\n\tPortBindings    nat.PortMap   \/\/ Port mapping between the exposed port (container) and the host\n\tRestartPolicy   RestartPolicy \/\/ Restart policy to be used for the container\n\tVolumeDriver    string        \/\/ Name of the volume driver used to mount volumes\n\tVolumesFrom     []string      \/\/ List of volumes to take from other container\n\n\t\/\/ Applicable to UNIX platforms\n\tCapAdd          *strslice.StrSlice \/\/ List of kernel capabilities to add to the container\n\tCapDrop         *strslice.StrSlice \/\/ List of kernel capabilities to remove from the container\n\tDNS             []string           `json:\"Dns\"`        \/\/ List of DNS server to lookup\n\tDNSOptions      []string           `json:\"DnsOptions\"` \/\/ List of DNSOption to look for\n\tDNSSearch       []string           `json:\"DnsSearch\"`  \/\/ List of DNSSearch to look for\n\tExtraHosts      []string           \/\/ List of extra hosts\n\tGroupAdd        []string           \/\/ List of additional groups that the container process will run as\n\tIpcMode         IpcMode            \/\/ IPC namespace to use for the container\n\tLinks           []string           \/\/ List of links (in the name:alias form)\n\tOomScoreAdj     int                \/\/ Container preference for OOM-killing\n\tPidMode         PidMode            \/\/ PID namespace to use for the container\n\tPrivileged      bool               \/\/ Is the container in privileged mode\n\tPublishAllPorts bool               \/\/ Should docker publish all exposed port for the container\n\tReadonlyRootfs  bool               \/\/ Is the container root filesystem in read-only\n\tSecurityOpt     []string           \/\/ List of string values to customize labels for MLS systems, such as SELinux.\n\tTmpfs           map[string]string  `json:\",omitempty\"` \/\/ List of tmpfs (mounts) used for the container\n\tUTSMode         UTSMode            \/\/ UTS namespace to use for the container\n\tShmSize         int64              \/\/ Total shm memory usage\n\n\t\/\/ Applicable to Windows\n\tConsoleSize [2]int         \/\/ Initial console size\n\tIsolation   IsolationLevel \/\/ Isolation level of the container (eg default, hyperv)\n\n\t\/\/ Contains container's resources (cgroups, ulimits)\n\tResources\n}\n<commit_msg>Fix comment of swap limit<commit_after>package container\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/docker\/engine-api\/types\/blkiodev\"\n\t\"github.com\/docker\/engine-api\/types\/strslice\"\n\t\"github.com\/docker\/go-connections\/nat\"\n\t\"github.com\/docker\/go-units\"\n)\n\n\/\/ NetworkMode represents the container network stack.\ntype NetworkMode string\n\n\/\/ IsolationLevel represents the isolation level of a container. The supported\n\/\/ values are platform specific\ntype IsolationLevel string\n\n\/\/ IsDefault indicates the default isolation level of a container. On Linux this\n\/\/ is the native driver. On Windows, this is a Windows Server Container.\nfunc (i IsolationLevel) IsDefault() bool {\n\treturn strings.ToLower(string(i)) == \"default\" || string(i) == \"\"\n}\n\n\/\/ IpcMode represents the container ipc stack.\ntype IpcMode string\n\n\/\/ IsPrivate indicates whether the container uses it's private ipc stack.\nfunc (n IpcMode) IsPrivate() bool {\n\treturn !(n.IsHost() || n.IsContainer())\n}\n\n\/\/ IsHost indicates whether the container uses the host's ipc stack.\nfunc (n IpcMode) IsHost() bool {\n\treturn n == \"host\"\n}\n\n\/\/ IsContainer indicates whether the container uses a container's ipc stack.\nfunc (n IpcMode) IsContainer() bool {\n\tparts := strings.SplitN(string(n), \":\", 2)\n\treturn len(parts) > 1 && parts[0] == \"container\"\n}\n\n\/\/ Valid indicates whether the ipc stack is valid.\nfunc (n IpcMode) Valid() bool {\n\tparts := strings.Split(string(n), \":\")\n\tswitch mode := parts[0]; mode {\n\tcase \"\", \"host\":\n\tcase \"container\":\n\t\tif len(parts) != 2 || parts[1] == \"\" {\n\t\t\treturn false\n\t\t}\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ Container returns the name of the container ipc stack is going to be used.\nfunc (n IpcMode) Container() string {\n\tparts := strings.SplitN(string(n), \":\", 2)\n\tif len(parts) > 1 {\n\t\treturn parts[1]\n\t}\n\treturn \"\"\n}\n\n\/\/ UTSMode represents the UTS namespace of the container.\ntype UTSMode string\n\n\/\/ IsPrivate indicates whether the container uses it's private UTS namespace.\nfunc (n UTSMode) IsPrivate() bool {\n\treturn !(n.IsHost())\n}\n\n\/\/ IsHost indicates whether the container uses the host's UTS namespace.\nfunc (n UTSMode) IsHost() bool {\n\treturn n == \"host\"\n}\n\n\/\/ Valid indicates whether the UTS namespace is valid.\nfunc (n UTSMode) Valid() bool {\n\tparts := strings.Split(string(n), \":\")\n\tswitch mode := parts[0]; mode {\n\tcase \"\", \"host\":\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ PidMode represents the pid stack of the container.\ntype PidMode string\n\n\/\/ IsPrivate indicates whether the container uses it's private pid stack.\nfunc (n PidMode) IsPrivate() bool {\n\treturn !(n.IsHost())\n}\n\n\/\/ IsHost indicates whether the container uses the host's pid stack.\nfunc (n PidMode) IsHost() bool {\n\treturn n == \"host\"\n}\n\n\/\/ Valid indicates whether the pid stack is valid.\nfunc (n PidMode) Valid() bool {\n\tparts := strings.Split(string(n), \":\")\n\tswitch mode := parts[0]; mode {\n\tcase \"\", \"host\":\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ DeviceMapping represents the device mapping between the host and the container.\ntype DeviceMapping struct {\n\tPathOnHost        string\n\tPathInContainer   string\n\tCgroupPermissions string\n}\n\n\/\/ RestartPolicy represents the restart policies of the container.\ntype RestartPolicy struct {\n\tName              string\n\tMaximumRetryCount int\n}\n\n\/\/ IsNone indicates whether the container has the \"no\" restart policy.\n\/\/ This means the container will not automatically restart when exiting.\nfunc (rp *RestartPolicy) IsNone() bool {\n\treturn rp.Name == \"no\"\n}\n\n\/\/ IsAlways indicates whether the container has the \"always\" restart policy.\n\/\/ This means the container will automatically restart regardless of the exit status.\nfunc (rp *RestartPolicy) IsAlways() bool {\n\treturn rp.Name == \"always\"\n}\n\n\/\/ IsOnFailure indicates whether the container has the \"on-failure\" restart policy.\n\/\/ This means the contain will automatically restart of exiting with a non-zero exit status.\nfunc (rp *RestartPolicy) IsOnFailure() bool {\n\treturn rp.Name == \"on-failure\"\n}\n\n\/\/ IsUnlessStopped indicates whether the container has the\n\/\/ \"unless-stopped\" restart policy. This means the container will\n\/\/ automatically restart unless user has put it to stopped state.\nfunc (rp *RestartPolicy) IsUnlessStopped() bool {\n\treturn rp.Name == \"unless-stopped\"\n}\n\n\/\/ IsSame compares two RestartPolicy to see if they are the same\nfunc (rp *RestartPolicy) IsSame(tp *RestartPolicy) bool {\n\treturn rp.Name == tp.Name && rp.MaximumRetryCount == tp.MaximumRetryCount\n}\n\n\/\/ LogConfig represents the logging configuration of the container.\ntype LogConfig struct {\n\tType   string\n\tConfig map[string]string\n}\n\n\/\/ Resources contains container's resources (cgroups config, ulimits...)\ntype Resources struct {\n\t\/\/ Applicable to all platforms\n\tCPUShares int64 `json:\"CpuShares\"` \/\/ CPU shares (relative weight vs. other containers)\n\n\t\/\/ Applicable to UNIX platforms\n\tCgroupParent         string \/\/ Parent cgroup.\n\tBlkioWeight          uint16 \/\/ Block IO weight (relative weight vs. other containers)\n\tBlkioWeightDevice    []*blkiodev.WeightDevice\n\tBlkioDeviceReadBps   []*blkiodev.ThrottleDevice\n\tBlkioDeviceWriteBps  []*blkiodev.ThrottleDevice\n\tBlkioDeviceReadIOps  []*blkiodev.ThrottleDevice\n\tBlkioDeviceWriteIOps []*blkiodev.ThrottleDevice\n\tCPUPeriod            int64           `json:\"CpuPeriod\"` \/\/ CPU CFS (Completely Fair Scheduler) period\n\tCPUQuota             int64           `json:\"CpuQuota\"`  \/\/ CPU CFS (Completely Fair Scheduler) quota\n\tCpusetCpus           string          \/\/ CpusetCpus 0-2, 0,1\n\tCpusetMems           string          \/\/ CpusetMems 0-2, 0,1\n\tDevices              []DeviceMapping \/\/ List of devices to map inside the container\n\tKernelMemory         int64           \/\/ Kernel memory limit (in bytes)\n\tMemory               int64           \/\/ Memory limit (in bytes)\n\tMemoryReservation    int64           \/\/ Memory soft limit (in bytes)\n\tMemorySwap           int64           \/\/ Total memory usage (memory + swap); set `-1` to enable unlimited swap\n\tMemorySwappiness     *int64          \/\/ Tuning container memory swappiness behaviour\n\tOomKillDisable       *bool           \/\/ Whether to disable OOM Killer or not\n\tPidsLimit            int64           \/\/ Setting pids limit for a container\n\tUlimits              []*units.Ulimit \/\/ List of ulimits to be set in the container\n}\n\n\/\/ UpdateConfig holds the mutable attributes of a Container.\n\/\/ Those attributes can be updated at runtime.\ntype UpdateConfig struct {\n\t\/\/ Contains container's resources (cgroups, ulimits)\n\tResources\n\tRestartPolicy RestartPolicy\n}\n\n\/\/ HostConfig the non-portable Config structure of a container.\n\/\/ Here, \"non-portable\" means \"dependent of the host we are running on\".\n\/\/ Portable information *should* appear in Config.\ntype HostConfig struct {\n\t\/\/ Applicable to all platforms\n\tBinds           []string      \/\/ List of volume bindings for this container\n\tContainerIDFile string        \/\/ File (path) where the containerId is written\n\tLogConfig       LogConfig     \/\/ Configuration of the logs for this container\n\tNetworkMode     NetworkMode   \/\/ Network mode to use for the container\n\tPortBindings    nat.PortMap   \/\/ Port mapping between the exposed port (container) and the host\n\tRestartPolicy   RestartPolicy \/\/ Restart policy to be used for the container\n\tVolumeDriver    string        \/\/ Name of the volume driver used to mount volumes\n\tVolumesFrom     []string      \/\/ List of volumes to take from other container\n\n\t\/\/ Applicable to UNIX platforms\n\tCapAdd          *strslice.StrSlice \/\/ List of kernel capabilities to add to the container\n\tCapDrop         *strslice.StrSlice \/\/ List of kernel capabilities to remove from the container\n\tDNS             []string           `json:\"Dns\"`        \/\/ List of DNS server to lookup\n\tDNSOptions      []string           `json:\"DnsOptions\"` \/\/ List of DNSOption to look for\n\tDNSSearch       []string           `json:\"DnsSearch\"`  \/\/ List of DNSSearch to look for\n\tExtraHosts      []string           \/\/ List of extra hosts\n\tGroupAdd        []string           \/\/ List of additional groups that the container process will run as\n\tIpcMode         IpcMode            \/\/ IPC namespace to use for the container\n\tLinks           []string           \/\/ List of links (in the name:alias form)\n\tOomScoreAdj     int                \/\/ Container preference for OOM-killing\n\tPidMode         PidMode            \/\/ PID namespace to use for the container\n\tPrivileged      bool               \/\/ Is the container in privileged mode\n\tPublishAllPorts bool               \/\/ Should docker publish all exposed port for the container\n\tReadonlyRootfs  bool               \/\/ Is the container root filesystem in read-only\n\tSecurityOpt     []string           \/\/ List of string values to customize labels for MLS systems, such as SELinux.\n\tTmpfs           map[string]string  `json:\",omitempty\"` \/\/ List of tmpfs (mounts) used for the container\n\tUTSMode         UTSMode            \/\/ UTS namespace to use for the container\n\tShmSize         int64              \/\/ Total shm memory usage\n\n\t\/\/ Applicable to Windows\n\tConsoleSize [2]int         \/\/ Initial console size\n\tIsolation   IsolationLevel \/\/ Isolation level of the container (eg default, hyperv)\n\n\t\/\/ Contains container's resources (cgroups, ulimits)\n\tResources\n}\n<|endoftext|>"}
{"text":"<commit_before>package dnsr\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\tlru \"github.com\/hashicorp\/golang-lru\"\n\t\"github.com\/miekg\/dns\"\n)\n\n\/\/go:generate sh generate.sh\n\nvar (\n\tRoot           *Resolver\n\tDebugLogger    io.Writer\n\tTimeout        = 1000 * time.Millisecond\n\tMaxRecursion   = 10\n\tMaxNameservers = 2\n\tMaxIPs         = 2\n)\n\nfunc init() {\n\tRoot = New(strings.Count(root, \"\\n\"))\n\tfor t := range dns.ParseZone(strings.NewReader(root), \"\", \"\") {\n\t\tif t.Error == nil {\n\t\t\tRoot.saveDNSRR(t.RR)\n\t\t}\n\t}\n}\n\n\/\/ Resolver implements a primitive, non-recursive, caching DNS resolver.\ntype Resolver struct {\n\tcache  *lru.Cache\n\tclient *dns.Client\n}\n\n\/\/ New initializes a Resolver with the specified cache size. Cache size defaults to 10,000 if size <= 0.\nfunc New(size int) *Resolver {\n\tif size <= 0 {\n\t\tsize = 10000\n\t}\n\tcache, _ := lru.New(size)\n\tr := &Resolver{\n\t\tclient: &dns.Client{\n\t\t\tDialTimeout:  Timeout,\n\t\t\tReadTimeout:  Timeout,\n\t\t\tWriteTimeout: Timeout,\n\t\t},\n\t\tcache: cache,\n\t}\n\treturn r\n}\n\n\/\/ Resolve finds DNS records of type qtype for the domain qname. It returns a slice of *RR.\n\/\/ For nonexistent domains (where a DNS server will return NXDOMAIN), it will return an empty, non-nil slice.\n\/\/ Specify an empty string in qtype to receive any DNS records found (currently A, AAAA, NS, CNAME, and TXT).\nfunc (r *Resolver) Resolve(qname string, qtype string) []*RR {\n\treturn r.resolve(qname, qtype, 0)\n}\n\nfunc (r *Resolver) resolve(qname string, qtype string, depth int) []*RR {\n\tif depth++; depth > MaxRecursion {\n\t\tlogMaxRecursion(qname, qtype, depth)\n\t\treturn nil\n\t}\n\tqname = toLowerFQDN(qname)\n\tif rrs := r.cacheGet(qname, qtype); rrs != nil {\n\t\treturn rrs\n\t}\n\tlogResolveStart(qname, qtype, depth)\n\tdefer logResolveEnd(qname, qtype, depth, time.Now())\n\treturn r.resolveNS(qname, qtype, depth)\n}\n\nfunc (r *Resolver) resolveNS(qname string, qtype string, depth int) []*RR {\n\tsuccess := make(chan bool, 1)\n\tfor pname, ok := qname, true; ok; pname, ok = parent(pname) {\n\t\tif pname == qname && qtype == \"NS\" { \/\/ If we’re looking for [foo.com,NS], then skip to [com,NS]\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Query all DNS servers in parallel\n\t\tcount := 0\n\t\tfor _, nrr := range r.resolve(pname, \"NS\", depth) {\n\t\t\tif qtype != \"\" { \/\/ Early out for specific queries\n\t\t\t\tif rrs := r.cacheGet(qname, qtype); rrs != nil {\n\t\t\t\t\treturn rrs\n\t\t\t\t}\n\t\t\t}\n\t\t\tif nrr.Type != \"NS\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif count++; count > MaxNameservers {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tgo r.exchange(success, nrr.Value, qname, qtype, depth)\n\t\t}\n\n\t\t\/\/ Wait for first response\n\t\tif count > 0 {\n\t\t\tselect {\n\t\t\tcase <-success:\n\t\t\t\treturn r.resolveCNAMEs(qname, qtype, depth)\n\t\t\tcase <-time.After(Timeout):\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (r *Resolver) exchange(success chan<- bool, host string, qname string, qtype string, depth int) {\n\tdtype := dns.StringToType[qtype]\n\tif dtype == 0 {\n\t\tdtype = dns.TypeA\n\t}\n\tqmsg := &dns.Msg{}\n\tqmsg.SetQuestion(qname, dtype)\n\tqmsg.MsgHdr.RecursionDesired = false\n\n\t\/\/ Find each A record for the DNS server\n\tcount := 0\n\tfor _, rr := range r.resolve(host, \"A\", depth) {\n\t\tif rr.Type != \"A\" { \/\/ FIXME: support AAAA records?\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Never query more than MaxIPs for any nameserver\n\t\tif count++; count > MaxIPs {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Synchronously query this DNS server\n\t\tstart := time.Now()\n\t\trmsg, _, err := r.client.Exchange(qmsg, rr.Value+\":53\")\n\t\tlogExchange(rr.Value, qmsg, depth, start, err)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ FIXME: cache NXDOMAIN responses responsibly\n\t\tif rmsg.Rcode == dns.RcodeNameError {\n\t\t\tr.cacheAdd(qname, nil)\n\t\t}\n\n\t\t\/\/ If successful, cache the results\n\t\tr.saveDNSRR(rmsg.Answer...)\n\t\tr.saveDNSRR(rmsg.Ns...)\n\t\tr.saveDNSRR(rmsg.Extra...)\n\n\t\t\/\/ Never block\n\t\tselect {\n\t\tcase success <- true:\n\t\tdefault:\n\t\t}\n\n\t\t\/\/ Return after first successful network request\n\t\treturn\n\t}\n}\n\nfunc (r *Resolver) resolveCNAMEs(qname string, qtype string, depth int) []*RR {\n\trrs := []*RR{} \/\/ Return non-nil slice indicating difference between NXDOMAIN and an error\n\tfor _, crr := range r.cacheGet(qname, \"\") {\n\t\trrs = append(rrs, crr)\n\t\tif crr.Type != \"CNAME\" {\n\t\t\tcontinue\n\t\t}\n\t\tlogCNAME(depth, crr.String())\n\t\tfor _, rr := range r.resolve(crr.Value, qtype, depth) {\n\t\t\tr.cacheAdd(qname, rr)\n\t\t\trrs = append(rrs, crr)\n\t\t}\n\t}\n\treturn rrs\n}\n\nfunc parent(name string) (string, bool) {\n\tlabels := dns.SplitDomainName(name)\n\tif labels == nil {\n\t\treturn \"\", false\n\t}\n\treturn toLowerFQDN(strings.Join(labels[1:], \".\")), true\n}\n\nfunc toLowerFQDN(name string) string {\n\treturn dns.Fqdn(strings.ToLower(name))\n}\n\nfunc logMaxRecursion(qname string, qtype string, depth int) {\n\tfmt.Printf(\"%s Error: MAX RECURSION @ %s %s %d\\n\",\n\t\tstrings.Repeat(\"│   \", depth-1), qname, qtype, depth)\n}\n\nfunc logResolveStart(qname string, qtype string, depth int) {\n\tif DebugLogger == nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(DebugLogger, \"%s┌─── resolve(\\\"%s\\\", \\\"%s\\\", %d)\\n\",\n\t\tstrings.Repeat(\"│   \", depth-1), qname, qtype, depth)\n}\n\nfunc logResolveEnd(qname string, qtype string, depth int, start time.Time) {\n\tif DebugLogger == nil {\n\t\treturn\n\t}\n\tdur := time.Since(start)\n\tfmt.Fprintf(DebugLogger, \"%s└─── %dms: resolve(\\\"%s\\\", \\\"%s\\\", %d)\\n\",\n\t\tstrings.Repeat(\"│   \", depth-1), dur\/time.Millisecond, qname, qtype, depth)\n}\n\nfunc logCNAME(depth int, cname string) {\n\tif DebugLogger == nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(DebugLogger, \"%s│    CNAME: %s\\n\", strings.Repeat(\"│   \", depth-1), cname)\n}\n\nfunc logExchange(host string, qmsg *dns.Msg, depth int, start time.Time, err error) {\n\tif DebugLogger == nil {\n\t\treturn\n\t}\n\tdur := time.Since(start)\n\tfmt.Fprintf(DebugLogger, \"%s│    %dms: dig @%s %s %s\\n\",\n\t\tstrings.Repeat(\"│   \", depth-1), dur\/time.Millisecond, host, qmsg.Question[0].Name, dns.TypeToString[qmsg.Question[0].Qtype])\n\tif err != nil {\n\t\tfmt.Fprintf(DebugLogger, \"%s│    %dms: ERROR: %s\\n\",\n\t\t\tstrings.Repeat(\"│   \", depth-1), dur\/time.Millisecond, err.Error())\n\t}\n}\n\n\/\/ RR represents a DNS resource record.\ntype RR struct {\n\tName  string\n\tType  string\n\tValue string\n}\n\n\/\/ String returns a string representation of an RR in zone-file format.\nfunc (rr *RR) String() string {\n\treturn rr.Name + \"\\t      3600\\tIN\\t\" + rr.Type + \"\\t\" + rr.Value\n}\n\nfunc convertRR(drr dns.RR) *RR {\n\tswitch t := drr.(type) {\n\tcase *dns.NS:\n\t\treturn &RR{t.Hdr.Name, dns.TypeToString[t.Hdr.Rrtype], t.Ns}\n\tcase *dns.CNAME:\n\t\treturn &RR{t.Hdr.Name, dns.TypeToString[t.Hdr.Rrtype], t.Target}\n\tcase *dns.A:\n\t\treturn &RR{t.Hdr.Name, dns.TypeToString[t.Hdr.Rrtype], t.A.String()}\n\tcase *dns.AAAA:\n\t\treturn &RR{t.Hdr.Name, dns.TypeToString[t.Hdr.Rrtype], t.AAAA.String()}\n\tcase *dns.TXT:\n\t\treturn &RR{t.Hdr.Name, dns.TypeToString[t.Hdr.Rrtype], strings.Join(t.Txt, \"\\t\")}\n\tdefault:\n\t\t\/\/ fmt.Printf(\"%s\\n\", drr.String())\n\t}\n\treturn nil\n}\n\ntype key struct {\n\tName string\n\tType string\n}\n\ntype entry struct {\n\tm   sync.RWMutex\n\trrs map[RR]struct{}\n}\n\n\/\/ saveDNSRR saves 1 or more DNS records to the resolver cache.\nfunc (r *Resolver) saveDNSRR(drrs ...dns.RR) {\n\tfor _, drr := range drrs {\n\t\tif rr := convertRR(drr); rr != nil {\n\t\t\tr.cacheAdd(rr.Name, rr)\n\t\t}\n\t}\n}\n\n\/\/ cacheAdd adds 0 or more DNS records to the resolver cache for a specific\n\/\/ domain name and record type. This ensures the cache entry exists, even\n\/\/ if empty, for NXDOMAIN responses.\nfunc (r *Resolver) cacheAdd(qname string, rr *RR) {\n\tqname = toLowerFQDN(qname)\n\te := r.getEntry(qname)\n\tif e == nil {\n\t\te = &entry{rrs: make(map[RR]struct{}, 0)}\n\t\te.m.Lock()\n\t\tr.cache.Add(qname, e)\n\t} else {\n\t\te.m.Lock()\n\t}\n\tdefer e.m.Unlock()\n\tif rr != nil {\n\t\te.rrs[*rr] = struct{}{}\n\t}\n}\n\n\/\/ cacheGet returns a randomly ordered slice of DNS records.\nfunc (r *Resolver) cacheGet(qname string, qtype string) []*RR {\n\te := r.getEntry(qname)\n\tif e == nil && r != Root {\n\t\te = Root.getEntry(qname)\n\t}\n\tif e == nil {\n\t\treturn nil\n\t}\n\te.m.RLock()\n\tdefer e.m.RUnlock()\n\tif len(e.rrs) == 0 {\n\t\treturn []*RR{}\n\t}\n\trrs := make([]*RR, 0, len(e.rrs))\n\tfor rr, _ := range e.rrs {\n\t\t\/\/ fmt.Printf(\"%s\\n\", rr.String())\n\t\tif qtype == \"\" || rr.Type == qtype {\n\t\t\trrs = append(rrs, &RR{rr.Name, rr.Type, rr.Value})\n\t\t}\n\t}\n\tif len(rrs) == 0 && (qtype != \"\" && qtype != \"NS\") {\n\t\treturn nil\n\t}\n\treturn rrs\n}\n\n\/\/ getEntry returns a single cache entry or nil if an entry does not exist in the cache.\nfunc (r *Resolver) getEntry(qname string) *entry {\n\tc, ok := r.cache.Get(qname)\n\tif !ok {\n\t\treturn nil\n\t}\n\te, ok := c.(*entry)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn e\n}\n<commit_msg>Do not log recursion errors to stdout<commit_after>package dnsr\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\tlru \"github.com\/hashicorp\/golang-lru\"\n\t\"github.com\/miekg\/dns\"\n)\n\n\/\/go:generate sh generate.sh\n\nvar (\n\tRoot           *Resolver\n\tDebugLogger    io.Writer\n\tTimeout        = 1000 * time.Millisecond\n\tMaxRecursion   = 10\n\tMaxNameservers = 2\n\tMaxIPs         = 2\n)\n\nfunc init() {\n\tRoot = New(strings.Count(root, \"\\n\"))\n\tfor t := range dns.ParseZone(strings.NewReader(root), \"\", \"\") {\n\t\tif t.Error == nil {\n\t\t\tRoot.saveDNSRR(t.RR)\n\t\t}\n\t}\n}\n\n\/\/ Resolver implements a primitive, non-recursive, caching DNS resolver.\ntype Resolver struct {\n\tcache  *lru.Cache\n\tclient *dns.Client\n}\n\n\/\/ New initializes a Resolver with the specified cache size. Cache size defaults to 10,000 if size <= 0.\nfunc New(size int) *Resolver {\n\tif size <= 0 {\n\t\tsize = 10000\n\t}\n\tcache, _ := lru.New(size)\n\tr := &Resolver{\n\t\tclient: &dns.Client{\n\t\t\tDialTimeout:  Timeout,\n\t\t\tReadTimeout:  Timeout,\n\t\t\tWriteTimeout: Timeout,\n\t\t},\n\t\tcache: cache,\n\t}\n\treturn r\n}\n\n\/\/ Resolve finds DNS records of type qtype for the domain qname. It returns a slice of *RR.\n\/\/ For nonexistent domains (where a DNS server will return NXDOMAIN), it will return an empty, non-nil slice.\n\/\/ Specify an empty string in qtype to receive any DNS records found (currently A, AAAA, NS, CNAME, and TXT).\nfunc (r *Resolver) Resolve(qname string, qtype string) []*RR {\n\treturn r.resolve(qname, qtype, 0)\n}\n\nfunc (r *Resolver) resolve(qname string, qtype string, depth int) []*RR {\n\tif depth++; depth > MaxRecursion {\n\t\tlogMaxRecursion(qname, qtype, depth)\n\t\treturn nil\n\t}\n\tqname = toLowerFQDN(qname)\n\tif rrs := r.cacheGet(qname, qtype); rrs != nil {\n\t\treturn rrs\n\t}\n\tlogResolveStart(qname, qtype, depth)\n\tdefer logResolveEnd(qname, qtype, depth, time.Now())\n\treturn r.resolveNS(qname, qtype, depth)\n}\n\nfunc (r *Resolver) resolveNS(qname string, qtype string, depth int) []*RR {\n\tsuccess := make(chan bool, 1)\n\tfor pname, ok := qname, true; ok; pname, ok = parent(pname) {\n\t\tif pname == qname && qtype == \"NS\" { \/\/ If we’re looking for [foo.com,NS], then skip to [com,NS]\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Query all DNS servers in parallel\n\t\tcount := 0\n\t\tfor _, nrr := range r.resolve(pname, \"NS\", depth) {\n\t\t\tif qtype != \"\" { \/\/ Early out for specific queries\n\t\t\t\tif rrs := r.cacheGet(qname, qtype); rrs != nil {\n\t\t\t\t\treturn rrs\n\t\t\t\t}\n\t\t\t}\n\t\t\tif nrr.Type != \"NS\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif count++; count > MaxNameservers {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tgo r.exchange(success, nrr.Value, qname, qtype, depth)\n\t\t}\n\n\t\t\/\/ Wait for first response\n\t\tif count > 0 {\n\t\t\tselect {\n\t\t\tcase <-success:\n\t\t\t\treturn r.resolveCNAMEs(qname, qtype, depth)\n\t\t\tcase <-time.After(Timeout):\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (r *Resolver) exchange(success chan<- bool, host string, qname string, qtype string, depth int) {\n\tdtype := dns.StringToType[qtype]\n\tif dtype == 0 {\n\t\tdtype = dns.TypeA\n\t}\n\tqmsg := &dns.Msg{}\n\tqmsg.SetQuestion(qname, dtype)\n\tqmsg.MsgHdr.RecursionDesired = false\n\n\t\/\/ Find each A record for the DNS server\n\tcount := 0\n\tfor _, rr := range r.resolve(host, \"A\", depth) {\n\t\tif rr.Type != \"A\" { \/\/ FIXME: support AAAA records?\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Never query more than MaxIPs for any nameserver\n\t\tif count++; count > MaxIPs {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Synchronously query this DNS server\n\t\tstart := time.Now()\n\t\trmsg, _, err := r.client.Exchange(qmsg, rr.Value+\":53\")\n\t\tlogExchange(rr.Value, qmsg, depth, start, err)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ FIXME: cache NXDOMAIN responses responsibly\n\t\tif rmsg.Rcode == dns.RcodeNameError {\n\t\t\tr.cacheAdd(qname, nil)\n\t\t}\n\n\t\t\/\/ If successful, cache the results\n\t\tr.saveDNSRR(rmsg.Answer...)\n\t\tr.saveDNSRR(rmsg.Ns...)\n\t\tr.saveDNSRR(rmsg.Extra...)\n\n\t\t\/\/ Never block\n\t\tselect {\n\t\tcase success <- true:\n\t\tdefault:\n\t\t}\n\n\t\t\/\/ Return after first successful network request\n\t\treturn\n\t}\n}\n\nfunc (r *Resolver) resolveCNAMEs(qname string, qtype string, depth int) []*RR {\n\trrs := []*RR{} \/\/ Return non-nil slice indicating difference between NXDOMAIN and an error\n\tfor _, crr := range r.cacheGet(qname, \"\") {\n\t\trrs = append(rrs, crr)\n\t\tif crr.Type != \"CNAME\" {\n\t\t\tcontinue\n\t\t}\n\t\tlogCNAME(depth, crr.String())\n\t\tfor _, rr := range r.resolve(crr.Value, qtype, depth) {\n\t\t\tr.cacheAdd(qname, rr)\n\t\t\trrs = append(rrs, crr)\n\t\t}\n\t}\n\treturn rrs\n}\n\nfunc parent(name string) (string, bool) {\n\tlabels := dns.SplitDomainName(name)\n\tif labels == nil {\n\t\treturn \"\", false\n\t}\n\treturn toLowerFQDN(strings.Join(labels[1:], \".\")), true\n}\n\nfunc toLowerFQDN(name string) string {\n\treturn dns.Fqdn(strings.ToLower(name))\n}\n\nfunc logMaxRecursion(qname string, qtype string, depth int) {\n\tif DebugLogger == nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(DebugLogger, \"%s Error: MAX RECURSION @ %s %s %d\\n\",\n\t\tstrings.Repeat(\"│   \", depth-1), qname, qtype, depth)\n}\n\nfunc logResolveStart(qname string, qtype string, depth int) {\n\tif DebugLogger == nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(DebugLogger, \"%s┌─── resolve(\\\"%s\\\", \\\"%s\\\", %d)\\n\",\n\t\tstrings.Repeat(\"│   \", depth-1), qname, qtype, depth)\n}\n\nfunc logResolveEnd(qname string, qtype string, depth int, start time.Time) {\n\tif DebugLogger == nil {\n\t\treturn\n\t}\n\tdur := time.Since(start)\n\tfmt.Fprintf(DebugLogger, \"%s└─── %dms: resolve(\\\"%s\\\", \\\"%s\\\", %d)\\n\",\n\t\tstrings.Repeat(\"│   \", depth-1), dur\/time.Millisecond, qname, qtype, depth)\n}\n\nfunc logCNAME(depth int, cname string) {\n\tif DebugLogger == nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(DebugLogger, \"%s│    CNAME: %s\\n\", strings.Repeat(\"│   \", depth-1), cname)\n}\n\nfunc logExchange(host string, qmsg *dns.Msg, depth int, start time.Time, err error) {\n\tif DebugLogger == nil {\n\t\treturn\n\t}\n\tdur := time.Since(start)\n\tfmt.Fprintf(DebugLogger, \"%s│    %dms: dig @%s %s %s\\n\",\n\t\tstrings.Repeat(\"│   \", depth-1), dur\/time.Millisecond, host, qmsg.Question[0].Name, dns.TypeToString[qmsg.Question[0].Qtype])\n\tif err != nil {\n\t\tfmt.Fprintf(DebugLogger, \"%s│    %dms: ERROR: %s\\n\",\n\t\t\tstrings.Repeat(\"│   \", depth-1), dur\/time.Millisecond, err.Error())\n\t}\n}\n\n\/\/ RR represents a DNS resource record.\ntype RR struct {\n\tName  string\n\tType  string\n\tValue string\n}\n\n\/\/ String returns a string representation of an RR in zone-file format.\nfunc (rr *RR) String() string {\n\treturn rr.Name + \"\\t      3600\\tIN\\t\" + rr.Type + \"\\t\" + rr.Value\n}\n\nfunc convertRR(drr dns.RR) *RR {\n\tswitch t := drr.(type) {\n\tcase *dns.NS:\n\t\treturn &RR{t.Hdr.Name, dns.TypeToString[t.Hdr.Rrtype], t.Ns}\n\tcase *dns.CNAME:\n\t\treturn &RR{t.Hdr.Name, dns.TypeToString[t.Hdr.Rrtype], t.Target}\n\tcase *dns.A:\n\t\treturn &RR{t.Hdr.Name, dns.TypeToString[t.Hdr.Rrtype], t.A.String()}\n\tcase *dns.AAAA:\n\t\treturn &RR{t.Hdr.Name, dns.TypeToString[t.Hdr.Rrtype], t.AAAA.String()}\n\tcase *dns.TXT:\n\t\treturn &RR{t.Hdr.Name, dns.TypeToString[t.Hdr.Rrtype], strings.Join(t.Txt, \"\\t\")}\n\tdefault:\n\t\t\/\/ fmt.Printf(\"%s\\n\", drr.String())\n\t}\n\treturn nil\n}\n\ntype key struct {\n\tName string\n\tType string\n}\n\ntype entry struct {\n\tm   sync.RWMutex\n\trrs map[RR]struct{}\n}\n\n\/\/ saveDNSRR saves 1 or more DNS records to the resolver cache.\nfunc (r *Resolver) saveDNSRR(drrs ...dns.RR) {\n\tfor _, drr := range drrs {\n\t\tif rr := convertRR(drr); rr != nil {\n\t\t\tr.cacheAdd(rr.Name, rr)\n\t\t}\n\t}\n}\n\n\/\/ cacheAdd adds 0 or more DNS records to the resolver cache for a specific\n\/\/ domain name and record type. This ensures the cache entry exists, even\n\/\/ if empty, for NXDOMAIN responses.\nfunc (r *Resolver) cacheAdd(qname string, rr *RR) {\n\tqname = toLowerFQDN(qname)\n\te := r.getEntry(qname)\n\tif e == nil {\n\t\te = &entry{rrs: make(map[RR]struct{}, 0)}\n\t\te.m.Lock()\n\t\tr.cache.Add(qname, e)\n\t} else {\n\t\te.m.Lock()\n\t}\n\tdefer e.m.Unlock()\n\tif rr != nil {\n\t\te.rrs[*rr] = struct{}{}\n\t}\n}\n\n\/\/ cacheGet returns a randomly ordered slice of DNS records.\nfunc (r *Resolver) cacheGet(qname string, qtype string) []*RR {\n\te := r.getEntry(qname)\n\tif e == nil && r != Root {\n\t\te = Root.getEntry(qname)\n\t}\n\tif e == nil {\n\t\treturn nil\n\t}\n\te.m.RLock()\n\tdefer e.m.RUnlock()\n\tif len(e.rrs) == 0 {\n\t\treturn []*RR{}\n\t}\n\trrs := make([]*RR, 0, len(e.rrs))\n\tfor rr, _ := range e.rrs {\n\t\t\/\/ fmt.Printf(\"%s\\n\", rr.String())\n\t\tif qtype == \"\" || rr.Type == qtype {\n\t\t\trrs = append(rrs, &RR{rr.Name, rr.Type, rr.Value})\n\t\t}\n\t}\n\tif len(rrs) == 0 && (qtype != \"\" && qtype != \"NS\") {\n\t\treturn nil\n\t}\n\treturn rrs\n}\n\n\/\/ getEntry returns a single cache entry or nil if an entry does not exist in the cache.\nfunc (r *Resolver) getEntry(qname string) *entry {\n\tc, ok := r.cache.Get(qname)\n\tif !ok {\n\t\treturn nil\n\t}\n\te, ok := c.(*entry)\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn e\n}\n<|endoftext|>"}
{"text":"<commit_before>package doit\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/digitalocean\/godo\"\n\t\"github.com\/docker\/docker\/pkg\/term\"\n\t\"github.com\/spf13\/viper\"\n\t\"golang.org\/x\/crypto\/ssh\"\n\t\"golang.org\/x\/crypto\/ssh\/terminal\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nvar (\n\t\/\/ DoitConfig holds the app's current configuration.\n\tDoitConfig Config = &LiveConfig{}\n)\n\n\/\/ Config is an interface that represent doit's config.\ntype Config interface {\n\tGetGodoClient() *godo.Client\n\tSSH(user, host, keyPath string, port int) error\n\tSet(ns, key string, val interface{})\n\tGetString(ns, key string) string\n\tGetBool(ns, key string) bool\n\tGetInt(ns, key string) int\n\tGetStringSlice(ns, key string) []string\n}\n\n\/\/ LiveConfig is an implementation of Config for live values.\ntype LiveConfig struct{}\n\nvar _ Config = &LiveConfig{}\n\n\/\/ GetGodoClient returns a GodoClient.\nfunc (c *LiveConfig) GetGodoClient() *godo.Client {\n\ttoken := viper.GetString(\"access-token\")\n\ttokenSource := &TokenSource{AccessToken: token}\n\toauthClient := oauth2.NewClient(oauth2.NoContext, tokenSource)\n\treturn godo.NewClient(oauthClient)\n}\n\nfunc sshConnect(user string, host string, method ssh.AuthMethod) (err error) {\n\tsshc := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{method},\n\t}\n\tconn, err := ssh.Dial(\"tcp\", host, sshc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsession.Stdout = os.Stdout\n\tsession.Stderr = os.Stderr\n\tsession.Stdin = os.Stdin\n\n\tdefer session.Close()\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 1,\n\t}\n\n\tvar (\n\t\ttermWidth, termHeight int\n\t)\n\tfd := os.Stdin.Fd()\n\tif term.IsTerminal(fd) {\n\t\toldState, err := term.MakeRaw(fd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdefer term.RestoreTerminal(fd, oldState)\n\n\t\twinsize, err := term.GetWinsize(fd)\n\t\tif err != nil {\n\t\t\ttermWidth = 80\n\t\t\ttermHeight = 24\n\t\t} else {\n\t\t\ttermWidth = int(winsize.Width)\n\t\t\ttermHeight = int(winsize.Height)\n\t\t}\n\t}\n\n\tif err := session.RequestPty(\"xterm\", termWidth, termHeight, modes); err != nil {\n\t\tsession.Close()\n\t\treturn err\n\t}\n\tif err == nil {\n\t\terr = session.Shell()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = session.Wait()\n\tif err != nil && err != io.EOF {\n\t\t\/\/ Ignore the error if it's an ExitError with an empty message,\n\t\t\/\/ this occurs when you do CTRL+c and then run exit cmd which isn't an\n\t\t\/\/ actual error.\n\t\twaitMsg, ok := err.(*ssh.ExitError)\n\t\tif ok && waitMsg.Msg() == \"\" {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn err\n\t}\n\treturn err\n}\n\n\/\/ SSH creates a ssh connection to a host.\nfunc (c *LiveConfig) SSH(user, host, keyPath string, port int) (err error) {\n\tlogrus.WithFields(logrus.Fields{\n\t\t\"user\": user,\n\t\t\"host\": host,\n\t}).Info(\"ssh\")\n\n\tsshHost := fmt.Sprintf(\"%s:%d\", host, port)\n\n\t\/\/ Key Auth\n\tkey, err := ioutil.ReadFile(keyPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tprivateKey, err := ssh.ParsePrivateKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := sshConnect(user, sshHost, ssh.PublicKeys(privateKey)); err != nil {\n\t\t\/\/ Password Auth if Key Auth Fails\n\t\tfd := os.Stdin.Fd()\n\t\tstate, err := terminal.MakeRaw(int(fd))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer terminal.Restore(int(fd), state)\n\t\tt := terminal.NewTerminal(os.Stdout, \">\")\n\t\tpassword, err := t.ReadPassword(\"Password: \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := sshConnect(user, sshHost, ssh.Password(string(password))); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ Set sets a config key.\nfunc (c *LiveConfig) Set(ns, key string, val interface{}) {\n\tnskey := fmt.Sprintf(\"%s-%s\", ns, key)\n\tviper.Set(nskey, val)\n}\n\n\/\/ GetString returns a config value as a string.\nfunc (c *LiveConfig) GetString(ns, key string) string {\n\tif ns == NSRoot {\n\t\treturn viper.GetString(key)\n\t}\n\n\tnskey := fmt.Sprintf(\"%s-%s\", ns, key)\n\treturn viper.GetString(nskey)\n}\n\n\/\/ GetBool returns a config value as a bool.\nfunc (c *LiveConfig) GetBool(ns, key string) bool {\n\tif ns == NSRoot {\n\t\treturn viper.GetBool(key)\n\t}\n\n\tnskey := fmt.Sprintf(\"%s-%s\", ns, key)\n\treturn viper.GetBool(nskey)\n}\n\n\/\/ GetInt returns a config value as an int.\nfunc (c *LiveConfig) GetInt(ns, key string) int {\n\tif ns == NSRoot {\n\t\treturn viper.GetInt(key)\n\t}\n\n\tnskey := fmt.Sprintf(\"%s-%s\", ns, key)\n\treturn viper.GetInt(nskey)\n}\n\n\/\/ GetStringSlice returns a config value as a string slice.\nfunc (c *LiveConfig) GetStringSlice(ns, key string) []string {\n\tif ns == NSRoot {\n\t\treturn viper.GetStringSlice(key)\n\t}\n\n\tnskey := fmt.Sprintf(\"%s-%s\", ns, key)\n\treturn viper.GetStringSlice(nskey)\n}\n<commit_msg>cleaned up code<commit_after>package doit\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/digitalocean\/godo\"\n\t\"github.com\/docker\/docker\/pkg\/term\"\n\t\"github.com\/spf13\/viper\"\n\t\"golang.org\/x\/crypto\/ssh\"\n\t\"golang.org\/x\/crypto\/ssh\/terminal\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nvar (\n\t\/\/ DoitConfig holds the app's current configuration.\n\tDoitConfig Config = &LiveConfig{}\n)\n\n\/\/ Config is an interface that represent doit's config.\ntype Config interface {\n\tGetGodoClient() *godo.Client\n\tSSH(user, host, keyPath string, port int) error\n\tSet(ns, key string, val interface{})\n\tGetString(ns, key string) string\n\tGetBool(ns, key string) bool\n\tGetInt(ns, key string) int\n\tGetStringSlice(ns, key string) []string\n}\n\n\/\/ LiveConfig is an implementation of Config for live values.\ntype LiveConfig struct{}\n\nvar _ Config = &LiveConfig{}\n\n\/\/ GetGodoClient returns a GodoClient.\nfunc (c *LiveConfig) GetGodoClient() *godo.Client {\n\ttoken := viper.GetString(\"access-token\")\n\ttokenSource := &TokenSource{AccessToken: token}\n\toauthClient := oauth2.NewClient(oauth2.NoContext, tokenSource)\n\treturn godo.NewClient(oauthClient)\n}\n\nfunc sshConnect(user string, host string, method ssh.AuthMethod) error {\n\tsshc := &ssh.ClientConfig{\n\t\tUser: user,\n\t\tAuth: []ssh.AuthMethod{method},\n\t}\n\tconn, err := ssh.Dial(\"tcp\", host, sshc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tsession, err := conn.NewSession()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer session.Close()\n\n\tsession.Stdout = os.Stdout\n\tsession.Stderr = os.Stderr\n\tsession.Stdin = os.Stdin\n\n\tvar (\n\t\ttermWidth, termHeight int\n\t)\n\tfd := os.Stdin.Fd()\n\n\toldState, err := term.MakeRaw(fd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer term.RestoreTerminal(fd, oldState)\n\n\twinsize, err := term.GetWinsize(fd)\n\tif err != nil {\n\t\ttermWidth = 80\n\t\ttermHeight = 24\n\t} else {\n\t\ttermWidth = int(winsize.Width)\n\t\ttermHeight = int(winsize.Height)\n\t}\n\n\tmodes := ssh.TerminalModes{\n\t\tssh.ECHO: 1,\n\t}\n\n\tif err := session.RequestPty(\"xterm\", termWidth, termHeight, modes); err != nil {\n\t\treturn err\n\t}\n\tif err == nil {\n\t\terr = session.Shell()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = session.Wait()\n\tif serr, ok := err.(*ssh.ExitError); ok && waitMsg.Msg() == \"\" {\n\t\treturn nil\n\t}\n\tif err == io.EOF {\n\t\treturn nil\n\t}\n\treturn err\n}\n\n\/\/ SSH creates a ssh connection to a host.\nfunc (c *LiveConfig) SSH(user, host, keyPath string, port int) (err error) {\n\tlogrus.WithFields(logrus.Fields{\n\t\t\"user\": user,\n\t\t\"host\": host,\n\t}).Info(\"ssh\")\n\n\tsshHost := fmt.Sprintf(\"%s:%d\", host, port)\n\n\t\/\/ Key Auth\n\tkey, err := ioutil.ReadFile(keyPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tprivateKey, err := ssh.ParsePrivateKey(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := sshConnect(user, sshHost, ssh.PublicKeys(privateKey)); err != nil {\n\t\t\/\/ Password Auth if Key Auth Fails\n\t\tfd := os.Stdin.Fd()\n\t\tstate, err := terminal.MakeRaw(int(fd))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer terminal.Restore(int(fd), state)\n\t\tt := terminal.NewTerminal(os.Stdout, \">\")\n\t\tpassword, err := t.ReadPassword(\"Password: \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := sshConnect(user, sshHost, ssh.Password(string(password))); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ Set sets a config key.\nfunc (c *LiveConfig) Set(ns, key string, val interface{}) {\n\tnskey := fmt.Sprintf(\"%s-%s\", ns, key)\n\tviper.Set(nskey, val)\n}\n\n\/\/ GetString returns a config value as a string.\nfunc (c *LiveConfig) GetString(ns, key string) string {\n\tif ns == NSRoot {\n\t\treturn viper.GetString(key)\n\t}\n\n\tnskey := fmt.Sprintf(\"%s-%s\", ns, key)\n\treturn viper.GetString(nskey)\n}\n\n\/\/ GetBool returns a config value as a bool.\nfunc (c *LiveConfig) GetBool(ns, key string) bool {\n\tif ns == NSRoot {\n\t\treturn viper.GetBool(key)\n\t}\n\n\tnskey := fmt.Sprintf(\"%s-%s\", ns, key)\n\treturn viper.GetBool(nskey)\n}\n\n\/\/ GetInt returns a config value as an int.\nfunc (c *LiveConfig) GetInt(ns, key string) int {\n\tif ns == NSRoot {\n\t\treturn viper.GetInt(key)\n\t}\n\n\tnskey := fmt.Sprintf(\"%s-%s\", ns, key)\n\treturn viper.GetInt(nskey)\n}\n\n\/\/ GetStringSlice returns a config value as a string slice.\nfunc (c *LiveConfig) GetStringSlice(ns, key string) []string {\n\tif ns == NSRoot {\n\t\treturn viper.GetStringSlice(key)\n\t}\n\n\tnskey := fmt.Sprintf(\"%s-%s\", ns, key)\n\treturn viper.GetStringSlice(nskey)\n}\n<|endoftext|>"}
{"text":"<commit_before>package messenger\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"net\/http\"\n)\n\ntype sessionDump struct {\n\tFBCookies   []*http.Cookie\n\tEdgeCookies []*http.Cookie\n}\n\n\/\/ DumpSession dumps the session (i.e. cookies) and returns it as a []byte.\n\/\/ Note that if you restore the session, you may not need to login, but you\n\/\/ must reconnect to chat.\nfunc (s *Session) DumpSession() ([]byte, error) {\n\ts.requestMutex.RUnlock()\n\tdefer s.requestMutex.RLock()\n\n\tfbCookies := s.client.Jar.Cookies(fbURL)\n\tedgeCookies := s.client.Jar.Cookies(edgeURL)\n\n\tbuf := new(bytes.Buffer)\n\tenc := gob.NewEncoder(buf)\n\terr := enc.Encode(sessionDump{\n\t\tFBCookies:   fbCookies,\n\t\tEdgeCookies: edgeCookies,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\n\/\/ RestoreSession restores the session (i.e. cookies) stored as a []byte\n\/\/ back into the session. Note that you may not need to login again, but you\n\/\/ must reconnect to chat.\nfunc (s *Session) RestoreSession(data []byte) error {\n\ts.requestMutex.Lock()\n\tdefer s.requestMutex.Unlock()\n\n\tbuf := bytes.NewReader(data)\n\tdec := gob.NewDecoder(buf)\n\trestoredSession := sessionDump{}\n\terr := dec.Decode(&restoredSession)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.client.Jar.SetCookies(fbURL, restoredSession.FBCookies)\n\ts.client.Jar.SetCookies(edgeURL, restoredSession.EdgeCookies)\n\n\treturn nil\n}\n\nfunc init() {\n\tgob.Register(sessionDump{})\n}\n<commit_msg>Fix mutex on session dump<commit_after>package messenger\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"net\/http\"\n)\n\ntype sessionDump struct {\n\tFBCookies   []*http.Cookie\n\tEdgeCookies []*http.Cookie\n}\n\n\/\/ DumpSession dumps the session (i.e. cookies) and returns it as a []byte.\n\/\/ Note that if you restore the session, you may not need to login, but you\n\/\/ must reconnect to chat.\nfunc (s *Session) DumpSession() ([]byte, error) {\n\ts.requestMutex.RLock()\n\tdefer s.requestMutex.RUnlock()\n\n\tfbCookies := s.client.Jar.Cookies(fbURL)\n\tedgeCookies := s.client.Jar.Cookies(edgeURL)\n\n\tbuf := new(bytes.Buffer)\n\tenc := gob.NewEncoder(buf)\n\terr := enc.Encode(sessionDump{\n\t\tFBCookies:   fbCookies,\n\t\tEdgeCookies: edgeCookies,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\n\/\/ RestoreSession restores the session (i.e. cookies) stored as a []byte\n\/\/ back into the session. Note that you may not need to login again, but you\n\/\/ must reconnect to chat.\nfunc (s *Session) RestoreSession(data []byte) error {\n\ts.requestMutex.Lock()\n\tdefer s.requestMutex.Unlock()\n\n\tbuf := bytes.NewReader(data)\n\tdec := gob.NewDecoder(buf)\n\trestoredSession := sessionDump{}\n\terr := dec.Decode(&restoredSession)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.client.Jar.SetCookies(fbURL, restoredSession.FBCookies)\n\ts.client.Jar.SetCookies(edgeURL, restoredSession.EdgeCookies)\n\n\treturn nil\n}\n\nfunc init() {\n\tgob.Register(sessionDump{})\n}\n<|endoftext|>"}
{"text":"<commit_before>package test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\tpeer \"github.com\/libp2p\/go-libp2p-peer\"\n\tpt \"github.com\/libp2p\/go-libp2p-peer\/test\"\n\tpstore \"github.com\/libp2p\/go-libp2p-peerstore\"\n\tma \"github.com\/multiformats\/go-multiaddr\"\n)\n\nvar addressBookSuite = map[string]func(book pstore.AddrBook) func(*testing.T){\n\t\"AddAddress\":           testAddAddress,\n\t\"Clear\":                testClearWorks,\n\t\"SetNegativeTTLClears\": testSetNegativeTTLClears,\n\t\"UpdateTTLs\":           testUpdateTTLs,\n\t\"NilAddrsDontBreak\":    testNilAddrsDontBreak,\n\t\"AddressesExpire\":      testAddressesExpire,\n\t\"ClearWithIter\":        testClearWithIterator,\n\t\"PeersWithAddresses\":   testPeersWithAddrs,\n}\n\ntype AddrBookFactory func() (pstore.AddrBook, func())\n\nfunc TestAddrBook(t *testing.T, factory AddrBookFactory) {\n\tfor name, test := range addressBookSuite {\n\t\t\/\/ Create a new peerstore.\n\t\tab, closeFunc := factory()\n\n\t\t\/\/ Run the test.\n\t\tt.Run(name, test(ab))\n\n\t\t\/\/ Cleanup.\n\t\tif closeFunc != nil {\n\t\t\tcloseFunc()\n\t\t}\n\t}\n}\n\nfunc generateAddrs(count int) []ma.Multiaddr {\n\tvar addrs = make([]ma.Multiaddr, count)\n\tfor i := 0; i < count; i++ {\n\t\taddrs[i] = multiaddr(fmt.Sprintf(\"\/ip4\/1.1.1.%d\/tcp\/1111\", i))\n\t}\n\treturn addrs\n}\n\nfunc generatePeerIds(count int) []peer.ID {\n\tvar ids = make([]peer.ID, count)\n\tfor i := 0; i < count; i++ {\n\t\tids[i], _ = pt.RandPeerID()\n\t}\n\treturn ids\n}\n\nfunc testAddAddress(ab pstore.AddrBook) func(*testing.T) {\n\treturn func(t *testing.T) {\n\t\tt.Run(\"add a single address\", func(t *testing.T) {\n\t\t\tid := generatePeerIds(1)[0]\n\t\t\taddrs := generateAddrs(1)\n\n\t\t\tab.AddAddr(id, addrs[0], time.Hour)\n\n\t\t\ttestHas(t, addrs, ab.Addrs(id))\n\t\t})\n\n\t\tt.Run(\"idempotent add single address\", func(t *testing.T) {\n\t\t\tid := generatePeerIds(1)[0]\n\t\t\taddrs := generateAddrs(1)\n\n\t\t\tab.AddAddr(id, addrs[0], time.Hour)\n\t\t\tab.AddAddr(id, addrs[0], time.Hour)\n\n\t\t\ttestHas(t, addrs, ab.Addrs(id))\n\t\t})\n\n\t\tt.Run(\"add multiple addresses\", func(t *testing.T) {\n\t\t\tid := generatePeerIds(1)[0]\n\t\t\taddrs := generateAddrs(3)\n\n\t\t\tab.AddAddrs(id, addrs, time.Hour)\n\t\t\ttestHas(t, addrs, ab.Addrs(id))\n\t\t})\n\n\t\tt.Run(\"idempotent add multiple addresses\", func(t *testing.T) {\n\t\t\tid := generatePeerIds(1)[0]\n\t\t\taddrs := generateAddrs(3)\n\n\t\t\tab.AddAddrs(id, addrs, time.Hour)\n\t\t\tab.AddAddrs(id, addrs, time.Hour)\n\n\t\t\ttestHas(t, addrs, ab.Addrs(id))\n\t\t})\n\t}\n}\n\nfunc testClearWorks(ab pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tids := generatePeerIds(2)\n\t\taddrs := generateAddrs(5)\n\n\t\tab.AddAddrs(ids[0], addrs[0:3], time.Hour)\n\t\tab.AddAddrs(ids[1], addrs[3:], time.Hour)\n\n\t\ttestHas(t, addrs[0:3], ab.Addrs(ids[0]))\n\t\ttestHas(t, addrs[3:], ab.Addrs(ids[1]))\n\n\t\tab.ClearAddrs(ids[0])\n\t\ttestHas(t, nil, ab.Addrs(ids[0]))\n\t\ttestHas(t, addrs[3:], ab.Addrs(ids[1]))\n\n\t\tab.ClearAddrs(ids[1])\n\t\ttestHas(t, nil, ab.Addrs(ids[0]))\n\t\ttestHas(t, nil, ab.Addrs(ids[1]))\n\t}\n}\n\nfunc testSetNegativeTTLClears(m pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tid := generatePeerIds(1)[0]\n\t\taddr := generateAddrs(1)[0]\n\n\t\tm.SetAddr(id, addr, time.Hour)\n\t\ttestHas(t, []ma.Multiaddr{addr}, m.Addrs(id))\n\n\t\tm.SetAddr(id, addr, -1)\n\t\ttestHas(t, nil, m.Addrs(id))\n\t}\n}\n\nfunc testUpdateTTLs(m pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tt.Run(\"update ttl of peer with no addrs\", func(t *testing.T) {\n\t\t\tid := generatePeerIds(1)[0]\n\n\t\t\t\/\/ Shouldn't panic.\n\t\t\tm.UpdateAddrs(id, time.Hour, time.Minute)\n\t\t})\n\n\t\tt.Run(\"update ttls successfully\", func(t *testing.T) {\n\t\t\tids := generatePeerIds(2)\n\t\t\taddrs1, addrs2 := generateAddrs(2), generateAddrs(2)\n\n\t\t\t\/\/ set two keys with different ttls for each peer.\n\t\t\tm.SetAddr(ids[0], addrs1[0], time.Hour)\n\t\t\tm.SetAddr(ids[0], addrs1[1], time.Minute)\n\t\t\tm.SetAddr(ids[1], addrs2[0], time.Hour)\n\t\t\tm.SetAddr(ids[1], addrs2[1], time.Minute)\n\n\t\t\t\/\/ Sanity check.\n\t\t\ttestHas(t, addrs1, m.Addrs(ids[0]))\n\t\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\t\t\/\/ Will only affect addrs1[0].\n\t\t\tm.UpdateAddrs(ids[0], time.Hour, time.Second)\n\n\t\t\t\/\/ No immediate effect.\n\t\t\ttestHas(t, addrs1, m.Addrs(ids[0]))\n\t\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\t\t\/\/ After a wait, addrs[0] is gone.\n\t\t\ttime.Sleep(1200 * time.Millisecond)\n\t\t\ttestHas(t, addrs1[1:2], m.Addrs(ids[0]))\n\t\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\t\t\/\/ Will only affect addrs2[0].\n\t\t\tm.UpdateAddrs(ids[1], time.Hour, time.Second)\n\n\t\t\t\/\/ No immediate effect.\n\t\t\ttestHas(t, addrs1[1:2], m.Addrs(ids[0]))\n\t\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\t\ttime.Sleep(1200 * time.Millisecond)\n\n\t\t\t\/\/ First addrs is gone in both.\n\t\t\ttestHas(t, addrs1[1:], m.Addrs(ids[0]))\n\t\t\ttestHas(t, addrs2[1:], m.Addrs(ids[1]))\n\t\t})\n\n\t}\n}\n\nfunc testNilAddrsDontBreak(m pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tid := generatePeerIds(1)[0]\n\n\t\tm.SetAddr(id, nil, time.Hour)\n\t\tm.AddAddr(id, nil, time.Hour)\n\t}\n}\n\nfunc testAddressesExpire(m pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tids := generatePeerIds(2)\n\t\taddrs1 := generateAddrs(3)\n\t\taddrs2 := generateAddrs(2)\n\n\t\tm.AddAddrs(ids[0], addrs1, time.Hour)\n\t\tm.AddAddrs(ids[1], addrs2, time.Hour)\n\n\t\ttestHas(t, addrs1, m.Addrs(ids[0]))\n\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\tm.AddAddrs(ids[0], addrs1, 2*time.Hour)\n\t\tm.AddAddrs(ids[1], addrs2, 2*time.Hour)\n\n\t\ttestHas(t, addrs1, m.Addrs(ids[0]))\n\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\tm.SetAddr(ids[0], addrs1[0], time.Millisecond)\n\t\t<-time.After(time.Millisecond * 5)\n\t\ttestHas(t, addrs1[1:3], m.Addrs(ids[0]))\n\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\tm.SetAddr(ids[0], addrs1[2], time.Millisecond)\n\t\t<-time.After(time.Millisecond * 5)\n\t\ttestHas(t, addrs1[1:2], m.Addrs(ids[0]))\n\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\tm.SetAddr(ids[1], addrs2[0], time.Millisecond)\n\t\t<-time.After(time.Millisecond * 5)\n\t\ttestHas(t, addrs1[1:2], m.Addrs(ids[0]))\n\t\ttestHas(t, addrs2[1:], m.Addrs(ids[1]))\n\n\t\tm.SetAddr(ids[1], addrs2[1], time.Millisecond)\n\t\t<-time.After(time.Millisecond * 5)\n\t\ttestHas(t, addrs1[1:2], m.Addrs(ids[0]))\n\t\ttestHas(t, nil, m.Addrs(ids[1]))\n\n\t\tm.SetAddr(ids[0], addrs1[1], time.Millisecond)\n\t\t<-time.After(time.Millisecond * 5)\n\t\ttestHas(t, nil, m.Addrs(ids[0]))\n\t\ttestHas(t, nil, m.Addrs(ids[1]))\n\t}\n}\n\nfunc testClearWithIterator(m pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tids := generatePeerIds(2)\n\t\taddrs := generateAddrs(100)\n\n\t\t\/\/ Add the peers with 50 addresses each.\n\t\tm.AddAddrs(ids[0], addrs[:50], pstore.PermanentAddrTTL)\n\t\tm.AddAddrs(ids[1], addrs[50:], pstore.PermanentAddrTTL)\n\n\t\tif all := append(m.Addrs(ids[0]), m.Addrs(ids[1])...); len(all) != 100 {\n\t\t\tt.Fatal(\"expected pstore to contain both peers with all their maddrs\")\n\t\t}\n\n\t\t\/\/ Since we don't fetch these peers, they won't be present in cache.\n\n\t\tm.ClearAddrs(ids[0])\n\t\tif all := append(m.Addrs(ids[0]), m.Addrs(ids[1])...); len(all) != 50 {\n\t\t\tt.Fatal(\"expected pstore to contain only addrs of peer 2\")\n\t\t}\n\n\t\tm.ClearAddrs(ids[1])\n\t\tif all := append(m.Addrs(ids[0]), m.Addrs(ids[1])...); len(all) != 0 {\n\t\t\tt.Fatal(\"expected pstore to contain no addresses\")\n\t\t}\n\t}\n}\n\nfunc testPeersWithAddrs(m pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\t\/\/ cannot run in parallel as the store is modified.\n\t\t\/\/ go runs sequentially in the specified order\n\t\t\/\/ see https:\/\/blog.golang.org\/subtests\n\n\t\tt.Run(\"empty addrbook\", func(t *testing.T) {\n\t\t\tif peers := m.PeersWithAddrs(); len(peers) != 0 {\n\t\t\t\tt.Fatal(\"expected to find no peers\")\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"non-empty addrbook\", func(t *testing.T) {\n\t\t\tids := generatePeerIds(2)\n\t\t\taddrs := generateAddrs(10)\n\n\t\t\tm.AddAddrs(ids[0], addrs[:5], pstore.PermanentAddrTTL)\n\t\t\tm.AddAddrs(ids[1], addrs[5:], pstore.PermanentAddrTTL)\n\n\t\t\tif peers := m.PeersWithAddrs(); len(peers) != 2 {\n\t\t\t\tt.Fatal(\"expected to find 2 peers\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc testHas(t *testing.T, exp, act []ma.Multiaddr) {\n\tt.Helper()\n\tif len(exp) != len(act) {\n\t\tt.Fatalf(\"lengths not the same. expected %d, got %d\\n\", len(exp), len(act))\n\t}\n\n\tfor _, a := range exp {\n\t\tfound := false\n\n\t\tfor _, b := range act {\n\t\t\tif a.Equal(b) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\tt.Fatalf(\"expected address %s not found\", a)\n\t\t}\n\t}\n}\n<commit_msg>hopefully fix intermittent time-dependent test failure.<commit_after>package test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\tpeer \"github.com\/libp2p\/go-libp2p-peer\"\n\tpt \"github.com\/libp2p\/go-libp2p-peer\/test\"\n\tpstore \"github.com\/libp2p\/go-libp2p-peerstore\"\n\tma \"github.com\/multiformats\/go-multiaddr\"\n)\n\nvar addressBookSuite = map[string]func(book pstore.AddrBook) func(*testing.T){\n\t\"AddAddress\":           testAddAddress,\n\t\"Clear\":                testClearWorks,\n\t\"SetNegativeTTLClears\": testSetNegativeTTLClears,\n\t\"UpdateTTLs\":           testUpdateTTLs,\n\t\"NilAddrsDontBreak\":    testNilAddrsDontBreak,\n\t\"AddressesExpire\":      testAddressesExpire,\n\t\"ClearWithIter\":        testClearWithIterator,\n\t\"PeersWithAddresses\":   testPeersWithAddrs,\n}\n\ntype AddrBookFactory func() (pstore.AddrBook, func())\n\nfunc TestAddrBook(t *testing.T, factory AddrBookFactory) {\n\tfor name, test := range addressBookSuite {\n\t\t\/\/ Create a new peerstore.\n\t\tab, closeFunc := factory()\n\n\t\t\/\/ Run the test.\n\t\tt.Run(name, test(ab))\n\n\t\t\/\/ Cleanup.\n\t\tif closeFunc != nil {\n\t\t\tcloseFunc()\n\t\t}\n\t}\n}\n\nfunc generateAddrs(count int) []ma.Multiaddr {\n\tvar addrs = make([]ma.Multiaddr, count)\n\tfor i := 0; i < count; i++ {\n\t\taddrs[i] = multiaddr(fmt.Sprintf(\"\/ip4\/1.1.1.%d\/tcp\/1111\", i))\n\t}\n\treturn addrs\n}\n\nfunc generatePeerIds(count int) []peer.ID {\n\tvar ids = make([]peer.ID, count)\n\tfor i := 0; i < count; i++ {\n\t\tids[i], _ = pt.RandPeerID()\n\t}\n\treturn ids\n}\n\nfunc testAddAddress(ab pstore.AddrBook) func(*testing.T) {\n\treturn func(t *testing.T) {\n\t\tt.Run(\"add a single address\", func(t *testing.T) {\n\t\t\tid := generatePeerIds(1)[0]\n\t\t\taddrs := generateAddrs(1)\n\n\t\t\tab.AddAddr(id, addrs[0], time.Hour)\n\n\t\t\ttestHas(t, addrs, ab.Addrs(id))\n\t\t})\n\n\t\tt.Run(\"idempotent add single address\", func(t *testing.T) {\n\t\t\tid := generatePeerIds(1)[0]\n\t\t\taddrs := generateAddrs(1)\n\n\t\t\tab.AddAddr(id, addrs[0], time.Hour)\n\t\t\tab.AddAddr(id, addrs[0], time.Hour)\n\n\t\t\ttestHas(t, addrs, ab.Addrs(id))\n\t\t})\n\n\t\tt.Run(\"add multiple addresses\", func(t *testing.T) {\n\t\t\tid := generatePeerIds(1)[0]\n\t\t\taddrs := generateAddrs(3)\n\n\t\t\tab.AddAddrs(id, addrs, time.Hour)\n\t\t\ttestHas(t, addrs, ab.Addrs(id))\n\t\t})\n\n\t\tt.Run(\"idempotent add multiple addresses\", func(t *testing.T) {\n\t\t\tid := generatePeerIds(1)[0]\n\t\t\taddrs := generateAddrs(3)\n\n\t\t\tab.AddAddrs(id, addrs, time.Hour)\n\t\t\tab.AddAddrs(id, addrs, time.Hour)\n\n\t\t\ttestHas(t, addrs, ab.Addrs(id))\n\t\t})\n\t}\n}\n\nfunc testClearWorks(ab pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tids := generatePeerIds(2)\n\t\taddrs := generateAddrs(5)\n\n\t\tab.AddAddrs(ids[0], addrs[0:3], time.Hour)\n\t\tab.AddAddrs(ids[1], addrs[3:], time.Hour)\n\n\t\ttestHas(t, addrs[0:3], ab.Addrs(ids[0]))\n\t\ttestHas(t, addrs[3:], ab.Addrs(ids[1]))\n\n\t\tab.ClearAddrs(ids[0])\n\t\ttestHas(t, nil, ab.Addrs(ids[0]))\n\t\ttestHas(t, addrs[3:], ab.Addrs(ids[1]))\n\n\t\tab.ClearAddrs(ids[1])\n\t\ttestHas(t, nil, ab.Addrs(ids[0]))\n\t\ttestHas(t, nil, ab.Addrs(ids[1]))\n\t}\n}\n\nfunc testSetNegativeTTLClears(m pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tid := generatePeerIds(1)[0]\n\t\taddr := generateAddrs(1)[0]\n\n\t\tm.SetAddr(id, addr, time.Hour)\n\t\ttestHas(t, []ma.Multiaddr{addr}, m.Addrs(id))\n\n\t\tm.SetAddr(id, addr, -1)\n\t\ttestHas(t, nil, m.Addrs(id))\n\t}\n}\n\nfunc testUpdateTTLs(m pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tt.Run(\"update ttl of peer with no addrs\", func(t *testing.T) {\n\t\t\tid := generatePeerIds(1)[0]\n\n\t\t\t\/\/ Shouldn't panic.\n\t\t\tm.UpdateAddrs(id, time.Hour, time.Minute)\n\t\t})\n\n\t\tt.Run(\"update ttls successfully\", func(t *testing.T) {\n\t\t\tids := generatePeerIds(2)\n\t\t\taddrs1, addrs2 := generateAddrs(2), generateAddrs(2)\n\n\t\t\t\/\/ set two keys with different ttls for each peer.\n\t\t\tm.SetAddr(ids[0], addrs1[0], time.Hour)\n\t\t\tm.SetAddr(ids[0], addrs1[1], time.Minute)\n\t\t\tm.SetAddr(ids[1], addrs2[0], time.Hour)\n\t\t\tm.SetAddr(ids[1], addrs2[1], time.Minute)\n\n\t\t\t\/\/ Sanity check.\n\t\t\ttestHas(t, addrs1, m.Addrs(ids[0]))\n\t\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\t\t\/\/ Will only affect addrs1[0].\n\t\t\tm.UpdateAddrs(ids[0], time.Hour, 100*time.Microsecond)\n\n\t\t\t\/\/ No immediate effect.\n\t\t\ttestHas(t, addrs1, m.Addrs(ids[0]))\n\t\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\t\t\/\/ After a wait, addrs[0] is gone.\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\ttestHas(t, addrs1[1:2], m.Addrs(ids[0]))\n\t\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\t\t\/\/ Will only affect addrs2[0].\n\t\t\tm.UpdateAddrs(ids[1], time.Hour, 100*time.Microsecond)\n\n\t\t\t\/\/ No immediate effect.\n\t\t\ttestHas(t, addrs1[1:2], m.Addrs(ids[0]))\n\t\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\n\t\t\t\/\/ First addrs is gone in both.\n\t\t\ttestHas(t, addrs1[1:], m.Addrs(ids[0]))\n\t\t\ttestHas(t, addrs2[1:], m.Addrs(ids[1]))\n\t\t})\n\n\t}\n}\n\nfunc testNilAddrsDontBreak(m pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tid := generatePeerIds(1)[0]\n\n\t\tm.SetAddr(id, nil, time.Hour)\n\t\tm.AddAddr(id, nil, time.Hour)\n\t}\n}\n\nfunc testAddressesExpire(m pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tids := generatePeerIds(2)\n\t\taddrs1 := generateAddrs(3)\n\t\taddrs2 := generateAddrs(2)\n\n\t\tm.AddAddrs(ids[0], addrs1, time.Hour)\n\t\tm.AddAddrs(ids[1], addrs2, time.Hour)\n\n\t\ttestHas(t, addrs1, m.Addrs(ids[0]))\n\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\tm.AddAddrs(ids[0], addrs1, 2*time.Hour)\n\t\tm.AddAddrs(ids[1], addrs2, 2*time.Hour)\n\n\t\ttestHas(t, addrs1, m.Addrs(ids[0]))\n\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\tm.SetAddr(ids[0], addrs1[0], time.Millisecond)\n\t\t<-time.After(time.Millisecond * 5)\n\t\ttestHas(t, addrs1[1:3], m.Addrs(ids[0]))\n\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\tm.SetAddr(ids[0], addrs1[2], time.Millisecond)\n\t\t<-time.After(time.Millisecond * 5)\n\t\ttestHas(t, addrs1[1:2], m.Addrs(ids[0]))\n\t\ttestHas(t, addrs2, m.Addrs(ids[1]))\n\n\t\tm.SetAddr(ids[1], addrs2[0], time.Millisecond)\n\t\t<-time.After(time.Millisecond * 5)\n\t\ttestHas(t, addrs1[1:2], m.Addrs(ids[0]))\n\t\ttestHas(t, addrs2[1:], m.Addrs(ids[1]))\n\n\t\tm.SetAddr(ids[1], addrs2[1], time.Millisecond)\n\t\t<-time.After(time.Millisecond * 5)\n\t\ttestHas(t, addrs1[1:2], m.Addrs(ids[0]))\n\t\ttestHas(t, nil, m.Addrs(ids[1]))\n\n\t\tm.SetAddr(ids[0], addrs1[1], time.Millisecond)\n\t\t<-time.After(time.Millisecond * 5)\n\t\ttestHas(t, nil, m.Addrs(ids[0]))\n\t\ttestHas(t, nil, m.Addrs(ids[1]))\n\t}\n}\n\nfunc testClearWithIterator(m pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\tids := generatePeerIds(2)\n\t\taddrs := generateAddrs(100)\n\n\t\t\/\/ Add the peers with 50 addresses each.\n\t\tm.AddAddrs(ids[0], addrs[:50], pstore.PermanentAddrTTL)\n\t\tm.AddAddrs(ids[1], addrs[50:], pstore.PermanentAddrTTL)\n\n\t\tif all := append(m.Addrs(ids[0]), m.Addrs(ids[1])...); len(all) != 100 {\n\t\t\tt.Fatal(\"expected pstore to contain both peers with all their maddrs\")\n\t\t}\n\n\t\t\/\/ Since we don't fetch these peers, they won't be present in cache.\n\n\t\tm.ClearAddrs(ids[0])\n\t\tif all := append(m.Addrs(ids[0]), m.Addrs(ids[1])...); len(all) != 50 {\n\t\t\tt.Fatal(\"expected pstore to contain only addrs of peer 2\")\n\t\t}\n\n\t\tm.ClearAddrs(ids[1])\n\t\tif all := append(m.Addrs(ids[0]), m.Addrs(ids[1])...); len(all) != 0 {\n\t\t\tt.Fatal(\"expected pstore to contain no addresses\")\n\t\t}\n\t}\n}\n\nfunc testPeersWithAddrs(m pstore.AddrBook) func(t *testing.T) {\n\treturn func(t *testing.T) {\n\t\t\/\/ cannot run in parallel as the store is modified.\n\t\t\/\/ go runs sequentially in the specified order\n\t\t\/\/ see https:\/\/blog.golang.org\/subtests\n\n\t\tt.Run(\"empty addrbook\", func(t *testing.T) {\n\t\t\tif peers := m.PeersWithAddrs(); len(peers) != 0 {\n\t\t\t\tt.Fatal(\"expected to find no peers\")\n\t\t\t}\n\t\t})\n\n\t\tt.Run(\"non-empty addrbook\", func(t *testing.T) {\n\t\t\tids := generatePeerIds(2)\n\t\t\taddrs := generateAddrs(10)\n\n\t\t\tm.AddAddrs(ids[0], addrs[:5], pstore.PermanentAddrTTL)\n\t\t\tm.AddAddrs(ids[1], addrs[5:], pstore.PermanentAddrTTL)\n\n\t\t\tif peers := m.PeersWithAddrs(); len(peers) != 2 {\n\t\t\t\tt.Fatal(\"expected to find 2 peers\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc testHas(t *testing.T, exp, act []ma.Multiaddr) {\n\tt.Helper()\n\tif len(exp) != len(act) {\n\t\tt.Fatalf(\"lengths not the same. expected %d, got %d\\n\", len(exp), len(act))\n\t}\n\n\tfor _, a := range exp {\n\t\tfound := false\n\n\t\tfor _, b := range act {\n\t\t\tif a.Equal(b) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\tt.Fatalf(\"expected address %s not found\", a)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package setup_instruments\n\nimport (\n\t\"database\/sql\"\n\t\"log\"\n\n\t\"github.com\/sjmudd\/pstop\/lib\"\n)\n\n\/\/ Error 1142: UPDATE command denied to user\nconst UPDATE_FAILED = \"Error 1142\"\n\ntype setup_instruments_row struct {\n\tNAME    string\n\tENABLED string\n\tTIMED   string\n}\n\ntype SetupInstruments struct {\n\tupdate_succeeded bool\n\trows []setup_instruments_row\n}\n\n\/\/ Change settings to monitor wait\/synch\/mutex\/%\nfunc (si *SetupInstruments) EnableMutexMonitoring(dbh *sql.DB) {\n\tsi.rows = make([]setup_instruments_row, 0, 100)\n\n\t\/\/ populate the rows which are not set\n\tsql := \"SELECT NAME, ENABLED, TIMED FROM setup_instruments WHERE NAME LIKE 'wait\/synch\/mutex\/%' AND ( enabled <> 'YES' OR timed <> 'YES' )\"\n\n\tlib.Logger.Println(\"Collecting p_s.setup_instruments wait\/synch\/mutex configuration settings\")\n\n\trows, err := dbh.Query(sql)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\n\n\t}\n\tdefer rows.Close()\n\n\tcount := 0\n\tfor rows.Next() {\n\t\tvar r setup_instruments_row\n\t\tif err := rows.Scan(\n\t\t\t&r.NAME,\n\t\t\t&r.ENABLED,\n\t\t\t&r.TIMED); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t\/\/ we collect all information even if it's mainly empty as we may reference it later\n\t\tsi.rows = append(si.rows, r)\n\t\tcount++\n\t}\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlib.Logger.Println(\"- found\", count, \"rows whose configuration need changing\")\n\n\t\/\/ update the rows which need to be set - do multiple updates but I don't care\n\tlib.Logger.Println(\"Updating p_s.setup_instruments to allow wait\/synch\/mutex configuration\")\n\n\tcount = 0\n\tfor i := range si.rows {\n\t\tsql := \"UPDATE setup_instruments SET enabled = 'YES', TIMED = 'YES' WHERE NAME = '\" + si.rows[i].NAME + \"'\"\n\t\tif _, err := dbh.Exec(sql); err == nil {\n\t\t\tsi.update_succeeded = true\n\t\t} else {\n\t\t\tif err.Error()[0:10] != UPDATE_FAILED {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tbreak\n\n\t\t}\n\t\tcount++\n\t}\n\tlib.Logger.Println(count, \"rows changed in p_s.setup_instruments\")\n}\n\n\/\/ restore any changed rows back to their original state\nfunc (si *SetupInstruments) Restore(dbh *sql.DB) {\n\t\/\/ If the previous update didn't work then don't try to restore\n\tif ! si.update_succeeded {\n\t\tlib.Logger.Println(\"Not restoring p_s.setup_instruments to its original settings as previous UPDATE had failed\")\n\t\treturn\n\t} else {\n\t\tlib.Logger.Println(\"Restoring p_s.setup_instruments to its original settings\")\n\t}\n\n\t\/\/ update the rows which need to be set - do multiple updates but I don't care\n\tcount := 0\n\tfor i := range si.rows {\n\t\tsql := \"UPDATE setup_instruments SET enabled = '\" + si.rows[i].ENABLED + \"', TIMED = '\" + si.rows[i].TIMED + \"' WHERE NAME = '\" + si.rows[i].NAME + \"'\"\n\t\tif _, err := dbh.Exec(sql); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tcount++\n\t}\n\tlib.Logger.Println(count, \"rows changed in p_s.setup_instruments\")\n}\n<commit_msg>log success\/failure to change ps.setup_instruments<commit_after>package setup_instruments\n\nimport (\n\t\"database\/sql\"\n\t\"log\"\n\n\t\"github.com\/sjmudd\/pstop\/lib\"\n)\n\n\/\/ Error 1142: UPDATE command denied to user\nconst UPDATE_FAILED = \"Error 1142\"\n\ntype setup_instruments_row struct {\n\tNAME    string\n\tENABLED string\n\tTIMED   string\n}\n\ntype SetupInstruments struct {\n\tupdate_succeeded bool\n\trows []setup_instruments_row\n}\n\n\/\/ Change settings to monitor wait\/synch\/mutex\/%\nfunc (si *SetupInstruments) EnableMutexMonitoring(dbh *sql.DB) {\n\tsi.rows = make([]setup_instruments_row, 0, 100)\n\n\t\/\/ populate the rows which are not set\n\tsql := \"SELECT NAME, ENABLED, TIMED FROM setup_instruments WHERE NAME LIKE 'wait\/synch\/mutex\/%' AND ( enabled <> 'YES' OR timed <> 'YES' )\"\n\n\tlib.Logger.Println(\"Collecting p_s.setup_instruments wait\/synch\/mutex configuration settings\")\n\n\trows, err := dbh.Query(sql)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\n\tcount := 0\n\tfor rows.Next() {\n\t\tvar r setup_instruments_row\n\t\tif err := rows.Scan(\n\t\t\t&r.NAME,\n\t\t\t&r.ENABLED,\n\t\t\t&r.TIMED); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t\/\/ we collect all information even if it's mainly empty as we may reference it later\n\t\tsi.rows = append(si.rows, r)\n\t\tcount++\n\t}\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlib.Logger.Println(\"- found\", count, \"rows whose configuration need changing\")\n\n\t\/\/ update the rows which need to be set - do multiple updates but I don't care\n\tlib.Logger.Println(\"Updating p_s.setup_instruments to allow wait\/synch\/mutex configuration\")\n\n\tcount = 0\n\tfor i := range si.rows {\n\t\tsql := \"UPDATE setup_instruments SET enabled = 'YES', TIMED = 'YES' WHERE NAME = '\" + si.rows[i].NAME + \"'\"\n\t\tif _, err := dbh.Exec(sql); err == nil {\n\t\t\tsi.update_succeeded = true\n\t\t} else {\n\t\t\tif err.Error()[0:10] != UPDATE_FAILED {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\tcount++\n\t}\n\tif si.update_succeeded {\n\t\tlib.Logger.Println(count, \"rows changed in p_s.setup_instruments\")\n\t} else {\n\t\tlib.Logger.Println( \"Insufficient privileges to UPDATE setup_instruments: \" . err.String() )\n\t}\n}\n\n\/\/ restore any changed rows back to their original state\nfunc (si *SetupInstruments) Restore(dbh *sql.DB) {\n\t\/\/ If the previous update didn't work then don't try to restore\n\tif ! si.update_succeeded {\n\t\tlib.Logger.Println(\"Not restoring p_s.setup_instruments to its original settings as previous UPDATE had failed\")\n\t\treturn\n\t} else {\n\t\tlib.Logger.Println(\"Restoring p_s.setup_instruments to its original settings\")\n\t}\n\n\t\/\/ update the rows which need to be set - do multiple updates but I don't care\n\tcount := 0\n\tfor i := range si.rows {\n\t\tsql := \"UPDATE setup_instruments SET enabled = '\" + si.rows[i].ENABLED + \"', TIMED = '\" + si.rows[i].TIMED + \"' WHERE NAME = '\" + si.rows[i].NAME + \"'\"\n\t\tif _, err := dbh.Exec(sql); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tcount++\n\t}\n\tlib.Logger.Println(count, \"rows changed in p_s.setup_instruments\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright The OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage exporterhelper\n\nimport (\n\t\"context\"\n\n\t\"go.uber.org\/zap\"\n\n\t\"go.opentelemetry.io\/collector\/component\"\n\t\"go.opentelemetry.io\/collector\/config\/configmodels\"\n\t\"go.opentelemetry.io\/collector\/consumer\/consumerdata\"\n\t\"go.opentelemetry.io\/collector\/consumer\/consumererror\"\n\t\"go.opentelemetry.io\/collector\/consumer\/pdata\"\n\t\"go.opentelemetry.io\/collector\/obsreport\"\n)\n\n\/\/ NumTimeSeries returns the number of timeseries in a MetricsData.\nfunc NumTimeSeries(md consumerdata.MetricsData) int {\n\treceivedTimeSeries := 0\n\tfor _, metric := range md.Metrics {\n\t\treceivedTimeSeries += len(metric.GetTimeseries())\n\t}\n\treturn receivedTimeSeries\n}\n\n\/\/ PushMetricsData is a helper function that is similar to ConsumeMetricsData but also returns\n\/\/ the number of dropped metrics.\ntype PushMetricsData func(ctx context.Context, md pdata.Metrics) (droppedTimeSeries int, err error)\n\ntype metricsRequest struct {\n\tbaseRequest\n\tmd     pdata.Metrics\n\tpusher PushMetricsData\n}\n\nfunc newMetricsRequest(ctx context.Context, md pdata.Metrics, pusher PushMetricsData) request {\n\treturn &metricsRequest{\n\t\tbaseRequest: baseRequest{ctx: ctx},\n\t\tmd:          md,\n\t\tpusher:      pusher,\n\t}\n}\n\nfunc (req *metricsRequest) onPartialError(partialErr consumererror.PartialError) request {\n\treturn newMetricsRequest(req.ctx, partialErr.GetMetrics(), req.pusher)\n}\n\nfunc (req *metricsRequest) export(ctx context.Context) (int, error) {\n\treturn req.pusher(ctx, req.md)\n}\n\nfunc (req *metricsRequest) count() int {\n\t_, numPoints := req.md.MetricAndDataPointCount()\n\treturn numPoints\n}\n\ntype metricsExporter struct {\n\t*baseExporter\n\tpusher PushMetricsData\n}\n\nfunc (mexp *metricsExporter) ConsumeMetrics(ctx context.Context, md pdata.Metrics) error {\n\tif mexp.baseExporter.convertResourceToTelemetry {\n\t\tmd = convertResourceToLabels(md)\n\t}\n\texporterCtx := obsreport.ExporterContext(ctx, mexp.cfg.Name())\n\treq := newMetricsRequest(exporterCtx, md, mexp.pusher)\n\t_, err := mexp.sender.send(req)\n\treturn err\n}\n\n\/\/ NewMetricsExporter creates an MetricsExporter that records observability metrics and wraps every request with a Span.\nfunc NewMetricsExporter(\n\tcfg configmodels.Exporter,\n\tlogger *zap.Logger,\n\tpushMetricsData PushMetricsData,\n\toptions ...ExporterOption,\n) (component.MetricsExporter, error) {\n\tif cfg == nil {\n\t\treturn nil, errNilConfig\n\t}\n\n\tif pushMetricsData == nil {\n\t\treturn nil, errNilPushMetricsData\n\t}\n\n\tbe := newBaseExporter(cfg, logger, options...)\n\tbe.wrapConsumerSender(func(nextSender requestSender) requestSender {\n\t\treturn &metricsSenderWithObservability{\n\t\t\texporterName: cfg.Name(),\n\t\t\tnextSender:   nextSender,\n\t\t}\n\t})\n\n\treturn &metricsExporter{\n\t\tbaseExporter: be,\n\t\tpusher:       pushMetricsData,\n\t}, nil\n}\n\ntype metricsSenderWithObservability struct {\n\texporterName string\n\tnextSender   requestSender\n}\n\nfunc (mewo *metricsSenderWithObservability) send(req request) (int, error) {\n\treq.setContext(obsreport.StartMetricsExportOp(req.context(), mewo.exporterName))\n\t_, err := mewo.nextSender.send(req)\n\n\t\/\/ TODO: this is not ideal: it should come from the next function itself.\n\t\/\/ \ttemporarily loading it from internal format. Once full switch is done\n\t\/\/ \tto new metrics will remove this.\n\tmReq := req.(*metricsRequest)\n\tnumReceivedMetrics, numPoints := mReq.md.MetricAndDataPointCount()\n\n\tobsreport.EndMetricsExportOp(req.context(), numPoints, err)\n\treturn numReceivedMetrics, err\n}\n<commit_msg>Remove unused public function, usage in contrib will be soon removed (#2118)<commit_after>\/\/ Copyright The OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage exporterhelper\n\nimport (\n\t\"context\"\n\n\t\"go.uber.org\/zap\"\n\n\t\"go.opentelemetry.io\/collector\/component\"\n\t\"go.opentelemetry.io\/collector\/config\/configmodels\"\n\t\"go.opentelemetry.io\/collector\/consumer\/consumererror\"\n\t\"go.opentelemetry.io\/collector\/consumer\/pdata\"\n\t\"go.opentelemetry.io\/collector\/obsreport\"\n)\n\n\/\/ PushMetricsData is a helper function that is similar to ConsumeMetricsData but also returns\n\/\/ the number of dropped metrics.\ntype PushMetricsData func(ctx context.Context, md pdata.Metrics) (droppedTimeSeries int, err error)\n\ntype metricsRequest struct {\n\tbaseRequest\n\tmd     pdata.Metrics\n\tpusher PushMetricsData\n}\n\nfunc newMetricsRequest(ctx context.Context, md pdata.Metrics, pusher PushMetricsData) request {\n\treturn &metricsRequest{\n\t\tbaseRequest: baseRequest{ctx: ctx},\n\t\tmd:          md,\n\t\tpusher:      pusher,\n\t}\n}\n\nfunc (req *metricsRequest) onPartialError(partialErr consumererror.PartialError) request {\n\treturn newMetricsRequest(req.ctx, partialErr.GetMetrics(), req.pusher)\n}\n\nfunc (req *metricsRequest) export(ctx context.Context) (int, error) {\n\treturn req.pusher(ctx, req.md)\n}\n\nfunc (req *metricsRequest) count() int {\n\t_, numPoints := req.md.MetricAndDataPointCount()\n\treturn numPoints\n}\n\ntype metricsExporter struct {\n\t*baseExporter\n\tpusher PushMetricsData\n}\n\nfunc (mexp *metricsExporter) ConsumeMetrics(ctx context.Context, md pdata.Metrics) error {\n\tif mexp.baseExporter.convertResourceToTelemetry {\n\t\tmd = convertResourceToLabels(md)\n\t}\n\texporterCtx := obsreport.ExporterContext(ctx, mexp.cfg.Name())\n\treq := newMetricsRequest(exporterCtx, md, mexp.pusher)\n\t_, err := mexp.sender.send(req)\n\treturn err\n}\n\n\/\/ NewMetricsExporter creates an MetricsExporter that records observability metrics and wraps every request with a Span.\nfunc NewMetricsExporter(\n\tcfg configmodels.Exporter,\n\tlogger *zap.Logger,\n\tpushMetricsData PushMetricsData,\n\toptions ...ExporterOption,\n) (component.MetricsExporter, error) {\n\tif cfg == nil {\n\t\treturn nil, errNilConfig\n\t}\n\n\tif pushMetricsData == nil {\n\t\treturn nil, errNilPushMetricsData\n\t}\n\n\tbe := newBaseExporter(cfg, logger, options...)\n\tbe.wrapConsumerSender(func(nextSender requestSender) requestSender {\n\t\treturn &metricsSenderWithObservability{\n\t\t\texporterName: cfg.Name(),\n\t\t\tnextSender:   nextSender,\n\t\t}\n\t})\n\n\treturn &metricsExporter{\n\t\tbaseExporter: be,\n\t\tpusher:       pushMetricsData,\n\t}, nil\n}\n\ntype metricsSenderWithObservability struct {\n\texporterName string\n\tnextSender   requestSender\n}\n\nfunc (mewo *metricsSenderWithObservability) send(req request) (int, error) {\n\treq.setContext(obsreport.StartMetricsExportOp(req.context(), mewo.exporterName))\n\t_, err := mewo.nextSender.send(req)\n\n\t\/\/ TODO: this is not ideal: it should come from the next function itself.\n\t\/\/ \ttemporarily loading it from internal format. Once full switch is done\n\t\/\/ \tto new metrics will remove this.\n\tmReq := req.(*metricsRequest)\n\tnumReceivedMetrics, numPoints := mReq.md.MetricAndDataPointCount()\n\n\tobsreport.EndMetricsExportOp(req.context(), numPoints, err)\n\treturn numReceivedMetrics, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package command\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/funkygao\/gafka\/ctx\"\n\t\"github.com\/funkygao\/gafka\/zk\"\n\t\"github.com\/funkygao\/gocli\"\n)\n\ntype TopBroker struct {\n\tUi  cli.Ui\n\tCmd string\n\n\tzone, cluster, topic string\n\tdrawMode             bool\n\tinterval             time.Duration\n\n\toffsets     map[string]int64 \/\/ host => offset sum\n\tlastOffsets map[string]int64\n}\n\nfunc (this *TopBroker) Run(args []string) (exitCode int) {\n\tcmdFlags := flag.NewFlagSet(\"topbroker\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { this.Ui.Output(this.Help()) }\n\tcmdFlags.StringVar(&this.zone, \"z\", ctx.ZkDefaultZone(), \"\")\n\tcmdFlags.StringVar(&this.cluster, \"c\", \"\", \"\")\n\tcmdFlags.StringVar(&this.topic, \"t\", \"\", \"\")\n\tcmdFlags.BoolVar(&this.drawMode, \"g\", false, \"\")\n\tcmdFlags.DurationVar(&this.interval, \"i\", time.Second*5, \"refresh interval\")\n\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tthis.offsets = make(map[string]int64)\n\tthis.lastOffsets = make(map[string]int64)\n\n\tif this.interval.Seconds() < 1 {\n\t\tthis.interval = time.Second\n\t}\n\n\tzkzone := zk.NewZkZone(zk.DefaultConfig(this.zone, ctx.ZoneZkAddrs(this.zone)))\n\tzkzone.ForSortedClusters(func(zkcluster *zk.ZkCluster) {\n\t\tif !patternMatched(zkcluster.Name(), this.cluster) {\n\t\t\treturn\n\t\t}\n\n\t\tgo this.clusterTopProducers(zkcluster)\n\t})\n\n\tticker := time.NewTicker(this.interval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\trefreshScreen()\n\t\t\tthis.showAndResetCounters()\n\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (this *TopBroker) showAndResetCounters() {\n\td := this.interval.Seconds()\n\tfor host, offset := range this.offsets {\n\t\tqps := float64(0)\n\t\tif lastOffset, present := this.lastOffsets[host]; present {\n\t\t\tqps = float64(offset-lastOffset) \/ d\n\t\t}\n\n\t\tthis.Ui.Output(fmt.Sprintf(\"%20s %.2f\", host, qps))\n\t}\n\n\tfor host, offset := range this.offsets {\n\t\tthis.lastOffsets[host] = offset\n\t}\n\tthis.offsets = make(map[string]int64)\n}\n\nfunc (this *TopBroker) clusterTopProducers(zkcluster *zk.ZkCluster) {\n\tkfk, err := sarama.NewClient(zkcluster.BrokerList(), sarama.NewConfig())\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer kfk.Close()\n\n\tfor {\n\t\ttopics, err := kfk.Topics()\n\t\tswallow(err)\n\n\t\tfor _, topic := range topics {\n\t\t\tif !patternMatched(topic, this.topic) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpartions, err := kfk.WritablePartitions(topic)\n\t\t\tswallow(err)\n\t\t\tfor _, partitionID := range partions {\n\t\t\t\tleader, err := kfk.Leader(topic, partitionID)\n\t\t\t\tswallow(err)\n\n\t\t\t\tlatestOffset, err := kfk.GetOffset(topic, partitionID,\n\t\t\t\t\tsarama.OffsetNewest)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\thost, _, err := net.SplitHostPort(leader.Addr())\n\t\t\t\tswallow(err)\n\n\t\t\t\thost = shortIp(host)\n\t\t\t\tif _, present := this.offsets[host]; !present {\n\t\t\t\t\tthis.offsets[host] = 0\n\t\t\t\t}\n\t\t\t\tthis.offsets[host] += latestOffset\n\t\t\t}\n\t\t}\n\n\t\ttime.Sleep(time.Second)\n\t\tkfk.RefreshMetadata(topics...)\n\t}\n}\n\nfunc (*TopBroker) Synopsis() string {\n\treturn \"Unix “top” like utility for kafka brokers\"\n}\n\nfunc (this *TopBroker) Help() string {\n\thelp := fmt.Sprintf(`\nUsage: %s topbroker [options]\n\n    Unix “top” like utility for kafka brokers\n\nOptions:\n\n    -z zone\n      Default %s\n\n    -c cluster pattern\n\n    -t topic pattern  \n\n    -i interval\n      Refresh interval in seconds.\n      e,g. 5s    \n\n`, this.Cmd)\n\treturn strings.TrimSpace(help)\n}\n<commit_msg>add lock<commit_after>package command\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/funkygao\/gafka\/ctx\"\n\t\"github.com\/funkygao\/gafka\/zk\"\n\t\"github.com\/funkygao\/gocli\"\n)\n\ntype TopBroker struct {\n\tUi  cli.Ui\n\tCmd string\n\n\tmu sync.Mutex\n\n\tzone, cluster, topic string\n\tdrawMode             bool\n\tinterval             time.Duration\n\tshortIp              bool\n\n\toffsets     map[string]int64 \/\/ host => offset sum\n\tlastOffsets map[string]int64\n}\n\nfunc (this *TopBroker) Run(args []string) (exitCode int) {\n\tcmdFlags := flag.NewFlagSet(\"topbroker\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { this.Ui.Output(this.Help()) }\n\tcmdFlags.StringVar(&this.zone, \"z\", ctx.ZkDefaultZone(), \"\")\n\tcmdFlags.StringVar(&this.cluster, \"c\", \"\", \"\")\n\tcmdFlags.StringVar(&this.topic, \"t\", \"\", \"\")\n\tcmdFlags.BoolVar(&this.drawMode, \"g\", false, \"\")\n\tcmdFlags.BoolVar(&this.shortIp, \"shortip\", false, \"\")\n\tcmdFlags.DurationVar(&this.interval, \"i\", time.Second*5, \"refresh interval\")\n\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tthis.offsets = make(map[string]int64)\n\tthis.lastOffsets = make(map[string]int64)\n\n\tif this.interval.Seconds() < 1 {\n\t\tthis.interval = time.Second\n\t}\n\n\tzkzone := zk.NewZkZone(zk.DefaultConfig(this.zone, ctx.ZoneZkAddrs(this.zone)))\n\tzkzone.ForSortedClusters(func(zkcluster *zk.ZkCluster) {\n\t\tif !patternMatched(zkcluster.Name(), this.cluster) {\n\t\t\treturn\n\t\t}\n\n\t\tgo this.clusterTopProducers(zkcluster)\n\t})\n\n\tticker := time.NewTicker(this.interval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\trefreshScreen()\n\t\t\tthis.showAndResetCounters()\n\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (this *TopBroker) showAndResetCounters() {\n\tthis.mu.Lock()\n\tdefer this.mu.Unlock()\n\n\td := this.interval.Seconds()\n\tfor host, offset := range this.offsets {\n\t\tqps := float64(0)\n\t\tif lastOffset, present := this.lastOffsets[host]; present {\n\t\t\tqps = float64(offset-lastOffset) \/ d\n\t\t}\n\n\t\tthis.Ui.Output(fmt.Sprintf(\"%20s %.2f\", host, qps))\n\t}\n\n\tfor host, offset := range this.offsets {\n\t\tthis.lastOffsets[host] = offset\n\t}\n\tthis.offsets = make(map[string]int64)\n}\n\nfunc (this *TopBroker) clusterTopProducers(zkcluster *zk.ZkCluster) {\n\tkfk, err := sarama.NewClient(zkcluster.BrokerList(), sarama.NewConfig())\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer kfk.Close()\n\n\tfor {\n\t\ttopics, err := kfk.Topics()\n\t\tswallow(err)\n\n\t\tfor _, topic := range topics {\n\t\t\tif !patternMatched(topic, this.topic) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tpartions, err := kfk.WritablePartitions(topic)\n\t\t\tswallow(err)\n\t\t\tfor _, partitionID := range partions {\n\t\t\t\tleader, err := kfk.Leader(topic, partitionID)\n\t\t\t\tswallow(err)\n\n\t\t\t\tlatestOffset, err := kfk.GetOffset(topic, partitionID,\n\t\t\t\t\tsarama.OffsetNewest)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\thost, _, err := net.SplitHostPort(leader.Addr())\n\t\t\t\tswallow(err)\n\n\t\t\t\tif this.shortIp {\n\t\t\t\t\thost = shortIp(host)\n\t\t\t\t}\n\n\t\t\t\tthis.mu.Lock()\n\t\t\t\tif _, present := this.offsets[host]; !present {\n\t\t\t\t\tthis.offsets[host] = 0\n\t\t\t\t}\n\t\t\t\tthis.offsets[host] += latestOffset\n\t\t\t\tthis.mu.Unlock()\n\t\t\t}\n\t\t}\n\n\t\ttime.Sleep(time.Second)\n\t\tkfk.RefreshMetadata(topics...)\n\t}\n}\n\nfunc (*TopBroker) Synopsis() string {\n\treturn \"Unix “top” like utility for kafka brokers\"\n}\n\nfunc (this *TopBroker) Help() string {\n\thelp := fmt.Sprintf(`\nUsage: %s topbroker [options]\n\n    Unix “top” like utility for kafka brokers\n\nOptions:\n\n    -z zone\n      Default %s\n\n    -c cluster pattern\n\n    -t topic pattern  \n\n    -i interval\n      Refresh interval in seconds.\n      e,g. 5s    \n\n    -shortip\n\n`, this.Cmd)\n\treturn strings.TrimSpace(help)\n}\n<|endoftext|>"}
{"text":"<commit_before>package softlayer\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n\t\"github.com\/softlayer\/softlayer-go\/session\"\n)\n\nfunc Provider() terraform.ResourceProvider {\n\tdefaultSoftLayerSession := session.New()\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"username\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: func() (interface{}, error) {\n\t\t\t\t\treturn defaultSoftLayerSession.UserName, nil\n\t\t\t\t},\n\t\t\t\tDescription: \"The user name for SoftLayer API operations.\",\n\t\t\t},\n\t\t\t\"api_key\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: func() (interface{}, error) {\n\t\t\t\t\treturn defaultSoftLayerSession.APIKey, nil\n\t\t\t\t},\n\t\t\t\tDescription: \"The API key for SoftLayer API operations.\",\n\t\t\t},\n\t\t\t\"endpoint_url\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: func() (interface{}, error) {\n\t\t\t\t\treturn defaultSoftLayerSession.Endpoint, nil\n\t\t\t\t},\n\t\t\t\tDescription: \"The endpoint url for the SoftLayer API.\",\n\t\t\t},\n\t\t\t\"timeout\": {\n\t\t\t\tType:        schema.TypeInt,\n\t\t\t\tOptional:    true,\n\t\t\t\tDescription: \"The timeout (in seconds) to set for any SoftLayer API calls made.\",\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"softlayer_ssh_key\":        dataSourceSoftLayerSSHKey(),\n\t\t\t\"softlayer_image_template\": dataSourceSoftLayerImageTemplate(),\n\t\t\t\"softlayer_vlan\":           dataSourceSoftLayerVlan(),\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"softlayer_virtual_guest\":          resourceSoftLayerVirtualGuest(),\n\t\t\t\"softlayer_bare_metal\":             resourceSoftLayerBareMetal(),\n\t\t\t\"softlayer_ssh_key\":                resourceSoftLayerSSHKey(),\n\t\t\t\"softlayer_dns_domain_record\":      resourceSoftLayerDnsDomainRecord(),\n\t\t\t\"softlayer_dns_domain\":             resourceSoftLayerDnsDomain(),\n\t\t\t\"softlayer_lb_vpx\":                 resourceSoftLayerLbVpx(),\n\t\t\t\"softlayer_lb_vpx_vip\":             resourceSoftLayerLbVpxVip(),\n\t\t\t\"softlayer_lb_vpx_service\":         resourceSoftLayerLbVpxService(),\n\t\t\t\"softlayer_lb_local\":               resourceSoftLayerLbLocal(),\n\t\t\t\"softlayer_lb_local_service_group\": resourceSoftLayerLbLocalServiceGroup(),\n\t\t\t\"softlayer_lb_local_service\":       resourceSoftLayerLbLocalService(),\n\t\t\t\"softlayer_security_certificate\":   resourceSoftLayerSecurityCertificate(),\n\t\t\t\"softlayer_user\":                   resourceSoftLayerUser(),\n\t\t\t\"softlayer_objectstorage_account\":  resourceSoftLayerObjectStorageAccount(),\n\t\t\t\"softlayer_provisioning_hook\":      resourceSoftLayerProvisioningHook(),\n\t\t\t\"softlayer_scale_policy\":           resourceSoftLayerScalePolicy(),\n\t\t\t\"softlayer_scale_group\":            resourceSoftLayerScaleGroup(),\n\t\t\t\"softlayer_basic_monitor\":          resourceSoftLayerBasicMonitor(),\n\t\t\t\"softlayer_vlan\":                   resourceSoftLayerVlan(),\n\t\t\t\"softlayer_global_ip\":              resourceSoftLayerGlobalIp(),\n\t\t},\n\n\t\tConfigureFunc: providerConfigure,\n\t}\n}\n\nfunc providerConfigure(d *schema.ResourceData) (interface{}, error) {\n\tsess := session.Session{\n\t\tUserName: d.Get(\"username\").(string),\n\t\tAPIKey:   d.Get(\"api_key\").(string),\n\t\tEndpoint: d.Get(\"endpoint_url\").(string),\n\t}\n\n\tif rawTimeout, ok := d.GetOk(\"timeout\"); ok {\n\t\ttimeout := rawTimeout.(int)\n\t\tsess.Timeout = time.Duration(timeout)\n\t}\n\n\tif sess.UserName == \"\" || sess.APIKey == \"\" {\n\t\treturn nil, errors.New(\n\t\t\t\"No SoftLayer credentials were found. Please ensure you have specified\" +\n\t\t\t\t\" them in the provider or in the environment (see the documentation).\",\n\t\t)\n\t}\n\n\tif os.Getenv(\"TF_LOG\") != \"\" {\n\t\tsess.Debug = true\n\t}\n\n\treturn &sess, nil\n}\n<commit_msg>Add vpx_ha resource to provider<commit_after>package softlayer\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n\t\"github.com\/softlayer\/softlayer-go\/session\"\n)\n\nfunc Provider() terraform.ResourceProvider {\n\tdefaultSoftLayerSession := session.New()\n\treturn &schema.Provider{\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"username\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: func() (interface{}, error) {\n\t\t\t\t\treturn defaultSoftLayerSession.UserName, nil\n\t\t\t\t},\n\t\t\t\tDescription: \"The user name for SoftLayer API operations.\",\n\t\t\t},\n\t\t\t\"api_key\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: func() (interface{}, error) {\n\t\t\t\t\treturn defaultSoftLayerSession.APIKey, nil\n\t\t\t\t},\n\t\t\t\tDescription: \"The API key for SoftLayer API operations.\",\n\t\t\t},\n\t\t\t\"endpoint_url\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tDefaultFunc: func() (interface{}, error) {\n\t\t\t\t\treturn defaultSoftLayerSession.Endpoint, nil\n\t\t\t\t},\n\t\t\t\tDescription: \"The endpoint url for the SoftLayer API.\",\n\t\t\t},\n\t\t\t\"timeout\": {\n\t\t\t\tType:        schema.TypeInt,\n\t\t\t\tOptional:    true,\n\t\t\t\tDescription: \"The timeout (in seconds) to set for any SoftLayer API calls made.\",\n\t\t\t},\n\t\t},\n\n\t\tDataSourcesMap: map[string]*schema.Resource{\n\t\t\t\"softlayer_ssh_key\":        dataSourceSoftLayerSSHKey(),\n\t\t\t\"softlayer_image_template\": dataSourceSoftLayerImageTemplate(),\n\t\t\t\"softlayer_vlan\":           dataSourceSoftLayerVlan(),\n\t\t},\n\n\t\tResourcesMap: map[string]*schema.Resource{\n\t\t\t\"softlayer_virtual_guest\":          resourceSoftLayerVirtualGuest(),\n\t\t\t\"softlayer_bare_metal\":             resourceSoftLayerBareMetal(),\n\t\t\t\"softlayer_ssh_key\":                resourceSoftLayerSSHKey(),\n\t\t\t\"softlayer_dns_domain_record\":      resourceSoftLayerDnsDomainRecord(),\n\t\t\t\"softlayer_dns_domain\":             resourceSoftLayerDnsDomain(),\n\t\t\t\"softlayer_lb_vpx\":                 resourceSoftLayerLbVpx(),\n\t\t\t\"softlayer_lb_vpx_vip\":             resourceSoftLayerLbVpxVip(),\n\t\t\t\"softlayer_lb_vpx_service\":         resourceSoftLayerLbVpxService(),\n\t\t\t\"softlayer_lb_vpx_ha\":              resourceSoftLayerLbVpxHa(),\n\t\t\t\"softlayer_lb_local\":               resourceSoftLayerLbLocal(),\n\t\t\t\"softlayer_lb_local_service_group\": resourceSoftLayerLbLocalServiceGroup(),\n\t\t\t\"softlayer_lb_local_service\":       resourceSoftLayerLbLocalService(),\n\t\t\t\"softlayer_security_certificate\":   resourceSoftLayerSecurityCertificate(),\n\t\t\t\"softlayer_user\":                   resourceSoftLayerUser(),\n\t\t\t\"softlayer_objectstorage_account\":  resourceSoftLayerObjectStorageAccount(),\n\t\t\t\"softlayer_provisioning_hook\":      resourceSoftLayerProvisioningHook(),\n\t\t\t\"softlayer_scale_policy\":           resourceSoftLayerScalePolicy(),\n\t\t\t\"softlayer_scale_group\":            resourceSoftLayerScaleGroup(),\n\t\t\t\"softlayer_basic_monitor\":          resourceSoftLayerBasicMonitor(),\n\t\t\t\"softlayer_vlan\":                   resourceSoftLayerVlan(),\n\t\t\t\"softlayer_global_ip\":              resourceSoftLayerGlobalIp(),\n\t\t},\n\n\t\tConfigureFunc: providerConfigure,\n\t}\n}\n\nfunc providerConfigure(d *schema.ResourceData) (interface{}, error) {\n\tsess := session.Session{\n\t\tUserName: d.Get(\"username\").(string),\n\t\tAPIKey:   d.Get(\"api_key\").(string),\n\t\tEndpoint: d.Get(\"endpoint_url\").(string),\n\t}\n\n\tif rawTimeout, ok := d.GetOk(\"timeout\"); ok {\n\t\ttimeout := rawTimeout.(int)\n\t\tsess.Timeout = time.Duration(timeout)\n\t}\n\n\tif sess.UserName == \"\" || sess.APIKey == \"\" {\n\t\treturn nil, errors.New(\n\t\t\t\"No SoftLayer credentials were found. Please ensure you have specified\" +\n\t\t\t\t\" them in the provider or in the environment (see the documentation).\",\n\t\t)\n\t}\n\n\tif os.Getenv(\"TF_LOG\") != \"\" {\n\t\tsess.Debug = true\n\t}\n\n\treturn &sess, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package errs provides a simple error package with stack traces.\npackage errs\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"runtime\"\n)\n\n\/\/ Namer is implemented by all errors returned in this package. It returns a\n\/\/ name for the class of error it is, and a boolean indicating if the name is\n\/\/ valid.\ntype Namer interface{ Name() (string, bool) }\n\n\/\/ Causer is implemented by all errors returned in this package. It returns\n\/\/ the underlying cause of the error, or nil if there is no underlying cause.\ntype Causer interface{ Cause() error }\n\n\/\/ New returns an error not contained in any class. This is the same as calling\n\/\/ fmt.Errorf(...) except it captures a stack trace on creation.\nfunc New(format string, args ...interface{}) error {\n\treturn (*Class).create(nil, 3, fmt.Errorf(format, args...))\n}\n\n\/\/ Wrap returns an error not contained in any class. It just associates a stack\n\/\/ trace with the error. Wrap returns nil if err is nil.\nfunc Wrap(err error) error {\n\treturn (*Class).create(nil, 3, err)\n}\n\n\/\/ Unwrap returns the underlying error, if any, or just the error.\nfunc Unwrap(err error) error {\n\t\/\/ we call Cause as much as possible. Since comparing arbitrary interfaces\n\t\/\/ with equality isn't panic safe, we only loop up to 100 times to ensure\n\t\/\/ that a poor implementation that loops does not cause a hang.\n\tfor i := 0; err != nil && i < 100; i++ {\n\t\tcauser, ok := err.(Causer)\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ if the cause of some error is nil, we return it.\n\t\tnerr := causer.Cause()\n\t\tif nerr == nil {\n\t\t\treturn err\n\t\t}\n\t\terr = nerr\n\t}\n\n\treturn err\n}\n\n\/\/ Classes returns all the classes that have wrapped the error.\nfunc Classes(err error) []*Class {\n\tif err, ok := err.(*errorT); ok && err != nil {\n\t\treturn append([]*Class(nil), err.classes...)\n\t}\n\treturn nil\n}\n\n\/\/\n\/\/ error classes\n\/\/\n\n\/\/ Class represents a class of errors. You can construct errors, and check if\n\/\/ errors are part of the class.\ntype Class string\n\n\/\/ Has returns true if the passed in error was wrapped by this class.\nfunc (c *Class) Has(err error) bool {\n\tif err, ok := err.(*errorT); ok {\n\t\tfor _, k := range err.classes {\n\t\t\tif k == c {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ New constructs an error with the format string that will be contained by\n\/\/ this class. This is the same as calling Wrap(fmt.Errorf(...)).\nfunc (c *Class) New(format string, args ...interface{}) error {\n\treturn c.create(3, fmt.Errorf(format, args...))\n}\n\n\/\/ Wrap returns a new error based on the passed in error that is contained in\n\/\/ this class. Wrap returns nil if err is nil.\nfunc (c *Class) Wrap(err error) error {\n\treturn c.create(3, err)\n}\n\n\/\/ create constructs the error, or just adds the class to the error, keeping\n\/\/ track of the stack if it needs to construct it.\nfunc (c *Class) create(depth int, err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif err, ok := err.(*errorT); ok {\n\t\tif c != nil && err.outerClass() != c {\n\t\t\terr.classes = append(err.classes, c)\n\t\t}\n\t\treturn err\n\t}\n\n\tvar pcs [256]uintptr\n\tn := runtime.Callers(depth, pcs[:])\n\n\tvar classes []*Class\n\tif c != nil {\n\t\tclasses = []*Class{c}\n\t}\n\n\treturn &errorT{\n\t\tclasses: classes,\n\t\terr:     err,\n\t\tpcs:     pcs[:n:n],\n\t}\n}\n\n\/\/\n\/\/ errors\n\/\/\n\n\/\/ errorT is the type of errors returned from this package.\ntype errorT struct {\n\tclasses []*Class\n\tpcs     []uintptr\n\terr     error\n}\n\nvar ( \/\/ ensure *errorT implements the helper interfaces.\n\t_ Namer  = (*errorT)(nil)\n\t_ Causer = (*errorT)(nil)\n\t_ error  = (*errorT)(nil)\n)\n\n\/\/ outerClass returns the outermost wrapping class of the error.\nfunc (e *errorT) outerClass() *Class {\n\tif len(e.classes) == 0 {\n\t\treturn nil\n\t}\n\treturn e.classes[len(e.classes)-1]\n}\n\n\/\/ errorT implements the error interface.\nfunc (e *errorT) Error() string {\n\treturn fmt.Sprintf(\"%v\", e)\n}\n\n\/\/ Format handles the formatting of the error. Using a \"+\" on the format string\n\/\/ specifier will also write the stack trace.\nfunc (e *errorT) Format(f fmt.State, c rune) {\n\tvar printSeparator bool\n\tfor i := len(e.classes) - 1; i >= 0; i-- {\n\t\tname := string(*e.classes[i])\n\t\tif len(name) > 0 {\n\t\t\tif printSeparator {\n\t\t\t\tfmt.Fprint(f, \": \")\n\t\t\t}\n\t\t\tprintSeparator = true\n\t\t\tfmt.Fprint(f, name)\n\t\t}\n\t}\n\tif len(e.err.Error()) > 0 {\n\t\tif printSeparator {\n\t\t\tfmt.Fprint(f, \": \")\n\t\t}\n\t\tfmt.Fprintf(f, \"%v\", e.err)\n\t}\n\n\tif f.Flag(int('+')) {\n\t\tsummarizeStack(f, e.pcs)\n\t}\n}\n\n\/\/ Cause implements the interface wrapping errors are expected to implement\n\/\/ to allow getting at underlying causes.\nfunc (e *errorT) Cause() error {\n\treturn e.err\n}\n\n\/\/ Name returns the name for the error, which is the first wrapping class.\nfunc (e *errorT) Name() (string, bool) {\n\touter := e.outerClass()\n\tif outer == nil {\n\t\treturn \"\", false\n\t}\n\treturn string(*outer), true\n}\n\n\/\/ summarizeStack writes stack line entries to the writer.\nfunc summarizeStack(w io.Writer, pcs []uintptr) {\n\tframes := runtime.CallersFrames(pcs)\n\tfor {\n\t\tframe, more := frames.Next()\n\t\tif !more {\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprintf(w, \"\\n\\t%s:%d\", frame.Function, frame.Line)\n\t}\n}\n<commit_msg>Avoid double error formatting<commit_after>\/\/ Package errs provides a simple error package with stack traces.\npackage errs\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"runtime\"\n)\n\n\/\/ Namer is implemented by all errors returned in this package. It returns a\n\/\/ name for the class of error it is, and a boolean indicating if the name is\n\/\/ valid.\ntype Namer interface{ Name() (string, bool) }\n\n\/\/ Causer is implemented by all errors returned in this package. It returns\n\/\/ the underlying cause of the error, or nil if there is no underlying cause.\ntype Causer interface{ Cause() error }\n\n\/\/ New returns an error not contained in any class. This is the same as calling\n\/\/ fmt.Errorf(...) except it captures a stack trace on creation.\nfunc New(format string, args ...interface{}) error {\n\treturn (*Class).create(nil, 3, fmt.Errorf(format, args...))\n}\n\n\/\/ Wrap returns an error not contained in any class. It just associates a stack\n\/\/ trace with the error. Wrap returns nil if err is nil.\nfunc Wrap(err error) error {\n\treturn (*Class).create(nil, 3, err)\n}\n\n\/\/ Unwrap returns the underlying error, if any, or just the error.\nfunc Unwrap(err error) error {\n\t\/\/ we call Cause as much as possible. Since comparing arbitrary interfaces\n\t\/\/ with equality isn't panic safe, we only loop up to 100 times to ensure\n\t\/\/ that a poor implementation that loops does not cause a hang.\n\tfor i := 0; err != nil && i < 100; i++ {\n\t\tcauser, ok := err.(Causer)\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ if the cause of some error is nil, we return it.\n\t\tnerr := causer.Cause()\n\t\tif nerr == nil {\n\t\t\treturn err\n\t\t}\n\t\terr = nerr\n\t}\n\n\treturn err\n}\n\n\/\/ Classes returns all the classes that have wrapped the error.\nfunc Classes(err error) []*Class {\n\tif err, ok := err.(*errorT); ok && err != nil {\n\t\treturn append([]*Class(nil), err.classes...)\n\t}\n\treturn nil\n}\n\n\/\/\n\/\/ error classes\n\/\/\n\n\/\/ Class represents a class of errors. You can construct errors, and check if\n\/\/ errors are part of the class.\ntype Class string\n\n\/\/ Has returns true if the passed in error was wrapped by this class.\nfunc (c *Class) Has(err error) bool {\n\tif err, ok := err.(*errorT); ok {\n\t\tfor _, k := range err.classes {\n\t\t\tif k == c {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ New constructs an error with the format string that will be contained by\n\/\/ this class. This is the same as calling Wrap(fmt.Errorf(...)).\nfunc (c *Class) New(format string, args ...interface{}) error {\n\treturn c.create(3, fmt.Errorf(format, args...))\n}\n\n\/\/ Wrap returns a new error based on the passed in error that is contained in\n\/\/ this class. Wrap returns nil if err is nil.\nfunc (c *Class) Wrap(err error) error {\n\treturn c.create(3, err)\n}\n\n\/\/ create constructs the error, or just adds the class to the error, keeping\n\/\/ track of the stack if it needs to construct it.\nfunc (c *Class) create(depth int, err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif err, ok := err.(*errorT); ok {\n\t\tif c != nil && err.outerClass() != c {\n\t\t\terr.classes = append(err.classes, c)\n\t\t}\n\t\treturn err\n\t}\n\n\tvar pcs [256]uintptr\n\tn := runtime.Callers(depth, pcs[:])\n\n\tvar classes []*Class\n\tif c != nil {\n\t\tclasses = []*Class{c}\n\t}\n\n\treturn &errorT{\n\t\tclasses: classes,\n\t\terr:     err,\n\t\tpcs:     pcs[:n:n],\n\t}\n}\n\n\/\/\n\/\/ errors\n\/\/\n\n\/\/ errorT is the type of errors returned from this package.\ntype errorT struct {\n\tclasses []*Class\n\tpcs     []uintptr\n\terr     error\n}\n\nvar ( \/\/ ensure *errorT implements the helper interfaces.\n\t_ Namer  = (*errorT)(nil)\n\t_ Causer = (*errorT)(nil)\n\t_ error  = (*errorT)(nil)\n)\n\n\/\/ outerClass returns the outermost wrapping class of the error.\nfunc (e *errorT) outerClass() *Class {\n\tif len(e.classes) == 0 {\n\t\treturn nil\n\t}\n\treturn e.classes[len(e.classes)-1]\n}\n\n\/\/ errorT implements the error interface.\nfunc (e *errorT) Error() string {\n\treturn fmt.Sprintf(\"%v\", e)\n}\n\n\/\/ Format handles the formatting of the error. Using a \"+\" on the format string\n\/\/ specifier will also write the stack trace.\nfunc (e *errorT) Format(f fmt.State, c rune) {\n\tvar printSeparator bool\n\tfor i := len(e.classes) - 1; i >= 0; i-- {\n\t\tname := string(*e.classes[i])\n\t\tif len(name) > 0 {\n\t\t\tif printSeparator {\n\t\t\t\tfmt.Fprint(f, \": \")\n\t\t\t}\n\t\t\tprintSeparator = true\n\t\t\tfmt.Fprint(f, name)\n\t\t}\n\t}\n\tif text := e.err.Error(); len(text) > 0 {\n\t\tif printSeparator {\n\t\t\tfmt.Fprint(f, \": \")\n\t\t}\n\t\tfmt.Fprintf(f, \"%v\", text)\n\t}\n\n\tif f.Flag(int('+')) {\n\t\tsummarizeStack(f, e.pcs)\n\t}\n}\n\n\/\/ Cause implements the interface wrapping errors are expected to implement\n\/\/ to allow getting at underlying causes.\nfunc (e *errorT) Cause() error {\n\treturn e.err\n}\n\n\/\/ Name returns the name for the error, which is the first wrapping class.\nfunc (e *errorT) Name() (string, bool) {\n\touter := e.outerClass()\n\tif outer == nil {\n\t\treturn \"\", false\n\t}\n\treturn string(*outer), true\n}\n\n\/\/ summarizeStack writes stack line entries to the writer.\nfunc summarizeStack(w io.Writer, pcs []uintptr) {\n\tframes := runtime.CallersFrames(pcs)\n\tfor {\n\t\tframe, more := frames.Next()\n\t\tif !more {\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprintf(w, \"\\n\\t%s:%d\", frame.Function, frame.Line)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n)\n\ntype Etcd struct{}\n\ntype members struct {\n\tMembers []struct {\n\t\tClientURLs []string `json:\"clientURLs\"`\n\t\tID         string   `json:\"id\"`\n\t\tName       string   `json:\"name\"`\n\t\tPeerURLs   []string `json:\"peerURLs\"`\n\t} `json:\"members\"`\n}\n\n\/\/ Read all members of an etcd cluster\nfunc etcdMembers(url string) (error, *members) {\n\tresp, err := http.Get(url + \"\/v2\/members\")\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\tmembers := &members{}\n\n\terr = json.Unmarshal(body, &members)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\treturn nil, members\n}\n\n\/\/ Iterate over all members looking for health\nfunc (e *Etcd) Check(url string) (bool, error) {\n\thealth := false\n\n\terr, members := etcdMembers(url)\n\tif err != nil {\n\t\treturn health, err\n\t}\n\n\tfor _, m := range members.Members {\n\t\tfor _, url := range m.ClientURLs {\n\t\t\tresp, err := http.Get(url + \"\/health\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"failed to check health of member %s on %s: %v\\n\", m.ID, url, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult := struct{ Health string }{}\n\t\t\td := json.NewDecoder(resp.Body)\n\t\t\terr = d.Decode(&result)\n\t\t\tresp.Body.Close()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"failed to check the health of member %s on %s: %v\\n\", m.ID, url, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif result.Health == \"true\" {\n\t\t\t\thealth = true\n\t\t\t\t\/\/ fmt.Printf(\"member %s is healthy: got healthy result from %s\\n\", m.ID, url)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"member %s is unhealthy: got unhealthy result from %s\\n\", m.ID, url)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn health, nil\n}\n<commit_msg>simplify members structure so we can instantiate one for testing<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n)\n\ntype Etcd struct{}\n\ntype memb struct {\n\tClientURLs []string `json:\"clientURLs\"`\n\tID         string   `json:\"id\"`\n\tName       string   `json:\"name\"`\n\tPeerURLs   []string `json:\"peerURLs\"`\n}\n\ntype members struct {\n\tMembers []memb `json:\"members\"`\n}\n\n\/\/ Read all members of an etcd cluster\nfunc etcdMembers(url string) (error, *members) {\n\tresp, err := http.Get(url + \"\/v2\/members\")\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\tmembers := &members{}\n\n\terr = json.Unmarshal(body, &members)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\n\treturn nil, members\n}\n\n\/\/ Iterate over all members looking for health\nfunc (e *Etcd) Check(url string) (bool, error) {\n\thealth := false\n\n\terr, members := etcdMembers(url)\n\tif err != nil {\n\t\treturn health, err\n\t}\n\n\tfor _, m := range members.Members {\n\t\tfor _, url := range m.ClientURLs {\n\t\t\tresp, err := http.Get(url + \"\/health\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"failed to check health of member %s on %s: %v\\n\", m.ID, url, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresult := struct{ Health string }{}\n\t\t\td := json.NewDecoder(resp.Body)\n\t\t\terr = d.Decode(&result)\n\t\t\tresp.Body.Close()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"failed to check the health of member %s on %s: %v\\n\", m.ID, url, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif result.Health == \"true\" {\n\t\t\t\thealth = true\n\t\t\t\t\/\/ fmt.Printf(\"member %s is healthy: got healthy result from %s\\n\", m.ID, url)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"member %s is unhealthy: got unhealthy result from %s\\n\", m.ID, url)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn health, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package hookah\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/go-multierror\"\n)\n\n\/\/ HookExec represents a call to a hook\ntype HookExec struct {\n\tRootDir string\n\n\tOwner string\n\tRepo  string\n\n\tEvent string\n\tData  io.ReadSeeker\n\n\tHookServer *HookServer\n}\n\n\/\/ GetPathExecs fetches the executable filenames for the given path\nfunc (h *HookExec) GetPathExecs() ([]string, error) {\n\tpath := filepath.Join(h.RootDir, h.Owner, h.Repo, h.Event)\n\n\tfiles := []string{}\n\n\tfs, err := os.Stat(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn files, nil\n\t\t}\n\n\t\treturn files, err\n\t}\n\n\tif fs.IsDir() {\n\t\td, err := os.Open(path)\n\t\tdefer d.Close()\n\t\tif err != nil {\n\t\t\treturn files, err\n\t\t}\n\n\t\tfi, err := d.Readdir(-1)\n\t\tif err != nil {\n\t\t\treturn files, err\n\t\t}\n\n\t\tfor _, fi := range fi {\n\t\t\tif isExecFile(fi) {\n\t\t\t\t\/\/ fmt.Println(fi.Name(), fi.Size(), \"bytes\")\n\t\t\t\tfiles = append(files, filepath.Join(path, fi.Name()))\n\t\t\t}\n\t\t}\n\n\t} else if isExecFile(fs) {\n\t\t\/\/ fmt.Println(fs.Name(), fs.Size(), \"bytes\")\n\t\tfiles = append(files, filepath.Join(path, fs.Name()))\n\t} else {\n\t\treturn files, errors.New(\"bad file mumbo jumbo\")\n\t}\n\n\treturn files, nil\n}\n\n\/\/ Exec triggers the execution of all scripts associated with the given Hook\nfunc (h *HookExec) Exec(timeout time.Duration) error {\n\tfiles, err := h.GetPathExecs()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar result error\n\n\th.HookServer.Lock()\n\tdefer h.HookServer.Unlock()\n\n\tfor _, f := range files {\n\t\tcmd := exec.Command(f)\n\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\n\t\tstdin, err := cmd.StdinPipe()\n\t\tif err != nil {\n\t\t\tmultierror.Append(result, err)\n\t\t\tcontinue\n\t\t}\n\t\tdefer stdin.Close()\n\n\t\t\/\/ io.Copy( cmd.StdinPipe\n\t\terr = cmd.Start()\n\t\tif err != nil {\n\t\t\tmultierror.Append(result, err)\n\t\t\tcontinue\n\t\t}\n\n\t\th.Data.Seek(0, 0)\n\t\tio.Copy(stdin, h.Data)\n\t\tstdin.Close()\n\n\t\ttimer := time.AfterFunc(timeout, func() {\n\t\t\tcmd.Process.Kill()\n\t\t})\n\n\t\terr = cmd.Wait()\n\t\ttimer.Stop()\n\n\t\tif err != nil {\n\t\t\tmultierror.Append(result, err)\n\t\t\tcontinue\n\t\t}\n\t}\n\n\treturn result\n}\n\n\/\/ todo: base this on OS\nfunc isExecFile(fi os.FileInfo) bool {\n\treturn fi.Mode().IsRegular() && fi.Mode()|0111 == fi.Mode()\n}\n<commit_msg>Small refactor<commit_after>package hookah\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/go-multierror\"\n)\n\n\/\/ HookExec represents a call to a hook\ntype HookExec struct {\n\tRootDir string\n\n\tOwner string\n\tRepo  string\n\n\tEvent string\n\tData  io.ReadSeeker\n\n\tHookServer *HookServer\n}\n\n\/\/ GetPathExecs fetches the executable filenames for the given path\nfunc (h *HookExec) GetPathExecs() ([]string, error) {\n\tpath := filepath.Join(h.RootDir, h.Owner, h.Repo, h.Event)\n\n\tfiles := []string{}\n\n\tfs, err := os.Stat(path)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn files, nil\n\t\t}\n\n\t\treturn files, err\n\t}\n\n\tif fs.IsDir() {\n\t\td, err := os.Open(path)\n\t\tdefer d.Close()\n\t\tif err != nil {\n\t\t\treturn files, err\n\t\t}\n\n\t\tfi, err := d.Readdir(-1)\n\t\tif err != nil {\n\t\t\treturn files, err\n\t\t}\n\n\t\tfor _, fi := range fi {\n\t\t\tif isExecFile(fi) {\n\t\t\t\t\/\/ fmt.Println(fi.Name(), fi.Size(), \"bytes\")\n\t\t\t\tfiles = append(files, filepath.Join(path, fi.Name()))\n\t\t\t}\n\t\t}\n\n\t} else if isExecFile(fs) {\n\t\t\/\/ fmt.Println(fs.Name(), fs.Size(), \"bytes\")\n\t\tfiles = append(files, filepath.Join(path, fs.Name()))\n\t} else {\n\t\treturn files, errors.New(\"bad file mumbo jumbo\")\n\t}\n\n\treturn files, nil\n}\n\n\/\/ Exec triggers the execution of all scripts associated with the given Hook\nfunc (h *HookExec) Exec(timeout time.Duration) error {\n\tfiles, err := h.GetPathExecs()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar result error\n\n\th.HookServer.Lock()\n\tdefer h.HookServer.Unlock()\n\n\tfor _, f := range files {\n\t\terr := execFile(f, h, timeout)\n\t\tmultierror.Append(result, err)\n\t}\n\n\treturn result\n}\n\nfunc execFile(f string, h *HookExec, timeout time.Duration) error {\n\tcmd := exec.Command(f)\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\tstdin, err := cmd.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stdin.Close()\n\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\th.Data.Seek(0, 0)\n\tio.Copy(stdin, h.Data)\n\tstdin.Close()\n\n\ttimer := time.AfterFunc(timeout, func() {\n\t\tcmd.Process.Kill()\n\t})\n\n\terr = cmd.Wait()\n\ttimer.Stop()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ todo: base this on OS\nfunc isExecFile(fi os.FileInfo) bool {\n\treturn fi.Mode().IsRegular() && fi.Mode()|0111 == fi.Mode()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\nvar cmdBase = []string{\"sh\", \"-c\"}\n\nfunc init() {\n\tif runtime.GOOS == \"windows\" {\n\t\tcmdBase = []string{\"cmd\", \"\/c\"}\n\t}\n}\n\nfunc Exec() error {\n\tsh, err := exec.LookPath(cmdBase[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigPath := \"~\/.config\/fillin\/fillin.json\"\n\tcmd, err := Run(configPath, os.Args[1:], nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := syscall.Exec(sh, append(cmdBase, cmd), os.Environ()); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>add comment<commit_after>package main\n\nimport (\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\nvar cmdBase = []string{\"sh\", \"-c\"}\n\nfunc init() {\n\tif runtime.GOOS == \"windows\" {\n\t\tcmdBase = []string{\"cmd\", \"\/c\"}\n\t}\n}\n\n\/\/ Exec fillin\nfunc Exec() error {\n\tsh, err := exec.LookPath(cmdBase[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigPath := \"~\/.config\/fillin\/fillin.json\"\n\tcmd, err := Run(configPath, os.Args[1:], nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := syscall.Exec(sh, append(cmdBase, cmd), os.Environ()); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage mount\n\nimport \"k8s.io\/utils\/exec\"\n\n\/\/ NewOsExec returns a new Exec interface implementation based on exec()\nfunc NewOsExec() Exec {\n\treturn &osExec{}\n}\n\n\/\/ Real implementation of Exec interface that uses simple utils.Exec\ntype osExec struct{}\n\nvar _ Exec = &osExec{}\n\nfunc (e *osExec) Run(cmd string, args ...string) ([]byte, error) {\n\texe := exec.New()\n\treturn exe.Command(cmd, args...).CombinedOutput()\n}\n\n\/\/ NewFakeExec returns a new FakeExec\nfunc NewFakeExec(run runHook) *FakeExec {\n\treturn &FakeExec{runHook: run}\n}\n\n\/\/ FakeExec for testing.\ntype FakeExec struct {\n\trunHook runHook\n}\ntype runHook func(cmd string, args ...string) ([]byte, error)\n\n\/\/ Run executes the command using the optional runhook, if given\nfunc (f *FakeExec) Run(cmd string, args ...string) ([]byte, error) {\n\tif f.runHook != nil {\n\t\treturn f.runHook(cmd, args...)\n\t}\n\treturn nil, nil\n}\n<commit_msg>Rename mount.NewOsExec to mount.NewOSExec<commit_after>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage mount\n\nimport \"k8s.io\/utils\/exec\"\n\n\/\/ NewOSExec returns a new Exec interface implementation based on exec()\nfunc NewOSExec() Exec {\n\treturn &osExec{}\n}\n\n\/\/ Real implementation of Exec interface that uses simple utils.Exec\ntype osExec struct{}\n\nvar _ Exec = &osExec{}\n\nfunc (e *osExec) Run(cmd string, args ...string) ([]byte, error) {\n\texe := exec.New()\n\treturn exe.Command(cmd, args...).CombinedOutput()\n}\n\n\/\/ NewFakeExec returns a new FakeExec\nfunc NewFakeExec(run runHook) *FakeExec {\n\treturn &FakeExec{runHook: run}\n}\n\n\/\/ FakeExec for testing.\ntype FakeExec struct {\n\trunHook runHook\n}\ntype runHook func(cmd string, args ...string) ([]byte, error)\n\n\/\/ Run executes the command using the optional runhook, if given\nfunc (f *FakeExec) Run(cmd string, args ...string) ([]byte, error) {\n\tif f.runHook != nil {\n\t\treturn f.runHook(cmd, args...)\n\t}\n\treturn nil, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package squirrel\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"reflect\"\n\t\"strings\"\n)\n\ntype expr struct {\n\tsql string\n\targs []interface{}\n}\n\n\/\/ Expr builds value expressions for InsertBuilder and UpdateBuilder.\n\/\/\n\/\/ Ex:\n\/\/     .Values(Expr(\"FROM_UNIXTIME(?)\", t))\nfunc Expr(sql string, args ...interface{}) expr {\n\treturn expr{sql: sql, args: args}\n}\n\nfunc (e expr) ToSql() (sql string, args []interface{}, err error) {\n\treturn e.sql, e.args, nil\n}\n\ntype exprs []expr\n\nfunc (es exprs) AppendToSql(w io.Writer, sep string, args []interface{}) ([]interface{}, error) {\n\tfor i, e := range es {\n\t\tif i > 0 {\n\t\t\t_, err := io.WriteString(w, sep)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\t_, err := io.WriteString(w, e.sql)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\targs = append(args, e.args...)\n\t}\n\treturn args, nil\n}\n\n\/\/ Eq is syntactic sugar for use with Where\/Having\/Set methods.\n\/\/ Ex:\n\/\/     .Where(Eq{\"id\": 1})\ntype Eq map[string]interface{}\n\nfunc (eq Eq) ToSql() (sql string, args []interface{}, err error) {\n\tvar exprs []string\n\tfor key, val := range eq {\n\t\texpr := \"\"\n\t\tif val == nil {\n\t\t\texpr = fmt.Sprintf(\"%s IS NULL\", key)\n\t\t} else {\n\t\t\tvalVal := reflect.ValueOf(val)\n\t\t\tif valVal.Kind() == reflect.Array || valVal.Kind() == reflect.Slice {\n\t\t\t\tplaceholders := make([]string, valVal.Len())\n\t\t\t\tfor i := 0; i < valVal.Len(); i++ {\n\t\t\t\t\tplaceholders[i] = \"?\"\n\t\t\t\t\targs = append(args, valVal.Index(i).Interface())\n\t\t\t\t}\n\t\t\t\tplaceholdersStr := strings.Join(placeholders, \",\")\n\t\t\t\texpr = fmt.Sprintf(\"%s IN (%s)\", key, placeholdersStr)\n\t\t\t} else {\n\t\t\t\texpr = fmt.Sprintf(\"%s = ?\", key)\n\t\t\t\targs = append(args, val)\n\t\t\t}\n\t\t}\n\t\texprs = append(exprs, expr)\n\t}\n\tsql = strings.Join(exprs, \" AND \")\n\treturn\n}\n\ntype conj []Sqlizer\n\nfunc (c conj) join(sep string) (sql string, args []interface{}, err error) {\n\tsqlParts := make([]string, len(c))\n\tfor i, sqlizer := range c {\n\t\tpartSql, partArgs, err := sqlizer.ToSql()\n\t\tif err != nil {\n\t\t\treturn \"\", nil, err\n\t\t}\n\t\tsqlParts[i] = partSql\n\t\targs = append(args, partArgs...)\n\t}\n\tsql = fmt.Sprintf(\"(%s)\", strings.Join(sqlParts, sep))\n\treturn\n}\n\ntype And conj\n\nfunc (a And) ToSql() (string, []interface{}, error) {\n\treturn conj(a).join(\" AND \")\n}\n\ntype Or conj\n\nfunc (o Or) ToSql() (string, []interface{}, error) {\n\treturn conj(o).join(\" OR \")\n}\n<commit_msg>Omit empty expressions from Or{} and And{}<commit_after>package squirrel\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"reflect\"\n\t\"strings\"\n)\n\ntype expr struct {\n\tsql string\n\targs []interface{}\n}\n\n\/\/ Expr builds value expressions for InsertBuilder and UpdateBuilder.\n\/\/\n\/\/ Ex:\n\/\/     .Values(Expr(\"FROM_UNIXTIME(?)\", t))\nfunc Expr(sql string, args ...interface{}) expr {\n\treturn expr{sql: sql, args: args}\n}\n\nfunc (e expr) ToSql() (sql string, args []interface{}, err error) {\n\treturn e.sql, e.args, nil\n}\n\ntype exprs []expr\n\nfunc (es exprs) AppendToSql(w io.Writer, sep string, args []interface{}) ([]interface{}, error) {\n\tfor i, e := range es {\n\t\tif i > 0 {\n\t\t\t_, err := io.WriteString(w, sep)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\t_, err := io.WriteString(w, e.sql)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\targs = append(args, e.args...)\n\t}\n\treturn args, nil\n}\n\n\/\/ Eq is syntactic sugar for use with Where\/Having\/Set methods.\n\/\/ Ex:\n\/\/     .Where(Eq{\"id\": 1})\ntype Eq map[string]interface{}\n\nfunc (eq Eq) ToSql() (sql string, args []interface{}, err error) {\n\tvar exprs []string\n\tfor key, val := range eq {\n\t\texpr := \"\"\n\t\tif val == nil {\n\t\t\texpr = fmt.Sprintf(\"%s IS NULL\", key)\n\t\t} else {\n\t\t\tvalVal := reflect.ValueOf(val)\n\t\t\tif valVal.Kind() == reflect.Array || valVal.Kind() == reflect.Slice {\n\t\t\t\tplaceholders := make([]string, valVal.Len())\n\t\t\t\tfor i := 0; i < valVal.Len(); i++ {\n\t\t\t\t\tplaceholders[i] = \"?\"\n\t\t\t\t\targs = append(args, valVal.Index(i).Interface())\n\t\t\t\t}\n\t\t\t\tplaceholdersStr := strings.Join(placeholders, \",\")\n\t\t\t\texpr = fmt.Sprintf(\"%s IN (%s)\", key, placeholdersStr)\n\t\t\t} else {\n\t\t\t\texpr = fmt.Sprintf(\"%s = ?\", key)\n\t\t\t\targs = append(args, val)\n\t\t\t}\n\t\t}\n\t\texprs = append(exprs, expr)\n\t}\n\tsql = strings.Join(exprs, \" AND \")\n\treturn\n}\n\ntype conj []Sqlizer\n\nfunc (c conj) join(sep string) (sql string, args []interface{}, err error) {\n\tvar sqlParts []string\n\tfor _, sqlizer := range c {\n\t\tpartSql, partArgs, err := sqlizer.ToSql()\n\t\tif err != nil {\n\t\t\treturn \"\", nil, err\n\t\t}\n\t\tif partSql != \"\" {\n\t\t\tsqlParts = append(sqlParts, partSql)\n\t\t\targs = append(args, partArgs...)\n\t\t}\n\t}\n\tif len(sqlParts) > 0 {\n\t\tsql = fmt.Sprintf(\"(%s)\", strings.Join(sqlParts, sep))\n\t}\n\treturn\n}\n\ntype And conj\n\nfunc (a And) ToSql() (string, []interface{}, error) {\n\treturn conj(a).join(\" AND \")\n}\n\ntype Or conj\n\nfunc (o Or) ToSql() (string, []interface{}, error) {\n\treturn conj(o).join(\" OR \")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/  Copyright (c) 2014 Couchbase, Inc.\n\/\/  Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/  you may not use this file except in compliance with the\n\/\/  License. You may obtain a copy of the License at\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/  Unless required by applicable law or agreed to in writing,\n\/\/  software distributed under the License is distributed on an \"AS\n\/\/  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n\/\/  express or implied. See the License for the specific language\n\/\/  governing permissions and limitations under the License.\n\npackage cbgt\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\/\/ A Feed interface represents an abstract data source.  A Feed\n\/\/ instance is hooked up to one-or-more Dest instances.  When incoming\n\/\/ data is received by a Feed, the Feed will invoke relvate methods on\n\/\/ the relevant Dest instances.\n\/\/\n\/\/ In this codebase, the words \"index source\", \"source\" and \"data\n\/\/ source\" are often associated with and used roughly as synonyms with\n\/\/ \"feed\".\ntype Feed interface {\n\tName() string\n\tIndexName() string\n\tStart() error\n\tClose() error\n\tDests() map[string]Dest \/\/ Key is partition identifier.\n\n\t\/\/ Writes stats as JSON to the given writer.\n\tStats(io.Writer) error\n}\n\n\/\/ Default values for feed parameters.\nconst FEED_SLEEP_MAX_MS = 10000\nconst FEED_SLEEP_INIT_MS = 100\nconst FEED_BACKOFF_FACTOR = 1.5\n\n\/\/ FeedTypes is a global registry of available feed types and is\n\/\/ initialized on startup.  It should be immutable after startup time.\nvar FeedTypes = make(map[string]*FeedType) \/\/ Key is sourceType.\n\n\/\/ A FeedType represents an immutable registration of a single feed\n\/\/ type or data source type.\ntype FeedType struct {\n\tStart           FeedStartFunc\n\tPartitions      FeedPartitionsFunc\n\tPublic          bool\n\tDescription     string\n\tStartSample     interface{}\n\tStartSampleDocs map[string]string\n}\n\n\/\/ A FeedStartFunc is part of a FeedType registration as is invoked by\n\/\/ a Manager when a new feed instance needs to be started.\ntype FeedStartFunc func(mgr *Manager, feedName, indexName, indexUUID string,\n\tsourceType, sourceName, sourceUUID, sourceParams string,\n\tdests map[string]Dest) error\n\n\/\/ Each Feed or data-source type knows of the data partitions for a\n\/\/ data source.\ntype FeedPartitionsFunc func(sourceType, sourceName, sourceUUID, sourceParams,\n\tserver string) ([]string, error)\n\n\/\/ RegisterFeedType is invoked at init\/startup time to register a\n\/\/ FeedType.\nfunc RegisterFeedType(sourceType string, f *FeedType) {\n\tFeedTypes[sourceType] = f\n}\n\n\/\/ DataSourcePartitions is a helper function that returns the data\n\/\/ source partitions for a named data source or feed type.\nfunc DataSourcePartitions(sourceType, sourceName, sourceUUID, sourceParams,\n\tserver string) ([]string, error) {\n\tfeedType, exists := FeedTypes[sourceType]\n\tif !exists || feedType == nil {\n\t\treturn nil, fmt.Errorf(\"feed: unknown sourceType: %s\", sourceType)\n\t}\n\n\treturn feedType.Partitions(sourceType, sourceName, sourceUUID,\n\t\tsourceParams, server)\n}\n<commit_msg>added FeedPartitionSeqsFunc to FeedType<commit_after>\/\/  Copyright (c) 2014 Couchbase, Inc.\n\/\/  Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/  you may not use this file except in compliance with the\n\/\/  License. You may obtain a copy of the License at\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/  Unless required by applicable law or agreed to in writing,\n\/\/  software distributed under the License is distributed on an \"AS\n\/\/  IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n\/\/  express or implied. See the License for the specific language\n\/\/  governing permissions and limitations under the License.\n\npackage cbgt\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\/\/ A Feed interface represents an abstract data source.  A Feed\n\/\/ instance is hooked up to one-or-more Dest instances.  When incoming\n\/\/ data is received by a Feed, the Feed will invoke relvate methods on\n\/\/ the relevant Dest instances.\n\/\/\n\/\/ In this codebase, the words \"index source\", \"source\" and \"data\n\/\/ source\" are often associated with and used roughly as synonyms with\n\/\/ \"feed\".\ntype Feed interface {\n\tName() string\n\tIndexName() string\n\tStart() error\n\tClose() error\n\tDests() map[string]Dest \/\/ Key is partition identifier.\n\n\t\/\/ Writes stats as JSON to the given writer.\n\tStats(io.Writer) error\n}\n\n\/\/ Default values for feed parameters.\nconst FEED_SLEEP_MAX_MS = 10000\nconst FEED_SLEEP_INIT_MS = 100\nconst FEED_BACKOFF_FACTOR = 1.5\n\n\/\/ FeedTypes is a global registry of available feed types and is\n\/\/ initialized on startup.  It should be immutable after startup time.\nvar FeedTypes = make(map[string]*FeedType) \/\/ Key is sourceType.\n\n\/\/ A FeedType represents an immutable registration of a single feed\n\/\/ type or data source type.\ntype FeedType struct {\n\tStart           FeedStartFunc\n\tPartitions      FeedPartitionsFunc\n\tPartitionSeqs   FeedPartitionSeqsFunc\n\tPublic          bool\n\tDescription     string\n\tStartSample     interface{}\n\tStartSampleDocs map[string]string\n}\n\n\/\/ A FeedStartFunc is part of a FeedType registration as is invoked by\n\/\/ a Manager when a new feed instance needs to be started.\ntype FeedStartFunc func(mgr *Manager,\n\tfeedName, indexName, indexUUID string,\n\tsourceType, sourceName, sourceUUID, sourceParams string,\n\tdests map[string]Dest) error\n\n\/\/ Each Feed or data-source type knows of the data partitions for a\n\/\/ data source.\ntype FeedPartitionsFunc func(sourceType, sourceName, sourceUUID,\n\tsourceParams, server string) ([]string, error)\n\n\/\/ Returns the current partitions and their seq's.\ntype FeedPartitionSeqsFunc func(sourceType, sourceName, sourceUUID,\n\tsourceParams, server string) (map[string]UUIDSeq, error)\n\n\/\/ A UUIDSeq associates a uuid (such as a partition uuid) with a seq.\ntype UUIDSeq struct {\n\tUUID string\n\tSeq  uint64\n}\n\n\/\/ RegisterFeedType is invoked at init\/startup time to register a\n\/\/ FeedType.\nfunc RegisterFeedType(sourceType string, f *FeedType) {\n\tFeedTypes[sourceType] = f\n}\n\n\/\/ DataSourcePartitions is a helper function that returns the data\n\/\/ source partitions for a named data source or feed type.\nfunc DataSourcePartitions(sourceType, sourceName, sourceUUID, sourceParams,\n\tserver string) ([]string, error) {\n\tfeedType, exists := FeedTypes[sourceType]\n\tif !exists || feedType == nil {\n\t\treturn nil, fmt.Errorf(\"feed: unknown sourceType: %s\", sourceType)\n\t}\n\n\treturn feedType.Partitions(sourceType, sourceName, sourceUUID,\n\t\tsourceParams, server)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"archive\/zip\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/ Download the zip file at the given URL to a temporary local directory.\n\/\/ Returns the absolute path to the downloaded zip file.\n\/\/ IMPORTANT: You must call \"defer os.RemoveAll(dir)\" in the calling function when done with the downloaded zip file!\nfunc downloadGithubZipFile(gitHubCommit GitHubCommit, gitHubToken string, instance GitHubInstance) (string, *FetchError) {\n\n\tvar zipFilePath string\n\n\t\/\/ Create a temp directory\n\t\/\/ Note that ioutil.TempDir has a peculiar interface. We need not specify any meaningful values to achieve our\n\t\/\/ goal of getting a temporary directory.\n\ttempDir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\treturn zipFilePath, wrapError(err)\n\t}\n\n\t\/\/ Download the zip file, possibly using the GitHub oAuth Token\n\thttpClient := &http.Client{}\n\treq, err := MakeGitHubZipFileRequest(gitHubCommit, gitHubToken, instance)\n\tif err != nil {\n\t\treturn zipFilePath, wrapError(err)\n\t}\n\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn zipFilePath, wrapError(err)\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn zipFilePath, newError(failedToDownloadFile, fmt.Sprintf(\"Failed to download file at the url %s. Received HTTP Response %d.\", req.URL.String(), resp.StatusCode))\n\t}\n\tif resp.Header.Get(\"Content-Type\") != \"application\/zip\" {\n\t\treturn zipFilePath, newError(failedToDownloadFile, fmt.Sprintf(\"Failed to download file at the url %s. Expected HTTP Response's \\\"Content-Type\\\" header to be \\\"application\/zip\\\", but was \\\"%s\\\"\", req.URL.String(), resp.Header.Get(\"Content-Type\")))\n\t}\n\n\t\/\/ Copy the contents of the downloaded file to our empty file\n\trespBodyBuffer := new(bytes.Buffer)\n\t_, err = respBodyBuffer.ReadFrom(resp.Body)\n\tif err != nil {\n\t\treturn zipFilePath, wrapError(err)\n\t}\n\n\terr = ioutil.WriteFile(filepath.Join(tempDir, \"repo.zip\"), respBodyBuffer.Bytes(), 0644)\n\tif err != nil {\n\t\treturn zipFilePath, wrapError(err)\n\t}\n\n\tzipFilePath = filepath.Join(tempDir, \"repo.zip\")\n\n\treturn zipFilePath, nil\n}\n\nfunc shouldExtractPathInZip(pathPrefix string, zipPath *zip.File) bool {\n\t\/\/\n\t\/\/ We need to return true (i.e extract file) based on the following conditions:\n\t\/\/\n\t\/\/ The current archive item is a directory.\n\t\/\/     Archive item's path name will always be appended with a \"\/\", so we use\n\t\/\/     this fact to ensure we are working with a full directory name.\n\t\/\/     Extract the file if (pathPrefix + \"\/\") is a prefix in path name\n\t\/\/\n\t\/\/ The current archive item is a file.\n\t\/\/ \t\tThere are two things possible here:\n\t\/\/\t\t1  User specified a filename that is an exact match for the current archive file,\n\t\/\/         we need to extract this file.\n\t\/\/      2  The current archive filename is not a exact match to the user supplied filename.\n\t\/\/\t\t   Check if (pathPrefix + \"\/\") is a prefix in f.Name, if yes, we extract this file.\n\n\tzipPathIsFile := !zipPath.FileInfo().IsDir()\n\treturn (zipPathIsFile && zipPath.Name == pathPrefix) || strings.Index(zipPath.Name, pathPrefix+\"\/\") == 0\n}\n\n\/\/ Decompress the file at zipFileAbsPath and move only those files under filesToExtractFromZipPath to localPath\nfunc extractFiles(zipFilePath, filesToExtractFromZipPath, localPath string) (int, error) {\n\n\t\/\/ Open the zip file for reading.\n\tr, err := zip.OpenReader(zipFilePath)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer r.Close()\n\n\t\/\/ pathPrefix represents the portion of the local file path we will ignore when copying the file to localPath\n\t\/\/ E.g. full path = fetch-test-public-0.0.3\/folder\/file1.txt\n\t\/\/      path prefix = fetch-test-public-0.0.3\n\t\/\/      file that will eventually get written = <localPath>\/folder\/file1.txt\n\n\t\/\/ By convention, the first file in the zip file is the top-level directory\n\tpathPrefix := r.File[0].Name\n\n\t\/\/ Add the path from which we will extract files to the path prefix so we can exclude the appropriate files\n\tpathPrefix = filepath.Join(pathPrefix, filesToExtractFromZipPath)\n\n\t\/\/ Count the number of files (not directories) unpacked\n\tfileCount := 0\n\n\t\/\/ Iterate through the files in the archive,\n\t\/\/ printing some of their contents.\n\tfor _, f := range r.File {\n\n\t\t\/\/ check if current archive file needs to be extracted\n\t\tif shouldExtractPathInZip(pathPrefix, f) {\n\n\t\t\tif f.FileInfo().IsDir() {\n\t\t\t\t\/\/ Create a directory\n\t\t\t\tpath := filepath.Join(localPath, strings.TrimPrefix(f.Name, pathPrefix))\n\t\t\t\terr = os.MkdirAll(path, 0777)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"Failed to create local directory %s: %s\", path, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Read the file into a byte array\n\t\t\t\treadCloser, err := f.Open()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"Failed to open file %s: %s\", f.Name, err)\n\t\t\t\t}\n\n\t\t\t\tbyteArray, err := ioutil.ReadAll(readCloser)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"Failed to read file %s: %s\", f.Name, err)\n\t\t\t\t}\n\n\t\t\t\t\/\/ Write the file\n\t\t\t\terr = ioutil.WriteFile(filepath.Join(localPath, strings.TrimPrefix(f.Name, pathPrefix)), byteArray, 0644)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, fmt.Errorf(\"Failed to write file: %s\", err)\n\t\t\t\t}\n\t\t\t\tfileCount++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn fileCount, nil\n}\n\n\/\/ Return an HTTP request that will fetch the given GitHub repo's zip file for the given tag, possibly with the gitHubOAuthToken in the header\n\/\/ Respects the GitHubCommit hierachy as defined in the code comments for GitHubCommit (e.g. GitTag > CommitSha)\nfunc MakeGitHubZipFileRequest(gitHubCommit GitHubCommit, gitHubToken string, instance GitHubInstance) (*http.Request, error) {\n\tvar request *http.Request\n\n\t\/\/ This represents either a commit, branch, or git tag\n\tvar gitRef string\n\tif gitHubCommit.CommitSha != \"\" {\n\t\tgitRef = gitHubCommit.CommitSha\n\t} else if gitHubCommit.BranchName != \"\" {\n\t\tgitRef = gitHubCommit.BranchName\n\t} else if gitHubCommit.GitTag != \"\" {\n\t\tgitRef = gitHubCommit.GitTag\n\t} else {\n\t\treturn request, fmt.Errorf(\"Neither a GitCommitSha nor a GitTag nor a BranchName were specified so impossible to identify a specific commit to download.\")\n\t}\n\n\turl := fmt.Sprintf(\"https:\/\/%s\/repos\/%s\/%s\/zipball\/%s\", instance.ApiUrl, gitHubCommit.Repo.Owner, gitHubCommit.Repo.Name, gitRef)\n\n\trequest, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn request, wrapError(err)\n\t}\n\n\tif gitHubToken != \"\" {\n\t\trequest.Header.Set(\"Authorization\", fmt.Sprintf(\"token %s\", gitHubToken))\n\t}\n\n\treturn request, nil\n}\n<commit_msg>Return number of files in all cases<commit_after>package main\n\nimport (\n\t\"archive\/zip\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/ Download the zip file at the given URL to a temporary local directory.\n\/\/ Returns the absolute path to the downloaded zip file.\n\/\/ IMPORTANT: You must call \"defer os.RemoveAll(dir)\" in the calling function when done with the downloaded zip file!\nfunc downloadGithubZipFile(gitHubCommit GitHubCommit, gitHubToken string, instance GitHubInstance) (string, *FetchError) {\n\n\tvar zipFilePath string\n\n\t\/\/ Create a temp directory\n\t\/\/ Note that ioutil.TempDir has a peculiar interface. We need not specify any meaningful values to achieve our\n\t\/\/ goal of getting a temporary directory.\n\ttempDir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\treturn zipFilePath, wrapError(err)\n\t}\n\n\t\/\/ Download the zip file, possibly using the GitHub oAuth Token\n\thttpClient := &http.Client{}\n\treq, err := MakeGitHubZipFileRequest(gitHubCommit, gitHubToken, instance)\n\tif err != nil {\n\t\treturn zipFilePath, wrapError(err)\n\t}\n\n\tresp, err := httpClient.Do(req)\n\tif err != nil {\n\t\treturn zipFilePath, wrapError(err)\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn zipFilePath, newError(failedToDownloadFile, fmt.Sprintf(\"Failed to download file at the url %s. Received HTTP Response %d.\", req.URL.String(), resp.StatusCode))\n\t}\n\tif resp.Header.Get(\"Content-Type\") != \"application\/zip\" {\n\t\treturn zipFilePath, newError(failedToDownloadFile, fmt.Sprintf(\"Failed to download file at the url %s. Expected HTTP Response's \\\"Content-Type\\\" header to be \\\"application\/zip\\\", but was \\\"%s\\\"\", req.URL.String(), resp.Header.Get(\"Content-Type\")))\n\t}\n\n\t\/\/ Copy the contents of the downloaded file to our empty file\n\trespBodyBuffer := new(bytes.Buffer)\n\t_, err = respBodyBuffer.ReadFrom(resp.Body)\n\tif err != nil {\n\t\treturn zipFilePath, wrapError(err)\n\t}\n\n\terr = ioutil.WriteFile(filepath.Join(tempDir, \"repo.zip\"), respBodyBuffer.Bytes(), 0644)\n\tif err != nil {\n\t\treturn zipFilePath, wrapError(err)\n\t}\n\n\tzipFilePath = filepath.Join(tempDir, \"repo.zip\")\n\n\treturn zipFilePath, nil\n}\n\nfunc shouldExtractPathInZip(pathPrefix string, zipPath *zip.File) bool {\n\t\/\/\n\t\/\/ We need to return true (i.e extract file) based on the following conditions:\n\t\/\/\n\t\/\/ The current archive item is a directory.\n\t\/\/     Archive item's path name will always be appended with a \"\/\", so we use\n\t\/\/     this fact to ensure we are working with a full directory name.\n\t\/\/     Extract the file if (pathPrefix + \"\/\") is a prefix in path name\n\t\/\/\n\t\/\/ The current archive item is a file.\n\t\/\/ \t\tThere are two things possible here:\n\t\/\/\t\t1  User specified a filename that is an exact match for the current archive file,\n\t\/\/         we need to extract this file.\n\t\/\/      2  The current archive filename is not a exact match to the user supplied filename.\n\t\/\/\t\t   Check if (pathPrefix + \"\/\") is a prefix in f.Name, if yes, we extract this file.\n\n\tzipPathIsFile := !zipPath.FileInfo().IsDir()\n\treturn (zipPathIsFile && zipPath.Name == pathPrefix) || strings.Index(zipPath.Name, pathPrefix+\"\/\") == 0\n}\n\n\/\/ Decompress the file at zipFileAbsPath and move only those files under filesToExtractFromZipPath to localPath\nfunc extractFiles(zipFilePath, filesToExtractFromZipPath, localPath string) (int, error) {\n\n\t\/\/ Open the zip file for reading.\n\tr, err := zip.OpenReader(zipFilePath)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer r.Close()\n\n\t\/\/ pathPrefix represents the portion of the local file path we will ignore when copying the file to localPath\n\t\/\/ E.g. full path = fetch-test-public-0.0.3\/folder\/file1.txt\n\t\/\/      path prefix = fetch-test-public-0.0.3\n\t\/\/      file that will eventually get written = <localPath>\/folder\/file1.txt\n\n\t\/\/ By convention, the first file in the zip file is the top-level directory\n\tpathPrefix := r.File[0].Name\n\n\t\/\/ Add the path from which we will extract files to the path prefix so we can exclude the appropriate files\n\tpathPrefix = filepath.Join(pathPrefix, filesToExtractFromZipPath)\n\n\t\/\/ Count the number of files (not directories) unpacked\n\tfileCount := 0\n\n\t\/\/ Iterate through the files in the archive,\n\t\/\/ printing some of their contents.\n\tfor _, f := range r.File {\n\n\t\t\/\/ check if current archive file needs to be extracted\n\t\tif shouldExtractPathInZip(pathPrefix, f) {\n\n\t\t\tif f.FileInfo().IsDir() {\n\t\t\t\t\/\/ Create a directory\n\t\t\t\tpath := filepath.Join(localPath, strings.TrimPrefix(f.Name, pathPrefix))\n\t\t\t\terr = os.MkdirAll(path, 0777)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fileCount, fmt.Errorf(\"Failed to create local directory %s: %s\", path, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ Read the file into a byte array\n\t\t\t\treadCloser, err := f.Open()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fileCount, fmt.Errorf(\"Failed to open file %s: %s\", f.Name, err)\n\t\t\t\t}\n\n\t\t\t\tbyteArray, err := ioutil.ReadAll(readCloser)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fileCount, fmt.Errorf(\"Failed to read file %s: %s\", f.Name, err)\n\t\t\t\t}\n\n\t\t\t\t\/\/ Write the file\n\t\t\t\terr = ioutil.WriteFile(filepath.Join(localPath, strings.TrimPrefix(f.Name, pathPrefix)), byteArray, 0644)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fileCount, fmt.Errorf(\"Failed to write file: %s\", err)\n\t\t\t\t}\n\t\t\t\tfileCount++\n\t\t\t}\n\t\t}\n\t}\n\n\treturn fileCount, nil\n}\n\n\/\/ Return an HTTP request that will fetch the given GitHub repo's zip file for the given tag, possibly with the gitHubOAuthToken in the header\n\/\/ Respects the GitHubCommit hierachy as defined in the code comments for GitHubCommit (e.g. GitTag > CommitSha)\nfunc MakeGitHubZipFileRequest(gitHubCommit GitHubCommit, gitHubToken string, instance GitHubInstance) (*http.Request, error) {\n\tvar request *http.Request\n\n\t\/\/ This represents either a commit, branch, or git tag\n\tvar gitRef string\n\tif gitHubCommit.CommitSha != \"\" {\n\t\tgitRef = gitHubCommit.CommitSha\n\t} else if gitHubCommit.BranchName != \"\" {\n\t\tgitRef = gitHubCommit.BranchName\n\t} else if gitHubCommit.GitTag != \"\" {\n\t\tgitRef = gitHubCommit.GitTag\n\t} else {\n\t\treturn request, fmt.Errorf(\"Neither a GitCommitSha nor a GitTag nor a BranchName were specified so impossible to identify a specific commit to download.\")\n\t}\n\n\turl := fmt.Sprintf(\"https:\/\/%s\/repos\/%s\/%s\/zipball\/%s\", instance.ApiUrl, gitHubCommit.Repo.Owner, gitHubCommit.Repo.Name, gitRef)\n\n\trequest, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn request, wrapError(err)\n\t}\n\n\tif gitHubToken != \"\" {\n\t\trequest.Header.Set(\"Authorization\", fmt.Sprintf(\"token %s\", gitHubToken))\n\t}\n\n\treturn request, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package bongo\n\nimport (\n\t\"github.com\/maxwellhealth\/mgo\"\n\t\"log\"\n\t\"math\"\n\t\"time\"\n)\n\ntype ResultSet struct {\n\tQuery      *mgo.Query\n\tIter       *mgo.Iter\n\tloadedIter bool\n\tCollection *Collection\n\tError      error\n\tParams     interface{}\n}\n\ntype PaginationInfo struct {\n\tCurrent       int `json:\"current\"`\n\tTotalPages    int `json:\"totalPages\"`\n\tPerPage       int `json:\"perPage\"`\n\tTotalRecords  int `json:\"totalRecords\"`\n\tRecordsOnPage int `json:\"recordsOnPage\"`\n}\n\nfunc (r *ResultSet) Next(mod interface{}) bool {\n\n\t\/\/ Check if the iter has been instantiated yet\n\tif !r.loadedIter {\n\t\tr.Iter = r.Query.Iter()\n\t\tr.loadedIter = true\n\t}\n\n\tgotResult := r.Iter.Next(mod)\n\n\tif gotResult {\n\n\t\tif hook, ok := mod.(interface {\n\t\t\tAfterFind(*Collection)\n\t\t}); ok {\n\t\t\thook.AfterFind(r.Collection)\n\t\t}\n\n\t\tif newt, ok := mod.(NewTracker); ok {\n\t\t\tnewt.SetIsNew(false)\n\t\t}\n\t\treturn true\n\t}\n\n\terr := r.Iter.Err()\n\tif err != nil {\n\t\tr.Error = err\n\t}\n\n\treturn false\n}\n\nfunc (r *ResultSet) Free() error {\n\tif r.loadedIter {\n\t\tif err := r.Iter.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Set skip + limit on the current query and generates a PaginationInfo struct with info for your front end\nfunc (r *ResultSet) Paginate(perPage, page int) (*PaginationInfo, error) {\n\tstart := time.Now()\n\telapsed := time.Since(start)\n\n\tlog.Printf(\"Line 74: %s\", elapsed)\n\tinfo := new(PaginationInfo)\n\n\t\/\/ Get count of current query\n\t\/\/ count, err := r.Query.Count()\n\n\tsess := r.Collection.Connection.Session.Copy()\n\tdefer sess.Close()\n\n\telapsed = time.Since(start)\n\n\tlog.Printf(\"Line 85: %s\", elapsed)\n\tcount, err := sess.DB(r.Collection.Connection.Config.Database).C(r.Collection.Name).Find(r.Params).Count()\n\t\/\/ count, err := r.Collection.Collection().Count()\n\n\tif err != nil {\n\t\treturn info, err\n\t}\n\n\telapsed = time.Since(start)\n\n\tlog.Printf(\"Line 95: %s\", elapsed)\n\n\t\/\/ Calculate how many pages\n\ttotalPages := int(math.Ceil(float64(count) \/ float64(perPage)))\n\n\tif page < 1 {\n\t\tpage = 1\n\t} else if page > totalPages {\n\t\tpage = totalPages\n\t}\n\n\telapsed = time.Since(start)\n\n\tlog.Printf(\"Line 108: %s\", elapsed)\n\n\tskip := (page - 1) * perPage\n\n\tr.Query.Skip(skip).Limit(perPage)\n\n\tinfo.TotalPages = totalPages\n\tinfo.PerPage = perPage\n\tinfo.Current = page\n\tinfo.TotalRecords = count\n\n\tif info.Current < info.TotalPages {\n\t\tinfo.RecordsOnPage = info.PerPage\n\t} else {\n\n\t\tinfo.RecordsOnPage = int(math.Mod(float64(count), float64(perPage)))\n\n\t\tif info.RecordsOnPage == 0 && count > 0 {\n\t\t\tinfo.RecordsOnPage = perPage\n\t\t}\n\n\t}\n\n\telapsed = time.Since(start)\n\n\tlog.Printf(\"Line 133: %s\", elapsed)\n\n\treturn info, nil\n}\n<commit_msg>Took out logging<commit_after>package bongo\n\nimport (\n\t\"github.com\/maxwellhealth\/mgo\"\n\t\"math\"\n)\n\ntype ResultSet struct {\n\tQuery      *mgo.Query\n\tIter       *mgo.Iter\n\tloadedIter bool\n\tCollection *Collection\n\tError      error\n\tParams     interface{}\n}\n\ntype PaginationInfo struct {\n\tCurrent       int `json:\"current\"`\n\tTotalPages    int `json:\"totalPages\"`\n\tPerPage       int `json:\"perPage\"`\n\tTotalRecords  int `json:\"totalRecords\"`\n\tRecordsOnPage int `json:\"recordsOnPage\"`\n}\n\nfunc (r *ResultSet) Next(mod interface{}) bool {\n\n\t\/\/ Check if the iter has been instantiated yet\n\tif !r.loadedIter {\n\t\tr.Iter = r.Query.Iter()\n\t\tr.loadedIter = true\n\t}\n\n\tgotResult := r.Iter.Next(mod)\n\n\tif gotResult {\n\n\t\tif hook, ok := mod.(interface {\n\t\t\tAfterFind(*Collection)\n\t\t}); ok {\n\t\t\thook.AfterFind(r.Collection)\n\t\t}\n\n\t\tif newt, ok := mod.(NewTracker); ok {\n\t\t\tnewt.SetIsNew(false)\n\t\t}\n\t\treturn true\n\t}\n\n\terr := r.Iter.Err()\n\tif err != nil {\n\t\tr.Error = err\n\t}\n\n\treturn false\n}\n\nfunc (r *ResultSet) Free() error {\n\tif r.loadedIter {\n\t\tif err := r.Iter.Close(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Set skip + limit on the current query and generates a PaginationInfo struct with info for your front end\nfunc (r *ResultSet) Paginate(perPage, page int) (*PaginationInfo, error) {\n\n\tinfo := new(PaginationInfo)\n\n\t\/\/ Get count of current query\n\t\/\/ count, err := r.Query.Count()\n\n\tsess := r.Collection.Connection.Session.Copy()\n\tdefer sess.Close()\n\n\tcount, err := sess.DB(r.Collection.Connection.Config.Database).C(r.Collection.Name).Find(r.Params).Count()\n\t\/\/ count, err := r.Collection.Collection().Count()\n\n\tif err != nil {\n\t\treturn info, err\n\t}\n\n\t\/\/ Calculate how many pages\n\ttotalPages := int(math.Ceil(float64(count) \/ float64(perPage)))\n\n\tif page < 1 {\n\t\tpage = 1\n\t} else if page > totalPages {\n\t\tpage = totalPages\n\t}\n\n\tskip := (page - 1) * perPage\n\n\tr.Query.Skip(skip).Limit(perPage)\n\n\tinfo.TotalPages = totalPages\n\tinfo.PerPage = perPage\n\tinfo.Current = page\n\tinfo.TotalRecords = count\n\n\tif info.Current < info.TotalPages {\n\t\tinfo.RecordsOnPage = info.PerPage\n\t} else {\n\n\t\tinfo.RecordsOnPage = int(math.Mod(float64(count), float64(perPage)))\n\n\t\tif info.RecordsOnPage == 0 && count > 0 {\n\t\t\tinfo.RecordsOnPage = perPage\n\t\t}\n\n\t}\n\n\treturn info, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ This flag enables bash-completion for all commands and subcommands\nvar BashCompletionFlag = BoolFlag{\"generate-bash-completion\", \"\"}\n\n\/\/ This flag prints the version for the application\nvar VersionFlag = BoolFlag{\"version, v\", \"print the version\"}\n\n\/\/ This flag prints the help for all commands and subcommands\nvar HelpFlag = BoolFlag{\"help, h\", \"show help\"}\n\n\/\/ Flag is a common interface related to parsing flags in cli.\n\/\/ For more advanced flag parsing techniques, it is recomended that\n\/\/ this interface be implemented.\ntype Flag interface {\n\tfmt.Stringer\n\t\/\/ Apply Flag settings to the given flag set\n\tApply(*flag.FlagSet)\n\tgetName() string\n}\n\nfunc flagSet(name string, flags []Flag) *flag.FlagSet {\n\tset := flag.NewFlagSet(name, flag.ContinueOnError)\n\n\tfor _, f := range flags {\n\t\tf.Apply(set)\n\t}\n\treturn set\n}\n\nfunc eachName(longName string, fn func(string)) {\n\tparts := strings.Split(longName, \",\")\n\tfor _, name := range parts {\n\t\tname = strings.Trim(name, \" \")\n\t\tfn(name)\n\t}\n}\n\n\/\/ Generic is a generic parseable type identified by a specific flag\ntype Generic interface {\n\tSet(value string) error\n\tString() string\n}\n\n\/\/ GenericFlag is the flag type for types implementing Generic\ntype GenericFlag struct {\n\tName  string\n\tValue Generic\n\tUsage string\n}\n\nfunc (f GenericFlag) String() string {\n\treturn fmt.Sprintf(\"%s%s %v\\t`%v` %s\", prefixFor(f.Name), f.Name, f.Value, \"-\"+f.Name+\" option -\"+f.Name+\" option\", f.Usage)\n}\n\nfunc (f GenericFlag) Apply(set *flag.FlagSet) {\n\teachName(f.Name, func(name string) {\n\t\tset.Var(f.Value, name, f.Usage)\n\t})\n}\n\nfunc (f GenericFlag) getName() string {\n\treturn f.Name\n}\n\ntype StringSlice []string\n\nfunc (f *StringSlice) Set(value string) error {\n\t*f = append(*f, value)\n\treturn nil\n}\n\nfunc (f *StringSlice) String() string {\n\treturn fmt.Sprintf(\"%s\", *f)\n}\n\nfunc (f *StringSlice) Value() []string {\n\treturn *f\n}\n\ntype StringSliceFlag struct {\n\tName  string\n\tValue *StringSlice\n\tUsage string\n}\n\nfunc (f StringSliceFlag) String() string {\n\tfirstName := strings.Trim(strings.Split(f.Name, \",\")[0], \" \")\n\tpref := prefixFor(firstName)\n\treturn fmt.Sprintf(\"%s '%v'\\t%v\", prefixedNames(f.Name), pref+firstName+\" option \"+pref+firstName+\" option\", f.Usage)\n}\n\nfunc (f StringSliceFlag) Apply(set *flag.FlagSet) {\n\teachName(f.Name, func(name string) {\n\t\tset.Var(f.Value, name, f.Usage)\n\t})\n}\n\nfunc (f StringSliceFlag) getName() string {\n\treturn f.Name\n}\n\ntype IntSlice []int\n\nfunc (f *IntSlice) Set(value string) error {\n\n\ttmp, err := strconv.Atoi(value)\n\tif err != nil {\n\t\treturn err\n\t} else {\n\t\t*f = append(*f, tmp)\n\t}\n\treturn nil\n}\n\nfunc (f *IntSlice) String() string {\n\treturn fmt.Sprintf(\"%d\", *f)\n}\n\nfunc (f *IntSlice) Value() []int {\n\treturn *f\n}\n\ntype IntSliceFlag struct {\n\tName  string\n\tValue *IntSlice\n\tUsage string\n}\n\nfunc (f IntSliceFlag) String() string {\n\tfirstName := strings.Trim(strings.Split(f.Name, \",\")[0], \" \")\n\tpref := prefixFor(firstName)\n\treturn fmt.Sprintf(\"%s '%v'\\t%v\", prefixedNames(f.Name), pref+firstName+\" option \"+pref+firstName+\" option\", f.Usage)\n}\n\nfunc (f IntSliceFlag) Apply(set *flag.FlagSet) {\n\teachName(f.Name, func(name string) {\n\t\tset.Var(f.Value, name, f.Usage)\n\t})\n}\n\nfunc (f IntSliceFlag) getName() string {\n\treturn f.Name\n}\n\ntype BoolFlag struct {\n\tName  string\n\tUsage string\n}\n\nfunc (f BoolFlag) String() string {\n\treturn fmt.Sprintf(\"%s\\t%v\", prefixedNames(f.Name), f.Usage)\n}\n\nfunc (f BoolFlag) Apply(set *flag.FlagSet) {\n\teachName(f.Name, func(name string) {\n\t\tset.Bool(name, false, f.Usage)\n\t})\n}\n\nfunc (f BoolFlag) getName() string {\n\treturn f.Name\n}\n\ntype BoolTFlag struct {\n\tName  string\n\tUsage string\n}\n\nfunc (f BoolTFlag) String() string {\n\treturn fmt.Sprintf(\"%s\\t%v\", prefixedNames(f.Name), f.Usage)\n}\n\nfunc (f BoolTFlag) Apply(set *flag.FlagSet) {\n\teachName(f.Name, func(name string) {\n\t\tset.Bool(name, true, f.Usage)\n\t})\n}\n\nfunc (f BoolTFlag) getName() string {\n\treturn f.Name\n}\n\ntype StringFlag struct {\n\tName  string\n\tValue string\n\tUsage string\n}\n\nfunc (f StringFlag) String() string {\n\tvar fmtString string\n\tfmtString = \"%s %v\\t%v\"\n\n\tif len(f.Value) > 0 {\n\t\tfmtString = \"%s '%v'\\t%v\"\n\t} else {\n\t\tfmtString = \"%s %v\\t%v\"\n\t}\n\n\treturn fmt.Sprintf(fmtString, prefixedNames(f.Name), f.Value, f.Usage)\n}\n\nfunc (f StringFlag) Apply(set *flag.FlagSet) {\n\teachName(f.Name, func(name string) {\n\t\tset.String(name, f.Value, f.Usage)\n\t})\n}\n\nfunc (f StringFlag) getName() string {\n\treturn f.Name\n}\n\ntype IntFlag struct {\n\tName  string\n\tValue int\n\tUsage string\n}\n\nfunc (f IntFlag) String() string {\n\treturn fmt.Sprintf(\"%s '%v'\\t%v\", prefixedNames(f.Name), f.Value, f.Usage)\n}\n\nfunc (f IntFlag) Apply(set *flag.FlagSet) {\n\teachName(f.Name, func(name string) {\n\t\tset.Int(name, f.Value, f.Usage)\n\t})\n}\n\nfunc (f IntFlag) getName() string {\n\treturn f.Name\n}\n\ntype Float64Flag struct {\n\tName  string\n\tValue float64\n\tUsage string\n}\n\nfunc (f Float64Flag) String() string {\n\treturn fmt.Sprintf(\"%s '%v'\\t%v\", prefixedNames(f.Name), f.Value, f.Usage)\n}\n\nfunc (f Float64Flag) Apply(set *flag.FlagSet) {\n\teachName(f.Name, func(name string) {\n\t\tset.Float64(name, f.Value, f.Usage)\n\t})\n}\n\nfunc (f Float64Flag) getName() string {\n\treturn f.Name\n}\n\nfunc prefixFor(name string) (prefix string) {\n\tif len(name) == 1 {\n\t\tprefix = \"-\"\n\t} else {\n\t\tprefix = \"--\"\n\t}\n\n\treturn\n}\n\nfunc prefixedNames(fullName string) (prefixed string) {\n\tparts := strings.Split(fullName, \",\")\n\tfor i, name := range parts {\n\t\tname = strings.Trim(name, \" \")\n\t\tprefixed += prefixFor(name) + name\n\t\tif i < len(parts)-1 {\n\t\t\tprefixed += \", \"\n\t\t}\n\t}\n\treturn\n}\n<commit_msg>Starting to hack in some env var configuration goodness<commit_after>package cli\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ This flag enables bash-completion for all commands and subcommands\nvar BashCompletionFlag = BoolFlag{\"generate-bash-completion\", \"\", \"\"}\n\n\/\/ This flag prints the version for the application\nvar VersionFlag = BoolFlag{\"version, v\", \"print the version\", \"\"}\n\n\/\/ This flag prints the help for all commands and subcommands\nvar HelpFlag = BoolFlag{\"help, h\", \"show help\", \"\"}\n\n\/\/ Flag is a common interface related to parsing flags in cli.\n\/\/ For more advanced flag parsing techniques, it is recomended that\n\/\/ this interface be implemented.\ntype Flag interface {\n\tfmt.Stringer\n\t\/\/ Apply Flag settings to the given flag set\n\tApply(*flag.FlagSet)\n\tgetName() string\n}\n\nfunc flagSet(name string, flags []Flag) *flag.FlagSet {\n\tset := flag.NewFlagSet(name, flag.ContinueOnError)\n\n\tfor _, f := range flags {\n\t\tf.Apply(set)\n\t}\n\treturn set\n}\n\nfunc eachName(longName string, fn func(string)) {\n\tparts := strings.Split(longName, \",\")\n\tfor _, name := range parts {\n\t\tname = strings.Trim(name, \" \")\n\t\tfn(name)\n\t}\n}\n\n\/\/ Generic is a generic parseable type identified by a specific flag\ntype Generic interface {\n\tSet(value string) error\n\tString() string\n}\n\n\/\/ GenericFlag is the flag type for types implementing Generic\ntype GenericFlag struct {\n\tName   string\n\tValue  Generic\n\tUsage  string\n\tEnvVar string\n}\n\nfunc (f GenericFlag) String() string {\n\treturn withEnvHint(f.EnvVar, fmt.Sprintf(\"%s%s %v\\t`%v` %s\", prefixFor(f.Name), f.Name, f.Value, \"-\"+f.Name+\" option -\"+f.Name+\" option\", f.Usage))\n}\n\nfunc (f GenericFlag) Apply(set *flag.FlagSet) {\n\tval := f.Value\n\tif f.EnvVar != \"\" {\n\t\tif envVal := os.Getenv(f.EnvVar); envVal != \"\" {\n\t\t\tval.Set(envVal)\n\t\t}\n\t}\n\n\teachName(f.Name, func(name string) {\n\t\tset.Var(f.Value, name, f.Usage)\n\t})\n}\n\nfunc (f GenericFlag) getName() string {\n\treturn f.Name\n}\n\ntype StringSlice []string\n\nfunc (f *StringSlice) Set(value string) error {\n\t*f = append(*f, value)\n\treturn nil\n}\n\nfunc (f *StringSlice) String() string {\n\treturn fmt.Sprintf(\"%s\", *f)\n}\n\nfunc (f *StringSlice) Value() []string {\n\treturn *f\n}\n\ntype StringSliceFlag struct {\n\tName   string\n\tValue  *StringSlice\n\tUsage  string\n\tEnvVar string\n}\n\nfunc (f StringSliceFlag) String() string {\n\tfirstName := strings.Trim(strings.Split(f.Name, \",\")[0], \" \")\n\tpref := prefixFor(firstName)\n\treturn withEnvHint(f.EnvVar, fmt.Sprintf(\"%s '%v'\\t%v\", prefixedNames(f.Name), pref+firstName+\" option \"+pref+firstName+\" option\", f.Usage))\n}\n\nfunc (f StringSliceFlag) Apply(set *flag.FlagSet) {\n\tif f.EnvVar != \"\" {\n\t\tif envVal := os.Getenv(f.EnvVar); envVal != \"\" {\n\t\t\tnewVal := &StringSlice{}\n\t\t\tfor _, s := range strings.Split(envVal, \",\") {\n\t\t\t\tnewVal.Set(s)\n\t\t\t}\n\t\t\tf.Value = newVal\n\t\t}\n\t}\n\n\teachName(f.Name, func(name string) {\n\t\tset.Var(f.Value, name, f.Usage)\n\t})\n}\n\nfunc (f StringSliceFlag) getName() string {\n\treturn f.Name\n}\n\ntype IntSlice []int\n\nfunc (f *IntSlice) Set(value string) error {\n\n\ttmp, err := strconv.Atoi(value)\n\tif err != nil {\n\t\treturn err\n\t} else {\n\t\t*f = append(*f, tmp)\n\t}\n\treturn nil\n}\n\nfunc (f *IntSlice) String() string {\n\treturn fmt.Sprintf(\"%d\", *f)\n}\n\nfunc (f *IntSlice) Value() []int {\n\treturn *f\n}\n\ntype IntSliceFlag struct {\n\tName   string\n\tValue  *IntSlice\n\tUsage  string\n\tEnvVar string\n}\n\nfunc (f IntSliceFlag) String() string {\n\tfirstName := strings.Trim(strings.Split(f.Name, \",\")[0], \" \")\n\tpref := prefixFor(firstName)\n\treturn withEnvHint(f.EnvVar, fmt.Sprintf(\"%s '%v'\\t%v\", prefixedNames(f.Name), pref+firstName+\" option \"+pref+firstName+\" option\", f.Usage))\n}\n\nfunc (f IntSliceFlag) Apply(set *flag.FlagSet) {\n\tif f.EnvVar != \"\" {\n\t\tif envVal := os.Getenv(f.EnvVar); envVal != \"\" {\n\t\t\tnewVal := &IntSlice{}\n\t\t\tfor _, s := range strings.Split(envVal, \",\") {\n\t\t\t\terr := newVal.Set(s)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprintf(os.Stderr, err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t\tf.Value = newVal\n\t\t}\n\t}\n\n\teachName(f.Name, func(name string) {\n\t\tset.Var(f.Value, name, f.Usage)\n\t})\n}\n\nfunc (f IntSliceFlag) getName() string {\n\treturn f.Name\n}\n\ntype BoolFlag struct {\n\tName   string\n\tUsage  string\n\tEnvVar string\n}\n\nfunc (f BoolFlag) String() string {\n\treturn withEnvHint(f.EnvVar, fmt.Sprintf(\"%s\\t%v\", prefixedNames(f.Name), f.Usage))\n}\n\nfunc (f BoolFlag) Apply(set *flag.FlagSet) {\n\tval := false\n\tif f.EnvVar != \"\" {\n\t\tif envVal := os.Getenv(f.EnvVar); envVal != \"\" {\n\t\t\tenvValBool, err := strconv.ParseBool(envVal)\n\t\t\tif err == nil {\n\t\t\t\tval = envValBool\n\t\t\t}\n\t\t}\n\t}\n\n\teachName(f.Name, func(name string) {\n\t\tset.Bool(name, val, f.Usage)\n\t})\n}\n\nfunc (f BoolFlag) getName() string {\n\treturn f.Name\n}\n\ntype BoolTFlag struct {\n\tName   string\n\tUsage  string\n\tEnvVar string\n}\n\nfunc (f BoolTFlag) String() string {\n\treturn withEnvHint(f.EnvVar, fmt.Sprintf(\"%s\\t%v\", prefixedNames(f.Name), f.Usage))\n}\n\nfunc (f BoolTFlag) Apply(set *flag.FlagSet) {\n\tval := true\n\tif f.EnvVar != \"\" {\n\t\tif envVal := os.Getenv(f.EnvVar); envVal != \"\" {\n\t\t\tenvValBool, err := strconv.ParseBool(envVal)\n\t\t\tif err == nil {\n\t\t\t\tval = envValBool\n\t\t\t}\n\t\t}\n\t}\n\n\teachName(f.Name, func(name string) {\n\t\tset.Bool(name, val, f.Usage)\n\t})\n}\n\nfunc (f BoolTFlag) getName() string {\n\treturn f.Name\n}\n\ntype StringFlag struct {\n\tName   string\n\tValue  string\n\tUsage  string\n\tEnvVar string\n}\n\nfunc (f StringFlag) String() string {\n\tvar fmtString string\n\tfmtString = \"%s %v\\t%v\"\n\n\tif len(f.Value) > 0 {\n\t\tfmtString = \"%s '%v'\\t%v\"\n\t} else {\n\t\tfmtString = \"%s %v\\t%v\"\n\t}\n\n\treturn withEnvHint(f.EnvVar, fmt.Sprintf(fmtString, prefixedNames(f.Name), f.Value, f.Usage))\n}\n\nfunc (f StringFlag) Apply(set *flag.FlagSet) {\n\tif f.EnvVar != \"\" {\n\t\tif envVal := os.Getenv(f.EnvVar); envVal != \"\" {\n\t\t\tf.Value = envVal\n\t\t}\n\t}\n\n\teachName(f.Name, func(name string) {\n\t\tset.String(name, f.Value, f.Usage)\n\t})\n}\n\nfunc (f StringFlag) getName() string {\n\treturn f.Name\n}\n\ntype IntFlag struct {\n\tName   string\n\tValue  int\n\tUsage  string\n\tEnvVar string\n}\n\nfunc (f IntFlag) String() string {\n\treturn withEnvHint(f.EnvVar, fmt.Sprintf(\"%s '%v'\\t%v\", prefixedNames(f.Name), f.Value, f.Usage))\n}\n\nfunc (f IntFlag) Apply(set *flag.FlagSet) {\n\tif f.EnvVar != \"\" {\n\t\tif envVal := os.Getenv(f.EnvVar); envVal != \"\" {\n\t\t\tenvValInt, err := strconv.ParseUint(envVal, 10, 64)\n\t\t\tif err == nil {\n\t\t\t\tf.Value = int(envValInt)\n\t\t\t}\n\t\t}\n\t}\n\n\teachName(f.Name, func(name string) {\n\t\tset.Int(name, f.Value, f.Usage)\n\t})\n}\n\nfunc (f IntFlag) getName() string {\n\treturn f.Name\n}\n\ntype Float64Flag struct {\n\tName   string\n\tValue  float64\n\tUsage  string\n\tEnvVar string\n}\n\nfunc (f Float64Flag) String() string {\n\treturn withEnvHint(f.EnvVar, fmt.Sprintf(\"%s '%v'\\t%v\", prefixedNames(f.Name), f.Value, f.Usage))\n}\n\nfunc (f Float64Flag) Apply(set *flag.FlagSet) {\n\tif f.EnvVar != \"\" {\n\t\tif envVal := os.Getenv(f.EnvVar); envVal != \"\" {\n\t\t\tenvValFloat, err := strconv.ParseFloat(envVal, 10)\n\t\t\tif err == nil {\n\t\t\t\tf.Value = float64(envValFloat)\n\t\t\t}\n\t\t}\n\t}\n\n\teachName(f.Name, func(name string) {\n\t\tset.Float64(name, f.Value, f.Usage)\n\t})\n}\n\nfunc (f Float64Flag) getName() string {\n\treturn f.Name\n}\n\nfunc prefixFor(name string) (prefix string) {\n\tif len(name) == 1 {\n\t\tprefix = \"-\"\n\t} else {\n\t\tprefix = \"--\"\n\t}\n\n\treturn\n}\n\nfunc prefixedNames(fullName string) (prefixed string) {\n\tparts := strings.Split(fullName, \",\")\n\tfor i, name := range parts {\n\t\tname = strings.Trim(name, \" \")\n\t\tprefixed += prefixFor(name) + name\n\t\tif i < len(parts)-1 {\n\t\t\tprefixed += \", \"\n\t\t}\n\t}\n\treturn\n}\n\nfunc withEnvHint(envVar, str string) string {\n\tenvText := \"\"\n\tif envVar != \"\" {\n\t\tenvText = fmt.Sprintf(\" [$%s]\", envVar)\n\t}\n\treturn str + envText\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"rais\/src\/iiif\"\n\t\"rais\/src\/magick\"\n\t\"rais\/src\/openjpeg\"\n\t\"rais\/src\/plugins\"\n\t\"rais\/src\/version\"\n\t\"time\"\n\n\t\"github.com\/BurntSushi\/toml\"\n\t\"github.com\/hashicorp\/golang-lru\"\n\t\"github.com\/spf13\/pflag\"\n\t\"github.com\/spf13\/viper\"\n\t\"github.com\/uoregon-libraries\/gopkg\/interrupts\"\n\t\"github.com\/uoregon-libraries\/gopkg\/logger\"\n)\n\nvar tilePath string\nvar infoCache *lru.Cache\nvar tileCache *lru.TwoQueueCache\n\n\/\/ Logger is the server's central logger.Logger instance\nvar Logger *logger.Logger\n\nconst defaultAddress = \":12415\"\nconst defaultInfoCacheLen = 10000\n\n\/\/ cacheHits and cacheMisses allow some rudimentary tracking of cache value\nvar cacheHits, cacheMisses int64\n\nvar defaultLogLevel = logger.Debug.String()\n\nfunc main() {\n\t\/\/ Defaults\n\tviper.SetDefault(\"Address\", defaultAddress)\n\tviper.SetDefault(\"InfoCacheLen\", defaultInfoCacheLen)\n\tviper.SetDefault(\"LogLevel\", defaultLogLevel)\n\n\t\/\/ Allow all configuration to be in environment variables\n\tviper.SetEnvPrefix(\"RAIS\")\n\tviper.AutomaticEnv()\n\n\t\/\/ Config file options\n\tviper.SetConfigName(\"rais\")\n\tviper.AddConfigPath(\"\/etc\")\n\tviper.AddConfigPath(\".\")\n\tviper.ReadInConfig()\n\n\t\/\/ CLI flags\n\tpflag.String(\"iiif-url\", \"\", `Base URL for serving IIIF requests, e.g., \"http:\/\/example.com\/images\/iiif\"`)\n\tviper.BindPFlag(\"IIIFURL\", pflag.CommandLine.Lookup(\"iiif-url\"))\n\tpflag.String(\"address\", defaultAddress, \"http service address\")\n\tviper.BindPFlag(\"Address\", pflag.CommandLine.Lookup(\"address\"))\n\tpflag.String(\"tile-path\", \"\", \"Base path for images\")\n\tviper.BindPFlag(\"TilePath\", pflag.CommandLine.Lookup(\"tile-path\"))\n\tpflag.Int(\"iiif-info-cache-size\", defaultInfoCacheLen, \"Maximum cached image info entries (IIIF only)\")\n\tviper.BindPFlag(\"InfoCacheLen\", pflag.CommandLine.Lookup(\"iiif-info-cache-size\"))\n\tpflag.String(\"capabilities-file\", \"\", \"TOML file describing capabilities, rather than everything RAIS supports\")\n\tviper.BindPFlag(\"CapabilitiesFile\", pflag.CommandLine.Lookup(\"capabilities-file\"))\n\tpflag.String(\"log-level\", defaultLogLevel, \"Log level: the server will only log notifications at \"+\n\t\t\"this level and above (must be DEBUG, INFO, WARN, ERROR, or CRIT)\")\n\tviper.BindPFlag(\"LogLevel\", pflag.CommandLine.Lookup(\"log-level\"))\n\tpflag.Int64(\"image-max-area\", math.MaxInt64, \"Maximum area (w x h) of images to be served\")\n\tviper.BindPFlag(\"ImageMaxArea\", pflag.CommandLine.Lookup(\"image-max-area\"))\n\tpflag.Int(\"image-max-width\", math.MaxInt32, \"Maximum width of images to be served\")\n\tviper.BindPFlag(\"ImageMaxWidth\", pflag.CommandLine.Lookup(\"image-max-width\"))\n\tpflag.Int(\"image-max-height\", math.MaxInt32, \"Maximum height of images to be served\")\n\tviper.BindPFlag(\"ImageMaxHeight\", pflag.CommandLine.Lookup(\"image-max-height\"))\n\n\tpflag.Parse()\n\n\t\/\/ Make sure required values exist\n\tif !viper.IsSet(\"TilePath\") {\n\t\tfmt.Println(\"ERROR: --tile-path is required\")\n\t\tpflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Make sure we have a valid log level\n\tvar level = logger.LogLevelFromString(viper.GetString(\"LogLevel\"))\n\tif level == logger.Invalid {\n\t\tfmt.Println(\"ERROR: --log-level must be DEBUG, INFO, WARN, ERROR, or CRIT\")\n\t\tpflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tLogger = logger.New(level)\n\topenjpeg.Logger = Logger\n\tmagick.Logger = Logger\n\n\tLoadPlugins(Logger)\n\n\t\/\/ Pull all values we need for all cases\n\ttilePath = viper.GetString(\"TilePath\")\n\taddress := viper.GetString(\"Address\")\n\n\tih := NewImageHandler(tilePath)\n\tih.Maximums.Area = viper.GetInt64(\"ImageMaxArea\")\n\tih.Maximums.Width = viper.GetInt(\"ImageMaxWidth\")\n\tih.Maximums.Height = viper.GetInt(\"ImageMaxHeight\")\n\n\t\/\/ Handle IIIF data only if we have a IIIF URL\n\tiiifURL := viper.GetString(\"IIIFURL\")\n\tif iiifURL == \"\" {\n\t\tfmt.Println(\"ERROR: --iiif-url must be set to the server's public URL\")\n\t\tpflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tLogger.Debugf(\"Attempting to start up IIIF at %s\", viper.GetString(\"IIIFURL\"))\n\tiiifBase, err := url.Parse(iiifURL)\n\tif err == nil && iiifBase.Scheme == \"\" {\n\t\terr = fmt.Errorf(\"empty scheme\")\n\t}\n\tif err == nil && iiifBase.Host == \"\" {\n\t\terr = fmt.Errorf(\"empty host\")\n\t}\n\tif err == nil && iiifBase.Path == \"\" {\n\t\terr = fmt.Errorf(\"empty path\")\n\t}\n\tif err != nil {\n\t\tLogger.Fatalf(\"Invalid IIIF URL (%s) specified: %s\", iiifURL, err)\n\t}\n\n\ticl := viper.GetInt(\"InfoCacheLen\")\n\tif icl > 0 {\n\t\tinfoCache, err = lru.New(icl)\n\t\tif err != nil {\n\t\t\tLogger.Fatalf(\"Unable to start info cache: %s\", err)\n\t\t}\n\t}\n\n\ttcl := viper.GetInt(\"TileCacheLen\")\n\tif tcl > 0 {\n\t\tLogger.Debugf(\"Creating a tile cache to hold up to %d tiles\", tcl)\n\t\ttileCache, err = lru.New2Q(tcl)\n\t\tif err != nil {\n\t\t\tLogger.Fatalf(\"Unable to start info cache: %s\", err)\n\t\t}\n\t}\n\n\tLogger.Infof(\"IIIF enabled at %s\", iiifBase.String())\n\tih.EnableIIIF(iiifBase)\n\n\tcapfile := viper.GetString(\"CapabilitiesFile\")\n\tif capfile != \"\" {\n\t\tih.FeatureSet = &iiif.FeatureSet{}\n\t\t_, err := toml.DecodeFile(capfile, &ih.FeatureSet)\n\t\tif err != nil {\n\t\t\tLogger.Fatalf(\"Invalid file or formatting in capabilities file '%s'\", capfile)\n\t\t}\n\t\tLogger.Debugf(\"Setting IIIF capabilities from file '%s'\", capfile)\n\t}\n\n\thandle(ih.IIIFBase.Path+\"\/\", http.HandlerFunc(ih.IIIFRoute))\n\thandle(\"\/images\/dzi\/\", http.HandlerFunc(ih.DZIRoute))\n\thandle(\"\/version\", http.HandlerFunc(VersionHandler))\n\n\tif tileCache != nil {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\ttime.Sleep(time.Minute * 10)\n\t\t\t\tLogger.Infof(\"Cache hits: %d; cache misses: %d\", cacheHits, cacheMisses)\n\t\t\t}\n\t\t}()\n\t}\n\n\tLogger.Infof(\"RAIS v%s starting...\", version.Version)\n\tvar srv = &http.Server{\n\t\tReadTimeout:  5 * time.Second,\n\t\tWriteTimeout: 30 * time.Second,\n\t\tAddr:         address,\n\t}\n\n\tinterrupts.TrapIntTerm(func() {\n\t\tLogger.Infof(\"Stopping RAIS...\")\n\t\tsrv.Shutdown(nil)\n\n\t\tif len(teardownPlugins) > 0 {\n\t\t\tLogger.Infof(\"Tearing down plugins\")\n\t\t\tfor _, plug := range teardownPlugins {\n\t\t\t\tplug()\n\t\t\t}\n\t\t\tLogger.Infof(\"Plugin teardown complete\")\n\t\t}\n\n\t\tLogger.Infof(\"Stopped\")\n\t})\n\n\tif err := srv.ListenAndServe(); err != nil {\n\t\t\/\/ Don't report a fatal error when we close the server\n\t\tif err != http.ErrServerClosed {\n\t\t\tLogger.Fatalf(\"Error starting listener: %s\", err)\n\t\t}\n\t}\n}\n\n\/\/ handle sends the pattern and raw handler to plugins, and sets up routing on\n\/\/ whatever is returned (if anything).  All plugins which wrap handlers are\n\/\/ allowed to run, but the behavior could definitely get weird depending on\n\/\/ what a given plugin does.  Ye be warned.\nfunc handle(pattern string, handler http.Handler) {\n\tfor _, plug := range wrapHandlerPlugins {\n\t\tvar h2, err = plug(pattern, handler)\n\t\tif err != plugins.ErrSkipped {\n\t\t\tlogger.Fatalf(\"Error trying to wrap handler %q: %s\", pattern, err)\n\t\t}\n\t\tif err == nil {\n\t\t\thandler = h2\n\t\t}\n\t}\n\thttp.Handle(pattern, handler)\n}\n\n\/\/ VersionHandler spits out the raw version string to the browser\nfunc VersionHandler(w http.ResponseWriter, req *http.Request) {\n\tw.Write([]byte(version.Version))\n}\n<commit_msg>rais-server: fix handle wrapper plugin loop<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"rais\/src\/iiif\"\n\t\"rais\/src\/magick\"\n\t\"rais\/src\/openjpeg\"\n\t\"rais\/src\/plugins\"\n\t\"rais\/src\/version\"\n\t\"time\"\n\n\t\"github.com\/BurntSushi\/toml\"\n\t\"github.com\/hashicorp\/golang-lru\"\n\t\"github.com\/spf13\/pflag\"\n\t\"github.com\/spf13\/viper\"\n\t\"github.com\/uoregon-libraries\/gopkg\/interrupts\"\n\t\"github.com\/uoregon-libraries\/gopkg\/logger\"\n)\n\nvar tilePath string\nvar infoCache *lru.Cache\nvar tileCache *lru.TwoQueueCache\n\n\/\/ Logger is the server's central logger.Logger instance\nvar Logger *logger.Logger\n\nconst defaultAddress = \":12415\"\nconst defaultInfoCacheLen = 10000\n\n\/\/ cacheHits and cacheMisses allow some rudimentary tracking of cache value\nvar cacheHits, cacheMisses int64\n\nvar defaultLogLevel = logger.Debug.String()\n\nfunc main() {\n\t\/\/ Defaults\n\tviper.SetDefault(\"Address\", defaultAddress)\n\tviper.SetDefault(\"InfoCacheLen\", defaultInfoCacheLen)\n\tviper.SetDefault(\"LogLevel\", defaultLogLevel)\n\n\t\/\/ Allow all configuration to be in environment variables\n\tviper.SetEnvPrefix(\"RAIS\")\n\tviper.AutomaticEnv()\n\n\t\/\/ Config file options\n\tviper.SetConfigName(\"rais\")\n\tviper.AddConfigPath(\"\/etc\")\n\tviper.AddConfigPath(\".\")\n\tviper.ReadInConfig()\n\n\t\/\/ CLI flags\n\tpflag.String(\"iiif-url\", \"\", `Base URL for serving IIIF requests, e.g., \"http:\/\/example.com\/images\/iiif\"`)\n\tviper.BindPFlag(\"IIIFURL\", pflag.CommandLine.Lookup(\"iiif-url\"))\n\tpflag.String(\"address\", defaultAddress, \"http service address\")\n\tviper.BindPFlag(\"Address\", pflag.CommandLine.Lookup(\"address\"))\n\tpflag.String(\"tile-path\", \"\", \"Base path for images\")\n\tviper.BindPFlag(\"TilePath\", pflag.CommandLine.Lookup(\"tile-path\"))\n\tpflag.Int(\"iiif-info-cache-size\", defaultInfoCacheLen, \"Maximum cached image info entries (IIIF only)\")\n\tviper.BindPFlag(\"InfoCacheLen\", pflag.CommandLine.Lookup(\"iiif-info-cache-size\"))\n\tpflag.String(\"capabilities-file\", \"\", \"TOML file describing capabilities, rather than everything RAIS supports\")\n\tviper.BindPFlag(\"CapabilitiesFile\", pflag.CommandLine.Lookup(\"capabilities-file\"))\n\tpflag.String(\"log-level\", defaultLogLevel, \"Log level: the server will only log notifications at \"+\n\t\t\"this level and above (must be DEBUG, INFO, WARN, ERROR, or CRIT)\")\n\tviper.BindPFlag(\"LogLevel\", pflag.CommandLine.Lookup(\"log-level\"))\n\tpflag.Int64(\"image-max-area\", math.MaxInt64, \"Maximum area (w x h) of images to be served\")\n\tviper.BindPFlag(\"ImageMaxArea\", pflag.CommandLine.Lookup(\"image-max-area\"))\n\tpflag.Int(\"image-max-width\", math.MaxInt32, \"Maximum width of images to be served\")\n\tviper.BindPFlag(\"ImageMaxWidth\", pflag.CommandLine.Lookup(\"image-max-width\"))\n\tpflag.Int(\"image-max-height\", math.MaxInt32, \"Maximum height of images to be served\")\n\tviper.BindPFlag(\"ImageMaxHeight\", pflag.CommandLine.Lookup(\"image-max-height\"))\n\n\tpflag.Parse()\n\n\t\/\/ Make sure required values exist\n\tif !viper.IsSet(\"TilePath\") {\n\t\tfmt.Println(\"ERROR: --tile-path is required\")\n\t\tpflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Make sure we have a valid log level\n\tvar level = logger.LogLevelFromString(viper.GetString(\"LogLevel\"))\n\tif level == logger.Invalid {\n\t\tfmt.Println(\"ERROR: --log-level must be DEBUG, INFO, WARN, ERROR, or CRIT\")\n\t\tpflag.Usage()\n\t\tos.Exit(1)\n\t}\n\tLogger = logger.New(level)\n\topenjpeg.Logger = Logger\n\tmagick.Logger = Logger\n\n\tLoadPlugins(Logger)\n\n\t\/\/ Pull all values we need for all cases\n\ttilePath = viper.GetString(\"TilePath\")\n\taddress := viper.GetString(\"Address\")\n\n\tih := NewImageHandler(tilePath)\n\tih.Maximums.Area = viper.GetInt64(\"ImageMaxArea\")\n\tih.Maximums.Width = viper.GetInt(\"ImageMaxWidth\")\n\tih.Maximums.Height = viper.GetInt(\"ImageMaxHeight\")\n\n\t\/\/ Handle IIIF data only if we have a IIIF URL\n\tiiifURL := viper.GetString(\"IIIFURL\")\n\tif iiifURL == \"\" {\n\t\tfmt.Println(\"ERROR: --iiif-url must be set to the server's public URL\")\n\t\tpflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tLogger.Debugf(\"Attempting to start up IIIF at %s\", viper.GetString(\"IIIFURL\"))\n\tiiifBase, err := url.Parse(iiifURL)\n\tif err == nil && iiifBase.Scheme == \"\" {\n\t\terr = fmt.Errorf(\"empty scheme\")\n\t}\n\tif err == nil && iiifBase.Host == \"\" {\n\t\terr = fmt.Errorf(\"empty host\")\n\t}\n\tif err == nil && iiifBase.Path == \"\" {\n\t\terr = fmt.Errorf(\"empty path\")\n\t}\n\tif err != nil {\n\t\tLogger.Fatalf(\"Invalid IIIF URL (%s) specified: %s\", iiifURL, err)\n\t}\n\n\ticl := viper.GetInt(\"InfoCacheLen\")\n\tif icl > 0 {\n\t\tinfoCache, err = lru.New(icl)\n\t\tif err != nil {\n\t\t\tLogger.Fatalf(\"Unable to start info cache: %s\", err)\n\t\t}\n\t}\n\n\ttcl := viper.GetInt(\"TileCacheLen\")\n\tif tcl > 0 {\n\t\tLogger.Debugf(\"Creating a tile cache to hold up to %d tiles\", tcl)\n\t\ttileCache, err = lru.New2Q(tcl)\n\t\tif err != nil {\n\t\t\tLogger.Fatalf(\"Unable to start info cache: %s\", err)\n\t\t}\n\t}\n\n\tLogger.Infof(\"IIIF enabled at %s\", iiifBase.String())\n\tih.EnableIIIF(iiifBase)\n\n\tcapfile := viper.GetString(\"CapabilitiesFile\")\n\tif capfile != \"\" {\n\t\tih.FeatureSet = &iiif.FeatureSet{}\n\t\t_, err := toml.DecodeFile(capfile, &ih.FeatureSet)\n\t\tif err != nil {\n\t\t\tLogger.Fatalf(\"Invalid file or formatting in capabilities file '%s'\", capfile)\n\t\t}\n\t\tLogger.Debugf(\"Setting IIIF capabilities from file '%s'\", capfile)\n\t}\n\n\thandle(ih.IIIFBase.Path+\"\/\", http.HandlerFunc(ih.IIIFRoute))\n\thandle(\"\/images\/dzi\/\", http.HandlerFunc(ih.DZIRoute))\n\thandle(\"\/version\", http.HandlerFunc(VersionHandler))\n\n\tif tileCache != nil {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\ttime.Sleep(time.Minute * 10)\n\t\t\t\tLogger.Infof(\"Cache hits: %d; cache misses: %d\", cacheHits, cacheMisses)\n\t\t\t}\n\t\t}()\n\t}\n\n\tLogger.Infof(\"RAIS v%s starting...\", version.Version)\n\tvar srv = &http.Server{\n\t\tReadTimeout:  5 * time.Second,\n\t\tWriteTimeout: 30 * time.Second,\n\t\tAddr:         address,\n\t}\n\n\tinterrupts.TrapIntTerm(func() {\n\t\tLogger.Infof(\"Stopping RAIS...\")\n\t\tsrv.Shutdown(nil)\n\n\t\tif len(teardownPlugins) > 0 {\n\t\t\tLogger.Infof(\"Tearing down plugins\")\n\t\t\tfor _, plug := range teardownPlugins {\n\t\t\t\tplug()\n\t\t\t}\n\t\t\tLogger.Infof(\"Plugin teardown complete\")\n\t\t}\n\n\t\tLogger.Infof(\"Stopped\")\n\t})\n\n\tif err := srv.ListenAndServe(); err != nil {\n\t\t\/\/ Don't report a fatal error when we close the server\n\t\tif err != http.ErrServerClosed {\n\t\t\tLogger.Fatalf(\"Error starting listener: %s\", err)\n\t\t}\n\t}\n}\n\n\/\/ handle sends the pattern and raw handler to plugins, and sets up routing on\n\/\/ whatever is returned (if anything).  All plugins which wrap handlers are\n\/\/ allowed to run, but the behavior could definitely get weird depending on\n\/\/ what a given plugin does.  Ye be warned.\nfunc handle(pattern string, handler http.Handler) {\n\tfor _, plug := range wrapHandlerPlugins {\n\t\tvar h2, err = plug(pattern, handler)\n\t\tif err == nil {\n\t\t\thandler = h2\n\t\t} else if err != plugins.ErrSkipped {\n\t\t\tlogger.Fatalf(\"Error trying to wrap handler %q: %s\", pattern, err)\n\t\t}\n\t}\n\thttp.Handle(pattern, handler)\n}\n\n\/\/ VersionHandler spits out the raw version string to the browser\nfunc VersionHandler(w http.ResponseWriter, req *http.Request) {\n\tw.Write([]byte(version.Version))\n}\n<|endoftext|>"}
{"text":"<commit_before>package berlingo\n\nimport (\n\t\"errors\"\n\t\"io\"\n)\n\n\/\/ AI is the primary interface that must be implemented by an author to use the berlingo framework\ntype AI interface {\n\tGameStart(*Game)\n\tTurn(*Game)\n\tGameOver(*Game)\n\tPing(*Game)\n}\n\ntype Game struct {\n\n\t\/\/ The AI implementation that will play the game\n\tAi AI\n\n\t\/\/ The json-parsed request received for the game.  Should normally not be needed by an AI author\n\tRequest *Request\n\t\/\/ The pending response that will be returned for the current move\n\tResponse *Response\n\n\t\/\/ General information on the game\n\tId                      string\n\tNumber_Of_Players       int\n\tMaximum_Number_Of_Turns int\n\tPlayer_Id               int\n\tTime_Limit_Per_Turn     int\n\n\t\/\/ Information on the current turn\n\tCurrent_Turn int\n\tTurns_Left   int\n\n\t\/\/ The game's parsed map\n\tMap *Map\n}\n\nfunc NewGame(ai AI, r io.Reader) (game *Game, err error) {\n\n\trequest, err := NewRequest(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse, err := NewResponse()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgame = &Game{\n\t\tAi:                      ai,\n\t\tRequest:                 request,\n\t\tResponse:                response,\n\t\tId:                      request.Infos.Game_Id,\n\t\tNumber_Of_Players:       request.Infos.Number_Of_Players,\n\t\tMaximum_Number_Of_Turns: request.Infos.Maximum_Number_Of_Turns,\n\t\tPlayer_Id:               request.Infos.Player_Id,\n\t\tTime_Limit_Per_Turn:     request.Infos.Time_Limit_Per_Turn,\n\t\tCurrent_Turn:            request.Infos.Current_Turn,\n\t\tTurns_Left:              request.Infos.Maximum_Number_Of_Turns - request.Infos.Current_Turn,\n\t}\n\n\tm, err := NewMap(game)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgame.Map = m\n\n\treturn game, nil\n\n}\n\n\/\/ Do invokes the appropriate AI method based on the Request Action\nfunc (game *Game) Do() {\n\tswitch game.Request.Action {\n\tcase \"game_start\":\n\t\tgame.Ai.GameStart(game)\n\tcase \"turn\":\n\t\tgame.Ai.Turn(game)\n\tcase \"game_over\":\n\t\tgame.Ai.GameOver(game)\n\tcase \"ping\":\n\t\tgame.Ai.Ping(game)\n\t}\n}\n\n\/\/ AddMove adds to the response queue the requested move characteristics\nfunc (game *Game) AddMove(from_node *Node, to_node *Node, num_soldiers int) (err error) {\n\tif from_node.Available_Soldiers < num_soldiers {\n\t\treturn errors.New(\"Not enough available soldiers\")\n\t}\n\tfrom_node.Available_Soldiers -= num_soldiers\n\tto_node.Incoming_Soldiers += num_soldiers\n\tgame.Response.AddMove(from_node, to_node, num_soldiers)\n\treturn nil\n}\n<commit_msg>Game#AddMove validation<commit_after>package berlingo\n\nimport (\n\t\"errors\"\n\t\"io\"\n)\n\n\/\/ AI is the primary interface that must be implemented by an author to use the berlingo framework\ntype AI interface {\n\tGameStart(*Game)\n\tTurn(*Game)\n\tGameOver(*Game)\n\tPing(*Game)\n}\n\ntype Game struct {\n\n\t\/\/ The AI implementation that will play the game\n\tAi AI\n\n\t\/\/ The json-parsed request received for the game.  Should normally not be needed by an AI author\n\tRequest *Request\n\t\/\/ The pending response that will be returned for the current move\n\tResponse *Response\n\n\t\/\/ General information on the game\n\tId                      string\n\tNumber_Of_Players       int\n\tMaximum_Number_Of_Turns int\n\tPlayer_Id               int\n\tTime_Limit_Per_Turn     int\n\n\t\/\/ Information on the current turn\n\tCurrent_Turn int\n\tTurns_Left   int\n\n\t\/\/ The game's parsed map\n\tMap *Map\n}\n\nfunc NewGame(ai AI, r io.Reader) (game *Game, err error) {\n\n\trequest, err := NewRequest(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse, err := NewResponse()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tgame = &Game{\n\t\tAi:                      ai,\n\t\tRequest:                 request,\n\t\tResponse:                response,\n\t\tId:                      request.Infos.Game_Id,\n\t\tNumber_Of_Players:       request.Infos.Number_Of_Players,\n\t\tMaximum_Number_Of_Turns: request.Infos.Maximum_Number_Of_Turns,\n\t\tPlayer_Id:               request.Infos.Player_Id,\n\t\tTime_Limit_Per_Turn:     request.Infos.Time_Limit_Per_Turn,\n\t\tCurrent_Turn:            request.Infos.Current_Turn,\n\t\tTurns_Left:              request.Infos.Maximum_Number_Of_Turns - request.Infos.Current_Turn,\n\t}\n\n\tm, err := NewMap(game)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgame.Map = m\n\n\treturn game, nil\n\n}\n\n\/\/ Do invokes the appropriate AI method based on the Request Action\nfunc (game *Game) Do() {\n\tswitch game.Request.Action {\n\tcase \"game_start\":\n\t\tgame.Ai.GameStart(game)\n\tcase \"turn\":\n\t\tgame.Ai.Turn(game)\n\tcase \"game_over\":\n\t\tgame.Ai.GameOver(game)\n\tcase \"ping\":\n\t\tgame.Ai.Ping(game)\n\t}\n}\n\n\/\/ AddMove adds to the response queue the requested move characteristics\nfunc (game *Game) AddMove(from_node *Node, to_node *Node, num_soldiers int) (err error) {\n\tif !from_node.IsOwned() {\n\t\treturn errors.New(\"Cannot move soldiers from a node you don't own\")\n\t} else if from_node.Available_Soldiers < num_soldiers {\n\t\treturn errors.New(\"Not enough available soldiers\")\n\t}\n\tfrom_node.Available_Soldiers -= num_soldiers\n\tto_node.Incoming_Soldiers += num_soldiers\n\tgame.Response.AddMove(from_node, to_node, num_soldiers)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package gamedayapi\n\nimport (\n\t\"bytes\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\ts \"strings\"\n\t\"time\"\n)\n\n\/\/ Game is the top-level abstraction, the starting point for clients.\n\/\/ A game is obtained using the GameFor function.\n\/\/ From a game, clients can navigate to all data: Innings, Boxscore, etc.\ntype Game struct {\n\tAwayAPMP        string `xml:\"away_ampm,attr\"`\n\tAwayCode        string `xml:\"away_code,attr\"`\n\tAwayLoss        string `xml:\"away_loss,attr\"`\n\tAwayTeamCity    string `xml:\"away_team_city,attr\"`\n\tAwayTeamID      string `xml:\"away_team_id,attr\"`\n\tAwayTeamName    string `xml:\"away_team_name,attr\"`\n\tAwayTime        string `xml:\"away_time,attr\"`\n\tAwayTimezone    string `xml:\"away_time_zone,attr\"`\n\tAwayWin         string `xml:\"away_win,attr\"`\n\tCalendarEventID string `xml:\"calendar_event_id,attr\"`\n\tHomeAMPM        string `xml:\"home_ampm,attr\"`\n\tHomeCode        string `xml:\"home_code,attr\"`\n\tHomeLoss        string `xml:\"home_loss,attr\"`\n\tHomeTeamCity    string `xml:\"home_team_city,attr\"`\n\tHomeTeamID      string `xml:\"home_team_id,attr\"`\n\tHomeTeamName    string `xml:\"home_team_name,attr\"`\n\tHomeTime        string `xml:\"home_time,attr\"`\n\tHomeTimezone    string `xml:\"home_time_zone,attr\"`\n\tHomeWin         string `xml:\"home_win,attr\"`\n\tID              string `xml:\"id,attr\"`\n\tGameday         string `xml:\"gameday,attr\"`\n\tGamePk          string `xml:\"game_pk,attr\"`\n\tGameType        string `xml:\"game_type,attr\"`\n\tStatus          string `xml:\"status,attr\"`\n\tTimeDate        string `xml:\"time_date,attr\"`\n\tTimezone        string `xml:\"time_zone,attr\"`\n\tVenue           string `xml:\"venue,attr\"`\n\n\t\/\/ GameDataDirectory does not always point to where the files are.\n\t\/\/ Use FetchableDataDirectory for building requests to gameday servers.\n\tGameDataDirectory string `xml:\"game_data_directory,attr\"`\n\n\tallInnings AllInnings\n\tboxscore   Boxscore\n\thitChart   HitChart\n\tplayers    Players\n\n\tyear int\n}\n\n\/\/ GameFor will return a pointer to a game instance for the team code and date provided.\n\/\/ This is the place to start for interacting with a game.\n\/\/ Does not account for doubleheaders. Use GamesFor if doubleheader support is needed.\nfunc GameFor(teamCode string, date time.Time) (*Game, error) {\n\tepg := EpgFor(date)\n\tgame, err := epg.GameForTeam(teamCode)\n\tif err != nil {\n\t\treturn &Game{}, err\n\t}\n\treturn game, nil\n}\n\n\/\/ GamesFor will return a collection of pointers to games for the team code and date provided.\n\/\/ Accounts for doubleheaders. In most cases, the collection will only have one game in it.\nfunc GamesFor(teamCode string, date time.Time) ([]*Game, error) {\n\tepg := EpgFor(date)\n\tgames, err := epg.GamesForTeam(teamCode)\n\tif err != nil {\n\t\treturn games, err\n\t}\n\treturn games, nil\n}\n\n\/\/ IsFinal returns true if the game status is Final.\nfunc (game *Game) IsFinal() bool {\n\treturn game.Status == \"Final\"\n}\n\n\/\/ AllInnings fetches the inning\/innings_all.xml file from gameday servers and fills in all the\n\/\/ structs beneath, all the way down to the pitches.\nfunc (game *Game) AllInnings() *AllInnings {\n\tif game.IsFinal() && len(game.allInnings.AtBat) == 0 {\n\t\tgame.load(\"\/inning\/inning_all.xml\", &game.allInnings)\n\t}\n\treturn &game.allInnings\n}\n\n\/\/ Boxscore fetches the boxscore.xml file from the gameday servers and fills in all the structs beneath.\nfunc (game *Game) Boxscore() *Boxscore {\n\tif game.IsFinal() && len(game.boxscore.GameID) == 0 {\n\t\tgame.load(\"\/boxscore.xml\", &game.boxscore)\n\t}\n\treturn &game.boxscore\n}\n\n\/\/ HitChart fetches the inning\/inning_hit.xml file from gameday servers\nfunc (game *Game) HitChart() *HitChart {\n\tif game.IsFinal() && len(game.hitChart.Hips) == 0 {\n\t\tgame.load(\"\/inning\/inning_hit.xml\", &game.hitChart)\n\t}\n\treturn &game.hitChart\n}\n\n\/\/ Players fetches the players.xml file from gameday servers\nfunc (game *Game) Players() *Players {\n\tif game.IsFinal() && len(game.players.Date) == 0 {\n\t\tgame.load(\"\/players.xml\", &game.players)\n\t}\n\treturn &game.players\n}\n\n\/\/func (game *Game) InningScores() *InningScores {}\n\n\/\/ EagerLoad will eagerly load all of the files that the library pulls from the MLB gameday servers.\n\/\/ Otherwise, files are lazily loaded as clients interact with the API.\nfunc (game *Game) EagerLoad() {\n\tgame.AllInnings()\n\tgame.Boxscore()\n\tgame.HitChart()\n\tgame.Players()\n}\n\n\/\/ Year returns the year in which the game was played.\n\/\/ Convenience method. Not a direct Gameday attribute.\nfunc (game *Game) Year() int {\n\tif game.year == 0 {\n\t\tidPieces := s.Split(game.ID, \"\/\")\n\t\tyear, _ := strconv.Atoi(idPieces[0])\n\t\tgame.year = year\n\t}\n\treturn game.year\n}\n\nfunc (game Game) load(fileName string, val interface{}) {\n\tfilePath := game.FetchableDataDirectory() + fileName\n\tlocalFilePath := BaseCachePath() + filePath\n\tif _, err := os.Stat(localFilePath); os.IsNotExist(err) {\n\t\tlog.Println(\"Cache miss on \" + localFilePath)\n\t\tfetchAndCache(filePath, val)\n\t} else {\n\t\tlog.Println(\"Cache hit on \" + localFilePath)\n\t\tbody, _ := ioutil.ReadFile(localFilePath)\n\t\txml.Unmarshal(body, val)\n\t}\n}\n\n\/\/ FetchableDataDirectory builds a data directory to the game files using the game's ID.\n\/\/ GameDataDirectory is not always reliable (see epg on 2013-04-11 vs 2013-04-10 as an example).\nfunc (game Game) FetchableDataDirectory() string {\n\tidPieces := s.Split(game.ID, \"\/\")\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(GamedayBasePath)\n\tbuffer.WriteString(fmt.Sprintf(\"\/year_%s\/month_%s\/day_%s\/gid_\", idPieces[0], idPieces[1], idPieces[2]))\n\tbuffer.WriteString(game.Gameday)\n\treturn buffer.String()\n}\n\nfunc fetchAndCache(filePath string, val interface{}) {\n\turlToFetch := GamedayHostname + filePath\n\tlog.Println(\"Fetching \" + urlToFetch)\n\tresp, err := http.Get(urlToFetch)\n\tcheck(err)\n\tif resp.StatusCode != 200 {\n\t\tlog.Fatal(resp.Status + \" fetching \" + urlToFetch)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tcheck(err)\n\txml.Unmarshal(body, val)\n\tcacheFile(filePath, body)\n}\n\nfunc cacheFile(filePath string, body []byte) {\n\tlocalCachePath := BaseCachePath() + filePath[0:s.LastIndex(filePath, \"\/\")]\n\tos.MkdirAll(localCachePath, (os.FileMode)(0775))\n\tf, err := os.Create(localCachePath + filePath[s.LastIndex(filePath, \"\/\"):])\n\tf.Write(body)\n\tcheck(err)\n\tdefer f.Close()\n}\n<commit_msg>Adding a couple attributes to the game.<commit_after>package gamedayapi\n\nimport (\n\t\"bytes\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\ts \"strings\"\n\t\"time\"\n)\n\n\/\/ Game is the top-level abstraction, the starting point for clients.\n\/\/ A game is obtained using the GameFor function.\n\/\/ From a game, clients can navigate to all data: Innings, Boxscore, etc.\ntype Game struct {\n\tAwayAPMP        string `xml:\"away_ampm,attr\"`\n\tAwayCode        string `xml:\"away_code,attr\"`\n\tAwayFileCode\tstring `xml:\"away_file_code,attr\"`\n\tAwayLoss        string `xml:\"away_loss,attr\"`\n\tAwayTeamCity    string `xml:\"away_team_city,attr\"`\n\tAwayTeamID      string `xml:\"away_team_id,attr\"`\n\tAwayTeamName    string `xml:\"away_team_name,attr\"`\n\tAwayTime        string `xml:\"away_time,attr\"`\n\tAwayTimezone    string `xml:\"away_time_zone,attr\"`\n\tAwayWin         string `xml:\"away_win,attr\"`\n\tCalendarEventID string `xml:\"calendar_event_id,attr\"`\n\tHomeAMPM        string `xml:\"home_ampm,attr\"`\n\tHomeCode        string `xml:\"home_code,attr\"`\n\tHomeFileCode\tstring `xml:\"home_file_code,attr\"`\n\tHomeLoss        string `xml:\"home_loss,attr\"`\n\tHomeTeamCity    string `xml:\"home_team_city,attr\"`\n\tHomeTeamID      string `xml:\"home_team_id,attr\"`\n\tHomeTeamName    string `xml:\"home_team_name,attr\"`\n\tHomeTime        string `xml:\"home_time,attr\"`\n\tHomeTimezone    string `xml:\"home_time_zone,attr\"`\n\tHomeWin         string `xml:\"home_win,attr\"`\n\tID              string `xml:\"id,attr\"`\n\tGameday         string `xml:\"gameday,attr\"`\n\tGamePk          string `xml:\"game_pk,attr\"`\n\tGameType        string `xml:\"game_type,attr\"`\n\tStatus          string `xml:\"status,attr\"`\n\tTimeDate        string `xml:\"time_date,attr\"`\n\tTimezone        string `xml:\"time_zone,attr\"`\n\tVenue           string `xml:\"venue,attr\"`\n\n\t\/\/ GameDataDirectory does not always point to where the files are.\n\t\/\/ Use FetchableDataDirectory for building requests to gameday servers.\n\tGameDataDirectory string `xml:\"game_data_directory,attr\"`\n\n\tallInnings AllInnings\n\tboxscore   Boxscore\n\thitChart   HitChart\n\tplayers    Players\n\n\tyear int\n}\n\n\/\/ GameFor will return a pointer to a game instance for the team code and date provided.\n\/\/ This is the place to start for interacting with a game.\n\/\/ Does not account for doubleheaders. Use GamesFor if doubleheader support is needed.\nfunc GameFor(teamCode string, date time.Time) (*Game, error) {\n\tepg := EpgFor(date)\n\tgame, err := epg.GameForTeam(teamCode)\n\tif err != nil {\n\t\treturn &Game{}, err\n\t}\n\treturn game, nil\n}\n\n\/\/ GamesFor will return a collection of pointers to games for the team code and date provided.\n\/\/ Accounts for doubleheaders. In most cases, the collection will only have one game in it.\nfunc GamesFor(teamCode string, date time.Time) ([]*Game, error) {\n\tepg := EpgFor(date)\n\tgames, err := epg.GamesForTeam(teamCode)\n\tif err != nil {\n\t\treturn games, err\n\t}\n\treturn games, nil\n}\n\n\/\/ IsFinal returns true if the game status is Final.\nfunc (game *Game) IsFinal() bool {\n\treturn game.Status == \"Final\"\n}\n\n\/\/ AllInnings fetches the inning\/innings_all.xml file from gameday servers and fills in all the\n\/\/ structs beneath, all the way down to the pitches.\nfunc (game *Game) AllInnings() *AllInnings {\n\tif game.IsFinal() && len(game.allInnings.AtBat) == 0 {\n\t\tgame.load(\"\/inning\/inning_all.xml\", &game.allInnings)\n\t}\n\treturn &game.allInnings\n}\n\n\/\/ Boxscore fetches the boxscore.xml file from the gameday servers and fills in all the structs beneath.\nfunc (game *Game) Boxscore() *Boxscore {\n\tif game.IsFinal() && len(game.boxscore.GameID) == 0 {\n\t\tgame.load(\"\/boxscore.xml\", &game.boxscore)\n\t}\n\treturn &game.boxscore\n}\n\n\/\/ HitChart fetches the inning\/inning_hit.xml file from gameday servers\nfunc (game *Game) HitChart() *HitChart {\n\tif game.IsFinal() && len(game.hitChart.Hips) == 0 {\n\t\tgame.load(\"\/inning\/inning_hit.xml\", &game.hitChart)\n\t}\n\treturn &game.hitChart\n}\n\n\/\/ Players fetches the players.xml file from gameday servers\nfunc (game *Game) Players() *Players {\n\tif game.IsFinal() && len(game.players.Date) == 0 {\n\t\tgame.load(\"\/players.xml\", &game.players)\n\t}\n\treturn &game.players\n}\n\n\/\/func (game *Game) InningScores() *InningScores {}\n\n\/\/ EagerLoad will eagerly load all of the files that the library pulls from the MLB gameday servers.\n\/\/ Otherwise, files are lazily loaded as clients interact with the API.\nfunc (game *Game) EagerLoad() {\n\tgame.AllInnings()\n\tgame.Boxscore()\n\tgame.HitChart()\n\tgame.Players()\n}\n\n\/\/ Year returns the year in which the game was played.\n\/\/ Convenience method. Not a direct Gameday attribute.\nfunc (game *Game) Year() int {\n\tif game.year == 0 {\n\t\tidPieces := s.Split(game.ID, \"\/\")\n\t\tyear, _ := strconv.Atoi(idPieces[0])\n\t\tgame.year = year\n\t}\n\treturn game.year\n}\n\nfunc (game Game) load(fileName string, val interface{}) {\n\tfilePath := game.FetchableDataDirectory() + fileName\n\tlocalFilePath := BaseCachePath() + filePath\n\tif _, err := os.Stat(localFilePath); os.IsNotExist(err) {\n\t\tlog.Println(\"Cache miss on \" + localFilePath)\n\t\tfetchAndCache(filePath, val)\n\t} else {\n\t\tlog.Println(\"Cache hit on \" + localFilePath)\n\t\tbody, _ := ioutil.ReadFile(localFilePath)\n\t\txml.Unmarshal(body, val)\n\t}\n}\n\n\/\/ FetchableDataDirectory builds a data directory to the game files using the game's ID.\n\/\/ GameDataDirectory is not always reliable (see epg on 2013-04-11 vs 2013-04-10 as an example).\nfunc (game Game) FetchableDataDirectory() string {\n\tidPieces := s.Split(game.ID, \"\/\")\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(GamedayBasePath)\n\tbuffer.WriteString(fmt.Sprintf(\"\/year_%s\/month_%s\/day_%s\/gid_\", idPieces[0], idPieces[1], idPieces[2]))\n\tbuffer.WriteString(game.Gameday)\n\treturn buffer.String()\n}\n\nfunc fetchAndCache(filePath string, val interface{}) {\n\turlToFetch := GamedayHostname + filePath\n\tlog.Println(\"Fetching \" + urlToFetch)\n\tresp, err := http.Get(urlToFetch)\n\tcheck(err)\n\tif resp.StatusCode != 200 {\n\t\tlog.Fatal(resp.Status + \" fetching \" + urlToFetch)\n\t}\n\tdefer resp.Body.Close()\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tcheck(err)\n\txml.Unmarshal(body, val)\n\tcacheFile(filePath, body)\n}\n\nfunc cacheFile(filePath string, body []byte) {\n\tlocalCachePath := BaseCachePath() + filePath[0:s.LastIndex(filePath, \"\/\")]\n\tos.MkdirAll(localCachePath, (os.FileMode)(0775))\n\tf, err := os.Create(localCachePath + filePath[s.LastIndex(filePath, \"\/\"):])\n\tf.Write(body)\n\tcheck(err)\n\tdefer f.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016-2019 Authors of Cilium\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/cilium\/cilium\/api\/v1\/models\"\n\t. \"github.com\/cilium\/cilium\/api\/v1\/server\/restapi\/service\"\n\t\"github.com\/cilium\/cilium\/pkg\/api\"\n\t\"github.com\/cilium\/cilium\/pkg\/loadbalancer\"\n\t\"github.com\/cilium\/cilium\/pkg\/logging\/logfields\"\n\t\"github.com\/cilium\/cilium\/pkg\/service\"\n\n\t\"github.com\/go-openapi\/runtime\/middleware\"\n)\n\n\/\/ SVCAdd is the public method to add services. We assume the ID provided is not in\n\/\/ sync with the KVStore. If that's the, case the service won't be used and an error is\n\/\/ returned to the caller.\n\/\/\n\/\/ Returns true if service was created.\nfunc (d *Daemon) SVCAdd(feL3n4Addr loadbalancer.L3n4AddrID, be []loadbalancer.LBBackEnd) (bool, error) {\n\tlog.WithField(logfields.ServiceID, feL3n4Addr.String()).Debug(\"adding service\")\n\tif feL3n4Addr.ID == 0 {\n\t\treturn false, fmt.Errorf(\"invalid service ID 0\")\n\t}\n\n\tcreated, id, err := d.svc.UpsertService(feL3n4Addr, be, service.TypeClusterIP)\n\tif err == nil && id != feL3n4Addr.ID {\n\t\treturn false,\n\t\t\tfmt.Errorf(\"the service provided is already registered with ID %d, please use that ID instead of %d\",\n\t\t\t\tid, feL3n4Addr.ID)\n\t}\n\n\treturn created, err\n}\n\ntype putServiceID struct {\n\td *Daemon\n}\n\nfunc NewPutServiceIDHandler(d *Daemon) PutServiceIDHandler {\n\treturn &putServiceID{d: d}\n}\n\nfunc (h *putServiceID) Handle(params PutServiceIDParams) middleware.Responder {\n\tlog.WithField(logfields.Params, logfields.Repr(params)).Debug(\"PUT \/service\/{id} request\")\n\n\tf, err := loadbalancer.NewL3n4AddrFromModel(params.Config.FrontendAddress)\n\tif err != nil {\n\t\treturn api.Error(PutServiceIDInvalidFrontendCode, err)\n\t}\n\n\tfrontend := loadbalancer.L3n4AddrID{\n\t\tL3n4Addr: *f,\n\t\tID:       loadbalancer.ID(params.Config.ID),\n\t}\n\n\tbackends := []loadbalancer.LBBackEnd{}\n\tfor _, v := range params.Config.BackendAddresses {\n\t\tb, err := loadbalancer.NewLBBackEndFromBackendModel(v)\n\t\tif err != nil {\n\t\t\treturn api.Error(PutServiceIDInvalidBackendCode, err)\n\t\t}\n\t\tbackends = append(backends, *b)\n\t}\n\n\tif created, err := h.d.SVCAdd(frontend, backends); err != nil {\n\t\treturn api.Error(PutServiceIDFailureCode, err)\n\t} else if created {\n\t\treturn NewPutServiceIDCreated()\n\t} else {\n\t\treturn NewPutServiceIDOK()\n\t}\n}\n\ntype deleteServiceID struct {\n\td *Daemon\n}\n\nfunc NewDeleteServiceIDHandler(d *Daemon) DeleteServiceIDHandler {\n\treturn &deleteServiceID{d: d}\n}\n\nfunc (h *deleteServiceID) Handle(params DeleteServiceIDParams) middleware.Responder {\n\tlog.WithField(logfields.Params, logfields.Repr(params)).Debug(\"DELETE \/service\/{id} request\")\n\n\tfound, err := h.d.svc.DeleteServiceByID(loadbalancer.ServiceID(params.ID))\n\tswitch {\n\tcase err != nil:\n\t\tlog.WithError(err).WithField(logfields.ServiceID, params.ID).\n\t\t\tWarn(\"DELETE \/service\/{id}: error deleting service\")\n\t\treturn api.Error(DeleteServiceIDFailureCode, err)\n\tcase !found:\n\t\treturn NewDeleteServiceIDNotFound()\n\tdefault:\n\t\treturn NewDeleteServiceIDOK()\n\t}\n}\n\ntype getServiceID struct {\n\tdaemon *Daemon\n}\n\nfunc NewGetServiceIDHandler(d *Daemon) GetServiceIDHandler {\n\treturn &getServiceID{daemon: d}\n}\n\nfunc (h *getServiceID) Handle(params GetServiceIDParams) middleware.Responder {\n\tlog.WithField(logfields.Params, logfields.Repr(params)).Debug(\"GET \/service\/{id} request\")\n\n\td := h.daemon\n\n\tif svc, ok := d.svc.GetDeepCopyServiceByID(loadbalancer.ServiceID(params.ID)); ok {\n\t\treturn NewGetServiceIDOK().WithPayload(svc.GetModel())\n\t}\n\treturn NewGetServiceIDNotFound()\n}\n\ntype getService struct {\n\td *Daemon\n}\n\nfunc NewGetServiceHandler(d *Daemon) GetServiceHandler {\n\treturn &getService{d: d}\n}\n\nfunc (h *getService) Handle(params GetServiceParams) middleware.Responder {\n\tlog.WithField(logfields.Params, logfields.Repr(params)).Debug(\"GET \/service request\")\n\tlist := h.d.GetServiceList()\n\treturn NewGetServiceOK().WithPayload(list)\n}\n\n\/\/ GetServiceList returns list of services\nfunc (d *Daemon) GetServiceList() []*models.Service {\n\tsvcs := d.svc.GetDeepCopyServices()\n\tlist := make([]*models.Service, 0, len(svcs))\n\n\tfor _, v := range svcs {\n\t\tlist = append(list, v.GetModel())\n\t}\n\treturn list\n}\n<commit_msg>daemon: Inline SVCAdd method into PUT handler<commit_after>\/\/ Copyright 2016-2019 Authors of Cilium\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/cilium\/cilium\/api\/v1\/models\"\n\t. \"github.com\/cilium\/cilium\/api\/v1\/server\/restapi\/service\"\n\t\"github.com\/cilium\/cilium\/pkg\/api\"\n\t\"github.com\/cilium\/cilium\/pkg\/loadbalancer\"\n\t\"github.com\/cilium\/cilium\/pkg\/logging\/logfields\"\n\t\"github.com\/cilium\/cilium\/pkg\/service\"\n\n\t\"github.com\/go-openapi\/runtime\/middleware\"\n)\n\ntype putServiceID struct {\n\td *Daemon\n}\n\nfunc NewPutServiceIDHandler(d *Daemon) PutServiceIDHandler {\n\treturn &putServiceID{d: d}\n}\n\nfunc (h *putServiceID) Handle(params PutServiceIDParams) middleware.Responder {\n\tlog.WithField(logfields.Params, logfields.Repr(params)).Debug(\"PUT \/service\/{id} request\")\n\n\tif params.Config.ID == 0 {\n\t\treturn api.Error(PutServiceIDFailureCode, fmt.Errorf(\"invalid service ID 0\"))\n\t}\n\n\tf, err := loadbalancer.NewL3n4AddrFromModel(params.Config.FrontendAddress)\n\tif err != nil {\n\t\treturn api.Error(PutServiceIDInvalidFrontendCode, err)\n\t}\n\n\tfrontend := loadbalancer.L3n4AddrID{\n\t\tL3n4Addr: *f,\n\t\tID:       loadbalancer.ID(params.Config.ID),\n\t}\n\tbackends := []loadbalancer.LBBackEnd{}\n\tfor _, v := range params.Config.BackendAddresses {\n\t\tb, err := loadbalancer.NewLBBackEndFromBackendModel(v)\n\t\tif err != nil {\n\t\t\treturn api.Error(PutServiceIDInvalidBackendCode, err)\n\t\t}\n\t\tbackends = append(backends, *b)\n\t}\n\n\tcreated, id, err := h.d.svc.UpsertService(frontend, backends, service.TypeClusterIP)\n\tif err == nil && id != frontend.ID {\n\t\treturn api.Error(PutServiceIDInvalidFrontendCode,\n\t\t\tfmt.Errorf(\"the service provided is already registered with ID %d, please use that ID instead of %d\",\n\t\t\t\tid, frontend.ID))\n\t} else if err != nil {\n\t\treturn api.Error(PutServiceIDFailureCode, err)\n\t} else if created {\n\t\treturn NewPutServiceIDCreated()\n\t} else {\n\t\treturn NewPutServiceIDOK()\n\t}\n}\n\ntype deleteServiceID struct {\n\td *Daemon\n}\n\nfunc NewDeleteServiceIDHandler(d *Daemon) DeleteServiceIDHandler {\n\treturn &deleteServiceID{d: d}\n}\n\nfunc (h *deleteServiceID) Handle(params DeleteServiceIDParams) middleware.Responder {\n\tlog.WithField(logfields.Params, logfields.Repr(params)).Debug(\"DELETE \/service\/{id} request\")\n\n\tfound, err := h.d.svc.DeleteServiceByID(loadbalancer.ServiceID(params.ID))\n\tswitch {\n\tcase err != nil:\n\t\tlog.WithError(err).WithField(logfields.ServiceID, params.ID).\n\t\t\tWarn(\"DELETE \/service\/{id}: error deleting service\")\n\t\treturn api.Error(DeleteServiceIDFailureCode, err)\n\tcase !found:\n\t\treturn NewDeleteServiceIDNotFound()\n\tdefault:\n\t\treturn NewDeleteServiceIDOK()\n\t}\n}\n\ntype getServiceID struct {\n\tdaemon *Daemon\n}\n\nfunc NewGetServiceIDHandler(d *Daemon) GetServiceIDHandler {\n\treturn &getServiceID{daemon: d}\n}\n\nfunc (h *getServiceID) Handle(params GetServiceIDParams) middleware.Responder {\n\tlog.WithField(logfields.Params, logfields.Repr(params)).Debug(\"GET \/service\/{id} request\")\n\n\td := h.daemon\n\n\tif svc, ok := d.svc.GetDeepCopyServiceByID(loadbalancer.ServiceID(params.ID)); ok {\n\t\treturn NewGetServiceIDOK().WithPayload(svc.GetModel())\n\t}\n\treturn NewGetServiceIDNotFound()\n}\n\ntype getService struct {\n\td *Daemon\n}\n\nfunc NewGetServiceHandler(d *Daemon) GetServiceHandler {\n\treturn &getService{d: d}\n}\n\nfunc (h *getService) Handle(params GetServiceParams) middleware.Responder {\n\tlog.WithField(logfields.Params, logfields.Repr(params)).Debug(\"GET \/service request\")\n\tlist := h.d.GetServiceList()\n\treturn NewGetServiceOK().WithPayload(list)\n}\n\n\/\/ GetServiceList returns list of services\nfunc (d *Daemon) GetServiceList() []*models.Service {\n\tsvcs := d.svc.GetDeepCopyServices()\n\tlist := make([]*models.Service, 0, len(svcs))\n\n\tfor _, v := range svcs {\n\t\tlist = append(list, v.GetModel())\n\t}\n\treturn list\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build !windows\n\n\/\/ TODO(amitkris): We need to split this file for solaris.\n\npackage daemon\n\nimport (\n\t\"encoding\/json\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/docker\/docker\/container\"\n\t\"github.com\/docker\/docker\/pkg\/fileutils\"\n\t\"github.com\/docker\/docker\/pkg\/mount\"\n\t\"github.com\/docker\/docker\/volume\"\n\t\"github.com\/docker\/docker\/volume\/drivers\"\n\t\"github.com\/docker\/docker\/volume\/local\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ setupMounts iterates through each of the mount points for a container and\n\/\/ calls Setup() on each. It also looks to see if is a network mount such as\n\/\/ \/etc\/resolv.conf, and if it is not, appends it to the array of mounts.\nfunc (daemon *Daemon) setupMounts(c *container.Container) ([]container.Mount, error) {\n\tvar mounts []container.Mount\n\t\/\/ TODO: tmpfs mounts should be part of Mountpoints\n\ttmpfsMounts := make(map[string]bool)\n\ttmpfsMountInfo, err := c.TmpfsMounts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, m := range tmpfsMountInfo {\n\t\ttmpfsMounts[m.Destination] = true\n\t}\n\tfor _, m := range c.MountPoints {\n\t\tif tmpfsMounts[m.Destination] {\n\t\t\tcontinue\n\t\t}\n\t\tif err := daemon.lazyInitializeVolume(c.ID, m); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trootUID, rootGID := daemon.GetRemappedUIDGID()\n\t\tpath, err := m.Setup(c.MountLabel, rootUID, rootGID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !c.TrySetNetworkMount(m.Destination, path) {\n\t\t\tmnt := container.Mount{\n\t\t\t\tSource:      path,\n\t\t\t\tDestination: m.Destination,\n\t\t\t\tWritable:    m.RW,\n\t\t\t\tPropagation: string(m.Propagation),\n\t\t\t}\n\t\t\tif m.Volume != nil {\n\t\t\t\tattributes := map[string]string{\n\t\t\t\t\t\"driver\":      m.Volume.DriverName(),\n\t\t\t\t\t\"container\":   c.ID,\n\t\t\t\t\t\"destination\": m.Destination,\n\t\t\t\t\t\"read\/write\":  strconv.FormatBool(m.RW),\n\t\t\t\t\t\"propagation\": string(m.Propagation),\n\t\t\t\t}\n\t\t\t\tdaemon.LogVolumeEvent(m.Volume.Name(), \"mount\", attributes)\n\t\t\t}\n\t\t\tmounts = append(mounts, mnt)\n\t\t}\n\t}\n\n\tmounts = sortMounts(mounts)\n\tnetMounts := c.NetworkMounts()\n\t\/\/ if we are going to mount any of the network files from container\n\t\/\/ metadata, the ownership must be set properly for potential container\n\t\/\/ remapped root (user namespaces)\n\trootUID, rootGID := daemon.GetRemappedUIDGID()\n\tfor _, mount := range netMounts {\n\t\tif err := os.Chown(mount.Source, rootUID, rootGID); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn append(mounts, netMounts...), nil\n}\n\n\/\/ sortMounts sorts an array of mounts in lexicographic order. This ensure that\n\/\/ when mounting, the mounts don't shadow other mounts. For example, if mounting\n\/\/ \/etc and \/etc\/resolv.conf, \/etc\/resolv.conf must not be mounted first.\nfunc sortMounts(m []container.Mount) []container.Mount {\n\tsort.Sort(mounts(m))\n\treturn m\n}\n\n\/\/ setBindModeIfNull is platform specific processing to ensure the\n\/\/ shared mode is set to 'z' if it is null. This is called in the case\n\/\/ of processing a named volume and not a typical bind.\nfunc setBindModeIfNull(bind *volume.MountPoint) {\n\tif bind.Mode == \"\" {\n\t\tbind.Mode = \"z\"\n\t}\n}\n\n\/\/ migrateVolume links the contents of a volume created pre Docker 1.7\n\/\/ into the location expected by the local driver.\n\/\/ It creates a symlink from DOCKER_ROOT\/vfs\/dir\/VOLUME_ID to DOCKER_ROOT\/volumes\/VOLUME_ID\/_container_data.\n\/\/ It preserves the volume json configuration generated pre Docker 1.7 to be able to\n\/\/ downgrade from Docker 1.7 to Docker 1.6 without losing volume compatibility.\nfunc migrateVolume(id, vfs string) error {\n\tl, err := volumedrivers.GetDriver(volume.DefaultDriverName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewDataPath := l.(*local.Root).DataPath(id)\n\tfi, err := os.Stat(newDataPath)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\tif fi != nil && fi.IsDir() {\n\t\treturn nil\n\t}\n\n\treturn os.Symlink(vfs, newDataPath)\n}\n\n\/\/ verifyVolumesInfo ports volumes configured for the containers pre docker 1.7.\n\/\/ It reads the container configuration and creates valid mount points for the old volumes.\nfunc (daemon *Daemon) verifyVolumesInfo(container *container.Container) error {\n\t\/\/ Inspect old structures only when we're upgrading from old versions\n\t\/\/ to versions >= 1.7 and the MountPoints has not been populated with volumes data.\n\ttype volumes struct {\n\t\tVolumes   map[string]string\n\t\tVolumesRW map[string]bool\n\t}\n\tcfgPath, err := container.ConfigPath()\n\tif err != nil {\n\t\treturn err\n\t}\n\tf, err := os.Open(cfgPath)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not open container config\")\n\t}\n\tvar cv volumes\n\tif err := json.NewDecoder(f).Decode(&cv); err != nil {\n\t\treturn errors.Wrap(err, \"could not decode container config\")\n\t}\n\n\tif len(container.MountPoints) == 0 && len(cv.Volumes) > 0 {\n\t\tfor destination, hostPath := range cv.Volumes {\n\t\t\tvfsPath := filepath.Join(daemon.root, \"vfs\", \"dir\")\n\t\t\trw := cv.VolumesRW != nil && cv.VolumesRW[destination]\n\n\t\t\tif strings.HasPrefix(hostPath, vfsPath) {\n\t\t\t\tid := filepath.Base(hostPath)\n\t\t\t\tv, err := daemon.volumes.CreateWithRef(id, volume.DefaultDriverName, container.ID, nil, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := migrateVolume(id, hostPath); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tcontainer.AddMountPointWithVolume(destination, v, true)\n\t\t\t} else { \/\/ Bind mount\n\t\t\t\tm := volume.MountPoint{Source: hostPath, Destination: destination, RW: rw}\n\t\t\t\tcontainer.MountPoints[destination] = &m\n\t\t\t}\n\t\t}\n\t\treturn container.ToDisk()\n\t}\n\treturn nil\n}\n\nfunc (daemon *Daemon) mountVolumes(container *container.Container) error {\n\tmounts, err := daemon.setupMounts(container)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, m := range mounts {\n\t\tdest, err := container.GetResourcePath(m.Destination)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar stat os.FileInfo\n\t\tstat, err = os.Stat(m.Source)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\topts := \"rbind,ro\"\n\t\tif m.Writable {\n\t\t\topts = \"rbind,rw\"\n\t\t}\n\n\t\tif err := mount.Mount(m.Source, dest, bindMountType, opts); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ mountVolumes() seems to be called for temporary mounts\n\t\t\/\/ outside the container. Soon these will be unmounted with\n\t\t\/\/ lazy unmount option and given we have mounted the rbind,\n\t\t\/\/ all the submounts will propagate if these are shared. If\n\t\t\/\/ daemon is running in host namespace and has \/ as shared\n\t\t\/\/ then these unmounts will propagate and unmount original\n\t\t\/\/ mount as well. So make all these mounts rprivate.\n\t\t\/\/ Do not use propagation property of volume as that should\n\t\t\/\/ apply only when mounting happen inside the container.\n\t\tif err := mount.MakeRPrivate(dest); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>close the file<commit_after>\/\/ +build !windows\n\n\/\/ TODO(amitkris): We need to split this file for solaris.\n\npackage daemon\n\nimport (\n\t\"encoding\/json\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/docker\/docker\/container\"\n\t\"github.com\/docker\/docker\/pkg\/fileutils\"\n\t\"github.com\/docker\/docker\/pkg\/mount\"\n\t\"github.com\/docker\/docker\/volume\"\n\t\"github.com\/docker\/docker\/volume\/drivers\"\n\t\"github.com\/docker\/docker\/volume\/local\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ setupMounts iterates through each of the mount points for a container and\n\/\/ calls Setup() on each. It also looks to see if is a network mount such as\n\/\/ \/etc\/resolv.conf, and if it is not, appends it to the array of mounts.\nfunc (daemon *Daemon) setupMounts(c *container.Container) ([]container.Mount, error) {\n\tvar mounts []container.Mount\n\t\/\/ TODO: tmpfs mounts should be part of Mountpoints\n\ttmpfsMounts := make(map[string]bool)\n\ttmpfsMountInfo, err := c.TmpfsMounts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, m := range tmpfsMountInfo {\n\t\ttmpfsMounts[m.Destination] = true\n\t}\n\tfor _, m := range c.MountPoints {\n\t\tif tmpfsMounts[m.Destination] {\n\t\t\tcontinue\n\t\t}\n\t\tif err := daemon.lazyInitializeVolume(c.ID, m); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trootUID, rootGID := daemon.GetRemappedUIDGID()\n\t\tpath, err := m.Setup(c.MountLabel, rootUID, rootGID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !c.TrySetNetworkMount(m.Destination, path) {\n\t\t\tmnt := container.Mount{\n\t\t\t\tSource:      path,\n\t\t\t\tDestination: m.Destination,\n\t\t\t\tWritable:    m.RW,\n\t\t\t\tPropagation: string(m.Propagation),\n\t\t\t}\n\t\t\tif m.Volume != nil {\n\t\t\t\tattributes := map[string]string{\n\t\t\t\t\t\"driver\":      m.Volume.DriverName(),\n\t\t\t\t\t\"container\":   c.ID,\n\t\t\t\t\t\"destination\": m.Destination,\n\t\t\t\t\t\"read\/write\":  strconv.FormatBool(m.RW),\n\t\t\t\t\t\"propagation\": string(m.Propagation),\n\t\t\t\t}\n\t\t\t\tdaemon.LogVolumeEvent(m.Volume.Name(), \"mount\", attributes)\n\t\t\t}\n\t\t\tmounts = append(mounts, mnt)\n\t\t}\n\t}\n\n\tmounts = sortMounts(mounts)\n\tnetMounts := c.NetworkMounts()\n\t\/\/ if we are going to mount any of the network files from container\n\t\/\/ metadata, the ownership must be set properly for potential container\n\t\/\/ remapped root (user namespaces)\n\trootUID, rootGID := daemon.GetRemappedUIDGID()\n\tfor _, mount := range netMounts {\n\t\tif err := os.Chown(mount.Source, rootUID, rootGID); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn append(mounts, netMounts...), nil\n}\n\n\/\/ sortMounts sorts an array of mounts in lexicographic order. This ensure that\n\/\/ when mounting, the mounts don't shadow other mounts. For example, if mounting\n\/\/ \/etc and \/etc\/resolv.conf, \/etc\/resolv.conf must not be mounted first.\nfunc sortMounts(m []container.Mount) []container.Mount {\n\tsort.Sort(mounts(m))\n\treturn m\n}\n\n\/\/ setBindModeIfNull is platform specific processing to ensure the\n\/\/ shared mode is set to 'z' if it is null. This is called in the case\n\/\/ of processing a named volume and not a typical bind.\nfunc setBindModeIfNull(bind *volume.MountPoint) {\n\tif bind.Mode == \"\" {\n\t\tbind.Mode = \"z\"\n\t}\n}\n\n\/\/ migrateVolume links the contents of a volume created pre Docker 1.7\n\/\/ into the location expected by the local driver.\n\/\/ It creates a symlink from DOCKER_ROOT\/vfs\/dir\/VOLUME_ID to DOCKER_ROOT\/volumes\/VOLUME_ID\/_container_data.\n\/\/ It preserves the volume json configuration generated pre Docker 1.7 to be able to\n\/\/ downgrade from Docker 1.7 to Docker 1.6 without losing volume compatibility.\nfunc migrateVolume(id, vfs string) error {\n\tl, err := volumedrivers.GetDriver(volume.DefaultDriverName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewDataPath := l.(*local.Root).DataPath(id)\n\tfi, err := os.Stat(newDataPath)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn err\n\t}\n\n\tif fi != nil && fi.IsDir() {\n\t\treturn nil\n\t}\n\n\treturn os.Symlink(vfs, newDataPath)\n}\n\n\/\/ verifyVolumesInfo ports volumes configured for the containers pre docker 1.7.\n\/\/ It reads the container configuration and creates valid mount points for the old volumes.\nfunc (daemon *Daemon) verifyVolumesInfo(container *container.Container) error {\n\t\/\/ Inspect old structures only when we're upgrading from old versions\n\t\/\/ to versions >= 1.7 and the MountPoints has not been populated with volumes data.\n\ttype volumes struct {\n\t\tVolumes   map[string]string\n\t\tVolumesRW map[string]bool\n\t}\n\tcfgPath, err := container.ConfigPath()\n\tif err != nil {\n\t\treturn err\n\t}\n\tf, err := os.Open(cfgPath)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not open container config\")\n\t}\n\tdefer f.Close()\n\tvar cv volumes\n\tif err := json.NewDecoder(f).Decode(&cv); err != nil {\n\t\treturn errors.Wrap(err, \"could not decode container config\")\n\t}\n\n\tif len(container.MountPoints) == 0 && len(cv.Volumes) > 0 {\n\t\tfor destination, hostPath := range cv.Volumes {\n\t\t\tvfsPath := filepath.Join(daemon.root, \"vfs\", \"dir\")\n\t\t\trw := cv.VolumesRW != nil && cv.VolumesRW[destination]\n\n\t\t\tif strings.HasPrefix(hostPath, vfsPath) {\n\t\t\t\tid := filepath.Base(hostPath)\n\t\t\t\tv, err := daemon.volumes.CreateWithRef(id, volume.DefaultDriverName, container.ID, nil, nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := migrateVolume(id, hostPath); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tcontainer.AddMountPointWithVolume(destination, v, true)\n\t\t\t} else { \/\/ Bind mount\n\t\t\t\tm := volume.MountPoint{Source: hostPath, Destination: destination, RW: rw}\n\t\t\t\tcontainer.MountPoints[destination] = &m\n\t\t\t}\n\t\t}\n\t\treturn container.ToDisk()\n\t}\n\treturn nil\n}\n\nfunc (daemon *Daemon) mountVolumes(container *container.Container) error {\n\tmounts, err := daemon.setupMounts(container)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, m := range mounts {\n\t\tdest, err := container.GetResourcePath(m.Destination)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar stat os.FileInfo\n\t\tstat, err = os.Stat(m.Source)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\topts := \"rbind,ro\"\n\t\tif m.Writable {\n\t\t\topts = \"rbind,rw\"\n\t\t}\n\n\t\tif err := mount.Mount(m.Source, dest, bindMountType, opts); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ mountVolumes() seems to be called for temporary mounts\n\t\t\/\/ outside the container. Soon these will be unmounted with\n\t\t\/\/ lazy unmount option and given we have mounted the rbind,\n\t\t\/\/ all the submounts will propagate if these are shared. If\n\t\t\/\/ daemon is running in host namespace and has \/ as shared\n\t\t\/\/ then these unmounts will propagate and unmount original\n\t\t\/\/ mount as well. So make all these mounts rprivate.\n\t\t\/\/ Do not use propagation property of volume as that should\n\t\t\/\/ apply only when mounting happen inside the container.\n\t\tif err := mount.MakeRPrivate(dest); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bitbucket.org\/kardianos\/osext\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/ethereum\/eth-go\/ethlog\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n)\n\nvar Identifier string\nvar StartRpc bool\nvar RpcPort int\nvar UseUPnP bool\nvar OutboundPort string\nvar ShowGenesis bool\nvar AddPeer string\nvar MaxPeer int\nvar GenAddr bool\nvar UseSeed bool\nvar ImportKey string\nvar ExportKey bool\nvar NonInteractive bool\nvar Datadir string\nvar LogFile string\nvar ConfigFile string\nvar DebugFile string\nvar LogLevel int\n\n\/\/ flags specific to gui client\nvar AssetPath string\n\nfunc defaultAssetPath() string {\n\tvar assetPath string\n\t\/\/ If the current working directory is the go-ethereum dir\n\t\/\/ assume a debug build and use the source directory as\n\t\/\/ asset directory.\n\tpwd, _ := os.Getwd()\n\tif pwd == path.Join(os.Getenv(\"GOPATH\"), \"src\", \"github.com\", \"ethereum\", \"go-ethereum\", \"ethereal\") {\n\t\tassetPath = path.Join(pwd, \"assets\")\n\t} else {\n\t\tswitch runtime.GOOS {\n\t\tcase \"darwin\":\n\t\t\t\/\/ Get Binary Directory\n\t\t\texedir, _ := osext.ExecutableFolder()\n\t\t\tassetPath = filepath.Join(exedir, \"..\/Resources\")\n\t\tcase \"linux\":\n\t\t\tassetPath = \"\/usr\/share\/ethereal\"\n\t\tcase \"window\":\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\tassetPath = \".\"\n\t\t}\n\t}\n\treturn assetPath\n}\n\nfunc defaultDataDir() string {\n\tusr, _ := user.Current()\n\treturn path.Join(usr.HomeDir, \".ethereal\")\n}\n\nvar defaultConfigFile = path.Join(defaultDataDir(), \"conf.ini\")\n\nfunc Init() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"%s [options] [filename]:\\noptions precedence: default < config file < environment variables < command line\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\n\tflag.StringVar(&Identifier, \"id\", \"\", \"Custom client identifier\")\n\tflag.StringVar(&OutboundPort, \"port\", \"30303\", \"listening port\")\n\tflag.BoolVar(&UseUPnP, \"upnp\", false, \"enable UPnP support\")\n\tflag.IntVar(&MaxPeer, \"maxpeer\", 10, \"maximum desired peers\")\n\tflag.IntVar(&RpcPort, \"rpcport\", 8080, \"port to start json-rpc server on\")\n\tflag.BoolVar(&StartRpc, \"rpc\", false, \"start rpc server\")\n\tflag.BoolVar(&NonInteractive, \"y\", false, \"non-interactive mode (say yes to confirmations)\")\n\tflag.BoolVar(&UseSeed, \"seed\", true, \"seed peers\")\n\tflag.BoolVar(&GenAddr, \"genaddr\", false, \"create a new priv\/pub key\")\n\tflag.BoolVar(&ExportKey, \"export\", false, \"export private key\")\n\tflag.StringVar(&LogFile, \"logfile\", \"\", \"log file (defaults to standard output)\")\n\tflag.StringVar(&ImportKey, \"import\", \"\", \"imports the given private key (hex)\")\n\tflag.StringVar(&Datadir, \"datadir\", defaultDataDir(), \"specifies the datadir to use\")\n\tflag.StringVar(&ConfigFile, \"conf\", defaultConfigFile, \"config file\")\n\tflag.StringVar(&DebugFile, \"debug\", \"\", \"debug file (no debugging if not set)\")\n\tflag.IntVar(&LogLevel, \"loglevel\", int(ethlog.InfoLevel), \"loglevel: 0-5: silent,error,warn,info,debug,debug detail)\")\n\n\tflag.StringVar(&AssetPath, \"asset_path\", defaultAssetPath(), \"absolute path to GUI assets directory\")\n\n\tflag.Parse()\n}\n<commit_msg>new command line options - keyring: keyring\/session identifier used by key manager - keystore: choice of db\/file key storage - import message updated - export: name of directory to export keys to (was bool)<commit_after>package main\n\nimport (\n\t\"bitbucket.org\/kardianos\/osext\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/ethereum\/eth-go\/ethlog\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n)\n\nvar Identifier string\nvar KeyRing string\nvar KeyStore string\nvar StartRpc bool\nvar RpcPort int\nvar UseUPnP bool\nvar OutboundPort string\nvar ShowGenesis bool\nvar AddPeer string\nvar MaxPeer int\nvar GenAddr bool\nvar UseSeed bool\nvar SecretFile string\nvar ExportDir string\nvar NonInteractive bool\nvar Datadir string\nvar LogFile string\nvar ConfigFile string\nvar DebugFile string\nvar LogLevel int\n\n\/\/ flags specific to gui client\nvar AssetPath string\n\nfunc defaultAssetPath() string {\n\tvar assetPath string\n\t\/\/ If the current working directory is the go-ethereum dir\n\t\/\/ assume a debug build and use the source directory as\n\t\/\/ asset directory.\n\tpwd, _ := os.Getwd()\n\tif pwd == path.Join(os.Getenv(\"GOPATH\"), \"src\", \"github.com\", \"ethereum\", \"go-ethereum\", \"ethereal\") {\n\t\tassetPath = path.Join(pwd, \"assets\")\n\t} else {\n\t\tswitch runtime.GOOS {\n\t\tcase \"darwin\":\n\t\t\t\/\/ Get Binary Directory\n\t\t\texedir, _ := osext.ExecutableFolder()\n\t\t\tassetPath = filepath.Join(exedir, \"..\/Resources\")\n\t\tcase \"linux\":\n\t\t\tassetPath = \"\/usr\/share\/ethereal\"\n\t\tcase \"window\":\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\tassetPath = \".\"\n\t\t}\n\t}\n\treturn assetPath\n}\n\nfunc defaultDataDir() string {\n\tusr, _ := user.Current()\n\treturn path.Join(usr.HomeDir, \".ethereal\")\n}\n\nvar defaultConfigFile = path.Join(defaultDataDir(), \"conf.ini\")\n\nfunc Init() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"%s [options] [filename]:\\noptions precedence: default < config file < environment variables < command line\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\n\tflag.StringVar(&Identifier, \"id\", \"\", \"Custom client identifier\")\n\tflag.StringVar(&KeyRing, \"keyring\", \"\", \"identifier for keyring to use\")\n\tflag.StringVar(&KeyStore, \"keystore\", \"db\", \"system to store keyrings: db|file (db)\")\n\tflag.StringVar(&OutboundPort, \"port\", \"30303\", \"listening port\")\n\tflag.BoolVar(&UseUPnP, \"upnp\", false, \"enable UPnP support\")\n\tflag.IntVar(&MaxPeer, \"maxpeer\", 10, \"maximum desired peers\")\n\tflag.IntVar(&RpcPort, \"rpcport\", 8080, \"port to start json-rpc server on\")\n\tflag.BoolVar(&StartRpc, \"rpc\", false, \"start rpc server\")\n\tflag.BoolVar(&NonInteractive, \"y\", false, \"non-interactive mode (say yes to confirmations)\")\n\tflag.BoolVar(&UseSeed, \"seed\", true, \"seed peers\")\n\tflag.BoolVar(&GenAddr, \"genaddr\", false, \"create a new priv\/pub key\")\n\tflag.StringVar(&SecretFile, \"import\", \"\", \"imports the file given (hex or mnemonic formats)\")\n\tflag.StringVar(&ExportDir, \"export\", \"\", \"exports the session keyring to files in the directory given\")\n\tflag.StringVar(&LogFile, \"logfile\", \"\", \"log file (defaults to standard output)\")\n\tflag.StringVar(&Datadir, \"datadir\", defaultDataDir(), \"specifies the datadir to use\")\n\tflag.StringVar(&ConfigFile, \"conf\", defaultConfigFile, \"config file\")\n\tflag.StringVar(&DebugFile, \"debug\", \"\", \"debug file (no debugging if not set)\")\n\tflag.IntVar(&LogLevel, \"loglevel\", int(ethlog.InfoLevel), \"loglevel: 0-5: silent,error,warn,info,debug,debug detail)\")\n\n\tflag.StringVar(&AssetPath, \"asset_path\", defaultAssetPath(), \"absolute path to GUI assets directory\")\n\n\tflag.Parse()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\/\/\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n)\n\nfunc readLine(scanner *bufio.Scanner) {\n\n\tscanner.Split(bufio.ScanLines)\n\n\tline := 0\n\n\tra, _ := regexp.Compile(\"[^\\\\s]\")\n\n\tfor scanner.Scan() {\n\t\tline += 1\n\t\tif line == 4 {\n\t\t\tfmt.Printf(\"%d: %v\\n\", line, ra.ReplaceAllString(scanner.Text(), \"-\"))\n\t\t} else {\n\t\t\tfmt.Printf(\"%d: %v\\n\", line, scanner.Text())\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}\n\nfunc Exists(name string) bool {\n\tif _, err := os.Stat(name); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\ntype replace_lines []int\n\nfunc main() {\n\n\t\/\/\tlines := flag.String()\n\n\tstat, _ := os.Stdin.Stat()\n\tif (stat.Mode() & os.ModeCharDevice) == 0 {\n\t\treadLine(bufio.NewScanner(os.Stdin))\n\t} else {\n\t\tif len(os.Args) > 1 {\n\n\t\t\tf := os.Args[1]\n\n\t\t\tfmt.Println(os.Args)\n\n\t\t\tif Exists(f) {\n\t\t\t\tfile, err := os.Open(f)\n\t\t\t\tdefer file.Close()\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\treadLine(bufio.NewScanner(file))\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>\tmodified:   gist.go<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc readLine(scanner *bufio.Scanner, replace_lines intslice) {\n\n\tscanner.Split(bufio.ScanLines)\n\n\tsort.Ints(replace_lines)\n\trl := removeDuplicates(replace_lines)\n\n\tfmt.Println(rl)\n\n\tline := 0\n\n\tra, _ := regexp.Compile(\"[^\\\\s]\")\n\n\tfor scanner.Scan() {\n\t\tline += 1\n\t\tif line == 4 {\n\t\t\tfmt.Printf(\"%d: %v\\n\", line, ra.ReplaceAllString(scanner.Text(), \"-\"))\n\t\t} else {\n\t\t\tfmt.Printf(\"%d: %v\\n\", line, scanner.Text())\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}\n\nfunc Exists(name string) bool {\n\tif _, err := os.Stat(name); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ slice of ints\ntype intslice []int\n\n\/\/ String is the method to format the flag's value.\nfunc (i *intslice) String() string {\n\treturn fmt.Sprint(*i)\n}\n\n\/\/ Set is the method to set the flag value, part of the flag.Value interface.\n\/\/ Set's argument is a string to be parsed to set the flag.\n\/\/ It's a comma-separated list, so we split it.\nfunc (i *intslice) Set(value string) error {\n\tif len(*i) > 0 {\n\t\treturn errors.New(\"line flag already set\")\n\t}\n\n\tfor _, ln := range strings.Split(value, \",\") {\n\t\t\/\/\n\t\t\/\/ try to sanitize input 1, 3,  7, 9\n\t\t\/\/fmt.Printf(\"[%s]\\n\", strings.TrimSpace(ln))\n\t\t\/\/\n\t\tline, err := strconv.Atoi(ln)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t*i = append(*i, line)\n\t}\n\n\treturn nil\n}\n\nfunc removeDuplicates(a []int) []int {\n\tresult := []int{}\n\tseen := map[int]int{}\n\tfor _, val := range a {\n\t\tif _, ok := seen[val]; !ok {\n\t\t\tresult = append(result, val)\n\t\t\tseen[val] = val\n\t\t}\n\t}\n\treturn result\n}\n\nvar replace_lines intslice\n\nfunc main() {\n\n\tflag.Var(&replace_lines, \"l\", \"Number of the line(s) to be replaced\")\n\n\tflag.Parse()\n\n\t\/\/\tif len(flag.Args()) == 0 {\n\tfmt.Println(\"--:\", flag.NArg(), flag.Args(), replace_lines)\n\t\/\/\t}\n\n\t\/\/if flag.NFlag() > 0 {\n\t\/\/fmt.Println(\"lines to be replaced:\")\n\t\/\/for i := 0; i < len(replace_lines); i++ {\n\t\/\/fmt.Printf(\"%d \", replace_lines[i])\n\t\/\/}\n\t\/\/}\n\n\tstat, _ := os.Stdin.Stat()\n\tif (stat.Mode() & os.ModeCharDevice) == 0 {\n\t\treadLine(bufio.NewScanner(os.Stdin), replace_lines)\n\t} else {\n\t\tif flag.NArg() > 0 {\n\n\t\t\tf := flag.Arg(0)\n\n\t\t\tif Exists(f) {\n\t\t\t\tfile, err := os.Open(f)\n\t\t\t\tdefer file.Close()\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\treadLine(bufio.NewScanner(file), replace_lines)\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>resource\/aws_cloudformation_stack_set_instance: Handle IAM eventual consistency retries during creation (#15173)<commit_after><|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/justincampbell\/zipcode\"\n\t\"github.com\/mlbright\/forecast\/v2\"\n)\n\nvar conditionIcons = map[string]string{\n\t\"clear-day\":           \"☀️\",\n\t\"clear-night\":         \"🌙\",\n\t\"cloudy\":              \"☁️\",\n\t\"fog\":                 \"🌁\",\n\t\"partly-cloudy-day\":   \"⛅️\",\n\t\"partly-cloudy-night\": \"🌙\",\n\t\"rain\":                \"☔️\",\n\t\"sleet\":               \"❄️ ☔️\",\n\t\"snow\":                \"❄️\",\n\t\"wind\":                \"🍃\",\n\t\"error\":               \"❗️\",\n}\n\nvar maxCacheAge, _ = time.ParseDuration(\"1h\")\n\nvar coordinates string\nvar key string\nvar tmpDir string\nvar zipCode string\n\nfunc init() {\n\tflag.StringVar(&coordinates, \"coordinates\", \"\", \"the coordinates, expressed as latitude,longitude\")\n\tflag.StringVar(&key, \"key\", os.Getenv(\"FORECAST_IO_API_KEY\"), \"your forecast.io API key\")\n\tflag.StringVar(&tmpDir, \"tmpdir\", os.TempDir(), \"the directory to use to store cached responses\")\n\tflag.StringVar(&zipCode, \"zipcode\", \"\", \"a USPS ZIP Code\")\n\n\tflag.Parse()\n}\n\nfunc main() {\n\tvar err error\n\tvar latitude string\n\tvar longitude string\n\n\tif key == \"\" {\n\t\texitWith(\"Please provide your forecast.io API key with -key, or set FORECAST_IO_API_KEY\", 1)\n\t}\n\n\tif zipCode != \"\" {\n\t\tcoord, err := zipcode.Lookup(zipCode)\n\t\tcheck(err)\n\t\tcoordinates = coord.String()\n\t}\n\n\tcoordinateParts := strings.Split(coordinates, \",\")\n\n\tif len(coordinateParts) != 2 {\n\t\texitWith(\"You must specify latitude and longitude like so: 39.95,-75.1667\", 1)\n\t}\n\n\tlatitude, longitude = coordinateParts[0], coordinateParts[1]\n\n\tcacheFilename := fmt.Sprintf(\"emoji-weather-%s-%s.json\", latitude, longitude)\n\tcacheFile := path.Join(tmpDir, cacheFilename)\n\n\tvar json []byte\n\n\tif isCacheStale(cacheFile) {\n\t\tjson, err = getForecast(key, latitude, longitude)\n\t\tcheck(err)\n\n\t\terr = writeCache(cacheFile, json)\n\t\tcheck(err)\n\t} else {\n\t\tjson, err = ioutil.ReadFile(cacheFile)\n\t\tcheck(err)\n\t}\n\n\tfmt.Println(formatConditions(extractConditionFromJSON(json)))\n}\n\nfunc isCacheStale(cacheFile string) bool {\n\tstat, err := os.Stat(cacheFile)\n\n\treturn os.IsNotExist(err) || time.Since(stat.ModTime()) > maxCacheAge\n}\n\nfunc getForecast(key string, latitude string, longitude string) (json []byte, err error) {\n\tres, err := forecast.GetResponse(key, latitude, longitude, \"now\", \"us\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tjson, err = ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn json, nil\n}\n\nfunc writeCache(cacheFile string, json []byte) (err error) {\n\treturn ioutil.WriteFile(cacheFile, json, 0644)\n}\n\nfunc formatConditions(condition string) (icon string) {\n\ticon, ok := conditionIcons[condition]\n\tif !ok {\n\t\ticon = condition\n\t}\n\treturn\n}\n\nfunc extractConditionFromJSON(jsonBlob []byte) (condition string) {\n\tf, err := forecast.FromJSON(jsonBlob)\n\n\tif err != nil {\n\t\treturn \"error\"\n\t}\n\n\tif f.Code > 0 {\n\t\treturn \"error\"\n\t}\n\n\treturn f.Currently.Icon\n}\n\nfunc exitWith(message interface{}, status int) {\n\tfmt.Printf(\"%v\\n\", message)\n\tos.Exit(status)\n}\n\nfunc check(err error) {\n\tif err != nil {\n\t\texitWith(err, 1)\n\t}\n}\n<commit_msg>Display helpful message when no location given<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/justincampbell\/zipcode\"\n\t\"github.com\/mlbright\/forecast\/v2\"\n)\n\nvar conditionIcons = map[string]string{\n\t\"clear-day\":           \"☀️\",\n\t\"clear-night\":         \"🌙\",\n\t\"cloudy\":              \"☁️\",\n\t\"fog\":                 \"🌁\",\n\t\"partly-cloudy-day\":   \"⛅️\",\n\t\"partly-cloudy-night\": \"🌙\",\n\t\"rain\":                \"☔️\",\n\t\"sleet\":               \"❄️ ☔️\",\n\t\"snow\":                \"❄️\",\n\t\"wind\":                \"🍃\",\n\t\"error\":               \"❗️\",\n}\n\nvar maxCacheAge, _ = time.ParseDuration(\"1h\")\n\nvar coordinates string\nvar key string\nvar tmpDir string\nvar zipCode string\n\nfunc init() {\n\tflag.StringVar(&coordinates, \"coordinates\", \"\", \"the coordinates, expressed as latitude,longitude\")\n\tflag.StringVar(&key, \"key\", os.Getenv(\"FORECAST_IO_API_KEY\"), \"your forecast.io API key\")\n\tflag.StringVar(&tmpDir, \"tmpdir\", os.TempDir(), \"the directory to use to store cached responses\")\n\tflag.StringVar(&zipCode, \"zipcode\", \"\", \"a USPS ZIP Code\")\n\n\tflag.Parse()\n}\n\nfunc main() {\n\tvar err error\n\tvar latitude string\n\tvar longitude string\n\n\tif key == \"\" {\n\t\texitWith(\"Please provide your forecast.io API key with -key, or set FORECAST_IO_API_KEY\", 1)\n\t}\n\n\tif coordinates == \"\" && zipCode == \"\" {\n\t\texitWith(\"Please provide a -zipcode or -coordinates\", 1)\n\t}\n\n\tif zipCode != \"\" {\n\t\tcoord, err := zipcode.Lookup(zipCode)\n\t\tcheck(err)\n\t\tcoordinates = coord.String()\n\t}\n\n\tcoordinateParts := strings.Split(coordinates, \",\")\n\n\tif len(coordinateParts) != 2 {\n\t\texitWith(\"You must specify latitude and longitude like so: 39.95,-75.1667\", 1)\n\t}\n\n\tlatitude, longitude = coordinateParts[0], coordinateParts[1]\n\n\tcacheFilename := fmt.Sprintf(\"emoji-weather-%s-%s.json\", latitude, longitude)\n\tcacheFile := path.Join(tmpDir, cacheFilename)\n\n\tvar json []byte\n\n\tif isCacheStale(cacheFile) {\n\t\tjson, err = getForecast(key, latitude, longitude)\n\t\tcheck(err)\n\n\t\terr = writeCache(cacheFile, json)\n\t\tcheck(err)\n\t} else {\n\t\tjson, err = ioutil.ReadFile(cacheFile)\n\t\tcheck(err)\n\t}\n\n\tfmt.Println(formatConditions(extractConditionFromJSON(json)))\n}\n\nfunc isCacheStale(cacheFile string) bool {\n\tstat, err := os.Stat(cacheFile)\n\n\treturn os.IsNotExist(err) || time.Since(stat.ModTime()) > maxCacheAge\n}\n\nfunc getForecast(key string, latitude string, longitude string) (json []byte, err error) {\n\tres, err := forecast.GetResponse(key, latitude, longitude, \"now\", \"us\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tjson, err = ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn json, nil\n}\n\nfunc writeCache(cacheFile string, json []byte) (err error) {\n\treturn ioutil.WriteFile(cacheFile, json, 0644)\n}\n\nfunc formatConditions(condition string) (icon string) {\n\ticon, ok := conditionIcons[condition]\n\tif !ok {\n\t\ticon = condition\n\t}\n\treturn\n}\n\nfunc extractConditionFromJSON(jsonBlob []byte) (condition string) {\n\tf, err := forecast.FromJSON(jsonBlob)\n\n\tif err != nil {\n\t\treturn \"error\"\n\t}\n\n\tif f.Code > 0 {\n\t\treturn \"error\"\n\t}\n\n\treturn f.Currently.Icon\n}\n\nfunc exitWith(message interface{}, status int) {\n\tfmt.Printf(\"%v\\n\", message)\n\tos.Exit(status)\n}\n\nfunc check(err error) {\n\tif err != nil {\n\t\texitWith(err, 1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"log\"\n\t\"net\/http\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/getlantern\/analytics\"\n\t\"github.com\/getlantern\/flashlight\/client\"\n\t\"github.com\/getlantern\/flashlight\/globals\"\n\t\"github.com\/getlantern\/flashlight\/util\"\n)\n\nconst (\n\tcloudConfigPollInterval = time.Second * 60\n)\n\n\/\/ clientConfig holds global configuration settings for all clients.\nvar (\n\tclientConfig  *config\n\ttrackingCodes = map[string]string{\n\t\t\"FireTweet\": \"UA-21408036-4\",\n\t}\n)\n\n\/\/ MobileClient is an extension of flashlight client with a few custom declarations for mobile\ntype MobileClient struct {\n\tclient.Client\n\tclosed  chan bool\n\tfronter *http.Client\n}\n\n\/\/ init attempts to setup client configuration.\nfunc init() {\n\tclientConfig = defaultConfig()\n}\n\n\/\/ NewClient creates a proxy client.\nfunc NewClient(addr, appName string) *MobileClient {\n\n\tclient := client.Client{\n\t\tAddr:         addr,\n\t\tReadTimeout:  0, \/\/ don't timeout\n\t\tWriteTimeout: 0,\n\t}\n\n\terr := globals.SetTrustedCAs(clientConfig.getTrustedCerts())\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to configure trusted CAs: %s\", err)\n\t}\n\n\thqfd := client.Configure(clientConfig.Client)\n\n\t\/\/ store GA session event\n\tsessionPayload := &analytics.Payload{\n\t\tHitType: analytics.EventType,\n\t\tEvent: &analytics.Event{\n\t\t\tCategory: \"Session\",\n\t\t\tAction:   \"Start\",\n\t\t\tLabel:    runtime.GOOS,\n\t\t},\n\t}\n\n\t\/\/ attach our app-specific analytics tracking code\n\t\/\/ to session info\n\tif appName != \"\" {\n\t\tif trackingId, ok := trackingCodes[appName]; ok {\n\t\t\tsessionPayload.TrackingId = trackingId\n\t\t}\n\t}\n\n\thttpClient, er := util.HTTPClient(cfg.CloudConfigCA, cfg.Addr)\n\tif er != nil {\n\t\tlog.Errorf(\"Could not create HTTP client %v\", er)\n\t} else {\n\t\tanalytics.SessionEvent(httpClient, sessionPayload)\n\t}\n\n\treturn &MobileClient{\n\t\tClient:  client,\n\t\tclosed:  make(chan bool),\n\t\tfronter: hqfd.NewDirectDomainFronter(),\n\t}\n}\n\nfunc (client *MobileClient) ServeHTTP() {\n\n\tdefer func() {\n\t\tclose(client.closed)\n\t}()\n\n\tgo func() {\n\t\tonListening := func() {\n\t\t\tlog.Printf(\"Now listening for connections...\")\n\t\t}\n\t\tif err := client.ListenAndServe(onListening); err != nil {\n\t\t\t\/\/ Error is not exported: https:\/\/golang.org\/src\/net\/net.go#L284\n\t\t\tif !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\t\tpanic(err.Error())\n\t\t\t}\n\t\t}\n\t}()\n\tgo client.pollConfiguration()\n}\n\n\/\/ updateConfig attempts to pull a configuration file from the network using\n\/\/ the client proxy itself.\nfunc (client *MobileClient) updateConfig() error {\n\tvar buf []byte\n\tvar err error\n\tif buf, err = pullConfigFile(client.fronter); err != nil {\n\t\treturn err\n\t}\n\treturn clientConfig.updateFrom(buf)\n}\n\n\/\/ pollConfiguration periodically checks for updates in the cloud configuration\n\/\/ file.\nfunc (client *MobileClient) pollConfiguration() {\n\tpollTimer := time.NewTimer(cloudConfigPollInterval)\n\tdefer pollTimer.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-client.closed:\n\t\t\treturn\n\t\tcase <-pollTimer.C:\n\t\t\t\/\/ Attempt to update configuration.\n\t\t\tvar err error\n\t\t\tif err = client.updateConfig(); err == nil {\n\t\t\t\t\/\/ Configuration changed, lets reload.\n\t\t\t\terr := globals.SetTrustedCAs(clientConfig.getTrustedCerts())\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Unable to configure trusted CAs: %s\", err)\n\t\t\t\t}\n\t\t\t\thqfc := client.Configure(clientConfig.Client)\n\t\t\t\tclient.fronter = hqfc.NewDirectDomainFronter()\n\t\t\t}\n\t\t\t\/\/ Sleeping 'till next pull.\n\t\t\tpollTimer.Reset(cloudConfigPollInterval)\n\t\t}\n\t}\n}\n\n\/\/ Stop is currently not implemented but should make the listener stop\n\/\/ accepting new connections and then kill all active connections.\nfunc (client *MobileClient) Stop() error {\n\tif err := client.Client.Stop(); err != nil {\n\t\tlog.Fatalf(\"Unable to stop proxy client: %q\", err)\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>Changed to record analytics only after the local server is definitely up and running #2540<commit_after>package client\n\nimport (\n\t\"log\"\n\t\"net\/http\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/getlantern\/analytics\"\n\t\"github.com\/getlantern\/flashlight\/client\"\n\t\"github.com\/getlantern\/flashlight\/globals\"\n\t\"github.com\/getlantern\/flashlight\/util\"\n)\n\nconst (\n\tcloudConfigPollInterval = time.Second * 60\n)\n\n\/\/ clientConfig holds global configuration settings for all clients.\nvar (\n\tclientConfig  *config\n\ttrackingCodes = map[string]string{\n\t\t\"FireTweet\": \"UA-21408036-4\",\n\t}\n)\n\n\/\/ MobileClient is an extension of flashlight client with a few custom declarations for mobile\ntype MobileClient struct {\n\tclient.Client\n\tclosed  chan bool\n\tfronter *http.Client\n\tappName string\n}\n\n\/\/ init attempts to setup client configuration.\nfunc init() {\n\tclientConfig = defaultConfig()\n}\n\n\/\/ NewClient creates a proxy client.\nfunc NewClient(addr, appName string) *MobileClient {\n\n\tclient := client.Client{\n\t\tAddr:         addr,\n\t\tReadTimeout:  0, \/\/ don't timeout\n\t\tWriteTimeout: 0,\n\t}\n\n\terr := globals.SetTrustedCAs(clientConfig.getTrustedCerts())\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to configure trusted CAs: %s\", err)\n\t}\n\n\thqfd := client.Configure(clientConfig.Client)\n\n\treturn &MobileClient{\n\t\tClient:  client,\n\t\tclosed:  make(chan bool),\n\t\tfronter: hqfd.NewDirectDomainFronter(),\n\t\tappName: appName,\n\t}\n}\n\nfunc (client *MobileClient) ServeHTTP() {\n\n\tdefer func() {\n\t\tclose(client.closed)\n\t}()\n\n\tgo func() {\n\t\tonListening := func() {\n\t\t\tlog.Printf(\"Now listening for connections...\")\n\t\t\tgo client.recordAnalytics()\n\t\t}\n\t\tif err := client.ListenAndServe(onListening); err != nil {\n\t\t\t\/\/ Error is not exported: https:\/\/golang.org\/src\/net\/net.go#L284\n\t\t\tif !strings.Contains(err.Error(), \"use of closed network connection\") {\n\t\t\t\tpanic(err.Error())\n\t\t\t}\n\t\t}\n\t}()\n\tgo client.pollConfiguration()\n}\n\nfunc (client *MobileClient) recordAnalytics() {\n\n\t\/\/ store GA session event\n\tsessionPayload := &analytics.Payload{\n\t\tHitType: analytics.EventType,\n\t\tEvent: &analytics.Event{\n\t\t\tCategory: \"Session\",\n\t\t\tAction:   \"Start\",\n\t\t\tLabel:    runtime.GOOS,\n\t\t},\n\t}\n\n\t\/\/ attach our app-specific analytics tracking code\n\t\/\/ to session info\n\tif client.appName != \"\" {\n\t\tif trackingId, ok := trackingCodes[client.appName]; ok {\n\t\t\tsessionPayload.TrackingId = trackingId\n\t\t}\n\t}\n\n\t\/\/ Report analytics, proxying through the local client. Note this\n\t\/\/ is a little unorthodox by Lantern standards because it doesn't\n\t\/\/ pin the certificate of the cloud.yaml root CA, instead relying\n\t\/\/ on the go defaults.\n\thttpClient, er := util.HTTPClient(\"\", client.Client.Addr)\n\tif er != nil {\n\t\tlog.Fatalf(\"Could not create HTTP client %v\", er)\n\t} else {\n\t\tanalytics.SessionEvent(httpClient, sessionPayload)\n\t}\n\n}\n\n\/\/ updateConfig attempts to pull a configuration file from the network using\n\/\/ the client proxy itself.\nfunc (client *MobileClient) updateConfig() error {\n\tvar buf []byte\n\tvar err error\n\tif buf, err = pullConfigFile(client.fronter); err != nil {\n\t\treturn err\n\t}\n\treturn clientConfig.updateFrom(buf)\n}\n\n\/\/ pollConfiguration periodically checks for updates in the cloud configuration\n\/\/ file.\nfunc (client *MobileClient) pollConfiguration() {\n\tpollTimer := time.NewTimer(cloudConfigPollInterval)\n\tdefer pollTimer.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-client.closed:\n\t\t\treturn\n\t\tcase <-pollTimer.C:\n\t\t\t\/\/ Attempt to update configuration.\n\t\t\tvar err error\n\t\t\tif err = client.updateConfig(); err == nil {\n\t\t\t\t\/\/ Configuration changed, lets reload.\n\t\t\t\terr := globals.SetTrustedCAs(clientConfig.getTrustedCerts())\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Unable to configure trusted CAs: %s\", err)\n\t\t\t\t}\n\t\t\t\thqfc := client.Configure(clientConfig.Client)\n\t\t\t\tclient.fronter = hqfc.NewDirectDomainFronter()\n\t\t\t}\n\t\t\t\/\/ Sleeping 'till next pull.\n\t\t\tpollTimer.Reset(cloudConfigPollInterval)\n\t\t}\n\t}\n}\n\n\/\/ Stop is currently not implemented but should make the listener stop\n\/\/ accepting new connections and then kill all active connections.\nfunc (client *MobileClient) Stop() error {\n\tif err := client.Client.Stop(); err != nil {\n\t\tlog.Fatalf(\"Unable to stop proxy client: %q\", err)\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package websocket\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/apex\/log\"\n\t\"github.com\/gbrlsnchs\/jwt\/v3\"\n\t\"github.com\/google\/uuid\"\n\t\"github.com\/gorilla\/websocket\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/pterodactyl\/wings\/config\"\n\t\"github.com\/pterodactyl\/wings\/environment\"\n\t\"github.com\/pterodactyl\/wings\/router\/tokens\"\n\t\"github.com\/pterodactyl\/wings\/server\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tPermissionConnect          = \"websocket.connect\"\n\tPermissionSendCommand      = \"control.console\"\n\tPermissionSendPowerStart   = \"control.start\"\n\tPermissionSendPowerStop    = \"control.stop\"\n\tPermissionSendPowerRestart = \"control.restart\"\n\tPermissionReceiveErrors    = \"admin.websocket.errors\"\n\tPermissionReceiveInstall   = \"admin.websocket.install\"\n\tPermissionReceiveBackups   = \"backup.read\"\n)\n\ntype Handler struct {\n\tsync.RWMutex\n\tConnection *websocket.Conn\n\tjwt        *tokens.WebsocketPayload `json:\"-\"`\n\tserver     *server.Server\n}\n\nvar (\n\tErrJwtNotPresent    = errors.New(\"jwt: no jwt present\")\n\tErrJwtNoConnectPerm = errors.New(\"jwt: missing connect permission\")\n\tErrJwtUuidMismatch  = errors.New(\"jwt: server uuid mismatch\")\n)\n\nfunc IsJwtError(err error) bool {\n\treturn errors.Is(err, ErrJwtNotPresent) ||\n\t\terrors.Is(err, ErrJwtNoConnectPerm) ||\n\t\terrors.Is(err, ErrJwtUuidMismatch) ||\n\t\terrors.Is(err, jwt.ErrExpValidation)\n}\n\n\/\/ Parses a JWT into a websocket token payload.\nfunc NewTokenPayload(token []byte) (*tokens.WebsocketPayload, error) {\n\tpayload := tokens.WebsocketPayload{}\n\terr := tokens.ParseToken(token, &payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !payload.HasPermission(PermissionConnect) {\n\t\treturn nil, errors.New(\"not authorized to connect to this socket\")\n\t}\n\n\treturn &payload, nil\n}\n\n\/\/ Returns a new websocket handler using the context provided.\nfunc GetHandler(s *server.Server, w http.ResponseWriter, r *http.Request) (*Handler, error) {\n\tupgrader := websocket.Upgrader{\n\t\t\/\/ Ensure that the websocket request is originating from the Panel itself,\n\t\t\/\/ and not some other location.\n\t\tCheckOrigin: func(r *http.Request) bool {\n\t\t\to := r.Header.Get(\"Origin\")\n\t\t\tif o == config.Get().PanelLocation {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tfor _, origin := range config.Get().AllowedOrigins {\n\t\t\t\tif origin == \"*\" {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\tif o != origin {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\treturn false\n\t\t},\n\t}\n\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Handler{\n\t\tConnection: conn,\n\t\tjwt:        nil,\n\t\tserver:     s,\n\t}, nil\n}\n\nfunc (h *Handler) SendJson(v *Message) error {\n\t\/\/ Do not send JSON down the line if the JWT on the connection is not valid!\n\tif err := h.TokenValid(); err != nil {\n\t\th.unsafeSendJson(Message{\n\t\t\tEvent: ErrorEvent,\n\t\t\tArgs:  []string{\"could not authenticate client: \" + err.Error()},\n\t\t})\n\n\t\treturn nil\n\t}\n\n\tj := h.GetJwt()\n\tif j != nil {\n\t\t\/\/ If we're sending installation output but the user does not have the required\n\t\t\/\/ permissions to see the output, don't send it down the line.\n\t\tif v.Event == server.InstallOutputEvent {\n\t\t\tif !j.HasPermission(PermissionReceiveInstall) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If the user does not have permission to see backup events, do not emit\n\t\t\/\/ them over the socket.\n\t\tif strings.HasPrefix(v.Event, server.BackupCompletedEvent) {\n\t\t\tif !j.HasPermission(PermissionReceiveBackups) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn h.unsafeSendJson(v)\n}\n\n\/\/ Sends JSON over the websocket connection, ignoring the authentication state of the\n\/\/ socket user. Do not call this directly unless you are positive a response should be\n\/\/ sent back to the client!\nfunc (h *Handler) unsafeSendJson(v interface{}) error {\n\th.Lock()\n\tdefer h.Unlock()\n\n\treturn h.Connection.WriteJSON(v)\n}\n\n\/\/ Checks if the JWT is still valid.\nfunc (h *Handler) TokenValid() error {\n\tj := h.GetJwt()\n\tif j == nil {\n\t\treturn ErrJwtNotPresent\n\t}\n\n\tif err := jwt.ExpirationTimeValidator(time.Now())(&j.Payload); err != nil {\n\t\treturn err\n\t}\n\n\tif !j.HasPermission(PermissionConnect) {\n\t\treturn ErrJwtNoConnectPerm\n\t}\n\n\tif h.server.Id() != j.GetServerUuid() {\n\t\treturn ErrJwtUuidMismatch\n\t}\n\n\treturn nil\n}\n\n\/\/ Sends an error back to the connected websocket instance by checking the permissions\n\/\/ of the token. If the user has the \"receive-errors\" grant we will send back the actual\n\/\/ error message, otherwise we just send back a standard error message.\nfunc (h *Handler) SendErrorJson(msg Message, err error, shouldLog ...bool) error {\n\tj := h.GetJwt()\n\texpected := errors.Is(err, server.ErrSuspended) ||\n\t\terrors.Is(err, server.ErrIsRunning) ||\n\t\terrors.Is(err, server.ErrNotEnoughDiskSpace)\n\n\tmessage := \"an unexpected error was encountered while handling this request\"\n\tif expected || (j != nil && j.HasPermission(PermissionReceiveErrors)) {\n\t\tmessage = err.Error()\n\t}\n\n\tm, u := h.GetErrorMessage(message)\n\n\twsm := Message{Event: ErrorEvent}\n\twsm.Args = []string{m}\n\n\tif len(shouldLog) == 0 || (len(shouldLog) == 1 && shouldLog[0] == true) {\n\t\tif !expected && !IsJwtError(err) {\n\t\t\th.server.Log().WithFields(log.Fields{\"event\": msg.Event, \"error_identifier\": u.String(), \"error\": err}).\n\t\t\t\tError(\"failed to handle websocket process; an error was encountered processing an event\")\n\t\t}\n\t}\n\n\treturn h.unsafeSendJson(wsm)\n}\n\n\/\/ Converts an error message into a more readable representation and returns a UUID\n\/\/ that can be cross-referenced to find the specific error that triggered.\nfunc (h *Handler) GetErrorMessage(msg string) (string, uuid.UUID) {\n\tu := uuid.Must(uuid.NewRandom())\n\n\tm := fmt.Sprintf(\"Error Event [%s]: %s\", u.String(), msg)\n\n\treturn m, u\n}\n\n\/\/ Sets the JWT for the websocket in a race-safe manner.\nfunc (h *Handler) setJwt(token *tokens.WebsocketPayload) {\n\th.Lock()\n\th.jwt = token\n\th.Unlock()\n}\n\nfunc (h *Handler) GetJwt() *tokens.WebsocketPayload {\n\th.RLock()\n\tdefer h.RUnlock()\n\n\treturn h.jwt\n}\n\n\/\/ Handle the inbound socket request and route it to the proper server action.\nfunc (h *Handler) HandleInbound(m Message) error {\n\tif m.Event != AuthenticationEvent {\n\t\tif err := h.TokenValid(); err != nil {\n\t\t\th.unsafeSendJson(Message{\n\t\t\t\tEvent: ErrorEvent,\n\t\t\t\tArgs:  []string{\"could not authenticate client: \" + err.Error()},\n\t\t\t})\n\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tswitch m.Event {\n\tcase AuthenticationEvent:\n\t\t{\n\t\t\ttoken, err := NewTokenPayload([]byte(strings.Join(m.Args, \"\")))\n\t\t\tif err != nil {\n\t\t\t\t\/\/ If the error says the JWT expired, send a token expired\n\t\t\t\t\/\/ event and hopefully the client renews the token.\n\t\t\t\tif err == jwt.ErrExpValidation {\n\t\t\t\t\th.SendJson(&Message{Event: TokenExpiredEvent})\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ Check if the user has previously authenticated successfully.\n\t\t\tnewConnection := h.GetJwt() == nil\n\n\t\t\t\/\/ Previously there was a HasPermission(PermissionConnect) check around this,\n\t\t\t\/\/ however NewTokenPayload will return an error if it doesn't have the connect\n\t\t\t\/\/ permission meaning that it was a redundant function call.\n\t\t\th.setJwt(token)\n\n\t\t\t\/\/ Tell the client they authenticated successfully.\n\t\t\th.unsafeSendJson(Message{\n\t\t\t\tEvent: AuthenticationSuccessEvent,\n\t\t\t\tArgs:  []string{},\n\t\t\t})\n\n\t\t\t\/\/ Check if the client was refreshing their authentication token\n\t\t\t\/\/ instead of authenticating for the first time.\n\t\t\tif !newConnection {\n\t\t\t\t\/\/ This prevents duplicate status messages as outlined in\n\t\t\t\t\/\/ https:\/\/github.com\/pterodactyl\/panel\/issues\/2077\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t\/\/ On every authentication event, send the current server status back\n\t\t\t\/\/ to the client. :)\n\t\t\tstate := h.server.GetState()\n\t\t\th.SendJson(&Message{\n\t\t\t\tEvent: server.StatusEvent,\n\t\t\t\tArgs:  []string{state},\n\t\t\t})\n\n\t\t\t\/\/ Only send the current disk usage if the server is offline, if docker container is running,\n\t\t\t\/\/ Environment#EnableResourcePolling() will send this data to all clients.\n\t\t\tif state == environment.ProcessOfflineState {\n\t\t\t\t_ = h.server.Filesystem.HasSpaceAvailable(false)\n\n\t\t\t\tb, _ := json.Marshal(h.server.Proc())\n\t\t\t\th.SendJson(&Message{\n\t\t\t\t\tEvent: server.StatsEvent,\n\t\t\t\t\tArgs:  []string{string(b)},\n\t\t\t\t})\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\tcase SetStateEvent:\n\t\t{\n\t\t\taction := server.PowerAction(strings.Join(m.Args, \"\"))\n\n\t\t\tactions := make(map[server.PowerAction]string)\n\t\t\tactions[server.PowerActionStart] = PermissionSendPowerStart\n\t\t\tactions[server.PowerActionStop] = PermissionSendPowerStop\n\t\t\tactions[server.PowerActionRestart] = PermissionSendPowerRestart\n\t\t\tactions[server.PowerActionTerminate] = PermissionSendPowerStop\n\n\t\t\t\/\/ Check that they have permission to perform this action if it is needed.\n\t\t\tif permission, exists := actions[action]; exists {\n\t\t\t\tif !h.GetJwt().HasPermission(permission) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := h.server.HandlePowerAction(action)\n\t\t\tif errors.Is(err, context.DeadlineExceeded) {\n\t\t\t\tm, _ := h.GetErrorMessage(\"another power action is currently being processed for this server, please try again later\")\n\n\t\t\t\th.SendJson(&Message{\n\t\t\t\t\tEvent: ErrorEvent,\n\t\t\t\t\tArgs:  []string{m},\n\t\t\t\t})\n\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\treturn err\n\t\t}\n\tcase SendServerLogsEvent:\n\t\t{\n\t\t\tif running, _ := h.server.Environment.IsRunning(); !running {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tlogs, err := h.server.Environment.Readlog(100)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfor _, line := range logs {\n\t\t\t\th.SendJson(&Message{\n\t\t\t\t\tEvent: server.ConsoleOutputEvent,\n\t\t\t\t\tArgs:  []string{line},\n\t\t\t\t})\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\tcase SendCommandEvent:\n\t\t{\n\t\t\tif !h.GetJwt().HasPermission(PermissionSendCommand) {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif h.server.GetState() == environment.ProcessOfflineState {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\treturn h.server.Environment.SendCommand(strings.Join(m.Args, \"\"))\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>Mask errors from websocket being closed; closes pterodactyl\/panel#2387<commit_after>package websocket\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/apex\/log\"\n\t\"github.com\/gbrlsnchs\/jwt\/v3\"\n\t\"github.com\/google\/uuid\"\n\t\"github.com\/gorilla\/websocket\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/pterodactyl\/wings\/config\"\n\t\"github.com\/pterodactyl\/wings\/environment\"\n\t\"github.com\/pterodactyl\/wings\/router\/tokens\"\n\t\"github.com\/pterodactyl\/wings\/server\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tPermissionConnect          = \"websocket.connect\"\n\tPermissionSendCommand      = \"control.console\"\n\tPermissionSendPowerStart   = \"control.start\"\n\tPermissionSendPowerStop    = \"control.stop\"\n\tPermissionSendPowerRestart = \"control.restart\"\n\tPermissionReceiveErrors    = \"admin.websocket.errors\"\n\tPermissionReceiveInstall   = \"admin.websocket.install\"\n\tPermissionReceiveBackups   = \"backup.read\"\n)\n\ntype Handler struct {\n\tsync.RWMutex\n\tConnection *websocket.Conn\n\tjwt        *tokens.WebsocketPayload `json:\"-\"`\n\tserver     *server.Server\n}\n\nvar (\n\tErrJwtNotPresent    = errors.New(\"jwt: no jwt present\")\n\tErrJwtNoConnectPerm = errors.New(\"jwt: missing connect permission\")\n\tErrJwtUuidMismatch  = errors.New(\"jwt: server uuid mismatch\")\n)\n\nfunc IsJwtError(err error) bool {\n\treturn errors.Is(err, ErrJwtNotPresent) ||\n\t\terrors.Is(err, ErrJwtNoConnectPerm) ||\n\t\terrors.Is(err, ErrJwtUuidMismatch) ||\n\t\terrors.Is(err, jwt.ErrExpValidation)\n}\n\n\/\/ Parses a JWT into a websocket token payload.\nfunc NewTokenPayload(token []byte) (*tokens.WebsocketPayload, error) {\n\tpayload := tokens.WebsocketPayload{}\n\terr := tokens.ParseToken(token, &payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !payload.HasPermission(PermissionConnect) {\n\t\treturn nil, errors.New(\"not authorized to connect to this socket\")\n\t}\n\n\treturn &payload, nil\n}\n\n\/\/ Returns a new websocket handler using the context provided.\nfunc GetHandler(s *server.Server, w http.ResponseWriter, r *http.Request) (*Handler, error) {\n\tupgrader := websocket.Upgrader{\n\t\t\/\/ Ensure that the websocket request is originating from the Panel itself,\n\t\t\/\/ and not some other location.\n\t\tCheckOrigin: func(r *http.Request) bool {\n\t\t\to := r.Header.Get(\"Origin\")\n\t\t\tif o == config.Get().PanelLocation {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tfor _, origin := range config.Get().AllowedOrigins {\n\t\t\t\tif origin == \"*\" {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\tif o != origin {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\treturn false\n\t\t},\n\t}\n\n\tconn, err := upgrader.Upgrade(w, r, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Handler{\n\t\tConnection: conn,\n\t\tjwt:        nil,\n\t\tserver:     s,\n\t}, nil\n}\n\nfunc (h *Handler) SendJson(v *Message) error {\n\t\/\/ Do not send JSON down the line if the JWT on the connection is not valid!\n\tif err := h.TokenValid(); err != nil {\n\t\th.unsafeSendJson(Message{\n\t\t\tEvent: ErrorEvent,\n\t\t\tArgs:  []string{\"could not authenticate client: \" + err.Error()},\n\t\t})\n\n\t\treturn nil\n\t}\n\n\tj := h.GetJwt()\n\tif j != nil {\n\t\t\/\/ If we're sending installation output but the user does not have the required\n\t\t\/\/ permissions to see the output, don't send it down the line.\n\t\tif v.Event == server.InstallOutputEvent {\n\t\t\tif !j.HasPermission(PermissionReceiveInstall) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If the user does not have permission to see backup events, do not emit\n\t\t\/\/ them over the socket.\n\t\tif strings.HasPrefix(v.Event, server.BackupCompletedEvent) {\n\t\t\tif !j.HasPermission(PermissionReceiveBackups) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := h.unsafeSendJson(v); err != nil {\n\t\t\/\/ Not entirely sure how this happens (likely just when there is a ton of console spam)\n\t\t\/\/ but I don't care to fix it right now, so just mask the error and throw a warning into\n\t\t\/\/ the logs for us to look into later.\n\t\tif errors.Is(err, websocket.ErrCloseSent) {\n\t\t\tif h.server != nil {\n\t\t\t\th.server.Log().WithField(\"subsystem\", \"websocket\").\n\t\t\t\t\tWithField(\"event\", v.Event).\n\t\t\t\t\tWarn(\"failed to send event to websocket: close already sent\")\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Sends JSON over the websocket connection, ignoring the authentication state of the\n\/\/ socket user. Do not call this directly unless you are positive a response should be\n\/\/ sent back to the client!\nfunc (h *Handler) unsafeSendJson(v interface{}) error {\n\th.Lock()\n\tdefer h.Unlock()\n\n\treturn h.Connection.WriteJSON(v)\n}\n\n\/\/ Checks if the JWT is still valid.\nfunc (h *Handler) TokenValid() error {\n\tj := h.GetJwt()\n\tif j == nil {\n\t\treturn ErrJwtNotPresent\n\t}\n\n\tif err := jwt.ExpirationTimeValidator(time.Now())(&j.Payload); err != nil {\n\t\treturn err\n\t}\n\n\tif !j.HasPermission(PermissionConnect) {\n\t\treturn ErrJwtNoConnectPerm\n\t}\n\n\tif h.server.Id() != j.GetServerUuid() {\n\t\treturn ErrJwtUuidMismatch\n\t}\n\n\treturn nil\n}\n\n\/\/ Sends an error back to the connected websocket instance by checking the permissions\n\/\/ of the token. If the user has the \"receive-errors\" grant we will send back the actual\n\/\/ error message, otherwise we just send back a standard error message.\nfunc (h *Handler) SendErrorJson(msg Message, err error, shouldLog ...bool) error {\n\tj := h.GetJwt()\n\texpected := errors.Is(err, server.ErrSuspended) ||\n\t\terrors.Is(err, server.ErrIsRunning) ||\n\t\terrors.Is(err, server.ErrNotEnoughDiskSpace)\n\n\tmessage := \"an unexpected error was encountered while handling this request\"\n\tif expected || (j != nil && j.HasPermission(PermissionReceiveErrors)) {\n\t\tmessage = err.Error()\n\t}\n\n\tm, u := h.GetErrorMessage(message)\n\n\twsm := Message{Event: ErrorEvent}\n\twsm.Args = []string{m}\n\n\tif len(shouldLog) == 0 || (len(shouldLog) == 1 && shouldLog[0] == true) {\n\t\tif !expected && !IsJwtError(err) {\n\t\t\th.server.Log().WithFields(log.Fields{\"event\": msg.Event, \"error_identifier\": u.String(), \"error\": err}).\n\t\t\t\tError(\"failed to handle websocket process; an error was encountered processing an event\")\n\t\t}\n\t}\n\n\treturn h.unsafeSendJson(wsm)\n}\n\n\/\/ Converts an error message into a more readable representation and returns a UUID\n\/\/ that can be cross-referenced to find the specific error that triggered.\nfunc (h *Handler) GetErrorMessage(msg string) (string, uuid.UUID) {\n\tu := uuid.Must(uuid.NewRandom())\n\n\tm := fmt.Sprintf(\"Error Event [%s]: %s\", u.String(), msg)\n\n\treturn m, u\n}\n\n\/\/ Sets the JWT for the websocket in a race-safe manner.\nfunc (h *Handler) setJwt(token *tokens.WebsocketPayload) {\n\th.Lock()\n\th.jwt = token\n\th.Unlock()\n}\n\nfunc (h *Handler) GetJwt() *tokens.WebsocketPayload {\n\th.RLock()\n\tdefer h.RUnlock()\n\n\treturn h.jwt\n}\n\n\/\/ Handle the inbound socket request and route it to the proper server action.\nfunc (h *Handler) HandleInbound(m Message) error {\n\tif m.Event != AuthenticationEvent {\n\t\tif err := h.TokenValid(); err != nil {\n\t\t\th.unsafeSendJson(Message{\n\t\t\t\tEvent: ErrorEvent,\n\t\t\t\tArgs:  []string{\"could not authenticate client: \" + err.Error()},\n\t\t\t})\n\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tswitch m.Event {\n\tcase AuthenticationEvent:\n\t\t{\n\t\t\ttoken, err := NewTokenPayload([]byte(strings.Join(m.Args, \"\")))\n\t\t\tif err != nil {\n\t\t\t\t\/\/ If the error says the JWT expired, send a token expired\n\t\t\t\t\/\/ event and hopefully the client renews the token.\n\t\t\t\tif err == jwt.ErrExpValidation {\n\t\t\t\t\th.SendJson(&Message{Event: TokenExpiredEvent})\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ Check if the user has previously authenticated successfully.\n\t\t\tnewConnection := h.GetJwt() == nil\n\n\t\t\t\/\/ Previously there was a HasPermission(PermissionConnect) check around this,\n\t\t\t\/\/ however NewTokenPayload will return an error if it doesn't have the connect\n\t\t\t\/\/ permission meaning that it was a redundant function call.\n\t\t\th.setJwt(token)\n\n\t\t\t\/\/ Tell the client they authenticated successfully.\n\t\t\th.unsafeSendJson(Message{\n\t\t\t\tEvent: AuthenticationSuccessEvent,\n\t\t\t\tArgs:  []string{},\n\t\t\t})\n\n\t\t\t\/\/ Check if the client was refreshing their authentication token\n\t\t\t\/\/ instead of authenticating for the first time.\n\t\t\tif !newConnection {\n\t\t\t\t\/\/ This prevents duplicate status messages as outlined in\n\t\t\t\t\/\/ https:\/\/github.com\/pterodactyl\/panel\/issues\/2077\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\t\/\/ On every authentication event, send the current server status back\n\t\t\t\/\/ to the client. :)\n\t\t\tstate := h.server.GetState()\n\t\t\th.SendJson(&Message{\n\t\t\t\tEvent: server.StatusEvent,\n\t\t\t\tArgs:  []string{state},\n\t\t\t})\n\n\t\t\t\/\/ Only send the current disk usage if the server is offline, if docker container is running,\n\t\t\t\/\/ Environment#EnableResourcePolling() will send this data to all clients.\n\t\t\tif state == environment.ProcessOfflineState {\n\t\t\t\t_ = h.server.Filesystem.HasSpaceAvailable(false)\n\n\t\t\t\tb, _ := json.Marshal(h.server.Proc())\n\t\t\t\th.SendJson(&Message{\n\t\t\t\t\tEvent: server.StatsEvent,\n\t\t\t\t\tArgs:  []string{string(b)},\n\t\t\t\t})\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\tcase SetStateEvent:\n\t\t{\n\t\t\taction := server.PowerAction(strings.Join(m.Args, \"\"))\n\n\t\t\tactions := make(map[server.PowerAction]string)\n\t\t\tactions[server.PowerActionStart] = PermissionSendPowerStart\n\t\t\tactions[server.PowerActionStop] = PermissionSendPowerStop\n\t\t\tactions[server.PowerActionRestart] = PermissionSendPowerRestart\n\t\t\tactions[server.PowerActionTerminate] = PermissionSendPowerStop\n\n\t\t\t\/\/ Check that they have permission to perform this action if it is needed.\n\t\t\tif permission, exists := actions[action]; exists {\n\t\t\t\tif !h.GetJwt().HasPermission(permission) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\terr := h.server.HandlePowerAction(action)\n\t\t\tif errors.Is(err, context.DeadlineExceeded) {\n\t\t\t\tm, _ := h.GetErrorMessage(\"another power action is currently being processed for this server, please try again later\")\n\n\t\t\t\th.SendJson(&Message{\n\t\t\t\t\tEvent: ErrorEvent,\n\t\t\t\t\tArgs:  []string{m},\n\t\t\t\t})\n\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\treturn err\n\t\t}\n\tcase SendServerLogsEvent:\n\t\t{\n\t\t\tif running, _ := h.server.Environment.IsRunning(); !running {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tlogs, err := h.server.Environment.Readlog(100)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfor _, line := range logs {\n\t\t\t\th.SendJson(&Message{\n\t\t\t\t\tEvent: server.ConsoleOutputEvent,\n\t\t\t\t\tArgs:  []string{line},\n\t\t\t\t})\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\tcase SendCommandEvent:\n\t\t{\n\t\t\tif !h.GetJwt().HasPermission(PermissionSendCommand) {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif h.server.GetState() == environment.ProcessOfflineState {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\treturn h.server.Environment.SendCommand(strings.Join(m.Args, \"\"))\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar (\n\tSPACES      = regexp.MustCompile(\"\\\\s+\")\n\tINVALID_POS = errors.New(\"invalid position\")\n)\n\ntype Pos struct {\n\tStart, End *int\n}\n\nfunc (p Pos) String() (result string) {\n\tif p.Start != nil {\n\t\tresult = strconv.Itoa(*p.Start)\n\t}\n\n\tresult += \":\"\n\n\tif p.End != nil {\n\t\tresult += strconv.Itoa(*p.End)\n\t}\n\n\treturn\n}\n\nfunc (p *Pos) Set(s string) error {\n\tp.Start = nil\n\tp.End = nil\n\n\tparts := strings.Split(s, \":\")\n\tif len(parts) < 1 || len(parts) > 2 {\n\t\treturn INVALID_POS\n\t}\n\n\tif len(parts[0]) > 0 {\n\t\tv, err := strconv.Atoi(parts[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tp.Start = &v\n\t}\n\n\tif len(parts) == 1 {\n\t\t\/\/ not a slice\n\t\t\/\/ note: same pointer (to distinguish from *p.End == *p.Start that returns an empty slice)\n\t\tp.End = p.Start\n\t} else if len(parts[1]) > 0 {\n\t\tv, err := strconv.Atoi(parts[1])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tp.End = &v\n\t}\n\n\treturn nil\n}\n\nfunc Slice(source []string, p Pos) []string {\n\tvar start, end int\n\n\tif p.Start == nil {\n\t\tstart = 0\n\t} else if *p.Start >= len(source) {\n\t\treturn source[0:0]\n\t} else if *p.Start < 0 {\n\t\tstart = len(source) + *p.Start\n\n\t\tif start < 0 {\n\t\t\tstart = 0\n\t\t}\n\t} else {\n\t\tstart = *p.Start\n\t}\n\n\tif p.End == p.Start {\n\t\t\/\/ this should return source[start]\n\t\tend = start + 1\n\t} else if p.End == nil || *p.End >= len(source) {\n\t\treturn source[start:]\n\t} else if *p.End < 0 {\n\t\tend = len(source) + *p.End\n\t} else {\n\t\tend = *p.End\n\t}\n\n\tif end < start {\n\t\tend = start\n\t}\n\n\treturn source[start:end]\n}\n\nfunc Quote(a []string) []string {\n\tq := make([]string, len(a))\n\tfor i, s := range a {\n\t\tq[i] = fmt.Sprintf(\"%q\", s)\n\t}\n\n\treturn q\n}\n\nfunc main() {\n\tifs := flag.String(\"ifs\", \" \", \"input field separator\")\n\tofs := flag.String(\"ofs\", \" \", \"input field separator\")\n\tquote := flag.Bool(\"quote\", false, \"quote returned fields\")\n\tflag.Parse()\n\n\tpos := make([]Pos, len(flag.Args()))\n\n\tfor i, arg := range flag.Args() {\n\t\tpos[i].Set(arg)\n\t}\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\tfor scanner.Scan() {\n\t\tif scanner.Err() != nil {\n\t\t\tlog.Fatal(scanner.Err())\n\t\t}\n\n\t\tline := scanner.Text()\n\n\t\tvar fields, result []string\n\n\t\t\/\/ split the line according to input field separator\n\t\tif *ifs == \" \" {\n\t\t\tfields = SPACES.Split(strings.TrimSpace(line), -1)\n\t\t} else {\n\t\t\tfields = strings.Split(line, *ifs)\n\t\t}\n\n\t\t\/\/ do some processing\n\t\tif len(pos) > 0 {\n\t\t\tresult = make([]string, 0)\n\n\t\t\tfor _, p := range pos {\n\t\t\t\tval := strings.Join(Slice(fields, p), *ifs)\n\t\t\t\tresult = append(result, val)\n\t\t\t}\n\t\t} else {\n\t\t\tresult = fields\n\t\t}\n\n\t\tif *quote {\n\t\t\tresult = Quote(result)\n\t\t}\n\n\t\t\/\/ join the result according to output field separator\n\t\tfmt.Println(strings.Join(result, *ofs))\n\t}\n}\n<commit_msg>Added --printf to print using specified format<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar (\n\tSPACES      = regexp.MustCompile(\"\\\\s+\")\n\tINVALID_POS = errors.New(\"invalid position\")\n)\n\ntype Pos struct {\n\tStart, End *int\n}\n\nfunc (p Pos) String() (result string) {\n\tif p.Start != nil {\n\t\tresult = strconv.Itoa(*p.Start)\n\t}\n\n\tresult += \":\"\n\n\tif p.End != nil {\n\t\tresult += strconv.Itoa(*p.End)\n\t}\n\n\treturn\n}\n\nfunc (p *Pos) Set(s string) error {\n\tp.Start = nil\n\tp.End = nil\n\n\tparts := strings.Split(s, \":\")\n\tif len(parts) < 1 || len(parts) > 2 {\n\t\treturn INVALID_POS\n\t}\n\n\tif len(parts[0]) > 0 {\n\t\tv, err := strconv.Atoi(parts[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tp.Start = &v\n\t}\n\n\tif len(parts) == 1 {\n\t\t\/\/ not a slice\n\t\t\/\/ note: same pointer (to distinguish from *p.End == *p.Start that returns an empty slice)\n\t\tp.End = p.Start\n\t} else if len(parts[1]) > 0 {\n\t\tv, err := strconv.Atoi(parts[1])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tp.End = &v\n\t}\n\n\treturn nil\n}\n\nfunc Slice(source []string, p Pos) []string {\n\tvar start, end int\n\n\tif p.Start == nil {\n\t\tstart = 0\n\t} else if *p.Start >= len(source) {\n\t\treturn source[0:0]\n\t} else if *p.Start < 0 {\n\t\tstart = len(source) + *p.Start\n\n\t\tif start < 0 {\n\t\t\tstart = 0\n\t\t}\n\t} else {\n\t\tstart = *p.Start\n\t}\n\n\tif p.End == p.Start {\n\t\t\/\/ this should return source[start]\n\t\tend = start + 1\n\t} else if p.End == nil || *p.End >= len(source) {\n\t\treturn source[start:]\n\t} else if *p.End < 0 {\n\t\tend = len(source) + *p.End\n\t} else {\n\t\tend = *p.End\n\t}\n\n\tif end < start {\n\t\tend = start\n\t}\n\n\treturn source[start:end]\n}\n\nfunc Quote(a []string) []string {\n\tq := make([]string, len(a))\n\tfor i, s := range a {\n\t\tq[i] = fmt.Sprintf(\"%q\", s)\n\t}\n\n\treturn q\n}\n\nfunc Print(format string, a []string) {\n\tprintable := make([]interface{}, len(a))\n\n\tfor i, v := range a {\n\t\tprintable[i] = v\n\t}\n\n\tfmt.Printf(format, printable...)\n}\n\nfunc main() {\n\tifs := flag.String(\"ifs\", \" \", \"input field separator\")\n\tofs := flag.String(\"ofs\", \" \", \"input field separator\")\n\tquote := flag.Bool(\"quote\", false, \"quote returned fields\")\n\tformat := flag.String(\"printf\", \"\", \"output is formatted according to specified format\")\n\n\tflag.Parse()\n\n\tpos := make([]Pos, len(flag.Args()))\n\n\tfor i, arg := range flag.Args() {\n\t\tpos[i].Set(arg)\n\t}\n\n\tif len(*format) > 0 && !strings.HasSuffix(*format, \"\\n\") {\n\t\t*format += \"\\n\"\n\t}\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\tfor scanner.Scan() {\n\t\tif scanner.Err() != nil {\n\t\t\tlog.Fatal(scanner.Err())\n\t\t}\n\n\t\tline := scanner.Text()\n\n\t\tvar fields, result []string\n\n\t\t\/\/ split the line according to input field separator\n\t\tif *ifs == \" \" {\n\t\t\tfields = SPACES.Split(strings.TrimSpace(line), -1)\n\t\t} else {\n\t\t\tfields = strings.Split(line, *ifs)\n\t\t}\n\n\t\t\/\/ do some processing\n\t\tif len(pos) > 0 {\n\t\t\tresult = make([]string, 0)\n\n\t\t\tfor _, p := range pos {\n\t\t\t\tval := strings.Join(Slice(fields, p), *ifs)\n\t\t\t\tresult = append(result, val)\n\t\t\t}\n\t\t} else {\n\t\t\tresult = fields\n\t\t}\n\n\t\tif *quote {\n\t\t\tresult = Quote(result)\n\t\t}\n\n\t\tif len(*format) > 0 {\n\t\t\tPrint(*format, result)\n\t\t} else {\n\t\t\t\/\/ join the result according to output field separator\n\t\t\tfmt.Println(strings.Join(result, *ofs))\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package etcd\n\nimport (\n\t\"fmt\"\n\t\"github.com\/coreos\/go-etcd\/etcd\"\n\t\"github.com\/lytics\/metafora\"\n\t\"math\"\n\t\"math\/rand\"\n)\n\nfunc NewEtcdFairBalancer(nodeid, namespace string, client *etcd.Client) *FairBalancer {\n\treturn NewDefaultFairBalancer(nodeid, &EtcdClusterState{client, namespace})\n}\n\n\/\/ Checks the current state of an Etcd cluster\ntype etcdClusterState struct {\n\tclient    *etcd.Client\n\tnamespace string\n}\n\nfunc (e *etcdClusterState) NodeTaskCount() (map[string]int, error) {\n\tconst sort = false\n\tconst recursive = true\n\tresp, err := e.client.Get(fmt.Sprintf(\"%s\/task\/\", e.namespace), sort, recursive)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ No current tasks\n\tif resp == nil {\n\t\treturn map[string]int{}, nil\n\t}\n\n\tnewstate := map[string]int{}\n\t\/\/ Get the list of all claimed work, create a map of the counts and\n\t\/\/ node values\n\t\/\/ We ignore tasks which have no claims\n\tfor _, task := range resp.Node.Nodes {\n\t\tfor _, claim := range task.Nodes {\n\t\t\tnewstate[claim.Value]++\n\t\t}\n\t}\n\n\treturn newstate, nil\n}\n<commit_msg>I broke the build<commit_after>package etcd\n\nimport (\n\t\"fmt\"\n\t\"github.com\/coreos\/go-etcd\/etcd\"\n\t\"github.com\/lytics\/metafora\"\n)\n\nfunc NewEtcdFairBalancer(nodeid, namespace string, client *etcd.Client) metafora.Balancer {\n\treturn metafora.NewDefaultFairBalancer(nodeid, &etcdClusterState{client, namespace})\n}\n\n\/\/ Checks the current state of an Etcd cluster\ntype etcdClusterState struct {\n\tclient    *etcd.Client\n\tnamespace string\n}\n\nfunc (e *etcdClusterState) NodeTaskCount() (map[string]int, error) {\n\tconst sort = false\n\tconst recursive = true\n\tresp, err := e.client.Get(fmt.Sprintf(\"%s\/task\/\", e.namespace), sort, recursive)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ No current tasks\n\tif resp == nil {\n\t\treturn map[string]int{}, nil\n\t}\n\n\tnewstate := map[string]int{}\n\t\/\/ Get the list of all claimed work, create a map of the counts and\n\t\/\/ node values\n\t\/\/ We ignore tasks which have no claims\n\tfor _, task := range resp.Node.Nodes {\n\t\tfor _, claim := range task.Nodes {\n\t\t\tnewstate[claim.Value]++\n\t\t}\n\t}\n\n\treturn newstate, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package event\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n)\n\ntype Message struct {\n\tEvent Event `json:\"-\"`\n}\n\ntype eventEnvelope struct {\n\tType         EventType        `json:\"type\"`\n\tEventPayload *json.RawMessage `json:\"event\"`\n}\n\nfunc (m Message) MarshalJSON() ([]byte, error) {\n\tvar envelope eventEnvelope\n\n\tpayload, err := json.Marshal(m.Event)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvelope.Type = m.Event.EventType()\n\tenvelope.EventPayload = (*json.RawMessage)(&payload)\n\n\treturn json.Marshal(envelope)\n}\n\nfunc (m *Message) UnmarshalJSON(bytes []byte) error {\n\tvar envelope eventEnvelope\n\n\terr := json.Unmarshal(bytes, &envelope)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch envelope.Type {\n\tcase EventTypeLog:\n\t\tevent := Log{}\n\t\terr = json.Unmarshal(*envelope.EventPayload, &event)\n\t\tm.Event = event\n\tcase EventTypeStatus:\n\t\tevent := Status{}\n\t\terr = json.Unmarshal(*envelope.EventPayload, &event)\n\t\tm.Event = event\n\tcase EventTypeInitialize:\n\t\tevent := Initialize{}\n\t\terr = json.Unmarshal(*envelope.EventPayload, &event)\n\t\tm.Event = event\n\tcase EventTypeStart:\n\t\tevent := Start{}\n\t\terr = json.Unmarshal(*envelope.EventPayload, &event)\n\t\tm.Event = event\n\tcase EventTypeFinish:\n\t\tevent := Finish{}\n\t\terr = json.Unmarshal(*envelope.EventPayload, &event)\n\t\tm.Event = event\n\tcase EventTypeError:\n\t\tevent := Error{}\n\t\terr = json.Unmarshal(*envelope.EventPayload, &event)\n\t\tm.Event = event\n\tcase EventTypeInput:\n\t\tevent := Input{}\n\t\terr = json.Unmarshal(*envelope.EventPayload, &event)\n\t\tm.Event = event\n\tcase EventTypeOutput:\n\t\tevent := Output{}\n\t\terr = json.Unmarshal(*envelope.EventPayload, &event)\n\t\tm.Event = event\n\tcase EventTypeVersion:\n\t\tevent := Version(\"\")\n\t\terr = json.Unmarshal(*envelope.EventPayload, &event)\n\t\tm.Event = event\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown event type: %v\", envelope.Type)\n\t}\n\n\treturn err\n}\n<commit_msg>split event parsing by type into helper<commit_after>package event\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n)\n\ntype Message struct {\n\tEvent Event `json:\"-\"`\n}\n\ntype eventEnvelope struct {\n\tType         EventType        `json:\"type\"`\n\tEventPayload *json.RawMessage `json:\"event\"`\n}\n\nfunc (m Message) MarshalJSON() ([]byte, error) {\n\tvar envelope eventEnvelope\n\n\tpayload, err := json.Marshal(m.Event)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvelope.Type = m.Event.EventType()\n\tenvelope.EventPayload = (*json.RawMessage)(&payload)\n\n\treturn json.Marshal(envelope)\n}\n\nfunc (m *Message) UnmarshalJSON(bytes []byte) error {\n\tvar envelope eventEnvelope\n\n\terr := json.Unmarshal(bytes, &envelope)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tevent, err := ParseEvent(envelope.Type, *envelope.EventPayload)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tm.Event = event\n\n\treturn nil\n}\n\nfunc ParseEvent(t EventType, payload []byte) (Event, error) {\n\tvar ev Event\n\tvar err error\n\n\tswitch t {\n\tcase EventTypeLog:\n\t\tevent := Log{}\n\t\terr = json.Unmarshal(payload, &event)\n\t\tev = event\n\tcase EventTypeStatus:\n\t\tevent := Status{}\n\t\terr = json.Unmarshal(payload, &event)\n\t\tev = event\n\tcase EventTypeInitialize:\n\t\tevent := Initialize{}\n\t\terr = json.Unmarshal(payload, &event)\n\t\tev = event\n\tcase EventTypeStart:\n\t\tevent := Start{}\n\t\terr = json.Unmarshal(payload, &event)\n\t\tev = event\n\tcase EventTypeFinish:\n\t\tevent := Finish{}\n\t\terr = json.Unmarshal(payload, &event)\n\t\tev = event\n\tcase EventTypeError:\n\t\tevent := Error{}\n\t\terr = json.Unmarshal(payload, &event)\n\t\tev = event\n\tcase EventTypeInput:\n\t\tevent := Input{}\n\t\terr = json.Unmarshal(payload, &event)\n\t\tev = event\n\tcase EventTypeOutput:\n\t\tevent := Output{}\n\t\terr = json.Unmarshal(payload, &event)\n\t\tev = event\n\tcase EventTypeVersion:\n\t\tevent := Version(\"\")\n\t\terr = json.Unmarshal(payload, &event)\n\t\tev = event\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown event type: %v\", t)\n\t}\n\n\treturn ev, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage atomic\n\nfunc generalCAS64(addr *uint64, old uint64, new uint64) bool\n\nvar GeneralCAS64 = generalCAS64\n<commit_msg>sync: fix linux\/arm build<commit_after>\/\/ Copyright 2013 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage atomic\n\nvar GeneralCAS64 = generalCAS64\n<|endoftext|>"}
{"text":"<commit_before>package gmgo\n\nimport (\n\t\"errors\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\t\"log\"\n\t\"reflect\"\n\t\"time\"\n)\n\n\/\/query representation to hide bson.M type to single file\ntype Q map[string]interface{}\n\ntype queryFunc func(q *mgo.Query, result interface{}) error\n\n\/\/ connectionMap holds all the db connection per database name\nvar connectionMap = make(map[string]Db)\n\n\/\/ Document interface implemented by structs that needs to be persisted. It should provide collection name,\n\/\/ as in the database. Also, a way to create new object id before saving.\ntype Document interface {\n\tCollectionName() string\n}\n\n\/\/ DbConfig represents the configuration params needed for MongoDB connection\ntype DbConfig struct {\n\tHost, DBName, UserName, Password string\n}\n\n\/\/ Db represents database connection which holds reference to global session and configuration for that database.\ntype Db struct {\n\tConfig  DbConfig\n\tSession *mgo.Session\n}\n\n\/\/ collection returns a mgo.Collection representation for given collection name and session\nfunc (db Db) collection(collectionName string, session *mgo.Session) *mgo.Collection {\n\treturn session.DB(db.Config.DBName).C(collectionName)\n}\n\n\/\/ slice returns the interface representation of actual collection type for returning list data\nfunc (db Db) slice(d Document) interface{} {\n\tdocumentType := reflect.TypeOf(d)\n\tdocumentSlice := reflect.MakeSlice(reflect.SliceOf(documentType), 0, 0)\n\n\t\/\/ Create a pointer to a slice value and set it to the slice\n\treturn reflect.New(documentSlice.Type()).Interface()\n}\n\nfunc (db Db) findQuery(d Document, s *mgo.Session, q interface{}) *mgo.Query {\n\t\/\/collection pointer for the given document\n\treturn db.collection(d.CollectionName(), s).Find(q)\n}\n\nfunc (db Db) executeFindAll(query Q, document Document, qf queryFunc) (interface{}, error) {\n\tsession := db.Session.Copy()\n\tdefer session.Close()\n\n\t\/\/collection pointer for the given document\n\tdocuments := db.slice(document)\n\tq := db.findQuery(document, session, query)\n\n\tif err := qf(q, documents); err != nil {\n\t\tlog.Printf(\"Error fetching %s list. Error: %s\\n\", document.CollectionName(), err)\n\t\treturn nil, err\n\t}\n\treturn results(documents)\n}\n\n\/\/ Save inserts the given document that represents the collection to the database.\nfunc (db Db) Save(document Document) error {\n\tsession := db.Session.Copy()\n\tdefer session.Close()\n\n\tcoll := db.collection(document.CollectionName(), session)\n\tif err := coll.Insert(document); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println(\"Document inserted successfully!\")\n\treturn nil\n}\n\n\/\/ Find the object by id. Returns error if it's not able to find the document. If document is found\n\/\/ it's copied to the passed in result object.\nfunc (db Db) FindById(id string, result Document) error {\n\tsession := db.Session.Copy()\n\tdefer session.Close()\n\n\tcoll := db.collection(result.CollectionName(), session)\n\tif err := coll.FindId(bson.ObjectIdHex(id)).One(result); err != nil {\n\t\tlog.Printf(\"Error fetching %s with id %s. Error: %s\\n\", result.CollectionName(), id, err)\n\t\treturn err\n\t} else {\n\t\tlog.Printf(\"Found data for id %s\\n\", id)\n\t}\n\treturn nil\n}\n\nfunc (db Db) Find(query map[string]interface{}, document Document) error {\n\tsession := db.Session.Copy()\n\tdefer session.Close()\n\n\tq := db.findQuery(document, session, query)\n\tif err := q.One(document); err != nil {\n\t\tlog.Printf(\"Error fetching %s with query %s. Error: %s\\n\", document.CollectionName(), query, err)\n\t\treturn err\n\t} else {\n\t\tlog.Printf(\"Found data for query %s\\n\", query)\n\t}\n\n\treturn nil\n}\n\nfunc (db Db) FindByRef(ref *mgo.DBRef, document Document) error {\n\tsession := db.Session.Copy()\n\tdefer session.Close()\n\n\tq := session.DB(db.Config.DBName).FindRef(ref)\n\tif err := q.One(document); err != nil {\n\t\tlog.Printf(\"Error fetching %s. Error: %s\\n\", document.CollectionName(), err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (db Db) FindAll(query Q, document Document) (interface{}, error) {\n\tfn := func(q *mgo.Query, result interface{}) error {\n\t\treturn q.All(result)\n\t}\n\treturn db.executeFindAll(query, document, fn)\n}\n\nfunc (db Db) FindWithLimit(limit int, query Q, document Document) (interface{}, error) {\n\tfn := func(q *mgo.Query, result interface{}) error {\n\t\treturn q.Limit(limit).All(result)\n\t}\n\treturn db.executeFindAll(query, document, fn)\n}\n\nfunc New(dbName string) (Db, error) {\n\tif db, ok := connectionMap[dbName]; ok {\n\t\treturn db, nil\n\t}\n\treturn Db{}, errors.New(\"Database connection not available. Perform 'Setup' first\")\n}\n\n\/\/ Setup the MongoDB connection based on passed in config. It can be called multiple times to setup connection to\n\/\/ multiple MongoDB instances.\nfunc Setup(dbConfig DbConfig) error {\n\tlog.Println(\"Connecting to MongoDB...\")\n\n\tmongoDBDialInfo := &mgo.DialInfo{\n\t\tAddrs:    []string{dbConfig.Host},\n\t\tTimeout:  5 * time.Second,\n\t\tDatabase: dbConfig.DBName,\n\t\tUsername: dbConfig.UserName,\n\t\tPassword: dbConfig.Password,\n\t}\n\n\tdbSession, err := mgo.DialWithInfo(mongoDBDialInfo)\n\tif err != nil {\n\t\tlog.Printf(\"MongoDB connection failed : %s. Exiting the program.\\n\", err)\n\t\treturn err\n\t}\n\n\tlog.Println(\"Connected to MongoDB successfully\")\n\n\t\/* Initialized database object with global session*\/\n\tconnectionMap[dbConfig.DBName] = Db{Session: dbSession, Config: dbConfig}\n\n\treturn nil\n}\n\nfunc results(documents interface{}) (interface{}, error) {\n\treturn reflect.ValueOf(documents).Elem().Interface(), nil\n}\n<commit_msg>update function<commit_after>package gmgo\n\nimport (\n\t\"errors\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\t\"log\"\n\t\"reflect\"\n\t\"time\"\n)\n\n\/\/query representation to hide bson.M type to single file\ntype Q map[string]interface{}\n\ntype queryFunc func(q *mgo.Query, result interface{}) error\n\n\/\/ connectionMap holds all the db connection per database name\nvar connectionMap = make(map[string]Db)\n\n\/\/ Document interface implemented by structs that needs to be persisted. It should provide collection name,\n\/\/ as in the database. Also, a way to create new object id before saving.\ntype Document interface {\n\tCollectionName() string\n}\n\n\/\/ DbConfig represents the configuration params needed for MongoDB connection\ntype DbConfig struct {\n\tHost, DBName, UserName, Password string\n}\n\n\/\/ Db represents database connection which holds reference to global session and configuration for that database.\ntype Db struct {\n\tConfig  DbConfig\n\tSession *mgo.Session\n}\n\n\/\/ collection returns a mgo.Collection representation for given collection name and session\nfunc (db Db) collection(collectionName string, session *mgo.Session) *mgo.Collection {\n\treturn session.DB(db.Config.DBName).C(collectionName)\n}\n\n\/\/ slice returns the interface representation of actual collection type for returning list data\nfunc (db Db) slice(d Document) interface{} {\n\tdocumentType := reflect.TypeOf(d)\n\tdocumentSlice := reflect.MakeSlice(reflect.SliceOf(documentType), 0, 0)\n\n\t\/\/ Create a pointer to a slice value and set it to the slice\n\treturn reflect.New(documentSlice.Type()).Interface()\n}\n\nfunc (db Db) findQuery(d Document, s *mgo.Session, q Q) *mgo.Query {\n\t\/\/collection pointer for the given document\n\treturn db.collection(d.CollectionName(), s).Find(q)\n}\n\nfunc (db Db) executeFindAll(query Q, document Document, qf queryFunc) (interface{}, error) {\n\tsession := db.Session.Copy()\n\tdefer session.Close()\n\n\t\/\/collection pointer for the given document\n\tdocuments := db.slice(document)\n\tq := db.findQuery(document, session, query)\n\n\tif err := qf(q, documents); err != nil {\n\t\tlog.Printf(\"Error fetching %s list. Error: %s\\n\", document.CollectionName(), err)\n\t\treturn nil, err\n\t}\n\treturn results(documents)\n}\n\n\/\/ Save inserts the given document that represents the collection to the database.\nfunc (db Db) Save(document Document) error {\n\tsession := db.Session.Copy()\n\tdefer session.Close()\n\n\tcoll := db.collection(document.CollectionName(), session)\n\tif err := coll.Insert(document); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Println(\"Document inserted successfully!\")\n\treturn nil\n}\n\n\/\/ Update updates the given document based on given selector\nfunc (db Db) Update(selector Q, document Document) error {\n\tsession := db.Session.Copy()\n\tdefer session.Close()\n\n\tcoll := db.collection(document.CollectionName(), session)\n\treturn coll.Update(selector, document)\n}\n\n\/\/ Find the object by id. Returns error if it's not able to find the document. If document is found\n\/\/ it's copied to the passed in result object.\nfunc (db Db) FindById(id string, result Document) error {\n\tsession := db.Session.Copy()\n\tdefer session.Close()\n\n\tcoll := db.collection(result.CollectionName(), session)\n\tif err := coll.FindId(bson.ObjectIdHex(id)).One(result); err != nil {\n\t\tlog.Printf(\"Error fetching %s with id %s. Error: %s\\n\", result.CollectionName(), id, err)\n\t\treturn err\n\t} else {\n\t\tlog.Printf(\"Found data for id %s\\n\", id)\n\t}\n\treturn nil\n}\n\nfunc (db Db) Find(query Q, document Document) error {\n\tsession := db.Session.Copy()\n\tdefer session.Close()\n\n\tq := db.findQuery(document, session, query)\n\tif err := q.One(document); err != nil {\n\t\tlog.Printf(\"Error fetching %s with query %s. Error: %s\\n\", document.CollectionName(), query, err)\n\t\treturn err\n\t} else {\n\t\tlog.Printf(\"Found data for query %s\\n\", query)\n\t}\n\n\treturn nil\n}\n\nfunc (db Db) FindByRef(ref *mgo.DBRef, document Document) error {\n\tsession := db.Session.Copy()\n\tdefer session.Close()\n\n\tq := session.DB(db.Config.DBName).FindRef(ref)\n\tif err := q.One(document); err != nil {\n\t\tlog.Printf(\"Error fetching %s. Error: %s\\n\", document.CollectionName(), err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (db Db) FindAll(query Q, document Document) (interface{}, error) {\n\tfn := func(q *mgo.Query, result interface{}) error {\n\t\treturn q.All(result)\n\t}\n\treturn db.executeFindAll(query, document, fn)\n}\n\nfunc (db Db) FindWithLimit(limit int, query Q, document Document) (interface{}, error) {\n\tfn := func(q *mgo.Query, result interface{}) error {\n\t\treturn q.Limit(limit).All(result)\n\t}\n\treturn db.executeFindAll(query, document, fn)\n}\n\nfunc New(dbName string) (Db, error) {\n\tif db, ok := connectionMap[dbName]; ok {\n\t\treturn db, nil\n\t}\n\treturn Db{}, errors.New(\"Database connection not available. Perform 'Setup' first\")\n}\n\n\/\/ Setup the MongoDB connection based on passed in config. It can be called multiple times to setup connection to\n\/\/ multiple MongoDB instances.\nfunc Setup(dbConfig DbConfig) error {\n\tlog.Println(\"Connecting to MongoDB...\")\n\n\tmongoDBDialInfo := &mgo.DialInfo{\n\t\tAddrs:    []string{dbConfig.Host},\n\t\tTimeout:  5 * time.Second,\n\t\tDatabase: dbConfig.DBName,\n\t\tUsername: dbConfig.UserName,\n\t\tPassword: dbConfig.Password,\n\t}\n\n\tdbSession, err := mgo.DialWithInfo(mongoDBDialInfo)\n\tif err != nil {\n\t\tlog.Printf(\"MongoDB connection failed : %s. Exiting the program.\\n\", err)\n\t\treturn err\n\t}\n\n\tlog.Println(\"Connected to MongoDB successfully\")\n\n\t\/* Initialized database object with global session*\/\n\tconnectionMap[dbConfig.DBName] = Db{Session: dbSession, Config: dbConfig}\n\n\treturn nil\n}\n\nfunc results(documents interface{}) (interface{}, error) {\n\treturn reflect.ValueOf(documents).Elem().Interface(), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012, Johan P. P. Samyn <johan.samyn@gmail.com> All rights reserved.\n\/\/ Use of this source code is governed by the BSD-2-clause license\n\/\/ that can be found in the LICENSE.txt file.\n\n\/\/ Package gohg is a Go client library for using the Mercurial dvcs\n\/\/ using it's Command Server for better performance.\n\/\/\n\/\/ For Mercurial see: http:\/\/mercurial\/selenic.com\/wiki.\n\/\/ For the Hg Command Server see: http:\/\/mercurial.selenic.com\/wiki\/CommandServer.\npackage gohg\n\nimport (\n\t\"encoding\/binary\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nconst t = \"hg serve [OPTION]\"\n\nvar server *exec.Cmd\nvar pout io.ReadCloser\nvar pin io.ReadCloser\n\ntype hgMsg struct {\n\tCh   string\n\tLn   uint\n\tData string\n}\n\ntype hgCmd struct {\n\tCmd  string\n\tLn   uint\n\tArgs string\n}\n\nfunc init() {\n\t\/\/ fmt.Println(\"Hello from gohg!\")\n} \/\/ init()\n\nfunc Connect(hg string, repo string, config []string) error {\n\n\t\/\/ for example:\n\t\/\/ server = exec.Command(\"M:\\\\DEV\\\\hg-stable\\\\hg\",\t\/\/ the Hg command\n\t\/\/ \t\t\"-R\", \"C:\\\\DEV\\\\go\\\\src\\\\golout\\\\\",\t\t\t\/\/ the repo\n\t\/\/ \t\t\"--config\", \"ui.interactive=True\",\t\t\t\/\/ mandatory settings\n\t\/\/ \t\t\"--config\", \"extensions.color=!\",\t\t\t\/\/ more settings (for Windows)\n\t\/\/ \t\t\"serve\", \"--cmdserver\", \"pipe\")\t\t\t\t\/\/ start the Command Server\n\n\tif hg == \"\" {\n\t\t\/\/ Use the default Mercurial.\n\t\thg = \"hg\"\n\t}\n\n\tvar err error\n\tvar oriRepo string\n\tsep := string(os.PathSeparator)\n\t\/\/ The Hg Command Server needs a repository.\n\tif repo == \"\" {\n\t\tif repo == \"\" {\n\t\t\trepo, err = os.Getwd()\n\t\t\toriRepo = repo\n\t\t} else {\n\t\t\trepo = strings.TrimRight(repo, sep)\n\t\t}\n\t}\n\t\/\/ If we do not find a Hg repo in the current dir, we search for one\n\t\/\/ up the path, in case we're deeper in it's working copy.\n\tfor {\n\t\t_, err = os.Stat(repo + sep + \".hg\")\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\tvar dir, file string\n\t\tdir, file = filepath.Split(repo)\n\t\tif dir == \"\" || file == \"\" {\n\t\t\trepo = \"\"\n\t\t\tbreak\n\t\t}\n\t\trepo = dir\n\t}\n\tif err != nil || repo == \"\" {\n\t\tlog.Fatal(\"could not find a Hg repository at: \" + oriRepo)\n\t}\n\n\t\/\/ if len(config) > 0 {\n\t\/\/ \tvar cfg string\n\t\/\/ \tfor i := 0; i < range(config) {\n\t\/\/ \t\tcfg = cfg + \",\" + config[i]\n\t\/\/ \t}\n\t\/\/ \tcmd = cmd + \",\" + cfg\n\t\/\/ }\n\n\tserver = exec.Command(hg)\n\tserver.Args = append(server.Args, \"-R\", repo)\n\tserver.Args = append(server.Args,\n\t\t\/\/ These arguments are fixed.\n\t\t\"--config\", \"ui.interactive=True\",\n\t\t\"--config\", \"extensions.color=!\",\n\t\t\"serve\", \"--cmdserver\", \"pipe\")\n\n\tvar pout io.ReadCloser\n\tpout, err = server.StdoutPipe()\n\tif err != nil {\n\t\tlog.Fatal(\"could not connect StdoutPipe: \", err)\n\t}\n\tvar pin io.WriteCloser\n\tpin, err = server.StdinPipe()\n\tif err != nil {\n\t\tlog.Fatal(\"could not connect StdinPipe: \", err)\n\t}\n\tif err := server.Start(); err != nil {\n\t\tlog.Fatal(\"could not start the Hg Command Server: \", err)\n\t}\n\t\/\/ temporarily, fo avoid compilation error that pin is not used\n\t_, err = pin.Write(make([]byte, 0))\n\t\/\/ fmt.Printf(\"pout=%v,    pin=%v\\n\", pout, pin)\n\n\ts := make([]byte, 1+4+1024)\n\t_, err = pout.Read(s)\n\tif err != io.EOF && err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif len(s) == 0 {\n\t\tlog.Fatal(\"no data received from Hg Command Server\")\n\t}\n\tvar ln uint32\n\tbuf := bytes.NewBuffer(s[1:5])\n\terr = binary.Read(buf, binary.BigEndian, &ln)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\tt := \"capabilities:\"\n\tl := len(t)\n\t\/\/ fmt.Println(\"[[\" + string(s[5:5+l]) + \"]]\")\n\tif string(s[5:5+l]) != t {\n\t\tlog.Fatal(\"could not connect a Hg Command Server\")\n\t}\n\n\tfmt.Println(\"Connection established with Hg Command Server at: \" + repo)\n\n\treturn nil\n\n} \/\/ Connect()\n\nfunc Close() error {\n\tfmt.Println(\"start of Close()\")\n\t\/\/ pout.Close()\n\t\/\/ pin.Close()\n\terr := server.Wait()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"before normal return of Close()\")\n\treturn nil\n} \/\/ Close()\n\nfunc RunCommand() {\n\n} \/\/ RunCommand()\n<commit_msg>small change to name of license<commit_after>\/\/ Copyright (c) 2012, Johan P. P. Samyn <johan.samyn@gmail.com> All rights reserved.\n\/\/ Use of this source code is governed by the Simplified BSD License\n\/\/ that can be found in the LICENSE.txt file.\n\n\/\/ Package gohg is a Go client library for using the Mercurial dvcs\n\/\/ using it's Command Server for better performance.\n\/\/\n\/\/ For Mercurial see: http:\/\/mercurial\/selenic.com\/wiki.\n\/\/ For the Hg Command Server see: http:\/\/mercurial.selenic.com\/wiki\/CommandServer.\npackage gohg\n\nimport (\n\t\"encoding\/binary\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nconst t = \"hg serve [OPTION]\"\n\nvar server *exec.Cmd\nvar pout io.ReadCloser\nvar pin io.ReadCloser\n\ntype hgMsg struct {\n\tCh   string\n\tLn   uint\n\tData string\n}\n\ntype hgCmd struct {\n\tCmd  string\n\tLn   uint\n\tArgs string\n}\n\nfunc init() {\n\t\/\/ fmt.Println(\"Hello from gohg!\")\n} \/\/ init()\n\nfunc Connect(hg string, repo string, config []string) error {\n\n\t\/\/ for example:\n\t\/\/ server = exec.Command(\"M:\\\\DEV\\\\hg-stable\\\\hg\",\t\/\/ the Hg command\n\t\/\/ \t\t\"-R\", \"C:\\\\DEV\\\\go\\\\src\\\\golout\\\\\",\t\t\t\/\/ the repo\n\t\/\/ \t\t\"--config\", \"ui.interactive=True\",\t\t\t\/\/ mandatory settings\n\t\/\/ \t\t\"--config\", \"extensions.color=!\",\t\t\t\/\/ more settings (for Windows)\n\t\/\/ \t\t\"serve\", \"--cmdserver\", \"pipe\")\t\t\t\t\/\/ start the Command Server\n\n\tif hg == \"\" {\n\t\t\/\/ Use the default Mercurial.\n\t\thg = \"hg\"\n\t}\n\n\tvar err error\n\tvar oriRepo string\n\tsep := string(os.PathSeparator)\n\t\/\/ The Hg Command Server needs a repository.\n\tif repo == \"\" {\n\t\tif repo == \"\" {\n\t\t\trepo, err = os.Getwd()\n\t\t\toriRepo = repo\n\t\t} else {\n\t\t\trepo = strings.TrimRight(repo, sep)\n\t\t}\n\t}\n\t\/\/ If we do not find a Hg repo in the current dir, we search for one\n\t\/\/ up the path, in case we're deeper in it's working copy.\n\tfor {\n\t\t_, err = os.Stat(repo + sep + \".hg\")\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t\tvar dir, file string\n\t\tdir, file = filepath.Split(repo)\n\t\tif dir == \"\" || file == \"\" {\n\t\t\trepo = \"\"\n\t\t\tbreak\n\t\t}\n\t\trepo = dir\n\t}\n\tif err != nil || repo == \"\" {\n\t\tlog.Fatal(\"could not find a Hg repository at: \" + oriRepo)\n\t}\n\n\t\/\/ if len(config) > 0 {\n\t\/\/ \tvar cfg string\n\t\/\/ \tfor i := 0; i < range(config) {\n\t\/\/ \t\tcfg = cfg + \",\" + config[i]\n\t\/\/ \t}\n\t\/\/ \tcmd = cmd + \",\" + cfg\n\t\/\/ }\n\n\tserver = exec.Command(hg)\n\tserver.Args = append(server.Args, \"-R\", repo)\n\tserver.Args = append(server.Args,\n\t\t\/\/ These arguments are fixed.\n\t\t\"--config\", \"ui.interactive=True\",\n\t\t\"--config\", \"extensions.color=!\",\n\t\t\"serve\", \"--cmdserver\", \"pipe\")\n\n\tvar pout io.ReadCloser\n\tpout, err = server.StdoutPipe()\n\tif err != nil {\n\t\tlog.Fatal(\"could not connect StdoutPipe: \", err)\n\t}\n\tvar pin io.WriteCloser\n\tpin, err = server.StdinPipe()\n\tif err != nil {\n\t\tlog.Fatal(\"could not connect StdinPipe: \", err)\n\t}\n\tif err := server.Start(); err != nil {\n\t\tlog.Fatal(\"could not start the Hg Command Server: \", err)\n\t}\n\t\/\/ temporarily, fo avoid compilation error that pin is not used\n\t_, err = pin.Write(make([]byte, 0))\n\t\/\/ fmt.Printf(\"pout=%v,    pin=%v\\n\", pout, pin)\n\n\ts := make([]byte, 1+4+1024)\n\t_, err = pout.Read(s)\n\tif err != io.EOF && err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif len(s) == 0 {\n\t\tlog.Fatal(\"no data received from Hg Command Server\")\n\t}\n\tvar ln uint32\n\tbuf := bytes.NewBuffer(s[1:5])\n\terr = binary.Read(buf, binary.BigEndian, &ln)\n\tif err != nil {\n\t\tfmt.Println(\"binary.Read failed:\", err)\n\t}\n\tt := \"capabilities:\"\n\tl := len(t)\n\t\/\/ fmt.Println(\"[[\" + string(s[5:5+l]) + \"]]\")\n\tif string(s[5:5+l]) != t {\n\t\tlog.Fatal(\"could not connect a Hg Command Server\")\n\t}\n\n\tfmt.Println(\"Connection established with Hg Command Server at: \" + repo)\n\n\treturn nil\n\n} \/\/ Connect()\n\nfunc Close() error {\n\tfmt.Println(\"start of Close()\")\n\t\/\/ pout.Close()\n\t\/\/ pin.Close()\n\terr := server.Wait()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"before normal return of Close()\")\n\treturn nil\n} \/\/ Close()\n\nfunc RunCommand() {\n\n} \/\/ RunCommand()\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Gone Time Tracker -or- Where has my time gone?\npackage main\n\nimport (\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/mewkiz\/pkg\/goutil\"\n)\n\nvar (\n\tgoneDir       string\n\tdumpFileName  string\n\tlogFileName   string\n\tindexFileName string\n\ttracks        Tracks\n\tzzz           bool\n\tlogger        *log.Logger\n\tcurrent       Window\n)\n\nfunc init() {\n\tvar err error\n\tgoneDir, err = goutil.SrcDir(\"github.com\/dim13\/gone\")\n\tif err != nil {\n\t\tlog.Fatal(\"init: \", err)\n\t}\n\tdumpFileName = filepath.Join(goneDir, \"gone.gob\")\n\tlogFileName = filepath.Join(goneDir, \"gone.log\")\n\tindexFileName = filepath.Join(goneDir, \"index.html\")\n}\n\ntype Tracker interface {\n\tUpdate(Window)\n\tSnooze(time.Duration)\n\tWakeup()\n}\n\ntype Tracks map[Window]Track\n\ntype Track struct {\n\tSeen  time.Time\n\tSpent time.Duration\n}\n\ntype Window struct {\n\tClass string\n\tName  string\n}\n\nfunc (t Track) String() string {\n\treturn fmt.Sprintf(\"%s %s\", t.Seen.Format(\"2006\/01\/02 15:04:05\"), t.Spent)\n}\n\nfunc (w Window) String() string {\n\treturn fmt.Sprintf(\"%s %s\", w.Class, w.Name)\n}\n\nfunc (t Tracks) Snooze(idle time.Duration) {\n\tif zzz == false {\n\t\tlog.Println(\"away from keyboard, idle for\", idle)\n\t\tif c, ok := t[current]; ok {\n\t\t\tif idle > c.Spent {\n\t\t\t\tc.Spent -= idle\n\t\t\t\tt[current] = c\n\t\t\t}\n\t\t}\n\t\tzzz = true\n\t}\n}\n\nfunc (t Tracks) Wakeup() {\n\tif zzz == true {\n\t\tlog.Println(\"back to keyboard\")\n\t\tzzz = false\n\t}\n}\n\nfunc (t Tracks) Update(w Window) {\n\tif zzz == false {\n\t\tif c, ok := t[current]; ok {\n\t\t\tc.Spent += time.Since(c.Seen)\n\t\t\tt[current] = c\n\t\t}\n\t}\n\n\tif _, ok := t[w]; !ok {\n\t\tt[w] = Track{}\n\t}\n\n\ts := t[w]\n\ts.Seen = time.Now()\n\tt[w] = s\n\n\tcurrent = w\n}\n\nfunc (t Tracks) Remove(d time.Duration) {\n\tfor k, v := range t {\n\t\tif time.Since(v.Seen) > d {\n\t\t\tlogger.Println(v, k)\n\t\t\tdelete(t, k)\n\t\t}\n\t}\n}\n\nfunc Load(fname string) Tracks {\n\tt := make(Tracks)\n\tdump, err := os.Open(fname)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn t\n\t}\n\tdefer dump.Close()\n\tdec := gob.NewDecoder(dump)\n\terr = dec.Decode(&t)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn t\n}\n\nfunc (t Tracks) Store(fname string) {\n\ttmp := fname + \".tmp\"\n\tdump, err := os.Create(tmp)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer dump.Close()\n\tenc := gob.NewEncoder(dump)\n\terr = enc.Encode(t)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tos.Remove(tmp)\n\t\treturn\n\t}\n\tos.Rename(tmp, fname)\n}\n\nfunc (t Tracks) Cleanup() {\n\tfor {\n\t\ttracks.Remove(8 * time.Hour)\n\t\ttracks.Store(dumpFileName)\n\t\ttime.Sleep(time.Minute)\n\t}\n}\n\nfunc main() {\n\tX := Connect()\n\tdefer X.Close()\n\n\tlogfile, err := os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer logfile.Close()\n\tlogger = log.New(logfile, \"\", log.LstdFlags)\n\n\ttracks = Load(dumpFileName)\n\n\tgo X.Collect(tracks)\n\tgo tracks.Cleanup()\n\n\twebReporter(\"127.0.0.1:8001\")\n}\n<commit_msg>prevent negative values<commit_after>\/\/ Gone Time Tracker -or- Where has my time gone?\npackage main\n\nimport (\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/mewkiz\/pkg\/goutil\"\n)\n\nvar (\n\tgoneDir       string\n\tdumpFileName  string\n\tlogFileName   string\n\tindexFileName string\n\ttracks        Tracks\n\tzzz           bool\n\tlogger        *log.Logger\n\tcurrent       Window\n)\n\nfunc init() {\n\tvar err error\n\tgoneDir, err = goutil.SrcDir(\"github.com\/dim13\/gone\")\n\tif err != nil {\n\t\tlog.Fatal(\"init: \", err)\n\t}\n\tdumpFileName = filepath.Join(goneDir, \"gone.gob\")\n\tlogFileName = filepath.Join(goneDir, \"gone.log\")\n\tindexFileName = filepath.Join(goneDir, \"index.html\")\n}\n\ntype Tracker interface {\n\tUpdate(Window)\n\tSnooze(time.Duration)\n\tWakeup()\n}\n\ntype Tracks map[Window]Track\n\ntype Track struct {\n\tSeen  time.Time\n\tSpent time.Duration\n}\n\ntype Window struct {\n\tClass string\n\tName  string\n}\n\nfunc (t Track) String() string {\n\treturn fmt.Sprintf(\"%s %s\", t.Seen.Format(\"2006\/01\/02 15:04:05\"), t.Spent)\n}\n\nfunc (w Window) String() string {\n\treturn fmt.Sprintf(\"%s %s\", w.Class, w.Name)\n}\n\nfunc (t Tracks) Snooze(idle time.Duration) {\n\tif zzz == false {\n\t\tlog.Println(\"away from keyboard, idle for\", idle)\n\t\tif c, ok := t[current]; ok {\n\t\t\tif idle > c.Spent && c.Spent > 0 {\n\t\t\t\tc.Spent -= idle\n\t\t\t\tt[current] = c\n\t\t\t}\n\t\t}\n\t\tzzz = true\n\t}\n}\n\nfunc (t Tracks) Wakeup() {\n\tif zzz == true {\n\t\tlog.Println(\"back to keyboard\")\n\t\tzzz = false\n\t}\n}\n\nfunc (t Tracks) Update(w Window) {\n\tif zzz == false {\n\t\tif c, ok := t[current]; ok {\n\t\t\tc.Spent += time.Since(c.Seen)\n\t\t\tt[current] = c\n\t\t}\n\t}\n\n\tif _, ok := t[w]; !ok {\n\t\tt[w] = Track{}\n\t}\n\n\ts := t[w]\n\ts.Seen = time.Now()\n\tt[w] = s\n\n\tcurrent = w\n}\n\nfunc (t Tracks) Remove(d time.Duration) {\n\tfor k, v := range t {\n\t\tif time.Since(v.Seen) > d {\n\t\t\tlogger.Println(v, k)\n\t\t\tdelete(t, k)\n\t\t}\n\t}\n}\n\nfunc Load(fname string) Tracks {\n\tt := make(Tracks)\n\tdump, err := os.Open(fname)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn t\n\t}\n\tdefer dump.Close()\n\tdec := gob.NewDecoder(dump)\n\terr = dec.Decode(&t)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn t\n}\n\nfunc (t Tracks) Store(fname string) {\n\ttmp := fname + \".tmp\"\n\tdump, err := os.Create(tmp)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer dump.Close()\n\tenc := gob.NewEncoder(dump)\n\terr = enc.Encode(t)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tos.Remove(tmp)\n\t\treturn\n\t}\n\tos.Rename(tmp, fname)\n}\n\nfunc (t Tracks) Cleanup() {\n\tfor {\n\t\ttracks.Remove(8 * time.Hour)\n\t\ttracks.Store(dumpFileName)\n\t\ttime.Sleep(time.Minute)\n\t}\n}\n\nfunc main() {\n\tX := Connect()\n\tdefer X.Close()\n\n\tlogfile, err := os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer logfile.Close()\n\tlogger = log.New(logfile, \"\", log.LstdFlags)\n\n\ttracks = Load(dumpFileName)\n\n\tgo X.Collect(tracks)\n\tgo tracks.Cleanup()\n\n\twebReporter(\"127.0.0.1:8001\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package gonn is a port from this: http:\/\/inkdrop.net\/dave\/docs\/neural-net-tutorial.cpp\npackage gonn\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"math\/rand\"\n)\n\nvar (\n\t\/\/ Eta [0.0..1.0] overall net training rate\n\tEta = 0.15\n\t\/\/ Alpha [0.0..1.0] multiplier of last weight chagne (momentum)\n\tAlpha = 0.5\n)\n\nfunc randomWeight() float64 {\n\treturn rand.Float64()\n}\n\nfunc transferFunction(x float64) float64 {\n\t\/\/ tanh - output range [-1.0..1.0]\n\t\/\/return 1.0 \/ (1.0 + math.Exp(-x))\n\treturn math.Tanh(x)\n}\n\nfunc transferFunctionDerivative(x float64) float64 {\n\t\/\/ tanh derivative\n\t\/\/ not the actual formula\n\t\/\/return 1.0\n\treturn (1.0 \/ (1.0 + math.Exp(-x))) - (1.0+math.Exp(-x))*(1.0+math.Exp(-x))\n\t\/\/return 1.0 - x*x\n}\n\ntype neuronConnection struct {\n\tWeight      float64\n\tDeltaWeight float64\n}\n\n\/\/ Neuron object\ntype Neuron struct {\n\toutputVal     float64\n\toutputWeights []neuronConnection\n\tmyIndex       int\n\tgradient      float64\n\n\t\/\/eta   float64 \/\/ [0.0..1.0] overall net training rate\n\t\/\/Alpha float64 \/\/ [0.0..n] multiplier of last weight chagne (momentum)\n}\n\n\/\/ NewNeuron intializes new neuron object\nfunc NewNeuron(numOutputs, myIndex int) *Neuron {\n\tn := new(Neuron)\n\t\/\/ c for connections\n\tfor c := 0; c < numOutputs; c++ {\n\t\tn.outputWeights = append(n.outputWeights, *new(neuronConnection))\n\t\tn.outputWeights[len(n.outputWeights)-1].Weight = randomWeight()\n\t}\n\tn.myIndex = myIndex\n\treturn n\n}\n\n\/\/ FeedForward does the math magic to its self\nfunc (n *Neuron) FeedForward(prevLayer *Layer) {\n\tvar sum float64\n\n\t\/\/ Sum the previous layer's outputs (which are our inputs)\n\t\/\/ Include the bias node from the previous layer\n\n\tfor i := 0; i < len(*prevLayer); i++ {\n\t\tsum += (*prevLayer)[i].outputVal *\n\t\t\t(*prevLayer)[i].outputWeights[n.myIndex].Weight\n\t}\n\n\tn.outputVal = transferFunction(sum)\n}\n\nfunc (n Neuron) sumDOW(nextLayer *Layer) float64 {\n\tvar sum float64\n\n\tfor i := 0; i < len(*nextLayer)-1; i++ {\n\t\tsum += n.outputWeights[i].Weight * (*nextLayer)[i].gradient\n\t}\n\n\treturn sum\n}\n\nfunc (n *Neuron) calculateOutputGradients(targetVal float64) {\n\tdelta := targetVal - n.outputVal\n\tn.gradient = delta * transferFunctionDerivative(n.outputVal)\n}\n\nfunc (n *Neuron) calculateHiddenGradients(nextLayer *Layer) {\n\tdow := n.sumDOW(nextLayer)\n\tn.gradient = dow * transferFunctionDerivative(n.outputVal)\n}\n\nfunc (n *Neuron) updateInputWeights(prevLayer *Layer) {\n\t\/\/ The weights to be updated are in the Conneciton container\n\t\/\/ int the neurons in the preceding layer\n\tfor i := 0; i < len(*prevLayer); i++ {\n\t\tneuron := &(*prevLayer)[i]\n\t\toldDeltaWeight := neuron.outputWeights[n.myIndex].DeltaWeight\n\n\t\tnewDeltaWeight :=\n\t\t\t\/\/ Individual input, magnified by the gradient and train rate:\n\t\t\tEta*neuron.outputVal*n.gradient +\n\t\t\t\t\/\/ Also add momentun = a fraction of the previous delta wieght\n\t\t\t\tAlpha*oldDeltaWeight\n\t\tneuron.outputWeights[n.myIndex].DeltaWeight = newDeltaWeight\n\t\tneuron.outputWeights[n.myIndex].Weight += newDeltaWeight\n\t}\n}\n\n\/\/ Layer is just array of neurons\ntype Layer []Neuron\n\n\/\/ NeuralNetwork holds all the data of the network\ntype NeuralNetwork struct {\n\tLayers                            []Layer \/\/ layers[layerNum][neuronNum]\n\terr                               float64\n\trecentAverageError                float64\n\tRecentAverageErrorSmoothingFactor float64\n}\n\n\/\/ NewNetwork initializes new network\nfunc NewNetwork(topology []int) *NeuralNetwork {\n\tn := new(NeuralNetwork)\n\t\/\/ Number of training smaples to average over\n\t\/\/n.RecentAverageErrorSmoothingFactor = 112.0\n\n\tfor layerNum := 0; layerNum < len(topology); layerNum++ {\n\t\tn.Layers = append(n.Layers, *new(Layer))\n\t\tvar numOutputs int\n\t\tif layerNum == len(topology)-1 {\n\t\t\tnumOutputs = 0\n\t\t} else {\n\t\t\tnumOutputs = topology[layerNum+1]\n\t\t}\n\n\t\t\/\/ We have made new layer, now fill in its neurons\n\t\t\/\/ and a bias neuron\n\t\tfor neuronNum := 0; neuronNum <= topology[layerNum]; neuronNum++ {\n\t\t\tn.Layers[len(n.Layers)-1] =\n\t\t\t\tappend(n.Layers[len(n.Layers)-1],\n\t\t\t\t\t*NewNeuron(numOutputs, neuronNum))\n\t\t}\n\n\t\t\/\/ Force the bias node's output value to 1.0. It's the last neuron\n\t\t\/\/ created above\n\t\tlayer := &n.Layers[layerNum]\n\t\t(*layer)[len(*layer)-1].outputVal = 1.0\n\t}\n\treturn n\n}\n\n\/\/ FeedForward takes inputs\nfunc (n *NeuralNetwork) FeedForward(inputVals []float64) {\n\t\/\/ Ignore bias\n\tif len(inputVals) > len(n.Layers[0])-1 {\n\t\tlog.Fatalf(\"Length if inputsVals must be the same as length of\"+\n\t\t\t\" the first layer (%d != %d)\", len(inputVals), len(n.Layers[0]))\n\t}\n\n\t\/\/ assign the input values into the input neurons\n\tfor i := 0; i < len(inputVals); i++ {\n\t\tn.Layers[0][i].outputVal = inputVals[i]\n\t}\n\n\t\/\/ Forward propagate\n\tfor layerNum := 1; layerNum < len(n.Layers); layerNum++ {\n\t\tprevLayer := &n.Layers[layerNum-1]\n\t\tfor i := 0; i < len(n.Layers[layerNum])-1; i++ {\n\t\t\tn.Layers[layerNum][i].FeedForward(prevLayer)\n\t\t}\n\t}\n}\n\n\/\/ BackProp does the backpropagation (this is where the net learns)\nfunc (n *NeuralNetwork) BackProp(targetVals []float64) {\n\t\/\/ Calculate overall net error (RMS of output errors)\n\t\/\/ RMS = \"Root Mean Square Error\"\n\toutputLayer := &n.Layers[len(n.Layers)-1]\n\tn.err = 0.0\n\n\tfor i := 0; i < len(*outputLayer)-1; i++ {\n\t\tdelta := targetVals[i] - (*outputLayer)[i].outputVal\n\t\tn.err += delta * delta\n\t}\n\tn.err \/= float64(len(*outputLayer)) - 1.0 \/\/ get average error squared\n\tn.err = math.Sqrt(n.err)                  \/\/ RMS\n\n\t\/\/if n.err > 2.0 {\n\t\/\/n.err = 1.0\n\t\/\/}\n\n\t\/\/ Implements a recent average measurement\n\tn.recentAverageError =\n\t\t(n.recentAverageError*n.RecentAverageErrorSmoothingFactor + n.err) \/\n\t\t\t(n.RecentAverageErrorSmoothingFactor + 1.0)\n\n\t\/\/ Calculate output layer gradiants\n\tfor i := 0; i < len(*outputLayer)-1; i++ {\n\t\t(*outputLayer)[i].calculateOutputGradients(targetVals[i])\n\t}\n\n\t\/\/ Calculate gradients on hidden layers\n\tfor layerNum := len(n.Layers) - 2; layerNum > 0; layerNum-- {\n\t\thiddenLayer := &n.Layers[layerNum]\n\t\tnextLayer := &n.Layers[layerNum+1]\n\n\t\tfor i := 0; i < len(*hiddenLayer); i++ {\n\t\t\t(*hiddenLayer)[i].calculateHiddenGradients(nextLayer)\n\t\t}\n\t}\n\n\t\/\/ For all layers from outputs to first hidden layer,\n\t\/\/ update connection weights\n\n\tfor layerNum := len(n.Layers) - 1; layerNum > 0; layerNum-- {\n\t\tlayer := &n.Layers[layerNum]\n\t\tprevLayer := &n.Layers[layerNum-1]\n\n\t\tfor i := 0; i < len(*layer)-1; i++ {\n\t\t\t(*layer)[i].updateInputWeights(prevLayer)\n\t\t}\n\t}\n}\n\n\/\/ GetAverageError return recentAvarageError value\nfunc (n *NeuralNetwork) GetAverageError() float64 {\n\treturn n.recentAverageError\n}\n\n\/\/ GetResults returns results from all output neurons as a string\nfunc (n *NeuralNetwork) GetResults() string {\n\tvar out string\n\tfor i, outputNeuron := range n.Layers[len(n.Layers)-1] {\n\t\tif i == len(n.Layers[len(n.Layers)-1])-1 {\n\t\t\t\/\/ Ignore bias\n\t\t\tcontinue\n\t\t}\n\t\tout += fmt.Sprintf(\"%f \", outputNeuron.outputVal)\n\t}\n\treturn out\n}\n<commit_msg>Export all values so can be json'ed<commit_after>\/\/ Package gonn is a port from this: http:\/\/inkdrop.net\/dave\/docs\/neural-net-tutorial.cpp\npackage gonn\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"math\/rand\"\n)\n\nvar (\n\t\/\/ Eta [0.0..1.0] overall net training rate\n\tEta = 0.15\n\t\/\/ Alpha [0.0..1.0] multiplier of last weight chagne (momentum)\n\tAlpha = 0.5\n)\n\nfunc randomWeight() float64 {\n\treturn rand.Float64()\n}\n\nfunc transferFunction(x float64) float64 {\n\t\/\/ tanh - output range [-1.0..1.0]\n\t\/\/return 1.0 \/ (1.0 + math.Exp(-x))\n\treturn math.Tanh(x)\n}\n\nfunc transferFunctionDerivative(x float64) float64 {\n\t\/\/ tanh derivative\n\t\/\/ not the actual formula\n\t\/\/return 1.0\n\treturn (1.0 \/ (1.0 + math.Exp(-x))) - (1.0+math.Exp(-x))*(1.0+math.Exp(-x))\n\t\/\/return 1.0 - x*x\n}\n\n\/\/ NeuronConnection is made between layers and their neurons\ntype NeuronConnection struct {\n\tWeight      float64\n\tDeltaWeight float64\n}\n\n\/\/ Neuron object\ntype Neuron struct {\n\tOutputVal     float64\n\tOutputWeights []NeuronConnection\n\tMyIndex       int\n\tGradient      float64\n\n\t\/\/eta   float64 \/\/ [0.0..1.0] overall net training rate\n\t\/\/Alpha float64 \/\/ [0.0..n] multiplier of last weight chagne (momentum)\n}\n\n\/\/ NewNeuron intializes new neuron object\nfunc NewNeuron(numOutputs, myIndex int) *Neuron {\n\tn := new(Neuron)\n\t\/\/ c for connections\n\tfor c := 0; c < numOutputs; c++ {\n\t\tn.OutputWeights = append(n.OutputWeights, *new(NeuronConnection))\n\t\tn.OutputWeights[len(n.OutputWeights)-1].Weight = randomWeight()\n\t}\n\tn.MyIndex = myIndex\n\treturn n\n}\n\n\/\/ FeedForward does the math magic to its self\nfunc (n *Neuron) FeedForward(prevLayer *Layer) {\n\tvar sum float64\n\n\t\/\/ Sum the previous layer's outputs (which are our inputs)\n\t\/\/ Include the bias node from the previous layer\n\n\tfor i := 0; i < len(*prevLayer); i++ {\n\t\tsum += (*prevLayer)[i].OutputVal *\n\t\t\t(*prevLayer)[i].OutputWeights[n.MyIndex].Weight\n\t}\n\n\tn.OutputVal = transferFunction(sum)\n}\n\nfunc (n Neuron) sumDOW(nextLayer *Layer) float64 {\n\tvar sum float64\n\n\tfor i := 0; i < len(*nextLayer)-1; i++ {\n\t\tsum += n.OutputWeights[i].Weight * (*nextLayer)[i].Gradient\n\t}\n\n\treturn sum\n}\n\nfunc (n *Neuron) calculateOutputGradients(targetVal float64) {\n\tdelta := targetVal - n.OutputVal\n\tn.Gradient = delta * transferFunctionDerivative(n.OutputVal)\n}\n\nfunc (n *Neuron) calculateHiddenGradients(nextLayer *Layer) {\n\tdow := n.sumDOW(nextLayer)\n\tn.Gradient = dow * transferFunctionDerivative(n.OutputVal)\n}\n\nfunc (n *Neuron) updateInputWeights(prevLayer *Layer) {\n\t\/\/ The weights to be updated are in the Conneciton container\n\t\/\/ int the neurons in the preceding layer\n\tfor i := 0; i < len(*prevLayer); i++ {\n\t\tneuron := &(*prevLayer)[i]\n\t\toldDeltaWeight := neuron.OutputWeights[n.MyIndex].DeltaWeight\n\n\t\tnewDeltaWeight :=\n\t\t\t\/\/ Individual input, magnified by the gradient and train rate:\n\t\t\tEta*neuron.OutputVal*n.Gradient +\n\t\t\t\t\/\/ Also add momentun = a fraction of the previous delta wieght\n\t\t\t\tAlpha*oldDeltaWeight\n\t\tneuron.OutputWeights[n.MyIndex].DeltaWeight = newDeltaWeight\n\t\tneuron.OutputWeights[n.MyIndex].Weight += newDeltaWeight\n\t}\n}\n\n\/\/ Layer is just array of neurons\ntype Layer []Neuron\n\n\/\/ NeuralNetwork holds all the data of the network\ntype NeuralNetwork struct {\n\tLayers                            []Layer \/\/ layers[layerNum][neuronNum]\n\tErr                               float64\n\tRecentAverageError                float64\n\tRecentAverageErrorSmoothingFactor float64\n}\n\n\/\/ NewNetwork initializes new network\nfunc NewNetwork(topology []int) *NeuralNetwork {\n\tn := new(NeuralNetwork)\n\t\/\/ Number of training smaples to average over\n\t\/\/n.RecentAverageErrorSmoothingFactor = 112.0\n\n\tfor layerNum := 0; layerNum < len(topology); layerNum++ {\n\t\tn.Layers = append(n.Layers, *new(Layer))\n\t\tvar numOutputs int\n\t\tif layerNum == len(topology)-1 {\n\t\t\tnumOutputs = 0\n\t\t} else {\n\t\t\tnumOutputs = topology[layerNum+1]\n\t\t}\n\n\t\t\/\/ We have made new layer, now fill in its neurons\n\t\t\/\/ and a bias neuron\n\t\tfor neuronNum := 0; neuronNum <= topology[layerNum]; neuronNum++ {\n\t\t\tn.Layers[len(n.Layers)-1] =\n\t\t\t\tappend(n.Layers[len(n.Layers)-1],\n\t\t\t\t\t*NewNeuron(numOutputs, neuronNum))\n\t\t}\n\n\t\t\/\/ Force the bias node's output value to 1.0. It's the last neuron\n\t\t\/\/ created above\n\t\tlayer := &n.Layers[layerNum]\n\t\t(*layer)[len(*layer)-1].OutputVal = 1.0\n\t}\n\treturn n\n}\n\n\/\/ FeedForward takes inputs\nfunc (n *NeuralNetwork) FeedForward(inputVals []float64) {\n\t\/\/ Ignore bias\n\tif len(inputVals) > len(n.Layers[0])-1 {\n\t\tlog.Fatalf(\"Length if inputsVals must be the same as length of\"+\n\t\t\t\" the first layer (%d != %d)\", len(inputVals), len(n.Layers[0]))\n\t}\n\n\t\/\/ assign the input values into the input neurons\n\tfor i := 0; i < len(inputVals); i++ {\n\t\tn.Layers[0][i].OutputVal = inputVals[i]\n\t}\n\n\t\/\/ Forward propagate\n\tfor layerNum := 1; layerNum < len(n.Layers); layerNum++ {\n\t\tprevLayer := &n.Layers[layerNum-1]\n\t\tfor i := 0; i < len(n.Layers[layerNum])-1; i++ {\n\t\t\tn.Layers[layerNum][i].FeedForward(prevLayer)\n\t\t}\n\t}\n}\n\n\/\/ BackProp does the backpropagation (this is where the net learns)\nfunc (n *NeuralNetwork) BackProp(targetVals []float64) {\n\t\/\/ Calculate overall net error (RMS of output errors)\n\t\/\/ RMS = \"Root Mean Square Error\"\n\toutputLayer := &n.Layers[len(n.Layers)-1]\n\tn.Err = 0.0\n\n\tfor i := 0; i < len(*outputLayer)-1; i++ {\n\t\tdelta := targetVals[i] - (*outputLayer)[i].OutputVal\n\t\tn.Err += delta * delta\n\t}\n\tn.Err \/= float64(len(*outputLayer)) - 1.0 \/\/ get average error squared\n\tn.Err = math.Sqrt(n.Err)                  \/\/ RMS\n\n\t\/\/if n.err > 2.0 {\n\t\/\/n.err = 1.0\n\t\/\/}\n\n\t\/\/ Implements a recent average measurement\n\tn.RecentAverageError =\n\t\t(n.RecentAverageError*n.RecentAverageErrorSmoothingFactor + n.Err) \/\n\t\t\t(n.RecentAverageErrorSmoothingFactor + 1.0)\n\n\t\/\/ Calculate output layer gradiants\n\tfor i := 0; i < len(*outputLayer)-1; i++ {\n\t\t(*outputLayer)[i].calculateOutputGradients(targetVals[i])\n\t}\n\n\t\/\/ Calculate gradients on hidden layers\n\tfor layerNum := len(n.Layers) - 2; layerNum > 0; layerNum-- {\n\t\thiddenLayer := &n.Layers[layerNum]\n\t\tnextLayer := &n.Layers[layerNum+1]\n\n\t\tfor i := 0; i < len(*hiddenLayer); i++ {\n\t\t\t(*hiddenLayer)[i].calculateHiddenGradients(nextLayer)\n\t\t}\n\t}\n\n\t\/\/ For all layers from outputs to first hidden layer,\n\t\/\/ update connection weights\n\n\tfor layerNum := len(n.Layers) - 1; layerNum > 0; layerNum-- {\n\t\tlayer := &n.Layers[layerNum]\n\t\tprevLayer := &n.Layers[layerNum-1]\n\n\t\tfor i := 0; i < len(*layer)-1; i++ {\n\t\t\t(*layer)[i].updateInputWeights(prevLayer)\n\t\t}\n\t}\n}\n\n\/\/ GetAverageError return recentAvarageError value\nfunc (n *NeuralNetwork) GetAverageError() float64 {\n\treturn n.RecentAverageError\n}\n\n\/\/ GetResults returns results from all output neurons as a string\nfunc (n *NeuralNetwork) GetResults() string {\n\tvar out string\n\tfor i, outputNeuron := range n.Layers[len(n.Layers)-1] {\n\t\tif i == len(n.Layers[len(n.Layers)-1])-1 {\n\t\t\t\/\/ Ignore bias\n\t\t\tcontinue\n\t\t}\n\t\tout += fmt.Sprintf(\"%f \", outputNeuron.OutputVal)\n\t}\n\treturn out\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"net\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tincomingQueueSize = 100\n\n\t\/\/ Gost used a number of fixed-size buffers for incoming messages to limit allocations. This is controlled\n\t\/\/ by udpBufSize and nUDPBufs. Note that gost cannot accept statsd messages larger than udpBufSize.\n\t\/\/ In this case, the total size of buffers for incoming messages is 10e3 * 1000 = 10MB.\n\tudpBufSize = 10e3\n\tnUDPBufs   = 1000\n)\n\nvar (\n\tconfigFile = flag.String(\"conf\", \"conf.toml\", \"TOML configuration file\")\n\tconf       *Conf\n\n\tbufPool = make(chan []byte, nUDPBufs) \/\/ pool of buffers for incoming messagse\n\n\tnamespace string                                \/\/ determined from conf.Namespace\n\tincoming  = make(chan *Stat, incomingQueueSize) \/\/ incoming stats are passed to the aggregator\n\toutgoing  = make(chan []byte)                   \/\/ outgoing Graphite messages\n\n\tstats = NewBufferedCounts() \/\/ e.g. counters -> { foo.bar -> 2 }\n\t\/\/ sets and timers require additional structures for intermediate computations.\n\tsetValues   = make(map[string]map[float64]struct{})\n\ttimerValues = make(map[string][]float64)\n\n\tdebugServer = &dServer{}\n\n\t\/\/ flushTicker and now are functions that the tests can stub out.\n\tflushTicker func() <-chan time.Time\n\tnow         func() time.Time = time.Now\n)\n\nfunc init() {\n\t\/\/ Preallocate the UDP buffer pool\n\tfor i := 0; i < nUDPBufs; i++ {\n\t\tbufPool <- make([]byte, udpBufSize)\n\t}\n}\n\ntype StatType int\n\nconst (\n\tStatCounter StatType = iota\n\tStatGauge\n\tStatTimer\n\tStatSet\n)\n\ntype Stat struct {\n\tType       StatType\n\tName       string\n\tValue      float64\n\tSampleRate float64\n}\n\n\/\/ tagToStatType maps a tag (e.g., []byte(\"c\")) to a StatType (e.g., StatCounter).\n\/\/ NOTE: This used to be a map[string]StatType but was changed for performance reasons.\nfunc tagToStatType(b []byte) (StatType, bool) {\n\tswitch len(b) {\n\tcase 1:\n\t\tswitch b[0] {\n\t\tcase 'c':\n\t\t\treturn StatCounter, true\n\t\tcase 'g':\n\t\t\treturn StatGauge, true\n\t\tcase 's':\n\t\t\treturn StatSet, true\n\t\t}\n\tcase 2:\n\t\tif b[0] == 'm' && b[1] == 's' {\n\t\t\treturn StatTimer, true\n\t\t}\n\t}\n\treturn 0, false\n}\n\ntype DiskUsageConf struct {\n\tPath   string `toml:\"path\"`\n\tValues string `toml:\"values\"`\n}\n\ntype OsStatsConf struct {\n\tCheckIntervalMS int                       `toml:\"check_interval_ms\"`\n\tLoadAvg         []int                     `toml:\"load_avg\"`\n\tLoadAvgPerCPU   []int                     `toml:\"load_avg_per_cpu\"`\n\tDiskUsage       map[string]*DiskUsageConf `toml:\"disk_usage\"`\n}\n\ntype Conf struct {\n\tGraphiteAddr             string       `toml:\"graphite_addr\"`\n\tPort                     int          `toml:\"port\"`\n\tDebugPort                int          `toml:\"debug_port\"`\n\tDebugLogging             bool         `toml:\"debug_logging\"`\n\tClearStatsBetweenFlushes bool         `toml:\"clear_stats_between_flushes\"`\n\tFlushIntervalMS          int          `toml:\"flush_interval_ms\"`\n\tNamespace                string       `toml:\"namespace\"`\n\tOsStats                  *OsStatsConf `toml:\"os_stats\"`\n}\n\nfunc handleMessages(buf []byte) {\n\tfor _, msg := range bytes.Split(buf, []byte{'\\n'}) {\n\t\tif len(msg) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tdebugServer.Print(\"[in] \", msg)\n\t\tstat, ok := parseStatsdMessage(msg)\n\t\tif !ok {\n\t\t\tlog.Println(\"bad message:\", string(msg))\n\t\t\tmetaCount(\"bad_messages_seen\")\n\t\t\tcontinue\n\t\t}\n\t\tincoming <- stat\n\t}\n\tbufPool <- buf[:udpBufSize] \/\/ Reset buf's length and return to the pool\n}\n\nfunc clientServer(c *net.UDPConn) error {\n\tfor {\n\t\tbuf := <-bufPool\n\t\tn, _, err := c.ReadFromUDP(buf)\n\t\t\/\/ TODO: Should we try to recover from such errors?\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmetaCount(\"packets_received\")\n\t\tif n >= udpBufSize {\n\t\t\tmetaCount(\"udp_message_too_large\")\n\t\t\tcontinue\n\t\t}\n\t\tgo handleMessages(buf[:n])\n\t}\n}\n\n\/\/ clearStats resets the state of all the stat types.\nfunc clearStats() {\n\t\/\/ There aren't great semantics for persisting timer values, so we clear them regardless.\n\ttimerValues = make(map[string][]float64)\n\n\tif conf.ClearStatsBetweenFlushes {\n\t\tfor name := range stats {\n\t\t\tdelete(stats, name)\n\t\t}\n\t\tsetValues = make(map[string]map[float64]struct{})\n\t} else {\n\t\tfor name, s := range stats {\n\t\t\tif strings.HasPrefix(name, \"timer.\") {\n\t\t\t\tdelete(stats, name)\n\t\t\t} else if name != \"gauge\" {\n\t\t\t\tfor k := range s {\n\t\t\t\t\ts[k] = 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k := range setValues {\n\t\t\tsetValues[k] = make(map[float64]struct{})\n\t\t}\n\t}\n}\n\n\/\/ postProcessStats computes derived stats prior to flushing.\nfunc postProcessStats() {\n\t\/\/ Compute the per-second rate for each counter\n\trateFactor := float64(conf.FlushIntervalMS) \/ 1000\n\tfor key, value := range stats.Get(\"count\") {\n\t\tstats.Set(\"rate\", key, value\/rateFactor)\n\t}\n\t\/\/ Compute the size of each set\n\tfor key, value := range setValues {\n\t\tstats.Set(\"set\", key, float64(len(value)))\n\t}\n\n\t\/\/ Process all the various stats for each timer\n\tfor key, values := range timerValues {\n\t\tif len(values) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\ttimerStats := make(map[string]float64)\n\t\tcount := float64(len(values))\n\t\t\/\/ rate is the rate (per second) at which timings were recorded (scaled for the sampling rate).\n\t\ttimerStats[\"rate\"] = stats.Get(\"timer.count\")[key] \/ rateFactor\n\t\t\/\/ sum is the total sum of all timings. You can use count and sum to compute statistics across buckets.\n\t\tsum := 0.0\n\t\tfor _, t := range values {\n\t\t\tsum += t\n\t\t}\n\t\ttimerStats[\"sum\"] = sum\n\t\tmean := sum \/ count\n\t\ttimerStats[\"mean\"] = mean\n\t\tsumSquares := 0.0\n\t\tfor _, v := range values {\n\t\t\td := v - mean\n\t\t\tsumSquares += d * d\n\t\t}\n\t\ttimerStats[\"stdev\"] = math.Sqrt(sumSquares \/ count)\n\t\tsort.Float64s(values)\n\t\ttimerStats[\"min\"] = values[0]\n\t\ttimerStats[\"max\"] = values[len(values)-1]\n\t\tif len(values)%2 == 0 {\n\t\t\ttimerStats[\"median\"] = float64(values[len(values)\/2-1]+values[len(values)\/2]) \/ 2\n\t\t} else {\n\t\t\ttimerStats[\"median\"] = float64(values[len(values)\/2])\n\t\t}\n\t\t\/\/ Now write out all these stats as namespaced keys\n\t\tfor statName, value := range timerStats {\n\t\t\tk := \"timer.\" + statName\n\t\t\tstats.Set(k, key, value)\n\t\t}\n\t}\n}\n\n\/\/ createGraphiteMessage buffers up a graphite message. We could write directly to the connection and avoid\n\/\/ the extra buffering but this allows us to use separate goroutines to write to graphite (potentially slow)\n\/\/ and aggregate (happening all the time).\nfunc createGraphiteMessage() (n int, msg []byte) {\n\tbuf := &bytes.Buffer{}\n\ttimestamp := now().Unix()\n\tfor typ, s := range stats {\n\t\tfor key, value := range s {\n\t\t\tn++\n\t\t\tfullKey := namespace + \".\" + key + \".\" + typ\n\t\t\tfmt.Fprintf(buf, \"%s %f %d\\n\", fullKey, value, timestamp)\n\t\t}\n\t}\n\treturn n, buf.Bytes()\n}\n\n\/\/ aggregate reads the incoming messages and aggregates them. It sends them to be flushed every flush\n\/\/ interval.\nfunc aggregate() {\n\tticker := flushTicker()\n\tfor {\n\t\tselect {\n\t\tcase stat := <-incoming:\n\t\t\tkey := stat.Name\n\t\t\tswitch stat.Type {\n\t\t\tcase StatCounter:\n\t\t\t\tstats.Inc(\"count\", key, stat.Value\/stat.SampleRate)\n\t\t\tcase StatSet:\n\t\t\t\tset, ok := setValues[key]\n\t\t\t\tif ok {\n\t\t\t\t\tset[stat.Value] = struct{}{}\n\t\t\t\t} else {\n\t\t\t\t\tsetValues[key] = map[float64]struct{}{stat.Value: {}}\n\t\t\t\t}\n\t\t\tcase StatGauge:\n\t\t\t\tstats.Set(\"gauge\", key, stat.Value)\n\t\t\tcase StatTimer:\n\t\t\t\tstats.Inc(\"timer.count\", key, 1.0\/stat.SampleRate)\n\t\t\t\ttimerValues[key] = append(timerValues[key], stat.Value)\n\t\t\t}\n\t\tcase <-ticker:\n\t\t\tpostProcessStats()\n\t\t\tn, msg := createGraphiteMessage()\n\t\t\tif n > 0 {\n\t\t\t\tdbg.Printf(\"Flushing %d stats.\\n\", n)\n\t\t\t\toutgoing <- msg\n\t\t\t} else {\n\t\t\t\tdbg.Println(\"No stats to flush.\")\n\t\t\t}\n\t\t\tclearStats()\n\t\t}\n\t}\n}\n\n\/\/ flush pushes outgoing messages to graphite.\nfunc flush() {\n\tfor msg := range outgoing {\n\t\tdebugServer.Print(\"[out] \", msg)\n\t\tconn, err := net.Dial(\"tcp\", conf.GraphiteAddr)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error: cannot connect to graphite at %s: %s\\n\", conf.GraphiteAddr, err)\n\t\t\tcontinue\n\t\t}\n\t\tif _, err := conn.Write(msg); err != nil {\n\t\t\tlog.Println(\"Warning: could not write Graphite message.\")\n\t\t}\n\t\tconn.Close()\n\t}\n}\n\n\/\/ dServer listens on a local tcp port and prints out debugging info to clients that connect.\ntype dServer struct {\n\tsync.Mutex\n\tClients []net.Conn\n}\n\nfunc (s *dServer) Start(port int) error {\n\taddr := fmt.Sprintf(\"127.0.0.1:%d\", port)\n\tlog.Println(\"Listening for debug TCP clients on\", addr)\n\tlistener, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tc, err := listener.Accept()\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts.Lock()\n\t\t\ts.Clients = append(s.Clients, c)\n\t\t\tdbg.Printf(\"Debug client connected. Currently %d connected client(s).\", len(s.Clients))\n\t\t\ts.Unlock()\n\t\t}\n\t}()\n\treturn nil\n}\n\nfunc (s *dServer) closeClient(client net.Conn) {\n\tfor i, c := range s.Clients {\n\t\tif c == client {\n\t\t\ts.Clients = append(s.Clients[:i], s.Clients[i+1:]...)\n\t\t\tclient.Close()\n\t\t\tdbg.Printf(\"Debug client disconnected. Currently %d connected client(s).\", len(s.Clients))\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (s *dServer) Print(tag string, msg []byte) {\n\ts.Lock()\n\tdefer s.Unlock()\n\tif len(s.Clients) == 0 {\n\t\treturn\n\t}\n\n\tclosed := []net.Conn{}\n\tfor _, line := range bytes.Split(msg, []byte{'\\n'}) {\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tmsg := append([]byte(tag), line...)\n\t\tmsg = append(msg, '\\n')\n\t\tfor _, c := range s.Clients {\n\t\t\t\/\/ Set an aggressive write timeout so a slow debug client can't impact performance.\n\t\t\tc.SetWriteDeadline(time.Now().Add(10 * time.Millisecond))\n\t\t\tif _, err := c.Write(msg); err != nil {\n\t\t\t\tclosed = append(closed, c)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tfor _, c := range closed {\n\t\t\ts.closeClient(c)\n\t\t}\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\tparseConf()\n\tflushTicker = func() <-chan time.Time {\n\t\treturn time.NewTicker(time.Duration(conf.FlushIntervalMS) * time.Millisecond).C\n\t}\n\n\tclearStats()\n\tgo flush()\n\tgo aggregate()\n\tif conf.OsStats != nil {\n\t\tgo checkOsStats()\n\t}\n\n\tif err := debugServer.Start(conf.DebugPort); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tudpAddr := fmt.Sprintf(\"localhost:%d\", conf.Port)\n\tudp, err := net.ResolveUDPAddr(\"udp\", udpAddr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(\"Listening for UDP client requests on\", udp)\n\tconn, err := net.ListenUDP(\"udp\", udp)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tgo log.Fatal(clientServer(conn))\n\n\tt := time.NewTimer(15 * time.Second)\n\t<-t.C\n}\n<commit_msg>Make buffer pool code slightly clearer<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"net\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tincomingQueueSize = 100\n\n\t\/\/ Gost used a number of fixed-size buffers for incoming messages to limit allocations. This is controlled\n\t\/\/ by udpBufSize and nUDPBufs. Note that gost cannot accept statsd messages larger than udpBufSize.\n\t\/\/ In this case, the total size of buffers for incoming messages is 10e3 * 1000 = 10MB.\n\tudpBufSize = 10e3\n\tnUDPBufs   = 1000\n)\n\nvar (\n\tconfigFile = flag.String(\"conf\", \"conf.toml\", \"TOML configuration file\")\n\tconf       *Conf\n\n\tbufPool = make(chan []byte, nUDPBufs) \/\/ pool of buffers for incoming messagse\n\n\tnamespace string                                \/\/ determined from conf.Namespace\n\tincoming  = make(chan *Stat, incomingQueueSize) \/\/ incoming stats are passed to the aggregator\n\toutgoing  = make(chan []byte)                   \/\/ outgoing Graphite messages\n\n\tstats = NewBufferedCounts() \/\/ e.g. counters -> { foo.bar -> 2 }\n\t\/\/ sets and timers require additional structures for intermediate computations.\n\tsetValues   = make(map[string]map[float64]struct{})\n\ttimerValues = make(map[string][]float64)\n\n\tdebugServer = &dServer{}\n\n\t\/\/ flushTicker and now are functions that the tests can stub out.\n\tflushTicker func() <-chan time.Time\n\tnow         func() time.Time = time.Now\n)\n\nfunc init() {\n\t\/\/ Preallocate the UDP buffer pool\n\tfor i := 0; i < nUDPBufs; i++ {\n\t\tbufPool <- make([]byte, udpBufSize)\n\t}\n}\n\ntype StatType int\n\nconst (\n\tStatCounter StatType = iota\n\tStatGauge\n\tStatTimer\n\tStatSet\n)\n\ntype Stat struct {\n\tType       StatType\n\tName       string\n\tValue      float64\n\tSampleRate float64\n}\n\n\/\/ tagToStatType maps a tag (e.g., []byte(\"c\")) to a StatType (e.g., StatCounter).\n\/\/ NOTE: This used to be a map[string]StatType but was changed for performance reasons.\nfunc tagToStatType(b []byte) (StatType, bool) {\n\tswitch len(b) {\n\tcase 1:\n\t\tswitch b[0] {\n\t\tcase 'c':\n\t\t\treturn StatCounter, true\n\t\tcase 'g':\n\t\t\treturn StatGauge, true\n\t\tcase 's':\n\t\t\treturn StatSet, true\n\t\t}\n\tcase 2:\n\t\tif b[0] == 'm' && b[1] == 's' {\n\t\t\treturn StatTimer, true\n\t\t}\n\t}\n\treturn 0, false\n}\n\ntype DiskUsageConf struct {\n\tPath   string `toml:\"path\"`\n\tValues string `toml:\"values\"`\n}\n\ntype OsStatsConf struct {\n\tCheckIntervalMS int                       `toml:\"check_interval_ms\"`\n\tLoadAvg         []int                     `toml:\"load_avg\"`\n\tLoadAvgPerCPU   []int                     `toml:\"load_avg_per_cpu\"`\n\tDiskUsage       map[string]*DiskUsageConf `toml:\"disk_usage\"`\n}\n\ntype Conf struct {\n\tGraphiteAddr             string       `toml:\"graphite_addr\"`\n\tPort                     int          `toml:\"port\"`\n\tDebugPort                int          `toml:\"debug_port\"`\n\tDebugLogging             bool         `toml:\"debug_logging\"`\n\tClearStatsBetweenFlushes bool         `toml:\"clear_stats_between_flushes\"`\n\tFlushIntervalMS          int          `toml:\"flush_interval_ms\"`\n\tNamespace                string       `toml:\"namespace\"`\n\tOsStats                  *OsStatsConf `toml:\"os_stats\"`\n}\n\nfunc handleMessages(buf []byte) {\n\tfor _, msg := range bytes.Split(buf, []byte{'\\n'}) {\n\t\tif len(msg) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tdebugServer.Print(\"[in] \", msg)\n\t\tstat, ok := parseStatsdMessage(msg)\n\t\tif !ok {\n\t\t\tlog.Println(\"bad message:\", string(msg))\n\t\t\tmetaCount(\"bad_messages_seen\")\n\t\t\tcontinue\n\t\t}\n\t\tincoming <- stat\n\t}\n\tbufPool <- buf[:cap(buf)] \/\/ Reset buf's length and return to the pool\n}\n\nfunc clientServer(c *net.UDPConn) error {\n\tfor {\n\t\tbuf := <-bufPool\n\t\tn, _, err := c.ReadFromUDP(buf)\n\t\t\/\/ TODO: Should we try to recover from such errors?\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmetaCount(\"packets_received\")\n\t\tif n >= udpBufSize {\n\t\t\tmetaCount(\"udp_message_too_large\")\n\t\t\tcontinue\n\t\t}\n\t\tgo handleMessages(buf[:n])\n\t}\n}\n\n\/\/ clearStats resets the state of all the stat types.\nfunc clearStats() {\n\t\/\/ There aren't great semantics for persisting timer values, so we clear them regardless.\n\ttimerValues = make(map[string][]float64)\n\n\tif conf.ClearStatsBetweenFlushes {\n\t\tfor name := range stats {\n\t\t\tdelete(stats, name)\n\t\t}\n\t\tsetValues = make(map[string]map[float64]struct{})\n\t} else {\n\t\tfor name, s := range stats {\n\t\t\tif strings.HasPrefix(name, \"timer.\") {\n\t\t\t\tdelete(stats, name)\n\t\t\t} else if name != \"gauge\" {\n\t\t\t\tfor k := range s {\n\t\t\t\t\ts[k] = 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor k := range setValues {\n\t\t\tsetValues[k] = make(map[float64]struct{})\n\t\t}\n\t}\n}\n\n\/\/ postProcessStats computes derived stats prior to flushing.\nfunc postProcessStats() {\n\t\/\/ Compute the per-second rate for each counter\n\trateFactor := float64(conf.FlushIntervalMS) \/ 1000\n\tfor key, value := range stats.Get(\"count\") {\n\t\tstats.Set(\"rate\", key, value\/rateFactor)\n\t}\n\t\/\/ Compute the size of each set\n\tfor key, value := range setValues {\n\t\tstats.Set(\"set\", key, float64(len(value)))\n\t}\n\n\t\/\/ Process all the various stats for each timer\n\tfor key, values := range timerValues {\n\t\tif len(values) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\ttimerStats := make(map[string]float64)\n\t\tcount := float64(len(values))\n\t\t\/\/ rate is the rate (per second) at which timings were recorded (scaled for the sampling rate).\n\t\ttimerStats[\"rate\"] = stats.Get(\"timer.count\")[key] \/ rateFactor\n\t\t\/\/ sum is the total sum of all timings. You can use count and sum to compute statistics across buckets.\n\t\tsum := 0.0\n\t\tfor _, t := range values {\n\t\t\tsum += t\n\t\t}\n\t\ttimerStats[\"sum\"] = sum\n\t\tmean := sum \/ count\n\t\ttimerStats[\"mean\"] = mean\n\t\tsumSquares := 0.0\n\t\tfor _, v := range values {\n\t\t\td := v - mean\n\t\t\tsumSquares += d * d\n\t\t}\n\t\ttimerStats[\"stdev\"] = math.Sqrt(sumSquares \/ count)\n\t\tsort.Float64s(values)\n\t\ttimerStats[\"min\"] = values[0]\n\t\ttimerStats[\"max\"] = values[len(values)-1]\n\t\tif len(values)%2 == 0 {\n\t\t\ttimerStats[\"median\"] = float64(values[len(values)\/2-1]+values[len(values)\/2]) \/ 2\n\t\t} else {\n\t\t\ttimerStats[\"median\"] = float64(values[len(values)\/2])\n\t\t}\n\t\t\/\/ Now write out all these stats as namespaced keys\n\t\tfor statName, value := range timerStats {\n\t\t\tk := \"timer.\" + statName\n\t\t\tstats.Set(k, key, value)\n\t\t}\n\t}\n}\n\n\/\/ createGraphiteMessage buffers up a graphite message. We could write directly to the connection and avoid\n\/\/ the extra buffering but this allows us to use separate goroutines to write to graphite (potentially slow)\n\/\/ and aggregate (happening all the time).\nfunc createGraphiteMessage() (n int, msg []byte) {\n\tbuf := &bytes.Buffer{}\n\ttimestamp := now().Unix()\n\tfor typ, s := range stats {\n\t\tfor key, value := range s {\n\t\t\tn++\n\t\t\tfullKey := namespace + \".\" + key + \".\" + typ\n\t\t\tfmt.Fprintf(buf, \"%s %f %d\\n\", fullKey, value, timestamp)\n\t\t}\n\t}\n\treturn n, buf.Bytes()\n}\n\n\/\/ aggregate reads the incoming messages and aggregates them. It sends them to be flushed every flush\n\/\/ interval.\nfunc aggregate() {\n\tticker := flushTicker()\n\tfor {\n\t\tselect {\n\t\tcase stat := <-incoming:\n\t\t\tkey := stat.Name\n\t\t\tswitch stat.Type {\n\t\t\tcase StatCounter:\n\t\t\t\tstats.Inc(\"count\", key, stat.Value\/stat.SampleRate)\n\t\t\tcase StatSet:\n\t\t\t\tset, ok := setValues[key]\n\t\t\t\tif ok {\n\t\t\t\t\tset[stat.Value] = struct{}{}\n\t\t\t\t} else {\n\t\t\t\t\tsetValues[key] = map[float64]struct{}{stat.Value: {}}\n\t\t\t\t}\n\t\t\tcase StatGauge:\n\t\t\t\tstats.Set(\"gauge\", key, stat.Value)\n\t\t\tcase StatTimer:\n\t\t\t\tstats.Inc(\"timer.count\", key, 1.0\/stat.SampleRate)\n\t\t\t\ttimerValues[key] = append(timerValues[key], stat.Value)\n\t\t\t}\n\t\tcase <-ticker:\n\t\t\tpostProcessStats()\n\t\t\tn, msg := createGraphiteMessage()\n\t\t\tif n > 0 {\n\t\t\t\tdbg.Printf(\"Flushing %d stats.\\n\", n)\n\t\t\t\toutgoing <- msg\n\t\t\t} else {\n\t\t\t\tdbg.Println(\"No stats to flush.\")\n\t\t\t}\n\t\t\tclearStats()\n\t\t}\n\t}\n}\n\n\/\/ flush pushes outgoing messages to graphite.\nfunc flush() {\n\tfor msg := range outgoing {\n\t\tdebugServer.Print(\"[out] \", msg)\n\t\tconn, err := net.Dial(\"tcp\", conf.GraphiteAddr)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error: cannot connect to graphite at %s: %s\\n\", conf.GraphiteAddr, err)\n\t\t\tcontinue\n\t\t}\n\t\tif _, err := conn.Write(msg); err != nil {\n\t\t\tlog.Println(\"Warning: could not write Graphite message.\")\n\t\t}\n\t\tconn.Close()\n\t}\n}\n\n\/\/ dServer listens on a local tcp port and prints out debugging info to clients that connect.\ntype dServer struct {\n\tsync.Mutex\n\tClients []net.Conn\n}\n\nfunc (s *dServer) Start(port int) error {\n\taddr := fmt.Sprintf(\"127.0.0.1:%d\", port)\n\tlog.Println(\"Listening for debug TCP clients on\", addr)\n\tlistener, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgo func() {\n\t\tfor {\n\t\t\tc, err := listener.Accept()\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts.Lock()\n\t\t\ts.Clients = append(s.Clients, c)\n\t\t\tdbg.Printf(\"Debug client connected. Currently %d connected client(s).\", len(s.Clients))\n\t\t\ts.Unlock()\n\t\t}\n\t}()\n\treturn nil\n}\n\nfunc (s *dServer) closeClient(client net.Conn) {\n\tfor i, c := range s.Clients {\n\t\tif c == client {\n\t\t\ts.Clients = append(s.Clients[:i], s.Clients[i+1:]...)\n\t\t\tclient.Close()\n\t\t\tdbg.Printf(\"Debug client disconnected. Currently %d connected client(s).\", len(s.Clients))\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (s *dServer) Print(tag string, msg []byte) {\n\ts.Lock()\n\tdefer s.Unlock()\n\tif len(s.Clients) == 0 {\n\t\treturn\n\t}\n\n\tclosed := []net.Conn{}\n\tfor _, line := range bytes.Split(msg, []byte{'\\n'}) {\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tmsg := append([]byte(tag), line...)\n\t\tmsg = append(msg, '\\n')\n\t\tfor _, c := range s.Clients {\n\t\t\t\/\/ Set an aggressive write timeout so a slow debug client can't impact performance.\n\t\t\tc.SetWriteDeadline(time.Now().Add(10 * time.Millisecond))\n\t\t\tif _, err := c.Write(msg); err != nil {\n\t\t\t\tclosed = append(closed, c)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tfor _, c := range closed {\n\t\t\ts.closeClient(c)\n\t\t}\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\tparseConf()\n\tflushTicker = func() <-chan time.Time {\n\t\treturn time.NewTicker(time.Duration(conf.FlushIntervalMS) * time.Millisecond).C\n\t}\n\n\tclearStats()\n\tgo flush()\n\tgo aggregate()\n\tif conf.OsStats != nil {\n\t\tgo checkOsStats()\n\t}\n\n\tif err := debugServer.Start(conf.DebugPort); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tudpAddr := fmt.Sprintf(\"localhost:%d\", conf.Port)\n\tudp, err := net.ResolveUDPAddr(\"udp\", udpAddr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(\"Listening for UDP client requests on\", udp)\n\tconn, err := net.ListenUDP(\"udp\", udp)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tgo log.Fatal(clientServer(conn))\n\n\tt := time.NewTimer(15 * time.Second)\n\t<-t.C\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/zbindenren\/gost\/configuration\"\n\t\"github.com\/zbindenren\/gost\/gist\"\n)\n\nfunc main() {\n\tc, err := configuration.LoadConfiguration()\n\tif err != nil {\n\t\tif err == configuration.ErrNoConfigFound {\n\t\t\tc, err = configuration.NewConfiguration()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\terr = c.Save()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tclient := gist.New(c)\n\n\tapp := cli.NewApp()\n\tapp.Version = \"1\"\n\tapp.Usage = \"utility to interact with your gists\"\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"description, d\",\n\t\t\tUsage: \"gist description\",\n\t\t},\n\t}\n\tapp.Action = func(c *cli.Context) {\n\t\tif len(c.Args()) == 0 {\n\t\t\tlog.Fatal(\"please specify files to use\")\n\t\t}\n\t\terr := client.Post(c.GlobalString(\"description\"), c.Args())\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:  \"ls\",\n\t\t\tUsage: \"list your gists or files in a gist\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tgists, err := client.List()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\tfor _, g := range gists {\n\t\t\t\t\t\tfiles := []string{}\n\t\t\t\t\t\tfor _, f := range g.Files {\n\t\t\t\t\t\t\tfiles = append(files, f.FileName)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfmt.Printf(\"%s %20s - %s\\n\", g.ID, strings.Join(files, \", \"), g.Description)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tgist, err := client.Get(c.Args().First())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\tfor _, f := range gist.Files {\n\t\t\t\t\t\tfmt.Printf(\"%20s %10d %s\\n\", f.FileName, f.Size, f.RawURL)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"rm\",\n\t\t\tUsage: \"delete gist or file in a gist\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"file, f\",\n\t\t\t\t\tUsage: \"deletes file\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tlog.Fatal(\"please specify a gist id\")\n\t\t\t\t}\n\t\t\t\terr := client.Delete(c.Args().First(), c.String(\"file\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"cat\",\n\t\t\tUsage: \"view gists\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"file, f\",\n\t\t\t\t\tUsage: \"specify file name\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t},\n\t\t\t\tcli.BoolFlag{\n\t\t\t\t\tName:  \"browser, b\",\n\t\t\t\t\tUsage: \"view in browser\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tlog.Fatal(\"please specify a gist id\")\n\t\t\t\t}\n\t\t\t\tif c.Bool(\"browser\") {\n\t\t\t\t\terr := client.ViewBrowser(c.Args().First())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\terr := client.View(c.Args().First(), c.String(\"file\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"get\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"file, f\",\n\t\t\t\t\tUsage: \"specify file name\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tUsage: \"download gist or file\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tlog.Fatal(\"gist id missing\")\n\t\t\t\t}\n\t\t\t\terr := client.Download(c.Args().First(), c.String(\"file\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"update\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringSliceFlag{\n\t\t\t\t\tName:  \"file, f\",\n\t\t\t\t\tUsage: \"specify file name(s)\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tUsage: \"updates gists\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tlog.Fatal(\"gist id missing\")\n\t\t\t\t}\n\t\t\t\tif len(c.StringSlice(\"file\")) == 0 && !c.GlobalIsSet(\"description\") {\n\t\t\t\t\tlog.Fatal(\"file name missing\")\n\t\t\t\t}\n\t\t\t\terr := client.Update(c.Args().First(), c.GlobalString(\"description\"), c.StringSlice(\"file\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t}\n\tapp.Run(os.Args)\n}\n<commit_msg>better formatting for ls output<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/zbindenren\/gost\/configuration\"\n\t\"github.com\/zbindenren\/gost\/gist\"\n)\n\nfunc main() {\n\tw := new(tabwriter.Writer)\n\tw.Init(os.Stdout, 0, 8, 0, '\\t', 0)\n\tc, err := configuration.LoadConfiguration()\n\tif err != nil {\n\t\tif err == configuration.ErrNoConfigFound {\n\t\t\tc, err = configuration.NewConfiguration()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\terr = c.Save()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tclient := gist.New(c)\n\n\tapp := cli.NewApp()\n\tapp.Version = \"1\"\n\tapp.Usage = \"utility to interact with your gists\"\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"description, d\",\n\t\t\tUsage: \"gist description\",\n\t\t},\n\t}\n\tapp.Action = func(c *cli.Context) {\n\t\tif len(c.Args()) == 0 {\n\t\t\tlog.Fatal(\"please specify files to use\")\n\t\t}\n\t\terr := client.Post(c.GlobalString(\"description\"), c.Args())\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:  \"ls\",\n\t\t\tUsage: \"list your gists or files in a gist\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tgists, err := client.List()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\tfor _, g := range gists {\n\t\t\t\t\t\tfiles := []string{}\n\t\t\t\t\t\tfor _, f := range g.Files {\n\t\t\t\t\t\t\tfiles = append(files, f.FileName)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfmt.Fprintf(w, \"%s\\t%s\\t- %s\\n\", g.ID, strings.Join(files, \", \"), g.Description)\n\t\t\t\t\t}\n\t\t\t\t\tw.Flush()\n\t\t\t\t} else {\n\t\t\t\t\tgist, err := client.Get(c.Args().First())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\tfor _, f := range gist.Files {\n\t\t\t\t\t\tfmt.Fprintf(w, \"%s\\t%d\\t%s\\n\", f.FileName, f.Size, f.RawURL)\n\t\t\t\t\t}\n\t\t\t\t\tw.Flush()\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"rm\",\n\t\t\tUsage: \"delete gist or file in a gist\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"file, f\",\n\t\t\t\t\tUsage: \"deletes file\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tlog.Fatal(\"please specify a gist id\")\n\t\t\t\t}\n\t\t\t\terr := client.Delete(c.Args().First(), c.String(\"file\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"cat\",\n\t\t\tUsage: \"view gists\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"file, f\",\n\t\t\t\t\tUsage: \"specify file name\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t},\n\t\t\t\tcli.BoolFlag{\n\t\t\t\t\tName:  \"browser, b\",\n\t\t\t\t\tUsage: \"view in browser\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tlog.Fatal(\"please specify a gist id\")\n\t\t\t\t}\n\t\t\t\tif c.Bool(\"browser\") {\n\t\t\t\t\terr := client.ViewBrowser(c.Args().First())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\terr := client.View(c.Args().First(), c.String(\"file\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"get\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"file, f\",\n\t\t\t\t\tUsage: \"specify file name\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tUsage: \"download gist or file\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tlog.Fatal(\"gist id missing\")\n\t\t\t\t}\n\t\t\t\terr := client.Download(c.Args().First(), c.String(\"file\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"update\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringSliceFlag{\n\t\t\t\t\tName:  \"file, f\",\n\t\t\t\t\tUsage: \"specify file name(s)\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tUsage: \"updates gists\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tif len(c.Args()) == 0 {\n\t\t\t\t\tlog.Fatal(\"gist id missing\")\n\t\t\t\t}\n\t\t\t\tif len(c.StringSlice(\"file\")) == 0 && !c.GlobalIsSet(\"description\") {\n\t\t\t\t\tlog.Fatal(\"file name missing\")\n\t\t\t\t}\n\t\t\t\terr := client.Update(c.Args().First(), c.GlobalString(\"description\"), c.StringSlice(\"file\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t}\n\tapp.Run(os.Args)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/echo-contrib\/pongor\"\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/labstack\/echo\/middleware\"\n)\n\nfunc main() {\n\tserv := echo.New()\n\tserv.Use(middleware.Logger())\n\tserv.Use(middleware.Recover())\n\tr := pongor.GetRenderer()\n\tserv.SetRenderer(r)\n\tserv.Static(\"\/static\", \".\/static\")\n\tserv.Get(\"\/\", func(ctx *echo.Context) error {\n\t\tctx.Render(200, \"index.html\", map[string]interface{}{\n\t\t\t\"title\": \"你好，世界\",\n\t\t})\n\t\treturn nil\n\t})\n\n\tserv.Run(\"127.0.0.1:9000\")\n}\n<commit_msg>Update pongo.go<commit_after>package main\n\nimport (\n\t\"github.com\/vodka-contrib\/pongor\"\n\t\"github.com\/insionng\/vodka\"\n\t\"github.com\/insionng\/vodka\/middleware\"\n)\n\nfunc main() {\n\tv := vodka.New()\n\tv.Use(middleware.Logger())\n\tv.Use(middleware.Recover())\n\tr := pongor.Renderor()\n\tv.SetRenderer(r)\n\tv.Static(\"\/static\", \".\/static\")\n\tv.Get(\"\/\", func(ctx *vodka.Context) error {\n\t\tctx.Render(200, \"index.html\", map[string]interface{}{\n\t\t\t\"title\": \"你好，世界\",\n\t\t})\n\t\treturn nil\n\t})\n\n\tv.Run(\"127.0.0.1:9000\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/c-14\/grue\/config\"\n\t\"os\"\n)\n\nconst version = \"0.1-alpha\"\n\nfunc usage() string {\n\treturn `usage: grue [--help] {add|fetch|import|init_cfg} ...\n\nSubcommands:\n\tadd <name> <url>\n\tfetch [-init]\n\timport <config>\n\tinit_cfg`\n}\n\nfunc add(args []string, conf *config.GrueConfig) error {\n\tif len(args) != 2 {\n\t\treturn errors.New(\"usage: grue add <name> <url>\")\n\t}\n\tvar name string = args[0]\n\tvar uri string = args[1]\n\treturn conf.AddAccount(name, uri)\n}\n\nfunc fetch(init bool, conf *config.GrueConfig) error {\n\tvar hasError bool = false\n\tret := make(chan error)\n\tgo fetchFeeds(ret, conf, init)\n\tfor r := range ret {\n\t\tif r != nil {\n\t\t\tfmt.Fprintln(os.Stderr, r)\n\t\t\thasError = true\n\t\t}\n\t}\n\tif hasError {\n\t\treturn errors.New(\"grue encountered errors during fetch\")\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Fprintln(os.Stderr, usage())\n\t\tos.Exit(EX_USAGE)\n\t}\n\tconf, err := config.ReadConfig()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(EX_TEMPFAIL)\n\t}\n\tdefer conf.Unlock()\n\tswitch cmd := os.Args[1]; cmd {\n\tcase \"add\":\n\t\terr = add(os.Args[2:], conf)\n\tcase \"fetch\":\n\t\tvar fetchCmd = flag.NewFlagSet(\"fetch\", flag.ExitOnError)\n\t\tvar initFlag = fetchCmd.Bool(\"init\", false, \"Don't send emails, only initialize database of read entries\")\n\t\terr = fetchCmd.Parse(os.Args[2:])\n\t\tif err == nil {\n\t\t\terr = fetch(*initFlag, conf)\n\t\t}\n\tcase \"import\":\n\t\terr = config.ImportCfg(os.Args[2:])\n\tcase \"init_cfg\":\n\t\tbreak\n\tcase \"-h\":\n\t\tfallthrough\n\tcase \"--help\":\n\t\tfmt.Println(usage())\n\tdefault:\n\t\tfmt.Fprintln(os.Stderr, usage())\n\t\tconf.Unlock()\n\t\tos.Exit(EX_USAGE)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t}\n}\n<commit_msg>Add -v\/--version switches<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/c-14\/grue\/config\"\n\t\"os\"\n)\n\nconst version = \"0.1-alpha\"\n\nfunc usage() string {\n\treturn `usage: grue [--help] {add|fetch|import|init_cfg} ...\n\nSubcommands:\n\tadd <name> <url>\n\tfetch [-init]\n\timport <config>\n\tinit_cfg`\n}\n\nfunc add(args []string, conf *config.GrueConfig) error {\n\tif len(args) != 2 {\n\t\treturn errors.New(\"usage: grue add <name> <url>\")\n\t}\n\tvar name string = args[0]\n\tvar uri string = args[1]\n\treturn conf.AddAccount(name, uri)\n}\n\nfunc fetch(init bool, conf *config.GrueConfig) error {\n\tvar hasError bool = false\n\tret := make(chan error)\n\tgo fetchFeeds(ret, conf, init)\n\tfor r := range ret {\n\t\tif r != nil {\n\t\t\tfmt.Fprintln(os.Stderr, r)\n\t\t\thasError = true\n\t\t}\n\t}\n\tif hasError {\n\t\treturn errors.New(\"grue encountered errors during fetch\")\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Fprintln(os.Stderr, usage())\n\t\tos.Exit(EX_USAGE)\n\t}\n\tconf, err := config.ReadConfig()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(EX_TEMPFAIL)\n\t}\n\tdefer conf.Unlock()\n\tswitch cmd := os.Args[1]; cmd {\n\tcase \"add\":\n\t\terr = add(os.Args[2:], conf)\n\tcase \"fetch\":\n\t\tvar fetchCmd = flag.NewFlagSet(\"fetch\", flag.ExitOnError)\n\t\tvar initFlag = fetchCmd.Bool(\"init\", false, \"Don't send emails, only initialize database of read entries\")\n\t\terr = fetchCmd.Parse(os.Args[2:])\n\t\tif err == nil {\n\t\t\terr = fetch(*initFlag, conf)\n\t\t}\n\tcase \"import\":\n\t\terr = config.ImportCfg(os.Args[2:])\n\tcase \"init_cfg\":\n\t\tbreak\n\tcase \"-v\":\n\t\tfallthrough\n\tcase \"--version\":\n\t\tfmt.Println(version)\n\tcase \"-h\":\n\t\tfallthrough\n\tcase \"--help\":\n\t\tfmt.Println(usage())\n\tdefault:\n\t\tfmt.Fprintln(os.Stderr, usage())\n\t\tconf.Unlock()\n\t\tos.Exit(EX_USAGE)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\n\t\"github.com\/c-14\/grue\/config\"\n)\n\nconst version = \"0.2.2\"\n\nfunc usage() string {\n\treturn `usage: grue [--help] {add|delete|fetch|import|init_cfg|list|rename} ...\n\nSubcommands:\n\tadd <name> <url>\n\tdelete <name>\n\tfetch [-init] [name]\n\timport <config>\n\tinit_cfg\n\tlist [name] [--full]\n\trename <old> <new>`\n}\n\nfunc add(args []string, conf *config.GrueConfig) error {\n\tif len(args) != 2 {\n\t\treturn errors.New(\"usage: grue add <name> <url>\")\n\t}\n\tvar name string = args[0]\n\tvar uri string = args[1]\n\treturn conf.AddAccount(name, uri)\n}\n\nfunc del(args []string, conf *config.GrueConfig) error {\n\tif len(args) != 1 {\n\t\treturn errors.New(\"usage: grue delete <name>\")\n\t}\n\tname := args[0]\n\tif err := conf.DeleteAccount(name); err != nil {\n\t\treturn err\n\t}\n\treturn DeleteHistory(name)\n}\n\nfunc fetch(args []string, conf *config.GrueConfig) error {\n\tvar initFlag bool\n\tfetchCmd := flag.NewFlagSet(\"fetch\", flag.ContinueOnError)\n\tfetchCmd.BoolVar(&initFlag, \"init\", false, \"Don't send emails, only initialize database of read entries\")\n\tif err := fetchCmd.Parse(os.Args[2:]); err != nil {\n\t\treturn err\n\t}\n\tif len(fetchCmd.Args()) == 0 {\n\t\treturn fetchFeeds(conf, initFlag)\n\t}\n\treturn fetchName(conf, fetchCmd.Arg(0), initFlag)\n}\n\nfunc list(args []string, conf *config.GrueConfig) error {\n\tconst (\n\t\tfmtShort = \"%s\\t%s\\n\"\n\t\tfmtFull  = \"%s:\\n%s\\n\"\n\t)\n\tvar full bool\n\tvar listCmd = flag.NewFlagSet(\"list\", flag.ContinueOnError)\n\tlistCmd.BoolVar(&full, \"full\", false, \"Show full account info\")\n\tif err := listCmd.Parse(args); err != nil {\n\t\treturn err\n\t}\n\tif len(listCmd.Args()) == 0 {\n\t\tvar keys []string\n\t\tfor k, _ := range conf.Accounts {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Strings(keys)\n\t\tif full {\n\t\t\tfor _, k := range keys {\n\t\t\t\tfmt.Printf(fmtFull, k, conf.Accounts[k])\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tfor _, k := range keys {\n\t\t\tfmt.Printf(fmtShort, k, conf.Accounts[k].URI)\n\t\t}\n\t\treturn nil\n\t}\n\n\tname := listCmd.Args()[0]\n\tif cfg, ok := conf.Accounts[name]; ok {\n\t\tif full {\n\t\t\tfmt.Printf(fmtFull, name, cfg)\n\t\t} else {\n\t\t\tfmt.Printf(fmtShort, name, cfg.URI)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc rename(args []string, conf *config.GrueConfig) error {\n\tif len(args) != 2 {\n\t\treturn errors.New(\"usage: grue rename <old> <new>\")\n\t}\n\told := args[0]\n\tnew := args[1]\n\tif err := conf.RenameAccount(old, new); err != nil {\n\t\treturn err\n\t}\n\treturn RenameHistory(old, new)\n}\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Fprintln(os.Stderr, usage())\n\t\tos.Exit(EX_USAGE)\n\t}\n\tconf, err := config.ReadConfig()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(EX_TEMPFAIL)\n\t}\n\tdefer conf.Unlock()\n\tswitch cmd := os.Args[1]; cmd {\n\tcase \"add\":\n\t\terr = add(os.Args[2:], conf)\n\tcase \"delete\":\n\t\terr = del(os.Args[2:], conf)\n\tcase \"fetch\":\n\t\terr = fetch(os.Args[2:], conf)\n\tcase \"import\":\n\t\terr = config.ImportCfg(os.Args[2:])\n\tcase \"init_cfg\":\n\t\tbreak\n\tcase \"list\":\n\t\terr = list(os.Args[2:], conf)\n\t\tbreak\n\tcase \"rename\":\n\t\terr = rename(os.Args[2:], conf)\n\tcase \"-v\":\n\t\tfallthrough\n\tcase \"--version\":\n\t\tfmt.Println(version)\n\tcase \"-h\":\n\t\tfallthrough\n\tcase \"--help\":\n\t\tfmt.Println(usage())\n\tdefault:\n\t\tfmt.Fprintln(os.Stderr, usage())\n\t\tconf.Unlock()\n\t\tos.Exit(EX_USAGE)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t}\n}\n<commit_msg>Simplify for loop<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\n\t\"github.com\/c-14\/grue\/config\"\n)\n\nconst version = \"0.2.2\"\n\nfunc usage() string {\n\treturn `usage: grue [--help] {add|delete|fetch|import|init_cfg|list|rename} ...\n\nSubcommands:\n\tadd <name> <url>\n\tdelete <name>\n\tfetch [-init] [name]\n\timport <config>\n\tinit_cfg\n\tlist [name] [--full]\n\trename <old> <new>`\n}\n\nfunc add(args []string, conf *config.GrueConfig) error {\n\tif len(args) != 2 {\n\t\treturn errors.New(\"usage: grue add <name> <url>\")\n\t}\n\tvar name string = args[0]\n\tvar uri string = args[1]\n\treturn conf.AddAccount(name, uri)\n}\n\nfunc del(args []string, conf *config.GrueConfig) error {\n\tif len(args) != 1 {\n\t\treturn errors.New(\"usage: grue delete <name>\")\n\t}\n\tname := args[0]\n\tif err := conf.DeleteAccount(name); err != nil {\n\t\treturn err\n\t}\n\treturn DeleteHistory(name)\n}\n\nfunc fetch(args []string, conf *config.GrueConfig) error {\n\tvar initFlag bool\n\tfetchCmd := flag.NewFlagSet(\"fetch\", flag.ContinueOnError)\n\tfetchCmd.BoolVar(&initFlag, \"init\", false, \"Don't send emails, only initialize database of read entries\")\n\tif err := fetchCmd.Parse(os.Args[2:]); err != nil {\n\t\treturn err\n\t}\n\tif len(fetchCmd.Args()) == 0 {\n\t\treturn fetchFeeds(conf, initFlag)\n\t}\n\treturn fetchName(conf, fetchCmd.Arg(0), initFlag)\n}\n\nfunc list(args []string, conf *config.GrueConfig) error {\n\tconst (\n\t\tfmtShort = \"%s\\t%s\\n\"\n\t\tfmtFull  = \"%s:\\n%s\\n\"\n\t)\n\tvar full bool\n\tvar listCmd = flag.NewFlagSet(\"list\", flag.ContinueOnError)\n\tlistCmd.BoolVar(&full, \"full\", false, \"Show full account info\")\n\tif err := listCmd.Parse(args); err != nil {\n\t\treturn err\n\t}\n\tif len(listCmd.Args()) == 0 {\n\t\tvar keys []string\n\t\tfor k := range conf.Accounts {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Strings(keys)\n\t\tif full {\n\t\t\tfor _, k := range keys {\n\t\t\t\tfmt.Printf(fmtFull, k, conf.Accounts[k])\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tfor _, k := range keys {\n\t\t\tfmt.Printf(fmtShort, k, conf.Accounts[k].URI)\n\t\t}\n\t\treturn nil\n\t}\n\n\tname := listCmd.Args()[0]\n\tif cfg, ok := conf.Accounts[name]; ok {\n\t\tif full {\n\t\t\tfmt.Printf(fmtFull, name, cfg)\n\t\t} else {\n\t\t\tfmt.Printf(fmtShort, name, cfg.URI)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc rename(args []string, conf *config.GrueConfig) error {\n\tif len(args) != 2 {\n\t\treturn errors.New(\"usage: grue rename <old> <new>\")\n\t}\n\told := args[0]\n\tnew := args[1]\n\tif err := conf.RenameAccount(old, new); err != nil {\n\t\treturn err\n\t}\n\treturn RenameHistory(old, new)\n}\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Fprintln(os.Stderr, usage())\n\t\tos.Exit(EX_USAGE)\n\t}\n\tconf, err := config.ReadConfig()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(EX_TEMPFAIL)\n\t}\n\tdefer conf.Unlock()\n\tswitch cmd := os.Args[1]; cmd {\n\tcase \"add\":\n\t\terr = add(os.Args[2:], conf)\n\tcase \"delete\":\n\t\terr = del(os.Args[2:], conf)\n\tcase \"fetch\":\n\t\terr = fetch(os.Args[2:], conf)\n\tcase \"import\":\n\t\terr = config.ImportCfg(os.Args[2:])\n\tcase \"init_cfg\":\n\t\tbreak\n\tcase \"list\":\n\t\terr = list(os.Args[2:], conf)\n\t\tbreak\n\tcase \"rename\":\n\t\terr = rename(os.Args[2:], conf)\n\tcase \"-v\":\n\t\tfallthrough\n\tcase \"--version\":\n\t\tfmt.Println(version)\n\tcase \"-h\":\n\t\tfallthrough\n\tcase \"--help\":\n\t\tfmt.Println(usage())\n\tdefault:\n\t\tfmt.Fprintln(os.Stderr, usage())\n\t\tconf.Unlock()\n\t\tos.Exit(EX_USAGE)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 - António Meireles  <antonio.meireles@reformi.st>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tkillCmd = &cobra.Command{\n\t\tUse:     \"kill\",\n\t\tAliases: []string{\"stop\", \"halt\"},\n\t\tShort:   \"Halts one or more running CoreOS instances\",\n\t\tPreRunE: func(cmd *cobra.Command, args []string) (err error) {\n\t\t\tengine.rawArgs.BindPFlags(cmd.Flags())\n\t\t\tif len(args) < 1 && !engine.rawArgs.GetBool(\"all\") {\n\t\t\t\treturn fmt.Errorf(\"This command requires either at least \" +\n\t\t\t\t\t\"one argument to work or --all.\")\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t\tRunE: killCommand,\n\t}\n)\n\nfunc killCommand(cmd *cobra.Command, args []string) (err error) {\n\tvar up []VMInfo\n\tif up, err = allRunningInstances(); err != nil {\n\t\treturn\n\t}\n\tif engine.rawArgs.GetBool(\"all\") {\n\t\tfor _, vm := range up {\n\t\t\tif err = vm.halt(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tfor _, arg := range args {\n\t\tfor _, vm := range up {\n\t\t\tif vm.Name == arg || vm.UUID == arg {\n\t\t\t\tif err = vm.halt(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (vm VMInfo) halt() (err error) {\n\tvar (\n\t\tsshSession *sshClient\n\t\tcommand    = \"sudo sync;sudo halt\"\n\t\thardKill   = func(e error) (err error) {\n\t\t\tif e != nil {\n\t\t\t\t\/\/ ssh messed up for some reason or target has no IP\n\t\t\t\tlog.Printf(\"couldn't ssh to %v (%v)...\\n\", vm.Name, e)\n\t\t\t\tif canKill := engine.allowedToRun(); canKill != nil {\n\t\t\t\t\treturn canKill\n\t\t\t\t}\n\t\t\t\tif p, ee := os.FindProcess(vm.Pid); ee == nil {\n\t\t\t\t\tlog.Println(\"hard kill...\")\n\t\t\t\t\tif err = p.Kill(); err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t)\n\tif sshSession, err = vm.startSSHsession(); err != nil {\n\t\tif err = hardKill(err); err != nil {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tdefer sshSession.close()\n\t\tif err =\n\t\t\thardKill(sshSession.executeRemoteCommand(command)); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\t\/\/ wait until it's _really_ dead, but not forever\n\tselect {\n\tcase <-time.After(3 * time.Second):\n\t\terr = fmt.Errorf(\"VM didn't shutdown normally after 3s (!)... \")\n\tcase <-time.Tick(100 * time.Millisecond):\n\t\tif _, ee := os.FindProcess(vm.Pid); ee == nil {\n\t\t\tif e :=\n\t\t\t\tos.RemoveAll(filepath.Join(engine.runDir,\n\t\t\t\t\tvm.UUID)); e != nil {\n\t\t\t\tlog.Println(e.Error())\n\t\t\t}\n\t\t\tlog.Printf(\"successfully halted '%s'\\n\", vm.Name)\n\t\t}\n\t}\n\treturn\n}\n\nfunc init() {\n\tkillCmd.Flags().BoolP(\"all\", \"a\", false, \"halts all running instances\")\n\tRootCmd.AddCommand(killCmd)\n}\n<commit_msg>fixes halt's exit code<commit_after>\/\/ Copyright 2015 - António Meireles  <antonio.meireles@reformi.st>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tkillCmd = &cobra.Command{\n\t\tUse:     \"kill\",\n\t\tAliases: []string{\"stop\", \"halt\"},\n\t\tShort:   \"Halts one or more running CoreOS instances\",\n\t\tPreRunE: func(cmd *cobra.Command, args []string) (err error) {\n\t\t\tengine.rawArgs.BindPFlags(cmd.Flags())\n\t\t\tif len(args) < 1 && !engine.rawArgs.GetBool(\"all\") {\n\t\t\t\terr = fmt.Errorf(\"This command requires either at least \" +\n\t\t\t\t\t\"one argument to work or --all.\")\n\t\t\t}\n\t\t\treturn\n\t\t},\n\t\tRunE: killCommand,\n\t}\n)\n\nfunc killCommand(cmd *cobra.Command, args []string) (err error) {\n\tvar (\n\t\tup []VMInfo\n\t\tvm VMInfo\n\t)\n\tif up, err = allRunningInstances(); err != nil {\n\t\treturn\n\t}\n\tif engine.rawArgs.GetBool(\"all\") {\n\t\tfor _, vm := range up {\n\t\t\tif err = vm.halt(); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\tfor _, arg := range args {\n\t\tif vm, err = vmInfo(arg); err != nil {\n\t\t\treturn\n\t\t} else if err = vm.halt(); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc (vm VMInfo) halt() (err error) {\n\tvar (\n\t\tsshSession *sshClient\n\t\tcommand    = \"sudo sync;sudo halt\"\n\t\thardKill   = func(e error) (err error) {\n\t\t\tif e != nil {\n\t\t\t\t\/\/ ssh messed up for some reason or target has no IP\n\t\t\t\tlog.Printf(\"couldn't ssh to %v (%v)...\\n\", vm.Name, e)\n\t\t\t\tif canKill := engine.allowedToRun(); canKill != nil {\n\t\t\t\t\treturn canKill\n\t\t\t\t}\n\t\t\t\tif p, ee := os.FindProcess(vm.Pid); ee == nil {\n\t\t\t\t\tlog.Println(\"hard kill...\")\n\t\t\t\t\tif err = p.Kill(); err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t)\n\tif sshSession, err = vm.startSSHsession(); err != nil {\n\t\tif err = hardKill(err); err != nil {\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tdefer sshSession.close()\n\t\tif err =\n\t\t\thardKill(sshSession.executeRemoteCommand(command)); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\t\/\/ wait until it's _really_ dead, but not forever\n\tselect {\n\tcase <-time.After(3 * time.Second):\n\t\terr = fmt.Errorf(\"VM didn't shutdown normally after 3s (!)... \")\n\tcase <-time.Tick(100 * time.Millisecond):\n\t\tif _, ee := os.FindProcess(vm.Pid); ee == nil {\n\t\t\tif e :=\n\t\t\t\tos.RemoveAll(filepath.Join(engine.runDir,\n\t\t\t\t\tvm.UUID)); e != nil {\n\t\t\t\tlog.Println(e.Error())\n\t\t\t}\n\t\t\tlog.Printf(\"successfully halted '%s'\\n\", vm.Name)\n\t\t}\n\t}\n\treturn\n}\n\nfunc init() {\n\tkillCmd.Flags().BoolP(\"all\", \"a\", false, \"halts all running instances\")\n\tRootCmd.AddCommand(killCmd)\n}\n<|endoftext|>"}
{"text":"<commit_before>package gps\n\nimport (\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"sort\"\n)\n\n\/\/ HashInputs computes a hash digest of all data in a SolveOpts that are as\n\/\/ function inputs to Solve().\n\/\/\n\/\/ The digest returned from this function is the same as the digest that would\n\/\/ be included with a Solve() Result. As such, it's appropriate for comparison\n\/\/ against the digest stored in a lock file, generated by a previous Solve(): if\n\/\/ the digests match, then manifest and lock are in sync, and a Solve() is\n\/\/ unnecessary.\n\/\/\n\/\/ (Basically, this is for memoization.)\nfunc (s *solver) HashInputs() ([]byte, error) {\n\t\/\/ Do these checks up front before any other work is needed, as they're the\n\t\/\/ only things that can cause errors\n\t\/\/ Pass in magic root values, and the bridge will analyze the right thing\n\tptree, err := s.b.listPackages(ProjectIdentifier{ProjectRoot: s.params.ImportRoot}, nil)\n\tif err != nil {\n\t\treturn nil, badOptsFailure(fmt.Sprintf(\"Error while parsing packages under %s: %s\", s.params.RootDir, err.Error()))\n\t}\n\n\td, dd := s.params.Manifest.DependencyConstraints(), s.params.Manifest.TestDependencyConstraints()\n\tp := make(sortedDeps, len(d))\n\tcopy(p, d)\n\tp = append(p, dd...)\n\n\tsort.Stable(p)\n\n\t\/\/ We have everything we need; now, compute the hash.\n\th := sha256.New()\n\tfor _, pd := range p {\n\t\th.Write([]byte(pd.Ident.ProjectRoot))\n\t\th.Write([]byte(pd.Ident.NetworkName))\n\t\t\/\/ FIXME Constraint.String() is a surjective-only transformation - tags\n\t\t\/\/ and branches with the same name are written out as the same string.\n\t\t\/\/ This could, albeit rarely, result in input collisions when a real\n\t\t\/\/ change has occurred.\n\t\th.Write([]byte(pd.Constraint.String()))\n\t}\n\n\t\/\/ The stdlib and old appengine packages play the same functional role in\n\t\/\/ solving as ignores. Because they change, albeit quite infrequently, we\n\t\/\/ have to include them in the hash.\n\th.Write([]byte(stdlibPkgs))\n\th.Write([]byte(appenginePkgs))\n\n\t\/\/ Write each of the packages, or the errors that were found for a\n\t\/\/ particular subpath, into the hash.\n\tfor _, perr := range ptree.Packages {\n\t\tif perr.Err != nil {\n\t\t\th.Write([]byte(perr.Err.Error()))\n\t\t} else {\n\t\t\th.Write([]byte(perr.P.Name))\n\t\t\th.Write([]byte(perr.P.CommentPath))\n\t\t\th.Write([]byte(perr.P.ImportPath))\n\t\t\tfor _, imp := range perr.P.Imports {\n\t\t\t\th.Write([]byte(imp))\n\t\t\t}\n\t\t\tfor _, imp := range perr.P.TestImports {\n\t\t\t\th.Write([]byte(imp))\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Add the package ignores, if any.\n\tif len(s.ig) > 0 {\n\t\t\/\/ Dump and sort the ignores\n\t\tig := make([]string, len(s.ig))\n\t\tk := 0\n\t\tfor pkg := range s.ig {\n\t\t\tig[k] = pkg\n\t\t\tk++\n\t\t}\n\t\tsort.Strings(ig)\n\n\t\tfor _, igp := range ig {\n\t\t\th.Write([]byte(igp))\n\t\t}\n\t}\n\n\tan, av := s.b.analyzerInfo()\n\th.Write([]byte(an))\n\th.Write([]byte(av.String()))\n\n\t\/\/ TODO(sdboyer) overrides\n\t\/\/ TODO(sdboyer) aliases\n\treturn h.Sum(nil), nil\n}\n\ntype sortedDeps []ProjectConstraint\n\nfunc (s sortedDeps) Len() int {\n\treturn len(s)\n}\n\nfunc (s sortedDeps) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\nfunc (s sortedDeps) Less(i, j int) bool {\n\treturn s[i].Ident.less(s[j].Ident)\n}\n<commit_msg>s\/sortedDeps\/sortedConstraints\/<commit_after>package gps\n\nimport (\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"sort\"\n)\n\n\/\/ HashInputs computes a hash digest of all data in a SolveOpts that are as\n\/\/ function inputs to Solve().\n\/\/\n\/\/ The digest returned from this function is the same as the digest that would\n\/\/ be included with a Solve() Result. As such, it's appropriate for comparison\n\/\/ against the digest stored in a lock file, generated by a previous Solve(): if\n\/\/ the digests match, then manifest and lock are in sync, and a Solve() is\n\/\/ unnecessary.\n\/\/\n\/\/ (Basically, this is for memoization.)\nfunc (s *solver) HashInputs() ([]byte, error) {\n\t\/\/ Do these checks up front before any other work is needed, as they're the\n\t\/\/ only things that can cause errors\n\t\/\/ Pass in magic root values, and the bridge will analyze the right thing\n\tptree, err := s.b.listPackages(ProjectIdentifier{ProjectRoot: s.params.ImportRoot}, nil)\n\tif err != nil {\n\t\treturn nil, badOptsFailure(fmt.Sprintf(\"Error while parsing packages under %s: %s\", s.params.RootDir, err.Error()))\n\t}\n\n\td, dd := s.params.Manifest.DependencyConstraints(), s.params.Manifest.TestDependencyConstraints()\n\tp := make(sortedConstraints, len(d))\n\tcopy(p, d)\n\tp = append(p, dd...)\n\n\tsort.Stable(p)\n\n\t\/\/ We have everything we need; now, compute the hash.\n\th := sha256.New()\n\tfor _, pd := range p {\n\t\th.Write([]byte(pd.Ident.ProjectRoot))\n\t\th.Write([]byte(pd.Ident.NetworkName))\n\t\t\/\/ FIXME Constraint.String() is a surjective-only transformation - tags\n\t\t\/\/ and branches with the same name are written out as the same string.\n\t\t\/\/ This could, albeit rarely, result in input collisions when a real\n\t\t\/\/ change has occurred.\n\t\th.Write([]byte(pd.Constraint.String()))\n\t}\n\n\t\/\/ The stdlib and old appengine packages play the same functional role in\n\t\/\/ solving as ignores. Because they change, albeit quite infrequently, we\n\t\/\/ have to include them in the hash.\n\th.Write([]byte(stdlibPkgs))\n\th.Write([]byte(appenginePkgs))\n\n\t\/\/ Write each of the packages, or the errors that were found for a\n\t\/\/ particular subpath, into the hash.\n\tfor _, perr := range ptree.Packages {\n\t\tif perr.Err != nil {\n\t\t\th.Write([]byte(perr.Err.Error()))\n\t\t} else {\n\t\t\th.Write([]byte(perr.P.Name))\n\t\t\th.Write([]byte(perr.P.CommentPath))\n\t\t\th.Write([]byte(perr.P.ImportPath))\n\t\t\tfor _, imp := range perr.P.Imports {\n\t\t\t\th.Write([]byte(imp))\n\t\t\t}\n\t\t\tfor _, imp := range perr.P.TestImports {\n\t\t\t\th.Write([]byte(imp))\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Add the package ignores, if any.\n\tif len(s.ig) > 0 {\n\t\t\/\/ Dump and sort the ignores\n\t\tig := make([]string, len(s.ig))\n\t\tk := 0\n\t\tfor pkg := range s.ig {\n\t\t\tig[k] = pkg\n\t\t\tk++\n\t\t}\n\t\tsort.Strings(ig)\n\n\t\tfor _, igp := range ig {\n\t\t\th.Write([]byte(igp))\n\t\t}\n\t}\n\n\tan, av := s.b.analyzerInfo()\n\th.Write([]byte(an))\n\th.Write([]byte(av.String()))\n\n\t\/\/ TODO(sdboyer) overrides\n\t\/\/ TODO(sdboyer) aliases\n\treturn h.Sum(nil), nil\n}\n\ntype sortedConstraints []ProjectConstraint\n\nfunc (s sortedConstraints) Len() int {\n\treturn len(s)\n}\n\nfunc (s sortedConstraints) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\nfunc (s sortedConstraints) Less(i, j int) bool {\n\treturn s[i].Ident.less(s[j].Ident)\n}\n<|endoftext|>"}
{"text":"<commit_before>package gps\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha256\"\n\t\"io\"\n\t\"sort\"\n)\n\n\/\/ HashInputs computes a hash digest of all data in SolveParams and the\n\/\/ RootManifest that act as function inputs to Solve().\n\/\/\n\/\/ The digest returned from this function is the same as the digest that would\n\/\/ be included with a Solve() Result. As such, it's appropriate for comparison\n\/\/ against the digest stored in a lock file, generated by a previous Solve(): if\n\/\/ the digests match, then manifest and lock are in sync, and a Solve() is\n\/\/ unnecessary.\n\/\/\n\/\/ (Basically, this is for memoization.)\nfunc (s *solver) HashInputs() (digest []byte) {\n\th := sha256.New()\n\ts.writeHashingInputs(h)\n\n\thd := h.Sum(nil)\n\tdigest = hd[:]\n\treturn\n}\n\nfunc (s *solver) writeHashingInputs(w io.Writer) {\n\twriteString := func(s string) {\n\t\t\/\/ Skip zero-length string writes; it doesn't affect the real hash\n\t\t\/\/ calculation, and keeps misleading newlines from showing up in the\n\t\t\/\/ debug output.\n\t\tif s != \"\" {\n\t\t\t\/\/ All users of writeHashingInputs cannot error on Write(), so just\n\t\t\t\/\/ ignore it\n\t\t\tw.Write([]byte(s))\n\t\t}\n\t}\n\n\t\/\/ Apply overrides to the constraints from the root. Otherwise, the hash\n\t\/\/ would be computed on the basis of a constraint from root that doesn't\n\t\/\/ actually affect solving.\n\twc := s.ovr.overrideAll(s.rm.DependencyConstraints().merge(s.rm.TestDependencyConstraints()))\n\n\tfor _, pd := range wc {\n\t\twriteString(string(pd.Ident.ProjectRoot))\n\t\twriteString(pd.Ident.Source)\n\t\t\/\/ FIXME Constraint.String() is a surjective-only transformation - tags\n\t\t\/\/ and branches with the same name are written out as the same string.\n\t\t\/\/ This could, albeit rarely, result in erroneously identical inputs\n\t\t\/\/ when a real change has occurred.\n\t\twriteString(pd.Constraint.String())\n\t}\n\n\t\/\/ Get the external reach list\n\n\t\/\/ Write each of the packages, or the errors that were found for a\n\t\/\/ particular subpath, into the hash. We need to do this in a\n\t\/\/ deterministic order, so expand and sort the map.\n\tvar pkgs []PackageOrErr\n\tfor _, perr := range s.rpt.Packages {\n\t\tpkgs = append(pkgs, perr)\n\t}\n\tsort.Sort(sortPackageOrErr(pkgs))\n\tfor _, perr := range pkgs {\n\t\tif perr.Err != nil {\n\t\t\twriteString(perr.Err.Error())\n\t\t} else {\n\t\t\twriteString(perr.P.Name)\n\t\t\twriteString(perr.P.CommentPath)\n\t\t\twriteString(perr.P.ImportPath)\n\t\t\tfor _, imp := range perr.P.Imports {\n\t\t\t\tif !isStdLib(imp) {\n\t\t\t\t\twriteString(imp)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, imp := range perr.P.TestImports {\n\t\t\t\tif !isStdLib(imp) {\n\t\t\t\t\twriteString(imp)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Write any require packages given in the root manifest.\n\tif len(s.req) > 0 {\n\t\t\/\/ Dump and sort the reqnores\n\t\treq := make([]string, 0, len(s.req))\n\t\tfor pkg := range s.req {\n\t\t\treq = append(req, pkg)\n\t\t}\n\t\tsort.Strings(req)\n\n\t\tfor _, reqp := range req {\n\t\t\twriteString(reqp)\n\t\t}\n\t}\n\n\t\/\/ Add the ignored packages, if any.\n\tif len(s.ig) > 0 {\n\t\t\/\/ Dump and sort the ignores\n\t\tig := make([]string, 0, len(s.ig))\n\t\tfor pkg := range s.ig {\n\t\t\tig = append(ig, pkg)\n\t\t}\n\t\tsort.Strings(ig)\n\n\t\tfor _, igp := range ig {\n\t\t\twriteString(igp)\n\t\t}\n\t}\n\n\tfor _, pc := range s.ovr.asSortedSlice() {\n\t\twriteString(string(pc.Ident.ProjectRoot))\n\t\tif pc.Ident.Source != \"\" {\n\t\t\twriteString(pc.Ident.Source)\n\t\t}\n\t\tif pc.Constraint != nil {\n\t\t\twriteString(pc.Constraint.String())\n\t\t}\n\t}\n\n\tan, av := s.b.AnalyzerInfo()\n\twriteString(an)\n\twriteString(av.String())\n}\n\n\/\/ bytes.Buffer wrapper that injects newlines after each call to Write().\ntype nlbuf bytes.Buffer\n\nfunc (buf *nlbuf) Write(p []byte) (n int, err error) {\n\tn, _ = (*bytes.Buffer)(buf).Write(p)\n\t(*bytes.Buffer)(buf).WriteByte('\\n')\n\treturn n + 1, nil\n}\n\n\/\/ HashingInputsAsString returns the raw input data used by Solver.HashInputs()\n\/\/ as a string.\n\/\/\n\/\/ This is primarily intended for debugging purposes.\nfunc HashingInputsAsString(s Solver) string {\n\tts := s.(*solver)\n\tbuf := new(nlbuf)\n\tts.writeHashingInputs(buf)\n\n\treturn (*bytes.Buffer)(buf).String()\n}\n\ntype sortPackageOrErr []PackageOrErr\n\nfunc (s sortPackageOrErr) Len() int      { return len(s) }\nfunc (s sortPackageOrErr) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s sortPackageOrErr) Less(i, j int) bool {\n\ta, b := s[i], s[j]\n\tif a.Err != nil || b.Err != nil {\n\t\t\/\/ Sort errors last.\n\t\tif b.Err == nil {\n\t\t\treturn false\n\t\t}\n\t\tif a.Err == nil {\n\t\t\treturn true\n\t\t}\n\t\t\/\/ And then by string.\n\t\treturn a.Err.Error() < b.Err.Error()\n\t}\n\t\/\/ And finally, sort by import path.\n\treturn a.P.ImportPath < b.P.ImportPath\n}\n<commit_msg>Remove pointless ifs<commit_after>package gps\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha256\"\n\t\"io\"\n\t\"sort\"\n)\n\n\/\/ HashInputs computes a hash digest of all data in SolveParams and the\n\/\/ RootManifest that act as function inputs to Solve().\n\/\/\n\/\/ The digest returned from this function is the same as the digest that would\n\/\/ be included with a Solve() Result. As such, it's appropriate for comparison\n\/\/ against the digest stored in a lock file, generated by a previous Solve(): if\n\/\/ the digests match, then manifest and lock are in sync, and a Solve() is\n\/\/ unnecessary.\n\/\/\n\/\/ (Basically, this is for memoization.)\nfunc (s *solver) HashInputs() (digest []byte) {\n\th := sha256.New()\n\ts.writeHashingInputs(h)\n\n\thd := h.Sum(nil)\n\tdigest = hd[:]\n\treturn\n}\n\nfunc (s *solver) writeHashingInputs(w io.Writer) {\n\twriteString := func(s string) {\n\t\t\/\/ Skip zero-length string writes; it doesn't affect the real hash\n\t\t\/\/ calculation, and keeps misleading newlines from showing up in the\n\t\t\/\/ debug output.\n\t\tif s != \"\" {\n\t\t\t\/\/ All users of writeHashingInputs cannot error on Write(), so just\n\t\t\t\/\/ ignore it\n\t\t\tw.Write([]byte(s))\n\t\t}\n\t}\n\n\t\/\/ Apply overrides to the constraints from the root. Otherwise, the hash\n\t\/\/ would be computed on the basis of a constraint from root that doesn't\n\t\/\/ actually affect solving.\n\twc := s.ovr.overrideAll(s.rm.DependencyConstraints().merge(s.rm.TestDependencyConstraints()))\n\n\tfor _, pd := range wc {\n\t\twriteString(string(pd.Ident.ProjectRoot))\n\t\twriteString(pd.Ident.Source)\n\t\t\/\/ FIXME Constraint.String() is a surjective-only transformation - tags\n\t\t\/\/ and branches with the same name are written out as the same string.\n\t\t\/\/ This could, albeit rarely, result in erroneously identical inputs\n\t\t\/\/ when a real change has occurred.\n\t\twriteString(pd.Constraint.String())\n\t}\n\n\t\/\/ Get the external reach list\n\n\t\/\/ Write each of the packages, or the errors that were found for a\n\t\/\/ particular subpath, into the hash. We need to do this in a\n\t\/\/ deterministic order, so expand and sort the map.\n\tvar pkgs []PackageOrErr\n\tfor _, perr := range s.rpt.Packages {\n\t\tpkgs = append(pkgs, perr)\n\t}\n\tsort.Sort(sortPackageOrErr(pkgs))\n\tfor _, perr := range pkgs {\n\t\tif perr.Err != nil {\n\t\t\twriteString(perr.Err.Error())\n\t\t} else {\n\t\t\twriteString(perr.P.Name)\n\t\t\twriteString(perr.P.CommentPath)\n\t\t\twriteString(perr.P.ImportPath)\n\t\t\tfor _, imp := range perr.P.Imports {\n\t\t\t\tif !isStdLib(imp) {\n\t\t\t\t\twriteString(imp)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, imp := range perr.P.TestImports {\n\t\t\t\tif !isStdLib(imp) {\n\t\t\t\t\twriteString(imp)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Write any required packages given in the root manifest.\n\treq := make([]string, 0, len(s.req))\n\tfor pkg := range s.req {\n\t\treq = append(req, pkg)\n\t}\n\tsort.Strings(req)\n\n\tfor _, reqp := range req {\n\t\twriteString(reqp)\n\t}\n\n\t\/\/ Add the ignored packages, if any.\n\tig := make([]string, 0, len(s.ig))\n\tfor pkg := range s.ig {\n\t\tig = append(ig, pkg)\n\t}\n\tsort.Strings(ig)\n\n\tfor _, igp := range ig {\n\t\twriteString(igp)\n\t}\n\n\tfor _, pc := range s.ovr.asSortedSlice() {\n\t\twriteString(string(pc.Ident.ProjectRoot))\n\t\tif pc.Ident.Source != \"\" {\n\t\t\twriteString(pc.Ident.Source)\n\t\t}\n\t\tif pc.Constraint != nil {\n\t\t\twriteString(pc.Constraint.String())\n\t\t}\n\t}\n\n\tan, av := s.b.AnalyzerInfo()\n\twriteString(an)\n\twriteString(av.String())\n}\n\n\/\/ bytes.Buffer wrapper that injects newlines after each call to Write().\ntype nlbuf bytes.Buffer\n\nfunc (buf *nlbuf) Write(p []byte) (n int, err error) {\n\tn, _ = (*bytes.Buffer)(buf).Write(p)\n\t(*bytes.Buffer)(buf).WriteByte('\\n')\n\treturn n + 1, nil\n}\n\n\/\/ HashingInputsAsString returns the raw input data used by Solver.HashInputs()\n\/\/ as a string.\n\/\/\n\/\/ This is primarily intended for debugging purposes.\nfunc HashingInputsAsString(s Solver) string {\n\tts := s.(*solver)\n\tbuf := new(nlbuf)\n\tts.writeHashingInputs(buf)\n\n\treturn (*bytes.Buffer)(buf).String()\n}\n\ntype sortPackageOrErr []PackageOrErr\n\nfunc (s sortPackageOrErr) Len() int      { return len(s) }\nfunc (s sortPackageOrErr) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s sortPackageOrErr) Less(i, j int) bool {\n\ta, b := s[i], s[j]\n\tif a.Err != nil || b.Err != nil {\n\t\t\/\/ Sort errors last.\n\t\tif b.Err == nil {\n\t\t\treturn false\n\t\t}\n\t\tif a.Err == nil {\n\t\t\treturn true\n\t\t}\n\t\t\/\/ And then by string.\n\t\treturn a.Err.Error() < b.Err.Error()\n\t}\n\t\/\/ And finally, sort by import path.\n\treturn a.P.ImportPath < b.P.ImportPath\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2014 Google Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage examples_test\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"testing\"\n\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\/latest\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\/validation\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/runtime\"\n\t\"github.com\/golang\/glog\"\n)\n\nfunc validateObject(obj runtime.Object) (errors []error) {\n\tctx := api.NewDefaultContext()\n\tswitch t := obj.(type) {\n\tcase *api.ReplicationController:\n\t\tif t.Namespace == \"\" {\n\t\t\tt.Namespace = api.NamespaceDefault\n\t\t}\n\t\terrors = validation.ValidateReplicationController(t)\n\tcase *api.ReplicationControllerList:\n\t\tfor i := range t.Items {\n\t\t\terrors = append(errors, validateObject(&t.Items[i])...)\n\t\t}\n\tcase *api.Service:\n\t\tif t.Namespace == \"\" {\n\t\t\tt.Namespace = api.NamespaceDefault\n\t\t}\n\t\tapi.ValidNamespace(ctx, &t.ObjectMeta)\n\t\terrors = validation.ValidateService(t)\n\tcase *api.ServiceList:\n\t\tfor i := range t.Items {\n\t\t\terrors = append(errors, validateObject(&t.Items[i])...)\n\t\t}\n\tcase *api.Pod:\n\t\tif t.Namespace == \"\" {\n\t\t\tt.Namespace = api.NamespaceDefault\n\t\t}\n\t\tapi.ValidNamespace(ctx, &t.ObjectMeta)\n\t\terrors = validation.ValidatePod(t)\n\tcase *api.PodList:\n\t\tfor i := range t.Items {\n\t\t\terrors = append(errors, validateObject(&t.Items[i])...)\n\t\t}\n\tdefault:\n\t\treturn []error{fmt.Errorf(\"no validation defined for %#v\", obj)}\n\t}\n\treturn errors\n}\n\nfunc walkJSONFiles(inDir string, fn func(name, path string, data []byte)) error {\n\terr := filepath.Walk(inDir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif info.IsDir() && path != inDir {\n\t\t\treturn filepath.SkipDir\n\t\t}\n\t\tname := filepath.Base(path)\n\t\text := filepath.Ext(name)\n\t\tif ext != \"\" {\n\t\t\tname = name[:len(name)-len(ext)]\n\t\t}\n\t\tif !(ext == \".json\" || ext == \".yaml\") {\n\t\t\treturn nil\n\t\t}\n\t\tglog.Infof(\"Testing %s\", path)\n\t\tdata, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfn(name, path, data)\n\t\treturn nil\n\t})\n\treturn err\n}\n\nfunc TestExampleObjectSchemas(t *testing.T) {\n\tcases := map[string]map[string]runtime.Object{\n\t\t\"..\/api\/examples\": {\n\t\t\t\"controller\":       &api.ReplicationController{},\n\t\t\t\"controller-list\":  &api.ReplicationControllerList{},\n\t\t\t\"pod\":              &api.Pod{},\n\t\t\t\"pod-list\":         &api.PodList{},\n\t\t\t\"service\":          &api.Service{},\n\t\t\t\"external-service\": &api.Service{},\n\t\t\t\"service-list\":     &api.ServiceList{},\n\t\t},\n\t\t\"..\/examples\/guestbook\": {\n\t\t\t\"frontend-controller\":    &api.ReplicationController{},\n\t\t\t\"redis-slave-controller\": &api.ReplicationController{},\n\t\t\t\"redis-master\":           &api.Pod{},\n\t\t\t\"frontend-service\":       &api.Service{},\n\t\t\t\"redis-master-service\":   &api.Service{},\n\t\t\t\"redis-slave-service\":    &api.Service{},\n\t\t},\n\t\t\"..\/examples\/guestbook\/v3_json_files\": {\n\t\t\t\"frontend-controller\":    &api.ReplicationController{},\n\t\t\t\"redis-slave-controller\": &api.ReplicationController{},\n\t\t\t\"redis-master\":           &api.ReplicationController{},\n\t\t\t\"frontend-service\":       &api.Service{},\n\t\t\t\"redis-master-service\":   &api.Service{},\n\t\t\t\"redis-slave-service\":    &api.Service{},\n\t\t},\n\t\t\"..\/examples\/walkthrough\": {\n\t\t\t\"pod1\": &api.Pod{},\n\t\t\t\"pod2\": &api.Pod{},\n\t\t\t\"pod-with-http-healthcheck\": &api.Pod{},\n\t\t\t\"service\":                   &api.Service{},\n\t\t\t\"replication-controller\":    &api.ReplicationController{},\n\t\t},\n\t\t\"..\/examples\/update-demo\": {\n\t\t\t\"kitten-rc\":   &api.ReplicationController{},\n\t\t\t\"nautilus-rc\": &api.ReplicationController{},\n\t\t},\n\t}\n\n\tfor path, expected := range cases {\n\t\ttested := 0\n\t\terr := walkJSONFiles(path, func(name, path string, data []byte) {\n\t\t\texpectedType, found := expected[name]\n\t\t\tif !found {\n\t\t\t\tt.Errorf(\"%s does not have a test case defined\", path)\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttested += 1\n\t\t\tif err := latest.Codec.DecodeInto(data, expectedType); err != nil {\n\t\t\t\tt.Errorf(\"%s did not decode correctly: %v\\n%s\", path, err, string(data))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif errors := validateObject(expectedType); len(errors) > 0 {\n\t\t\t\tt.Errorf(\"%s did not validate correctly: %v\", path, errors)\n\t\t\t}\n\t\t})\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Expected no error, Got %v\", err)\n\t\t}\n\t\tif tested != len(expected) {\n\t\t\tt.Errorf(\"Expected %d examples, Got %d\", len(expected), tested)\n\t\t}\n\t}\n}\n\nvar sampleRegexp = regexp.MustCompile(\"(?ms)^```(?:(?P<type>yaml)\\\\w*\\\\n(?P<content>.+?)|\\\\w*\\\\n(?P<content>\\\\{.+?\\\\}))\\\\w*\\\\n^```\")\nvar subsetRegexp = regexp.MustCompile(\"(?ms)\\\\.{3}\")\n\nfunc TestReadme(t *testing.T) {\n\tpaths := []string{\n\t\t\"..\/README.md\",\n\t\t\"..\/examples\/walkthrough\/README.md\",\n\t}\n\n\tfor _, path := range paths {\n\t\tdata, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unable to read file %s: %v\", path, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tmatches := sampleRegexp.FindAllStringSubmatch(string(data), -1)\n\t\tif matches == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, match := range matches {\n\t\t\tvar content, subtype string\n\t\t\tfor i, name := range sampleRegexp.SubexpNames() {\n\t\t\t\tif name == \"type\" {\n\t\t\t\t\tsubtype = match[i]\n\t\t\t\t}\n\t\t\t\tif name == \"content\" && match[i] != \"\" {\n\t\t\t\t\tcontent = match[i]\n\t\t\t\t}\n\t\t\t}\n\t\t\tif subtype == \"yaml\" && subsetRegexp.FindString(content) != \"\" {\n\t\t\t\tt.Logf(\"skipping (%s): \\n%s\", subtype, content)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/t.Logf(\"testing (%s): \\n%s\", subtype, content)\n\t\t\texpectedType := &api.Pod{}\n\t\t\tif err := latest.Codec.DecodeInto([]byte(content), expectedType); err != nil {\n\t\t\t\tt.Errorf(\"%s did not decode correctly: %v\\n%s\", path, err, string(content))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif errors := validateObject(expectedType); len(errors) > 0 {\n\t\t\t\tt.Errorf(\"%s did not validate correctly: %v\", path, errors)\n\t\t\t}\n\t\t\t_, err := latest.Codec.Encode(expectedType)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Could not encode object: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>updating testcases<commit_after>\/*\nCopyright 2014 Google Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage examples_test\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"testing\"\n\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\/latest\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/api\/validation\"\n\t\"github.com\/GoogleCloudPlatform\/kubernetes\/pkg\/runtime\"\n\t\"github.com\/golang\/glog\"\n)\n\nfunc validateObject(obj runtime.Object) (errors []error) {\n\tctx := api.NewDefaultContext()\n\tswitch t := obj.(type) {\n\tcase *api.ReplicationController:\n\t\tif t.Namespace == \"\" {\n\t\t\tt.Namespace = api.NamespaceDefault\n\t\t}\n\t\terrors = validation.ValidateReplicationController(t)\n\tcase *api.ReplicationControllerList:\n\t\tfor i := range t.Items {\n\t\t\terrors = append(errors, validateObject(&t.Items[i])...)\n\t\t}\n\tcase *api.Service:\n\t\tif t.Namespace == \"\" {\n\t\t\tt.Namespace = api.NamespaceDefault\n\t\t}\n\t\tapi.ValidNamespace(ctx, &t.ObjectMeta)\n\t\terrors = validation.ValidateService(t)\n\tcase *api.ServiceList:\n\t\tfor i := range t.Items {\n\t\t\terrors = append(errors, validateObject(&t.Items[i])...)\n\t\t}\n\tcase *api.Pod:\n\t\tif t.Namespace == \"\" {\n\t\t\tt.Namespace = api.NamespaceDefault\n\t\t}\n\t\tapi.ValidNamespace(ctx, &t.ObjectMeta)\n\t\terrors = validation.ValidatePod(t)\n\tcase *api.PodList:\n\t\tfor i := range t.Items {\n\t\t\terrors = append(errors, validateObject(&t.Items[i])...)\n\t\t}\n\tdefault:\n\t\treturn []error{fmt.Errorf(\"no validation defined for %#v\", obj)}\n\t}\n\treturn errors\n}\n\nfunc walkJSONFiles(inDir string, fn func(name, path string, data []byte)) error {\n\terr := filepath.Walk(inDir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif info.IsDir() && path != inDir {\n\t\t\treturn filepath.SkipDir\n\t\t}\n\t\tname := filepath.Base(path)\n\t\text := filepath.Ext(name)\n\t\tif ext != \"\" {\n\t\t\tname = name[:len(name)-len(ext)]\n\t\t}\n\t\tif !(ext == \".json\" || ext == \".yaml\") {\n\t\t\treturn nil\n\t\t}\n\t\tglog.Infof(\"Testing %s\", path)\n\t\tdata, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfn(name, path, data)\n\t\treturn nil\n\t})\n\treturn err\n}\n\nfunc TestExampleObjectSchemas(t *testing.T) {\n\tcases := map[string]map[string]runtime.Object{\n\t\t\"..\/api\/examples\": {\n\t\t\t\"controller\":       &api.ReplicationController{},\n\t\t\t\"controller-list\":  &api.ReplicationControllerList{},\n\t\t\t\"pod\":              &api.Pod{},\n\t\t\t\"pod-list\":         &api.PodList{},\n\t\t\t\"service\":          &api.Service{},\n\t\t\t\"external-service\": &api.Service{},\n\t\t\t\"service-list\":     &api.ServiceList{},\n\t\t},\n\t\t\"..\/examples\/guestbook\": {\n\t\t\t\"frontend-controller\":    &api.ReplicationController{},\n\t\t\t\"redis-slave-controller\": &api.ReplicationController{},\n\t\t\t\"redis-master\":           &api.Pod{},\n\t\t\t\"frontend-service\":       &api.Service{},\n\t\t\t\"redis-master-service\":   &api.Service{},\n\t\t\t\"redis-slave-service\":    &api.Service{},\n\t\t},\n\t\t\"..\/examples\/guestbook\/v3_json_files\": {\n\t\t\t\"frontend-controller\":    &api.ReplicationController{},\n\t\t\t\"redis-slave-controller\": &api.ReplicationController{},\n\t\t\t\"redis-master\":           &api.ReplicationController{},\n\t\t\t\"frontend-service\":       &api.Service{},\n\t\t\t\"redis-master-service\":   &api.Service{},\n\t\t\t\"redis-slave-service\":    &api.Service{},\n\t\t},\n\t\t\"..\/examples\/guestbook-go\": {\n\t\t\t\"guestbook-controller\":    &api.ReplicationController{},\n\t\t\t\"redis-slave-controller\":  &api.ReplicationController{},\n\t\t\t\"redis-master-controller\": &api.ReplicationController{},\n\t\t\t\"guestbook-service\":       &api.Service{},\n\t\t\t\"redis-master-service\":    &api.Service{},\n\t\t\t\"redis-slave-service\":     &api.Service{},\n\t\t},\n\t\t\"..\/examples\/guestbook-go\/v3_json_files\": {\n\t\t\t\"guestbook-controller\":    &api.ReplicationController{},\n\t\t\t\"redis-slave-controller\":  &api.ReplicationController{},\n\t\t\t\"redis-master-controller\": &api.ReplicationController{},\n\t\t\t\"guestbook-service\":       &api.Service{},\n\t\t\t\"redis-master-service\":    &api.Service{},\n\t\t\t\"redis-slave-service\":     &api.Service{},\n\t\t},\n\t\t\"..\/examples\/walkthrough\": {\n\t\t\t\"pod1\": &api.Pod{},\n\t\t\t\"pod2\": &api.Pod{},\n\t\t\t\"pod-with-http-healthcheck\": &api.Pod{},\n\t\t\t\"service\":                   &api.Service{},\n\t\t\t\"replication-controller\":    &api.ReplicationController{},\n\t\t},\n\t\t\"..\/examples\/update-demo\": {\n\t\t\t\"kitten-rc\":   &api.ReplicationController{},\n\t\t\t\"nautilus-rc\": &api.ReplicationController{},\n\t\t},\n\t}\n\n\tfor path, expected := range cases {\n\t\ttested := 0\n\t\terr := walkJSONFiles(path, func(name, path string, data []byte) {\n\t\t\texpectedType, found := expected[name]\n\t\t\tif !found {\n\t\t\t\tt.Errorf(\"%s does not have a test case defined\", path)\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttested += 1\n\t\t\tif err := latest.Codec.DecodeInto(data, expectedType); err != nil {\n\t\t\t\tt.Errorf(\"%s did not decode correctly: %v\\n%s\", path, err, string(data))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif errors := validateObject(expectedType); len(errors) > 0 {\n\t\t\t\tt.Errorf(\"%s did not validate correctly: %v\", path, errors)\n\t\t\t}\n\t\t})\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Expected no error, Got %v\", err)\n\t\t}\n\t\tif tested != len(expected) {\n\t\t\tt.Errorf(\"Expected %d examples, Got %d\", len(expected), tested)\n\t\t}\n\t}\n}\n\nvar sampleRegexp = regexp.MustCompile(\"(?ms)^```(?:(?P<type>yaml)\\\\w*\\\\n(?P<content>.+?)|\\\\w*\\\\n(?P<content>\\\\{.+?\\\\}))\\\\w*\\\\n^```\")\nvar subsetRegexp = regexp.MustCompile(\"(?ms)\\\\.{3}\")\n\nfunc TestReadme(t *testing.T) {\n\tpaths := []string{\n\t\t\"..\/README.md\",\n\t\t\"..\/examples\/walkthrough\/README.md\",\n\t}\n\n\tfor _, path := range paths {\n\t\tdata, err := ioutil.ReadFile(path)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Unable to read file %s: %v\", path, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tmatches := sampleRegexp.FindAllStringSubmatch(string(data), -1)\n\t\tif matches == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, match := range matches {\n\t\t\tvar content, subtype string\n\t\t\tfor i, name := range sampleRegexp.SubexpNames() {\n\t\t\t\tif name == \"type\" {\n\t\t\t\t\tsubtype = match[i]\n\t\t\t\t}\n\t\t\t\tif name == \"content\" && match[i] != \"\" {\n\t\t\t\t\tcontent = match[i]\n\t\t\t\t}\n\t\t\t}\n\t\t\tif subtype == \"yaml\" && subsetRegexp.FindString(content) != \"\" {\n\t\t\t\tt.Logf(\"skipping (%s): \\n%s\", subtype, content)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/t.Logf(\"testing (%s): \\n%s\", subtype, content)\n\t\t\texpectedType := &api.Pod{}\n\t\t\tif err := latest.Codec.DecodeInto([]byte(content), expectedType); err != nil {\n\t\t\t\tt.Errorf(\"%s did not decode correctly: %v\\n%s\", path, err, string(content))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif errors := validateObject(expectedType); len(errors) > 0 {\n\t\t\t\tt.Errorf(\"%s did not validate correctly: %v\", path, errors)\n\t\t\t}\n\t\t\t_, err := latest.Codec.Encode(expectedType)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Could not encode object: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package sexp\n\nfunc DontPanic(f func() error) (err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tif ue, ok := e.(*UnmarshalError); ok {\n\t\t\t\terr = ue\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\treturn f()\n}\n\n\/\/ A simple helper structure inspired by the simplejson-go API. Use Help\n\/\/ function to actually acquire it from the given *Node.\ntype Helper struct {\n\tnode *Node\n\terr *UnmarshalError\n}\n\nfunc Help(node *Node) Helper {\n\treturn Helper{node, nil}\n}\n\nfunc (h Helper) IsValid() bool {\n\treturn h.node != nil\n}\n\nfunc (h Helper) Next() Helper {\n\tif h.node == nil {\n\t\treturn h\n\t}\n\tif h.node.Next == nil {\n\t\terr := NewUnmarshalError(h.node, nil,\n\t\t\t\"a sibling of the node was requested, but it has none\")\n\t\treturn Helper{nil, err}\n\t}\n\treturn Helper{h.node.Next, nil}\n}\n\nfunc (h Helper) Child(n int) Helper {\n\tif h.node == nil {\n\t\treturn h\n\t}\n\tc := h.node.Children\n\tif c == nil {\n\t\terr := NewUnmarshalError(h.node, nil,\n\t\t\t\"cannot retrieve %d%s child node, node is not a list\",\n\t\t\tn+1, number_suffix(n+1))\n\t\treturn Helper{nil, err}\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tc = c.Next\n\t\tif c == nil {\n\t\t\terr := NewUnmarshalError(h.node, nil,\n\t\t\t\t\"cannot retrieve %d%s child node, %s\",\n\t\t\t\tn+1, number_suffix(n+1),\n\t\t\t\tthe_list_has_n_children(h.node.NumChildren()))\n\t\t\treturn Helper{nil, err}\n\t\t}\n\t}\n\treturn Helper{c, nil}\n}\n\nfunc (h Helper) IsList() bool {\n\tif h.node == nil {\n\t\treturn false\n\t}\n\treturn h.node.IsList()\n}\n\nfunc (h Helper) IsScalar() bool {\n\tif h.node == nil {\n\t\treturn false\n\t}\n\treturn h.node.IsScalar()\n}\n\nfunc (h Helper) Bool() (bool, error) {\n\tif h.node == nil {\n\t\treturn false, h.err\n\t}\n\tvar v bool\n\terr := h.node.Unmarshal(&v)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn v, nil\n}\n\nfunc (h Helper) Int() (int, error) {\n\tif h.node == nil {\n\t\treturn 0, h.err\n\t}\n\tvar v int\n\terr := h.node.Unmarshal(&v)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v, nil\n}\n\nfunc (h Helper) Float64() (float64, error) {\n\tif h.node == nil {\n\t\treturn 0, h.err\n\t}\n\tvar v float64\n\terr := h.node.Unmarshal(&v)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v, nil\n}\n\nfunc (h Helper) String() (string, error) {\n\tif h.node == nil {\n\t\treturn \"\", h.err\n\t}\n\tvar v string\n\terr := h.node.Unmarshal(&v)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn v, nil\n}\n\nfunc (h Helper) MustBool() bool {\n\tv, err := h.Bool()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}\n\nfunc (h Helper) MustInt() int {\n\tv, err := h.Int()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}\n\nfunc (h Helper) MustFloat64() float64 {\n\tv, err := h.Float64()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}\n\nfunc (h Helper) MustString() string {\n\tv, err := h.String()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}\n<commit_msg>Add Node and MustNode accessors for Helper.<commit_after>package sexp\n\nfunc DontPanic(f func() error) (err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tif ue, ok := e.(*UnmarshalError); ok {\n\t\t\t\terr = ue\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpanic(e)\n\t\t}\n\t}()\n\treturn f()\n}\n\n\/\/ A simple helper structure inspired by the simplejson-go API. Use Help\n\/\/ function to actually acquire it from the given *Node.\ntype Helper struct {\n\tnode *Node\n\terr *UnmarshalError\n}\n\nfunc Help(node *Node) Helper {\n\treturn Helper{node, nil}\n}\n\nfunc (h Helper) IsValid() bool {\n\treturn h.node != nil\n}\n\nfunc (h Helper) Next() Helper {\n\tif h.node == nil {\n\t\treturn h\n\t}\n\tif h.node.Next == nil {\n\t\terr := NewUnmarshalError(h.node, nil,\n\t\t\t\"a sibling of the node was requested, but it has none\")\n\t\treturn Helper{nil, err}\n\t}\n\treturn Helper{h.node.Next, nil}\n}\n\nfunc (h Helper) Child(n int) Helper {\n\tif h.node == nil {\n\t\treturn h\n\t}\n\tc := h.node.Children\n\tif c == nil {\n\t\terr := NewUnmarshalError(h.node, nil,\n\t\t\t\"cannot retrieve %d%s child node, node is not a list\",\n\t\t\tn+1, number_suffix(n+1))\n\t\treturn Helper{nil, err}\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tc = c.Next\n\t\tif c == nil {\n\t\t\terr := NewUnmarshalError(h.node, nil,\n\t\t\t\t\"cannot retrieve %d%s child node, %s\",\n\t\t\t\tn+1, number_suffix(n+1),\n\t\t\t\tthe_list_has_n_children(h.node.NumChildren()))\n\t\t\treturn Helper{nil, err}\n\t\t}\n\t}\n\treturn Helper{c, nil}\n}\n\nfunc (h Helper) IsList() bool {\n\tif h.node == nil {\n\t\treturn false\n\t}\n\treturn h.node.IsList()\n}\n\nfunc (h Helper) IsScalar() bool {\n\tif h.node == nil {\n\t\treturn false\n\t}\n\treturn h.node.IsScalar()\n}\n\nfunc (h Helper) Bool() (bool, error) {\n\tif h.node == nil {\n\t\treturn false, h.err\n\t}\n\tvar v bool\n\terr := h.node.Unmarshal(&v)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn v, nil\n}\n\nfunc (h Helper) Int() (int, error) {\n\tif h.node == nil {\n\t\treturn 0, h.err\n\t}\n\tvar v int\n\terr := h.node.Unmarshal(&v)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v, nil\n}\n\nfunc (h Helper) Float64() (float64, error) {\n\tif h.node == nil {\n\t\treturn 0, h.err\n\t}\n\tvar v float64\n\terr := h.node.Unmarshal(&v)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn v, nil\n}\n\nfunc (h Helper) String() (string, error) {\n\tif h.node == nil {\n\t\treturn \"\", h.err\n\t}\n\tvar v string\n\terr := h.node.Unmarshal(&v)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn v, nil\n}\n\nfunc (h Helper) Node() (*Node, error) {\n\tif h.node == nil {\n\t\treturn nil, h.err\n\t}\n\treturn h.node, nil\n}\n\nfunc (h Helper) MustBool() bool {\n\tv, err := h.Bool()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}\n\nfunc (h Helper) MustInt() int {\n\tv, err := h.Int()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}\n\nfunc (h Helper) MustFloat64() float64 {\n\tv, err := h.Float64()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}\n\nfunc (h Helper) MustString() string {\n\tv, err := h.String()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}\n\nfunc (h Helper) MustNode() *Node {\n\tv, err := h.Node()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn v\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013-2014 by Michael Dvorkin. All Rights Reserved.\n\/\/ Use of this source code is governed by a MIT-style license that can\n\/\/ be found in the LICENSE file.\n\npackage expect\n\nimport(`fmt`; `runtime`; `path\/filepath`; `strings`; `testing`)\n\nfunc Eq(t *testing.T, actual, expected interface{}) {\n\tlog(t, actual, expected, equal(actual, expected))\n}\n\nfunc True(t *testing.T, actual interface{}) {\n\tlog(t, actual, true, equal(actual, true))\n}\n\nfunc False(t *testing.T, actual interface{}) {\n\tlog(t, actual, false, equal(actual, false))\n}\n\nfunc Contain(t *testing.T, actual interface{}, expected string) {\n\tmatch(t, fmt.Sprintf(`%+v`, actual), expected, true)\n}\n\nfunc NotContain(t *testing.T, actual interface{}, expected string) {\n\tmatch(t, fmt.Sprintf(`%+v`, actual), expected, false)\n}\n\nfunc equal(actual, expected interface{}) (passed bool) {\n\tswitch expected.(type) {\n\tcase bool:\n\t\tif assertion, ok := actual.(bool); ok {\n\t\t\tpassed = (assertion == expected)\n\t\t}\n\tcase int:\n\t\tif assertion, ok := actual.(int); ok {\n\t\t\tpassed = (assertion == expected)\n\t\t}\n\tcase uint64:\n\t\tif assertion, ok := actual.(uint64); ok {\n\t\t\tpassed = (assertion == expected)\n\t\t}\n\tdefault:\n\t\tpassed = (fmt.Sprintf(`%v`, actual) == fmt.Sprintf(`%v`, expected))\n\t}\n\treturn\n}\n\n\/\/ Simple success\/failure logger that assumes source test file is at Caller(2).\nfunc log(t *testing.T, actual, expected interface{}, passed bool) {\n\t_, file, line, _ := runtime.Caller(2) \t\/\/ Get the calling file path and line number.\n\tfile = filepath.Base(file) \t\t\/\/ Keep file name only.\n\n\tif !passed {\n\t\tt.Errorf(\"\\r\\t\\x1B[31m%s line %d\\nExpected: %v\\n  Actual: %v\\x1B[0m\", file, line, expected, actual)\n\t} else if (testing.Verbose()) {\n\t\tt.Logf(\"\\r\\t\\x1B[32m%s line %d: %v\\x1B[0m\", file, line, actual)\n\t}\n}\n\nfunc match(t *testing.T, actual, expected string, contains bool) {\n\tpassed := (contains == strings.Contains(actual, expected))\n\n\t_, file, line, _ := runtime.Caller(2)\n\tfile = filepath.Base(file)\n\n\tif !passed {\n\t\tt.Errorf(\"\\r\\t\\x1B[31m%s line %d\\nContains: %s\\n  Actual: %s\\x1B[0m\", file, line, expected, actual)\n\t} else if (testing.Verbose()) {\n\t\tt.Logf(\"\\r\\t\\x1B[32m%s line %d: %v\\x1B[0m\", file, line, actual)\n\t}\n}\n<commit_msg>Added expect.Ne(...) for not equal tests<commit_after>\/\/ Copyright (c) 2013-2014 by Michael Dvorkin. All Rights Reserved.\n\/\/ Use of this source code is governed by a MIT-style license that can\n\/\/ be found in the LICENSE file.\n\npackage expect\n\nimport(`fmt`; `runtime`; `path\/filepath`; `strings`; `testing`)\n\nfunc Eq(t *testing.T, actual, expected interface{}) {\n\tlog(t, actual, expected, equal(actual, expected))\n}\n\nfunc Ne(t *testing.T, actual, expected interface{}) {\n\tlog(t, actual, expected, !equal(actual, expected))\n}\n\nfunc True(t *testing.T, actual interface{}) {\n\tlog(t, actual, true, equal(actual, true))\n}\n\nfunc False(t *testing.T, actual interface{}) {\n\tlog(t, actual, false, equal(actual, false))\n}\n\nfunc Contain(t *testing.T, actual interface{}, expected string) {\n\tmatch(t, fmt.Sprintf(`%+v`, actual), expected, true)\n}\n\nfunc NotContain(t *testing.T, actual interface{}, expected string) {\n\tmatch(t, fmt.Sprintf(`%+v`, actual), expected, false)\n}\n\nfunc equal(actual, expected interface{}) (passed bool) {\n\tswitch expected.(type) {\n\tcase bool:\n\t\tif assertion, ok := actual.(bool); ok {\n\t\t\tpassed = (assertion == expected)\n\t\t}\n\tcase int:\n\t\tif assertion, ok := actual.(int); ok {\n\t\t\tpassed = (assertion == expected)\n\t\t}\n\tcase uint64:\n\t\tif assertion, ok := actual.(uint64); ok {\n\t\t\tpassed = (assertion == expected)\n\t\t}\n\tdefault:\n\t\tpassed = (fmt.Sprintf(`%v`, actual) == fmt.Sprintf(`%v`, expected))\n\t}\n\treturn\n}\n\n\/\/ Simple success\/failure logger that assumes source test file is at Caller(2).\nfunc log(t *testing.T, actual, expected interface{}, passed bool) {\n\t_, file, line, _ := runtime.Caller(2) \t\/\/ Get the calling file path and line number.\n\tfile = filepath.Base(file) \t\t\/\/ Keep file name only.\n\n\tif !passed {\n\t\tt.Errorf(\"\\r\\t\\x1B[31m%s line %d\\nExpected: %v\\n  Actual: %v\\x1B[0m\", file, line, expected, actual)\n\t} else if (testing.Verbose()) {\n\t\tt.Logf(\"\\r\\t\\x1B[32m%s line %d: %v\\x1B[0m\", file, line, actual)\n\t}\n}\n\nfunc match(t *testing.T, actual, expected string, contains bool) {\n\tpassed := (contains == strings.Contains(actual, expected))\n\n\t_, file, line, _ := runtime.Caller(2)\n\tfile = filepath.Base(file)\n\n\tif !passed {\n\t\tt.Errorf(\"\\r\\t\\x1B[31m%s line %d\\nContains: %s\\n  Actual: %s\\x1B[0m\", file, line, expected, actual)\n\t} else if (testing.Verbose()) {\n\t\tt.Logf(\"\\r\\t\\x1B[32m%s line %d: %v\\x1B[0m\", file, line, actual)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 The Prometheus Authors\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/ TestNegativeCounter validates when we send a negative\n\/\/ number to a counter that we no longer panic the Exporter Listener.\nfunc TestNegativeCounter(t *testing.T) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr := e.(error)\n\t\t\tif err.Error() == \"counter cannot decrease in value\" {\n\t\t\t\tt.Fatalf(\"Counter was negative and causes a panic.\")\n\t\t\t} else {\n\t\t\t\tt.Fatalf(\"Unknown panic and error: %q\", err.Error())\n\t\t\t}\n\t\t}\n\t}()\n\n\tevents := make(chan Events, 1)\n\tc := Events{\n\t\t&CounterEvent{\n\t\t\tmetricName: \"foo\",\n\t\t\tvalue:      -1,\n\t\t},\n\t}\n\tevents <- c\n\tex := NewExporter(&metricMapper{})\n\n\t\/\/ Close channel to signify we are done with the listener after a short period.\n\tgo func() {\n\t\ttime.Sleep(time.Millisecond * 100)\n\t\tclose(events)\n\t}()\n\n\tex.Listen(events)\n}\n<commit_msg>Fix parameter to NewExporter in test<commit_after>\/\/ Copyright 2013 The Prometheus Authors\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/ TestNegativeCounter validates when we send a negative\n\/\/ number to a counter that we no longer panic the Exporter Listener.\nfunc TestNegativeCounter(t *testing.T) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr := e.(error)\n\t\t\tif err.Error() == \"counter cannot decrease in value\" {\n\t\t\t\tt.Fatalf(\"Counter was negative and causes a panic.\")\n\t\t\t} else {\n\t\t\t\tt.Fatalf(\"Unknown panic and error: %q\", err.Error())\n\t\t\t}\n\t\t}\n\t}()\n\n\tevents := make(chan Events, 1)\n\tc := Events{\n\t\t&CounterEvent{\n\t\t\tmetricName: \"foo\",\n\t\t\tvalue:      -1,\n\t\t},\n\t}\n\tevents <- c\n\tex := NewExporter(&metricMapper{}, true)\n\n\t\/\/ Close channel to signify we are done with the listener after a short period.\n\tgo func() {\n\t\ttime.Sleep(time.Millisecond * 100)\n\t\tclose(events)\n\t}()\n\n\tex.Listen(events)\n}\n<|endoftext|>"}
{"text":"<commit_before>package goat\n\nfunc DbManager() {\n\t\/\/ channels\n\tSqlRequestChan := make(chan Request)\n\tMapRequestChan := make(chan Request, 100)\n\n\t\/\/ launch databases\n\tif Static.Config.Map {\n\t\tgo new(MapDb).HandleDb(Static.RequestChan)\n\t\tStatic.LogChan <- \"MapDb instance launched\"\n\t}\n\tif Static.Config.Sql {\n\t\tgo new(SqlDb).HandleDb(Static.RequestChan)\n\t\tStatic.LogChan <- \"SqlDb instance launched\"\n\t}\n\n\tif Static.Config.Map && Static.Config.Sql {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase hold := <-Static.RequestChan:\n\t\t\t\tif hold.Data == nil {\n\t\t\t\t\tMapRequestChan <- hold\n\t\t\t\t} else {\n\t\t\t\t\tMapRequestChan <- hold\n\t\t\t\t\tSqlRequestChan <- hold\n\t\t\t\t}\n\t\t\tcase hold := <-Static.PersistentChan:\n\t\t\t\tSqlRequestChan <- hold\n\t\t\t}\n\t\t}\n\t} else if Static.Config.Map {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase hold := <-Static.RequestChan:\n\t\t\t\tMapRequestChan <- hold\n\t\t\t}\n\t\t}\n\t} else if Static.Config.Sql {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase hold := <-Static.RequestChan:\n\t\t\t\tSqlRequestChan <- hold\n\t\t\t}\n\t\t}\n\t} else {\n\t\tStatic.LogChan <- \"No database in use.\"\n\t}\n}\n\n\/\/ Holds information for request from database\ntype Request struct {\n\tId           string\n\tData         interface{}\n\tResponseChan chan Response\n}\n\n\/\/ Holds information for response from database\ntype Response struct {\n\tId   string\n\tDb   string\n\tData interface{}\n}\ntype WriteResponse struct {\n\tComplete bool\n}\n\n\/\/ DbHandler interface method HandleDb defines a database handler which handles requests\ntype DbHandler interface {\n\tHandleDb(RequestChan chan Request)\n}\n\n\/\/ MapDb is a key value storage database\n\/\/ Id will be an identification for sharding\ntype MapDb struct {\n\tId      string\n\tDb      map[string]map[string]interface{}\n\tWorkers map[string]MapWorker\n}\n\n\/\/ Handle data MapDb requests\nfunc (db MapDb) HandleDb(RequestChan chan Request) {\n\tdb.Db = make(map[string]map[string]interface{})\n\tfor {\n\t\tselect {\n\t\tcase hold := <-RequestChan:\n\t\t\tl := len(hold.Id)\n\t\t\ts := Static.Config.CacheSize\n\t\t\tkey := hold.Id[l-s : l-1]\n\t\t\tswitch {\n\t\t\t\/\/ This logic needs to be refactored so that the number of shards can be\n\t\t\t\/\/ determined via the config file, which will define the number of digits\n\t\t\t\/\/ used from the ID for the shard name\n\t\t\tcase hold.Data == nil:\n\t\t\t\t_, ok := db.Db[key]\n\t\t\t\tif !ok {\n\t\t\t\t\tdb.Db[key] = make(map[string]interface{})\n\t\t\t\t}\n\t\t\t\tgo new(MapWorker).Read(hold, db.Db[key])\n\t\t\tcase hold.Data != nil:\n\t\t\t\t_, ok := db.Db[key]\n\t\t\t\tif !ok {\n\t\t\t\t\tdb.Db[key] = make(map[string]interface{})\n\t\t\t\t}\n\t\t\t\tgo new(MapWorker).Write(hold, db.Db[key])\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ SqlDb is a Sql based database\ntype SqlDb struct {\n}\n\n\/\/ Handle Sql based requests\nfunc (s SqlDb) HandleDb(RequestChan chan Request) {\n}\n<commit_msg>fixed blockign request chan<commit_after>package goat\n\nfunc DbManager() {\n\t\/\/ channels\n\tSqlRequestChan := make(chan Request)\n\tMapRequestChan := make(chan Request, 100)\n\n\t\/\/ launch databases\n\tif Static.Config.Map {\n\t\tgo new(MapDb).HandleDb(MapRequestChan)\n\t\tStatic.LogChan <- \"MapDb instance launched\"\n\t}\n\tif Static.Config.Sql {\n\t\tgo new(SqlDb).HandleDb(SqlRequestChan)\n\t\tStatic.LogChan <- \"SqlDb instance launched\"\n\t}\n\n\tif Static.Config.Map && Static.Config.Sql {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase hold := <-Static.RequestChan:\n\t\t\t\tif hold.Data == nil {\n\t\t\t\t\tMapRequestChan <- hold\n\t\t\t\t} else {\n\t\t\t\t\tMapRequestChan <- hold\n\t\t\t\t\tSqlRequestChan <- hold\n\t\t\t\t}\n\t\t\tcase hold := <-Static.PersistentChan:\n\t\t\t\tSqlRequestChan <- hold\n\t\t\t}\n\t\t}\n\t} else if Static.Config.Map {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase hold := <-Static.RequestChan:\n\t\t\t\tMapRequestChan <- hold\n\t\t\t}\n\t\t}\n\t} else if Static.Config.Sql {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase hold := <-Static.RequestChan:\n\t\t\t\tSqlRequestChan <- hold\n\t\t\t}\n\t\t}\n\t} else {\n\t\tStatic.LogChan <- \"No database in use.\"\n\t}\n}\n\n\/\/ Holds information for request from database\ntype Request struct {\n\tId           string\n\tData         interface{}\n\tResponseChan chan Response\n}\n\n\/\/ Holds information for response from database\ntype Response struct {\n\tId   string\n\tDb   string\n\tData interface{}\n}\ntype WriteResponse struct {\n\tComplete bool\n}\n\n\/\/ DbHandler interface method HandleDb defines a database handler which handles requests\ntype DbHandler interface {\n\tHandleDb(RequestChan chan Request)\n}\n\n\/\/ MapDb is a key value storage database\n\/\/ Id will be an identification for sharding\ntype MapDb struct {\n\tId      string\n\tDb      map[string]map[string]interface{}\n\tWorkers map[string]MapWorker\n}\n\n\/\/ Handle data MapDb requests\nfunc (db MapDb) HandleDb(RequestChan chan Request) {\n\tdb.Db = make(map[string]map[string]interface{})\n\tfor {\n\t\tselect {\n\t\tcase hold := <-RequestChan:\n\t\t\tl := len(hold.Id)\n\t\t\ts := Static.Config.CacheSize\n\t\t\tkey := hold.Id[l-s : l-1]\n\t\t\tswitch {\n\t\t\t\/\/ This logic needs to be refactored so that the number of shards can be\n\t\t\t\/\/ determined via the config file, which will define the number of digits\n\t\t\t\/\/ used from the ID for the shard name\n\t\t\tcase hold.Data == nil:\n\t\t\t\t\/\/ check if key exits\n\t\t\t\t_, ok := db.Db[key]\n\t\t\t\tif !ok {\n\t\t\t\t\t\/\/ if key does not exist, make a new map with the given key\n\t\t\t\t\tdb.Db[key] = make(map[string]interface{})\n\t\t\t\t}\n\t\t\t\tgo new(MapWorker).Read(hold, db.Db[key])\n\t\t\tcase hold.Data != nil:\n\t\t\t\t\/\/ check if key exits\n\t\t\t\t_, ok := db.Db[key]\n\t\t\t\tif !ok {\n\t\t\t\t\t\/\/ if key does not exist, make a new map with the given key\n\t\t\t\t\tdb.Db[key] = make(map[string]interface{})\n\t\t\t\t}\n\t\t\t\tgo new(MapWorker).Write(hold, db.Db[key])\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ SqlDb is a Sql based database\ntype SqlDb struct {\n}\n\n\/\/ Handle Sql based requests\nfunc (s SqlDb) HandleDb(RequestChan chan Request) {\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\tauth \"github.com\/heroku\/lumbermill\/Godeps\/_workspace\/src\/github.com\/heroku\/authenticater\"\n\tinflux \"github.com\/heroku\/lumbermill\/Godeps\/_workspace\/src\/github.com\/influxdb\/influxdb-go\"\n)\n\nvar influxDbStaleTimeout = 24 * time.Minute \/\/ Would be nice to make this smaller, but it lags due to continuous queries.\nvar influxDbSeriesCheckQueries = []string{\n\t\"select * from MaxMean1mLoad.10m.dyno.dyno.load.%s limit 1\",\n\t\"select * from MaxMeanRssSwapMemory.10m.dyno.mem.%s limit 1\",\n}\n\nvar healthCheckClientsLock = new(sync.Mutex)\nvar healthCheckClients = make(map[string]*influx.Client)\n\ntype server struct {\n\tsync.WaitGroup\n\tconnectionCloser chan struct{}\n\thashRing         *hashRing\n\thttp             *http.Server\n\tshutdownChan     shutdownChan\n\tisShuttingDown   bool\n\tcredStore        map[string]string\n\n\t\/\/ scheduler based sampling lock for writing to recentTokens\n\ttokenLock        *int32\n\trecentTokensLock *sync.RWMutex\n\trecentTokens     map[string]string\n}\n\nfunc newServer(httpServer *http.Server, ath auth.Authenticater, hashRing *hashRing) *server {\n\ts := &server{\n\t\tconnectionCloser: make(chan struct{}),\n\t\tshutdownChan:     make(chan struct{}),\n\t\thttp:             httpServer,\n\t\thashRing:         hashRing,\n\t\tcredStore:        make(map[string]string),\n\t\ttokenLock:        new(int32),\n\t\trecentTokensLock: new(sync.RWMutex),\n\t\trecentTokens:     make(map[string]string),\n\t}\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"\/drain\", auth.WrapAuth(ath,\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\ts.serveDrain(w, r)\n\t\t\ts.recycleConnection(w)\n\t\t}))\n\n\tmux.HandleFunc(\"\/health\", s.serveHealth)\n\tmux.HandleFunc(\"\/health\/influxdb\", s.serveInfluxDBHealth)\n\tmux.HandleFunc(\"\/target\/\", auth.WrapAuth(ath, s.serveTarget))\n\n\ts.http.Handler = mux\n\n\treturn s\n}\n\nfunc (s *server) Close() error {\n\ts.shutdownChan <- struct{}{}\n\treturn nil\n}\n\nfunc (s *server) scheduleConnectionRecycling(after time.Duration) {\n\tfor !s.isShuttingDown {\n\t\ttime.Sleep(after)\n\t\ts.connectionCloser <- struct{}{}\n\t}\n}\n\nfunc (s *server) recycleConnection(w http.ResponseWriter) {\n\tselect {\n\tcase <-s.connectionCloser:\n\t\tw.Header().Set(\"Connection\", \"close\")\n\tdefault:\n\t\tif s.isShuttingDown {\n\t\t\tw.Header().Set(\"Connection\", \"close\")\n\t\t}\n\t}\n}\n\nfunc (s *server) Run(connRecycle time.Duration) {\n\tgo s.awaitShutdown()\n\tgo s.scheduleConnectionRecycling(connRecycle)\n\n\tif err := s.http.ListenAndServe(); err != nil {\n\t\tlog.Fatalln(\"Unable to start HTTP server: \", err)\n\t}\n}\n\n\/\/ Serves a 200 OK, unless shutdown has been requested.\n\/\/ Shutting down serves a 503 since that's how ELBs implement connection draining.\nfunc (s *server) serveHealth(w http.ResponseWriter, r *http.Request) {\n\tif s.isShuttingDown {\n\t\thttp.Error(w, \"Shutting Down\", 503)\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc getHealthCheckClient(host string, f clientFunc) (*influx.Client, error) {\n\tvar client *influx.Client\n\tvar exists bool\n\thealthCheckClientsLock.Lock()\n\tdefer healthCheckClientsLock.Unlock()\n\n\tif client, exists = healthCheckClients[host]; !exists {\n\t\tvar err error\n\n\t\tclientConfig := createInfluxDBClient(host, f)\n\t\tclient, err = influx.NewClient(&clientConfig)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"err=%q at=getHealthCheckClient host=%q\", err, host)\n\t\t\treturn nil, err\n\t\t}\n\n\t\thealthCheckClients[host] = client\n\t\treturn client, nil\n\t}\n\n\treturn client, nil\n}\n\nfunc checkRecentToken(client *influx.Client, token, host string, errors chan error) {\n\tfor _, qfmt := range influxDbSeriesCheckQueries {\n\t\tquery := fmt.Sprintf(qfmt, token)\n\t\tresults, err := client.Query(query, influx.Second)\n\t\tif err != nil || len(results) == 0 {\n\t\t\terrors <- fmt.Errorf(\"at=influxdb-health err=%q result_length=%d host=%q query=%q\", err, len(results), host, query)\n\t\t\tcontinue\n\t\t}\n\n\t\tt, ok := results[0].Points[0][0].(float64)\n\t\tif !ok {\n\t\t\terrors <- fmt.Errorf(\"at=influxdb-health err=\\\"time column was not a number\\\" host=%q query=%q\", host, query)\n\t\t\tcontinue\n\t\t}\n\n\t\tts := time.Unix(int64(t), int64(0)).UTC()\n\t\tnow := time.Now().UTC()\n\t\tif now.Sub(ts) > influxDbStaleTimeout {\n\t\t\terrors <- fmt.Errorf(\"at=influxdb-health err=\\\"stale data\\\" host=%q ts=%q now=%q query=%q\", host, ts, now, query)\n\t\t}\n\t}\n}\n\nfunc (s *server) checkRecentTokens() []error {\n\tvar errSlice []error\n\n\twg := new(sync.WaitGroup)\n\n\ts.recentTokensLock.RLock()\n\ttokenMap := make(map[string]string)\n\tfor host, token := range s.recentTokens {\n\t\ttokenMap[host] = token\n\t}\n\ts.recentTokensLock.RUnlock()\n\n\terrors := make(chan error, len(tokenMap)*len(influxDbSeriesCheckQueries))\n\n\tfor host, token := range tokenMap {\n\t\twg.Add(1)\n\t\tgo func(token, host string) {\n\t\t\tclient, err := getHealthCheckClient(host, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcheckRecentToken(client, token, host, errors)\n\t\t\twg.Done()\n\t\t}(token, host)\n\t}\n\n\twg.Wait()\n\tclose(errors)\n\n\tfor err := range errors {\n\t\terrSlice = append(errSlice, err)\n\t}\n\n\treturn errSlice\n}\n\nfunc (s *server) serveInfluxDBHealth(w http.ResponseWriter, r *http.Request) {\n\terrors := s.checkRecentTokens()\n\n\tif len(errors) > 0 {\n\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t\tfor _, err := range errors {\n\t\t\tw.Write([]byte(err.Error() + \"\\n\"))\n\t\t\tlog.Println(err)\n\t\t}\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc (s *server) awaitShutdown() {\n\t<-s.shutdownChan\n\tlog.Printf(\"Shutting down.\")\n\ts.isShuttingDown = true\n}\n<commit_msg>Cleanup getHealthCheckClient helper<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n\n\tauth \"github.com\/heroku\/lumbermill\/Godeps\/_workspace\/src\/github.com\/heroku\/authenticater\"\n\tinflux \"github.com\/heroku\/lumbermill\/Godeps\/_workspace\/src\/github.com\/influxdb\/influxdb-go\"\n)\n\nvar influxDbStaleTimeout = 24 * time.Minute \/\/ Would be nice to make this smaller, but it lags due to continuous queries.\nvar influxDbSeriesCheckQueries = []string{\n\t\"select * from MaxMean1mLoad.10m.dyno.dyno.load.%s limit 1\",\n\t\"select * from MaxMeanRssSwapMemory.10m.dyno.mem.%s limit 1\",\n}\n\nvar healthCheckClientsLock = new(sync.Mutex)\nvar healthCheckClients = make(map[string]*influx.Client)\n\ntype server struct {\n\tsync.WaitGroup\n\tconnectionCloser chan struct{}\n\thashRing         *hashRing\n\thttp             *http.Server\n\tshutdownChan     shutdownChan\n\tisShuttingDown   bool\n\tcredStore        map[string]string\n\n\t\/\/ scheduler based sampling lock for writing to recentTokens\n\ttokenLock        *int32\n\trecentTokensLock *sync.RWMutex\n\trecentTokens     map[string]string\n}\n\nfunc newServer(httpServer *http.Server, ath auth.Authenticater, hashRing *hashRing) *server {\n\ts := &server{\n\t\tconnectionCloser: make(chan struct{}),\n\t\tshutdownChan:     make(chan struct{}),\n\t\thttp:             httpServer,\n\t\thashRing:         hashRing,\n\t\tcredStore:        make(map[string]string),\n\t\ttokenLock:        new(int32),\n\t\trecentTokensLock: new(sync.RWMutex),\n\t\trecentTokens:     make(map[string]string),\n\t}\n\n\tmux := http.NewServeMux()\n\n\tmux.HandleFunc(\"\/drain\", auth.WrapAuth(ath,\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\ts.serveDrain(w, r)\n\t\t\ts.recycleConnection(w)\n\t\t}))\n\n\tmux.HandleFunc(\"\/health\", s.serveHealth)\n\tmux.HandleFunc(\"\/health\/influxdb\", s.serveInfluxDBHealth)\n\tmux.HandleFunc(\"\/target\/\", auth.WrapAuth(ath, s.serveTarget))\n\n\ts.http.Handler = mux\n\n\treturn s\n}\n\nfunc (s *server) Close() error {\n\ts.shutdownChan <- struct{}{}\n\treturn nil\n}\n\nfunc (s *server) scheduleConnectionRecycling(after time.Duration) {\n\tfor !s.isShuttingDown {\n\t\ttime.Sleep(after)\n\t\ts.connectionCloser <- struct{}{}\n\t}\n}\n\nfunc (s *server) recycleConnection(w http.ResponseWriter) {\n\tselect {\n\tcase <-s.connectionCloser:\n\t\tw.Header().Set(\"Connection\", \"close\")\n\tdefault:\n\t\tif s.isShuttingDown {\n\t\t\tw.Header().Set(\"Connection\", \"close\")\n\t\t}\n\t}\n}\n\nfunc (s *server) Run(connRecycle time.Duration) {\n\tgo s.awaitShutdown()\n\tgo s.scheduleConnectionRecycling(connRecycle)\n\n\tif err := s.http.ListenAndServe(); err != nil {\n\t\tlog.Fatalln(\"Unable to start HTTP server: \", err)\n\t}\n}\n\n\/\/ Serves a 200 OK, unless shutdown has been requested.\n\/\/ Shutting down serves a 503 since that's how ELBs implement connection draining.\nfunc (s *server) serveHealth(w http.ResponseWriter, r *http.Request) {\n\tif s.isShuttingDown {\n\t\thttp.Error(w, \"Shutting Down\", 503)\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc getHealthCheckClient(host string, f clientFunc) (*influx.Client, error) {\n\thealthCheckClientsLock.Lock()\n\tdefer healthCheckClientsLock.Unlock()\n\n\tclient, exists := healthCheckClients[host]\n\tif !exists {\n\t\tvar err error\n\t\tclientConfig := createInfluxDBClient(host, f)\n\t\tclient, err = influx.NewClient(&clientConfig)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"err=%q at=getHealthCheckClient host=%q\", err, host)\n\t\t\treturn nil, err\n\t\t}\n\n\t\thealthCheckClients[host] = client\n\t}\n\n\treturn client, nil\n}\n\nfunc checkRecentToken(client *influx.Client, token, host string, errors chan error) {\n\tfor _, qfmt := range influxDbSeriesCheckQueries {\n\t\tquery := fmt.Sprintf(qfmt, token)\n\t\tresults, err := client.Query(query, influx.Second)\n\t\tif err != nil || len(results) == 0 {\n\t\t\terrors <- fmt.Errorf(\"at=influxdb-health err=%q result_length=%d host=%q query=%q\", err, len(results), host, query)\n\t\t\tcontinue\n\t\t}\n\n\t\tt, ok := results[0].Points[0][0].(float64)\n\t\tif !ok {\n\t\t\terrors <- fmt.Errorf(\"at=influxdb-health err=\\\"time column was not a number\\\" host=%q query=%q\", host, query)\n\t\t\tcontinue\n\t\t}\n\n\t\tts := time.Unix(int64(t), int64(0)).UTC()\n\t\tnow := time.Now().UTC()\n\t\tif now.Sub(ts) > influxDbStaleTimeout {\n\t\t\terrors <- fmt.Errorf(\"at=influxdb-health err=\\\"stale data\\\" host=%q ts=%q now=%q query=%q\", host, ts, now, query)\n\t\t}\n\t}\n}\n\nfunc (s *server) checkRecentTokens() []error {\n\tvar errSlice []error\n\n\twg := new(sync.WaitGroup)\n\n\ts.recentTokensLock.RLock()\n\ttokenMap := make(map[string]string)\n\tfor host, token := range s.recentTokens {\n\t\ttokenMap[host] = token\n\t}\n\ts.recentTokensLock.RUnlock()\n\n\terrors := make(chan error, len(tokenMap)*len(influxDbSeriesCheckQueries))\n\n\tfor host, token := range tokenMap {\n\t\twg.Add(1)\n\t\tgo func(token, host string) {\n\t\t\tclient, err := getHealthCheckClient(host, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tcheckRecentToken(client, token, host, errors)\n\t\t\twg.Done()\n\t\t}(token, host)\n\t}\n\n\twg.Wait()\n\tclose(errors)\n\n\tfor err := range errors {\n\t\terrSlice = append(errSlice, err)\n\t}\n\n\treturn errSlice\n}\n\nfunc (s *server) serveInfluxDBHealth(w http.ResponseWriter, r *http.Request) {\n\terrors := s.checkRecentTokens()\n\n\tif len(errors) > 0 {\n\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t\tfor _, err := range errors {\n\t\t\tw.Write([]byte(err.Error() + \"\\n\"))\n\t\t\tlog.Println(err)\n\t\t}\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc (s *server) awaitShutdown() {\n\t<-s.shutdownChan\n\tlog.Printf(\"Shutting down.\")\n\ts.isShuttingDown = true\n}\n<|endoftext|>"}
{"text":"<commit_before>package oauth\n\nimport (\n    \"bufio\"\n    \/\/\"bytes\"\n    \"crypto\/tls\"\n    \"net\"\n    \"fmt\"\n    \"http\"\n    \"io\"\n    \"os\"\n    \"strings\"\n)\n\ntype badStringError struct {\n    what string\n    str string\n}\n\nfunc (e *badStringError) String() string {\n    return fmt.Sprintf(\"%s %q\", e.what, e.str)\n}\n\ntype readClose struct {\n    io.Reader\n    io.Closer\n}\n\ntype nopCloser struct {\n    io.Reader\n}\nfunc (nopCloser) Close() os.Error { return nil }\n\nfunc hasPort(s string) bool {\n    return strings.LastIndex(s, \":\") > strings.LastIndex(s, \"]\")\n}\n\nfunc send(req *http.Request) (resp *http.Response, err os.Error) {\n    \/\/dump, _ := http.DumpRequest(req, true)\n    \/\/fmt.Fprintf(os.Stderr, \"%s\", dump)\n    \/\/fmt.Fprintf(os.Stderr, \"\\n--- body:\\n%s\\n---\", bodyString(req.Body))\n    if req.URL.Scheme != \"http\" && req.URL.Scheme != \"https\" {\n        return nil, &badStringError{\"unsupported protocol scheme\", req.URL.Scheme}\n    }\n\n    addr := req.URL.Host\n    var conn net.Conn\n    switch(req.URL.Scheme) {\n    case \"http\":\n        if !hasPort(addr) {\n            addr += \":http\"\n        }\n\n        conn, err = net.Dial(\"tcp\", \"\", addr)\n    case \"https\":\n        if !hasPort(addr) {\n            addr += \":https\"\n        }\n\n        conn, err = tls.Dial(\"tcp\", \"\", addr)\n    }\n    if err != nil {\n        return nil, err\n    }\n\n    err = req.Write(conn)\n    if err != nil {\n        conn.Close()\n        return nil, err\n    }\n\n    reader := bufio.NewReader(conn)\n    resp, err = http.ReadResponse(reader, req.Method)\n    if err != nil {\n        conn.Close()\n        return nil, err\n    }\n\n    resp.Body = readClose{resp.Body, conn}\n\n    return\n}\n\nfunc post(url string, oauthHeaders map[string]string) (r *http.Response, err os.Error) {\n    var req http.Request\n    req.Method = \"POST\"\n    req.ProtoMajor = 1\n    req.ProtoMinor = 1\n    req.Close = true\n    req.Header = map[string]string{\n        \"Authorization\": \"OAuth \",\n    }\n    req.TransferEncoding = []string{\"chunked\"}\n\n    first := true\n    for k, v := range oauthHeaders {\n        if first {\n            first = false\n        } else {\n            req.Header[\"Authorization\"] += \",\\n    \"\n        }\n        req.Header[\"Authorization\"] += k+\"=\\\"\"+v+\"\\\"\"\n    }\n\n    req.URL, err = http.ParseURL(url)\n    if err != nil {\n        return nil, err\n    }\n\n    return send(&req)\n}\n\nfunc get(url string, oauthHeaders map[string]string) (r *http.Response, err os.Error) {\n    var req http.Request\n    req.Method = \"GET\"\n    req.ProtoMajor = 1\n    req.ProtoMinor = 1\n    req.Close = true\n    req.Header = map[string]string{\n        \"Authorization\": \"OAuth \",\n    }\n    req.TransferEncoding = []string{\"chunked\"}\n\n    first := true\n    for k, v := range oauthHeaders {\n        if first {\n            first = false\n        } else {\n            req.Header[\"Authorization\"] += \",\\n    \"\n        }\n        req.Header[\"Authorization\"] += k+\"=\\\"\"+v+\"\\\"\"\n    }\n\n    req.URL, err = http.ParseURL(url)\n    if err != nil {\n        return nil, err\n    }\n\n    return send(&req)\n}\n\n<commit_msg>Account for updates in networking code.<commit_after>package oauth\n\nimport (\n    \"bufio\"\n    \/\/\"bytes\"\n    \"crypto\/tls\"\n    \"net\"\n    \"fmt\"\n    \"http\"\n    \"io\"\n    \"os\"\n    \"strings\"\n)\n\ntype badStringError struct {\n    what string\n    str string\n}\n\nfunc (e *badStringError) String() string {\n    return fmt.Sprintf(\"%s %q\", e.what, e.str)\n}\n\ntype readClose struct {\n    io.Reader\n    io.Closer\n}\n\ntype nopCloser struct {\n    io.Reader\n}\nfunc (nopCloser) Close() os.Error { return nil }\n\nfunc hasPort(s string) bool {\n    return strings.LastIndex(s, \":\") > strings.LastIndex(s, \"]\")\n}\n\nfunc send(req *http.Request) (resp *http.Response, err os.Error) {\n    \/\/dump, _ := http.DumpRequest(req, true)\n    \/\/fmt.Fprintf(os.Stderr, \"%s\", dump)\n    \/\/fmt.Fprintf(os.Stderr, \"\\n--- body:\\n%s\\n---\", bodyString(req.Body))\n    if req.URL.Scheme != \"http\" && req.URL.Scheme != \"https\" {\n        return nil, &badStringError{\"unsupported protocol scheme\", req.URL.Scheme}\n    }\n\n    addr := req.URL.Host\n    var conn net.Conn\n    switch(req.URL.Scheme) {\n    case \"http\":\n        if !hasPort(addr) {\n            addr += \":http\"\n        }\n\n        conn, err = net.Dial(\"tcp\", addr)\n    case \"https\":\n        if !hasPort(addr) {\n            addr += \":https\"\n        }\n\n        conn, err = tls.Dial(\"tcp\", addr, nil)\n    }\n    if err != nil {\n        return nil, err\n    }\n\n    err = req.Write(conn)\n    if err != nil {\n        conn.Close()\n        return nil, err\n    }\n\n    reader := bufio.NewReader(conn)\n    resp, err = http.ReadResponse(reader, req.Method)\n    if err != nil {\n        conn.Close()\n        return nil, err\n    }\n\n    resp.Body = readClose{resp.Body, conn}\n\n    return\n}\n\nfunc post(url string, oauthHeaders map[string]string) (r *http.Response, err os.Error) {\n    var req http.Request\n    req.Method = \"POST\"\n    req.ProtoMajor = 1\n    req.ProtoMinor = 1\n    req.Close = true\n    req.Header = map[string][]string{\n        \"Authorization\": {\"OAuth \"},\n    }\n    req.TransferEncoding = []string{\"chunked\"}\n\n    first := true\n    for k, v := range oauthHeaders {\n        if first {\n            first = false\n        } else {\n            req.Header[\"Authorization\"][0] += \",\\n    \"\n        }\n        req.Header[\"Authorization\"][0] += k+\"=\\\"\"+v+\"\\\"\"\n    }\n\n    req.URL, err = http.ParseURL(url)\n    if err != nil {\n        return nil, err\n    }\n\n    return send(&req)\n}\n\nfunc get(url string, oauthHeaders map[string]string) (r *http.Response, err os.Error) {\n    var req http.Request\n    req.Method = \"GET\"\n    req.ProtoMajor = 1\n    req.ProtoMinor = 1\n    req.Close = true\n    req.Header = map[string][]string{\n        \"Authorization\": {\"OAuth \"},\n    }\n    req.TransferEncoding = []string{\"chunked\"}\n\n    first := true\n    for k, v := range oauthHeaders {\n        if first {\n            first = false\n        } else {\n            req.Header[\"Authorization\"][0] += \",\\n    \"\n        }\n        req.Header[\"Authorization\"][0] += k+\"=\\\"\"+v+\"\\\"\"\n    }\n\n    req.URL, err = http.ParseURL(url)\n    if err != nil {\n        return nil, err\n    }\n\n    return send(&req)\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package extend\nimport (\n\t\"reflect\"\n)\n\nconst initialSize = 4\n\n\/\/ Pusher must be passed a pointer to a slice. It returns\n\/\/ a function that pushes a new value onto the end of the\n\/\/ slice, reallocating the slice if necessary.\nfunc Pusher(ap interface{}) func(interface{}) {\n\tv := reflect.NewValue(ap).(*reflect.PtrValue).Elem().(*reflect.SliceValue)\n\tt := v.Type().(*reflect.SliceType)\n\treturn func(x interface{}) {\n\t\tlen, cap := v.Len(), v.Cap()\n\t\tif len < cap {\n\t\t\tv.SetLen(len+1)\n\t\t}else{\n\t\t\tif cap == 0 {\n\t\t\t\tcap = initialSize\n\t\t\t}else{\n\t\t\t\tcap *= 2\n\t\t\t}\n\t\t\tb := reflect.MakeSlice(t, len+1, cap)\n\t\t\treflect.ArrayCopy(b, v)\n\t\t\tv.SetValue(b)\n\t\t}\n\t\t\n\t\tv.Elem(len).SetValue(reflect.NewValue(x))\n\t}\n}\n<commit_msg>enabled unsafe hackery for 80% speed increase.<commit_after>package extend\nimport (\n\t\"reflect\"\n\t\"unsafe\"\n)\n\nconst initialSize = 4\n\ntype interfaceHeader struct {\n\tt uintptr\n\tdata uintptr\n}\n\n\/\/ Pusher must be passed a pointer to a slice. It returns\n\/\/ a function that pushes a new value onto the end of the\n\/\/ slice, reallocating the slice if necessary.\nfunc Pusher(ap interface{}) func(interface{}) {\n\tv := reflect.NewValue(ap).(*reflect.PtrValue).Elem().(*reflect.SliceValue)\n\th := (*reflect.SliceHeader)(unsafe.Pointer(v.Addr()))\n\tt := v.Type().(*reflect.SliceType)\n\tesize := t.Elem().Size()\n\t_, isInterface := t.Elem().(*reflect.InterfaceType)\n\tunsafeCopy := !isInterface && esize <= uintptr(unsafe.Sizeof(uintptr(0)))\n\tif !unsafeCopy {\n\t\treturn func(x interface{}) {\n\t\t\tlen, cap := h.Len, h.Cap\n\t\t\tif len < cap {\n\t\t\t\th.Len++\n\t\t\t}else{\n\t\t\t\tif cap == 0 {\n\t\t\t\t\tcap = initialSize\n\t\t\t\t}else{\n\t\t\t\t\tcap *= 2\n\t\t\t\t}\n\t\t\t\tb := reflect.MakeSlice(t, len+1, cap)\n\t\t\t\treflect.ArrayCopy(b, v)\n\t\t\t\tv.SetValue(b)\n\t\t\t}\n\t\t\tv.Elem(len).SetValue(reflect.NewValue(x))\n\t\t}\n\t}\n\t\/\/ Nasty unsafe hackery:\n\t\/\/\n\t\/\/ We know that the size of the type fits in a pointer,\n\t\/\/ so the value is held directly inside the interface value.\n\t\/\/ We copy each element to icopy, so that we can take\n\t\/\/ the address of it without triggering the allocator.\n\t\/\/ We set up e1 as a []byte alias to the data,\n\t\/\/ and do the actual copy by setting up e0 as a []byte\n\t\/\/ alias to the array element and invoking copy().\n\t\/\/ TODO: enable this code for type with size > sizeof(uintptr).\n\tvar e0 []byte\n\tvar e1 []byte\n\the0 := (*reflect.SliceHeader)(unsafe.Pointer(&e0))\n\the1 := (*reflect.SliceHeader)(unsafe.Pointer(&e1))\n\tvar icopy interface{}\n\the1.Data = uintptr(unsafe.Pointer(&icopy)) + uintptr(unsafe.Offsetof(interfaceHeader{}.data))\n\the1.Len = int(esize)\n\the1.Cap = int(esize)\n\n\treturn func(x interface{}) {\n\t\tlen, cap := h.Len, h.Cap\n\t\tif len < cap {\n\t\t\th.Len++\n\t\t}else{\n\t\t\tif cap == 0 {\n\t\t\t\tcap = initialSize\n\t\t\t}else{\n\t\t\t\tcap *= 2\n\t\t\t}\n\t\t\tb := reflect.MakeSlice(t, len+1, cap)\n\t\t\treflect.ArrayCopy(b, v)\n\t\t\tv.SetValue(b)\n\t\t}\n\t\ticopy = x\n\t\the0.Data = h.Data + esize * uintptr(len)\n\t\the0.Len = int(esize)\n\t\the0.Cap = int(esize)\n\t\tcopy(e0, e1)\n\t\te0 = nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2015 ENDOH takanao.\n<https:\/\/github.com\/MiCHiLU\/go-lru-cache-stats>\n\nCopyright 2013 Google Inc.\n<https:\/\/github.com\/golang\/groupcache>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage lru\n\nimport (\n\t\"bytes\"\n\t\"net\/http\"\n\t\"sync\"\n)\n\nvar httpPoolMade bool\n\ntype httpGetter struct {\n\ttransport func(Context) http.RoundTripper\n\tbaseURL   string\n}\n\nvar bufferPool = sync.Pool{\n\tNew: func() interface{} { return new(bytes.Buffer) },\n}\n<commit_msg>remove vars<commit_after>\/*\nCopyright 2015 ENDOH takanao.\n<https:\/\/github.com\/MiCHiLU\/go-lru-cache-stats>\n\nCopyright 2013 Google Inc.\n<https:\/\/github.com\/golang\/groupcache>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage lru\n\nimport (\n\t\"net\/http\"\n)\n\ntype httpGetter struct {\n\ttransport func(Context) http.RoundTripper\n\tbaseURL   string\n}\n<|endoftext|>"}
{"text":"<commit_before>package lily\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/cookiejar\"\n\tnetUrl \"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc HTTPStatusCodeIsOk(statusCode int) bool {\n\treturn statusCode > 199 && statusCode < 300\n}\n\nfunc HTTPSetContentTypeJSON(w http.ResponseWriter) {\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n}\n\nfunc HTTPSetContentTypeHTML(w http.ResponseWriter) {\n\tw.Header().Set(\"Content-Type\", \"text\/html; charset=UTF-8\")\n}\n\nfunc HTTPRespondStr(w http.ResponseWriter, code int, body string) {\n\tif len(body) == 0 {\n\t\tpanic(\"body must be not empty\")\n\t}\n\tw.WriteHeader(code)\n\tfmt.Fprint(w, body)\n}\n\nfunc HTTPRespondJSONObj(w http.ResponseWriter, code int, obj interface{}) {\n\tHTTPSetContentTypeJSON(w)\n\tw.WriteHeader(code)\n\tErrPanic(json.NewEncoder(w).Encode(obj))\n}\n\nfunc HTTPRespondJSONParseError(w http.ResponseWriter) {\n\tHTTPRespond400(w, \"bad_json\", \"Fail to parse JSON\")\n}\n\nfunc HTTPSendRequest(withJar bool, method, url string, urlParams map[string]string,\n\tdata []byte, timeout time.Duration, headers ...string) (*http.Response, error) {\n\tvar err error\n\tvar req *http.Request\n\tvar jar http.CookieJar\n\n\tif data != nil {\n\t\treq, err = http.NewRequest(method, url, bytes.NewBuffer(data))\n\t\tErrPanic(err)\n\t} else {\n\t\treq, err = http.NewRequest(method, url, nil)\n\t\tErrPanic(err)\n\t}\n\n\tif urlParams != nil {\n\t\tq := netUrl.Values{}\n\t\tfor k, v := range urlParams {\n\t\t\tq.Add(k, v)\n\t\t}\n\t\treq.URL.RawQuery = q.Encode()\n\t}\n\n\tfor i := 0; (i + 1) < len(headers); i += 2 {\n\t\treq.Header.Set(headers[i], headers[i+1])\n\t}\n\n\tif withJar {\n\t\tjar, err = cookiejar.New(nil)\n\t\tErrPanic(err)\n\t}\n\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t\tJar:     jar,\n\t}\n\n\treturn client.Do(req)\n}\n\nfunc HTTPSendRequestReceiveBytes(withJar, errSCode bool, method, url string, urlParams map[string]string,\n\tdata []byte, timeout time.Duration, headers ...string) (int, []byte, error) {\n\tvar res []byte\n\n\tresp, err := HTTPSendRequest(withJar, method, url, urlParams, data, timeout, headers...)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tres, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\tif !HTTPStatusCodeIsOk(resp.StatusCode) {\n\t\tif errSCode {\n\t\t\treturn resp.StatusCode, res, errors.New(fmt.Sprintf(\"bad_http_status_code - %d\\nbody: %s\", resp.StatusCode, string(res)))\n\t\t}\n\t\treturn resp.StatusCode, res, nil\n\t}\n\n\treturn resp.StatusCode, res, nil\n}\n\nfunc HTTPSendRequestReceiveString(withJar, errSCode bool, method, url string, urlParams map[string]string,\n\tdata []byte, timeout time.Duration, headers ...string) (int, string, error) {\n\tsCode, resBytes, err := HTTPSendRequestReceiveBytes(withJar, errSCode, method, url, urlParams, data, timeout, headers...)\n\n\treturn sCode, string(resBytes), err\n}\n\nfunc HTTPSendRequestReceiveJSONObj(withJar, errSCode bool, method, url string, urlParams map[string]string,\n\tdata []byte, rObj interface{}, timeout time.Duration, headers ...string) (int, []byte, error) {\n\tsCode, rBytes, err := HTTPSendRequestReceiveBytes(\n\t\twithJar, errSCode, method, url, urlParams, data, timeout, headers...)\n\tif err != nil || !HTTPStatusCodeIsOk(sCode) {\n\t\treturn sCode, rBytes, err\n\t}\n\n\terr = json.Unmarshal(rBytes, rObj)\n\tif err != nil {\n\t\treturn sCode, rBytes, errors.New(fmt.Sprintf(\"fail_to_parse_json - %s\\nbody: %s\", err.Error(), string(rBytes)))\n\t}\n\n\treturn sCode, rBytes, nil\n}\n\nfunc HTTPSendJSONObjRequest(withJar bool, method, url string, urlParams map[string]string,\n\tsObj interface{}, timeout time.Duration, headers ...string) (*http.Response, error) {\n\tsBytes, err := json.Marshal(sObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn HTTPSendRequest(withJar, method, url, urlParams, sBytes, timeout, headers...)\n}\n\nfunc HTTPSendJSONObjRequestReceiveBytes(withJar, errSCode bool, method, url string, urlParams map[string]string,\n\tsObj interface{}, timeout time.Duration, headers ...string) (int, []byte, error) {\n\tsBytes, err := json.Marshal(sObj)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\treturn HTTPSendRequestReceiveBytes(withJar, errSCode, method, url, urlParams, sBytes, timeout, headers...)\n}\n\nfunc HTTPSendJSONObjRequestReceiveString(withJar, errSCode bool, method, url string, urlParams map[string]string,\n\tsObj interface{}, timeout time.Duration, headers ...string) (int, string, error) {\n\tsBytes, err := json.Marshal(sObj)\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\n\treturn HTTPSendRequestReceiveString(withJar, errSCode, method, url, urlParams, sBytes, timeout, headers...)\n}\n\nfunc HTTPSendJSONObjRequestReceiveJSONObj(withJar, errSCode bool, method, url string, urlParams map[string]string,\n\tsObj interface{}, rObj interface{}, timeout time.Duration, headers ...string) (int, []byte, error) {\n\tsBytes, err := json.Marshal(sObj)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\treturn HTTPSendRequestReceiveJSONObj(withJar, errSCode, method, url, urlParams, sBytes, rObj, timeout, headers...)\n}\n\nfunc HTTPRetrieveRequestHostURL(r *http.Request) string {\n\tscheme := r.Header.Get(\"X-Forwarded-Proto\")\n\tif scheme == \"\" {\n\t\tif r.TLS == nil {\n\t\t\tscheme = \"http\"\n\t\t} else {\n\t\t\tscheme = \"https\"\n\t\t}\n\t}\n\treturn scheme + \":\/\/\" + r.Host\n}\n\nfunc HTTPRetrieveRemoteIP(r *http.Request) (result string) {\n\tresult = \"\"\n\tif parts := strings.Split(r.RemoteAddr, \":\"); len(parts) == 2 {\n\t\tresult = parts[0]\n\t}\n\t\/\/ If we have a forwarded-for header, take the address from there\n\tif xff := strings.Trim(r.Header.Get(\"X-Forwarded-For\"), \",\"); len(xff) > 0 {\n\t\taddrs := strings.Split(xff, \",\")\n\t\tlastFwd := addrs[len(addrs)-1]\n\t\tif ip := net.ParseIP(lastFwd); ip != nil {\n\t\t\tresult = ip.String()\n\t\t}\n\t\t\/\/ parse X-Real-Ip header\n\t} else if xri := r.Header.Get(\"X-Real-Ip\"); len(xri) > 0 {\n\t\tif ip := net.ParseIP(xri); ip != nil {\n\t\t\tresult = ip.String()\n\t\t}\n\t}\n\treturn\n}\n\nfunc HTTPUploadFileFromRequestForm(r *http.Request, key, dirPath, dir string, filename string) (string, error) {\n\tvar err error\n\n\tfinalDirPath := filepath.Join(dirPath, dir)\n\n\terr = os.MkdirAll(finalDirPath, os.ModePerm)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsrcFile, header, err := r.FormFile(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer srcFile.Close()\n\n\tfileExt := filepath.Ext(header.Filename)\n\tif fileExt == \"\" {\n\t\treturn \"\", errors.New(\"bad_extension\")\n\t}\n\n\tdstFile, err := TempFile(finalDirPath, filename+\"_*\"+fileExt)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer dstFile.Close()\n\n\t_, err = io.Copy(dstFile, srcFile)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = os.Chmod(dstFile.Name(), 0644)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnewName, err := filepath.Rel(dirPath, dstFile.Name())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn newName, nil\n}\n\nfunc HTTPRespondError(w http.ResponseWriter, code int, err string, detail string, extras ...interface{}) {\n\tobj := map[string]interface{}{}\n\tobj[\"error\"] = err\n\tobj[\"error_dsc\"] = detail\n\tfor i := 0; (i + 1) < len(extras); i += 2 {\n\t\tobj[extras[i].(string)] = extras[i+1]\n\t}\n\tHTTPRespondJSONObj(w, code, obj)\n}\n\nfunc HTTPRespond400(w http.ResponseWriter, err, detail string, extras ...interface{}) {\n\tHTTPRespondError(w, 400, err, detail, extras...)\n}\n\nfunc HTTPRespond401(w http.ResponseWriter, detail string) {\n\tHTTPRespondError(w, 401, \"unauthorized\", detail)\n}\n\nfunc HTTPRespond403(w http.ResponseWriter, detail string) {\n\tHTTPRespondError(w, 403, \"permission_denied\", detail)\n}\n\nfunc HTTPRespond404(w http.ResponseWriter, detail string) {\n\tHTTPRespondError(w, 404, \"not_found\", detail)\n}\n<commit_msg>upgrade http<commit_after>package lily\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/cookiejar\"\n\tnetUrl \"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc HTTPMwCORSAllowAll(h http.Handler, maxAge string) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Vary\", \"Origin\")\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tif r.Method == \"OPTIONS\" {\n\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, OPTIONS\")\n\t\t\t\/\/ headers\n\t\t\trequestHeaders := strings.Split(r.Header.Get(\"Access-Control-Request-Headers\"), \",\")\n\t\t\tvar allowedHeaders []string\n\t\t\tfor _, v := range requestHeaders {\n\t\t\t\tallowedHeaders = append(allowedHeaders, http.CanonicalHeaderKey(strings.TrimSpace(v)))\n\t\t\t}\n\t\t\tif len(allowedHeaders) > 0 {\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", strings.Join(allowedHeaders, \",\"))\n\t\t\t}\n\t\t\tw.Header().Set(\"Access-Control-Max-Age\", maxAge)\n\t\t} else {\n\t\t\th.ServeHTTP(w, r)\n\t\t}\n\t})\n}\n\nfunc HTTPStatusCodeIsOk(statusCode int) bool {\n\treturn statusCode > 199 && statusCode < 300\n}\n\nfunc HTTPSetContentTypeJSON(w http.ResponseWriter) {\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n}\n\nfunc HTTPSetContentTypeHTML(w http.ResponseWriter) {\n\tw.Header().Set(\"Content-Type\", \"text\/html; charset=UTF-8\")\n}\n\nfunc HTTPRespondStr(w http.ResponseWriter, code int, body string) {\n\tif len(body) == 0 {\n\t\tpanic(\"body must be not empty\")\n\t}\n\tw.WriteHeader(code)\n\tfmt.Fprint(w, body)\n}\n\nfunc HTTPRespondJSONObj(w http.ResponseWriter, code int, obj interface{}) {\n\tHTTPSetContentTypeJSON(w)\n\tw.WriteHeader(code)\n\tErrPanic(json.NewEncoder(w).Encode(obj))\n}\n\nfunc HTTPRespondJSONParseError(w http.ResponseWriter) {\n\tHTTPRespond400(w, \"bad_json\", \"Fail to parse JSON\")\n}\n\nfunc HTTPSendRequest(withJar bool, method, url string, urlParams map[string]string,\n\tdata []byte, timeout time.Duration, headers ...string) (*http.Response, error) {\n\tvar err error\n\tvar req *http.Request\n\tvar jar http.CookieJar\n\n\tif data != nil {\n\t\treq, err = http.NewRequest(method, url, bytes.NewBuffer(data))\n\t\tErrPanic(err)\n\t} else {\n\t\treq, err = http.NewRequest(method, url, nil)\n\t\tErrPanic(err)\n\t}\n\n\tif urlParams != nil {\n\t\tq := netUrl.Values{}\n\t\tfor k, v := range urlParams {\n\t\t\tq.Add(k, v)\n\t\t}\n\t\treq.URL.RawQuery = q.Encode()\n\t}\n\n\tfor i := 0; (i + 1) < len(headers); i += 2 {\n\t\treq.Header.Set(headers[i], headers[i+1])\n\t}\n\n\tif withJar {\n\t\tjar, err = cookiejar.New(nil)\n\t\tErrPanic(err)\n\t}\n\n\tclient := http.Client{\n\t\tTimeout: timeout,\n\t\tJar:     jar,\n\t}\n\n\treturn client.Do(req)\n}\n\nfunc HTTPSendRequestReceiveBytes(withJar, errSCode bool, method, url string, urlParams map[string]string,\n\tdata []byte, timeout time.Duration, headers ...string) (int, []byte, error) {\n\tvar res []byte\n\n\tresp, err := HTTPSendRequest(withJar, method, url, urlParams, data, timeout, headers...)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tres, err = ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\tif !HTTPStatusCodeIsOk(resp.StatusCode) {\n\t\tif errSCode {\n\t\t\treturn resp.StatusCode, res, errors.New(fmt.Sprintf(\"bad_http_status_code - %d\\nbody: %s\", resp.StatusCode, string(res)))\n\t\t}\n\t\treturn resp.StatusCode, res, nil\n\t}\n\n\treturn resp.StatusCode, res, nil\n}\n\nfunc HTTPSendRequestReceiveString(withJar, errSCode bool, method, url string, urlParams map[string]string,\n\tdata []byte, timeout time.Duration, headers ...string) (int, string, error) {\n\tsCode, resBytes, err := HTTPSendRequestReceiveBytes(withJar, errSCode, method, url, urlParams, data, timeout, headers...)\n\n\treturn sCode, string(resBytes), err\n}\n\nfunc HTTPSendRequestReceiveJSONObj(withJar, errSCode bool, method, url string, urlParams map[string]string,\n\tdata []byte, rObj interface{}, timeout time.Duration, headers ...string) (int, []byte, error) {\n\tsCode, rBytes, err := HTTPSendRequestReceiveBytes(\n\t\twithJar, errSCode, method, url, urlParams, data, timeout, headers...)\n\tif err != nil || !HTTPStatusCodeIsOk(sCode) {\n\t\treturn sCode, rBytes, err\n\t}\n\n\terr = json.Unmarshal(rBytes, rObj)\n\tif err != nil {\n\t\treturn sCode, rBytes, errors.New(fmt.Sprintf(\"fail_to_parse_json - %s\\nbody: %s\", err.Error(), string(rBytes)))\n\t}\n\n\treturn sCode, rBytes, nil\n}\n\nfunc HTTPSendJSONObjRequest(withJar bool, method, url string, urlParams map[string]string,\n\tsObj interface{}, timeout time.Duration, headers ...string) (*http.Response, error) {\n\tsBytes, err := json.Marshal(sObj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn HTTPSendRequest(withJar, method, url, urlParams, sBytes, timeout, headers...)\n}\n\nfunc HTTPSendJSONObjRequestReceiveBytes(withJar, errSCode bool, method, url string, urlParams map[string]string,\n\tsObj interface{}, timeout time.Duration, headers ...string) (int, []byte, error) {\n\tsBytes, err := json.Marshal(sObj)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\treturn HTTPSendRequestReceiveBytes(withJar, errSCode, method, url, urlParams, sBytes, timeout, headers...)\n}\n\nfunc HTTPSendJSONObjRequestReceiveString(withJar, errSCode bool, method, url string, urlParams map[string]string,\n\tsObj interface{}, timeout time.Duration, headers ...string) (int, string, error) {\n\tsBytes, err := json.Marshal(sObj)\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\n\treturn HTTPSendRequestReceiveString(withJar, errSCode, method, url, urlParams, sBytes, timeout, headers...)\n}\n\nfunc HTTPSendJSONObjRequestReceiveJSONObj(withJar, errSCode bool, method, url string, urlParams map[string]string,\n\tsObj interface{}, rObj interface{}, timeout time.Duration, headers ...string) (int, []byte, error) {\n\tsBytes, err := json.Marshal(sObj)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\treturn HTTPSendRequestReceiveJSONObj(withJar, errSCode, method, url, urlParams, sBytes, rObj, timeout, headers...)\n}\n\nfunc HTTPRetrieveRequestHostURL(r *http.Request) string {\n\tscheme := r.Header.Get(\"X-Forwarded-Proto\")\n\tif scheme == \"\" {\n\t\tif r.TLS == nil {\n\t\t\tscheme = \"http\"\n\t\t} else {\n\t\t\tscheme = \"https\"\n\t\t}\n\t}\n\treturn scheme + \":\/\/\" + r.Host\n}\n\nfunc HTTPRetrieveRemoteIP(r *http.Request) (result string) {\n\tresult = \"\"\n\tif parts := strings.Split(r.RemoteAddr, \":\"); len(parts) == 2 {\n\t\tresult = parts[0]\n\t}\n\t\/\/ If we have a forwarded-for header, take the address from there\n\tif xff := strings.Trim(r.Header.Get(\"X-Forwarded-For\"), \",\"); len(xff) > 0 {\n\t\taddrs := strings.Split(xff, \",\")\n\t\tlastFwd := addrs[len(addrs)-1]\n\t\tif ip := net.ParseIP(lastFwd); ip != nil {\n\t\t\tresult = ip.String()\n\t\t}\n\t\t\/\/ parse X-Real-Ip header\n\t} else if xri := r.Header.Get(\"X-Real-Ip\"); len(xri) > 0 {\n\t\tif ip := net.ParseIP(xri); ip != nil {\n\t\t\tresult = ip.String()\n\t\t}\n\t}\n\treturn\n}\n\nfunc HTTPUploadFileFromRequestForm(r *http.Request, key, dirPath, dir string, filename string) (string, error) {\n\tvar err error\n\n\tfinalDirPath := filepath.Join(dirPath, dir)\n\n\terr = os.MkdirAll(finalDirPath, os.ModePerm)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsrcFile, header, err := r.FormFile(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer srcFile.Close()\n\n\tfileExt := filepath.Ext(header.Filename)\n\tif fileExt == \"\" {\n\t\treturn \"\", errors.New(\"bad_extension\")\n\t}\n\n\tdstFile, err := TempFile(finalDirPath, filename+\"_*\"+fileExt)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer dstFile.Close()\n\n\t_, err = io.Copy(dstFile, srcFile)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = os.Chmod(dstFile.Name(), 0644)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tnewName, err := filepath.Rel(dirPath, dstFile.Name())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn newName, nil\n}\n\nfunc HTTPRespondError(w http.ResponseWriter, code int, err string, detail string, extras ...interface{}) {\n\tobj := map[string]interface{}{}\n\tobj[\"error\"] = err\n\tobj[\"error_dsc\"] = detail\n\tfor i := 0; (i + 1) < len(extras); i += 2 {\n\t\tobj[extras[i].(string)] = extras[i+1]\n\t}\n\tHTTPRespondJSONObj(w, code, obj)\n}\n\nfunc HTTPRespond400(w http.ResponseWriter, err, detail string, extras ...interface{}) {\n\tHTTPRespondError(w, 400, err, detail, extras...)\n}\n\nfunc HTTPRespond401(w http.ResponseWriter, detail string) {\n\tHTTPRespondError(w, 401, \"unauthorized\", detail)\n}\n\nfunc HTTPRespond403(w http.ResponseWriter, detail string) {\n\tHTTPRespondError(w, 403, \"permission_denied\", detail)\n}\n\nfunc HTTPRespond404(w http.ResponseWriter, detail string) {\n\tHTTPRespondError(w, 404, \"not_found\", detail)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2015 ENDOH takanao.\n<https:\/\/github.com\/MiCHiLU\/go-lru-cache-stats>\n\nCopyright 2013 Google Inc.\n<https:\/\/github.com\/golang\/groupcache>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage lru\n\nimport (\n\t\"bytes\"\n\t\"net\/http\"\n\t\"sync\"\n)\n\nconst defaultBasePath = \"\/_groupcache\/\"\n\nconst defaultReplicas = 50\n\n\/\/ HTTPPoolOptions are the configurations of a HTTPPool.\ntype HTTPPoolOptions struct {\n\t\/\/ BasePath specifies the HTTP path that will serve groupcache requests.\n\t\/\/ If blank, it defaults to \"\/_groupcache\/\".\n\tBasePath string\n\n\t\/\/ Replicas specifies the number of key replicas on the consistent hash.\n\t\/\/ If blank, it defaults to 50.\n\tReplicas int\n}\n\nvar httpPoolMade bool\n\ntype httpGetter struct {\n\ttransport func(Context) http.RoundTripper\n\tbaseURL   string\n}\n\nvar bufferPool = sync.Pool{\n\tNew: func() interface{} { return new(bytes.Buffer) },\n}\n<commit_msg>remove consts<commit_after>\/*\nCopyright 2015 ENDOH takanao.\n<https:\/\/github.com\/MiCHiLU\/go-lru-cache-stats>\n\nCopyright 2013 Google Inc.\n<https:\/\/github.com\/golang\/groupcache>\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage lru\n\nimport (\n\t\"bytes\"\n\t\"net\/http\"\n\t\"sync\"\n)\n\n\/\/ HTTPPoolOptions are the configurations of a HTTPPool.\ntype HTTPPoolOptions struct {\n\t\/\/ BasePath specifies the HTTP path that will serve groupcache requests.\n\t\/\/ If blank, it defaults to \"\/_groupcache\/\".\n\tBasePath string\n\n\t\/\/ Replicas specifies the number of key replicas on the consistent hash.\n\t\/\/ If blank, it defaults to 50.\n\tReplicas int\n}\n\nvar httpPoolMade bool\n\ntype httpGetter struct {\n\ttransport func(Context) http.RoundTripper\n\tbaseURL   string\n}\n\nvar bufferPool = sync.Pool{\n\tNew: func() interface{} { return new(bytes.Buffer) },\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2013-2014, Jeremy Bingham (<jbingham@gmail.com>)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage search\n\nimport (\n\t\"fmt\"\n\t\"github.com\/ctdk\/goas\/v2\/logger\"\n\t\"github.com\/ctdk\/goiardi\/indexer\"\n\t\/\/\"github.com\/ctdk\/goiardi\/util\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype PostgresSearch struct {\n}\n\ntype PgQuery struct {\n\tqueryChain Queryable\n\tpaths []string\n\tqueryStrs []string\n\targuments []string\n}\n\ntype gClause struct {\n\tclause string\n\top Op\n}\n\nfunc (p *PostgresSearch) Search(idx string, q string, rows int, sortOrder string, start int, partialData map[string]interface{}) ([]map[string]interface{}, error) {\n\t\/\/ keep up with the ersatz solr.\n\tqq := &Tokenizer{Buffer: q}\n\tqq.Init()\n\tif err := qq.Parse(); err != nil {\n\t\treturn nil, err\n\t}\n\tqq.Execute()\n\tqchain := qq.Evaluate()\n\n\tpgQ := &PgQuery{ queryChain: qchain }\n\n\tlogger.Debugf(\"what on earth is the chain? %q\", qchain)\n\terr := pgQ.execute()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ dummy\n\tdres := make([]map[string]interface{}, 0)\n\treturn dres, nil\n}\n\nfunc (p *PostgresSearch) GetEndpoints() []string {\n\t\/\/ TODO: deal with possible errors\n\tendpoints, err := indexer.Endpoints()\n\treturn endpoints\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn endpoints\n}\n\nfunc (pq *PgQuery) execute(startTableID ...*int) error {\n\tp := pq.queryChain\n\tcurOp := OpNotAnOp\n\topMap := map[Op]string{\n\t\tOpNotAnOp: \"(not an op)\",\n\t\tOpUnaryNot: \"not\",\n\t\tOpUnaryReq: \"req\",\n\t\tOpUnaryPro: \"pro\",\n\t\tOpBinAnd: \"and\",\n\t\tOpBinOr: \"or\",\n\t\tOpBoost: \"boost\",\n\t\tOpFuzzy: \"fuzzy\",\n\t\tOpStartGroup: \"start group\",\n\t\tOpEndGroup: \"end group\",\n\t\tOpStartIncl: \"start inc\",\n\t\tOpEndIncl: \"end inc\",\n\t\tOpStartExcl: \"start exc\",\n\t\tOpEndExcl: \"end exc\",\n\t}\n\tvar t *int\n\tif len(startTableID) == 0 {\n\t\tz := 0\n\t\tt = &z\n\t} else {\n\t\tt = startTableID[0]\n\t}\n\tfor p != nil {\n\t\tswitch c := p.(type) {\n\t\tcase *BasicQuery:\n\t\t\tpq.paths = append(pq.paths, string(c.field))\n\t\t\tlogger.Debugf(\"basic t%d: field: %s op: %s term: %+v complete %v\", *t, c.field, opMap[c.op], c.term, c.complete)\n\t\t\targs, qstr := buildBasicQuery(c.field, c.term, t, curOp)\n\t\t\tlogger.Debugf(\"qstr: %s\", qstr)\n\t\t\tpq.arguments = append(pq.arguments, args...)\n\t\t\tpq.queryStrs = append(pq.queryStrs, qstr)\n\t\t\t*t++\n\t\tcase *GroupedQuery:\n\t\t\tpq.paths = append(pq.paths, string(c.field))\n\t\t\tlogger.Debugf(\"grouped t%d: field: %s op: %s terms: %+v complete %v\", *t, c.field, opMap[c.op], c.terms, c.complete)\n\t\t\targs, qstr := buildGroupedQuery(c.field, c.terms, t, curOp)\n\t\t\tlogger.Debugf(\"qstr: %s\", qstr)\n\t\t\tpq.arguments = append(pq.arguments, args...)\n\t\t\tpq.queryStrs = append(pq.queryStrs, qstr)\n\t\t\t*t++\n\t\tcase *RangeQuery:\n\t\t\tpq.paths = append(pq.paths, string(c.field))\n\t\t\tlogger.Debugf(\"range t%d: field %s op %s start %s end %s inclusive %v complete %v\", *t, c.field, opMap[c.op], c.start, c.end, c.inclusive, c.complete)\n\t\t\targs, qstr := buildRangeQuery(c.field, c.start, c.end, c.inclusive, t, curOp)\n\t\t\tlogger.Debugf(\"qstr: %s\", qstr)\n\t\t\tpq.arguments = append(pq.arguments, args...)\n\t\t\tpq.queryStrs = append(pq.queryStrs, qstr)\n\t\t\t*t++\n\t\tcase *SubQuery:\n\t\t\tlogger.Debugf(\"STARTING SUBQUERY: op %s complete %v\", opMap[c.op], c.complete)\n\t\t\tnewq, nend, nerr := extractSubQuery(c)\n\t\t\tif nerr != nil {\n\t\t\t\treturn nerr\n\t\t\t}\n\t\t\tp = nend\n\t\t\tlogger.Debugf(\"OP NOW: %s\", opMap[p.Op()])\n\t\t\tnp := &PgQuery{ queryChain: newq }\n\t\t\terr := np.execute(t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlogger.Debugf(\"subquery paths: %v\", np.paths)\n\t\t\tlogger.Debugf(\"subquery args: %v\", np.arguments)\n\t\t\tlogger.Debugf(\"subquery qstrs: %v\", np.queryStrs)\n\t\t\tpq.paths = append(pq.paths, np.paths...)\n\t\t\tpq.arguments = append(pq.arguments, np.arguments...)\n\t\t\tpq.queryStrs = append(pq.queryStrs, fmt.Sprintf(\"%s(%s)\", binOp(curOp), strings.Join(np.queryStrs, \" \")))\n\t\t\tlogger.Debugf(\"ENDING SUBQUERY\")\n\t\tdefault:\n\t\t\terr := fmt.Errorf(\"Unknown type %T for query\", c)\n\t\t\treturn err\n\t\t}\n\t\tcurOp = p.Op()\n\t\tp = p.Next()\n\t}\n\tlogger.Debugf(\"paths: %v\", pq.paths)\n\tlogger.Debugf(\"arguments: %v\", pq.arguments)\n\tlogger.Debugf(\"query strings: %v\", pq.queryStrs)\n\tlogger.Debugf(\"number of tables: %d\", *t)\n\treturn nil\n}\n\nfunc buildBasicQuery(field Field, term QueryTerm, tNum *int, op Op) ([]string, string) {\n\topStr := binOp(op)\n\tcop := matchOp(term.mod, term)\n\n\tvar q string\n\targs := []string{ string(field) }\n\tif term.term == \"*\" {\n\t\tq = fmt.Sprintf(\"%s(f%d.path ~ _ARG_)\", opStr, *tNum)\n\t} else {\n\t\tq = fmt.Sprintf(\"%s(f%d.path ~ _ARG_ AND f%d.value %s _ARG_)\", opStr, *tNum, *tNum, cop)\n\t\targs = append(args, string(term.term))\n\t}\n\n\treturn args, q\n}\n\nfunc buildGroupedQuery(field Field, terms []QueryTerm, tNum *int, op Op) ([]string, string) {\n\topStr := binOp(op)\n\n\tvar q string\n\targs := []string{ string(field) }\n\tvar grouped []*gClause\n\n\tfor _, v := range terms {\n\t\tcop := matchOp(op, v)\n\t\t\n\t\tclause := fmt.Sprintf(\"f%d.value %s _ARG_\", *tNum, cop)\n\t\tg := &gClause{ clause, v.mod }\n\t\tgrouped = append(grouped, g)\n\t\targs = append(args, string(v.term))\n\t}\n\tvar clauseArr []string\n\tfor i, g := range grouped {\n\t\tvar j string\n\t\tif i != 0 {\n\t\t\tif g.op == OpUnaryPro || g.op == OpUnaryReq || g.op == OpUnaryNot {\n\t\t\t\tj = \" AND \"\n\t\t\t} else {\n\t\t\t\tj = \" OR \"\n\t\t\t}\n\t\t}\n\t\tclauseArr = append(clauseArr, fmt.Sprintf(\"%s%s\", j, g.clause))\n\t}\n\tclauses := strings.Join(clauseArr, \" \")\n\tq = fmt.Sprintf(\"%s(f%d.path ~ _ARG_ AND (%s))\", opStr, *tNum, clauses)\n\treturn args, q\n}\n\nfunc buildRangeQuery(field Field, start RangeTerm, end RangeTerm, inclusive bool, tNum *int, op Op) ([]string, string) {\n\tif start > end {\n\t\tstart, end = end, start\n\t}\n\n\tvar q string\n\targs := []string{ string(field) }\n\n\topStr := binOp(op)\n\tvar equals string\n\tif inclusive {\n\t\tequals = \"=\"\n\t}\n\tvar ranges []string\n\tif string(start) != \"*\" {\n\t\ts := fmt.Sprintf(\"f%d.value >%s _ARG_\", *tNum, equals)\n\t\tranges = append(ranges, s)\n\t\targs = append(args, string(start))\n\t}\n\tif string(end) != \"*\" {\n\t\te := fmt.Sprintf(\"f%d.value <%s _ARG_\", *tNum, equals)\n\t\tranges = append(ranges, e)\n\t\targs = append(args, string(end))\n\t}\n\tvar rangeStr string\n\tif len(ranges) != 0 {\n\t\trangeStr = fmt.Sprintf(\" AND (%s)\", strings.Join(ranges, \" AND \"))\n\t}\n\tq = fmt.Sprintf(\"%s(f%d.path ~ _ARG_%s)\", opStr, *tNum, rangeStr)\n\treturn args, q\n}\n\nfunc matchOp(op Op, term QueryTerm) string {\n\tr := regexp.MustCompile(`\\*|\\?`)\n\tvar cop string\n\tif r.MatchString(string(term.term)) {\n\t\tif term.mod == OpUnaryNot || term.mod == OpUnaryPro {\n\t\t\tcop = \"NOT LIKE\"\n\t\t} else {\n\t\t\tcop = \"LIKE\"\n\t\t}\n\t} else {\n\t\tif term.mod == OpUnaryNot || term.mod == OpUnaryPro {\n\t\t\tcop = \"<>\"\n\t\t} else {\n\t\t\tcop = \"=\"\n\t\t}\n\t}\n\treturn cop\n}\n\nfunc binOp(op Op) string {\n\tvar opStr string\n\tif op != OpNotAnOp {\n\t\tif op == OpBinAnd {\n\t\t\topStr = \" AND \"\n\t\t} else {\n\t\t\topStr = \" OR \"\n\t\t}\n\t}\n\treturn opStr\n}\n<commit_msg>queries build now<commit_after>\/*\n * Copyright (c) 2013-2014, Jeremy Bingham (<jbingham@gmail.com>)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage search\n\nimport (\n\t\"fmt\"\n\t\"github.com\/ctdk\/goas\/v2\/logger\"\n\t\"github.com\/ctdk\/goiardi\/indexer\"\n\t\/\/\"github.com\/ctdk\/goiardi\/util\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype PostgresSearch struct {\n}\n\ntype PgQuery struct {\n\tidx string\n\tqueryChain Queryable\n\tpaths []string\n\tqueryStrs []string\n\targuments []string\n}\n\ntype gClause struct {\n\tclause string\n\top Op\n}\n\nfunc (p *PostgresSearch) Search(idx string, q string, rows int, sortOrder string, start int, partialData map[string]interface{}) ([]map[string]interface{}, error) {\n\t\/\/ keep up with the ersatz solr.\n\tqq := &Tokenizer{Buffer: q}\n\tqq.Init()\n\tif err := qq.Parse(); err != nil {\n\t\treturn nil, err\n\t}\n\tqq.Execute()\n\tqchain := qq.Evaluate()\n\n\tpgQ := &PgQuery{ idx: idx, queryChain: qchain }\n\n\tlogger.Debugf(\"what on earth is the chain? %q\", qchain)\n\terr := pgQ.execute()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ dummy\n\tdres := make([]map[string]interface{}, 0)\n\treturn dres, nil\n}\n\nfunc (p *PostgresSearch) GetEndpoints() []string {\n\t\/\/ TODO: deal with possible errors\n\tendpoints, err := indexer.Endpoints()\n\treturn endpoints\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn endpoints\n}\n\nfunc (pq *PgQuery) execute(startTableID ...*int) error {\n\tp := pq.queryChain\n\tcurOp := OpNotAnOp\n\topMap := map[Op]string{\n\t\tOpNotAnOp: \"(not an op)\",\n\t\tOpUnaryNot: \"not\",\n\t\tOpUnaryReq: \"req\",\n\t\tOpUnaryPro: \"pro\",\n\t\tOpBinAnd: \"and\",\n\t\tOpBinOr: \"or\",\n\t\tOpBoost: \"boost\",\n\t\tOpFuzzy: \"fuzzy\",\n\t\tOpStartGroup: \"start group\",\n\t\tOpEndGroup: \"end group\",\n\t\tOpStartIncl: \"start inc\",\n\t\tOpEndIncl: \"end inc\",\n\t\tOpStartExcl: \"start exc\",\n\t\tOpEndExcl: \"end exc\",\n\t}\n\tvar t *int\n\tif len(startTableID) == 0 {\n\t\tz := 0\n\t\tt = &z\n\t} else {\n\t\tt = startTableID[0]\n\t}\n\tfor p != nil {\n\t\tswitch c := p.(type) {\n\t\tcase *BasicQuery:\n\t\t\tpq.paths = append(pq.paths, string(c.field))\n\t\t\tlogger.Debugf(\"basic t%d: field: %s op: %s term: %+v complete %v\", *t, c.field, opMap[c.op], c.term, c.complete)\n\t\t\targs, qstr := buildBasicQuery(c.field, c.term, t, curOp)\n\t\t\tlogger.Debugf(\"qstr: %s\", qstr)\n\t\t\tpq.arguments = append(pq.arguments, args...)\n\t\t\tpq.queryStrs = append(pq.queryStrs, qstr)\n\t\t\t*t++\n\t\tcase *GroupedQuery:\n\t\t\tpq.paths = append(pq.paths, string(c.field))\n\t\t\tlogger.Debugf(\"grouped t%d: field: %s op: %s terms: %+v complete %v\", *t, c.field, opMap[c.op], c.terms, c.complete)\n\t\t\targs, qstr := buildGroupedQuery(c.field, c.terms, t, curOp)\n\t\t\tlogger.Debugf(\"qstr: %s\", qstr)\n\t\t\tpq.arguments = append(pq.arguments, args...)\n\t\t\tpq.queryStrs = append(pq.queryStrs, qstr)\n\t\t\t*t++\n\t\tcase *RangeQuery:\n\t\t\tpq.paths = append(pq.paths, string(c.field))\n\t\t\tlogger.Debugf(\"range t%d: field %s op %s start %s end %s inclusive %v complete %v\", *t, c.field, opMap[c.op], c.start, c.end, c.inclusive, c.complete)\n\t\t\targs, qstr := buildRangeQuery(c.field, c.start, c.end, c.inclusive, t, curOp)\n\t\t\tlogger.Debugf(\"qstr: %s\", qstr)\n\t\t\tpq.arguments = append(pq.arguments, args...)\n\t\t\tpq.queryStrs = append(pq.queryStrs, qstr)\n\t\t\t*t++\n\t\tcase *SubQuery:\n\t\t\tlogger.Debugf(\"STARTING SUBQUERY: op %s complete %v\", opMap[c.op], c.complete)\n\t\t\tnewq, nend, nerr := extractSubQuery(c)\n\t\t\tif nerr != nil {\n\t\t\t\treturn nerr\n\t\t\t}\n\t\t\tp = nend\n\t\t\tlogger.Debugf(\"OP NOW: %s\", opMap[p.Op()])\n\t\t\tnp := &PgQuery{ queryChain: newq }\n\t\t\terr := np.execute(t)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlogger.Debugf(\"subquery paths: %v\", np.paths)\n\t\t\tlogger.Debugf(\"subquery args: %v\", np.arguments)\n\t\t\tlogger.Debugf(\"subquery qstrs: %v\", np.queryStrs)\n\t\t\tpq.paths = append(pq.paths, np.paths...)\n\t\t\tpq.arguments = append(pq.arguments, np.arguments...)\n\t\t\tpq.queryStrs = append(pq.queryStrs, fmt.Sprintf(\"%s(%s)\", binOp(curOp), strings.Join(np.queryStrs, \" \")))\n\t\t\tlogger.Debugf(\"ENDING SUBQUERY\")\n\t\tdefault:\n\t\t\terr := fmt.Errorf(\"Unknown type %T for query\", c)\n\t\t\treturn err\n\t\t}\n\t\tcurOp = p.Op()\n\t\tp = p.Next()\n\t}\n\tlogger.Debugf(\"paths: %v\", pq.paths)\n\tlogger.Debugf(\"arguments: %v\", pq.arguments)\n\tlogger.Debugf(\"query strings: %v\", pq.queryStrs)\n\tlogger.Debugf(\"number of tables: %d\", *t)\n\tfullQ, allArgs := craftFullQuery(1, pq.idx, pq.paths, pq.arguments, pq.queryStrs, t)\n\tlogger.Debugf(\"full query: %s\", fullQ)\n\tlogger.Debugf(\"all %d args: %v\", len(allArgs), allArgs)\n\treturn nil\n}\n\nfunc buildBasicQuery(field Field, term QueryTerm, tNum *int, op Op) ([]string, string) {\n\topStr := binOp(op)\n\tcop := matchOp(term.mod, term)\n\n\tvar q string\n\targs := []string{ string(field) }\n\tif term.term == \"*\" {\n\t\tq = fmt.Sprintf(\"%s(f%d.path ~ _ARG_)\", opStr, *tNum)\n\t} else {\n\t\tq = fmt.Sprintf(\"%s(f%d.path ~ _ARG_ AND f%d.value %s _ARG_)\", opStr, *tNum, *tNum, cop)\n\t\targs = append(args, string(term.term))\n\t}\n\n\treturn args, q\n}\n\nfunc buildGroupedQuery(field Field, terms []QueryTerm, tNum *int, op Op) ([]string, string) {\n\topStr := binOp(op)\n\n\tvar q string\n\targs := []string{ string(field) }\n\tvar grouped []*gClause\n\n\tfor _, v := range terms {\n\t\tcop := matchOp(op, v)\n\t\t\n\t\tclause := fmt.Sprintf(\"f%d.value %s _ARG_\", *tNum, cop)\n\t\tg := &gClause{ clause, v.mod }\n\t\tgrouped = append(grouped, g)\n\t\targs = append(args, string(v.term))\n\t}\n\tvar clauseArr []string\n\tfor i, g := range grouped {\n\t\tvar j string\n\t\tif i != 0 {\n\t\t\tif g.op == OpUnaryPro || g.op == OpUnaryReq || g.op == OpUnaryNot {\n\t\t\t\tj = \" AND \"\n\t\t\t} else {\n\t\t\t\tj = \" OR \"\n\t\t\t}\n\t\t}\n\t\tclauseArr = append(clauseArr, fmt.Sprintf(\"%s%s\", j, g.clause))\n\t}\n\tclauses := strings.Join(clauseArr, \" \")\n\tq = fmt.Sprintf(\"%s(f%d.path ~ _ARG_ AND (%s))\", opStr, *tNum, clauses)\n\treturn args, q\n}\n\nfunc buildRangeQuery(field Field, start RangeTerm, end RangeTerm, inclusive bool, tNum *int, op Op) ([]string, string) {\n\tif start > end {\n\t\tstart, end = end, start\n\t}\n\n\tvar q string\n\targs := []string{ string(field) }\n\n\topStr := binOp(op)\n\tvar equals string\n\tif inclusive {\n\t\tequals = \"=\"\n\t}\n\tvar ranges []string\n\tif string(start) != \"*\" {\n\t\ts := fmt.Sprintf(\"f%d.value >%s _ARG_\", *tNum, equals)\n\t\tranges = append(ranges, s)\n\t\targs = append(args, string(start))\n\t}\n\tif string(end) != \"*\" {\n\t\te := fmt.Sprintf(\"f%d.value <%s _ARG_\", *tNum, equals)\n\t\tranges = append(ranges, e)\n\t\targs = append(args, string(end))\n\t}\n\tvar rangeStr string\n\tif len(ranges) != 0 {\n\t\trangeStr = fmt.Sprintf(\" AND (%s)\", strings.Join(ranges, \" AND \"))\n\t}\n\tq = fmt.Sprintf(\"%s(f%d.path ~ _ARG_%s)\", opStr, *tNum, rangeStr)\n\treturn args, q\n}\n\nfunc matchOp(op Op, term QueryTerm) string {\n\tr := regexp.MustCompile(`\\*|\\?`)\n\tvar cop string\n\tif r.MatchString(string(term.term)) {\n\t\tif term.mod == OpUnaryNot || term.mod == OpUnaryPro {\n\t\t\tcop = \"NOT LIKE\"\n\t\t} else {\n\t\t\tcop = \"LIKE\"\n\t\t}\n\t} else {\n\t\tif term.mod == OpUnaryNot || term.mod == OpUnaryPro {\n\t\t\tcop = \"<>\"\n\t\t} else {\n\t\t\tcop = \"=\"\n\t\t}\n\t}\n\treturn cop\n}\n\nfunc binOp(op Op) string {\n\tvar opStr string\n\tif op != OpNotAnOp {\n\t\tif op == OpBinAnd {\n\t\t\topStr = \" AND \"\n\t\t} else {\n\t\t\topStr = \" OR \"\n\t\t}\n\t}\n\treturn opStr\n}\n\nfunc craftFullQuery(orgID int, idx string, paths []string, arguments []string, queryStrs []string, tNum *int) (string, []interface{}) {\n\t\/\/ TODO: FIX\n\tallArgs := make([]interface{}, 0, len(paths) + len(arguments) + 2)\n\tallArgs = append(allArgs, orgID)\n\tallArgs = append(allArgs, idx)\n\tfor _, v := range paths {\n\t\tallArgs = append(allArgs, v)\n\t}\n\tfor _, v := range arguments {\n\t\tallArgs = append(allArgs, v)\n\t}\n\n\tpcount := 3\n\tparams := make([]string, 0, len(paths))\n\tfor range paths {\n\t\tparams = append(params, fmt.Sprintf(\"$%d\", pcount))\n\t\tpcount++\n\t}\n\twithStatement := fmt.Sprintf(\"WITH found_items AS (SELECT item_name, path, value FROM goiardi.search_items si JOIN goiardi.search_collections sc ON si.search_collection_id = sc.id WHERE si.organization_id = $1 AND sc.name = $2 AND path ? ARRAY[%s]::lquery[]), items AS (SELECT DISTINCT item_name FROM found_items)\", strings.Join(params, \", \"))\n\tvar selectStmt string\n\tif *tNum == 1 {\n\t\tselectStmt = fmt.Sprintf(\"SELECT DISTINCT item_name FROM found_items f0 WHERE %s\", queryStrs[0])\n\t} else {\n\t\tjoins := make([]string, 0, *tNum)\n\t\tfor i := 0; i < *tNum; i++ {\n\t\t\tj := fmt.Sprintf(\"INNER JOIN found_items AS f%d ON i.item_name = f%d.item_name\", i, i)\n\t\t\tjoins = append(joins, j)\n\t\t}\n\t\tselectStmt = fmt.Sprintf(\"SELECT i.item_name FROM items i %s WHERE %s\", strings.Join(joins, \" \"), strings.Join(queryStrs, \" \"))\n\t}\n\tfullQuery := strings.Join([]string{ withStatement, selectStmt }, \" \")\n\tre := regexp.MustCompile(\"_ARG_\")\n\trfunc := func([]byte) []byte {\n\t\tr := []byte(fmt.Sprintf(\"$%d\", pcount))\n\t\tpcount++\n\t\treturn r\n\t}\n\tfullQuery = string(re.ReplaceAllFunc([]byte(fullQuery), rfunc))\n\n\treturn fullQuery, allArgs\n}\n<|endoftext|>"}
{"text":"<commit_before>package icsi\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst notaryDomain = \"notary.icsi.berkeley.edu\"\n\ntype Status int\n\nconst (\n\tUnknown Status = iota\n\tSeen\n\tValidated\n)\n\nvar (\n\tipSeen      = net.IP{127, 0, 0, 1}\n\tipValidated = net.IP{127, 0, 0, 2}\n\n\terrInvalidResponse = errors.New(\"icsi: invalid response\")\n\terrUnknownVersion  = errors.New(\"icsi: unknown version\")\n\terrMultipleRecords = errors.New(\"icsi: multiple records\")\n)\n\nfunc dnsname(sha []byte) string {\n\treturn fmt.Sprintf(\"%x.%s\", sha, notaryDomain)\n}\n\nfunc isnxdomain(err error) bool {\n\tif err, ok := err.(*net.DNSError); ok {\n\t\treturn err.Err == \"no such host\"\n\t}\n\treturn false\n}\n\nfunc QueryStatus(sha []byte) (Status, error) {\n\tips, err := net.LookupIP(dnsname(sha))\n\tif err != nil {\n\t\tif isnxdomain(err) {\n\t\t\treturn Unknown, nil\n\t\t}\n\t\treturn Unknown, err\n\t}\n\n\tif len(ips) != 1 {\n\t\treturn Unknown, errMultipleRecords\n\t}\n\tif bytes.Equal(ips[0], ipSeen) {\n\t\treturn Seen, nil\n\t}\n\tif bytes.Equal(ips[0], ipValidated) {\n\t\treturn Validated, nil\n\t}\n\n\treturn Unknown, nil\n}\n\ntype Response struct {\n\tVersion   int\n\tFirstSeen time.Time\n\tLastSeen  time.Time\n\tTimesSeen int\n\tValidated bool\n}\n\nfunc parseDate(s string) (time.Time, error) {\n\ti, err := strconv.ParseInt(s, 10, 32)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\treturn time.Unix(0, 0).UTC().AddDate(0, 0, int(i)), nil\n}\n\nfunc parseResponse(txt string) (*Response, error) {\n\tvar r Response\n\n\ttok := strings.Split(txt, \" \")\n\tfor _, t := range tok {\n\t\tpair := strings.Split(t, \"=\")\n\t\tif len(pair) != 2 {\n\t\t\treturn nil, errInvalidResponse\n\t\t}\n\t\tswitch pair[0] {\n\t\tcase \"version\":\n\t\t\ti, err := strconv.ParseInt(pair[1], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errInvalidResponse\n\t\t\t}\n\t\t\tr.Version = int(i)\n\t\tcase \"first_seen\":\n\t\t\tt, err := parseDate(pair[1])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errInvalidResponse\n\t\t\t}\n\t\t\tr.FirstSeen = t\n\t\tcase \"last_seen\":\n\t\t\tt, err := parseDate(pair[1])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errInvalidResponse\n\t\t\t}\n\t\t\tr.LastSeen = t\n\t\tcase \"times_seen\":\n\t\t\ti, err := strconv.ParseInt(pair[1], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errInvalidResponse\n\t\t\t}\n\t\t\tr.TimesSeen = int(i)\n\t\tcase \"validated\":\n\t\t\ti, err := strconv.ParseInt(pair[1], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errInvalidResponse\n\t\t\t}\n\t\t\tr.Validated = i == 1\n\t\t}\n\t}\n\n\tif r.Version != 1 {\n\t\treturn nil, errUnknownVersion\n\t}\n\n\treturn &r, nil\n\n}\n\nfunc Query(sha []byte) (*Response, error) {\n\ttxts, err := net.LookupTXT(dnsname(sha))\n\tif err != nil {\n\t\tif isnxdomain(err) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif len(txts) != 1 {\n\t\treturn nil, errMultipleRecords\n\t}\n\n\treturn parseResponse(txts[0])\n\n}\n<commit_msg>add Hash<commit_after>package icsi\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha1\"\n\t\"crypto\/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst notaryDomain = \"notary.icsi.berkeley.edu\"\n\ntype Status int\n\nconst (\n\tUnknown Status = iota\n\tSeen\n\tValidated\n)\n\nvar (\n\tipSeen      = net.IP{127, 0, 0, 1}\n\tipValidated = net.IP{127, 0, 0, 2}\n\n\terrInvalidResponse = errors.New(\"icsi: invalid response\")\n\terrUnknownVersion  = errors.New(\"icsi: unknown version\")\n\terrMultipleRecords = errors.New(\"icsi: multiple records\")\n)\n\nfunc dnsname(sha []byte) string {\n\treturn fmt.Sprintf(\"%x.%s\", sha, notaryDomain)\n}\n\nfunc isnxdomain(err error) bool {\n\tif err, ok := err.(*net.DNSError); ok {\n\t\treturn err.Err == \"no such host\"\n\t}\n\treturn false\n}\n\nfunc QueryStatus(sha []byte) (Status, error) {\n\tips, err := net.LookupIP(dnsname(sha))\n\tif err != nil {\n\t\tif isnxdomain(err) {\n\t\t\treturn Unknown, nil\n\t\t}\n\t\treturn Unknown, err\n\t}\n\n\tif len(ips) != 1 {\n\t\treturn Unknown, errMultipleRecords\n\t}\n\tif bytes.Equal(ips[0], ipSeen) {\n\t\treturn Seen, nil\n\t}\n\tif bytes.Equal(ips[0], ipValidated) {\n\t\treturn Validated, nil\n\t}\n\n\treturn Unknown, nil\n}\n\ntype Response struct {\n\tVersion   int\n\tFirstSeen time.Time\n\tLastSeen  time.Time\n\tTimesSeen int\n\tValidated bool\n}\n\nfunc parseDate(s string) (time.Time, error) {\n\ti, err := strconv.ParseInt(s, 10, 32)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\treturn time.Unix(0, 0).UTC().AddDate(0, 0, int(i)), nil\n}\n\nfunc parseResponse(txt string) (*Response, error) {\n\tvar r Response\n\n\ttok := strings.Split(txt, \" \")\n\tfor _, t := range tok {\n\t\tpair := strings.Split(t, \"=\")\n\t\tif len(pair) != 2 {\n\t\t\treturn nil, errInvalidResponse\n\t\t}\n\t\tswitch pair[0] {\n\t\tcase \"version\":\n\t\t\ti, err := strconv.ParseInt(pair[1], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errInvalidResponse\n\t\t\t}\n\t\t\tr.Version = int(i)\n\t\tcase \"first_seen\":\n\t\t\tt, err := parseDate(pair[1])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errInvalidResponse\n\t\t\t}\n\t\t\tr.FirstSeen = t\n\t\tcase \"last_seen\":\n\t\t\tt, err := parseDate(pair[1])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errInvalidResponse\n\t\t\t}\n\t\t\tr.LastSeen = t\n\t\tcase \"times_seen\":\n\t\t\ti, err := strconv.ParseInt(pair[1], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errInvalidResponse\n\t\t\t}\n\t\t\tr.TimesSeen = int(i)\n\t\tcase \"validated\":\n\t\t\ti, err := strconv.ParseInt(pair[1], 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errInvalidResponse\n\t\t\t}\n\t\t\tr.Validated = i == 1\n\t\t}\n\t}\n\n\tif r.Version != 1 {\n\t\treturn nil, errUnknownVersion\n\t}\n\n\treturn &r, nil\n\n}\n\nfunc Query(sha []byte) (*Response, error) {\n\ttxts, err := net.LookupTXT(dnsname(sha))\n\tif err != nil {\n\t\tif isnxdomain(err) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif len(txts) != 1 {\n\t\treturn nil, errMultipleRecords\n\t}\n\n\treturn parseResponse(txts[0])\n\n}\n\nfunc Hash(cert *x509.Certificate) []byte {\n\th := sha1.New()\n\th.Write(cert.Raw)\n\treturn h.Sum(nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package raft\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"hash\"\n\t\"hash\/crc64\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\ttestPath      = \"permTest\"\n\tsnapPath      = \"snapshots\"\n\tmetaFilePath  = \"meta.json\"\n\tstateFilePath = \"state.bin\"\n\ttmpSuffix     = \".tmp\"\n)\n\n\/\/ FileSnapshotStore implements the SnapshotStore interface and allows\n\/\/ snapshots to be made on the local disk.\ntype FileSnapshotStore struct {\n\tpath   string\n\tretain int\n\tlogger *log.Logger\n}\n\ntype snapMetaSlice []*fileSnapshotMeta\n\n\/\/ FileSnapshotSink implements SnapshotSink with a file.\ntype FileSnapshotSink struct {\n\tstore  *FileSnapshotStore\n\tlogger *log.Logger\n\tdir    string\n\tmeta   fileSnapshotMeta\n\n\tstateFile *os.File\n\tstateHash hash.Hash64\n\tbuffered  *bufio.Writer\n\n\tclosed bool\n}\n\n\/\/ fileSnapshotMeta is stored on disk. We also put a CRC\n\/\/ on disk so that we can verify the snapshot\ntype fileSnapshotMeta struct {\n\tSnapshotMeta\n\tCRC []byte\n}\n\n\/\/ bufferedFile is returned when we open a snapshot. This way\n\/\/ reads are buffered and the file still gets closed.\ntype bufferedFile struct {\n\tbh *bufio.Reader\n\tfh *os.File\n}\n\nfunc (b *bufferedFile) Read(p []byte) (n int, err error) {\n\treturn b.bh.Read(p)\n}\n\nfunc (b *bufferedFile) Close() error {\n\treturn b.fh.Close()\n}\n\n\/\/ NewFileSnapshotStore creates a new FileSnapshotStore based\n\/\/ on a base directory. The `retain` parameter controls how many\n\/\/ snapshots are retained. Must be at least 1.\nfunc NewFileSnapshotStore(base string, retain int, logOutput io.Writer) (*FileSnapshotStore, error) {\n\tif retain < 1 {\n\t\treturn nil, fmt.Errorf(\"must retain at least one snapshot\")\n\t}\n\tif logOutput == nil {\n\t\tlogOutput = os.Stderr\n\t}\n\n\t\/\/ Ensure our path exists\n\tpath := filepath.Join(base, snapPath)\n\tif err := os.Mkdir(path, 0755); err != nil && !os.IsExist(err) {\n\t\treturn nil, fmt.Errorf(\"snapshot path not accessible: %v\", err)\n\t}\n\n\t\/\/ Setup the store\n\tstore := &FileSnapshotStore{\n\t\tpath:   path,\n\t\tretain: retain,\n\t\tlogger: log.New(logOutput, \"\", log.LstdFlags),\n\t}\n\n\t\/\/ Do a permissions test\n\tif err := store.testPermissions(); err != nil {\n\t\treturn nil, fmt.Errorf(\"permissions test failed: %v\", err)\n\t}\n\treturn store, nil\n}\n\n\/\/ testPermissions tries to touch a file in our path to see if it works\nfunc (f *FileSnapshotStore) testPermissions() error {\n\tpath := filepath.Join(f.path, testPath)\n\tfh, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfh.Close()\n\tos.Remove(path)\n\treturn nil\n}\n\n\/\/ snapshotName generate s name for the snapshot\nfunc snapshotName(term, index uint64) string {\n\tnow := time.Now()\n\tmsec := now.UnixNano() \/ int64(time.Millisecond)\n\treturn fmt.Sprintf(\"%d-%d-%d\", term, index, msec)\n}\n\n\/\/ Create is used to start a new snapshot\nfunc (f *FileSnapshotStore) Create(index, term uint64, peers []byte) (SnapshotSink, error) {\n\t\/\/ Create a new path\n\tname := snapshotName(term, index)\n\tpath := filepath.Join(f.path, name+tmpSuffix)\n\tf.logger.Printf(\"[INFO] snapshot: Creating new snapshot at %s\", path)\n\n\t\/\/ Make the directory\n\tif err := os.Mkdir(path, 0755); err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to make snapshot directory: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Create the sink\n\tsink := &FileSnapshotSink{\n\t\tstore:  f,\n\t\tlogger: f.logger,\n\t\tdir:    path,\n\t\tmeta: fileSnapshotMeta{\n\t\t\tSnapshotMeta: SnapshotMeta{\n\t\t\t\tID:    name,\n\t\t\t\tIndex: index,\n\t\t\t\tTerm:  term,\n\t\t\t\tPeers: peers,\n\t\t\t},\n\t\t\tCRC: nil,\n\t\t},\n\t}\n\n\t\/\/ Write out the meta data\n\tif err := sink.writeMeta(); err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to write metadata: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Open the state file\n\tstatePath := filepath.Join(path, stateFilePath)\n\tfh, err := os.Create(statePath)\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to create state file: %v\", err)\n\t\treturn nil, err\n\t}\n\tsink.stateFile = fh\n\n\t\/\/ Create a CRC64 hash\n\tsink.stateHash = crc64.New(crc64.MakeTable(crc64.ECMA))\n\n\t\/\/ Wrap both the hash and file in a MultiWriter with buffering\n\tmulti := io.MultiWriter(sink.stateFile, sink.stateHash)\n\tsink.buffered = bufio.NewWriter(multi)\n\n\t\/\/ Done\n\treturn sink, nil\n}\n\n\/\/ List returns available snapshots in the store.\nfunc (f *FileSnapshotStore) List() ([]*SnapshotMeta, error) {\n\t\/\/ Get the eligible snapshots\n\tsnapshots, err := f.getSnapshots()\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to get snapshots: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tvar snapMeta []*SnapshotMeta\n\tfor _, meta := range snapshots {\n\t\tsnapMeta = append(snapMeta, &meta.SnapshotMeta)\n\t\tif len(snapMeta) == f.retain {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn snapMeta, nil\n}\n\n\/\/ getSnapshots returns all the known snapshots\nfunc (f *FileSnapshotStore) getSnapshots() ([]*fileSnapshotMeta, error) {\n\t\/\/ Get the eligible snapshots\n\tsnapshots, err := ioutil.ReadDir(f.path)\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to scan snapshot dir: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Populate the metadata\n\tvar snapMeta []*fileSnapshotMeta\n\tfor _, snap := range snapshots {\n\t\t\/\/ Ignore any files\n\t\tif !snap.IsDir() {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Ignore any temporary snapshots\n\t\tdirName := snap.Name()\n\t\tif strings.HasSuffix(dirName, tmpSuffix) {\n\t\t\tf.logger.Printf(\"[WARN] snapshot: Found temporary snapshot: %v\", dirName)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Try to read the meta data\n\t\tmeta, err := f.readMeta(dirName)\n\t\tif err != nil {\n\t\t\tf.logger.Printf(\"[WARN] snapshot: Failed to read metadata for %v: %v\", dirName, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Append, but only return up to the retain count\n\t\tsnapMeta = append(snapMeta, meta)\n\t}\n\n\t\/\/ Sort the snapshot, reverse so we get new -> old\n\tsort.Sort(sort.Reverse(snapMetaSlice(snapMeta)))\n\n\treturn snapMeta, nil\n}\n\n\/\/ readMeta is used to read the meta data for a given named backup\nfunc (f *FileSnapshotStore) readMeta(name string) (*fileSnapshotMeta, error) {\n\t\/\/ Open the meta file\n\tmetaPath := filepath.Join(f.path, name, metaFilePath)\n\tfh, err := os.Open(metaPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fh.Close()\n\n\t\/\/ Buffer the file IO\n\tbuffered := bufio.NewReader(fh)\n\n\t\/\/ Read in the JSON\n\tmeta := &fileSnapshotMeta{}\n\tdec := json.NewDecoder(buffered)\n\tif err := dec.Decode(meta); err != nil {\n\t\treturn nil, err\n\t}\n\treturn meta, nil\n}\n\n\/\/ Open takes a snapshot ID and returns a ReadCloser for that snapshot.\nfunc (f *FileSnapshotStore) Open(id string) (*SnapshotMeta, io.ReadCloser, error) {\n\t\/\/ Get the metadata\n\tmeta, err := f.readMeta(id)\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to get meta data to open snapshot: %v\", err)\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Open the state file\n\tstatePath := filepath.Join(f.path, id, stateFilePath)\n\tfh, err := os.Open(statePath)\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to open state file: %v\", err)\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Create a CRC64 hash\n\tstateHash := crc64.New(crc64.MakeTable(crc64.ECMA))\n\n\t\/\/ Compute the hash\n\t_, err = io.Copy(stateHash, fh)\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to read state file: %v\", err)\n\t\tfh.Close()\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Verify the hash\n\tcomputed := stateHash.Sum(nil)\n\tif bytes.Compare(meta.CRC, computed) != 0 {\n\t\tf.logger.Printf(\"[ERR] snapshot: CRC checksum failed (stored: %v computed: %v)\",\n\t\t\tmeta.CRC, computed)\n\t\tfh.Close()\n\t\treturn nil, nil, fmt.Errorf(\"CRC mismatch\")\n\t}\n\n\t\/\/ Seek to the start\n\tif _, err := fh.Seek(0, 0); err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: State file seek failed: %v\", err)\n\t\tfh.Close()\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Return a buffered file\n\tbuffered := &bufferedFile{\n\t\tbh: bufio.NewReader(fh),\n\t\tfh: fh,\n\t}\n\n\treturn &meta.SnapshotMeta, buffered, nil\n}\n\n\/\/ ReapSnapshots reaps any snapshots beyond the retain count.\nfunc (f *FileSnapshotStore) ReapSnapshots() error {\n\tsnapshots, err := f.getSnapshots()\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to get snapshots: %v\", err)\n\t\treturn err\n\t}\n\n\tfor i := f.retain; i < len(snapshots); i++ {\n\t\tpath := filepath.Join(f.path, snapshots[i].ID)\n\t\tf.logger.Printf(\"[INFO] snapshot: reaping snapshot %v\", path)\n\t\tif err := os.RemoveAll(path); err != nil {\n\t\t\tf.logger.Printf(\"[ERR] snapshot: Failed to reap snapshot %v: %v\", path, err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ ID returns the ID of the snapshot, can be used with Open()\n\/\/ after the snapshot is finalized.\nfunc (s *FileSnapshotSink) ID() string {\n\treturn s.meta.ID\n}\n\n\/\/ Write is used to append to the state file. We write to the\n\/\/ buffered IO object to reduce the amount of context switches\nfunc (s *FileSnapshotSink) Write(b []byte) (int, error) {\n\treturn s.buffered.Write(b)\n}\n\n\/\/ Close is used to indicate a successful end\nfunc (s *FileSnapshotSink) Close() error {\n\t\/\/ Make sure close is idempotent\n\tif s.closed {\n\t\treturn nil\n\t}\n\ts.closed = true\n\n\t\/\/ Close the open handles\n\tif err := s.finalize(); err != nil {\n\t\ts.logger.Printf(\"[ERR] snapshot: Failed to finalize snapshot: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Write out the meta data\n\tif err := s.writeMeta(); err != nil {\n\t\ts.logger.Printf(\"[ERR] snapshot: Failed to write metadata: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Move the directory into place\n\tnewPath := strings.TrimSuffix(s.dir, tmpSuffix)\n\tif err := os.Rename(s.dir, newPath); err != nil {\n\t\ts.logger.Printf(\"[ERR] snapshot: Failed to move snapshot into place: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Reap any old snapshots\n\ts.store.ReapSnapshots()\n\treturn nil\n}\n\n\/\/ Cancel is used to indicate an unsuccessful end\nfunc (s *FileSnapshotSink) Cancel() error {\n\t\/\/ Make sure close is idempotent\n\tif s.closed {\n\t\treturn nil\n\t}\n\ts.closed = true\n\n\t\/\/ Close the open handles\n\tif err := s.finalize(); err != nil {\n\t\ts.logger.Printf(\"[ERR] snapshot: Failed to finalize snapshot: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Attempt to remove all artifacts\n\treturn os.RemoveAll(s.dir)\n}\n\n\/\/ finalize is used to close all of our resources\nfunc (s *FileSnapshotSink) finalize() error {\n\t\/\/ Flush any remaining data\n\tif err := s.buffered.Flush(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Get the file size\n\tstat, statErr := s.stateFile.Stat()\n\n\t\/\/ Close the file\n\tif err := s.stateFile.Close(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Set the file size, check after we close\n\tif statErr != nil {\n\t\treturn statErr\n\t}\n\ts.meta.Size = stat.Size()\n\n\t\/\/ Set the CRC\n\ts.meta.CRC = s.stateHash.Sum(nil)\n\treturn nil\n}\n\n\/\/ writeMeta is used to write out the metadata we have\nfunc (s *FileSnapshotSink) writeMeta() error {\n\t\/\/ Open the meta file\n\tmetaPath := filepath.Join(s.dir, metaFilePath)\n\tfh, err := os.Create(metaPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fh.Close()\n\n\t\/\/ Buffer the file IO\n\tbuffered := bufio.NewWriter(fh)\n\tdefer buffered.Flush()\n\n\t\/\/ Write out as JSON\n\tenc := json.NewEncoder(buffered)\n\tif err := enc.Encode(&s.meta); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Implement the sort interface for []*fileSnapshotMeta\nfunc (s snapMetaSlice) Len() int {\n\treturn len(s)\n}\n\nfunc (s snapMetaSlice) Less(i, j int) bool {\n\tif s[i].Term != s[j].Term {\n\t\treturn s[i].Term < s[j].Term\n\t}\n\tif s[i].Index != s[j].Index {\n\t\treturn s[i].Index < s[j].Index\n\t}\n\treturn s[i].ID < s[j].ID\n}\n\nfunc (s snapMetaSlice) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n<commit_msg>Use MkdirAll instead to be more resilient.<commit_after>package raft\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"hash\"\n\t\"hash\/crc64\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\ttestPath      = \"permTest\"\n\tsnapPath      = \"snapshots\"\n\tmetaFilePath  = \"meta.json\"\n\tstateFilePath = \"state.bin\"\n\ttmpSuffix     = \".tmp\"\n)\n\n\/\/ FileSnapshotStore implements the SnapshotStore interface and allows\n\/\/ snapshots to be made on the local disk.\ntype FileSnapshotStore struct {\n\tpath   string\n\tretain int\n\tlogger *log.Logger\n}\n\ntype snapMetaSlice []*fileSnapshotMeta\n\n\/\/ FileSnapshotSink implements SnapshotSink with a file.\ntype FileSnapshotSink struct {\n\tstore  *FileSnapshotStore\n\tlogger *log.Logger\n\tdir    string\n\tmeta   fileSnapshotMeta\n\n\tstateFile *os.File\n\tstateHash hash.Hash64\n\tbuffered  *bufio.Writer\n\n\tclosed bool\n}\n\n\/\/ fileSnapshotMeta is stored on disk. We also put a CRC\n\/\/ on disk so that we can verify the snapshot\ntype fileSnapshotMeta struct {\n\tSnapshotMeta\n\tCRC []byte\n}\n\n\/\/ bufferedFile is returned when we open a snapshot. This way\n\/\/ reads are buffered and the file still gets closed.\ntype bufferedFile struct {\n\tbh *bufio.Reader\n\tfh *os.File\n}\n\nfunc (b *bufferedFile) Read(p []byte) (n int, err error) {\n\treturn b.bh.Read(p)\n}\n\nfunc (b *bufferedFile) Close() error {\n\treturn b.fh.Close()\n}\n\n\/\/ NewFileSnapshotStore creates a new FileSnapshotStore based\n\/\/ on a base directory. The `retain` parameter controls how many\n\/\/ snapshots are retained. Must be at least 1.\nfunc NewFileSnapshotStore(base string, retain int, logOutput io.Writer) (*FileSnapshotStore, error) {\n\tif retain < 1 {\n\t\treturn nil, fmt.Errorf(\"must retain at least one snapshot\")\n\t}\n\tif logOutput == nil {\n\t\tlogOutput = os.Stderr\n\t}\n\n\t\/\/ Ensure our path exists\n\tpath := filepath.Join(base, snapPath)\n\tif err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) {\n\t\treturn nil, fmt.Errorf(\"snapshot path not accessible: %v\", err)\n\t}\n\n\t\/\/ Setup the store\n\tstore := &FileSnapshotStore{\n\t\tpath:   path,\n\t\tretain: retain,\n\t\tlogger: log.New(logOutput, \"\", log.LstdFlags),\n\t}\n\n\t\/\/ Do a permissions test\n\tif err := store.testPermissions(); err != nil {\n\t\treturn nil, fmt.Errorf(\"permissions test failed: %v\", err)\n\t}\n\treturn store, nil\n}\n\n\/\/ testPermissions tries to touch a file in our path to see if it works\nfunc (f *FileSnapshotStore) testPermissions() error {\n\tpath := filepath.Join(f.path, testPath)\n\tfh, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfh.Close()\n\tos.Remove(path)\n\treturn nil\n}\n\n\/\/ snapshotName generate s name for the snapshot\nfunc snapshotName(term, index uint64) string {\n\tnow := time.Now()\n\tmsec := now.UnixNano() \/ int64(time.Millisecond)\n\treturn fmt.Sprintf(\"%d-%d-%d\", term, index, msec)\n}\n\n\/\/ Create is used to start a new snapshot\nfunc (f *FileSnapshotStore) Create(index, term uint64, peers []byte) (SnapshotSink, error) {\n\t\/\/ Create a new path\n\tname := snapshotName(term, index)\n\tpath := filepath.Join(f.path, name+tmpSuffix)\n\tf.logger.Printf(\"[INFO] snapshot: Creating new snapshot at %s\", path)\n\n\t\/\/ Make the directory\n\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to make snapshot directory: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Create the sink\n\tsink := &FileSnapshotSink{\n\t\tstore:  f,\n\t\tlogger: f.logger,\n\t\tdir:    path,\n\t\tmeta: fileSnapshotMeta{\n\t\t\tSnapshotMeta: SnapshotMeta{\n\t\t\t\tID:    name,\n\t\t\t\tIndex: index,\n\t\t\t\tTerm:  term,\n\t\t\t\tPeers: peers,\n\t\t\t},\n\t\t\tCRC: nil,\n\t\t},\n\t}\n\n\t\/\/ Write out the meta data\n\tif err := sink.writeMeta(); err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to write metadata: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Open the state file\n\tstatePath := filepath.Join(path, stateFilePath)\n\tfh, err := os.Create(statePath)\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to create state file: %v\", err)\n\t\treturn nil, err\n\t}\n\tsink.stateFile = fh\n\n\t\/\/ Create a CRC64 hash\n\tsink.stateHash = crc64.New(crc64.MakeTable(crc64.ECMA))\n\n\t\/\/ Wrap both the hash and file in a MultiWriter with buffering\n\tmulti := io.MultiWriter(sink.stateFile, sink.stateHash)\n\tsink.buffered = bufio.NewWriter(multi)\n\n\t\/\/ Done\n\treturn sink, nil\n}\n\n\/\/ List returns available snapshots in the store.\nfunc (f *FileSnapshotStore) List() ([]*SnapshotMeta, error) {\n\t\/\/ Get the eligible snapshots\n\tsnapshots, err := f.getSnapshots()\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to get snapshots: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tvar snapMeta []*SnapshotMeta\n\tfor _, meta := range snapshots {\n\t\tsnapMeta = append(snapMeta, &meta.SnapshotMeta)\n\t\tif len(snapMeta) == f.retain {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn snapMeta, nil\n}\n\n\/\/ getSnapshots returns all the known snapshots\nfunc (f *FileSnapshotStore) getSnapshots() ([]*fileSnapshotMeta, error) {\n\t\/\/ Get the eligible snapshots\n\tsnapshots, err := ioutil.ReadDir(f.path)\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to scan snapshot dir: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Populate the metadata\n\tvar snapMeta []*fileSnapshotMeta\n\tfor _, snap := range snapshots {\n\t\t\/\/ Ignore any files\n\t\tif !snap.IsDir() {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Ignore any temporary snapshots\n\t\tdirName := snap.Name()\n\t\tif strings.HasSuffix(dirName, tmpSuffix) {\n\t\t\tf.logger.Printf(\"[WARN] snapshot: Found temporary snapshot: %v\", dirName)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Try to read the meta data\n\t\tmeta, err := f.readMeta(dirName)\n\t\tif err != nil {\n\t\t\tf.logger.Printf(\"[WARN] snapshot: Failed to read metadata for %v: %v\", dirName, err)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Append, but only return up to the retain count\n\t\tsnapMeta = append(snapMeta, meta)\n\t}\n\n\t\/\/ Sort the snapshot, reverse so we get new -> old\n\tsort.Sort(sort.Reverse(snapMetaSlice(snapMeta)))\n\n\treturn snapMeta, nil\n}\n\n\/\/ readMeta is used to read the meta data for a given named backup\nfunc (f *FileSnapshotStore) readMeta(name string) (*fileSnapshotMeta, error) {\n\t\/\/ Open the meta file\n\tmetaPath := filepath.Join(f.path, name, metaFilePath)\n\tfh, err := os.Open(metaPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer fh.Close()\n\n\t\/\/ Buffer the file IO\n\tbuffered := bufio.NewReader(fh)\n\n\t\/\/ Read in the JSON\n\tmeta := &fileSnapshotMeta{}\n\tdec := json.NewDecoder(buffered)\n\tif err := dec.Decode(meta); err != nil {\n\t\treturn nil, err\n\t}\n\treturn meta, nil\n}\n\n\/\/ Open takes a snapshot ID and returns a ReadCloser for that snapshot.\nfunc (f *FileSnapshotStore) Open(id string) (*SnapshotMeta, io.ReadCloser, error) {\n\t\/\/ Get the metadata\n\tmeta, err := f.readMeta(id)\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to get meta data to open snapshot: %v\", err)\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Open the state file\n\tstatePath := filepath.Join(f.path, id, stateFilePath)\n\tfh, err := os.Open(statePath)\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to open state file: %v\", err)\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Create a CRC64 hash\n\tstateHash := crc64.New(crc64.MakeTable(crc64.ECMA))\n\n\t\/\/ Compute the hash\n\t_, err = io.Copy(stateHash, fh)\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to read state file: %v\", err)\n\t\tfh.Close()\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Verify the hash\n\tcomputed := stateHash.Sum(nil)\n\tif bytes.Compare(meta.CRC, computed) != 0 {\n\t\tf.logger.Printf(\"[ERR] snapshot: CRC checksum failed (stored: %v computed: %v)\",\n\t\t\tmeta.CRC, computed)\n\t\tfh.Close()\n\t\treturn nil, nil, fmt.Errorf(\"CRC mismatch\")\n\t}\n\n\t\/\/ Seek to the start\n\tif _, err := fh.Seek(0, 0); err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: State file seek failed: %v\", err)\n\t\tfh.Close()\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Return a buffered file\n\tbuffered := &bufferedFile{\n\t\tbh: bufio.NewReader(fh),\n\t\tfh: fh,\n\t}\n\n\treturn &meta.SnapshotMeta, buffered, nil\n}\n\n\/\/ ReapSnapshots reaps any snapshots beyond the retain count.\nfunc (f *FileSnapshotStore) ReapSnapshots() error {\n\tsnapshots, err := f.getSnapshots()\n\tif err != nil {\n\t\tf.logger.Printf(\"[ERR] snapshot: Failed to get snapshots: %v\", err)\n\t\treturn err\n\t}\n\n\tfor i := f.retain; i < len(snapshots); i++ {\n\t\tpath := filepath.Join(f.path, snapshots[i].ID)\n\t\tf.logger.Printf(\"[INFO] snapshot: reaping snapshot %v\", path)\n\t\tif err := os.RemoveAll(path); err != nil {\n\t\t\tf.logger.Printf(\"[ERR] snapshot: Failed to reap snapshot %v: %v\", path, err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ ID returns the ID of the snapshot, can be used with Open()\n\/\/ after the snapshot is finalized.\nfunc (s *FileSnapshotSink) ID() string {\n\treturn s.meta.ID\n}\n\n\/\/ Write is used to append to the state file. We write to the\n\/\/ buffered IO object to reduce the amount of context switches\nfunc (s *FileSnapshotSink) Write(b []byte) (int, error) {\n\treturn s.buffered.Write(b)\n}\n\n\/\/ Close is used to indicate a successful end\nfunc (s *FileSnapshotSink) Close() error {\n\t\/\/ Make sure close is idempotent\n\tif s.closed {\n\t\treturn nil\n\t}\n\ts.closed = true\n\n\t\/\/ Close the open handles\n\tif err := s.finalize(); err != nil {\n\t\ts.logger.Printf(\"[ERR] snapshot: Failed to finalize snapshot: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Write out the meta data\n\tif err := s.writeMeta(); err != nil {\n\t\ts.logger.Printf(\"[ERR] snapshot: Failed to write metadata: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Move the directory into place\n\tnewPath := strings.TrimSuffix(s.dir, tmpSuffix)\n\tif err := os.Rename(s.dir, newPath); err != nil {\n\t\ts.logger.Printf(\"[ERR] snapshot: Failed to move snapshot into place: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Reap any old snapshots\n\ts.store.ReapSnapshots()\n\treturn nil\n}\n\n\/\/ Cancel is used to indicate an unsuccessful end\nfunc (s *FileSnapshotSink) Cancel() error {\n\t\/\/ Make sure close is idempotent\n\tif s.closed {\n\t\treturn nil\n\t}\n\ts.closed = true\n\n\t\/\/ Close the open handles\n\tif err := s.finalize(); err != nil {\n\t\ts.logger.Printf(\"[ERR] snapshot: Failed to finalize snapshot: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Attempt to remove all artifacts\n\treturn os.RemoveAll(s.dir)\n}\n\n\/\/ finalize is used to close all of our resources\nfunc (s *FileSnapshotSink) finalize() error {\n\t\/\/ Flush any remaining data\n\tif err := s.buffered.Flush(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Get the file size\n\tstat, statErr := s.stateFile.Stat()\n\n\t\/\/ Close the file\n\tif err := s.stateFile.Close(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Set the file size, check after we close\n\tif statErr != nil {\n\t\treturn statErr\n\t}\n\ts.meta.Size = stat.Size()\n\n\t\/\/ Set the CRC\n\ts.meta.CRC = s.stateHash.Sum(nil)\n\treturn nil\n}\n\n\/\/ writeMeta is used to write out the metadata we have\nfunc (s *FileSnapshotSink) writeMeta() error {\n\t\/\/ Open the meta file\n\tmetaPath := filepath.Join(s.dir, metaFilePath)\n\tfh, err := os.Create(metaPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fh.Close()\n\n\t\/\/ Buffer the file IO\n\tbuffered := bufio.NewWriter(fh)\n\tdefer buffered.Flush()\n\n\t\/\/ Write out as JSON\n\tenc := json.NewEncoder(buffered)\n\tif err := enc.Encode(&s.meta); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Implement the sort interface for []*fileSnapshotMeta\nfunc (s snapMetaSlice) Len() int {\n\treturn len(s)\n}\n\nfunc (s snapMetaSlice) Less(i, j int) bool {\n\tif s[i].Term != s[j].Term {\n\t\treturn s[i].Term < s[j].Term\n\t}\n\tif s[i].Index != s[j].Index {\n\t\treturn s[i].Index < s[j].Index\n\t}\n\treturn s[i].ID < s[j].ID\n}\n\nfunc (s snapMetaSlice) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n<|endoftext|>"}
{"text":"<commit_before>package gitmediafilters\n\nimport (\n\t\"..\"\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n)\n\ntype CleanedAsset struct {\n\tSize          int64\n\tFile          *os.File\n\tSha           string\n\tmediafilepath string\n}\n\nfunc Clean(reader io.Reader) (*CleanedAsset, error) {\n\ttmp, err := gitmedia.TempFile()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toidHash := sha256.New()\n\twriter := io.MultiWriter(oidHash, tmp)\n\twritten, err := io.Copy(writer, reader)\n\toidHash.Write([]byte(strconv.FormatInt(written, 10)))\n\n\treturn &CleanedAsset{written, tmp, hex.EncodeToString(oidHash.Sum(nil)), \"\"}, err\n}\n\nfunc (a *CleanedAsset) Close() error {\n\treturn os.Remove(a.File.Name())\n}\n<commit_msg>only hash the file content<commit_after>package gitmediafilters\n\nimport (\n\t\"..\"\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"io\"\n\t\"os\"\n)\n\ntype CleanedAsset struct {\n\tSize          int64\n\tFile          *os.File\n\tSha           string\n\tmediafilepath string\n}\n\nfunc Clean(reader io.Reader) (*CleanedAsset, error) {\n\ttmp, err := gitmedia.TempFile()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toidHash := sha256.New()\n\twriter := io.MultiWriter(oidHash, tmp)\n\twritten, err := io.Copy(writer, reader)\n\n\treturn &CleanedAsset{written, tmp, hex.EncodeToString(oidHash.Sum(nil)), \"\"}, err\n}\n\nfunc (a *CleanedAsset) Close() error {\n\treturn os.Remove(a.File.Name())\n}\n<|endoftext|>"}
{"text":"<commit_before>package firebase_test\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n\n\t\"code.google.com\/p\/gomock\/gomock\"\n\n\t\"github.com\/JustinTulloss\/firebase\"\n\t\"github.com\/JustinTulloss\/firebase\/mock_firebase\"\n)\n\ntype Name struct {\n\tFirst string `json:\",omitempty\"`\n\tLast  string `json:\",omitempty\"`\n}\n\nfunc nameAlloc() interface{} {\n\treturn &Name{}\n}\n\n\/*\nSet the two variables below and set them to your own\nFirebase URL and credentials (optional) if you're forking the code\nand want to test your changes.\n*\/\n\n\/\/ enter your firebase credentials for testing.\nvar (\n\ttestUrl  string = os.Getenv(\"FIREBASE_TEST_URL\")\n\ttestAuth string = os.Getenv(\"FIREBASE_TEST_AUTH\")\n)\n\nfunc TestValue(t *testing.T) {\n\tclient := firebase.NewClient(testUrl+\"\/tests\", testAuth, nil)\n\n\tvar r map[string]interface{}\n\terr := client.Value(&r)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif r == nil {\n\t\tt.Fatalf(\"No values returned from the server\\n\")\n\t}\n}\n\nfunc TestChild(t *testing.T) {\n\tclient := firebase.NewClient(testUrl+\"\/tests\", testAuth, nil)\n\n\tr := client.Child(\"\")\n\n\tif r == nil {\n\t\tt.Fatalf(\"No child returned from the server\\n\")\n\t}\n}\n\nfunc TestPush(t *testing.T) {\n\tclient := firebase.NewClient(testUrl+\"\/tests\", testAuth, nil)\n\n\tname := &Name{First: \"FirstName\", Last: \"LastName\"}\n\n\tr, err := client.Push(name, nil)\n\n\tif err != nil {\n\t\tt.Fatalf(\"%v\\n\", err)\n\t}\n\n\tif r == nil {\n\t\tt.Fatalf(\"No client returned from the server\\n\")\n\t}\n\n\tnewName := &Name{}\n\tc2 := firebase.NewClient(r.String(), testAuth, nil)\n\tc2.Value(newName)\n\tif !reflect.DeepEqual(name, newName) {\n\t\tt.Errorf(\"Expected %v to equal %v\", name, newName)\n\t}\n}\n\nfunc TestSet(t *testing.T) {\n\tc1 := firebase.NewClient(testUrl+\"\/tests\/users\", testAuth, nil)\n\n\tname := &Name{First: \"First\", Last: \"last\"}\n\tc2, _ := c1.Push(name, nil)\n\n\tnewName := &Name{First: \"NewFirst\", Last: \"NewLast\"}\n\tr, err := c2.Set(\"\", newName, map[string]string{\"print\": \"silent\"})\n\n\tif err != nil {\n\t\tt.Fatalf(\"%v\\n\", err)\n\t}\n\n\tif r == nil {\n\t\tt.Fatalf(\"No client returned from the server\\n\")\n\t}\n}\n\nfunc TestUpdate(t *testing.T) {\n\tc1 := firebase.NewClient(testUrl+\"\/tests\/users\", testAuth, nil)\n\n\tname := &Name{First: \"First\", Last: \"last\"}\n\tc2, _ := c1.Push(name, nil)\n\n\tnewName := &Name{Last: \"NewLast\"}\n\terr := c2.Update(\"\", newName, nil)\n\n\tif err != nil {\n\t\tt.Fatalf(\"%v\\n\", err)\n\t}\n}\n\nfunc TestRemovet(t *testing.T) {\n\tc1 := firebase.NewClient(testUrl+\"\/tests\/users\", testAuth, nil)\n\n\tname := &Name{First: \"First\", Last: \"last\"}\n\tc2, _ := c1.Push(name, nil)\n\n\terr := c2.Remove(\"\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"%v\\n\", err)\n\t}\n\n\tvar val map[string]interface{}\n\tc3 := firebase.NewClient(c2.String(), testAuth, nil)\n\terr = c3.Value(&val)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(val) != 0 {\n\t\tt.Errorf(\"Expected %s to be removed, was %v\", c2.String(), val)\n\t}\n}\n\nfunc TestRules(t *testing.T) {\n\tclient := firebase.NewClient(testUrl, testAuth, nil)\n\n\tr, err := client.Rules(nil)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error retrieving rules: %v\\n\", err)\n\t}\n\n\tif r == nil {\n\t\tt.Fatalf(\"No child returned from the server\\n\")\n\t}\n}\n\nfunc TestSetRules(t *testing.T) {\n\tclient := firebase.NewClient(testUrl, testAuth, nil)\n\n\trules := &firebase.Rules{\n\t\t\"rules\": map[string]interface{}{\n\t\t\t\".read\":  \"auth.username == 'admin'\",\n\t\t\t\".write\": \"auth.username == 'admin'\",\n\t\t\t\"ordered\": map[string]interface{}{\n\t\t\t\t\".indexOn\": []string{\"First\"},\n\t\t\t\t\"kids\": map[string]interface{}{\n\t\t\t\t\t\".indexOn\": []string{\"Age\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\terr := client.SetRules(rules, nil)\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error setting rules: %v\\n\", err)\n\t}\n}\n\nfunc TestOrderBy(t *testing.T) {\n\tclient := firebase.NewClient(testUrl, testAuth, nil).Child(\"ordered\")\n\tdefer client.Remove(\"\", nil)\n\n\tnames := []*Name{\n\t\t&Name{First: \"BBBB\", Last: \"YYYY\"},\n\t\t&Name{First: \"AAAA\", Last: \"ZZZZZ\"},\n\t}\n\n\tfor _, n := range names {\n\t\t_, err := client.Push(n, nil)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Couldn't push new name: %s\\n\", err)\n\t\t}\n\t}\n\n\ti := 0\n\tfor n := range client.OrderBy(firebase.KeyProp).Iterator(nameAlloc) {\n\t\tif n.Value.(*Name).First != names[i].First {\n\t\t\tt.Fatalf(\"Key order was not delivered\")\n\t\t}\n\t\ti++\n\t}\n\tif i == 0 {\n\t\tt.Fatalf(\"Did not receive names ordered by key\")\n\t}\n\n\texpectedOrder := []*Name{names[1], names[0]}\n\ti = 0\n\tfor n := range client.OrderBy(\"First\").Iterator(nameAlloc) {\n\t\tif n.Value.(*Name).First != expectedOrder[i].First {\n\t\t\tt.Fatalf(\"Child prop order was not delivered\")\n\t\t}\n\t\ti++\n\t}\n\tif i == 0 {\n\t\tt.Fatalf(\"Did not receive names ordered by first name\")\n\t}\n\n\tkids := map[string]map[string]interface{}{\n\t\t\"a\": map[string]interface{}{\"Name\": \"Bob\", \"Age\": 14},\n\t\t\"b\": map[string]interface{}{\"Name\": \"Alice\", \"Age\": 13},\n\t}\n\t_, err := client.Set(\"kids\", kids, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"Could not set kids: %s\\n\", err)\n\t}\n\n\texpectedKidsOrder := []map[string]interface{}{kids[\"b\"], kids[\"a\"]}\n\ti = 0\n\tfor n := range client.Child(\"kids\").OrderBy(\"Age\").Iterator(nil) {\n\t\tif (*n.Value.(*map[string]interface{}))[\"First\"] != expectedKidsOrder[i][\"First\"] {\n\t\t\tt.Fatalf(\"Child prop order by age was not delivered\")\n\t\t}\n\t\ti++\n\t}\n\tif i == 0 {\n\t\tt.Fatalf(\"Did not receive names ordered by age\")\n\t}\n}\n\nfunc TestTimestamp(t *testing.T) {\n\tts := firebase.Timestamp(time.Now())\n\tmarshaled, err := json.Marshal(&ts)\n\tif err != nil {\n\t\tt.Fatalf(\"Could not marshal a timestamp to json: %s\\n\", err)\n\t}\n\tunmarshaledTs := firebase.Timestamp{}\n\terr = json.Unmarshal(marshaled, &unmarshaledTs)\n\tif err != nil {\n\t\tt.Fatalf(\"Could not unmarshal a timestamp to json: %s\\n\", err)\n\t}\n\t\/\/ Compare unix timestamps as we lose some fidelity in the nanoseconds\n\tif time.Time(ts).Unix() != time.Time(unmarshaledTs).Unix() {\n\t\tt.Fatalf(\"Unmarshaled time %s not equivalent to marshaled time %s\",\n\t\t\tunmarshaledTs,\n\t\t\tts,\n\t\t)\n\t}\n}\n\nfunc TestServerTimestamp(t *testing.T) {\n\tb, err := json.Marshal(firebase.ServerTimestamp)\n\tif err != nil {\n\t\tt.Fatalf(\"Could not marshal server timestamp: %s\\n\", err)\n\t}\n\tif string(b) != `{\".sv\":\"timestamp\"}` {\n\t\tt.Fatalf(\"Unexpected timestamp json value: %s\\n\", b)\n\t}\n}\n\nfunc TestIterator(t *testing.T) {\n\tclient := firebase.NewClient(testUrl+\"\/test-iterator\", testAuth, nil)\n\tdefer client.Remove(\"\", nil)\n\tnames := []Name{\n\t\t{First: \"FirstName\", Last: \"LastName\"},\n\t\t{First: \"Second\", Last: \"Seconder\"},\n\t}\n\tfor _, name := range names {\n\t\t_, err := client.Push(name, nil)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%v\\n\", err)\n\t\t}\n\t}\n\n\tvar i = 0\n\tfor nameEntry := range client.Iterator(nameAlloc) {\n\t\tname := nameEntry.Value.(*Name)\n\t\tif !reflect.DeepEqual(&names[i], name) {\n\t\t\tt.Errorf(\"Expected %v to equal %v\", &names[i], name)\n\t\t}\n\t\ti++\n\t}\n\tif i != len(names) {\n\t\tt.Fatalf(\"Did not receive all names, received %d\\n\", i)\n\t}\n}\n\nfunc TestShallow(t *testing.T) {\n\tclient := firebase.NewClient(testUrl+\"\/test-shallow\", testAuth, nil)\n\tdefer client.Remove(\"\", nil)\n\tclient.Set(\"one\", 1, nil)\n\tclient.Set(\"two\", 2, nil)\n\tkeys, err := client.Shallow()\n\tif err != nil {\n\t\tt.Errorf(\"Error when calling shallow: %s\\n\", err)\n\t}\n\tif !reflect.DeepEqual(keys, []string{\"one\", \"two\"}) {\n\t\tt.Errorf(\"keys (%v) were not correct\\n\", keys)\n\t}\n}\n\nfunc TestKey(t *testing.T) {\n\tclient := firebase.NewClient(testUrl+\"\/test\", testAuth, nil)\n\tif client.Key() != \"test\" {\n\t\tt.Errorf(\"Key should have been test, was %s\\n\", client.Key())\n\t}\n\n\tclient = firebase.NewClient(testUrl, testAuth, nil)\n\tif client.Key() != \"\" {\n\t\tt.Errorf(\"Key should have been empty, was %s\\n\", client.Key())\n\t}\n\n\tclient = client.Child(\"\/a\/b\/c\/d\/e\/f\/g\")\n\tif client.Key() != \"g\" {\n\t\tt.Errorf(\"Key should have been 'g', was %s\\n\", client.Key())\n\t}\n}\n\nfunc TestMockable(t *testing.T) {\n\tmockCtrl := gomock.NewController(t)\n\tdefer mockCtrl.Finish()\n\n\tmockFire := mock_firebase.NewMockClient(mockCtrl)\n\tmockFire.EXPECT().Child(\"test\")\n\tmockFire.Child(\"test\")\n}\n\nfunc TestMain(m *testing.M) {\n\tif testUrl == \"\" || testAuth == \"\" {\n\t\tfmt.Printf(\"You need to set FIREBASE_TEST_URL and FIREBASE_TEST_AUTH\\n\")\n\t\tos.Exit(1)\n\t}\n\tos.Exit(m.Run())\n}\n<commit_msg>Convert unit tests to ginkgo\/gomega<commit_after>package firebase\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar (\n\ttestUrl  = \"\"\n\ttestAuth = \"\"\n)\n\ntype Name struct {\n\tFirst string `json:\",omitempty\"`\n\tLast  string `json:\",omitempty\"`\n}\n\nfunc nameAlloc() interface{} {\n\treturn &Name{}\n}\n\nfunc fakeServer(handler http.Handler) (*httptest.Server, *client) {\n\ttestServer := httptest.NewServer(handler)\n\n\tc := NewClient(testServer.URL, testAuth, nil)\n\ttestClient, isClient := c.(*client)\n\tExpect(isClient).To(BeTrue())\n\n\treturn testServer, testClient\n}\n\nvar _ = Describe(\"Transforming client urls\/queries\", func() {\n\tvar (\n\t\tc        *client\n\t\tisClient bool\n\t\ttestURL  string = \"https:\/\/who.cares.com\"\n\t)\n\n\tBeforeEach(func() {\n\t\tc, isClient = NewClient(testURL, testAuth, nil).(*client)\n\t\tExpect(isClient).To(BeTrue())\n\t})\n\n\tIt(\"Adds the child path to the returned client object\", func() {\n\t\tchild, isClient := c.Child(\"child\").(*client)\n\t\tExpect(isClient).To(BeTrue())\n\n\t\tExpect(child.url).To(Equal(testURL + \"\/child\"))\n\t})\n\n\tIt(\"Sets a query string param to ask for a shallow object\", func() {\n\t\tshallow, isClient := c.Shallow().(*client)\n\t\tExpect(isClient).To(BeTrue())\n\n\t\tExpect(shallow.params[\"shallow\"]).To(Equal(\"true\"))\n\t})\n\n\tIt(\"Retrieves the key of a client\", func() {\n\t\tExpect(c.Key()).To(Equal(\"\"))\n\t\tExpect(c.Child(\"test\").Key()).To(Equal(\"test\"))\n\t\tExpect(c.Child(\"\/a\/b\/c\/d\/e\/f\/g\").Key()).To(Equal(\"g\"))\n\t})\n})\n\nvar _ = Describe(\"Manipulating values from firebase\", func() {\n\tvar (\n\t\ttestResource Name\n\t\ttestServer   *httptest.Server\n\t\ttestClient   *client\n\t\thandler      func(w http.ResponseWriter, r *http.Request)\n\t)\n\n\tBeforeEach(func() {\n\t\ttestResource = Name{First: \"FirstName\", Last: \"LastName\"}\n\t})\n\n\tJustBeforeEach(func() {\n\t\ttestServer, testClient = fakeServer(http.HandlerFunc(handler))\n\t})\n\n\tContext(\"Retrieving a value from firebase\", func() {\n\t\tBeforeEach(func() {\n\t\t\thandler = func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tExpect(r.Method).To(Equal(\"GET\"))\n\t\t\t\tfmt.Fprintln(w, `{\"bru\": \"haha\"}`)\n\t\t\t}\n\t\t})\n\n\t\tIt(\"Retrieves the expected value from the resource path\", func() {\n\t\t\tvar r map[string]interface{}\n\t\t\terr := testClient.Child(\"\").Value(&r)\n\t\t\tExpect(err).To(BeNil())\n\n\t\t\tExpect(len(r)).To(Equal(1))\n\t\t\tExpect(r[\"bru\"]).To(Equal(\"haha\"))\n\t\t})\n\t})\n\n\tContext(\"Pushing a new value to firebase\", func() {\n\t\tvar (\n\t\t\tpushedName string = \"baloo\"\n\t\t)\n\n\t\tBeforeEach(func() {\n\t\t\thandler = func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tExpect(r.Method).To(Equal(\"POST\"))\n\n\t\t\t\tvar pushed Name\n\t\t\t\tdefer r.Body.Close()\n\n\t\t\t\tdecoder := json.NewDecoder(r.Body)\n\t\t\t\terr := decoder.Decode(&pushed)\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(pushed).To(Equal(testResource))\n\n\t\t\t\tfmt.Fprintf(w, `{\"name\": \"%s\"}`, pushedName)\n\t\t\t}\n\t\t})\n\n\t\tIt(\"Pushes the new resource and returns a matching client\", func() {\n\t\t\tname := &testResource\n\n\t\t\tresponse, err := testClient.Child(\"path\").Push(name, nil)\n\t\t\tExpect(err).To(BeNil())\n\n\t\t\tresponseClient, isClient := response.(*client)\n\t\t\tExpect(isClient).To(BeTrue())\n\t\t\tExpect(responseClient.url).To(Equal(testServer.URL + \"\/path\/\" +\n\t\t\t\tpushedName))\n\t\t})\n\t})\n\n\tContext(\"Setting an existing value in firebase\", func() {\n\t\tvar (\n\t\t\tnewName Name   = Name{First: \"NewFirst\", Last: \"NewLast\"}\n\t\t\tsetPath string = \"set\"\n\t\t)\n\n\t\tBeforeEach(func() {\n\t\t\thandler = func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tExpect(r.Method).To(Equal(\"PUT\"))\n\n\t\t\t\tvar setValue Name\n\t\t\t\tdefer r.Body.Close()\n\n\t\t\t\tdecoder := json.NewDecoder(r.Body)\n\t\t\t\terr := decoder.Decode(&setValue)\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(setValue).To(Equal(newName))\n\t\t\t}\n\t\t})\n\n\t\tIt(\"Overwrites the value of the existing resource\", func() {\n\t\t\tresponse, err := testClient.Set(setPath, &newName, nil)\n\t\t\tExpect(err).To(BeNil())\n\n\t\t\tresponseClient, isClient := response.(*client)\n\t\t\tExpect(isClient).To(BeTrue())\n\t\t\tExpect(responseClient.url).To(Equal(testServer.URL + \"\/\" +\n\t\t\t\tsetPath))\n\t\t})\n\t})\n\n\tContext(\"Update an existing value in firebase\", func() {\n\t\tvar (\n\t\t\tupdatedName Name   = Name{Last: \"NewLast\"}\n\t\t\tupdatePath  string = \"update\"\n\t\t)\n\n\t\tBeforeEach(func() {\n\t\t\thandler = func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tExpect(r.Method).To(Equal(\"PATCH\"))\n\t\t\t\tExpect(r.URL.String()).To(Equal(\"\/\" + updatePath + \".json\"))\n\n\t\t\t\tvar updateValue Name\n\t\t\t\tdefer r.Body.Close()\n\n\t\t\t\tdecoder := json.NewDecoder(r.Body)\n\t\t\t\terr := decoder.Decode(&updateValue)\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(updateValue).To(Equal(updatedName))\n\t\t\t}\n\t\t})\n\n\t\tIt(\"Changes the value of the existing resource\", func() {\n\t\t\terr := testClient.Update(updatePath, &updatedName, nil)\n\t\t\tExpect(err).To(BeNil())\n\t\t})\n\t})\n\n\tContext(\"Delete an existing value in firebase\", func() {\n\t\tvar (\n\t\t\trmPath string = \"update\"\n\t\t)\n\n\t\tBeforeEach(func() {\n\t\t\thandler = func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tExpect(r.Method).To(Equal(\"DELETE\"))\n\t\t\t\tExpect(r.URL.String()).To(Equal(\"\/\" + rmPath + \".json\"))\n\t\t\t}\n\t\t})\n\n\t\tIt(\"Deletes the resource\", func() {\n\t\t\terr := testClient.Remove(rmPath, nil)\n\t\t\tExpect(err).To(BeNil())\n\t\t})\n\t})\n\n\tContext(\"Reading the security rules\", func() {\n\t\tvar testRules Rules = make(map[string]interface{})\n\n\t\tBeforeEach(func() {\n\t\t\ttestRules[\"rules\"] = \"anything goes\"\n\n\t\t\thandler = func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tExpect(r.Method).To(Equal(\"GET\"))\n\t\t\t\tExpect(r.URL.String()).To(Equal(\"\/.settings\/rules.json\"))\n\n\t\t\t\tencoder := json.NewEncoder(w)\n\t\t\t\terr := encoder.Encode(testRules)\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t}\n\t\t})\n\n\t\tIt(\"Retrieves the firebase's security rules\", func() {\n\t\t\trules, err := testClient.Rules(nil)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(*rules).To(Equal(testRules))\n\t\t})\n\t})\n\n\tContext(\"Changing the firebase's security rules\", func() {\n\t\tvar newRules Rules\n\n\t\tBeforeEach(func() {\n\t\t\tnewRules = Rules{\n\t\t\t\t\"rules\": map[string]interface{}{\n\t\t\t\t\t\".read\":  \"auth.username == 'admin'\",\n\t\t\t\t\t\".write\": \"auth.username == 'admin'\",\n\t\t\t\t\t\"ordered\": map[string]interface{}{\n\t\t\t\t\t\t\".indexOn\": []string{\"First\"},\n\t\t\t\t\t\t\"kids\": map[string]interface{}{\n\t\t\t\t\t\t\t\".indexOn\": []string{\"Age\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\thandler = func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tvar changedRules Rules\n\t\t\t\tExpect(r.Method).To(Equal(\"PUT\"))\n\t\t\t\tExpect(r.URL.String()).To(Equal(\"\/.settings\/rules.json\"))\n\n\t\t\t\tdefer r.Body.Close()\n\t\t\t\tdecoder := json.NewDecoder(r.Body)\n\t\t\t\terr := decoder.Decode(&changedRules)\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t}\n\t\t})\n\n\t\tIt(\"Changes the security rules\", func() {\n\t\t\terr := testClient.SetRules(&newRules, nil)\n\t\t\tExpect(err).To(BeNil())\n\t\t})\n\t})\n})\n\nvar _ = Describe(\"Firebase timestamps\", func() {\n\tIt(\"Marshals a timestamp into ms since the epoch\", func() {\n\t\tts := Timestamp(time.Now())\n\t\tmarshaled, err := json.Marshal(&ts)\n\t\tExpect(err).To(BeNil())\n\n\t\tunmarshaledTs := Timestamp{}\n\t\terr = json.Unmarshal(marshaled, &unmarshaledTs)\n\t\tExpect(err).To(BeNil())\n\n\t\t\/\/ Compare unix timestamps as we lose some fidelity in the nanoseconds\n\t\tExpect(time.Time(ts).Unix()).To(Equal(time.Time(unmarshaledTs).Unix()))\n\t})\n\n\tIt(\"Marhsals a server-side timestamp\", func() {\n\t\ttext, err := json.Marshal(ServerTimestamp)\n\t\tExpect(err).To(BeNil())\n\t\tExpect(string(text)).To(Equal(`{\".sv\":\"timestamp\"}`))\n\t})\n})\n\nfunc TestOrderBy(t *testing.T) {\n\tt.Skip(\"needs httptest\")\n\tclient := NewClient(testUrl, testAuth, nil).Child(\"ordered\")\n\tdefer client.Remove(\"\", nil)\n\n\tnames := []*Name{\n\t\t&Name{First: \"BBBB\", Last: \"YYYY\"},\n\t\t&Name{First: \"AAAA\", Last: \"ZZZZZ\"},\n\t}\n\n\tfor _, n := range names {\n\t\t_, err := client.Push(n, nil)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Couldn't push new name: %s\\n\", err)\n\t\t}\n\t}\n\n\ti := 0\n\tfor n := range client.OrderBy(KeyProp).Iterator(nameAlloc) {\n\t\tif n.Value.(*Name).First != names[i].First {\n\t\t\tt.Fatalf(\"Key order was not delivered\")\n\t\t}\n\t\ti++\n\t}\n\tif i == 0 {\n\t\tt.Fatalf(\"Did not receive names ordered by key\")\n\t}\n\n\texpectedOrder := []*Name{names[1], names[0]}\n\ti = 0\n\tfor n := range client.OrderBy(\"First\").Iterator(nameAlloc) {\n\t\tif n.Value.(*Name).First != expectedOrder[i].First {\n\t\t\tt.Fatalf(\"Child prop order was not delivered\")\n\t\t}\n\t\ti++\n\t}\n\tif i == 0 {\n\t\tt.Fatalf(\"Did not receive names ordered by first name\")\n\t}\n\n\tkids := map[string]map[string]interface{}{\n\t\t\"a\": map[string]interface{}{\"Name\": \"Bob\", \"Age\": 14},\n\t\t\"b\": map[string]interface{}{\"Name\": \"Alice\", \"Age\": 13},\n\t}\n\t_, err := client.Set(\"kids\", kids, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"Could not set kids: %s\\n\", err)\n\t}\n\n\texpectedKidsOrder := []map[string]interface{}{kids[\"b\"], kids[\"a\"]}\n\ti = 0\n\tfor n := range client.Child(\"kids\").OrderBy(\"Age\").Iterator(nil) {\n\t\tif (*n.Value.(*map[string]interface{}))[\"First\"] != expectedKidsOrder[i][\"First\"] {\n\t\t\tt.Fatalf(\"Child prop order by age was not delivered\")\n\t\t}\n\t\ti++\n\t}\n\tif i == 0 {\n\t\tt.Fatalf(\"Did not receive names ordered by age\")\n\t}\n}\n\nfunc TestIterator(t *testing.T) {\n\tt.Skip(\"needs httptest\")\n\tclient := NewClient(testUrl+\"\/test-iterator\", testAuth, nil)\n\tdefer client.Remove(\"\", nil)\n\tnames := []Name{\n\t\t{First: \"FirstName\", Last: \"LastName\"},\n\t\t{First: \"Second\", Last: \"Seconder\"},\n\t}\n\tfor _, name := range names {\n\t\t_, err := client.Push(name, nil)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%v\\n\", err)\n\t\t}\n\t}\n\n\tvar i = 0\n\tfor nameEntry := range client.Iterator(nameAlloc) {\n\t\tname := nameEntry.Value.(*Name)\n\t\tif !reflect.DeepEqual(&names[i], name) {\n\t\t\tt.Errorf(\"Expected %v to equal %v\", &names[i], name)\n\t\t}\n\t\ti++\n\t}\n\tif i != len(names) {\n\t\tt.Fatalf(\"Did not receive all names, received %d\\n\", i)\n\t}\n}\n\nfunc TestFirebase(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Firebase Suite\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"os\/exec\"\n\t\"strings\"\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"bufio\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\n\t\"github.com\/flynn\/go-discover\/discover\"\n\t\"github.com\/flynn\/lorne\/types\"\n\t\"github.com\/titanous\/go-dockerclient\"\n\t\"github.com\/flynn\/sampi\/types\"\n\tsc \"github.com\/flynn\/sampi\/client\"\n\tlc \"github.com\/flynn\/lorne\/client\"\n)\n\n\/\/ WARNING: assumes one host at the moment (firstHost will always be the same)\n\n\nvar sd *discover.Client\nvar sched *sc.Client\nvar host *lc.Client\nvar hostid string\n\nfunc init() {\n\tvar err error\n\tsd, err = discover.NewClient()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tsched, err = sc.New()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\thostid = findHost()\n\thost, err = lc.New(hostid)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc main() {\n\troot := \"\/var\/lib\/demo\/apps\"\n\thostname := shell(\"curl -s icanhazip.com\")\n\n\tset, _ := sd.Services(\"shelf\")\n\taddrs := set.OnlineAddrs()\n\tif len(addrs) < 1 {\n\t\tpanic(\"Shelf is not discoverable\")\n\t}\n\tshelfHost := addrs[0]\n\n\tapp := os.Args[2]\n\tos.MkdirAll(root+\"\/\"+app, 0755)\n\n\tfmt.Printf(\"-----> Building %s on %s ...\\n\", app, hostname)\n\n\tscheduleAndAttach(app + \".build\", docker.Config{\n\t\tImage:        \"flynn\/slugbuilder\",\n\t\tCmd:          []string{\"http:\/\/\" + shelfHost + \"\/\" + app + \".tgz\"},\n\t\tTty:          false,\n\t\tAttachStdin:  true,\n\t\tAttachStdout: true,\n\t\tAttachStderr: true,\n\t\tOpenStdin:    true,\n\t\tStdinOnce:    true,\n\t})\n\n\tfmt.Printf(\"-----> Deploying %s ...\\n\", app)\n\t\n\tjobid := app + \".web\"\n\n\tstopIfExists(jobid)\n\tscheduleWithTcpPort(jobid, docker.Config{\n\t\tImage:        \"flynn\/slugrunner\",\n\t\tCmd:          []string{\"start web\"},\n\t\tTty:          false,\n\t\tAttachStdin:  false,\n\t\tAttachStdout: false,\n\t\tAttachStderr: false,\n\t\tOpenStdin:    false,\n\t\tStdinOnce:    false,\n\t\tEnv: []string{\n\t\t\t\"SLUG_URL=http:\/\/\" + shelfHost + \"\/\" + app + \".tgz\",\n\t\t},\n\t})\n\n\tfmt.Printf(\"=====> Application deployed!\\n\")\n\t\/\/fmt.Printf(\"       %s\\n\", getUrl(jobid))\n\tfmt.Println(\"\")\n\n}\n\nfunc shell(cmdline string) string {\n        out, err := exec.Command(\"bash\", \"-c\", cmdline).Output()\n        if err != nil {\n                panic(err)\n        }\n        return strings.Trim(string(out), \" \\n\")\n}\n\nfunc stopIfExists(jobid string) {\n\t_, err := host.GetJob(jobid)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err := host.StopJob(jobid); err != nil {\n\t\treturn\n\t}\n}\n\nfunc scheduleWithTcpPort(jobid string, config docker.Config) {\n\n\tschedReq := &sampi.ScheduleReq{\n\t\tIncremental: true,\n\t\tHostJobs:    map[string][]*sampi.Job{hostid: {{ID: jobid, Config: &config, TCPPorts: 1}}},\n\t}\n\tif _, err := sched.Schedule(schedReq); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\/*func getUrl(jobid string) string {\n\tif job, err := host.GetJob(jobid); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}*\/\n\nfunc findHost() string {\n\tstate, err := sched.State()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar firstHost string\n\tfor k := range state {\n\t\tfirstHost = k\n\t\tbreak\n\t}\n\tif firstHost == \"\" {\n\t\tlog.Fatal(\"no hosts\")\n\t}\n\treturn firstHost\n}\n\nfunc scheduleAndAttach(jobid string, config docker.Config) {\n\n\tservices, err := sd.Services(\"flynn-lorne-attach.\" + hostid)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconn, err := net.Dial(\"tcp\", services.OnlineAddrs()[0])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = gob.NewEncoder(conn).Encode(&lorne.AttachReq{\n\t\tJobID: jobid,\n\t\tFlags: lorne.AttachFlagStdout | lorne.AttachFlagStderr | lorne.AttachFlagStdin | lorne.AttachFlagStream,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tattachState := make([]byte, 1)\n\tif _, err := conn.Read(attachState); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tswitch attachState[0] {\n\tcase lorne.AttachError:\n\t\tlog.Fatal(\"attach error\")\n\t}\n\n\tschedReq := &sampi.ScheduleReq{\n\t\tIncremental: true,\n\t\tHostJobs:    map[string][]*sampi.Job{hostid: {{ID: jobid, Config: &config}}},\n\t}\n\tif _, err := sched.Schedule(schedReq); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif _, err := conn.Read(attachState); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tgo func() {\n\t\tio.Copy(conn, os.Stdin)\n\t\tconn.(*net.TCPConn).CloseWrite()\n\t}()\n\tscanner := bufio.NewScanner(conn)\n\tfor scanner.Scan() {\n\t\tfmt.Fprintln(os.Stdout, scanner.Text()[8:])\n\t}\n\tconn.Close()\n}\n<commit_msg>added lorne and sampi to project<commit_after>package main\n\nimport (\n\t\"os\/exec\"\n\t\"strings\"\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"bufio\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\n\t\"github.com\/flynn\/go-discover\/discover\"\n\t\"github.com\/flynn\/lorne\/types\"\n\t\"github.com\/titanous\/go-dockerclient\"\n\t\"github.com\/flynn\/sampi\/types\"\n\tsc \"github.com\/flynn\/sampi\/client\"\n\tlc \"github.com\/flynn\/lorne\/client\"\n)\n\n\/\/ WARNING: assumes one host at the moment (firstHost will always be the same)\n\n\nvar sd *discover.Client\nvar sched *sc.Client\nvar host *lc.Client\nvar hostid string\n\nfunc init() {\n\tvar err error\n\tsd, err = discover.NewClient()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tsched, err = sc.New()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\thostid = findHost()\n\thost, err = lc.New(hostid)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc main() {\n\troot := \"\/var\/lib\/demo\/apps\"\n\thostname := shell(\"curl -s icanhazip.com\")\n\n\tset, _ := sd.Services(\"shelf\")\n\taddrs := set.OnlineAddrs()\n\tif len(addrs) < 1 {\n\t\tpanic(\"Shelf is not discoverable\")\n\t}\n\tshelfHost := addrs[0]\n\n\tapp := os.Args[2]\n\tos.MkdirAll(root+\"\/\"+app, 0755)\n\n\tfmt.Printf(\"-----> Building %s on %s ...\\n\", app, hostname)\n\n\tscheduleAndAttach(app + \".build\", docker.Config{\n\t\tImage:        \"flynn\/slugbuilder\",\n\t\tCmd:          []string{\"http:\/\/\" + shelfHost + \"\/\" + app + \".tgz\"},\n\t\tTty:          false,\n\t\tAttachStdin:  true,\n\t\tAttachStdout: true,\n\t\tAttachStderr: true,\n\t\tOpenStdin:    true,\n\t\tStdinOnce:    true,\n\t})\n\n\tfmt.Printf(\"-----> Deploying %s ...\\n\", app)\n\t\n\tjobid := app + \".web\"\n\n\tstopIfExists(jobid)\n\tscheduleWithTcpPort(jobid, docker.Config{\n\t\tImage:        \"flynn\/slugrunner\",\n\t\tCmd:          []string{\"start\", \"web\"},\n\t\tTty:          false,\n\t\tAttachStdin:  false,\n\t\tAttachStdout: false,\n\t\tAttachStderr: false,\n\t\tOpenStdin:    false,\n\t\tStdinOnce:    false,\n\t\tEnv: []string{\n\t\t\t\"SLUG_URL=http:\/\/\" + shelfHost + \"\/\" + app + \".tgz\",\n\t\t},\n\t})\n\n\tfmt.Printf(\"=====> Application deployed!\\n\")\n\t\/\/fmt.Printf(\"       %s\\n\", getUrl(jobid))\n\tfmt.Println(\"\")\n\n}\n\nfunc shell(cmdline string) string {\n        out, err := exec.Command(\"bash\", \"-c\", cmdline).Output()\n        if err != nil {\n                panic(err)\n        }\n        return strings.Trim(string(out), \" \\n\")\n}\n\nfunc stopIfExists(jobid string) {\n\t_, err := host.GetJob(jobid)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err := host.StopJob(jobid); err != nil {\n\t\treturn\n\t}\n}\n\nfunc scheduleWithTcpPort(jobid string, config docker.Config) {\n\n\tschedReq := &sampi.ScheduleReq{\n\t\tIncremental: true,\n\t\tHostJobs:    map[string][]*sampi.Job{hostid: {{ID: jobid, Config: &config, TCPPorts: 1}}},\n\t}\n\tif _, err := sched.Schedule(schedReq); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\/*func getUrl(jobid string) string {\n\tif job, err := host.GetJob(jobid); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}*\/\n\nfunc findHost() string {\n\tstate, err := sched.State()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar firstHost string\n\tfor k := range state {\n\t\tfirstHost = k\n\t\tbreak\n\t}\n\tif firstHost == \"\" {\n\t\tlog.Fatal(\"no hosts\")\n\t}\n\treturn firstHost\n}\n\nfunc scheduleAndAttach(jobid string, config docker.Config) {\n\n\tservices, err := sd.Services(\"flynn-lorne-attach.\" + hostid)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconn, err := net.Dial(\"tcp\", services.OnlineAddrs()[0])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = gob.NewEncoder(conn).Encode(&lorne.AttachReq{\n\t\tJobID: jobid,\n\t\tFlags: lorne.AttachFlagStdout | lorne.AttachFlagStderr | lorne.AttachFlagStdin | lorne.AttachFlagStream,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tattachState := make([]byte, 1)\n\tif _, err := conn.Read(attachState); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tswitch attachState[0] {\n\tcase lorne.AttachError:\n\t\tlog.Fatal(\"attach error\")\n\t}\n\n\tschedReq := &sampi.ScheduleReq{\n\t\tIncremental: true,\n\t\tHostJobs:    map[string][]*sampi.Job{hostid: {{ID: jobid, Config: &config}}},\n\t}\n\tif _, err := sched.Schedule(schedReq); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif _, err := conn.Read(attachState); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tgo func() {\n\t\tio.Copy(conn, os.Stdin)\n\t\tconn.(*net.TCPConn).CloseWrite()\n\t}()\n\tscanner := bufio.NewScanner(conn)\n\tfor scanner.Scan() {\n\t\tfmt.Fprintln(os.Stdout, scanner.Text()[8:])\n\t}\n\tconn.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>package dependencies\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-cli\/artifactory\/utils\"\n\tgolangutil \"github.com\/jfrog\/jfrog-cli-go\/jfrog-cli\/artifactory\/utils\/golang\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-cli\/utils\/config\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-client\/artifactory\/buildinfo\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-client\/artifactory\/services\/vgo\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-client\/utils\/errorutils\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-client\/utils\/io\/fileutils\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-client\/utils\/io\/fileutils\/checksum\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-client\/utils\/log\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nfunc Load() ([]Dependency, error) {\n\tgoPath, err := getGOPATH()\n\tif err != nil {\n\t\treturn nil, errorutils.CheckError(err)\n\t}\n\tcachePath := filepath.Join(goPath, \"src\", \"v\", \"cache\")\n\treturn getDependencies(cachePath)\n}\n\n\/\/ Represent vgo dependency project.\n\/\/ Includes publishing capabilities and build info dependencies.\ntype Dependency struct {\n\tbuildInfoDependencies []buildinfo.Dependency\n\tid                    string\n\tmodContent            []byte\n\tzipPath               string\n\tversion               string\n}\n\nfunc (dependency *Dependency) GetId() string {\n\treturn dependency.id\n}\n\nfunc (dependency *Dependency) Publish(targetRepo string, details *config.ArtifactoryDetails) error {\n\tlog.Info(\"Publishing:\", dependency.id, \"to\", targetRepo)\n\tservicesManager, err := utils.CreateServiceManager(details, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparams := &vgo.VgoParamsImpl{}\n\tparams.ZipPath = dependency.zipPath\n\tparams.ModContent = dependency.modContent\n\tparams.Version = dependency.version\n\tparams.TargetRepo = targetRepo\n\n\treturn servicesManager.PublishVgoProject(params)\n}\n\nfunc (dependency *Dependency) Dependencies() []buildinfo.Dependency {\n\treturn dependency.buildInfoDependencies\n}\n\nfunc getDependencies(cachePath string) ([]Dependency, error) {\n\tvgoCmd, err := golangutil.NewCmd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvgoCmd.Command = []string{\"list\"}\n\tvgoCmd.CommandFlags = []string{\"-m\"}\n\toutput, err := utils.RunCmdOutput(vgoCmd)\n\tif err != nil {\n\t\treturn nil, errorutils.CheckError(err)\n\t}\n\n\tnameVersionMap, err := parseListOutput(output)\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\tdeps := []Dependency{}\n\tfor name, ver := range nameVersionMap {\n\t\tdep, err := createDependency(cachePath, name, ver)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif dep != nil {\n\t\t\tdeps = append(deps, *dep)\n\t\t}\n\t}\n\treturn deps, nil\n}\n\n\/\/ Creates a vgo dependency.\n\/\/ Returns a nil value in case the dependency does not include a zip in the cache.\nfunc createDependency(cachePath, dependencyName, version string) (*Dependency, error) {\n\t\/\/ We first check if the this dependency has a zip binary in the local vgo cache.\n\t\/\/ Core golang dependencies do not have a binary, and we should therefore skip them.\n\tzipPath := filepath.Join(cachePath, dependencyName, \"@v\", version+\".zip\")\n\tfileExists, err := fileutils.IsFileExists(zipPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Zip binary does not exist, so we skip it by returning a nil dependency.\n\tif !fileExists {\n\t\treturn nil, nil\n\t}\n\n\tdep := Dependency{}\n\n\tdep.id = strings.Join([]string{dependencyName, version}, \":\")\n\tdep.version = version\n\tdep.zipPath = zipPath\n\tdep.modContent, err = ioutil.ReadFile(filepath.Join(cachePath, dependencyName, \"@v\", version+\".mod\"))\n\tif err != nil {\n\t\treturn &dep, errorutils.CheckError(err)\n\t}\n\n\t\/\/ Mod file dependency\n\tmodDependency := buildinfo.Dependency{Id: dep.id}\n\tchecksums, err := checksum.Calc(bytes.NewBuffer(dep.modContent))\n\tif err != nil {\n\t\treturn &dep, err\n\t}\n\tmodDependency.Checksum = &buildinfo.Checksum{Sha1: checksums[checksum.SHA1], Md5: checksums[checksum.MD5]}\n\n\t\/\/ Zip file dependency\n\tzipDependency := buildinfo.Dependency{Id: dep.id}\n\tfileDetails, err := fileutils.GetFileDetails(dep.zipPath)\n\tif err != nil {\n\t\treturn &dep, err\n\t}\n\tzipDependency.Checksum = &buildinfo.Checksum{Sha1: fileDetails.Checksum.Sha1, Md5: fileDetails.Checksum.Md5}\n\n\tdep.buildInfoDependencies = append(dep.buildInfoDependencies, modDependency, zipDependency)\n\treturn &dep, nil\n}\n\nfunc parseListOutput(content []byte) (map[string]string, error) {\n\tdepRegexp, err := regexp.Compile(\"(\\\\S+)\\\\s+(\\\\S+)\")\n\tif err != nil {\n\t\treturn nil, errorutils.CheckError(err)\n\t}\n\n\tdepMap := map[string]string{}\n\tlines := bytes.Split(content, []byte(\"\\n\"))\n\tfor i := 2; i < len(lines); i++ {\n\t\tdependency := depRegexp.FindStringSubmatch(string(lines[i]))\n\t\tif len(dependency) == 3 {\n\t\t\tdepMap[dependency[1]] = dependency[2]\n\t\t}\n\t}\n\treturn depMap, nil\n}\n\nfunc getGOPATH() (string, error) {\n\tvgoCmd, err := golangutil.NewCmd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvgoCmd.Command = []string{\"env\", \"GOPATH\"}\n\toutput, err := utils.RunCmdOutput(vgoCmd)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not find GOPATH env: %s\", err.Error())\n\t}\n\treturn strings.TrimSpace(string(output)), nil\n}\n<commit_msg>\"jfrog rt go-publish\" fix - Skip publishing dependencies which do not have a zip binary.<commit_after>package dependencies\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-cli\/artifactory\/utils\"\n\tgolangutil \"github.com\/jfrog\/jfrog-cli-go\/jfrog-cli\/artifactory\/utils\/golang\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-cli\/utils\/config\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-client\/artifactory\/buildinfo\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-client\/artifactory\/services\/vgo\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-client\/utils\/errorutils\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-client\/utils\/io\/fileutils\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-client\/utils\/io\/fileutils\/checksum\"\n\t\"github.com\/jfrog\/jfrog-cli-go\/jfrog-client\/utils\/log\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nfunc Load() ([]Dependency, error) {\n\tgoPath, err := getGOPATH()\n\tif err != nil {\n\t\treturn nil, errorutils.CheckError(err)\n\t}\n\tcachePath := filepath.Join(goPath, \"src\", \"v\", \"cache\")\n\treturn getDependencies(cachePath)\n}\n\n\/\/ Represent vgo dependency project.\n\/\/ Includes publishing capabilities and build info dependencies.\ntype Dependency struct {\n\tbuildInfoDependencies []buildinfo.Dependency\n\tid                    string\n\tmodContent            []byte\n\tzipPath               string\n\tversion               string\n}\n\nfunc (dependency *Dependency) GetId() string {\n\treturn dependency.id\n}\n\nfunc (dependency *Dependency) Publish(targetRepo string, details *config.ArtifactoryDetails) error {\n\tlog.Info(\"Publishing:\", dependency.id, \"to\", targetRepo)\n\tservicesManager, err := utils.CreateServiceManager(details, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparams := &vgo.VgoParamsImpl{}\n\tparams.ZipPath = dependency.zipPath\n\tparams.ModContent = dependency.modContent\n\tparams.Version = dependency.version\n\tparams.TargetRepo = targetRepo\n\n\treturn servicesManager.PublishVgoProject(params)\n}\n\nfunc (dependency *Dependency) Dependencies() []buildinfo.Dependency {\n\treturn dependency.buildInfoDependencies\n}\n\nfunc getDependencies(cachePath string) ([]Dependency, error) {\n\tvgoCmd, err := golangutil.NewCmd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvgoCmd.Command = []string{\"list\"}\n\tvgoCmd.CommandFlags = []string{\"-m\"}\n\toutput, err := utils.RunCmdOutput(vgoCmd)\n\tif err != nil {\n\t\treturn nil, errorutils.CheckError(err)\n\t}\n\n\tnameVersionMap, err := parseListOutput(output)\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\tdeps := []Dependency{}\n\tfor name, ver := range nameVersionMap {\n\t\tdep, err := createDependency(cachePath, name, ver)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif dep != nil {\n\t\t\tdeps = append(deps, *dep)\n\t\t}\n\t}\n\treturn deps, nil\n}\n\n\/\/ Creates a vgo dependency.\n\/\/ Returns a nil value in case the dependency does not include a zip in the cache.\nfunc createDependency(cachePath, dependencyName, version string) (*Dependency, error) {\n\t\/\/ We first check if the this dependency has a zip binary in the local vgo cache.\n\t\/\/ If it does not, nil is returned. This seems to be a bug in vgo.\n\tzipPath := filepath.Join(cachePath, dependencyName, \"@v\", version+\".zip\")\n\tfileExists, err := fileutils.IsFileExists(zipPath)\n\tif err != nil {\n\t\tlog.Warn(fmt.Sprintf(\"Could not find zip binary for dependency '%s' at %s.\", dependencyName, zipPath))\n\t\treturn nil, err\n\t}\n\t\/\/ Zip binary does not exist, so we skip it by returning a nil dependency.\n\tif !fileExists {\n\t\treturn nil, nil\n\t}\n\n\tdep := Dependency{}\n\n\tdep.id = strings.Join([]string{dependencyName, version}, \":\")\n\tdep.version = version\n\tdep.zipPath = zipPath\n\tdep.modContent, err = ioutil.ReadFile(filepath.Join(cachePath, dependencyName, \"@v\", version+\".mod\"))\n\tif err != nil {\n\t\treturn &dep, errorutils.CheckError(err)\n\t}\n\n\t\/\/ Mod file dependency\n\tmodDependency := buildinfo.Dependency{Id: dep.id}\n\tchecksums, err := checksum.Calc(bytes.NewBuffer(dep.modContent))\n\tif err != nil {\n\t\treturn &dep, err\n\t}\n\tmodDependency.Checksum = &buildinfo.Checksum{Sha1: checksums[checksum.SHA1], Md5: checksums[checksum.MD5]}\n\n\t\/\/ Zip file dependency\n\tzipDependency := buildinfo.Dependency{Id: dep.id}\n\tfileDetails, err := fileutils.GetFileDetails(dep.zipPath)\n\tif err != nil {\n\t\treturn &dep, err\n\t}\n\tzipDependency.Checksum = &buildinfo.Checksum{Sha1: fileDetails.Checksum.Sha1, Md5: fileDetails.Checksum.Md5}\n\n\tdep.buildInfoDependencies = append(dep.buildInfoDependencies, modDependency, zipDependency)\n\treturn &dep, nil\n}\n\nfunc parseListOutput(content []byte) (map[string]string, error) {\n\tdepRegexp, err := regexp.Compile(\"(\\\\S+)\\\\s+(\\\\S+)\")\n\tif err != nil {\n\t\treturn nil, errorutils.CheckError(err)\n\t}\n\n\tdepMap := map[string]string{}\n\tlines := bytes.Split(content, []byte(\"\\n\"))\n\tfor i := 2; i < len(lines); i++ {\n\t\tdependency := depRegexp.FindStringSubmatch(string(lines[i]))\n\t\tif len(dependency) == 3 {\n\t\t\tdepMap[dependency[1]] = dependency[2]\n\t\t}\n\t}\n\treturn depMap, nil\n}\n\nfunc getGOPATH() (string, error) {\n\tvgoCmd, err := golangutil.NewCmd()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tvgoCmd.Command = []string{\"env\", \"GOPATH\"}\n\toutput, err := utils.RunCmdOutput(vgoCmd)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not find GOPATH env: %s\", err.Error())\n\t}\n\treturn strings.TrimSpace(string(output)), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"koding\/kite-handler\/command\"\n\t\"koding\/kite-handler\/fs\"\n\t\"koding\/kite-handler\/terminal\"\n\t\"koding\/kites\/klient\/collaboration\"\n\t\"koding\/kites\/klient\/protocol\"\n\t\"koding\/kites\/klient\/usage\"\n\n\t\"github.com\/koding\/kite\"\n\t\"github.com\/koding\/kite\/config\"\n)\n\nvar (\n\tflagIP          = flag.String(\"ip\", \"\", \"Change public ip\")\n\tflagPort        = flag.Int(\"port\", 56789, \"Change running port\")\n\tflagVersion     = flag.Bool(\"version\", false, \"Show version and exit\")\n\tflagEnvironment = flag.String(\"env\", protocol.Environment, \"Change environment\")\n\tflagRegion      = flag.String(\"region\", protocol.Region, \"Change region\")\n\tflagRegisterURL = flag.String(\"register-url\", \"\", \"Change register URL to kontrol\")\n\tflagDebug       = flag.Bool(\"debug\", false, \"Debug mode\")\n\n\t\/\/ update paramters\n\tflagUpdateInterval = flag.Duration(\"update-interval\", time.Minute*5,\n\t\t\"Change interval for checking for new updates\")\n\tflagUpdateURL = flag.String(\"update-url\",\n\t\t\"https:\/\/s3.amazonaws.com\/koding-klient\/\"+protocol.Environment+\"\/latest-version.txt\",\n\t\t\"Change update endpoint for latest version\")\n\n\tVERSION = protocol.Version\n\tNAME    = protocol.Name\n\n\t\/\/ this is our main reference to count and measure metrics for the klient\n\t\/\/ we count only those methods, please add\/remove methods here that will\n\t\/\/ reset the timer of a klient.\n\tusg = usage.NewUsage(map[string]bool{\n\t\t\"fs.readDirectory\":    true,\n\t\t\"fs.glob\":             true,\n\t\t\"fs.readFile\":         true,\n\t\t\"fs.writeFile\":        true,\n\t\t\"fs.uniquePath\":       true,\n\t\t\"fs.getInfo\":          true,\n\t\t\"fs.setPermissions\":   true,\n\t\t\"fs.remove\":           true,\n\t\t\"fs.rename\":           true,\n\t\t\"fs.createDirectory\":  true,\n\t\t\"fs.move\":             true,\n\t\t\"fs.copy\":             true,\n\t\t\"webterm.getSessions\": true,\n\t\t\"webterm.connect\":     true,\n\t\t\"webterm.killSession\": true,\n\t\t\"exec\":                true,\n\t\t\"klient.share\":        true,\n\t\t\"klient.unshare\":      true,\n\t\t\"klient.shared\":       true,\n\t})\n\n\t\/\/ this is used to allow other users to call any klient method.\n\tcollab = collaboration.New()\n\n\t\/\/ we also could use an atomic boolean this is simple for now.\n\tupdating   = false\n\tupdatingMu sync.Mutex \/\/ protects updating\n)\n\nfunc main() {\n\tflag.Parse()\n\tif *flagVersion {\n\t\tfmt.Println(VERSION)\n\t\tos.Exit(0)\n\t}\n\n\tk := newKite()\n\n\t\/\/ Close the klient.db in any case. Corrupt db would be catastrophic\n\tdefer collab.Close()\n\n\tk.Log.Info(\"Running as version %s\", VERSION)\n\tk.Run()\n}\n\nfunc newKite() *kite.Kite {\n\tk := kite.New(NAME, VERSION)\n\n\tif *flagDebug {\n\t\tk.SetLogLevel(kite.DEBUG)\n\t}\n\n\tconf := config.MustGet()\n\tk.Config = conf\n\tk.Config.Port = *flagPort\n\tk.Config.Environment = *flagEnvironment\n\tk.Config.Region = *flagRegion\n\tk.Id = conf.Id \/\/ always boot up with the same id in the kite.key\n\n\t\/\/ FIXME: It's ugly I know. It's a fix for Koding local development and is\n\t\/\/ needed\n\tif !strings.Contains(k.Config.KontrolURL, \"ngrok\") {\n\t\t\/\/ override current kontrolURL so it talks to port 3000, this is needed\n\t\t\/\/ because ELB can forward requests based on ports. The port 80 and 443 are\n\t\t\/\/ HTTP\/HTTPS only so our kite can't connect it (we use websocket). However\n\t\t\/\/ We have a TCP proxy at 3000 which allows us to connect via WebSocket.\n\t\tu, _ := url.Parse(k.Config.KontrolURL)\n\n\t\thost := u.Host\n\t\tif HasPort(u.Host) {\n\t\t\thost, _, _ = net.SplitHostPort(u.Host)\n\t\t}\n\n\t\tu.Host = AddPort(host, \"3000\")\n\t\tu.Scheme = \"http\"\n\t\tk.Config.KontrolURL = u.String()\n\t}\n\n\tif *flagUpdateInterval < time.Minute {\n\t\tk.Log.Warning(\"Update interval can't be less than one minute. Setting to one minute.\")\n\t\t*flagUpdateInterval = time.Minute\n\t}\n\n\tupdater := &Updater{\n\t\tEndpoint: *flagUpdateURL,\n\t\tInterval: *flagUpdateInterval,\n\t\tLog:      k.Log,\n\t}\n\n\t\/\/ before we register check for latest update and re-update itself before\n\t\/\/ we continue\n\tk.Log.Info(\"Checking for new updates\")\n\tif err := updater.checkAndUpdate(); err != nil {\n\t\tk.Log.Warning(\"Self-update: %s\", err)\n\t}\n\n\tgo updater.Run()\n\n\tuserIn := func(user string, users ...string) bool {\n\t\tfor _, u := range users {\n\t\t\tif u == user {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t\/\/ don't pass any request if the caller is outside of our scope.\n\t\/\/ don't allow anyone to call a method if we are during an update.\n\tk.PreHandleFunc(func(r *kite.Request) (interface{}, error) {\n\t\t\/\/ only authenticated methods have correct username. For example\n\t\t\/\/ kite.ping has authentication disabled so username can be empty.\n\t\tif r.Auth != nil {\n\t\t\tk.Log.Info(\"Kite '%s\/%s\/%s' called method: '%s'\",\n\t\t\t\tr.Username, r.Client.Environment, r.Client.Name, r.Method)\n\n\t\t\t\/\/ Allow these users by default\n\t\t\tallowedUsers := []string{k.Config.Username, \"koding\"}\n\n\t\t\t\/\/ Allow collaboration users as well\n\t\t\tsharedUsers, err := collab.GetAll()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Can't read shared users from the storage. Err: %v\", err)\n\t\t\t}\n\t\t\tallowedUsers = append(allowedUsers, sharedUsers...)\n\n\t\t\tif !userIn(r.Username, allowedUsers...) {\n\t\t\t\treturn nil, fmt.Errorf(\"User '%s' is not allowed to make a call to us.\", r.Username)\n\t\t\t}\n\t\t}\n\n\t\tupdatingMu.Lock()\n\t\tdefer updatingMu.Unlock()\n\n\t\tif updating {\n\t\t\treturn nil, errors.New(\"Updating klient. Can't accept any method.\")\n\t\t}\n\n\t\treturn true, nil\n\t})\n\n\t\/\/ Unshare collab users if the klient owner disconnects\n\tk.OnDisconnect(func(c *kite.Client) {\n\t\tk.Log.Info(\"Kite '%s\/%s\/%s' is disconnected\", c.Username, c.Environment, c.Name)\n\t\tif c.Username == k.Config.Username {\n\t\t\tsharedUsers, err := collab.GetAll()\n\t\t\tif err != nil {\n\t\t\t\tk.Log.Warning(\"Couldn't unshare users: '%s'\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tk.Log.Info(\"Unsharing users '%s'\", sharedUsers)\n\t\t\tfor _, user := range sharedUsers {\n\t\t\t\tif err := collab.Delete(user); err != nil {\n\t\t\t\t\tk.Log.Warning(\"Couldn't delete user from storage: '%s'\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n\t\/\/ Metrics, is used by Kloud to get usage so Kloud can stop free VMs\n\tk.PreHandleFunc(usg.Counter) \/\/ we measure every incoming request\n\tk.HandleFunc(\"klient.usage\", usg.Current)\n\n\t\/\/ Collaboration, is used by our Koding.com browser client\n\tk.HandleFunc(\"klient.share\", collab.Share)\n\tk.HandleFunc(\"klient.unshare\", collab.Unshare)\n\tk.HandleFunc(\"klient.shared\", collab.Shared)\n\n\t\/\/ Filesystem\n\tk.HandleFunc(\"fs.readDirectory\", fs.ReadDirectory)\n\tk.HandleFunc(\"fs.glob\", fs.Glob)\n\tk.HandleFunc(\"fs.readFile\", fs.ReadFile)\n\tk.HandleFunc(\"fs.writeFile\", fs.WriteFile)\n\tk.HandleFunc(\"fs.uniquePath\", fs.UniquePath)\n\tk.HandleFunc(\"fs.getInfo\", fs.GetInfo)\n\tk.HandleFunc(\"fs.setPermissions\", fs.SetPermissions)\n\tk.HandleFunc(\"fs.remove\", fs.Remove)\n\tk.HandleFunc(\"fs.rename\", fs.Rename)\n\tk.HandleFunc(\"fs.createDirectory\", fs.CreateDirectory)\n\tk.HandleFunc(\"fs.move\", fs.Move)\n\tk.HandleFunc(\"fs.copy\", fs.Copy)\n\n\t\/\/ Terminal\n\tterminal.ResetFunc = usg.Reset\n\tk.HandleFunc(\"webterm.getSessions\", terminal.GetSessions)\n\tk.HandleFunc(\"webterm.connect\", terminal.Connect)\n\tk.HandleFunc(\"webterm.killSession\", terminal.KillSession)\n\n\t\/\/ Execution\n\tk.HandleFunc(\"exec\", command.Exec)\n\n\tif err := register(k); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn k\n}\n\n\/\/ Given a string of the form \"host\", \"host:port\", or \"[ipv6::address]:port\",\n\/\/ return true if the string includes a port.\nfunc HasPort(s string) bool { return strings.LastIndex(s, \":\") > strings.LastIndex(s, \"]\") }\n\n\/\/ Given a string of the form \"host\", \"port\", returns \"host:port\"\nfunc AddPort(host, port string) string {\n\tif ok := HasPort(host); ok {\n\t\treturn host\n\t}\n\n\treturn host + \":\" + port\n}\n<commit_msg>kite-handler\/terminal: make Terminal Handler a struct to modify certain things<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"koding\/kite-handler\/command\"\n\t\"koding\/kite-handler\/fs\"\n\t\"koding\/kite-handler\/terminal\"\n\t\"koding\/kites\/klient\/collaboration\"\n\t\"koding\/kites\/klient\/protocol\"\n\t\"koding\/kites\/klient\/usage\"\n\n\t\"github.com\/koding\/kite\"\n\t\"github.com\/koding\/kite\/config\"\n)\n\nvar (\n\tflagIP          = flag.String(\"ip\", \"\", \"Change public ip\")\n\tflagPort        = flag.Int(\"port\", 56789, \"Change running port\")\n\tflagVersion     = flag.Bool(\"version\", false, \"Show version and exit\")\n\tflagEnvironment = flag.String(\"env\", protocol.Environment, \"Change environment\")\n\tflagRegion      = flag.String(\"region\", protocol.Region, \"Change region\")\n\tflagRegisterURL = flag.String(\"register-url\", \"\", \"Change register URL to kontrol\")\n\tflagDebug       = flag.Bool(\"debug\", false, \"Debug mode\")\n\n\t\/\/ update paramters\n\tflagUpdateInterval = flag.Duration(\"update-interval\", time.Minute*5,\n\t\t\"Change interval for checking for new updates\")\n\tflagUpdateURL = flag.String(\"update-url\",\n\t\t\"https:\/\/s3.amazonaws.com\/koding-klient\/\"+protocol.Environment+\"\/latest-version.txt\",\n\t\t\"Change update endpoint for latest version\")\n\n\tVERSION = protocol.Version\n\tNAME    = protocol.Name\n\n\t\/\/ this is our main reference to count and measure metrics for the klient\n\t\/\/ we count only those methods, please add\/remove methods here that will\n\t\/\/ reset the timer of a klient.\n\tusg = usage.NewUsage(map[string]bool{\n\t\t\"fs.readDirectory\":    true,\n\t\t\"fs.glob\":             true,\n\t\t\"fs.readFile\":         true,\n\t\t\"fs.writeFile\":        true,\n\t\t\"fs.uniquePath\":       true,\n\t\t\"fs.getInfo\":          true,\n\t\t\"fs.setPermissions\":   true,\n\t\t\"fs.remove\":           true,\n\t\t\"fs.rename\":           true,\n\t\t\"fs.createDirectory\":  true,\n\t\t\"fs.move\":             true,\n\t\t\"fs.copy\":             true,\n\t\t\"webterm.getSessions\": true,\n\t\t\"webterm.connect\":     true,\n\t\t\"webterm.killSession\": true,\n\t\t\"exec\":                true,\n\t\t\"klient.share\":        true,\n\t\t\"klient.unshare\":      true,\n\t\t\"klient.shared\":       true,\n\t})\n\n\t\/\/ this is used to allow other users to call any klient method.\n\tcollab = collaboration.New()\n\n\t\/\/ we also could use an atomic boolean this is simple for now.\n\tupdating   = false\n\tupdatingMu sync.Mutex \/\/ protects updating\n)\n\nfunc main() {\n\tflag.Parse()\n\tif *flagVersion {\n\t\tfmt.Println(VERSION)\n\t\tos.Exit(0)\n\t}\n\n\tk := newKite()\n\n\t\/\/ Close the klient.db in any case. Corrupt db would be catastrophic\n\tdefer collab.Close()\n\n\tk.Log.Info(\"Running as version %s\", VERSION)\n\tk.Run()\n}\n\nfunc newKite() *kite.Kite {\n\tk := kite.New(NAME, VERSION)\n\n\tif *flagDebug {\n\t\tk.SetLogLevel(kite.DEBUG)\n\t}\n\n\tconf := config.MustGet()\n\tk.Config = conf\n\tk.Config.Port = *flagPort\n\tk.Config.Environment = *flagEnvironment\n\tk.Config.Region = *flagRegion\n\tk.Id = conf.Id \/\/ always boot up with the same id in the kite.key\n\n\t\/\/ FIXME: It's ugly I know. It's a fix for Koding local development and is\n\t\/\/ needed\n\tif !strings.Contains(k.Config.KontrolURL, \"ngrok\") {\n\t\t\/\/ override current kontrolURL so it talks to port 3000, this is needed\n\t\t\/\/ because ELB can forward requests based on ports. The port 80 and 443 are\n\t\t\/\/ HTTP\/HTTPS only so our kite can't connect it (we use websocket). However\n\t\t\/\/ We have a TCP proxy at 3000 which allows us to connect via WebSocket.\n\t\tu, _ := url.Parse(k.Config.KontrolURL)\n\n\t\thost := u.Host\n\t\tif HasPort(u.Host) {\n\t\t\thost, _, _ = net.SplitHostPort(u.Host)\n\t\t}\n\n\t\tu.Host = AddPort(host, \"3000\")\n\t\tu.Scheme = \"http\"\n\t\tk.Config.KontrolURL = u.String()\n\t}\n\n\tif *flagUpdateInterval < time.Minute {\n\t\tk.Log.Warning(\"Update interval can't be less than one minute. Setting to one minute.\")\n\t\t*flagUpdateInterval = time.Minute\n\t}\n\n\tupdater := &Updater{\n\t\tEndpoint: *flagUpdateURL,\n\t\tInterval: *flagUpdateInterval,\n\t\tLog:      k.Log,\n\t}\n\n\t\/\/ before we register check for latest update and re-update itself before\n\t\/\/ we continue\n\tk.Log.Info(\"Checking for new updates\")\n\tif err := updater.checkAndUpdate(); err != nil {\n\t\tk.Log.Warning(\"Self-update: %s\", err)\n\t}\n\n\tgo updater.Run()\n\n\tuserIn := func(user string, users ...string) bool {\n\t\tfor _, u := range users {\n\t\t\tif u == user {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t\/\/ don't pass any request if the caller is outside of our scope.\n\t\/\/ don't allow anyone to call a method if we are during an update.\n\tk.PreHandleFunc(func(r *kite.Request) (interface{}, error) {\n\t\t\/\/ only authenticated methods have correct username. For example\n\t\t\/\/ kite.ping has authentication disabled so username can be empty.\n\t\tif r.Auth != nil {\n\t\t\tk.Log.Info(\"Kite '%s\/%s\/%s' called method: '%s'\",\n\t\t\t\tr.Username, r.Client.Environment, r.Client.Name, r.Method)\n\n\t\t\t\/\/ Allow these users by default\n\t\t\tallowedUsers := []string{k.Config.Username, \"koding\"}\n\n\t\t\t\/\/ Allow collaboration users as well\n\t\t\tsharedUsers, err := collab.GetAll()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Can't read shared users from the storage. Err: %v\", err)\n\t\t\t}\n\t\t\tallowedUsers = append(allowedUsers, sharedUsers...)\n\n\t\t\tif !userIn(r.Username, allowedUsers...) {\n\t\t\t\treturn nil, fmt.Errorf(\"User '%s' is not allowed to make a call to us.\", r.Username)\n\t\t\t}\n\t\t}\n\n\t\tupdatingMu.Lock()\n\t\tdefer updatingMu.Unlock()\n\n\t\tif updating {\n\t\t\treturn nil, errors.New(\"Updating klient. Can't accept any method.\")\n\t\t}\n\n\t\treturn true, nil\n\t})\n\n\t\/\/ Unshare collab users if the klient owner disconnects\n\tk.OnDisconnect(func(c *kite.Client) {\n\t\tk.Log.Info(\"Kite '%s\/%s\/%s' is disconnected\", c.Username, c.Environment, c.Name)\n\t\tif c.Username == k.Config.Username {\n\t\t\tsharedUsers, err := collab.GetAll()\n\t\t\tif err != nil {\n\t\t\t\tk.Log.Warning(\"Couldn't unshare users: '%s'\", err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tk.Log.Info(\"Unsharing users '%s'\", sharedUsers)\n\t\t\tfor _, user := range sharedUsers {\n\t\t\t\tif err := collab.Delete(user); err != nil {\n\t\t\t\t\tk.Log.Warning(\"Couldn't delete user from storage: '%s'\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n\t\/\/ Metrics, is used by Kloud to get usage so Kloud can stop free VMs\n\tk.PreHandleFunc(usg.Counter) \/\/ we measure every incoming request\n\tk.HandleFunc(\"klient.usage\", usg.Current)\n\n\t\/\/ Collaboration, is used by our Koding.com browser client\n\tk.HandleFunc(\"klient.share\", collab.Share)\n\tk.HandleFunc(\"klient.unshare\", collab.Unshare)\n\tk.HandleFunc(\"klient.shared\", collab.Shared)\n\n\t\/\/ Filesystem\n\tk.HandleFunc(\"fs.readDirectory\", fs.ReadDirectory)\n\tk.HandleFunc(\"fs.glob\", fs.Glob)\n\tk.HandleFunc(\"fs.readFile\", fs.ReadFile)\n\tk.HandleFunc(\"fs.writeFile\", fs.WriteFile)\n\tk.HandleFunc(\"fs.uniquePath\", fs.UniquePath)\n\tk.HandleFunc(\"fs.getInfo\", fs.GetInfo)\n\tk.HandleFunc(\"fs.setPermissions\", fs.SetPermissions)\n\tk.HandleFunc(\"fs.remove\", fs.Remove)\n\tk.HandleFunc(\"fs.rename\", fs.Rename)\n\tk.HandleFunc(\"fs.createDirectory\", fs.CreateDirectory)\n\tk.HandleFunc(\"fs.move\", fs.Move)\n\tk.HandleFunc(\"fs.copy\", fs.Copy)\n\n\t\/\/ Terminal\n\tterm := &terminal.Terminal{\n\t\tInputHook: usg.Reset,\n\t}\n\n\tk.HandleFunc(\"webterm.getSessions\", term.GetSessions)\n\tk.HandleFunc(\"webterm.connect\", term.Connect)\n\tk.HandleFunc(\"webterm.killSession\", term.KillSession)\n\n\t\/\/ Execution\n\tk.HandleFunc(\"exec\", command.Exec)\n\n\tif err := register(k); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn k\n}\n\n\/\/ Given a string of the form \"host\", \"host:port\", or \"[ipv6::address]:port\",\n\/\/ return true if the string includes a port.\nfunc HasPort(s string) bool { return strings.LastIndex(s, \":\") > strings.LastIndex(s, \"]\") }\n\n\/\/ Given a string of the form \"host\", \"port\", returns \"host:port\"\nfunc AddPort(host, port string) string {\n\tif ok := HasPort(host); ok {\n\t\treturn host\n\t}\n\n\treturn host + \":\" + port\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/grokify\/gotilla\/fmt\/fmtutil\"\n\n\t\"github.com\/grokify\/chathooks\/src\/adapters\"\n\t\"github.com\/grokify\/chathooks\/src\/config\"\n\t\"github.com\/grokify\/chathooks\/src\/util\"\n\tcc \"github.com\/grokify\/commonchat\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/valyala\/fasthttp\"\n\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/aha\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/appsignal\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/apteligent\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/circleci\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/codeship\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/confluence\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/datadog\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/deskdotcom\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/enchant\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/gosquared\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/gosquared2\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/heroku\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/librato\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/magnumci\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/marketo\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/opsgenie\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/papertrail\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/pingdom\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/raygun\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/runscope\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/semaphore\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/statuspage\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/travisci\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/userlike\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/victorops\"\n)\n\nconst (\n\tGLIP_WEBHOOK_ENV  = \"GLIP_WEBHOOK\"\n\tSLACK_WEBHOOK_ENV = \"SLACK_WEBHOOK\"\n)\n\ntype Sender struct {\n\tAdapter adapters.Adapter\n}\n\nfunc (sender *Sender) SendCcMessage(ccMsg cc.Message, err error) {\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Bad Test Message: %v\\n\", err))\n\t}\n\tvar resMsg interface{}\n\treq, resp, err := sender.Adapter.SendMessage(ccMsg, &resMsg)\n\tfmt.Printf(\"RESPONSE_STATUS_CODE [%v]\\n\", resp.StatusCode())\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR [%v]\\n\", err)\n\t}\n\tfasthttp.ReleaseRequest(req)\n\tfasthttp.ReleaseResponse(resp)\n}\n\nfunc main() {\n\tlog.SetLevel(log.DebugLevel)\n\n\tguidPointer := flag.String(\"guid\", \"\", \"Glip webhook GUID or URL\")\n\texamplePointer := flag.String(\"example\", \"\", \"Example message type\")\n\tadapterType := flag.String(\"adapter\", \"\", \"Adapter\")\n\n\tflag.Parse()\n\twebhookURLOrUID := strings.TrimSpace(*guidPointer)\n\texample := strings.ToLower(strings.TrimSpace(*examplePointer))\n\n\tfmt.Printf(\"LENGUID[%v]\\n\", len(webhookURLOrUID))\n\tfmt.Printf(\"GUID [%v]\\n\", webhookURLOrUID)\n\tfmt.Printf(\"EXAMPLE [%v]\\n\", example)\n\n\tif len(example) < 1 {\n\t\tpanic(\"Usage: send_example.go -hook=<GUID> -adapter=glip -example=raygun\")\n\t}\n\n\tcfg := config.Configuration{\n\t\tIconBaseURL:    \"https:\/\/grokify.github.io\/chathooks\/icons\/\",\n\t\tLogrusLogLevel: log.DebugLevel}\n\n\tsender := Sender{}\n\tif *adapterType == \"glip\" {\n\t\tif len(webhookURLOrUID) < 1 {\n\t\t\twebhookURLOrUID = os.Getenv(GLIP_WEBHOOK_ENV)\n\t\t\tfmt.Printf(\"GLIP_GUID_ENV [%v]\\n\", webhookURLOrUID)\n\t\t}\n\t\tadapter, err := adapters.NewGlipAdapter(webhookURLOrUID)\n\t\tif err != nil {\n\t\t\tpanic(\"Incorrect Webhook GUID or URL\")\n\t\t}\n\t\tsender.Adapter = adapter\n\t} else if *adapterType == \"slack\" {\n\t\tif len(webhookURLOrUID) < 1 {\n\t\t\twebhookURLOrUID = os.Getenv(SLACK_WEBHOOK_ENV)\n\t\t\tfmt.Printf(\"SLACK_GUID_ENV [%v]\\n\", webhookURLOrUID)\n\t\t}\n\t\tadapter, err := adapters.NewSlackAdapter(webhookURLOrUID)\n\t\tif err != nil {\n\t\t\tpanic(\"Incorrect Webhook GUID or URL\")\n\t\t}\n\t\tsender.Adapter = adapter\n\t} else {\n\t\tpanic(\"Invalid Adapter\")\n\t}\n\n\texampleData, err := util.NewExampleData()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Invalid Example Data: %v\\n\", err))\n\t}\n\tfmtutil.PrintJSON(exampleData)\n\n\tswitch example {\n\tcase \"aha\":\n\t\tsource := exampleData.Data[aha.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(aha.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"appsignal\":\n\t\tsource := exampleData.Data[appsignal.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(appsignal.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"apteligent\":\n\t\tsource := exampleData.Data[apteligent.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(apteligent.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"circleci\":\n\t\tsender.SendCcMessage(circleci.ExampleMessage(cfg, exampleData))\n\tcase \"codeship\":\n\t\tsender.SendCcMessage(codeship.ExampleMessage(cfg, exampleData))\n\tcase \"confluence\":\n\t\tsource := exampleData.Data[confluence.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(confluence.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"datadog\":\n\t\tsender.SendCcMessage(datadog.ExampleMessage(cfg, exampleData))\n\tcase \"deskdotcom\":\n\t\tsource := exampleData.Data[deskdotcom.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(deskdotcom.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"enchant\":\n\t\tsender.SendCcMessage(enchant.ExampleMessage(cfg, exampleData))\n\tcase \"gosquared\":\n\t\tsource := exampleData.Data[gosquared.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(gosquared.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"gosquared2\":\n\t\tsource := exampleData.Data[gosquared.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(gosquared2.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"heroku\":\n\t\tsender.SendCcMessage(heroku.ExampleMessage(cfg, exampleData))\n\tcase \"librato\":\n\t\tsource := exampleData.Data[librato.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(librato.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"magnumci\":\n\t\tsender.SendCcMessage(magnumci.ExampleMessage(cfg, exampleData))\n\tcase \"marketo\":\n\t\tsource := exampleData.Data[marketo.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(marketo.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"opsgenie\":\n\t\tsource := exampleData.Data[opsgenie.HandlerKey]\n\t\tfor i, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(opsgenie.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t\tif i == 8 {\n\t\t\t\ttime.Sleep(2000 * time.Millisecond)\n\t\t\t}\n\t\t}\n\tcase \"papertrail\":\n\t\tsource := exampleData.Data[papertrail.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(papertrail.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"pingdom\":\n\t\tsource := exampleData.Data[pingdom.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(pingdom.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"raygun\":\n\t\tsender.SendCcMessage(raygun.ExampleMessage(cfg, exampleData))\n\tcase \"runscope\":\n\t\tsender.SendCcMessage(runscope.ExampleMessage(cfg, exampleData))\n\tcase \"semaphore\":\n\t\tsource := exampleData.Data[semaphore.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(semaphore.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"statuspage\":\n\t\tsource := exampleData.Data[statuspage.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(statuspage.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"travisci\":\n\t\tsender.SendCcMessage(travisci.ExampleMessage(cfg, exampleData))\n\tcase \"userlike\":\n\t\tsource := exampleData.Data[userlike.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(userlike.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"victorops\":\n\t\tsender.SendCcMessage(victorops.ExampleMessage(cfg, exampleData))\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Unknown webhook source %v\\n\", example))\n\t}\n}\n<commit_msg>update examples\/local_send<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/grokify\/gotilla\/fmt\/fmtutil\"\n\n\t\/\/\"github.com\/grokify\/chathooks\/src\/adapters\"\n\t\"github.com\/grokify\/chathooks\/src\/config\"\n\t\"github.com\/grokify\/chathooks\/src\/util\"\n\tcc \"github.com\/grokify\/commonchat\"\n\tccglip \"github.com\/grokify\/commonchat\/glip\"\n\tccslack \"github.com\/grokify\/commonchat\/slack\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/valyala\/fasthttp\"\n\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/aha\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/appsignal\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/apteligent\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/circleci\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/codeship\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/confluence\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/datadog\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/deskdotcom\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/enchant\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/gosquared\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/gosquared2\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/heroku\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/librato\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/magnumci\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/marketo\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/opsgenie\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/papertrail\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/pingdom\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/raygun\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/runscope\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/semaphore\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/statuspage\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/travisci\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/userlike\"\n\t\"github.com\/grokify\/chathooks\/src\/handlers\/victorops\"\n)\n\nconst (\n\tGLIP_WEBHOOK_ENV  = \"GLIP_WEBHOOK\"\n\tSLACK_WEBHOOK_ENV = \"SLACK_WEBHOOK\"\n)\n\ntype Sender struct {\n\tAdapter cc.Adapter\n}\n\nfunc (sender *Sender) SendCcMessage(ccMsg cc.Message, err error) {\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Bad Test Message: %v\\n\", err))\n\t}\n\tvar resMsg interface{}\n\treq, resp, err := sender.Adapter.SendMessage(ccMsg, &resMsg)\n\tfmt.Printf(\"RESPONSE_STATUS_CODE [%v]\\n\", resp.StatusCode())\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR [%v]\\n\", err)\n\t}\n\tfasthttp.ReleaseRequest(req)\n\tfasthttp.ReleaseResponse(resp)\n}\n\nfunc main() {\n\tlog.SetLevel(log.DebugLevel)\n\n\tguidPointer := flag.String(\"guid\", \"\", \"Glip webhook GUID or URL\")\n\texamplePointer := flag.String(\"example\", \"\", \"Example message type\")\n\tadapterType := flag.String(\"adapter\", \"\", \"Adapter\")\n\n\tflag.Parse()\n\twebhookURLOrUID := strings.TrimSpace(*guidPointer)\n\texample := strings.ToLower(strings.TrimSpace(*examplePointer))\n\n\tfmt.Printf(\"LENGUID[%v]\\n\", len(webhookURLOrUID))\n\tfmt.Printf(\"GUID [%v]\\n\", webhookURLOrUID)\n\tfmt.Printf(\"EXAMPLE [%v]\\n\", example)\n\n\tif len(example) < 1 {\n\t\tpanic(\"Usage: send_example.go -hook=<GUID> -adapter=glip -example=raygun\")\n\t}\n\n\tcfg := config.Configuration{\n\t\tIconBaseURL:    \"https:\/\/grokify.github.io\/chathooks\/icons\/\",\n\t\tLogrusLogLevel: log.DebugLevel}\n\n\tsender := Sender{}\n\tif *adapterType == \"glip\" {\n\t\tif len(webhookURLOrUID) < 1 {\n\t\t\twebhookURLOrUID = os.Getenv(GLIP_WEBHOOK_ENV)\n\t\t\tfmt.Printf(\"GLIP_GUID_ENV [%v]\\n\", webhookURLOrUID)\n\t\t}\n\t\tadapter, err := ccglip.NewGlipAdapter(webhookURLOrUID)\n\t\tif err != nil {\n\t\t\tpanic(\"Incorrect Webhook GUID or URL\")\n\t\t}\n\t\tsender.Adapter = adapter\n\t} else if *adapterType == \"slack\" {\n\t\tif len(webhookURLOrUID) < 1 {\n\t\t\twebhookURLOrUID = os.Getenv(SLACK_WEBHOOK_ENV)\n\t\t\tfmt.Printf(\"SLACK_GUID_ENV [%v]\\n\", webhookURLOrUID)\n\t\t}\n\t\tadapter, err := ccslack.NewSlackAdapter(webhookURLOrUID)\n\t\tif err != nil {\n\t\t\tpanic(\"Incorrect Webhook GUID or URL\")\n\t\t}\n\t\tsender.Adapter = adapter\n\t} else {\n\t\tpanic(\"Invalid Adapter\")\n\t}\n\n\texampleData, err := util.NewExampleData()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Invalid Example Data: %v\\n\", err))\n\t}\n\tfmtutil.PrintJSON(exampleData)\n\n\tswitch example {\n\tcase \"aha\":\n\t\tsource := exampleData.Data[aha.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(aha.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"appsignal\":\n\t\tsource := exampleData.Data[appsignal.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(appsignal.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"apteligent\":\n\t\tsource := exampleData.Data[apteligent.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(apteligent.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"circleci\":\n\t\tsender.SendCcMessage(circleci.ExampleMessage(cfg, exampleData))\n\tcase \"codeship\":\n\t\tsender.SendCcMessage(codeship.ExampleMessage(cfg, exampleData))\n\tcase \"confluence\":\n\t\tsource := exampleData.Data[confluence.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(confluence.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"datadog\":\n\t\tsender.SendCcMessage(datadog.ExampleMessage(cfg, exampleData))\n\tcase \"deskdotcom\":\n\t\tsource := exampleData.Data[deskdotcom.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(deskdotcom.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"enchant\":\n\t\tsender.SendCcMessage(enchant.ExampleMessage(cfg, exampleData))\n\tcase \"gosquared\":\n\t\tsource := exampleData.Data[gosquared.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(gosquared.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"gosquared2\":\n\t\tsource := exampleData.Data[gosquared.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(gosquared2.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"heroku\":\n\t\tsender.SendCcMessage(heroku.ExampleMessage(cfg, exampleData))\n\tcase \"librato\":\n\t\tsource := exampleData.Data[librato.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(librato.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"magnumci\":\n\t\tsender.SendCcMessage(magnumci.ExampleMessage(cfg, exampleData))\n\tcase \"marketo\":\n\t\tsource := exampleData.Data[marketo.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(marketo.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"opsgenie\":\n\t\tsource := exampleData.Data[opsgenie.HandlerKey]\n\t\tfor i, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(opsgenie.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t\tif i == 8 {\n\t\t\t\ttime.Sleep(2000 * time.Millisecond)\n\t\t\t}\n\t\t}\n\tcase \"papertrail\":\n\t\tsource := exampleData.Data[papertrail.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(papertrail.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"pingdom\":\n\t\tsource := exampleData.Data[pingdom.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(pingdom.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"raygun\":\n\t\tsender.SendCcMessage(raygun.ExampleMessage(cfg, exampleData))\n\tcase \"runscope\":\n\t\tsender.SendCcMessage(runscope.ExampleMessage(cfg, exampleData))\n\tcase \"semaphore\":\n\t\tsource := exampleData.Data[semaphore.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(semaphore.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"statuspage\":\n\t\tsource := exampleData.Data[statuspage.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(statuspage.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"travisci\":\n\t\tsender.SendCcMessage(travisci.ExampleMessage(cfg, exampleData))\n\tcase \"userlike\":\n\t\tsource := exampleData.Data[userlike.HandlerKey]\n\t\tfor _, eventSlug := range source.EventSlugs {\n\t\t\tsender.SendCcMessage(userlike.ExampleMessage(cfg, exampleData, eventSlug))\n\t\t}\n\tcase \"victorops\":\n\t\tsender.SendCcMessage(victorops.ExampleMessage(cfg, exampleData))\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Unknown webhook source %v\\n\", example))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/rubblelabs\/ripple\/data\"\n\t\"github.com\/rubblelabs\/ripple\/websockets\"\n)\n\nfunc checkErr(err error, quit bool) {\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tif quit {\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}\n\nvar (\n\thost    = flag.String(\"host\", \"wss:\/\/s-east.ripple.com:443\", \"websockets host to connect to\")\n\taccount = flag.String(\"account\", \"\", \"optional account to monitor\")\n)\n\nfunc main() {\n\tflag.Parse()\n\tvar (\n\t\tfilter *data.Account\n\t\terr    error\n\t)\n\tif len(*account) > 0 {\n\t\tfilter, err = data.NewAccountFromAddress(*account)\n\t\tcheckErr(err, true)\n\t}\n\n\tr, err := websockets.NewRemote(*host)\n\tcheckErr(err, true)\n\n\tconfirmation, err := r.Subscribe(true, true, false, false)\n\tcheckErr(err, true)\n\tlog.Printf(\"Subscribed at: %d \", confirmation.LedgerSequence)\n\n\tfor {\n\t\tmsg, ok := <-r.Incoming\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tswitch msg := msg.(type) {\n\t\tcase *websockets.TransactionStreamMsg:\n\t\t\ttrades, err := data.NewTradeSlice(&msg.Transaction)\n\t\t\tcheckErr(err, false)\n\t\t\tif filter != nil {\n\t\t\t\ttrades = trades.Filter(*filter)\n\t\t\t}\n\t\t\tfor _, trade := range trades {\n\t\t\t\tlog.Println(trade)\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Fill in missing LedgerSequence in trades tool<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/rubblelabs\/ripple\/data\"\n\t\"github.com\/rubblelabs\/ripple\/websockets\"\n)\n\nfunc checkErr(err error, quit bool) {\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\tif quit {\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}\n\nvar (\n\thost    = flag.String(\"host\", \"wss:\/\/s-east.ripple.com:443\", \"websockets host to connect to\")\n\taccount = flag.String(\"account\", \"\", \"optional account to monitor\")\n)\n\nfunc main() {\n\tflag.Parse()\n\tvar (\n\t\tfilter *data.Account\n\t\terr    error\n\t)\n\tif len(*account) > 0 {\n\t\tfilter, err = data.NewAccountFromAddress(*account)\n\t\tcheckErr(err, true)\n\t}\n\n\tr, err := websockets.NewRemote(*host)\n\tcheckErr(err, true)\n\n\tconfirmation, err := r.Subscribe(true, true, false, false)\n\tcheckErr(err, true)\n\tlog.Printf(\"Subscribed at: %d \", confirmation.LedgerSequence)\n\n\tfor {\n\t\tmsg, ok := <-r.Incoming\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tswitch msg := msg.(type) {\n\t\tcase *websockets.TransactionStreamMsg:\n\t\t\tmsg.Transaction.LedgerSequence = msg.LedgerSequence\n\t\t\ttrades, err := data.NewTradeSlice(&msg.Transaction)\n\t\t\tcheckErr(err, false)\n\t\t\tif filter != nil {\n\t\t\t\ttrades = trades.Filter(*filter)\n\t\t\t}\n\t\t\tfor _, trade := range trades {\n\t\t\t\tlog.Println(trade)\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/rosshendrickson-wf\/education\/examples\/toyserver\/message\"\n)\n\n\/\/1000ms\/sec \/ 900FPS = 1.111.. ms per frame\n\/\/1000ms\/sec \/ 450FPS = 2.222.. ms per frame\n\/\/Increase in execution time: 1.111.. ms\n\/\/\n\/\/1000ms\/sec \/ 60FPS = 16.666.. ms per frame\n\/\/1000ms\/sec \/ 56.25FPS = 17.777.. ms per frame\n\n\/\/ read from the connection ever 5ms and apply the updates\nfunc runShip(address, serverPort, clientPort string) {\n\n\tcommands := make(chan *message.Vector, 1000)\n\tship := &Ship{commands: commands}\n\n\tship.Connect(address, serverPort, clientPort)\n\n\t\/\/ApplyUpdates := time.NewTicker(time.Millisecond * 5).C\n\tSendCommands := time.NewTicker(time.Millisecond * 500).C\n\t\/\/Display := time.NewTicker(time.Millisecond * 120).C\n\tDisplayFrames := time.NewTicker(time.Second * 1).C\n\tRandom := time.NewTicker(time.Millisecond * 5).C\n\tDieTime := time.NewTicker(time.Second * 10).C\n\nOuterLoop:\n\tfor {\n\t\tselect {\n\t\t\/\/\tcase <-ApplyUpdates:\n\t\t\/\/\t\tship.ApplyUpdates()\n\t\tcase <-SendCommands:\n\t\t\tship.SendCommands()\n\t\t\/\/\tcase <-Display:\n\t\t\/\/\t\tship.Display()\n\t\tcase <-DisplayFrames:\n\t\t\tship.DisplayFrames()\n\t\tcase <-Random:\n\t\t\tship.commands <- RandomMove()\n\t\tcase <-DieTime:\n\t\t\tship.Close()\n\t\t\tlog.Printf(\"Ship %+v dead\", ship)\n\t\t\tbreak OuterLoop\n\t\tdefault:\n\t\t}\n\t}\n}\n\ntype Ship struct {\n\txp         int\n\typ         int\n\thealth     int\n\tname       [8]byte\n\tconn       *net.UDPConn\n\tsconn      *net.UDPConn\n\tcommands   chan *message.Vector\n\tupdates    chan []byte\n\tshipTime   int\n\tserverTime int\n\tframes     int\n\tlock       sync.Mutex\n\tstop       bool\n\trevision   int\n\tserverAddr net.Addr\n}\n\nfunc (s *Ship) Connect(address, serverPort, clientPort string) {\n\n\t\/\/ spin off a goroutine to read from the connection\n\taddr, err := net.ResolveUDPAddr(\"udp4\", \":\"+clientPort)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tconn, err := net.ListenUDP(\"udp\", addr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tsaddr, err := net.ResolveUDPAddr(\"udp4\", address+\":\"+serverPort)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ts.serverAddr = saddr\n\n\tsconn, err := net.DialUDP(\"udp\", nil, saddr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\ts.sconn = sconn\n\n\tgo func() {\n\t\tfor {\n\t\t\tdefer conn.Close()\n\t\t\tconnbuf := bufio.NewReader(conn)\n\t\t\ts.handleUpdate(conn, connbuf)\n\t\t\tif s.Stop() {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\ts.conn = conn\n}\n\nfunc (s *Ship) Close() {\n\ts.lock.Lock()\n\ts.stop = true\n\ts.lock.Unlock()\n}\n\nfunc (s *Ship) Stop() bool {\n\ts.lock.Lock()\n\tresult := s.stop\n\ts.lock.Unlock()\n\treturn result\n}\n\nfunc (s *Ship) handleUpdate(conn *net.UDPConn, reader *bufio.Reader) {\n\tvar buf []byte = make([]byte, 512)\n\tconn.ReadFromUDP(buf[0:])\n\tm := message.PacketToMessage(buf)\n\tlog.Printf(\"ship got message %+v\", m)\n\ts.frames++\n\t\/\/\ts.updates <- buf\n}\n\nfunc (s *Ship) update(xdir, ydir int) {\n\ts.xp += xdir\n\ts.yp += ydir\n}\n\nfunc (s *Ship) DisplayFrames() {\n\tlog.Printf(\"------------%s:%d\", s.name, s.frames)\n\ts.frames = 0\n}\n\nfunc (s *Ship) Display() {\n\tfmt.Printf(\"%s:%d,%d\", s.name, s.xp, s.yp)\n}\n\nfunc (s *Ship) gatherCommands() []*message.Vector {\n\n\tvar stop bool\n\ttime.AfterFunc(time.Millisecond*1, func() {\n\t\tstop = true\n\t})\n\n\tvar commands []*message.Vector\nOuterLoop:\n\tfor {\n\t\tselect {\n\t\tcase v := <-s.commands:\n\t\t\tif v != nil {\n\t\t\t\tcommands = append(commands, v)\n\t\t\t}\n\t\t\tif stop {\n\t\t\t\tbreak OuterLoop\n\t\t\t}\n\t\tdefault:\n\t\t\tif stop {\n\t\t\t\tbreak OuterLoop\n\t\t\t}\n\t\t}\n\t}\n\n\treturn commands\n}\n\nfunc (s *Ship) SendCommands() {\n\ts.revision++\n\tlog.Printf(\"Sending Commands at Rev %d\", s.revision)\n\tms := message.VectorsToMessages(s.gatherCommands(), s.revision)\n\ts.sendMessages(ms...)\n}\n\nfunc (s *Ship) sendMessages(ms ...*message.Message) {\n\t\/\/ actuall send the vector over the wire as a command\n\tfor _, m := range ms {\n\t\tb := message.MessageToPacket(m)\n\t\ts.sconn.Write(b)\n\t}\n}\n\n\/\/ reads in as many updates as possible in 1 millisecond\nfunc (s *Ship) gatherUpdates() []*message.Vector {\n\n\tvar stop bool\n\ttime.AfterFunc(time.Millisecond*1, func() {\n\t\tstop = true\n\t})\n\n\tvar updates []*message.Vector\nOuterLoop:\n\tfor {\n\t\tselect {\n\t\tcase b := <-s.updates:\n\t\t\tvar m message.Message\n\t\t\tjson.Unmarshal(b, m)\n\t\t\tif m.Type != \"\" {\n\t\t\t\tprintln(\"Ship got message\")\n\t\t\t\t\/\/\t\t\t\tupdates = append(updates, m.Vectors...)\n\t\t\t}\n\t\t\tif stop {\n\t\t\t\tbreak OuterLoop\n\t\t\t}\n\t\tdefault:\n\t\t}\n\t}\n\treturn updates\n}\n\nfunc (s *Ship) ApplyUpdates() {\n\n\t\/\/ Updates override the position as they are state updates\n\tfor _, update := range s.gatherUpdates() {\n\t\ts.xp = update.X\n\t\ts.yp = update.Y\n\t}\n\tfmt.Printf(\"%s:%d,%d\", s.name, s.xp, s.yp)\n\ts.frames++\n}\n\nfunc random(min, max int) int {\n\trand.Seed(time.Now().Unix())\n\treturn rand.Intn(max-min) + min\n}\n\nfunc RandomMove() *message.Vector {\n\n\txdir := random(1, 6)\n\tydir := random(1, 10)\n\n\treturn &message.Vector{xdir, ydir}\n}\n\nfunc main() {\n\n\trunShip(\"\", \"10234\", \"55102\")\n}\n\nfunc test() {\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Sends Random traffic\n\taddr, err := net.ResolveUDPAddr(\"udp\", \":10234\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tconn, err := net.DialUDP(\"udp\", nil, addr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tdefer conn.Close()\n\tlog.Println(\"Connected to \", addr)\n\tnum := 100000\n\tvectors := randVectors(num)\n\n\tms := message.VectorsToMessages(vectors, 101)\n\n\tfor {\n\t\t\/\/\t\tnewAddr := new(net.UDPAddr)\n\t\t\/\/\t\t*newAddr = *addr\n\t\t\/\/\t\tnewAddr.IP = make(net.IP, len(addr.IP))\n\t\t\/\/\t\tcopy(newAddr.IP, addr.IP)\n\t\t\/\/\n\t\t\/\/conn.WriteToUDP(b, newAddr)\n\t\tfor i, m := range ms {\n\t\t\tm.Revision = i\n\t\t\tp := message.MessageToPacket(m)\n\t\t\tconn.Write(p)\n\t\t}\n\n\t\t\/\/\tvar buf []byte = make([]byte, 512)\n\t\t\/\/\tn, a, err := conn.ReadFromUDP(buf[0:])\n\t\t\/\/\tlog.Printf(\"read %s %d\", a, n)\n\t\t\/\/\tif err != nil {\n\t\t\/\/\t\treturn\n\t\t\/\/\t}\n\t\t\/\/log.Printf(\"Sent %d vectors in %d\", num, len(ms))\n\t\t\/\/time.Sleep(time.Second * 1)\n\t\tprintln(\"Sent Messages\")\n\t\ttime.Sleep(time.Millisecond * 1000)\n\t}\n}\n\nfunc randVectors(num int) []*message.Vector {\n\n\tresults := make([]*message.Vector, num)\n\tfor i := range results {\n\n\t\tresults[i] = RandomMove()\n\t}\n\n\treturn results\n}\n<commit_msg>Pong message confirmed back, do not need to listen<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/rosshendrickson-wf\/education\/examples\/toyserver\/message\"\n)\n\n\/\/1000ms\/sec \/ 900FPS = 1.111.. ms per frame\n\/\/1000ms\/sec \/ 450FPS = 2.222.. ms per frame\n\/\/Increase in execution time: 1.111.. ms\n\/\/\n\/\/1000ms\/sec \/ 60FPS = 16.666.. ms per frame\n\/\/1000ms\/sec \/ 56.25FPS = 17.777.. ms per frame\n\n\/\/ read from the connection ever 5ms and apply the updates\nfunc runShip(address, serverPort, clientPort string) {\n\n\tcommands := make(chan *message.Vector, 1000)\n\tship := &Ship{commands: commands}\n\n\tship.Connect(address, serverPort, clientPort)\n\n\t\/\/ApplyUpdates := time.NewTicker(time.Millisecond * 5).C\n\tSendCommands := time.NewTicker(time.Millisecond * 500).C\n\t\/\/Display := time.NewTicker(time.Millisecond * 120).C\n\tDisplayFrames := time.NewTicker(time.Second * 1).C\n\tRandom := time.NewTicker(time.Millisecond * 5).C\n\tDieTime := time.NewTicker(time.Second * 10).C\n\nOuterLoop:\n\tfor {\n\t\tselect {\n\t\t\/\/\tcase <-ApplyUpdates:\n\t\t\/\/\t\tship.ApplyUpdates()\n\t\tcase <-SendCommands:\n\t\t\tship.SendCommands()\n\t\t\/\/\tcase <-Display:\n\t\t\/\/\t\tship.Display()\n\t\tcase <-DisplayFrames:\n\t\t\tship.DisplayFrames()\n\t\tcase <-Random:\n\t\t\tship.commands <- RandomMove()\n\t\tcase <-DieTime:\n\t\t\tship.Close()\n\t\t\tlog.Printf(\"Ship %+v dead\", ship)\n\t\t\tbreak OuterLoop\n\t\tdefault:\n\t\t}\n\t}\n}\n\ntype Ship struct {\n\txp         int\n\typ         int\n\thealth     int\n\tname       [8]byte\n\tconn       *net.UDPConn\n\tsconn      *net.UDPConn\n\tcommands   chan *message.Vector\n\tupdates    chan []byte\n\tshipTime   int\n\tserverTime int\n\tframes     int\n\tlock       sync.Mutex\n\tstop       bool\n\trevision   int\n\tserverAddr net.Addr\n}\n\nfunc (s *Ship) Connect(address, serverPort, clientPort string) {\n\n\t\/\/ spin off a goroutine to read from the connection\n\taddr, err := net.ResolveUDPAddr(\"udp4\", \":\"+clientPort)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tconn, err := net.ListenUDP(\"udp\", addr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tsaddr, err := net.ResolveUDPAddr(\"udp4\", address+\":\"+serverPort)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ts.serverAddr = saddr\n\n\tsconn, err := net.DialUDP(\"udp\", nil, saddr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\ts.sconn = sconn\n\n\tgo func() {\n\t\tfor {\n\t\t\tdefer conn.Close()\n\t\t\tconnbuf := bufio.NewReader(conn)\n\t\t\ts.handleUpdate(sconn, connbuf)\n\t\t\tif s.Stop() {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\ts.conn = conn\n}\n\nfunc (s *Ship) Close() {\n\ts.lock.Lock()\n\ts.stop = true\n\ts.lock.Unlock()\n}\n\nfunc (s *Ship) Stop() bool {\n\ts.lock.Lock()\n\tresult := s.stop\n\ts.lock.Unlock()\n\treturn result\n}\n\nfunc (s *Ship) handleUpdate(conn *net.UDPConn, reader *bufio.Reader) {\n\tvar buf []byte = make([]byte, 512)\n\tconn.ReadFromUDP(buf[0:])\n\tm := message.PacketToMessage(buf)\n\tlog.Printf(\"ship got message %+v\", m)\n\ts.frames++\n\t\/\/\ts.updates <- buf\n}\n\nfunc (s *Ship) update(xdir, ydir int) {\n\ts.xp += xdir\n\ts.yp += ydir\n}\n\nfunc (s *Ship) DisplayFrames() {\n\tlog.Printf(\"------------%s:%d\", s.name, s.frames)\n\ts.frames = 0\n}\n\nfunc (s *Ship) Display() {\n\tfmt.Printf(\"%s:%d,%d\", s.name, s.xp, s.yp)\n}\n\nfunc (s *Ship) gatherCommands() []*message.Vector {\n\n\tvar stop bool\n\ttime.AfterFunc(time.Millisecond*1, func() {\n\t\tstop = true\n\t})\n\n\tvar commands []*message.Vector\nOuterLoop:\n\tfor {\n\t\tselect {\n\t\tcase v := <-s.commands:\n\t\t\tif v != nil {\n\t\t\t\tcommands = append(commands, v)\n\t\t\t}\n\t\t\tif stop {\n\t\t\t\tbreak OuterLoop\n\t\t\t}\n\t\tdefault:\n\t\t\tif stop {\n\t\t\t\tbreak OuterLoop\n\t\t\t}\n\t\t}\n\t}\n\n\treturn commands\n}\n\nfunc (s *Ship) SendCommands() {\n\ts.revision++\n\tlog.Printf(\"Sending Commands at Rev %d\", s.revision)\n\tms := message.VectorsToMessages(s.gatherCommands(), s.revision)\n\ts.sendMessages(ms...)\n}\n\nfunc (s *Ship) sendMessages(ms ...*message.Message) {\n\t\/\/ actuall send the vector over the wire as a command\n\tfor _, m := range ms {\n\t\tb := message.MessageToPacket(m)\n\t\ts.sconn.Write(b)\n\t}\n}\n\n\/\/ reads in as many updates as possible in 1 millisecond\nfunc (s *Ship) gatherUpdates() []*message.Vector {\n\n\tvar stop bool\n\ttime.AfterFunc(time.Millisecond*1, func() {\n\t\tstop = true\n\t})\n\n\tvar updates []*message.Vector\nOuterLoop:\n\tfor {\n\t\tselect {\n\t\tcase b := <-s.updates:\n\t\t\tvar m message.Message\n\t\t\tjson.Unmarshal(b, m)\n\t\t\tif m.Type != \"\" {\n\t\t\t\tprintln(\"Ship got message\")\n\t\t\t\t\/\/\t\t\t\tupdates = append(updates, m.Vectors...)\n\t\t\t}\n\t\t\tif stop {\n\t\t\t\tbreak OuterLoop\n\t\t\t}\n\t\tdefault:\n\t\t}\n\t}\n\treturn updates\n}\n\nfunc (s *Ship) ApplyUpdates() {\n\n\t\/\/ Updates override the position as they are state updates\n\tfor _, update := range s.gatherUpdates() {\n\t\ts.xp = update.X\n\t\ts.yp = update.Y\n\t}\n\tfmt.Printf(\"%s:%d,%d\", s.name, s.xp, s.yp)\n\ts.frames++\n}\n\nfunc random(min, max int) int {\n\trand.Seed(time.Now().Unix())\n\treturn rand.Intn(max-min) + min\n}\n\nfunc RandomMove() *message.Vector {\n\n\txdir := random(1, 6)\n\tydir := random(1, 10)\n\n\treturn &message.Vector{xdir, ydir}\n}\n\nfunc main() {\n\n\trunShip(\"\", \"10234\", \"55102\")\n}\n\nfunc test() {\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Sends Random traffic\n\taddr, err := net.ResolveUDPAddr(\"udp\", \":10234\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tconn, err := net.DialUDP(\"udp\", nil, addr)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tdefer conn.Close()\n\tlog.Println(\"Connected to \", addr)\n\tnum := 100000\n\tvectors := randVectors(num)\n\n\tms := message.VectorsToMessages(vectors, 101)\n\n\tfor {\n\t\t\/\/\t\tnewAddr := new(net.UDPAddr)\n\t\t\/\/\t\t*newAddr = *addr\n\t\t\/\/\t\tnewAddr.IP = make(net.IP, len(addr.IP))\n\t\t\/\/\t\tcopy(newAddr.IP, addr.IP)\n\t\t\/\/\n\t\t\/\/conn.WriteToUDP(b, newAddr)\n\t\tfor i, m := range ms {\n\t\t\tm.Revision = i\n\t\t\tp := message.MessageToPacket(m)\n\t\t\tconn.Write(p)\n\t\t}\n\n\t\t\/\/\tvar buf []byte = make([]byte, 512)\n\t\t\/\/\tn, a, err := conn.ReadFromUDP(buf[0:])\n\t\t\/\/\tlog.Printf(\"read %s %d\", a, n)\n\t\t\/\/\tif err != nil {\n\t\t\/\/\t\treturn\n\t\t\/\/\t}\n\t\t\/\/log.Printf(\"Sent %d vectors in %d\", num, len(ms))\n\t\t\/\/time.Sleep(time.Second * 1)\n\t\tprintln(\"Sent Messages\")\n\t\ttime.Sleep(time.Millisecond * 1000)\n\t}\n}\n\nfunc randVectors(num int) []*message.Vector {\n\n\tresults := make([]*message.Vector, num)\n\tfor i := range results {\n\n\t\tresults[i] = RandomMove()\n\t}\n\n\treturn results\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage inode\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/internal\/gcsx\"\n\t\"github.com\/jacobsa\/fuse\/fuseops\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\"\n\t\"github.com\/jacobsa\/syncutil\"\n\t\"github.com\/jacobsa\/timeutil\"\n\t\"golang.org\/x\/net\/context\"\n)\n\ntype FileInode struct {\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Dependencies\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tbucket gcs.Bucket\n\tsyncer gcsx.Syncer\n\tclock  timeutil.Clock\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Constant data\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tid           fuseops.InodeID\n\tname         string\n\tattrs        fuseops.InodeAttributes\n\tgcsChunkSize uint64\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Mutable state\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ A mutex that must be held when calling certain methods. See documentation\n\t\/\/ for each method.\n\tmu syncutil.InvariantMutex\n\n\t\/\/ GUARDED_BY(mu)\n\tlc lookupCount\n\n\t\/\/ The source object from which this inode derives.\n\t\/\/\n\t\/\/ INVARIANT: src.Name == name\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tsrc gcs.Object\n\n\t\/\/ The current content of this inode, or nil if the source object is still\n\t\/\/ authoritative.\n\tcontent gcsx.TempFile\n\n\t\/\/ Has Destroy been called?\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tdestroyed bool\n}\n\nvar _ Inode = &FileInode{}\n\n\/\/ Create a file inode for the given object in GCS. The initial lookup count is\n\/\/ zero.\n\/\/\n\/\/ REQUIRES: o != nil\n\/\/ REQUIRES: o.Generation > 0\n\/\/ REQUIRES: len(o.Name) > 0\n\/\/ REQUIRES: o.Name[len(o.Name)-1] != '\/'\nfunc NewFileInode(\n\tid fuseops.InodeID,\n\to *gcs.Object,\n\tattrs fuseops.InodeAttributes,\n\tbucket gcs.Bucket,\n\tsyncer gcsx.Syncer,\n\tclock timeutil.Clock) (f *FileInode) {\n\t\/\/ Set up the basic struct.\n\tf = &FileInode{\n\t\tbucket: bucket,\n\t\tsyncer: syncer,\n\t\tclock:  clock,\n\t\tid:     id,\n\t\tname:   o.Name,\n\t\tattrs:  attrs,\n\t\tsrc:    *o,\n\t}\n\n\tf.lc.Init(id)\n\n\t\/\/ Set up invariant checking.\n\tf.mu = syncutil.NewInvariantMutex(f.checkInvariants)\n\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) checkInvariants() {\n\tif f.destroyed {\n\t\treturn\n\t}\n\n\t\/\/ Make sure the name is legal.\n\tname := f.Name()\n\tif len(name) == 0 || name[len(name)-1] == '\/' {\n\t\tpanic(\"Illegal file name: \" + name)\n\t}\n\n\t\/\/ INVARIANT: src.Name == name\n\tif f.src.Name != name {\n\t\tpanic(fmt.Sprintf(\"Name mismatch: %q vs. %q\", f.src.Name, name))\n\t}\n\n\t\/\/ INVARIANT: content.CheckInvariants() does not panic\n\tif f.content != nil {\n\t\tf.content.CheckInvariants()\n\t}\n}\n\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) clobbered(ctx context.Context) (b bool, err error) {\n\t\/\/ Stat the object in GCS.\n\treq := &gcs.StatObjectRequest{Name: f.name}\n\to, err := f.bucket.StatObject(ctx, req)\n\n\t\/\/ Special case: \"not found\" means we have been clobbered.\n\tif _, ok := err.(*gcs.NotFoundError); ok {\n\t\terr = nil\n\t\tb = true\n\t\treturn\n\t}\n\n\t\/\/ Propagate other errors.\n\tif err != nil {\n\t\terr = fmt.Errorf(\"StatObject: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ We are clobbered iff the generation doesn't match our source generation.\n\tb = (o.Generation != f.src.Generation)\n\n\treturn\n}\n\n\/\/ Ensure that f.content != nil\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) ensureContent(ctx context.Context) (err error) {\n\t\/\/ Is there anything to do?\n\tif f.content != nil {\n\t\treturn\n\t}\n\n\t\/\/ Open a reader for the generation we care about.\n\trc, err := f.bucket.NewReader(\n\t\tctx,\n\t\t&gcs.ReadObjectRequest{\n\t\t\tName:       f.src.Name,\n\t\t\tGeneration: f.src.Generation,\n\t\t})\n\n\tif err != nil {\n\t\terr = fmt.Errorf(\"NewReader: %v\", err)\n\t\treturn\n\t}\n\n\tdefer rc.Close()\n\n\t\/\/ Create a temporary file with its contents.\n\ttf, err := gcsx.NewTempFile(rc, f.clock)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"NewTempFile: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Update state.\n\tf.content = tf\n\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Public interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (f *FileInode) Lock() {\n\tf.mu.Lock()\n}\n\nfunc (f *FileInode) Unlock() {\n\tf.mu.Unlock()\n}\n\nfunc (f *FileInode) ID() fuseops.InodeID {\n\treturn f.id\n}\n\nfunc (f *FileInode) Name() string {\n\treturn f.name\n}\n\n\/\/ Return a record for the GCS object generation from which this inode is\n\/\/ branched. The record is guaranteed not to be modified, and users must not\n\/\/ modify it.\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Source() *gcs.Object {\n\t\/\/ Make a copy, since we modify f.src.\n\to := f.src\n\treturn &o\n}\n\n\/\/ If true, it is safe to serve reads directly from the object generation given\n\/\/ by f.Source(), rather than calling f.ReadAt. Doing so may be more efficient,\n\/\/ because f.ReadAt may cause the entire object to be faulted in and requires\n\/\/ the inode to be locked during the read.\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) SourceGenerationIsAuthoritative() bool {\n\treturn f.content == nil\n}\n\n\/\/ Equivalent to f.Source().Generation.\n\/\/\n\/\/ LOCKS_REQUIRED(f)\nfunc (f *FileInode) SourceGeneration() int64 {\n\treturn f.src.Generation\n}\n\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) IncrementLookupCount() {\n\tf.lc.Inc()\n}\n\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) DecrementLookupCount(n uint64) (destroy bool) {\n\tdestroy = f.lc.Dec(n)\n\treturn\n}\n\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Destroy() (err error) {\n\tf.destroyed = true\n\n\tif f.content != nil {\n\t\tf.content.Destroy()\n\t}\n\n\treturn\n}\n\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Attributes(\n\tctx context.Context) (attrs fuseops.InodeAttributes, err error) {\n\tattrs = f.attrs\n\n\t\/\/ Obtain default information from the source object.\n\tattrs.Mtime = f.src.Updated\n\tattrs.Size = uint64(f.src.Size)\n\n\t\/\/ If GCS is no longer authoritative, stat our local content to obtain size\n\t\/\/ and mtime.\n\tif f.content != nil {\n\t\tvar sr gcsx.StatResult\n\t\tsr, err = f.content.Stat()\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Stat: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tattrs.Size = uint64(sr.Size)\n\t\tif sr.Mtime != nil {\n\t\t\tattrs.Mtime = *sr.Mtime\n\t\t}\n\t}\n\n\t\/\/ If the object has been clobbered, we reflect that as the inode being\n\t\/\/ unlinked.\n\tclobbered, err := f.clobbered(ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"clobbered: %v\", err)\n\t\treturn\n\t}\n\n\tif !clobbered {\n\t\tattrs.Nlink = 1\n\t}\n\n\treturn\n}\n\n\/\/ Serve a read for this file with semantics matching io.ReaderAt.\n\/\/\n\/\/ The caller may be better off reading directly from GCS when\n\/\/ f.SourceGenerationIsAuthoritative() is true.\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Read(\n\tctx context.Context,\n\tdst []byte,\n\toffset int64) (n int, err error) {\n\t\/\/ Make sure f.content != nil.\n\terr = f.ensureContent(ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"ensureContent: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Read from the local content, propagating io.EOF.\n\tn, err = f.content.ReadAt(dst, offset)\n\tswitch {\n\tcase err == io.EOF:\n\t\treturn\n\n\tcase err != nil:\n\t\terr = fmt.Errorf(\"content.ReadAt: %v\", err)\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ Serve a write for this file with semantics matching fuseops.WriteFileOp.\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Write(\n\tctx context.Context,\n\tdata []byte,\n\toffset int64) (err error) {\n\t\/\/ Make sure f.content != nil.\n\terr = f.ensureContent(ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"ensureContent: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Write to the mutable content. Note that io.WriterAt guarantees it returns\n\t\/\/ an error for short writes.\n\t_, err = f.content.WriteAt(data, offset)\n\n\treturn\n}\n\n\/\/ Write out contents to GCS. If this fails due to the generation having been\n\/\/ clobbered, treat it as a non-error (simulating the inode having been\n\/\/ unlinked).\n\/\/\n\/\/ After this method succeeds, SourceGeneration will return the new generation\n\/\/ by which this inode should be known (which may be the same as before). If it\n\/\/ fails, the generation will not change.\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Sync(ctx context.Context) (err error) {\n\t\/\/ If we have not been dirtied, there is nothing to do.\n\tif f.content == nil {\n\t\treturn\n\t}\n\n\t\/\/ Write out the contents if they are dirty.\n\tnewObj, err := f.syncer.SyncObject(ctx, &f.src, f.content)\n\n\t\/\/ Special case: a precondition error means we were clobbered, which we treat\n\t\/\/ as being unlinked. There's no reason to return an error in that case.\n\tif _, ok := err.(*gcs.PreconditionError); ok {\n\t\terr = nil\n\t}\n\n\t\/\/ Propagate other errors.\n\tif err != nil {\n\t\terr = fmt.Errorf(\"SyncObject: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ If we wrote out a new object, we need to update our state.\n\tif newObj != nil {\n\t\tf.src = *newObj\n\t\tf.content = nil\n\t}\n\n\treturn\n}\n\n\/\/ Truncate the file to the specified size.\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Truncate(\n\tctx context.Context,\n\tsize int64) (err error) {\n\t\/\/ Make sure f.content != nil.\n\terr = f.ensureContent(ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"ensureContent: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Call through.\n\terr = f.content.Truncate(size)\n\n\treturn\n}\n<commit_msg>Removed an unused field.<commit_after>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage inode\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/internal\/gcsx\"\n\t\"github.com\/jacobsa\/fuse\/fuseops\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\"\n\t\"github.com\/jacobsa\/syncutil\"\n\t\"github.com\/jacobsa\/timeutil\"\n\t\"golang.org\/x\/net\/context\"\n)\n\ntype FileInode struct {\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Dependencies\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tbucket gcs.Bucket\n\tsyncer gcsx.Syncer\n\tclock  timeutil.Clock\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Constant data\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tid    fuseops.InodeID\n\tname  string\n\tattrs fuseops.InodeAttributes\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Mutable state\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ A mutex that must be held when calling certain methods. See documentation\n\t\/\/ for each method.\n\tmu syncutil.InvariantMutex\n\n\t\/\/ GUARDED_BY(mu)\n\tlc lookupCount\n\n\t\/\/ The source object from which this inode derives.\n\t\/\/\n\t\/\/ INVARIANT: src.Name == name\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tsrc gcs.Object\n\n\t\/\/ The current content of this inode, or nil if the source object is still\n\t\/\/ authoritative.\n\tcontent gcsx.TempFile\n\n\t\/\/ Has Destroy been called?\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tdestroyed bool\n}\n\nvar _ Inode = &FileInode{}\n\n\/\/ Create a file inode for the given object in GCS. The initial lookup count is\n\/\/ zero.\n\/\/\n\/\/ REQUIRES: o != nil\n\/\/ REQUIRES: o.Generation > 0\n\/\/ REQUIRES: len(o.Name) > 0\n\/\/ REQUIRES: o.Name[len(o.Name)-1] != '\/'\nfunc NewFileInode(\n\tid fuseops.InodeID,\n\to *gcs.Object,\n\tattrs fuseops.InodeAttributes,\n\tbucket gcs.Bucket,\n\tsyncer gcsx.Syncer,\n\tclock timeutil.Clock) (f *FileInode) {\n\t\/\/ Set up the basic struct.\n\tf = &FileInode{\n\t\tbucket: bucket,\n\t\tsyncer: syncer,\n\t\tclock:  clock,\n\t\tid:     id,\n\t\tname:   o.Name,\n\t\tattrs:  attrs,\n\t\tsrc:    *o,\n\t}\n\n\tf.lc.Init(id)\n\n\t\/\/ Set up invariant checking.\n\tf.mu = syncutil.NewInvariantMutex(f.checkInvariants)\n\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) checkInvariants() {\n\tif f.destroyed {\n\t\treturn\n\t}\n\n\t\/\/ Make sure the name is legal.\n\tname := f.Name()\n\tif len(name) == 0 || name[len(name)-1] == '\/' {\n\t\tpanic(\"Illegal file name: \" + name)\n\t}\n\n\t\/\/ INVARIANT: src.Name == name\n\tif f.src.Name != name {\n\t\tpanic(fmt.Sprintf(\"Name mismatch: %q vs. %q\", f.src.Name, name))\n\t}\n\n\t\/\/ INVARIANT: content.CheckInvariants() does not panic\n\tif f.content != nil {\n\t\tf.content.CheckInvariants()\n\t}\n}\n\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) clobbered(ctx context.Context) (b bool, err error) {\n\t\/\/ Stat the object in GCS.\n\treq := &gcs.StatObjectRequest{Name: f.name}\n\to, err := f.bucket.StatObject(ctx, req)\n\n\t\/\/ Special case: \"not found\" means we have been clobbered.\n\tif _, ok := err.(*gcs.NotFoundError); ok {\n\t\terr = nil\n\t\tb = true\n\t\treturn\n\t}\n\n\t\/\/ Propagate other errors.\n\tif err != nil {\n\t\terr = fmt.Errorf(\"StatObject: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ We are clobbered iff the generation doesn't match our source generation.\n\tb = (o.Generation != f.src.Generation)\n\n\treturn\n}\n\n\/\/ Ensure that f.content != nil\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) ensureContent(ctx context.Context) (err error) {\n\t\/\/ Is there anything to do?\n\tif f.content != nil {\n\t\treturn\n\t}\n\n\t\/\/ Open a reader for the generation we care about.\n\trc, err := f.bucket.NewReader(\n\t\tctx,\n\t\t&gcs.ReadObjectRequest{\n\t\t\tName:       f.src.Name,\n\t\t\tGeneration: f.src.Generation,\n\t\t})\n\n\tif err != nil {\n\t\terr = fmt.Errorf(\"NewReader: %v\", err)\n\t\treturn\n\t}\n\n\tdefer rc.Close()\n\n\t\/\/ Create a temporary file with its contents.\n\ttf, err := gcsx.NewTempFile(rc, f.clock)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"NewTempFile: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Update state.\n\tf.content = tf\n\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Public interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (f *FileInode) Lock() {\n\tf.mu.Lock()\n}\n\nfunc (f *FileInode) Unlock() {\n\tf.mu.Unlock()\n}\n\nfunc (f *FileInode) ID() fuseops.InodeID {\n\treturn f.id\n}\n\nfunc (f *FileInode) Name() string {\n\treturn f.name\n}\n\n\/\/ Return a record for the GCS object generation from which this inode is\n\/\/ branched. The record is guaranteed not to be modified, and users must not\n\/\/ modify it.\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Source() *gcs.Object {\n\t\/\/ Make a copy, since we modify f.src.\n\to := f.src\n\treturn &o\n}\n\n\/\/ If true, it is safe to serve reads directly from the object generation given\n\/\/ by f.Source(), rather than calling f.ReadAt. Doing so may be more efficient,\n\/\/ because f.ReadAt may cause the entire object to be faulted in and requires\n\/\/ the inode to be locked during the read.\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) SourceGenerationIsAuthoritative() bool {\n\treturn f.content == nil\n}\n\n\/\/ Equivalent to f.Source().Generation.\n\/\/\n\/\/ LOCKS_REQUIRED(f)\nfunc (f *FileInode) SourceGeneration() int64 {\n\treturn f.src.Generation\n}\n\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) IncrementLookupCount() {\n\tf.lc.Inc()\n}\n\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) DecrementLookupCount(n uint64) (destroy bool) {\n\tdestroy = f.lc.Dec(n)\n\treturn\n}\n\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Destroy() (err error) {\n\tf.destroyed = true\n\n\tif f.content != nil {\n\t\tf.content.Destroy()\n\t}\n\n\treturn\n}\n\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Attributes(\n\tctx context.Context) (attrs fuseops.InodeAttributes, err error) {\n\tattrs = f.attrs\n\n\t\/\/ Obtain default information from the source object.\n\tattrs.Mtime = f.src.Updated\n\tattrs.Size = uint64(f.src.Size)\n\n\t\/\/ If GCS is no longer authoritative, stat our local content to obtain size\n\t\/\/ and mtime.\n\tif f.content != nil {\n\t\tvar sr gcsx.StatResult\n\t\tsr, err = f.content.Stat()\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"Stat: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tattrs.Size = uint64(sr.Size)\n\t\tif sr.Mtime != nil {\n\t\t\tattrs.Mtime = *sr.Mtime\n\t\t}\n\t}\n\n\t\/\/ If the object has been clobbered, we reflect that as the inode being\n\t\/\/ unlinked.\n\tclobbered, err := f.clobbered(ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"clobbered: %v\", err)\n\t\treturn\n\t}\n\n\tif !clobbered {\n\t\tattrs.Nlink = 1\n\t}\n\n\treturn\n}\n\n\/\/ Serve a read for this file with semantics matching io.ReaderAt.\n\/\/\n\/\/ The caller may be better off reading directly from GCS when\n\/\/ f.SourceGenerationIsAuthoritative() is true.\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Read(\n\tctx context.Context,\n\tdst []byte,\n\toffset int64) (n int, err error) {\n\t\/\/ Make sure f.content != nil.\n\terr = f.ensureContent(ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"ensureContent: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Read from the local content, propagating io.EOF.\n\tn, err = f.content.ReadAt(dst, offset)\n\tswitch {\n\tcase err == io.EOF:\n\t\treturn\n\n\tcase err != nil:\n\t\terr = fmt.Errorf(\"content.ReadAt: %v\", err)\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ Serve a write for this file with semantics matching fuseops.WriteFileOp.\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Write(\n\tctx context.Context,\n\tdata []byte,\n\toffset int64) (err error) {\n\t\/\/ Make sure f.content != nil.\n\terr = f.ensureContent(ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"ensureContent: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Write to the mutable content. Note that io.WriterAt guarantees it returns\n\t\/\/ an error for short writes.\n\t_, err = f.content.WriteAt(data, offset)\n\n\treturn\n}\n\n\/\/ Write out contents to GCS. If this fails due to the generation having been\n\/\/ clobbered, treat it as a non-error (simulating the inode having been\n\/\/ unlinked).\n\/\/\n\/\/ After this method succeeds, SourceGeneration will return the new generation\n\/\/ by which this inode should be known (which may be the same as before). If it\n\/\/ fails, the generation will not change.\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Sync(ctx context.Context) (err error) {\n\t\/\/ If we have not been dirtied, there is nothing to do.\n\tif f.content == nil {\n\t\treturn\n\t}\n\n\t\/\/ Write out the contents if they are dirty.\n\tnewObj, err := f.syncer.SyncObject(ctx, &f.src, f.content)\n\n\t\/\/ Special case: a precondition error means we were clobbered, which we treat\n\t\/\/ as being unlinked. There's no reason to return an error in that case.\n\tif _, ok := err.(*gcs.PreconditionError); ok {\n\t\terr = nil\n\t}\n\n\t\/\/ Propagate other errors.\n\tif err != nil {\n\t\terr = fmt.Errorf(\"SyncObject: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ If we wrote out a new object, we need to update our state.\n\tif newObj != nil {\n\t\tf.src = *newObj\n\t\tf.content = nil\n\t}\n\n\treturn\n}\n\n\/\/ Truncate the file to the specified size.\n\/\/\n\/\/ LOCKS_REQUIRED(f.mu)\nfunc (f *FileInode) Truncate(\n\tctx context.Context,\n\tsize int64) (err error) {\n\t\/\/ Make sure f.content != nil.\n\terr = f.ensureContent(ctx)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"ensureContent: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Call through.\n\terr = f.content.Truncate(size)\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package serialapi\n\nimport (\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc Test_Decode(t *testing.T) {\n\n\traw := []string{\n\t\t\"01 04 01 13 01 00\",\n\n\t\t\"01 11 00 04 00 02 0b 71 05 07 00 00 ff 07 00 01 08 00 00\",\n\t\t\"01 11 00 04 00 02 0b 71 05 07 ff 00 ff 07 08 01 08 00 00\",\n\t\t\"01 11 00 04 00 02 0b 71 05 07 00 00 ff 07 00 01 08 00 00\",\n\n\t\t\"01 0c 00 04 00 03 06 31 05 03 0a 00 c2 00\",\n\t\t\"01 0c 00 04 00 03 06 31 05 03 0a 00 1d 00\",\n\n\t\t\"01 09 00 04 00 02 03 20 01 00 00\",\n\t\t\"01 09 00 04 00 02 03 20 01 ff 00\",\n\n\t\t\"01 08 00 04 04 03 02 84 07 00\",\n\t}\n\n\tfor _, val := range raw {\n\t\tdata := []byte{}\n\n\t\tbytes := strings.Split(val, \" \")\n\t\tfor _, b := range bytes {\n\t\t\tdhex, _ := hex.DecodeString(b)\n\t\t\tdata = append(data, dhex...)\n\t\t}\n\n\t\tmsg := CreateMessage(data)\n\t\tfmt.Printf(\"%+v\\n\\n\", msg.Data)\n\t}\n\n}\n<commit_msg>Fix broken serialapi tests<commit_after>package serialapi\n\nimport (\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc Test_Decode(t *testing.T) {\n\n\traw := []string{\n\t\t\"01 04 01 13 01 00\",\n\n\t\t\"01 11 00 04 00 02 0b 71 05 07 00 00 ff 07 00 01 08 00 00\",\n\t\t\"01 11 00 04 00 02 0b 71 05 07 ff 00 ff 07 08 01 08 00 00\",\n\t\t\"01 11 00 04 00 02 0b 71 05 07 00 00 ff 07 00 01 08 00 00\",\n\n\t\t\"01 0c 00 04 00 03 06 31 05 03 0a 00 c2 00\",\n\t\t\"01 0c 00 04 00 03 06 31 05 03 0a 00 1d 00\",\n\n\t\t\"01 09 00 04 00 02 03 20 01 00 00\",\n\t\t\"01 09 00 04 00 02 03 20 01 ff 00\",\n\n\t\t\"01 08 00 04 04 03 02 84 07 00\",\n\t}\n\n\tfor _, val := range raw {\n\t\tdata := []byte{}\n\n\t\tbytes := strings.Split(val, \" \")\n\t\tfor _, b := range bytes {\n\t\t\tdhex, _ := hex.DecodeString(b)\n\t\t\tdata = append(data, dhex...)\n\t\t}\n\n\t\tmsg := NewMessage(data)\n\t\tfmt.Printf(\"%+v\\n\\n\", msg.Data)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package git\n\nimport (\n    \"os\"\n)\n\ntype mkMonad struct {\n    err error\n}\n\nfunc (m *mkMonad) Mk(name string, perm os.FileMode) {\n    if m.err != nil {\n        m.err = os.Mkdir(name, 0666)\n    }\n}\n\nfunc Init() {\n    var m mkMonad\n    var list = []string{\n        \".git\"\n        \".git\/info\"\n        \".git\/hooks\",\n        \".git\/objects\",\n        \".git\/objects\/info\",\n        \".git\/objects\/pack\",\n        \".git\/refs\",\n        \".git\/refs\/heads\",\n        \".git\/refs\/tags\",\n    }\n\n    for _, path := range list {\n        m.MkDir(path, 0666)\n    }\n}\n<commit_msg>init.go: Mk method doesn't exist.<commit_after>package git\n\nimport (\n\t\"os\"\n)\n\ntype mkMonad struct {\n\terr error\n}\n\nfunc (m *mkMonad) MkDir(name string, perm os.FileMode) {\n\tif m.err != nil {\n\t\tm.err = os.Mkdir(name, 0666)\n\t}\n}\n\nfunc Init() {\n\tvar m mkMonad\n\tvar list = []string{\n\t\t\".git\",\n\t\t\".git\/info\",\n\t\t\".git\/hooks\",\n\t\t\".git\/objects\",\n\t\t\".git\/objects\/info\",\n\t\t\".git\/objects\/pack\",\n\t\t\".git\/refs\",\n\t\t\".git\/refs\/heads\",\n\t\t\".git\/refs\/tags\",\n\t}\n\n\tfor _, path := range list {\n\t\tm.MkDir(path, 0666)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package dog\n\nimport \"runtime\"\n\n\/\/ DefaultRunner defines the runner to use in case the task does not specify it.\n\/\/\n\/\/ The value is automatically assigned based on the operating system when the\n\/\/ package initializes.\nvar DefaultRunner string\n\n\/\/ ProvideExtraInfo specifies if dog needs to provide execution info (duration,\n\/\/ exit status) after task execution.\nvar ProvideExtraInfo bool\n\n\/\/ deprecation warning flags\nvar deprecationWarningRun bool\nvar deprecationWarningExec bool\n\nfunc init() {\n\tif runtime.GOOS == \"windows\" {\n\t\tDefaultRunner = \"cmd\" \/\/ not implemented yet\n\t} else {\n\t\tDefaultRunner = \"sh\"\n\t}\n}\n<commit_msg>Remove Windows support, was not implemented anyway<commit_after>package dog\n\n\/\/ DefaultRunner defines the runner to use in case the task does not specify it.\nvar DefaultRunner = \"sh\"\n\n\/\/ ProvideExtraInfo specifies if dog needs to provide execution info (duration,\n\/\/ exit status) after task execution.\nvar ProvideExtraInfo bool\n\n\/\/ deprecation warning flags\nvar deprecationWarningRun bool\nvar deprecationWarningExec bool\n<|endoftext|>"}
{"text":"<commit_before>package s3api\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/filer\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/filer_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/iam_pb\"\n\txhttp \"github.com\/chrislusf\/seaweedfs\/weed\/s3api\/http\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/s3api\/s3_constants\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/s3api\/s3err\"\n)\n\ntype Action string\n\ntype Iam interface {\n\tCheck(f http.HandlerFunc, actions ...Action) http.HandlerFunc\n}\n\ntype IdentityAccessManagement struct {\n\tidentities []*Identity\n\tdomain     string\n}\n\ntype Identity struct {\n\tName        string\n\tCredentials []*Credential\n\tActions     []Action\n}\n\ntype Credential struct {\n\tAccessKey string\n\tSecretKey string\n}\n\nfunc (action Action) isAdmin() bool {\n\treturn strings.HasPrefix(string(action), s3_constants.ACTION_ADMIN)\n}\n\nfunc (action Action) isOwner(bucket string) bool {\n\treturn string(action) == s3_constants.ACTION_ADMIN+\":\"+bucket\n}\n\nfunc (action Action) overBucket(bucket string) bool {\n\treturn strings.HasSuffix(string(action), \":\"+bucket) || strings.HasSuffix(string(action), \":*\")\n}\n\nfunc (action Action) getPermission() Permission {\n\tswitch act := strings.Split(string(action), \":\")[0]; act {\n\tcase s3_constants.ACTION_ADMIN:\n\t\treturn Permission(\"FULL_CONTROL\")\n\tcase s3_constants.ACTION_WRITE:\n\t\treturn Permission(\"WRITE\")\n\tcase s3_constants.ACTION_READ:\n\t\treturn Permission(\"READ\")\n\tdefault:\n\t\treturn Permission(\"\")\n\t}\n}\n\nfunc NewIdentityAccessManagement(option *S3ApiServerOption) *IdentityAccessManagement {\n\tiam := &IdentityAccessManagement{\n\t\tdomain: option.DomainName,\n\t}\n\tif option.Config != \"\" {\n\t\tif err := iam.loadS3ApiConfigurationFromFile(option.Config); err != nil {\n\t\t\tglog.Fatalf(\"fail to load config file %s: %v\", option.Config, err)\n\t\t}\n\t} else {\n\t\tif err := iam.loadS3ApiConfigurationFromFiler(option); err != nil {\n\t\t\tglog.Warningf(\"fail to load config: %v\", err)\n\t\t}\n\t}\n\treturn iam\n}\n\nfunc (iam *IdentityAccessManagement) loadS3ApiConfigurationFromFiler(option *S3ApiServerOption) (err error) {\n\tvar content []byte\n\terr = pb.WithFilerClient(option.Filer, option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {\n\t\tcontent, err = filer.ReadInsideFiler(client, filer.IamConfigDirecotry, filer.IamIdentityFile)\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"read S3 config: %v\", err)\n\t}\n\treturn iam.loadS3ApiConfigurationFromBytes(content)\n}\n\nfunc (iam *IdentityAccessManagement) loadS3ApiConfigurationFromFile(fileName string) error {\n\tcontent, readErr := os.ReadFile(fileName)\n\tif readErr != nil {\n\t\tglog.Warningf(\"fail to read %s : %v\", fileName, readErr)\n\t\treturn fmt.Errorf(\"fail to read %s : %v\", fileName, readErr)\n\t}\n\treturn iam.loadS3ApiConfigurationFromBytes(content)\n}\n\nfunc (iam *IdentityAccessManagement) loadS3ApiConfigurationFromBytes(content []byte) error {\n\ts3ApiConfiguration := &iam_pb.S3ApiConfiguration{}\n\tif err := filer.ParseS3ConfigurationFromBytes(content, s3ApiConfiguration); err != nil {\n\t\tglog.Warningf(\"unmarshal error: %v\", err)\n\t\treturn fmt.Errorf(\"unmarshal error: %v\", err)\n\t}\n\tif err := iam.loadS3ApiConfiguration(s3ApiConfiguration); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (iam *IdentityAccessManagement) loadS3ApiConfiguration(config *iam_pb.S3ApiConfiguration) error {\n\tvar identities []*Identity\n\tfor _, ident := range config.Identities {\n\t\tt := &Identity{\n\t\t\tName:        ident.Name,\n\t\t\tCredentials: nil,\n\t\t\tActions:     nil,\n\t\t}\n\t\tfor _, action := range ident.Actions {\n\t\t\tt.Actions = append(t.Actions, Action(action))\n\t\t}\n\t\tfor _, cred := range ident.Credentials {\n\t\t\tt.Credentials = append(t.Credentials, &Credential{\n\t\t\t\tAccessKey: cred.AccessKey,\n\t\t\t\tSecretKey: cred.SecretKey,\n\t\t\t})\n\t\t}\n\t\tidentities = append(identities, t)\n\t}\n\n\t\/\/ atomically switch\n\tiam.identities = identities\n\treturn nil\n}\n\nfunc (iam *IdentityAccessManagement) isEnabled() bool {\n\n\treturn len(iam.identities) > 0\n}\n\nfunc (iam *IdentityAccessManagement) lookupByAccessKey(accessKey string) (identity *Identity, cred *Credential, found bool) {\n\n\tfor _, ident := range iam.identities {\n\t\tfor _, cred := range ident.Credentials {\n\t\t\tif cred.AccessKey == accessKey {\n\t\t\t\treturn ident, cred, true\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, nil, false\n}\n\nfunc (iam *IdentityAccessManagement) lookupAnonymous() (identity *Identity, found bool) {\n\n\tfor _, ident := range iam.identities {\n\t\tif ident.Name == \"anonymous\" {\n\t\t\treturn ident, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, action Action) http.HandlerFunc {\n\n\tif !iam.isEnabled() {\n\t\treturn f\n\t}\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tidentity, errCode := iam.authRequest(r, action)\n\t\tif errCode == s3err.ErrNone {\n\t\t\tif identity != nil && identity.Name != \"\" {\n\t\t\t\tr.Header.Set(xhttp.AmzIdentityId, identity.Name)\n\t\t\t\tif identity.isAdmin() {\n\t\t\t\t\tr.Header.Set(xhttp.AmzIsAdmin, \"true\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tf(w, r)\n\t\t\treturn\n\t\t}\n\t\ts3err.WriteErrorResponse(w, r, errCode)\n\t}\n}\n\n\/\/ check whether the request has valid access keys\nfunc (iam *IdentityAccessManagement) authRequest(r *http.Request, action Action) (*Identity, s3err.ErrorCode) {\n\tvar identity *Identity\n\tvar s3Err s3err.ErrorCode\n\tvar found bool\n\tswitch getRequestAuthType(r) {\n\tcase authTypeStreamingSigned:\n\t\treturn identity, s3err.ErrNone\n\tcase authTypeUnknown:\n\t\tglog.V(3).Infof(\"unknown auth type\")\n\t\treturn identity, s3err.ErrAccessDenied\n\tcase authTypePresignedV2, authTypeSignedV2:\n\t\tglog.V(3).Infof(\"v2 auth type\")\n\t\tidentity, s3Err = iam.isReqAuthenticatedV2(r)\n\tcase authTypeSigned, authTypePresigned:\n\t\tglog.V(3).Infof(\"v4 auth type\")\n\t\tidentity, s3Err = iam.reqSignatureV4Verify(r)\n\tcase authTypePostPolicy:\n\t\tglog.V(3).Infof(\"post policy auth type\")\n\t\treturn identity, s3err.ErrNone\n\tcase authTypeJWT:\n\t\tglog.V(3).Infof(\"jwt auth type\")\n\t\treturn identity, s3err.ErrNotImplemented\n\tcase authTypeAnonymous:\n\t\tidentity, found = iam.lookupAnonymous()\n\t\tif !found {\n\t\t\treturn identity, s3err.ErrAccessDenied\n\t\t}\n\tdefault:\n\t\treturn identity, s3err.ErrNotImplemented\n\t}\n\n\tif s3Err != s3err.ErrNone {\n\t\treturn identity, s3Err\n\t}\n\n\tglog.V(3).Infof(\"user name: %v actions: %v, action: %v\", identity.Name, identity.Actions, action)\n\n\tbucket, _ := getBucketAndObject(r)\n\n\tif !identity.canDo(action, bucket) {\n\t\treturn identity, s3err.ErrAccessDenied\n\t}\n\n\treturn identity, s3err.ErrNone\n\n}\n\nfunc (iam *IdentityAccessManagement) authUser(r *http.Request) (*Identity, s3err.ErrorCode) {\n\tvar identity *Identity\n\tvar s3Err s3err.ErrorCode\n\tvar found bool\n\tswitch getRequestAuthType(r) {\n\tcase authTypeStreamingSigned:\n\t\treturn identity, s3err.ErrNone\n\tcase authTypeUnknown:\n\t\tglog.V(3).Infof(\"unknown auth type\")\n\t\treturn identity, s3err.ErrAccessDenied\n\tcase authTypePresignedV2, authTypeSignedV2:\n\t\tglog.V(3).Infof(\"v2 auth type\")\n\t\tidentity, s3Err = iam.isReqAuthenticatedV2(r)\n\tcase authTypeSigned, authTypePresigned:\n\t\tglog.V(3).Infof(\"v4 auth type\")\n\t\tidentity, s3Err = iam.reqSignatureV4Verify(r)\n\tcase authTypePostPolicy:\n\t\tglog.V(3).Infof(\"post policy auth type\")\n\t\treturn identity, s3err.ErrNone\n\tcase authTypeJWT:\n\t\tglog.V(3).Infof(\"jwt auth type\")\n\t\treturn identity, s3err.ErrNotImplemented\n\tcase authTypeAnonymous:\n\t\tidentity, found = iam.lookupAnonymous()\n\t\tif !found {\n\t\t\treturn identity, s3err.ErrAccessDenied\n\t\t}\n\tdefault:\n\t\treturn identity, s3err.ErrNotImplemented\n\t}\n\n\tglog.V(3).Infof(\"auth error: %v\", s3Err)\n\tif s3Err != s3err.ErrNone {\n\t\treturn identity, s3Err\n\t}\n\treturn identity, s3err.ErrNone\n}\n\nfunc (identity *Identity) canDo(action Action, bucket string) bool {\n\tif identity.isAdmin() {\n\t\treturn true\n\t}\n\tfor _, a := range identity.Actions {\n\t\tif a == action {\n\t\t\treturn true\n\t\t}\n\t}\n\tif bucket == \"\" {\n\t\treturn false\n\t}\n\tlimitedByBucket := string(action) + \":\" + bucket\n\tadminLimitedByBucket := s3_constants.ACTION_ADMIN + \":\" + bucket\n\tfor _, a := range identity.Actions {\n\t\tact := string(a)\n\t\tif strings.HasSuffix(act, \"*\") {\n\t\t\tif strings.HasPrefix(limitedByBucket, act[:len(act)-1]) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif strings.HasPrefix(adminLimitedByBucket, act[:len(act)-1]) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else {\n\t\t\tif act == limitedByBucket {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif act == adminLimitedByBucket {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (identity *Identity) isAdmin() bool {\n\tfor _, a := range identity.Actions {\n\t\tif a == \"Admin\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>log unknown access key<commit_after>package s3api\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/filer\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/filer_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/iam_pb\"\n\txhttp \"github.com\/chrislusf\/seaweedfs\/weed\/s3api\/http\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/s3api\/s3_constants\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/s3api\/s3err\"\n)\n\ntype Action string\n\ntype Iam interface {\n\tCheck(f http.HandlerFunc, actions ...Action) http.HandlerFunc\n}\n\ntype IdentityAccessManagement struct {\n\tidentities []*Identity\n\tdomain     string\n}\n\ntype Identity struct {\n\tName        string\n\tCredentials []*Credential\n\tActions     []Action\n}\n\ntype Credential struct {\n\tAccessKey string\n\tSecretKey string\n}\n\nfunc (action Action) isAdmin() bool {\n\treturn strings.HasPrefix(string(action), s3_constants.ACTION_ADMIN)\n}\n\nfunc (action Action) isOwner(bucket string) bool {\n\treturn string(action) == s3_constants.ACTION_ADMIN+\":\"+bucket\n}\n\nfunc (action Action) overBucket(bucket string) bool {\n\treturn strings.HasSuffix(string(action), \":\"+bucket) || strings.HasSuffix(string(action), \":*\")\n}\n\nfunc (action Action) getPermission() Permission {\n\tswitch act := strings.Split(string(action), \":\")[0]; act {\n\tcase s3_constants.ACTION_ADMIN:\n\t\treturn Permission(\"FULL_CONTROL\")\n\tcase s3_constants.ACTION_WRITE:\n\t\treturn Permission(\"WRITE\")\n\tcase s3_constants.ACTION_READ:\n\t\treturn Permission(\"READ\")\n\tdefault:\n\t\treturn Permission(\"\")\n\t}\n}\n\nfunc NewIdentityAccessManagement(option *S3ApiServerOption) *IdentityAccessManagement {\n\tiam := &IdentityAccessManagement{\n\t\tdomain: option.DomainName,\n\t}\n\tif option.Config != \"\" {\n\t\tif err := iam.loadS3ApiConfigurationFromFile(option.Config); err != nil {\n\t\t\tglog.Fatalf(\"fail to load config file %s: %v\", option.Config, err)\n\t\t}\n\t} else {\n\t\tif err := iam.loadS3ApiConfigurationFromFiler(option); err != nil {\n\t\t\tglog.Warningf(\"fail to load config: %v\", err)\n\t\t}\n\t}\n\treturn iam\n}\n\nfunc (iam *IdentityAccessManagement) loadS3ApiConfigurationFromFiler(option *S3ApiServerOption) (err error) {\n\tvar content []byte\n\terr = pb.WithFilerClient(option.Filer, option.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {\n\t\tcontent, err = filer.ReadInsideFiler(client, filer.IamConfigDirecotry, filer.IamIdentityFile)\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"read S3 config: %v\", err)\n\t}\n\treturn iam.loadS3ApiConfigurationFromBytes(content)\n}\n\nfunc (iam *IdentityAccessManagement) loadS3ApiConfigurationFromFile(fileName string) error {\n\tcontent, readErr := os.ReadFile(fileName)\n\tif readErr != nil {\n\t\tglog.Warningf(\"fail to read %s : %v\", fileName, readErr)\n\t\treturn fmt.Errorf(\"fail to read %s : %v\", fileName, readErr)\n\t}\n\treturn iam.loadS3ApiConfigurationFromBytes(content)\n}\n\nfunc (iam *IdentityAccessManagement) loadS3ApiConfigurationFromBytes(content []byte) error {\n\ts3ApiConfiguration := &iam_pb.S3ApiConfiguration{}\n\tif err := filer.ParseS3ConfigurationFromBytes(content, s3ApiConfiguration); err != nil {\n\t\tglog.Warningf(\"unmarshal error: %v\", err)\n\t\treturn fmt.Errorf(\"unmarshal error: %v\", err)\n\t}\n\tif err := iam.loadS3ApiConfiguration(s3ApiConfiguration); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (iam *IdentityAccessManagement) loadS3ApiConfiguration(config *iam_pb.S3ApiConfiguration) error {\n\tvar identities []*Identity\n\tfor _, ident := range config.Identities {\n\t\tt := &Identity{\n\t\t\tName:        ident.Name,\n\t\t\tCredentials: nil,\n\t\t\tActions:     nil,\n\t\t}\n\t\tfor _, action := range ident.Actions {\n\t\t\tt.Actions = append(t.Actions, Action(action))\n\t\t}\n\t\tfor _, cred := range ident.Credentials {\n\t\t\tt.Credentials = append(t.Credentials, &Credential{\n\t\t\t\tAccessKey: cred.AccessKey,\n\t\t\t\tSecretKey: cred.SecretKey,\n\t\t\t})\n\t\t}\n\t\tidentities = append(identities, t)\n\t}\n\n\t\/\/ atomically switch\n\tiam.identities = identities\n\treturn nil\n}\n\nfunc (iam *IdentityAccessManagement) isEnabled() bool {\n\n\treturn len(iam.identities) > 0\n}\n\nfunc (iam *IdentityAccessManagement) lookupByAccessKey(accessKey string) (identity *Identity, cred *Credential, found bool) {\n\n\tfor _, ident := range iam.identities {\n\t\tfor _, cred := range ident.Credentials {\n\t\t\tprintln(\"checking\", ident.Name, cred.AccessKey)\n\t\t\tif cred.AccessKey == accessKey {\n\t\t\t\treturn ident, cred, true\n\t\t\t}\n\t\t}\n\t}\n\tglog.V(1).Infof(\"could not find accessKey %s\", accessKey)\n\treturn nil, nil, false\n}\n\nfunc (iam *IdentityAccessManagement) lookupAnonymous() (identity *Identity, found bool) {\n\n\tfor _, ident := range iam.identities {\n\t\tif ident.Name == \"anonymous\" {\n\t\t\treturn ident, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, action Action) http.HandlerFunc {\n\n\tif !iam.isEnabled() {\n\t\treturn f\n\t}\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tidentity, errCode := iam.authRequest(r, action)\n\t\tif errCode == s3err.ErrNone {\n\t\t\tif identity != nil && identity.Name != \"\" {\n\t\t\t\tr.Header.Set(xhttp.AmzIdentityId, identity.Name)\n\t\t\t\tif identity.isAdmin() {\n\t\t\t\t\tr.Header.Set(xhttp.AmzIsAdmin, \"true\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tf(w, r)\n\t\t\treturn\n\t\t}\n\t\ts3err.WriteErrorResponse(w, r, errCode)\n\t}\n}\n\n\/\/ check whether the request has valid access keys\nfunc (iam *IdentityAccessManagement) authRequest(r *http.Request, action Action) (*Identity, s3err.ErrorCode) {\n\tvar identity *Identity\n\tvar s3Err s3err.ErrorCode\n\tvar found bool\n\tswitch getRequestAuthType(r) {\n\tcase authTypeStreamingSigned:\n\t\treturn identity, s3err.ErrNone\n\tcase authTypeUnknown:\n\t\tglog.V(3).Infof(\"unknown auth type\")\n\t\treturn identity, s3err.ErrAccessDenied\n\tcase authTypePresignedV2, authTypeSignedV2:\n\t\tglog.V(3).Infof(\"v2 auth type\")\n\t\tidentity, s3Err = iam.isReqAuthenticatedV2(r)\n\tcase authTypeSigned, authTypePresigned:\n\t\tglog.V(3).Infof(\"v4 auth type\")\n\t\tidentity, s3Err = iam.reqSignatureV4Verify(r)\n\tcase authTypePostPolicy:\n\t\tglog.V(3).Infof(\"post policy auth type\")\n\t\treturn identity, s3err.ErrNone\n\tcase authTypeJWT:\n\t\tglog.V(3).Infof(\"jwt auth type\")\n\t\treturn identity, s3err.ErrNotImplemented\n\tcase authTypeAnonymous:\n\t\tidentity, found = iam.lookupAnonymous()\n\t\tif !found {\n\t\t\treturn identity, s3err.ErrAccessDenied\n\t\t}\n\tdefault:\n\t\treturn identity, s3err.ErrNotImplemented\n\t}\n\n\tif s3Err != s3err.ErrNone {\n\t\treturn identity, s3Err\n\t}\n\n\tglog.V(3).Infof(\"user name: %v actions: %v, action: %v\", identity.Name, identity.Actions, action)\n\n\tbucket, _ := getBucketAndObject(r)\n\n\tif !identity.canDo(action, bucket) {\n\t\treturn identity, s3err.ErrAccessDenied\n\t}\n\n\treturn identity, s3err.ErrNone\n\n}\n\nfunc (iam *IdentityAccessManagement) authUser(r *http.Request) (*Identity, s3err.ErrorCode) {\n\tvar identity *Identity\n\tvar s3Err s3err.ErrorCode\n\tvar found bool\n\tswitch getRequestAuthType(r) {\n\tcase authTypeStreamingSigned:\n\t\treturn identity, s3err.ErrNone\n\tcase authTypeUnknown:\n\t\tglog.V(3).Infof(\"unknown auth type\")\n\t\treturn identity, s3err.ErrAccessDenied\n\tcase authTypePresignedV2, authTypeSignedV2:\n\t\tglog.V(3).Infof(\"v2 auth type\")\n\t\tidentity, s3Err = iam.isReqAuthenticatedV2(r)\n\tcase authTypeSigned, authTypePresigned:\n\t\tglog.V(3).Infof(\"v4 auth type\")\n\t\tidentity, s3Err = iam.reqSignatureV4Verify(r)\n\tcase authTypePostPolicy:\n\t\tglog.V(3).Infof(\"post policy auth type\")\n\t\treturn identity, s3err.ErrNone\n\tcase authTypeJWT:\n\t\tglog.V(3).Infof(\"jwt auth type\")\n\t\treturn identity, s3err.ErrNotImplemented\n\tcase authTypeAnonymous:\n\t\tidentity, found = iam.lookupAnonymous()\n\t\tif !found {\n\t\t\treturn identity, s3err.ErrAccessDenied\n\t\t}\n\tdefault:\n\t\treturn identity, s3err.ErrNotImplemented\n\t}\n\n\tglog.V(3).Infof(\"auth error: %v\", s3Err)\n\tif s3Err != s3err.ErrNone {\n\t\treturn identity, s3Err\n\t}\n\treturn identity, s3err.ErrNone\n}\n\nfunc (identity *Identity) canDo(action Action, bucket string) bool {\n\tif identity.isAdmin() {\n\t\treturn true\n\t}\n\tfor _, a := range identity.Actions {\n\t\tif a == action {\n\t\t\treturn true\n\t\t}\n\t}\n\tif bucket == \"\" {\n\t\treturn false\n\t}\n\tlimitedByBucket := string(action) + \":\" + bucket\n\tadminLimitedByBucket := s3_constants.ACTION_ADMIN + \":\" + bucket\n\tfor _, a := range identity.Actions {\n\t\tact := string(a)\n\t\tif strings.HasSuffix(act, \"*\") {\n\t\t\tif strings.HasPrefix(limitedByBucket, act[:len(act)-1]) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif strings.HasPrefix(adminLimitedByBucket, act[:len(act)-1]) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t} else {\n\t\t\tif act == limitedByBucket {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif act == adminLimitedByBucket {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (identity *Identity) isAdmin() bool {\n\tfor _, a := range identity.Actions {\n\t\tif a == \"Admin\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package shell\n\nimport (\n\t\"context\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/master_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/wdclient\"\n)\n\nconst (\n\tRenewInteval     = 4 * time.Second\n\tSafeRenewInteval = 3 * time.Second\n\tInitLockInteval  = 1 * time.Second\n)\n\ntype ExclusiveLocker struct {\n\tmasterClient *wdclient.MasterClient\n\ttoken        int64\n\tlockTsNs     int64\n\tisLocking    bool\n}\n\nfunc NewExclusiveLocker(masterClient *wdclient.MasterClient) *ExclusiveLocker {\n\treturn &ExclusiveLocker{\n\t\tmasterClient: masterClient,\n\t}\n}\n\nfunc (l *ExclusiveLocker) GetToken() (token int64, lockTsNs int64) {\n\tfor time.Unix(0, atomic.LoadInt64(&l.lockTsNs)).Add(SafeRenewInteval).Before(time.Now()) {\n\t\t\/\/ wait until now is within the safe lock period, no immediate renewal to change the token\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\treturn atomic.LoadInt64(&l.token), atomic.LoadInt64(&l.lockTsNs)\n}\n\nfunc (l *ExclusiveLocker) RequestLock() {\n\t\/\/ retry to get the lease\n\tfor {\n\t\tif err := l.masterClient.WithClient(func(client master_pb.SeaweedClient) error {\n\t\t\tresp, err := client.LeaseAdminToken(context.Background(), &master_pb.LeaseAdminTokenRequest{})\n\t\t\tif err == nil {\n\t\t\t\tatomic.StoreInt64(&l.token, resp.Token)\n\t\t\t\tatomic.StoreInt64(&l.lockTsNs, resp.LockTsNs)\n\t\t\t}\n\t\t\treturn err\n\t\t}); err != nil {\n\t\t\t\/\/ println(\"leasing problem\", err.Error())\n\t\t\ttime.Sleep(InitLockInteval)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tl.isLocking = true\n\n\t\/\/ start a goroutine to renew the lease\n\tgo func() {\n\t\tfor l.isLocking {\n\t\t\tif err := l.masterClient.WithClient(func(client master_pb.SeaweedClient) error {\n\t\t\t\tresp, err := client.LeaseAdminToken(context.Background(), &master_pb.LeaseAdminTokenRequest{\n\t\t\t\t\tPreviousToken:    atomic.LoadInt64(&l.token),\n\t\t\t\t\tPreviousLockTime: atomic.LoadInt64(&l.lockTsNs),\n\t\t\t\t})\n\t\t\t\tif err == nil {\n\t\t\t\t\tatomic.StoreInt64(&l.token, resp.Token)\n\t\t\t\t\tatomic.StoreInt64(&l.lockTsNs, resp.LockTsNs)\n\t\t\t\t\t\/\/ println(\"ts\", l.lockTsNs, \"token\", l.token)\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}); err != nil {\n\t\t\t\tglog.Error(\"failed to renew lock: %v\", err)\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\ttime.Sleep(RenewInteval)\n\t\t\t}\n\n\t\t}\n\t}()\n\n}\n\nfunc (l *ExclusiveLocker) ReleaseLock() {\n\tl.isLocking = false\n\tl.masterClient.WithClient(func(client master_pb.SeaweedClient) error {\n\t\tclient.ReleaseAdminToken(context.Background(), &master_pb.ReleaseAdminTokenRequest{\n\t\t\tPreviousToken:    atomic.LoadInt64(&l.token),\n\t\t\tPreviousLockTime: atomic.LoadInt64(&l.lockTsNs),\n\t\t})\n\t\treturn nil\n\t})\n\tatomic.StoreInt64(&l.token, 0)\n\tatomic.StoreInt64(&l.lockTsNs, 0)\n}\n<commit_msg>allow lock with an existing lock<commit_after>package shell\n\nimport (\n\t\"context\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/master_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/wdclient\"\n)\n\nconst (\n\tRenewInteval     = 4 * time.Second\n\tSafeRenewInteval = 3 * time.Second\n\tInitLockInteval  = 1 * time.Second\n)\n\ntype ExclusiveLocker struct {\n\tmasterClient *wdclient.MasterClient\n\ttoken        int64\n\tlockTsNs     int64\n\tisLocking    bool\n}\n\nfunc NewExclusiveLocker(masterClient *wdclient.MasterClient) *ExclusiveLocker {\n\treturn &ExclusiveLocker{\n\t\tmasterClient: masterClient,\n\t}\n}\n\nfunc (l *ExclusiveLocker) GetToken() (token int64, lockTsNs int64) {\n\tfor time.Unix(0, atomic.LoadInt64(&l.lockTsNs)).Add(SafeRenewInteval).Before(time.Now()) {\n\t\t\/\/ wait until now is within the safe lock period, no immediate renewal to change the token\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\treturn atomic.LoadInt64(&l.token), atomic.LoadInt64(&l.lockTsNs)\n}\n\nfunc (l *ExclusiveLocker) RequestLock() {\n\t\/\/ retry to get the lease\n\tfor {\n\t\tif err := l.masterClient.WithClient(func(client master_pb.SeaweedClient) error {\n\t\t\tresp, err := client.LeaseAdminToken(context.Background(), &master_pb.LeaseAdminTokenRequest{\n\t\t\t\tPreviousToken:    atomic.LoadInt64(&l.token),\n\t\t\t\tPreviousLockTime: atomic.LoadInt64(&l.lockTsNs),\n\t\t\t})\n\t\t\tif err == nil {\n\t\t\t\tatomic.StoreInt64(&l.token, resp.Token)\n\t\t\t\tatomic.StoreInt64(&l.lockTsNs, resp.LockTsNs)\n\t\t\t}\n\t\t\treturn err\n\t\t}); err != nil {\n\t\t\t\/\/ println(\"leasing problem\", err.Error())\n\t\t\ttime.Sleep(InitLockInteval)\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tl.isLocking = true\n\n\t\/\/ start a goroutine to renew the lease\n\tgo func() {\n\t\tfor l.isLocking {\n\t\t\tif err := l.masterClient.WithClient(func(client master_pb.SeaweedClient) error {\n\t\t\t\tresp, err := client.LeaseAdminToken(context.Background(), &master_pb.LeaseAdminTokenRequest{\n\t\t\t\t\tPreviousToken:    atomic.LoadInt64(&l.token),\n\t\t\t\t\tPreviousLockTime: atomic.LoadInt64(&l.lockTsNs),\n\t\t\t\t})\n\t\t\t\tif err == nil {\n\t\t\t\t\tatomic.StoreInt64(&l.token, resp.Token)\n\t\t\t\t\tatomic.StoreInt64(&l.lockTsNs, resp.LockTsNs)\n\t\t\t\t\t\/\/ println(\"ts\", l.lockTsNs, \"token\", l.token)\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}); err != nil {\n\t\t\t\tglog.Error(\"failed to renew lock: %v\", err)\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\ttime.Sleep(RenewInteval)\n\t\t\t}\n\n\t\t}\n\t}()\n\n}\n\nfunc (l *ExclusiveLocker) ReleaseLock() {\n\tl.isLocking = false\n\tl.masterClient.WithClient(func(client master_pb.SeaweedClient) error {\n\t\tclient.ReleaseAdminToken(context.Background(), &master_pb.ReleaseAdminTokenRequest{\n\t\t\tPreviousToken:    atomic.LoadInt64(&l.token),\n\t\t\tPreviousLockTime: atomic.LoadInt64(&l.lockTsNs),\n\t\t})\n\t\treturn nil\n\t})\n\tatomic.StoreInt64(&l.token, 0)\n\tatomic.StoreInt64(&l.lockTsNs, 0)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n\/\/ Functions main purpose is to break a large program into a number of smaller\n\/\/ tasks (functions). It also helps enforce the D-R-Y (dont repeat yourself)\n\/\/ principle, the same task can be invoked several times, so a function promotes code reuse.\n\n\/\/ There are 3 types of functions in Go:\n\/\/ - Normal functions with an identifier\n\/\/ - Anonymous or lamda functions\n\/\/ - Methods\n\n\/\/ Any of these can have parameters and return values. The definition of all the\n\/\/ function parameters and return values, together with their types, is called\n\/\/ the function signature.\n\n\/\/ The function main is special, go programs begins execution in the function\n\/\/ named main located in package main.\n\nfunc main() {\n\n\t\/\/ You invoke the function by specifying the name of the package it is\n\t\/\/ defined in followed by a . (dot) followed by the name of the function\n\t\/\/ and any parameters within a set of parantheses.\n\t\/\/ However if the function is defined in the current package then it can\n\t\/\/ be invoked by referring to its name and providing the values for\n\t\/\/ all defined parameters, if any.\n\tGreet()\n\n\tx, y := 1, 2\n\t\/\/ You can capture the returned value either assigning it to a variable or\n\t\/\/ passing it as argument to another function\n\tr := add(x, y)\n\tfmt.Printf(\"The sum of %d and %d is %d\\n\", x, y, r)\n\n\tnumr, denom := 3, 0\n\tquot, err := divide(numr, denom)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t} else {\n\t\tfmt.Printf(\"Result of %d \/ %d is %d\\n\", numr, denom, quot)\n\t}\n\n\t\/\/ One or more returned values can be discarded using the blank identifier _ (underscore)\n\n\t\/\/ When would this be useful?\n\t\/\/ Recall that its illegal to declare a variable and not use it. Now suppose\n\t\/\/ you have function that you wrote or calling a function defined in some\n\t\/\/ package, but you do not want to consume one or more returned values.\n\t\/\/ The only way out, is to use the blank indentifier.\n\n\t\/\/ For example here the second retured value error is being discarded\n\t\/\/ NOTE: Its considered bad parctice to ignore errors. Please dont do this in normal code.\n\t\/\/ I am ignoring the error returned only to demonstrate how to discard one or more returned values.\n\tq, _ := divide(numr, denom)\n\tfmt.Printf(\"Result of %d \/ %d is %d\\n\", numr, denom, q)\n\n\t\/\/ call the variadic function sum\n\tn := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}\n\t\/\/ n... is the shorthand to pass each element of the slice to the function\n\ts := sum(\"Sum of input number is:\", n...)\n\tfmt.Printf(\"%s\", s)\n\n\t\/\/ call recursive function\n\tfmt.Printf(\"Fibonacci of 10 is %d\\n\", fibonacci(10))\n\n\t\/\/ A function that does not have a name is called anonymous function\n\t\/\/ (also known under the names of a lambda function, a function literal, or a closure).\n\t\/\/ Such a function cannot stand on its own, since complier would throw an error.\n\t\/\/ Hence such functions  must be either assigned to variable or must be\n\t\/\/ directly invoked or returned as output value of a named function\n\n\t\/\/ The variable prod's value is a function that returns product of the passed numbers\n\tprod := func(x, y int) int {\n\t\treturn x * y\n\t}\n\tfmt.Printf(\"%d * %d = %d\\n\", x, y, prod(x, y))\n\n\t\/\/ To directly invoke an anonymous function, put pair of () after the closing\n\t\/\/ '}' brackets within which we can list the optional parameters to the function.\n\tfunc(x, y int) {\n\t\tfmt.Printf(\"%d %% %d = %d\\n\", x, y, x%y)\n\t}(4, 2) \/\/ 4,2 are the parameters to the anonymous function\n}\n\n\/\/ The keyword func introduces a function\n\/\/ A function can take zero or more paramaters\n\/\/ One of the functions parameters can accept arbitary number of values\n\/\/ A function can return zero or more values, unlike other languages\n\/\/ A function can take other function as paramters or return functions as return values\n\/\/ A function which starts with capital\/uppercase letter is exported (visible\/accessible from other packages)\n\/\/ The order in which functions are defined in go source file is of no\n\/\/ consequence, however it is idiomatic to define the main function as first function.\n\n\/\/ Greet is a function that take no paraters and returns no values. Notice this\n\/\/ function start with capital letter hence it is said to be a exported function.\nfunc Greet() {\n\tfmt.Printf(\"Hello how are you?\\n\")\n}\n\n\/\/ add is a function that take two parameters of type int and return a single\n\/\/ value of the type int. Notice this function start with lowercase letter hence\n\/\/ it is said to be un-exported function.\nfunc add(x, y int) int {\n\treturn x + y\n}\n\nvar ErrDivideByZero = errors.New(\"Division by zero is not allowed\")\n\n\/\/ A function can return one or more values. This forms very foundations of Go's error\n\/\/ handling machinary, since unlike other languages go does not support exception handling\nfunc divide(x, y int) (int, error) {\n\tif y == 0 {\n\t\treturn 0, ErrDivideByZero\n\t}\n\treturn x \/ y, nil\n}\n\n\/\/ A function parameter can accept arbitary number of values. Such functions are\n\/\/ called as variadic functions. A variadic parameter is prefixed by ... (three asterisks)\n\/\/ to its type. There can only be one such parameter. If a function happens to take\n\/\/ more than one parameter, then the parameter that accepts multiple values\n\/\/ must be the last one. The following example show one such function.\n\/\/ The value of the variadic parameter is accessible as a slice within the\n\/\/ function body, which are be iterated over using the for..range loop\nfunc sum(title string, nums ...int) string {\n\tfmt.Printf(\"Data type of nums is %T\\n\", nums)\n\ts := 0\n\tfor _, v := range nums {\n\t\ts += v\n\t}\n\treturn fmt.Sprintf(\"%s %d\\n\", title, s)\n}\n\n\/\/ A function that calls itself in the body of the function is called a recursive function.\nfunc fibonacci(num int) int {\n\tif num == 0 {\n\t\treturn 0\n\t} else if num == 1 {\n\t\treturn 1\n\t}\n\n\treturn fibonacci(num-1) + fibonacci(num-2)\n}\n<commit_msg>add named return<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n\/\/ Functions main purpose is to break a large program into a number of smaller\n\/\/ tasks (functions). It also helps enforce the D-R-Y (dont repeat yourself)\n\/\/ principle, the same task can be invoked several times, so a function promotes code reuse.\n\n\/\/ There are 3 types of functions in Go:\n\/\/ - Normal functions with an identifier\n\/\/ - Anonymous or lamda functions\n\/\/ - Methods\n\n\/\/ Any of these can have parameters and return values. The definition of all the\n\/\/ function parameters and return values, together with their types, is called\n\/\/ the function signature.\n\n\/\/ The function main is special, go programs begins execution in the function\n\/\/ named main located in package main.\n\nfunc main() {\n\n\t\/\/ You invoke the function by specifying the name of the package it is\n\t\/\/ defined in followed by a . (dot) followed by the name of the function\n\t\/\/ and any parameters within a set of parantheses.\n\t\/\/ However if the function is defined in the current package then it can\n\t\/\/ be invoked by referring to its name and providing the values for\n\t\/\/ all defined parameters, if any.\n\tGreet()\n\n\tx, y := 1, 2\n\t\/\/ You can capture the returned value either assigning it to a variable or\n\t\/\/ passing it as argument to another function\n\tr := add(x, y)\n\tfmt.Printf(\"The sum of %d and %d is %d\\n\", x, y, r)\n\n\tnumr, denom := 3, 0\n\tquot, err := divide(numr, denom)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t} else {\n\t\tfmt.Printf(\"Result of %d \/ %d is %d\\n\", numr, denom, quot)\n\t}\n\n\t\/\/ One or more returned values can be discarded using the blank identifier _ (underscore)\n\n\t\/\/ When would this be useful?\n\t\/\/ Recall that its illegal to declare a variable and not use it. Now suppose\n\t\/\/ you have function that you wrote or calling a function defined in some\n\t\/\/ package, but you do not want to consume one or more returned values.\n\t\/\/ The only way out, is to use the blank indentifier.\n\n\t\/\/ For example here the second retured value error is being discarded\n\t\/\/ NOTE: Its considered bad parctice to ignore errors. Please dont do this in normal code.\n\t\/\/ I am ignoring the error returned only to demonstrate how to discard one or more returned values.\n\tq, _ := divide(numr, denom)\n\tfmt.Printf(\"Result of %d \/ %d is %d\\n\", numr, denom, q)\n\n\t\/\/ call the variadic function sum\n\tn := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}\n\t\/\/ n... is the shorthand to pass each element of the slice to the function\n\ts := sum(\"Sum of input number is:\", n...)\n\tfmt.Printf(\"%s\", s)\n\n\t\/\/ call recursive function\n\tfmt.Printf(\"Fibonacci of 10 is %d\\n\", fibonacci(10))\n\n\t\/\/ A function that does not have a name is called anonymous function\n\t\/\/ (also known under the names of a lambda function, a function literal, or a closure).\n\t\/\/ Such a function cannot stand on its own, since complier would throw an error.\n\t\/\/ Hence such functions  must be either assigned to variable or must be\n\t\/\/ directly invoked or returned as output value of a named function\n\n\t\/\/ The variable prod's value is a function that returns product of the passed numbers\n\tprod := func(x, y int) int {\n\t\treturn x * y\n\t}\n\tfmt.Printf(\"%d * %d = %d\\n\", x, y, prod(x, y))\n\n\t\/\/ To directly invoke an anonymous function, put pair of () after the closing\n\t\/\/ '}' brackets within which we can list the optional parameters to the function.\n\tfunc(x, y int) {\n\t\tfmt.Printf(\"%d %% %d = %d\\n\", x, y, x%y)\n\t}(4, 2) \/\/ 4,2 are the parameters to the anonymous function\n}\n\n\/\/ The keyword func introduces a function\n\/\/ A function can take zero or more paramaters\n\/\/ One of the functions parameters can accept arbitary number of values\n\/\/ A function can return zero or more values, unlike other languages\n\/\/ A function can take other function as paramters or return functions as return values\n\/\/ A function which starts with capital\/uppercase letter is exported (visible\/accessible from other packages)\n\/\/ The order in which functions are defined in go source file is of no\n\/\/ consequence, however it is idiomatic to define the main function as first function.\n\n\/\/ Greet is a function that take no paraters and returns no values. Notice this\n\/\/ function start with capital letter hence it is said to be a exported function.\nfunc Greet() {\n\tfmt.Printf(\"Hello how are you?\\n\")\n}\n\n\/\/ add is a function that take two parameters of type int and return a single\n\/\/ value of the type int. Notice this function start with lowercase letter hence\n\/\/ it is said to be un-exported function.\nfunc add(x, y int) int {\n\treturn x + y\n}\n\nvar ErrDivideByZero = errors.New(\"Division by zero is not allowed\")\n\n\/\/ A function can return one or more values. This forms very foundations of Go's error\n\/\/ handling machinary, since unlike other languages go does not support exception handling\n\/\/ NOTE: If you have more than one returned value then they must enclosed in set of parens\nfunc divide(x, y int) (int, error) {\n\tif y == 0 {\n\t\treturn 0, ErrDivideByZero\n\t}\n\treturn x \/ y, nil\n}\n\n\/\/ A function parameter can accept arbitary number of values. Such functions are\n\/\/ called as variadic functions. A variadic parameter is prefixed by ... (three asterisks)\n\/\/ to its type. There can only be one such parameter. If a function happens to take\n\/\/ more than one parameter, then the parameter that accepts multiple values\n\/\/ must be the last one. The following example show one such function.\n\/\/ The value of the variadic parameter is accessible as a slice within the\n\/\/ function body, which are be iterated over using the for..range loop\nfunc sum(title string, nums ...int) string {\n\tfmt.Printf(\"Data type of nums is %T\\n\", nums)\n\ts := 0\n\tfor _, v := range nums {\n\t\ts += v\n\t}\n\treturn fmt.Sprintf(\"%s %d\\n\", title, s)\n}\n\n\/\/ A function that calls itself in the body of the function is called a recursive function.\nfunc fibonacci(num int) int {\n\tif num == 0 {\n\t\treturn 0\n\t} else if num == 1 {\n\t\treturn 1\n\t}\n\n\treturn fibonacci(num-1) + fibonacci(num-2)\n}\n\n\/\/ A function can have named return values, in which case you can named naked retrun\n\/\/ statement. The last computed value of the variable would be retuned when the\n\/\/ function exits\nfunc IsEven(n int) (result bool) {\n\tresult = false\n\tif n%2 == 0 {\n\t\tresult = true\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/joyrexus\/buckets\"\n\t\"github.com\/julienschmidt\/httprouter\"\n)\n\nconst verbose = false \/\/ if `true` you'll see log output\n\nfunc main() {\n\t\/\/ Open a buckets database.\n\tbx, err := buckets.Open(tempFilePath())\n\tif err != nil {\n\t\tlog.Fatalf(\"couldn't open db: %v\", err)\n\t}\n\n\t\/\/ Delete and close the db when done.\n\tdefer os.Remove(bx.Path())\n\tdefer bx.Close()\n\n\t\/\/ Create a bucket for storing todos.\n\tbucket, err := bx.New([]byte(\"todos\"))\n\tif err != nil {\n\t\tlog.Fatalf(\"couldn't create todos bucket: %v\", err)\n\t}\n\n\t\/\/ Initialize our controller for handling specific routes.\n\tcontrol := NewController(bucket)\n\n\t\/\/ Create and setup our router.\n\trouter := httprouter.New()\n\trouter.POST(\"\/day\/:day\", control.post)\n\trouter.GET(\"\/day\/:day\", control.getDayTasks)\n\trouter.GET(\"\/weekend\", control.getWeekendTasks)\n\trouter.GET(\"\/weekdays\", control.getWeekdayTasks)\n\n\t\/\/ Start our web server.\n\tsrv := httptest.NewServer(router)\n\tdefer srv.Close()\n\n\t\/\/ Setup daily todos for client to post.\n\tposts := []*Todo{\n\t\t&Todo{Day: \"mon\", Task: \"milk cows\"},\n\t\t&Todo{Day: \"mon\", Task: \"feed cows\"},\n\t\t&Todo{Day: \"mon\", Task: \"wash cows\"},\n\t\t&Todo{Day: \"tue\", Task: \"wash laundry\"},\n\t\t&Todo{Day: \"tue\", Task: \"fold laundry\"},\n\t\t&Todo{Day: \"tue\", Task: \"iron laundry\"},\n\t\t&Todo{Day: \"wed\", Task: \"flip burgers\"},\n\t\t&Todo{Day: \"thu\", Task: \"join army\"},\n\t\t&Todo{Day: \"fri\", Task: \"kill time\"},\n\t\t&Todo{Day: \"sat\", Task: \"have beer\"},\n\t\t&Todo{Day: \"sat\", Task: \"make merry\"},\n\t\t&Todo{Day: \"sun\", Task: \"take aspirin\"},\n\t\t&Todo{Day: \"sun\", Task: \"pray quietly\"},\n\t}\n\n\t\/\/ Create our client.\n\tclient := new(Client)\n\n\t\/\/ Use our client to post each daily todo.\n\tfor _, todo := range posts {\n\t\turl := srv.URL + \"\/day\/\" + todo.Day\n\t\tif err := client.post(url, todo); err != nil {\n\t\t\tfmt.Printf(\"client post error: %v\", err)\n\t\t}\n\t}\n\n\t\/\/ Now, let's try retrieving the persisted todos.\n\n\t\/\/ Get a list of tasks for each day.\n\tweek := []string{\"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\", \"sun\"}\n\tfmt.Println(\"daily tasks ...\")\n\tfor _, day := range week {\n\t\turl := srv.URL + \"\/day\/\" + day\n\t\ttasks, err := client.get(url)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"client get error: %v\", err)\n\t\t}\n\t\tfmt.Printf(\"  %s: %s\\n\", day, tasks)\n\t}\n\t\/\/ Output:\n\t\/\/ daily tasks ...\n\t\/\/   mon: milk cows, feed cows, wash cows\n\t\/\/   tue: wash laundry, fold laundry, iron laundry\n\t\/\/   wed: flip burgers\n\t\/\/   thu: join army\n\t\/\/   fri: kill time\n\t\/\/   sat: have beer, make merry\n\t\/\/   sun: take aspirin, pray quietly\n\n\t\/\/ Get a list of combined tasks for weekdays.\n\ttasks, err := client.get(srv.URL + \"\/weekdays\")\n\tif err != nil {\n\t\tfmt.Printf(\"client get error: %v\", err)\n\t}\n\tfmt.Printf(\"\\nweekday tasks: %s\\n\", tasks)\n\t\/\/ Output:\n\t\/\/ weekday tasks: milk cows, feed cows, wash cows, wash laundry,\n\t\/\/ fold laundry, iron laundry, flip burgers, join army, kill time\n\n\t\/\/ Get a list of combined tasks for the weekend.\n\ttasks, err = client.get(srv.URL + \"\/weekend\")\n\tif err != nil {\n\t\tfmt.Printf(\"client get error: %v\", err)\n\t}\n\tfmt.Printf(\"\\nweekend tasks: %s\\n\", tasks)\n\t\/\/ Output:\n\t\/\/ weekend tasks: have beer, make merry, take aspirin, pray quietly\n}\n\n\/* -- MODELS --*\/\n\n\/\/ A Todo models a daily task.\ntype Todo struct {\n\tTask    string    \/\/ task to be done\n\tDay     string    \/\/ day to do task\n\tCreated time.Time \/\/ when created\n}\n\n\/\/ Encode marshals a Todo into a buffer.\nfunc (todo *Todo) Encode() (*bytes.Buffer, error) {\n\tb, err := json.Marshal(todo)\n\tif err != nil {\n\t\treturn &bytes.Buffer{}, err\n\t}\n\treturn bytes.NewBuffer(b), nil\n}\n\n\/\/ A TaskList is a list of tasks for a particular day.\ntype TaskList struct {\n\tWhen  string\n\tTasks []string\n}\n\n\/* -- CONTROLLER -- *\/\n\n\/\/ NewController initializes a new instance of our controller.\n\/\/ It provides handler methods for our router.\nfunc NewController(bk *buckets.Bucket) *Controller {\n\t\/\/ map of days to integers\n\tdaynum := map[string]int{\n\t\t\"mon\": 1, \/\/ monday is the first day of the week\n\t\t\"tue\": 2,\n\t\t\"wed\": 3,\n\t\t\"thu\": 4,\n\t\t\"fri\": 5,\n\t\t\"sat\": 6,\n\t\t\"sun\": 7,\n\t}\n\t\/\/ map of scanners for iterating over keys subsets of keys\n\tscan := map[string]buckets.Scanner{\n\t\t\"mon\": bk.NewPrefixScanner([]byte(\"1\")),\n\t\t\"tue\": bk.NewPrefixScanner([]byte(\"2\")),\n\t\t\"wed\": bk.NewPrefixScanner([]byte(\"3\")),\n\t\t\"thu\": bk.NewPrefixScanner([]byte(\"4\")),\n\t\t\"fri\": bk.NewPrefixScanner([]byte(\"5\")),\n\t\t\"sat\": bk.NewPrefixScanner([]byte(\"6\")),\n\t\t\"sun\": bk.NewPrefixScanner([]byte(\"7\")),\n\t\t\/\/ weekdays are mon to fri: 1 <= key < 6.\n\t\t\"weekday\": bk.NewRangeScanner([]byte(\"1\"), []byte(\"6\")),\n\t\t\/\/ weekends are sat to sun: 6 <= key < 8.\n\t\t\"weekend\": bk.NewRangeScanner([]byte(\"6\"), []byte(\"8\")),\n\t}\n\treturn &Controller{bk, daynum, scan}\n}\n\n\/\/ This Controller handles requests for todo items.  The items are stored\n\/\/ in a todos bucket.  The request URLs are used as bucket keys and the\n\/\/ raw json payload as values.\n\/\/\n\/\/ Note that since we're using `httprouter` (abbreviated as `mux` when\n\/\/ imported) as our router, each method is a `httprouter.Handle` rather\n\/\/ than a `http.HandlerFunc`.\ntype Controller struct {\n\ttodos  *buckets.Bucket\n\tdaynum map[string]int\n\tscan   map[string]buckets.Scanner\n}\n\n\/\/ getWeekendTasks handles get requests for `\/weekend`, returning the\n\/\/ combined task list for saturday and sunday.\n\/\/\n\/\/ Note how we utilize the RangeItems method, which makes it easy\n\/\/ to get items in our todos bucket with keys in a certain range \n\/\/ (6 <= key < 8), viz., the items for sat and sun.\nfunc (c *Controller) getWeekendTasks(w http.ResponseWriter, r *http.Request,\n\t_ httprouter.Params) {\n\n\t\/\/ Get todo items within the weekend range.\n\titems, err := c.todos.RangeItems([]byte(\"6\"), []byte(\"8\"))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t}\n\n\t\/\/ Generate a list of tasks based on todo items retrieved.\n\ttaskList := &TaskList{\"weekend\", []string{}}\n\n\tfor _, item := range items {\n\t\ttodo, err := decode(item.Value)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t}\n\t\ttaskList.Tasks = append(taskList.Tasks, todo.Task)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tjson.NewEncoder(w).Encode(taskList)\n}\n\n\/\/ getWeekdayTasks handles get requests for `\/weekdays`, returning the\n\/\/ combined task list for monday through friday.\n\/\/\n\/\/ Note how we utilize the RangeItems method, which makes it easy\n\/\/ to get items in our todos bucket with keys in a certain range \n\/\/ (1 <= key < 6), viz., the items for mon through fri.\nfunc (c *Controller) getWeekdayTasks(w http.ResponseWriter, r *http.Request,\n\t_ httprouter.Params) {\n\n\t\/\/ Get todo items within the weekday range.\n\titems, err := c.todos.RangeItems([]byte(\"1\"), []byte(\"6\"))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t}\n\n\t\/\/ Generate a list of tasks based on todo items retrieved.\n\ttaskList := &TaskList{\"weekdays\", []string{}}\n\n\tfor _, item := range items {\n\t\ttodo, err := decode(item.Value)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t}\n\t\ttaskList.Tasks = append(taskList.Tasks, todo.Task)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tjson.NewEncoder(w).Encode(taskList)\n}\n\n\/\/ getDayTasks handles get requests for `\/:day`, returning a particular\n\/\/ day's task list.\n\/\/\n\/\/ Note how we utilize the PrefixItems method for the day requested (as\n\/\/ indicated in the route's `day` parameter). This makes it easy to get \n\/\/ items in our todos bucket with a certain prefix, viz. those with the\n\/\/ prefix representing the requested day.\nfunc (c *Controller) getDayTasks(w http.ResponseWriter, r *http.Request,\n\tp httprouter.Params) {\n\n\t\/\/ Get todo items for the day requested.\n\tday := p.ByName(\"day\")\n\tnum := c.daynum[day]\n\tpre := []byte(strconv.Itoa(num)) \/\/ daynum prefix to use\n\titems, err := c.todos.PrefixItems(pre)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t}\n\n\t\/\/ Generate a list of tasks based on todo items retrieved.\n\ttaskList := &TaskList{day, []string{}}\n\n\tfor _, item := range items {\n\t\ttodo, err := decode(item.Value)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t}\n\t\ttaskList.Tasks = append(taskList.Tasks, todo.Task)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tjson.NewEncoder(w).Encode(taskList)\n}\n\n\/\/ post handles post requests to create a daily todo item.\n\/\/\n\/\/\nfunc (c *Controller) post(w http.ResponseWriter, r *http.Request,\n\tp httprouter.Params) {\n\n\t\/\/ Read request body's json payload into buffer.\n\tb, err := ioutil.ReadAll(r.Body)\n\ttodo, err := decode(b)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t}\n\n\t\/\/ Use the day number + creation time as key.\n\tday := p.ByName(\"day\")\n\tnum := c.daynum[day] \/\/ number of day of week\n\tcreated := todo.Created.Format(time.RFC3339Nano)\n\tkey := fmt.Sprintf(\"%d\/%s\", num, created)\n\n\t\/\/ Put key\/buffer into todos bucket.\n\tif err := c.todos.Put([]byte(key), b); err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\tif verbose {\n\t\tlog.Printf(\"server: %s: %v\", key, todo.Task)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text\/plain\")\n\tfmt.Fprintf(w, \"put todo for %s: %s\\n\", key, todo)\n}\n\n\/* -- CLIENT -- *\/\n\n\/\/ Our http client for sending requests.\ntype Client struct{}\n\n\/\/ post sends a post request with a json payload.\nfunc (c *Client) post(url string, todo *Todo) error {\n\ttodo.Created = time.Now()\n\tbodyType := \"application\/json\"\n\tbody, err := todo.Encode()\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := http.Post(url, bodyType, body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif verbose {\n\t\tlog.Printf(\"client: %s\\n\", resp.Status)\n\t}\n\treturn nil\n}\n\n\/\/ get sends get requests and expects responses to be a json-encoded\n\/\/ task list.\nfunc (c *Client) get(url string) (string, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\ttaskList := new(TaskList)\n\tif err = json.NewDecoder(resp.Body).Decode(taskList); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.Join(taskList.Tasks, \", \"), nil\n}\n\n\/* -- UTILITY FUNCTIONS, &c. -- *\/\n\n\/\/ decode unmarshals a json-encoded byteslice into a Todo.\nfunc decode(b []byte) (*Todo, error) {\n\ttodo := new(Todo)\n\tif err := json.Unmarshal(b, todo); err != nil {\n\t\treturn &Todo{}, err\n\t}\n\treturn todo, nil\n}\n\n\/\/ tempFilePath returns a temporary file path.\nfunc tempFilePath() string {\n\tf, _ := ioutil.TempFile(\"\", \"bolt-\")\n\tif err := f.Close(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := os.Remove(f.Name()); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn f.Name()\n}\n<commit_msg>remove map of scanners<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/joyrexus\/buckets\"\n\t\"github.com\/julienschmidt\/httprouter\"\n)\n\nconst verbose = false \/\/ if `true` you'll see log output\n\nfunc main() {\n\t\/\/ Open a buckets database.\n\tbx, err := buckets.Open(tempFilePath())\n\tif err != nil {\n\t\tlog.Fatalf(\"couldn't open db: %v\", err)\n\t}\n\n\t\/\/ Delete and close the db when done.\n\tdefer os.Remove(bx.Path())\n\tdefer bx.Close()\n\n\t\/\/ Create a bucket for storing todos.\n\tbucket, err := bx.New([]byte(\"todos\"))\n\tif err != nil {\n\t\tlog.Fatalf(\"couldn't create todos bucket: %v\", err)\n\t}\n\n\t\/\/ Initialize our controller for handling specific routes.\n\tcontrol := NewController(bucket)\n\n\t\/\/ Create and setup our router.\n\trouter := httprouter.New()\n\trouter.POST(\"\/day\/:day\", control.post)\n\trouter.GET(\"\/day\/:day\", control.getDayTasks)\n\trouter.GET(\"\/weekend\", control.getWeekendTasks)\n\trouter.GET(\"\/weekdays\", control.getWeekdayTasks)\n\n\t\/\/ Start our web server.\n\tsrv := httptest.NewServer(router)\n\tdefer srv.Close()\n\n\t\/\/ Setup daily todos for client to post.\n\tposts := []*Todo{\n\t\t&Todo{Day: \"mon\", Task: \"milk cows\"},\n\t\t&Todo{Day: \"mon\", Task: \"feed cows\"},\n\t\t&Todo{Day: \"mon\", Task: \"wash cows\"},\n\t\t&Todo{Day: \"tue\", Task: \"wash laundry\"},\n\t\t&Todo{Day: \"tue\", Task: \"fold laundry\"},\n\t\t&Todo{Day: \"tue\", Task: \"iron laundry\"},\n\t\t&Todo{Day: \"wed\", Task: \"flip burgers\"},\n\t\t&Todo{Day: \"thu\", Task: \"join army\"},\n\t\t&Todo{Day: \"fri\", Task: \"kill time\"},\n\t\t&Todo{Day: \"sat\", Task: \"have beer\"},\n\t\t&Todo{Day: \"sat\", Task: \"make merry\"},\n\t\t&Todo{Day: \"sun\", Task: \"take aspirin\"},\n\t\t&Todo{Day: \"sun\", Task: \"pray quietly\"},\n\t}\n\n\t\/\/ Create our client.\n\tclient := new(Client)\n\n\t\/\/ Use our client to post each daily todo.\n\tfor _, todo := range posts {\n\t\turl := srv.URL + \"\/day\/\" + todo.Day\n\t\tif err := client.post(url, todo); err != nil {\n\t\t\tfmt.Printf(\"client post error: %v\", err)\n\t\t}\n\t}\n\n\t\/\/ Now, let's try retrieving the persisted todos.\n\n\t\/\/ Get a list of tasks for each day.\n\tweek := []string{\"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\", \"sun\"}\n\tfmt.Println(\"daily tasks ...\")\n\tfor _, day := range week {\n\t\turl := srv.URL + \"\/day\/\" + day\n\t\ttasks, err := client.get(url)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"client get error: %v\", err)\n\t\t}\n\t\tfmt.Printf(\"  %s: %s\\n\", day, tasks)\n\t}\n\t\/\/ Output:\n\t\/\/ daily tasks ...\n\t\/\/   mon: milk cows, feed cows, wash cows\n\t\/\/   tue: wash laundry, fold laundry, iron laundry\n\t\/\/   wed: flip burgers\n\t\/\/   thu: join army\n\t\/\/   fri: kill time\n\t\/\/   sat: have beer, make merry\n\t\/\/   sun: take aspirin, pray quietly\n\n\t\/\/ Get a list of combined tasks for weekdays.\n\ttasks, err := client.get(srv.URL + \"\/weekdays\")\n\tif err != nil {\n\t\tfmt.Printf(\"client get error: %v\", err)\n\t}\n\tfmt.Printf(\"\\nweekday tasks: %s\\n\", tasks)\n\t\/\/ Output:\n\t\/\/ weekday tasks: milk cows, feed cows, wash cows, wash laundry,\n\t\/\/ fold laundry, iron laundry, flip burgers, join army, kill time\n\n\t\/\/ Get a list of combined tasks for the weekend.\n\ttasks, err = client.get(srv.URL + \"\/weekend\")\n\tif err != nil {\n\t\tfmt.Printf(\"client get error: %v\", err)\n\t}\n\tfmt.Printf(\"\\nweekend tasks: %s\\n\", tasks)\n\t\/\/ Output:\n\t\/\/ weekend tasks: have beer, make merry, take aspirin, pray quietly\n}\n\n\/* -- MODELS --*\/\n\n\/\/ A Todo models a daily task.\ntype Todo struct {\n\tTask    string    \/\/ task to be done\n\tDay     string    \/\/ day to do task\n\tCreated time.Time \/\/ when created\n}\n\n\/\/ Encode marshals a Todo into a buffer.\nfunc (todo *Todo) Encode() (*bytes.Buffer, error) {\n\tb, err := json.Marshal(todo)\n\tif err != nil {\n\t\treturn &bytes.Buffer{}, err\n\t}\n\treturn bytes.NewBuffer(b), nil\n}\n\n\/\/ A TaskList is a list of tasks for a particular day.\ntype TaskList struct {\n\tWhen  string\n\tTasks []string\n}\n\n\/* -- CONTROLLER -- *\/\n\n\/\/ NewController initializes a new instance of our controller.\n\/\/ It provides handler methods for our router.\nfunc NewController(bk *buckets.Bucket) *Controller {\n\t\/\/ map of days to integers\n\tdaynum := map[string]int{\n\t\t\"mon\": 1, \/\/ monday is the first day of the week\n\t\t\"tue\": 2,\n\t\t\"wed\": 3,\n\t\t\"thu\": 4,\n\t\t\"fri\": 5,\n\t\t\"sat\": 6,\n\t\t\"sun\": 7,\n\t}\n\treturn &Controller{bk, daynum}\n}\n\n\/\/ This Controller handles requests for todo items.  The items are stored\n\/\/ in a todos bucket.  The request URLs are used as bucket keys and the\n\/\/ raw json payload as values.\n\/\/\n\/\/ Note that since we're using `httprouter` (abbreviated as `mux` when\n\/\/ imported) as our router, each method is a `httprouter.Handle` rather\n\/\/ than a `http.HandlerFunc`.\ntype Controller struct {\n\ttodos  *buckets.Bucket\n\tdaynum map[string]int\n}\n\n\/\/ getWeekendTasks handles get requests for `\/weekend`, returning the\n\/\/ combined task list for saturday and sunday.\n\/\/\n\/\/ Note how we utilize the RangeItems method, which makes it easy\n\/\/ to get items in our todos bucket with keys in a certain range \n\/\/ (6 <= key < 8), viz., the items for sat and sun.\nfunc (c *Controller) getWeekendTasks(w http.ResponseWriter, r *http.Request,\n\t_ httprouter.Params) {\n\n\t\/\/ Get todo items within the weekend range.\n\titems, err := c.todos.RangeItems([]byte(\"6\"), []byte(\"8\"))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t}\n\n\t\/\/ Generate a list of tasks based on todo items retrieved.\n\ttaskList := &TaskList{\"weekend\", []string{}}\n\n\tfor _, item := range items {\n\t\ttodo, err := decode(item.Value)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t}\n\t\ttaskList.Tasks = append(taskList.Tasks, todo.Task)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tjson.NewEncoder(w).Encode(taskList)\n}\n\n\/\/ getWeekdayTasks handles get requests for `\/weekdays`, returning the\n\/\/ combined task list for monday through friday.\n\/\/\n\/\/ Note how we utilize the RangeItems method, which makes it easy\n\/\/ to get items in our todos bucket with keys in a certain range \n\/\/ (1 <= key < 6), viz., the items for mon through fri.\nfunc (c *Controller) getWeekdayTasks(w http.ResponseWriter, r *http.Request,\n\t_ httprouter.Params) {\n\n\t\/\/ Get todo items within the weekday range.\n\titems, err := c.todos.RangeItems([]byte(\"1\"), []byte(\"6\"))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t}\n\n\t\/\/ Generate a list of tasks based on todo items retrieved.\n\ttaskList := &TaskList{\"weekdays\", []string{}}\n\n\tfor _, item := range items {\n\t\ttodo, err := decode(item.Value)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t}\n\t\ttaskList.Tasks = append(taskList.Tasks, todo.Task)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tjson.NewEncoder(w).Encode(taskList)\n}\n\n\/\/ getDayTasks handles get requests for `\/:day`, returning a particular\n\/\/ day's task list.\n\/\/\n\/\/ Note how we utilize the PrefixItems method for the day requested (as\n\/\/ indicated in the route's `day` parameter). This makes it easy to get \n\/\/ items in our todos bucket with a certain prefix, viz. those with the\n\/\/ prefix representing the requested day.\nfunc (c *Controller) getDayTasks(w http.ResponseWriter, r *http.Request,\n\tp httprouter.Params) {\n\n\t\/\/ Get todo items for the day requested.\n\tday := p.ByName(\"day\")\n\tnum := c.daynum[day]\n\tpre := []byte(strconv.Itoa(num)) \/\/ daynum prefix to use\n\titems, err := c.todos.PrefixItems(pre)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t}\n\n\t\/\/ Generate a list of tasks based on todo items retrieved.\n\ttaskList := &TaskList{day, []string{}}\n\n\tfor _, item := range items {\n\t\ttodo, err := decode(item.Value)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t}\n\t\ttaskList.Tasks = append(taskList.Tasks, todo.Task)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tjson.NewEncoder(w).Encode(taskList)\n}\n\n\/\/ post handles post requests to create a daily todo item.\n\/\/\n\/\/\nfunc (c *Controller) post(w http.ResponseWriter, r *http.Request,\n\tp httprouter.Params) {\n\n\t\/\/ Read request body's json payload into buffer.\n\tb, err := ioutil.ReadAll(r.Body)\n\ttodo, err := decode(b)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t}\n\n\t\/\/ Use the day number + creation time as key.\n\tday := p.ByName(\"day\")\n\tnum := c.daynum[day] \/\/ number of day of week\n\tcreated := todo.Created.Format(time.RFC3339Nano)\n\tkey := fmt.Sprintf(\"%d\/%s\", num, created)\n\n\t\/\/ Put key\/buffer into todos bucket.\n\tif err := c.todos.Put([]byte(key), b); err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\tif verbose {\n\t\tlog.Printf(\"server: %s: %v\", key, todo.Task)\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text\/plain\")\n\tfmt.Fprintf(w, \"put todo for %s: %s\\n\", key, todo)\n}\n\n\/* -- CLIENT -- *\/\n\n\/\/ Our http client for sending requests.\ntype Client struct{}\n\n\/\/ post sends a post request with a json payload.\nfunc (c *Client) post(url string, todo *Todo) error {\n\ttodo.Created = time.Now()\n\tbodyType := \"application\/json\"\n\tbody, err := todo.Encode()\n\tif err != nil {\n\t\treturn err\n\t}\n\tresp, err := http.Post(url, bodyType, body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif verbose {\n\t\tlog.Printf(\"client: %s\\n\", resp.Status)\n\t}\n\treturn nil\n}\n\n\/\/ get sends get requests and expects responses to be a json-encoded\n\/\/ task list.\nfunc (c *Client) get(url string) (string, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\ttaskList := new(TaskList)\n\tif err = json.NewDecoder(resp.Body).Decode(taskList); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.Join(taskList.Tasks, \", \"), nil\n}\n\n\/* -- UTILITY FUNCTIONS, &c. -- *\/\n\n\/\/ decode unmarshals a json-encoded byteslice into a Todo.\nfunc decode(b []byte) (*Todo, error) {\n\ttodo := new(Todo)\n\tif err := json.Unmarshal(b, todo); err != nil {\n\t\treturn &Todo{}, err\n\t}\n\treturn todo, nil\n}\n\n\/\/ tempFilePath returns a temporary file path.\nfunc tempFilePath() string {\n\tf, _ := ioutil.TempFile(\"\", \"bolt-\")\n\tif err := f.Close(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := os.Remove(f.Name()); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn f.Name()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ \thttps:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage hsts\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/google\/go-safeweb\/safehttp\"\n)\n\n\/\/ Plugin implements automatic HSTS functionality.\ntype Plugin struct {\n\t\/\/ The time, in seconds, that the browser should remember\n\t\/\/ that a site is only to be accessed using HTTPS.\n\tMaxAge uint64\n\n\t\/\/ This field controls the includeSubDomains directive.\n\t\/\/ When DisableIncludeSubDomains is false, all subdomains\n\t\/\/ of the domain where this service is hosted will also be added\n\t\/\/ to the browsers HSTS list.\n\tDisableIncludeSubDomains bool\n\n\t\/\/ This field controls the preload directive.\n\t\/\/ This should only be enabled if this site should be\n\t\/\/ added to the browser HSTS preload list, which is supported\n\t\/\/ by all major browsers. See https:\/\/hstspreload.org\/ for\n\t\/\/ more info.\n\tPreload bool\n}\n\n\/\/ NewPlugin creates a new HSTS plugin with safe defaults.\nfunc NewPlugin() Plugin {\n\treturn Plugin{MaxAge: 63072000} \/\/ two years in seconds\n}\n\n\/\/ Before should be executed before the request is sent to the handler.\n\/\/ The function redirects HTTP requests to HTTPS. When HTTPS traffic\n\/\/ is received the Strict-Transport-Security header is applied to the\n\/\/ response.\nfunc (p *Plugin) Before(w safehttp.ResponseWriter, r *safehttp.IncomingRequest) safehttp.Result {\n\tif r.TLS == nil {\n\t\tr.URL.Scheme = \"https\"\n\t\treturn w.Redirect(r, r.URL.String(), safehttp.StatusMovedPermanently)\n\t}\n\n\tvar value strings.Builder\n\tvalue.WriteString(\"max-age=\")\n\tvalue.WriteString(strconv.FormatUint(p.MaxAge, 10))\n\tif !p.DisableIncludeSubDomains {\n\t\tvalue.WriteString(\"; includeSubDomains\")\n\t}\n\tif p.Preload {\n\t\tvalue.WriteString(\"; preload\")\n\t}\n\th := w.Header()\n\tif err := h.Set(\"Strict-Transport-Security\", value.String()); err != nil {\n\t\t\/\/ TODO(@mattiasgrenfeldt): Replace the response with an actual saferesponse somehow.\n\t\treturn w.ServerError(safehttp.StatusInternalServerError, \"Internal Server Error\")\n\t}\n\t\/\/ TODO: Implement header claiming.\n\th.MarkImmutable(\"Strict-Transport-Security\")\n\treturn safehttp.Result{}\n}\n<commit_msg>Added BehindProxy option<commit_after>\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ \thttps:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage hsts\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/google\/go-safeweb\/safehttp\"\n)\n\n\/\/ Plugin implements automatic HSTS functionality.\ntype Plugin struct {\n\t\/\/ The time, in seconds, that the browser should remember\n\t\/\/ that a site is only to be accessed using HTTPS.\n\tMaxAge uint64\n\n\t\/\/ This field controls the includeSubDomains directive.\n\t\/\/ When DisableIncludeSubDomains is false, all subdomains\n\t\/\/ of the domain where this service is hosted will also be added\n\t\/\/ to the browsers HSTS list.\n\tDisableIncludeSubDomains bool\n\n\t\/\/ This field controls the preload directive.\n\t\/\/ This should only be enabled if this site should be\n\t\/\/ added to the browser HSTS preload list, which is supported\n\t\/\/ by all major browsers. See https:\/\/hstspreload.org\/ for\n\t\/\/ more info.\n\tPreload bool\n\n\t\/\/ If this server is behind a proxy that terminates HTTPS\n\t\/\/ traffic then this should be enabled. If this is enabled\n\t\/\/ then the plugin will always send the Strict-Transport-Security\n\t\/\/ header and will not redirect HTTP traffic to HTTPS traffic.\n\tBehindProxy bool\n}\n\n\/\/ NewPlugin creates a new HSTS plugin with safe defaults.\nfunc NewPlugin() Plugin {\n\treturn Plugin{MaxAge: 63072000} \/\/ two years in seconds\n}\n\n\/\/ Before should be executed before the request is sent to the handler.\n\/\/ The function redirects HTTP requests to HTTPS. When HTTPS traffic\n\/\/ is received the Strict-Transport-Security header is applied to the\n\/\/ response.\nfunc (p *Plugin) Before(w safehttp.ResponseWriter, r *safehttp.IncomingRequest) safehttp.Result {\n\tif !p.BehindProxy && r.TLS == nil {\n\t\tr.URL.Scheme = \"https\"\n\t\treturn w.Redirect(r, r.URL.String(), safehttp.StatusMovedPermanently)\n\t}\n\n\tvar value strings.Builder\n\tvalue.WriteString(\"max-age=\")\n\tvalue.WriteString(strconv.FormatUint(p.MaxAge, 10))\n\tif !p.DisableIncludeSubDomains {\n\t\tvalue.WriteString(\"; includeSubDomains\")\n\t}\n\tif p.Preload {\n\t\tvalue.WriteString(\"; preload\")\n\t}\n\th := w.Header()\n\tif err := h.Set(\"Strict-Transport-Security\", value.String()); err != nil {\n\t\t\/\/ TODO(@mattiasgrenfeldt): Replace the response with an actual saferesponse somehow.\n\t\treturn w.ServerError(safehttp.StatusInternalServerError, \"Internal Server Error\")\n\t}\n\t\/\/ TODO: Implement header claiming.\n\th.MarkImmutable(\"Strict-Transport-Security\")\n\treturn safehttp.Result{}\n}\n<|endoftext|>"}
{"text":"<commit_before>package twitter\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/dghubble\/sling\"\n)\n\n\/\/ FollowerService provides methods for accessing Twitter friendship endpoints.\ntype FriendshipService struct {\n\tsling *sling.Sling\n}\n\n\/\/ Creates a new friendship service\nfunc newFriendshipService(sling *sling.Sling) *FriendshipService {\n\treturn &FriendshipService{\n\t\tsling: sling.Path(\"friendships\/\"),\n\t}\n}\n\n\/\/ The relationship status between the authenticated user and the target\ntype FriendshipLookupStatus struct {\n\tName        string   `json:\"name\"`\n\tScreenName  string   `json:\"screen_name\"`\n\tID          int64    `json:\"id\"`\n\tIDStr       string   `json:\"id_str\"`\n\tConnections []string `json:\"connections\"`\n}\n\n\/\/ Basic parameters for friendship requests\ntype FriendshipLookupParams struct {\n\tUserID     string `url:\"user_id,omitempty\"`\n\tScreenName string `url:\"screen_name,omitempty\"`\n}\n\n\/\/ Returns the relationships of the authenticating user to target user\nfunc (s *FriendshipService) Lookup(params *FriendshipLookupParams) (*[]FriendshipLookupStatus, *http.Response, error) {\n\tfriendships := new([]FriendshipLookupStatus)\n\tapiError := new(APIError)\n\tresp, err := s.sling.New().Get(\"lookup.json\").QueryStruct(params).Receive(friendships, apiError)\n\treturn friendships, resp, relevantError(err, *apiError)\n}\n\n\/\/ Result from the Friendship show function\ntype FriendshipShowResult struct {\n\tRelationship FriendshipRelationship `json:\"relationship\"`\n}\n\n\/\/ The underlying relationship of the show function\ntype FriendshipRelationship struct {\n\tTarget FriendshipRelationshipTarget `json:\"target\"`\n\tSource FriendshipRelationshipSource `json:\"source\"`\n}\n\n\/\/ The target's attributes from the show function\ntype FriendshipRelationshipTarget struct {\n\tIDStr      string `json:\"id_str\"`\n\tID         int64  `json:\"id\"`\n\tScreenName string `json:\"screen_name\"`\n\tFollowing  bool   `json:\"following\"`\n\tFollowedBy bool   `json:\"followed_by\"`\n}\n\n\/\/ The source's attributes from the show function\ntype FriendshipRelationshipSource struct {\n\tCanDM                bool   `json:\"can_dm\"`\n\tBlocking             bool   `json:\"blocking\"`\n\tMuting               bool   `json:\"muting\"`\n\tIDStr                string `json:\"id_str\"`\n\tAllReplies           bool   `json:\"all_replies\"`\n\tWantRetweets         bool   `json:\"want_retweets\"`\n\tID                   int64  `json:\"id\"`\n\tMarkedSpam           bool   `json:\"marked_spam\"`\n\tScreenName           string `json:\"screen_name\"`\n\tFollowing            bool   `json:\"following\"`\n\tFollowedBy           bool   `json:\"followed_by\"`\n\tNotificationsEnabled bool   `json:\"notifications_enabled\"`\n}\n\n\/\/ The parameters given to the show function\ntype FriendshipShowParams struct {\n\tSourceScreenName string `url:\"source_screen_name,omitempty\"`\n\tSourceID         string `url:\"source_id,omitempty\"`\n\tTargetScreenName string `url:\"target_screen_name,omitempty\"`\n\tTargetID         string `url:\"target_id,omitempty\"`\n}\n\n\/\/ Returns the relationship between any two specified users\nfunc (s *FriendshipService) Show(params *FriendshipShowParams) (*FriendshipShowResult, *http.Response, error) {\n\tfriendships := new(FriendshipShowResult)\n\tapiError := new(APIError)\n\tresp, err := s.sling.New().Get(\"show.json\").QueryStruct(params).Receive(friendships, apiError)\n\treturn friendships, resp, relevantError(err, *apiError)\n}\n\n\/\/ Generic return result\ntype FriendshipGenericResult struct {\n\tName string `json:\"name\"`\n\tID   int64  `json:\"id\"`\n}\n\n\/\/ Unfollow a user\nfunc (s *FriendshipService) Destroy(params *FriendshipLookupParams) (*FriendshipGenericResult, *http.Response, error) {\n\tfriendships := new(FriendshipGenericResult)\n\tapiError := new(APIError)\n\tresp, err := s.sling.New().Post(\"destroy.json\").QueryStruct(params).Receive(friendships, apiError)\n\treturn friendships, resp, relevantError(err, *apiError)\n}\n\n\/\/ Follow a user\nfunc (s *FriendshipService) Create(params *FriendshipLookupParams) (*FriendshipGenericResult, *http.Response, error) {\n\tfriendships := new(FriendshipGenericResult)\n\tapiError := new(APIError)\n\tresp, err := s.sling.New().Post(\"create.json\").QueryStruct(params).Receive(friendships, apiError)\n\treturn friendships, resp, relevantError(err, *apiError)\n}\n<commit_msg>Update comments to start with relevant name<commit_after>package twitter\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/dghubble\/sling\"\n)\n\n\/\/ FollowerService provides methods for accessing Twitter friendship endpoints.\ntype FriendshipService struct {\n\tsling *sling.Sling\n}\n\n\/\/ Creates a new friendship service\nfunc newFriendshipService(sling *sling.Sling) *FriendshipService {\n\treturn &FriendshipService{\n\t\tsling: sling.Path(\"friendships\/\"),\n\t}\n}\n\n\/\/ FriendshipLookupStatus is The relationship status between the authenticated user and the target\ntype FriendshipLookupStatus struct {\n\tName        string   `json:\"name\"`\n\tScreenName  string   `json:\"screen_name\"`\n\tID          int64    `json:\"id\"`\n\tIDStr       string   `json:\"id_str\"`\n\tConnections []string `json:\"connections\"`\n}\n\n\/\/ FriendshipLookupParams are Basic parameters for friendship requests\ntype FriendshipLookupParams struct {\n\tUserID     string `url:\"user_id,omitempty\"`\n\tScreenName string `url:\"screen_name,omitempty\"`\n}\n\n\/\/ Lookup returns the relationships of the authenticating user to target user\nfunc (s *FriendshipService) Lookup(params *FriendshipLookupParams) (*[]FriendshipLookupStatus, *http.Response, error) {\n\tfriendships := new([]FriendshipLookupStatus)\n\tapiError := new(APIError)\n\tresp, err := s.sling.New().Get(\"lookup.json\").QueryStruct(params).Receive(friendships, apiError)\n\treturn friendships, resp, relevantError(err, *apiError)\n}\n\n\/\/ FriendshipShowResult is the result from the Friendship show function\ntype FriendshipShowResult struct {\n\tRelationship FriendshipRelationship `json:\"relationship\"`\n}\n\n\/\/ FriendshipRelationship is the underlying relationship of the show function\ntype FriendshipRelationship struct {\n\tTarget FriendshipRelationshipTarget `json:\"target\"`\n\tSource FriendshipRelationshipSource `json:\"source\"`\n}\n\n\/\/ FriendshipRelationshipTarget is the target's attributes from the show function\ntype FriendshipRelationshipTarget struct {\n\tIDStr      string `json:\"id_str\"`\n\tID         int64  `json:\"id\"`\n\tScreenName string `json:\"screen_name\"`\n\tFollowing  bool   `json:\"following\"`\n\tFollowedBy bool   `json:\"followed_by\"`\n}\n\n\/\/ FriendshipRelationshipSource is the source's attributes from the show function\ntype FriendshipRelationshipSource struct {\n\tCanDM                bool   `json:\"can_dm\"`\n\tBlocking             bool   `json:\"blocking\"`\n\tMuting               bool   `json:\"muting\"`\n\tIDStr                string `json:\"id_str\"`\n\tAllReplies           bool   `json:\"all_replies\"`\n\tWantRetweets         bool   `json:\"want_retweets\"`\n\tID                   int64  `json:\"id\"`\n\tMarkedSpam           bool   `json:\"marked_spam\"`\n\tScreenName           string `json:\"screen_name\"`\n\tFollowing            bool   `json:\"following\"`\n\tFollowedBy           bool   `json:\"followed_by\"`\n\tNotificationsEnabled bool   `json:\"notifications_enabled\"`\n}\n\n\/\/ FriendshipShowParams are the parameters given to the show function\ntype FriendshipShowParams struct {\n\tSourceScreenName string `url:\"source_screen_name,omitempty\"`\n\tSourceID         string `url:\"source_id,omitempty\"`\n\tTargetScreenName string `url:\"target_screen_name,omitempty\"`\n\tTargetID         string `url:\"target_id,omitempty\"`\n}\n\n\/\/ Show returns the relationship between any two specified users\nfunc (s *FriendshipService) Show(params *FriendshipShowParams) (*FriendshipShowResult, *http.Response, error) {\n\tfriendships := new(FriendshipShowResult)\n\tapiError := new(APIError)\n\tresp, err := s.sling.New().Get(\"show.json\").QueryStruct(params).Receive(friendships, apiError)\n\treturn friendships, resp, relevantError(err, *apiError)\n}\n\n\/\/ FriendshipGenericResult is a generic return result\ntype FriendshipGenericResult struct {\n\tName string `json:\"name\"`\n\tID   int64  `json:\"id\"`\n}\n\n\/\/ Destroy unfollows a user\nfunc (s *FriendshipService) Destroy(params *FriendshipLookupParams) (*FriendshipGenericResult, *http.Response, error) {\n\tfriendships := new(FriendshipGenericResult)\n\tapiError := new(APIError)\n\tresp, err := s.sling.New().Post(\"destroy.json\").QueryStruct(params).Receive(friendships, apiError)\n\treturn friendships, resp, relevantError(err, *apiError)\n}\n\n\/\/ Create follows a user\nfunc (s *FriendshipService) Create(params *FriendshipLookupParams) (*FriendshipGenericResult, *http.Response, error) {\n\tfriendships := new(FriendshipGenericResult)\n\tapiError := new(APIError)\n\tresp, err := s.sling.New().Post(\"create.json\").QueryStruct(params).Receive(friendships, apiError)\n\treturn friendships, resp, relevantError(err, *apiError)\n}\n<|endoftext|>"}
{"text":"<commit_before>package task\n\nimport (\n\t\"fmt\"\n\t\"neon\/build\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n)\n\nfunc init() {\n\tbuild.AddTask(build.TaskDesc{\n\t\tName: \"neon\",\n\t\tFunc: neon,\n\t\tArgs: reflect.TypeOf(neonArgs{}),\n\t\tHelp: `Run a NeON build.\n\nArguments:\n\n- neon: the build file to run (string).\n- targets: the target(s) to run (strings, wrap, optional).\n\nExamples:\n\n    # run target 'foo' of build file 'bar\/build.yml'\n    - neon:    'bar\/build.yml'\n      targets: 'foo'`,\n\t})\n}\n\ntype neonArgs struct {\n\tNeon    string   `neon:\"file\"`\n\tTargets []string `neon:\"optional,wrap\"`\n}\n\nfunc neon(context *build.Context, args interface{}) error {\n\tparams := args.(neonArgs)\n\tpath, err := filepath.Abs(params.Neon)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting build file path: %v\", err)\n\t}\n\tbase := filepath.Dir(path)\n\tnewBuild, err := build.NewBuild(path, base, context.Build.Repository)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"instantiating build: %v\", err)\n\t}\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting current directory: %v\", err)\n\t}\n\tdefer os.Chdir(dir)\n\tos.Chdir(newBuild.Dir)\n\tbuildContext := build.NewContext(newBuild)\n\terr = buildContext.Init()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"initializing build context: %v\", err)\n\t}\n\terr = newBuild.Run(context, params.Targets)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"running build '%s': %v\", params.Neon, err)\n\t}\n\treturn nil\n}\n<commit_msg>Fixed context error with neon task<commit_after>package task\n\nimport (\n\t\"fmt\"\n\t\"neon\/build\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n)\n\nfunc init() {\n\tbuild.AddTask(build.TaskDesc{\n\t\tName: \"neon\",\n\t\tFunc: neon,\n\t\tArgs: reflect.TypeOf(neonArgs{}),\n\t\tHelp: `Run a NeON build.\n\nArguments:\n\n- neon: the build file to run (string).\n- targets: the target(s) to run (strings, wrap, optional).\n\nExamples:\n\n    # run target 'foo' of build file 'bar\/build.yml'\n    - neon:    'bar\/build.yml'\n      targets: 'foo'`,\n\t})\n}\n\ntype neonArgs struct {\n\tNeon    string   `neon:\"file\"`\n\tTargets []string `neon:\"optional,wrap\"`\n}\n\nfunc neon(context *build.Context, args interface{}) error {\n\tparams := args.(neonArgs)\n\t\/\/ FIXME: path relative to build directory\n\tpath, err := filepath.Abs(params.Neon)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting build file path: %v\", err)\n\t}\n\tbase := filepath.Dir(path)\n\tnewBuild, err := build.NewBuild(path, base, context.Build.Repository)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"instantiating build: %v\", err)\n\t}\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting current directory: %v\", err)\n\t}\n\tdefer os.Chdir(dir)\n\tos.Chdir(newBuild.Dir)\n\tnewContext := build.NewContext(newBuild)\n\terr = newContext.Init()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"initializing build context: %v\", err)\n\t}\n\terr = newBuild.Run(newContext, params.Targets)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"running build '%s': %v\", params.Neon, err)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage forgetfs\n\nimport \"github.com\/jacobsa\/fuse\"\n\n\/\/ Create a file system whose sole contents are a file named \"foo\" and a\n\/\/ directory named \"bar\".\n\/\/\n\/\/ The file \"foo\" may be opened for reading and\/or writing, but reads and\n\/\/ writes aren't supported. Additionally, any non-existent file or directory\n\/\/ name may be created within any directory, but the resulting inode will\n\/\/ appear to have been unlinked immediately.\n\/\/\n\/\/ The file system maintains reference counts for the inodes involved. It will\n\/\/ panic if a reference count becomes negative or if an inode ID is re-used\n\/\/ after we expect it to be dead. Its Check method may be used to check that\n\/\/ there are no inodes with non-zero reference counts remaining, after\n\/\/ unmounting.\nfunc NewFileSystem() (fs *ForgetFS) {\n\tfs = &ForgetFS{}\n\treturn\n}\n\ntype ForgetFS struct {\n}\n\nfunc (fs *ForgetFS) ServeOps(c *fuse.Connection) {\n\tpanic(\"TODO: Export dispatch function from fuseutil and use it here.\")\n}\n\n\/\/ Panic if there are any inodes that have a non-zero reference count. For use\n\/\/ after unmounting.\nfunc (fs *ForgetFS) Check() {\n\tpanic(\"TODO\")\n}\n<commit_msg>Revised a plan.<commit_after>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage forgetfs\n\nimport (\n\t\"github.com\/jacobsa\/fuse\"\n\t\"github.com\/jacobsa\/fuse\/fuseutil\"\n)\n\n\/\/ Create a file system whose sole contents are a file named \"foo\" and a\n\/\/ directory named \"bar\".\n\/\/\n\/\/ The file \"foo\" may be opened for reading and\/or writing, but reads and\n\/\/ writes aren't supported. Additionally, any non-existent file or directory\n\/\/ name may be created within any directory, but the resulting inode will\n\/\/ appear to have been unlinked immediately.\n\/\/\n\/\/ The file system maintains reference counts for the inodes involved. It will\n\/\/ panic if a reference count becomes negative or if an inode ID is re-used\n\/\/ after we expect it to be dead. Its Check method may be used to check that\n\/\/ there are no inodes with non-zero reference counts remaining, after\n\/\/ unmounting.\nfunc NewFileSystem() (fs *ForgetFS) {\n\timpl := &fsImpl{}\n\n\tfs = &ForgetFS{\n\t\timpl:   impl,\n\t\tserver: fuseutil.NewFileSystemServer(impl),\n\t}\n\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ForgetFS\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype ForgetFS struct {\n\timpl   *fsImpl\n\tserver fuse.Server\n}\n\nfunc (fs *ForgetFS) ServeOps(c *fuse.Connection) {\n\tfs.server.ServeOps(c)\n}\n\n\/\/ Panic if there are any inodes that have a non-zero reference count. For use\n\/\/ after unmounting.\nfunc (fs *ForgetFS) Check() {\n\tpanic(\"TODO\")\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Actual implementation\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype fsImpl struct {\n\tfuseutil.NotImplementedFileSystem\n}\n<|endoftext|>"}
{"text":"<commit_before>package store\n\nimport (\n\t\"os\"\n)\n\nvar emptyDir = node{V: \"\", Ds: make(map[string]node), Rev: Dir}\n\nconst ErrorPath = \"\/ctl\/err\"\n\nconst Nop = \"nop:\"\n\n\/\/ This structure should be kept immutable.\ntype node struct {\n\tV   string\n\tRev int64\n\tDs  map[string]node\n}\n\nfunc (n node) String() string {\n\treturn \"<node>\"\n}\n\nfunc (n node) readdir() []string {\n\tnames := make([]string, len(n.Ds))\n\ti := 0\n\tfor name := range n.Ds {\n\t\tnames[i] = name\n\t\ti++\n\t}\n\treturn names\n}\n\nfunc (n node) at(parts []string) (node, os.Error) {\n\tswitch len(parts) {\n\tcase 0:\n\t\treturn n, nil\n\tdefault:\n\t\tif n.Ds != nil {\n\t\t\tif m, ok := n.Ds[parts[0]]; ok {\n\t\t\t\treturn m.at(parts[1:])\n\t\t\t}\n\t\t}\n\t\treturn node{}, os.ENOENT\n\t}\n\tpanic(\"unreachable\")\n}\n\nfunc (n node) get(parts []string) ([]string, int64) {\n\tswitch m, err := n.at(parts); err {\n\tcase os.ENOENT:\n\t\treturn []string{\"\"}, Missing\n\tdefault:\n\t\tif len(m.Ds) > 0 {\n\t\t\treturn m.readdir(), m.Rev\n\t\t} else {\n\t\t\treturn []string{m.V}, m.Rev\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}\n\nfunc (n node) Get(path string) ([]string, int64) {\n\tif err := checkPath(path); err != nil {\n\t\treturn []string{\"\"}, Missing\n\t}\n\n\treturn n.get(split(path))\n}\n\nfunc (n node) stat(parts []string) (int32, int64) {\n\tswitch m, err := n.at(parts); err {\n\tcase os.ENOENT:\n\t\treturn 0, Missing\n\tdefault:\n\t\tl := len(m.Ds)\n\t\tif l > 0 {\n\t\t\treturn int32(l), m.Rev\n\t\t} else {\n\t\t\treturn int32(len(m.V)), m.Rev\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}\n\nfunc (n node) Stat(path string) (int32, int64) {\n\tif err := checkPath(path); err != nil {\n\t\treturn 0, Missing\n\t}\n\n\treturn n.stat(split(path))\n}\n\n\nfunc copyMap(a map[string]node) map[string]node {\n\tb := make(map[string]node)\n\tfor k, v := range a {\n\t\tb[k] = v\n\t}\n\treturn b\n}\n\n\/\/ Return value is replacement node\nfunc (n node) set(parts []string, v string, rev int64, keep bool) (node, bool) {\n\tif len(parts) == 0 {\n\t\treturn node{v, rev, n.Ds}, keep\n\t}\n\n\tn.Ds = copyMap(n.Ds)\n\tp, ok := n.Ds[parts[0]].set(parts[1:], v, rev, keep)\n\tn.Ds[parts[0]] = p, ok\n\tn.Rev = Dir\n\treturn n, len(n.Ds) > 0\n}\n\nfunc (n node) setp(k, v string, rev int64, keep bool) node {\n\tif err := checkPath(k); err != nil {\n\t\treturn n\n\t}\n\n\tn, _ = n.set(split(k), v, rev, keep)\n\treturn n\n}\n\nfunc (n node) apply(seqn int64, mut string) (rep node, ev Event) {\n\tev.Seqn, ev.Rev, ev.Mut = seqn, seqn, mut\n\tif mut == Nop {\n\t\tev.Path = \"\/\"\n\t\tev.Rev = nop\n\t\trep = n\n\t\tev.Getter = rep\n\t\treturn\n\t}\n\n\tvar rev int64\n\tvar keep bool\n\tev.Path, ev.Body, rev, keep, ev.Err = decode(mut)\n\n\tif ev.Err == nil && keep {\n\t\tcomponents := split(ev.Path)\n\t\tfor i := 0; i < len(components)-1; i++ {\n\t\t\t_, dirRev := n.get(components[0 : i+1])\n\t\t\tif dirRev == Missing {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif dirRev != Dir {\n\t\t\t\tev.Err = os.ENOTDIR\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif ev.Err == nil {\n\t\t_, curRev := n.Get(ev.Path)\n\t\tif rev != Clobber && rev < curRev {\n\t\t\tev.Err = ErrRevMismatch\n\t\t} else if curRev == Dir {\n\t\t\tev.Err = os.EISDIR\n\t\t}\n\t}\n\n\tif ev.Err != nil {\n\t\tev.Path, ev.Body, rev, keep = ErrorPath, ev.Err.String(), Clobber, true\n\t}\n\n\tif !keep {\n\t\tev.Rev = Missing\n\t}\n\n\trep = n.setp(ev.Path, ev.Body, ev.Rev, keep)\n\tev.Getter = rep\n\treturn\n}\n<commit_msg>store: remove unnecessary syntax check<commit_after>package store\n\nimport (\n\t\"os\"\n)\n\nvar emptyDir = node{V: \"\", Ds: make(map[string]node), Rev: Dir}\n\nconst ErrorPath = \"\/ctl\/err\"\n\nconst Nop = \"nop:\"\n\n\/\/ This structure should be kept immutable.\ntype node struct {\n\tV   string\n\tRev int64\n\tDs  map[string]node\n}\n\nfunc (n node) String() string {\n\treturn \"<node>\"\n}\n\nfunc (n node) readdir() []string {\n\tnames := make([]string, len(n.Ds))\n\ti := 0\n\tfor name := range n.Ds {\n\t\tnames[i] = name\n\t\ti++\n\t}\n\treturn names\n}\n\nfunc (n node) at(parts []string) (node, os.Error) {\n\tswitch len(parts) {\n\tcase 0:\n\t\treturn n, nil\n\tdefault:\n\t\tif n.Ds != nil {\n\t\t\tif m, ok := n.Ds[parts[0]]; ok {\n\t\t\t\treturn m.at(parts[1:])\n\t\t\t}\n\t\t}\n\t\treturn node{}, os.ENOENT\n\t}\n\tpanic(\"unreachable\")\n}\n\nfunc (n node) get(parts []string) ([]string, int64) {\n\tswitch m, err := n.at(parts); err {\n\tcase os.ENOENT:\n\t\treturn []string{\"\"}, Missing\n\tdefault:\n\t\tif len(m.Ds) > 0 {\n\t\t\treturn m.readdir(), m.Rev\n\t\t} else {\n\t\t\treturn []string{m.V}, m.Rev\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}\n\nfunc (n node) Get(path string) ([]string, int64) {\n\treturn n.get(split(path))\n}\n\nfunc (n node) stat(parts []string) (int32, int64) {\n\tswitch m, err := n.at(parts); err {\n\tcase os.ENOENT:\n\t\treturn 0, Missing\n\tdefault:\n\t\tl := len(m.Ds)\n\t\tif l > 0 {\n\t\t\treturn int32(l), m.Rev\n\t\t} else {\n\t\t\treturn int32(len(m.V)), m.Rev\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}\n\nfunc (n node) Stat(path string) (int32, int64) {\n\tif err := checkPath(path); err != nil {\n\t\treturn 0, Missing\n\t}\n\n\treturn n.stat(split(path))\n}\n\n\nfunc copyMap(a map[string]node) map[string]node {\n\tb := make(map[string]node)\n\tfor k, v := range a {\n\t\tb[k] = v\n\t}\n\treturn b\n}\n\n\/\/ Return value is replacement node\nfunc (n node) set(parts []string, v string, rev int64, keep bool) (node, bool) {\n\tif len(parts) == 0 {\n\t\treturn node{v, rev, n.Ds}, keep\n\t}\n\n\tn.Ds = copyMap(n.Ds)\n\tp, ok := n.Ds[parts[0]].set(parts[1:], v, rev, keep)\n\tn.Ds[parts[0]] = p, ok\n\tn.Rev = Dir\n\treturn n, len(n.Ds) > 0\n}\n\nfunc (n node) setp(k, v string, rev int64, keep bool) node {\n\tif err := checkPath(k); err != nil {\n\t\treturn n\n\t}\n\n\tn, _ = n.set(split(k), v, rev, keep)\n\treturn n\n}\n\nfunc (n node) apply(seqn int64, mut string) (rep node, ev Event) {\n\tev.Seqn, ev.Rev, ev.Mut = seqn, seqn, mut\n\tif mut == Nop {\n\t\tev.Path = \"\/\"\n\t\tev.Rev = nop\n\t\trep = n\n\t\tev.Getter = rep\n\t\treturn\n\t}\n\n\tvar rev int64\n\tvar keep bool\n\tev.Path, ev.Body, rev, keep, ev.Err = decode(mut)\n\n\tif ev.Err == nil && keep {\n\t\tcomponents := split(ev.Path)\n\t\tfor i := 0; i < len(components)-1; i++ {\n\t\t\t_, dirRev := n.get(components[0 : i+1])\n\t\t\tif dirRev == Missing {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif dirRev != Dir {\n\t\t\t\tev.Err = os.ENOTDIR\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif ev.Err == nil {\n\t\t_, curRev := n.Get(ev.Path)\n\t\tif rev != Clobber && rev < curRev {\n\t\t\tev.Err = ErrRevMismatch\n\t\t} else if curRev == Dir {\n\t\t\tev.Err = os.EISDIR\n\t\t}\n\t}\n\n\tif ev.Err != nil {\n\t\tev.Path, ev.Body, rev, keep = ErrorPath, ev.Err.String(), Clobber, true\n\t}\n\n\tif !keep {\n\t\tev.Rev = Missing\n\t}\n\n\trep = n.setp(ev.Path, ev.Body, ev.Rev, keep)\n\tev.Getter = rep\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/technoweenie\/grohl\"\n)\n\ntype IMagick struct{}\n\ntype processPipelineStep func(workingDirectoryPath string, inputFilePath string, args *ProcessArgs) (outputFilePath string, err error)\n\nvar defaultPipeline = []processPipelineStep{\n\tdownloadRemote,\n\tpreProcessImage,\n\tprocessImage,\n}\n\n\/\/ Process a remote asset url using graphicsmagick with the args supplied\n\/\/ and write the response to w\nfunc (p *IMagick) Process(w http.ResponseWriter, r *http.Request, args *ProcessArgs) (err error) {\n\ttempDir, err := createTemporaryWorkspace()\n\tif err != nil {\n\t\treturn\n\t}\n\t\/\/ defer os.RemoveAll(tempDir)\n\n\tvar filePath string\n\n\tfor _, step := range defaultPipeline {\n\t\tfilePath, err = step(tempDir, filePath, args)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ serve response\n\thttp.ServeFile(w, r, filePath)\n\treturn\n}\n\nfunc createTemporaryWorkspace() (string, error) {\n\treturn ioutil.TempDir(\"\", \"_firesize\")\n}\n\nfunc downloadRemote(tempDir string, _ string, args *ProcessArgs) (string, error) {\n\turl := args.Url\n\tinFile := filepath.Join(tempDir, \"in\")\n\n\tgrohl.Log(grohl.Data{\n\t\t\"processor\": \"imagick\",\n\t\t\"download\":  url,\n\t\t\"local\":     inFile,\n\t})\n\n\tout, err := os.Create(inFile)\n\tif err != nil {\n\t\treturn inFile, err\n\t}\n\tdefer out.Close()\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn inFile, err\n\t}\n\tdefer resp.Body.Close()\n\n\t_, err = io.Copy(out, resp.Body)\n\n\treturn inFile, err\n}\n\nfunc preProcessImage(tempDir string, inFile string, args *ProcessArgs) (string, error) {\n\tif isAnimatedGif(inFile) {\n\t\targs.Format = \"gif\" \/\/ Total hack cos format is incorrectly .png on example\n\t\treturn coalesceAnimatedGif(tempDir, inFile)\n\t} else {\n\t\treturn inFile, nil\n\t}\n}\n\nfunc processImage(tempDir string, inFile string, args *ProcessArgs) (string, error) {\n\toutFile := filepath.Join(tempDir, \"out\")\n\tcmdArgs, outFileWithFormat := args.CommandArgs(inFile, outFile)\n\n\tgrohl.Log(grohl.Data{\n\t\t\"processor\": \"imagick\",\n\t\t\"args\":      cmdArgs,\n\t})\n\n\texecutable := \"convert\"\n\tcmd := exec.Command(executable, cmdArgs...)\n\tvar outErr bytes.Buffer\n\tcmd.Stdout, cmd.Stderr = &outErr, &outErr\n\terr := runWithTimeout(cmd, 60*time.Second)\n\tif err != nil {\n\t\tgrohl.Log(grohl.Data{\n\t\t\t\"processor\": \"imagick\",\n\t\t\t\"failure\":   err,\n\t\t\t\"args\":      cmdArgs,\n\t\t\t\"output\":    string(outErr.Bytes()),\n\t\t})\n\t}\n\n\treturn outFileWithFormat, err\n}\n\nfunc isAnimatedGif(inFile string) bool {\n\t\/\/ identify -format %n updates-product-click.gif # => 105\n\tcmd := exec.Command(\"identify\", \"-format\", \"%n\", inFile)\n\tvar stdout, stderr bytes.Buffer\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\terr := runWithTimeout(cmd, 10*time.Second)\n\tif err != nil {\n\t\toutput := string(stderr.Bytes())\n\t\tgrohl.Log(grohl.Data{\n\t\t\t\"identify-error\": err,\n\t\t\t\"raw-stderr\":     output,\n\t\t})\n\t} else {\n\t\toutput := string(stdout.Bytes())\n\t\tnumFrames, err := strconv.Atoi(output)\n\t\tif err != nil {\n\t\t\tgrohl.Log(grohl.Data{\n\t\t\t\t\"identify-error\": \"non numeric identify output\",\n\t\t\t\t\"raw-stdout\":     output,\n\t\t\t})\n\t\t} else {\n\t\t\tgrohl.Log(grohl.Data{\n\t\t\t\t\"processor\":  \"imagick\",\n\t\t\t\t\"num-frames\": numFrames,\n\t\t\t})\n\t\t\treturn numFrames > 1\n\t\t}\n\t}\n\t\/\/ if anything fucks out assume not animated\n\treturn false\n}\n\nfunc coalesceAnimatedGif(tempDir string, inFile string) (string, error) {\n\toutFile := filepath.Join(tempDir, \"temp\")\n\n\t\/\/ convert do.gif -coalesce temporary.gif\n\tcmd := exec.Command(\"convert\", inFile, \"-coalesce\", outFile)\n\t_ = runWithTimeout(cmd, 60*time.Second)\n\n\treturn outFile, nil\n}\n\nfunc runWithTimeout(cmd *exec.Cmd, timeout time.Duration) error {\n\t\/\/ Start the process\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Kill the process if it doesn't exit in time\n\tdefer time.AfterFunc(timeout, func() {\n\t\tfmt.Println(\"command timed out\")\n\t\tcmd.Process.Kill()\n\t}).Stop()\n\n\t\/\/ Wait for the process to finish\n\treturn cmd.Wait()\n}\n<commit_msg>Make error logging more consistent.<commit_after>package models\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/technoweenie\/grohl\"\n)\n\ntype IMagick struct{}\n\ntype processPipelineStep func(workingDirectoryPath string, inputFilePath string, args *ProcessArgs) (outputFilePath string, err error)\n\nvar defaultPipeline = []processPipelineStep{\n\tdownloadRemote,\n\tpreProcessImage,\n\tprocessImage,\n}\n\n\/\/ Process a remote asset url using graphicsmagick with the args supplied\n\/\/ and write the response to w\nfunc (p *IMagick) Process(w http.ResponseWriter, r *http.Request, args *ProcessArgs) (err error) {\n\ttempDir, err := createTemporaryWorkspace()\n\tif err != nil {\n\t\treturn\n\t}\n\t\/\/ defer os.RemoveAll(tempDir)\n\n\tvar filePath string\n\n\tfor _, step := range defaultPipeline {\n\t\tfilePath, err = step(tempDir, filePath, args)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ serve response\n\thttp.ServeFile(w, r, filePath)\n\treturn\n}\n\nfunc createTemporaryWorkspace() (string, error) {\n\treturn ioutil.TempDir(\"\", \"_firesize\")\n}\n\nfunc downloadRemote(tempDir string, _ string, args *ProcessArgs) (string, error) {\n\turl := args.Url\n\tinFile := filepath.Join(tempDir, \"in\")\n\n\tgrohl.Log(grohl.Data{\n\t\t\"processor\": \"imagick\",\n\t\t\"download\":  url,\n\t\t\"local\":     inFile,\n\t})\n\n\tout, err := os.Create(inFile)\n\tif err != nil {\n\t\treturn inFile, err\n\t}\n\tdefer out.Close()\n\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn inFile, err\n\t}\n\tdefer resp.Body.Close()\n\n\t_, err = io.Copy(out, resp.Body)\n\n\treturn inFile, err\n}\n\nfunc preProcessImage(tempDir string, inFile string, args *ProcessArgs) (string, error) {\n\tif isAnimatedGif(inFile) {\n\t\targs.Format = \"gif\" \/\/ Total hack cos format is incorrectly .png on example\n\t\treturn coalesceAnimatedGif(tempDir, inFile)\n\t} else {\n\t\treturn inFile, nil\n\t}\n}\n\nfunc processImage(tempDir string, inFile string, args *ProcessArgs) (string, error) {\n\toutFile := filepath.Join(tempDir, \"out\")\n\tcmdArgs, outFileWithFormat := args.CommandArgs(inFile, outFile)\n\n\tgrohl.Log(grohl.Data{\n\t\t\"processor\": \"imagick\",\n\t\t\"args\":      cmdArgs,\n\t})\n\n\texecutable := \"convert\"\n\tcmd := exec.Command(executable, cmdArgs...)\n\tvar outErr bytes.Buffer\n\tcmd.Stdout, cmd.Stderr = &outErr, &outErr\n\terr := runWithTimeout(cmd, 60*time.Second)\n\tif err != nil {\n\t\tgrohl.Log(grohl.Data{\n\t\t\t\"processor\": \"imagick\",\n\t\t\t\"step\":      \"convert\",\n\t\t\t\"failure\":   err,\n\t\t\t\"args\":      cmdArgs,\n\t\t\t\"output\":    string(outErr.Bytes()),\n\t\t})\n\t}\n\n\treturn outFileWithFormat, err\n}\n\nfunc isAnimatedGif(inFile string) bool {\n\t\/\/ identify -format %n updates-product-click.gif # => 105\n\tcmd := exec.Command(\"identify\", \"-format\", \"%n\", inFile)\n\tvar stdout, stderr bytes.Buffer\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\terr := runWithTimeout(cmd, 10*time.Second)\n\tif err != nil {\n\t\toutput := string(stderr.Bytes())\n\t\tgrohl.Log(grohl.Data{\n\t\t\t\"processor\": \"imagick\",\n\t\t\t\"step\":      \"identify\",\n\t\t\t\"failure\":   err,\n\t\t\t\"output\":    output,\n\t\t})\n\t} else {\n\t\toutput := string(stdout.Bytes())\n\t\tnumFrames, err := strconv.Atoi(output)\n\t\tif err != nil {\n\t\t\tgrohl.Log(grohl.Data{\n\t\t\t\t\"processor\": \"imagick\",\n\t\t\t\t\"step\":      \"identify\",\n\t\t\t\t\"failure\":   err,\n\t\t\t\t\"output\":    output,\n\t\t\t\t\"message\":   \"non numeric identify output\",\n\t\t\t})\n\t\t} else {\n\t\t\tgrohl.Log(grohl.Data{\n\t\t\t\t\"processor\":  \"imagick\",\n\t\t\t\t\"step\":       \"identify\",\n\t\t\t\t\"num-frames\": numFrames,\n\t\t\t})\n\t\t\treturn numFrames > 1\n\t\t}\n\t}\n\t\/\/ if anything fucks out assume not animated\n\treturn false\n}\n\nfunc coalesceAnimatedGif(tempDir string, inFile string) (string, error) {\n\toutFile := filepath.Join(tempDir, \"temp\")\n\n\t\/\/ convert do.gif -coalesce temporary.gif\n\tcmd := exec.Command(\"convert\", inFile, \"-coalesce\", outFile)\n\t_ = runWithTimeout(cmd, 60*time.Second)\n\n\treturn outFile, nil\n}\n\nfunc runWithTimeout(cmd *exec.Cmd, timeout time.Duration) error {\n\t\/\/ Start the process\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Kill the process if it doesn't exit in time\n\tdefer time.AfterFunc(timeout, func() {\n\t\tfmt.Println(\"command timed out\")\n\t\tcmd.Process.Kill()\n\t}).Stop()\n\n\t\/\/ Wait for the process to finish\n\treturn cmd.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage docker\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com\/docker\/libcontainer\"\n\t\"github.com\/docker\/libcontainer\/cgroups\"\n\tcgroup_fs \"github.com\/docker\/libcontainer\/cgroups\/fs\"\n\t\"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/google\/cadvisor\/container\"\n\tcontainerLibcontainer \"github.com\/google\/cadvisor\/container\/libcontainer\"\n\t\"github.com\/google\/cadvisor\/fs\"\n\t\"github.com\/google\/cadvisor\/info\"\n\t\"github.com\/google\/cadvisor\/utils\"\n)\n\n\/\/ Relative path from Docker root to the libcontainer per-container state.\nconst pathToLibcontainerState = \"execdriver\/native\"\n\n\/\/ Path to aufs dir where all the files exist.\n\/\/ aufs\/layers is ignored here since it does not hold a lot of data.\n\/\/ aufs\/mnt contains the mount points used to compose the rootfs. Hence it is also ignored.\nvar pathToAufsDir = \"aufs\/diff\"\n\nvar fileNotFound = errors.New(\"file not found\")\n\ntype dockerContainerHandler struct {\n\tclient               *docker.Client\n\tname                 string\n\tid                   string\n\taliases              []string\n\tmachineInfoFactory   info.MachineInfoFactory\n\tlibcontainerStateDir string\n\tcgroup               cgroups.Cgroup\n\tusesAufsDriver       bool\n\tfsInfo               fs.FsInfo\n\tstorageDirs          []string\n}\n\nfunc newDockerContainerHandler(\n\tclient *docker.Client,\n\tname string,\n\tmachineInfoFactory info.MachineInfoFactory,\n\tdockerRootDir string,\n\tusesAufsDriver bool,\n) (container.ContainerHandler, error) {\n\tfsInfo, err := fs.NewFsInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thandler := &dockerContainerHandler{\n\t\tclient:               client,\n\t\tname:                 name,\n\t\tmachineInfoFactory:   machineInfoFactory,\n\t\tlibcontainerStateDir: path.Join(dockerRootDir, pathToLibcontainerState),\n\t\tcgroup: cgroups.Cgroup{\n\t\t\tParent: \"\/\",\n\t\t\tName:   name,\n\t\t},\n\t\tusesAufsDriver: usesAufsDriver,\n\t\tfsInfo:         fsInfo,\n\t}\n\thandler.storageDirs = append(handler.storageDirs, path.Join(dockerRootDir, pathToAufsDir, path.Base(name)))\n\tif handler.isDockerRoot() {\n\t\treturn handler, nil\n\t}\n\tid := containerNameToDockerId(name)\n\thandler.id = id\n\tctnr, err := client.InspectContainer(id)\n\t\/\/ We assume that if Inspect fails then the container is not known to docker.\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to inspect container %s - %s\\n\", id, err)\n\t}\n\thandler.aliases = append(handler.aliases, path.Join(\"\/docker\", ctnr.Name))\n\treturn handler, nil\n}\n\nfunc containerNameToDockerId(name string) string {\n\tid := path.Base(name)\n\n\t\/\/ Turn systemd cgroup name into Docker ID.\n\tif useSystemd {\n\t\tconst systemdDockerPrefix = \"docker-\"\n\t\tif strings.HasPrefix(id, systemdDockerPrefix) {\n\t\t\tid = id[len(systemdDockerPrefix):]\n\t\t}\n\n\t\tconst systemdScopeSuffix = \".scope\"\n\t\tif strings.HasSuffix(id, systemdScopeSuffix) {\n\t\t\tid = id[:len(id)-len(systemdScopeSuffix)]\n\t\t}\n\t}\n\n\treturn id\n}\n\nfunc (self *dockerContainerHandler) ContainerReference() (info.ContainerReference, error) {\n\treturn info.ContainerReference{\n\t\tName:    self.name,\n\t\tAliases: self.aliases,\n\t}, nil\n}\n\nfunc (self *dockerContainerHandler) isDockerRoot() bool {\n\treturn self.name == \"\/docker\"\n}\n\n\/\/ TODO(vmarmol): Switch to getting this from libcontainer once we have a solid API.\nfunc (self *dockerContainerHandler) readLibcontainerConfig() (config *libcontainer.Config, err error) {\n\tconfigPath := path.Join(self.libcontainerStateDir, self.id, \"container.json\")\n\tif !utils.FileExists(configPath) {\n\t\t\/\/ TODO(vishh): Return file name as well once we have a better error interface.\n\t\terr = fileNotFound\n\t\treturn\n\t}\n\tf, err := os.Open(configPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open %s - %s\\n\", configPath, err)\n\t}\n\tdefer f.Close()\n\td := json.NewDecoder(f)\n\tretConfig := new(libcontainer.Config)\n\terr = d.Decode(retConfig)\n\tif err != nil {\n\t\treturn\n\t}\n\tconfig = retConfig\n\n\t\/\/ Replace cgroup parent and name with our own since we may be running in a different context.\n\t*config.Cgroups = self.cgroup\n\n\treturn\n}\n\nfunc (self *dockerContainerHandler) readLibcontainerState() (state *libcontainer.State, err error) {\n\tstatePath := path.Join(self.libcontainerStateDir, self.id, \"state.json\")\n\tif !utils.FileExists(statePath) {\n\t\t\/\/ TODO(vmarmol): Remove this once we can depend on a newer Docker.\n\t\t\/\/ Libcontainer changed how its state was stored, try the old way of a \"pid\" file\n\t\tif utils.FileExists(path.Join(self.libcontainerStateDir, self.id, \"pid\")) {\n\t\t\t\/\/ We don't need the old state, return an empty state and we'll gracefully degrade.\n\t\t\tstate = new(libcontainer.State)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ TODO(vishh): Return file name as well once we have a better error interface.\n\t\terr = fileNotFound\n\t\treturn\n\t}\n\tf, err := os.Open(statePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open %s - %s\\n\", statePath, err)\n\t}\n\tdefer f.Close()\n\td := json.NewDecoder(f)\n\tretState := new(libcontainer.State)\n\terr = d.Decode(retState)\n\tif err != nil {\n\t\treturn\n\t}\n\tstate = retState\n\n\treturn\n}\n\nfunc libcontainerConfigToContainerSpec(config *libcontainer.Config, mi *info.MachineInfo) info.ContainerSpec {\n\tvar spec info.ContainerSpec\n\tspec.HasMemory = true\n\tspec.Memory.Limit = math.MaxUint64\n\tspec.Memory.SwapLimit = math.MaxUint64\n\tif config.Cgroups.Memory > 0 {\n\t\tspec.Memory.Limit = uint64(config.Cgroups.Memory)\n\t}\n\tif config.Cgroups.MemorySwap > 0 {\n\t\tspec.Memory.SwapLimit = uint64(config.Cgroups.MemorySwap)\n\t}\n\n\t\/\/ Get CPU info\n\tspec.HasCpu = true\n\tspec.Cpu.Limit = 1024\n\tif config.Cgroups.CpuShares != 0 {\n\t\tspec.Cpu.Limit = uint64(config.Cgroups.CpuShares)\n\t}\n\tif config.Cgroups.CpusetCpus == \"\" {\n\t\t\/\/ All cores are active.\n\t\tspec.Cpu.Mask = fmt.Sprintf(\"0-%d\", mi.NumCores-1)\n\t} else {\n\t\tspec.Cpu.Mask = config.Cgroups.CpusetCpus\n\t}\n\n\tspec.HasNetwork = true\n\treturn spec\n}\n\nfunc (self *dockerContainerHandler) GetSpec() (spec info.ContainerSpec, err error) {\n\tif self.isDockerRoot() {\n\t\treturn info.ContainerSpec{}, nil\n\t}\n\tmi, err := self.machineInfoFactory.GetMachineInfo()\n\tif err != nil {\n\t\treturn\n\t}\n\tlibcontainerConfig, err := self.readLibcontainerConfig()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tspec = libcontainerConfigToContainerSpec(libcontainerConfig, mi)\n\n\tif self.usesAufsDriver {\n\t\tspec.HasFilesystem = true\n\t}\n\n\treturn\n}\n\nfunc (self *dockerContainerHandler) getFsStats(stats *info.ContainerStats) error {\n\t\/\/ No support for non-aufs storage drivers.\n\tif !self.usesAufsDriver {\n\t\treturn nil\n\t}\n\n\t\/\/ As of now we assume that all the storage dirs are on the same device.\n\t\/\/ The first storage dir will be that of the image layers.\n\tdeviceInfo, err := self.fsInfo.GetDirFsDevice(self.storageDirs[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmi, err := self.machineInfoFactory.GetMachineInfo()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar limit uint64 = 0\n\t\/\/ Docker does not impose any filesystem limits for containers. So use capacity as limit.\n\tfor _, fs := range mi.Filesystems {\n\t\tif fs.Device == deviceInfo.Device {\n\t\t\tlimit = fs.Capacity\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfsStat := info.FsStats{Device: deviceInfo.Device, Limit: limit}\n\n\tvar usage uint64 = 0\n\tfor _, dir := range self.storageDirs {\n\t\t\/\/ TODO(Vishh): Add support for external mounts.\n\t\tdirUsage, err := self.fsInfo.GetDirUsage(dir)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tusage += dirUsage\n\t}\n\tfsStat.Usage = usage\n\tstats.Filesystem = append(stats.Filesystem, fsStat)\n\n\treturn nil\n}\n\nfunc (self *dockerContainerHandler) GetStats() (stats *info.ContainerStats, err error) {\n\tif self.isDockerRoot() {\n\t\treturn &info.ContainerStats{}, nil\n\t}\n\tstate, err := self.readLibcontainerState()\n\tif err != nil {\n\t\tif err == fileNotFound {\n\t\t\tglog.Errorf(\"Libcontainer state not found for container %q\", self.name)\n\t\t\treturn &info.ContainerStats{}, nil\n\t\t}\n\t\treturn\n\t}\n\n\tstats, err = containerLibcontainer.GetStats(&self.cgroup, state)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = self.getFsStats(stats)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn stats, nil\n}\n\nfunc (self *dockerContainerHandler) ListContainers(listType container.ListType) ([]info.ContainerReference, error) {\n\tif self.name != \"\/docker\" {\n\t\treturn []info.ContainerReference{}, nil\n\t}\n\topt := docker.ListContainersOptions{\n\t\tAll: true,\n\t}\n\tcontainers, err := self.client.ListContainers(opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ On non-systemd systems Docker containers are under \/docker.\n\tcontainerPrefix := \"\/docker\"\n\tif useSystemd {\n\t\tcontainerPrefix = \"\/system.slice\"\n\t}\n\n\tret := make([]info.ContainerReference, 0, len(containers)+1)\n\tfor _, c := range containers {\n\t\tif !strings.HasPrefix(c.Status, \"Up \") {\n\t\t\tcontinue\n\t\t}\n\n\t\tref := info.ContainerReference{\n\t\t\tName:    path.Join(containerPrefix, c.ID),\n\t\t\tAliases: c.Names,\n\t\t}\n\t\tret = append(ret, ref)\n\t}\n\n\treturn ret, nil\n}\n\nfunc (self *dockerContainerHandler) ListThreads(listType container.ListType) ([]int, error) {\n\treturn nil, nil\n}\n\nfunc (self *dockerContainerHandler) ListProcesses(listType container.ListType) ([]int, error) {\n\treturn cgroup_fs.GetPids(&self.cgroup)\n}\n\nfunc (self *dockerContainerHandler) WatchSubcontainers(events chan container.SubcontainerEvent) error {\n\treturn fmt.Errorf(\"watch is unimplemented in the Docker container driver\")\n}\n\nfunc (self *dockerContainerHandler) StopWatchingSubcontainers() error {\n\t\/\/ No-op for Docker driver.\n\treturn nil\n}\n<commit_msg>Only overwrite the Name and Parent in the libcontainer Cgroup.<commit_after>\/\/ Copyright 2014 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage docker\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com\/docker\/libcontainer\"\n\t\"github.com\/docker\/libcontainer\/cgroups\"\n\tcgroup_fs \"github.com\/docker\/libcontainer\/cgroups\/fs\"\n\t\"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/google\/cadvisor\/container\"\n\tcontainerLibcontainer \"github.com\/google\/cadvisor\/container\/libcontainer\"\n\t\"github.com\/google\/cadvisor\/fs\"\n\t\"github.com\/google\/cadvisor\/info\"\n\t\"github.com\/google\/cadvisor\/utils\"\n)\n\n\/\/ Relative path from Docker root to the libcontainer per-container state.\nconst pathToLibcontainerState = \"execdriver\/native\"\n\n\/\/ Path to aufs dir where all the files exist.\n\/\/ aufs\/layers is ignored here since it does not hold a lot of data.\n\/\/ aufs\/mnt contains the mount points used to compose the rootfs. Hence it is also ignored.\nvar pathToAufsDir = \"aufs\/diff\"\n\nvar fileNotFound = errors.New(\"file not found\")\n\ntype dockerContainerHandler struct {\n\tclient               *docker.Client\n\tname                 string\n\tid                   string\n\taliases              []string\n\tmachineInfoFactory   info.MachineInfoFactory\n\tlibcontainerStateDir string\n\tcgroup               cgroups.Cgroup\n\tusesAufsDriver       bool\n\tfsInfo               fs.FsInfo\n\tstorageDirs          []string\n}\n\nfunc newDockerContainerHandler(\n\tclient *docker.Client,\n\tname string,\n\tmachineInfoFactory info.MachineInfoFactory,\n\tdockerRootDir string,\n\tusesAufsDriver bool,\n) (container.ContainerHandler, error) {\n\tfsInfo, err := fs.NewFsInfo()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thandler := &dockerContainerHandler{\n\t\tclient:               client,\n\t\tname:                 name,\n\t\tmachineInfoFactory:   machineInfoFactory,\n\t\tlibcontainerStateDir: path.Join(dockerRootDir, pathToLibcontainerState),\n\t\tcgroup: cgroups.Cgroup{\n\t\t\tParent: \"\/\",\n\t\t\tName:   name,\n\t\t},\n\t\tusesAufsDriver: usesAufsDriver,\n\t\tfsInfo:         fsInfo,\n\t}\n\thandler.storageDirs = append(handler.storageDirs, path.Join(dockerRootDir, pathToAufsDir, path.Base(name)))\n\tif handler.isDockerRoot() {\n\t\treturn handler, nil\n\t}\n\tid := containerNameToDockerId(name)\n\thandler.id = id\n\tctnr, err := client.InspectContainer(id)\n\t\/\/ We assume that if Inspect fails then the container is not known to docker.\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to inspect container %s - %s\\n\", id, err)\n\t}\n\thandler.aliases = append(handler.aliases, path.Join(\"\/docker\", ctnr.Name))\n\treturn handler, nil\n}\n\nfunc containerNameToDockerId(name string) string {\n\tid := path.Base(name)\n\n\t\/\/ Turn systemd cgroup name into Docker ID.\n\tif useSystemd {\n\t\tconst systemdDockerPrefix = \"docker-\"\n\t\tif strings.HasPrefix(id, systemdDockerPrefix) {\n\t\t\tid = id[len(systemdDockerPrefix):]\n\t\t}\n\n\t\tconst systemdScopeSuffix = \".scope\"\n\t\tif strings.HasSuffix(id, systemdScopeSuffix) {\n\t\t\tid = id[:len(id)-len(systemdScopeSuffix)]\n\t\t}\n\t}\n\n\treturn id\n}\n\nfunc (self *dockerContainerHandler) ContainerReference() (info.ContainerReference, error) {\n\treturn info.ContainerReference{\n\t\tName:    self.name,\n\t\tAliases: self.aliases,\n\t}, nil\n}\n\nfunc (self *dockerContainerHandler) isDockerRoot() bool {\n\treturn self.name == \"\/docker\"\n}\n\n\/\/ TODO(vmarmol): Switch to getting this from libcontainer once we have a solid API.\nfunc (self *dockerContainerHandler) readLibcontainerConfig() (config *libcontainer.Config, err error) {\n\tconfigPath := path.Join(self.libcontainerStateDir, self.id, \"container.json\")\n\tif !utils.FileExists(configPath) {\n\t\t\/\/ TODO(vishh): Return file name as well once we have a better error interface.\n\t\terr = fileNotFound\n\t\treturn\n\t}\n\tf, err := os.Open(configPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open %s - %s\\n\", configPath, err)\n\t}\n\tdefer f.Close()\n\td := json.NewDecoder(f)\n\tretConfig := new(libcontainer.Config)\n\terr = d.Decode(retConfig)\n\tif err != nil {\n\t\treturn\n\t}\n\tconfig = retConfig\n\n\t\/\/ Replace cgroup parent and name with our own since we may be running in a different context.\n\tconfig.Cgroups.Name = self.cgroup.Name\n\tconfig.Cgroups.Parent = self.cgroup.Parent\n\n\treturn\n}\n\nfunc (self *dockerContainerHandler) readLibcontainerState() (state *libcontainer.State, err error) {\n\tstatePath := path.Join(self.libcontainerStateDir, self.id, \"state.json\")\n\tif !utils.FileExists(statePath) {\n\t\t\/\/ TODO(vmarmol): Remove this once we can depend on a newer Docker.\n\t\t\/\/ Libcontainer changed how its state was stored, try the old way of a \"pid\" file\n\t\tif utils.FileExists(path.Join(self.libcontainerStateDir, self.id, \"pid\")) {\n\t\t\t\/\/ We don't need the old state, return an empty state and we'll gracefully degrade.\n\t\t\tstate = new(libcontainer.State)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ TODO(vishh): Return file name as well once we have a better error interface.\n\t\terr = fileNotFound\n\t\treturn\n\t}\n\tf, err := os.Open(statePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open %s - %s\\n\", statePath, err)\n\t}\n\tdefer f.Close()\n\td := json.NewDecoder(f)\n\tretState := new(libcontainer.State)\n\terr = d.Decode(retState)\n\tif err != nil {\n\t\treturn\n\t}\n\tstate = retState\n\n\treturn\n}\n\nfunc libcontainerConfigToContainerSpec(config *libcontainer.Config, mi *info.MachineInfo) info.ContainerSpec {\n\tvar spec info.ContainerSpec\n\tspec.HasMemory = true\n\tspec.Memory.Limit = math.MaxUint64\n\tspec.Memory.SwapLimit = math.MaxUint64\n\tif config.Cgroups.Memory > 0 {\n\t\tspec.Memory.Limit = uint64(config.Cgroups.Memory)\n\t}\n\tif config.Cgroups.MemorySwap > 0 {\n\t\tspec.Memory.SwapLimit = uint64(config.Cgroups.MemorySwap)\n\t}\n\n\t\/\/ Get CPU info\n\tspec.HasCpu = true\n\tspec.Cpu.Limit = 1024\n\tif config.Cgroups.CpuShares != 0 {\n\t\tspec.Cpu.Limit = uint64(config.Cgroups.CpuShares)\n\t}\n\tif config.Cgroups.CpusetCpus == \"\" {\n\t\t\/\/ All cores are active.\n\t\tspec.Cpu.Mask = fmt.Sprintf(\"0-%d\", mi.NumCores-1)\n\t} else {\n\t\tspec.Cpu.Mask = config.Cgroups.CpusetCpus\n\t}\n\n\tspec.HasNetwork = true\n\treturn spec\n}\n\nfunc (self *dockerContainerHandler) GetSpec() (spec info.ContainerSpec, err error) {\n\tif self.isDockerRoot() {\n\t\treturn info.ContainerSpec{}, nil\n\t}\n\tmi, err := self.machineInfoFactory.GetMachineInfo()\n\tif err != nil {\n\t\treturn\n\t}\n\tlibcontainerConfig, err := self.readLibcontainerConfig()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tspec = libcontainerConfigToContainerSpec(libcontainerConfig, mi)\n\n\tif self.usesAufsDriver {\n\t\tspec.HasFilesystem = true\n\t}\n\n\treturn\n}\n\nfunc (self *dockerContainerHandler) getFsStats(stats *info.ContainerStats) error {\n\t\/\/ No support for non-aufs storage drivers.\n\tif !self.usesAufsDriver {\n\t\treturn nil\n\t}\n\n\t\/\/ As of now we assume that all the storage dirs are on the same device.\n\t\/\/ The first storage dir will be that of the image layers.\n\tdeviceInfo, err := self.fsInfo.GetDirFsDevice(self.storageDirs[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmi, err := self.machineInfoFactory.GetMachineInfo()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar limit uint64 = 0\n\t\/\/ Docker does not impose any filesystem limits for containers. So use capacity as limit.\n\tfor _, fs := range mi.Filesystems {\n\t\tif fs.Device == deviceInfo.Device {\n\t\t\tlimit = fs.Capacity\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfsStat := info.FsStats{Device: deviceInfo.Device, Limit: limit}\n\n\tvar usage uint64 = 0\n\tfor _, dir := range self.storageDirs {\n\t\t\/\/ TODO(Vishh): Add support for external mounts.\n\t\tdirUsage, err := self.fsInfo.GetDirUsage(dir)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tusage += dirUsage\n\t}\n\tfsStat.Usage = usage\n\tstats.Filesystem = append(stats.Filesystem, fsStat)\n\n\treturn nil\n}\n\nfunc (self *dockerContainerHandler) GetStats() (stats *info.ContainerStats, err error) {\n\tif self.isDockerRoot() {\n\t\treturn &info.ContainerStats{}, nil\n\t}\n\tstate, err := self.readLibcontainerState()\n\tif err != nil {\n\t\tif err == fileNotFound {\n\t\t\tglog.Errorf(\"Libcontainer state not found for container %q\", self.name)\n\t\t\treturn &info.ContainerStats{}, nil\n\t\t}\n\t\treturn\n\t}\n\n\tstats, err = containerLibcontainer.GetStats(&self.cgroup, state)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = self.getFsStats(stats)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn stats, nil\n}\n\nfunc (self *dockerContainerHandler) ListContainers(listType container.ListType) ([]info.ContainerReference, error) {\n\tif self.name != \"\/docker\" {\n\t\treturn []info.ContainerReference{}, nil\n\t}\n\topt := docker.ListContainersOptions{\n\t\tAll: true,\n\t}\n\tcontainers, err := self.client.ListContainers(opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ On non-systemd systems Docker containers are under \/docker.\n\tcontainerPrefix := \"\/docker\"\n\tif useSystemd {\n\t\tcontainerPrefix = \"\/system.slice\"\n\t}\n\n\tret := make([]info.ContainerReference, 0, len(containers)+1)\n\tfor _, c := range containers {\n\t\tif !strings.HasPrefix(c.Status, \"Up \") {\n\t\t\tcontinue\n\t\t}\n\n\t\tref := info.ContainerReference{\n\t\t\tName:    path.Join(containerPrefix, c.ID),\n\t\t\tAliases: c.Names,\n\t\t}\n\t\tret = append(ret, ref)\n\t}\n\n\treturn ret, nil\n}\n\nfunc (self *dockerContainerHandler) ListThreads(listType container.ListType) ([]int, error) {\n\treturn nil, nil\n}\n\nfunc (self *dockerContainerHandler) ListProcesses(listType container.ListType) ([]int, error) {\n\treturn cgroup_fs.GetPids(&self.cgroup)\n}\n\nfunc (self *dockerContainerHandler) WatchSubcontainers(events chan container.SubcontainerEvent) error {\n\treturn fmt.Errorf(\"watch is unimplemented in the Docker container driver\")\n}\n\nfunc (self *dockerContainerHandler) StopWatchingSubcontainers() error {\n\t\/\/ No-op for Docker driver.\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014, Bryan Matsuo. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ launch.go [created: Thu, 20 Mar 2014]\n\n\/*\nLaunch instances\n\nthe \"launch\" command can be used to spin up one or more new ec2 instances.\n\n\toti launch -h\n\n*\/\npackage main\n\nimport (\n\t\"code.google.com\/p\/go-uuid\/uuid\"\n\t\"github.com\/bmatsuo\/oti\/otisub\"\n\t\"github.com\/bmatsuo\/oti\/otitag\"\n\t\"github.com\/crowdmob\/goamz\/aws\"\n\tawsec2 \"github.com\/crowdmob\/goamz\/ec2\"\n\n\t\"flag\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar launch = otisub.Register(\"launch\", func(args []string) {\n\tfs := otisub.FlagSet(flag.ExitOnError, \"inspect\", \"imagename [directive ...] ...\")\n\tsessionType := fs.String(\"s\", \"launch\", \"session type for management purposes\")\n\tkeyname := fs.String(\"k\", \"\", \"default key pair used to run instances\")\n\twaitPending := fs.Bool(\"w\", false, \"wait while instances are 'pending'\")\n\tfs.Parse(args)\n\targs = fs.Args()\n\n\tumfts, err := ParseUserLaunchManifest(args)\n\tif err != nil {\n\t\tLog.Fatal(err)\n\t}\n\n\tif len(umfts) == 0 {\n\t\tLog.Fatal(\"no manifests\")\n\t}\n\n\tawsregion := aws.USEast\n\tawsauth, err := Config.AwsAuth()\n\tif err != nil {\n\t\tLog.Fatalln(\"error reading aws credentials: \", err)\n\t}\n\n\tec2 := awsec2.New(awsauth, awsregion)\n\n\t\/\/ find images based on manifest names (if no image is explicitly specified)\n\tfor _, mft := range ManifestsNeedingImageLookup(umfts) { \/\/ mft points into mfts\n\t\timages, err := LookupImages(ec2, mft.Name)\n\t\tif err != nil {\n\t\t\tLog.Fatal(\"error locating image ids: \", err)\n\t\t}\n\t\tif len(images) > 0 {\n\t\t\tLog.Fatal(\"ambigous results: %v\", images)\n\t\t}\n\t\tmft.Ec2ImageId = images[0].Id\n\t}\n\n\tif DEBUG {\n\t\tfor _, m := range umfts {\n\t\t\tLog.Printf(\"%#v\", m)\n\t\t}\n\t}\n\n\tsessionId, err := NewSessionId(*sessionType)\n\tif err != nil {\n\t\tLog.Fatal(err)\n\t}\n\n\tLog.Println(\"session id: \", sessionId)\n\tfmt.Println(sessionId) \/\/ to stdout\n\n\tmfts, err := BuildSystemLaunchManifests(ec2, sessionId, *keyname, umfts)\n\tif err != nil {\n\t\tLog.Fatalln(err)\n\t}\n\n\tif DEBUG {\n\t\tfor _, m := range mfts {\n\t\t\tLog.Printf(\"%#v\", m)\n\t\t}\n\t}\n\n\tvar haserrors bool\n\tfor _, m := range mfts {\n\t\trunopts := &awsec2.RunInstancesOptions{\n\t\t\tImageId:        m.Ec2.ImageId,\n\t\t\tMinCount:       m.Min,\n\t\t\tMaxCount:       m.Max,\n\t\t\tKeyName:        m.Ec2.KeyName,\n\t\t\tInstanceType:   m.Ec2.InstanceType,\n\t\t\tSecurityGroups: m.Ec2.SecurityGroups,\n\t\t}\n\t\tresp, err := ec2.RunInstances(runopts)\n\t\tif err != nil {\n\t\t\thaserrors = true\n\t\t\tLog.Printf(\"error running %q: %v\", m.Name, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar instanceIds []string\n\t\tfor _, inst := range resp.Instances {\n\t\t\tinstanceIds = append(instanceIds, inst.InstanceId)\n\t\t}\n\n\t\tif DEBUG {\n\t\t\tLog.Printf(\"started instances: %v\", instanceIds)\n\t\t}\n\n\t\t_, err = ec2.CreateTags(instanceIds, []awsec2.Tag{\n\t\t\t{Config.Ec2Tag(otitag.SessionId), string(m.SessionId)},\n\t\t})\n\t\tif err != nil {\n\t\t\thaserrors = true\n\t\t\tLog.Printf(\"error tagging instances: %v\", err)\n\t\t}\n\t}\n\tif haserrors {\n\t\tLog.Fatal()\n\t}\n\n\t\/\/ wait for instances to boot\n\tif *waitPending {\n\t\tLog.Fatal(\"waiting not implemented\")\n\t}\n})\n\n\/\/ create LaunchManifests from the given ULMs. the manifests are given the\n\/\/ provided session id and, if the ULM does not specify a ec2 key name, the\n\/\/ provided keyname as well.\nfunc BuildSystemLaunchManifests(ec2 *awsec2.EC2, sessionId SessionId, keyname string, umfts []ULM) ([]LaunchManifest, error) {\n\tmfts := make([]LaunchManifest, len(umfts))\n\n\t\/\/ get real security groups.\n\tsecgroups, err := LookupSecurityGroups(ec2, umfts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error locating up security groups: %v\", err)\n\t}\n\n\t\/\/ get key pairs TODO\n\n\t\/\/ build each LaunchManifest\n\tfor i := range umfts {\n\t\tm := &mfts[i]\n\t\tum := &umfts[i]\n\t\tm.SessionId = sessionId\n\t\tm.Name = um.Name\n\t\tm.Min = um.Min\n\t\tm.Max = um.Max\n\t\tm.Ec2.InstanceType = um.Ec2InstanceType\n\t\tm.Ec2.ImageId = um.Ec2ImageId\n\t\tm.Ec2.KeyName = um.Ec2KeyName\n\t\tif m.Ec2.KeyName == \"\" {\n\t\t\tm.Ec2.KeyName = keyname\n\t\t}\n\t\tfor _, group := range um.Ec2SecGroups {\n\t\t\tfound := false\n\t\t\tfor _, info := range secgroups {\n\t\t\t\tif info.Id == group {\n\t\t\t\t\tm.Ec2.SecurityGroups = append(m.Ec2.SecurityGroups, info.SecurityGroup)\n\t\t\t\t\tfound = true\n\t\t\t\t} else if info.Name == group {\n\t\t\t\t\tm.Ec2.SecurityGroups = append(m.Ec2.SecurityGroups, info.SecurityGroup)\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\treturn nil, fmt.Errorf(\"unknown security group: %q\", group)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn mfts, nil\n}\n\nfunc LookupSecurityGroups(ec2 *awsec2.EC2, mfts []ULM) ([]awsec2.SecurityGroupInfo, error) {\n\tvar groups []awsec2.SecurityGroup\n\tfor i := range mfts {\n\t\tfor _, group := range mfts[i].Ec2SecGroups {\n\t\t\tif strings.HasPrefix(group, \"sg-\") {\n\t\t\t\tgroups = append(groups, awsec2.SecurityGroup{Id: group})\n\t\t\t} else {\n\t\t\t\tgroups = append(groups, awsec2.SecurityGroup{Name: group})\n\t\t\t}\n\t\t}\n\t}\n\n\tresp, err := ec2.SecurityGroups(groups, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.Groups, nil\n}\n\nfunc ManifestsNeedingImageLookup(ulms []ULM) []*ULM {\n\tvar _ulms []*ULM\n\tfor i := range ulms {\n\t\tif ulms[i].Ec2ImageId == \"\" {\n\t\t\t_ulms = append(_ulms, &ulms[i])\n\t\t}\n\t}\n\treturn _ulms\n}\n\n\/\/ use the packer config to locate images on ec2.\nfunc LookupImages(ec2 *awsec2.EC2, name string) ([]awsec2.Image, error) {\n\treturn nil, fmt.Errorf(\"unimplemented\")\n}\n\n\/\/ User Launch Manifest -- information read from the command line\ntype ULM struct {\n\tName            string   \/\/ OTI name that can be used to filter images\n\tEc2ImageId      string   \/\/ AWS EC2 image id.\n\tEc2InstanceType string   \/\/ AWS EC2 instance type.\n\tEc2KeyName      string   \/\/ AWS EC2 key pair name\n\tEc2SecGroups    []string \/\/ Security groups to assign the instances\n\tMin, Max        int      \/\/ may not be empty\n}\n\ntype ArgumentError struct {\n\ti   int\n\terr error\n}\n\nfunc (err ArgumentError) Error() string {\n\treturn fmt.Sprintf(\"argument %d: %v\", err.i, err.err)\n}\n\nvar ErrEndOfArgs = ArgumentError{-1, fmt.Errorf(\"no more arguments\")}\n\n\/\/ parses a set launch manifest. manifests have the form\n\/\/\tname [ flag[=val] ... ] -- ...\n\/\/ for reference use the following list of flags and the default values\n\/\/\tflag      alias  default\n\/\/\tmin              1\n\/\/\tmax              1\n\/\/\tec2type          \"t1.micro\"\n\/\/\tami              \"\"\n\/\/\tkeyname          \"\"\n\/\/\tsecgroup         \"\"\nfunc ParseUserLaunchManifest(args []string) ([]ULM, error) {\n\tulms := make([]ULM, 0, len(args))\n\tsepseq := \"--\"\n\n\tparseUlm := func(args []string) (ulm ULM, rest []string, err error) {\n\t\trest = args\n\n\t\tif len(rest) == 0 {\n\t\t\treturn ULM{}, nil, ErrEndOfArgs\n\t\t}\n\n\t\tif rest[0] == sepseq {\n\t\t\terr := fmt.Errorf(\"unexpected separator sequence %v\", sepseq)\n\t\t\treturn ULM{}, nil, err\n\t\t}\n\n\t\tulm.Name, rest = args[0], rest[1:]\n\n\t\t\/\/ set defaults\n\t\tulm.Min, ulm.Max = 1, 1\n\t\tulm.Ec2InstanceType = \"t1.micro\"\n\n\t\tretErr := func(err error) (ULM, []string, error) {\n\t\t\treturn ULM{}, nil, err\n\t\t}\n\t\tulmErr := func(err error) error { return fmt.Errorf(\"%v %v\", ulm.Name, err) }\n\t\tulmFlagErr := func(key string, err error) error {\n\t\t\treturn ulmErr(fmt.Errorf(\"invalid flag %q: %v\", key, err))\n\t\t}\n\n\t\tflags := make(map[string][]string)\n\t\tfor len(rest) > 0 && rest[0] != sepseq {\n\t\t\tvar head string\n\t\t\thead, rest = rest[0], rest[1:]\n\t\t\tkey, value := head, \"\"\n\n\t\t\tpair := strings.SplitN(key, \"=\", 2)\n\t\t\tif len(pair) == 2 {\n\t\t\t\tkey, value = pair[0], pair[1]\n\t\t\t}\n\n\t\t\tswitch key {\n\t\t\tcase \"min\", \"max\", \"secgroup\", \"ami\", \"keyname\", \"ec2type\":\n\t\t\tdefault:\n\t\t\t\terr := fmt.Errorf(\"unexpected flag %v\", key)\n\t\t\t\treturn retErr(ulmErr(err))\n\t\t\t}\n\n\t\t\tflags[key] = append(flags[key], value)\n\t\t}\n\n\t\tfor k, vs := range flags {\n\t\t\tvar err error\n\t\t\tnumvs := len(vs)\n\t\t\tswitch k {\n\t\t\tcase \"min\":\n\t\t\t\tif numvs > 1 {\n\t\t\t\t\terr = fmt.Errorf(\"specified multiple times\")\n\t\t\t\t} else {\n\t\t\t\t\tulm.Min, err = strconv.Atoi(vs[0])\n\t\t\t\t}\n\t\t\tcase \"max\":\n\t\t\t\tif numvs > 1 {\n\t\t\t\t\terr = fmt.Errorf(\"specified multiple times\")\n\t\t\t\t} else {\n\t\t\t\t\tulm.Max, err = strconv.Atoi(vs[0])\n\t\t\t\t}\n\t\t\tcase \"secgroup\":\n\t\t\t\tulm.Ec2SecGroups = vs\n\t\t\tcase \"ec2type\":\n\t\t\t\tif numvs > 1 {\n\t\t\t\t\terr = fmt.Errorf(\"specified multiple times\")\n\t\t\t\t} else {\n\t\t\t\t\tulm.Ec2InstanceType = vs[0]\n\t\t\t\t}\n\t\t\tcase \"ami\":\n\t\t\t\tif numvs > 1 {\n\t\t\t\t\terr = fmt.Errorf(\"specified multiple times\")\n\t\t\t\t} else {\n\t\t\t\t\tulm.Ec2ImageId = vs[0]\n\t\t\t\t}\n\t\t\tcase \"keyname\":\n\t\t\t\tif numvs > 1 {\n\t\t\t\t\terr = fmt.Errorf(\"specified multiple times\")\n\t\t\t\t} else {\n\t\t\t\t\tulm.Ec2KeyName = vs[0]\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn retErr(ulmFlagErr(k, err))\n\t\t\t}\n\t\t}\n\n\t\tif len(ulm.Ec2SecGroups) == 0 {\n\t\t\treturn retErr(ulmFlagErr(\"secgroup\", fmt.Errorf(\"required for now\")))\n\t\t}\n\n\t\tif ulm.Ec2ImageId == \"\" {\n\t\t\treturn retErr(ulmFlagErr(\"ami\", fmt.Errorf(\"required for now\")))\n\t\t}\n\n\t\tif ulm.Min > ulm.Max {\n\t\t\treturn retErr(ulmErr(err))\n\t\t}\n\n\t\tif len(rest) > 0 && rest[0] == sepseq {\n\t\t\treturn ulm, rest[1:], nil\n\t\t} else {\n\t\t\treturn ulm, nil, nil\n\t\t}\n\t}\n\n\tfor len(args) > 0 {\n\t\tvar ulm ULM\n\t\tvar err error\n\t\tulm, args, err = parseUlm(args)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tulms = append(ulms, ulm)\n\t}\n\n\treturn ulms, nil\n}\n\ntype LaunchManifest struct {\n\tName      string    \/\/ configured by the user\n\tMin, Max  int       \/\/ configured by the user\n\tSessionId SessionId \/\/ generated at runtime\n\tEc2       struct {\n\t\tImageId        string                 \/\/ located AWS image id\n\t\tInstanceType   string                 \/\/ configured by the user\n\t\tKeyName        string                 \/\/ configured by the user or generated at run-time\n\t\tSecurityGroups []awsec2.SecurityGroup \/\/ configured by the user or created at runtime\n\t}\n}\n\ntype SessionId string\n\nfunc NewSessionId(sessiontype string) (SessionId, error) {\n\tif strings.Contains(sessiontype, \":\") {\n\t\treturn \"\", fmt.Errorf(\"session type cannot contain ':'\")\n\t}\n\tif sessiontype == \"\" {\n\t\tsessiontype = \"session\"\n\t}\n\tsid := SessionId(fmt.Sprintf(\"%s:%v\", sessiontype, uuid.New()))\n\treturn sid, nil\n}\n\nfunc (sid SessionId) Type() string {\n\treturn strings.SplitN(string(sid), \":\", 2)[0]\n}\n<commit_msg>add region flag -r to `oti launch`<commit_after>\/\/ Copyright 2014, Bryan Matsuo. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ launch.go [created: Thu, 20 Mar 2014]\n\n\/*\nLaunch instances\n\nthe \"launch\" command can be used to spin up one or more new ec2 instances.\n\n\toti launch -h\n\n*\/\npackage main\n\nimport (\n\t\"code.google.com\/p\/go-uuid\/uuid\"\n\t\"github.com\/bmatsuo\/oti\/otisub\"\n\t\"github.com\/bmatsuo\/oti\/otitag\"\n\t\"github.com\/crowdmob\/goamz\/aws\"\n\tawsec2 \"github.com\/crowdmob\/goamz\/ec2\"\n\n\t\"flag\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar launch = otisub.Register(\"launch\", func(args []string) {\n\tfs := otisub.FlagSet(flag.ExitOnError, \"inspect\", \"imagename [directive ...] ...\")\n\tsessionType := fs.String(\"s\", \"launch\", \"session type for management purposes\")\n\tkeyname := fs.String(\"k\", \"\", \"default key pair used to run instances\")\n\tregion := fs.String(\"r\", \"us-east-1\", \"region to run instances in\")\n\twaitPending := fs.Bool(\"w\", false, \"wait while instances are 'pending'\")\n\tfs.Parse(args)\n\targs = fs.Args()\n\n\tumfts, err := ParseUserLaunchManifest(args)\n\tif err != nil {\n\t\tLog.Fatal(err)\n\t}\n\n\tif len(umfts) == 0 {\n\t\tLog.Fatal(\"no manifests\")\n\t}\n\n\tif *region != \"us-east-1\" {\n\t\tLog.Fatal(\"unsupported region %q\", *region)\n\t}\n\tawsregion := aws.USEast\n\tawsauth, err := Config.AwsAuth()\n\tif err != nil {\n\t\tLog.Fatalln(\"error reading aws credentials: \", err)\n\t}\n\n\tec2 := awsec2.New(awsauth, awsregion)\n\n\t\/\/ find images based on manifest names (if no image is explicitly specified)\n\tfor _, mft := range ManifestsNeedingImageLookup(umfts) { \/\/ mft points into mfts\n\t\timages, err := LookupImages(ec2, mft.Name)\n\t\tif err != nil {\n\t\t\tLog.Fatal(\"error locating image ids: \", err)\n\t\t}\n\t\tif len(images) > 0 {\n\t\t\tLog.Fatal(\"ambigous results: %v\", images)\n\t\t}\n\t\tmft.Ec2ImageId = images[0].Id\n\t}\n\n\tif DEBUG {\n\t\tfor _, m := range umfts {\n\t\t\tLog.Printf(\"%#v\", m)\n\t\t}\n\t}\n\n\tsessionId, err := NewSessionId(*sessionType)\n\tif err != nil {\n\t\tLog.Fatal(err)\n\t}\n\n\tLog.Println(\"session id: \", sessionId)\n\tfmt.Println(sessionId) \/\/ to stdout\n\n\tmfts, err := BuildSystemLaunchManifests(ec2, sessionId, *keyname, umfts)\n\tif err != nil {\n\t\tLog.Fatalln(err)\n\t}\n\n\tif DEBUG {\n\t\tfor _, m := range mfts {\n\t\t\tLog.Printf(\"%#v\", m)\n\t\t}\n\t}\n\n\tvar haserrors bool\n\tfor _, m := range mfts {\n\t\trunopts := &awsec2.RunInstancesOptions{\n\t\t\tImageId:        m.Ec2.ImageId,\n\t\t\tMinCount:       m.Min,\n\t\t\tMaxCount:       m.Max,\n\t\t\tKeyName:        m.Ec2.KeyName,\n\t\t\tInstanceType:   m.Ec2.InstanceType,\n\t\t\tSecurityGroups: m.Ec2.SecurityGroups,\n\t\t}\n\t\tresp, err := ec2.RunInstances(runopts)\n\t\tif err != nil {\n\t\t\thaserrors = true\n\t\t\tLog.Printf(\"error running %q: %v\", m.Name, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar instanceIds []string\n\t\tfor _, inst := range resp.Instances {\n\t\t\tinstanceIds = append(instanceIds, inst.InstanceId)\n\t\t}\n\n\t\tif DEBUG {\n\t\t\tLog.Printf(\"started instances: %v\", instanceIds)\n\t\t}\n\n\t\t_, err = ec2.CreateTags(instanceIds, []awsec2.Tag{\n\t\t\t{Config.Ec2Tag(otitag.SessionId), string(m.SessionId)},\n\t\t})\n\t\tif err != nil {\n\t\t\thaserrors = true\n\t\t\tLog.Printf(\"error tagging instances: %v\", err)\n\t\t}\n\t}\n\tif haserrors {\n\t\tLog.Fatal()\n\t}\n\n\t\/\/ wait for instances to boot\n\tif *waitPending {\n\t\tLog.Fatal(\"waiting not implemented\")\n\t}\n})\n\n\/\/ create LaunchManifests from the given ULMs. the manifests are given the\n\/\/ provided session id and, if the ULM does not specify a ec2 key name, the\n\/\/ provided keyname as well.\nfunc BuildSystemLaunchManifests(ec2 *awsec2.EC2, sessionId SessionId, keyname string, umfts []ULM) ([]LaunchManifest, error) {\n\tmfts := make([]LaunchManifest, len(umfts))\n\n\t\/\/ get real security groups.\n\tsecgroups, err := LookupSecurityGroups(ec2, umfts)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error locating up security groups: %v\", err)\n\t}\n\n\t\/\/ get key pairs TODO\n\n\t\/\/ build each LaunchManifest\n\tfor i := range umfts {\n\t\tm := &mfts[i]\n\t\tum := &umfts[i]\n\t\tm.SessionId = sessionId\n\t\tm.Name = um.Name\n\t\tm.Min = um.Min\n\t\tm.Max = um.Max\n\t\tm.Ec2.InstanceType = um.Ec2InstanceType\n\t\tm.Ec2.ImageId = um.Ec2ImageId\n\t\tm.Ec2.KeyName = um.Ec2KeyName\n\t\tif m.Ec2.KeyName == \"\" {\n\t\t\tm.Ec2.KeyName = keyname\n\t\t}\n\t\tfor _, group := range um.Ec2SecGroups {\n\t\t\tfound := false\n\t\t\tfor _, info := range secgroups {\n\t\t\t\tif info.Id == group {\n\t\t\t\t\tm.Ec2.SecurityGroups = append(m.Ec2.SecurityGroups, info.SecurityGroup)\n\t\t\t\t\tfound = true\n\t\t\t\t} else if info.Name == group {\n\t\t\t\t\tm.Ec2.SecurityGroups = append(m.Ec2.SecurityGroups, info.SecurityGroup)\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\treturn nil, fmt.Errorf(\"unknown security group: %q\", group)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn mfts, nil\n}\n\nfunc LookupSecurityGroups(ec2 *awsec2.EC2, mfts []ULM) ([]awsec2.SecurityGroupInfo, error) {\n\tvar groups []awsec2.SecurityGroup\n\tfor i := range mfts {\n\t\tfor _, group := range mfts[i].Ec2SecGroups {\n\t\t\tif strings.HasPrefix(group, \"sg-\") {\n\t\t\t\tgroups = append(groups, awsec2.SecurityGroup{Id: group})\n\t\t\t} else {\n\t\t\t\tgroups = append(groups, awsec2.SecurityGroup{Name: group})\n\t\t\t}\n\t\t}\n\t}\n\n\tresp, err := ec2.SecurityGroups(groups, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.Groups, nil\n}\n\nfunc ManifestsNeedingImageLookup(ulms []ULM) []*ULM {\n\tvar _ulms []*ULM\n\tfor i := range ulms {\n\t\tif ulms[i].Ec2ImageId == \"\" {\n\t\t\t_ulms = append(_ulms, &ulms[i])\n\t\t}\n\t}\n\treturn _ulms\n}\n\n\/\/ use the packer config to locate images on ec2.\nfunc LookupImages(ec2 *awsec2.EC2, name string) ([]awsec2.Image, error) {\n\treturn nil, fmt.Errorf(\"unimplemented\")\n}\n\n\/\/ User Launch Manifest -- information read from the command line\ntype ULM struct {\n\tName            string   \/\/ OTI name that can be used to filter images\n\tEc2ImageId      string   \/\/ AWS EC2 image id.\n\tEc2InstanceType string   \/\/ AWS EC2 instance type.\n\tEc2KeyName      string   \/\/ AWS EC2 key pair name\n\tEc2SecGroups    []string \/\/ Security groups to assign the instances\n\tMin, Max        int      \/\/ may not be empty\n}\n\ntype ArgumentError struct {\n\ti   int\n\terr error\n}\n\nfunc (err ArgumentError) Error() string {\n\treturn fmt.Sprintf(\"argument %d: %v\", err.i, err.err)\n}\n\nvar ErrEndOfArgs = ArgumentError{-1, fmt.Errorf(\"no more arguments\")}\n\n\/\/ parses a set launch manifest. manifests have the form\n\/\/\tname [ flag[=val] ... ] -- ...\n\/\/ for reference use the following list of flags and the default values\n\/\/\tflag      alias  default\n\/\/\tmin              1\n\/\/\tmax              1\n\/\/\tec2type          \"t1.micro\"\n\/\/\tami              \"\"\n\/\/\tkeyname          \"\"\n\/\/\tsecgroup         \"\"\nfunc ParseUserLaunchManifest(args []string) ([]ULM, error) {\n\tulms := make([]ULM, 0, len(args))\n\tsepseq := \"--\"\n\n\tparseUlm := func(args []string) (ulm ULM, rest []string, err error) {\n\t\trest = args\n\n\t\tif len(rest) == 0 {\n\t\t\treturn ULM{}, nil, ErrEndOfArgs\n\t\t}\n\n\t\tif rest[0] == sepseq {\n\t\t\terr := fmt.Errorf(\"unexpected separator sequence %v\", sepseq)\n\t\t\treturn ULM{}, nil, err\n\t\t}\n\n\t\tulm.Name, rest = args[0], rest[1:]\n\n\t\t\/\/ set defaults\n\t\tulm.Min, ulm.Max = 1, 1\n\t\tulm.Ec2InstanceType = \"t1.micro\"\n\n\t\tretErr := func(err error) (ULM, []string, error) {\n\t\t\treturn ULM{}, nil, err\n\t\t}\n\t\tulmErr := func(err error) error { return fmt.Errorf(\"%v %v\", ulm.Name, err) }\n\t\tulmFlagErr := func(key string, err error) error {\n\t\t\treturn ulmErr(fmt.Errorf(\"invalid flag %q: %v\", key, err))\n\t\t}\n\n\t\tflags := make(map[string][]string)\n\t\tfor len(rest) > 0 && rest[0] != sepseq {\n\t\t\tvar head string\n\t\t\thead, rest = rest[0], rest[1:]\n\t\t\tkey, value := head, \"\"\n\n\t\t\tpair := strings.SplitN(key, \"=\", 2)\n\t\t\tif len(pair) == 2 {\n\t\t\t\tkey, value = pair[0], pair[1]\n\t\t\t}\n\n\t\t\tswitch key {\n\t\t\tcase \"min\", \"max\", \"secgroup\", \"ami\", \"keyname\", \"ec2type\":\n\t\t\tdefault:\n\t\t\t\terr := fmt.Errorf(\"unexpected flag %v\", key)\n\t\t\t\treturn retErr(ulmErr(err))\n\t\t\t}\n\n\t\t\tflags[key] = append(flags[key], value)\n\t\t}\n\n\t\tfor k, vs := range flags {\n\t\t\tvar err error\n\t\t\tnumvs := len(vs)\n\t\t\tswitch k {\n\t\t\tcase \"min\":\n\t\t\t\tif numvs > 1 {\n\t\t\t\t\terr = fmt.Errorf(\"specified multiple times\")\n\t\t\t\t} else {\n\t\t\t\t\tulm.Min, err = strconv.Atoi(vs[0])\n\t\t\t\t}\n\t\t\tcase \"max\":\n\t\t\t\tif numvs > 1 {\n\t\t\t\t\terr = fmt.Errorf(\"specified multiple times\")\n\t\t\t\t} else {\n\t\t\t\t\tulm.Max, err = strconv.Atoi(vs[0])\n\t\t\t\t}\n\t\t\tcase \"secgroup\":\n\t\t\t\tulm.Ec2SecGroups = vs\n\t\t\tcase \"ec2type\":\n\t\t\t\tif numvs > 1 {\n\t\t\t\t\terr = fmt.Errorf(\"specified multiple times\")\n\t\t\t\t} else {\n\t\t\t\t\tulm.Ec2InstanceType = vs[0]\n\t\t\t\t}\n\t\t\tcase \"ami\":\n\t\t\t\tif numvs > 1 {\n\t\t\t\t\terr = fmt.Errorf(\"specified multiple times\")\n\t\t\t\t} else {\n\t\t\t\t\tulm.Ec2ImageId = vs[0]\n\t\t\t\t}\n\t\t\tcase \"keyname\":\n\t\t\t\tif numvs > 1 {\n\t\t\t\t\terr = fmt.Errorf(\"specified multiple times\")\n\t\t\t\t} else {\n\t\t\t\t\tulm.Ec2KeyName = vs[0]\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn retErr(ulmFlagErr(k, err))\n\t\t\t}\n\t\t}\n\n\t\tif len(ulm.Ec2SecGroups) == 0 {\n\t\t\treturn retErr(ulmFlagErr(\"secgroup\", fmt.Errorf(\"required for now\")))\n\t\t}\n\n\t\tif ulm.Ec2ImageId == \"\" {\n\t\t\treturn retErr(ulmFlagErr(\"ami\", fmt.Errorf(\"required for now\")))\n\t\t}\n\n\t\tif ulm.Min > ulm.Max {\n\t\t\treturn retErr(ulmErr(err))\n\t\t}\n\n\t\tif len(rest) > 0 && rest[0] == sepseq {\n\t\t\treturn ulm, rest[1:], nil\n\t\t} else {\n\t\t\treturn ulm, nil, nil\n\t\t}\n\t}\n\n\tfor len(args) > 0 {\n\t\tvar ulm ULM\n\t\tvar err error\n\t\tulm, args, err = parseUlm(args)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tulms = append(ulms, ulm)\n\t}\n\n\treturn ulms, nil\n}\n\ntype LaunchManifest struct {\n\tName      string    \/\/ configured by the user\n\tMin, Max  int       \/\/ configured by the user\n\tSessionId SessionId \/\/ generated at runtime\n\tEc2       struct {\n\t\tImageId        string                 \/\/ located AWS image id\n\t\tInstanceType   string                 \/\/ configured by the user\n\t\tKeyName        string                 \/\/ configured by the user or generated at run-time\n\t\tSecurityGroups []awsec2.SecurityGroup \/\/ configured by the user or created at runtime\n\t}\n}\n\ntype SessionId string\n\nfunc NewSessionId(sessiontype string) (SessionId, error) {\n\tif strings.Contains(sessiontype, \":\") {\n\t\treturn \"\", fmt.Errorf(\"session type cannot contain ':'\")\n\t}\n\tif sessiontype == \"\" {\n\t\tsessiontype = \"session\"\n\t}\n\tsid := SessionId(fmt.Sprintf(\"%s:%v\", sessiontype, uuid.New()))\n\treturn sid, nil\n}\n\nfunc (sid SessionId) Type() string {\n\treturn strings.SplitN(string(sid), \":\", 2)[0]\n}\n<|endoftext|>"}
{"text":"<commit_before>package openapi\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nconst (\n\texampleCom  = \"https:\/\/example.com\"\n\texampleMail = \"foo@example.com\"\n)\n\ntype candidate struct {\n\tlabel  string\n\tin     validater\n\thasErr bool\n}\n\nfunc testValidater(t *testing.T, candidates []candidate) {\n\tt.Helper()\n\tfor _, c := range candidates {\n\t\tif err := c.in.Validate(); (err != nil) != c.hasErr {\n\t\t\tif c.hasErr {\n\t\t\t\tt.Error(\"error should be occurred, but not\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tt.Errorf(\"error is occurred: %s\", err)\n\t\t}\n\t}\n}\n\nfunc TestHasDuplicatedParameter(t *testing.T) {\n\tt.Run(\"no duplicated param\", testHasDuplicatedParameterFalse)\n\tt.Run(\"there's duplicated param\", testHasDuplicatedParameterTrue)\n}\n\nfunc testHasDuplicatedParameterFalse(t *testing.T) {\n\tparams := []*Parameter{\n\t\t&Parameter{Name: \"foo\", In: \"header\"},\n\t\t&Parameter{Name: \"foo\", In: \"path\", Required: true},\n\t\t&Parameter{Name: \"bar\", In: \"path\", Required: true},\n\t}\n\tif hasDuplicatedParameter(params) {\n\t\tt.Error(\"should return false\")\n\t}\n}\n\nfunc testHasDuplicatedParameterTrue(t *testing.T) {\n\tparams := []*Parameter{\n\t\t&Parameter{Name: \"foo\", In: \"header\"},\n\t\t&Parameter{Name: \"foo\", In: \"header\"},\n\t}\n\tif !hasDuplicatedParameter(params) {\n\t\tt.Error(\"should return true\")\n\t}\n}\n\nfunc TestMustURL(t *testing.T) {\n\tcandidates := []struct {\n\t\tlabel  string\n\t\tin     string\n\t\thasErr bool\n\t}{\n\t\t{\"empty\", \"\", true},\n\t\t{\"valid HTTP url\", \"http:\/\/example.com\", false},\n\t\t{\"allowed relative path\", \"foo\/bar\/baz\", true},\n\t\t{\"absolute path\", \"\/foo\/bar\/baz\", false},\n\t\t{\"plain string\", \"foobarbaz\", true},\n\t}\n\tfor _, c := range candidates {\n\t\tif err := mustURL(c.label, c.in); (err != nil) != c.hasErr {\n\t\t\tt.Logf(\"error occured at %s\", c.label)\n\t\t\tif c.hasErr {\n\t\t\t\tt.Error(\"error should occured, but not\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tt.Error(\"error should not occurred, but occurred\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc TestDocumentValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Document{}, true},\n\t\t{\"withInvalidVersion\", Document{Version: \"1.0\"}, true},\n\t\t{\"withVersion\", Document{Version: \"3.0.0\"}, true},\n\t\t{\"valid\", Document{Version: \"3.0.0\", Info: &Info{Title: \"foo\", TermsOfService: exampleCom, Version: \"1.0\"}, Paths: Paths{}}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestValidateOASVersion(t *testing.T) {\n\tcandidates := []struct {\n\t\tlabel  string\n\t\tin     string\n\t\thasErr bool\n\t}{\n\t\t{\"empty\", \"\", true},\n\t\t{\"invalidVersion\", \"foobar\", true},\n\t\t{\"swagger\", \"2.0\", true},\n\t\t{\"valid\", \"3.0.0\", false},\n\t}\n\tfor _, c := range candidates {\n\t\tif err := validateOASVersion(c.in); (err != nil) != c.hasErr {\n\t\t\tt.Log(c.label)\n\t\t\tif c.hasErr {\n\t\t\t\tt.Error(\"error should be occurred, but not\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tt.Errorf(\"error should not be occured: %s\", err)\n\t\t}\n\t}\n}\n\nfunc TestInfoValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Info{}, true},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestContactValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Contact{}, true},\n\t\t{\"withURL\", Contact{URL: exampleCom}, false},\n\t\t{\"invalidURL\", Contact{URL: \"foobar\"}, true},\n\t\t{\"withEmail\", Contact{Email: exampleMail}, true},\n\t\t{\"valid\", Contact{URL: exampleCom, Email: exampleMail}, false},\n\t\t{\"invalidEmail\", Contact{URL: exampleCom, Email: \"foobar\"}, true},\n\t}\n\n\ttestValidater(t, candidates)\n}\n\nfunc TestLicenseValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", License{}, true},\n\t\t{\"withName\", License{Name: \"foobar\"}, true},\n\t\t{\"withURL\", License{URL: exampleCom}, true},\n\t\t{\"invalidURL\", License{Name: \"foobar\", URL: \"foobar\"}, true},\n\t\t{\"valid\", License{Name: \"foobar\", URL: exampleCom}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestServerValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Server{}, true},\n\t\t{\"invalidURL\", Server{URL: \"foobar%\"}, true},\n\t\t{\"withURL\", Server{URL: exampleCom}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestServerVariableValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", ServerVariable{}, true},\n\t\t{\"withDefault\", ServerVariable{Default: \"default\"}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestComponents(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Components{}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestComponentsValidateKeys(t *testing.T) {\n\tcandidates := []struct {\n\t\tlabel  string\n\t\tin     Components\n\t\thasErr bool\n\t}{\n\t\t{\"empty\", Components{}, true},\n\t}\n\tfor _, c := range candidates {\n\t\tif err := c.in.validateKeys(); (err != nil) != c.hasErr {\n\t\t\tt.Log(c.label)\n\t\t\tif c.hasErr {\n\t\t\t\tt.Error(\"error should be occurred, but not\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tt.Errorf(\"error should not be occurred: %s\", err)\n\t\t}\n\t}\n}\n\nfunc TestReduceComponentKeys(t *testing.T) {\n\tcandidates := []struct {\n\t\tlabel    string\n\t\tin       Components\n\t\texpected []string\n\t}{\n\t\t{\"empty\", Components{}, []string{}},\n\t}\n\tfor _, c := range candidates {\n\t\tkeys := reduceComponentKeys(c.in)\n\t\tif !reflect.DeepEqual(keys, c.expected) {\n\t\t\tt.Log(c.label)\n\t\t\tt.Errorf(\"%+v != %+v\", keys, c.expected)\n\t\t}\n\t}\n}\n\nfunc TestReduceComponentObjects(t *testing.T) {\n\tcandidates := []struct {\n\t\tlabel    string\n\t\tin       Components\n\t\texpected []validater\n\t}{\n\t\t{\"empty\", Components{}, []validater{}},\n\t}\n\tfor _, c := range candidates {\n\t\tobjects := reduceComponentObjects(c.in)\n\t\tif !reflect.DeepEqual(objects, c.expected) {\n\t\t\tt.Log(c.label)\n\t\t\tt.Errorf(\"%+v != %+v\", objects, c.expected)\n\t\t}\n\t}\n}\n\nfunc TestPathsValidate(t *testing.T) {\n\tt.Run(\"duplicate pathItem\", testPathItemDuplicate)\n}\n\nfunc getPaths(id1, id2 string) Paths {\n\treturn Paths{\n\t\t\"\/foo\/bar\": &PathItem{\n\t\t\tGet:  &Operation{OperationID: id1, Responses: Responses{\"200\": &Response{Description: \"foo\"}}},\n\t\t\tPost: &Operation{OperationID: id2, Responses: Responses{\"200\": &Response{Description: \"foo\"}}},\n\t\t},\n\t}\n}\n\nfunc testPathItemDuplicate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"invalid\", getPaths(\"foobar\", \"foobar\"), true},\n\t\t{\"valid\", getPaths(\"foo\", \"bar\"), false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestExternalDocumentationValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", ExternalDocumentation{}, true},\n\t\t{\"invalidURL\", ExternalDocumentation{URL: \"foobar\"}, true},\n\t\t{\"valid\", ExternalDocumentation{URL: exampleCom}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestTagValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Tag{}, true},\n\t\t{\"withEmptyExternalDocs\", Tag{ExternalDocs: &ExternalDocumentation{}}, true},\n\t\t{\"withValidExternalDocs\", Tag{ExternalDocs: &ExternalDocumentation{URL: exampleCom}}, true},\n\n\t\t{\"withName\", Tag{Name: \"foo\"}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestSchemaValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Schema{}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestDiscriminatorValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Discriminator{}, true},\n\t\t{\"withPropertyName\", Discriminator{PropertyName: \"foobar\"}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestXMLValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", XML{}, true},\n\t\t{\"invalidURLNamespace\", XML{Namespace: \"foobar\"}, true},\n\t\t{\"withNamespace\", XML{Namespace: exampleCom}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestOAuthFlowValidate(t *testing.T) {\n\tmockScopes := map[string]string{\"foo\": \"bar\"}\n\n\tempty := OAuthFlow{}\n\taURL := OAuthFlow{AuthorizationURL: exampleCom}\n\ttURL := OAuthFlow{TokenURL: exampleCom}\n\trURL := OAuthFlow{RefreshURL: exampleCom}\n\tscopes := OAuthFlow{Scopes: mockScopes}\n\tatURL := OAuthFlow{AuthorizationURL: exampleCom, TokenURL: exampleCom}\n\tarURL := OAuthFlow{AuthorizationURL: exampleCom, RefreshURL: exampleCom}\n\taURLscopes := OAuthFlow{AuthorizationURL: exampleCom, Scopes: mockScopes}\n\ttrURL := OAuthFlow{TokenURL: exampleCom, RefreshURL: exampleCom}\n\ttURLscopes := OAuthFlow{TokenURL: exampleCom, Scopes: mockScopes}\n\trURLscopes := OAuthFlow{RefreshURL: exampleCom, Scopes: mockScopes}\n\tatrURL := OAuthFlow{AuthorizationURL: exampleCom, TokenURL: exampleCom, RefreshURL: exampleCom}\n\tatURLscopes := OAuthFlow{AuthorizationURL: exampleCom, TokenURL: exampleCom, Scopes: mockScopes}\n\tarURLscopes := OAuthFlow{AuthorizationURL: exampleCom, RefreshURL: exampleCom, Scopes: mockScopes}\n\ttrURLscopes := OAuthFlow{TokenURL: exampleCom, RefreshURL: exampleCom, Scopes: mockScopes}\n\tatrURLscopes := OAuthFlow{AuthorizationURL: exampleCom, TokenURL: exampleCom, RefreshURL: exampleCom, Scopes: mockScopes}\n\tinvalidURL := OAuthFlow{AuthorizationURL: \"foobar\", TokenURL: \"foobar\", RefreshURL: \"foobar\", Scopes: mockScopes}\n\tzeroMap := OAuthFlow{AuthorizationURL: exampleCom, TokenURL: exampleCom, RefreshURL: exampleCom, Scopes: map[string]string{}}\n\n\tcandidates := []struct {\n\t\tlabel   string\n\t\tin      OAuthFlow\n\t\thaveErr [4]bool\n\t}{\n\t\t{\"empty\", empty, [4]bool{true, true, true, true}},\n\t\t{\"aURL\", aURL, [4]bool{true, true, true, true}},\n\t\t{\"tURL\", tURL, [4]bool{true, true, true, true}},\n\t\t{\"rURL\", rURL, [4]bool{true, true, true, true}},\n\t\t{\"scopes\", scopes, [4]bool{true, true, true, true}},\n\t\t{\"aURL\/tURL\", atURL, [4]bool{true, true, true, true}},\n\t\t{\"aURL\/rURL\", arURL, [4]bool{true, true, true, true}},\n\t\t{\"aURL\/scopes\", aURLscopes, [4]bool{false, true, true, true}},\n\t\t{\"tURL\/rURL\", trURL, [4]bool{true, true, true, true}},\n\t\t{\"tURL\/scopes\", tURLscopes, [4]bool{true, false, false, true}},\n\t\t{\"rURL\/scopes\", rURLscopes, [4]bool{true, true, true, true}},\n\t\t{\"aURL\/tURL\/rURL\", atrURL, [4]bool{true, true, true, true}},\n\t\t{\"aURL\/tURL\/scopes\", atURLscopes, [4]bool{false, false, false, false}},\n\t\t{\"aURL\/rURL\/scopes\", arURLscopes, [4]bool{false, true, true, true}},\n\t\t{\"tURL\/rURL\/scopes\", trURLscopes, [4]bool{true, false, false, true}},\n\t\t{\"aURL\/tURL\/rURL\/scopes\", atrURLscopes, [4]bool{false, false, false, false}},\n\n\t\t{\"invalidURL\", invalidURL, [4]bool{true, true, true, true}},\n\t\t{\"zero length map\", zeroMap, [4]bool{true, true, true, true}},\n\t}\n\tfor _, c := range candidates {\n\t\ttestOAuthFlowValidate(t, c.label, c.in, c.haveErr)\n\t}\n}\n\nvar flowTypes = []string{\"implicit\", \"password\", \"clientCredentials\", \"authorizationCode\"}\n\nfunc testOAuthFlowValidate(t *testing.T, label string, oauthFlow OAuthFlow, haveErr [4]bool) {\n\tif err := oauthFlow.Validate(\"\"); err == nil {\n\t\tt.Logf(\"%s-empty\", label)\n\t\tt.Error(\"error should be occurred, but not\")\n\t}\n\tif err := oauthFlow.Validate(\"foobar\"); err == nil {\n\t\tt.Logf(\"%s-wrongtype\", label)\n\t\tt.Error(\"error should be occurred, but not\")\n\t}\n\tfor i, flowType := range flowTypes {\n\t\tif err := oauthFlow.Validate(flowType); (err != nil) != haveErr[i] {\n\t\t\tt.Logf(\"%s-%s\", label, flowType)\n\t\t\tif haveErr[i] {\n\t\t\t\tt.Error(\"error should be occurred, but not\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tt.Error(\"error should not be occurred, but occurred\")\n\t\t\tt.Log(err)\n\t\t}\n\t}\n}\n<commit_msg>fix test case<commit_after>package openapi\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nconst (\n\texampleCom  = \"https:\/\/example.com\"\n\texampleMail = \"foo@example.com\"\n)\n\ntype candidate struct {\n\tlabel  string\n\tin     validater\n\thasErr bool\n}\n\nfunc testValidater(t *testing.T, candidates []candidate) {\n\tt.Helper()\n\tfor _, c := range candidates {\n\t\tif err := c.in.Validate(); (err != nil) != c.hasErr {\n\t\t\tif c.hasErr {\n\t\t\t\tt.Error(\"error should be occurred, but not\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tt.Errorf(\"error is occurred: %s\", err)\n\t\t}\n\t}\n}\n\nfunc TestHasDuplicatedParameter(t *testing.T) {\n\tt.Run(\"no duplicated param\", testHasDuplicatedParameterFalse)\n\tt.Run(\"there's duplicated param\", testHasDuplicatedParameterTrue)\n}\n\nfunc testHasDuplicatedParameterFalse(t *testing.T) {\n\tparams := []*Parameter{\n\t\t&Parameter{Name: \"foo\", In: \"header\"},\n\t\t&Parameter{Name: \"foo\", In: \"path\", Required: true},\n\t\t&Parameter{Name: \"bar\", In: \"path\", Required: true},\n\t}\n\tif hasDuplicatedParameter(params) {\n\t\tt.Error(\"should return false\")\n\t}\n}\n\nfunc testHasDuplicatedParameterTrue(t *testing.T) {\n\tparams := []*Parameter{\n\t\t&Parameter{Name: \"foo\", In: \"header\"},\n\t\t&Parameter{Name: \"foo\", In: \"header\"},\n\t}\n\tif !hasDuplicatedParameter(params) {\n\t\tt.Error(\"should return true\")\n\t}\n}\n\nfunc TestMustURL(t *testing.T) {\n\tcandidates := []struct {\n\t\tlabel  string\n\t\tin     string\n\t\thasErr bool\n\t}{\n\t\t{\"empty\", \"\", true},\n\t\t{\"valid HTTP url\", \"http:\/\/example.com\", false},\n\t\t{\"allowed relative path\", \"foo\/bar\/baz\", true},\n\t\t{\"absolute path\", \"\/foo\/bar\/baz\", false},\n\t\t{\"plain string\", \"foobarbaz\", true},\n\t}\n\tfor _, c := range candidates {\n\t\tif err := mustURL(c.label, c.in); (err != nil) != c.hasErr {\n\t\t\tt.Logf(\"error occured at %s\", c.label)\n\t\t\tif c.hasErr {\n\t\t\t\tt.Error(\"error should occured, but not\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tt.Error(\"error should not occurred, but occurred\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc TestDocumentValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Document{}, true},\n\t\t{\"withInvalidVersion\", Document{Version: \"1.0\"}, true},\n\t\t{\"withVersion\", Document{Version: \"3.0.0\"}, true},\n\t\t{\"valid\", Document{Version: \"3.0.0\", Info: &Info{Title: \"foo\", TermsOfService: exampleCom, Version: \"1.0\"}, Paths: Paths{}}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestValidateOASVersion(t *testing.T) {\n\tcandidates := []struct {\n\t\tlabel  string\n\t\tin     string\n\t\thasErr bool\n\t}{\n\t\t{\"empty\", \"\", true},\n\t\t{\"invalidVersion\", \"foobar\", true},\n\t\t{\"swagger\", \"2.0\", true},\n\t\t{\"valid\", \"3.0.0\", false},\n\t}\n\tfor _, c := range candidates {\n\t\tif err := validateOASVersion(c.in); (err != nil) != c.hasErr {\n\t\t\tt.Log(c.label)\n\t\t\tif c.hasErr {\n\t\t\t\tt.Error(\"error should be occurred, but not\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tt.Errorf(\"error should not be occured: %s\", err)\n\t\t}\n\t}\n}\n\nfunc TestInfoValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Info{}, true},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestContactValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Contact{}, true},\n\t\t{\"withURL\", Contact{URL: exampleCom}, false},\n\t\t{\"invalidURL\", Contact{URL: \"foobar\"}, true},\n\t\t{\"withEmail\", Contact{Email: exampleMail}, true},\n\t\t{\"valid\", Contact{URL: exampleCom, Email: exampleMail}, false},\n\t\t{\"invalidEmail\", Contact{URL: exampleCom, Email: \"foobar\"}, true},\n\t}\n\n\ttestValidater(t, candidates)\n}\n\nfunc TestLicenseValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", License{}, true},\n\t\t{\"withName\", License{Name: \"foobar\"}, true},\n\t\t{\"withURL\", License{URL: exampleCom}, true},\n\t\t{\"invalidURL\", License{Name: \"foobar\", URL: \"foobar\"}, true},\n\t\t{\"valid\", License{Name: \"foobar\", URL: exampleCom}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestServerValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Server{}, true},\n\t\t{\"invalidURL\", Server{URL: \"foobar%\"}, true},\n\t\t{\"withURL\", Server{URL: exampleCom}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestServerVariableValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", ServerVariable{}, true},\n\t\t{\"withDefault\", ServerVariable{Default: \"default\"}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestComponents(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Components{}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestComponentsValidateKeys(t *testing.T) {\n\tcandidates := []struct {\n\t\tlabel  string\n\t\tin     Components\n\t\thasErr bool\n\t}{\n\t\t{\"empty\", Components{}, false},\n\t}\n\tfor _, c := range candidates {\n\t\tif err := c.in.validateKeys(); (err != nil) != c.hasErr {\n\t\t\tt.Log(c.label)\n\t\t\tif c.hasErr {\n\t\t\t\tt.Error(\"error should be occurred, but not\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tt.Errorf(\"error should not be occurred: %s\", err)\n\t\t}\n\t}\n}\n\nfunc TestReduceComponentKeys(t *testing.T) {\n\tcandidates := []struct {\n\t\tlabel    string\n\t\tin       Components\n\t\texpected []string\n\t}{\n\t\t{\"empty\", Components{}, []string{}},\n\t}\n\tfor _, c := range candidates {\n\t\tkeys := reduceComponentKeys(c.in)\n\t\tif !reflect.DeepEqual(keys, c.expected) {\n\t\t\tt.Log(c.label)\n\t\t\tt.Errorf(\"%+v != %+v\", keys, c.expected)\n\t\t}\n\t}\n}\n\nfunc TestReduceComponentObjects(t *testing.T) {\n\tcandidates := []struct {\n\t\tlabel    string\n\t\tin       Components\n\t\texpected []validater\n\t}{\n\t\t{\"empty\", Components{}, []validater{}},\n\t}\n\tfor _, c := range candidates {\n\t\tobjects := reduceComponentObjects(c.in)\n\t\tif !reflect.DeepEqual(objects, c.expected) {\n\t\t\tt.Log(c.label)\n\t\t\tt.Errorf(\"%+v != %+v\", objects, c.expected)\n\t\t}\n\t}\n}\n\nfunc TestPathsValidate(t *testing.T) {\n\tt.Run(\"duplicate pathItem\", testPathItemDuplicate)\n}\n\nfunc getPaths(id1, id2 string) Paths {\n\treturn Paths{\n\t\t\"\/foo\/bar\": &PathItem{\n\t\t\tGet:  &Operation{OperationID: id1, Responses: Responses{\"200\": &Response{Description: \"foo\"}}},\n\t\t\tPost: &Operation{OperationID: id2, Responses: Responses{\"200\": &Response{Description: \"foo\"}}},\n\t\t},\n\t}\n}\n\nfunc testPathItemDuplicate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"invalid\", getPaths(\"foobar\", \"foobar\"), true},\n\t\t{\"valid\", getPaths(\"foo\", \"bar\"), false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestExternalDocumentationValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", ExternalDocumentation{}, true},\n\t\t{\"invalidURL\", ExternalDocumentation{URL: \"foobar\"}, true},\n\t\t{\"valid\", ExternalDocumentation{URL: exampleCom}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestTagValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Tag{}, true},\n\t\t{\"withEmptyExternalDocs\", Tag{ExternalDocs: &ExternalDocumentation{}}, true},\n\t\t{\"withValidExternalDocs\", Tag{ExternalDocs: &ExternalDocumentation{URL: exampleCom}}, true},\n\n\t\t{\"withName\", Tag{Name: \"foo\"}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestSchemaValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Schema{}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestDiscriminatorValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", Discriminator{}, true},\n\t\t{\"withPropertyName\", Discriminator{PropertyName: \"foobar\"}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestXMLValidate(t *testing.T) {\n\tcandidates := []candidate{\n\t\t{\"empty\", XML{}, true},\n\t\t{\"invalidURLNamespace\", XML{Namespace: \"foobar\"}, true},\n\t\t{\"withNamespace\", XML{Namespace: exampleCom}, false},\n\t}\n\ttestValidater(t, candidates)\n}\n\nfunc TestOAuthFlowValidate(t *testing.T) {\n\tmockScopes := map[string]string{\"foo\": \"bar\"}\n\n\tempty := OAuthFlow{}\n\taURL := OAuthFlow{AuthorizationURL: exampleCom}\n\ttURL := OAuthFlow{TokenURL: exampleCom}\n\trURL := OAuthFlow{RefreshURL: exampleCom}\n\tscopes := OAuthFlow{Scopes: mockScopes}\n\tatURL := OAuthFlow{AuthorizationURL: exampleCom, TokenURL: exampleCom}\n\tarURL := OAuthFlow{AuthorizationURL: exampleCom, RefreshURL: exampleCom}\n\taURLscopes := OAuthFlow{AuthorizationURL: exampleCom, Scopes: mockScopes}\n\ttrURL := OAuthFlow{TokenURL: exampleCom, RefreshURL: exampleCom}\n\ttURLscopes := OAuthFlow{TokenURL: exampleCom, Scopes: mockScopes}\n\trURLscopes := OAuthFlow{RefreshURL: exampleCom, Scopes: mockScopes}\n\tatrURL := OAuthFlow{AuthorizationURL: exampleCom, TokenURL: exampleCom, RefreshURL: exampleCom}\n\tatURLscopes := OAuthFlow{AuthorizationURL: exampleCom, TokenURL: exampleCom, Scopes: mockScopes}\n\tarURLscopes := OAuthFlow{AuthorizationURL: exampleCom, RefreshURL: exampleCom, Scopes: mockScopes}\n\ttrURLscopes := OAuthFlow{TokenURL: exampleCom, RefreshURL: exampleCom, Scopes: mockScopes}\n\tatrURLscopes := OAuthFlow{AuthorizationURL: exampleCom, TokenURL: exampleCom, RefreshURL: exampleCom, Scopes: mockScopes}\n\tinvalidURL := OAuthFlow{AuthorizationURL: \"foobar\", TokenURL: \"foobar\", RefreshURL: \"foobar\", Scopes: mockScopes}\n\tzeroMap := OAuthFlow{AuthorizationURL: exampleCom, TokenURL: exampleCom, RefreshURL: exampleCom, Scopes: map[string]string{}}\n\n\tcandidates := []struct {\n\t\tlabel   string\n\t\tin      OAuthFlow\n\t\thaveErr [4]bool\n\t}{\n\t\t{\"empty\", empty, [4]bool{true, true, true, true}},\n\t\t{\"aURL\", aURL, [4]bool{true, true, true, true}},\n\t\t{\"tURL\", tURL, [4]bool{true, true, true, true}},\n\t\t{\"rURL\", rURL, [4]bool{true, true, true, true}},\n\t\t{\"scopes\", scopes, [4]bool{true, true, true, true}},\n\t\t{\"aURL\/tURL\", atURL, [4]bool{true, true, true, true}},\n\t\t{\"aURL\/rURL\", arURL, [4]bool{true, true, true, true}},\n\t\t{\"aURL\/scopes\", aURLscopes, [4]bool{false, true, true, true}},\n\t\t{\"tURL\/rURL\", trURL, [4]bool{true, true, true, true}},\n\t\t{\"tURL\/scopes\", tURLscopes, [4]bool{true, false, false, true}},\n\t\t{\"rURL\/scopes\", rURLscopes, [4]bool{true, true, true, true}},\n\t\t{\"aURL\/tURL\/rURL\", atrURL, [4]bool{true, true, true, true}},\n\t\t{\"aURL\/tURL\/scopes\", atURLscopes, [4]bool{false, false, false, false}},\n\t\t{\"aURL\/rURL\/scopes\", arURLscopes, [4]bool{false, true, true, true}},\n\t\t{\"tURL\/rURL\/scopes\", trURLscopes, [4]bool{true, false, false, true}},\n\t\t{\"aURL\/tURL\/rURL\/scopes\", atrURLscopes, [4]bool{false, false, false, false}},\n\n\t\t{\"invalidURL\", invalidURL, [4]bool{true, true, true, true}},\n\t\t{\"zero length map\", zeroMap, [4]bool{true, true, true, true}},\n\t}\n\tfor _, c := range candidates {\n\t\ttestOAuthFlowValidate(t, c.label, c.in, c.haveErr)\n\t}\n}\n\nvar flowTypes = []string{\"implicit\", \"password\", \"clientCredentials\", \"authorizationCode\"}\n\nfunc testOAuthFlowValidate(t *testing.T, label string, oauthFlow OAuthFlow, haveErr [4]bool) {\n\tif err := oauthFlow.Validate(\"\"); err == nil {\n\t\tt.Logf(\"%s-empty\", label)\n\t\tt.Error(\"error should be occurred, but not\")\n\t}\n\tif err := oauthFlow.Validate(\"foobar\"); err == nil {\n\t\tt.Logf(\"%s-wrongtype\", label)\n\t\tt.Error(\"error should be occurred, but not\")\n\t}\n\tfor i, flowType := range flowTypes {\n\t\tif err := oauthFlow.Validate(flowType); (err != nil) != haveErr[i] {\n\t\t\tt.Logf(\"%s-%s\", label, flowType)\n\t\t\tif haveErr[i] {\n\t\t\t\tt.Error(\"error should be occurred, but not\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tt.Error(\"error should not be occurred, but occurred\")\n\t\t\tt.Log(err)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>removing old test code<commit_after><|endoftext|>"}
{"text":"<commit_before>package schemagen\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"reflect\"\n\t\"sort\"\n\t\"text\/template\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\tu \"github.com\/radeksimko\/terraform-gen\/internal\/util\"\n)\n\ntype getDocsFunc func(iface interface{}, sf *reflect.StructField) string\ntype filterFunc func(iface interface{}, sf *reflect.StructField, s *schema.Schema) bool\n\ntype SchemaGenerator struct {\n\tDocsFunc   getDocsFunc\n\tFilterFunc filterFunc\n}\n\nfunc (g *SchemaGenerator) FromStruct(iface interface{}) map[string]string {\n\trawType := u.DereferencePtrType(reflect.TypeOf(iface))\n\tfields := make(map[string]string, 0)\n\n\tfor i := 0; i < rawType.NumField(); i++ {\n\t\tsf := rawType.Field(i)\n\n\t\tcontent, err := g.generateField(sf.Name, sf.Type, iface, &sf, false)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"ERROR: %s\", err)\n\t\t} else {\n\t\t\tfields[u.Underscore(sf.Name)] = content\n\t\t}\n\t}\n\n\treturn fields\n}\n\nfunc (g *SchemaGenerator) generateField(sfName string, sfType reflect.Type, iface interface{}, sf *reflect.StructField, isNested bool) (string, error) {\n\tkind := u.DereferencePtrType(sfType).Kind()\n\tvar comment, setFunc string\n\ts := &schema.Schema{}\n\n\tif sf != nil {\n\t\tif !g.FilterFunc(iface, sf, s) {\n\t\t\treturn \"\", fmt.Errorf(\"Skipping %q (filter)\", sf.Name)\n\t\t}\n\t\tcomment = g.DocsFunc(iface, sf)\n\t}\n\n\tswitch kind {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\ts.Type = schema.TypeInt\n\tcase reflect.Float32, reflect.Float64:\n\t\ts.Type = schema.TypeFloat\n\tcase reflect.String:\n\t\ts.Type = schema.TypeString\n\tcase reflect.Bool:\n\t\ts.Type = schema.TypeBool\n\tcase reflect.Slice:\n\t\t\/\/ TODO: TypeList may be more suitable for some situations\n\t\ts.Type = schema.TypeSet\n\t\telem, err := g.generateField(\"\", sfType.Elem(), iface, nil, true)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Unable to generate Elem for %q: %s\", sfName, err)\n\t\t}\n\t\ts.Elem = elem\n\n\t\telemKind := u.DereferencePtrType(sfType.Elem()).Kind()\n\t\tif elemKind == reflect.String {\n\t\t\tsetFunc = \"schema.HashString\"\n\t\t}\n\tcase reflect.Map:\n\t\ts.Type = schema.TypeMap\n\tcase reflect.Struct:\n\t\tstructType := sfType\n\t\tif structType.Kind() == reflect.Ptr {\n\t\t\tstructType = structType.Elem()\n\t\t}\n\n\t\ts.Type = schema.TypeList\n\t\ts.MaxItems = 1\n\n\t\telem := \"&schema.Resource{\\nSchema: map[string]*schema.Schema{\\n\"\n\n\t\tiface := reflect.New(structType).Elem().Interface()\n\n\t\tm := g.FromStruct(iface)\n\t\tfieldNames := make([]string, len(m), len(m))\n\t\ti := 0\n\t\tfor k, _ := range m {\n\t\t\tfieldNames[i] = k\n\t\t\ti++\n\t\t}\n\t\tsort.Strings(fieldNames)\n\t\tfor _, k := range fieldNames {\n\t\t\telem += fmt.Sprintf(\"%q: %s,\\n\", k, m[k])\n\t\t}\n\t\telem += \"},\\n}\"\n\t\tif isNested {\n\t\t\treturn elem, nil\n\t\t}\n\n\t\ts.Elem = elem\n\tdefault:\n\t\tf := fmt.Sprintf(\"%s %s\\n\", sfName, sfType.String())\n\t\treturn \"\", fmt.Errorf(\"Unable to process: %s\", f)\n\t}\n\n\ts.Description = comment\n\n\treturn schemaCode(s, setFunc, isNested)\n}\n\nfunc schemaCode(s *schema.Schema, setFunc string, isNested bool) (string, error) {\n\tbuf := bytes.NewBuffer([]byte{})\n\terr := schemaTemplate.Execute(buf, struct {\n\t\tSchema   *schema.Schema\n\t\tSetFunc  string\n\t\tIsNested bool\n\t}{\n\t\tSchema:   s,\n\t\tSetFunc:  setFunc,\n\t\tIsNested: isNested,\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn buf.String(), nil\n}\n\nvar schemaTemplate = template.Must(template.New(\"schema\").Parse(`&schema.Schema{{\"{\"}}{{if not .IsNested}}\n{{end}}Type: schema.{{.Schema.Type}},{{if ne .Schema.Description \"\"}}\nDescription: {{printf \"%q\" .Schema.Description}},{{end}}{{if .Schema.Required}}\nRequired: {{.Schema.Required}},{{end}}{{if .Schema.Optional}}\nOptional: {{.Schema.Optional}},{{end}}{{if .Schema.ForceNew}}\nForceNew: {{.Schema.ForceNew}},{{end}}{{if .Schema.Computed}}\nComputed: {{.Schema.Computed}},{{end}}{{if gt .Schema.MaxItems 0}}\nMaxItems: {{.Schema.MaxItems}},{{end}}{{if .Schema.Elem}}\nElem: {{.Schema.Elem}},{{end}}{{if ne .SetFunc \"\"}}{{if not .IsNested}}\n{{end}}Set: {{.SetFunc}},{{end}}{{if not .IsNested}}\n{{end}}{{\"}\"}}`))\n<commit_msg>Mention todo for SetFunc<commit_after>package schemagen\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"reflect\"\n\t\"sort\"\n\t\"text\/template\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\tu \"github.com\/radeksimko\/terraform-gen\/internal\/util\"\n)\n\ntype getDocsFunc func(iface interface{}, sf *reflect.StructField) string\ntype filterFunc func(iface interface{}, sf *reflect.StructField, s *schema.Schema) bool\n\ntype SchemaGenerator struct {\n\tDocsFunc   getDocsFunc\n\tFilterFunc filterFunc\n}\n\nfunc (g *SchemaGenerator) FromStruct(iface interface{}) map[string]string {\n\trawType := u.DereferencePtrType(reflect.TypeOf(iface))\n\tfields := make(map[string]string, 0)\n\n\tfor i := 0; i < rawType.NumField(); i++ {\n\t\tsf := rawType.Field(i)\n\n\t\tcontent, err := g.generateField(sf.Name, sf.Type, iface, &sf, false)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"ERROR: %s\", err)\n\t\t} else {\n\t\t\tfields[u.Underscore(sf.Name)] = content\n\t\t}\n\t}\n\n\treturn fields\n}\n\nfunc (g *SchemaGenerator) generateField(sfName string, sfType reflect.Type, iface interface{}, sf *reflect.StructField, isNested bool) (string, error) {\n\tkind := u.DereferencePtrType(sfType).Kind()\n\tvar comment, setFunc string\n\ts := &schema.Schema{}\n\n\tif sf != nil {\n\t\tif !g.FilterFunc(iface, sf, s) {\n\t\t\treturn \"\", fmt.Errorf(\"Skipping %q (filter)\", sf.Name)\n\t\t}\n\t\tcomment = g.DocsFunc(iface, sf)\n\t}\n\n\tswitch kind {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\ts.Type = schema.TypeInt\n\tcase reflect.Float32, reflect.Float64:\n\t\ts.Type = schema.TypeFloat\n\tcase reflect.String:\n\t\ts.Type = schema.TypeString\n\tcase reflect.Bool:\n\t\ts.Type = schema.TypeBool\n\tcase reflect.Slice:\n\t\t\/\/ TODO: TypeList may be more suitable for some situations\n\t\t\/\/ TODO: Proper SetFunc may be required for TypeSet\n\t\ts.Type = schema.TypeSet\n\t\telem, err := g.generateField(\"\", sfType.Elem(), iface, nil, true)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"Unable to generate Elem for %q: %s\", sfName, err)\n\t\t}\n\t\ts.Elem = elem\n\n\t\telemKind := u.DereferencePtrType(sfType.Elem()).Kind()\n\t\tif elemKind == reflect.String {\n\t\t\tsetFunc = \"schema.HashString\"\n\t\t}\n\tcase reflect.Map:\n\t\ts.Type = schema.TypeMap\n\tcase reflect.Struct:\n\t\tstructType := sfType\n\t\tif structType.Kind() == reflect.Ptr {\n\t\t\tstructType = structType.Elem()\n\t\t}\n\n\t\ts.Type = schema.TypeList\n\t\ts.MaxItems = 1\n\n\t\telem := \"&schema.Resource{\\nSchema: map[string]*schema.Schema{\\n\"\n\n\t\tiface := reflect.New(structType).Elem().Interface()\n\n\t\tm := g.FromStruct(iface)\n\t\tfieldNames := make([]string, len(m), len(m))\n\t\ti := 0\n\t\tfor k, _ := range m {\n\t\t\tfieldNames[i] = k\n\t\t\ti++\n\t\t}\n\t\tsort.Strings(fieldNames)\n\t\tfor _, k := range fieldNames {\n\t\t\telem += fmt.Sprintf(\"%q: %s,\\n\", k, m[k])\n\t\t}\n\t\telem += \"},\\n}\"\n\t\tif isNested {\n\t\t\treturn elem, nil\n\t\t}\n\n\t\ts.Elem = elem\n\tdefault:\n\t\tf := fmt.Sprintf(\"%s %s\\n\", sfName, sfType.String())\n\t\treturn \"\", fmt.Errorf(\"Unable to process: %s\", f)\n\t}\n\n\ts.Description = comment\n\n\treturn schemaCode(s, setFunc, isNested)\n}\n\nfunc schemaCode(s *schema.Schema, setFunc string, isNested bool) (string, error) {\n\tbuf := bytes.NewBuffer([]byte{})\n\terr := schemaTemplate.Execute(buf, struct {\n\t\tSchema   *schema.Schema\n\t\tSetFunc  string\n\t\tIsNested bool\n\t}{\n\t\tSchema:   s,\n\t\tSetFunc:  setFunc,\n\t\tIsNested: isNested,\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn buf.String(), nil\n}\n\nvar schemaTemplate = template.Must(template.New(\"schema\").Parse(`&schema.Schema{{\"{\"}}{{if not .IsNested}}\n{{end}}Type: schema.{{.Schema.Type}},{{if ne .Schema.Description \"\"}}\nDescription: {{printf \"%q\" .Schema.Description}},{{end}}{{if .Schema.Required}}\nRequired: {{.Schema.Required}},{{end}}{{if .Schema.Optional}}\nOptional: {{.Schema.Optional}},{{end}}{{if .Schema.ForceNew}}\nForceNew: {{.Schema.ForceNew}},{{end}}{{if .Schema.Computed}}\nComputed: {{.Schema.Computed}},{{end}}{{if gt .Schema.MaxItems 0}}\nMaxItems: {{.Schema.MaxItems}},{{end}}{{if .Schema.Elem}}\nElem: {{.Schema.Elem}},{{end}}{{if ne .SetFunc \"\"}}{{if not .IsNested}}\n{{end}}Set: {{.SetFunc}},{{end}}{{if not .IsNested}}\n{{end}}{{\"}\"}}`))\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 by caixw, All rights reserved.\n\/\/ Use of this source code is governed by a MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage is\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/issue9\/assert\"\n)\n\nfunc TestCNPhone(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(CNPhone(\"444488888888-4444\"))\n\ta.True(CNPhone(\"3337777777-1\"))\n\ta.True(CNPhone(\"333-7777777-1\"))\n\ta.True(CNPhone(\"7777777\"))\n\ta.True(CNPhone(\"88888888\"))\n\n\ta.False(CNPhone(\"333-7777777-\"))      \/\/ 尾部没有分机号\n\ta.False(CNPhone(\"22-88888888\"))       \/\/ 区号只有2位\n\ta.False(CNPhone(\"33-88888888-55555\")) \/\/ 分机号超过4位\n}\n\nfunc TestCNMobile(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(CNMobile(\"15011111111\"))\n\ta.True(CNMobile(\"015011111111\"))\n\ta.True(CNMobile(\"8615011111111\"))\n\ta.True(CNMobile(\"+8615011111111\"))\n\ta.True(CNMobile(\"+8619911111111\"))\n\n\ta.False(CNMobile(\"+86150111111112\")) \/\/ 尾部多个2\n\ta.False(CNMobile(\"50111111112\"))     \/\/ 开头少1\n\ta.False(CNMobile(\"+8650111111112\"))  \/\/ 开头少1\n\ta.False(CNMobile(\"8650111111112\"))   \/\/ 开头少1\n\ta.False(CNMobile(\"154111111112\"))    \/\/ 不存在的前缀154\n\ta.False(CNMobile(\"+8619811111111\"))\n}\n\nfunc TestCNTel(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(CNTel(\"444488888888-4444\"))\n\ta.True(CNTel(\"3337777777-1\"))\n\ta.True(CNTel(\"333-7777777-1\"))\n\ta.True(CNTel(\"7777777\"))\n\ta.True(CNTel(\"88888888\"))\n\ta.True(CNTel(\"15011111111\"))\n\ta.True(CNTel(\"015011111111\"))\n\ta.True(CNTel(\"8615011111111\"))\n\ta.True(CNTel(\"+8615011111111\"))\n}\n\nfunc TestURL(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(URL(\"http:\/\/www.example.com\"))\n\ta.True(URL([]byte(\"http:\/\/example.com\")))\n\ta.True(URL(\"http:\/\/www.example.com\/\"))\n\ta.True(URL(\"http:\/\/www.example.com\/path\/?a=b\"))\n\ta.True(URL(\"https:\/\/www.example.com:88\/path1\/path2\"))\n\ta.True(URL(\"ftp:\/\/pwd:user@www.example.com\/index.go?a=b\"))\n\ta.True(URL([]byte(\"ftp:\/\/pwd:user@www.example.com\/index.go?a=b\")))\n\ta.True(URL(\"pwd:user@www.example.com\/path\/\"))\n\ta.True(URL(\"pwd:user@www.example.com:80\/path\/\"))\n\ta.True(URL(\"https:\/\/127.0.0.1\/path\/\"))\n\ta.True(URL(\"https:\/\/fe80:0:0:0:204:61ff:fe9d:f156\/path\/\"))\n\ta.True(URL(\"https:\/\/127.0.0.1\/path\/\/index.go?arg1=val1&arg2=val\/2\"))\n\ta.True(URL(\"https:\/\/::1\/path\/index.go?arg1=val1\"))\n\n\ta.False(URL(\"https:\/\/[::1]:80\/path\/\"))\n\ta.False(URL(\"https:\/\/298.1.1.1\/path\/index.go?arg1=val1\"))\n\ta.False(URL(\"https:\/\/~.example.com\/path\/index.go?arg1=val1\"))\n}\n\nfunc TestIP(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(IP(\"fe80:0000:0000:0000:0204:61ff:fe9d:f156\"))\n\ta.True(IP(\"fe80:0:0:0:204:61ff:fe9d:f156\"))\n\ta.True(IP(\"0.0.0.0\"))\n\ta.True(IP(\"255.255.255.255\"))\n\ta.True(IP(\"255.0.3.255\"))\n\n\ta.False(IP(\"255.0:3.255\"))\n\ta.False(IP(\"275.0.3.255\"))\n}\n\nfunc TestIP6(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(IP6(\"fe80:0000:0000:0000:0204:61ff:fe9d:f156\"))      \/\/ full form of IPv6\n\ta.True(IP6(\"fe80:0:0:0:204:61ff:fe9d:f156\"))                \/\/ drop leading zeroes\n\ta.True(IP6(\"fe80::204:61ff:fe9d:f156\"))                     \/\/ collapse multiple zeroes to :: in the IPv6 address\n\ta.True(IP6(\"fe80:0000:0000:0000:0204:61ff:254.157.241.86\")) \/\/ IPv4 dotted quad at the end\n\ta.True(IP6(\"fe80:0:0:0:0204:61ff:254.157.241.86\"))          \/\/ drop leading zeroes, IPv4 dotted quad at the end\n\ta.True(IP6(\"fe80::204:61ff:254.157.241.86\"))                \/\/ dotted quad at the end, multiple zeroes collapsed\n\ta.True(IP6(\"::1\"))                                          \/\/ localhost\n\ta.True(IP6(\"fe80::\"))                                       \/\/ link-local prefix\n\ta.True(IP6(\"2001::\"))                                       \/\/ global unicast prefix\n}\n\nfunc TestIP4(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(IP4(\"0.0.0.0\"))\n\ta.True(IP4(\"255.255.255.255\"))\n\ta.True(IP4(\"255.0.3.255\"))\n\ta.True(IP4(\"127.010.0.1\"))\n\ta.True(IP4(\"027.01.0.1\"))\n\n\ta.False(IP4(\"1127.01.0.1\"))\n}\n\nfunc TestEmail(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(Email(\"email@email.com\"))\n\ta.True(Email(\"em2il@email.com.cn\"))\n\ta.True(Email(\"12345@qq.com\"))\n\ta.True(Email(\"email.test@email.com\"))\n\ta.True(Email(\"email.test@email123.com\"))\n\ta.True(Email(\"em2il@email\"))\n\n\t\/\/ 2个@\n\ta.False(Email(\"em@2l@email.com\"))\n\t\/\/ 没有@\n\ta.False(Email(\"email2email.com.cn\"))\n}\n<commit_msg>修正测试错误<commit_after>\/\/ Copyright 2014 by caixw, All rights reserved.\n\/\/ Use of this source code is governed by a MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage is\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/issue9\/assert\"\n)\n\nfunc TestCNPhone(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(CNPhone(\"444488888888-4444\"))\n\ta.True(CNPhone(\"3337777777-1\"))\n\ta.True(CNPhone(\"333-7777777-1\"))\n\ta.True(CNPhone(\"7777777\"))\n\ta.True(CNPhone(\"88888888\"))\n\n\ta.False(CNPhone(\"333-7777777-\"))      \/\/ 尾部没有分机号\n\ta.False(CNPhone(\"22-88888888\"))       \/\/ 区号只有2位\n\ta.False(CNPhone(\"33-88888888-55555\")) \/\/ 分机号超过4位\n}\n\nfunc TestCNMobile(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(CNMobile(\"15011111111\"))\n\ta.True(CNMobile(\"015011111111\"))\n\ta.True(CNMobile(\"8615011111111\"))\n\ta.True(CNMobile(\"+8615011111111\"))\n\ta.True(CNMobile(\"+8619911111111\"))\n\n\ta.False(CNMobile(\"+86150111111112\")) \/\/ 尾部多个2\n\ta.False(CNMobile(\"50111111112\"))     \/\/ 开头少1\n\ta.False(CNMobile(\"+8650111111112\"))  \/\/ 开头少1\n\ta.False(CNMobile(\"8650111111112\"))   \/\/ 开头少1\n\ta.False(CNMobile(\"154111111112\"))    \/\/ 不存在的前缀154\n\ta.False(CNMobile(\"+8619711111111\"))\n}\n\nfunc TestCNTel(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(CNTel(\"444488888888-4444\"))\n\ta.True(CNTel(\"3337777777-1\"))\n\ta.True(CNTel(\"333-7777777-1\"))\n\ta.True(CNTel(\"7777777\"))\n\ta.True(CNTel(\"88888888\"))\n\ta.True(CNTel(\"15011111111\"))\n\ta.True(CNTel(\"015011111111\"))\n\ta.True(CNTel(\"8615011111111\"))\n\ta.True(CNTel(\"+8615011111111\"))\n}\n\nfunc TestURL(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(URL(\"http:\/\/www.example.com\"))\n\ta.True(URL([]byte(\"http:\/\/example.com\")))\n\ta.True(URL(\"http:\/\/www.example.com\/\"))\n\ta.True(URL(\"http:\/\/www.example.com\/path\/?a=b\"))\n\ta.True(URL(\"https:\/\/www.example.com:88\/path1\/path2\"))\n\ta.True(URL(\"ftp:\/\/pwd:user@www.example.com\/index.go?a=b\"))\n\ta.True(URL([]byte(\"ftp:\/\/pwd:user@www.example.com\/index.go?a=b\")))\n\ta.True(URL(\"pwd:user@www.example.com\/path\/\"))\n\ta.True(URL(\"pwd:user@www.example.com:80\/path\/\"))\n\ta.True(URL(\"https:\/\/127.0.0.1\/path\/\"))\n\ta.True(URL(\"https:\/\/fe80:0:0:0:204:61ff:fe9d:f156\/path\/\"))\n\ta.True(URL(\"https:\/\/127.0.0.1\/path\/\/index.go?arg1=val1&arg2=val\/2\"))\n\ta.True(URL(\"https:\/\/::1\/path\/index.go?arg1=val1\"))\n\n\ta.False(URL(\"https:\/\/[::1]:80\/path\/\"))\n\ta.False(URL(\"https:\/\/298.1.1.1\/path\/index.go?arg1=val1\"))\n\ta.False(URL(\"https:\/\/~.example.com\/path\/index.go?arg1=val1\"))\n}\n\nfunc TestIP(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(IP(\"fe80:0000:0000:0000:0204:61ff:fe9d:f156\"))\n\ta.True(IP(\"fe80:0:0:0:204:61ff:fe9d:f156\"))\n\ta.True(IP(\"0.0.0.0\"))\n\ta.True(IP(\"255.255.255.255\"))\n\ta.True(IP(\"255.0.3.255\"))\n\n\ta.False(IP(\"255.0:3.255\"))\n\ta.False(IP(\"275.0.3.255\"))\n}\n\nfunc TestIP6(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(IP6(\"fe80:0000:0000:0000:0204:61ff:fe9d:f156\"))      \/\/ full form of IPv6\n\ta.True(IP6(\"fe80:0:0:0:204:61ff:fe9d:f156\"))                \/\/ drop leading zeroes\n\ta.True(IP6(\"fe80::204:61ff:fe9d:f156\"))                     \/\/ collapse multiple zeroes to :: in the IPv6 address\n\ta.True(IP6(\"fe80:0000:0000:0000:0204:61ff:254.157.241.86\")) \/\/ IPv4 dotted quad at the end\n\ta.True(IP6(\"fe80:0:0:0:0204:61ff:254.157.241.86\"))          \/\/ drop leading zeroes, IPv4 dotted quad at the end\n\ta.True(IP6(\"fe80::204:61ff:254.157.241.86\"))                \/\/ dotted quad at the end, multiple zeroes collapsed\n\ta.True(IP6(\"::1\"))                                          \/\/ localhost\n\ta.True(IP6(\"fe80::\"))                                       \/\/ link-local prefix\n\ta.True(IP6(\"2001::\"))                                       \/\/ global unicast prefix\n}\n\nfunc TestIP4(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(IP4(\"0.0.0.0\"))\n\ta.True(IP4(\"255.255.255.255\"))\n\ta.True(IP4(\"255.0.3.255\"))\n\ta.True(IP4(\"127.010.0.1\"))\n\ta.True(IP4(\"027.01.0.1\"))\n\n\ta.False(IP4(\"1127.01.0.1\"))\n}\n\nfunc TestEmail(t *testing.T) {\n\ta := assert.New(t)\n\n\ta.True(Email(\"email@email.com\"))\n\ta.True(Email(\"em2il@email.com.cn\"))\n\ta.True(Email(\"12345@qq.com\"))\n\ta.True(Email(\"email.test@email.com\"))\n\ta.True(Email(\"email.test@email123.com\"))\n\ta.True(Email(\"em2il@email\"))\n\n\t\/\/ 2个@\n\ta.False(Email(\"em@2l@email.com\"))\n\t\/\/ 没有@\n\ta.False(Email(\"email2email.com.cn\"))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage rsyslog_test\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\tstdtesting \"testing\"\n\t\"time\"\n\n\t\"github.com\/juju\/testing\"\n\tjc \"github.com\/juju\/testing\/checkers\"\n\tgc \"launchpad.net\/gocheck\"\n\n\t\"launchpad.net\/juju-core\/cert\"\n\tjujutesting \"launchpad.net\/juju-core\/juju\/testing\"\n\t\"launchpad.net\/juju-core\/state\"\n\t\"launchpad.net\/juju-core\/state\/api\"\n\tcoretesting \"launchpad.net\/juju-core\/testing\"\n\t\"launchpad.net\/juju-core\/utils\/syslog\"\n\t\"launchpad.net\/juju-core\/worker\/rsyslog\"\n)\n\nfunc TestPackage(t *stdtesting.T) {\n\tcoretesting.MgoTestPackage(t)\n}\n\ntype RsyslogSuite struct {\n\tjujutesting.JujuConnSuite\n}\n\nvar _ = gc.Suite(&RsyslogSuite{})\n\nfunc (s *RsyslogSuite) SetUpSuite(c *gc.C) {\n\ts.JujuConnSuite.SetUpSuite(c)\n\t\/\/ TODO(waigani) 2014-03-19 bug 1294462\n\t\/\/ Add patch for suite functions\n\trestore := testing.PatchValue(rsyslog.LookupUser, func(username string) (uid, gid int, err error) {\n\t\t\/\/ worker will not attempt to chown files if uid\/gid is 0\n\t\treturn 0, 0, nil\n\t})\n\ts.AddSuiteCleanup(func(*gc.C) { restore() })\n}\n\nfunc (s *RsyslogSuite) SetUpTest(c *gc.C) {\n\ts.JujuConnSuite.SetUpTest(c)\n\ts.PatchValue(rsyslog.RestartRsyslog, func() error { return nil })\n\ts.PatchValue(rsyslog.LogDir, c.MkDir())\n\ts.PatchValue(rsyslog.RsyslogConfDir, c.MkDir())\n}\n\nfunc waitForFile(c *gc.C, file string) {\n\ttimeout := time.After(coretesting.LongWait)\n\tfor {\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\tc.Fatalf(\"timed out waiting for %s to be written\", file)\n\t\tcase <-time.After(coretesting.ShortWait):\n\t\t\tif _, err := os.Stat(file); err == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc waitForRestart(c *gc.C, restarted chan struct{}) {\n\ttimeout := time.After(coretesting.LongWait)\n\tfor {\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\tc.Fatalf(\"timed out waiting for rsyslog to be restarted\")\n\t\tcase <-restarted:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (s *RsyslogSuite) TestStartStop(c *gc.C) {\n\tst, m := s.OpenAPIAsNewMachine(c, state.JobHostUnits)\n\tworker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeForwarding, m.Tag(), \"\", []string{\"0.1.2.3\"})\n\tc.Assert(err, gc.IsNil)\n\tworker.Kill()\n\tc.Assert(worker.Wait(), gc.IsNil)\n}\n\nfunc (s *RsyslogSuite) TestTearDown(c *gc.C) {\n\tst, m := s.OpenAPIAsNewMachine(c, state.JobManageEnviron)\n\tworker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeAccumulate, m.Tag(), \"\", []string{\"0.1.2.3\"})\n\tc.Assert(err, gc.IsNil)\n\tconfFile := filepath.Join(*rsyslog.RsyslogConfDir, \"25-juju.conf\")\n\t\/\/ On worker teardown, the rsyslog config file should be removed.\n\tdefer func() {\n\t\t_, err := os.Stat(confFile)\n\t\tc.Assert(err, jc.Satisfies, os.IsNotExist)\n\t}()\n\tdefer func() { c.Assert(worker.Wait(), gc.IsNil) }()\n\tdefer worker.Kill()\n\twaitForFile(c, confFile)\n}\n\nfunc (s *RsyslogSuite) TestModeForwarding(c *gc.C) {\n\terr := s.APIState.Client().EnvironmentSet(map[string]interface{}{\"rsyslog-ca-cert\": coretesting.CACert})\n\tc.Assert(err, gc.IsNil)\n\tst, m := s.OpenAPIAsNewMachine(c, state.JobHostUnits)\n\taddrs := []string{\"0.1.2.3\", \"0.2.4.6\"}\n\tworker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeForwarding, m.Tag(), \"\", addrs)\n\tc.Assert(err, gc.IsNil)\n\tdefer func() { c.Assert(worker.Wait(), gc.IsNil) }()\n\tdefer worker.Kill()\n\n\t\/\/ We should get a ca-cert.pem with the contents introduced into state config.\n\twaitForFile(c, filepath.Join(*rsyslog.LogDir, \"ca-cert.pem\"))\n\tcaCertPEM, err := ioutil.ReadFile(filepath.Join(*rsyslog.LogDir, \"ca-cert.pem\"))\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(string(caCertPEM), gc.DeepEquals, coretesting.CACert)\n\n\t\/\/ Verify rsyslog configuration.\n\twaitForFile(c, filepath.Join(*rsyslog.RsyslogConfDir, \"25-juju.conf\"))\n\trsyslogConf, err := ioutil.ReadFile(filepath.Join(*rsyslog.RsyslogConfDir, \"25-juju.conf\"))\n\tc.Assert(err, gc.IsNil)\n\n\tsyslogPort := s.Conn.Environ.Config().SyslogPort()\n\tsyslogConfig := syslog.NewForwardConfig(m.Tag(), *rsyslog.LogDir, syslogPort, \"\", addrs)\n\tsyslogConfig.ConfigDir = *rsyslog.RsyslogConfDir\n\trendered, err := syslogConfig.Render()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(string(rsyslogConf), gc.DeepEquals, string(rendered))\n}\n\nfunc (s *RsyslogSuite) TestModeAccumulate(c *gc.C) {\n\tst, m := s.OpenAPIAsNewMachine(c, state.JobManageEnviron)\n\tworker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeAccumulate, m.Tag(), \"\", nil)\n\tc.Assert(err, gc.IsNil)\n\tdefer func() { c.Assert(worker.Wait(), gc.IsNil) }()\n\tdefer worker.Kill()\n\twaitForFile(c, filepath.Join(*rsyslog.LogDir, \"ca-cert.pem\"))\n\n\t\/\/ We should have ca-cert.pem, rsyslog-cert.pem, and rsyslog-key.pem.\n\tcaCertPEM, err := ioutil.ReadFile(filepath.Join(*rsyslog.LogDir, \"ca-cert.pem\"))\n\tc.Assert(err, gc.IsNil)\n\trsyslogCertPEM, err := ioutil.ReadFile(filepath.Join(*rsyslog.LogDir, \"rsyslog-cert.pem\"))\n\tc.Assert(err, gc.IsNil)\n\trsyslogKeyPEM, err := ioutil.ReadFile(filepath.Join(*rsyslog.LogDir, \"rsyslog-key.pem\"))\n\tc.Assert(err, gc.IsNil)\n\t_, _, err = cert.ParseCertAndKey(string(rsyslogCertPEM), string(rsyslogKeyPEM))\n\tc.Assert(err, gc.IsNil)\n\terr = cert.Verify(string(rsyslogCertPEM), string(caCertPEM), time.Now().UTC())\n\tc.Assert(err, gc.IsNil)\n\n\t\/\/ Verify rsyslog configuration.\n\twaitForFile(c, filepath.Join(*rsyslog.RsyslogConfDir, \"25-juju.conf\"))\n\trsyslogConf, err := ioutil.ReadFile(filepath.Join(*rsyslog.RsyslogConfDir, \"25-juju.conf\"))\n\tc.Assert(err, gc.IsNil)\n\n\tsyslogPort := s.Conn.Environ.Config().SyslogPort()\n\tsyslogConfig := syslog.NewAccumulateConfig(m.Tag(), *rsyslog.LogDir, syslogPort, \"\", []string{\"foo:80\"})\n\tsyslogConfig.ConfigDir = *rsyslog.RsyslogConfDir\n\trendered, err := syslogConfig.Render()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(string(rsyslogConf), gc.DeepEquals, string(rendered))\n}\n\nfunc (s *RsyslogSuite) TestNamespace(c *gc.C) {\n\tst, _ := s.OpenAPIAsNewMachine(c, state.JobManageEnviron)\n\t\/\/ namespace only takes effect in filenames\n\t\/\/ for machine-0; all others assume isolation.\n\ts.testNamespace(c, st, \"machine-0\", \"\", \"25-juju.conf\", *rsyslog.LogDir)\n\ts.testNamespace(c, st, \"machine-0\", \"mynamespace\", \"25-juju-mynamespace.conf\", *rsyslog.LogDir+\"-mynamespace\")\n\ts.testNamespace(c, st, \"machine-1\", \"\", \"25-juju.conf\", *rsyslog.LogDir)\n\ts.testNamespace(c, st, \"machine-1\", \"mynamespace\", \"25-juju.conf\", *rsyslog.LogDir)\n\ts.testNamespace(c, st, \"unit-myservice-0\", \"\", \"26-juju-unit-myservice-0.conf\", *rsyslog.LogDir)\n\ts.testNamespace(c, st, \"unit-myservice-0\", \"mynamespace\", \"26-juju-unit-myservice-0.conf\", *rsyslog.LogDir)\n}\n\n\/\/ testNamespace starts a worker and ensures that\n\/\/ the rsyslog config file has the expected filename,\n\/\/ and the appropriate log dir is used.\nfunc (s *RsyslogSuite) testNamespace(c *gc.C, st *api.State, tag, namespace, expectedFilename, expectedLogDir string) {\n\trestarted := make(chan struct{}, 2) \/\/ once for create, once for teardown\n\ts.PatchValue(rsyslog.RestartRsyslog, func() error {\n\t\trestarted <- struct{}{}\n\t\treturn nil\n\t})\n\n\terr := os.MkdirAll(expectedLogDir, 0755)\n\tc.Assert(err, gc.IsNil)\n\terr = s.APIState.Client().EnvironmentSet(map[string]interface{}{\"rsyslog-ca-cert\": coretesting.CACert})\n\tc.Assert(err, gc.IsNil)\n\tworker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeForwarding, tag, namespace, []string{\"0.1.2.3\"})\n\tc.Assert(err, gc.IsNil)\n\tdefer func() { c.Assert(worker.Wait(), gc.IsNil) }()\n\tdefer worker.Kill()\n\n\t\/\/ Ensure that ca-cert.pem gets written to the expected log dir.\n\twaitForFile(c, filepath.Join(expectedLogDir, \"ca-cert.pem\"))\n\n\t\/\/ Wait for rsyslog to be restarted, so we can check to see\n\t\/\/ what the name of the config file is.\n\twaitForRestart(c, restarted)\n\tdir, err := os.Open(*rsyslog.RsyslogConfDir)\n\tc.Assert(err, gc.IsNil)\n\tnames, err := dir.Readdirnames(-1)\n\tdir.Close()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(names, gc.HasLen, 1)\n\tc.Assert(names[0], gc.Equals, expectedFilename)\n}\n\nfunc (s *RsyslogSuite) TestConfigChange(c *gc.C) {\n\tvar restarted bool\n\ts.PatchValue(rsyslog.RestartRsyslog, func() error {\n\t\trestarted = true\n\t\treturn nil\n\t})\n\n\tst, m := s.OpenAPIAsNewMachine(c, state.JobHostUnits)\n\thandler, err := rsyslog.NewRsyslogConfigHandler(st.Rsyslog(), rsyslog.RsyslogModeForwarding, m.Tag(), \"\", []string{\"0.1.2.3\"})\n\tc.Assert(err, gc.IsNil)\n\n\tassertRestart := func(v bool) {\n\t\terr := handler.Handle()\n\t\tc.Assert(err, gc.IsNil)\n\t\tc.Assert(restarted, gc.Equals, v)\n\t\trestarted = false\n\t\t\/\/ Handling again should not restart, as no changes have been made.\n\t\terr = handler.Handle()\n\t\tc.Assert(err, gc.IsNil)\n\t\tc.Assert(restarted, jc.IsFalse)\n\t}\n\n\terr = s.APIState.Client().EnvironmentSet(map[string]interface{}{\"rsyslog-ca-cert\": coretesting.CACert})\n\tc.Assert(err, gc.IsNil)\n\tassertRestart(true)\n\n\terr = s.APIState.Client().EnvironmentSet(map[string]interface{}{\"syslog-port\": 1})\n\tc.Assert(err, gc.IsNil)\n\tassertRestart(true)\n\n\terr = s.APIState.Client().EnvironmentSet(map[string]interface{}{\"unrelated\": \"anything\"})\n\tc.Assert(err, gc.IsNil)\n\tassertRestart(false)\n\n\terr = s.APIState.Client().EnvironmentSet(map[string]interface{}{\"syslog-port\": 2})\n\tc.Assert(err, gc.IsNil)\n\tassertRestart(true)\n}\n<commit_msg>Test fix<commit_after>\/\/ Copyright 2014 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage rsyslog_test\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\tstdtesting \"testing\"\n\t\"time\"\n\n\t\"github.com\/juju\/testing\"\n\tjc \"github.com\/juju\/testing\/checkers\"\n\tgc \"launchpad.net\/gocheck\"\n\n\t\"launchpad.net\/juju-core\/cert\"\n\tjujutesting \"launchpad.net\/juju-core\/juju\/testing\"\n\t\"launchpad.net\/juju-core\/state\"\n\t\"launchpad.net\/juju-core\/state\/api\"\n\tcoretesting \"launchpad.net\/juju-core\/testing\"\n\t\"launchpad.net\/juju-core\/utils\/syslog\"\n\t\"launchpad.net\/juju-core\/worker\/rsyslog\"\n)\n\nfunc TestPackage(t *stdtesting.T) {\n\tcoretesting.MgoTestPackage(t)\n}\n\ntype RsyslogSuite struct {\n\tjujutesting.JujuConnSuite\n}\n\nvar _ = gc.Suite(&RsyslogSuite{})\n\nfunc (s *RsyslogSuite) SetUpSuite(c *gc.C) {\n\ts.JujuConnSuite.SetUpSuite(c)\n\t\/\/ TODO(waigani) 2014-03-19 bug 1294462\n\t\/\/ Add patch for suite functions\n\trestore := testing.PatchValue(rsyslog.LookupUser, func(username string) (uid, gid int, err error) {\n\t\t\/\/ worker will not attempt to chown files if uid\/gid is 0\n\t\treturn 0, 0, nil\n\t})\n\ts.AddSuiteCleanup(func(*gc.C) { restore() })\n}\n\nfunc (s *RsyslogSuite) SetUpTest(c *gc.C) {\n\ts.JujuConnSuite.SetUpTest(c)\n\ts.PatchValue(rsyslog.RestartRsyslog, func() error { return nil })\n\ts.PatchValue(rsyslog.LogDir, c.MkDir())\n\ts.PatchValue(rsyslog.RsyslogConfDir, c.MkDir())\n}\n\nfunc waitForFile(c *gc.C, file string) {\n\ttimeout := time.After(coretesting.LongWait)\n\tfor {\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\tc.Fatalf(\"timed out waiting for %s to be written\", file)\n\t\tcase <-time.After(coretesting.ShortWait):\n\t\t\tif _, err := os.Stat(file); err == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc waitForRestart(c *gc.C, restarted chan struct{}) {\n\ttimeout := time.After(coretesting.LongWait)\n\tfor {\n\t\tselect {\n\t\tcase <-timeout:\n\t\t\tc.Fatalf(\"timed out waiting for rsyslog to be restarted\")\n\t\tcase <-restarted:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (s *RsyslogSuite) TestStartStop(c *gc.C) {\n\tst, m := s.OpenAPIAsNewMachine(c, state.JobHostUnits)\n\tworker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeForwarding, m.Tag(), \"\", []string{\"0.1.2.3\"})\n\tc.Assert(err, gc.IsNil)\n\tworker.Kill()\n\tc.Assert(worker.Wait(), gc.IsNil)\n}\n\nfunc (s *RsyslogSuite) TestTearDown(c *gc.C) {\n\tst, m := s.OpenAPIAsNewMachine(c, state.JobManageEnviron)\n\tworker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeAccumulate, m.Tag(), \"\", []string{\"0.1.2.3\"})\n\tc.Assert(err, gc.IsNil)\n\tconfFile := filepath.Join(*rsyslog.RsyslogConfDir, \"25-juju.conf\")\n\t\/\/ On worker teardown, the rsyslog config file should be removed.\n\tdefer func() {\n\t\t_, err := os.Stat(confFile)\n\t\tc.Assert(err, jc.Satisfies, os.IsNotExist)\n\t}()\n\tdefer func() { c.Assert(worker.Wait(), gc.IsNil) }()\n\tdefer worker.Kill()\n\twaitForFile(c, confFile)\n}\n\nfunc (s *RsyslogSuite) TestModeForwarding(c *gc.C) {\n\terr := s.APIState.Client().EnvironmentSet(map[string]interface{}{\"rsyslog-ca-cert\": coretesting.CACert})\n\tc.Assert(err, gc.IsNil)\n\tst, m := s.OpenAPIAsNewMachine(c, state.JobHostUnits)\n\taddrs := []string{\"0.1.2.3\", \"0.2.4.6\"}\n\tworker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeForwarding, m.Tag(), \"\", addrs)\n\tc.Assert(err, gc.IsNil)\n\tdefer func() { c.Assert(worker.Wait(), gc.IsNil) }()\n\tdefer worker.Kill()\n\n\t\/\/ We should get a ca-cert.pem with the contents introduced into state config.\n\twaitForFile(c, filepath.Join(*rsyslog.LogDir, \"ca-cert.pem\"))\n\tcaCertPEM, err := ioutil.ReadFile(filepath.Join(*rsyslog.LogDir, \"ca-cert.pem\"))\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(string(caCertPEM), gc.DeepEquals, coretesting.CACert)\n\n\t\/\/ Verify rsyslog configuration.\n\twaitForFile(c, filepath.Join(*rsyslog.RsyslogConfDir, \"25-juju.conf\"))\n\trsyslogConf, err := ioutil.ReadFile(filepath.Join(*rsyslog.RsyslogConfDir, \"25-juju.conf\"))\n\tc.Assert(err, gc.IsNil)\n\n\tsyslogPort := s.Conn.Environ.Config().SyslogPort()\n\tsyslogConfig := syslog.NewForwardConfig(m.Tag(), *rsyslog.LogDir, syslogPort, \"\", addrs)\n\tsyslogConfig.ConfigDir = *rsyslog.RsyslogConfDir\n\trendered, err := syslogConfig.Render()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(string(rsyslogConf), gc.DeepEquals, string(rendered))\n}\n\nfunc (s *RsyslogSuite) TestModeAccumulate(c *gc.C) {\n\tst, m := s.OpenAPIAsNewMachine(c, state.JobManageEnviron)\n\tworker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeAccumulate, m.Tag(), \"\", nil)\n\tc.Assert(err, gc.IsNil)\n\tdefer func() { c.Assert(worker.Wait(), gc.IsNil) }()\n\tdefer worker.Kill()\n\twaitForFile(c, filepath.Join(*rsyslog.LogDir, \"ca-cert.pem\"))\n\n\t\/\/ We should have ca-cert.pem, rsyslog-cert.pem, and rsyslog-key.pem.\n\tcaCertPEM, err := ioutil.ReadFile(filepath.Join(*rsyslog.LogDir, \"ca-cert.pem\"))\n\tc.Assert(err, gc.IsNil)\n\trsyslogCertPEM, err := ioutil.ReadFile(filepath.Join(*rsyslog.LogDir, \"rsyslog-cert.pem\"))\n\tc.Assert(err, gc.IsNil)\n\trsyslogKeyPEM, err := ioutil.ReadFile(filepath.Join(*rsyslog.LogDir, \"rsyslog-key.pem\"))\n\tc.Assert(err, gc.IsNil)\n\t_, _, err = cert.ParseCertAndKey(string(rsyslogCertPEM), string(rsyslogKeyPEM))\n\tc.Assert(err, gc.IsNil)\n\terr = cert.Verify(string(rsyslogCertPEM), string(caCertPEM), time.Now().UTC())\n\tc.Assert(err, gc.IsNil)\n\n\t\/\/ Verify rsyslog configuration.\n\twaitForFile(c, filepath.Join(*rsyslog.RsyslogConfDir, \"25-juju.conf\"))\n\trsyslogConf, err := ioutil.ReadFile(filepath.Join(*rsyslog.RsyslogConfDir, \"25-juju.conf\"))\n\tc.Assert(err, gc.IsNil)\n\n\tsyslogPort := s.Conn.Environ.Config().SyslogPort()\n\tsyslogConfig := syslog.NewAccumulateConfig(m.Tag(), *rsyslog.LogDir, syslogPort, \"\", []string{})\n\tsyslogConfig.ConfigDir = *rsyslog.RsyslogConfDir\n\trendered, err := syslogConfig.Render()\n\tc.Assert(err, gc.IsNil)\n\n\tc.Assert(string(rsyslogConf), gc.DeepEquals, string(rendered))\n}\n\nfunc (s *RsyslogSuite) TestNamespace(c *gc.C) {\n\tst, _ := s.OpenAPIAsNewMachine(c, state.JobManageEnviron)\n\t\/\/ namespace only takes effect in filenames\n\t\/\/ for machine-0; all others assume isolation.\n\ts.testNamespace(c, st, \"machine-0\", \"\", \"25-juju.conf\", *rsyslog.LogDir)\n\ts.testNamespace(c, st, \"machine-0\", \"mynamespace\", \"25-juju-mynamespace.conf\", *rsyslog.LogDir+\"-mynamespace\")\n\ts.testNamespace(c, st, \"machine-1\", \"\", \"25-juju.conf\", *rsyslog.LogDir)\n\ts.testNamespace(c, st, \"machine-1\", \"mynamespace\", \"25-juju.conf\", *rsyslog.LogDir)\n\ts.testNamespace(c, st, \"unit-myservice-0\", \"\", \"26-juju-unit-myservice-0.conf\", *rsyslog.LogDir)\n\ts.testNamespace(c, st, \"unit-myservice-0\", \"mynamespace\", \"26-juju-unit-myservice-0.conf\", *rsyslog.LogDir)\n}\n\n\/\/ testNamespace starts a worker and ensures that\n\/\/ the rsyslog config file has the expected filename,\n\/\/ and the appropriate log dir is used.\nfunc (s *RsyslogSuite) testNamespace(c *gc.C, st *api.State, tag, namespace, expectedFilename, expectedLogDir string) {\n\trestarted := make(chan struct{}, 2) \/\/ once for create, once for teardown\n\ts.PatchValue(rsyslog.RestartRsyslog, func() error {\n\t\trestarted <- struct{}{}\n\t\treturn nil\n\t})\n\n\terr := os.MkdirAll(expectedLogDir, 0755)\n\tc.Assert(err, gc.IsNil)\n\terr = s.APIState.Client().EnvironmentSet(map[string]interface{}{\"rsyslog-ca-cert\": coretesting.CACert})\n\tc.Assert(err, gc.IsNil)\n\tworker, err := rsyslog.NewRsyslogConfigWorker(st.Rsyslog(), rsyslog.RsyslogModeForwarding, tag, namespace, []string{\"0.1.2.3\"})\n\tc.Assert(err, gc.IsNil)\n\tdefer func() { c.Assert(worker.Wait(), gc.IsNil) }()\n\tdefer worker.Kill()\n\n\t\/\/ Ensure that ca-cert.pem gets written to the expected log dir.\n\twaitForFile(c, filepath.Join(expectedLogDir, \"ca-cert.pem\"))\n\n\t\/\/ Wait for rsyslog to be restarted, so we can check to see\n\t\/\/ what the name of the config file is.\n\twaitForRestart(c, restarted)\n\tdir, err := os.Open(*rsyslog.RsyslogConfDir)\n\tc.Assert(err, gc.IsNil)\n\tnames, err := dir.Readdirnames(-1)\n\tdir.Close()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(names, gc.HasLen, 1)\n\tc.Assert(names[0], gc.Equals, expectedFilename)\n}\n\nfunc (s *RsyslogSuite) TestConfigChange(c *gc.C) {\n\tvar restarted bool\n\ts.PatchValue(rsyslog.RestartRsyslog, func() error {\n\t\trestarted = true\n\t\treturn nil\n\t})\n\n\tst, m := s.OpenAPIAsNewMachine(c, state.JobHostUnits)\n\thandler, err := rsyslog.NewRsyslogConfigHandler(st.Rsyslog(), rsyslog.RsyslogModeForwarding, m.Tag(), \"\", []string{\"0.1.2.3\"})\n\tc.Assert(err, gc.IsNil)\n\n\tassertRestart := func(v bool) {\n\t\terr := handler.Handle()\n\t\tc.Assert(err, gc.IsNil)\n\t\tc.Assert(restarted, gc.Equals, v)\n\t\trestarted = false\n\t\t\/\/ Handling again should not restart, as no changes have been made.\n\t\terr = handler.Handle()\n\t\tc.Assert(err, gc.IsNil)\n\t\tc.Assert(restarted, jc.IsFalse)\n\t}\n\n\terr = s.APIState.Client().EnvironmentSet(map[string]interface{}{\"rsyslog-ca-cert\": coretesting.CACert})\n\tc.Assert(err, gc.IsNil)\n\tassertRestart(true)\n\n\terr = s.APIState.Client().EnvironmentSet(map[string]interface{}{\"syslog-port\": 1})\n\tc.Assert(err, gc.IsNil)\n\tassertRestart(true)\n\n\terr = s.APIState.Client().EnvironmentSet(map[string]interface{}{\"unrelated\": \"anything\"})\n\tc.Assert(err, gc.IsNil)\n\tassertRestart(false)\n\n\terr = s.APIState.Client().EnvironmentSet(map[string]interface{}{\"syslog-port\": 2})\n\tc.Assert(err, gc.IsNil)\n\tassertRestart(true)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012-2014 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage charm\n\nimport (\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/juju\/utils\"\n\t\"gopkg.in\/juju\/charm.v6-unstable\"\n\n\t\"github.com\/juju\/juju\/downloader\"\n)\n\n\/\/ Download exposes the downloader.Download methods needed here.\ntype Downloader interface {\n\t\/\/ Download starts a new charm archive download, waits for it to\n\t\/\/ complete, and returns the local name of the file.\n\tDownload(req downloader.Request) (string, error)\n}\n\n\/\/ BundlesDir is responsible for storing and retrieving charm bundles\n\/\/ identified by state charms.\ntype BundlesDir struct {\n\tpath       string\n\tdownloader Downloader\n}\n\n\/\/ NewBundlesDir returns a new BundlesDir which uses path for storage.\nfunc NewBundlesDir(path string, dlr Downloader) *BundlesDir {\n\tif dlr == nil {\n\t\tdlr = downloader.New(downloader.NewArgs{\n\t\t\tHostnameVerification: utils.NoVerifySSLHostnames,\n\t\t})\n\t}\n\treturn &BundlesDir{\n\t\tpath:       path,\n\t\tdownloader: dlr,\n\t}\n}\n\n\/\/ Read returns a charm bundle from the directory. If no bundle exists yet,\n\/\/ one will be downloaded and validated and copied into the directory before\n\/\/ being returned. Downloads will be aborted if a value is received on abort.\nfunc (d *BundlesDir) Read(info BundleInfo, abort <-chan struct{}) (Bundle, error) {\n\tpath := d.bundlePath(info)\n\tif _, err := os.Stat(path); err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := d.download(info, path, abort); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn charm.ReadCharmArchive(path)\n}\n\n\/\/ download fetches the supplied charm and checks that it has the correct sha256\n\/\/ hash, then copies it into the directory. If a value is received on abort, the\n\/\/ download will be stopped.\nfunc (d *BundlesDir) download(info BundleInfo, target string, abort <-chan struct{}) (err error) {\n\t\/\/ First download...\n\tcurl, err := url.Parse(info.URL().String())\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"could not parse charm URL\")\n\t}\n\texpectedSha256, err := info.ArchiveSha256()\n\treq := downloader.Request{\n\t\tURL:       curl,\n\t\tTargetDir: downloadsPath(d.path), \/\/ XXX check this\n\t\tVerify:    downloader.NewSha256Verifier(expectedSha256),\n\t\tAbort:     abort,\n\t}\n\tlogger.Infof(\"downloading %s from API server\", info.URL())\n\tfilename, err := d.downloader.Download(req)\n\tif err != nil {\n\t\treturn errors.Annotatef(err, \"failed to download charm %q from API server\", info.URL())\n\t}\n\tdefer errors.DeferredAnnotatef(&err, \"downloaded but failed to copy charm to %q from %q\", target, filename)\n\n\t\/\/ ...then move the right location.\n\tif err := os.MkdirAll(d.path, 0755); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tif err := os.Rename(filename, target); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\treturn nil\n}\n\n\/\/ bundlePath returns the path to the location where the verified charm\n\/\/ bundle identified by info will be, or has been, saved.\nfunc (d *BundlesDir) bundlePath(info BundleInfo) string {\n\treturn d.bundleURLPath(info.URL())\n}\n\n\/\/ bundleURLPath returns the path to the location where the verified charm\n\/\/ bundle identified by url will be, or has been, saved.\nfunc (d *BundlesDir) bundleURLPath(url *charm.URL) string {\n\treturn path.Join(d.path, charm.Quote(url.String()))\n}\n\n\/\/ ClearDownloads removes any entries in the temporary bundle download\n\/\/ directory. It is intended to be called on uniter startup.\nfunc ClearDownloads(bundlesDir string) error {\n\tdownloadDir := downloadsPath(bundlesDir)\n\terr := os.RemoveAll(downloadDir)\n\treturn errors.Annotate(err, \"unable to clear bundle downloads\")\n}\n\n\/\/ downloadsPath returns the path to the directory into which charms are\n\/\/ downloaded.\nfunc downloadsPath(bunsDir string) string {\n\treturn path.Join(bunsDir, \"downloads\")\n}\n<commit_msg>worker\/uniter\/charm: Removed a reminder<commit_after>\/\/ Copyright 2012-2014 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage charm\n\nimport (\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/juju\/utils\"\n\t\"gopkg.in\/juju\/charm.v6-unstable\"\n\n\t\"github.com\/juju\/juju\/downloader\"\n)\n\n\/\/ Download exposes the downloader.Download methods needed here.\ntype Downloader interface {\n\t\/\/ Download starts a new charm archive download, waits for it to\n\t\/\/ complete, and returns the local name of the file.\n\tDownload(req downloader.Request) (string, error)\n}\n\n\/\/ BundlesDir is responsible for storing and retrieving charm bundles\n\/\/ identified by state charms.\ntype BundlesDir struct {\n\tpath       string\n\tdownloader Downloader\n}\n\n\/\/ NewBundlesDir returns a new BundlesDir which uses path for storage.\nfunc NewBundlesDir(path string, dlr Downloader) *BundlesDir {\n\tif dlr == nil {\n\t\tdlr = downloader.New(downloader.NewArgs{\n\t\t\tHostnameVerification: utils.NoVerifySSLHostnames,\n\t\t})\n\t}\n\treturn &BundlesDir{\n\t\tpath:       path,\n\t\tdownloader: dlr,\n\t}\n}\n\n\/\/ Read returns a charm bundle from the directory. If no bundle exists yet,\n\/\/ one will be downloaded and validated and copied into the directory before\n\/\/ being returned. Downloads will be aborted if a value is received on abort.\nfunc (d *BundlesDir) Read(info BundleInfo, abort <-chan struct{}) (Bundle, error) {\n\tpath := d.bundlePath(info)\n\tif _, err := os.Stat(path); err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\tif err := d.download(info, path, abort); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn charm.ReadCharmArchive(path)\n}\n\n\/\/ download fetches the supplied charm and checks that it has the correct sha256\n\/\/ hash, then copies it into the directory. If a value is received on abort, the\n\/\/ download will be stopped.\nfunc (d *BundlesDir) download(info BundleInfo, target string, abort <-chan struct{}) (err error) {\n\t\/\/ First download...\n\tcurl, err := url.Parse(info.URL().String())\n\tif err != nil {\n\t\treturn errors.Annotate(err, \"could not parse charm URL\")\n\t}\n\texpectedSha256, err := info.ArchiveSha256()\n\treq := downloader.Request{\n\t\tURL:       curl,\n\t\tTargetDir: downloadsPath(d.path),\n\t\tVerify:    downloader.NewSha256Verifier(expectedSha256),\n\t\tAbort:     abort,\n\t}\n\tlogger.Infof(\"downloading %s from API server\", info.URL())\n\tfilename, err := d.downloader.Download(req)\n\tif err != nil {\n\t\treturn errors.Annotatef(err, \"failed to download charm %q from API server\", info.URL())\n\t}\n\tdefer errors.DeferredAnnotatef(&err, \"downloaded but failed to copy charm to %q from %q\", target, filename)\n\n\t\/\/ ...then move the right location.\n\tif err := os.MkdirAll(d.path, 0755); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tif err := os.Rename(filename, target); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\treturn nil\n}\n\n\/\/ bundlePath returns the path to the location where the verified charm\n\/\/ bundle identified by info will be, or has been, saved.\nfunc (d *BundlesDir) bundlePath(info BundleInfo) string {\n\treturn d.bundleURLPath(info.URL())\n}\n\n\/\/ bundleURLPath returns the path to the location where the verified charm\n\/\/ bundle identified by url will be, or has been, saved.\nfunc (d *BundlesDir) bundleURLPath(url *charm.URL) string {\n\treturn path.Join(d.path, charm.Quote(url.String()))\n}\n\n\/\/ ClearDownloads removes any entries in the temporary bundle download\n\/\/ directory. It is intended to be called on uniter startup.\nfunc ClearDownloads(bundlesDir string) error {\n\tdownloadDir := downloadsPath(bundlesDir)\n\terr := os.RemoveAll(downloadDir)\n\treturn errors.Annotate(err, \"unable to clear bundle downloads\")\n}\n\n\/\/ downloadsPath returns the path to the directory into which charms are\n\/\/ downloaded.\nfunc downloadsPath(bunsDir string) string {\n\treturn path.Join(bunsDir, \"downloads\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package validator\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\/utf8\"\n)\n\nvar (\n\t\/\/ ERR_MSG_X_MUST_BE_OF_TYPE_Y = `%s must be of type %s`\n\n\t\/\/ ERR_MSG_X_IS_MISSING_AND_REQUIRED  = `%s is missing and required`\n\t\/\/ ERR_MSG_MUST_BE_OF_TYPE_X          = `must be of type %s`\n\t\/\/ ERR_MSG_ARRAY_ITEMS_MUST_BE_UNIQUE = `array items must be unique`\n\n\tERR_MSG_STRING_LENGTH_MUST_BE_GREATER_OR_EQUAL = `string length must be greater or equal to %d`\n\tERR_MSG_STRING_LENGTH_MUST_BE_LOWER_OR_EQUAL   = `string length must be lower or equal to %d`\n\tERR_MSG_DOES_NOT_MATCH_PATTERN                 = `does not match pattern '%s'`\n\tERR_MSG_MUST_MATCH_ONE_ENUM_VALUES             = `must match one of the enum values [%s]`\n\n\tERR_MSG_NUMBER_MUST_BE_GREATER = `must be greater than %f`\n\tERR_MSG_NUMBER_MUST_BE_LOWER   = `must be lower than %f`\n\tERR_MSG_MULTIPLE_OF            = `must be a multiple of %f`\n\n\tERR_MSG_DATE = `date should not be zero`\n\n\t\/\/ ERR_MSG_NUMBER_MUST_BE_LOWER_OR_EQUAL   = `must be lower than or equal to %s`\n\t\/\/ ERR_MSG_NUMBER_MUST_BE_GREATER_OR_EQUAL = `must be greater than or equal to %f`\n\n\t\/\/ ERR_MSG_NUMBER_MUST_VALIDATE_ALLOF = `must validate all the schemas (allOf)`\n\t\/\/ ERR_MSG_NUMBER_MUST_VALIDATE_ONEOF = `must validate one and only one schema (oneOf)`\n\t\/\/ ERR_MSG_NUMBER_MUST_VALIDATE_ANYOF = `must validate at least one schema (anyOf)`\n\t\/\/ ERR_MSG_NUMBER_MUST_VALIDATE_NOT   = `must not validate the schema (not)`\n\n\t\/\/ ERR_MSG_ARRAY_MIN_ITEMS = `array must have at least %d items`\n\t\/\/ ERR_MSG_ARRAY_MAX_ITEMS = `array must have at the most %d items`\n\n\t\/\/ ERR_MSG_ARRAY_MIN_PROPERTIES = `must have at least %d properties`\n\t\/\/ ERR_MSG_ARRAY_MAX_PROPERTIES = `must have at the most %d properties`\n\n\t\/\/ ERR_MSG_HAS_DEPENDENCY_ON = `has a dependency on %s`\n\n\t\/\/ ERR_MSG_ARRAY_NO_ADDITIONAL_ITEM = `no additional item allowed on array`\n\n\t\/\/ ERR_MSG_ADDITIONAL_PROPERTY_NOT_ALLOWED = `additional property \"%s\" is not allowed`\n\t\/\/ ERR_MSG_INVALID_PATTERN_PROPERTY        = `property \"%s\" does not match pattern %s`\n)\n\ntype Validator interface {\n\tValidate() error\n}\n\ntype valide struct {\n\tf func() error\n}\n\nfunc (v *valide) Validate() error {\n\treturn v.f()\n}\n\nfunc MinLength(data string, length int) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tif utf8.RuneCount([]byte(data)) < length {\n\t\t\t\treturn fmt.Errorf(ERR_MSG_STRING_LENGTH_MUST_BE_GREATER_OR_EQUAL, length)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\nfunc MaxLength(data string, length int) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tif utf8.RuneCount([]byte(data)) > length {\n\t\t\t\treturn fmt.Errorf(ERR_MSG_STRING_LENGTH_MUST_BE_LOWER_OR_EQUAL, length)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\nfunc Pattern(data string, pattern string) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\t\/\/ TODO add caching for compile?\n\t\t\tregex, err := regexp.Compile(pattern)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif !regex.MatchString(data) {\n\t\t\t\treturn fmt.Errorf(ERR_MSG_DOES_NOT_MATCH_PATTERN, pattern)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\n\/\/ OneOf creates a validator to check if the given value is one of the element\n\/\/ of given string slice\nfunc OneOf(data string, enums []string) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tfor _, val := range enums {\n\t\t\t\tif val == data {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn fmt.Errorf(ERR_MSG_MUST_MATCH_ONE_ENUM_VALUES, strings.Join(enums, \",\"))\n\t\t},\n\t}\n}\n\n\/\/ Min creates a validator to check if the given value is greater than the given\n\/\/ value\nfunc Min(data float64, min float64) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tif data < min {\n\t\t\t\treturn fmt.Errorf(ERR_MSG_NUMBER_MUST_BE_GREATER, min)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\n\/\/ Max creates a validator to check if the given value is lower than the given\n\/\/ value\nfunc Max(data float64, max float64) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tif data > max {\n\t\t\t\treturn fmt.Errorf(ERR_MSG_NUMBER_MUST_BE_LOWER, max)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\n\/\/ MultipleOf creates a validator to check if the check value is multiple of the\n\/\/ given value\nfunc MultipleOf(data float64, multipleOf float64) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tif math.Mod(data, multipleOf) == 0 {\n\t\t\t\treturn fmt.Errorf(ERR_MSG_MULTIPLE_OF, multipleOf)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\n\/\/ Date creates a validator to check if the given date is not zero date\nfunc Date(data time.Time) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tif data.IsZero() {\n\t\t\t\treturn fmt.Errorf(ERR_MSG_DATE)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\n\/\/ NewMulti creates a multi validator, it stops the execution with the first error if error happens while validating\nfunc NewMulti(v ...Validator) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tfor _, vv := range v {\n\t\t\t\tif err := vv.Validate(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n<commit_msg>Validator: make variable names go idiomatic<commit_after>\/\/ Package validator provides a simple validator system for the json-schemas\npackage validator\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\/utf8\"\n)\n\nvar (\n\t\/\/ ERR_MSG_X_MUST_BE_OF_TYPE_Y = `%s must be of type %s`\n\n\t\/\/ ERR_MSG_X_IS_MISSING_AND_REQUIRED  = `%s is missing and required`\n\t\/\/ ERR_MSG_MUST_BE_OF_TYPE_X          = `must be of type %s`\n\t\/\/ ERR_MSG_ARRAY_ITEMS_MUST_BE_UNIQUE = `array items must be unique`\n\n\t\/\/ ErrMsgStringLengthMustBeGreaterOrEqual ...\n\tErrMsgStringLengthMustBeGreaterOrEqual = `string length must be greater or equal to %d`\n\n\t\/\/ ErrMsgStringLengthMustBeLowerOrEqual ...\n\tErrMsgStringLengthMustBeLowerOrEqual = `string length must be lower or equal to %d`\n\n\t\/\/ ErrMsgDoesNotMatchPattern ...\n\tErrMsgDoesNotMatchPattern = `does not match pattern '%s'`\n\n\t\/\/ ErrMsgMustMatchOneEnumValues ...\n\tErrMsgMustMatchOneEnumValues = `must match one of the enum values [%s]`\n\n\t\/\/ ErrMsgNumberMustBeGreater ...\n\tErrMsgNumberMustBeGreater = `must be greater than %f`\n\n\t\/\/ ErrMsgNumberMustBeLower ...\n\tErrMsgNumberMustBeLower = `must be lower than %f`\n\n\t\/\/ ErrMsgMultipleOf ...\n\tErrMsgMultipleOf = `must be a multiple of %f`\n\n\t\/\/ ErrMsgDate ...\n\tErrMsgDate = `date should not be zero`\n\n\t\/\/ ErrMsgNumberMustBeLowerOrEqual   = `must be lower than or equal to %s`\n\t\/\/ ErrMsgNumberMustBeGreatorOrEqual = `must be greater than or equal to %f`\n\n\t\/\/ ERR_MSG_NUMBER_MUST_VALIDATE_ALLOF = `must validate all the schemas (allOf)`\n\t\/\/ ERR_MSG_NUMBER_MUST_VALIDATE_ONEOF = `must validate one and only one schema (oneOf)`\n\t\/\/ ERR_MSG_NUMBER_MUST_VALIDATE_ANYOF = `must validate at least one schema (anyOf)`\n\t\/\/ ERR_MSG_NUMBER_MUST_VALIDATE_NOT   = `must not validate the schema (not)`\n\n\t\/\/ ERR_MSG_ARRAY_MIN_ITEMS = `array must have at least %d items`\n\t\/\/ ERR_MSG_ARRAY_MAX_ITEMS = `array must have at the most %d items`\n\n\t\/\/ ERR_MSG_ARRAY_MIN_PROPERTIES = `must have at least %d properties`\n\t\/\/ ERR_MSG_ARRAY_MAX_PROPERTIES = `must have at the most %d properties`\n\n\t\/\/ ERR_MSG_HAS_DEPENDENCY_ON = `has a dependency on %s`\n\n\t\/\/ ERR_MSG_ARRAY_NO_ADDITIONAL_ITEM = `no additional item allowed on array`\n\n\t\/\/ ERR_MSG_ADDITIONAL_PROPERTY_NOT_ALLOWED = `additional property \"%s\" is not allowed`\n\t\/\/ ERR_MSG_INVALID_PATTERN_PROPERTY        = `property \"%s\" does not match pattern %s`\n)\n\n\/\/ Validator provides an interface for validation contract\ntype Validator interface {\n\tValidate() error\n}\n\ntype valide struct {\n\tf func() error\n}\n\n\/\/ Validate validates the pre-built valide struct\nfunc (v *valide) Validate() error {\n\treturn v.f()\n}\n\n\/\/ MinLength createas a validator for checking if the string has the required\n\/\/ min length\nfunc MinLength(data string, length int) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tif utf8.RuneCount([]byte(data)) < length {\n\t\t\t\treturn fmt.Errorf(ErrMsgStringLengthMustBeGreaterOrEqual, length)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\n\/\/ MaxLength createas a validator for checking if the string has the required\n\/\/ max length\nfunc MaxLength(data string, length int) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tif utf8.RuneCount([]byte(data)) > length {\n\t\t\t\treturn fmt.Errorf(ErrMsgStringLengthMustBeLowerOrEqual, length)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\n\/\/ Pattern validates the given string with the given regex\nfunc Pattern(data string, pattern string) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\t\/\/ TODO add caching for compile?\n\t\t\tregex, err := regexp.Compile(pattern)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif !regex.MatchString(data) {\n\t\t\t\treturn fmt.Errorf(ErrMsgDoesNotMatchPattern, pattern)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\n\/\/ OneOf creates a validator to check if the given value is one of the element\n\/\/ of given string slice\nfunc OneOf(data string, enums []string) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tfor _, val := range enums {\n\t\t\t\tif val == data {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn fmt.Errorf(ErrMsgMustMatchOneEnumValues, strings.Join(enums, \",\"))\n\t\t},\n\t}\n}\n\n\/\/ Min creates a validator to check if the given value is greater than the given\n\/\/ value\nfunc Min(data float64, min float64) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tif data < min {\n\t\t\t\treturn fmt.Errorf(ErrMsgNumberMustBeGreater, min)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\n\/\/ Max creates a validator to check if the given value is lower than the given\n\/\/ value\nfunc Max(data float64, max float64) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tif data > max {\n\t\t\t\treturn fmt.Errorf(ErrMsgNumberMustBeLower, max)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\n\/\/ MultipleOf creates a validator to check if the check value is multiple of the\n\/\/ given value\nfunc MultipleOf(data float64, multipleOf float64) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tif math.Mod(data, multipleOf) == 0 {\n\t\t\t\treturn fmt.Errorf(ErrMsgMultipleOf, multipleOf)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\n\/\/ Date creates a validator to check if the given date is not zero date\nfunc Date(data time.Time) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tif data.IsZero() {\n\t\t\t\treturn fmt.Errorf(ErrMsgDate)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\n\/\/ NewMulti creates a multi validator, it stops the execution with the first error if error happens while validating\nfunc NewMulti(v ...Validator) Validator {\n\treturn &valide{\n\t\tf: func() error {\n\t\t\tfor _, vv := range v {\n\t\t\t\tif err := vv.Validate(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package proxynetworkserviceserver\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/golang\/protobuf\/ptypes\/empty\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"google.golang.org\/grpc\"\n\n\t\"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/apis\/clusterinfo\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/apis\/registry\"\n\tremote_connection \"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/apis\/remote\/connection\"\n\tremote_networkservice \"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/apis\/remote\/networkservice\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/serviceregistry\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/k8s\/pkg\/utils\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/pkg\/tools\"\n)\n\n\/\/ Default values and environment variables of proxy connection\nconst (\n\tProxyNsmdK8sAddressEnv         = \"PROXY_NSMD_K8S_ADDRESS\"\n\tProxyNsmdK8sAddressDefaults    = \"pnsmgr-svc:5005\"\n\tProxyNsmdK8sRemotePortEnv      = \"PROXY_NSMD_K8S_REMOTE_PORT\"\n\tProxyNsmdK8sRemotePortDefaults = \"80\"\n)\n\ntype proxyNetworkServiceServer struct {\n\tserviceRegistry serviceregistry.ServiceRegistry\n}\n\n\/\/ NewProxyNetworkServiceServer creates a new remote.NetworkServiceServer\nfunc NewProxyNetworkServiceServer(serviceRegistry serviceregistry.ServiceRegistry) remote_networkservice.NetworkServiceServer {\n\tserver := &proxyNetworkServiceServer{\n\t\tserviceRegistry: serviceRegistry,\n\t}\n\treturn server\n}\n\nfunc (srv *proxyNetworkServiceServer) Request(ctx context.Context, request *remote_networkservice.NetworkServiceRequest) (*remote_connection.Connection, error) {\n\tlogrus.Infof(\"ProxyNSMD: Received request from client to connect to NetworkService: %v\", request)\n\n\tdestNsmName := request.Connection.DestinationNetworkServiceManagerName\n\tdNsmName, dNsmAddress, err := utils.ParseNsmURL(destNsmName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ProxyNSMD: Failed to extract destination nsm address\")\n\t}\n\n\trequest.Connection.DestinationNetworkServiceManagerName = dNsmName\n\n\tdNsm := &registry.NetworkServiceManager{\n\t\tName: dNsmName,\n\t\tUrl:  dNsmAddress,\n\t}\n\n\tclient, conn, err := srv.serviceRegistry.RemoteNetworkServiceClient(ctx, dNsm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif e := conn.Close(); e != nil {\n\t\t\tlogrus.Errorf(\"ProxyNSMD: Failed to close Network Service Client (%s). %v\", destNsmName, e)\n\t\t}\n\t}()\n\n\tlocalNsrURL := os.Getenv(ProxyNsmdK8sAddressEnv)\n\tif strings.TrimSpace(localNsrURL) == \"\" {\n\t\tlocalNsrURL = ProxyNsmdK8sAddressDefaults\n\t}\n\n\tlocalClusterInfoClient, localConn, err := createClusterInfoClient(ctx, localNsrURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err = localConn.Close(); err != nil {\n\t\t\tlogrus.Errorf(\"ProxyNSMD: Failed to close the local Cluster Info Client (%s). %v\", localNsrURL, err)\n\t\t}\n\t}()\n\n\tremoteNsrPort := os.Getenv(ProxyNsmdK8sRemotePortEnv)\n\tif strings.TrimSpace(remoteNsrPort) == \"\" {\n\t\tremoteNsrPort = ProxyNsmdK8sRemotePortDefaults\n\t}\n\n\tremoteRegistryAddress := dNsmAddress[:strings.Index(dNsmAddress, \":\")] + \":\" + remoteNsrPort\n\tlogrus.Infof(\"ProxyNSMD: Connecting to remote service registry at %v\", remoteRegistryAddress)\n\n\tremoteClusterInfoClient, remoteConn, err := createClusterInfoClient(ctx, remoteRegistryAddress)\n\tif err != nil {\n\t\tlogrus.Errorf(\"ProxyNSMD: Failed connecting to remote service registry at %v: %v\", remoteRegistryAddress, err)\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err = remoteConn.Close(); err != nil {\n\t\t\tlogrus.Errorf(\"ProxyNSMD: Failed to close the remote Cluster Info Client (%s). %v\", remoteRegistryAddress, err)\n\t\t}\n\t}()\n\n\tlocalSrcIP := request.MechanismPreferences[0].Parameters[\"src_ip\"]\n\n\tlocalNodeIPConfiguration, err := localClusterInfoClient.GetNodeIPConfiguration(ctx, &clusterinfo.NodeIPConfiguration{InternalIP: localSrcIP})\n\tif err == nil {\n\t\tif len(localNodeIPConfiguration.ExternalIP) > 0 {\n\t\t\trequest.MechanismPreferences[0].Parameters[\"src_ip\"] = localNodeIPConfiguration.ExternalIP\n\t\t}\n\t}\n\n\tlogrus.Infof(\"ProxyNSMD: Sending request to remote network service: %v\", request)\n\n\tresponse, err := client.Request(ctx, request)\n\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\tremoteNodeIPConfiguration, err := remoteClusterInfoClient.GetNodeIPConfiguration(ctx, &clusterinfo.NodeIPConfiguration{InternalIP: response.Mechanism.Parameters[\"dst_ip\"]})\n\tif err == nil {\n\t\tif len(remoteNodeIPConfiguration.ExternalIP) > 0 {\n\t\t\tresponse.Mechanism.Parameters[\"dst_ip\"] = remoteNodeIPConfiguration.ExternalIP\n\t\t}\n\t}\n\n\tresponse.Mechanism.Parameters[\"src_ip\"] = localSrcIP\n\tresponse.DestinationNetworkServiceManagerName = destNsmName\n\n\tlogrus.Infof(\"ProxyNSMD: Received response from remote network service: %v\", response)\n\n\treturn response, err\n}\n\nfunc (srv *proxyNetworkServiceServer) Close(ctx context.Context, connection *remote_connection.Connection) (*empty.Empty, error) {\n\tlogrus.Infof(\"ProxyNSMD: Proxy closing connection: %v\", *connection)\n\n\tdestNsmName := connection.DestinationNetworkServiceManagerName\n\tdNsmName, dNsmAddress, err := utils.ParseNsmURL(destNsmName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ProxyNSMD: Failed to extract destination nsm address\")\n\t}\n\n\tdNsm := &registry.NetworkServiceManager{\n\t\tName: dNsmName,\n\t\tUrl:  dNsmAddress,\n\t}\n\n\tclient, conn, err := srv.serviceRegistry.RemoteNetworkServiceClient(ctx, dNsm)\n\tif err != nil {\n\t\tlogrus.Errorf(\"ProxyNSMD: Failed to create NSE Client. %v\", err)\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err := conn.Close(); err != nil {\n\t\t\tlogrus.Errorf(\"ProxyNSMD: Failed to close NSE Client. %v\", err)\n\t\t}\n\t}()\n\n\treturn client.Close(ctx, connection)\n}\n\nfunc createClusterInfoClient(ctx context.Context, address string) (clusterinfo.ClusterInfoClient, *grpc.ClientConn, error) {\n\terr := tools.WaitForPortAvailable(ctx, \"tcp\", address, 100*time.Millisecond)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tconn, err := tools.DialContextTCP(ctx, address)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tclient := clusterinfo.NewClusterInfoClient(conn)\n\treturn client, conn, nil\n}\n<commit_msg>Add request attempts into proxy-nsmd request (#1538)<commit_after>package proxynetworkserviceserver\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/golang\/protobuf\/ptypes\/empty\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"google.golang.org\/grpc\"\n\n\t\"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/apis\/clusterinfo\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/apis\/registry\"\n\tremote_connection \"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/apis\/remote\/connection\"\n\tremote_networkservice \"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/apis\/remote\/networkservice\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/serviceregistry\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/k8s\/pkg\/utils\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/pkg\/tools\"\n)\n\n\/\/ Default values and environment variables of proxy connection\nconst (\n\tProxyNsmdK8sAddressEnv         = \"PROXY_NSMD_K8S_ADDRESS\"\n\tProxyNsmdK8sAddressDefaults    = \"pnsmgr-svc:5005\"\n\tProxyNsmdK8sRemotePortEnv      = \"PROXY_NSMD_K8S_REMOTE_PORT\"\n\tProxyNsmdK8sRemotePortDefaults = \"80\"\n\n\tRequestConnectTimeout  = 15 * time.Second\n\tRequestConnectAttempts = 3\n)\n\ntype proxyNetworkServiceServer struct {\n\tserviceRegistry serviceregistry.ServiceRegistry\n}\n\n\/\/ NewProxyNetworkServiceServer creates a new remote.NetworkServiceServer\nfunc NewProxyNetworkServiceServer(serviceRegistry serviceregistry.ServiceRegistry) remote_networkservice.NetworkServiceServer {\n\tserver := &proxyNetworkServiceServer{\n\t\tserviceRegistry: serviceRegistry,\n\t}\n\treturn server\n}\n\nfunc (srv *proxyNetworkServiceServer) Request(ctx context.Context, request *remote_networkservice.NetworkServiceRequest) (*remote_connection.Connection, error) {\n\tlogrus.Infof(\"ProxyNSMD: Received request from client to connect to NetworkService: %v\", request)\n\n\tdestNsmName := request.Connection.DestinationNetworkServiceManagerName\n\tdNsmName, dNsmAddress, err := utils.ParseNsmURL(destNsmName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ProxyNSMD: Failed to extract destination nsm address\")\n\t}\n\n\trequest.Connection.DestinationNetworkServiceManagerName = dNsmName\n\n\tdNsm := &registry.NetworkServiceManager{\n\t\tName: dNsmName,\n\t\tUrl:  dNsmAddress,\n\t}\n\n\tvar client remote_networkservice.NetworkServiceClient\n\tvar conn *grpc.ClientConn\n\tfor i := 0; i < RequestConnectAttempts; i++ {\n\t\trnsCtx, pingCancel := context.WithTimeout(ctx, RequestConnectTimeout)\n\t\tdefer pingCancel()\n\n\t\tclient, conn, err = srv.serviceRegistry.RemoteNetworkServiceClient(rnsCtx, dNsm)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif err != nil {\n\t\tlogrus.Errorf(\"ProxyNSMD: Failed connect to Network Service Client (%s): %v\", destNsmName, err)\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\tif e := conn.Close(); e != nil {\n\t\t\tlogrus.Errorf(\"ProxyNSMD: Failed to close Network Service Client (%s): %v\", destNsmName, e)\n\t\t}\n\t}()\n\n\tlocalNsrURL := os.Getenv(ProxyNsmdK8sAddressEnv)\n\tif strings.TrimSpace(localNsrURL) == \"\" {\n\t\tlocalNsrURL = ProxyNsmdK8sAddressDefaults\n\t}\n\n\tlocalClusterInfoClient, localConn, err := createClusterInfoClient(ctx, localNsrURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err = localConn.Close(); err != nil {\n\t\t\tlogrus.Errorf(\"ProxyNSMD: Failed to close the local Cluster Info Client (%s). %v\", localNsrURL, err)\n\t\t}\n\t}()\n\n\tremoteNsrPort := os.Getenv(ProxyNsmdK8sRemotePortEnv)\n\tif strings.TrimSpace(remoteNsrPort) == \"\" {\n\t\tremoteNsrPort = ProxyNsmdK8sRemotePortDefaults\n\t}\n\n\tremoteRegistryAddress := dNsmAddress[:strings.Index(dNsmAddress, \":\")] + \":\" + remoteNsrPort\n\tlogrus.Infof(\"ProxyNSMD: Connecting to remote service registry at %v\", remoteRegistryAddress)\n\n\tremoteClusterInfoClient, remoteConn, err := createClusterInfoClient(ctx, remoteRegistryAddress)\n\tif err != nil {\n\t\tlogrus.Errorf(\"ProxyNSMD: Failed connecting to remote service registry at %v: %v\", remoteRegistryAddress, err)\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err = remoteConn.Close(); err != nil {\n\t\t\tlogrus.Errorf(\"ProxyNSMD: Failed to close the remote Cluster Info Client (%s). %v\", remoteRegistryAddress, err)\n\t\t}\n\t}()\n\n\tlocalSrcIP := request.MechanismPreferences[0].Parameters[\"src_ip\"]\n\n\tlocalNodeIPConfiguration, err := localClusterInfoClient.GetNodeIPConfiguration(ctx, &clusterinfo.NodeIPConfiguration{InternalIP: localSrcIP})\n\tif err == nil {\n\t\tif len(localNodeIPConfiguration.ExternalIP) > 0 {\n\t\t\trequest.MechanismPreferences[0].Parameters[\"src_ip\"] = localNodeIPConfiguration.ExternalIP\n\t\t}\n\t}\n\n\tlogrus.Infof(\"ProxyNSMD: Sending request to remote network service: %v\", request)\n\n\tresponse, err := client.Request(ctx, request)\n\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\tremoteNodeIPConfiguration, err := remoteClusterInfoClient.GetNodeIPConfiguration(ctx, &clusterinfo.NodeIPConfiguration{InternalIP: response.Mechanism.Parameters[\"dst_ip\"]})\n\tif err == nil {\n\t\tif len(remoteNodeIPConfiguration.ExternalIP) > 0 {\n\t\t\tresponse.Mechanism.Parameters[\"dst_ip\"] = remoteNodeIPConfiguration.ExternalIP\n\t\t}\n\t}\n\n\tresponse.Mechanism.Parameters[\"src_ip\"] = localSrcIP\n\tresponse.DestinationNetworkServiceManagerName = destNsmName\n\n\tlogrus.Infof(\"ProxyNSMD: Received response from remote network service: %v\", response)\n\n\treturn response, err\n}\n\nfunc (srv *proxyNetworkServiceServer) Close(ctx context.Context, connection *remote_connection.Connection) (*empty.Empty, error) {\n\tlogrus.Infof(\"ProxyNSMD: Proxy closing connection: %v\", *connection)\n\n\tdestNsmName := connection.DestinationNetworkServiceManagerName\n\tdNsmName, dNsmAddress, err := utils.ParseNsmURL(destNsmName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ProxyNSMD: Failed to extract destination nsm address\")\n\t}\n\n\tdNsm := &registry.NetworkServiceManager{\n\t\tName: dNsmName,\n\t\tUrl:  dNsmAddress,\n\t}\n\n\tclient, conn, err := srv.serviceRegistry.RemoteNetworkServiceClient(ctx, dNsm)\n\tif err != nil {\n\t\tlogrus.Errorf(\"ProxyNSMD: Failed to create NSE Client. %v\", err)\n\t\treturn nil, err\n\t}\n\tdefer func() {\n\t\tif err := conn.Close(); err != nil {\n\t\t\tlogrus.Errorf(\"ProxyNSMD: Failed to close NSE Client. %v\", err)\n\t\t}\n\t}()\n\n\treturn client.Close(ctx, connection)\n}\n\nfunc createClusterInfoClient(ctx context.Context, address string) (clusterinfo.ClusterInfoClient, *grpc.ClientConn, error) {\n\terr := tools.WaitForPortAvailable(ctx, \"tcp\", address, 100*time.Millisecond)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tconn, err := tools.DialContextTCP(ctx, address)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tclient := clusterinfo.NewClusterInfoClient(conn)\n\treturn client, conn, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package php\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\nconst shortPHPBegin = \"<?\"\nconst longPHPBegin = \"<?php\"\nconst phpEnd = \"?>\"\n\nconst eof = -1\n\n\/\/ lexHTML consumes and emits an html item until it\n\/\/ finds a php begin\nfunc lexHTML(l *lexer) stateFn {\n\tfor {\n\t\tif strings.HasPrefix(l.input[l.pos:], shortPHPBegin) {\n\t\t\tif l.pos > l.start {\n\t\t\t\tl.emit(itemHTML)\n\t\t\t}\n\t\t\treturn lexPHPBegin\n\t\t}\n\t\tif l.next() == eof {\n\t\t\tbreak\n\t\t}\n\t}\n\tif l.pos > l.start {\n\t\tl.emit(itemHTML)\n\t}\n\tl.emit(itemEOF)\n\treturn nil\n}\n\nfunc lexPHPBegin(l *lexer) stateFn {\n\tif strings.HasPrefix(l.input[l.pos:], longPHPBegin) {\n\t\tl.pos += len(longPHPBegin)\n\t}\n\tif strings.HasPrefix(l.input[l.pos:], shortPHPBegin) {\n\t\tl.pos += len(shortPHPBegin)\n\t}\n\tl.emit(itemPHPBegin)\n\treturn lexPHP\n}\n\nfunc lexPHP(l *lexer) stateFn {\n\tl.skipSpace()\n\n\tif r := l.peek(); unicode.IsDigit(r) {\n\t\treturn lexNumberLiteral\n\t} else if r == '.' {\n\t\tl.next()\n\t\tif unicode.IsDigit(l.peek()) {\n\t\t\tl.backup()\n\t\t\treturn lexNumberLiteral\n\t\t}\n\t\tl.backup()\n\t}\n\n\tif strings.HasPrefix(l.input[l.pos:], \"?>\") {\n\t\treturn lexPHPEnd\n\t}\n\n\tif strings.HasPrefix(l.input[l.pos:], \"\/\/\") {\n\t\treturn lexLineComment\n\t}\n\n\tif strings.HasPrefix(l.input[l.pos:], \"\/*\") {\n\t\treturn lexBlockComment\n\t}\n\n\tfor _, token := range tokenList {\n\t\titem := tokenMap[token]\n\t\tif strings.HasPrefix(l.input[l.pos:], token) {\n\t\t\tl.pos += len(token)\n\t\t\tif isKeyword(item) && l.accept(alphabet+underscore+digits) {\n\t\t\t\tl.backup()\n\t\t\t\tl.pos -= len(token)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl.emit(item)\n\t\t\treturn lexPHP\n\t\t}\n\t}\n\n\tif strings.HasPrefix(l.input[l.pos:], \"$\") {\n\t\treturn lexIdentifier\n\t}\n\n\tif l.next() == eof {\n\t\tl.emit(itemEOF)\n\t\treturn nil\n\t}\n\tl.backup()\n\n\tif l.peek() == '\\'' {\n\t\treturn lexSingleQuotedStringLiteral\n\t}\n\n\tif l.peek() == '\"' {\n\t\treturn lexDoubleQuotedStringLiteral\n\t}\n\n\tl.acceptRun(alphabet + underscore + digits + \"\\\\\")\n\tl.emit(itemNonVariableIdentifier)\n\treturn lexPHP\n}\n\nfunc lexNumberLiteral(l *lexer) stateFn {\n\t\/\/ is negative?\n\tl.accept(\"-\")\n\tl.acceptRun(digits)\n\n\t\/\/ is decimal?\n\tif l.accept(\".\") {\n\t\tl.acceptRun(digits)\n\t}\n\n\tl.emit(itemNumberLiteral)\n\treturn lexPHP\n}\n\nfunc lexSingleQuotedStringLiteral(l *lexer) stateFn {\n\tl.next()\n\tfor {\n\t\tswitch l.next() {\n\t\tcase '\\\\':\n\t\t\tl.next()\n\t\t\tcontinue\n\t\tcase '\\'':\n\t\t\tl.emit(itemStringLiteral)\n\t\t\treturn lexPHP\n\t\t}\n\t}\n}\n\nfunc lexDoubleQuotedStringLiteral(l *lexer) stateFn {\n\tl.next()\n\tfor {\n\t\tswitch l.next() {\n\t\tcase '\\\\':\n\t\t\tl.next()\n\t\t\tcontinue\n\t\tcase '\"':\n\t\t\tl.emit(itemStringLiteral)\n\t\t\treturn lexPHP\n\t\t}\n\t}\n}\n\nfunc lexIf(l *lexer) stateFn {\n\treturn l.errorf(\"if is not supported\")\n}\n\nfunc lexCondition(l *lexer) stateFn {\n\t\/\/ this could be useful in the condition of a while, do-while, for terminator, if, and if-else block\n\t\/\/ what state should it return?\n\t\/\/ in all cases except do-while, after this is done, a block-begin is the correct state\n\n\t\/\/ how can this take advantage of the lexPHP function?\n\treturn lexPHP\n}\n\nconst alphabet = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst digits = \"0123456789\"\nconst underscore = \"_\"\n\nfunc lexIdentifier(l *lexer) stateFn {\n\tl.accept(\"$\")\n\tl.accept(underscore + alphabet)\n\tl.acceptRun(underscore + alphabet + digits)\n\tl.emit(itemIdentifier)\n\treturn lexPHP\n}\n\nfunc lexFunctionArgs(l *lexer) stateFn {\n\tl.skipSpace()\n\tswitch r := l.next(); {\n\tcase r == '(':\n\t\tl.emit(itemOpenParen)\n\t\tif l.peek() == ')' {\n\t\t\treturn lexFunctionArgs\n\t\t}\n\t\treturn lexFunctionArg\n\tcase r == ')':\n\t\tl.emit(itemCloseParen)\n\t\treturn lexPHP\n\tcase r == ',':\n\t\tl.emit(itemArgumentSeparator)\n\t\treturn lexFunctionArg\n\tdefault:\n\t\treturn l.errorf(\"invalid function argument separator: '%s'\", string(r))\n\t}\n}\n\nfunc lexFunctionArg(l *lexer) stateFn {\n\tl.skipSpace()\n\tif l.peek() != '$' {\n\t\tl.accept(underscore + alphabet)\n\t\tl.acceptRun(underscore + alphabet + digits)\n\t\tl.emit(itemTypeHint)\n\t}\n\tl.skipSpace()\n\tl.next()\n\tl.accept(underscore + alphabet)\n\tl.acceptRun(underscore + alphabet + digits)\n\tl.emit(itemArgumentName)\n\treturn lexFunctionArgs\n}\n\n\/\/ lexBlockBegin lexes the beginning of a code block delimited by '{'.\n\/\/ This state occurs after the declaration of control flow structures.\nfunc lexBlockBegin(l *lexer) stateFn {\n\tfor isSpace(l.peek()) {\n\t\tl.next()\n\t}\n\tif l.next() == '{' {\n\t\tl.emit(itemBlockBegin)\n\t} else {\n\t\tl.errorf(\"expecting { to begin a new block\")\n\t}\n\treturn lexPHP\n}\n\n\/\/ lexBlockEnd lexes the end of a code block delimited by '}'.\nfunc lexBlockEnd(l *lexer) stateFn {\n\tl.pos += 1\n\tl.emit(itemBlockEnd)\n\treturn lexPHP\n}\n\n\/\/ lexPHPEnd lexes the end of a PHP section returning the context to HTML\nfunc lexPHPEnd(l *lexer) stateFn {\n\tl.pos += len(phpEnd)\n\tl.emit(itemPHPEnd)\n\treturn lexHTML\n}\n\nfunc lexLineComment(l *lexer) stateFn {\n\tl.pos += strings.Index(l.input[l.pos:], \"\\n\") + 1\n\tl.ignore()\n\treturn lexPHP\n}\n\nfunc lexBlockComment(l *lexer) stateFn {\n\tl.pos += strings.Index(l.input[l.pos:], \"*\/\") + 2\n\tl.ignore()\n\treturn lexPHP\n}\n<commit_msg>Removed dead code<commit_after>package php\n\nimport (\n\t\"strings\"\n\t\"unicode\"\n)\n\nconst shortPHPBegin = \"<?\"\nconst longPHPBegin = \"<?php\"\nconst phpEnd = \"?>\"\n\nconst eof = -1\n\n\/\/ lexHTML consumes and emits an html item until it\n\/\/ finds a php begin\nfunc lexHTML(l *lexer) stateFn {\n\tfor {\n\t\tif strings.HasPrefix(l.input[l.pos:], shortPHPBegin) {\n\t\t\tif l.pos > l.start {\n\t\t\t\tl.emit(itemHTML)\n\t\t\t}\n\t\t\treturn lexPHPBegin\n\t\t}\n\t\tif l.next() == eof {\n\t\t\tbreak\n\t\t}\n\t}\n\tif l.pos > l.start {\n\t\tl.emit(itemHTML)\n\t}\n\tl.emit(itemEOF)\n\treturn nil\n}\n\nfunc lexPHPBegin(l *lexer) stateFn {\n\tif strings.HasPrefix(l.input[l.pos:], longPHPBegin) {\n\t\tl.pos += len(longPHPBegin)\n\t}\n\tif strings.HasPrefix(l.input[l.pos:], shortPHPBegin) {\n\t\tl.pos += len(shortPHPBegin)\n\t}\n\tl.emit(itemPHPBegin)\n\treturn lexPHP\n}\n\nfunc lexPHP(l *lexer) stateFn {\n\tl.skipSpace()\n\n\tif r := l.peek(); unicode.IsDigit(r) {\n\t\treturn lexNumberLiteral\n\t} else if r == '.' {\n\t\tl.next()\n\t\tif unicode.IsDigit(l.peek()) {\n\t\t\tl.backup()\n\t\t\treturn lexNumberLiteral\n\t\t}\n\t\tl.backup()\n\t}\n\n\tif strings.HasPrefix(l.input[l.pos:], \"?>\") {\n\t\treturn lexPHPEnd\n\t}\n\n\tif strings.HasPrefix(l.input[l.pos:], \"\/\/\") {\n\t\treturn lexLineComment\n\t}\n\n\tif strings.HasPrefix(l.input[l.pos:], \"\/*\") {\n\t\treturn lexBlockComment\n\t}\n\n\tfor _, token := range tokenList {\n\t\titem := tokenMap[token]\n\t\tif strings.HasPrefix(l.input[l.pos:], token) {\n\t\t\tl.pos += len(token)\n\t\t\tif isKeyword(item) && l.accept(alphabet+underscore+digits) {\n\t\t\t\tl.backup()\n\t\t\t\tl.pos -= len(token)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl.emit(item)\n\t\t\treturn lexPHP\n\t\t}\n\t}\n\n\tif strings.HasPrefix(l.input[l.pos:], \"$\") {\n\t\treturn lexIdentifier\n\t}\n\n\tif l.next() == eof {\n\t\tl.emit(itemEOF)\n\t\treturn nil\n\t}\n\tl.backup()\n\n\tif l.peek() == '\\'' {\n\t\treturn lexSingleQuotedStringLiteral\n\t}\n\n\tif l.peek() == '\"' {\n\t\treturn lexDoubleQuotedStringLiteral\n\t}\n\n\tl.acceptRun(alphabet + underscore + digits + \"\\\\\")\n\tl.emit(itemNonVariableIdentifier)\n\treturn lexPHP\n}\n\nfunc lexNumberLiteral(l *lexer) stateFn {\n\t\/\/ is decimal?\n\tl.acceptRun(digits)\n\tif l.accept(\".\") {\n\t\tl.acceptRun(digits)\n\t}\n\n\tl.emit(itemNumberLiteral)\n\treturn lexPHP\n}\n\nfunc lexSingleQuotedStringLiteral(l *lexer) stateFn {\n\tl.next()\n\tfor {\n\t\tswitch l.next() {\n\t\tcase '\\\\':\n\t\t\tl.next()\n\t\t\tcontinue\n\t\tcase '\\'':\n\t\t\tl.emit(itemStringLiteral)\n\t\t\treturn lexPHP\n\t\t}\n\t}\n}\n\nfunc lexDoubleQuotedStringLiteral(l *lexer) stateFn {\n\tl.next()\n\tfor {\n\t\tswitch l.next() {\n\t\tcase '\\\\':\n\t\t\tl.next()\n\t\t\tcontinue\n\t\tcase '\"':\n\t\t\tl.emit(itemStringLiteral)\n\t\t\treturn lexPHP\n\t\t}\n\t}\n}\n\nfunc lexIf(l *lexer) stateFn {\n\treturn l.errorf(\"if is not supported\")\n}\n\nfunc lexCondition(l *lexer) stateFn {\n\t\/\/ this could be useful in the condition of a while, do-while, for terminator, if, and if-else block\n\t\/\/ what state should it return?\n\t\/\/ in all cases except do-while, after this is done, a block-begin is the correct state\n\n\t\/\/ how can this take advantage of the lexPHP function?\n\treturn lexPHP\n}\n\nconst alphabet = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst digits = \"0123456789\"\nconst underscore = \"_\"\n\nfunc lexIdentifier(l *lexer) stateFn {\n\tl.accept(\"$\")\n\tl.accept(underscore + alphabet)\n\tl.acceptRun(underscore + alphabet + digits)\n\tl.emit(itemIdentifier)\n\treturn lexPHP\n}\n\n\/\/ lexBlockBegin lexes the beginning of a code block delimited by '{'.\n\/\/ This state occurs after the declaration of control flow structures.\nfunc lexBlockBegin(l *lexer) stateFn {\n\tfor isSpace(l.peek()) {\n\t\tl.next()\n\t}\n\tif l.next() == '{' {\n\t\tl.emit(itemBlockBegin)\n\t} else {\n\t\tl.errorf(\"expecting { to begin a new block\")\n\t}\n\treturn lexPHP\n}\n\n\/\/ lexBlockEnd lexes the end of a code block delimited by '}'.\nfunc lexBlockEnd(l *lexer) stateFn {\n\tl.pos += 1\n\tl.emit(itemBlockEnd)\n\treturn lexPHP\n}\n\n\/\/ lexPHPEnd lexes the end of a PHP section returning the context to HTML\nfunc lexPHPEnd(l *lexer) stateFn {\n\tl.pos += len(phpEnd)\n\tl.emit(itemPHPEnd)\n\treturn lexHTML\n}\n\nfunc lexLineComment(l *lexer) stateFn {\n\tl.pos += strings.Index(l.input[l.pos:], \"\\n\") + 1\n\tl.ignore()\n\treturn lexPHP\n}\n\nfunc lexBlockComment(l *lexer) stateFn {\n\tl.pos += strings.Index(l.input[l.pos:], \"*\/\") + 2\n\tl.ignore()\n\treturn lexPHP\n}\n<|endoftext|>"}
{"text":"<commit_before>package lfchan\n\nimport (\n\t\"runtime\"\n\t\"sync\/atomic\"\n)\n\ntype innerChan struct {\n\tq       []AtomicValue\n\tsendIdx uint32\n\trecvIdx uint32\n\tlen     int32\n\tdie     int32\n}\n\n\/\/ Chan is a lock free channel that supports concurrent channel operations.\ntype Chan struct {\n\t*innerChan\n}\n\n\/\/ New returns a new channel with the buffer set to 1\nfunc New() Chan {\n\treturn NewSize(1)\n}\n\n\/\/ NewSize creates a buffered channel, with minimum length of 1\nfunc NewSize(sz int) Chan {\n\tif sz < 1 {\n\t\tpanic(\"sz < 1\")\n\t}\n\treturn Chan{&innerChan{\n\t\tq:       make([]AtomicValue, sz),\n\t\tsendIdx: ^uint32(0),\n\t\trecvIdx: ^uint32(0),\n\t}}\n}\n\n\/\/ Send adds v to the buffer of the channel and returns true, if the channel is closed it returns false\nfunc (ch Chan) Send(v interface{}, block bool) bool {\n\tif !block && ch.Len() == ch.Cap() {\n\t\treturn false\n\t}\n\tncpu, ln, cnt := uint32(runtime.NumCPU()), uint32(len(ch.q)), uint32(0)\n\tfor !ch.Closed() {\n\n\t\ti := atomic.AddUint32(&ch.sendIdx, 1)\n\t\tif ch.q[i%ln].CompareAndSwap(nil, v) {\n\t\t\tatomic.AddInt32(&ch.len, 1)\n\t\t\treturn true\n\t\t}\n\t\tif block {\n\t\t\tif i%(ncpu*100) == 0 {\n\t\t\t\tfor i := uint32(0); i < ncpu; i++ {\n\t\t\t\t\truntime.Gosched()\n\t\t\t\t}\n\t\t\t}\n\t\t} else if cnt++; cnt == ln {\n\t\t\tbreak\n\t\t}\n\t\truntime.Gosched()\n\t}\n\treturn false\n}\n\n\/\/ Recv blocks until a value is available and returns v, true, or if the channel is closed and\n\/\/ the buffer is empty, it will return nil, false\nfunc (ch Chan) Recv(block bool) (interface{}, bool) {\n\tif !block && ch.Len() == 0 { \/\/ fast path\n\t\treturn nil, false\n\t}\n\tncpu, ln, cnt := uint32(runtime.NumCPU()), uint32(len(ch.q)), uint32(0)\n\tfor !ch.Closed() || ch.Len() > 0 {\n\t\ti := atomic.AddUint32(&ch.recvIdx, 1)\n\t\tif v := ch.q[i%ln].Swap(nil); v != nil {\n\t\t\tatomic.AddInt32(&ch.len, -1)\n\t\t\treturn v, true\n\t\t}\n\t\tif block {\n\t\t\tif i%(ncpu*100) == 0 {\n\t\t\t\tfor i := uint32(0); i < ncpu; i++ {\n\t\t\t\t\truntime.Gosched()\n\t\t\t\t}\n\t\t\t}\n\t\t} else if cnt++; cnt == ln {\n\t\t\tbreak\n\t\t}\n\t\truntime.Gosched()\n\t}\n\treturn nil, false\n}\n\n\/\/ Close marks the channel as closed\nfunc (ch Chan) Close() { atomic.StoreInt32(&ch.die, 1) }\n\n\/\/ Closed returns true if the channel have been closed\nfunc (ch Chan) Closed() bool { return atomic.LoadInt32(&ch.die) == 1 }\n\n\/\/ Cap returns the size of the internal queue\nfunc (ch Chan) Cap() int { return len(ch.q) }\n\n\/\/ Len returns the number of elements queued\nfunc (ch Chan) Len() int { return int(atomic.LoadInt32(&ch.len)) }\n\n\/\/ SelectSend sends v to the first available channel, if block is true, it blocks until a channel a accepts the value.\n\/\/ returns false if all channels were full and block is false.\nfunc SelectSend(block bool, v interface{}, chans ...Chan) bool {\n\tfor {\n\t\tfor i := range chans {\n\t\t\tif ok := chans[i].Send(v, false); ok {\n\t\t\t\treturn ok\n\t\t\t}\n\t\t}\n\t\tif !block {\n\t\t\treturn false\n\t\t}\n\t\truntime.Gosched()\n\t}\n}\n\n\/\/ SelectRecv returns the first available value from chans, if block is true, it blocks until a value is available.\n\/\/ returns nil, false if all channels were empty and block is false.\nfunc SelectRecv(block bool, chans ...Chan) (interface{}, bool) {\n\tfor {\n\t\tfor i := range chans {\n\t\t\tif v, ok := chans[i].Recv(false); ok {\n\t\t\t\treturn v, ok\n\t\t\t}\n\t\t}\n\t\tif !block {\n\t\t\treturn nil, false\n\t\t}\n\t\truntime.Gosched()\n\t}\n}\n<commit_msg>Send\/RecvOnly impl<commit_after>package lfchan\n\nimport (\n\t\"runtime\"\n\t\"sync\/atomic\"\n)\n\ntype innerChan struct {\n\tq       []AtomicValue\n\tsendIdx uint32\n\trecvIdx uint32\n\tlen     int32\n\tdie     int32\n}\n\n\/\/ Chan is a lock free channel that supports concurrent channel operations.\ntype Chan struct {\n\t*innerChan\n}\n\n\/\/ New returns a new channel with the buffer set to 1\nfunc New() Chan {\n\treturn NewSize(1)\n}\n\n\/\/ NewSize creates a buffered channel, with minimum length of 1\nfunc NewSize(sz int) Chan {\n\tif sz < 1 {\n\t\tpanic(\"sz < 1\")\n\t}\n\treturn Chan{&innerChan{\n\t\tq:       make([]AtomicValue, sz),\n\t\tsendIdx: ^uint32(0),\n\t\trecvIdx: ^uint32(0),\n\t}}\n}\n\n\/\/ Send adds v to the buffer of the channel and returns true, if the channel is closed it returns false\nfunc (ch Chan) Send(v interface{}, block bool) bool {\n\tif !block && ch.Len() == ch.Cap() {\n\t\treturn false\n\t}\n\tncpu, ln, cnt := uint32(runtime.NumCPU()), uint32(len(ch.q)), uint32(0)\n\tfor !ch.Closed() {\n\n\t\ti := atomic.AddUint32(&ch.sendIdx, 1)\n\t\tif ch.q[i%ln].CompareAndSwap(nil, v) {\n\t\t\tatomic.AddInt32(&ch.len, 1)\n\t\t\treturn true\n\t\t}\n\t\tif block {\n\t\t\tif i%(ncpu*100) == 0 {\n\t\t\t\tfor i := uint32(0); i < ncpu; i++ {\n\t\t\t\t\truntime.Gosched()\n\t\t\t\t}\n\t\t\t}\n\t\t} else if cnt++; cnt == ln {\n\t\t\tbreak\n\t\t}\n\t\truntime.Gosched()\n\t}\n\treturn false\n}\n\n\/\/ Recv blocks until a value is available and returns v, true, or if the channel is closed and\n\/\/ the buffer is empty, it will return nil, false\nfunc (ch Chan) Recv(block bool) (interface{}, bool) {\n\tif !block && ch.Len() == 0 { \/\/ fast path\n\t\treturn nil, false\n\t}\n\tncpu, ln, cnt := uint32(runtime.NumCPU()), uint32(len(ch.q)), uint32(0)\n\tfor !ch.Closed() || ch.Len() > 0 {\n\t\ti := atomic.AddUint32(&ch.recvIdx, 1)\n\t\tif v := ch.q[i%ln].Swap(nil); v != nil {\n\t\t\tatomic.AddInt32(&ch.len, -1)\n\t\t\treturn v, true\n\t\t}\n\t\tif block {\n\t\t\tif i%(ncpu*100) == 0 {\n\t\t\t\tfor i := uint32(0); i < ncpu; i++ {\n\t\t\t\t\truntime.Gosched()\n\t\t\t\t}\n\t\t\t}\n\t\t} else if cnt++; cnt == ln {\n\t\t\tbreak\n\t\t}\n\t\truntime.Gosched()\n\t}\n\treturn nil, false\n}\n\n\/\/ RecvOnly returns a receive-only channel.\nfunc (ch Chan) RecvOnly() RecvOnly { return RecvOnly{ch} }\n\n\/\/ RecvOnly returns a send-only channel.\nfunc (ch Chan) SendOnly() SendOnly { return SendOnly{ch} }\n\n\/\/ Close marks the channel as closed\nfunc (ch Chan) Close() { atomic.StoreInt32(&ch.die, 1) }\n\n\/\/ Closed returns true if the channel have been closed\nfunc (ch Chan) Closed() bool { return atomic.LoadInt32(&ch.die) == 1 }\n\n\/\/ Cap returns the size of the internal queue\nfunc (ch Chan) Cap() int { return len(ch.q) }\n\n\/\/ Len returns the number of elements queued\nfunc (ch Chan) Len() int { return int(atomic.LoadInt32(&ch.len)) }\n\n\/\/ SelectSend sends v to the first available channel, if block is true, it blocks until a channel a accepts the value.\n\/\/ returns false if all channels were full and block is false.\nfunc SelectSend(block bool, v interface{}, chans ...Chan) bool {\n\tfor {\n\t\tfor i := range chans {\n\t\t\tif ok := chans[i].Send(v, false); ok {\n\t\t\t\treturn ok\n\t\t\t}\n\t\t}\n\t\tif !block {\n\t\t\treturn false\n\t\t}\n\t\truntime.Gosched()\n\t}\n}\n\n\/\/ SelectRecv returns the first available value from chans, if block is true, it blocks until a value is available.\n\/\/ returns nil, false if all channels were empty and block is false.\nfunc SelectRecv(block bool, chans ...Chan) (interface{}, bool) {\n\tfor {\n\t\tfor i := range chans {\n\t\t\tif v, ok := chans[i].Recv(false); ok {\n\t\t\t\treturn v, ok\n\t\t\t}\n\t\t}\n\t\tif !block {\n\t\t\treturn nil, false\n\t\t}\n\t\truntime.Gosched()\n\t}\n}\n\n\/\/ RecvOnly is a channel only has receive operations.\ntype RecvOnly struct{ c Chan }\n\n\/\/ Recv\nfunc (ro RecvOnly) Recv(block bool) (interface{}, bool) { return ro.c.Recv(block) }\n\n\/\/ SebdOnly is a channel only has send operations.\ntype SendOnly struct{ c Chan }\n\n\/\/ Send\nfunc (so SendOnly) Send(v interface{}, block bool) bool { return so.c.Send(v, block) }\n<|endoftext|>"}
{"text":"<commit_before>package cobertura\n\nimport (\n\t\"encoding\/xml\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codeclimate\/test-reporter\/env\"\n\t\"github.com\/codeclimate\/test-reporter\/formatters\"\n\t\"github.com\/pkg\/errors\"\n)\n\nvar searchPaths = []string{\"cobertura.xml\", \"cobertura.ser\"}\n\ntype Formatter struct {\n\tPath string\n}\n\nfunc (f *Formatter) Search(paths ...string) (string, error) {\n\tpaths = append(paths, searchPaths...)\n\tfor _, p := range paths {\n\t\tlogrus.Debugf(\"checking search path %s for cobertura formatter\", p)\n\t\tif _, err := os.Stat(p); err == nil {\n\t\t\tf.Path = p\n\t\t\treturn p, nil\n\t\t}\n\t}\n\n\treturn \"\", errors.WithStack(errors.Errorf(\"could not find any files in search paths for cobertura. search paths were: %s\", strings.Join(paths, \", \")))\n}\n\nfunc (r Formatter) Format() (formatters.Report, error) {\n\trep, err := formatters.NewReport()\n\tif err != nil {\n\t\treturn rep, err\n\t}\n\n\tfx, err := os.Open(r.Path)\n\tif err != nil {\n\t\treturn rep, errors.WithStack(err)\n\t}\n\n\tcoberturaFile := &xmlFile{}\n\terr = xml.NewDecoder(fx).Decode(coberturaFile)\n\n\tif err != nil {\n\t\treturn rep, errors.WithStack(err)\n\t}\n\n\tgitHead, _ := env.GetHead()\n\tfor _, pp := range coberturaFile.Packages {\n\t\tmergedClasses := make(map[string]*xmlClass)\n\t\t\/\/ merge Classes by filename\n\t\tfor i, clss := range pp.Classes {\n\t\t\tfilename := clss.FileName\n\t\t\tif _, ok := mergedClasses[filename]; ok {\n\t\t\t\t\/\/ Appends lines for mergedClasses with the same filename\n\t\t\t\tlines := append(mergedClasses[filename].Lines, clss.Lines...)\n\t\t\t\tmergedClasses[filename].Lines = lines\n\t\t\t} else {\n\t\t\t\tmergedClasses[filename] = &pp.Classes[i]\n\t\t\t}\n\t\t}\n\n\t\tfor _, pf := range mergedClasses {\n\t\t\tnum := 1\n\t\t\tfileName := coberturaFile.getFullFilePath(pf.FileName)\n\t\t\tlogrus.Debugf(\"creating test file report for %s\", fileName)\n\t\t\tsf, err := formatters.NewSourceFile(fileName, gitHead)\n\t\t\tif err != nil {\n\t\t\t\treturn rep, errors.WithStack(err)\n\t\t\t}\n\t\t\tsort.Sort(ByLineNum(pf.Lines))\n\t\t\tfor _, l := range pf.Lines {\n\t\t\t\tif l.Num > 0 {\n\t\t\t\t\tfor num < l.Num {\n\t\t\t\t\t\tsf.Coverage = append(sf.Coverage, formatters.NullInt{})\n\t\t\t\t\t\tnum++\n\t\t\t\t\t}\n\t\t\t\t\tif l.Num <= len(sf.Coverage) {\n\t\t\t\t\t\thits := sf.Coverage[l.Num-1].Int + l.Hits\n\t\t\t\t\t\tsf.Coverage[l.Num-1] = formatters.NewNullInt(hits)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tni := formatters.NewNullInt(l.Hits)\n\t\t\t\t\t\tsf.Coverage = append(sf.Coverage, ni)\n\t\t\t\t\t\tnum++\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlogrus.Warnf(\"Invalid line number %d in file %s\", l.Num, fileName)\n\t\t\t\t}\n\t\t\t}\n\t\t\terr = rep.AddSourceFile(sf)\n\t\t\tif err != nil {\n\t\t\t\treturn rep, errors.WithStack(err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn rep, nil\n}\n<commit_msg>Remove cobertura.ser from Cobertura searchPaths (#365)<commit_after>package cobertura\n\nimport (\n\t\"encoding\/xml\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codeclimate\/test-reporter\/env\"\n\t\"github.com\/codeclimate\/test-reporter\/formatters\"\n\t\"github.com\/pkg\/errors\"\n)\n\nvar searchPaths = []string{\"cobertura.xml\"}\n\ntype Formatter struct {\n\tPath string\n}\n\nfunc (f *Formatter) Search(paths ...string) (string, error) {\n\tpaths = append(paths, searchPaths...)\n\tfor _, p := range paths {\n\t\tlogrus.Debugf(\"checking search path %s for cobertura formatter\", p)\n\t\tif _, err := os.Stat(p); err == nil {\n\t\t\tf.Path = p\n\t\t\treturn p, nil\n\t\t}\n\t}\n\n\treturn \"\", errors.WithStack(errors.Errorf(\"could not find any files in search paths for cobertura. search paths were: %s\", strings.Join(paths, \", \")))\n}\n\nfunc (r Formatter) Format() (formatters.Report, error) {\n\trep, err := formatters.NewReport()\n\tif err != nil {\n\t\treturn rep, err\n\t}\n\n\tfx, err := os.Open(r.Path)\n\tif err != nil {\n\t\treturn rep, errors.WithStack(err)\n\t}\n\n\tcoberturaFile := &xmlFile{}\n\terr = xml.NewDecoder(fx).Decode(coberturaFile)\n\n\tif err != nil {\n\t\treturn rep, errors.WithStack(err)\n\t}\n\n\tgitHead, _ := env.GetHead()\n\tfor _, pp := range coberturaFile.Packages {\n\t\tmergedClasses := make(map[string]*xmlClass)\n\t\t\/\/ merge Classes by filename\n\t\tfor i, clss := range pp.Classes {\n\t\t\tfilename := clss.FileName\n\t\t\tif _, ok := mergedClasses[filename]; ok {\n\t\t\t\t\/\/ Appends lines for mergedClasses with the same filename\n\t\t\t\tlines := append(mergedClasses[filename].Lines, clss.Lines...)\n\t\t\t\tmergedClasses[filename].Lines = lines\n\t\t\t} else {\n\t\t\t\tmergedClasses[filename] = &pp.Classes[i]\n\t\t\t}\n\t\t}\n\n\t\tfor _, pf := range mergedClasses {\n\t\t\tnum := 1\n\t\t\tfileName := coberturaFile.getFullFilePath(pf.FileName)\n\t\t\tlogrus.Debugf(\"creating test file report for %s\", fileName)\n\t\t\tsf, err := formatters.NewSourceFile(fileName, gitHead)\n\t\t\tif err != nil {\n\t\t\t\treturn rep, errors.WithStack(err)\n\t\t\t}\n\t\t\tsort.Sort(ByLineNum(pf.Lines))\n\t\t\tfor _, l := range pf.Lines {\n\t\t\t\tif l.Num > 0 {\n\t\t\t\t\tfor num < l.Num {\n\t\t\t\t\t\tsf.Coverage = append(sf.Coverage, formatters.NullInt{})\n\t\t\t\t\t\tnum++\n\t\t\t\t\t}\n\t\t\t\t\tif l.Num <= len(sf.Coverage) {\n\t\t\t\t\t\thits := sf.Coverage[l.Num-1].Int + l.Hits\n\t\t\t\t\t\tsf.Coverage[l.Num-1] = formatters.NewNullInt(hits)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tni := formatters.NewNullInt(l.Hits)\n\t\t\t\t\t\tsf.Coverage = append(sf.Coverage, ni)\n\t\t\t\t\t\tnum++\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlogrus.Warnf(\"Invalid line number %d in file %s\", l.Num, fileName)\n\t\t\t\t}\n\t\t\t}\n\t\t\terr = rep.AddSourceFile(sf)\n\t\t\tif err != nil {\n\t\t\t\treturn rep, errors.WithStack(err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn rep, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package expr\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/StackExchange\/bosun\/_third_party\/github.com\/StackExchange\/scollector\/opentsdb\"\n)\n\nfunc TestExprSimple(t *testing.T) {\n\tvar exprTests = []struct {\n\t\tinput  string\n\t\toutput Scalar\n\t}{\n\t\t{\"!1\", 0},\n\t\t{\"-2\", -2},\n\t\t{\"1.444-010+2*3e2-4\/5+0xff\", 847.644},\n\t\t{\"1>2\", 0},\n\t\t{\"3>2\", 1},\n\t\t{\"1==1\", 1},\n\t\t{\"1==2\", 0},\n\t\t{\"1!=01\", 0},\n\t\t{\"1!=2\", 1},\n\t\t{\"1<2\", 1},\n\t\t{\"2<1\", 0},\n\t\t{\"1||0\", 1},\n\t\t{\"0||0\", 0},\n\t\t{\"1&&0\", 0},\n\t\t{\"1&&2\", 1},\n\t\t{\"1<=0\", 0},\n\t\t{\"1<=1\", 1},\n\t\t{\"1<=2\", 1},\n\t\t{\"1>=0\", 1},\n\t\t{\"1>=1\", 1},\n\t\t{\"1>=2\", 0},\n\t\t{\"-1 > 0\", 0},\n\t\t{\"-1 < 0\", 1},\n\t}\n\n\tfor _, et := range exprTests {\n\t\te, err := New(et.input)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tbreak\n\t\t}\n\t\tr, _, err := e.Execute(opentsdb.Host(\"\"), nil, time.Now(), 0, false, nil, nil)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tbreak\n\t\t} else if len(r.Results) != 1 {\n\t\t\tt.Error(\"bad r len\", len(r.Results))\n\t\t\tbreak\n\t\t} else if len(r.Results[0].Group) != 0 {\n\t\t\tt.Error(\"bad group len\", r.Results[0].Group)\n\t\t\tbreak\n\t\t} else if r.Results[0].Value != et.output {\n\t\t\tt.Errorf(\"expected %v, got %v: %v\\nast: %v\", et.output, r.Results[0].Value, et.input, e)\n\t\t}\n\t}\n}\n\nfunc TestExprParse(t *testing.T) {\n\tvar exprTests = []struct {\n\t\tinput string\n\t\tvalid bool\n\t}{\n\t\t{`avg(q(\"test\", \"1m\", 1))`, false},\n\t}\n\n\tfor _, et := range exprTests {\n\t\t_, err := New(et.input)\n\t\tif et.valid && err != nil {\n\t\t\tt.Error(err)\n\t\t} else if !et.valid && err == nil {\n\t\t\tt.Errorf(\"expected invalid, but no error: %v\", et.input)\n\t\t}\n\t}\n}\n\n\/*\nconst TSDBHost = \"ny-devtsdb04:4242\"\n\nfunc TestExprQuery(t *testing.T) {\n\te, err := New(`forecastlr(q(\"avg:os.cpu{host=ny-lb05}\", \"1m\", \"\"), -10)`)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, _, err = e.Execute(opentsdb.Host(TSDBHost), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n*\/\n<commit_msg>Fix test<commit_after>package expr\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/StackExchange\/bosun\/_third_party\/github.com\/StackExchange\/scollector\/opentsdb\"\n)\n\nfunc TestExprSimple(t *testing.T) {\n\tvar exprTests = []struct {\n\t\tinput  string\n\t\toutput Scalar\n\t}{\n\t\t{\"!1\", 0},\n\t\t{\"-2\", -2},\n\t\t{\"1.444-010+2*3e2-4\/5+0xff\", 847.644},\n\t\t{\"1>2\", 0},\n\t\t{\"3>2\", 1},\n\t\t{\"1==1\", 1},\n\t\t{\"1==2\", 0},\n\t\t{\"1!=01\", 0},\n\t\t{\"1!=2\", 1},\n\t\t{\"1<2\", 1},\n\t\t{\"2<1\", 0},\n\t\t{\"1||0\", 1},\n\t\t{\"0||0\", 0},\n\t\t{\"1&&0\", 0},\n\t\t{\"1&&2\", 1},\n\t\t{\"1<=0\", 0},\n\t\t{\"1<=1\", 1},\n\t\t{\"1<=2\", 1},\n\t\t{\"1>=0\", 1},\n\t\t{\"1>=1\", 1},\n\t\t{\"1>=2\", 0},\n\t\t{\"-1 > 0\", 0},\n\t\t{\"-1 < 0\", 1},\n\t}\n\n\tfor _, et := range exprTests {\n\t\te, err := New(et.input)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tbreak\n\t\t}\n\t\tr, _, err := e.Execute(opentsdb.Host(\"\"), nil, time.Now(), 0, false, nil, nil, nil)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tbreak\n\t\t} else if len(r.Results) != 1 {\n\t\t\tt.Error(\"bad r len\", len(r.Results))\n\t\t\tbreak\n\t\t} else if len(r.Results[0].Group) != 0 {\n\t\t\tt.Error(\"bad group len\", r.Results[0].Group)\n\t\t\tbreak\n\t\t} else if r.Results[0].Value != et.output {\n\t\t\tt.Errorf(\"expected %v, got %v: %v\\nast: %v\", et.output, r.Results[0].Value, et.input, e)\n\t\t}\n\t}\n}\n\nfunc TestExprParse(t *testing.T) {\n\tvar exprTests = []struct {\n\t\tinput string\n\t\tvalid bool\n\t}{\n\t\t{`avg(q(\"test\", \"1m\", 1))`, false},\n\t}\n\n\tfor _, et := range exprTests {\n\t\t_, err := New(et.input)\n\t\tif et.valid && err != nil {\n\t\t\tt.Error(err)\n\t\t} else if !et.valid && err == nil {\n\t\t\tt.Errorf(\"expected invalid, but no error: %v\", et.input)\n\t\t}\n\t}\n}\n\n\/*\nconst TSDBHost = \"ny-devtsdb04:4242\"\n\nfunc TestExprQuery(t *testing.T) {\n\te, err := New(`forecastlr(q(\"avg:os.cpu{host=ny-lb05}\", \"1m\", \"\"), -10)`)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t_, _, err = e.Execute(opentsdb.Host(TSDBHost), nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n*\/\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"gopkg.in\/yaml.v2\"\n\n\t\"io\/ioutil\"\n\n\t\"github.com\/alexgarzao\/ms-gen\/swaggerparser\"\n)\n\ntype (\n\tApi struct {\n\t\tFilename            string\n\t\tOutputDir           string\n\t\tServiceName         string\n\t\tFriendlyServiceName string\n\t\tCommonImportPath    string\n\t\tMethods             []*Method\n\t\tDefinitions         []Definition\n\t\tCurrentMethod       *Method\n\t}\n\n\tDefinition struct {\n\t\tName       string\n\t\tProperties []*Property\n\t}\n)\n\nfunc NewApi(filename string, outputDir string) (api *Api) {\n\tapi = new(Api)\n\tapi.Filename = filename\n\tapi.OutputDir = outputDir\n\n\treturn api\n}\n\nfunc (api *Api) LoadFromSwagger() error {\n\t\/\/ Reading from swagger file.\n\tconfig, err := ioutil.ReadFile(api.Filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := api.parser(config); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (api *Api) parser(text []byte) error {\n\tswagger := new(swaggerparser.Swagger)\n\n\tif err := yaml.Unmarshal(text, swagger); err != nil {\n\t\treturn err\n\t}\n\n\tapi.ServiceName = \"myservice\"\n\tapi.FriendlyServiceName = swagger.Info.Title\n\n\tapi.Methods = api.fillMethods(swagger.Paths)\n\n\tapi.Definitions = api.fillDefinitions(swagger.Definitions)\n\n\tcommonImportPath, err := GetCommonImportPath(api.OutputDir, api.ServiceName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tapi.CommonImportPath = commonImportPath\n\n\treturn nil\n}\n\n\/\/ Fill methods.\nfunc (api *Api) fillMethods(pathDefinitions map[string]*swaggerparser.Path) []*Method {\n\tvar methods []*Method\n\tfor k, v := range pathDefinitions {\n\t\tif v.Get != nil {\n\t\t\tmethods = append(methods, NewMethod(api.ServiceName, k, \"Get\", v.Get))\n\t\t}\n\n\t\tif v.Post != nil {\n\t\t\tmethods = append(methods, NewMethod(api.ServiceName, k, \"Post\", v.Post))\n\t\t}\n\n\t\tif v.Put != nil {\n\t\t\tmethods = append(methods, NewMethod(api.ServiceName, k, \"Put\", v.Put))\n\t\t}\n\t}\n\n\treturn methods\n}\n\n\/\/ Fill definitions.\nfunc (api *Api) fillDefinitions(apiDefinitions map[string]*swaggerparser.JSONSchema) []Definition {\n\tvar definitions []Definition\n\n\tfor apiDefinitionKey, apiDefinitionValue := range apiDefinitions {\n\t\tdefinition := Definition{}\n\t\tdefinition.Name = apiDefinitionKey\n\t\tfor propertyKey, propertyValue := range apiDefinitionValue.Properties {\n\t\t\tproperty := NewProperty(propertyKey, propertyValue)\n\t\t\tdefinition.Properties = append(definition.Properties, property)\n\t\t}\n\t\tdefinitions = append(definitions, definition)\n\t}\n\n\treturn definitions\n}\n<commit_msg>Refactor: Definition class was moved to a new file.<commit_after>package main\n\nimport (\n\t\"gopkg.in\/yaml.v2\"\n\n\t\"io\/ioutil\"\n\n\t\"github.com\/alexgarzao\/ms-gen\/swaggerparser\"\n)\n\ntype Api struct {\n\tFilename            string\n\tOutputDir           string\n\tServiceName         string\n\tFriendlyServiceName string\n\tCommonImportPath    string\n\tMethods             []*Method\n\tDefinitions         []*Definition\n\tCurrentMethod       *Method\n}\n\nfunc NewApi(filename string, outputDir string) (api *Api) {\n\tapi = new(Api)\n\tapi.Filename = filename\n\tapi.OutputDir = outputDir\n\n\treturn api\n}\n\nfunc (api *Api) LoadFromSwagger() error {\n\t\/\/ Reading from swagger file.\n\tconfig, err := ioutil.ReadFile(api.Filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := api.parser(config); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (api *Api) parser(text []byte) error {\n\tswagger := new(swaggerparser.Swagger)\n\n\tif err := yaml.Unmarshal(text, swagger); err != nil {\n\t\treturn err\n\t}\n\n\tapi.ServiceName = \"myservice\"\n\tapi.FriendlyServiceName = swagger.Info.Title\n\n\tapi.Methods = api.fillMethods(swagger.Paths)\n\n\tapi.Definitions = FillDefinitions(swagger.Definitions)\n\n\tcommonImportPath, err := GetCommonImportPath(api.OutputDir, api.ServiceName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tapi.CommonImportPath = commonImportPath\n\n\treturn nil\n}\n\n\/\/ Fill methods.\nfunc (api *Api) fillMethods(pathDefinitions map[string]*swaggerparser.Path) []*Method {\n\tvar methods []*Method\n\tfor k, v := range pathDefinitions {\n\t\tif v.Get != nil {\n\t\t\tmethods = append(methods, NewMethod(api.ServiceName, k, \"Get\", v.Get))\n\t\t}\n\n\t\tif v.Post != nil {\n\t\t\tmethods = append(methods, NewMethod(api.ServiceName, k, \"Post\", v.Post))\n\t\t}\n\n\t\tif v.Put != nil {\n\t\t\tmethods = append(methods, NewMethod(api.ServiceName, k, \"Put\", v.Put))\n\t\t}\n\t}\n\n\treturn methods\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ File: .\/blockfreight\/bft\/crypto\/crypto.go\n\/\/ Summary: Application code for Blockfreight™ | The blockchain of global freight.\n\/\/ License: MIT License\n\/\/ Company: Blockfreight, Inc.\n\/\/ Author: Julian Nunez, Neil Tran, Julian Smith & contributors\n\/\/ Site: https:\/\/blockfreight.com\n\/\/ Support: <support@blockfreight.com>\n\n\/\/ Copyright 2017 Blockfreight, Inc.\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/\/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\/\/ =================================================================================================================================================\n\/\/ =================================================================================================================================================\n\/\/\n\/\/ BBBBBBBBBBBb     lll                                kkk             ffff                         iii                  hhh            ttt\n\/\/ BBBB``````BBBB   lll                                kkk            fff                           ```                  hhh            ttt\n\/\/ BBBB      BBBB   lll      oooooo        ccccccc     kkk    kkkk  fffffff  rrr  rrr    eeeee      iii     gggggg ggg   hhh  hhhhh   tttttttt\n\/\/ BBBBBBBBBBBB     lll    ooo    oooo    ccc    ccc   kkk   kkk    fffffff  rrrrrrrr eee    eeee   iii   gggg   ggggg   hhhh   hhhh  tttttttt\n\/\/ BBBBBBBBBBBBBB   lll   ooo      ooo   ccc           kkkkkkk        fff    rrrr    eeeeeeeeeeeee  iii  gggg      ggg   hhh     hhh    ttt\n\/\/ BBBB       BBB   lll   ooo      ooo   ccc           kkkk kkkk      fff    rrr     eeeeeeeeeeeee  iii   ggg      ggg   hhh     hhh    ttt\n\/\/ BBBB      BBBB   lll   oooo    oooo   cccc    ccc   kkk   kkkk     fff    rrr      eee      eee  iii    ggg    gggg   hhh     hhh    tttt    ....\n\/\/ BBBBBBBBBBBBB    lll     oooooooo       ccccccc     kkk     kkkk   fff    rrr       eeeeeeeee    iii     gggggg ggg   hhh     hhh     ttttt  ....\n\/\/                                                                                                        ggg      ggg\n\/\/   Blockfreight™ | The blockchain of global freight.                                                      ggggggggg\n\/\/\n\/\/ =================================================================================================================================================\n\/\/ =================================================================================================================================================\n\n\/\/ Package crypto provides useful functions to sign BF_TX.\npackage crypto\n\nimport (\n    \/\/ =======================\n    \/\/ Golang Standard library\n    \/\/ =======================\n    \"crypto\/ecdsa\"      \/\/ Implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-3.\n    \"crypto\/elliptic\"   \/\/ Implements several standard elliptic curves over prime fields.\n    \"crypto\/md5\"        \/\/ Implements the MD5 hash algorithm as defined in RFC 1321.\n    \"crypto\/rand\"       \/\/ Implements a cryptographically secure pseudorandom number generator.\n    \"fmt\"               \/\/ Implements formatted I\/O with functions analogous to C's printf and scanf.\n    \"hash\"              \/\/ Provides interfaces for hash functions.\n    \"io\"                \/\/ Provides basic interfaces to I\/O primitives.\n    \"math\/big\"          \/\/ Implements arbitrary-precision arithmetic (big numbers).\n    \"os\"                \/\/ Provides a platform-independent interface to operating system functionality.\n    \"strconv\"           \/\/ Implements conversions to and from string representations of basic data types.\n\n    \/\/ ======================\n    \/\/ Blockfreight™ packages\n    \/\/ ======================\n    \"github.com\/blockfreight\/blockfreight-alpha\/blockfreight\/bft\/bf_tx\" \/\/ Defines the Blockfreight™ Transaction (BF_TX) transaction standard and provides some useful functions to work with the BF_TX.\n)\n\n\/\/  @todo: OP_2 <pubkey1> <pubkey2> <pubkey3> <pubkey4> <pubkey5> OP_3 OP_CHECKMULTISIGVERIFY <pubkey3> OP_CHECKSIG\n\n\/\/ Function Sign_BF_TX has the whole process of signing each BF_TX.\nfunc Sign_BF_TX(bft_tx bf_tx.BF_TX) bf_tx.BF_TX {\n\n    content := bf_tx.BF_TXContent(bft_tx)\n\n    pubkeyCurve := elliptic.P256() \/\/see http:\/\/golang.org\/pkg\/crypto\/elliptic\/#P256\n\n    privatekey := new(ecdsa.PrivateKey)\n    privatekey, err := ecdsa.GenerateKey(pubkeyCurve, rand.Reader) \/\/ this generates a public & private key pair\n\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    pubkey := privatekey.PublicKey\n\n    \/\/ Sign ecdsa style\n    var h hash.Hash\n    h = md5.New()\n    r := big.NewInt(0)\n    s := big.NewInt(0)\n\n    io.WriteString(h, content)\n    signhash := h.Sum(nil)\n\n    r, s, serr := ecdsa.Sign(rand.Reader, privatekey, signhash)\n    if serr != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n\n    signature := r.Bytes()\n    signature = append(signature, s.Bytes()...)\n    \n    sign := \"\"\n    for i, _ := range signature {\n        sign += strconv.Itoa(int(signature[i]))\n    }\n    \n    \/\/ Verification\n    verifystatus := ecdsa.Verify(&pubkey, signhash, r, s)\n    \n    \/\/Set Private Key and Sign to BF_TX\n    bft_tx.PrivateKey = *privatekey\n    bft_tx.Signhash = signhash\n    bft_tx.Signature = sign\n    bft_tx.Signed = verifystatus\n    \n    return bft_tx\n}\n\n\/\/ =================================================\n\/\/ Blockfreight™ | The blockchain of global freight.\n\/\/ =================================================\n\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                    BBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                       BBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBB        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBB        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBB         BBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                     BBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBBB        BBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBBBB       BBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBBB        BBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBB        BBB       BBBBB\n\/\/ BBBBBBB                       BBBB       BBBBB\n\/\/ BBBBBBB                    BBBBBBB       BBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\n\/\/ ==================================================\n\/\/ Blockfreight™ | The blockchain for global freight.\n\/\/ ==================================================\n<commit_msg>Modify assignation of bool attribute when the BF_TX was verified<commit_after>\/\/ File: .\/blockfreight\/bft\/crypto\/crypto.go\n\/\/ Summary: Application code for Blockfreight™ | The blockchain of global freight.\n\/\/ License: MIT License\n\/\/ Company: Blockfreight, Inc.\n\/\/ Author: Julian Nunez, Neil Tran, Julian Smith & contributors\n\/\/ Site: https:\/\/blockfreight.com\n\/\/ Support: <support@blockfreight.com>\n\n\/\/ Copyright 2017 Blockfreight, Inc.\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/\/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\/\/ =================================================================================================================================================\n\/\/ =================================================================================================================================================\n\/\/\n\/\/ BBBBBBBBBBBb     lll                                kkk             ffff                         iii                  hhh            ttt\n\/\/ BBBB``````BBBB   lll                                kkk            fff                           ```                  hhh            ttt\n\/\/ BBBB      BBBB   lll      oooooo        ccccccc     kkk    kkkk  fffffff  rrr  rrr    eeeee      iii     gggggg ggg   hhh  hhhhh   tttttttt\n\/\/ BBBBBBBBBBBB     lll    ooo    oooo    ccc    ccc   kkk   kkk    fffffff  rrrrrrrr eee    eeee   iii   gggg   ggggg   hhhh   hhhh  tttttttt\n\/\/ BBBBBBBBBBBBBB   lll   ooo      ooo   ccc           kkkkkkk        fff    rrrr    eeeeeeeeeeeee  iii  gggg      ggg   hhh     hhh    ttt\n\/\/ BBBB       BBB   lll   ooo      ooo   ccc           kkkk kkkk      fff    rrr     eeeeeeeeeeeee  iii   ggg      ggg   hhh     hhh    ttt\n\/\/ BBBB      BBBB   lll   oooo    oooo   cccc    ccc   kkk   kkkk     fff    rrr      eee      eee  iii    ggg    gggg   hhh     hhh    tttt    ....\n\/\/ BBBBBBBBBBBBB    lll     oooooooo       ccccccc     kkk     kkkk   fff    rrr       eeeeeeeee    iii     gggggg ggg   hhh     hhh     ttttt  ....\n\/\/                                                                                                        ggg      ggg\n\/\/   Blockfreight™ | The blockchain of global freight.                                                      ggggggggg\n\/\/\n\/\/ =================================================================================================================================================\n\/\/ =================================================================================================================================================\n\n\/\/ Package crypto provides useful functions to sign BF_TX.\npackage crypto\n\nimport (\n    \/\/ =======================\n    \/\/ Golang Standard library\n    \/\/ =======================\n    \"crypto\/ecdsa\"      \/\/ Implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-3.\n    \"crypto\/elliptic\"   \/\/ Implements several standard elliptic curves over prime fields.\n    \"crypto\/md5\"        \/\/ Implements the MD5 hash algorithm as defined in RFC 1321.\n    \"crypto\/rand\"       \/\/ Implements a cryptographically secure pseudorandom number generator.\n    \"fmt\"               \/\/ Implements formatted I\/O with functions analogous to C's printf and scanf.\n    \"hash\"              \/\/ Provides interfaces for hash functions.\n    \"io\"                \/\/ Provides basic interfaces to I\/O primitives.\n    \"math\/big\"          \/\/ Implements arbitrary-precision arithmetic (big numbers).\n    \"os\"                \/\/ Provides a platform-independent interface to operating system functionality.\n    \"strconv\"           \/\/ Implements conversions to and from string representations of basic data types.\n\n    \/\/ ======================\n    \/\/ Blockfreight™ packages\n    \/\/ ======================\n    \"github.com\/blockfreight\/blockfreight-alpha\/blockfreight\/bft\/bf_tx\" \/\/ Defines the Blockfreight™ Transaction (BF_TX) transaction standard and provides some useful functions to work with the BF_TX.\n)\n\n\/\/  @todo: OP_2 <pubkey1> <pubkey2> <pubkey3> <pubkey4> <pubkey5> OP_3 OP_CHECKMULTISIGVERIFY <pubkey3> OP_CHECKSIG\n\n\/\/ Function Sign_BF_TX has the whole process of signing each BF_TX.\nfunc Sign_BF_TX(bft_tx bf_tx.BF_TX) bf_tx.BF_TX {\n\n    content := bf_tx.BF_TXContent(bft_tx)\n\n    pubkeyCurve := elliptic.P256() \/\/see http:\/\/golang.org\/pkg\/crypto\/elliptic\/#P256\n\n    privatekey := new(ecdsa.PrivateKey)\n    privatekey, err := ecdsa.GenerateKey(pubkeyCurve, rand.Reader) \/\/ this generates a public & private key pair\n\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    pubkey := privatekey.PublicKey\n\n    \/\/ Sign ecdsa style\n    var h hash.Hash\n    h = md5.New()\n    r := big.NewInt(0)\n    s := big.NewInt(0)\n\n    io.WriteString(h, content)\n    signhash := h.Sum(nil)\n\n    r, s, serr := ecdsa.Sign(rand.Reader, privatekey, signhash)\n    if serr != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n\n    signature := r.Bytes()\n    signature = append(signature, s.Bytes()...)\n    \n    sign := \"\"\n    for i, _ := range signature {\n        sign += strconv.Itoa(int(signature[i]))\n    }\n    \n    \/\/ Verification\n    verifystatus := ecdsa.Verify(&pubkey, signhash, r, s)\n    \n    \/\/Set Private Key and Sign to BF_TX\n    bft_tx.PrivateKey = *privatekey\n    bft_tx.Signhash = signhash\n    bft_tx.Signature = sign\n    bft_tx.Verified = verifystatus\n    \n    return bft_tx\n}\n\n\/\/ =================================================\n\/\/ Blockfreight™ | The blockchain of global freight.\n\/\/ =================================================\n\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                    BBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                       BBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBB        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBB        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBB         BBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                     BBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBBB        BBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBBBB       BBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBBB        BBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBB        BBB       BBBBB\n\/\/ BBBBBBB                       BBBB       BBBBB\n\/\/ BBBBBBB                    BBBBBBB       BBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\n\/\/ ==================================================\n\/\/ Blockfreight™ | The blockchain for global freight.\n\/\/ ==================================================\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"runtime\"\n\t\"runtime\/debug\"\n\t\"sort\"\n\t\"strconv\"\n\t\"sync\"\n\n\t\"fiber\/src\/templates\"\n\n\t\"github.com\/gofiber\/fiber\"\n\t\"github.com\/gofiber\/utils\"\n\tpgx \"github.com\/jackc\/pgx\/v4\"\n\t\"github.com\/jackc\/pgx\/v4\/pgxpool\"\n)\n\nvar (\n\tchild        bool\n\tdb           *pgxpool.Pool\n\tcachedWorlds Worlds\n)\n\nconst (\n\tqueryparam       = \"q\"\n\thelloworld       = \"Hello, World!\"\n\tworldcount       = 10000\n\tworldselectsql   = \"SELECT id, randomNumber FROM World WHERE id = $1\"\n\tworldupdatesql   = \"UPDATE World SET randomNumber = $1 WHERE id = $2\"\n\tworldcachesql    = \"SELECT * FROM World LIMIT $1\"\n\tfortuneselectsql = \"SELECT id, message FROM Fortune\"\n)\n\nfunc main() {\n\tinitDatabase()\n\n\tapp := fiber.New(&fiber.Settings{\n\t\tCaseSensitive:            true,\n\t\tStrictRouting:            true,\n\t\tDisableHeaderNormalizing: true,\n\t\tServerHeader:             \"go\",\n\t})\n\n\tif utils.GetArgument(\"-prefork-child\") {\n\t\tchild = true\n\t}\n\tif utils.GetArgument(\"-nogc\") {\n\t\tdebug.SetGCPercent(-1)\n\t}\n\n\tapp.Get(\"\/plaintext\", plaintextHandler)\n\tapp.Get(\"\/json\", jsonHandler)\n\tapp.Get(\"\/db\", dbHandler)\n\tapp.Get(\"\/update\", updateHandler)\n\tapp.Get(\"\/queries\", queriesHandler)\n\tapp.Get(\"\/fortunes\", templateHandler)\n\tapp.Get(\"\/cached-worlds\", cachedHandler)\n\tapp.Listen(8080)\n}\n\n\/\/ Message ...\ntype Message struct {\n\tMessage string `json:\"message\"`\n}\n\n\/\/ Worlds ...\ntype Worlds []World\n\n\/\/ World ...\ntype World struct {\n\tID           int32 `json:\"id\"`\n\tRandomNumber int32 `json:\"randomNumber\"`\n}\n\n\/\/ JSONpool ...\nvar JSONpool = sync.Pool{\n\tNew: func() interface{} {\n\t\treturn new(Message)\n\t},\n}\n\n\/\/ AcquireJSON ...\nfunc AcquireJSON() *Message {\n\treturn JSONpool.Get().(*Message)\n}\n\n\/\/ ReleaseJSON ...\nfunc ReleaseJSON(json *Message) {\n\tjson.Message = \"\"\n\tJSONpool.Put(json)\n}\n\n\/\/ WorldPool ...\nvar WorldPool = sync.Pool{\n\tNew: func() interface{} {\n\t\treturn new(World)\n\t},\n}\n\n\/\/ AcquireWorld ...\nfunc AcquireWorld() *World {\n\treturn WorldPool.Get().(*World)\n}\n\n\/\/ ReleaseWorld ...\nfunc ReleaseWorld(w *World) {\n\tw.ID = 0\n\tw.RandomNumber = 0\n\tWorldPool.Put(w)\n}\n\n\/\/ WorldsPool ...\nvar WorldsPool = sync.Pool{\n\tNew: func() interface{} {\n\t\treturn make(Worlds, 0, 500)\n\t},\n}\n\n\/\/ AcquireWorlds ...\nfunc AcquireWorlds() Worlds {\n\treturn WorldsPool.Get().(Worlds)\n}\n\n\/\/ ReleaseWorlds ...ReleaseWorlds\nfunc ReleaseWorlds(w Worlds) {\n\tw = w[:0]\n\tWorldsPool.Put(w)\n}\n\n\/\/ initDatabase :\nfunc initDatabase() {\n\tmaxConn := runtime.NumCPU()\n\tif maxConn == 0 {\n\t\tmaxConn = 8\n\t}\n\tif child {\n\t\tmaxConn = maxConn\n\t} else {\n\t\tmaxConn = maxConn * 4\n\t}\n\n\tvar err error\n\tdb, err = pgxpool.Connect(context.Background(), fmt.Sprintf(\"host=%s port=%d user=%s password=%s dbname=%s pool_max_conns=%d\", \"tfb-database\", 5432, \"benchmarkdbuser\", \"benchmarkdbpass\", \"hello_world\", maxConn))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tpopulateCache()\n}\n\n\/\/ this will populate the cached worlds for the cache test\nfunc populateCache() {\n\tworlds := make(Worlds, worldcount)\n\trows, err := db.Query(context.Background(), worldcachesql, worldcount)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor i := 0; i < worldcount; i++ {\n\t\tw := &worlds[i]\n\t\tif !rows.Next() {\n\t\t\tbreak\n\t\t}\n\t\tif err := rows.Scan(&w.ID, &w.RandomNumber); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\t\/\/db.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)\n\t}\n\tcachedWorlds = worlds\n}\n\n\/\/ jsonHandler :\nfunc jsonHandler(c *fiber.Ctx) {\n\tm := AcquireJSON()\n\tm.Message = helloworld\n\tc.JSON(&m)\n\tReleaseJSON(m)\n}\n\n\/\/ dbHandler :\nfunc dbHandler(c *fiber.Ctx) {\n\tw := AcquireWorld()\n\tdb.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)\n\tc.JSON(&w)\n\tReleaseWorld(w)\n}\n\n\/\/ Frameworks\/Go\/fasthttp\/src\/server-postgresql\/server.go#104\nfunc templateHandler(c *fiber.Ctx) {\n\trows, _ := db.Query(context.Background(), fortuneselectsql)\n\n\tvar f templates.Fortune\n\tfortunes := make([]templates.Fortune, 0, 16)\n\tfor rows.Next() {\n\t\t_ = rows.Scan(&f.ID, &f.Message)\n\t\tfortunes = append(fortunes, f)\n\t}\n\trows.Close()\n\tfortunes = append(fortunes, templates.Fortune{\n\t\tMessage: \"Additional fortune added at request time.\",\n\t})\n\n\tsort.Slice(fortunes, func(i, j int) bool {\n\t\treturn fortunes[i].Message < fortunes[j].Message\n\t})\n\n\tc.Set(fiber.HeaderContentType, fiber.MIMETextHTMLCharsetUTF8)\n\n\ttemplates.WriteFortunePage(c.Fasthttp, fortunes)\n}\n\n\/\/ queriesHandler :\nfunc queriesHandler(c *fiber.Ctx) {\n\tn := QueriesCount(c)\n\tworlds := AcquireWorlds()[:n]\n\tfor i := 0; i < n; i++ {\n\t\tw := &worlds[i]\n\t\tdb.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)\n\t}\n\tc.JSON(&worlds)\n\tReleaseWorlds(worlds)\n}\n\n\/\/ updateHandler :\nfunc updateHandler(c *fiber.Ctx) {\n\tn := QueriesCount(c)\n\tworlds := AcquireWorlds()[:n]\n\tfor i := 0; i < n; i++ {\n\t\tw := &worlds[i]\n\t\tdb.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)\n\t\tw.RandomNumber = int32(RandomWorld())\n\t}\n\t\/\/ sorting is required for insert deadlock prevention.\n\tsort.Slice(worlds, func(i, j int) bool {\n\t\treturn worlds[i].ID < worlds[j].ID\n\t})\n\n\tbatch := pgx.Batch{}\n\tfor _, w := range worlds {\n\t\tbatch.Queue(worldupdatesql, w.RandomNumber, w.ID)\n\t}\n\tdb.SendBatch(context.Background(), &batch).Close()\n\tc.JSON(&worlds)\n\tReleaseWorlds(worlds)\n}\n\nvar helloworldRaw = []byte(\"Hello, World!\")\n\n\/\/ plaintextHandler :\nfunc plaintextHandler(c *fiber.Ctx) {\n\tc.SendBytes(helloworldRaw)\n}\n\n\/\/ cachedHandler :\nfunc cachedHandler(c *fiber.Ctx) {\n\tn := QueriesCount(c)\n\tworlds := AcquireWorlds()[:n]\n\tfor i := 0; i < n; i++ {\n\t\tworlds[i] = cachedWorlds[RandomWorld()-1]\n\t}\n\tc.JSON(&worlds)\n\tReleaseWorlds(worlds)\n}\n\n\/\/ RandomWorld :\nfunc RandomWorld() int {\n\treturn rand.Intn(worldcount) + 1\n}\n\n\/\/ QueriesCount :\nfunc QueriesCount(c *fiber.Ctx) int {\n\tn, _ := strconv.Atoi(c.Query(queryparam))\n\tif n < 1 {\n\t\tn = 1\n\t} else if n > 500 {\n\t\tn = 500\n\t}\n\treturn n\n}\n<commit_msg>🐛 Fiber: Fix Prefork (#5878)<commit_after>package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"runtime\"\n\t\"runtime\/debug\"\n\t\"sort\"\n\t\"strconv\"\n\t\"sync\"\n\n\t\"fiber\/src\/templates\"\n\n\t\"github.com\/gofiber\/fiber\"\n\t\"github.com\/gofiber\/utils\"\n\tpgx \"github.com\/jackc\/pgx\/v4\"\n\t\"github.com\/jackc\/pgx\/v4\/pgxpool\"\n)\n\nvar (\n\tchild        bool\n\tdb           *pgxpool.Pool\n\tcachedWorlds Worlds\n)\n\nconst (\n\tqueryparam       = \"q\"\n\thelloworld       = \"Hello, World!\"\n\tworldcount       = 10000\n\tworldselectsql   = \"SELECT id, randomNumber FROM World WHERE id = $1\"\n\tworldupdatesql   = \"UPDATE World SET randomNumber = $1 WHERE id = $2\"\n\tworldcachesql    = \"SELECT * FROM World LIMIT $1\"\n\tfortuneselectsql = \"SELECT id, message FROM Fortune\"\n)\n\nfunc main() {\n\tinitDatabase()\n\n\tapp := fiber.New(&fiber.Settings{\n\t\tCaseSensitive:            true,\n\t\tStrictRouting:            true,\n\t\tDisableHeaderNormalizing: true,\n\t\tServerHeader:             \"go\",\n\t})\n\tif utils.GetArgument(\"-prefork\") {\n\t\tapp.Settings.Prefork = true\n\t}\n\tif utils.GetArgument(\"-prefork-child\") {\n\t\tchild = true\n\t}\n\tif utils.GetArgument(\"-nogc\") {\n\t\tdebug.SetGCPercent(-1)\n\t}\n\n\tif utils.GetArgument(\"-prefork-child\") {\n\t\tchild = true\n\t}\n\tif utils.GetArgument(\"-nogc\") {\n\t\tdebug.SetGCPercent(-1)\n\t}\n\n\tapp.Get(\"\/plaintext\", plaintextHandler)\n\tapp.Get(\"\/json\", jsonHandler)\n\tapp.Get(\"\/db\", dbHandler)\n\tapp.Get(\"\/update\", updateHandler)\n\tapp.Get(\"\/queries\", queriesHandler)\n\tapp.Get(\"\/fortunes\", templateHandler)\n\tapp.Get(\"\/cached-worlds\", cachedHandler)\n\tapp.Listen(8080)\n}\n\n\/\/ Message ...\ntype Message struct {\n\tMessage string `json:\"message\"`\n}\n\n\/\/ Worlds ...\ntype Worlds []World\n\n\/\/ World ...\ntype World struct {\n\tID           int32 `json:\"id\"`\n\tRandomNumber int32 `json:\"randomNumber\"`\n}\n\n\/\/ JSONpool ...\nvar JSONpool = sync.Pool{\n\tNew: func() interface{} {\n\t\treturn new(Message)\n\t},\n}\n\n\/\/ AcquireJSON ...\nfunc AcquireJSON() *Message {\n\treturn JSONpool.Get().(*Message)\n}\n\n\/\/ ReleaseJSON ...\nfunc ReleaseJSON(json *Message) {\n\tjson.Message = \"\"\n\tJSONpool.Put(json)\n}\n\n\/\/ WorldPool ...\nvar WorldPool = sync.Pool{\n\tNew: func() interface{} {\n\t\treturn new(World)\n\t},\n}\n\n\/\/ AcquireWorld ...\nfunc AcquireWorld() *World {\n\treturn WorldPool.Get().(*World)\n}\n\n\/\/ ReleaseWorld ...\nfunc ReleaseWorld(w *World) {\n\tw.ID = 0\n\tw.RandomNumber = 0\n\tWorldPool.Put(w)\n}\n\n\/\/ WorldsPool ...\nvar WorldsPool = sync.Pool{\n\tNew: func() interface{} {\n\t\treturn make(Worlds, 0, 500)\n\t},\n}\n\n\/\/ AcquireWorlds ...\nfunc AcquireWorlds() Worlds {\n\treturn WorldsPool.Get().(Worlds)\n}\n\n\/\/ ReleaseWorlds ...ReleaseWorlds\nfunc ReleaseWorlds(w Worlds) {\n\tw = w[:0]\n\tWorldsPool.Put(w)\n}\n\n\/\/ initDatabase :\nfunc initDatabase() {\n\tmaxConn := runtime.NumCPU()\n\tif maxConn == 0 {\n\t\tmaxConn = 8\n\t}\n\tif child {\n\t\tmaxConn = maxConn\n\t} else {\n\t\tmaxConn = maxConn * 4\n\t}\n\n\tvar err error\n\tdb, err = pgxpool.Connect(context.Background(), fmt.Sprintf(\"host=%s port=%d user=%s password=%s dbname=%s pool_max_conns=%d\", \"tfb-database\", 5432, \"benchmarkdbuser\", \"benchmarkdbpass\", \"hello_world\", maxConn))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tpopulateCache()\n}\n\n\/\/ this will populate the cached worlds for the cache test\nfunc populateCache() {\n\tworlds := make(Worlds, worldcount)\n\trows, err := db.Query(context.Background(), worldcachesql, worldcount)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor i := 0; i < worldcount; i++ {\n\t\tw := &worlds[i]\n\t\tif !rows.Next() {\n\t\t\tbreak\n\t\t}\n\t\tif err := rows.Scan(&w.ID, &w.RandomNumber); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\t\/\/db.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)\n\t}\n\tcachedWorlds = worlds\n}\n\n\/\/ jsonHandler :\nfunc jsonHandler(c *fiber.Ctx) {\n\tm := AcquireJSON()\n\tm.Message = helloworld\n\tc.JSON(&m)\n\tReleaseJSON(m)\n}\n\n\/\/ dbHandler :\nfunc dbHandler(c *fiber.Ctx) {\n\tw := AcquireWorld()\n\tdb.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)\n\tc.JSON(&w)\n\tReleaseWorld(w)\n}\n\n\/\/ Frameworks\/Go\/fasthttp\/src\/server-postgresql\/server.go#104\nfunc templateHandler(c *fiber.Ctx) {\n\trows, _ := db.Query(context.Background(), fortuneselectsql)\n\n\tvar f templates.Fortune\n\tfortunes := make([]templates.Fortune, 0, 16)\n\tfor rows.Next() {\n\t\t_ = rows.Scan(&f.ID, &f.Message)\n\t\tfortunes = append(fortunes, f)\n\t}\n\trows.Close()\n\tfortunes = append(fortunes, templates.Fortune{\n\t\tMessage: \"Additional fortune added at request time.\",\n\t})\n\n\tsort.Slice(fortunes, func(i, j int) bool {\n\t\treturn fortunes[i].Message < fortunes[j].Message\n\t})\n\n\tc.Set(fiber.HeaderContentType, fiber.MIMETextHTMLCharsetUTF8)\n\n\ttemplates.WriteFortunePage(c.Fasthttp, fortunes)\n}\n\n\/\/ queriesHandler :\nfunc queriesHandler(c *fiber.Ctx) {\n\tn := QueriesCount(c)\n\tworlds := AcquireWorlds()[:n]\n\tfor i := 0; i < n; i++ {\n\t\tw := &worlds[i]\n\t\tdb.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)\n\t}\n\tc.JSON(&worlds)\n\tReleaseWorlds(worlds)\n}\n\n\/\/ updateHandler :\nfunc updateHandler(c *fiber.Ctx) {\n\tn := QueriesCount(c)\n\tworlds := AcquireWorlds()[:n]\n\tfor i := 0; i < n; i++ {\n\t\tw := &worlds[i]\n\t\tdb.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)\n\t\tw.RandomNumber = int32(RandomWorld())\n\t}\n\t\/\/ sorting is required for insert deadlock prevention.\n\tsort.Slice(worlds, func(i, j int) bool {\n\t\treturn worlds[i].ID < worlds[j].ID\n\t})\n\n\tbatch := pgx.Batch{}\n\tfor _, w := range worlds {\n\t\tbatch.Queue(worldupdatesql, w.RandomNumber, w.ID)\n\t}\n\tdb.SendBatch(context.Background(), &batch).Close()\n\tc.JSON(&worlds)\n\tReleaseWorlds(worlds)\n}\n\nvar helloworldRaw = []byte(\"Hello, World!\")\n\n\/\/ plaintextHandler :\nfunc plaintextHandler(c *fiber.Ctx) {\n\tc.SendBytes(helloworldRaw)\n}\n\n\/\/ cachedHandler :\nfunc cachedHandler(c *fiber.Ctx) {\n\tn := QueriesCount(c)\n\tworlds := AcquireWorlds()[:n]\n\tfor i := 0; i < n; i++ {\n\t\tworlds[i] = cachedWorlds[RandomWorld()-1]\n\t}\n\tc.JSON(&worlds)\n\tReleaseWorlds(worlds)\n}\n\n\/\/ RandomWorld :\nfunc RandomWorld() int {\n\treturn rand.Intn(worldcount) + 1\n}\n\n\/\/ QueriesCount :\nfunc QueriesCount(c *fiber.Ctx) int {\n\tn, _ := strconv.Atoi(c.Query(queryparam))\n\tif n < 1 {\n\t\tn = 1\n\t} else if n > 500 {\n\t\tn = 500\n\t}\n\treturn n\n}\n<|endoftext|>"}
{"text":"<commit_before>package gateway\n\nimport (\n\t\"net\/url\"\n\n\t\"log\"\n\n\t\"github.com\/ReneGa\/tweetcount-microservices\/ingestor\/client\"\n\t\"github.com\/ReneGa\/tweetcount-microservices\/ingestor\/domain\"\n\t\"github.com\/chimeracoder\/anaconda\"\n)\n\n\/\/ Twitter is a gateway to the Twitter streaming API\ntype Twitter interface {\n\tTweets(query string) domain.Tweets\n}\n\n\/\/ NewAnacondaTwitter creates a new Twitter client\nfunc NewAnacondaTwitter(\n\tanaconda client.Anaconda,\n\tkey string,\n\tkeySecret string,\n\ttoken string,\n\ttokenSecret string,\n) Twitter {\n\tanaconda.SetConsumerKey(key)\n\tanaconda.SetConsumerSecret(keySecret)\n\tapi := anaconda.NewTwitterAPI(token, tokenSecret)\n\treturn &anacondaTwitter{api}\n}\n\ntype anacondaTwitter struct{ client.AnacondaAPI }\n\n\/\/ Tweets returns a stream of public Tweets for a given search query.\nfunc (a anacondaTwitter) Tweets(query string) domain.Tweets {\n\tstream := a.PublicStreamFilter(url.Values{\n\t\t\"track\": {query},\n\t})\n\tanacondaChan := stream.C()\n\tout := make(chan domain.Tweet)\n\tstop := make(chan bool)\n\n\ttweets := domain.Tweets{\n\t\tData: out,\n\t\tStop: stop,\n\t}\n\n\tgo func() {\n\t\tdefer close(out)\n\t\tdefer stream.Stop()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase item := <-anacondaChan:\n\t\t\t\tlog.Println(item)\n\t\t\t\tif t, ok := item.(anaconda.Tweet); ok {\n\t\t\t\t\ttweetTime, _ := t.CreatedAtTime()\n\t\t\t\t\tout <- domain.Tweet{\n\t\t\t\t\t\tText: t.Text,\n\t\t\t\t\t\tID:   t.IdStr,\n\t\t\t\t\t\tTime: tweetTime,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn tweets\n}\n<commit_msg>remove debug log<commit_after>package gateway\n\nimport (\n\t\"net\/url\"\n\n\t\"github.com\/ReneGa\/tweetcount-microservices\/ingestor\/client\"\n\t\"github.com\/ReneGa\/tweetcount-microservices\/ingestor\/domain\"\n\t\"github.com\/chimeracoder\/anaconda\"\n)\n\n\/\/ Twitter is a gateway to the Twitter streaming API\ntype Twitter interface {\n\tTweets(query string) domain.Tweets\n}\n\n\/\/ NewAnacondaTwitter creates a new Twitter client\nfunc NewAnacondaTwitter(\n\tanaconda client.Anaconda,\n\tkey string,\n\tkeySecret string,\n\ttoken string,\n\ttokenSecret string,\n) Twitter {\n\tanaconda.SetConsumerKey(key)\n\tanaconda.SetConsumerSecret(keySecret)\n\tapi := anaconda.NewTwitterAPI(token, tokenSecret)\n\treturn &anacondaTwitter{api}\n}\n\ntype anacondaTwitter struct{ client.AnacondaAPI }\n\n\/\/ Tweets returns a stream of public Tweets for a given search query.\nfunc (a anacondaTwitter) Tweets(query string) domain.Tweets {\n\tstream := a.PublicStreamFilter(url.Values{\n\t\t\"track\": {query},\n\t})\n\tanacondaChan := stream.C()\n\tout := make(chan domain.Tweet)\n\tstop := make(chan bool)\n\n\ttweets := domain.Tweets{\n\t\tData: out,\n\t\tStop: stop,\n\t}\n\n\tgo func() {\n\t\tdefer close(out)\n\t\tdefer stream.Stop()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase item := <-anacondaChan:\n\t\t\t\tif t, ok := item.(anaconda.Tweet); ok {\n\t\t\t\t\ttweetTime, _ := t.CreatedAtTime()\n\t\t\t\t\tout <- domain.Tweet{\n\t\t\t\t\t\tText: t.Text,\n\t\t\t\t\t\tID:   t.IdStr,\n\t\t\t\t\t\tTime: tweetTime,\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn tweets\n}\n<|endoftext|>"}
{"text":"<commit_before>package user\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/sethgrid\/pester\"\n\t\"github.com\/starptech\/go-web\/feed\"\n)\n\n\/\/ Example only configurable with env variables\n\/\/\n\/\/ store := feed.NewMemoryStore()\n\/\/ uf := userFeed.NewUser(feed.Config{Table: \"user\", Interval: 5, URL: \"http:\/\/example.de\/feed\"}, store)\n\/\/ go uf.Start()\n\/\/\n\/\/ The feed endpoint accept a parameter called \"last\" which is used as cursor for the current feed position\n\/\/ This cursor will be saved when the update process is done\n\/\/ GET http:\/\/example.de\/feed?last=1503769504008\n\/\/ { \"items\": [{ \"name\": \"peter\" }] }\n\/\/\n\ntype Feed struct {\n\tafter  uint64\n\tticker *time.Ticker\n\tstore  feed.FeedStore\n\tconfig feed.Config\n}\n\n\/\/ NewUser start the timer and return a new userFeed instance\nfunc NewUser(config feed.Config, s feed.FeedStore) *Feed {\n\tu := &Feed{}\n\tu.config = config\n\tu.store = s\n\tu.after = u.store.GetPosition(u.config.Table)\n\tu.ticker = time.NewTicker(time.Duration(u.config.Interval) * time.Second)\n\treturn u\n}\n\n\/\/ Start poll updates in certain intervals\nfunc (u *Feed) Start() {\n\tfor range u.ticker.C {\n\t\tu.poll(u.after)\n\t}\n}\n\n\/\/ poll start a request against the feed endpoint\nfunc (u *Feed) poll(last uint64) {\n\tfeed, err := u.request()\n\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\tdefault:\n\t\t\tfmt.Println(err)\n\t\t}\n\t} else if err := u.store.Save(feed); err == nil {\n\t\tu.store.SetPosition(u.config.Table, last)\n\t}\n\n\tfmt.Println(feed)\n}\n\n\/\/ Request the feed endpoint and return the feed results\nfunc (u *Feed) request() (*feed.RootFeed, error) {\n\tclient := pester.New()\n\tclient.Concurrency = 3\n\tclient.MaxRetries = 5\n\tclient.Backoff = pester.ExponentialBackoff\n\tclient.KeepLog = true\n\n\tresp, err := client.Get(u.config.URL + \"?after=\" + string(u.after))\n\tdefer func() {\n\t\terr := resp.Body.Close()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error closing response body %q\\n\", err)\n\t\t}\n\t}()\n\n\tif err != nil {\n\t\treturn nil, feed.ErrClient\n\t}\n\n\tpayload, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\treturn nil, feed.ErrReadBody\n\t}\n\n\tf := &feed.RootFeed{}\n\tif err := json.Unmarshal(payload, f); err != nil {\n\t\treturn nil, feed.ErrUnMarshaling\n\t}\n\n\treturn f, nil\n}\n<commit_msg>Update user.go<commit_after>package user\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/sethgrid\/pester\"\n\t\"github.com\/starptech\/go-web\/feed\"\n)\n\n\/\/ Example:\n\/\/ cfg := feed.Config{Table: \"user\", Interval: 5, URL: \"http:\/\/example.de\/feed\"}\n\/\/ store := feed.NewMemoryStore()\n\/\/ uf := userFeed.NewUser(cfg, store)\n\/\/ go uf.Start()\n\/\/\n\/\/ The feed endpoint accept a parameter called \"last\" which is used as cursor for the current feed position\n\/\/ This cursor will be saved when the update process is done\n\/\/ GET http:\/\/example.de\/feed?last=1503769504008\n\/\/ { \"items\": [{ \"name\": \"peter\" }] }\n\/\/\n\ntype Feed struct {\n\tafter  uint64\n\tticker *time.Ticker\n\tstore  feed.FeedStore\n\tconfig feed.Config\n}\n\n\/\/ NewUser start the timer and return a new userFeed instance\nfunc NewUser(config feed.Config, s feed.FeedStore) *Feed {\n\tu := &Feed{}\n\tu.config = config\n\tu.store = s\n\tu.after = u.store.GetPosition(u.config.Table)\n\tu.ticker = time.NewTicker(time.Duration(u.config.Interval) * time.Second)\n\treturn u\n}\n\n\/\/ Start poll updates in certain intervals\nfunc (u *Feed) Start() {\n\tfor range u.ticker.C {\n\t\tu.poll(u.after)\n\t}\n}\n\n\/\/ poll start a request against the feed endpoint\nfunc (u *Feed) poll(last uint64) {\n\tfeed, err := u.request()\n\n\tif err != nil {\n\t\tswitch err.(type) {\n\t\tdefault:\n\t\t\tfmt.Println(err)\n\t\t}\n\t} else if err := u.store.Save(feed); err == nil {\n\t\tu.store.SetPosition(u.config.Table, last)\n\t}\n\n\tfmt.Println(feed)\n}\n\n\/\/ Request the feed endpoint and return the feed results\nfunc (u *Feed) request() (*feed.RootFeed, error) {\n\tclient := pester.New()\n\tclient.Concurrency = 3\n\tclient.MaxRetries = 5\n\tclient.Backoff = pester.ExponentialBackoff\n\tclient.KeepLog = true\n\n\tresp, err := client.Get(u.config.URL + \"?after=\" + string(u.after))\n\tdefer func() {\n\t\terr := resp.Body.Close()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error closing response body %q\\n\", err)\n\t\t}\n\t}()\n\n\tif err != nil {\n\t\treturn nil, feed.ErrClient\n\t}\n\n\tpayload, err := ioutil.ReadAll(resp.Body)\n\n\tif err != nil {\n\t\treturn nil, feed.ErrReadBody\n\t}\n\n\tf := &feed.RootFeed{}\n\tif err := json.Unmarshal(payload, f); err != nil {\n\t\treturn nil, feed.ErrUnMarshaling\n\t}\n\n\treturn f, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"github.com\/russross\/blackfriday\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype FileRepository struct {\n\tdirectory string\n\tposts BlogPosts\n\ttags []string\n}\n\nfunc NewFileRepository(directory string) *FileRepository {\n\n\tf := new(FileRepository)\n\tf.directory = directory\n\tf.posts, _ = f.fetchAllPosts()\n\tf.tags = f.fetchAllTags()\n\n\treturn f\n}\n\nfunc (f *FileRepository) AllTags() []string {\n\treturn f.tags\n}\n\nfunc (f *FileRepository) AllPosts() BlogPosts {\n\treturn f.posts\n}\n\nfunc (f *FileRepository) PostWithUrl(url string) (*BlogPost, error) {\n\n\tfor i := range f.posts {\n\t\tif f.posts[i].Url() == url {\n\t\t\treturn f.posts[i], nil\n\t\t}\n\t}\n\n\terr := errors.New(\"Could not find post\")\n\n\treturn nil, err\n}\n\nfunc (f *FileRepository) PostsWithTag(tag string) BlogPosts {\n\n\tfilteredPosts := BlogPosts{}\n\n\tfor i := range f.posts {\n\t\tif f.posts[i].ContainsTag(tag) {\n\t\t\tfilteredPosts = append(filteredPosts, f.posts[i])\n\t\t}\n\t}\n\n\treturn filteredPosts\n}\n\nfunc (f *FileRepository) PostsInRange(start, count int) BlogPosts {\n\n\tif start + count > len(f.posts) {\n\t\tcount = len(f.posts) - start\n\t}\n\n\treturn f.posts[start:start + count]\n}\n\nfunc (f *FileRepository) fetchAllPosts() (BlogPosts, error) {\n\n\tdirname := f.directory + string(filepath.Separator)\n\n\tfiles, err := ioutil.ReadDir(dirname)\n\n\tposts := BlogPosts{}\n\n\tfor i := range files {\n\n\t\tif files[i].IsDir() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif filepath.Ext(files[i].Name()) != \".md\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tpost, err := f.fetchPost(files[i].Name())\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tposts = append(posts, post)\n\t}\n\n\tsort.Sort(posts)\n\n\treturn posts, err\n}\n\nfunc (f *FileRepository) fetchAllTags() []string {\n\n\t\/\/ We're using a map to simulate a set\n\ttagMap := make(map[string]bool)\n\n\tfor i := range f.posts {\n\t\tfor j := range f.posts[i].Tags() {\n\t\t\ttagMap[strings.ToLower(f.posts[i].Tags()[j])] = true\n\t\t}\n\t}\n\n\ttags := []string{}\n\n\tfor key := range tagMap {\n\t\ttags = append(tags, key)\n\t}\n\n\tsort.Strings(tags)\n\n\treturn tags\n}\n\nfunc (f *FileRepository) fetchPost(filename string) (*BlogPost, error) {\n\n\tpost := new(BlogPost)\n\n\tdirname := f.directory + string(filepath.Separator)\n\n\tfile, err := ioutil.ReadFile(dirname + filename)\n\n\tif err != nil {\n\t\treturn post, err\n\t}\n\n\tfile = []byte(f.extractHeader(string(file), post))\n\n\thtmlFlags := blackfriday.HTML_USE_SMARTYPANTS\n\textensions := blackfriday.EXTENSION_HARD_LINE_BREAK | blackfriday.EXTENSION_FENCED_CODE | blackfriday.EXTENSION_NO_INTRA_EMPHASIS\n\n\trenderer := blackfriday.HtmlRenderer(htmlFlags, post.Title(), \"\")\n\n\toutput := blackfriday.Markdown(file, renderer, extensions)\n\n\tpost.SetBody(string(output))\n\n\treturn post, nil\n}\n\nfunc (f *FileRepository) extractHeader(text string, post *BlogPost) string {\n\n\tlines := strings.Split(text, \"\\n\")\n\n\theaderSize := 0\n\n\tfor i := range lines {\n\t\tif strings.Contains(lines[i], \":\") {\n\t\t\tcomponents := strings.Split(lines[i], \":\")\n\n\t\t\theader := strings.ToLower(strings.Trim(components[0], \" \"))\n\t\t\tseparatorIndex := strings.Index(lines[i], \":\") + 1\n\t\t\tdata := strings.Trim(lines[i][separatorIndex:], \" \")\n\n\t\t\tswitch header {\n\t\t\tcase \"title\":\n\t\t\t\tpost.SetTitle(data)\n\t\t\tcase \"tags\":\n\n\t\t\t\ttags := strings.Split(data, \",\")\n\n\t\t\t\tformattedTags := []string{}\n\n\t\t\t\tfor j := range tags {\n\t\t\t\t\ttags[j] = strings.Trim(tags[j], \" \")\n\t\t\t\t\ttags[j] = strings.Replace(tags[j], \" \", \"-\", -1)\n\n\t\t\t\t\tif tags[j] != \"\" {\n\t\t\t\t\t\tformattedTags = append(formattedTags, tags[j])\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tpost.SetTags(formattedTags)\n\t\t\tcase \"date\":\n\t\t\t\tpost.SetPublishDate(stringToTime(data))\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\theaderSize += len(lines[i]) + 1\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn text[headerSize:]\n}\n\nfunc stringToTime(s string) time.Time {\n\n\tyear, err := strconv.Atoi(s[:4])\n\n\tif err != nil {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\tmonth, err := strconv.Atoi(s[5:7])\n\n\tif err != nil {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\tday, err := strconv.Atoi(s[8:10])\n\n\tif err != nil {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\thour, err := strconv.Atoi(s[11:13])\n\n\tif err != nil {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\tminute, err := strconv.Atoi(s[14:16])\n\n\tif err != nil {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\tseconds, err := strconv.Atoi(s[17:19])\n\n\tif err != nil {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\tlocation, err := time.LoadLocation(\"UTC\")\n\n\treturn time.Date(year, time.Month(month), day, hour, minute, seconds, 0, location)\n}\n<commit_msg>Added mutexes to file repository functions. File repository updates its cache every 10 minutes.<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"github.com\/russross\/blackfriday\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\t\"sync\"\n)\n\ntype FileRepository struct {\n\tdirectory string\n\tposts BlogPosts\n\ttags []string\n\tlastUpdated time.Time\n\tmutex sync.RWMutex\n}\n\nfunc NewFileRepository(directory string) *FileRepository {\n\n\tf := new(FileRepository)\n\tf.directory = directory\n\n\tf.fetchAllPosts()\n\tf.fetchAllTags()\n\n\tf.lastUpdated = time.Now()\n\n\tgo f.update()\n\n\n\treturn f\n}\n\nfunc (f *FileRepository) AllTags() []string {\n\treturn f.tags\n}\n\nfunc (f *FileRepository) AllPosts() BlogPosts {\n\treturn f.posts\n}\n\nfunc (f *FileRepository) PostWithUrl(url string) (*BlogPost, error) {\n\n\tf.mutex.RLock()\n\tdefer f.mutex.RUnlock()\n\n\tfor i := range f.posts {\n\t\tif f.posts[i].Url() == url {\n\t\t\treturn f.posts[i], nil\n\t\t}\n\t}\n\n\terr := errors.New(\"Could not find post\")\n\n\treturn nil, err\n}\n\nfunc (f *FileRepository) PostsWithTag(tag string) BlogPosts {\n\n\tf.mutex.RLock()\n\tdefer f.mutex.RUnlock()\n\n\tfilteredPosts := BlogPosts{}\n\n\tfor i := range f.posts {\n\t\tif f.posts[i].ContainsTag(tag) {\n\t\t\tfilteredPosts = append(filteredPosts, f.posts[i])\n\t\t}\n\t}\n\n\treturn filteredPosts\n}\n\nfunc (f *FileRepository) PostsInRange(start, count int) BlogPosts {\n\n\tf.mutex.RLock()\n\tdefer f.mutex.RUnlock()\n\n\tif start + count > len(f.posts) {\n\t\tcount = len(f.posts) - start\n\t}\n\n\treturn f.posts[start:start + count]\n}\n\nfunc (f *FileRepository) update() {\n\n\tf.mutex.Lock()\n\tdefer f.mutex.Unlock()\n\n\tfor {\n\t\tf.fetchAllPosts()\n\t\tf.fetchAllTags()\n\t\tf.lastUpdated = time.Now()\n\n\t\ttime.Sleep(10 * time.Minute)\n\t}\n}\n\nfunc (f *FileRepository) fetchAllPosts() error {\n\n\tf.mutex.Lock()\n\tdefer f.mutex.Unlock()\n\n\tdirname := f.directory + string(filepath.Separator)\n\n\tfiles, err := ioutil.ReadDir(dirname)\n\n\tf.posts = BlogPosts{}\n\n\tfor i := range files {\n\n\t\tif files[i].IsDir() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif filepath.Ext(files[i].Name()) != \".md\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tpost, err := f.fetchPost(files[i].Name())\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tf.posts = append(f.posts, post)\n\t}\n\n\tsort.Sort(f.posts)\n\n\treturn err\n}\n\nfunc (f *FileRepository) fetchAllTags() {\n\n\tf.mutex.Lock()\n\tdefer f.mutex.Unlock()\n\n\t\/\/ We're using a map to simulate a set\n\ttagMap := make(map[string]bool)\n\n\tfor i := range f.posts {\n\t\tfor j := range f.posts[i].Tags() {\n\t\t\ttagMap[strings.ToLower(f.posts[i].Tags()[j])] = true\n\t\t}\n\t}\n\n\tf.tags = []string{}\n\n\tfor key := range tagMap {\n\t\tf.tags = append(f.tags, key)\n\t}\n\n\tsort.Strings(f.tags)\n}\n\nfunc (f *FileRepository) fetchPost(filename string) (*BlogPost, error) {\n\n\tpost := new(BlogPost)\n\n\tdirname := f.directory + string(filepath.Separator)\n\n\tfile, err := ioutil.ReadFile(dirname + filename)\n\n\tif err != nil {\n\t\treturn post, err\n\t}\n\n\tfile = []byte(f.extractHeader(string(file), post))\n\n\thtmlFlags := blackfriday.HTML_USE_SMARTYPANTS\n\textensions := blackfriday.EXTENSION_HARD_LINE_BREAK | blackfriday.EXTENSION_FENCED_CODE | blackfriday.EXTENSION_NO_INTRA_EMPHASIS\n\n\trenderer := blackfriday.HtmlRenderer(htmlFlags, post.Title(), \"\")\n\n\toutput := blackfriday.Markdown(file, renderer, extensions)\n\n\tpost.SetBody(string(output))\n\n\treturn post, nil\n}\n\nfunc (f *FileRepository) extractHeader(text string, post *BlogPost) string {\n\n\tlines := strings.Split(text, \"\\n\")\n\n\theaderSize := 0\n\n\tfor i := range lines {\n\t\tif strings.Contains(lines[i], \":\") {\n\t\t\tcomponents := strings.Split(lines[i], \":\")\n\n\t\t\theader := strings.ToLower(strings.Trim(components[0], \" \"))\n\t\t\tseparatorIndex := strings.Index(lines[i], \":\") + 1\n\t\t\tdata := strings.Trim(lines[i][separatorIndex:], \" \")\n\n\t\t\tswitch header {\n\t\t\tcase \"title\":\n\t\t\t\tpost.SetTitle(data)\n\t\t\tcase \"tags\":\n\n\t\t\t\ttags := strings.Split(data, \",\")\n\n\t\t\t\tformattedTags := []string{}\n\n\t\t\t\tfor j := range tags {\n\t\t\t\t\ttags[j] = strings.Trim(tags[j], \" \")\n\t\t\t\t\ttags[j] = strings.Replace(tags[j], \" \", \"-\", -1)\n\n\t\t\t\t\tif tags[j] != \"\" {\n\t\t\t\t\t\tformattedTags = append(formattedTags, tags[j])\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tpost.SetTags(formattedTags)\n\t\t\tcase \"date\":\n\t\t\t\tpost.SetPublishDate(stringToTime(data))\n\t\t\tdefault:\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\theaderSize += len(lines[i]) + 1\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn text[headerSize:]\n}\n\nfunc stringToTime(s string) time.Time {\n\n\tyear, err := strconv.Atoi(s[:4])\n\n\tif err != nil {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\tmonth, err := strconv.Atoi(s[5:7])\n\n\tif err != nil {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\tday, err := strconv.Atoi(s[8:10])\n\n\tif err != nil {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\thour, err := strconv.Atoi(s[11:13])\n\n\tif err != nil {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\tminute, err := strconv.Atoi(s[14:16])\n\n\tif err != nil {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\tseconds, err := strconv.Atoi(s[17:19])\n\n\tif err != nil {\n\t\treturn time.Unix(0, 0)\n\t}\n\n\tlocation, err := time.LoadLocation(\"UTC\")\n\n\treturn time.Date(year, time.Month(month), day, hour, minute, seconds, 0, location)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The Gosl Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage al\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/cpmech\/gosl\/chk\"\n\t\"github.com\/cpmech\/gosl\/io\"\n)\n\nfunc TestQueue01(tst *testing.T) {\n\n\t\/\/verbose()\n\tchk.PrintTitle(\"Queue01\")\n\n\tguessedMaxSize := 20\n\tqu := NewQueue(guessedMaxSize)\n\tmember := qu.Out()\n\tif member != nil {\n\t\ttst.Errorf(\"returned member should be nil in an empty Queue\\n\")\n\t\treturn\n\t}\n\tqu.Debug = true\n\n\t\/\/ add\n\tio.PfYel(\"In(l)\\n\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 0)\n\tqu.In(FromString(\"l\"))\n\tchk.String(tst, \"[l]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[l]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"l\")\n\tchk.String(tst, ToString(qu.Back()), \"l\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 1)\n\n\tio.PfYel(\"\\nIn(o)\\n\")\n\tqu.In(FromString(\"o\"))\n\tchk.String(tst, \"[l o]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[l o]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"l\")\n\tchk.String(tst, ToString(qu.Back()), \"o\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 2)\n\n\tio.PfYel(\"\\nIn(v)\\n\")\n\tqu.In(FromString(\"v\"))\n\tchk.String(tst, \"[l o v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[l o v]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"l\")\n\tchk.String(tst, ToString(qu.Back()), \"v\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 3)\n\n\t\/\/ remove\n\tio.PfYel(\"\\nOut(l)\\n\")\n\tres := ToString(qu.Out())\n\tchk.String(tst, \"[l o v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[o v]\", qu.String())\n\tchk.String(tst, res, \"l\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 2)\n\n\tio.PfYel(\"\\nOut(o)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, \"[l o v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[v]\", qu.String())\n\tchk.String(tst, res, \"o\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 1)\n\n\tio.PfYel(\"\\nOut(v)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, \"[l o v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[]\", qu.String())\n\tchk.String(tst, res, \"v\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 0)\n\n\t\/\/ try to remove more in empty queue\n\tio.PfYel(\"\\nOut(nothing)\\n\")\n\tmember = qu.Out()\n\tif member != nil {\n\t\ttst.Errorf(\"returned member should be nil in an empty Queue\\n\")\n\t\treturn\n\t}\n\tchk.String(tst, \"[]\", qu.String())\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 0)\n\n\t\/\/ add again\n\tio.PfYel(\"\\nIn(a)\\n\")\n\tqu.In(FromString(\"a\"))\n\tchk.String(tst, \"[a o v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[a]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"a\")\n\tchk.String(tst, ToString(qu.Back()), \"a\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 1)\n\n\tio.PfYel(\"\\nIn(b)\\n\")\n\tqu.In(FromString(\"b\"))\n\tchk.String(tst, \"[a b v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[a b]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"a\")\n\tchk.String(tst, ToString(qu.Back()), \"b\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 2)\n\n\tio.PfYel(\"\\nOut(a)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, \"[a b v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[b]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"b\")\n\tchk.String(tst, ToString(qu.Back()), \"b\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 1)\n\n\tio.PfYel(\"\\nIn(a) again\\n\")\n\tqu.In(FromString(\"a\"))\n\tchk.String(tst, \"[a b a]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[b a]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"b\")\n\tchk.String(tst, ToString(qu.Back()), \"a\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 2)\n\n\tio.PfYel(\"\\nIn(c)\\n\")\n\tqu.In(FromString(\"c\"))\n\tchk.String(tst, \"[c b a]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[b a c]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"b\")\n\tchk.String(tst, ToString(qu.Back()), \"c\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 3)\n\n\tio.PfYel(\"\\nIn(x)\\n\")\n\tqu.In(FromString(\"x\"))\n\tchk.String(tst, \"[b a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[b a c x]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"b\")\n\tchk.String(tst, ToString(qu.Back()), \"x\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 4)\n\n\tio.PfYel(\"\\nOut(b)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, \"[b a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[a c x]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"a\")\n\tchk.String(tst, ToString(qu.Back()), \"x\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 3)\n\n\tio.PfYel(\"\\nOut(a)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, \"[b a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[c x]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"c\")\n\tchk.String(tst, ToString(qu.Back()), \"x\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 2)\n\n\tio.PfYel(\"\\nOut(c)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, \"[b a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[x]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"x\")\n\tchk.String(tst, ToString(qu.Back()), \"x\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 1)\n\n\tio.PfYel(\"\\nOut(x)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, \"[b a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[]\", qu.String())\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 0)\n\n\tio.PfYel(\"\\nOut(nothing)\\n\")\n\tchk.String(tst, \"[b a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[]\", qu.String())\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 0)\n\n\tio.PfYel(\"\\nIn(i)\\n\")\n\tqu.In(FromString(\"i\"))\n\tchk.String(tst, \"[i a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[i]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"i\")\n\tchk.String(tst, ToString(qu.Back()), \"i\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 1)\n\n\tio.PfYel(\"\\nIn(j)\\n\")\n\tqu.In(FromString(\"j\"))\n\tchk.String(tst, \"[i j c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[i j]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"i\")\n\tchk.String(tst, ToString(qu.Back()), \"j\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 2)\n}\n<commit_msg>Improve test<commit_after>\/\/ Copyright 2016 The Gosl Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage al\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/cpmech\/gosl\/chk\"\n\t\"github.com\/cpmech\/gosl\/io\"\n)\n\nfunc TestQueue01(tst *testing.T) {\n\n\t\/\/verbose()\n\tchk.PrintTitle(\"Queue01\")\n\n\tguessedMaxSize := 20\n\tqu := NewQueue(guessedMaxSize)\n\tmember := qu.Out()\n\tif member != nil {\n\t\ttst.Errorf(\"returned member should be nil in an empty Queue\\n\")\n\t\treturn\n\t}\n\tqu.Debug = true\n\n\t\/\/ add\n\tio.PfYel(\"In(l)\\n\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 0)\n\tqu.In(FromString(\"l\"))\n\tchk.String(tst, \"[l]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[l]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"l\")\n\tchk.String(tst, ToString(qu.Back()), \"l\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 1)\n\n\tio.PfYel(\"\\nIn(o)\\n\")\n\tqu.In(FromString(\"o\"))\n\tchk.String(tst, \"[l o]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[l o]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"l\")\n\tchk.String(tst, ToString(qu.Back()), \"o\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 2)\n\n\tio.PfYel(\"\\nIn(v)\\n\")\n\tqu.In(FromString(\"v\"))\n\tchk.String(tst, \"[l o v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[l o v]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"l\")\n\tchk.String(tst, ToString(qu.Back()), \"v\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 3)\n\n\t\/\/ remove\n\tio.PfYel(\"\\nOut(l)\\n\")\n\tres := ToString(qu.Out())\n\tchk.String(tst, \"[l o v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[o v]\", qu.String())\n\tchk.String(tst, res, \"l\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 2)\n\n\tio.PfYel(\"\\nOut(o)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, \"[l o v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[v]\", qu.String())\n\tchk.String(tst, res, \"o\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 1)\n\n\tio.PfYel(\"\\nOut(v)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, \"[l o v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[]\", qu.String())\n\tchk.String(tst, res, \"v\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 0)\n\n\t\/\/ try to remove more in empty queue\n\tio.PfYel(\"\\nOut(nothing)\\n\")\n\tmember = qu.Out()\n\tif member != nil {\n\t\ttst.Errorf(\"returned member should be nil in an empty Queue\\n\")\n\t\treturn\n\t}\n\tchk.String(tst, \"[]\", qu.String())\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 0)\n\n\t\/\/ add again\n\tio.PfYel(\"\\nIn(a)\\n\")\n\tqu.In(FromString(\"a\"))\n\tchk.String(tst, \"[a o v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[a]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"a\")\n\tchk.String(tst, ToString(qu.Back()), \"a\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 1)\n\n\tio.PfYel(\"\\nIn(b)\\n\")\n\tqu.In(FromString(\"b\"))\n\tchk.String(tst, \"[a b v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[a b]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"a\")\n\tchk.String(tst, ToString(qu.Back()), \"b\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 2)\n\n\tio.PfYel(\"\\nOut(a)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, res, \"a\")\n\tchk.String(tst, \"[a b v]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[b]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"b\")\n\tchk.String(tst, ToString(qu.Back()), \"b\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 1)\n\n\tio.PfYel(\"\\nIn(a) again\\n\")\n\tqu.In(FromString(\"a\"))\n\tchk.String(tst, \"[a b a]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[b a]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"b\")\n\tchk.String(tst, ToString(qu.Back()), \"a\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 2)\n\n\tio.PfYel(\"\\nIn(c)\\n\")\n\tqu.In(FromString(\"c\"))\n\tchk.String(tst, \"[c b a]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[b a c]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"b\")\n\tchk.String(tst, ToString(qu.Back()), \"c\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 3)\n\n\tio.PfYel(\"\\nIn(x)\\n\")\n\tqu.In(FromString(\"x\"))\n\tchk.String(tst, \"[b a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[b a c x]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"b\")\n\tchk.String(tst, ToString(qu.Back()), \"x\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 4)\n\n\tio.PfYel(\"\\nOut(b)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, res, \"b\")\n\tchk.String(tst, \"[b a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[a c x]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"a\")\n\tchk.String(tst, ToString(qu.Back()), \"x\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 3)\n\n\tio.PfYel(\"\\nOut(a)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, res, \"a\")\n\tchk.String(tst, \"[b a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[c x]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"c\")\n\tchk.String(tst, ToString(qu.Back()), \"x\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 2)\n\n\tio.PfYel(\"\\nOut(c)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, res, \"c\")\n\tchk.String(tst, \"[b a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[x]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"x\")\n\tchk.String(tst, ToString(qu.Back()), \"x\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 1)\n\n\tio.PfYel(\"\\nOut(x)\\n\")\n\tres = ToString(qu.Out())\n\tchk.String(tst, res, \"x\")\n\tchk.String(tst, \"[b a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[]\", qu.String())\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 0)\n\n\tio.PfYel(\"\\nOut(nothing)\\n\")\n\tchk.String(tst, \"[b a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[]\", qu.String())\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 0)\n\n\tio.PfYel(\"\\nIn(i)\\n\")\n\tqu.In(FromString(\"i\"))\n\tchk.String(tst, \"[i a c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[i]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"i\")\n\tchk.String(tst, ToString(qu.Back()), \"i\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 1)\n\n\tio.PfYel(\"\\nIn(j)\\n\")\n\tqu.In(FromString(\"j\"))\n\tchk.String(tst, \"[i j c x]\", io.Sf(\"%v\", qu.ring))\n\tchk.String(tst, \"[i j]\", qu.String())\n\tchk.String(tst, ToString(qu.Front()), \"i\")\n\tchk.String(tst, ToString(qu.Back()), \"j\")\n\tchk.Int(tst, \"len(queue)\", qu.Nmembers(), 2)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014 Datacratic. All rights reserved.\n\npackage rest\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ Client is a convenience REST client which simplifies the creation of REST\n\/\/ requests.\ntype Client struct {\n\t*http.Client\n\n\t\/\/ Host is the address of the remote REST endpoint where requests should be\n\t\/\/ sent to.\n\tHost string\n\n\t\/\/ Root is a prefix that will be preprended to all path requests created by\n\t\/\/ this client.\n\tRoot string\n\n\t\/\/ Header is a list of HTTP requests that will be added to every requests\n\t\/\/ originating from this client.\n\tHeader http.Header\n\n\t\/\/ Limit sets a hard limit on the number of concurrent requests. If not set\n\t\/\/ then no limits are imposed.\n\tLimit uint\n\n\tinitialize sync.Once\n\n\tlimit chan struct{}\n}\n\n\/\/ NewRequest creates a new Request object for the given HTTP method.\nfunc (client *Client) NewRequest(method string) *Request {\n\tclient.initialize.Do(func() {\n\t\tif client.Client == nil {\n\t\t\tclient.Client = http.DefaultClient\n\t\t}\n\n\t\tif client.Limit > 0 {\n\t\t\tclient.limit = make(chan struct{})\n\n\t\t\tfor i := uint(0); i < client.Limit; i++ {\n\t\t\t\tclient.end()\n\t\t\t}\n\t\t}\n\n\t})\n\n\treturn &Request{\n\t\tREST:   client,\n\t\tClient: client.Client,\n\t\tHost:   client.Host,\n\t\tMethod: method,\n\t\tRoot:   client.Root,\n\t\tHeader: client.Header,\n\t}\n}\n\nfunc (client *Client) begin() {\n\tif client.limit != nil {\n\t\t<-client.limit\n\t}\n}\n\nfunc (client *Client) end() {\n\tif client.limit != nil {\n\t\tclient.limit <- struct{}{}\n\t}\n}\n\n\/\/ Request is used to gradually construct REST requests and send them to a\n\/\/ remote endpoint. Request object should be created via the NewRequest function\n\/\/ or the Client.NewRequest function and filled in via the SetXxx and AddXxx\n\/\/ functions. Finally the request is sent via the Send function which returns a\n\/\/ Response object.\ntype Request struct {\n\n\t\/\/ REST is the client that originated the request. Can be nil.\n\tREST *Client\n\n\t\/\/ Client is the http.Client used to send the request. Defaults to\n\t\/\/ http.DefaultClient and can changed via the SetClient method.\n\tClient *http.Client\n\n\t\/\/ Host is the address of the remote REST endpoint where requests should be\n\t\/\/ sent to.\n\tHost string\n\n\t\/\/ Root is a prefix that will be preprended to all path requests created by\n\t\/\/ this client.\n\tRoot string\n\n\t\/\/ Path is the absolute path where the Request should be routed to on the\n\t\/\/ remote endpoint. Can be changed via the SetPath method.\n\tPath string\n\n\t\/\/ Method is the HTTP verb used for the HTTP request.\n\tMethod string\n\n\t\/\/ Header contains all the headers to be added to the HTTP request. Can be\n\t\/\/ changed via the AddHeader method.\n\tHeader http.Header\n\n\t\/\/ Body is the JSON serialized body of the HTTP request. Can be set via the\n\t\/\/ SetBody method.\n\tBody []byte\n\n\tHTTP *http.Request\n\n\terr *Error\n}\n\n\/\/ NewRequest creates a new Request object to be sent to the given host using\n\/\/ the given HTTP verb.\nfunc NewRequest(host, method string) *Request {\n\treturn &Request{\n\t\tHost:   host,\n\t\tMethod: method,\n\t\tClient: http.DefaultClient,\n\t}\n}\n\n\/\/ SetClient selects the http.Client to be used to execute the requests.\nfunc (req *Request) SetClient(client *http.Client) *Request {\n\treq.Client = client\n\treturn req\n}\n\n\/\/ SetPath formats and sets the path where the request will be routed to. Note\n\/\/ that the root is prefixed to the path before formatting the string.\nfunc (req *Request) SetPath(path string, args ...interface{}) *Request {\n\treq.Path = fmt.Sprintf(JoinPath(req.Root, path), args...)\n\treturn req\n}\n\n\/\/ AddHeader adds the given header to the request.\nfunc (req *Request) AddHeader(key, value string) *Request {\n\tif req.Header == nil {\n\t\treq.Header = make(http.Header)\n\t}\n\n\treq.Header.Add(key, value)\n\treturn req\n}\n\n\/\/ SetBody marshals the given objects and sets it as the body of the\n\/\/ request. The Content-Length header will be automatically set.\nfunc (req *Request) SetBody(obj interface{}) *Request {\n\tvar err error\n\tif req.Body, err = json.Marshal(obj); err == nil {\n\t\treq.AddHeader(\"Content-Length\", strconv.Itoa(len(req.Body)))\n\n\t} else {\n\t\treq.err = &Error{MarshalError, err}\n\t}\n\n\treturn req\n}\n\n\/\/ Send attempts to send the request to the remote endpoint and returns a\n\/\/ Response which contains the result.\nfunc (req *Request) Send() *Response {\n\tt0 := time.Now()\n\n\tif len(req.Path) == 0 {\n\t\treq.Path = req.Root\n\t}\n\n\tresp := &Response{Request: req, Error: req.err}\n\n\tif resp.Error == nil {\n\t\tif req.REST != nil {\n\t\t\treq.REST.begin()\n\t\t}\n\n\t\treq.send(resp)\n\n\t\tif req.REST != nil {\n\t\t\treq.REST.end()\n\t\t}\n\t}\n\n\tresp.Latency = time.Since(t0)\n\treturn resp\n}\n\nfunc (req *Request) send(resp *Response) {\n\tvar reader io.Reader\n\tif len(req.Body) > 0 {\n\t\treader = bytes.NewReader(req.Body)\n\t}\n\n\turl := strings.TrimRight(req.Host, \"\/\") + req.Path\n\n\tvar err error\n\n\tif req.HTTP, err = http.NewRequest(req.Method, url, reader); err != nil {\n\t\tresp.Error = &Error{NewRequestError, err}\n\t\treturn\n\t}\n\n\treq.AddHeader(\"Content-Type\", \"application\/json\")\n\treq.HTTP.Header = req.Header\n\n\thttpResp, err := req.Client.Do(req.HTTP)\n\tif err != nil {\n\t\tresp.Error = &Error{SendRequestError, err}\n\t\treturn\n\t}\n\n\tresp.Code = httpResp.StatusCode\n\tresp.Header = httpResp.Header\n\n\tif resp.Body, err = ioutil.ReadAll(httpResp.Body); err != nil {\n\t\tresp.Error = &Error{ReadBodyError, err}\n\t}\n\n\thttpResp.Body.Close()\n\treturn\n}\n\n\/\/ Response holds the result of a sent REST request. The response should be read\n\/\/ via the GetBody method which checks the various fields to detect errors.\ntype Response struct {\n\n\t\/\/ Request is the request that originated the response.\n\tRequest *Request\n\n\t\/\/ Code is the http status code returned by the endpoint.\n\tCode int\n\n\t\/\/ Header holds the headers of the HTTP response.\n\tHeader http.Header\n\n\t\/\/ Body holds the raw unmarshalled body of the HTTP response. GetBody can be\n\t\/\/ used to unmarshal the body.\n\tBody []byte\n\n\t\/\/ Error is set if an error occured while sending the request.\n\tError *Error\n\n\t\/\/ Latency indicates how long the request round-trip took.\n\tLatency time.Duration\n}\n\n\/\/ GetBody checks the various fields of the response for errors and unmarshals\n\/\/ the response body if the given object is not nil. If an error is detected,\n\/\/ the error type and error will be returned instead.\nfunc (resp *Response) GetBody(obj interface{}) (err *Error) {\n\tif resp.Error != nil {\n\t\terr = resp.Error\n\n\t} else if resp.Code == http.StatusNotFound {\n\t\terr = &Error{UnknownRoute, errors.New(string(resp.Body))}\n\n\t} else if resp.Code >= 400 {\n\t\terr = &Error{EndpointError, errors.New(string(resp.Body))}\n\n\t} else if resp.Code < 200 && resp.Code >= 300 {\n\t\terr = ErrorFmt(UnexpectedStatusCode, \"unexpected status code: %d\", resp.Code)\n\n\t} else if resp.Code == http.StatusNoContent {\n\t\tif obj == nil {\n\t\t\treturn\n\t\t}\n\t\terr = ErrorFmt(UnexpectedStatusCode, \"unexpected status code: 204\")\n\n\t} else if contentType := resp.Header.Get(\"Content-Type\"); contentType != \"application\/json\" {\n\t\terr = ErrorFmt(UnsupportedContentType, \"unsupported content-type: '%s' != 'application\/json'\", contentType)\n\n\t} else if jsonErr := json.Unmarshal(resp.Body, obj); err != nil {\n\t\terr = &Error{UnmarshalError, jsonErr}\n\t}\n\n\treturn\n}\n<commit_msg>client limits no longer block infinitely.<commit_after>\/\/ Copyright (c) 2014 Datacratic. All rights reserved.\n\npackage rest\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ Client is a convenience REST client which simplifies the creation of REST\n\/\/ requests.\ntype Client struct {\n\t*http.Client\n\n\t\/\/ Host is the address of the remote REST endpoint where requests should be\n\t\/\/ sent to.\n\tHost string\n\n\t\/\/ Root is a prefix that will be preprended to all path requests created by\n\t\/\/ this client.\n\tRoot string\n\n\t\/\/ Header is a list of HTTP requests that will be added to every requests\n\t\/\/ originating from this client.\n\tHeader http.Header\n\n\t\/\/ Limit sets a hard limit on the number of concurrent requests. If not set\n\t\/\/ then no limits are imposed.\n\tLimit uint\n\n\tinitialize sync.Once\n\n\tlimit chan struct{}\n}\n\n\/\/ NewRequest creates a new Request object for the given HTTP method.\nfunc (client *Client) NewRequest(method string) *Request {\n\tclient.initialize.Do(func() {\n\t\tif client.Client == nil {\n\t\t\tclient.Client = http.DefaultClient\n\t\t}\n\n\t\tif client.Limit > 0 {\n\t\t\tclient.limit = make(chan struct{}, client.Limit)\n\n\t\t\tfor i := uint(0); i < client.Limit; i++ {\n\t\t\t\tclient.end()\n\t\t\t}\n\t\t}\n\n\t})\n\n\treturn &Request{\n\t\tREST:   client,\n\t\tClient: client.Client,\n\t\tHost:   client.Host,\n\t\tMethod: method,\n\t\tRoot:   client.Root,\n\t\tHeader: client.Header,\n\t}\n}\n\nfunc (client *Client) begin() {\n\tif client.limit != nil {\n\t\t<-client.limit\n\t}\n}\n\nfunc (client *Client) end() {\n\tif client.limit != nil {\n\t\tclient.limit <- struct{}{}\n\t}\n}\n\n\/\/ Request is used to gradually construct REST requests and send them to a\n\/\/ remote endpoint. Request object should be created via the NewRequest function\n\/\/ or the Client.NewRequest function and filled in via the SetXxx and AddXxx\n\/\/ functions. Finally the request is sent via the Send function which returns a\n\/\/ Response object.\ntype Request struct {\n\n\t\/\/ REST is the client that originated the request. Can be nil.\n\tREST *Client\n\n\t\/\/ Client is the http.Client used to send the request. Defaults to\n\t\/\/ http.DefaultClient and can changed via the SetClient method.\n\tClient *http.Client\n\n\t\/\/ Host is the address of the remote REST endpoint where requests should be\n\t\/\/ sent to.\n\tHost string\n\n\t\/\/ Root is a prefix that will be preprended to all path requests created by\n\t\/\/ this client.\n\tRoot string\n\n\t\/\/ Path is the absolute path where the Request should be routed to on the\n\t\/\/ remote endpoint. Can be changed via the SetPath method.\n\tPath string\n\n\t\/\/ Method is the HTTP verb used for the HTTP request.\n\tMethod string\n\n\t\/\/ Header contains all the headers to be added to the HTTP request. Can be\n\t\/\/ changed via the AddHeader method.\n\tHeader http.Header\n\n\t\/\/ Body is the JSON serialized body of the HTTP request. Can be set via the\n\t\/\/ SetBody method.\n\tBody []byte\n\n\tHTTP *http.Request\n\n\terr *Error\n}\n\n\/\/ NewRequest creates a new Request object to be sent to the given host using\n\/\/ the given HTTP verb.\nfunc NewRequest(host, method string) *Request {\n\treturn &Request{\n\t\tHost:   host,\n\t\tMethod: method,\n\t\tClient: http.DefaultClient,\n\t}\n}\n\n\/\/ SetClient selects the http.Client to be used to execute the requests.\nfunc (req *Request) SetClient(client *http.Client) *Request {\n\treq.Client = client\n\treturn req\n}\n\n\/\/ SetPath formats and sets the path where the request will be routed to. Note\n\/\/ that the root is prefixed to the path before formatting the string.\nfunc (req *Request) SetPath(path string, args ...interface{}) *Request {\n\treq.Path = fmt.Sprintf(JoinPath(req.Root, path), args...)\n\treturn req\n}\n\n\/\/ AddHeader adds the given header to the request.\nfunc (req *Request) AddHeader(key, value string) *Request {\n\tif req.Header == nil {\n\t\treq.Header = make(http.Header)\n\t}\n\n\treq.Header.Add(key, value)\n\treturn req\n}\n\n\/\/ SetBody marshals the given objects and sets it as the body of the\n\/\/ request. The Content-Length header will be automatically set.\nfunc (req *Request) SetBody(obj interface{}) *Request {\n\tvar err error\n\tif req.Body, err = json.Marshal(obj); err == nil {\n\t\treq.AddHeader(\"Content-Length\", strconv.Itoa(len(req.Body)))\n\n\t} else {\n\t\treq.err = &Error{MarshalError, err}\n\t}\n\n\treturn req\n}\n\n\/\/ Send attempts to send the request to the remote endpoint and returns a\n\/\/ Response which contains the result.\nfunc (req *Request) Send() *Response {\n\tt0 := time.Now()\n\n\tif len(req.Path) == 0 {\n\t\treq.Path = req.Root\n\t}\n\n\tresp := &Response{Request: req, Error: req.err}\n\n\tif resp.Error == nil {\n\t\tif req.REST != nil {\n\t\t\treq.REST.begin()\n\t\t}\n\n\t\treq.send(resp)\n\n\t\tif req.REST != nil {\n\t\t\treq.REST.end()\n\t\t}\n\t}\n\n\tresp.Latency = time.Since(t0)\n\treturn resp\n}\n\nfunc (req *Request) send(resp *Response) {\n\tvar reader io.Reader\n\tif len(req.Body) > 0 {\n\t\treader = bytes.NewReader(req.Body)\n\t}\n\n\turl := strings.TrimRight(req.Host, \"\/\") + req.Path\n\n\tvar err error\n\n\tif req.HTTP, err = http.NewRequest(req.Method, url, reader); err != nil {\n\t\tresp.Error = &Error{NewRequestError, err}\n\t\treturn\n\t}\n\n\treq.AddHeader(\"Content-Type\", \"application\/json\")\n\treq.HTTP.Header = req.Header\n\n\thttpResp, err := req.Client.Do(req.HTTP)\n\tif err != nil {\n\t\tresp.Error = &Error{SendRequestError, err}\n\t\treturn\n\t}\n\n\tresp.Code = httpResp.StatusCode\n\tresp.Header = httpResp.Header\n\n\tif resp.Body, err = ioutil.ReadAll(httpResp.Body); err != nil {\n\t\tresp.Error = &Error{ReadBodyError, err}\n\t}\n\n\thttpResp.Body.Close()\n\treturn\n}\n\n\/\/ Response holds the result of a sent REST request. The response should be read\n\/\/ via the GetBody method which checks the various fields to detect errors.\ntype Response struct {\n\n\t\/\/ Request is the request that originated the response.\n\tRequest *Request\n\n\t\/\/ Code is the http status code returned by the endpoint.\n\tCode int\n\n\t\/\/ Header holds the headers of the HTTP response.\n\tHeader http.Header\n\n\t\/\/ Body holds the raw unmarshalled body of the HTTP response. GetBody can be\n\t\/\/ used to unmarshal the body.\n\tBody []byte\n\n\t\/\/ Error is set if an error occured while sending the request.\n\tError *Error\n\n\t\/\/ Latency indicates how long the request round-trip took.\n\tLatency time.Duration\n}\n\n\/\/ GetBody checks the various fields of the response for errors and unmarshals\n\/\/ the response body if the given object is not nil. If an error is detected,\n\/\/ the error type and error will be returned instead.\nfunc (resp *Response) GetBody(obj interface{}) (err *Error) {\n\tif resp.Error != nil {\n\t\terr = resp.Error\n\n\t} else if resp.Code == http.StatusNotFound {\n\t\terr = &Error{UnknownRoute, errors.New(string(resp.Body))}\n\n\t} else if resp.Code >= 400 {\n\t\terr = &Error{EndpointError, errors.New(string(resp.Body))}\n\n\t} else if resp.Code < 200 && resp.Code >= 300 {\n\t\terr = ErrorFmt(UnexpectedStatusCode, \"unexpected status code: %d\", resp.Code)\n\n\t} else if resp.Code == http.StatusNoContent {\n\t\tif obj == nil {\n\t\t\treturn\n\t\t}\n\t\terr = ErrorFmt(UnexpectedStatusCode, \"unexpected status code: 204\")\n\n\t} else if contentType := resp.Header.Get(\"Content-Type\"); contentType != \"application\/json\" {\n\t\terr = ErrorFmt(UnsupportedContentType, \"unsupported content-type: '%s' != 'application\/json'\", contentType)\n\n\t} else if jsonErr := json.Unmarshal(resp.Body, obj); err != nil {\n\t\terr = &Error{UnmarshalError, jsonErr}\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage restorable\n\nimport (\n\t\"image\"\n\t\"image\/color\"\n\t\"image\/draw\"\n\t\"runtime\"\n\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/math\"\n)\n\n\/\/ CopyImage copies origImg to a new RGBA image.\n\/\/\n\/\/ Basically CopyImage just calls draw.Draw.\n\/\/ If origImg is a paletted image, an optimized copying method is used.\n\/\/\n\/\/ CopyImage is used only internally but it is exposed for testing.\nfunc CopyImage(origImg image.Image) *image.RGBA {\n\tsize := origImg.Bounds().Size()\n\tw, h := size.X, size.Y\n\tnewImg := image.NewRGBA(image.Rect(0, 0, math.NextPowerOf2Int(w), math.NextPowerOf2Int(h)))\n\tswitch origImg := origImg.(type) {\n\tcase *image.Paletted:\n\t\tb := origImg.Bounds()\n\t\tx0 := b.Min.X\n\t\ty0 := b.Min.Y\n\t\tx1 := b.Max.X\n\t\ty1 := b.Max.Y\n\t\tpalette := make([]uint8, len(origImg.Palette)*4)\n\t\tfor i, c := range origImg.Palette {\n\t\t\trgba := color.RGBAModel.Convert(c).(color.RGBA)\n\t\t\tpalette[4*i] = rgba.R\n\t\t\tpalette[4*i+1] = rgba.G\n\t\t\tpalette[4*i+2] = rgba.B\n\t\t\tpalette[4*i+3] = rgba.A\n\t\t}\n\t\tindex0 := 0\n\t\tindex1 := 0\n\t\td0 := origImg.Stride - (x1 - x0)\n\t\td1 := newImg.Stride - (x1-x0)*4\n\t\tpix0 := origImg.Pix\n\t\tpix1 := newImg.Pix\n\t\tfor j := 0; j < y1-y0; j++ {\n\t\t\tfor i := 0; i < x1-x0; i++ {\n\t\t\t\tp := int(pix0[index0])\n\t\t\t\tpix1[index1] = palette[4*p]\n\t\t\t\tpix1[index1+1] = palette[4*p+1]\n\t\t\t\tpix1[index1+2] = palette[4*p+2]\n\t\t\t\tpix1[index1+3] = palette[4*p+3]\n\t\t\t\tindex0++\n\t\t\t\tindex1 += 4\n\t\t\t}\n\t\t\tindex0 += d0\n\t\t\tindex1 += d1\n\t\t}\n\tdefault:\n\t\tdraw.Draw(newImg, image.Rect(0, 0, w, h), origImg, origImg.Bounds().Min, draw.Src)\n\t}\n\truntime.Gosched()\n\treturn newImg\n}\n<commit_msg>restorable: Remove unneeded NextPowerOf2Int usage<commit_after>\/\/ Copyright 2017 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage restorable\n\nimport (\n\t\"image\"\n\t\"image\/color\"\n\t\"image\/draw\"\n\t\"runtime\"\n)\n\n\/\/ CopyImage copies origImg to a new RGBA image.\n\/\/\n\/\/ Basically CopyImage just calls draw.Draw.\n\/\/ If origImg is a paletted image, an optimized copying method is used.\n\/\/\n\/\/ CopyImage is used only internally but it is exposed for testing.\nfunc CopyImage(origImg image.Image) *image.RGBA {\n\tsize := origImg.Bounds().Size()\n\tw, h := size.X, size.Y\n\tnewImg := image.NewRGBA(image.Rect(0, 0, w, h))\n\tswitch origImg := origImg.(type) {\n\tcase *image.Paletted:\n\t\tb := origImg.Bounds()\n\t\tx0 := b.Min.X\n\t\ty0 := b.Min.Y\n\t\tx1 := b.Max.X\n\t\ty1 := b.Max.Y\n\t\tpalette := make([]uint8, len(origImg.Palette)*4)\n\t\tfor i, c := range origImg.Palette {\n\t\t\trgba := color.RGBAModel.Convert(c).(color.RGBA)\n\t\t\tpalette[4*i] = rgba.R\n\t\t\tpalette[4*i+1] = rgba.G\n\t\t\tpalette[4*i+2] = rgba.B\n\t\t\tpalette[4*i+3] = rgba.A\n\t\t}\n\t\tindex0 := 0\n\t\tindex1 := 0\n\t\td0 := origImg.Stride - (x1 - x0)\n\t\td1 := newImg.Stride - (x1-x0)*4\n\t\tpix0 := origImg.Pix\n\t\tpix1 := newImg.Pix\n\t\tfor j := 0; j < y1-y0; j++ {\n\t\t\tfor i := 0; i < x1-x0; i++ {\n\t\t\t\tp := int(pix0[index0])\n\t\t\t\tpix1[index1] = palette[4*p]\n\t\t\t\tpix1[index1+1] = palette[4*p+1]\n\t\t\t\tpix1[index1+2] = palette[4*p+2]\n\t\t\t\tpix1[index1+3] = palette[4*p+3]\n\t\t\t\tindex0++\n\t\t\t\tindex1 += 4\n\t\t\t}\n\t\t\tindex0 += d0\n\t\t\tindex1 += d1\n\t\t}\n\tdefault:\n\t\tdraw.Draw(newImg, image.Rect(0, 0, w, h), origImg, origImg.Bounds().Min, draw.Src)\n\t}\n\truntime.Gosched()\n\treturn newImg\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright(C) 2022 github.com\/fsgo  All Rights Reserved.\n\/\/ Author: hidu <duv123@gmail.com>\n\/\/ Date: 2022\/11\/13\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"io\/fs\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\n\t\"github.com\/fatih\/color\"\n)\n\nvar name = flag.String(\"name\", \"\", \"find file name\")\n\nfunc main() {\n\tflag.Parse()\n\tif len(*name) == 0 {\n\t\tlog.Fatalln(color.RedString(\"-name is required\"))\n\t}\n\tcmdName := flag.Arg(0)\n\tif len(cmdName) == 0 {\n\t\tlog.Fatalln(color.RedString(\"cmd is empty\"))\n\t}\n\tvar fail int\n\terr := filepath.Walk(\".\/\", func(path string, info fs.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn := filepath.Base(path)\n\t\tif n != *name {\n\t\t\treturn nil\n\t\t}\n\t\tdir := filepath.Dir(path)\n\t\tcmd := exec.Command(cmdName, flag.Args()[1:]...)\n\t\tcolor.Cyan(\"Dir: %s Exec: %s\", dir, cmd.String())\n\t\tcmd.Dir = dir\n\t\tcmd.Stdin = os.Stdin\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\tif e1 := cmd.Run(); e1 != nil {\n\t\t\tfail++\n\t\t\tcolor.Red(e1.Error())\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Fatalln(color.RedString(err.Error()))\n\t}\n\tif fail > 0 {\n\t\tlog.Fatalln(color.RedString(\"total %d tasks failed\", fail))\n\t}\n}\n\nfunc init() {\n\tcolor.Output = os.Stderr\n}\n<commit_msg>update<commit_after>\/\/ Copyright(C) 2022 github.com\/fsgo  All Rights Reserved.\n\/\/ Author: hidu <duv123@gmail.com>\n\/\/ Date: 2022\/11\/13\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/fs\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\n\t\"github.com\/fatih\/color\"\n)\n\nvar name = flag.String(\"name\", \"go.mod\", \"find file name\")\nvar useReg = flag.Bool(\"e\", false, \"name as regular expression\")\n\nfunc main() {\n\tflag.Parse()\n\tif len(*name) == 0 {\n\t\tlog.Fatalln(color.RedString(\"-name is required\"))\n\t}\n\tcmdName := flag.Arg(0)\n\tif len(cmdName) == 0 {\n\t\tlog.Fatalln(color.RedString(\"cmd is empty\"))\n\t}\n\n\tvar reg *regexp.Regexp\n\tif *useReg {\n\t\tr, err := regexp.Compile(*name)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(color.RedString(\"regexp.Compile(%q): %v\", *name, err))\n\t\t}\n\t\treg = r\n\t}\n\n\tmatch := func(fileName string) bool {\n\t\tif *useReg {\n\t\t\treturn reg.MatchString(fileName)\n\t\t}\n\t\treturn fileName == *name\n\t}\n\tvar index int\n\tvar fail int\n\terr := filepath.Walk(\".\/\", func(path string, info fs.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tfileName := filepath.Base(path)\n\n\t\tif !match(fileName) {\n\t\t\treturn nil\n\t\t}\n\t\tindex++\n\n\t\tdir := filepath.Dir(path)\n\t\tcmd := exec.Command(cmdName, flag.Args()[1:]...)\n\n\t\ts0 := color.GreenString(\"%3d.\", index)\n\t\ts1 := color.CyanString(\"Dir: %s, MatchFile: %s\", dir, fileName)\n\t\ts2 := color.YellowString(\"Exec: %s\", cmd.String())\n\t\tfmt.Println(s0, s1, s2)\n\n\t\tcmd.Dir = dir\n\t\tcmd.Stdin = os.Stdin\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\tif e1 := cmd.Run(); e1 != nil {\n\t\t\tfail++\n\t\t\tcolor.Red(e1.Error())\n\t\t}\n\t\treturn fs.SkipDir\n\t})\n\tif err != nil {\n\t\tlog.Fatalln(color.RedString(err.Error()))\n\t}\n\tif fail > 0 {\n\t\tlog.Fatalln(color.RedString(\"total %d tasks failed\", fail))\n\t}\n}\n\nfunc init() {\n\tcolor.Output = os.Stderr\n}\n<|endoftext|>"}
{"text":"<commit_before>package digests\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/ion-channel\/ionic\/scanner\"\n\t\"github.com\/ion-channel\/ionic\/scans\"\n)\n\nfunc vulnerabilityDigests(status *scanner.ScanStatus, eval *scans.Evaluation) ([]Digest, error) {\n\tdigests := make([]Digest, 0)\n\n\tvar vulnCount, uniqVulnCount int\n\tvar highs int\n\tvar crits int\n\tif eval != nil {\n\t\tb, ok := eval.TranslatedResults.Data.(scans.VulnerabilityResults)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"error coercing evaluation translated results into vuln\")\n\t\t}\n\n\t\tvulnCount = b.Meta.VulnerabilityCount\n\n\t\tids := make(map[int]bool, 0)\n\n\t\tfor i := range b.Vulnerabilities {\n\t\t\tfor j := range b.Vulnerabilities[i].Vulnerabilities {\n\t\t\t\tv := b.Vulnerabilities[i].Vulnerabilities[j]\n\t\t\t\tids[v.ID] = true\n\n\t\t\t\tswitch v.ScoreVersion {\n\t\t\t\tcase \"3.0\":\n\t\t\t\t\tif v.ScoreDetails.CVSSv3 != nil && v.ScoreDetails.CVSSv3.BaseScore >= 9.0 {\n\t\t\t\t\t\tcrits++\n\t\t\t\t\t} else if v.ScoreDetails.CVSSv3 != nil && v.ScoreDetails.CVSSv3.BaseScore >= 7.0 {\n\t\t\t\t\t\thighs++\n\t\t\t\t\t}\n\t\t\t\tcase \"2.0\":\n\t\t\t\t\tif v.ScoreDetails.CVSSv2 != nil && v.ScoreDetails.CVSSv2.BaseScore >= 7.0 {\n\t\t\t\t\t\thighs++\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tuniqVulnCount = len(ids)\n\t}\n\n\t\/\/ total vulns\n\td := NewDigest(status, totalVulnerabilitiesIndex, \"total vulnerability\", \"total vulnerabilities\")\n\n\tif eval != nil && !status.Errored() {\n\t\terr := d.AppendEval(eval, \"count\", vulnCount)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to add evaluation data to total vulnerabilities digest: %v\", err.Error())\n\t\t}\n\n\t\tif vulnCount > 0 {\n\t\t\td.Warning = true\n\t\t\td.WarningMessage = \"vulnerabilities found\"\n\n\t\t\tif vulnCount == 1 {\n\t\t\t\td.WarningMessage = \"vulnerability found\"\n\t\t\t}\n\t\t}\n\n\t\td.Evaluated = false \/\/ As of now there's no rule to evaluate this against so it's set to not evaluated.\n\t}\n\n\tdigests = append(digests, *d)\n\n\t\/\/ unique vulns\n\td = NewDigest(status, uniqueVulnerabilitiesIndex, \"unique vulnerability\", \"unique vulnerabilities\")\n\n\tif eval != nil && !status.Errored() {\n\t\terr := d.AppendEval(eval, \"count\", uniqVulnCount)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to add evaluation data to unique vulnerabilities digest: %v\", err.Error())\n\t\t}\n\n\t\tif uniqVulnCount > 0 {\n\t\t\td.Warning = true\n\t\t\td.WarningMessage = \"vulnerabilities found\"\n\n\t\t\tif uniqVulnCount == 1 {\n\t\t\t\td.WarningMessage = \"vulnerability found\"\n\t\t\t}\n\t\t}\n\n\t\td.Evaluated = false \/\/ As of now there's no rule to evaluate this against so it's set to not evaluated.\n\t}\n\n\tdigests = append(digests, *d)\n\n\t\/\/ high vulns\n\td = NewDigest(status, highVulnerabilitiesIndex, \"high vulnerability\", \"high vulnerabilities\")\n\n\tif eval != nil && !status.Errored() {\n\t\terr := d.AppendEval(eval, \"count\", highs)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to add evaluation data to unique vulnerabilities digest: %v\", err.Error())\n\t\t}\n\n\t\tif highs == 0 {\n\t\t\td.Passed = true\n\t\t}\n\t}\n\n\tdigests = append(digests, *d)\n\n\t\/\/ critical vulns\n\td = NewDigest(status, criticalVulnerabilitiesIndex, \"critical vulnerability\", \"critical vulnerabilities\")\n\n\tif eval != nil && !status.Errored() {\n\t\terr := d.AppendEval(eval, \"count\", crits)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to add evaluation data to unique vulnerabilities digest: %v\", err.Error())\n\t\t}\n\n\t\tif crits == 0 {\n\t\t\td.Passed = true\n\t\t}\n\t}\n\n\tdigests = append(digests, *d)\n\n\treturn digests, nil\n}\n<commit_msg>And the fix.<commit_after>package digests\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com\/ion-channel\/ionic\/scanner\"\n\t\"github.com\/ion-channel\/ionic\/scans\"\n)\n\nfunc vulnerabilityDigests(status *scanner.ScanStatus, eval *scans.Evaluation) ([]Digest, error) {\n\tdigests := make([]Digest, 0)\n\n\tvar vulnCount, uniqVulnCount int\n\tvar highs int\n\tvar crits int\n\tif eval != nil {\n\t\tb, ok := eval.TranslatedResults.Data.(scans.VulnerabilityResults)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"error coercing evaluation translated results into vuln\")\n\t\t}\n\n\t\tvulnCount = b.Meta.VulnerabilityCount\n\n\t\tids := make(map[int]bool, 0)\n\n\t\tfor i := range b.Vulnerabilities {\n\t\t\tfor j := range b.Vulnerabilities[i].Vulnerabilities {\n\t\t\t\tv := b.Vulnerabilities[i].Vulnerabilities[j]\n\t\t\t\tids[v.ID] = true\n\n\t\t\t\tif v.ScoreSystem == \"NPM\" {\n\t\t\t\t\tif npmScore, err := strconv.ParseFloat(v.Score, 32); err == nil {\n\t\t\t\t\t\tif npmScore > 7 { \/\/ 10, 9, 8\n\t\t\t\t\t\t\tcrits++\n\t\t\t\t\t\t} else if npmScore > 5 { \/\/ 7, 6\n\t\t\t\t\t\t\thighs++\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tswitch v.ScoreVersion {\n\t\t\t\t\tcase \"3.0\":\n\t\t\t\t\t\tif v.ScoreDetails.CVSSv3 != nil && v.ScoreDetails.CVSSv3.BaseScore >= 9.0 {\n\t\t\t\t\t\t\tcrits++\n\t\t\t\t\t\t} else if v.ScoreDetails.CVSSv3 != nil && v.ScoreDetails.CVSSv3.BaseScore >= 7.0 {\n\t\t\t\t\t\t\thighs++\n\t\t\t\t\t\t}\n\t\t\t\t\tcase \"2.0\":\n\t\t\t\t\t\tif v.ScoreDetails.CVSSv2 != nil && v.ScoreDetails.CVSSv2.BaseScore >= 7.0 {\n\t\t\t\t\t\t\thighs++\n\t\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\tuniqVulnCount = len(ids)\n\t}\n\n\t\/\/ total vulns\n\td := NewDigest(status, totalVulnerabilitiesIndex, \"total vulnerability\", \"total vulnerabilities\")\n\n\tif eval != nil && !status.Errored() {\n\t\terr := d.AppendEval(eval, \"count\", vulnCount)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to add evaluation data to total vulnerabilities digest: %v\", err.Error())\n\t\t}\n\n\t\tif vulnCount > 0 {\n\t\t\td.Warning = true\n\t\t\td.WarningMessage = \"vulnerabilities found\"\n\n\t\t\tif vulnCount == 1 {\n\t\t\t\td.WarningMessage = \"vulnerability found\"\n\t\t\t}\n\t\t}\n\n\t\td.Evaluated = false \/\/ As of now there's no rule to evaluate this against so it's set to not evaluated.\n\t}\n\n\tdigests = append(digests, *d)\n\n\t\/\/ unique vulns\n\td = NewDigest(status, uniqueVulnerabilitiesIndex, \"unique vulnerability\", \"unique vulnerabilities\")\n\n\tif eval != nil && !status.Errored() {\n\t\terr := d.AppendEval(eval, \"count\", uniqVulnCount)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to add evaluation data to unique vulnerabilities digest: %v\", err.Error())\n\t\t}\n\n\t\tif uniqVulnCount > 0 {\n\t\t\td.Warning = true\n\t\t\td.WarningMessage = \"vulnerabilities found\"\n\n\t\t\tif uniqVulnCount == 1 {\n\t\t\t\td.WarningMessage = \"vulnerability found\"\n\t\t\t}\n\t\t}\n\n\t\td.Evaluated = false \/\/ As of now there's no rule to evaluate this against so it's set to not evaluated.\n\t}\n\n\tdigests = append(digests, *d)\n\n\t\/\/ high vulns\n\td = NewDigest(status, highVulnerabilitiesIndex, \"high vulnerability\", \"high vulnerabilities\")\n\n\tif eval != nil && !status.Errored() {\n\t\terr := d.AppendEval(eval, \"count\", highs)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to add evaluation data to unique vulnerabilities digest: %v\", err.Error())\n\t\t}\n\n\t\tif highs == 0 {\n\t\t\td.Passed = true\n\t\t}\n\t}\n\n\tdigests = append(digests, *d)\n\n\t\/\/ critical vulns\n\td = NewDigest(status, criticalVulnerabilitiesIndex, \"critical vulnerability\", \"critical vulnerabilities\")\n\n\tif eval != nil && !status.Errored() {\n\t\terr := d.AppendEval(eval, \"count\", crits)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to add evaluation data to unique vulnerabilities digest: %v\", err.Error())\n\t\t}\n\n\t\tif crits == 0 {\n\t\t\td.Passed = true\n\t\t}\n\t}\n\n\tdigests = append(digests, *d)\n\n\treturn digests, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage unsharded\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"vitess.io\/vitess\/go\/vt\/log\"\n\n\t\"github.com\/google\/go-cmp\/cmp\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\n\t\"vitess.io\/vitess\/go\/mysql\"\n\t\"vitess.io\/vitess\/go\/sqltypes\"\n\t\"vitess.io\/vitess\/go\/test\/endtoend\/cluster\"\n)\n\nvar (\n\tclusterInstance *cluster.LocalProcessCluster\n\tcell            = \"zone1\"\n\thostname        = \"localhost\"\n\tKeyspaceName    = \"customer\"\n\tSchemaSQL       = `\nCREATE TABLE t1 (\n    c1 BIGINT NOT NULL,\n    c2 BIGINT NOT NULL,\n    c3 BIGINT,\n    c4 varchar(100),\n    PRIMARY KEY (c1),\n    UNIQUE KEY (c2),\n    UNIQUE KEY (c3),\n    UNIQUE KEY (c4)\n) ENGINE=Innodb;\n\nCREATE TABLE allDefaults (\n  id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,\n  name VARCHAR(255)\n) ENGINE=Innodb;`\n\tVSchema = `\n{\n    \"sharded\": false,\n    \"tables\": {\n        \"t1\": {\n            \"columns\": [\n                {\n                    \"name\": \"c1\",\n                    \"type\": \"INT64\"\n                },\n                {\n                    \"name\": \"c2\",\n                    \"type\": \"INT64\"\n                },\n                {\n                    \"name\": \"c3\",\n                    \"type\": \"INT64\"\n                },\n                {\n                    \"name\": \"c4\",\n                    \"type\": \"VARCHAR\"\n                }\n            ]\n        },\n        \"allDefaults\": {\n            \"columns\": [\n                {\n                    \"name\": \"id\",\n                    \"type\": \"INT64\"\n                },\n                {\n                    \"name\": \"name\",\n                    \"type\": \"VARCHAR\"\n                }\n            ]\n        }\n    }\n}\n`\n\n\tcreateProcSQL = `use vt_customer;\nCREATE PROCEDURE sp_insert()\nBEGIN\n\tinsert into allDefaults () values ();\nEND;\n\nCREATE PROCEDURE sp_delete()\nBEGIN\n\tdelete from allDefaults;\nEND;\n\nCREATE PROCEDURE sp_multi_dml()\nBEGIN\n\tinsert into allDefaults () values ();\n\tdelete from allDefaults;\nEND;\n\nCREATE PROCEDURE sp_variable()\nBEGIN\n\tinsert into allDefaults () values ();\n\tSELECT min(id) INTO @myvar FROM allDefaults;\n\tDELETE FROM allDefaults WHERE id = @myvar;\nEND;\n\nCREATE PROCEDURE sp_select()\nBEGIN\n\tSELECT * FROM allDefaults;\nEND;\n\nCREATE PROCEDURE sp_all()\nBEGIN\n\tinsert into allDefaults () values ();\n    select * from allDefaults;\n\tdelete from allDefaults;\n    set autocommit = 0;\nEND;\n\nCREATE PROCEDURE in_parameter(IN val int)\nBEGIN\n\tinsert into allDefaults(id) values(val);\nEND;\n\nCREATE PROCEDURE out_parameter(OUT val int)\nBEGIN\n\tinsert into allDefaults(id) values (128);\n\tselect 128 into val from dual;\nEND;\n`\n)\n\nfunc TestMain(m *testing.M) {\n\tdefer cluster.PanicHandler(nil)\n\tflag.Parse()\n\n\texitCode := func() int {\n\t\tclusterInstance = cluster.NewCluster(cell, hostname)\n\t\tdefer clusterInstance.Teardown()\n\n\t\t\/\/ Start topo server\n\t\tif err := clusterInstance.StartTopo(); err != nil {\n\t\t\treturn 1\n\t\t}\n\n\t\t\/\/ Start keyspace\n\t\tKeyspace := &cluster.Keyspace{\n\t\t\tName:      KeyspaceName,\n\t\t\tSchemaSQL: SchemaSQL,\n\t\t\tVSchema:   VSchema,\n\t\t}\n\t\tif err := clusterInstance.StartUnshardedKeyspace(*Keyspace, 0, false); err != nil {\n\t\t\tlog.Fatal(err.Error())\n\t\t\treturn 1\n\t\t}\n\n\t\t\/\/ Start vtgate\n\t\tif err := clusterInstance.StartVtgate(); err != nil {\n\t\t\tlog.Fatal(err.Error())\n\t\t\treturn 1\n\t\t}\n\n\t\tmasterProcess := clusterInstance.Keyspaces[0].Shards[0].MasterTablet().VttabletProcess\n\t\tif _, err := masterProcess.QueryTablet(createProcSQL, KeyspaceName, false); err != nil {\n\t\t\tlog.Fatal(err.Error())\n\t\t\treturn 1\n\t\t}\n\n\t\treturn m.Run()\n\t}()\n\tos.Exit(exitCode)\n}\n\nfunc TestSelectIntoAndLoadFrom(t *testing.T) {\n\t\/\/ Test is skipped because it requires secure-file-priv variable to be set to not NULL or empty.\n\tt.Skip()\n\tdefer cluster.PanicHandler(t)\n\tctx := context.Background()\n\tvtParams := mysql.ConnParams{\n\t\tHost: \"localhost\",\n\t\tPort: clusterInstance.VtgateMySQLPort,\n\t}\n\tconn, err := mysql.Connect(ctx, &vtParams)\n\trequire.Nil(t, err)\n\tdefer conn.Close()\n\n\tdefer exec(t, conn, `delete from t1`)\n\texec(t, conn, `insert into t1(c1, c2, c3, c4) values (300,100,300,'abc')`)\n\tres := exec(t, conn, `select @@secure_file_priv;`)\n\tdirectory := res.Rows[0][0].ToString()\n\tquery := `select * from t1 into outfile '` + directory + `x.txt'`\n\texec(t, conn, query)\n\tdefer os.Remove(directory + `x.txt`)\n\tquery = `load data infile '` + directory + `x.txt' into table t1`\n\texecAssertError(t, conn, query, \"Duplicate entry '300' for key 'PRIMARY'\")\n\texec(t, conn, `delete from t1`)\n\texec(t, conn, query)\n\tassertMatches(t, conn, `select c1,c2,c3 from t1`, `[[INT64(300) INT64(100) INT64(300)]]`)\n\tquery = `select * from t1 into dumpfile '` + directory + `x1.txt'`\n\texec(t, conn, query)\n\tdefer os.Remove(directory + `x1.txt`)\n\tquery = `select * from t1 into outfile '` + directory + `x2.txt' Fields terminated by ';' optionally enclosed by '\"' escaped by '\\t' lines terminated by '\\n'`\n\texec(t, conn, query)\n\tdefer os.Remove(directory + `x2.txt`)\n\tquery = `load data infile '` + directory + `x2.txt' replace into table t1 Fields terminated by ';' optionally enclosed by '\"' escaped by '\\t' lines terminated by '\\n'`\n\texec(t, conn, query)\n\tassertMatches(t, conn, `select c1,c2,c3 from t1`, `[[INT64(300) INT64(100) INT64(300)]]`)\n}\n\nfunc TestEmptyStatement(t *testing.T) {\n\tdefer cluster.PanicHandler(t)\n\tctx := context.Background()\n\tvtParams := mysql.ConnParams{\n\t\tHost: \"localhost\",\n\t\tPort: clusterInstance.VtgateMySQLPort,\n\t}\n\tconn, err := mysql.Connect(ctx, &vtParams)\n\trequire.Nil(t, err)\n\tdefer conn.Close()\n\tdefer exec(t, conn, `delete from t1`)\n\texecAssertError(t, conn, \" \\t;\", \"Query was empty\")\n\texecMulti(t, conn, `insert into t1(c1, c2, c3, c4) values (300,100,300,'abc'); ;; insert into t1(c1, c2, c3, c4) values (301,101,301,'abcd');;`)\n\tassertMatches(t, conn, `select c1,c2,c3 from t1`, `[[INT64(300) INT64(100) INT64(300)] [INT64(301) INT64(101) INT64(301)]]`)\n}\n\nfunc TestInsertAllDefaults(t *testing.T) {\n\tdefer cluster.PanicHandler(t)\n\tctx := context.Background()\n\tvtParams := mysql.ConnParams{\n\t\tHost: \"localhost\",\n\t\tPort: clusterInstance.VtgateMySQLPort,\n\t}\n\tconn, err := mysql.Connect(ctx, &vtParams)\n\trequire.NoError(t, err)\n\tdefer conn.Close()\n\n\texec(t, conn, `insert into allDefaults () values ()`)\n\tassertMatches(t, conn, `select * from allDefaults`, \"[[INT64(1) NULL]]\")\n}\n\nfunc TestDDLUnsharded(t *testing.T) {\n\tdefer cluster.PanicHandler(t)\n\tctx := context.Background()\n\tvtParams := mysql.ConnParams{\n\t\tHost: \"localhost\",\n\t\tPort: clusterInstance.VtgateMySQLPort,\n\t}\n\tconn, err := mysql.Connect(ctx, &vtParams)\n\trequire.NoError(t, err)\n\tdefer conn.Close()\n\n\texec(t, conn, `create table tempt1(c1 BIGINT NOT NULL,c2 BIGINT NOT NULL,c3 BIGINT,c4 varchar(100),PRIMARY KEY (c1), UNIQUE KEY (c2),UNIQUE KEY (c3), UNIQUE KEY (c4))`)\n\t\/\/ Test that create view works and the output is as expected\n\texec(t, conn, `create view v1 as select * from tempt1`)\n\texec(t, conn, `insert into tempt1(c1, c2, c3, c4) values (300,100,300,'abc'),(30,10,30,'ac'),(3,0,3,'a')`)\n\tassertMatches(t, conn, \"select * from v1\", `[[INT64(3) INT64(0) INT64(3) VARCHAR(\"a\")] [INT64(30) INT64(10) INT64(30) VARCHAR(\"ac\")] [INT64(300) INT64(100) INT64(300) VARCHAR(\"abc\")]]`)\n\texec(t, conn, `drop view v1`)\n\texec(t, conn, `drop table tempt1`)\n\tassertMatches(t, conn, \"show tables\", `[[VARCHAR(\"allDefaults\")] [VARCHAR(\"t1\")]]`)\n}\n\nfunc TestCallProcedure(t *testing.T) {\n\tdefer cluster.PanicHandler(t)\n\tctx := context.Background()\n\tvtParams := mysql.ConnParams{\n\t\tHost:   \"localhost\",\n\t\tPort:   clusterInstance.VtgateMySQLPort,\n\t\tFlags:  mysql.CapabilityClientMultiResults,\n\t\tDbName: \"@master\",\n\t}\n\ttime.Sleep(5 * time.Second)\n\tconn, err := mysql.Connect(ctx, &vtParams)\n\trequire.NoError(t, err)\n\tdefer conn.Close()\n\tqr := exec(t, conn, `CALL sp_insert()`)\n\trequire.EqualValues(t, 1, qr.RowsAffected)\n\n\t_, err = conn.ExecuteFetch(`CALL sp_select()`, 1000, true)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"Multi-Resultset not supported in stored procedure\")\n\n\t_, err = conn.ExecuteFetch(`CALL sp_all()`, 1000, true)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"Multi-Resultset not supported in stored procedure\")\n\n\tqr = exec(t, conn, `CALL sp_delete()`)\n\trequire.GreaterOrEqual(t, 1, int(qr.RowsAffected))\n\n\tqr = exec(t, conn, `CALL sp_multi_dml()`)\n\trequire.EqualValues(t, 1, qr.RowsAffected)\n\n\tqr = exec(t, conn, `CALL sp_variable()`)\n\trequire.EqualValues(t, 1, qr.RowsAffected)\n\n\tqr = exec(t, conn, `CALL in_parameter(42)`)\n\trequire.EqualValues(t, 1, qr.RowsAffected)\n\n\t_ = exec(t, conn, `SET @foo = 123`)\n\tqr = exec(t, conn, `CALL in_parameter(@foo)`)\n\trequire.EqualValues(t, 1, qr.RowsAffected)\n\tqr = exec(t, conn, \"select * from allDefaults where id = 123\")\n\tassert.NotEmpty(t, qr.Rows)\n\n\t_, err = conn.ExecuteFetch(`CALL out_parameter(@foo)`, 100, true)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"OUT and INOUT parameters are not supported\")\n}\n\nfunc exec(t *testing.T, conn *mysql.Conn, query string) *sqltypes.Result {\n\tt.Helper()\n\tqr, err := conn.ExecuteFetch(query, 1000, true)\n\trequire.NoError(t, err)\n\treturn qr\n}\n\nfunc execMulti(t *testing.T, conn *mysql.Conn, query string) []*sqltypes.Result {\n\tt.Helper()\n\tvar res []*sqltypes.Result\n\tqr, more, err := conn.ExecuteFetchMulti(query, 1000, true)\n\tres = append(res, qr)\n\trequire.NoError(t, err)\n\tfor more == true {\n\t\tqr, more, _, err = conn.ReadQueryResult(1000, true)\n\t\trequire.NoError(t, err)\n\t\tres = append(res, qr)\n\t}\n\treturn res\n}\n\nfunc execAssertError(t *testing.T, conn *mysql.Conn, query string, errorString string) {\n\tt.Helper()\n\t_, err := conn.ExecuteFetch(query, 1000, true)\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), errorString)\n}\n\nfunc assertMatches(t *testing.T, conn *mysql.Conn, query, expected string) {\n\tt.Helper()\n\tqr := exec(t, conn, query)\n\tgot := fmt.Sprintf(\"%v\", qr.Rows)\n\tdiff := cmp.Diff(expected, got)\n\tif diff != \"\" {\n\t\tt.Errorf(\"Query: %s (-want +got):\\n%s\", query, diff)\n\t}\n}\n<commit_msg>added e2e test<commit_after>\/*\nCopyright 2020 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage unsharded\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"vitess.io\/vitess\/go\/vt\/log\"\n\n\t\"github.com\/google\/go-cmp\/cmp\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\n\t\"vitess.io\/vitess\/go\/mysql\"\n\t\"vitess.io\/vitess\/go\/sqltypes\"\n\t\"vitess.io\/vitess\/go\/test\/endtoend\/cluster\"\n)\n\nvar (\n\tclusterInstance *cluster.LocalProcessCluster\n\tcell            = \"zone1\"\n\thostname        = \"localhost\"\n\tKeyspaceName    = \"customer\"\n\tSchemaSQL       = `\nCREATE TABLE t1 (\n    c1 BIGINT NOT NULL,\n    c2 BIGINT NOT NULL,\n    c3 BIGINT,\n    c4 varchar(100),\n    PRIMARY KEY (c1),\n    UNIQUE KEY (c2),\n    UNIQUE KEY (c3),\n    UNIQUE KEY (c4)\n) ENGINE=Innodb;\n\nCREATE TABLE allDefaults (\n  id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,\n  name VARCHAR(255)\n) ENGINE=Innodb;`\n\tVSchema = `\n{\n    \"sharded\": false,\n    \"tables\": {\n        \"t1\": {\n            \"columns\": [\n                {\n                    \"name\": \"c1\",\n                    \"type\": \"INT64\"\n                },\n                {\n                    \"name\": \"c2\",\n                    \"type\": \"INT64\"\n                },\n                {\n                    \"name\": \"c3\",\n                    \"type\": \"INT64\"\n                },\n                {\n                    \"name\": \"c4\",\n                    \"type\": \"VARCHAR\"\n                }\n            ]\n        },\n        \"allDefaults\": {\n            \"columns\": [\n                {\n                    \"name\": \"id\",\n                    \"type\": \"INT64\"\n                },\n                {\n                    \"name\": \"name\",\n                    \"type\": \"VARCHAR\"\n                }\n            ]\n        }\n    }\n}\n`\n\n\tcreateProcSQL = `use vt_customer;\nCREATE PROCEDURE sp_insert()\nBEGIN\n\tinsert into allDefaults () values ();\nEND;\n\nCREATE PROCEDURE sp_delete()\nBEGIN\n\tdelete from allDefaults;\nEND;\n\nCREATE PROCEDURE sp_multi_dml()\nBEGIN\n\tinsert into allDefaults () values ();\n\tdelete from allDefaults;\nEND;\n\nCREATE PROCEDURE sp_variable()\nBEGIN\n\tinsert into allDefaults () values ();\n\tSELECT min(id) INTO @myvar FROM allDefaults;\n\tDELETE FROM allDefaults WHERE id = @myvar;\nEND;\n\nCREATE PROCEDURE sp_select()\nBEGIN\n\tSELECT * FROM allDefaults;\nEND;\n\nCREATE PROCEDURE sp_all()\nBEGIN\n\tinsert into allDefaults () values ();\n    select * from allDefaults;\n\tdelete from allDefaults;\n    set autocommit = 0;\nEND;\n\nCREATE PROCEDURE in_parameter(IN val int)\nBEGIN\n\tinsert into allDefaults(id) values(val);\nEND;\n\nCREATE PROCEDURE out_parameter(OUT val int)\nBEGIN\n\tinsert into allDefaults(id) values (128);\n\tselect 128 into val from dual;\nEND;\n`\n)\n\nfunc TestMain(m *testing.M) {\n\tdefer cluster.PanicHandler(nil)\n\tflag.Parse()\n\n\texitCode := func() int {\n\t\tclusterInstance = cluster.NewCluster(cell, hostname)\n\t\tdefer clusterInstance.Teardown()\n\n\t\t\/\/ Start topo server\n\t\tif err := clusterInstance.StartTopo(); err != nil {\n\t\t\treturn 1\n\t\t}\n\n\t\t\/\/ Start keyspace\n\t\tKeyspace := &cluster.Keyspace{\n\t\t\tName:      KeyspaceName,\n\t\t\tSchemaSQL: SchemaSQL,\n\t\t\tVSchema:   VSchema,\n\t\t}\n\t\tif err := clusterInstance.StartUnshardedKeyspace(*Keyspace, 0, false); err != nil {\n\t\t\tlog.Fatal(err.Error())\n\t\t\treturn 1\n\t\t}\n\n\t\t\/\/ Start vtgate\n\t\tif err := clusterInstance.StartVtgate(); err != nil {\n\t\t\tlog.Fatal(err.Error())\n\t\t\treturn 1\n\t\t}\n\n\t\tmasterProcess := clusterInstance.Keyspaces[0].Shards[0].MasterTablet().VttabletProcess\n\t\tif _, err := masterProcess.QueryTablet(createProcSQL, KeyspaceName, false); err != nil {\n\t\t\tlog.Fatal(err.Error())\n\t\t\treturn 1\n\t\t}\n\n\t\treturn m.Run()\n\t}()\n\tos.Exit(exitCode)\n}\n\nfunc TestSelectIntoAndLoadFrom(t *testing.T) {\n\t\/\/ Test is skipped because it requires secure-file-priv variable to be set to not NULL or empty.\n\tt.Skip()\n\tdefer cluster.PanicHandler(t)\n\tctx := context.Background()\n\tvtParams := mysql.ConnParams{\n\t\tHost: \"localhost\",\n\t\tPort: clusterInstance.VtgateMySQLPort,\n\t}\n\tconn, err := mysql.Connect(ctx, &vtParams)\n\trequire.Nil(t, err)\n\tdefer conn.Close()\n\n\tdefer exec(t, conn, `delete from t1`)\n\texec(t, conn, `insert into t1(c1, c2, c3, c4) values (300,100,300,'abc')`)\n\tres := exec(t, conn, `select @@secure_file_priv;`)\n\tdirectory := res.Rows[0][0].ToString()\n\tquery := `select * from t1 into outfile '` + directory + `x.txt'`\n\texec(t, conn, query)\n\tdefer os.Remove(directory + `x.txt`)\n\tquery = `load data infile '` + directory + `x.txt' into table t1`\n\texecAssertError(t, conn, query, \"Duplicate entry '300' for key 'PRIMARY'\")\n\texec(t, conn, `delete from t1`)\n\texec(t, conn, query)\n\tassertMatches(t, conn, `select c1,c2,c3 from t1`, `[[INT64(300) INT64(100) INT64(300)]]`)\n\tquery = `select * from t1 into dumpfile '` + directory + `x1.txt'`\n\texec(t, conn, query)\n\tdefer os.Remove(directory + `x1.txt`)\n\tquery = `select * from t1 into outfile '` + directory + `x2.txt' Fields terminated by ';' optionally enclosed by '\"' escaped by '\\t' lines terminated by '\\n'`\n\texec(t, conn, query)\n\tdefer os.Remove(directory + `x2.txt`)\n\tquery = `load data infile '` + directory + `x2.txt' replace into table t1 Fields terminated by ';' optionally enclosed by '\"' escaped by '\\t' lines terminated by '\\n'`\n\texec(t, conn, query)\n\tassertMatches(t, conn, `select c1,c2,c3 from t1`, `[[INT64(300) INT64(100) INT64(300)]]`)\n}\n\nfunc TestEmptyStatement(t *testing.T) {\n\tdefer cluster.PanicHandler(t)\n\tctx := context.Background()\n\tvtParams := mysql.ConnParams{\n\t\tHost: \"localhost\",\n\t\tPort: clusterInstance.VtgateMySQLPort,\n\t}\n\tconn, err := mysql.Connect(ctx, &vtParams)\n\trequire.Nil(t, err)\n\tdefer conn.Close()\n\tdefer exec(t, conn, `delete from t1`)\n\texecAssertError(t, conn, \" \\t;\", \"Query was empty\")\n\texecMulti(t, conn, `insert into t1(c1, c2, c3, c4) values (300,100,300,'abc'); ;; insert into t1(c1, c2, c3, c4) values (301,101,301,'abcd');;`)\n\tassertMatches(t, conn, `select c1,c2,c3 from t1`, `[[INT64(300) INT64(100) INT64(300)] [INT64(301) INT64(101) INT64(301)]]`)\n}\n\nfunc TestInsertAllDefaults(t *testing.T) {\n\tdefer cluster.PanicHandler(t)\n\tctx := context.Background()\n\tvtParams := mysql.ConnParams{\n\t\tHost: \"localhost\",\n\t\tPort: clusterInstance.VtgateMySQLPort,\n\t}\n\tconn, err := mysql.Connect(ctx, &vtParams)\n\trequire.NoError(t, err)\n\tdefer conn.Close()\n\n\texec(t, conn, `insert into allDefaults () values ()`)\n\tassertMatches(t, conn, `select * from allDefaults`, \"[[INT64(1) NULL]]\")\n}\n\nfunc TestDDLUnsharded(t *testing.T) {\n\tdefer cluster.PanicHandler(t)\n\tctx := context.Background()\n\tvtParams := mysql.ConnParams{\n\t\tHost: \"localhost\",\n\t\tPort: clusterInstance.VtgateMySQLPort,\n\t}\n\tconn, err := mysql.Connect(ctx, &vtParams)\n\trequire.NoError(t, err)\n\tdefer conn.Close()\n\n\texec(t, conn, `create table tempt1(c1 BIGINT NOT NULL,c2 BIGINT NOT NULL,c3 BIGINT,c4 varchar(100),PRIMARY KEY (c1), UNIQUE KEY (c2),UNIQUE KEY (c3), UNIQUE KEY (c4))`)\n\t\/\/ Test that create view works and the output is as expected\n\texec(t, conn, `create view v1 as select * from tempt1`)\n\texec(t, conn, `insert into tempt1(c1, c2, c3, c4) values (300,100,300,'abc'),(30,10,30,'ac'),(3,0,3,'a')`)\n\tassertMatches(t, conn, \"select * from v1\", `[[INT64(3) INT64(0) INT64(3) VARCHAR(\"a\")] [INT64(30) INT64(10) INT64(30) VARCHAR(\"ac\")] [INT64(300) INT64(100) INT64(300) VARCHAR(\"abc\")]]`)\n\texec(t, conn, `drop view v1`)\n\texec(t, conn, `drop table tempt1`)\n\tassertMatches(t, conn, \"show tables\", `[[VARCHAR(\"allDefaults\")] [VARCHAR(\"t1\")]]`)\n}\n\nfunc TestCallProcedure(t *testing.T) {\n\tdefer cluster.PanicHandler(t)\n\tctx := context.Background()\n\tvtParams := mysql.ConnParams{\n\t\tHost:   \"localhost\",\n\t\tPort:   clusterInstance.VtgateMySQLPort,\n\t\tFlags:  mysql.CapabilityClientMultiResults,\n\t\tDbName: \"@master\",\n\t}\n\ttime.Sleep(5 * time.Second)\n\tconn, err := mysql.Connect(ctx, &vtParams)\n\trequire.NoError(t, err)\n\tdefer conn.Close()\n\tqr := exec(t, conn, `CALL sp_insert()`)\n\trequire.EqualValues(t, 1, qr.RowsAffected)\n\n\t_, err = conn.ExecuteFetch(`CALL sp_select()`, 1000, true)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"Multi-Resultset not supported in stored procedure\")\n\n\t_, err = conn.ExecuteFetch(`CALL sp_all()`, 1000, true)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"Multi-Resultset not supported in stored procedure\")\n\n\tqr = exec(t, conn, `CALL sp_delete()`)\n\trequire.GreaterOrEqual(t, 1, int(qr.RowsAffected))\n\n\tqr = exec(t, conn, `CALL sp_multi_dml()`)\n\trequire.EqualValues(t, 1, qr.RowsAffected)\n\n\tqr = exec(t, conn, `CALL sp_variable()`)\n\trequire.EqualValues(t, 1, qr.RowsAffected)\n\n\tqr = exec(t, conn, `CALL in_parameter(42)`)\n\trequire.EqualValues(t, 1, qr.RowsAffected)\n\n\t_ = exec(t, conn, `SET @foo = 123`)\n\tqr = exec(t, conn, `CALL in_parameter(@foo)`)\n\trequire.EqualValues(t, 1, qr.RowsAffected)\n\tqr = exec(t, conn, \"select * from allDefaults where id = 123\")\n\tassert.NotEmpty(t, qr.Rows)\n\n\t_, err = conn.ExecuteFetch(`CALL out_parameter(@foo)`, 100, true)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"OUT and INOUT parameters are not supported\")\n}\n\nfunc TestTempTable(t *testing.T) {\n\tdefer cluster.PanicHandler(t)\n\tctx := context.Background()\n\tvtParams := mysql.ConnParams{\n\t\tHost: \"localhost\",\n\t\tPort: clusterInstance.VtgateMySQLPort,\n\t}\n\tconn1, err := mysql.Connect(ctx, &vtParams)\n\trequire.NoError(t, err)\n\tdefer conn1.Close()\n\n\t_ = exec(t, conn1, `create temporary table temp_t(id bigint primary key)`)\n\t_ = exec(t, conn1, `insert into temp_t(id) values (1),(2),(3)`)\n\t\/\/\tassertMatches(t, conn1, `select id from temp_t order by id`, `[[INT64(1)] [INT64(2)] [INT64(3)]]`)\n\tassertMatches(t, conn1, `select count(table_id) from information_schema.innodb_temp_table_info`, `[[INT64(1)]]`)\n\n\tconn2, err := mysql.Connect(ctx, &vtParams)\n\trequire.NoError(t, err)\n\tdefer conn2.Close()\n\n\tassertMatches(t, conn2, `select count(table_id) from information_schema.innodb_temp_table_info`, `[[INT64(1)]]`)\n\texecAssertError(t, conn2, `show create table temp_t`, `Table 'vt_customer.temp_t' doesn't exist (errno 1146) (sqlstate 42S02)`)\n}\n\nfunc exec(t *testing.T, conn *mysql.Conn, query string) *sqltypes.Result {\n\tt.Helper()\n\tqr, err := conn.ExecuteFetch(query, 1000, true)\n\trequire.NoError(t, err)\n\treturn qr\n}\n\nfunc execMulti(t *testing.T, conn *mysql.Conn, query string) []*sqltypes.Result {\n\tt.Helper()\n\tvar res []*sqltypes.Result\n\tqr, more, err := conn.ExecuteFetchMulti(query, 1000, true)\n\tres = append(res, qr)\n\trequire.NoError(t, err)\n\tfor more == true {\n\t\tqr, more, _, err = conn.ReadQueryResult(1000, true)\n\t\trequire.NoError(t, err)\n\t\tres = append(res, qr)\n\t}\n\treturn res\n}\n\nfunc execAssertError(t *testing.T, conn *mysql.Conn, query string, errorString string) {\n\tt.Helper()\n\t_, err := conn.ExecuteFetch(query, 1000, true)\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), errorString)\n}\n\nfunc assertMatches(t *testing.T, conn *mysql.Conn, query, expected string) {\n\tt.Helper()\n\tqr := exec(t, conn, query)\n\tgot := fmt.Sprintf(\"%v\", qr.Rows)\n\tdiff := cmp.Diff(expected, got)\n\tif diff != \"\" {\n\t\tt.Errorf(\"Query: %s (-want +got):\\n%s\", query, diff)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package flannel\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/rancher\/k3s\/pkg\/agent\/util\"\n\t\"github.com\/rancher\/k3s\/pkg\/daemons\/config\"\n\t\"github.com\/sirupsen\/logrus\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\tv1 \"k8s.io\/client-go\/kubernetes\/typed\/core\/v1\"\n)\n\nconst (\n\tcniConf = `{\n  \"name\":\"cbr0\",\n  \"cniVersion\":\"0.3.1\",\n  \"plugins\":[\n    {\n      \"type\":\"flannel\",\n      \"delegate\":{\n        \"hairpinMode\":true,\n        \"forceAddress\":true,\n        \"isDefaultGateway\":true\n      }\n    },\n    {\n      \"type\":\"portmap\",\n      \"capabilities\":{\n        \"portMappings\":true\n      }\n    }\n  ]\n}\n`\n\n\tflannelConf = `{\n\t\"Network\": \"%CIDR%\",\n\t\"Backend\": %backend%\n}\n`\n\n\tvxlanBackend = `{\n\t\"Type\": \"vxlan\"\n}`\n\n\tipsecBackend = `{\n\t\"Type\": \"ipsec\",\n\t\"UDPEncap\": true,\n\t\"PSK\": \"%psk%\"\n}`\n\n\twireguardBackend = `{\n\t\"Type\": \"extension\",\n\t\"PreStartupCommand\": \"wg genkey | tee privatekey | wg pubkey\",\n\t\"PostStartupCommand\": \"export SUBNET_IP=$(echo $SUBNET | cut -d'\/' -f 1); ip link del flannel.1 2>\/dev\/null; echo $PATH >&2; wg-add.sh flannel.1 && wg set flannel.1 listen-port 51820 private-key privatekey persistent-keepalive 25 && ip addr add $SUBNET_IP\/32 dev flannel.1 && ip link set flannel.1 up && ip route add $NETWORK dev flannel.1\",\n\t\"ShutdownCommand\": \"ip link del flannel.1\",\n\t\"SubnetAddCommand\": \"read PUBLICKEY; wg set flannel.1 peer $PUBLICKEY endpoint $PUBLIC_IP:51820 allowed-ips $SUBNET\",\n\t\"SubnetRemoveCommand\": \"read PUBLICKEY; wg set flannel.1 peer $PUBLICKEY remove\"\n}`\n)\n\nfunc Prepare(ctx context.Context, nodeConfig *config.Node) error {\n\tif err := createCNIConf(nodeConfig.AgentConfig.CNIConfDir); err != nil {\n\t\treturn err\n\t}\n\n\treturn createFlannelConf(nodeConfig)\n}\n\nfunc Run(ctx context.Context, nodeConfig *config.Node, nodes v1.NodeInterface) error {\n\tnodeName := nodeConfig.AgentConfig.NodeName\n\n\tfor {\n\t\tnode, err := nodes.Get(nodeName, metav1.GetOptions{})\n\t\tif err == nil && node.Spec.PodCIDR != \"\" {\n\t\t\tbreak\n\t\t}\n\t\tif err == nil {\n\t\t\tlogrus.Infof(\"waiting for node %s CIDR not assigned yet\", nodeName)\n\t\t} else {\n\t\t\tlogrus.Infof(\"waiting for node %s: %v\", nodeName, err)\n\t\t}\n\t\ttime.Sleep(2 * time.Second)\n\t}\n\n\tgo func() {\n\t\terr := flannel(ctx, nodeConfig.FlannelIface, nodeConfig.FlannelConf, nodeConfig.AgentConfig.KubeConfigKubelet)\n\t\tlogrus.Fatalf(\"flannel exited: %v\", err)\n\t}()\n\n\treturn nil\n}\n\nfunc createCNIConf(dir string) error {\n\tif dir == \"\" {\n\t\treturn nil\n\t}\n\tp := filepath.Join(dir, \"10-flannel.conflist\")\n\treturn util.WriteFile(p, cniConf)\n}\n\nfunc createFlannelConf(nodeConfig *config.Node) error {\n\tif nodeConfig.FlannelConf == \"\" {\n\t\treturn nil\n\t}\n\tif nodeConfig.FlannelConfOverride {\n\t\tlogrus.Infof(\"Using custom flannel conf defined at %s\", nodeConfig.FlannelConf)\n\t\treturn nil\n\t}\n\tconfJSON := strings.Replace(flannelConf, \"%CIDR%\", nodeConfig.AgentConfig.ClusterCIDR.String(), -1)\n\n\tvar backendConf string\n\n\tswitch nodeConfig.FlannelBackend {\n\tcase config.FlannelBackendVXLAN:\n\t\tbackendConf = vxlanBackend\n\tcase config.FlannelBackendIPSEC:\n\t\tbackendConf = strings.Replace(ipsecBackend, \"%psk%\", nodeConfig.AgentConfig.IPSECPSK, -1)\n\t\tif err := setupStrongSwan(nodeConfig); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase config.FlannelBackendWireguard:\n\t\tbackendConf = wireguardBackend\n\tdefault:\n\t\treturn fmt.Errorf(\"Cannot configure unknown flannel backend '%s'\", nodeConfig.FlannelBackend)\n\t}\n\tconfJSON = strings.Replace(confJSON, \"%backend%\", backendConf, -1)\n\n\treturn util.WriteFile(nodeConfig.FlannelConf, confJSON)\n}\n\nfunc setupStrongSwan(nodeConfig *config.Node) error {\n\t\/\/ if data dir env is not set point to root\n\tdataDir := os.Getenv(\"K3S_DATA_DIR\")\n\tif dataDir == \"\" {\n\t\tdataDir = \"\/\"\n\t}\n\tdataDir = path.Join(dataDir, \"etc\", \"strongswan\")\n\n\tinfo, err := os.Lstat(nodeConfig.AgentConfig.StrongSwanDir)\n\t\/\/ something exists but is not a symlink, return\n\tif err == nil && info.Mode()&os.ModeSymlink == 0 {\n\t\treturn nil\n\t}\n\tif err == nil {\n\t\ttarget, err := os.Readlink(nodeConfig.AgentConfig.StrongSwanDir)\n\t\t\/\/ current link is the same, return\n\t\tif err == nil && target == dataDir {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t\/\/ clean up strongswan old link\n\tos.Remove(nodeConfig.AgentConfig.StrongSwanDir)\n\n\t\/\/ make new strongswan link\n\treturn os.Symlink(dataDir, nodeConfig.AgentConfig.StrongSwanDir)\n}\n<commit_msg>Revert \"Merge pull request #1190 from erikwilson\/wireguard-keepalive\"<commit_after>package flannel\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/rancher\/k3s\/pkg\/agent\/util\"\n\t\"github.com\/rancher\/k3s\/pkg\/daemons\/config\"\n\t\"github.com\/sirupsen\/logrus\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\tv1 \"k8s.io\/client-go\/kubernetes\/typed\/core\/v1\"\n)\n\nconst (\n\tcniConf = `{\n  \"name\":\"cbr0\",\n  \"cniVersion\":\"0.3.1\",\n  \"plugins\":[\n    {\n      \"type\":\"flannel\",\n      \"delegate\":{\n        \"hairpinMode\":true,\n        \"forceAddress\":true,\n        \"isDefaultGateway\":true\n      }\n    },\n    {\n      \"type\":\"portmap\",\n      \"capabilities\":{\n        \"portMappings\":true\n      }\n    }\n  ]\n}\n`\n\n\tflannelConf = `{\n\t\"Network\": \"%CIDR%\",\n\t\"Backend\": %backend%\n}\n`\n\n\tvxlanBackend = `{\n\t\"Type\": \"vxlan\"\n}`\n\n\tipsecBackend = `{\n\t\"Type\": \"ipsec\",\n\t\"UDPEncap\": true,\n\t\"PSK\": \"%psk%\"\n}`\n\n\twireguardBackend = `{\n\t\"Type\": \"extension\",\n\t\"PreStartupCommand\": \"wg genkey | tee privatekey | wg pubkey\",\n\t\"PostStartupCommand\": \"export SUBNET_IP=$(echo $SUBNET | cut -d'\/' -f 1); ip link del flannel.1 2>\/dev\/null; echo $PATH >&2; wg-add.sh flannel.1 && wg set flannel.1 listen-port 51820 private-key privatekey && ip addr add $SUBNET_IP\/32 dev flannel.1 && ip link set flannel.1 up && ip route add $NETWORK dev flannel.1\",\n\t\"ShutdownCommand\": \"ip link del flannel.1\",\n\t\"SubnetAddCommand\": \"read PUBLICKEY; wg set flannel.1 peer $PUBLICKEY endpoint $PUBLIC_IP:51820 allowed-ips $SUBNET\",\n\t\"SubnetRemoveCommand\": \"read PUBLICKEY; wg set flannel.1 peer $PUBLICKEY remove\"\n}`\n)\n\nfunc Prepare(ctx context.Context, nodeConfig *config.Node) error {\n\tif err := createCNIConf(nodeConfig.AgentConfig.CNIConfDir); err != nil {\n\t\treturn err\n\t}\n\n\treturn createFlannelConf(nodeConfig)\n}\n\nfunc Run(ctx context.Context, nodeConfig *config.Node, nodes v1.NodeInterface) error {\n\tnodeName := nodeConfig.AgentConfig.NodeName\n\n\tfor {\n\t\tnode, err := nodes.Get(nodeName, metav1.GetOptions{})\n\t\tif err == nil && node.Spec.PodCIDR != \"\" {\n\t\t\tbreak\n\t\t}\n\t\tif err == nil {\n\t\t\tlogrus.Infof(\"waiting for node %s CIDR not assigned yet\", nodeName)\n\t\t} else {\n\t\t\tlogrus.Infof(\"waiting for node %s: %v\", nodeName, err)\n\t\t}\n\t\ttime.Sleep(2 * time.Second)\n\t}\n\n\tgo func() {\n\t\terr := flannel(ctx, nodeConfig.FlannelIface, nodeConfig.FlannelConf, nodeConfig.AgentConfig.KubeConfigKubelet)\n\t\tlogrus.Fatalf(\"flannel exited: %v\", err)\n\t}()\n\n\treturn nil\n}\n\nfunc createCNIConf(dir string) error {\n\tif dir == \"\" {\n\t\treturn nil\n\t}\n\tp := filepath.Join(dir, \"10-flannel.conflist\")\n\treturn util.WriteFile(p, cniConf)\n}\n\nfunc createFlannelConf(nodeConfig *config.Node) error {\n\tif nodeConfig.FlannelConf == \"\" {\n\t\treturn nil\n\t}\n\tif nodeConfig.FlannelConfOverride {\n\t\tlogrus.Infof(\"Using custom flannel conf defined at %s\", nodeConfig.FlannelConf)\n\t\treturn nil\n\t}\n\tconfJSON := strings.Replace(flannelConf, \"%CIDR%\", nodeConfig.AgentConfig.ClusterCIDR.String(), -1)\n\n\tvar backendConf string\n\n\tswitch nodeConfig.FlannelBackend {\n\tcase config.FlannelBackendVXLAN:\n\t\tbackendConf = vxlanBackend\n\tcase config.FlannelBackendIPSEC:\n\t\tbackendConf = strings.Replace(ipsecBackend, \"%psk%\", nodeConfig.AgentConfig.IPSECPSK, -1)\n\t\tif err := setupStrongSwan(nodeConfig); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase config.FlannelBackendWireguard:\n\t\tbackendConf = wireguardBackend\n\tdefault:\n\t\treturn fmt.Errorf(\"Cannot configure unknown flannel backend '%s'\", nodeConfig.FlannelBackend)\n\t}\n\tconfJSON = strings.Replace(confJSON, \"%backend%\", backendConf, -1)\n\n\treturn util.WriteFile(nodeConfig.FlannelConf, confJSON)\n}\n\nfunc setupStrongSwan(nodeConfig *config.Node) error {\n\t\/\/ if data dir env is not set point to root\n\tdataDir := os.Getenv(\"K3S_DATA_DIR\")\n\tif dataDir == \"\" {\n\t\tdataDir = \"\/\"\n\t}\n\tdataDir = path.Join(dataDir, \"etc\", \"strongswan\")\n\n\tinfo, err := os.Lstat(nodeConfig.AgentConfig.StrongSwanDir)\n\t\/\/ something exists but is not a symlink, return\n\tif err == nil && info.Mode()&os.ModeSymlink == 0 {\n\t\treturn nil\n\t}\n\tif err == nil {\n\t\ttarget, err := os.Readlink(nodeConfig.AgentConfig.StrongSwanDir)\n\t\t\/\/ current link is the same, return\n\t\tif err == nil && target == dataDir {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t\/\/ clean up strongswan old link\n\tos.Remove(nodeConfig.AgentConfig.StrongSwanDir)\n\n\t\/\/ make new strongswan link\n\treturn os.Symlink(dataDir, nodeConfig.AgentConfig.StrongSwanDir)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ +k8s:conversion-gen=k8s.io\/kubernetes\/pkg\/apis\/storage\n\/\/ +k8s:conversion-gen-external-types=k8s.io\/api\/storage\/v1\n\/\/ +groupName=storage.k8s.io\n\/\/ +k8s:defaulter-gen=TypeMeta\n\/\/ +k8s:defaulter-gen-input=..\/..\/..\/..\/vendor\/k8s.io\/api\/storage\/v1\n\npackage v1\n<commit_msg>Add canonical import paths to storage packages<commit_after>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ +k8s:conversion-gen=k8s.io\/kubernetes\/pkg\/apis\/storage\n\/\/ +k8s:conversion-gen-external-types=k8s.io\/api\/storage\/v1\n\/\/ +groupName=storage.k8s.io\n\/\/ +k8s:defaulter-gen=TypeMeta\n\/\/ +k8s:defaulter-gen-input=..\/..\/..\/..\/vendor\/k8s.io\/api\/storage\/v1\n\npackage v1 \/\/ import \"k8s.io\/kubernetes\/pkg\/apis\/storage\/v1\"\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage apiserver\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\/install\"\n\tv1 \"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\/v1\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\/v1beta1\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/client\/clientset\/clientset\"\n\texternalinformers \"k8s.io\/apiextensions-apiserver\/pkg\/client\/informers\/externalversions\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/controller\/apiapproval\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/controller\/establish\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/controller\/finalizer\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/controller\/nonstructuralschema\"\n\topenapicontroller \"k8s.io\/apiextensions-apiserver\/pkg\/controller\/openapi\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/controller\/status\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/registry\/customresourcedefinition\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/serializer\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n\t\"k8s.io\/apimachinery\/pkg\/version\"\n\t\"k8s.io\/apiserver\/pkg\/endpoints\/discovery\"\n\tgenericregistry \"k8s.io\/apiserver\/pkg\/registry\/generic\"\n\t\"k8s.io\/apiserver\/pkg\/registry\/rest\"\n\tgenericapiserver \"k8s.io\/apiserver\/pkg\/server\"\n\tserverstorage \"k8s.io\/apiserver\/pkg\/server\/storage\"\n\t\"k8s.io\/apiserver\/pkg\/util\/webhook\"\n)\n\nvar (\n\tScheme = runtime.NewScheme()\n\tCodecs = serializer.NewCodecFactory(Scheme)\n\n\t\/\/ if you modify this, make sure you update the crEncoder\n\tunversionedVersion = schema.GroupVersion{Group: \"\", Version: \"v1\"}\n\tunversionedTypes   = []runtime.Object{\n\t\t&metav1.Status{},\n\t\t&metav1.WatchEvent{},\n\t\t&metav1.APIVersions{},\n\t\t&metav1.APIGroupList{},\n\t\t&metav1.APIGroup{},\n\t\t&metav1.APIResourceList{},\n\t}\n)\n\nfunc init() {\n\tinstall.Install(Scheme)\n\n\t\/\/ we need to add the options to empty v1\n\tmetav1.AddToGroupVersion(Scheme, schema.GroupVersion{Group: \"\", Version: \"v1\"})\n\n\tScheme.AddUnversionedTypes(unversionedVersion, unversionedTypes...)\n}\n\ntype ExtraConfig struct {\n\tCRDRESTOptionsGetter genericregistry.RESTOptionsGetter\n\n\t\/\/ MasterCount is used to detect whether cluster is HA, and if it is\n\t\/\/ the CRD Establishing will be hold by 5 seconds.\n\tMasterCount int\n\n\t\/\/ ServiceResolver is used in CR webhook converters to resolve webhook's service names\n\tServiceResolver webhook.ServiceResolver\n\t\/\/ AuthResolverWrapper is used in CR webhook converters\n\tAuthResolverWrapper webhook.AuthenticationInfoResolverWrapper\n}\n\ntype Config struct {\n\tGenericConfig *genericapiserver.RecommendedConfig\n\tExtraConfig   ExtraConfig\n}\n\ntype completedConfig struct {\n\tGenericConfig genericapiserver.CompletedConfig\n\tExtraConfig   *ExtraConfig\n}\n\ntype CompletedConfig struct {\n\t\/\/ Embed a private pointer that cannot be instantiated outside of this package.\n\t*completedConfig\n}\n\ntype CustomResourceDefinitions struct {\n\tGenericAPIServer *genericapiserver.GenericAPIServer\n\n\t\/\/ provided for easier embedding\n\tInformers externalinformers.SharedInformerFactory\n}\n\n\/\/ Complete fills in any fields not set that are required to have valid data. It's mutating the receiver.\nfunc (cfg *Config) Complete() CompletedConfig {\n\tc := completedConfig{\n\t\tcfg.GenericConfig.Complete(),\n\t\t&cfg.ExtraConfig,\n\t}\n\n\tc.GenericConfig.EnableDiscovery = false\n\tc.GenericConfig.Version = &version.Info{\n\t\tMajor: \"0\",\n\t\tMinor: \"1\",\n\t}\n\n\treturn CompletedConfig{&c}\n}\n\n\/\/ New returns a new instance of CustomResourceDefinitions from the given config.\nfunc (c completedConfig) New(delegationTarget genericapiserver.DelegationTarget) (*CustomResourceDefinitions, error) {\n\tgenericServer, err := c.GenericConfig.New(\"apiextensions-apiserver\", delegationTarget)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := &CustomResourceDefinitions{\n\t\tGenericAPIServer: genericServer,\n\t}\n\n\tapiResourceConfig := c.GenericConfig.MergedResourceConfig\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(apiextensions.GroupName, Scheme, metav1.ParameterCodec, Codecs)\n\tif apiResourceConfig.VersionEnabled(v1beta1.SchemeGroupVersion) {\n\t\tstorage := map[string]rest.Storage{}\n\t\t\/\/ customresourcedefinitions\n\t\tcustomResourceDefinitionStorage, err := customresourcedefinition.NewREST(Scheme, c.GenericConfig.RESTOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[\"customresourcedefinitions\"] = customResourceDefinitionStorage\n\t\tstorage[\"customresourcedefinitions\/status\"] = customresourcedefinition.NewStatusREST(Scheme, customResourceDefinitionStorage)\n\n\t\tapiGroupInfo.VersionedResourcesStorageMap[v1beta1.SchemeGroupVersion.Version] = storage\n\t}\n\tif apiResourceConfig.VersionEnabled(v1.SchemeGroupVersion) {\n\t\tstorage := map[string]rest.Storage{}\n\t\t\/\/ customresourcedefinitions\n\t\tcustomResourceDefinitionStorage, err := customresourcedefinition.NewREST(Scheme, c.GenericConfig.RESTOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[\"customresourcedefinitions\"] = customResourceDefinitionStorage\n\t\tstorage[\"customresourcedefinitions\/status\"] = customresourcedefinition.NewStatusREST(Scheme, customResourceDefinitionStorage)\n\n\t\tapiGroupInfo.VersionedResourcesStorageMap[v1.SchemeGroupVersion.Version] = storage\n\t}\n\n\tif err := s.GenericAPIServer.InstallAPIGroup(&apiGroupInfo); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcrdClient, err := clientset.NewForConfig(s.GenericAPIServer.LoopbackClientConfig)\n\tif err != nil {\n\t\t\/\/ it's really bad that this is leaking here, but until we can fix the test (which I'm pretty sure isn't even testing what it wants to test),\n\t\t\/\/ we need to be able to move forward\n\t\treturn nil, fmt.Errorf(\"failed to create clientset: %v\", err)\n\t}\n\ts.Informers = externalinformers.NewSharedInformerFactory(crdClient, 5*time.Minute)\n\n\tdelegateHandler := delegationTarget.UnprotectedHandler()\n\tif delegateHandler == nil {\n\t\tdelegateHandler = http.NotFoundHandler()\n\t}\n\n\tversionDiscoveryHandler := &versionDiscoveryHandler{\n\t\tdiscovery: map[schema.GroupVersion]*discovery.APIVersionHandler{},\n\t\tdelegate:  delegateHandler,\n\t}\n\tgroupDiscoveryHandler := &groupDiscoveryHandler{\n\t\tdiscovery: map[string]*discovery.APIGroupHandler{},\n\t\tdelegate:  delegateHandler,\n\t}\n\testablishingController := establish.NewEstablishingController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), crdClient.ApiextensionsV1())\n\tcrdHandler, err := NewCustomResourceDefinitionHandler(\n\t\tversionDiscoveryHandler,\n\t\tgroupDiscoveryHandler,\n\t\ts.Informers.Apiextensions().V1().CustomResourceDefinitions(),\n\t\tdelegateHandler,\n\t\tc.ExtraConfig.CRDRESTOptionsGetter,\n\t\tc.GenericConfig.AdmissionControl,\n\t\testablishingController,\n\t\tc.ExtraConfig.ServiceResolver,\n\t\tc.ExtraConfig.AuthResolverWrapper,\n\t\tc.ExtraConfig.MasterCount,\n\t\ts.GenericAPIServer.Authorizer,\n\t\tc.GenericConfig.RequestTimeout,\n\t\ttime.Duration(c.GenericConfig.MinRequestTimeout)*time.Second,\n\t\tapiGroupInfo.StaticOpenAPISpec,\n\t\tc.GenericConfig.MaxRequestBodyBytes,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.GenericAPIServer.Handler.NonGoRestfulMux.Handle(\"\/apis\", crdHandler)\n\ts.GenericAPIServer.Handler.NonGoRestfulMux.HandlePrefix(\"\/apis\/\", crdHandler)\n\n\tdiscoveryController := NewDiscoveryController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), versionDiscoveryHandler, groupDiscoveryHandler)\n\tnamingController := status.NewNamingConditionController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), crdClient.ApiextensionsV1())\n\tnonStructuralSchemaController := nonstructuralschema.NewConditionController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), crdClient.ApiextensionsV1())\n\tapiApprovalController := apiapproval.NewKubernetesAPIApprovalPolicyConformantConditionController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), crdClient.ApiextensionsV1())\n\tfinalizingController := finalizer.NewCRDFinalizer(\n\t\ts.Informers.Apiextensions().V1().CustomResourceDefinitions(),\n\t\tcrdClient.ApiextensionsV1(),\n\t\tcrdHandler,\n\t)\n\topenapiController := openapicontroller.NewController(s.Informers.Apiextensions().V1().CustomResourceDefinitions())\n\n\ts.GenericAPIServer.AddPostStartHookOrDie(\"start-apiextensions-informers\", func(context genericapiserver.PostStartHookContext) error {\n\t\ts.Informers.Start(context.StopCh)\n\t\treturn nil\n\t})\n\ts.GenericAPIServer.AddPostStartHookOrDie(\"start-apiextensions-controllers\", func(context genericapiserver.PostStartHookContext) error {\n\t\t\/\/ OpenAPIVersionedService and StaticOpenAPISpec are populated in generic apiserver PrepareRun().\n\t\t\/\/ Together they serve the \/openapi\/v2 endpoint on a generic apiserver. A generic apiserver may\n\t\t\/\/ choose to not enable OpenAPI by having null openAPIConfig, and thus OpenAPIVersionedService\n\t\t\/\/ and StaticOpenAPISpec are both null. In that case we don't run the CRD OpenAPI controller.\n\t\tif s.GenericAPIServer.OpenAPIVersionedService != nil && s.GenericAPIServer.StaticOpenAPISpec != nil {\n\t\t\tgo openapiController.Run(s.GenericAPIServer.StaticOpenAPISpec, s.GenericAPIServer.OpenAPIVersionedService, context.StopCh)\n\t\t}\n\n\t\tgo namingController.Run(context.StopCh)\n\t\tgo establishingController.Run(context.StopCh)\n\t\tgo nonStructuralSchemaController.Run(5, context.StopCh)\n\t\tgo apiApprovalController.Run(5, context.StopCh)\n\t\tgo finalizingController.Run(5, context.StopCh)\n\n\t\tdiscoverySyncedCh := make(chan struct{})\n\t\tgo discoveryController.Run(context.StopCh, discoverySyncedCh)\n\t\tselect {\n\t\tcase <-context.StopCh:\n\t\tcase <-discoverySyncedCh:\n\t\t}\n\n\t\treturn nil\n\t})\n\t\/\/ we don't want to report healthy until we can handle all CRDs that have already been registered.  Waiting for the informer\n\t\/\/ to sync makes sure that the lister will be valid before we begin.  There may still be races for CRDs added after startup,\n\t\/\/ but we won't go healthy until we can handle the ones already present.\n\ts.GenericAPIServer.AddPostStartHookOrDie(\"crd-informer-synced\", func(context genericapiserver.PostStartHookContext) error {\n\t\treturn wait.PollImmediateUntil(100*time.Millisecond, func() (bool, error) {\n\t\t\treturn s.Informers.Apiextensions().V1().CustomResourceDefinitions().Informer().HasSynced(), nil\n\t\t}, context.StopCh)\n\t})\n\n\treturn s, nil\n}\n\nfunc DefaultAPIResourceConfigSource() *serverstorage.ResourceConfig {\n\tret := serverstorage.NewResourceConfig()\n\t\/\/ NOTE: GroupVersions listed here will be enabled by default. Don't put alpha versions in the list.\n\tret.EnableVersions(\n\t\tv1beta1.SchemeGroupVersion,\n\t\tv1.SchemeGroupVersion,\n\t)\n\n\treturn ret\n}\n<commit_msg>conditionally serve beta<commit_after>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage apiserver\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\/install\"\n\tv1 \"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\/v1\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\/v1beta1\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/client\/clientset\/clientset\"\n\texternalinformers \"k8s.io\/apiextensions-apiserver\/pkg\/client\/informers\/externalversions\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/controller\/apiapproval\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/controller\/establish\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/controller\/finalizer\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/controller\/nonstructuralschema\"\n\topenapicontroller \"k8s.io\/apiextensions-apiserver\/pkg\/controller\/openapi\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/controller\/status\"\n\t\"k8s.io\/apiextensions-apiserver\/pkg\/registry\/customresourcedefinition\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/serializer\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n\t\"k8s.io\/apimachinery\/pkg\/version\"\n\t\"k8s.io\/apiserver\/pkg\/endpoints\/discovery\"\n\tgenericregistry \"k8s.io\/apiserver\/pkg\/registry\/generic\"\n\t\"k8s.io\/apiserver\/pkg\/registry\/rest\"\n\tgenericapiserver \"k8s.io\/apiserver\/pkg\/server\"\n\tserverstorage \"k8s.io\/apiserver\/pkg\/server\/storage\"\n\t\"k8s.io\/apiserver\/pkg\/util\/webhook\"\n)\n\nvar (\n\tScheme = runtime.NewScheme()\n\tCodecs = serializer.NewCodecFactory(Scheme)\n\n\t\/\/ if you modify this, make sure you update the crEncoder\n\tunversionedVersion = schema.GroupVersion{Group: \"\", Version: \"v1\"}\n\tunversionedTypes   = []runtime.Object{\n\t\t&metav1.Status{},\n\t\t&metav1.WatchEvent{},\n\t\t&metav1.APIVersions{},\n\t\t&metav1.APIGroupList{},\n\t\t&metav1.APIGroup{},\n\t\t&metav1.APIResourceList{},\n\t}\n)\n\nfunc init() {\n\tinstall.Install(Scheme)\n\n\t\/\/ we need to add the options to empty v1\n\tmetav1.AddToGroupVersion(Scheme, schema.GroupVersion{Group: \"\", Version: \"v1\"})\n\n\tScheme.AddUnversionedTypes(unversionedVersion, unversionedTypes...)\n}\n\ntype ExtraConfig struct {\n\tCRDRESTOptionsGetter genericregistry.RESTOptionsGetter\n\n\t\/\/ MasterCount is used to detect whether cluster is HA, and if it is\n\t\/\/ the CRD Establishing will be hold by 5 seconds.\n\tMasterCount int\n\n\t\/\/ ServiceResolver is used in CR webhook converters to resolve webhook's service names\n\tServiceResolver webhook.ServiceResolver\n\t\/\/ AuthResolverWrapper is used in CR webhook converters\n\tAuthResolverWrapper webhook.AuthenticationInfoResolverWrapper\n}\n\ntype Config struct {\n\tGenericConfig *genericapiserver.RecommendedConfig\n\tExtraConfig   ExtraConfig\n}\n\ntype completedConfig struct {\n\tGenericConfig genericapiserver.CompletedConfig\n\tExtraConfig   *ExtraConfig\n}\n\ntype CompletedConfig struct {\n\t\/\/ Embed a private pointer that cannot be instantiated outside of this package.\n\t*completedConfig\n}\n\ntype CustomResourceDefinitions struct {\n\tGenericAPIServer *genericapiserver.GenericAPIServer\n\n\t\/\/ provided for easier embedding\n\tInformers externalinformers.SharedInformerFactory\n}\n\n\/\/ Complete fills in any fields not set that are required to have valid data. It's mutating the receiver.\nfunc (cfg *Config) Complete() CompletedConfig {\n\tc := completedConfig{\n\t\tcfg.GenericConfig.Complete(),\n\t\t&cfg.ExtraConfig,\n\t}\n\n\tc.GenericConfig.EnableDiscovery = false\n\tc.GenericConfig.Version = &version.Info{\n\t\tMajor: \"0\",\n\t\tMinor: \"1\",\n\t}\n\n\treturn CompletedConfig{&c}\n}\n\n\/\/ New returns a new instance of CustomResourceDefinitions from the given config.\nfunc (c completedConfig) New(delegationTarget genericapiserver.DelegationTarget) (*CustomResourceDefinitions, error) {\n\tgenericServer, err := c.GenericConfig.New(\"apiextensions-apiserver\", delegationTarget)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := &CustomResourceDefinitions{\n\t\tGenericAPIServer: genericServer,\n\t}\n\n\t\/\/ used later  to filter the served resource by those that have expired.\n\tresourceExpirationEvaluator, err := genericapiserver.NewResourceExpirationEvaluator(*c.GenericConfig.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tapiResourceConfig := c.GenericConfig.MergedResourceConfig\n\tapiGroupInfo := genericapiserver.NewDefaultAPIGroupInfo(apiextensions.GroupName, Scheme, metav1.ParameterCodec, Codecs)\n\tif resourceExpirationEvaluator.ShouldServeForVersion(1, 22) && apiResourceConfig.VersionEnabled(v1beta1.SchemeGroupVersion) {\n\t\tstorage := map[string]rest.Storage{}\n\t\t\/\/ customresourcedefinitions\n\t\tcustomResourceDefinitionStorage, err := customresourcedefinition.NewREST(Scheme, c.GenericConfig.RESTOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[\"customresourcedefinitions\"] = customResourceDefinitionStorage\n\t\tstorage[\"customresourcedefinitions\/status\"] = customresourcedefinition.NewStatusREST(Scheme, customResourceDefinitionStorage)\n\n\t\tapiGroupInfo.VersionedResourcesStorageMap[v1beta1.SchemeGroupVersion.Version] = storage\n\t}\n\tif apiResourceConfig.VersionEnabled(v1.SchemeGroupVersion) {\n\t\tstorage := map[string]rest.Storage{}\n\t\t\/\/ customresourcedefinitions\n\t\tcustomResourceDefinitionStorage, err := customresourcedefinition.NewREST(Scheme, c.GenericConfig.RESTOptionsGetter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tstorage[\"customresourcedefinitions\"] = customResourceDefinitionStorage\n\t\tstorage[\"customresourcedefinitions\/status\"] = customresourcedefinition.NewStatusREST(Scheme, customResourceDefinitionStorage)\n\n\t\tapiGroupInfo.VersionedResourcesStorageMap[v1.SchemeGroupVersion.Version] = storage\n\t}\n\n\tif err := s.GenericAPIServer.InstallAPIGroup(&apiGroupInfo); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcrdClient, err := clientset.NewForConfig(s.GenericAPIServer.LoopbackClientConfig)\n\tif err != nil {\n\t\t\/\/ it's really bad that this is leaking here, but until we can fix the test (which I'm pretty sure isn't even testing what it wants to test),\n\t\t\/\/ we need to be able to move forward\n\t\treturn nil, fmt.Errorf(\"failed to create clientset: %v\", err)\n\t}\n\ts.Informers = externalinformers.NewSharedInformerFactory(crdClient, 5*time.Minute)\n\n\tdelegateHandler := delegationTarget.UnprotectedHandler()\n\tif delegateHandler == nil {\n\t\tdelegateHandler = http.NotFoundHandler()\n\t}\n\n\tversionDiscoveryHandler := &versionDiscoveryHandler{\n\t\tdiscovery: map[schema.GroupVersion]*discovery.APIVersionHandler{},\n\t\tdelegate:  delegateHandler,\n\t}\n\tgroupDiscoveryHandler := &groupDiscoveryHandler{\n\t\tdiscovery: map[string]*discovery.APIGroupHandler{},\n\t\tdelegate:  delegateHandler,\n\t}\n\testablishingController := establish.NewEstablishingController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), crdClient.ApiextensionsV1())\n\tcrdHandler, err := NewCustomResourceDefinitionHandler(\n\t\tversionDiscoveryHandler,\n\t\tgroupDiscoveryHandler,\n\t\ts.Informers.Apiextensions().V1().CustomResourceDefinitions(),\n\t\tdelegateHandler,\n\t\tc.ExtraConfig.CRDRESTOptionsGetter,\n\t\tc.GenericConfig.AdmissionControl,\n\t\testablishingController,\n\t\tc.ExtraConfig.ServiceResolver,\n\t\tc.ExtraConfig.AuthResolverWrapper,\n\t\tc.ExtraConfig.MasterCount,\n\t\ts.GenericAPIServer.Authorizer,\n\t\tc.GenericConfig.RequestTimeout,\n\t\ttime.Duration(c.GenericConfig.MinRequestTimeout)*time.Second,\n\t\tapiGroupInfo.StaticOpenAPISpec,\n\t\tc.GenericConfig.MaxRequestBodyBytes,\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.GenericAPIServer.Handler.NonGoRestfulMux.Handle(\"\/apis\", crdHandler)\n\ts.GenericAPIServer.Handler.NonGoRestfulMux.HandlePrefix(\"\/apis\/\", crdHandler)\n\n\tdiscoveryController := NewDiscoveryController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), versionDiscoveryHandler, groupDiscoveryHandler)\n\tnamingController := status.NewNamingConditionController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), crdClient.ApiextensionsV1())\n\tnonStructuralSchemaController := nonstructuralschema.NewConditionController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), crdClient.ApiextensionsV1())\n\tapiApprovalController := apiapproval.NewKubernetesAPIApprovalPolicyConformantConditionController(s.Informers.Apiextensions().V1().CustomResourceDefinitions(), crdClient.ApiextensionsV1())\n\tfinalizingController := finalizer.NewCRDFinalizer(\n\t\ts.Informers.Apiextensions().V1().CustomResourceDefinitions(),\n\t\tcrdClient.ApiextensionsV1(),\n\t\tcrdHandler,\n\t)\n\topenapiController := openapicontroller.NewController(s.Informers.Apiextensions().V1().CustomResourceDefinitions())\n\n\ts.GenericAPIServer.AddPostStartHookOrDie(\"start-apiextensions-informers\", func(context genericapiserver.PostStartHookContext) error {\n\t\ts.Informers.Start(context.StopCh)\n\t\treturn nil\n\t})\n\ts.GenericAPIServer.AddPostStartHookOrDie(\"start-apiextensions-controllers\", func(context genericapiserver.PostStartHookContext) error {\n\t\t\/\/ OpenAPIVersionedService and StaticOpenAPISpec are populated in generic apiserver PrepareRun().\n\t\t\/\/ Together they serve the \/openapi\/v2 endpoint on a generic apiserver. A generic apiserver may\n\t\t\/\/ choose to not enable OpenAPI by having null openAPIConfig, and thus OpenAPIVersionedService\n\t\t\/\/ and StaticOpenAPISpec are both null. In that case we don't run the CRD OpenAPI controller.\n\t\tif s.GenericAPIServer.OpenAPIVersionedService != nil && s.GenericAPIServer.StaticOpenAPISpec != nil {\n\t\t\tgo openapiController.Run(s.GenericAPIServer.StaticOpenAPISpec, s.GenericAPIServer.OpenAPIVersionedService, context.StopCh)\n\t\t}\n\n\t\tgo namingController.Run(context.StopCh)\n\t\tgo establishingController.Run(context.StopCh)\n\t\tgo nonStructuralSchemaController.Run(5, context.StopCh)\n\t\tgo apiApprovalController.Run(5, context.StopCh)\n\t\tgo finalizingController.Run(5, context.StopCh)\n\n\t\tdiscoverySyncedCh := make(chan struct{})\n\t\tgo discoveryController.Run(context.StopCh, discoverySyncedCh)\n\t\tselect {\n\t\tcase <-context.StopCh:\n\t\tcase <-discoverySyncedCh:\n\t\t}\n\n\t\treturn nil\n\t})\n\t\/\/ we don't want to report healthy until we can handle all CRDs that have already been registered.  Waiting for the informer\n\t\/\/ to sync makes sure that the lister will be valid before we begin.  There may still be races for CRDs added after startup,\n\t\/\/ but we won't go healthy until we can handle the ones already present.\n\ts.GenericAPIServer.AddPostStartHookOrDie(\"crd-informer-synced\", func(context genericapiserver.PostStartHookContext) error {\n\t\treturn wait.PollImmediateUntil(100*time.Millisecond, func() (bool, error) {\n\t\t\treturn s.Informers.Apiextensions().V1().CustomResourceDefinitions().Informer().HasSynced(), nil\n\t\t}, context.StopCh)\n\t})\n\n\treturn s, nil\n}\n\nfunc DefaultAPIResourceConfigSource() *serverstorage.ResourceConfig {\n\tret := serverstorage.NewResourceConfig()\n\t\/\/ NOTE: GroupVersions listed here will be enabled by default. Don't put alpha versions in the list.\n\tret.EnableVersions(\n\t\tv1beta1.SchemeGroupVersion,\n\t\tv1.SchemeGroupVersion,\n\t)\n\n\treturn ret\n}\n<|endoftext|>"}
{"text":"<commit_before>package group\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/docker\/infrakit\/pkg\/spi\/group\"\n\t\"github.com\/docker\/infrakit\/pkg\/spi\/instance\"\n)\n\ntype scaler struct {\n\tid             group.ID\n\tscaled         Scaled\n\tsize           uint\n\tpollInterval   time.Duration\n\tmaxParallelNum uint\n\tlock           sync.Mutex\n\tstop           chan bool\n}\n\n\/\/ NewScalingGroup creates a supervisor that monitors a group of instances on a provisioner, attempting to maintain a\n\/\/ desired size.\nfunc NewScalingGroup(id group.ID, scaled Scaled, size uint, pollInterval time.Duration, maxParallelNum uint) Supervisor {\n\treturn &scaler{\n\t\tid:             id,\n\t\tscaled:         scaled,\n\t\tsize:           size,\n\t\tpollInterval:   pollInterval,\n\t\tmaxParallelNum: maxParallelNum,\n\t\tstop:           make(chan bool),\n\t}\n}\n\nfunc (s *scaler) PlanUpdate(scaled Scaled, settings groupSettings, newSettings groupSettings) (updatePlan, error) {\n\n\tsizeChange := int(newSettings.config.Allocation.Size) - int(settings.config.Allocation.Size)\n\n\tinstances, err := labelAndList(s.scaled)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdesired, undesired := desiredAndUndesiredInstances(instances, newSettings)\n\n\tplan := scalerUpdatePlan{\n\t\toriginalSize: settings.config.Allocation.Size,\n\t\tnewSize:      newSettings.config.Allocation.Size,\n\t\tscaler:       s,\n\t\trollingPlan:  noopUpdate{},\n\t}\n\n\tswitch {\n\tcase sizeChange == 0:\n\t\trollCount := len(undesired)\n\n\t\tif rollCount == 0 {\n\t\t\tif settings.config.InstanceHash() == newSettings.config.InstanceHash() {\n\n\t\t\t\t\/\/ This is a no-op update because:\n\t\t\t\t\/\/  - the instance configuration is unchanged\n\t\t\t\t\/\/  - the group contains no instances with an undesired state\n\t\t\t\t\/\/  - the group size is unchanged\n\t\t\t\treturn &noopUpdate{}, nil\n\t\t\t}\n\n\t\t\t\/\/ This case likely occurs because a group was created in a way that no instances are being\n\t\t\t\/\/ created. We proceed with the update here, which will likely only change the target\n\t\t\t\/\/ configuration in the scaler.\n\n\t\t\tplan.desc = \"Adjusting the instance configuration, no restarts necessary\"\n\t\t\treturn &plan, nil\n\t\t}\n\n\t\tplan.desc = fmt.Sprintf(\"Performing a rolling update on %d instances\", rollCount)\n\n\tcase sizeChange < 0:\n\t\trollCount := int(newSettings.config.Allocation.Size) - len(desired)\n\t\tif rollCount < 0 {\n\t\t\trollCount = 0\n\t\t}\n\n\t\tif rollCount == 0 {\n\t\t\tplan.desc = fmt.Sprintf(\n\t\t\t\t\"Terminating %d instances to reduce the group size to %d\",\n\t\t\t\tint(sizeChange)*-1,\n\t\t\t\tnewSettings.config.Allocation.Size)\n\t\t} else {\n\t\t\tplan.desc = fmt.Sprintf(\n\t\t\t\t\"Terminating %d instances to reduce the group size to %d, \"+\n\t\t\t\t\t\" then performing a rolling update on %d instances\",\n\t\t\t\tint(sizeChange)*-1,\n\t\t\t\tnewSettings.config.Allocation.Size,\n\t\t\t\trollCount)\n\t\t}\n\n\tcase sizeChange > 0:\n\t\trollCount := len(undesired)\n\n\t\tif rollCount == 0 {\n\t\t\tplan.desc = fmt.Sprintf(\n\t\t\t\t\"Adding %d instances to increase the group size to %d\",\n\t\t\t\tsizeChange,\n\t\t\t\tnewSettings.config.Allocation.Size)\n\t\t} else {\n\t\t\tplan.desc = fmt.Sprintf(\n\t\t\t\t\"Performing a rolling update on %d instances,\"+\n\t\t\t\t\t\" then adding %d instances to increase the group size to %d\",\n\t\t\t\trollCount,\n\t\t\t\tsizeChange,\n\t\t\t\tnewSettings.config.Allocation.Size)\n\t\t}\n\t}\n\n\tplan.rollingPlan = &rollingupdate{\n\t\tscaled:     scaled,\n\t\tupdatingTo: newSettings,\n\t\tstop:       make(chan bool),\n\t}\n\n\treturn plan, nil\n}\n\ntype scalerUpdatePlan struct {\n\tdesc         string\n\toriginalSize uint\n\tnewSize      uint\n\trollingPlan  updatePlan\n\tscaler       *scaler\n}\n\nfunc (s scalerUpdatePlan) Explain() string {\n\treturn s.desc\n}\n\nfunc (s scalerUpdatePlan) Run(pollInterval time.Duration) error {\n\n\t\/\/ If the number of instances is being decreased, first lower the group size.  This eliminates\n\t\/\/ instances that would otherwise be rolled first, avoiding unnecessary work.\n\t\/\/ We could further optimize by selecting undesired instances to destroy, for example if the\n\t\/\/ scaler already has a mix of desired and undesired instances.\n\tif s.newSize < s.originalSize {\n\t\ts.scaler.SetSize(s.newSize)\n\t}\n\n\tif err := s.rollingPlan.Run(pollInterval); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Rolling has completed.  If the update included a group size increase, perform that now.\n\tif s.newSize > s.originalSize {\n\t\ts.scaler.SetSize(s.newSize)\n\t}\n\n\treturn nil\n}\n\nfunc (s scalerUpdatePlan) Stop() {\n\ts.rollingPlan.Stop()\n}\n\nfunc (s *scaler) SetSize(size uint) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tlog.Infof(\"Set target size to %d\", size)\n\ts.size = size\n}\n\nfunc (s *scaler) getSize() uint {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\treturn s.size\n}\n\nfunc (s *scaler) SetMaxParallelNum(psize uint) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tlog.Infof(\"Set max parallel instance creation  to %d\", psize)\n\ts.maxParallelNum = psize\n}\n\nfunc (s *scaler) getMaxParallelNum() uint {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\treturn s.maxParallelNum\n}\n\nfunc (s *scaler) Stop() {\n\tclose(s.stop)\n}\n\nfunc (s *scaler) Run() {\n\tticker := time.NewTicker(s.pollInterval)\n\n\ts.converge()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\ts.converge()\n\t\tcase <-s.stop:\n\t\t\tticker.Stop()\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (s *scaler) ID() group.ID {\n\treturn s.id\n}\n\nfunc (s *scaler) Size() uint {\n\treturn s.size\n}\n\nfunc (s *scaler) waitIfReachParallelLimit(current int, batch *sync.WaitGroup) {\n\tif s.maxParallelNum > 0 && (current+1)%int(s.maxParallelNum) == 0 {\n\t\tlog.Infof(\"Reach limit parallel instance operation number %d, waiting...\", s.maxParallelNum)\n\t\tbatch.Wait()\n\t}\n\treturn\n}\n\nfunc (s *scaler) converge() {\n\tdescriptions, err := labelAndList(s.scaled)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to list group instances: %s\", err)\n\t\treturn\n\t}\n\n\tlog.Debugf(\"Found existing instances: %v\", descriptions)\n\n\tgrp := sync.WaitGroup{}\n\n\tactualSize := uint(len(descriptions))\n\tdesiredSize := s.getSize()\n\tswitch {\n\tcase actualSize == desiredSize:\n\t\tlog.Debugf(\"Group has %d instances, no action is needed\", desiredSize)\n\n\tcase actualSize > desiredSize:\n\t\tremove := actualSize - desiredSize\n\t\tlog.Infof(\"Removing %d instances from group to reach desired %d\", remove, desiredSize)\n\n\t\tsorted := make([]instance.Description, len(descriptions))\n\t\tcopy(sorted, descriptions)\n\n\t\t\/\/ Sorting first ensures that redundant operations are non-destructive.\n\t\tsort.Sort(sortByID(sorted))\n\n\t\t\/\/ TODO(wfarner): Consider favoring removal of instances that do not match the desired configuration by\n\t\t\/\/ injecting a sorter.\n\t\tfor i, toDestroy := range sorted[:remove] {\n\t\t\tgrp.Add(1)\n\t\t\tdestroy := toDestroy\n\t\t\tgo func() {\n\t\t\t\tdefer grp.Done()\n\t\t\t\ts.scaled.Destroy(destroy)\n\t\t\t}()\n\t\t\ts.waitIfReachParallelLimit(i, &grp)\n\t\t}\n\n\tcase actualSize < desiredSize:\n\t\tadd := desiredSize - actualSize\n\t\tlog.Infof(\"Adding %d instances to group to reach desired %d\", add, desiredSize)\n\n\t\tfor i := 0; i < int(add); i++ {\n\t\t\tgrp.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer grp.Done()\n\n\t\t\t\ts.scaled.CreateOne(nil)\n\t\t\t}()\n\t\t\ts.waitIfReachParallelLimit(i, &grp)\n\t\t}\n\t}\n\n\t\/\/ Wait for outstanding actions to finish.\n\t\/\/ It is not imperative to avoid stepping on another removal operation by this routine\n\t\/\/ (within this process or another) since the selection of removal candidates is stable.\n\t\/\/ However, we do so here to mitigate redundant work and avoidable benign (but confusing) errors\n\t\/\/ when overlaps happen.\n\tgrp.Wait()\n}\n<commit_msg>Fix race condition (#445)<commit_after>package group\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/docker\/infrakit\/pkg\/spi\/group\"\n\t\"github.com\/docker\/infrakit\/pkg\/spi\/instance\"\n)\n\ntype scaler struct {\n\tid             group.ID\n\tscaled         Scaled\n\tsize           uint\n\tpollInterval   time.Duration\n\tmaxParallelNum uint\n\tlock           sync.Mutex\n\tstop           chan bool\n}\n\n\/\/ NewScalingGroup creates a supervisor that monitors a group of instances on a provisioner, attempting to maintain a\n\/\/ desired size.\nfunc NewScalingGroup(id group.ID, scaled Scaled, size uint, pollInterval time.Duration, maxParallelNum uint) Supervisor {\n\treturn &scaler{\n\t\tid:             id,\n\t\tscaled:         scaled,\n\t\tsize:           size,\n\t\tpollInterval:   pollInterval,\n\t\tmaxParallelNum: maxParallelNum,\n\t\tstop:           make(chan bool),\n\t}\n}\n\nfunc (s *scaler) PlanUpdate(scaled Scaled, settings groupSettings, newSettings groupSettings) (updatePlan, error) {\n\n\tsizeChange := int(newSettings.config.Allocation.Size) - int(settings.config.Allocation.Size)\n\n\tinstances, err := labelAndList(s.scaled)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdesired, undesired := desiredAndUndesiredInstances(instances, newSettings)\n\n\tplan := scalerUpdatePlan{\n\t\toriginalSize: settings.config.Allocation.Size,\n\t\tnewSize:      newSettings.config.Allocation.Size,\n\t\tscaler:       s,\n\t\trollingPlan:  noopUpdate{},\n\t}\n\n\tswitch {\n\tcase sizeChange == 0:\n\t\trollCount := len(undesired)\n\n\t\tif rollCount == 0 {\n\t\t\tif settings.config.InstanceHash() == newSettings.config.InstanceHash() {\n\n\t\t\t\t\/\/ This is a no-op update because:\n\t\t\t\t\/\/  - the instance configuration is unchanged\n\t\t\t\t\/\/  - the group contains no instances with an undesired state\n\t\t\t\t\/\/  - the group size is unchanged\n\t\t\t\treturn &noopUpdate{}, nil\n\t\t\t}\n\n\t\t\t\/\/ This case likely occurs because a group was created in a way that no instances are being\n\t\t\t\/\/ created. We proceed with the update here, which will likely only change the target\n\t\t\t\/\/ configuration in the scaler.\n\n\t\t\tplan.desc = \"Adjusting the instance configuration, no restarts necessary\"\n\t\t\treturn &plan, nil\n\t\t}\n\n\t\tplan.desc = fmt.Sprintf(\"Performing a rolling update on %d instances\", rollCount)\n\n\tcase sizeChange < 0:\n\t\trollCount := int(newSettings.config.Allocation.Size) - len(desired)\n\t\tif rollCount < 0 {\n\t\t\trollCount = 0\n\t\t}\n\n\t\tif rollCount == 0 {\n\t\t\tplan.desc = fmt.Sprintf(\n\t\t\t\t\"Terminating %d instances to reduce the group size to %d\",\n\t\t\t\tint(sizeChange)*-1,\n\t\t\t\tnewSettings.config.Allocation.Size)\n\t\t} else {\n\t\t\tplan.desc = fmt.Sprintf(\n\t\t\t\t\"Terminating %d instances to reduce the group size to %d, \"+\n\t\t\t\t\t\" then performing a rolling update on %d instances\",\n\t\t\t\tint(sizeChange)*-1,\n\t\t\t\tnewSettings.config.Allocation.Size,\n\t\t\t\trollCount)\n\t\t}\n\n\tcase sizeChange > 0:\n\t\trollCount := len(undesired)\n\n\t\tif rollCount == 0 {\n\t\t\tplan.desc = fmt.Sprintf(\n\t\t\t\t\"Adding %d instances to increase the group size to %d\",\n\t\t\t\tsizeChange,\n\t\t\t\tnewSettings.config.Allocation.Size)\n\t\t} else {\n\t\t\tplan.desc = fmt.Sprintf(\n\t\t\t\t\"Performing a rolling update on %d instances,\"+\n\t\t\t\t\t\" then adding %d instances to increase the group size to %d\",\n\t\t\t\trollCount,\n\t\t\t\tsizeChange,\n\t\t\t\tnewSettings.config.Allocation.Size)\n\t\t}\n\t}\n\n\tplan.rollingPlan = &rollingupdate{\n\t\tscaled:     scaled,\n\t\tupdatingTo: newSettings,\n\t\tstop:       make(chan bool),\n\t}\n\n\treturn plan, nil\n}\n\ntype scalerUpdatePlan struct {\n\tdesc         string\n\toriginalSize uint\n\tnewSize      uint\n\trollingPlan  updatePlan\n\tscaler       *scaler\n}\n\nfunc (s scalerUpdatePlan) Explain() string {\n\treturn s.desc\n}\n\nfunc (s scalerUpdatePlan) Run(pollInterval time.Duration) error {\n\n\t\/\/ If the number of instances is being decreased, first lower the group size.  This eliminates\n\t\/\/ instances that would otherwise be rolled first, avoiding unnecessary work.\n\t\/\/ We could further optimize by selecting undesired instances to destroy, for example if the\n\t\/\/ scaler already has a mix of desired and undesired instances.\n\tif s.newSize < s.originalSize {\n\t\ts.scaler.SetSize(s.newSize)\n\t}\n\n\tif err := s.rollingPlan.Run(pollInterval); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Rolling has completed.  If the update included a group size increase, perform that now.\n\tif s.newSize > s.originalSize {\n\t\ts.scaler.SetSize(s.newSize)\n\t}\n\n\treturn nil\n}\n\nfunc (s scalerUpdatePlan) Stop() {\n\ts.rollingPlan.Stop()\n}\n\nfunc (s *scaler) SetSize(size uint) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tlog.Infof(\"Set target size to %d\", size)\n\ts.size = size\n}\n\nfunc (s *scaler) getSize() uint {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\treturn s.size\n}\n\nfunc (s *scaler) SetMaxParallelNum(psize uint) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\tlog.Infof(\"Set max parallel instance creation  to %d\", psize)\n\ts.maxParallelNum = psize\n}\n\nfunc (s *scaler) getMaxParallelNum() uint {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\n\treturn s.maxParallelNum\n}\n\nfunc (s *scaler) Stop() {\n\tclose(s.stop)\n}\n\nfunc (s *scaler) Run() {\n\tticker := time.NewTicker(s.pollInterval)\n\n\ts.converge()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\ts.converge()\n\t\tcase <-s.stop:\n\t\t\tticker.Stop()\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (s *scaler) ID() group.ID {\n\treturn s.id\n}\n\nfunc (s *scaler) Size() uint {\n\treturn s.getSize()\n}\n\nfunc (s *scaler) waitIfReachParallelLimit(current int, batch *sync.WaitGroup) {\n\tif s.maxParallelNum > 0 && (current+1)%int(s.maxParallelNum) == 0 {\n\t\tlog.Infof(\"Reach limit parallel instance operation number %d, waiting...\", s.maxParallelNum)\n\t\tbatch.Wait()\n\t}\n\treturn\n}\n\nfunc (s *scaler) converge() {\n\tdescriptions, err := labelAndList(s.scaled)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to list group instances: %s\", err)\n\t\treturn\n\t}\n\n\tlog.Debugf(\"Found existing instances: %v\", descriptions)\n\n\tgrp := sync.WaitGroup{}\n\n\tactualSize := uint(len(descriptions))\n\tdesiredSize := s.getSize()\n\tswitch {\n\tcase actualSize == desiredSize:\n\t\tlog.Debugf(\"Group has %d instances, no action is needed\", desiredSize)\n\n\tcase actualSize > desiredSize:\n\t\tremove := actualSize - desiredSize\n\t\tlog.Infof(\"Removing %d instances from group to reach desired %d\", remove, desiredSize)\n\n\t\tsorted := make([]instance.Description, len(descriptions))\n\t\tcopy(sorted, descriptions)\n\n\t\t\/\/ Sorting first ensures that redundant operations are non-destructive.\n\t\tsort.Sort(sortByID(sorted))\n\n\t\t\/\/ TODO(wfarner): Consider favoring removal of instances that do not match the desired configuration by\n\t\t\/\/ injecting a sorter.\n\t\tfor i, toDestroy := range sorted[:remove] {\n\t\t\tgrp.Add(1)\n\t\t\tdestroy := toDestroy\n\t\t\tgo func() {\n\t\t\t\tdefer grp.Done()\n\t\t\t\ts.scaled.Destroy(destroy)\n\t\t\t}()\n\t\t\ts.waitIfReachParallelLimit(i, &grp)\n\t\t}\n\n\tcase actualSize < desiredSize:\n\t\tadd := desiredSize - actualSize\n\t\tlog.Infof(\"Adding %d instances to group to reach desired %d\", add, desiredSize)\n\n\t\tfor i := 0; i < int(add); i++ {\n\t\t\tgrp.Add(1)\n\t\t\tgo func() {\n\t\t\t\tdefer grp.Done()\n\n\t\t\t\ts.scaled.CreateOne(nil)\n\t\t\t}()\n\t\t\ts.waitIfReachParallelLimit(i, &grp)\n\t\t}\n\t}\n\n\t\/\/ Wait for outstanding actions to finish.\n\t\/\/ It is not imperative to avoid stepping on another removal operation by this routine\n\t\/\/ (within this process or another) since the selection of removal candidates is stable.\n\t\/\/ However, we do so here to mitigate redundant work and avoidable benign (but confusing) errors\n\t\/\/ when overlaps happen.\n\tgrp.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>package redis\n\nimport (\n\t\"sync\"\n\t\"time\"\n\t\"github.com\/BluePecker\/JwtAuth\/pkg\/storage\"\n\t\"github.com\/go-redis\/redis\"\n\t\"crypto\/md5\"\n\t\"encoding\/hex\"\n\t\"github.com\/BluePecker\/JwtAuth\/pkg\/storage\/redis\/uri\"\n\t\"reflect\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/kataras\/iris\/core\/errors\"\n)\n\ntype (\n\tRedis struct {\n\t\tcreate time.Time\n\t\tmu     sync.RWMutex\n\t\tengine Client\n\t}\n\n\tClient interface {\n\t\tPing() *redis.StatusCmd\n\n\t\tClose() error\n\n\t\tPipelined(fn func(redis.Pipeliner) error) ([]redis.Cmder, error)\n\n\t\tZScore(key, field string) *redis.FloatCmd\n\n\t\tZRem(key string, members ... interface{}) *redis.IntCmd\n\n\t\tZRange(key string, start, stop int64) *redis.StringSliceCmd\n\t}\n)\n\nfunc inject(from, target reflect.Value) {\n\tindirect := reflect.Indirect(target.Elem())\n\tfor index := 0; index < from.Elem().NumField(); index++ {\n\t\tname := from.Elem().Type().Field(index).Name\n\t\tf1 := from.Elem().FieldByName(name)\n\t\tf2 := indirect.FieldByName(name)\n\t\tif f2.IsValid() {\n\t\t\tif f1.Type() == f2.Type() && f2.CanSet() {\n\t\t\t\tf2.Set(f1)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (r *Redis) Initializer(opts string) error {\n\tgeneric, err := uri.Parser(opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tswitch reflect.ValueOf(generic).Interface().(type) {\n\tcase *redis.ClusterOptions:\n\t\toptions := &redis.ClusterOptions{}\n\t\tinject(reflect.ValueOf(generic), reflect.ValueOf(options))\n\t\tr.engine = redis.NewClusterClient(options)\n\t\tbreak\n\tcase *redis.Options:\n\t\toptions := &redis.Options{}\n\t\tinject(reflect.ValueOf(generic), reflect.ValueOf(options))\n\t\tr.engine = redis.NewClient(options)\n\t\tbreak\n\t}\n\tstatusCmd := r.engine.Ping()\n\tif statusCmd.Err() != nil {\n\t\tlogrus.Error(statusCmd.Err())\n\t\tdefer r.engine.Close()\n\t}\n\treturn statusCmd.Err()\n}\n\nfunc (r *Redis) HSet(key, field string, value interface{}, maxLen, expire int64) error {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\t_, err := r.engine.Pipelined(func(p redis.Pipeliner) error {\n\t\texp := time.Duration(expire) * time.Second\n\t\ttmp := jwtMd5(key)\n\t\tval := jwtMd5(tmp + field)\n\t\tscore := expire + int64(time.Now().Unix())\n\t\tif cmd := p.ZAdd(tmp, redis.Z{Score: float64(score), Member: val}); cmd.Err() != nil {\n\t\t\treturn cmd.Err()\n\t\t} else {\n\t\t\tif cmd := p.Expire(tmp, exp); cmd.Err() != nil {\n\t\t\t\treturn cmd.Err()\n\t\t\t}\n\t\t\tif cmd := p.Set(val, value, exp); cmd.Err() != nil {\n\t\t\t\tp.ZRem(tmp, redis.Z{Score: float64(score), Member: val})\n\t\t\t\treturn cmd.Err()\n\t\t\t}\n\t\t}\n\t\tif cmd := p.ZCard(tmp); cmd.Err() != nil {\n\t\t\treturn cmd.Err()\n\t\t} else {\n\t\t\tlogrus.Error(cmd.Val(), \" \", maxLen)\n\t\t\tif cmd.Val() > maxLen {\n\t\t\t\tif cmd := p.ZRange(tmp, 0, cmd.Val()-maxLen); cmd.Err() != nil {\n\t\t\t\t\treturn cmd.Err()\n\t\t\t\t} else {\n\t\t\t\t\tp.Del(cmd.Val()...)\n\t\t\t\t}\n\t\t\t\tcmd = p.ZRemRangeByRank(tmp, 0, cmd.Val()-maxLen)\n\t\t\t\tif cmd.Err() != nil {\n\t\t\t\t\treturn cmd.Err()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\treturn err\n}\n\nfunc (r *Redis) HGet(key, field string) (string, float64, error) {\n\tr.mu.RLock()\n\tdefer r.mu.RLock()\n\ttmp := jwtMd5(key)\n\treturn r.hGet(tmp, jwtMd5(tmp+field))\n}\n\nfunc (r *Redis) hGet(key, field string) (string, float64, error) {\n\tif cmd := r.engine.ZScore(key, field); cmd.Err() != nil {\n\t\treturn \"\", -1, cmd.Err()\n\t} else if cmd.Val() < float64(time.Now().Unix()) {\n\t\tif cmd := r.engine.ZRem(key, field); cmd.Err() != nil {\n\t\t\treturn \"\", -1, cmd.Err()\n\t\t} else {\n\t\t\treturn \"\", -1, errors.New(\"key has been expired.\")\n\t\t}\n\t} else {\n\t\tvar strCmd *redis.StringCmd\n\t\tvar durCmd *redis.DurationCmd\n\t\t_, err := r.engine.Pipelined(func(p redis.Pipeliner) error {\n\t\t\tif strCmd = p.Get(field); cmd.Err() != nil {\n\t\t\t\treturn strCmd.Err()\n\t\t\t}\n\t\t\tif durCmd = p.TTL(field); cmd.Err() != nil {\n\t\t\t\treturn durCmd.Err()\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn \"\", -1, err\n\t\t}\n\t\treturn strCmd.Val(), durCmd.Val().Seconds(), nil\n\t}\n}\n\nfunc (r *Redis) HScan(key string, do func(token string, ttl float64)) error {\n\tr.mu.RLock()\n\tdefer r.mu.RLock()\n\ttmp := jwtMd5(key)\n\tif cmd := r.engine.ZRange(tmp, 0, -1); cmd.Err() != nil {\n\t\treturn cmd.Err()\n\t} else {\n\t\tfor _, field := range cmd.Val() {\n\t\t\tsinged, ttl, err := r.hGet(tmp, field)\n\t\t\tif err == nil {\n\t\t\t\tdo(singed, ttl)\n\t\t\t} else {\n\t\t\t\tlogrus.Info(err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc (r *Redis) HRem(key string, field ... string) error {\n\tr.mu.Lock()\n\tdefer r.mu.Lock()\n\tvar v1 []interface{}\n\tvar v2 []string\n\ttmp := jwtMd5(key)\n\tfor _, v := range field {\n\t\tv1 = append(v1, jwtMd5(tmp+v))\n\t\tv2 = append(v2, jwtMd5(tmp+v))\n\t}\n\t_, err := r.engine.Pipelined(func(p redis.Pipeliner) error {\n\t\tp.ZRem(tmp, v1...)\n\t\tp.Del(v2...)\n\t\treturn nil\n\t})\n\treturn err\n}\n\nfunc jwtMd5(key string) string {\n\thash := md5.New()\n\thash.Write([]byte(key))\n\treturn hex.EncodeToString(hash.Sum([]byte(\"jwt#\")))\n}\n\nfunc init() {\n\tstorage.Register(\"redis\", &Redis{})\n}\n<commit_msg>debug<commit_after>package redis\n\nimport (\n\t\"sync\"\n\t\"time\"\n\t\"github.com\/BluePecker\/JwtAuth\/pkg\/storage\"\n\t\"github.com\/go-redis\/redis\"\n\t\"crypto\/md5\"\n\t\"encoding\/hex\"\n\t\"github.com\/BluePecker\/JwtAuth\/pkg\/storage\/redis\/uri\"\n\t\"reflect\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/kataras\/iris\/core\/errors\"\n)\n\ntype (\n\tRedis struct {\n\t\tcreate time.Time\n\t\tmu     sync.RWMutex\n\t\tengine Client\n\t}\n\n\tClient interface {\n\t\tPing() *redis.StatusCmd\n\n\t\tClose() error\n\n\t\tPipelined(fn func(redis.Pipeliner) error) ([]redis.Cmder, error)\n\n\t\tZScore(key, field string) *redis.FloatCmd\n\n\t\tZRem(key string, members ... interface{}) *redis.IntCmd\n\n\t\tZRange(key string, start, stop int64) *redis.StringSliceCmd\n\t}\n)\n\nfunc inject(from, target reflect.Value) {\n\tindirect := reflect.Indirect(target.Elem())\n\tfor index := 0; index < from.Elem().NumField(); index++ {\n\t\tname := from.Elem().Type().Field(index).Name\n\t\tf1 := from.Elem().FieldByName(name)\n\t\tf2 := indirect.FieldByName(name)\n\t\tif f2.IsValid() {\n\t\t\tif f1.Type() == f2.Type() && f2.CanSet() {\n\t\t\t\tf2.Set(f1)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (r *Redis) Initializer(opts string) error {\n\tgeneric, err := uri.Parser(opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tswitch reflect.ValueOf(generic).Interface().(type) {\n\tcase *redis.ClusterOptions:\n\t\toptions := &redis.ClusterOptions{}\n\t\tinject(reflect.ValueOf(generic), reflect.ValueOf(options))\n\t\tr.engine = redis.NewClusterClient(options)\n\t\tbreak\n\tcase *redis.Options:\n\t\toptions := &redis.Options{}\n\t\tinject(reflect.ValueOf(generic), reflect.ValueOf(options))\n\t\tr.engine = redis.NewClient(options)\n\t\tbreak\n\t}\n\tstatusCmd := r.engine.Ping()\n\tif statusCmd.Err() != nil {\n\t\tlogrus.Error(statusCmd.Err())\n\t\tdefer r.engine.Close()\n\t}\n\treturn statusCmd.Err()\n}\n\nfunc (r *Redis) HSet(key, field string, value interface{}, maxLen, expire int64) error {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\t_, err := r.engine.Pipelined(func(p redis.Pipeliner) error {\n\t\texp := time.Duration(expire) * time.Second\n\t\ttmp := jwtMd5(key)\n\t\tval := jwtMd5(tmp + field)\n\t\tscore := expire + int64(time.Now().Unix())\n\t\tif cmd := p.ZAdd(tmp, redis.Z{Score: float64(score), Member: val}); cmd.Err() != nil {\n\t\t\treturn cmd.Err()\n\t\t} else {\n\t\t\tif cmd := p.Expire(tmp, exp); cmd.Err() != nil {\n\t\t\t\treturn cmd.Err()\n\t\t\t}\n\t\t\tif cmd := p.Set(val, value, exp); cmd.Err() != nil {\n\t\t\t\tp.ZRem(tmp, redis.Z{Score: float64(score), Member: val})\n\t\t\t\treturn cmd.Err()\n\t\t\t}\n\t\t}\n\t\tif cmd := p.ZCard(tmp); cmd.Err() != nil {\n\t\t\treturn cmd.Err()\n\t\t} else {\n\t\t\tlogrus.Error(tmp, \" \", cmd.Val(), \" \", maxLen)\n\t\t\tif cmd.Val() > maxLen {\n\t\t\t\tif cmd := p.ZRange(tmp, 0, cmd.Val()-maxLen); cmd.Err() != nil {\n\t\t\t\t\treturn cmd.Err()\n\t\t\t\t} else {\n\t\t\t\t\tp.Del(cmd.Val()...)\n\t\t\t\t}\n\t\t\t\tcmd = p.ZRemRangeByRank(tmp, 0, cmd.Val()-maxLen)\n\t\t\t\tif cmd.Err() != nil {\n\t\t\t\t\treturn cmd.Err()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\treturn err\n}\n\nfunc (r *Redis) HGet(key, field string) (string, float64, error) {\n\tr.mu.RLock()\n\tdefer r.mu.RLock()\n\ttmp := jwtMd5(key)\n\treturn r.hGet(tmp, jwtMd5(tmp+field))\n}\n\nfunc (r *Redis) hGet(key, field string) (string, float64, error) {\n\tif cmd := r.engine.ZScore(key, field); cmd.Err() != nil {\n\t\treturn \"\", -1, cmd.Err()\n\t} else if cmd.Val() < float64(time.Now().Unix()) {\n\t\tif cmd := r.engine.ZRem(key, field); cmd.Err() != nil {\n\t\t\treturn \"\", -1, cmd.Err()\n\t\t} else {\n\t\t\treturn \"\", -1, errors.New(\"key has been expired.\")\n\t\t}\n\t} else {\n\t\tvar strCmd *redis.StringCmd\n\t\tvar durCmd *redis.DurationCmd\n\t\t_, err := r.engine.Pipelined(func(p redis.Pipeliner) error {\n\t\t\tif strCmd = p.Get(field); cmd.Err() != nil {\n\t\t\t\treturn strCmd.Err()\n\t\t\t}\n\t\t\tif durCmd = p.TTL(field); cmd.Err() != nil {\n\t\t\t\treturn durCmd.Err()\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn \"\", -1, err\n\t\t}\n\t\treturn strCmd.Val(), durCmd.Val().Seconds(), nil\n\t}\n}\n\nfunc (r *Redis) HScan(key string, do func(token string, ttl float64)) error {\n\tr.mu.RLock()\n\tdefer r.mu.RLock()\n\ttmp := jwtMd5(key)\n\tif cmd := r.engine.ZRange(tmp, 0, -1); cmd.Err() != nil {\n\t\treturn cmd.Err()\n\t} else {\n\t\tfor _, field := range cmd.Val() {\n\t\t\tsinged, ttl, err := r.hGet(tmp, field)\n\t\t\tif err == nil {\n\t\t\t\tdo(singed, ttl)\n\t\t\t} else {\n\t\t\t\tlogrus.Info(err)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc (r *Redis) HRem(key string, field ... string) error {\n\tr.mu.Lock()\n\tdefer r.mu.Lock()\n\tvar v1 []interface{}\n\tvar v2 []string\n\ttmp := jwtMd5(key)\n\tfor _, v := range field {\n\t\tv1 = append(v1, jwtMd5(tmp+v))\n\t\tv2 = append(v2, jwtMd5(tmp+v))\n\t}\n\t_, err := r.engine.Pipelined(func(p redis.Pipeliner) error {\n\t\tp.ZRem(tmp, v1...)\n\t\tp.Del(v2...)\n\t\treturn nil\n\t})\n\treturn err\n}\n\nfunc jwtMd5(key string) string {\n\thash := md5.New()\n\thash.Write([]byte(key))\n\treturn hex.EncodeToString(hash.Sum([]byte(\"jwt#\")))\n}\n\nfunc init() {\n\tstorage.Register(\"redis\", &Redis{})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage docker\n\nimport (\n\t\"github.com\/fsouza\/go-dockerclient\"\n)\n\n\/\/ DockerClient connects to Docker client on host\nfunc DockerClient() (*docker.Client, error) {\n\n\t\/\/ Default end-point, HTTP + TLS support to be added in the future\n\t\/\/ Eventually functionality to specify end-point added to command-line\n\tendpoint := \"unix:\/\/\/var\/run\/docker.sock\"\n\n\t\/\/ Use the unix socker end-point. No support for TLS (yet)\n\tclient, err := docker.NewClient(endpoint)\n\tif err != nil {\n\t\treturn client, err\n\t}\n\n\treturn client, nil\n}\n<commit_msg>Create docker client from environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, and DOCKER_CERT_PATH<commit_after>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage docker\n\nimport (\n\t\"github.com\/fsouza\/go-dockerclient\"\n\t\"os\"\n)\n\n\/\/ DockerClient connects to Docker client on host\nfunc DockerClient() (*docker.Client, error) {\n\n\tvar (\n\t\terr    error\n\t\tclient *docker.Client\n\t)\n\n\tdockerHost := os.Getenv(\"DOCKER_HOST\")\n\n\tif len(dockerHost) > 0 {\n\t\t\/\/ Create client instance from Docker's environment variables:\n\t\t\/\/ DOCKER_HOST, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH\n\t\tclient, err = docker.NewClientFromEnv()\n\t} else {\n\t\t\/\/ Default unix socker end-point\n\t\tendpoint := \"unix:\/\/\/var\/run\/docker.sock\"\n\t\tclient, err = docker.NewClient(endpoint)\n\t}\n\tif err != nil {\n\t\treturn client, err\n\t}\n\n\treturn client, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package application\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/pressly\/chi\"\n\t\"github.com\/pressly\/chi\/middleware\"\n)\n\n\/\/ GetRouter return http.Handler for tests and core\nfunc GetRouter(test bool) http.Handler {\n\trouter := chi.NewRouter()\n\n\tif !test {\n\t\trouter.Use(middleware.Logger)\n\t\trouter.Use(middleware.Recoverer)\n\t}\n\trouter.Mount(\"\/debug\", middleware.Profiler())\n\n\t\/\/ Set a timeout value on the request context (ctx), that will signal\n\t\/\/ through ctx.Done() that the request has timed out and further\n\t\/\/ processing should be stopped.\n\trouter.Use(middleware.Timeout(60 * time.Second))\n\n\trouter.Get(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tJSON(w, h{\n\t\t\t\"foo\": \"bar\",\n\t\t})\n\t})\n\n\trouter.Mount(\"\/\", func() http.Handler {\n\t\tr := chi.NewRouter()\n\t\tr.Use(AuthorizationMiddleware)\n\t\tr.Post(\"\/ReqEnter\", ReqEnter)\n\t\tr.Post(\"\/ReqBuyProduct\", ReqBuyProduct)\n\t\tr.Post(\"\/ReqReduceTries\", ReqReduceTries)\n\t\tr.Post(\"\/ReqReduceCredits\", ReqReduceCredits)\n\t\tr.Post(\"\/ReqSavePlayerProgress\", ReqSavePlayerProgress)\n\t\tr.Post(\"\/ReqUsersProgress\", ReqUsersProgress)\n\t\treturn r\n\t}())\n\trouter.Post(\"\/VkPay\", VkPay)\n\n\trouter.Get(\"\/crossdomain.xml\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(`<?xml version=\"1.0\"?><cross-domain-policy><allow-access-from domain=\"*\" \/><\/cross-domain-policy>`))\n\t})\n\t\/\/ http:\/\/119226.selcdn.ru\/bubble\/ShootTheBubbleDevVK.html\n\t\/\/ http:\/\/bubble-srv-dev.herokuapp.com\/bubble\/ShootTheBubbleDevVK.html\n\trouter.Get(\"\/bubble\/*filePath\", ServeStatick)\n\trouter.Get(\"\/cache-clear\", ClearStatickCache)\n\n\trouter.Get(\"\/exception\", func(w http.ResponseWriter, r *http.Request) {\n\t\tpanic(\"test log.Fatal\")\n\t})\n\n\trouter.Get(\"\/debug-vk\", func(w http.ResponseWriter, r *http.Request) {\n\t\tJSON(w, h{\n\t\t\t\"levels\": VkWorker.Levels,\n\t\t\t\"events\": VkWorker.Events,\n\t\t})\n\t})\n\n\tloaderio := os.Getenv(\"LOADERIO\")\n\tloaderioRoute := fmt.Sprintf(\"\/loaderio-%s\", loaderio)\n\trouter.Get(loaderioRoute, func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(fmt.Sprintf(\"loaderio-%s\", loaderio)))\n\t})\n\n\treturn router\n}\n<commit_msg>forget tests<commit_after>package application\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/pressly\/chi\"\n\t\"github.com\/pressly\/chi\/middleware\"\n)\n\n\/\/ GetRouter return http.Handler for tests and core\nfunc GetRouter(test bool) http.Handler {\n\trouter := chi.NewRouter()\n\n\tif !test {\n\t\trouter.Use(middleware.Logger)\n\t\trouter.Use(middleware.Recoverer)\n\t}\n\n\t\/\/ Set a timeout value on the request context (ctx), that will signal\n\t\/\/ through ctx.Done() that the request has timed out and further\n\t\/\/ processing should be stopped.\n\trouter.Use(middleware.Timeout(60 * time.Second))\n\n\trouter.Mount(\"\/debug\", middleware.Profiler())\n\n\trouter.Get(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tJSON(w, h{\n\t\t\t\"foo\": \"bar\",\n\t\t})\n\t})\n\n\trouter.Mount(\"\/\", func() http.Handler {\n\t\tr := chi.NewRouter()\n\t\tr.Use(AuthorizationMiddleware)\n\t\tr.Post(\"\/ReqEnter\", ReqEnter)\n\t\tr.Post(\"\/ReqBuyProduct\", ReqBuyProduct)\n\t\tr.Post(\"\/ReqReduceTries\", ReqReduceTries)\n\t\tr.Post(\"\/ReqReduceCredits\", ReqReduceCredits)\n\t\tr.Post(\"\/ReqSavePlayerProgress\", ReqSavePlayerProgress)\n\t\tr.Post(\"\/ReqUsersProgress\", ReqUsersProgress)\n\t\treturn r\n\t}())\n\trouter.Post(\"\/VkPay\", VkPay)\n\n\trouter.Get(\"\/crossdomain.xml\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(`<?xml version=\"1.0\"?><cross-domain-policy><allow-access-from domain=\"*\" \/><\/cross-domain-policy>`))\n\t})\n\t\/\/ http:\/\/119226.selcdn.ru\/bubble\/ShootTheBubbleDevVK.html\n\t\/\/ http:\/\/bubble-srv-dev.herokuapp.com\/bubble\/ShootTheBubbleDevVK.html\n\trouter.Get(\"\/bubble\/*filePath\", ServeStatick)\n\trouter.Get(\"\/cache-clear\", ClearStatickCache)\n\n\trouter.Get(\"\/exception\", func(w http.ResponseWriter, r *http.Request) {\n\t\tpanic(\"test log.Fatal\")\n\t})\n\n\trouter.Get(\"\/debug-vk\", func(w http.ResponseWriter, r *http.Request) {\n\t\tJSON(w, h{\n\t\t\t\"levels\": VkWorker.Levels,\n\t\t\t\"events\": VkWorker.Events,\n\t\t})\n\t})\n\n\tloaderio := os.Getenv(\"LOADERIO\")\n\tloaderioRoute := fmt.Sprintf(\"\/loaderio-%s\", loaderio)\n\trouter.Get(loaderioRoute, func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(fmt.Sprintf(\"loaderio-%s\", loaderio)))\n\t})\n\n\treturn router\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nfunc main() {\n\tif strings.Contains(os.Args[0], \"run_e2e.sh\") || strings.Contains(os.Args[0], \"gorunner\") {\n\t\tlog.Print(\"warn: calling test with e2e.test is deprecated and will be removed in 1.25, please rely on container manifest to invoke executable\")\n\t}\n\tenv := envWithDefaults(map[string]string{\n\t\tresultsDirEnvKey: defaultResultsDir,\n\t\tskipEnvKey:       defaultSkip,\n\t\tfocusEnvKey:      defaultFocus,\n\t\tproviderEnvKey:   defaultProvider,\n\t\tparallelEnvKey:   defaultParallel,\n\t\tginkgoEnvKey:     defaultGinkgoBinary,\n\t\ttestBinEnvKey:    defaultTestBinary,\n\t})\n\n\tif err := configureAndRunWithEnv(env); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\/\/ configureAndRunWithEnv uses the given environment to configure and then start the test run.\n\/\/ It will handle TERM signals gracefully and kill the test process and will\n\/\/ save the logs\/results to the location specified via the RESULTS_DIR environment\n\/\/ variable.\nfunc configureAndRunWithEnv(env Getenver) error {\n\t\/\/ Ensure we save results regardless of other errors. This helps any\n\t\/\/ consumer who may be polling for the results.\n\tresultsDir := env.Getenv(resultsDirEnvKey)\n\tdefer saveResults(resultsDir)\n\n\t\/\/ Print the output to stdout and a logfile which will be returned\n\t\/\/ as part of the results tarball.\n\tlogFilePath := filepath.Join(resultsDir, logFileName)\n\tlogFile, err := os.Create(logFilePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create log file %v: %w\", logFilePath, err)\n\t}\n\tmw := io.MultiWriter(os.Stdout, logFile)\n\tcmd := getCmd(env, mw)\n\n\tlog.Printf(\"Running command:\\n%v\\n\", cmdInfo(cmd))\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"starting command: %w\", err)\n\t}\n\n\t\/\/ Handle signals and shutdown process gracefully.\n\tgo setupSigHandler(cmd.Process.Pid)\n\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"running command: %w\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ setupSigHandler will kill the process identified by the given PID if it\n\/\/ gets a TERM signal.\nfunc setupSigHandler(pid int) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\n\t\/\/ Block until a signal is received.\n\tlog.Println(\"Now listening for interrupts\")\n\ts := <-c\n\tlog.Printf(\"Got signal: %v. Shutting down test process (PID: %v)\\n\", s, pid)\n\tp, err := os.FindProcess(pid)\n\tif err != nil {\n\t\tlog.Printf(\"Could not find process %v to shut down.\\n\", pid)\n\t\treturn\n\t}\n\tif err := p.Signal(s); err != nil {\n\t\tlog.Printf(\"Failed to signal test process to terminate: %v\\n\", err)\n\t\treturn\n\t}\n\tlog.Printf(\"Signalled process %v to terminate successfully.\\n\", pid)\n}\n\n\/\/ saveResults will tar the results directory and write the resulting tarball path\n\/\/ into the donefile.\nfunc saveResults(resultsDir string) error {\n\tlog.Printf(\"Saving results at %v\\n\", resultsDir)\n\n\terr := tarDir(resultsDir, filepath.Join(resultsDir, resultsTarballName))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"tar directory %v: %w\", resultsDir, err)\n\t}\n\n\tdoneFile := filepath.Join(resultsDir, doneFileName)\n\n\tresultsTarball := filepath.Join(resultsDir, resultsTarballName)\n\tresultsTarball, err = filepath.Abs(resultsTarball)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to find absolute path for %v: %w\", resultsTarball, err)\n\t}\n\n\terr = ioutil.WriteFile(doneFile, []byte(resultsTarball), os.FileMode(0777))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"writing donefile: %w\", err)\n\t}\n\n\treturn nil\n}\n<commit_msg>create resultsDir if the folder not exists<commit_after>\/*\nCopyright 2019 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nfunc main() {\n\tif strings.Contains(os.Args[0], \"run_e2e.sh\") || strings.Contains(os.Args[0], \"gorunner\") {\n\t\tlog.Print(\"warn: calling test with e2e.test is deprecated and will be removed in 1.25, please rely on container manifest to invoke executable\")\n\t}\n\tenv := envWithDefaults(map[string]string{\n\t\tresultsDirEnvKey: defaultResultsDir,\n\t\tskipEnvKey:       defaultSkip,\n\t\tfocusEnvKey:      defaultFocus,\n\t\tproviderEnvKey:   defaultProvider,\n\t\tparallelEnvKey:   defaultParallel,\n\t\tginkgoEnvKey:     defaultGinkgoBinary,\n\t\ttestBinEnvKey:    defaultTestBinary,\n\t})\n\n\tif err := configureAndRunWithEnv(env); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\/\/ configureAndRunWithEnv uses the given environment to configure and then start the test run.\n\/\/ It will handle TERM signals gracefully and kill the test process and will\n\/\/ save the logs\/results to the location specified via the RESULTS_DIR environment\n\/\/ variable.\nfunc configureAndRunWithEnv(env Getenver) error {\n\t\/\/ Ensure we save results regardless of other errors. This helps any\n\t\/\/ consumer who may be polling for the results.\n\tresultsDir := env.Getenv(resultsDirEnvKey)\n\tdefer saveResults(resultsDir)\n\n\t\/\/ Print the output to stdout and a logfile which will be returned\n\t\/\/ as part of the results tarball.\n\tlogFilePath := filepath.Join(resultsDir, logFileName)\n\t\/\/ ensure the resultsDir actually exists\n\tif _, err := os.Stat(resultsDir); os.IsNotExist(err) {\n\t\tlog.Printf(\"The resultsDir %v does not exist, will create it\", resultsDir)\n\t\tif mkdirErr := os.Mkdir(resultsDir, 0755); mkdirErr != nil {\n\t\t\treturn fmt.Errorf(\"failed to create log directory %v: %w\", resultsDir, mkdirErr)\n\t\t}\n\t}\n\tlogFile, err := os.Create(logFilePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create log file %v: %w\", logFilePath, err)\n\t}\n\tmw := io.MultiWriter(os.Stdout, logFile)\n\tcmd := getCmd(env, mw)\n\n\tlog.Printf(\"Running command:\\n%v\\n\", cmdInfo(cmd))\n\terr = cmd.Start()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"starting command: %w\", err)\n\t}\n\n\t\/\/ Handle signals and shutdown process gracefully.\n\tgo setupSigHandler(cmd.Process.Pid)\n\n\terr = cmd.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"running command: %w\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ setupSigHandler will kill the process identified by the given PID if it\n\/\/ gets a TERM signal.\nfunc setupSigHandler(pid int) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\n\t\/\/ Block until a signal is received.\n\tlog.Println(\"Now listening for interrupts\")\n\ts := <-c\n\tlog.Printf(\"Got signal: %v. Shutting down test process (PID: %v)\\n\", s, pid)\n\tp, err := os.FindProcess(pid)\n\tif err != nil {\n\t\tlog.Printf(\"Could not find process %v to shut down.\\n\", pid)\n\t\treturn\n\t}\n\tif err := p.Signal(s); err != nil {\n\t\tlog.Printf(\"Failed to signal test process to terminate: %v\\n\", err)\n\t\treturn\n\t}\n\tlog.Printf(\"Signalled process %v to terminate successfully.\\n\", pid)\n}\n\n\/\/ saveResults will tar the results directory and write the resulting tarball path\n\/\/ into the donefile.\nfunc saveResults(resultsDir string) error {\n\tlog.Printf(\"Saving results at %v\\n\", resultsDir)\n\n\terr := tarDir(resultsDir, filepath.Join(resultsDir, resultsTarballName))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"tar directory %v: %w\", resultsDir, err)\n\t}\n\n\tdoneFile := filepath.Join(resultsDir, doneFileName)\n\n\tresultsTarball := filepath.Join(resultsDir, resultsTarballName)\n\tresultsTarball, err = filepath.Abs(resultsTarball)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to find absolute path for %v: %w\", resultsTarball, err)\n\t}\n\n\terr = ioutil.WriteFile(doneFile, []byte(resultsTarball), os.FileMode(0777))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"writing donefile: %w\", err)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\tflag \"github.com\/spf13\/pflag\"\n\t\"golang.org\/x\/oauth2\"\n\t\"golang.org\/x\/oauth2\/google\"\n\t\"google.golang.org\/api\/gmail\/v1\"\n)\n\n\/\/ GmaildConfig is the format for the gmaild daemon\ntype GmaildConfig struct {\n\t\/\/ The file path to credentials file\n\t\/\/ defaults to $HOME\/credentials.json\n\tCredFile string\n\t\/\/ The file path to the token file\n\t\/\/ defaults to $HOME\/token.json\n\tTokFile string\n\t\/\/ The command to get executed on new messages\n\tExecString string\n}\n\nfunc getClient(tokFile string, config *oauth2.Config) *http.Client {\n\ttok, err := tokenFromFile(tokFile)\n\tif err == nil {\n\t\treturn config.Client(context.Background(), tok)\n\t}\n\n\ttok, err = getTokenFromWeb(config)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get auth token from gmail: %v\", err)\n\t}\n\tsaveToken(tokFile, tok)\n\treturn config.Client(context.Background(), tok)\n}\n\nfunc getTokenFromWeb(config *oauth2.Config) (*oauth2.Token, error) {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go here: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tmsg := fmt.Sprintf(\"Could not read auth code: %v\", err)\n\t\treturn nil, errors.New(msg)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Unable to retrieve token from web: %v\", err)\n\t\treturn nil, errors.New(msg)\n\t}\n\treturn tok, nil\n}\n\nfunc tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}\n\nfunc saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache auth token: %s\\n\", err)\n\t}\n\tdefer f.Close()\n\n\tjson.NewEncoder(f).Encode(token)\n}\n\nfunc getMessage(srv *gmail.Service, userID string, messageID string) (*gmail.Message, error) {\n\treturn srv.Users.Messages.Get(userID, messageID).Do()\n}\n\nfunc getMostRecentHistoryID(srv *gmail.Service, userID string) (uint64, error) {\n\tr, err := srv.Users.Messages.List(userID).MaxResults(1).Do()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tfor _, m := range r.Messages {\n\t\tmessage, err := getMessage(srv, userID, m.Id)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn message.HistoryId, nil\n\t}\n\n\treturn 0, errors.New(\"Could not get the most recent history ID\")\n}\n\n\/\/ First result = has new messages since\n\/\/ second result = most recently seen history ID\nfunc hasMessagesSince(srv *gmail.Service, userID string, historyID uint64) (bool, uint64) {\n\tr, err := srv.Users.History.List(userID).HistoryTypes(\"messageAdded\").StartHistoryId(historyID).Do()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get message history due to %v\\n\", err)\n\t}\n\n\tnewHistoryID := r.HistoryId\n\thasResults := (len(r.History) > 0)\n\treturn hasResults, newHistoryID\n}\n\nfunc parseCommandLine(\n\tusr *user.User,\n\targuments []string,\n) (*GmaildConfig, error) {\n\thomeDir := usr.HomeDir\n\tdefaultCredentials := filepath.Join(homeDir, \"credentials.json\")\n\tdefaultTokFile := filepath.Join(homeDir, \"token.json\")\n\n\tdefaultCommand := flag.NewFlagSet(\"gmaild\", flag.ExitOnError)\n\tcredFile := defaultCommand.StringP(\n\t\t\"credentials\",\n\t\t\"c\",\n\t\tdefaultCredentials,\n\t\t\"Saved credentials file\")\n\ttokFile := defaultCommand.StringP(\"token\", \"t\", defaultTokFile, \"Saved token file\")\n\texec := defaultCommand.StringP(\"exec\", \"e\", \"\", \"Command to execute for each message\")\n\n\tif len(arguments) <= 1 {\n\t\t\/\/ Clearly this is buggy crap\n\t\tdefaultCommand.PrintDefaults()\n\t\treturn nil, errors.New(\"Invalid command string format\")\n\t}\n\n\tdefaultCommand.Parse(arguments[1:])\n\n\tif len(*exec) == 0 {\n\t\treturn nil, errors.New(\"Exec string must be set\")\n\t}\n\n\tconfig := GmaildConfig{\n\t\tCredFile:   *credFile,\n\t\tTokFile:    *tokFile,\n\t\tExecString: *exec,\n\t}\n\treturn &config, nil\n}\n\nfunc main() {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not determine current user %v\\n\", err)\n\t}\n\tgmaildConfig, err := parseCommandLine(usr, os.Args)\n\t\n  if err != nil {\n    log.Fatalf(\"%v\\n\", err)\n\t}\n\n\tb, err := ioutil.ReadFile(gmaildConfig.CredFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to read client secret: %v\\n\", err)\n\t}\n\n\tconfig, err := google.ConfigFromJSON(b, gmail.GmailReadonlyScope)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to parse client secret: %v\\n\", err)\n\t}\n\tclient := getClient(gmaildConfig.TokFile, config)\n\n\tsrv, err := gmail.New(client)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to get Gmail client: %v\\n\", err)\n\t}\n\n\tuser := \"me\"\n\thistoryID, err := getMostRecentHistoryID(srv, user)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\thasMessages := false\n\tticker := time.NewTicker(30 * time.Second)\n\tquit := make(chan os.Signal, 1)\n\tsignal.Notify(quit, os.Interrupt)\n\nouter:\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n      oldHistoryID := historyID\n\t\t\thasMessages, historyID = hasMessagesSince(srv, user, historyID)\n\t\t\tfmt.Printf(\"Checking for messages between %v -> %v\\n\", oldHistoryID, historyID)\n\t\t\tif hasMessages {\n\t\t\t\tcmd := exec.Command(\"bash\", \"-c\", gmaildConfig.ExecString)\n\t\t\t\tvar out bytes.Buffer\n\t\t\t\tcmd.Stdout = &out\n\t\t\t\terr := cmd.Run()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"Result: %v\\n\", out.String())\n\t\t\t}\n\t\tcase <-quit:\n\t\t\tbreak outer\n\t\t}\n\t}\n\tticker.Stop()\n}\n<commit_msg>Factor out message channel to its own function<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\tflag \"github.com\/spf13\/pflag\"\n\t\"golang.org\/x\/oauth2\"\n\t\"golang.org\/x\/oauth2\/google\"\n\t\"google.golang.org\/api\/gmail\/v1\"\n)\n\n\/\/ GmaildConfig is the format for the gmaild daemon\ntype GmaildConfig struct {\n\t\/\/ The file path to credentials file\n\t\/\/ defaults to $HOME\/credentials.json\n\tCredFile string\n\t\/\/ The file path to the token file\n\t\/\/ defaults to $HOME\/token.json\n\tTokFile string\n\t\/\/ The command to get executed on new messages\n\tExecString string\n}\n\n\/\/ A MessageEvent is a wrapper for each message received\n\/\/ when checking for gmail events\ntype MessageEvent struct {\n\t\/\/ The receieved email associated with the message event\n\tMessageAdded gmail.Message\n}\n\nfunc getClient(tokFile string, config *oauth2.Config) *http.Client {\n\ttok, err := tokenFromFile(tokFile)\n\tif err == nil {\n\t\treturn config.Client(context.Background(), tok)\n\t}\n\n\ttok, err = getTokenFromWeb(config)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get auth token from gmail: %v\", err)\n\t}\n\tsaveToken(tokFile, tok)\n\treturn config.Client(context.Background(), tok)\n}\n\nfunc getTokenFromWeb(config *oauth2.Config) (*oauth2.Token, error) {\n\tauthURL := config.AuthCodeURL(\"state-token\", oauth2.AccessTypeOffline)\n\tfmt.Printf(\"Go here: \\n%v\\n\", authURL)\n\n\tvar authCode string\n\tif _, err := fmt.Scan(&authCode); err != nil {\n\t\tmsg := fmt.Sprintf(\"Could not read auth code: %v\", err)\n\t\treturn nil, errors.New(msg)\n\t}\n\n\ttok, err := config.Exchange(context.TODO(), authCode)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Unable to retrieve token from web: %v\", err)\n\t\treturn nil, errors.New(msg)\n\t}\n\treturn tok, nil\n}\n\nfunc tokenFromFile(file string) (*oauth2.Token, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\ttok := &oauth2.Token{}\n\terr = json.NewDecoder(f).Decode(tok)\n\treturn tok, err\n}\n\nfunc saveToken(path string, token *oauth2.Token) {\n\tfmt.Printf(\"Saving credential file to %s\\n\", path)\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to cache auth token: %s\\n\", err)\n\t}\n\tdefer f.Close()\n\n\tjson.NewEncoder(f).Encode(token)\n}\n\nfunc getMessage(srv *gmail.Service, userID string, messageID string) (*gmail.Message, error) {\n\treturn srv.Users.Messages.Get(userID, messageID).Do()\n}\n\nfunc getMostRecentHistoryID(srv *gmail.Service, userID string) (uint64, error) {\n\tr, err := srv.Users.Messages.List(userID).MaxResults(1).Do()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tfor _, m := range r.Messages {\n\t\tmessage, err := getMessage(srv, userID, m.Id)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\treturn message.HistoryId, nil\n\t}\n\n\treturn 0, errors.New(\"Could not get the most recent history ID\")\n}\n\n\/\/ First result = most recently seen history ID\n\/\/ second result = Any messages since last update\nfunc hasMessagesSince(srv *gmail.Service, userID string, historyID uint64) (uint64, []MessageEvent) {\n\tr, err := srv.Users.History.List(userID).HistoryTypes(\"messageAdded\").StartHistoryId(historyID).Do()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get message history due to %v\\n\", err)\n\t}\n\n\tnewHistoryID := r.HistoryId\n\tresult := make([]MessageEvent, 0)\n\tfor _, h := range r.History {\n\t\tfor _, messageAdded := range h.MessagesAdded {\n\t\t\tmessageEvent := MessageEvent{\n\t\t\t\tMessageAdded: *messageAdded.Message,\n\t\t\t}\n\n\t\t\tresult = append(result, messageEvent)\n\t\t}\n\t}\n\n\treturn newHistoryID, result\n}\n\nfunc parseCommandLine(\n\tusr *user.User,\n\targuments []string,\n) (*GmaildConfig, error) {\n\thomeDir := usr.HomeDir\n\tdefaultCredentials := filepath.Join(homeDir, \"credentials.json\")\n\tdefaultTokFile := filepath.Join(homeDir, \"token.json\")\n\n\tdefaultCommand := flag.NewFlagSet(\"gmaild\", flag.ExitOnError)\n\tcredFile := defaultCommand.StringP(\n\t\t\"credentials\",\n\t\t\"c\",\n\t\tdefaultCredentials,\n\t\t\"Saved credentials file\")\n\ttokFile := defaultCommand.StringP(\"token\", \"t\", defaultTokFile, \"Saved token file\")\n\texec := defaultCommand.StringP(\"exec\", \"e\", \"\", \"Command to execute for each message\")\n\n\tif len(arguments) <= 1 {\n\t\t\/\/ Clearly this is buggy crap\n\t\tdefaultCommand.PrintDefaults()\n\t\treturn nil, errors.New(\"Invalid command string format\")\n\t}\n\n\tdefaultCommand.Parse(arguments[1:])\n\n\tif len(*exec) == 0 {\n\t\treturn nil, errors.New(\"Exec string must be set\")\n\t}\n\n\tconfig := GmaildConfig{\n\t\tCredFile:   *credFile,\n\t\tTokFile:    *tokFile,\n\t\tExecString: *exec,\n\t}\n\treturn &config, nil\n}\n\nfunc getNewMessages(\n\tsrv *gmail.Service,\n\tuserID string,\n\tstartHistoryID uint64) <-chan MessageEvent {\n\tmessageEventChan := make(chan MessageEvent)\n\n\thistoryID := startHistoryID\n\tgo func() {\n\t\tticker := time.NewTicker(30 * time.Second)\n\t\tfor range ticker.C {\n\t\t\tvar messages []MessageEvent\n\t\t\toldHistoryID := historyID\n\t\t\thistoryID, messages = hasMessagesSince(srv, userID, historyID)\n\t\t\tfmt.Printf(\"Checking for messages between %v -> %v\\n\", oldHistoryID, historyID)\n\t\t\tfor _, message := range messages {\n\t\t\t\tmessageEventChan <- message\n\t\t\t}\n\t\t}\n\t\tclose(messageEventChan)\n\t}()\n\n\treturn messageEventChan\n}\n\nfunc main() {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not determine current user %v\\n\", err)\n\t}\n\n\tgmaildConfig, err := parseCommandLine(usr, os.Args)\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\\n\", err)\n\t}\n\n\tb, err := ioutil.ReadFile(gmaildConfig.CredFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to read client secret: %v\\n\", err)\n\t}\n\n\tconfig, err := google.ConfigFromJSON(b, gmail.GmailReadonlyScope)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to parse client secret: %v\\n\", err)\n\t}\n\n\tclient := getClient(gmaildConfig.TokFile, config)\n\tsrv, err := gmail.New(client)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to get Gmail client: %v\\n\", err)\n\t}\n\n\tuser := \"me\"\n\thistoryID, err := getMostRecentHistoryID(srv, user)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tmessageChannel := getNewMessages(srv, user, historyID)\n\tquit := make(chan os.Signal, 1)\n\tsignal.Notify(quit, os.Interrupt)\n\nouter:\n\tfor {\n\t\tselect {\n\t\tcase message := <-messageChannel:\n\t\t\tcmd := exec.Command(\"bash\", \"-c\", gmaildConfig.ExecString)\n\t\t\tfmt.Printf(\"%v\\n\", message.MessageAdded.Raw)\n\n\t\t\tvar out bytes.Buffer\n\t\t\tcmd.Stdout = &out\n\t\t\terr := cmd.Run()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tfmt.Printf(\"Result: %v\\n\", out.String())\n\t\tcase <-quit:\n\t\t\tbreak outer\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gorush\n\nimport (\n\t\"github.com\/gin-gonic\/gin\"\n\t\"gopkg.in\/redis.v3\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"sync\/atomic\"\n)\n\n\/\/ StatusApp is app status structure\ntype StatusApp struct {\n\tQueueMax   int           `json:\"queue_max\"`\n\tQueueUsage int           `json:\"queue_usage\"`\n\tTotalCount int64         `json:\"total_count\"`\n\tIos        IosStatus     `json:\"ios\"`\n\tAndroid    AndroidStatus `json:\"android\"`\n}\n\n\/\/ AndroidStatus is android structure\ntype AndroidStatus struct {\n\tPushSuccess int64 `json:\"push_success\"`\n\tPushError   int64 `json:\"push_error\"`\n}\n\n\/\/ IosStatus is iOS structure\ntype IosStatus struct {\n\tPushSuccess int64 `json:\"push_success\"`\n\tPushError   int64 `json:\"push_error\"`\n}\n\nfunc initApp() {\n\tRushStatus.TotalCount = 0\n\tRushStatus.Ios.PushSuccess = 0\n\tRushStatus.Ios.PushError = 0\n\tRushStatus.Android.PushSuccess = 0\n\tRushStatus.Android.PushError = 0\n}\n\n\/\/ InitAppStatus for initialize app status\nfunc InitAppStatus() {\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tinitApp()\n\tcase \"redis\":\n\t\tRedisClient = redis.NewClient(&redis.Options{\n\t\t\tAddr:     PushConf.Stat.Redis.Addr,\n\t\t\tPassword: PushConf.Stat.Redis.Password,\n\t\t\tDB:       PushConf.Stat.Redis.DB,\n\t\t})\n\tdefault:\n\t\tinitApp()\n\t}\n\n}\n\nfunc addTotalCount(count int64) {\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tatomic.AddInt64(&RushStatus.TotalCount, count)\n\tcase \"redis\":\n\t\tRedisClient.Set(\"key1\", strconv.Itoa(int(count)), 0)\n\tdefault:\n\t\tatomic.AddInt64(&RushStatus.TotalCount, count)\n\t}\n}\n\nfunc addIosSuccess(count int64) {\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tatomic.AddInt64(&RushStatus.Ios.PushSuccess, count)\n\tcase \"redis\":\n\t\tRedisClient.Set(\"key2\", strconv.Itoa(int(count)), 0)\n\tdefault:\n\t\tatomic.AddInt64(&RushStatus.Ios.PushSuccess, count)\n\t}\n}\n\nfunc addIosError(count int64) {\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tatomic.AddInt64(&RushStatus.Ios.PushError, count)\n\tcase \"redis\":\n\t\tRedisClient.Set(\"key3\", strconv.Itoa(int(count)), 0)\n\tdefault:\n\t\tatomic.AddInt64(&RushStatus.Ios.PushError, count)\n\t}\n}\n\nfunc addAndroidSuccess(count int64) {\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tatomic.AddInt64(&RushStatus.Android.PushSuccess, count)\n\tcase \"redis\":\n\n\t\tRedisClient.Set(\"key4\", strconv.Itoa(int(count)), 0)\n\tdefault:\n\t\tatomic.AddInt64(&RushStatus.Android.PushSuccess, count)\n\t}\n}\n\nfunc addAndroidError(count int64) {\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tatomic.AddInt64(&RushStatus.Android.PushError, count)\n\tcase \"redis\":\n\t\tRedisClient.Set(\"key5\", strconv.Itoa(int(count)), 0)\n\tdefault:\n\t\tatomic.AddInt64(&RushStatus.Android.PushError, count)\n\t}\n}\n\nfunc getTotalCount() int64 {\n\tvar count int64\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tcount = atomic.LoadInt64(&RushStatus.TotalCount)\n\tcase \"redis\":\n\t\tval, _ := RedisClient.Get(\"key1\").Result()\n\t\tcount, _ = strconv.ParseInt(val, 10, 64)\n\tdefault:\n\t\tcount = atomic.LoadInt64(&RushStatus.TotalCount)\n\t}\n\n\treturn count\n}\n\nfunc getIosSuccess() int64 {\n\tvar count int64\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tcount = atomic.LoadInt64(&RushStatus.Ios.PushSuccess)\n\tcase \"redis\":\n\t\tval, _ := RedisClient.Get(\"key2\").Result()\n\t\tcount, _ = strconv.ParseInt(val, 10, 64)\n\tdefault:\n\t\tcount = atomic.LoadInt64(&RushStatus.Ios.PushSuccess)\n\t}\n\n\treturn count\n}\n\nfunc getIosError() int64 {\n\tvar count int64\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tcount = atomic.LoadInt64(&RushStatus.Ios.PushError)\n\tcase \"redis\":\n\t\tval, _ := RedisClient.Get(\"key3\").Result()\n\t\tcount, _ = strconv.ParseInt(val, 10, 64)\n\tdefault:\n\t\tcount = atomic.LoadInt64(&RushStatus.Ios.PushError)\n\t}\n\n\treturn count\n}\n\nfunc getAndroidSuccess() int64 {\n\tvar count int64\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tcount = atomic.LoadInt64(&RushStatus.Android.PushSuccess)\n\tcase \"redis\":\n\t\tval, _ := RedisClient.Get(\"key4\").Result()\n\t\tcount, _ = strconv.ParseInt(val, 10, 64)\n\tdefault:\n\t\tcount = atomic.LoadInt64(&RushStatus.Android.PushSuccess)\n\t}\n\n\treturn count\n}\n\nfunc getAndroidError() int64 {\n\tvar count int64\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tcount = atomic.LoadInt64(&RushStatus.Android.PushError)\n\tcase \"redis\":\n\t\tval, _ := RedisClient.Get(\"key5\").Result()\n\t\tcount, _ = strconv.ParseInt(val, 10, 64)\n\tdefault:\n\t\tcount = atomic.LoadInt64(&RushStatus.Android.PushError)\n\t}\n\n\treturn count\n}\n\nfunc appStatusHandler(c *gin.Context) {\n\tresult := StatusApp{}\n\n\tresult.QueueMax = cap(QueueNotification)\n\tresult.QueueUsage = len(QueueNotification)\n\tresult.TotalCount = getTotalCount()\n\tresult.Ios.PushSuccess = getIosSuccess()\n\tresult.Ios.PushError = getIosError()\n\tresult.Android.PushSuccess = getAndroidSuccess()\n\tresult.Android.PushError = getAndroidError()\n\n\tc.JSON(http.StatusOK, result)\n}\n<commit_msg>fix initial error count for redis.<commit_after>package gorush\n\nimport (\n\t\"github.com\/gin-gonic\/gin\"\n\t\"gopkg.in\/redis.v3\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"sync\/atomic\"\n)\n\n\/\/ StatusApp is app status structure\ntype StatusApp struct {\n\tQueueMax   int           `json:\"queue_max\"`\n\tQueueUsage int           `json:\"queue_usage\"`\n\tTotalCount int64         `json:\"total_count\"`\n\tIos        IosStatus     `json:\"ios\"`\n\tAndroid    AndroidStatus `json:\"android\"`\n}\n\n\/\/ AndroidStatus is android structure\ntype AndroidStatus struct {\n\tPushSuccess int64 `json:\"push_success\"`\n\tPushError   int64 `json:\"push_error\"`\n}\n\n\/\/ IosStatus is iOS structure\ntype IosStatus struct {\n\tPushSuccess int64 `json:\"push_success\"`\n\tPushError   int64 `json:\"push_error\"`\n}\n\nfunc initApp() {\n\tRushStatus.TotalCount = 0\n\tRushStatus.Ios.PushSuccess = 0\n\tRushStatus.Ios.PushError = 0\n\tRushStatus.Android.PushSuccess = 0\n\tRushStatus.Android.PushError = 0\n}\n\n\/\/ InitAppStatus for initialize app status\nfunc InitAppStatus() {\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tinitApp()\n\tcase \"redis\":\n\t\tRedisClient = redis.NewClient(&redis.Options{\n\t\t\tAddr:     PushConf.Stat.Redis.Addr,\n\t\t\tPassword: PushConf.Stat.Redis.Password,\n\t\t\tDB:       PushConf.Stat.Redis.DB,\n\t\t})\n\n\t\tRushStatus.TotalCount = getTotalCount()\n\t\tRushStatus.Ios.PushSuccess = getIosSuccess()\n\t\tRushStatus.Ios.PushError = getIosError()\n\t\tRushStatus.Android.PushSuccess = getAndroidSuccess()\n\t\tRushStatus.Android.PushError = getAndroidError()\n\tdefault:\n\t\tinitApp()\n\t}\n\n}\n\nfunc addTotalCount(count int64) {\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tatomic.AddInt64(&RushStatus.TotalCount, count)\n\tcase \"redis\":\n\t\tRedisClient.Set(\"key1\", strconv.Itoa(int(count)), 0)\n\tdefault:\n\t\tatomic.AddInt64(&RushStatus.TotalCount, count)\n\t}\n}\n\nfunc addIosSuccess(count int64) {\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tatomic.AddInt64(&RushStatus.Ios.PushSuccess, count)\n\tcase \"redis\":\n\t\tRedisClient.Set(\"key2\", strconv.Itoa(int(count)), 0)\n\tdefault:\n\t\tatomic.AddInt64(&RushStatus.Ios.PushSuccess, count)\n\t}\n}\n\nfunc addIosError(count int64) {\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tatomic.AddInt64(&RushStatus.Ios.PushError, count)\n\tcase \"redis\":\n\t\tRedisClient.Set(\"key3\", strconv.Itoa(int(count)), 0)\n\tdefault:\n\t\tatomic.AddInt64(&RushStatus.Ios.PushError, count)\n\t}\n}\n\nfunc addAndroidSuccess(count int64) {\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tatomic.AddInt64(&RushStatus.Android.PushSuccess, count)\n\tcase \"redis\":\n\n\t\tRedisClient.Set(\"key4\", strconv.Itoa(int(count)), 0)\n\tdefault:\n\t\tatomic.AddInt64(&RushStatus.Android.PushSuccess, count)\n\t}\n}\n\nfunc addAndroidError(count int64) {\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tatomic.AddInt64(&RushStatus.Android.PushError, count)\n\tcase \"redis\":\n\t\tRedisClient.Set(\"key5\", strconv.Itoa(int(count)), 0)\n\tdefault:\n\t\tatomic.AddInt64(&RushStatus.Android.PushError, count)\n\t}\n}\n\nfunc getTotalCount() int64 {\n\tvar count int64\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tcount = atomic.LoadInt64(&RushStatus.TotalCount)\n\tcase \"redis\":\n\t\tval, _ := RedisClient.Get(\"key1\").Result()\n\t\tcount, _ = strconv.ParseInt(val, 10, 64)\n\tdefault:\n\t\tcount = atomic.LoadInt64(&RushStatus.TotalCount)\n\t}\n\n\treturn count\n}\n\nfunc getIosSuccess() int64 {\n\tvar count int64\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tcount = atomic.LoadInt64(&RushStatus.Ios.PushSuccess)\n\tcase \"redis\":\n\t\tval, _ := RedisClient.Get(\"key2\").Result()\n\t\tcount, _ = strconv.ParseInt(val, 10, 64)\n\tdefault:\n\t\tcount = atomic.LoadInt64(&RushStatus.Ios.PushSuccess)\n\t}\n\n\treturn count\n}\n\nfunc getIosError() int64 {\n\tvar count int64\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tcount = atomic.LoadInt64(&RushStatus.Ios.PushError)\n\tcase \"redis\":\n\t\tval, _ := RedisClient.Get(\"key3\").Result()\n\t\tcount, _ = strconv.ParseInt(val, 10, 64)\n\tdefault:\n\t\tcount = atomic.LoadInt64(&RushStatus.Ios.PushError)\n\t}\n\n\treturn count\n}\n\nfunc getAndroidSuccess() int64 {\n\tvar count int64\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tcount = atomic.LoadInt64(&RushStatus.Android.PushSuccess)\n\tcase \"redis\":\n\t\tval, _ := RedisClient.Get(\"key4\").Result()\n\t\tcount, _ = strconv.ParseInt(val, 10, 64)\n\tdefault:\n\t\tcount = atomic.LoadInt64(&RushStatus.Android.PushSuccess)\n\t}\n\n\treturn count\n}\n\nfunc getAndroidError() int64 {\n\tvar count int64\n\tswitch PushConf.Stat.Engine {\n\tcase \"memory\":\n\t\tcount = atomic.LoadInt64(&RushStatus.Android.PushError)\n\tcase \"redis\":\n\t\tval, _ := RedisClient.Get(\"key5\").Result()\n\t\tcount, _ = strconv.ParseInt(val, 10, 64)\n\tdefault:\n\t\tcount = atomic.LoadInt64(&RushStatus.Android.PushError)\n\t}\n\n\treturn count\n}\n\nfunc appStatusHandler(c *gin.Context) {\n\tresult := StatusApp{}\n\n\tresult.QueueMax = cap(QueueNotification)\n\tresult.QueueUsage = len(QueueNotification)\n\tresult.TotalCount = getTotalCount()\n\tresult.Ios.PushSuccess = getIosSuccess()\n\tresult.Ios.PushError = getIosError()\n\tresult.Android.PushSuccess = getAndroidSuccess()\n\tresult.Android.PushError = getAndroidError()\n\n\tc.JSON(http.StatusOK, result)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage oglemock_test\n\nimport (\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/ogletest\"\n\t\"github.com\/jacobsa\/oglemock\"\n\t\"math\"\n\t\"reflect\"\n\t\"testing\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvar someInt int = 17\n\ntype ReturnTest struct {\n}\n\nfunc init()                     { RegisterTestSuite(&ReturnTest{}) }\nfunc TestOgletest(t *testing.T) { RunTests(t) }\n\ntype returnTestCase struct {\n\tsuppliedVal interface{}\n\texpectedVal interface{}\n\texpectedCheckTypeResult bool\n\texpectedCheckTypeErrorSubstring string\n}\n\nfunc (t *ReturnTest) runTestCases(signature reflect.Type, cases []returnTestCase) {\n\tfor i, c := range cases {\n\t\ta := oglemock.Return(c.suppliedVal)\n\n\t\t\/\/ CheckType\n\t\terr := a.CheckType(signature)\n\t\tif c.expectedCheckTypeResult {\n\t\t\tExpectEq(nil, err, \"Test case %d: %v\", i, c)\n\t\t} else {\n\t\t\tExpectThat(err, Error(HasSubstr(c.expectedCheckTypeErrorSubstring)),\n\t\t\t\t\"Test case %d: %v\", i, c)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Invoke\n\t\tres := a.Invoke([]interface{}{})\n\t\tAssertThat(res, ElementsAre(Any()))\n\t\tExpectThat(res[0], IdenticalTo(c.expectedVal), \"Test case %d: %v\", i, c)\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *ReturnTest) NoReturnValues() {\n\tsig := reflect.TypeOf(func() {})\n\tvar a oglemock.Action\n\tvar err error\n\tvar vals []interface{}\n\n\t\/\/ No values.\n\ta = oglemock.Return()\n\terr = a.CheckType(sig)\n\tAssertEq(nil, err)\n\n\tvals = a.Invoke([]interface{}{})\n\tExpectThat(vals, ElementsAre())\n\n\t\/\/ One value.\n\ta = oglemock.Return(17)\n\terr = a.CheckType(sig)\n\tExpectThat(err, Error(HasSubstr(\"given 1 val\")))\n\tExpectThat(err, Error(HasSubstr(\"expected 0\")))\n\n\t\/\/ Two values.\n\ta = oglemock.Return(17, 19)\n\terr = a.CheckType(sig)\n\tExpectThat(err, Error(HasSubstr(\"given 2 vals\")))\n\tExpectThat(err, Error(HasSubstr(\"expected 0\")))\n}\n\nfunc (t *ReturnTest) MultipleReturnValues() {\n\tsig := reflect.TypeOf(func() (int, string) { return 0, \"\" })\n\tvar a oglemock.Action\n\tvar err error\n\tvar vals []interface{}\n\n\t\/\/ No values.\n\ta = oglemock.Return()\n\terr = a.CheckType(sig)\n\tExpectThat(err, Error(HasSubstr(\"given 0 vals\")))\n\tExpectThat(err, Error(HasSubstr(\"expected 2\")))\n\n\t\/\/ One value.\n\ta = oglemock.Return(17)\n\terr = a.CheckType(sig)\n\tExpectThat(err, Error(HasSubstr(\"given 1 val\")))\n\tExpectThat(err, Error(HasSubstr(\"expected 2\")))\n\n\t\/\/ Two values.\n\ta = oglemock.Return(17, \"taco\")\n\terr = a.CheckType(sig)\n\tAssertEq(nil, err)\n\n\tvals = a.Invoke([]interface{}{})\n\tExpectThat(vals, ElementsAre(IdenticalTo(int(17)), \"taco\"))\n}\n\nfunc (t *ReturnTest) Bool() {\n\ttype namedType bool\n\n\tsig := reflect.TypeOf(func() bool { return false })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ bool(true), bool(true), true, \"\" },\n\t\t{ bool(false), bool(false), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(true), bool(true), true, \"\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int16(1), nil, false, \"given int\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Int() {\n\ttype namedType int\n\n\tsig := reflect.TypeOf(func() int { return 0 })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ int(0), int(0), true, \"\" },\n\t\t{ int(math.MaxInt32), int(math.MaxInt32), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(17), int(17), true, \"\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int16(1), nil, false, \"given int16\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Int8() {\n\ttype namedType int8\n\n\tsig := reflect.TypeOf(func() int8 { return 0 })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ int8(0), int8(0), true, \"\" },\n\t\t{ int8(math.MaxInt8), int8(math.MaxInt8), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(17), int8(17), true, \"\" },\n\n\t\t\/\/ In-range ints.\n\t\t{ int(17), int8(17), true, \"\" },\n\t\t{ int(math.MaxInt8), int8(math.MaxInt8), true, \"\" },\n\n\t\t\/\/ Out of range ints.\n\t\t{ int(math.MaxInt8 + 1), nil, false, \"out of range\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int16(1), nil, false, \"given int16\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Int16() {\n\ttype namedType int16\n\n\tsig := reflect.TypeOf(func() int16 { return 0 })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ int16(0), int16(0), true, \"\" },\n\t\t{ int16(math.MaxInt16), int16(math.MaxInt16), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(17), int16(17), true, \"\" },\n\n\t\t\/\/ In-range ints.\n\t\t{ int(17), int16(17), true, \"\" },\n\t\t{ int(math.MaxInt16), int16(math.MaxInt16), true, \"\" },\n\n\t\t\/\/ Out of range ints.\n\t\t{ int(math.MaxInt16 + 1), nil, false, \"out of range\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int8(1), nil, false, \"given int8\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Int32() {\n\ttype namedType int32\n\n\tsig := reflect.TypeOf(func() int32 { return 0 })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ int32(0), int32(0), true, \"\" },\n\t\t{ int32(math.MaxInt32), int32(math.MaxInt32), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(17), int32(17), true, \"\" },\n\n\t\t\/\/ In-range ints.\n\t\t{ int(17), int32(17), true, \"\" },\n\t\t{ int(math.MaxInt32), int32(math.MaxInt32), true, \"\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int16(1), nil, false, \"given int16\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Rune() {\n\ttype namedType rune\n\n\tsig := reflect.TypeOf(func() rune { return 0 })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ rune(0), rune(0), true, \"\" },\n\t\t{ rune(math.MaxInt32), rune(math.MaxInt32), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(17), rune(17), true, \"\" },\n\n\t\t\/\/ Aliased version of type.\n\t\t{ int32(17), rune(17), true, \"\" },\n\n\t\t\/\/ In-range ints.\n\t\t{ int(17), rune(17), true, \"\" },\n\t\t{ int(math.MaxInt32), rune(math.MaxInt32), true, \"\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int16(1), nil, false, \"given int16\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Int64() {\n\ttype namedType int64\n\n\tsig := reflect.TypeOf(func() int64 { return 0 })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ int64(0), int64(0), true, \"\" },\n\t\t{ int64(math.MaxInt64), int64(math.MaxInt64), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(17), int64(17), true, \"\" },\n\n\t\t\/\/ In-range ints.\n\t\t{ int(17), int64(17), true, \"\" },\n\t\t{ int(math.MaxInt32), int64(math.MaxInt32), true, \"\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int16(1), nil, false, \"given int16\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Uint() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Uint8() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Byte() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Uint16() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Uint32() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Uint64() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Uintptr() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Float32() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Float64() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Complex64() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Complex128() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) ArrayOfInt() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) ChanOfInt() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Func() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Interface() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) MapFromStringToInt() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) PointerToString() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) SliceOfInts() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) String() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Struct() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) UnsafePointer() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) NamedNumericType() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) NamedNonNumericType() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) NamedChannelType() {\n\tExpectTrue(false, \"TODO\")\n}\n<commit_msg>Added negative test cases.<commit_after>\/\/ Copyright 2011 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage oglemock_test\n\nimport (\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/ogletest\"\n\t\"github.com\/jacobsa\/oglemock\"\n\t\"math\"\n\t\"reflect\"\n\t\"testing\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvar someInt int = 17\n\ntype ReturnTest struct {\n}\n\nfunc init()                     { RegisterTestSuite(&ReturnTest{}) }\nfunc TestOgletest(t *testing.T) { RunTests(t) }\n\ntype returnTestCase struct {\n\tsuppliedVal interface{}\n\texpectedVal interface{}\n\texpectedCheckTypeResult bool\n\texpectedCheckTypeErrorSubstring string\n}\n\nfunc (t *ReturnTest) runTestCases(signature reflect.Type, cases []returnTestCase) {\n\tfor i, c := range cases {\n\t\ta := oglemock.Return(c.suppliedVal)\n\n\t\t\/\/ CheckType\n\t\terr := a.CheckType(signature)\n\t\tif c.expectedCheckTypeResult {\n\t\t\tExpectEq(nil, err, \"Test case %d: %v\", i, c)\n\t\t} else {\n\t\t\tExpectThat(err, Error(HasSubstr(c.expectedCheckTypeErrorSubstring)),\n\t\t\t\t\"Test case %d: %v\", i, c)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Invoke\n\t\tres := a.Invoke([]interface{}{})\n\t\tAssertThat(res, ElementsAre(Any()))\n\t\tExpectThat(res[0], IdenticalTo(c.expectedVal), \"Test case %d: %v\", i, c)\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *ReturnTest) NoReturnValues() {\n\tsig := reflect.TypeOf(func() {})\n\tvar a oglemock.Action\n\tvar err error\n\tvar vals []interface{}\n\n\t\/\/ No values.\n\ta = oglemock.Return()\n\terr = a.CheckType(sig)\n\tAssertEq(nil, err)\n\n\tvals = a.Invoke([]interface{}{})\n\tExpectThat(vals, ElementsAre())\n\n\t\/\/ One value.\n\ta = oglemock.Return(17)\n\terr = a.CheckType(sig)\n\tExpectThat(err, Error(HasSubstr(\"given 1 val\")))\n\tExpectThat(err, Error(HasSubstr(\"expected 0\")))\n\n\t\/\/ Two values.\n\ta = oglemock.Return(17, 19)\n\terr = a.CheckType(sig)\n\tExpectThat(err, Error(HasSubstr(\"given 2 vals\")))\n\tExpectThat(err, Error(HasSubstr(\"expected 0\")))\n}\n\nfunc (t *ReturnTest) MultipleReturnValues() {\n\tsig := reflect.TypeOf(func() (int, string) { return 0, \"\" })\n\tvar a oglemock.Action\n\tvar err error\n\tvar vals []interface{}\n\n\t\/\/ No values.\n\ta = oglemock.Return()\n\terr = a.CheckType(sig)\n\tExpectThat(err, Error(HasSubstr(\"given 0 vals\")))\n\tExpectThat(err, Error(HasSubstr(\"expected 2\")))\n\n\t\/\/ One value.\n\ta = oglemock.Return(17)\n\terr = a.CheckType(sig)\n\tExpectThat(err, Error(HasSubstr(\"given 1 val\")))\n\tExpectThat(err, Error(HasSubstr(\"expected 2\")))\n\n\t\/\/ Two values.\n\ta = oglemock.Return(17, \"taco\")\n\terr = a.CheckType(sig)\n\tAssertEq(nil, err)\n\n\tvals = a.Invoke([]interface{}{})\n\tExpectThat(vals, ElementsAre(IdenticalTo(int(17)), \"taco\"))\n}\n\nfunc (t *ReturnTest) Bool() {\n\ttype namedType bool\n\n\tsig := reflect.TypeOf(func() bool { return false })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ bool(true), bool(true), true, \"\" },\n\t\t{ bool(false), bool(false), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(true), bool(true), true, \"\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int16(1), nil, false, \"given int\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Int() {\n\ttype namedType int\n\n\tsig := reflect.TypeOf(func() int { return 0 })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ int(math.MinInt32), int(math.MinInt32), true, \"\" },\n\t\t{ int(math.MaxInt32), int(math.MaxInt32), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(17), int(17), true, \"\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int16(1), nil, false, \"given int16\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Int8() {\n\ttype namedType int8\n\n\tsig := reflect.TypeOf(func() int8 { return 0 })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ int8(math.MinInt8), int8(math.MinInt8), true, \"\" },\n\t\t{ int8(math.MaxInt8), int8(math.MaxInt8), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(17), int8(17), true, \"\" },\n\n\t\t\/\/ In-range ints.\n\t\t{ int(math.MinInt8), int8(math.MinInt8), true, \"\" },\n\t\t{ int(math.MaxInt8), int8(math.MaxInt8), true, \"\" },\n\n\t\t\/\/ Out of range ints.\n\t\t{ int(math.MinInt8 - 1), nil, false, \"out of range\" },\n\t\t{ int(math.MaxInt8 + 1), nil, false, \"out of range\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int16(1), nil, false, \"given int16\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Int16() {\n\ttype namedType int16\n\n\tsig := reflect.TypeOf(func() int16 { return 0 })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ int16(math.MinInt16), int16(math.MinInt16), true, \"\" },\n\t\t{ int16(math.MaxInt16), int16(math.MaxInt16), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(17), int16(17), true, \"\" },\n\n\t\t\/\/ In-range ints.\n\t\t{ int(math.MinInt16), int16(math.MinInt16), true, \"\" },\n\t\t{ int(math.MaxInt16), int16(math.MaxInt16), true, \"\" },\n\n\t\t\/\/ Out of range ints.\n\t\t{ int(math.MinInt16 - 1), nil, false, \"out of range\" },\n\t\t{ int(math.MaxInt16 + 1), nil, false, \"out of range\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int8(1), nil, false, \"given int8\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Int32() {\n\ttype namedType int32\n\n\tsig := reflect.TypeOf(func() int32 { return 0 })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ int32(math.MinInt32), int32(math.MinInt32), true, \"\" },\n\t\t{ int32(math.MaxInt32), int32(math.MaxInt32), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(17), int32(17), true, \"\" },\n\n\t\t\/\/ In-range ints.\n\t\t{ int(math.MinInt32), int32(math.MinInt32), true, \"\" },\n\t\t{ int(math.MaxInt32), int32(math.MaxInt32), true, \"\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int16(1), nil, false, \"given int16\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Rune() {\n\ttype namedType rune\n\n\tsig := reflect.TypeOf(func() rune { return 0 })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ rune(math.MinInt32), rune(math.MinInt32), true, \"\" },\n\t\t{ rune(math.MaxInt32), rune(math.MaxInt32), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(17), rune(17), true, \"\" },\n\n\t\t\/\/ Aliased version of type.\n\t\t{ int32(17), rune(17), true, \"\" },\n\n\t\t\/\/ In-range ints.\n\t\t{ int(math.MinInt32), rune(math.MinInt32), true, \"\" },\n\t\t{ int(math.MaxInt32), rune(math.MaxInt32), true, \"\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int16(1), nil, false, \"given int16\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Int64() {\n\ttype namedType int64\n\n\tsig := reflect.TypeOf(func() int64 { return 0 })\n\tcases := []returnTestCase{\n\t\t\/\/ Identical types.\n\t\t{ int64(math.MinInt64), int64(math.MinInt64), true, \"\" },\n\t\t{ int64(math.MaxInt64), int64(math.MaxInt64), true, \"\" },\n\n\t\t\/\/ Named version of same underlying type.\n\t\t{ namedType(17), int64(17), true, \"\" },\n\n\t\t\/\/ In-range ints.\n\t\t{ int(math.MinInt32), int64(math.MinInt32), true, \"\" },\n\t\t{ int(math.MaxInt32), int64(math.MaxInt32), true, \"\" },\n\n\t\t\/\/ Wrong types.\n\t\t{ nil, nil, false, \"given <nil>\" },\n\t\t{ int16(1), nil, false, \"given int16\" },\n\t\t{ float64(1), nil, false, \"given float64\" },\n\t\t{ complex128(1), nil, false, \"given complex128\" },\n\t\t{ &someInt, nil, false, \"given *int\" },\n\t\t{ make(chan int), nil, false, \"given chan int\" },\n\t}\n\n\tt.runTestCases(sig, cases)\n}\n\nfunc (t *ReturnTest) Uint() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Uint8() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Byte() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Uint16() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Uint32() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Uint64() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Uintptr() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Float32() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Float64() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Complex64() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Complex128() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) ArrayOfInt() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) ChanOfInt() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Func() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Interface() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) MapFromStringToInt() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) PointerToString() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) SliceOfInts() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) String() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) Struct() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) UnsafePointer() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) NamedNumericType() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) NamedNonNumericType() {\n\tExpectTrue(false, \"TODO\")\n}\n\nfunc (t *ReturnTest) NamedChannelType() {\n\tExpectTrue(false, \"TODO\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (c) 2015 The heketi Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\npackage glusterfs\n\nimport (\n\t\"fmt\"\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/heketi\/heketi\/rest\"\n\t\"github.com\/heketi\/heketi\/utils\"\n\t\"net\/http\"\n\t\"time\"\n)\n\nconst (\n\tASYNC_ROUTE           = \"\/queue\"\n\tBOLTDB_BUCKET_CLUSTER = \"CLUSTER\"\n\tBOLTDB_BUCKET_NODE    = \"NODE\"\n\tBOLTDB_BUCKET_VOLUME  = \"VOLUME\"\n\tBOLTDB_BUCKET_DEVICE  = \"DEVICE\"\n\tBOLTDB_BUCKET_BRICK   = \"BRICK\"\n)\n\nvar (\n\tlogger     = utils.NewLogger(\"[heketi]\", utils.LEVEL_DEBUG)\n\tdbfilename = \"heketi.db\"\n)\n\ntype App struct {\n\tasyncManager *rest.AsyncHttpManager\n\tdb           *bolt.DB\n}\n\nfunc NewApp() *App {\n\tapp := &App{}\n\n\t\/\/ Setup asynchronous manager\n\tapp.asyncManager = rest.NewAsyncHttpManager(ASYNC_ROUTE)\n\n\t\/\/ Setup BoltDB database\n\tvar err error\n\tapp.db, err = bolt.Open(dbfilename, 0600, &bolt.Options{Timeout: 3 * time.Second})\n\tif err != nil {\n\t\tlogger.Error(\"Unable to open database\")\n\t\treturn nil\n\t}\n\n\terr = app.db.Update(func(tx *bolt.Tx) error {\n\t\t\/\/ Create Cluster Bucket\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(BOLTDB_BUCKET_CLUSTER))\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Unable to create cluster bucket in DB\")\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Create Node Bucket\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(BOLTDB_BUCKET_NODE))\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Unable to create cluster bucket in DB\")\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Create Volume Bucket\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(BOLTDB_BUCKET_VOLUME))\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Unable to create cluster bucket in DB\")\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Create Device Bucket\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(BOLTDB_BUCKET_DEVICE))\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Unable to create cluster bucket in DB\")\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Create Brick Bucket\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(BOLTDB_BUCKET_BRICK))\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Unable to create cluster bucket in DB\")\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\n\t})\n\tif err != nil {\n\t\tlogger.Err(err)\n\t\treturn nil\n\t}\n\n\tlogger.Info(\"GlusterFS Application Loaded\")\n\n\treturn app\n}\n\n\/\/ Register Routes\nfunc (a *App) SetRoutes(router *mux.Router) error {\n\n\troutes := rest.Routes{\n\n\t\t\/\/ HelloWorld\n\t\trest.Route{\"Hello\", \"GET\", \"\/hello\", a.Hello},\n\n\t\t\/\/ Asynchronous Manager\n\t\trest.Route{\"Async\", \"GET\", ASYNC_ROUTE + \"\/{id:[A-Fa-f0-9]+}\", a.asyncManager.HandlerStatus},\n\n\t\t\/\/ Cluster\n\t\trest.Route{\"ClusterCreate\", \"POST\", \"\/clusters\", a.ClusterCreate},\n\t\trest.Route{\"ClusterInfo\", \"GET\", \"\/clusters\/{id:[A-Fa-f0-9]+}\", a.NotImplemented},\n\t\trest.Route{\"ClusterList\", \"GET\", \"\/clusters\", a.ClusterList},\n\t\trest.Route{\"ClusterDelete\", \"DELETE\", \"\/clusters\/{id:[A-Fa-f0-9]+}\", a.NotImplemented},\n\n\t\t\/\/ Node\n\t\trest.Route{\"NodeAdd\", \"POST\", \"\/nodes\", a.NotImplemented},\n\t\trest.Route{\"NodeInfo\", \"GET\", \"\/nodes\/{id:[A-Fa-f0-9]+}\", a.NotImplemented},\n\t\trest.Route{\"NodeDelete\", \"DELETE\", \"\/nodes\/{id:[A-Fa-f0-9]+}\", a.NotImplemented},\n\n\t\t\/\/ Devices\n\t\trest.Route{\"DeviceAdd\", \"POST\", \"\/devices\", a.NotImplemented},\n\t\trest.Route{\"DeviceInfo\", \"GET\", \"\/devices\/{id:[A-Fa-f0-9]+}\", a.NotImplemented},\n\t\trest.Route{\"DeviceDelete\", \"DELETE\", \"\/devices\/{id:[A-Fa-f0-9]+}\", a.NotImplemented},\n\n\t\t\/\/ Volume\n\t\trest.Route{\"VolumeCreate\", \"POST\", \"\/volumes\", a.NotImplemented},\n\t\trest.Route{\"VolumeInfo\", \"GET\", \"\/volumes\/{id:[A-Fa-f0-9]+}\", a.NotImplemented},\n\t\trest.Route{\"VolumeExpand\", \"POST\", \"\/volumes\/{id:[A-Fa-f0-9]+}\/expand\", a.NotImplemented},\n\t\trest.Route{\"VolumeDelete\", \"DELETE\", \"\/volumes\/{id:[A-Fa-f0-9]+}\", a.NotImplemented},\n\t\trest.Route{\"VolumeList\", \"GET\", \"\/volumes\", a.NotImplemented},\n\t}\n\n\t\/\/ Register all routes from the App\n\tfor _, route := range routes {\n\n\t\t\/\/ Add routes from the table\n\t\trouter.\n\t\t\tMethods(route.Method).\n\t\t\tPath(route.Pattern).\n\t\t\tName(route.Name).\n\t\t\tHandler(route.HandlerFunc)\n\n\t}\n\n\treturn nil\n\n}\n\nfunc (a *App) Close() {\n\n\t\/\/ Close the DB\n\ta.db.Close()\n\tlogger.Info(\"Closed\")\n}\n\nfunc (a *App) Hello(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprint(w, \"HelloWorld from GlusterFS Application\")\n}\n\nfunc (a *App) NotImplemented(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, \"Function not yet supported\", http.StatusNotImplemented)\n}\n<commit_msg>Fix errors found by go vet<commit_after>\/\/\n\/\/ Copyright (c) 2015 The heketi Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\npackage glusterfs\n\nimport (\n\t\"fmt\"\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/heketi\/heketi\/rest\"\n\t\"github.com\/heketi\/heketi\/utils\"\n\t\"net\/http\"\n\t\"time\"\n)\n\nconst (\n\tASYNC_ROUTE           = \"\/queue\"\n\tBOLTDB_BUCKET_CLUSTER = \"CLUSTER\"\n\tBOLTDB_BUCKET_NODE    = \"NODE\"\n\tBOLTDB_BUCKET_VOLUME  = \"VOLUME\"\n\tBOLTDB_BUCKET_DEVICE  = \"DEVICE\"\n\tBOLTDB_BUCKET_BRICK   = \"BRICK\"\n)\n\nvar (\n\tlogger     = utils.NewLogger(\"[heketi]\", utils.LEVEL_DEBUG)\n\tdbfilename = \"heketi.db\"\n)\n\ntype App struct {\n\tasyncManager *rest.AsyncHttpManager\n\tdb           *bolt.DB\n}\n\nfunc NewApp() *App {\n\tapp := &App{}\n\n\t\/\/ Setup asynchronous manager\n\tapp.asyncManager = rest.NewAsyncHttpManager(ASYNC_ROUTE)\n\n\t\/\/ Setup BoltDB database\n\tvar err error\n\tapp.db, err = bolt.Open(dbfilename, 0600, &bolt.Options{Timeout: 3 * time.Second})\n\tif err != nil {\n\t\tlogger.Error(\"Unable to open database\")\n\t\treturn nil\n\t}\n\n\terr = app.db.Update(func(tx *bolt.Tx) error {\n\t\t\/\/ Create Cluster Bucket\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(BOLTDB_BUCKET_CLUSTER))\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Unable to create cluster bucket in DB\")\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Create Node Bucket\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(BOLTDB_BUCKET_NODE))\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Unable to create cluster bucket in DB\")\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Create Volume Bucket\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(BOLTDB_BUCKET_VOLUME))\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Unable to create cluster bucket in DB\")\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Create Device Bucket\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(BOLTDB_BUCKET_DEVICE))\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Unable to create cluster bucket in DB\")\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Create Brick Bucket\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(BOLTDB_BUCKET_BRICK))\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Unable to create cluster bucket in DB\")\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\n\t})\n\tif err != nil {\n\t\tlogger.Err(err)\n\t\treturn nil\n\t}\n\n\tlogger.Info(\"GlusterFS Application Loaded\")\n\n\treturn app\n}\n\n\/\/ Register Routes\nfunc (a *App) SetRoutes(router *mux.Router) error {\n\n\troutes := rest.Routes{\n\n\t\t\/\/ HelloWorld\n\t\trest.Route{\n\t\t\tName:        \"Hello\",\n\t\t\tMethod:      \"GET\",\n\t\t\tPattern:     \"\/hello\",\n\t\t\tHandlerFunc: a.Hello},\n\n\t\t\/\/ Asynchronous Manager\n\t\trest.Route{\n\t\t\tName:        \"Async\",\n\t\t\tMethod:      \"GET\",\n\t\t\tPattern:     ASYNC_ROUTE + \"\/{id:[A-Fa-f0-9]+}\",\n\t\t\tHandlerFunc: a.asyncManager.HandlerStatus},\n\n\t\t\/\/ Cluster\n\t\trest.Route{\n\t\t\tName:        \"ClusterCreate\",\n\t\t\tMethod:      \"POST\",\n\t\t\tPattern:     \"\/clusters\",\n\t\t\tHandlerFunc: a.ClusterCreate},\n\t\trest.Route{\n\t\t\tName:        \"ClusterInfo\",\n\t\t\tMethod:      \"GET\",\n\t\t\tPattern:     \"\/clusters\/{id:[A-Fa-f0-9]+}\",\n\t\t\tHandlerFunc: a.NotImplemented},\n\t\trest.Route{\n\t\t\tName:        \"ClusterList\",\n\t\t\tMethod:      \"GET\",\n\t\t\tPattern:     \"\/clusters\",\n\t\t\tHandlerFunc: a.ClusterList},\n\t\trest.Route{\n\t\t\tName:        \"ClusterDelete\",\n\t\t\tMethod:      \"DELETE\",\n\t\t\tPattern:     \"\/clusters\/{id:[A-Fa-f0-9]+}\",\n\t\t\tHandlerFunc: a.NotImplemented},\n\n\t\t\/\/ Node\n\t\trest.Route{\n\t\t\tName:        \"NodeAdd\",\n\t\t\tMethod:      \"POST\",\n\t\t\tPattern:     \"\/nodes\",\n\t\t\tHandlerFunc: a.NotImplemented},\n\t\trest.Route{\n\t\t\tName:        \"NodeInfo\",\n\t\t\tMethod:      \"GET\",\n\t\t\tPattern:     \"\/nodes\/{id:[A-Fa-f0-9]+}\",\n\t\t\tHandlerFunc: a.NotImplemented},\n\t\trest.Route{\n\t\t\tName:        \"NodeDelete\",\n\t\t\tMethod:      \"DELETE\",\n\t\t\tPattern:     \"\/nodes\/{id:[A-Fa-f0-9]+}\",\n\t\t\tHandlerFunc: a.NotImplemented},\n\n\t\t\/\/ Devices\n\t\trest.Route{\n\t\t\tName:        \"DeviceAdd\",\n\t\t\tMethod:      \"POST\",\n\t\t\tPattern:     \"\/devices\",\n\t\t\tHandlerFunc: a.NotImplemented},\n\t\trest.Route{\n\t\t\tName:        \"DeviceInfo\",\n\t\t\tMethod:      \"GET\",\n\t\t\tPattern:     \"\/devices\/{id:[A-Fa-f0-9]+}\",\n\t\t\tHandlerFunc: a.NotImplemented},\n\t\trest.Route{\n\t\t\tName:        \"DeviceDelete\",\n\t\t\tMethod:      \"DELETE\",\n\t\t\tPattern:     \"\/devices\/{id:[A-Fa-f0-9]+}\",\n\t\t\tHandlerFunc: a.NotImplemented},\n\n\t\t\/\/ Volume\n\t\trest.Route{\n\t\t\tName:        \"VolumeCreate\",\n\t\t\tMethod:      \"POST\",\n\t\t\tPattern:     \"\/volumes\",\n\t\t\tHandlerFunc: a.NotImplemented},\n\t\trest.Route{\n\t\t\tName:        \"VolumeInfo\",\n\t\t\tMethod:      \"GET\",\n\t\t\tPattern:     \"\/volumes\/{id:[A-Fa-f0-9]+}\",\n\t\t\tHandlerFunc: a.NotImplemented},\n\t\trest.Route{\n\t\t\tName:        \"VolumeExpand\",\n\t\t\tMethod:      \"POST\",\n\t\t\tPattern:     \"\/volumes\/{id:[A-Fa-f0-9]+}\/expand\",\n\t\t\tHandlerFunc: a.NotImplemented},\n\t\trest.Route{\n\t\t\tName:        \"VolumeDelete\",\n\t\t\tMethod:      \"DELETE\",\n\t\t\tPattern:     \"\/volumes\/{id:[A-Fa-f0-9]+}\",\n\t\t\tHandlerFunc: a.NotImplemented},\n\t\trest.Route{\n\t\t\tName:        \"VolumeList\",\n\t\t\tMethod:      \"GET\",\n\t\t\tPattern:     \"\/volumes\",\n\t\t\tHandlerFunc: a.NotImplemented},\n\t}\n\n\t\/\/ Register all routes from the App\n\tfor _, route := range routes {\n\n\t\t\/\/ Add routes from the table\n\t\trouter.\n\t\t\tMethods(route.Method).\n\t\t\tPath(route.Pattern).\n\t\t\tName(route.Name).\n\t\t\tHandler(route.HandlerFunc)\n\n\t}\n\n\treturn nil\n\n}\n\nfunc (a *App) Close() {\n\n\t\/\/ Close the DB\n\ta.db.Close()\n\tlogger.Info(\"Closed\")\n}\n\nfunc (a *App) Hello(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=UTF-8\")\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprint(w, \"HelloWorld from GlusterFS Application\")\n}\n\nfunc (a *App) NotImplemented(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, \"Function not yet supported\", http.StatusNotImplemented)\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"time\"\n\n\t\"github.com\/BurntSushi\/toml\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\ter \"github.com\/maliceio\/malice\/malice\/errors\"\n\t\"github.com\/maliceio\/malice\/malice\/maldirs\"\n\t\"github.com\/maliceio\/malice\/utils\"\n)\n\n\/\/ \"github.com\/pelletier\/go-toml\"\n\n\/\/ Configuration represents the malice runtime configuration.\ntype Configuration struct {\n\tTitle       string\n\tAuthor      authorInfo\n\tWeb         webConfig\n\tEmail       emailConfig\n\tDB          databaseConfig `toml:\"database\"`\n\tEnvironment envConfig\n\tDocker      dockerConfig\n\tLogger      loggerConfig\n\tProxy       proxyConfig\n}\n\ntype authorInfo struct {\n\tName         string\n\tOrganization string\n\tEmail        string\n}\n\ntype webConfig struct {\n\tURL      string\n\tAdminURL string `toml:\"admin_url\"`\n}\n\ntype databaseConfig struct {\n\tName    string\n\tServer  string\n\tPorts   []int\n\tTimeout int\n\tEnabled bool\n}\n\ntype emailConfig struct {\n\tHost     string\n\tport     int\n\tUsername string `toml:\"user\"`\n\tPassword string `toml:\"pass\"`\n}\n\ntype envConfig struct {\n\tRun string\n}\n\ntype dockerConfig struct {\n\tName     string `toml:\"machine-name\"`\n\tEndPoint string\n\tTimeout  time.Duration\n\tBinds    string\n\tLinks    string\n}\n\ntype loggerConfig struct {\n\tFileName   string\n\tMaxSize    int\n\tMaxAge     int\n\tMaxBackups int\n\tLocalTime  bool\n}\n\ntype proxyConfig struct {\n\tEnable bool\n\tHTTP   string\n\tHTTPS  string\n}\n\n\/\/ Conf represents the Malice runtime configuration\nvar Conf Configuration\n\n\/\/ Load config.toml into Conf var\n\/\/ Try to load config from\n\/\/ - git repo folder      : MALICE_ROOT\/config\/config.toml\n\/\/ - .malice folder       : $HOME\/.malice\/config.toml\n\/\/ - binary embedded file : bindata\nfunc Load() {\n\n\tvar configPath string\n\n\t\/\/ Check for config config in repo\n\tconfigPath = path.Join(\n\t\tutils.Getopt(\"GOPATH\", \"\"),\n\t\t\"src\/github.com\/maliceio\/malice\/config\/config.toml\",\n\t)\n\tif _, err := os.Stat(configPath); err == nil {\n\t\t_, err := toml.DecodeFile(\".\/config\/config.toml\", &Conf)\n\t\ter.CheckError(err)\n\t\tlog.Debug(\"Malice config loaded from: \", configPath)\n\t\treturn\n\t}\n\n\t\/\/ Check for config config in .malice folder\n\tconfigPath = path.Join(maldirs.GetBaseDir(), \".\/config.toml\")\n\tif _, err := os.Stat(configPath); err == nil {\n\t\t_, err := toml.DecodeFile(configPath, &Conf)\n\t\ter.CheckError(err)\n\t\tlog.Debug(\"Malice config loaded from: \", configPath)\n\t\treturn\n\t}\n\n\t\/\/ Read plugin config out of bindata\n\ttomlData, err := Asset(\"config\/config.toml\")\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\tif _, err = toml.Decode(string(tomlData), &Conf); err == nil {\n\t\t\/\/ Create .malice folder in the users home directory\n\t\ter.CheckError(os.MkdirAll(maldirs.GetBaseDir(), 0777))\n\t\t\/\/ Create the config config in the .malice folder\n\t\ter.CheckError(ioutil.WriteFile(configPath, tomlData, 0644))\n\t\tlog.Debug(\"Malice config loaded from config\/bindata.go\")\n\t}\n\ter.CheckError(err)\n\n\treturn\n}\n<commit_msg>fix config load<commit_after>package config\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"time\"\n\n\t\"github.com\/BurntSushi\/toml\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\ter \"github.com\/maliceio\/malice\/malice\/errors\"\n\t\"github.com\/maliceio\/malice\/malice\/maldirs\"\n\t\"github.com\/maliceio\/malice\/utils\"\n)\n\n\/\/ \"github.com\/pelletier\/go-toml\"\n\n\/\/ Configuration represents the malice runtime configuration.\ntype Configuration struct {\n\tTitle       string\n\tAuthor      authorInfo\n\tWeb         webConfig\n\tEmail       emailConfig\n\tDB          databaseConfig `toml:\"database\"`\n\tEnvironment envConfig\n\tDocker      dockerConfig\n\tLogger      loggerConfig\n\tProxy       proxyConfig\n}\n\ntype authorInfo struct {\n\tName         string\n\tOrganization string\n\tEmail        string\n}\n\ntype webConfig struct {\n\tURL      string\n\tAdminURL string `toml:\"admin_url\"`\n}\n\ntype databaseConfig struct {\n\tName    string\n\tServer  string\n\tPorts   []int\n\tTimeout int\n\tEnabled bool\n}\n\ntype emailConfig struct {\n\tHost     string\n\tport     int\n\tUsername string `toml:\"user\"`\n\tPassword string `toml:\"pass\"`\n}\n\ntype envConfig struct {\n\tRun string\n}\n\ntype dockerConfig struct {\n\tName     string `toml:\"machine-name\"`\n\tEndPoint string\n\tTimeout  time.Duration\n\tBinds    string\n\tLinks    string\n}\n\ntype loggerConfig struct {\n\tFileName   string\n\tMaxSize    int\n\tMaxAge     int\n\tMaxBackups int\n\tLocalTime  bool\n}\n\ntype proxyConfig struct {\n\tEnable bool\n\tHTTP   string\n\tHTTPS  string\n}\n\n\/\/ Conf represents the Malice runtime configuration\nvar Conf Configuration\n\n\/\/ Load config.toml into Conf var\n\/\/ Try to load config from\n\/\/ - git repo folder      : MALICE_ROOT\/config\/config.toml\n\/\/ - .malice folder       : $HOME\/.malice\/config.toml\n\/\/ - binary embedded file : bindata\nfunc Load() {\n\n\tvar configPath string\n\n\t\/\/ Check for config config in repo\n\tconfigPath = path.Join(\n\t\tutils.Getopt(\"GOPATH\", \"\"),\n\t\t\"src\/github.com\/maliceio\/malice\/config\/config.toml\",\n\t)\n\tif _, err := os.Stat(configPath); err == nil {\n\t\t_, err := toml.DecodeFile(configPath, &Conf)\n\t\ter.CheckError(err)\n\t\tlog.Debug(\"Malice config loaded from: \", configPath)\n\t\treturn\n\t}\n\n\t\/\/ Check for config config in .malice folder\n\tconfigPath = path.Join(maldirs.GetBaseDir(), \".\/config.toml\")\n\tif _, err := os.Stat(configPath); err == nil {\n\t\t_, err := toml.DecodeFile(configPath, &Conf)\n\t\ter.CheckError(err)\n\t\tlog.Debug(\"Malice config loaded from: \", configPath)\n\t\treturn\n\t}\n\n\t\/\/ Read plugin config out of bindata\n\ttomlData, err := Asset(\"config\/config.toml\")\n\tif err != nil {\n\t\tlog.Error(err)\n\t}\n\tif _, err = toml.Decode(string(tomlData), &Conf); err == nil {\n\t\t\/\/ Create .malice folder in the users home directory\n\t\ter.CheckError(os.MkdirAll(maldirs.GetBaseDir(), 0777))\n\t\t\/\/ Create the config config in the .malice folder\n\t\ter.CheckError(ioutil.WriteFile(configPath, tomlData, 0644))\n\t\tlog.Debug(\"Malice config loaded from config\/bindata.go\")\n\t}\n\ter.CheckError(err)\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"testing\"\n)\n\nvar testRules = []Rule{\n\tRule{\"\/tmp\/foo\", \"\/usr\/local\/bar\/foobar\", \"*.txt\", false, false},\n\tRule{\"\/tmp\/foo\", \"\/usr\/local\/foo\/foobar\", \"*.zip\", true, true},\n\tRule{\"\/tmp\/bar\", \"\/usr\/local\/bar\/barfoo\", \"*.jpg\", false, false},\n}\n\nfunc TestParseConfig(t *testing.T) {\n\trules, err := ParseConfig(fixtures + \"\/example_config.json\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfor _, testRule := range testRules {\n\t\tfound := false\n\n\t\tfor _, rule := range rules {\n\t\t\tfound = found || (testRule.Path == rule.Path &&\n\t\t\ttestRule.Run == rule.Run &&\n\t\t\ttestRule.Pattern == rule.Pattern &&\n\t\t\ttestRule.ChangePwd == rule.ChangePwd)\n\t\t}\n\n\t\tif !found {\n\t\t\tt.Errorf(\"Rule not found: %+v\", testRule)\n\t\t}\n\t}\n}\n<commit_msg>go fmt<commit_after>package main\n\nimport (\n\t\"testing\"\n)\n\nvar testRules = []Rule{\n\tRule{\"\/tmp\/foo\", \"\/usr\/local\/bar\/foobar\", \"*.txt\", false, false},\n\tRule{\"\/tmp\/foo\", \"\/usr\/local\/foo\/foobar\", \"*.zip\", true, true},\n\tRule{\"\/tmp\/bar\", \"\/usr\/local\/bar\/barfoo\", \"*.jpg\", false, false},\n}\n\nfunc TestParseConfig(t *testing.T) {\n\trules, err := ParseConfig(fixtures + \"\/example_config.json\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tfor _, testRule := range testRules {\n\t\tfound := false\n\n\t\tfor _, rule := range rules {\n\t\t\tfound = found || (testRule.Path == rule.Path &&\n\t\t\t\ttestRule.Run == rule.Run &&\n\t\t\t\ttestRule.Pattern == rule.Pattern &&\n\t\t\t\ttestRule.ChangePwd == rule.ChangePwd)\n\t\t}\n\n\t\tif !found {\n\t\t\tt.Errorf(\"Rule not found: %+v\", testRule)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package atlas\n\nimport (\n\t\"fmt\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n)\n\nfunc TestCheckName(t *testing.T) {\n\tos.Setenv(\"HOME\", \"\/home\/foo\")\n\n\t\/\/ Check tag usage\n\tfile := \"mytag\"\n\tres := checkName(file)\n\trealPath := path.Join(os.Getenv(\"HOME\"), fmt.Sprintf(\".%s\", file), \"config.toml\")\n\tassert.EqualValues(t, realPath, res, \"should be equal\")\n\n\t\/\/ Check fullname usage\n\tfile = \"\/nonexistent\/foobar.toml\"\n\tres = checkName(file)\n\tassert.EqualValues(t, realPath, res, \"should be equal\")\n\n\t\/\/ Check bad usage\n\tfile = \"\/toto.yaml\"\n\tres = checkName(file)\n\tassert.EqualValues(t, \"\", res, \"should be equal\")\n\n\t\/\/ Check plain file\n\tfile = \"foo.toml\"\n\tres = checkName(file)\n\tassert.EqualValues(t, file, res, \"should be equal\")\n}\n\nfunc TestLoadConfig(t *testing.T) {\n\tfile := \"newconfig.toml\"\n\tconf, err := LoadConfig(file)\n\tassert.NoError(t, err, \"no file is no error\")\n\n\tfile = \"config.toml\"\n\tconf, err = LoadConfig(file)\n\tassert.NoError(t, err, \"no error\")\n\n\tdefaultProbe := 666\n\tassert.EqualValues(t, defaultProbe, conf.DefaultProbe, \"should be equal\")\n\n\tkey := \"<INSERT-API-KEY>\"\n\tassert.EqualValues(t, key, conf.APIKey, \"should be equal\")\n\n\tpoolSize := 10\n\tassert.EqualValues(t, poolSize, conf.PoolSize, \"should be equal\")\n}\n<commit_msg>Fix test with the right variable.<commit_after>package atlas\n\nimport (\n\t\"fmt\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n)\n\nfunc TestCheckName(t *testing.T) {\n\tos.Setenv(\"HOME\", \"\/home\/foo\")\n\n\t\/\/ Check tag usage\n\tfile := \"mytag\"\n\tres := checkName(file)\n\trealPath := path.Join(os.Getenv(\"HOME\"), fmt.Sprintf(\".%s\", file), \"config.toml\")\n\tassert.EqualValues(t, realPath, res, \"should be equal\")\n\n\t\/\/ Check fullname usage\n\tfile = \"\/nonexistent\/foobar.toml\"\n\tres = checkName(file)\n\tassert.EqualValues(t, file, res, \"should be equal\")\n\n\t\/\/ Check bad usage\n\tfile = \"\/toto.yaml\"\n\tres = checkName(file)\n\tassert.EqualValues(t, \"\", res, \"should be equal\")\n\n\t\/\/ Check plain file\n\tfile = \"foo.toml\"\n\tres = checkName(file)\n\tassert.EqualValues(t, file, res, \"should be equal\")\n}\n\nfunc TestLoadConfig(t *testing.T) {\n\tfile := \"newconfig.toml\"\n\tconf, err := LoadConfig(file)\n\tassert.NoError(t, err, \"no file is no error\")\n\n\tfile = \"config.toml\"\n\tconf, err = LoadConfig(file)\n\tassert.NoError(t, err, \"no error\")\n\n\tdefaultProbe := 666\n\tassert.EqualValues(t, defaultProbe, conf.DefaultProbe, \"should be equal\")\n\n\tkey := \"<INSERT-API-KEY>\"\n\tassert.EqualValues(t, key, conf.APIKey, \"should be equal\")\n\n\tpoolSize := 10\n\tassert.EqualValues(t, poolSize, conf.PoolSize, \"should be equal\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package dotweb\n<commit_msg>remove consts_test.go consts_test.go is not neccesary<commit_after><|endoftext|>"}
{"text":"<commit_before>package infrastructure\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestGraphiteDateFormat(t *testing.T) {\n\tmytime := time.Date(2009, time.November, 10, 9, 0, 0, 0, time.Local)\n\tf := graphiteDateFormat(mytime)\n\tif f != \"09:00_20091110\" {\n\t\tt.Error(f)\n\t}\n}\n\nfunc TestIntegrationMulti(t *testing.T) {\n\tt.Parallel()\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, `[{\"target\": \"machine.jvm.gc.PS-MarkSweep.runs\", \"datapoints\": [[185, 1409763000], [741, 1409790300], [null, 1409790600]]},{\"target\": \"machine2.jvm.gc.PS-MarkSweep.runs\", \"datapoints\": [[185, 1409763000], [741, 1409790300]]}]`)\n\t}))\n\tdefer ts.Close()\n\n\tc, err := New(ts.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tpointlist, err := c.QueryMultiSince([]string{\"machine*.jvm.gc.PS-MarkSweep.runs\"}, time.Second*time.Duration(200))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tpoints := pointlist.asMap()\n\n\tif len(points) != 2 {\n\t\tt.Fatal(\"Missing points:\", len(points))\n\t}\n\tif ints, _ := points[\"machine.jvm.gc.PS-MarkSweep.runs\"].AsInts(); len(ints) != 3 {\n\t\tt.Error(\"Expected first points target to have length 3:\", len(ints))\n\t}\n\tif ints, _ := points[\"machine2.jvm.gc.PS-MarkSweep.runs\"].AsInts(); len(ints) != 2 {\n\t\tt.Error(\"Expected first points target to have length 2:\", len(ints))\n\t}\n}\n\nfunc TestIntegration(t *testing.T) {\n\tt.Parallel()\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, `[{\"target\": \"machine.jvm.gc.PS-MarkSweep.runs\", \"datapoints\": [[185, 1409763000], [741, 1409790300], [null, 1409790600], [756, 1409790900]]}]`)\n\t}))\n\tdefer ts.Close()\n\n\tc, err := New(ts.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tpoints, err := c.QueryIntsSince(\"machine.jvm.gc.PS-MarkSweep.runs\", time.Second*time.Duration(200))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(points) != 4 {\n\t\tt.Fatal(\"Missing points:\", len(points))\n\t}\n}\n\nfunc TestParsingFloatGraphiteResult(t *testing.T) {\n\tt.Parallel()\n\n\ts := `[{\"target\": \"machine.jvm.gc.PS-MarkSweep.runs\", \"datapoints\": [[185.0, 1409763000], [741.0, 1409790300], [null, 1409790600], [756.0, 1409790900]]}]`\n\n\tresponse, err := parseGraphiteResponse([]byte(s))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tidps, err := response[0].AsInts()\n\tif err == nil {\n\t\tt.Error(\"Expected an error.\")\n\t}\n\tif idps != nil {\n\t\tt.Error(\"Expected nil result.\")\n\t}\n\tif len(response) != 1 {\n\t\tt.Error(\"Unexpected list length:\", len(response))\n\t}\n\n\tfpts, err := response[0].AsFloats()\n\tif err != nil {\n\t\tt.Error(\"Unexpected error.\")\n\t}\n\tif fpts == nil {\n\t\tt.Fatal(\"Unexpected nil result.\")\n\t}\n\n\tif len(fpts) != 4 {\n\t\tt.Fatal(\"Missing points:\", len(fpts))\n\t}\n\ttimes := []int64{\n\t\t1409763000,\n\t\t1409790300,\n\t\t1409790600,\n\t\t1409790900,\n\t}\n\tvalues := []*float64{\n\t\tmakeFloat64Pointer(185.0),\n\t\tmakeFloat64Pointer(741.0),\n\t\tnil,\n\t\tmakeFloat64Pointer(756.0),\n\t}\n\tfor i, p := range fpts {\n\t\tif p.Time.Unix() != times[i] {\n\t\t\tt.Error(\"Incorrect UNIX timestamp. Expected:\", times[i], \"Got:\", p.Time.Unix())\n\t\t}\n\t\tif (p.Value == nil && values[i] != nil) || (p.Value != nil && values[i] == nil) {\n\t\t\tt.Error(\"nil value mismatch for element:\", i)\n\t\t} else if p.Value != nil && math.Abs(float64(*p.Value-*values[i])) > 0.0001 {\n\t\t\tt.Error(\"value mismatch. Got:\", *p.Value, \"Expected:\", *values[i])\n\t\t}\n\t}\n}\n\nfunc TestParsingIntGraphiteResult(t *testing.T) {\n\tt.Parallel()\n\n\ts := `[{\"target\": \"machine.jvm.gc.PS-MarkSweep.runs\", \"datapoints\": [[185, 1409763000], [741, 1409790300], [null, 1409790600], [756, 1409790900]]}]`\n\n\tresponse, err := parseGraphiteResponse([]byte(s))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(response) != 1 {\n\t\tt.Fatal(\"Unexpected list length:\", len(response))\n\t}\n\n\t\/\/ Introspection testing. Should be avoided if possible.\n\tif response[0].err != nil {\n\t\tt.Error(\"Response should not have had any errors.\")\n\t}\n\tif l := len(response[0].points); l != 4 {\n\t\tt.Fatal(\"Not enough points:\", l)\n\t}\n\n\t\/\/ Floats are tested in separate test. Just making sure we aren't getting any\n\t\/\/ suspicious errors.\n\tidps, err := response[0].AsFloats()\n\tif err != nil {\n\t\tt.Error(\"Unexpected error.\")\n\t}\n\tif idps == nil {\n\t\tt.Error(\"Unexpected nil result.\")\n\t}\n\n\tfpts, err := response[0].AsInts()\n\tif err != nil {\n\t\tt.Error(\"Unexpected error.\")\n\t}\n\tif fpts == nil {\n\t\tt.Fatal(\"Unexpected nil result.\")\n\t}\n\n\tif len(fpts) != 4 {\n\t\tt.Fatal(\"Missing points:\", len(fpts))\n\t}\n\ttimes := []int64{\n\t\t1409763000,\n\t\t1409790300,\n\t\t1409790600,\n\t\t1409790900,\n\t}\n\tvalues := []*int64{\n\t\tmakeInt64Pointer(185),\n\t\tmakeInt64Pointer(741),\n\t\tnil,\n\t\tmakeInt64Pointer(756),\n\t}\n\tfor i, p := range fpts {\n\t\tif p.Time.Unix() != times[i] {\n\t\t\tt.Error(\"Incorrect UNIX timestamp. Expected:\", times[i], \"Got:\", p.Time.Unix())\n\t\t}\n\t\tif (p.Value == nil && values[i] != nil) || (p.Value != nil && values[i] == nil) {\n\t\t\tt.Error(\"nil value mismatch for element:\", i)\n\t\t} else if p.Value != nil && *p.Value != *values[i] {\n\t\t\tt.Error(\"value mismatch. Got:\", *p.Value, \"Expected:\", *values[i])\n\t\t}\n\t}\n}\n\nfunc makeFloat64Pointer(v float64) *float64 {\n\tr := new(float64)\n\t*r = v\n\treturn r\n}\n\nfunc makeInt64Pointer(v int64) *int64 {\n\tr := new(int64)\n\t*r = v\n\treturn r\n}\n\nfunc TestQueryRealGraphite(t *testing.T) {\n\tgraphiteUrl := os.Getenv(\"GRAPHITE_URL\")\n\tif graphiteUrl == \"\" {\n\t\tt.Skip()\n\t}\n\tc, err := New(graphiteUrl)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tday := 24 * time.Hour\n\taWeek := day * 7\n\n\t\/\/ Expect this metric to exist on all Graphite instances. Using glob to\n\t\/\/ ignore speicific Graphite agent name.\n\t_, err = c.QueryFloatsSince(\"sumSeries(carbon.agents.*.avgUpdateTime)\", aWeek)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestGraphiteDurationString(t *testing.T) {\n\taWeek := 7 * 24 * time.Hour\n\ts := graphiteSinceString(aWeek)\n\tif s != \"-10080minutes\" {\n\t\tt.Error(s)\n\t}\n}\n\nfunc TestFindRealGraphite(t *testing.T) {\n\tgraphiteUrl := os.Getenv(\"GRAPHITE_URL\")\n\tif graphiteUrl == \"\" {\n\t\tt.Skip()\n\t}\n\tc, err := New(graphiteUrl)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tres, err := c.Find(\"carbon.*\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(res) <= 0 {\n\t\tt.Error(\"Expected more results.\")\n\t}\n}\n<commit_msg>Fix(test)<commit_after>package infrastructure\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestGraphiteDateFormat(t *testing.T) {\n\tmytime := time.Date(2009, time.November, 10, 9, 0, 0, 0, time.Local)\n\tf := graphiteDateFormat(mytime)\n\tif f != \"09:00_20091110\" {\n\t\tt.Error(f)\n\t}\n}\n\nfunc TestIntegrationMulti(t *testing.T) {\n\tt.Parallel()\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, `[{\"target\": \"machine.jvm.gc.PS-MarkSweep.runs\", \"datapoints\": [[185, 1409763000], [741, 1409790300], [null, 1409790600]]},{\"target\": \"machine2.jvm.gc.PS-MarkSweep.runs\", \"datapoints\": [[185, 1409763000], [741, 1409790300]]}]`)\n\t}))\n\tdefer ts.Close()\n\n\tc, err := New(ts.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tpointlist, err := c.QueryMultiSince([]string{\"machine*.jvm.gc.PS-MarkSweep.runs\"}, time.Second*time.Duration(200))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tpoints := pointlist.asMap()\n\n\tif len(points) != 2 {\n\t\tt.Fatal(\"Missing points:\", len(points))\n\t}\n\tif ints, _ := points[\"machine.jvm.gc.PS-MarkSweep.runs\"].AsInts(); len(ints) != 3 {\n\t\tt.Error(\"Expected first points target to have length 3:\", len(ints))\n\t}\n\tif ints, _ := points[\"machine2.jvm.gc.PS-MarkSweep.runs\"].AsInts(); len(ints) != 2 {\n\t\tt.Error(\"Expected first points target to have length 2:\", len(ints))\n\t}\n}\n\nfunc TestIntegration(t *testing.T) {\n\tt.Parallel()\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintln(w, `[{\"target\": \"machine.jvm.gc.PS-MarkSweep.runs\", \"datapoints\": [[185, 1409763000], [741, 1409790300], [null, 1409790600], [756, 1409790900]]}]`)\n\t}))\n\tdefer ts.Close()\n\n\tc, err := New(ts.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tpoints, err := c.QueryIntsSince(\"machine.jvm.gc.PS-MarkSweep.runs\", time.Second*time.Duration(200))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(points) != 4 {\n\t\tt.Fatal(\"Missing points:\", len(points))\n\t}\n}\n\nfunc TestParsingFloatGraphiteResult(t *testing.T) {\n\tt.Parallel()\n\n\ts := `[{\"target\": \"machine.jvm.gc.PS-MarkSweep.runs\", \"datapoints\": [[185.0, 1409763000], [741.0, 1409790300], [null, 1409790600], [756.0, 1409790900]]}]`\n\n\tresponse, err := parseGraphiteResponse([]byte(s))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tidps, err := response[0].AsInts()\n\tif err != nil {\n\t\tt.Error(\"Unxpected error.\")\n\t}\n\tif idps == nil {\n\t\tt.Error(\"Unxpected nil result.\")\n\t}\n\tif len(response) != 1 {\n\t\tt.Error(\"Unexpected list length:\", len(response))\n\t}\n\n\tfpts, err := response[0].AsFloats()\n\tif err != nil {\n\t\tt.Error(\"Unexpected error.\")\n\t}\n\tif fpts == nil {\n\t\tt.Fatal(\"Unexpected nil result.\")\n\t}\n\n\tif len(fpts) != 4 {\n\t\tt.Fatal(\"Missing points:\", len(fpts))\n\t}\n\ttimes := []int64{\n\t\t1409763000,\n\t\t1409790300,\n\t\t1409790600,\n\t\t1409790900,\n\t}\n\tvalues := []*float64{\n\t\tmakeFloat64Pointer(185.0),\n\t\tmakeFloat64Pointer(741.0),\n\t\tnil,\n\t\tmakeFloat64Pointer(756.0),\n\t}\n\tfor i, p := range fpts {\n\t\tif p.Time.Unix() != times[i] {\n\t\t\tt.Error(\"Incorrect UNIX timestamp. Expected:\", times[i], \"Got:\", p.Time.Unix())\n\t\t}\n\t\tif (p.Value == nil && values[i] != nil) || (p.Value != nil && values[i] == nil) {\n\t\t\tt.Error(\"nil value mismatch for element:\", i)\n\t\t} else if p.Value != nil && math.Abs(float64(*p.Value-*values[i])) > 0.0001 {\n\t\t\tt.Error(\"value mismatch. Got:\", *p.Value, \"Expected:\", *values[i])\n\t\t}\n\t}\n}\n\nfunc TestParsingIntGraphiteResult(t *testing.T) {\n\tt.Parallel()\n\n\ts := `[{\"target\": \"machine.jvm.gc.PS-MarkSweep.runs\", \"datapoints\": [[185, 1409763000], [741, 1409790300], [null, 1409790600], [756, 1409790900]]}]`\n\n\tresponse, err := parseGraphiteResponse([]byte(s))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif len(response) != 1 {\n\t\tt.Fatal(\"Unexpected list length:\", len(response))\n\t}\n\n\t\/\/ Introspection testing. Should be avoided if possible.\n\tif response[0].err != nil {\n\t\tt.Error(\"Response should not have had any errors.\")\n\t}\n\tif l := len(response[0].points); l != 4 {\n\t\tt.Fatal(\"Not enough points:\", l)\n\t}\n\n\t\/\/ Floats are tested in separate test. Just making sure we aren't getting any\n\t\/\/ suspicious errors.\n\tidps, err := response[0].AsFloats()\n\tif err != nil {\n\t\tt.Error(\"Unexpected error.\")\n\t}\n\tif idps == nil {\n\t\tt.Error(\"Unexpected nil result.\")\n\t}\n\n\tfpts, err := response[0].AsInts()\n\tif err != nil {\n\t\tt.Error(\"Unexpected error.\")\n\t}\n\tif fpts == nil {\n\t\tt.Fatal(\"Unexpected nil result.\")\n\t}\n\n\tif len(fpts) != 4 {\n\t\tt.Fatal(\"Missing points:\", len(fpts))\n\t}\n\ttimes := []int64{\n\t\t1409763000,\n\t\t1409790300,\n\t\t1409790600,\n\t\t1409790900,\n\t}\n\tvalues := []*int64{\n\t\tmakeInt64Pointer(185),\n\t\tmakeInt64Pointer(741),\n\t\tnil,\n\t\tmakeInt64Pointer(756),\n\t}\n\tfor i, p := range fpts {\n\t\tif p.Time.Unix() != times[i] {\n\t\t\tt.Error(\"Incorrect UNIX timestamp. Expected:\", times[i], \"Got:\", p.Time.Unix())\n\t\t}\n\t\tif (p.Value == nil && values[i] != nil) || (p.Value != nil && values[i] == nil) {\n\t\t\tt.Error(\"nil value mismatch for element:\", i)\n\t\t} else if p.Value != nil && *p.Value != *values[i] {\n\t\t\tt.Error(\"value mismatch. Got:\", *p.Value, \"Expected:\", *values[i])\n\t\t}\n\t}\n}\n\nfunc makeFloat64Pointer(v float64) *float64 {\n\tr := new(float64)\n\t*r = v\n\treturn r\n}\n\nfunc makeInt64Pointer(v int64) *int64 {\n\tr := new(int64)\n\t*r = v\n\treturn r\n}\n\nfunc TestQueryRealGraphite(t *testing.T) {\n\tgraphiteUrl := os.Getenv(\"GRAPHITE_URL\")\n\tif graphiteUrl == \"\" {\n\t\tt.Skip()\n\t}\n\tc, err := New(graphiteUrl)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tday := 24 * time.Hour\n\taWeek := day * 7\n\n\t\/\/ Expect this metric to exist on all Graphite instances. Using glob to\n\t\/\/ ignore speicific Graphite agent name.\n\t_, err = c.QueryFloatsSince(\"sumSeries(carbon.agents.*.avgUpdateTime)\", aWeek)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestGraphiteDurationString(t *testing.T) {\n\taWeek := 7 * 24 * time.Hour\n\ts := graphiteSinceString(aWeek)\n\tif s != \"-10080minutes\" {\n\t\tt.Error(s)\n\t}\n}\n\nfunc TestFindRealGraphite(t *testing.T) {\n\tgraphiteUrl := os.Getenv(\"GRAPHITE_URL\")\n\tif graphiteUrl == \"\" {\n\t\tt.Skip()\n\t}\n\tc, err := New(graphiteUrl)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tres, err := c.Find(\"carbon.*\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(res) <= 0 {\n\t\tt.Error(\"Expected more results.\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/   Copyright 2018 MSolution.IO\n\/\/\n\/\/   Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/   you may not use this file except in compliance with the License.\n\/\/   You may obtain a copy of the License at\n\/\/\n\/\/       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/   Unless required by applicable law or agreed to in writing, software\n\/\/   distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/   See the License for the specific language governing permissions and\n\/\/   limitations under the License.\n\npackage shared_account\n\nimport (\n\t\"database\/sql\"\n\t\"net\/http\"\n\t\"errors\"\n\n\t\"github.com\/trackit\/trackit-server\/routes\"\n\t\"github.com\/trackit\/trackit-server\/users\"\n\t\"github.com\/trackit\/trackit-server\/db\"\n)\n\n\/\/ inviteUserRequest is the expected request body for the invite user route handler.\ntype InviteUserRequest struct {\n\tEmail           string `json:\"email\" req:\"nonzero\"`\n\tAccountId       int    `json:\"accountId\"`\n\tPermissionLevel int    `json:\"permissionLevel\"`\n}\n\ntype updateUsersSharedAccountRequest struct {\n\tShareId         int `json:\"shareId\" req:\"nonzero\"`\n\tPermissionLevel int `json:\"permissionLevel\"`\n}\n\ntype deleteUsersSharedAccountRequest struct {\n\tShareId         int `json:\"shareId\" req:\"nonzero\"`\n}\n\nfunc init() {\n\troutes.MethodMuxer{\n\t\thttp.MethodGet: routes.H(listSharedUsers).With(\n\t\t\tdb.RequestTransaction{db.Db},\n\t\t\tusers.RequireAuthenticatedUser{users.ViewerAsParent},\n\t\t\troutes.Documentation{\n\t\t\t\tSummary:     \"List shared users\",\n\t\t\t\tDescription: \"Return a list of user who have an access to an AWS account on Trackit\",\n\t\t\t},\n\t\t\troutes.QueryArgs{\n\t\t\t\troutes.AwsAccountIdQueryArg,\n\t\t\t},\n\t\t),\n\t\thttp.MethodPost: routes.H(inviteUser).With(\n\t\t\tdb.RequestTransaction{db.Db},\n\t\t\tusers.RequireAuthenticatedUser{users.ViewerAsParent},\n\t\t\troutes.RequestContentType{\"application\/json\"},\n\t\t\troutes.RequestBody{InviteUserRequest{\"example@example.com\", 1234, 0}},\n\t\t\troutes.Documentation{\n\t\t\t\tSummary:     \"Creates an invite\",\n\t\t\t\tDescription: \"Creates an invite for account team sharing\",\n\t\t\t},\n\t\t),\n\t\thttp.MethodPatch: routes.H(updateSharedUsers).With(\n\t\t\tdb.RequestTransaction{db.Db},\n\t\t\tusers.RequireAuthenticatedUser{users.ViewerAsParent},\n\t\t\troutes.RequestContentType{\"application\/json\"},\n\t\t\troutes.RequestBody{updateUsersSharedAccountRequest{1, 2}},\n\t\t\troutes.Documentation{\n\t\t\t\tSummary:     \"Update shared users\",\n\t\t\t\tDescription: \"Update shared users associated with a specific AWS account\",\n\t\t\t},\n\t\t),\n\t\thttp.MethodDelete: routes.H(deleteSharedUsers).With(\n\t\t\tdb.RequestTransaction{db.Db},\n\t\t\tusers.RequireAuthenticatedUser{users.ViewerAsParent},\n\t\t\troutes.RequestBody{deleteUsersSharedAccountRequest{1}},\n\t\t\troutes.Documentation{\n\t\t\t\tSummary:     \"Delete shared users\",\n\t\t\t\tDescription: \"Delete shared users associated with a specific AWS account\",\n\t\t\t},\n\t\t),\n\t}.H().With(\n\t\tdb.RequestTransaction{db.Db},\n\t\troutes.Documentation{\n\t\t\tSummary: \"interact with shared accounts\",\n\t\t},\n\t).Register(\"\/user\/share\")\n}\n\n\/\/ inviteUser handles users invite for team sharing.\nfunc inviteUser(request *http.Request, a routes.Arguments) (int, interface{}) {\n\tvar body InviteUserRequest\n\troutes.MustRequestBody(a, &body)\n\ttx := a[db.Transaction].(*sql.Tx)\n\tuser := a[users.AuthenticatedUser].(users.User)\n\treturn InviteUserWithValidBody(request, body, tx, user)\n}\n\n\/\/ listSharedUsers handles listing of users who have an access to an AWS account.\nfunc listSharedUsers(request *http.Request, a routes.Arguments) (int, interface{}) {\n\tbody := a[routes.AwsAccountIdQueryArg].(int)\n\ttx := a[db.Transaction].(*sql.Tx)\n\tuser := a[users.AuthenticatedUser].(users.User)\n\treturn listSharedUserAccessWithValidBody(request, body, tx, user)\n}\n\n\/\/ updateSharedUsers handles updates of user permission level for team sharing.\nfunc updateSharedUsers(request *http.Request, a routes.Arguments) (int, interface{}) {\n\tvar body updateUsersSharedAccountRequest\n\troutes.MustRequestBody(a, &body)\n\ttx := a[db.Transaction].(*sql.Tx)\n\tuser := a[users.AuthenticatedUser].(users.User)\n\treturn updateSharedUserAccessWithValidBody(request, body, tx, user)\n}\n\n\/\/ deleteSharedUsers handles user access deletion for team sharing\nfunc deleteSharedUsers(request *http.Request, a routes.Arguments) (int, interface{}) {\n\tvar body deleteUsersSharedAccountRequest\n\troutes.MustRequestBody(a, &body)\n\ttx := a[db.Transaction].(*sql.Tx)\n\tuser := a[users.AuthenticatedUser].(users.User)\n\treturn deleteSharedUserAccessWithValidBody(request, body, tx, user)\n}\n\n\/\/ listSharedUserAccessWithValidBody tries to list users who have an access to an AWS account\nfunc listSharedUserAccessWithValidBody(request *http.Request, body int, tx *sql.Tx, user users.User) (int, interface{}) {\n\tsecurity, err := safetyCheckByAccountId(request.Context(), tx, body, user)\n\tif !security || err != nil {\n\t\treturn 403, err\n\t}\n\tres, err := GetSharingList(request.Context(), db.Db, body)\n\tif err != nil {\n\t\treturn 403, errors.New(\"Error retrieving shared users list\")\n\t} else {\n\t\treturn 200, res\n\t}\n}\n\n\/\/ updateSharedUserAccessWithValidBody tries to update users permission level for team sharing\nfunc updateSharedUserAccessWithValidBody(request *http.Request, body updateUsersSharedAccountRequest, tx *sql.Tx, user users.User) (int, interface{}) {\n\tsecurity, err := safetyCheckByShareId(request.Context(), tx, body.ShareId, user)\n\tif !security || err != nil {\n\t\treturn 403, err\n\t}\n\tres, err := UpdateSharedUser(request.Context(), db.Db, body.ShareId, body.PermissionLevel)\n\tif err != nil {\n\t\treturn 403, errors.New(\"Error updating shared user list\")\n\t}\n\treturn 200, res\n}\n\n\/\/ deleteSharedUserAccessWithValidBody tries to delete users from accessing specific shared aws account\nfunc deleteSharedUserAccessWithValidBody(request *http.Request, body deleteUsersSharedAccountRequest, tx *sql.Tx, user users.User) (int, interface{}) {\n\tsecurity, err := safetyCheckByShareId(request.Context(), tx, body.ShareId, user)\n\tif !security || err != nil {\n\t\treturn 403, err\n\t}\n\terr = DeleteSharedUser(request.Context(), db.Db, body.ShareId)\n\tif err != nil {\n\t\treturn 403, errors.New(\"Error deleting shared user\")\n\t}\n\treturn 200, nil\n}\n<commit_msg>Correcting variable name<commit_after>\/\/   Copyright 2018 MSolution.IO\n\/\/\n\/\/   Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/   you may not use this file except in compliance with the License.\n\/\/   You may obtain a copy of the License at\n\/\/\n\/\/       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/   Unless required by applicable law or agreed to in writing, software\n\/\/   distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/   See the License for the specific language governing permissions and\n\/\/   limitations under the License.\n\npackage shared_account\n\nimport (\n\t\"database\/sql\"\n\t\"net\/http\"\n\t\"errors\"\n\n\t\"github.com\/trackit\/trackit-server\/routes\"\n\t\"github.com\/trackit\/trackit-server\/users\"\n\t\"github.com\/trackit\/trackit-server\/db\"\n)\n\n\/\/ inviteUserRequest is the expected request body for the invite user route handler.\ntype InviteUserRequest struct {\n\tEmail           string `json:\"email\" req:\"nonzero\"`\n\tAccountId       int    `json:\"accountId\"`\n\tPermissionLevel int    `json:\"permissionLevel\"`\n}\n\ntype updateUsersSharedAccountRequest struct {\n\tShareId         int `json:\"shareId\" req:\"nonzero\"`\n\tPermissionLevel int `json:\"permissionLevel\"`\n}\n\ntype deleteUsersSharedAccountRequest struct {\n\tShareId         int `json:\"shareId\" req:\"nonzero\"`\n}\n\nfunc init() {\n\troutes.MethodMuxer{\n\t\thttp.MethodGet: routes.H(listSharedUsers).With(\n\t\t\tdb.RequestTransaction{db.Db},\n\t\t\tusers.RequireAuthenticatedUser{users.ViewerAsParent},\n\t\t\troutes.Documentation{\n\t\t\t\tSummary:     \"List shared users\",\n\t\t\t\tDescription: \"Return a list of user who have an access to an AWS account on Trackit\",\n\t\t\t},\n\t\t\troutes.QueryArgs{\n\t\t\t\troutes.AwsAccountIdQueryArg,\n\t\t\t},\n\t\t),\n\t\thttp.MethodPost: routes.H(inviteUser).With(\n\t\t\tdb.RequestTransaction{db.Db},\n\t\t\tusers.RequireAuthenticatedUser{users.ViewerAsParent},\n\t\t\troutes.RequestContentType{\"application\/json\"},\n\t\t\troutes.RequestBody{InviteUserRequest{\"example@example.com\", 1234, 0}},\n\t\t\troutes.Documentation{\n\t\t\t\tSummary:     \"Creates an invite\",\n\t\t\t\tDescription: \"Creates an invite for account team sharing\",\n\t\t\t},\n\t\t),\n\t\thttp.MethodPatch: routes.H(updateSharedUsers).With(\n\t\t\tdb.RequestTransaction{db.Db},\n\t\t\tusers.RequireAuthenticatedUser{users.ViewerAsParent},\n\t\t\troutes.RequestContentType{\"application\/json\"},\n\t\t\troutes.RequestBody{updateUsersSharedAccountRequest{1, 2}},\n\t\t\troutes.Documentation{\n\t\t\t\tSummary:     \"Update shared users\",\n\t\t\t\tDescription: \"Update shared users associated with a specific AWS account\",\n\t\t\t},\n\t\t),\n\t\thttp.MethodDelete: routes.H(deleteSharedUsers).With(\n\t\t\tdb.RequestTransaction{db.Db},\n\t\t\tusers.RequireAuthenticatedUser{users.ViewerAsParent},\n\t\t\troutes.RequestBody{deleteUsersSharedAccountRequest{1}},\n\t\t\troutes.Documentation{\n\t\t\t\tSummary:     \"Delete shared users\",\n\t\t\t\tDescription: \"Delete shared users associated with a specific AWS account\",\n\t\t\t},\n\t\t),\n\t}.H().With(\n\t\tdb.RequestTransaction{db.Db},\n\t\troutes.Documentation{\n\t\t\tSummary: \"interact with shared accounts\",\n\t\t},\n\t).Register(\"\/user\/share\")\n}\n\n\/\/ inviteUser handles users invite for team sharing.\nfunc inviteUser(request *http.Request, a routes.Arguments) (int, interface{}) {\n\tvar body InviteUserRequest\n\troutes.MustRequestBody(a, &body)\n\ttx := a[db.Transaction].(*sql.Tx)\n\tuser := a[users.AuthenticatedUser].(users.User)\n\treturn InviteUserWithValidBody(request, body, tx, user)\n}\n\n\/\/ listSharedUsers handles listing of users who have an access to an AWS account.\nfunc listSharedUsers(request *http.Request, a routes.Arguments) (int, interface{}) {\n\taccountId := a[routes.AwsAccountIdQueryArg].(int)\n\ttx := a[db.Transaction].(*sql.Tx)\n\tuser := a[users.AuthenticatedUser].(users.User)\n\treturn listSharedUserAccessWithValidBody(request, accountId, tx, user)\n}\n\n\/\/ updateSharedUsers handles updates of user permission level for team sharing.\nfunc updateSharedUsers(request *http.Request, a routes.Arguments) (int, interface{}) {\n\tvar body updateUsersSharedAccountRequest\n\troutes.MustRequestBody(a, &body)\n\ttx := a[db.Transaction].(*sql.Tx)\n\tuser := a[users.AuthenticatedUser].(users.User)\n\treturn updateSharedUserAccessWithValidBody(request, body, tx, user)\n}\n\n\/\/ deleteSharedUsers handles user access deletion for team sharing\nfunc deleteSharedUsers(request *http.Request, a routes.Arguments) (int, interface{}) {\n\tvar body deleteUsersSharedAccountRequest\n\troutes.MustRequestBody(a, &body)\n\ttx := a[db.Transaction].(*sql.Tx)\n\tuser := a[users.AuthenticatedUser].(users.User)\n\treturn deleteSharedUserAccessWithValidBody(request, body, tx, user)\n}\n\n\/\/ listSharedUserAccessWithValidBody tries to list users who have an access to an AWS account\nfunc listSharedUserAccessWithValidBody(request *http.Request, accountId int, tx *sql.Tx, user users.User) (int, interface{}) {\n\tsecurity, err := safetyCheckByAccountId(request.Context(), tx, accountId, user)\n\tif !security || err != nil {\n\t\treturn 403, err\n\t}\n\tres, err := GetSharingList(request.Context(), db.Db, accountId)\n\tif err != nil {\n\t\treturn 403, errors.New(\"Error retrieving shared users list\")\n\t} else {\n\t\treturn 200, res\n\t}\n}\n\n\/\/ updateSharedUserAccessWithValidBody tries to update users permission level for team sharing\nfunc updateSharedUserAccessWithValidBody(request *http.Request, body updateUsersSharedAccountRequest, tx *sql.Tx, user users.User) (int, interface{}) {\n\tsecurity, err := safetyCheckByShareId(request.Context(), tx, body.ShareId, user)\n\tif !security || err != nil {\n\t\treturn 403, err\n\t}\n\tres, err := UpdateSharedUser(request.Context(), db.Db, body.ShareId, body.PermissionLevel)\n\tif err != nil {\n\t\treturn 403, errors.New(\"Error updating shared user list\")\n\t}\n\treturn 200, res\n}\n\n\/\/ deleteSharedUserAccessWithValidBody tries to delete users from accessing specific shared aws account\nfunc deleteSharedUserAccessWithValidBody(request *http.Request, body deleteUsersSharedAccountRequest, tx *sql.Tx, user users.User) (int, interface{}) {\n\tsecurity, err := safetyCheckByShareId(request.Context(), tx, body.ShareId, user)\n\tif !security || err != nil {\n\t\treturn 403, err\n\t}\n\terr = DeleteSharedUser(request.Context(), db.Db, body.ShareId)\n\tif err != nil {\n\t\treturn 403, errors.New(\"Error deleting shared user\")\n\t}\n\treturn 200, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file is subject to a 1-clause BSD license.\n\/\/ Its contents can be found in the enclosed LICENSE file.\n\npackage ipintel\n\nimport (\n\t\"crypto\/md5\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/jteeuwen\/ircb\/cmd\"\n\t\"github.com\/jteeuwen\/ircb\/plugin\"\n\t\"github.com\/jteeuwen\/ircb\/proto\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar regMibbit = regexp.MustCompile(`^[a-fA-F0-9]{8}$`)\n\nconst url = \"http:\/\/api.neustar.biz\/ipi\/std\/v1\/ipinfo\/%s?apikey=%s&sig=%s&format=json\"\n\nfunc init() { plugin.Register(New) }\n\ntype Plugin struct {\n\t*plugin.Base\n}\n\nfunc New(profile string) plugin.Plugin {\n\tp := new(Plugin)\n\tp.Base = plugin.New(profile, \"ipintel\")\n\treturn p\n}\n\nfunc (p *Plugin) Load(c *proto.Client) (err error) {\n\terr = p.Base.Load(c)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tini := p.LoadConfig()\n\tif ini == nil {\n\t\tlog.Fatalf(\"[ipintel] No configuration found.\")\n\t\treturn\n\t}\n\n\tkey := ini.Section(\"api\").S(\"key\", \"\")\n\tif len(key) == 0 {\n\t\tlog.Fatalf(\"[ipintel] No API key found.\")\n\t\treturn\n\t}\n\n\tshared := ini.Section(\"api\").S(\"shared\", \"\")\n\tif len(shared) == 0 {\n\t\tlog.Fatalf(\"[ipintel] No API shared secret found.\")\n\t\treturn\n\t}\n\n\tdrift := ini.Section(\"api\").I64(\"drift\", 0)\n\tif len(shared) == 0 {\n\t\tlog.Fatalf(\"[ipintel] No API shared secret found.\")\n\t\treturn\n\t}\n\n\tw := new(cmd.Command)\n\tw.Name = \"loc\"\n\tw.Description = \"Fetch geo-location data for the given IP address.\"\n\tw.Restricted = false\n\tw.Params = []cmd.Param{\n\t\t{Name: \"ip\", Description: \"IPv4 address to look up\", Pattern: cmd.RegIPv4},\n\t}\n\tw.Execute = func(cmd *cmd.Command, c *proto.Client, m *proto.Message) {\n\t\thash := md5.New()\n\t\tstamp := fmt.Sprintf(\"%d\", time.Now().UTC().Unix()+drift)\n\t\tio.WriteString(hash, key+shared+stamp)\n\n\t\tsig := fmt.Sprintf(\"%x\", hash.Sum(nil))\n\t\ttarget := fmt.Sprintf(url, cmd.Params[0].Value, key, sig)\n\n\t\tresp, err := http.Get(target)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[ipintel]: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tresp.Body.Close()\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[ipintel]: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tvar data Response\n\t\terr = json.Unmarshal(body, &data)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[ipintel]: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tinf := data.IPInfo\n\n\t\tc.PrivMsg(m.Receiver,\n\t\t\t\"%s: %s (%s), Network org.: %s, Carrier: %s, TLD: %s, SLD: %s. \"+\n\t\t\t\t\"Location: %s\/%s\/%s\/%s (%f, %f). Postalcode: %s, Timezone: %d\",\n\t\t\tm.SenderName,\n\n\t\t\tinf.IPAddress, inf.IPType,\n\t\t\tinf.Network.Organization,\n\t\t\tinf.Network.Carrier,\n\t\t\tinf.Network.Domain.TLD,\n\t\t\tinf.Network.Domain.SLD,\n\n\t\t\tinf.Location.Continent,\n\t\t\tinf.Location.CountryData.Name,\n\t\t\tinf.Location.StateData.Name,\n\t\t\tinf.Location.CityData.Name,\n\t\t\tinf.Location.Latitude,\n\t\t\tinf.Location.Longitude,\n\t\t\tinf.Location.CityData.PostalCode,\n\t\t\tinf.Location.CityData.TimeZone,\n\t\t)\n\t}\n\n\tcmd.Register(w)\n\n\tw = new(cmd.Command)\n\tw.Name = \"mibbit\"\n\tw.Description = \"Resolve a mibbit address to a real IP address.\"\n\tw.Restricted = false\n\tw.Params = []cmd.Param{\n\t\t{Name: \"hex\", Description: \"Mibbit hex string\", Pattern: regMibbit},\n\t}\n\tw.Execute = func(cmd *cmd.Command, c *proto.Client, m *proto.Message) {\n\t\thex := cmd.Params[0].Value\n\n\t\tvar ip [4]uint64\n\t\tvar err error\n\n\t\tip[0], err = strconv.ParseUint(hex[:2], 16, 8)\n\t\tif err != nil {\n\t\t\tgoto error\n\t\t}\n\n\t\tip[1], err = strconv.ParseUint(hex[2:4], 16, 8)\n\t\tif err != nil {\n\t\t\tgoto error\n\t\t}\n\n\t\tip[2], err = strconv.ParseUint(hex[4:6], 16, 8)\n\t\tif err != nil {\n\t\t\tgoto error\n\t\t}\n\n\t\tip[3], err = strconv.ParseUint(hex[6:], 16, 8)\n\t\tif err != nil {\n\t\t\tgoto error\n\t\t}\n\n\t\tc.PrivMsg(m.Receiver, \"%s: %s -> %d.%d.%d.%d\",\n\t\t\tm.SenderName, hex, ip[0], ip[1], ip[2], ip[3])\n\t\treturn\n\n\terror:\n\t\tc.PrivMsg(m.Receiver, \"%s: invalid mibbit address.\", m.SenderName)\n\t}\n\n\tcmd.Register(w)\n\n\treturn\n}\n<commit_msg>Includes hostname lookup in mibbit command.<commit_after>\/\/ This file is subject to a 1-clause BSD license.\n\/\/ Its contents can be found in the enclosed LICENSE file.\n\npackage ipintel\n\nimport (\n\t\"crypto\/md5\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/jteeuwen\/ircb\/cmd\"\n\t\"github.com\/jteeuwen\/ircb\/plugin\"\n\t\"github.com\/jteeuwen\/ircb\/proto\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar regMibbit = regexp.MustCompile(`^[a-fA-F0-9]{8}$`)\n\nconst url = \"http:\/\/api.neustar.biz\/ipi\/std\/v1\/ipinfo\/%s?apikey=%s&sig=%s&format=json\"\n\nfunc init() { plugin.Register(New) }\n\ntype Plugin struct {\n\t*plugin.Base\n}\n\nfunc New(profile string) plugin.Plugin {\n\tp := new(Plugin)\n\tp.Base = plugin.New(profile, \"ipintel\")\n\treturn p\n}\n\nfunc (p *Plugin) Load(c *proto.Client) (err error) {\n\terr = p.Base.Load(c)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tini := p.LoadConfig()\n\tif ini == nil {\n\t\tlog.Fatalf(\"[ipintel] No configuration found.\")\n\t\treturn\n\t}\n\n\tkey := ini.Section(\"api\").S(\"key\", \"\")\n\tif len(key) == 0 {\n\t\tlog.Fatalf(\"[ipintel] No API key found.\")\n\t\treturn\n\t}\n\n\tshared := ini.Section(\"api\").S(\"shared\", \"\")\n\tif len(shared) == 0 {\n\t\tlog.Fatalf(\"[ipintel] No API shared secret found.\")\n\t\treturn\n\t}\n\n\tdrift := ini.Section(\"api\").I64(\"drift\", 0)\n\tif len(shared) == 0 {\n\t\tlog.Fatalf(\"[ipintel] No API shared secret found.\")\n\t\treturn\n\t}\n\n\tw := new(cmd.Command)\n\tw.Name = \"loc\"\n\tw.Description = \"Fetch geo-location data for the given IP address.\"\n\tw.Restricted = false\n\tw.Params = []cmd.Param{\n\t\t{Name: \"ip\", Description: \"IPv4 address to look up\", Pattern: cmd.RegIPv4},\n\t}\n\tw.Execute = func(cmd *cmd.Command, c *proto.Client, m *proto.Message) {\n\t\thash := md5.New()\n\t\tstamp := fmt.Sprintf(\"%d\", time.Now().UTC().Unix()+drift)\n\t\tio.WriteString(hash, key+shared+stamp)\n\n\t\tsig := fmt.Sprintf(\"%x\", hash.Sum(nil))\n\t\ttarget := fmt.Sprintf(url, cmd.Params[0].Value, key, sig)\n\n\t\tresp, err := http.Get(target)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[ipintel]: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tresp.Body.Close()\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[ipintel]: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tvar data Response\n\t\terr = json.Unmarshal(body, &data)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[ipintel]: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tinf := data.IPInfo\n\n\t\tc.PrivMsg(m.Receiver,\n\t\t\t\"%s: %s (%s), Network org.: %s, Carrier: %s, TLD: %s, SLD: %s. \"+\n\t\t\t\t\"Location: %s\/%s\/%s\/%s (%f, %f). Postalcode: %s, Timezone: %d\",\n\t\t\tm.SenderName,\n\n\t\t\tinf.IPAddress, inf.IPType,\n\t\t\tinf.Network.Organization,\n\t\t\tinf.Network.Carrier,\n\t\t\tinf.Network.Domain.TLD,\n\t\t\tinf.Network.Domain.SLD,\n\n\t\t\tinf.Location.Continent,\n\t\t\tinf.Location.CountryData.Name,\n\t\t\tinf.Location.StateData.Name,\n\t\t\tinf.Location.CityData.Name,\n\t\t\tinf.Location.Latitude,\n\t\t\tinf.Location.Longitude,\n\t\t\tinf.Location.CityData.PostalCode,\n\t\t\tinf.Location.CityData.TimeZone,\n\t\t)\n\t}\n\n\tcmd.Register(w)\n\n\tw = new(cmd.Command)\n\tw.Name = \"mibbit\"\n\tw.Description = \"Resolve a mibbit address to a real IP address.\"\n\tw.Restricted = false\n\tw.Params = []cmd.Param{\n\t\t{Name: \"hex\", Description: \"Mibbit hex string\", Pattern: regMibbit},\n\t}\n\tw.Execute = func(cmd *cmd.Command, c *proto.Client, m *proto.Message) {\n\t\thex := cmd.Params[0].Value\n\n\t\tvar ip [4]uint64\n\t\tvar err error\n\n\t\tip[0], err = strconv.ParseUint(hex[:2], 16, 8)\n\t\tif err != nil {\n\t\t\tc.PrivMsg(m.Receiver, \"%s: invalid mibbit address.\", m.SenderName)\n\t\t\treturn\n\t\t}\n\n\t\tip[1], err = strconv.ParseUint(hex[2:4], 16, 8)\n\t\tif err != nil {\n\t\t\tc.PrivMsg(m.Receiver, \"%s: invalid mibbit address.\", m.SenderName)\n\t\t\treturn\n\t\t}\n\n\t\tip[2], err = strconv.ParseUint(hex[4:6], 16, 8)\n\t\tif err != nil {\n\t\t\tc.PrivMsg(m.Receiver, \"%s: invalid mibbit address.\", m.SenderName)\n\t\t\treturn\n\t\t}\n\n\t\tip[3], err = strconv.ParseUint(hex[6:], 16, 8)\n\t\tif err != nil {\n\t\t\tc.PrivMsg(m.Receiver, \"%s: invalid mibbit address.\", m.SenderName)\n\t\t\treturn\n\t\t}\n\n\t\taddress := fmt.Sprintf(\"%d.%d.%d.%d\", ip[0], ip[1], ip[2], ip[3])\n\t\tnames, err := net.LookupAddr(address)\n\n\t\tif err != nil || len(names) == 0 {\n\t\t\tc.PrivMsg(m.Receiver, \"%s: %s is %s\", m.SenderName, hex, address)\n\t\t} else {\n\t\t\tc.PrivMsg(m.Receiver, \"%s: %s is %s \/ %s\",\n\t\t\t\tm.SenderName, hex, address, names[0])\n\t\t}\n\t}\n\n\tcmd.Register(w)\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 The Pythia Authors.\n\/\/ This file is part of Pythia.\n\/\/\n\/\/ Pythia is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, version 3 of the License.\n\/\/\n\/\/ Pythia is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with Pythia.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\npackage backend\n\nimport (\n\t\"pythia\"\n\t\"testing\"\n\t\"testutils\"\n\t\"testutils\/pytest\"\n\t\"time\"\n)\n\n\/\/ NewTestJob creates a job, configured with the paths exported from make.\nfunc newTestJob(task pythia.Task, input string) *Job {\n\tjob := NewJob()\n\tjob.Task = task\n\tjob.Input = input\n\tjob.UmlPath = pytest.UmlPath\n\tjob.EnvDir = pytest.VmDir\n\tjob.TasksDir = pytest.TasksDir\n\treturn job\n}\n\n\/\/ RunTask executes task with input.\n\/\/ It checks that the execution time and output length are within the specified\n\/\/ limits.\nfunc runTask(t *testing.T, task pythia.Task, input string) (status pythia.Status, output string) {\n\tjob := newTestJob(task, input)\n\twd := testutils.Watchdog(t, task.Limits.Time+1)\n\tstatus, output = job.Execute()\n\twd.Stop()\n\tif len(output) > task.Limits.Output {\n\t\tt.Errorf(\"Job output is too large: max %d, got %d.\", task.Limits.Output,\n\t\t\tlen(output))\n\t}\n\treturn\n}\n\n\/\/ RunTaskCheck behaves like RunTask, but additionally checks for expected\n\/\/ status and output.\nfunc runTaskCheck(t *testing.T, task pythia.Task, input string,\n\tstatus pythia.Status, output string) {\n\tst, out := runTask(t, task, input)\n\ttestutils.Expect(t, \"status\", status, st)\n\ttestutils.Expect(t, \"output\", output, out)\n}\n\n\/\/ Shortcut for runTask(t, pytest.ReadTask(t, basename), ...)\nfunc run(t *testing.T, basename string, input string, status pythia.Status,\n\toutput string) {\n\trunTaskCheck(t, pytest.ReadTask(t, basename), input, status, output)\n}\n\n\/\/ Basic hello world task.\nfunc TestJobHelloWorld(t *testing.T) {\n\trun(t, \"hello-world\", \"\", pythia.Success, \"Hello world!\\n\")\n}\n\n\/\/ Check that the goroutines are cleaned correctly.\nfunc TestJobCleanup(t *testing.T) {\n\ttestutils.CheckGoroutines(t, func() {\n\t\trun(t, \"hello-world\", \"\", pythia.Success, \"Hello world!\\n\")\n\t})\n}\n\n\/\/ Hello world task with input.\nfunc TestJobHelloInput(t *testing.T) {\n\trun(t, \"hello-input\", \"me\\npythia\\n\",\n\t\tpythia.Success, \"Hello me!\\nHello pythia!\\n\")\n}\n\n\/\/ This task should time out after 5 seconds.\nfunc TestJobTimeout(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"skipping timeout test in short mode\")\n\t}\n\trun(t, \"timeout\", \"\", pythia.Timeout, \"Start\\n\")\n}\n\n\/\/ This task should overflow the output buffer.\nfunc TestJobOverflow(t *testing.T) {\n\ttask := pytest.ReadTask(t, \"overflow\")\n\tt.Log(\"Trying limit 10\")\n\ttask.Limits.Output = 10\n\trunTaskCheck(t, task, \"\", pythia.Success, \"abcde\")\n\tt.Log(\"Trying limit 6\")\n\ttask.Limits.Output = 6\n\trunTaskCheck(t, task, \"\", pythia.Success, \"abcde\")\n\tt.Log(\"Trying limit 5\")\n\ttask.Limits.Output = 5\n\trunTaskCheck(t, task, \"\", pythia.Success, \"abcde\")\n\tt.Log(\"Trying limit 4\")\n\ttask.Limits.Output = 4\n\trunTaskCheck(t, task, \"\", pythia.Overflow, \"abcd\")\n\tt.Log(\"Trying limit 3\")\n\ttask.Limits.Output = 3\n\trunTaskCheck(t, task, \"\", pythia.Overflow, \"abc\")\n}\n\n\/\/ This task should overflow and be killed before the end.\nfunc TestJobOverflowKill(t *testing.T) {\n\twd := testutils.Watchdog(t, 2)\n\trun(t, \"overflow-kill\", \"\", pythia.Overflow, \"abcde\")\n\twd.Stop()\n}\n\n\/\/ This task is a fork bomb. It should succeed, but not take the whole time.\nfunc TestJobForkbomb(t *testing.T) {\n\twd := testutils.Watchdog(t, 10)\n\trun(t, \"forkbomb\", \"\", pythia.Success, \"Start\\nDone\\n\")\n\twd.Stop()\n}\n\n\/\/ Flooding the disk should not have any adverse effect.\nfunc TestJobFlooddisk(t *testing.T) {\n\trun(t, \"flooddisk\", \"\", pythia.Success, \"Start\\nDone\\n\")\n}\n\n\/\/ Aborting a job shall be immediate.\nfunc TestJobAbort(t *testing.T) {\n\tjob := newTestJob(pytest.ReadTask(t, \"timeout\"), \"\")\n\tdone := make(chan bool)\n\tgo func() {\n\t\twd := testutils.Watchdog(t, 2)\n\t\tstatus, output := job.Execute()\n\t\twd.Stop()\n\t\ttestutils.Expect(t, \"status\", pythia.Abort, status)\n\t\ttestutils.Expect(t, \"output\", \"Start\\n\", output)\n\t\tdone <- true\n\t}()\n\ttime.Sleep(1 * time.Second)\n\tjob.Abort()\n\t<-done\n}\n\n\/\/ vim:set sw=4 ts=4 noet:\n<commit_msg>Fix the watchdog to allow 60sec instead of 2 for forkbomb testing<commit_after>\/\/ Copyright 2013 The Pythia Authors.\n\/\/ This file is part of Pythia.\n\/\/\n\/\/ Pythia is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, version 3 of the License.\n\/\/\n\/\/ Pythia is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with Pythia.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\npackage backend\n\nimport (\n\t\"pythia\"\n\t\"testing\"\n\t\"testutils\"\n\t\"testutils\/pytest\"\n\t\"time\"\n)\n\n\/\/ NewTestJob creates a job, configured with the paths exported from make.\nfunc newTestJob(task pythia.Task, input string) *Job {\n\tjob := NewJob()\n\tjob.Task = task\n\tjob.Input = input\n\tjob.UmlPath = pytest.UmlPath\n\tjob.EnvDir = pytest.VmDir\n\tjob.TasksDir = pytest.TasksDir\n\treturn job\n}\n\n\/\/ RunTask executes task with input.\n\/\/ It checks that the execution time and output length are within the specified\n\/\/ limits.\nfunc runTask(t *testing.T, task pythia.Task, input string) (status pythia.Status, output string) {\n\tjob := newTestJob(task, input)\n\twd := testutils.Watchdog(t, task.Limits.Time+1)\n\tstatus, output = job.Execute()\n\twd.Stop()\n\tif len(output) > task.Limits.Output {\n\t\tt.Errorf(\"Job output is too large: max %d, got %d.\", task.Limits.Output,\n\t\t\tlen(output))\n\t}\n\treturn\n}\n\n\/\/ RunTaskCheck behaves like RunTask, but additionally checks for expected\n\/\/ status and output.\nfunc runTaskCheck(t *testing.T, task pythia.Task, input string,\n\tstatus pythia.Status, output string) {\n\tst, out := runTask(t, task, input)\n\ttestutils.Expect(t, \"status\", status, st)\n\ttestutils.Expect(t, \"output\", output, out)\n}\n\n\/\/ Shortcut for runTask(t, pytest.ReadTask(t, basename), ...)\nfunc run(t *testing.T, basename string, input string, status pythia.Status,\n\toutput string) {\n\trunTaskCheck(t, pytest.ReadTask(t, basename), input, status, output)\n}\n\n\/\/ Basic hello world task.\nfunc TestJobHelloWorld(t *testing.T) {\n\trun(t, \"hello-world\", \"\", pythia.Success, \"Hello world!\\n\")\n}\n\n\/\/ Check that the goroutines are cleaned correctly.\nfunc TestJobCleanup(t *testing.T) {\n\ttestutils.CheckGoroutines(t, func() {\n\t\trun(t, \"hello-world\", \"\", pythia.Success, \"Hello world!\\n\")\n\t})\n}\n\n\/\/ Hello world task with input.\nfunc TestJobHelloInput(t *testing.T) {\n\trun(t, \"hello-input\", \"me\\npythia\\n\",\n\t\tpythia.Success, \"Hello me!\\nHello pythia!\\n\")\n}\n\n\/\/ This task should time out after 5 seconds.\nfunc TestJobTimeout(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"skipping timeout test in short mode\")\n\t}\n\trun(t, \"timeout\", \"\", pythia.Timeout, \"Start\\n\")\n}\n\n\/\/ This task should overflow the output buffer.\nfunc TestJobOverflow(t *testing.T) {\n\ttask := pytest.ReadTask(t, \"overflow\")\n\tt.Log(\"Trying limit 10\")\n\ttask.Limits.Output = 10\n\trunTaskCheck(t, task, \"\", pythia.Success, \"abcde\")\n\tt.Log(\"Trying limit 6\")\n\ttask.Limits.Output = 6\n\trunTaskCheck(t, task, \"\", pythia.Success, \"abcde\")\n\tt.Log(\"Trying limit 5\")\n\ttask.Limits.Output = 5\n\trunTaskCheck(t, task, \"\", pythia.Success, \"abcde\")\n\tt.Log(\"Trying limit 4\")\n\ttask.Limits.Output = 4\n\trunTaskCheck(t, task, \"\", pythia.Overflow, \"abcd\")\n\tt.Log(\"Trying limit 3\")\n\ttask.Limits.Output = 3\n\trunTaskCheck(t, task, \"\", pythia.Overflow, \"abc\")\n}\n\n\/\/ This task should overflow and be killed before the end.\nfunc TestJobOverflowKill(t *testing.T) {\n\twd := testutils.Watchdog(t, 2)\n\trun(t, \"overflow-kill\", \"\", pythia.Overflow, \"abcde\")\n\twd.Stop()\n}\n\n\/\/ This task is a fork bomb. It should succeed, but not take the whole time.\nfunc TestJobForkbomb(t *testing.T) {\n\twd := testutils.Watchdog(t, 60)\n\trun(t, \"forkbomb\", \"\", pythia.Success, \"Start\\nDone\\n\")\n\twd.Stop()\n}\n\n\/\/ Flooding the disk should not have any adverse effect.\nfunc TestJobFlooddisk(t *testing.T) {\n\trun(t, \"flooddisk\", \"\", pythia.Success, \"Start\\nDone\\n\")\n}\n\n\/\/ Aborting a job shall be immediate.\nfunc TestJobAbort(t *testing.T) {\n\tjob := newTestJob(pytest.ReadTask(t, \"timeout\"), \"\")\n\tdone := make(chan bool)\n\tgo func() {\n\t\twd := testutils.Watchdog(t, 2)\n\t\tstatus, output := job.Execute()\n\t\twd.Stop()\n\t\ttestutils.Expect(t, \"status\", pythia.Abort, status)\n\t\ttestutils.Expect(t, \"output\", \"Start\\n\", output)\n\t\tdone <- true\n\t}()\n\ttime.Sleep(1 * time.Second)\n\tjob.Abort()\n\t<-done\n}\n\n\/\/ vim:set sw=4 ts=4 noet:\n<|endoftext|>"}
{"text":"<commit_before>package generator\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"chain\/database\/pg\"\n\t\"chain\/errors\"\n\t\"chain\/log\"\n\t\"chain\/protocol\"\n\t\"chain\/protocol\/bc\"\n\t\"chain\/protocol\/state\"\n)\n\n\/\/ A BlockSigner signs blocks.\ntype BlockSigner interface {\n\t\/\/ SignBlock returns an ed25519 signature over the block's sighash.\n\t\/\/ See also the Chain Protocol spec for the complete required behavior\n\t\/\/ of a block signer.\n\tSignBlock(context.Context, *bc.Block) (signature []byte, err error)\n}\n\n\/\/ generator produces new blocks on an interval.\ntype generator struct {\n\t\/\/ config\n\tchain   *protocol.Chain\n\tsigners []BlockSigner\n\n\t\/\/ latestBlock and latestSnapshot are current as long as this\n\t\/\/ process remains the leader process. If the process is demoted,\n\t\/\/ generator.Generate() should return and this struct should be\n\t\/\/ garbage collected.\n\tlatestBlock    *bc.Block\n\tlatestSnapshot *state.Snapshot\n}\n\n\/\/ Generate runs in a loop, making one new block\n\/\/ every block period. It returns when its context\n\/\/ is canceled.\nfunc Generate(ctx context.Context, c *protocol.Chain, s []BlockSigner, period time.Duration) {\n\t\/\/ This process just became leader, so it's responsible\n\t\/\/ for recovering after the previous leader's exit.\n\trecoveredBlock, recoveredSnapshot, err := c.Recover(ctx)\n\tif err != nil {\n\t\tlog.Fatal(ctx, log.KeyError, err)\n\t}\n\n\tg := &generator{\n\t\tchain:          c,\n\t\tsigners:        s,\n\t\tlatestBlock:    recoveredBlock,\n\t\tlatestSnapshot: recoveredSnapshot,\n\t}\n\n\t\/\/ Check to see if we already have a pending, generated block.\n\t\/\/ This can happen if the leader process exits between generating\n\t\/\/ the block and committing the signed block to the blockchain.\n\tb, err := g.getPendingBlock(ctx)\n\tif err != nil {\n\t\tlog.Fatal(ctx, err)\n\t}\n\tif b != nil && (g.latestBlock == nil || b.Height == g.latestBlock.Height+1) {\n\t\ts, err := g.chain.ValidateBlock(ctx, g.latestSnapshot, g.latestBlock, b)\n\t\tif err != nil {\n\t\t\tlog.Fatal(ctx, err)\n\t\t}\n\n\t\t\/\/ g.commitBlock will update g.latestBlock and g.latestSnapshot.\n\t\t_, err = g.commitBlock(ctx, b, s)\n\t\tif err != nil {\n\t\t\tlog.Fatal(ctx, err)\n\t\t}\n\t}\n\n\tticks := time.Tick(period)\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tlog.Messagef(ctx, \"Deposed, Generate exiting\")\n\t\t\treturn\n\t\tcase <-ticks:\n\t\t\t_, err := g.makeBlock(ctx)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(ctx, err)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ GetBlocks returns contiguous blocks\n\/\/ with heights larger than afterHeight,\n\/\/ in block-height order.\n\/\/ If successful, it always returns at least one block,\n\/\/ waiting if necessary until one is created.\n\/\/ It is not guaranteed to return all available blocks.\n\/\/ It is an error to request blocks very far in the future.\nfunc GetBlocks(ctx context.Context, c *protocol.Chain, afterHeight uint64) ([]*bc.Block, error) {\n\t\/\/ TODO(kr): This is not a generator function.\n\t\/\/ Move this to another package.\n\terr := c.WaitForBlockSoon(afterHeight + 1)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"waiting for block at height %d\", afterHeight+1)\n\t}\n\n\tconst q = `SELECT data FROM blocks WHERE height > $1 ORDER BY height`\n\tvar blocks []*bc.Block\n\terr = pg.ForQueryRows(ctx, q, afterHeight, func(b bc.Block) {\n\t\tblocks = append(blocks, &b)\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"querying blocks from the db\")\n\t}\n\treturn blocks, nil\n}\n<commit_msg>core\/generator: limit blocks fetched at a time<commit_after>package generator\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"chain\/database\/pg\"\n\t\"chain\/errors\"\n\t\"chain\/log\"\n\t\"chain\/protocol\"\n\t\"chain\/protocol\/bc\"\n\t\"chain\/protocol\/state\"\n)\n\n\/\/ A BlockSigner signs blocks.\ntype BlockSigner interface {\n\t\/\/ SignBlock returns an ed25519 signature over the block's sighash.\n\t\/\/ See also the Chain Protocol spec for the complete required behavior\n\t\/\/ of a block signer.\n\tSignBlock(context.Context, *bc.Block) (signature []byte, err error)\n}\n\n\/\/ generator produces new blocks on an interval.\ntype generator struct {\n\t\/\/ config\n\tchain   *protocol.Chain\n\tsigners []BlockSigner\n\n\t\/\/ latestBlock and latestSnapshot are current as long as this\n\t\/\/ process remains the leader process. If the process is demoted,\n\t\/\/ generator.Generate() should return and this struct should be\n\t\/\/ garbage collected.\n\tlatestBlock    *bc.Block\n\tlatestSnapshot *state.Snapshot\n}\n\n\/\/ Generate runs in a loop, making one new block\n\/\/ every block period. It returns when its context\n\/\/ is canceled.\nfunc Generate(ctx context.Context, c *protocol.Chain, s []BlockSigner, period time.Duration) {\n\t\/\/ This process just became leader, so it's responsible\n\t\/\/ for recovering after the previous leader's exit.\n\trecoveredBlock, recoveredSnapshot, err := c.Recover(ctx)\n\tif err != nil {\n\t\tlog.Fatal(ctx, log.KeyError, err)\n\t}\n\n\tg := &generator{\n\t\tchain:          c,\n\t\tsigners:        s,\n\t\tlatestBlock:    recoveredBlock,\n\t\tlatestSnapshot: recoveredSnapshot,\n\t}\n\n\t\/\/ Check to see if we already have a pending, generated block.\n\t\/\/ This can happen if the leader process exits between generating\n\t\/\/ the block and committing the signed block to the blockchain.\n\tb, err := g.getPendingBlock(ctx)\n\tif err != nil {\n\t\tlog.Fatal(ctx, err)\n\t}\n\tif b != nil && (g.latestBlock == nil || b.Height == g.latestBlock.Height+1) {\n\t\ts, err := g.chain.ValidateBlock(ctx, g.latestSnapshot, g.latestBlock, b)\n\t\tif err != nil {\n\t\t\tlog.Fatal(ctx, err)\n\t\t}\n\n\t\t\/\/ g.commitBlock will update g.latestBlock and g.latestSnapshot.\n\t\t_, err = g.commitBlock(ctx, b, s)\n\t\tif err != nil {\n\t\t\tlog.Fatal(ctx, err)\n\t\t}\n\t}\n\n\tticks := time.Tick(period)\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tlog.Messagef(ctx, \"Deposed, Generate exiting\")\n\t\t\treturn\n\t\tcase <-ticks:\n\t\t\t_, err := g.makeBlock(ctx)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(ctx, err)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ GetBlocks returns contiguous blocks\n\/\/ with heights larger than afterHeight,\n\/\/ in block-height order.\n\/\/ If successful, it always returns at least one block,\n\/\/ waiting if necessary until one is created.\n\/\/ It is not guaranteed to return all available blocks.\n\/\/ It is an error to request blocks very far in the future.\nfunc GetBlocks(ctx context.Context, c *protocol.Chain, afterHeight uint64) ([]*bc.Block, error) {\n\t\/\/ TODO(kr): This is not a generator function.\n\t\/\/ Move this to another package.\n\terr := c.WaitForBlockSoon(afterHeight + 1)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"waiting for block at height %d\", afterHeight+1)\n\t}\n\n\tconst q = `SELECT data FROM blocks WHERE height > $1 ORDER BY height LIMIT 10`\n\tvar blocks []*bc.Block\n\terr = pg.ForQueryRows(ctx, q, afterHeight, func(b bc.Block) {\n\t\tblocks = append(blocks, &b)\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"querying blocks from the db\")\n\t}\n\treturn blocks, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package contnet\n\nimport (\n\t\"github.com\/asaskevich\/EventBus\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n)\n\nfunc init() {\n\trand.Seed(time.Now().Unix())\n}\n\ntype NetConfig struct {\n\tMaxContentAge           time.Duration\n\tCheckContentAgeInterval time.Duration\n\tItemsPerPage            uint8\n\tNoveltyPct              float64\n\tSnapshotPath            string\n\tSnapshotInterval        time.Duration\n}\n\ntype Net struct {\n\tsync.RWMutex\n\tconfig       *NetConfig\n\tbus          *EventBus.EventBus\n\tcontentStore *ContentStore\n\tprofileStore *ProfileStore\n\ttrendStore   *TrendStore\n\tindex        *Index\n}\ntype NetFactory struct{}\n\nfunc (factory NetFactory) New(config *NetConfig) *Net {\n\tbus := EventBus.New()\n\tcontentStore := Object.ContentStore.New(config, bus)\n\tnet := &Net{\n\t\tconfig:       config,\n\t\tbus:          bus,\n\t\tcontentStore: contentStore,\n\t\tprofileStore: Object.ProfileStore.New(),\n\t\ttrendStore:   Object.TrendStore.New(bus),\n\t\tindex:        Object.Index.New(config, bus, contentStore),\n\t}\n\tif err := net.Restore(); err != nil {\n\t\tlog.Print(\"Failed to restore net object, proceeding empty.\")\n\t}\n\tgo net.__snapshot()\n\tgo net.index.__refresh()\n\n\treturn net\n}\n\nfunc (net *Net) __snapshot() {\n\tfor {\n\t\tnet.Snapshot()\n\t\ttime.Sleep(net.config.SnapshotInterval)\n\t}\n}\n\nfunc (net *Net) Snapshot() error {\n\tif err := net.contentStore.Snapshot(net.config.SnapshotPath, \"content\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := net.index.Snapshot(net.config.SnapshotPath, \"index\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := net.profileStore.Snapshot(net.config.SnapshotPath, \"profiles\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := net.trendStore.Snapshot(net.config.SnapshotPath, \"trends\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (net *Net) Restore() error {\n\tif err := net.contentStore.RestoreFromSnapshot(net.config.SnapshotPath, \"content\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := net.index.RestoreFromSnapshot(net.config.SnapshotPath, \"index\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := net.profileStore.RestoreFromSnapshot(net.config.SnapshotPath, \"profiles\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := net.trendStore.RestoreFromSnapshot(net.config.SnapshotPath, \"trends\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Attempts to update network object with content specified.\n\/\/ If content did not exist, it is added to the network.\n\/\/ If content did exist, it is updated.\nfunc (net *Net) SaveContent(content *Content) {\n\tnet.contentStore.Upsert(content)\n}\n\n\/\/ Attempts to update network object with action for profile specified.\nfunc (net *Net) SaveAction(action *Action) error {\n\t\/\/ get related content's copy, if any\n\trelatedContent := net.contentStore.Get(action.ContentID)\n\n\t\/\/ if content does not exist\n\tif relatedContent == nil {\n\t\treturn Errors.ContentNotFound\n\t}\n\n\t\/\/ inject related content to action\n\taction.Content = relatedContent\n\n\t\/\/ save action to profile\n\tnet.profileStore.Save(action)\n\n\t\/\/ everything is okay\n\treturn nil\n}\n\ntype SelectionCacheInfo struct {\n\tCurrentIndex int\n\tMaximumIndex int\n}\n\nfunc (net *Net) Select(profileID int64, page uint8) []ID {\n\t\/\/ get user's profile, if any\n\tprofile := net.profileStore.Get(ID(profileID))\n\n\t\/\/ assign topic interests & sort\n\tvar interests TopicInterests\n\tif profile != nil {\n\t\tTopicInterestBy(topicInterestCriteria).Sort(profile.TopicInterests)\n\t} else {\n\t\tinterests = TopicInterests{}\n\t}\n\n\ttotalContentsToRetrieve := int(page) * int(net.config.ItemsPerPage)\n\ttotalContentsByInterest := int((1 - net.config.NoveltyPct) * float64(totalContentsToRetrieve))\n\n\t\/\/ select interesting contents\n\tinterestingContents := net.__selectOfInterest(interests, totalContentsByInterest)\n\n\t\/\/ select popular contents (how many remaining \/ 2)\n\ttotalContentsByTrend := int((totalContentsToRetrieve - len(interestingContents)) \/ 2)\n\ttrendingContents := net.__selectOfTrending(interestingContents, totalContentsByTrend)\n\n\t\/\/ fill the remainder randomly\n\ttotalContentsRemaining := totalContentsToRetrieve - len(interestingContents) - len(trendingContents)\n\tout := append(interestingContents, trendingContents...)\n\tremainingContents := net.__selectOfRemaining(out, totalContentsRemaining)\n\n\t\/\/ prep the final result\n\tout = append(out, remainingContents...)\n\treturn out\n}\n\nfunc (net *Net) __selectOfInterest(interests TopicInterests, howMany int) []ID {\n\t\/\/ abort early if nothing to select..\n\tif len(interests) == 0 {\n\t\treturn []ID{}\n\t}\n\n\t\/\/ we have sorted topic interests for this user.\n\t\/\/ now we extract topics from topic-interest objects for querying the index\n\t\/\/ and we use dem iterations to form cumulative probabilities slice to be used later for randomly drawing topics\n\tinterestTopics := Topics{}\n\tcumulativeProbabilities := []float64{}\n\tfor i := 0; i < len(interests); i++ {\n\t\tinterestTopics = append(interestTopics, &interests[i].Topic)\n\t\tcumulativeProbabilities = append(cumulativeProbabilities, float64(interests[i].Interest))\n\t\tif i > 0 {\n\t\t\tcumulativeProbabilities[i] += cumulativeProbabilities[i-1]\n\t\t}\n\t}\n\n\t\/\/ use the previously created topics slice for querying the index\n\ttopicContents := net.index.GetForTopics(interestTopics)\n\t\/\/ now we have all content IDs for all topics interesting to this user\n\t\/\/ to control where we're at, we will create temporary cache that will mark extraction location for each topic\n\tcache := map[Topic]*SelectionCacheInfo{}\n\t\/\/ filling in the cache\n\tfor i := 0; i < len(interests); i++ {\n\t\tinterest := interests[i]\n\t\tcache[interest.Topic] = &SelectionCacheInfo{\n\t\t\tCurrentIndex: 0,\n\t\t\tMaximumIndex: len(topicContents[i]) - 1,\n\t\t}\n\t}\n\n\t\/\/ now we have the following data available:\n\t\/\/ 1. topics of interest for user sorted in descending order by how interesting they are\n\t\/\/ 2. for each topic of interest there is an array of ID's available for that topic\n\t\/\/ 3. map showing what index to choose for each topic\n\t\/\/ 4. cumulative probabilities\n\n\t\/\/ while there is anything interesting for user available & we haven't selected as many items as needed\n\tout := []ID{}\n\tfor len(cache) > 0 && len(out) < howMany {\n\t\t\/\/ select a random topic of interest\n\t\ttopic, i := __drawRandomTopicInterest(interests, cumulativeProbabilities)\n\n\t\t\/\/ select its best content (first index available)\n\t\tindexToSelect := cache[topic].CurrentIndex\n\n\t\t\/\/ current index can be ahead of the max index in some special cases\n\t\tif indexToSelect <= cache[topic].MaximumIndex {\n\t\t\tselectedID := topicContents[i][indexToSelect]\n\n\t\t\tif !__idsContainID(out, selectedID) {\n\t\t\t\tout = append(out, selectedID)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ advance current index in cache\n\t\tcache[topic].CurrentIndex++\n\n\t\t\/\/ if we overshot the maximum index for this topic, remove it\n\t\tif cache[topic].CurrentIndex > cache[topic].MaximumIndex {\n\t\t\t\/\/ remove from cache\n\t\t\tdelete(cache, topic)\n\t\t\t\/\/ remove from interest topics\n\t\t\tinterestTopics = append(interestTopics[:i], interestTopics[i+1:]...)\n\t\t\t\/\/ remove from topic contents\n\t\t\ttopicContents = append(topicContents[:i], topicContents[i+1:]...)\n\t\t\t\/\/ remove from interests\n\t\t\tinterests = append(interests[:i], interests[i+1:]...)\n\t\t\t\/\/ recalculate interests\n\t\t\tcumulativeProbabilities = __recalculateCumulativeProbabilities(interests)\n\t\t}\n\t}\n\n\treturn out\n}\n\nfunc __idsContainID(ids []ID, id ID) bool {\n\tfor i := 0; i < len(ids); i++ {\n\t\tif ids[i] == id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc __drawRandomTopicInterest(topicInterests TopicInterests, cumulativeProbabilities []float64) (Topic, int) {\n\trandomFloat := rand.Float64()\n\tfor i := 0; i < len(cumulativeProbabilities); i++ {\n\t\tif cumulativeProbabilities[i] >= randomFloat {\n\t\t\treturn topicInterests[i].Topic, i\n\t\t}\n\t}\n\t\/\/ this is guaranteed not to happen\n\treturn topicInterests[len(topicInterests)-1].Topic, len(topicInterests)\n}\n\nfunc __recalculateCumulativeProbabilities(topicInterests TopicInterests) []float64 {\n\t\/\/ calculate sum of cumulative interests\n\tsum := float64(0)\n\tfor i := 0; i < len(topicInterests); i++ {\n\t\tsum += float64(topicInterests[i].CumulativeInterest)\n\t}\n\n\toutput := []float64{}\n\n\tfor i := 0; i < len(topicInterests); i++ {\n\t\toutput = append(output, float64(topicInterests[i].CumulativeInterest)\/sum)\n\t\tif i > 0 {\n\t\t\toutput[i] += output[i-1]\n\t\t}\n\t}\n\n\treturn output\n}\n\nfunc (net *Net) __selectOfTrending(ignore []ID, howMany int) []ID {\n\t\/\/ select top 10 trending topics\n\ttrendingTopics := net.trendStore.GetTopN(10)\n\n\t\/\/ nothing trending, bail early\n\tif len(trendingTopics) == 0 {\n\t\treturn []ID{}\n\t}\n\n\t\/\/ get content IDs for trending topics\n\tcontentIDs := net.index.GetForTopics(trendingTopics)\n\n\t\/\/ cache indices foreach contentID\n\tcache := map[Topic]*SelectionCacheInfo{}\n\t\/\/ filling in the cache\n\tfor i := 0; i < len(trendingTopics); i++ {\n\t\tcache[*trendingTopics[i]] = &SelectionCacheInfo{\n\t\t\tCurrentIndex: 0,\n\t\t\tMaximumIndex: len(contentIDs[i]) - 1,\n\t\t}\n\t}\n\n\tnextTrendInd := 0\n\tout := []ID{}\n\tfor len(cache) > 0 && len(out) < howMany {\n        trendingTopic := *trendingTopics[nextTrendInd]\n\n        \/\/ select its best content (first index available)\n        indexToSelect := cache[trendingTopic].CurrentIndex\n\n        \/\/ current index can be ahead of the max index in some special cases\n        if indexToSelect <= cache[trendingTopic].MaximumIndex {\n            selectedID := contentIDs[nextTrendInd][indexToSelect]\n\n            if !__idsContainID(out, selectedID) && !__idsContainID(ignore, selectedID) {\n                out = append(out, selectedID)\n            }\n        }\n\n        \/\/ advance current index in cache\n        cache[trendingTopic].CurrentIndex++\n\n        \/\/ if we overshot the maximum index for this topic, remove it\n        if cache[trendingTopic].CurrentIndex > cache[trendingTopic].MaximumIndex {\n            \/\/ remove from cache\n            delete(cache, trendingTopic)\n            \/\/ remove from trending topics\n            trendingTopics = append(trendingTopics[:nextTrendInd], trendingTopics[nextTrendInd+1:]...)\n            \/\/ go back one position\n            nextTrendInd--\n        }\n\n        \/\/ reset the counter\n\t\tnextTrendInd++\n\t\tif nextTrendInd == len(trendingTopics) {\n\t\t\tnextTrendInd = 0\n\t\t}\n\t}\n\n\treturn out\n}\n\nfunc (net *Net) __selectOfRemaining(ignore []ID, howMany int) []ID {\n\t\/\/ if we are asking for more content items then there are available in content store\n\tif howMany >= (net.contentStore.Count() - len(ignore)) {\n\t\treturn net.contentStore.GetAllContentIDs()\n\t}\n\n\t\/\/ otherwise, draw random elements until howMany is satisifed. ignore duplicates of course.\n\tout := []ID{}\n\n\tfor len(out) < howMany {\n\t\trandomID := net.contentStore.GetAnyContentID()\n\t\tif !__idsContainID(out, randomID) && !__idsContainID(ignore, randomID) {\n\t\t\tout = append(out, randomID)\n\t\t}\n\t}\n\n\treturn out\n\n}\n\nfunc (net *Net) Describe() *NetDescription {\n\treturn &NetDescription{\n\t\tContents: net.contentStore.Describe(),\n\t\tIndex:    net.index.Describe(),\n\t\tProfiles: net.profileStore.Describe(),\n\t\tTrends:   net.trendStore.Describe(),\n\t}\n}\n<commit_msg>Fixes and formatting<commit_after>package contnet\n\nimport (\n\t\"github.com\/asaskevich\/EventBus\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n)\n\nfunc init() {\n\trand.Seed(time.Now().Unix())\n}\n\ntype NetConfig struct {\n\tMaxContentAge           time.Duration\n\tCheckContentAgeInterval time.Duration\n\tItemsPerPage            uint8\n\tNoveltyPct              float64\n\tSnapshotPath            string\n\tSnapshotInterval        time.Duration\n}\n\ntype Net struct {\n\tsync.RWMutex\n\tconfig       *NetConfig\n\tbus          *EventBus.EventBus\n\tcontentStore *ContentStore\n\tprofileStore *ProfileStore\n\ttrendStore   *TrendStore\n\tindex        *Index\n}\ntype NetFactory struct{}\n\nfunc (factory NetFactory) New(config *NetConfig) *Net {\n\tbus := EventBus.New()\n\tcontentStore := Object.ContentStore.New(config, bus)\n\tnet := &Net{\n\t\tconfig:       config,\n\t\tbus:          bus,\n\t\tcontentStore: contentStore,\n\t\tprofileStore: Object.ProfileStore.New(),\n\t\ttrendStore:   Object.TrendStore.New(bus),\n\t\tindex:        Object.Index.New(config, bus, contentStore),\n\t}\n\tif err := net.Restore(); err != nil {\n\t\tlog.Print(\"Failed to restore net object, proceeding empty.\")\n\t}\n\tgo net.__snapshot()\n\tgo net.index.__refresh()\n\n\treturn net\n}\n\nfunc (net *Net) __snapshot() {\n\tfor {\n\t\tnet.Snapshot()\n\t\ttime.Sleep(net.config.SnapshotInterval)\n\t}\n}\n\nfunc (net *Net) Snapshot() error {\n\tif err := net.contentStore.Snapshot(net.config.SnapshotPath, \"content\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := net.index.Snapshot(net.config.SnapshotPath, \"index\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := net.profileStore.Snapshot(net.config.SnapshotPath, \"profiles\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := net.trendStore.Snapshot(net.config.SnapshotPath, \"trends\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (net *Net) Restore() error {\n\tif err := net.contentStore.RestoreFromSnapshot(net.config.SnapshotPath, \"content\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := net.index.RestoreFromSnapshot(net.config.SnapshotPath, \"index\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := net.profileStore.RestoreFromSnapshot(net.config.SnapshotPath, \"profiles\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := net.trendStore.RestoreFromSnapshot(net.config.SnapshotPath, \"trends\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Attempts to update network object with content specified.\n\/\/ If content did not exist, it is added to the network.\n\/\/ If content did exist, it is updated.\nfunc (net *Net) SaveContent(content *Content) {\n\tnet.contentStore.Upsert(content)\n}\n\n\/\/ Attempts to update network object with action for profile specified.\nfunc (net *Net) SaveAction(action *Action) error {\n\t\/\/ get related content's copy, if any\n\trelatedContent := net.contentStore.Get(action.ContentID)\n\n\t\/\/ if content does not exist\n\tif relatedContent == nil {\n\t\treturn Errors.ContentNotFound\n\t}\n\n\t\/\/ inject related content to action\n\taction.Content = relatedContent\n\n\t\/\/ save action to profile\n\tnet.profileStore.Save(action)\n\n\t\/\/ everything is okay\n\treturn nil\n}\n\ntype SelectionCacheInfo struct {\n\tCurrentIndex int\n\tMaximumIndex int\n}\n\nfunc (net *Net) Select(profileID int64, page uint8) []ID {\n\t\/\/ get user's profile, if any\n\tprofile := net.profileStore.Get(ID(profileID))\n\n\t\/\/ assign topic interests & sort\n\tvar interests TopicInterests\n\tif profile != nil {\n\t\tTopicInterestBy(topicInterestCriteria).Sort(profile.TopicInterests)\n\t\tinterests = profile.TopicInterests\n\t} else {\n\t\tinterests = TopicInterests{}\n\t}\n\n\ttotalContentsToRetrieve := int(page) * int(net.config.ItemsPerPage)\n\ttotalContentsByInterest := int((1 - net.config.NoveltyPct) * float64(totalContentsToRetrieve))\n\n\t\/\/ select interesting contents\n\tinterestingContents := net.__selectOfInterest(interests, totalContentsByInterest)\n\t\/\/log.Println(\"Interesting: \", len(interestingContents))\n\n\t\/\/ select popular contents (how many remaining \/ 2)\n\ttotalContentsByTrend := int((totalContentsToRetrieve - len(interestingContents)) \/ 2)\n\ttrendingContents := net.__selectOfTrending(interestingContents, totalContentsByTrend)\n\t\/\/log.Println(\"Trending: \", len(trendingContents))\n\n\t\/\/ fill the remainder randomly\n\ttotalContentsRemaining := totalContentsToRetrieve - len(interestingContents) - len(trendingContents)\n\tout := append(interestingContents, trendingContents...)\n\tremainingContents := net.__selectOfRemaining(out, totalContentsRemaining)\n\t\/\/log.Println(\"Remaining: \", len(remainingContents))\n\n\t\/\/ prep the final result\n\tout = append(out, remainingContents...)\n\treturn out\n}\n\nfunc (net *Net) __selectOfInterest(interests TopicInterests, howMany int) []ID {\n\t\/\/ abort early if nothing to select..\n\tif len(interests) == 0 {\n\t\treturn []ID{}\n\t}\n\n\t\/\/ we have sorted topic interests for this user.\n\t\/\/ now we extract topics from topic-interest objects for querying the index\n\t\/\/ and we use dem iterations to form cumulative probabilities slice to be used later for randomly drawing topics\n\tinterestTopics := Topics{}\n\tcumulativeProbabilities := []float64{}\n\tfor i := 0; i < len(interests); i++ {\n\t\tinterestTopics = append(interestTopics, &interests[i].Topic)\n\t\tcumulativeProbabilities = append(cumulativeProbabilities, float64(interests[i].Interest))\n\t\tif i > 0 {\n\t\t\tcumulativeProbabilities[i] += cumulativeProbabilities[i-1]\n\t\t}\n\t}\n\n\t\/\/ use the previously created topics slice for querying the index\n\ttopicContents := net.index.GetForTopics(interestTopics)\n\n\t\/\/ now we have all content IDs for all topics interesting to this user\n\t\/\/ to control where we're at, we will create temporary cache that will mark extraction location for each topic\n\tcache := map[Topic]*SelectionCacheInfo{}\n\t\/\/ filling in the cache\n\tfor i := 0; i < len(interests); i++ {\n\t\tinterest := interests[i]\n\t\tcache[interest.Topic] = &SelectionCacheInfo{\n\t\t\tCurrentIndex: 0,\n\t\t\tMaximumIndex: len(topicContents[i]) - 1,\n\t\t}\n\t}\n\n\t\/\/ now we have the following data available:\n\t\/\/ 1. topics of interest for user sorted in descending order by how interesting they are\n\t\/\/ 2. for each topic of interest there is an array of ID's available for that topic\n\t\/\/ 3. map showing what index to choose for each topic\n\t\/\/ 4. cumulative probabilities\n\n\t\/\/ while there is anything interesting for user available & we haven't selected as many items as needed\n\tout := []ID{}\n\tfor len(cache) > 0 && len(out) < howMany {\n\t\t\/\/ select a random topic of interest\n\t\ttopic, i := __drawRandomTopicInterest(interests, cumulativeProbabilities)\n\n\t\t\/\/ select its best content (first index available)\n\t\tindexToSelect := cache[topic].CurrentIndex\n\n\t\t\/\/ current index can be ahead of the max index in some special cases\n\t\tif indexToSelect <= cache[topic].MaximumIndex {\n\t\t\tselectedID := topicContents[i][indexToSelect]\n\t\t\tif !__idsContainID(out, selectedID) {\n\t\t\t\tout = append(out, selectedID)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ advance current index in cache\n\t\tcache[topic].CurrentIndex++\n\n\t\t\/\/ if we overshot the maximum index for this topic, remove it\n\t\tif cache[topic].CurrentIndex > cache[topic].MaximumIndex {\n\t\t\t\/\/ remove from cache\n\t\t\tdelete(cache, topic)\n\t\t\t\/\/ remove from interest topics\n\t\t\tinterestTopics = append(interestTopics[:i], interestTopics[i+1:]...)\n\t\t\t\/\/ remove from topic contents\n\t\t\ttopicContents = append(topicContents[:i], topicContents[i+1:]...)\n\t\t\t\/\/ remove from interests\n\t\t\tinterests = append(interests[:i], interests[i+1:]...)\n\t\t\t\/\/ recalculate interests\n\t\t\tcumulativeProbabilities = __recalculateCumulativeProbabilities(interests)\n\t\t}\n\t}\n\n\treturn out\n}\n\nfunc __idsContainID(ids []ID, id ID) bool {\n\tfor i := 0; i < len(ids); i++ {\n\t\tif ids[i] == id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc __drawRandomTopicInterest(topicInterests TopicInterests, cumulativeProbabilities []float64) (Topic, int) {\n\trandomFloat := rand.Float64()\n\tfor i := 0; i < len(cumulativeProbabilities); i++ {\n\t\tif cumulativeProbabilities[i] >= randomFloat {\n\t\t\treturn topicInterests[i].Topic, i\n\t\t}\n\t}\n\t\/\/ this is guaranteed not to happen\n\treturn topicInterests[len(topicInterests)-1].Topic, len(topicInterests) - 1\n}\n\nfunc __recalculateCumulativeProbabilities(topicInterests TopicInterests) []float64 {\n\t\/\/ calculate sum of cumulative interests\n\tsum := float64(0)\n\tfor i := 0; i < len(topicInterests); i++ {\n\t\tsum += float64(topicInterests[i].CumulativeInterest)\n\t}\n\n\toutput := []float64{}\n\n\tfor i := 0; i < len(topicInterests); i++ {\n\t\toutput = append(output, float64(topicInterests[i].CumulativeInterest)\/sum)\n\t\tif i > 0 {\n\t\t\toutput[i] += output[i-1]\n\t\t}\n\t}\n\n\treturn output\n}\n\nfunc (net *Net) __selectOfTrending(ignore []ID, howMany int) []ID {\n\t\/\/ select top 10 trending topics\n\ttrendingTopics := net.trendStore.GetTopN(10)\n\n\t\/\/ nothing trending, bail early\n\tif len(trendingTopics) == 0 {\n\t\treturn []ID{}\n\t}\n\n\t\/\/ get content IDs for trending topics\n\tcontentIDs := net.index.GetForTopics(trendingTopics)\n\n\t\/\/ cache indices foreach contentID\n\tcache := map[Topic]*SelectionCacheInfo{}\n\t\/\/ filling in the cache\n\tfor i := 0; i < len(trendingTopics); i++ {\n\t\tcache[*trendingTopics[i]] = &SelectionCacheInfo{\n\t\t\tCurrentIndex: 0,\n\t\t\tMaximumIndex: len(contentIDs[i]) - 1,\n\t\t}\n\t}\n\n\tnextTrendInd := 0\n\tout := []ID{}\n\tfor len(cache) > 0 && len(out) < howMany {\n\t\ttrendingTopic := *trendingTopics[nextTrendInd]\n\n\t\t\/\/ select its best content (first index available)\n\t\tindexToSelect := cache[trendingTopic].CurrentIndex\n\n\t\t\/\/ current index can be ahead of the max index in some special cases\n\t\tif indexToSelect <= cache[trendingTopic].MaximumIndex {\n\t\t\tselectedID := contentIDs[nextTrendInd][indexToSelect]\n\n\t\t\tif !__idsContainID(out, selectedID) && !__idsContainID(ignore, selectedID) {\n\t\t\t\tout = append(out, selectedID)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ advance current index in cache\n\t\tcache[trendingTopic].CurrentIndex++\n\n\t\t\/\/ if we overshot the maximum index for this topic, remove it\n\t\tif cache[trendingTopic].CurrentIndex > cache[trendingTopic].MaximumIndex {\n\t\t\t\/\/ remove from cache\n\t\t\tdelete(cache, trendingTopic)\n\t\t\t\/\/ remove from trending topics\n\t\t\ttrendingTopics = append(trendingTopics[:nextTrendInd], trendingTopics[nextTrendInd+1:]...)\n\t\t\t\/\/ go back one position\n\t\t\tnextTrendInd--\n\t\t}\n\n\t\t\/\/ reset the counter\n\t\tnextTrendInd++\n\t\tif nextTrendInd == len(trendingTopics) {\n\t\t\tnextTrendInd = 0\n\t\t}\n\t}\n\n\treturn out\n}\n\nfunc (net *Net) __selectOfRemaining(ignore []ID, howMany int) []ID {\n\t\/\/ if we are asking for more content items then there are available in content store\n\tif howMany >= (net.contentStore.Count() - len(ignore)) {\n\t\tids := net.contentStore.GetAllContentIDs()\n\t\t\/\/ filter out ignored ones\n\t\tfor i := 0; i < len(ids); i++ {\n\t\t\tif __idsContainID(ignore, ids[i]) {\n\t\t\t\tids = append(ids[:i], ids[i+1:]...)\n\t\t\t\ti--\n\t\t\t}\n\t\t}\n\t\treturn ids\n\n\t}\n\n\t\/\/ otherwise, draw random elements until howMany is satisifed. ignore duplicates of course.\n\tout := []ID{}\n\n\tfor len(out) < howMany {\n\t\trandomID := net.contentStore.GetAnyContentID()\n\t\tif !__idsContainID(out, randomID) && !__idsContainID(ignore, randomID) {\n\t\t\tout = append(out, randomID)\n\t\t}\n\t}\n\n\treturn out\n\n}\n\nfunc (net *Net) Describe() *NetDescription {\n\treturn &NetDescription{\n\t\tContents: net.contentStore.Describe(),\n\t\tIndex:    net.index.Describe(),\n\t\tProfiles: net.profileStore.Describe(),\n\t\tTrends:   net.trendStore.Describe(),\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"net\/http\"\n\t\"path\"\n\t\"sync\"\n\n\t\"github.com\/eirka\/eirka-libs\/config\"\n\t\"github.com\/eirka\/eirka-libs\/db\"\n\te \"github.com\/eirka\/eirka-libs\/errors\"\n)\n\nvar (\n\tsitemap = make(map[string]*SiteData)\n\tmu      = new(sync.RWMutex)\n)\n\n\/\/ SiteData holds imageboard settings\ntype SiteData struct {\n\tIb          uint\n\tApi         string\n\tImg         string\n\tTitle       string\n\tDesc        string\n\tNsfw        bool\n\tStyle       string\n\tLogo        string\n\tBase        string\n\tImageboards []Imageboard\n}\n\ntype Imageboard struct {\n\tTitle   string\n\tAddress string\n}\n\n\/\/ Details gets the imageboard settings from the request for the page handler variables\nfunc Details() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\n\t\tvar host, base string\n\n\t\thost = c.Request.Host\n\n\t\t\/\/ figure out our path and host\n\t\tif path.Dir(host) == \".\" {\n\t\t\t\/\/ we're on the base in this case\n\t\t\thost = path.Base(host)\n\t\t} else {\n\t\t\thost = path.Dir(host)\n\t\t\tbase = fmt.Sprintf(\"%s\/\", path.Base(host))\n\t\t}\n\n\t\tmu.RLock()\n\t\t\/\/ check the sitemap to see if its cached\n\t\tsite := sitemap[host]\n\t\tmu.RUnlock()\n\n\t\t\/\/ if not query the database\n\t\tif site == nil {\n\n\t\t\tsitedata := &SiteData{}\n\n\t\t\t\/\/ set the base for angularjs\n\t\t\tsitedata.Base = base\n\n\t\t\t\/\/ Get Database handle\n\t\t\tdbase, err := db.GetDb()\n\t\t\tif err != nil {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrInternalError))\n\t\t\t\tc.Error(err).SetMeta(\"Details.GetDb\")\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ get the info about the imageboard\n\t\t\terr = dbase.QueryRow(`SELECT ib_id,ib_title,ib_description,ib_nsfw,ib_api,ib_img,ib_style,ib_logo FROM imageboards WHERE ib_domain = ?`, host).Scan(&sitedata.Ib, &sitedata.Title, &sitedata.Desc, &sitedata.Nsfw, &sitedata.Api, &sitedata.Img, &sitedata.Style, &sitedata.Logo)\n\t\t\tif err == sql.ErrNoRows {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrNotFound))\n\t\t\t\tc.Error(err).SetMeta(\"Details.QueryRow\")\n\t\t\t\treturn\n\t\t\t} else if err != nil {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrInternalError))\n\t\t\t\tc.Error(err).SetMeta(\"Details.QueryRow\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ collect the links to the other imageboards for nav menu\n\t\t\trows, err := dbase.Query(`SELECT ib_title,ib_domain FROM imageboards WHERE ib_id != ?`, sitedata.Ib)\n\t\t\tif err != nil {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrInternalError))\n\t\t\t\tc.Error(err).SetMeta(\"Details.Query\")\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer rows.Close()\n\n\t\t\tfor rows.Next() {\n\n\t\t\t\tib := Imageboard{}\n\n\t\t\t\terr := rows.Scan(&ib.Title, &ib.Address)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tsitedata.Imageboards = append(sitedata.Imageboards, ib)\n\t\t\t}\n\t\t\tif rows.Err() != nil {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrInternalError))\n\t\t\t\tc.Error(err).SetMeta(\"Details.Query\")\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmu.Lock()\n\t\t\tsitemap[host] = sitedata\n\t\t\tmu.Unlock()\n\n\t\t}\n\n\t\tc.Next()\n\n\t}\n\n}\n\n\/\/ IndexController generates pages for angularjs frontend\nfunc IndexController(c *gin.Context) {\n\n\t\/\/ Get parameters from csrf middleware\n\tcsrf_token := c.MustGet(\"csrf_token\").(string)\n\n\thost := c.Request.Host\n\n\tmu.RLock()\n\tsite := sitemap[host]\n\tmu.RUnlock()\n\n\tc.HTML(http.StatusOK, \"index\", gin.H{\n\t\t\"primjs\":      config.Settings.Prim.Js,\n\t\t\"primcss\":     config.Settings.Prim.Css,\n\t\t\"ib\":          site.Ib,\n\t\t\"base\":        site.Base,\n\t\t\"apisrv\":      site.Api,\n\t\t\"imgsrv\":      site.Img,\n\t\t\"title\":       site.Title,\n\t\t\"desc\":        site.Desc,\n\t\t\"nsfw\":        site.Nsfw,\n\t\t\"style\":       site.Style,\n\t\t\"logo\":        site.Logo,\n\t\t\"imageboards\": site.Imageboards,\n\t\t\"csrf\":        csrf_token,\n\t})\n\n\treturn\n\n}\n\n\/\/ ErrorController generates pages and a 404 response\nfunc ErrorController(c *gin.Context) {\n\n\t\/\/ Get parameters from csrf middleware\n\tcsrf_token := c.MustGet(\"csrf_token\").(string)\n\n\thost := c.Request.Host\n\n\tmu.RLock()\n\tsite := sitemap[host]\n\tmu.RUnlock()\n\n\tc.HTML(http.StatusNotFound, \"index\", gin.H{\n\t\t\"primjs\":      config.Settings.Prim.Js,\n\t\t\"primcss\":     config.Settings.Prim.Css,\n\t\t\"ib\":          site.Ib,\n\t\t\"base\":        site.Base,\n\t\t\"apisrv\":      site.Api,\n\t\t\"imgsrv\":      site.Img,\n\t\t\"title\":       site.Title,\n\t\t\"desc\":        site.Desc,\n\t\t\"nsfw\":        site.Nsfw,\n\t\t\"style\":       site.Style,\n\t\t\"logo\":        site.Logo,\n\t\t\"imageboards\": site.Imageboards,\n\t\t\"csrf\":        csrf_token,\n\t})\n\n\treturn\n\n}\n<commit_msg>add subdirectory support<commit_after>package main\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"net\/http\"\n\t\"path\"\n\t\"sync\"\n\n\t\"github.com\/eirka\/eirka-libs\/config\"\n\t\"github.com\/eirka\/eirka-libs\/db\"\n\te \"github.com\/eirka\/eirka-libs\/errors\"\n)\n\nvar (\n\tsitemap = make(map[string]*SiteData)\n\tmu      = new(sync.RWMutex)\n)\n\n\/\/ SiteData holds imageboard settings\ntype SiteData struct {\n\tIb          uint\n\tApi         string\n\tImg         string\n\tTitle       string\n\tDesc        string\n\tNsfw        bool\n\tStyle       string\n\tLogo        string\n\tBase        string\n\tImageboards []Imageboard\n}\n\ntype Imageboard struct {\n\tTitle   string\n\tAddress string\n}\n\n\/\/ Details gets the imageboard settings from the request for the page handler variables\nfunc Details() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\n\t\tvar host, base string\n\n\t\thost = c.Request.Host\n\n\t\t\/\/ figure out our path and host\n\t\tif path.Dir(host) == \".\" {\n\t\t\t\/\/ we're on the base in this case\n\t\t\thost = path.Base(host)\n\t\t} else {\n\t\t\thost = path.Dir(host)\n\t\t\tbase = fmt.Sprintf(\"%s\/\", path.Base(host))\n\t\t}\n\n\t\tfmt.Println(host, base)\n\n\t\tmu.RLock()\n\t\t\/\/ check the sitemap to see if its cached\n\t\tsite := sitemap[host]\n\t\tmu.RUnlock()\n\n\t\t\/\/ if not query the database\n\t\tif site == nil {\n\n\t\t\tsitedata := &SiteData{}\n\n\t\t\t\/\/ set the base for angularjs\n\t\t\tsitedata.Base = base\n\n\t\t\t\/\/ Get Database handle\n\t\t\tdbase, err := db.GetDb()\n\t\t\tif err != nil {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrInternalError))\n\t\t\t\tc.Error(err).SetMeta(\"Details.GetDb\")\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ get the info about the imageboard\n\t\t\terr = dbase.QueryRow(`SELECT ib_id,ib_title,ib_description,ib_nsfw,ib_api,ib_img,ib_style,ib_logo FROM imageboards WHERE ib_domain = ?`, host).Scan(&sitedata.Ib, &sitedata.Title, &sitedata.Desc, &sitedata.Nsfw, &sitedata.Api, &sitedata.Img, &sitedata.Style, &sitedata.Logo)\n\t\t\tif err == sql.ErrNoRows {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrNotFound))\n\t\t\t\tc.Error(err).SetMeta(\"Details.QueryRow\")\n\t\t\t\treturn\n\t\t\t} else if err != nil {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrInternalError))\n\t\t\t\tc.Error(err).SetMeta(\"Details.QueryRow\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ collect the links to the other imageboards for nav menu\n\t\t\trows, err := dbase.Query(`SELECT ib_title,ib_domain FROM imageboards WHERE ib_id != ?`, sitedata.Ib)\n\t\t\tif err != nil {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrInternalError))\n\t\t\t\tc.Error(err).SetMeta(\"Details.Query\")\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer rows.Close()\n\n\t\t\tfor rows.Next() {\n\n\t\t\t\tib := Imageboard{}\n\n\t\t\t\terr := rows.Scan(&ib.Title, &ib.Address)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tsitedata.Imageboards = append(sitedata.Imageboards, ib)\n\t\t\t}\n\t\t\tif rows.Err() != nil {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrInternalError))\n\t\t\t\tc.Error(err).SetMeta(\"Details.Query\")\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmu.Lock()\n\t\t\tsitemap[host] = sitedata\n\t\t\tmu.Unlock()\n\n\t\t}\n\n\t\tc.Next()\n\n\t}\n\n}\n\n\/\/ IndexController generates pages for angularjs frontend\nfunc IndexController(c *gin.Context) {\n\n\t\/\/ Get parameters from csrf middleware\n\tcsrf_token := c.MustGet(\"csrf_token\").(string)\n\n\thost := c.Request.Host\n\n\tmu.RLock()\n\tsite := sitemap[host]\n\tmu.RUnlock()\n\n\tc.HTML(http.StatusOK, \"index\", gin.H{\n\t\t\"primjs\":      config.Settings.Prim.Js,\n\t\t\"primcss\":     config.Settings.Prim.Css,\n\t\t\"ib\":          site.Ib,\n\t\t\"base\":        site.Base,\n\t\t\"apisrv\":      site.Api,\n\t\t\"imgsrv\":      site.Img,\n\t\t\"title\":       site.Title,\n\t\t\"desc\":        site.Desc,\n\t\t\"nsfw\":        site.Nsfw,\n\t\t\"style\":       site.Style,\n\t\t\"logo\":        site.Logo,\n\t\t\"imageboards\": site.Imageboards,\n\t\t\"csrf\":        csrf_token,\n\t})\n\n\treturn\n\n}\n\n\/\/ ErrorController generates pages and a 404 response\nfunc ErrorController(c *gin.Context) {\n\n\t\/\/ Get parameters from csrf middleware\n\tcsrf_token := c.MustGet(\"csrf_token\").(string)\n\n\thost := c.Request.Host\n\n\tmu.RLock()\n\tsite := sitemap[host]\n\tmu.RUnlock()\n\n\tc.HTML(http.StatusNotFound, \"index\", gin.H{\n\t\t\"primjs\":      config.Settings.Prim.Js,\n\t\t\"primcss\":     config.Settings.Prim.Css,\n\t\t\"ib\":          site.Ib,\n\t\t\"base\":        site.Base,\n\t\t\"apisrv\":      site.Api,\n\t\t\"imgsrv\":      site.Img,\n\t\t\"title\":       site.Title,\n\t\t\"desc\":        site.Desc,\n\t\t\"nsfw\":        site.Nsfw,\n\t\t\"style\":       site.Style,\n\t\t\"logo\":        site.Logo,\n\t\t\"imageboards\": site.Imageboards,\n\t\t\"csrf\":        csrf_token,\n\t})\n\n\treturn\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/gin-gonic\/gin\"\n\t\"net\/http\"\n\t\"sync\"\n\n\t\"github.com\/eirka\/eirka-libs\/config\"\n\t\"github.com\/eirka\/eirka-libs\/db\"\n)\n\nvar (\n\tsitemap = make(map[string]*SiteData)\n\tmu      = new(sync.RWMutex)\n)\n\ntype SiteData struct {\n\tIb          uint\n\tApi         string\n\tImg         string\n\tTitle       string\n\tDesc        string\n\tNsfw        bool\n\tStyle       string\n\tLogo        string\n\tImageboards []Imageboard\n}\n\ntype Imageboard struct {\n\tTitle   string\n\tAddress string\n}\n\n\/\/ gets the details from the request for the page handler variables\nfunc Details() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\n\t\thost := c.Request.Host\n\n\t\tmu.RLock()\n\t\tsite := sitemap[host]\n\t\tmu.RUnlock()\n\n\t\tif site == nil {\n\n\t\t\tsitedata := &SiteData{}\n\n\t\t\t\/\/ Get Database handle\n\t\t\tdbase, err := db.GetDb()\n\t\t\tif err != nil {\n\t\t\t\tc.Error(err)\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = dbase.QueryRow(`SELECT ib_id,ib_title,ib_description,ib_nsfw,ib_api,ib_img,ib_style,ib_logo FROM imageboards WHERE ib_domain = ?`, host).Scan(&sitedata.Ib, &sitedata.Title, &sitedata.Desc, &sitedata.Nsfw, &sitedata.Api, &sitedata.Img, &sitedata.Style, &sitedata.Logo)\n\t\t\tif err != nil {\n\t\t\t\tc.Error(err)\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\trows, err := dbase.Query(`SELECT ib_title,ib_domain FROM imageboards WHERE ib_id != ?`, sitedata.Ib)\n\t\t\tif err != nil {\n\t\t\t\tc.Error(err)\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer rows.Close()\n\n\t\t\tfor rows.Next() {\n\n\t\t\t\tib := Imageboard{}\n\n\t\t\t\terr := rows.Scan(&ib.Title, &ib.Address)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tsitedata.Imageboards = append(sitedata.Imageboards, ib)\n\t\t\t}\n\t\t\terr = rows.Err()\n\t\t\tif err != nil {\n\t\t\t\tc.Error(err)\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmu.Lock()\n\t\t\tsitemap[host] = sitedata\n\t\t\tmu.Unlock()\n\n\t\t}\n\n\t\tc.Next()\n\n\t}\n}\n\n\/\/ Handles index page generation\nfunc IndexController(c *gin.Context) {\n\n\t\/\/ Get parameters from validate middleware\n\tcsrf_token := c.MustGet(\"csrf_token\").(string)\n\n\thost := c.Request.Host\n\n\tmu.RLock()\n\tsite := sitemap[host]\n\tmu.RUnlock()\n\n\tc.HTML(http.StatusOK, \"index\", gin.H{\n\t\t\"primjs\":      config.Settings.Prim.Js,\n\t\t\"primcss\":     config.Settings.Prim.Css,\n\t\t\"ib\":          site.Ib,\n\t\t\"apisrv\":      site.Api,\n\t\t\"imgsrv\":      site.Img,\n\t\t\"title\":       site.Title,\n\t\t\"desc\":        site.Desc,\n\t\t\"nsfw\":        site.Nsfw,\n\t\t\"style\":       site.Style,\n\t\t\"logo\":        site.Logo,\n\t\t\"imageboards\": site.Imageboards,\n\t\t\"csrf\":        csrf_token,\n\t})\n\n\treturn\n\n}\n\n\/\/ Handles error messages for wrong routes\nfunc ErrorController(c *gin.Context) {\n\n\tc.String(http.StatusNotFound, \"Not Found\")\n\n\treturn\n\n}\n<commit_msg>add error meta data<commit_after>package main\n\nimport (\n\t\"github.com\/gin-gonic\/gin\"\n\t\"net\/http\"\n\t\"sync\"\n\n\t\"github.com\/eirka\/eirka-libs\/config\"\n\t\"github.com\/eirka\/eirka-libs\/db\"\n\te \"github.com\/eirka\/eirka-libs\/errors\"\n)\n\nvar (\n\tsitemap = make(map[string]*SiteData)\n\tmu      = new(sync.RWMutex)\n)\n\n\/\/ SiteData holds imageboard settings\ntype SiteData struct {\n\tIb          uint\n\tApi         string\n\tImg         string\n\tTitle       string\n\tDesc        string\n\tNsfw        bool\n\tStyle       string\n\tLogo        string\n\tImageboards []Imageboard\n}\n\ntype Imageboard struct {\n\tTitle   string\n\tAddress string\n}\n\n\/\/ Details gets the imageboard settings from the request for the page handler variables\nfunc Details() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\n\t\thost := c.Request.Host\n\n\t\tmu.RLock()\n\t\tsite := sitemap[host]\n\t\tmu.RUnlock()\n\n\t\tif site == nil {\n\n\t\t\tsitedata := &SiteData{}\n\n\t\t\t\/\/ Get Database handle\n\t\t\tdbase, err := db.GetDb()\n\t\t\tif err != nil {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrInternalError))\n\t\t\t\tc.Error(err).SetMeta(\"Details.GetDb\")\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = dbase.QueryRow(`SELECT ib_id,ib_title,ib_description,ib_nsfw,ib_api,ib_img,ib_style,ib_logo FROM imageboards WHERE ib_domain = ?`, host).Scan(&sitedata.Ib, &sitedata.Title, &sitedata.Desc, &sitedata.Nsfw, &sitedata.Api, &sitedata.Img, &sitedata.Style, &sitedata.Logo)\n\t\t\tif err != nil {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrInternalError))\n\t\t\t\tc.Error(err).SetMeta(\"Details.QueryRow\")\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\trows, err := dbase.Query(`SELECT ib_title,ib_domain FROM imageboards WHERE ib_id != ?`, sitedata.Ib)\n\t\t\tif err != nil {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrInternalError))\n\t\t\t\tc.Error(err).SetMeta(\"Details.Query\")\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer rows.Close()\n\n\t\t\tfor rows.Next() {\n\n\t\t\t\tib := Imageboard{}\n\n\t\t\t\terr := rows.Scan(&ib.Title, &ib.Address)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tsitedata.Imageboards = append(sitedata.Imageboards, ib)\n\t\t\t}\n\t\t\terr = rows.Err()\n\t\t\tif err != nil {\n\t\t\t\tc.JSON(e.ErrorMessage(e.ErrInternalError))\n\t\t\t\tc.Error(err).SetMeta(\"Details.Query\")\n\t\t\t\tc.Abort()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tmu.Lock()\n\t\t\tsitemap[host] = sitedata\n\t\t\tmu.Unlock()\n\n\t\t}\n\n\t\tc.Next()\n\n\t}\n\n}\n\n\/\/ IndexController generates pages for angularjs frontend\nfunc IndexController(c *gin.Context) {\n\n\t\/\/ Get parameters from csrf middleware\n\tcsrf_token := c.MustGet(\"csrf_token\").(string)\n\n\thost := c.Request.Host\n\n\tmu.RLock()\n\tsite := sitemap[host]\n\tmu.RUnlock()\n\n\tc.HTML(http.StatusOK, \"index\", gin.H{\n\t\t\"primjs\":      config.Settings.Prim.Js,\n\t\t\"primcss\":     config.Settings.Prim.Css,\n\t\t\"ib\":          site.Ib,\n\t\t\"apisrv\":      site.Api,\n\t\t\"imgsrv\":      site.Img,\n\t\t\"title\":       site.Title,\n\t\t\"desc\":        site.Desc,\n\t\t\"nsfw\":        site.Nsfw,\n\t\t\"style\":       site.Style,\n\t\t\"logo\":        site.Logo,\n\t\t\"imageboards\": site.Imageboards,\n\t\t\"csrf\":        csrf_token,\n\t})\n\n\treturn\n\n}\n\n\/\/ ErrorController handles error messages for wrong routes\nfunc ErrorController(c *gin.Context) {\n\n\tc.String(http.StatusNotFound, \"Not Found\")\n\n\treturn\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 The Convention Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/\n\/\/ Every file starts with a copyright. Gophers tend to use BSD-like licenses.\n\/\/ \"The PackageName Authors\" in copyrights along with maintained AUTHORS,\n\/\/ CONTRIBUTORS, and LICENSE files are idiomatic. Comments are proper English\n\/\/ sentences, always started with \"\/\/\", and bound to 80 char line length. Code\n\/\/ itself is not bound any line length, but long lines are often a code smell.\n\n\/\/ Package conventions is an example Go package that is loaded with\n\/\/ documentation specifically targetting new developers that have done the Go\n\/\/ Tour and have read the documentation on the \"go\" binary, but want to know\n\/\/ more about writing packages and software.\n\/\/\n\/\/ The documentation for an entire package written here; only one of the files\n\/\/ in a package should have it. Comments are always on the line above the thing\n\/\/ they are documenting. Package declarations and any exports require comments\n\/\/ that should be in the form of \"Package pkgname ...\" and \"ExportName ...\"\n\/\/ respectively. When Go is properly commented in this way, automatic docs\n\/\/ can be generated via the \"godoc\" binary or via godoc.org. For example:\n\/\/ http:\/\/godoc.org\/github.com\/jzelinskie\/conventions is where you can see the\n\/\/ docs for this package, although this package was created specifically to\n\/\/ have its source read directly.\npackage conventions\n\n\/\/ The import and const keywords should always be expanded into their multi-line\n\/\/ form.\n\/\/\n\/\/ One $GOPATH contains all of the packages on the internet. Whenever something\n\/\/ is exported, the author must maintain stability of that package's API. For\n\/\/ git repos, \"go get\" will look for a \"go1\" tag or fallback to the master\n\/\/ branch. If an author is a bad citizen, they may break their API and those\n\/\/ depending on it will have two options: update their code or fork the package.\n\/\/ Forking comes at a cost: it changes the name of all of the imports,\n\/\/ essentially creating a brand new package.\nimport (\n\t\/\/ Imports from the Go standard libraries are grouped together at the top.\n\t\"errors\"\n\t\"fmt\"\n\n\t\/\/ Third party imports are placed below the standard libraries. Setting up\n\t\/\/ text editor hooks to run gofmt and lint on save is a good idea.\n\t_ \"github.com\/golang\/lint\"\n\n\t\/\/ Local imports are placed below the third party libraries. Importing a\n\t\/\/ package as _ is useful if you require some side-effect of init() from the\n\t\/\/ package.\n\t_ \"github.com\/jzelinskie\/conventions\/subpkg\"\n)\n\n\/\/ Constants always follow the imports.\nconst (\n\tenums = iota\n\tare\n\tpretty\n\tcool\n)\n\n\/\/ Exported variables are usually in multi-line form, however when defining\n\/\/ huge literals such as the constants used in cryptographic hashing algorithms,\n\/\/ it is fine to have repeated var statements.\nvar (\n\t\/\/ ErrStupidMistake is an example of an exported error type.\n\tErrStupidMistake = errors.New(\"stupid mistakes are the story of my life\")\n)\n\n\/\/ Example is an example of how to define new types.\n\/\/\n\/\/ Fields are one-per-line and grouped together however you think is most\n\/\/ logical. Don't worry too much about writing struct tags for every encoding\n\/\/ under the sun. Someone can easily create a wrapper type that implements\n\/\/ the encoding's marshaler interface (i.e. json.Marshaler).\ntype Example struct {\n\tID          int\n\tName        string\n\tDescription string\n\n\tirrelevant string\n}\n\n\/\/ NewExample is an example constructor for the Example type.\n\/\/\n\/\/ Constructors are always the first thing to follow the type declaration.\n\/\/ Constructors always begin with \"New\" and can simply be called \"New\" if the\n\/\/ name of the type being returned is the same as the package (i.e.\n\/\/ config.New()). Returning a reference literal is better than allocating with\n\/\/ the new keyword. Always have a trailing comma on the last item in anything\n\/\/ multi-line; this is done to reduce diff sizes in version control systems.\nfunc NewExample(id int, name, description string) *Example {\n\treturn &Example{\n\t\tID:          id,\n\t\tName:        name,\n\t\tDescription: description,\n\t}\n}\n\n\/\/ Method is an example method for the Example type.\n\/\/\n\/\/ Methods are always what come after constructors. Godoc will order them\n\/\/ alphabetically, but it is often more useful to order them logically.\n\/\/ For most receivers, prefer pointers over values.  Exceptions to this\n\/\/ are small arrays, small structs (or structs that are natural value\n\/\/ types), maps, functions, and channels.\nfunc (e Example) Method() (bool, error) {\n\t\/\/ The use of := for capturing the result of function calls and expressions\n\t\/\/ is preferrable to the use of var.\n\tnameLength := len(e.Name)\n\tresult := nameLength < 10\n\n\t\/\/ Keep lines between logical groups of statements, including the final\n\t\/\/ return.\n\treturn result, nil\n}\n\n\/\/ Second to last in a file is an init func. This func enables you to run code\n\/\/ at package import time.\nfunc init() {\n}\n\n\/\/ Last in a file should be a main func. This func should only be present in a\n\/\/ package named main to generate a binary file.\nfunc main() {\n\t\/\/ Break long function calls into its multi-line form. Functions with lots of\n\t\/\/ parameters are often a code smell.\n\texample := NewExample(\n\t\t1,\n\t\t\"conventions\",\n\t\t\"this is getting quite meta\",\n\t)\n\n\t\/\/ If there is no desire to expose any variables outside of the scope of an\n\t\/\/ if-statement, this two-claused form is preferable.\n\tif _, err := example.Method(); err != nil {\n\t\t\/\/ Panics are used only in situations that inform the programmer that they\n\t\t\/\/ are doing something wrong. They should not be used like exceptions --\n\t\t\/\/ error is a builtin type for a reason.\n\t\tpanic(\"conventions: example method should always return a nil error.\")\n\t}\n\n\t\/\/ When a zero-value is desired, use the var keyword. Avoid using := inside\n\t\/\/ if statements as variables can accidently become shadowed.\n\tvar multiplier int\n\tif example.ID > 10 {\n\t\tmultiplier = 10\n\t} else {\n\t\tmultiplier = example.ID\n\t}\n\tfmt.Printf(\"Multiplier: %v\", multiplier)\n}\n<commit_msg>Add ShortMethod<commit_after>\/\/ Copyright 2014 The Convention Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/\n\/\/ Every file starts with a copyright. Gophers tend to use BSD-like licenses.\n\/\/ \"The PackageName Authors\" in copyrights along with maintained AUTHORS,\n\/\/ CONTRIBUTORS, and LICENSE files are idiomatic. Comments are proper English\n\/\/ sentences, always started with \"\/\/\", and bound to 80 char line length. Code\n\/\/ itself is not bound any line length, but long lines are often a code smell.\n\n\/\/ Package conventions is an example Go package that is loaded with\n\/\/ documentation specifically targetting new developers that have done the Go\n\/\/ Tour and have read the documentation on the \"go\" binary, but want to know\n\/\/ more about writing packages and software.\n\/\/\n\/\/ The documentation for an entire package written here; only one of the files\n\/\/ in a package should have it. Comments are always on the line above the thing\n\/\/ they are documenting. Package declarations and any exports require comments\n\/\/ that should be in the form of \"Package pkgname ...\" and \"ExportName ...\"\n\/\/ respectively. When Go is properly commented in this way, automatic docs\n\/\/ can be generated via the \"godoc\" binary or via godoc.org. For example:\n\/\/ http:\/\/godoc.org\/github.com\/jzelinskie\/conventions is where you can see the\n\/\/ docs for this package, although this package was created specifically to\n\/\/ have its source read directly.\npackage conventions\n\n\/\/ The import and const keywords should always be expanded into their multi-line\n\/\/ form.\n\/\/\n\/\/ One $GOPATH contains all of the packages on the internet. Whenever something\n\/\/ is exported, the author must maintain stability of that package's API. For\n\/\/ git repos, \"go get\" will look for a \"go1\" tag or fallback to the master\n\/\/ branch. If an author is a bad citizen, they may break their API and those\n\/\/ depending on it will have two options: update their code or fork the package.\n\/\/ Forking comes at a cost: it changes the name of all of the imports,\n\/\/ essentially creating a brand new package.\nimport (\n\t\/\/ Imports from the Go standard libraries are grouped together at the top.\n\t\"errors\"\n\t\"fmt\"\n\n\t\/\/ Third party imports are placed below the standard libraries. Setting up\n\t\/\/ text editor hooks to run gofmt and lint on save is a good idea.\n\t_ \"github.com\/golang\/lint\"\n\n\t\/\/ Local imports are placed below the third party libraries. Importing a\n\t\/\/ package as _ is useful if you require some side-effect of init() from the\n\t\/\/ package.\n\t_ \"github.com\/jzelinskie\/conventions\/subpkg\"\n)\n\n\/\/ Constants always follow the imports.\nconst (\n\tenums = iota\n\tare\n\tpretty\n\tcool\n)\n\n\/\/ Exported variables are usually in multi-line form, however when defining\n\/\/ huge literals such as the constants used in cryptographic hashing algorithms,\n\/\/ it is fine to have repeated var statements.\nvar (\n\t\/\/ ErrStupidMistake is an example of an exported error type.\n\tErrStupidMistake = errors.New(\"stupid mistakes are the story of my life\")\n)\n\n\/\/ Example is an example of how to define new types.\n\/\/\n\/\/ Fields are one-per-line and grouped together however you think is most\n\/\/ logical. Don't worry too much about writing struct tags for every encoding\n\/\/ under the sun. Someone can easily create a wrapper type that implements\n\/\/ the encoding's marshaler interface (i.e. json.Marshaler).\ntype Example struct {\n\tID          int\n\tName        string\n\tDescription string\n\n\tirrelevant string\n}\n\n\/\/ NewExample is an example constructor for the Example type.\n\/\/\n\/\/ Constructors are always the first thing to follow the type declaration.\n\/\/ Constructors always begin with \"New\" and can simply be called \"New\" if the\n\/\/ name of the type being returned is the same as the package (i.e.\n\/\/ config.New()). Returning a reference literal is better than allocating with\n\/\/ the new keyword. Always have a trailing comma on the last item in anything\n\/\/ multi-line; this is done to reduce diff sizes in version control systems.\nfunc NewExample(id int, name, description string) *Example {\n\treturn &Example{\n\t\tID:          id,\n\t\tName:        name,\n\t\tDescription: description,\n\t}\n}\n\n\/\/ Method is an example method for the Example type.\n\/\/\n\/\/ Methods are always what come after constructors. Godoc will order them\n\/\/ alphabetically, but it is often more useful to order them logically.\n\/\/ For most receivers, prefer pointers over values.  Exceptions to this\n\/\/ are small arrays, small structs (or structs that are natural value\n\/\/ types), maps, functions, and channels.\nfunc (e Example) Method() (bool, error) {\n\t\/\/ The use of := for capturing the result of function calls and expressions\n\t\/\/ is preferrable to the use of var.\n\tnameLength := len(e.Name)\n\tresult := nameLength < 10\n\n\t\/\/ Keep lines between logical groups of statements, including the final\n\t\/\/ return.\n\treturn result, nil\n}\n\n\/\/ ShortMethod is an example of a method short enough to be kept on one line.\n\/\/ The gofmt tool will not automatically put methods that are this short on one\n\/\/ line, but it will not break them down into multiple lines either.\nfunc (e Example) ShortMethod() int { return 0 }\n\n\/\/ Second to last in a file is an init func. This func enables you to run code\n\/\/ at package import time.\nfunc init() {\n}\n\n\/\/ Last in a file should be a main func. This func should only be present in a\n\/\/ package named main to generate a binary file.\nfunc main() {\n\t\/\/ Break long function calls into its multi-line form. Functions with lots of\n\t\/\/ parameters are often a code smell.\n\texample := NewExample(\n\t\t1,\n\t\t\"conventions\",\n\t\t\"this is getting quite meta\",\n\t)\n\n\t\/\/ If there is no desire to expose any variables outside of the scope of an\n\t\/\/ if-statement, this two-claused form is preferable.\n\tif _, err := example.Method(); err != nil {\n\t\t\/\/ Panics are used only in situations that inform the programmer that they\n\t\t\/\/ are doing something wrong. They should not be used like exceptions --\n\t\t\/\/ error is a builtin type for a reason.\n\t\tpanic(\"conventions: example method should always return a nil error.\")\n\t}\n\n\t\/\/ When a zero-value is desired, use the var keyword. Avoid using := inside\n\t\/\/ if statements as variables can accidently become shadowed.\n\tvar multiplier int\n\tif example.ID > 10 {\n\t\tmultiplier = 10\n\t} else {\n\t\tmultiplier = example.ID\n\t}\n\tfmt.Printf(\"Multiplier: %v\", multiplier)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/rpc\"\n\t\"pault.ag\/go\/service\"\n\t\"strings\"\n)\n\n\/* *\/\n\nfunc BeACoordinator(cert, key, ca, host string, port int) {\n\tlog.Printf(\"Bringing TCP server online!\\n\")\n\tl, err := service.ListenFromKeys(\n\t\tfmt.Sprintf(\"%s:%d\", host, port),\n\t\tcert, key, ca,\n\t)\n\tif err != nil {\n\t\tlog.Fatalf(\"Server Ouchie! %s\", err)\n\t}\n\tcoordinator := MinionCoordinator{}\n\tlog.Printf(\"Great, waiting for Minions, and telling them what to do!\\n\")\n\tservice.Handle(l, &coordinator)\n}\n\n\/**\/\n\ntype MinionCoordinator struct{ service.Coordinator }\n\nfunc (m *MinionCoordinator) Handle(client *rpc.Client, conn *service.Conn) {\n\tminion := RemoteMinion{client}\n\n\tlog.Printf(\"Got a connection from %s\\n\", conn.CommonNames[0])\n\n\tarches, err := minion.Arches()\n\tif err != nil {\n\t\tlog.Fatalf(\"Ouch: %s\\n\", err)\n\t}\n\n\tlog.Printf(\" -> They can do %s\", strings.Join(arches, \", \"))\n\n\tftbfs, err := minion.Build(\n\t\t[]Archive{Archive{}},\n\t\tChrootTarget{Chroot: \"unstable\", Suite: \"unstable\"},\n\t\t\"amd64\", \"pool\/f\/fbautostart_fnord.dsc\",\n\t)\n\tlog.Printf(\"Heard back: %s %s\\n\", ftbfs, err)\n}\n<commit_msg>shuffle order<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/rpc\"\n\t\"pault.ag\/go\/service\"\n\t\"strings\"\n)\n\n\/* *\/\n\ntype MinionCoordinator struct{ service.Coordinator }\n\nfunc (m *MinionCoordinator) Handle(client *rpc.Client, conn *service.Conn) {\n\tminion := RemoteMinion{client}\n\n\tlog.Printf(\"Got a connection from %s\\n\", conn.CommonNames[0])\n\n\tarches, err := minion.Arches()\n\tif err != nil {\n\t\tlog.Fatalf(\"Ouch: %s\\n\", err)\n\t}\n\n\tlog.Printf(\" -> They can do %s\", strings.Join(arches, \", \"))\n\n\tftbfs, err := minion.Build(\n\t\t[]Archive{Archive{}},\n\t\tChrootTarget{Chroot: \"unstable\", Suite: \"unstable\"},\n\t\t\"amd64\", \"pool\/f\/fbautostart_fnord.dsc\",\n\t)\n\tlog.Printf(\"Heard back: %s %s\\n\", ftbfs, err)\n}\n\n\/* *\/\n\nfunc BeACoordinator(cert, key, ca, host string, port int) {\n\tlog.Printf(\"Bringing TCP server online!\\n\")\n\tl, err := service.ListenFromKeys(\n\t\tfmt.Sprintf(\"%s:%d\", host, port),\n\t\tcert, key, ca,\n\t)\n\tif err != nil {\n\t\tlog.Fatalf(\"Server Ouchie! %s\", err)\n\t}\n\tcoordinator := MinionCoordinator{}\n\tlog.Printf(\"Great, waiting for Minions, and telling them what to do!\\n\")\n\tservice.Handle(l, &coordinator)\n}\n\n\/**\/\n<|endoftext|>"}
{"text":"<commit_before>package ddtxn\n\nimport (\n\t\"container\/heap\"\n\t\"ddtxn\/dlog\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\nconst (\n\tBUMP_EPOCH_MS = 80\n\tEPOCH_INCR    = 1 << 32\n\tTXID_MASK     = 0x00000000ffffffff\n\tCLEAR_TID     = 0xffffffff00000000\n)\n\nvar PhaseLength = flag.Int(\"phase\", 80, \"Phase length in milliseconds, default 80\")\n\ntype Coordinator struct {\n\tn        int\n\tWorkers  []*Worker\n\tepochTID uint64 \/\/ Global TID, atomically incremented and read\n\n\t\/\/ Notify workers\n\twepoch []chan TID\n\twsafe  []chan TID\n\twgo    []chan TID\n\twdone  []chan TID\n\n\tCoordinate            bool\n\tPotentialPhaseChanges int64\n\tDone                  chan chan bool\n\tAccelerate            chan bool\n\ttrigger               int32\n\tto_remove             map[Key]bool\n\n\tTotalCoordTime time.Duration\n\tGoTime         time.Duration\n\tReadTime       time.Duration\n\tMergeTime      time.Duration\n}\n\nfunc NewCoordinator(n int, s *Store) *Coordinator {\n\tc := &Coordinator{\n\t\tn:                     n,\n\t\tWorkers:               make([]*Worker, n),\n\t\tepochTID:              EPOCH_INCR,\n\t\twepoch:                make([]chan TID, n),\n\t\twsafe:                 make([]chan TID, n),\n\t\twgo:                   make([]chan TID, n),\n\t\twdone:                 make([]chan TID, n),\n\t\tDone:                  make(chan chan bool),\n\t\tAccelerate:            make(chan bool),\n\t\tCoordinate:            false,\n\t\tPotentialPhaseChanges: 0,\n\t\tto_remove:             make(map[Key]bool),\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tc.wepoch[i] = make(chan TID)\n\t\tc.wsafe[i] = make(chan TID)\n\t\tc.wgo[i] = make(chan TID)\n\t\tc.wdone[i] = make(chan TID)\n\t\tc.Workers[i] = NewWorker(i, s, c)\n\t}\n\tdlog.Printf(\"[coordinator] %v workers\\n\", n)\n\tgo c.Process()\n\treturn c\n}\n\nvar NextEpoch int64\n\nfunc (c *Coordinator) NextGlobalTID() TID {\n\tatomic.AddInt64(&NextEpoch, 1)\n\tx := atomic.AddUint64(&c.epochTID, EPOCH_INCR)\n\treturn TID(x)\n}\n\nfunc (c *Coordinator) GetEpoch() TID {\n\tx := atomic.LoadUint64(&c.epochTID)\n\treturn TID(x)\n}\n\nvar RMoved int64\nvar WMoved int64\nvar Time_in_IE time.Duration\nvar Time_in_IE1 time.Duration\n\nfunc (c *Coordinator) Stats() (map[Key]bool, map[Key]bool) {\n\tif c.PotentialPhaseChanges%(10) != 0 {\n\t\treturn nil, nil\n\t}\n\tstart2 := time.Now()\n\ts := c.Workers[0].store\n\tfor i := 0; i < c.n; i++ {\n\t\tw := c.Workers[i]\n\t\tc.Workers[i].Lock()\n\t\ts.cand.Merge(w.local_store.candidates)\n\t}\n\tpotential_dd_keys := make(map[Key]bool)\n\tto_remove := make(map[Key]bool)\n\txx := len(*s.cand.h)\n\tfor i := 0; i < xx; i++ {\n\t\to := heap.Pop(s.cand.h).(*OneStat)\n\t\tbr, _ := s.getKey(o.k)\n\t\tif !br.dd {\n\t\t\tif len(s.dd) == 0 {\n\t\t\t\t\/\/ Higher threshold for the first one, since it kicks off phases\n\t\t\t\tif o.ratio() > 1.33*(*WRRatio) && (o.writes > 1 || o.conflicts > 5) {\n\t\t\t\t\tpotential_dd_keys[o.k] = true\n\t\t\t\t\tdlog.Printf(\"move %v to split1 r:%v w:%v c:%v s:%v ra:%v\\n\", o.k, o.reads, o.writes, o.conflicts, o.stash, o.ratio())\n\t\t\t\t} else {\n\t\t\t\t\tdlog.Printf(\"%v no move inertia r:%v w:%v c:%v s:%v ra:%v\\n\", o.k, o.reads, o.writes, o.conflicts, o.stash, o.ratio())\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif o.ratio() > *WRRatio && (o.writes > 1 || o.conflicts > 1) {\n\t\t\t\tpotential_dd_keys[o.k] = true\n\t\t\t\tdlog.Printf(\"move %v to split2 r:%v w:%v c:%v s:%v ra:%v\\n\", o.k, o.reads, o.writes, o.conflicts, o.stash, o.ratio())\n\t\t\t} else {\n\t\t\t\tdlog.Printf(\"too low; no move :%v; r:%v w:%v c:%v s:%v ra:%v; wr: %v\\n\", o.k, o.reads, o.writes, o.conflicts, o.stash, o.ratio(), *WRRatio)\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Check to see if we need to remove anything from dd\n\tfor k, v := range s.dd {\n\t\tif !v {\n\t\t\tcontinue\n\t\t}\n\t\to, ok := s.cand.m[k]\n\t\tif !ok {\n\t\t\tdlog.Printf(\"Key %v was split but now is not in store candidates\\n\", k)\n\t\t\tcontinue\n\t\t}\n\t\tif o.ratio() < (*WRRatio)\/2 {\n\t\t\tif x, ok := c.to_remove[k]; x && ok {\n\t\t\t\tc.to_remove[k] = false\n\t\t\t\tto_remove[k] = true\n\t\t\t} else {\n\t\t\t\tc.to_remove[k] = true\n\t\t\t}\n\t\t\tdlog.Printf(\"move %v from split r:%v w:%v c:%v s:%v ratio:%v\\n\", k, o.reads, o.writes, o.conflicts, o.stash, o.ratio())\n\t\t}\n\t}\n\tif len(s.dd) == 0 && len(potential_dd_keys) == 0 {\n\t\ts.any_dd = false\n\t\tc.Coordinate = false\n\t} else {\n\t\tc.Coordinate = true\n\t\ts.any_dd = true\n\t}\n\t\/\/ Reset global store\n\tx := make([]*OneStat, 0)\n\tsh := StatsHeap(x)\n\ts.cand = &Candidates{make(map[Key]*OneStat), &sh}\n\n\tfor i := 0; i < c.n; i++ {\n\t\t\/\/ Reset local stores and unlock\n\t\tw := c.Workers[i]\n\t\tx := make([]*OneStat, 0)\n\t\tsh := StatsHeap(x)\n\t\tw.local_store.candidates = &Candidates{make(map[Key]*OneStat), &sh}\n\t\tw.Unlock()\n\t}\n\tend := time.Since(start2)\n\tTime_in_IE1 += end\n\treturn potential_dd_keys, to_remove\n}\n\nfunc (c *Coordinator) IncrementEpoch(force bool) {\n\tstart1 := time.Now()\n\tc.PotentialPhaseChanges++\n\ts := c.Workers[0].store\n\tvar move_dd, remove_dd map[Key]bool\n\tif *AlwaysSplit {\n\t\tc.Coordinate = true\n\t\ts.any_dd = true\n\t} else {\n\t\tmove_dd, remove_dd = c.Stats()\n\t}\n\tif !c.Coordinate && !force {\n\t\tc.TotalCoordTime += time.Since(start1)\n\t\treturn\n\t}\n\tnext_epoch := c.NextGlobalTID()\n\n\t\/\/ Wait for everyone to merge the previous epoch\n\tsx := time.Now()\n\tfor i := 0; i < c.n; i++ {\n\t\te := <-c.wepoch[i]\n\t\tif e != next_epoch {\n\t\t\tlog.Fatalf(\"Out of alignment in epoch ack; I expected %v, got %v\\n\", next_epoch, e)\n\t\t}\n\t}\n\tc.MergeTime += time.Since(sx)\n\n\t\/\/ All merged.  The previous epoch is now safe; tell everyone to\n\t\/\/ do their reads.\n\tsx = time.Now()\n\tatomic.StoreInt32(&c.trigger, 0)\n\tfor i := 0; i < c.n; i++ {\n\t\tc.wsafe[i] <- next_epoch\n\t}\n\tfor i := 0; i < c.n; i++ {\n\t\te := <-c.wdone[i]\n\t\tif e != next_epoch {\n\t\t\tlog.Fatalf(\"Out of alignment in done; I expected %v, got %v\\n\", next_epoch, e)\n\t\t}\n\n\t}\n\tc.ReadTime += time.Since(sx)\n\t\/\/ Merge dd\n\tif !*AlwaysSplit {\n\t\tif move_dd != nil {\n\t\t\tfor k, _ := range move_dd {\n\t\t\t\tbr, _ := s.getKey(k)\n\t\t\t\tbr.dd = true\n\t\t\t\ts.dd[k] = true\n\t\t\t\tWMoved += 1\n\t\t\t}\n\t\t}\n\t\tif remove_dd != nil {\n\t\t\tfor k, _ := range remove_dd {\n\t\t\t\tbr, _ := s.getKey(k)\n\t\t\t\tbr.dd = false\n\t\t\t\ts.dd[k] = false\n\t\t\t\tRMoved += 1\n\t\t\t}\n\t\t}\n\t}\n\n\tsx = time.Now()\n\tfor i := 0; i < c.n; i++ {\n\t\tc.wgo[i] <- next_epoch\n\t}\n\tc.GoTime += time.Since(sx)\n\tc.TotalCoordTime += time.Since(start1)\n}\n\nfunc (c *Coordinator) Finish() {\n\tdlog.Printf(\"Coordinator finishing\\n\")\n\tx := make(chan bool)\n\tc.Done <- x\n\t<-x\n}\n\nvar Nfast int64\n\nfunc (c *Coordinator) Process() {\n\ttm := time.NewTicker(time.Duration(*PhaseLength) * time.Millisecond).C\n\n\t\/\/ More frequently, check if the workers are demanding a phase\n\t\/\/ change due to long stashed queue lengths.\n\tcheck_trigger := time.NewTicker(time.Duration(*PhaseLength) * time.Microsecond * 10).C\n\n\tfor {\n\t\tselect {\n\t\tcase x := <-c.Done:\n\t\t\tif *SysType == DOPPEL && c.n > 1 {\n\t\t\t\tc.IncrementEpoch(true)\n\t\t\t}\n\t\t\tfor i := 0; i < c.n; i++ {\n\t\t\t\tc.Workers[i].done <- true\n\t\t\t}\n\t\t\tx <- true\n\t\t\treturn\n\t\tcase <-tm:\n\t\t\tif *SysType == DOPPEL && c.n > 1 {\n\t\t\t\tc.IncrementEpoch(false)\n\t\t\t}\n\t\tcase <-check_trigger:\n\t\t\tif *SysType == DOPPEL && c.n > 1 {\n\t\t\t\tx := atomic.LoadInt32(&c.trigger)\n\t\t\t\tif x == int32(c.n) {\n\t\t\t\t\tNfast++\n\t\t\t\t\tatomic.StoreInt32(&c.trigger, 0)\n\t\t\t\t\tc.IncrementEpoch(true)\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-c.Accelerate:\n\t\t\tif *SysType == DOPPEL && c.n > 1 {\n\t\t\t\tdlog.Printf(\"Accelerating\\n\")\n\t\t\t\tc.IncrementEpoch(true)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc compute(w *Worker, txn int) (int64, int64) {\n\tvar total int64\n\tvar sum int64\n\tvar i int64\n\tfor i = 0; i < TIMES; i++ {\n\t\ttotal = total + w.times[txn][i]\n\t\tsum = sum + (w.times[txn][i] * i)\n\t}\n\tvar x99 int64 = int64(float64(total) * .99)\n\tvar y99 int64\n\tvar v99 int64\n\tfor i = 0; i < TIMES; i++ {\n\t\ty99 = y99 + w.times[txn][i]\n\t\tif y99 >= x99 {\n\t\t\tv99 = i\n\t\t\tbreak\n\t\t}\n\t}\n\tdlog.Printf(\"%v avg: %v us; 99: %v us, x99: %v, sum: %v, total: %v \\n\", txn, sum\/total, v99, x99, sum, total)\n\treturn sum \/ total, v99\n}\n\nfunc (c *Coordinator) Latency() (string, string) {\n\tif !*Latency {\n\t\treturn \"\", \"\"\n\t}\n\tfor i := 1; i < c.n; i++ {\n\t\tfor j := 0; j < 4; j++ {\n\t\t\tfor k := 0; k < TIMES; k++ {\n\t\t\t\tc.Workers[0].times[j][k] = c.Workers[0].times[j][k] + c.Workers[i].times[j][k]\n\t\t\t}\n\t\t}\n\t}\n\tx, y := compute(c.Workers[0], D_BUY)\n\tx2, y2 := compute(c.Workers[0], D_READ_TWO)\n\treturn fmt.Sprintf(\"Read 99: %v\\nRead Avg: %v\\n\", y2, x2), fmt.Sprintf(\"Write 99: %v\\nWrite Avg: %v\\n\", y, x)\n\n}\n<commit_msg>easier to read<commit_after>package ddtxn\n\nimport (\n\t\"container\/heap\"\n\t\"ddtxn\/dlog\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\nconst (\n\tBUMP_EPOCH_MS = 80\n\tEPOCH_INCR    = 1 << 32\n\tTXID_MASK     = 0x00000000ffffffff\n\tCLEAR_TID     = 0xffffffff00000000\n)\n\nvar PhaseLength = flag.Int(\"phase\", 80, \"Phase length in milliseconds, default 80\")\n\ntype Coordinator struct {\n\tn        int\n\tWorkers  []*Worker\n\tepochTID uint64 \/\/ Global TID, atomically incremented and read\n\n\t\/\/ Notify workers\n\twepoch []chan TID\n\twsafe  []chan TID\n\twgo    []chan TID\n\twdone  []chan TID\n\n\tCoordinate            bool\n\tPotentialPhaseChanges int64\n\tDone                  chan chan bool\n\tAccelerate            chan bool\n\ttrigger               int32\n\tto_remove             map[Key]bool\n\n\tTotalCoordTime time.Duration\n\tGoTime         time.Duration\n\tReadTime       time.Duration\n\tMergeTime      time.Duration\n}\n\nfunc NewCoordinator(n int, s *Store) *Coordinator {\n\tc := &Coordinator{\n\t\tn:                     n,\n\t\tWorkers:               make([]*Worker, n),\n\t\tepochTID:              EPOCH_INCR,\n\t\twepoch:                make([]chan TID, n),\n\t\twsafe:                 make([]chan TID, n),\n\t\twgo:                   make([]chan TID, n),\n\t\twdone:                 make([]chan TID, n),\n\t\tDone:                  make(chan chan bool),\n\t\tAccelerate:            make(chan bool),\n\t\tCoordinate:            false,\n\t\tPotentialPhaseChanges: 0,\n\t\tto_remove:             make(map[Key]bool),\n\t}\n\tfor i := 0; i < n; i++ {\n\t\tc.wepoch[i] = make(chan TID)\n\t\tc.wsafe[i] = make(chan TID)\n\t\tc.wgo[i] = make(chan TID)\n\t\tc.wdone[i] = make(chan TID)\n\t\tc.Workers[i] = NewWorker(i, s, c)\n\t}\n\tdlog.Printf(\"[coordinator] %v workers\\n\", n)\n\tgo c.Process()\n\treturn c\n}\n\nvar NextEpoch int64\n\nfunc (c *Coordinator) NextGlobalTID() TID {\n\tatomic.AddInt64(&NextEpoch, 1)\n\tx := atomic.AddUint64(&c.epochTID, EPOCH_INCR)\n\treturn TID(x)\n}\n\nfunc (c *Coordinator) GetEpoch() TID {\n\tx := atomic.LoadUint64(&c.epochTID)\n\treturn TID(x)\n}\n\nvar RMoved int64\nvar WMoved int64\nvar Time_in_IE time.Duration\nvar Time_in_IE1 time.Duration\n\nfunc (c *Coordinator) Stats() (map[Key]bool, map[Key]bool) {\n\tif c.PotentialPhaseChanges%(10) != 0 {\n\t\treturn nil, nil\n\t}\n\tstart2 := time.Now()\n\ts := c.Workers[0].store\n\tfor i := 0; i < c.n; i++ {\n\t\tw := c.Workers[i]\n\t\tc.Workers[i].Lock()\n\t\ts.cand.Merge(w.local_store.candidates)\n\t}\n\tpotential_dd_keys := make(map[Key]bool)\n\tto_remove := make(map[Key]bool)\n\txx := len(*s.cand.h)\n\tfor i := 0; i < xx; i++ {\n\t\to := heap.Pop(s.cand.h).(*OneStat)\n\t\tbr, _ := s.getKey(o.k)\n\t\tif !br.dd {\n\t\t\tif len(s.dd) == 0 {\n\t\t\t\t\/\/ Higher threshold for the first one, since it kicks off phases\n\t\t\t\tif o.ratio() > 1.33*(*WRRatio) && (o.writes > 1 || o.conflicts > 5) {\n\t\t\t\t\tpotential_dd_keys[o.k] = true\n\t\t\t\t\tdlog.Printf(\"move %v to split1 r:%v w:%v c:%v s:%v ra:%v\\n\", o.k, o.reads, o.writes, o.conflicts, o.stash, o.ratio())\n\t\t\t\t} else {\n\t\t\t\t\tdlog.Printf(\"%v no move inertia r:%v w:%v c:%v s:%v ra:%v\\n\", o.k, o.reads, o.writes, o.conflicts, o.stash, o.ratio())\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif o.ratio() > *WRRatio && (o.writes > 1 || o.conflicts > 1) {\n\t\t\t\tpotential_dd_keys[o.k] = true\n\t\t\t\tdlog.Printf(\"move %v to split2 r:%v w:%v c:%v s:%v ra:%v\\n\", o.k, o.reads, o.writes, o.conflicts, o.stash, o.ratio())\n\t\t\t} else {\n\t\t\t\tdlog.Printf(\"too low; no move :%v; r:%v w:%v c:%v s:%v ra:%v; wr: %v\\n\", o.k, o.reads, o.writes, o.conflicts, o.stash, o.ratio(), *WRRatio)\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Check to see if we need to remove anything from dd\n\tfor k, v := range s.dd {\n\t\tif !v {\n\t\t\tcontinue\n\t\t}\n\t\to, ok := s.cand.m[k]\n\t\tif !ok {\n\t\t\tdlog.Printf(\"Key %v was split but now is not in store candidates\\n\", k)\n\t\t\tcontinue\n\t\t}\n\t\tif o.ratio() < (*WRRatio)\/2 {\n\t\t\tif x, ok := c.to_remove[k]; x && ok {\n\t\t\t\tc.to_remove[k] = false\n\t\t\t\tto_remove[k] = true\n\t\t\t} else {\n\t\t\t\tc.to_remove[k] = true\n\t\t\t}\n\t\t\tdlog.Printf(\"move %v from split r:%v w:%v c:%v s:%v ratio:%v\\n\", k, o.reads, o.writes, o.conflicts, o.stash, o.ratio())\n\t\t}\n\t}\n\tif len(s.dd) == 0 && len(potential_dd_keys) == 0 {\n\t\ts.any_dd = false\n\t\tc.Coordinate = false\n\t} else {\n\t\tc.Coordinate = true\n\t\ts.any_dd = true\n\t}\n\t\/\/ Reset global store\n\tx := make([]*OneStat, 0)\n\tsh := StatsHeap(x)\n\ts.cand = &Candidates{make(map[Key]*OneStat), &sh}\n\n\tfor i := 0; i < c.n; i++ {\n\t\t\/\/ Reset local stores and unlock\n\t\tw := c.Workers[i]\n\t\tx := make([]*OneStat, 0)\n\t\tsh := StatsHeap(x)\n\t\tw.local_store.candidates = &Candidates{make(map[Key]*OneStat), &sh}\n\t\tw.Unlock()\n\t}\n\tend := time.Since(start2)\n\tTime_in_IE1 += end\n\treturn potential_dd_keys, to_remove\n}\n\nfunc (c *Coordinator) IncrementEpoch(force bool) {\n\tstart1 := time.Now()\n\tc.PotentialPhaseChanges++\n\ts := c.Workers[0].store\n\tvar move_dd, remove_dd map[Key]bool\n\tif *AlwaysSplit {\n\t\tc.Coordinate = true\n\t\ts.any_dd = true\n\t} else {\n\t\tmove_dd, remove_dd = c.Stats()\n\t}\n\tif !c.Coordinate && !force {\n\t\tc.TotalCoordTime += time.Since(start1)\n\t\treturn\n\t}\n\tnext_epoch := c.NextGlobalTID()\n\n\t\/\/ Wait for everyone to merge the previous epoch\n\tsx := time.Now()\n\tfor i := 0; i < c.n; i++ {\n\t\te := <-c.wepoch[i]\n\t\tif e != next_epoch {\n\t\t\tlog.Fatalf(\"Out of alignment in epoch ack; I expected %v, got %v\\n\", next_epoch, e)\n\t\t}\n\t}\n\tc.MergeTime += time.Since(sx)\n\n\t\/\/ All merged.  The previous epoch is now safe; tell everyone to\n\t\/\/ do their reads.\n\tsx = time.Now()\n\tatomic.StoreInt32(&c.trigger, 0)\n\tfor i := 0; i < c.n; i++ {\n\t\tc.wsafe[i] <- next_epoch\n\t}\n\tfor i := 0; i < c.n; i++ {\n\t\te := <-c.wdone[i]\n\t\tif e != next_epoch {\n\t\t\tlog.Fatalf(\"Out of alignment in done; I expected %v, got %v\\n\", next_epoch, e)\n\t\t}\n\n\t}\n\tc.ReadTime += time.Since(sx)\n\t\/\/ Merge dd\n\tif !*AlwaysSplit {\n\t\tif move_dd != nil {\n\t\t\tfor k, _ := range move_dd {\n\t\t\t\tbr, _ := s.getKey(k)\n\t\t\t\tbr.dd = true\n\t\t\t\ts.dd[k] = true\n\t\t\t\tWMoved += 1\n\t\t\t}\n\t\t}\n\t\tif remove_dd != nil {\n\t\t\tfor k, _ := range remove_dd {\n\t\t\t\tbr, _ := s.getKey(k)\n\t\t\t\tbr.dd = false\n\t\t\t\ts.dd[k] = false\n\t\t\t\tRMoved += 1\n\t\t\t}\n\t\t}\n\t}\n\n\tsx = time.Now()\n\tfor i := 0; i < c.n; i++ {\n\t\tc.wgo[i] <- next_epoch\n\t}\n\tc.GoTime += time.Since(sx)\n\tc.TotalCoordTime += time.Since(start1)\n}\n\nfunc (c *Coordinator) Finish() {\n\tdlog.Printf(\"Coordinator finishing\\n\")\n\tx := make(chan bool)\n\tc.Done <- x\n\t<-x\n}\n\nvar Nfast int64\n\nfunc (c *Coordinator) Process() {\n\ttm := time.NewTicker(time.Duration(*PhaseLength) * time.Millisecond).C\n\n\t\/\/ More frequently, check if the workers are demanding a phase\n\t\/\/ change due to long stashed queue lengths.\n\tcheck_trigger := time.NewTicker(time.Duration(*PhaseLength) * time.Microsecond * 10).C\n\n\tfor {\n\t\tselect {\n\t\tcase x := <-c.Done:\n\t\t\tif *SysType == DOPPEL && c.n > 1 {\n\t\t\t\tc.IncrementEpoch(true)\n\t\t\t}\n\t\t\tfor i := 0; i < c.n; i++ {\n\t\t\t\tc.Workers[i].done <- true\n\t\t\t}\n\t\t\tx <- true\n\t\t\treturn\n\t\tcase <-tm:\n\t\t\tif *SysType == DOPPEL && c.n > 1 {\n\t\t\t\tc.IncrementEpoch(false)\n\t\t\t}\n\t\tcase <-check_trigger:\n\t\t\tif *SysType == DOPPEL && c.n > 1 {\n\t\t\t\tx := atomic.LoadInt32(&c.trigger)\n\t\t\t\tif x == int32(c.n) {\n\t\t\t\t\tNfast++\n\t\t\t\t\tatomic.StoreInt32(&c.trigger, 0)\n\t\t\t\t\tc.IncrementEpoch(true)\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-c.Accelerate:\n\t\t\tif *SysType == DOPPEL && c.n > 1 {\n\t\t\t\tdlog.Printf(\"Accelerating\\n\")\n\t\t\t\tc.IncrementEpoch(true)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc compute(w *Worker, txn int) (int64, int64) {\n\tvar total int64\n\tvar sum int64\n\tvar i int64\n\tfor i = 0; i < TIMES; i++ {\n\t\ttotal = total + w.times[txn][i]\n\t\tsum = sum + (w.times[txn][i] * i)\n\t}\n\tvar x99 int64 = int64(float64(total) * .99)\n\tvar y99 int64\n\tvar v99 int64\n\tfor i = 0; i < TIMES; i++ {\n\t\ty99 = y99 + w.times[txn][i]\n\t\tif y99 >= x99 {\n\t\t\tv99 = i\n\t\t\tbreak\n\t\t}\n\t}\n\tdlog.Printf(\"%v avg: %v us; 99: %v us, x99: %v, sum: %v, total: %v \\n\", txn, sum\/total, v99, x99, sum, total)\n\treturn sum \/ total, v99\n}\n\nfunc (c *Coordinator) Latency() (string, string) {\n\tif !*Latency {\n\t\treturn \"\", \"\"\n\t}\n\tfor i := 1; i < c.n; i++ {\n\t\tfor j := 0; j < 4; j++ {\n\t\t\tfor k := 0; k < TIMES; k++ {\n\t\t\t\tc.Workers[0].times[j][k] = c.Workers[0].times[j][k] + c.Workers[i].times[j][k]\n\t\t\t}\n\t\t}\n\t}\n\tx, y := compute(c.Workers[0], D_BUY)\n\tx2, y2 := compute(c.Workers[0], D_READ_TWO)\n\treturn fmt.Sprintf(\"Read\/Write Avg: %v\/%v\\n\", x2, x), fmt.Sprintf(\"Read\/Write 99: %v\/%v\\n\", y2, y)\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage fs_test\n\nimport (\n\t\"github.com\/jacobsa\/comeback\/fs\"\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/ogletest\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n)\n\nfunc TestCreate(t *testing.T) { RunTests(t) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CreateFile\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype CreateFileTest struct {\n\tfileSystemTest\n\n\tpath  string\n\tperms os.FileMode\n\n\tw   io.WriteCloser\n\terr error\n}\n\nfunc init() { RegisterTestSuite(&CreateFileTest{}) }\n\nfunc (t *CreateFileTest) SetUp(i *TestInfo) {\n\t\/\/ Common\n\tt.fileSystemTest.SetUp(i)\n\n\t\/\/ Set up defaults.\n\tt.path = path.Join(t.baseDir, \"taco\")\n\tt.perms = 0644\n}\n\nfunc (t *CreateFileTest) call() {\n\tt.w, t.err = t.fileSystem.CreateFile(t.path, t.perms)\n}\n\nfunc (t *CreateFileTest) list() []*fs.DirectoryEntry {\n\tentries, err := t.fileSystem.ReadDir(t.baseDir)\n\tAssertEq(nil, err)\n\treturn entries\n}\n\nfunc (t *CreateFileTest) NonExistentParent() {\n\tt.path = \"\/foo\/bar\/baz\/qux\"\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"qux\")))\n\tExpectThat(t.err, Error(HasSubstr(\"no such\")))\n}\n\nfunc (t *CreateFileTest) NoPermissionsForParent() {\n\tdirpath := path.Join(t.baseDir, \"foo\")\n\tt.path = path.Join(dirpath, \"taco\")\n\n\t\/\/ Parent\n\terr := os.Mkdir(dirpath, 0100)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"foo\")))\n\tExpectThat(t.err, Error(HasSubstr(\"permission denied\")))\n}\n\nfunc (t *CreateFileTest) FileAlreadyExists() {\n\t\/\/ Create\n\terr := ioutil.WriteFile(t.path, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"file exists\")))\n}\n\nfunc (t *CreateFileTest) CreatesCorrectEntry() {\n\tt.path = path.Join(t.baseDir, \"taco\")\n\tt.perms = 0674  \/\/ Conflicts with default umask\n\n\t\/\/ Call\n\tt.call()\n\tAssertEq(nil, t.err)\n\tdefer t.w.Close()\n\n\t\/\/ List\n\tentries := t.list()\n\n\tAssertThat(entries, ElementsAre(Any()))\n\tentry := entries[0]\n\n\tExpectEq(fs.TypeFile, entry.Type)\n\tExpectEq(\"taco\", entry.Name)\n\tExpectEq(0674, entry.Permissions)\n}\n\nfunc (t *CreateFileTest) SavesDataToCorrectPlace() {\n\t\/\/ Call\n\tt.call()\n\tAssertEq(nil, t.err)\n\n\t\/\/ Write\n\texpected := []byte(\"taco\")\n\t_, err := t.w.Write(expected)\n\tAssertEq(nil, err)\n\n\t\/\/ Close\n\tAssertEq(nil, t.w.Close())\n\n\t\/\/ Read\n\tdata, err := ioutil.ReadFile(t.path)\n\tAssertEq(nil, err)\n\n\tExpectThat(data, DeepEquals(expected))\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Mkdir\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype MkdirTest struct {\n\tfileSystemTest\n\n\tpath  string\n\tperms os.FileMode\n\n\terr error\n}\n\nfunc init() { RegisterTestSuite(&MkdirTest{}) }\n\nfunc (t *MkdirTest) SetUp(i *TestInfo) {\n\t\/\/ Common\n\tt.fileSystemTest.SetUp(i)\n\n\t\/\/ Set up defaults.\n\tt.path = path.Join(t.baseDir, \"taco\")\n\tt.perms = 0644\n}\n\nfunc (t *MkdirTest) call() {\n\tt.err = t.fileSystem.Mkdir(t.path, t.perms)\n}\n\nfunc (t *MkdirTest) list() []*fs.DirectoryEntry {\n\tentries, err := t.fileSystem.ReadDir(t.baseDir)\n\tAssertEq(nil, err)\n\treturn entries\n}\n\nfunc (t *MkdirTest) NonExistentParent() {\n\tt.path = \"\/foo\/bar\/baz\/qux\"\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"qux\")))\n\tExpectThat(t.err, Error(HasSubstr(\"no such\")))\n}\n\nfunc (t *MkdirTest) NoPermissionsForParent() {\n\tdirpath := path.Join(t.baseDir, \"foo\")\n\tt.path = path.Join(dirpath, \"taco\")\n\n\t\/\/ Parent\n\terr := os.Mkdir(dirpath, 0100)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"foo\")))\n\tExpectThat(t.err, Error(HasSubstr(\"permission denied\")))\n}\n\nfunc (t *MkdirTest) FileAlreadyExistsWithSameName() {\n\t\/\/ Create\n\terr := ioutil.WriteFile(t.path, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"file exists\")))\n}\n\nfunc (t *MkdirTest) CreatesCorrectEntry() {\n\tt.path = path.Join(t.baseDir, \"taco\")\n\tt.perms = 0674  \/\/ Conflicts with default umask\n\n\t\/\/ Call\n\tt.call()\n\tAssertEq(nil, t.err)\n\n\t\/\/ List\n\tentries := t.list()\n\n\tAssertThat(entries, ElementsAre(Any()))\n\tentry := entries[0]\n\n\tExpectEq(fs.TypeDirectory, entry.Type)\n\tExpectEq(\"taco\", entry.Name)\n\tExpectEq(0674, entry.Permissions)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CreateNamedPipe\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype CreateNamedPipeTest struct {\n\tfileSystemTest\n\n\tpath  string\n\tperms os.FileMode\n\n\terr error\n}\n\nfunc init() { RegisterTestSuite(&CreateNamedPipeTest{}) }\n\nfunc (t *CreateNamedPipeTest) SetUp(i *TestInfo) {\n\t\/\/ Common\n\tt.fileSystemTest.SetUp(i)\n\n\t\/\/ Set up defaults.\n\tt.path = path.Join(t.baseDir, \"taco\")\n\tt.perms = 0644\n}\n\nfunc (t *CreateNamedPipeTest) call() {\n\tt.err = t.fileSystem.CreateNamedPipe(t.path, t.perms)\n}\n\nfunc (t *CreateNamedPipeTest) list() []*fs.DirectoryEntry {\n\tentries, err := t.fileSystem.ReadDir(t.baseDir)\n\tAssertEq(nil, err)\n\treturn entries\n}\n\nfunc (t *CreateNamedPipeTest) NonExistentParent() {\n\tt.path = \"\/foo\/bar\/baz\/qux\"\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"no such\")))\n}\n\nfunc (t *CreateNamedPipeTest) NoPermissionsForParent() {\n\tdirpath := path.Join(t.baseDir, \"foo\")\n\tt.path = path.Join(dirpath, \"taco\")\n\n\t\/\/ Parent\n\terr := os.Mkdir(dirpath, 0100)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"permission denied\")))\n}\n\nfunc (t *CreateNamedPipeTest) FileAlreadyExistsWithSameName() {\n\t\/\/ Create\n\terr := ioutil.WriteFile(t.path, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"file exists\")))\n}\n\nfunc (t *CreateNamedPipeTest) CreatesCorrectEntry() {\n\tt.path = path.Join(t.baseDir, \"taco\")\n\tt.perms = 0674  \/\/ Conflicts with default umask\n\n\t\/\/ Call\n\tt.call()\n\tAssertEq(nil, t.err)\n\n\t\/\/ List\n\tentries := t.list()\n\n\tAssertThat(entries, ElementsAre(Any()))\n\tentry := entries[0]\n\n\tExpectEq(fs.TypeNamedPipe, entry.Type)\n\tExpectEq(\"taco\", entry.Name)\n\tExpectEq(0674, entry.Permissions)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CreateSymlink\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype CreateSymlinkTest struct {\n\tfileSystemTest\n\n\ttarget  string\n\tsource  string\n\tperms os.FileMode\n\n\terr error\n}\n\nfunc init() { RegisterTestSuite(&CreateSymlinkTest{}) }\n\nfunc (t *CreateSymlinkTest) SetUp(i *TestInfo) {\n\t\/\/ Common\n\tt.fileSystemTest.SetUp(i)\n\n\t\/\/ Set up defaults.\n\tt.source = path.Join(t.baseDir, \"taco\")\n\tt.target = \"\/foo\/bar\"\n\tt.perms = 0644\n}\n\nfunc (t *CreateSymlinkTest) call() {\n\tt.err = t.fileSystem.CreateSymlink(t.target, t.source, t.perms)\n}\n\nfunc (t *CreateSymlinkTest) list() []*fs.DirectoryEntry {\n\tentries, err := t.fileSystem.ReadDir(t.baseDir)\n\tAssertEq(nil, err)\n\treturn entries\n}\n\nfunc (t *CreateSymlinkTest) NonExistentParent() {\n\tt.source = \"\/foo\/bar\/baz\/qux\"\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"qux\")))\n\tExpectThat(t.err, Error(HasSubstr(\"no such\")))\n}\n\nfunc (t *CreateSymlinkTest) NoPermissionsForParent() {\n\tdirpath := path.Join(t.baseDir, \"foo\")\n\tt.source = path.Join(dirpath, \"taco\")\n\n\t\/\/ Parent\n\terr := os.Mkdir(dirpath, 0100)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"foo\")))\n\tExpectThat(t.err, Error(HasSubstr(\"permission denied\")))\n}\n\nfunc (t *CreateSymlinkTest) FileAlreadyExistsWithSameName() {\n\t\/\/ Create\n\terr := ioutil.WriteFile(t.source, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"file exists\")))\n}\n\nfunc (t *CreateSymlinkTest) CreatesCorrectEntry() {\n\tt.source = path.Join(t.baseDir, \"taco\")\n\tt.target = \"\/burrito\"\n\tt.perms = 0674  \/\/ Conflicts with default umask\n\n\t\/\/ Call\n\tt.call()\n\tAssertEq(nil, t.err)\n\n\t\/\/ List\n\tentries := t.list()\n\n\tAssertThat(entries, ElementsAre(Any()))\n\tentry := entries[0]\n\n\tExpectEq(fs.TypeSymlink, entry.Type)\n\tExpectEq(\"taco\", entry.Name)\n\tExpectEq(\"\/burrito\", entry.Target)\n\tExpectEq(0674, entry.Permissions)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CreateHardLink\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype CreateHardLinkTest struct {\n\tfileSystemTest\n\n\ttarget  string\n\tsource  string\n\n\terr error\n}\n\nfunc init() { RegisterTestSuite(&CreateHardLinkTest{}) }\n\nfunc (t *CreateHardLinkTest) SetUp(i *TestInfo) {\n\t\/\/ Common\n\tt.fileSystemTest.SetUp(i)\n\n\t\/\/ Set up defaults.\n\tt.source = path.Join(t.baseDir, \"taco\")\n\tt.target = path.Join(t.baseDir, \"burrito\")\n}\n\nfunc (t *CreateHardLinkTest) call() {\n\tt.err = t.fileSystem.CreateHardLink(t.target, t.source)\n}\n\nfunc (t *CreateHardLinkTest) list() []*fs.DirectoryEntry {\n\tentries, err := t.fileSystem.ReadDir(t.baseDir)\n\tAssertEq(nil, err)\n\treturn entries\n}\n\nfunc (t *CreateHardLinkTest) NonExistentParent() {\n\tt.source = \"\/foo\/bar\/baz\/qux\"\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"qux\")))\n\tExpectThat(t.err, Error(HasSubstr(\"no such\")))\n}\n\nfunc (t *CreateHardLinkTest) NoPermissionsForParent() {\n\tdirpath := path.Join(t.baseDir, \"foo\")\n\tt.source = path.Join(dirpath, \"taco\")\n\n\t\/\/ Create target\n\terr := ioutil.WriteFile(t.target, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Parent\n\terr = os.Mkdir(dirpath, 0100)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"foo\")))\n\tExpectThat(t.err, Error(HasSubstr(\"permission denied\")))\n}\n\nfunc (t *CreateHardLinkTest) TargetDoesntExist() {\n\tt.source = path.Join(t.baseDir, \"taco\")\n\tt.target = \"\/burrito\"\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"burrito\")))\n\tExpectThat(t.err, Error(HasSubstr(\"no such\")))\n\tExpectThat(t.err, Error(HasSubstr(\"file\")))\n}\n\nfunc (t *CreateHardLinkTest) FileAlreadyExistsWithSameName() {\n\t\/\/ Create source\n\terr := ioutil.WriteFile(t.source, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Create target\n\terr = ioutil.WriteFile(t.target, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"file exists\")))\n}\n\nfunc (t *CreateHardLinkTest) CreatesCorrectEntry() {\n\tt.source = path.Join(t.baseDir, \"taco\")\n\tt.target = path.Join(t.baseDir, \"burrito\")\n\n\t\/\/ Create target\n\terr := ioutil.WriteFile(t.target, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\tAssertEq(nil, t.err)\n\n\t\/\/ List\n\tentries := t.list()\n\n\tAssertThat(entries, ElementsAre(Any(), Any()))\n\n\tentry0 := entries[0]\n\tExpectEq(fs.TypeFile, entry0.Type)\n\tExpectEq(\"burrito\", entry0.Name)\n\n\tentry1 := entries[1]\n\tExpectEq(fs.TypeFile, entry1.Type)\n\tExpectEq(\"taco\", entry1.Name)\n\n\tAssertNe(0, entry0.ContainingDevice)\n\tExpectEq(entry1.ContainingDevice, entry0.ContainingDevice)\n\n\tAssertNe(0, entry0.Inode)\n\tExpectEq(entry1.Inode, entry0.Inode)\n}\n<commit_msg>Fixed formatting.<commit_after>\/\/ Copyright 2012 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage fs_test\n\nimport (\n\t\"github.com\/jacobsa\/comeback\/fs\"\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/ogletest\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n)\n\nfunc TestCreate(t *testing.T) { RunTests(t) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CreateFile\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype CreateFileTest struct {\n\tfileSystemTest\n\n\tpath  string\n\tperms os.FileMode\n\n\tw   io.WriteCloser\n\terr error\n}\n\nfunc init() { RegisterTestSuite(&CreateFileTest{}) }\n\nfunc (t *CreateFileTest) SetUp(i *TestInfo) {\n\t\/\/ Common\n\tt.fileSystemTest.SetUp(i)\n\n\t\/\/ Set up defaults.\n\tt.path = path.Join(t.baseDir, \"taco\")\n\tt.perms = 0644\n}\n\nfunc (t *CreateFileTest) call() {\n\tt.w, t.err = t.fileSystem.CreateFile(t.path, t.perms)\n}\n\nfunc (t *CreateFileTest) list() []*fs.DirectoryEntry {\n\tentries, err := t.fileSystem.ReadDir(t.baseDir)\n\tAssertEq(nil, err)\n\treturn entries\n}\n\nfunc (t *CreateFileTest) NonExistentParent() {\n\tt.path = \"\/foo\/bar\/baz\/qux\"\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"qux\")))\n\tExpectThat(t.err, Error(HasSubstr(\"no such\")))\n}\n\nfunc (t *CreateFileTest) NoPermissionsForParent() {\n\tdirpath := path.Join(t.baseDir, \"foo\")\n\tt.path = path.Join(dirpath, \"taco\")\n\n\t\/\/ Parent\n\terr := os.Mkdir(dirpath, 0100)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"foo\")))\n\tExpectThat(t.err, Error(HasSubstr(\"permission denied\")))\n}\n\nfunc (t *CreateFileTest) FileAlreadyExists() {\n\t\/\/ Create\n\terr := ioutil.WriteFile(t.path, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"file exists\")))\n}\n\nfunc (t *CreateFileTest) CreatesCorrectEntry() {\n\tt.path = path.Join(t.baseDir, \"taco\")\n\tt.perms = 0674 \/\/ Conflicts with default umask\n\n\t\/\/ Call\n\tt.call()\n\tAssertEq(nil, t.err)\n\tdefer t.w.Close()\n\n\t\/\/ List\n\tentries := t.list()\n\n\tAssertThat(entries, ElementsAre(Any()))\n\tentry := entries[0]\n\n\tExpectEq(fs.TypeFile, entry.Type)\n\tExpectEq(\"taco\", entry.Name)\n\tExpectEq(0674, entry.Permissions)\n}\n\nfunc (t *CreateFileTest) SavesDataToCorrectPlace() {\n\t\/\/ Call\n\tt.call()\n\tAssertEq(nil, t.err)\n\n\t\/\/ Write\n\texpected := []byte(\"taco\")\n\t_, err := t.w.Write(expected)\n\tAssertEq(nil, err)\n\n\t\/\/ Close\n\tAssertEq(nil, t.w.Close())\n\n\t\/\/ Read\n\tdata, err := ioutil.ReadFile(t.path)\n\tAssertEq(nil, err)\n\n\tExpectThat(data, DeepEquals(expected))\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Mkdir\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype MkdirTest struct {\n\tfileSystemTest\n\n\tpath  string\n\tperms os.FileMode\n\n\terr error\n}\n\nfunc init() { RegisterTestSuite(&MkdirTest{}) }\n\nfunc (t *MkdirTest) SetUp(i *TestInfo) {\n\t\/\/ Common\n\tt.fileSystemTest.SetUp(i)\n\n\t\/\/ Set up defaults.\n\tt.path = path.Join(t.baseDir, \"taco\")\n\tt.perms = 0644\n}\n\nfunc (t *MkdirTest) call() {\n\tt.err = t.fileSystem.Mkdir(t.path, t.perms)\n}\n\nfunc (t *MkdirTest) list() []*fs.DirectoryEntry {\n\tentries, err := t.fileSystem.ReadDir(t.baseDir)\n\tAssertEq(nil, err)\n\treturn entries\n}\n\nfunc (t *MkdirTest) NonExistentParent() {\n\tt.path = \"\/foo\/bar\/baz\/qux\"\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"qux\")))\n\tExpectThat(t.err, Error(HasSubstr(\"no such\")))\n}\n\nfunc (t *MkdirTest) NoPermissionsForParent() {\n\tdirpath := path.Join(t.baseDir, \"foo\")\n\tt.path = path.Join(dirpath, \"taco\")\n\n\t\/\/ Parent\n\terr := os.Mkdir(dirpath, 0100)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"foo\")))\n\tExpectThat(t.err, Error(HasSubstr(\"permission denied\")))\n}\n\nfunc (t *MkdirTest) FileAlreadyExistsWithSameName() {\n\t\/\/ Create\n\terr := ioutil.WriteFile(t.path, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"file exists\")))\n}\n\nfunc (t *MkdirTest) CreatesCorrectEntry() {\n\tt.path = path.Join(t.baseDir, \"taco\")\n\tt.perms = 0674 \/\/ Conflicts with default umask\n\n\t\/\/ Call\n\tt.call()\n\tAssertEq(nil, t.err)\n\n\t\/\/ List\n\tentries := t.list()\n\n\tAssertThat(entries, ElementsAre(Any()))\n\tentry := entries[0]\n\n\tExpectEq(fs.TypeDirectory, entry.Type)\n\tExpectEq(\"taco\", entry.Name)\n\tExpectEq(0674, entry.Permissions)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CreateNamedPipe\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype CreateNamedPipeTest struct {\n\tfileSystemTest\n\n\tpath  string\n\tperms os.FileMode\n\n\terr error\n}\n\nfunc init() { RegisterTestSuite(&CreateNamedPipeTest{}) }\n\nfunc (t *CreateNamedPipeTest) SetUp(i *TestInfo) {\n\t\/\/ Common\n\tt.fileSystemTest.SetUp(i)\n\n\t\/\/ Set up defaults.\n\tt.path = path.Join(t.baseDir, \"taco\")\n\tt.perms = 0644\n}\n\nfunc (t *CreateNamedPipeTest) call() {\n\tt.err = t.fileSystem.CreateNamedPipe(t.path, t.perms)\n}\n\nfunc (t *CreateNamedPipeTest) list() []*fs.DirectoryEntry {\n\tentries, err := t.fileSystem.ReadDir(t.baseDir)\n\tAssertEq(nil, err)\n\treturn entries\n}\n\nfunc (t *CreateNamedPipeTest) NonExistentParent() {\n\tt.path = \"\/foo\/bar\/baz\/qux\"\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"no such\")))\n}\n\nfunc (t *CreateNamedPipeTest) NoPermissionsForParent() {\n\tdirpath := path.Join(t.baseDir, \"foo\")\n\tt.path = path.Join(dirpath, \"taco\")\n\n\t\/\/ Parent\n\terr := os.Mkdir(dirpath, 0100)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"permission denied\")))\n}\n\nfunc (t *CreateNamedPipeTest) FileAlreadyExistsWithSameName() {\n\t\/\/ Create\n\terr := ioutil.WriteFile(t.path, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"file exists\")))\n}\n\nfunc (t *CreateNamedPipeTest) CreatesCorrectEntry() {\n\tt.path = path.Join(t.baseDir, \"taco\")\n\tt.perms = 0674 \/\/ Conflicts with default umask\n\n\t\/\/ Call\n\tt.call()\n\tAssertEq(nil, t.err)\n\n\t\/\/ List\n\tentries := t.list()\n\n\tAssertThat(entries, ElementsAre(Any()))\n\tentry := entries[0]\n\n\tExpectEq(fs.TypeNamedPipe, entry.Type)\n\tExpectEq(\"taco\", entry.Name)\n\tExpectEq(0674, entry.Permissions)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CreateSymlink\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype CreateSymlinkTest struct {\n\tfileSystemTest\n\n\ttarget string\n\tsource string\n\tperms  os.FileMode\n\n\terr error\n}\n\nfunc init() { RegisterTestSuite(&CreateSymlinkTest{}) }\n\nfunc (t *CreateSymlinkTest) SetUp(i *TestInfo) {\n\t\/\/ Common\n\tt.fileSystemTest.SetUp(i)\n\n\t\/\/ Set up defaults.\n\tt.source = path.Join(t.baseDir, \"taco\")\n\tt.target = \"\/foo\/bar\"\n\tt.perms = 0644\n}\n\nfunc (t *CreateSymlinkTest) call() {\n\tt.err = t.fileSystem.CreateSymlink(t.target, t.source, t.perms)\n}\n\nfunc (t *CreateSymlinkTest) list() []*fs.DirectoryEntry {\n\tentries, err := t.fileSystem.ReadDir(t.baseDir)\n\tAssertEq(nil, err)\n\treturn entries\n}\n\nfunc (t *CreateSymlinkTest) NonExistentParent() {\n\tt.source = \"\/foo\/bar\/baz\/qux\"\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"qux\")))\n\tExpectThat(t.err, Error(HasSubstr(\"no such\")))\n}\n\nfunc (t *CreateSymlinkTest) NoPermissionsForParent() {\n\tdirpath := path.Join(t.baseDir, \"foo\")\n\tt.source = path.Join(dirpath, \"taco\")\n\n\t\/\/ Parent\n\terr := os.Mkdir(dirpath, 0100)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"foo\")))\n\tExpectThat(t.err, Error(HasSubstr(\"permission denied\")))\n}\n\nfunc (t *CreateSymlinkTest) FileAlreadyExistsWithSameName() {\n\t\/\/ Create\n\terr := ioutil.WriteFile(t.source, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"file exists\")))\n}\n\nfunc (t *CreateSymlinkTest) CreatesCorrectEntry() {\n\tt.source = path.Join(t.baseDir, \"taco\")\n\tt.target = \"\/burrito\"\n\tt.perms = 0674 \/\/ Conflicts with default umask\n\n\t\/\/ Call\n\tt.call()\n\tAssertEq(nil, t.err)\n\n\t\/\/ List\n\tentries := t.list()\n\n\tAssertThat(entries, ElementsAre(Any()))\n\tentry := entries[0]\n\n\tExpectEq(fs.TypeSymlink, entry.Type)\n\tExpectEq(\"taco\", entry.Name)\n\tExpectEq(\"\/burrito\", entry.Target)\n\tExpectEq(0674, entry.Permissions)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CreateHardLink\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype CreateHardLinkTest struct {\n\tfileSystemTest\n\n\ttarget string\n\tsource string\n\n\terr error\n}\n\nfunc init() { RegisterTestSuite(&CreateHardLinkTest{}) }\n\nfunc (t *CreateHardLinkTest) SetUp(i *TestInfo) {\n\t\/\/ Common\n\tt.fileSystemTest.SetUp(i)\n\n\t\/\/ Set up defaults.\n\tt.source = path.Join(t.baseDir, \"taco\")\n\tt.target = path.Join(t.baseDir, \"burrito\")\n}\n\nfunc (t *CreateHardLinkTest) call() {\n\tt.err = t.fileSystem.CreateHardLink(t.target, t.source)\n}\n\nfunc (t *CreateHardLinkTest) list() []*fs.DirectoryEntry {\n\tentries, err := t.fileSystem.ReadDir(t.baseDir)\n\tAssertEq(nil, err)\n\treturn entries\n}\n\nfunc (t *CreateHardLinkTest) NonExistentParent() {\n\tt.source = \"\/foo\/bar\/baz\/qux\"\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"qux\")))\n\tExpectThat(t.err, Error(HasSubstr(\"no such\")))\n}\n\nfunc (t *CreateHardLinkTest) NoPermissionsForParent() {\n\tdirpath := path.Join(t.baseDir, \"foo\")\n\tt.source = path.Join(dirpath, \"taco\")\n\n\t\/\/ Create target\n\terr := ioutil.WriteFile(t.target, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Parent\n\terr = os.Mkdir(dirpath, 0100)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"foo\")))\n\tExpectThat(t.err, Error(HasSubstr(\"permission denied\")))\n}\n\nfunc (t *CreateHardLinkTest) TargetDoesntExist() {\n\tt.source = path.Join(t.baseDir, \"taco\")\n\tt.target = \"\/burrito\"\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"burrito\")))\n\tExpectThat(t.err, Error(HasSubstr(\"no such\")))\n\tExpectThat(t.err, Error(HasSubstr(\"file\")))\n}\n\nfunc (t *CreateHardLinkTest) FileAlreadyExistsWithSameName() {\n\t\/\/ Create source\n\terr := ioutil.WriteFile(t.source, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Create target\n\terr = ioutil.WriteFile(t.target, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\n\tExpectThat(t.err, Error(HasSubstr(\"file exists\")))\n}\n\nfunc (t *CreateHardLinkTest) CreatesCorrectEntry() {\n\tt.source = path.Join(t.baseDir, \"taco\")\n\tt.target = path.Join(t.baseDir, \"burrito\")\n\n\t\/\/ Create target\n\terr := ioutil.WriteFile(t.target, []byte{}, 0644)\n\tAssertEq(nil, err)\n\n\t\/\/ Call\n\tt.call()\n\tAssertEq(nil, t.err)\n\n\t\/\/ List\n\tentries := t.list()\n\n\tAssertThat(entries, ElementsAre(Any(), Any()))\n\n\tentry0 := entries[0]\n\tExpectEq(fs.TypeFile, entry0.Type)\n\tExpectEq(\"burrito\", entry0.Name)\n\n\tentry1 := entries[1]\n\tExpectEq(fs.TypeFile, entry1.Type)\n\tExpectEq(\"taco\", entry1.Name)\n\n\tAssertNe(0, entry0.ContainingDevice)\n\tExpectEq(entry1.ContainingDevice, entry0.ContainingDevice)\n\n\tAssertNe(0, entry0.Inode)\n\tExpectEq(entry1.Inode, entry0.Inode)\n}\n<|endoftext|>"}
{"text":"<commit_before>package core\n\nimport (\n\t\"archive\/tar\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fsouza\/go-dockerclient\"\n)\n\ntype Docker struct {\n\tendPoint string\n\tenv      *Environment\n\tclient   *docker.Client\n}\n\nfunc NewDocker(endPoint string, env *Environment) (*Docker, error) {\n\tDebug(\"Connected to docker\", \"end-point\", endPoint)\n\n\tvar c *docker.Client\n\tvar err error\n\tif env != nil && env.CertPath != \"\" {\n\t\tc, err = docker.NewTLSClient(\n\t\t\tendPoint,\n\t\t\tenv.CertPath+\"\/cert.pem\",\n\t\t\tenv.CertPath+\"\/key.pem\",\n\t\t\tenv.CertPath+\"\/ca.pem\",\n\t\t)\n\t} else {\n\t\tc, err = docker.NewClient(endPoint)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Docker{client: c, endPoint: endPoint, env: env}, nil\n}\n\nfunc (d *Docker) Deploy(p *Project, rev Revision, dockerfile *Dockerfile, output io.Writer, force bool) error {\n\tDebug(\"Deploying dockerfile\", \"project\", p, \"revision\", rev, \"end-point\", d.endPoint)\n\tif err := d.Clean(p); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.BuildImage(p, rev, dockerfile, output); err != nil {\n\t\treturn err\n\t}\n\n\treturn d.Run(p, rev)\n}\n\nfunc (d *Docker) Clean(p *Project) error {\n\tif err := d.cleanContainers(p); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.cleanImages(p); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) cleanContainers(p *Project) error {\n\tl, err := d.ListContainers(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tDebug(\"Cleaning containers\", \"project\", p, \"count\", len(l), \"end-point\", d.endPoint)\n\tfor _, c := range l {\n\t\tif !c.IsRunning() {\n\t\t\tcontinue\n\t\t}\n\n\t\tDebug(\"Stoping container and image\", \"project\", p, \"container\", c.GetShortId(), \"end-point\", d.endPoint)\n\t\tif err := d.killContainer(c); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tDebug(\"Removing container\", \"project\", p, \"container\", c.GetShortId(), \"end-point\", d.endPoint)\n\t\tif err := d.removeContainer(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) killContainer(c *Container) error {\n\tkopts := docker.KillContainerOptions{ID: c.ID}\n\tif err := d.client.KillContainer(kopts); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) removeContainer(c *Container) error {\n\tropts := docker.RemoveContainerOptions{ID: c.ID}\n\tif err := d.client.RemoveContainer(ropts); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) cleanImages(p *Project) error {\n\tl, err := d.ListImages(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkeep := p.History\n\tif keep < 0 {\n\t\tkeep = 0\n\t}\n\n\tcount := len(l)\n\tif count < keep {\n\t\treturn nil\n\t}\n\n\tDebug(\"Removing old images\", \"project\", p, \"count\", count-keep, \"end-point\", d.endPoint)\n\tfor _, i := range l[:count-keep] {\n\t\tDebug(\"Removing image\", \"project\", p, \"image\", i.ID, \"end-point\", d.endPoint)\n\t\tif err := d.removeImage(i); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) removeImage(i *Image) error {\n\tif err := d.client.RemoveImage(i.ID); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) ListContainers(p *Project) ([]*Container, error) {\n\tDebug(\"Retrieving current containers\", \"project\", p, \"end-point\", d.endPoint)\n\n\tl, err := d.client.ListContainers(docker.ListContainersOptions{\n\t\tAll: true,\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr := make([]*Container, 0)\n\tfor _, c := range l {\n\t\tcontainer := &Container{\n\t\t\tImage:          ImageId(c.Image),\n\t\t\tAPIContainers:  c,\n\t\t\tDockerEndPoint: d.endPoint,\n\t\t}\n\n\t\tif container.BelongsTo(p) {\n\t\t\tr = append(r, container)\n\t\t}\n\t}\n\n\tsort.Sort(ContainersByCreated(r))\n\n\treturn r, nil\n}\n\nfunc (d *Docker) ListImages(p *Project) ([]*Image, error) {\n\tDebug(\"Retrieving current containers\", \"project\", p, \"end-point\", d.endPoint)\n\n\tl, err := d.client.ListImages(docker.ListImagesOptions{All: true})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr := make([]*Image, 0)\n\tfor _, i := range l {\n\t\timage := &Image{\n\t\t\tAPIImages:      i,\n\t\t\tDockerEndPoint: d.endPoint,\n\t\t}\n\n\t\tif image.BelongsTo(p) {\n\t\t\tr = append(r, image)\n\t\t}\n\t}\n\n\tsort.Sort(ImagesByCreated(r))\n\n\treturn r, nil\n}\n\nfunc (d *Docker) BuildImage(\n\tp *Project, rev Revision, dockerfile *Dockerfile, output io.Writer,\n) error {\n\tDebug(\"Building image\", \"project\", p, \"revision\", rev, \"end-point\", d.endPoint)\n\n\tinput := bytes.NewBuffer(nil)\n\tif err := d.buildTar(p, dockerfile.Get(), input); err != nil {\n\t\treturn err\n\t}\n\n\timage := d.getImageName(p, rev)\n\topts := docker.BuildImageOptions{\n\t\tName:           string(image),\n\t\tNoCache:        p.NoCache,\n\t\tRmTmpContainer: p.NoCache,\n\t\tInputStream:    input,\n\t\tOutputStream:   output,\n\t}\n\n\treturn d.client.BuildImage(opts)\n}\n\nfunc (d *Docker) Run(p *Project, rev Revision) error {\n\tDebug(\"Creating container from image\", \"project\", p, \"revision\", rev, \"end-point\", d.endPoint)\n\tc, err := d.createContainer(p, d.getImageName(p, rev))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tInfo(\"Running new container\",\n\t\t\"project\", p,\n\t\t\"revision\", rev.GetShort(),\n\t\t\"container\", c.GetShortId(),\n\t\t\"end-point\", d.endPoint,\n\t)\n\n\tif err := d.startContainer(p, c); err != nil {\n\t\treturn err\n\t}\n\n\treturn d.restartLinkedContainers(p)\n}\n\nfunc (d *Docker) getImageName(p *Project, rev Revision) ImageId {\n\tc := rev.String()\n\tif p.UseShortRevisions {\n\t\tc = rev.GetShort()\n\t}\n\n\treturn ImageId(fmt.Sprintf(\"%s:%s\", p.Name, c))\n}\n\nfunc (d *Docker) createContainer(p *Project, image ImageId) (*Container, error) {\n\tc, err := d.client.CreateContainer(docker.CreateContainerOptions{\n\t\tName: p.Name,\n\t\tConfig: &docker.Config{\n\t\t\tImage: string(image),\n\t\t},\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Container{Image: image, APIContainers: docker.APIContainers{ID: c.ID}}, nil\n}\n\nfunc (d *Docker) startContainer(p *Project, c *Container) error {\n\tports, err := d.formatPorts(p.Ports)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trestartPolicy, err := d.formatRestartPolicy(p.Restart)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn d.client.StartContainer(c.ID, &docker.HostConfig{\n\t\tPortBindings:  ports,\n\t\tRestartPolicy: restartPolicy,\n\t\tLinks:         d.formatLinks(p.Links),\n\t})\n}\n\nfunc (d *Docker) formatLinks(links map[string]*Link) []string {\n\tr := make([]string, 0)\n\tfor _, link := range links {\n\t\tr = append(r, link.String())\n\t}\n\n\treturn r\n}\n\nfunc (d *Docker) formatRestartPolicy(restart string) (policy docker.RestartPolicy, err error) {\n\tvalues := strings.SplitN(restart, \":\", 2)\n\tif values[0] == \"no\" || restart == \"\" {\n\t\tpolicy = docker.NeverRestart()\n\t\treturn\n\t}\n\n\tif values[0] == \"always\" {\n\t\tpolicy = docker.AlwaysRestart()\n\t\treturn\n\t}\n\n\tif values[0] == \"on-failure\" {\n\t\tvar maxRetry int\n\t\tmaxRetry, err = strconv.Atoi(values[1])\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tpolicy = docker.RestartOnFailure(maxRetry)\n\t\treturn\n\t}\n\n\terr = errors.New(fmt.Sprintf(\"Malformed restart policy %q\", restart))\n\treturn\n}\n\nfunc (d *Docker) formatPorts(ports []string) (map[docker.Port][]docker.PortBinding, error) {\n\tr := make(map[docker.Port][]docker.PortBinding, 0)\n\tfor _, p := range ports {\n\t\tguest, host, err := d.formatPort(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif _, ok := r[guest]; !ok {\n\t\t\tr[guest] = make([]docker.PortBinding, 0)\n\t\t}\n\n\t\tr[guest] = append(r[guest], host)\n\t}\n\n\treturn r, nil\n}\n\n\/\/ <host_interface>:<host_port>:<container_port>\/<proto>\nfunc (d *Docker) formatPort(port string) (guest docker.Port, host docker.PortBinding, err error) {\n\tp1 := strings.SplitN(port, \"@\", 2)\n\tif len(p1) == 2 && d.env != nil && d.env.Name != p1[1] {\n\t\treturn\n\t}\n\n\tp2 := strings.SplitN(p1[0], \"\/\", 2)\n\tp3 := strings.SplitN(p2[0], \":\", 3)\n\n\tif len(p2) != 2 || len(p3) != 3 {\n\t\terr = errors.New(fmt.Sprintf(\"Malformed port %q\", port))\n\t\treturn\n\t}\n\n\tguest = docker.Port(fmt.Sprintf(\"%s\/%s\", p3[2], p2[1]))\n\thost = docker.PortBinding{\n\t\tHostIP:   p3[0],\n\t\tHostPort: p3[1],\n\t}\n\n\treturn\n}\n\nfunc (d *Docker) buildTar(p *Project, dockerfile []byte, buf *bytes.Buffer) error {\n\tt := time.Now()\n\n\ttr := tar.NewWriter(buf)\n\ttr.WriteHeader(&tar.Header{\n\t\tName:       \"Dockerfile\",\n\t\tSize:       int64(len(dockerfile)),\n\t\tModTime:    t,\n\t\tAccessTime: t,\n\t\tChangeTime: t,\n\t})\n\n\tif _, err := tr.Write(dockerfile); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, file := range p.Files {\n\t\tif err := d.addFileToTar(file, tr); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttr.Close()\n\treturn nil\n}\n\nfunc (d *Docker) addFileToTar(file string, tr *tar.Writer) error {\n\tcontent, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfInfo, err := os.Lstat(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\th, err := tar.FileInfoHeader(fInfo, \"\")\n\th.Name = path.Base(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := tr.WriteHeader(h); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := tr.Write(content); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) restartLinkedContainers(p *Project) error {\n\tfailed := false\n\tfor _, linked := range p.LinkedBy {\n\t\tlist, err := d.ListContainers(linked)\n\t\tif err != nil {\n\t\t\tfailed = true\n\t\t\tError(err.Error(), \"project\", p)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, lc := range list {\n\t\t\tInfo(\"Restarting linked container\", \"project\", linked, \"container\", lc.GetShortId())\n\t\t\tif err := d.restartContainer(linked, lc); err != nil {\n\t\t\t\tfailed = true\n\t\t\t\tError(\"Unable to restart container\", \"project\", linked, \"container\", lc.GetShortId())\n\t\t\t}\n\t\t}\n\t}\n\n\tif failed {\n\t\treturn errors.New(\"Unable to restart one or more containers\")\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) restartContainer(p *Project, c *Container) error {\n\tif !c.IsRunning() {\n\t\treturn nil\n\t}\n\n\tif err := d.killContainer(c); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.startContainer(p, c); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>Deploy: don't clean containers until the new image is built.<commit_after>package core\n\nimport (\n\t\"archive\/tar\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fsouza\/go-dockerclient\"\n)\n\ntype Docker struct {\n\tendPoint string\n\tenv      *Environment\n\tclient   *docker.Client\n}\n\nfunc NewDocker(endPoint string, env *Environment) (*Docker, error) {\n\tDebug(\"Connected to docker\", \"end-point\", endPoint)\n\n\tvar c *docker.Client\n\tvar err error\n\tif env != nil && env.CertPath != \"\" {\n\t\tc, err = docker.NewTLSClient(\n\t\t\tendPoint,\n\t\t\tenv.CertPath+\"\/cert.pem\",\n\t\t\tenv.CertPath+\"\/key.pem\",\n\t\t\tenv.CertPath+\"\/ca.pem\",\n\t\t)\n\t} else {\n\t\tc, err = docker.NewClient(endPoint)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Docker{client: c, endPoint: endPoint, env: env}, nil\n}\n\nfunc (d *Docker) Deploy(p *Project, rev Revision, dockerfile *Dockerfile, output io.Writer, force bool) error {\n\tDebug(\"Deploying dockerfile\", \"project\", p, \"revision\", rev, \"end-point\", d.endPoint)\n\n\tif err := d.cleanImages(p); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.BuildImage(p, rev, dockerfile, output); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.cleanContainers(p); err != nil {\n\t\treturn err\n\t}\n\n\treturn d.Run(p, rev)\n}\n\nfunc (d *Docker) Clean(p *Project) error {\n\tif err := d.cleanContainers(p); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.cleanImages(p); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) cleanContainers(p *Project) error {\n\tl, err := d.ListContainers(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tDebug(\"Cleaning containers\", \"project\", p, \"count\", len(l), \"end-point\", d.endPoint)\n\tfor _, c := range l {\n\t\tif !c.IsRunning() {\n\t\t\tcontinue\n\t\t}\n\n\t\tDebug(\"Stoping container and image\", \"project\", p, \"container\", c.GetShortId(), \"end-point\", d.endPoint)\n\t\tif err := d.killContainer(c); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tDebug(\"Removing container\", \"project\", p, \"container\", c.GetShortId(), \"end-point\", d.endPoint)\n\t\tif err := d.removeContainer(c); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) killContainer(c *Container) error {\n\tkopts := docker.KillContainerOptions{ID: c.ID}\n\tif err := d.client.KillContainer(kopts); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) removeContainer(c *Container) error {\n\tropts := docker.RemoveContainerOptions{ID: c.ID}\n\tif err := d.client.RemoveContainer(ropts); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) cleanImages(p *Project) error {\n\tl, err := d.ListImages(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkeep := p.History\n\tif keep < 0 {\n\t\tkeep = 0\n\t}\n\n\tcount := len(l)\n\tif count < keep {\n\t\treturn nil\n\t}\n\n\tDebug(\"Removing old images\", \"project\", p, \"count\", count-keep, \"end-point\", d.endPoint)\n\tfor _, i := range l[:count-keep] {\n\t\tDebug(\"Removing image\", \"project\", p, \"image\", i.ID, \"end-point\", d.endPoint)\n\t\tif err := d.removeImage(i); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) removeImage(i *Image) error {\n\tif err := d.client.RemoveImage(i.ID); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) ListContainers(p *Project) ([]*Container, error) {\n\tDebug(\"Retrieving current containers\", \"project\", p, \"end-point\", d.endPoint)\n\n\tl, err := d.client.ListContainers(docker.ListContainersOptions{\n\t\tAll: true,\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr := make([]*Container, 0)\n\tfor _, c := range l {\n\t\tcontainer := &Container{\n\t\t\tImage:          ImageId(c.Image),\n\t\t\tAPIContainers:  c,\n\t\t\tDockerEndPoint: d.endPoint,\n\t\t}\n\n\t\tif container.BelongsTo(p) {\n\t\t\tr = append(r, container)\n\t\t}\n\t}\n\n\tsort.Sort(ContainersByCreated(r))\n\n\treturn r, nil\n}\n\nfunc (d *Docker) ListImages(p *Project) ([]*Image, error) {\n\tDebug(\"Retrieving current containers\", \"project\", p, \"end-point\", d.endPoint)\n\n\tl, err := d.client.ListImages(docker.ListImagesOptions{All: true})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr := make([]*Image, 0)\n\tfor _, i := range l {\n\t\timage := &Image{\n\t\t\tAPIImages:      i,\n\t\t\tDockerEndPoint: d.endPoint,\n\t\t}\n\n\t\tif image.BelongsTo(p) {\n\t\t\tr = append(r, image)\n\t\t}\n\t}\n\n\tsort.Sort(ImagesByCreated(r))\n\n\treturn r, nil\n}\n\nfunc (d *Docker) BuildImage(\n\tp *Project, rev Revision, dockerfile *Dockerfile, output io.Writer,\n) error {\n\tDebug(\"Building image\", \"project\", p, \"revision\", rev, \"end-point\", d.endPoint)\n\n\tinput := bytes.NewBuffer(nil)\n\tif err := d.buildTar(p, dockerfile.Get(), input); err != nil {\n\t\treturn err\n\t}\n\n\timage := d.getImageName(p, rev)\n\topts := docker.BuildImageOptions{\n\t\tName:           string(image),\n\t\tNoCache:        p.NoCache,\n\t\tRmTmpContainer: p.NoCache,\n\t\tInputStream:    input,\n\t\tOutputStream:   output,\n\t}\n\n\treturn d.client.BuildImage(opts)\n}\n\nfunc (d *Docker) Run(p *Project, rev Revision) error {\n\tDebug(\"Creating container from image\", \"project\", p, \"revision\", rev, \"end-point\", d.endPoint)\n\tc, err := d.createContainer(p, d.getImageName(p, rev))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tInfo(\"Running new container\",\n\t\t\"project\", p,\n\t\t\"revision\", rev.GetShort(),\n\t\t\"container\", c.GetShortId(),\n\t\t\"end-point\", d.endPoint,\n\t)\n\n\tif err := d.startContainer(p, c); err != nil {\n\t\treturn err\n\t}\n\n\treturn d.restartLinkedContainers(p)\n}\n\nfunc (d *Docker) getImageName(p *Project, rev Revision) ImageId {\n\tc := rev.String()\n\tif p.UseShortRevisions {\n\t\tc = rev.GetShort()\n\t}\n\n\treturn ImageId(fmt.Sprintf(\"%s:%s\", p.Name, c))\n}\n\nfunc (d *Docker) createContainer(p *Project, image ImageId) (*Container, error) {\n\tc, err := d.client.CreateContainer(docker.CreateContainerOptions{\n\t\tName: p.Name,\n\t\tConfig: &docker.Config{\n\t\t\tImage: string(image),\n\t\t},\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Container{Image: image, APIContainers: docker.APIContainers{ID: c.ID}}, nil\n}\n\nfunc (d *Docker) startContainer(p *Project, c *Container) error {\n\tports, err := d.formatPorts(p.Ports)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trestartPolicy, err := d.formatRestartPolicy(p.Restart)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn d.client.StartContainer(c.ID, &docker.HostConfig{\n\t\tPortBindings:  ports,\n\t\tRestartPolicy: restartPolicy,\n\t\tLinks:         d.formatLinks(p.Links),\n\t})\n}\n\nfunc (d *Docker) formatLinks(links map[string]*Link) []string {\n\tr := make([]string, 0)\n\tfor _, link := range links {\n\t\tr = append(r, link.String())\n\t}\n\n\treturn r\n}\n\nfunc (d *Docker) formatRestartPolicy(restart string) (policy docker.RestartPolicy, err error) {\n\tvalues := strings.SplitN(restart, \":\", 2)\n\tif values[0] == \"no\" || restart == \"\" {\n\t\tpolicy = docker.NeverRestart()\n\t\treturn\n\t}\n\n\tif values[0] == \"always\" {\n\t\tpolicy = docker.AlwaysRestart()\n\t\treturn\n\t}\n\n\tif values[0] == \"on-failure\" {\n\t\tvar maxRetry int\n\t\tmaxRetry, err = strconv.Atoi(values[1])\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tpolicy = docker.RestartOnFailure(maxRetry)\n\t\treturn\n\t}\n\n\terr = errors.New(fmt.Sprintf(\"Malformed restart policy %q\", restart))\n\treturn\n}\n\nfunc (d *Docker) formatPorts(ports []string) (map[docker.Port][]docker.PortBinding, error) {\n\tr := make(map[docker.Port][]docker.PortBinding, 0)\n\tfor _, p := range ports {\n\t\tguest, host, err := d.formatPort(p)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif _, ok := r[guest]; !ok {\n\t\t\tr[guest] = make([]docker.PortBinding, 0)\n\t\t}\n\n\t\tr[guest] = append(r[guest], host)\n\t}\n\n\treturn r, nil\n}\n\n\/\/ <host_interface>:<host_port>:<container_port>\/<proto>\nfunc (d *Docker) formatPort(port string) (guest docker.Port, host docker.PortBinding, err error) {\n\tp1 := strings.SplitN(port, \"@\", 2)\n\tif len(p1) == 2 && d.env != nil && d.env.Name != p1[1] {\n\t\treturn\n\t}\n\n\tp2 := strings.SplitN(p1[0], \"\/\", 2)\n\tp3 := strings.SplitN(p2[0], \":\", 3)\n\n\tif len(p2) != 2 || len(p3) != 3 {\n\t\terr = errors.New(fmt.Sprintf(\"Malformed port %q\", port))\n\t\treturn\n\t}\n\n\tguest = docker.Port(fmt.Sprintf(\"%s\/%s\", p3[2], p2[1]))\n\thost = docker.PortBinding{\n\t\tHostIP:   p3[0],\n\t\tHostPort: p3[1],\n\t}\n\n\treturn\n}\n\nfunc (d *Docker) buildTar(p *Project, dockerfile []byte, buf *bytes.Buffer) error {\n\tt := time.Now()\n\n\ttr := tar.NewWriter(buf)\n\ttr.WriteHeader(&tar.Header{\n\t\tName:       \"Dockerfile\",\n\t\tSize:       int64(len(dockerfile)),\n\t\tModTime:    t,\n\t\tAccessTime: t,\n\t\tChangeTime: t,\n\t})\n\n\tif _, err := tr.Write(dockerfile); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, file := range p.Files {\n\t\tif err := d.addFileToTar(file, tr); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttr.Close()\n\treturn nil\n}\n\nfunc (d *Docker) addFileToTar(file string, tr *tar.Writer) error {\n\tcontent, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfInfo, err := os.Lstat(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\th, err := tar.FileInfoHeader(fInfo, \"\")\n\th.Name = path.Base(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := tr.WriteHeader(h); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := tr.Write(content); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) restartLinkedContainers(p *Project) error {\n\tfailed := false\n\tfor _, linked := range p.LinkedBy {\n\t\tlist, err := d.ListContainers(linked)\n\t\tif err != nil {\n\t\t\tfailed = true\n\t\t\tError(err.Error(), \"project\", p)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, lc := range list {\n\t\t\tInfo(\"Restarting linked container\", \"project\", linked, \"container\", lc.GetShortId())\n\t\t\tif err := d.restartContainer(linked, lc); err != nil {\n\t\t\t\tfailed = true\n\t\t\t\tError(\"Unable to restart container\", \"project\", linked, \"container\", lc.GetShortId())\n\t\t\t}\n\t\t}\n\t}\n\n\tif failed {\n\t\treturn errors.New(\"Unable to restart one or more containers\")\n\t}\n\n\treturn nil\n}\n\nfunc (d *Docker) restartContainer(p *Project, c *Container) error {\n\tif !c.IsRunning() {\n\t\treturn nil\n\t}\n\n\tif err := d.killContainer(c); err != nil {\n\t\treturn err\n\t}\n\n\tif err := d.startContainer(p, c); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package members\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/mypurecloud\/platform-client-sdk-cli\/build\/gc\/logger\"\n\t\"github.com\/mypurecloud\/platform-client-sdk-cli\/build\/gc\/models\"\n\t\"github.com\/mypurecloud\/platform-client-sdk-cli\/build\/gc\/retry\"\n\t\"github.com\/mypurecloud\/platform-client-sdk-cli\/build\/gc\/utils\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nfunc init() {\n\tnote := \"Note: The 'version' value from the command input will be ignored and the latest version value will be retrieved from the API instead\"\n\taddCmd.SetHelpTemplate(fmt.Sprintf(\"%s\\nOperation:\\n  %s %s\\n\\n%s\\n\", addCmd.UsageTemplate(), addMembersCommand.Method, addMembersCommand.Path, note))\n\tutils.AddFileFlagIfUpsert(addCmd.Flags(), addMembersCommand.Method)\n\tmembersCmd.AddCommand(addCmd)\n}\n\ntype groupMembers struct {\n\tVersion int `json:\"version\"`\n}\n\ntype addGroupMembersBody struct {\n\tMemberIds []string `json:\"memberIds\"`\n\tVersion   int      `json:\"version\"`\n}\n\nvar (\n\taddMembersCommand = models.HandWrittenCommand{\n\t\tPath:   \"\/api\/v2\/groups\/{groupId}\/members\",\n\t\tMethod: http.MethodPost,\n\t}\n\tgetMembersCommand = models.HandWrittenCommand{\n\t\tPath:   \"\/api\/v2\/groups\/{groupId}\/members\",\n\t\tMethod: http.MethodGet,\n\t}\n)\n\nvar addCmd = &cobra.Command{\n\tUse:   \"add [groupId]\",\n\tShort: \"Add members\",\n\tLong:  `Add members`,\n\tArgs:  utils.DetermineArgs([]string{\"groupId\"}),\n\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tgroupId, args := args[0], args[1:]\n\t\tpath := strings.Replace(addMembersCommand.Path, \"{groupId}\", fmt.Sprintf(\"%v\", groupId), -1)\n\n\t\tcurrentVersion := getGroupVersion(path)\n\n\t\tinputData := utils.ResolveInputData(cmd)\n\t\tbody := &addGroupMembersBody{}\n\t\terr := json.Unmarshal([]byte(inputData), body)\n\t\tif err != nil {\n\t\t\tlogger.Fatal(err)\n\t\t}\n\n\t\tbody.Version = currentVersion\n\t\tbodyString, _ := json.Marshal(body)\n\n\t\tretryFunc := retry.RetryWithData(path, string(bodyString), CommandService.Post)\n\t\t\/\/ TODO read from config file\n\t\tretryConfig := &retry.RetryConfiguration{\n\t\t\tRetryWaitMin: 5 * time.Second,\n\t\t\tRetryWaitMax: 60 * time.Second,\n\t\t\tRetryMax:     20,\n\t\t}\n\t\tresults, err := retryFunc(retryConfig)\n\t\tif err != nil {\n\t\t\tlogger.Fatal(err)\n\t\t}\n\n\t\tutils.Render(results)\n\t},\n}\n\nfunc getGroupVersion(path string) int {\n\tretryFunc := CommandService.DetermineAction(getMembersCommand.Method, \"get\", path, getMembersCommand.Path)\n\tretryConfig := &retry.RetryConfiguration{\n\t\tRetryWaitMin: 5 * time.Second,\n\t\tRetryWaitMax: 60 * time.Second,\n\t\tRetryMax:     20,\n\t}\n\tresults, err := retryFunc(retryConfig)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\tgroupMember := make([]groupMembers, 0)\n\terr = json.Unmarshal([]byte(results), &groupMember)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\treturn groupMember[0].Version\n}\n<commit_msg>Fixing bug in custom add groups members command due to using wrong API<commit_after>package members\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/mypurecloud\/platform-client-sdk-cli\/build\/gc\/logger\"\n\t\"github.com\/mypurecloud\/platform-client-sdk-cli\/build\/gc\/models\"\n\t\"github.com\/mypurecloud\/platform-client-sdk-cli\/build\/gc\/retry\"\n\t\"github.com\/mypurecloud\/platform-client-sdk-cli\/build\/gc\/utils\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nfunc init() {\n\tnote := \"Note: The 'version' value from the command input will be ignored and the latest version value will be retrieved from the API instead\"\n\taddCmd.SetHelpTemplate(fmt.Sprintf(\"%s\\nOperation:\\n  %s %s\\n\\n%s\\n\", addCmd.UsageTemplate(), addMembersCommand.Method, addMembersCommand.Path, note))\n\tutils.AddFileFlagIfUpsert(addCmd.Flags(), addMembersCommand.Method)\n\tmembersCmd.AddCommand(addCmd)\n}\n\ntype group struct {\n\tVersion int `json:\"version\"`\n}\n\ntype addGroupMembersBody struct {\n\tMemberIds []string `json:\"memberIds\"`\n\tVersion   int      `json:\"version\"`\n}\n\nvar (\n\taddMembersCommand = models.HandWrittenCommand{\n\t\tPath:   \"\/api\/v2\/groups\/{groupId}\/members\",\n\t\tMethod: http.MethodPost,\n\t}\n\tgetMembersCommand = models.HandWrittenCommand{\n\t\tPath:   \"\/api\/v2\/groups\/{groupId}\",\n\t\tMethod: http.MethodGet,\n\t}\n)\n\nvar addCmd = &cobra.Command{\n\tUse:   \"add [groupId]\",\n\tShort: \"Add members\",\n\tLong:  `Add members`,\n\tArgs:  utils.DetermineArgs([]string{\"groupId\"}),\n\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tgroupId, args := args[0], args[1:]\n\t\tpath := strings.Replace(getMembersCommand.Path, \"{groupId}\", fmt.Sprintf(\"%v\", groupId), -1)\n\n\t\tcurrentVersion := getGroupVersion(path)\n\n\t\tinputData := utils.ResolveInputData(cmd)\n\t\tbody := &addGroupMembersBody{}\n\t\terr := json.Unmarshal([]byte(inputData), body)\n\t\tif err != nil {\n\t\t\tlogger.Fatal(err)\n\t\t}\n\n\t\tbody.Version = currentVersion\n\t\tbodyString, _ := json.Marshal(body)\n\n\t\tpath = strings.Replace(addMembersCommand.Path, \"{groupId}\", fmt.Sprintf(\"%v\", groupId), -1)\n\t\tretryFunc := retry.RetryWithData(path, string(bodyString), CommandService.Post)\n\t\t\/\/ TODO read from config file\n\t\tretryConfig := &retry.RetryConfiguration{\n\t\t\tRetryWaitMin: 5 * time.Second,\n\t\t\tRetryWaitMax: 60 * time.Second,\n\t\t\tRetryMax:     20,\n\t\t}\n\t\tresults, err := retryFunc(retryConfig)\n\t\tif err != nil {\n\t\t\tlogger.Fatal(err)\n\t\t}\n\n\t\tutils.Render(results)\n\t},\n}\n\nfunc getGroupVersion(path string) int {\n\tretryFunc := CommandService.DetermineAction(getMembersCommand.Method, \"get\", path, getMembersCommand.Path)\n\tretryConfig := &retry.RetryConfiguration{\n\t\tRetryWaitMin: 5 * time.Second,\n\t\tRetryWaitMax: 60 * time.Second,\n\t\tRetryMax:     20,\n\t}\n\tresults, err := retryFunc(retryConfig)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\tgroupResult := group{}\n\terr = json.Unmarshal([]byte(results), &groupResult)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\treturn groupResult.Version\n}\n<|endoftext|>"}
{"text":"<commit_before>package goCompany\n\nimport \"testing\"\n\nfunc TestGetCompanyInfo(t *testing.T) {\n\tok := 5990130\n\tresult, _ := GetCompanyInfo(\"7736002426\")\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetEmployees(t *testing.T) {\n\tok := 149735376\n\tresult, _ := GetEmployees(\"32357\")\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetIndivEntrep(t *testing.T) {\n\tok := 1\n\tresult, _ := GetIndivEntrep(\"7528374\")\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetCompFounder(t *testing.T) {\n\tok := 5545071\n\tresult, _ := GetCompFounder(\"2191023\")\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetDepComp(t *testing.T) {\n\tok := 1425227\n\tresult, _ := GetDepComp(\"7030\")\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetPerson(t *testing.T) {\n\tok := \"АЛЕКСЕЙ\"\n\tresult, _ := GetPerson(\"2191023\")\n\tif result.FirstName != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetPositions(t *testing.T) {\n\tok := 147863776\n\tresult, _ := GetPositions(\"2191023\")\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetIDData(t *testing.T) {\n\tok := 7030\n\tresult, _ := GetIDData(\"7030\")\n\tif result.ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetFounders(t *testing.T) {\n\tok := 253175464\n\tresult, _ := GetFounders(\"7030\")\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestResponse(t *testing.T) {\n\tok := []byte(\"[ ]\")\n\tresult := response(\"https:\/\/ru.rus.company\/интеграция\/компании\/\")\n\tif result[0] != ok[0] {\n\t\tt.Fatalf(\"Want %v, but got %v\", result[0], ok[0])\n\t}\n}\n<commit_msg>tests err<commit_after>package goCompany\n\nimport \"testing\"\n\nfunc TestGetCompanyInfo(t *testing.T) {\n\tok := 5990130\n\tresult, err := GetCompanyInfo(\"7736002426\")\n\tif err != nil {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetEmployees(t *testing.T) {\n\tok := 149735376\n\tresult, err := GetEmployees(\"32357\")\n\tif err != nil {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetIndivEntrep(t *testing.T) {\n\tok := 1\n\tresult, _ := GetIndivEntrep(\"7528374\")\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetCompFounder(t *testing.T) {\n\tok := 5545071\n\tresult, _ := GetCompFounder(\"2191023\")\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetDepComp(t *testing.T) {\n\tok := 1425227\n\tresult, _ := GetDepComp(\"7030\")\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetPerson(t *testing.T) {\n\tok := \"АЛЕКСЕЙ\"\n\tresult, _ := GetPerson(\"2191023\")\n\tif result.FirstName != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetPositions(t *testing.T) {\n\tok := 147863776\n\tresult, _ := GetPositions(\"2191023\")\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetIDData(t *testing.T) {\n\tok := 7030\n\tresult, _ := GetIDData(\"7030\")\n\tif result.ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestGetFounders(t *testing.T) {\n\tok := 253175464\n\tresult, _ := GetFounders(\"7030\")\n\tif result[0].ID != ok {\n\t\tt.Fatalf(\"Want %v, but got %v\", result, ok)\n\t}\n}\n\nfunc TestResponse(t *testing.T) {\n\tok := []byte(\"[ ]\")\n\tresult := response(\"https:\/\/ru.rus.company\/интеграция\/компании\/\")\n\tif result[0] != ok[0] {\n\t\tt.Fatalf(\"Want %v, but got %v\", result[0], ok[0])\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Numgrad Authors. All rights reserved.\n\/\/ See the LICENSE file for rights to use this source code.\n\n\/\/ Package typecheck is a Numengrad type checker.\npackage typecheck\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"go\/constant\"\n\tgotoken \"go\/token\"\n\t\"math\/big\"\n\n\t\"numgrad.io\/lang\/expr\"\n\t\"numgrad.io\/lang\/stmt\"\n\t\"numgrad.io\/lang\/tipe\"\n\t\"numgrad.io\/lang\/token\"\n)\n\ntype Checker struct {\n\t\/\/ TODO: we could put these on our AST. Should we?\n\tTypes  map[expr.Expr]tipe.Type\n\tDefs   map[*expr.Ident]*Obj\n\tValues map[expr.Expr]constant.Value\n\n\t\/\/ TODO NamedInfo map[*tipe.Named]NamedInfo\n\n\tcur *Scope\n}\n\n\/\/ TODO type NamedInfo struct {\n\/\/\tObj *Obj\n\/\/\tMethods []*Obj\n\/\/}\n\nfunc New() *Checker {\n\treturn &Checker{\n\t\tTypes:  make(map[expr.Expr]tipe.Type),\n\t\tDefs:   make(map[*expr.Ident]*Obj),\n\t\tValues: make(map[expr.Expr]constant.Value),\n\t\tcur:    &Scope{Objs: make(map[string]*Obj)},\n\t}\n}\n\ntype partialMode int\n\nconst (\n\tmodeInvalid partialMode = iota\n\tmodeVoid\n\tmodeConst\n\tmodeVar\n\tmodeBuiltin\n)\n\ntype partial struct {\n\tmode partialMode\n\ttyp  tipe.Type\n\tval  constant.Value\n\texpr expr.Expr\n}\n\nfunc (c *Checker) errorf(format string, args ...interface{}) {\n\tfmt.Printf(\"typecheck error: %s\\n\", fmt.Sprintf(format, args...))\n}\n\nfunc defaultType(t tipe.Type) tipe.Type {\n\tb, ok := t.(tipe.Basic)\n\tif !ok {\n\t\treturn t\n\t}\n\tswitch b {\n\tcase tipe.UntypedBool:\n\t\treturn tipe.Bool\n\tcase tipe.UntypedInteger:\n\t\treturn tipe.Integer\n\tcase tipe.UntypedFloat:\n\t\treturn tipe.Float\n\t}\n\treturn t\n}\n\nfunc (c *Checker) stmt(s stmt.Stmt) {\n\tswitch s := s.(type) {\n\tcase *stmt.Assign:\n\t\tif len(s.Left) != len(s.Right) {\n\t\t\tpanic(\"TODO artity mismatch, i.e. x, y := f()\")\n\t\t}\n\t\tvar partials []partial\n\t\tfor _, rhs := range s.Right {\n\t\t\tpartials = append(partials, c.expr(rhs))\n\t\t}\n\t\tif s.Decl {\n\t\t\tfor i, lhs := range s.Left {\n\t\t\t\tp := partials[i]\n\t\t\t\tif isUntyped(p.typ) {\n\t\t\t\t\tc.constrainUntyped(&p, defaultType(p.typ))\n\t\t\t\t}\n\t\t\t\tobj := &Obj{Type: partials[i].typ}\n\t\t\t\tc.Defs[lhs.(*expr.Ident)] = obj\n\t\t\t\tc.cur.Objs[lhs.(*expr.Ident).Name] = obj\n\t\t\t}\n\t\t} else {\n\t\t\tfor i, lhs := range s.Left {\n\t\t\t\tp := partials[i]\n\t\t\t\tlhsP := c.expr(lhs)\n\t\t\t\tif isUntyped(p.typ) {\n\t\t\t\t\tc.constrainUntyped(&p, c.Types[lhsP.expr])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"typecheck: unknown stmt %T\", s))\n\t}\n}\n\nfunc (c *Checker) expr(e expr.Expr) (p partial) {\n\t\/\/ TODO more mode adjustment\n\tp = c.exprPartial(e)\n\tif p.mode == modeConst {\n\t\tc.Values[p.expr] = p.val\n\t\tc.Types[p.expr] = p.typ\n\t}\n\treturn p\n}\n\nfunc (c *Checker) exprPartial(e expr.Expr) (p partial) {\n\tfmt.Printf(\"exprPartial(%s)\\n\", e.Sexp())\n\tp.expr = e\n\tswitch e := e.(type) {\n\tcase *expr.Ident:\n\t\tobj := c.cur.LookupRec(e.Name)\n\t\tif obj == nil {\n\t\t\tp.mode = modeInvalid\n\t\t\tc.errorf(\"undeclared identifier: %s\", e.Name)\n\t\t\treturn p\n\t\t}\n\t\tc.Defs[e] = obj \/\/ TODO Defs is more than definitions? rename?\n\t\tp.mode = modeVar\n\t\treturn p\n\tcase *expr.BasicLiteral:\n\t\tp.mode = modeConst\n\t\t\/\/ TODO: use constant.Value in BasicLiteral directly.\n\t\tswitch v := e.Value.(type) {\n\t\tcase *big.Int:\n\t\t\tp.typ = tipe.UntypedInteger\n\t\t\tp.val = constant.MakeFromLiteral(v.String(), gotoken.INT, 0)\n\t\tcase *big.Float:\n\t\t\tp.typ = tipe.UntypedFloat\n\t\t\tp.val = constant.MakeFromLiteral(v.String(), gotoken.FLOAT, 0)\n\t\t}\n\t\treturn p\n\tcase *expr.Binary:\n\t\tleft := c.expr(e.Left)\n\t\tright := c.expr(e.Right)\n\t\tc.constrainUntyped(&left, right.typ)\n\t\tc.constrainUntyped(&right, left.typ)\n\t\tif left.mode == modeInvalid {\n\t\t\treturn left\n\t\t}\n\t\tif right.mode == modeInvalid {\n\t\t\treturn right\n\t\t}\n\t\tleft.expr = e\n\t\t\/\/ TODO check for division by zero\n\t\t\/\/ TODO check for comparison\n\t\tif left.mode == modeConst && right.mode == modeConst {\n\t\t\tleft.val = constant.BinaryOp(left.val, convGoOp(e.Op), right.val)\n\t\t\t\/\/ TODO check rounding\n\t\t}\n\n\t\treturn left\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"expr TODO: %T\", e))\n\t}\n}\n\nfunc convGoOp(op token.Token) gotoken.Token {\n\tswitch op {\n\tcase token.Add:\n\t\treturn gotoken.ADD\n\tcase token.Sub:\n\t\treturn gotoken.SUB\n\tcase token.Mul:\n\t\treturn gotoken.MUL\n\tcase token.Div:\n\t\treturn gotoken.QUO \/\/ TODO: QUO_ASSIGN for int div\n\tcase token.Rem:\n\t\treturn gotoken.REM\n\tcase token.Pow:\n\t\tpanic(\"TODO token.Pow\")\n\t\treturn gotoken.REM\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"typecheck: bad op: %s\", op))\n\t}\n}\n\nfunc (c *Checker) constrainUntyped(p *partial, t tipe.Type) {\n\tif p.mode == modeInvalid || isTyped(p.typ) || t == tipe.Invalid {\n\t\treturn\n\t}\n\n\t\/\/ catch invalid constraints\n\tif isUntyped(t) {\n\t\tswitch {\n\t\tcase t == tipe.UntypedFloat && p.typ == tipe.UntypedInteger:\n\t\t\t\/\/ promote untyped int to float\n\t\tcase t == tipe.UntypedComplex && (p.typ == tipe.UntypedInteger || p.typ == tipe.UntypedFloat):\n\t\t\t\/\/ promote untyped int or float to complex\n\t\tcase t != p.typ:\n\t\t\tpanic(\"cannot convert untyped\")\n\t\t\t\/\/ TODO c.errorf(\"cannot convert %s to %s\", x, typ)\n\t\t}\n\t} else {\n\t\tswitch t := Underlying(t).(type) {\n\t\tcase tipe.Basic:\n\t\t\tswitch p.mode {\n\t\t\tcase modeConst:\n\t\t\t\tp.val = round(p.val, t)\n\t\t\t\tif p.val == nil {\n\t\t\t\t\tpanic(\"cannot convert\")\n\t\t\t\t\t\/\/ TODO c.errorf\n\t\t\t\t}\n\t\t\tcase modeVar:\n\t\t\t\tpanic(\"TODO coerce var to basic\")\n\t\t\t}\n\t\t}\n\t}\n\n\tp.typ = t\n\tc.constrainExprType(p.expr, p.typ)\n}\n\n\/\/ constrainExprType descends an expression constraining the type.\nfunc (c *Checker) constrainExprType(e expr.Expr, t tipe.Type) {\n\toldt := c.Types[e]\n\tif oldt == t {\n\t\treturn\n\t}\n\tc.Types[e] = t\n\n\tswitch e := e.(type) {\n\tcase *expr.Bad, *expr.FuncLiteral: \/\/ TODO etc\n\t\treturn\n\tcase *expr.Binary:\n\t\tif c.Values[e] != nil {\n\t\t\tbreak\n\t\t}\n\t\tswitch e.Op {\n\t\tcase token.Equal, token.NotEqual,\n\t\t\ttoken.Less, token.LessEqual,\n\t\t\ttoken.Greater, token.GreaterEqual:\n\t\t\t\/\/ comparisons generate their own bool type\n\t\t\treturn\n\t\t}\n\t\tc.constrainExprType(e.Left, t)\n\t\tc.constrainExprType(e.Right, t)\n\t}\n\n\tc.Types[e] = t\n}\n\nfunc round(v constant.Value, t tipe.Basic) constant.Value {\n\tswitch v.Kind() {\n\tcase constant.Unknown:\n\t\treturn v\n\tcase constant.Bool:\n\t\tif t == tipe.Bool || t == tipe.UntypedBool {\n\t\t\treturn v\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\tcase constant.Int:\n\t\tswitch t {\n\t\tcase tipe.Integer, tipe.UntypedInteger:\n\t\t\treturn v\n\t\tcase tipe.Float, tipe.UntypedFloat, tipe.UntypedComplex:\n\t\t\treturn v\n\t\tcase tipe.Int64:\n\t\t\tif _, ok := constant.Int64Val(v); ok {\n\t\t\t\treturn v\n\t\t\t} else {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\tcase constant.Float:\n\t\tswitch t {\n\t\tcase tipe.Float, tipe.UntypedFloat, tipe.UntypedComplex:\n\t\t\treturn v\n\t\tcase tipe.Float32:\n\t\t\tr, _ := constant.Float32Val(v)\n\t\t\treturn constant.MakeFloat64(float64(r))\n\t\tcase tipe.Float64:\n\t\t\tr, _ := constant.Float64Val(v)\n\t\t\treturn constant.MakeFloat64(float64(r))\n\t\t}\n\t}\n\t\/\/ TODO many more comparisons\n\treturn nil\n}\n\nfunc (c *Checker) Add(s stmt.Stmt) {\n\tc.stmt(s)\n}\n\nfunc (c *Checker) String() string {\n\tbuf := new(bytes.Buffer)\n\tbuf.WriteString(\"typecheck.Checker{\\n\")\n\tbuf.WriteString(\"\\tTypes: map[expr.Expr]tipe.Type{\\n\")\n\tfor k, v := range c.Types {\n\t\tfmt.Fprintf(buf, \"\\t\\t(%p)%s: %s\\n\", k, k.Sexp(), v.Sexp())\n\t}\n\tbuf.WriteString(\"\\t},\\n\")\n\tbuf.WriteString(\"\\tDefs: map[*expr.Ident]*Obj{\\n\")\n\tfor k, v := range c.Defs {\n\t\tt := \"niltype\"\n\t\tif v.Type != nil {\n\t\t\tt = v.Type.Sexp()\n\t\t}\n\t\tfmt.Fprintf(buf, \"\\t\\t(%p)%s: (%p).Type:%s\\n\", k, k.Sexp(), v, t)\n\t}\n\tbuf.WriteString(\"\\t},\\n\")\n\tbuf.WriteString(\"\\tValues : map[expr.Expr]constant.Value{\\n\")\n\tfor k, v := range c.Values {\n\t\tfmt.Fprintf(buf, \"\\t\\t(%p)%s: %s\\n\", k, k.Sexp(), v)\n\t}\n\tbuf.WriteString(\"\\t},\\n\")\n\tbuf.WriteString(\"}\")\n\treturn buf.String()\n}\n\ntype Scope struct {\n\tParent *Scope\n\tObjs   map[string]*Obj\n}\n\nfunc (s *Scope) LookupRec(name string) *Obj {\n\tfor s != nil {\n\t\tif o := s.Objs[name]; o != nil {\n\t\t\treturn o\n\t\t}\n\t\ts = s.Parent\n\t}\n\treturn nil\n}\n\n\/\/ An Obj represents a declared constant, type, variable, or function.\ntype Obj struct {\n\tType tipe.Type\n\tUsed bool\n}\n\nfunc Underlying(t tipe.Type) tipe.Type {\n\tif n, ok := t.(*tipe.Named); ok {\n\t\treturn n.Underlying\n\t}\n\treturn t\n}\n\nfunc isTyped(t tipe.Type) bool {\n\treturn Underlying(t) != tipe.Invalid && !isUntyped(t)\n}\n\nfunc isUntyped(t tipe.Type) bool {\n\tswitch Underlying(t) {\n\tcase tipe.UntypedBool, tipe.UntypedInteger, tipe.UntypedFloat, tipe.UntypedComplex:\n\t\treturn true\n\t}\n\treturn false\n}\n<commit_msg>lang\/typecheck: propagate ident types to decls<commit_after>\/\/ Copyright 2015 The Numgrad Authors. All rights reserved.\n\/\/ See the LICENSE file for rights to use this source code.\n\n\/\/ Package typecheck is a Numengrad type checker.\npackage typecheck\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"go\/constant\"\n\tgotoken \"go\/token\"\n\t\"math\/big\"\n\n\t\"numgrad.io\/lang\/expr\"\n\t\"numgrad.io\/lang\/stmt\"\n\t\"numgrad.io\/lang\/tipe\"\n\t\"numgrad.io\/lang\/token\"\n)\n\ntype Checker struct {\n\t\/\/ TODO: we could put these on our AST. Should we?\n\tTypes  map[expr.Expr]tipe.Type\n\tDefs   map[*expr.Ident]*Obj\n\tValues map[expr.Expr]constant.Value\n\n\t\/\/ TODO NamedInfo map[*tipe.Named]NamedInfo\n\n\tcur *Scope\n}\n\n\/\/ TODO type NamedInfo struct {\n\/\/\tObj *Obj\n\/\/\tMethods []*Obj\n\/\/}\n\nfunc New() *Checker {\n\treturn &Checker{\n\t\tTypes:  make(map[expr.Expr]tipe.Type),\n\t\tDefs:   make(map[*expr.Ident]*Obj),\n\t\tValues: make(map[expr.Expr]constant.Value),\n\t\tcur:    &Scope{Objs: make(map[string]*Obj)},\n\t}\n}\n\ntype partialMode int\n\nconst (\n\tmodeInvalid partialMode = iota\n\tmodeVoid\n\tmodeConst\n\tmodeVar\n\tmodeBuiltin\n)\n\ntype partial struct {\n\tmode partialMode\n\ttyp  tipe.Type\n\tval  constant.Value\n\texpr expr.Expr\n}\n\nfunc (c *Checker) errorf(format string, args ...interface{}) {\n\tfmt.Printf(\"typecheck error: %s\\n\", fmt.Sprintf(format, args...))\n}\n\nfunc defaultType(t tipe.Type) tipe.Type {\n\tb, ok := t.(tipe.Basic)\n\tif !ok {\n\t\treturn t\n\t}\n\tswitch b {\n\tcase tipe.UntypedBool:\n\t\treturn tipe.Bool\n\tcase tipe.UntypedInteger:\n\t\treturn tipe.Integer\n\tcase tipe.UntypedFloat:\n\t\treturn tipe.Float\n\t}\n\treturn t\n}\n\nfunc (c *Checker) stmt(s stmt.Stmt) {\n\tswitch s := s.(type) {\n\tcase *stmt.Assign:\n\t\tif len(s.Left) != len(s.Right) {\n\t\t\tpanic(\"TODO artity mismatch, i.e. x, y := f()\")\n\t\t}\n\t\tvar partials []partial\n\t\tfor _, rhs := range s.Right {\n\t\t\tpartials = append(partials, c.expr(rhs))\n\t\t}\n\t\tif s.Decl {\n\t\t\tfor i, lhs := range s.Left {\n\t\t\t\tp := partials[i]\n\t\t\t\tif isUntyped(p.typ) {\n\t\t\t\t\tc.constrainUntyped(&p, defaultType(p.typ))\n\t\t\t\t}\n\t\t\t\tobj := &Obj{Type: p.typ}\n\t\t\t\tc.Defs[lhs.(*expr.Ident)] = obj\n\t\t\t\tc.cur.Objs[lhs.(*expr.Ident).Name] = obj\n\t\t\t}\n\t\t} else {\n\t\t\tfor i, lhs := range s.Left {\n\t\t\t\tp := partials[i]\n\t\t\t\tlhsP := c.expr(lhs)\n\t\t\t\tif isUntyped(p.typ) {\n\t\t\t\t\tc.constrainUntyped(&p, lhsP.typ)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"typecheck: unknown stmt %T\", s))\n\t}\n}\n\nfunc (c *Checker) expr(e expr.Expr) (p partial) {\n\t\/\/ TODO more mode adjustment\n\tp = c.exprPartial(e)\n\tif p.mode == modeConst {\n\t\tc.Values[p.expr] = p.val\n\t\tc.Types[p.expr] = p.typ\n\t}\n\treturn p\n}\n\nfunc (c *Checker) exprPartial(e expr.Expr) (p partial) {\n\tfmt.Printf(\"exprPartial(%s)\\n\", e.Sexp())\n\tp.expr = e\n\tswitch e := e.(type) {\n\tcase *expr.Ident:\n\t\tobj := c.cur.LookupRec(e.Name)\n\t\tif obj == nil {\n\t\t\tp.mode = modeInvalid\n\t\t\tc.errorf(\"undeclared identifier: %s\", e.Name)\n\t\t\treturn p\n\t\t}\n\t\tc.Defs[e] = obj \/\/ TODO Defs is more than definitions? rename?\n\t\tp.mode = modeVar\n\t\tp.typ = obj.Type\n\t\treturn p\n\tcase *expr.BasicLiteral:\n\t\tp.mode = modeConst\n\t\t\/\/ TODO: use constant.Value in BasicLiteral directly.\n\t\tswitch v := e.Value.(type) {\n\t\tcase *big.Int:\n\t\t\tp.typ = tipe.UntypedInteger\n\t\t\tp.val = constant.MakeFromLiteral(v.String(), gotoken.INT, 0)\n\t\tcase *big.Float:\n\t\t\tp.typ = tipe.UntypedFloat\n\t\t\tp.val = constant.MakeFromLiteral(v.String(), gotoken.FLOAT, 0)\n\t\t}\n\t\treturn p\n\tcase *expr.Binary:\n\t\tleft := c.expr(e.Left)\n\t\tright := c.expr(e.Right)\n\t\tc.constrainUntyped(&left, right.typ)\n\t\tc.constrainUntyped(&right, left.typ)\n\t\tif left.mode == modeInvalid {\n\t\t\treturn left\n\t\t}\n\t\tif right.mode == modeInvalid {\n\t\t\treturn right\n\t\t}\n\t\tleft.expr = e\n\t\t\/\/ TODO check for division by zero\n\t\t\/\/ TODO check for comparison\n\t\tif left.mode == modeConst && right.mode == modeConst {\n\t\t\tleft.val = constant.BinaryOp(left.val, convGoOp(e.Op), right.val)\n\t\t\t\/\/ TODO check rounding\n\t\t}\n\n\t\treturn left\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"expr TODO: %T\", e))\n\t}\n}\n\nfunc convGoOp(op token.Token) gotoken.Token {\n\tswitch op {\n\tcase token.Add:\n\t\treturn gotoken.ADD\n\tcase token.Sub:\n\t\treturn gotoken.SUB\n\tcase token.Mul:\n\t\treturn gotoken.MUL\n\tcase token.Div:\n\t\treturn gotoken.QUO \/\/ TODO: QUO_ASSIGN for int div\n\tcase token.Rem:\n\t\treturn gotoken.REM\n\tcase token.Pow:\n\t\tpanic(\"TODO token.Pow\")\n\t\treturn gotoken.REM\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"typecheck: bad op: %s\", op))\n\t}\n}\n\nfunc (c *Checker) constrainUntyped(p *partial, t tipe.Type) {\n\tif p.mode == modeInvalid || isTyped(p.typ) || t == tipe.Invalid {\n\t\treturn\n\t}\n\n\t\/\/ catch invalid constraints\n\tif isUntyped(t) {\n\t\tswitch {\n\t\tcase t == tipe.UntypedFloat && p.typ == tipe.UntypedInteger:\n\t\t\t\/\/ promote untyped int to float\n\t\tcase t == tipe.UntypedComplex && (p.typ == tipe.UntypedInteger || p.typ == tipe.UntypedFloat):\n\t\t\t\/\/ promote untyped int or float to complex\n\t\tcase t != p.typ:\n\t\t\tpanic(\"cannot convert untyped\")\n\t\t\t\/\/ TODO c.errorf(\"cannot convert %s to %s\", x, typ)\n\t\t}\n\t} else {\n\t\tswitch t := Underlying(t).(type) {\n\t\tcase tipe.Basic:\n\t\t\tswitch p.mode {\n\t\t\tcase modeConst:\n\t\t\t\tp.val = round(p.val, t)\n\t\t\t\tif p.val == nil {\n\t\t\t\t\tpanic(\"cannot convert\")\n\t\t\t\t\t\/\/ TODO c.errorf\n\t\t\t\t}\n\t\t\tcase modeVar:\n\t\t\t\tpanic(\"TODO coerce var to basic\")\n\t\t\t}\n\t\t}\n\t}\n\n\tp.typ = t\n\tc.constrainExprType(p.expr, p.typ)\n}\n\n\/\/ constrainExprType descends an expression constraining the type.\nfunc (c *Checker) constrainExprType(e expr.Expr, t tipe.Type) {\n\toldt := c.Types[e]\n\tif oldt == t {\n\t\treturn\n\t}\n\tc.Types[e] = t\n\n\tswitch e := e.(type) {\n\tcase *expr.Bad, *expr.FuncLiteral: \/\/ TODO etc\n\t\treturn\n\tcase *expr.Binary:\n\t\tif c.Values[e] != nil {\n\t\t\tbreak\n\t\t}\n\t\tswitch e.Op {\n\t\tcase token.Equal, token.NotEqual,\n\t\t\ttoken.Less, token.LessEqual,\n\t\t\ttoken.Greater, token.GreaterEqual:\n\t\t\t\/\/ comparisons generate their own bool type\n\t\t\treturn\n\t\t}\n\t\tc.constrainExprType(e.Left, t)\n\t\tc.constrainExprType(e.Right, t)\n\t}\n\n\tc.Types[e] = t\n}\n\nfunc round(v constant.Value, t tipe.Basic) constant.Value {\n\tswitch v.Kind() {\n\tcase constant.Unknown:\n\t\treturn v\n\tcase constant.Bool:\n\t\tif t == tipe.Bool || t == tipe.UntypedBool {\n\t\t\treturn v\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\tcase constant.Int:\n\t\tswitch t {\n\t\tcase tipe.Integer, tipe.UntypedInteger:\n\t\t\treturn v\n\t\tcase tipe.Float, tipe.UntypedFloat, tipe.UntypedComplex:\n\t\t\treturn v\n\t\tcase tipe.Int64:\n\t\t\tif _, ok := constant.Int64Val(v); ok {\n\t\t\t\treturn v\n\t\t\t} else {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\tcase constant.Float:\n\t\tswitch t {\n\t\tcase tipe.Float, tipe.UntypedFloat, tipe.UntypedComplex:\n\t\t\treturn v\n\t\tcase tipe.Float32:\n\t\t\tr, _ := constant.Float32Val(v)\n\t\t\treturn constant.MakeFloat64(float64(r))\n\t\tcase tipe.Float64:\n\t\t\tr, _ := constant.Float64Val(v)\n\t\t\treturn constant.MakeFloat64(float64(r))\n\t\t}\n\t}\n\t\/\/ TODO many more comparisons\n\treturn nil\n}\n\nfunc (c *Checker) Add(s stmt.Stmt) {\n\tc.stmt(s)\n}\n\nfunc (c *Checker) String() string {\n\tbuf := new(bytes.Buffer)\n\tbuf.WriteString(\"typecheck.Checker{\\n\")\n\tbuf.WriteString(\"\\tTypes: map[expr.Expr]tipe.Type{\\n\")\n\tfor k, v := range c.Types {\n\t\tfmt.Fprintf(buf, \"\\t\\t(%p)%s: %s\\n\", k, k.Sexp(), v.Sexp())\n\t}\n\tbuf.WriteString(\"\\t},\\n\")\n\tbuf.WriteString(\"\\tDefs: map[*expr.Ident]*Obj{\\n\")\n\tfor k, v := range c.Defs {\n\t\tt := \"niltype\"\n\t\tif v.Type != nil {\n\t\t\tt = v.Type.Sexp()\n\t\t}\n\t\tfmt.Fprintf(buf, \"\\t\\t(%p)%s: (%p).Type:%s\\n\", k, k.Sexp(), v, t)\n\t}\n\tbuf.WriteString(\"\\t},\\n\")\n\tbuf.WriteString(\"\\tValues : map[expr.Expr]constant.Value{\\n\")\n\tfor k, v := range c.Values {\n\t\tfmt.Fprintf(buf, \"\\t\\t(%p)%s: %s\\n\", k, k.Sexp(), v)\n\t}\n\tbuf.WriteString(\"\\t},\\n\")\n\tbuf.WriteString(\"}\")\n\treturn buf.String()\n}\n\ntype Scope struct {\n\tParent *Scope\n\tObjs   map[string]*Obj\n}\n\nfunc (s *Scope) LookupRec(name string) *Obj {\n\tfor s != nil {\n\t\tif o := s.Objs[name]; o != nil {\n\t\t\treturn o\n\t\t}\n\t\ts = s.Parent\n\t}\n\treturn nil\n}\n\n\/\/ An Obj represents a declared constant, type, variable, or function.\ntype Obj struct {\n\tType tipe.Type\n\tUsed bool\n}\n\nfunc Underlying(t tipe.Type) tipe.Type {\n\tif n, ok := t.(*tipe.Named); ok {\n\t\treturn n.Underlying\n\t}\n\treturn t\n}\n\nfunc isTyped(t tipe.Type) bool {\n\treturn Underlying(t) != tipe.Invalid && !isUntyped(t)\n}\n\nfunc isUntyped(t tipe.Type) bool {\n\tswitch Underlying(t) {\n\tcase tipe.UntypedBool, tipe.UntypedInteger, tipe.UntypedFloat, tipe.UntypedComplex:\n\t\treturn true\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\nvar testData uint32\n\nfunc checkSymbols(t *testing.T, nmoutput []byte) {\n\tswitch runtime.GOOS {\n\tcase \"linux\", \"darwin\", \"solaris\":\n\t\tt.Skip(\"skipping test; see http:\/\/golang.org\/issue\/7829\")\n\t}\n\tvar checkSymbolsFound, testDataFound bool\n\tscanner := bufio.NewScanner(bytes.NewBuffer(nmoutput))\n\tfor scanner.Scan() {\n\t\tf := strings.Fields(scanner.Text())\n\t\tif len(f) < 3 {\n\t\t\tt.Error(\"nm must have at least 3 columns\")\n\t\t\tcontinue\n\t\t}\n\t\tswitch f[2] {\n\t\tcase \"cmd\/nm.checkSymbols\":\n\t\t\tcheckSymbolsFound = true\n\t\t\taddr := \"0x\" + f[0]\n\t\t\tif addr != fmt.Sprintf(\"%p\", checkSymbols) {\n\t\t\t\tt.Errorf(\"nm shows wrong address %v for checkSymbols (%p)\", addr, checkSymbols)\n\t\t\t}\n\t\tcase \"cmd\/nm.testData\":\n\t\t\ttestDataFound = true\n\t\t\taddr := \"0x\" + f[0]\n\t\t\tif addr != fmt.Sprintf(\"%p\", &testData) {\n\t\t\t\tt.Errorf(\"nm shows wrong address %v for testData (%p)\", addr, &testData)\n\t\t\t}\n\t\t}\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tt.Errorf(\"error while reading symbols: %v\", err)\n\t\treturn\n\t}\n\tif !checkSymbolsFound {\n\t\tt.Error(\"nm shows no checkSymbols symbol\")\n\t}\n\tif !testDataFound {\n\t\tt.Error(\"nm shows no testData symbol\")\n\t}\n}\n\nfunc TestNM(t *testing.T) {\n\tout, err := exec.Command(\"go\", \"build\", \"-o\", \"testnm.exe\", \"cmd\/nm\").CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"go build -o testnm.exe cmd\/nm: %v\\n%s\", err, string(out))\n\t}\n\tdefer os.Remove(\"testnm.exe\")\n\n\ttestfiles := []string{\n\t\t\"elf\/testdata\/gcc-386-freebsd-exec\",\n\t\t\"elf\/testdata\/gcc-amd64-linux-exec\",\n\t\t\"macho\/testdata\/gcc-386-darwin-exec\",\n\t\t\"macho\/testdata\/gcc-amd64-darwin-exec\",\n\t\t\"pe\/testdata\/gcc-amd64-mingw-exec\",\n\t\t\"pe\/testdata\/gcc-386-mingw-exec\",\n\t\t\"plan9obj\/testdata\/amd64-plan9-exec\",\n\t\t\"plan9obj\/testdata\/386-plan9-exec\",\n\t}\n\tfor _, f := range testfiles {\n\t\texepath := filepath.Join(runtime.GOROOT(), \"src\", \"pkg\", \"debug\", f)\n\t\tcmd := exec.Command(\".\/testnm.exe\", exepath)\n\t\tout, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"go tool nm %v: %v\\n%s\", exepath, err, string(out))\n\t\t}\n\t}\n\n\tcmd := exec.Command(\".\/testnm.exe\", os.Args[0])\n\tout, err = cmd.CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"go tool nm %v: %v\\n%s\", os.Args[0], err, string(out))\n\t}\n\tcheckSymbols(t, out)\n}\n<commit_msg>cmd\/nm: do not fail TestNM if symbol has less then 3 columns in nm output<commit_after>\/\/ Copyright 2014 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\nvar testData uint32\n\nfunc checkSymbols(t *testing.T, nmoutput []byte) {\n\tvar checkSymbolsFound, testDataFound bool\n\tscanner := bufio.NewScanner(bytes.NewBuffer(nmoutput))\n\tfor scanner.Scan() {\n\t\tf := strings.Fields(scanner.Text())\n\t\tif len(f) < 3 {\n\t\t\tcontinue\n\t\t}\n\t\tswitch f[2] {\n\t\tcase \"cmd\/nm.checkSymbols\":\n\t\t\tcheckSymbolsFound = true\n\t\t\taddr := \"0x\" + f[0]\n\t\t\tif addr != fmt.Sprintf(\"%p\", checkSymbols) {\n\t\t\t\tt.Errorf(\"nm shows wrong address %v for checkSymbols (%p)\", addr, checkSymbols)\n\t\t\t}\n\t\tcase \"cmd\/nm.testData\":\n\t\t\ttestDataFound = true\n\t\t\taddr := \"0x\" + f[0]\n\t\t\tif addr != fmt.Sprintf(\"%p\", &testData) {\n\t\t\t\tt.Errorf(\"nm shows wrong address %v for testData (%p)\", addr, &testData)\n\t\t\t}\n\t\t}\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tt.Errorf(\"error while reading symbols: %v\", err)\n\t\treturn\n\t}\n\tif !checkSymbolsFound {\n\t\tt.Error(\"nm shows no checkSymbols symbol\")\n\t}\n\tif !testDataFound {\n\t\tt.Error(\"nm shows no testData symbol\")\n\t}\n}\n\nfunc TestNM(t *testing.T) {\n\tout, err := exec.Command(\"go\", \"build\", \"-o\", \"testnm.exe\", \"cmd\/nm\").CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"go build -o testnm.exe cmd\/nm: %v\\n%s\", err, string(out))\n\t}\n\tdefer os.Remove(\"testnm.exe\")\n\n\ttestfiles := []string{\n\t\t\"elf\/testdata\/gcc-386-freebsd-exec\",\n\t\t\"elf\/testdata\/gcc-amd64-linux-exec\",\n\t\t\"macho\/testdata\/gcc-386-darwin-exec\",\n\t\t\"macho\/testdata\/gcc-amd64-darwin-exec\",\n\t\t\"pe\/testdata\/gcc-amd64-mingw-exec\",\n\t\t\"pe\/testdata\/gcc-386-mingw-exec\",\n\t\t\"plan9obj\/testdata\/amd64-plan9-exec\",\n\t\t\"plan9obj\/testdata\/386-plan9-exec\",\n\t}\n\tfor _, f := range testfiles {\n\t\texepath := filepath.Join(runtime.GOROOT(), \"src\", \"pkg\", \"debug\", f)\n\t\tcmd := exec.Command(\".\/testnm.exe\", exepath)\n\t\tout, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"go tool nm %v: %v\\n%s\", exepath, err, string(out))\n\t\t}\n\t}\n\n\tcmd := exec.Command(\".\/testnm.exe\", os.Args[0])\n\tout, err = cmd.CombinedOutput()\n\tif err != nil {\n\t\tt.Fatalf(\"go tool nm %v: %v\\n%s\", os.Args[0], err, string(out))\n\t}\n\tcheckSymbols(t, out)\n}\n<|endoftext|>"}
{"text":"<commit_before>package core\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Parser struct {\n\tend      int\n\tlen      int\n\tposition int\n\tdata     []byte\n}\n\nfunc NewParser(data []byte) *Parser {\n\tp := &Parser{\n\t\tdata: data,\n\t\tlen:  len(data),\n\t\tend:  len(data) - 1,\n\t}\n\treturn p\n}\n\nfunc (p *Parser) ReadLiteral() *Literal {\n\tstart := p.position\n\tfor {\n\t\tif p.SkipUntil('%') == false {\n\t\t\treturn &Literal{clone(p.data[start:p.len])}\n\t\t}\n\t\tif p.Prev() == '<' {\n\t\t\tp.position++ \/\/move past the %\n\t\t\treturn &Literal{clone(p.data[start : p.position-2])}\n\t\t}\n\t}\n}\n\nfunc (p *Parser) ReadValue() (Value, error) {\n\tfirst := p.SkipSpaces()\n\tnegate := false\n\tif first == '-' {\n\t\tnegate = true\n\t\tp.position++\n\t\tfirst = p.SkipSpaces()\n\t}\n\tvar value Value\n\tvar err error\n\tif first == 0 {\n\t\treturn nil, p.error(\"Expected value, got nothing\")\n\t}\n\tif first >= '0' && first <= '9' {\n\t\t value, err = p.ReadNumber(negate)\n\t} else if first == '\\'' {\n\t\tvalue, err = p.ReadChar(negate)\n\t} else if first == '\"' {\n\t\tvalue, err =  p.ReadString(negate)\n\t} else {\n\t\tvalue, err = p.ReadDynamic(negate)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc1 := p.SkipSpaces()\n\tif c1 == '%' && p.data[p.position+1] == '>' {\n\t\treturn value, nil\n\t}\n\tfactory, ok := Operations[c1]\n\tif ok == false {\n\t\treturn value, nil\n\t}\n\tp.position++\n\tright, err := p.ReadValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn factory(value, right), nil\n}\n\nfunc (p *Parser) ReadNumber(negate bool) (Value, error) {\n\tinteger := 0\n\tfraction := 0\n\ttarget := &integer\n\tpartLength := 0\n\tisDecimal := false\n\tfor ; p.position < p.end; p.position++ {\n\t\tc := p.data[p.position]\n\t\tif c == '.' {\n\t\t\tif isDecimal {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttarget = &fraction\n\t\t\tpartLength = 0\n\t\t\tisDecimal = true\n\t\t\tcontinue\n\t\t}\n\t\tif c < '0' || c > '9' {\n\t\t\tbreak\n\t\t}\n\t\tpartLength++\n\t\t*target = *target*10 + int(c-'0')\n\t}\n\n\tif isDecimal {\n\t\tvalue := float64(integer) + float64(fraction)\/math.Pow10(partLength)\n\t\tif negate {\n\t\t\tvalue *= -1\n\t\t}\n\t\treturn &StaticValue{value}, nil\n\t}\n\tif negate {\n\t\tinteger *= -1\n\t}\n\treturn &StaticValue{integer}, nil\n}\n\nfunc (p *Parser) ReadChar(negate bool) (Value, error) {\n\tif negate {\n\t\treturn nil, p.error(\"Don't know what to do with a negative character\")\n\t}\n\tc := p.Next()\n\tif c == '\\\\' {\n\t\tc = p.Next()\n\t}\n\tif p.Next() != '\\'' {\n\t\treturn nil, p.error(\"Invalid character\")\n\t}\n\tp.position++\n\treturn &StaticValue{c}, nil\n}\n\nfunc (p *Parser) ReadString(negate bool) (Value, error) {\n\tif negate {\n\t\treturn nil, p.error(\"Don't know what to do with a negative string\")\n\t}\n\tp.position++\n\tstart := p.position\n\tescaped := 0\n\n\tfor ; p.position < p.end; p.position++ {\n\t\tc := p.data[p.position]\n\t\tif c == '\\\\' {\n\t\t\tescaped++\n\t\t\tp.position++\n\t\t\tcontinue\n\t\t}\n\t\tif c == '\"' {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvar data []byte\n\tvar err error\n\tif escaped > 0 {\n\t\tdata, err = p.unescape(p.data[start:p.position], escaped)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tdata = p.data[start:p.position]\n\t}\n\tp.position++ \/\/consume the \"\n\treturn &StaticValue{string(data)}, nil\n}\n\nfunc (p *Parser) ReadDynamic(negate bool) (Value, error) {\n\tstart := p.position\n\tfields := make([]string, 0, 5)\n\ttypes := make([]DynamicFieldType, 0, 5)\n\targs := make([][]Value, 0, 5)\n\tfor ;p.position < p.end; p.position++ {\n\t\tc := p.data[p.position]\n\t\tif (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' {\n\t\t\tcontinue\n\t\t}\n\t\tfield := string(bytes.ToLower(p.data[start:p.position]))\n\t\tisEnd := c != '.' && c != '(' && c != '['\n\t\tif c == '.' || isEnd {\n\t\t\tif isEnd && p.position - start == 1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfields = append(fields, field)\n\t\t\ttypes = append(types, FieldType)\n\t\t\targs = append(args, nil)\n\t\t\tstart = p.position+1\n\t\t\tif isEnd {\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else if c == '[' {\n\t\t\tprintln(field)\n\t\t\tfields = append(fields, field)\n\t\t\ttypes = append(types, IndexedType)\n\t\t\tp.position++\n\t\t\targ, err := p.ReadIndexing()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\targs = append(args, arg)\n\t\t\tstart = p.position\n\t\t} else if c == '(' {\n\t\t\tfields = append(fields, field)\n\t\t\ttypes = append(types, MethodType)\n\t\t\tp.position++\n\t\t\targ, err := p.ReadArgs()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\targs = append(args, arg)\n\t\t\tstart = p.position+1\n\t\t}\n\t}\n\treturn &DynamicValue{fields, types, args}, nil\n}\n\nfunc (p *Parser) ReadIndexing() ([]Value, error) {\n\tfirst, err := p.ReadValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc := p.SkipSpaces()\n\tif c == ']' {\n\t\treturn []Value{first}, nil\n\t}\n\tif c != ':' {\n\t\treturn nil, p.error(\"Unrecognized array\/map index\")\n\t}\n\n\tp.position++\n\tsecond, err := p.ReadValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif c = p.SkipSpaces(); c != ']' {\n\t\treturn nil, p.error(\"Expected closing array\/map bracket\")\n\t}\n\treturn []Value{first, second}, nil\n}\n\nfunc (p *Parser) ReadArgs() ([]Value, error) {\n\tif p.data[p.position] == ')' {\n\t\treturn nil, nil\n\t}\n\n\tvalues := make([]Value, 0, 3)\n\tfor {\n\t\tvalue, err := p.ReadValue()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvalues = append(values, value)\n\t\tc := p.SkipSpaces()\n\t\tif c == ')' {\n\t\t\tbreak\n\t\t}\n\t\tif c != ',' {\n\t\t\treturn nil, p.error(\"Invalid argument list given to function\")\n\t\t}\n\t}\n\treturn values, nil\n}\n\nfunc (p *Parser) ReadTagType() TagType {\n\tswitch p.Consume() {\n\tcase 0:\n\t\treturn NoTag\n\tcase '=':\n\t\treturn OutputTag\n\tcase '!':\n\t\treturn UnsafeTag\n\tdefault:\n\t\treturn NoTag \/\/todo CodeTag\n\t}\n}\n\nfunc (p *Parser) ReadCloseTag() error {\n\tif p.SkipSpaces() != '%' || p.Next() != '>' {\n\t\treturn p.error(\"Expected closing tag\")\n\t}\n\tp.position++\n\treturn nil\n}\n\nfunc (p *Parser) SkipUntil(b byte) bool {\n\tif at := bytes.IndexByte(p.data[p.position:], b); at != -1 {\n\t\tp.position = p.position + at\n\t\treturn true\n\t}\n\tp.position = len(p.data)\n\treturn false\n}\n\nfunc (p *Parser) SkipSpaces() byte {\n\tfor ; p.position < p.end; p.position++ {\n\t\tc := p.data[p.position]\n\t\tif c != ' ' && c != '\\t' && c != '\\n' && c != '\\r' {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn 0\n}\n\nfunc (p *Parser) Consume() byte {\n\tif p.position > p.end {\n\t\treturn 0\n\t}\n\tc := p.data[p.position]\n\tp.position++\n\treturn c\n}\n\nfunc (p *Parser) Next() byte {\n\tp.position++\n\tif p.position > p.end {\n\t\treturn 0\n\t}\n\treturn p.data[p.position]\n}\n\nfunc (p *Parser) Prev() byte {\n\treturn p.data[p.position-1]\n}\n\nfunc (p *Parser) Dump() {\n\tfmt.Println(string(p.data[p.position:]))\n}\n\nfunc (p *Parser) error(s string) error {\n\tend := p.position\n\tfor ; end < p.end; end++ {\n\t\tif p.data[end] == '%' && p.data[end+1] == '>' {\n\t\t\tbreak\n\t\t}\n\t}\n\tend += 2 \/\/consume the > + this is exclusive\n\tif end > p.len {\n\t\tend = p.len\n\t}\n\tstart := p.position\n\tfor ; start > 0; start-- {\n\t\tif p.data[start] == '%' && p.data[start-1] == '<' {\n\t\t\tstart--\n\t\t\tbreak\n\t\t}\n\t}\n\treturn errors.New(fmt.Sprintf(\"%s: %v\", s, string(p.data[start:end])))\n}\n\nfunc (p *Parser) unescape(data []byte, escaped int) ([]byte, error) {\n\tvalue := make([]byte, len(data)-escaped)\n\tat := 0\n\tfor {\n\t\tindex := bytes.IndexByte(data, '\\\\')\n\t\tif index == -1 {\n\t\t\tcopy(value[at:], data)\n\t\t\tbreak\n\t\t}\n\t\tat += copy(value[at:], data[:index])\n\t\tswitch data[index+1] {\n\t\tcase 'n':\n\t\t\tvalue[at] = '\\n'\n\t\tcase 'r':\n\t\t\tvalue[at] = '\\r'\n\t\tcase 't':\n\t\t\tvalue[at] = '\\t'\n\t\tcase '\"':\n\t\t\tvalue[at] = '\"'\n\t\tcase '\\\\':\n\t\t\tvalue[at] = '\\\\'\n\t\tdefault:\n\t\t\treturn nil, p.error(fmt.Sprintf(\"Unknown escape sequence \\\\%s\", string(data[index+1])))\n\t\t}\n\t\tat++\n\t\tdata = data[index+2:]\n\t}\n\treturn value, nil\n}\n\nfunc clone(data []byte) []byte {\n\tc := make([]byte, len(data))\n\tcopy(c, data)\n\treturn c\n}\n<commit_msg>support [1:] and [:4] slices<commit_after>package core\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Parser struct {\n\tend      int\n\tlen      int\n\tposition int\n\tdata     []byte\n}\n\nfunc NewParser(data []byte) *Parser {\n\tp := &Parser{\n\t\tdata: data,\n\t\tlen:  len(data),\n\t\tend:  len(data) - 1,\n\t}\n\treturn p\n}\n\nfunc (p *Parser) ReadLiteral() *Literal {\n\tstart := p.position\n\tfor {\n\t\tif p.SkipUntil('%') == false {\n\t\t\treturn &Literal{clone(p.data[start:p.len])}\n\t\t}\n\t\tif p.Prev() == '<' {\n\t\t\tp.position++ \/\/move past the %\n\t\t\treturn &Literal{clone(p.data[start : p.position-2])}\n\t\t}\n\t}\n}\n\nfunc (p *Parser) ReadValue() (Value, error) {\n\tfirst := p.SkipSpaces()\n\tnegate := false\n\tif first == '-' {\n\t\tnegate = true\n\t\tp.position++\n\t\tfirst = p.SkipSpaces()\n\t}\n\tvar value Value\n\tvar err error\n\tif first == 0 {\n\t\treturn nil, p.error(\"Expected value, got nothing\")\n\t}\n\tif first >= '0' && first <= '9' {\n\t\t value, err = p.ReadNumber(negate)\n\t} else if first == '\\'' {\n\t\tvalue, err = p.ReadChar(negate)\n\t} else if first == '\"' {\n\t\tvalue, err =  p.ReadString(negate)\n\t} else {\n\t\tvalue, err = p.ReadDynamic(negate)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc1 := p.SkipSpaces()\n\tif c1 == '%' && p.data[p.position+1] == '>' {\n\t\treturn value, nil\n\t}\n\tfactory, ok := Operations[c1]\n\tif ok == false {\n\t\treturn value, nil\n\t}\n\tp.position++\n\tright, err := p.ReadValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn factory(value, right), nil\n}\n\nfunc (p *Parser) ReadNumber(negate bool) (Value, error) {\n\tinteger := 0\n\tfraction := 0\n\ttarget := &integer\n\tpartLength := 0\n\tisDecimal := false\n\tfor ; p.position < p.end; p.position++ {\n\t\tc := p.data[p.position]\n\t\tif c == '.' {\n\t\t\tif isDecimal {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttarget = &fraction\n\t\t\tpartLength = 0\n\t\t\tisDecimal = true\n\t\t\tcontinue\n\t\t}\n\t\tif c < '0' || c > '9' {\n\t\t\tbreak\n\t\t}\n\t\tpartLength++\n\t\t*target = *target*10 + int(c-'0')\n\t}\n\n\tif isDecimal {\n\t\tvalue := float64(integer) + float64(fraction)\/math.Pow10(partLength)\n\t\tif negate {\n\t\t\tvalue *= -1\n\t\t}\n\t\treturn &StaticValue{value}, nil\n\t}\n\tif negate {\n\t\tinteger *= -1\n\t}\n\treturn &StaticValue{integer}, nil\n}\n\nfunc (p *Parser) ReadChar(negate bool) (Value, error) {\n\tif negate {\n\t\treturn nil, p.error(\"Don't know what to do with a negative character\")\n\t}\n\tc := p.Next()\n\tif c == '\\\\' {\n\t\tc = p.Next()\n\t}\n\tif p.Next() != '\\'' {\n\t\treturn nil, p.error(\"Invalid character\")\n\t}\n\tp.position++\n\treturn &StaticValue{c}, nil\n}\n\nfunc (p *Parser) ReadString(negate bool) (Value, error) {\n\tif negate {\n\t\treturn nil, p.error(\"Don't know what to do with a negative string\")\n\t}\n\tp.position++\n\tstart := p.position\n\tescaped := 0\n\n\tfor ; p.position < p.end; p.position++ {\n\t\tc := p.data[p.position]\n\t\tif c == '\\\\' {\n\t\t\tescaped++\n\t\t\tp.position++\n\t\t\tcontinue\n\t\t}\n\t\tif c == '\"' {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvar data []byte\n\tvar err error\n\tif escaped > 0 {\n\t\tdata, err = p.unescape(p.data[start:p.position], escaped)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tdata = p.data[start:p.position]\n\t}\n\tp.position++ \/\/consume the \"\n\treturn &StaticValue{string(data)}, nil\n}\n\nfunc (p *Parser) ReadDynamic(negate bool) (Value, error) {\n\tstart := p.position\n\tfields := make([]string, 0, 5)\n\ttypes := make([]DynamicFieldType, 0, 5)\n\targs := make([][]Value, 0, 5)\n\tfor ;p.position < p.end; p.position++ {\n\t\tc := p.data[p.position]\n\t\tif (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' {\n\t\t\tcontinue\n\t\t}\n\t\tfield := string(bytes.ToLower(p.data[start:p.position]))\n\t\tisEnd := c != '.' && c != '(' && c != '['\n\t\tif c == '.' || isEnd {\n\t\t\tif isEnd && p.position - start == 1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfields = append(fields, field)\n\t\t\ttypes = append(types, FieldType)\n\t\t\targs = append(args, nil)\n\t\t\tstart = p.position+1\n\t\t\tif isEnd {\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else if c == '[' {\n\t\t\tprintln(field)\n\t\t\tfields = append(fields, field)\n\t\t\ttypes = append(types, IndexedType)\n\t\t\tp.position++\n\t\t\targ, err := p.ReadIndexing()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\targs = append(args, arg)\n\t\t\tstart = p.position\n\t\t} else if c == '(' {\n\t\t\tfields = append(fields, field)\n\t\t\ttypes = append(types, MethodType)\n\t\t\tp.position++\n\t\t\targ, err := p.ReadArgs()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\targs = append(args, arg)\n\t\t\tstart = p.position+1\n\t\t}\n\t}\n\treturn &DynamicValue{fields, types, args}, nil\n}\n\nfunc (p *Parser) ReadIndexing() ([]Value, error) {\n\timplicitStart := false\n\tif p.SkipSpaces() == ':' {\n\t\timplicitStart = true\n\t\tp.position++\n\t}\n\tfirst, err := p.ReadValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif implicitStart {\n\t\treturn []Value{&StaticValue{0}, first}, nil\n\t}\n\n\tc := p.SkipSpaces()\n\tif c == ']' {\n\t\treturn []Value{first}, nil\n\t}\n\tif c != ':' {\n\t\treturn nil, p.error(\"Unrecognized array\/map index\")\n\t}\n\n\tp.position++\n\tif p.SkipSpaces() == ']' {\n\t\treturn []Value{first}, nil\n\t}\n\tsecond, err := p.ReadValue()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif c = p.SkipSpaces(); c != ']' {\n\t\treturn nil, p.error(\"Expected closing array\/map bracket\")\n\t}\n\treturn []Value{first, second}, nil\n}\n\nfunc (p *Parser) ReadArgs() ([]Value, error) {\n\tif p.data[p.position] == ')' {\n\t\treturn nil, nil\n\t}\n\n\tvalues := make([]Value, 0, 3)\n\tfor {\n\t\tvalue, err := p.ReadValue()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvalues = append(values, value)\n\t\tc := p.SkipSpaces()\n\t\tif c == ')' {\n\t\t\tbreak\n\t\t}\n\t\tif c != ',' {\n\t\t\treturn nil, p.error(\"Invalid argument list given to function\")\n\t\t}\n\t}\n\treturn values, nil\n}\n\nfunc (p *Parser) ReadTagType() TagType {\n\tswitch p.Consume() {\n\tcase 0:\n\t\treturn NoTag\n\tcase '=':\n\t\treturn OutputTag\n\tcase '!':\n\t\treturn UnsafeTag\n\tdefault:\n\t\treturn NoTag \/\/todo CodeTag\n\t}\n}\n\nfunc (p *Parser) ReadCloseTag() error {\n\tif p.SkipSpaces() != '%' || p.Next() != '>' {\n\t\treturn p.error(\"Expected closing tag\")\n\t}\n\tp.position++\n\treturn nil\n}\n\nfunc (p *Parser) SkipUntil(b byte) bool {\n\tif at := bytes.IndexByte(p.data[p.position:], b); at != -1 {\n\t\tp.position = p.position + at\n\t\treturn true\n\t}\n\tp.position = len(p.data)\n\treturn false\n}\n\nfunc (p *Parser) SkipSpaces() byte {\n\tfor ; p.position < p.end; p.position++ {\n\t\tc := p.data[p.position]\n\t\tif c != ' ' && c != '\\t' && c != '\\n' && c != '\\r' {\n\t\t\treturn c\n\t\t}\n\t}\n\treturn 0\n}\n\nfunc (p *Parser) Consume() byte {\n\tif p.position > p.end {\n\t\treturn 0\n\t}\n\tc := p.data[p.position]\n\tp.position++\n\treturn c\n}\n\nfunc (p *Parser) Next() byte {\n\tp.position++\n\tif p.position > p.end {\n\t\treturn 0\n\t}\n\treturn p.data[p.position]\n}\n\nfunc (p *Parser) Prev() byte {\n\treturn p.data[p.position-1]\n}\n\nfunc (p *Parser) Dump() {\n\tfmt.Println(string(p.data[p.position:]))\n}\n\nfunc (p *Parser) error(s string) error {\n\tend := p.position\n\tfor ; end < p.end; end++ {\n\t\tif p.data[end] == '%' && p.data[end+1] == '>' {\n\t\t\tbreak\n\t\t}\n\t}\n\tend += 2 \/\/consume the > + this is exclusive\n\tif end > p.len {\n\t\tend = p.len\n\t}\n\tstart := p.position\n\tfor ; start > 0; start-- {\n\t\tif p.data[start] == '%' && p.data[start-1] == '<' {\n\t\t\tstart--\n\t\t\tbreak\n\t\t}\n\t}\n\treturn errors.New(fmt.Sprintf(\"%s: %v\", s, string(p.data[start:end])))\n}\n\nfunc (p *Parser) unescape(data []byte, escaped int) ([]byte, error) {\n\tvalue := make([]byte, len(data)-escaped)\n\tat := 0\n\tfor {\n\t\tindex := bytes.IndexByte(data, '\\\\')\n\t\tif index == -1 {\n\t\t\tcopy(value[at:], data)\n\t\t\tbreak\n\t\t}\n\t\tat += copy(value[at:], data[:index])\n\t\tswitch data[index+1] {\n\t\tcase 'n':\n\t\t\tvalue[at] = '\\n'\n\t\tcase 'r':\n\t\t\tvalue[at] = '\\r'\n\t\tcase 't':\n\t\t\tvalue[at] = '\\t'\n\t\tcase '\"':\n\t\t\tvalue[at] = '\"'\n\t\tcase '\\\\':\n\t\t\tvalue[at] = '\\\\'\n\t\tdefault:\n\t\t\treturn nil, p.error(fmt.Sprintf(\"Unknown escape sequence \\\\%s\", string(data[index+1])))\n\t\t}\n\t\tat++\n\t\tdata = data[index+2:]\n\t}\n\treturn value, nil\n}\n\nfunc clone(data []byte) []byte {\n\tc := make([]byte, len(data))\n\tcopy(c, data)\n\treturn c\n}\n<|endoftext|>"}
{"text":"<commit_before>package core\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"sync\"\n\n\t\"text\/template\"\n\n\t\"github.com\/bulletind\/khabar\/config\"\n\t\"github.com\/bulletind\/khabar\/db\"\n\t\"github.com\/bulletind\/khabar\/dbapi\/gully\"\n\t\"github.com\/bulletind\/khabar\/dbapi\/pending\"\n\t\"github.com\/bulletind\/khabar\/dbapi\/topics\"\n\t\"github.com\/bulletind\/khabar\/dbapi\/user_locale\"\n\t\"github.com\/nicksnyder\/go-i18n\/i18n\"\n\t\"gopkg.in\/simversity\/gotracer.v1\"\n)\n\nconst webIdent = \"web\"\nconst DEFAULT_LOCALE = \"en_US\"\nconst DEFAULT_TIMEZONE = \"GMT+0.0\"\n\nfunc sendToChannel(\n\tpending_item *pending.PendingItem,\n\ttext, channelIdent string,\n\tcontext map[string]interface{},\n) {\n\thandlerFunc, ok := ChannelMap[channelIdent]\n\tif !ok {\n\t\tlog.Println(\"No handler for Topic:\" + pending_item.Topic + \" Channel:\" + channelIdent)\n\t\treturn\n\t}\n\n\tdefer gotracer.Tracer{Dummy: true}.Notify()\n\thandlerFunc(pending_item, text, context)\n}\n\nfunc getText(locale, ident string, pending_item *pending.PendingItem) string {\n\tT, _ := i18n.Tfunc(\n\t\tlocale+\"_\"+pending_item.AppName+\"_\"+pending_item.Organization+\"_\"+ident,\n\t\tlocale+\"_\"+pending_item.AppName+\"_\"+ident,\n\t\tlocale+\"_\"+ident,\n\t)\n\n\ttext := T(pending_item.Topic, pending_item.Context)\n\tif text == pending_item.Topic {\n\t\ttext = \"\"\n\t}\n\n\treturn text\n}\n\nfunc send(locale, channelIdent string, pending_item *pending.PendingItem) {\n\n\tif !topics.ChannelAllowed(pending_item.User, pending_item.AppName,\n\t\tpending_item.Organization, pending_item.Topic, channelIdent) {\n\t\tlog.Println(\"Channel :\" + channelIdent + \" \" + \"is blocked for topic :\" + pending_item.Topic)\n\t\treturn\n\t}\n\n\tchannel, err := gully.FindOne(\n\t\tpending_item.User,\n\t\tpending_item.AppName, pending_item.Organization,\n\t\tchannelIdent,\n\t)\n\n\tif err != nil {\n\t\tlog.Println(\"Unable to find channel : \" + channelIdent + err.Error())\n\t\treturn\n\t}\n\n\ttext := getText(locale, channelIdent, pending_item)\n\tif text == \"\" {\n\t\t\/\/ If Topic == text, do not send the notification. This can happen\n\t\t\/\/ if the translation fails to find a sensible string in the JSON files\n\t\t\/\/ OR the translation provided was meaningless. To prevent the users\n\t\t\/\/ from being annpyed, abort this routine.\n\n\t\tlog.Println(\"No translation for:\" + channelIdent + pending_item.Topic)\n\t\treturn\n\t}\n\n\tif channel.Ident == EMAIL || channel.Ident == PUSH {\n\t\tvar buffer bytes.Buffer\n\t\tbuffer.WriteString(channelIdent)\n\t\tbuffer.WriteString(\"_subject\")\n\t\tsubjectIdent := buffer.String()\n\n\t\tsubject := getText(locale, subjectIdent, pending_item)\n\t\tif subject != \"\" {\n\t\t\tpending_item.Context[\"subject\"] = subject\n\t\t}\n\t}\n\n\tif channel.Ident == EMAIL {\n\t\tbuffer := new(bytes.Buffer)\n\n\t\ttransDir := config.Settings.Khabar.TranslationDirectory\n\t\tpath := transDir + \"\/\" + locale + \"_base_email.tmpl\"\n\n\t\tif _, err := os.Stat(path); err == nil {\n\t\t\tcontent, err := ioutil.ReadFile(path)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Cannot Load the base email template\")\n\t\t\t} else {\n\t\t\t\tt := template.Must(template.New(\"email\").Parse(string(content)))\n\n\t\t\t\tdata := struct{ Content string }{text}\n\t\t\t\tt.Execute(buffer, &data)\n\t\t\t\ttext = buffer.String()\n\t\t\t}\n\t\t}\n\t}\n\n\tsendToChannel(pending_item, text, channel.Ident, channel.Data)\n}\n\nfunc SendNotification(pending_item *pending.PendingItem) {\n\tuserLocale, err := user_locale.Get(pending_item.User)\n\tif err != nil {\n\t\tlog.Println(\"Unable to find locale for user :\" + err.Error())\n\t\tuserLocale = new(db.UserLocale)\n\n\t\t\/\/FIXME:: Please do not hardcode this.\n\t\tuserLocale.Locale = DEFAULT_LOCALE\n\t\tuserLocale.TimeZone = DEFAULT_TIMEZONE\n\t}\n\n\tchildwg := new(sync.WaitGroup)\n\n\tfor channel, _ := range ChannelMap {\n\t\tchildwg.Add(1)\n\n\t\tgo func(\n\t\t\tlocale, channelIdent string,\n\t\t\tpending_item *pending.PendingItem,\n\t\t) {\n\t\t\tdefer childwg.Done()\n\t\t\tsend(locale, channelIdent, pending_item)\n\t\t}(userLocale.Locale, channel, pending_item)\n\t}\n\n\tchildwg.Wait()\n}\n<commit_msg>Changes for proper subject to be loaded<commit_after>package core\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"sync\"\n\n\t\"text\/template\"\n\n\t\"github.com\/bulletind\/khabar\/config\"\n\t\"github.com\/bulletind\/khabar\/db\"\n\t\"github.com\/bulletind\/khabar\/dbapi\/gully\"\n\t\"github.com\/bulletind\/khabar\/dbapi\/pending\"\n\t\"github.com\/bulletind\/khabar\/dbapi\/topics\"\n\t\"github.com\/bulletind\/khabar\/dbapi\/user_locale\"\n\t\"github.com\/nicksnyder\/go-i18n\/i18n\"\n\t\"gopkg.in\/simversity\/gotracer.v1\"\n)\n\nconst webIdent = \"web\"\nconst DEFAULT_LOCALE = \"en_US\"\nconst DEFAULT_TIMEZONE = \"GMT+0.0\"\n\nfunc sendToChannel(\n\tpending_item *pending.PendingItem,\n\ttext, channelIdent string,\n\tcontext map[string]interface{},\n) {\n\thandlerFunc, ok := ChannelMap[channelIdent]\n\tif !ok {\n\t\tlog.Println(\"No handler for Topic:\" + pending_item.Topic + \" Channel:\" + channelIdent)\n\t\treturn\n\t}\n\n\tdefer gotracer.Tracer{Dummy: true}.Notify()\n\thandlerFunc(pending_item, text, context)\n}\n\nfunc getText(locale, ident, channel string, pending_item *pending.PendingItem) string {\n\tT, _ := i18n.Tfunc(\n\t\tlocale+\"_\"+pending_item.AppName+\"_\"+pending_item.Organization+\"_\"+channel,\n\t\tlocale+\"_\"+pending_item.AppName+\"_\"+channel,\n\t\tlocale+\"_\"+channel,\n\t)\n\n\ttext := T(ident, pending_item.Context)\n\tif text == ident {\n\t\ttext = \"\"\n\t}\n\n\treturn text\n}\n\nfunc send(locale, channelIdent string, pending_item *pending.PendingItem) {\n\n\tif !topics.ChannelAllowed(pending_item.User, pending_item.AppName,\n\t\tpending_item.Organization, pending_item.Topic, channelIdent) {\n\t\tlog.Println(\"Channel :\" + channelIdent + \" \" + \"is blocked for topic :\" + pending_item.Topic)\n\t\treturn\n\t}\n\n\tchannel, err := gully.FindOne(\n\t\tpending_item.User,\n\t\tpending_item.AppName, pending_item.Organization,\n\t\tchannelIdent,\n\t)\n\n\tif err != nil {\n\t\tlog.Println(\"Unable to find channel : \" + channelIdent + err.Error())\n\t\treturn\n\t}\n\n\ttext := getText(locale, pending_item.Topic, channelIdent, pending_item)\n\tif text == \"\" {\n\t\t\/\/ If Topic == text, do not send the notification. This can happen\n\t\t\/\/ if the translation fails to find a sensible string in the JSON files\n\t\t\/\/ OR the translation provided was meaningless. To prevent the users\n\t\t\/\/ from being annpyed, abort this routine.\n\n\t\tlog.Println(\"No translation for:\" + channelIdent + pending_item.Topic)\n\t\treturn\n\t}\n\n\tif channelIdent == EMAIL || channel.Ident == PUSH {\n\t\tsubject := getText(locale, pending_item.Topic+\"_subject\", channelIdent, pending_item)\n\n\t\tif subject != \"\" {\n\t\t\tpending_item.Context[\"subject\"] = subject\n\t\t}\n\t}\n\n\tif channelIdent == EMAIL {\n\t\tbuffer := new(bytes.Buffer)\n\n\t\ttransDir := config.Settings.Khabar.TranslationDirectory\n\t\tpath := transDir + \"\/\" + locale + \"_base_email.tmpl\"\n\n\t\tif _, err := os.Stat(path); err == nil {\n\t\t\tcontent, err := ioutil.ReadFile(path)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Cannot Load the base email template\")\n\t\t\t} else {\n\t\t\t\tt := template.Must(template.New(\"email\").Parse(string(content)))\n\n\t\t\t\tdata := struct{ Content string }{text}\n\t\t\t\tt.Execute(buffer, &data)\n\t\t\t\ttext = buffer.String()\n\t\t\t}\n\t\t}\n\t}\n\n\tsendToChannel(pending_item, text, channel.Ident, channel.Data)\n}\n\nfunc SendNotification(pending_item *pending.PendingItem) {\n\tuserLocale, err := user_locale.Get(pending_item.User)\n\tif err != nil {\n\t\tlog.Println(\"Unable to find locale for user :\" + err.Error())\n\t\tuserLocale = new(db.UserLocale)\n\n\t\t\/\/FIXME:: Please do not hardcode this.\n\t\tuserLocale.Locale = DEFAULT_LOCALE\n\t\tuserLocale.TimeZone = DEFAULT_TIMEZONE\n\t}\n\n\tchildwg := new(sync.WaitGroup)\n\n\tfor channel, _ := range ChannelMap {\n\t\tchildwg.Add(1)\n\n\t\tgo func(\n\t\t\tlocale, channelIdent string,\n\t\t\tpending_item *pending.PendingItem,\n\t\t) {\n\t\t\tdefer childwg.Done()\n\t\t\tsend(locale, channelIdent, pending_item)\n\t\t}(userLocale.Locale, channel, pending_item)\n\t}\n\n\tchildwg.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cmd\n\nimport (\n\t\"fmt\"\n\t\"github.com\/blang\/semver\"\n\t\"github.com\/spf13\/cobra\"\n\t\"io\"\n\t\"k8s.io\/kops\/channels\/pkg\/channels\"\n\t\"k8s.io\/kops\/util\/pkg\/tables\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype ApplyChannelOptions struct {\n\tYes   bool\n\tFiles []string\n}\n\nfunc NewCmdApplyChannel(f Factory, out io.Writer) *cobra.Command {\n\tvar options ApplyChannelOptions\n\n\tcmd := &cobra.Command{\n\t\tUse:   \"channel\",\n\t\tShort: \"Apply channel\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn RunApplyChannel(f, out, &options, args)\n\t\t},\n\t}\n\n\tcmd.Flags().BoolVar(&options.Yes, \"yes\", false, \"Apply update\")\n\tcmd.Flags().StringSliceVar(&options.Files, \"f\", []string{}, \"Apply from a local file\")\n\n\treturn cmd\n}\n\nfunc RunApplyChannel(f Factory, out io.Writer, options *ApplyChannelOptions, args []string) error {\n\tk8sClient, err := f.KubernetesClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkubernetesVersionInfo, err := k8sClient.Discovery().ServerVersion()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error querying kubernetes version: %v\", err)\n\t}\n\n\t\/\/kubernetesVersion, err := semver.Parse(kubernetesVersionInfo.Major + \".\" + kubernetesVersionInfo.Minor + \".0\")\n\t\/\/if err != nil {\n\t\/\/\treturn fmt.Errorf(\"cannot parse kubernetes version %q\", kubernetesVersionInfo.Major+\".\"+kubernetesVersionInfo.Minor + \".0\")\n\t\/\/}\n\n\tkubernetesVersion, err := semver.ParseTolerant(kubernetesVersionInfo.GitVersion)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot parse kubernetes version %q\", kubernetesVersionInfo.GitVersion)\n\t}\n\n\t\/\/ Remove Pre and Patch, as they make semver comparisons impractical\n\tkubernetesVersion.Pre = nil\n\n\tmenu := channels.NewAddonMenu()\n\n\tfor _, name := range args {\n\t\tlocation, err := url.Parse(name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to parse argument %q as url\", name)\n\t\t}\n\t\tif !location.IsAbs() {\n\t\t\t\/\/ We recognize the following \"well-known\" format:\n\t\t\t\/\/ <name> with no slashes ->\n\t\t\tif strings.Contains(name, \"\/\") {\n\t\t\t\treturn fmt.Errorf(\"Channel format not recognized (did you mean to use `-f` to specify a local file?): %q\", name)\n\t\t\t}\n\t\t\texpanded := \"https:\/\/raw.githubusercontent.com\/kubernetes\/kops\/master\/addons\/\" + name + \"\/addon.yaml\"\n\t\t\tlocation, err = url.Parse(expanded)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to parse expanded argument %q as url\", expanded)\n\t\t\t}\n\t\t}\n\t\to, err := channels.LoadAddons(name, location)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error loading channel %q: %v\", location, err)\n\t\t}\n\n\t\tcurrent, err := o.GetCurrent(kubernetesVersion)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error processing latest versions in %q: %v\", location, err)\n\t\t}\n\t\tmenu.MergeAddons(current)\n\t}\n\n\tfor _, f := range options.Files {\n\t\tlocation, err := url.Parse(f)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to parse argument %q as url\", f)\n\t\t}\n\t\tif !location.IsAbs() {\n\t\t\tcwd, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error getting current directory: %v\", err)\n\t\t\t}\n\t\t\tbaseURL, err := url.Parse(cwd + string(os.PathSeparator))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error building url for current directory %q: %v\", cwd, err)\n\t\t\t}\n\t\t\tlocation = baseURL.ResolveReference(location)\n\t\t}\n\t\to, err := channels.LoadAddons(f, location)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error loading file %q: %v\", f, err)\n\t\t}\n\n\t\tcurrent, err := o.GetCurrent(kubernetesVersion)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error processing latest versions in %q: %v\", f, err)\n\t\t}\n\t\tmenu.MergeAddons(current)\n\t}\n\n\tvar updates []*channels.AddonUpdate\n\tvar needUpdates []*channels.Addon\n\tfor _, addon := range menu.Addons {\n\t\t\/\/ TODO: Cache lookups to prevent repeated lookups?\n\t\tupdate, err := addon.GetRequiredUpdates(k8sClient)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error checking for required update: %v\", err)\n\t\t}\n\t\tif update != nil {\n\t\t\tupdates = append(updates, update)\n\t\t\tneedUpdates = append(needUpdates, addon)\n\t\t}\n\t}\n\n\tif len(updates) == 0 {\n\t\tfmt.Printf(\"No update required\\n\")\n\t\treturn nil\n\t}\n\n\t{\n\t\tt := &tables.Table{}\n\t\tt.AddColumn(\"NAME\", func(r *channels.AddonUpdate) string {\n\t\t\treturn r.Name\n\t\t})\n\t\tt.AddColumn(\"CURRENT\", func(r *channels.AddonUpdate) string {\n\t\t\tif r.ExistingVersion == nil {\n\t\t\t\treturn \"-\"\n\t\t\t}\n\t\t\tif r.ExistingVersion.Version != nil {\n\t\t\t\treturn *r.ExistingVersion.Version\n\t\t\t}\n\t\t\treturn \"?\"\n\t\t})\n\t\tt.AddColumn(\"UPDATE\", func(r *channels.AddonUpdate) string {\n\t\t\tif r.NewVersion == nil {\n\t\t\t\treturn \"-\"\n\t\t\t}\n\t\t\tif r.NewVersion.Version != nil {\n\t\t\t\treturn *r.NewVersion.Version\n\t\t\t}\n\t\t\treturn \"?\"\n\t\t})\n\n\t\tcolumns := []string{\"NAME\", \"CURRENT\", \"UPDATE\"}\n\t\terr := t.Render(updates, os.Stdout, columns...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !options.Yes {\n\t\tfmt.Printf(\"\\nMust specify --yes to update\\n\")\n\t\treturn nil\n\t}\n\n\tfor _, needUpdate := range needUpdates {\n\t\tupdate, err := needUpdate.EnsureUpdated(k8sClient)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error updating %q: %v\", needUpdate.Name, err)\n\t\t}\n\t\t\/\/ Could have been a concurrent request\n\t\tif update != nil {\n\t\t\tif update.NewVersion.Version != nil {\n\t\t\t\tfmt.Printf(\"Updated %q to %s\\n\", update.Name, *update.NewVersion.Version)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Updated %q\\n\", update.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"\\n\")\n\n\treturn nil\n}\n<commit_msg>channels: accept -f and --files<commit_after>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cmd\n\nimport (\n\t\"fmt\"\n\t\"github.com\/blang\/semver\"\n\t\"github.com\/spf13\/cobra\"\n\t\"io\"\n\t\"k8s.io\/kops\/channels\/pkg\/channels\"\n\t\"k8s.io\/kops\/util\/pkg\/tables\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype ApplyChannelOptions struct {\n\tYes   bool\n\tFiles []string\n}\n\nfunc NewCmdApplyChannel(f Factory, out io.Writer) *cobra.Command {\n\tvar options ApplyChannelOptions\n\n\tcmd := &cobra.Command{\n\t\tUse:   \"channel\",\n\t\tShort: \"Apply channel\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn RunApplyChannel(f, out, &options, args)\n\t\t},\n\t}\n\n\tcmd.Flags().BoolVar(&options.Yes, \"yes\", false, \"Apply update\")\n\tcmd.Flags().StringSliceVarP(&options.Files, \"filename\", \"f\", []string{}, \"Apply from a local file\")\n\n\treturn cmd\n}\n\nfunc RunApplyChannel(f Factory, out io.Writer, options *ApplyChannelOptions, args []string) error {\n\tk8sClient, err := f.KubernetesClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkubernetesVersionInfo, err := k8sClient.Discovery().ServerVersion()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error querying kubernetes version: %v\", err)\n\t}\n\n\t\/\/kubernetesVersion, err := semver.Parse(kubernetesVersionInfo.Major + \".\" + kubernetesVersionInfo.Minor + \".0\")\n\t\/\/if err != nil {\n\t\/\/\treturn fmt.Errorf(\"cannot parse kubernetes version %q\", kubernetesVersionInfo.Major+\".\"+kubernetesVersionInfo.Minor + \".0\")\n\t\/\/}\n\n\tkubernetesVersion, err := semver.ParseTolerant(kubernetesVersionInfo.GitVersion)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot parse kubernetes version %q\", kubernetesVersionInfo.GitVersion)\n\t}\n\n\t\/\/ Remove Pre and Patch, as they make semver comparisons impractical\n\tkubernetesVersion.Pre = nil\n\n\tmenu := channels.NewAddonMenu()\n\n\tfor _, name := range args {\n\t\tlocation, err := url.Parse(name)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to parse argument %q as url\", name)\n\t\t}\n\t\tif !location.IsAbs() {\n\t\t\t\/\/ We recognize the following \"well-known\" format:\n\t\t\t\/\/ <name> with no slashes ->\n\t\t\tif strings.Contains(name, \"\/\") {\n\t\t\t\treturn fmt.Errorf(\"Channel format not recognized (did you mean to use `-f` to specify a local file?): %q\", name)\n\t\t\t}\n\t\t\texpanded := \"https:\/\/raw.githubusercontent.com\/kubernetes\/kops\/master\/addons\/\" + name + \"\/addon.yaml\"\n\t\t\tlocation, err = url.Parse(expanded)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to parse expanded argument %q as url\", expanded)\n\t\t\t}\n\t\t}\n\t\to, err := channels.LoadAddons(name, location)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error loading channel %q: %v\", location, err)\n\t\t}\n\n\t\tcurrent, err := o.GetCurrent(kubernetesVersion)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error processing latest versions in %q: %v\", location, err)\n\t\t}\n\t\tmenu.MergeAddons(current)\n\t}\n\n\tfor _, f := range options.Files {\n\t\tlocation, err := url.Parse(f)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to parse argument %q as url\", f)\n\t\t}\n\t\tif !location.IsAbs() {\n\t\t\tcwd, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error getting current directory: %v\", err)\n\t\t\t}\n\t\t\tbaseURL, err := url.Parse(cwd + string(os.PathSeparator))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error building url for current directory %q: %v\", cwd, err)\n\t\t\t}\n\t\t\tlocation = baseURL.ResolveReference(location)\n\t\t}\n\t\to, err := channels.LoadAddons(f, location)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error loading file %q: %v\", f, err)\n\t\t}\n\n\t\tcurrent, err := o.GetCurrent(kubernetesVersion)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error processing latest versions in %q: %v\", f, err)\n\t\t}\n\t\tmenu.MergeAddons(current)\n\t}\n\n\tvar updates []*channels.AddonUpdate\n\tvar needUpdates []*channels.Addon\n\tfor _, addon := range menu.Addons {\n\t\t\/\/ TODO: Cache lookups to prevent repeated lookups?\n\t\tupdate, err := addon.GetRequiredUpdates(k8sClient)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error checking for required update: %v\", err)\n\t\t}\n\t\tif update != nil {\n\t\t\tupdates = append(updates, update)\n\t\t\tneedUpdates = append(needUpdates, addon)\n\t\t}\n\t}\n\n\tif len(updates) == 0 {\n\t\tfmt.Printf(\"No update required\\n\")\n\t\treturn nil\n\t}\n\n\t{\n\t\tt := &tables.Table{}\n\t\tt.AddColumn(\"NAME\", func(r *channels.AddonUpdate) string {\n\t\t\treturn r.Name\n\t\t})\n\t\tt.AddColumn(\"CURRENT\", func(r *channels.AddonUpdate) string {\n\t\t\tif r.ExistingVersion == nil {\n\t\t\t\treturn \"-\"\n\t\t\t}\n\t\t\tif r.ExistingVersion.Version != nil {\n\t\t\t\treturn *r.ExistingVersion.Version\n\t\t\t}\n\t\t\treturn \"?\"\n\t\t})\n\t\tt.AddColumn(\"UPDATE\", func(r *channels.AddonUpdate) string {\n\t\t\tif r.NewVersion == nil {\n\t\t\t\treturn \"-\"\n\t\t\t}\n\t\t\tif r.NewVersion.Version != nil {\n\t\t\t\treturn *r.NewVersion.Version\n\t\t\t}\n\t\t\treturn \"?\"\n\t\t})\n\n\t\tcolumns := []string{\"NAME\", \"CURRENT\", \"UPDATE\"}\n\t\terr := t.Render(updates, os.Stdout, columns...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !options.Yes {\n\t\tfmt.Printf(\"\\nMust specify --yes to update\\n\")\n\t\treturn nil\n\t}\n\n\tfor _, needUpdate := range needUpdates {\n\t\tupdate, err := needUpdate.EnsureUpdated(k8sClient)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error updating %q: %v\", needUpdate.Name, err)\n\t\t}\n\t\t\/\/ Could have been a concurrent request\n\t\tif update != nil {\n\t\t\tif update.NewVersion.Version != nil {\n\t\t\t\tfmt.Printf(\"Updated %q to %s\\n\", update.Name, *update.NewVersion.Version)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Updated %q\\n\", update.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Printf(\"\\n\")\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package dynago\n\nimport (\n\t\"encoding\/json\"\n\t\"time\"\n)\n\nconst (\n\tSELECT_ALL        = \"ALL_ATTRIBUTES\"\n\tSELECT_PROJECTED  = \"ALL_PROJECTED_ATTRIBUTES\"\n\tSELECT_ATTRIBUTES = \"SPECIFIC_ATTRIBUTES\"\n\tSELECT_COUNT      = \"COUNT\"\n)\n\nvar (\n\tRETURN_CONSUMED = map[bool]string{true: \"TOTAL\", false: \"NONE\"}\n\n\tRETURN_TOTAL_CONSUMED = \"TOTAL\"\n\tRETURN_INDEX_CONSUMED = \"INDEXED\"\n\n\tRETURN_METRICS = map[bool]string{true: \"SIZE\", false: \"NONE\"}\n\n\tRETURN_NONE        = \"NONE\"\n\tRETURN_ALL_OLD     = \"ALL_OLD\"\n\tRETURN_ALL_NEW     = \"ALL_NEW\"\n\tRETURN_UPDATED_OLD = \"UPDATED_OLD\"\n\tRETURN_UPDATED_NEW = \"UPDATED_NEW\"\n)\n\ntype ConsumedCapacityDescription struct {\n\tCapacityUnits float32\n\tTableName     string\n}\n\ntype KeyValue struct {\n\tKey   AttributeDefinition\n\tValue interface{}\n}\n\n\/\/ Items are maps of name\/value pairs\ntype Item map[string]interface{}\n\nfunc (pi *Item) UnmarshalJSON(data []byte) error {\n\tvar dbitem AttributeNameValue\n\n\tif err := json.Unmarshal(data, &dbitem); err != nil {\n\t\treturn err\n\t}\n\n\titem := make(Item)\n\n\tfor k, v := range dbitem {\n\t\titem[k] = DecodeValue(v)\n\t}\n\n\t*pi = item\n\treturn nil\n}\n\nfunc (pi *Item) MarshalJSON() ([]byte, error) {\n\tdbitem := AttributeNameValue{}\n\n\tfor k, v := range *pi {\n\t\tdbitem[k] = EncodeValue(v)\n\t}\n\n\treturn json.Marshal(dbitem)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Put\/Update\/Delete Item Result\n\/\/\n\ntype ItemResult struct {\n\tAttributes            Item\n\tConsumedCapacity      ConsumedCapacityDescription\n\tItemCollectionMetrics ItemCollectionMetrics\n}\n\ntype ItemCollectionMetrics struct {\n\tItemCollectionKey   AttributeNameValue\n\tSizeEstimateRangeGB []float64\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Put\/Update\/Delete Item Request\n\/\/\n\ntype ItemRequest struct {\n\tTableName string\n\n\tItem             *Item              `json:\",omitempty\"` \/\/ PutItem\n\tKey              AttributeNameValue `json:\",omitempty\"` \/\/ UpdateItem\/DeleteItem\n\tUpdateExpression string             `json:\",omitempty\"` \/\/ UpdateItem\n\n\tConditionExpression       string             `json:\",omitempty\"`\n\tExpressionAttributeNames  map[string]string  `json:\",omitempty\"`\n\tExpressionAttributeValues AttributeNameValue `json:\",omitempty\"`\n\n\tReturnConsumedCapacity      string `json:\",omitempty\"` \/\/ INDEXED | TOTAL | NONE\n\tReturnItemCollectionMetrics string `json:\",omitempty\"` \/\/ SIZE | NONE\n\tReturnValues                string `json:\",omitempty\"` \/\/ NONE | ALL_OLD | UPDATED_OLD | ALL_NEW | UPDATED_NEW\n}\n\ntype ItemOption func(*ItemRequest)\n\nfunc ConditionExpression(expr string) ItemOption {\n\treturn func(req *ItemRequest) {\n\t\treq.ConditionExpression = expr\n\t}\n}\n\nfunc ExpressionAttributeNames(names map[string]string) ItemOption {\n\treturn func(req *ItemRequest) {\n\t\treq.ExpressionAttributeNames = names\n\t}\n}\n\nfunc ExpressionAttributeValues(values map[string]interface{}) ItemOption {\n\treturn func(req *ItemRequest) {\n\t\treq.ExpressionAttributeValues = EncodeItem(values)\n\t}\n}\n\nfunc ReturnConsumed(target string) ItemOption {\n\treturn func(req *ItemRequest) {\n\t\treq.ReturnConsumedCapacity = target\n\t}\n}\n\nfunc ReturnMetrics(ret bool) ItemOption {\n\treturn func(req *ItemRequest) {\n\t\treq.ReturnItemCollectionMetrics = RETURN_METRICS[ret]\n\t}\n}\n\nfunc ReturnValues(target string) ItemOption {\n\treturn func(req *ItemRequest) {\n\t\treq.ReturnValues = target\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PutItem\n\/\/\n\nfunc (db *DBClient) PutItem(tableName string, item Item, options ...ItemOption) (*Item, float32, error) {\n\tvar req = ItemRequest{TableName: tableName, Item: &item}\n\tvar res ItemResult\n\n\tfor _, option := range options {\n\t\toption(&req)\n\t}\n\n\tif err := db.Query(\"PutItem\", &req).Decode(&res); err != nil {\n\t\treturn nil, 0.0, err\n\t} else {\n\t\treturn &res.Attributes, res.ConsumedCapacity.CapacityUnits, err\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ UpdateItem\n\/\/\n\nfunc (db *DBClient) UpdateItem(tableName string, hashKey *KeyValue, rangeKey *KeyValue, updates string, options ...ItemOption) (*Item, float32, error) {\n\tvar req = ItemRequest{TableName: tableName, UpdateExpression: updates}\n\tvar res ItemResult\n\n\treq.Key = EncodeAttribute(hashKey.Key, hashKey.Value)\n\tif rangeKey != nil {\n\t\treq.Key[rangeKey.Key.AttributeName] = EncodeAttributeValue(rangeKey.Key, rangeKey.Value)\n\t}\n\n\tif rangeKey != nil {\n\t\treq.Key[rangeKey.Key.AttributeName] = EncodeAttributeValue(rangeKey.Key, rangeKey.Value)\n\t}\n\n\tfor _, option := range options {\n\t\toption(&req)\n\t}\n\n\tif err := db.Query(\"UpdateItem\", &req).Decode(&res); err != nil {\n\t\treturn nil, 0.0, err\n\t} else {\n\t\treturn &res.Attributes, res.ConsumedCapacity.CapacityUnits, err\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ DeleteItem\n\/\/\n\nfunc (db *DBClient) DeleteItem(tableName string, hashKey *KeyValue, rangeKey *KeyValue, options ...ItemOption) (*Item, float32, error) {\n\tvar req = ItemRequest{TableName: tableName}\n\tvar res ItemResult\n\n\treq.Key = EncodeAttribute(hashKey.Key, hashKey.Value)\n\tif rangeKey != nil {\n\t\treq.Key[rangeKey.Key.AttributeName] = EncodeAttributeValue(rangeKey.Key, rangeKey.Value)\n\t}\n\n\tfor _, option := range options {\n\t\toption(&req)\n\t}\n\n\tif err := db.Query(\"DeleteItem\", &req).Decode(&res); err != nil {\n\t\treturn nil, 0.0, err\n\t} else {\n\t\treturn &res.Attributes, res.ConsumedCapacity.CapacityUnits, err\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ GetItem\n\/\/\n\ntype GetItemRequest struct {\n\tTableName              string\n\tKey                    AttributeNameValue\n\tAttributesToGet        []string\n\tConsistentRead         bool\n\tReturnConsumedCapacity string\n}\n\ntype GetItemResult struct {\n\tConsumedCapacity ConsumedCapacityDescription\n\n\tItem Item\n}\n\nfunc (db *DBClient) GetItem(tableName string, hashKey *KeyValue, rangeKey *KeyValue, attributes []string, consistent bool, consumed bool) (map[string]interface{}, float32, error) {\n\n\treq := GetItemRequest{TableName: tableName, AttributesToGet: attributes, ConsistentRead: consistent, ReturnConsumedCapacity: RETURN_CONSUMED[consumed]}\n\treq.Key = EncodeAttribute(hashKey.Key, hashKey.Value)\n\tif rangeKey != nil {\n\t\treq.Key[rangeKey.Key.AttributeName] = EncodeAttributeValue(rangeKey.Key, rangeKey.Value)\n\t}\n\n\tvar res GetItemResult\n\n\tif err := db.Query(\"GetItem\", req).Decode(&res); err != nil {\n\t\treturn nil, 0.0, err\n\t}\n\n\tif len(res.Item) == 0 {\n\t\treturn nil, res.ConsumedCapacity.CapacityUnits, nil\n\t}\n\n\treturn res.Item, res.ConsumedCapacity.CapacityUnits, nil\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Query\n\/\/\n\ntype QueryRequest struct {\n\tTableName        string\n\tAttributesToGet  []string `json:\",omitempty\"`\n\tScanIndexForward bool\n\n\tExclusiveStartKey AttributeNameValue   `json:\",omitempty\"`\n\tKeyConditions     map[string]Condition `json:\",omitempty\"`\n\tIndexName         string               `json:\",omitempty\"`\n\n\tFilterExpression          string             `json:\",omitempty\"`\n\tProjectionExpression      string             `json:\",omitempty\"`\n\tExpressionAttributeNames  map[string]string  `json:\",omitempty\"`\n\tExpressionAttributeValues AttributeNameValue `json:\",omitempty\"`\n\n\tLimit                  *int   `json:\",omitempty\"`\n\tSelect                 string `json:\",omitempty\"`\n\tReturnConsumedCapacity string `json:\",omitempty\"`\n\n\ttable *TableInstance\n}\n\ntype QueryResult struct {\n\tItems            []Item\n\tConsumedCapacity ConsumedCapacityDescription\n\tLastEvaluatedKey AttributeNameValue\n\tCount            int\n\tScannedCount     int\n}\n\nfunc QueryTable(table *TableInstance) *QueryRequest {\n\treturn &QueryRequest{TableName: table.Name, ScanIndexForward: true, KeyConditions: make(map[string]Condition), table: table}\n}\n\nfunc Query(tableName string) *QueryRequest {\n\treturn &QueryRequest{TableName: tableName, ScanIndexForward: true, KeyConditions: make(map[string]Condition)}\n}\n\nfunc (req *QueryRequest) SetAttributes(attributes []string) *QueryRequest {\n\treq.AttributesToGet = attributes\n\treturn req\n}\n\nfunc (req *QueryRequest) SetStartKey(startKey AttributeNameValue) *QueryRequest {\n\treq.ExclusiveStartKey = startKey\n\treturn req\n}\n\nfunc (req *QueryRequest) SetIndex(indexName string) *QueryRequest {\n\treq.IndexName = indexName\n\treturn req\n}\n\nfunc (req *QueryRequest) SetCondition(attrName string, condition Condition) *QueryRequest {\n\treq.KeyConditions[attrName] = condition\n\treturn req\n}\n\nfunc (req *QueryRequest) SetAttrCondition(cond AttrCondition) *QueryRequest {\n\tfor k, v := range cond {\n\t\treq.KeyConditions[k] = v\n\t}\n\n\treturn req\n}\n\nfunc (req *QueryRequest) SetFilterExpression(filter string) *QueryRequest {\n\treq.FilterExpression = filter\n\treturn req\n}\n\nfunc (req *QueryRequest) SetProjectionExpression(proj string) *QueryRequest {\n\treq.ProjectionExpression = proj\n\treturn req\n}\n\nfunc (req *QueryRequest) SetLimit(limit int) *QueryRequest {\n\treq.Limit = &limit\n\treturn req\n}\n\nfunc (req *QueryRequest) SetSelect(selectValue string) *QueryRequest {\n\treq.Select = selectValue\n\treturn req\n}\n\nfunc (req *QueryRequest) SetConsumed(consumed bool) *QueryRequest {\n\treq.ReturnConsumedCapacity = RETURN_CONSUMED[consumed]\n\treturn req\n}\n\nfunc (req *QueryRequest) Exec(db *DBClient) ([]Item, AttributeNameValue, float32, error) {\n\tif db == nil && req.table != nil {\n\t\tdb = req.table.DB\n\t}\n\n\tvar res QueryResult\n\n\tif err := db.Query(\"Query\", req).Decode(&res); err != nil {\n\t\treturn nil, nil, 0.0, err\n\t}\n\n\treturn res.Items, res.LastEvaluatedKey, res.ConsumedCapacity.CapacityUnits, nil\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Scan\n\/\/\n\ntype ScanRequest struct {\n\tTableName         string\n\tAttributesToGet   []string\n\tExclusiveStartKey AttributeNameValue\n\n\tFilterExpression          string             `json:\",omitempty\"`\n\tProjectionExpression      string             `json:\",omitempty\"`\n\tExpressionAttributeNames  map[string]string  `json:\",omitempty\"`\n\tExpressionAttributeValues AttributeNameValue `json:\",omitempty\"`\n\n\tLimit                  *int   `json:\",omitempty\"`\n\tSegment                *int   `json:\",omitempty\"`\n\tTotalSegments          *int   `json:\",omitempty\"`\n\tSelect                 string `json:\",omitempty\"`\n\tReturnConsumedCapacity string `json:\",omitempty\"`\n\n\ttable *TableInstance\n}\n\nfunc ScanTable(table *TableInstance) *ScanRequest {\n\treturn &ScanRequest{TableName: table.Name, table: table}\n}\n\nfunc Scan(tableName string) *ScanRequest {\n\treturn &ScanRequest{TableName: tableName}\n}\n\nfunc (req *ScanRequest) SetAttributes(attributes []string) *ScanRequest {\n\treq.AttributesToGet = attributes\n\treturn req\n}\n\nfunc (req *ScanRequest) SetStartKey(startKey AttributeNameValue) *ScanRequest {\n\treq.ExclusiveStartKey = startKey\n\treturn req\n}\n\nfunc (req *ScanRequest) SetFilterExpression(filter string) *ScanRequest {\n\treq.FilterExpression = filter\n\treturn req\n}\n\nfunc (req *ScanRequest) SetProjectionExpression(proj string) *ScanRequest {\n\treq.ProjectionExpression = proj\n\treturn req\n}\n\nfunc (req *ScanRequest) SetLimit(limit int) *ScanRequest {\n\treq.Limit = &limit\n\treturn req\n}\n\nfunc (req *ScanRequest) SetSegment(segment, totalSegments int) *ScanRequest {\n\treq.Segment = &segment\n\treq.TotalSegments = &totalSegments\n\treturn req\n}\n\nfunc (req *ScanRequest) SetSelect(selectValue string) *ScanRequest {\n\treq.Select = selectValue\n\treturn req\n}\n\nfunc (req *ScanRequest) SetConsumed(consumed bool) *ScanRequest {\n\treq.ReturnConsumedCapacity = RETURN_CONSUMED[consumed]\n\treturn req\n}\n\nfunc (req *ScanRequest) Exec(db *DBClient) ([]Item, AttributeNameValue, float32, error) {\n\tvar res QueryResult\n\n\tif err := db.Query(\"Scan\", req).Decode(&res); err != nil {\n\t\treturn nil, nil, 0.0, err\n\t}\n\n\treturn res.Items, res.LastEvaluatedKey, res.ConsumedCapacity.CapacityUnits, nil\n}\n\nfunc (req *ScanRequest) Count(db *DBClient) (count int, scount int, consumed float32, err error) {\n\treturn req.CountWithDelay(db, 0)\n}\n\nfunc (req *ScanRequest) CountWithDelay(db *DBClient, delay time.Duration) (count int, scount int, consumed float32, err error) {\n\tvar res QueryResult\n\n\tcreq := *req\n\tcreq.Select = SELECT_COUNT\n\n\tfor {\n\t\tres.LastEvaluatedKey = nil\n\n\t\tif err = db.Query(\"Scan\", &creq).Decode(&res); err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tcount += res.Count\n\t\tscount += res.ScannedCount\n\t\tconsumed += res.ConsumedCapacity.CapacityUnits\n\n\t\tif res.LastEvaluatedKey == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tcreq.ExclusiveStartKey = make(AttributeNameValue)\n\t\tfor k, v := range res.LastEvaluatedKey {\n\t\t\tcreq.ExclusiveStartKey[k] = v\n\t\t}\n\n\t\tif delay > 0 {\n\t\t\ttime.Sleep(delay)\n\t\t}\n\t}\n\n\treturn\n}\n<commit_msg>make some parameters optionals (no need to pass nil)<commit_after>package dynago\n\nimport (\n\t\"encoding\/json\"\n\t\"time\"\n)\n\nconst (\n\tSELECT_ALL        = \"ALL_ATTRIBUTES\"\n\tSELECT_PROJECTED  = \"ALL_PROJECTED_ATTRIBUTES\"\n\tSELECT_ATTRIBUTES = \"SPECIFIC_ATTRIBUTES\"\n\tSELECT_COUNT      = \"COUNT\"\n)\n\nvar (\n\tRETURN_CONSUMED = map[bool]string{true: \"TOTAL\", false: \"NONE\"}\n\n\tRETURN_TOTAL_CONSUMED = \"TOTAL\"\n\tRETURN_INDEX_CONSUMED = \"INDEXED\"\n\n\tRETURN_METRICS = map[bool]string{true: \"SIZE\", false: \"NONE\"}\n\n\tRETURN_NONE        = \"NONE\"\n\tRETURN_ALL_OLD     = \"ALL_OLD\"\n\tRETURN_ALL_NEW     = \"ALL_NEW\"\n\tRETURN_UPDATED_OLD = \"UPDATED_OLD\"\n\tRETURN_UPDATED_NEW = \"UPDATED_NEW\"\n)\n\ntype ConsumedCapacityDescription struct {\n\tCapacityUnits float32\n\tTableName     string\n}\n\ntype KeyValue struct {\n\tKey   AttributeDefinition\n\tValue interface{}\n}\n\n\/\/ Items are maps of name\/value pairs\ntype Item map[string]interface{}\n\nfunc (pi *Item) UnmarshalJSON(data []byte) error {\n\tvar dbitem AttributeNameValue\n\n\tif err := json.Unmarshal(data, &dbitem); err != nil {\n\t\treturn err\n\t}\n\n\titem := make(Item)\n\n\tfor k, v := range dbitem {\n\t\titem[k] = DecodeValue(v)\n\t}\n\n\t*pi = item\n\treturn nil\n}\n\nfunc (pi *Item) MarshalJSON() ([]byte, error) {\n\tdbitem := AttributeNameValue{}\n\n\tfor k, v := range *pi {\n\t\tdbitem[k] = EncodeValue(v)\n\t}\n\n\treturn json.Marshal(dbitem)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Put\/Update\/Delete Item Result\n\/\/\n\ntype ItemResult struct {\n\tAttributes            Item\n\tConsumedCapacity      ConsumedCapacityDescription\n\tItemCollectionMetrics ItemCollectionMetrics\n}\n\ntype ItemCollectionMetrics struct {\n\tItemCollectionKey   AttributeNameValue\n\tSizeEstimateRangeGB []float64\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Put\/Update\/Delete Item Request\n\/\/\n\ntype ItemRequest struct {\n\tTableName string\n\n\tItem             *Item              `json:\",omitempty\"` \/\/ PutItem\n\tKey              AttributeNameValue `json:\",omitempty\"` \/\/ UpdateItem\/DeleteItem\n\tUpdateExpression string             `json:\",omitempty\"` \/\/ UpdateItem\n\n\tConditionExpression       string             `json:\",omitempty\"`\n\tExpressionAttributeNames  map[string]string  `json:\",omitempty\"`\n\tExpressionAttributeValues AttributeNameValue `json:\",omitempty\"`\n\n\tReturnConsumedCapacity      string `json:\",omitempty\"` \/\/ INDEXED | TOTAL | NONE\n\tReturnItemCollectionMetrics string `json:\",omitempty\"` \/\/ SIZE | NONE\n\tReturnValues                string `json:\",omitempty\"` \/\/ NONE | ALL_OLD | UPDATED_OLD | ALL_NEW | UPDATED_NEW\n}\n\ntype ItemOption func(*ItemRequest)\n\nfunc ConditionExpression(expr string) ItemOption {\n\treturn func(req *ItemRequest) {\n\t\treq.ConditionExpression = expr\n\t}\n}\n\nfunc ExpressionAttributeNames(names map[string]string) ItemOption {\n\treturn func(req *ItemRequest) {\n\t\treq.ExpressionAttributeNames = names\n\t}\n}\n\nfunc ExpressionAttributeValues(values map[string]interface{}) ItemOption {\n\treturn func(req *ItemRequest) {\n\t\treq.ExpressionAttributeValues = EncodeItem(values)\n\t}\n}\n\nfunc ReturnConsumed(target string) ItemOption {\n\treturn func(req *ItemRequest) {\n\t\treq.ReturnConsumedCapacity = target\n\t}\n}\n\nfunc ReturnMetrics(ret bool) ItemOption {\n\treturn func(req *ItemRequest) {\n\t\treq.ReturnItemCollectionMetrics = RETURN_METRICS[ret]\n\t}\n}\n\nfunc ReturnValues(target string) ItemOption {\n\treturn func(req *ItemRequest) {\n\t\treq.ReturnValues = target\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ PutItem\n\/\/\n\nfunc (db *DBClient) PutItem(tableName string, item Item, options ...ItemOption) (*Item, float32, error) {\n\tvar req = ItemRequest{TableName: tableName, Item: &item}\n\tvar res ItemResult\n\n\tfor _, option := range options {\n\t\toption(&req)\n\t}\n\n\tif err := db.Query(\"PutItem\", &req).Decode(&res); err != nil {\n\t\treturn nil, 0.0, err\n\t} else {\n\t\treturn &res.Attributes, res.ConsumedCapacity.CapacityUnits, err\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ UpdateItem\n\/\/\n\nfunc (db *DBClient) UpdateItem(tableName string, hashKey *KeyValue, rangeKey *KeyValue, updates string, options ...ItemOption) (*Item, float32, error) {\n\tvar req = ItemRequest{TableName: tableName, UpdateExpression: updates}\n\tvar res ItemResult\n\n\treq.Key = EncodeAttribute(hashKey.Key, hashKey.Value)\n\tif rangeKey != nil {\n\t\treq.Key[rangeKey.Key.AttributeName] = EncodeAttributeValue(rangeKey.Key, rangeKey.Value)\n\t}\n\n\tif rangeKey != nil {\n\t\treq.Key[rangeKey.Key.AttributeName] = EncodeAttributeValue(rangeKey.Key, rangeKey.Value)\n\t}\n\n\tfor _, option := range options {\n\t\toption(&req)\n\t}\n\n\tif err := db.Query(\"UpdateItem\", &req).Decode(&res); err != nil {\n\t\treturn nil, 0.0, err\n\t} else {\n\t\treturn &res.Attributes, res.ConsumedCapacity.CapacityUnits, err\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ DeleteItem\n\/\/\n\nfunc (db *DBClient) DeleteItem(tableName string, hashKey *KeyValue, rangeKey *KeyValue, options ...ItemOption) (*Item, float32, error) {\n\tvar req = ItemRequest{TableName: tableName}\n\tvar res ItemResult\n\n\treq.Key = EncodeAttribute(hashKey.Key, hashKey.Value)\n\tif rangeKey != nil {\n\t\treq.Key[rangeKey.Key.AttributeName] = EncodeAttributeValue(rangeKey.Key, rangeKey.Value)\n\t}\n\n\tfor _, option := range options {\n\t\toption(&req)\n\t}\n\n\tif err := db.Query(\"DeleteItem\", &req).Decode(&res); err != nil {\n\t\treturn nil, 0.0, err\n\t} else {\n\t\treturn &res.Attributes, res.ConsumedCapacity.CapacityUnits, err\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ GetItem\n\/\/\n\ntype GetItemRequest struct {\n\tTableName              string\n\tKey                    AttributeNameValue\n\tAttributesToGet        []string `json:\",omitempty\"`\n\tConsistentRead         bool\n\tReturnConsumedCapacity string `json:\",omitempty\"`\n}\n\ntype GetItemResult struct {\n\tConsumedCapacity ConsumedCapacityDescription\n\n\tItem Item\n}\n\nfunc (db *DBClient) GetItem(tableName string, hashKey *KeyValue, rangeKey *KeyValue, attributes []string, consistent bool, consumed bool) (map[string]interface{}, float32, error) {\n\n\treq := GetItemRequest{TableName: tableName, AttributesToGet: attributes, ConsistentRead: consistent, ReturnConsumedCapacity: RETURN_CONSUMED[consumed]}\n\treq.Key = EncodeAttribute(hashKey.Key, hashKey.Value)\n\tif rangeKey != nil {\n\t\treq.Key[rangeKey.Key.AttributeName] = EncodeAttributeValue(rangeKey.Key, rangeKey.Value)\n\t}\n\n\tvar res GetItemResult\n\n\tif err := db.Query(\"GetItem\", req).Decode(&res); err != nil {\n\t\treturn nil, 0.0, err\n\t}\n\n\tif len(res.Item) == 0 {\n\t\treturn nil, res.ConsumedCapacity.CapacityUnits, nil\n\t}\n\n\treturn res.Item, res.ConsumedCapacity.CapacityUnits, nil\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Query\n\/\/\n\ntype QueryRequest struct {\n\tTableName        string\n\tAttributesToGet  []string `json:\",omitempty\"`\n\tScanIndexForward bool\n\n\tExclusiveStartKey AttributeNameValue   `json:\",omitempty\"`\n\tKeyConditions     map[string]Condition `json:\",omitempty\"`\n\tIndexName         string               `json:\",omitempty\"`\n\n\tFilterExpression          string             `json:\",omitempty\"`\n\tProjectionExpression      string             `json:\",omitempty\"`\n\tExpressionAttributeNames  map[string]string  `json:\",omitempty\"`\n\tExpressionAttributeValues AttributeNameValue `json:\",omitempty\"`\n\n\tLimit                  *int   `json:\",omitempty\"`\n\tSelect                 string `json:\",omitempty\"`\n\tReturnConsumedCapacity string `json:\",omitempty\"`\n\n\ttable *TableInstance\n}\n\ntype QueryResult struct {\n\tItems            []Item\n\tConsumedCapacity ConsumedCapacityDescription\n\tLastEvaluatedKey AttributeNameValue\n\tCount            int\n\tScannedCount     int\n}\n\nfunc QueryTable(table *TableInstance) *QueryRequest {\n\treturn &QueryRequest{TableName: table.Name, ScanIndexForward: true, KeyConditions: make(map[string]Condition), table: table}\n}\n\nfunc Query(tableName string) *QueryRequest {\n\treturn &QueryRequest{TableName: tableName, ScanIndexForward: true, KeyConditions: make(map[string]Condition)}\n}\n\nfunc (req *QueryRequest) SetAttributes(attributes []string) *QueryRequest {\n\treq.AttributesToGet = attributes\n\treturn req\n}\n\nfunc (req *QueryRequest) SetStartKey(startKey AttributeNameValue) *QueryRequest {\n\treq.ExclusiveStartKey = startKey\n\treturn req\n}\n\nfunc (req *QueryRequest) SetIndex(indexName string) *QueryRequest {\n\treq.IndexName = indexName\n\treturn req\n}\n\nfunc (req *QueryRequest) SetCondition(attrName string, condition Condition) *QueryRequest {\n\treq.KeyConditions[attrName] = condition\n\treturn req\n}\n\nfunc (req *QueryRequest) SetAttrCondition(cond AttrCondition) *QueryRequest {\n\tfor k, v := range cond {\n\t\treq.KeyConditions[k] = v\n\t}\n\n\treturn req\n}\n\nfunc (req *QueryRequest) SetFilterExpression(filter string) *QueryRequest {\n\treq.FilterExpression = filter\n\treturn req\n}\n\nfunc (req *QueryRequest) SetProjectionExpression(proj string) *QueryRequest {\n\treq.ProjectionExpression = proj\n\treturn req\n}\n\nfunc (req *QueryRequest) SetLimit(limit int) *QueryRequest {\n\treq.Limit = &limit\n\treturn req\n}\n\nfunc (req *QueryRequest) SetSelect(selectValue string) *QueryRequest {\n\treq.Select = selectValue\n\treturn req\n}\n\nfunc (req *QueryRequest) SetConsumed(consumed bool) *QueryRequest {\n\treq.ReturnConsumedCapacity = RETURN_CONSUMED[consumed]\n\treturn req\n}\n\nfunc (req *QueryRequest) Exec(db *DBClient) ([]Item, AttributeNameValue, float32, error) {\n\tif db == nil && req.table != nil {\n\t\tdb = req.table.DB\n\t}\n\n\tvar res QueryResult\n\n\tif err := db.Query(\"Query\", req).Decode(&res); err != nil {\n\t\treturn nil, nil, 0.0, err\n\t}\n\n\treturn res.Items, res.LastEvaluatedKey, res.ConsumedCapacity.CapacityUnits, nil\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Scan\n\/\/\n\ntype ScanRequest struct {\n\tTableName         string\n\tAttributesToGet   []string\n\tExclusiveStartKey AttributeNameValue\n\n\tFilterExpression          string             `json:\",omitempty\"`\n\tProjectionExpression      string             `json:\",omitempty\"`\n\tExpressionAttributeNames  map[string]string  `json:\",omitempty\"`\n\tExpressionAttributeValues AttributeNameValue `json:\",omitempty\"`\n\n\tLimit                  *int   `json:\",omitempty\"`\n\tSegment                *int   `json:\",omitempty\"`\n\tTotalSegments          *int   `json:\",omitempty\"`\n\tSelect                 string `json:\",omitempty\"`\n\tReturnConsumedCapacity string `json:\",omitempty\"`\n\n\ttable *TableInstance\n}\n\nfunc ScanTable(table *TableInstance) *ScanRequest {\n\treturn &ScanRequest{TableName: table.Name, table: table}\n}\n\nfunc Scan(tableName string) *ScanRequest {\n\treturn &ScanRequest{TableName: tableName}\n}\n\nfunc (req *ScanRequest) SetAttributes(attributes []string) *ScanRequest {\n\treq.AttributesToGet = attributes\n\treturn req\n}\n\nfunc (req *ScanRequest) SetStartKey(startKey AttributeNameValue) *ScanRequest {\n\treq.ExclusiveStartKey = startKey\n\treturn req\n}\n\nfunc (req *ScanRequest) SetFilterExpression(filter string) *ScanRequest {\n\treq.FilterExpression = filter\n\treturn req\n}\n\nfunc (req *ScanRequest) SetProjectionExpression(proj string) *ScanRequest {\n\treq.ProjectionExpression = proj\n\treturn req\n}\n\nfunc (req *ScanRequest) SetLimit(limit int) *ScanRequest {\n\treq.Limit = &limit\n\treturn req\n}\n\nfunc (req *ScanRequest) SetSegment(segment, totalSegments int) *ScanRequest {\n\treq.Segment = &segment\n\treq.TotalSegments = &totalSegments\n\treturn req\n}\n\nfunc (req *ScanRequest) SetSelect(selectValue string) *ScanRequest {\n\treq.Select = selectValue\n\treturn req\n}\n\nfunc (req *ScanRequest) SetConsumed(consumed bool) *ScanRequest {\n\treq.ReturnConsumedCapacity = RETURN_CONSUMED[consumed]\n\treturn req\n}\n\nfunc (req *ScanRequest) Exec(db *DBClient) ([]Item, AttributeNameValue, float32, error) {\n\tvar res QueryResult\n\n\tif err := db.Query(\"Scan\", req).Decode(&res); err != nil {\n\t\treturn nil, nil, 0.0, err\n\t}\n\n\treturn res.Items, res.LastEvaluatedKey, res.ConsumedCapacity.CapacityUnits, nil\n}\n\nfunc (req *ScanRequest) Count(db *DBClient) (count int, scount int, consumed float32, err error) {\n\treturn req.CountWithDelay(db, 0)\n}\n\nfunc (req *ScanRequest) CountWithDelay(db *DBClient, delay time.Duration) (count int, scount int, consumed float32, err error) {\n\tvar res QueryResult\n\n\tcreq := *req\n\tcreq.Select = SELECT_COUNT\n\n\tfor {\n\t\tres.LastEvaluatedKey = nil\n\n\t\tif err = db.Query(\"Scan\", &creq).Decode(&res); err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tcount += res.Count\n\t\tscount += res.ScannedCount\n\t\tconsumed += res.ConsumedCapacity.CapacityUnits\n\n\t\tif res.LastEvaluatedKey == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tcreq.ExclusiveStartKey = make(AttributeNameValue)\n\t\tfor k, v := range res.LastEvaluatedKey {\n\t\t\tcreq.ExclusiveStartKey[k] = v\n\t\t}\n\n\t\tif delay > 0 {\n\t\t\ttime.Sleep(delay)\n\t\t}\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/api\/prometheus\"\n\t\"github.com\/prometheus\/common\/expfmt\"\n\t\"github.com\/prometheus\/common\/model\"\n)\n\ntype Tag struct {\n\tName  model.LabelName\n\tValue model.LabelValue\n}\n\ntype Metric struct {\n\tTags  []Tag\n\tValue float64\n}\n\nfunc CreateJSONMetrics(samples model.Vector) string {\n\tmetrics := []Metric{}\n\n\tfor _, sample := range samples {\n\t\tmetric := Metric{}\n\n\t\tfor name, value := range sample.Metric {\n\t\t\ttag := Tag{\n\t\t\t\tName:  name,\n\t\t\t\tValue: value,\n\t\t\t}\n\n\t\t\tmetric.Tags = append(metric.Tags, tag)\n\t\t}\n\n\t\tmetric.Value = float64(sample.Value)\n\n\t\tmetrics = append(metrics, metric)\n\t}\n\n\tjsonMetrics, _ := json.Marshal(metrics)\n\n\treturn string(jsonMetrics)\n}\n\nfunc CreateGraphiteMetrics(samples model.Vector) string {\n\tmetrics := \"\"\n\n\tfor _, sample := range samples {\n\t\tname := sample.Metric[\"__name__\"]\n\n\t\tvalue := sample.Value\n\n\t\tnow := time.Now()\n\t\ttimestamp := now.Unix()\n\n\t\tmetric := fmt.Sprintf(\"%s %f %v\\n\", name, value, timestamp)\n\n\t\tmetrics += metric\n\t}\n\n\treturn metrics\n}\n\nfunc CreateInfluxMetrics(samples model.Vector) string {\n\tmetrics := \"\"\n\n\tfor _, sample := range samples {\n\t\tmetric := string(sample.Metric[\"__name__\"])\n\n\t\tfor name, value := range sample.Metric {\n\t\t\tif name != \"__name__\" {\n\t\t\t\tmetric += fmt.Sprintf(\",%s=%s\", name, value)\n\t\t\t}\n\t\t}\n\n\t\tvalue := sample.Value\n\n\t\tnow := time.Now()\n\t\ttimestamp := now.Unix()\n\n\t\tmetric += fmt.Sprintf(\" value=%f %v\\n\", value, timestamp)\n\n\t\tmetrics += metric\n\t}\n\n\treturn metrics\n}\n\nfunc OutputMetrics(samples model.Vector, outputFormat string) error {\n\toutput := \"\"\n\n\tswitch outputFormat {\n\tcase \"influx\":\n\t\toutput = CreateInfluxMetrics(samples)\n\tcase \"graphite\":\n\t\toutput = CreateGraphiteMetrics(samples)\n\tcase \"json\":\n\t\toutput = CreateJSONMetrics(samples)\n\t}\n\n\tfmt.Println(output)\n\n\treturn nil\n}\n\nfunc QueryPrometheus(promURL string, queryString string) (model.Vector, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tpromConfig := prometheus.Config{Address: promURL}\n\tpromClient, err := prometheus.New(promConfig)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpromQueryClient := prometheus.NewQueryAPI(promClient)\n\n\tpromResponse, err := promQueryClient.Query(ctx, queryString, time.Now())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif promResponse.Type() == model.ValVector {\n\t\treturn promResponse.(model.Vector), nil\n\t}\n\n\treturn nil, errors.New(\"unexpected response type\")\n}\n\nfunc QueryExporter(exporterURL string) (model.Vector, error) {\n\texpResponse, err := http.Get(exporterURL)\n\tdefer expResponse.Body.Close()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif expResponse.StatusCode != http.StatusOK {\n\t\treturn nil, errors.New(\"exporter returned non OK HTTP response status\")\n\t}\n\n\tvar parser expfmt.TextParser\n\n\tmetricFamilies, err := parser.TextToMetricFamilies(expResponse.Body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsamples := model.Vector{}\n\n\tdecodeOptions := &expfmt.DecodeOptions{\n\t\tTimestamp: model.Time(time.Now().Unix()),\n\t}\n\n\tfor _, family := range metricFamilies {\n\t\tfamilySamples, _ := expfmt.ExtractSamples(decodeOptions, family)\n\t\tsamples = append(samples, familySamples...)\n\t}\n\n\treturn samples, nil\n}\n\nfunc main() {\n\texporterURL := flag.String(\"exporter-url\", \"\", \"Prometheus exporter URL to pull metrics from\")\n\tpromURL := flag.String(\"prom-url\", \"http:\/\/localhost:9090\", \"Prometheus API URL\")\n\tqueryString := flag.String(\"prom-query\", \"up\", \"Prometheus API query string\")\n\toutputFormat := flag.String(\"output-format\", \"influx\", \"The check output format to use for metrics {influx|graphite|json}\")\n\tflag.Parse()\n\n\tsamples := model.Vector{}\n\tvar err error\n\n\tif *exporterURL != \"\" {\n\t\tsamples, err = QueryExporter(*exporterURL)\n\t} else {\n\t\tsamples, err = QueryPrometheus(*promURL, *queryString)\n\t}\n\n\tif err != nil {\n\t\tfmt.Errorf(\"%v\", err)\n\t\tos.Exit(2)\n\t}\n\n\terr = OutputMetrics(samples, *outputFormat)\n\n\tif err != nil {\n\t\tfmt.Errorf(\"%v\", err)\n\t\tos.Exit(2)\n\t}\n}\n<commit_msg>added metric prefix cli argument, an optional a metric name prefix for line protocols<commit_after>package main\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/api\/prometheus\"\n\t\"github.com\/prometheus\/common\/expfmt\"\n\t\"github.com\/prometheus\/common\/model\"\n)\n\ntype Tag struct {\n\tName  model.LabelName\n\tValue model.LabelValue\n}\n\ntype Metric struct {\n\tTags  []Tag\n\tValue float64\n}\n\nfunc CreateJSONMetrics(samples model.Vector) string {\n\tmetrics := []Metric{}\n\n\tfor _, sample := range samples {\n\t\tmetric := Metric{}\n\n\t\tfor name, value := range sample.Metric {\n\t\t\ttag := Tag{\n\t\t\t\tName:  name,\n\t\t\t\tValue: value,\n\t\t\t}\n\n\t\t\tmetric.Tags = append(metric.Tags, tag)\n\t\t}\n\n\t\tmetric.Value = float64(sample.Value)\n\n\t\tmetrics = append(metrics, metric)\n\t}\n\n\tjsonMetrics, _ := json.Marshal(metrics)\n\n\treturn string(jsonMetrics)\n}\n\nfunc CreateGraphiteMetrics(samples model.Vector, metricPrefix string) string {\n\tmetrics := \"\"\n\n\tfor _, sample := range samples {\n\t\tname := fmt.Sprintf(\"%s%s\", metricPrefix, sample.Metric[\"__name__\"])\n\n\t\tvalue := sample.Value\n\n\t\tnow := time.Now()\n\t\ttimestamp := now.Unix()\n\n\t\tmetric := fmt.Sprintf(\"%s %f %v\\n\", name, value, timestamp)\n\n\t\tmetrics += metric\n\t}\n\n\treturn metrics\n}\n\nfunc CreateInfluxMetrics(samples model.Vector, metricPrefix string) string {\n\tmetrics := \"\"\n\n\tfor _, sample := range samples {\n\t\tmetric := fmt.Sprintf(\"%s%s\", metricPrefix, sample.Metric[\"__name__\"])\n\n\t\tfor name, value := range sample.Metric {\n\t\t\tif name != \"__name__\" {\n\t\t\t\tmetric += fmt.Sprintf(\",%s=%s\", name, value)\n\t\t\t}\n\t\t}\n\n\t\tvalue := sample.Value\n\n\t\tnow := time.Now()\n\t\ttimestamp := now.Unix()\n\n\t\tmetric += fmt.Sprintf(\" value=%f %v\\n\", value, timestamp)\n\n\t\tmetrics += metric\n\t}\n\n\treturn metrics\n}\n\nfunc OutputMetrics(samples model.Vector, outputFormat string, metricPrefix string) error {\n\toutput := \"\"\n\n\tswitch outputFormat {\n\tcase \"influx\":\n\t\toutput = CreateInfluxMetrics(samples, metricPrefix)\n\tcase \"graphite\":\n\t\toutput = CreateGraphiteMetrics(samples, metricPrefix)\n\tcase \"json\":\n\t\toutput = CreateJSONMetrics(samples)\n\t}\n\n\tfmt.Println(output)\n\n\treturn nil\n}\n\nfunc QueryPrometheus(promURL string, queryString string) (model.Vector, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tpromConfig := prometheus.Config{Address: promURL}\n\tpromClient, err := prometheus.New(promConfig)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpromQueryClient := prometheus.NewQueryAPI(promClient)\n\n\tpromResponse, err := promQueryClient.Query(ctx, queryString, time.Now())\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif promResponse.Type() == model.ValVector {\n\t\treturn promResponse.(model.Vector), nil\n\t}\n\n\treturn nil, errors.New(\"unexpected response type\")\n}\n\nfunc QueryExporter(exporterURL string) (model.Vector, error) {\n\texpResponse, err := http.Get(exporterURL)\n\tdefer expResponse.Body.Close()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif expResponse.StatusCode != http.StatusOK {\n\t\treturn nil, errors.New(\"exporter returned non OK HTTP response status\")\n\t}\n\n\tvar parser expfmt.TextParser\n\n\tmetricFamilies, err := parser.TextToMetricFamilies(expResponse.Body)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsamples := model.Vector{}\n\n\tdecodeOptions := &expfmt.DecodeOptions{\n\t\tTimestamp: model.Time(time.Now().Unix()),\n\t}\n\n\tfor _, family := range metricFamilies {\n\t\tfamilySamples, _ := expfmt.ExtractSamples(decodeOptions, family)\n\t\tsamples = append(samples, familySamples...)\n\t}\n\n\treturn samples, nil\n}\n\nfunc main() {\n\texporterURL := flag.String(\"exporter-url\", \"\", \"Prometheus exporter URL to pull metrics from.\")\n\tpromURL := flag.String(\"prom-url\", \"http:\/\/localhost:9090\", \"Prometheus API URL.\")\n\tqueryString := flag.String(\"prom-query\", \"up\", \"Prometheus API query string.\")\n\toutputFormat := flag.String(\"output-format\", \"influx\", \"The check output format to use for metrics {influx|graphite|json}.\")\n\tmetricPrefix := flag.String(\"metric-prefix\", \"\", \"Metric name prefix, only supported by line protocol output formats.\")\n\tflag.Parse()\n\n\tsamples := model.Vector{}\n\tvar err error\n\n\tif *exporterURL != \"\" {\n\t\tsamples, err = QueryExporter(*exporterURL)\n\t} else {\n\t\tsamples, err = QueryPrometheus(*promURL, *queryString)\n\t}\n\n\tif err != nil {\n\t\tfmt.Errorf(\"%v\", err)\n\t\tos.Exit(2)\n\t}\n\n\terr = OutputMetrics(samples, *outputFormat, *metricPrefix)\n\n\tif err != nil {\n\t\tfmt.Errorf(\"%v\", err)\n\t\tos.Exit(2)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package crypto\n\nimport (\n\t\"crypto\/rand\"\n\t\"math\/big\"\n)\n\n\/\/ RandBytes returns n bytes of random data.\nfunc RandBytes(n int) ([]byte, error) {\n\tb := make([]byte, n)\n\t_, err := rand.Read(b)\n\treturn b, err\n}\n\n\/\/ RandIntn returns a non-negative random integer in the range [0,n). It panics\n\/\/ if n <= 0.\nfunc RandIntn(n int) (int, error) {\n\tr, err := rand.Int(rand.Reader, big.NewInt(int64(n)))\n\treturn int(r.Int64()), err\n}\n\n\/\/ Perm returns, as a slice of n ints, a random permutation of the integers\n\/\/ [0,n).\nfunc Perm(n int) ([]int, error) {\n\tm := make([]int, n)\n\tfor i := 0; i < n; i++ {\n\t\tj, err := RandIntn(i + 1)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tm[i] = m[j]\n\t\tm[j] = i\n\t}\n\treturn m, nil\n}\n<commit_msg>change crypto\/rand.go to not be able to return errors<commit_after>package crypto\n\nimport (\n\t\"crypto\/rand\"\n\t\"math\/big\"\n\t\"sync\/atomic\"\n)\n\nvar (\n\t\/\/ Two counters is used in case the first overflows. The first is not at\n\t\/\/ risk of overflowing, but we're paranoid.\n\tcounter     uint64\n\tcounter2    uint64\n\tentropyBase Hash\n)\n\n\/\/ init will create an entropy pool that the RNG will draw from. On most\n\/\/ systems, hashing out of a preset RNG pool will be substantially faster than\n\/\/ using crypto\/rand, which relies on syscalls.\nfunc init() {\n\t\/\/ Use 64 bytes in case the first 32 aren't completely random.\n\tbase := make([]byte, 64)\n\t_, err := rand.Read(base)\n\tif err != nil {\n\t\tpanic(\"unable to set entropy for the crypto package\")\n\t}\n\tentropyBase = HashObject(base)\n}\n\n\/\/ RandBytes returns n bytes of random data.\nfunc RandBytes(n int) ([]byte, error) {\n\tb := make([]byte, n)\n\tfor i := 0; i < n; i += HashSize {\n\t\t\/\/ Fetch and update the counter values before executing the hash.\n\t\tvar newCounter, newCounter2 uint64\n\t\tnewCounter = atomic.AddUint64(&counter, 1)\n\t\tif newCounter == 0 {\n\t\t\tnewCounter2 = atomic.AddUint64(&counter2, 1)\n\t\t} else {\n\t\t\tnewCounter2 = atomic.LoadUint64(&counter2)\n\t\t}\n\t\t\/\/ Grab some entropy using the unique counter set.\n\t\tentropy := HashAll(newCounter, newCounter2, entropyBase)\n\n\t\t\/\/ Fill out 'b'.\n\t\tcopy(b[i:], entropy[:])\n\t}\n\treturn b, nil\n}\n\n\/\/ RandIntn returns a non-negative random integer in the range [0,n). It panics\n\/\/ if n <= 0.\nfunc RandIntn(n int) (int, error) {\n\tif n <= 0 {\n\t\tpanic(\"RandIntn must be called with a positive, nonzero number\")\n\t}\n\n\t\/\/ Fetch and update the counter values before executing the hash.\n\tvar newCounter, newCounter2 uint64\n\tnewCounter = atomic.AddUint64(&counter, 1)\n\tif newCounter == 0 {\n\t\tnewCounter2 = atomic.AddUint64(&counter2, 1)\n\t} else {\n\t\tnewCounter2 = atomic.LoadUint64(&counter2)\n\t}\n\t\/\/ Grab some entropy using the unique counter set.\n\tentropy := HashAll(newCounter, newCounter2, entropyBase)\n\n\t\/\/ Convert the first 24 bytes into a big.Int, then grab the modulus of n.\n\t\/\/ 24 bytes means that there is at least 16 bytes of overflow, which means\n\t\/\/ early numbers are favored by less than 1-in-2^128 - a cryptographically\n\t\/\/ safe preference.\n\tb := new(big.Int)\n\tb.SetBytes(entropy[:24])\n\n\t\/\/ Take the modules of 'b'  and 'n' and return the result as an int.\n\treturn int(b.Mod(b, big.NewInt(int64(n))).Int64()), nil\n}\n\n\/\/ Read will fill 'b' with completely random data.\nfunc Read(b []byte) {\n\tn := len(b)\n\tfor i := 0; i < n; i += HashSize {\n\t\t\/\/ Fetch and update the counter values before executing the hash.\n\t\tvar newCounter, newCounter2 uint64\n\t\tnewCounter = atomic.AddUint64(&counter, 1)\n\t\tif newCounter == 0 {\n\t\t\tnewCounter2 = atomic.AddUint64(&counter2, 1)\n\t\t} else {\n\t\t\tnewCounter2 = atomic.LoadUint64(&counter2)\n\t\t}\n\t\t\/\/ Grab some entropy using the unique counter set.\n\t\tentropy := HashAll(newCounter, newCounter2, entropyBase)\n\n\t\t\/\/ Fill out 'b'.\n\t\tcopy(b[i:], entropy[:])\n\t}\n}\n\n\/\/ Perm returns, as a slice of n ints, a random permutation of the integers\n\/\/ [0,n).\nfunc Perm(n int) ([]int, error) {\n\tm := make([]int, n)\n\tfor i := 0; i < n; i++ {\n\t\tj, _ := RandIntn(i + 1)\n\t\tm[i] = m[j]\n\t\tm[j] = i\n\t}\n\treturn m, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package packetdeserializers\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/piot\/hasty-protocol\/asciistring\"\n\t\"github.com\/piot\/hasty-protocol\/commands\"\n\t\"github.com\/piot\/hasty-protocol\/deserialize\"\n\t\"github.com\/piot\/hasty-protocol\/packet\"\n\t\"github.com\/piot\/hasty-protocol\/realmname\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ ToConnect : Channel to subscribe to\nfunc ToConnect(in packet.Packet) (commands.Connect, error) {\n\tif in.Type() != packet.Connect {\n\t\treturn commands.Connect{}, errors.New(\"Illegal packet type\")\n\t}\n\n\tpayload := in.Payload()\n\tpos := 0\n\tversionObject, versionOctetCount, versionErr := deserialize.ToVersion(payload[0:3])\n\tif versionErr != nil {\n\t\treturn commands.Connect{}, errors.New(\"Illegal version\")\n\t}\n\tpos += versionOctetCount\n\trealmString, _, realmStringErr := asciistring.FromOctets(payload[pos:])\n\tif realmStringErr != nil {\n\t\treturn commands.Connect{}, fmt.Errorf(\"Illegal realm %s\", realmStringErr)\n\t}\n\trealm, realmErr := realmname.NewName(realmString)\n\tif realmErr != nil {\n\t\treturn commands.Connect{}, realmErr\n\t}\n\tconnect := commands.NewConnect(realm, versionObject)\n\tlog.Infof(\"connect %s\\n\", connect)\n\treturn connect, nil\n}\n<commit_msg>minor logging<commit_after>package packetdeserializers\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/piot\/hasty-protocol\/asciistring\"\n\t\"github.com\/piot\/hasty-protocol\/commands\"\n\t\"github.com\/piot\/hasty-protocol\/deserialize\"\n\t\"github.com\/piot\/hasty-protocol\/packet\"\n\t\"github.com\/piot\/hasty-protocol\/realmname\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ ToConnect : Channel to subscribe to\nfunc ToConnect(in packet.Packet) (commands.Connect, error) {\n\tif in.Type() != packet.Connect {\n\t\treturn commands.Connect{}, errors.New(\"Illegal packet type\")\n\t}\n\n\tpayload := in.Payload()\n\tpos := 0\n\tversionObject, versionOctetCount, versionErr := deserialize.ToVersion(payload[0:3])\n\tif versionErr != nil {\n\t\treturn commands.Connect{}, errors.New(\"Illegal version\")\n\t}\n\tpos += versionOctetCount\n\trealmString, _, realmStringErr := asciistring.FromOctets(payload[pos:])\n\tif realmStringErr != nil {\n\t\treturn commands.Connect{}, fmt.Errorf(\"Illegal realm %s\", realmStringErr)\n\t}\n\trealm, realmErr := realmname.NewName(realmString)\n\tif realmErr != nil {\n\t\treturn commands.Connect{}, realmErr\n\t}\n\tconnect := commands.NewConnect(realm, versionObject)\n\tlog.Infof(\"%s\", connect)\n\treturn connect, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package input\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/venicegeo\/pzsvc-exec\/worker\/config\"\n)\n\nvar httpClient = http.Client{\n\tTimeout: 30 * time.Second,\n}\n\ntype asyncDownloader interface {\n\tDownloadInputAsync(source config.InputSource) chan error\n}\n\ntype defaultAsyncDownloader struct{}\n\nvar asyncDownloaderInstance asyncDownloader = defaultAsyncDownloader{}\n\nfunc (dl defaultAsyncDownloader) DownloadInputAsync(source config.InputSource) chan error {\n\terrChan := make(chan error)\n\n\tgo func() {\n\t\tvar err error\n\t\tdefer close(errChan)\n\n\t\ttargetFile, err := fileCheckerInstance.CheckAndOpen(source.FileName, 0777)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\tdefer targetFile.Close()\n\n\t\tresp, err := httpClient.Get(source.URL)\n\t\tif err == nil && resp.StatusCode != http.StatusOK {\n\t\t\terr = fmt.Errorf(\"Unexpected HTTP status: %v\", resp.StatusCode)\n\t\t}\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\t_, err = io.Copy(targetFile, resp.Body)\n\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn errChan\n}\n<commit_msg>Configurable Client Timeout<commit_after>package input\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/venicegeo\/pzsvc-exec\/worker\/config\"\n)\n\nfunc getClientTimeout() time.Duration {\n\tdefaultTimeout := 30\n\tif envTimeout := os.Getenv(\"HTTP_TIMEOUT\"); envTimeout != \"\" {\n\t\tdefaultTimeout , _ = strconv.Atoi(envTimeout)\n\t}\n\treturn (time.Duration(defaultTimeout) * time.Second)\n}\n\nvar httpClient = http.Client{\n\tTimeout: getClientTimeout(),\n}\n\ntype asyncDownloader interface {\n\tDownloadInputAsync(source config.InputSource) chan error\n}\n\ntype defaultAsyncDownloader struct{}\n\nvar asyncDownloaderInstance asyncDownloader = defaultAsyncDownloader{}\n\nfunc (dl defaultAsyncDownloader) DownloadInputAsync(source config.InputSource) chan error {\n\terrChan := make(chan error)\n\n\tgo func() {\n\t\tvar err error\n\t\tdefer close(errChan)\n\n\t\ttargetFile, err := fileCheckerInstance.CheckAndOpen(source.FileName, 0777)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\tdefer targetFile.Close()\n\n\t\tresp, err := httpClient.Get(source.URL)\n\t\tif err == nil && resp.StatusCode != http.StatusOK {\n\t\t\terr = fmt.Errorf(\"Unexpected HTTP status: %v\", resp.StatusCode)\n\t\t}\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\t_, err = io.Copy(targetFile, resp.Body)\n\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn errChan\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\n   This file is licensed under the Apache License, Version 2.0 (the \"License\").\n   You may not use this file except in compliance with the License. A copy of\n   the License is located at\n\n    http:\/\/aws.amazon.com\/apache2.0\/\n\n   This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n   CONDITIONS OF ANY KIND, either express or implied. See the License for the\n   specific language governing permissions and limitations under the License.\n*\/\n\npackage main\n\nimport (\n    \"github.com\/aws\/aws-sdk-go\/aws\"\n    \"github.com\/aws\/aws-sdk-go\/aws\/session\"\n    \"github.com\/aws\/aws-sdk-go\/service\/s3\"\n\n    \"fmt\"\n)\n\n\/\/ Tag S3 bucket MyBucket with cost center tag \"123456\" and stack tag \"MyTestStack\".\n\/\/\n\/\/ See:\n\/\/    http:\/\/docs.aws.amazon.com\/awsaccountbilling\/latest\/aboutv2\/cost-alloc-tags.html\nfunc main() {\n    \/\/ Pre-defined values\n    bucket := \"MyBucket\"\n    tagName1 := \"Cost Center\"\n    tagValue1 := \"123456\"\n    tagName2 := \"Stack\"\n    tagValue2 := \"MyTestStack\"\n    \n    \/\/ Initialize a session in us-west-2 that the SDK will use to load credentials\n    \/\/ from the shared credentials file. (~\/.aws\/ccredentials).\n    sess, err := session.NewSession(&aws.Config{\n        Region: aws.String(\"us-west-2\")},\n    )\n    if err != nil {\n        fmt.Println(err.Error())\n        return\n    }\n\n    \/\/ Create S3 service client\n    svc := s3.New(sess)\n\n    \/\/ Create input for PutBucket method\n    input := &s3.PutBucketTaggingInput{\n        Bucket: aws.String(bucket),\n        Tagging: &s3.Tagging{\n            TagSet: []*s3.Tag{\n                {\n                    Key:   aws.String(tagName1),\n                    Value: aws.String(tagValue),\n                },\n                {\n                    Key:   aws.String(tagName2),\n                    Value: aws.String(tagValue2),\n              },\n            },\n        },\n    }\n\n    _, err = svc.PutBucketTagging(input)\n    if err != nil {\n        fmt.Println(err.Error())\n        return\n    }\n\n    \/\/ Now show the tags\n    \/\/ Create input for GetBucket method\n    input := &s3.GetBucketTaggingInput{\n        Bucket: aws.String(bucket),\n    }\n\n    result, err := svc.GetBucketTagging(input)\n    if err != nil {\n        fmt.Println(err.Error())\n        return\n    }\n\n    numTags := len(result.TagSet)\n\n    if numTags > 0 {\n        fmt.Println(\"Found\", numTags, \"Tag(s):\")\n        fmt.Println(\"\")\n\n        for _, t := range result.TagSet {\n            fmt.Println(\"  Key:  \", *t.Key)\n            fmt.Println(\"  Value:\", *t.Value)\n            fmt.Println(\"\")\n        }\n    } else {\n        fmt.Println(\"Did not find any tags\")\n    }\n}\n<commit_msg>Fixed typos in 'Using the AWS SDK for Go with AWS Services' topic<commit_after>\/*\n   Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\n   This file is licensed under the Apache License, Version 2.0 (the \"License\").\n   You may not use this file except in compliance with the License. A copy of\n   the License is located at\n\n    http:\/\/aws.amazon.com\/apache2.0\/\n\n   This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n   CONDITIONS OF ANY KIND, either express or implied. See the License for the\n   specific language governing permissions and limitations under the License.\n*\/\n\npackage main\n\nimport (\n    \"github.com\/aws\/aws-sdk-go\/aws\"\n    \"github.com\/aws\/aws-sdk-go\/aws\/session\"\n    \"github.com\/aws\/aws-sdk-go\/service\/s3\"\n\n    \"fmt\"\n)\n\n\/\/ Tag S3 bucket MyBucket with cost center tag \"123456\" and stack tag \"MyTestStack\".\n\/\/\n\/\/ See:\n\/\/    http:\/\/docs.aws.amazon.com\/awsaccountbilling\/latest\/aboutv2\/cost-alloc-tags.html\nfunc main() {\n    \/\/ Pre-defined values\n    bucket := \"MyBucket\"\n    tagName1 := \"Cost Center\"\n    tagValue1 := \"123456\"\n    tagName2 := \"Stack\"\n    tagValue2 := \"MyTestStack\"\n    \n    \/\/ Initialize a session in us-west-2 that the SDK will use to load credentials\n    \/\/ from the shared credentials file. (~\/.aws\/credentials).\n    sess, err := session.NewSession(&aws.Config{\n        Region: aws.String(\"us-west-2\")},\n    )\n    if err != nil {\n        fmt.Println(err.Error())\n        return\n    }\n\n    \/\/ Create S3 service client\n    svc := s3.New(sess)\n\n    \/\/ Create input for PutBucket method\n    input := &s3.PutBucketTaggingInput{\n        Bucket: aws.String(bucket),\n        Tagging: &s3.Tagging{\n            TagSet: []*s3.Tag{\n                {\n                    Key:   aws.String(tagName1),\n                    Value: aws.String(tagValue1),\n                },\n                {\n                    Key:   aws.String(tagName2),\n                    Value: aws.String(tagValue2),\n              },\n            },\n        },\n    }\n\n    _, err = svc.PutBucketTagging(input)\n    if err != nil {\n        fmt.Println(err.Error())\n        return\n    }\n\n    \/\/ Now show the tags\n    \/\/ Create input for GetBucket method\n    input := &s3.GetBucketTaggingInput{\n        Bucket: aws.String(bucket),\n    }\n\n    result, err := svc.GetBucketTagging(input)\n    if err != nil {\n        fmt.Println(err.Error())\n        return\n    }\n\n    numTags := len(result.TagSet)\n\n    if numTags > 0 {\n        fmt.Println(\"Found\", numTags, \"Tag(s):\")\n        fmt.Println(\"\")\n\n        for _, t := range result.TagSet {\n            fmt.Println(\"  Key:  \", *t.Key)\n            fmt.Println(\"  Value:\", *t.Value)\n            fmt.Println(\"\")\n        }\n    } else {\n        fmt.Println(\"Did not find any tags\")\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ Package cephbackupstorage implements the BackupStorage interface\n\/\/ for Ceph Cloud Storage.\npackage cephbackupstorage\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"errors\"\n\n\tminio \"github.com\/minio\/minio-go\"\n\t\"golang.org\/x\/net\/context\"\n\n\t\"vitess.io\/vitess\/go\/vt\/concurrency\"\n\t\"vitess.io\/vitess\/go\/vt\/log\"\n\t\"vitess.io\/vitess\/go\/vt\/mysqlctl\/backupstorage\"\n)\n\nvar (\n\t\/\/ configFilePath is where the configs\/credentials for backups will be stored.\n\tconfigFilePath = flag.String(\"ceph_backup_storage_config\", \"ceph_backup_config.json\",\n\t\t\"Path to JSON config file for ceph backup storage\")\n)\n\nvar storageConfig struct {\n\tAccessKey string `json:\"accessKey\"`\n\tSecretKey string `json:\"secretKey\"`\n\tEndPoint  string `json:\"endPoint\"`\n\tUseSSL    bool   `json:\"useSSL\"`\n}\n\n\/\/ CephBackupHandle implements BackupHandle for Ceph Cloud Storage.\ntype CephBackupHandle struct {\n\tclient    *minio.Client\n\tbs        *CephBackupStorage\n\tdir       string\n\tname      string\n\treadOnly  bool\n\terrors    concurrency.AllErrorRecorder\n\twaitGroup sync.WaitGroup\n}\n\n\/\/ Directory implements BackupHandle.\nfunc (bh *CephBackupHandle) Directory() string {\n\treturn bh.dir\n}\n\n\/\/ Name implements BackupHandle.\nfunc (bh *CephBackupHandle) Name() string {\n\treturn bh.name\n}\n\n\/\/ AddFile implements BackupHandle.\nfunc (bh *CephBackupHandle) AddFile(ctx context.Context, filename string, filesize int64) (io.WriteCloser, error) {\n\tif bh.readOnly {\n\t\treturn nil, fmt.Errorf(\"AddFile cannot be called on read-only backup\")\n\t}\n\treader, writer := io.Pipe()\n\tbh.waitGroup.Add(1)\n\tgo func() {\n\t\tdefer bh.waitGroup.Done()\n\n\t\t\/\/ ceph bucket name is where the backups will go\n\t\t\/\/backup handle dir field contains keyspace\/shard value\n\t\tbucket := alterBucketName(bh.dir)\n\n\t\t\/\/ Give PutObject() the read end of the pipe.\n\t\tobject := objName(bh.dir, bh.name, filename)\n\t\t_, err := bh.client.PutObjectWithContext(ctx, bucket, object, reader, -1, minio.PutObjectOptions{ContentType: \"application\/octet-stream\"})\n\t\tif err != nil {\n\t\t\t\/\/ Signal the writer that an error occurred, in case it's not done writing yet.\n\t\t\treader.CloseWithError(err)\n\t\t\t\/\/ In case the error happened after the writer finished, we need to remember it.\n\t\t\tbh.errors.RecordError(err)\n\t\t}\n\t}()\n\t\/\/ Give our caller the write end of the pipe.\n\treturn writer, nil\n}\n\n\/\/ EndBackup implements BackupHandle.\nfunc (bh *CephBackupHandle) EndBackup(ctx context.Context) error {\n\tif bh.readOnly {\n\t\treturn fmt.Errorf(\"EndBackup cannot be called on read-only backup\")\n\t}\n\tbh.waitGroup.Wait()\n\t\/\/ Return the saved PutObject() errors, if any.\n\treturn bh.errors.Error()\n}\n\n\/\/ AbortBackup implements BackupHandle.\nfunc (bh *CephBackupHandle) AbortBackup(ctx context.Context) error {\n\tif bh.readOnly {\n\t\treturn fmt.Errorf(\"AbortBackup cannot be called on read-only backup\")\n\t}\n\treturn bh.bs.RemoveBackup(ctx, bh.dir, bh.name)\n}\n\n\/\/ ReadFile implements BackupHandle.\nfunc (bh *CephBackupHandle) ReadFile(ctx context.Context, filename string) (io.ReadCloser, error) {\n\tif !bh.readOnly {\n\t\treturn nil, fmt.Errorf(\"ReadFile cannot be called on read-write backup\")\n\t}\n\t\/\/ ceph bucket name\n\tbucket := alterBucketName(bh.dir)\n\tobject := objName(bh.dir, bh.name, filename)\n\treturn bh.client.GetObjectWithContext(ctx, bucket, object, minio.GetObjectOptions{})\n}\n\n\/\/ CephBackupStorage implements BackupStorage for Ceph Cloud Storage.\ntype CephBackupStorage struct {\n\t\/\/ client is the instance of the Ceph Cloud Storage Go client.\n\t\/\/ Once this field is set, it must not be written again\/unset to nil.\n\t_client *minio.Client\n\t\/\/ mu guards all fields.\n\tmu sync.Mutex\n}\n\n\/\/ ListBackups implements BackupStorage.\nfunc (bs *CephBackupStorage) ListBackups(ctx context.Context, dir string) ([]backupstorage.BackupHandle, error) {\n\tc, err := bs.client()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ ceph bucket name\n\tbucket := alterBucketName(dir)\n\n\t\/\/ List prefixes that begin with dir (i.e. list subdirs).\n\tvar subdirs []string\n\tsearchPrefix := objName(dir, \"\")\n\n\tdoneCh := make(chan struct{})\n\tfor object := range c.ListObjects(bucket, searchPrefix, false, doneCh) {\n\t\tif object.Err != nil {\n\t\t\t_, err := c.BucketExists(bucket)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t\treturn nil, object.Err\n\t\t}\n\t\tsubdir := strings.TrimPrefix(object.Key, searchPrefix)\n\t\tsubdir = strings.TrimSuffix(subdir, \"\/\")\n\t\tsubdirs = append(subdirs, subdir)\n\t}\n\n\t\/\/ Backups must be returned in order, oldest first.\n\tsort.Strings(subdirs)\n\n\tresult := make([]backupstorage.BackupHandle, 0, len(subdirs))\n\tfor _, subdir := range subdirs {\n\t\tresult = append(result, &CephBackupHandle{\n\t\t\tclient:   c,\n\t\t\tbs:       bs,\n\t\t\tdir:      dir,\n\t\t\tname:     subdir,\n\t\t\treadOnly: true,\n\t\t})\n\t}\n\treturn result, nil\n}\n\n\/\/ StartBackup implements BackupStorage.\nfunc (bs *CephBackupStorage) StartBackup(ctx context.Context, dir, name string) (backupstorage.BackupHandle, error) {\n\tc, err := bs.client()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ ceph bucket name\n\tbucket := alterBucketName(dir)\n\n\tfound, err := c.BucketExists(bucket)\n\n\tif err != nil {\n\t\tlog.Info(\"Error from BucketExists: %v, quitting\", bucket)\n\t\treturn nil, errors.New(\"Error checking whether bucket exists: \" + bucket)\n\t}\n\tif !found {\n\t\tlog.Info(\"Bucket: %v doesn't exist, creating new bucket with the required name\", bucket)\n\t\terr = c.MakeBucket(bucket, \"\")\n\t\tif err != nil {\n\t\t\tlog.Info(\"Error creating Bucket: %v, quitting\", bucket)\n\t\t\treturn nil, errors.New(\"Error creating new bucket: \" + bucket)\n\t\t}\n\t}\n\n\treturn &CephBackupHandle{\n\t\tclient:   c,\n\t\tbs:       bs,\n\t\tdir:      dir,\n\t\tname:     name,\n\t\treadOnly: false,\n\t}, nil\n}\n\n\/\/ RemoveBackup implements BackupStorage.\nfunc (bs *CephBackupStorage) RemoveBackup(ctx context.Context, dir, name string) error {\n\tc, err := bs.client()\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ ceph bucket name\n\tbucket := alterBucketName(dir)\n\n\tfullName := objName(dir, name, \"\")\n\tvar arr []string\n\tdoneCh := make(chan struct{})\n\tdefer close(doneCh)\n\tfor object := range c.ListObjects(bucket, fullName, true, doneCh) {\n\t\tif object.Err != nil {\n\t\t\treturn object.Err\n\t\t}\n\t\tarr = append(arr, object.Key)\n\t}\n\tfor _, obj := range arr {\n\t\terr = c.RemoveObject(bucket, obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Close implements BackupStorage.\nfunc (bs *CephBackupStorage) Close() error {\n\tbs.mu.Lock()\n\tdefer bs.mu.Unlock()\n\n\tif bs._client != nil {\n\t\t\/\/ a new client the next time one is needed.\n\t\tbs._client = nil\n\t}\n\treturn nil\n}\n\n\/\/ client returns the Ceph Storage client instance.\n\/\/ If there isn't one yet, it tries to create one.\nfunc (bs *CephBackupStorage) client() (*minio.Client, error) {\n\tbs.mu.Lock()\n\tdefer bs.mu.Unlock()\n\n\tif bs._client == nil {\n\t\tconfigFile, err := os.Open(*configFilePath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"file not present : %v\", err)\n\t\t}\n\t\tdefer configFile.Close()\n\t\tjsonParser := json.NewDecoder(configFile)\n\t\tif err = jsonParser.Decode(&storageConfig); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error parsing the json file : %v\", err)\n\t\t}\n\n\t\taccessKey := storageConfig.AccessKey\n\t\tsecretKey := storageConfig.SecretKey\n\t\turl := storageConfig.EndPoint\n\t\tuseSSL := storageConfig.UseSSL\n\n\t\tclient, err := minio.NewV2(url, accessKey, secretKey, useSSL)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbs._client = client\n\t}\n\treturn bs._client, nil\n}\n\nfunc init() {\n\tbackupstorage.BackupStorageMap[\"ceph\"] = &CephBackupStorage{}\n}\n\n\/\/ objName joins path parts into an object name.\n\/\/ Unlike path.Join, it doesn't collapse \"..\" or strip trailing slashes.\n\/\/ It also adds the value of the -gcs_backup_storage_root flag if set.\nfunc objName(parts ...string) string {\n\treturn strings.Join(parts, \"\/\")\n}\n\n\/\/ keeping in view the bucket naming conventions for ceph\n\/\/ only keyspace informations is extracted and used for bucket name\nfunc alterBucketName(dir string) string {\n\tbucket := strings.ToLower(dir)\n\tbucket = strings.Split(bucket, \"\/\")[0]\n\tbucket = strings.Replace(bucket, \"_\", \"-\", -1)\n\treturn bucket\n}\n<commit_msg>pass in correct filesize in ceph backup<commit_after>\/*\nCopyright 2019 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ Package cephbackupstorage implements the BackupStorage interface\n\/\/ for Ceph Cloud Storage.\npackage cephbackupstorage\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"errors\"\n\n\tminio \"github.com\/minio\/minio-go\"\n\t\"golang.org\/x\/net\/context\"\n\n\t\"vitess.io\/vitess\/go\/vt\/concurrency\"\n\t\"vitess.io\/vitess\/go\/vt\/log\"\n\t\"vitess.io\/vitess\/go\/vt\/mysqlctl\/backupstorage\"\n)\n\nvar (\n\t\/\/ configFilePath is where the configs\/credentials for backups will be stored.\n\tconfigFilePath = flag.String(\"ceph_backup_storage_config\", \"ceph_backup_config.json\",\n\t\t\"Path to JSON config file for ceph backup storage\")\n)\n\nvar storageConfig struct {\n\tAccessKey string `json:\"accessKey\"`\n\tSecretKey string `json:\"secretKey\"`\n\tEndPoint  string `json:\"endPoint\"`\n\tUseSSL    bool   `json:\"useSSL\"`\n}\n\n\/\/ CephBackupHandle implements BackupHandle for Ceph Cloud Storage.\ntype CephBackupHandle struct {\n\tclient    *minio.Client\n\tbs        *CephBackupStorage\n\tdir       string\n\tname      string\n\treadOnly  bool\n\terrors    concurrency.AllErrorRecorder\n\twaitGroup sync.WaitGroup\n}\n\n\/\/ Directory implements BackupHandle.\nfunc (bh *CephBackupHandle) Directory() string {\n\treturn bh.dir\n}\n\n\/\/ Name implements BackupHandle.\nfunc (bh *CephBackupHandle) Name() string {\n\treturn bh.name\n}\n\n\/\/ AddFile implements BackupHandle.\nfunc (bh *CephBackupHandle) AddFile(ctx context.Context, filename string, filesize int64) (io.WriteCloser, error) {\n\tif bh.readOnly {\n\t\treturn nil, fmt.Errorf(\"AddFile cannot be called on read-only backup\")\n\t}\n\treader, writer := io.Pipe()\n\tbh.waitGroup.Add(1)\n\tgo func() {\n\t\tdefer bh.waitGroup.Done()\n\n\t\t\/\/ ceph bucket name is where the backups will go\n\t\t\/\/backup handle dir field contains keyspace\/shard value\n\t\tbucket := alterBucketName(bh.dir)\n\n\t\t\/\/ Give PutObject() the read end of the pipe.\n\t\tobject := objName(bh.dir, bh.name, filename)\n\t\t\/\/ if filesize is given as 0, pass it as -1 = UNKNOWN\n\t\tif filesize == 0 {\n\t\t\tfilesize = -1\n\t\t}\n\t\t_, err := bh.client.PutObjectWithContext(ctx, bucket, object, reader, filesize, minio.PutObjectOptions{ContentType: \"application\/octet-stream\"})\n\t\tif err != nil {\n\t\t\t\/\/ Signal the writer that an error occurred, in case it's not done writing yet.\n\t\t\treader.CloseWithError(err)\n\t\t\t\/\/ In case the error happened after the writer finished, we need to remember it.\n\t\t\tbh.errors.RecordError(err)\n\t\t}\n\t}()\n\t\/\/ Give our caller the write end of the pipe.\n\treturn writer, nil\n}\n\n\/\/ EndBackup implements BackupHandle.\nfunc (bh *CephBackupHandle) EndBackup(ctx context.Context) error {\n\tif bh.readOnly {\n\t\treturn fmt.Errorf(\"EndBackup cannot be called on read-only backup\")\n\t}\n\tbh.waitGroup.Wait()\n\t\/\/ Return the saved PutObject() errors, if any.\n\treturn bh.errors.Error()\n}\n\n\/\/ AbortBackup implements BackupHandle.\nfunc (bh *CephBackupHandle) AbortBackup(ctx context.Context) error {\n\tif bh.readOnly {\n\t\treturn fmt.Errorf(\"AbortBackup cannot be called on read-only backup\")\n\t}\n\treturn bh.bs.RemoveBackup(ctx, bh.dir, bh.name)\n}\n\n\/\/ ReadFile implements BackupHandle.\nfunc (bh *CephBackupHandle) ReadFile(ctx context.Context, filename string) (io.ReadCloser, error) {\n\tif !bh.readOnly {\n\t\treturn nil, fmt.Errorf(\"ReadFile cannot be called on read-write backup\")\n\t}\n\t\/\/ ceph bucket name\n\tbucket := alterBucketName(bh.dir)\n\tobject := objName(bh.dir, bh.name, filename)\n\treturn bh.client.GetObjectWithContext(ctx, bucket, object, minio.GetObjectOptions{})\n}\n\n\/\/ CephBackupStorage implements BackupStorage for Ceph Cloud Storage.\ntype CephBackupStorage struct {\n\t\/\/ client is the instance of the Ceph Cloud Storage Go client.\n\t\/\/ Once this field is set, it must not be written again\/unset to nil.\n\t_client *minio.Client\n\t\/\/ mu guards all fields.\n\tmu sync.Mutex\n}\n\n\/\/ ListBackups implements BackupStorage.\nfunc (bs *CephBackupStorage) ListBackups(ctx context.Context, dir string) ([]backupstorage.BackupHandle, error) {\n\tc, err := bs.client()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ ceph bucket name\n\tbucket := alterBucketName(dir)\n\n\t\/\/ List prefixes that begin with dir (i.e. list subdirs).\n\tvar subdirs []string\n\tsearchPrefix := objName(dir, \"\")\n\n\tdoneCh := make(chan struct{})\n\tfor object := range c.ListObjects(bucket, searchPrefix, false, doneCh) {\n\t\tif object.Err != nil {\n\t\t\t_, err := c.BucketExists(bucket)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t\treturn nil, object.Err\n\t\t}\n\t\tsubdir := strings.TrimPrefix(object.Key, searchPrefix)\n\t\tsubdir = strings.TrimSuffix(subdir, \"\/\")\n\t\tsubdirs = append(subdirs, subdir)\n\t}\n\n\t\/\/ Backups must be returned in order, oldest first.\n\tsort.Strings(subdirs)\n\n\tresult := make([]backupstorage.BackupHandle, 0, len(subdirs))\n\tfor _, subdir := range subdirs {\n\t\tresult = append(result, &CephBackupHandle{\n\t\t\tclient:   c,\n\t\t\tbs:       bs,\n\t\t\tdir:      dir,\n\t\t\tname:     subdir,\n\t\t\treadOnly: true,\n\t\t})\n\t}\n\treturn result, nil\n}\n\n\/\/ StartBackup implements BackupStorage.\nfunc (bs *CephBackupStorage) StartBackup(ctx context.Context, dir, name string) (backupstorage.BackupHandle, error) {\n\tc, err := bs.client()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ ceph bucket name\n\tbucket := alterBucketName(dir)\n\n\tfound, err := c.BucketExists(bucket)\n\n\tif err != nil {\n\t\tlog.Info(\"Error from BucketExists: %v, quitting\", bucket)\n\t\treturn nil, errors.New(\"Error checking whether bucket exists: \" + bucket)\n\t}\n\tif !found {\n\t\tlog.Info(\"Bucket: %v doesn't exist, creating new bucket with the required name\", bucket)\n\t\terr = c.MakeBucket(bucket, \"\")\n\t\tif err != nil {\n\t\t\tlog.Info(\"Error creating Bucket: %v, quitting\", bucket)\n\t\t\treturn nil, errors.New(\"Error creating new bucket: \" + bucket)\n\t\t}\n\t}\n\n\treturn &CephBackupHandle{\n\t\tclient:   c,\n\t\tbs:       bs,\n\t\tdir:      dir,\n\t\tname:     name,\n\t\treadOnly: false,\n\t}, nil\n}\n\n\/\/ RemoveBackup implements BackupStorage.\nfunc (bs *CephBackupStorage) RemoveBackup(ctx context.Context, dir, name string) error {\n\tc, err := bs.client()\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ ceph bucket name\n\tbucket := alterBucketName(dir)\n\n\tfullName := objName(dir, name, \"\")\n\tvar arr []string\n\tdoneCh := make(chan struct{})\n\tdefer close(doneCh)\n\tfor object := range c.ListObjects(bucket, fullName, true, doneCh) {\n\t\tif object.Err != nil {\n\t\t\treturn object.Err\n\t\t}\n\t\tarr = append(arr, object.Key)\n\t}\n\tfor _, obj := range arr {\n\t\terr = c.RemoveObject(bucket, obj)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Close implements BackupStorage.\nfunc (bs *CephBackupStorage) Close() error {\n\tbs.mu.Lock()\n\tdefer bs.mu.Unlock()\n\n\tif bs._client != nil {\n\t\t\/\/ a new client the next time one is needed.\n\t\tbs._client = nil\n\t}\n\treturn nil\n}\n\n\/\/ client returns the Ceph Storage client instance.\n\/\/ If there isn't one yet, it tries to create one.\nfunc (bs *CephBackupStorage) client() (*minio.Client, error) {\n\tbs.mu.Lock()\n\tdefer bs.mu.Unlock()\n\n\tif bs._client == nil {\n\t\tconfigFile, err := os.Open(*configFilePath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"file not present : %v\", err)\n\t\t}\n\t\tdefer configFile.Close()\n\t\tjsonParser := json.NewDecoder(configFile)\n\t\tif err = jsonParser.Decode(&storageConfig); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error parsing the json file : %v\", err)\n\t\t}\n\n\t\taccessKey := storageConfig.AccessKey\n\t\tsecretKey := storageConfig.SecretKey\n\t\turl := storageConfig.EndPoint\n\t\tuseSSL := storageConfig.UseSSL\n\n\t\tclient, err := minio.NewV2(url, accessKey, secretKey, useSSL)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbs._client = client\n\t}\n\treturn bs._client, nil\n}\n\nfunc init() {\n\tbackupstorage.BackupStorageMap[\"ceph\"] = &CephBackupStorage{}\n}\n\n\/\/ objName joins path parts into an object name.\n\/\/ Unlike path.Join, it doesn't collapse \"..\" or strip trailing slashes.\n\/\/ It also adds the value of the -gcs_backup_storage_root flag if set.\nfunc objName(parts ...string) string {\n\treturn strings.Join(parts, \"\/\")\n}\n\n\/\/ keeping in view the bucket naming conventions for ceph\n\/\/ only keyspace informations is extracted and used for bucket name\nfunc alterBucketName(dir string) string {\n\tbucket := strings.ToLower(dir)\n\tbucket = strings.Split(bucket, \"\/\")[0]\n\tbucket = strings.Replace(bucket, \"_\", \"-\", -1)\n\treturn bucket\n}\n<|endoftext|>"}
{"text":"<commit_before>package dormantdatabase\n\nimport (\n\t\"sync\"\n\n\thookapi \"github.com\/appscode\/kubernetes-webhook-util\/admission\/v1beta1\"\n\tdynamic_util \"github.com\/appscode\/kutil\/dynamic\"\n\tmeta_util \"github.com\/appscode\/kutil\/meta\"\n\tapi \"github.com\/kubedb\/apimachinery\/apis\/kubedb\/v1alpha1\"\n\tcs \"github.com\/kubedb\/apimachinery\/client\/clientset\/versioned\"\n\tplugin \"github.com\/kubedb\/apimachinery\/pkg\/admission\"\n\tadmission \"k8s.io\/api\/admission\/v1beta1\"\n\tcore \"k8s.io\/api\/core\/v1\"\n\tkerr \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\t\"k8s.io\/client-go\/dynamic\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\tclientsetscheme \"k8s.io\/client-go\/kubernetes\/scheme\"\n\t\"k8s.io\/client-go\/rest\"\n\t\"k8s.io\/client-go\/tools\/reference\"\n)\n\ntype DormantDatabaseValidator struct {\n\tclient      kubernetes.Interface\n\tdc          dynamic.Interface\n\textClient   cs.Interface\n\tlock        sync.RWMutex\n\tinitialized bool\n}\n\nvar _ hookapi.AdmissionHook = &DormantDatabaseValidator{}\n\nfunc (a *DormantDatabaseValidator) Resource() (plural schema.GroupVersionResource, singular string) {\n\treturn schema.GroupVersionResource{\n\t\t\tGroup:    \"validators.kubedb.com\",\n\t\t\tVersion:  \"v1alpha1\",\n\t\t\tResource: \"dormantdatabases\",\n\t\t},\n\t\t\"dormantdatabase\"\n}\n\nfunc (a *DormantDatabaseValidator) Initialize(config *rest.Config, stopCh <-chan struct{}) error {\n\ta.lock.Lock()\n\tdefer a.lock.Unlock()\n\n\ta.initialized = true\n\n\tvar err error\n\tif a.client, err = kubernetes.NewForConfig(config); err != nil {\n\t\treturn err\n\t}\n\tif a.dc, err = dynamic.NewForConfig(config); err != nil {\n\t\treturn err\n\t}\n\tif a.extClient, err = cs.NewForConfig(config); err != nil {\n\t\treturn err\n\t}\n\treturn err\n}\n\nfunc (a *DormantDatabaseValidator) Admit(req *admission.AdmissionRequest) *admission.AdmissionResponse {\n\tstatus := &admission.AdmissionResponse{}\n\n\t\/\/ No validation on CREATE\n\tif (req.Operation != admission.Update && req.Operation != admission.Delete) ||\n\t\tlen(req.SubResource) != 0 ||\n\t\treq.Kind.Group != api.SchemeGroupVersion.Group ||\n\t\treq.Kind.Kind != api.ResourceKindDormantDatabase {\n\t\tstatus.Allowed = true\n\t\treturn status\n\t}\n\n\ta.lock.RLock()\n\tdefer a.lock.RUnlock()\n\tif !a.initialized {\n\t\treturn hookapi.StatusUninitialized()\n\t}\n\n\tswitch req.Operation {\n\tcase admission.Delete:\n\t\tif req.Name != \"\" {\n\t\t\t\/\/ req.Object.Raw = nil, so read from kubernetes\n\t\t\tobj, err := a.extClient.KubedbV1alpha1().DormantDatabases(req.Namespace).Get(req.Name, metav1.GetOptions{})\n\t\t\tif err != nil && !kerr.IsNotFound(err) {\n\t\t\t\treturn hookapi.StatusInternalServerError(err)\n\t\t\t} else if kerr.IsNotFound(err) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err := a.handleOwnerReferences(obj); err != nil {\n\t\t\t\treturn hookapi.StatusInternalServerError(err)\n\t\t\t}\n\t\t}\n\tcase admission.Update:\n\t\t\/\/ validate the operation made by User\n\t\tobj, err := meta_util.UnmarshalFromJSON(req.Object.Raw, api.SchemeGroupVersion)\n\t\tif err != nil {\n\t\t\treturn hookapi.StatusBadRequest(err)\n\t\t}\n\t\tOldObj, err := meta_util.UnmarshalFromJSON(req.OldObject.Raw, api.SchemeGroupVersion)\n\t\tif err != nil {\n\t\t\treturn hookapi.StatusBadRequest(err)\n\t\t}\n\t\tif err := plugin.ValidateUpdate(obj, OldObj, req.Kind.Kind); err != nil {\n\t\t\treturn hookapi.StatusBadRequest(err)\n\t\t}\n\t}\n\n\tstatus.Allowed = true\n\treturn status\n}\n\nfunc (a *DormantDatabaseValidator) handleOwnerReferences(dormantDatabase *api.DormantDatabase) error {\n\tif dormantDatabase.Spec.WipeOut {\n\t\tif err := a.setOwnerReferenceToObjects(dormantDatabase); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif err := a.removeOwnerReferenceFromObjects(dormantDatabase); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (a *DormantDatabaseValidator) setOwnerReferenceToObjects(dormantDatabase *api.DormantDatabase) error {\n\t\/\/ Get LabelSelector for Other Components first\n\tdbKind, err := meta_util.GetStringValue(dormantDatabase.ObjectMeta.Labels, api.LabelDatabaseKind)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlabelMap := map[string]string{\n\t\tapi.LabelDatabaseName: dormantDatabase.Name,\n\t\tapi.LabelDatabaseKind: dbKind,\n\t}\n\tselector := labels.SelectorFromSet(labelMap)\n\n\t\/\/ Get object reference of dormant database\n\tref, rerr := reference.GetReference(clientsetscheme.Scheme, dormantDatabase)\n\tif rerr != nil {\n\t\treturn rerr\n\t}\n\tif err := dynamic_util.EnsureOwnerReferenceForSelector(\n\t\ta.dc,\n\t\tapi.SchemeGroupVersion.WithResource(api.ResourcePluralSnapshot),\n\t\tdormantDatabase.Namespace,\n\t\tselector,\n\t\tref); err != nil {\n\t\treturn nil\n\t}\n\tif err := dynamic_util.EnsureOwnerReferenceForSelector(\n\t\ta.dc,\n\t\tcore.SchemeGroupVersion.WithResource(\"persistentvolumeclaims\"),\n\t\t\"\", \/\/ non-namespaced\n\t\tselector,\n\t\tref); err != nil {\n\t\treturn nil\n\t}\n\tif err := dynamic_util.EnsureOwnerReferenceForItems(\n\t\ta.dc,\n\t\tcore.SchemeGroupVersion.WithResource(\"secrets\"),\n\t\tdormantDatabase.Namespace,\n\t\tdormantDatabase.GetDatabaseSecrets(),\n\t\tref); err != nil {\n\t\treturn nil\n\t}\n\treturn nil\n}\n\nfunc (a *DormantDatabaseValidator) removeOwnerReferenceFromObjects(dormantDatabase *api.DormantDatabase) error {\n\t\/\/ First, Get LabelSelector for Other Components\n\tdbKind, err := meta_util.GetStringValue(dormantDatabase.ObjectMeta.Labels, api.LabelDatabaseKind)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlabelMap := map[string]string{\n\t\tapi.LabelDatabaseName: dormantDatabase.Name,\n\t\tapi.LabelDatabaseKind: dbKind,\n\t}\n\tselector := labels.SelectorFromSet(labelMap)\n\n\t\/\/ Get object reference of dormant database\n\tref, rerr := reference.GetReference(clientsetscheme.Scheme, dormantDatabase)\n\tif rerr != nil {\n\t\treturn rerr\n\t}\n\tif err := dynamic_util.RemoveOwnerReferenceForSelector(\n\t\ta.dc,\n\t\tapi.SchemeGroupVersion.WithResource(api.ResourcePluralSnapshot),\n\t\tdormantDatabase.Namespace,\n\t\tselector,\n\t\tref); err != nil {\n\t\treturn nil\n\t}\n\tif err := dynamic_util.RemoveOwnerReferenceForSelector(\n\t\ta.dc,\n\t\tcore.SchemeGroupVersion.WithResource(\"persistentvolumeclaims\"),\n\t\t\"\", \/\/ non-namespaced\n\t\tselector,\n\t\tref); err != nil {\n\t\treturn nil\n\t}\n\tif err := dynamic_util.RemoveOwnerReferenceForItems(\n\t\ta.dc,\n\t\tcore.SchemeGroupVersion.WithResource(\"secrets\"),\n\t\tdormantDatabase.Namespace,\n\t\tdormantDatabase.GetDatabaseSecrets(),\n\t\tref); err != nil {\n\t\treturn nil\n\t}\n\treturn nil\n}\n<commit_msg>Provide namespace to DynamicClient for PersistentVolumeClaims resource (#308)<commit_after>package dormantdatabase\n\nimport (\n\t\"sync\"\n\n\thookapi \"github.com\/appscode\/kubernetes-webhook-util\/admission\/v1beta1\"\n\tdynamic_util \"github.com\/appscode\/kutil\/dynamic\"\n\tmeta_util \"github.com\/appscode\/kutil\/meta\"\n\tapi \"github.com\/kubedb\/apimachinery\/apis\/kubedb\/v1alpha1\"\n\tcs \"github.com\/kubedb\/apimachinery\/client\/clientset\/versioned\"\n\tplugin \"github.com\/kubedb\/apimachinery\/pkg\/admission\"\n\tadmission \"k8s.io\/api\/admission\/v1beta1\"\n\tcore \"k8s.io\/api\/core\/v1\"\n\tkerr \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\t\"k8s.io\/client-go\/dynamic\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\tclientsetscheme \"k8s.io\/client-go\/kubernetes\/scheme\"\n\t\"k8s.io\/client-go\/rest\"\n\t\"k8s.io\/client-go\/tools\/reference\"\n)\n\ntype DormantDatabaseValidator struct {\n\tclient      kubernetes.Interface\n\tdc          dynamic.Interface\n\textClient   cs.Interface\n\tlock        sync.RWMutex\n\tinitialized bool\n}\n\nvar _ hookapi.AdmissionHook = &DormantDatabaseValidator{}\n\nfunc (a *DormantDatabaseValidator) Resource() (plural schema.GroupVersionResource, singular string) {\n\treturn schema.GroupVersionResource{\n\t\t\tGroup:    \"validators.kubedb.com\",\n\t\t\tVersion:  \"v1alpha1\",\n\t\t\tResource: \"dormantdatabases\",\n\t\t},\n\t\t\"dormantdatabase\"\n}\n\nfunc (a *DormantDatabaseValidator) Initialize(config *rest.Config, stopCh <-chan struct{}) error {\n\ta.lock.Lock()\n\tdefer a.lock.Unlock()\n\n\ta.initialized = true\n\n\tvar err error\n\tif a.client, err = kubernetes.NewForConfig(config); err != nil {\n\t\treturn err\n\t}\n\tif a.dc, err = dynamic.NewForConfig(config); err != nil {\n\t\treturn err\n\t}\n\tif a.extClient, err = cs.NewForConfig(config); err != nil {\n\t\treturn err\n\t}\n\treturn err\n}\n\nfunc (a *DormantDatabaseValidator) Admit(req *admission.AdmissionRequest) *admission.AdmissionResponse {\n\tstatus := &admission.AdmissionResponse{}\n\n\t\/\/ No validation on CREATE\n\tif (req.Operation != admission.Update && req.Operation != admission.Delete) ||\n\t\tlen(req.SubResource) != 0 ||\n\t\treq.Kind.Group != api.SchemeGroupVersion.Group ||\n\t\treq.Kind.Kind != api.ResourceKindDormantDatabase {\n\t\tstatus.Allowed = true\n\t\treturn status\n\t}\n\n\ta.lock.RLock()\n\tdefer a.lock.RUnlock()\n\tif !a.initialized {\n\t\treturn hookapi.StatusUninitialized()\n\t}\n\n\tswitch req.Operation {\n\tcase admission.Delete:\n\t\tif req.Name != \"\" {\n\t\t\t\/\/ req.Object.Raw = nil, so read from kubernetes\n\t\t\tobj, err := a.extClient.KubedbV1alpha1().DormantDatabases(req.Namespace).Get(req.Name, metav1.GetOptions{})\n\t\t\tif err != nil && !kerr.IsNotFound(err) {\n\t\t\t\treturn hookapi.StatusInternalServerError(err)\n\t\t\t} else if kerr.IsNotFound(err) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err := a.handleOwnerReferences(obj); err != nil {\n\t\t\t\treturn hookapi.StatusInternalServerError(err)\n\t\t\t}\n\t\t}\n\tcase admission.Update:\n\t\t\/\/ validate the operation made by User\n\t\tobj, err := meta_util.UnmarshalFromJSON(req.Object.Raw, api.SchemeGroupVersion)\n\t\tif err != nil {\n\t\t\treturn hookapi.StatusBadRequest(err)\n\t\t}\n\t\tOldObj, err := meta_util.UnmarshalFromJSON(req.OldObject.Raw, api.SchemeGroupVersion)\n\t\tif err != nil {\n\t\t\treturn hookapi.StatusBadRequest(err)\n\t\t}\n\t\tif err := plugin.ValidateUpdate(obj, OldObj, req.Kind.Kind); err != nil {\n\t\t\treturn hookapi.StatusBadRequest(err)\n\t\t}\n\t}\n\n\tstatus.Allowed = true\n\treturn status\n}\n\nfunc (a *DormantDatabaseValidator) handleOwnerReferences(dormantDatabase *api.DormantDatabase) error {\n\tif dormantDatabase.Spec.WipeOut {\n\t\tif err := a.setOwnerReferenceToObjects(dormantDatabase); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif err := a.removeOwnerReferenceFromObjects(dormantDatabase); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (a *DormantDatabaseValidator) setOwnerReferenceToObjects(dormantDatabase *api.DormantDatabase) error {\n\t\/\/ Get LabelSelector for Other Components first\n\tdbKind, err := meta_util.GetStringValue(dormantDatabase.ObjectMeta.Labels, api.LabelDatabaseKind)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlabelMap := map[string]string{\n\t\tapi.LabelDatabaseName: dormantDatabase.Name,\n\t\tapi.LabelDatabaseKind: dbKind,\n\t}\n\tselector := labels.SelectorFromSet(labelMap)\n\n\t\/\/ Get object reference of dormant database\n\tref, rerr := reference.GetReference(clientsetscheme.Scheme, dormantDatabase)\n\tif rerr != nil {\n\t\treturn rerr\n\t}\n\tif err := dynamic_util.EnsureOwnerReferenceForSelector(\n\t\ta.dc,\n\t\tapi.SchemeGroupVersion.WithResource(api.ResourcePluralSnapshot),\n\t\tdormantDatabase.Namespace,\n\t\tselector,\n\t\tref); err != nil {\n\t\treturn nil\n\t}\n\tif err := dynamic_util.EnsureOwnerReferenceForSelector(\n\t\ta.dc,\n\t\tcore.SchemeGroupVersion.WithResource(\"persistentvolumeclaims\"),\n\t\tdormantDatabase.Namespace,\n\t\tselector,\n\t\tref); err != nil {\n\t\treturn nil\n\t}\n\tif err := dynamic_util.EnsureOwnerReferenceForItems(\n\t\ta.dc,\n\t\tcore.SchemeGroupVersion.WithResource(\"secrets\"),\n\t\tdormantDatabase.Namespace,\n\t\tdormantDatabase.GetDatabaseSecrets(),\n\t\tref); err != nil {\n\t\treturn nil\n\t}\n\treturn nil\n}\n\nfunc (a *DormantDatabaseValidator) removeOwnerReferenceFromObjects(dormantDatabase *api.DormantDatabase) error {\n\t\/\/ First, Get LabelSelector for Other Components\n\tdbKind, err := meta_util.GetStringValue(dormantDatabase.ObjectMeta.Labels, api.LabelDatabaseKind)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlabelMap := map[string]string{\n\t\tapi.LabelDatabaseName: dormantDatabase.Name,\n\t\tapi.LabelDatabaseKind: dbKind,\n\t}\n\tselector := labels.SelectorFromSet(labelMap)\n\n\t\/\/ Get object reference of dormant database\n\tref, rerr := reference.GetReference(clientsetscheme.Scheme, dormantDatabase)\n\tif rerr != nil {\n\t\treturn rerr\n\t}\n\tif err := dynamic_util.RemoveOwnerReferenceForSelector(\n\t\ta.dc,\n\t\tapi.SchemeGroupVersion.WithResource(api.ResourcePluralSnapshot),\n\t\tdormantDatabase.Namespace,\n\t\tselector,\n\t\tref); err != nil {\n\t\treturn nil\n\t}\n\tif err := dynamic_util.RemoveOwnerReferenceForSelector(\n\t\ta.dc,\n\t\tcore.SchemeGroupVersion.WithResource(\"persistentvolumeclaims\"),\n\t\tdormantDatabase.Namespace,\n\t\tselector,\n\t\tref); err != nil {\n\t\treturn nil\n\t}\n\tif err := dynamic_util.RemoveOwnerReferenceForItems(\n\t\ta.dc,\n\t\tcore.SchemeGroupVersion.WithResource(\"secrets\"),\n\t\tdormantDatabase.Namespace,\n\t\tdormantDatabase.GetDatabaseSecrets(),\n\t\tref); err != nil {\n\t\treturn nil\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package derivatives_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/bitfinexcom\/bitfinex-api-go\/pkg\/models\/derivatives\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc TestNewDerivativeStatusFromWsRaw(t *testing.T) {\n\tt.Run(\"insufficient arguments\", func(t *testing.T) {\n\t\tpayload := []interface{}{float64(1591614631576)}\n\n\t\td, err := derivatives.NewDerivativeStatusFromWsRaw(\"tBTCF0:USTF0\", payload)\n\t\trequire.NotNil(t, err)\n\t\trequire.Nil(t, d)\n\t})\n\n\tt.Run(\"valid arguments\", func(t *testing.T) {\n\t\tpayload := []interface{}{\n\t\t\tfloat64(1591614631576),\n\t\t\tnil,\n\t\t\t9271.1234567,\n\t\t\t9275.3,\n\t\t\tnil,\n\t\t\t1391472.27686063,\n\t\t\tnil,\n\t\t\t1594656000000,\n\t\t\t-0.00011968,\n\t\t\t3144,\n\t\t\tnil,\n\t\t\t0,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\t9276.06,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\t3813.72957182,\n\t\t}\n\n\t\td, err := derivatives.NewDerivativeStatusFromWsRaw(\"tBTCF0:USTF0\", payload)\n\t\trequire.Nil(t, err)\n\n\t\texpected := &derivatives.DerivativeStatus{\n\t\t\tSymbol:               \"tBTCF0:USTF0\",\n\t\t\tMTS:                  1591614631576,\n\t\t\tPrice:                9271.1234567,\n\t\t\tSpotPrice:            9275.3,\n\t\t\tInsuranceFundBalance: 1.39147227686063e+06,\n\t\t\tFundingAccrued:       -0.00011968,\n\t\t\tMarkPrice:            9276.06,\n\t\t\tOpenInterest:         3813.72957182,\n\t\t}\n\t\tassert.Equal(t, expected, d)\n\t})\n}\n\nfunc TestNewDerivativeStatusFromRaw(t *testing.T) {\n\tt.Run(\"insufficient arguments\", func(t *testing.T) {\n\t\tpayload := []interface{}{\"tBTCF0:USTF0\"}\n\n\t\td, err := derivatives.NewDerivativeStatusFromRaw(payload)\n\t\trequire.NotNil(t, err)\n\t\trequire.Nil(t, d)\n\t})\n\n\tt.Run(\"valid arguments\", func(t *testing.T) {\n\t\tpayload := []interface{}{\n\t\t\t\"tBTCF0:USTF0\",\n\t\t\tfloat64(1591614631576),\n\t\t\tnil,\n\t\t\t9271.1234567,\n\t\t\t9275.3,\n\t\t\tnil,\n\t\t\t1391472.27686063,\n\t\t\tnil,\n\t\t\t1594656000000,\n\t\t\t-0.00011968,\n\t\t\t3144,\n\t\t\tnil,\n\t\t\t0,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\t9276.06,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\t3813.72957182,\n\t\t}\n\n\t\td, err := derivatives.NewDerivativeStatusFromRaw(payload)\n\t\trequire.Nil(t, err)\n\n\t\texpected := &derivatives.DerivativeStatus{\n\t\t\tSymbol:               \"tBTCF0:USTF0\",\n\t\t\tMTS:                  1591614631576,\n\t\t\tPrice:                9271.1234567,\n\t\t\tSpotPrice:            9275.3,\n\t\t\tInsuranceFundBalance: 1.39147227686063e+06,\n\t\t\tFundingAccrued:       -0.00011968,\n\t\t\tMarkPrice:            9276.06,\n\t\t\tOpenInterest:         3813.72957182,\n\t\t}\n\t\tassert.Equal(t, expected, d)\n\t})\n}\n<commit_msg>adding more tests to cover snapshot functionaity for derivatives status<commit_after>package derivatives_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/bitfinexcom\/bitfinex-api-go\/pkg\/models\/derivatives\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc TestNewDerivativeStatusFromWsRaw(t *testing.T) {\n\tt.Run(\"insufficient arguments\", func(t *testing.T) {\n\t\tpayload := []interface{}{float64(1591614631576)}\n\n\t\td, err := derivatives.FromWsRaw(\"tBTCF0:USTF0\", payload)\n\t\trequire.NotNil(t, err)\n\t\trequire.Nil(t, d)\n\t})\n\n\tt.Run(\"valid arguments\", func(t *testing.T) {\n\t\tpayload := []interface{}{\n\t\t\tfloat64(1591614631576),\n\t\t\tnil,\n\t\t\t9271.1234567,\n\t\t\t9275.3,\n\t\t\tnil,\n\t\t\t1391472.27686063,\n\t\t\tnil,\n\t\t\t1594656000000,\n\t\t\t-0.00011968,\n\t\t\t3144,\n\t\t\tnil,\n\t\t\t0,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\t9276.06,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\t3813.72957182,\n\t\t}\n\n\t\td, err := derivatives.FromWsRaw(\"tBTCF0:USTF0\", payload)\n\t\trequire.Nil(t, err)\n\n\t\texpected := &derivatives.DerivativeStatus{\n\t\t\tSymbol:               \"tBTCF0:USTF0\",\n\t\t\tMTS:                  1591614631576,\n\t\t\tPrice:                9271.1234567,\n\t\t\tSpotPrice:            9275.3,\n\t\t\tInsuranceFundBalance: 1.39147227686063e+06,\n\t\t\tFundingAccrued:       -0.00011968,\n\t\t\tFundingStep:          3144,\n\t\t\tMarkPrice:            9276.06,\n\t\t\tOpenInterest:         3813.72957182,\n\t\t}\n\t\tassert.Equal(t, expected, d)\n\t})\n}\n\nfunc TestNewDerivativeStatusFromRaw(t *testing.T) {\n\tt.Run(\"insufficient arguments\", func(t *testing.T) {\n\t\tpayload := []interface{}{\"tBTCF0:USTF0\"}\n\n\t\td, err := derivatives.FromRaw(payload)\n\t\trequire.NotNil(t, err)\n\t\trequire.Nil(t, d)\n\t})\n\n\tt.Run(\"valid arguments\", func(t *testing.T) {\n\t\tpayload := []interface{}{\n\t\t\t\"tBTCF0:USTF0\",\n\t\t\tfloat64(1591614631576),\n\t\t\tnil,\n\t\t\t9271.1234567,\n\t\t\t9275.3,\n\t\t\tnil,\n\t\t\t1391472.27686063,\n\t\t\tnil,\n\t\t\t1594656000000,\n\t\t\t-0.00011968,\n\t\t\t3144,\n\t\t\tnil,\n\t\t\t0,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\t9276.06,\n\t\t\tnil,\n\t\t\tnil,\n\t\t\t3813.72957182,\n\t\t}\n\n\t\td, err := derivatives.FromRaw(payload)\n\t\trequire.Nil(t, err)\n\n\t\texpected := &derivatives.DerivativeStatus{\n\t\t\tSymbol:               \"tBTCF0:USTF0\",\n\t\t\tMTS:                  1591614631576,\n\t\t\tPrice:                9271.1234567,\n\t\t\tSpotPrice:            9275.3,\n\t\t\tInsuranceFundBalance: 1.39147227686063e+06,\n\t\t\tFundingAccrued:       -0.00011968,\n\t\t\tFundingStep:          3144,\n\t\t\tMarkPrice:            9276.06,\n\t\t\tOpenInterest:         3813.72957182,\n\t\t}\n\t\tassert.Equal(t, expected, d)\n\t})\n}\n\nfunc TestSnapshotFromRaw(t *testing.T) {\n\tt.Run(\"invalid arguments\", func(t *testing.T) {\n\t\tpayload := [][]interface{}{{\"tBTCF0:USTF0\"}}\n\t\tss, err := derivatives.SnapshotFromRaw(payload)\n\t\trequire.NotNil(t, err)\n\t\trequire.Nil(t, ss)\n\t})\n\n\tt.Run(\"valid arguments\", func(t *testing.T) {\n\t\tpayload := [][]interface{}{\n\t\t\t{\n\t\t\t\t\"tBTCF0:USTF0\",\n\t\t\t\tfloat64(1591614631576),\n\t\t\t\tnil,\n\t\t\t\t9271.1234567,\n\t\t\t\t9275.3,\n\t\t\t\tnil,\n\t\t\t\t1391472.27686063,\n\t\t\t\tnil,\n\t\t\t\t1594656000000,\n\t\t\t\t-0.00011968,\n\t\t\t\t3144,\n\t\t\t\tnil,\n\t\t\t\t0,\n\t\t\t\tnil,\n\t\t\t\tnil,\n\t\t\t\t9276.06,\n\t\t\t\tnil,\n\t\t\t\tnil,\n\t\t\t\t3813.72957182,\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"tBTCF0:USTF0\",\n\t\t\t\tfloat64(1591614631576),\n\t\t\t\tnil,\n\t\t\t\t9271.1234567,\n\t\t\t\t9275.3,\n\t\t\t\tnil,\n\t\t\t\t1391472.27686063,\n\t\t\t\tnil,\n\t\t\t\t1594656000000,\n\t\t\t\t-0.00011968,\n\t\t\t\t3200,\n\t\t\t\tnil,\n\t\t\t\t0,\n\t\t\t\tnil,\n\t\t\t\tnil,\n\t\t\t\t9276.06,\n\t\t\t\tnil,\n\t\t\t\tnil,\n\t\t\t\t3813.72957182,\n\t\t\t},\n\t\t}\n\t\tss, err := derivatives.SnapshotFromRaw(payload)\n\t\trequire.Nil(t, err)\n\n\t\texpected := &derivatives.DerivativeStatusSnapshot{\n\t\t\tSnapshot: []*derivatives.DerivativeStatus{\n\t\t\t\t{\n\t\t\t\t\tSymbol:               \"tBTCF0:USTF0\",\n\t\t\t\t\tMTS:                  1591614631576,\n\t\t\t\t\tPrice:                9271.1234567,\n\t\t\t\t\tSpotPrice:            9275.3,\n\t\t\t\t\tInsuranceFundBalance: 1.39147227686063e+06,\n\t\t\t\t\tFundingAccrued:       -0.00011968,\n\t\t\t\t\tFundingStep:          3144,\n\t\t\t\t\tMarkPrice:            9276.06,\n\t\t\t\t\tOpenInterest:         3813.72957182,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tSymbol:               \"tBTCF0:USTF0\",\n\t\t\t\t\tMTS:                  1591614631576,\n\t\t\t\t\tPrice:                9271.1234567,\n\t\t\t\t\tSpotPrice:            9275.3,\n\t\t\t\t\tInsuranceFundBalance: 1.39147227686063e+06,\n\t\t\t\t\tFundingAccrued:       -0.00011968,\n\t\t\t\t\tFundingStep:          3200,\n\t\t\t\t\tMarkPrice:            9276.06,\n\t\t\t\t\tOpenInterest:         3813.72957182,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\tassert.Equal(t, expected, ss)\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package syslog\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/lager\"\n\t\"code.cloudfoundry.org\/lager\/lagerctx\"\n\t\"github.com\/concourse\/concourse\/atc\/db\"\n\t\"github.com\/concourse\/concourse\/atc\/event\"\n)\n\n\/\/go:generate counterfeiter . Drainer\n\ntype Drainer interface {\n\tRun(context.Context) error\n}\n\ntype drainer struct {\n\thostname     string\n\ttransport    string `yaml:\"transport\"`\n\taddress      string `yaml:\"address\"`\n\tcaCerts      []string\n\tbuildFactory db.BuildFactory\n}\n\nfunc NewDrainer(transport string, address string, hostname string, caCerts []string, buildFactory db.BuildFactory) Drainer {\n\treturn &drainer{\n\t\thostname:     hostname,\n\t\ttransport:    transport,\n\t\taddress:      address,\n\t\tbuildFactory: buildFactory,\n\t\tcaCerts:      caCerts,\n\t}\n}\n\nfunc (d *drainer) Run(ctx context.Context) error {\n\tlogger := lagerctx.FromContext(ctx).Session(\"syslog\")\n\n\tbuilds, err := d.buildFactory.GetDrainableBuilds()\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-get-drainable-builds\", err)\n\t\treturn err\n\t}\n\n\tif len(builds) > 0 {\n\t\tsyslog, err := Dial(d.transport, d.address, d.caCerts)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed-to-connect\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ ignore any errors coming from syslog.Close()\n\t\tdefer db.Close(syslog)\n\n\t\tfor _, build := range builds {\n\t\t\terr := d.drainBuild(logger, build, syslog)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (d *drainer) drainBuild(logger lager.Logger, build db.Build, syslog *Syslog) error {\n\tlogger = logger.Session(\"drain-build\", lager.Data{\n\t\t\"team\":     build.TeamName(),\n\t\t\"pipeline\": build.PipelineName(),\n\t\t\"job\":      build.JobName(),\n\t\t\"build\":    build.Name(),\n\t})\n\n\tevents, err := build.Events(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ ignore any errors coming from events.Close()\n\tdefer db.Close(events)\n\n\tfor {\n\t\tev, err := events.Next()\n\t\tif err != nil {\n\t\t\tif err == db.ErrEndOfBuildEventStream {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlogger.Error(\"failed-to-get-next-event\", err)\n\t\t\treturn err\n\t\t}\n\n\t\tif ev.Event == event.EventTypeLog {\n\t\t\tvar log event.Log\n\n\t\t\terr := json.Unmarshal(*ev.Data, &log)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(\"failed-to-unmarshal\", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpayload := log.Payload\n\t\t\ttag := build.TeamName() + \"\/\" + build.PipelineName() + \"\/\" + build.JobName() + \"\/\" + build.Name() + \"\/\" + string(log.Origin.ID)\n\n\t\t\terr = syslog.Write(d.hostname, tag, time.Unix(log.Time, 0), payload)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(\"failed-to-write-to-server\", err, lager.Data{\"tag\": tag})\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\terr = build.SetDrained(true)\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-update-status\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>atc: cleanup syslog logging<commit_after>package syslog\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/lager\"\n\t\"code.cloudfoundry.org\/lager\/lagerctx\"\n\t\"github.com\/concourse\/concourse\/atc\/db\"\n\t\"github.com\/concourse\/concourse\/atc\/event\"\n)\n\n\/\/go:generate counterfeiter . Drainer\n\ntype Drainer interface {\n\tRun(context.Context) error\n}\n\ntype drainer struct {\n\thostname     string\n\ttransport    string `yaml:\"transport\"`\n\taddress      string `yaml:\"address\"`\n\tcaCerts      []string\n\tbuildFactory db.BuildFactory\n}\n\nfunc NewDrainer(transport string, address string, hostname string, caCerts []string, buildFactory db.BuildFactory) Drainer {\n\treturn &drainer{\n\t\thostname:     hostname,\n\t\ttransport:    transport,\n\t\taddress:      address,\n\t\tbuildFactory: buildFactory,\n\t\tcaCerts:      caCerts,\n\t}\n}\n\nfunc (d *drainer) Run(ctx context.Context) error {\n\tlogger := lagerctx.FromContext(ctx).Session(\"syslog\")\n\n\tbuilds, err := d.buildFactory.GetDrainableBuilds()\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-get-drainable-builds\", err)\n\t\treturn err\n\t}\n\n\tif len(builds) > 0 {\n\t\tsyslog, err := Dial(d.transport, d.address, d.caCerts)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed-to-connect\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ ignore any errors coming from syslog.Close()\n\t\tdefer db.Close(syslog)\n\n\t\tfor _, build := range builds {\n\t\t\terr := d.drainBuild(logger, build, syslog)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (d *drainer) drainBuild(logger lager.Logger, build db.Build, syslog *Syslog) error {\n\tlogger = logger.Session(\"drain-build\", lager.Data{\n\t\t\"team\":     build.TeamName(),\n\t\t\"pipeline\": build.PipelineName(),\n\t\t\"job\":      build.JobName(),\n\t\t\"build\":    build.Name(),\n\t})\n\n\tevents, err := build.Events(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ ignore any errors coming from events.Close()\n\tdefer db.Close(events)\n\n\tfor {\n\t\tev, err := events.Next()\n\t\tif err != nil {\n\t\t\tif err == db.ErrEndOfBuildEventStream {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tlogger.Error(\"failed-to-get-next-event\", err)\n\t\t\treturn err\n\t\t}\n\n\t\tif ev.Event == event.EventTypeLog {\n\t\t\tvar log event.Log\n\n\t\t\terr := json.Unmarshal(*ev.Data, &log)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(\"failed-to-unmarshal\", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpayload := log.Payload\n\t\t\ttag := build.TeamName() + \"\/\" + build.PipelineName() + \"\/\" + build.JobName() + \"\/\" + build.Name() + \"\/\" + string(log.Origin.ID)\n\n\t\t\terr = syslog.Write(d.hostname, tag, time.Unix(log.Time, 0), payload)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(\"failed-to-write-to-server\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\terr = build.SetDrained(true)\n\tif err != nil {\n\t\tlogger.Error(\"failed-to-update-status\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package datastore\n\nimport (\n\t\"github.com\/favclip\/testerator\"\n\t\"google.golang.org\/appengine\/datastore\"\n)\n\nfunc init() {\n\ttesterator.DefaultSetup.Cleaners = append(testerator.DefaultSetup.Cleaners, cleanup)\n}\n\nfunc cleanup(s *testerator.Setup) error {\n\tt := datastore.NewQuery(\"__kind__\").KeysOnly().Run(s.Context)\n\tkinds := make([]string, 0)\n\tfor {\n\t\tkey, err := t.Next(nil)\n\t\tif err == datastore.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkinds = append(kinds, key.StringID())\n\t}\n\n\tfor _, kind := range kinds {\n\t\tq := datastore.NewQuery(kind).KeysOnly()\n\t\tkeys, err := q.GetAll(s.Context, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = datastore.DeleteMulti(s.Context, keys)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>Claeanup datastore under all namespaces<commit_after>package datastore\n\nimport (\n\t\"context\"\n\n\t\"github.com\/favclip\/testerator\"\n\t\"google.golang.org\/appengine\"\n\t\"google.golang.org\/appengine\/datastore\"\n)\n\nfunc init() {\n\ttesterator.DefaultSetup.Cleaners = append(testerator.DefaultSetup.Cleaners, cleanup)\n}\n\nfunc cleanup(s *testerator.Setup) error {\n\tcontexts := []context.Context{s.Context}\n\n\tq := datastore.NewQuery(\"__namespace__\").KeysOnly()\n\tnamespaces, err := q.GetAll(s.Context, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, ns := range namespaces {\n\t\tnsContext, err := appengine.Namespace(s.Context, ns.StringID())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcontexts = append(contexts, nsContext)\n\t}\n\n\tfor _, ctx := range contexts {\n\t\terr := cleanupUnderContext(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc cleanupUnderContext(ctx context.Context) error {\n\tt := datastore.NewQuery(\"__kind__\").KeysOnly().Run(ctx)\n\tkinds := make([]string, 0)\n\tfor {\n\t\tkey, err := t.Next(nil)\n\t\tif err == datastore.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkinds = append(kinds, key.StringID())\n\t}\n\n\tfor _, kind := range kinds {\n\t\tq := datastore.NewQuery(kind).KeysOnly()\n\t\tkeys, err := q.GetAll(ctx, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = datastore.DeleteMulti(ctx, keys)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/chromium\/hstspreload\"\n\t\"github.com\/chromium\/hstspreload\/chromiumpreload\"\n)\n\nfunc main() {\n\tstaticHandler := http.FileServer(http.Dir(\"static\"))\n\thttp.Handle(\"\/\", staticHandler)\n\thttp.Handle(\"\/style.css\", staticHandler)\n\thttp.Handle(\"\/index.js\", staticHandler)\n\n\thttp.HandleFunc(\"\/robots.txt\", http.NotFound)\n\thttp.HandleFunc(\"\/favicon.ico\", http.NotFound)\n\n\thttp.HandleFunc(\"\/checkdomain\/\", checkdomain)\n\thttp.HandleFunc(\"\/status\/\", status)\n\n\thttp.HandleFunc(\"\/submit\/\", submit)\n\thttp.HandleFunc(\"\/pending\", pending)\n\thttp.HandleFunc(\"\/update\", update)\n\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc checkdomain(w http.ResponseWriter, r *http.Request) {\n\tdomain := r.URL.Path[len(\"\/checkdomain\/\"):]\n\n\tissues := hstspreload.CheckDomain(domain)\n\n\tb, err := json.MarshalIndent(hstspreload.MakeSlices(issues), \"\", \"  \")\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error: could not encode JSON.\\n\", http.StatusInternalServerError)\n\t} else {\n\t\tfmt.Fprintf(w, \"%s\\n\", b)\n\t}\n}\n\n\/\/ writeJSONOrBust should only be called if nothing has been written yet.\nfunc writeJSONOrBust(w http.ResponseWriter, v interface{}) {\n\tw.Header().Set(\"Content-type\", \"text\/css; charset=utf-8\")\n\n\tb, err := json.MarshalIndent(v, \"\", \"  \")\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Internal error: could not format JSON. (%s)\\n\", err)\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"%s\\n\", b)\n\treturn\n}\n\nfunc status(w http.ResponseWriter, r *http.Request) {\n\tdomain := chromiumpreload.Domain(r.URL.Path[len(\"\/status\/\"):])\n\n\tstate, err := stateForDomain(domain)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Internal error: could not retrieve status. (%s)\\n\", err)\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tstate.Name = domain\n\twriteJSONOrBust(w, state)\n}\n\nfunc submit(w http.ResponseWriter, r *http.Request) {\n\tdomainStr := r.URL.Path[len(\"\/submit\/\"):]\n\tdomain := chromiumpreload.Domain(domainStr)\n\n\tissues := hstspreload.CheckDomain(domainStr)\n\tif len(issues.Errors) > 0 {\n\t\twriteJSONOrBust(w, issues)\n\t\treturn\n\t}\n\n\tstate, stateErr := stateForDomain(domain)\n\tif stateErr != nil {\n\t\tmsg := fmt.Sprintf(\"Internal error: could not get current domain status. (%s)\\n\", stateErr)\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t}\n\n\tswitch state.Status {\n\tcase StatusUnknown:\n\t\tfallthrough\n\tcase StatusRemoved:\n\t\tputErr := putState(DomainState{\n\t\t\tName:           domain,\n\t\t\tStatus:         StatusPending,\n\t\t\tSubmissionDate: time.Now(),\n\t\t})\n\t\tif putErr != nil {\n\t\t\tissues = hstspreload.Issues{\n\t\t\t\tErrors:   append(issues.Errors, \"Internal error: Unable to save to the pending list.\\n\"),\n\t\t\t\tWarnings: issues.Warnings,\n\t\t\t}\n\t\t}\n\tcase StatusPending:\n\t\tformattedDate := state.SubmissionDate.Format(\"Monday, _2 January 2006\")\n\t\tissues = hstspreload.Issues{\n\t\t\tErrors:   issues.Errors,\n\t\t\tWarnings: append(issues.Warnings, fmt.Sprintf(\"Domain is already pending. It was submitted on %s.\\n\", formattedDate)),\n\t\t}\n\tcase StatusPreloaded:\n\t\tissues = hstspreload.Issues{\n\t\t\tErrors:   append(issues.Errors, \"Domain is already preloaded.\\n\"),\n\t\t\tWarnings: issues.Warnings,\n\t\t}\n\tcase StatusRejected:\n\t\trejectedMsg := fmt.Sprintf(\"Domain has been rejected. (%s)\\n\", state.Message)\n\t\tissues = hstspreload.Issues{\n\t\t\tErrors:   append(issues.Warnings, rejectedMsg),\n\t\t\tWarnings: issues.Warnings,\n\t\t}\n\tdefault:\n\t\tissues = hstspreload.Issues{\n\t\t\tErrors:   append(issues.Warnings, \"Cannot preload.\\n\"),\n\t\t\tWarnings: issues.Warnings,\n\t\t}\n\t}\n\n\twriteJSONOrBust(w, hstspreload.MakeSlices(issues))\n}\n\nfunc pending(w http.ResponseWriter, r *http.Request) {\n\tnames, err := domainsWithStatus(StatusPending)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Internal error: could not retrieve pending list. (%s)\\n\", err)\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"[\\n\")\n\tfor i, name := range names {\n\t\tcomma := \",\"\n\t\tif i+1 == len(names) {\n\t\t\tcomma = \"\"\n\t\t}\n\n\t\tfmt.Fprintf(w, `    { \"name\": \"%s\", \"include_subdomains\": true, \"mode\": \"force-https\" }%s\n`, name, comma)\n\t}\n\tfmt.Fprintf(w, \"]\\n\")\n}\n\nfunc difference(from []chromiumpreload.Domain, take []chromiumpreload.Domain) (diff []chromiumpreload.Domain) {\n\ttakeSet := make(map[chromiumpreload.Domain]bool)\n\tfor _, elem := range take {\n\t\ttakeSet[elem] = true\n\t}\n\n\tfor _, elem := range from {\n\t\tif !takeSet[elem] {\n\t\t\tdiff = append(diff, elem)\n\t\t}\n\t}\n\n\treturn diff\n}\n\nfunc update(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Get preload list.\n\tpreloadList, listErr := chromiumpreload.GetLatest()\n\tif listErr != nil {\n\t\tmsg := fmt.Sprintf(\n\t\t\t\"Internal error: could not retrieve latest preload list. (%s)\\n\",\n\t\t\tlistErr,\n\t\t)\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tvar actualPreload []chromiumpreload.Domain\n\tfor _, entry := range preloadList.Entries {\n\t\tif entry.Mode == chromiumpreload.ForceHTTPS {\n\t\t\tactualPreload = append(actualPreload, entry.Name)\n\t\t}\n\t}\n\n\t\/\/ Get domains currently recorded as preloaded.\n\tdatabasePreload, dbErr := domainsWithStatus(StatusPreloaded)\n\tif dbErr != nil {\n\t\tmsg := fmt.Sprintf(\n\t\t\t\"Internal error: could not retrieve domain names previously marked as preloaded. (%s)\\n\",\n\t\t\tdbErr,\n\t\t)\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/ Calculate values that are out of date.\n\tvar updates []DomainState\n\n\tadded := difference(actualPreload, databasePreload)\n\tfor _, name := range added {\n\t\tupdates = append(updates, DomainState{\n\t\t\tName:   name,\n\t\t\tStatus: StatusPreloaded,\n\t\t})\n\t}\n\n\tremoved := difference(databasePreload, actualPreload)\n\tfor _, name := range removed {\n\t\tupdates = append(updates, DomainState{\n\t\t\tName:   name,\n\t\t\tStatus: StatusRemoved,\n\t\t})\n\t}\n\n\tfmt.Fprintf(w, `The preload list has %d entries.\n- # of preloaded HSTS entries: %d\n- # to be added in this update: %d\n- # to be removed this update: %d\n`,\n\t\tlen(preloadList.Entries),\n\t\tlen(actualPreload),\n\t\tlen(added),\n\t\tlen(removed),\n\t)\n\n\t\/\/ Create statusReport function to show progress.\n\twritten := false\n\tf, ok := w.(http.Flusher)\n\tif !ok {\n\t\thttp.Error(w, \"Internal error: Could not create `http.Flusher`.\\n\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tstatusReport := func(format string, args ...interface{}) {\n\t\tfmt.Fprintf(w, format, args...)\n\t\tf.Flush()\n\t\twritten = true\n\t}\n\n\t\/\/ Update the database\n\tputErr := putStates(updates, statusReport)\n\tif putErr != nil {\n\t\tmsg := fmt.Sprintf(\n\t\t\t\"Internal error: datastore update failed. (%s)\\n\",\n\t\t\tputErr,\n\t\t)\n\t\tif written {\n\t\t\t\/\/ The header and part of the body have already been sent, so we\n\t\t\t\/\/ can't change the status code anymore.\n\t\t\tfmt.Fprintf(w, msg)\n\t\t} else {\n\t\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"Success. %d domain states updated.\\n\", len(updates))\n}\n<commit_msg>Allow rejected domains to be submitted again.<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/chromium\/hstspreload\"\n\t\"github.com\/chromium\/hstspreload\/chromiumpreload\"\n)\n\nfunc main() {\n\tstaticHandler := http.FileServer(http.Dir(\"static\"))\n\thttp.Handle(\"\/\", staticHandler)\n\thttp.Handle(\"\/style.css\", staticHandler)\n\thttp.Handle(\"\/index.js\", staticHandler)\n\n\thttp.HandleFunc(\"\/robots.txt\", http.NotFound)\n\thttp.HandleFunc(\"\/favicon.ico\", http.NotFound)\n\n\thttp.HandleFunc(\"\/checkdomain\/\", checkdomain)\n\thttp.HandleFunc(\"\/status\/\", status)\n\n\thttp.HandleFunc(\"\/submit\/\", submit)\n\thttp.HandleFunc(\"\/pending\", pending)\n\thttp.HandleFunc(\"\/update\", update)\n\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc checkdomain(w http.ResponseWriter, r *http.Request) {\n\tdomain := r.URL.Path[len(\"\/checkdomain\/\"):]\n\n\tissues := hstspreload.CheckDomain(domain)\n\n\tb, err := json.MarshalIndent(hstspreload.MakeSlices(issues), \"\", \"  \")\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error: could not encode JSON.\\n\", http.StatusInternalServerError)\n\t} else {\n\t\tfmt.Fprintf(w, \"%s\\n\", b)\n\t}\n}\n\n\/\/ writeJSONOrBust should only be called if nothing has been written yet.\nfunc writeJSONOrBust(w http.ResponseWriter, v interface{}) {\n\tw.Header().Set(\"Content-type\", \"text\/css; charset=utf-8\")\n\n\tb, err := json.MarshalIndent(v, \"\", \"  \")\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Internal error: could not format JSON. (%s)\\n\", err)\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"%s\\n\", b)\n\treturn\n}\n\nfunc status(w http.ResponseWriter, r *http.Request) {\n\tdomain := chromiumpreload.Domain(r.URL.Path[len(\"\/status\/\"):])\n\n\tstate, err := stateForDomain(domain)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Internal error: could not retrieve status. (%s)\\n\", err)\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tstate.Name = domain\n\twriteJSONOrBust(w, state)\n}\n\nfunc submit(w http.ResponseWriter, r *http.Request) {\n\tdomainStr := r.URL.Path[len(\"\/submit\/\"):]\n\tdomain := chromiumpreload.Domain(domainStr)\n\n\tissues := hstspreload.CheckDomain(domainStr)\n\tif len(issues.Errors) > 0 {\n\t\twriteJSONOrBust(w, issues)\n\t\treturn\n\t}\n\n\tstate, stateErr := stateForDomain(domain)\n\tif stateErr != nil {\n\t\tmsg := fmt.Sprintf(\"Internal error: could not get current domain status. (%s)\\n\", stateErr)\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t}\n\n\tswitch state.Status {\n\tcase StatusUnknown:\n\t\tfallthrough\n\tcase StatusRejected:\n\t\tfallthrough\n\tcase StatusRemoved:\n\t\tputErr := putState(DomainState{\n\t\t\tName:           domain,\n\t\t\tStatus:         StatusPending,\n\t\t\tSubmissionDate: time.Now(),\n\t\t})\n\t\tif putErr != nil {\n\t\t\tissues = hstspreload.Issues{\n\t\t\t\tErrors:   append(issues.Errors, \"Internal error: Unable to save to the pending list.\\n\"),\n\t\t\t\tWarnings: issues.Warnings,\n\t\t\t}\n\t\t}\n\tcase StatusPending:\n\t\tformattedDate := state.SubmissionDate.Format(\"Monday, _2 January 2006\")\n\t\tissues = hstspreload.Issues{\n\t\t\tErrors:   issues.Errors,\n\t\t\tWarnings: append(issues.Warnings, fmt.Sprintf(\"Domain is already pending. It was submitted on %s.\\n\", formattedDate)),\n\t\t}\n\tcase StatusPreloaded:\n\t\tissues = hstspreload.Issues{\n\t\t\tErrors:   append(issues.Errors, \"Domain is already preloaded.\\n\"),\n\t\t\tWarnings: issues.Warnings,\n\t\t}\n\tdefault:\n\t\tissues = hstspreload.Issues{\n\t\t\tErrors:   append(issues.Warnings, \"Cannot preload.\\n\"),\n\t\t\tWarnings: issues.Warnings,\n\t\t}\n\t}\n\n\twriteJSONOrBust(w, hstspreload.MakeSlices(issues))\n}\n\nfunc pending(w http.ResponseWriter, r *http.Request) {\n\tnames, err := domainsWithStatus(StatusPending)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Internal error: could not retrieve pending list. (%s)\\n\", err)\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"[\\n\")\n\tfor i, name := range names {\n\t\tcomma := \",\"\n\t\tif i+1 == len(names) {\n\t\t\tcomma = \"\"\n\t\t}\n\n\t\tfmt.Fprintf(w, `    { \"name\": \"%s\", \"include_subdomains\": true, \"mode\": \"force-https\" }%s\n`, name, comma)\n\t}\n\tfmt.Fprintf(w, \"]\\n\")\n}\n\nfunc difference(from []chromiumpreload.Domain, take []chromiumpreload.Domain) (diff []chromiumpreload.Domain) {\n\ttakeSet := make(map[chromiumpreload.Domain]bool)\n\tfor _, elem := range take {\n\t\ttakeSet[elem] = true\n\t}\n\n\tfor _, elem := range from {\n\t\tif !takeSet[elem] {\n\t\t\tdiff = append(diff, elem)\n\t\t}\n\t}\n\n\treturn diff\n}\n\nfunc update(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Get preload list.\n\tpreloadList, listErr := chromiumpreload.GetLatest()\n\tif listErr != nil {\n\t\tmsg := fmt.Sprintf(\n\t\t\t\"Internal error: could not retrieve latest preload list. (%s)\\n\",\n\t\t\tlistErr,\n\t\t)\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tvar actualPreload []chromiumpreload.Domain\n\tfor _, entry := range preloadList.Entries {\n\t\tif entry.Mode == chromiumpreload.ForceHTTPS {\n\t\t\tactualPreload = append(actualPreload, entry.Name)\n\t\t}\n\t}\n\n\t\/\/ Get domains currently recorded as preloaded.\n\tdatabasePreload, dbErr := domainsWithStatus(StatusPreloaded)\n\tif dbErr != nil {\n\t\tmsg := fmt.Sprintf(\n\t\t\t\"Internal error: could not retrieve domain names previously marked as preloaded. (%s)\\n\",\n\t\t\tdbErr,\n\t\t)\n\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/ Calculate values that are out of date.\n\tvar updates []DomainState\n\n\tadded := difference(actualPreload, databasePreload)\n\tfor _, name := range added {\n\t\tupdates = append(updates, DomainState{\n\t\t\tName:   name,\n\t\t\tStatus: StatusPreloaded,\n\t\t})\n\t}\n\n\tremoved := difference(databasePreload, actualPreload)\n\tfor _, name := range removed {\n\t\tupdates = append(updates, DomainState{\n\t\t\tName:   name,\n\t\t\tStatus: StatusRemoved,\n\t\t})\n\t}\n\n\tfmt.Fprintf(w, `The preload list has %d entries.\n- # of preloaded HSTS entries: %d\n- # to be added in this update: %d\n- # to be removed this update: %d\n`,\n\t\tlen(preloadList.Entries),\n\t\tlen(actualPreload),\n\t\tlen(added),\n\t\tlen(removed),\n\t)\n\n\t\/\/ Create statusReport function to show progress.\n\twritten := false\n\tf, ok := w.(http.Flusher)\n\tif !ok {\n\t\thttp.Error(w, \"Internal error: Could not create `http.Flusher`.\\n\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tstatusReport := func(format string, args ...interface{}) {\n\t\tfmt.Fprintf(w, format, args...)\n\t\tf.Flush()\n\t\twritten = true\n\t}\n\n\t\/\/ Update the database\n\tputErr := putStates(updates, statusReport)\n\tif putErr != nil {\n\t\tmsg := fmt.Sprintf(\n\t\t\t\"Internal error: datastore update failed. (%s)\\n\",\n\t\t\tputErr,\n\t\t)\n\t\tif written {\n\t\t\t\/\/ The header and part of the body have already been sent, so we\n\t\t\t\/\/ can't change the status code anymore.\n\t\t\tfmt.Fprintf(w, msg)\n\t\t} else {\n\t\t\thttp.Error(w, msg, http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Fprintf(w, \"Success. %d domain states updated.\\n\", len(updates))\n}\n<|endoftext|>"}
{"text":"<commit_before>package httphandlers\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/Financial-Times\/service-status-go\/buildinfo\"\n\t\"net\/http\"\n)\n\ntype FtHandler func(http.ResponseWriter, *http.Request)\n\n\/\/BuildInfoHandler is a HandlerFunc that returns a JSON representation of the build-info.\nfunc BuildInfoHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tif err := json.NewEncoder(w).Encode(buildinfo.GetBuildInfo()); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc (f FtHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"GET\" {\n\t\tf(w, r)\n\t} else {\n\t\tw.Header().Set(\"Allow\", \"GET\")\n\t\thttp.Error(w, \"Method not allowed\", http.StatusMethodNotAllowed)\n\t}\n}\n<commit_msg>commit to share, do not use !<commit_after>package httphandlers\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/Financial-Times\/service-status-go\/buildinfo\"\n\t\"net\/http\"\n)\n\n\/\/ FtHandler looks like a standard handler to me\ntype FtHandler func(http.ResponseWriter, *http.Request)\n\n\/\/BuildInfo provides a JSON representation of the build-info.\nfunc BuildInfo(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tif err := json.NewEncoder(w).Encode(buildinfo.GetBuildInfo()); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc (f FtHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"GET\" {\n\t\tf(w, r)\n\t} else {\n\t\tw.Header().Set(\"Allow\", \"GET\")\n\t\thttp.Error(w, \"Method not allowed\", http.StatusMethodNotAllowed)\n\t}\n}\n\ntype httpMux interface {\n\tHandleFunc(string, func(http.ResponseWriter, *http.Request))\n}\n\n\/\/ RegisterPing just registeres the Ping handler with an http mux\nfunc RegisterPing(mux httpMux) {\n\tmux.HandleFunc(\"\/__ping\", Ping)\n\tmux.HandleFunc(\"\/ping\", Ping)\n}\n\n\/\/ RegisterBuildInfo adds the build-info handlers\nfunc RegisterBuildInfo(mux httpMux) {\n\tmux.HandleFunc(\"\/__build-info\", BuildInfo)\n\tmux.HandleFunc(\"\/build-info\", BuildInfo)\n}\n\n\/\/ RegisterAll adds all the handlers\nfunc RegisterAll(mux httpMux) {\n\tRegisterPing(mux)\n\tRegisterBuildInfo(mux)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage sync\n\nimport (\n\t\"internal\/race\"\n\t\"sync\/atomic\"\n\t\"unsafe\"\n)\n\n\/\/ A WaitGroup waits for a collection of goroutines to finish.\n\/\/ The main goroutine calls Add to set the number of\n\/\/ goroutines to wait for. Then each of the goroutines\n\/\/ runs and calls Done when finished. At the same time,\n\/\/ Wait can be used to block until all goroutines have finished.\n\/\/\n\/\/ A WaitGroup must not be copied after first use.\ntype WaitGroup struct {\n\tnoCopy noCopy\n\n\t\/\/ 64-bit value: high 32 bits are counter, low 32 bits are waiter count.\n\t\/\/ 64-bit atomic operations require 64-bit alignment, but 32-bit\n\t\/\/ compilers do not ensure it. So we allocate 12 bytes and then use\n\t\/\/ the aligned 8 bytes in them as state, and the other 4 as storage\n\t\/\/ for the sema.\n\tstate1 [3]uint32\n}\n\n\/\/ state returns pointers to the state and sema fields stored within wg.state1.\nfunc (wg *WaitGroup) state() (statep *uint64, semap *uint32) {\n\tif uintptr(unsafe.Pointer(&wg.state1))%8 == 0 {\n\t\treturn (*uint64)(unsafe.Pointer(&wg.state1)), &wg.state1[2]\n\t} else {\n\t\treturn (*uint64)(unsafe.Pointer(&wg.state1[1])), &wg.state1[0]\n\t}\n}\n\n\/\/ Add adds delta, which may be negative, to the WaitGroup counter.\n\/\/ If the counter becomes zero, all goroutines blocked on Wait are released.\n\/\/ If the counter goes negative, Add panics.\n\/\/\n\/\/ Note that calls with a positive delta that occur when the counter is zero\n\/\/ must happen before a Wait. Calls with a negative delta, or calls with a\n\/\/ positive delta that start when the counter is greater than zero, may happen\n\/\/ at any time.\n\/\/ Typically this means the calls to Add should execute before the statement\n\/\/ creating the goroutine or other event to be waited for.\n\/\/ If a WaitGroup is reused to wait for several independent sets of events,\n\/\/ new Add calls must happen after all previous Wait calls have returned.\n\/\/ See the WaitGroup example.\nfunc (wg *WaitGroup) Add(delta int) {\n\tstatep, semap := wg.state()\n\tif race.Enabled {\n\t\t_ = *statep \/\/ trigger nil deref early\n\t\tif delta < 0 {\n\t\t\t\/\/ Synchronize decrements with Wait.\n\t\t\trace.ReleaseMerge(unsafe.Pointer(wg))\n\t\t}\n\t\trace.Disable()\n\t\tdefer race.Enable()\n\t}\n\tstate := atomic.AddUint64(statep, uint64(delta)<<32)\n\tv := int32(state >> 32)\n\tw := uint32(state)\n\tif race.Enabled && delta > 0 && v == int32(delta) {\n\t\t\/\/ The first increment must be synchronized with Wait.\n\t\t\/\/ Need to model this as a read, because there can be\n\t\t\/\/ several concurrent wg.counter transitions from 0.\n\t\trace.Read(unsafe.Pointer(semap))\n\t}\n\tif v < 0 {\n\t\tpanic(\"sync: negative WaitGroup counter\")\n\t}\n\tif w != 0 && delta > 0 && v == int32(delta) {\n\t\tpanic(\"sync: WaitGroup misuse: Add called concurrently with Wait\")\n\t}\n\tif v > 0 || w == 0 {\n\t\treturn\n\t}\n\t\/\/ This goroutine has set counter to 0 when waiters > 0.\n\t\/\/ Now there can't be concurrent mutations of state:\n\t\/\/ - Adds must not happen concurrently with Wait,\n\t\/\/ - Wait does not increment waiters if it sees counter == 0.\n\t\/\/ Still do a cheap sanity check to detect WaitGroup misuse.\n\tif *statep != state {\n\t\tpanic(\"sync: WaitGroup misuse: Add called concurrently with Wait\")\n\t}\n\t\/\/ Reset waiters count to 0.\n\t*statep = 0\n\tfor ; w != 0; w-- {\n\t\truntime_Semrelease(semap, false, 0)\n\t}\n}\n\n\/\/ Done decrements the WaitGroup counter by one.\nfunc (wg *WaitGroup) Done() {\n\twg.Add(-1)\n}\n\n\/\/ Wait blocks until the WaitGroup counter is zero.\nfunc (wg *WaitGroup) Wait() {\n\tstatep, semap := wg.state()\n\tif race.Enabled {\n\t\t_ = *statep \/\/ trigger nil deref early\n\t\trace.Disable()\n\t}\n\tfor {\n\t\tstate := atomic.LoadUint64(statep)\n\t\tv := int32(state >> 32)\n\t\tw := uint32(state)\n\t\tif v == 0 {\n\t\t\t\/\/ Counter is 0, no need to wait.\n\t\t\tif race.Enabled {\n\t\t\t\trace.Enable()\n\t\t\t\trace.Acquire(unsafe.Pointer(wg))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\t\/\/ Increment waiters count.\n\t\tif atomic.CompareAndSwapUint64(statep, state, state+1) {\n\t\t\tif race.Enabled && w == 0 {\n\t\t\t\t\/\/ Wait must be synchronized with the first Add.\n\t\t\t\t\/\/ Need to model this is as a write to race with the read in Add.\n\t\t\t\t\/\/ As a consequence, can do the write only for the first waiter,\n\t\t\t\t\/\/ otherwise concurrent Waits will race with each other.\n\t\t\t\trace.Write(unsafe.Pointer(semap))\n\t\t\t}\n\t\t\truntime_Semacquire(semap)\n\t\t\tif *statep != 0 {\n\t\t\t\tpanic(\"sync: WaitGroup is reused before previous Wait has returned\")\n\t\t\t}\n\t\t\tif race.Enabled {\n\t\t\t\trace.Enable()\n\t\t\t\trace.Acquire(unsafe.Pointer(wg))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}\n<commit_msg>sync: avoid a dynamic check in WaitGroup on 64-bit architectures<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage sync\n\nimport (\n\t\"internal\/race\"\n\t\"sync\/atomic\"\n\t\"unsafe\"\n)\n\n\/\/ A WaitGroup waits for a collection of goroutines to finish.\n\/\/ The main goroutine calls Add to set the number of\n\/\/ goroutines to wait for. Then each of the goroutines\n\/\/ runs and calls Done when finished. At the same time,\n\/\/ Wait can be used to block until all goroutines have finished.\n\/\/\n\/\/ A WaitGroup must not be copied after first use.\ntype WaitGroup struct {\n\tnoCopy noCopy\n\n\t\/\/ 64-bit value: high 32 bits are counter, low 32 bits are waiter count.\n\t\/\/ 64-bit atomic operations require 64-bit alignment, but 32-bit\n\t\/\/ compilers only guarantee that 64-bit fields are 32-bit aligned.\n\t\/\/ For this reason on 32 bit architectures we need to check in state()\n\t\/\/ if state1 is aligned or not, and dynamically \"swap\" the field order if\n\t\/\/ needed.\n\tstate1 uint64\n\tstate2 uint32\n}\n\n\/\/ state returns pointers to the state and sema fields stored within wg.state*.\nfunc (wg *WaitGroup) state() (statep *uint64, semap *uint32) {\n\tif unsafe.Alignof(wg.state1) == 8 || uintptr(unsafe.Pointer(&wg.state1))%8 == 0 {\n\t\t\/\/ state1 is 64-bit aligned: nothing to do.\n\t\treturn &wg.state1, &wg.state2\n\t} else {\n\t\t\/\/ state1 is 32-bit aligned but not 64-bit aligned: this means that\n\t\t\/\/ (&state1)+4 is 64-bit aligned.\n\t\tstate := (*[3]uint32)(unsafe.Pointer(&wg.state1))\n\t\treturn (*uint64)(unsafe.Pointer(&state[1])), &state[0]\n\t}\n}\n\n\/\/ Add adds delta, which may be negative, to the WaitGroup counter.\n\/\/ If the counter becomes zero, all goroutines blocked on Wait are released.\n\/\/ If the counter goes negative, Add panics.\n\/\/\n\/\/ Note that calls with a positive delta that occur when the counter is zero\n\/\/ must happen before a Wait. Calls with a negative delta, or calls with a\n\/\/ positive delta that start when the counter is greater than zero, may happen\n\/\/ at any time.\n\/\/ Typically this means the calls to Add should execute before the statement\n\/\/ creating the goroutine or other event to be waited for.\n\/\/ If a WaitGroup is reused to wait for several independent sets of events,\n\/\/ new Add calls must happen after all previous Wait calls have returned.\n\/\/ See the WaitGroup example.\nfunc (wg *WaitGroup) Add(delta int) {\n\tstatep, semap := wg.state()\n\tif race.Enabled {\n\t\t_ = *statep \/\/ trigger nil deref early\n\t\tif delta < 0 {\n\t\t\t\/\/ Synchronize decrements with Wait.\n\t\t\trace.ReleaseMerge(unsafe.Pointer(wg))\n\t\t}\n\t\trace.Disable()\n\t\tdefer race.Enable()\n\t}\n\tstate := atomic.AddUint64(statep, uint64(delta)<<32)\n\tv := int32(state >> 32)\n\tw := uint32(state)\n\tif race.Enabled && delta > 0 && v == int32(delta) {\n\t\t\/\/ The first increment must be synchronized with Wait.\n\t\t\/\/ Need to model this as a read, because there can be\n\t\t\/\/ several concurrent wg.counter transitions from 0.\n\t\trace.Read(unsafe.Pointer(semap))\n\t}\n\tif v < 0 {\n\t\tpanic(\"sync: negative WaitGroup counter\")\n\t}\n\tif w != 0 && delta > 0 && v == int32(delta) {\n\t\tpanic(\"sync: WaitGroup misuse: Add called concurrently with Wait\")\n\t}\n\tif v > 0 || w == 0 {\n\t\treturn\n\t}\n\t\/\/ This goroutine has set counter to 0 when waiters > 0.\n\t\/\/ Now there can't be concurrent mutations of state:\n\t\/\/ - Adds must not happen concurrently with Wait,\n\t\/\/ - Wait does not increment waiters if it sees counter == 0.\n\t\/\/ Still do a cheap sanity check to detect WaitGroup misuse.\n\tif *statep != state {\n\t\tpanic(\"sync: WaitGroup misuse: Add called concurrently with Wait\")\n\t}\n\t\/\/ Reset waiters count to 0.\n\t*statep = 0\n\tfor ; w != 0; w-- {\n\t\truntime_Semrelease(semap, false, 0)\n\t}\n}\n\n\/\/ Done decrements the WaitGroup counter by one.\nfunc (wg *WaitGroup) Done() {\n\twg.Add(-1)\n}\n\n\/\/ Wait blocks until the WaitGroup counter is zero.\nfunc (wg *WaitGroup) Wait() {\n\tstatep, semap := wg.state()\n\tif race.Enabled {\n\t\t_ = *statep \/\/ trigger nil deref early\n\t\trace.Disable()\n\t}\n\tfor {\n\t\tstate := atomic.LoadUint64(statep)\n\t\tv := int32(state >> 32)\n\t\tw := uint32(state)\n\t\tif v == 0 {\n\t\t\t\/\/ Counter is 0, no need to wait.\n\t\t\tif race.Enabled {\n\t\t\t\trace.Enable()\n\t\t\t\trace.Acquire(unsafe.Pointer(wg))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\t\/\/ Increment waiters count.\n\t\tif atomic.CompareAndSwapUint64(statep, state, state+1) {\n\t\t\tif race.Enabled && w == 0 {\n\t\t\t\t\/\/ Wait must be synchronized with the first Add.\n\t\t\t\t\/\/ Need to model this is as a write to race with the read in Add.\n\t\t\t\t\/\/ As a consequence, can do the write only for the first waiter,\n\t\t\t\t\/\/ otherwise concurrent Waits will race with each other.\n\t\t\t\trace.Write(unsafe.Pointer(semap))\n\t\t\t}\n\t\t\truntime_Semacquire(semap)\n\t\t\tif *statep != 0 {\n\t\t\t\tpanic(\"sync: WaitGroup is reused before previous Wait has returned\")\n\t\t\t}\n\t\t\tif race.Enabled {\n\t\t\t\trace.Enable()\n\t\t\t\trace.Acquire(unsafe.Pointer(wg))\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package platform\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/containers\/image\/v5\/types\"\n\timgspecv1 \"github.com\/opencontainers\/image-spec\/specs-go\/v1\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestWantedPlatformsCompatibility(t *testing.T) {\n\tctx := &types.SystemContext{\n\t\tArchitectureChoice: \"arm\",\n\t\tOSChoice:           \"linux\",\n\t\tVariantChoice:      \"v6\",\n\t}\n\tplatforms, err := WantedPlatforms(ctx)\n\tassert.Nil(t, err)\n\tassert.Equal(t, len(platforms), 2)\n\tassert.Equal(t, platforms[0], imgspecv1.Platform{\n\t\tOS:           ctx.OSChoice,\n\t\tArchitecture: ctx.ArchitectureChoice,\n\t\tVariant:      \"v6\",\n\t})\n\tassert.Equal(t, platforms[1], imgspecv1.Platform{\n\t\tOS:           ctx.OSChoice,\n\t\tArchitecture: ctx.ArchitectureChoice,\n\t\tVariant:      \"v5\",\n\t})\n}\n\nfunc TestWantedPlatformsCustom(t *testing.T) {\n\tctx := &types.SystemContext{\n\t\tArchitectureChoice: \"armel\",\n\t\tOSChoice:           \"freeBSD\",\n\t\tVariantChoice:      \"custom\",\n\t}\n\tplatforms, err := WantedPlatforms(ctx)\n\tassert.Nil(t, err)\n\tassert.Equal(t, len(platforms), 1)\n\tassert.Equal(t, platforms[0], imgspecv1.Platform{\n\t\tOS:           ctx.OSChoice,\n\t\tArchitecture: ctx.ArchitectureChoice,\n\t\tVariant:      ctx.VariantChoice,\n\t})\n}\n<commit_msg>Simplify WantedPlatforms tests<commit_after>package platform\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/containers\/image\/v5\/types\"\n\timgspecv1 \"github.com\/opencontainers\/image-spec\/specs-go\/v1\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestWantedPlatformsCompatibility(t *testing.T) {\n\tctx := &types.SystemContext{\n\t\tArchitectureChoice: \"arm\",\n\t\tOSChoice:           \"linux\",\n\t\tVariantChoice:      \"v6\",\n\t}\n\tplatforms, err := WantedPlatforms(ctx)\n\tassert.Nil(t, err)\n\tassert.Equal(t, []imgspecv1.Platform{\n\t\t{OS: ctx.OSChoice, Architecture: ctx.ArchitectureChoice, Variant: \"v6\"},\n\t\t{OS: ctx.OSChoice, Architecture: ctx.ArchitectureChoice, Variant: \"v5\"},\n\t}, platforms)\n}\n\nfunc TestWantedPlatformsCustom(t *testing.T) {\n\tctx := &types.SystemContext{\n\t\tArchitectureChoice: \"armel\",\n\t\tOSChoice:           \"freeBSD\",\n\t\tVariantChoice:      \"custom\",\n\t}\n\tplatforms, err := WantedPlatforms(ctx)\n\tassert.Nil(t, err)\n\tassert.Equal(t, []imgspecv1.Platform{\n\t\t{OS: ctx.OSChoice, Architecture: ctx.ArchitectureChoice, Variant: ctx.VariantChoice},\n\t}, platforms)\n}\n<|endoftext|>"}
{"text":"<commit_before>package provider\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/validation\"\n\t\"github.com\/hashicorp\/terraform\/helper\/validation\"\n\t\"github.com\/mackerelio\/mackerel-client-go\"\n)\n\nfunc resourceMackerelChannel() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceMackerelChannelCreate,\n\t\tRead:   resourceMackerelChannelRead,\n\t\tDelete: resourceMackerelChannelDelete,\n\t\tImporter: &schema.ResourceImporter{\n\t\t\tState: schema.ImportStatePassthrough,\n\t\t},\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"type\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\t\"email\",\n\t\t\t\t\t\"slack\",\n\t\t\t\t\t\"webhook\",\n\t\t\t\t}, false),\n\t\t\t},\n\t\t\t\"name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"emails\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\t\t\t\/\/ Field name may only contain lowercase alphanumeric characters & underscores.\n\t\t\t\"user_ids\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\t\t\t\"events\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\t\t\t\"url\": {\n\t\t\t\tType:          schema.TypeString,\n\t\t\t\tOptional:      true,\n\t\t\t\tForceNew:      true,\n\t\t\t\tConflictsWith: []string{\"emails\", \"user_ids\"},\n\t\t\t},\n\t\t\t\"mentions\": {\n\t\t\t\tType:     schema.TypeMap,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\t\t\t\"enabled_graph_image\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceMackerelChannelCreate(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*mackerel.Client)\n\n\tinput, err := buildChannelParameter(d)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tchannel, err := client.CreateChannel(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[DEBUG] mackerel channel %q created.\", channel.ID)\n\td.SetId(channel.ID)\n\n\treturn resourceMackerelChannelRead(d, meta)\n}\n\nfunc resourceMackerelChannelRead(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*mackerel.Client)\n\n\tlog.Printf(\"[DEBUG] Reading mackerel channel: %q\", d.Id())\n\tchannels, err := client.FindChannels()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, channel := range channels {\n\t\tif channel.ID == d.Id() {\n\t\t\t_ = d.Set(\"id\", channel.ID)\n\t\t\t_ = d.Set(\"name\", channel.Name)\n\t\t\t_ = d.Set(\"type\", channel.Type)\n\t\t\t_ = d.Set(\"url\", channel.URL)\n\t\t\t_ = d.Set(\"enabled_graph_image\", channel.EnabledGraphImage)\n\t\t\t_ = d.Set(\"user_ids\", channel.UserIDs)\n\t\t\t_ = d.Set(\"mentions\", channel.Mentions)\n\t\t\t_ = d.Set(\"events\", channel.Events)\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc resourceMackerelChannelDelete(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*mackerel.Client)\n\n\t_, err := client.DeleteChannel(d.Id())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[DEBUG] mackerel channel %q deleted.\", d.Id())\n\td.SetId(\"\")\n\n\treturn nil\n}\n\nfunc buildChannelParameter(d *schema.ResourceData) (*mackerel.Channel, error) {\n\tswitch d.Get(\"type\").(string) {\n\tcase \"email\":\n\t\treturn buildEmailParameter(d)\n\tcase \"slack\":\n\t\treturn buildSlackParameter(d)\n\tcase \"webhook\":\n\t\treturn buildWebhookParameter(d)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%v is not valid input for type\", d.Get(\"type\"))\n\t}\n}\n\n\/\/ build parameter for email\nfunc buildEmailParameter(d *schema.ResourceData) (*mackerel.Channel, error) {\n\tinput := &mackerel.Channel{\n\t\tName: d.Get(\"name\").(string),\n\t\tType: d.Get(\"type\").(string),\n\t}\n\n\tif v, ok := d.GetOk(\"emails\"); ok {\n\t\ttmp := expandStringList(v.([]interface{}))\n\t\tinput.Emails = &tmp\n\t}\n\n\tif v, ok := d.GetOk(\"user_ids\"); ok {\n\t\ttmp := expandStringList(v.([]interface{}))\n\t\tinput.UserIDs = &tmp\n\t}\n\n\tif input.Emails == nil && input.UserIDs == nil {\n\t\treturn nil, fmt.Errorf(\"emails or user_ids is required\")\n\t}\n\n\tif v, ok := d.GetOk(\"events\"); ok {\n\t\ttmp := expandStringList(v.([]interface{}))\n\t\terr := validateChannelEvent(tmp, []string{\"alert\", \"alertGroup\"})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinput.Events = &tmp\n\t}\n\n\treturn input, nil\n}\n\n\/\/ build parameter for slack\nfunc buildSlackParameter(d *schema.ResourceData) (*mackerel.Channel, error) {\n\tinput := &mackerel.Channel{\n\t\tName: d.Get(\"name\").(string),\n\t\tType: d.Get(\"type\").(string),\n\t\tURL:  d.Get(\"url\").(string),\n\t}\n\n\tif v, ok := d.Get(\"enabled_graph_image\").(bool); ok {\n\t\tinput.EnabledGraphImage = &v\n\t}\n\n\tif v, ok := d.GetOk(\"mentions\"); ok {\n\t\t\/\/ Convert from schema.TypeMap to mackerel.Mentions\n\t\tmentionJSON, err := json.Marshal(v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar mentions mackerel.Mentions\n\t\terr = json.Unmarshal(mentionJSON, &mentions)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinput.Mentions = mentions\n\t}\n\n\tif v, ok := d.GetOk(\"events\"); ok {\n\t\ttmp := expandStringList(v.([]interface{}))\n\t\terr := validateChannelEvent(tmp, []string{\"alert\", \"alertGroup\", \"hostStatus\", \"hostRegister\", \"hostRetire\", \"monitor\"})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinput.Events = &tmp\n\t}\n\n\treturn input, nil\n}\n\n\/\/ build parameter for webhook\nfunc buildWebhookParameter(d *schema.ResourceData) (*mackerel.Channel, error) {\n\tinput := &mackerel.Channel{\n\t\tName: d.Get(\"name\").(string),\n\t\tType: d.Get(\"type\").(string),\n\t\tURL:  d.Get(\"url\").(string),\n\t}\n\n\tif v, ok := d.Get(\"enabled_graph_image\").(bool); ok {\n\t\tinput.EnabledGraphImage = &v\n\t}\n\n\tif v, ok := d.GetOk(\"events\"); ok {\n\t\ttmp := expandStringList(v.([]interface{}))\n\t\terr := validateChannelEvent(tmp, []string{\"alert\", \"alertGroup\", \"hostStatus\", \"hostRegister\", \"hostRetire\", \"monitor\"})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinput.Events = &tmp\n\t}\n\n\treturn input, nil\n}\n<commit_msg>Remove unused package<commit_after>package provider\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/validation\"\n\t\"github.com\/mackerelio\/mackerel-client-go\"\n)\n\nfunc resourceMackerelChannel() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceMackerelChannelCreate,\n\t\tRead:   resourceMackerelChannelRead,\n\t\tDelete: resourceMackerelChannelDelete,\n\t\tImporter: &schema.ResourceImporter{\n\t\t\tState: schema.ImportStatePassthrough,\n\t\t},\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"type\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\t\"email\",\n\t\t\t\t\t\"slack\",\n\t\t\t\t\t\"webhook\",\n\t\t\t\t}, false),\n\t\t\t},\n\t\t\t\"name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"emails\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\t\t\t\/\/ Field name may only contain lowercase alphanumeric characters & underscores.\n\t\t\t\"user_ids\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\t\t\t\"events\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\t\t\t\"url\": {\n\t\t\t\tType:          schema.TypeString,\n\t\t\t\tOptional:      true,\n\t\t\t\tForceNew:      true,\n\t\t\t\tConflictsWith: []string{\"emails\", \"user_ids\"},\n\t\t\t},\n\t\t\t\"mentions\": {\n\t\t\t\tType:     schema.TypeMap,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t},\n\t\t\t\"enabled_graph_image\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceMackerelChannelCreate(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*mackerel.Client)\n\n\tinput, err := buildChannelParameter(d)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tchannel, err := client.CreateChannel(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[DEBUG] mackerel channel %q created.\", channel.ID)\n\td.SetId(channel.ID)\n\n\treturn resourceMackerelChannelRead(d, meta)\n}\n\nfunc resourceMackerelChannelRead(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*mackerel.Client)\n\n\tlog.Printf(\"[DEBUG] Reading mackerel channel: %q\", d.Id())\n\tchannels, err := client.FindChannels()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, channel := range channels {\n\t\tif channel.ID == d.Id() {\n\t\t\t_ = d.Set(\"id\", channel.ID)\n\t\t\t_ = d.Set(\"name\", channel.Name)\n\t\t\t_ = d.Set(\"type\", channel.Type)\n\t\t\t_ = d.Set(\"url\", channel.URL)\n\t\t\t_ = d.Set(\"enabled_graph_image\", channel.EnabledGraphImage)\n\t\t\t_ = d.Set(\"user_ids\", channel.UserIDs)\n\t\t\t_ = d.Set(\"mentions\", channel.Mentions)\n\t\t\t_ = d.Set(\"events\", channel.Events)\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc resourceMackerelChannelDelete(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*mackerel.Client)\n\n\t_, err := client.DeleteChannel(d.Id())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[DEBUG] mackerel channel %q deleted.\", d.Id())\n\td.SetId(\"\")\n\n\treturn nil\n}\n\nfunc buildChannelParameter(d *schema.ResourceData) (*mackerel.Channel, error) {\n\tswitch d.Get(\"type\").(string) {\n\tcase \"email\":\n\t\treturn buildEmailParameter(d)\n\tcase \"slack\":\n\t\treturn buildSlackParameter(d)\n\tcase \"webhook\":\n\t\treturn buildWebhookParameter(d)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%v is not valid input for type\", d.Get(\"type\"))\n\t}\n}\n\n\/\/ build parameter for email\nfunc buildEmailParameter(d *schema.ResourceData) (*mackerel.Channel, error) {\n\tinput := &mackerel.Channel{\n\t\tName: d.Get(\"name\").(string),\n\t\tType: d.Get(\"type\").(string),\n\t}\n\n\tif v, ok := d.GetOk(\"emails\"); ok {\n\t\ttmp := expandStringList(v.([]interface{}))\n\t\tinput.Emails = &tmp\n\t}\n\n\tif v, ok := d.GetOk(\"user_ids\"); ok {\n\t\ttmp := expandStringList(v.([]interface{}))\n\t\tinput.UserIDs = &tmp\n\t}\n\n\tif input.Emails == nil && input.UserIDs == nil {\n\t\treturn nil, fmt.Errorf(\"emails or user_ids is required\")\n\t}\n\n\tif v, ok := d.GetOk(\"events\"); ok {\n\t\ttmp := expandStringList(v.([]interface{}))\n\t\terr := validateChannelEvent(tmp, []string{\"alert\", \"alertGroup\"})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinput.Events = &tmp\n\t}\n\n\treturn input, nil\n}\n\n\/\/ build parameter for slack\nfunc buildSlackParameter(d *schema.ResourceData) (*mackerel.Channel, error) {\n\tinput := &mackerel.Channel{\n\t\tName: d.Get(\"name\").(string),\n\t\tType: d.Get(\"type\").(string),\n\t\tURL:  d.Get(\"url\").(string),\n\t}\n\n\tif v, ok := d.Get(\"enabled_graph_image\").(bool); ok {\n\t\tinput.EnabledGraphImage = &v\n\t}\n\n\tif v, ok := d.GetOk(\"mentions\"); ok {\n\t\t\/\/ Convert from schema.TypeMap to mackerel.Mentions\n\t\tmentionJSON, err := json.Marshal(v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar mentions mackerel.Mentions\n\t\terr = json.Unmarshal(mentionJSON, &mentions)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinput.Mentions = mentions\n\t}\n\n\tif v, ok := d.GetOk(\"events\"); ok {\n\t\ttmp := expandStringList(v.([]interface{}))\n\t\terr := validateChannelEvent(tmp, []string{\"alert\", \"alertGroup\", \"hostStatus\", \"hostRegister\", \"hostRetire\", \"monitor\"})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinput.Events = &tmp\n\t}\n\n\treturn input, nil\n}\n\n\/\/ build parameter for webhook\nfunc buildWebhookParameter(d *schema.ResourceData) (*mackerel.Channel, error) {\n\tinput := &mackerel.Channel{\n\t\tName: d.Get(\"name\").(string),\n\t\tType: d.Get(\"type\").(string),\n\t\tURL:  d.Get(\"url\").(string),\n\t}\n\n\tif v, ok := d.Get(\"enabled_graph_image\").(bool); ok {\n\t\tinput.EnabledGraphImage = &v\n\t}\n\n\tif v, ok := d.GetOk(\"events\"); ok {\n\t\ttmp := expandStringList(v.([]interface{}))\n\t\terr := validateChannelEvent(tmp, []string{\"alert\", \"alertGroup\", \"hostStatus\", \"hostRegister\", \"hostRetire\", \"monitor\"})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tinput.Events = &tmp\n\t}\n\n\treturn input, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package awsdriver\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"time\"\n\n\t\"github.com\/wallix\/awless\/logger\"\n\t\"github.com\/wallix\/awless\/template\"\n\t\"github.com\/wallix\/awless\/template\/driver\"\n)\n\nfunc AWSLookupDefinitions(key string) (t template.Definition, ok bool) {\n\tt, ok = AWSTemplatesDefinitions[key]\n\treturn\n}\n\ntype driverCall struct {\n\td       driver.Driver\n\tfn      interface{}\n\tlogger  *logger.Logger\n\tdesc    string\n\tsetters []setter\n}\n\nfunc (dc *driverCall) execute(input interface{}) (output interface{}, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\toutput = nil\n\t\t\terr = fmt.Errorf(\"%s\", e)\n\t\t}\n\t}()\n\n\tfor _, s := range dc.setters {\n\t\tif err = s.set(input); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tfnVal := reflect.ValueOf(dc.fn)\n\tvalues := []reflect.Value{reflect.ValueOf(input)}\n\n\tstart := time.Now()\n\tresults := fnVal.Call(values)\n\n\tif err, ok := results[1].Interface().(error); ok && err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: %s\", dc.desc, err)\n\t}\n\n\tdc.logger.ExtraVerbosef(\"%s call took %s\", dc.desc, time.Since(start))\n\tdc.logger.Verbosef(\"%s done\", dc.desc)\n\n\toutput = results[0].Interface()\n\n\treturn\n}\n<commit_msg>Define utility default AWS template env<commit_after>package awsdriver\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"time\"\n\n\t\"github.com\/wallix\/awless\/logger\"\n\t\"github.com\/wallix\/awless\/template\"\n\t\"github.com\/wallix\/awless\/template\/driver\"\n)\n\nfunc DefaultTemplateEnv() *template.Env {\n\tenv := template.NewEnv()\n\tenv.DefLookupFunc = AWSLookupDefinitions\n\treturn env\n}\n\nfunc AWSLookupDefinitions(key string) (t template.Definition, ok bool) {\n\tt, ok = AWSTemplatesDefinitions[key]\n\treturn\n}\n\ntype driverCall struct {\n\td       driver.Driver\n\tfn      interface{}\n\tlogger  *logger.Logger\n\tdesc    string\n\tsetters []setter\n}\n\nfunc (dc *driverCall) execute(input interface{}) (output interface{}, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\toutput = nil\n\t\t\terr = fmt.Errorf(\"%s\", e)\n\t\t}\n\t}()\n\n\tfor _, s := range dc.setters {\n\t\tif err = s.set(input); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tfnVal := reflect.ValueOf(dc.fn)\n\tvalues := []reflect.Value{reflect.ValueOf(input)}\n\n\tstart := time.Now()\n\tresults := fnVal.Call(values)\n\n\tif err, ok := results[1].Interface().(error); ok && err != nil {\n\t\treturn nil, fmt.Errorf(\"%s: %s\", dc.desc, err)\n\t}\n\n\tdc.logger.ExtraVerbosef(\"%s call took %s\", dc.desc, time.Since(start))\n\tdc.logger.Verbosef(\"%s done\", dc.desc)\n\n\toutput = results[0].Interface()\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"net\/http\"\n\t\"time\"\n)\n\n\/\/ HomeHandler renders both loggedin and loggedout page for user.\n\/\/ When user is loggedin, we send some data with payload so the\n\/\/ client doesn't need to fetch them after the page loads.\nfunc HomeHandler(w http.ResponseWriter, r *http.Request) {\n\tuserInfo, err := fetchUserInfo(w, r)\n\tif err != nil {\n\t\twriteLoggedOutHomeToResp(w)\n\t\treturn\n\t}\n\n\tonItem := make(chan Item, 0)   \/\/ individual prefetched items come here\n\tonDone := make(chan bool, 1)   \/\/ signals when done prefetching items\n\tonError := make(chan error, 1) \/\/ when error prefetching, return right away\n\n\toutputter := &Outputter{OnItem: onItem, OnError: onError}\n\n\tuser := NewLoggedInUser()\n\tuser.Set(\"Group\", kodingGroup)\n\tuser.Set(\"Username\", userInfo.Username)\n\tuser.Set(\"SessionId\", userInfo.ClientId)\n\tuser.Set(\"Impersonating\", userInfo.Impersonating)\n\n\tvar collectItemCount = 3\n\n\t\/\/ on new register, there's a race condition where SocialApiId\n\t\/\/ isn't sometimes set; in that case don't prefetch socialdata\n\t\/\/ since it'll return empty\n\tif !isSocialIdEmpty(userInfo.SocialApiId) {\n\t\tcollectItemCount = 4\n\t\tgo fetchSocial(userInfo.SocialApiId, outputter)\n\t}\n\n\t\/\/ the goroutines below (and maybe one above) will work in parallel\n\t\/\/ and send results\n\tgo collectItems(user, onItem, onDone, collectItemCount)\n\n\tgo sendAccount(userInfo.Account, outputter)\n\tgo fetchMachines(userInfo.UserId, outputter)\n\tgo fetchWorkspaces(userInfo.AccountId, outputter)\n\n\t\/\/ return in 750ms regardless and let client get what it wants\n\ttimeout := time.NewTimer(time.Millisecond * 750)\n\n\tselect {\n\tcase <-onError:\n\t\twriteLoggedOutHomeToResp(w)\n\tcase <-timeout.C:\n\t\twriteLoggedInHomeToResp(w, user)\n\tcase <-onDone:\n\t\twriteLoggedInHomeToResp(w, user)\n\t}\n}\n\nfunc collectItems(resp *LoggedInUser, onItem <-chan Item, onDone chan<- bool, max int) {\n\tfor i := 1; i <= max; i++ {\n\t\titem := <-onItem\n\t\tresp.Set(item.Name, item.Data)\n\t}\n\n\tonDone <- true\n}\n\nfunc isSocialIdEmpty(id string) bool {\n\treturn id == \"\"\n}\n<commit_msg>go-webserver: comments, formatting fixes<commit_after>package main\n\nimport (\n\t\"net\/http\"\n\t\"time\"\n)\n\n\/\/ HomeHandler renders both loggedin and loggedout page for user.\n\/\/ When user is loggedin, we send some extra data with the payload\n\/\/ so the client doesn't need to fetch them after the page loads.\nfunc HomeHandler(w http.ResponseWriter, r *http.Request) {\n\tuserInfo, err := fetchUserInfo(w, r)\n\tif err != nil {\n\t\twriteLoggedOutHomeToResp(w)\n\t\treturn\n\t}\n\n\tonItem := make(chan Item, 0)   \/\/ individual prefetched items come here\n\tonDone := make(chan bool, 1)   \/\/ signals when done prefetching items\n\tonError := make(chan error, 1) \/\/ when there's an error, return right away\n\n\tcollectItemCount := 3\n\toutputter := &Outputter{OnItem: onItem, OnError: onError}\n\n\t\/\/ on new register, there's a race condition where SocialApiId\n\t\/\/ isn't sometimes set; in that case don't prefetch socialdata\n\t\/\/ since it'll return empty\n\tif !isSocialIdEmpty(userInfo.SocialApiId) {\n\t\tcollectItemCount = 4\n\t\tgo fetchSocial(userInfo.SocialApiId, outputter)\n\t}\n\n\tuser := NewLoggedInUser()\n\tuser.Set(\"Group\", kodingGroup)\n\tuser.Set(\"Username\", userInfo.Username)\n\tuser.Set(\"SessionId\", userInfo.ClientId)\n\tuser.Set(\"Impersonating\", userInfo.Impersonating)\n\n\t\/\/ the goroutines below (and maybe one above) will work in parallel\n\t\/\/ and send results\n\tgo collectItems(user, onItem, onDone, collectItemCount)\n\n\tgo sendAccount(userInfo.Account, outputter)\n\tgo fetchMachines(userInfo.UserId, outputter)\n\tgo fetchWorkspaces(userInfo.AccountId, outputter)\n\n\t\/\/ return in 750ms regardless and let client get what it wants\n\ttimeout := time.NewTimer(time.Millisecond * 750)\n\n\tselect {\n\tcase <-onError:\n\t\twriteLoggedOutHomeToResp(w)\n\tcase <-timeout.C:\n\t\twriteLoggedInHomeToResp(w, user)\n\tcase <-onDone:\n\t\twriteLoggedInHomeToResp(w, user)\n\t}\n}\n\nfunc collectItems(resp *LoggedInUser, onItem <-chan Item, onDone chan<- bool, max int) {\n\tfor i := 1; i <= max; i++ {\n\t\titem := <-onItem\n\t\tresp.Set(item.Name, item.Data)\n\t}\n\n\tonDone <- true\n}\n\nfunc isSocialIdEmpty(id string) bool {\n\treturn id == \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"github.com\/kopia\/kopia\/repo\"\n\t\"github.com\/kopia\/kopia\/repo\/blob\"\n\t\"github.com\/kopia\/kopia\/repo\/content\"\n\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\nvar (\n\tconnectCommand                = repositoryCommands.Command(\"connect\", \"Connect to a repository.\")\n\tconnectPersistCredentials     bool\n\tconnectCacheDirectory         string\n\tconnectMaxCacheSizeMB         int64\n\tconnectMaxMetadataCacheSizeMB int64\n\tconnectMaxListCacheDuration   time.Duration\n\tconnectHostname               string\n\tconnectUsername               string\n\tconnectCheckForUpdates        bool\n)\n\nfunc setupConnectOptions(cmd *kingpin.CmdClause) {\n\t\/\/ Set up flags shared between 'create' and 'connect'. Note that because those flags are used by both command\n\t\/\/ we must use *Var() methods, otherwise one of the commands would always get default flag values.\n\tcmd.Flag(\"persist-credentials\", \"Persist credentials\").Default(\"true\").BoolVar(&connectPersistCredentials)\n\tcmd.Flag(\"cache-directory\", \"Cache directory\").PlaceHolder(\"PATH\").StringVar(&connectCacheDirectory)\n\tcmd.Flag(\"content-cache-size-mb\", \"Size of local content cache\").PlaceHolder(\"MB\").Default(\"5000\").Int64Var(&connectMaxCacheSizeMB)\n\tcmd.Flag(\"metadata-cache-size-mb\", \"Size of local metadata cache\").PlaceHolder(\"MB\").Default(\"500\").Int64Var(&connectMaxMetadataCacheSizeMB)\n\tcmd.Flag(\"max-list-cache-duration\", \"Duration of index cache\").Default(\"600s\").Hidden().DurationVar(&connectMaxListCacheDuration)\n\tcmd.Flag(\"override-hostname\", \"Override hostname used by this repository connection\").Hidden().StringVar(&connectHostname)\n\tcmd.Flag(\"override-username\", \"Override username used by this repository connection\").Hidden().StringVar(&connectUsername)\n\tcmd.Flag(\"check-for-updates\", \"Periodically check for Kopia updates on GitHub\").Default(\"true\").Envar(checkForUpdatesEnvar).BoolVar(&connectCheckForUpdates)\n}\n\nfunc connectOptions() *repo.ConnectOptions {\n\treturn &repo.ConnectOptions{\n\t\tPersistCredentials: connectPersistCredentials,\n\t\tCachingOptions: content.CachingOptions{\n\t\t\tCacheDirectory:          connectCacheDirectory,\n\t\t\tMaxCacheSizeBytes:       connectMaxCacheSizeMB << 20, \/\/nolint:gomnd\n\t\t\tMaxListCacheDurationSec: int(connectMaxListCacheDuration.Seconds()),\n\t\t},\n\t\tHostnameOverride: connectHostname,\n\t\tUsernameOverride: connectUsername,\n\t}\n}\n\nfunc init() {\n\tsetupConnectOptions(connectCommand)\n}\n\nfunc runConnectCommandWithStorage(ctx context.Context, st blob.Storage) error {\n\tpassword, err := getPasswordFromFlags(ctx, false, false)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting password\")\n\t}\n\n\treturn runConnectCommandWithStorageAndPassword(ctx, st, password)\n}\n\nfunc runConnectCommandWithStorageAndPassword(ctx context.Context, st blob.Storage, password string) error {\n\tconfigFile := repositoryConfigFileName()\n\tif err := repo.Connect(ctx, configFile, st, password, connectOptions()); err != nil {\n\t\treturn err\n\t}\n\n\tprintStderr(\"Connected to repository.\\n\")\n\tmaybeInitializeUpdateCheck(ctx)\n\n\treturn nil\n}\n<commit_msg>cli: fixed metadata cache size on connect\/create<commit_after>package cli\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"github.com\/kopia\/kopia\/repo\"\n\t\"github.com\/kopia\/kopia\/repo\/blob\"\n\t\"github.com\/kopia\/kopia\/repo\/content\"\n\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\nvar (\n\tconnectCommand                = repositoryCommands.Command(\"connect\", \"Connect to a repository.\")\n\tconnectPersistCredentials     bool\n\tconnectCacheDirectory         string\n\tconnectMaxCacheSizeMB         int64\n\tconnectMaxMetadataCacheSizeMB int64\n\tconnectMaxListCacheDuration   time.Duration\n\tconnectHostname               string\n\tconnectUsername               string\n\tconnectCheckForUpdates        bool\n)\n\nfunc setupConnectOptions(cmd *kingpin.CmdClause) {\n\t\/\/ Set up flags shared between 'create' and 'connect'. Note that because those flags are used by both command\n\t\/\/ we must use *Var() methods, otherwise one of the commands would always get default flag values.\n\tcmd.Flag(\"persist-credentials\", \"Persist credentials\").Default(\"true\").BoolVar(&connectPersistCredentials)\n\tcmd.Flag(\"cache-directory\", \"Cache directory\").PlaceHolder(\"PATH\").StringVar(&connectCacheDirectory)\n\tcmd.Flag(\"content-cache-size-mb\", \"Size of local content cache\").PlaceHolder(\"MB\").Default(\"5000\").Int64Var(&connectMaxCacheSizeMB)\n\tcmd.Flag(\"metadata-cache-size-mb\", \"Size of local metadata cache\").PlaceHolder(\"MB\").Default(\"5000\").Int64Var(&connectMaxMetadataCacheSizeMB)\n\tcmd.Flag(\"max-list-cache-duration\", \"Duration of index cache\").Default(\"600s\").Hidden().DurationVar(&connectMaxListCacheDuration)\n\tcmd.Flag(\"override-hostname\", \"Override hostname used by this repository connection\").Hidden().StringVar(&connectHostname)\n\tcmd.Flag(\"override-username\", \"Override username used by this repository connection\").Hidden().StringVar(&connectUsername)\n\tcmd.Flag(\"check-for-updates\", \"Periodically check for Kopia updates on GitHub\").Default(\"true\").Envar(checkForUpdatesEnvar).BoolVar(&connectCheckForUpdates)\n}\n\nfunc connectOptions() *repo.ConnectOptions {\n\treturn &repo.ConnectOptions{\n\t\tPersistCredentials: connectPersistCredentials,\n\t\tCachingOptions: content.CachingOptions{\n\t\t\tCacheDirectory:            connectCacheDirectory,\n\t\t\tMaxCacheSizeBytes:         connectMaxCacheSizeMB << 20,         \/\/nolint:gomnd\n\t\t\tMaxMetadataCacheSizeBytes: connectMaxMetadataCacheSizeMB << 20, \/\/nolint:gomnd\n\t\t\tMaxListCacheDurationSec:   int(connectMaxListCacheDuration.Seconds()),\n\t\t},\n\t\tHostnameOverride: connectHostname,\n\t\tUsernameOverride: connectUsername,\n\t}\n}\n\nfunc init() {\n\tsetupConnectOptions(connectCommand)\n}\n\nfunc runConnectCommandWithStorage(ctx context.Context, st blob.Storage) error {\n\tpassword, err := getPasswordFromFlags(ctx, false, false)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting password\")\n\t}\n\n\treturn runConnectCommandWithStorageAndPassword(ctx, st, password)\n}\n\nfunc runConnectCommandWithStorageAndPassword(ctx context.Context, st blob.Storage, password string) error {\n\tconfigFile := repositoryConfigFileName()\n\tif err := repo.Connect(ctx, configFile, st, password, connectOptions()); err != nil {\n\t\treturn err\n\t}\n\n\tprintStderr(\"Connected to repository.\\n\")\n\tmaybeInitializeUpdateCheck(ctx)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package backend\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\/credentials\"\n\t\"github.com\/lib\/pq\"\n\t\"github.com\/twitchscience\/aws_utils\/logger\"\n\t\"github.com\/twitchscience\/rs_ingester\/redshift\"\n\t\"github.com\/twitchscience\/scoop_protocol\/scoop_protocol\"\n)\n\nvar (\n\ttransformerTypeMap = map[string]string{\n\t\t\"ipCity\":       \"varchar(64)\",\n\t\t\"ipCountry\":    \"varchar(2)\",\n\t\t\"ipRegion\":     \"varchar(64)\",\n\t\t\"ipAsn\":        \"varchar(128)\",\n\t\t\"ipAsnInteger\": \"int\",\n\t\t\"f@timestamp\":  \"datetime\",\n\t}\n)\n\n\/\/RedshiftBackend is the struct that holds the RSConnection pool and where backend operations are done from\ntype RedshiftBackend struct {\n\tconnection  *redshift.RSConnection\n\tcredentials *credentials.Credentials\n\ttableLocks  map[string]*sync.Mutex\n}\n\nfunc buildTableLocks(conn *redshift.RSConnection) (map[string]*sync.Mutex, error) {\n\tlocks := make(map[string]*sync.Mutex)\n\tcurrentTableVersions, err := getTableVersions(conn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor table := range currentTableVersions {\n\t\tlocks[table] = &sync.Mutex{}\n\t\tlogger.Info(\"Created %s Lock\", table)\n\t}\n\treturn locks, nil\n}\n\n\/\/BuildRedshiftBackend builds a new redshift backend by also creating a new rsConnection\nfunc BuildRedshiftBackend(credentials *credentials.Credentials, poolSize int, rsURL string) (*RedshiftBackend, error) {\n\tconn, err := redshift.BuildRSConnection(rsURL, poolSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := 0; i < 5; i++ {\n\t\tgo conn.Listen()\n\t}\n\ttableLocks, err := buildTableLocks(conn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RedshiftBackend{\n\t\tconnection:  conn,\n\t\tcredentials: credentials,\n\t\ttableLocks:  tableLocks,\n\t}, nil\n}\n\n\/\/HealthCheck makes sure that that redshift is reachable\nfunc (r *RedshiftBackend) HealthCheck() error {\n\terr := r.connection.Conn.Ping()\n\treturn err\n}\n\n\/\/Create makes a TableCreateRequest and returns the transaction\nfunc (r *RedshiftBackend) Create(cfg *scoop_protocol.Config) error {\n\tcreateTable := &redshift.TableCreateRequest{\n\t\tBuiltOn: time.Now(),\n\t\tTable:   cfg,\n\t}\n\tcreateComment := &redshift.CreateTableCommentRequest{\n\t\tBuiltOn: time.Now(),\n\t\tConfig:  cfg,\n\t}\n\treturn r.connection.ExecInTransaction(createTable, createComment)\n}\n\n\/\/Copy makes a RowCopyRequest and executes the request\nfunc (r *RedshiftBackend) Copy(rc *scoop_protocol.RowCopyRequest) error {\n\treturn r.connection.ExecFnInTransaction(redshift.RowCopyRequest{\n\t\tBuiltOn:     time.Now(),\n\t\tName:        rc.TableName,\n\t\tKey:         rc.KeyName,\n\t\tCredentials: redshift.CopyCredentials(r.credentials),\n\t}.TxExec)\n}\n\n\/\/ManifestCopy makes a ManifestRowCopyRequest and returns the function that executes the request\nfunc (r *RedshiftBackend) ManifestCopy(rc *scoop_protocol.ManifestRowCopyRequest) error {\n\tlock, exist := r.tableLocks[rc.TableName]\n\tif !exist {\n\t\treturn fmt.Errorf(\"Lock for %s did not exist\", rc.TableName)\n\t}\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\treturn r.connection.ExecFnInTransaction(redshift.ManifestRowCopyRequest{\n\t\tBuiltOn:     time.Now(),\n\t\tName:        rc.TableName,\n\t\tManifestURL: rc.ManifestURL,\n\t\tCredentials: redshift.CopyCredentials(r.credentials),\n\t}.TxExec)\n}\n\n\/\/LoadCheck makes a LoadCheckRequest and returns the response of the load check\nfunc (r *RedshiftBackend) LoadCheck(req *scoop_protocol.LoadCheckRequest) (*scoop_protocol.LoadCheckResponse, error) {\n\tresp := &scoop_protocol.LoadCheckResponse{ManifestURL: req.ManifestURL}\n\terr := r.connection.ExecFnInTransaction(func(t *sql.Tx) (err error) {\n\t\tresp.LoadStatus, err = redshift.CheckLoadStatus(t, req.ManifestURL)\n\t\treturn\n\t})\n\treturn resp, err\n}\n\nfunc performColumnCheck(current, additions *scoop_protocol.Config) error {\n\tfor _, col := range current.Columns {\n\t\tfor _, add := range additions.Columns {\n\t\t\tif col.OutboundName == add.OutboundName {\n\t\t\t\treturn fmt.Errorf(\"Event: %s already has Property: %s\", current.EventName, col.OutboundName)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/Update runs the update table operation on redshift\nfunc (r *RedshiftBackend) Update(additions *scoop_protocol.Config) error {\n\treturn r.connection.ExecFnInTransaction(func(tx *sql.Tx) error {\n\t\tcurrentCfg, err := r.Schema(additions.EventName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := performColumnCheck(currentCfg, additions); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ preflight checks good, now alter table\n\t\tupdateTable := &redshift.TableAlterRequest{\n\t\t\tTableName: additions.EventName,\n\t\t\tAdditions: additions.Columns,\n\t\t}\n\t\tfor _, query := range updateTable.ProduceQueries() {\n\t\t\tif _, err := tx.Exec(query); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t\/\/ update comment\n\t\tcurrentCfg.Columns = append(currentCfg.Columns, additions.Columns...)\n\t\tcreateComment := &redshift.CreateTableCommentRequest{\n\t\t\tConfig: currentCfg,\n\t\t}\n\t\tif _, err := tx.Exec(createComment.GetExec()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n}\n\n\/\/Query allows for the execution of an arbitrary QueryRequest\nfunc (r *RedshiftBackend) Query(req *redshift.QueryRequest) ([]byte, error) {\n\treturn req.Exec(r.connection)\n}\n\n\/\/AllSchemas returns a list of all table schemas in the logs schema in redshift\nfunc (r *RedshiftBackend) AllSchemas() ([]scoop_protocol.Config, error) {\n\treq := &redshift.TableListRequest{\n\t\tBuiltOn: time.Now(),\n\t\tSchema:  \"logs\",\n\t}\n\ttables, err := req.Query(r.connection)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tschemas := make([]scoop_protocol.Config, len(tables))\n\tfor i, t := range tables {\n\t\ts, err := r.Schema(t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tschemas[i] = *s\n\t}\n\treturn schemas, nil\n}\n\n\/\/Schema returns a specific table schema in the logs schema in redshift\nfunc (r *RedshiftBackend) Schema(event string) (*scoop_protocol.Config, error) {\n\treq := &redshift.ReadTableCommentRequest{\n\t\tBuiltOn: time.Now(),\n\t\tName:    event,\n\t\tSchema:  \"logs\",\n\t}\n\tcomment, err := req.Query(r.connection)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"Error reading comment on table\")\n\t\treturn nil, err\n\t}\n\tvar cfg scoop_protocol.Config\n\terr = json.Unmarshal([]byte(comment), &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cfg, nil\n}\n\nfunc getTableVersions(conn *redshift.RSConnection) (map[string]int, error) {\n\tversions := make(map[string]int)\n\trows, err := conn.Conn.Query(`SELECT name, MAX(version) FROM infra.table_version GROUP BY name;`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error SELECTing the table versions from ace's infra.table_version: %v\", err)\n\t}\n\tdefer func() {\n\t\terr = rows.Close()\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"Error closing rows\")\n\t\t}\n\t}()\n\tfor rows.Next() {\n\t\tvar table string\n\t\tvar version int\n\t\tif err := rows.Scan(&table, &version); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tversions[table] = version\n\t}\n\treturn versions, nil\n}\n\n\/\/ TableVersions returns the event tables with version numbers\nfunc (r *RedshiftBackend) TableVersions() (map[string]int, error) {\n\treturn getTableVersions(r.connection)\n}\n\n\/\/NewUser returns a function that executes a new uesr operation on redshift\nfunc (r *RedshiftBackend) NewUser(user, pw string) error {\n\treturn r.connection.ExecFnInTransaction((&redshift.NewUser{\n\t\tUser:     user,\n\t\tPassword: pw,\n\t}).TxExec)\n}\n\n\/\/UpdatePassword returns a function that executes an UpdatePassword operation on redshift\nfunc (r *RedshiftBackend) UpdatePassword(user, pw string) error {\n\treturn r.connection.ExecFnInTransaction((&redshift.UpdatePassword{\n\t\tUser:     user,\n\t\tPassword: pw,\n\t}).TxExec)\n}\n\n\/\/MakeSuperuser returns a function that executes a make super user operation on redshift\nfunc (r *RedshiftBackend) MakeSuperuser(user string) error {\n\treturn r.connection.ExecFnInTransaction((&redshift.MakeSuperuser{\n\t\tUser: user,\n\t}).TxExec)\n}\n\n\/\/UpdateGroup returns a function that executes an operation that updates a group to add a new user, on redshift\nfunc (r *RedshiftBackend) UpdateGroup(user, group string) error {\n\treturn r.connection.ExecFnInTransaction((&redshift.UpdateGroup{\n\t\tUser:  user,\n\t\tGroup: group,\n\t}).TxExec)\n}\n\n\/\/EnforcePermissions returns a function that repairs permissions on all tables on redshift\nfunc (r *RedshiftBackend) EnforcePermissions() error {\n\treturn r.connection.ExecFnInTransaction((&redshift.EnforcePerms{}).TxExec)\n}\n\ntype migrationStep scoop_protocol.Operation\n\nfunc parseFunctionalType(s string) (string, bool) {\n\tif len(s) > 0 && s[0] == 'f' && s[1] == '@' {\n\t\ttransformerType, ok := transformerTypeMap[s[:strings.LastIndex(s, \"@\")]]\n\t\treturn transformerType, ok\n\t}\n\treturn \"\", false\n}\n\nfunc (m *migrationStep) getCreationForm() string {\n\ttranType, isTranslated := transformerTypeMap[m.ColumnType]\n\tfuncType, isFunc := parseFunctionalType(m.ColumnType)\n\n\tvar colType string\n\tif isTranslated {\n\t\tcolType = tranType\n\t} else if isFunc {\n\t\tcolType = funcType\n\t} else {\n\t\tcolType = m.ColumnType\n\t}\n\n\tmaybeColOpts := \"\"\n\tif len(m.ColumnOptions) > 1 {\n\t\tmaybeColOpts = m.ColumnOptions\n\t}\n\n\treturn fmt.Sprintf(\"%s %s%s\", pq.QuoteIdentifier(m.Outbound), colType, maybeColOpts)\n}\n\n\/\/ expectVersion checks to see if the version in infra.table_version is what was\n\/\/ given. Special case for version=-1 means you expect table doesn't exist\nfunc expectVersion(tx *sql.Tx, table string, version int) error {\n\tvar readVersion int\n\terr := tx.QueryRow(`SELECT MAX(version) FROM infra.table_version WHERE name = $1 GROUP BY name;`, table).Scan(&readVersion)\n\tswitch {\n\tcase err == sql.ErrNoRows:\n\t\tif version == -1 {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"Expected version %d for table %s, but table doesn't exist in infra.table_version.\", version, table)\n\tcase err != nil:\n\t\treturn fmt.Errorf(\"Error finding table version from ace: %v\", err)\n\tdefault:\n\t\tif readVersion != version {\n\t\t\treturn fmt.Errorf(\"Expected version %d for table %s, but got version %d in infra.table_version\", version, table, readVersion)\n\t\t}\n\t\treturn nil\n\t}\n}\n\n\/\/ApplyOperations applies operations to a table and updates the table's version\nfunc (r *RedshiftBackend) ApplyOperations(table string, ops []scoop_protocol.Operation, targetVersion int) error {\n\tlock, exist := r.tableLocks[table]\n\tif !exist {\n\t\treturn fmt.Errorf(\"Lock for %s did not exist\", table)\n\t}\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\treturn r.connection.ExecFnInTransaction(func(tx *sql.Tx) error {\n\t\terr := expectVersion(tx, table, targetVersion-1)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, op := range ops {\n\t\t\tmStep := migrationStep(op)\n\t\t\tswitch mStep.Action {\n\t\t\tcase \"add\":\n\t\t\t\tquery := fmt.Sprintf(\"ALTER TABLE %s ADD COLUMN %s\", pq.QuoteIdentifier(table), mStep.getCreationForm())\n\t\t\t\t_, err = tx.Exec(query)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tcase \"delete\":\n\t\t\t\tquery := fmt.Sprintf(\"ALTER TABLE %s DROP COLUMN %s\", pq.QuoteIdentifier(table), pq.QuoteIdentifier(mStep.Outbound))\n\t\t\t\t_, err = tx.Exec(query)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Unknown operation action: %s\", mStep.Action)\n\t\t\t}\n\t\t}\n\t\tquery := fmt.Sprintf(\"INSERT INTO infra.table_version (name, version, ts) VALUES ($1, $2, GETDATE())\")\n\t\t_, err = tx.Exec(query, table, targetVersion)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error updating table_version in ace: %v\", err)\n\t\t}\n\t\treturn nil\n\t})\n}\n\ntype newTable []scoop_protocol.Operation\n\n\/\/buildNewTable creates a newTable from a list of Operations and checks that all the operations\n\/\/are add column operations\nfunc buildNewTable(ops []scoop_protocol.Operation) (newTable, error) {\n\tfor _, op := range ops {\n\t\tif op.Action != \"add\" {\n\t\t\treturn nil, fmt.Errorf(\"newTable must be made out of action=add operations, received action=%s\", op.Action)\n\t\t}\n\t}\n\treturn newTable(ops), nil\n}\n\nfunc (n *newTable) getColumnCreationString() string {\n\tout := bytes.NewBuffer(make([]byte, 0, 256))\n\t_, _ = out.WriteRune('(') \/\/ WriteRune and WriteString error always nil\n\tfor i, op := range *n {\n\t\tstep := migrationStep(op)\n\t\t_, _ = out.WriteString(step.getCreationForm())\n\t\tif i+1 != len(*n) {\n\t\t\t_, _ = out.WriteRune(',')\n\t\t}\n\t}\n\t_, _ = out.WriteRune(')')\n\treturn out.String()\n}\n\n\/\/CreateTable creates a new table at logs.`table` with the columns in ops\nfunc (r *RedshiftBackend) CreateTable(table string, ops []scoop_protocol.Operation) error {\n\tnewTable, err := buildNewTable(ops)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn r.connection.ExecFnInTransaction(func(tx *sql.Tx) error {\n\t\terr := expectVersion(tx, table, -1)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tquery := fmt.Sprintf(`CREATE TABLE %s%s;`, pq.QuoteIdentifier(table), newTable.getColumnCreationString())\n\t\t_, err = tx.Exec(query)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error CREATEing TABLE %s: %v\", table, err)\n\t\t}\n\t\tr.tableLocks[table] = &sync.Mutex{}\n\t\tquery = \"INSERT INTO infra.table_version (name, version, ts) VALUES ($1, 0, GETDATE())\"\n\t\t_, err = tx.Exec(query, table)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error updating table_version in ace: %v\", err)\n\t\t}\n\t\treturn nil\n\t})\n}\n<commit_msg>Add cascade<commit_after>package backend\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\/credentials\"\n\t\"github.com\/lib\/pq\"\n\t\"github.com\/twitchscience\/aws_utils\/logger\"\n\t\"github.com\/twitchscience\/rs_ingester\/redshift\"\n\t\"github.com\/twitchscience\/scoop_protocol\/scoop_protocol\"\n)\n\nvar (\n\ttransformerTypeMap = map[string]string{\n\t\t\"ipCity\":       \"varchar(64)\",\n\t\t\"ipCountry\":    \"varchar(2)\",\n\t\t\"ipRegion\":     \"varchar(64)\",\n\t\t\"ipAsn\":        \"varchar(128)\",\n\t\t\"ipAsnInteger\": \"int\",\n\t\t\"f@timestamp\":  \"datetime\",\n\t}\n)\n\n\/\/RedshiftBackend is the struct that holds the RSConnection pool and where backend operations are done from\ntype RedshiftBackend struct {\n\tconnection  *redshift.RSConnection\n\tcredentials *credentials.Credentials\n\ttableLocks  map[string]*sync.Mutex\n}\n\nfunc buildTableLocks(conn *redshift.RSConnection) (map[string]*sync.Mutex, error) {\n\tlocks := make(map[string]*sync.Mutex)\n\tcurrentTableVersions, err := getTableVersions(conn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor table := range currentTableVersions {\n\t\tlocks[table] = &sync.Mutex{}\n\t\tlogger.Info(\"Created %s Lock\", table)\n\t}\n\treturn locks, nil\n}\n\n\/\/BuildRedshiftBackend builds a new redshift backend by also creating a new rsConnection\nfunc BuildRedshiftBackend(credentials *credentials.Credentials, poolSize int, rsURL string) (*RedshiftBackend, error) {\n\tconn, err := redshift.BuildRSConnection(rsURL, poolSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i := 0; i < 5; i++ {\n\t\tgo conn.Listen()\n\t}\n\ttableLocks, err := buildTableLocks(conn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &RedshiftBackend{\n\t\tconnection:  conn,\n\t\tcredentials: credentials,\n\t\ttableLocks:  tableLocks,\n\t}, nil\n}\n\n\/\/HealthCheck makes sure that that redshift is reachable\nfunc (r *RedshiftBackend) HealthCheck() error {\n\terr := r.connection.Conn.Ping()\n\treturn err\n}\n\n\/\/Create makes a TableCreateRequest and returns the transaction\nfunc (r *RedshiftBackend) Create(cfg *scoop_protocol.Config) error {\n\tcreateTable := &redshift.TableCreateRequest{\n\t\tBuiltOn: time.Now(),\n\t\tTable:   cfg,\n\t}\n\tcreateComment := &redshift.CreateTableCommentRequest{\n\t\tBuiltOn: time.Now(),\n\t\tConfig:  cfg,\n\t}\n\treturn r.connection.ExecInTransaction(createTable, createComment)\n}\n\n\/\/Copy makes a RowCopyRequest and executes the request\nfunc (r *RedshiftBackend) Copy(rc *scoop_protocol.RowCopyRequest) error {\n\treturn r.connection.ExecFnInTransaction(redshift.RowCopyRequest{\n\t\tBuiltOn:     time.Now(),\n\t\tName:        rc.TableName,\n\t\tKey:         rc.KeyName,\n\t\tCredentials: redshift.CopyCredentials(r.credentials),\n\t}.TxExec)\n}\n\n\/\/ManifestCopy makes a ManifestRowCopyRequest and returns the function that executes the request\nfunc (r *RedshiftBackend) ManifestCopy(rc *scoop_protocol.ManifestRowCopyRequest) error {\n\tlock, exist := r.tableLocks[rc.TableName]\n\tif !exist {\n\t\treturn fmt.Errorf(\"Lock for %s did not exist\", rc.TableName)\n\t}\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\treturn r.connection.ExecFnInTransaction(redshift.ManifestRowCopyRequest{\n\t\tBuiltOn:     time.Now(),\n\t\tName:        rc.TableName,\n\t\tManifestURL: rc.ManifestURL,\n\t\tCredentials: redshift.CopyCredentials(r.credentials),\n\t}.TxExec)\n}\n\n\/\/LoadCheck makes a LoadCheckRequest and returns the response of the load check\nfunc (r *RedshiftBackend) LoadCheck(req *scoop_protocol.LoadCheckRequest) (*scoop_protocol.LoadCheckResponse, error) {\n\tresp := &scoop_protocol.LoadCheckResponse{ManifestURL: req.ManifestURL}\n\terr := r.connection.ExecFnInTransaction(func(t *sql.Tx) (err error) {\n\t\tresp.LoadStatus, err = redshift.CheckLoadStatus(t, req.ManifestURL)\n\t\treturn\n\t})\n\treturn resp, err\n}\n\nfunc performColumnCheck(current, additions *scoop_protocol.Config) error {\n\tfor _, col := range current.Columns {\n\t\tfor _, add := range additions.Columns {\n\t\t\tif col.OutboundName == add.OutboundName {\n\t\t\t\treturn fmt.Errorf(\"Event: %s already has Property: %s\", current.EventName, col.OutboundName)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/Update runs the update table operation on redshift\nfunc (r *RedshiftBackend) Update(additions *scoop_protocol.Config) error {\n\treturn r.connection.ExecFnInTransaction(func(tx *sql.Tx) error {\n\t\tcurrentCfg, err := r.Schema(additions.EventName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := performColumnCheck(currentCfg, additions); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ preflight checks good, now alter table\n\t\tupdateTable := &redshift.TableAlterRequest{\n\t\t\tTableName: additions.EventName,\n\t\t\tAdditions: additions.Columns,\n\t\t}\n\t\tfor _, query := range updateTable.ProduceQueries() {\n\t\t\tif _, err := tx.Exec(query); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t\/\/ update comment\n\t\tcurrentCfg.Columns = append(currentCfg.Columns, additions.Columns...)\n\t\tcreateComment := &redshift.CreateTableCommentRequest{\n\t\t\tConfig: currentCfg,\n\t\t}\n\t\tif _, err := tx.Exec(createComment.GetExec()); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n}\n\n\/\/Query allows for the execution of an arbitrary QueryRequest\nfunc (r *RedshiftBackend) Query(req *redshift.QueryRequest) ([]byte, error) {\n\treturn req.Exec(r.connection)\n}\n\n\/\/AllSchemas returns a list of all table schemas in the logs schema in redshift\nfunc (r *RedshiftBackend) AllSchemas() ([]scoop_protocol.Config, error) {\n\treq := &redshift.TableListRequest{\n\t\tBuiltOn: time.Now(),\n\t\tSchema:  \"logs\",\n\t}\n\ttables, err := req.Query(r.connection)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tschemas := make([]scoop_protocol.Config, len(tables))\n\tfor i, t := range tables {\n\t\ts, err := r.Schema(t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tschemas[i] = *s\n\t}\n\treturn schemas, nil\n}\n\n\/\/Schema returns a specific table schema in the logs schema in redshift\nfunc (r *RedshiftBackend) Schema(event string) (*scoop_protocol.Config, error) {\n\treq := &redshift.ReadTableCommentRequest{\n\t\tBuiltOn: time.Now(),\n\t\tName:    event,\n\t\tSchema:  \"logs\",\n\t}\n\tcomment, err := req.Query(r.connection)\n\tif err != nil {\n\t\tlogger.WithError(err).Error(\"Error reading comment on table\")\n\t\treturn nil, err\n\t}\n\tvar cfg scoop_protocol.Config\n\terr = json.Unmarshal([]byte(comment), &cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cfg, nil\n}\n\nfunc getTableVersions(conn *redshift.RSConnection) (map[string]int, error) {\n\tversions := make(map[string]int)\n\trows, err := conn.Conn.Query(`SELECT name, MAX(version) FROM infra.table_version GROUP BY name;`)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error SELECTing the table versions from ace's infra.table_version: %v\", err)\n\t}\n\tdefer func() {\n\t\terr = rows.Close()\n\t\tif err != nil {\n\t\t\tlogger.WithError(err).Error(\"Error closing rows\")\n\t\t}\n\t}()\n\tfor rows.Next() {\n\t\tvar table string\n\t\tvar version int\n\t\tif err := rows.Scan(&table, &version); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tversions[table] = version\n\t}\n\treturn versions, nil\n}\n\n\/\/ TableVersions returns the event tables with version numbers\nfunc (r *RedshiftBackend) TableVersions() (map[string]int, error) {\n\treturn getTableVersions(r.connection)\n}\n\n\/\/NewUser returns a function that executes a new uesr operation on redshift\nfunc (r *RedshiftBackend) NewUser(user, pw string) error {\n\treturn r.connection.ExecFnInTransaction((&redshift.NewUser{\n\t\tUser:     user,\n\t\tPassword: pw,\n\t}).TxExec)\n}\n\n\/\/UpdatePassword returns a function that executes an UpdatePassword operation on redshift\nfunc (r *RedshiftBackend) UpdatePassword(user, pw string) error {\n\treturn r.connection.ExecFnInTransaction((&redshift.UpdatePassword{\n\t\tUser:     user,\n\t\tPassword: pw,\n\t}).TxExec)\n}\n\n\/\/MakeSuperuser returns a function that executes a make super user operation on redshift\nfunc (r *RedshiftBackend) MakeSuperuser(user string) error {\n\treturn r.connection.ExecFnInTransaction((&redshift.MakeSuperuser{\n\t\tUser: user,\n\t}).TxExec)\n}\n\n\/\/UpdateGroup returns a function that executes an operation that updates a group to add a new user, on redshift\nfunc (r *RedshiftBackend) UpdateGroup(user, group string) error {\n\treturn r.connection.ExecFnInTransaction((&redshift.UpdateGroup{\n\t\tUser:  user,\n\t\tGroup: group,\n\t}).TxExec)\n}\n\n\/\/EnforcePermissions returns a function that repairs permissions on all tables on redshift\nfunc (r *RedshiftBackend) EnforcePermissions() error {\n\treturn r.connection.ExecFnInTransaction((&redshift.EnforcePerms{}).TxExec)\n}\n\ntype migrationStep scoop_protocol.Operation\n\nfunc parseFunctionalType(s string) (string, bool) {\n\tif len(s) > 0 && s[0] == 'f' && s[1] == '@' {\n\t\ttransformerType, ok := transformerTypeMap[s[:strings.LastIndex(s, \"@\")]]\n\t\treturn transformerType, ok\n\t}\n\treturn \"\", false\n}\n\nfunc (m *migrationStep) getCreationForm() string {\n\ttranType, isTranslated := transformerTypeMap[m.ColumnType]\n\tfuncType, isFunc := parseFunctionalType(m.ColumnType)\n\n\tvar colType string\n\tif isTranslated {\n\t\tcolType = tranType\n\t} else if isFunc {\n\t\tcolType = funcType\n\t} else {\n\t\tcolType = m.ColumnType\n\t}\n\n\tmaybeColOpts := \"\"\n\tif len(m.ColumnOptions) > 1 {\n\t\tmaybeColOpts = m.ColumnOptions\n\t}\n\n\treturn fmt.Sprintf(\"%s %s%s\", pq.QuoteIdentifier(m.Outbound), colType, maybeColOpts)\n}\n\n\/\/ expectVersion checks to see if the version in infra.table_version is what was\n\/\/ given. Special case for version=-1 means you expect table doesn't exist\nfunc expectVersion(tx *sql.Tx, table string, version int) error {\n\tvar readVersion int\n\terr := tx.QueryRow(`SELECT MAX(version) FROM infra.table_version WHERE name = $1 GROUP BY name;`, table).Scan(&readVersion)\n\tswitch {\n\tcase err == sql.ErrNoRows:\n\t\tif version == -1 {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"Expected version %d for table %s, but table doesn't exist in infra.table_version.\", version, table)\n\tcase err != nil:\n\t\treturn fmt.Errorf(\"Error finding table version from ace: %v\", err)\n\tdefault:\n\t\tif readVersion != version {\n\t\t\treturn fmt.Errorf(\"Expected version %d for table %s, but got version %d in infra.table_version\", version, table, readVersion)\n\t\t}\n\t\treturn nil\n\t}\n}\n\n\/\/ApplyOperations applies operations to a table and updates the table's version\nfunc (r *RedshiftBackend) ApplyOperations(table string, ops []scoop_protocol.Operation, targetVersion int) error {\n\tlock, exist := r.tableLocks[table]\n\tif !exist {\n\t\treturn fmt.Errorf(\"Lock for %s did not exist\", table)\n\t}\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\treturn r.connection.ExecFnInTransaction(func(tx *sql.Tx) error {\n\t\terr := expectVersion(tx, table, targetVersion-1)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, op := range ops {\n\t\t\tmStep := migrationStep(op)\n\t\t\tswitch mStep.Action {\n\t\t\tcase \"add\":\n\t\t\t\tquery := fmt.Sprintf(\"ALTER TABLE %s ADD COLUMN %s\", pq.QuoteIdentifier(table), mStep.getCreationForm())\n\t\t\t\t_, err = tx.Exec(query)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tcase \"delete\":\n\t\t\t\tquery := fmt.Sprintf(\"ALTER TABLE %s DROP COLUMN %s CASCADE\", pq.QuoteIdentifier(table), pq.QuoteIdentifier(mStep.Outbound))\n\t\t\t\t_, err = tx.Exec(query)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Unknown operation action: %s\", mStep.Action)\n\t\t\t}\n\t\t}\n\t\tquery := fmt.Sprintf(\"INSERT INTO infra.table_version (name, version, ts) VALUES ($1, $2, GETDATE())\")\n\t\t_, err = tx.Exec(query, table, targetVersion)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error updating table_version in ace: %v\", err)\n\t\t}\n\t\treturn nil\n\t})\n}\n\ntype newTable []scoop_protocol.Operation\n\n\/\/buildNewTable creates a newTable from a list of Operations and checks that all the operations\n\/\/are add column operations\nfunc buildNewTable(ops []scoop_protocol.Operation) (newTable, error) {\n\tfor _, op := range ops {\n\t\tif op.Action != \"add\" {\n\t\t\treturn nil, fmt.Errorf(\"newTable must be made out of action=add operations, received action=%s\", op.Action)\n\t\t}\n\t}\n\treturn newTable(ops), nil\n}\n\nfunc (n *newTable) getColumnCreationString() string {\n\tout := bytes.NewBuffer(make([]byte, 0, 256))\n\t_, _ = out.WriteRune('(') \/\/ WriteRune and WriteString error always nil\n\tfor i, op := range *n {\n\t\tstep := migrationStep(op)\n\t\t_, _ = out.WriteString(step.getCreationForm())\n\t\tif i+1 != len(*n) {\n\t\t\t_, _ = out.WriteRune(',')\n\t\t}\n\t}\n\t_, _ = out.WriteRune(')')\n\treturn out.String()\n}\n\n\/\/CreateTable creates a new table at logs.`table` with the columns in ops\nfunc (r *RedshiftBackend) CreateTable(table string, ops []scoop_protocol.Operation) error {\n\tnewTable, err := buildNewTable(ops)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn r.connection.ExecFnInTransaction(func(tx *sql.Tx) error {\n\t\terr := expectVersion(tx, table, -1)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tquery := fmt.Sprintf(`CREATE TABLE %s%s;`, pq.QuoteIdentifier(table), newTable.getColumnCreationString())\n\t\t_, err = tx.Exec(query)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error CREATEing TABLE %s: %v\", table, err)\n\t\t}\n\t\tr.tableLocks[table] = &sync.Mutex{}\n\t\tquery = \"INSERT INTO infra.table_version (name, version, ts) VALUES ($1, 0, GETDATE())\"\n\t\t_, err = tx.Exec(query, table)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error updating table_version in ace: %v\", err)\n\t\t}\n\t\treturn nil\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 The lime Authors.\n\/\/ Use of this source code is governed by a 2-clause\n\/\/ BSD-style license that can be found in the LICENSE file.\n\npackage render\n<commit_msg>Add some tests for render\/view.<commit_after>\/\/ Copyright 2014 The lime Authors.\n\/\/ Use of this source code is governed by a 2-clause\n\/\/ BSD-style license that can be found in the LICENSE file.\n\npackage render\n\nimport (\n\t\"github.com\/quarnster\/util\/text\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestViewRegionsCull(t *testing.T) {\n\ttests := []struct {\n\t\tregions []text.Region\n\t\tcull text.Region\n\t\texp []text.Region\n\t}{\n\t\t{\n\t\t\t[]text.Region{{100, 200}},\n\t\t\ttext.Region{0, 50},\n\t\t\t[]text.Region{},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 100}},\n\t\t\ttext.Region{100, 100},\n\t\t\t[]text.Region{{100, 100}},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 100}},\n\t\t\ttext.Region{95, 105},\n\t\t\t[]text.Region{{100, 100}},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 100}},\n\t\t\ttext.Region{95, 100},\n\t\t\t[]text.Region{{100, 100}},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 200}},\n\t\t\ttext.Region{150, 150},\n\t\t\t[]text.Region{{150, 150}},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 200}},\n\t\t\ttext.Region{90, 100},\n\t\t\t[]text.Region{{100, 100}},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 200}},\n\t\t\ttext.Region{100, 150},\n\t\t\t[]text.Region{{100, 150}},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 200}},\n\t\t\ttext.Region{150, 175},\n\t\t\t[]text.Region{{150, 175}},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 200}},\n\t\t\ttext.Region{0, 150},\n\t\t\t[]text.Region{{100, 150}},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 200}},\n\t\t\ttext.Region{150, 250},\n\t\t\t[]text.Region{{150, 200}},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 200}},\n\t\t\ttext.Region{0, 250},\n\t\t\t[]text.Region{{100, 200}},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 200}, {300, 400}},\n\t\t\ttext.Region{0, 500},\n\t\t\t[]text.Region{{100, 200}, {300, 400}},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 200}, {300, 400}},\n\t\t\ttext.Region{150, 350},\n\t\t\t[]text.Region{{150, 200}, {300, 350}},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 200}, {300, 400}},\n\t\t\ttext.Region{150, 250},\n\t\t\t[]text.Region{{150, 200}},\n\t\t},\n\t\t{\n\t\t\t[]text.Region{{100, 200}, {300, 400}},\n\t\t\ttext.Region{250, 350},\n\t\t\t[]text.Region{{300, 350}},\n\t\t},\n\t}\n\n\tfor i, test := range tests {\n\t\tvr := ViewRegions{}\n\t\tvr.Regions.AddAll(test.regions)\n\n\t\tvr.Cull(test.cull)\n\n\t\tr := vr.Regions.Regions()\n\n\t\tif !reflect.DeepEqual(r, test.exp) {\n\t\t\tt.Errorf(\"Test %d: Expected %s, but got %s\", i, test.exp, r)\n\t\t}\n\t}\n}\n\nfunc TestViewRegionsClone(t *testing.T) {\n\tvr := ViewRegions{\n\t\tScope:   \"testScope\",\n\t\tIcon:    \"testIcon\",\n\t\tFlags:   100,\n\t}\n\tvr.Regions.AddAll([]text.Region{{0, 0}, {120, 300}, {24, 34}, {45, 40}})\n\n\tc := vr.Clone()\n\tif !reflect.DeepEqual(c, vr) {\n\t\tt.Errorf(\"Expected %+v, but got %+v\", vr, c)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage context\n\nimport (\n\t\"sort\"\n\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/juju\/loggo\"\n\t\"github.com\/juju\/utils\/set\"\n\t\"gopkg.in\/juju\/charm.v5\"\n\n\t\"github.com\/juju\/juju\/process\"\n)\n\nvar logger = loggo.GetLogger(\"juju.process.context\")\n\n\/\/ TODO(ericsnow) Normalize method names across all the arch. layers\n\/\/ (e.g. List->AllProcesses, Get->Processes, Set->AddProcess).\n\n\/\/ APIClient represents the API needs of a Context.\ntype APIClient interface {\n\t\/\/ List requests the list of registered process IDs from state.\n\tList() ([]string, error)\n\t\/\/ Get requests the process info for the given ID.\n\tGet(ids ...string) ([]*process.Info, error)\n\t\/\/ Set sends a request to update state with the provided processes.\n\tSet(procs ...*process.Info) error\n\t\/\/ AllDefinitions returns the process definitions found in the\n\t\/\/ unit's metadata.\n\tAllDefinitions() ([]charm.Process, error)\n}\n\n\/\/ TODO(ericsnow) Rename Get and Set to more specifically describe what\n\/\/ they are for.\n\n\/\/ omponent provides the hook context data specific to workload processes.\ntype Component interface {\n\t\/\/ Get returns the process info corresponding to the given ID.\n\tGet(procName string) (*process.Info, error)\n\t\/\/ Set records the process info in the hook context.\n\tSet(procName string, info *process.Info) error\n\t\/\/ List returns the list of registered process IDs.\n\tList() ([]string, error)\n\t\/\/ ListDefinitions returns the charm-defined processes.\n\tListDefinitions() ([]charm.Process, error)\n\t\/\/ Flush pushes the hook context data out to state.\n\tFlush() error\n}\n\n\/\/ Context is the workload process portion of the hook context.\ntype Context struct {\n\tapi       APIClient\n\tprocesses map[string]*process.Info\n\tupdates   map[string]*process.Info\n\tids       set.Strings\n}\n\n\/\/ NewContext returns a new jujuc.ContextComponent for workload processes.\nfunc NewContext(api APIClient, procs ...*process.Info) *Context {\n\tids := set.NewStrings()\n\tprocesses := make(map[string]*process.Info)\n\tfor _, proc := range procs {\n\t\tprocesses[proc.Name] = proc\n\t\tids.Add(proc.ID())\n\t}\n\treturn &Context{\n\t\tprocesses: processes,\n\t\tapi:       api,\n\t\tids:       ids,\n\t}\n}\n\n\/\/ NewContextAPI returns a new jujuc.ContextComponent for workload processes.\nfunc NewContextAPI(api APIClient) (*Context, error) {\n\tids, err := api.List()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tctx := NewContext(api)\n\tfor _, id := range ids {\n\t\tctx.processes[id] = nil\n\t\tctx.ids.Add(id)\n\t}\n\treturn ctx, nil\n}\n\n\/\/ HookContext is the portion of jujuc.Context used in this package.\ntype HookContext interface {\n\t\/\/ Component implements jujuc.Context.\n\tComponent(string) (Component, error)\n}\n\n\/\/ ContextComponent returns the hook context for the workload\n\/\/ process component.\nfunc ContextComponent(ctx HookContext) (Component, error) {\n\tcompCtx, err := ctx.Component(process.ComponentName)\n\tif errors.IsNotFound(err) {\n\t\treturn nil, errors.Errorf(\"component %q not registered\", process.ComponentName)\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tif compCtx == nil {\n\t\treturn nil, errors.Errorf(\"component %q disabled\", process.ComponentName)\n\t}\n\treturn compCtx, nil\n}\n\nfunc (c *Context) addProc(id string, original *process.Info) error {\n\tvar proc *process.Info\n\tif original != nil {\n\t\tinfo := *original\n\t\tinfo.Name = id\n\t\tproc = &info\n\t}\n\tif _, ok := c.processes[id]; !ok {\n\t\tc.processes[id] = proc\n\t} else {\n\t\tif proc == nil {\n\t\t\treturn errors.Errorf(\"update can't be nil\")\n\t\t}\n\t\tc.set(id, proc)\n\t}\n\treturn nil\n}\n\n\/\/ Processes returns the processes known to the context.\nfunc (c *Context) Processes() ([]*process.Info, error) {\n\tvar procs []*process.Info\n\tfor id, info := range mergeProcMaps(c.processes, c.updates) {\n\t\tif info == nil {\n\t\t\tfetched, err := c.api.Get(id)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Trace(err)\n\t\t\t}\n\t\t\tinfo = fetched[0]\n\t\t\tc.processes[id] = info\n\t\t}\n\t\tprocs = append(procs, info)\n\t}\n\treturn procs, nil\n}\n\nfunc mergeProcMaps(procs, updates map[string]*process.Info) map[string]*process.Info {\n\t\/\/ At this point procs and updates have already been checked for\n\t\/\/ nil values so we won't see any here.\n\tresult := make(map[string]*process.Info)\n\tfor k, v := range procs {\n\t\tresult[k] = v\n\t}\n\tfor k, v := range updates {\n\t\tresult[k] = v\n\t}\n\treturn result\n}\n\n\/\/ TODO(ericsnow) Should be build in refreshes?\n\n\/\/ Get returns the process info corresponding to the given ID.\nfunc (c *Context) Get(procName string) (*process.Info, error) {\n\tactual, ok := c.updates[procName]\n\tif !ok {\n\t\tactual, ok = c.processes[procName]\n\t\tif !ok {\n\t\t\treturn nil, errors.NotFoundf(\"%s\", procName)\n\t\t}\n\t}\n\tif actual == nil {\n\t\tfetched, err := c.api.Get(procName)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tactual = fetched[0]\n\t\tc.processes[procName] = actual\n\t}\n\treturn actual, nil\n}\n\n\/\/ List returns the names of all registered processes.\nfunc (c *Context) List() ([]string, error) {\n\tids := make([]string, len(c.ids))\n\tcopy(ids, c.ids.Values())\n\tsort.Strings(ids)\n\treturn ids, nil\n}\n\n\/\/ Set records the process info in the hook context.\nfunc (c *Context) Set(procName string, info *process.Info) error {\n\tif procName != info.Name {\n\t\treturn errors.Errorf(\"mismatch on name: %s != %s\", procName, info.Name)\n\t}\n\t\/\/ TODO(ericsnow) We are likely missing mechanisim for local persistence.\n\n\tc.set(procName, info)\n\treturn nil\n}\n\nfunc (c *Context) set(id string, pInfo *process.Info) {\n\tif c.updates == nil {\n\t\tc.updates = make(map[string]*process.Info)\n\t}\n\tvar info process.Info\n\tinfo = *pInfo\n\tc.updates[id] = &info\n\tc.ids.Add(id)\n}\n\n\/\/ ListDefinitions returns the unit's charm-defined processes.\nfunc (c *Context) ListDefinitions() ([]charm.Process, error) {\n\tdefinitions, err := c.api.AllDefinitions()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treturn definitions, nil\n}\n\n\/\/ TODO(ericsnow) The context machinery is not actually using this yet.\n\n\/\/ Flush implements jujuc.ContextComponent. In this case that means all\n\/\/ added and updated process.Info in the hook context are pushed to\n\/\/ Juju state via the API.\nfunc (c *Context) Flush() error {\n\tif len(c.updates) == 0 {\n\t\treturn nil\n\t}\n\n\tvar updates []*process.Info\n\tfor _, info := range c.updates {\n\t\tupdates = append(updates, info)\n\t}\n\tif err := c.api.Set(updates...); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfor k, v := range c.updates {\n\t\tc.processes[k] = v\n\t}\n\tc.updates = nil\n\treturn nil\n}\n<commit_msg>Get rid of Context.ids.<commit_after>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage context\n\nimport (\n\t\"sort\"\n\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/juju\/loggo\"\n\t\"gopkg.in\/juju\/charm.v5\"\n\n\t\"github.com\/juju\/juju\/process\"\n)\n\nvar logger = loggo.GetLogger(\"juju.process.context\")\n\n\/\/ TODO(ericsnow) Normalize method names across all the arch. layers\n\/\/ (e.g. List->AllProcesses, Get->Processes, Set->AddProcess).\n\n\/\/ APIClient represents the API needs of a Context.\ntype APIClient interface {\n\t\/\/ List requests the list of registered process IDs from state.\n\tList() ([]string, error)\n\t\/\/ Get requests the process info for the given ID.\n\tGet(ids ...string) ([]*process.Info, error)\n\t\/\/ Set sends a request to update state with the provided processes.\n\tSet(procs ...*process.Info) error\n\t\/\/ AllDefinitions returns the process definitions found in the\n\t\/\/ unit's metadata.\n\tAllDefinitions() ([]charm.Process, error)\n}\n\n\/\/ TODO(ericsnow) Rename Get and Set to more specifically describe what\n\/\/ they are for.\n\n\/\/ omponent provides the hook context data specific to workload processes.\ntype Component interface {\n\t\/\/ Get returns the process info corresponding to the given ID.\n\tGet(procName string) (*process.Info, error)\n\t\/\/ Set records the process info in the hook context.\n\tSet(procName string, info *process.Info) error\n\t\/\/ List returns the list of registered process IDs.\n\tList() ([]string, error)\n\t\/\/ ListDefinitions returns the charm-defined processes.\n\tListDefinitions() ([]charm.Process, error)\n\t\/\/ Flush pushes the hook context data out to state.\n\tFlush() error\n}\n\n\/\/ Context is the workload process portion of the hook context.\ntype Context struct {\n\tapi       APIClient\n\tprocesses map[string]*process.Info\n\tupdates   map[string]*process.Info\n}\n\n\/\/ NewContext returns a new jujuc.ContextComponent for workload processes.\nfunc NewContext(api APIClient, procs ...*process.Info) *Context {\n\tprocesses := make(map[string]*process.Info)\n\tfor _, proc := range procs {\n\t\tprocesses[proc.Name] = proc\n\t}\n\treturn &Context{\n\t\tprocesses: processes,\n\t\tapi:       api,\n\t}\n}\n\n\/\/ NewContextAPI returns a new jujuc.ContextComponent for workload processes.\nfunc NewContextAPI(api APIClient) (*Context, error) {\n\tids, err := api.List()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tctx := NewContext(api)\n\tfor _, id := range ids {\n\t\tctx.processes[id] = nil\n\t}\n\treturn ctx, nil\n}\n\n\/\/ HookContext is the portion of jujuc.Context used in this package.\ntype HookContext interface {\n\t\/\/ Component implements jujuc.Context.\n\tComponent(string) (Component, error)\n}\n\n\/\/ ContextComponent returns the hook context for the workload\n\/\/ process component.\nfunc ContextComponent(ctx HookContext) (Component, error) {\n\tcompCtx, err := ctx.Component(process.ComponentName)\n\tif errors.IsNotFound(err) {\n\t\treturn nil, errors.Errorf(\"component %q not registered\", process.ComponentName)\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tif compCtx == nil {\n\t\treturn nil, errors.Errorf(\"component %q disabled\", process.ComponentName)\n\t}\n\treturn compCtx, nil\n}\n\nfunc (c *Context) addProc(id string, original *process.Info) error {\n\tvar proc *process.Info\n\tif original != nil {\n\t\tinfo := *original\n\t\tinfo.Name = id\n\t\tproc = &info\n\t}\n\tif _, ok := c.processes[id]; !ok {\n\t\tc.processes[id] = proc\n\t} else {\n\t\tif proc == nil {\n\t\t\treturn errors.Errorf(\"update can't be nil\")\n\t\t}\n\t\tc.set(id, proc)\n\t}\n\treturn nil\n}\n\n\/\/ Processes returns the processes known to the context.\nfunc (c *Context) Processes() ([]*process.Info, error) {\n\tvar procs []*process.Info\n\tfor id, info := range mergeProcMaps(c.processes, c.updates) {\n\t\tif info == nil {\n\t\t\tfetched, err := c.api.Get(id)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Trace(err)\n\t\t\t}\n\t\t\tinfo = fetched[0]\n\t\t\tc.processes[id] = info\n\t\t}\n\t\tprocs = append(procs, info)\n\t}\n\treturn procs, nil\n}\n\nfunc mergeProcMaps(procs, updates map[string]*process.Info) map[string]*process.Info {\n\t\/\/ At this point procs and updates have already been checked for\n\t\/\/ nil values so we won't see any here.\n\tresult := make(map[string]*process.Info)\n\tfor k, v := range procs {\n\t\tresult[k] = v\n\t}\n\tfor k, v := range updates {\n\t\tresult[k] = v\n\t}\n\treturn result\n}\n\n\/\/ TODO(ericsnow) Should be build in refreshes?\n\n\/\/ Get returns the process info corresponding to the given ID.\nfunc (c *Context) Get(procName string) (*process.Info, error) {\n\tactual, ok := c.updates[procName]\n\tif !ok {\n\t\tactual, ok = c.processes[procName]\n\t\tif !ok {\n\t\t\treturn nil, errors.NotFoundf(\"%s\", procName)\n\t\t}\n\t}\n\tif actual == nil {\n\t\tfetched, err := c.api.Get(procName)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tactual = fetched[0]\n\t\tc.processes[procName] = actual\n\t}\n\treturn actual, nil\n}\n\n\/\/ List returns the names of all registered processes.\nfunc (c *Context) List() ([]string, error) {\n\tprocs, err := c.Processes()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tif len(procs) == 0 {\n\t\treturn nil, nil\n\t}\n\tvar ids []string\n\tfor _, proc := range procs {\n\t\tids = append(ids, proc.ID())\n\t}\n\tsort.Strings(ids)\n\treturn ids, nil\n}\n\n\/\/ Set records the process info in the hook context.\nfunc (c *Context) Set(procName string, info *process.Info) error {\n\tif procName != info.Name {\n\t\treturn errors.Errorf(\"mismatch on name: %s != %s\", procName, info.Name)\n\t}\n\t\/\/ TODO(ericsnow) We are likely missing mechanisim for local persistence.\n\n\tc.set(procName, info)\n\treturn nil\n}\n\nfunc (c *Context) set(id string, pInfo *process.Info) {\n\tif c.updates == nil {\n\t\tc.updates = make(map[string]*process.Info)\n\t}\n\tvar info process.Info\n\tinfo = *pInfo\n\tc.updates[id] = &info\n}\n\n\/\/ ListDefinitions returns the unit's charm-defined processes.\nfunc (c *Context) ListDefinitions() ([]charm.Process, error) {\n\tdefinitions, err := c.api.AllDefinitions()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\treturn definitions, nil\n}\n\n\/\/ TODO(ericsnow) The context machinery is not actually using this yet.\n\n\/\/ Flush implements jujuc.ContextComponent. In this case that means all\n\/\/ added and updated process.Info in the hook context are pushed to\n\/\/ Juju state via the API.\nfunc (c *Context) Flush() error {\n\tif len(c.updates) == 0 {\n\t\treturn nil\n\t}\n\n\tvar updates []*process.Info\n\tfor _, info := range c.updates {\n\t\tupdates = append(updates, info)\n\t}\n\tif err := c.api.Set(updates...); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfor k, v := range c.updates {\n\t\tc.processes[k] = v\n\t}\n\tc.updates = nil\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage context\n\nimport (\n\t\"github.com\/juju\/errors\"\n\n\t\"github.com\/juju\/juju\/process\"\n)\n\n\/\/ APIClient represents the API needs of a Context.\ntype APIClient interface {\n\t\/\/ List requests the list of registered process IDs from state.\n\tList() ([]string, error)\n\t\/\/ Get requests the process info for the given ID.\n\tGet(ids ...string) ([]*process.Info, error)\n\t\/\/ Set sends a request to update state with the provided processes.\n\tSet(procs ...*process.Info) error\n}\n\n\/\/ omponent provides the hook context data specific to workload processes.\ntype Component interface {\n\t\/\/ Get returns the process info corresponding to the given ID.\n\tGet(procName string) (*process.Info, error)\n\t\/\/ Set records the process info in the hook context.\n\tSet(procName string, info *process.Info) error\n}\n\n\/\/ Context is the workload process portion of the hook context.\ntype Context struct {\n\tapi       APIClient\n\tprocesses map[string]*process.Info\n\tupdates   map[string]*process.Info\n}\n\n\/\/ NewContext returns a new jujuc.ContextComponent for workload processes.\nfunc NewContext(api APIClient, procs ...*process.Info) *Context {\n\tprocesses := make(map[string]*process.Info)\n\tfor _, proc := range procs {\n\t\tprocesses[proc.Name] = proc\n\t}\n\treturn &Context{\n\t\tprocesses: processes,\n\t\tapi:       api,\n\t}\n}\n\n\/\/ NewContextAPI returns a new jujuc.ContextComponent for workload processes.\nfunc NewContextAPI(api APIClient) (*Context, error) {\n\tids, err := api.List()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tctx := NewContext(api)\n\tfor _, id := range ids {\n\t\tctx.processes[id] = nil\n\t}\n\treturn ctx, nil\n}\n\n\/\/ HookContext is the portion of jujuc.Context used in this package.\ntype HookContext interface {\n\t\/\/ Component implements jujuc.Context.\n\tComponent(string) (Component, error)\n}\n\n\/\/ ContextComponent returns the hook context for the workload\n\/\/ process component.\nfunc ContextComponent(ctx HookContext) (Component, error) {\n\tcompCtx, err := ctx.Component(process.ComponentName)\n\tif errors.IsNotFound(err) {\n\t\treturn nil, errors.Errorf(\"component %q not registered\", process.ComponentName)\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tif compCtx == nil {\n\t\treturn nil, errors.Errorf(\"component %q disabled\", process.ComponentName)\n\t}\n\treturn compCtx, nil\n}\n\nfunc (c *Context) addProc(id string, original *process.Info) error {\n\tvar proc *process.Info\n\tif original != nil {\n\t\tinfo := *original\n\t\tinfo.Name = id\n\t\tproc = &info\n\t}\n\tif _, ok := c.processes[id]; !ok {\n\t\tc.processes[id] = proc\n\t} else {\n\t\tif proc == nil {\n\t\t\treturn errors.Errorf(\"update can't be nil\")\n\t\t}\n\t\tc.set(id, proc)\n\t}\n\treturn nil\n}\n\n\/\/ Processes returns the processes known to the context.\nfunc (c *Context) Processes() ([]*process.Info, error) {\n\tvar procs []*process.Info\n\tfor id, info := range mergeProcMaps(c.processes, c.updates) {\n\t\tif info == nil {\n\t\t\tfetched, err := c.api.Get(id)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Trace(err)\n\t\t\t}\n\t\t\tinfo = fetched[0]\n\t\t\tc.processes[id] = info\n\t\t}\n\t\tprocs = append(procs, info)\n\t}\n\treturn procs, nil\n}\n\nfunc mergeProcMaps(procs, updates map[string]*process.Info) map[string]*process.Info {\n\t\/\/ At this point procs and updates have already been checked for\n\t\/\/ nil values so we won't see any here.\n\tresult := make(map[string]*process.Info)\n\tfor k, v := range procs {\n\t\tresult[k] = v\n\t}\n\tfor k, v := range updates {\n\t\tresult[k] = v\n\t}\n\treturn result\n}\n\n\/\/ Get returns the process info corresponding to the given ID.\nfunc (c *Context) Get(procName string) (*process.Info, error) {\n\tactual, ok := c.updates[procName]\n\tif !ok {\n\t\tactual, ok = c.processes[procName]\n\t\tif !ok {\n\t\t\treturn nil, errors.NotFoundf(\"%s\", procName)\n\t\t}\n\t}\n\tif actual == nil {\n\t\tfetched, err := c.api.Get(procName)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tactual = fetched[0]\n\t\tc.processes[procName] = actual\n\t}\n\treturn actual, nil\n}\n\n\/\/ Set records the process info in the hook context.\nfunc (c *Context) Set(procName string, info *process.Info) error {\n\tif procName != info.Name {\n\t\treturn errors.Errorf(\"mismatch on name: %s != %s\", procName, info.Name)\n\t}\n\t\/\/ TODO(ericsnow) We are likely missing mechanisim for local persistence.\n\n\tc.set(procName, info)\n\treturn nil\n}\n\nfunc (c *Context) set(id string, pInfo *process.Info) {\n\tif c.updates == nil {\n\t\tc.updates = make(map[string]*process.Info)\n\t}\n\tvar info process.Info\n\tinfo = *pInfo\n\tc.updates[id] = &info\n}\n\n\/\/ Flush implements jujuc.ContextComponent. In this case that means all\n\/\/ added and updated process.Info in the hook context are pushed to\n\/\/ Juju state via the API.\nfunc (c *Context) Flush() error {\n\tif len(c.updates) == 0 {\n\t\treturn nil\n\t}\n\n\tvar updates []*process.Info\n\tfor _, info := range c.updates {\n\t\tupdates = append(updates, info)\n\t}\n\tif err := c.api.Set(updates...); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfor k, v := range c.updates {\n\t\tc.processes[k] = v\n\t}\n\tc.updates = nil\n\treturn nil\n}\n<commit_msg>Add a TODO.<commit_after>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage context\n\nimport (\n\t\"github.com\/juju\/errors\"\n\n\t\"github.com\/juju\/juju\/process\"\n)\n\n\/\/ APIClient represents the API needs of a Context.\ntype APIClient interface {\n\t\/\/ List requests the list of registered process IDs from state.\n\tList() ([]string, error)\n\t\/\/ Get requests the process info for the given ID.\n\tGet(ids ...string) ([]*process.Info, error)\n\t\/\/ Set sends a request to update state with the provided processes.\n\tSet(procs ...*process.Info) error\n}\n\n\/\/ omponent provides the hook context data specific to workload processes.\ntype Component interface {\n\t\/\/ Get returns the process info corresponding to the given ID.\n\tGet(procName string) (*process.Info, error)\n\t\/\/ Set records the process info in the hook context.\n\tSet(procName string, info *process.Info) error\n}\n\n\/\/ Context is the workload process portion of the hook context.\ntype Context struct {\n\tapi       APIClient\n\tprocesses map[string]*process.Info\n\tupdates   map[string]*process.Info\n}\n\n\/\/ NewContext returns a new jujuc.ContextComponent for workload processes.\nfunc NewContext(api APIClient, procs ...*process.Info) *Context {\n\tprocesses := make(map[string]*process.Info)\n\tfor _, proc := range procs {\n\t\tprocesses[proc.Name] = proc\n\t}\n\treturn &Context{\n\t\tprocesses: processes,\n\t\tapi:       api,\n\t}\n}\n\n\/\/ NewContextAPI returns a new jujuc.ContextComponent for workload processes.\nfunc NewContextAPI(api APIClient) (*Context, error) {\n\tids, err := api.List()\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tctx := NewContext(api)\n\tfor _, id := range ids {\n\t\tctx.processes[id] = nil\n\t}\n\treturn ctx, nil\n}\n\n\/\/ HookContext is the portion of jujuc.Context used in this package.\ntype HookContext interface {\n\t\/\/ Component implements jujuc.Context.\n\tComponent(string) (Component, error)\n}\n\n\/\/ ContextComponent returns the hook context for the workload\n\/\/ process component.\nfunc ContextComponent(ctx HookContext) (Component, error) {\n\tcompCtx, err := ctx.Component(process.ComponentName)\n\tif errors.IsNotFound(err) {\n\t\treturn nil, errors.Errorf(\"component %q not registered\", process.ComponentName)\n\t}\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tif compCtx == nil {\n\t\treturn nil, errors.Errorf(\"component %q disabled\", process.ComponentName)\n\t}\n\treturn compCtx, nil\n}\n\nfunc (c *Context) addProc(id string, original *process.Info) error {\n\tvar proc *process.Info\n\tif original != nil {\n\t\tinfo := *original\n\t\tinfo.Name = id\n\t\tproc = &info\n\t}\n\tif _, ok := c.processes[id]; !ok {\n\t\tc.processes[id] = proc\n\t} else {\n\t\tif proc == nil {\n\t\t\treturn errors.Errorf(\"update can't be nil\")\n\t\t}\n\t\tc.set(id, proc)\n\t}\n\treturn nil\n}\n\n\/\/ Processes returns the processes known to the context.\nfunc (c *Context) Processes() ([]*process.Info, error) {\n\tvar procs []*process.Info\n\tfor id, info := range mergeProcMaps(c.processes, c.updates) {\n\t\tif info == nil {\n\t\t\tfetched, err := c.api.Get(id)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Trace(err)\n\t\t\t}\n\t\t\tinfo = fetched[0]\n\t\t\tc.processes[id] = info\n\t\t}\n\t\tprocs = append(procs, info)\n\t}\n\treturn procs, nil\n}\n\nfunc mergeProcMaps(procs, updates map[string]*process.Info) map[string]*process.Info {\n\t\/\/ At this point procs and updates have already been checked for\n\t\/\/ nil values so we won't see any here.\n\tresult := make(map[string]*process.Info)\n\tfor k, v := range procs {\n\t\tresult[k] = v\n\t}\n\tfor k, v := range updates {\n\t\tresult[k] = v\n\t}\n\treturn result\n}\n\n\/\/ Get returns the process info corresponding to the given ID.\nfunc (c *Context) Get(procName string) (*process.Info, error) {\n\tactual, ok := c.updates[procName]\n\tif !ok {\n\t\tactual, ok = c.processes[procName]\n\t\tif !ok {\n\t\t\treturn nil, errors.NotFoundf(\"%s\", procName)\n\t\t}\n\t}\n\tif actual == nil {\n\t\tfetched, err := c.api.Get(procName)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tactual = fetched[0]\n\t\tc.processes[procName] = actual\n\t}\n\treturn actual, nil\n}\n\n\/\/ Set records the process info in the hook context.\nfunc (c *Context) Set(procName string, info *process.Info) error {\n\tif procName != info.Name {\n\t\treturn errors.Errorf(\"mismatch on name: %s != %s\", procName, info.Name)\n\t}\n\t\/\/ TODO(ericsnow) We are likely missing mechanisim for local persistence.\n\n\tc.set(procName, info)\n\treturn nil\n}\n\nfunc (c *Context) set(id string, pInfo *process.Info) {\n\tif c.updates == nil {\n\t\tc.updates = make(map[string]*process.Info)\n\t}\n\tvar info process.Info\n\tinfo = *pInfo\n\tc.updates[id] = &info\n}\n\n\/\/ TODO(ericsnow) The context machinery is not actually using this yet.\n\n\/\/ Flush implements jujuc.ContextComponent. In this case that means all\n\/\/ added and updated process.Info in the hook context are pushed to\n\/\/ Juju state via the API.\nfunc (c *Context) Flush() error {\n\tif len(c.updates) == 0 {\n\t\treturn nil\n\t}\n\n\tvar updates []*process.Info\n\tfor _, info := range c.updates {\n\t\tupdates = append(updates, info)\n\t}\n\tif err := c.api.Set(updates...); err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\n\tfor k, v := range c.updates {\n\t\tc.processes[k] = v\n\t}\n\tc.updates = nil\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The LUCI Authors. All rights reserved.\n\/\/ Use of this source code is governed under the Apache License, Version 2.0\n\/\/ that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"time\"\n\n\thumanize \"github.com\/dustin\/go-humanize\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/luci\/luci-go\/client\/isolate\"\n\t\"github.com\/luci\/luci-go\/common\/eventlog\"\n\tlogpb \"github.com\/luci\/luci-go\/common\/eventlog\/proto\"\n\t\"github.com\/luci\/luci-go\/common\/isolated\"\n\t\"github.com\/luci\/luci-go\/common\/isolatedclient\"\n\t\"github.com\/maruel\/subcommands\"\n)\n\nconst (\n\t\/\/ archiveThreshold is the size (in bytes) used to determine whether to add\n\t\/\/ files to a tar archive before uploading. Files smaller than this size will\n\t\/\/ be combined into archives before being uploaded to the server.\n\tarchiveThreshold = 100e3 \/\/ 100kB\n\n\t\/\/ archiveSizeTrigger is the desired size of the created archives. Once\n\t\/\/ archives reach this size, they will be closed and prepared for upload.\n\tarchiveSizeTrigger = 10e6\n)\n\nvar cmdExpArchive = &subcommands.Command{\n\tUsageLine: \"exparchive <options>\",\n\tShortDesc: \"EXPERIMENTAL parses a .isolate file to create a .isolated file, and uploads it and all referenced files to an isolate server\",\n\tLongDesc:  \"All the files listed in the .isolated file are put in the isolate server cache. Small files are combined together in a tar archive before uploading.\",\n\tCommandRun: func() subcommands.CommandRun {\n\t\tc := &expArchiveRun{}\n\t\tc.commonServerFlags.Init()\n\t\tc.isolateFlags.Init(&c.Flags)\n\t\treturn c\n\t},\n}\n\n\/\/ expArchiveRun contains the logic for the experimental archive subcommand.\n\/\/ It implements subcommand.CommandRun\ntype expArchiveRun struct {\n\tcommonServerFlags \/\/ Provides the GetFlags method.\n\tisolateFlags      isolateFlags\n}\n\n\/\/ Item represents a file or symlink referenced by an isolate file.\ntype Item struct {\n\tPath    string\n\tRelPath string\n\tSize    int64\n\tMode    os.FileMode\n\n\tDigest isolated.HexDigest\n}\n\n\/\/ main contains the core logic for experimental archive.\nfunc (c *expArchiveRun) main() error {\n\tstart := time.Now()\n\tarchiveOpts := &c.isolateFlags.ArchiveOptions\n\t\/\/ Parse the incoming isolate file.\n\tdeps, rootDir, isol, err := isolate.ProcessIsolate(archiveOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to process isolate: %v\", err)\n\t}\n\tlog.Printf(\"Isolate referenced %d deps\", len(deps))\n\n\t\/\/ Create the isolated client which connects to the isolate server.\n\tauthCl, err := c.createAuthClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient := isolatedclient.New(nil, authCl, c.isolatedFlags.ServerURL, c.isolatedFlags.Namespace, nil)\n\n\tchecker := NewChecker(client)\n\n\t\/\/ Walk each of the deps, partioning the results into symlinks and files categorised by size.\n\tvar links, archiveFiles, indivFiles []*Item\n\tvar archiveSize, indivSize int64 \/\/ Cumulative size of archived\/individual files.\n\tfor _, dep := range deps {\n\t\t\/\/ Try to walk dep. If dep is a file (or symlink), the inner function is called exactly once.\n\t\terr := filepath.Walk(filepath.Clean(dep), func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif info.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\trelPath, err := filepath.Rel(rootDir, path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\titem := &Item{\n\t\t\t\tPath:    path,\n\t\t\t\tRelPath: relPath,\n\t\t\t\tMode:    info.Mode(),\n\t\t\t\tSize:    info.Size(),\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase item.Mode&os.ModeSymlink == os.ModeSymlink:\n\t\t\t\tlinks = append(links, item)\n\t\t\tcase item.Size < archiveThreshold:\n\t\t\t\tarchiveFiles = append(archiveFiles, item)\n\t\t\t\tarchiveSize += item.Size\n\t\t\tdefault:\n\t\t\t\tindivFiles = append(indivFiles, item)\n\t\t\t\tindivSize += item.Size\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Construct a map of the files that constitute the isolate.\n\tfiles := make(map[string]isolated.File)\n\n\tlog.Printf(\"Isolate expanded to %d files (total size %s) and %d symlinks\", len(archiveFiles)+len(indivFiles), humanize.Bytes(uint64(archiveSize+indivSize)), len(links))\n\tlog.Printf(\"\\t%d files (%s) to be isolated individually\", len(indivFiles), humanize.Bytes(uint64(indivSize)))\n\tlog.Printf(\"\\t%d files (%s) to be isolated in archives\", len(archiveFiles), humanize.Bytes(uint64(archiveSize)))\n\n\t\/\/ Handle the symlinks.\n\tfor _, item := range links {\n\t\tl, err := os.Readlink(item.Path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to resolve symlink for %q: %v\", item.Path, err)\n\t\t}\n\t\tfiles[item.RelPath] = isolated.SymLink(l)\n\t}\n\n\t\/\/ Handle the small to-be-archived files.\n\tarchiveCallback := func(tar *Tar) {\n\t\tlog.Printf(\"Created tar archive %q (%s)\", tar.Digest, humanize.Bytes(uint64(len(tar.Content))))\n\t\tlog.Printf(\"\\tcontains %d files (total %s)\", tar.FileCount, humanize.Bytes(uint64(tar.FileSize)))\n\t\t\/\/ Mint an item for this tar.\n\t\titem := &Item{\n\t\t\tPath:    fmt.Sprintf(\".%s.tar\", tar.Digest),\n\t\t\tRelPath: fmt.Sprintf(\".%s.tar\", tar.Digest),\n\t\t\tSize:    int64(len(tar.Content)),\n\t\t\tMode:    0644, \/\/ Read\n\t\t\tDigest:  tar.Digest,\n\t\t}\n\t\tfiles[item.RelPath] = isolated.TarFile(item.Digest, int(item.Mode), item.Size)\n\t\tchecker.AddItem(item, false, func(item *Item, ps *isolatedclient.PushState) {\n\t\t\tif ps == nil {\n\t\t\t\ttar.Release()\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ XXX(djd): Actually upload the tar file.\n\t\t\tlog.Printf(\"XXX: %q needs to be uploaded\", item.RelPath)\n\t\t\ttar.Release()\n\t\t})\n\t}\n\n\tarchiver := NewTarAchiver(archiveCallback)\n\tfor _, item := range archiveFiles {\n\t\tif err := archiver.AddItem(item); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tarchiver.Flush()\n\n\t\/\/ Handle the large individually-uploaded files.\n\tfor _, item := range indivFiles {\n\t\td, err := hashFile(item.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\titem.Digest = d\n\t\tfiles[item.RelPath] = isolated.BasicFile(item.Digest, int(item.Mode), item.Size)\n\t\tchecker.AddItem(item, false, func(item *Item, ps *isolatedclient.PushState) {\n\t\t\tif ps == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ XXX(djd): Actually upload the file.\n\t\t\tlog.Printf(\"XXX: %q needs to be uploaded\", item.RelPath)\n\t\t})\n\t}\n\n\t\/\/ Marshal the isolated file into JSON.\n\tisol.Files = files\n\tisolJSON, err := json.Marshal(isol)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ TODO(djd): actually check\/upload the isolated.\n\n\t\/\/ Make sure that all pending items have been checked.\n\tif err := checker.Close(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Write the isolated file, and emit its digest to stdout.\n\tif err := ioutil.WriteFile(archiveOpts.Isolated, isolJSON, 0644); err != nil {\n\t\treturn err\n\t}\n\tisolatedHash := string(isolated.HashBytes(isolJSON))\n\tfmt.Printf(\"%s\\t%s\\n\", isolatedHash, filepath.Base(archiveOpts.Isolated))\n\n\tend := time.Now()\n\n\tif endpoint := eventlogEndpoint(c.isolateFlags.EventlogEndpoint); endpoint != \"\" {\n\t\tctx := context.Background()\n\t\tlogger := eventlog.NewClient(ctx, endpoint)\n\n\t\t\/\/ TODO(mcgreevy): fill out more stats in archiveDetails.\n\t\tarchiveDetails := &logpb.IsolateClientEvent_ArchiveDetails{\n\t\t\tIsolateHash: []string{isolatedHash},\n\t\t}\n\t\tif err := logStats(ctx, logger, start, end, archiveDetails); err != nil {\n\t\t\tlog.Printf(\"Failed to log to eventlog: %v\", err)\n\t\t}\n\t}\n\n\treturn errors.New(\"experimental archive is not implemented\")\n}\n\nfunc (c *expArchiveRun) parseFlags(args []string) error {\n\tif len(args) != 0 {\n\t\treturn errors.New(\"position arguments not expected\")\n\t}\n\tif err := c.commonServerFlags.Parse(); err != nil {\n\t\treturn err\n\t}\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := c.isolateFlags.Parse(cwd, RequireIsolateFile&RequireIsolatedFile); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *expArchiveRun) Run(a subcommands.Application, args []string, _ subcommands.Env) int {\n\tfmt.Fprintln(a.GetErr(), \"WARNING: this command is experimental\")\n\tif err := c.parseFlags(args); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tif len(c.isolateFlags.ArchiveOptions.Blacklist) != 0 {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: blacklist is not supported\\n\", a.GetName())\n\t\treturn 1\n\t}\n\tif err := c.main(); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\treturn 0\n}\n\nfunc hashFile(path string) (isolated.HexDigest, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\treturn isolated.Hash(f)\n}\n\nfunc logStats(ctx context.Context, logger *eventlog.Client, start, end time.Time, archiveDetails *logpb.IsolateClientEvent_ArchiveDetails) error {\n\tevent := logger.NewLogEvent(ctx, eventlog.Point())\n\tevent.InfraEvent.IsolateClientEvent = &logpb.IsolateClientEvent{\n\t\tBinary: &logpb.Binary{\n\t\t\tName:          proto.String(\"isolate\"),\n\t\t\tVersionNumber: proto.String(version),\n\t\t},\n\t\tOperation:      logpb.IsolateClientEvent_ARCHIVE.Enum(),\n\t\tArchiveDetails: archiveDetails,\n\t\t\/\/ TODO(mcgreevy): fill out Master, Builder, BuildId, Slave.\n\t\tStartTsUsec: proto.Int64(int64(start.UnixNano() \/ 1e3)),\n\t\tEndTsUsec:   proto.Int64(int64(end.UnixNano() \/ 1e3)),\n\t}\n\treturn logger.LogSync(ctx, event)\n}\n\nfunc eventlogEndpoint(endpointFlag string) string {\n\tswitch endpointFlag {\n\tcase \"test\":\n\t\treturn eventlog.TestEndpoint\n\tcase \"prod\":\n\t\treturn eventlog.ProdEndpoint\n\tdefault:\n\t\treturn endpointFlag\n\t}\n}\n<commit_msg>client\/isolate: wire up object uploading in exparchive<commit_after>\/\/ Copyright 2015 The LUCI Authors. All rights reserved.\n\/\/ Use of this source code is governed under the Apache License, Version 2.0\n\/\/ that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"time\"\n\n\thumanize \"github.com\/dustin\/go-humanize\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/luci\/luci-go\/client\/isolate\"\n\t\"github.com\/luci\/luci-go\/common\/eventlog\"\n\tlogpb \"github.com\/luci\/luci-go\/common\/eventlog\/proto\"\n\t\"github.com\/luci\/luci-go\/common\/isolated\"\n\t\"github.com\/luci\/luci-go\/common\/isolatedclient\"\n\t\"github.com\/maruel\/subcommands\"\n)\n\nconst (\n\t\/\/ archiveThreshold is the size (in bytes) used to determine whether to add\n\t\/\/ files to a tar archive before uploading. Files smaller than this size will\n\t\/\/ be combined into archives before being uploaded to the server.\n\tarchiveThreshold = 100e3 \/\/ 100kB\n\n\t\/\/ archiveSizeTrigger is the desired size of the created archives. Once\n\t\/\/ archives reach this size, they will be closed and prepared for upload.\n\tarchiveSizeTrigger = 10e6\n)\n\nvar cmdExpArchive = &subcommands.Command{\n\tUsageLine: \"exparchive <options>\",\n\tShortDesc: \"EXPERIMENTAL parses a .isolate file to create a .isolated file, and uploads it and all referenced files to an isolate server\",\n\tLongDesc:  \"All the files listed in the .isolated file are put in the isolate server cache. Small files are combined together in a tar archive before uploading.\",\n\tCommandRun: func() subcommands.CommandRun {\n\t\tc := &expArchiveRun{}\n\t\tc.commonServerFlags.Init()\n\t\tc.isolateFlags.Init(&c.Flags)\n\t\treturn c\n\t},\n}\n\n\/\/ expArchiveRun contains the logic for the experimental archive subcommand.\n\/\/ It implements subcommand.CommandRun\ntype expArchiveRun struct {\n\tcommonServerFlags \/\/ Provides the GetFlags method.\n\tisolateFlags      isolateFlags\n}\n\n\/\/ Item represents a file or symlink referenced by an isolate file.\ntype Item struct {\n\tPath    string\n\tRelPath string\n\tSize    int64\n\tMode    os.FileMode\n\n\tDigest isolated.HexDigest\n}\n\n\/\/ main contains the core logic for experimental archive.\nfunc (c *expArchiveRun) main() error {\n\t\/\/ TODO(djd): This func is long and has a lot of internal complexity (like,\n\t\/\/ such as, archiveCallback). Refactor.\n\n\tstart := time.Now()\n\tarchiveOpts := &c.isolateFlags.ArchiveOptions\n\t\/\/ Parse the incoming isolate file.\n\tdeps, rootDir, isol, err := isolate.ProcessIsolate(archiveOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to process isolate: %v\", err)\n\t}\n\tlog.Printf(\"Isolate referenced %d deps\", len(deps))\n\n\t\/\/ Set up a background context which is cancelled when this function returns.\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\t\/\/ Create the isolated client which connects to the isolate server.\n\tauthCl, err := c.createAuthClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient := isolatedclient.New(nil, authCl, c.isolatedFlags.ServerURL, c.isolatedFlags.Namespace, nil)\n\n\t\/\/ Set up a checker and pair of uploaders. One uploader is for in-memory\n\t\/\/ files, and one is for on-disk files (we want to limit the latter to only\n\t\/\/ one upload at a time).\n\t\/\/ TODO(djd): Make NewChecker take a context arg.\n\tchecker := NewChecker(client)\n\tmemUploader, fileUploader := NewUploader(ctx, client, 10), NewUploader(ctx, client, 1)\n\n\t\/\/ Walk each of the deps, partioning the results into symlinks and files categorised by size.\n\tvar links, archiveFiles, indivFiles []*Item\n\tvar archiveSize, indivSize int64 \/\/ Cumulative size of archived\/individual files.\n\tfor _, dep := range deps {\n\t\t\/\/ Try to walk dep. If dep is a file (or symlink), the inner function is called exactly once.\n\t\terr := filepath.Walk(filepath.Clean(dep), func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif info.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\trelPath, err := filepath.Rel(rootDir, path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\titem := &Item{\n\t\t\t\tPath:    path,\n\t\t\t\tRelPath: relPath,\n\t\t\t\tMode:    info.Mode(),\n\t\t\t\tSize:    info.Size(),\n\t\t\t}\n\n\t\t\tswitch {\n\t\t\tcase item.Mode&os.ModeSymlink == os.ModeSymlink:\n\t\t\t\tlinks = append(links, item)\n\t\t\tcase item.Size < archiveThreshold:\n\t\t\t\tarchiveFiles = append(archiveFiles, item)\n\t\t\t\tarchiveSize += item.Size\n\t\t\tdefault:\n\t\t\t\tindivFiles = append(indivFiles, item)\n\t\t\t\tindivSize += item.Size\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Construct a map of the files that constitute the isolate.\n\tfiles := make(map[string]isolated.File)\n\n\tlog.Printf(\"Isolate expanded to %d files (total size %s) and %d symlinks\", len(archiveFiles)+len(indivFiles), humanize.Bytes(uint64(archiveSize+indivSize)), len(links))\n\tlog.Printf(\"\\t%d files (%s) to be isolated individually\", len(indivFiles), humanize.Bytes(uint64(indivSize)))\n\tlog.Printf(\"\\t%d files (%s) to be isolated in archives\", len(archiveFiles), humanize.Bytes(uint64(archiveSize)))\n\n\t\/\/ Handle the symlinks.\n\tfor _, item := range links {\n\t\tl, err := os.Readlink(item.Path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to resolve symlink for %q: %v\", item.Path, err)\n\t\t}\n\t\tfiles[item.RelPath] = isolated.SymLink(l)\n\t}\n\n\t\/\/ Handle the small to-be-archived files.\n\tarchiveCallback := func(tar *Tar) {\n\t\tlog.Printf(\"Created tar archive %q (%s)\", tar.Digest, humanize.Bytes(uint64(len(tar.Content))))\n\t\tlog.Printf(\"\\tcontains %d files (total %s)\", tar.FileCount, humanize.Bytes(uint64(tar.FileSize)))\n\t\t\/\/ Mint an item for this tar.\n\t\titem := &Item{\n\t\t\tPath:    fmt.Sprintf(\".%s.tar\", tar.Digest),\n\t\t\tRelPath: fmt.Sprintf(\".%s.tar\", tar.Digest),\n\t\t\tSize:    int64(len(tar.Content)),\n\t\t\tMode:    0644, \/\/ Read\n\t\t\tDigest:  tar.Digest,\n\t\t}\n\t\tfiles[item.RelPath] = isolated.TarFile(item.Digest, int(item.Mode), item.Size)\n\t\tchecker.AddItem(item, false, func(item *Item, ps *isolatedclient.PushState) {\n\t\t\tif ps == nil {\n\t\t\t\ttar.Release()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Printf(\"QUEUED %q for upload\", item.RelPath)\n\t\t\tmemUploader.UploadBytes(item.RelPath, tar.Content, ps, func() {\n\t\t\t\tlog.Printf(\"UPLOADED %q\", item.RelPath)\n\t\t\t\ttar.Release()\n\t\t\t})\n\t\t})\n\t}\n\n\tarchiver := NewTarAchiver(archiveCallback)\n\tfor _, item := range archiveFiles {\n\t\tif err := archiver.AddItem(item); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tarchiver.Flush()\n\n\t\/\/ Handle the large individually-uploaded files.\n\tfor _, item := range indivFiles {\n\t\td, err := hashFile(item.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\titem.Digest = d\n\t\tfiles[item.RelPath] = isolated.BasicFile(item.Digest, int(item.Mode), item.Size)\n\t\tchecker.AddItem(item, false, func(item *Item, ps *isolatedclient.PushState) {\n\t\t\tif ps == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Printf(\"QUEUED %q for upload\", item.RelPath)\n\t\t\tfileUploader.UploadFile(item, ps, func() {\n\t\t\t\tlog.Printf(\"UPLOADED %q\", item.RelPath)\n\t\t\t})\n\t\t})\n\t}\n\n\t\/\/ Marshal the isolated file into JSON, and create an Item to describe it.\n\tisol.Files = files\n\tisolJSON, err := json.Marshal(isol)\n\tif err != nil {\n\t\treturn err\n\t}\n\tisolItem := &Item{\n\t\tPath:    archiveOpts.Isolated,\n\t\tRelPath: filepath.Base(archiveOpts.Isolated),\n\t\tDigest:  isolated.HashBytes(isolJSON),\n\t\tSize:    int64(len(isolJSON)),\n\t}\n\n\t\/\/ Check and upload isolate JSON.\n\tchecker.AddItem(isolItem, true, func(item *Item, ps *isolatedclient.PushState) {\n\t\tif ps == nil {\n\t\t\treturn\n\t\t}\n\t\tlog.Printf(\"QUEUED %q for upload\", item.RelPath)\n\t\tmemUploader.UploadBytes(item.RelPath, isolJSON, ps, func() {\n\t\t\tlog.Printf(\"UPLOADED %q\", item.RelPath)\n\t\t})\n\t})\n\n\t\/\/ Make sure that all pending items have been checked.\n\tif err := checker.Close(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Make sure that all the uploads have completed successfully.\n\tif err := fileUploader.Close(); err != nil {\n\t\treturn err\n\t}\n\tif err := memUploader.Close(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Write the isolated file, and emit its digest to stdout.\n\tif err := ioutil.WriteFile(archiveOpts.Isolated, isolJSON, 0644); err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(\"%s\\t%s\\n\", isolItem.Digest, filepath.Base(archiveOpts.Isolated))\n\n\tend := time.Now()\n\n\tif endpoint := eventlogEndpoint(c.isolateFlags.EventlogEndpoint); endpoint != \"\" {\n\t\tlogger := eventlog.NewClient(ctx, endpoint)\n\n\t\t\/\/ TODO(mcgreevy): fill out more stats in archiveDetails.\n\t\tarchiveDetails := &logpb.IsolateClientEvent_ArchiveDetails{\n\t\t\tIsolateHash: []string{string(isolItem.Digest)},\n\t\t}\n\t\tif err := logStats(ctx, logger, start, end, archiveDetails); err != nil {\n\t\t\tlog.Printf(\"Failed to log to eventlog: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *expArchiveRun) parseFlags(args []string) error {\n\tif len(args) != 0 {\n\t\treturn errors.New(\"position arguments not expected\")\n\t}\n\tif err := c.commonServerFlags.Parse(); err != nil {\n\t\treturn err\n\t}\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := c.isolateFlags.Parse(cwd, RequireIsolateFile&RequireIsolatedFile); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *expArchiveRun) Run(a subcommands.Application, args []string, _ subcommands.Env) int {\n\tfmt.Fprintln(a.GetErr(), \"WARNING: this command is experimental\")\n\tif err := c.parseFlags(args); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\tif len(c.isolateFlags.ArchiveOptions.Blacklist) != 0 {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: blacklist is not supported\\n\", a.GetName())\n\t\treturn 1\n\t}\n\tif err := c.main(); err != nil {\n\t\tfmt.Fprintf(a.GetErr(), \"%s: %s\\n\", a.GetName(), err)\n\t\treturn 1\n\t}\n\treturn 0\n}\n\nfunc hashFile(path string) (isolated.HexDigest, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer f.Close()\n\treturn isolated.Hash(f)\n}\n\nfunc logStats(ctx context.Context, logger *eventlog.Client, start, end time.Time, archiveDetails *logpb.IsolateClientEvent_ArchiveDetails) error {\n\tevent := logger.NewLogEvent(ctx, eventlog.Point())\n\tevent.InfraEvent.IsolateClientEvent = &logpb.IsolateClientEvent{\n\t\tBinary: &logpb.Binary{\n\t\t\tName:          proto.String(\"isolate\"),\n\t\t\tVersionNumber: proto.String(version),\n\t\t},\n\t\tOperation:      logpb.IsolateClientEvent_ARCHIVE.Enum(),\n\t\tArchiveDetails: archiveDetails,\n\t\t\/\/ TODO(mcgreevy): fill out Master, Builder, BuildId, Slave.\n\t\tStartTsUsec: proto.Int64(int64(start.UnixNano() \/ 1e3)),\n\t\tEndTsUsec:   proto.Int64(int64(end.UnixNano() \/ 1e3)),\n\t}\n\treturn logger.LogSync(ctx, event)\n}\n\nfunc eventlogEndpoint(endpointFlag string) string {\n\tswitch endpointFlag {\n\tcase \"test\":\n\t\treturn eventlog.TestEndpoint\n\tcase \"prod\":\n\t\treturn eventlog.ProdEndpoint\n\tdefault:\n\t\treturn endpointFlag\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 Authors of Cilium\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/cilium\/cilium\/api\/v1\/models\"\n\t. \"github.com\/cilium\/cilium\/api\/v1\/server\/restapi\/policy\"\n\t\"github.com\/cilium\/cilium\/pkg\/api\"\n\t\"github.com\/cilium\/cilium\/pkg\/endpoint\"\n\t\"github.com\/cilium\/cilium\/pkg\/endpointmanager\"\n\t\"github.com\/cilium\/cilium\/pkg\/fqdn\"\n\t\"github.com\/cilium\/cilium\/pkg\/fqdn\/dnsproxy\"\n\t\"github.com\/cilium\/cilium\/pkg\/fqdn\/matchpattern\"\n\t\"github.com\/cilium\/cilium\/pkg\/logging\/logfields\"\n\t\"github.com\/cilium\/cilium\/pkg\/node\"\n\t\"github.com\/cilium\/cilium\/pkg\/option\"\n\tpolicyApi \"github.com\/cilium\/cilium\/pkg\/policy\/api\"\n\t\"github.com\/cilium\/cilium\/pkg\/proxy\"\n\t\"github.com\/cilium\/cilium\/pkg\/proxy\/accesslog\"\n\t\"github.com\/cilium\/cilium\/pkg\/proxy\/logger\"\n\t\"github.com\/cilium\/cilium\/pkg\/u8proto\"\n\t\"github.com\/go-openapi\/runtime\/middleware\"\n\t\"github.com\/go-openapi\/strfmt\"\n\n\t\"github.com\/miekg\/dns\"\n)\n\n\/\/ bootstrapFQDN initializes the toFQDNs related subsystems: DNSPoller,\n\/\/ d.dnsRuleGen, and the DNS proxy.\n\/\/ dnsRuleGen and DNSPoller will use the default resolver and, implicitly, the\n\/\/ default DNS cache. The proxy binds to all interfaces, and uses the\n\/\/ configured DNS proxy port (this may be 0 and so OS-assigned).\nfunc (d *Daemon) bootstrapFQDN(restoredEndpoints *endpointRestoreState) (err error) {\n\tcfg := fqdn.Config{\n\t\tMinTTL:         option.Config.ToFQDNsMinTTL,\n\t\tCache:          fqdn.DefaultDNSCache,\n\t\tLookupDNSNames: fqdn.DNSLookupDefaultResolver,\n\t\tAddGeneratedRules: func(generatedRules []*policyApi.Rule) error {\n\t\t\t\/\/ Insert the new rules into the policy repository. We need them to\n\t\t\t\/\/ replace the previous set. This requires the labels to match (including\n\t\t\t\/\/ the ToFQDN-UUID one).\n\t\t\t_, err := d.PolicyAdd(generatedRules, &AddOptions{Replace: true, Generated: true})\n\t\t\treturn err\n\t\t},\n\t\tPollerResponseNotify: func(lookupTime time.Time, qname string, response *fqdn.DNSIPRecords) {\n\t\t\t\/\/ Do nothing if this option is off\n\t\t\tif !option.Config.ToFQDNsEnablePollerEvents {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ FIXME: Not always true but we don't have the protocol information here\n\t\t\tprotocol := accesslog.TransportProtocol(u8proto.ProtoIDs[\"udp\"])\n\n\t\t\trecord := logger.LogRecord{\n\t\t\t\tLogRecord: accesslog.LogRecord{\n\t\t\t\t\tType:              accesslog.TypeResponse,\n\t\t\t\t\tObservationPoint:  accesslog.Ingress,\n\t\t\t\t\tIPVersion:         accesslog.VersionIPv4,\n\t\t\t\t\tTransportProtocol: protocol,\n\t\t\t\t\tTimestamp:         time.Now().UTC().Format(time.RFC3339Nano),\n\t\t\t\t\tNodeAddressInfo: accesslog.NodeAddressInfo{\n\t\t\t\t\t\tIPv4: node.GetExternalIPv4().String(),\n\t\t\t\t\t\tIPv6: node.GetIPv6().String(),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tlogger.LogTags.Verdict(accesslog.VerdictForwarded, \"DNSPoller\")(&record)\n\t\t\tlogger.LogTags.DNS(&accesslog.LogRecordDNS{\n\t\t\t\tQuery:             qname,\n\t\t\t\tIPs:               response.IPs,\n\t\t\t\tTTL:               uint32(response.TTL),\n\t\t\t\tCNAMEs:            nil,\n\t\t\t\tObservationSource: accesslog.DNSSourceAgentPoller,\n\t\t\t})(&record)\n\t\t\trecord.Log()\n\t\t}}\n\n\td.dnsRuleGen = fqdn.NewRuleGen(cfg)\n\td.dnsPoller = fqdn.NewDNSPoller(cfg, d.dnsRuleGen)\n\tif option.Config.ToFQDNsEnablePoller {\n\t\tfqdn.StartDNSPoller(d.dnsPoller)\n\t}\n\n\t\/\/ Prefill the cache with DNS lookups from restored endpoints. This is needed\n\t\/\/ to maintain continuity of which IPs are allowed.\n\t\/\/ Note: This is TTL aware, and expired data will not be used (e.g. when\n\t\/\/ restoring after a long delay).\n\tfor _, restoredEP := range restoredEndpoints.restored {\n\t\t\/\/ Upgrades from old ciliums have this nil\n\t\tif restoredEP.DNSHistory != nil {\n\t\t\tfqdn.DefaultDNSCache.UpdateFromCache(restoredEP.DNSHistory)\n\t\t}\n\t}\n\n\t\/\/ Once we stop returning errors from StartDNSProxy this should live in\n\t\/\/ StartProxySupport\n\tproxy.DefaultDNSProxy, err = dnsproxy.StartDNSProxy(\"\", uint16(option.Config.ToFQDNsProxyPort),\n\t\t\/\/ LookupEPByIP\n\t\tfunc(endpointIP net.IP) (endpointID string, err error) {\n\t\t\te := endpointmanager.LookupIPv4(endpointIP.String())\n\t\t\tif e == nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"Cannot find endpoint with IP %s\", endpointIP.String())\n\t\t\t}\n\n\t\t\treturn e.StringID(), nil\n\t\t},\n\t\t\/\/ NotifyOnDNSMsg handles DNS data in the daemon by emitting monitor\n\t\t\/\/ events, proxy metrics and storing DNS data in the DNS cache. This may\n\t\t\/\/ result in rule generation.\n\t\t\/\/ It will:\n\t\t\/\/ - Report a monitor error event and proxy metrics when the proxy sees an\n\t\t\/\/   error, and when it can't process something in this function\n\t\t\/\/ - Report the verdict in a monitor event and emit proxy metrics\n\t\t\/\/ - Insert the DNS data into the cache when msg is a DNS response and we\n\t\t\/\/   can lookup the endpoint related to it\n\t\t\/\/ srcAddr and dstAddr should match the packet reported on (i.e. the\n\t\t\/\/ endpoint is srcAddr for requests, and dstAddr for responses).\n\t\tfunc(lookupTime time.Time, srcAddr, dstAddr string, msg *dns.Msg, protocol string, allowed bool, proxyErr error) error {\n\t\t\tvar protoID = u8proto.ProtoIDs[strings.ToLower(protocol)]\n\n\t\t\tvar verdict accesslog.FlowVerdict\n\t\t\tvar reason string\n\t\t\tswitch {\n\t\t\tcase proxyErr != nil:\n\t\t\t\tverdict = accesslog.VerdictError\n\t\t\t\treason = \"Error: \" + proxyErr.Error()\n\t\t\tcase allowed:\n\t\t\t\tverdict = accesslog.VerdictForwarded\n\t\t\t\treason = \"Allowed by policy\"\n\t\t\tcase !allowed:\n\t\t\t\tverdict = accesslog.VerdictDenied\n\t\t\t\treason = \"Denied by policy\"\n\t\t\t}\n\n\t\t\tvar epAddr string     \/\/ the address of the endpoint that originated the request\n\t\t\tvar serverAddr string \/\/ the address of the DNS target\n\t\t\tvar ingress = msg.Response\n\t\t\tvar flowType accesslog.FlowType\n\t\t\tif ingress {\n\t\t\t\tflowType = accesslog.TypeResponse\n\t\t\t\tepAddr = dstAddr\n\t\t\t\tserverAddr = srcAddr\n\t\t\t} else {\n\t\t\t\tflowType = accesslog.TypeRequest\n\t\t\t\tepAddr = srcAddr\n\t\t\t\tserverAddr = dstAddr\n\t\t\t}\n\n\t\t\tvar serverPort int\n\t\t\t_, serverPortStr, err := net.SplitHostPort(serverAddr)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).Error(\"cannot extract endpoint IP from DNS request\")\n\t\t\t} else {\n\t\t\t\tif serverPort, err = strconv.Atoi(serverPortStr); err != nil {\n\t\t\t\t\tlog.WithError(err).WithField(logfields.Port, serverPortStr).Error(\"cannot parse destination port\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar ep *endpoint.Endpoint\n\t\t\tepIP, _, err := net.SplitHostPort(epAddr)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).Error(\"cannot extract endpoint IP from DNS request\")\n\t\t\t\tep.UpdateProxyStatistics(\"dns\", uint16(serverPort), ingress, !ingress, accesslog.VerdictError)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tep = endpointmanager.LookupIPv4(epIP)\n\t\t\tif ep == nil {\n\t\t\t\t\/\/ This is a hard fail. We cannot proceed because record.Log requires a\n\t\t\t\t\/\/ non-nil ep, and we also don't want to insert this data into the\n\t\t\t\t\/\/ cache if we don't know that an endpoint asked for it (this is\n\t\t\t\t\/\/ asserted via ep != nil here and msg.Response && msg.Rcode ==\n\t\t\t\t\/\/ dns.RcodeSuccess below).\n\t\t\t\terr := fmt.Errorf(\"Cannot find matching endpoint for IPs %s or %s\", srcAddr, dstAddr)\n\t\t\t\tlog.WithError(err).Error(\"cannot find matching endpoint\")\n\t\t\t\tep.UpdateProxyStatistics(\"dns\", uint16(serverPort), ingress, !ingress, accesslog.VerdictError)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tqname, responseIPs, TTL, CNAMEs, err := dnsproxy.ExtractMsgDetails(msg)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ This error is ok because all these values are used for reporting, or filling in the cache.\n\t\t\t\tlog.WithError(err).Error(\"cannot extract DNS message details\")\n\t\t\t}\n\n\t\t\tep.UpdateProxyStatistics(\"dns\", uint16(serverPort), ingress, !ingress, verdict)\n\t\t\trecord := logger.NewLogRecord(proxy.DefaultEndpointInfoRegistry, ep, flowType, ingress,\n\t\t\t\tfunc(lr *logger.LogRecord) { lr.LogRecord.TransportProtocol = accesslog.TransportProtocol(protoID) },\n\t\t\t\tlogger.LogTags.Verdict(verdict, reason),\n\t\t\t\tlogger.LogTags.Addressing(logger.AddressingInfo{\n\t\t\t\t\tSrcIPPort:   srcAddr,\n\t\t\t\t\tDstIPPort:   dstAddr,\n\t\t\t\t\tSrcIdentity: 0, \/\/ 0 more correctly finds src and dst EP data\n\t\t\t\t}),\n\t\t\t\tlogger.LogTags.DNS(&accesslog.LogRecordDNS{\n\t\t\t\t\tQuery:             qname,\n\t\t\t\t\tIPs:               responseIPs,\n\t\t\t\t\tTTL:               TTL,\n\t\t\t\t\tCNAMEs:            CNAMEs,\n\t\t\t\t\tObservationSource: accesslog.DNSSourceProxy,\n\t\t\t\t}),\n\t\t\t)\n\t\t\trecord.Log()\n\n\t\t\tif msg.Response && msg.Rcode == dns.RcodeSuccess {\n\t\t\t\t\/\/ This must happen before the ruleGen update below, to ensure that\n\t\t\t\t\/\/ this data is included in the serialized Endpoint object.\n\t\t\t\t\/\/ Note: We need to fixup minTTL to be consistent with how we insert it\n\t\t\t\t\/\/ elsewhere i.e. we don't want to lose the lower bound for DNS data\n\t\t\t\t\/\/ TTL if we reboot twice.\n\t\t\t\tlog.WithField(logfields.EndpointID, ep.ID).Debug(\"Recording DNS lookup in endpoint specific cache\")\n\t\t\t\teffectiveTTL := int(TTL)\n\t\t\t\tif effectiveTTL < option.Config.ToFQDNsMinTTL {\n\t\t\t\t\teffectiveTTL = option.Config.ToFQDNsMinTTL\n\t\t\t\t}\n\t\t\t\tep.DNSHistory.Update(lookupTime, qname, responseIPs, effectiveTTL)\n\t\t\t\tlog.Debug(\"Updating DNS name in cache from response to to query\")\n\t\t\t\terr = d.dnsRuleGen.UpdateGenerateDNS(lookupTime, map[string]*fqdn.DNSIPRecords{\n\t\t\t\t\tqname: {\n\t\t\t\t\t\tIPs: responseIPs,\n\t\t\t\t\t\tTTL: int(effectiveTTL),\n\t\t\t\t\t}})\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.WithError(err).Error(\"error updating internal DNS cache for rule generation\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\tproxy.DefaultDNSProxy.SetRejectReply(option.Config.FQDNRejectResponse)\n\treturn err \/\/ filled by StartDNSProxy\n}\n\ntype getFqdnCache struct {\n\tdaemon *Daemon\n}\n\nfunc NewGetFqdnCacheHandler(d *Daemon) GetFqdnCacheHandler {\n\treturn &getFqdnCache{daemon: d}\n}\n\nfunc (h *getFqdnCache) Handle(params GetFqdnCacheParams) middleware.Responder {\n\t\/\/ endpoints we want data from\n\tendpoints := endpointmanager.GetEndpoints()\n\n\tCIDRStr := \"\"\n\tif params.Cidr != nil {\n\t\tCIDRStr = *params.Cidr\n\t}\n\n\tmatchPatternStr := \"\"\n\tif params.Matchpattern != nil {\n\t\tmatchPatternStr = *params.Matchpattern\n\t}\n\n\tlookups, err := extractDNSLookups(endpoints, CIDRStr, matchPatternStr)\n\tswitch {\n\tcase err != nil:\n\t\treturn api.Error(GetFqdnCacheBadRequestCode, err)\n\tcase len(lookups) == 0:\n\t\treturn NewGetFqdnCacheIDNotFound()\n\t}\n\n\treturn NewGetFqdnCacheIDOK().WithPayload(lookups)\n}\n\ntype getFqdnCacheID struct {\n\tdaemon *Daemon\n}\n\nfunc NewGetFqdnCacheIDHandler(d *Daemon) GetFqdnCacheIDHandler {\n\treturn &getFqdnCacheID{daemon: d}\n}\n\nfunc (h *getFqdnCacheID) Handle(params GetFqdnCacheIDParams) middleware.Responder {\n\tvar endpoints []*endpoint.Endpoint\n\tif params.ID != \"\" {\n\t\tep, err := endpointmanager.Lookup(params.ID)\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\treturn api.Error(GetFqdnCacheIDBadRequestCode, err)\n\t\tcase ep == nil:\n\t\t\treturn api.Error(GetFqdnCacheIDNotFoundCode, fmt.Errorf(\"Cannot find endpoint %s\", params.ID))\n\t\tdefault:\n\t\t\tendpoints = []*endpoint.Endpoint{ep}\n\t\t}\n\t}\n\n\tCIDRStr := \"\"\n\tif params.Cidr != nil {\n\t\tCIDRStr = *params.Cidr\n\t}\n\n\tmatchPatternStr := \"\"\n\tif params.Matchpattern != nil {\n\t\tmatchPatternStr = *params.Matchpattern\n\t}\n\n\tlookups, err := extractDNSLookups(endpoints, CIDRStr, matchPatternStr)\n\tswitch {\n\tcase err != nil:\n\t\treturn api.Error(GetFqdnCacheBadRequestCode, err)\n\tcase len(lookups) == 0:\n\t\treturn NewGetFqdnCacheIDNotFound()\n\t}\n\n\treturn NewGetFqdnCacheIDOK().WithPayload(lookups)\n}\n\n\/\/ extractDNSLookups returns API models.DNSLookup copies of DNS data in each\n\/\/ endpoint's DNSHistory. These are filtered by CIDRStr and matchPatternStr if\n\/\/ they are non-empty.\nfunc extractDNSLookups(endpoints []*endpoint.Endpoint, CIDRStr, matchPatternStr string) (lookups []*models.DNSLookup, err error) {\n\tcidrMatcher := func(ip net.IP) bool { return true }\n\tif CIDRStr != \"\" {\n\t\t_, cidr, err := net.ParseCIDR(CIDRStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcidrMatcher = func(ip net.IP) bool { return cidr.Contains(ip) }\n\t}\n\n\tnameMatcher := func(name string) bool { return true }\n\tif matchPatternStr != \"\" {\n\t\tmatcher, err := matchpattern.Validate(matchPatternStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnameMatcher = func(name string) bool { return matcher.MatchString(name) }\n\t}\n\n\tfor _, ep := range endpoints {\n\t\tfor _, lookup := range ep.DNSHistory.Dump() {\n\t\t\tif !nameMatcher(lookup.Name) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ The API model needs strings\n\t\t\tIPStrings := make([]string, 0, len(lookup.IPs))\n\n\t\t\t\/\/ only proceed if any IP matches the cidr selector\n\t\t\tanIPMatches := false\n\t\t\tfor _, ip := range lookup.IPs {\n\t\t\t\tanIPMatches = anIPMatches || cidrMatcher(ip)\n\t\t\t\tIPStrings = append(IPStrings, ip.String())\n\t\t\t}\n\t\t\tif !anIPMatches {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlookups = append(lookups, &models.DNSLookup{\n\t\t\t\tFqdn:           lookup.Name,\n\t\t\t\tIps:            IPStrings,\n\t\t\t\tLookupTime:     strfmt.DateTime(lookup.LookupTime),\n\t\t\t\tTTL:            int64(lookup.TTL),\n\t\t\t\tExpirationTime: strfmt.DateTime(lookup.ExpirationTime),\n\t\t\t\tEndpointID:     int64(ep.ID),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn lookups, nil\n}\n<commit_msg>fqdn: Do not report stats on nil Endpoint<commit_after>\/\/ Copyright 2019 Authors of Cilium\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/cilium\/cilium\/api\/v1\/models\"\n\t. \"github.com\/cilium\/cilium\/api\/v1\/server\/restapi\/policy\"\n\t\"github.com\/cilium\/cilium\/pkg\/api\"\n\t\"github.com\/cilium\/cilium\/pkg\/endpoint\"\n\t\"github.com\/cilium\/cilium\/pkg\/endpointmanager\"\n\t\"github.com\/cilium\/cilium\/pkg\/fqdn\"\n\t\"github.com\/cilium\/cilium\/pkg\/fqdn\/dnsproxy\"\n\t\"github.com\/cilium\/cilium\/pkg\/fqdn\/matchpattern\"\n\t\"github.com\/cilium\/cilium\/pkg\/logging\/logfields\"\n\t\"github.com\/cilium\/cilium\/pkg\/node\"\n\t\"github.com\/cilium\/cilium\/pkg\/option\"\n\tpolicyApi \"github.com\/cilium\/cilium\/pkg\/policy\/api\"\n\t\"github.com\/cilium\/cilium\/pkg\/proxy\"\n\t\"github.com\/cilium\/cilium\/pkg\/proxy\/accesslog\"\n\t\"github.com\/cilium\/cilium\/pkg\/proxy\/logger\"\n\t\"github.com\/cilium\/cilium\/pkg\/u8proto\"\n\t\"github.com\/go-openapi\/runtime\/middleware\"\n\t\"github.com\/go-openapi\/strfmt\"\n\n\t\"github.com\/miekg\/dns\"\n)\n\n\/\/ bootstrapFQDN initializes the toFQDNs related subsystems: DNSPoller,\n\/\/ d.dnsRuleGen, and the DNS proxy.\n\/\/ dnsRuleGen and DNSPoller will use the default resolver and, implicitly, the\n\/\/ default DNS cache. The proxy binds to all interfaces, and uses the\n\/\/ configured DNS proxy port (this may be 0 and so OS-assigned).\nfunc (d *Daemon) bootstrapFQDN(restoredEndpoints *endpointRestoreState) (err error) {\n\tcfg := fqdn.Config{\n\t\tMinTTL:         option.Config.ToFQDNsMinTTL,\n\t\tCache:          fqdn.DefaultDNSCache,\n\t\tLookupDNSNames: fqdn.DNSLookupDefaultResolver,\n\t\tAddGeneratedRules: func(generatedRules []*policyApi.Rule) error {\n\t\t\t\/\/ Insert the new rules into the policy repository. We need them to\n\t\t\t\/\/ replace the previous set. This requires the labels to match (including\n\t\t\t\/\/ the ToFQDN-UUID one).\n\t\t\t_, err := d.PolicyAdd(generatedRules, &AddOptions{Replace: true, Generated: true})\n\t\t\treturn err\n\t\t},\n\t\tPollerResponseNotify: func(lookupTime time.Time, qname string, response *fqdn.DNSIPRecords) {\n\t\t\t\/\/ Do nothing if this option is off\n\t\t\tif !option.Config.ToFQDNsEnablePollerEvents {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ FIXME: Not always true but we don't have the protocol information here\n\t\t\tprotocol := accesslog.TransportProtocol(u8proto.ProtoIDs[\"udp\"])\n\n\t\t\trecord := logger.LogRecord{\n\t\t\t\tLogRecord: accesslog.LogRecord{\n\t\t\t\t\tType:              accesslog.TypeResponse,\n\t\t\t\t\tObservationPoint:  accesslog.Ingress,\n\t\t\t\t\tIPVersion:         accesslog.VersionIPv4,\n\t\t\t\t\tTransportProtocol: protocol,\n\t\t\t\t\tTimestamp:         time.Now().UTC().Format(time.RFC3339Nano),\n\t\t\t\t\tNodeAddressInfo: accesslog.NodeAddressInfo{\n\t\t\t\t\t\tIPv4: node.GetExternalIPv4().String(),\n\t\t\t\t\t\tIPv6: node.GetIPv6().String(),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tlogger.LogTags.Verdict(accesslog.VerdictForwarded, \"DNSPoller\")(&record)\n\t\t\tlogger.LogTags.DNS(&accesslog.LogRecordDNS{\n\t\t\t\tQuery:             qname,\n\t\t\t\tIPs:               response.IPs,\n\t\t\t\tTTL:               uint32(response.TTL),\n\t\t\t\tCNAMEs:            nil,\n\t\t\t\tObservationSource: accesslog.DNSSourceAgentPoller,\n\t\t\t})(&record)\n\t\t\trecord.Log()\n\t\t}}\n\n\td.dnsRuleGen = fqdn.NewRuleGen(cfg)\n\td.dnsPoller = fqdn.NewDNSPoller(cfg, d.dnsRuleGen)\n\tif option.Config.ToFQDNsEnablePoller {\n\t\tfqdn.StartDNSPoller(d.dnsPoller)\n\t}\n\n\t\/\/ Prefill the cache with DNS lookups from restored endpoints. This is needed\n\t\/\/ to maintain continuity of which IPs are allowed.\n\t\/\/ Note: This is TTL aware, and expired data will not be used (e.g. when\n\t\/\/ restoring after a long delay).\n\tfor _, restoredEP := range restoredEndpoints.restored {\n\t\t\/\/ Upgrades from old ciliums have this nil\n\t\tif restoredEP.DNSHistory != nil {\n\t\t\tfqdn.DefaultDNSCache.UpdateFromCache(restoredEP.DNSHistory)\n\t\t}\n\t}\n\n\t\/\/ Once we stop returning errors from StartDNSProxy this should live in\n\t\/\/ StartProxySupport\n\tproxy.DefaultDNSProxy, err = dnsproxy.StartDNSProxy(\"\", uint16(option.Config.ToFQDNsProxyPort),\n\t\t\/\/ LookupEPByIP\n\t\tfunc(endpointIP net.IP) (endpointID string, err error) {\n\t\t\te := endpointmanager.LookupIPv4(endpointIP.String())\n\t\t\tif e == nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"Cannot find endpoint with IP %s\", endpointIP.String())\n\t\t\t}\n\n\t\t\treturn e.StringID(), nil\n\t\t},\n\t\t\/\/ NotifyOnDNSMsg handles DNS data in the daemon by emitting monitor\n\t\t\/\/ events, proxy metrics and storing DNS data in the DNS cache. This may\n\t\t\/\/ result in rule generation.\n\t\t\/\/ It will:\n\t\t\/\/ - Report a monitor error event and proxy metrics when the proxy sees an\n\t\t\/\/   error, and when it can't process something in this function\n\t\t\/\/ - Report the verdict in a monitor event and emit proxy metrics\n\t\t\/\/ - Insert the DNS data into the cache when msg is a DNS response and we\n\t\t\/\/   can lookup the endpoint related to it\n\t\t\/\/ srcAddr and dstAddr should match the packet reported on (i.e. the\n\t\t\/\/ endpoint is srcAddr for requests, and dstAddr for responses).\n\t\tfunc(lookupTime time.Time, srcAddr, dstAddr string, msg *dns.Msg, protocol string, allowed bool, proxyErr error) error {\n\t\t\tvar protoID = u8proto.ProtoIDs[strings.ToLower(protocol)]\n\n\t\t\tvar verdict accesslog.FlowVerdict\n\t\t\tvar reason string\n\t\t\tswitch {\n\t\t\tcase proxyErr != nil:\n\t\t\t\tverdict = accesslog.VerdictError\n\t\t\t\treason = \"Error: \" + proxyErr.Error()\n\t\t\tcase allowed:\n\t\t\t\tverdict = accesslog.VerdictForwarded\n\t\t\t\treason = \"Allowed by policy\"\n\t\t\tcase !allowed:\n\t\t\t\tverdict = accesslog.VerdictDenied\n\t\t\t\treason = \"Denied by policy\"\n\t\t\t}\n\n\t\t\tvar epAddr string     \/\/ the address of the endpoint that originated the request\n\t\t\tvar serverAddr string \/\/ the address of the DNS target\n\t\t\tvar ingress = msg.Response\n\t\t\tvar flowType accesslog.FlowType\n\t\t\tif ingress {\n\t\t\t\tflowType = accesslog.TypeResponse\n\t\t\t\tepAddr = dstAddr\n\t\t\t\tserverAddr = srcAddr\n\t\t\t} else {\n\t\t\t\tflowType = accesslog.TypeRequest\n\t\t\t\tepAddr = srcAddr\n\t\t\t\tserverAddr = dstAddr\n\t\t\t}\n\n\t\t\tvar serverPort int\n\t\t\t_, serverPortStr, err := net.SplitHostPort(serverAddr)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).Error(\"cannot extract endpoint IP from DNS request\")\n\t\t\t} else {\n\t\t\t\tif serverPort, err = strconv.Atoi(serverPortStr); err != nil {\n\t\t\t\t\tlog.WithError(err).WithField(logfields.Port, serverPortStr).Error(\"cannot parse destination port\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar ep *endpoint.Endpoint\n\t\t\tepIP, _, err := net.SplitHostPort(epAddr)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).Error(\"cannot extract endpoint IP from DNS request\")\n\t\t\t\tep.UpdateProxyStatistics(\"dns\", uint16(serverPort), ingress, !ingress, accesslog.VerdictError)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tep = endpointmanager.LookupIPv4(epIP)\n\t\t\tif ep == nil {\n\t\t\t\t\/\/ This is a hard fail. We cannot proceed because record.Log requires a\n\t\t\t\t\/\/ non-nil ep, and we also don't want to insert this data into the\n\t\t\t\t\/\/ cache if we don't know that an endpoint asked for it (this is\n\t\t\t\t\/\/ asserted via ep != nil here and msg.Response && msg.Rcode ==\n\t\t\t\t\/\/ dns.RcodeSuccess below).\n\t\t\t\terr := fmt.Errorf(\"Cannot find matching endpoint for IPs %s or %s\", srcAddr, dstAddr)\n\t\t\t\tlog.WithError(err).Error(\"cannot find matching endpoint\")\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tqname, responseIPs, TTL, CNAMEs, err := dnsproxy.ExtractMsgDetails(msg)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ This error is ok because all these values are used for reporting, or filling in the cache.\n\t\t\t\tlog.WithError(err).Error(\"cannot extract DNS message details\")\n\t\t\t}\n\n\t\t\tep.UpdateProxyStatistics(\"dns\", uint16(serverPort), ingress, !ingress, verdict)\n\t\t\trecord := logger.NewLogRecord(proxy.DefaultEndpointInfoRegistry, ep, flowType, ingress,\n\t\t\t\tfunc(lr *logger.LogRecord) { lr.LogRecord.TransportProtocol = accesslog.TransportProtocol(protoID) },\n\t\t\t\tlogger.LogTags.Verdict(verdict, reason),\n\t\t\t\tlogger.LogTags.Addressing(logger.AddressingInfo{\n\t\t\t\t\tSrcIPPort:   srcAddr,\n\t\t\t\t\tDstIPPort:   dstAddr,\n\t\t\t\t\tSrcIdentity: 0, \/\/ 0 more correctly finds src and dst EP data\n\t\t\t\t}),\n\t\t\t\tlogger.LogTags.DNS(&accesslog.LogRecordDNS{\n\t\t\t\t\tQuery:             qname,\n\t\t\t\t\tIPs:               responseIPs,\n\t\t\t\t\tTTL:               TTL,\n\t\t\t\t\tCNAMEs:            CNAMEs,\n\t\t\t\t\tObservationSource: accesslog.DNSSourceProxy,\n\t\t\t\t}),\n\t\t\t)\n\t\t\trecord.Log()\n\n\t\t\tif msg.Response && msg.Rcode == dns.RcodeSuccess {\n\t\t\t\t\/\/ This must happen before the ruleGen update below, to ensure that\n\t\t\t\t\/\/ this data is included in the serialized Endpoint object.\n\t\t\t\t\/\/ Note: We need to fixup minTTL to be consistent with how we insert it\n\t\t\t\t\/\/ elsewhere i.e. we don't want to lose the lower bound for DNS data\n\t\t\t\t\/\/ TTL if we reboot twice.\n\t\t\t\tlog.WithField(logfields.EndpointID, ep.ID).Debug(\"Recording DNS lookup in endpoint specific cache\")\n\t\t\t\teffectiveTTL := int(TTL)\n\t\t\t\tif effectiveTTL < option.Config.ToFQDNsMinTTL {\n\t\t\t\t\teffectiveTTL = option.Config.ToFQDNsMinTTL\n\t\t\t\t}\n\t\t\t\tep.DNSHistory.Update(lookupTime, qname, responseIPs, effectiveTTL)\n\t\t\t\tlog.Debug(\"Updating DNS name in cache from response to to query\")\n\t\t\t\terr = d.dnsRuleGen.UpdateGenerateDNS(lookupTime, map[string]*fqdn.DNSIPRecords{\n\t\t\t\t\tqname: {\n\t\t\t\t\t\tIPs: responseIPs,\n\t\t\t\t\t\tTTL: int(effectiveTTL),\n\t\t\t\t\t}})\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.WithError(err).Error(\"error updating internal DNS cache for rule generation\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\tproxy.DefaultDNSProxy.SetRejectReply(option.Config.FQDNRejectResponse)\n\treturn err \/\/ filled by StartDNSProxy\n}\n\ntype getFqdnCache struct {\n\tdaemon *Daemon\n}\n\nfunc NewGetFqdnCacheHandler(d *Daemon) GetFqdnCacheHandler {\n\treturn &getFqdnCache{daemon: d}\n}\n\nfunc (h *getFqdnCache) Handle(params GetFqdnCacheParams) middleware.Responder {\n\t\/\/ endpoints we want data from\n\tendpoints := endpointmanager.GetEndpoints()\n\n\tCIDRStr := \"\"\n\tif params.Cidr != nil {\n\t\tCIDRStr = *params.Cidr\n\t}\n\n\tmatchPatternStr := \"\"\n\tif params.Matchpattern != nil {\n\t\tmatchPatternStr = *params.Matchpattern\n\t}\n\n\tlookups, err := extractDNSLookups(endpoints, CIDRStr, matchPatternStr)\n\tswitch {\n\tcase err != nil:\n\t\treturn api.Error(GetFqdnCacheBadRequestCode, err)\n\tcase len(lookups) == 0:\n\t\treturn NewGetFqdnCacheIDNotFound()\n\t}\n\n\treturn NewGetFqdnCacheIDOK().WithPayload(lookups)\n}\n\ntype getFqdnCacheID struct {\n\tdaemon *Daemon\n}\n\nfunc NewGetFqdnCacheIDHandler(d *Daemon) GetFqdnCacheIDHandler {\n\treturn &getFqdnCacheID{daemon: d}\n}\n\nfunc (h *getFqdnCacheID) Handle(params GetFqdnCacheIDParams) middleware.Responder {\n\tvar endpoints []*endpoint.Endpoint\n\tif params.ID != \"\" {\n\t\tep, err := endpointmanager.Lookup(params.ID)\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\treturn api.Error(GetFqdnCacheIDBadRequestCode, err)\n\t\tcase ep == nil:\n\t\t\treturn api.Error(GetFqdnCacheIDNotFoundCode, fmt.Errorf(\"Cannot find endpoint %s\", params.ID))\n\t\tdefault:\n\t\t\tendpoints = []*endpoint.Endpoint{ep}\n\t\t}\n\t}\n\n\tCIDRStr := \"\"\n\tif params.Cidr != nil {\n\t\tCIDRStr = *params.Cidr\n\t}\n\n\tmatchPatternStr := \"\"\n\tif params.Matchpattern != nil {\n\t\tmatchPatternStr = *params.Matchpattern\n\t}\n\n\tlookups, err := extractDNSLookups(endpoints, CIDRStr, matchPatternStr)\n\tswitch {\n\tcase err != nil:\n\t\treturn api.Error(GetFqdnCacheBadRequestCode, err)\n\tcase len(lookups) == 0:\n\t\treturn NewGetFqdnCacheIDNotFound()\n\t}\n\n\treturn NewGetFqdnCacheIDOK().WithPayload(lookups)\n}\n\n\/\/ extractDNSLookups returns API models.DNSLookup copies of DNS data in each\n\/\/ endpoint's DNSHistory. These are filtered by CIDRStr and matchPatternStr if\n\/\/ they are non-empty.\nfunc extractDNSLookups(endpoints []*endpoint.Endpoint, CIDRStr, matchPatternStr string) (lookups []*models.DNSLookup, err error) {\n\tcidrMatcher := func(ip net.IP) bool { return true }\n\tif CIDRStr != \"\" {\n\t\t_, cidr, err := net.ParseCIDR(CIDRStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcidrMatcher = func(ip net.IP) bool { return cidr.Contains(ip) }\n\t}\n\n\tnameMatcher := func(name string) bool { return true }\n\tif matchPatternStr != \"\" {\n\t\tmatcher, err := matchpattern.Validate(matchPatternStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnameMatcher = func(name string) bool { return matcher.MatchString(name) }\n\t}\n\n\tfor _, ep := range endpoints {\n\t\tfor _, lookup := range ep.DNSHistory.Dump() {\n\t\t\tif !nameMatcher(lookup.Name) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ The API model needs strings\n\t\t\tIPStrings := make([]string, 0, len(lookup.IPs))\n\n\t\t\t\/\/ only proceed if any IP matches the cidr selector\n\t\t\tanIPMatches := false\n\t\t\tfor _, ip := range lookup.IPs {\n\t\t\t\tanIPMatches = anIPMatches || cidrMatcher(ip)\n\t\t\t\tIPStrings = append(IPStrings, ip.String())\n\t\t\t}\n\t\t\tif !anIPMatches {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlookups = append(lookups, &models.DNSLookup{\n\t\t\t\tFqdn:           lookup.Name,\n\t\t\t\tIps:            IPStrings,\n\t\t\t\tLookupTime:     strfmt.DateTime(lookup.LookupTime),\n\t\t\t\tTTL:            int64(lookup.TTL),\n\t\t\t\tExpirationTime: strfmt.DateTime(lookup.ExpirationTime),\n\t\t\t\tEndpointID:     int64(ep.ID),\n\t\t\t})\n\t\t}\n\t}\n\n\treturn lookups, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package dalga\n\n\/\/ TODO backoff\n\nimport (\n\t\"database\/sql\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/cenkalti\/dalga\/vendor\/github.com\/go-sql-driver\/mysql\"\n)\n\nvar debugging = flag.Bool(\"debug\", false, \"turn on debug messages\")\n\nfunc debug(args ...interface{}) {\n\tif *debugging {\n\t\tlog.Println(args...)\n\t}\n}\n\ntype Dalga struct {\n\tconfig   Config\n\tdb       *sql.DB\n\ttable    *table\n\tlistener net.Listener\n\tclient   http.Client\n\t\/\/ to wake up publisher when a new job is scheduled or cancelled\n\tnotify chan struct{}\n\t\/\/ will be closed when dalga is ready to accept requests\n\tready chan struct{}\n\t\/\/ will be closed by Shutdown method\n\tshutdown chan struct{}\n\t\/\/ to stop publisher goroutine\n\tstopPublisher chan struct{}\n\t\/\/ will be closed when publisher goroutine is stopped\n\tpublisherStopped chan struct{}\n}\n\nfunc New(config Config) *Dalga {\n\td := &Dalga{\n\t\tconfig:           config,\n\t\tnotify:           make(chan struct{}, 1),\n\t\tready:            make(chan struct{}),\n\t\tshutdown:         make(chan struct{}),\n\t\tstopPublisher:    make(chan struct{}),\n\t\tpublisherStopped: make(chan struct{}),\n\t}\n\td.client.Timeout = time.Duration(config.Endpoint.Timeout) * time.Second\n\treturn d\n}\n\n\/\/ Run Dalga. This function is blocking. Returns nil if Shutdown is called.\nfunc (d *Dalga) Run() error {\n\tif err := d.connectDB(); err != nil {\n\t\treturn err\n\t}\n\tdefer d.db.Close()\n\n\tvar err error\n\td.listener, err = net.Listen(\"tcp\", d.config.Listen.Addr())\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening\", d.listener.Addr())\n\n\tclose(d.ready)\n\n\tgo d.publisher()\n\tdefer func() {\n\t\tclose(d.stopPublisher)\n\t\t<-d.publisherStopped\n\t}()\n\n\tif err = d.serveHTTP(); err != nil {\n\t\tselect {\n\t\tcase _, ok := <-d.shutdown:\n\t\t\tif !ok {\n\t\t\t\t\/\/ shutdown in progress, do not return error\n\t\t\t\treturn nil\n\t\t\t}\n\t\tdefault:\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ Shutdown running Dalga.\nfunc (d *Dalga) Shutdown() error {\n\tclose(d.shutdown)\n\treturn d.listener.Close()\n}\n\n\/\/ NotifyReady returns a channel that will be closed when Dalga is running.\nfunc (d *Dalga) NotifyReady() <-chan struct{} {\n\treturn d.ready\n}\n\nfunc (d *Dalga) connectDB() error {\n\tvar err error\n\td.db, err = sql.Open(\"mysql\", d.config.MySQL.DSN())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = d.db.Ping(); err != nil {\n\t\treturn err\n\t}\n\tlog.Print(\"Connected to MySQL\")\n\td.table = &table{d.db, d.config.MySQL.Table}\n\treturn nil\n}\n\n\/\/ CreateTable creates the table for storing jobs.\nfunc (d *Dalga) CreateTable() error {\n\tdb, err := sql.Open(\"mysql\", d.config.MySQL.DSN())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\tt := &table{db, d.config.MySQL.Table}\n\treturn t.Create()\n}\n\n\/\/ GetJob returns the job with description routing key.\nfunc (d *Dalga) GetJob(description, routingKey string) (*Job, error) {\n\treturn d.table.Get(description, routingKey)\n}\n\n\/\/ ScheduleJob inserts a new job to the table or replaces existing one.\n\/\/ Returns the created or replaced job.\nfunc (d *Dalga) ScheduleJob(description, routingKey string, interval uint32, oneOff bool) (*Job, error) {\n\tjob := newJob(description, routingKey, interval, oneOff)\n\terr := d.table.Insert(job)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td.notifyPublisher(\"new job\")\n\tdebug(\"Job is scheduled:\", job)\n\treturn job, nil\n}\n\n\/\/ TriggerJob publishes the job to RabbitMQ immediately and resets the next run time of the job.\nfunc (d *Dalga) TriggerJob(description, routingKey string) (*Job, error) {\n\tjob, err := d.GetJob(description, routingKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjob.NextRun = time.Now().UTC()\n\tif err := d.table.Insert(job); err != nil {\n\t\treturn nil, err\n\t}\n\td.notifyPublisher(\"job is triggered\")\n\tdebug(\"Job is triggered:\", job)\n\treturn job, nil\n}\n\n\/\/ CancelJob deletes the job with description and routing key.\nfunc (d *Dalga) CancelJob(description, routingKey string) error {\n\terr := d.table.Delete(description, routingKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.notifyPublisher(\"job cancelled\")\n\tdebug(\"Job is cancelled\")\n\treturn nil\n}\n\nfunc (d *Dalga) notifyPublisher(debugMessage string) {\n\tselect {\n\tcase d.notify <- struct{}{}:\n\t\tdebug(\"notifying publisher:\", debugMessage)\n\tdefault:\n\t}\n}\n\n\/\/ publisher runs a loop that reads the next Job from the queue and publishes it.\nfunc (d *Dalga) publisher() {\n\tdefer close(d.publisherStopped)\n\n\tfor {\n\t\tdebug(\"---\")\n\n\t\tvar after <-chan time.Time\n\n\t\tjob, err := d.table.Front()\n\t\tif err != nil {\n\t\t\tif err == sql.ErrNoRows {\n\t\t\t\tdebug(\"No scheduled jobs in the table\")\n\t\t\t} else if myErr, ok := err.(*mysql.MySQLError); ok && myErr.Number == 1146 {\n\t\t\t\t\/\/ Table doesn't exist\n\t\t\t\tlog.Fatal(myErr)\n\t\t\t} else {\n\t\t\t\tlog.Print(err)\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tremaining := job.Remaining()\n\t\t\tafter = time.After(remaining)\n\t\t\tdebug(\"Next job:\", job, \"Remaining:\", remaining)\n\t\t}\n\n\t\t\/\/ Sleep until the next job's run time or the webserver's wakes us up.\n\t\tselect {\n\t\tcase <-after:\n\t\t\tdebug(\"Job sleep time finished\")\n\t\t\tif err = d.publish(job); err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t}\n\t\tcase <-d.notify:\n\t\t\tdebug(\"Woken up from sleep by notification\")\n\t\t\tcontinue\n\t\tcase <-d.stopPublisher:\n\t\t\tdebug(\"Came quit message\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ publish makes a POST request to the endpoint and updates the Job's next run time.\nfunc (d *Dalga) publish(j *Job) error {\n\tdebug(\"publish\", *j)\n\n\tvar add time.Duration\n\tif j.Interval == 0 {\n\t\tadd = time.Duration(d.config.Endpoint.Timeout) * time.Second\n\t} else {\n\t\tadd = j.Interval\n\t}\n\n\tj.NextRun = time.Now().UTC().Add(add)\n\n\tif err := d.table.UpdateNextRun(j); err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\tif err := d.postJob(j); err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t}()\n\n\treturn nil\n}\n\nfunc (d *Dalga) postJob(j *Job) error {\n\tresp, err := d.client.Post(d.config.Endpoint.BaseURL+j.Path, \"text\/plain\", strings.NewReader(j.Body))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"endpoint error: %d\", resp.StatusCode)\n\t}\n\n\tif j.Interval == 0 {\n\t\tdebug(\"deleting one-off job\")\n\t\treturn d.table.Delete(j.Path, j.Body)\n\t}\n\n\treturn nil\n}\n<commit_msg>Do not do multiple POSTs for the same job at the same time<commit_after>package dalga\n\n\/\/ TODO backoff\n\nimport (\n\t\"database\/sql\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/cenkalti\/dalga\/vendor\/github.com\/go-sql-driver\/mysql\"\n)\n\nvar debugging = flag.Bool(\"debug\", false, \"turn on debug messages\")\n\nfunc debug(args ...interface{}) {\n\tif *debugging {\n\t\tlog.Println(args...)\n\t}\n}\n\ntype Dalga struct {\n\tconfig     Config\n\tdb         *sql.DB\n\ttable      *table\n\tlistener   net.Listener\n\tclient     http.Client\n\tactiveJobs map[string]struct{}\n\tm          sync.Mutex\n\t\/\/ to wake up publisher when a new job is scheduled or cancelled\n\tnotify chan struct{}\n\t\/\/ will be closed when dalga is ready to accept requests\n\tready chan struct{}\n\t\/\/ will be closed by Shutdown method\n\tshutdown chan struct{}\n\t\/\/ to stop publisher goroutine\n\tstopPublisher chan struct{}\n\t\/\/ will be closed when publisher goroutine is stopped\n\tpublisherStopped chan struct{}\n}\n\nfunc New(config Config) *Dalga {\n\td := &Dalga{\n\t\tconfig:           config,\n\t\tactiveJobs:       make(map[string]struct{}),\n\t\tnotify:           make(chan struct{}, 1),\n\t\tready:            make(chan struct{}),\n\t\tshutdown:         make(chan struct{}),\n\t\tstopPublisher:    make(chan struct{}),\n\t\tpublisherStopped: make(chan struct{}),\n\t}\n\td.client.Timeout = time.Duration(config.Endpoint.Timeout) * time.Second\n\treturn d\n}\n\n\/\/ Run Dalga. This function is blocking. Returns nil if Shutdown is called.\nfunc (d *Dalga) Run() error {\n\tif err := d.connectDB(); err != nil {\n\t\treturn err\n\t}\n\tdefer d.db.Close()\n\n\tvar err error\n\td.listener, err = net.Listen(\"tcp\", d.config.Listen.Addr())\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Println(\"Listening\", d.listener.Addr())\n\n\tclose(d.ready)\n\n\tgo d.publisher()\n\tdefer func() {\n\t\tclose(d.stopPublisher)\n\t\t<-d.publisherStopped\n\t}()\n\n\tif err = d.serveHTTP(); err != nil {\n\t\tselect {\n\t\tcase _, ok := <-d.shutdown:\n\t\t\tif !ok {\n\t\t\t\t\/\/ shutdown in progress, do not return error\n\t\t\t\treturn nil\n\t\t\t}\n\t\tdefault:\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ Shutdown running Dalga.\nfunc (d *Dalga) Shutdown() error {\n\tclose(d.shutdown)\n\treturn d.listener.Close()\n}\n\n\/\/ NotifyReady returns a channel that will be closed when Dalga is running.\nfunc (d *Dalga) NotifyReady() <-chan struct{} {\n\treturn d.ready\n}\n\nfunc (d *Dalga) connectDB() error {\n\tvar err error\n\td.db, err = sql.Open(\"mysql\", d.config.MySQL.DSN())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = d.db.Ping(); err != nil {\n\t\treturn err\n\t}\n\tlog.Print(\"Connected to MySQL\")\n\td.table = &table{d.db, d.config.MySQL.Table}\n\treturn nil\n}\n\n\/\/ CreateTable creates the table for storing jobs.\nfunc (d *Dalga) CreateTable() error {\n\tdb, err := sql.Open(\"mysql\", d.config.MySQL.DSN())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\tt := &table{db, d.config.MySQL.Table}\n\treturn t.Create()\n}\n\n\/\/ GetJob returns the job with description routing key.\nfunc (d *Dalga) GetJob(description, routingKey string) (*Job, error) {\n\treturn d.table.Get(description, routingKey)\n}\n\n\/\/ ScheduleJob inserts a new job to the table or replaces existing one.\n\/\/ Returns the created or replaced job.\nfunc (d *Dalga) ScheduleJob(description, routingKey string, interval uint32, oneOff bool) (*Job, error) {\n\tjob := newJob(description, routingKey, interval, oneOff)\n\terr := d.table.Insert(job)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\td.notifyPublisher(\"new job\")\n\tdebug(\"Job is scheduled:\", job)\n\treturn job, nil\n}\n\n\/\/ TriggerJob publishes the job to RabbitMQ immediately and resets the next run time of the job.\nfunc (d *Dalga) TriggerJob(description, routingKey string) (*Job, error) {\n\tjob, err := d.GetJob(description, routingKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjob.NextRun = time.Now().UTC()\n\tif err := d.table.Insert(job); err != nil {\n\t\treturn nil, err\n\t}\n\td.notifyPublisher(\"job is triggered\")\n\tdebug(\"Job is triggered:\", job)\n\treturn job, nil\n}\n\n\/\/ CancelJob deletes the job with description and routing key.\nfunc (d *Dalga) CancelJob(description, routingKey string) error {\n\terr := d.table.Delete(description, routingKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.notifyPublisher(\"job cancelled\")\n\tdebug(\"Job is cancelled\")\n\treturn nil\n}\n\nfunc (d *Dalga) notifyPublisher(debugMessage string) {\n\tselect {\n\tcase d.notify <- struct{}{}:\n\t\tdebug(\"notifying publisher:\", debugMessage)\n\tdefault:\n\t}\n}\n\n\/\/ publisher runs a loop that reads the next Job from the queue and publishes it.\nfunc (d *Dalga) publisher() {\n\tdefer close(d.publisherStopped)\n\n\tfor {\n\t\tdebug(\"---\")\n\n\t\tvar after <-chan time.Time\n\n\t\tjob, err := d.table.Front()\n\t\tif err != nil {\n\t\t\tif err == sql.ErrNoRows {\n\t\t\t\tdebug(\"No scheduled jobs in the table\")\n\t\t\t} else if myErr, ok := err.(*mysql.MySQLError); ok && myErr.Number == 1146 {\n\t\t\t\t\/\/ Table doesn't exist\n\t\t\t\tlog.Fatal(myErr)\n\t\t\t} else {\n\t\t\t\tlog.Print(err)\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tremaining := job.Remaining()\n\t\t\tafter = time.After(remaining)\n\t\t\tdebug(\"Next job:\", job, \"Remaining:\", remaining)\n\t\t}\n\n\t\t\/\/ Sleep until the next job's run time or the webserver's wakes us up.\n\t\tselect {\n\t\tcase <-after:\n\t\t\tdebug(\"Job sleep time finished\")\n\t\t\tif err = d.publish(job); err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t}\n\t\tcase <-d.notify:\n\t\t\tdebug(\"Woken up from sleep by notification\")\n\t\t\tcontinue\n\t\tcase <-d.stopPublisher:\n\t\t\tdebug(\"Came quit message\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ publish makes a POST request to the endpoint and updates the Job's next run time.\nfunc (d *Dalga) publish(j *Job) error {\n\tdebug(\"publish\", *j)\n\n\tvar add time.Duration\n\tif j.Interval == 0 {\n\t\tadd = d.client.Timeout\n\t} else {\n\t\tadd = j.Interval\n\t}\n\n\tj.NextRun = time.Now().UTC().Add(add)\n\n\tif err := d.table.UpdateNextRun(j); err != nil {\n\t\treturn err\n\t}\n\n\tgo func() {\n\t\t\/\/ Do not do multiple POSTs for the same job at the same time.\n\t\tkey := j.Path + j.Body\n\t\td.m.Lock()\n\t\tif _, ok := d.activeJobs[key]; ok {\n\t\t\td.m.Unlock()\n\t\t\treturn\n\t\t}\n\t\td.activeJobs[key] = struct{}{}\n\t\td.m.Unlock()\n\n\t\tif err := d.postJob(j); err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\n\t\td.m.Lock()\n\t\tdelete(d.activeJobs, key)\n\t\td.m.Unlock()\n\t}()\n\n\treturn nil\n}\n\nfunc (d *Dalga) postJob(j *Job) error {\n\tresp, err := d.client.Post(d.config.Endpoint.BaseURL+j.Path, \"text\/plain\", strings.NewReader(j.Body))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"endpoint error: %d\", resp.StatusCode)\n\t}\n\n\tif j.Interval == 0 {\n\t\tdebug(\"deleting one-off job\")\n\t\treturn d.table.Delete(j.Path, j.Body)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"os\"\n)\n\ntype UDPRecv struct {\n\tData       []byte \/\/ UDP payload\n\tRemoteAddr *net.UDPAddr\n}\n\n\/\/ listenUDP goroutine has its own internal read buf that it gives a slice into\n\/\/ when it receives a packet. It passes the slice and the source address into\n\/\/ the channel.\n\/\/ TODO: make this take an Iface so it can log statistics\nfunc listenUDP(conn UDPReadWrite, c chan UDPRecv) error {\n\tcolors := []string{\"magenta\", \"yellow\", \"cyan\", \"white:blue\", \"black:white\"}\n\tansi_colors := make([]string, len(colors))\n\tfor i, color := range colors {\n\t\tansi_colors[i] = ansi.ColorCode(color)\n\t}\n\tansi_reset := ansi.ColorCode(\"reset\")\n\n\tread_buf := make([]byte, BUF_SIZE)\n\tfor {\n\t\tlog.Printf(\"Listening on conn %p\", conn)\n\t\tcount, remote_addr, err := conn.ReadFromUDP(read_buf)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn err\n\t\t}\n\t\tc <- UDPRecv{\n\t\t\tData:       read_buf[:count],\n\t\t\tRemoteAddr: remote_addr,\n\t\t}\n\n\t\tif DEBUG_LEVEL >= 1 {\n\t\t\tfmt.Print(ansi_colors[0], \"R\", ansi_reset)\n\t\t}\n\n\t}\n}\n\nfunc listenTun(tundev *os.File, read_buf []byte, c chan int) error {\n\tfor {\n\t\tcount, err := tundev.Read(read_buf)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn err\n\t\t}\n\t\tc <- count\n\t}\n}\n<commit_msg>Fixed ansi color imports<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/mgutz\/ansi\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n)\n\ntype UDPRecv struct {\n\tData       []byte \/\/ UDP payload\n\tRemoteAddr *net.UDPAddr\n}\n\n\/\/ listenUDP goroutine has its own internal read buf that it gives a slice into\n\/\/ when it receives a packet. It passes the slice and the source address into\n\/\/ the channel.\n\/\/ TODO: make this take an Iface so it can log statistics\nfunc listenUDP(conn UDPReadWrite, c chan UDPRecv) error {\n\tcolors := []string{\"magenta\", \"yellow\", \"cyan\", \"white:blue\", \"black:white\"}\n\tansi_colors := make([]string, len(colors))\n\tfor i, color := range colors {\n\t\tansi_colors[i] = ansi.ColorCode(color)\n\t}\n\tansi_reset := ansi.ColorCode(\"reset\")\n\n\tread_buf := make([]byte, BUF_SIZE)\n\tfor {\n\t\tlog.Printf(\"Listening on conn %p\", conn)\n\t\tcount, remote_addr, err := conn.ReadFromUDP(read_buf)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn err\n\t\t}\n\t\tc <- UDPRecv{\n\t\t\tData:       read_buf[:count],\n\t\t\tRemoteAddr: remote_addr,\n\t\t}\n\n\t\tif DEBUG_LEVEL >= 1 {\n\t\t\tfmt.Print(ansi_colors[0], \"R\", ansi_reset)\n\t\t}\n\n\t}\n}\n\nfunc listenTun(tundev *os.File, read_buf []byte, c chan int) error {\n\tfor {\n\t\tcount, err := tundev.Read(read_buf)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn err\n\t\t}\n\t\tc <- count\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package deployments\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/asobti\/kube-monkey\/config\"\n\t\"k8s.io\/api\/extensions\/v1beta1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\nconst (\n\tIDENTIFIER = \"kube-monkey-id\"\n\tNAME       = \"deployment_name\"\n\tNAMESPACE  = metav1.NamespaceDefault\n)\n\nfunc newDeployment(name string, labels map[string]string) v1beta1.Deployment {\n\n\treturn v1beta1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName:      name,\n\t\t\tNamespace: NAMESPACE,\n\t\t\tLabels:    labels,\n\t\t},\n\t}\n}\n\nfunc TestNew(t *testing.T) {\n\n\tv1depl := newDeployment(\n\t\tNAME,\n\t\tmap[string]string{\n\t\t\tconfig.IdentLabelKey: IDENTIFIER,\n\t\t\tconfig.MtbfLabelKey:  \"1\",\n\t\t},\n\t)\n\tdepl, err := New(&v1depl)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif ns := depl.Namespace(); ns != NAMESPACE {\n\t\tt.Errorf(\"Unexpected deployment Namespace, got %s\", ns)\n\t}\n\n\tif k := depl.Kind(); k != \"v1beta1.Deployment\" {\n\t\tt.Errorf(\"Unexpected deployment Kindepl, got %s\", k)\n\t}\n\n\tif n := depl.Name(); n != NAME {\n\t\tt.Errorf(\"Unexpected deployment Name, got %s\", n)\n\t}\n\n\tif i := depl.Identifier(); i != IDENTIFIER {\n\t\tt.Errorf(\"Unexpected deployment Identifier, got %s\", i)\n\t}\n\n\tif m := depl.Mtbf(); m != 1 {\n\t\tt.Errorf(\"Unexpected deployment Mtbf, got %d\", m)\n\t}\n\n}\n\nfunc TestInvalidIdentifier(t *testing.T) {\n\tv1depl := newDeployment(\n\t\tNAME,\n\t\tmap[string]string{\n\t\t\tconfig.MtbfLabelKey: \"1\",\n\t\t},\n\t)\n\t_, err := New(&v1depl)\n\n\tif err == nil {\n\t\tt.Error(\"Expected an error if config.IdentLabelKey label doesn't exist\")\n\t}\n}\n\nfunc TestInvalidMtbf(t *testing.T) {\n\tv1depl := newDeployment(\n\t\tNAME,\n\t\tmap[string]string{\n\t\t\tconfig.IdentLabelKey: IDENTIFIER,\n\t\t},\n\t)\n\t_, err := New(&v1depl)\n\n\tif err == nil {\n\t\tt.Error(\"Expected an error if config.MtbfLabelKey label doesn't exist\")\n\t}\n\n\tv1depl = newDeployment(\n\t\tNAME,\n\t\tmap[string]string{\n\t\t\tconfig.IdentLabelKey: IDENTIFIER,\n\t\t\tconfig.MtbfLabelKey:  \"string\",\n\t\t},\n\t)\n\t_, err = New(&v1depl)\n\n\tif err == nil {\n\t\tt.Error(\"Expected an error if config.MtbfLabelKey label can't be converted a Int type\")\n\t}\n\tv1depl = newDeployment(\n\t\tNAME,\n\t\tmap[string]string{\n\t\t\tconfig.IdentLabelKey: IDENTIFIER,\n\t\t\tconfig.MtbfLabelKey:  \"0\",\n\t\t},\n\t)\n\t_, err = New(&v1depl)\n\n\tif err == nil {\n\t\tt.Error(\"Expected an error if config.MtbfLabelKey label is lower than 1\")\n\t}\n}\n<commit_msg>Port UT to testify\/assert<commit_after>package deployments\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/asobti\/kube-monkey\/config\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"k8s.io\/api\/extensions\/v1beta1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\nconst (\n\tIDENTIFIER = \"kube-monkey-id\"\n\tNAME       = \"deployment_name\"\n\tNAMESPACE  = metav1.NamespaceDefault\n)\n\nfunc newDeployment(name string, labels map[string]string) v1beta1.Deployment {\n\n\treturn v1beta1.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName:      name,\n\t\t\tNamespace: NAMESPACE,\n\t\t\tLabels:    labels,\n\t\t},\n\t}\n}\n\nfunc TestNew(t *testing.T) {\n\n\tv1depl := newDeployment(\n\t\tNAME,\n\t\tmap[string]string{\n\t\t\tconfig.IdentLabelKey: IDENTIFIER,\n\t\t\tconfig.MtbfLabelKey:  \"1\",\n\t\t},\n\t)\n\tdepl, err := New(&v1depl)\n\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"v1beta1.Deployment\", depl.Kind())\n\tassert.Equal(t, NAME, depl.Name())\n\tassert.Equal(t, NAMESPACE, depl.Namespace())\n\tassert.Equal(t, IDENTIFIER, depl.Identifier())\n\tassert.Equal(t, 1, depl.Mtbf())\n}\n\nfunc TestInvalidIdentifier(t *testing.T) {\n\tv1depl := newDeployment(\n\t\tNAME,\n\t\tmap[string]string{\n\t\t\tconfig.MtbfLabelKey: \"1\",\n\t\t},\n\t)\n\t_, err := New(&v1depl)\n\n\tassert.Errorf(t, err, \"Expected an error if \"+config.IdentLabelKey+\" label doesn't exist\")\n}\n\nfunc TestInvalidMtbf(t *testing.T) {\n\tv1depl := newDeployment(\n\t\tNAME,\n\t\tmap[string]string{\n\t\t\tconfig.IdentLabelKey: IDENTIFIER,\n\t\t},\n\t)\n\t_, err := New(&v1depl)\n\n\tassert.Errorf(t, err, \"Expected an error if \"+config.MtbfLabelKey+\" label doesn't exist\")\n\n\tv1depl = newDeployment(\n\t\tNAME,\n\t\tmap[string]string{\n\t\t\tconfig.IdentLabelKey: IDENTIFIER,\n\t\t\tconfig.MtbfLabelKey:  \"string\",\n\t\t},\n\t)\n\t_, err = New(&v1depl)\n\n\tassert.Errorf(t, err, \"Expected an error if \"+config.MtbfLabelKey+\" label can't be converted a Int type\")\n\n\tv1depl = newDeployment(\n\t\tNAME,\n\t\tmap[string]string{\n\t\t\tconfig.IdentLabelKey: IDENTIFIER,\n\t\t\tconfig.MtbfLabelKey:  \"0\",\n\t\t},\n\t)\n\t_, err = New(&v1depl)\n\n\tassert.Errorf(t, err, \"Expected an error if \"+config.MtbfLabelKey+\" label is lower than 1\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package api has type definitions for webdav\npackage api\n\nimport (\n\t\"encoding\/xml\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ Wed, 27 Sep 2017 14:28:34 GMT\n\ttimeFormat = time.RFC1123\n\t\/\/ The same as time.RFC1123 with optional leading zeros on the date\n\t\/\/ see https:\/\/github.com\/ncw\/rclone\/issues\/2574\n\tnoZerosRFC1123 = \"Mon, _2 Jan 2006 15:04:05 MST\"\n)\n\n\/\/ Multistatus contains responses returned from an HTTP 207 return code\ntype Multistatus struct {\n\tResponses []Response `xml:\"response\"`\n}\n\n\/\/ Response contains an Href the response it about and its properties\ntype Response struct {\n\tHref  string `xml:\"href\"`\n\tProps Prop   `xml:\"propstat\"`\n}\n\n\/\/ Prop is the properties of a response\n\/\/\n\/\/ This is a lazy way of decoding the multiple <s:propstat> in the\n\/\/ response.\n\/\/\n\/\/ The response might look like this\n\/\/\n\/\/ <d:response>\n\/\/   <d:href>\/remote.php\/webdav\/Nextcloud%20Manual.pdf<\/d:href>\n\/\/   <d:propstat>\n\/\/     <d:prop>\n\/\/       <d:getlastmodified>Tue, 19 Dec 2017 22:02:36 GMT<\/d:getlastmodified>\n\/\/       <d:getcontentlength>4143665<\/d:getcontentlength>\n\/\/       <d:resourcetype\/>\n\/\/       <d:getetag>\"048d7be4437ff7deeae94db50ff3e209\"<\/d:getetag>\n\/\/       <d:getcontenttype>application\/pdf<\/d:getcontenttype>\n\/\/     <\/d:prop>\n\/\/     <d:status>HTTP\/1.1 200 OK<\/d:status>\n\/\/   <\/d:propstat>\n\/\/   <d:propstat>\n\/\/     <d:prop>\n\/\/       <d:quota-used-bytes\/>\n\/\/       <d:quota-available-bytes\/>\n\/\/     <\/d:prop>\n\/\/     <d:status>HTTP\/1.1 404 Not Found<\/d:status>\n\/\/   <\/d:propstat>\n\/\/ <\/d:response>\n\/\/\n\/\/ So we elide the array of <d:propstat> and within that the array of\n\/\/ <d:prop> into one struct.\n\/\/\n\/\/ Note that status collects all the status values for which we just\n\/\/ check the first is OK.\ntype Prop struct {\n\tStatus   []string  `xml:\"DAV: status\"`\n\tName     string    `xml:\"DAV: prop>displayname,omitempty\"`\n\tType     *xml.Name `xml:\"DAV: prop>resourcetype>collection,omitempty\"`\n\tSize     int64     `xml:\"DAV: prop>getcontentlength,omitempty\"`\n\tModified Time      `xml:\"DAV: prop>getlastmodified,omitempty\"`\n}\n\n\/\/ Parse a status of the form \"HTTP\/1.1 200 OK\" or \"HTTP\/1.1 200\"\nvar parseStatus = regexp.MustCompile(`^HTTP\/[0-9.]+\\s+(\\d+)`)\n\n\/\/ StatusOK examines the Status and returns an OK flag\nfunc (p *Prop) StatusOK() bool {\n\t\/\/ Assume OK if no statuses received\n\tif len(p.Status) == 0 {\n\t\treturn true\n\t}\n\tmatch := parseStatus.FindStringSubmatch(p.Status[0])\n\tif len(match) < 2 {\n\t\treturn false\n\t}\n\tcode, err := strconv.Atoi(match[1])\n\tif err != nil {\n\t\treturn false\n\t}\n\tif code >= 200 && code < 300 {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ PropValue is a tagged name and value\ntype PropValue struct {\n\tXMLName xml.Name `xml:\"\"`\n\tValue   string   `xml:\",chardata\"`\n}\n\n\/\/ Error is used to desribe webdav errors\n\/\/\n\/\/ <d:error xmlns:d=\"DAV:\" xmlns:s=\"http:\/\/sabredav.org\/ns\">\n\/\/   <s:exception>Sabre\\DAV\\Exception\\NotFound<\/s:exception>\n\/\/   <s:message>File with name Photo could not be located<\/s:message>\n\/\/ <\/d:error>\ntype Error struct {\n\tException  string `xml:\"exception,omitempty\"`\n\tMessage    string `xml:\"message,omitempty\"`\n\tStatus     string\n\tStatusCode int\n}\n\n\/\/ Error returns a string for the error and statistifes the error interface\nfunc (e *Error) Error() string {\n\tvar out []string\n\tif e.Message != \"\" {\n\t\tout = append(out, e.Message)\n\t}\n\tif e.Exception != \"\" {\n\t\tout = append(out, e.Exception)\n\t}\n\tif e.Status != \"\" {\n\t\tout = append(out, e.Status)\n\t}\n\tif len(out) == 0 {\n\t\treturn \"Webdav Error\"\n\t}\n\treturn strings.Join(out, \": \")\n}\n\n\/\/ Time represents represents date and time information for the\n\/\/ webdav API marshalling to and from timeFormat\ntype Time time.Time\n\n\/\/ MarshalXML turns a Time into XML\nfunc (t *Time) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\ttimeString := (*time.Time)(t).Format(timeFormat)\n\treturn e.EncodeElement(timeString, start)\n}\n\n\/\/ Possible time formats to parse the time with\nvar timeFormats = []string{\n\ttimeFormat,     \/\/ Wed, 27 Sep 2017 14:28:34 GMT (as per RFC)\n\ttime.RFC1123Z,  \/\/ Fri, 05 Jan 2018 14:14:38 +0000 (as used by mydrive.ch)\n\ttime.UnixDate,  \/\/ Wed May 17 15:31:58 UTC 2017 (as used in an internal server)\n\tnoZerosRFC1123, \/\/ Fri, 7 Sep 2018 08:49:58 GMT (as used by server in #2574)\n}\n\n\/\/ UnmarshalXML turns XML into a Time\nfunc (t *Time) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\terr := d.DecodeElement(&v, &start)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ If time is missing then return the epoch\n\tif v == \"\" {\n\t\t*t = Time(time.Unix(0, 0))\n\t\treturn nil\n\t}\n\n\t\/\/ Parse the time format in multiple possible ways\n\tvar newT time.Time\n\tfor _, timeFormat := range timeFormats {\n\t\tnewT, err = time.Parse(timeFormat, v)\n\t\tif err == nil {\n\t\t\t*t = Time(newT)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn err\n}\n<commit_msg>WebDav - Add RFC3339 date format - fixes #2712<commit_after>\/\/ Package api has type definitions for webdav\npackage api\n\nimport (\n\t\"encoding\/xml\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ Wed, 27 Sep 2017 14:28:34 GMT\n\ttimeFormat = time.RFC1123\n\t\/\/ The same as time.RFC1123 with optional leading zeros on the date\n\t\/\/ see https:\/\/github.com\/ncw\/rclone\/issues\/2574\n\tnoZerosRFC1123 = \"Mon, _2 Jan 2006 15:04:05 MST\"\n)\n\n\/\/ Multistatus contains responses returned from an HTTP 207 return code\ntype Multistatus struct {\n\tResponses []Response `xml:\"response\"`\n}\n\n\/\/ Response contains an Href the response it about and its properties\ntype Response struct {\n\tHref  string `xml:\"href\"`\n\tProps Prop   `xml:\"propstat\"`\n}\n\n\/\/ Prop is the properties of a response\n\/\/\n\/\/ This is a lazy way of decoding the multiple <s:propstat> in the\n\/\/ response.\n\/\/\n\/\/ The response might look like this\n\/\/\n\/\/ <d:response>\n\/\/   <d:href>\/remote.php\/webdav\/Nextcloud%20Manual.pdf<\/d:href>\n\/\/   <d:propstat>\n\/\/     <d:prop>\n\/\/       <d:getlastmodified>Tue, 19 Dec 2017 22:02:36 GMT<\/d:getlastmodified>\n\/\/       <d:getcontentlength>4143665<\/d:getcontentlength>\n\/\/       <d:resourcetype\/>\n\/\/       <d:getetag>\"048d7be4437ff7deeae94db50ff3e209\"<\/d:getetag>\n\/\/       <d:getcontenttype>application\/pdf<\/d:getcontenttype>\n\/\/     <\/d:prop>\n\/\/     <d:status>HTTP\/1.1 200 OK<\/d:status>\n\/\/   <\/d:propstat>\n\/\/   <d:propstat>\n\/\/     <d:prop>\n\/\/       <d:quota-used-bytes\/>\n\/\/       <d:quota-available-bytes\/>\n\/\/     <\/d:prop>\n\/\/     <d:status>HTTP\/1.1 404 Not Found<\/d:status>\n\/\/   <\/d:propstat>\n\/\/ <\/d:response>\n\/\/\n\/\/ So we elide the array of <d:propstat> and within that the array of\n\/\/ <d:prop> into one struct.\n\/\/\n\/\/ Note that status collects all the status values for which we just\n\/\/ check the first is OK.\ntype Prop struct {\n\tStatus   []string  `xml:\"DAV: status\"`\n\tName     string    `xml:\"DAV: prop>displayname,omitempty\"`\n\tType     *xml.Name `xml:\"DAV: prop>resourcetype>collection,omitempty\"`\n\tSize     int64     `xml:\"DAV: prop>getcontentlength,omitempty\"`\n\tModified Time      `xml:\"DAV: prop>getlastmodified,omitempty\"`\n}\n\n\/\/ Parse a status of the form \"HTTP\/1.1 200 OK\" or \"HTTP\/1.1 200\"\nvar parseStatus = regexp.MustCompile(`^HTTP\/[0-9.]+\\s+(\\d+)`)\n\n\/\/ StatusOK examines the Status and returns an OK flag\nfunc (p *Prop) StatusOK() bool {\n\t\/\/ Assume OK if no statuses received\n\tif len(p.Status) == 0 {\n\t\treturn true\n\t}\n\tmatch := parseStatus.FindStringSubmatch(p.Status[0])\n\tif len(match) < 2 {\n\t\treturn false\n\t}\n\tcode, err := strconv.Atoi(match[1])\n\tif err != nil {\n\t\treturn false\n\t}\n\tif code >= 200 && code < 300 {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ PropValue is a tagged name and value\ntype PropValue struct {\n\tXMLName xml.Name `xml:\"\"`\n\tValue   string   `xml:\",chardata\"`\n}\n\n\/\/ Error is used to desribe webdav errors\n\/\/\n\/\/ <d:error xmlns:d=\"DAV:\" xmlns:s=\"http:\/\/sabredav.org\/ns\">\n\/\/   <s:exception>Sabre\\DAV\\Exception\\NotFound<\/s:exception>\n\/\/   <s:message>File with name Photo could not be located<\/s:message>\n\/\/ <\/d:error>\ntype Error struct {\n\tException  string `xml:\"exception,omitempty\"`\n\tMessage    string `xml:\"message,omitempty\"`\n\tStatus     string\n\tStatusCode int\n}\n\n\/\/ Error returns a string for the error and statistifes the error interface\nfunc (e *Error) Error() string {\n\tvar out []string\n\tif e.Message != \"\" {\n\t\tout = append(out, e.Message)\n\t}\n\tif e.Exception != \"\" {\n\t\tout = append(out, e.Exception)\n\t}\n\tif e.Status != \"\" {\n\t\tout = append(out, e.Status)\n\t}\n\tif len(out) == 0 {\n\t\treturn \"Webdav Error\"\n\t}\n\treturn strings.Join(out, \": \")\n}\n\n\/\/ Time represents represents date and time information for the\n\/\/ webdav API marshalling to and from timeFormat\ntype Time time.Time\n\n\/\/ MarshalXML turns a Time into XML\nfunc (t *Time) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\ttimeString := (*time.Time)(t).Format(timeFormat)\n\treturn e.EncodeElement(timeString, start)\n}\n\n\/\/ Possible time formats to parse the time with\nvar timeFormats = []string{\n\ttimeFormat,     \/\/ Wed, 27 Sep 2017 14:28:34 GMT (as per RFC)\n\ttime.RFC1123Z,  \/\/ Fri, 05 Jan 2018 14:14:38 +0000 (as used by mydrive.ch)\n\ttime.UnixDate,  \/\/ Wed May 17 15:31:58 UTC 2017 (as used in an internal server)\n\tnoZerosRFC1123, \/\/ Fri, 7 Sep 2018 08:49:58 GMT (as used by server in #2574)\n        time.RFC3339,   \/\/ Wed, 31 Oct 2018 13:57:11 CET (as used by komfortcloud.de)\n}\n\n\/\/ UnmarshalXML turns XML into a Time\nfunc (t *Time) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\tvar v string\n\terr := d.DecodeElement(&v, &start)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ If time is missing then return the epoch\n\tif v == \"\" {\n\t\t*t = Time(time.Unix(0, 0))\n\t\treturn nil\n\t}\n\n\t\/\/ Parse the time format in multiple possible ways\n\tvar newT time.Time\n\tfor _, timeFormat := range timeFormats {\n\t\tnewT, err = time.Parse(timeFormat, v)\n\t\tif err == nil {\n\t\t\t*t = Time(newT)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package azuread\n\nimport (\n\t\"crypto\/sha1\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/Azure\/azure-sdk-for-go\/services\/graphrbac\/1.6\/graphrbac\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n\n\t\"github.com\/terraform-providers\/terraform-provider-azuread\/azuread\/helpers\/ar\"\n\t\"github.com\/terraform-providers\/terraform-provider-azuread\/azuread\/helpers\/graph\"\n\t\"github.com\/terraform-providers\/terraform-provider-azuread\/azuread\/helpers\/validate\"\n)\n\nfunc dataUsers() *schema.Resource {\n\treturn &schema.Resource{\n\t\tRead: dataSourceUsersRead,\n\n\t\tImporter: &schema.ResourceImporter{\n\t\t\tState: schema.ImportStatePassthrough,\n\t\t},\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"object_ids\": {\n\t\t\t\tType:         schema.TypeList,\n\t\t\t\tOptional:     true,\n\t\t\t\tComputed:     true,\n\t\t\t\tExactlyOneOf: []string{\"object_ids\", \"user_principal_names\", \"mail_nicknames\"},\n\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\tType:         schema.TypeString,\n\t\t\t\t\tValidateFunc: validate.UUID,\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"user_principal_names\": {\n\t\t\t\tType:         schema.TypeList,\n\t\t\t\tOptional:     true,\n\t\t\t\tComputed:     true,\n\t\t\t\tExactlyOneOf: []string{\"object_ids\", \"user_principal_names\", \"mail_nicknames\"},\n\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\tType:         schema.TypeString,\n\t\t\t\t\tValidateFunc: validate.NoEmptyStrings,\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"mail_nicknames\": {\n\t\t\t\tType:         schema.TypeList,\n\t\t\t\tOptional:     true,\n\t\t\t\tComputed:     true,\n\t\t\t\tExactlyOneOf: []string{\"object_ids\", \"user_principal_names\", \"mail_nicknames\"},\n\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\tType:         schema.TypeString,\n\t\t\t\t\tValidateFunc: validate.NoEmptyStrings,\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"ignore_missing\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault:  false,\n\t\t\t},\n\n\t\t\t\"users\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tComputed: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"account_enabled\": {\n\t\t\t\t\t\t\tType:     schema.TypeBool,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"display_name\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"immutable_id\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"mail\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"mail_nickname\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"object_id\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"onpremises_sam_account_name\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"onpremises_user_principal_name\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"usage_location\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"user_principal_name\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc dataSourceUsersRead(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*ArmClient).usersClient\n\tctx := meta.(*ArmClient).StopContext\n\n\tvar users []*graphrbac.User\n\texpectedCount := 0\n\n\tignoreMissing := d.Get(\"ignore_missing\").(bool)\n\tif upns, ok := d.Get(\"user_principal_names\").([]interface{}); ok && len(upns) > 0 {\n\t\texpectedCount = len(upns)\n\t\tfor _, v := range upns {\n\t\t\tu, err := client.Get(ctx, v.(string))\n\t\t\tif err != nil {\n\t\t\t\tif ignoreMissing && ar.ResponseWasNotFound(u.Response) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"making Read request on AzureAD User with ID %q: %+v\", v.(string), err)\n\t\t\t}\n\t\t\tusers = append(users, &u)\n\t\t}\n\t} else {\n\t\tif oids, ok := d.Get(\"object_ids\").([]interface{}); ok && len(oids) > 0 {\n\t\t\texpectedCount = len(oids)\n\t\t\tfor _, v := range oids {\n\t\t\t\tu, err := graph.UserGetByObjectId(&client, ctx, v.(string))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"finding Azure AD User with object ID %q: %+v\", v.(string), err)\n\t\t\t\t}\n\t\t\t\tif u == nil {\n\t\t\t\t\tif ignoreMissing {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn fmt.Errorf(\"found no AD Users with object ID %q\", v.(string))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tusers = append(users, u)\n\t\t\t}\n\t\t} else if mailNicknames, ok := d.Get(\"mail_nicknames\").([]interface{}); ok && len(mailNicknames) > 0 {\n\t\t\texpectedCount = len(mailNicknames)\n\t\t\tfor _, v := range mailNicknames {\n\t\t\t\tu, err := graph.UserGetByMailNickname(&client, ctx, v.(string))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"finding Azure AD User with email alias %q: %+v\", v.(string), err)\n\t\t\t\t}\n\t\t\t\tif u == nil {\n\t\t\t\t\tif ignoreMissing {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn fmt.Errorf(\"found no AD Users with email alias %q\", v.(string))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tusers = append(users, u)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !ignoreMissing && len(users) != expectedCount {\n\t\treturn fmt.Errorf(\"unexpected number of users returned (%d != %d)\", len(users), expectedCount)\n\t}\n\n\t\/\/ TODO: consider disallowing no results in v1.0\n\t\/\/if len(users) == 0 {\n\t\/\/\treturn fmt.Errorf(\"no users were returned\")\n\t\/\/}\n\n\tupns := make([]string, 0, len(users))\n\toids := make([]string, 0, len(users))\n\tmailNicknames := make([]string, 0, len(users))\n\tuserList := make([]map[string]interface{}, 0, len(users))\n\tfor _, u := range users {\n\t\tif u.ObjectID == nil || u.UserPrincipalName == nil {\n\t\t\treturn fmt.Errorf(\"user with nil ObjectId or UPN was found: %v\", u)\n\t\t}\n\n\t\toids = append(oids, *u.ObjectID)\n\t\tupns = append(upns, *u.UserPrincipalName)\n\t\tmailNicknames = append(mailNicknames, *u.MailNickname)\n\n\t\tuser := make(map[string]interface{})\n\t\tuser[\"account_enabled\"] = u.AccountEnabled\n\t\tuser[\"display_name\"] = u.DisplayName\n\t\tuser[\"immutable_id\"] = u.ImmutableID\n\t\tuser[\"mail\"] = u.Mail\n\t\tuser[\"mail_nickname\"] = u.MailNickname\n\t\tuser[\"object_id\"] = u.ObjectID\n\t\tuser[\"onpremises_sam_account_name\"] = u.AdditionalProperties[\"onPremisesSamAccountName\"]\n\t\tuser[\"onpremises_user_principal_name\"] = u.AdditionalProperties[\"onPremisesUserPrincipalName\"]\n\t\tuser[\"usage_location\"] = u.UsageLocation\n\t\tuser[\"user_principal_name\"] = u.UserPrincipalName\n\t\tuserList = append(userList, user)\n\t}\n\n\th := sha1.New()\n\tif _, err := h.Write([]byte(strings.Join(upns, \"-\"))); err != nil {\n\t\treturn fmt.Errorf(\"unable to compute hash for UPNs: %v\", err)\n\t}\n\n\td.SetId(\"users#\" + base64.URLEncoding.EncodeToString(h.Sum(nil)))\n\td.Set(\"object_ids\", oids)\n\td.Set(\"user_principal_names\", upns)\n\td.Set(\"mail_nicknames\", mailNicknames)\n\td.Set(\"users\", userList)\n\n\treturn nil\n}\n<commit_msg>Fix for users read lookup loop breaking rather than continuing<commit_after>package azuread\n\nimport (\n\t\"crypto\/sha1\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/Azure\/azure-sdk-for-go\/services\/graphrbac\/1.6\/graphrbac\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n\n\t\"github.com\/terraform-providers\/terraform-provider-azuread\/azuread\/helpers\/ar\"\n\t\"github.com\/terraform-providers\/terraform-provider-azuread\/azuread\/helpers\/graph\"\n\t\"github.com\/terraform-providers\/terraform-provider-azuread\/azuread\/helpers\/validate\"\n)\n\nfunc dataUsers() *schema.Resource {\n\treturn &schema.Resource{\n\t\tRead: dataSourceUsersRead,\n\n\t\tImporter: &schema.ResourceImporter{\n\t\t\tState: schema.ImportStatePassthrough,\n\t\t},\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"object_ids\": {\n\t\t\t\tType:         schema.TypeList,\n\t\t\t\tOptional:     true,\n\t\t\t\tComputed:     true,\n\t\t\t\tExactlyOneOf: []string{\"object_ids\", \"user_principal_names\", \"mail_nicknames\"},\n\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\tType:         schema.TypeString,\n\t\t\t\t\tValidateFunc: validate.UUID,\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"user_principal_names\": {\n\t\t\t\tType:         schema.TypeList,\n\t\t\t\tOptional:     true,\n\t\t\t\tComputed:     true,\n\t\t\t\tExactlyOneOf: []string{\"object_ids\", \"user_principal_names\", \"mail_nicknames\"},\n\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\tType:         schema.TypeString,\n\t\t\t\t\tValidateFunc: validate.NoEmptyStrings,\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"mail_nicknames\": {\n\t\t\t\tType:         schema.TypeList,\n\t\t\t\tOptional:     true,\n\t\t\t\tComputed:     true,\n\t\t\t\tExactlyOneOf: []string{\"object_ids\", \"user_principal_names\", \"mail_nicknames\"},\n\t\t\t\tElem: &schema.Schema{\n\t\t\t\t\tType:         schema.TypeString,\n\t\t\t\t\tValidateFunc: validate.NoEmptyStrings,\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"ignore_missing\": {\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault:  false,\n\t\t\t},\n\n\t\t\t\"users\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tComputed: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"account_enabled\": {\n\t\t\t\t\t\t\tType:     schema.TypeBool,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"display_name\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"immutable_id\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"mail\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"mail_nickname\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"object_id\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"onpremises_sam_account_name\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"onpremises_user_principal_name\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"usage_location\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\n\t\t\t\t\t\t\"user_principal_name\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc dataSourceUsersRead(d *schema.ResourceData, meta interface{}) error {\n\tclient := meta.(*ArmClient).usersClient\n\tctx := meta.(*ArmClient).StopContext\n\n\tvar users []*graphrbac.User\n\texpectedCount := 0\n\n\tignoreMissing := d.Get(\"ignore_missing\").(bool)\n\tif upns, ok := d.Get(\"user_principal_names\").([]interface{}); ok && len(upns) > 0 {\n\t\texpectedCount = len(upns)\n\t\tfor _, v := range upns {\n\t\t\tu, err := client.Get(ctx, v.(string))\n\t\t\tif err != nil {\n\t\t\t\tif ignoreMissing && ar.ResponseWasNotFound(u.Response) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\treturn fmt.Errorf(\"making Read request on AzureAD User with ID %q: %+v\", v.(string), err)\n\t\t\t}\n\t\t\tusers = append(users, &u)\n\t\t}\n\t} else {\n\t\tif oids, ok := d.Get(\"object_ids\").([]interface{}); ok && len(oids) > 0 {\n\t\t\texpectedCount = len(oids)\n\t\t\tfor _, v := range oids {\n\t\t\t\tu, err := graph.UserGetByObjectId(&client, ctx, v.(string))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"finding Azure AD User with object ID %q: %+v\", v.(string), err)\n\t\t\t\t}\n\t\t\t\tif u == nil {\n\t\t\t\t\tif ignoreMissing {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn fmt.Errorf(\"found no AD Users with object ID %q\", v.(string))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tusers = append(users, u)\n\t\t\t}\n\t\t} else if mailNicknames, ok := d.Get(\"mail_nicknames\").([]interface{}); ok && len(mailNicknames) > 0 {\n\t\t\texpectedCount = len(mailNicknames)\n\t\t\tfor _, v := range mailNicknames {\n\t\t\t\tu, err := graph.UserGetByMailNickname(&client, ctx, v.(string))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"finding Azure AD User with email alias %q: %+v\", v.(string), err)\n\t\t\t\t}\n\t\t\t\tif u == nil {\n\t\t\t\t\tif ignoreMissing {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn fmt.Errorf(\"found no AD Users with email alias %q\", v.(string))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tusers = append(users, u)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !ignoreMissing && len(users) != expectedCount {\n\t\treturn fmt.Errorf(\"unexpected number of users returned (%d != %d)\", len(users), expectedCount)\n\t}\n\n\t\/\/ TODO: consider disallowing no results in v1.0\n\t\/\/if len(users) == 0 {\n\t\/\/\treturn fmt.Errorf(\"no users were returned\")\n\t\/\/}\n\n\tupns := make([]string, 0, len(users))\n\toids := make([]string, 0, len(users))\n\tmailNicknames := make([]string, 0, len(users))\n\tuserList := make([]map[string]interface{}, 0, len(users))\n\tfor _, u := range users {\n\t\tif u.ObjectID == nil || u.UserPrincipalName == nil {\n\t\t\treturn fmt.Errorf(\"user with nil ObjectId or UPN was found: %v\", u)\n\t\t}\n\n\t\toids = append(oids, *u.ObjectID)\n\t\tupns = append(upns, *u.UserPrincipalName)\n\t\tmailNicknames = append(mailNicknames, *u.MailNickname)\n\n\t\tuser := make(map[string]interface{})\n\t\tuser[\"account_enabled\"] = u.AccountEnabled\n\t\tuser[\"display_name\"] = u.DisplayName\n\t\tuser[\"immutable_id\"] = u.ImmutableID\n\t\tuser[\"mail\"] = u.Mail\n\t\tuser[\"mail_nickname\"] = u.MailNickname\n\t\tuser[\"object_id\"] = u.ObjectID\n\t\tuser[\"onpremises_sam_account_name\"] = u.AdditionalProperties[\"onPremisesSamAccountName\"]\n\t\tuser[\"onpremises_user_principal_name\"] = u.AdditionalProperties[\"onPremisesUserPrincipalName\"]\n\t\tuser[\"usage_location\"] = u.UsageLocation\n\t\tuser[\"user_principal_name\"] = u.UserPrincipalName\n\t\tuserList = append(userList, user)\n\t}\n\n\th := sha1.New()\n\tif _, err := h.Write([]byte(strings.Join(upns, \"-\"))); err != nil {\n\t\treturn fmt.Errorf(\"unable to compute hash for UPNs: %v\", err)\n\t}\n\n\td.SetId(\"users#\" + base64.URLEncoding.EncodeToString(h.Sum(nil)))\n\td.Set(\"object_ids\", oids)\n\td.Set(\"user_principal_names\", upns)\n\td.Set(\"mail_nicknames\", mailNicknames)\n\td.Set(\"users\", userList)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package backend\n\nimport (\n\t\"bytes\"\n\t\"crypto\/x509\"\n\t\"encoding\/json\"\n\t\"encoding\/pem\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/pkg\/sftp\"\n\tworkerctx \"github.com\/travis-ci\/worker\/lib\/context\"\n\t\"github.com\/travis-ci\/worker\/lib\/metrics\"\n\t\"golang.org\/x\/crypto\/ssh\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar nonAlphaNumRegexp = regexp.MustCompile(`[^a-zA-Z0-9_]+`)\n\ntype JupiterBrainProvider struct {\n\tclient           *http.Client\n\tbaseURL          *url.URL\n\timageAliases     map[string]string\n\tsshKeyPath       string\n\tsshKeyPassphrase string\n\tkeychainPassword string\n}\n\ntype JupiterBrainInstance struct {\n\tpayload  jupiterBrainInstancePayload\n\tprovider *JupiterBrainProvider\n}\n\ntype jupiterBrainInstancePayload struct {\n\tID          string   `json:\"id\"`\n\tIpAddresses []string `json:\"ip-addresses\"`\n\tState       string   `json:\"state\"`\n\tBaseImage   string   `json:\"base-image,omitempty\"`\n\tType        string   `json:\"type,omitempty\"`\n}\n\ntype jupiterBrainDataResponse struct {\n\tData []jupiterBrainInstancePayload `json:\"data\"`\n}\n\nfunc NewJupiterBrainProvider(config map[string]string) (*JupiterBrainProvider, error) {\n\tendpoint, ok := config[\"endpoint\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected endpoint config key\")\n\t}\n\tbaseURL, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taliasNames, ok := config[\"image_aliases\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected image_aliases config key\")\n\t}\n\n\timageAliases := make(map[string]string, len(aliasNames))\n\n\tfor _, aliasName := range strings.Split(aliasNames, \",\") {\n\t\tnormalizedAliasName := string(nonAlphaNumRegexp.ReplaceAll([]byte(aliasName), []byte(\"_\")))\n\n\t\timageName, ok := config[fmt.Sprintf(\"image_alias_%s\", normalizedAliasName)]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"expected image alias %q\", aliasName)\n\t\t}\n\n\t\timageAliases[aliasName] = imageName\n\t}\n\n\tsshKeyPath, ok := config[\"ssh_key_path\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected ssh_key_path config key\")\n\t}\n\n\tsshKeyPassphrase, ok := config[\"ssh_key_passphrase\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected ssh_key_passphrase config key\")\n\t}\n\n\tkeychainPassword, ok := config[\"keychain_password\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected keychain_password config key\")\n\t}\n\n\treturn &JupiterBrainProvider{\n\t\tclient:           http.DefaultClient,\n\t\tbaseURL:          baseURL,\n\t\timageAliases:     imageAliases,\n\t\tsshKeyPath:       sshKeyPath,\n\t\tsshKeyPassphrase: sshKeyPassphrase,\n\t\tkeychainPassword: keychainPassword,\n\t}, nil\n}\n\nfunc (p *JupiterBrainProvider) Start(ctx context.Context, startAttributes StartAttributes) (Instance, error) {\n\tu, err := p.baseURL.Parse(\"instances\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\timageName, ok := p.imageAliases[startAttributes.OsxImage]\n\tif !ok {\n\t\timageName, _ = p.imageAliases[\"default\"]\n\t}\n\n\tif imageName == \"\" {\n\t\treturn nil, fmt.Errorf(\"no image alias for %s\", startAttributes.OsxImage)\n\t}\n\n\tstartBooting := time.Now()\n\n\tbodyPayload := map[string]map[string]string{\n\t\t\"data\": {\n\t\t\t\"type\":       \"instances\",\n\t\t\t\"base-image\": imageName,\n\t\t},\n\t}\n\n\tjsonBody, err := json.Marshal(bodyPayload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := p.client.Post(u.String(), \"application\/vnd.api+json\", bytes.NewReader(jsonBody))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer io.Copy(ioutil.Discard, resp.Body)\n\tdefer resp.Body.Close()\n\n\tif c := resp.StatusCode; c < 200 || c >= 300 {\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"expected 2xx from Jupiter Brain API, got %d (error: %s)\", c, body)\n\t}\n\n\tvar dataPayload jupiterBrainDataResponse\n\terr = json.NewDecoder(resp.Body).Decode(&dataPayload)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't decode created payload: %s\", err)\n\t}\n\n\tpayload := dataPayload.Data[0]\n\n\tinstanceReady := make(chan jupiterBrainInstancePayload, 1)\n\terrChan := make(chan error, 1)\n\tgo func(id string) {\n\t\tu, err := p.baseURL.Parse(fmt.Sprintf(\"instances\/%s\", url.QueryEscape(id)))\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tfor true {\n\t\t\tresp, err := p.client.Do(req)\n\t\t\tif err != nil {\n\t\t\t\terrChan <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif resp.StatusCode != 200 {\n\t\t\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\t\t\terrChan <- fmt.Errorf(\"unknown status code: %d, expected 200 (body: %q)\", resp.StatusCode, string(body))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar dataPayload jupiterBrainDataResponse\n\t\t\terr = json.NewDecoder(resp.Body).Decode(&dataPayload)\n\t\t\tif err != nil {\n\t\t\t\terrChan <- fmt.Errorf(\"couldn't decode refresh payload: %s\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpayload := dataPayload.Data[0]\n\n\t\t\t_, _ = io.Copy(ioutil.Discard, resp.Body)\n\t\t\t_ = resp.Body.Close()\n\n\t\t\tvar ip net.IP\n\t\t\tfor _, ipString := range payload.IpAddresses {\n\t\t\t\tcurIp := net.ParseIP(ipString)\n\t\t\t\tif curIp.To4() != nil {\n\t\t\t\t\tip = curIp\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ip == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconn, err := net.Dial(\"tcp\", fmt.Sprintf(\"%s:22\", ip.String()))\n\t\t\tif conn != nil {\n\t\t\t\tconn.Close()\n\t\t\t}\n\n\t\t\tif err == nil {\n\t\t\t\tinstanceReady <- payload\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(payload.ID)\n\n\tselect {\n\tcase payload := <-instanceReady:\n\t\tmetrics.TimeSince(\"worker.vm.provider.jupiterbrain.boot\", startBooting)\n\t\tworkerctx.LoggerFromContext(ctx).WithField(\"instance_uuid\", payload.ID).Info(\"booted instance\")\n\t\treturn &JupiterBrainInstance{\n\t\t\tpayload:  payload,\n\t\t\tprovider: p,\n\t\t}, nil\n\tcase err := <-errChan:\n\t\tinstance := &JupiterBrainInstance{\n\t\t\tpayload:  payload,\n\t\t\tprovider: p,\n\t\t}\n\t\tinstance.Stop(ctx)\n\n\t\treturn nil, err\n\tcase <-ctx.Done():\n\t\tif ctx.Err() == context.DeadlineExceeded {\n\t\t\tmetrics.Mark(\"worker.vm.provider.jupiterbrain.boot.timeout\")\n\t\t}\n\n\t\tinstance := &JupiterBrainInstance{\n\t\t\tpayload:  payload,\n\t\t\tprovider: p,\n\t\t}\n\t\tinstance.Stop(ctx)\n\n\t\treturn nil, ctx.Err()\n\t}\n}\n\nfunc (i *JupiterBrainInstance) UploadScript(ctx context.Context, script []byte) error {\n\tclient, err := i.sshClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\n\tsftp, err := sftp.NewClient(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer sftp.Close()\n\n\tf, err := sftp.Create(\"build.sh\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = f.Write(script)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err = sftp.Create(\"wrapper.sh\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = fmt.Fprintf(f, `#!\/bin\/bash\n\n[[ -f ~\/build.sh.exit ]] && rm ~\/build.sh.exit\n\nuntil nc 127.0.0.1 15782; do sleep 1; done\n\nuntil [[ -f ~\/build.sh.exit ]]; do sleep 1; done\nexit $(cat ~\/build.sh.exit)\n`)\n\n\treturn err\n}\n\nfunc (i *JupiterBrainInstance) RunScript(ctx context.Context, output io.WriteCloser) (RunResult, error) {\n\tclient, err := i.sshClient()\n\tif err != nil {\n\t\treturn RunResult{Completed: false}, err\n\t}\n\tdefer client.Close()\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn RunResult{Completed: false}, err\n\t}\n\tdefer session.Close()\n\n\terr = session.RequestPty(\"xterm\", 80, 40, ssh.TerminalModes{})\n\tif err != nil {\n\t\treturn RunResult{Completed: false}, err\n\t}\n\n\tsession.Stdout = output\n\tsession.Stderr = output\n\n\terr = session.Run(\"bash ~\/wrapper.sh\")\n\tdefer output.Close()\n\tif err == nil {\n\t\treturn RunResult{Completed: true, ExitCode: 0}, nil\n\t}\n\n\tswitch err := err.(type) {\n\tcase *ssh.ExitError:\n\t\treturn RunResult{Completed: true, ExitCode: uint8(err.ExitStatus())}, nil\n\tdefault:\n\t\treturn RunResult{Completed: false}, err\n\t}\n}\n\nfunc (i *JupiterBrainInstance) Stop(ctx context.Context) error {\n\tu, err := i.provider.baseURL.Parse(fmt.Sprintf(\"instances\/%s\", url.QueryEscape(i.payload.ID)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := http.NewRequest(\"DELETE\", u.String(), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := i.provider.client.Do(req)\n\tio.Copy(ioutil.Discard, resp.Body)\n\tresp.Body.Close()\n\treturn err\n}\n\nfunc (i *JupiterBrainInstance) sshClient() (*ssh.Client, error) {\n\tfile, err := ioutil.ReadFile(i.provider.sshKeyPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, _ := pem.Decode(file)\n\tif block == nil {\n\t\treturn nil, fmt.Errorf(\"ssh key does not contain a valid PEM block\")\n\t}\n\n\tder, err := x509.DecryptPEMBlock(block, []byte(i.provider.sshKeyPassphrase))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey, err := x509.ParsePKCS1PrivateKey(der)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsigner, err := ssh.NewSignerFromKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ip net.IP\n\tfor _, ipString := range i.payload.IpAddresses {\n\t\tcurIp := net.ParseIP(ipString)\n\t\tif curIp.To4() != nil {\n\t\t\tip = curIp\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\tif ip == nil {\n\t\treturn nil, fmt.Errorf(\"no valid IPv4 address\")\n\t}\n\n\treturn ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:22\", ip.String()), &ssh.ClientConfig{\n\t\tUser: \"travis\",\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t})\n}\n<commit_msg>jupiterbrain: pass authentication token to API<commit_after>package backend\n\nimport (\n\t\"bytes\"\n\t\"crypto\/x509\"\n\t\"encoding\/json\"\n\t\"encoding\/pem\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/pkg\/sftp\"\n\tworkerctx \"github.com\/travis-ci\/worker\/lib\/context\"\n\t\"github.com\/travis-ci\/worker\/lib\/metrics\"\n\t\"golang.org\/x\/crypto\/ssh\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar nonAlphaNumRegexp = regexp.MustCompile(`[^a-zA-Z0-9_]+`)\n\ntype JupiterBrainProvider struct {\n\tclient           *http.Client\n\tbaseURL          *url.URL\n\timageAliases     map[string]string\n\tsshKeyPath       string\n\tsshKeyPassphrase string\n\tkeychainPassword string\n}\n\ntype JupiterBrainInstance struct {\n\tpayload  jupiterBrainInstancePayload\n\tprovider *JupiterBrainProvider\n}\n\ntype jupiterBrainInstancePayload struct {\n\tID          string   `json:\"id\"`\n\tIpAddresses []string `json:\"ip-addresses\"`\n\tState       string   `json:\"state\"`\n\tBaseImage   string   `json:\"base-image,omitempty\"`\n\tType        string   `json:\"type,omitempty\"`\n}\n\ntype jupiterBrainDataResponse struct {\n\tData []jupiterBrainInstancePayload `json:\"data\"`\n}\n\nfunc NewJupiterBrainProvider(config map[string]string) (*JupiterBrainProvider, error) {\n\tendpoint, ok := config[\"endpoint\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected endpoint config key\")\n\t}\n\tbaseURL, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taliasNames, ok := config[\"image_aliases\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected image_aliases config key\")\n\t}\n\n\timageAliases := make(map[string]string, len(aliasNames))\n\n\tfor _, aliasName := range strings.Split(aliasNames, \",\") {\n\t\tnormalizedAliasName := string(nonAlphaNumRegexp.ReplaceAll([]byte(aliasName), []byte(\"_\")))\n\n\t\timageName, ok := config[fmt.Sprintf(\"image_alias_%s\", normalizedAliasName)]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"expected image alias %q\", aliasName)\n\t\t}\n\n\t\timageAliases[aliasName] = imageName\n\t}\n\n\tsshKeyPath, ok := config[\"ssh_key_path\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected ssh_key_path config key\")\n\t}\n\n\tsshKeyPassphrase, ok := config[\"ssh_key_passphrase\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected ssh_key_passphrase config key\")\n\t}\n\n\tkeychainPassword, ok := config[\"keychain_password\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"expected keychain_password config key\")\n\t}\n\n\treturn &JupiterBrainProvider{\n\t\tclient:           http.DefaultClient,\n\t\tbaseURL:          baseURL,\n\t\timageAliases:     imageAliases,\n\t\tsshKeyPath:       sshKeyPath,\n\t\tsshKeyPassphrase: sshKeyPassphrase,\n\t\tkeychainPassword: keychainPassword,\n\t}, nil\n}\n\nfunc (p *JupiterBrainProvider) Start(ctx context.Context, startAttributes StartAttributes) (Instance, error) {\n\tu, err := p.baseURL.Parse(\"instances\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\timageName, ok := p.imageAliases[startAttributes.OsxImage]\n\tif !ok {\n\t\timageName, _ = p.imageAliases[\"default\"]\n\t}\n\n\tif imageName == \"\" {\n\t\treturn nil, fmt.Errorf(\"no image alias for %s\", startAttributes.OsxImage)\n\t}\n\n\tstartBooting := time.Now()\n\n\tbodyPayload := map[string]map[string]string{\n\t\t\"data\": {\n\t\t\t\"type\":       \"instances\",\n\t\t\t\"base-image\": imageName,\n\t\t},\n\t}\n\n\tjsonBody, err := json.Marshal(bodyPayload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", u.String(), bytes.NewReader(jsonBody))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application\/vnd.api+json\")\n\n\tresp, err := p.httpDo(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer io.Copy(ioutil.Discard, resp.Body)\n\tdefer resp.Body.Close()\n\n\tif c := resp.StatusCode; c < 200 || c >= 300 {\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"expected 2xx from Jupiter Brain API, got %d (error: %s)\", c, body)\n\t}\n\n\tvar dataPayload jupiterBrainDataResponse\n\terr = json.NewDecoder(resp.Body).Decode(&dataPayload)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't decode created payload: %s\", err)\n\t}\n\n\tpayload := dataPayload.Data[0]\n\n\tinstanceReady := make(chan jupiterBrainInstancePayload, 1)\n\terrChan := make(chan error, 1)\n\tgo func(id string) {\n\t\tu, err := p.baseURL.Parse(fmt.Sprintf(\"instances\/%s\", url.QueryEscape(id)))\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tfor true {\n\t\t\tresp, err := p.httpDo(req)\n\t\t\tif err != nil {\n\t\t\t\terrChan <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif resp.StatusCode != 200 {\n\t\t\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\t\t\terrChan <- fmt.Errorf(\"unknown status code: %d, expected 200 (body: %q)\", resp.StatusCode, string(body))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar dataPayload jupiterBrainDataResponse\n\t\t\terr = json.NewDecoder(resp.Body).Decode(&dataPayload)\n\t\t\tif err != nil {\n\t\t\t\terrChan <- fmt.Errorf(\"couldn't decode refresh payload: %s\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpayload := dataPayload.Data[0]\n\n\t\t\t_, _ = io.Copy(ioutil.Discard, resp.Body)\n\t\t\t_ = resp.Body.Close()\n\n\t\t\tvar ip net.IP\n\t\t\tfor _, ipString := range payload.IpAddresses {\n\t\t\t\tcurIp := net.ParseIP(ipString)\n\t\t\t\tif curIp.To4() != nil {\n\t\t\t\t\tip = curIp\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif ip == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconn, err := net.Dial(\"tcp\", fmt.Sprintf(\"%s:22\", ip.String()))\n\t\t\tif conn != nil {\n\t\t\t\tconn.Close()\n\t\t\t}\n\n\t\t\tif err == nil {\n\t\t\t\tinstanceReady <- payload\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}(payload.ID)\n\n\tselect {\n\tcase payload := <-instanceReady:\n\t\tmetrics.TimeSince(\"worker.vm.provider.jupiterbrain.boot\", startBooting)\n\t\tworkerctx.LoggerFromContext(ctx).WithField(\"instance_uuid\", payload.ID).Info(\"booted instance\")\n\t\treturn &JupiterBrainInstance{\n\t\t\tpayload:  payload,\n\t\t\tprovider: p,\n\t\t}, nil\n\tcase err := <-errChan:\n\t\tinstance := &JupiterBrainInstance{\n\t\t\tpayload:  payload,\n\t\t\tprovider: p,\n\t\t}\n\t\tinstance.Stop(ctx)\n\n\t\treturn nil, err\n\tcase <-ctx.Done():\n\t\tif ctx.Err() == context.DeadlineExceeded {\n\t\t\tmetrics.Mark(\"worker.vm.provider.jupiterbrain.boot.timeout\")\n\t\t}\n\n\t\tinstance := &JupiterBrainInstance{\n\t\t\tpayload:  payload,\n\t\t\tprovider: p,\n\t\t}\n\t\tinstance.Stop(ctx)\n\n\t\treturn nil, ctx.Err()\n\t}\n}\n\nfunc (p *JupiterBrainProvider) httpDo(req *http.Request) (*http.Response, error) {\n\tif req.URL.User != nil {\n\t\ttoken := req.URL.User.Username()\n\t\treq.URL.User = nil\n\t\treq.Header.Set(\"Authorization\", \"token \"+token)\n\t}\n\n\treturn p.client.Do(req)\n}\n\nfunc (i *JupiterBrainInstance) UploadScript(ctx context.Context, script []byte) error {\n\tclient, err := i.sshClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer client.Close()\n\n\tsftp, err := sftp.NewClient(client)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer sftp.Close()\n\n\tf, err := sftp.Create(\"build.sh\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = f.Write(script)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err = sftp.Create(\"wrapper.sh\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = fmt.Fprintf(f, `#!\/bin\/bash\n\n[[ -f ~\/build.sh.exit ]] && rm ~\/build.sh.exit\n\nuntil nc 127.0.0.1 15782; do sleep 1; done\n\nuntil [[ -f ~\/build.sh.exit ]]; do sleep 1; done\nexit $(cat ~\/build.sh.exit)\n`)\n\n\treturn err\n}\n\nfunc (i *JupiterBrainInstance) RunScript(ctx context.Context, output io.WriteCloser) (RunResult, error) {\n\tclient, err := i.sshClient()\n\tif err != nil {\n\t\treturn RunResult{Completed: false}, err\n\t}\n\tdefer client.Close()\n\n\tsession, err := client.NewSession()\n\tif err != nil {\n\t\treturn RunResult{Completed: false}, err\n\t}\n\tdefer session.Close()\n\n\terr = session.RequestPty(\"xterm\", 80, 40, ssh.TerminalModes{})\n\tif err != nil {\n\t\treturn RunResult{Completed: false}, err\n\t}\n\n\tsession.Stdout = output\n\tsession.Stderr = output\n\n\terr = session.Run(\"bash ~\/wrapper.sh\")\n\tdefer output.Close()\n\tif err == nil {\n\t\treturn RunResult{Completed: true, ExitCode: 0}, nil\n\t}\n\n\tswitch err := err.(type) {\n\tcase *ssh.ExitError:\n\t\treturn RunResult{Completed: true, ExitCode: uint8(err.ExitStatus())}, nil\n\tdefault:\n\t\treturn RunResult{Completed: false}, err\n\t}\n}\n\nfunc (i *JupiterBrainInstance) Stop(ctx context.Context) error {\n\tu, err := i.provider.baseURL.Parse(fmt.Sprintf(\"instances\/%s\", url.QueryEscape(i.payload.ID)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := http.NewRequest(\"DELETE\", u.String(), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresp, err := i.provider.httpDo(req)\n\tio.Copy(ioutil.Discard, resp.Body)\n\tresp.Body.Close()\n\treturn err\n}\n\nfunc (i *JupiterBrainInstance) sshClient() (*ssh.Client, error) {\n\tfile, err := ioutil.ReadFile(i.provider.sshKeyPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, _ := pem.Decode(file)\n\tif block == nil {\n\t\treturn nil, fmt.Errorf(\"ssh key does not contain a valid PEM block\")\n\t}\n\n\tder, err := x509.DecryptPEMBlock(block, []byte(i.provider.sshKeyPassphrase))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey, err := x509.ParsePKCS1PrivateKey(der)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsigner, err := ssh.NewSignerFromKey(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar ip net.IP\n\tfor _, ipString := range i.payload.IpAddresses {\n\t\tcurIp := net.ParseIP(ipString)\n\t\tif curIp.To4() != nil {\n\t\t\tip = curIp\n\t\t\tbreak\n\t\t}\n\n\t}\n\n\tif ip == nil {\n\t\treturn nil, fmt.Errorf(\"no valid IPv4 address\")\n\t}\n\n\treturn ssh.Dial(\"tcp\", fmt.Sprintf(\"%s:22\", ip.String()), &ssh.ClientConfig{\n\t\tUser: \"travis\",\n\t\tAuth: []ssh.AuthMethod{\n\t\t\tssh.PublicKeys(signer),\n\t\t},\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package sanity\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/pkg\/api\/v1\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n)\n\nconst (\n\t\/\/ nodeCountVar is the environment variable to check for Node count.\n\tnodeCountVar = \"NODE_COUNT\"\n\n\t\/\/ kubeconfigEnv is the environment variable that is checked for a the kubeconfig path to be loaded.\n\tkubeconfigEnv = \"TEST_KUBECONFIG\"\n)\n\ntype timer struct {\n\ttimeout time.Time\n}\n\nfunc newTimer(timeout time.Duration) *timer {\n\treturn &timer{time.Now().Add(timeout)}\n}\n\nfunc (t *timer) timedOut() bool {\n\treturn time.Now().After(t.timeout)\n}\n\nfunc newClient(t *testing.T) *kubernetes.Clientset {\n\tkcfgPath := os.Getenv(kubeconfigEnv)\n\tif len(kcfgPath) == 0 {\n\t\tt.Fatalf(\"no kubeconfig path in environment variable %s\", kubeconfigEnv)\n\t}\n\n\trules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: kcfgPath}\n\tcfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, &clientcmd.ConfigOverrides{})\n\trestConfig, err := cfg.ClientConfig()\n\tif err != nil {\n\t\tt.Fatalf(\"could not create client config: %v\", err)\n\t}\n\n\tcs, err := kubernetes.NewForConfig(restConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"could not create clientset: %v\", err)\n\t}\n\treturn cs\n}\n\nfunc TestCluster(t *testing.T) {\n\t\/\/ verify that api server is up in 10 min\n\tt.Run(\"APIAvailable\", testAPIAvailable)\n\n\t\/\/ wait for all nodes to become available\n\tt.Run(\"AllNodesRunning\", testAllNodesRunning)\n\tt.Run(\"AllPodsRunning\", testAllPodsRunning)\n\tt.Run(\"GetLogs\", testLogs)\n\tt.Run(\"KillAPIServer\", testKillAPIServer)\n}\n\nfunc testAPIAvailable(t *testing.T) {\n\t\/\/ chan signaled when API server found\n\tdone := waitForAPIServer(t)\n\n\t\/\/ timeout searching for server\n\twait := 10 * time.Minute\n\tt.Logf(\"Waiting %v for API server to become available\", wait)\n\n\ttimeout := time.After(wait)\n\tselect {\n\tcase <-timeout:\n\t\tt.Fatalf(\"Could not connect to API server in %v, FAILING!\", wait)\n\tcase <-done:\n\t\tt.Log(\"API server is available.\")\n\t\treturn\n\t}\n}\n\nfunc testAllPodsRunning(t *testing.T) {\n\tc := newClient(t)\n\n\ttimer := newTimer(10 * time.Minute)\n\n\tfor {\n\t\tif timer.timedOut() {\n\t\t\tt.Fatalf(\"timed out waiting for pods to be ready.\")\n\t\t}\n\n\t\tpods, err := c.Core().Pods(\"\").List(v1.ListOptions{})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"could not list pods: %v\", err)\n\t\t}\n\n\t\tallReady := len(pods.Items) != 0\n\t\tfor _, p := range pods.Items {\n\t\t\tif p.Status.Phase != v1.PodRunning {\n\t\t\t\tallReady = false\n\t\t\t\tt.Logf(\"pod %s\/%s not running\", p.Namespace, p.Name)\n\t\t\t}\n\t\t}\n\t\tif allReady {\n\t\t\treturn\n\t\t}\n\n\t\ttime.Sleep(3 * time.Second)\n\t}\n}\n\nfunc testLogs(t *testing.T) {\n\t\/\/ TODO: Diagnose why this fails.\n\tt.SkipNow()\n\tc := newClient(t)\n\n\tnamespace := \"tectonic-system\"\n\tpodPrefix := \"tectonic-identity\"\n\n\twait := 3 * time.Minute\n\ttimeout := time.After(wait)\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tfor {\n\t\t\terr := validatePodLogging(c, namespace, podPrefix)\n\t\t\tif err == nil {\n\t\t\t\tdone <- struct{}{}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tt.Log(\"Failed to get Pod logs with error: \", err)\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-timeout:\n\t\tt.Fatalf(\"Failed to gather logs for %s\/%s* in %v\", namespace, podPrefix, wait)\n\tcase <-done:\n\t\treturn\n\t}\n}\n\n\/\/ validatePodLogging verifies that logs can be retrieved for a container in Pod.\nfunc validatePodLogging(c *kubernetes.Clientset, namespace, podPrefix string) error {\n\tpods, err := c.Pods(namespace).List(v1.ListOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not list pods: %v\", err)\n\t}\n\n\tvar names string\n\tfor _, p := range pods.Items {\n\t\tif len(names) != 0 {\n\t\t\tnames += \", \"\n\t\t}\n\t\tnames += p.Name\n\n\t\tif !strings.HasPrefix(p.Name, podPrefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif len(p.Spec.Containers) == 0 {\n\t\t\treturn fmt.Errorf(\"tectonic identity pod has no containers\")\n\t\t}\n\n\t\topt := v1.PodLogOptions{\n\t\t\tContainer: p.Spec.Containers[0].Name,\n\t\t}\n\n\t\tresult := c.Core().Pods(namespace).GetLogs(p.Name, &opt).Do()\n\t\tif err := result.Error(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get pod logs: %v\", err)\n\t\t}\n\n\t\tvar statusCode int\n\t\tresult.StatusCode(&statusCode)\n\t\tif statusCode\/100 != 2 {\n\t\t\treturn fmt.Errorf(\"expected 200 from log response, got %d\", statusCode)\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"failed to find tectonic-identity pod (found pods in %s: %s)\", namespace, names)\n}\n\nfunc testAllNodesRunning(t *testing.T) {\n\tc := newClient(t)\n\n\texpNodeCount, err := strconv.Atoi(os.Getenv(nodeCountVar))\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get number of expected nodes from envvar %s: %v\", nodeCountVar, err)\n\t}\n\n\ttimer := newTimer(10 * time.Minute)\n\tfor {\n\t\tif timer.timedOut() {\n\t\t\tt.Fatalf(\"timed out waiting for nodes to be ready.\")\n\t\t}\n\n\t\tnodes, err := c.Core().Nodes().List(v1.ListOptions{})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"could not list nodes: %v\", err)\n\t\t}\n\n\t\tallReady := len(nodes.Items) != 0\n\t\tfor _, node := range nodes.Items {\n\t\t\tif nodeReady(node) {\n\t\t\t\tt.Logf(\"node %s ready\", node.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallReady = false\n\t\t\tt.Logf(\"node %s not ready\", node.Name)\n\t\t}\n\n\t\tif allReady {\n\t\t\treturn\n\t\t}\n\n\t\tif got := len(nodes.Items); got != expNodeCount {\n\t\t\tt.Logf(\"expected %d nodes got %d\", expNodeCount, got)\n\t\t}\n\n\t\ttime.Sleep(10 * time.Second)\n\t}\n}\n\nfunc testKillAPIServer(t *testing.T) {\n\tc := newClient(t)\n\tpods, err := getAPIServers(c)\n\tif err != nil {\n\t\tt.Fatalf(\"get apiserver pod: %v\", err)\n\t}\n\n\toldPod := map[string]bool{}\n\n\t\/\/ Nuke all API servers.\n\tfor _, pod := range pods.Items {\n\t\tif err := c.Core().Pods(pod.Namespace).Delete(pod.Name, nil); err != nil {\n\t\t\tt.Fatalf(\"failed to delete pod %s: %v\", pod.Name, err)\n\t\t}\n\t\toldPod[pod.Name] = true\n\t}\n\n\t\/\/ API servers and temp API servers come in and out. Ensure\n\t\/\/ that the API server we detect is running for a couple\n\t\/\/ iterations.\n\trunningLastTime := false\n\n\tapiServerUp := func() bool {\n\t\tpods, err := getAPIServers(c)\n\t\tif err != nil {\n\t\t\tt.Logf(\"get apiserver pod: %v\", err)\n\t\t\treturn false\n\t\t}\n\n\t\tfor _, pod := range pods.Items {\n\t\t\tif oldPod[pod.Name] {\n\t\t\t\tt.Logf(\"old API server %s still running\", pod.Name)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\tallReady := len(pods.Items) != 0\n\t\tfor _, p := range pods.Items {\n\t\t\tif p.Status.Phase != v1.PodRunning {\n\t\t\t\tallReady = false\n\t\t\t}\n\t\t}\n\n\t\tif allReady {\n\t\t\tif runningLastTime {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\trunningLastTime = true\n\t\t}\n\t\treturn false\n\t}\n\n\ttimer := newTimer(6 * time.Minute)\n\tfor {\n\t\tif timer.timedOut() {\n\t\t\tt.Fatalf(\"timed out waiting for pods to be ready.\")\n\t\t}\n\n\t\tif apiServerUp() {\n\t\t\treturn\n\t\t}\n\n\t\ttime.Sleep(10 * time.Second)\n\t}\n}\n\nfunc waitForAPIServer(t *testing.T) <-chan struct{} {\n\tdone := make(chan struct{}, 1)\n\tgo func() {\n\t\tvar client *kubernetes.Clientset\n\t\tfor {\n\t\t\tclient = newClient(t)\n\t\t\t_, err := client.ServerVersion()\n\t\t\tif err == nil {\n\t\t\t\tdone <- struct{}{}\n\t\t\t\treturn\n\t\t\t}\n\t\t\twait := 10 * time.Second\n\t\t\tt.Logf(\"Waiting %v after failed attempt to connect to API server. Error was: %v\", wait, err)\n\t\t\ttime.Sleep(wait)\n\t\t}\n\t}()\n\treturn done\n}\n\nfunc getAPIServers(client *kubernetes.Clientset) (*v1.PodList, error) {\n\tconst (\n\t\tapiServerSelector   = \"k8s-app=kube-apiserver\"\n\t\tkubeSystemNamespace = \"kube-system\"\n\t)\n\tpods, err := client.Core().Pods(kubeSystemNamespace).List(v1.ListOptions{LabelSelector: apiServerSelector})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(pods.Items) == 0 {\n\t\treturn nil, fmt.Errorf(\"no pods matched the label selector %q in the %s namespace\", apiServerSelector, kubeSystemNamespace)\n\t}\n\treturn pods, nil\n}\n\n\/\/ podsStr prints a comma separated list of namespaced Pod names\nfunc podsStr(pods []v1.Pod) (out string) {\n\tfor n, p := range pods {\n\t\t\/\/ add comma to all entries except first\n\t\tif n != 0 {\n\t\t\tout += \", \"\n\t\t}\n\t\tout += fmt.Sprintf(\"%s\/%s\", p.GetNamespace(), p.GetName())\n\t}\n\treturn\n}\n\nfunc nodeReady(node v1.Node) (ok bool) {\n\tfor _, cond := range node.Status.Conditions {\n\t\tif cond.Type == v1.NodeReady {\n\t\t\treturn cond.Status == v1.ConditionTrue\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>installer\/tests\/sanity: enable Pod logging test<commit_after>package sanity\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/pkg\/api\/v1\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n)\n\nconst (\n\t\/\/ nodeCountVar is the environment variable to check for Node count.\n\tnodeCountVar = \"NODE_COUNT\"\n\n\t\/\/ kubeconfigEnv is the environment variable that is checked for a the kubeconfig path to be loaded.\n\tkubeconfigEnv = \"TEST_KUBECONFIG\"\n)\n\ntype timer struct {\n\ttimeout time.Time\n}\n\nfunc newTimer(timeout time.Duration) *timer {\n\treturn &timer{time.Now().Add(timeout)}\n}\n\nfunc (t *timer) timedOut() bool {\n\treturn time.Now().After(t.timeout)\n}\n\nfunc newClient(t *testing.T) *kubernetes.Clientset {\n\tkcfgPath := os.Getenv(kubeconfigEnv)\n\tif len(kcfgPath) == 0 {\n\t\tt.Fatalf(\"no kubeconfig path in environment variable %s\", kubeconfigEnv)\n\t}\n\n\trules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: kcfgPath}\n\tcfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, &clientcmd.ConfigOverrides{})\n\trestConfig, err := cfg.ClientConfig()\n\tif err != nil {\n\t\tt.Fatalf(\"could not create client config: %v\", err)\n\t}\n\n\tcs, err := kubernetes.NewForConfig(restConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"could not create clientset: %v\", err)\n\t}\n\treturn cs\n}\n\nfunc TestCluster(t *testing.T) {\n\t\/\/ verify that api server is up in 10 min\n\tt.Run(\"APIAvailable\", testAPIAvailable)\n\n\t\/\/ wait for all nodes to become available\n\tt.Run(\"AllNodesRunning\", testAllNodesRunning)\n\tt.Run(\"GetLogs\", testLogs)\n\tt.Run(\"AllPodsRunning\", testAllPodsRunning)\n\tt.Run(\"KillAPIServer\", testKillAPIServer)\n}\n\nfunc testAPIAvailable(t *testing.T) {\n\t\/\/ chan signaled when API server found\n\tdone := waitForAPIServer(t)\n\n\t\/\/ timeout searching for server\n\twait := 10 * time.Minute\n\tt.Logf(\"Waiting %v for API server to become available\", wait)\n\n\ttimeout := time.After(wait)\n\tselect {\n\tcase <-timeout:\n\t\tt.Fatalf(\"Could not connect to API server in %v, FAILING!\", wait)\n\tcase <-done:\n\t\tt.Log(\"API server is available.\")\n\t\treturn\n\t}\n}\n\nfunc testAllPodsRunning(t *testing.T) {\n\tc := newClient(t)\n\n\ttimer := newTimer(10 * time.Minute)\n\n\tfor {\n\t\tif timer.timedOut() {\n\t\t\tt.Fatalf(\"timed out waiting for pods to be ready.\")\n\t\t}\n\n\t\tpods, err := c.Core().Pods(\"\").List(v1.ListOptions{})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"could not list pods: %v\", err)\n\t\t}\n\n\t\tallReady := len(pods.Items) != 0\n\t\tfor _, p := range pods.Items {\n\t\t\tif p.Status.Phase != v1.PodRunning {\n\t\t\t\tallReady = false\n\t\t\t\tt.Logf(\"pod %s\/%s not running\", p.Namespace, p.Name)\n\t\t\t}\n\t\t}\n\t\tif allReady {\n\t\t\treturn\n\t\t}\n\n\t\ttime.Sleep(3 * time.Second)\n\t}\n}\n\nfunc testLogs(t *testing.T) {\n\tc := newClient(t)\n\n\tnamespace := \"tectonic-system\"\n\tpodPrefix := \"tectonic-identity\"\n\n\twait := 3 * time.Minute\n\ttimeout := time.After(wait)\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tfor {\n\t\t\terr := validatePodLogging(c, namespace, podPrefix)\n\t\t\tif err == nil {\n\t\t\t\tdone <- struct{}{}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tt.Log(\"Failed to get Pod logs with error: \", err)\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-timeout:\n\t\tt.Fatalf(\"Failed to gather logs for %s\/%s* in %v\", namespace, podPrefix, wait)\n\tcase <-done:\n\t\treturn\n\t}\n}\n\n\/\/ validatePodLogging verifies that logs can be retrieved for a container in Pod.\nfunc validatePodLogging(c *kubernetes.Clientset, namespace, podPrefix string) error {\n\tpods, err := c.Pods(namespace).List(v1.ListOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not list pods: %v\", err)\n\t}\n\n\tvar names string\n\tfor _, p := range pods.Items {\n\t\tif len(names) != 0 {\n\t\t\tnames += \", \"\n\t\t}\n\t\tnames += p.Name\n\n\t\tif !strings.HasPrefix(p.Name, podPrefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif len(p.Spec.Containers) == 0 {\n\t\t\treturn fmt.Errorf(\"tectonic identity pod has no containers\")\n\t\t}\n\n\t\topt := v1.PodLogOptions{\n\t\t\tContainer: p.Spec.Containers[0].Name,\n\t\t}\n\n\t\tresult := c.Core().Pods(namespace).GetLogs(p.Name, &opt).Do()\n\t\tif err := result.Error(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get pod logs: %v\", err)\n\t\t}\n\n\t\tvar statusCode int\n\t\tresult.StatusCode(&statusCode)\n\t\tif statusCode\/100 != 2 {\n\t\t\treturn fmt.Errorf(\"expected 200 from log response, got %d\", statusCode)\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"failed to find tectonic-identity pod (found pods in %s: %s)\", namespace, names)\n}\n\nfunc testAllNodesRunning(t *testing.T) {\n\tc := newClient(t)\n\n\texpNodeCount, err := strconv.Atoi(os.Getenv(nodeCountVar))\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get number of expected nodes from envvar %s: %v\", nodeCountVar, err)\n\t}\n\n\ttimer := newTimer(10 * time.Minute)\n\tfor {\n\t\tif timer.timedOut() {\n\t\t\tt.Fatalf(\"timed out waiting for nodes to be ready.\")\n\t\t}\n\n\t\tnodes, err := c.Core().Nodes().List(v1.ListOptions{})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"could not list nodes: %v\", err)\n\t\t}\n\n\t\tallReady := len(nodes.Items) != 0\n\t\tfor _, node := range nodes.Items {\n\t\t\tif nodeReady(node) {\n\t\t\t\tt.Logf(\"node %s ready\", node.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallReady = false\n\t\t\tt.Logf(\"node %s not ready\", node.Name)\n\t\t}\n\n\t\tif allReady {\n\t\t\treturn\n\t\t}\n\n\t\tif got := len(nodes.Items); got != expNodeCount {\n\t\t\tt.Logf(\"expected %d nodes got %d\", expNodeCount, got)\n\t\t}\n\n\t\ttime.Sleep(10 * time.Second)\n\t}\n}\n\nfunc testKillAPIServer(t *testing.T) {\n\tc := newClient(t)\n\tpods, err := getAPIServers(c)\n\tif err != nil {\n\t\tt.Fatalf(\"get apiserver pod: %v\", err)\n\t}\n\n\toldPod := map[string]bool{}\n\n\t\/\/ Nuke all API servers.\n\tfor _, pod := range pods.Items {\n\t\tif err := c.Core().Pods(pod.Namespace).Delete(pod.Name, nil); err != nil {\n\t\t\tt.Fatalf(\"failed to delete pod %s: %v\", pod.Name, err)\n\t\t}\n\t\toldPod[pod.Name] = true\n\t}\n\n\t\/\/ API servers and temp API servers come in and out. Ensure\n\t\/\/ that the API server we detect is running for a couple\n\t\/\/ iterations.\n\trunningLastTime := false\n\n\tapiServerUp := func() bool {\n\t\tpods, err := getAPIServers(c)\n\t\tif err != nil {\n\t\t\tt.Logf(\"get apiserver pod: %v\", err)\n\t\t\treturn false\n\t\t}\n\n\t\tfor _, pod := range pods.Items {\n\t\t\tif oldPod[pod.Name] {\n\t\t\t\tt.Logf(\"old API server %s still running\", pod.Name)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\tallReady := len(pods.Items) != 0\n\t\tfor _, p := range pods.Items {\n\t\t\tif p.Status.Phase != v1.PodRunning {\n\t\t\t\tallReady = false\n\t\t\t}\n\t\t}\n\n\t\tif allReady {\n\t\t\tif runningLastTime {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\trunningLastTime = true\n\t\t}\n\t\treturn false\n\t}\n\n\ttimer := newTimer(6 * time.Minute)\n\tfor {\n\t\tif timer.timedOut() {\n\t\t\tt.Fatalf(\"timed out waiting for pods to be ready.\")\n\t\t}\n\n\t\tif apiServerUp() {\n\t\t\treturn\n\t\t}\n\n\t\ttime.Sleep(10 * time.Second)\n\t}\n}\n\nfunc waitForAPIServer(t *testing.T) <-chan struct{} {\n\tdone := make(chan struct{}, 1)\n\tgo func() {\n\t\tvar client *kubernetes.Clientset\n\t\tfor {\n\t\t\tclient = newClient(t)\n\t\t\t_, err := client.ServerVersion()\n\t\t\tif err == nil {\n\t\t\t\tdone <- struct{}{}\n\t\t\t\treturn\n\t\t\t}\n\t\t\twait := 10 * time.Second\n\t\t\tt.Logf(\"Waiting %v after failed attempt to connect to API server. Error was: %v\", wait, err)\n\t\t\ttime.Sleep(wait)\n\t\t}\n\t}()\n\treturn done\n}\n\nfunc getAPIServers(client *kubernetes.Clientset) (*v1.PodList, error) {\n\tconst (\n\t\tapiServerSelector   = \"k8s-app=kube-apiserver\"\n\t\tkubeSystemNamespace = \"kube-system\"\n\t)\n\tpods, err := client.Core().Pods(kubeSystemNamespace).List(v1.ListOptions{LabelSelector: apiServerSelector})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(pods.Items) == 0 {\n\t\treturn nil, fmt.Errorf(\"no pods matched the label selector %q in the %s namespace\", apiServerSelector, kubeSystemNamespace)\n\t}\n\treturn pods, nil\n}\n\n\/\/ podsStr prints a comma separated list of namespaced Pod names\nfunc podsStr(pods []v1.Pod) (out string) {\n\tfor n, p := range pods {\n\t\t\/\/ add comma to all entries except first\n\t\tif n != 0 {\n\t\t\tout += \", \"\n\t\t}\n\t\tout += fmt.Sprintf(\"%s\/%s\", p.GetNamespace(), p.GetName())\n\t}\n\treturn\n}\n\nfunc nodeReady(node v1.Node) (ok bool) {\n\tfor _, cond := range node.Status.Conditions {\n\t\tif cond.Type == v1.NodeReady {\n\t\t\treturn cond.Status == v1.ConditionTrue\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2017 Circonus, Inc. <support@circonus.com>\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/\n\npackage builtins\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/builtins\/collector\"\n\tcgm \"github.com\/circonus-labs\/circonus-gometrics\/v3\"\n\t\"github.com\/rs\/zerolog\"\n)\n\n\/\/ fake collector stub\n\ntype foo struct {\n\tlastMetrics     cgm.Metrics\n\tid              string\n\tlastError       error\n\tlastEnd         time.Time\n\tlastStart       time.Time\n\tlogger          zerolog.Logger\n\tlastRunDuration time.Duration\n\tsync.Mutex\n}\n\nfunc newFoo() collector.Collector {\n\treturn &foo{id: \"foo\"}\n}\nfunc (f *foo) Collect(ctx context.Context) error {\n\tf.Lock()\n\tdefer f.Unlock()\n\tf.lastStart = time.Now()\n\tf.lastMetrics = cgm.Metrics{\"bar\": cgm.Metric{Type: \"i\", Value: 1}}\n\tf.lastEnd = time.Now()\n\tf.lastRunDuration = time.Since(f.lastStart)\n\treturn nil\n}\nfunc (f *foo) Flush() cgm.Metrics {\n\tf.Lock()\n\tdefer f.Unlock()\n\treturn f.lastMetrics\n}\nfunc (f *foo) ID() string {\n\tf.Lock()\n\tdefer f.Unlock()\n\treturn f.id\n}\nfunc (f *foo) Inventory() collector.InventoryStats {\n\treturn collector.InventoryStats{\n\t\tID:              f.id,\n\t\tLastRunStart:    f.lastStart.Format(time.RFC3339Nano),\n\t\tLastRunEnd:      f.lastEnd.Format(time.RFC3339Nano),\n\t\tLastRunDuration: f.lastRunDuration.String(),\n\t\tLastError:       f.lastError.Error(),\n\t}\n}\nfunc (f *foo) Logger() zerolog.Logger {\n\treturn f.logger\n}\n\n\/\/ end fake collector stub\n\nfunc TestNew(t *testing.T) {\n\tt.Log(\"Testing New\")\n\tzerolog.SetGlobalLevel(zerolog.Disabled)\n\n\tb, err := New(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t}\n\tif b == nil {\n\t\tt.Fatal(\"expected a builtins instance\")\n\t}\n}\n\nfunc TestRun(t *testing.T) {\n\tt.Log(\"Testing Run\")\n\tzerolog.SetGlobalLevel(zerolog.Disabled)\n\n\tt.Log(\"all (no collectors)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t}\n\n\t\trerr := b.Run(context.Background(), \"\")\n\t\tif rerr != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (no collectors)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t}\n\n\t\trerr := b.Run(context.Background(), \"foo\")\n\t\tif rerr != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t}\n\n\tt.Log(\"all (already running)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t\treturn\n\t\t}\n\n\t\tb.collectors[\"foo\"] = newFoo()\n\t\tb.running = true\n\n\t\trerr := b.Run(context.Background(), \"\")\n\t\tif rerr != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (unknown)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t\treturn\n\t\t}\n\n\t\tb.collectors[\"foo\"] = newFoo()\n\n\t\trerr := b.Run(context.Background(), \"bar\")\n\t\tif rerr != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t}\n\n\tt.Log(\"all (valid)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t\treturn\n\t\t}\n\n\t\tb.collectors[\"foo\"] = newFoo()\n\n\t\trerr := b.Run(context.Background(), \"\")\n\t\tif rerr != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (valid)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t\treturn\n\t\t}\n\n\t\tb.collectors[\"foo\"] = newFoo()\n\n\t\trerr := b.Run(context.Background(), \"foo\")\n\t\tif rerr != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t}\n}\n\nfunc TestIsBuiltIn(t *testing.T) {\n\tt.Log(\"Testing IsBuiltIn\")\n\tzerolog.SetGlobalLevel(zerolog.Disabled)\n\n\tt.Log(\"w\/o id\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t}\n\n\t\tif b.IsBuiltin(\"\") {\n\t\t\tt.Fatal(\"expected false\")\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (not found)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t\treturn\n\t\t}\n\n\t\tif b.IsBuiltin(\"foo\") {\n\t\t\tt.Fatal(\"expected false\")\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (valid)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t\treturn\n\t\t}\n\t\tb.collectors[\"foo\"] = newFoo()\n\n\t\tif !b.IsBuiltin(\"foo\") {\n\t\t\tt.Fatal(\"expected true\")\n\t\t}\n\t}\n}\n\nfunc TestFlush(t *testing.T) {\n\tt.Log(\"Testing Flush\")\n\tzerolog.SetGlobalLevel(zerolog.Disabled)\n\n\tt.Log(\"w\/o id\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t}\n\n\t\tmetrics := b.Flush(\"\")\n\t\tif metrics == nil {\n\t\t\tt.Fatal(\"expected metrics\")\n\t\t}\n\t\tif len(*metrics) > 0 {\n\t\t\tt.Fatalf(\"expected empty metrics, got %#v\", *metrics)\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (not found)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t}\n\n\t\tmetrics := b.Flush(\"foo\")\n\t\tif metrics == nil {\n\t\t\tt.Fatal(\"expected metrics\")\n\t\t}\n\t\tif len(*metrics) > 0 {\n\t\t\tt.Fatalf(\"expected empty metrics, got %#v\", *metrics)\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (valid)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t}\n\n\t\tb.collectors[\"foo\"] = newFoo()\n\t\t_ = b.collectors[\"foo\"].Collect(context.Background())\n\n\t\tmetrics := b.Flush(\"foo\")\n\t\tif metrics == nil {\n\t\t\tt.Fatal(\"expected metrics\")\n\t\t}\n\t\tif len(*metrics) == 0 {\n\t\t\tt.Fatalf(\"expected at least 1 metric, got %#v\", *metrics)\n\t\t}\n\t}\n}\n<commit_msg>upd: lint issue<commit_after>\/\/ Copyright © 2017 Circonus, Inc. <support@circonus.com>\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/\n\npackage builtins\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/builtins\/collector\"\n\tcgm \"github.com\/circonus-labs\/circonus-gometrics\/v3\"\n\t\"github.com\/rs\/zerolog\"\n)\n\n\/\/ fake collector stub\n\ntype foo struct {\n\tlastMetrics     cgm.Metrics\n\tid              string\n\tlastError       error\n\tlastEnd         time.Time\n\tlastStart       time.Time\n\tlogger          zerolog.Logger\n\tlastRunDuration time.Duration\n\tsync.Mutex\n}\n\nfunc newFoo() collector.Collector {\n\treturn &foo{id: \"foo\"}\n}\nfunc (f *foo) Collect(ctx context.Context) error {\n\tf.Lock()\n\tdefer f.Unlock()\n\tf.lastStart = time.Now()\n\tf.lastMetrics = cgm.Metrics{\"bar\": cgm.Metric{Type: \"i\", Value: 1}}\n\tf.lastEnd = time.Now()\n\tf.lastRunDuration = time.Since(f.lastStart)\n\treturn nil\n}\nfunc (f *foo) Flush() cgm.Metrics {\n\tf.Lock()\n\tdefer f.Unlock()\n\treturn f.lastMetrics\n}\nfunc (f *foo) ID() string {\n\tf.Lock()\n\tdefer f.Unlock()\n\treturn f.id\n}\nfunc (f *foo) Inventory() collector.InventoryStats {\n\treturn collector.InventoryStats{\n\t\tID:              f.id,\n\t\tLastRunStart:    f.lastStart.Format(time.RFC3339Nano),\n\t\tLastRunEnd:      f.lastEnd.Format(time.RFC3339Nano),\n\t\tLastRunDuration: f.lastRunDuration.String(),\n\t\tLastError:       f.lastError.Error(),\n\t}\n}\nfunc (f *foo) Logger() zerolog.Logger {\n\treturn f.logger\n}\n\n\/\/ end fake collector stub\n\nfunc TestNew(t *testing.T) {\n\tt.Log(\"Testing New\")\n\tzerolog.SetGlobalLevel(zerolog.Disabled)\n\n\tb, err := New(context.Background())\n\tif err != nil {\n\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t}\n\tif b == nil {\n\t\tt.Fatal(\"expected a builtins instance\")\n\t}\n}\n\nfunc TestRun(t *testing.T) {\n\tt.Log(\"Testing Run\")\n\tzerolog.SetGlobalLevel(zerolog.Disabled)\n\n\tt.Log(\"all (no collectors)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t}\n\n\t\trerr := b.Run(context.Background(), \"\")\n\t\tif rerr != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (no collectors)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t}\n\n\t\trerr := b.Run(context.Background(), \"foo\")\n\t\tif rerr != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t}\n\n\tt.Log(\"all (already running)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t\treturn\n\t\t}\n\n\t\tb.collectors[\"foo\"] = newFoo()\n\t\tb.running = true\n\n\t\trerr := b.Run(context.Background(), \"\")\n\t\tif rerr != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (unknown)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t\treturn\n\t\t}\n\n\t\tb.collectors[\"foo\"] = newFoo()\n\n\t\trerr := b.Run(context.Background(), \"bar\")\n\t\tif rerr != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t}\n\n\tt.Log(\"all (valid)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t\treturn\n\t\t}\n\n\t\tb.collectors[\"foo\"] = newFoo()\n\n\t\trerr := b.Run(context.Background(), \"\")\n\t\tif rerr != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (valid)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t\treturn\n\t\t}\n\n\t\tb.collectors[\"foo\"] = newFoo()\n\n\t\trerr := b.Run(context.Background(), \"foo\")\n\t\tif rerr != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t}\n}\n\nfunc TestIsBuiltIn(t *testing.T) {\n\tt.Log(\"Testing IsBuiltIn\")\n\tzerolog.SetGlobalLevel(zerolog.Disabled)\n\n\tt.Log(\"w\/o id\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t}\n\n\t\tif b.IsBuiltin(\"\") {\n\t\t\tt.Fatal(\"expected false\")\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (not found)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t\treturn\n\t\t}\n\n\t\tif b.IsBuiltin(\"foo\") {\n\t\t\tt.Fatal(\"expected false\")\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (valid)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t\treturn\n\t\t}\n\t\tb.collectors[\"foo\"] = newFoo()\n\n\t\tif !b.IsBuiltin(\"foo\") {\n\t\t\tt.Fatal(\"expected true\")\n\t\t}\n\t}\n}\n\nfunc TestFlush(t *testing.T) {\n\tt.Log(\"Testing Flush\")\n\tzerolog.SetGlobalLevel(zerolog.Disabled)\n\n\tt.Log(\"w\/o id\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t}\n\n\t\tmetrics := b.Flush(\"\")\n\t\tif metrics == nil {\n\t\t\tt.Fatal(\"expected metrics\")\n\t\t}\n\t\tif len(*metrics) > 0 { \/\/nolint:staticcheck\n\t\t\tt.Fatalf(\"expected empty metrics, got %#v\", *metrics)\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (not found)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t}\n\n\t\tmetrics := b.Flush(\"foo\")\n\t\tif metrics == nil {\n\t\t\tt.Fatal(\"expected metrics\")\n\t\t}\n\t\tif len(*metrics) > 0 {\n\t\t\tt.Fatalf(\"expected empty metrics, got %#v\", *metrics)\n\t\t}\n\t}\n\n\tt.Log(\"w\/id (valid)\")\n\t{\n\t\tb, err := New(context.Background())\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"expected NO error, got (%s)\", err)\n\t\t}\n\t\tif b == nil {\n\t\t\tt.Fatal(\"expected a builtins instance\")\n\t\t}\n\n\t\tb.collectors[\"foo\"] = newFoo()\n\t\t_ = b.collectors[\"foo\"].Collect(context.Background())\n\n\t\tmetrics := b.Flush(\"foo\")\n\t\tif metrics == nil {\n\t\t\tt.Fatal(\"expected metrics\")\n\t\t}\n\t\tif len(*metrics) == 0 {\n\t\t\tt.Fatalf(\"expected at least 1 metric, got %#v\", *metrics)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gojobs\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"reflect\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/pascallouisperez\/goutil\/errors\"\n\t\"github.com\/pascallouisperez\/reflext\"\n)\n\nconst (\n\tstatusPending    = \"pending\"\n\tstatusProcessing = \"processing\"\n\tstatusFailed     = \"failed\"\n\tstatusCompleted  = \"completed\"\n)\n\nconst (\n\t_ int32 = iota\n\tqueueStopped\n\tqueueStarting\n\tqueueRunning\n\tqueueStopping\n)\n\ntype clock interface {\n\t\/\/ UnixNow returns the number of seconds elapsed since January 1, 1970 UTC\n\t\/\/ Equivalent of time.Now().Unix()\n\tUnixNow() int64\n}\n\n\/\/ JobQueue is the entry point to registering, scheduling, and querying\n\/\/ jobs.\ntype JobQueue struct {\n\tnumFetchers int\n\tnumWorkers  int\n\n\tdb          *sql.DB\n\tprocessorId int64\n\tconfigs     map[string]jobConfig\n\tstatus      *int32\n\tworkersWg   sync.WaitGroup\n\tfetcherWg   sync.WaitGroup\n\tmaybeJobIds chan int64\n\tclock       clock\n}\n\ntype Job interface {\n\t\/\/ ID returns the identifier of the job.\n\tID() int64\n\n\t\/\/ Name returns the name of the job.\n\tName() string\n\n\t\/\/ Params returns the specific struct associated with this job.\n\tParams() (interface{}, error)\n}\n\ntype jobConfig struct {\n\tname             string\n\thandler          reflect.Value\n\tparamsType       reflect.Type\n\tattempts         int\n\tbackoffInSeconds int64\n}\n\ntype jobRecord struct {\n\tid            int64\n\tname          string\n\tparams        []byte\n\tremaining     int\n\tschedulableAt int64\n}\n\nfunc (rec *jobRecord) attempt(conf jobConfig) int {\n\treturn conf.attempts - rec.remaining\n}\n\ntype realClock struct{}\n\nfunc (realClock) UnixNow() int64 {\n\treturn time.Now().Unix()\n}\n\n\/\/ QueueConfiguration groups optional queue configuration parameters. For\n\/\/ all parameters, reasonable defaults are provided by the library.\ntype QueueConfiguration struct {\n\t\/\/ NumWorkers specifies the number of workers (i.e. goroutines processing\n\t\/\/ jobs) to spawn when this queue is started. Default is 5.\n\tNumWorkers int\n}\n\nfunc NewJobQueue(db *sql.DB, processorId int64, optConfs ...QueueConfiguration) *JobQueue {\n\tstatus := queueStopped\n\tjq := JobQueue{\n\t\tdb:          db,\n\t\tprocessorId: processorId,\n\t\tconfigs:     make(map[string]jobConfig, 10),\n\t\tstatus:      &status,\n\t\tclock:       realClock{},\n\t\tnumFetchers: 1,\n\t\tnumWorkers:  5,\n\t}\n\n\t\/\/ Optional configuration.\n\tif size := len(optConfs); size > 1 {\n\t\tpanic(\"too many configurations provided\")\n\t} else if size == 1 {\n\t\tconf := optConfs[0]\n\t\tif conf.NumWorkers > 0 {\n\t\t\tjq.numWorkers = conf.NumWorkers\n\t\t}\n\t}\n\n\treturn &jq\n}\n\nvar handlerMatcher = reflext.MustCompile(\"func ({*struct}) error\")\n\n\/\/ JobConfiguration groups optional job configuration parameters. For\n\/\/ all parameters, reasonable defaults are provided by the library.\ntype JobConfiguration struct {\n\t\/\/ Attempts specifies the number processing attempts to try before aborting\n\t\/\/ a job, and marking is failed.\n\tAttempts int\n\n\t\/\/ Backoff specifies the base duration off which the total exponential backoff\n\t\/\/ is calculated when the job is retried one, twice, thrice, etc.\n\t\/\/ While time.Duration can be expressed in nanoseconds, only durations of seconds\n\t\/\/ or more are considered valid.\n\tBackoff time.Duration\n}\n\nfunc (jq *JobQueue) Register(name string, handler interface{}, optConfs ...JobConfiguration) error {\n\tif name == \"\" {\n\t\treturn errors.New(\"job name cannot be empty\")\n\t}\n\n\tif _, ok := jq.configs[name]; ok {\n\t\treturn errors.New(\"job %s: already registered\", name)\n\t}\n\n\tif st := atomic.LoadInt32(jq.status); st != queueStopped {\n\t\t\/\/ TODO(pascal): if we cared about super pedantic, we should increment\n\t\t\/\/ a wait group on entry to Register, and wait on this wg in Start to\n\t\t\/\/ allow concurrent registrations to complete. But then, we should\n\t\t\/\/ also be careful about concurrent registrations writing to the shared\n\t\t\/\/ configs map. For now, we're going to assume registration is done in a\n\t\t\/\/ simple way.\n\t\treturn errors.New(\"job %s: unable to register once queue has started\", name)\n\t}\n\n\tif handler == nil {\n\t\treturn errors.New(\"job %s: missing handler\", name)\n\t}\n\n\tvar paramsType reflect.Type\n\tif types, ok := handlerMatcher.FindAll(handler); ok {\n\t\tparamsType = types[0]\n\t} else {\n\t\treturn errors.New(\"job %s: expected %s, was %T\", name, handlerMatcher, handler)\n\t}\n\n\t\/\/ Defaults.\n\tconf := jobConfig{\n\t\tname:             name,\n\t\thandler:          reflect.ValueOf(handler),\n\t\tparamsType:       paramsType,\n\t\tattempts:         3,\n\t\tbackoffInSeconds: 5,\n\t}\n\n\t\/\/ Optional configuration.\n\tif l := len(optConfs); l > 1 {\n\t\treturn errors.New(\"job %s: too many optional configurations provided\", name)\n\t} else if l == 1 {\n\t\toptConf := optConfs[0]\n\t\tif optConf.Attempts > 0 {\n\t\t\tconf.attempts = optConf.Attempts\n\t\t}\n\t\tif b := optConf.Backoff.Nanoseconds() \/ 1000000000; b > 0 {\n\t\t\tconf.backoffInSeconds = b\n\t\t}\n\t}\n\n\tjq.configs[name] = conf\n\treturn nil\n}\n\nfunc (jq *JobQueue) fetcher(fetcherIndex int) {\n\tjq.fetcherWg.Add(1)\n\tdefer jq.fetcherWg.Done()\n\n\tfor {\n\t\tif st := atomic.LoadInt32(jq.status); st == queueStopping {\n\t\t\treturn\n\t\t}\n\n\t\tjobId, hasNext, err := jq.maybeNext()\n\t\tif err != nil {\n\t\t\tglog.Infof(\"fetcher[%d], internal error while fetching potential next job: %s\", fetcherIndex, err)\n\t\t}\n\t\tif !hasNext {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\tjq.maybeJobIds <- jobId\n\t}\n}\n\nfunc (jq *JobQueue) worker(workerIndex int) {\n\tjq.workersWg.Add(1)\n\tdefer jq.workersWg.Done()\n\n\tfor {\n\t\tif st := atomic.LoadInt32(jq.status); st == queueStopping {\n\t\t\treturn\n\t\t}\n\n\t\tjobId := <-jq.maybeJobIds\n\n\t\tlocked, err := jq.attemptLock(jobId)\n\t\tif err != nil {\n\t\t\tglog.Infof(\"worker[%d] internal error while attempting to lock job: %s\", workerIndex, err)\n\t\t}\n\t\tif !locked {\n\t\t\tcontinue\n\t\t}\n\n\t\trec, err := jq.getJobRecord(jobId)\n\t\tif err != nil {\n\t\t\tglog.Infof(\"worker[%d] internal error while fetching job record: %s\", workerIndex, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tjobErr := jq.safeProcess(rec, jq.configs[rec.name])\n\t\tif jobErr != nil {\n\t\t\tif rec.remaining > 0 {\n\t\t\t\terr = jq.reEnqueue(rec)\n\t\t\t} else {\n\t\t\t\terr = jq.markAs(rec.id, statusFailed)\n\t\t\t}\n\t\t} else {\n\t\t\terr = jq.markAs(rec.id, statusCompleted)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tglog.Infof(\"worker[%d] internal error in post process of job: %s\", err)\n\t\t}\n\t}\n\n}\n\nfunc (jq *JobQueue) Start() error {\n\t\/\/ Mark queue as starting.\n\tif !atomic.CompareAndSwapInt32(jq.status, queueStopped, queueStarting) {\n\t\treturn errors.New(\"can only start a queue which is stopped\")\n\t}\n\n\t\/\/ Fresh channel.\n\tjq.maybeJobIds = make(chan int64)\n\n\t\/\/ Start fetchers.\n\tfor i := 0; i < jq.numFetchers; i++ {\n\t\tgo jq.fetcher(i)\n\t}\n\n\t\/\/ Start workers.\n\tfor i := 0; i < jq.numWorkers; i++ {\n\t\tgo jq.worker(i)\n\t}\n\n\t\/\/ Mark queue as running.\n\tatomic.StoreInt32(jq.status, queueRunning)\n\n\treturn nil\n}\n\nfunc (jq *JobQueue) Stop() error {\n\tif !atomic.CompareAndSwapInt32(jq.status, queueRunning, queueStopping) {\n\t\treturn errors.New(\"unable to stop\")\n\t}\n\tclose(jq.maybeJobIds)\n\tjq.workersWg.Wait()\n\tjq.fetcherWg.Wait()\n\tatomic.StoreInt32(jq.status, queueStopped)\n\tjq.maybeJobIds = nil\n\treturn nil\n}\n\nfunc (jq *JobQueue) Enqueue(tx *sql.Tx, name string, params interface{}) (int64, error) {\n\tconf, ok := jq.configs[name]\n\tif !ok {\n\t\treturn -1, errors.New(\"unknown job: %s\", name)\n\t}\n\n\tvar (\n\t\tparamsAsBytes []byte\n\t\terr           error\n\t)\n\tif params != nil {\n\t\tactualParamsType := reflect.TypeOf(params)\n\t\tif !actualParamsType.AssignableTo(conf.paramsType) {\n\t\t\treturn -1, errors.New(\"job %s: incorrect param type, expected %s, got %s\",\n\t\t\t\tconf.name, conf.paramsType, actualParamsType)\n\t\t}\n\n\t\tparamsAsBytes, err = json.Marshal(params)\n\t\tif err != nil {\n\t\t\treturn -1, errors.New(\"job %s: unable to marshall parms %s\", err)\n\t\t}\n\t}\n\n\tnow := jq.clock.UnixNow()\n\tres, err := tx.Exec(`\n\t\tinsert into job_queue (name, params, remaining, status, created_at, schedulable_at)\n\t\tvalues (?, ?, ?, ?, ?, ?)`,\n\t\tname, paramsAsBytes, conf.attempts, statusPending, now, now)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tjobId, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\treturn jobId, nil\n}\n\nfunc (jq *JobQueue) Get(jobId int64) (Job, error) {\n\trec, err := jq.getJobRecord(jobId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconf, ok := jq.configs[rec.name]\n\tif !ok {\n\t\treturn nil, errors.New(\"job %s has not been registered\", rec.name)\n\t}\n\treturn &jobRecordExternal{rec, conf.paramsType}, nil\n}\n\nfunc (jq *JobQueue) safeProcess(rec *jobRecord, conf jobConfig) error {\n\tvar (\n\t\terr     error\n\t\telapsed int64\n\t)\n\n\t\/\/ Process, with panic handling.\n\tfunc() {\n\t\telapsed = time.Now().UnixNano()\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\terr = errors.New(\"job %s panicked: %s\", conf.name, r)\n\t\t\t}\n\t\t}()\n\n\t\terr = func() error {\n\t\t\tparams, err := (&jobRecordExternal{rec, conf.paramsType}).Params()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturns := conf.handler.Call([]reflect.Value{reflect.ValueOf(params)})\n\t\t\tif !returns[0].IsNil() {\n\t\t\t\treturn returns[0].Interface().(error)\n\t\t\t}\n\t\t\treturn nil\n\t\t}()\n\t}()\n\n\t\/\/ Logging.\n\telapsed = (time.Now().UnixNano() - elapsed) \/ 1000000\n\tif err == nil {\n\t\tglog.Infof(\"job %s(%d) succeeded: attempt=%d, elapsed=%dms\",\n\t\t\trec.name, rec.id,\n\t\t\trec.attempt(conf), elapsed)\n\t} else {\n\t\tglog.Infof(\"job %s(%d) failed: attempt=%d, elapsed=%dms, remaining=%d, err=%s\",\n\t\t\trec.name, rec.id,\n\t\t\trec.attempt(conf), elapsed, rec.remaining, err)\n\t}\n\n\t\/\/ Done\n\treturn err\n}\n\nfunc (jq *JobQueue) maybeNext() (int64, bool, error) {\n\tnow := jq.clock.UnixNow()\n\trows, err := jq.db.Query(`\n\t\tselect id from job_queue\n\t\twhere status = ? and remaining > 0 and schedulable_at <= ?\n\t\torder by schedulable_at asc limit 1`,\n\t\tstatusPending, now)\n\tif err != nil {\n\t\treturn -1, false, err\n\t}\n\tdefer rows.Close()\n\tif !rows.Next() {\n\t\treturn -1, false, nil\n\t}\n\tvar jobId int64\n\terr = rows.Scan(&jobId)\n\tif err != nil {\n\t\treturn -1, false, err\n\t}\n\treturn jobId, true, nil\n}\n\nfunc (jq *JobQueue) attemptLock(jobId int64) (bool, error) {\n\tres, err := jq.db.Exec(\n\t\t\"update job_queue set status = ?, processor_id = ?, remaining = remaining - 1 where id = ? and status = ?\",\n\t\tstatusProcessing, jq.processorId, jobId, statusPending)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tchanged, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn changed == 1, nil\n}\n\nfunc (jq *JobQueue) markAs(jobId int64, status string) error {\n\t_, err := jq.db.Exec(\n\t\t\"update job_queue set status = ?, processor_id = null where id = ?\",\n\t\tstatus, jobId)\n\treturn err\n}\n\nfunc (jq *JobQueue) reEnqueue(rec *jobRecord) error {\n\tconf := jq.configs[rec.name]\n\tbackoffMultiplier := 1 << uint(rec.attempt(conf)-1)\n\tnewSchedulableAt := jq.clock.UnixNow() + conf.backoffInSeconds*int64(backoffMultiplier)\n\t_, err := jq.db.Exec(\n\t\t\"update job_queue set status = ?, schedulable_at = ?, processor_id = null where id = ?\",\n\t\tstatusPending, newSchedulableAt, rec.id)\n\treturn err\n}\n\nfunc (jq *JobQueue) getJobRecord(jobId int64) (*jobRecord, error) {\n\tvar (\n\t\tname          string\n\t\tparams        []byte\n\t\tremaining     int\n\t\tschedulableAt int64\n\t)\n\terr := jq.db.\n\t\tQueryRow(\n\t\t\t\"select name, params, remaining, schedulable_at from job_queue where id = ?\",\n\t\t\tjobId).\n\t\tScan(&name, &params, &remaining, &schedulableAt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trec := jobRecord{\n\t\tid:            jobId,\n\t\tname:          name,\n\t\tparams:        params,\n\t\tremaining:     remaining,\n\t\tschedulableAt: schedulableAt,\n\t}\n\treturn &rec, nil\n}\n\ntype jobRecordExternal struct {\n\t*jobRecord\n\tparamsType reflect.Type\n}\n\n\/\/ Assert jobRecord implements the Job interface.\nvar _ Job = &jobRecordExternal{}\n\nfunc (rec *jobRecordExternal) ID() int64 {\n\treturn rec.id\n}\n\nfunc (rec *jobRecordExternal) Name() string {\n\treturn rec.name\n}\n\nfunc (rec *jobRecordExternal) Params() (interface{}, error) {\n\tparams := reflect.New(rec.paramsType.Elem()).Interface()\n\tif rec.params != nil {\n\t\tif err := json.Unmarshal(rec.params, &params); err != nil {\n\t\t\treturn nil, errors.New(\"job %s unmarshall error: %s\", rec.name, err)\n\t\t}\n\t}\n\treturn params, nil\n}\n<commit_msg>Must wait for fetchers to stop (since they publish on the channel) before closing the channel<commit_after>package gojobs\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"reflect\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/pascallouisperez\/goutil\/errors\"\n\t\"github.com\/pascallouisperez\/reflext\"\n)\n\nconst (\n\tstatusPending    = \"pending\"\n\tstatusProcessing = \"processing\"\n\tstatusFailed     = \"failed\"\n\tstatusCompleted  = \"completed\"\n)\n\nconst (\n\t_ int32 = iota\n\tqueueStopped\n\tqueueStarting\n\tqueueRunning\n\tqueueStopping\n)\n\ntype clock interface {\n\t\/\/ UnixNow returns the number of seconds elapsed since January 1, 1970 UTC\n\t\/\/ Equivalent of time.Now().Unix()\n\tUnixNow() int64\n}\n\n\/\/ JobQueue is the entry point to registering, scheduling, and querying\n\/\/ jobs.\ntype JobQueue struct {\n\tnumFetchers int\n\tnumWorkers  int\n\n\tdb          *sql.DB\n\tprocessorId int64\n\tconfigs     map[string]jobConfig\n\tstatus      *int32\n\tworkersWg   sync.WaitGroup\n\tfetcherWg   sync.WaitGroup\n\tmaybeJobIds chan int64\n\tclock       clock\n}\n\ntype Job interface {\n\t\/\/ ID returns the identifier of the job.\n\tID() int64\n\n\t\/\/ Name returns the name of the job.\n\tName() string\n\n\t\/\/ Params returns the specific struct associated with this job.\n\tParams() (interface{}, error)\n}\n\ntype jobConfig struct {\n\tname             string\n\thandler          reflect.Value\n\tparamsType       reflect.Type\n\tattempts         int\n\tbackoffInSeconds int64\n}\n\ntype jobRecord struct {\n\tid            int64\n\tname          string\n\tparams        []byte\n\tremaining     int\n\tschedulableAt int64\n}\n\nfunc (rec *jobRecord) attempt(conf jobConfig) int {\n\treturn conf.attempts - rec.remaining\n}\n\ntype realClock struct{}\n\nfunc (realClock) UnixNow() int64 {\n\treturn time.Now().Unix()\n}\n\n\/\/ QueueConfiguration groups optional queue configuration parameters. For\n\/\/ all parameters, reasonable defaults are provided by the library.\ntype QueueConfiguration struct {\n\t\/\/ NumWorkers specifies the number of workers (i.e. goroutines processing\n\t\/\/ jobs) to spawn when this queue is started. Default is 5.\n\tNumWorkers int\n}\n\nfunc NewJobQueue(db *sql.DB, processorId int64, optConfs ...QueueConfiguration) *JobQueue {\n\tstatus := queueStopped\n\tjq := JobQueue{\n\t\tdb:          db,\n\t\tprocessorId: processorId,\n\t\tconfigs:     make(map[string]jobConfig, 10),\n\t\tstatus:      &status,\n\t\tclock:       realClock{},\n\t\tnumFetchers: 1,\n\t\tnumWorkers:  5,\n\t}\n\n\t\/\/ Optional configuration.\n\tif size := len(optConfs); size > 1 {\n\t\tpanic(\"too many configurations provided\")\n\t} else if size == 1 {\n\t\tconf := optConfs[0]\n\t\tif conf.NumWorkers > 0 {\n\t\t\tjq.numWorkers = conf.NumWorkers\n\t\t}\n\t}\n\n\treturn &jq\n}\n\nvar handlerMatcher = reflext.MustCompile(\"func ({*struct}) error\")\n\n\/\/ JobConfiguration groups optional job configuration parameters. For\n\/\/ all parameters, reasonable defaults are provided by the library.\ntype JobConfiguration struct {\n\t\/\/ Attempts specifies the number processing attempts to try before aborting\n\t\/\/ a job, and marking is failed.\n\tAttempts int\n\n\t\/\/ Backoff specifies the base duration off which the total exponential backoff\n\t\/\/ is calculated when the job is retried one, twice, thrice, etc.\n\t\/\/ While time.Duration can be expressed in nanoseconds, only durations of seconds\n\t\/\/ or more are considered valid.\n\tBackoff time.Duration\n}\n\nfunc (jq *JobQueue) Register(name string, handler interface{}, optConfs ...JobConfiguration) error {\n\tif name == \"\" {\n\t\treturn errors.New(\"job name cannot be empty\")\n\t}\n\n\tif _, ok := jq.configs[name]; ok {\n\t\treturn errors.New(\"job %s: already registered\", name)\n\t}\n\n\tif st := atomic.LoadInt32(jq.status); st != queueStopped {\n\t\t\/\/ TODO(pascal): if we cared about super pedantic, we should increment\n\t\t\/\/ a wait group on entry to Register, and wait on this wg in Start to\n\t\t\/\/ allow concurrent registrations to complete. But then, we should\n\t\t\/\/ also be careful about concurrent registrations writing to the shared\n\t\t\/\/ configs map. For now, we're going to assume registration is done in a\n\t\t\/\/ simple way.\n\t\treturn errors.New(\"job %s: unable to register once queue has started\", name)\n\t}\n\n\tif handler == nil {\n\t\treturn errors.New(\"job %s: missing handler\", name)\n\t}\n\n\tvar paramsType reflect.Type\n\tif types, ok := handlerMatcher.FindAll(handler); ok {\n\t\tparamsType = types[0]\n\t} else {\n\t\treturn errors.New(\"job %s: expected %s, was %T\", name, handlerMatcher, handler)\n\t}\n\n\t\/\/ Defaults.\n\tconf := jobConfig{\n\t\tname:             name,\n\t\thandler:          reflect.ValueOf(handler),\n\t\tparamsType:       paramsType,\n\t\tattempts:         3,\n\t\tbackoffInSeconds: 5,\n\t}\n\n\t\/\/ Optional configuration.\n\tif l := len(optConfs); l > 1 {\n\t\treturn errors.New(\"job %s: too many optional configurations provided\", name)\n\t} else if l == 1 {\n\t\toptConf := optConfs[0]\n\t\tif optConf.Attempts > 0 {\n\t\t\tconf.attempts = optConf.Attempts\n\t\t}\n\t\tif b := optConf.Backoff.Nanoseconds() \/ 1000000000; b > 0 {\n\t\t\tconf.backoffInSeconds = b\n\t\t}\n\t}\n\n\tjq.configs[name] = conf\n\treturn nil\n}\n\nfunc (jq *JobQueue) fetcher(fetcherIndex int) {\n\tjq.fetcherWg.Add(1)\n\tdefer jq.fetcherWg.Done()\n\n\tfor {\n\t\tif st := atomic.LoadInt32(jq.status); st == queueStopping {\n\t\t\treturn\n\t\t}\n\n\t\tjobId, hasNext, err := jq.maybeNext()\n\t\tif err != nil {\n\t\t\tglog.Infof(\"fetcher[%d], internal error while fetching potential next job: %s\", fetcherIndex, err)\n\t\t}\n\t\tif !hasNext {\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\tjq.maybeJobIds <- jobId\n\t}\n}\n\nfunc (jq *JobQueue) worker(workerIndex int) {\n\tjq.workersWg.Add(1)\n\tdefer jq.workersWg.Done()\n\n\tfor {\n\t\tif st := atomic.LoadInt32(jq.status); st == queueStopping {\n\t\t\treturn\n\t\t}\n\n\t\tjobId := <-jq.maybeJobIds\n\n\t\tlocked, err := jq.attemptLock(jobId)\n\t\tif err != nil {\n\t\t\tglog.Infof(\"worker[%d] internal error while attempting to lock job: %s\", workerIndex, err)\n\t\t}\n\t\tif !locked {\n\t\t\tcontinue\n\t\t}\n\n\t\trec, err := jq.getJobRecord(jobId)\n\t\tif err != nil {\n\t\t\tglog.Infof(\"worker[%d] internal error while fetching job record: %s\", workerIndex, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tjobErr := jq.safeProcess(rec, jq.configs[rec.name])\n\t\tif jobErr != nil {\n\t\t\tif rec.remaining > 0 {\n\t\t\t\terr = jq.reEnqueue(rec)\n\t\t\t} else {\n\t\t\t\terr = jq.markAs(rec.id, statusFailed)\n\t\t\t}\n\t\t} else {\n\t\t\terr = jq.markAs(rec.id, statusCompleted)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tglog.Infof(\"worker[%d] internal error in post process of job: %s\", err)\n\t\t}\n\t}\n\n}\n\nfunc (jq *JobQueue) Start() error {\n\t\/\/ Mark queue as starting.\n\tif !atomic.CompareAndSwapInt32(jq.status, queueStopped, queueStarting) {\n\t\treturn errors.New(\"can only start a queue which is stopped\")\n\t}\n\n\t\/\/ Fresh channel.\n\tjq.maybeJobIds = make(chan int64)\n\n\t\/\/ Start fetchers.\n\tfor i := 0; i < jq.numFetchers; i++ {\n\t\tgo jq.fetcher(i)\n\t}\n\n\t\/\/ Start workers.\n\tfor i := 0; i < jq.numWorkers; i++ {\n\t\tgo jq.worker(i)\n\t}\n\n\t\/\/ Mark queue as running.\n\tatomic.StoreInt32(jq.status, queueRunning)\n\n\treturn nil\n}\n\nfunc (jq *JobQueue) Stop() error {\n\tif !atomic.CompareAndSwapInt32(jq.status, queueRunning, queueStopping) {\n\t\treturn errors.New(\"unable to stop\")\n\t}\n\tjq.fetcherWg.Wait()\n\tclose(jq.maybeJobIds)\n\tjq.workersWg.Wait()\n\tatomic.StoreInt32(jq.status, queueStopped)\n\tjq.maybeJobIds = nil\n\treturn nil\n}\n\nfunc (jq *JobQueue) Enqueue(tx *sql.Tx, name string, params interface{}) (int64, error) {\n\tconf, ok := jq.configs[name]\n\tif !ok {\n\t\treturn -1, errors.New(\"unknown job: %s\", name)\n\t}\n\n\tvar (\n\t\tparamsAsBytes []byte\n\t\terr           error\n\t)\n\tif params != nil {\n\t\tactualParamsType := reflect.TypeOf(params)\n\t\tif !actualParamsType.AssignableTo(conf.paramsType) {\n\t\t\treturn -1, errors.New(\"job %s: incorrect param type, expected %s, got %s\",\n\t\t\t\tconf.name, conf.paramsType, actualParamsType)\n\t\t}\n\n\t\tparamsAsBytes, err = json.Marshal(params)\n\t\tif err != nil {\n\t\t\treturn -1, errors.New(\"job %s: unable to marshall parms %s\", err)\n\t\t}\n\t}\n\n\tnow := jq.clock.UnixNow()\n\tres, err := tx.Exec(`\n\t\tinsert into job_queue (name, params, remaining, status, created_at, schedulable_at)\n\t\tvalues (?, ?, ?, ?, ?, ?)`,\n\t\tname, paramsAsBytes, conf.attempts, statusPending, now, now)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tjobId, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\treturn jobId, nil\n}\n\nfunc (jq *JobQueue) Get(jobId int64) (Job, error) {\n\trec, err := jq.getJobRecord(jobId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconf, ok := jq.configs[rec.name]\n\tif !ok {\n\t\treturn nil, errors.New(\"job %s has not been registered\", rec.name)\n\t}\n\treturn &jobRecordExternal{rec, conf.paramsType}, nil\n}\n\nfunc (jq *JobQueue) safeProcess(rec *jobRecord, conf jobConfig) error {\n\tvar (\n\t\terr     error\n\t\telapsed int64\n\t)\n\n\t\/\/ Process, with panic handling.\n\tfunc() {\n\t\telapsed = time.Now().UnixNano()\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\terr = errors.New(\"job %s panicked: %s\", conf.name, r)\n\t\t\t}\n\t\t}()\n\n\t\terr = func() error {\n\t\t\tparams, err := (&jobRecordExternal{rec, conf.paramsType}).Params()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturns := conf.handler.Call([]reflect.Value{reflect.ValueOf(params)})\n\t\t\tif !returns[0].IsNil() {\n\t\t\t\treturn returns[0].Interface().(error)\n\t\t\t}\n\t\t\treturn nil\n\t\t}()\n\t}()\n\n\t\/\/ Logging.\n\telapsed = (time.Now().UnixNano() - elapsed) \/ 1000000\n\tif err == nil {\n\t\tglog.Infof(\"job %s(%d) succeeded: attempt=%d, elapsed=%dms\",\n\t\t\trec.name, rec.id,\n\t\t\trec.attempt(conf), elapsed)\n\t} else {\n\t\tglog.Infof(\"job %s(%d) failed: attempt=%d, elapsed=%dms, remaining=%d, err=%s\",\n\t\t\trec.name, rec.id,\n\t\t\trec.attempt(conf), elapsed, rec.remaining, err)\n\t}\n\n\t\/\/ Done\n\treturn err\n}\n\nfunc (jq *JobQueue) maybeNext() (int64, bool, error) {\n\tnow := jq.clock.UnixNow()\n\trows, err := jq.db.Query(`\n\t\tselect id from job_queue\n\t\twhere status = ? and remaining > 0 and schedulable_at <= ?\n\t\torder by schedulable_at asc limit 1`,\n\t\tstatusPending, now)\n\tif err != nil {\n\t\treturn -1, false, err\n\t}\n\tdefer rows.Close()\n\tif !rows.Next() {\n\t\treturn -1, false, nil\n\t}\n\tvar jobId int64\n\terr = rows.Scan(&jobId)\n\tif err != nil {\n\t\treturn -1, false, err\n\t}\n\treturn jobId, true, nil\n}\n\nfunc (jq *JobQueue) attemptLock(jobId int64) (bool, error) {\n\tres, err := jq.db.Exec(\n\t\t\"update job_queue set status = ?, processor_id = ?, remaining = remaining - 1 where id = ? and status = ?\",\n\t\tstatusProcessing, jq.processorId, jobId, statusPending)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tchanged, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn changed == 1, nil\n}\n\nfunc (jq *JobQueue) markAs(jobId int64, status string) error {\n\t_, err := jq.db.Exec(\n\t\t\"update job_queue set status = ?, processor_id = null where id = ?\",\n\t\tstatus, jobId)\n\treturn err\n}\n\nfunc (jq *JobQueue) reEnqueue(rec *jobRecord) error {\n\tconf := jq.configs[rec.name]\n\tbackoffMultiplier := 1 << uint(rec.attempt(conf)-1)\n\tnewSchedulableAt := jq.clock.UnixNow() + conf.backoffInSeconds*int64(backoffMultiplier)\n\t_, err := jq.db.Exec(\n\t\t\"update job_queue set status = ?, schedulable_at = ?, processor_id = null where id = ?\",\n\t\tstatusPending, newSchedulableAt, rec.id)\n\treturn err\n}\n\nfunc (jq *JobQueue) getJobRecord(jobId int64) (*jobRecord, error) {\n\tvar (\n\t\tname          string\n\t\tparams        []byte\n\t\tremaining     int\n\t\tschedulableAt int64\n\t)\n\terr := jq.db.\n\t\tQueryRow(\n\t\t\t\"select name, params, remaining, schedulable_at from job_queue where id = ?\",\n\t\t\tjobId).\n\t\tScan(&name, &params, &remaining, &schedulableAt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trec := jobRecord{\n\t\tid:            jobId,\n\t\tname:          name,\n\t\tparams:        params,\n\t\tremaining:     remaining,\n\t\tschedulableAt: schedulableAt,\n\t}\n\treturn &rec, nil\n}\n\ntype jobRecordExternal struct {\n\t*jobRecord\n\tparamsType reflect.Type\n}\n\n\/\/ Assert jobRecord implements the Job interface.\nvar _ Job = &jobRecordExternal{}\n\nfunc (rec *jobRecordExternal) ID() int64 {\n\treturn rec.id\n}\n\nfunc (rec *jobRecordExternal) Name() string {\n\treturn rec.name\n}\n\nfunc (rec *jobRecordExternal) Params() (interface{}, error) {\n\tparams := reflect.New(rec.paramsType.Elem()).Interface()\n\tif rec.params != nil {\n\t\tif err := json.Unmarshal(rec.params, &params); err != nil {\n\t\t\treturn nil, errors.New(\"job %s unmarshall error: %s\", rec.name, err)\n\t\t}\n\t}\n\treturn params, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright 2017, Arkbriar\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\npackage gitlab\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n)\n\n\/\/ JobsService handles communication with the ci builds related methods\n\/\/ of the GitLab API.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ce\/api\/jobs.html\ntype JobsService struct {\n\tclient *Client\n}\n\n\/\/ Job represents a ci build.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ce\/api\/jobs.html\ntype Job struct {\n\tCommit            *Commit    `json:\"commit\"`\n\tCoverage          float64    `json:\"coverage\"`\n\tAllowFailure      bool       `json:\"allow_failure\"`\n\tCreatedAt         *time.Time `json:\"created_at\"`\n\tStartedAt         *time.Time `json:\"started_at\"`\n\tFinishedAt        *time.Time `json:\"finished_at\"`\n\tDuration          float64    `json:\"duration\"`\n\tArtifactsExpireAt *time.Time `json:\"artifacts_expire_at\"`\n\tID                int        `json:\"id\"`\n\tName              string     `json:\"name\"`\n\tPipeline          struct {\n\t\tID     int    `json:\"id\"`\n\t\tRef    string `json:\"ref\"`\n\t\tSha    string `json:\"sha\"`\n\t\tStatus string `json:\"status\"`\n\t} `json:\"pipeline\"`\n\tRef       string `json:\"ref\"`\n\tArtifacts []struct {\n\t\tFileType   string `json:\"file_type\"`\n\t\tFilename   string `json:\"filename\"`\n\t\tSize       int    `json:\"size\"`\n\t\tFileFormat string `json:\"file_format\"`\n\t} `json:\"artifacts\"`\n\tArtifactsFile struct {\n\t\tFilename string `json:\"filename\"`\n\t\tSize     int    `json:\"size\"`\n\t} `json:\"artifacts_file\"`\n\tRunner struct {\n\t\tID          int    `json:\"id\"`\n\t\tDescription string `json:\"description\"`\n\t\tActive      bool   `json:\"active\"`\n\t\tIsShared    bool   `json:\"is_shared\"`\n\t\tName        string `json:\"name\"`\n\t} `json:\"runner\"`\n\tStage  string `json:\"stage\"`\n\tStatus string `json:\"status\"`\n\tTag    bool   `json:\"tag\"`\n\tWebURL string `json:\"web_url\"`\n\tUser   *User  `json:\"user\"`\n}\n\n\/\/ ListJobsOptions are options for two list apis\ntype ListJobsOptions struct {\n\tListOptions\n\tScope []BuildStateValue `url:\"scope[],omitempty\" json:\"scope,omitempty\"`\n}\n\n\/\/ ListProjectJobs gets a list of jobs in a project.\n\/\/\n\/\/ The scope of jobs to show, one or array of: created, pending, running,\n\/\/ failed, success, canceled, skipped; showing all jobs if none provided\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#list-project-jobs\nfunc (s *JobsService) ListProjectJobs(pid interface{}, opts *ListJobsOptions, options ...RequestOptionFunc) ([]Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\", pathEscape(project))\n\n\treq, err := s.client.NewRequest(\"GET\", u, opts, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar jobs []Job\n\tresp, err := s.client.Do(req, &jobs)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn jobs, resp, err\n}\n\n\/\/ ListPipelineJobs gets a list of jobs for specific pipeline in a\n\/\/ project. If the pipeline ID is not found, it will respond with 404.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#list-pipeline-jobs\nfunc (s *JobsService) ListPipelineJobs(pid interface{}, pipelineID int, opts *ListJobsOptions, options ...RequestOptionFunc) ([]*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/pipelines\/%d\/jobs\", pathEscape(project), pipelineID)\n\n\treq, err := s.client.NewRequest(\"GET\", u, opts, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar jobs []*Job\n\tresp, err := s.client.Do(req, &jobs)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn jobs, resp, err\n}\n\n\/\/ GetJob gets a single job of a project.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#get-a-single-job\nfunc (s *JobsService) GetJob(pid interface{}, jobID int, options ...RequestOptionFunc) (*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjob := new(Job)\n\tresp, err := s.client.Do(req, job)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn job, resp, err\n}\n\n\/\/ GetJobArtifacts get jobs artifacts of a project\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/job_artifacts.html#get-job-artifacts\nfunc (s *JobsService) GetJobArtifacts(pid interface{}, jobID int, options ...RequestOptionFunc) (io.Reader, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/artifacts\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tartifactsBuf := new(bytes.Buffer)\n\tresp, err := s.client.Do(req, artifactsBuf)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn artifactsBuf, resp, err\n}\n\n\/\/ DownloadArtifactsFileOptions represents the available DownloadArtifactsFile()\n\/\/ options.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/job_artifacts.html#download-the-artifacts-archive\ntype DownloadArtifactsFileOptions struct {\n\tJob *string `url:\"job\" json:\"job\"`\n}\n\n\/\/ DownloadArtifactsFile download the artifacts file from the given\n\/\/ reference name and job provided the job finished successfully.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/job_artifacts.html#download-the-artifacts-archive\nfunc (s *JobsService) DownloadArtifactsFile(pid interface{}, refName string, opt *DownloadArtifactsFileOptions, options ...RequestOptionFunc) (io.Reader, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/artifacts\/%s\/download\", pathEscape(project), refName)\n\n\treq, err := s.client.NewRequest(\"GET\", u, opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tartifactsBuf := new(bytes.Buffer)\n\tresp, err := s.client.Do(req, artifactsBuf)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn artifactsBuf, resp, err\n}\n\n\/\/ DownloadSingleArtifactsFile download a file from the artifacts from the\n\/\/ given reference name and job provided the job finished successfully.\n\/\/ Only a single file is going to be extracted from the archive and streamed\n\/\/ to a client.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/job_artifacts.html#download-a-single-artifact-file-by-job-id\nfunc (s *JobsService) DownloadSingleArtifactsFile(pid interface{}, jobID int, artifactPath string, options ...RequestOptionFunc) (io.Reader, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tu := fmt.Sprintf(\n\t\t\"projects\/%s\/jobs\/%d\/artifacts\/%s\",\n\t\tpathEscape(project),\n\t\tjobID,\n\t\tartifactPath,\n\t)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tartifactBuf := new(bytes.Buffer)\n\tresp, err := s.client.Do(req, artifactBuf)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn artifactBuf, resp, err\n}\n\n\/\/ GetTraceFile gets a trace of a specific job of a project\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#get-a-trace-file\nfunc (s *JobsService) GetTraceFile(pid interface{}, jobID int, options ...RequestOptionFunc) (io.Reader, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/trace\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\ttraceBuf := new(bytes.Buffer)\n\tresp, err := s.client.Do(req, traceBuf)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn traceBuf, resp, err\n}\n\n\/\/ CancelJob cancels a single job of a project.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#cancel-a-job\nfunc (s *JobsService) CancelJob(pid interface{}, jobID int, options ...RequestOptionFunc) (*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/cancel\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjob := new(Job)\n\tresp, err := s.client.Do(req, job)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn job, resp, err\n}\n\n\/\/ RetryJob retries a single job of a project\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#retry-a-job\nfunc (s *JobsService) RetryJob(pid interface{}, jobID int, options ...RequestOptionFunc) (*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/retry\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjob := new(Job)\n\tresp, err := s.client.Do(req, job)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn job, resp, err\n}\n\n\/\/ EraseJob erases a single job of a project, removes a job\n\/\/ artifacts and a job trace.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#erase-a-job\nfunc (s *JobsService) EraseJob(pid interface{}, jobID int, options ...RequestOptionFunc) (*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/erase\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjob := new(Job)\n\tresp, err := s.client.Do(req, job)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn job, resp, err\n}\n\n\/\/ KeepArtifacts prevents artifacts from being deleted when\n\/\/ expiration is set.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/job_artifacts.html#keep-artifacts\nfunc (s *JobsService) KeepArtifacts(pid interface{}, jobID int, options ...RequestOptionFunc) (*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/artifacts\/keep\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjob := new(Job)\n\tresp, err := s.client.Do(req, job)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn job, resp, err\n}\n\n\/\/ PlayJob triggers a manual action to start a job.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#play-a-job\nfunc (s *JobsService) PlayJob(pid interface{}, jobID int, options ...RequestOptionFunc) (*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/play\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjob := new(Job)\n\tresp, err := s.client.Do(req, job)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn job, resp, err\n}\n<commit_msg>Add method to delete artifacts for a job<commit_after>\/\/\n\/\/ Copyright 2017, Arkbriar\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\npackage gitlab\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n)\n\n\/\/ JobsService handles communication with the ci builds related methods\n\/\/ of the GitLab API.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ce\/api\/jobs.html\ntype JobsService struct {\n\tclient *Client\n}\n\n\/\/ Job represents a ci build.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ce\/api\/jobs.html\ntype Job struct {\n\tCommit            *Commit    `json:\"commit\"`\n\tCoverage          float64    `json:\"coverage\"`\n\tAllowFailure      bool       `json:\"allow_failure\"`\n\tCreatedAt         *time.Time `json:\"created_at\"`\n\tStartedAt         *time.Time `json:\"started_at\"`\n\tFinishedAt        *time.Time `json:\"finished_at\"`\n\tDuration          float64    `json:\"duration\"`\n\tArtifactsExpireAt *time.Time `json:\"artifacts_expire_at\"`\n\tID                int        `json:\"id\"`\n\tName              string     `json:\"name\"`\n\tPipeline          struct {\n\t\tID     int    `json:\"id\"`\n\t\tRef    string `json:\"ref\"`\n\t\tSha    string `json:\"sha\"`\n\t\tStatus string `json:\"status\"`\n\t} `json:\"pipeline\"`\n\tRef       string `json:\"ref\"`\n\tArtifacts []struct {\n\t\tFileType   string `json:\"file_type\"`\n\t\tFilename   string `json:\"filename\"`\n\t\tSize       int    `json:\"size\"`\n\t\tFileFormat string `json:\"file_format\"`\n\t} `json:\"artifacts\"`\n\tArtifactsFile struct {\n\t\tFilename string `json:\"filename\"`\n\t\tSize     int    `json:\"size\"`\n\t} `json:\"artifacts_file\"`\n\tRunner struct {\n\t\tID          int    `json:\"id\"`\n\t\tDescription string `json:\"description\"`\n\t\tActive      bool   `json:\"active\"`\n\t\tIsShared    bool   `json:\"is_shared\"`\n\t\tName        string `json:\"name\"`\n\t} `json:\"runner\"`\n\tStage  string `json:\"stage\"`\n\tStatus string `json:\"status\"`\n\tTag    bool   `json:\"tag\"`\n\tWebURL string `json:\"web_url\"`\n\tUser   *User  `json:\"user\"`\n}\n\n\/\/ ListJobsOptions are options for two list apis\ntype ListJobsOptions struct {\n\tListOptions\n\tScope []BuildStateValue `url:\"scope[],omitempty\" json:\"scope,omitempty\"`\n}\n\n\/\/ ListProjectJobs gets a list of jobs in a project.\n\/\/\n\/\/ The scope of jobs to show, one or array of: created, pending, running,\n\/\/ failed, success, canceled, skipped; showing all jobs if none provided\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#list-project-jobs\nfunc (s *JobsService) ListProjectJobs(pid interface{}, opts *ListJobsOptions, options ...RequestOptionFunc) ([]Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\", pathEscape(project))\n\n\treq, err := s.client.NewRequest(\"GET\", u, opts, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar jobs []Job\n\tresp, err := s.client.Do(req, &jobs)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn jobs, resp, err\n}\n\n\/\/ ListPipelineJobs gets a list of jobs for specific pipeline in a\n\/\/ project. If the pipeline ID is not found, it will respond with 404.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#list-pipeline-jobs\nfunc (s *JobsService) ListPipelineJobs(pid interface{}, pipelineID int, opts *ListJobsOptions, options ...RequestOptionFunc) ([]*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/pipelines\/%d\/jobs\", pathEscape(project), pipelineID)\n\n\treq, err := s.client.NewRequest(\"GET\", u, opts, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar jobs []*Job\n\tresp, err := s.client.Do(req, &jobs)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn jobs, resp, err\n}\n\n\/\/ GetJob gets a single job of a project.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#get-a-single-job\nfunc (s *JobsService) GetJob(pid interface{}, jobID int, options ...RequestOptionFunc) (*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjob := new(Job)\n\tresp, err := s.client.Do(req, job)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn job, resp, err\n}\n\n\/\/ GetJobArtifacts get jobs artifacts of a project\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/job_artifacts.html#get-job-artifacts\nfunc (s *JobsService) GetJobArtifacts(pid interface{}, jobID int, options ...RequestOptionFunc) (io.Reader, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/artifacts\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tartifactsBuf := new(bytes.Buffer)\n\tresp, err := s.client.Do(req, artifactsBuf)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn artifactsBuf, resp, err\n}\n\n\/\/ DownloadArtifactsFileOptions represents the available DownloadArtifactsFile()\n\/\/ options.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/job_artifacts.html#download-the-artifacts-archive\ntype DownloadArtifactsFileOptions struct {\n\tJob *string `url:\"job\" json:\"job\"`\n}\n\n\/\/ DownloadArtifactsFile download the artifacts file from the given\n\/\/ reference name and job provided the job finished successfully.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/job_artifacts.html#download-the-artifacts-archive\nfunc (s *JobsService) DownloadArtifactsFile(pid interface{}, refName string, opt *DownloadArtifactsFileOptions, options ...RequestOptionFunc) (io.Reader, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/artifacts\/%s\/download\", pathEscape(project), refName)\n\n\treq, err := s.client.NewRequest(\"GET\", u, opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tartifactsBuf := new(bytes.Buffer)\n\tresp, err := s.client.Do(req, artifactsBuf)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn artifactsBuf, resp, err\n}\n\n\/\/ DownloadSingleArtifactsFile download a file from the artifacts from the\n\/\/ given reference name and job provided the job finished successfully.\n\/\/ Only a single file is going to be extracted from the archive and streamed\n\/\/ to a client.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/job_artifacts.html#download-a-single-artifact-file-by-job-id\nfunc (s *JobsService) DownloadSingleArtifactsFile(pid interface{}, jobID int, artifactPath string, options ...RequestOptionFunc) (io.Reader, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tu := fmt.Sprintf(\n\t\t\"projects\/%s\/jobs\/%d\/artifacts\/%s\",\n\t\tpathEscape(project),\n\t\tjobID,\n\t\tartifactPath,\n\t)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tartifactBuf := new(bytes.Buffer)\n\tresp, err := s.client.Do(req, artifactBuf)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn artifactBuf, resp, err\n}\n\n\/\/ GetTraceFile gets a trace of a specific job of a project\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#get-a-trace-file\nfunc (s *JobsService) GetTraceFile(pid interface{}, jobID int, options ...RequestOptionFunc) (io.Reader, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/trace\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"GET\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\ttraceBuf := new(bytes.Buffer)\n\tresp, err := s.client.Do(req, traceBuf)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn traceBuf, resp, err\n}\n\n\/\/ CancelJob cancels a single job of a project.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#cancel-a-job\nfunc (s *JobsService) CancelJob(pid interface{}, jobID int, options ...RequestOptionFunc) (*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/cancel\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjob := new(Job)\n\tresp, err := s.client.Do(req, job)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn job, resp, err\n}\n\n\/\/ RetryJob retries a single job of a project\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#retry-a-job\nfunc (s *JobsService) RetryJob(pid interface{}, jobID int, options ...RequestOptionFunc) (*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/retry\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjob := new(Job)\n\tresp, err := s.client.Do(req, job)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn job, resp, err\n}\n\n\/\/ EraseJob erases a single job of a project, removes a job\n\/\/ artifacts and a job trace.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#erase-a-job\nfunc (s *JobsService) EraseJob(pid interface{}, jobID int, options ...RequestOptionFunc) (*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/erase\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjob := new(Job)\n\tresp, err := s.client.Do(req, job)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn job, resp, err\n}\n\n\/\/ KeepArtifacts prevents artifacts from being deleted when\n\/\/ expiration is set.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/job_artifacts.html#keep-artifacts\nfunc (s *JobsService) KeepArtifacts(pid interface{}, jobID int, options ...RequestOptionFunc) (*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/artifacts\/keep\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjob := new(Job)\n\tresp, err := s.client.Do(req, job)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn job, resp, err\n}\n\n\/\/ PlayJob triggers a manual action to start a job.\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/jobs.html#play-a-job\nfunc (s *JobsService) PlayJob(pid interface{}, jobID int, options ...RequestOptionFunc) (*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/play\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjob := new(Job)\n\tresp, err := s.client.Do(req, job)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn job, resp, err\n}\n\n\/\/ DeleteArtifacts delete artifacts of a job\n\/\/\n\/\/ GitLab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ce\/api\/job_artifacts.html#delete-artifacts\nfunc (s *JobsService) DeleteArtifacts(pid interface{}, jobID int, options ...RequestOptionFunc) (*Job, *Response, error) {\n\tproject, err := parseID(pid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"projects\/%s\/jobs\/%d\/artifacts\", pathEscape(project), jobID)\n\n\treq, err := s.client.NewRequest(\"DELETE\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tjob := new(Job)\n\tresp, err := s.client.Do(req, job)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn job, resp, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 The Knative Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage generators\n\nimport (\n\t\"io\"\n\t\"k8s.io\/gengo\/generator\"\n\t\"k8s.io\/gengo\/namer\"\n\t\"k8s.io\/gengo\/types\"\n\t\"k8s.io\/klog\"\n)\n\n\/\/ reconcilerControllerGenerator produces a file for setting up the reconciler\n\/\/ with injection.\ntype reconcilerControllerGenerator struct {\n\tgenerator.DefaultGen\n\toutputPackage string\n\timports       namer.ImportTracker\n\tfiltered      bool\n\n\tclientPkg           string\n\tschemePkg           string\n\tinformerPackagePath string\n}\n\nvar _ generator.Generator = (*reconcilerControllerGenerator)(nil)\n\nfunc (g *reconcilerControllerGenerator) Filter(c *generator.Context, t *types.Type) bool {\n\t\/\/ We generate a single client, so return true once.\n\tif !g.filtered {\n\t\tg.filtered = true\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (g *reconcilerControllerGenerator) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}\n\nfunc (g *reconcilerControllerGenerator) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.imports.ImportLines()...)\n\treturn\n}\n\nfunc (g *reconcilerControllerGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"{{\", \"}}\")\n\n\tklog.V(5).Infof(\"processing type %v\", t)\n\n\tm := map[string]interface{}{\n\t\t\"type\": t,\n\t\t\"controllerImpl\": c.Universe.Type(types.Name{\n\t\t\tPackage: \"knative.dev\/pkg\/controller\",\n\t\t\tName:    \"Impl\",\n\t\t}),\n\t\t\"loggingFromContext\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"knative.dev\/pkg\/logging\",\n\t\t\tName:    \"FromContext\",\n\t\t}),\n\t\t\"corev1EventSource\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"k8s.io\/api\/core\/v1\",\n\t\t\tName:    \"EventSource\",\n\t\t}),\n\t\t\"clientGet\": c.Universe.Function(types.Name{\n\t\t\tPackage: g.clientPkg,\n\t\t\tName:    \"Get\",\n\t\t}),\n\t\t\"informerGet\": c.Universe.Function(types.Name{\n\t\t\tPackage: g.informerPackagePath,\n\t\t\tName:    \"Get\",\n\t\t}),\n\t\t\"schemeScheme\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"k8s.io\/client-go\/kubernetes\/scheme\",\n\t\t\tName:    \"Scheme\",\n\t\t}),\n\t\t\"schemeAddToScheme\": c.Universe.Function(types.Name{\n\t\t\tPackage: g.schemePkg,\n\t\t\tName:    \"AddToScheme\",\n\t\t}),\n\t\t\"kubeclientGet\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"knative.dev\/pkg\/client\/injection\/kube\/client\",\n\t\t\tName:    \"Get\",\n\t\t}),\n\t\t\"typedcorev1EventSinkImpl\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"k8s.io\/client-go\/kubernetes\/typed\/core\/v1\",\n\t\t\tName:    \"EventSinkImpl\",\n\t\t}),\n\t\t\"recordNewBroadcaster\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"k8s.io\/client-go\/tools\/record\",\n\t\t\tName:    \"NewBroadcaster\",\n\t\t}),\n\t\t\"watchInterface\": c.Universe.Type(types.Name{\n\t\t\tPackage: \"k8s.io\/apimachinery\/pkg\/watch\",\n\t\t\tName:    \"Interface\",\n\t\t}),\n\t\t\"controllerGetEventRecorder\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"knative.dev\/pkg\/controller\",\n\t\t\tName:    \"GetEventRecorder\",\n\t\t}),\n\t}\n\n\tsw.Do(reconcilerControllerNewImpl, m)\n\n\treturn sw.Error()\n}\n\nvar reconcilerControllerNewImpl = `\nconst (\n\tdefaultControllerAgentName = \"{{.type|lowercaseSingular}}-controller\"\n\tdefaultFinalizerName       = \"{{.type|lowercaseSingular}}\"\n)\n\nfunc NewImpl(ctx context.Context, r Interface) *{{.controllerImpl|raw}} {\n\tlogger := {{.loggingFromContext|raw}}(ctx)\n\n\t{{.type|lowercaseSingular}}Informer := {{.informerGet|raw}}(ctx)\n\n\trecorder := {{.controllerGetEventRecorder|raw}}(ctx)\n\tif recorder == nil {\n\t\t\/\/ Create event broadcaster\n\t\tlogger.Debug(\"Creating event broadcaster\")\n\t\teventBroadcaster := {{.recordNewBroadcaster|raw}}()\n\t\twatches := []{{.watchInterface|raw}}{\n\t\t\teventBroadcaster.StartLogging(logger.Named(\"event-broadcaster\").Infof),\n\t\t\teventBroadcaster.StartRecordingToSink(\n\t\t\t\t&{{.typedcorev1EventSinkImpl|raw}}{Interface: {{.kubeclientGet|raw}}(ctx).CoreV1().Events(\"\")}),\n\t\t}\n\t\trecorder = eventBroadcaster.NewRecorder({{.schemeScheme|raw}}, {{.corev1EventSource|raw}}{Component: defaultControllerAgentName})\n\t\tgo func() {\n\t\t\t<-ctx.Done()\n\t\t\tfor _, w := range watches {\n\t\t\t\tw.Stop()\n\t\t\t}\n\t\t}()\n\t}\n\n\tc := &reconcilerImpl{\n\t\tClient:  {{.clientGet|raw}}(ctx),\n\t\tLister:  {{.type|lowercaseSingular}}Informer.Lister(),\n\t\tRecorder: recorder,\n\t\tFinalizerName: defaultFinalizerName,\n\t\treconciler:    r,\n\t}\n\timpl := controller.NewImpl(c, logger, \"{{.type|allLowercasePlural}}\")\n\n\treturn impl\n}\n\nfunc init() {\n\t{{.schemeAddToScheme|raw}}({{.schemeScheme|raw}})\n}\n`\n<commit_msg>golang format tools (#1056)<commit_after>\/*\nCopyright 2020 The Knative Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage generators\n\nimport (\n\t\"io\"\n\n\t\"k8s.io\/gengo\/generator\"\n\t\"k8s.io\/gengo\/namer\"\n\t\"k8s.io\/gengo\/types\"\n\t\"k8s.io\/klog\"\n)\n\n\/\/ reconcilerControllerGenerator produces a file for setting up the reconciler\n\/\/ with injection.\ntype reconcilerControllerGenerator struct {\n\tgenerator.DefaultGen\n\toutputPackage string\n\timports       namer.ImportTracker\n\tfiltered      bool\n\n\tclientPkg           string\n\tschemePkg           string\n\tinformerPackagePath string\n}\n\nvar _ generator.Generator = (*reconcilerControllerGenerator)(nil)\n\nfunc (g *reconcilerControllerGenerator) Filter(c *generator.Context, t *types.Type) bool {\n\t\/\/ We generate a single client, so return true once.\n\tif !g.filtered {\n\t\tg.filtered = true\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (g *reconcilerControllerGenerator) Namers(c *generator.Context) namer.NameSystems {\n\treturn namer.NameSystems{\n\t\t\"raw\": namer.NewRawNamer(g.outputPackage, g.imports),\n\t}\n}\n\nfunc (g *reconcilerControllerGenerator) Imports(c *generator.Context) (imports []string) {\n\timports = append(imports, g.imports.ImportLines()...)\n\treturn\n}\n\nfunc (g *reconcilerControllerGenerator) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {\n\tsw := generator.NewSnippetWriter(w, c, \"{{\", \"}}\")\n\n\tklog.V(5).Infof(\"processing type %v\", t)\n\n\tm := map[string]interface{}{\n\t\t\"type\": t,\n\t\t\"controllerImpl\": c.Universe.Type(types.Name{\n\t\t\tPackage: \"knative.dev\/pkg\/controller\",\n\t\t\tName:    \"Impl\",\n\t\t}),\n\t\t\"loggingFromContext\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"knative.dev\/pkg\/logging\",\n\t\t\tName:    \"FromContext\",\n\t\t}),\n\t\t\"corev1EventSource\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"k8s.io\/api\/core\/v1\",\n\t\t\tName:    \"EventSource\",\n\t\t}),\n\t\t\"clientGet\": c.Universe.Function(types.Name{\n\t\t\tPackage: g.clientPkg,\n\t\t\tName:    \"Get\",\n\t\t}),\n\t\t\"informerGet\": c.Universe.Function(types.Name{\n\t\t\tPackage: g.informerPackagePath,\n\t\t\tName:    \"Get\",\n\t\t}),\n\t\t\"schemeScheme\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"k8s.io\/client-go\/kubernetes\/scheme\",\n\t\t\tName:    \"Scheme\",\n\t\t}),\n\t\t\"schemeAddToScheme\": c.Universe.Function(types.Name{\n\t\t\tPackage: g.schemePkg,\n\t\t\tName:    \"AddToScheme\",\n\t\t}),\n\t\t\"kubeclientGet\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"knative.dev\/pkg\/client\/injection\/kube\/client\",\n\t\t\tName:    \"Get\",\n\t\t}),\n\t\t\"typedcorev1EventSinkImpl\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"k8s.io\/client-go\/kubernetes\/typed\/core\/v1\",\n\t\t\tName:    \"EventSinkImpl\",\n\t\t}),\n\t\t\"recordNewBroadcaster\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"k8s.io\/client-go\/tools\/record\",\n\t\t\tName:    \"NewBroadcaster\",\n\t\t}),\n\t\t\"watchInterface\": c.Universe.Type(types.Name{\n\t\t\tPackage: \"k8s.io\/apimachinery\/pkg\/watch\",\n\t\t\tName:    \"Interface\",\n\t\t}),\n\t\t\"controllerGetEventRecorder\": c.Universe.Function(types.Name{\n\t\t\tPackage: \"knative.dev\/pkg\/controller\",\n\t\t\tName:    \"GetEventRecorder\",\n\t\t}),\n\t}\n\n\tsw.Do(reconcilerControllerNewImpl, m)\n\n\treturn sw.Error()\n}\n\nvar reconcilerControllerNewImpl = `\nconst (\n\tdefaultControllerAgentName = \"{{.type|lowercaseSingular}}-controller\"\n\tdefaultFinalizerName       = \"{{.type|lowercaseSingular}}\"\n)\n\nfunc NewImpl(ctx context.Context, r Interface) *{{.controllerImpl|raw}} {\n\tlogger := {{.loggingFromContext|raw}}(ctx)\n\n\t{{.type|lowercaseSingular}}Informer := {{.informerGet|raw}}(ctx)\n\n\trecorder := {{.controllerGetEventRecorder|raw}}(ctx)\n\tif recorder == nil {\n\t\t\/\/ Create event broadcaster\n\t\tlogger.Debug(\"Creating event broadcaster\")\n\t\teventBroadcaster := {{.recordNewBroadcaster|raw}}()\n\t\twatches := []{{.watchInterface|raw}}{\n\t\t\teventBroadcaster.StartLogging(logger.Named(\"event-broadcaster\").Infof),\n\t\t\teventBroadcaster.StartRecordingToSink(\n\t\t\t\t&{{.typedcorev1EventSinkImpl|raw}}{Interface: {{.kubeclientGet|raw}}(ctx).CoreV1().Events(\"\")}),\n\t\t}\n\t\trecorder = eventBroadcaster.NewRecorder({{.schemeScheme|raw}}, {{.corev1EventSource|raw}}{Component: defaultControllerAgentName})\n\t\tgo func() {\n\t\t\t<-ctx.Done()\n\t\t\tfor _, w := range watches {\n\t\t\t\tw.Stop()\n\t\t\t}\n\t\t}()\n\t}\n\n\tc := &reconcilerImpl{\n\t\tClient:  {{.clientGet|raw}}(ctx),\n\t\tLister:  {{.type|lowercaseSingular}}Informer.Lister(),\n\t\tRecorder: recorder,\n\t\tFinalizerName: defaultFinalizerName,\n\t\treconciler:    r,\n\t}\n\timpl := controller.NewImpl(c, logger, \"{{.type|allLowercasePlural}}\")\n\n\treturn impl\n}\n\nfunc init() {\n\t{{.schemeAddToScheme|raw}}({{.schemeScheme|raw}})\n}\n`\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016, Marc Lavergne <mlavergn@gmail.com>. All rights reserved.\n\/\/ Use of this source code is governed by the MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage goweb\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t. \"golog\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype JSONSliceType []interface{}\ntype JSONMapType map[string]interface{}\n\nconst (\n\tJSONArrayType = iota\n\tJSONDictionaryType\n\tJSONUnknownType\n)\n\ntype _JSONDelimiter []string\n\nvar _JSONArrayDelimiter = []string{\"[\", \"]\"}\nvar _JSONDictionaryDelimiter = []string{\"{\", \"}\"}\n\n\/\/\n\/\/ IdentifityJSONFragment\n\/\/\nfunc IdentifityJSONFragment(jsonString string) (result int, index int) {\n\tresult = JSONUnknownType\n\tindex = -1\n\n\tarrDelimiterIndex := -1\n\tdictDelimiterIndex := strings.Index(jsonString, _JSONDictionaryDelimiter[0])\n\tif dictDelimiterIndex == 0 {\n\t\tresult = JSONDictionaryType\n\t\tindex = dictDelimiterIndex\n\t} else {\n\t\tarrDelimiterIndex = strings.Index(jsonString, _JSONArrayDelimiter[0])\n\t\tif dictDelimiterIndex == -1 && arrDelimiterIndex >= 0 {\n\t\t\tresult = JSONArrayType\n\t\t\tindex = arrDelimiterIndex\n\t\t} else if arrDelimiterIndex == -1 && dictDelimiterIndex >= 0 {\n\t\t\tresult = JSONDictionaryType\n\t\t\tindex = dictDelimiterIndex\n\t\t} else if dictDelimiterIndex < arrDelimiterIndex {\n\t\t\tresult = JSONDictionaryType\n\t\t\tindex = dictDelimiterIndex\n\t\t} else if arrDelimiterIndex < dictDelimiterIndex {\n\t\t\tresult = JSONArrayType\n\t\t\tindex = arrDelimiterIndex\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/\n\/\/ ToJSON\n\/\/\nfunc ToJSON(jsonMap JSONMapType) (result string, err error) {\n\tjsonBytes, err := json.Marshal(jsonMap)\n\tif err != nil {\n\t\tLogError(err)\n\t} else {\n\t\tresult = string(jsonBytes)\n\t}\n\n\treturn\n}\n\n\/\/\n\/\/ FromJSON\n\/\/\nfunc FromJSON(jsonString string) (result JSONMapType, err error) {\n\tbytes := []byte(jsonString)\n\terr = json.Unmarshal(bytes, &result)\n\n\tif err != nil {\n\t\tif strings.Index(err.Error(), \"cannot unmarshal array into\") != -1 {\n\t\t\tvar resultArr JSONSliceType\n\t\t\terr = json.Unmarshal(bytes, &resultArr)\n\t\t\tif err == nil {\n\t\t\t\tresult = make(JSONMapType)\n\t\t\t\tresult[\"[]\"] = resultArr\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/\n\/\/ ExtractJSON isolates and tidys JSON string while attepting to parse the contents into a JSONMap\n\/\/\nfunc ExtractJSON(jsonString string, jsonType int) (result JSONMapType, err error) {\n\t\/\/ unmarshall is strict and wants complete JSON structures\n\tjsonString, jsonType = IsolateJSON(jsonString, jsonType)\n\tresult, err = FromJSON(jsonString)\n\tif err != nil {\n\t\tjsonString = TidyScript(jsonString)\n\t\tresult, err = FromJSON(jsonString)\n\t\tif err != nil {\n\t\t\tjsonString = TidyJSON(jsonString, jsonType)\n\t\t\tresult, err = FromJSON(jsonString)\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/\n\/\/ IsolateJSON isolates the JSON parsable text based on array or dictionary delimiters\n\/\/\nfunc IsolateJSON(jsonString string, jsonTypeIn int) (result string, jsonType int) {\n\tvar delimiter []string = nil\n\tvar delimiterIndex int\n\n\tif jsonTypeIn == JSONUnknownType {\n\t\tjsonType, delimiterIndex = IdentifityJSONFragment(jsonString)\n\t} else {\n\t\tjsonType = jsonTypeIn\n\t\tdelimiterIndex = strings.Index(jsonString, _JSONDictionaryDelimiter[0])\n\n\t}\n\n\tswitch jsonType {\n\tcase JSONArrayType:\n\t\tdelimiter = _JSONArrayDelimiter\n\tcase JSONDictionaryType:\n\t\tdelimiter = _JSONDictionaryDelimiter\n\tdefault:\n\t\treturn\n\t}\n\n\tif delimiterIndex > 0 {\n\t\tresult = jsonString[delimiterIndex:]\n\t}\n\n\tdelimiterIndex = strings.Index(result, delimiter[1])\n\tif delimiterIndex >= 0 {\n\t\tresult = result[:delimiterIndex+1]\n\t}\n\n\treturn\n}\n\n\/\/\n\/\/ TidyScript\n\/\/\nfunc TidyScript(jsonString string) (result string) {\n\t\/\/ no newlines\n\tresult = strings.Replace(jsonString, \"\\n\", \"\", -1)\n\t\/\/ no tabs\n\tresult = strings.Replace(result, \"\\t\", \"\", -1)\n\n\treturn\n}\n\n\/\/\n\/\/ TidyJSON\n\/\/\nfunc TidyJSON(jsonString string, jsonType int) (result string) {\n\t\/\/ JSON improper escaping detected - need to split the string and tidy it\n\tvar jsonDelimiter []string\n\tif jsonType == JSONDictionaryType {\n\t\t\/\/ dictionary cleanup\n\t\tjsonDelimiter = _JSONDictionaryDelimiter\n\t\tentries := strings.Split(jsonString[1:len(jsonString)-1], \",\")\n\t\tfor _, entry := range entries {\n\t\t\tval := strings.Split(entry, \":\")\n\t\t\tresult += fmt.Sprintf(\"\\\"%s\\\": \\\"%s\\\",\", strings.Trim(val[0], \" '\\\"\"), strings.Trim(val[1], \" '\\\"\"))\n\t\t}\n\t} else {\n\t\t\/\/ array\n\t\tjsonDelimiter = _JSONArrayDelimiter\n\t\tentries := strings.Split(jsonString[1:len(jsonString)-1], \",\")\n\t\tfor _, entry := range entries {\n\t\t\tresult += fmt.Sprintf(\"\\\"%s\\\",\", strings.Trim(entry, \" '\"))\n\t\t}\n\t}\n\n\t\/\/ reconstitute the result dropping the last comma\n\tresult = jsonDelimiter[0] + result[:len(result)-1] + jsonDelimiter[1]\n\n\treturn result\n}\n\nfunc numericConversion(jsonstring string) (result int, err error) {\n\tif strings.ToLower(jsonstring) == strings.ToUpper(jsonstring) {\n\t\tresult, err = strconv.Atoi(jsonstring)\n\t\tif err != nil {\n\t\t\tresult, err = EvaluateEquation(jsonstring)\n\t\t}\n\t} else {\n\t\terr = errors.New(\"string\")\n\t}\n\n\treturn\n}\n\n\/\/\n\/\/ TidyValues\n\/\/\nfunc TidyValues(jsonString string, jsonType int) (result string) {\n\tvar jsonDelimiter []string\n\tif jsonType == JSONDictionaryType {\n\t\t\/\/ dictionary cleanup\n\t\tjsonDelimiter = _JSONDictionaryDelimiter\n\t\tentries := strings.Split(jsonString[1:len(jsonString)-1], \",\")\n\t\tfor _, entry := range entries {\n\t\t\tval := strings.Split(entry, \":\")\n\t\t\tival, err := numericConversion(val[1])\n\t\t\tif err == nil {\n\t\t\t\tresult += fmt.Sprintf(\"\\\"%s\\\": %d,\", val[0], ival)\n\t\t\t} else {\n\t\t\t\tresult += fmt.Sprintf(\"\\\"%s\\\": \\\"%s\\\",\", val[0], val[1])\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\/\/ array\n\t\tjsonDelimiter = _JSONArrayDelimiter\n\t\tentries := strings.Split(jsonString[1:len(jsonString)-1], \",\")\n\t\tfor _, entry := range entries {\n\t\t\tival, err := numericConversion(entry)\n\t\t\tif err == nil {\n\t\t\t\tresult += fmt.Sprintf(\"%d,\", ival)\n\t\t\t} else {\n\t\t\t\tresult += fmt.Sprintf(\"\\\"%s\\\",\", entry)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ reconstitute the result dropping the last comma\n\tresult = jsonDelimiter[0] + result[:len(result)-1] + jsonDelimiter[1]\n\n\treturn result\n}\n<commit_msg>Fix: JSON index checks<commit_after>\/\/ Copyright 2016, Marc Lavergne <mlavergn@gmail.com>. All rights reserved.\n\/\/ Use of this source code is governed by the MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage goweb\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t. \"golog\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype JSONSliceType []interface{}\ntype JSONMapType map[string]interface{}\n\nconst (\n\tJSONArrayType = iota\n\tJSONDictionaryType\n\tJSONUnknownType\n)\n\ntype _JSONDelimiter []string\n\nvar _JSONArrayDelimiter = []string{\"[\", \"]\"}\nvar _JSONDictionaryDelimiter = []string{\"{\", \"}\"}\n\n\/\/\n\/\/ IdentifityJSONFragment\n\/\/\nfunc IdentifityJSONFragment(jsonString string) (result int, index int) {\n\tresult = JSONUnknownType\n\tindex = -1\n\n\tarrDelimiterIndex := -1\n\tdictDelimiterIndex := strings.Index(jsonString, _JSONDictionaryDelimiter[0])\n\tif dictDelimiterIndex == 0 {\n\t\tresult = JSONDictionaryType\n\t\tindex = dictDelimiterIndex\n\t} else {\n\t\tarrDelimiterIndex = strings.Index(jsonString, _JSONArrayDelimiter[0])\n\t\tif dictDelimiterIndex == -1 && arrDelimiterIndex >= 0 {\n\t\t\tresult = JSONArrayType\n\t\t\tindex = arrDelimiterIndex\n\t\t} else if arrDelimiterIndex == -1 && dictDelimiterIndex >= 0 {\n\t\t\tresult = JSONDictionaryType\n\t\t\tindex = dictDelimiterIndex\n\t\t} else if dictDelimiterIndex < arrDelimiterIndex {\n\t\t\tresult = JSONDictionaryType\n\t\t\tindex = dictDelimiterIndex\n\t\t} else if arrDelimiterIndex < dictDelimiterIndex {\n\t\t\tresult = JSONArrayType\n\t\t\tindex = arrDelimiterIndex\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/\n\/\/ ToJSON\n\/\/\nfunc ToJSON(jsonMap JSONMapType) (result string, err error) {\n\tjsonBytes, err := json.Marshal(jsonMap)\n\tif err != nil {\n\t\tLogError(err)\n\t} else {\n\t\tresult = string(jsonBytes)\n\t}\n\n\treturn\n}\n\n\/\/\n\/\/ FromJSON\n\/\/\nfunc FromJSON(jsonString string) (result JSONMapType, err error) {\n\tbytes := []byte(jsonString)\n\terr = json.Unmarshal(bytes, &result)\n\n\tif err != nil {\n\t\tif strings.Index(err.Error(), \"cannot unmarshal array into\") != -1 {\n\t\t\tvar resultArr JSONSliceType\n\t\t\terr = json.Unmarshal(bytes, &resultArr)\n\t\t\tif err == nil {\n\t\t\t\tresult = make(JSONMapType)\n\t\t\t\tresult[\"[]\"] = resultArr\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/\n\/\/ ExtractJSON isolates and tidys JSON string while attepting to parse the contents into a JSONMap\n\/\/\nfunc ExtractJSON(jsonString string, jsonType int) (result JSONMapType, err error) {\n\t\/\/ unmarshall is strict and wants complete JSON structures\n\tjsonString, jsonType = IsolateJSON(jsonString, jsonType)\n\tresult, err = FromJSON(jsonString)\n\tif err != nil {\n\t\tjsonString = TidyScript(jsonString)\n\t\tresult, err = FromJSON(jsonString)\n\t\tif err != nil {\n\t\t\tjsonString = TidyJSON(jsonString, jsonType)\n\t\t\tresult, err = FromJSON(jsonString)\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/\n\/\/ IsolateJSON isolates the JSON parsable text based on array or dictionary delimiters\n\/\/\nfunc IsolateJSON(jsonString string, jsonTypeIn int) (result string, jsonType int) {\n\tvar delimiter []string = nil\n\tdelimiterIndex := -1\n\n\tif jsonTypeIn == JSONUnknownType {\n\t\tjsonType, delimiterIndex = IdentifityJSONFragment(jsonString)\n\t} else {\n\t\tjsonType = jsonTypeIn\n\t\tdelimiterIndex = strings.Index(jsonString, _JSONDictionaryDelimiter[0])\n\n\t}\n\n\tswitch jsonType {\n\tcase JSONArrayType:\n\t\tdelimiter = _JSONArrayDelimiter\n\tcase JSONDictionaryType:\n\t\tdelimiter = _JSONDictionaryDelimiter\n\tdefault:\n\t\treturn\n\t}\n\n\tif delimiterIndex >= 0 {\n\t\tresult = jsonString[delimiterIndex:]\n\t\tdelimiterIndex = strings.Index(result, delimiter[1])\n\t\tif delimiterIndex >= 0 {\n\t\t\tresult = result[:delimiterIndex+1]\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/\n\/\/ TidyScript\n\/\/\nfunc TidyScript(jsonString string) (result string) {\n\t\/\/ no newlines\n\tresult = strings.Replace(jsonString, \"\\n\", \"\", -1)\n\t\/\/ no tabs\n\tresult = strings.Replace(result, \"\\t\", \"\", -1)\n\n\treturn\n}\n\n\/\/\n\/\/ TidyJSON\n\/\/\nfunc TidyJSON(jsonString string, jsonType int) (result string) {\n\t\/\/ JSON improper escaping detected - need to split the string and tidy it\n\tif len(jsonString) > 1 { \n\t\tvar jsonDelimiter []string\n\t\tif jsonType == JSONDictionaryType {\n\t\t\t\/\/ dictionary cleanup\n\t\t\tjsonDelimiter = _JSONDictionaryDelimiter\n\t\t\tentries := strings.Split(jsonString[1:len(jsonString)-1], \",\")\n\t\t\tfor _, entry := range entries {\n\t\t\t\tval := strings.Split(entry, \":\")\n\t\t\t\tif len(val) >= 2 {\n\t\t\t\t\tresult += fmt.Sprintf(\"\\\"%s\\\": \\\"%s\\\",\", strings.Trim(val[0], \" '\\\"\"), strings.Trim(val[1], \" '\\\"\"))\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ array\n\t\t\tjsonDelimiter = _JSONArrayDelimiter\n\t\t\tentries := strings.Split(jsonString[1:len(jsonString)-1], \",\")\n\t\t\tfor _, entry := range entries {\n\t\t\t\tresult += fmt.Sprintf(\"\\\"%s\\\",\", strings.Trim(entry, \" '\"))\n\t\t\t}\n\t\t}\n\n\t\t\/\/ reconstitute the result dropping the last comma\n\t\tresultLen := len(result)\n\t\tif resultLen > 1 {\n\t\t\tresult = jsonDelimiter[0] + result[:resultLen-1] + jsonDelimiter[1]\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc numericConversion(jsonstring string) (result int, err error) {\n\tif strings.ToLower(jsonstring) == strings.ToUpper(jsonstring) {\n\t\tresult, err = strconv.Atoi(jsonstring)\n\t\tif err != nil {\n\t\t\tresult, err = EvaluateEquation(jsonstring)\n\t\t}\n\t} else {\n\t\terr = errors.New(\"string\")\n\t}\n\n\treturn\n}\n\n\/\/\n\/\/ TidyValues\n\/\/\nfunc TidyValues(jsonString string, jsonType int) (result string) {\n\tvar jsonDelimiter []string\n\tif jsonType == JSONDictionaryType {\n\t\t\/\/ dictionary cleanup\n\t\tjsonDelimiter = _JSONDictionaryDelimiter\n\t\tentries := strings.Split(jsonString[1:len(jsonString)-1], \",\")\n\t\tfor _, entry := range entries {\n\t\t\tval := strings.Split(entry, \":\")\n\t\t\tival, err := numericConversion(val[1])\n\t\t\tif err == nil {\n\t\t\t\tresult += fmt.Sprintf(\"\\\"%s\\\": %d,\", val[0], ival)\n\t\t\t} else {\n\t\t\t\tresult += fmt.Sprintf(\"\\\"%s\\\": \\\"%s\\\",\", val[0], val[1])\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\/\/ array\n\t\tjsonDelimiter = _JSONArrayDelimiter\n\t\tentries := strings.Split(jsonString[1:len(jsonString)-1], \",\")\n\t\tfor _, entry := range entries {\n\t\t\tival, err := numericConversion(entry)\n\t\t\tif err == nil {\n\t\t\t\tresult += fmt.Sprintf(\"%d,\", ival)\n\t\t\t} else {\n\t\t\t\tresult += fmt.Sprintf(\"\\\"%s\\\",\", entry)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ reconstitute the result dropping the last comma\n\tresult = jsonDelimiter[0] + result[:len(result)-1] + jsonDelimiter[1]\n\n\treturn result\n}\n<|endoftext|>"}
{"text":"<commit_before>package split\n\nimport \"net\/http\"\n\n\/\/ WriteResponses serialize the responses passed as argument into the ResponseWriter\nfunc WriteResponses(w http.ResponseWriter, esponses []*http.Response) error {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"Not impelmented yet\"))\n\treturn nil\n}\n<commit_msg>Collect and pack responses<commit_after>package split\n\nimport (\n\t\"bytes\"\n\t\"mime\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"net\/textproto\"\n)\n\n\/\/ WriteResponses serialize the responses passed as argument into the ResponseWriter\nfunc WriteResponses(w http.ResponseWriter, responses []*http.Response) error {\n\tvar buf bytes.Buffer\n\tmultipartWriter := multipart.NewWriter(&buf)\n\n\tmimeHeaders := textproto.MIMEHeader(make(map[string][]string))\n\tmimeHeaders.Set(\"Content-Type\", \"application\/http\")\n\n\tfor _, resp := range responses {\n\t\tpart, err := multipartWriter.CreatePart(mimeHeaders)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp.Write(part)\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Header().Set(\"Content-Type\", mime.FormatMediaType(\"multipart\/mixed\", map[string]string{\"boundary\": multipartWriter.Boundary()}))\n\tbuf.WriteTo(w)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Static hash table test cases. *\/\npackage chunkfile\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestPutGetReopenClear(t *testing.T) {\n\ttmp := \"\/tmp\/tiedot_hash_test\"\n\tos.Remove(tmp)\n\tdefer os.Remove(tmp)\n\tht, err := OpenHash(tmp)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open: %v\", err)\n\t}\n\t\/\/ Test initial size information\n\tif !(ht.NumBuckets == INITIAL_BUCKETS && ht.File.UsedSize == INITIAL_BUCKETS*BUCKET_SIZE && ht.File.Size == HT_FILE_SIZE) {\n\t\tt.Fatal(\"Wrong size\")\n\t}\n\tdefer ht.File.Close()\n\tfor i := uint64(0); i < 1024*1024*2; i++ {\n\t\tht.Put(i, i)\n\t}\n\tfor i := uint64(0); i < 1024*1024*2; i++ {\n\t\tkeys, vals := ht.Get(i, 0, func(a, b uint64) bool {\n\t\t\treturn true\n\t\t})\n\t\tif !(len(keys) == 1 && keys[0] == i && len(vals) == 1 && vals[0] == i) {\n\t\t\tt.Fatalf(\"Get failed on key %d, got %v and %v\", i, keys, vals)\n\t\t}\n\t}\n\tnumBuckets := ht.NumBuckets\n\t\/\/ Reopen the hash table and test the features\n\treopened, err := OpenHash(tmp)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open: %v\", err)\n\t}\n\tif reopened.NumBuckets != numBuckets {\n\t\tt.Fatalf(\"Wrong NumBuckets\")\n\t}\n\tif reopened.File.UsedSize != numBuckets*BUCKET_SIZE {\n\t\tt.Fatalf(\"Wrong UsedSize\")\n\t}\n\tfor i := uint64(0); i < 1024*1024*2; i++ {\n\t\tkeys, vals := reopened.Get(i, 0, func(a, b uint64) bool {\n\t\t\treturn true\n\t\t})\n\t\tif !(len(keys) == 1 && keys[0] == i && len(vals) == 1 && vals[0] == i) {\n\t\t\tt.Fatalf(\"Get failed on key %d, got %v and %v\", i, keys, vals)\n\t\t}\n\t}\n\t\/\/ Clear the hash table\n\treopened.Clear()\n\tif !(reopened.NumBuckets == INITIAL_BUCKETS && reopened.File.UsedSize == INITIAL_BUCKETS*BUCKET_SIZE) {\n\t\tt.Fatal(\"Did not clear the hash table\")\n\t}\n\tkeys, vals := ht.GetAll(0)\n\tif len(keys) != 0 || len(vals) != 0 {\n\t\tt.Fatal(\"Did not clear the hash table\")\n\t}\n}\n\nfunc TestPutGet2(t *testing.T) {\n\ttmp := \"\/tmp\/tiedot_hash_test\"\n\tos.Remove(tmp)\n\tdefer os.Remove(tmp)\n\tht, err := OpenHash(tmp)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open: %v\", err)\n\t\treturn\n\t}\n\tdefer ht.File.Close()\n\tht.Put(1, 1)\n\tht.Put(1, 2)\n\tht.Put(1, 3)\n\tht.Put(2, 1)\n\tht.Put(2, 2)\n\tht.Put(2, 3)\n\tkeys, vals := ht.Get(1, 0, func(a, b uint64) bool {\n\t\treturn true\n\t})\n\tif !(len(keys) == 3 && len(vals) == 3) {\n\t\tt.Fatalf(\"Get failed, got %v, %v\", keys, vals)\n\t}\n\tkeys, vals = ht.Get(2, 2, func(a, b uint64) bool {\n\t\treturn true\n\t})\n\tif !(len(keys) == 2 && len(vals) == 2) {\n\t\tt.Fatalf(\"Get failed, got %v, %v\", keys, vals)\n\t}\n\tkeys, vals = ht.Get(1, 0, func(a, b uint64) bool {\n\t\treturn b >= 2\n\t})\n\tif !(len(keys) == 2 && len(vals) == 2) {\n\t\tt.Fatalf(\"Get failed, got %v, %v\", keys, vals)\n\t}\n}\n\nfunc TestPutRemove(t *testing.T) {\n\ttmp := \"\/tmp\/tiedot_hash_test\"\n\tos.Remove(tmp)\n\tdefer os.Remove(tmp)\n\tht, err := OpenHash(tmp)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open: %v\", err)\n\t\treturn\n\t}\n\tdefer ht.File.Close()\n\tht.Put(1, 1)\n\tht.Put(1, 2)\n\tht.Put(1, 3)\n\tht.Put(2, 1)\n\tht.Put(2, 2)\n\tht.Put(2, 3)\n\tht.Remove(1, 1)\n\tht.Remove(2, 2)\n\tkeys, vals := ht.Get(1, 0, func(a, b uint64) bool {\n\t\treturn true\n\t})\n\tif !(len(keys) == 2 && len(vals) == 2) {\n\t\tt.Fatalf(\"Did not delete, still have %v, %v\", keys, vals)\n\t}\n\tkeys, vals = ht.Get(2, 0, func(a, b uint64) bool {\n\t\treturn true\n\t})\n\tif !(len(keys) == 2 && len(vals) == 2) {\n\t\tt.Fatalf(\"Did not delete, still have %v, %v\", keys, vals)\n\t}\n}\n\nfunc TestGetAll(t *testing.T) {\n\ttmp := \"\/tmp\/tiedot_hash_test\"\n\tos.Remove(tmp)\n\tdefer os.Remove(tmp)\n\tht, err := OpenHash(tmp)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open: %v\", err)\n\t\treturn\n\t}\n\tdefer ht.File.Close()\n\tht.Put(1, 1)\n\tht.Put(1, 2)\n\tht.Put(1, 3)\n\tht.Put(2, 1)\n\tht.Put(2, 2)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tkeys, vals := ht.GetAll(0)\n\tif !(len(keys) == 16 && len(vals) == 16) {\n\t\tt.Fatalf(\"Did not get everything, got only %v, %v\", keys, vals)\n\t}\n\tkeys, vals = ht.GetAll(3)\n\tif !(len(keys) == 3 && len(vals) == 3) {\n\t\tt.Fatalf(\"Did not get three values, got %v, %v\", keys, vals)\n\t}\n}\n<commit_msg>just a reminder<commit_after>\/* Static hash table test cases. *\/\npackage chunkfile\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestPutGetReopenClear(t *testing.T) {\n\ttmp := \"\/tmp\/tiedot_hash_test\"\n\tos.Remove(tmp)\n\tdefer os.Remove(tmp)\n\tht, err := OpenHash(tmp)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open: %v\", err)\n\t}\n\t\/\/ Test initial size information\n\tif !(ht.NumBuckets == INITIAL_BUCKETS && ht.File.UsedSize == INITIAL_BUCKETS*BUCKET_SIZE && ht.File.Size == HT_FILE_SIZE) {\n\t\tt.Fatal(\"Wrong size\")\n\t}\n\tdefer ht.File.Close()\n\tfmt.Println(\"Please be patient, this may take a minute.\")\n\tfor i := uint64(0); i < 1024*1024*2; i++ {\n\t\tht.Put(i, i)\n\t}\n\tfor i := uint64(0); i < 1024*1024*2; i++ {\n\t\tkeys, vals := ht.Get(i, 0, func(a, b uint64) bool {\n\t\t\treturn true\n\t\t})\n\t\tif !(len(keys) == 1 && keys[0] == i && len(vals) == 1 && vals[0] == i) {\n\t\t\tt.Fatalf(\"Get failed on key %d, got %v and %v\", i, keys, vals)\n\t\t}\n\t}\n\tnumBuckets := ht.NumBuckets\n\t\/\/ Reopen the hash table and test the features\n\treopened, err := OpenHash(tmp)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open: %v\", err)\n\t}\n\tif reopened.NumBuckets != numBuckets {\n\t\tt.Fatalf(\"Wrong NumBuckets\")\n\t}\n\tif reopened.File.UsedSize != numBuckets*BUCKET_SIZE {\n\t\tt.Fatalf(\"Wrong UsedSize\")\n\t}\n\tfor i := uint64(0); i < 1024*1024*2; i++ {\n\t\tkeys, vals := reopened.Get(i, 0, func(a, b uint64) bool {\n\t\t\treturn true\n\t\t})\n\t\tif !(len(keys) == 1 && keys[0] == i && len(vals) == 1 && vals[0] == i) {\n\t\t\tt.Fatalf(\"Get failed on key %d, got %v and %v\", i, keys, vals)\n\t\t}\n\t}\n\t\/\/ Clear the hash table\n\treopened.Clear()\n\tif !(reopened.NumBuckets == INITIAL_BUCKETS && reopened.File.UsedSize == INITIAL_BUCKETS*BUCKET_SIZE) {\n\t\tt.Fatal(\"Did not clear the hash table\")\n\t}\n\tkeys, vals := ht.GetAll(0)\n\tif len(keys) != 0 || len(vals) != 0 {\n\t\tt.Fatal(\"Did not clear the hash table\")\n\t}\n}\n\nfunc TestPutGet2(t *testing.T) {\n\ttmp := \"\/tmp\/tiedot_hash_test\"\n\tos.Remove(tmp)\n\tdefer os.Remove(tmp)\n\tht, err := OpenHash(tmp)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open: %v\", err)\n\t\treturn\n\t}\n\tdefer ht.File.Close()\n\tht.Put(1, 1)\n\tht.Put(1, 2)\n\tht.Put(1, 3)\n\tht.Put(2, 1)\n\tht.Put(2, 2)\n\tht.Put(2, 3)\n\tkeys, vals := ht.Get(1, 0, func(a, b uint64) bool {\n\t\treturn true\n\t})\n\tif !(len(keys) == 3 && len(vals) == 3) {\n\t\tt.Fatalf(\"Get failed, got %v, %v\", keys, vals)\n\t}\n\tkeys, vals = ht.Get(2, 2, func(a, b uint64) bool {\n\t\treturn true\n\t})\n\tif !(len(keys) == 2 && len(vals) == 2) {\n\t\tt.Fatalf(\"Get failed, got %v, %v\", keys, vals)\n\t}\n\tkeys, vals = ht.Get(1, 0, func(a, b uint64) bool {\n\t\treturn b >= 2\n\t})\n\tif !(len(keys) == 2 && len(vals) == 2) {\n\t\tt.Fatalf(\"Get failed, got %v, %v\", keys, vals)\n\t}\n}\n\nfunc TestPutRemove(t *testing.T) {\n\ttmp := \"\/tmp\/tiedot_hash_test\"\n\tos.Remove(tmp)\n\tdefer os.Remove(tmp)\n\tht, err := OpenHash(tmp)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open: %v\", err)\n\t\treturn\n\t}\n\tdefer ht.File.Close()\n\tht.Put(1, 1)\n\tht.Put(1, 2)\n\tht.Put(1, 3)\n\tht.Put(2, 1)\n\tht.Put(2, 2)\n\tht.Put(2, 3)\n\tht.Remove(1, 1)\n\tht.Remove(2, 2)\n\tkeys, vals := ht.Get(1, 0, func(a, b uint64) bool {\n\t\treturn true\n\t})\n\tif !(len(keys) == 2 && len(vals) == 2) {\n\t\tt.Fatalf(\"Did not delete, still have %v, %v\", keys, vals)\n\t}\n\tkeys, vals = ht.Get(2, 0, func(a, b uint64) bool {\n\t\treturn true\n\t})\n\tif !(len(keys) == 2 && len(vals) == 2) {\n\t\tt.Fatalf(\"Did not delete, still have %v, %v\", keys, vals)\n\t}\n}\n\nfunc TestGetAll(t *testing.T) {\n\ttmp := \"\/tmp\/tiedot_hash_test\"\n\tos.Remove(tmp)\n\tdefer os.Remove(tmp)\n\tht, err := OpenHash(tmp)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open: %v\", err)\n\t\treturn\n\t}\n\tdefer ht.File.Close()\n\tht.Put(1, 1)\n\tht.Put(1, 2)\n\tht.Put(1, 3)\n\tht.Put(2, 1)\n\tht.Put(2, 2)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tht.Put(2, 3)\n\tkeys, vals := ht.GetAll(0)\n\tif !(len(keys) == 16 && len(vals) == 16) {\n\t\tt.Fatalf(\"Did not get everything, got only %v, %v\", keys, vals)\n\t}\n\tkeys, vals = ht.GetAll(3)\n\tif !(len(keys) == 3 && len(vals) == 3) {\n\t\tt.Fatalf(\"Did not get three values, got %v, %v\", keys, vals)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package has_vm_test\n\nimport (\n\t\"encoding\/json\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\n\ttesthelperscpi \"github.com\/maximilien\/bosh-softlayer-cpi\/test_helpers\"\n\tslclient \"github.com\/maximilien\/softlayer-go\/client\"\n\tdatatypes \"github.com\/maximilien\/softlayer-go\/data_types\"\n\tsoftlayer \"github.com\/maximilien\/softlayer-go\/softlayer\"\n\ttesthelpers \"github.com\/maximilien\/softlayer-go\/test_helpers\"\n)\n\nconst configPath = \"test_fixtures\/cpi_methods\/config.json\"\n\nvar _ = Describe(\"BOSH Director Level Integration for has_vm\", func() {\n\tvar (\n\t\terr error\n\n\t\tclient softlayer.Client\n\n\t\tusername, apiKey string\n\n\t\taccountService      softlayer.SoftLayer_Account_Service\n\t\tvirtualGuestService softlayer.SoftLayer_Virtual_Guest_Service\n\n\t\tvirtualGuest  datatypes.SoftLayer_Virtual_Guest\n\t\tcreatedSshKey datatypes.SoftLayer_Security_Ssh_Key\n\n\t\trootTemplatePath, tmpConfigPath, strVGID string\n\n\t\treplacementMap map[string]string\n\n\t\toutput map[string]interface{}\n\t)\n\n\tBeforeEach(func() {\n\t\tusername = os.Getenv(\"SL_USERNAME\")\n\t\tExpect(username).ToNot(Equal(\"\"), \"username cannot be empty, set SL_USERNAME\")\n\n\t\tapiKey = os.Getenv(\"SL_API_KEY\")\n\t\tExpect(apiKey).ToNot(Equal(\"\"), \"apiKey cannot be empty, set SL_API_KEY\")\n\n\t\tclient = slclient.NewSoftLayerClient(username, apiKey)\n\t\tExpect(client).ToNot(BeNil())\n\n\t\taccountService, err = testhelpers.CreateAccountService()\n\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\tvirtualGuestService, err = testhelpers.CreateVirtualGuestService()\n\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\ttesthelpers.TIMEOUT = 35 * time.Minute\n\t\ttesthelpers.POLLING_INTERVAL = 10 * time.Second\n\n\t\tpwd, err := os.Getwd()\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\trootTemplatePath = filepath.Join(pwd, \"..\", \"..\")\n\n\t\ttmpConfigPath, err = testhelperscpi.CreateTmpConfigPath(rootTemplatePath, configPath, username, apiKey)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t})\n\n\tAfterEach(func() {\n\t\terr = os.RemoveAll(tmpConfigPath)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t})\n\n\tContext(\"has_vm with actual vm\", func() {\n\t\tBeforeEach(func() {\n\t\t\terr = testhelpers.FindAndDeleteTestSshKeys()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\tcreatedSshKey, _ = testhelpers.CreateTestSshKey()\n\t\t\ttesthelpers.WaitForCreatedSshKeyToBePresent(createdSshKey.Id)\n\n\t\t\tvirtualGuest = testhelpers.CreateVirtualGuestAndMarkItTest([]datatypes.SoftLayer_Security_Ssh_Key{createdSshKey})\n\n\t\t\ttesthelpers.WaitForVirtualGuestToBeRunning(virtualGuest.Id)\n\t\t\ttesthelpers.WaitForVirtualGuestToHaveNoActiveTransactions(virtualGuest.Id)\n\n\t\t\tstrVGID = strconv.Itoa(virtualGuest.Id)\n\n\t\t\treplacementMap = map[string]string{\n\t\t\t\t\"ID\":           strVGID,\n\t\t\t\t\"DirectorUuid\": \"fake-director-uuid\",\n\t\t\t}\n\t\t})\n\n\t\tAfterEach(func() {\n\t\t\ttesthelpers.DeleteVirtualGuest(virtualGuest.Id)\n\t\t\ttesthelpers.DeleteSshKey(createdSshKey.Id)\n\t\t})\n\n\t\tIt(\"returns true because vm exists\", func() {\n\t\t\tjsonPayload, err := testhelperscpi.GenerateCpiJsonPayload(\"has_vm\", rootTemplatePath, replacementMap)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\toutputBytes, err := testhelperscpi.RunCpi(rootTemplatePath, tmpConfigPath, jsonPayload)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\n\t\t\terr = json.Unmarshal(outputBytes, &output)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(output[\"result\"]).To(BeTrue())\n\t\t})\n\t})\n\n\tContext(\"has_vm without valid vm id\", func() {\n\t\tBeforeEach(func() {\n\t\t\treplacementMap = map[string]string{\n\t\t\t\t\"ID\":           \"123456\",\n\t\t\t\t\"DirectorUuid\": \"fake-director-uuid\",\n\t\t\t}\n\t\t})\n\n\t\tIt(\"returns false because vm doesn't exist\", func() {\n\t\t\tjsonPayload, err := testhelperscpi.GenerateCpiJsonPayload(\"has_vm\", rootTemplatePath, replacementMap)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\toutputBytes, err := testhelperscpi.RunCpi(rootTemplatePath, tmpConfigPath, jsonPayload)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\n\t\t\terr = json.Unmarshal(outputBytes, &output)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(output[\"result\"]).To(BeFalse())\n\t\t})\n\t})\n})\n<commit_msg>finally fixing this go fmt issue<commit_after>package has_vm_test\n\nimport (\n\t\"encoding\/json\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\n\ttesthelperscpi \"github.com\/maximilien\/bosh-softlayer-cpi\/test_helpers\"\n\tslclient \"github.com\/maximilien\/softlayer-go\/client\"\n\tdatatypes \"github.com\/maximilien\/softlayer-go\/data_types\"\n\tsoftlayer \"github.com\/maximilien\/softlayer-go\/softlayer\"\n\ttesthelpers \"github.com\/maximilien\/softlayer-go\/test_helpers\"\n)\n\nconst configPath = \"test_fixtures\/cpi_methods\/config.json\"\n\nvar _ = Describe(\"BOSH Director Level Integration for has_vm\", func() {\n\tvar (\n\t\terr error\n\n\t\tclient softlayer.Client\n\n\t\tusername, apiKey string\n\n\t\taccountService      softlayer.SoftLayer_Account_Service\n\t\tvirtualGuestService softlayer.SoftLayer_Virtual_Guest_Service\n\n\t\tvirtualGuest  datatypes.SoftLayer_Virtual_Guest\n\t\tcreatedSshKey datatypes.SoftLayer_Security_Ssh_Key\n\n\t\trootTemplatePath, tmpConfigPath, strVGID string\n\n\t\treplacementMap map[string]string\n\n\t\toutput map[string]interface{}\n\t)\n\n\tBeforeEach(func() {\n\t\tusername = os.Getenv(\"SL_USERNAME\")\n\t\tExpect(username).ToNot(Equal(\"\"), \"username cannot be empty, set SL_USERNAME\")\n\n\t\tapiKey = os.Getenv(\"SL_API_KEY\")\n\t\tExpect(apiKey).ToNot(Equal(\"\"), \"apiKey cannot be empty, set SL_API_KEY\")\n\n\t\tclient = slclient.NewSoftLayerClient(username, apiKey)\n\t\tExpect(client).ToNot(BeNil())\n\n\t\taccountService, err = testhelpers.CreateAccountService()\n\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\tvirtualGuestService, err = testhelpers.CreateVirtualGuestService()\n\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\ttesthelpers.TIMEOUT = 35 * time.Minute\n\t\ttesthelpers.POLLING_INTERVAL = 10 * time.Second\n\n\t\tpwd, err := os.Getwd()\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\trootTemplatePath = filepath.Join(pwd, \"..\", \"..\")\n\n\t\ttmpConfigPath, err = testhelperscpi.CreateTmpConfigPath(rootTemplatePath, configPath, username, apiKey)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t})\n\n\tAfterEach(func() {\n\t\terr = os.RemoveAll(tmpConfigPath)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t})\n\n\tContext(\"has_vm with actual vm\", func() {\n\t\tBeforeEach(func() {\n\t\t\terr = testhelpers.FindAndDeleteTestSshKeys()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\tcreatedSshKey, _ = testhelpers.CreateTestSshKey()\n\t\t\ttesthelpers.WaitForCreatedSshKeyToBePresent(createdSshKey.Id)\n\n\t\t\tvirtualGuest = testhelpers.CreateVirtualGuestAndMarkItTest([]datatypes.SoftLayer_Security_Ssh_Key{createdSshKey})\n\n\t\t\ttesthelpers.WaitForVirtualGuestToBeRunning(virtualGuest.Id)\n\t\t\ttesthelpers.WaitForVirtualGuestToHaveNoActiveTransactions(virtualGuest.Id)\n\n\t\t\tstrVGID = strconv.Itoa(virtualGuest.Id)\n\n\t\t\treplacementMap = map[string]string{\n\t\t\t\t\"ID\":           strVGID,\n\t\t\t\t\"DirectorUuid\": \"fake-director-uuid\",\n\t\t\t}\n\t\t})\n\n\t\tAfterEach(func() {\n\t\t\ttesthelpers.DeleteVirtualGuest(virtualGuest.Id)\n\t\t\ttesthelpers.DeleteSshKey(createdSshKey.Id)\n\t\t})\n\n\t\tIt(\"returns true because vm exists\", func() {\n\t\t\tjsonPayload, err := testhelperscpi.GenerateCpiJsonPayload(\"has_vm\", rootTemplatePath, replacementMap)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\toutputBytes, err := testhelperscpi.RunCpi(rootTemplatePath, tmpConfigPath, jsonPayload)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\terr = json.Unmarshal(outputBytes, &output)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(output[\"result\"]).To(BeTrue())\n\t\t})\n\t})\n\n\tContext(\"has_vm without valid vm id\", func() {\n\t\tBeforeEach(func() {\n\t\t\treplacementMap = map[string]string{\n\t\t\t\t\"ID\":           \"123456\",\n\t\t\t\t\"DirectorUuid\": \"fake-director-uuid\",\n\t\t\t}\n\t\t})\n\n\t\tIt(\"returns false because vm doesn't exist\", func() {\n\t\t\tjsonPayload, err := testhelperscpi.GenerateCpiJsonPayload(\"has_vm\", rootTemplatePath, replacementMap)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\toutputBytes, err := testhelperscpi.RunCpi(rootTemplatePath, tmpConfigPath, jsonPayload)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\terr = json.Unmarshal(outputBytes, &output)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(output[\"result\"]).To(BeFalse())\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package symbolizer provides a routine to populate a profile with\n\/\/ symbol, file and line number information. It relies on the\n\/\/ addr2liner and demangle packages to do the actual work.\npackage symbolizer\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/google\/pprof\/internal\/binutils\"\n\t\"github.com\/google\/pprof\/internal\/plugin\"\n\t\"github.com\/google\/pprof\/internal\/symbolz\"\n\t\"github.com\/google\/pprof\/profile\"\n\t\"github.com\/ianlancetaylor\/demangle\"\n)\n\n\/\/ Symbolizer implements the plugin.Symbolize interface.\ntype Symbolizer struct {\n\tObj       plugin.ObjTool\n\tUI        plugin.UI\n\tTransport http.RoundTripper\n}\n\n\/\/ test taps for dependency injection\nvar symbolzSymbolize = symbolz.Symbolize\nvar localSymbolize = doLocalSymbolize\nvar demangleFunction = Demangle\n\n\/\/ Symbolize attempts to symbolize profile p. First uses binutils on\n\/\/ local binaries; if the source is a URL it attempts to get any\n\/\/ missed entries using symbolz.\nfunc (s *Symbolizer) Symbolize(mode string, sources plugin.MappingSources, p *profile.Profile) error {\n\tremote, local, fast, force, demanglerMode := true, true, false, false, \"\"\n\tfor _, o := range strings.Split(strings.ToLower(mode), \":\") {\n\t\tswitch o {\n\t\tcase \"\":\n\t\t\tcontinue\n\t\tcase \"none\", \"no\":\n\t\t\treturn nil\n\t\tcase \"local\":\n\t\t\tremote, local = false, true\n\t\tcase \"fastlocal\":\n\t\t\tremote, local, fast = false, true, true\n\t\tcase \"remote\":\n\t\t\tremote, local = true, false\n\t\tcase \"force\":\n\t\t\tforce = true\n\t\tdefault:\n\t\t\tswitch d := strings.TrimPrefix(o, \"demangle=\"); d {\n\t\t\tcase \"full\", \"none\", \"templates\":\n\t\t\t\tdemanglerMode = d\n\t\t\t\tforce = true\n\t\t\t\tcontinue\n\t\t\tcase \"default\":\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts.UI.PrintErr(\"ignoring unrecognized symbolization option: \" + mode)\n\t\t\ts.UI.PrintErr(\"expecting -symbolize=[local|fastlocal|remote|none][:force][:demangle=[none|full|templates|default]\")\n\t\t}\n\t}\n\n\tvar err error\n\tif local {\n\t\t\/\/ Symbolize locally using binutils.\n\t\tif err = localSymbolize(p, fast, force, s.Obj, s.UI); err != nil {\n\t\t\ts.UI.PrintErr(\"local symbolization: \" + err.Error())\n\t\t}\n\t}\n\tif remote {\n\t\tpost := func(source, post string) ([]byte, error) {\n\t\t\treturn postURL(source, post, s.Transport)\n\t\t}\n\t\tif err = symbolzSymbolize(p, force, sources, post, s.UI); err != nil {\n\t\t\treturn err \/\/ Ran out of options.\n\t\t}\n\t}\n\n\tdemangleFunction(p, force, demanglerMode)\n\treturn nil\n}\n\n\/\/ postURL issues a POST to a URL over HTTP.\nfunc postURL(source, post string, tr http.RoundTripper) ([]byte, error) {\n\tclient := &http.Client{\n\t\tTransport: tr,\n\t}\n\tresp, err := client.Post(source, \"application\/octet-stream\", strings.NewReader(post))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"http post %s: %v\", source, err)\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"http post %s: %v\", source, statusCodeError(resp))\n\t}\n\treturn ioutil.ReadAll(resp.Body)\n}\n\nfunc statusCodeError(resp *http.Response) error {\n\tif resp.Header.Get(\"X-Go-Pprof\") != \"\" && strings.Contains(resp.Header.Get(\"Content-Type\"), \"text\/plain\") {\n\t\t\/\/ error is from pprof endpoint\n\t\tif body, err := ioutil.ReadAll(resp.Body); err == nil {\n\t\t\treturn fmt.Errorf(\"server response: %s - %s\", resp.Status, body)\n\t\t}\n\t}\n\treturn fmt.Errorf(\"server response: %s\", resp.Status)\n}\n\n\/\/ doLocalSymbolize adds symbol and line number information to all locations\n\/\/ in a profile. mode enables some options to control\n\/\/ symbolization.\nfunc doLocalSymbolize(prof *profile.Profile, fast, force bool, obj plugin.ObjTool, ui plugin.UI) error {\n\tif fast {\n\t\tif bu, ok := obj.(*binutils.Binutils); ok {\n\t\t\tbu.SetFastSymbolization(true)\n\t\t}\n\t}\n\n\tmt, err := newMapping(prof, obj, ui, force)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer mt.close()\n\n\tfunctions := make(map[profile.Function]*profile.Function)\n\tfor _, l := range mt.prof.Location {\n\t\tm := l.Mapping\n\t\tsegment := mt.segments[m]\n\t\tif segment == nil {\n\t\t\t\/\/ Nothing to do.\n\t\t\tcontinue\n\t\t}\n\n\t\tstack, err := segment.SourceLine(l.Address)\n\t\tif err != nil || len(stack) == 0 {\n\t\t\t\/\/ No answers from addr2line.\n\t\t\tcontinue\n\t\t}\n\n\t\tl.Line = make([]profile.Line, len(stack))\n\t\tl.IsFolded = false\n\t\tfor i, frame := range stack {\n\t\t\tif frame.Func != \"\" {\n\t\t\t\tm.HasFunctions = true\n\t\t\t}\n\t\t\tif frame.File != \"\" {\n\t\t\t\tm.HasFilenames = true\n\t\t\t}\n\t\t\tif frame.Line != 0 {\n\t\t\t\tm.HasLineNumbers = true\n\t\t\t}\n\t\t\tf := &profile.Function{\n\t\t\t\tName:       frame.Func,\n\t\t\t\tSystemName: frame.Func,\n\t\t\t\tFilename:   frame.File,\n\t\t\t}\n\t\t\tif fp := functions[*f]; fp != nil {\n\t\t\t\tf = fp\n\t\t\t} else {\n\t\t\t\tfunctions[*f] = f\n\t\t\t\tf.ID = uint64(len(mt.prof.Function)) + 1\n\t\t\t\tmt.prof.Function = append(mt.prof.Function, f)\n\t\t\t}\n\t\t\tl.Line[i] = profile.Line{\n\t\t\t\tFunction: f,\n\t\t\t\tLine:     int64(frame.Line),\n\t\t\t}\n\t\t}\n\n\t\tif len(stack) > 0 {\n\t\t\tm.HasInlineFrames = true\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Demangle updates the function names in a profile with demangled C++\n\/\/ names, simplified according to demanglerMode. If force is set,\n\/\/ overwrite any names that appear already demangled.\nfunc Demangle(prof *profile.Profile, force bool, demanglerMode string) {\n\tif force {\n\t\t\/\/ Remove the current demangled names to force demangling\n\t\tfor _, f := range prof.Function {\n\t\t\tif f.Name != \"\" && f.SystemName != \"\" {\n\t\t\t\tf.Name = f.SystemName\n\t\t\t}\n\t\t}\n\t}\n\n\tvar options []demangle.Option\n\tswitch demanglerMode {\n\tcase \"\": \/\/ demangled, simplified: no parameters, no templates, no return type\n\t\toptions = []demangle.Option{demangle.NoParams, demangle.NoTemplateParams}\n\tcase \"templates\": \/\/ demangled, simplified: no parameters, no return type\n\t\toptions = []demangle.Option{demangle.NoParams}\n\tcase \"full\":\n\t\toptions = []demangle.Option{demangle.NoClones}\n\tcase \"none\": \/\/ no demangling\n\t\treturn\n\t}\n\n\t\/\/ Copy the options because they may be updated by the call.\n\to := make([]demangle.Option, len(options))\n\tfor _, fn := range prof.Function {\n\t\tif fn.Name != \"\" && fn.SystemName != fn.Name {\n\t\t\tcontinue \/\/ Already demangled.\n\t\t}\n\t\tcopy(o, options)\n\t\tif demangled := demangle.Filter(fn.SystemName, o...); demangled != fn.SystemName {\n\t\t\tfn.Name = demangled\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Could not demangle. Apply heuristics in case the name is\n\t\t\/\/ already demangled.\n\t\tname := fn.SystemName\n\t\tif looksLikeDemangledCPlusPlus(name) {\n\t\t\tif demanglerMode == \"\" || demanglerMode == \"templates\" {\n\t\t\t\tname = removeMatching(name, '(', ')')\n\t\t\t}\n\t\t\tif demanglerMode == \"\" {\n\t\t\t\tname = removeMatching(name, '<', '>')\n\t\t\t}\n\t\t}\n\t\tfn.Name = name\n\t}\n}\n\n\/\/ looksLikeDemangledCPlusPlus is a heuristic to decide if a name is\n\/\/ the result of demangling C++. If so, further heuristics will be\n\/\/ applied to simplify the name.\nfunc looksLikeDemangledCPlusPlus(demangled string) bool {\n\tif strings.Contains(demangled, \".<\") { \/\/ Skip java names of the form \"class.<init>\"\n\t\treturn false\n\t}\n\treturn strings.ContainsAny(demangled, \"<>[]\") || strings.Contains(demangled, \"::\")\n}\n\n\/\/ removeMatching removes nested instances of start..end from name.\nfunc removeMatching(name string, start, end byte) string {\n\ts := string(start) + string(end)\n\tvar nesting, first, current int\n\tfor index := strings.IndexAny(name[current:], s); index != -1; index = strings.IndexAny(name[current:], s) {\n\t\tswitch current += index; name[current] {\n\t\tcase start:\n\t\t\tnesting++\n\t\t\tif nesting == 1 {\n\t\t\t\tfirst = current\n\t\t\t}\n\t\tcase end:\n\t\t\tnesting--\n\t\t\tswitch {\n\t\t\tcase nesting < 0:\n\t\t\t\treturn name \/\/ Mismatch, abort\n\t\t\tcase nesting == 0:\n\t\t\t\tname = name[:first] + name[current+1:]\n\t\t\t\tcurrent = first - 1\n\t\t\t}\n\t\t}\n\t\tcurrent++\n\t}\n\treturn name\n}\n\n\/\/ newMapping creates a mappingTable for a profile.\nfunc newMapping(prof *profile.Profile, obj plugin.ObjTool, ui plugin.UI, force bool) (*mappingTable, error) {\n\tmt := &mappingTable{\n\t\tprof:     prof,\n\t\tsegments: make(map[*profile.Mapping]plugin.ObjFile),\n\t}\n\n\t\/\/ Identify used mappings\n\tmappings := make(map[*profile.Mapping]bool)\n\tfor _, l := range prof.Location {\n\t\tmappings[l.Mapping] = true\n\t}\n\n\tmissingBinaries := false\n\tfor midx, m := range prof.Mapping {\n\t\tif !mappings[m] {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Do not attempt to re-symbolize a mapping that has already been symbolized.\n\t\tif !force && (m.HasFunctions || m.HasFilenames || m.HasLineNumbers) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif m.File == \"\" {\n\t\t\tif midx == 0 {\n\t\t\t\tui.PrintErr(\"Main binary filename not available.\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmissingBinaries = true\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Skip well-known system mappings\n\t\tif m.Unsymbolizable() {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Skip mappings pointing to a source URL\n\t\tif m.BuildID == \"\" {\n\t\t\tif u, err := url.Parse(m.File); err == nil && u.IsAbs() && strings.Contains(strings.ToLower(u.Scheme), \"http\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tname := filepath.Base(m.File)\n\t\tf, err := obj.Open(m.File, m.Start, m.Limit, m.Offset)\n\t\tif err != nil {\n\t\t\tui.PrintErr(\"Local symbolization failed for \", name, \": \", err)\n\t\t\tmissingBinaries = true\n\t\t\tcontinue\n\t\t}\n\t\tif fid := f.BuildID(); m.BuildID != \"\" && fid != \"\" && fid != m.BuildID {\n\t\t\tui.PrintErr(\"Local symbolization failed for \", name, \": build ID mismatch\")\n\t\t\tf.Close()\n\t\t\tcontinue\n\t\t}\n\n\t\tmt.segments[m] = f\n\t}\n\tif missingBinaries {\n\t\tui.PrintErr(\"Some binary filenames not available. Symbolization may be incomplete.\\n\" +\n\t\t\t\"Try setting PPROF_BINARY_PATH to the search path for local binaries.\")\n\t}\n\treturn mt, nil\n}\n\n\/\/ mappingTable contains the mechanisms for symbolization of a\n\/\/ profile.\ntype mappingTable struct {\n\tprof     *profile.Profile\n\tsegments map[*profile.Mapping]plugin.ObjFile\n}\n\n\/\/ Close releases any external processes being used for the mapping.\nfunc (mt *mappingTable) close() {\n\tfor _, segment := range mt.segments {\n\t\tsegment.Close()\n\t}\n}\n<commit_msg>Log build ID in local symbolization error messages. (#679)<commit_after>\/\/ Copyright 2014 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package symbolizer provides a routine to populate a profile with\n\/\/ symbol, file and line number information. It relies on the\n\/\/ addr2liner and demangle packages to do the actual work.\npackage symbolizer\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/google\/pprof\/internal\/binutils\"\n\t\"github.com\/google\/pprof\/internal\/plugin\"\n\t\"github.com\/google\/pprof\/internal\/symbolz\"\n\t\"github.com\/google\/pprof\/profile\"\n\t\"github.com\/ianlancetaylor\/demangle\"\n)\n\n\/\/ Symbolizer implements the plugin.Symbolize interface.\ntype Symbolizer struct {\n\tObj       plugin.ObjTool\n\tUI        plugin.UI\n\tTransport http.RoundTripper\n}\n\n\/\/ test taps for dependency injection\nvar symbolzSymbolize = symbolz.Symbolize\nvar localSymbolize = doLocalSymbolize\nvar demangleFunction = Demangle\n\n\/\/ Symbolize attempts to symbolize profile p. First uses binutils on\n\/\/ local binaries; if the source is a URL it attempts to get any\n\/\/ missed entries using symbolz.\nfunc (s *Symbolizer) Symbolize(mode string, sources plugin.MappingSources, p *profile.Profile) error {\n\tremote, local, fast, force, demanglerMode := true, true, false, false, \"\"\n\tfor _, o := range strings.Split(strings.ToLower(mode), \":\") {\n\t\tswitch o {\n\t\tcase \"\":\n\t\t\tcontinue\n\t\tcase \"none\", \"no\":\n\t\t\treturn nil\n\t\tcase \"local\":\n\t\t\tremote, local = false, true\n\t\tcase \"fastlocal\":\n\t\t\tremote, local, fast = false, true, true\n\t\tcase \"remote\":\n\t\t\tremote, local = true, false\n\t\tcase \"force\":\n\t\t\tforce = true\n\t\tdefault:\n\t\t\tswitch d := strings.TrimPrefix(o, \"demangle=\"); d {\n\t\t\tcase \"full\", \"none\", \"templates\":\n\t\t\t\tdemanglerMode = d\n\t\t\t\tforce = true\n\t\t\t\tcontinue\n\t\t\tcase \"default\":\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts.UI.PrintErr(\"ignoring unrecognized symbolization option: \" + mode)\n\t\t\ts.UI.PrintErr(\"expecting -symbolize=[local|fastlocal|remote|none][:force][:demangle=[none|full|templates|default]\")\n\t\t}\n\t}\n\n\tvar err error\n\tif local {\n\t\t\/\/ Symbolize locally using binutils.\n\t\tif err = localSymbolize(p, fast, force, s.Obj, s.UI); err != nil {\n\t\t\ts.UI.PrintErr(\"local symbolization: \" + err.Error())\n\t\t}\n\t}\n\tif remote {\n\t\tpost := func(source, post string) ([]byte, error) {\n\t\t\treturn postURL(source, post, s.Transport)\n\t\t}\n\t\tif err = symbolzSymbolize(p, force, sources, post, s.UI); err != nil {\n\t\t\treturn err \/\/ Ran out of options.\n\t\t}\n\t}\n\n\tdemangleFunction(p, force, demanglerMode)\n\treturn nil\n}\n\n\/\/ postURL issues a POST to a URL over HTTP.\nfunc postURL(source, post string, tr http.RoundTripper) ([]byte, error) {\n\tclient := &http.Client{\n\t\tTransport: tr,\n\t}\n\tresp, err := client.Post(source, \"application\/octet-stream\", strings.NewReader(post))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"http post %s: %v\", source, err)\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"http post %s: %v\", source, statusCodeError(resp))\n\t}\n\treturn ioutil.ReadAll(resp.Body)\n}\n\nfunc statusCodeError(resp *http.Response) error {\n\tif resp.Header.Get(\"X-Go-Pprof\") != \"\" && strings.Contains(resp.Header.Get(\"Content-Type\"), \"text\/plain\") {\n\t\t\/\/ error is from pprof endpoint\n\t\tif body, err := ioutil.ReadAll(resp.Body); err == nil {\n\t\t\treturn fmt.Errorf(\"server response: %s - %s\", resp.Status, body)\n\t\t}\n\t}\n\treturn fmt.Errorf(\"server response: %s\", resp.Status)\n}\n\n\/\/ doLocalSymbolize adds symbol and line number information to all locations\n\/\/ in a profile. mode enables some options to control\n\/\/ symbolization.\nfunc doLocalSymbolize(prof *profile.Profile, fast, force bool, obj plugin.ObjTool, ui plugin.UI) error {\n\tif fast {\n\t\tif bu, ok := obj.(*binutils.Binutils); ok {\n\t\t\tbu.SetFastSymbolization(true)\n\t\t}\n\t}\n\n\tmt, err := newMapping(prof, obj, ui, force)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer mt.close()\n\n\tfunctions := make(map[profile.Function]*profile.Function)\n\tfor _, l := range mt.prof.Location {\n\t\tm := l.Mapping\n\t\tsegment := mt.segments[m]\n\t\tif segment == nil {\n\t\t\t\/\/ Nothing to do.\n\t\t\tcontinue\n\t\t}\n\n\t\tstack, err := segment.SourceLine(l.Address)\n\t\tif err != nil || len(stack) == 0 {\n\t\t\t\/\/ No answers from addr2line.\n\t\t\tcontinue\n\t\t}\n\n\t\tl.Line = make([]profile.Line, len(stack))\n\t\tl.IsFolded = false\n\t\tfor i, frame := range stack {\n\t\t\tif frame.Func != \"\" {\n\t\t\t\tm.HasFunctions = true\n\t\t\t}\n\t\t\tif frame.File != \"\" {\n\t\t\t\tm.HasFilenames = true\n\t\t\t}\n\t\t\tif frame.Line != 0 {\n\t\t\t\tm.HasLineNumbers = true\n\t\t\t}\n\t\t\tf := &profile.Function{\n\t\t\t\tName:       frame.Func,\n\t\t\t\tSystemName: frame.Func,\n\t\t\t\tFilename:   frame.File,\n\t\t\t}\n\t\t\tif fp := functions[*f]; fp != nil {\n\t\t\t\tf = fp\n\t\t\t} else {\n\t\t\t\tfunctions[*f] = f\n\t\t\t\tf.ID = uint64(len(mt.prof.Function)) + 1\n\t\t\t\tmt.prof.Function = append(mt.prof.Function, f)\n\t\t\t}\n\t\t\tl.Line[i] = profile.Line{\n\t\t\t\tFunction: f,\n\t\t\t\tLine:     int64(frame.Line),\n\t\t\t}\n\t\t}\n\n\t\tif len(stack) > 0 {\n\t\t\tm.HasInlineFrames = true\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Demangle updates the function names in a profile with demangled C++\n\/\/ names, simplified according to demanglerMode. If force is set,\n\/\/ overwrite any names that appear already demangled.\nfunc Demangle(prof *profile.Profile, force bool, demanglerMode string) {\n\tif force {\n\t\t\/\/ Remove the current demangled names to force demangling\n\t\tfor _, f := range prof.Function {\n\t\t\tif f.Name != \"\" && f.SystemName != \"\" {\n\t\t\t\tf.Name = f.SystemName\n\t\t\t}\n\t\t}\n\t}\n\n\tvar options []demangle.Option\n\tswitch demanglerMode {\n\tcase \"\": \/\/ demangled, simplified: no parameters, no templates, no return type\n\t\toptions = []demangle.Option{demangle.NoParams, demangle.NoTemplateParams}\n\tcase \"templates\": \/\/ demangled, simplified: no parameters, no return type\n\t\toptions = []demangle.Option{demangle.NoParams}\n\tcase \"full\":\n\t\toptions = []demangle.Option{demangle.NoClones}\n\tcase \"none\": \/\/ no demangling\n\t\treturn\n\t}\n\n\t\/\/ Copy the options because they may be updated by the call.\n\to := make([]demangle.Option, len(options))\n\tfor _, fn := range prof.Function {\n\t\tif fn.Name != \"\" && fn.SystemName != fn.Name {\n\t\t\tcontinue \/\/ Already demangled.\n\t\t}\n\t\tcopy(o, options)\n\t\tif demangled := demangle.Filter(fn.SystemName, o...); demangled != fn.SystemName {\n\t\t\tfn.Name = demangled\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Could not demangle. Apply heuristics in case the name is\n\t\t\/\/ already demangled.\n\t\tname := fn.SystemName\n\t\tif looksLikeDemangledCPlusPlus(name) {\n\t\t\tif demanglerMode == \"\" || demanglerMode == \"templates\" {\n\t\t\t\tname = removeMatching(name, '(', ')')\n\t\t\t}\n\t\t\tif demanglerMode == \"\" {\n\t\t\t\tname = removeMatching(name, '<', '>')\n\t\t\t}\n\t\t}\n\t\tfn.Name = name\n\t}\n}\n\n\/\/ looksLikeDemangledCPlusPlus is a heuristic to decide if a name is\n\/\/ the result of demangling C++. If so, further heuristics will be\n\/\/ applied to simplify the name.\nfunc looksLikeDemangledCPlusPlus(demangled string) bool {\n\tif strings.Contains(demangled, \".<\") { \/\/ Skip java names of the form \"class.<init>\"\n\t\treturn false\n\t}\n\treturn strings.ContainsAny(demangled, \"<>[]\") || strings.Contains(demangled, \"::\")\n}\n\n\/\/ removeMatching removes nested instances of start..end from name.\nfunc removeMatching(name string, start, end byte) string {\n\ts := string(start) + string(end)\n\tvar nesting, first, current int\n\tfor index := strings.IndexAny(name[current:], s); index != -1; index = strings.IndexAny(name[current:], s) {\n\t\tswitch current += index; name[current] {\n\t\tcase start:\n\t\t\tnesting++\n\t\t\tif nesting == 1 {\n\t\t\t\tfirst = current\n\t\t\t}\n\t\tcase end:\n\t\t\tnesting--\n\t\t\tswitch {\n\t\t\tcase nesting < 0:\n\t\t\t\treturn name \/\/ Mismatch, abort\n\t\t\tcase nesting == 0:\n\t\t\t\tname = name[:first] + name[current+1:]\n\t\t\t\tcurrent = first - 1\n\t\t\t}\n\t\t}\n\t\tcurrent++\n\t}\n\treturn name\n}\n\n\/\/ newMapping creates a mappingTable for a profile.\nfunc newMapping(prof *profile.Profile, obj plugin.ObjTool, ui plugin.UI, force bool) (*mappingTable, error) {\n\tmt := &mappingTable{\n\t\tprof:     prof,\n\t\tsegments: make(map[*profile.Mapping]plugin.ObjFile),\n\t}\n\n\t\/\/ Identify used mappings\n\tmappings := make(map[*profile.Mapping]bool)\n\tfor _, l := range prof.Location {\n\t\tmappings[l.Mapping] = true\n\t}\n\n\tmissingBinaries := false\n\tfor midx, m := range prof.Mapping {\n\t\tif !mappings[m] {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Do not attempt to re-symbolize a mapping that has already been symbolized.\n\t\tif !force && (m.HasFunctions || m.HasFilenames || m.HasLineNumbers) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif m.File == \"\" {\n\t\t\tif midx == 0 {\n\t\t\t\tui.PrintErr(\"Main binary filename not available.\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmissingBinaries = true\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Skip well-known system mappings\n\t\tif m.Unsymbolizable() {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Skip mappings pointing to a source URL\n\t\tif m.BuildID == \"\" {\n\t\t\tif u, err := url.Parse(m.File); err == nil && u.IsAbs() && strings.Contains(strings.ToLower(u.Scheme), \"http\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tname := filepath.Base(m.File)\n\t\tif m.BuildID != \"\" {\n\t\t\tname += fmt.Sprintf(\" (build ID %s)\", m.BuildID)\n\t\t}\n\t\tf, err := obj.Open(m.File, m.Start, m.Limit, m.Offset)\n\t\tif err != nil {\n\t\t\tui.PrintErr(\"Local symbolization failed for \", name, \": \", err)\n\t\t\tmissingBinaries = true\n\t\t\tcontinue\n\t\t}\n\t\tif fid := f.BuildID(); m.BuildID != \"\" && fid != \"\" && fid != m.BuildID {\n\t\t\tui.PrintErr(\"Local symbolization failed for \", name, \": build ID mismatch\")\n\t\t\tf.Close()\n\t\t\tcontinue\n\t\t}\n\n\t\tmt.segments[m] = f\n\t}\n\tif missingBinaries {\n\t\tui.PrintErr(\"Some binary filenames not available. Symbolization may be incomplete.\\n\" +\n\t\t\t\"Try setting PPROF_BINARY_PATH to the search path for local binaries.\")\n\t}\n\treturn mt, nil\n}\n\n\/\/ mappingTable contains the mechanisms for symbolization of a\n\/\/ profile.\ntype mappingTable struct {\n\tprof     *profile.Profile\n\tsegments map[*profile.Mapping]plugin.ObjFile\n}\n\n\/\/ Close releases any external processes being used for the mapping.\nfunc (mt *mappingTable) close() {\n\tfor _, segment := range mt.segments {\n\t\tsegment.Close()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package filetype\n\nimport (\n\t\"github.com\/h2non\/filetype\/matchers\"\n\t\"github.com\/h2non\/filetype\/types\"\n)\n\n\/\/ Image tries to match a file as image type\nfunc Image(buf []byte) (types.Type, error) {\n\treturn doMatchMap(buf, matchers.Image)\n}\n\n\/\/ IsImage checks if the given buffer is an image type\nfunc IsImage(buf []byte) bool {\n\tkind, _ := Image(buf)\n\treturn kind != types.Unknown\n}\n\n\/\/ Audio tries to match a file as audio type\nfunc Audio(buf []byte) (types.Type, error) {\n\treturn doMatchMap(buf, matchers.Audio)\n}\n\n\/\/ IsAudio checks if the given buffer is an audio type\nfunc IsAudio(buf []byte) bool {\n\tkind, _ := Audio(buf)\n\treturn kind != types.Unknown\n}\n\n\/\/ Video tries to match a file as video type\nfunc Video(buf []byte) (types.Type, error) {\n\treturn doMatchMap(buf, matchers.Video)\n}\n\n\/\/ IsVideo checks if the given buffer is a video type\nfunc IsVideo(buf []byte) bool {\n\tkind, _ := Video(buf)\n\treturn kind != types.Unknown\n}\n\n\/\/ Font tries to match a file as text font type\nfunc Font(buf []byte) (types.Type, error) {\n\treturn doMatchMap(buf, matchers.Font)\n}\n\n\/\/ IsFont checks if the given buffer is a font type\nfunc IsFont(buf []byte) bool {\n\tkind, _ := Font(buf)\n\treturn kind != types.Unknown\n}\n\n\/\/ Archive tries to match a file as generic archive type\nfunc Archive(buf []byte) (types.Type, error) {\n\treturn doMatchMap(buf, matchers.Archive)\n}\n\n\/\/ IsArchive checks if the given buffer is an archive type\nfunc IsArchive(buf []byte) bool {\n\tkind, _ := Archive(buf)\n\treturn kind != types.Unknown\n}\n\n\/\/ Document tries to match a file as document type\nfunc Document(buf []byte) (types.Type, error) {\n\treturn doMatchMap(buf, matchers.Document)\n}\n\n\/\/ IsDocument checks if the given buffer is an document type\nfunc IsDocument(buf []byte) bool {\n\tkind, _ := Document(buf)\n\treturn kind != types.Unknown\n}\n\nfunc doMatchMap(buf []byte, machers matchers.Map) (types.Type, error) {\n\tkind := MatchMap(buf, machers)\n\tif kind != types.Unknown {\n\t\treturn kind, nil\n\t}\n\treturn kind, ErrUnknownBuffer\n}\n<commit_msg>fix(#108): add application file matchers<commit_after>package filetype\n\nimport (\n\t\"github.com\/h2non\/filetype\/matchers\"\n\t\"github.com\/h2non\/filetype\/types\"\n)\n\n\/\/ Image tries to match a file as image type\nfunc Image(buf []byte) (types.Type, error) {\n\treturn doMatchMap(buf, matchers.Image)\n}\n\n\/\/ IsImage checks if the given buffer is an image type\nfunc IsImage(buf []byte) bool {\n\tkind, _ := Image(buf)\n\treturn kind != types.Unknown\n}\n\n\/\/ Audio tries to match a file as audio type\nfunc Audio(buf []byte) (types.Type, error) {\n\treturn doMatchMap(buf, matchers.Audio)\n}\n\n\/\/ IsAudio checks if the given buffer is an audio type\nfunc IsAudio(buf []byte) bool {\n\tkind, _ := Audio(buf)\n\treturn kind != types.Unknown\n}\n\n\/\/ Video tries to match a file as video type\nfunc Video(buf []byte) (types.Type, error) {\n\treturn doMatchMap(buf, matchers.Video)\n}\n\n\/\/ IsVideo checks if the given buffer is a video type\nfunc IsVideo(buf []byte) bool {\n\tkind, _ := Video(buf)\n\treturn kind != types.Unknown\n}\n\n\/\/ Font tries to match a file as text font type\nfunc Font(buf []byte) (types.Type, error) {\n\treturn doMatchMap(buf, matchers.Font)\n}\n\n\/\/ IsFont checks if the given buffer is a font type\nfunc IsFont(buf []byte) bool {\n\tkind, _ := Font(buf)\n\treturn kind != types.Unknown\n}\n\n\/\/ Archive tries to match a file as generic archive type\nfunc Archive(buf []byte) (types.Type, error) {\n\treturn doMatchMap(buf, matchers.Archive)\n}\n\n\/\/ IsArchive checks if the given buffer is an archive type\nfunc IsArchive(buf []byte) bool {\n\tkind, _ := Archive(buf)\n\treturn kind != types.Unknown\n}\n\n\/\/ Document tries to match a file as document type\nfunc Document(buf []byte) (types.Type, error) {\n\treturn doMatchMap(buf, matchers.Document)\n}\n\n\/\/ IsDocument checks if the given buffer is an document type\nfunc IsDocument(buf []byte) bool {\n\tkind, _ := Document(buf)\n\treturn kind != types.Unknown\n}\n\n\/\/ Application tries to match a file as an application type\nfunc Application(buf []byte) (types.Type, error) {\n\treturn doMatchMap(buf, matchers.Application)\n}\n\n\/\/ IsApplication checks if the given buffer is an application type\nfunc IsApplication(buf []byte) bool {\n\tkind, _ := Application(buf)\n\treturn kind != types.Unknown\n}\n\nfunc doMatchMap(buf []byte, machers matchers.Map) (types.Type, error) {\n\tkind := MatchMap(buf, machers)\n\tif kind != types.Unknown {\n\t\treturn kind, nil\n\t}\n\treturn kind, ErrUnknownBuffer\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 by caixw, All rights reserved.\n\/\/ Use of this source code is governed by a MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage loader\n\nimport (\n\t\"github.com\/issue9\/web\"\n\n\t\"github.com\/caixw\/gitype\/helper\"\n)\n\n\/\/ 归档的类型\nconst (\n\tArchiveTypeYear  = \"year\"\n\tArchiveTypeMonth = \"month\"\n)\n\n\/\/ 归档的排序方式\nconst (\n\tArchiveOrderDesc = \"desc\"\n\tArchiveOrderAsc  = \"asc\"\n)\n\n\/\/ RSS RSS 和 Atom 相关的配置项\ntype RSS struct {\n\tTitle string `yaml:\"title\"`\n\tURL   string `yaml:\"url\"`\n\tType  string `yaml:\"type,omitempty\"`\n\tSize  int    `yaml:\"size\"` \/\/ 显示数量\n}\n\n\/\/ Opensearch opensearch 相关的配置\ntype Opensearch struct {\n\tURL   string `yaml:\"url\"`\n\tType  string `yaml:\"type,omitempty\"`\n\tTitle string `yaml:\"title,omitempty\"`\n\n\tShortName   string `yaml:\"shortName\"`\n\tDescription string `yaml:\"description\"`\n\tLongName    string `yaml:\"longName,omitempty\"`\n\tImage       *Icon  `yaml:\"image,omitempty\"`\n}\n\n\/\/ Sitemap sitemap 相关的配置\ntype Sitemap struct {\n\tURL  string `yaml:\"url\"`\n\tType string `yaml:\"type,omitempty\"`\n\n\tXslURL     string  `yaml:\"xslURL,omitempty\"`    \/\/ 为 sitemap 指定一个 xsl 文件\n\tPriority   float64 `yaml:\"priority\"`            \/\/ 默认的优先级\n\tChangefreq string  `yaml:\"changefreq\"`          \/\/ 默认的更新频率\n\tEnableTag  bool    `yaml:\"enableTag,omitempty\"` \/\/ 是否将标签相关的页面写入 sitemap\n\n\t\/\/ 文章可以指定一个专门的值\n\tPostPriority   float64 `yaml:\"postPriority\"`\n\tPostChangefreq string  `yaml:\"postChangefreq\"`\n}\n\n\/\/ Archive 存档页的配置内容\ntype Archive struct {\n\tOrder  string `yaml:\"order\"`            \/\/ 排序方式\n\tType   string `yaml:\"type,omitempty\"`   \/\/ 存档的分类方式，可以按年或是按月\n\tFormat string `yaml:\"format,omitempty\"` \/\/ 标题的格式化字符串\n}\n\n\/\/ Manifest 表示 PWA 中的相关配置\ntype Manifest struct {\n\tURL  string `yaml:\"url\"`\n\tType string `yaml:\"type,omitempty\"`\n\n\tLang        string  `yaml:\"lang\"`\n\tName        string  `yaml:\"name\"`\n\tShortName   string  `yaml:\"shortName\"`\n\tStartURL    string  `yaml:\"startURL,omitempty\"`\n\tDisplay     string  `yaml:\"display,omitempty\"`\n\tDescription string  `yaml:\"description,omitempty\"`\n\tDir         string  `yaml:\"dir,omitempty\"`\n\tOrientation string  `yaml:\"orientation,omitempty\"`\n\tScope       string  `yaml:\"scope,omitempty\"`\n\tThemeColor  string  `yaml:\"themeColor,omitempty\"`\n\tBackground  string  `yaml:\"backgroundColor,omitempty\"`\n\tIcons       []*Icon `yaml:\"icons\"`\n}\n\nfunc (rss *RSS) sanitize(conf *Config, typ string) *helper.FieldError {\n\tif rss.Size <= 0 {\n\t\treturn &helper.FieldError{Message: \"必须大于 0\", Field: typ + \".Size\"}\n\t}\n\tif len(rss.URL) == 0 {\n\t\treturn &helper.FieldError{Message: \"不能为空\", Field: typ + \".URL\"}\n\t}\n\n\tswitch typ {\n\tcase \"rss\":\n\t\trss.Type = contentTypeRSS\n\tcase \"atom\":\n\t\trss.Type = contentTypeAtom\n\tdefault:\n\t\tpanic(\"无效的 typ 值\")\n\t}\n\n\tif len(rss.Title) == 0 {\n\t\trss.Title = conf.Title\n\t}\n\n\treturn nil\n}\n\n\/\/ 检测 opensearch 取值是否正确\nfunc (s *Opensearch) sanitize(conf *Config) *helper.FieldError {\n\tswitch {\n\tcase len(s.URL) == 0:\n\t\treturn &helper.FieldError{Message: \"不能为空\", Field: \"opensearch.url\"}\n\tcase len(s.ShortName) == 0:\n\t\treturn &helper.FieldError{Message: \"不能为空\", Field: \"opensearch.shortName\"}\n\tcase len(s.Description) == 0:\n\t\treturn &helper.FieldError{Message: \"不能为空\", Field: \"opensearch.description\"}\n\t}\n\n\tif len(s.Type) == 0 {\n\t\ts.Type = contentTypeOpensearch\n\t}\n\n\tif s.Image == nil && conf.Icon != nil {\n\t\ts.Image = conf.Icon\n\t}\n\n\treturn nil\n}\n\n\/\/ 检测 sitemap 取值是否正确\nfunc (s *Sitemap) sanitize() *helper.FieldError {\n\tswitch {\n\tcase len(s.URL) == 0:\n\t\treturn &helper.FieldError{Message: \"不能为空\", Field: \"sitemap.url\"}\n\tcase s.Priority > 1 || s.Priority < 0:\n\t\treturn &helper.FieldError{Message: \"介于[0,1]之间的浮点数\", Field: \"sitemap.priority\"}\n\tcase s.PostPriority > 1 || s.PostPriority < 0:\n\t\treturn &helper.FieldError{Message: \"介于[0,1]之间的浮点数\", Field: \"sitemap.postPriority\"}\n\tcase !isChangereq(s.Changefreq):\n\t\treturn &helper.FieldError{Message: \"取值不正确\", Field: \"sitemap.changefreq\"}\n\tcase !isChangereq(s.PostChangefreq):\n\t\treturn &helper.FieldError{Message: \"取值不正确\", Field: \"sitemap.postChangefreq\"}\n\t}\n\n\tif len(s.Type) == 0 {\n\t\ts.Type = contentTypeXML\n\t}\n\n\treturn nil\n}\n\nfunc (a *Archive) sanitize() *helper.FieldError {\n\tif len(a.Type) == 0 {\n\t\ta.Type = ArchiveTypeYear\n\t} else {\n\t\tif a.Type != ArchiveTypeMonth && a.Type != ArchiveTypeYear {\n\t\t\treturn &helper.FieldError{Message: \"取值不正确\", Field: \"archive.type\"}\n\t\t}\n\t}\n\n\tif len(a.Order) == 0 {\n\t\ta.Order = ArchiveOrderDesc\n\t} else {\n\t\tif a.Order != ArchiveOrderAsc && a.Order != ArchiveOrderDesc {\n\t\t\treturn &helper.FieldError{Message: \"取值不正确\", Field: \"archive.order\"}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (m *Manifest) sanitize(conf *Config) *helper.FieldError {\n\tif m.URL == \"\" {\n\t\treturn &helper.FieldError{Message: \"不能为空\", Field: \"pwa.url\"}\n\t}\n\n\tif m.Type == \"\" {\n\t\tm.Type = contentManifest\n\t}\n\n\tif m.Lang == \"\" {\n\t\tm.Lang = conf.Language\n\t}\n\n\tif m.Name == \"\" {\n\t\tm.Name = conf.Title\n\t}\n\n\tif m.ShortName == \"\" {\n\t\tm.ShortName = conf.Subtitle\n\t}\n\n\tif m.StartURL == \"\" {\n\t\tm.StartURL = web.URL(\"\")\n\t}\n\n\tif m.Display == \"\" {\n\t\tm.Display = \"browser\"\n\t} else {\n\t\tif !inStrings(m.Display, pwaDisplays) {\n\t\t\treturn &helper.FieldError{Message: \"取值不正确\", Field: \"pwa.display\"}\n\t\t}\n\t}\n\n\tif len(m.Icons) == 0 { \/\/ nil 或是 len(m.Icons) == 0\n\t\tm.Icons = []*Icon{conf.Icon}\n\t}\n\n\treturn nil\n}\n\nvar changereqs = []string{\n\t\"never\",\n\t\"yearly\",\n\t\"monthly\",\n\t\"weekly\",\n\t\"daily\",\n\t\"hourly\",\n\t\"always\",\n}\n\nvar pwaDisplays = []string{\n\t\"fullscreen\",\n\t\"standalone\",\n\t\"minimal-ul\",\n\t\"browser\",\n}\n\nfunc isChangereq(val string) bool {\n\treturn inStrings(val, changereqs)\n}\n\nfunc inStrings(val string, vals []string) bool {\n\tfor _, v := range vals {\n\t\tif v == val {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>添加对配置项中部分枚举类型的判断<commit_after>\/\/ Copyright 2015 by caixw, All rights reserved.\n\/\/ Use of this source code is governed by a MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage loader\n\nimport (\n\t\"github.com\/issue9\/web\"\n\n\t\"github.com\/caixw\/gitype\/helper\"\n)\n\n\/\/ 归档的类型\nconst (\n\tArchiveTypeYear  = \"year\"\n\tArchiveTypeMonth = \"month\"\n)\n\n\/\/ 归档的排序方式\nconst (\n\tArchiveOrderDesc = \"desc\"\n\tArchiveOrderAsc  = \"asc\"\n)\n\n\/\/ RSS RSS 和 Atom 相关的配置项\ntype RSS struct {\n\tTitle string `yaml:\"title\"`\n\tURL   string `yaml:\"url\"`\n\tType  string `yaml:\"type,omitempty\"`\n\tSize  int    `yaml:\"size\"` \/\/ 显示数量\n}\n\n\/\/ Opensearch opensearch 相关的配置\ntype Opensearch struct {\n\tURL   string `yaml:\"url\"`\n\tType  string `yaml:\"type,omitempty\"`\n\tTitle string `yaml:\"title,omitempty\"`\n\n\tShortName   string `yaml:\"shortName\"`\n\tDescription string `yaml:\"description\"`\n\tLongName    string `yaml:\"longName,omitempty\"`\n\tImage       *Icon  `yaml:\"image,omitempty\"`\n}\n\n\/\/ Sitemap sitemap 相关的配置\ntype Sitemap struct {\n\tURL  string `yaml:\"url\"`\n\tType string `yaml:\"type,omitempty\"`\n\n\tXslURL     string  `yaml:\"xslURL,omitempty\"`    \/\/ 为 sitemap 指定一个 xsl 文件\n\tPriority   float64 `yaml:\"priority\"`            \/\/ 默认的优先级\n\tChangefreq string  `yaml:\"changefreq\"`          \/\/ 默认的更新频率\n\tEnableTag  bool    `yaml:\"enableTag,omitempty\"` \/\/ 是否将标签相关的页面写入 sitemap\n\n\t\/\/ 文章可以指定一个专门的值\n\tPostPriority   float64 `yaml:\"postPriority\"`\n\tPostChangefreq string  `yaml:\"postChangefreq\"`\n}\n\n\/\/ Archive 存档页的配置内容\ntype Archive struct {\n\tOrder  string `yaml:\"order\"`            \/\/ 排序方式\n\tType   string `yaml:\"type,omitempty\"`   \/\/ 存档的分类方式，可以按年或是按月\n\tFormat string `yaml:\"format,omitempty\"` \/\/ 标题的格式化字符串\n}\n\n\/\/ Manifest 表示 PWA 中的相关配置\ntype Manifest struct {\n\tURL  string `yaml:\"url\"`\n\tType string `yaml:\"type,omitempty\"`\n\n\tLang        string  `yaml:\"lang\"`\n\tName        string  `yaml:\"name\"`\n\tShortName   string  `yaml:\"shortName\"`\n\tStartURL    string  `yaml:\"startURL,omitempty\"`\n\tDisplay     string  `yaml:\"display,omitempty\"`\n\tDescription string  `yaml:\"description,omitempty\"`\n\tDir         string  `yaml:\"dir,omitempty\"`\n\tOrientation string  `yaml:\"orientation,omitempty\"`\n\tScope       string  `yaml:\"scope,omitempty\"`\n\tThemeColor  string  `yaml:\"themeColor,omitempty\"`\n\tBackground  string  `yaml:\"backgroundColor,omitempty\"`\n\tIcons       []*Icon `yaml:\"icons\"`\n}\n\nfunc (rss *RSS) sanitize(conf *Config, typ string) *helper.FieldError {\n\tif rss.Size <= 0 {\n\t\treturn &helper.FieldError{Message: \"必须大于 0\", Field: typ + \".Size\"}\n\t}\n\tif len(rss.URL) == 0 {\n\t\treturn &helper.FieldError{Message: \"不能为空\", Field: typ + \".URL\"}\n\t}\n\n\tswitch typ {\n\tcase \"rss\":\n\t\trss.Type = contentTypeRSS\n\tcase \"atom\":\n\t\trss.Type = contentTypeAtom\n\tdefault:\n\t\tpanic(\"无效的 typ 值\")\n\t}\n\n\tif len(rss.Title) == 0 {\n\t\trss.Title = conf.Title\n\t}\n\n\treturn nil\n}\n\n\/\/ 检测 opensearch 取值是否正确\nfunc (s *Opensearch) sanitize(conf *Config) *helper.FieldError {\n\tswitch {\n\tcase len(s.URL) == 0:\n\t\treturn &helper.FieldError{Message: \"不能为空\", Field: \"opensearch.url\"}\n\tcase len(s.ShortName) == 0:\n\t\treturn &helper.FieldError{Message: \"不能为空\", Field: \"opensearch.shortName\"}\n\tcase len(s.Description) == 0:\n\t\treturn &helper.FieldError{Message: \"不能为空\", Field: \"opensearch.description\"}\n\t}\n\n\tif len(s.Type) == 0 {\n\t\ts.Type = contentTypeOpensearch\n\t}\n\n\tif s.Image == nil && conf.Icon != nil {\n\t\ts.Image = conf.Icon\n\t}\n\n\treturn nil\n}\n\n\/\/ 检测 sitemap 取值是否正确\nfunc (s *Sitemap) sanitize() *helper.FieldError {\n\tswitch {\n\tcase len(s.URL) == 0:\n\t\treturn &helper.FieldError{Message: \"不能为空\", Field: \"sitemap.url\"}\n\tcase s.Priority > 1 || s.Priority < 0:\n\t\treturn &helper.FieldError{Message: \"介于[0,1]之间的浮点数\", Field: \"sitemap.priority\"}\n\tcase s.PostPriority > 1 || s.PostPriority < 0:\n\t\treturn &helper.FieldError{Message: \"介于[0,1]之间的浮点数\", Field: \"sitemap.postPriority\"}\n\tcase !isChangereq(s.Changefreq):\n\t\treturn &helper.FieldError{Message: \"取值不正确\", Field: \"sitemap.changefreq\"}\n\tcase !isChangereq(s.PostChangefreq):\n\t\treturn &helper.FieldError{Message: \"取值不正确\", Field: \"sitemap.postChangefreq\"}\n\t}\n\n\tif len(s.Type) == 0 {\n\t\ts.Type = contentTypeXML\n\t}\n\n\treturn nil\n}\n\nfunc (a *Archive) sanitize() *helper.FieldError {\n\tif len(a.Type) == 0 {\n\t\ta.Type = ArchiveTypeYear\n\t} else {\n\t\tif a.Type != ArchiveTypeMonth && a.Type != ArchiveTypeYear {\n\t\t\treturn &helper.FieldError{Message: \"取值不正确\", Field: \"archive.type\"}\n\t\t}\n\t}\n\n\tif len(a.Order) == 0 {\n\t\ta.Order = ArchiveOrderDesc\n\t} else {\n\t\tif a.Order != ArchiveOrderAsc && a.Order != ArchiveOrderDesc {\n\t\t\treturn &helper.FieldError{Message: \"取值不正确\", Field: \"archive.order\"}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (m *Manifest) sanitize(conf *Config) *helper.FieldError {\n\tif m.URL == \"\" {\n\t\treturn &helper.FieldError{Message: \"不能为空\", Field: \"pwa.url\"}\n\t}\n\n\tif m.Type == \"\" {\n\t\tm.Type = contentManifest\n\t}\n\n\tif m.Lang == \"\" {\n\t\tm.Lang = conf.Language\n\t}\n\n\tif m.Name == \"\" {\n\t\tm.Name = conf.Title\n\t}\n\n\tif m.ShortName == \"\" {\n\t\tm.ShortName = conf.Subtitle\n\t}\n\n\tif m.StartURL == \"\" {\n\t\tm.StartURL = web.URL(\"\")\n\t}\n\n\tif m.Display == \"\" {\n\t\tm.Display = \"browser\"\n\t} else if !inStrings(m.Display, pwaDisplays) {\n\t\treturn &helper.FieldError{Message: \"取值不正确\", Field: \"pwa.display\"}\n\t}\n\n\tif m.Dir == \"\" {\n\t\tm.Dir = \"auto\"\n\t} else if !inStrings(m.Dir, pwaDirs) {\n\t\treturn &helper.FieldError{Message: \"取值不正确\", Field: \"pwa.dir\"}\n\t}\n\n\tif m.Orientation != \"\" && !inStrings(m.Orientation, pwaOrientations) {\n\t\treturn &helper.FieldError{Message: \"取值不正确\", Field: \"pwa.orientation\"}\n\t}\n\n\tif len(m.Icons) == 0 { \/\/ nil 或是 len(m.Icons) == 0\n\t\tm.Icons = []*Icon{conf.Icon}\n\t}\n\n\treturn nil\n}\n\nvar changereqs = []string{\n\t\"never\",\n\t\"yearly\",\n\t\"monthly\",\n\t\"weekly\",\n\t\"daily\",\n\t\"hourly\",\n\t\"always\",\n}\n\nvar pwaDisplays = []string{\n\t\"fullscreen\",\n\t\"standalone\",\n\t\"minimal-ul\",\n\t\"browser\",\n}\n\nvar pwaOrientations = []string{\n\t\"any\",\n\t\"natural\",\n\t\"landscape\",\n\t\"landscape-primary\",\n\t\"landscape-secondary\",\n\t\"portrait\",\n\t\"portrait-primary\",\n\t\"portrait-secondary\",\n}\n\nvar pwaDirs = []string{\n\t\"rtl\",\n\t\"ltr\",\n\t\"auto\",\n}\n\nfunc isChangereq(val string) bool {\n\treturn inStrings(val, changereqs)\n}\n\nfunc inStrings(val string, vals []string) bool {\n\tfor _, v := range vals {\n\t\tif v == val {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package rundeck\n\nimport (\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\/\/ JobSummary is an abbreviated description of a job that includes only its basic\n\/\/ descriptive information and identifiers.\ntype JobSummary struct {\n\tXMLName     xml.Name `xml:\"job\"`\n\tID          string   `xml:\"id,attr\"`\n\tName        string   `xml:\"name\"`\n\tGroupName   string   `xml:\"group\"`\n\tProjectName string   `xml:\"project\"`\n\tDescription string   `xml:\"description,omitempty\"`\n}\n\ntype jobSummaryList struct {\n\tXMLName xml.Name     `xml:\"jobs\"`\n\tJobs    []JobSummary `xml:\"job\"`\n}\n\n\/\/ JobDetail is a comprehensive description of a job, including its entire definition.\ntype JobDetail struct {\n\tXMLName                   xml.Name            `xml:\"job\"`\n\tID                        string              `xml:\"uuid,omitempty\"`\n\tName                      string              `xml:\"name\"`\n\tGroupName                 string              `xml:\"group,omitempty\"`\n\tProjectName               string              `xml:\"context>project,omitempty\"`\n\tOptionsConfig             *JobOptions         `xml:\"context>options,omitempty\"`\n\tDescription               string              `xml:\"description,omitempty\"`\n\tLogLevel                  string              `xml:\"loglevel,omitempty\"`\n\tAllowConcurrentExecutions bool                `xml:\"multipleExecutions\"`\n\tDispatch                  *JobDispatch        `xml:\"dispatch\"`\n\tCommandSequence           *JobCommandSequence `xml:\"sequence,omitempty\"`\n\tNodeFilter                *JobNodeFilter      `xml:\"nodefilters,omitempty\"`\n}\n\ntype jobDetailList struct {\n\tXMLName xml.Name    `xml:\"joblist\"`\n\tJobs    []JobDetail `xml:\"job\"`\n}\n\n\/\/ JobOptions represents the set of options on a job, if any.\ntype JobOptions struct {\n\tPreserveOrder bool        `xml:\"preserveOrder,attr,omitempty\"`\n\tOptions       []JobOption `xml:\"option\"`\n}\n\n\/\/ JobOption represents a single option on a job.\ntype JobOption struct {\n\tXMLName                 xml.Name        `xml:\"option\"`\n\n\t\/\/ The name of the option, which can be used to interpolate its value\n\t\/\/ into job commands.\n\tName                    string          `xml:\"name,attr,omitempty\"`\n\n\t\/\/ The default value of the option.\n\tDefaultValue            string          `xml:\"value,attr,omitempty\"`\n\n\t\/\/ A sequence of predefined choices for this option. Mutually exclusive with ValueChoicesURL.\n\tValueChoices            JobValueChoices `xml:\"values,attr\"`\n\n\t\/\/ A URL from which the predefined choices for this option will be retrieved.\n\t\/\/ Mutually exclusive with ValueChoices\n\tValueChoicesURL         string          `xml:\"valuesUrl,attr,omitempty\"`\n\n\t\/\/ If set, Rundeck will reject values that are not in the set of predefined choices.\n\tRequirePredefinedChoice bool            `xml:\"enforcedvalues,attr,omitempty\"`\n\n\t\/\/ Regular expression to be used to validate the option value.\n\tValidationRegex         string          `xml:\"regex,attr,omitempty\"`\n\n\t\/\/ Description of the value to be shown in the Rundeck UI.\n\tDescription             string          `xml:\"description,omitempty\"`\n\n\t\/\/ If set, Rundeck requires a value to be set for this option.\n\tIsRequired              bool            `xml:\"required,attr,omitempty\"`\n\n\t\/\/ When either ValueChoices or ValueChoicesURL is set, controls whether more than one\n\t\/\/ choice may be selected as the value.\n\tAllowsMultipleValues    bool            `xml:\"multivalued,attr,omitempty\"`\n\n\t\/\/ If AllowsMultipleChoices is set, the string that will be used to delimit the multiple\n\t\/\/ chosen options.\n\tMultiValueDelimiter     string          `xml:\"delimeter,attr,omitempty\"`\n\n\t\/\/ If set, the input for this field will be obscured in the UI. Useful for passwords\n\t\/\/ and other secrets.\n\tObscureInput            bool            `xml:\"secure,attr,omitempty\"`\n\n\t\/\/ If set, the value can be accessed from scripts.\n\tValueIsExposedToScripts bool            `xml:\"valueExposed,attr,omitempty\"`\n}\n\n\/\/ JobValueChoices is a specialization of []string representing a sequence of predefined values\n\/\/ for a job option.\ntype JobValueChoices []string\n\n\/\/ JobCommandSequence describes the sequence of operations that a job will perform.\ntype JobCommandSequence struct {\n\tXMLName          xml.Name     `xml:\"sequence\"`\n\n\t\/\/ If set, Rundeck will continue with subsequent commands after a command fails.\n\tContinueOnError  bool         `xml:\"keepgoing,attr\"`\n\n\t\/\/ Chooses the strategy by which Rundeck will execute commands. Can either be \"node-first\" or\n\t\/\/ \"step-first\".\n\tOrderingStrategy string       `xml:\"strategy,attr,omitempty\"`\n\n\t\/\/ Sequence of commands to run in the sequence.\n\tCommands         []JobCommand `xml:\"command\"`\n}\n\n\/\/ JobCommand describes a particular command to run within the sequence of commands on a job.\n\/\/ The members of this struct are mutually-exclusive except for the pair of ScriptFile and\n\/\/ ScriptFileArgs.\ntype JobCommand struct {\n\tXMLName        xml.Name\n\n\t\/\/ A literal shell command to run.\n\tShellCommand   string            `xml:\"exec,omitempty\"`\n\n\t\/\/ An inline program to run. This will be written to disk and executed, so if it is\n\t\/\/ a shell script it should have an appropriate #! line.\n\tScript         string            `xml:\"script,omitempty\"`\n\n\t\/\/ A pre-existing file (on the target nodes) that will be executed.\n\tScriptFile     string            `xml:\"scriptfile,omitempty\"`\n\n\t\/\/ When ScriptFile is set, the arguments to provide to the script when executing it.\n\tScriptFileArgs string            `xml:\"scriptargs,omitempty\"`\n\n\t\/\/ A reference to another job to run as this command.\n\tJob            *JobCommandJobRef `xml:\"jobref\"`\n\n\t\/\/ Configuration for a step plugin to run as this command.\n\tStepPlugin     *JobPlugin        `xml:\"step-plugin\"`\n\n\t\/\/ Configuration for a node step plugin to run as this command.\n\tNodeStepPlugin *JobPlugin        `xml:\"node-step-plugin\"`\n}\n\n\/\/ JobCommandJobRef is a reference to another job that will run as one of the commands of a job.\ntype JobCommandJobRef struct {\n\tXMLName        xml.Name                  `xml:\"jobref\"`\n\tName           string                    `xml:\"name,attr\"`\n\tGroupName      string                    `xml:\"group,attr\"`\n\tRunForEachNode bool                      `xml:\"nodeStep,attr\"`\n\tArguments      JobCommandJobRefArguments `xml:\"arg\"`\n}\n\n\/\/ JobCommandJobRefArguments is a string representing the arguments in a JobCommandJobRef.\ntype JobCommandJobRefArguments string\n\n\/\/ JobPlugin is a configuration for a plugin to run within a job.\ntype JobPlugin struct {\n\tXMLName xml.Name\n\tType    string          `xml:\"type,attr\"`\n\tConfig  JobPluginConfig `xml:\"configuration\"`\n}\n\n\/\/ JobPluginConfig is a specialization of map[string]string for job plugin configuration.\ntype JobPluginConfig map[string]string\n\n\/\/ JobNodeFilter describes which nodes from the project's resource list will run the configured\n\/\/ commands.\ntype JobNodeFilter struct {\n\tExcludePrecedence bool   `xml:\"excludeprecedence\"`\n\tQuery             string `xml:\"filter,omitempty\"`\n}\n\ntype jobImportResults struct {\n\tSucceeded jobImportResultsCategory `xml:\"succeeded\"`\n\tFailed    jobImportResultsCategory `xml:\"failed\"`\n\tSkipped   jobImportResultsCategory `xml:\"skipped\"`\n}\n\ntype jobImportResultsCategory struct {\n\tCount   int               `xml:\"count,attr\"`\n\tResults []jobImportResult `xml:\"job\"`\n}\n\ntype jobImportResult struct {\n\tID          string `xml:\"id,omitempty\"`\n\tName        string `xml:\"name\"`\n\tGroupName   string `xml:\"group,omitempty\"`\n\tProjectName string `xml:\"context>project,omitempty\"`\n\tError       string `xml:\"error\"`\n}\n\ntype JobDispatch struct {\n\tMaxThreadCount  int    `xml:\"threadcount,omitempty\"`\n\tContinueOnError bool   `xml:\"keepgoing\"`\n\tRankAttribute   string `xml:\"rankAttribute,omitempty\"`\n\tRankOrder       string `xml:\"rankOrder,omitempty\"`\n}\n\n\/\/ GetJobSummariesForProject returns summaries of the jobs belonging to the named project.\nfunc (c *Client) GetJobSummariesForProject(projectName string) ([]JobSummary, error) {\n\tjobList := &jobSummaryList{}\n\terr := c.get([]string{\"project\", projectName, \"jobs\"}, nil, jobList)\n\treturn jobList.Jobs, err\n}\n\n\/\/ GetJobsForProject returns the full job details of the jobs belonging to the named project.\nfunc (c *Client) GetJobsForProject(projectName string) ([]JobDetail, error) {\n\tjobList := &jobDetailList{}\n\terr := c.get([]string{\"jobs\", \"export\"}, map[string]string{\"project\": projectName}, jobList)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jobList.Jobs, nil\n}\n\n\/\/ GetJob returns the full job details of the job with the given id.\nfunc (c *Client) GetJob(id string) (*JobDetail, error) {\n\tjobList := &jobDetailList{}\n\terr := c.get([]string{\"job\", id}, nil, jobList)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &jobList.Jobs[0], nil\n}\n\n\/\/ CreateJob creates a new job based on the provided structure.\nfunc (c *Client) CreateJob(job *JobDetail) (*JobSummary, error) {\n\treturn c.importJob(job, \"create\")\n}\n\n\/\/ CreateOrUpdateJob takes a job detail structure which has its ID set and either updates\n\/\/ an existing job with the same id or creates a new job with that id.\nfunc (c *Client) CreateOrUpdateJob(job *JobDetail) (*JobSummary, error) {\n\treturn c.importJob(job, \"update\")\n}\n\nfunc (c *Client) importJob(job *JobDetail, dupeOption string) (*JobSummary, error) {\n\tjobList := &jobDetailList{\n\t\tJobs: []JobDetail{*job},\n\t}\n\targs := map[string]string{\n\t\t\"format\":     \"xml\",\n\t\t\"dupeOption\": dupeOption,\n\t\t\"uuidOption\": \"preserve\",\n\t}\n\tresult := &jobImportResults{}\n\terr := c.postXMLBatch([]string{\"jobs\", \"import\"}, args, jobList, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif result.Failed.Count > 0 {\n\t\terrMsg := result.Failed.Results[0].Error\n\t\treturn nil, fmt.Errorf(errMsg)\n\t}\n\n\tif result.Succeeded.Count != 1 {\n\t\t\/\/ Should never happen, since we send nothing in the request\n\t\t\/\/ that should cause a job to be skipped.\n\t\treturn nil, fmt.Errorf(\"job was skipped\")\n\t}\n\n\treturn result.Succeeded.Results[0].JobSummary(), nil\n}\n\n\/\/ DeleteJob deletes the job with the given id.\nfunc (c *Client) DeleteJob(id string) error {\n\treturn c.delete([]string{\"job\", id})\n}\n\nfunc (c JobValueChoices) MarshalXMLAttr(name xml.Name) (xml.Attr, error) {\n\tif len(c) > 0 {\n\t\treturn xml.Attr{name, strings.Join(c, \",\")}, nil\n\t} else {\n\t\treturn xml.Attr{}, nil\n\t}\n}\n\nfunc (c *JobValueChoices) UnmarshalXMLAttr(attr xml.Attr) error {\n\tvalues := strings.Split(attr.Value, \",\")\n\t*c = values\n\treturn nil\n}\n\nfunc (a JobCommandJobRefArguments) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tstart.Attr = []xml.Attr{\n\t\txml.Attr{xml.Name{Local: \"line\"}, string(a)},\n\t}\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{start.Name})\n\treturn nil\n}\n\nfunc (a *JobCommandJobRefArguments) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\ttype jobRefArgs struct {\n\t\tLine string `xml:\"line,attr\"`\n\t}\n\targs := jobRefArgs{}\n\td.DecodeElement(&args, &start)\n\n\t*a = JobCommandJobRefArguments(args.Line)\n\n\treturn nil\n}\n\nfunc (c JobPluginConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\trc := map[string]string(c)\n\treturn marshalMapToXML(&rc, e, start, \"entry\", \"key\", \"value\")\n}\n\nfunc (c *JobPluginConfig) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\trc := (*map[string]string)(c)\n\treturn unmarshalMapFromXML(rc, d, start, \"entry\", \"key\", \"value\")\n}\n\n\/\/ JobSummary produces a JobSummary instance with values populated from the import result.\n\/\/ The summary object won't have its Description populated, since import results do not\n\/\/ include descriptions.\nfunc (r *jobImportResult) JobSummary() *JobSummary {\n\treturn &JobSummary{\n\t\tID:          r.ID,\n\t\tName:        r.Name,\n\t\tGroupName:   r.GroupName,\n\t\tProjectName: r.ProjectName,\n\t}\n}\n<commit_msg>gofmt<commit_after>package rundeck\n\nimport (\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\/\/ JobSummary is an abbreviated description of a job that includes only its basic\n\/\/ descriptive information and identifiers.\ntype JobSummary struct {\n\tXMLName     xml.Name `xml:\"job\"`\n\tID          string   `xml:\"id,attr\"`\n\tName        string   `xml:\"name\"`\n\tGroupName   string   `xml:\"group\"`\n\tProjectName string   `xml:\"project\"`\n\tDescription string   `xml:\"description,omitempty\"`\n}\n\ntype jobSummaryList struct {\n\tXMLName xml.Name     `xml:\"jobs\"`\n\tJobs    []JobSummary `xml:\"job\"`\n}\n\n\/\/ JobDetail is a comprehensive description of a job, including its entire definition.\ntype JobDetail struct {\n\tXMLName                   xml.Name            `xml:\"job\"`\n\tID                        string              `xml:\"uuid,omitempty\"`\n\tName                      string              `xml:\"name\"`\n\tGroupName                 string              `xml:\"group,omitempty\"`\n\tProjectName               string              `xml:\"context>project,omitempty\"`\n\tOptionsConfig             *JobOptions         `xml:\"context>options,omitempty\"`\n\tDescription               string              `xml:\"description,omitempty\"`\n\tLogLevel                  string              `xml:\"loglevel,omitempty\"`\n\tAllowConcurrentExecutions bool                `xml:\"multipleExecutions\"`\n\tDispatch                  *JobDispatch        `xml:\"dispatch\"`\n\tCommandSequence           *JobCommandSequence `xml:\"sequence,omitempty\"`\n\tNodeFilter                *JobNodeFilter      `xml:\"nodefilters,omitempty\"`\n}\n\ntype jobDetailList struct {\n\tXMLName xml.Name    `xml:\"joblist\"`\n\tJobs    []JobDetail `xml:\"job\"`\n}\n\n\/\/ JobOptions represents the set of options on a job, if any.\ntype JobOptions struct {\n\tPreserveOrder bool        `xml:\"preserveOrder,attr,omitempty\"`\n\tOptions       []JobOption `xml:\"option\"`\n}\n\n\/\/ JobOption represents a single option on a job.\ntype JobOption struct {\n\tXMLName xml.Name `xml:\"option\"`\n\n\t\/\/ The name of the option, which can be used to interpolate its value\n\t\/\/ into job commands.\n\tName string `xml:\"name,attr,omitempty\"`\n\n\t\/\/ The default value of the option.\n\tDefaultValue string `xml:\"value,attr,omitempty\"`\n\n\t\/\/ A sequence of predefined choices for this option. Mutually exclusive with ValueChoicesURL.\n\tValueChoices JobValueChoices `xml:\"values,attr\"`\n\n\t\/\/ A URL from which the predefined choices for this option will be retrieved.\n\t\/\/ Mutually exclusive with ValueChoices\n\tValueChoicesURL string `xml:\"valuesUrl,attr,omitempty\"`\n\n\t\/\/ If set, Rundeck will reject values that are not in the set of predefined choices.\n\tRequirePredefinedChoice bool `xml:\"enforcedvalues,attr,omitempty\"`\n\n\t\/\/ Regular expression to be used to validate the option value.\n\tValidationRegex string `xml:\"regex,attr,omitempty\"`\n\n\t\/\/ Description of the value to be shown in the Rundeck UI.\n\tDescription string `xml:\"description,omitempty\"`\n\n\t\/\/ If set, Rundeck requires a value to be set for this option.\n\tIsRequired bool `xml:\"required,attr,omitempty\"`\n\n\t\/\/ When either ValueChoices or ValueChoicesURL is set, controls whether more than one\n\t\/\/ choice may be selected as the value.\n\tAllowsMultipleValues bool `xml:\"multivalued,attr,omitempty\"`\n\n\t\/\/ If AllowsMultipleChoices is set, the string that will be used to delimit the multiple\n\t\/\/ chosen options.\n\tMultiValueDelimiter string `xml:\"delimeter,attr,omitempty\"`\n\n\t\/\/ If set, the input for this field will be obscured in the UI. Useful for passwords\n\t\/\/ and other secrets.\n\tObscureInput bool `xml:\"secure,attr,omitempty\"`\n\n\t\/\/ If set, the value can be accessed from scripts.\n\tValueIsExposedToScripts bool `xml:\"valueExposed,attr,omitempty\"`\n}\n\n\/\/ JobValueChoices is a specialization of []string representing a sequence of predefined values\n\/\/ for a job option.\ntype JobValueChoices []string\n\n\/\/ JobCommandSequence describes the sequence of operations that a job will perform.\ntype JobCommandSequence struct {\n\tXMLName xml.Name `xml:\"sequence\"`\n\n\t\/\/ If set, Rundeck will continue with subsequent commands after a command fails.\n\tContinueOnError bool `xml:\"keepgoing,attr\"`\n\n\t\/\/ Chooses the strategy by which Rundeck will execute commands. Can either be \"node-first\" or\n\t\/\/ \"step-first\".\n\tOrderingStrategy string `xml:\"strategy,attr,omitempty\"`\n\n\t\/\/ Sequence of commands to run in the sequence.\n\tCommands []JobCommand `xml:\"command\"`\n}\n\n\/\/ JobCommand describes a particular command to run within the sequence of commands on a job.\n\/\/ The members of this struct are mutually-exclusive except for the pair of ScriptFile and\n\/\/ ScriptFileArgs.\ntype JobCommand struct {\n\tXMLName xml.Name\n\n\t\/\/ A literal shell command to run.\n\tShellCommand string `xml:\"exec,omitempty\"`\n\n\t\/\/ An inline program to run. This will be written to disk and executed, so if it is\n\t\/\/ a shell script it should have an appropriate #! line.\n\tScript string `xml:\"script,omitempty\"`\n\n\t\/\/ A pre-existing file (on the target nodes) that will be executed.\n\tScriptFile string `xml:\"scriptfile,omitempty\"`\n\n\t\/\/ When ScriptFile is set, the arguments to provide to the script when executing it.\n\tScriptFileArgs string `xml:\"scriptargs,omitempty\"`\n\n\t\/\/ A reference to another job to run as this command.\n\tJob *JobCommandJobRef `xml:\"jobref\"`\n\n\t\/\/ Configuration for a step plugin to run as this command.\n\tStepPlugin *JobPlugin `xml:\"step-plugin\"`\n\n\t\/\/ Configuration for a node step plugin to run as this command.\n\tNodeStepPlugin *JobPlugin `xml:\"node-step-plugin\"`\n}\n\n\/\/ JobCommandJobRef is a reference to another job that will run as one of the commands of a job.\ntype JobCommandJobRef struct {\n\tXMLName        xml.Name                  `xml:\"jobref\"`\n\tName           string                    `xml:\"name,attr\"`\n\tGroupName      string                    `xml:\"group,attr\"`\n\tRunForEachNode bool                      `xml:\"nodeStep,attr\"`\n\tArguments      JobCommandJobRefArguments `xml:\"arg\"`\n}\n\n\/\/ JobCommandJobRefArguments is a string representing the arguments in a JobCommandJobRef.\ntype JobCommandJobRefArguments string\n\n\/\/ JobPlugin is a configuration for a plugin to run within a job.\ntype JobPlugin struct {\n\tXMLName xml.Name\n\tType    string          `xml:\"type,attr\"`\n\tConfig  JobPluginConfig `xml:\"configuration\"`\n}\n\n\/\/ JobPluginConfig is a specialization of map[string]string for job plugin configuration.\ntype JobPluginConfig map[string]string\n\n\/\/ JobNodeFilter describes which nodes from the project's resource list will run the configured\n\/\/ commands.\ntype JobNodeFilter struct {\n\tExcludePrecedence bool   `xml:\"excludeprecedence\"`\n\tQuery             string `xml:\"filter,omitempty\"`\n}\n\ntype jobImportResults struct {\n\tSucceeded jobImportResultsCategory `xml:\"succeeded\"`\n\tFailed    jobImportResultsCategory `xml:\"failed\"`\n\tSkipped   jobImportResultsCategory `xml:\"skipped\"`\n}\n\ntype jobImportResultsCategory struct {\n\tCount   int               `xml:\"count,attr\"`\n\tResults []jobImportResult `xml:\"job\"`\n}\n\ntype jobImportResult struct {\n\tID          string `xml:\"id,omitempty\"`\n\tName        string `xml:\"name\"`\n\tGroupName   string `xml:\"group,omitempty\"`\n\tProjectName string `xml:\"context>project,omitempty\"`\n\tError       string `xml:\"error\"`\n}\n\ntype JobDispatch struct {\n\tMaxThreadCount  int    `xml:\"threadcount,omitempty\"`\n\tContinueOnError bool   `xml:\"keepgoing\"`\n\tRankAttribute   string `xml:\"rankAttribute,omitempty\"`\n\tRankOrder       string `xml:\"rankOrder,omitempty\"`\n}\n\n\/\/ GetJobSummariesForProject returns summaries of the jobs belonging to the named project.\nfunc (c *Client) GetJobSummariesForProject(projectName string) ([]JobSummary, error) {\n\tjobList := &jobSummaryList{}\n\terr := c.get([]string{\"project\", projectName, \"jobs\"}, nil, jobList)\n\treturn jobList.Jobs, err\n}\n\n\/\/ GetJobsForProject returns the full job details of the jobs belonging to the named project.\nfunc (c *Client) GetJobsForProject(projectName string) ([]JobDetail, error) {\n\tjobList := &jobDetailList{}\n\terr := c.get([]string{\"jobs\", \"export\"}, map[string]string{\"project\": projectName}, jobList)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn jobList.Jobs, nil\n}\n\n\/\/ GetJob returns the full job details of the job with the given id.\nfunc (c *Client) GetJob(id string) (*JobDetail, error) {\n\tjobList := &jobDetailList{}\n\terr := c.get([]string{\"job\", id}, nil, jobList)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &jobList.Jobs[0], nil\n}\n\n\/\/ CreateJob creates a new job based on the provided structure.\nfunc (c *Client) CreateJob(job *JobDetail) (*JobSummary, error) {\n\treturn c.importJob(job, \"create\")\n}\n\n\/\/ CreateOrUpdateJob takes a job detail structure which has its ID set and either updates\n\/\/ an existing job with the same id or creates a new job with that id.\nfunc (c *Client) CreateOrUpdateJob(job *JobDetail) (*JobSummary, error) {\n\treturn c.importJob(job, \"update\")\n}\n\nfunc (c *Client) importJob(job *JobDetail, dupeOption string) (*JobSummary, error) {\n\tjobList := &jobDetailList{\n\t\tJobs: []JobDetail{*job},\n\t}\n\targs := map[string]string{\n\t\t\"format\":     \"xml\",\n\t\t\"dupeOption\": dupeOption,\n\t\t\"uuidOption\": \"preserve\",\n\t}\n\tresult := &jobImportResults{}\n\terr := c.postXMLBatch([]string{\"jobs\", \"import\"}, args, jobList, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif result.Failed.Count > 0 {\n\t\terrMsg := result.Failed.Results[0].Error\n\t\treturn nil, fmt.Errorf(errMsg)\n\t}\n\n\tif result.Succeeded.Count != 1 {\n\t\t\/\/ Should never happen, since we send nothing in the request\n\t\t\/\/ that should cause a job to be skipped.\n\t\treturn nil, fmt.Errorf(\"job was skipped\")\n\t}\n\n\treturn result.Succeeded.Results[0].JobSummary(), nil\n}\n\n\/\/ DeleteJob deletes the job with the given id.\nfunc (c *Client) DeleteJob(id string) error {\n\treturn c.delete([]string{\"job\", id})\n}\n\nfunc (c JobValueChoices) MarshalXMLAttr(name xml.Name) (xml.Attr, error) {\n\tif len(c) > 0 {\n\t\treturn xml.Attr{name, strings.Join(c, \",\")}, nil\n\t} else {\n\t\treturn xml.Attr{}, nil\n\t}\n}\n\nfunc (c *JobValueChoices) UnmarshalXMLAttr(attr xml.Attr) error {\n\tvalues := strings.Split(attr.Value, \",\")\n\t*c = values\n\treturn nil\n}\n\nfunc (a JobCommandJobRefArguments) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\tstart.Attr = []xml.Attr{\n\t\txml.Attr{xml.Name{Local: \"line\"}, string(a)},\n\t}\n\te.EncodeToken(start)\n\te.EncodeToken(xml.EndElement{start.Name})\n\treturn nil\n}\n\nfunc (a *JobCommandJobRefArguments) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\ttype jobRefArgs struct {\n\t\tLine string `xml:\"line,attr\"`\n\t}\n\targs := jobRefArgs{}\n\td.DecodeElement(&args, &start)\n\n\t*a = JobCommandJobRefArguments(args.Line)\n\n\treturn nil\n}\n\nfunc (c JobPluginConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {\n\trc := map[string]string(c)\n\treturn marshalMapToXML(&rc, e, start, \"entry\", \"key\", \"value\")\n}\n\nfunc (c *JobPluginConfig) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {\n\trc := (*map[string]string)(c)\n\treturn unmarshalMapFromXML(rc, d, start, \"entry\", \"key\", \"value\")\n}\n\n\/\/ JobSummary produces a JobSummary instance with values populated from the import result.\n\/\/ The summary object won't have its Description populated, since import results do not\n\/\/ include descriptions.\nfunc (r *jobImportResult) JobSummary() *JobSummary {\n\treturn &JobSummary{\n\t\tID:          r.ID,\n\t\tName:        r.Name,\n\t\tGroupName:   r.GroupName,\n\t\tProjectName: r.ProjectName,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package blobs_test\n\nimport (\n\t\"fmt\"\n\t\"github.com\/xercoy\/blobs\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n)\n\nvar (\n\ttempDir = os.TempDir()\n)\n\nfunc TestCreateRandomAmount(t *testing.T) {\n\tlog.Println(\"\\n\\nStarting TestCreateRandomAmount...\")\n\n\tcontentSrc := strings.NewReader(\"icecream\")\n\n\ttestRunner := blobs.NewRunner(contentSrc, tempDir, \"1MB\", \"%d.dat\", 15, true)\n\n\terr := blobs.Mk(testRunner)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n}\n\nfunc TestNewRunner(t *testing.T) {\n\tlog.Println(\"\\n\\nStarting TestNewRunner...\")\n\n\ttestReader := strings.NewReader(\"foobarbaz\")\n\ttestRunner := blobs.NewRunner(testReader, tempDir, \"2MB\", \"%d.dat\", 3, false)\n\n\tfmtString := \"Given Runner field %s not equal to the given test value.\"\n\tvar value string\n\n\t\/\/Read from the Src field\n\trdrContent, err := ioutil.ReadAll(testRunner.Src)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tif testRunner.Amount != 3 {\n\t\tvalue = \"Amount\"\n\t\tt.Errorf(fmtString, value)\n\n\t} else if testRunner.Unit != \"2MB\" {\n\t\tvalue = \"Unit\"\n\t\tt.Errorf(fmtString, value)\n\n\t} else if testRunner.Dest != tempDir {\n\t\tvalue = \"Dest\"\n\t\tt.Errorf(fmtString, value)\n\n\t} else if testRunner.FormatStr != \"%d.dat\" {\n\t\tvalue = \"FormatStr\"\n\t\tt.Errorf(fmtString, value)\n\n\t} else if (string)(rdrContent) != \"foobarbaz\" {\n\t\tvalue = \"Src\"\n\t\tt.Errorf(fmtString, value)\n\t}\n}\n\nfunc TestMk(t *testing.T) {\n\tlog.Println(\"\\n\\nStarting TestMk...\")\n\n\ttestReader := strings.NewReader(\"helloWorld\")\n\ttestRunner := blobs.NewRunner(testReader, tempDir, \"2MB\", \"%d.dat\", 5, false)\n\n\terr := blobs.Mk(testRunner)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t\/\/ Doesn't work for some reason:\n\t\/\/ wildcardStr := strings.Replace(testRunner.FormatStr, \"%d\", \"*\", -1)\n\t\/\/ Iterate through and ls each file for now...\n\tfor i := 1; i <= testRunner.Amount; i++ {\n\t\tfileName := fmt.Sprintf(testRunner.FormatStr, i)\n\n\t\tblobFilter := filepath.Join(os.TempDir(), fileName)\n\n\t\tcmd := exec.Command(\"ls\", \"-l\", blobFilter)\n\t\tcmdOutput, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tt.Error(err.Error())\n\t\t}\n\n\t\tlog.Printf(\"%s\", cmdOutput)\n\t}\n}\n<commit_msg>Modidied runner tests to use blobs directly.<commit_after>package blobs\n\nimport (\n\t\"fmt\"\n\n\t\/\/\t\"github.com\/xercoy\/blobs\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n)\n\nvar (\n\ttempDir = os.TempDir()\n)\n\nfunc TestCreateRandomAmount(t *testing.T) {\n\tlog.Println(\"\\n\\nStarting TestCreateRandomAmount...\")\n\n\tcontentSrc := strings.NewReader(\"icecream\")\n\n\ttestRunner := NewRunner(contentSrc, tempDir, \"1MB\", \"%d.dat\", 15, true)\n\n\terr := Mk(testRunner)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n}\n\nfunc TestNewRunner(t *testing.T) {\n\tlog.Println(\"\\n\\nStarting TestNewRunner...\")\n\n\ttestReader := strings.NewReader(\"foobarbaz\")\n\ttestRunner := NewRunner(testReader, tempDir, \"2MB\", \"%d.dat\", 3, false)\n\n\tfmtString := \"Given Runner field %s not equal to the given test value.\"\n\tvar value string\n\n\t\/\/Read from the Src field\n\trdrContent, err := ioutil.ReadAll(testRunner.Src)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tif testRunner.Amount != 3 {\n\t\tvalue = \"Amount\"\n\t\tt.Errorf(fmtString, value)\n\n\t} else if testRunner.Unit != \"2MB\" {\n\t\tvalue = \"Unit\"\n\t\tt.Errorf(fmtString, value)\n\n\t} else if testRunner.Dest != tempDir {\n\t\tvalue = \"Dest\"\n\t\tt.Errorf(fmtString, value)\n\n\t} else if testRunner.FormatStr != \"%d.dat\" {\n\t\tvalue = \"FormatStr\"\n\t\tt.Errorf(fmtString, value)\n\n\t} else if (string)(rdrContent) != \"foobarbaz\" {\n\t\tvalue = \"Src\"\n\t\tt.Errorf(fmtString, value)\n\t}\n}\n\nfunc TestMk(t *testing.T) {\n\tlog.Println(\"\\n\\nStarting TestMk...\")\n\n\ttestReader := strings.NewReader(\"helloWorld\")\n\ttestRunner := NewRunner(testReader, tempDir, \"2MB\", \"%d.dat\", 5, false)\n\n\terr := Mk(testRunner)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\t\/\/ Doesn't work for some reason:\n\t\/\/ wildcardStr := strings.Replace(testRunner.FormatStr, \"%d\", \"*\", -1)\n\t\/\/ Iterate through and ls each file for now...\n\tfor i := 1; i <= testRunner.Amount; i++ {\n\t\tfileName := fmt.Sprintf(testRunner.FormatStr, i)\n\n\t\tblobFilter := filepath.Join(os.TempDir(), fileName)\n\n\t\tcmd := exec.Command(\"ls\", \"-l\", blobFilter)\n\t\tcmdOutput, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tt.Error(err.Error())\n\t\t}\n\n\t\tlog.Printf(\"%s\", cmdOutput)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2021 The Matrix.org Foundation C.I.C.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package msc2946 'Spaces Summary' implements https:\/\/github.com\/matrix-org\/matrix-doc\/pull\/2946\npackage msc2946\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"sync\"\n\n\t\"github.com\/gorilla\/mux\"\n\tchttputil \"github.com\/matrix-org\/dendrite\/clientapi\/httputil\"\n\t\"github.com\/matrix-org\/dendrite\/internal\/hooks\"\n\t\"github.com\/matrix-org\/dendrite\/internal\/httputil\"\n\troomserver \"github.com\/matrix-org\/dendrite\/roomserver\/api\"\n\t\"github.com\/matrix-org\/dendrite\/setup\"\n\tuserapi \"github.com\/matrix-org\/dendrite\/userapi\/api\"\n\t\"github.com\/matrix-org\/gomatrixserverlib\"\n\t\"github.com\/matrix-org\/util\"\n\t\"github.com\/tidwall\/gjson\"\n)\n\nconst (\n\tConstCreateEventContentKey = \"org.matrix.msc1772.type\"\n\tConstSpaceChildEventType   = \"org.matrix.msc1772.space.child\"\n\tConstSpaceParentEventType  = \"org.matrix.msc1772.room.parent\"\n)\n\n\/\/ SpacesRequest is the request body to POST \/_matrix\/client\/r0\/rooms\/{roomID}\/spaces\ntype SpacesRequest struct {\n\tMaxRoomsPerSpace int    `json:\"max_rooms_per_space\"`\n\tLimit            int    `json:\"limit\"`\n\tBatch            string `json:\"batch\"`\n}\n\n\/\/ Defaults sets the request defaults\nfunc (r *SpacesRequest) Defaults() {\n\tr.Limit = 100\n\tr.MaxRoomsPerSpace = -1\n}\n\n\/\/ SpacesResponse is the response body to POST \/_matrix\/client\/r0\/rooms\/{roomID}\/spaces\ntype SpacesResponse struct {\n\tNextBatch string `json:\"next_batch\"`\n\t\/\/ Rooms are nodes on the space graph.\n\tRooms []Room `json:\"rooms\"`\n\t\/\/ Events are edges on the space graph, exclusively m.space.child or m.room.parent events\n\tEvents []gomatrixserverlib.ClientEvent `json:\"events\"`\n}\n\n\/\/ Room is a node on the space graph\ntype Room struct {\n\tgomatrixserverlib.PublicRoom\n\tNumRefs  int    `json:\"num_refs\"`\n\tRoomType string `json:\"room_type\"`\n}\n\n\/\/ Enable this MSC\nfunc Enable(\n\tbase *setup.BaseDendrite, rsAPI roomserver.RoomserverInternalAPI, userAPI userapi.UserInternalAPI,\n) error {\n\tdb, err := NewDatabase(&base.Cfg.MSCs.Database)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot enable MSC2946: %w\", err)\n\t}\n\thooks.Enable()\n\thooks.Attach(hooks.KindNewEventPersisted, func(headeredEvent interface{}) {\n\t\the := headeredEvent.(*gomatrixserverlib.HeaderedEvent)\n\t\thookErr := db.StoreReference(context.Background(), he)\n\t\tif hookErr != nil {\n\t\t\tutil.GetLogger(context.Background()).WithError(hookErr).WithField(\"event_id\", he.EventID()).Error(\n\t\t\t\t\"failed to StoreReference\",\n\t\t\t)\n\t\t}\n\t})\n\n\tbase.PublicClientAPIMux.Handle(\"\/unstable\/rooms\/{roomID}\/spaces\",\n\t\thttputil.MakeAuthAPI(\"spaces\", userAPI, spacesHandler(db, rsAPI)),\n\t).Methods(http.MethodPost, http.MethodOptions)\n\treturn nil\n}\n\nfunc spacesHandler(db Database, rsAPI roomserver.RoomserverInternalAPI) func(*http.Request, *userapi.Device) util.JSONResponse {\n\tinMemoryBatchCache := make(map[string]set)\n\treturn func(req *http.Request, device *userapi.Device) util.JSONResponse {\n\t\t\/\/ Extract the room ID from the request. Sanity check request data.\n\t\tparams, err := httputil.URLDecodeMapValues(mux.Vars(req))\n\t\tif err != nil {\n\t\t\treturn util.ErrorResponse(err)\n\t\t}\n\t\troomID := params[\"roomID\"]\n\t\tvar r SpacesRequest\n\t\tr.Defaults()\n\t\tif resErr := chttputil.UnmarshalJSONRequest(req, &r); resErr != nil {\n\t\t\treturn *resErr\n\t\t}\n\t\tif r.Limit > 100 {\n\t\t\tr.Limit = 100\n\t\t}\n\t\tw := walker{\n\t\t\treq:        &r,\n\t\t\trootRoomID: roomID,\n\t\t\tcaller:     device,\n\t\t\tctx:        req.Context(),\n\n\t\t\tdb:                 db,\n\t\t\trsAPI:              rsAPI,\n\t\t\tinMemoryBatchCache: inMemoryBatchCache,\n\t\t}\n\t\tres := w.walk()\n\t\treturn util.JSONResponse{\n\t\t\tCode: 200,\n\t\t\tJSON: res,\n\t\t}\n\t}\n}\n\ntype walker struct {\n\treq        *SpacesRequest\n\trootRoomID string\n\tcaller     *userapi.Device\n\tdb         Database\n\trsAPI      roomserver.RoomserverInternalAPI\n\tctx        context.Context\n\n\t\/\/ user ID|device ID|batch_num => event\/room IDs sent to client\n\tinMemoryBatchCache map[string]set\n\tmu                 sync.Mutex\n}\n\nfunc (w *walker) alreadySent(id string) bool {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\tm, ok := w.inMemoryBatchCache[w.caller.UserID+\"|\"+w.caller.ID]\n\tif !ok {\n\t\treturn false\n\t}\n\treturn m[id]\n}\n\nfunc (w *walker) markSent(id string) {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\tm := w.inMemoryBatchCache[w.caller.UserID+\"|\"+w.caller.ID]\n\tif m == nil {\n\t\tm = make(set)\n\t}\n\tm[id] = true\n\tw.inMemoryBatchCache[w.caller.UserID+\"|\"+w.caller.ID] = m\n}\n\n\/\/ nolint:gocyclo\nfunc (w *walker) walk() *SpacesResponse {\n\tvar res SpacesResponse\n\t\/\/ Begin walking the graph starting with the room ID in the request in a queue of unvisited rooms\n\tunvisited := []string{w.rootRoomID}\n\tprocessed := make(set)\n\tfor len(unvisited) > 0 {\n\t\troomID := unvisited[0]\n\t\tunvisited = unvisited[1:]\n\t\t\/\/ If this room has already been processed, skip. NB: do not remember this between calls\n\t\tif processed[roomID] || roomID == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Mark this room as processed.\n\t\tprocessed[roomID] = true\n\t\t\/\/ Is the caller currently joined to the room or is the room `world_readable`\n\t\t\/\/ If no, skip this room. If yes, continue.\n\t\tif !w.authorised(roomID) {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Get all `m.space.child` and `m.room.parent` state events for the room. *In addition*, get\n\t\t\/\/ all `m.space.child` and `m.room.parent` state events which *point to* (via `state_key` or `content.room_id`)\n\t\t\/\/ this room. This requires servers to store reverse lookups.\n\t\trefs, err := w.references(roomID)\n\t\tif err != nil {\n\t\t\tutil.GetLogger(w.ctx).WithError(err).WithField(\"room_id\", roomID).Error(\"failed to extract references for room\")\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ If this room has not ever been in `rooms` (across multiple requests), extract the\n\t\t\/\/ `PublicRoomsChunk` for this room.\n\t\tif !w.alreadySent(roomID) {\n\t\t\tpubRoom := w.publicRoomsChunk(roomID)\n\t\t\troomType := \"\"\n\t\t\tcreate := w.stateEvent(roomID, \"m.room.create\", \"\")\n\t\t\tif create != nil {\n\t\t\t\troomType = gjson.GetBytes(create.Content(), ConstCreateEventContentKey).Str\n\t\t\t}\n\n\t\t\t\/\/ Add the total number of events to `PublicRoomsChunk` under `num_refs`. Add `PublicRoomsChunk` to `rooms`.\n\t\t\tres.Rooms = append(res.Rooms, Room{\n\t\t\t\tPublicRoom: *pubRoom,\n\t\t\t\tNumRefs:    refs.len(),\n\t\t\t\tRoomType:   roomType,\n\t\t\t})\n\t\t}\n\n\t\tuniqueRooms := make(set)\n\n\t\t\/\/ If this is the root room from the original request, insert all these events into `events` if\n\t\t\/\/ they haven't been added before (across multiple requests).\n\t\tif w.rootRoomID == roomID {\n\t\t\tfor _, ev := range refs.events() {\n\t\t\t\tif !w.alreadySent(ev.EventID()) {\n\t\t\t\t\tres.Events = append(res.Events, gomatrixserverlib.HeaderedToClientEvent(\n\t\t\t\t\t\tev, gomatrixserverlib.FormatAll,\n\t\t\t\t\t))\n\t\t\t\t\tuniqueRooms[ev.RoomID()] = true\n\t\t\t\t\tuniqueRooms[SpaceTarget(ev)] = true\n\t\t\t\t\tw.markSent(ev.EventID())\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Else add them to `events` honouring the `limit` and `max_rooms_per_space` values. If either\n\t\t\t\/\/ are exceeded, stop adding events. If the event has already been added, do not add it again.\n\t\t\tnumAdded := 0\n\t\t\tfor _, ev := range refs.events() {\n\t\t\t\tif w.req.Limit > 0 && len(res.Events) >= w.req.Limit {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif w.req.MaxRoomsPerSpace > 0 && numAdded >= w.req.MaxRoomsPerSpace {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif w.alreadySent(ev.EventID()) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tres.Events = append(res.Events, gomatrixserverlib.HeaderedToClientEvent(\n\t\t\t\t\tev, gomatrixserverlib.FormatAll,\n\t\t\t\t))\n\t\t\t\tuniqueRooms[ev.RoomID()] = true\n\t\t\t\tuniqueRooms[SpaceTarget(ev)] = true\n\t\t\t\tw.markSent(ev.EventID())\n\t\t\t\t\/\/ we don't distinguish between child state events and parent state events for the purposes of\n\t\t\t\t\/\/ max_rooms_per_space, maybe we should?\n\t\t\t\tnumAdded++\n\t\t\t}\n\t\t}\n\n\t\t\/\/ For each referenced room ID in the events being returned to the caller (both parent and child)\n\t\t\/\/ add the room ID to the queue of unvisited rooms. Loop from the beginning.\n\t\tfor roomID := range uniqueRooms {\n\t\t\tunvisited = append(unvisited, roomID)\n\t\t}\n\t}\n\treturn &res\n}\n\nfunc (w *walker) stateEvent(roomID, evType, stateKey string) *gomatrixserverlib.HeaderedEvent {\n\tvar queryRes roomserver.QueryCurrentStateResponse\n\ttuple := gomatrixserverlib.StateKeyTuple{\n\t\tEventType: evType,\n\t\tStateKey:  stateKey,\n\t}\n\terr := w.rsAPI.QueryCurrentState(w.ctx, &roomserver.QueryCurrentStateRequest{\n\t\tRoomID:      roomID,\n\t\tStateTuples: []gomatrixserverlib.StateKeyTuple{tuple},\n\t}, &queryRes)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn queryRes.StateEvents[tuple]\n}\n\nfunc (w *walker) publicRoomsChunk(roomID string) *gomatrixserverlib.PublicRoom {\n\tpubRooms, err := roomserver.PopulatePublicRooms(w.ctx, []string{roomID}, w.rsAPI)\n\tif err != nil {\n\t\tutil.GetLogger(w.ctx).WithError(err).Error(\"failed to PopulatePublicRooms\")\n\t\treturn nil\n\t}\n\tif len(pubRooms) == 0 {\n\t\treturn nil\n\t}\n\treturn &pubRooms[0]\n}\n\n\/\/ authorised returns true iff the user is joined this room or the room is world_readable\nfunc (w *walker) authorised(roomID string) bool {\n\thisVisTuple := gomatrixserverlib.StateKeyTuple{\n\t\tEventType: gomatrixserverlib.MRoomHistoryVisibility,\n\t\tStateKey:  \"\",\n\t}\n\troomMemberTuple := gomatrixserverlib.StateKeyTuple{\n\t\tEventType: gomatrixserverlib.MRoomMember,\n\t\tStateKey:  w.caller.UserID,\n\t}\n\tvar queryRes roomserver.QueryCurrentStateResponse\n\terr := w.rsAPI.QueryCurrentState(w.ctx, &roomserver.QueryCurrentStateRequest{\n\t\tRoomID: roomID,\n\t\tStateTuples: []gomatrixserverlib.StateKeyTuple{\n\t\t\thisVisTuple, roomMemberTuple,\n\t\t},\n\t}, &queryRes)\n\tif err != nil {\n\t\tutil.GetLogger(w.ctx).WithError(err).Error(\"failed to QueryCurrentState\")\n\t\treturn false\n\t}\n\tmemberEv := queryRes.StateEvents[roomMemberTuple]\n\thisVisEv := queryRes.StateEvents[hisVisTuple]\n\tif memberEv != nil {\n\t\tmembership, _ := memberEv.Membership()\n\t\tif membership == gomatrixserverlib.Join {\n\t\t\treturn true\n\t\t}\n\t}\n\tif hisVisEv != nil {\n\t\thisVis, _ := hisVisEv.HistoryVisibility()\n\t\tif hisVis == \"world_readable\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ references returns all references pointing to or from this room.\nfunc (w *walker) references(roomID string) (eventLookup, error) {\n\tevents, err := w.db.References(w.ctx, roomID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tel := make(eventLookup)\n\tfor _, ev := range events {\n\t\tel.set(ev)\n\t}\n\treturn el, nil\n}\n\n\/\/ state event lookup across multiple rooms keyed on event type\n\/\/ NOT THREAD SAFE\ntype eventLookup map[string][]*gomatrixserverlib.HeaderedEvent\n\nfunc (el eventLookup) set(ev *gomatrixserverlib.HeaderedEvent) {\n\tevs := el[ev.Type()]\n\tif evs == nil {\n\t\tevs = make([]*gomatrixserverlib.HeaderedEvent, 0)\n\t}\n\tevs = append(evs, ev)\n\tel[ev.Type()] = evs\n}\n\nfunc (el eventLookup) len() int {\n\tsum := 0\n\tfor _, evs := range el {\n\t\tsum += len(evs)\n\t}\n\treturn sum\n}\n\nfunc (el eventLookup) events() (events []*gomatrixserverlib.HeaderedEvent) {\n\tfor _, evs := range el {\n\t\tevents = append(events, evs...)\n\t}\n\treturn\n}\n\ntype set map[string]bool\n<commit_msg>Per request cache for now as we don't do batching correclty<commit_after>\/\/ Copyright 2021 The Matrix.org Foundation C.I.C.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package msc2946 'Spaces Summary' implements https:\/\/github.com\/matrix-org\/matrix-doc\/pull\/2946\npackage msc2946\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"sync\"\n\n\t\"github.com\/gorilla\/mux\"\n\tchttputil \"github.com\/matrix-org\/dendrite\/clientapi\/httputil\"\n\t\"github.com\/matrix-org\/dendrite\/internal\/hooks\"\n\t\"github.com\/matrix-org\/dendrite\/internal\/httputil\"\n\troomserver \"github.com\/matrix-org\/dendrite\/roomserver\/api\"\n\t\"github.com\/matrix-org\/dendrite\/setup\"\n\tuserapi \"github.com\/matrix-org\/dendrite\/userapi\/api\"\n\t\"github.com\/matrix-org\/gomatrixserverlib\"\n\t\"github.com\/matrix-org\/util\"\n\t\"github.com\/tidwall\/gjson\"\n)\n\nconst (\n\tConstCreateEventContentKey = \"org.matrix.msc1772.type\"\n\tConstSpaceChildEventType   = \"org.matrix.msc1772.space.child\"\n\tConstSpaceParentEventType  = \"org.matrix.msc1772.room.parent\"\n)\n\n\/\/ SpacesRequest is the request body to POST \/_matrix\/client\/r0\/rooms\/{roomID}\/spaces\ntype SpacesRequest struct {\n\tMaxRoomsPerSpace int    `json:\"max_rooms_per_space\"`\n\tLimit            int    `json:\"limit\"`\n\tBatch            string `json:\"batch\"`\n}\n\n\/\/ Defaults sets the request defaults\nfunc (r *SpacesRequest) Defaults() {\n\tr.Limit = 100\n\tr.MaxRoomsPerSpace = -1\n}\n\n\/\/ SpacesResponse is the response body to POST \/_matrix\/client\/r0\/rooms\/{roomID}\/spaces\ntype SpacesResponse struct {\n\tNextBatch string `json:\"next_batch\"`\n\t\/\/ Rooms are nodes on the space graph.\n\tRooms []Room `json:\"rooms\"`\n\t\/\/ Events are edges on the space graph, exclusively m.space.child or m.room.parent events\n\tEvents []gomatrixserverlib.ClientEvent `json:\"events\"`\n}\n\n\/\/ Room is a node on the space graph\ntype Room struct {\n\tgomatrixserverlib.PublicRoom\n\tNumRefs  int    `json:\"num_refs\"`\n\tRoomType string `json:\"room_type\"`\n}\n\n\/\/ Enable this MSC\nfunc Enable(\n\tbase *setup.BaseDendrite, rsAPI roomserver.RoomserverInternalAPI, userAPI userapi.UserInternalAPI,\n) error {\n\tdb, err := NewDatabase(&base.Cfg.MSCs.Database)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot enable MSC2946: %w\", err)\n\t}\n\thooks.Enable()\n\thooks.Attach(hooks.KindNewEventPersisted, func(headeredEvent interface{}) {\n\t\the := headeredEvent.(*gomatrixserverlib.HeaderedEvent)\n\t\thookErr := db.StoreReference(context.Background(), he)\n\t\tif hookErr != nil {\n\t\t\tutil.GetLogger(context.Background()).WithError(hookErr).WithField(\"event_id\", he.EventID()).Error(\n\t\t\t\t\"failed to StoreReference\",\n\t\t\t)\n\t\t}\n\t})\n\n\tbase.PublicClientAPIMux.Handle(\"\/unstable\/rooms\/{roomID}\/spaces\",\n\t\thttputil.MakeAuthAPI(\"spaces\", userAPI, spacesHandler(db, rsAPI)),\n\t).Methods(http.MethodPost, http.MethodOptions)\n\treturn nil\n}\n\nfunc spacesHandler(db Database, rsAPI roomserver.RoomserverInternalAPI) func(*http.Request, *userapi.Device) util.JSONResponse {\n\treturn func(req *http.Request, device *userapi.Device) util.JSONResponse {\n\t\tinMemoryBatchCache := make(map[string]set)\n\t\t\/\/ Extract the room ID from the request. Sanity check request data.\n\t\tparams, err := httputil.URLDecodeMapValues(mux.Vars(req))\n\t\tif err != nil {\n\t\t\treturn util.ErrorResponse(err)\n\t\t}\n\t\troomID := params[\"roomID\"]\n\t\tvar r SpacesRequest\n\t\tr.Defaults()\n\t\tif resErr := chttputil.UnmarshalJSONRequest(req, &r); resErr != nil {\n\t\t\treturn *resErr\n\t\t}\n\t\tif r.Limit > 100 {\n\t\t\tr.Limit = 100\n\t\t}\n\t\tw := walker{\n\t\t\treq:        &r,\n\t\t\trootRoomID: roomID,\n\t\t\tcaller:     device,\n\t\t\tctx:        req.Context(),\n\n\t\t\tdb:                 db,\n\t\t\trsAPI:              rsAPI,\n\t\t\tinMemoryBatchCache: inMemoryBatchCache,\n\t\t}\n\t\tres := w.walk()\n\t\treturn util.JSONResponse{\n\t\t\tCode: 200,\n\t\t\tJSON: res,\n\t\t}\n\t}\n}\n\ntype walker struct {\n\treq        *SpacesRequest\n\trootRoomID string\n\tcaller     *userapi.Device\n\tdb         Database\n\trsAPI      roomserver.RoomserverInternalAPI\n\tctx        context.Context\n\n\t\/\/ user ID|device ID|batch_num => event\/room IDs sent to client\n\tinMemoryBatchCache map[string]set\n\tmu                 sync.Mutex\n}\n\nfunc (w *walker) alreadySent(id string) bool {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\tm, ok := w.inMemoryBatchCache[w.caller.UserID+\"|\"+w.caller.ID]\n\tif !ok {\n\t\treturn false\n\t}\n\treturn m[id]\n}\n\nfunc (w *walker) markSent(id string) {\n\tw.mu.Lock()\n\tdefer w.mu.Unlock()\n\tm := w.inMemoryBatchCache[w.caller.UserID+\"|\"+w.caller.ID]\n\tif m == nil {\n\t\tm = make(set)\n\t}\n\tm[id] = true\n\tw.inMemoryBatchCache[w.caller.UserID+\"|\"+w.caller.ID] = m\n}\n\n\/\/ nolint:gocyclo\nfunc (w *walker) walk() *SpacesResponse {\n\tvar res SpacesResponse\n\t\/\/ Begin walking the graph starting with the room ID in the request in a queue of unvisited rooms\n\tunvisited := []string{w.rootRoomID}\n\tprocessed := make(set)\n\tfor len(unvisited) > 0 {\n\t\troomID := unvisited[0]\n\t\tunvisited = unvisited[1:]\n\t\t\/\/ If this room has already been processed, skip. NB: do not remember this between calls\n\t\tif processed[roomID] || roomID == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Mark this room as processed.\n\t\tprocessed[roomID] = true\n\t\t\/\/ Is the caller currently joined to the room or is the room `world_readable`\n\t\t\/\/ If no, skip this room. If yes, continue.\n\t\tif !w.authorised(roomID) {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Get all `m.space.child` and `m.room.parent` state events for the room. *In addition*, get\n\t\t\/\/ all `m.space.child` and `m.room.parent` state events which *point to* (via `state_key` or `content.room_id`)\n\t\t\/\/ this room. This requires servers to store reverse lookups.\n\t\trefs, err := w.references(roomID)\n\t\tif err != nil {\n\t\t\tutil.GetLogger(w.ctx).WithError(err).WithField(\"room_id\", roomID).Error(\"failed to extract references for room\")\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ If this room has not ever been in `rooms` (across multiple requests), extract the\n\t\t\/\/ `PublicRoomsChunk` for this room.\n\t\tif !w.alreadySent(roomID) {\n\t\t\tpubRoom := w.publicRoomsChunk(roomID)\n\t\t\troomType := \"\"\n\t\t\tcreate := w.stateEvent(roomID, \"m.room.create\", \"\")\n\t\t\tif create != nil {\n\t\t\t\troomType = gjson.GetBytes(create.Content(), ConstCreateEventContentKey).Str\n\t\t\t}\n\n\t\t\t\/\/ Add the total number of events to `PublicRoomsChunk` under `num_refs`. Add `PublicRoomsChunk` to `rooms`.\n\t\t\tres.Rooms = append(res.Rooms, Room{\n\t\t\t\tPublicRoom: *pubRoom,\n\t\t\t\tNumRefs:    refs.len(),\n\t\t\t\tRoomType:   roomType,\n\t\t\t})\n\t\t}\n\n\t\tuniqueRooms := make(set)\n\n\t\t\/\/ If this is the root room from the original request, insert all these events into `events` if\n\t\t\/\/ they haven't been added before (across multiple requests).\n\t\tif w.rootRoomID == roomID {\n\t\t\tfor _, ev := range refs.events() {\n\t\t\t\tif !w.alreadySent(ev.EventID()) {\n\t\t\t\t\tres.Events = append(res.Events, gomatrixserverlib.HeaderedToClientEvent(\n\t\t\t\t\t\tev, gomatrixserverlib.FormatAll,\n\t\t\t\t\t))\n\t\t\t\t\tuniqueRooms[ev.RoomID()] = true\n\t\t\t\t\tuniqueRooms[SpaceTarget(ev)] = true\n\t\t\t\t\tw.markSent(ev.EventID())\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Else add them to `events` honouring the `limit` and `max_rooms_per_space` values. If either\n\t\t\t\/\/ are exceeded, stop adding events. If the event has already been added, do not add it again.\n\t\t\tnumAdded := 0\n\t\t\tfor _, ev := range refs.events() {\n\t\t\t\tif w.req.Limit > 0 && len(res.Events) >= w.req.Limit {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif w.req.MaxRoomsPerSpace > 0 && numAdded >= w.req.MaxRoomsPerSpace {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif w.alreadySent(ev.EventID()) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tres.Events = append(res.Events, gomatrixserverlib.HeaderedToClientEvent(\n\t\t\t\t\tev, gomatrixserverlib.FormatAll,\n\t\t\t\t))\n\t\t\t\tuniqueRooms[ev.RoomID()] = true\n\t\t\t\tuniqueRooms[SpaceTarget(ev)] = true\n\t\t\t\tw.markSent(ev.EventID())\n\t\t\t\t\/\/ we don't distinguish between child state events and parent state events for the purposes of\n\t\t\t\t\/\/ max_rooms_per_space, maybe we should?\n\t\t\t\tnumAdded++\n\t\t\t}\n\t\t}\n\n\t\t\/\/ For each referenced room ID in the events being returned to the caller (both parent and child)\n\t\t\/\/ add the room ID to the queue of unvisited rooms. Loop from the beginning.\n\t\tfor roomID := range uniqueRooms {\n\t\t\tunvisited = append(unvisited, roomID)\n\t\t}\n\t}\n\treturn &res\n}\n\nfunc (w *walker) stateEvent(roomID, evType, stateKey string) *gomatrixserverlib.HeaderedEvent {\n\tvar queryRes roomserver.QueryCurrentStateResponse\n\ttuple := gomatrixserverlib.StateKeyTuple{\n\t\tEventType: evType,\n\t\tStateKey:  stateKey,\n\t}\n\terr := w.rsAPI.QueryCurrentState(w.ctx, &roomserver.QueryCurrentStateRequest{\n\t\tRoomID:      roomID,\n\t\tStateTuples: []gomatrixserverlib.StateKeyTuple{tuple},\n\t}, &queryRes)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn queryRes.StateEvents[tuple]\n}\n\nfunc (w *walker) publicRoomsChunk(roomID string) *gomatrixserverlib.PublicRoom {\n\tpubRooms, err := roomserver.PopulatePublicRooms(w.ctx, []string{roomID}, w.rsAPI)\n\tif err != nil {\n\t\tutil.GetLogger(w.ctx).WithError(err).Error(\"failed to PopulatePublicRooms\")\n\t\treturn nil\n\t}\n\tif len(pubRooms) == 0 {\n\t\treturn nil\n\t}\n\treturn &pubRooms[0]\n}\n\n\/\/ authorised returns true iff the user is joined this room or the room is world_readable\nfunc (w *walker) authorised(roomID string) bool {\n\thisVisTuple := gomatrixserverlib.StateKeyTuple{\n\t\tEventType: gomatrixserverlib.MRoomHistoryVisibility,\n\t\tStateKey:  \"\",\n\t}\n\troomMemberTuple := gomatrixserverlib.StateKeyTuple{\n\t\tEventType: gomatrixserverlib.MRoomMember,\n\t\tStateKey:  w.caller.UserID,\n\t}\n\tvar queryRes roomserver.QueryCurrentStateResponse\n\terr := w.rsAPI.QueryCurrentState(w.ctx, &roomserver.QueryCurrentStateRequest{\n\t\tRoomID: roomID,\n\t\tStateTuples: []gomatrixserverlib.StateKeyTuple{\n\t\t\thisVisTuple, roomMemberTuple,\n\t\t},\n\t}, &queryRes)\n\tif err != nil {\n\t\tutil.GetLogger(w.ctx).WithError(err).Error(\"failed to QueryCurrentState\")\n\t\treturn false\n\t}\n\tmemberEv := queryRes.StateEvents[roomMemberTuple]\n\thisVisEv := queryRes.StateEvents[hisVisTuple]\n\tif memberEv != nil {\n\t\tmembership, _ := memberEv.Membership()\n\t\tif membership == gomatrixserverlib.Join {\n\t\t\treturn true\n\t\t}\n\t}\n\tif hisVisEv != nil {\n\t\thisVis, _ := hisVisEv.HistoryVisibility()\n\t\tif hisVis == \"world_readable\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ references returns all references pointing to or from this room.\nfunc (w *walker) references(roomID string) (eventLookup, error) {\n\tevents, err := w.db.References(w.ctx, roomID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tel := make(eventLookup)\n\tfor _, ev := range events {\n\t\tel.set(ev)\n\t}\n\treturn el, nil\n}\n\n\/\/ state event lookup across multiple rooms keyed on event type\n\/\/ NOT THREAD SAFE\ntype eventLookup map[string][]*gomatrixserverlib.HeaderedEvent\n\nfunc (el eventLookup) set(ev *gomatrixserverlib.HeaderedEvent) {\n\tevs := el[ev.Type()]\n\tif evs == nil {\n\t\tevs = make([]*gomatrixserverlib.HeaderedEvent, 0)\n\t}\n\tevs = append(evs, ev)\n\tel[ev.Type()] = evs\n}\n\nfunc (el eventLookup) len() int {\n\tsum := 0\n\tfor _, evs := range el {\n\t\tsum += len(evs)\n\t}\n\treturn sum\n}\n\nfunc (el eventLookup) events() (events []*gomatrixserverlib.HeaderedEvent) {\n\tfor _, evs := range el {\n\t\tevents = append(events, evs...)\n\t}\n\treturn\n}\n\ntype set map[string]bool\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This package implements a provisioner for Packer that executes a\n\/\/ saltstack highstate within the remote machine\npackage saltmasterless\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/mitchellh\/packer\/builder\/common\"\n\t\"github.com\/mitchellh\/packer\/packer\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nvar Ui packer.Ui\n\nconst DefaultTempConfigDir = \"\/tmp\/salt\"\n\ntype Config struct {\n\t\/\/ If true, run the salt-bootstrap script\n\tSkipBootstrap bool   `mapstructure:\"skip_bootstrap\"`\n\tBootstrapArgs string `mapstructure:\"bootstrap_args\"`\n\n\t\/\/ Local path to the salt state tree\n\tLocalStateTree string `mapstructure:\"local_state_tree\"`\n\n\t\/\/ Where files will be copied before moving to the \/srv\/salt directory\n\tTempConfigDir string `mapstructure:\"temp_config_dir\"`\n}\n\ntype Provisioner struct {\n\tconfig Config\n}\n\nfunc (p *Provisioner) Prepare(raws ...interface{}) error {\n\tmd, err := common.DecodeConfig(&p.config, raws...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif p.config.TempConfigDir == \"\" {\n\t\tp.config.TempConfigDir = DefaultTempConfigDir\n\t}\n\n\t\/\/ Accumulate any errors\n\terrs := common.CheckUnusedConfig(md)\n\n\tif p.config.LocalStateTree == \"\" {\n\t\terrs = packer.MultiErrorAppend(errs,\n\t\t\terrors.New(\"Please specify a local_state_tree\"))\n\t}\n\n\tif errs != nil && len(errs.Errors) > 0 {\n\t\treturn errs\n\t}\n\n\treturn nil\n}\n\nfunc (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {\n\tvar err error\n\n\tif !p.config.SkipBootstrap {\n\t\tcmd := &packer.RemoteCmd{\n\t\t\tCommand: fmt.Sprintf(\"wget -O - http:\/\/bootstrap.saltstack.org | sudo sh -s %s\", p.config.BootstrapArgs),\n\t\t}\n\t\tui.Say(fmt.Sprintf(\"Installing Salt with command %s\", cmd))\n\t\tif err = cmd.StartWithUi(comm, ui); err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to install Salt: %d\", err)\n\t\t}\n\t}\n\n\tui.Say(fmt.Sprintf(\"Creating remote directory: %s\", p.config.TempConfigDir))\n\tcmd := &packer.RemoteCmd{Command: fmt.Sprintf(\"mkdir -p %s\", p.config.TempConfigDir)}\n\tif err = cmd.StartWithUi(comm, ui); err != nil {\n\t\treturn fmt.Errorf(\"Error creating remote salt state directory: %s\", err)\n\t}\n\n\tui.Say(fmt.Sprintf(\"Uploading local state tree: %s\", p.config.LocalStateTree))\n\tif err = UploadLocalDirectory(p.config.LocalStateTree, p.config.TempConfigDir, comm); err != nil {\n\t\treturn fmt.Errorf(\"Error uploading local state tree to remote: %s\", err)\n\t}\n\n\tui.Say(fmt.Sprintf(\"Moving %s to \/srv\/salt\", p.config.TempConfigDir))\n\tcmd = &packer.RemoteCmd{Command: fmt.Sprintf(\"sudo mv %s \/srv\/salt\", p.config.TempConfigDir)}\n\tif err = cmd.StartWithUi(comm, ui); err != nil {\n\t\treturn fmt.Errorf(\"Unable to move %s to \/srv\/salt: %d\", p.config.TempConfigDir, err)\n\t}\n\n\tui.Say(\"Running highstate\")\n\tcmd = &packer.RemoteCmd{Command: \"sudo salt-call --local state.highstate -l info\"}\n\tif err = cmd.StartWithUi(comm, ui); err != nil {\n\t\treturn fmt.Errorf(\"Error executing highstate: %s\", err)\n\t}\n\n\tui.Say(\"Removing \/srv\/salt\")\n\tcmd = &packer.RemoteCmd{Command: \"sudo rm -r \/srv\/salt\"}\n\tif err = cmd.StartWithUi(comm, ui); err != nil {\n\t\treturn fmt.Errorf(\"Unable to remove \/srv\/salt: %d\", err)\n\t}\n\n\treturn nil\n}\n\nfunc UploadLocalDirectory(localDir string, remoteDir string, comm packer.Communicator) (err error) {\n\tvisitPath := func(localPath string, f os.FileInfo, err error) (err2 error) {\n\t\tlocalRelPath := strings.Replace(localPath, localDir, \"\", 1)\n\t\tremotePath := fmt.Sprintf(\"%s%s\", remoteDir, localRelPath)\n\t\tif f.IsDir() && f.Name() == \".git\" {\n\t\t\treturn filepath.SkipDir\n\t\t}\n\t\tif f.IsDir() {\n\t\t\t\/\/ Make remote directory\n\t\t\tcmd := &packer.RemoteCmd{Command: fmt.Sprintf(\"mkdir -p %s\", remotePath)}\n\t\t\tif err = cmd.StartWithUi(comm, Ui); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Upload file to existing directory\n\t\t\tfile, err := os.Open(localPath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error opening file: %s\", err)\n\t\t\t}\n\t\t\tdefer file.Close()\n\n\t\t\tUi.Say(fmt.Sprintf(\"Uploading file %s: %s\", localPath, remotePath))\n\t\t\tif err = comm.Upload(remotePath, file); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error uploading file: %s\", err)\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\terr = filepath.Walk(localDir, visitPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error uploading local directory %s: %s\", localDir, err)\n\t}\n\n\treturn nil\n}\n<commit_msg>provisioner\/salt-masterless: use Messages for minor steps<commit_after>\/\/ This package implements a provisioner for Packer that executes a\n\/\/ saltstack highstate within the remote machine\npackage saltmasterless\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/mitchellh\/packer\/builder\/common\"\n\t\"github.com\/mitchellh\/packer\/packer\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nvar Ui packer.Ui\n\nconst DefaultTempConfigDir = \"\/tmp\/salt\"\n\ntype Config struct {\n\t\/\/ If true, run the salt-bootstrap script\n\tSkipBootstrap bool   `mapstructure:\"skip_bootstrap\"`\n\tBootstrapArgs string `mapstructure:\"bootstrap_args\"`\n\n\t\/\/ Local path to the salt state tree\n\tLocalStateTree string `mapstructure:\"local_state_tree\"`\n\n\t\/\/ Where files will be copied before moving to the \/srv\/salt directory\n\tTempConfigDir string `mapstructure:\"temp_config_dir\"`\n}\n\ntype Provisioner struct {\n\tconfig Config\n}\n\nfunc (p *Provisioner) Prepare(raws ...interface{}) error {\n\tmd, err := common.DecodeConfig(&p.config, raws...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif p.config.TempConfigDir == \"\" {\n\t\tp.config.TempConfigDir = DefaultTempConfigDir\n\t}\n\n\t\/\/ Accumulate any errors\n\terrs := common.CheckUnusedConfig(md)\n\n\tif p.config.LocalStateTree == \"\" {\n\t\terrs = packer.MultiErrorAppend(errs,\n\t\t\terrors.New(\"Please specify a local_state_tree\"))\n\t}\n\n\tif errs != nil && len(errs.Errors) > 0 {\n\t\treturn errs\n\t}\n\n\treturn nil\n}\n\nfunc (p *Provisioner) Provision(ui packer.Ui, comm packer.Communicator) error {\n\tvar err error\n\n\tui.Say(\"Provisioning with Salt...\")\n\tif !p.config.SkipBootstrap {\n\t\tcmd := &packer.RemoteCmd{\n\t\t\tCommand: fmt.Sprintf(\"wget -O - http:\/\/bootstrap.saltstack.org | sudo sh -s %s\", p.config.BootstrapArgs),\n\t\t}\n\t\tui.Message(fmt.Sprintf(\"Installing Salt with command %s\", cmd))\n\t\tif err = cmd.StartWithUi(comm, ui); err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to install Salt: %d\", err)\n\t\t}\n\t}\n\n\tui.Message(fmt.Sprintf(\"Creating remote directory: %s\", p.config.TempConfigDir))\n\tcmd := &packer.RemoteCmd{Command: fmt.Sprintf(\"mkdir -p %s\", p.config.TempConfigDir)}\n\tif err = cmd.StartWithUi(comm, ui); err != nil {\n\t\treturn fmt.Errorf(\"Error creating remote salt state directory: %s\", err)\n\t}\n\n\tui.Message(fmt.Sprintf(\"Uploading local state tree: %s\", p.config.LocalStateTree))\n\tif err = UploadLocalDirectory(p.config.LocalStateTree, p.config.TempConfigDir, comm); err != nil {\n\t\treturn fmt.Errorf(\"Error uploading local state tree to remote: %s\", err)\n\t}\n\n\tui.Message(fmt.Sprintf(\"Moving %s to \/srv\/salt\", p.config.TempConfigDir))\n\tcmd = &packer.RemoteCmd{Command: fmt.Sprintf(\"sudo mv %s \/srv\/salt\", p.config.TempConfigDir)}\n\tif err = cmd.StartWithUi(comm, ui); err != nil {\n\t\treturn fmt.Errorf(\"Unable to move %s to \/srv\/salt: %d\", p.config.TempConfigDir, err)\n\t}\n\n\tui.Message(\"Running highstate\")\n\tcmd = &packer.RemoteCmd{Command: \"sudo salt-call --local state.highstate -l info\"}\n\tif err = cmd.StartWithUi(comm, ui); err != nil {\n\t\treturn fmt.Errorf(\"Error executing highstate: %s\", err)\n\t}\n\n\tui.Message(\"Removing \/srv\/salt\")\n\tcmd = &packer.RemoteCmd{Command: \"sudo rm -r \/srv\/salt\"}\n\tif err = cmd.StartWithUi(comm, ui); err != nil {\n\t\treturn fmt.Errorf(\"Unable to remove \/srv\/salt: %d\", err)\n\t}\n\n\treturn nil\n}\n\nfunc UploadLocalDirectory(localDir string, remoteDir string, comm packer.Communicator) (err error) {\n\tvisitPath := func(localPath string, f os.FileInfo, err error) (err2 error) {\n\t\tlocalRelPath := strings.Replace(localPath, localDir, \"\", 1)\n\t\tremotePath := fmt.Sprintf(\"%s%s\", remoteDir, localRelPath)\n\t\tif f.IsDir() && f.Name() == \".git\" {\n\t\t\treturn filepath.SkipDir\n\t\t}\n\t\tif f.IsDir() {\n\t\t\t\/\/ Make remote directory\n\t\t\tcmd := &packer.RemoteCmd{Command: fmt.Sprintf(\"mkdir -p %s\", remotePath)}\n\t\t\tif err = cmd.StartWithUi(comm, Ui); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Upload file to existing directory\n\t\t\tfile, err := os.Open(localPath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error opening file: %s\", err)\n\t\t\t}\n\t\t\tdefer file.Close()\n\n\t\t\tUi.Message(fmt.Sprintf(\"Uploading file %s: %s\", localPath, remotePath))\n\t\t\tif err = comm.Upload(remotePath, file); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error uploading file: %s\", err)\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\terr = filepath.Walk(localDir, visitPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error uploading local directory %s: %s\", localDir, err)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package gitter\n\nimport (\n\t\"github.com\/oklahomer\/go-sarah\"\n\t\"github.com\/oklahomer\/go-sarah\/log\"\n\t\"github.com\/oklahomer\/go-sarah\/retry\"\n\t\"golang.org\/x\/net\/context\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ GITTER is a dedicated BotType for gitter implementation.\n\tGITTER sarah.BotType = \"gitter\"\n)\n\n\/\/ Adapter stores REST\/Streaming API clients' instances to let users interact with gitter.\ntype Adapter struct {\n\tconfig             *Config\n\trestAPIClient      *RestAPIClient\n\tstreamingAPIClient *StreamingAPIClient\n}\n\n\/\/ NewAdapter creates and returns new Adapter instance.\nfunc NewAdapter(config *Config) *Adapter {\n\treturn &Adapter{\n\t\tconfig:             config,\n\t\trestAPIClient:      NewRestAPIClient(config.Token),\n\t\tstreamingAPIClient: NewStreamingAPIClient(config.Token),\n\t}\n}\n\n\/\/ BotType returns gitter designated BotType.\nfunc (adapter *Adapter) BotType() sarah.BotType {\n\treturn GITTER\n}\n\n\/\/ Run fetches all belonging Room and connects to them.\nfunc (adapter *Adapter) Run(ctx context.Context, enqueueInput func(sarah.Input) error, notifyErr func(error)) {\n\t\/\/ fetch joined rooms\n\trooms, err := fetchRooms(ctx, adapter.restAPIClient, adapter.config.RetryLimit, adapter.config.RetryInterval)\n\tif err != nil {\n\t\tnotifyErr(sarah.NewBotNonContinuableError(err.Error()))\n\t\treturn\n\t}\n\n\tfor _, room := range *rooms {\n\t\tgo adapter.runEachRoom(ctx, room, enqueueInput)\n\t}\n}\n\n\/\/ SendMessage let Bot send message to gitter.\nfunc (adapter *Adapter) SendMessage(ctx context.Context, output sarah.Output) {\n\tswitch content := output.Content().(type) {\n\tcase string:\n\t\troom, ok := output.Destination().(*Room)\n\t\tif !ok {\n\t\t\tlog.Errorf(\"Destination is not instance of Room. %#v.\", output.Destination())\n\t\t\treturn\n\t\t}\n\t\tadapter.restAPIClient.PostMessage(ctx, room, content)\n\tdefault:\n\t\tlog.Warnf(\"unexpected output %#v\", output)\n\t}\n}\n\nfunc (adapter *Adapter) runEachRoom(ctx context.Context, room *Room, enqueueInput func(sarah.Input) error) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Infof(\"connecting to room: %s\", room.ID)\n\t\t\tconn, err := connectRoom(ctx, adapter.streamingAPIClient, room, adapter.config.RetryLimit, adapter.config.RetryInterval)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warnf(\"could not connect to room: %s\", room.ID)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconnErr := receiveMessageRecursive(conn, enqueueInput)\n\t\t\tconn.Close()\n\t\t\tif connErr == nil {\n\t\t\t\t\/\/ Connection is intentionally closed by caller.\n\t\t\t\t\/\/ No more interaction follows.\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ TODO: Intentional connection close such as context.cancel also comes here.\n\t\t\t\/\/ It would be nice if we could detect such event to distinguish intentional behaviour and unintentional connection error.\n\t\t\t\/\/ But, the truth is, given error is just a privately defined error instance given by http package.\n\t\t\t\/\/ var errRequestCanceled = errors.New(\"net\/http: request canceled\")\n\t\t\t\/\/ For now, let error log appear and proceed to next loop, select case with ctx.Done() will eventually return.\n\t\t\tlog.Error(connErr.Error())\n\t\t}\n\t}\n}\n\nfunc fetchRooms(ctx context.Context, fetcher RoomsFetcher, retrial uint, interval time.Duration) (*Rooms, error) {\n\tvar rooms *Rooms\n\terr := retry.WithInterval(retrial, func() error {\n\t\tr, e := fetcher.Rooms(ctx)\n\t\trooms = r\n\t\treturn e\n\t}, interval)\n\n\treturn rooms, err\n}\n\nfunc receiveMessageRecursive(messageReceiver MessageReceiver, enqueueInput func(sarah.Input) error) error {\n\tlog.Infof(\"start receiving message\")\n\tfor {\n\t\tmessage, err := messageReceiver.Receive()\n\n\t\tif err == ErrEmptyPayload {\n\t\t\t\/\/ https:\/\/developer.gitter.im\/docs\/streaming-api\n\t\t\t\/\/ Parsers must be tolerant of occasional extra newline characters placed between messages.\n\t\t\t\/\/ These characters are sent as periodic \"keep-alive\" messages to tell clients and NAT firewalls\n\t\t\t\/\/ that the connection is still alive during low message volume periods.\n\t\t\tcontinue\n\t\t} else if malformedErr, ok := err.(*MalformedPayloadError); ok {\n\t\t\tlog.Warnf(\"skipping malformed input: %s\", malformedErr)\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\t\/\/ At this point, assume connection is unstable or is closed.\n\t\t\t\/\/ Let caller proceed to reconnect or quit.\n\t\t\treturn err\n\t\t}\n\n\t\tenqueueInput(message)\n\t}\n}\n\nfunc connectRoom(ctx context.Context, connector StreamConnector, room *Room, retrial uint, interval time.Duration) (Connection, error) {\n\tvar conn Connection\n\terr := retry.WithInterval(retrial, func() error {\n\t\tr, e := connector.Connect(ctx, room)\n\t\tif e != nil {\n\t\t\tlog.Error(e)\n\t\t}\n\t\tconn = r\n\t\treturn e\n\t}, interval)\n\n\treturn conn, err\n}\n\n\/\/ NewStringResponse creates new sarah.CommandResponse instance with given string.\nfunc NewStringResponse(responseContent string) *sarah.CommandResponse {\n\treturn &sarah.CommandResponse{\n\t\tContent:     responseContent,\n\t\tUserContext: nil,\n\t}\n}\n\n\/\/ NewStringResponseWithNext creates new sarah.CommandResponse instance with given string and next function to continue\nfunc NewStringResponseWithNext(responseContent string, next sarah.ContextualFunc) *sarah.CommandResponse {\n\treturn &sarah.CommandResponse{\n\t\tContent:     responseContent,\n\t\tUserContext: sarah.NewUserContext(next),\n\t}\n}\n<commit_msg>Apply same interface to gitter adapter constructor<commit_after>package gitter\n\nimport (\n\t\"github.com\/oklahomer\/go-sarah\"\n\t\"github.com\/oklahomer\/go-sarah\/log\"\n\t\"github.com\/oklahomer\/go-sarah\/retry\"\n\t\"golang.org\/x\/net\/context\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ GITTER is a dedicated BotType for gitter implementation.\n\tGITTER sarah.BotType = \"gitter\"\n)\n\n\/\/ AdapterOption defines function signature that Adapter's functional option must satisfy.\ntype AdapterOption func(adapter *Adapter) error\n\n\/\/ Adapter stores REST\/Streaming API clients' instances to let users interact with gitter.\ntype Adapter struct {\n\tconfig             *Config\n\trestAPIClient      *RestAPIClient\n\tstreamingAPIClient *StreamingAPIClient\n}\n\n\/\/ NewAdapter creates and returns new Adapter instance.\nfunc NewAdapter(config *Config, options ...AdapterOption) (*Adapter, error) {\n\tadapter := &Adapter{\n\t\tconfig:             config,\n\t\trestAPIClient:      NewRestAPIClient(config.Token),\n\t\tstreamingAPIClient: NewStreamingAPIClient(config.Token),\n\t}\n\n\tfor _, opt := range options {\n\t\terr := opt(adapter)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn adapter, nil\n}\n\n\/\/ BotType returns gitter designated BotType.\nfunc (adapter *Adapter) BotType() sarah.BotType {\n\treturn GITTER\n}\n\n\/\/ Run fetches all belonging Room and connects to them.\nfunc (adapter *Adapter) Run(ctx context.Context, enqueueInput func(sarah.Input) error, notifyErr func(error)) {\n\t\/\/ fetch joined rooms\n\trooms, err := fetchRooms(ctx, adapter.restAPIClient, adapter.config.RetryLimit, adapter.config.RetryInterval)\n\tif err != nil {\n\t\tnotifyErr(sarah.NewBotNonContinuableError(err.Error()))\n\t\treturn\n\t}\n\n\tfor _, room := range *rooms {\n\t\tgo adapter.runEachRoom(ctx, room, enqueueInput)\n\t}\n}\n\n\/\/ SendMessage let Bot send message to gitter.\nfunc (adapter *Adapter) SendMessage(ctx context.Context, output sarah.Output) {\n\tswitch content := output.Content().(type) {\n\tcase string:\n\t\troom, ok := output.Destination().(*Room)\n\t\tif !ok {\n\t\t\tlog.Errorf(\"Destination is not instance of Room. %#v.\", output.Destination())\n\t\t\treturn\n\t\t}\n\t\tadapter.restAPIClient.PostMessage(ctx, room, content)\n\tdefault:\n\t\tlog.Warnf(\"unexpected output %#v\", output)\n\t}\n}\n\nfunc (adapter *Adapter) runEachRoom(ctx context.Context, room *Room, enqueueInput func(sarah.Input) error) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tdefault:\n\t\t\tlog.Infof(\"connecting to room: %s\", room.ID)\n\t\t\tconn, err := connectRoom(ctx, adapter.streamingAPIClient, room, adapter.config.RetryLimit, adapter.config.RetryInterval)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warnf(\"could not connect to room: %s\", room.ID)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconnErr := receiveMessageRecursive(conn, enqueueInput)\n\t\t\tconn.Close()\n\t\t\tif connErr == nil {\n\t\t\t\t\/\/ Connection is intentionally closed by caller.\n\t\t\t\t\/\/ No more interaction follows.\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ TODO: Intentional connection close such as context.cancel also comes here.\n\t\t\t\/\/ It would be nice if we could detect such event to distinguish intentional behaviour and unintentional connection error.\n\t\t\t\/\/ But, the truth is, given error is just a privately defined error instance given by http package.\n\t\t\t\/\/ var errRequestCanceled = errors.New(\"net\/http: request canceled\")\n\t\t\t\/\/ For now, let error log appear and proceed to next loop, select case with ctx.Done() will eventually return.\n\t\t\tlog.Error(connErr.Error())\n\t\t}\n\t}\n}\n\nfunc fetchRooms(ctx context.Context, fetcher RoomsFetcher, retrial uint, interval time.Duration) (*Rooms, error) {\n\tvar rooms *Rooms\n\terr := retry.WithInterval(retrial, func() error {\n\t\tr, e := fetcher.Rooms(ctx)\n\t\trooms = r\n\t\treturn e\n\t}, interval)\n\n\treturn rooms, err\n}\n\nfunc receiveMessageRecursive(messageReceiver MessageReceiver, enqueueInput func(sarah.Input) error) error {\n\tlog.Infof(\"start receiving message\")\n\tfor {\n\t\tmessage, err := messageReceiver.Receive()\n\n\t\tif err == ErrEmptyPayload {\n\t\t\t\/\/ https:\/\/developer.gitter.im\/docs\/streaming-api\n\t\t\t\/\/ Parsers must be tolerant of occasional extra newline characters placed between messages.\n\t\t\t\/\/ These characters are sent as periodic \"keep-alive\" messages to tell clients and NAT firewalls\n\t\t\t\/\/ that the connection is still alive during low message volume periods.\n\t\t\tcontinue\n\t\t} else if malformedErr, ok := err.(*MalformedPayloadError); ok {\n\t\t\tlog.Warnf(\"skipping malformed input: %s\", malformedErr)\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\t\/\/ At this point, assume connection is unstable or is closed.\n\t\t\t\/\/ Let caller proceed to reconnect or quit.\n\t\t\treturn err\n\t\t}\n\n\t\tenqueueInput(message)\n\t}\n}\n\nfunc connectRoom(ctx context.Context, connector StreamConnector, room *Room, retrial uint, interval time.Duration) (Connection, error) {\n\tvar conn Connection\n\terr := retry.WithInterval(retrial, func() error {\n\t\tr, e := connector.Connect(ctx, room)\n\t\tif e != nil {\n\t\t\tlog.Error(e)\n\t\t}\n\t\tconn = r\n\t\treturn e\n\t}, interval)\n\n\treturn conn, err\n}\n\n\/\/ NewStringResponse creates new sarah.CommandResponse instance with given string.\nfunc NewStringResponse(responseContent string) *sarah.CommandResponse {\n\treturn &sarah.CommandResponse{\n\t\tContent:     responseContent,\n\t\tUserContext: nil,\n\t}\n}\n\n\/\/ NewStringResponseWithNext creates new sarah.CommandResponse instance with given string and next function to continue\nfunc NewStringResponseWithNext(responseContent string, next sarah.ContextualFunc) *sarah.CommandResponse {\n\treturn &sarah.CommandResponse{\n\t\tContent:     responseContent,\n\t\tUserContext: sarah.NewUserContext(next),\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package nodes\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/google\/go-cmp\/cmp\"\n)\n\n\/\/ AllowUnexported option for cmp to make sure we can diff properly.\nvar cmpOpt = cmp.AllowUnexported(InfoboxNode{}, node{}, ListNode{}, TextNode{})\n\nfunc TestNewInfoboxNode(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tinKind    InfoboxKind\n\t\tinContent []Node\n\t\tout       *InfoboxNode\n\t}{\n\t\t{\n\t\t\tname:   \"PositiveEmpty\",\n\t\t\tinKind: InfoboxPositive,\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode: node{typ: NodeInfobox},\n\t\t\t\tKind: InfoboxPositive,\n\t\t\t\t\/\/ TODO: Do we really want this to not be nil?\n\t\t\t\tContent: NewListNode(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:      \"PositiveOneContent\",\n\t\t\tinKind:    InfoboxPositive,\n\t\t\tinContent: []Node{NewTextNode(\"hello\")},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tKind:    InfoboxPositive,\n\t\t\t\tContent: NewListNode(NewTextNode(\"hello\")),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:      \"PositiveMultiContent\",\n\t\t\tinKind:    InfoboxPositive,\n\t\t\tinContent: []Node{NewTextNode(\"orange\"), NewTextNode(\"strawberry\"), NewTextNode(\"pineapple\")},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tKind:    InfoboxPositive,\n\t\t\t\tContent: NewListNode(NewTextNode(\"orange\"), NewTextNode(\"strawberry\"), NewTextNode(\"pineapple\")),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:   \"NegativeEmpty\",\n\t\t\tinKind: InfoboxNegative,\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode: node{typ: NodeInfobox},\n\t\t\t\tKind: InfoboxNegative,\n\t\t\t\t\/\/ TODO: Do we really want this to not be nil?\n\t\t\t\tContent: NewListNode(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:      \"NegativeOneContent\",\n\t\t\tinKind:    InfoboxNegative,\n\t\t\tinContent: []Node{NewTextNode(\"hello\")},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tKind:    InfoboxNegative,\n\t\t\t\tContent: NewListNode(NewTextNode(\"hello\")),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:      \"NegativeMultiContent\",\n\t\t\tinKind:    InfoboxNegative,\n\t\t\tinContent: []Node{NewTextNode(\"orange\"), NewTextNode(\"strawberry\"), NewTextNode(\"pineapple\")},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tKind:    InfoboxNegative,\n\t\t\t\tContent: NewListNode(NewTextNode(\"orange\"), NewTextNode(\"strawberry\"), NewTextNode(\"pineapple\")),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\/\/ TODO: Should we set a default value?\n\t\t\tname:      \"NoKind\",\n\t\t\tinContent: []Node{NewTextNode(\"orange\")},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tContent: NewListNode(NewTextNode(\"orange\")),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\/\/ TODO: Should this return an error instead?\n\t\t\tname:      \"UnsupportedKind\",\n\t\t\tinKind:    \"this is not a valid kind of infobox\",\n\t\t\tinContent: []Node{NewTextNode(\"orange\")},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tKind:    \"this is not a valid kind of infobox\",\n\t\t\t\tContent: NewListNode(NewTextNode(\"orange\")),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:      \"ListOfOneList\",\n\t\t\tinKind:    InfoboxPositive,\n\t\t\tinContent: []Node{NewListNode(NewTextNode(\"a\"), NewTextNode(\"b\"))},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tKind:    InfoboxPositive,\n\t\t\t\tContent: NewListNode(NewListNode(NewTextNode(\"a\"), NewTextNode(\"b\"))),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tout := NewInfoboxNode(tc.inKind, tc.inContent...)\n\t\t\tif diff := cmp.Diff(tc.out, out, cmpOpt); diff != \"\" {\n\t\t\t\tt.Errorf(\"NewInfoboxNode(%q, %v) got diff (-want +got): %s\", tc.inKind, tc.inContent, diff)\n\t\t\t\treturn\n\t\t\t}\n\t\t})\n\t}\n}\n<commit_msg>Add test for empty InfoboxNode init.<commit_after>package nodes\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/google\/go-cmp\/cmp\"\n)\n\n\/\/ AllowUnexported option for cmp to make sure we can diff properly.\nvar cmpOpt = cmp.AllowUnexported(InfoboxNode{}, node{}, ListNode{}, TextNode{})\n\nfunc TestNewInfoboxNode(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tinKind    InfoboxKind\n\t\tinContent []Node\n\t\tout       *InfoboxNode\n\t}{\n\t\t{\n\t\t\tname:   \"PositiveEmpty\",\n\t\t\tinKind: InfoboxPositive,\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode: node{typ: NodeInfobox},\n\t\t\t\tKind: InfoboxPositive,\n\t\t\t\t\/\/ TODO: Do we really want this to not be nil?\n\t\t\t\tContent: NewListNode(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:      \"PositiveOneContent\",\n\t\t\tinKind:    InfoboxPositive,\n\t\t\tinContent: []Node{NewTextNode(\"hello\")},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tKind:    InfoboxPositive,\n\t\t\t\tContent: NewListNode(NewTextNode(\"hello\")),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:      \"PositiveMultiContent\",\n\t\t\tinKind:    InfoboxPositive,\n\t\t\tinContent: []Node{NewTextNode(\"orange\"), NewTextNode(\"strawberry\"), NewTextNode(\"pineapple\")},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tKind:    InfoboxPositive,\n\t\t\t\tContent: NewListNode(NewTextNode(\"orange\"), NewTextNode(\"strawberry\"), NewTextNode(\"pineapple\")),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:   \"NegativeEmpty\",\n\t\t\tinKind: InfoboxNegative,\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode: node{typ: NodeInfobox},\n\t\t\t\tKind: InfoboxNegative,\n\t\t\t\t\/\/ TODO: Do we really want this to not be nil?\n\t\t\t\tContent: NewListNode(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:      \"NegativeOneContent\",\n\t\t\tinKind:    InfoboxNegative,\n\t\t\tinContent: []Node{NewTextNode(\"hello\")},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tKind:    InfoboxNegative,\n\t\t\t\tContent: NewListNode(NewTextNode(\"hello\")),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:      \"NegativeMultiContent\",\n\t\t\tinKind:    InfoboxNegative,\n\t\t\tinContent: []Node{NewTextNode(\"orange\"), NewTextNode(\"strawberry\"), NewTextNode(\"pineapple\")},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tKind:    InfoboxNegative,\n\t\t\t\tContent: NewListNode(NewTextNode(\"orange\"), NewTextNode(\"strawberry\"), NewTextNode(\"pineapple\")),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\/\/ TODO: Should we set a default value?\n\t\t\tname:      \"NoKind\",\n\t\t\tinContent: []Node{NewTextNode(\"orange\")},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tContent: NewListNode(NewTextNode(\"orange\")),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\t\/\/ TODO: Should this return an error instead?\n\t\t\tname:      \"UnsupportedKind\",\n\t\t\tinKind:    \"this is not a valid kind of infobox\",\n\t\t\tinContent: []Node{NewTextNode(\"orange\")},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tKind:    \"this is not a valid kind of infobox\",\n\t\t\t\tContent: NewListNode(NewTextNode(\"orange\")),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:      \"ListOfOneList\",\n\t\t\tinKind:    InfoboxPositive,\n\t\t\tinContent: []Node{NewListNode(NewTextNode(\"a\"), NewTextNode(\"b\"))},\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tKind:    InfoboxPositive,\n\t\t\t\tContent: NewListNode(NewListNode(NewTextNode(\"a\"), NewTextNode(\"b\"))),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Empty\",\n\t\t\tout: &InfoboxNode{\n\t\t\t\tnode:    node{typ: NodeInfobox},\n\t\t\t\tContent: NewListNode(),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tout := NewInfoboxNode(tc.inKind, tc.inContent...)\n\t\t\tif diff := cmp.Diff(tc.out, out, cmpOpt); diff != \"\" {\n\t\t\t\tt.Errorf(\"NewInfoboxNode(%q, %v) got diff (-want +got): %s\", tc.inKind, tc.inContent, diff)\n\t\t\t\treturn\n\t\t\t}\n\t\t})\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package conio\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Result int\n\nconst (\n\tCONTINUE Result = iota\n\tENTER    Result = iota\n\tABORT    Result = iota\n)\n\ntype KeyFuncT interface {\n\tCall(buffer *Buffer) Result\n}\n\ntype KeyGoFuncT struct {\n\tF func(buffer *Buffer) Result\n}\n\nfunc (this *KeyGoFuncT) Call(buffer *Buffer) Result {\n\treturn this.F(buffer)\n}\n\nvar keyMap = map[rune]KeyFuncT{\n\tname2char[K_CTRL_A]: name2func[F_BEGINNING_OF_LINE],\n\tname2char[K_CTRL_B]: name2func[F_BACKWARD_CHAR],\n\tname2char[K_CTRL_C]: name2func[F_INTR],\n\tname2char[K_CTRL_D]: name2func[F_DELETE_OR_ABORT],\n\tname2char[K_CTRL_E]: name2func[F_END_OF_LINE],\n\tname2char[K_CTRL_F]: name2func[F_FORARD_CHAR],\n\tname2char[K_CTRL_H]: name2func[F_BACKWARD_DELETE_CHAR],\n\tname2char[K_CTRL_K]: name2func[F_KILL_LINE],\n\tname2char[K_CTRL_L]: name2func[F_CLEAR_SCREEN],\n\tname2char[K_CTRL_M]: name2func[F_ACCEPT_LINE],\n\tname2char[K_CTRL_U]: name2func[F_UNIX_LINE_DISCARD],\n\tname2char[K_CTRL_Y]: name2func[F_YANK],\n\tname2char[K_DELETE]: name2func[F_DELETE_CHAR],\n\tname2char[K_ENTER]:  name2func[F_ACCEPT_LINE],\n\tname2char[K_ESCAPE]: name2func[F_KILL_WHOLE_LINE],\n\tname2char[K_CTRL_N]: name2func[F_HISTORY_DOWN],\n\tname2char[K_CTRL_P]: name2func[F_HISTORY_UP],\n}\n\nvar scanMap = map[uint16]KeyFuncT{\n\tname2scan[K_CTRL]:   name2func[F_PASS],\n\tname2scan[K_DELETE]: name2func[F_DELETE_CHAR],\n\tname2scan[K_END]:    name2func[F_END_OF_LINE],\n\tname2scan[K_HOME]:   name2func[F_BEGINNING_OF_LINE],\n\tname2scan[K_LEFT]:   name2func[F_BACKWARD_CHAR],\n\tname2scan[K_RIGHT]:  name2func[F_FORARD_CHAR],\n\tname2scan[K_SHIFT]:  name2func[F_PASS],\n\tname2scan[K_DOWN]:   name2func[F_HISTORY_DOWN],\n\tname2scan[K_UP]:     name2func[F_HISTORY_UP],\n}\n\nvar altMap = map[uint16]KeyFuncT{\n\tname2alt[K_ALT_V]: name2func[F_YANK],\n}\n\nfunc normWord(src string) string {\n\treturn strings.Replace(strings.ToUpper(src), \"-\", \"_\", -1)\n}\n\nfunc BindKeyFunc(keyName string, funcValue KeyFuncT) error {\n\tkeyName_ := normWord(keyName)\n\tif altValue, altOk := name2alt[keyName_]; altOk {\n\t\taltMap[altValue] = funcValue\n\t\treturn nil\n\t} else if charValue, charOk := name2char[keyName_]; charOk {\n\t\tkeyMap[charValue] = funcValue\n\t\treturn nil\n\t} else if scanValue, scanOk := name2scan[keyName_]; scanOk {\n\t\tscanMap[scanValue] = funcValue\n\t\treturn nil\n\t} else {\n\t\treturn fmt.Errorf(\"%s: no such keyname\", keyName)\n\t}\n}\n\nfunc GetFunc(funcName string) (KeyFuncT, error) {\n\trc, ok := name2func[normWord(funcName)]\n\tif ok {\n\t\treturn rc, nil\n\t} else {\n\t\treturn nil, fmt.Errorf(\"%s: not found in the function-list\", funcName)\n\t}\n}\n\nfunc BindKeySymbol(keyName, funcName string) error {\n\tfuncValue, funcOk := name2func[normWord(funcName)]\n\tif !funcOk {\n\t\treturn fmt.Errorf(\"%s: no such function.\", funcName)\n\t}\n\treturn BindKeyFunc(keyName, funcValue)\n}\n\nfunc BindKeySymbolFunc(keyName, funcName string, funcValue KeyFuncT) error {\n\tname2func[normWord(funcName)] = funcValue\n\treturn BindKeyFunc(keyName, funcValue)\n}\n\nfunc ReadLinePromptFunc(promptFunc func() int) (string, Result) {\n\tthis := Buffer{Buffer: make([]rune, 20)}\n\tthis.ViewWidth, _ = GetScreenBufferInfo().ViewSize()\n\tthis.ViewWidth--\n\n\tthis.Prompt = promptFunc\n\tif this.Prompt != nil {\n\t\tthis.ViewWidth = this.ViewWidth - this.Prompt()\n\t}\n\tfor {\n\t\tstdOut.Flush()\n\t\tshineCursor()\n\t\tthis.Unicode, this.Keycode, this.ShiftState = GetKey()\n\t\tvar f KeyFuncT\n\t\tvar ok bool\n\t\tif (this.ShiftState & ALT_PRESSED) != 0 {\n\t\t\tf, ok = altMap[this.Keycode]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else if this.Unicode != 0 {\n\t\t\tf, ok = keyMap[this.Unicode]\n\t\t\tif !ok {\n\t\t\t\t\/\/f = KeyFuncInsertReport\n\t\t\t\tf = &KeyGoFuncT{KeyFuncInsertSelf}\n\t\t\t}\n\t\t} else {\n\t\t\tf, ok = scanMap[this.Keycode]\n\t\t\tif !ok {\n\t\t\t\tf = &KeyGoFuncT{KeyFuncPass}\n\t\t\t}\n\t\t}\n\t\trc := f.Call(&this)\n\t\tif rc != CONTINUE {\n\t\t\tstdOut.WriteRune('\\n')\n\t\t\tstdOut.Flush()\n\t\t\tresult := this.String()\n\t\t\tif result == \"\" {\n\t\t\t\tHistoryResetPointer()\n\t\t\t}\n\t\t\tif last := LastHistory(); last == nil || result != last.Line {\n\t\t\t\tHistoryPush(result)\n\t\t\t}\n\t\t\treturn result, rc\n\t\t}\n\t}\n}\n\n\/\/ Not used on NYAGOS. Provide this as library for other applications.\nfunc ReadLinePromptStr(promptStr string) (string, Result) {\n\treturn ReadLinePromptFunc(func() int {\n\t\tfmt.Print(promptStr)\n\t\treturn len(promptStr)\n\t})\n}\n<commit_msg>Let functions bound on ALT-* not run with Ctrl<commit_after>package conio\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Result int\n\nconst (\n\tCONTINUE Result = iota\n\tENTER    Result = iota\n\tABORT    Result = iota\n)\n\ntype KeyFuncT interface {\n\tCall(buffer *Buffer) Result\n}\n\ntype KeyGoFuncT struct {\n\tF func(buffer *Buffer) Result\n}\n\nfunc (this *KeyGoFuncT) Call(buffer *Buffer) Result {\n\treturn this.F(buffer)\n}\n\nvar keyMap = map[rune]KeyFuncT{\n\tname2char[K_CTRL_A]: name2func[F_BEGINNING_OF_LINE],\n\tname2char[K_CTRL_B]: name2func[F_BACKWARD_CHAR],\n\tname2char[K_CTRL_C]: name2func[F_INTR],\n\tname2char[K_CTRL_D]: name2func[F_DELETE_OR_ABORT],\n\tname2char[K_CTRL_E]: name2func[F_END_OF_LINE],\n\tname2char[K_CTRL_F]: name2func[F_FORARD_CHAR],\n\tname2char[K_CTRL_H]: name2func[F_BACKWARD_DELETE_CHAR],\n\tname2char[K_CTRL_K]: name2func[F_KILL_LINE],\n\tname2char[K_CTRL_L]: name2func[F_CLEAR_SCREEN],\n\tname2char[K_CTRL_M]: name2func[F_ACCEPT_LINE],\n\tname2char[K_CTRL_U]: name2func[F_UNIX_LINE_DISCARD],\n\tname2char[K_CTRL_Y]: name2func[F_YANK],\n\tname2char[K_DELETE]: name2func[F_DELETE_CHAR],\n\tname2char[K_ENTER]:  name2func[F_ACCEPT_LINE],\n\tname2char[K_ESCAPE]: name2func[F_KILL_WHOLE_LINE],\n\tname2char[K_CTRL_N]: name2func[F_HISTORY_DOWN],\n\tname2char[K_CTRL_P]: name2func[F_HISTORY_UP],\n}\n\nvar scanMap = map[uint16]KeyFuncT{\n\tname2scan[K_CTRL]:   name2func[F_PASS],\n\tname2scan[K_DELETE]: name2func[F_DELETE_CHAR],\n\tname2scan[K_END]:    name2func[F_END_OF_LINE],\n\tname2scan[K_HOME]:   name2func[F_BEGINNING_OF_LINE],\n\tname2scan[K_LEFT]:   name2func[F_BACKWARD_CHAR],\n\tname2scan[K_RIGHT]:  name2func[F_FORARD_CHAR],\n\tname2scan[K_SHIFT]:  name2func[F_PASS],\n\tname2scan[K_DOWN]:   name2func[F_HISTORY_DOWN],\n\tname2scan[K_UP]:     name2func[F_HISTORY_UP],\n}\n\nvar altMap = map[uint16]KeyFuncT{\n\tname2alt[K_ALT_V]: name2func[F_YANK],\n}\n\nfunc normWord(src string) string {\n\treturn strings.Replace(strings.ToUpper(src), \"-\", \"_\", -1)\n}\n\nfunc BindKeyFunc(keyName string, funcValue KeyFuncT) error {\n\tkeyName_ := normWord(keyName)\n\tif altValue, altOk := name2alt[keyName_]; altOk {\n\t\taltMap[altValue] = funcValue\n\t\treturn nil\n\t} else if charValue, charOk := name2char[keyName_]; charOk {\n\t\tkeyMap[charValue] = funcValue\n\t\treturn nil\n\t} else if scanValue, scanOk := name2scan[keyName_]; scanOk {\n\t\tscanMap[scanValue] = funcValue\n\t\treturn nil\n\t} else {\n\t\treturn fmt.Errorf(\"%s: no such keyname\", keyName)\n\t}\n}\n\nfunc GetFunc(funcName string) (KeyFuncT, error) {\n\trc, ok := name2func[normWord(funcName)]\n\tif ok {\n\t\treturn rc, nil\n\t} else {\n\t\treturn nil, fmt.Errorf(\"%s: not found in the function-list\", funcName)\n\t}\n}\n\nfunc BindKeySymbol(keyName, funcName string) error {\n\tfuncValue, funcOk := name2func[normWord(funcName)]\n\tif !funcOk {\n\t\treturn fmt.Errorf(\"%s: no such function.\", funcName)\n\t}\n\treturn BindKeyFunc(keyName, funcValue)\n}\n\nfunc BindKeySymbolFunc(keyName, funcName string, funcValue KeyFuncT) error {\n\tname2func[normWord(funcName)] = funcValue\n\treturn BindKeyFunc(keyName, funcValue)\n}\n\nfunc ReadLinePromptFunc(promptFunc func() int) (string, Result) {\n\tthis := Buffer{Buffer: make([]rune, 20)}\n\tthis.ViewWidth, _ = GetScreenBufferInfo().ViewSize()\n\tthis.ViewWidth--\n\n\tthis.Prompt = promptFunc\n\tif this.Prompt != nil {\n\t\tthis.ViewWidth = this.ViewWidth - this.Prompt()\n\t}\n\tfor {\n\t\tstdOut.Flush()\n\t\tshineCursor()\n\t\tthis.Unicode, this.Keycode, this.ShiftState = GetKey()\n\t\tvar f KeyFuncT\n\t\tvar ok bool\n\t\tif (this.ShiftState&ALT_PRESSED) != 0 &&\n\t\t\t(this.ShiftState&CTRL_PRESSED) == 0 {\n\t\t\tf, ok = altMap[this.Keycode]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else if this.Unicode != 0 {\n\t\t\tf, ok = keyMap[this.Unicode]\n\t\t\tif !ok {\n\t\t\t\t\/\/f = KeyFuncInsertReport\n\t\t\t\tf = &KeyGoFuncT{KeyFuncInsertSelf}\n\t\t\t}\n\t\t} else {\n\t\t\tf, ok = scanMap[this.Keycode]\n\t\t\tif !ok {\n\t\t\t\tf = &KeyGoFuncT{KeyFuncPass}\n\t\t\t}\n\t\t}\n\t\trc := f.Call(&this)\n\t\tif rc != CONTINUE {\n\t\t\tstdOut.WriteRune('\\n')\n\t\t\tstdOut.Flush()\n\t\t\tresult := this.String()\n\t\t\tif result == \"\" {\n\t\t\t\tHistoryResetPointer()\n\t\t\t}\n\t\t\tif last := LastHistory(); last == nil || result != last.Line {\n\t\t\t\tHistoryPush(result)\n\t\t\t}\n\t\t\treturn result, rc\n\t\t}\n\t}\n}\n\n\/\/ Not used on NYAGOS. Provide this as library for other applications.\nfunc ReadLinePromptStr(promptStr string) (string, Result) {\n\treturn ReadLinePromptFunc(func() int {\n\t\tfmt.Print(promptStr)\n\t\treturn len(promptStr)\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package logrus\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\t\"sync\/atomic\"\n)\n\ntype Logger struct {\n\t\/\/ The logs are `io.Copy`'d to this in a mutex. It's common to set this to a\n\t\/\/ file, or leave it default which is `os.Stderr`. You can also set this to\n\t\/\/ something more adventorous, such as logging to Kafka.\n\tOut io.Writer\n\t\/\/ Hooks for the logger instance. These allow firing events based on logging\n\t\/\/ levels and log entries. For example, to send errors to an error tracking\n\t\/\/ service, log to StatsD or dump the core on fatal errors.\n\tHooks LevelHooks\n\t\/\/ All log entries pass through the formatter before logged to Out. The\n\t\/\/ included formatters are `TextFormatter` and `JSONFormatter` for which\n\t\/\/ TextFormatter is the default. In development (when a TTY is attached) it\n\t\/\/ logs with colors, but to a file it wouldn't. You can easily implement your\n\t\/\/ own that implements the `Formatter` interface, see the `README` or included\n\t\/\/ formatters for examples.\n\tFormatter Formatter\n\t\/\/ The logging level the logger should log at. This is typically (and defaults\n\t\/\/ to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be\n\t\/\/ logged.\n\tLevel Level\n\t\/\/ Used to sync writing to the log. Locking is enabled by Default\n\tmu MutexWrap\n\t\/\/ Reusable empty entry\n\tentryPool sync.Pool\n}\n\ntype MutexWrap struct {\n\tlock     sync.Mutex\n\tdisabled bool\n}\n\nfunc (mw *MutexWrap) Lock() {\n\tif !mw.disabled {\n\t\tmw.lock.Lock()\n\t}\n}\n\nfunc (mw *MutexWrap) Unlock() {\n\tif !mw.disabled {\n\t\tmw.lock.Unlock()\n\t}\n}\n\nfunc (mw *MutexWrap) Disable() {\n\tmw.disabled = true\n}\n\n\/\/ Creates a new logger. Configuration should be set by changing `Formatter`,\n\/\/ `Out` and `Hooks` directly on the default logger instance. You can also just\n\/\/ instantiate your own:\n\/\/\n\/\/    var log = &Logger{\n\/\/      Out: os.Stderr,\n\/\/      Formatter: new(JSONFormatter),\n\/\/      Hooks: make(LevelHooks),\n\/\/      Level: logrus.DebugLevel,\n\/\/    }\n\/\/\n\/\/ It's recommended to make this a global instance called `log`.\nfunc New() *Logger {\n\treturn &Logger{\n\t\tOut:       os.Stderr,\n\t\tFormatter: new(TextFormatter),\n\t\tHooks:     make(LevelHooks),\n\t\tLevel:     InfoLevel,\n\t}\n}\n\nfunc (logger *Logger) newEntry() *Entry {\n\tentry, ok := logger.entryPool.Get().(*Entry)\n\tif ok {\n\t\treturn entry\n\t}\n\treturn NewEntry(logger)\n}\n\nfunc (logger *Logger) releaseEntry(entry *Entry) {\n\tlogger.entryPool.Put(entry)\n}\n\n\/\/ Adds a field to the log entry, note that it doesn't log until you call\n\/\/ Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry.\n\/\/ If you want multiple fields, use `WithFields`.\nfunc (logger *Logger) WithField(key string, value interface{}) *Entry {\n\tentry := logger.newEntry()\n\tdefer logger.releaseEntry(entry)\n\treturn entry.WithField(key, value)\n}\n\n\/\/ Adds a struct of fields to the log entry. All it does is call `WithField` for\n\/\/ each `Field`.\nfunc (logger *Logger) WithFields(fields Fields) *Entry {\n\tentry := logger.newEntry()\n\tdefer logger.releaseEntry(entry)\n\treturn entry.WithFields(fields)\n}\n\n\/\/ Add an error as single field to the log entry.  All it does is call\n\/\/ `WithError` for the given `error`.\nfunc (logger *Logger) WithError(err error) *Entry {\n\tentry := logger.newEntry()\n\tdefer logger.releaseEntry(entry)\n\treturn entry.WithError(err)\n}\n\nfunc (logger *Logger) Debugf(format string, args ...interface{}) {\n\tif logger.level() >= DebugLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Debugf(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Infof(format string, args ...interface{}) {\n\tif logger.level() >= InfoLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Infof(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Printf(format string, args ...interface{}) {\n\tentry := logger.newEntry()\n\tentry.Printf(format, args...)\n\tlogger.releaseEntry(entry)\n}\n\nfunc (logger *Logger) Warnf(format string, args ...interface{}) {\n\tif logger.level() >= WarnLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Warnf(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Warningf(format string, args ...interface{}) {\n\tif logger.level() >= WarnLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Warnf(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Errorf(format string, args ...interface{}) {\n\tif logger.level() >= ErrorLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Errorf(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Fatalf(format string, args ...interface{}) {\n\tif logger.level() >= FatalLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Fatalf(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n\tExit(1)\n}\n\nfunc (logger *Logger) Panicf(format string, args ...interface{}) {\n\tif logger.level() >= PanicLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Panicf(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Debug(args ...interface{}) {\n\tif logger.level() >= DebugLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Debug(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Info(args ...interface{}) {\n\tif logger.level() >= InfoLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Info(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Print(args ...interface{}) {\n\tentry := logger.newEntry()\n\tentry.Info(args...)\n\tlogger.releaseEntry(entry)\n}\n\nfunc (logger *Logger) Warn(args ...interface{}) {\n\tif logger.level() >= WarnLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Warn(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Warning(args ...interface{}) {\n\tif logger.level() >= WarnLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Warn(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Error(args ...interface{}) {\n\tif logger.level() >= ErrorLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Error(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Fatal(args ...interface{}) {\n\tif logger.level() >= FatalLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Fatal(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n\tExit(1)\n}\n\nfunc (logger *Logger) Panic(args ...interface{}) {\n\tif logger.level() >= PanicLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Panic(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Debugln(args ...interface{}) {\n\tif logger.level() >= DebugLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Debugln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Infoln(args ...interface{}) {\n\tif logger.level() >= InfoLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Infoln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Println(args ...interface{}) {\n\tentry := logger.newEntry()\n\tentry.Println(args...)\n\tlogger.releaseEntry(entry)\n}\n\nfunc (logger *Logger) Warnln(args ...interface{}) {\n\tif logger.level() >= WarnLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Warnln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Warningln(args ...interface{}) {\n\tif logger.level() >= WarnLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Warnln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Errorln(args ...interface{}) {\n\tif logger.level() >= ErrorLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Errorln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Fatalln(args ...interface{}) {\n\tif logger.level() >= FatalLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Fatalln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n\tExit(1)\n}\n\nfunc (logger *Logger) Panicln(args ...interface{}) {\n\tif logger.level() >= PanicLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Panicln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\n\/\/When file is opened with appending mode, it's safe to\n\/\/write concurrently to a file (within 4k message on Linux).\n\/\/In these cases user can choose to disable the lock.\nfunc (logger *Logger) SetNoLock() {\n\tlogger.mu.Disable()\n}\n\nfunc (logger *Logger) level() Level {\n\treturn Level(atomic.LoadUint32((*uint32)(&logger.Level)))\n}\n\nfunc (logger *Logger) SetLevel(level Level) {\n\tatomic.StoreUint32((*uint32)(&logger.Level), uint32(level))\n}\n\nfunc (logger *Logger) AddHook(hook Hook) {\n\tlogger.mu.Lock()\n\tdefer logger.mu.Unlock()\n\tlogger.Hooks.Add(hook)\n}\n<commit_msg>Fix typo in docstring<commit_after>package logrus\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\t\"sync\/atomic\"\n)\n\ntype Logger struct {\n\t\/\/ The logs are `io.Copy`'d to this in a mutex. It's common to set this to a\n\t\/\/ file, or leave it default which is `os.Stderr`. You can also set this to\n\t\/\/ something more adventurous, such as logging to Kafka.\n\tOut io.Writer\n\t\/\/ Hooks for the logger instance. These allow firing events based on logging\n\t\/\/ levels and log entries. For example, to send errors to an error tracking\n\t\/\/ service, log to StatsD or dump the core on fatal errors.\n\tHooks LevelHooks\n\t\/\/ All log entries pass through the formatter before logged to Out. The\n\t\/\/ included formatters are `TextFormatter` and `JSONFormatter` for which\n\t\/\/ TextFormatter is the default. In development (when a TTY is attached) it\n\t\/\/ logs with colors, but to a file it wouldn't. You can easily implement your\n\t\/\/ own that implements the `Formatter` interface, see the `README` or included\n\t\/\/ formatters for examples.\n\tFormatter Formatter\n\t\/\/ The logging level the logger should log at. This is typically (and defaults\n\t\/\/ to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be\n\t\/\/ logged.\n\tLevel Level\n\t\/\/ Used to sync writing to the log. Locking is enabled by Default\n\tmu MutexWrap\n\t\/\/ Reusable empty entry\n\tentryPool sync.Pool\n}\n\ntype MutexWrap struct {\n\tlock     sync.Mutex\n\tdisabled bool\n}\n\nfunc (mw *MutexWrap) Lock() {\n\tif !mw.disabled {\n\t\tmw.lock.Lock()\n\t}\n}\n\nfunc (mw *MutexWrap) Unlock() {\n\tif !mw.disabled {\n\t\tmw.lock.Unlock()\n\t}\n}\n\nfunc (mw *MutexWrap) Disable() {\n\tmw.disabled = true\n}\n\n\/\/ Creates a new logger. Configuration should be set by changing `Formatter`,\n\/\/ `Out` and `Hooks` directly on the default logger instance. You can also just\n\/\/ instantiate your own:\n\/\/\n\/\/    var log = &Logger{\n\/\/      Out: os.Stderr,\n\/\/      Formatter: new(JSONFormatter),\n\/\/      Hooks: make(LevelHooks),\n\/\/      Level: logrus.DebugLevel,\n\/\/    }\n\/\/\n\/\/ It's recommended to make this a global instance called `log`.\nfunc New() *Logger {\n\treturn &Logger{\n\t\tOut:       os.Stderr,\n\t\tFormatter: new(TextFormatter),\n\t\tHooks:     make(LevelHooks),\n\t\tLevel:     InfoLevel,\n\t}\n}\n\nfunc (logger *Logger) newEntry() *Entry {\n\tentry, ok := logger.entryPool.Get().(*Entry)\n\tif ok {\n\t\treturn entry\n\t}\n\treturn NewEntry(logger)\n}\n\nfunc (logger *Logger) releaseEntry(entry *Entry) {\n\tlogger.entryPool.Put(entry)\n}\n\n\/\/ Adds a field to the log entry, note that it doesn't log until you call\n\/\/ Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry.\n\/\/ If you want multiple fields, use `WithFields`.\nfunc (logger *Logger) WithField(key string, value interface{}) *Entry {\n\tentry := logger.newEntry()\n\tdefer logger.releaseEntry(entry)\n\treturn entry.WithField(key, value)\n}\n\n\/\/ Adds a struct of fields to the log entry. All it does is call `WithField` for\n\/\/ each `Field`.\nfunc (logger *Logger) WithFields(fields Fields) *Entry {\n\tentry := logger.newEntry()\n\tdefer logger.releaseEntry(entry)\n\treturn entry.WithFields(fields)\n}\n\n\/\/ Add an error as single field to the log entry.  All it does is call\n\/\/ `WithError` for the given `error`.\nfunc (logger *Logger) WithError(err error) *Entry {\n\tentry := logger.newEntry()\n\tdefer logger.releaseEntry(entry)\n\treturn entry.WithError(err)\n}\n\nfunc (logger *Logger) Debugf(format string, args ...interface{}) {\n\tif logger.level() >= DebugLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Debugf(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Infof(format string, args ...interface{}) {\n\tif logger.level() >= InfoLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Infof(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Printf(format string, args ...interface{}) {\n\tentry := logger.newEntry()\n\tentry.Printf(format, args...)\n\tlogger.releaseEntry(entry)\n}\n\nfunc (logger *Logger) Warnf(format string, args ...interface{}) {\n\tif logger.level() >= WarnLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Warnf(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Warningf(format string, args ...interface{}) {\n\tif logger.level() >= WarnLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Warnf(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Errorf(format string, args ...interface{}) {\n\tif logger.level() >= ErrorLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Errorf(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Fatalf(format string, args ...interface{}) {\n\tif logger.level() >= FatalLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Fatalf(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n\tExit(1)\n}\n\nfunc (logger *Logger) Panicf(format string, args ...interface{}) {\n\tif logger.level() >= PanicLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Panicf(format, args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Debug(args ...interface{}) {\n\tif logger.level() >= DebugLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Debug(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Info(args ...interface{}) {\n\tif logger.level() >= InfoLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Info(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Print(args ...interface{}) {\n\tentry := logger.newEntry()\n\tentry.Info(args...)\n\tlogger.releaseEntry(entry)\n}\n\nfunc (logger *Logger) Warn(args ...interface{}) {\n\tif logger.level() >= WarnLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Warn(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Warning(args ...interface{}) {\n\tif logger.level() >= WarnLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Warn(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Error(args ...interface{}) {\n\tif logger.level() >= ErrorLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Error(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Fatal(args ...interface{}) {\n\tif logger.level() >= FatalLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Fatal(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n\tExit(1)\n}\n\nfunc (logger *Logger) Panic(args ...interface{}) {\n\tif logger.level() >= PanicLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Panic(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Debugln(args ...interface{}) {\n\tif logger.level() >= DebugLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Debugln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Infoln(args ...interface{}) {\n\tif logger.level() >= InfoLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Infoln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Println(args ...interface{}) {\n\tentry := logger.newEntry()\n\tentry.Println(args...)\n\tlogger.releaseEntry(entry)\n}\n\nfunc (logger *Logger) Warnln(args ...interface{}) {\n\tif logger.level() >= WarnLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Warnln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Warningln(args ...interface{}) {\n\tif logger.level() >= WarnLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Warnln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Errorln(args ...interface{}) {\n\tif logger.level() >= ErrorLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Errorln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\nfunc (logger *Logger) Fatalln(args ...interface{}) {\n\tif logger.level() >= FatalLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Fatalln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n\tExit(1)\n}\n\nfunc (logger *Logger) Panicln(args ...interface{}) {\n\tif logger.level() >= PanicLevel {\n\t\tentry := logger.newEntry()\n\t\tentry.Panicln(args...)\n\t\tlogger.releaseEntry(entry)\n\t}\n}\n\n\/\/When file is opened with appending mode, it's safe to\n\/\/write concurrently to a file (within 4k message on Linux).\n\/\/In these cases user can choose to disable the lock.\nfunc (logger *Logger) SetNoLock() {\n\tlogger.mu.Disable()\n}\n\nfunc (logger *Logger) level() Level {\n\treturn Level(atomic.LoadUint32((*uint32)(&logger.Level)))\n}\n\nfunc (logger *Logger) SetLevel(level Level) {\n\tatomic.StoreUint32((*uint32)(&logger.Level), uint32(level))\n}\n\nfunc (logger *Logger) AddHook(hook Hook) {\n\tlogger.mu.Lock()\n\tdefer logger.mu.Unlock()\n\tlogger.Hooks.Add(hook)\n}\n<|endoftext|>"}
{"text":"<commit_before>package libkb\n\nimport \"os\"\n\n\/\/ TrapKeypress is designed to read stdin, looking for Ctrl-C or\n\/\/ Ctrl-D.  When it receives either, it will shut down the client.\n\/\/ To use it, do this:\n\/\/\n\/\/ func x() {\n\/\/\tdone := make(chan bool)\n\/\/\tdefer close(done)\n\/\/\tgo libkb.TrapKeypress(done)\n\/\/\t\/\/ do something that takes a long time and doesn't prompt\n\/\/\t\/\/ the user for anything\n\/\/ }\n\/\/\n\/\/ When the function exits, TrapKeypress will stop.  It will\n\/\/ consume one more byte from stdin, however, as there is no way\n\/\/ to cancel the pending read.\n\/\/\n\/\/ This is only necessary when there is a long-running command\n\/\/ that doesn't use the ui to prompt the user.  For example,\n\/\/ logging in on a new device while it is waiting for the `sibkey\n\/\/ add` command to run on an existing device.\nfunc TrapKeypress(done chan bool) {\n\tkeys := make(chan byte)\n\tgo func() {\n\t\tbuf := make([]byte, 1)\n\t\tfor {\n\t\t\t_, err := os.Stdin.Read(buf)\n\t\t\tif err != nil {\n\t\t\t\tG.Log.Debug(\"stdin read error: %s\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase keys <- buf[0]:\n\t\t\tcase <-done:\n\t\t\t\tG.Log.Debug(\"TrapKeypress read goroutine stopping due to closed done chan\")\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase k := <-keys:\n\t\t\tif k == 3 || k == 4 {\n\t\t\t\t\/\/ ctrl-c or ctrl-d pressed\n\t\t\t\tG.Log.Debug(\"TrapKeypress trapped ctrl-c or ctrl-d\")\n\t\t\t\tG.Shutdown()\n\t\t\t\tG.Log.Error(\"interrupted\")\n\t\t\t\tos.Exit(3)\n\t\t\t}\n\t\tcase <-done:\n\t\t\tG.Log.Debug(\"TrapKeypress received on done chan, exiting\")\n\t\t\treturn\n\t\t}\n\t}\n}\n<commit_msg>Remove unused code press.go<commit_after><|endoftext|>"}
{"text":"<commit_before>\/* Licensed to the Apache Software Foundation (ASF) under one or more\ncontributor license agreements.  See the NOTICE file distributed with\nthis work for additional information regarding copyright ownership.\nThe ASF licenses this file to You under the Apache License, Version 2.0\n(the \"License\"); you may not use this file except in compliance with\nthe License.  You may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\npackage siesta\n\nimport (\n\t\"fmt\"\n\n\tlog \"github.com\/cihub\/seelog\"\n)\n\n\/\/Logger used by this client. Defaults to build-in logger with Info log level.\nvar Logger KafkaLogger = NewDefaultLogger(InfoLevel)\n\n\/\/ KafkaLogger is a logger interface. Lets you plug-in your custom logging library instead of using built-in one.\ntype KafkaLogger interface {\n\t\/\/Formats a given message according to given params to log with level Trace.\n\tTrace(message string, params ...interface{})\n\n\t\/\/Formats a given message according to given params to log with level Debug.\n\tDebug(message string, params ...interface{})\n\n\t\/\/Formats a given message according to given params to log with level Info.\n\tInfo(message string, params ...interface{})\n\n\t\/\/Formats a given message according to given params to log with level Warn.\n\tWarn(message string, params ...interface{})\n\n\t\/\/Formats a given message according to given params to log with level Error.\n\tError(message string, params ...interface{})\n\n\t\/\/Formats a given message according to given params to log with level Critical.\n\tCritical(message string, params ...interface{})\n}\n\n\/\/ LogLevel represents a logging level.\ntype LogLevel string\n\nconst (\n\t\/\/ TraceLevel is used for debugging to find problems in functions, variables etc.\n\tTraceLevel LogLevel = \"trace\"\n\n\t\/\/ DebugLevel is used for detailed system reports and diagnostic messages.\n\tDebugLevel LogLevel = \"debug\"\n\n\t\/\/ InfoLevel is used for general information about a running application.\n\tInfoLevel LogLevel = \"info\"\n\n\t\/\/ WarnLevel is used to indicate small errors and failures that should not happen normally but are recovered automatically.\n\tWarnLevel LogLevel = \"warn\"\n\n\t\/\/ ErrorLevel is used to indicate severe errors that affect application workflow and are not handled automatically.\n\tErrorLevel LogLevel = \"error\"\n\n\t\/\/ CriticalLevel is used to indicate fatal errors that may cause data corruption or loss.\n\tCriticalLevel LogLevel = \"critical\"\n)\n\n\/\/ Trace writes a given message with a given tag to log with level Trace.\nfunc Trace(tag interface{}, message interface{}) {\n\tLogger.Trace(fmt.Sprintf(\"[%s] %s\", tag, message))\n}\n\n\/\/ Tracef formats a given message according to given params with a given tag to log with level Trace.\nfunc Tracef(tag interface{}, message interface{}, params ...interface{}) {\n\tLogger.Trace(fmt.Sprintf(\"[%s] %s\", tag, message), params...)\n}\n\n\/\/ Debug writes a given message with a given tag to log with level Debug.\nfunc Debug(tag interface{}, message interface{}) {\n\tLogger.Debug(fmt.Sprintf(\"[%s] %s\", tag, message))\n}\n\n\/\/ Debugf formats a given message according to given params with a given tag to log with level Debug.\nfunc Debugf(tag interface{}, message interface{}, params ...interface{}) {\n\tLogger.Debug(fmt.Sprintf(\"[%s] %s\", tag, message), params...)\n}\n\n\/\/ Info writes a given message with a given tag to log with level Info.\nfunc Info(tag interface{}, message interface{}) {\n\tLogger.Info(fmt.Sprintf(\"[%s] %s\", tag, message))\n}\n\n\/\/ Infof formats a given message according to given params with a given tag to log with level Info.\nfunc Infof(tag interface{}, message interface{}, params ...interface{}) {\n\tLogger.Info(fmt.Sprintf(\"[%s] %s\", tag, message), params...)\n}\n\n\/\/ Warn writes a given message with a given tag to log with level Warn.\nfunc Warn(tag interface{}, message interface{}) {\n\tLogger.Warn(fmt.Sprintf(\"[%s] %s\", tag, message))\n}\n\n\/\/ Warnf formats a given message according to given params with a given tag to log with level Warn.\nfunc Warnf(tag interface{}, message interface{}, params ...interface{}) {\n\tLogger.Warn(fmt.Sprintf(\"[%s] %s\", tag, message), params...)\n}\n\n\/\/ Error writes a given message with a given tag to log with level Error.\nfunc Error(tag interface{}, message interface{}) {\n\tLogger.Error(fmt.Sprintf(\"[%s] %s\", tag, message))\n}\n\n\/\/ Errorf formats a given message according to given params with a given tag to log with level Error.\nfunc Errorf(tag interface{}, message interface{}, params ...interface{}) {\n\tLogger.Error(fmt.Sprintf(\"[%s] %s\", tag, message), params...)\n}\n\n\/\/ Critical writes a given message with a given tag to log with level Critical.\nfunc Critical(tag interface{}, message interface{}) {\n\tLogger.Critical(fmt.Sprintf(\"[%s] %s\", tag, message))\n}\n\n\/\/ Criticalf formats a given message according to given params with a given tag to log with level Critical.\nfunc Criticalf(tag interface{}, message interface{}, params ...interface{}) {\n\tLogger.Critical(fmt.Sprintf(\"[%s] %s\", tag, message), params...)\n}\n\n\/\/ DefaultLogger is a default implementation of KafkaLogger interface used in this client.\ntype DefaultLogger struct {\n\tlogger log.LoggerInterface\n}\n\n\/\/ NewDefaultLogger creates a new DefaultLogger that is configured to write messages to console with minimum log level Level.\nfunc NewDefaultLogger(Level LogLevel) *DefaultLogger {\n\tvar config = fmt.Sprintf(`<seelog minlevel=\"%s\">\n    <outputs formatid=\"main\">\n        <console \/>\n    <\/outputs>\n\n    <formats>\n        <format id=\"main\" format=\"%%Date\/%%Time [%%LEVEL] %%Msg%%n\"\/>\n    <\/formats>\n<\/seelog>`, Level)\n\tlogger, _ := log.LoggerFromConfigAsBytes([]byte(config))\n\treturn &DefaultLogger{logger}\n}\n\n\/\/ Trace formats a given message according to given params to log with level Trace.\nfunc (dl *DefaultLogger) Trace(message string, params ...interface{}) {\n\tdl.logger.Tracef(message, params...)\n}\n\n\/\/ Debug formats a given message according to given params to log with level Debug.\nfunc (dl *DefaultLogger) Debug(message string, params ...interface{}) {\n\tdl.logger.Debugf(message, params...)\n}\n\n\/\/ Info formats a given message according to given params to log with level Info.\nfunc (dl *DefaultLogger) Info(message string, params ...interface{}) {\n\tdl.logger.Infof(message, params...)\n}\n\n\/\/ Warn formats a given message according to given params to log with level Warn.\nfunc (dl *DefaultLogger) Warn(message string, params ...interface{}) {\n\tdl.logger.Warnf(message, params...)\n}\n\n\/\/ Error formats a given message according to given params to log with level Error.\nfunc (dl *DefaultLogger) Error(message string, params ...interface{}) {\n\tdl.logger.Errorf(message, params...)\n}\n\n\/\/ Critical formats a given message according to given params to log with level Critical.\nfunc (dl *DefaultLogger) Critical(message string, params ...interface{}) {\n\tdl.logger.Criticalf(message, params...)\n}\n<commit_msg>Replaced logger package to use gopkg.in<commit_after>\/* Licensed to the Apache Software Foundation (ASF) under one or more\ncontributor license agreements.  See the NOTICE file distributed with\nthis work for additional information regarding copyright ownership.\nThe ASF licenses this file to You under the Apache License, Version 2.0\n(the \"License\"); you may not use this file except in compliance with\nthe License.  You may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\npackage siesta\n\nimport (\n\t\"fmt\"\n\n\tlog \"gopkg.in\/cihub\/seelog.v2\"\n)\n\n\/\/Logger used by this client. Defaults to build-in logger with Info log level.\nvar Logger KafkaLogger = NewDefaultLogger(InfoLevel)\n\n\/\/ KafkaLogger is a logger interface. Lets you plug-in your custom logging library instead of using built-in one.\ntype KafkaLogger interface {\n\t\/\/Formats a given message according to given params to log with level Trace.\n\tTrace(message string, params ...interface{})\n\n\t\/\/Formats a given message according to given params to log with level Debug.\n\tDebug(message string, params ...interface{})\n\n\t\/\/Formats a given message according to given params to log with level Info.\n\tInfo(message string, params ...interface{})\n\n\t\/\/Formats a given message according to given params to log with level Warn.\n\tWarn(message string, params ...interface{})\n\n\t\/\/Formats a given message according to given params to log with level Error.\n\tError(message string, params ...interface{})\n\n\t\/\/Formats a given message according to given params to log with level Critical.\n\tCritical(message string, params ...interface{})\n}\n\n\/\/ LogLevel represents a logging level.\ntype LogLevel string\n\nconst (\n\t\/\/ TraceLevel is used for debugging to find problems in functions, variables etc.\n\tTraceLevel LogLevel = \"trace\"\n\n\t\/\/ DebugLevel is used for detailed system reports and diagnostic messages.\n\tDebugLevel LogLevel = \"debug\"\n\n\t\/\/ InfoLevel is used for general information about a running application.\n\tInfoLevel LogLevel = \"info\"\n\n\t\/\/ WarnLevel is used to indicate small errors and failures that should not happen normally but are recovered automatically.\n\tWarnLevel LogLevel = \"warn\"\n\n\t\/\/ ErrorLevel is used to indicate severe errors that affect application workflow and are not handled automatically.\n\tErrorLevel LogLevel = \"error\"\n\n\t\/\/ CriticalLevel is used to indicate fatal errors that may cause data corruption or loss.\n\tCriticalLevel LogLevel = \"critical\"\n)\n\n\/\/ Trace writes a given message with a given tag to log with level Trace.\nfunc Trace(tag interface{}, message interface{}) {\n\tLogger.Trace(fmt.Sprintf(\"[%s] %s\", tag, message))\n}\n\n\/\/ Tracef formats a given message according to given params with a given tag to log with level Trace.\nfunc Tracef(tag interface{}, message interface{}, params ...interface{}) {\n\tLogger.Trace(fmt.Sprintf(\"[%s] %s\", tag, message), params...)\n}\n\n\/\/ Debug writes a given message with a given tag to log with level Debug.\nfunc Debug(tag interface{}, message interface{}) {\n\tLogger.Debug(fmt.Sprintf(\"[%s] %s\", tag, message))\n}\n\n\/\/ Debugf formats a given message according to given params with a given tag to log with level Debug.\nfunc Debugf(tag interface{}, message interface{}, params ...interface{}) {\n\tLogger.Debug(fmt.Sprintf(\"[%s] %s\", tag, message), params...)\n}\n\n\/\/ Info writes a given message with a given tag to log with level Info.\nfunc Info(tag interface{}, message interface{}) {\n\tLogger.Info(fmt.Sprintf(\"[%s] %s\", tag, message))\n}\n\n\/\/ Infof formats a given message according to given params with a given tag to log with level Info.\nfunc Infof(tag interface{}, message interface{}, params ...interface{}) {\n\tLogger.Info(fmt.Sprintf(\"[%s] %s\", tag, message), params...)\n}\n\n\/\/ Warn writes a given message with a given tag to log with level Warn.\nfunc Warn(tag interface{}, message interface{}) {\n\tLogger.Warn(fmt.Sprintf(\"[%s] %s\", tag, message))\n}\n\n\/\/ Warnf formats a given message according to given params with a given tag to log with level Warn.\nfunc Warnf(tag interface{}, message interface{}, params ...interface{}) {\n\tLogger.Warn(fmt.Sprintf(\"[%s] %s\", tag, message), params...)\n}\n\n\/\/ Error writes a given message with a given tag to log with level Error.\nfunc Error(tag interface{}, message interface{}) {\n\tLogger.Error(fmt.Sprintf(\"[%s] %s\", tag, message))\n}\n\n\/\/ Errorf formats a given message according to given params with a given tag to log with level Error.\nfunc Errorf(tag interface{}, message interface{}, params ...interface{}) {\n\tLogger.Error(fmt.Sprintf(\"[%s] %s\", tag, message), params...)\n}\n\n\/\/ Critical writes a given message with a given tag to log with level Critical.\nfunc Critical(tag interface{}, message interface{}) {\n\tLogger.Critical(fmt.Sprintf(\"[%s] %s\", tag, message))\n}\n\n\/\/ Criticalf formats a given message according to given params with a given tag to log with level Critical.\nfunc Criticalf(tag interface{}, message interface{}, params ...interface{}) {\n\tLogger.Critical(fmt.Sprintf(\"[%s] %s\", tag, message), params...)\n}\n\n\/\/ DefaultLogger is a default implementation of KafkaLogger interface used in this client.\ntype DefaultLogger struct {\n\tlogger log.LoggerInterface\n}\n\n\/\/ NewDefaultLogger creates a new DefaultLogger that is configured to write messages to console with minimum log level Level.\nfunc NewDefaultLogger(Level LogLevel) *DefaultLogger {\n\tvar config = fmt.Sprintf(`<seelog minlevel=\"%s\">\n    <outputs formatid=\"main\">\n        <console \/>\n    <\/outputs>\n\n    <formats>\n        <format id=\"main\" format=\"%%Date\/%%Time [%%LEVEL] %%Msg%%n\"\/>\n    <\/formats>\n<\/seelog>`, Level)\n\tlogger, _ := log.LoggerFromConfigAsBytes([]byte(config))\n\treturn &DefaultLogger{logger}\n}\n\n\/\/ Trace formats a given message according to given params to log with level Trace.\nfunc (dl *DefaultLogger) Trace(message string, params ...interface{}) {\n\tdl.logger.Tracef(message, params...)\n}\n\n\/\/ Debug formats a given message according to given params to log with level Debug.\nfunc (dl *DefaultLogger) Debug(message string, params ...interface{}) {\n\tdl.logger.Debugf(message, params...)\n}\n\n\/\/ Info formats a given message according to given params to log with level Info.\nfunc (dl *DefaultLogger) Info(message string, params ...interface{}) {\n\tdl.logger.Infof(message, params...)\n}\n\n\/\/ Warn formats a given message according to given params to log with level Warn.\nfunc (dl *DefaultLogger) Warn(message string, params ...interface{}) {\n\tdl.logger.Warnf(message, params...)\n}\n\n\/\/ Error formats a given message according to given params to log with level Error.\nfunc (dl *DefaultLogger) Error(message string, params ...interface{}) {\n\tdl.logger.Errorf(message, params...)\n}\n\n\/\/ Critical formats a given message according to given params to log with level Critical.\nfunc (dl *DefaultLogger) Critical(message string, params ...interface{}) {\n\tdl.logger.Criticalf(message, params...)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ This file implements Sizes.\n\npackage types\n\n\/\/ Sizes defines the sizing functions for package unsafe.\ntype Sizes interface {\n\t\/\/ Alignof returns the alignment of a variable of type T.\n\t\/\/ Alignof must implement the alignment guarantees required by the spec.\n\tAlignof(T Type) int64\n\n\t\/\/ Offsetsof returns the offsets of the given struct fields, in bytes.\n\t\/\/ Offsetsof must implement the offset guarantees required by the spec.\n\tOffsetsof(fields []*Var) []int64\n\n\t\/\/ Sizeof returns the size of a variable of type T.\n\t\/\/ Sizeof must implement the size guarantees required by the spec.\n\tSizeof(T Type) int64\n}\n\n\/\/ StdSizes is a convenience type for creating commonly used Sizes.\n\/\/ It makes the following simplifying assumptions:\n\/\/\n\/\/\t- The size of explicitly sized basic types (int16, etc.) is the\n\/\/\t  specified size.\n\/\/\t- The size of strings, functions, and interfaces is 2*WordSize.\n\/\/\t- The size of slices is 3*WordSize.\n\/\/\t- All other types have size WordSize.\n\/\/\t- Arrays and structs are aligned per spec definition; all other\n\/\/\t  types are naturally aligned with a maximum alignment MaxAlign.\n\/\/\n\/\/ *StdSizes implements Sizes.\n\/\/\ntype StdSizes struct {\n\tWordSize int64 \/\/ word size in bytes - must be >= 4 (32bits)\n\tMaxAlign int64 \/\/ maximum alignment in bytes - must be >= 1\n}\n\nfunc (s *StdSizes) Alignof(T Type) int64 {\n\t\/\/ For arrays and structs, alignment is defined in terms\n\t\/\/ of alignment of the elements and fields, respectively.\n\tswitch t := T.Underlying().(type) {\n\tcase *Array:\n\t\t\/\/ spec: \"For a variable x of array type: unsafe.Alignof(x)\n\t\t\/\/ is the same as unsafe.Alignof(x[0]), but at least 1.\"\n\t\treturn s.Alignof(t.elem)\n\tcase *Struct:\n\t\t\/\/ spec: \"For a variable x of struct type: unsafe.Alignof(x)\n\t\t\/\/ is the largest of the values unsafe.Alignof(x.f) for each\n\t\t\/\/ field f of x, but at least 1.\"\n\t\tmax := int64(1)\n\t\tfor _, f := range t.fields {\n\t\t\tif a := s.Alignof(f.typ); a > max {\n\t\t\t\tmax = a\n\t\t\t}\n\t\t}\n\t\treturn max\n\t}\n\ta := s.Sizeof(T) \/\/ may be 0\n\t\/\/ spec: \"For a variable x of any type: unsafe.Alignof(x) is at least 1.\"\n\tif a < 1 {\n\t\treturn 1\n\t}\n\tif a > s.MaxAlign {\n\t\treturn s.MaxAlign\n\t}\n\treturn a\n}\n\nfunc (s *StdSizes) Offsetsof(fields []*Var) []int64 {\n\toffsets := make([]int64, len(fields))\n\tvar o int64\n\tfor i, f := range fields {\n\t\ta := s.Alignof(f.typ)\n\t\to = align(o, a)\n\t\toffsets[i] = o\n\t\to += s.Sizeof(f.typ)\n\t}\n\treturn offsets\n}\n\nfunc (s *StdSizes) Sizeof(T Type) int64 {\n\tswitch t := T.Underlying().(type) {\n\tcase *Basic:\n\t\tif z := t.size; z > 0 {\n\t\t\treturn z\n\t\t}\n\t\tif t.kind == String {\n\t\t\treturn s.WordSize * 2\n\t\t}\n\tcase *Array:\n\t\ta := s.Alignof(t.elem)\n\t\tz := s.Sizeof(t.elem)\n\t\treturn align(z, a) * t.len \/\/ may be 0\n\tcase *Slice:\n\t\treturn s.WordSize * 3\n\tcase *Struct:\n\t\tn := t.NumFields()\n\t\tif n == 0 {\n\t\t\treturn 0\n\t\t}\n\t\toffsets := t.offsets\n\t\tif t.offsets == nil {\n\t\t\t\/\/ compute offsets on demand\n\t\t\toffsets = s.Offsetsof(t.fields)\n\t\t\tt.offsets = offsets\n\t\t}\n\t\treturn offsets[n-1] + s.Sizeof(t.fields[n-1].typ)\n\tcase *Signature, *Interface:\n\t\treturn s.WordSize * 2\n\t}\n\treturn s.WordSize \/\/ catch-all\n}\n\n\/\/ stdSizes is used if Config.Sizes == nil.\nvar stdSizes = StdSizes{8, 8}\n\nfunc (conf *Config) alignof(T Type) int64 {\n\tif s := conf.Sizes; s != nil {\n\t\tif a := s.Alignof(T); a >= 1 {\n\t\t\treturn a\n\t\t}\n\t\tpanic(\"Config.Sizes.Alignof returned an alignment < 1\")\n\t}\n\treturn stdSizes.Alignof(T)\n}\n\nfunc (conf *Config) offsetsof(T *Struct) []int64 {\n\toffsets := T.offsets\n\tif offsets == nil && T.NumFields() > 0 {\n\t\t\/\/ compute offsets on demand\n\t\tif s := conf.Sizes; s != nil {\n\t\t\toffsets = s.Offsetsof(T.fields)\n\t\t\t\/\/ sanity checks\n\t\t\tif len(offsets) != T.NumFields() {\n\t\t\t\tpanic(\"Config.Sizes.Offsetsof returned the wrong number of offsets\")\n\t\t\t}\n\t\t\tfor _, o := range offsets {\n\t\t\t\tif o < 0 {\n\t\t\t\t\tpanic(\"Config.Sizes.Offsetsof returned an offset < 0\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\toffsets = stdSizes.Offsetsof(T.fields)\n\t\t}\n\t\tT.offsets = offsets\n\t}\n\treturn offsets\n}\n\n\/\/ offsetof returns the offset of the field specified via\n\/\/ the index sequence relative to typ. All embedded fields\n\/\/ must be structs (rather than pointer to structs).\nfunc (conf *Config) offsetof(typ Type, index []int) int64 {\n\tvar o int64\n\tfor _, i := range index {\n\t\ts := typ.Underlying().(*Struct)\n\t\to += conf.offsetsof(s)[i]\n\t\ttyp = s.fields[i].typ\n\t}\n\treturn o\n}\n\nfunc (conf *Config) sizeof(T Type) int64 {\n\tif s := conf.Sizes; s != nil {\n\t\tif z := s.Sizeof(T); z >= 0 {\n\t\t\treturn z\n\t\t}\n\t\tpanic(\"Config.Sizes.Sizeof returned a size < 0\")\n\t}\n\treturn stdSizes.Sizeof(T)\n}\n\n\/\/ align returns the smallest y >= x such that y % a == 0.\nfunc align(x, a int64) int64 {\n\ty := x + a - 1\n\treturn y - y%a\n}\n<commit_msg>go.tools\/go\/types: use WordSize as function pointer size<commit_after>\/\/ Copyright 2013 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ This file implements Sizes.\n\npackage types\n\n\/\/ Sizes defines the sizing functions for package unsafe.\ntype Sizes interface {\n\t\/\/ Alignof returns the alignment of a variable of type T.\n\t\/\/ Alignof must implement the alignment guarantees required by the spec.\n\tAlignof(T Type) int64\n\n\t\/\/ Offsetsof returns the offsets of the given struct fields, in bytes.\n\t\/\/ Offsetsof must implement the offset guarantees required by the spec.\n\tOffsetsof(fields []*Var) []int64\n\n\t\/\/ Sizeof returns the size of a variable of type T.\n\t\/\/ Sizeof must implement the size guarantees required by the spec.\n\tSizeof(T Type) int64\n}\n\n\/\/ StdSizes is a convenience type for creating commonly used Sizes.\n\/\/ It makes the following simplifying assumptions:\n\/\/\n\/\/\t- The size of explicitly sized basic types (int16, etc.) is the\n\/\/\t  specified size.\n\/\/\t- The size of strings and interfaces is 2*WordSize.\n\/\/\t- The size of slices is 3*WordSize.\n\/\/\t- All other types have size WordSize.\n\/\/\t- Arrays and structs are aligned per spec definition; all other\n\/\/\t  types are naturally aligned with a maximum alignment MaxAlign.\n\/\/\n\/\/ *StdSizes implements Sizes.\n\/\/\ntype StdSizes struct {\n\tWordSize int64 \/\/ word size in bytes - must be >= 4 (32bits)\n\tMaxAlign int64 \/\/ maximum alignment in bytes - must be >= 1\n}\n\nfunc (s *StdSizes) Alignof(T Type) int64 {\n\t\/\/ For arrays and structs, alignment is defined in terms\n\t\/\/ of alignment of the elements and fields, respectively.\n\tswitch t := T.Underlying().(type) {\n\tcase *Array:\n\t\t\/\/ spec: \"For a variable x of array type: unsafe.Alignof(x)\n\t\t\/\/ is the same as unsafe.Alignof(x[0]), but at least 1.\"\n\t\treturn s.Alignof(t.elem)\n\tcase *Struct:\n\t\t\/\/ spec: \"For a variable x of struct type: unsafe.Alignof(x)\n\t\t\/\/ is the largest of the values unsafe.Alignof(x.f) for each\n\t\t\/\/ field f of x, but at least 1.\"\n\t\tmax := int64(1)\n\t\tfor _, f := range t.fields {\n\t\t\tif a := s.Alignof(f.typ); a > max {\n\t\t\t\tmax = a\n\t\t\t}\n\t\t}\n\t\treturn max\n\t}\n\ta := s.Sizeof(T) \/\/ may be 0\n\t\/\/ spec: \"For a variable x of any type: unsafe.Alignof(x) is at least 1.\"\n\tif a < 1 {\n\t\treturn 1\n\t}\n\tif a > s.MaxAlign {\n\t\treturn s.MaxAlign\n\t}\n\treturn a\n}\n\nfunc (s *StdSizes) Offsetsof(fields []*Var) []int64 {\n\toffsets := make([]int64, len(fields))\n\tvar o int64\n\tfor i, f := range fields {\n\t\ta := s.Alignof(f.typ)\n\t\to = align(o, a)\n\t\toffsets[i] = o\n\t\to += s.Sizeof(f.typ)\n\t}\n\treturn offsets\n}\n\nfunc (s *StdSizes) Sizeof(T Type) int64 {\n\tswitch t := T.Underlying().(type) {\n\tcase *Basic:\n\t\tif z := t.size; z > 0 {\n\t\t\treturn z\n\t\t}\n\t\tif t.kind == String {\n\t\t\treturn s.WordSize * 2\n\t\t}\n\tcase *Array:\n\t\ta := s.Alignof(t.elem)\n\t\tz := s.Sizeof(t.elem)\n\t\treturn align(z, a) * t.len \/\/ may be 0\n\tcase *Slice:\n\t\treturn s.WordSize * 3\n\tcase *Struct:\n\t\tn := t.NumFields()\n\t\tif n == 0 {\n\t\t\treturn 0\n\t\t}\n\t\toffsets := t.offsets\n\t\tif t.offsets == nil {\n\t\t\t\/\/ compute offsets on demand\n\t\t\toffsets = s.Offsetsof(t.fields)\n\t\t\tt.offsets = offsets\n\t\t}\n\t\treturn offsets[n-1] + s.Sizeof(t.fields[n-1].typ)\n\tcase *Interface:\n\t\treturn s.WordSize * 2\n\t}\n\treturn s.WordSize \/\/ catch-all\n}\n\n\/\/ stdSizes is used if Config.Sizes == nil.\nvar stdSizes = StdSizes{8, 8}\n\nfunc (conf *Config) alignof(T Type) int64 {\n\tif s := conf.Sizes; s != nil {\n\t\tif a := s.Alignof(T); a >= 1 {\n\t\t\treturn a\n\t\t}\n\t\tpanic(\"Config.Sizes.Alignof returned an alignment < 1\")\n\t}\n\treturn stdSizes.Alignof(T)\n}\n\nfunc (conf *Config) offsetsof(T *Struct) []int64 {\n\toffsets := T.offsets\n\tif offsets == nil && T.NumFields() > 0 {\n\t\t\/\/ compute offsets on demand\n\t\tif s := conf.Sizes; s != nil {\n\t\t\toffsets = s.Offsetsof(T.fields)\n\t\t\t\/\/ sanity checks\n\t\t\tif len(offsets) != T.NumFields() {\n\t\t\t\tpanic(\"Config.Sizes.Offsetsof returned the wrong number of offsets\")\n\t\t\t}\n\t\t\tfor _, o := range offsets {\n\t\t\t\tif o < 0 {\n\t\t\t\t\tpanic(\"Config.Sizes.Offsetsof returned an offset < 0\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\toffsets = stdSizes.Offsetsof(T.fields)\n\t\t}\n\t\tT.offsets = offsets\n\t}\n\treturn offsets\n}\n\n\/\/ offsetof returns the offset of the field specified via\n\/\/ the index sequence relative to typ. All embedded fields\n\/\/ must be structs (rather than pointer to structs).\nfunc (conf *Config) offsetof(typ Type, index []int) int64 {\n\tvar o int64\n\tfor _, i := range index {\n\t\ts := typ.Underlying().(*Struct)\n\t\to += conf.offsetsof(s)[i]\n\t\ttyp = s.fields[i].typ\n\t}\n\treturn o\n}\n\nfunc (conf *Config) sizeof(T Type) int64 {\n\tif s := conf.Sizes; s != nil {\n\t\tif z := s.Sizeof(T); z >= 0 {\n\t\t\treturn z\n\t\t}\n\t\tpanic(\"Config.Sizes.Sizeof returned a size < 0\")\n\t}\n\treturn stdSizes.Sizeof(T)\n}\n\n\/\/ align returns the smallest y >= x such that y % a == 0.\nfunc align(x, a int64) int64 {\n\ty := x + a - 1\n\treturn y - y%a\n}\n<|endoftext|>"}
{"text":"<commit_before>package logger\r\n\r\nimport (\r\n\t\"bytes\"\r\n\t\"encoding\/json\"\r\n\t\"fmt\"\r\n\t\"log\"\r\n\t\"os\"\r\n\t\"strconv\"\r\n\t\"sync\"\r\n\t\"time\"\r\n)\r\n\r\nconst (\r\n\t_VER string = \"1.0.0\"\r\n)\r\n\r\ntype UNIT int64\r\n\r\nconst (\r\n\t_       = iota\r\n\tKB UNIT = 1 << (iota * 10)\r\n\tMB\r\n\tGB\r\n\tTB\r\n)\r\n\r\nconst (\r\n\tLOG int = iota\r\n\tDEBUG\r\n\tINFO\r\n\tWARN\r\n\tERROR\r\n\tFATAL\r\n)\r\n\r\nconst (\r\n\tOS_LINUX = iota\r\n\tOS_X\r\n\tOS_WIN\r\n\tOS_OTHERS\r\n)\r\n\r\n\/\/日志结构对象\r\nvar logObj *LogFile\r\nvar logLevel = 1\r\nvar maxFileSize int64\r\nvar maxFileCount int32\r\nvar dailyFlag bool\r\nvar consoleAppender = false\r\n\r\nconst (\r\n\t\/\/TimeDayFormat 日期格式化到日\r\n\tTimeDayFormat = \"2006-01-02\"\r\n\t\/\/TimeFormat 日期格式化到秒\r\n\tTimeFormat = \"2006-01-02 15:04:05\"\r\n)\r\n\r\nvar logFormat = \"%s %s:%d %s %s\"\r\nvar logObjFormat = \"%s %s:%d %s %s %s %s\"\r\nvar consoleFormat = \"%s:%d %s %s\"\r\n\r\n\/\/SetConsole 设置终端是否显示\r\nfunc SetConsole(isConsole bool) {\r\n\tconsoleAppender = isConsole\r\n}\r\n\r\n\/\/SetLevel 设置日子级别\r\nfunc SetLevel(_level int) {\r\n\tlogLevel = _level\r\n}\r\n\r\n\/\/RollingLogger 生成按文件大小及数量分割日子类\r\nfunc RollingLogger(fileDir, fileName string, maxNumber int32, maxSize int64, _unit UNIT) {\r\n\trollingLogger(fileDir, fileName, maxNumber, maxSize, _unit)\r\n}\r\n\r\n\/\/SetRollingFile 生成按文件大小及数量分割日子类\r\nfunc SetRollingFile(fileDir, fileName string, maxNumber int32, maxSize int64, _unit UNIT) {\r\n\trollingLogger(fileDir, fileName, maxNumber, maxSize, _unit)\r\n}\r\n\r\nfunc rollingLogger(fileDir, fileName string, maxNumber int32, maxSize int64, _unit UNIT) {\r\n\tmaxFileCount = maxNumber\r\n\tmaxFileSize = maxSize * int64(_unit)\r\n\tdailyFlag = false\r\n\tlogObj = &LogFile{dir: fileDir, filename: fileName, mu: new(sync.Mutex)}\r\n\tlogObj.mu.Lock()\r\n\tdefer logObj.mu.Unlock()\r\n\r\n\tlogObj.logfile, _ = os.OpenFile(fileDir+\"\/\"+fileName, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0777)\r\n\tfi, err := logObj.logfile.Stat()\r\n\tif err != nil {\r\n\t\tlog.Println(err.Error())\r\n\t\treturn\r\n\t}\r\n\tlogObj.filesize = fi.Size()\r\n}\r\n\r\n\/\/DailyLogger new按日期分割日子类\r\nfunc DailyLogger(fileDir, filename string) {\r\n\tdailyLogger(fileDir, filename)\r\n}\r\n\r\nfunc dailyLogger(fileDir, fileName string) {\r\n\tdailyFlag = true\r\n\tt, _ := time.Parse(TimeDayFormat, time.Now().Format(TimeDayFormat))\r\n\tlogObj = &LogFile{dir: fileDir, filename: fileName, _date: &t, mu: new(sync.Mutex)}\r\n\tlogObj.mu.Lock()\r\n\tdefer logObj.mu.Unlock()\r\n\r\n\tif !logObj.isMustRename() {\r\n\t\tvar err error\r\n\t\tlogObj.logfile, err = os.OpenFile(fileDir+\"\/\"+fileName, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0777)\r\n\t\tif err != nil {\r\n\t\t\tlog.Println(err.Error())\r\n\t\t}\r\n\t} else {\r\n\t\tlogObj.rename()\r\n\t}\r\n}\r\n\r\nfunc concat(delimiter string, input ...interface{}) string {\r\n\tbuffer := bytes.Buffer{}\r\n\tl := len(input)\r\n\tfor i := 0; i < l; i++ {\r\n\t\tbuffer.WriteString(fmt.Sprint(input[i]))\r\n\t\tif i < l-1 {\r\n\t\t\tbuffer.WriteString(delimiter)\r\n\t\t}\r\n\t}\r\n\treturn buffer.String()\r\n}\r\n\r\nfunc console(msg string) {\r\n\tif logObj == nil || logObj.logfile == nil || consoleAppender {\r\n\t\tlog.Print(msg)\r\n\t}\r\n}\r\n\r\nfunc buildJSONMessage(level int, l *LogObj, msg string) string {\r\n\tfile, line := getTraceFileLine()\r\n\tlogInfo := map[string]interface{}{\"atime\": time.Now().Format(TimeFormat), \"bfile\": file + \" \" + strconv.Itoa(line), \"clevel\": getTraceLevelName(level)}\r\n\r\n\tif l != nil {\r\n\t\tlogInfo[\"dlogid\"] = l.logid\r\n\t\tlogInfo[\"etag\"] = l.tag\r\n\t}\r\n\tlogInfo[\"msg\"] = msg\r\n\tresb, err := json.Marshal(logInfo)\r\n\tif err != nil {\r\n\t\tlog.Println(err.Error())\r\n\t\treturn \"\"\r\n\t}\r\n\treturn string(resb) + getOsEol()\r\n}\r\n\r\nfunc buildLogMessage(level int, l *LogObj, msg string) string {\r\n\tfile, line := getTraceFileLine()\r\n\tlogInfo := \"\"\r\n\tif l == nil {\r\n\t\tlogInfo = fmt.Sprintf(logFormat+getOsEol(), time.Now().Format(TimeFormat), file, line, getTraceLevelName(level), msg)\r\n\t} else {\r\n\t\tlogInfo = fmt.Sprintf(logObjFormat+getOsEol(), time.Now().Format(TimeFormat), file, line, l.logid, l.tag, getTraceLevelName(level), msg)\r\n\t}\r\n\treturn logInfo\r\n}\r\n\r\nfunc catchError() {\r\n\tif err := recover(); err != nil {\r\n\t\tlog.Println(\"err\", err)\r\n\t}\r\n}\r\n\r\n\/\/Trace write\r\nfunc Trace(level int, l *LogObj, v ...interface{}) bool {\r\n\tdefer catchError()\r\n\tif logObj != nil {\r\n\t\tlogObj.mu.Lock()\r\n\t\tdefer logObj.mu.Unlock()\r\n\t}\r\n\tmsg := concat(\" \", v...)\r\n\tlogStr := \"\"\r\n\tif l.json {\r\n\t\tlogStr = buildJSONMessage(level, l, msg)\r\n\t} else {\r\n\t\tlogStr = buildLogMessage(level, l, msg)\r\n\t}\r\n\tconsole(logStr)\r\n\tif v[0] != nil && v[0].(string) == \"remote\" {\r\n\t\tremoteMsg := concat(\" \", v[1:]...)\r\n\t\tgo httpLog(remoteMsg)\r\n\t}\r\n\tif level >= logLevel {\r\n\t\tif logObj != nil {\r\n\t\t\t_, err := logObj.write([]byte(logStr))\r\n\t\t\tif err != nil {\r\n\t\t\t\tlog.Println(err.Error())\r\n\t\t\t\treturn false\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}\r\n\r\n\/\/Log LOG\r\nfunc Log(v ...interface{}) bool {\r\n\treturn Trace(LOG, nil, v...)\r\n}\r\n\r\n\/\/Debug DEBUG\r\nfunc Debug(v ...interface{}) bool {\r\n\treturn Trace(DEBUG, nil, v...)\r\n}\r\n\r\n\/\/Info INFO\r\nfunc Info(v ...interface{}) bool {\r\n\treturn Trace(INFO, nil, v...)\r\n}\r\n\r\n\/\/Warn WARN\r\nfunc Warn(v ...interface{}) bool {\r\n\treturn Trace(WARN, nil, v...)\r\n}\r\n\r\n\/\/Error ERROR\r\nfunc Error(v ...interface{}) bool {\r\n\treturn Trace(ERROR, nil, v...)\r\n}\r\n\r\n\/\/Fatal FATAL\r\nfunc Fatal(v ...interface{}) bool {\r\n\treturn Trace(FATAL, nil, v...)\r\n}\r\n<commit_msg>modify nil pointer when write log<commit_after>package logger\r\n\r\nimport (\r\n\t\"bytes\"\r\n\t\"encoding\/json\"\r\n\t\"fmt\"\r\n\t\"log\"\r\n\t\"os\"\r\n\t\"strconv\"\r\n\t\"sync\"\r\n\t\"time\"\r\n)\r\n\r\nconst (\r\n\t_VER string = \"1.0.0\"\r\n)\r\n\r\ntype UNIT int64\r\n\r\nconst (\r\n\t_       = iota\r\n\tKB UNIT = 1 << (iota * 10)\r\n\tMB\r\n\tGB\r\n\tTB\r\n)\r\n\r\nconst (\r\n\tLOG int = iota\r\n\tDEBUG\r\n\tINFO\r\n\tWARN\r\n\tERROR\r\n\tFATAL\r\n)\r\n\r\nconst (\r\n\tOS_LINUX = iota\r\n\tOS_X\r\n\tOS_WIN\r\n\tOS_OTHERS\r\n)\r\n\r\n\/\/日志结构对象\r\nvar logObj *LogFile\r\nvar logLevel = 1\r\nvar maxFileSize int64\r\nvar maxFileCount int32\r\nvar dailyFlag bool\r\nvar consoleAppender = false\r\n\r\nconst (\r\n\t\/\/TimeDayFormat 日期格式化到日\r\n\tTimeDayFormat = \"2006-01-02\"\r\n\t\/\/TimeFormat 日期格式化到秒\r\n\tTimeFormat = \"2006-01-02 15:04:05\"\r\n)\r\n\r\nvar logFormat = \"%s %s:%d %s %s\"\r\nvar logObjFormat = \"%s %s:%d %s %s %s %s\"\r\nvar consoleFormat = \"%s:%d %s %s\"\r\n\r\n\/\/SetConsole 设置终端是否显示\r\nfunc SetConsole(isConsole bool) {\r\n\tconsoleAppender = isConsole\r\n}\r\n\r\n\/\/SetLevel 设置日子级别\r\nfunc SetLevel(_level int) {\r\n\tlogLevel = _level\r\n}\r\n\r\n\/\/RollingLogger 生成按文件大小及数量分割日子类\r\nfunc RollingLogger(fileDir, fileName string, maxNumber int32, maxSize int64, _unit UNIT) {\r\n\trollingLogger(fileDir, fileName, maxNumber, maxSize, _unit)\r\n}\r\n\r\n\/\/SetRollingFile 生成按文件大小及数量分割日子类\r\nfunc SetRollingFile(fileDir, fileName string, maxNumber int32, maxSize int64, _unit UNIT) {\r\n\trollingLogger(fileDir, fileName, maxNumber, maxSize, _unit)\r\n}\r\n\r\nfunc rollingLogger(fileDir, fileName string, maxNumber int32, maxSize int64, _unit UNIT) {\r\n\tmaxFileCount = maxNumber\r\n\tmaxFileSize = maxSize * int64(_unit)\r\n\tdailyFlag = false\r\n\tlogObj = &LogFile{dir: fileDir, filename: fileName, mu: new(sync.Mutex)}\r\n\tlogObj.mu.Lock()\r\n\tdefer logObj.mu.Unlock()\r\n\r\n\tlogObj.logfile, _ = os.OpenFile(fileDir+\"\/\"+fileName, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0777)\r\n\tfi, err := logObj.logfile.Stat()\r\n\tif err != nil {\r\n\t\tlog.Println(err.Error())\r\n\t\treturn\r\n\t}\r\n\tlogObj.filesize = fi.Size()\r\n}\r\n\r\n\/\/DailyLogger new按日期分割日子类\r\nfunc DailyLogger(fileDir, filename string) {\r\n\tdailyLogger(fileDir, filename)\r\n}\r\n\r\nfunc dailyLogger(fileDir, fileName string) {\r\n\tdailyFlag = true\r\n\tt, _ := time.Parse(TimeDayFormat, time.Now().Format(TimeDayFormat))\r\n\tlogObj = &LogFile{dir: fileDir, filename: fileName, _date: &t, mu: new(sync.Mutex)}\r\n\tlogObj.mu.Lock()\r\n\tdefer logObj.mu.Unlock()\r\n\r\n\tif !logObj.isMustRename() {\r\n\t\tvar err error\r\n\t\tlogObj.logfile, err = os.OpenFile(fileDir+\"\/\"+fileName, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0777)\r\n\t\tif err != nil {\r\n\t\t\tlog.Println(err.Error())\r\n\t\t}\r\n\t} else {\r\n\t\tlogObj.rename()\r\n\t}\r\n}\r\n\r\nfunc concat(delimiter string, input ...interface{}) string {\r\n\tbuffer := bytes.Buffer{}\r\n\tl := len(input)\r\n\tfor i := 0; i < l; i++ {\r\n\t\tbuffer.WriteString(fmt.Sprint(input[i]))\r\n\t\tif i < l-1 {\r\n\t\t\tbuffer.WriteString(delimiter)\r\n\t\t}\r\n\t}\r\n\treturn buffer.String()\r\n}\r\n\r\nfunc console(msg string) {\r\n\tif logObj == nil || logObj.logfile == nil || consoleAppender {\r\n\t\tlog.Print(msg)\r\n\t}\r\n}\r\n\r\nfunc buildJSONMessage(level int, l *LogObj, msg string) string {\r\n\tfile, line := getTraceFileLine()\r\n\tlogInfo := map[string]interface{}{\"atime\": time.Now().Format(TimeFormat), \"bfile\": file + \" \" + strconv.Itoa(line), \"clevel\": getTraceLevelName(level)}\r\n\r\n\tif l != nil {\r\n\t\tlogInfo[\"dlogid\"] = l.logid\r\n\t\tlogInfo[\"etag\"] = l.tag\r\n\t}\r\n\tlogInfo[\"msg\"] = msg\r\n\tresb, err := json.Marshal(logInfo)\r\n\tif err != nil {\r\n\t\tlog.Println(err.Error())\r\n\t\treturn \"\"\r\n\t}\r\n\treturn string(resb) + getOsEol()\r\n}\r\n\r\nfunc buildLogMessage(level int, l *LogObj, msg string) string {\r\n\tfile, line := getTraceFileLine()\r\n\tlogInfo := \"\"\r\n\tif l == nil {\r\n\t\tlogInfo = fmt.Sprintf(logFormat+getOsEol(), time.Now().Format(TimeFormat), file, line, getTraceLevelName(level), msg)\r\n\t} else {\r\n\t\tlogInfo = fmt.Sprintf(logObjFormat+getOsEol(), time.Now().Format(TimeFormat), file, line, l.logid, l.tag, getTraceLevelName(level), msg)\r\n\t}\r\n\treturn logInfo\r\n}\r\n\r\nfunc catchError() {\r\n\tif err := recover(); err != nil {\r\n\t\tlog.Println(\"err\", err)\r\n\t}\r\n}\r\n\r\n\/\/Trace write\r\nfunc Trace(level int, l *LogObj, v ...interface{}) bool {\r\n\tdefer catchError()\r\n\tif logObj != nil {\r\n\t\tlogObj.mu.Lock()\r\n\t\tdefer logObj.mu.Unlock()\r\n\t}\r\n\tmsg := concat(\" \", v...)\r\n\tlogStr := \"\"\r\n\tif l != nil && l.json {\r\n\t\tlogStr = buildJSONMessage(level, l, msg)\r\n\t} else {\r\n\t\tlogStr = buildLogMessage(level, l, msg)\r\n\t}\r\n\tconsole(logStr)\r\n\tif v[0] != nil && v[0].(string) == \"remote\" {\r\n\t\tremoteMsg := concat(\" \", v[1:]...)\r\n\t\tgo httpLog(remoteMsg)\r\n\t}\r\n\tif level >= logLevel {\r\n\t\tif logObj != nil {\r\n\t\t\t_, err := logObj.write([]byte(logStr))\r\n\t\t\tif err != nil {\r\n\t\t\t\tlog.Println(err.Error())\r\n\t\t\t\treturn false\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}\r\n\r\n\/\/Log LOG\r\nfunc Log(v ...interface{}) bool {\r\n\treturn Trace(LOG, nil, v...)\r\n}\r\n\r\n\/\/Debug DEBUG\r\nfunc Debug(v ...interface{}) bool {\r\n\treturn Trace(DEBUG, nil, v...)\r\n}\r\n\r\n\/\/Info INFO\r\nfunc Info(v ...interface{}) bool {\r\n\treturn Trace(INFO, nil, v...)\r\n}\r\n\r\n\/\/Warn WARN\r\nfunc Warn(v ...interface{}) bool {\r\n\treturn Trace(WARN, nil, v...)\r\n}\r\n\r\n\/\/Error ERROR\r\nfunc Error(v ...interface{}) bool {\r\n\treturn Trace(ERROR, nil, v...)\r\n}\r\n\r\n\/\/Fatal FATAL\r\nfunc Fatal(v ...interface{}) bool {\r\n\treturn Trace(FATAL, nil, v...)\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage backup_test\n\nimport (\n\t\"github.com\/jacobsa\/comeback\/backup\"\n\t\"github.com\/jacobsa\/comeback\/backup\/mock\"\n\t\"github.com\/jacobsa\/comeback\/blob\"\n\t\"github.com\/jacobsa\/comeback\/blob\/mock\"\n\t\"github.com\/jacobsa\/comeback\/fs\/mock\"\n\t. \"github.com\/jacobsa\/ogletest\"\n\t\"testing\"\n)\n\nfunc TestDirectoryRestorer(t *testing.T) { RunTests(t) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype DirectoryRestorerTest struct {\n\tblobStore    mock_blob.MockStore\n\tfileSystem   mock_fs.MockFileSystem\n\tfileRestorer mock_backup.MockFileRestorer\n\twrapped      mock_backup.MockDirectoryRestorer\n\n\tdirRestorer backup.DirectoryRestorer\n\n\tscore    blob.Score\n\tbasePath string\n\trelPath  string\n\n\terr error\n}\n\nfunc init() { RegisterTestSuite(&DirectoryRestorerTest{}) }\n\nfunc (t *DirectoryRestorerTest) SetUp(i *TestInfo) {\n\tvar err error\n\n\t\/\/ Create dependencies.\n\tt.blobStore = mock_blob.NewMockStore(i.MockController, \"blobStore\")\n\tt.fileSystem = mock_fs.NewMockFileSystem(i.MockController, \"fileSystem\")\n\tt.fileRestorer = mock_backup.NewMockFileRestorer(i.MockController, \"fileRestorer\")\n\tt.wrapped = mock_backup.NewMockDirectoryRestorer(i.MockController, \"wrapped\")\n\n\t\/\/ Create restorer.\n\tt.dirRestorer, err = backup.NewNonRecursiveDirectoryRestorer(\n\t\tt.blobStore,\n\t\tt.fileSystem,\n\t\tt.fileRestorer,\n\t\tt.wrapped,\n\t)\n\n\tAssertEq(nil, err)\n}\n\nfunc (t *DirectoryRestorerTest) call() {\n\tt.err = t.dirRestorer.RestoreDirectory(t.score, t.basePath, t.relPath)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *DirectoryRestorerTest) CallsBlobStore() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) BlobStoreReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) BlobStoreReturnsJunk() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) NoEntries() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) FileEntry_CallsLinkForHardLink() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) FileEntry_LinkReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) FileEntry_LinkSucceeds() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) FileEntry_CallsRestoreFile() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) FileEntry_RestoreFileReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) DirEntry_ZeroScores() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) DirEntry_TwoScores() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) DirEntry_CallsMkdir() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) DirEntry_MkdirReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) DirEntry_CallsWrapped() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) DirEntry_WrappedReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) SymlinkEntry_CallsSymlink() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) SymlinkEntry_SymlinkReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) PipeEntry_CallsCreate() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) PipeEntry_CreateReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) BlockDevEntry_CallsCreate() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) BlockDevEntry_CreateReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) CharDevEntry_CallsCreate() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) CharDevEntry_CreateReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) CallsChown() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) ChownReturnsErrorForOneEntry() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) CallsSetModTime() {\n\tExpectEq(\"TODO\", \"\")\n\t\/\/ NOTE: Not for devices (see restore.go)\n}\n\nfunc (t *DirectoryRestorerTest) SetModTimeReturnsErrorForOneEntry() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) EverythingSucceeds() {\n\tExpectEq(\"TODO\", \"\")\n}\n<commit_msg>DirectoryRestorerTest.CallsBlobStore<commit_after>\/\/ Copyright 2012 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage backup_test\n\nimport (\n\t\"errors\"\n\t\"github.com\/jacobsa\/comeback\/backup\"\n\t\"github.com\/jacobsa\/comeback\/backup\/mock\"\n\t\"github.com\/jacobsa\/comeback\/blob\"\n\t\"github.com\/jacobsa\/comeback\/blob\/mock\"\n\t\"github.com\/jacobsa\/comeback\/fs\/mock\"\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t\"github.com\/jacobsa\/oglemock\"\n\t. \"github.com\/jacobsa\/ogletest\"\n\t\"testing\"\n)\n\nfunc TestDirectoryRestorer(t *testing.T) { RunTests(t) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype DirectoryRestorerTest struct {\n\tblobStore    mock_blob.MockStore\n\tfileSystem   mock_fs.MockFileSystem\n\tfileRestorer mock_backup.MockFileRestorer\n\twrapped      mock_backup.MockDirectoryRestorer\n\n\tdirRestorer backup.DirectoryRestorer\n\n\tscore    blob.Score\n\tbasePath string\n\trelPath  string\n\n\terr error\n}\n\nfunc init() { RegisterTestSuite(&DirectoryRestorerTest{}) }\n\nfunc (t *DirectoryRestorerTest) SetUp(i *TestInfo) {\n\tvar err error\n\n\t\/\/ Create dependencies.\n\tt.blobStore = mock_blob.NewMockStore(i.MockController, \"blobStore\")\n\tt.fileSystem = mock_fs.NewMockFileSystem(i.MockController, \"fileSystem\")\n\tt.fileRestorer = mock_backup.NewMockFileRestorer(i.MockController, \"fileRestorer\")\n\tt.wrapped = mock_backup.NewMockDirectoryRestorer(i.MockController, \"wrapped\")\n\n\t\/\/ Create restorer.\n\tt.dirRestorer, err = backup.NewNonRecursiveDirectoryRestorer(\n\t\tt.blobStore,\n\t\tt.fileSystem,\n\t\tt.fileRestorer,\n\t\tt.wrapped,\n\t)\n\n\tAssertEq(nil, err)\n}\n\nfunc (t *DirectoryRestorerTest) call() {\n\tt.err = t.dirRestorer.RestoreDirectory(t.score, t.basePath, t.relPath)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *DirectoryRestorerTest) CallsBlobStore() {\n\tt.score = []byte(\"taco\")\n\n\t\/\/ Blob store\n\tExpectCall(t.blobStore, \"Load\")(DeepEquals(t.score)).\n\t\tWillOnce(oglemock.Return(nil, errors.New(\"\")))\n\n\t\/\/ Call\n\tt.call()\n}\n\nfunc (t *DirectoryRestorerTest) BlobStoreReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) BlobStoreReturnsJunk() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) NoEntries() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) FileEntry_CallsLinkForHardLink() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) FileEntry_LinkReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) FileEntry_LinkSucceeds() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) FileEntry_CallsRestoreFile() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) FileEntry_RestoreFileReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) DirEntry_ZeroScores() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) DirEntry_TwoScores() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) DirEntry_CallsMkdir() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) DirEntry_MkdirReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) DirEntry_CallsWrapped() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) DirEntry_WrappedReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) SymlinkEntry_CallsSymlink() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) SymlinkEntry_SymlinkReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) PipeEntry_CallsCreate() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) PipeEntry_CreateReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) BlockDevEntry_CallsCreate() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) BlockDevEntry_CreateReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) CharDevEntry_CallsCreate() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) CharDevEntry_CreateReturnsError() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) CallsChown() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) ChownReturnsErrorForOneEntry() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) CallsSetModTime() {\n\tExpectEq(\"TODO\", \"\")\n\t\/\/ NOTE: Not for devices (see restore.go)\n}\n\nfunc (t *DirectoryRestorerTest) SetModTimeReturnsErrorForOneEntry() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *DirectoryRestorerTest) EverythingSucceeds() {\n\tExpectEq(\"TODO\", \"\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package ln\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n)\n\n\/\/ Priority represents the importance of an Event.\ntype Priority int\n\nconst (\n\t\/\/ PriEmergency is the emergency priority, and is the highest.\n\tPriEmergency Priority = iota\n\t\/\/ PriAlert is the alert priority\n\tPriAlert\n\t\/\/ PriCritical is the critical priority\n\tPriCritical\n\t\/\/ PriError is the error priority.\n\tPriError\n\t\/\/ PriWarning is the warning priority\n\tPriWarning\n\t\/\/ PriNotice is the notice priority\n\tPriNotice\n\t\/\/ PriInfo is the info priority\n\tPriInfo\n\t\/\/ PriDebug is the debug priority.\n\tPriDebug\n)\n\nvar priStrings = []string{\n\t\"emerg\",\n\t\"alert\",\n\t\"crit\",\n\t\"error\",\n\t\"warn\",\n\t\"notice\",\n\t\"info\",\n\t\"debug\",\n}\n\nfunc (p Priority) String() string {\n\tif int(p) < len(priStrings) {\n\t\treturn priStrings[p]\n\t}\n\n\treturn \"UNKNOWN\"\n}\n\n\/\/ Logger holds the current priority and list of filters\ntype Logger struct {\n\tPri     Priority\n\tFilters []Filter\n}\n\n\/\/ DefaultLogger is the default implementation of Logger\nvar DefaultLogger *Logger\n\nfunc init() {\n\tvar defaultFilters []Filter\n\n\t\/\/ Default to STDOUT for logging, but allow LN_OUT to change it.\n\tout := os.Stdout\n\tif os.Getenv(\"LN_OUT\") == \"<stderr>\" {\n\t\tout = os.Stderr\n\t}\n\n\t\/\/ Default to INFO for the level, but allow LN_PRI to change it.\n\tpri := PriInfo\n\tif lnPri := os.Getenv(\"LN_PRI\"); lnPri != \"\" {\n\t\tfor idx, p := range priStrings {\n\t\t\tif p == lnPri {\n\t\t\t\tpri = Priority(idx)\n\t\t\t}\n\t\t}\n\t}\n\n\tdefaultFilters = append(defaultFilters, NewWriterFilter(out, nil))\n\n\tDefaultLogger = &Logger{\n\t\tPri:     pri,\n\t\tFilters: defaultFilters,\n\t}\n\n}\n\n\/\/ F is a key-value mapping for structured data.\ntype F map[string]interface{}\n\n\/\/ Event represents an event\ntype Event struct {\n\tPri     Priority\n\tTime    time.Time\n\tData    F\n\tMessage string\n}\n\n\/\/ Log is the generic logging method.\nfunc (l *Logger) Log(p Priority, xs ...interface{}) {\n\tif l.Pri < p {\n\t\treturn \/\/ don't log\n\t}\n\n\tvar bits []interface{}\n\tevent := Event{Pri: p, Time: time.Now()}\n\n\t\/\/ Assemble the event\n\tfor _, b := range xs {\n\t\tswitch b.(type) {\n\t\tcase F:\n\t\t\tbf := b.(F)\n\t\t\tif event.Data == nil {\n\t\t\t\tevent.Data = bf\n\t\t\t} else {\n\t\t\t\tfor k, v := range bf {\n\t\t\t\t\tevent.Data[k] = v\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\tbits = append(bits, b)\n\t\t}\n\t}\n\n\tevent.Message = fmt.Sprint(bits...)\n\n\tif l.Pri == PriDebug {\n\t\tframe := callersFrame()\n\t\tevent.Data[\"_lineno\"] = frame.lineno\n\t\tevent.Data[\"_function\"] = frame.function\n\t\tevent.Data[\"_filename\"] = frame.filename\n\t}\n\n\tl.filter(event)\n}\n\nfunc (l *Logger) filter(e Event) {\n\tfor _, f := range l.Filters {\n\t\tif !f.Apply(e) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ Emergency sets the priority of this event to PriEmergency\nfunc (l *Logger) Emergency(xs ...interface{}) {\n\tl.Log(PriEmergency, xs...)\n}\n\n\/\/ Alert sets the priority of this event to PriAlert\nfunc (l *Logger) Alert(xs ...interface{}) {\n\tl.Log(PriAlert, xs...)\n}\n\n\/\/ Critical sets the priority of this event to PriCritical\nfunc (l *Logger) Critical(xs ...interface{}) {\n\tl.Log(PriCritical, xs...)\n}\n\n\/\/ Error sets the priority of this event to PriError\nfunc (l *Logger) Error(xs ...interface{}) {\n\tl.Log(PriError, xs...)\n}\n\n\/\/ Warning sets the priority of this event to PriWarning\nfunc (l *Logger) Warning(xs ...interface{}) {\n\tl.Log(PriWarning, xs...)\n}\n\n\/\/ Notice sets the priority of this event to PriNotice\nfunc (l *Logger) Notice(xs ...interface{}) {\n\tl.Log(PriNotice, xs...)\n}\n\n\/\/ Info sets the priority of this event to PriInfo\nfunc (l *Logger) Info(xs ...interface{}) {\n\tl.Log(PriInfo, xs...)\n}\n\n\/\/ Debug sets the priority of this event to PriDebug\nfunc (l *Logger) Debug(xs ...interface{}) {\n\tl.Log(PriDebug, xs...)\n}\n\n\/\/ Default Implementation\n\n\/\/ Emergency sets the priority of this event to PriEmergency\nfunc Emergency(xs ...interface{}) {\n\tDefaultLogger.Log(PriEmergency, xs...)\n}\n\n\/\/ Alert sets the priority of this event to PriAlert\nfunc Alert(xs ...interface{}) {\n\tDefaultLogger.Log(PriAlert, xs...)\n}\n\n\/\/ Critical sets the priority of this event to PriCritical\nfunc Critical(xs ...interface{}) {\n\tDefaultLogger.Log(PriCritical, xs...)\n}\n\n\/\/ Error sets the priority of this event to PriError\nfunc Error(xs ...interface{}) {\n\tDefaultLogger.Log(PriError, xs...)\n}\n\n\/\/ Warning sets the priority of this event to PriWarning\nfunc Warning(xs ...interface{}) {\n\tDefaultLogger.Log(PriWarning, xs...)\n}\n\n\/\/ Notice sets the priority of this event to PriNotice\nfunc Notice(xs ...interface{}) {\n\tDefaultLogger.Log(PriNotice, xs...)\n}\n\n\/\/ Info sets the priority of this event to PriInfo\nfunc Info(xs ...interface{}) {\n\tDefaultLogger.Log(PriInfo, xs...)\n}\n\n\/\/ Debug sets the priority of this event to PriDebug\nfunc Debug(xs ...interface{}) {\n\tDefaultLogger.Log(PriDebug, xs...)\n}\n<commit_msg>panic! when event's data is nil.<commit_after>package ln\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n)\n\n\/\/ Priority represents the importance of an Event.\ntype Priority int\n\nconst (\n\t\/\/ PriEmergency is the emergency priority, and is the highest.\n\tPriEmergency Priority = iota\n\t\/\/ PriAlert is the alert priority\n\tPriAlert\n\t\/\/ PriCritical is the critical priority\n\tPriCritical\n\t\/\/ PriError is the error priority.\n\tPriError\n\t\/\/ PriWarning is the warning priority\n\tPriWarning\n\t\/\/ PriNotice is the notice priority\n\tPriNotice\n\t\/\/ PriInfo is the info priority\n\tPriInfo\n\t\/\/ PriDebug is the debug priority.\n\tPriDebug\n)\n\nvar priStrings = []string{\n\t\"emerg\",\n\t\"alert\",\n\t\"crit\",\n\t\"error\",\n\t\"warn\",\n\t\"notice\",\n\t\"info\",\n\t\"debug\",\n}\n\nfunc (p Priority) String() string {\n\tif int(p) < len(priStrings) {\n\t\treturn priStrings[p]\n\t}\n\n\treturn \"UNKNOWN\"\n}\n\n\/\/ Logger holds the current priority and list of filters\ntype Logger struct {\n\tPri     Priority\n\tFilters []Filter\n}\n\n\/\/ DefaultLogger is the default implementation of Logger\nvar DefaultLogger *Logger\n\nfunc init() {\n\tvar defaultFilters []Filter\n\n\t\/\/ Default to STDOUT for logging, but allow LN_OUT to change it.\n\tout := os.Stdout\n\tif os.Getenv(\"LN_OUT\") == \"<stderr>\" {\n\t\tout = os.Stderr\n\t}\n\n\t\/\/ Default to INFO for the level, but allow LN_PRI to change it.\n\tpri := PriInfo\n\tif lnPri := os.Getenv(\"LN_PRI\"); lnPri != \"\" {\n\t\tfor idx, p := range priStrings {\n\t\t\tif p == lnPri {\n\t\t\t\tpri = Priority(idx)\n\t\t\t}\n\t\t}\n\t}\n\n\tdefaultFilters = append(defaultFilters, NewWriterFilter(out, nil))\n\n\tDefaultLogger = &Logger{\n\t\tPri:     pri,\n\t\tFilters: defaultFilters,\n\t}\n\n}\n\n\/\/ F is a key-value mapping for structured data.\ntype F map[string]interface{}\n\n\/\/ Event represents an event\ntype Event struct {\n\tPri     Priority\n\tTime    time.Time\n\tData    F\n\tMessage string\n}\n\n\/\/ Log is the generic logging method.\nfunc (l *Logger) Log(p Priority, xs ...interface{}) {\n\tif l.Pri < p {\n\t\treturn \/\/ don't log\n\t}\n\n\tvar bits []interface{}\n\tevent := Event{Pri: p, Time: time.Now()}\n\n\t\/\/ Assemble the event\n\tfor _, b := range xs {\n\t\tswitch b.(type) {\n\t\tcase F:\n\t\t\tbf := b.(F)\n\t\t\tif event.Data == nil {\n\t\t\t\tevent.Data = bf\n\t\t\t} else {\n\t\t\t\tfor k, v := range bf {\n\t\t\t\t\tevent.Data[k] = v\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\tbits = append(bits, b)\n\t\t}\n\t}\n\n\tevent.Message = fmt.Sprint(bits...)\n\n\tif l.Pri == PriDebug {\n\t\tframe := callersFrame()\n\t\tif event.Data == nil {\n\t\t\tevent.Data = make(F)\n\t\t}\n\t\tevent.Data[\"_lineno\"] = frame.lineno\n\t\tevent.Data[\"_function\"] = frame.function\n\t\tevent.Data[\"_filename\"] = frame.filename\n\t}\n\n\tl.filter(event)\n}\n\nfunc (l *Logger) filter(e Event) {\n\tfor _, f := range l.Filters {\n\t\tif !f.Apply(e) {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ Emergency sets the priority of this event to PriEmergency\nfunc (l *Logger) Emergency(xs ...interface{}) {\n\tl.Log(PriEmergency, xs...)\n}\n\n\/\/ Alert sets the priority of this event to PriAlert\nfunc (l *Logger) Alert(xs ...interface{}) {\n\tl.Log(PriAlert, xs...)\n}\n\n\/\/ Critical sets the priority of this event to PriCritical\nfunc (l *Logger) Critical(xs ...interface{}) {\n\tl.Log(PriCritical, xs...)\n}\n\n\/\/ Error sets the priority of this event to PriError\nfunc (l *Logger) Error(xs ...interface{}) {\n\tl.Log(PriError, xs...)\n}\n\n\/\/ Warning sets the priority of this event to PriWarning\nfunc (l *Logger) Warning(xs ...interface{}) {\n\tl.Log(PriWarning, xs...)\n}\n\n\/\/ Notice sets the priority of this event to PriNotice\nfunc (l *Logger) Notice(xs ...interface{}) {\n\tl.Log(PriNotice, xs...)\n}\n\n\/\/ Info sets the priority of this event to PriInfo\nfunc (l *Logger) Info(xs ...interface{}) {\n\tl.Log(PriInfo, xs...)\n}\n\n\/\/ Debug sets the priority of this event to PriDebug\nfunc (l *Logger) Debug(xs ...interface{}) {\n\tl.Log(PriDebug, xs...)\n}\n\n\/\/ Default Implementation\n\n\/\/ Emergency sets the priority of this event to PriEmergency\nfunc Emergency(xs ...interface{}) {\n\tDefaultLogger.Log(PriEmergency, xs...)\n}\n\n\/\/ Alert sets the priority of this event to PriAlert\nfunc Alert(xs ...interface{}) {\n\tDefaultLogger.Log(PriAlert, xs...)\n}\n\n\/\/ Critical sets the priority of this event to PriCritical\nfunc Critical(xs ...interface{}) {\n\tDefaultLogger.Log(PriCritical, xs...)\n}\n\n\/\/ Error sets the priority of this event to PriError\nfunc Error(xs ...interface{}) {\n\tDefaultLogger.Log(PriError, xs...)\n}\n\n\/\/ Warning sets the priority of this event to PriWarning\nfunc Warning(xs ...interface{}) {\n\tDefaultLogger.Log(PriWarning, xs...)\n}\n\n\/\/ Notice sets the priority of this event to PriNotice\nfunc Notice(xs ...interface{}) {\n\tDefaultLogger.Log(PriNotice, xs...)\n}\n\n\/\/ Info sets the priority of this event to PriInfo\nfunc Info(xs ...interface{}) {\n\tDefaultLogger.Log(PriInfo, xs...)\n}\n\n\/\/ Debug sets the priority of this event to PriDebug\nfunc Debug(xs ...interface{}) {\n\tDefaultLogger.Log(PriDebug, xs...)\n}\n<|endoftext|>"}
{"text":"<commit_before>package jshapi\n\nimport (\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/derekdowling\/go-json-spec-handler\"\n\t\"github.com\/derekdowling\/go-stdlogger\"\n)\n\n\/\/ ILogger is the default standard logger used in JSH API:\n\/\/ https:\/\/godoc.org\/github.com\/derekdowling\/goji2-logger#Logger\n\/\/ This should be compatible with almost all loggers including the std log package\n\/\/ and Logrus.\ntype ILogger std.Logger\n\n\/\/ Logger can be overridden with your own logger to utilize any custom features\n\/\/ it might have\nvar Logger ILogger = log.New(os.Stderr, \"jshapi: \", log.LstdFlags)\n\n\/\/ SendAndLog is a jsh wrapper function that first prepares a jsh.Sendable response,\n\/\/ and then handles logging 5XX errors that it encounters in the process.\nfunc SendAndLog(ctx context.Context, w http.ResponseWriter, r *http.Request, sendable jsh.Sendable) {\n\n\tintentionalErr, isType := sendable.(*jsh.Error)\n\tif isType && intentionalErr.Status() >= 500 {\n\t\tLogger.Printf(\"Returning ISE for: %s\", intentionalErr.Internal())\n\t}\n\n\tresponse, err := sendable.Prepare(r, true)\n\n\tif err != nil && response.HTTPStatus >= 500 {\n\t\tLogger.Printf(\"Error preparing response: %s\\n\", err.Internal())\n\t}\n\n\tsendErr := jsh.SendResponse(w, r, response)\n\tif sendErr != nil {\n\t\tLogger.Println(err.Error())\n\t}\n}\n<commit_msg>Removing weird sub-type<commit_after>package jshapi\n\nimport (\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/derekdowling\/go-json-spec-handler\"\n\t\"github.com\/derekdowling\/go-stdlogger\"\n)\n\n\/\/ Logger can be overridden with your own logger to utilize any custom features\n\/\/ it might have. Interface defined here: https:\/\/github.com\/derekdowling\/go-stdlogger\/blob\/master\/logger.go\nvar Logger std.Logger = log.New(os.Stderr, \"jshapi: \", log.LstdFlags)\n\n\/\/ SendAndLog is a jsh wrapper function that first prepares a jsh.Sendable response,\n\/\/ and then handles logging 5XX errors that it encounters in the process.\nfunc SendAndLog(ctx context.Context, w http.ResponseWriter, r *http.Request, sendable jsh.Sendable) {\n\n\tintentionalErr, isType := sendable.(*jsh.Error)\n\tif isType && intentionalErr.Status() >= 500 {\n\t\tLogger.Printf(\"Returning ISE for: %s\", intentionalErr.Internal())\n\t}\n\n\tresponse, err := sendable.Prepare(r, true)\n\n\tif err != nil && response.HTTPStatus >= 500 {\n\t\tLogger.Printf(\"Error preparing response: %s\\n\", err.Internal())\n\t}\n\n\tsendErr := jsh.SendResponse(w, r, response)\n\tif sendErr != nil {\n\t\tLogger.Println(err.Error())\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2011 Google Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage localdisk\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"camli\/blobref\"\n)\n\ntype readBlobRequest struct {\n\tch      chan<- blobref.SizedBlobRef\n\tafter   string\n\tremain  *uint \/\/ limit countdown\n\tdirRoot string\n\n\t\/\/ Not used on initial request, only on recursion\n\tblobPrefix, pathInto string\n}\n\ntype enumerateError struct {\n\tmsg string\n\terr os.Error\n}\n\nfunc (ee *enumerateError) String() string {\n\treturn fmt.Sprintf(\"Enumerate error: %s: %v\", ee.msg, ee.err)\n}\n\nfunc readBlobs(opts readBlobRequest) os.Error {\n\tdirFullPath := opts.dirRoot + \"\/\" + opts.pathInto\n\tdir, err := os.Open(dirFullPath)\n\tif err != nil {\n\t\treturn &enumerateError{\"localdisk: opening directory \" + dirFullPath, err}\n\t}\n\tdefer dir.Close()\n\tnames, err := dir.Readdirnames(32768)\n\tif err != nil {\n\t\treturn &enumerateError{\"localdisk: readdirnames of \" + dirFullPath, err}\n\t}\n\tsort.SortStrings(names)\n\tfor _, name := range names {\n\t\tif *opts.remain == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tif name == \"partition\" {\n\t\t\tcontinue\n\t\t}\n\t\tfullPath := dirFullPath + \"\/\" + name\n\t\tfi, err := os.Stat(fullPath)\n\t\tif err != nil {\n\t\t\treturn &enumerateError{\"localdisk: stat of file \" + fullPath, err}\n\t\t}\n\n\t\tif fi.IsDirectory() {\n\t\t\tvar newBlobPrefix string\n\t\t\tif opts.blobPrefix == \"\" {\n\t\t\t\tnewBlobPrefix = name + \"-\"\n\t\t\t} else {\n\t\t\t\tnewBlobPrefix = opts.blobPrefix + name\n\t\t\t}\n\t\t\tif len(opts.after) > 0 {\n\t\t\t\tcompareLen := len(newBlobPrefix)\n\t\t\t\tif len(opts.after) < compareLen {\n\t\t\t\t\tcompareLen = len(opts.after)\n\t\t\t\t}\n\t\t\t\tif newBlobPrefix[0:compareLen] < opts.after[0:compareLen] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tropts := opts\n\t\t\tropts.blobPrefix = newBlobPrefix\n\t\t\tropts.pathInto = opts.pathInto + \"\/\" + name\n\t\t\treadBlobs(ropts)\n\t\t\tcontinue\n\t\t}\n\n\t\tif fi.IsRegular() && strings.HasSuffix(name, \".dat\") {\n\t\t\tblobName := name[0 : len(name)-4]\n\t\t\tif blobName <= opts.after {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tblobRef := blobref.Parse(blobName)\n\t\t\tif blobRef != nil {\n\t\t\t\topts.ch <- blobref.SizedBlobRef{BlobRef: blobRef, Size: fi.Size}\n\t\t\t\t(*opts.remain)--\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (ds *DiskStorage) EnumerateBlobs(dest chan<- blobref.SizedBlobRef, after string, limit uint, waitSeconds int) os.Error {\n\tdirRoot := ds.PartitionRoot(ds.partition)\n\tlimitMutable := limit\n\tvar err os.Error\n\tdoScan := func() {\n\t\terr = readBlobs(readBlobRequest{\n\t\t\tch:      dest,\n\t\t\tdirRoot: dirRoot,\n\t\t\tafter:   after,\n\t\t\tremain:  &limitMutable,\n\t\t})\n\t}\n\tdoScan()\n\n\t\/\/ The not waiting case:\n\tif err != nil || limitMutable != limit || waitSeconds == 0 {\n\t\tclose(dest)\n\t\treturn err\n\t}\n\n\t\/\/ The case where we have to wait for waitSeconds for any blob\n\t\/\/ to possibly appear.\n\thub := ds.GetBlobHub()\n\tch := make(chan *blobref.BlobRef, 1)\n\thub.RegisterListener(ch)\n\tdefer hub.UnregisterListener(ch)\n\ttimer := time.NewTimer(int64(waitSeconds) * 1e9)\n\tdefer timer.Stop()\n\tselect {\n\tcase <-timer.C:\n\t\t\/\/ Done waiting.\n\t\treturn nil\n\tcase <-ch:\n\t\t\/\/ Don't actually care what it is, but _something_\n\t\t\/\/ arrived.  We can just re-scan.\n\t\t\/\/ TODO: might be better to just stat this one item\n\t\t\/\/ so there's no race?  But this is easier:\n\t\tdoScan()\n\t}\n\tclose(dest)\n\treturn err\n}\n<commit_msg>localdisk: use defer to reliably close the channel. missed a case on enumerate timeout before.<commit_after>\/*\nCopyright 2011 Google Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage localdisk\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"camli\/blobref\"\n)\n\ntype readBlobRequest struct {\n\tch      chan<- blobref.SizedBlobRef\n\tafter   string\n\tremain  *uint \/\/ limit countdown\n\tdirRoot string\n\n\t\/\/ Not used on initial request, only on recursion\n\tblobPrefix, pathInto string\n}\n\ntype enumerateError struct {\n\tmsg string\n\terr os.Error\n}\n\nfunc (ee *enumerateError) String() string {\n\treturn fmt.Sprintf(\"Enumerate error: %s: %v\", ee.msg, ee.err)\n}\n\nfunc readBlobs(opts readBlobRequest) os.Error {\n\tdirFullPath := opts.dirRoot + \"\/\" + opts.pathInto\n\tdir, err := os.Open(dirFullPath)\n\tif err != nil {\n\t\treturn &enumerateError{\"localdisk: opening directory \" + dirFullPath, err}\n\t}\n\tdefer dir.Close()\n\tnames, err := dir.Readdirnames(32768)\n\tif err != nil {\n\t\treturn &enumerateError{\"localdisk: readdirnames of \" + dirFullPath, err}\n\t}\n\tsort.SortStrings(names)\n\tfor _, name := range names {\n\t\tif *opts.remain == 0 {\n\t\t\treturn nil\n\t\t}\n\t\tif name == \"partition\" {\n\t\t\tcontinue\n\t\t}\n\t\tfullPath := dirFullPath + \"\/\" + name\n\t\tfi, err := os.Stat(fullPath)\n\t\tif err != nil {\n\t\t\treturn &enumerateError{\"localdisk: stat of file \" + fullPath, err}\n\t\t}\n\n\t\tif fi.IsDirectory() {\n\t\t\tvar newBlobPrefix string\n\t\t\tif opts.blobPrefix == \"\" {\n\t\t\t\tnewBlobPrefix = name + \"-\"\n\t\t\t} else {\n\t\t\t\tnewBlobPrefix = opts.blobPrefix + name\n\t\t\t}\n\t\t\tif len(opts.after) > 0 {\n\t\t\t\tcompareLen := len(newBlobPrefix)\n\t\t\t\tif len(opts.after) < compareLen {\n\t\t\t\t\tcompareLen = len(opts.after)\n\t\t\t\t}\n\t\t\t\tif newBlobPrefix[0:compareLen] < opts.after[0:compareLen] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tropts := opts\n\t\t\tropts.blobPrefix = newBlobPrefix\n\t\t\tropts.pathInto = opts.pathInto + \"\/\" + name\n\t\t\treadBlobs(ropts)\n\t\t\tcontinue\n\t\t}\n\n\t\tif fi.IsRegular() && strings.HasSuffix(name, \".dat\") {\n\t\t\tblobName := name[0 : len(name)-4]\n\t\t\tif blobName <= opts.after {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tblobRef := blobref.Parse(blobName)\n\t\t\tif blobRef != nil {\n\t\t\t\topts.ch <- blobref.SizedBlobRef{BlobRef: blobRef, Size: fi.Size}\n\t\t\t\t(*opts.remain)--\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (ds *DiskStorage) EnumerateBlobs(dest chan<- blobref.SizedBlobRef, after string, limit uint, waitSeconds int) os.Error {\n\tdefer close(dest)\n\n\tdirRoot := ds.PartitionRoot(ds.partition)\n\tlimitMutable := limit\n\tvar err os.Error\n\tdoScan := func() {\n\t\terr = readBlobs(readBlobRequest{\n\t\t\tch:      dest,\n\t\t\tdirRoot: dirRoot,\n\t\t\tafter:   after,\n\t\t\tremain:  &limitMutable,\n\t\t})\n\t}\n\tdoScan()\n\n\t\/\/ The not waiting case:\n\tif err != nil || limitMutable != limit || waitSeconds == 0 {\n\t\treturn err\n\t}\n\n\t\/\/ The case where we have to wait for waitSeconds for any blob\n\t\/\/ to possibly appear.\n\thub := ds.GetBlobHub()\n\tch := make(chan *blobref.BlobRef, 1)\n\thub.RegisterListener(ch)\n\tdefer hub.UnregisterListener(ch)\n\ttimer := time.NewTimer(int64(waitSeconds) * 1e9)\n\tdefer timer.Stop()\n\tselect {\n\tcase <-timer.C:\n\t\t\/\/ Done waiting.\n\t\treturn nil\n\tcase <-ch:\n\t\t\/\/ Don't actually care what it is, but _something_\n\t\t\/\/ arrived.  We can just re-scan.\n\t\t\/\/ TODO: might be better to just stat this one item\n\t\t\/\/ so there's no race?  But this is easier:\n\t\tdoScan()\n\t}\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package gocd\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\n\/\/  Server is an object representation of a GoCD server\ntype Server struct {\n\tHost     string\n\tPort     string\n\tUser     string\n\tPassword string\n\tTimeout  time.Duration\n}\n\n\/\/ NewServerConfig Create a Server object from a config\nfunc NewServerConfig(host string, port string, user string, password string, timeoutStr string) *Server {\n\n\t\/\/ timeout casting to seconds\n\ttimeout := time.Duration(120 * time.Second)\n\ti, err := strconv.Atoi(timeoutStr)\n\tif err == nil {\n\t\ttimeout = time.Duration(i) * time.Second\n\t} else {\n\t\tlog.Warn(\"Failed to convert timeout to seconds: \", err)\n\t}\n\n\treturn &Server{\n\t\tHost:     host,\n\t\tPort:     port,\n\t\tUser:     user,\n\t\tPassword: password,\n\t\tTimeout:  timeout,\n\t}\n}\n\n\/\/ URL returns the host of the GoCD server\nfunc (server Server) URL() string {\n\treturn fmt.Sprintf(\"%s:%s\", server.Host, server.Port)\n}\n\n\/\/ client returns a http client with longer timeout and skip verify\nfunc client(timeout time.Duration) *http.Client {\n\ttransCfg := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\treturn &http.Client{\n\t\tTimeout:   timeout,\n\t\tTransport: transCfg,\n\t}\n}\n\nfunc printPrettyJSON(body []byte, objectname string) (prettyJSON bytes.Buffer, err error) {\n\terr = json.Indent(&prettyJSON, body, \"\", \"\\t\")\n\tif err != nil {\n\t\tlog.Warn(\"Failed to prettify JSON: \", err)\n\t}\n\tlog.Debug(objectname+\" JSON:\", string(prettyJSON.Bytes()))\n\treturn\n}\n\n\/\/ readPipelineJSONFromFile reads a GoCD structure from a json file\nfunc readPipelineJSONFromFile(path string) (pipeline Pipeline, err error) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err == nil {\n\t\terr = json.Unmarshal(data, &pipeline)\n\t}\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) pipelineConfigPUT(pipeline Pipeline, etag string) (pipelineResult Pipeline, err error) {\n\n\tpipelineName := pipeline.Name\n\n\tpayloadBytes, err := json.Marshal(pipeline)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpayloadBody := bytes.NewReader(payloadBytes)\n\n\treq, err := http.NewRequest(\"PUT\", server.URL()+\"\/go\/api\/admin\/pipelines\/\"+pipelineName, payloadBody)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Accept\", \"application\/vnd.go.cd.v4+json\")\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\treq.Header.Set(\"If-Match\", etag)\n\n\tlog.Debugf(\"Sending request: %v\", req)\n\tresp, err := client(server.Timeout).Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d, response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\tprintPrettyJSON(body, \"pipelineConfig\")\n\n\terr = json.Unmarshal(body, &pipelineResult)\n\treturn\n}\n\n\/\/ Generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) pipelineConfigPOST(pipelineConfig PipelineConfig) (pipeline Pipeline, err error) {\n\tpayloadBytes, err := json.Marshal(pipelineConfig)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpayloadBody := bytes.NewReader(payloadBytes)\n\n\treq, err := http.NewRequest(\"POST\", server.URL()+\"\/go\/api\/admin\/pipelines\", payloadBody)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Accept\", \"application\/vnd.go.cd.v4+json\")\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\n\tlog.Debugf(\"Sending request: %v\", req)\n\tresp, err := client(server.Timeout).Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\tprintPrettyJSON(body, \"pipelineConfig\")\n\n\terr = json.Unmarshal(body, &pipeline)\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) pipelineDELETE(pipelineName string) (pipeline Pipeline, err error) {\n\treq, err := http.NewRequest(\"DELETE\", server.URL()+\"\/go\/api\/admin\/pipelines\/\"+pipelineName, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Accept\", \"application\/vnd.go.cd.v4+json\")\n\n\tresp, err := client(server.Timeout).Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s using server url: %s\", resp.StatusCode, body, server.URL())\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(body, &pipeline)\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) environmentGET() (environment []Environment, err error) {\n\treq, err := http.NewRequest(\"GET\", server.URL()+\"\/go\/api\/admin\/environments\", nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Accept\", \"application\/vnd.go.cd.v2+json\")\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\tvar fullReturn EnvironmentConfig\n\terr = json.Unmarshal(body, &fullReturn)\n\n\tenvironment = fullReturn.Embedded.Environment\n\n\treturn\n}\n\nfunc findPipelineInEnvironment(environment []Environment, pipelineName string) (envName string) {\n\t\/\/var envName string\n\tenvName = \"\"\n\n\tfor _, v := range environment {\n\t\tfor _, p := range v.Pipelines {\n\t\t\tif p.Name == pipelineName {\n\t\t\t\tenvName = v.Name\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) environmentPATCH(pipelineName string, environmentName string) (err error) {\n\tdata := Payload{}\n\tdata.Pipelines.Remove = []string{pipelineName}\n\n\tpayloadBytes, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn\n\t}\n\tpayloadBody := bytes.NewReader(payloadBytes)\n\n\treq, err := http.NewRequest(\"PATCH\", server.URL()+\"\/go\/api\/admin\/environments\/\"+environmentName, payloadBody)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Accept\", \"application\/vnd.go.cd.v2+json\")\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) pipelineGET(pipelineName string) (pipeline Pipeline, etag string, err error) {\n\treq, err := http.NewRequest(\"GET\", server.URL()+\"\/go\/api\/admin\/pipelines\/\"+pipelineName, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Accept\", \"application\/vnd.go.cd.v4+json\")\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\n\tlog.Debugf(\"Sending request: %v\", req)\n\tresp, err := client(server.Timeout).Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\tprintPrettyJSON(body, \"pipelineConfig\")\n\n\tetag = resp.Header.Get(\"ETag\")\n\terr = json.Unmarshal(body, &pipeline)\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) artifactGET(pipelineName string, pipelineID int, stageName string, stageID int, jobName string, artifactPath string) (fileBytes *bytes.Buffer, err error) {\n\treqStr := fmt.Sprintf(\"%s\/go\/files\/%s\/%d\/%s\/%d\/%s\/%s\/\", server.URL(),\n\t\tpipelineName, pipelineID, stageName, stageID, jobName, artifactPath)\n\treq, err := http.NewRequest(\"GET\", reqStr, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\n\tlog.Debugf(\"Sending request: %v\", req)\n\tresp, err := client(server.Timeout).Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\tfileBytes = bytes.NewBuffer(body)\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) historyGET(pipelineName string) (historyJSON bytes.Buffer, err error) {\n\treq, err := http.NewRequest(\"GET\", server.URL()+\"\/go\/api\/pipelines\/\"+pipelineName+\"\/history\", nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\n\tlog.Debugf(\"Sending request: %v\", req)\n\tresp, err := client(server.Timeout).Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\thistoryJSON, err = printPrettyJSON(body, \"pipelineHistory\")\n\treturn\n}\n\n\/\/ writePipeline helper function to write a pipeline to file\nfunc writePipeline(path string, pipeline Pipeline) (err error) {\n\tpipelineJSON, _ := json.MarshalIndent(pipeline, \"\", \"    \")\n\terr = ioutil.WriteFile(path, pipelineJSON, 0666)\n\treturn\n}\n<commit_msg>change struct name<commit_after>package gocd\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\n\/\/  Server is an object representation of a GoCD server\ntype Server struct {\n\tHost     string\n\tPort     string\n\tUser     string\n\tPassword string\n\tTimeout  time.Duration\n}\n\n\/\/ NewServerConfig Create a Server object from a config\nfunc NewServerConfig(host string, port string, user string, password string, timeoutStr string) *Server {\n\n\t\/\/ timeout casting to seconds\n\ttimeout := time.Duration(120 * time.Second)\n\ti, err := strconv.Atoi(timeoutStr)\n\tif err == nil {\n\t\ttimeout = time.Duration(i) * time.Second\n\t} else {\n\t\tlog.Warn(\"Failed to convert timeout to seconds: \", err)\n\t}\n\n\treturn &Server{\n\t\tHost:     host,\n\t\tPort:     port,\n\t\tUser:     user,\n\t\tPassword: password,\n\t\tTimeout:  timeout,\n\t}\n}\n\n\/\/ URL returns the host of the GoCD server\nfunc (server Server) URL() string {\n\treturn fmt.Sprintf(\"%s:%s\", server.Host, server.Port)\n}\n\n\/\/ client returns a http client with longer timeout and skip verify\nfunc client(timeout time.Duration) *http.Client {\n\ttransCfg := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\treturn &http.Client{\n\t\tTimeout:   timeout,\n\t\tTransport: transCfg,\n\t}\n}\n\nfunc printPrettyJSON(body []byte, objectname string) (prettyJSON bytes.Buffer, err error) {\n\terr = json.Indent(&prettyJSON, body, \"\", \"\\t\")\n\tif err != nil {\n\t\tlog.Warn(\"Failed to prettify JSON: \", err)\n\t}\n\tlog.Debug(objectname+\" JSON:\", string(prettyJSON.Bytes()))\n\treturn\n}\n\n\/\/ readPipelineJSONFromFile reads a GoCD structure from a json file\nfunc readPipelineJSONFromFile(path string) (pipeline Pipeline, err error) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err == nil {\n\t\terr = json.Unmarshal(data, &pipeline)\n\t}\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) pipelineConfigPUT(pipeline Pipeline, etag string) (pipelineResult Pipeline, err error) {\n\n\tpipelineName := pipeline.Name\n\n\tpayloadBytes, err := json.Marshal(pipeline)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpayloadBody := bytes.NewReader(payloadBytes)\n\n\treq, err := http.NewRequest(\"PUT\", server.URL()+\"\/go\/api\/admin\/pipelines\/\"+pipelineName, payloadBody)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Accept\", \"application\/vnd.go.cd.v4+json\")\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\treq.Header.Set(\"If-Match\", etag)\n\n\tlog.Debugf(\"Sending request: %v\", req)\n\tresp, err := client(server.Timeout).Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d, response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\tprintPrettyJSON(body, \"pipelineConfig\")\n\n\terr = json.Unmarshal(body, &pipelineResult)\n\treturn\n}\n\n\/\/ Generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) pipelineConfigPOST(pipelineConfig PipelineConfig) (pipeline Pipeline, err error) {\n\tpayloadBytes, err := json.Marshal(pipelineConfig)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tpayloadBody := bytes.NewReader(payloadBytes)\n\n\treq, err := http.NewRequest(\"POST\", server.URL()+\"\/go\/api\/admin\/pipelines\", payloadBody)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Accept\", \"application\/vnd.go.cd.v4+json\")\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\n\tlog.Debugf(\"Sending request: %v\", req)\n\tresp, err := client(server.Timeout).Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\tprintPrettyJSON(body, \"pipelineConfig\")\n\n\terr = json.Unmarshal(body, &pipeline)\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) pipelineDELETE(pipelineName string) (pipeline Pipeline, err error) {\n\treq, err := http.NewRequest(\"DELETE\", server.URL()+\"\/go\/api\/admin\/pipelines\/\"+pipelineName, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Accept\", \"application\/vnd.go.cd.v4+json\")\n\n\tresp, err := client(server.Timeout).Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s using server url: %s\", resp.StatusCode, body, server.URL())\n\t\treturn\n\t}\n\n\terr = json.Unmarshal(body, &pipeline)\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) environmentGET() (environment []Environment, err error) {\n\treq, err := http.NewRequest(\"GET\", server.URL()+\"\/go\/api\/admin\/environments\", nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Accept\", \"application\/vnd.go.cd.v2+json\")\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\tvar fullReturn EnvironmentConfig\n\terr = json.Unmarshal(body, &fullReturn)\n\n\tenvironment = fullReturn.Embedded.Environment\n\n\treturn\n}\n\nfunc findPipelineInEnvironment(environment []Environment, pipelineName string) (envName string) {\n\t\/\/var envName string\n\tenvName = \"\"\n\n\tfor _, v := range environment {\n\t\tfor _, p := range v.Pipelines {\n\t\t\tif p.Name == pipelineName {\n\t\t\t\tenvName = v.Name\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) environmentPATCH(pipelineName string, environmentName string) (err error) {\n\tdata := PatchPayload{}\n\tdata.Pipelines.Remove = []string{pipelineName}\n\n\tpayloadBytes, err := json.Marshal(data)\n\tif err != nil {\n\t\treturn\n\t}\n\tpayloadBody := bytes.NewReader(payloadBytes)\n\n\treq, err := http.NewRequest(\"PATCH\", server.URL()+\"\/go\/api\/admin\/environments\/\"+environmentName, payloadBody)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Accept\", \"application\/vnd.go.cd.v2+json\")\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) pipelineGET(pipelineName string) (pipeline Pipeline, etag string, err error) {\n\treq, err := http.NewRequest(\"GET\", server.URL()+\"\/go\/api\/admin\/pipelines\/\"+pipelineName, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Accept\", \"application\/vnd.go.cd.v4+json\")\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\n\tlog.Debugf(\"Sending request: %v\", req)\n\tresp, err := client(server.Timeout).Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\tprintPrettyJSON(body, \"pipelineConfig\")\n\n\tetag = resp.Header.Get(\"ETag\")\n\terr = json.Unmarshal(body, &pipeline)\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) artifactGET(pipelineName string, pipelineID int, stageName string, stageID int, jobName string, artifactPath string) (fileBytes *bytes.Buffer, err error) {\n\treqStr := fmt.Sprintf(\"%s\/go\/files\/%s\/%d\/%s\/%d\/%s\/%s\/\", server.URL(),\n\t\tpipelineName, pipelineID, stageName, stageID, jobName, artifactPath)\n\treq, err := http.NewRequest(\"GET\", reqStr, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\n\tlog.Debugf(\"Sending request: %v\", req)\n\tresp, err := client(server.Timeout).Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\tfileBytes = bytes.NewBuffer(body)\n\treturn\n}\n\n\/\/ Partially generated by curl-to-Go: https:\/\/mholt.github.io\/curl-to-go\nfunc (server Server) historyGET(pipelineName string) (historyJSON bytes.Buffer, err error) {\n\treq, err := http.NewRequest(\"GET\", server.URL()+\"\/go\/api\/pipelines\/\"+pipelineName+\"\/history\", nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(server.User) > 0 && len(server.Password) > 0 {\n\t\treq.SetBasicAuth(server.User, server.Password)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\n\tlog.Debugf(\"Sending request: %v\", req)\n\tresp, err := client(server.Timeout).Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Bad response code: %d with response: %s\", resp.StatusCode, body)\n\t\treturn\n\t}\n\n\thistoryJSON, err = printPrettyJSON(body, \"pipelineHistory\")\n\treturn\n}\n\n\/\/ writePipeline helper function to write a pipeline to file\nfunc writePipeline(path string, pipeline Pipeline) (err error) {\n\tpipelineJSON, _ := json.MarshalIndent(pipeline, \"\", \"    \")\n\terr = ioutil.WriteFile(path, pipelineJSON, 0666)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\n\/\/ XXX\npackage commands\n\nimport (\n\t\"github.com\/juju\/cmd\"\n\tjc \"github.com\/juju\/testing\/checkers\"\n\tgc \"gopkg.in\/check.v1\"\n\n\t\"github.com\/juju\/juju\/api\/controller\"\n\t\"github.com\/juju\/juju\/cmd\/modelcmd\"\n\t\"github.com\/juju\/juju\/feature\"\n\t\"github.com\/juju\/juju\/jujuclient\"\n\t\"github.com\/juju\/juju\/jujuclient\/jujuclienttesting\"\n\t\"github.com\/juju\/juju\/testing\"\n)\n\ntype MigrateSuite struct {\n\ttesting.FakeJujuXDGDataHomeSuite\n\tapi   *fakeMigrateAPI\n\tstore *jujuclienttesting.MemStore\n}\n\nvar _ = gc.Suite(&MigrateSuite{})\n\nconst modelUUID = \"deadbeef-0bad-400d-8000-4b1d0d06f00d\"\nconst targetControllerUUID = \"beefdead-0bad-400d-8000-4b1d0d06f00d\"\n\nfunc (s *MigrateSuite) SetUpTest(c *gc.C) {\n\ts.SetInitialFeatureFlags(feature.Migration)\n\ts.FakeJujuXDGDataHomeSuite.SetUpTest(c)\n\n\ts.store = jujuclienttesting.NewMemStore()\n\n\t\/\/ Define the source controller in the config and set it as the default.\n\terr := s.store.UpdateController(\"source\", jujuclient.ControllerDetails{\n\t\tControllerUUID: \"eeeeeeee-0bad-400d-8000-4b1d0d06f00d\",\n\t\tCACert:         \"somecert\",\n\t})\n\tc.Assert(err, jc.ErrorIsNil)\n\terr = modelcmd.WriteCurrentController(\"source\")\n\tc.Assert(err, jc.ErrorIsNil)\n\n\t\/\/ Define an account for the model in the source controller in the config.\n\terr = s.store.UpdateAccount(\"source\", \"source@local\", jujuclient.AccountDetails{\n\t\tUser: \"whatever@local\",\n\t})\n\tc.Assert(err, jc.ErrorIsNil)\n\terr = s.store.SetCurrentAccount(\"source\", \"source@local\")\n\tc.Assert(err, jc.ErrorIsNil)\n\n\t\/\/ Define the model to migrate in the config.\n\terr = s.store.UpdateModel(\"source\", \"source@local\", \"model\", jujuclient.ModelDetails{\n\t\tModelUUID: modelUUID,\n\t})\n\tc.Assert(err, jc.ErrorIsNil)\n\n\t\/\/ Define the account for the target controller.\n\terr = s.store.UpdateAccount(\"target\", \"target@local\", jujuclient.AccountDetails{\n\t\tUser:     \"admin@local\",\n\t\tPassword: \"secret\",\n\t})\n\tc.Assert(err, jc.ErrorIsNil)\n\terr = s.store.SetCurrentAccount(\"target\", \"target@local\")\n\tc.Assert(err, jc.ErrorIsNil)\n\n\t\/\/ Define the target controller in the config.\n\terr = s.store.UpdateController(\"target\", jujuclient.ControllerDetails{\n\t\tControllerUUID: targetControllerUUID,\n\t\tAPIEndpoints:   []string{\"1.2.3.4:5\"},\n\t\tCACert:         \"cert\",\n\t})\n\tc.Assert(err, jc.ErrorIsNil)\n\n\ts.api = &fakeMigrateAPI{}\n}\n\nfunc (s *MigrateSuite) TestMissingModel(c *gc.C) {\n\t_, err := s.runCommand(c)\n\tc.Assert(err, gc.ErrorMatches, \"model not specified\")\n}\n\nfunc (s *MigrateSuite) TestMissingTargetController(c *gc.C) {\n\t_, err := s.runCommand(c, \"mymodel\")\n\tc.Assert(err, gc.ErrorMatches, \"target controller not specified\")\n}\n\nfunc (s *MigrateSuite) TestTooManyArgs(c *gc.C) {\n\t_, err := s.runCommand(c, \"one\", \"too\", \"many\")\n\tc.Assert(err, gc.ErrorMatches, \"too many arguments specified\")\n}\n\nfunc (s *MigrateSuite) TestSuccess(c *gc.C) {\n\tctx, err := s.runCommand(c, \"model\", \"target\")\n\tc.Assert(err, jc.ErrorIsNil)\n\n\tc.Check(testing.Stderr(ctx), gc.Matches, \"Migration started with ID \\\"uuid:0\\\"\\n\")\n\tc.Check(s.api.specSeen, jc.DeepEquals, &controller.ModelMigrationSpec{\n\t\tModelUUID:            modelUUID,\n\t\tTargetControllerUUID: targetControllerUUID,\n\t\tTargetAddrs:          []string{\"1.2.3.4:5\"},\n\t\tTargetCACert:         \"cert\",\n\t\tTargetUser:           \"admin@local\",\n\t\tTargetPassword:       \"secret\",\n\t})\n}\n\nfunc (s *MigrateSuite) TestModelDoesntExist(c *gc.C) {\n\t_, err := s.runCommand(c, \"wat\", \"target\")\n\tc.Check(err, gc.ErrorMatches, \"model .+ not found\")\n\tc.Check(s.api.specSeen, gc.IsNil) \/\/ API shouldn't have been called\n}\n\nfunc (s *MigrateSuite) TestControllerDoesntExist(c *gc.C) {\n\t_, err := s.runCommand(c, \"model\", \"wat\")\n\tc.Check(err, gc.ErrorMatches, \"controller wat not found\")\n\tc.Check(s.api.specSeen, gc.IsNil) \/\/ API shouldn't have been called\n}\n\nfunc (s *MigrateSuite) runCommand(c *gc.C, args ...string) (*cmd.Context, error) {\n\tcmd := &migrateCommand{\n\t\tapi: s.api,\n\t}\n\tcmd.SetClientStore(s.store)\n\treturn testing.RunCommand(c, modelcmd.WrapController(cmd), args...)\n}\n\ntype fakeMigrateAPI struct {\n\tspecSeen *controller.ModelMigrationSpec\n}\n\nfunc (a *fakeMigrateAPI) InitiateModelMigration(spec controller.ModelMigrationSpec) (string, error) {\n\ta.specSeen = &spec\n\treturn \"uuid:0\", nil\n}\n<commit_msg>Remove dead comment.<commit_after>\/\/ Copyright 2016 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage commands\n\nimport (\n\t\"github.com\/juju\/cmd\"\n\tjc \"github.com\/juju\/testing\/checkers\"\n\tgc \"gopkg.in\/check.v1\"\n\n\t\"github.com\/juju\/juju\/api\/controller\"\n\t\"github.com\/juju\/juju\/cmd\/modelcmd\"\n\t\"github.com\/juju\/juju\/feature\"\n\t\"github.com\/juju\/juju\/jujuclient\"\n\t\"github.com\/juju\/juju\/jujuclient\/jujuclienttesting\"\n\t\"github.com\/juju\/juju\/testing\"\n)\n\ntype MigrateSuite struct {\n\ttesting.FakeJujuXDGDataHomeSuite\n\tapi   *fakeMigrateAPI\n\tstore *jujuclienttesting.MemStore\n}\n\nvar _ = gc.Suite(&MigrateSuite{})\n\nconst modelUUID = \"deadbeef-0bad-400d-8000-4b1d0d06f00d\"\nconst targetControllerUUID = \"beefdead-0bad-400d-8000-4b1d0d06f00d\"\n\nfunc (s *MigrateSuite) SetUpTest(c *gc.C) {\n\ts.SetInitialFeatureFlags(feature.Migration)\n\ts.FakeJujuXDGDataHomeSuite.SetUpTest(c)\n\n\ts.store = jujuclienttesting.NewMemStore()\n\n\t\/\/ Define the source controller in the config and set it as the default.\n\terr := s.store.UpdateController(\"source\", jujuclient.ControllerDetails{\n\t\tControllerUUID: \"eeeeeeee-0bad-400d-8000-4b1d0d06f00d\",\n\t\tCACert:         \"somecert\",\n\t})\n\tc.Assert(err, jc.ErrorIsNil)\n\terr = modelcmd.WriteCurrentController(\"source\")\n\tc.Assert(err, jc.ErrorIsNil)\n\n\t\/\/ Define an account for the model in the source controller in the config.\n\terr = s.store.UpdateAccount(\"source\", \"source@local\", jujuclient.AccountDetails{\n\t\tUser: \"whatever@local\",\n\t})\n\tc.Assert(err, jc.ErrorIsNil)\n\terr = s.store.SetCurrentAccount(\"source\", \"source@local\")\n\tc.Assert(err, jc.ErrorIsNil)\n\n\t\/\/ Define the model to migrate in the config.\n\terr = s.store.UpdateModel(\"source\", \"source@local\", \"model\", jujuclient.ModelDetails{\n\t\tModelUUID: modelUUID,\n\t})\n\tc.Assert(err, jc.ErrorIsNil)\n\n\t\/\/ Define the account for the target controller.\n\terr = s.store.UpdateAccount(\"target\", \"target@local\", jujuclient.AccountDetails{\n\t\tUser:     \"admin@local\",\n\t\tPassword: \"secret\",\n\t})\n\tc.Assert(err, jc.ErrorIsNil)\n\terr = s.store.SetCurrentAccount(\"target\", \"target@local\")\n\tc.Assert(err, jc.ErrorIsNil)\n\n\t\/\/ Define the target controller in the config.\n\terr = s.store.UpdateController(\"target\", jujuclient.ControllerDetails{\n\t\tControllerUUID: targetControllerUUID,\n\t\tAPIEndpoints:   []string{\"1.2.3.4:5\"},\n\t\tCACert:         \"cert\",\n\t})\n\tc.Assert(err, jc.ErrorIsNil)\n\n\ts.api = &fakeMigrateAPI{}\n}\n\nfunc (s *MigrateSuite) TestMissingModel(c *gc.C) {\n\t_, err := s.runCommand(c)\n\tc.Assert(err, gc.ErrorMatches, \"model not specified\")\n}\n\nfunc (s *MigrateSuite) TestMissingTargetController(c *gc.C) {\n\t_, err := s.runCommand(c, \"mymodel\")\n\tc.Assert(err, gc.ErrorMatches, \"target controller not specified\")\n}\n\nfunc (s *MigrateSuite) TestTooManyArgs(c *gc.C) {\n\t_, err := s.runCommand(c, \"one\", \"too\", \"many\")\n\tc.Assert(err, gc.ErrorMatches, \"too many arguments specified\")\n}\n\nfunc (s *MigrateSuite) TestSuccess(c *gc.C) {\n\tctx, err := s.runCommand(c, \"model\", \"target\")\n\tc.Assert(err, jc.ErrorIsNil)\n\n\tc.Check(testing.Stderr(ctx), gc.Matches, \"Migration started with ID \\\"uuid:0\\\"\\n\")\n\tc.Check(s.api.specSeen, jc.DeepEquals, &controller.ModelMigrationSpec{\n\t\tModelUUID:            modelUUID,\n\t\tTargetControllerUUID: targetControllerUUID,\n\t\tTargetAddrs:          []string{\"1.2.3.4:5\"},\n\t\tTargetCACert:         \"cert\",\n\t\tTargetUser:           \"admin@local\",\n\t\tTargetPassword:       \"secret\",\n\t})\n}\n\nfunc (s *MigrateSuite) TestModelDoesntExist(c *gc.C) {\n\t_, err := s.runCommand(c, \"wat\", \"target\")\n\tc.Check(err, gc.ErrorMatches, \"model .+ not found\")\n\tc.Check(s.api.specSeen, gc.IsNil) \/\/ API shouldn't have been called\n}\n\nfunc (s *MigrateSuite) TestControllerDoesntExist(c *gc.C) {\n\t_, err := s.runCommand(c, \"model\", \"wat\")\n\tc.Check(err, gc.ErrorMatches, \"controller wat not found\")\n\tc.Check(s.api.specSeen, gc.IsNil) \/\/ API shouldn't have been called\n}\n\nfunc (s *MigrateSuite) runCommand(c *gc.C, args ...string) (*cmd.Context, error) {\n\tcmd := &migrateCommand{\n\t\tapi: s.api,\n\t}\n\tcmd.SetClientStore(s.store)\n\treturn testing.RunCommand(c, modelcmd.WrapController(cmd), args...)\n}\n\ntype fakeMigrateAPI struct {\n\tspecSeen *controller.ModelMigrationSpec\n}\n\nfunc (a *fakeMigrateAPI) InitiateModelMigration(spec controller.ModelMigrationSpec) (string, error) {\n\ta.specSeen = &spec\n\treturn \"uuid:0\", nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com\/mistifyio\/gozfs\/nv\"\n)\n\ntype header struct {\n\tSize     uint32\n\tExtSpace uint8\n\tError    uint8\n\tEndian   uint8\n\tReserved uint8\n}\n\nfunc getSize(b []byte) (int64, error) {\n\th := header{}\n\tbuf := bytes.NewBuffer(b)\n\terr := binary.Read(buf, binary.LittleEndian, &h)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif h.Endian != 1 {\n\t\tbuf := bytes.NewBuffer(b)\n\t\terr := binary.Read(buf, binary.BigEndian, &h)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tif h.Reserved != 0 {\n\t\treturn 0, errors.New(\"non-zero Reserved field\")\n\t}\n\tif h.Endian > 1 {\n\t\treturn 0, errors.New(\"unknown Endian value\")\n\t}\n\tif h.Error != 0 {\n\t\treturn 0, syscall.Errno(h.Error)\n\t}\n\n\treturn int64(h.Size), nil\n}\n\nfunc properties(name string, types map[string]bool, recurse bool, depth uint64) (map[string]interface{}, error) {\n\tlisting, err := list(name, types, recurse, depth)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tret := make(map[string]interface{}, len(listing))\n\tfor _, l := range listing {\n\t\tname := l[\"name\"].(string)\n\t\tprops := l[\"properties\"].(map[string]interface{})\n\t\tret[name] = props\n\t}\n\treturn ret, nil\n}\n\nfunc list(name string, types map[string]bool, recurse bool, depth uint64) ([]map[string]interface{}, error) {\n\tvar reader io.Reader\n\treader, writer, err := os.Pipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer reader.(*os.File).Close()\n\tdefer writer.Close()\n\n\topts := map[string]interface{}{\n\t\t\"fd\": int32(writer.Fd()),\n\t}\n\tif types != nil {\n\t\topts[\"type\"] = types\n\t}\n\tif recurse != false {\n\t\tif depth != 0 {\n\t\t\topts[\"recurse\"] = depth\n\t\t} else {\n\t\t\topts[\"recurse\"] = true\n\t\t}\n\t}\n\targs := map[string]interface{}{\n\t\t\"cmd\":     \"zfs_list\",\n\t\t\"innvl\":   map[string]interface{}{},\n\t\t\"opts\":    opts,\n\t\t\"version\": uint64(0),\n\t}\n\n\tencoded := &bytes.Buffer{}\n\terr = nv.NewNativeEncoder(encoded).Encode(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = ioctl(zfs, name, encoded.Bytes(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar buf []byte\n\treader = bufio.NewReader(reader)\n\n\tret := []map[string]interface{}{}\n\tfor {\n\t\theader := make([]byte, 8)\n\t\t_, err = io.ReadFull(reader, header)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tvar size int64\n\t\tsize, err = getSize(header)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif size == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tif len(buf) < int(size) {\n\t\t\tl := (size + 1023) & ^1023\n\t\t\tbuf = make([]byte, l)\n\t\t}\n\t\tbuf = buf[:size]\n\n\t\t_, err = io.ReadFull(reader, buf)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tm := map[string]interface{}{}\n\t\terr = nv.NewXDRDecoder(bytes.NewReader(buf)).Decode(&m)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tret = append(ret, m)\n\t}\n\treturn ret, err\n}\n<commit_msg>move reading of pipe header into getSize<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com\/mistifyio\/gozfs\/nv\"\n)\n\ntype header struct {\n\tSize     uint32\n\tExtSpace uint8\n\tError    uint8\n\tEndian   uint8\n\tReserved uint8\n}\n\nfunc getSize(r io.Reader) (int64, error) {\n\tbuf := make([]byte, 8)\n\n\t_, err := io.ReadFull(r, buf)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\th := header{}\n\terr = binary.Read(bytes.NewReader(buf), binary.LittleEndian, &h)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif h.Endian != 1 {\n\t\terr := binary.Read(bytes.NewReader(buf), binary.BigEndian, &h)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tif h.Reserved != 0 {\n\t\treturn 0, errors.New(\"non-zero Reserved field\")\n\t}\n\tif h.Endian > 1 {\n\t\treturn 0, errors.New(\"unknown Endian value\")\n\t}\n\tif h.Error != 0 {\n\t\treturn 0, syscall.Errno(h.Error)\n\t}\n\n\treturn int64(h.Size), nil\n}\n\nfunc properties(name string, types map[string]bool, recurse bool, depth uint64) (map[string]interface{}, error) {\n\tlisting, err := list(name, types, recurse, depth)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tret := make(map[string]interface{}, len(listing))\n\tfor _, l := range listing {\n\t\tname := l[\"name\"].(string)\n\t\tprops := l[\"properties\"].(map[string]interface{})\n\t\tret[name] = props\n\t}\n\treturn ret, nil\n}\n\nfunc list(name string, types map[string]bool, recurse bool, depth uint64) ([]map[string]interface{}, error) {\n\tvar reader io.Reader\n\treader, writer, err := os.Pipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer reader.(*os.File).Close()\n\tdefer writer.Close()\n\n\topts := map[string]interface{}{\n\t\t\"fd\": int32(writer.Fd()),\n\t}\n\tif types != nil {\n\t\topts[\"type\"] = types\n\t}\n\tif recurse != false {\n\t\tif depth != 0 {\n\t\t\topts[\"recurse\"] = depth\n\t\t} else {\n\t\t\topts[\"recurse\"] = true\n\t\t}\n\t}\n\targs := map[string]interface{}{\n\t\t\"cmd\":     \"zfs_list\",\n\t\t\"innvl\":   map[string]interface{}{},\n\t\t\"opts\":    opts,\n\t\t\"version\": uint64(0),\n\t}\n\n\tencoded := &bytes.Buffer{}\n\terr = nv.NewNativeEncoder(encoded).Encode(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = ioctl(zfs, name, encoded.Bytes(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar buf []byte\n\treader = bufio.NewReader(reader)\n\n\tret := []map[string]interface{}{}\n\tfor {\n\t\tvar size int64\n\t\tsize, err = getSize(reader)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif size == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tif len(buf) < int(size) {\n\t\t\tl := (size + 1023) & ^1023\n\t\t\tbuf = make([]byte, l)\n\t\t}\n\t\tbuf = buf[:size]\n\n\t\t_, err = io.ReadFull(reader, buf)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tm := map[string]interface{}{}\n\t\terr = nv.NewXDRDecoder(bytes.NewReader(buf)).Decode(&m)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tret = append(ret, m)\n\t}\n\treturn ret, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"flag\"\n\t\"strings\"\n\t\"testing\"\n\n\t\/\/\"github.com\/google\/note-maps\/notes\"\n\t\"github.com\/google\/note-maps\/notes\/genji\"\n\t\"github.com\/google\/note-maps\/notes\/pbdb\"\n\t\"github.com\/google\/subcommands\"\n)\n\ntype noCloseDB struct{ *genji.GenjiNoteMap }\n\nfunc (noCloseDB) Close() error { return nil }\n\nfunc TestIntegration_SetFindGet(t *testing.T) {\n\tctx := context.Background()\n\tdb, err := genji.Open(\":memory:\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar (\n\t\tnm    = pbdb.NewNoteMap(db)\n\t\tcfg   = Config{overrideDb: nm}\n\t\tfind  = findCmd{&cfg}\n\t\tset   = setCmd{&cfg}\n\t\tflags = flag.NewFlagSet(\"\", flag.PanicOnError)\n\t\tcmdr  = subcommands.NewCommander(flags, \"testing\")\n\t)\n\tcmdr.Register(&find, \"\")\n\tcmdr.Register(&set, \"\")\n\texec := func(args ...string) (string, subcommands.ExitStatus) {\n\t\tbuf := bytes.NewBuffer(nil)\n\t\tcfg.output = buf\n\t\tflags.Parse(args)\n\t\tstatus := cmdr.Execute(ctx)\n\t\treturn buf.String(), status\n\t}\n\tif o, s := exec(\"set\", \"note: &42\\n- is: hello\"); s != subcommands.ExitSuccess {\n\t\tt.Fatal(\"failed to set initial note\")\n\t} else {\n\t\texpect := `42` + \"\\n\"\n\t\tif o != expect {\n\t\t\tt.Fatalf(\"expected %#v, got %#v\", expect, o)\n\t\t}\n\t}\n\tif o, s := exec(`find`); s != subcommands.ExitSuccess {\n\t\tt.Fatal(\"failed to set initial note\")\n\t} else {\n\t\texpect := strings.Join([]string{\n\t\t\t\"---\",\n\t\t\t\"note: &42\",\n\t\t\t\"    - is: hello\",\n\t\t\t\"---\",\n\t\t}, \"\\n\") + \"\\n\"\n\t\tif o != expect {\n\t\t\tt.Fatalf(\"expected %#v, got %#v\", expect, o)\n\t\t}\n\t}\n}\n<commit_msg>Fix new segfault in cmd\/note-maps tests<commit_after>\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"flag\"\n\t\"strings\"\n\t\"testing\"\n\n\t\/\/\"github.com\/google\/note-maps\/notes\"\n\t\"github.com\/google\/note-maps\/notes\/genji\"\n\t\"github.com\/google\/note-maps\/notes\/pbdb\"\n\t\"github.com\/google\/subcommands\"\n)\n\ntype noCloseDB struct{ *genji.GenjiNoteMap }\n\nfunc (noCloseDB) Close() error { return nil }\n\nfunc TestIntegration_SetFindGet(t *testing.T) {\n\tctx := context.Background()\n\tdb, err := genji.Open(\":memory:\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar (\n\t\tnm    = pbdb.NewNoteMap(noCloseDB{db})\n\t\tcfg   = Config{overrideDb: nm}\n\t\tfind  = findCmd{&cfg}\n\t\tset   = setCmd{&cfg}\n\t\tflags = flag.NewFlagSet(\"\", flag.PanicOnError)\n\t\tcmdr  = subcommands.NewCommander(flags, \"testing\")\n\t)\n\tcmdr.Register(&find, \"\")\n\tcmdr.Register(&set, \"\")\n\texec := func(args ...string) (string, subcommands.ExitStatus) {\n\t\tbuf := bytes.NewBuffer(nil)\n\t\tcfg.output = buf\n\t\tflags.Parse(args)\n\t\tstatus := cmdr.Execute(ctx)\n\t\treturn buf.String(), status\n\t}\n\tif o, s := exec(\"set\", \"note: &42\\n- is: hello\"); s != subcommands.ExitSuccess {\n\t\tt.Fatal(\"failed to set initial note\")\n\t} else {\n\t\texpect := `42` + \"\\n\"\n\t\tif o != expect {\n\t\t\tt.Fatalf(\"expected %#v, got %#v\", expect, o)\n\t\t}\n\t}\n\tif o, s := exec(`find`); s != subcommands.ExitSuccess {\n\t\tt.Fatal(\"failed to set initial note\")\n\t} else {\n\t\texpect := strings.Join([]string{\n\t\t\t\"---\",\n\t\t\t\"note: &42\",\n\t\t\t\"    - is: hello\",\n\t\t\t\"---\",\n\t\t}, \"\\n\") + \"\\n\"\n\t\tif o != expect {\n\t\t\tt.Fatalf(\"expected %#v, got %#v\", expect, o)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cmd\n\nimport (\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/cobra\"\n\t\"k8s.io\/release\/pkg\/announce\"\n)\n\n\/\/ releaseNotesCmd represents the subcommand for `krel release-notes`\nvar githuPageCmd = &cobra.Command{\n\tUse:   \"github\",\n\tShort: \"Updates the github page of a release\",\n\tLong: `publish-release github\n\nThis command updates the GitHub release page for a given tag. It will\nupdate the page using a built in template or you can update it using\na custom template.\n\nBefore updating the page, the tag has to exist already on github.\n\nTo publish the page, --nomock has to be defined. Otherwise, the rendered\npage will be printed to stdout and the program will exit.\n\nCUSTOM TEMPLATES\n================\nYou can define a custom golang template to use in your release page. Your\ntemplate can contain string substitutions and you can define those using \nthe --substitution flag:\n\n  --substitution=\"releaseTheme:Accentuate the Paw-sitive\"\n  --substitution=\"releaseLogo:accentuate-the-pawsitive.png\"\n\nASSET FILES\n===========\nThis command supports uploading release assets to the github page. You\ncan add asset files with the --asset flag:\n\n  --asset=_output\/kubernetes-1.18.2-2.fc33.x86_64.rpm\n\nYou can also specify a label for the assets by appending it with a colon\nto the asset file:\n\n  --asset=\"_output\/kubernetes-1.18.2-2.fc33.x86_64.rpm:RPM Package for amd64\"\n\n`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\/\/ Run the PR creation function\n\t\treturn runGithubPage(ghPageOpts)\n\t},\n}\n\ntype githubPageCmdLineOptions struct {\n\tnoupdate      bool\n\tdraft         bool\n\tname          string\n\trepo          string\n\ttemplate      string\n\tsubstitutions []string\n\tassets        []string\n}\n\nvar ghPageOpts = &githubPageCmdLineOptions{}\n\nfunc init() {\n\tgithuPageCmd.PersistentFlags().StringVarP(\n\t\t&ghPageOpts.repo,\n\t\t\"repo\",\n\t\t\"r\",\n\t\t\"\",\n\t\t\"repository slug containing the release page\",\n\t)\n\tgithuPageCmd.PersistentFlags().StringVar(\n\t\t&ghPageOpts.template,\n\t\t\"template\",\n\t\t\"\",\n\t\t\"path to a custom page template\",\n\t)\n\tgithuPageCmd.PersistentFlags().StringVarP(\n\t\t&ghPageOpts.name,\n\t\t\"name\",\n\t\t\"n\",\n\t\t\"\",\n\t\t\"name for the release\",\n\t)\n\tgithuPageCmd.PersistentFlags().StringSliceVarP(\n\t\t&ghPageOpts.assets,\n\t\t\"asset\",\n\t\t\"a\",\n\t\t[]string{},\n\t\t\"Path to asset file for the release. Can be specified multiple times.\",\n\t)\n\tgithuPageCmd.PersistentFlags().StringSliceVarP(\n\t\t&ghPageOpts.substitutions,\n\t\t\"substitution\",\n\t\t\"s\",\n\t\t[]string{},\n\t\t\"String substitution for the page template\",\n\t)\n\tgithuPageCmd.PersistentFlags().BoolVar(\n\t\t&ghPageOpts.noupdate,\n\t\t\"noupdate\",\n\t\tfalse,\n\t\t\"Fail if the release already exists\",\n\t)\n\tgithuPageCmd.PersistentFlags().BoolVar(\n\t\t&ghPageOpts.draft,\n\t\t\"draft\",\n\t\tfalse,\n\t\t\"Mark the release as a draft in GitHub so you can finish editing and publish it manually.\",\n\t)\n\trootCmd.AddCommand(githuPageCmd)\n}\n\nfunc runGithubPage(opts *githubPageCmdLineOptions) error {\n\t\/\/ Build the release page options\n\tannounceOpts := announce.GitHubPageOptions{\n\t\tAssetFiles:            opts.assets,\n\t\tTag:                   commandLineOpts.tag,\n\t\tNoMock:                commandLineOpts.nomock,\n\t\tUpdateIfReleaseExists: !opts.noupdate,\n\t\tName:                  opts.name,\n\t\tDraft:                 opts.draft,\n\t}\n\n\t\/\/ Assign the repository data\n\tif err := announceOpts.SetRepository(opts.repo); err != nil {\n\t\treturn errors.Wrap(err, \"assigning the repository slug\")\n\t}\n\n\t\/\/ Assign the substitutions\n\tif err := announceOpts.ParseSubstitutions(opts.substitutions); err != nil {\n\t\treturn errors.Wrap(err, \"parsing template substitutions\")\n\t}\n\n\t\/\/ Read the csutom template data\n\tif err := announceOpts.ReadTemplate(opts.template); err != nil {\n\t\treturn errors.Wrap(err, \"reading the template file\")\n\t}\n\n\t\/\/ Validate the options\n\tif err := announceOpts.Validate(); err != nil {\n\t\treturn errors.Wrap(err, \"validating options\")\n\t}\n\n\t\/\/ Run the update process\n\treturn announce.UpdateGitHubPage(&announceOpts)\n}\n<commit_msg>Mark repo as required flag<commit_after>\/*\nCopyright 2020 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cmd\n\nimport (\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/cobra\"\n\t\"k8s.io\/release\/pkg\/announce\"\n)\n\n\/\/ releaseNotesCmd represents the subcommand for `krel release-notes`\nvar githuPageCmd = &cobra.Command{\n\tUse:   \"github\",\n\tShort: \"Updates the github page of a release\",\n\tLong: `publish-release github\n\nThis command updates the GitHub release page for a given tag. It will\nupdate the page using a built in template or you can update it using\na custom template.\n\nBefore updating the page, the tag has to exist already on github.\n\nTo publish the page, --nomock has to be defined. Otherwise, the rendered\npage will be printed to stdout and the program will exit.\n\nCUSTOM TEMPLATES\n================\nYou can define a custom golang template to use in your release page. Your\ntemplate can contain string substitutions and you can define those using \nthe --substitution flag:\n\n  --substitution=\"releaseTheme:Accentuate the Paw-sitive\"\n  --substitution=\"releaseLogo:accentuate-the-pawsitive.png\"\n\nASSET FILES\n===========\nThis command supports uploading release assets to the github page. You\ncan add asset files with the --asset flag:\n\n  --asset=_output\/kubernetes-1.18.2-2.fc33.x86_64.rpm\n\nYou can also specify a label for the assets by appending it with a colon\nto the asset file:\n\n  --asset=\"_output\/kubernetes-1.18.2-2.fc33.x86_64.rpm:RPM Package for amd64\"\n\n`,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\/\/ Run the PR creation function\n\t\treturn runGithubPage(ghPageOpts)\n\t},\n}\n\ntype githubPageCmdLineOptions struct {\n\tnoupdate      bool\n\tdraft         bool\n\tname          string\n\trepo          string\n\ttemplate      string\n\tsubstitutions []string\n\tassets        []string\n}\n\nvar ghPageOpts = &githubPageCmdLineOptions{}\n\nfunc init() {\n\tgithuPageCmd.PersistentFlags().StringVarP(\n\t\t&ghPageOpts.repo,\n\t\t\"repo\",\n\t\t\"r\",\n\t\t\"\",\n\t\t\"repository slug containing the release page\",\n\t)\n\tgithuPageCmd.PersistentFlags().StringVar(\n\t\t&ghPageOpts.template,\n\t\t\"template\",\n\t\t\"\",\n\t\t\"path to a custom page template\",\n\t)\n\tgithuPageCmd.PersistentFlags().StringVarP(\n\t\t&ghPageOpts.name,\n\t\t\"name\",\n\t\t\"n\",\n\t\t\"\",\n\t\t\"name for the release\",\n\t)\n\tgithuPageCmd.PersistentFlags().StringSliceVarP(\n\t\t&ghPageOpts.assets,\n\t\t\"asset\",\n\t\t\"a\",\n\t\t[]string{},\n\t\t\"Path to asset file for the release. Can be specified multiple times.\",\n\t)\n\tgithuPageCmd.PersistentFlags().StringSliceVarP(\n\t\t&ghPageOpts.substitutions,\n\t\t\"substitution\",\n\t\t\"s\",\n\t\t[]string{},\n\t\t\"String substitution for the page template\",\n\t)\n\tgithuPageCmd.PersistentFlags().BoolVar(\n\t\t&ghPageOpts.noupdate,\n\t\t\"noupdate\",\n\t\tfalse,\n\t\t\"Fail if the release already exists\",\n\t)\n\tgithuPageCmd.PersistentFlags().BoolVar(\n\t\t&ghPageOpts.draft,\n\t\t\"draft\",\n\t\tfalse,\n\t\t\"Mark the release as a draft in GitHub so you can finish editing and publish it manually.\",\n\t)\n\n\tfor _, f := range []string{\"template\", \"asset\"} {\n\t\tif err := githuPageCmd.MarkPersistentFlagFilename(f); err != nil {\n\t\t\tlogrus.Error(err)\n\t\t}\n\t}\n\n\tif err := githuPageCmd.MarkPersistentFlagRequired(\"repo\"); err != nil {\n\t\tlogrus.Error(err)\n\t}\n\n\trootCmd.AddCommand(githuPageCmd)\n}\n\nfunc runGithubPage(opts *githubPageCmdLineOptions) error {\n\t\/\/ Build the release page options\n\tannounceOpts := announce.GitHubPageOptions{\n\t\tAssetFiles:            opts.assets,\n\t\tTag:                   commandLineOpts.tag,\n\t\tNoMock:                commandLineOpts.nomock,\n\t\tUpdateIfReleaseExists: !opts.noupdate,\n\t\tName:                  opts.name,\n\t\tDraft:                 opts.draft,\n\t}\n\n\t\/\/ Assign the repository data\n\tif err := announceOpts.SetRepository(opts.repo); err != nil {\n\t\treturn errors.Wrap(err, \"assigning the repository slug\")\n\t}\n\n\t\/\/ Assign the substitutions\n\tif err := announceOpts.ParseSubstitutions(opts.substitutions); err != nil {\n\t\treturn errors.Wrap(err, \"parsing template substitutions\")\n\t}\n\n\t\/\/ Read the csutom template data\n\tif err := announceOpts.ReadTemplate(opts.template); err != nil {\n\t\treturn errors.Wrap(err, \"reading the template file\")\n\t}\n\n\t\/\/ Validate the options\n\tif err := announceOpts.Validate(); err != nil {\n\t\treturn errors.Wrap(err, \"validating options\")\n\t}\n\n\t\/\/ Run the update process\n\treturn announce.UpdateGitHubPage(&announceOpts)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ ctclient is a command-line utility for interacting with CT logs.\npackage main\n\nimport (\n\t\"encoding\/pem\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\tct \"github.com\/google\/certificate-transparency-go\"\n\t\"github.com\/google\/certificate-transparency-go\/client\"\n\t\"github.com\/google\/certificate-transparency-go\/jsonclient\"\n\t\"github.com\/google\/certificate-transparency-go\/x509\"\n\t\"github.com\/google\/certificate-transparency-go\/x509util\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar logURI = flag.String(\"log_uri\", \"http:\/\/ct.googleapis.com\/aviator\", \"CT log base URI\")\nvar pubKey = flag.String(\"pub_key\", \"\", \"Name of file containing log's public key\")\nvar certChain = flag.String(\"cert_chain\", \"\", \"Name of file containing certificate chain as concatenated PEM files\")\nvar textOut = flag.Bool(\"text\", true, \"Display certificates as text\")\nvar getFirst = flag.Int64(\"first\", -1, \"First entry to get\")\nvar getLast = flag.Int64(\"last\", -1, \"Last entry to get\")\n\nfunc ctTimestampToTime(ts uint64) time.Time {\n\tsecs := int64(ts \/ 1000)\n\tmsecs := int64(ts % 1000)\n\treturn time.Unix(secs, msecs*1000000)\n}\n\nfunc signatureToString(signed *ct.DigitallySigned) string {\n\treturn fmt.Sprintf(\"Signature: Hash=%v Sign=%v Value=%x\", signed.Algorithm.Hash, signed.Algorithm.Signature, signed.Signature)\n}\n\nfunc getSTH(ctx context.Context, logClient *client.LogClient) {\n\tsth, err := logClient.GetSTH(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ Display the STH\n\twhen := ctTimestampToTime(sth.Timestamp)\n\tfmt.Printf(\"%v: Got STH for %v log (size=%d) at %v, hash %x\\n\", when, sth.Version, sth.TreeSize, *logURI, sth.SHA256RootHash)\n\tfmt.Printf(\"%v\\n\", signatureToString(&sth.TreeHeadSignature))\n}\n\nfunc addChain(ctx context.Context, logClient *client.LogClient) {\n\tif *certChain == \"\" {\n\t\tlog.Fatalf(\"No certificate chain file specified with -cert_chain\")\n\t}\n\trest, err := ioutil.ReadFile(*certChain)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to read certificate file: %v\", err)\n\t}\n\tvar chain []ct.ASN1Cert\n\tfor {\n\t\tvar block *pem.Block\n\t\tblock, rest = pem.Decode(rest)\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\t\tif block.Type == \"CERTIFICATE\" {\n\t\t\tchain = append(chain, ct.ASN1Cert{Data: block.Bytes})\n\t\t}\n\t}\n\tif len(chain) == 0 {\n\t\tlog.Fatalf(\"No certificates found in %s\", *certChain)\n\t}\n\n\t\/\/ Examine the leaf to see if it looks like a pre-certificate.\n\tisPrecert := false\n\tleaf, err := x509.ParseCertificate(chain[0].Data)\n\tif err == nil {\n\t\tcount, _ := x509util.OidInExtensions(x509.OIDExtensionCTPoison, leaf.Extensions)\n\t\tif count > 0 {\n\t\t\tisPrecert = true\n\t\t\tfmt.Print(\"Uploading pre-certificate to log\\n\")\n\t\t}\n\t}\n\n\tvar sct *ct.SignedCertificateTimestamp\n\tif isPrecert {\n\t\tsct, err = logClient.AddPreChain(ctx, chain)\n\t} else {\n\t\tsct, err = logClient.AddChain(ctx, chain)\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ Display the SCT\n\twhen := ctTimestampToTime(sct.Timestamp)\n\tfmt.Printf(\"%v: Uploaded chain of %d certs to %v log at %v\\n\", when, len(chain), sct.SCTVersion, *logURI)\n\tfmt.Printf(\"%v\\n\", signatureToString(&sct.Signature))\n}\n\nfunc getRoots(ctx context.Context, logClient *client.LogClient) {\n\troots, err := logClient.GetAcceptedRoots(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, root := range roots {\n\t\tshowCert(root)\n\t}\n}\n\nfunc getEntries(ctx context.Context, logClient *client.LogClient) {\n\tif *getFirst == -1 {\n\t\tlog.Fatal(\"No -first option supplied\")\n\t}\n\tif *getLast == -1 {\n\t\tlog.Fatal(\"No -last option supplied\")\n\t}\n\tentries, err := logClient.GetEntries(ctx, *getFirst, *getLast)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, entry := range entries {\n\t\tts := entry.Leaf.TimestampedEntry\n\t\twhen := ctTimestampToTime(ts.Timestamp)\n\t\tfmt.Printf(\"Index=%d Timestamp=%v \", entry.Index, when)\n\t\tswitch ts.EntryType {\n\t\tcase ct.X509LogEntryType:\n\t\t\tfmt.Printf(\"X.509 certificate:\\n\")\n\t\t\tshowCert(*ts.X509Entry)\n\t\tcase ct.PrecertLogEntryType:\n\t\t\tfmt.Printf(\"pre-certificate from issuer with keyhash %x:\\n\", ts.PrecertEntry.IssuerKeyHash)\n\t\t\tshowTBSCert(ts.PrecertEntry.TBSCertificate)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Unhandled log entry type %d\", entry.Leaf.TimestampedEntry.EntryType)\n\t\t}\n\t}\n}\n\nfunc showCert(cert ct.ASN1Cert) {\n\tif *textOut {\n\t\tc, err := x509.ParseCertificate(cert.Data)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error parsing certificate: %q\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", x509util.CertificateToString(c))\n\t} else {\n\t\tif err := pem.Encode(os.Stdout, &pem.Block{Type: \"CERTIFICATE\", Bytes: cert.Data}); err != nil {\n\t\t\tlog.Printf(\"Failed to PEM encode cert: %q\", err.Error())\n\t\t}\n\t}\n}\n\nfunc showTBSCert(tbs []byte) {\n\tif *textOut {\n\t\tc, err := x509.ParseTBSCertificate(tbs)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error parsing certificate: %q\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", x509util.CertificateToString(c))\n\t} else {\n\t\tfmt.Printf(\"%x\\n\", tbs)\n\t}\n}\n\nfunc dieWithUsage(msg string) {\n\tfmt.Fprintf(os.Stderr, msg)\n\tfmt.Fprintf(os.Stderr, \"Usage: ctclient [options] <cmd>\\n\"+\n\t\t\"where cmd is one of:\\n\"+\n\t\t\"   sth         retrieve signed tree head\\n\"+\n\t\t\"   upload      upload cert chain and show SCT (needs -cert_chain)\\n\"+\n\t\t\"   getroots    show accepted roots\\n\"+\n\t\t\"   getentries  get log entries (needs -first and -last)\\n\")\n\tos.Exit(1)\n}\n\nfunc main() {\n\tflag.Parse()\n\thttpClient := &http.Client{\n\t\tTimeout: 10 * time.Second,\n\t\tTransport: &http.Transport{\n\t\t\tTLSHandshakeTimeout:   30 * time.Second,\n\t\t\tResponseHeaderTimeout: 30 * time.Second,\n\t\t\tMaxIdleConnsPerHost:   10,\n\t\t\tDisableKeepAlives:     false,\n\t\t\tMaxIdleConns:          100,\n\t\t\tIdleConnTimeout:       90 * time.Second,\n\t\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t},\n\t}\n\tvar opts jsonclient.Options\n\tif *pubKey != \"\" {\n\t\tpubkey, err := ioutil.ReadFile(*pubKey)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\topts.PublicKey = string(pubkey)\n\t}\n\tlogClient, err := client.New(*logURI, httpClient, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\targs := flag.Args()\n\tif len(args) != 1 {\n\t\tdieWithUsage(\"Need command argument\")\n\t}\n\tctx := context.Background()\n\tcmd := args[0]\n\tswitch cmd {\n\tcase \"sth\":\n\t\tgetSTH(ctx, logClient)\n\tcase \"upload\":\n\t\taddChain(ctx, logClient)\n\tcase \"getroots\", \"get_roots\", \"get-roots\":\n\t\tgetRoots(ctx, logClient)\n\tcase \"getentries\", \"get_entries\":\n\t\tgetEntries(ctx, logClient)\n\tdefault:\n\t\tdieWithUsage(fmt.Sprintf(\"Unknown command '%s'\", cmd))\n\t}\n}\n<commit_msg>ctclient: Insert newline between error message and usage message<commit_after>\/\/ Copyright 2016 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ ctclient is a command-line utility for interacting with CT logs.\npackage main\n\nimport (\n\t\"encoding\/pem\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\tct \"github.com\/google\/certificate-transparency-go\"\n\t\"github.com\/google\/certificate-transparency-go\/client\"\n\t\"github.com\/google\/certificate-transparency-go\/jsonclient\"\n\t\"github.com\/google\/certificate-transparency-go\/x509\"\n\t\"github.com\/google\/certificate-transparency-go\/x509util\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar logURI = flag.String(\"log_uri\", \"http:\/\/ct.googleapis.com\/aviator\", \"CT log base URI\")\nvar pubKey = flag.String(\"pub_key\", \"\", \"Name of file containing log's public key\")\nvar certChain = flag.String(\"cert_chain\", \"\", \"Name of file containing certificate chain as concatenated PEM files\")\nvar textOut = flag.Bool(\"text\", true, \"Display certificates as text\")\nvar getFirst = flag.Int64(\"first\", -1, \"First entry to get\")\nvar getLast = flag.Int64(\"last\", -1, \"Last entry to get\")\n\nfunc ctTimestampToTime(ts uint64) time.Time {\n\tsecs := int64(ts \/ 1000)\n\tmsecs := int64(ts % 1000)\n\treturn time.Unix(secs, msecs*1000000)\n}\n\nfunc signatureToString(signed *ct.DigitallySigned) string {\n\treturn fmt.Sprintf(\"Signature: Hash=%v Sign=%v Value=%x\", signed.Algorithm.Hash, signed.Algorithm.Signature, signed.Signature)\n}\n\nfunc getSTH(ctx context.Context, logClient *client.LogClient) {\n\tsth, err := logClient.GetSTH(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ Display the STH\n\twhen := ctTimestampToTime(sth.Timestamp)\n\tfmt.Printf(\"%v: Got STH for %v log (size=%d) at %v, hash %x\\n\", when, sth.Version, sth.TreeSize, *logURI, sth.SHA256RootHash)\n\tfmt.Printf(\"%v\\n\", signatureToString(&sth.TreeHeadSignature))\n}\n\nfunc addChain(ctx context.Context, logClient *client.LogClient) {\n\tif *certChain == \"\" {\n\t\tlog.Fatalf(\"No certificate chain file specified with -cert_chain\")\n\t}\n\trest, err := ioutil.ReadFile(*certChain)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to read certificate file: %v\", err)\n\t}\n\tvar chain []ct.ASN1Cert\n\tfor {\n\t\tvar block *pem.Block\n\t\tblock, rest = pem.Decode(rest)\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\t\tif block.Type == \"CERTIFICATE\" {\n\t\t\tchain = append(chain, ct.ASN1Cert{Data: block.Bytes})\n\t\t}\n\t}\n\tif len(chain) == 0 {\n\t\tlog.Fatalf(\"No certificates found in %s\", *certChain)\n\t}\n\n\t\/\/ Examine the leaf to see if it looks like a pre-certificate.\n\tisPrecert := false\n\tleaf, err := x509.ParseCertificate(chain[0].Data)\n\tif err == nil {\n\t\tcount, _ := x509util.OidInExtensions(x509.OIDExtensionCTPoison, leaf.Extensions)\n\t\tif count > 0 {\n\t\t\tisPrecert = true\n\t\t\tfmt.Print(\"Uploading pre-certificate to log\\n\")\n\t\t}\n\t}\n\n\tvar sct *ct.SignedCertificateTimestamp\n\tif isPrecert {\n\t\tsct, err = logClient.AddPreChain(ctx, chain)\n\t} else {\n\t\tsct, err = logClient.AddChain(ctx, chain)\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ Display the SCT\n\twhen := ctTimestampToTime(sct.Timestamp)\n\tfmt.Printf(\"%v: Uploaded chain of %d certs to %v log at %v\\n\", when, len(chain), sct.SCTVersion, *logURI)\n\tfmt.Printf(\"%v\\n\", signatureToString(&sct.Signature))\n}\n\nfunc getRoots(ctx context.Context, logClient *client.LogClient) {\n\troots, err := logClient.GetAcceptedRoots(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, root := range roots {\n\t\tshowCert(root)\n\t}\n}\n\nfunc getEntries(ctx context.Context, logClient *client.LogClient) {\n\tif *getFirst == -1 {\n\t\tlog.Fatal(\"No -first option supplied\")\n\t}\n\tif *getLast == -1 {\n\t\tlog.Fatal(\"No -last option supplied\")\n\t}\n\tentries, err := logClient.GetEntries(ctx, *getFirst, *getLast)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, entry := range entries {\n\t\tts := entry.Leaf.TimestampedEntry\n\t\twhen := ctTimestampToTime(ts.Timestamp)\n\t\tfmt.Printf(\"Index=%d Timestamp=%v \", entry.Index, when)\n\t\tswitch ts.EntryType {\n\t\tcase ct.X509LogEntryType:\n\t\t\tfmt.Printf(\"X.509 certificate:\\n\")\n\t\t\tshowCert(*ts.X509Entry)\n\t\tcase ct.PrecertLogEntryType:\n\t\t\tfmt.Printf(\"pre-certificate from issuer with keyhash %x:\\n\", ts.PrecertEntry.IssuerKeyHash)\n\t\t\tshowTBSCert(ts.PrecertEntry.TBSCertificate)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Unhandled log entry type %d\", entry.Leaf.TimestampedEntry.EntryType)\n\t\t}\n\t}\n}\n\nfunc showCert(cert ct.ASN1Cert) {\n\tif *textOut {\n\t\tc, err := x509.ParseCertificate(cert.Data)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error parsing certificate: %q\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", x509util.CertificateToString(c))\n\t} else {\n\t\tif err := pem.Encode(os.Stdout, &pem.Block{Type: \"CERTIFICATE\", Bytes: cert.Data}); err != nil {\n\t\t\tlog.Printf(\"Failed to PEM encode cert: %q\", err.Error())\n\t\t}\n\t}\n}\n\nfunc showTBSCert(tbs []byte) {\n\tif *textOut {\n\t\tc, err := x509.ParseTBSCertificate(tbs)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error parsing certificate: %q\", err.Error())\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", x509util.CertificateToString(c))\n\t} else {\n\t\tfmt.Printf(\"%x\\n\", tbs)\n\t}\n}\n\nfunc dieWithUsage(msg string) {\n\tfmt.Fprintln(os.Stderr, msg)\n\tfmt.Fprintf(os.Stderr, \"Usage: ctclient [options] <cmd>\\n\"+\n\t\t\"where cmd is one of:\\n\"+\n\t\t\"   sth         retrieve signed tree head\\n\"+\n\t\t\"   upload      upload cert chain and show SCT (needs -cert_chain)\\n\"+\n\t\t\"   getroots    show accepted roots\\n\"+\n\t\t\"   getentries  get log entries (needs -first and -last)\\n\")\n\tos.Exit(1)\n}\n\nfunc main() {\n\tflag.Parse()\n\thttpClient := &http.Client{\n\t\tTimeout: 10 * time.Second,\n\t\tTransport: &http.Transport{\n\t\t\tTLSHandshakeTimeout:   30 * time.Second,\n\t\t\tResponseHeaderTimeout: 30 * time.Second,\n\t\t\tMaxIdleConnsPerHost:   10,\n\t\t\tDisableKeepAlives:     false,\n\t\t\tMaxIdleConns:          100,\n\t\t\tIdleConnTimeout:       90 * time.Second,\n\t\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t},\n\t}\n\tvar opts jsonclient.Options\n\tif *pubKey != \"\" {\n\t\tpubkey, err := ioutil.ReadFile(*pubKey)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\topts.PublicKey = string(pubkey)\n\t}\n\tlogClient, err := client.New(*logURI, httpClient, opts)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\targs := flag.Args()\n\tif len(args) != 1 {\n\t\tdieWithUsage(\"Need command argument\")\n\t}\n\tctx := context.Background()\n\tcmd := args[0]\n\tswitch cmd {\n\tcase \"sth\":\n\t\tgetSTH(ctx, logClient)\n\tcase \"upload\":\n\t\taddChain(ctx, logClient)\n\tcase \"getroots\", \"get_roots\", \"get-roots\":\n\t\tgetRoots(ctx, logClient)\n\tcase \"getentries\", \"get_entries\":\n\t\tgetEntries(ctx, logClient)\n\tdefault:\n\t\tdieWithUsage(fmt.Sprintf(\"Unknown command '%s'\", cmd))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2018 Banzai Cloud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\twhhttp \"github.com\/slok\/kubewebhook\/pkg\/http\"\n\t\"github.com\/slok\/kubewebhook\/pkg\/log\"\n\t\"github.com\/slok\/kubewebhook\/pkg\/webhook\/mutating\"\n\t\"github.com\/spf13\/viper\"\n\tcorev1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/rest\"\n)\n\ntype vaultConfig struct {\n\taddr       string\n\trole       string\n\tpath       string\n\tskipVerify string\n\tuseAgent   bool\n}\n\nvar vaultAgentConfig = `\npid_file = \".\/pidfile\"\nexit_after_auth = true\n\nauto_auth {\n\tmethod \"kubernetes\" {\n\t\tmount_path = \"%s\"\n\t\tconfig = {\n\t\t\trole = \"%s\"\n\t\t}\n\t}\n\n\tsink \"file\" {\n\t\tconfig = {\n\t\t\tpath = \"\/vault\/token\"\n\t\t}\n\t}\n}`\n\nfunc getInitContainers(vaultConfig vaultConfig) []corev1.Container {\n\tcontainers := []corev1.Container{}\n\n\tif vaultConfig.useAgent {\n\t\tcontainers = append(containers, corev1.Container{\n\t\t\tName:            \"vault-agent\",\n\t\t\tImage:           viper.GetString(\"vault_image\"),\n\t\t\tImagePullPolicy: corev1.PullIfNotPresent,\n\t\t\tCommand:         []string{\"vault\", \"agent\", \"-config=\/vault-agent\/config.hcl\"},\n\t\t\tEnv: []corev1.EnvVar{\n\t\t\t\t{\n\t\t\t\t\tName:  \"VAULT_ADDR\",\n\t\t\t\t\tValue: vaultConfig.addr,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:  \"VAULT_SKIP_VERIFY\",\n\t\t\t\t\tValue: vaultConfig.skipVerify,\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t\t{\n\t\t\t\t\tName:      \"vault-agent-config\",\n\t\t\t\t\tMountPath: \"\/vault-agent\/\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:      \"vault-env\",\n\t\t\t\t\tMountPath: \"\/vault\/\",\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\n\tcontainers = append(containers, corev1.Container{\n\t\tName:            \"copy-vault-env\",\n\t\tImage:           viper.GetString(\"vault_env_image\"),\n\t\tImagePullPolicy: corev1.PullIfNotPresent,\n\t\tCommand:         []string{\"sh\", \"-c\", \"cp \/usr\/local\/bin\/vault-env \/vault\/\"},\n\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t{\n\t\t\t\tName:      \"vault-env\",\n\t\t\t\tMountPath: \"\/vault\/\",\n\t\t\t},\n\t\t},\n\t})\n\n\treturn containers\n}\n\nfunc getVolumes(name string, vaultConfig vaultConfig) []corev1.Volume {\n\tvolumes := []corev1.Volume{\n\t\t{\n\t\t\tName: \"vault-env\",\n\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\tEmptyDir: &corev1.EmptyDirVolumeSource{\n\t\t\t\t\tMedium: corev1.StorageMediumMemory,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tif vaultConfig.useAgent {\n\t\tvolumes = append(volumes, corev1.Volume{\n\t\t\tName: \"vault-agent-config\",\n\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\tConfigMap: &corev1.ConfigMapVolumeSource{\n\t\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\t\tName: name + \"-vault-agent-config\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\n\treturn volumes\n}\n\nfunc vaultSecretsMutator(_ context.Context, obj metav1.Object) (bool, error) {\n\tvar podSpec *corev1.PodSpec\n\n\tswitch v := obj.(type) {\n\tcase *corev1.Pod:\n\t\tpodSpec = &v.Spec\n\tdefault:\n\t\treturn false, nil\n\t}\n\n\tvaultConfig := parseVaultConfig(obj)\n\n\treturn false, mutatePodSpec(obj, podSpec, vaultConfig)\n}\n\nfunc parseVaultConfig(obj metav1.Object) vaultConfig {\n\tvar vaultConfig vaultConfig\n\tannotations := obj.GetAnnotations()\n\tvaultConfig.addr = annotations[\"vault.security.banzaicloud.io\/vault-addr\"]\n\tvaultConfig.role = annotations[\"vault.security.banzaicloud.io\/vault-role\"]\n\tif vaultConfig.role == \"\" {\n\t\tvaultConfig.role = \"default\"\n\t}\n\tvaultConfig.path = annotations[\"vault.security.banzaicloud.io\/vault-path\"]\n\tif vaultConfig.path == \"\" {\n\t\tvaultConfig.path = \"kubernetes\"\n\t}\n\tvaultConfig.skipVerify = annotations[\"vault.security.banzaicloud.io\/vault-skip-verify\"]\n\tvaultConfig.useAgent, _ = strconv.ParseBool(annotations[\"vault.security.banzaicloud.io\/vault-agent\"])\n\treturn vaultConfig\n}\n\nfunc getConfigMapForVaultAgent(obj metav1.Object, vaultConfig vaultConfig) *corev1.ConfigMap {\n\treturn &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: obj.GetName() + \"-vault-agent-config\",\n\t\t\t\/\/ OwnerReferences: []metav1.OwnerReference{\n\t\t\t\/\/ \t{\n\t\t\t\/\/ \t\tName: obj.GetName(),\n\t\t\t\/\/ \t\t\/\/ UID:  obj.GetUID(),\n\t\t\t\/\/ \t},\n\t\t\t\/\/ },\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"config.hcl\": fmt.Sprintf(vaultAgentConfig, vaultConfig.path, vaultConfig.role),\n\t\t},\n\t}\n}\n\nfunc getDataFromConfigmap(cmName string, obj metav1.Object) (map[string]string, error) {\n\tkubeConfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfigMap, err := clientset.CoreV1().ConfigMaps(obj.GetNamespace()).Get(cmName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn configMap.Data, nil\n}\n\nfunc mutateContainers(containers []corev1.Container, vaultConfig vaultConfig, obj metav1.Object) bool {\n\tmutated := false\n\tfor i, container := range containers {\n\t\tvar envVars []corev1.EnvVar\n\t\tfor _, env := range container.Env {\n\t\t\tif strings.HasPrefix(env.Value, \"vault:\") {\n\t\t\t\tenvVars = append(envVars, env)\n\t\t\t}\n\t\t\tif env.ValueFrom != nil {\n\t\t\t\tdata, err := getDataFromConfigmap(env.ValueFrom.ConfigMapKeyRef.Name, obj)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif strings.HasPrefix(data[env.ValueFrom.ConfigMapKeyRef.Key], \"vault:\") {\n\t\t\t\t\tfromCM := corev1.EnvVar{\n\t\t\t\t\t\tName:  env.Name,\n\t\t\t\t\t\tValue: data[env.ValueFrom.ConfigMapKeyRef.Key],\n\t\t\t\t\t}\n\t\t\t\t\tenvVars = append(envVars, fromCM)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(envVars) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tmutated = true\n\n\t\targs := append(container.Command, container.Args...)\n\n\t\tcontainer.Command = []string{\"\/vault\/vault-env\"}\n\t\tcontainer.Args = args\n\n\t\tcontainer.VolumeMounts = append(container.VolumeMounts, []corev1.VolumeMount{\n\t\t\t{\n\t\t\t\tName:      \"vault-env\",\n\t\t\t\tMountPath: \"\/vault\/\",\n\t\t\t},\n\t\t}...)\n\n\t\tcontainer.Env = append(container.Env, []corev1.EnvVar{\n\t\t\t{\n\t\t\t\tName:  \"VAULT_ADDR\",\n\t\t\t\tValue: vaultConfig.addr,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName:  \"VAULT_SKIP_VERIFY\",\n\t\t\t\tValue: vaultConfig.skipVerify,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName:  \"VAULT_PATH\",\n\t\t\t\tValue: vaultConfig.path,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName:  \"VAULT_ROLE\",\n\t\t\t\tValue: vaultConfig.role,\n\t\t\t},\n\t\t}...)\n\n\t\tif vaultConfig.useAgent {\n\t\t\tcontainer.Env = append(container.Env, corev1.EnvVar{\n\t\t\t\tName:  \"VAULT_TOKEN_FILE\",\n\t\t\t\tValue: \"\/vault\/token\",\n\t\t\t})\n\t\t}\n\n\t\tcontainers[i] = container\n\t}\n\n\treturn mutated\n}\n\nfunc mutatePodSpec(obj metav1.Object, podSpec *corev1.PodSpec, vaultConfig vaultConfig) error {\n\n\tkubeConfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinitContainersMutated := mutateContainers(podSpec.InitContainers, vaultConfig, obj)\n\tcontainersMutated := mutateContainers(podSpec.Containers, vaultConfig, obj)\n\n\tif initContainersMutated || containersMutated {\n\n\t\tif vaultConfig.useAgent {\n\n\t\t\tconfigMap := getConfigMapForVaultAgent(obj, vaultConfig)\n\n\t\t\t_, err := clientset.CoreV1().ConfigMaps(obj.GetNamespace()).Create(configMap)\n\t\t\tif err != nil {\n\t\t\t\tif errors.IsAlreadyExists(err) {\n\t\t\t\t\t_, err = clientset.CoreV1().ConfigMaps(obj.GetNamespace()).Update(configMap)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpodSpec.InitContainers = append(getInitContainers(vaultConfig), podSpec.InitContainers...)\n\t\tpodSpec.Volumes = append(podSpec.Volumes, getVolumes(obj.GetName(), vaultConfig)...)\n\t}\n\n\treturn nil\n}\n\nfunc initConfig() {\n\tviper.SetDefault(\"vault_image\", \"vault:latest\")\n\tviper.SetDefault(\"vault_env_image\", \"banzaicloud\/vault-env:latest\")\n\tviper.AutomaticEnv()\n}\n\nfunc handlerFor(config mutating.WebhookConfig, mutator mutating.MutatorFunc, logger log.Logger) http.Handler {\n\twebhook, err := mutating.NewWebhook(config, mutator, nil, nil, logger)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error creating webhook: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\thandler, err := whhttp.HandlerFor(webhook)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error creating webhook: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn handler\n}\n\nfunc main() {\n\n\tinitConfig()\n\n\tlogger := &log.Std{Debug: viper.GetBool(\"debug\")}\n\n\tmutator := mutating.MutatorFunc(vaultSecretsMutator)\n\n\tpodHandler := handlerFor(mutating.WebhookConfig{Name: \"vault-secrets-pods\", Obj: &corev1.Pod{}}, mutator, logger)\n\n\tmux := http.NewServeMux()\n\tmux.Handle(\"\/pods\", podHandler)\n\n\tlogger.Infof(\"Listening on :443\")\n\terr := http.ListenAndServeTLS(\":443\", viper.GetString(\"tls_cert_file\"), viper.GetString(\"tls_private_key_file\"), mux)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error serving webhook: %s\", err)\n\t\tos.Exit(1)\n\t}\n}\n<commit_msg>add secretKeyRef<commit_after>\/\/ Copyright © 2018 Banzai Cloud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\twhhttp \"github.com\/slok\/kubewebhook\/pkg\/http\"\n\t\"github.com\/slok\/kubewebhook\/pkg\/log\"\n\t\"github.com\/slok\/kubewebhook\/pkg\/webhook\/mutating\"\n\t\"github.com\/spf13\/viper\"\n\tcorev1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/rest\"\n)\n\ntype vaultConfig struct {\n\taddr       string\n\trole       string\n\tpath       string\n\tskipVerify string\n\tuseAgent   bool\n}\n\nvar vaultAgentConfig = `\npid_file = \".\/pidfile\"\nexit_after_auth = true\n\nauto_auth {\n\tmethod \"kubernetes\" {\n\t\tmount_path = \"%s\"\n\t\tconfig = {\n\t\t\trole = \"%s\"\n\t\t}\n\t}\n\n\tsink \"file\" {\n\t\tconfig = {\n\t\t\tpath = \"\/vault\/token\"\n\t\t}\n\t}\n}`\n\nfunc getInitContainers(vaultConfig vaultConfig) []corev1.Container {\n\tcontainers := []corev1.Container{}\n\n\tif vaultConfig.useAgent {\n\t\tcontainers = append(containers, corev1.Container{\n\t\t\tName:            \"vault-agent\",\n\t\t\tImage:           viper.GetString(\"vault_image\"),\n\t\t\tImagePullPolicy: corev1.PullIfNotPresent,\n\t\t\tCommand:         []string{\"vault\", \"agent\", \"-config=\/vault-agent\/config.hcl\"},\n\t\t\tEnv: []corev1.EnvVar{\n\t\t\t\t{\n\t\t\t\t\tName:  \"VAULT_ADDR\",\n\t\t\t\t\tValue: vaultConfig.addr,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:  \"VAULT_SKIP_VERIFY\",\n\t\t\t\t\tValue: vaultConfig.skipVerify,\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t\t{\n\t\t\t\t\tName:      \"vault-agent-config\",\n\t\t\t\t\tMountPath: \"\/vault-agent\/\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName:      \"vault-env\",\n\t\t\t\t\tMountPath: \"\/vault\/\",\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\n\tcontainers = append(containers, corev1.Container{\n\t\tName:            \"copy-vault-env\",\n\t\tImage:           viper.GetString(\"vault_env_image\"),\n\t\tImagePullPolicy: corev1.PullIfNotPresent,\n\t\tCommand:         []string{\"sh\", \"-c\", \"cp \/usr\/local\/bin\/vault-env \/vault\/\"},\n\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t{\n\t\t\t\tName:      \"vault-env\",\n\t\t\t\tMountPath: \"\/vault\/\",\n\t\t\t},\n\t\t},\n\t})\n\n\treturn containers\n}\n\nfunc getVolumes(name string, vaultConfig vaultConfig) []corev1.Volume {\n\tvolumes := []corev1.Volume{\n\t\t{\n\t\t\tName: \"vault-env\",\n\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\tEmptyDir: &corev1.EmptyDirVolumeSource{\n\t\t\t\t\tMedium: corev1.StorageMediumMemory,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tif vaultConfig.useAgent {\n\t\tvolumes = append(volumes, corev1.Volume{\n\t\t\tName: \"vault-agent-config\",\n\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\tConfigMap: &corev1.ConfigMapVolumeSource{\n\t\t\t\t\tLocalObjectReference: corev1.LocalObjectReference{\n\t\t\t\t\t\tName: name + \"-vault-agent-config\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\n\treturn volumes\n}\n\nfunc vaultSecretsMutator(_ context.Context, obj metav1.Object) (bool, error) {\n\tvar podSpec *corev1.PodSpec\n\n\tswitch v := obj.(type) {\n\tcase *corev1.Pod:\n\t\tpodSpec = &v.Spec\n\tdefault:\n\t\treturn false, nil\n\t}\n\n\tvaultConfig := parseVaultConfig(obj)\n\n\treturn false, mutatePodSpec(obj, podSpec, vaultConfig)\n}\n\nfunc parseVaultConfig(obj metav1.Object) vaultConfig {\n\tvar vaultConfig vaultConfig\n\tannotations := obj.GetAnnotations()\n\tvaultConfig.addr = annotations[\"vault.security.banzaicloud.io\/vault-addr\"]\n\tvaultConfig.role = annotations[\"vault.security.banzaicloud.io\/vault-role\"]\n\tif vaultConfig.role == \"\" {\n\t\tvaultConfig.role = \"default\"\n\t}\n\tvaultConfig.path = annotations[\"vault.security.banzaicloud.io\/vault-path\"]\n\tif vaultConfig.path == \"\" {\n\t\tvaultConfig.path = \"kubernetes\"\n\t}\n\tvaultConfig.skipVerify = annotations[\"vault.security.banzaicloud.io\/vault-skip-verify\"]\n\tvaultConfig.useAgent, _ = strconv.ParseBool(annotations[\"vault.security.banzaicloud.io\/vault-agent\"])\n\treturn vaultConfig\n}\n\nfunc getConfigMapForVaultAgent(obj metav1.Object, vaultConfig vaultConfig) *corev1.ConfigMap {\n\treturn &corev1.ConfigMap{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: obj.GetName() + \"-vault-agent-config\",\n\t\t\t\/\/ OwnerReferences: []metav1.OwnerReference{\n\t\t\t\/\/ \t{\n\t\t\t\/\/ \t\tName: obj.GetName(),\n\t\t\t\/\/ \t\t\/\/ UID:  obj.GetUID(),\n\t\t\t\/\/ \t},\n\t\t\t\/\/ },\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"config.hcl\": fmt.Sprintf(vaultAgentConfig, vaultConfig.path, vaultConfig.role),\n\t\t},\n\t}\n}\n\nfunc getDataFromConfigmap(cmName string, ns string) (map[string]string, error) {\n\tkubeConfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfigMap, err := clientset.CoreV1().ConfigMaps(ns).Get(cmName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn configMap.Data, nil\n}\n\nfunc getDataFromSecret(secretName string, ns string) (map[string][]byte, error) {\n\tkubeConfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsecret, err := clientset.CoreV1().Secrets(ns).Get(secretName, metav1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn secret.Data, nil\n}\n\nfunc mutateContainers(containers []corev1.Container, vaultConfig vaultConfig, ns string) bool {\n\tmutated := false\n\tfor i, container := range containers {\n\t\tvar envVars []corev1.EnvVar\n\t\tfor _, env := range container.Env {\n\t\t\tif strings.HasPrefix(env.Value, \"vault:\") {\n\t\t\t\tenvVars = append(envVars, env)\n\t\t\t}\n\t\t\tif env.ValueFrom != nil {\n\t\t\t\tif env.ValueFrom.ConfigMapKeyRef != nil {\n\t\t\t\t\tdata, err := getDataFromConfigmap(env.ValueFrom.ConfigMapKeyRef.Name, ns)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif strings.HasPrefix(data[env.ValueFrom.ConfigMapKeyRef.Key], \"vault:\") {\n\t\t\t\t\t\tfromCM := corev1.EnvVar{\n\t\t\t\t\t\t\tName:  env.Name,\n\t\t\t\t\t\t\tValue: data[env.ValueFrom.ConfigMapKeyRef.Key],\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenvVars = append(envVars, fromCM)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif env.ValueFrom.SecretKeyRef != nil {\n\t\t\t\t\tdata, err := getDataFromSecret(env.ValueFrom.SecretKeyRef.Name, ns)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Println(string(data[env.ValueFrom.SecretKeyRef.Key]))\n\t\t\t\t\tif strings.HasPrefix(string(data[env.ValueFrom.SecretKeyRef.Key]), \"vault:\") {\n\t\t\t\t\t\tfromSecret := corev1.EnvVar{\n\t\t\t\t\t\t\tName:  env.Name,\n\t\t\t\t\t\t\tValue: string(data[env.ValueFrom.SecretKeyRef.Key]),\n\t\t\t\t\t\t}\n\t\t\t\t\t\tenvVars = append(envVars, fromSecret)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif len(envVars) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tmutated = true\n\n\t\targs := append(container.Command, container.Args...)\n\n\t\tcontainer.Command = []string{\"\/vault\/vault-env\"}\n\t\tcontainer.Args = args\n\n\t\tcontainer.VolumeMounts = append(container.VolumeMounts, []corev1.VolumeMount{\n\t\t\t{\n\t\t\t\tName:      \"vault-env\",\n\t\t\t\tMountPath: \"\/vault\/\",\n\t\t\t},\n\t\t}...)\n\n\t\tcontainer.Env = append(container.Env, []corev1.EnvVar{\n\t\t\t{\n\t\t\t\tName:  \"VAULT_ADDR\",\n\t\t\t\tValue: vaultConfig.addr,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName:  \"VAULT_SKIP_VERIFY\",\n\t\t\t\tValue: vaultConfig.skipVerify,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName:  \"VAULT_PATH\",\n\t\t\t\tValue: vaultConfig.path,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName:  \"VAULT_ROLE\",\n\t\t\t\tValue: vaultConfig.role,\n\t\t\t},\n\t\t}...)\n\n\t\tif vaultConfig.useAgent {\n\t\t\tcontainer.Env = append(container.Env, corev1.EnvVar{\n\t\t\t\tName:  \"VAULT_TOKEN_FILE\",\n\t\t\t\tValue: \"\/vault\/token\",\n\t\t\t})\n\t\t}\n\n\t\tcontainers[i] = container\n\t}\n\n\treturn mutated\n}\n\nfunc mutatePodSpec(obj metav1.Object, podSpec *corev1.PodSpec, vaultConfig vaultConfig) error {\n\n\tkubeConfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(kubeConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinitContainersMutated := mutateContainers(podSpec.InitContainers, vaultConfig, obj.GetNamespace())\n\tcontainersMutated := mutateContainers(podSpec.Containers, vaultConfig, obj.GetNamespace())\n\n\tif initContainersMutated || containersMutated {\n\n\t\tif vaultConfig.useAgent {\n\n\t\t\tconfigMap := getConfigMapForVaultAgent(obj, vaultConfig)\n\n\t\t\t_, err := clientset.CoreV1().ConfigMaps(obj.GetNamespace()).Create(configMap)\n\t\t\tif err != nil {\n\t\t\t\tif errors.IsAlreadyExists(err) {\n\t\t\t\t\t_, err = clientset.CoreV1().ConfigMaps(obj.GetNamespace()).Update(configMap)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tpodSpec.InitContainers = append(getInitContainers(vaultConfig), podSpec.InitContainers...)\n\t\tpodSpec.Volumes = append(podSpec.Volumes, getVolumes(obj.GetName(), vaultConfig)...)\n\t}\n\n\treturn nil\n}\n\nfunc initConfig() {\n\tviper.SetDefault(\"vault_image\", \"vault:latest\")\n\tviper.SetDefault(\"vault_env_image\", \"banzaicloud\/vault-env:latest\")\n\tviper.AutomaticEnv()\n}\n\nfunc handlerFor(config mutating.WebhookConfig, mutator mutating.MutatorFunc, logger log.Logger) http.Handler {\n\twebhook, err := mutating.NewWebhook(config, mutator, nil, nil, logger)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error creating webhook: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\thandler, err := whhttp.HandlerFor(webhook)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error creating webhook: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn handler\n}\n\nfunc main() {\n\n\tinitConfig()\n\n\tlogger := &log.Std{Debug: viper.GetBool(\"debug\")}\n\n\tmutator := mutating.MutatorFunc(vaultSecretsMutator)\n\n\tpodHandler := handlerFor(mutating.WebhookConfig{Name: \"vault-secrets-pods\", Obj: &corev1.Pod{}}, mutator, logger)\n\n\tmux := http.NewServeMux()\n\tmux.Handle(\"\/pods\", podHandler)\n\n\tlogger.Infof(\"Listening on :443\")\n\terr := http.ListenAndServeTLS(\":443\", viper.GetString(\"tls_cert_file\"), viper.GetString(\"tls_private_key_file\"), mux)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"error serving webhook: %s\", err)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package daemon\n\nimport (\n\t\"fmt\"\n\t\"github.com\/andres-erbsen\/chatterbox\/proto\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc handleError(err error, t *testing.T) {\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestSpawnConversationInOutbox(t *testing.T) {\n\t\/\/ init the file system + configuration structure\n\trootDir, err := ioutil.TempDir(\"\", \"\")\n\tdefer os.RemoveAll(rootDir)\n\thandleError(err, t)\n\n\tconf := Config{\n\t\tRootDir:    rootDir,\n\t\tNow:        func() time.Time { return time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) },\n\t\tTempPrefix: \"some_ui\",\n\t}\n\n\terr = InitFs(conf)\n\thandleError(err, t)\n\n\tsubject := \"test subject\"\n\trecipients := []string{\"recipient_dename_b\", \"recipient_dename_a\"}\n\tmessages := [][]byte{[]byte(\"message1\"), []byte(\"message2\")}\n\terr = SpawnConversationInOutbox(conf, subject, recipients, messages)\n\thandleError(err, t)\n\n\t\/\/ check that a conversation exists in the outbox with the correct name\n\toutboxDir := conf.OutboxDir()\n\texpectedName := \"2009-11-10T23:00:00Z-0-user_dename-recipient_dename_a-recipient_dename_b\"\n\t_, err = os.Stat(filepath.Join(outboxDir, expectedName))\n\thandleError(err, t)\n\n\t\/\/ check that it has a valid metadata file\n\tmetadataBytes, err := ioutil.ReadFile(filepath.Join(outboxDir, expectedName, MetadataFileName))\n\thandleError(err, t)\n\tmetadataProto := new(proto.ConversationMetadata)\n\terr = metadataProto.Unmarshal(metadataBytes)\n\thandleError(err, t)\n\n\t\/\/ check that it has all message files; for now assume they have the correct contents\n\tfiles, err := ioutil.ReadDir(filepath.Join(outboxDir, expectedName))\n\thandleError(err, t)\n\tif len(files) != 3 { \/\/ metadata file + 2 messages\n\t\tt.Error(fmt.Sprintf(\"Wrong number of files %d in outgoing conversation; should be 3\", len(files)))\n\t}\n\n\t\/\/ check that the temp directory has been cleaned up\n\tfiles, err = ioutil.ReadDir(conf.TmpDir())\n\thandleError(err, t)\n\tif len(files) > 0 {\n\t\tt.Error(\"tmp directory not cleaned up\")\n\t}\n}\n<commit_msg>fix broken test<commit_after>package daemon\n\nimport (\n\t\"fmt\"\n\t\"github.com\/andres-erbsen\/chatterbox\/proto\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc handleError(err error, t *testing.T) {\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestSpawnConversationInOutbox(t *testing.T) {\n\t\/\/ init the file system + configuration structure\n\trootDir, err := ioutil.TempDir(\"\", \"\")\n\tdefer os.RemoveAll(rootDir)\n\thandleError(err, t)\n\n\tconf := &Config{\n\t\tRootDir:    rootDir,\n\t\tNow:        func() time.Time { return time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) },\n\t\tTempPrefix: \"some_ui\",\n\t}\n\n\terr = InitFs(conf)\n\thandleError(err, t)\n\n\tsubject := \"test subject\"\n\trecipients := []string{\"recipient_dename_b\", \"recipient_dename_a\"}\n\tmessages := [][]byte{[]byte(\"message1\"), []byte(\"message2\")}\n\terr = SpawnConversationInOutbox(conf, subject, recipients, messages)\n\thandleError(err, t)\n\n\t\/\/ check that a conversation exists in the outbox with the correct name\n\toutboxDir := conf.OutboxDir()\n\texpectedName := \"2009-11-10T23:00:00Z-0-user_dename-recipient_dename_a-recipient_dename_b\"\n\t_, err = os.Stat(filepath.Join(outboxDir, expectedName))\n\thandleError(err, t)\n\n\t\/\/ check that it has a valid metadata file\n\tmetadataBytes, err := ioutil.ReadFile(filepath.Join(outboxDir, expectedName, MetadataFileName))\n\thandleError(err, t)\n\tmetadataProto := new(proto.ConversationMetadata)\n\terr = metadataProto.Unmarshal(metadataBytes)\n\thandleError(err, t)\n\n\t\/\/ check that it has all message files; for now assume they have the correct contents\n\tfiles, err := ioutil.ReadDir(filepath.Join(outboxDir, expectedName))\n\thandleError(err, t)\n\tif len(files) != 3 { \/\/ metadata file + 2 messages\n\t\tt.Error(fmt.Sprintf(\"Wrong number of files %d in outgoing conversation; should be 3\", len(files)))\n\t}\n\n\t\/\/ check that the temp directory has been cleaned up\n\tfiles, err = ioutil.ReadDir(conf.TmpDir())\n\thandleError(err, t)\n\tif len(files) > 0 {\n\t\tt.Error(\"tmp directory not cleaned up\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package discordgo\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"sync\/atomic\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ VARS NEEDED FOR TESTING\nvar (\n\tdg    *Session \/\/ Stores a global discordgo user session\n\tdgBot *Session \/\/ Stores a global discordgo bot session\n\n\tenvToken    = os.Getenv(\"DGU_TOKEN\")  \/\/ Token to use when authenticating the user account\n\tenvBotToken = os.Getenv(\"DGB_TOKEN\")  \/\/ Token to use when authenticating the bot account\n\tenvGuild    = os.Getenv(\"DG_GUILD\")   \/\/ Guild ID to use for tests\n\tenvChannel  = os.Getenv(\"DG_CHANNEL\") \/\/ Channel ID to use for tests\n\tenvAdmin    = os.Getenv(\"DG_ADMIN\")   \/\/ User ID of admin user to use for tests\n)\n\nfunc init() {\n\tfmt.Println(\"Init is being called.\")\n\tif envBotToken != \"\" {\n\t\tif d, err := New(envBotToken); err == nil {\n\t\t\tdgBot = d\n\t\t}\n\t}\n\n\tif d, err := New(envToken); err == nil {\n\t\tdg = d\n\t} else {\n\t\tfmt.Println(\"dg is nil, error\", err)\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ START OF TESTS\n\n\/\/ TestNew tests the New() function without any arguments.  This should return\n\/\/ a valid Session{} struct and no errors.\nfunc TestNew(t *testing.T) {\n\n\t_, err := New()\n\tif err != nil {\n\t\tt.Errorf(\"New() returned error: %+v\", err)\n\t}\n}\n\n\/\/ TestInvalidToken tests the New() function with an invalid token\nfunc TestInvalidToken(t *testing.T) {\n\td, err := New(\"asjkldhflkjasdh\")\n\tif err != nil {\n\t\tt.Fatalf(\"New(InvalidToken) returned error: %+v\", err)\n\t}\n\n\t\/\/ New with just a token does not do any communication, so attempt an api call.\n\t_, err = d.UserSettings()\n\tif err == nil {\n\t\tt.Errorf(\"New(InvalidToken), d.UserSettings returned nil error.\")\n\t}\n}\n\n\/\/ TestNewToken tests the New() function with a Token.\nfunc TestNewToken(t *testing.T) {\n\n\tif envToken == \"\" {\n\t\tt.Skip(\"Skipping New(token), DGU_TOKEN not set\")\n\t}\n\n\td, err := New(envToken)\n\tif err != nil {\n\t\tt.Fatalf(\"New(envToken) returned error: %+v\", err)\n\t}\n\n\tif d == nil {\n\t\tt.Fatal(\"New(envToken), d is nil, should be Session{}\")\n\t}\n\n\tif d.Token == \"\" {\n\t\tt.Fatal(\"New(envToken), d.Token is empty, should be a valid Token.\")\n\t}\n}\n\nfunc TestOpenClose(t *testing.T) {\n\tif envToken == \"\" {\n\t\tt.Skip(\"Skipping TestClose, DGU_TOKEN not set\")\n\t}\n\n\td, err := New(envToken)\n\tif err != nil {\n\t\tt.Fatalf(\"TestClose, New(envToken) returned error: %+v\", err)\n\t}\n\n\tif err = d.Open(); err != nil {\n\t\tt.Fatalf(\"TestClose, d.Open failed: %+v\", err)\n\t}\n\n\t\/\/ We need a better way to know the session is ready for use,\n\t\/\/ this is totally gross.\n\tstart := time.Now()\n\tfor {\n\t\td.RLock()\n\t\tif d.DataReady {\n\t\t\td.RUnlock()\n\t\t\tbreak\n\t\t}\n\t\td.RUnlock()\n\n\t\tif time.Since(start) > 10*time.Second {\n\t\t\tt.Fatal(\"DataReady never became true.yy\")\n\t\t}\n\t\truntime.Gosched()\n\t}\n\n\t\/\/ TODO find a better way\n\t\/\/ Add a small sleep here to make sure heartbeat and other events\n\t\/\/ have enough time to get fired.  Need a way to actually check\n\t\/\/ those events.\n\ttime.Sleep(2 * time.Second)\n\n\t\/\/ UpdateStatus - maybe we move this into wsapi_test.go but the websocket\n\t\/\/ created here is needed.  This helps tests that the websocket was setup\n\t\/\/ and it is working.\n\tif err = d.UpdateGameStatus(0, time.Now().String()); err != nil {\n\t\tt.Errorf(\"UpdateStatus error: %+v\", err)\n\t}\n\n\tif err = d.Close(); err != nil {\n\t\tt.Fatalf(\"TestClose, d.Close failed: %+v\", err)\n\t}\n}\n\nfunc TestAddHandler(t *testing.T) {\n\n\ttestHandlerCalled := int32(0)\n\ttestHandler := func(s *Session, m *MessageCreate) {\n\t\tatomic.AddInt32(&testHandlerCalled, 1)\n\t}\n\n\tinterfaceHandlerCalled := int32(0)\n\tinterfaceHandler := func(s *Session, i interface{}) {\n\t\tatomic.AddInt32(&interfaceHandlerCalled, 1)\n\t}\n\n\tbogusHandlerCalled := int32(0)\n\tbogusHandler := func(s *Session, se *Session) {\n\t\tatomic.AddInt32(&bogusHandlerCalled, 1)\n\t}\n\n\td := Session{}\n\td.AddHandler(testHandler)\n\td.AddHandler(testHandler)\n\n\td.AddHandler(interfaceHandler)\n\td.AddHandler(bogusHandler)\n\n\td.handleEvent(messageCreateEventType, &MessageCreate{})\n\td.handleEvent(messageDeleteEventType, &MessageDelete{})\n\n\t<-time.After(500 * time.Millisecond)\n\n\t\/\/ testHandler will be called twice because it was added twice.\n\tif atomic.LoadInt32(&testHandlerCalled) != 2 {\n\t\tt.Fatalf(\"testHandler was not called twice.\")\n\t}\n\n\t\/\/ interfaceHandler will be called twice, once for each event.\n\tif atomic.LoadInt32(&interfaceHandlerCalled) != 2 {\n\t\tt.Fatalf(\"interfaceHandler was not called twice.\")\n\t}\n\n\tif atomic.LoadInt32(&bogusHandlerCalled) != 0 {\n\t\tt.Fatalf(\"bogusHandler was called.\")\n\t}\n}\n\nfunc TestRemoveHandler(t *testing.T) {\n\n\ttestHandlerCalled := int32(0)\n\ttestHandler := func(s *Session, m *MessageCreate) {\n\t\tatomic.AddInt32(&testHandlerCalled, 1)\n\t}\n\n\td := Session{}\n\tr := d.AddHandler(testHandler)\n\n\td.handleEvent(messageCreateEventType, &MessageCreate{})\n\n\tr()\n\n\td.handleEvent(messageCreateEventType, &MessageCreate{})\n\n\t<-time.After(500 * time.Millisecond)\n\n\t\/\/ testHandler will be called once, as it was removed in between calls.\n\tif atomic.LoadInt32(&testHandlerCalled) != 1 {\n\t\tt.Fatalf(\"testHandler was not called once.\")\n\t}\n}\n<commit_msg>feat: dropped unnecessary tests for New function<commit_after>package discordgo\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"sync\/atomic\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ VARS NEEDED FOR TESTING\nvar (\n\tdg    *Session \/\/ Stores a global discordgo user session\n\tdgBot *Session \/\/ Stores a global discordgo bot session\n\n\tenvToken    = os.Getenv(\"DGU_TOKEN\")  \/\/ Token to use when authenticating the user account\n\tenvBotToken = os.Getenv(\"DGB_TOKEN\")  \/\/ Token to use when authenticating the bot account\n\tenvGuild    = os.Getenv(\"DG_GUILD\")   \/\/ Guild ID to use for tests\n\tenvChannel  = os.Getenv(\"DG_CHANNEL\") \/\/ Channel ID to use for tests\n\tenvAdmin    = os.Getenv(\"DG_ADMIN\")   \/\/ User ID of admin user to use for tests\n)\n\nfunc init() {\n\tfmt.Println(\"Init is being called.\")\n\tif envBotToken != \"\" {\n\t\tif d, err := New(envBotToken); err == nil {\n\t\t\tdgBot = d\n\t\t}\n\t}\n\n\tif d, err := New(envToken); err == nil {\n\t\tdg = d\n\t} else {\n\t\tfmt.Println(\"dg is nil, error\", err)\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ START OF TESTS\n\n\/\/ TestNewToken tests the New() function with a Token.\nfunc TestNewToken(t *testing.T) {\n\n\tif envToken == \"\" {\n\t\tt.Skip(\"Skipping New(token), DGU_TOKEN not set\")\n\t}\n\n\td, err := New(envToken)\n\tif err != nil {\n\t\tt.Fatalf(\"New(envToken) returned error: %+v\", err)\n\t}\n\n\tif d == nil {\n\t\tt.Fatal(\"New(envToken), d is nil, should be Session{}\")\n\t}\n\n\tif d.Token == \"\" {\n\t\tt.Fatal(\"New(envToken), d.Token is empty, should be a valid Token.\")\n\t}\n}\n\nfunc TestOpenClose(t *testing.T) {\n\tif envToken == \"\" {\n\t\tt.Skip(\"Skipping TestClose, DGU_TOKEN not set\")\n\t}\n\n\td, err := New(envToken)\n\tif err != nil {\n\t\tt.Fatalf(\"TestClose, New(envToken) returned error: %+v\", err)\n\t}\n\n\tif err = d.Open(); err != nil {\n\t\tt.Fatalf(\"TestClose, d.Open failed: %+v\", err)\n\t}\n\n\t\/\/ We need a better way to know the session is ready for use,\n\t\/\/ this is totally gross.\n\tstart := time.Now()\n\tfor {\n\t\td.RLock()\n\t\tif d.DataReady {\n\t\t\td.RUnlock()\n\t\t\tbreak\n\t\t}\n\t\td.RUnlock()\n\n\t\tif time.Since(start) > 10*time.Second {\n\t\t\tt.Fatal(\"DataReady never became true.yy\")\n\t\t}\n\t\truntime.Gosched()\n\t}\n\n\t\/\/ TODO find a better way\n\t\/\/ Add a small sleep here to make sure heartbeat and other events\n\t\/\/ have enough time to get fired.  Need a way to actually check\n\t\/\/ those events.\n\ttime.Sleep(2 * time.Second)\n\n\t\/\/ UpdateStatus - maybe we move this into wsapi_test.go but the websocket\n\t\/\/ created here is needed.  This helps tests that the websocket was setup\n\t\/\/ and it is working.\n\tif err = d.UpdateGameStatus(0, time.Now().String()); err != nil {\n\t\tt.Errorf(\"UpdateStatus error: %+v\", err)\n\t}\n\n\tif err = d.Close(); err != nil {\n\t\tt.Fatalf(\"TestClose, d.Close failed: %+v\", err)\n\t}\n}\n\nfunc TestAddHandler(t *testing.T) {\n\n\ttestHandlerCalled := int32(0)\n\ttestHandler := func(s *Session, m *MessageCreate) {\n\t\tatomic.AddInt32(&testHandlerCalled, 1)\n\t}\n\n\tinterfaceHandlerCalled := int32(0)\n\tinterfaceHandler := func(s *Session, i interface{}) {\n\t\tatomic.AddInt32(&interfaceHandlerCalled, 1)\n\t}\n\n\tbogusHandlerCalled := int32(0)\n\tbogusHandler := func(s *Session, se *Session) {\n\t\tatomic.AddInt32(&bogusHandlerCalled, 1)\n\t}\n\n\td := Session{}\n\td.AddHandler(testHandler)\n\td.AddHandler(testHandler)\n\n\td.AddHandler(interfaceHandler)\n\td.AddHandler(bogusHandler)\n\n\td.handleEvent(messageCreateEventType, &MessageCreate{})\n\td.handleEvent(messageDeleteEventType, &MessageDelete{})\n\n\t<-time.After(500 * time.Millisecond)\n\n\t\/\/ testHandler will be called twice because it was added twice.\n\tif atomic.LoadInt32(&testHandlerCalled) != 2 {\n\t\tt.Fatalf(\"testHandler was not called twice.\")\n\t}\n\n\t\/\/ interfaceHandler will be called twice, once for each event.\n\tif atomic.LoadInt32(&interfaceHandlerCalled) != 2 {\n\t\tt.Fatalf(\"interfaceHandler was not called twice.\")\n\t}\n\n\tif atomic.LoadInt32(&bogusHandlerCalled) != 0 {\n\t\tt.Fatalf(\"bogusHandler was called.\")\n\t}\n}\n\nfunc TestRemoveHandler(t *testing.T) {\n\n\ttestHandlerCalled := int32(0)\n\ttestHandler := func(s *Session, m *MessageCreate) {\n\t\tatomic.AddInt32(&testHandlerCalled, 1)\n\t}\n\n\td := Session{}\n\tr := d.AddHandler(testHandler)\n\n\td.handleEvent(messageCreateEventType, &MessageCreate{})\n\n\tr()\n\n\td.handleEvent(messageCreateEventType, &MessageCreate{})\n\n\t<-time.After(500 * time.Millisecond)\n\n\t\/\/ testHandler will be called once, as it was removed in between calls.\n\tif atomic.LoadInt32(&testHandlerCalled) != 1 {\n\t\tt.Fatalf(\"testHandler was not called once.\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ lint_subject_common_name_not_from_san.go\n\/************************************************\nCAB: 7.1.4.2.2\nIf present, this field MUST contain a single IP address\nor Fully‐Qualified Domain Name that is one of the values\ncontained in the Certificate’s subjectAltName extension (see Section 7.1.4.2.1).\n************************************************\/\n\npackage lints\n\nimport (\n\t\"github.com\/zmap\/zcrypto\/x509\"\n\t\"github.com\/zmap\/zlint\/util\"\n)\n\ntype subjectCommonNameNotFromSAN struct {\n\t\/\/ Internal data here\n}\n\nfunc (l *subjectCommonNameNotFromSAN) Initialize() error {\n\treturn nil\n}\n\nfunc (l *subjectCommonNameNotFromSAN) CheckApplies(c *x509.Certificate) bool {\n\treturn c.Subject.CommonName != \"\"\n}\n\nfunc (l *subjectCommonNameNotFromSAN) RunTest(c *x509.Certificate) (ResultStruct, error) {\n\tcn := c.Subject.CommonName\n\n\tfor _, dn := range c.DNSNames {\n\t\tif cn == dn {\n\t\t\treturn ResultStruct{Result: Pass}, nil\n\t\t}\n\t}\n\n\tfor _, ip := range c.IPAddresses {\n\t\tif cn == string(ip) {\n\t\t\treturn ResultStruct{Result: Pass}, nil\n\t\t}\n\t}\n\n\treturn ResultStruct{Result: Error}, nil\n}\n\nfunc init() {\n\tRegisterLint(&Lint{\n\t\tName:          \"e_subject_common_name_not_from_san\",\n\t\tDescription:   \"The common name field must include only names from the SAN extension.\",\n\t\tProvidence:    \"CAB: 7.1.4.2.2\",\n\t\tEffectiveDate: util.CABEffectiveDate,\n\t\tTest:          &subjectCommonNameNotFromSAN{}})\n}\n<commit_msg>fixing bug in ip checking for common names (#19)<commit_after>\/\/ lint_subject_common_name_not_from_san.go\n\/************************************************\nCAB: 7.1.4.2.2\nIf present, this field MUST contain a single IP address\nor Fully‐Qualified Domain Name that is one of the values\ncontained in the Certificate’s subjectAltName extension (see Section 7.1.4.2.1).\n************************************************\/\n\npackage lints\n\nimport (\n\t\"github.com\/zmap\/zcrypto\/x509\"\n\t\"github.com\/zmap\/zlint\/util\"\n)\n\ntype subjectCommonNameNotFromSAN struct {\n\t\/\/ Internal data here\n}\n\nfunc (l *subjectCommonNameNotFromSAN) Initialize() error {\n\treturn nil\n}\n\nfunc (l *subjectCommonNameNotFromSAN) CheckApplies(c *x509.Certificate) bool {\n\treturn c.Subject.CommonName != \"\"\n}\n\nfunc (l *subjectCommonNameNotFromSAN) RunTest(c *x509.Certificate) (ResultStruct, error) {\n\tcn := c.Subject.CommonName\n\n\tfor _, dn := range c.DNSNames {\n\t\tif cn == dn {\n\t\t\treturn ResultStruct{Result: Pass}, nil\n\t\t}\n\t}\n\n\tfor _, ip := range c.IPAddresses {\n\t\tif cn == ip.String() {\n\t\t\treturn ResultStruct{Result: Pass}, nil\n\t\t}\n\t}\n\n\treturn ResultStruct{Result: Error}, nil\n}\n\nfunc init() {\n\tRegisterLint(&Lint{\n\t\tName:          \"e_subject_common_name_not_from_san\",\n\t\tDescription:   \"The common name field must include only names from the SAN extension.\",\n\t\tProvidence:    \"CAB: 7.1.4.2.2\",\n\t\tEffectiveDate: util.CABEffectiveDate,\n\t\tTest:          &subjectCommonNameNotFromSAN{}})\n}\n<|endoftext|>"}
{"text":"<commit_before>package sched\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tAsterisk = \"*\"\n\tQuestion = \"?\"\n\tHyphen   = \"-\"\n\tSlash    = \"\/\"\n\tComma    = \",\"\n\tHash     = \"#\"\n\tLast     = \"L\"\n\tWeekday  = \"W\"\n\n\tFieldSeparators = \" \\t\"\n\tTrimCutset      = FieldSeparators + \"\\n\"\n)\n\ntype ParseError struct {\n\tExpression  string\n\tDescription string\n}\n\nfunc newParseError(exp, desc string) *ParseError {\n\treturn &ParseError{\n\t\tExpression:  exp,\n\t\tDescription: desc,\n\t}\n}\n\nfunc (p *ParseError) Error() string {\n\treturn fmt.Sprintf(\"sched: could not parse %q: %v\", p.Expression, p.Description)\n}\n\nvar fieldSeparatorFunc = func(r rune) bool {\n\treturn strings.ContainsRune(FieldSeparators, r)\n}\n\nfunc Fields(expression string) []string {\n\treturn strings.FieldsFunc(strings.Trim(expression, TrimCutset), fieldSeparatorFunc)\n}\n\nfunc FieldParts(field string) []string {\n\tresult := strings.Split(field, Comma)\n\tif len(result) == 1 && len(result[0]) == 0 {\n\t\treturn []string{}\n\t}\n\treturn result\n}\n\nfunc MustParse(expression string) Schedule {\n\ts, err := Parse(expression)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s\n}\n\nfunc Parse(expression string) (Schedule, error) {\n\t\/\/ParseErrors should be returned from this function and no others.\n\tfieldStrings, err := getNormalizedFields(expression)\n\tif err != nil {\n\t\treturn nil, newParseError(expression, err.Error())\n\t}\n\ts := newSchedule()\n\tfor i, fieldString := range fieldStrings {\n\t\tfi := fieldIndex(i)\n\t\tnexter, err := parseField(fieldString, fi)\n\t\tif err != nil {\n\t\t\treturn nil, newParseError(expression, err.Error())\n\t\t}\n\t\ts.setNexter(nexter, fi)\n\t}\n\treturn s, nil\n}\n\nfunc getNormalizedFields(expression string) ([]string, error) {\n\tfields := Fields(expression)\n\tvar err error = nil\n\tcount, err := validateNumberOfFields(fields)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif count == 1 {\n\t\tfields, err = getNormalizedDirectiveFields(fields[0])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif count == 5 {\n\t\tfields = append([]string{Asterisk}, fields...)\n\t\tcount++\n\t}\n\tif count == 6 {\n\t\tfields = append(fields, Asterisk)\n\t\tcount++\n\t}\n\treturn fields, nil\n}\n\nfunc validateNumberOfFields(fields []string) (int, error) {\n\tcount := len(fields)\n\tif count != 1 && count != 5 && count != 6 && count != 7 {\n\t\treturn 0, fmt.Errorf(\"number of fields must be 1, 5, 6, or 7\")\n\t}\n\treturn count, nil\n}\n\nfunc getNormalizedDirectiveFields(directive string) ([]string, error) {\n\tformat := \"\"\n\tdirective = strings.ToLower(directive)\n\tswitch directive {\n\tcase Yearly:\n\t\tformat = YearlyFormat\n\tcase Annually:\n\t\tformat = AnnuallyFormat\n\tcase Monthly:\n\t\tformat = MonthlyFormat\n\tcase Weekly:\n\t\tformat = WeeklyFormat\n\tcase Daily:\n\t\tformat = DailyFormat\n\tcase Hourly:\n\t\tformat = HourlyFormat\n\tcase Minutely:\n\t\tformat = MinutelyFormat\n\tcase Secondly:\n\t\tformat = SecondlyFormat\n\t}\n\tif format == \"\" {\n\t\treturn nil, fmt.Errorf(\"the directive %q is not recognized\", directive)\n\t}\n\treturn Fields(format), nil\n}\n\nfunc parseField(field string, fi fieldIndex) (nexter interface{}, err error) {\n\tparts := FieldParts(field)\n\tif fi.isDateField() {\n\t\tnexter, err = parseDateFieldNexterParts(parts, fi)\n\t} else {\n\t\tnexter, err = parseFieldNexterParts(parts, fi)\n\t}\n\tif err != nil {\n\t\terr = fmt.Errorf(\"%v field: %v\", fi, err.Error())\n\t\tnexter = nil\n\t}\n\treturn\n}\n\nfunc parseDateFieldNexterParts(parts []string, fi fieldIndex) (dateFieldNexter, error) {\n\treturn nil, nil\n}\n\nfunc parseFieldNexterParts(parts []string, fi fieldIndex) (fieldNexter, error) {\n\treturn nil, nil\n}\n\nfunc parseFieldNexterPart(part string, fi fieldIndex) (fieldNexter, error) {\n\tif len(part) == 0 {\n\t\treturn nil, fmt.Errorf(\"cannot be empty\")\n\t}\n\tslashIndex := strings.Index(part, Slash)\n\tif slashIndex < 0 {\n\t\treturn parseRangeOrConstantNexter(part[:slashIndex], fi)\n\t}\n\tif slashIndex == 0 {\n\t\treturn nil, fmt.Errorf(\"value before step cannot be empty\")\n\t}\n\trn, err := parseRangeNexter(part[:slashIndex], fi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinc, err := parseIncValue(part[slashIndex+1:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newRangeDivNexter(rn, inc), nil\n}\n\nfunc parseRangeOrConstantNexter(part string, fi fieldIndex) (fieldNexter, error) {\n\tpart = convertPossibleAnyToRange(part, fi)\n\tif strings.Contains(part, Hyphen) {\n\t\treturn parseRangeNexter(part, fi)\n\t}\n\treturn parseValueNexter(part, fi)\n}\n\nfunc convertPossibleAnyToRange(part string, fi fieldIndex) string {\n\trangeString := fi.rangeString()\n\tif fi.isDateField() {\n\t\tpart = strings.Replace(part, Question, Asterisk, -1)\n\t}\n\treturn strings.Replace(part, Asterisk, rangeString, -1)\n}\n\n\/\/parseRangeNexter will panic if part does not conatin Hyphen.\nfunc parseRangeNexter(part string, fi fieldIndex) (*rangeNexter, error) {\n\thyphenIndex := strings.Index(part, Hyphen)\n\tmin, err := parseSingleValue(part[:hyphenIndex], fi)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"left side of range: %v\", err.Error())\n\t}\n\tmax, err := parseSingleValue(part[hyphenIndex+1:], fi)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"right side of range: %v\", err.Error())\n\t}\n\tif max <= min {\n\t\treturn nil, fmt.Errorf(\"left side of range must be strictly less than right side\")\n\t}\n\treturn newRangeNexter(min, max), nil\n}\n\nfunc parseValueNexter(part string, fi fieldIndex) (valueNexter, error) {\n\tvalue, err := parseSingleValue(part, fi)\n\tif err != nil {\n\t\treturn valueNexter(invalidValue), err\n\t}\n\treturn valueNexter(value), nil\n}\n\nfunc parseSingleValue(value string, fi fieldIndex) (int, error) {\n\tvalue = convertPossibleMonthDowToInteger(value, fi)\n\tresult, err := strconv.Atoi(value)\n\tif err != nil {\n\t\tif fi.isDateField() {\n\t\t\treturn invalidValue, fmt.Errorf(\"must be a decimal integer or valid string alias\")\n\t\t}\n\t\treturn invalidValue, fmt.Errorf(\"must be a decimal integer\")\n\t}\n\tif !fi.isInRange(result) {\n\t\treturn invalidValue, fmt.Errorf(\"not in range\")\n\t}\n\treturn result, nil\n}\n\nfunc convertPossibleMonthDowToInteger(value string, fi fieldIndex) string {\n\tif fi == month {\n\t\treturn convertMonthToInteger(value)\n\t}\n\tif fi == dow {\n\t\treturn converDowToInteger(value)\n\t}\n\treturn value\n}\n\nfunc convertMonthToInteger(value string) string {\n\tif len(value) < 3 {\n\t\treturn value\n\t}\n\tvalue = strings.ToUpper(value)\n\tfor m := time.January; m <= time.December; m++ {\n\t\tif strings.HasPrefix(strings.ToUpper(fmt.Sprint(m)), value) {\n\t\t\treturn fmt.Sprint(int(m))\n\t\t}\n\t}\n\treturn value\n}\n\nfunc converDowToInteger(value string) string {\n\tif len(value) < 3 {\n\t\treturn value\n\t}\n\tvalue = strings.ToUpper(value)\n\tfor w := time.Sunday; w <= time.Saturday; w++ {\n\t\tif strings.HasPrefix(strings.ToUpper(fmt.Sprint(w)), value) {\n\t\t\treturn fmt.Sprint(int(w))\n\t\t}\n\t}\n\treturn value\n}\n\nfunc parseIncValue(value string) (int, error) {\n\tif len(value) == 0 {\n\t\treturn invalidValue, fmt.Errorf(\"step value cannot be empty\")\n\t}\n\tinc, err := strconv.Atoi(value)\n\tif err != nil || inc <= 0 {\n\t\treturn invalidValue, fmt.Errorf(\"step value must be a positive decimal integer\")\n\t}\n\treturn inc, nil\n}\n<commit_msg>Adds parseFieldNexterParts implementation.<commit_after>package sched\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tAsterisk = \"*\"\n\tQuestion = \"?\"\n\tHyphen   = \"-\"\n\tSlash    = \"\/\"\n\tComma    = \",\"\n\tHash     = \"#\"\n\tLast     = \"L\"\n\tWeekday  = \"W\"\n\n\tFieldSeparators = \" \\t\"\n\tTrimCutset      = FieldSeparators + \"\\n\"\n)\n\ntype ParseError struct {\n\tExpression  string\n\tDescription string\n}\n\nfunc newParseError(exp, desc string) *ParseError {\n\treturn &ParseError{\n\t\tExpression:  exp,\n\t\tDescription: desc,\n\t}\n}\n\nfunc (p *ParseError) Error() string {\n\treturn fmt.Sprintf(\"sched: could not parse %q: %v\", p.Expression, p.Description)\n}\n\nvar fieldSeparatorFunc = func(r rune) bool {\n\treturn strings.ContainsRune(FieldSeparators, r)\n}\n\nfunc Fields(expression string) []string {\n\treturn strings.FieldsFunc(strings.Trim(expression, TrimCutset), fieldSeparatorFunc)\n}\n\nfunc FieldParts(field string) []string {\n\tresult := strings.Split(field, Comma)\n\tif len(result) == 1 && len(result[0]) == 0 {\n\t\treturn []string{}\n\t}\n\treturn result\n}\n\nfunc MustParse(expression string) Schedule {\n\ts, err := Parse(expression)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s\n}\n\nfunc Parse(expression string) (Schedule, error) {\n\t\/\/ParseErrors should be returned from this function and no others.\n\tfieldStrings, err := getNormalizedFields(expression)\n\tif err != nil {\n\t\treturn nil, newParseError(expression, err.Error())\n\t}\n\ts := newSchedule()\n\tfor i, fieldString := range fieldStrings {\n\t\tfi := fieldIndex(i)\n\t\tnexter, err := parseField(fieldString, fi)\n\t\tif err != nil {\n\t\t\treturn nil, newParseError(expression, err.Error())\n\t\t}\n\t\ts.setNexter(nexter, fi)\n\t}\n\treturn s, nil\n}\n\nfunc getNormalizedFields(expression string) ([]string, error) {\n\tfields := Fields(expression)\n\tvar err error = nil\n\tcount, err := validateNumberOfFields(fields)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif count == 1 {\n\t\tfields, err = getNormalizedDirectiveFields(fields[0])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif count == 5 {\n\t\tfields = append([]string{Asterisk}, fields...)\n\t\tcount++\n\t}\n\tif count == 6 {\n\t\tfields = append(fields, Asterisk)\n\t\tcount++\n\t}\n\treturn fields, nil\n}\n\nfunc validateNumberOfFields(fields []string) (int, error) {\n\tcount := len(fields)\n\tif count != 1 && count != 5 && count != 6 && count != 7 {\n\t\treturn 0, fmt.Errorf(\"number of fields must be 1, 5, 6, or 7\")\n\t}\n\treturn count, nil\n}\n\nfunc getNormalizedDirectiveFields(directive string) ([]string, error) {\n\tformat := \"\"\n\tdirective = strings.ToLower(directive)\n\tswitch directive {\n\tcase Yearly:\n\t\tformat = YearlyFormat\n\tcase Annually:\n\t\tformat = AnnuallyFormat\n\tcase Monthly:\n\t\tformat = MonthlyFormat\n\tcase Weekly:\n\t\tformat = WeeklyFormat\n\tcase Daily:\n\t\tformat = DailyFormat\n\tcase Hourly:\n\t\tformat = HourlyFormat\n\tcase Minutely:\n\t\tformat = MinutelyFormat\n\tcase Secondly:\n\t\tformat = SecondlyFormat\n\t}\n\tif format == \"\" {\n\t\treturn nil, fmt.Errorf(\"the directive %q is not recognized\", directive)\n\t}\n\treturn Fields(format), nil\n}\n\nfunc parseField(field string, fi fieldIndex) (nexter interface{}, err error) {\n\tparts := FieldParts(field)\n\tif fi.isDateField() {\n\t\tnexter, err = parseDateFieldNexterParts(parts, fi)\n\t} else {\n\t\tnexter, err = parseFieldNexterParts(parts, fi)\n\t}\n\tif err != nil {\n\t\terr = fmt.Errorf(\"%v field: %v\", fi, err.Error())\n\t\tnexter = nil\n\t}\n\treturn\n}\n\nfunc parseDateFieldNexterParts(parts []string, fi fieldIndex) (dateFieldNexter, error) {\n\treturn nil, nil\n}\n\nfunc parseFieldNexterParts(parts []string, fi fieldIndex) (fieldNexter, error) {\n\tif len(parts) == 1 {\n\t\treturn parseFieldNexterPart(parts[0], fi)\n\t}\n\tresult := multiNexter(make([]fieldNexter, 0, len(parts)))\n\tfor i, part := range parts {\n\t\tnexter, err := parseFieldNexterPart(part, fi)\n\t\tif err != nil {\n\t\t\treturn nil, newPartError(i, err)\n\t\t}\n\t\tresult = append(result, nexter)\n\t}\n\treturn result, nil\n}\n\nfunc newPartError(index int, old error) error {\n\treturn fmt.Errorf(\"part %v: %v\", index+1, old.Error())\n}\n\nfunc parseFieldNexterPart(part string, fi fieldIndex) (fieldNexter, error) {\n\tif len(part) == 0 {\n\t\treturn nil, fmt.Errorf(\"cannot be empty\")\n\t}\n\tslashIndex := strings.Index(part, Slash)\n\tif slashIndex < 0 {\n\t\treturn parseRangeOrConstantNexter(part[:slashIndex], fi)\n\t}\n\tif slashIndex == 0 {\n\t\treturn nil, fmt.Errorf(\"value before step cannot be empty\")\n\t}\n\trn, err := parseRangeNexter(part[:slashIndex], fi)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinc, err := parseIncValue(part[slashIndex+1:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newRangeDivNexter(rn, inc), nil\n}\n\nfunc parseRangeOrConstantNexter(part string, fi fieldIndex) (fieldNexter, error) {\n\tpart = convertPossibleAnyToRange(part, fi)\n\tif strings.Contains(part, Hyphen) {\n\t\treturn parseRangeNexter(part, fi)\n\t}\n\treturn parseValueNexter(part, fi)\n}\n\nfunc convertPossibleAnyToRange(part string, fi fieldIndex) string {\n\trangeString := fi.rangeString()\n\tif fi.isDateField() {\n\t\tpart = strings.Replace(part, Question, Asterisk, -1)\n\t}\n\treturn strings.Replace(part, Asterisk, rangeString, -1)\n}\n\n\/\/parseRangeNexter will panic if part does not conatin Hyphen.\nfunc parseRangeNexter(part string, fi fieldIndex) (*rangeNexter, error) {\n\thyphenIndex := strings.Index(part, Hyphen)\n\tmin, err := parseSingleValue(part[:hyphenIndex], fi)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"left side of range: %v\", err.Error())\n\t}\n\tmax, err := parseSingleValue(part[hyphenIndex+1:], fi)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"right side of range: %v\", err.Error())\n\t}\n\tif min >= max {\n\t\treturn nil, fmt.Errorf(\"left side of range must be strictly less than right side\")\n\t}\n\treturn newRangeNexter(min, max), nil\n}\n\nfunc parseValueNexter(part string, fi fieldIndex) (valueNexter, error) {\n\tvalue, err := parseSingleValue(part, fi)\n\tif err != nil {\n\t\treturn valueNexter(invalidValue), err\n\t}\n\treturn valueNexter(value), nil\n}\n\nfunc parseSingleValue(value string, fi fieldIndex) (int, error) {\n\tvalue = convertPossibleMonthDowToInteger(value, fi)\n\tresult, err := strconv.Atoi(value)\n\tif err != nil {\n\t\tif fi.isDateField() {\n\t\t\treturn invalidValue, fmt.Errorf(\"must be a decimal integer or valid string alias\")\n\t\t}\n\t\treturn invalidValue, fmt.Errorf(\"must be a decimal integer\")\n\t}\n\tif !fi.isInRange(result) {\n\t\treturn invalidValue, fmt.Errorf(\"not in range\")\n\t}\n\treturn result, nil\n}\n\nfunc convertPossibleMonthDowToInteger(value string, fi fieldIndex) string {\n\tif fi == month {\n\t\treturn convertMonthToInteger(value)\n\t}\n\tif fi == dow {\n\t\treturn converDowToInteger(value)\n\t}\n\treturn value\n}\n\nfunc convertMonthToInteger(value string) string {\n\tif len(value) < 3 {\n\t\treturn value\n\t}\n\tvalue = strings.ToUpper(value)\n\tfor m := time.January; m <= time.December; m++ {\n\t\tif strings.HasPrefix(strings.ToUpper(fmt.Sprint(m)), value) {\n\t\t\treturn fmt.Sprint(int(m))\n\t\t}\n\t}\n\treturn value\n}\n\nfunc converDowToInteger(value string) string {\n\tif len(value) < 3 {\n\t\treturn value\n\t}\n\tvalue = strings.ToUpper(value)\n\tfor w := time.Sunday; w <= time.Saturday; w++ {\n\t\tif strings.HasPrefix(strings.ToUpper(fmt.Sprint(w)), value) {\n\t\t\treturn fmt.Sprint(int(w))\n\t\t}\n\t}\n\treturn value\n}\n\nfunc parseIncValue(value string) (int, error) {\n\tif len(value) == 0 {\n\t\treturn invalidValue, fmt.Errorf(\"step value cannot be empty\")\n\t}\n\tinc, err := strconv.Atoi(value)\n\tif err != nil || inc <= 0 {\n\t\treturn invalidValue, fmt.Errorf(\"step value must be a positive decimal integer\")\n\t}\n\treturn inc, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package push\n\nimport (\n\t\"code.cloudfoundry.org\/cli\/integration\/helpers\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gbytes\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"push with --strategy rolling\", func() {\n\tvar (\n\t\tappName  string\n\t\tuserName string\n\t)\n\n\tBeforeEach(func() {\n\t\tappName = helpers.PrefixedRandomName(\"app\")\n\t\tuserName, _ = helpers.GetCredentials()\n\t})\n\n\tWhen(\"the app exists\", func() {\n\t\tBeforeEach(func() {\n\t\t\thelpers.WithHelloWorldApp(func(appDir string) {\n\t\t\t\tEventually(helpers.CustomCF(helpers.CFEnv{WorkingDirectory: appDir},\n\t\t\t\t\tPushCommandName, appName,\n\t\t\t\t)).Should(Exit(0))\n\t\t\t})\n\t\t})\n\n\t\tIt(\"pushes the app and creates a new deployment\", func() {\n\t\t\thelpers.WithHelloWorldApp(func(appDir string) {\n\t\t\t\tsession := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: appDir},\n\t\t\t\t\tPushCommandName, appName, \"--strategy\", \"rolling\",\n\t\t\t\t)\n\n\t\t\t\tEventually(session).Should(Say(`Updating app %s\\.\\.\\.`, appName))\n\t\t\t\tEventually(session).Should(Say(`Pushing app %s to org %s \/ space %s as %s\\.\\.\\.`, appName, organization, space, userName))\n\t\t\t\tEventually(session).Should(Say(`Getting app info\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Packaging files to upload\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Uploading files\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`100.00%`))\n\t\t\t\tEventually(session).Should(Say(`Waiting for API to complete processing files\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Staging app and tracing logs\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Starting deployment for app %s\\.\\.\\.`, appName))\n\t\t\t\tEventually(session).Should(Say(`Waiting for app to deploy\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`name:\\s+%s`, appName))\n\t\t\t\tEventually(session).Should(Say(`requested state:\\s+started`))\n\t\t\t\tEventually(session).Should(Say(`routes:\\s+%s.%s`, appName, helpers.DefaultSharedDomain()))\n\t\t\t\tEventually(session).Should(Say(`type:\\s+web`))\n\t\t\t\tEventually(session).Should(Say(`start command:\\s+%s`, helpers.StaticfileBuildpackStartCommand))\n\t\t\t\tEventually(session).Should(Say(`#0\\s+running`))\n\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t})\n\t\t})\n\t})\n\n\tWhen(\"the app crashes\", func() {\n\t\tBeforeEach(func() {\n\t\t\thelpers.WithHelloWorldApp(func(appDir string) {\n\t\t\t\tEventually(helpers.CustomCF(helpers.CFEnv{WorkingDirectory: appDir},\n\t\t\t\t\tPushCommandName, appName,\n\t\t\t\t)).Should(Exit(0))\n\t\t\t})\n\t\t})\n\n\t\tIt(\"times out\", func() {\n\t\t\thelpers.WithCrashingApp(func(appDir string) {\n\t\t\t\tsession := helpers.CustomCF(helpers.CFEnv{\n\t\t\t\t\tWorkingDirectory: appDir,\n\t\t\t\t\tEnvVars: map[string]string{\"CF_STARTUP_TIMEOUT\": \"0.1\"},\n\t\t\t\t}, PushCommandName, appName, \"--strategy\", \"rolling\")\n\t\t\t\tEventually(session).Should(Say(`Updating app %s\\.\\.\\.`, appName))\n\t\t\t\tEventually(session).Should(Say(`Pushing app %s to org %s \/ space %s as %s\\.\\.\\.`, appName, organization, space, userName))\n\t\t\t\tEventually(session).Should(Say(`Getting app info\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Packaging files to upload\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Uploading files\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`100.00%`))\n\t\t\t\tEventually(session).Should(Say(`Waiting for API to complete processing files\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Staging app and tracing logs\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Starting deployment for app %s\\.\\.\\.`, appName))\n\t\t\t\tEventually(session).Should(Say(`Waiting for app to deploy\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`FAILED`))\n\t\t\t\tEventually(session.Err).Should(Say(`Start app timeout`))\n\t\t\t\tEventually(session.Err).Should(Say(`TIP: Application must be listening on the right port\\. Instead of hard coding the port, use the \\$PORT environment variable\\.`))\n\t\t\t\tEventually(session.Err).Should(Say(`Use 'cf logs %s --recent' for more information`, appName))\n\t\t\t\tEventually(session).Should(Exit(1))\n\t\t\t})\n\t\t})\n\t})\n})\n<commit_msg>Fix go fmt errors<commit_after>package push\n\nimport (\n\t\"code.cloudfoundry.org\/cli\/integration\/helpers\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gbytes\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"push with --strategy rolling\", func() {\n\tvar (\n\t\tappName  string\n\t\tuserName string\n\t)\n\n\tBeforeEach(func() {\n\t\tappName = helpers.PrefixedRandomName(\"app\")\n\t\tuserName, _ = helpers.GetCredentials()\n\t})\n\n\tWhen(\"the app exists\", func() {\n\t\tBeforeEach(func() {\n\t\t\thelpers.WithHelloWorldApp(func(appDir string) {\n\t\t\t\tEventually(helpers.CustomCF(helpers.CFEnv{WorkingDirectory: appDir},\n\t\t\t\t\tPushCommandName, appName,\n\t\t\t\t)).Should(Exit(0))\n\t\t\t})\n\t\t})\n\n\t\tIt(\"pushes the app and creates a new deployment\", func() {\n\t\t\thelpers.WithHelloWorldApp(func(appDir string) {\n\t\t\t\tsession := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: appDir},\n\t\t\t\t\tPushCommandName, appName, \"--strategy\", \"rolling\",\n\t\t\t\t)\n\n\t\t\t\tEventually(session).Should(Say(`Updating app %s\\.\\.\\.`, appName))\n\t\t\t\tEventually(session).Should(Say(`Pushing app %s to org %s \/ space %s as %s\\.\\.\\.`, appName, organization, space, userName))\n\t\t\t\tEventually(session).Should(Say(`Getting app info\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Packaging files to upload\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Uploading files\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`100.00%`))\n\t\t\t\tEventually(session).Should(Say(`Waiting for API to complete processing files\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Staging app and tracing logs\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Starting deployment for app %s\\.\\.\\.`, appName))\n\t\t\t\tEventually(session).Should(Say(`Waiting for app to deploy\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`name:\\s+%s`, appName))\n\t\t\t\tEventually(session).Should(Say(`requested state:\\s+started`))\n\t\t\t\tEventually(session).Should(Say(`routes:\\s+%s.%s`, appName, helpers.DefaultSharedDomain()))\n\t\t\t\tEventually(session).Should(Say(`type:\\s+web`))\n\t\t\t\tEventually(session).Should(Say(`start command:\\s+%s`, helpers.StaticfileBuildpackStartCommand))\n\t\t\t\tEventually(session).Should(Say(`#0\\s+running`))\n\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t})\n\t\t})\n\t})\n\n\tWhen(\"the app crashes\", func() {\n\t\tBeforeEach(func() {\n\t\t\thelpers.WithHelloWorldApp(func(appDir string) {\n\t\t\t\tEventually(helpers.CustomCF(helpers.CFEnv{WorkingDirectory: appDir},\n\t\t\t\t\tPushCommandName, appName,\n\t\t\t\t)).Should(Exit(0))\n\t\t\t})\n\t\t})\n\n\t\tIt(\"times out\", func() {\n\t\t\thelpers.WithCrashingApp(func(appDir string) {\n\t\t\t\tsession := helpers.CustomCF(helpers.CFEnv{\n\t\t\t\t\tWorkingDirectory: appDir,\n\t\t\t\t\tEnvVars:          map[string]string{\"CF_STARTUP_TIMEOUT\": \"0.1\"},\n\t\t\t\t}, PushCommandName, appName, \"--strategy\", \"rolling\")\n\t\t\t\tEventually(session).Should(Say(`Updating app %s\\.\\.\\.`, appName))\n\t\t\t\tEventually(session).Should(Say(`Pushing app %s to org %s \/ space %s as %s\\.\\.\\.`, appName, organization, space, userName))\n\t\t\t\tEventually(session).Should(Say(`Getting app info\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Packaging files to upload\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Uploading files\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`100.00%`))\n\t\t\t\tEventually(session).Should(Say(`Waiting for API to complete processing files\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Staging app and tracing logs\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`Starting deployment for app %s\\.\\.\\.`, appName))\n\t\t\t\tEventually(session).Should(Say(`Waiting for app to deploy\\.\\.\\.`))\n\t\t\t\tEventually(session).Should(Say(`FAILED`))\n\t\t\t\tEventually(session.Err).Should(Say(`Start app timeout`))\n\t\t\t\tEventually(session.Err).Should(Say(`TIP: Application must be listening on the right port\\. Instead of hard coding the port, use the \\$PORT environment variable\\.`))\n\t\t\t\tEventually(session.Err).Should(Say(`Use 'cf logs %s --recent' for more information`, appName))\n\t\t\t\tEventually(session).Should(Exit(1))\n\t\t\t})\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2020 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage opengl\n\nimport (\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/driver\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/shaderir\"\n)\n\ntype Shader struct {\n\tid       driver.ShaderID\n\tgraphics *Graphics\n\n\tir *shaderir.Program\n\tp  program\n}\n\nfunc NewShader(id driver.ShaderID, graphics *Graphics, program *shaderir.Program) (*Shader, error) {\n\ts := &Shader{\n\t\tid:       id,\n\t\tgraphics: graphics,\n\t\tir:       program,\n\t}\n\tif err := s.compile(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn s, nil\n}\n\nfunc (s *Shader) ID() driver.ShaderID {\n\treturn s.id\n}\n\nfunc (s *Shader) Dispose() {\n\ts.graphics.context.deleteProgram(s.p)\n\ts.graphics.removeShader(s)\n}\n\nfunc (s *Shader) compile() error {\n\tvssrc, fssrc := s.ir.Glsl()\n\tprintln(vssrc, fssrc)\n\n\tvs, err := s.graphics.context.newShader(vertexShader, vssrc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer s.graphics.context.deleteShader(vs)\n\n\tfs, err := s.graphics.context.newShader(fragmentShader, fssrc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer s.graphics.context.deleteShader(vs)\n\n\tp, err := s.graphics.context.newProgram([]shader{vs, fs}, theArrayBufferLayout.names())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.p = p\n\treturn nil\n}\n<commit_msg>graphicsdriver\/opengl: Bug fix: deleted a wrong shader program<commit_after>\/\/ Copyright 2020 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage opengl\n\nimport (\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/driver\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/shaderir\"\n)\n\ntype Shader struct {\n\tid       driver.ShaderID\n\tgraphics *Graphics\n\n\tir *shaderir.Program\n\tp  program\n}\n\nfunc NewShader(id driver.ShaderID, graphics *Graphics, program *shaderir.Program) (*Shader, error) {\n\ts := &Shader{\n\t\tid:       id,\n\t\tgraphics: graphics,\n\t\tir:       program,\n\t}\n\tif err := s.compile(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn s, nil\n}\n\nfunc (s *Shader) ID() driver.ShaderID {\n\treturn s.id\n}\n\nfunc (s *Shader) Dispose() {\n\ts.graphics.context.deleteProgram(s.p)\n\ts.graphics.removeShader(s)\n}\n\nfunc (s *Shader) compile() error {\n\tvssrc, fssrc := s.ir.Glsl()\n\tprintln(vssrc, fssrc)\n\n\tvs, err := s.graphics.context.newShader(vertexShader, vssrc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer s.graphics.context.deleteShader(vs)\n\n\tfs, err := s.graphics.context.newShader(fragmentShader, fssrc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer s.graphics.context.deleteShader(fs)\n\n\tp, err := s.graphics.context.newProgram([]shader{vs, fs}, theArrayBufferLayout.names())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.p = p\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport(\n  \"fmt\"\n  \"os\"\n  \"io\/ioutil\"\n  \"path\/filepath\"\n  \"os\/exec\"\n  \"strings\"\n)\n\nconst(\n  LUNCHY_VERSION = \"0.1.0\"\n)\n\nfunc printUsage() {\n  fmt.Printf(\"Lunchy %s, the friendly launchctl wrapper\\n\", LUNCHY_VERSION)\n  fmt.Println(\"Usage: lunchy [start|stop|restart|list|status|install|show|edit] [options]\")\n}\n\nfunc findPlists(path string) []string {\n  result := []string{}\n  files, err := ioutil.ReadDir(path)\n\n  if err != nil {\n    return result\n  }\n\n  for _, file := range files {\n    if !file.IsDir() {\n      if (filepath.Ext(file.Name())) == \".plist\" {\n        name := strings.Replace(file.Name(), \".plist\", \"\", -1)\n        result = append(result, name)\n      }\n    }\n  }\n\n  return result\n}\n\nfunc getPlists() []string {\n  path := fmt.Sprintf(\"%s\/Library\/LaunchAgents\", os.Getenv(\"HOME\")) \n  files := findPlists(path)\n\n  return files\n}\n\nfunc sliceIncludes(slice []string, match string) bool {\n  for _, val := range slice {\n    if val == match {\n      return true\n    }\n  }\n\n  return false\n}\n\nfunc printList() {\n  for _, file := range getPlists() {\n    fmt.Println(file)\n  }\n}\n\nfunc printStatus(args []string) {\n  out, err := exec.Command(\"launchctl\", \"list\").Output()\n\n  if err != nil {\n    fmt.Println(\"Failed to execute\", err)\n    os.Exit(1)\n  }\n\n  installed := getPlists()\n  lines := strings.Split(strings.TrimSpace(string(out)), \"\\n\")\n\n  for _, line := range lines {\n    chunks := strings.Split(line, \"\\t\")\n\n    if sliceIncludes(installed, chunks[2]) {\n      fmt.Println(line)\n    }\n  }\n}\n\nfunc main() {\n  args := os.Args\n\n  if (len(args) == 1) {\n    printUsage()\n    os.Exit(1)\n  }\n\n  switch args[1] {\n  default:\n    printUsage()\n    os.Exit(1)\n  case \"list\":\n    printList()\n    return\n  case \"status\":\n    printStatus(args)\n    return\n  }\n}<commit_msg>Add pattern matching in status<commit_after>package main\n\nimport(\n  \"fmt\"\n  \"os\"\n  \"io\/ioutil\"\n  \"path\/filepath\"\n  \"os\/exec\"\n  \"strings\"\n)\n\nconst(\n  LUNCHY_VERSION = \"0.1.0\"\n)\n\nfunc printUsage() {\n  fmt.Printf(\"Lunchy %s, the friendly launchctl wrapper\\n\", LUNCHY_VERSION)\n  fmt.Println(\"Usage: lunchy [start|stop|restart|list|status|install|show|edit] [options]\")\n}\n\nfunc findPlists(path string) []string {\n  result := []string{}\n  files, err := ioutil.ReadDir(path)\n\n  if err != nil {\n    return result\n  }\n\n  for _, file := range files {\n    if !file.IsDir() {\n      if (filepath.Ext(file.Name())) == \".plist\" {\n        name := strings.Replace(file.Name(), \".plist\", \"\", -1)\n        result = append(result, name)\n      }\n    }\n  }\n\n  return result\n}\n\nfunc getPlists() []string {\n  path := fmt.Sprintf(\"%s\/Library\/LaunchAgents\", os.Getenv(\"HOME\")) \n  files := findPlists(path)\n\n  return files\n}\n\nfunc sliceIncludes(slice []string, match string) bool {\n  for _, val := range slice {\n    if val == match {\n      return true\n    }\n  }\n\n  return false\n}\n\nfunc printList() {\n  for _, file := range getPlists() {\n    fmt.Println(file)\n  }\n}\n\nfunc printStatus(args []string) {\n  out, err := exec.Command(\"launchctl\", \"list\").Output()\n\n  if err != nil {\n    fmt.Println(\"Failed to execute\", err)\n    os.Exit(1)\n  }\n\n  pattern := \"\"\n\n  if len(args) == 3 {\n    pattern = args[2]\n  }\n\n  installed := getPlists()\n  lines := strings.Split(strings.TrimSpace(string(out)), \"\\n\")\n  \n  for _, line := range lines {\n    chunks := strings.Split(line, \"\\t\")\n\n    if len(pattern) > 0 {\n      if strings.Index(chunks[2], pattern) != -1 {\n        if sliceIncludes(installed, chunks[2]) {\n          fmt.Println(line)\n        }\n      }\n    } else {\n      if sliceIncludes(installed, chunks[2]) {\n        fmt.Println(line)\n      }\n    }\n  }\n}\n\nfunc main() {\n  args := os.Args\n\n  if (len(args) == 1) {\n    printUsage()\n    os.Exit(1)\n  }\n\n  switch args[1] {\n  default:\n    printUsage()\n    os.Exit(1)\n  case \"list\":\n    printList()\n    return\n  case \"status\":\n    printStatus(args)\n    return\n  }\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nconst (\n\tLUNCHY_VERSION = \"0.1.5\"\n)\n\nfunc fileExists(path string) bool {\n\t_, err := os.Stat(path)\n\treturn err == nil\n}\n\nfunc fileCopy(src string, dst string) error {\n\ts, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer s.Close()\n\n\td, err := os.Create(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := io.Copy(d, s); err != nil {\n\t\td.Close()\n\t\treturn err\n\t}\n\n\treturn d.Close()\n}\n\nfunc findPlists(path string) []string {\n\tresult := []string{}\n\tfiles, err := ioutil.ReadDir(path)\n\n\tif err != nil {\n\t\treturn result\n\t}\n\n\tfor _, file := range files {\n\t\tif !file.IsDir() {\n\t\t\tif (filepath.Ext(file.Name())) == \".plist\" {\n\t\t\t\tname := strings.Replace(file.Name(), \".plist\", \"\", -1)\n\t\t\t\tresult = append(result, name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc getPlists() []string {\n\tpath := fmt.Sprintf(\"%s\/Library\/LaunchAgents\", os.Getenv(\"HOME\"))\n\tfiles := findPlists(path)\n\n\treturn files\n}\n\nfunc getPlist(name string) string {\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\treturn plist\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nfunc sliceIncludes(slice []string, match string) bool {\n\tfor _, val := range slice {\n\t\tif val == match {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc printUsage() {\n\tfmt.Printf(\"Lunchy %s, the friendly launchctl wrapper\\n\", LUNCHY_VERSION)\n\tfmt.Println(\"Usage: lunchy [start|stop|restart|list|status|install|show|edit|remove|scan] [options]\")\n}\n\nfunc printList() {\n\tfor _, file := range getPlists() {\n\t\tfmt.Println(file)\n\t}\n}\n\nfunc printStatus(args []string) {\n\tout, err := exec.Command(\"launchctl\", \"list\").Output()\n\n\tif err != nil {\n\t\tfatal(\"failed to get process list\")\n\t}\n\n\tpattern := \"\"\n\n\tif len(args) == 3 {\n\t\tpattern = args[2]\n\t}\n\n\tinstalled := getPlists()\n\tlines := strings.Split(strings.TrimSpace(string(out)), \"\\n\")\n\n\tfor _, line := range lines {\n\t\tchunks := strings.Split(line, \"\\t\")\n\t\tclean_line := strings.Replace(line, \"\\t\", \" \", -1)\n\n\t\tif len(pattern) > 0 {\n\t\t\tif strings.Index(chunks[2], pattern) != -1 {\n\t\t\t\tif sliceIncludes(installed, chunks[2]) {\n\t\t\t\t\tfmt.Println(clean_line)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif sliceIncludes(installed, chunks[2]) {\n\t\t\t\tfmt.Println(clean_line)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc exitWithInvalidArgs(args []string, msg string) {\n\tif len(args) < 3 {\n\t\tfmt.Println(msg)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc startDaemons(args []string) {\n\texitWithInvalidArgs(args, \"name required\")\n\n\tname := args[2]\n\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\tstartDaemon(plist)\n\t\t}\n\t}\n}\n\nfunc startDaemon(name string) {\n\tpath := fmt.Sprintf(\"%s\/Library\/LaunchAgents\/%s.plist\", os.Getenv(\"HOME\"), name)\n\t_, err := exec.Command(\"launchctl\", \"load\", path).Output()\n\n\tif err != nil {\n\t\tfmt.Println(\"failed to start\", name)\n\t\treturn\n\t}\n\n\tfmt.Println(\"started\", name)\n}\n\nfunc stopDaemons(args []string) {\n\texitWithInvalidArgs(args, \"name required\")\n\n\tname := args[2]\n\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\tstopDaemon(plist)\n\t\t}\n\t}\n}\n\nfunc stopDaemon(name string) {\n\tpath := fmt.Sprintf(\"%s\/Library\/LaunchAgents\/%s.plist\", os.Getenv(\"HOME\"), name)\n\t_, err := exec.Command(\"launchctl\", \"unload\", path).Output()\n\n\tif err != nil {\n\t\tfmt.Println(\"failed to stop\", name)\n\t\treturn\n\t}\n\n\tfmt.Println(\"stopped\", name)\n}\n\nfunc restartDaemons(args []string) {\n\texitWithInvalidArgs(args, \"name required\")\n\n\tname := args[2]\n\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\tstopDaemon(plist)\n\t\t\tstartDaemon(plist)\n\t\t}\n\t}\n}\n\nfunc showPlist(args []string) {\n\texitWithInvalidArgs(args, \"name required\")\n\n\tname := args[2]\n\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\tprintPlistContent(plist)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc printPlistContent(name string) {\n\tpath := fmt.Sprintf(\"%s\/Library\/LaunchAgents\/%s.plist\", os.Getenv(\"HOME\"), name)\n\tcontents, err := ioutil.ReadFile(path)\n\n\tif err != nil {\n\t\tfatal(\"unable to read plist\")\n\t}\n\n\tfmt.Printf(string(contents))\n}\n\nfunc editPlist(args []string) {\n\texitWithInvalidArgs(args, \"name required\")\n\n\tname := args[2]\n\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\teditPlistContent(plist)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc editPlistContent(name string) {\n\tpath := fmt.Sprintf(\"%s\/Library\/LaunchAgents\/%s.plist\", os.Getenv(\"HOME\"), name)\n\teditor := os.Getenv(\"EDITOR\")\n\n\tif len(editor) == 0 {\n\t\tfatal(\"EDITOR environment variable is not set\")\n\t}\n\n\tcmd := exec.Command(editor, path)\n\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\n\tcmd.Start()\n\tcmd.Wait()\n}\n\nfunc installPlist(args []string) {\n\texitWithInvalidArgs(args, \"path required\")\n\n\tpath := args[2]\n\n\tif !fileExists(path) {\n\t\tfatal(\"source file does not exist\")\n\t}\n\n\tinfo, _ := os.Stat(path)\n\tbase_path := fmt.Sprintf(\"%s\/%s\", os.Getenv(\"HOME\"), \"Library\/LaunchAgents\")\n\tnew_path := fmt.Sprintf(\"%s\/%s\", base_path, info.Name())\n\n\tif fileExists(new_path) && os.Remove(new_path) != nil {\n\t\tfatal(\"unable to delete existing plist\")\n\t}\n\n\tif fileCopy(path, new_path) != nil {\n\t\tfatal(\"failed to copy file\")\n\t}\n\n\tfmt.Println(path, \"installed to\", base_path)\n}\n\nfunc removePlist(args []string) {\n\texitWithInvalidArgs(args, \"name required\")\n\n\tname := args[2]\n\tbase_path := fmt.Sprintf(\"%s\/%s\", os.Getenv(\"HOME\"), \"Library\/LaunchAgents\")\n\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\tpath := fmt.Sprintf(\"%s\/%s.plist\", base_path, plist)\n\n\t\t\tif os.Remove(path) == nil {\n\t\t\t\tfmt.Println(\"removed\", path)\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"failed to remove\", path)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc scanPath(args []string) {\n\tpath := fmt.Sprintf(\"%s\/%s\", os.Getenv(\"HOME\"), \"Library\/LaunchAgents\")\n\n\tif len(args) >= 3 {\n\t\tpath = args[2]\n\t}\n\n\tfor _, f := range findPlists(path) {\n\t\tfmt.Println(f)\n\t}\n}\n\nfunc fatal(message string) {\n\tfmt.Println(message)\n\tos.Exit(1)\n}\n\nfunc main() {\n\targs := os.Args\n\n\tif len(args) == 1 {\n\t\tprintUsage()\n\t\tos.Exit(1)\n\t}\n\n\tswitch args[1] {\n\tdefault:\n\t\tprintUsage()\n\t\tos.Exit(1)\n\tcase \"help\":\n\t\tprintUsage()\n\t\treturn\n\tcase \"list\", \"ls\":\n\t\tprintList()\n\t\treturn\n\tcase \"status\", \"ps\":\n\t\tprintStatus(args)\n\t\treturn\n\tcase \"start\":\n\t\tstartDaemons(args)\n\t\treturn\n\tcase \"stop\":\n\t\tstopDaemons(args)\n\t\treturn\n\tcase \"restart\":\n\t\trestartDaemons(args)\n\t\treturn\n\tcase \"show\":\n\t\tshowPlist(args)\n\t\treturn\n\tcase \"edit\":\n\t\teditPlist(args)\n\t\treturn\n\tcase \"install\", \"add\":\n\t\tinstallPlist(args)\n\t\treturn\n\tcase \"remove\", \"rm\":\n\t\tremovePlist(args)\n\t\treturn\n\tcase \"scan\":\n\t\tscanPath(args)\n\t\treturn\n\t}\n}\n<commit_msg>Allow scanning all homebrew-based plists with 'scan homebrew' command<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n)\n\nconst (\n\tLUNCHY_VERSION = \"0.1.5\"\n)\n\nfunc fileExists(path string) bool {\n\t_, err := os.Stat(path)\n\treturn err == nil\n}\n\nfunc fileCopy(src string, dst string) error {\n\ts, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer s.Close()\n\n\td, err := os.Create(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := io.Copy(d, s); err != nil {\n\t\td.Close()\n\t\treturn err\n\t}\n\n\treturn d.Close()\n}\n\nfunc findPlists(path string) []string {\n\toutput, err := exec.Command(\"find\", path, \"-name\", \"homebrew.*.plist\", \"-type\", \"f\").Output()\n\tif err != nil {\n\t\treturn []string{}\n\t}\n\n\treturn strings.Split(strings.TrimSpace(string(output)), \"\\n\")\n}\n\nfunc getPlists() []string {\n\tpath := fmt.Sprintf(\"%s\/Library\/LaunchAgents\", os.Getenv(\"HOME\"))\n\tfiles := findPlists(path)\n\n\treturn files\n}\n\nfunc getPlist(name string) string {\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\treturn plist\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nfunc sliceIncludes(slice []string, match string) bool {\n\tfor _, val := range slice {\n\t\tif val == match {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc printUsage() {\n\tfmt.Printf(\"Lunchy %s, the friendly launchctl wrapper\\n\", LUNCHY_VERSION)\n\tfmt.Println(\"Usage: lunchy [start|stop|restart|list|status|install|show|edit|remove|scan] [options]\")\n}\n\nfunc printList() {\n\tfor _, file := range getPlists() {\n\t\tfmt.Println(file)\n\t}\n}\n\nfunc printStatus(args []string) {\n\tout, err := exec.Command(\"launchctl\", \"list\").Output()\n\n\tif err != nil {\n\t\tfatal(\"failed to get process list\")\n\t}\n\n\tpattern := \"\"\n\n\tif len(args) == 3 {\n\t\tpattern = args[2]\n\t}\n\n\tinstalled := getPlists()\n\tlines := strings.Split(strings.TrimSpace(string(out)), \"\\n\")\n\n\tfor _, line := range lines {\n\t\tchunks := strings.Split(line, \"\\t\")\n\t\tclean_line := strings.Replace(line, \"\\t\", \" \", -1)\n\n\t\tif len(pattern) > 0 {\n\t\t\tif strings.Index(chunks[2], pattern) != -1 {\n\t\t\t\tif sliceIncludes(installed, chunks[2]) {\n\t\t\t\t\tfmt.Println(clean_line)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif sliceIncludes(installed, chunks[2]) {\n\t\t\t\tfmt.Println(clean_line)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc exitWithInvalidArgs(args []string, msg string) {\n\tif len(args) < 3 {\n\t\tfmt.Println(msg)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc startDaemons(args []string) {\n\texitWithInvalidArgs(args, \"name required\")\n\n\tname := args[2]\n\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\tstartDaemon(plist)\n\t\t}\n\t}\n}\n\nfunc startDaemon(name string) {\n\tpath := fmt.Sprintf(\"%s\/Library\/LaunchAgents\/%s.plist\", os.Getenv(\"HOME\"), name)\n\t_, err := exec.Command(\"launchctl\", \"load\", path).Output()\n\n\tif err != nil {\n\t\tfmt.Println(\"failed to start\", name)\n\t\treturn\n\t}\n\n\tfmt.Println(\"started\", name)\n}\n\nfunc stopDaemons(args []string) {\n\texitWithInvalidArgs(args, \"name required\")\n\n\tname := args[2]\n\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\tstopDaemon(plist)\n\t\t}\n\t}\n}\n\nfunc stopDaemon(name string) {\n\tpath := fmt.Sprintf(\"%s\/Library\/LaunchAgents\/%s.plist\", os.Getenv(\"HOME\"), name)\n\t_, err := exec.Command(\"launchctl\", \"unload\", path).Output()\n\n\tif err != nil {\n\t\tfmt.Println(\"failed to stop\", name)\n\t\treturn\n\t}\n\n\tfmt.Println(\"stopped\", name)\n}\n\nfunc restartDaemons(args []string) {\n\texitWithInvalidArgs(args, \"name required\")\n\n\tname := args[2]\n\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\tstopDaemon(plist)\n\t\t\tstartDaemon(plist)\n\t\t}\n\t}\n}\n\nfunc showPlist(args []string) {\n\texitWithInvalidArgs(args, \"name required\")\n\n\tname := args[2]\n\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\tprintPlistContent(plist)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc printPlistContent(name string) {\n\tpath := fmt.Sprintf(\"%s\/Library\/LaunchAgents\/%s.plist\", os.Getenv(\"HOME\"), name)\n\tcontents, err := ioutil.ReadFile(path)\n\n\tif err != nil {\n\t\tfatal(\"unable to read plist\")\n\t}\n\n\tfmt.Printf(string(contents))\n}\n\nfunc editPlist(args []string) {\n\texitWithInvalidArgs(args, \"name required\")\n\n\tname := args[2]\n\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\teditPlistContent(plist)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc editPlistContent(name string) {\n\tpath := fmt.Sprintf(\"%s\/Library\/LaunchAgents\/%s.plist\", os.Getenv(\"HOME\"), name)\n\teditor := os.Getenv(\"EDITOR\")\n\n\tif len(editor) == 0 {\n\t\tfatal(\"EDITOR environment variable is not set\")\n\t}\n\n\tcmd := exec.Command(editor, path)\n\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\n\tcmd.Start()\n\tcmd.Wait()\n}\n\nfunc installPlist(args []string) {\n\texitWithInvalidArgs(args, \"path required\")\n\n\tpath := args[2]\n\n\tif !fileExists(path) {\n\t\tfatal(\"source file does not exist\")\n\t}\n\n\tinfo, _ := os.Stat(path)\n\tbase_path := fmt.Sprintf(\"%s\/%s\", os.Getenv(\"HOME\"), \"Library\/LaunchAgents\")\n\tnew_path := fmt.Sprintf(\"%s\/%s\", base_path, info.Name())\n\n\tif fileExists(new_path) && os.Remove(new_path) != nil {\n\t\tfatal(\"unable to delete existing plist\")\n\t}\n\n\tif fileCopy(path, new_path) != nil {\n\t\tfatal(\"failed to copy file\")\n\t}\n\n\tfmt.Println(path, \"installed to\", base_path)\n}\n\nfunc removePlist(args []string) {\n\texitWithInvalidArgs(args, \"name required\")\n\n\tname := args[2]\n\tbase_path := fmt.Sprintf(\"%s\/%s\", os.Getenv(\"HOME\"), \"Library\/LaunchAgents\")\n\n\tfor _, plist := range getPlists() {\n\t\tif strings.Index(plist, name) != -1 {\n\t\t\tpath := fmt.Sprintf(\"%s\/%s.plist\", base_path, plist)\n\n\t\t\tif os.Remove(path) == nil {\n\t\t\t\tfmt.Println(\"removed\", path)\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"failed to remove\", path)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc scanPath(args []string) {\n\tpath := fmt.Sprintf(\"%s\/%s\", os.Getenv(\"HOME\"), \"Library\/LaunchAgents\")\n\n\tif len(args) >= 3 {\n\t\tpath = args[2]\n\t}\n\n\t\/\/ This is a handy override to find all homebrew-based lists\n\tif path == \"homebrew\" {\n\t\tpath = \"\/usr\/local\/Cellar\"\n\t}\n\n\tfor _, f := range findPlists(path) {\n\t\tfmt.Println(f)\n\t}\n}\n\nfunc fatal(message string) {\n\tfmt.Println(message)\n\tos.Exit(1)\n}\n\nfunc main() {\n\targs := os.Args\n\n\tif len(args) == 1 {\n\t\tprintUsage()\n\t\tos.Exit(1)\n\t}\n\n\tswitch args[1] {\n\tdefault:\n\t\tprintUsage()\n\t\tos.Exit(1)\n\tcase \"help\":\n\t\tprintUsage()\n\t\treturn\n\tcase \"list\", \"ls\":\n\t\tprintList()\n\t\treturn\n\tcase \"status\", \"ps\":\n\t\tprintStatus(args)\n\t\treturn\n\tcase \"start\":\n\t\tstartDaemons(args)\n\t\treturn\n\tcase \"stop\":\n\t\tstopDaemons(args)\n\t\treturn\n\tcase \"restart\":\n\t\trestartDaemons(args)\n\t\treturn\n\tcase \"show\":\n\t\tshowPlist(args)\n\t\treturn\n\tcase \"edit\":\n\t\teditPlist(args)\n\t\treturn\n\tcase \"install\", \"add\":\n\t\tinstallPlist(args)\n\t\treturn\n\tcase \"remove\", \"rm\":\n\t\tremovePlist(args)\n\t\treturn\n\tcase \"scan\":\n\t\tscanPath(args)\n\t\treturn\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package hu\n\nfunc (interpreter *Interpreter) quote(object Object, environment *Environment) Object {\n\treturn cons(quote_symbol, object)\n}\n\nfunc (interpreter *Interpreter) unquote(object Object, environment *Environment) Object {\n\t\/\/ TODO check that car is quote\n\treturn cdr(object)\n}\n\nfunc (interpreter *Interpreter) evalList(list Object, environment *Environment) Object {\n\teval := func(object Object) Object { return interpreter.evaluate(object, environment) }\n\treturn list_from(list, eval)\n}\n\nfunc (interpreter *Interpreter) define(object Object, environment *Environment) Object {\n\tvar variable, value Object\n\n\tif is_symbol(car(object)) {\n\t\tvariable = car(object)\n\t\tvalue = car(cdr(object))\n\t} else {\n\t\tvariable = car(car(object))\n\t\tparameters := cdr(car(object))\n\t\tbody := cdr(object)\n\t\tvalue = interpreter.lambda(cons(parameters, body), environment)\n\t}\n\n\tenvironment.Define(variable, value)\n\treturn nil\n}\n\nfunc (interpreter *Interpreter) set(object Object, environment *Environment) Object {\n\tvariable := car(object)\n\tvalue := car(cdr(object))\n\tvalue = interpreter.evaluate(value, environment)\n\tenvironment.Set(variable, value)\n\treturn nil\n}\n\nfunc (interpreter *Interpreter) lambda(object Object, outer *Environment) Object {\n\tparameters := car(object)\n\tfunction := cdr(object)\n\tf := func(interpreter *Interpreter, object Object, environment *Environment) Object {\n\t\toperands := interpreter.evalList(object, environment)\n\t\tenvironment = outer.Extend(parameters, operands)\n\t\tfunction := interpreter.evalList(function, environment)\n\t\treturn interpreter.begin(function, environment)\n\t}\n\treturn &PrimitiveFunctionObject{f}\n}\n\nfunc (interpreter *Interpreter) begin(object Object, environment *Environment) Object {\n\tvar result Object\n\tfor expressions := object; expressions != nil; expressions = cdr(expressions) {\n\t\texpression := car(expressions)\n\t\tresult = interpreter.evaluate(expression, environment)\n\t}\n\treturn result\n}\n\nfunc (interpreter *Interpreter) and(object Object, environment *Environment) Object {\n\tresult := TRUE\n\ttests := object\n\tfor exp := tests; exp != nil; exp = cdr(exp) {\n\t\tfirst_exp := car(exp)\n\t\tresult = interpreter.evaluate(first_exp, environment)\n\t\tif is_false(result) {\n\t\t\treturn result\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (interpreter *Interpreter) or(object Object, environment *Environment) Object {\n\tresult := FALSE\n\ttests := object\n\tfor exp := tests; exp != nil; exp = cdr(exp) {\n\t\tfirst_exp := car(exp)\n\t\tresult = interpreter.evaluate(first_exp, environment)\n\t\tif is_true(result) {\n\t\t\treturn result\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (interpreter *Interpreter) ifPrimitive(object Object, environment *Environment) Object {\n\tif_predicate := car(object)\n\tif is_true(interpreter.evaluate(if_predicate, environment)) {\n\t\tif_consequent := car(cdr(object))\n\t\tobject = if_consequent\n\t} else {\n\t\tvar if_alternative Object\n\t\tif is_the_empty_list(cdr(cdr(object))) {\n\t\t\tif_alternative = FALSE\n\t\t} else {\n\t\t\tif_alternative = car(cdr(cdr(object)))\n\t\t}\n\t\tobject = if_alternative\n\t}\n\treturn interpreter.evaluate(object, environment)\n}\n\nfunc (interpreter *Interpreter) apply(object Object, environment *Environment) Object {\n\toperator := car(object)\n\toperands := cdr(object)\n\treturn &ExpressionObject{operator, operands}\n}\n\nfunc (interpreter *Interpreter) evalPrimitive(object Object, environment *Environment) Object {\n\texpression := car(object)\n\tenvironment = car(cdr(object)).(*Environment)\n\treturn interpreter.evaluate(expression, environment)\n}\n\nfunc (interpreter *Interpreter) let(object Object, environment *Environment) Object {\n\tbindings := car(object)\n\tbody := cdr(object)\n\n\tbinding_parameter := func(binding Object) Object { return car(binding) }\n\tparameters := list_from(bindings, binding_parameter)\n\n\tbinding_arguments := func(binding Object) Object { return car(cdr(binding)) }\n\targuments := list_from(bindings, binding_arguments)\n\n\toperator := interpreter.lambda(cons(parameters, body), environment)\n\toperands := arguments\n\n\treturn &ExpressionObject{operator, operands}\n}\n<commit_msg>Evaluate value expression before binding it. <commit_after>package hu\n\nfunc (interpreter *Interpreter) quote(object Object, environment *Environment) Object {\n\treturn cons(quote_symbol, object)\n}\n\nfunc (interpreter *Interpreter) unquote(object Object, environment *Environment) Object {\n\t\/\/ TODO check that car is quote\n\treturn cdr(object)\n}\n\nfunc (interpreter *Interpreter) evalList(list Object, environment *Environment) Object {\n\teval := func(object Object) Object { return interpreter.evaluate(object, environment) }\n\treturn list_from(list, eval)\n}\n\nfunc (interpreter *Interpreter) define(object Object, environment *Environment) Object {\n\tvar variable, value Object\n\n\tif is_symbol(car(object)) {\n\t\tvariable = car(object)\n\t\tvalue = interpreter.evaluate(car(cdr(object)), environment)\n\t} else {\n\t\tvariable = car(car(object))\n\t\tparameters := cdr(car(object))\n\t\tbody := cdr(object)\n\t\tvalue = interpreter.lambda(cons(parameters, body), environment)\n\t}\n\n\tenvironment.Define(variable, value)\n\treturn nil\n}\n\nfunc (interpreter *Interpreter) set(object Object, environment *Environment) Object {\n\tvariable := car(object)\n\tvalue := car(cdr(object))\n\tvalue = interpreter.evaluate(value, environment)\n\tenvironment.Set(variable, value)\n\treturn nil\n}\n\nfunc (interpreter *Interpreter) lambda(object Object, outer *Environment) Object {\n\tparameters := car(object)\n\tfunction := cdr(object)\n\tf := func(interpreter *Interpreter, object Object, environment *Environment) Object {\n\t\toperands := interpreter.evalList(object, environment)\n\t\tenvironment = outer.Extend(parameters, operands)\n\t\tfunction := interpreter.evalList(function, environment)\n\t\treturn interpreter.begin(function, environment)\n\t}\n\treturn &PrimitiveFunctionObject{f}\n}\n\nfunc (interpreter *Interpreter) begin(object Object, environment *Environment) Object {\n\tvar result Object\n\tfor expressions := object; expressions != nil; expressions = cdr(expressions) {\n\t\texpression := car(expressions)\n\t\tresult = interpreter.evaluate(expression, environment)\n\t}\n\treturn result\n}\n\nfunc (interpreter *Interpreter) and(object Object, environment *Environment) Object {\n\tresult := TRUE\n\ttests := object\n\tfor exp := tests; exp != nil; exp = cdr(exp) {\n\t\tfirst_exp := car(exp)\n\t\tresult = interpreter.evaluate(first_exp, environment)\n\t\tif is_false(result) {\n\t\t\treturn result\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (interpreter *Interpreter) or(object Object, environment *Environment) Object {\n\tresult := FALSE\n\ttests := object\n\tfor exp := tests; exp != nil; exp = cdr(exp) {\n\t\tfirst_exp := car(exp)\n\t\tresult = interpreter.evaluate(first_exp, environment)\n\t\tif is_true(result) {\n\t\t\treturn result\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (interpreter *Interpreter) ifPrimitive(object Object, environment *Environment) Object {\n\tif_predicate := car(object)\n\tif is_true(interpreter.evaluate(if_predicate, environment)) {\n\t\tif_consequent := car(cdr(object))\n\t\tobject = if_consequent\n\t} else {\n\t\tvar if_alternative Object\n\t\tif is_the_empty_list(cdr(cdr(object))) {\n\t\t\tif_alternative = FALSE\n\t\t} else {\n\t\t\tif_alternative = car(cdr(cdr(object)))\n\t\t}\n\t\tobject = if_alternative\n\t}\n\treturn interpreter.evaluate(object, environment)\n}\n\nfunc (interpreter *Interpreter) apply(object Object, environment *Environment) Object {\n\toperator := car(object)\n\toperands := cdr(object)\n\treturn &ExpressionObject{operator, operands}\n}\n\nfunc (interpreter *Interpreter) evalPrimitive(object Object, environment *Environment) Object {\n\texpression := car(object)\n\tenvironment = car(cdr(object)).(*Environment)\n\treturn interpreter.evaluate(expression, environment)\n}\n\nfunc (interpreter *Interpreter) let(object Object, environment *Environment) Object {\n\tbindings := car(object)\n\tbody := cdr(object)\n\n\tbinding_parameter := func(binding Object) Object { return car(binding) }\n\tparameters := list_from(bindings, binding_parameter)\n\n\tbinding_arguments := func(binding Object) Object { return car(cdr(binding)) }\n\targuments := list_from(bindings, binding_arguments)\n\n\toperator := interpreter.lambda(cons(parameters, body), environment)\n\toperands := arguments\n\n\treturn &ExpressionObject{operator, operands}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"encoding\/gob\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n)\n\ntype dumpTraceFlags struct {\n\tTracePath string\n}\n\nvar (\n\tdumpTraceFlagset = flag.NewFlagSet(\"dump-trace\", flag.ExitOnError)\n\t_dumpTraceFlags  = dumpTraceFlags{}\n)\n\nfunc init() {\n\tdumpTraceFlagset.StringVar(&_dumpTraceFlags.TracePath, \"trace-path\", \"\", \"path of trace data file\")\n}\n\nfunc dumpTrace(args []string) {\n\tdumpTraceFlagset.Parse(args)\n\n\tif _dumpTraceFlags.TracePath == \"\" {\n\t\tfmt.Printf(\"specify path of trace data file\\n\")\n\t\tos.Exit(1)\n\t}\n\n\tfile, err := os.Open(_dumpTraceFlags.TracePath)\n\tif err != nil {\n\t\tfmt.Printf(\"failed to open trace data file(%s): %s\\n\", _dumpTraceFlags.TracePath, err)\n\t\tos.Exit(1)\n\t}\n\n\tdec := gob.NewDecoder(file)\n\tvar trace SingleTrace\n\tderr := dec.Decode(&trace)\n\tif derr != nil {\n\t\tfmt.Printf(\"failed to decode trace file(%s): %s\\n\", _dumpTraceFlags.TracePath, err)\n\t\tos.Exit(1)\n\t}\n\n\tfor i, ev := range trace.EventSequence {\n\t\tfmt.Printf(\"%d: %s, %s(%s)\\n\", i, ev.ProcId, ev.EventType, ev.EventParam)\n\t}\n}\n\nfunc runSearchTools(name string, args []string) {\n\tswitch name {\n\tcase \"dump-trace\":\n\t\tdumpTrace(args)\n\tdefault:\n\t\tfmt.Printf(\"unknown subcommand: %s\\n\", name)\n\t\tos.Exit(1)\n\t}\n}\n<commit_msg>search tools: a stub for duplication calculator<commit_after>\/\/ Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"encoding\/gob\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n)\n\ntype dumpTraceFlags struct {\n\tTracePath string\n}\n\ntype calcDuplicationFlags struct {\n\tTraceDir string\n}\n\nvar (\n\tdumpTraceFlagset = flag.NewFlagSet(\"dump-trace\", flag.ExitOnError)\n\t_dumpTraceFlags  = dumpTraceFlags{}\n\n\tcalcDuplicationFlagset = flag.NewFlagSet(\"calc-duplication\", flag.ExitOnError)\n\t_calcDuplicationFlags  = calcDuplicationFlags{}\n)\n\nfunc init() {\n\tdumpTraceFlagset.StringVar(&_dumpTraceFlags.TracePath, \"trace-path\", \"\", \"path of trace data file\")\n\n\tcalcDuplicationFlagset.StringVar(&_calcDuplicationFlags.TraceDir, \"trace-dir\", \"\", \"path of trace data directory\")\n}\n\nfunc dumpTrace(args []string) {\n\tdumpTraceFlagset.Parse(args)\n\n\tif _dumpTraceFlags.TracePath == \"\" {\n\t\tfmt.Printf(\"specify path of trace data file\\n\")\n\t\tos.Exit(1)\n\t}\n\n\tfile, err := os.Open(_dumpTraceFlags.TracePath)\n\tif err != nil {\n\t\tfmt.Printf(\"failed to open trace data file(%s): %s\\n\", _dumpTraceFlags.TracePath, err)\n\t\tos.Exit(1)\n\t}\n\n\tdec := gob.NewDecoder(file)\n\tvar trace SingleTrace\n\tderr := dec.Decode(&trace)\n\tif derr != nil {\n\t\tfmt.Printf(\"failed to decode trace file(%s): %s\\n\", _dumpTraceFlags.TracePath, err)\n\t\tos.Exit(1)\n\t}\n\n\tfor i, ev := range trace.EventSequence {\n\t\tfmt.Printf(\"%d: %s, %s(%s)\\n\", i, ev.ProcId, ev.EventType, ev.EventParam)\n\t}\n}\n\nfunc calcDuplication(args []string) {\n\tcalcDuplicationFlagset.Parse(args)\n\n\ttraceDir := _calcDuplicationFlags.TraceDir\n\tif traceDir == \"\" {\n\t\tfmt.Printf(\"specify directory path of trace data\\n\")\n\t\tos.Exit(1)\n\t}\n\n\tdes, err := ioutil.ReadDir(traceDir)\n\tif err != nil {\n\t\tfmt.Printf(\"failed to read directory(%s): %s\\n\", traceDir, err)\n\t\tos.Exit(1)\n\t}\n\n\tif len(des) == 0 {\n\t\tfmt.Printf(\"directory %s is empty\\n\", traceDir)\n\t\tos.Exit(1)\n\t}\n\n\tinfoFile, oerr := os.Open(traceDir + \"\/\" + SearchModeInfoPath)\n\tif oerr != nil {\n\t\tfmt.Printf(\"failed to read info file of search mode: %s\\n\", oerr)\n\t\tos.Exit(1)\n\t}\n\n\tinfoDec := gob.NewDecoder(infoFile)\n\tvar info SearchModeInfo\n\tderr := infoDec.Decode(&info)\n\tif derr != nil {\n\t\tfmt.Printf(\"failed to decode info file: %s\\n\", derr)\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Printf(\"a number of collected traces: %d\\n\", info.NrCollectedTraces)\n}\n\nfunc runSearchTools(name string, args []string) {\n\tswitch name {\n\tcase \"dump-trace\":\n\t\tdumpTrace(args)\n\tcase \"calc-duplication\":\n\t\tcalcDuplication(args)\n\tdefault:\n\t\tfmt.Printf(\"unknown subcommand: %s\\n\", name)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package notmain\n\nimport (\n\t\"bufio\"\n\t\"compress\/gzip\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/letsencrypt\/boulder\/cmd\"\n)\n\nvar raIssuanceLineRE = regexp.MustCompile(`Certificate request - successful JSON=(.*)`)\n\n\/\/ TODO: Extract the \"Valid for issuance: (true|false)\" field too.\nvar vaCAALineRE = regexp.MustCompile(`Checked CAA records for ([a-z0-9-.*]+), \\[Present: (true|false)`)\n\ntype issuanceEvent struct {\n\tSerialNumber string\n\tNames        []string\n\tRequester    int64\n\n\tissuanceTime time.Time\n}\n\nfunc openFile(path string) (*bufio.Scanner, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar reader io.Reader\n\treader = f\n\tif strings.HasSuffix(path, \".gz\") {\n\t\treader, err = gzip.NewReader(f)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tscanner := bufio.NewScanner(reader)\n\treturn scanner, nil\n}\n\nfunc parseTimestamp(line []byte) (time.Time, error) {\n\tdatestamp, err := time.Parse(time.RFC3339, string(line[0:32]))\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\treturn datestamp, nil\n}\n\n\/\/ loadIssuanceLog processes a single issuance (RA) log file. It returns a map\n\/\/ of names to slices of timestamps at which certificates for those names were\n\/\/ issued. It also returns the earliest and latest timestamps seen, to allow\n\/\/ CAA log processing to quickly skip irrelevant entries.\nfunc loadIssuanceLog(path string) (map[string][]time.Time, time.Time, time.Time, error) {\n\tscanner, err := openFile(path)\n\tif err != nil {\n\t\treturn nil, time.Time{}, time.Time{}, fmt.Errorf(\"failed to open %q: %w\", path, err)\n\t}\n\n\tlinesCount := 0\n\tearliest := time.Time{}\n\tlatest := time.Time{}\n\n\tissuanceMap := map[string][]time.Time{}\n\tfor scanner.Scan() {\n\t\tline := scanner.Bytes()\n\t\tlinesCount++\n\n\t\tmatches := raIssuanceLineRE.FindSubmatch(line)\n\t\tif matches == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif len(matches) != 2 {\n\t\t\treturn nil, earliest, latest, fmt.Errorf(\"line %d: unexpected number of regex matches\", linesCount)\n\t\t}\n\n\t\tvar ie issuanceEvent\n\t\terr := json.Unmarshal(matches[1], &ie)\n\t\tif err != nil {\n\t\t\treturn nil, earliest, latest, fmt.Errorf(\"line %d: failed to unmarshal JSON: %w\", linesCount, err)\n\t\t}\n\n\t\t\/\/ Populate the issuance time from the syslog timestamp, rather than the\n\t\t\/\/ ResponseTime member of the JSON. This makes testing a lot simpler because\n\t\t\/\/ of how we mess with time sometimes. Given that these timestamps are\n\t\t\/\/ generated on the same system, they should be tightly coupled anyway.\n\t\tie.issuanceTime, err = parseTimestamp(line)\n\t\tif err != nil {\n\t\t\treturn nil, earliest, latest, fmt.Errorf(\"line %d: failed to parse timestamp: %w\", linesCount, err)\n\t\t}\n\n\t\tif earliest.IsZero() || ie.issuanceTime.Before(earliest) {\n\t\t\tearliest = ie.issuanceTime\n\t\t}\n\t\tif latest.IsZero() || ie.issuanceTime.After(latest) {\n\t\t\tlatest = ie.issuanceTime\n\t\t}\n\t\tfor _, name := range ie.Names {\n\t\t\tissuanceMap[name] = append(issuanceMap[name], ie.issuanceTime)\n\t\t}\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, earliest, latest, err\n\t}\n\n\treturn issuanceMap, earliest, latest, nil\n}\n\n\/\/ processCAALog processes a single CAA (VA) log file. It modifies the input map\n\/\/ (of issuance names to times, as returned by `loadIssuanceLog`) to remove any\n\/\/ timestamps which are covered by (i.e. less than 8 hours after) a CAA check\n\/\/ for that name in the log file. It also prunes any names whose slice of\n\/\/ issuance times becomes empty.\nfunc processCAALog(path string, issuances map[string][]time.Time, earliest time.Time, latest time.Time, tolerance time.Duration) error {\n\tscanner, err := openFile(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open %q: %w\", path, err)\n\t}\n\n\tlinesCount := 0\n\n\tfor scanner.Scan() {\n\t\tline := scanner.Bytes()\n\t\tlinesCount++\n\n\t\tmatches := vaCAALineRE.FindSubmatch(line)\n\t\tif matches == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif len(matches) != 3 {\n\t\t\treturn fmt.Errorf(\"line %d: unexpected number of regex matches\", linesCount)\n\t\t}\n\t\tname := string(matches[1])\n\t\tpresent := string(matches[2])\n\n\t\tcheckTime, err := parseTimestamp(line)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"line %d: failed to parse timestamp: %w\", linesCount, err)\n\t\t}\n\n\t\t\/\/ Don't bother processing rows that definitely fall outside the period we\n\t\t\/\/ care about.\n\t\tif checkTime.After(latest) || checkTime.Before(earliest.Add(-8*time.Hour)) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ TODO: Only remove covered issuance timestamps if the CAA check actually\n\t\t\/\/ said that we're allowed to issue (i.e. had \"Valid for issuance: true\").\n\t\tissuances[name] = removeCoveredTimestamps(issuances[name], checkTime, tolerance)\n\t\tif len(issuances[name]) == 0 {\n\t\t\tdelete(issuances, name)\n\t\t}\n\n\t\t\/\/ If the CAA check didn't find any CAA records for w.x.y.z, then that means\n\t\t\/\/ that we checked the CAA records for x.y.z, y.z, and z as well, and are\n\t\t\/\/ covered for any issuance for those names.\n\t\tif present == \"false\" {\n\t\t\tlabels := strings.Split(name, \".\")\n\t\t\tfor i := 1; i < len(labels)-1; i++ {\n\t\t\t\ttailName := strings.Join(labels[i:], \".\")\n\t\t\t\tissuances[tailName] = removeCoveredTimestamps(issuances[tailName], checkTime, tolerance)\n\t\t\t\tif len(issuances[tailName]) == 0 {\n\t\t\t\t\tdelete(issuances, tailName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn scanner.Err()\n}\n\n\/\/ removeCoveredTimestamps returns a new slice of timestamps which contains all\n\/\/ timestamps that are *not* within 8 hours after the input timestamp.\nfunc removeCoveredTimestamps(timestamps []time.Time, cover time.Time, tolerance time.Duration) []time.Time {\n\tr := make([]time.Time, 0)\n\tfor _, ts := range timestamps {\n\t\t\/\/ Copy the timestamp into the results slice if it is before the covering\n\t\t\/\/ timestamp, or more than 8 hours after the covering timestamp (i.e. if\n\t\t\/\/ it is *not* covered by the covering timestamp).\n\t\tdiff := ts.Sub(cover)\n\t\tif diff < -tolerance || diff > 8*time.Hour+tolerance {\n\t\t\tts := ts\n\t\t\tr = append(r, ts)\n\t\t}\n\t}\n\treturn r\n}\n\n\/\/ formatErrors returns nil if the input map is empty. Otherwise, it returns an\n\/\/ error containing a listing of every name and issuance time that was not\n\/\/ covered by a CAA check.\nfunc formatErrors(remaining map[string][]time.Time) string {\n\tif len(remaining) == 0 {\n\t\treturn \"\"\n\t}\n\n\tmessages := make([]string, len(remaining))\n\tfor name, timestamps := range remaining {\n\t\tfor _, timestamp := range timestamps {\n\t\t\tmessages = append(messages, fmt.Sprintf(\"%v: %s\", timestamp, name))\n\t\t}\n\t}\n\n\tsort.Strings(messages)\n\treturn strings.Join(messages, \"\\n\")\n}\n\nfunc main() {\n\tlogStdoutLevel := flag.Int(\"stdout-level\", 6, \"Minimum severity of messages to send to stdout\")\n\tlogSyslogLevel := flag.Int(\"syslog-level\", 6, \"Minimum severity of messages to send to syslog\")\n\traLog := flag.String(\"ra-log\", \"\", \"Path to a single boulder-ra log file\")\n\tvaLogs := flag.String(\"va-logs\", \"\", \"List of paths to boulder-va logs, separated by commas\")\n\ttimeTolerance := flag.Duration(\"time-tolerance\", 0, \"How much slop to allow when comparing timestamps for ordering\")\n\tearliestFlag := flag.String(\"earliest\", \"\", \"Deprecated.\")\n\tlatestFlag := flag.String(\"latest\", \"\", \"Deprecated.\")\n\n\tflag.Parse()\n\n\tlogger := cmd.NewLogger(cmd.SyslogConfig{\n\t\tStdoutLevel: *logStdoutLevel,\n\t\tSyslogLevel: *logSyslogLevel,\n\t})\n\n\tif *timeTolerance < 0 {\n\t\tcmd.Fail(\"value of -time-tolerance must be non-negative\")\n\t}\n\n\tif *earliestFlag != \"\" || *latestFlag != \"\" {\n\t\tlogger.Info(\"The -earliest and -latest flags are deprecated and ignored.\")\n\t}\n\n\t\/\/ Build a map from hostnames to times at which those names were issued for.\n\t\/\/ Also retrieve the earliest and latest issuance times represented in the\n\t\/\/ data, so we can be more efficient when examining entries from the CAA log.\n\tissuanceMap, earliest, latest, err := loadIssuanceLog(*raLog)\n\tcmd.FailOnError(err, \"failed to load issuance logs\")\n\n\t\/\/ Try to pare the issuance map down to nothing by removing every entry which\n\t\/\/ is covered by a CAA check.\n\tfor _, vaLog := range strings.Split(*vaLogs, \",\") {\n\t\terr = processCAALog(vaLog, issuanceMap, earliest, latest, *timeTolerance)\n\t\tcmd.FailOnError(err, \"failed to process CAA checking logs\")\n\t}\n\n\terrStr := formatErrors(issuanceMap)\n\tif errStr != \"\" {\n\t\tlogger.AuditErrf(\"The following issuances were missing CAA checks:\\n%s\", errStr)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc init() {\n\tcmd.RegisterCommand(\"caa-log-checker\", main)\n}\n<commit_msg>Improve caa-log-checker errors (#5784)<commit_after>package notmain\n\nimport (\n\t\"bufio\"\n\t\"compress\/gzip\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/letsencrypt\/boulder\/cmd\"\n\tblog \"github.com\/letsencrypt\/boulder\/log\"\n)\n\nvar raIssuanceLineRE = regexp.MustCompile(`Certificate request - successful JSON=(.*)`)\n\n\/\/ TODO: Extract the \"Valid for issuance: (true|false)\" field too.\nvar vaCAALineRE = regexp.MustCompile(`Checked CAA records for ([a-z0-9-.*]+), \\[Present: (true|false)`)\n\ntype issuanceEvent struct {\n\tSerialNumber string\n\tNames        []string\n\tRequester    int64\n\n\tissuanceTime time.Time\n}\n\nfunc openFile(path string) (*bufio.Scanner, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar reader io.Reader\n\treader = f\n\tif strings.HasSuffix(path, \".gz\") {\n\t\treader, err = gzip.NewReader(f)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tscanner := bufio.NewScanner(reader)\n\treturn scanner, nil\n}\n\nfunc parseTimestamp(line []byte) (time.Time, error) {\n\tdatestamp, err := time.Parse(time.RFC3339, string(line[0:32]))\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\treturn datestamp, nil\n}\n\n\/\/ loadIssuanceLog processes a single issuance (RA) log file. It returns a map\n\/\/ of names to slices of timestamps at which certificates for those names were\n\/\/ issued. It also returns the earliest and latest timestamps seen, to allow\n\/\/ CAA log processing to quickly skip irrelevant entries.\nfunc loadIssuanceLog(path string) (map[string][]time.Time, time.Time, time.Time, error) {\n\tscanner, err := openFile(path)\n\tif err != nil {\n\t\treturn nil, time.Time{}, time.Time{}, fmt.Errorf(\"failed to open %q: %w\", path, err)\n\t}\n\n\tlinesCount := 0\n\tearliest := time.Time{}\n\tlatest := time.Time{}\n\n\tissuanceMap := map[string][]time.Time{}\n\tfor scanner.Scan() {\n\t\tline := scanner.Bytes()\n\t\tlinesCount++\n\n\t\tmatches := raIssuanceLineRE.FindSubmatch(line)\n\t\tif matches == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif len(matches) != 2 {\n\t\t\treturn nil, earliest, latest, fmt.Errorf(\"line %d: unexpected number of regex matches\", linesCount)\n\t\t}\n\n\t\tvar ie issuanceEvent\n\t\terr := json.Unmarshal(matches[1], &ie)\n\t\tif err != nil {\n\t\t\treturn nil, earliest, latest, fmt.Errorf(\"line %d: failed to unmarshal JSON: %w\", linesCount, err)\n\t\t}\n\n\t\t\/\/ Populate the issuance time from the syslog timestamp, rather than the\n\t\t\/\/ ResponseTime member of the JSON. This makes testing a lot simpler because\n\t\t\/\/ of how we mess with time sometimes. Given that these timestamps are\n\t\t\/\/ generated on the same system, they should be tightly coupled anyway.\n\t\tie.issuanceTime, err = parseTimestamp(line)\n\t\tif err != nil {\n\t\t\treturn nil, earliest, latest, fmt.Errorf(\"line %d: failed to parse timestamp: %w\", linesCount, err)\n\t\t}\n\n\t\tif earliest.IsZero() || ie.issuanceTime.Before(earliest) {\n\t\t\tearliest = ie.issuanceTime\n\t\t}\n\t\tif latest.IsZero() || ie.issuanceTime.After(latest) {\n\t\t\tlatest = ie.issuanceTime\n\t\t}\n\t\tfor _, name := range ie.Names {\n\t\t\tissuanceMap[name] = append(issuanceMap[name], ie.issuanceTime)\n\t\t}\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, earliest, latest, err\n\t}\n\n\treturn issuanceMap, earliest, latest, nil\n}\n\n\/\/ processCAALog processes a single CAA (VA) log file. It modifies the input map\n\/\/ (of issuance names to times, as returned by `loadIssuanceLog`) to remove any\n\/\/ timestamps which are covered by (i.e. less than 8 hours after) a CAA check\n\/\/ for that name in the log file. It also prunes any names whose slice of\n\/\/ issuance times becomes empty.\nfunc processCAALog(path string, issuances map[string][]time.Time, earliest time.Time, latest time.Time, tolerance time.Duration) error {\n\tscanner, err := openFile(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open %q: %w\", path, err)\n\t}\n\n\tlinesCount := 0\n\n\tfor scanner.Scan() {\n\t\tline := scanner.Bytes()\n\t\tlinesCount++\n\n\t\tmatches := vaCAALineRE.FindSubmatch(line)\n\t\tif matches == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif len(matches) != 3 {\n\t\t\treturn fmt.Errorf(\"line %d: unexpected number of regex matches\", linesCount)\n\t\t}\n\t\tname := string(matches[1])\n\t\tpresent := string(matches[2])\n\n\t\tcheckTime, err := parseTimestamp(line)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"line %d: failed to parse timestamp: %w\", linesCount, err)\n\t\t}\n\n\t\t\/\/ Don't bother processing rows that definitely fall outside the period we\n\t\t\/\/ care about.\n\t\tif checkTime.After(latest) || checkTime.Before(earliest.Add(-8*time.Hour)) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ TODO: Only remove covered issuance timestamps if the CAA check actually\n\t\t\/\/ said that we're allowed to issue (i.e. had \"Valid for issuance: true\").\n\t\tissuances[name] = removeCoveredTimestamps(issuances[name], checkTime, tolerance)\n\t\tif len(issuances[name]) == 0 {\n\t\t\tdelete(issuances, name)\n\t\t}\n\n\t\t\/\/ If the CAA check didn't find any CAA records for w.x.y.z, then that means\n\t\t\/\/ that we checked the CAA records for x.y.z, y.z, and z as well, and are\n\t\t\/\/ covered for any issuance for those names.\n\t\tif present == \"false\" {\n\t\t\tlabels := strings.Split(name, \".\")\n\t\t\tfor i := 1; i < len(labels)-1; i++ {\n\t\t\t\ttailName := strings.Join(labels[i:], \".\")\n\t\t\t\tissuances[tailName] = removeCoveredTimestamps(issuances[tailName], checkTime, tolerance)\n\t\t\t\tif len(issuances[tailName]) == 0 {\n\t\t\t\t\tdelete(issuances, tailName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn scanner.Err()\n}\n\n\/\/ removeCoveredTimestamps returns a new slice of timestamps which contains all\n\/\/ timestamps that are *not* within 8 hours after the input timestamp.\nfunc removeCoveredTimestamps(timestamps []time.Time, cover time.Time, tolerance time.Duration) []time.Time {\n\tr := make([]time.Time, 0)\n\tfor _, ts := range timestamps {\n\t\t\/\/ Copy the timestamp into the results slice if it is before the covering\n\t\t\/\/ timestamp, or more than 8 hours after the covering timestamp (i.e. if\n\t\t\/\/ it is *not* covered by the covering timestamp).\n\t\tdiff := ts.Sub(cover)\n\t\tif diff < -tolerance || diff > 8*time.Hour+tolerance {\n\t\t\tts := ts\n\t\t\tr = append(r, ts)\n\t\t}\n\t}\n\treturn r\n}\n\n\/\/ emitErrors returns nil if the input map is empty. Otherwise, it logs\n\/\/ a line for each name and issuance time that was not covered by a CAA\n\/\/ check, and return an error.\nfunc emitErrors(log blog.Logger, remaining map[string][]time.Time) error {\n\tif len(remaining) == 0 {\n\t\treturn nil\n\t}\n\n\tfor name, timestamps := range remaining {\n\t\tfor _, timestamp := range timestamps {\n\t\t\tlog.Infof(\"CAA-checking log event not found for issuance of %s at %s\", name, timestamp)\n\t\t}\n\t}\n\n\treturn errors.New(\"Some CAA-checking log events not found\")\n}\n\nfunc main() {\n\tlogStdoutLevel := flag.Int(\"stdout-level\", 6, \"Minimum severity of messages to send to stdout\")\n\tlogSyslogLevel := flag.Int(\"syslog-level\", 6, \"Minimum severity of messages to send to syslog\")\n\traLog := flag.String(\"ra-log\", \"\", \"Path to a single boulder-ra log file\")\n\tvaLogs := flag.String(\"va-logs\", \"\", \"List of paths to boulder-va logs, separated by commas\")\n\ttimeTolerance := flag.Duration(\"time-tolerance\", 0, \"How much slop to allow when comparing timestamps for ordering\")\n\tearliestFlag := flag.String(\"earliest\", \"\", \"Deprecated.\")\n\tlatestFlag := flag.String(\"latest\", \"\", \"Deprecated.\")\n\n\tflag.Parse()\n\n\tlogger := cmd.NewLogger(cmd.SyslogConfig{\n\t\tStdoutLevel: *logStdoutLevel,\n\t\tSyslogLevel: *logSyslogLevel,\n\t})\n\n\tif *timeTolerance < 0 {\n\t\tcmd.Fail(\"value of -time-tolerance must be non-negative\")\n\t}\n\n\tif *earliestFlag != \"\" || *latestFlag != \"\" {\n\t\tlogger.Info(\"The -earliest and -latest flags are deprecated and ignored.\")\n\t}\n\n\t\/\/ Build a map from hostnames to times at which those names were issued for.\n\t\/\/ Also retrieve the earliest and latest issuance times represented in the\n\t\/\/ data, so we can be more efficient when examining entries from the CAA log.\n\tissuanceMap, earliest, latest, err := loadIssuanceLog(*raLog)\n\tcmd.FailOnError(err, \"failed to load issuance logs\")\n\n\t\/\/ Try to pare the issuance map down to nothing by removing every entry which\n\t\/\/ is covered by a CAA check.\n\tfor _, vaLog := range strings.Split(*vaLogs, \",\") {\n\t\terr = processCAALog(vaLog, issuanceMap, earliest, latest, *timeTolerance)\n\t\tcmd.FailOnError(err, \"failed to process CAA checking logs\")\n\t}\n\n\terr = emitErrors(logger, issuanceMap)\n\tif err != nil {\n\t\tlogger.AuditErrf(\"%s\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc init() {\n\tcmd.RegisterCommand(\"caa-log-checker\", main)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/mistifyio\/mistify\/acomm\"\n\tflags \"github.com\/spf13\/pflag\"\n)\n\nconst (\n\targSep = \"=\"\n)\n\nfunc main() {\n\tlog.SetLevel(log.FatalLevel)\n\n\tvar coordinator, httpAddr, taskName string\n\tvar taskArgs []string\n\tvar streamRequest bool\n\tflags.StringVarP(&coordinator, \"coordinator_url\", \"c\", \"\", \"url of the coordinator\")\n\tflags.StringVarP(&taskName, \"task\", \"t\", \"\", \"task to run\")\n\tflags.StringSliceVarP(&taskArgs, \"request_arg\", \"a\", []string{}, fmt.Sprintf(\"task specific argument the form 'key%svalue'. can be set multiple times\", argSep))\n\tflags.StringVarP(&httpAddr, \"http_addr\", \"r\", \":4080\", \"address for http server to listen for responses and stream request data\")\n\tflags.BoolVarP(&streamRequest, \"stream\", \"s\", false, \"stream data from STDIN to provider\")\n\tflags.Parse()\n\n\targs, err := parseTaskArgs(taskArgs)\n\tdieOnError(err)\n\n\tresult, streamResult, respErr, err := startHTTPServer(httpAddr)\n\tdieOnError(err)\n\n\tdieOnError(makeRequest(coordinator, taskName, httpAddr, streamRequest, args))\n\n\tselect {\n\tcase err := <-respErr:\n\t\tdieOnError(err)\n\tcase result := <-result:\n\t\tj, _ := json.Marshal(result)\n\t\tfmt.Println(string(j))\n\tcase streamResult := <-streamResult:\n\t\tdieOnError(acomm.Stream(os.Stdout, streamResult))\n\t}\n}\n\nfunc dieOnError(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\n\/\/ argmap is an arbitrarilly nested map\ntype argmap map[string]interface{}\n\nfunc (am argmap) set(keys []string, value interface{}) error {\n\tif len(keys) == 0 {\n\t\tfmt.Println(\"no more keys and returning\")\n\t\treturn nil\n\t}\n\n\tkey := keys[0]\n\n\tif len(keys) == 1 {\n\t\tam[key] = value\n\t\treturn nil\n\t}\n\n\tvar m argmap\n\tmi, ok := am[key]\n\tif !ok {\n\t\tm = make(argmap)\n\t\tam[key] = m\n\t} else {\n\t\tm, ok = mi.(argmap)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"intermediate nested key %s defined and not a map\", key)\n\t\t}\n\t}\n\n\treturn m.set(keys[1:], value)\n}\n\nfunc parseTaskArgs(taskArgs []string) (map[string]interface{}, error) {\n\tout := make(argmap)\n\tfor _, in := range taskArgs {\n\t\tparts := strings.Split(in, argSep)\n\t\tif len(parts) < 2 {\n\t\t\treturn nil, fmt.Errorf(\"invalid request arg: '%s'\", in)\n\t\t}\n\n\t\tvalueS := strings.Join(parts[1:], argSep)\n\t\tvar value interface{}\n\t\tif arg, err := strconv.ParseInt(valueS, 10, 64); err == nil {\n\t\t\tvalue = arg\n\t\t} else if arg, err := strconv.ParseBool(valueS); err == nil {\n\t\t\tvalue = arg\n\t\t} else {\n\t\t\tvalue = valueS\n\t\t}\n\n\t\tkeys := strings.Split(parts[0], \".\")\n\t\tif err := out.set(keys, value); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\treturn out, nil\n}\n\nfunc startHTTPServer(addr string) (chan interface{}, chan *url.URL, chan error, error) {\n\tresult := make(chan interface{}, 1)\n\terrChan := make(chan error, 1)\n\tstream := make(chan *url.URL, 1)\n\n\thttp.HandleFunc(\"\/response\", func(w http.ResponseWriter, r *http.Request) {\n\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tresp := &acomm.Response{}\n\t\tif err := json.Unmarshal(body, resp); err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tack, _ := json.Marshal(&acomm.Response{})\n\t\t_, _ = w.Write(ack)\n\n\t\tif resp.Error != nil {\n\t\t\terrChan <- resp.Error\n\t\t\treturn\n\t\t}\n\n\t\tif resp.StreamURL != nil {\n\t\t\tstream <- resp.StreamURL\n\t\t} else {\n\t\t\tresult <- resp.Result\n\t\t}\n\t})\n\thttp.HandleFunc(\"\/stream\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif _, err := io.Copy(w, os.Stdin); err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t})\n\n\trunErr := make(chan error)\n\trunning := time.NewTimer(time.Second)\n\tgo func() {\n\t\tif err := http.ListenAndServe(addr, nil); err != nil {\n\t\t\trunErr <- err\n\t\t}\n\t}()\n\n\tvar err error\n\tselect {\n\tcase <-running.C:\n\tcase err = <-runErr:\n\t}\n\n\treturn result, stream, errChan, err\n}\n\nfunc makeRequest(coordinator, taskName, httpAddr string, stream bool, taskArgs map[string]interface{}) error {\n\tcoordinatorURL, err := url.ParseRequestURI(coordinator)\n\tif err != nil {\n\t\treturn errors.New(\"invalid coordinator url\")\n\t}\n\n\tresponseHook := fmt.Sprintf(\"http:\/\/%s\/response\", httpAddr)\n\tstreamURL := \"\"\n\tif stream {\n\t\tstreamURL = fmt.Sprintf(\"http:\/\/%s\/stream\", httpAddr)\n\t}\n\treq, err := acomm.NewRequest(taskName, responseHook, streamURL, taskArgs, nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn acomm.Send(coordinatorURL, req)\n}\n<commit_msg>Remove debug line that snuck in<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/mistifyio\/mistify\/acomm\"\n\tflags \"github.com\/spf13\/pflag\"\n)\n\nconst (\n\targSep = \"=\"\n)\n\nfunc main() {\n\tlog.SetLevel(log.FatalLevel)\n\n\tvar coordinator, httpAddr, taskName string\n\tvar taskArgs []string\n\tvar streamRequest bool\n\tflags.StringVarP(&coordinator, \"coordinator_url\", \"c\", \"\", \"url of the coordinator\")\n\tflags.StringVarP(&taskName, \"task\", \"t\", \"\", \"task to run\")\n\tflags.StringSliceVarP(&taskArgs, \"request_arg\", \"a\", []string{}, fmt.Sprintf(\"task specific argument the form 'key%svalue'. can be set multiple times\", argSep))\n\tflags.StringVarP(&httpAddr, \"http_addr\", \"r\", \":4080\", \"address for http server to listen for responses and stream request data\")\n\tflags.BoolVarP(&streamRequest, \"stream\", \"s\", false, \"stream data from STDIN to provider\")\n\tflags.Parse()\n\n\targs, err := parseTaskArgs(taskArgs)\n\tdieOnError(err)\n\n\tresult, streamResult, respErr, err := startHTTPServer(httpAddr)\n\tdieOnError(err)\n\n\tdieOnError(makeRequest(coordinator, taskName, httpAddr, streamRequest, args))\n\n\tselect {\n\tcase err := <-respErr:\n\t\tdieOnError(err)\n\tcase result := <-result:\n\t\tj, _ := json.Marshal(result)\n\t\tfmt.Println(string(j))\n\tcase streamResult := <-streamResult:\n\t\tdieOnError(acomm.Stream(os.Stdout, streamResult))\n\t}\n}\n\nfunc dieOnError(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n\n\/\/ argmap is an arbitrarilly nested map\ntype argmap map[string]interface{}\n\nfunc (am argmap) set(keys []string, value interface{}) error {\n\tif len(keys) == 0 {\n\t\treturn nil\n\t}\n\n\tkey := keys[0]\n\n\tif len(keys) == 1 {\n\t\tam[key] = value\n\t\treturn nil\n\t}\n\n\tvar m argmap\n\tmi, ok := am[key]\n\tif !ok {\n\t\tm = make(argmap)\n\t\tam[key] = m\n\t} else {\n\t\tm, ok = mi.(argmap)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"intermediate nested key %s defined and not a map\", key)\n\t\t}\n\t}\n\n\treturn m.set(keys[1:], value)\n}\n\nfunc parseTaskArgs(taskArgs []string) (map[string]interface{}, error) {\n\tout := make(argmap)\n\tfor _, in := range taskArgs {\n\t\tparts := strings.Split(in, argSep)\n\t\tif len(parts) < 2 {\n\t\t\treturn nil, fmt.Errorf(\"invalid request arg: '%s'\", in)\n\t\t}\n\n\t\tvalueS := strings.Join(parts[1:], argSep)\n\t\tvar value interface{}\n\t\tif arg, err := strconv.ParseInt(valueS, 10, 64); err == nil {\n\t\t\tvalue = arg\n\t\t} else if arg, err := strconv.ParseBool(valueS); err == nil {\n\t\t\tvalue = arg\n\t\t} else {\n\t\t\tvalue = valueS\n\t\t}\n\n\t\tkeys := strings.Split(parts[0], \".\")\n\t\tif err := out.set(keys, value); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\treturn out, nil\n}\n\nfunc startHTTPServer(addr string) (chan interface{}, chan *url.URL, chan error, error) {\n\tresult := make(chan interface{}, 1)\n\terrChan := make(chan error, 1)\n\tstream := make(chan *url.URL, 1)\n\n\thttp.HandleFunc(\"\/response\", func(w http.ResponseWriter, r *http.Request) {\n\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tresp := &acomm.Response{}\n\t\tif err := json.Unmarshal(body, resp); err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\n\t\tack, _ := json.Marshal(&acomm.Response{})\n\t\t_, _ = w.Write(ack)\n\n\t\tif resp.Error != nil {\n\t\t\terrChan <- resp.Error\n\t\t\treturn\n\t\t}\n\n\t\tif resp.StreamURL != nil {\n\t\t\tstream <- resp.StreamURL\n\t\t} else {\n\t\t\tresult <- resp.Result\n\t\t}\n\t})\n\thttp.HandleFunc(\"\/stream\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif _, err := io.Copy(w, os.Stdin); err != nil {\n\t\t\terrChan <- err\n\t\t\treturn\n\t\t}\n\t})\n\n\trunErr := make(chan error)\n\trunning := time.NewTimer(time.Second)\n\tgo func() {\n\t\tif err := http.ListenAndServe(addr, nil); err != nil {\n\t\t\trunErr <- err\n\t\t}\n\t}()\n\n\tvar err error\n\tselect {\n\tcase <-running.C:\n\tcase err = <-runErr:\n\t}\n\n\treturn result, stream, errChan, err\n}\n\nfunc makeRequest(coordinator, taskName, httpAddr string, stream bool, taskArgs map[string]interface{}) error {\n\tcoordinatorURL, err := url.ParseRequestURI(coordinator)\n\tif err != nil {\n\t\treturn errors.New(\"invalid coordinator url\")\n\t}\n\n\tresponseHook := fmt.Sprintf(\"http:\/\/%s\/response\", httpAddr)\n\tstreamURL := \"\"\n\tif stream {\n\t\tstreamURL = fmt.Sprintf(\"http:\/\/%s\/stream\", httpAddr)\n\t}\n\treq, err := acomm.NewRequest(taskName, responseHook, streamURL, taskArgs, nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn acomm.Send(coordinatorURL, req)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2017 G. Hussain Chinoy <ghchinoy@gmail.com>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com\/ghchinoy\/cectl\/ce\"\n\t\"github.com\/olekukonko\/tablewriter\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ listFormualInstancesCmd represents the listFormualInstances command\nvar listFormulaInstancesCmd = &cobra.Command{\n\tUse:   \"instances <id>\",\n\tShort: \"List Instances associated with a specific Formula\",\n\tLong:  `Retrieve a list of all instances associated with a particular formula template.`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\tif len(args) < 1 {\n\t\t\tfmt.Println(\"must supply an ID of a Formula\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tif !viper.IsSet(profile + \".base\") {\n\t\t\tfmt.Println(\"Can't find info for profile\", profile)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tbase := viper.Get(profile + \".base\")\n\t\tuser := viper.Get(profile + \".user\")\n\t\torg := viper.Get(profile + \".org\")\n\n\t\turl := fmt.Sprintf(\"%s%s\",\n\t\t\tbase,\n\t\t\tfmt.Sprintf(ce.FormulaInstancesURIFormat, args[0]),\n\t\t)\n\t\tauth := fmt.Sprintf(\"User %s, Organization %s\", user, org)\n\n\t\tclient := &http.Client{}\n\t\treq, err := http.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Can't construct request\", err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t\treq.Header.Add(\"Authorization\", auth)\n\t\treq.Header.Add(\"Accept\", \"application\/json\")\n\t\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Cannot process response\", err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t\tbodybytes, err := ioutil.ReadAll(resp.Body)\n\t\tdefer resp.Body.Close()\n\n\t\tif outputJSON {\n\t\t\tfmt.Printf(\"%s\\n\", bodybytes)\n\t\t\treturn\n\t\t}\n\n\t\tif resp.StatusCode == 200 {\n\t\t\tdata := [][]string{}\n\n\t\t\tvar instances []ce.FormulaInstance\n\t\t\terr = json.Unmarshal(bodybytes, &instances)\n\t\t\tfor _, v := range instances {\n\t\t\t\tdata = append(data, []string{\n\t\t\t\t\tstrconv.Itoa(v.ID),\n\t\t\t\t\tv.Name,\n\t\t\t\t\tstrconv.FormatBool(v.Active),\n\t\t\t\t\tfmt.Sprintf(\"%v %s\", v.Formula.ID, v.Formula.Name),\n\t\t\t\t\tv.CreatedDate.String(),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\ttable := tablewriter.NewWriter(os.Stdout)\n\t\t\ttable.SetHeader([]string{\"ID\", \"Instance\", \"active\", \"Formula\", \"Created\"})\n\t\t\ttable.SetBorder(false)\n\t\t\ttable.AppendBulk(data)\n\t\t\ttable.Render()\n\t\t}\n\n\t},\n}\n\nfunc init() {\n\tformulasCmd.AddCommand(listFormulaInstancesCmd)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\n\t\/\/ Cobra supports Persistent Flags which will work for this command\n\t\/\/ and all subcommands, e.g.:\n\t\/\/ listFormualInstancesCmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t\/\/ Cobra supports local flags which will only run when this command\n\t\/\/ is called directly, e.g.:\n\t\/\/ listFormualInstancesCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n\n}\n<commit_msg>conifg param names<commit_after>\/\/ Copyright © 2017 G. Hussain Chinoy <ghchinoy@gmail.com>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/ghchinoy\/cectl\/ce\"\n\t\"github.com\/olekukonko\/tablewriter\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ listFormualInstancesCmd represents the listFormualInstances command\nvar listFormulaInstancesCmd = &cobra.Command{\n\tUse:   \"instances <id>\",\n\tShort: \"List Instances associated with a specific Formula\",\n\tLong:  `Retrieve a list of all instances associated with a particular formula template.`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\tif len(args) < 1 {\n\t\t\tfmt.Println(\"must supply an ID of a Formula\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tif !viper.IsSet(profile + \".base\") {\n\t\t\tfmt.Println(\"Can't find info for profile\", profile)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tbase := viper.Get(profile + \".base\")\n\t\tuser := viper.Get(profile + \".user\")\n\t\torg := viper.Get(profile + \".org\")\n\n\t\turl := fmt.Sprintf(\"%s%s\",\n\t\t\tbase,\n\t\t\tfmt.Sprintf(ce.FormulaInstancesURIFormat, args[0]),\n\t\t)\n\t\tauth := fmt.Sprintf(\"User %s, Organization %s\", user, org)\n\n\t\tclient := &http.Client{}\n\t\treq, err := http.NewRequest(\"GET\", url, nil)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Can't construct request\", err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t\treq.Header.Add(\"Authorization\", auth)\n\t\treq.Header.Add(\"Accept\", \"application\/json\")\n\t\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Cannot process response\", err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t\tbodybytes, err := ioutil.ReadAll(resp.Body)\n\t\tdefer resp.Body.Close()\n\n\t\tif outputJSON {\n\t\t\tfmt.Printf(\"%s\\n\", bodybytes)\n\t\t\treturn\n\t\t}\n\n\t\tif resp.StatusCode == 200 {\n\t\t\tdata := [][]string{}\n\n\t\t\tvar instances []ce.FormulaInstance\n\t\t\terr = json.Unmarshal(bodybytes, &instances)\n\t\t\tfor _, v := range instances {\n\n\t\t\t\tvar configs []string\n\t\t\t\tif c, ok := v.Configuration.(map[string]interface{}); ok {\n\t\t\t\t\tfor k, v := range c {\n\t\t\t\t\t\tconfigs = append(configs, fmt.Sprintf(\"%s:%s\", k, v))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tdata = append(data, []string{\n\t\t\t\t\tstrconv.Itoa(v.ID),\n\t\t\t\t\tv.Name,\n\t\t\t\t\tstrconv.FormatBool(v.Active),\n\t\t\t\t\tfmt.Sprintf(\"%v %s\", v.Formula.ID, v.Formula.Name),\n\t\t\t\t\tstrings.Join(configs, \", \"),\n\t\t\t\t\tv.CreatedDate.String(),\n\t\t\t\t})\n\t\t\t}\n\n\t\t\ttable := tablewriter.NewWriter(os.Stdout)\n\t\t\ttable.SetHeader([]string{\"ID\", \"Instance\", \"active\", \"Formula\", \"Configuration\", \"Created\"})\n\t\t\ttable.SetBorder(false)\n\t\t\ttable.AppendBulk(data)\n\t\t\ttable.Render()\n\t\t}\n\n\t},\n}\n\nfunc init() {\n\tformulasCmd.AddCommand(listFormulaInstancesCmd)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\n\t\/\/ Cobra supports Persistent Flags which will work for this command\n\t\/\/ and all subcommands, e.g.:\n\t\/\/ listFormualInstancesCmd.PersistentFlags().String(\"foo\", \"\", \"A help for foo\")\n\n\t\/\/ Cobra supports local flags which will only run when this command\n\t\/\/ is called directly, e.g.:\n\t\/\/ listFormualInstancesCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package tls partially implements TLS 1.2, as specified in RFC 5246.\npackage tls\n\nimport (\n\t\"crypto\"\n\t\"crypto\/ecdsa\"\n\t\"crypto\/rsa\"\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Server returns a new TLS server side connection\n\/\/ using conn as the underlying transport.\n\/\/ The configuration config must be non-nil and must have\n\/\/ at least one certificate.\nfunc Server(conn net.Conn, config *Config) *Conn {\n\treturn &Conn{conn: conn, config: config}\n}\n\n\/\/ Client returns a new TLS client side connection\n\/\/ using conn as the underlying transport.\n\/\/ The config cannot be nil: users must set either ServerName or\n\/\/ InsecureSkipVerify in the config.\nfunc Client(conn net.Conn, config *Config) *Conn {\n\treturn &Conn{conn: conn, config: config, isClient: true}\n}\n\n\/\/ A listener implements a network listener (net.Listener) for TLS connections.\ntype listener struct {\n\tnet.Listener\n\tconfig *Config\n}\n\n\/\/ Accept waits for and returns the next incoming TLS connection.\n\/\/ The returned connection c is a *tls.Conn.\nfunc (l *listener) Accept() (c net.Conn, err error) {\n\tc, err = l.Listener.Accept()\n\tif err != nil {\n\t\treturn\n\t}\n\tc = Server(c, l.config)\n\treturn\n}\n\n\/\/ NewListener creates a Listener which accepts connections from an inner\n\/\/ Listener and wraps each connection with Server.\n\/\/ The configuration config must be non-nil and must have\n\/\/ at least one certificate.\nfunc NewListener(inner net.Listener, config *Config) net.Listener {\n\tl := new(listener)\n\tl.Listener = inner\n\tl.config = config\n\treturn l\n}\n\n\/\/ Listen creates a TLS listener accepting connections on the\n\/\/ given network address using net.Listen.\n\/\/ The configuration config must be non-nil and must have\n\/\/ at least one certificate.\nfunc Listen(network, laddr string, config *Config) (net.Listener, error) {\n\tif config == nil || len(config.Certificates) == 0 {\n\t\treturn nil, errors.New(\"tls.Listen: no certificates in configuration\")\n\t}\n\tl, err := net.Listen(network, laddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewListener(l, config), nil\n}\n\ntype timeoutError struct{}\n\nfunc (timeoutError) Error() string   { return \"tls: DialWithDialer timed out\" }\nfunc (timeoutError) Timeout() bool   { return true }\nfunc (timeoutError) Temporary() bool { return true }\n\n\/\/ DialWithDialer connects to the given network address using dialer.Dial and\n\/\/ then initiates a TLS handshake, returning the resulting TLS connection. Any\n\/\/ timeout or deadline given in the dialer apply to connection and TLS\n\/\/ handshake as a whole.\n\/\/\n\/\/ DialWithDialer interprets a nil configuration as equivalent to the zero\n\/\/ configuration; see the documentation of Config for the defaults.\nfunc DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {\n\t\/\/ We want the Timeout and Deadline values from dialer to cover the\n\t\/\/ whole process: TCP connection and TLS handshake. This means that we\n\t\/\/ also need to start our own timers now.\n\ttimeout := dialer.Timeout\n\n\tif !dialer.Deadline.IsZero() {\n\t\tdeadlineTimeout := dialer.Deadline.Sub(time.Now())\n\t\tif timeout == 0 || deadlineTimeout < timeout {\n\t\t\ttimeout = deadlineTimeout\n\t\t}\n\t}\n\n\tvar errChannel chan error\n\n\tif timeout != 0 {\n\t\terrChannel = make(chan error, 2)\n\t\ttime.AfterFunc(timeout, func() {\n\t\t\terrChannel <- timeoutError{}\n\t\t})\n\t}\n\n\trawConn, err := dialer.Dial(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcolonPos := strings.LastIndex(addr, \":\")\n\tif colonPos == -1 {\n\t\tcolonPos = len(addr)\n\t}\n\thostname := addr[:colonPos]\n\n\tif config == nil {\n\t\tconfig = defaultConfig()\n\t}\n\t\/\/ If no ServerName is set, infer the ServerName\n\t\/\/ from the hostname we're connecting to.\n\tif config.ServerName == \"\" {\n\t\t\/\/ Make a copy to avoid polluting argument or default.\n\t\tc := *config\n\t\tc.ServerName = hostname\n\t\tconfig = &c\n\t}\n\n\tconn := Client(rawConn, config)\n\n\tif timeout == 0 {\n\t\terr = conn.Handshake()\n\t} else {\n\t\tgo func() {\n\t\t\terrChannel <- conn.Handshake()\n\t\t}()\n\n\t\terr = <-errChannel\n\t}\n\n\tif err != nil {\n\t\trawConn.Close()\n\t\treturn nil, err\n\t}\n\n\treturn conn, nil\n}\n\n\/\/ Dial connects to the given network address using net.Dial\n\/\/ and then initiates a TLS handshake, returning the resulting\n\/\/ TLS connection.\n\/\/ Dial interprets a nil configuration as equivalent to\n\/\/ the zero configuration; see the documentation of Config\n\/\/ for the defaults.\nfunc Dial(network, addr string, config *Config) (*Conn, error) {\n\treturn DialWithDialer(new(net.Dialer), network, addr, config)\n}\n\n\/\/ LoadX509KeyPair reads and parses a public\/private key pair from a pair of\n\/\/ files. The files must contain PEM encoded data.\nfunc LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {\n\tcertPEMBlock, err := ioutil.ReadFile(certFile)\n\tif err != nil {\n\t\treturn Certificate{}, err\n\t}\n\tkeyPEMBlock, err := ioutil.ReadFile(keyFile)\n\tif err != nil {\n\t\treturn Certificate{}, err\n\t}\n\treturn X509KeyPair(certPEMBlock, keyPEMBlock)\n}\n\n\/\/ X509KeyPair parses a public\/private key pair from a pair of\n\/\/ PEM encoded data.\nfunc X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {\n\tvar cert Certificate\n\tvar certDERBlock *pem.Block\n\tfail := func(err error) (Certificate, error) { return Certificate{}, err }\n\tfor {\n\t\tcertDERBlock, certPEMBlock = pem.Decode(certPEMBlock)\n\t\tif certDERBlock == nil {\n\t\t\tbreak\n\t\t}\n\t\tif certDERBlock.Type == \"CERTIFICATE\" {\n\t\t\tcert.Certificate = append(cert.Certificate, certDERBlock.Bytes)\n\t\t}\n\t}\n\n\tif len(cert.Certificate) == 0 {\n\t\treturn fail(errors.New(\"crypto\/tls: failed to parse certificate PEM data\"))\n\t}\n\n\tvar keyDERBlock *pem.Block\n\tfor {\n\t\tkeyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)\n\t\tif keyDERBlock == nil {\n\t\t\treturn fail(errors.New(\"crypto\/tls: failed to parse key PEM data\"))\n\t\t}\n\t\tif keyDERBlock.Type == \"PRIVATE KEY\" || strings.HasSuffix(keyDERBlock.Type, \" PRIVATE KEY\") {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvar err error\n\tcert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)\n\tif err != nil {\n\t\treturn fail(err)\n\t}\n\n\t\/\/ We don't need to parse the public key for TLS, but we so do anyway\n\t\/\/ to check that it looks sane and matches the private key.\n\tx509Cert, err := x509.ParseCertificate(cert.Certificate[0])\n\tif err != nil {\n\t\treturn fail(err)\n\t}\n\n\tswitch pub := x509Cert.PublicKey.(type) {\n\tcase *rsa.PublicKey:\n\t\tpriv, ok := cert.PrivateKey.(*rsa.PrivateKey)\n\t\tif !ok {\n\t\t\treturn fail(errors.New(\"crypto\/tls: private key type does not match public key type\"))\n\t\t}\n\t\tif pub.N.Cmp(priv.N) != 0 {\n\t\t\treturn fail(errors.New(\"crypto\/tls: private key does not match public key\"))\n\t\t}\n\tcase *ecdsa.PublicKey:\n\t\tpriv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)\n\t\tif !ok {\n\t\t\treturn fail(errors.New(\"crypto\/tls: private key type does not match public key type\"))\n\n\t\t}\n\t\tif pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {\n\t\t\treturn fail(errors.New(\"crypto\/tls: private key does not match public key\"))\n\t\t}\n\tdefault:\n\t\treturn fail(errors.New(\"crypto\/tls: unknown public key algorithm\"))\n\t}\n\n\treturn cert, nil\n}\n\n\/\/ Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates\n\/\/ PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.\n\/\/ OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.\nfunc parsePrivateKey(der []byte) (crypto.PrivateKey, error) {\n\tif key, err := x509.ParsePKCS1PrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\tif key, err := x509.ParsePKCS8PrivateKey(der); err == nil {\n\t\tswitch key := key.(type) {\n\t\tcase *rsa.PrivateKey, *ecdsa.PrivateKey:\n\t\t\treturn key, nil\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"crypto\/tls: found unknown private key type in PKCS#8 wrapping\")\n\t\t}\n\t}\n\tif key, err := x509.ParseECPrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\n\treturn nil, errors.New(\"crypto\/tls: failed to parse private key\")\n}\n<commit_msg>crypto\/tls: allow tls.Listen when only GetCertificate is provided.<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package tls partially implements TLS 1.2, as specified in RFC 5246.\npackage tls\n\nimport (\n\t\"crypto\"\n\t\"crypto\/ecdsa\"\n\t\"crypto\/rsa\"\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Server returns a new TLS server side connection\n\/\/ using conn as the underlying transport.\n\/\/ The configuration config must be non-nil and must have\n\/\/ at least one certificate.\nfunc Server(conn net.Conn, config *Config) *Conn {\n\treturn &Conn{conn: conn, config: config}\n}\n\n\/\/ Client returns a new TLS client side connection\n\/\/ using conn as the underlying transport.\n\/\/ The config cannot be nil: users must set either ServerName or\n\/\/ InsecureSkipVerify in the config.\nfunc Client(conn net.Conn, config *Config) *Conn {\n\treturn &Conn{conn: conn, config: config, isClient: true}\n}\n\n\/\/ A listener implements a network listener (net.Listener) for TLS connections.\ntype listener struct {\n\tnet.Listener\n\tconfig *Config\n}\n\n\/\/ Accept waits for and returns the next incoming TLS connection.\n\/\/ The returned connection c is a *tls.Conn.\nfunc (l *listener) Accept() (c net.Conn, err error) {\n\tc, err = l.Listener.Accept()\n\tif err != nil {\n\t\treturn\n\t}\n\tc = Server(c, l.config)\n\treturn\n}\n\n\/\/ NewListener creates a Listener which accepts connections from an inner\n\/\/ Listener and wraps each connection with Server.\n\/\/ The configuration config must be non-nil and must have\n\/\/ at least one certificate.\nfunc NewListener(inner net.Listener, config *Config) net.Listener {\n\tl := new(listener)\n\tl.Listener = inner\n\tl.config = config\n\treturn l\n}\n\n\/\/ Listen creates a TLS listener accepting connections on the\n\/\/ given network address using net.Listen.\n\/\/ The configuration config must be non-nil and must have\n\/\/ at least one certificate.\nfunc Listen(network, laddr string, config *Config) (net.Listener, error) {\n\tif config == nil || (len(config.Certificates) == 0 && config.GetCertificate == nil) {\n\t\treturn nil, errors.New(\"tls: neither Certificates nor GetCertificate set in Config\")\n\t}\n\tl, err := net.Listen(network, laddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewListener(l, config), nil\n}\n\ntype timeoutError struct{}\n\nfunc (timeoutError) Error() string   { return \"tls: DialWithDialer timed out\" }\nfunc (timeoutError) Timeout() bool   { return true }\nfunc (timeoutError) Temporary() bool { return true }\n\n\/\/ DialWithDialer connects to the given network address using dialer.Dial and\n\/\/ then initiates a TLS handshake, returning the resulting TLS connection. Any\n\/\/ timeout or deadline given in the dialer apply to connection and TLS\n\/\/ handshake as a whole.\n\/\/\n\/\/ DialWithDialer interprets a nil configuration as equivalent to the zero\n\/\/ configuration; see the documentation of Config for the defaults.\nfunc DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) {\n\t\/\/ We want the Timeout and Deadline values from dialer to cover the\n\t\/\/ whole process: TCP connection and TLS handshake. This means that we\n\t\/\/ also need to start our own timers now.\n\ttimeout := dialer.Timeout\n\n\tif !dialer.Deadline.IsZero() {\n\t\tdeadlineTimeout := dialer.Deadline.Sub(time.Now())\n\t\tif timeout == 0 || deadlineTimeout < timeout {\n\t\t\ttimeout = deadlineTimeout\n\t\t}\n\t}\n\n\tvar errChannel chan error\n\n\tif timeout != 0 {\n\t\terrChannel = make(chan error, 2)\n\t\ttime.AfterFunc(timeout, func() {\n\t\t\terrChannel <- timeoutError{}\n\t\t})\n\t}\n\n\trawConn, err := dialer.Dial(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcolonPos := strings.LastIndex(addr, \":\")\n\tif colonPos == -1 {\n\t\tcolonPos = len(addr)\n\t}\n\thostname := addr[:colonPos]\n\n\tif config == nil {\n\t\tconfig = defaultConfig()\n\t}\n\t\/\/ If no ServerName is set, infer the ServerName\n\t\/\/ from the hostname we're connecting to.\n\tif config.ServerName == \"\" {\n\t\t\/\/ Make a copy to avoid polluting argument or default.\n\t\tc := *config\n\t\tc.ServerName = hostname\n\t\tconfig = &c\n\t}\n\n\tconn := Client(rawConn, config)\n\n\tif timeout == 0 {\n\t\terr = conn.Handshake()\n\t} else {\n\t\tgo func() {\n\t\t\terrChannel <- conn.Handshake()\n\t\t}()\n\n\t\terr = <-errChannel\n\t}\n\n\tif err != nil {\n\t\trawConn.Close()\n\t\treturn nil, err\n\t}\n\n\treturn conn, nil\n}\n\n\/\/ Dial connects to the given network address using net.Dial\n\/\/ and then initiates a TLS handshake, returning the resulting\n\/\/ TLS connection.\n\/\/ Dial interprets a nil configuration as equivalent to\n\/\/ the zero configuration; see the documentation of Config\n\/\/ for the defaults.\nfunc Dial(network, addr string, config *Config) (*Conn, error) {\n\treturn DialWithDialer(new(net.Dialer), network, addr, config)\n}\n\n\/\/ LoadX509KeyPair reads and parses a public\/private key pair from a pair of\n\/\/ files. The files must contain PEM encoded data.\nfunc LoadX509KeyPair(certFile, keyFile string) (Certificate, error) {\n\tcertPEMBlock, err := ioutil.ReadFile(certFile)\n\tif err != nil {\n\t\treturn Certificate{}, err\n\t}\n\tkeyPEMBlock, err := ioutil.ReadFile(keyFile)\n\tif err != nil {\n\t\treturn Certificate{}, err\n\t}\n\treturn X509KeyPair(certPEMBlock, keyPEMBlock)\n}\n\n\/\/ X509KeyPair parses a public\/private key pair from a pair of\n\/\/ PEM encoded data.\nfunc X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error) {\n\tvar cert Certificate\n\tvar certDERBlock *pem.Block\n\tfail := func(err error) (Certificate, error) { return Certificate{}, err }\n\tfor {\n\t\tcertDERBlock, certPEMBlock = pem.Decode(certPEMBlock)\n\t\tif certDERBlock == nil {\n\t\t\tbreak\n\t\t}\n\t\tif certDERBlock.Type == \"CERTIFICATE\" {\n\t\t\tcert.Certificate = append(cert.Certificate, certDERBlock.Bytes)\n\t\t}\n\t}\n\n\tif len(cert.Certificate) == 0 {\n\t\treturn fail(errors.New(\"crypto\/tls: failed to parse certificate PEM data\"))\n\t}\n\n\tvar keyDERBlock *pem.Block\n\tfor {\n\t\tkeyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock)\n\t\tif keyDERBlock == nil {\n\t\t\treturn fail(errors.New(\"crypto\/tls: failed to parse key PEM data\"))\n\t\t}\n\t\tif keyDERBlock.Type == \"PRIVATE KEY\" || strings.HasSuffix(keyDERBlock.Type, \" PRIVATE KEY\") {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvar err error\n\tcert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes)\n\tif err != nil {\n\t\treturn fail(err)\n\t}\n\n\t\/\/ We don't need to parse the public key for TLS, but we so do anyway\n\t\/\/ to check that it looks sane and matches the private key.\n\tx509Cert, err := x509.ParseCertificate(cert.Certificate[0])\n\tif err != nil {\n\t\treturn fail(err)\n\t}\n\n\tswitch pub := x509Cert.PublicKey.(type) {\n\tcase *rsa.PublicKey:\n\t\tpriv, ok := cert.PrivateKey.(*rsa.PrivateKey)\n\t\tif !ok {\n\t\t\treturn fail(errors.New(\"crypto\/tls: private key type does not match public key type\"))\n\t\t}\n\t\tif pub.N.Cmp(priv.N) != 0 {\n\t\t\treturn fail(errors.New(\"crypto\/tls: private key does not match public key\"))\n\t\t}\n\tcase *ecdsa.PublicKey:\n\t\tpriv, ok := cert.PrivateKey.(*ecdsa.PrivateKey)\n\t\tif !ok {\n\t\t\treturn fail(errors.New(\"crypto\/tls: private key type does not match public key type\"))\n\n\t\t}\n\t\tif pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 {\n\t\t\treturn fail(errors.New(\"crypto\/tls: private key does not match public key\"))\n\t\t}\n\tdefault:\n\t\treturn fail(errors.New(\"crypto\/tls: unknown public key algorithm\"))\n\t}\n\n\treturn cert, nil\n}\n\n\/\/ Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates\n\/\/ PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.\n\/\/ OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.\nfunc parsePrivateKey(der []byte) (crypto.PrivateKey, error) {\n\tif key, err := x509.ParsePKCS1PrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\tif key, err := x509.ParsePKCS8PrivateKey(der); err == nil {\n\t\tswitch key := key.(type) {\n\t\tcase *rsa.PrivateKey, *ecdsa.PrivateKey:\n\t\t\treturn key, nil\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"crypto\/tls: found unknown private key type in PKCS#8 wrapping\")\n\t\t}\n\t}\n\tif key, err := x509.ParseECPrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\n\treturn nil, errors.New(\"crypto\/tls: failed to parse private key\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package restserver\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"encoding\/hex\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestJoin(t *testing.T) {\n\tvar tests = []struct {\n\t\tbase, name string\n\t\tresult     string\n\t}{\n\t\t{\"\/\", \"foo\/bar\", \"\/foo\/bar\"},\n\t\t{\"\/srv\/server\", \"foo\/bar\", \"\/srv\/server\/foo\/bar\"},\n\t\t{\"\/srv\/server\", \"\/foo\/bar\", \"\/srv\/server\/foo\/bar\"},\n\t\t{\"\/srv\/server\", \"foo\/..\/bar\", \"\/srv\/server\/bar\"},\n\t\t{\"\/srv\/server\", \"..\/bar\", \"\/srv\/server\/bar\"},\n\t\t{\"\/srv\/server\", \"..\", \"\/srv\/server\"},\n\t\t{\"\/srv\/server\", \"..\/..\", \"\/srv\/server\"},\n\t\t{\"\/srv\/server\", \"\/repo\/data\/\", \"\/srv\/server\/repo\/data\"},\n\t\t{\"\/srv\/server\", \"\/repo\/data\/..\/..\", \"\/srv\/server\"},\n\t\t{\"\/srv\/server\", \"\/repo\/data\/..\/data\/..\/..\/..\", \"\/srv\/server\"},\n\t\t{\"\/srv\/server\", \"\/repo\/data\/..\/data\/..\/..\/..\", \"\/srv\/server\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(\"\", func(t *testing.T) {\n\t\t\tgot, err := join(filepath.FromSlash(test.base), test.name)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\twant := filepath.FromSlash(test.result)\n\t\t\tif got != want {\n\t\t\t\tt.Fatalf(\"wrong result returned, want %v, got %v\", want, got)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIsUserPath(t *testing.T) {\n\tvar tests = []struct {\n\t\tusername string\n\t\tpath     string\n\t\tresult   bool\n\t}{\n\t\t{\"foo\", \"\/\", false},\n\t\t{\"foo\", \"\/foo\", true},\n\t\t{\"foo\", \"\/foo\/\", true},\n\t\t{\"foo\", \"\/foo\/bar\", true},\n\t\t{\"foo\", \"\/foobar\", false},\n\t}\n\n\tfor _, test := range tests {\n\t\tresult := isUserPath(test.username, test.path)\n\t\tif result != test.result {\n\t\t\tt.Errorf(\"isUserPath(%q, %q) was incorrect, got: %v, want: %v.\", test.username, test.path, result, test.result)\n\t\t}\n\t}\n}\n\n\/\/ declare a few helper functions\n\n\/\/ wantFunc tests the HTTP response in res and calls t.Error() if something is incorrect.\ntype wantFunc func(t testing.TB, res *httptest.ResponseRecorder)\n\n\/\/ newRequest returns a new HTTP request with the given params. On error, t.Fatal is called.\nfunc newRequest(t testing.TB, method, path string, body io.Reader) *http.Request {\n\treq, err := http.NewRequest(method, path, body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn req\n}\n\n\/\/ wantCode returns a function which checks that the response has the correct HTTP status code.\nfunc wantCode(code int) wantFunc {\n\treturn func(t testing.TB, res *httptest.ResponseRecorder) {\n\t\tif res.Code != code {\n\t\t\tt.Errorf(\"wrong response code, want %v, got %v\", code, res.Code)\n\t\t}\n\t}\n}\n\n\/\/ wantBody returns a function which checks that the response has the data in the body.\nfunc wantBody(body string) wantFunc {\n\treturn func(t testing.TB, res *httptest.ResponseRecorder) {\n\t\tif res.Body == nil {\n\t\t\tt.Errorf(\"body is nil, want %q\", body)\n\t\t\treturn\n\t\t}\n\n\t\tif !bytes.Equal(res.Body.Bytes(), []byte(body)) {\n\t\t\tt.Errorf(\"wrong response body, want:\\n  %q\\ngot:\\n  %q\", body, res.Body.Bytes())\n\t\t}\n\t}\n}\n\n\/\/ checkRequest uses f to process the request and runs the checker functions on the result.\nfunc checkRequest(t testing.TB, f http.HandlerFunc, req *http.Request, want []wantFunc) {\n\trr := httptest.NewRecorder()\n\tf(rr, req)\n\n\tfor _, fn := range want {\n\t\tfn(t, rr)\n\t}\n}\n\n\/\/ TestRequest is a sequence of HTTP requests with (optional) tests for the response.\ntype TestRequest struct {\n\treq  *http.Request\n\twant []wantFunc\n}\n\n\/\/ createOverwriteDeleteSeq returns a sequence which will create a new file at\n\/\/ path, and then try to overwrite and delete it.\nfunc createOverwriteDeleteSeq(t testing.TB, path string) []TestRequest {\n\t\/\/ add a file, try to overwrite and delete it\n\treq := []TestRequest{\n\t\t{\n\t\t\treq:  newRequest(t, \"GET\", path, nil),\n\t\t\twant: []wantFunc{wantCode(http.StatusNotFound)},\n\t\t},\n\t\t{\n\t\t\treq:  newRequest(t, \"POST\", path, strings.NewReader(\"foobar test config\")),\n\t\t\twant: []wantFunc{wantCode(http.StatusOK)},\n\t\t},\n\t\t{\n\t\t\treq: newRequest(t, \"GET\", path, nil),\n\t\t\twant: []wantFunc{\n\t\t\t\twantCode(http.StatusOK),\n\t\t\t\twantBody(\"foobar test config\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\treq:  newRequest(t, \"POST\", path, strings.NewReader(\"other config\")),\n\t\t\twant: []wantFunc{wantCode(http.StatusForbidden)},\n\t\t},\n\t\t{\n\t\t\treq: newRequest(t, \"GET\", path, nil),\n\t\t\twant: []wantFunc{\n\t\t\t\twantCode(http.StatusOK),\n\t\t\t\twantBody(\"foobar test config\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\treq:  newRequest(t, \"DELETE\", path, nil),\n\t\t\twant: []wantFunc{wantCode(http.StatusForbidden)},\n\t\t},\n\t\t{\n\t\t\treq: newRequest(t, \"GET\", path, nil),\n\t\t\twant: []wantFunc{\n\t\t\t\twantCode(http.StatusOK),\n\t\t\t\twantBody(\"foobar test config\"),\n\t\t\t},\n\t\t},\n\t}\n\treturn req\n}\n\n\/\/ TestResticHandler runs tests on the restic handler code, especially in append-only mode.\nfunc TestResticHandler(t *testing.T) {\n\tbuf := make([]byte, 32)\n\t_, err := io.ReadFull(rand.Reader, buf)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\trandomID := hex.EncodeToString(buf)\n\n\tvar tests = []struct {\n\t\tseq []TestRequest\n\t}{\n\t\t{createOverwriteDeleteSeq(t, \"\/config\")},\n\t\t{createOverwriteDeleteSeq(t, \"\/data\/\"+randomID)},\n\t\t{\n\t\t\t\/\/ ensure we can add and remove lock files\n\t\t\t[]TestRequest{\n\t\t\t\t{\n\t\t\t\t\treq:  newRequest(t, \"GET\", \"\/locks\/\"+randomID, nil),\n\t\t\t\t\twant: []wantFunc{wantCode(http.StatusNotFound)},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\treq:  newRequest(t, \"POST\", \"\/locks\/\"+randomID, strings.NewReader(\"lock file\")),\n\t\t\t\t\twant: []wantFunc{wantCode(http.StatusOK)},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\treq: newRequest(t, \"GET\", \"\/locks\/\"+randomID, nil),\n\t\t\t\t\twant: []wantFunc{\n\t\t\t\t\t\twantCode(http.StatusOK),\n\t\t\t\t\t\twantBody(\"lock file\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\treq:  newRequest(t, \"POST\", \"\/locks\/\"+randomID, strings.NewReader(\"other lock file\")),\n\t\t\t\t\twant: []wantFunc{wantCode(http.StatusForbidden)},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\treq:  newRequest(t, \"DELETE\", \"\/locks\/\"+randomID, nil),\n\t\t\t\t\twant: []wantFunc{wantCode(http.StatusOK)},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\treq:  newRequest(t, \"GET\", \"\/locks\/\"+randomID, nil),\n\t\t\t\t\twant: []wantFunc{wantCode(http.StatusNotFound)},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t\/\/ setup rclone with a local backend in a temporary directory\n\ttempdir, err := ioutil.TempDir(\"\", \"rclone-restic-test-\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ make sure the tempdir is properly removed\n\tdefer func() {\n\t\terr := os.RemoveAll(tempdir)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\t\/\/ set append-only mode and configure path\n\tmux := NewHandler(Server{\n\t\tAppendOnly: true,\n\t\tPath:       tempdir,\n\t})\n\n\t\/\/ create the repo\n\tcheckRequest(t, mux.ServeHTTP,\n\t\tnewRequest(t, \"POST\", \"\/?create=true\", nil),\n\t\t[]wantFunc{wantCode(http.StatusOK)})\n\n\tfor _, test := range tests {\n\t\tt.Run(\"\", func(t *testing.T) {\n\t\t\tfor i, seq := range test.seq {\n\t\t\t\tt.Logf(\"request %v: %v %v\", i, seq.req.Method, seq.req.URL.Path)\n\t\t\t\tcheckRequest(t, mux.ServeHTTP, seq.req, seq.want)\n\t\t\t}\n\t\t})\n\t}\n}\n<commit_msg>Fix tests<commit_after>package restserver\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"encoding\/hex\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestJoin(t *testing.T) {\n\tvar tests = []struct {\n\t\tbase   string\n\t\tnames  []string\n\t\tresult string\n\t}{\n\t\t{\"\/\", []string{\"foo\", \"bar\"}, \"\/foo\/bar\"},\n\t\t{\"\/srv\/server\", []string{\"foo\", \"bar\"}, \"\/srv\/server\/foo\/bar\"},\n\t\t{\"\/srv\/server\", []string{\"foo\", \"..\", \"bar\"}, \"\/srv\/server\/foo\/bar\"},\n\t\t{\"\/srv\/server\", []string{\"..\", \"bar\"}, \"\/srv\/server\/bar\"},\n\t\t{\"\/srv\/server\", []string{\"..\"}, \"\/srv\/server\"},\n\t\t{\"\/srv\/server\", []string{\"..\", \"..\"}, \"\/srv\/server\"},\n\t\t{\"\/srv\/server\", []string{\"repo\", \"data\"}, \"\/srv\/server\/repo\/data\"},\n\t\t{\"\/srv\/server\", []string{\"repo\", \"data\", \"..\", \"..\"}, \"\/srv\/server\/repo\/data\"},\n\t\t{\"\/srv\/server\", []string{\"repo\", \"data\", \"..\", \"data\", \"..\", \"..\", \"..\"}, \"\/srv\/server\/repo\/data\/data\"},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(\"\", func(t *testing.T) {\n\t\t\tgot, err := join(filepath.FromSlash(test.base), test.names...)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\twant := filepath.FromSlash(test.result)\n\t\t\tif got != want {\n\t\t\t\tt.Fatalf(\"wrong result returned, want %v, got %v\", want, got)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestIsUserPath(t *testing.T) {\n\tvar tests = []struct {\n\t\tusername string\n\t\tpath     string\n\t\tresult   bool\n\t}{\n\t\t{\"foo\", \"\/\", false},\n\t\t{\"foo\", \"\/foo\", true},\n\t\t{\"foo\", \"\/foo\/\", true},\n\t\t{\"foo\", \"\/foo\/bar\", true},\n\t\t{\"foo\", \"\/foobar\", false},\n\t}\n\n\tfor _, test := range tests {\n\t\tresult := isUserPath(test.username, test.path)\n\t\tif result != test.result {\n\t\t\tt.Errorf(\"isUserPath(%q, %q) was incorrect, got: %v, want: %v.\", test.username, test.path, result, test.result)\n\t\t}\n\t}\n}\n\n\/\/ declare a few helper functions\n\n\/\/ wantFunc tests the HTTP response in res and calls t.Error() if something is incorrect.\ntype wantFunc func(t testing.TB, res *httptest.ResponseRecorder)\n\n\/\/ newRequest returns a new HTTP request with the given params. On error, t.Fatal is called.\nfunc newRequest(t testing.TB, method, path string, body io.Reader) *http.Request {\n\treq, err := http.NewRequest(method, path, body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn req\n}\n\n\/\/ wantCode returns a function which checks that the response has the correct HTTP status code.\nfunc wantCode(code int) wantFunc {\n\treturn func(t testing.TB, res *httptest.ResponseRecorder) {\n\t\tif res.Code != code {\n\t\t\tt.Errorf(\"wrong response code, want %v, got %v\", code, res.Code)\n\t\t}\n\t}\n}\n\n\/\/ wantBody returns a function which checks that the response has the data in the body.\nfunc wantBody(body string) wantFunc {\n\treturn func(t testing.TB, res *httptest.ResponseRecorder) {\n\t\tif res.Body == nil {\n\t\t\tt.Errorf(\"body is nil, want %q\", body)\n\t\t\treturn\n\t\t}\n\n\t\tif !bytes.Equal(res.Body.Bytes(), []byte(body)) {\n\t\t\tt.Errorf(\"wrong response body, want:\\n  %q\\ngot:\\n  %q\", body, res.Body.Bytes())\n\t\t}\n\t}\n}\n\n\/\/ checkRequest uses f to process the request and runs the checker functions on the result.\nfunc checkRequest(t testing.TB, f http.HandlerFunc, req *http.Request, want []wantFunc) {\n\trr := httptest.NewRecorder()\n\tf(rr, req)\n\n\tfor _, fn := range want {\n\t\tfn(t, rr)\n\t}\n}\n\n\/\/ TestRequest is a sequence of HTTP requests with (optional) tests for the response.\ntype TestRequest struct {\n\treq  *http.Request\n\twant []wantFunc\n}\n\n\/\/ createOverwriteDeleteSeq returns a sequence which will create a new file at\n\/\/ path, and then try to overwrite and delete it.\nfunc createOverwriteDeleteSeq(t testing.TB, path string) []TestRequest {\n\t\/\/ add a file, try to overwrite and delete it\n\treq := []TestRequest{\n\t\t{\n\t\t\treq:  newRequest(t, \"GET\", path, nil),\n\t\t\twant: []wantFunc{wantCode(http.StatusNotFound)},\n\t\t},\n\t\t{\n\t\t\treq:  newRequest(t, \"POST\", path, strings.NewReader(\"foobar test config\")),\n\t\t\twant: []wantFunc{wantCode(http.StatusOK)},\n\t\t},\n\t\t{\n\t\t\treq: newRequest(t, \"GET\", path, nil),\n\t\t\twant: []wantFunc{\n\t\t\t\twantCode(http.StatusOK),\n\t\t\t\twantBody(\"foobar test config\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\treq:  newRequest(t, \"POST\", path, strings.NewReader(\"other config\")),\n\t\t\twant: []wantFunc{wantCode(http.StatusForbidden)},\n\t\t},\n\t\t{\n\t\t\treq: newRequest(t, \"GET\", path, nil),\n\t\t\twant: []wantFunc{\n\t\t\t\twantCode(http.StatusOK),\n\t\t\t\twantBody(\"foobar test config\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\treq:  newRequest(t, \"DELETE\", path, nil),\n\t\t\twant: []wantFunc{wantCode(http.StatusForbidden)},\n\t\t},\n\t\t{\n\t\t\treq: newRequest(t, \"GET\", path, nil),\n\t\t\twant: []wantFunc{\n\t\t\t\twantCode(http.StatusOK),\n\t\t\t\twantBody(\"foobar test config\"),\n\t\t\t},\n\t\t},\n\t}\n\treturn req\n}\n\n\/\/ TestResticHandler runs tests on the restic handler code, especially in append-only mode.\nfunc TestResticHandler(t *testing.T) {\n\tbuf := make([]byte, 32)\n\t_, err := io.ReadFull(rand.Reader, buf)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\trandomID := hex.EncodeToString(buf)\n\n\tvar tests = []struct {\n\t\tseq []TestRequest\n\t}{\n\t\t{createOverwriteDeleteSeq(t, \"\/config\")},\n\t\t{createOverwriteDeleteSeq(t, \"\/data\/\"+randomID)},\n\t\t{\n\t\t\t\/\/ ensure we can add and remove lock files\n\t\t\t[]TestRequest{\n\t\t\t\t{\n\t\t\t\t\treq:  newRequest(t, \"GET\", \"\/locks\/\"+randomID, nil),\n\t\t\t\t\twant: []wantFunc{wantCode(http.StatusNotFound)},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\treq:  newRequest(t, \"POST\", \"\/locks\/\"+randomID, strings.NewReader(\"lock file\")),\n\t\t\t\t\twant: []wantFunc{wantCode(http.StatusOK)},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\treq: newRequest(t, \"GET\", \"\/locks\/\"+randomID, nil),\n\t\t\t\t\twant: []wantFunc{\n\t\t\t\t\t\twantCode(http.StatusOK),\n\t\t\t\t\t\twantBody(\"lock file\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\treq:  newRequest(t, \"POST\", \"\/locks\/\"+randomID, strings.NewReader(\"other lock file\")),\n\t\t\t\t\twant: []wantFunc{wantCode(http.StatusForbidden)},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\treq:  newRequest(t, \"DELETE\", \"\/locks\/\"+randomID, nil),\n\t\t\t\t\twant: []wantFunc{wantCode(http.StatusOK)},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\treq:  newRequest(t, \"GET\", \"\/locks\/\"+randomID, nil),\n\t\t\t\t\twant: []wantFunc{wantCode(http.StatusNotFound)},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t\/\/ setup rclone with a local backend in a temporary directory\n\ttempdir, err := ioutil.TempDir(\"\", \"rclone-restic-test-\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ make sure the tempdir is properly removed\n\tdefer func() {\n\t\terr := os.RemoveAll(tempdir)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}()\n\n\t\/\/ set append-only mode and configure path\n\tmux := NewHandler(Server{\n\t\tAppendOnly: true,\n\t\tPath:       tempdir,\n\t})\n\n\t\/\/ create the repo\n\tcheckRequest(t, mux.ServeHTTP,\n\t\tnewRequest(t, \"POST\", \"\/?create=true\", nil),\n\t\t[]wantFunc{wantCode(http.StatusOK)})\n\n\tfor _, test := range tests {\n\t\tt.Run(\"\", func(t *testing.T) {\n\t\t\tfor i, seq := range test.seq {\n\t\t\t\tt.Logf(\"request %v: %v %v\", i, seq.req.Method, seq.req.URL.Path)\n\t\t\t\tcheckRequest(t, mux.ServeHTTP, seq.req, seq.want)\n\t\t\t}\n\t\t})\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package dbr\n\nimport (\n\t\"reflect\"\n\t\"time\"\n)\n\n\/\/ Unvetted thots:\n\/\/ Given a query and given a structure (field list), there's 2 sets of fields.\n\/\/ Take the intersection. We can fill those in. great.\n\/\/ For fields in the structure that aren't in the query, we'll let that slide if db:\"-\"\n\/\/ For fields in the structure that aren't in the query but without db:\"-\", return error\n\/\/ For fields in the query that aren't in the structure, we'll ignore them.\n\n\/\/ dest can be:\n\/\/ - addr of a structure\n\/\/ - addr of slice of pointers to structures\n\/\/ If it's a single structure, only the first record returned will be set.\n\/\/ If it's a slice it won't be emptied first. New records will be allocated for each found record.\n\/\/ Returns the number of items found (which is not necessarily the # of items set)\nfunc (b *SelectBuilder) LoadAll(dest interface{}) (int, error) {\n\t\/\/\n\t\/\/ Validate the dest, and extract the reflection values we need.\n\t\/\/\n\n\t\/\/ This must be a pointer to a slice\n\tvalueOfDest := reflect.ValueOf(dest)\n\tkindOfDest := valueOfDest.Kind()\n\n\tif kindOfDest != reflect.Ptr {\n\t\tpanic(\"invalid type passed to LoadAll. Need a pointer to a slice\")\n\t}\n\n\t\/\/ This must a slice\n\tvalueOfDest = reflect.Indirect(valueOfDest)\n\tkindOfDest = valueOfDest.Kind()\n\n\tif kindOfDest != reflect.Slice {\n\t\tpanic(\"invalid type passed to LoadAll. Need a pointer to a slice\")\n\t}\n\n\t\/\/ The slice elements must be pointers to structures\n\trecordType := valueOfDest.Type().Elem()\n\tif recordType.Kind() != reflect.Ptr {\n\t\tpanic(\"Elements need to be pointers to structures\")\n\t}\n\n\trecordType = recordType.Elem()\n\tif recordType.Kind() != reflect.Struct {\n\t\tpanic(\"Elements need to be pointers to structures\")\n\t}\n\n\t\/\/\n\t\/\/ Get full SQL\n\t\/\/\n\tfullSql, err := Interpolate(b.ToSql())\n\tif err != nil {\n\t\treturn 0, b.EventErr(\"dbr.select.load_all.interpolate\", err)\n\t}\n\n\tnumberOfRowsReturned := 0\n\n\t\/\/ Start the timer:\n\tstartTime := time.Now()\n\tdefer func() { b.TimingKv(\"dbr.select\", time.Since(startTime).Nanoseconds(), kvs{\"sql\": fullSql}) }()\n\n\t\/\/ Run the query:\n\trows, err := b.runner.Query(fullSql)\n\tif err != nil {\n\t\treturn 0, b.EventErrKv(\"dbr.select.load_all.query\", err, kvs{\"sql\": fullSql})\n\t}\n\tdefer rows.Close()\n\n\t\/\/ Get the columns returned\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn numberOfRowsReturned, b.EventErrKv(\"dbr.select.load_one.rows.Columns\", err, kvs{\"sql\": fullSql})\n\t}\n\n\t\/\/ Create a map of this result set to the struct fields\n\tfieldMap, err := b.calculateFieldMap(recordType, columns, false)\n\tif err != nil {\n\t\treturn numberOfRowsReturned, b.EventErrKv(\"dbr.select.load_all.calculateFieldMap\", err, kvs{\"sql\": fullSql})\n\t}\n\n\t\/\/ Iterate over rows\n\tsliceValue := valueOfDest\n\tfor rows.Next() {\n\t\t\/\/ Create a new record to store our row:\n\t\tpointerToNewRecord := reflect.New(recordType)\n\t\tnewRecord := reflect.Indirect(pointerToNewRecord)\n\n\t\t\/\/ Build a 'holder', which is an []interface{}. Each value will be the address of the field corresponding to our newly made record:\n\t\tholder, err := b.holderFor(newRecord, fieldMap)\n\t\tif err != nil {\n\t\t\treturn numberOfRowsReturned, b.EventErrKv(\"dbr.select.load_all.holderFor\", err, kvs{\"sql\": fullSql})\n\t\t}\n\n\t\t\/\/ Load up our new structure with the row's values\n\t\terr = rows.Scan(holder...)\n\t\tif err != nil {\n\t\t\treturn numberOfRowsReturned, b.EventErrKv(\"dbr.select.load_all.scan\", err, kvs{\"sql\": fullSql})\n\t\t}\n\n\t\t\/\/ Append our new record to the slice:\n\t\tsliceValue = reflect.Append(sliceValue, pointerToNewRecord)\n\n\t\tnumberOfRowsReturned += 1\n\t}\n\tvalueOfDest.Set(sliceValue)\n\n\t\/\/ Check for errors at the end. Supposedly these are error that can happen during iteration.\n\tif err = rows.Err(); err != nil {\n\t\treturn numberOfRowsReturned, b.EventErrKv(\"dbr.select.load_all.rows_err\", err, kvs{\"sql\": fullSql})\n\t}\n\n\treturn numberOfRowsReturned, nil\n}\n\n\/\/ Returns ErrNotFound if nothing was found\nfunc (b *SelectBuilder) LoadOne(dest interface{}) error {\n\t\/\/\n\t\/\/ Validate the dest, and extract the reflection values we need.\n\t\/\/\n\tvalueOfDest := reflect.ValueOf(dest)\n\tindirectOfDest := reflect.Indirect(valueOfDest)\n\tkindOfDest := valueOfDest.Kind()\n\n\tif kindOfDest != reflect.Ptr || indirectOfDest.Kind() != reflect.Struct {\n\t\tpanic(\"you need to pass in the address of a struct\")\n\t}\n\n\trecordType := indirectOfDest.Type()\n\n\t\/\/\n\t\/\/ Get full SQL\n\t\/\/\n\tfullSql, err := Interpolate(b.ToSql())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Start the timer:\n\tstartTime := time.Now()\n\tdefer func() { b.TimingKv(\"dbr.select\", time.Since(startTime).Nanoseconds(), kvs{\"sql\": fullSql}) }()\n\n\t\/\/ Run the query:\n\trows, err := b.runner.Query(fullSql)\n\tif err != nil {\n\t\treturn b.EventErrKv(\"dbr.select.load_one.query\", err, kvs{\"sql\": fullSql})\n\t}\n\tdefer rows.Close()\n\n\t\/\/ Get the columns of this result set\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn b.EventErrKv(\"dbr.select.load_one.rows.Columns\", err, kvs{\"sql\": fullSql})\n\t}\n\n\t\/\/ Create a map of this result set to the struct columns\n\tfieldMap, err := b.calculateFieldMap(recordType, columns, false)\n\tif err != nil {\n\t\treturn b.EventErrKv(\"dbr.select.load_one.calculateFieldMap\", err, kvs{\"sql\": fullSql})\n\t}\n\n\tif rows.Next() {\n\t\t\/\/ Build a 'holder', which is an []interface{}. Each value will be the address of the field corresponding to our newly made record:\n\t\tholder, err := b.holderFor(indirectOfDest, fieldMap)\n\t\tif err != nil {\n\t\t\treturn b.EventErrKv(\"dbr.select.load_one.holderFor\", err, kvs{\"sql\": fullSql})\n\t\t}\n\n\t\t\/\/ Load up our new structure with the row's values\n\t\terr = rows.Scan(holder...)\n\t\tif err != nil {\n\t\t\treturn b.EventErrKv(\"dbr.select.load_one.scan\", err, kvs{\"sql\": fullSql})\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn b.EventErrKv(\"dbr.select.load_one.rows_err\", err, kvs{\"sql\": fullSql})\n\t}\n\n\treturn ErrNotFound\n}\n\n\/\/ Returns ErrNotFound if no value was found, and it was therefore not set.\nfunc (b *SelectBuilder) LoadValue(dest interface{}) error {\n\t\/\/ Validate the dest\n\tvalueOfDest := reflect.ValueOf(dest)\n\tkindOfDest := valueOfDest.Kind()\n\n\tif kindOfDest != reflect.Ptr {\n\t\tpanic(\"Destination must be a pointer\")\n\t}\n\n\t\/\/\n\t\/\/ Get full SQL\n\t\/\/\n\tfullSql, err := Interpolate(b.ToSql())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Start the timer:\n\tstartTime := time.Now()\n\tdefer func() { b.TimingKv(\"dbr.select\", time.Since(startTime).Nanoseconds(), kvs{\"sql\": fullSql}) }()\n\n\t\/\/ Run the query:\n\trows, err := b.runner.Query(fullSql)\n\tif err != nil {\n\t\treturn b.EventErrKv(\"dbr.select.load_value.query\", err, kvs{\"sql\": fullSql})\n\t}\n\tdefer rows.Close()\n\n\tif rows.Next() {\n\t\terr = rows.Scan(dest)\n\t\tif err != nil {\n\t\t\treturn b.EventErrKv(\"dbr.select.load_value.scan\", err, kvs{\"sql\": fullSql})\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn b.EventErrKv(\"dbr.select.load_value.rows_err\", err, kvs{\"sql\": fullSql})\n\t}\n\n\treturn ErrNotFound\n}\n<commit_msg>CLEANUP: Fix out of date comment because it was wrong.<commit_after>package dbr\n\nimport (\n\t\"reflect\"\n\t\"time\"\n)\n\n\/\/ Unvetted thots:\n\/\/ Given a query and given a structure (field list), there's 2 sets of fields.\n\/\/ Take the intersection. We can fill those in. great.\n\/\/ For fields in the structure that aren't in the query, we'll let that slide if db:\"-\"\n\/\/ For fields in the structure that aren't in the query but without db:\"-\", return error\n\/\/ For fields in the query that aren't in the structure, we'll ignore them.\n\n\/\/ dest must be a pointer to a slice of pointers to structs\n\/\/ Returns the number of items found (which is not necessarily the # of items set)\nfunc (b *SelectBuilder) LoadAll(dest interface{}) (int, error) {\n\t\/\/\n\t\/\/ Validate the dest, and extract the reflection values we need.\n\t\/\/\n\n\t\/\/ This must be a pointer to a slice\n\tvalueOfDest := reflect.ValueOf(dest)\n\tkindOfDest := valueOfDest.Kind()\n\n\tif kindOfDest != reflect.Ptr {\n\t\tpanic(\"invalid type passed to LoadAll. Need a pointer to a slice\")\n\t}\n\n\t\/\/ This must a slice\n\tvalueOfDest = reflect.Indirect(valueOfDest)\n\tkindOfDest = valueOfDest.Kind()\n\n\tif kindOfDest != reflect.Slice {\n\t\tpanic(\"invalid type passed to LoadAll. Need a pointer to a slice\")\n\t}\n\n\t\/\/ The slice elements must be pointers to structures\n\trecordType := valueOfDest.Type().Elem()\n\tif recordType.Kind() != reflect.Ptr {\n\t\tpanic(\"Elements need to be pointers to structures\")\n\t}\n\n\trecordType = recordType.Elem()\n\tif recordType.Kind() != reflect.Struct {\n\t\tpanic(\"Elements need to be pointers to structures\")\n\t}\n\n\t\/\/\n\t\/\/ Get full SQL\n\t\/\/\n\tfullSql, err := Interpolate(b.ToSql())\n\tif err != nil {\n\t\treturn 0, b.EventErr(\"dbr.select.load_all.interpolate\", err)\n\t}\n\n\tnumberOfRowsReturned := 0\n\n\t\/\/ Start the timer:\n\tstartTime := time.Now()\n\tdefer func() { b.TimingKv(\"dbr.select\", time.Since(startTime).Nanoseconds(), kvs{\"sql\": fullSql}) }()\n\n\t\/\/ Run the query:\n\trows, err := b.runner.Query(fullSql)\n\tif err != nil {\n\t\treturn 0, b.EventErrKv(\"dbr.select.load_all.query\", err, kvs{\"sql\": fullSql})\n\t}\n\tdefer rows.Close()\n\n\t\/\/ Get the columns returned\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn numberOfRowsReturned, b.EventErrKv(\"dbr.select.load_one.rows.Columns\", err, kvs{\"sql\": fullSql})\n\t}\n\n\t\/\/ Create a map of this result set to the struct fields\n\tfieldMap, err := b.calculateFieldMap(recordType, columns, false)\n\tif err != nil {\n\t\treturn numberOfRowsReturned, b.EventErrKv(\"dbr.select.load_all.calculateFieldMap\", err, kvs{\"sql\": fullSql})\n\t}\n\n\t\/\/ Iterate over rows\n\tsliceValue := valueOfDest\n\tfor rows.Next() {\n\t\t\/\/ Create a new record to store our row:\n\t\tpointerToNewRecord := reflect.New(recordType)\n\t\tnewRecord := reflect.Indirect(pointerToNewRecord)\n\n\t\t\/\/ Build a 'holder', which is an []interface{}. Each value will be the address of the field corresponding to our newly made record:\n\t\tholder, err := b.holderFor(newRecord, fieldMap)\n\t\tif err != nil {\n\t\t\treturn numberOfRowsReturned, b.EventErrKv(\"dbr.select.load_all.holderFor\", err, kvs{\"sql\": fullSql})\n\t\t}\n\n\t\t\/\/ Load up our new structure with the row's values\n\t\terr = rows.Scan(holder...)\n\t\tif err != nil {\n\t\t\treturn numberOfRowsReturned, b.EventErrKv(\"dbr.select.load_all.scan\", err, kvs{\"sql\": fullSql})\n\t\t}\n\n\t\t\/\/ Append our new record to the slice:\n\t\tsliceValue = reflect.Append(sliceValue, pointerToNewRecord)\n\n\t\tnumberOfRowsReturned += 1\n\t}\n\tvalueOfDest.Set(sliceValue)\n\n\t\/\/ Check for errors at the end. Supposedly these are error that can happen during iteration.\n\tif err = rows.Err(); err != nil {\n\t\treturn numberOfRowsReturned, b.EventErrKv(\"dbr.select.load_all.rows_err\", err, kvs{\"sql\": fullSql})\n\t}\n\n\treturn numberOfRowsReturned, nil\n}\n\n\/\/ Returns ErrNotFound if nothing was found\nfunc (b *SelectBuilder) LoadOne(dest interface{}) error {\n\t\/\/\n\t\/\/ Validate the dest, and extract the reflection values we need.\n\t\/\/\n\tvalueOfDest := reflect.ValueOf(dest)\n\tindirectOfDest := reflect.Indirect(valueOfDest)\n\tkindOfDest := valueOfDest.Kind()\n\n\tif kindOfDest != reflect.Ptr || indirectOfDest.Kind() != reflect.Struct {\n\t\tpanic(\"you need to pass in the address of a struct\")\n\t}\n\n\trecordType := indirectOfDest.Type()\n\n\t\/\/\n\t\/\/ Get full SQL\n\t\/\/\n\tfullSql, err := Interpolate(b.ToSql())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Start the timer:\n\tstartTime := time.Now()\n\tdefer func() { b.TimingKv(\"dbr.select\", time.Since(startTime).Nanoseconds(), kvs{\"sql\": fullSql}) }()\n\n\t\/\/ Run the query:\n\trows, err := b.runner.Query(fullSql)\n\tif err != nil {\n\t\treturn b.EventErrKv(\"dbr.select.load_one.query\", err, kvs{\"sql\": fullSql})\n\t}\n\tdefer rows.Close()\n\n\t\/\/ Get the columns of this result set\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn b.EventErrKv(\"dbr.select.load_one.rows.Columns\", err, kvs{\"sql\": fullSql})\n\t}\n\n\t\/\/ Create a map of this result set to the struct columns\n\tfieldMap, err := b.calculateFieldMap(recordType, columns, false)\n\tif err != nil {\n\t\treturn b.EventErrKv(\"dbr.select.load_one.calculateFieldMap\", err, kvs{\"sql\": fullSql})\n\t}\n\n\tif rows.Next() {\n\t\t\/\/ Build a 'holder', which is an []interface{}. Each value will be the address of the field corresponding to our newly made record:\n\t\tholder, err := b.holderFor(indirectOfDest, fieldMap)\n\t\tif err != nil {\n\t\t\treturn b.EventErrKv(\"dbr.select.load_one.holderFor\", err, kvs{\"sql\": fullSql})\n\t\t}\n\n\t\t\/\/ Load up our new structure with the row's values\n\t\terr = rows.Scan(holder...)\n\t\tif err != nil {\n\t\t\treturn b.EventErrKv(\"dbr.select.load_one.scan\", err, kvs{\"sql\": fullSql})\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn b.EventErrKv(\"dbr.select.load_one.rows_err\", err, kvs{\"sql\": fullSql})\n\t}\n\n\treturn ErrNotFound\n}\n\n\/\/ Returns ErrNotFound if no value was found, and it was therefore not set.\nfunc (b *SelectBuilder) LoadValue(dest interface{}) error {\n\t\/\/ Validate the dest\n\tvalueOfDest := reflect.ValueOf(dest)\n\tkindOfDest := valueOfDest.Kind()\n\n\tif kindOfDest != reflect.Ptr {\n\t\tpanic(\"Destination must be a pointer\")\n\t}\n\n\t\/\/\n\t\/\/ Get full SQL\n\t\/\/\n\tfullSql, err := Interpolate(b.ToSql())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Start the timer:\n\tstartTime := time.Now()\n\tdefer func() { b.TimingKv(\"dbr.select\", time.Since(startTime).Nanoseconds(), kvs{\"sql\": fullSql}) }()\n\n\t\/\/ Run the query:\n\trows, err := b.runner.Query(fullSql)\n\tif err != nil {\n\t\treturn b.EventErrKv(\"dbr.select.load_value.query\", err, kvs{\"sql\": fullSql})\n\t}\n\tdefer rows.Close()\n\n\tif rows.Next() {\n\t\terr = rows.Scan(dest)\n\t\tif err != nil {\n\t\t\treturn b.EventErrKv(\"dbr.select.load_value.scan\", err, kvs{\"sql\": fullSql})\n\t\t}\n\t\treturn nil\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn b.EventErrKv(\"dbr.select.load_value.rows_err\", err, kvs{\"sql\": fullSql})\n\t}\n\n\treturn ErrNotFound\n}\n<|endoftext|>"}
{"text":"<commit_before>package hawser\n\nimport (\n\t\"fmt\"\n\t\"github.com\/hawser\/git-hawser\/git\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype Configuration struct {\n\tCurrentRemote         string\n\tgitConfig             map[string]string\n\tremotes               []string\n\thttpClient            *http.Client\n\tredirectingHttpClient *http.Client\n\tisTracingHttp         bool\n}\n\nvar (\n\tConfig        = NewConfig()\n\tRedirectError = fmt.Errorf(\"Unexpected redirection\")\n\thttpPrefixRe  = regexp.MustCompile(\"\\\\Ahttps?:\/\/\")\n\tdefaultRemote = \"origin\"\n)\n\nfunc NewConfig() *Configuration {\n\tc := &Configuration{\n\t\tCurrentRemote: defaultRemote,\n\t\tisTracingHttp: len(os.Getenv(\"GIT_CURL_VERBOSE\")) > 0,\n\t}\n\treturn c\n}\n\nfunc (c *Configuration) Endpoint() string {\n\tif url, ok := c.GitConfig(\"hawser.url\"); ok {\n\t\treturn url\n\t}\n\n\tif len(c.CurrentRemote) > 0 && c.CurrentRemote != defaultRemote {\n\t\tif endpoint := c.RemoteEndpoint(c.CurrentRemote); len(endpoint) > 0 {\n\t\t\treturn endpoint\n\t\t}\n\t}\n\n\treturn c.RemoteEndpoint(defaultRemote)\n}\n\nfunc (c *Configuration) RemoteEndpoint(remote string) string {\n\tif len(remote) == 0 {\n\t\tremote = defaultRemote\n\t}\n\n\tif url, ok := c.GitConfig(\"remote.\" + remote + \".hawser\"); ok {\n\t\treturn url\n\t}\n\n\tif url, ok := c.GitConfig(\"remote.\" + remote + \".url\"); ok {\n\t\tif !httpPrefixRe.MatchString(url) {\n\t\t\tpieces := strings.SplitN(url, \":\", 2)\n\t\t\thostPieces := strings.SplitN(pieces[0], \"@\", 2)\n\t\t\tif len(hostPieces) < 2 {\n\t\t\t\treturn \"unknown\"\n\t\t\t}\n\t\t\turl = fmt.Sprintf(\"https:\/\/%s\/%s\", hostPieces[1], pieces[1])\n\t\t}\n\n\t\tif path.Ext(url) == \".git\" {\n\t\t\treturn url + \"\/info\/media\"\n\t\t}\n\t\treturn url + \".git\/info\/media\"\n\t}\n\n\treturn \"\"\n}\n\nfunc (c *Configuration) Remotes() []string {\n\tc.loadGitConfig()\n\treturn c.remotes\n}\n\nfunc (c *Configuration) GitConfig(key string) (string, bool) {\n\tc.loadGitConfig()\n\tvalue, ok := c.gitConfig[strings.ToLower(key)]\n\treturn value, ok\n}\n\nfunc (c *Configuration) SetConfig(key, value string) {\n\tc.loadGitConfig()\n\tc.gitConfig[key] = value\n}\n\nfunc (c *Configuration) ObjectUrl(oid string) *url.URL {\n\tu, _ := url.Parse(c.Endpoint())\n\tu.Path = path.Join(u.Path, \"objects\", oid)\n\treturn u\n}\n\ntype AltConfig struct {\n\tRemote map[string]*struct {\n\t\tMedia string\n\t}\n\n\tMedia struct {\n\t\tUrl string\n\t}\n}\n\nfunc (c *Configuration) loadGitConfig() {\n\tif c.gitConfig != nil {\n\t\treturn\n\t}\n\n\tuniqRemotes := make(map[string]bool)\n\n\tc.gitConfig = make(map[string]string)\n\n\tvar output string\n\tlistOutput, err := git.Config.List()\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Error listing git config: %s\", err))\n\t}\n\n\tfileOutput, err := git.Config.ListFromFile()\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Error listing git config from file: %s\", err))\n\t}\n\n\toutput = listOutput + \"\\n\" + fileOutput\n\n\tlines := strings.Split(output, \"\\n\")\n\tfor _, line := range lines {\n\t\tpieces := strings.SplitN(line, \"=\", 2)\n\t\tif len(pieces) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tkey := strings.ToLower(pieces[0])\n\t\tc.gitConfig[key] = pieces[1]\n\n\t\tkeyParts := strings.Split(key, \".\")\n\t\tif len(keyParts) > 1 && keyParts[0] == \"remote\" {\n\t\t\tremote := keyParts[1]\n\t\t\tuniqRemotes[remote] = remote == \"origin\"\n\t\t}\n\t}\n\n\tc.remotes = make([]string, 0, len(uniqRemotes))\n\tfor remote, isOrigin := range uniqRemotes {\n\t\tif isOrigin {\n\t\t\tcontinue\n\t\t}\n\t\tc.remotes = append(c.remotes, remote)\n\t}\n}\n\nfunc configFileExists(filename string) bool {\n\tif _, err := os.Stat(filename); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}\n<commit_msg>アーア アアアア アーアー<commit_after>package hawser\n\nimport (\n\t\"fmt\"\n\t\"github.com\/hawser\/git-hawser\/git\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype Configuration struct {\n\tCurrentRemote         string\n\tgitConfig             map[string]string\n\tremotes               []string\n\thttpClient            *http.Client\n\tredirectingHttpClient *http.Client\n\tisTracingHttp         bool\n}\n\nvar (\n\tConfig        = NewConfig()\n\tRedirectError = fmt.Errorf(\"Unexpected redirection\")\n\thttpPrefixRe  = regexp.MustCompile(\"\\\\Ahttps?:\/\/\")\n\tdefaultRemote = \"origin\"\n)\n\nfunc NewConfig() *Configuration {\n\tc := &Configuration{\n\t\tCurrentRemote: defaultRemote,\n\t\tisTracingHttp: len(os.Getenv(\"GIT_CURL_VERBOSE\")) > 0,\n\t}\n\treturn c\n}\n\nfunc (c *Configuration) Endpoint() string {\n\tif url, ok := c.GitConfig(\"hawser.url\"); ok {\n\t\treturn url\n\t}\n\n\tif len(c.CurrentRemote) > 0 && c.CurrentRemote != defaultRemote {\n\t\tif endpoint := c.RemoteEndpoint(c.CurrentRemote); len(endpoint) > 0 {\n\t\t\treturn endpoint\n\t\t}\n\t}\n\n\treturn c.RemoteEndpoint(defaultRemote)\n}\n\nfunc (c *Configuration) RemoteEndpoint(remote string) string {\n\tif len(remote) == 0 {\n\t\tremote = defaultRemote\n\t}\n\n\tif url, ok := c.GitConfig(\"remote.\" + remote + \".hawser\"); ok {\n\t\treturn url\n\t}\n\n\tif url, ok := c.GitConfig(\"remote.\" + remote + \".url\"); ok {\n\t\tif !httpPrefixRe.MatchString(url) {\n\t\t\tpieces := strings.SplitN(url, \":\", 2)\n\t\t\thostPieces := strings.SplitN(pieces[0], \"@\", 2)\n\t\t\tif len(hostPieces) < 2 {\n\t\t\t\treturn \"unknown\"\n\t\t\t}\n\t\t\turl = fmt.Sprintf(\"https:\/\/%s\/%s\", hostPieces[1], pieces[1])\n\t\t}\n\n\t\tif path.Ext(url) == \".git\" {\n\t\t\treturn url + \"\/info\/media\"\n\t\t}\n\t\treturn url + \".git\/info\/media\"\n\t}\n\n\treturn \"\"\n}\n\nfunc (c *Configuration) Remotes() []string {\n\tc.loadGitConfig()\n\treturn c.remotes\n}\n\nfunc (c *Configuration) GitConfig(key string) (string, bool) {\n\tc.loadGitConfig()\n\tvalue, ok := c.gitConfig[strings.ToLower(key)]\n\treturn value, ok\n}\n\nfunc (c *Configuration) SetConfig(key, value string) {\n\tc.loadGitConfig()\n\tc.gitConfig[key] = value\n}\n\nfunc (c *Configuration) ObjectUrl(oid string) *url.URL {\n\tu, _ := url.Parse(c.Endpoint())\n\tu.Path = path.Join(u.Path, \"objects\", oid)\n\treturn u\n}\n\ntype AltConfig struct {\n\tRemote map[string]*struct {\n\t\tMedia string\n\t}\n\n\tMedia struct {\n\t\tUrl string\n\t}\n}\n\nfunc (c *Configuration) loadGitConfig() {\n\tif c.gitConfig != nil {\n\t\treturn\n\t}\n\n\tuniqRemotes := make(map[string]bool)\n\n\tc.gitConfig = make(map[string]string)\n\n\tvar output string\n\tlistOutput, err := git.Config.List()\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Error listing git config: %s\", err))\n\t}\n\n\tfileOutput, err := git.Config.ListFromFile()\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Error listing git config from file: %s\", err))\n\t}\n\n\toutput = listOutput + \"\\n\" + fileOutput\n\n\tlines := strings.Split(output, \"\\n\")\n\tfor _, line := range lines {\n\t\tpieces := strings.SplitN(line, \"=\", 2)\n\t\tif len(pieces) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tkey := strings.ToLower(pieces[0])\n\t\tc.gitConfig[key] = pieces[1]\n\n\t\tkeyParts := strings.Split(key, \".\")\n\t\tif len(keyParts) > 1 && keyParts[0] == \"remote\" {\n\t\t\tremote := keyParts[1]\n\t\t\tuniqRemotes[remote] = remote == \"origin\"\n\t\t}\n\t}\n\n\tc.remotes = make([]string, 0, len(uniqRemotes))\n\tfor remote, isOrigin := range uniqRemotes {\n\t\tif isOrigin {\n\t\t\tcontinue\n\t\t}\n\t\tc.remotes = append(c.remotes, remote)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/asamy\/steam\"\n)\n\nfunc main() {\n\tlog.SetFlags(log.LstdFlags | log.Lshortfile)\n\n\ttimeTip, err := steam.GetTimeTip()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Time tip: %#v\\n\", timeTip)\n\ttimeDiff := time.Duration(timeTip.Time - time.Now().Unix())\n\n\tsession := steam.NewSession(&http.Client{}, \"\")\n\tif err := session.Login(os.Getenv(\"steamAccount\"), os.Getenv(\"steamPassword\"), os.Getenv(\"steamSharedSecret\"), timeDiff); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"Login successful\")\n\n\tsid := steam.SteamID(76561198078821986)\n\tapps, err := session.GetInventoryAppStats(sid)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, v := range apps {\n\t\tlog.Printf(\"-- AppID total asset count: %d\\n\", v.AssetCount)\n\t\tfor _, context := range v.Contexts {\n\t\t\tlog.Printf(\"-- Items on %d %d (count %d)\\n\", v.AppID, context.ID, context.AssetCount)\n\t\t\tinven, err := session.GetInventory(sid, v.AppID, context.ID, steam.LangEng)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tfor _, item := range inven {\n\t\t\t\tlog.Printf(\"Item: %s = %d\\n\", item.Name.MarketHash, item.AssetID)\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Println(\"Bye!\")\n}\n<commit_msg>examples\/inventory: sleep a bit before next request<commit_after>package main\n\nimport (\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/asamy\/steam\"\n)\n\nfunc main() {\n\tlog.SetFlags(log.LstdFlags | log.Lshortfile)\n\n\ttimeTip, err := steam.GetTimeTip()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Time tip: %#v\\n\", timeTip)\n\ttimeDiff := time.Duration(timeTip.Time - time.Now().Unix())\n\n\tsession := steam.NewSession(&http.Client{}, \"\")\n\tif err := session.Login(os.Getenv(\"steamAccount\"), os.Getenv(\"steamPassword\"), os.Getenv(\"steamSharedSecret\"), timeDiff); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Print(\"Login successful\")\n\n\tsid := steam.SteamID(76561198078821986)\n\tapps, err := session.GetInventoryAppStats(sid)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, v := range apps {\n\t\tlog.Printf(\"-- AppID total asset count: %d\\n\", v.AssetCount)\n\t\tfor _, context := range v.Contexts {\n\t\t\tlog.Printf(\"-- Items on %d %d (count %d)\\n\", v.AppID, context.ID, context.AssetCount)\n\t\t\tinven, err := session.GetInventory(sid, v.AppID, context.ID, steam.LangEng)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tfor _, item := range inven {\n\t\t\t\tlog.Printf(\"Item: %s = %d\\n\", item.Name.MarketHash, item.AssetID)\n\t\t\t}\n\n\t\t\t\/\/ Wait a bit so we don't get an error.\n\t\t\ttime.Sleep(time.Millisecond * 100)\n\t\t}\n\t}\n\n\tlog.Println(\"Bye!\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package alloc\n\nimport (\n\t\"sync\"\n)\n\ntype BufferPool struct {\n\tchain     chan []byte\n\tallocator *sync.Pool\n}\n\nfunc NewBufferPool(bufferSize, poolSize int) *BufferPool {\n\tpool := &BufferPool{\n\t\tchain: make(chan []byte, poolSize),\n\t\tallocator: &sync.Pool{\n\t\t\tNew: func() interface{} { return make([]byte, bufferSize) },\n\t\t},\n\t}\n\tfor i := 0; i < poolSize\/2; i++ {\n\t\tpool.chain <- make([]byte, bufferSize)\n\t}\n\treturn pool\n}\n\nfunc (p *BufferPool) Allocate() *Buffer {\n\tvar b []byte\n\tselect {\n\tcase b = <-p.chain:\n\tdefault:\n\t\tb = p.allocator.Get().([]byte)\n\t}\n\treturn CreateBuffer(b, p)\n}\n\nfunc (p *BufferPool) Free(buffer *Buffer) {\n\trawBuffer := buffer.head\n\tif rawBuffer == nil {\n\t\treturn\n\t}\n\tselect {\n\tcase p.chain <- rawBuffer:\n\tdefault:\n\t\tp.allocator.Put(rawBuffer)\n\t}\n}\n\nconst (\n\tSmallBufferSize = 1600 - defaultOffset\n\tBufferSize      = 8*1024 - defaultOffset\n\tLargeBufferSize = 64*1024 - defaultOffset\n)\n\nvar smallPool = NewBufferPool(1600, 128)\nvar mediumPool = NewBufferPool(8*1024, 128)\nvar largePool = NewBufferPool(64*1024, 64)\n<commit_msg>update buffer pool size<commit_after>package alloc\n\nimport (\n\t\"sync\"\n)\n\ntype BufferPool struct {\n\tchain     chan []byte\n\tallocator *sync.Pool\n}\n\nfunc NewBufferPool(bufferSize, poolSize int) *BufferPool {\n\tpool := &BufferPool{\n\t\tchain: make(chan []byte, poolSize),\n\t\tallocator: &sync.Pool{\n\t\t\tNew: func() interface{} { return make([]byte, bufferSize) },\n\t\t},\n\t}\n\tfor i := 0; i < poolSize\/2; i++ {\n\t\tpool.chain <- make([]byte, bufferSize)\n\t}\n\treturn pool\n}\n\nfunc (p *BufferPool) Allocate() *Buffer {\n\tvar b []byte\n\tselect {\n\tcase b = <-p.chain:\n\tdefault:\n\t\tb = p.allocator.Get().([]byte)\n\t}\n\treturn CreateBuffer(b, p)\n}\n\nfunc (p *BufferPool) Free(buffer *Buffer) {\n\trawBuffer := buffer.head\n\tif rawBuffer == nil {\n\t\treturn\n\t}\n\tselect {\n\tcase p.chain <- rawBuffer:\n\tdefault:\n\t\tp.allocator.Put(rawBuffer)\n\t}\n}\n\nconst (\n\tSmallBufferSize = 1600 - defaultOffset\n\tBufferSize      = 8*1024 - defaultOffset\n\tLargeBufferSize = 64*1024 - defaultOffset\n)\n\nvar smallPool = NewBufferPool(1600, 1024)\nvar mediumPool = NewBufferPool(8*1024, 256)\nvar largePool = NewBufferPool(64*1024, 32)\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"sigs.k8s.io\/kustomize\/kyaml\/fn\/framework\"\n\t\"sigs.k8s.io\/kustomize\/kyaml\/fn\/framework\/command\"\n\t\"sigs.k8s.io\/kustomize\/kyaml\/kio\/kioutil\"\n\t\"sigs.k8s.io\/kustomize\/kyaml\/yaml\"\n\n\tkptfilev1 \"github.com\/GoogleContainerTools\/kpt-functions-sdk\/go\/pkg\/api\/kptfile\/v1\"\n\tkptutil \"github.com\/GoogleContainerTools\/kpt-functions-sdk\/go\/pkg\/api\/util\"\n)\n\nvar (\n\tkccAPIVersionRegex = regexp.MustCompile(`^([\\w]+)\\.cnrm\\.cloud\\.google\\.com\\\/[\\w]+$`)\n)\n\nconst (\n\tprojectIDSetterName = \"project-id\"\n\tprojectIDAnnotation = \"cnrm.cloud.google.com\/project-id\"\n)\n\nfunc findSetterNode(nodes []*yaml.RNode, path string) (*yaml.RNode, error) {\n\tfor _, node := range nodes {\n\t\tnp := node.GetAnnotations()[kioutil.PathAnnotation]\n\t\tif np == path {\n\t\t\treturn node, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(`file %s doesn't exist, please ensure the file specified in \"configPath\" exists and retry`, path)\n}\n\nfunc findKptfiles(nodes []*yaml.RNode) ([]*kptfilev1.KptFile, error) {\n\tkptfiles := []*kptfilev1.KptFile{}\n\tfor _, node := range nodes {\n\t\tif node.GetKind() == kptfilev1.KptFileKind {\n\t\t\ts, err := node.String()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to read Kptfile: %w\", err)\n\t\t\t}\n\t\t\tkf, err := kptutil.DecodeKptfile(s)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to read Kptfile: %w\", err)\n\t\t\t}\n\t\t\tkptfiles = append(kptfiles, kf)\n\t\t}\n\t}\n\tif len(kptfiles) == 0 {\n\t\treturn nil, fmt.Errorf(\"unable to find Kptfile, please include --include-meta-resources flag if a Kptfile is present\")\n\t}\n\treturn kptfiles, nil\n}\n\nfunc setKptfile(nodes []*yaml.RNode, kf *kptfilev1.KptFile) error {\n\tb, err := yaml.Marshal(kf)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal updated Kptfile: %w\", err)\n\t}\n\tkNode, err := yaml.Parse(string(b))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse updated Kptfile: %w\", err)\n\t}\n\n\tfor i := range nodes {\n\t\tif nodes[i].GetAnnotations()[kioutil.PathAnnotation] == kf.Annotations[kioutil.PathAnnotation] {\n\t\t\tnodes[i] = kNode\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n\n}\n\nfunc setSettersOnKptfile(nodes []*yaml.RNode, kf *kptfilev1.KptFile, projectID string) error {\n\tif kf.Pipeline == nil {\n\t\tkf.Pipeline = &kptfilev1.Pipeline{}\n\t}\n\tfor _, fn := range kf.Pipeline.Mutators {\n\t\tif !strings.Contains(fn.Image, \"apply-setters\") {\n\t\t\tcontinue\n\t\t}\n\t\tif fn.ConfigMap != nil {\n\t\t\tif fn.ConfigMap[projectIDSetterName] == \"\" {\n\t\t\t\tfn.ConfigMap[projectIDSetterName] = projectID\n\t\t\t}\n\t\t\tif err := setKptfile(nodes, kf); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to update Kptfile file: %w\", err)\n\t\t\t}\n\t\t\treturn nil\n\t\t} else if fn.ConfigPath != \"\" {\n\t\t\tsettersConfig, err := findSetterNode(nodes, fn.ConfigPath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to find setter file: %w\", err)\n\t\t\t}\n\t\t\tdataMap := settersConfig.GetDataMap()\n\t\t\tif dataMap[projectIDSetterName] == \"\" {\n\t\t\t\tdataMap[projectIDSetterName] = projectID\n\t\t\t\tsettersConfig.SetDataMap(dataMap)\n\t\t\t}\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"unable to find `ConfigMap` or `configPath` as the `functionConfig` for apply-setters\")\n\t\t}\n\t}\n\n\tfn := kptfilev1.Function{\n\t\tImage: \"gcr.io\/kpt-fn\/apply-setters:v0.2\",\n\t\tConfigMap: map[string]string{\n\t\t\tprojectIDSetterName: projectID,\n\t\t},\n\t}\n\tkf.Pipeline.Mutators = append(kf.Pipeline.Mutators, fn)\n\tif err := setKptfile(nodes, kf); err != nil {\n\t\treturn fmt.Errorf(\"failed to update Kptfile file: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc setSetters(nodes []*yaml.RNode, projectID string) error {\n\tkptfiles, err := findKptfiles(nodes)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"faild to find Kptfile: %v\", err)\n\t}\n\n\tfor _, kf := range kptfiles {\n\t\tif err := setSettersOnKptfile(nodes, kf, projectID); err != nil {\n\t\t\treturn fmt.Errorf(\"error updating Kptfile: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc setProjectIDAnnotation(nodes []*yaml.RNode, projectID string) error {\n\tfor _, node := range nodes {\n\t\tmatches := kccAPIVersionRegex.FindStringSubmatch(node.GetApiVersion())\n\t\t\/\/ Check if it's a Config Connector resource (apiVersion: *.cnrm.cloud.google.com\/*).\n\t\t\/\/ Ignore Config Connector system resources (apiVersion: core.cnrm.cloud.google.com\/*).\n\t\tif len(matches) == 2 && matches[1] != \"core\" {\n\t\t\tannotations := node.GetAnnotations()\n\t\t\tif _, ok := annotations[projectIDAnnotation]; !ok {\n\t\t\t\tannotations[projectIDAnnotation] = projectID\n\t\t\t\tif err := node.SetAnnotations(annotations); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to set project-id annotation: %w\", err)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\ntype projectIDProcessor struct{}\n\nfunc (p *projectIDProcessor) Process(resourceList *framework.ResourceList) error {\n\tdm := resourceList.FunctionConfig.GetDataMap()\n\tprojectID := dm[projectIDSetterName]\n\n\tif err := setSetters(resourceList.Items, projectID); err != nil {\n\t\treturn fmt.Errorf(\"failed to set project-id setter: %w\", err)\n\t}\n\tif err := setProjectIDAnnotation(resourceList.Items, projectID); err != nil {\n\t\treturn fmt.Errorf(\"failed to set project-id annotation: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\tpp := projectIDProcessor{}\n\tcmd := command.Build(&pp, command.StandaloneEnabled, false)\n\n\tif err := cmd.Execute(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n<commit_msg>Typo fix in set-project-id (#587)<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"sigs.k8s.io\/kustomize\/kyaml\/fn\/framework\"\n\t\"sigs.k8s.io\/kustomize\/kyaml\/fn\/framework\/command\"\n\t\"sigs.k8s.io\/kustomize\/kyaml\/kio\/kioutil\"\n\t\"sigs.k8s.io\/kustomize\/kyaml\/yaml\"\n\n\tkptfilev1 \"github.com\/GoogleContainerTools\/kpt-functions-sdk\/go\/pkg\/api\/kptfile\/v1\"\n\tkptutil \"github.com\/GoogleContainerTools\/kpt-functions-sdk\/go\/pkg\/api\/util\"\n)\n\nvar (\n\tkccAPIVersionRegex = regexp.MustCompile(`^([\\w]+)\\.cnrm\\.cloud\\.google\\.com\\\/[\\w]+$`)\n)\n\nconst (\n\tprojectIDSetterName = \"project-id\"\n\tprojectIDAnnotation = \"cnrm.cloud.google.com\/project-id\"\n)\n\nfunc findSetterNode(nodes []*yaml.RNode, path string) (*yaml.RNode, error) {\n\tfor _, node := range nodes {\n\t\tnp := node.GetAnnotations()[kioutil.PathAnnotation]\n\t\tif np == path {\n\t\t\treturn node, nil\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(`file %s doesn't exist, please ensure the file specified in \"configPath\" exists and retry`, path)\n}\n\nfunc findKptfiles(nodes []*yaml.RNode) ([]*kptfilev1.KptFile, error) {\n\tkptfiles := []*kptfilev1.KptFile{}\n\tfor _, node := range nodes {\n\t\tif node.GetKind() == kptfilev1.KptFileKind {\n\t\t\ts, err := node.String()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to read Kptfile: %w\", err)\n\t\t\t}\n\t\t\tkf, err := kptutil.DecodeKptfile(s)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to read Kptfile: %w\", err)\n\t\t\t}\n\t\t\tkptfiles = append(kptfiles, kf)\n\t\t}\n\t}\n\tif len(kptfiles) == 0 {\n\t\treturn nil, fmt.Errorf(\"unable to find Kptfile, please include --include-meta-resources flag if a Kptfile is present\")\n\t}\n\treturn kptfiles, nil\n}\n\nfunc setKptfile(nodes []*yaml.RNode, kf *kptfilev1.KptFile) error {\n\tb, err := yaml.Marshal(kf)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal updated Kptfile: %w\", err)\n\t}\n\tkNode, err := yaml.Parse(string(b))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse updated Kptfile: %w\", err)\n\t}\n\n\tfor i := range nodes {\n\t\tif nodes[i].GetAnnotations()[kioutil.PathAnnotation] == kf.Annotations[kioutil.PathAnnotation] {\n\t\t\tnodes[i] = kNode\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n\n}\n\nfunc setSettersOnKptfile(nodes []*yaml.RNode, kf *kptfilev1.KptFile, projectID string) error {\n\tif kf.Pipeline == nil {\n\t\tkf.Pipeline = &kptfilev1.Pipeline{}\n\t}\n\tfor _, fn := range kf.Pipeline.Mutators {\n\t\tif !strings.Contains(fn.Image, \"apply-setters\") {\n\t\t\tcontinue\n\t\t}\n\t\tif fn.ConfigMap != nil {\n\t\t\tif fn.ConfigMap[projectIDSetterName] == \"\" {\n\t\t\t\tfn.ConfigMap[projectIDSetterName] = projectID\n\t\t\t}\n\t\t\tif err := setKptfile(nodes, kf); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to update Kptfile file: %w\", err)\n\t\t\t}\n\t\t\treturn nil\n\t\t} else if fn.ConfigPath != \"\" {\n\t\t\tsettersConfig, err := findSetterNode(nodes, fn.ConfigPath)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to find setter file: %w\", err)\n\t\t\t}\n\t\t\tdataMap := settersConfig.GetDataMap()\n\t\t\tif dataMap[projectIDSetterName] == \"\" {\n\t\t\t\tdataMap[projectIDSetterName] = projectID\n\t\t\t\tsettersConfig.SetDataMap(dataMap)\n\t\t\t}\n\t\t\treturn nil\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"unable to find `ConfigMap` or `configPath` as the `functionConfig` for apply-setters\")\n\t\t}\n\t}\n\n\tfn := kptfilev1.Function{\n\t\tImage: \"gcr.io\/kpt-fn\/apply-setters:v0.2\",\n\t\tConfigMap: map[string]string{\n\t\t\tprojectIDSetterName: projectID,\n\t\t},\n\t}\n\tkf.Pipeline.Mutators = append(kf.Pipeline.Mutators, fn)\n\tif err := setKptfile(nodes, kf); err != nil {\n\t\treturn fmt.Errorf(\"failed to update Kptfile file: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc setSetters(nodes []*yaml.RNode, projectID string) error {\n\tkptfiles, err := findKptfiles(nodes)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to find Kptfile: %v\", err)\n\t}\n\n\tfor _, kf := range kptfiles {\n\t\tif err := setSettersOnKptfile(nodes, kf, projectID); err != nil {\n\t\t\treturn fmt.Errorf(\"error updating Kptfile: %w\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc setProjectIDAnnotation(nodes []*yaml.RNode, projectID string) error {\n\tfor _, node := range nodes {\n\t\tmatches := kccAPIVersionRegex.FindStringSubmatch(node.GetApiVersion())\n\t\t\/\/ Check if it's a Config Connector resource (apiVersion: *.cnrm.cloud.google.com\/*).\n\t\t\/\/ Ignore Config Connector system resources (apiVersion: core.cnrm.cloud.google.com\/*).\n\t\tif len(matches) == 2 && matches[1] != \"core\" {\n\t\t\tannotations := node.GetAnnotations()\n\t\t\tif _, ok := annotations[projectIDAnnotation]; !ok {\n\t\t\t\tannotations[projectIDAnnotation] = projectID\n\t\t\t\tif err := node.SetAnnotations(annotations); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to set project-id annotation: %w\", err)\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\ntype projectIDProcessor struct{}\n\nfunc (p *projectIDProcessor) Process(resourceList *framework.ResourceList) error {\n\tdm := resourceList.FunctionConfig.GetDataMap()\n\tprojectID := dm[projectIDSetterName]\n\n\tif err := setSetters(resourceList.Items, projectID); err != nil {\n\t\treturn fmt.Errorf(\"failed to set project-id setter: %w\", err)\n\t}\n\tif err := setProjectIDAnnotation(resourceList.Items, projectID); err != nil {\n\t\treturn fmt.Errorf(\"failed to set project-id annotation: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\tpp := projectIDProcessor{}\n\tcmd := command.Build(&pp, command.StandaloneEnabled, false)\n\n\tif err := cmd.Execute(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 CoreOS, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage locksmith\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"golang.org\/x\/crypto\/ssh\"\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/coreos\/mantle\/kola\/cluster\"\n\t\"github.com\/coreos\/mantle\/kola\/register\"\n\t\"github.com\/coreos\/mantle\/kola\/tests\/etcd\"\n\t\"github.com\/coreos\/mantle\/lang\/worker\"\n\t\"github.com\/coreos\/mantle\/platform\"\n\t\"github.com\/coreos\/mantle\/util\"\n)\n\nfunc init() {\n\tregister.Register(&register.Test{\n\t\tName:        \"coreos.locksmith.cluster\",\n\t\tRun:         locksmithCluster,\n\t\tClusterSize: 3,\n\t\tUserData: `{\n  \"ignition\": { \"version\": \"2.0.0\" },\n  \"systemd\": {\n    \"units\": [\n      {\n        \"name\": \"etcd2.service\",\n        \"enable\": true,\n        \"dropins\": [{\n          \"name\": \"metadata.conf\",\n          \"contents\": \"[Unit]\\nWants=coreos-metadata.service\\nAfter=coreos-metadata.service\\n\\n[Service]\\nEnvironmentFile=-\/run\/metadata\/coreos\\nExecStart=\\nExecStart=\/usr\/bin\/etcd2 --name=$name --discovery=$discovery --advertise-client-urls=http:\/\/$private_ipv4:2379 --initial-advertise-peer-urls=http:\/\/$private_ipv4:2380 --listen-client-urls=http:\/\/0.0.0.0:2379,http:\/\/0.0.0.0:4001 --listen-peer-urls=http:\/\/$private_ipv4:2380,http:\/\/$private_ipv4:7001\"\n        }]\n      },\n      {\n        \"name\": \"coreos-metadata.service\",\n        \"dropins\": [{\n          \"name\": \"qemu.conf\",\n          \"contents\": \"[Unit]\\nConditionVirtualization=!qemu\"\n        }]\n      }\n    ]\n  },\n  \"storage\": {\n    \"files\": [{\n      \"filesystem\": \"root\",\n      \"path\": \"\/etc\/coreos\/update.conf\",\n      \"contents\": { \"source\": \"data:,REBOOT_STRATEGY=etcd-lock%0A\" },\n      \"mode\": 420\n    }]\n  }\n}`,\n\t})\n\tregister.Register(&register.Test{\n\t\tName:        \"coreos.locksmith.tls\",\n\t\tRun:         locksmithTLS,\n\t\tClusterSize: 1,\n\t\tUserData: `{\n  \"ignition\": { \"version\": \"2.0.0\" },\n  \"systemd\": {\n    \"units\": [\n      {\n        \"name\": \"certgen.service\",\n        \"contents\": \"[Service]\\nType=oneshot\\nRemainAfterExit=yes\\nExecStartPre=\/usr\/bin\/mkdir -p \/etc\/ssl\/etcd\\nExecStart=\/usr\/bin\/openssl req -x509 -nodes -newkey rsa:4096 -sha512 -days 3 -extensions etcd_ca -subj '\/CN=etcd CA' -out \/etc\/ssl\/etcd\/ca-etcd-cert.pem -keyout \/etc\/ssl\/etcd\/ca-etcd-key.pem\\nExecStart=\/usr\/bin\/openssl req -x509 -nodes -newkey rsa:4096 -sha512 -days 3 -extensions etcd_server -subj '\/CN=localhost' -out \/etc\/ssl\/etcd\/etcd-cert-self.pem -keyout \/etc\/ssl\/etcd\/etcd-key.pem\\nExecStart=\/usr\/bin\/openssl x509 -CA \/etc\/ssl\/etcd\/ca-etcd-cert.pem -CAkey \/etc\/ssl\/etcd\/ca-etcd-key.pem -CAcreateserial -sha512 -days 3 -in \/etc\/ssl\/etcd\/etcd-cert-self.pem -out \/etc\/ssl\/etcd\/etcd-cert.pem\\nExecStart=\/usr\/bin\/openssl req -x509 -nodes -newkey rsa:4096 -sha512 -days 3 -extensions etcd_ca -subj '\/CN=locksmith CA' -out \/etc\/ssl\/etcd\/ca-locksmith-cert.pem -keyout \/etc\/ssl\/etcd\/ca-locksmith-key.pem\\nExecStart=\/usr\/bin\/openssl req -x509 -nodes -newkey rsa:4096 -sha512 -days 3 -extensions etcd_client -subj '\/CN=locksmith client' -out \/etc\/ssl\/etcd\/locksmith-cert-self.pem -keyout \/etc\/ssl\/etcd\/locksmith-key.pem\\nExecStart=\/usr\/bin\/openssl x509 -CA \/etc\/ssl\/etcd\/ca-locksmith-cert.pem -CAkey \/etc\/ssl\/etcd\/ca-locksmith-key.pem -CAcreateserial -sha512 -days 3 -in \/etc\/ssl\/etcd\/locksmith-cert-self.pem -out \/etc\/ssl\/etcd\/locksmith-cert.pem\\nExecStart=\/usr\/bin\/chmod 0644 \/etc\/ssl\/etcd\/ca-etcd-cert.pem \/etc\/ssl\/etcd\/ca-etcd-key.pem \/etc\/ssl\/etcd\/ca-locksmith-cert.pem \/etc\/ssl\/etcd\/ca-locksmith-key.pem \/etc\/ssl\/etcd\/etcd-cert.pem \/etc\/ssl\/etcd\/etcd-key.pem \/etc\/ssl\/etcd\/locksmith-cert.pem \/etc\/ssl\/etcd\/locksmith-key.pem\\nExecStart=\/usr\/bin\/ln -fns ..\/etcd\/ca-etcd-cert.pem \/etc\/ssl\/certs\/etcd.pem\\nExecStart=\/usr\/bin\/c_rehash\"\n      },\n      {\n        \"name\": \"etcd2.service\",\n        \"dropins\": [{\n          \"name\": \"environment.conf\",\n          \"contents\": \"[Unit]\\nAfter=certgen.service\\nRequires=certgen.service\\n[Service]\\nEnvironment=ETCD_ADVERTISE_CLIENT_URLS=https:\/\/127.0.0.1:2379\\nEnvironment=ETCD_LISTEN_CLIENT_URLS=https:\/\/127.0.0.1:2379\\nEnvironment=ETCD_CERT_FILE=\/etc\/ssl\/etcd\/etcd-cert.pem\\nEnvironment=ETCD_KEY_FILE=\/etc\/ssl\/etcd\/etcd-key.pem\\nEnvironment=ETCD_TRUSTED_CA_FILE=\/etc\/ssl\/etcd\/ca-locksmith-cert.pem\\nEnvironment=ETCD_CERT_AUTH=true\"\n        }]\n      },\n      {\n        \"name\": \"locksmithd.service\",\n        \"enable\": true,\n        \"dropins\": [{\n          \"name\": \"environment.conf\",\n          \"contents\": \"[Unit]\\nAfter=etcd2.service\\nRequires=etcd2.service\\n[Service]\\nEnvironment=LOCKSMITHD_ETCD_CERTFILE=\/etc\/ssl\/etcd\/locksmith-cert.pem\\nEnvironment=LOCKSMITHD_ETCD_KEYFILE=\/etc\/ssl\/etcd\/locksmith-key.pem\\nEnvironment=LOCKSMITHD_ETCD_CAFILE=\/etc\/ssl\/etcd\/ca-etcd-cert.pem\\nEnvironment=LOCKSMITHD_ENDPOINT=https:\/\/localhost:2379\\nEnvironment=LOCKSMITHD_REBOOT_WINDOW_START=00:00\\nEnvironment=LOCKSMITHD_REBOOT_WINDOW_LENGTH=23h59m\"\n        }]\n      }\n    ]\n  },\n  \"storage\": {\n    \"files\": [\n      {\n        \"filesystem\": \"root\",\n        \"path\": \"\/etc\/coreos\/update.conf\",\n        \"contents\": { \"source\": \"data:,REBOOT_STRATEGY=etcd-lock%0A\" },\n        \"mode\": 420\n      },\n      {\n        \"filesystem\": \"root\",\n        \"path\": \"\/etc\/ssl\/openssl.cnf\",\n        \"contents\": { \"source\": \"data:,%5Breq%5D%0Adistinguished_name=req%0A%5Betcd_ca%5D%0AbasicConstraints=CA:true%0AkeyUsage=keyCertSign,cRLSign%0AsubjectKeyIdentifier=hash%0A%5Betcd_client%5D%0AbasicConstraints=CA:FALSE%0AextendedKeyUsage=clientAuth%0AkeyUsage=digitalSignature,keyEncipherment%0A%5Betcd_server%5D%0AbasicConstraints=CA:FALSE%0AextendedKeyUsage=serverAuth%0AkeyUsage=digitalSignature,keyEncipherment%0AsubjectAltName=IP:127.0.0.1%0A\" },\n        \"mode\": 420\n      }\n    ]\n  }\n}`,\n\t})\n}\n\nfunc locksmithCluster(c cluster.TestCluster) error {\n\tmachs := c.Machines()\n\n\t\/\/ Wait for all etcd cluster nodes to be ready.\n\tif err := etcd.GetClusterHealth(machs[0], len(machs)); err != nil {\n\t\treturn fmt.Errorf(\"cluster health: %v\", err)\n\t}\n\n\toutput, err := machs[0].SSH(\"locksmithctl status\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"locksmithctl status: %q: %v\", output, err)\n\t}\n\n\tctx := context.Background()\n\twg := worker.NewWorkerGroup(ctx, len(machs))\n\n\t\/\/ reboot all the things\n\tfor _, m := range machs {\n\t\tworker := func(c context.Context) error {\n\t\t\tcmd := \"sudo systemctl stop sshd.socket && sudo locksmithctl send-need-reboot\"\n\t\t\toutput, err := m.SSH(cmd)\n\t\t\tif _, ok := err.(*ssh.ExitMissingError); ok {\n\t\t\t\terr = nil \/\/ A terminated session is perfectly normal during reboot.\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to run %q: output: %q status: %q\", cmd, output, err)\n\t\t\t}\n\n\t\t\treturn platform.CheckMachine(m)\n\t\t}\n\n\t\tif err := wg.Start(worker); err != nil {\n\t\t\treturn wg.WaitError(err)\n\t\t}\n\t}\n\n\treturn wg.Wait()\n}\n\nfunc locksmithTLS(c cluster.TestCluster) error {\n\tm := c.Machines()[0]\n\tlCmd := \"sudo locksmithctl --endpoint https:\/\/localhost:2379 --etcd-cafile \/etc\/ssl\/etcd\/ca-etcd-cert.pem --etcd-certfile \/etc\/ssl\/etcd\/locksmith-cert.pem --etcd-keyfile \/etc\/ssl\/etcd\/locksmith-key.pem \"\n\n\t\/\/ First verify etcd has a valid TLS connection ready\n\toutput, err := m.SSH(\"openssl s_client -showcerts -verify_return_error -connect localhost:2379 < \/dev\/null\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"openssl s_client: %q: %v\", output, err)\n\t}\n\n\t\/\/ Also verify locksmithctl understands the TLS connection\n\toutput, err = m.SSH(lCmd + \"status\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"locksmithctl status: %q: %v\", output, err)\n\t}\n\n\t\/\/ Stop locksmithd\n\toutput, err = m.SSH(\"sudo systemctl stop locksmithd.service\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"systemctl stop: %q: %v\", output, err)\n\t}\n\n\t\/\/ Set the lock while locksmithd isn't looking\n\toutput, err = m.SSH(lCmd + \"lock\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"locksmithctl lock: %q: %v\", output, err)\n\t}\n\n\t\/\/ Verify it is locked\n\toutput, err = m.SSH(lCmd + \"status\")\n\tif err != nil || !bytes.HasPrefix(output, []byte(\"Available: 0\\nMax: 1\")) {\n\t\treturn fmt.Errorf(\"locksmithctl status (locked): %q: %v\", output, err)\n\t}\n\n\t\/\/ Start locksmithd\n\toutput, err = m.SSH(\"sudo systemctl start locksmithd.service\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"systemctl start: %q: %v\", output, err)\n\t}\n\n\t\/\/ Verify it is unlocked (after locksmithd wakes up again)\n\tchecker := func() error {\n\t\toutput, err := m.SSH(lCmd + \"status\")\n\t\tif err != nil || !bytes.HasPrefix(output, []byte(\"Available: 1\\nMax: 1\")) {\n\t\t\treturn fmt.Errorf(\"locksmithctl status (unlocked): %q: %v\", output, err)\n\t\t}\n\t\treturn nil\n\t}\n\treturn util.Retry(10, 12*time.Second, checker)\n}\n<commit_msg>kola\/tests\/locksmith: use OpenSSL certificate verification status<commit_after>\/\/ Copyright 2016 CoreOS, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage locksmith\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"golang.org\/x\/crypto\/ssh\"\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/coreos\/mantle\/kola\/cluster\"\n\t\"github.com\/coreos\/mantle\/kola\/register\"\n\t\"github.com\/coreos\/mantle\/kola\/tests\/etcd\"\n\t\"github.com\/coreos\/mantle\/lang\/worker\"\n\t\"github.com\/coreos\/mantle\/platform\"\n\t\"github.com\/coreos\/mantle\/util\"\n)\n\nfunc init() {\n\tregister.Register(&register.Test{\n\t\tName:        \"coreos.locksmith.cluster\",\n\t\tRun:         locksmithCluster,\n\t\tClusterSize: 3,\n\t\tUserData: `{\n  \"ignition\": { \"version\": \"2.0.0\" },\n  \"systemd\": {\n    \"units\": [\n      {\n        \"name\": \"etcd2.service\",\n        \"enable\": true,\n        \"dropins\": [{\n          \"name\": \"metadata.conf\",\n          \"contents\": \"[Unit]\\nWants=coreos-metadata.service\\nAfter=coreos-metadata.service\\n\\n[Service]\\nEnvironmentFile=-\/run\/metadata\/coreos\\nExecStart=\\nExecStart=\/usr\/bin\/etcd2 --name=$name --discovery=$discovery --advertise-client-urls=http:\/\/$private_ipv4:2379 --initial-advertise-peer-urls=http:\/\/$private_ipv4:2380 --listen-client-urls=http:\/\/0.0.0.0:2379,http:\/\/0.0.0.0:4001 --listen-peer-urls=http:\/\/$private_ipv4:2380,http:\/\/$private_ipv4:7001\"\n        }]\n      },\n      {\n        \"name\": \"coreos-metadata.service\",\n        \"dropins\": [{\n          \"name\": \"qemu.conf\",\n          \"contents\": \"[Unit]\\nConditionVirtualization=!qemu\"\n        }]\n      }\n    ]\n  },\n  \"storage\": {\n    \"files\": [{\n      \"filesystem\": \"root\",\n      \"path\": \"\/etc\/coreos\/update.conf\",\n      \"contents\": { \"source\": \"data:,REBOOT_STRATEGY=etcd-lock%0A\" },\n      \"mode\": 420\n    }]\n  }\n}`,\n\t})\n\tregister.Register(&register.Test{\n\t\tName:        \"coreos.locksmith.tls\",\n\t\tRun:         locksmithTLS,\n\t\tClusterSize: 1,\n\t\tUserData: `{\n  \"ignition\": { \"version\": \"2.0.0\" },\n  \"systemd\": {\n    \"units\": [\n      {\n        \"name\": \"certgen.service\",\n        \"contents\": \"[Service]\\nType=oneshot\\nRemainAfterExit=yes\\nExecStartPre=\/usr\/bin\/mkdir -p \/etc\/ssl\/etcd\\nExecStart=\/usr\/bin\/openssl req -x509 -nodes -newkey rsa:4096 -sha512 -days 3 -extensions etcd_ca -subj '\/CN=etcd CA' -out \/etc\/ssl\/etcd\/ca-etcd-cert.pem -keyout \/etc\/ssl\/etcd\/ca-etcd-key.pem\\nExecStart=\/usr\/bin\/openssl req -x509 -nodes -newkey rsa:4096 -sha512 -days 3 -extensions etcd_server -subj '\/CN=localhost' -out \/etc\/ssl\/etcd\/etcd-cert-self.pem -keyout \/etc\/ssl\/etcd\/etcd-key.pem\\nExecStart=\/usr\/bin\/openssl x509 -CA \/etc\/ssl\/etcd\/ca-etcd-cert.pem -CAkey \/etc\/ssl\/etcd\/ca-etcd-key.pem -CAcreateserial -sha512 -days 3 -in \/etc\/ssl\/etcd\/etcd-cert-self.pem -out \/etc\/ssl\/etcd\/etcd-cert.pem\\nExecStart=\/usr\/bin\/openssl req -x509 -nodes -newkey rsa:4096 -sha512 -days 3 -extensions etcd_ca -subj '\/CN=locksmith CA' -out \/etc\/ssl\/etcd\/ca-locksmith-cert.pem -keyout \/etc\/ssl\/etcd\/ca-locksmith-key.pem\\nExecStart=\/usr\/bin\/openssl req -x509 -nodes -newkey rsa:4096 -sha512 -days 3 -extensions etcd_client -subj '\/CN=locksmith client' -out \/etc\/ssl\/etcd\/locksmith-cert-self.pem -keyout \/etc\/ssl\/etcd\/locksmith-key.pem\\nExecStart=\/usr\/bin\/openssl x509 -CA \/etc\/ssl\/etcd\/ca-locksmith-cert.pem -CAkey \/etc\/ssl\/etcd\/ca-locksmith-key.pem -CAcreateserial -sha512 -days 3 -in \/etc\/ssl\/etcd\/locksmith-cert-self.pem -out \/etc\/ssl\/etcd\/locksmith-cert.pem\\nExecStart=\/usr\/bin\/chmod 0644 \/etc\/ssl\/etcd\/ca-etcd-cert.pem \/etc\/ssl\/etcd\/ca-etcd-key.pem \/etc\/ssl\/etcd\/ca-locksmith-cert.pem \/etc\/ssl\/etcd\/ca-locksmith-key.pem \/etc\/ssl\/etcd\/etcd-cert.pem \/etc\/ssl\/etcd\/etcd-key.pem \/etc\/ssl\/etcd\/locksmith-cert.pem \/etc\/ssl\/etcd\/locksmith-key.pem\\nExecStart=\/usr\/bin\/ln -fns ..\/etcd\/ca-etcd-cert.pem \/etc\/ssl\/certs\/etcd.pem\\nExecStart=\/usr\/bin\/c_rehash\"\n      },\n      {\n        \"name\": \"etcd2.service\",\n        \"dropins\": [{\n          \"name\": \"environment.conf\",\n          \"contents\": \"[Unit]\\nAfter=certgen.service\\nRequires=certgen.service\\n[Service]\\nEnvironment=ETCD_ADVERTISE_CLIENT_URLS=https:\/\/127.0.0.1:2379\\nEnvironment=ETCD_LISTEN_CLIENT_URLS=https:\/\/127.0.0.1:2379\\nEnvironment=ETCD_CERT_FILE=\/etc\/ssl\/etcd\/etcd-cert.pem\\nEnvironment=ETCD_KEY_FILE=\/etc\/ssl\/etcd\/etcd-key.pem\\nEnvironment=ETCD_TRUSTED_CA_FILE=\/etc\/ssl\/etcd\/ca-locksmith-cert.pem\\nEnvironment=ETCD_CERT_AUTH=true\"\n        }]\n      },\n      {\n        \"name\": \"locksmithd.service\",\n        \"enable\": true,\n        \"dropins\": [{\n          \"name\": \"environment.conf\",\n          \"contents\": \"[Unit]\\nAfter=etcd2.service\\nRequires=etcd2.service\\n[Service]\\nEnvironment=LOCKSMITHD_ETCD_CERTFILE=\/etc\/ssl\/etcd\/locksmith-cert.pem\\nEnvironment=LOCKSMITHD_ETCD_KEYFILE=\/etc\/ssl\/etcd\/locksmith-key.pem\\nEnvironment=LOCKSMITHD_ETCD_CAFILE=\/etc\/ssl\/etcd\/ca-etcd-cert.pem\\nEnvironment=LOCKSMITHD_ENDPOINT=https:\/\/localhost:2379\\nEnvironment=LOCKSMITHD_REBOOT_WINDOW_START=00:00\\nEnvironment=LOCKSMITHD_REBOOT_WINDOW_LENGTH=23h59m\"\n        }]\n      }\n    ]\n  },\n  \"storage\": {\n    \"files\": [\n      {\n        \"filesystem\": \"root\",\n        \"path\": \"\/etc\/coreos\/update.conf\",\n        \"contents\": { \"source\": \"data:,REBOOT_STRATEGY=etcd-lock%0A\" },\n        \"mode\": 420\n      },\n      {\n        \"filesystem\": \"root\",\n        \"path\": \"\/etc\/ssl\/openssl.cnf\",\n        \"contents\": { \"source\": \"data:,%5Breq%5D%0Adistinguished_name=req%0A%5Betcd_ca%5D%0AbasicConstraints=CA:true%0AkeyUsage=keyCertSign,cRLSign%0AsubjectKeyIdentifier=hash%0A%5Betcd_client%5D%0AbasicConstraints=CA:FALSE%0AextendedKeyUsage=clientAuth%0AkeyUsage=digitalSignature,keyEncipherment%0A%5Betcd_server%5D%0AbasicConstraints=CA:FALSE%0AextendedKeyUsage=serverAuth%0AkeyUsage=digitalSignature,keyEncipherment%0AsubjectAltName=IP:127.0.0.1%0A\" },\n        \"mode\": 420\n      }\n    ]\n  }\n}`,\n\t})\n}\n\nfunc locksmithCluster(c cluster.TestCluster) error {\n\tmachs := c.Machines()\n\n\t\/\/ Wait for all etcd cluster nodes to be ready.\n\tif err := etcd.GetClusterHealth(machs[0], len(machs)); err != nil {\n\t\treturn fmt.Errorf(\"cluster health: %v\", err)\n\t}\n\n\toutput, err := machs[0].SSH(\"locksmithctl status\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"locksmithctl status: %q: %v\", output, err)\n\t}\n\n\tctx := context.Background()\n\twg := worker.NewWorkerGroup(ctx, len(machs))\n\n\t\/\/ reboot all the things\n\tfor _, m := range machs {\n\t\tworker := func(c context.Context) error {\n\t\t\tcmd := \"sudo systemctl stop sshd.socket && sudo locksmithctl send-need-reboot\"\n\t\t\toutput, err := m.SSH(cmd)\n\t\t\tif _, ok := err.(*ssh.ExitMissingError); ok {\n\t\t\t\terr = nil \/\/ A terminated session is perfectly normal during reboot.\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to run %q: output: %q status: %q\", cmd, output, err)\n\t\t\t}\n\n\t\t\treturn platform.CheckMachine(m)\n\t\t}\n\n\t\tif err := wg.Start(worker); err != nil {\n\t\t\treturn wg.WaitError(err)\n\t\t}\n\t}\n\n\treturn wg.Wait()\n}\n\nfunc locksmithTLS(c cluster.TestCluster) error {\n\tm := c.Machines()[0]\n\tlCmd := \"sudo locksmithctl --endpoint https:\/\/localhost:2379 --etcd-cafile \/etc\/ssl\/etcd\/ca-etcd-cert.pem --etcd-certfile \/etc\/ssl\/etcd\/locksmith-cert.pem --etcd-keyfile \/etc\/ssl\/etcd\/locksmith-key.pem \"\n\n\t\/\/ First verify etcd has a valid TLS connection ready\n\toutput, err := m.SSH(\"openssl s_client -showcerts -verify_return_error -verify_ip 127.0.0.1 -verify_hostname localhost -connect localhost:2379 0<\/dev\/null 2>\/dev\/null\")\n\tif err != nil || !bytes.Contains(output, []byte(\"Verify return code: 0\")) {\n\t\treturn fmt.Errorf(\"openssl s_client: %q: %v\", output, err)\n\t}\n\n\t\/\/ Also verify locksmithctl understands the TLS connection\n\toutput, err = m.SSH(lCmd + \"status\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"locksmithctl status: %q: %v\", output, err)\n\t}\n\n\t\/\/ Stop locksmithd\n\toutput, err = m.SSH(\"sudo systemctl stop locksmithd.service\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"systemctl stop: %q: %v\", output, err)\n\t}\n\n\t\/\/ Set the lock while locksmithd isn't looking\n\toutput, err = m.SSH(lCmd + \"lock\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"locksmithctl lock: %q: %v\", output, err)\n\t}\n\n\t\/\/ Verify it is locked\n\toutput, err = m.SSH(lCmd + \"status\")\n\tif err != nil || !bytes.HasPrefix(output, []byte(\"Available: 0\\nMax: 1\")) {\n\t\treturn fmt.Errorf(\"locksmithctl status (locked): %q: %v\", output, err)\n\t}\n\n\t\/\/ Start locksmithd\n\toutput, err = m.SSH(\"sudo systemctl start locksmithd.service\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"systemctl start: %q: %v\", output, err)\n\t}\n\n\t\/\/ Verify it is unlocked (after locksmithd wakes up again)\n\tchecker := func() error {\n\t\toutput, err := m.SSH(lCmd + \"status\")\n\t\tif err != nil || !bytes.HasPrefix(output, []byte(\"Available: 1\\nMax: 1\")) {\n\t\t\treturn fmt.Errorf(\"locksmithctl status (unlocked): %q: %v\", output, err)\n\t\t}\n\t\treturn nil\n\t}\n\treturn util.Retry(10, 12*time.Second, checker)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage transport\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/oauth2\"\n\t\"k8s.io\/klog\"\n)\n\n\/\/ TokenSourceWrapTransport returns a WrapTransport that injects bearer tokens\n\/\/ authentication from an oauth2.TokenSource.\nfunc TokenSourceWrapTransport(ts oauth2.TokenSource) func(http.RoundTripper) http.RoundTripper {\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn &tokenSourceTransport{\n\t\t\tbase: rt,\n\t\t\tort: &oauth2.Transport{\n\t\t\t\tSource: ts,\n\t\t\t\tBase:   rt,\n\t\t\t},\n\t\t}\n\t}\n}\n\n\/\/ NewCachedFileTokenSource returns a oauth2.TokenSource reads a token from a\n\/\/ file at a specified path and periodically reloads it.\nfunc NewCachedFileTokenSource(path string) oauth2.TokenSource {\n\treturn &cachingTokenSource{\n\t\tnow:    time.Now,\n\t\tleeway: 1 * time.Minute,\n\t\tbase: &fileTokenSource{\n\t\t\tpath: path,\n\t\t\t\/\/ This period was picked because it is half of the minimum validity\n\t\t\t\/\/ duration for a token provisioned by they TokenRequest API. This is\n\t\t\t\/\/ unsophisticated and should induce rotation at a frequency that should\n\t\t\t\/\/ work with the token volume source.\n\t\t\tperiod: 5 * time.Minute,\n\t\t},\n\t}\n}\n\ntype tokenSourceTransport struct {\n\tbase http.RoundTripper\n\tort  http.RoundTripper\n}\n\nfunc (tst *tokenSourceTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\t\/\/ This is to allow --token to override other bearer token providers.\n\tif req.Header.Get(\"Authorization\") != \"\" {\n\t\treturn tst.base.RoundTrip(req)\n\t}\n\treturn tst.ort.RoundTrip(req)\n}\n\ntype fileTokenSource struct {\n\tpath   string\n\tperiod time.Duration\n}\n\nvar _ = oauth2.TokenSource(&fileTokenSource{})\n\nfunc (ts *fileTokenSource) Token() (*oauth2.Token, error) {\n\ttokb, err := ioutil.ReadFile(ts.path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read token file %q: %v\", ts.path, err)\n\t}\n\ttok := strings.TrimSpace(string(tokb))\n\tif len(tok) == 0 {\n\t\treturn nil, fmt.Errorf(\"read empty token from file %q\", ts.path)\n\t}\n\n\treturn &oauth2.Token{\n\t\tAccessToken: tok,\n\t\tExpiry:      time.Now().Add(ts.period),\n\t}, nil\n}\n\ntype cachingTokenSource struct {\n\tbase   oauth2.TokenSource\n\tleeway time.Duration\n\n\tsync.RWMutex\n\ttok *oauth2.Token\n\n\t\/\/ for testing\n\tnow func() time.Time\n}\n\nvar _ = oauth2.TokenSource(&cachingTokenSource{})\n\nfunc (ts *cachingTokenSource) Token() (*oauth2.Token, error) {\n\tnow := ts.now()\n\t\/\/ fast path\n\tts.RLock()\n\ttok := ts.tok\n\tts.RUnlock()\n\n\tif tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) {\n\t\treturn tok, nil\n\t}\n\n\t\/\/ slow path\n\tts.Lock()\n\tdefer ts.Unlock()\n\tif tok := ts.tok; tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) {\n\t\treturn tok, nil\n\t}\n\n\ttok, err := ts.base.Token()\n\tif err != nil {\n\t\tif ts.tok == nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.Errorf(\"Unable to rotate token: %v\", err)\n\t\treturn ts.tok, nil\n\t}\n\n\tts.tok = tok\n\treturn tok, nil\n}\n<commit_msg>Shorten re-read period for token files to work with ProjectedTokenVolumeSource<commit_after>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage transport\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/oauth2\"\n\t\"k8s.io\/klog\"\n)\n\n\/\/ TokenSourceWrapTransport returns a WrapTransport that injects bearer tokens\n\/\/ authentication from an oauth2.TokenSource.\nfunc TokenSourceWrapTransport(ts oauth2.TokenSource) func(http.RoundTripper) http.RoundTripper {\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn &tokenSourceTransport{\n\t\t\tbase: rt,\n\t\t\tort: &oauth2.Transport{\n\t\t\t\tSource: ts,\n\t\t\t\tBase:   rt,\n\t\t\t},\n\t\t}\n\t}\n}\n\n\/\/ NewCachedFileTokenSource returns a oauth2.TokenSource reads a token from a\n\/\/ file at a specified path and periodically reloads it.\nfunc NewCachedFileTokenSource(path string) oauth2.TokenSource {\n\treturn &cachingTokenSource{\n\t\tnow:    time.Now,\n\t\tleeway: 10 * time.Second,\n\t\tbase: &fileTokenSource{\n\t\t\tpath: path,\n\t\t\t\/\/ This period was picked because it is half of the duration between when the kubelet\n\t\t\t\/\/ refreshes a projected service account token and when the original token expires.\n\t\t\t\/\/ Default token lifetime is 10 minutes, and the kubelet starts refreshing at 80% of lifetime.\n\t\t\t\/\/ This should induce re-reading at a frequency that works with the token volume source.\n\t\t\tperiod: time.Minute,\n\t\t},\n\t}\n}\n\ntype tokenSourceTransport struct {\n\tbase http.RoundTripper\n\tort  http.RoundTripper\n}\n\nfunc (tst *tokenSourceTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\t\/\/ This is to allow --token to override other bearer token providers.\n\tif req.Header.Get(\"Authorization\") != \"\" {\n\t\treturn tst.base.RoundTrip(req)\n\t}\n\treturn tst.ort.RoundTrip(req)\n}\n\ntype fileTokenSource struct {\n\tpath   string\n\tperiod time.Duration\n}\n\nvar _ = oauth2.TokenSource(&fileTokenSource{})\n\nfunc (ts *fileTokenSource) Token() (*oauth2.Token, error) {\n\ttokb, err := ioutil.ReadFile(ts.path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read token file %q: %v\", ts.path, err)\n\t}\n\ttok := strings.TrimSpace(string(tokb))\n\tif len(tok) == 0 {\n\t\treturn nil, fmt.Errorf(\"read empty token from file %q\", ts.path)\n\t}\n\n\treturn &oauth2.Token{\n\t\tAccessToken: tok,\n\t\tExpiry:      time.Now().Add(ts.period),\n\t}, nil\n}\n\ntype cachingTokenSource struct {\n\tbase   oauth2.TokenSource\n\tleeway time.Duration\n\n\tsync.RWMutex\n\ttok *oauth2.Token\n\n\t\/\/ for testing\n\tnow func() time.Time\n}\n\nvar _ = oauth2.TokenSource(&cachingTokenSource{})\n\nfunc (ts *cachingTokenSource) Token() (*oauth2.Token, error) {\n\tnow := ts.now()\n\t\/\/ fast path\n\tts.RLock()\n\ttok := ts.tok\n\tts.RUnlock()\n\n\tif tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) {\n\t\treturn tok, nil\n\t}\n\n\t\/\/ slow path\n\tts.Lock()\n\tdefer ts.Unlock()\n\tif tok := ts.tok; tok != nil && tok.Expiry.Add(-1*ts.leeway).After(now) {\n\t\treturn tok, nil\n\t}\n\n\ttok, err := ts.base.Token()\n\tif err != nil {\n\t\tif ts.tok == nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tklog.Errorf(\"Unable to rotate token: %v\", err)\n\t\treturn ts.tok, nil\n\t}\n\n\tts.tok = tok\n\treturn tok, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/codegangsta\/cli\"\n\tmp \"github.com\/mackerelio\/go-mackerel-plugin\"\n)\n\n\/\/ metric value structure\nvar graphdef map[string](mp.Graphs) = map[string](mp.Graphs){\n\t\"php-apc.purges\": mp.Graphs{\n\t\tLabel: \"APC purge count\",\n\t\tUnit:  \"integer\",\n\t\tMetrics: [](mp.Metrics){\n\t\t\tmp.Metrics{Name: \"cache_full_count\", Label: \"File Cache\", Diff: true, Stacked: false},\n\t\t\tmp.Metrics{Name: \"user_cache_full_count\", Label: \"User Cache\", Diff: true, Stacked: false},\n\t\t},\n\t},\n\t\"php-apc.stats\": mp.Graphs{\n\t\tLabel: \"APC file cache statistics\",\n\t\tUnit:  \"integer\",\n\t\tMetrics: [](mp.Metrics){\n\t\t\tmp.Metrics{Name: \"cache_hits\", Label: \"Hits\", Diff: true, Stacked: false},\n\t\t\tmp.Metrics{Name: \"cache_misses\", Label: \"Misses\", Diff: true, Stacked: false},\n\t\t},\n\t},\n\t\"php-apc.cache_size\": mp.Graphs{\n\t\tLabel: \"APC cache size\",\n\t\tUnit:  \"float\",\n\t\tMetrics: [](mp.Metrics){\n\t\t\tmp.Metrics{Name: \"Code Cache\", Label: \"cached_files_size\", Diff: false, Stacked: true},\n\t\t\tmp.Metrics{Name: \"User Items Cache\", Label: \"user_cache_vars_size\", Diff: false, Stacked: true},\n\t\t\tmp.Metrics{Name: \"Limit\", Label: \"total_memory\", Diff: false, Stacked: false},\n\t\t},\n\t},\n\t\"php-apc.user_stats\": mp.Graphs{\n\t\tLabel: \"APC user cache statistics\",\n\t\tUnit:  \"integer\",\n\t\tMetrics: [](mp.Metrics){\n\t\t\tmp.Metrics{Name: \"user_cache_hits\", Label: \"Hits\", Diff: true, Stacked: false},\n\t\t\tmp.Metrics{Name: \"user_cache_misses\", Label: \"Misses\", Diff: true, Stacked: false},\n\t\t},\n\t},\n}\n\n\/\/ for fetching metrics\ntype PhpApcPlugin struct {\n\tHost     string\n\tPort     uint16\n\tPath     string\n\tTempfile string\n}\n\n\/\/ Graph definition\nfunc (c PhpApcPlugin) GraphDefinition() map[string](mp.Graphs) {\n\treturn graphdef\n}\n\n\/\/ main function\nfunc doMain(c *cli.Context) {\n\n\tvar phpapc PhpApcPlugin\n\n\tphpapc.Host = c.String(\"http_host\")\n\tphpapc.Port = uint16(c.Int(\"http_port\"))\n\tphpapc.Path = c.String(\"status_page\")\n\n\thelper := mp.NewMackerelPlugin(phpapc)\n\thelper.Tempfile = c.String(\"tempfile\")\n\n\tif os.Getenv(\"MACKEREL_AGENT_PLUGIN_META\") != \"\" {\n\t\thelper.OutputDefinitions()\n\t} else {\n\t\thelper.OutputValues()\n\t}\n}\n\n\/\/ fetch metrics\nfunc (c PhpApcPlugin) FetchMetrics() (map[string]float64, error) {\n\tdata, err := getPhpApcMetrics(c.Host, c.Port, c.Path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstat := make(map[string]float64)\n\terr_stat := parsePhpApcStatus(data, &stat)\n\tif err_stat != nil {\n\t\treturn nil, err_stat\n\t}\n\n\treturn stat, nil\n}\n\n\/\/ parsing metrics from server-status?auto\nfunc parsePhpApcStatus(str string, p *map[string]float64) error {\n\tfor _, line := range strings.Split(str, \"\\n\") {\n\t\trecord := strings.Split(line, \":\")\n\t\tif len(record) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tvar err_parse error\n\t\t(*p)[record[0]], err_parse = strconv.ParseFloat(strings.Trim(record[1], \" \"), 64)\n\t\tif err_parse != nil {\n\t\t\treturn err_parse\n\t\t}\n\t}\n\n\tif len(*p) == 0 {\n\t\treturn errors.New(\"Status data not found.\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Getting php-apc status from server-status module data.\nfunc getPhpApcMetrics(host string, port uint16, path string) (string, error) {\n\turi := \"http:\/\/\" + host + \":\" + strconv.FormatUint(uint64(port), 10) + path\n\tresp, err := http.Get(uri)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"HTTP status error: %d\", resp.StatusCode))\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body[:]), nil\n}\n\n\/\/ main\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"php-apc_metrics\"\n\tapp.Version = Version\n\tapp.Usage = \"Get metrics from php-apc.\"\n\tapp.Author = \"Yuichiro Saito\"\n\tapp.Email = \"saito@heartbeats.jp\"\n\tapp.Flags = Flags\n\tapp.Action = doMain\n\n\tapp.Run(os.Args)\n}\n<commit_msg>Fix label and name.<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/codegangsta\/cli\"\n\tmp \"github.com\/mackerelio\/go-mackerel-plugin\"\n)\n\n\/\/ metric value structure\nvar graphdef map[string](mp.Graphs) = map[string](mp.Graphs){\n\t\"php-apc.purges\": mp.Graphs{\n\t\tLabel: \"PHP APC purge count\",\n\t\tUnit:  \"integer\",\n\t\tMetrics: [](mp.Metrics){\n\t\t\tmp.Metrics{Name: \"cache_full_count\", Label: \"File Cache\", Diff: true, Stacked: false},\n\t\t\tmp.Metrics{Name: \"user_cache_full_count\", Label: \"User Cache\", Diff: true, Stacked: false},\n\t\t},\n\t},\n\t\"php-apc.stats\": mp.Graphs{\n\t\tLabel: \"PHP APC file cache statistics\",\n\t\tUnit:  \"integer\",\n\t\tMetrics: [](mp.Metrics){\n\t\t\tmp.Metrics{Name: \"cache_hits\", Label: \"Hits\", Diff: true, Stacked: false},\n\t\t\tmp.Metrics{Name: \"cache_misses\", Label: \"Misses\", Diff: true, Stacked: false},\n\t\t},\n\t},\n\t\"php-apc.cache_size\": mp.Graphs{\n\t\tLabel: \"PHP APC cache size\",\n\t\tUnit:  \"float\",\n\t\tMetrics: [](mp.Metrics){\n\t\t\tmp.Metrics{Name: \"cached_files_size\", Label: \"File Cache\", Diff: false, Stacked: true},\n\t\t\tmp.Metrics{Name: \"user_cache_vars_size\", Label: \"User Cache\", Diff: false, Stacked: true},\n\t\t\tmp.Metrics{Name: \"total_memory\", Label: \"Total\", Diff: false, Stacked: false},\n\t\t},\n\t},\n\t\"php-apc.user_stats\": mp.Graphs{\n\t\tLabel: \"PHP APC user cache statistics\",\n\t\tUnit:  \"integer\",\n\t\tMetrics: [](mp.Metrics){\n\t\t\tmp.Metrics{Name: \"user_cache_hits\", Label: \"Hits\", Diff: true, Stacked: false},\n\t\t\tmp.Metrics{Name: \"user_cache_misses\", Label: \"Misses\", Diff: true, Stacked: false},\n\t\t},\n\t},\n}\n\n\/\/ for fetching metrics\ntype PhpApcPlugin struct {\n\tHost     string\n\tPort     uint16\n\tPath     string\n\tTempfile string\n}\n\n\/\/ Graph definition\nfunc (c PhpApcPlugin) GraphDefinition() map[string](mp.Graphs) {\n\treturn graphdef\n}\n\n\/\/ main function\nfunc doMain(c *cli.Context) {\n\n\tvar phpapc PhpApcPlugin\n\n\tphpapc.Host = c.String(\"http_host\")\n\tphpapc.Port = uint16(c.Int(\"http_port\"))\n\tphpapc.Path = c.String(\"status_page\")\n\n\thelper := mp.NewMackerelPlugin(phpapc)\n\thelper.Tempfile = c.String(\"tempfile\")\n\n\tif os.Getenv(\"MACKEREL_AGENT_PLUGIN_META\") != \"\" {\n\t\thelper.OutputDefinitions()\n\t} else {\n\t\thelper.OutputValues()\n\t}\n}\n\n\/\/ fetch metrics\nfunc (c PhpApcPlugin) FetchMetrics() (map[string]float64, error) {\n\tdata, err := getPhpApcMetrics(c.Host, c.Port, c.Path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstat := make(map[string]float64)\n\terr_stat := parsePhpApcStatus(data, &stat)\n\tif err_stat != nil {\n\t\treturn nil, err_stat\n\t}\n\n\treturn stat, nil\n}\n\n\/\/ parsing metrics from server-status?auto\nfunc parsePhpApcStatus(str string, p *map[string]float64) error {\n\tfor _, line := range strings.Split(str, \"\\n\") {\n\t\trecord := strings.Split(line, \":\")\n\t\tif len(record) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tvar err_parse error\n\t\t(*p)[record[0]], err_parse = strconv.ParseFloat(strings.Trim(record[1], \" \"), 64)\n\t\tif err_parse != nil {\n\t\t\treturn err_parse\n\t\t}\n\t}\n\n\tif len(*p) == 0 {\n\t\treturn errors.New(\"Status data not found.\")\n\t}\n\n\treturn nil\n}\n\n\/\/ Getting php-apc status from server-status module data.\nfunc getPhpApcMetrics(host string, port uint16, path string) (string, error) {\n\turi := \"http:\/\/\" + host + \":\" + strconv.FormatUint(uint64(port), 10) + path\n\tresp, err := http.Get(uri)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn \"\", errors.New(fmt.Sprintf(\"HTTP status error: %d\", resp.StatusCode))\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(body[:]), nil\n}\n\n\/\/ main\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"php-apc_metrics\"\n\tapp.Version = Version\n\tapp.Usage = \"Get metrics from php-apc.\"\n\tapp.Author = \"Yuichiro Saito\"\n\tapp.Email = \"saito@heartbeats.jp\"\n\tapp.Flags = Flags\n\tapp.Action = doMain\n\n\tapp.Run(os.Args)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 tsuru authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage docker\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/globocom\/config\"\n\t\"github.com\/globocom\/tsuru\/fs\"\n\t\"github.com\/globocom\/tsuru\/log\"\n\t\"github.com\/globocom\/tsuru\/provision\"\n\t\"github.com\/globocom\/tsuru\/repository\"\n\t\"io\/ioutil\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\"\n\t\"strings\"\n)\n\nvar fsystem fs.Fs\n\nfunc filesystem() fs.Fs {\n\tif fsystem == nil {\n\t\tfsystem = fs.OsFs{}\n\t}\n\treturn fsystem\n}\n\n\/\/ runCmd executes commands and log the given stdout and stderror.\nfunc runCmd(cmd string, args ...string) (string, error) {\n\tout := bytes.Buffer{}\n\terr := executor().Execute(cmd, args, nil, &out, &out)\n\tlog.Printf(\"running the cmd: %s with the args: %s\", cmd, args)\n\treturn out.String(), err\n}\n\nfunc getSSHCommands() ([]string, error) {\n\taddKeyCommand, err := config.GetString(\"docker:ssh:add-key-cmd\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyFile, err := config.GetString(\"docker:ssh:public-key\")\n\tif err != nil {\n\t\tif u, err := user.Current(); err == nil {\n\t\t\tkeyFile = path.Join(u.HomeDir, \".ssh\", \"id_rsa.pub\")\n\t\t} else {\n\t\t\tkeyFile = os.ExpandEnv(\"${HOME}\/.ssh\/id_rsa.pub\")\n\t\t}\n\t}\n\tf, err := filesystem().Open(keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tkeyContent, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsshdPath, err := config.GetString(\"docker:ssh:sshd-path\")\n\tif err != nil {\n\t\tsshdPath = \"\/usr\/sbin\/sshd\"\n\t}\n\treturn []string{\n\t\tfmt.Sprintf(\"%s %s\", addKeyCommand, keyContent),\n\t\tsshdPath,\n\t}, nil\n}\n\nfunc runContainerCmd(app provision.App) ([]string, string, error) {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\trepoNamespace, err := config.GetString(\"docker:repository-namespace\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tdeployCmd, err := config.GetString(\"docker:deploy-cmd\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tappRepo := repository.GetReadOnlyUrl(app.GetName())\n\trunBin, err := config.GetString(\"docker:run-cmd:bin\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\trunArgs, err := config.GetString(\"docker:run-cmd:args\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tport, err := config.GetString(\"docker:run-cmd:port\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tcommands, err := getSSHCommands()\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tcommands = append(commands, fmt.Sprintf(\"%s %s\", deployCmd, appRepo), fmt.Sprintf(\"%s %s\", runBin, runArgs))\n\timageName := fmt.Sprintf(\"%s\/%s\", repoNamespace, app.GetPlatform()) \/\/ TODO (flaviamissi): should use same algorithm as image.repositoryName\n\tcontainerCmd := strings.Join(commands, \" && \")\n\twholeCmd := []string{docker, \"run\", \"-d\", \"-t\", \"-p\", port, imageName, \"\/bin\/bash\", \"-c\", containerCmd}\n\treturn wholeCmd, port, nil\n}\n\ntype container struct {\n\tId      string `bson:\"_id\"`\n\tAppName string\n\tType    string\n\tIp      string\n\tPort    string\n}\n\n\/\/ newContainer creates a new container in Docker and stores it in the database.\n\/\/\n\/\/ TODO (flaviamissi): make it atomic\nfunc newContainer(app provision.App) (*container, error) {\n\tappName := app.GetName()\n\tc := container{\n\t\tAppName: appName,\n\t\tType:    app.GetPlatform(),\n\t}\n\terr := c.create(app)\n\tif err != nil {\n\t\tlog.Printf(\"Error creating container %s\", appName)\n\t\tlog.Printf(\"Error was: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}\n\nfunc (c *container) inspect() (map[string]interface{}, error) {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout, err := runCmd(docker, \"inspect\", c.Id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar r map[string]interface{}\n\terr = json.Unmarshal([]byte(out), &r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}\n\n\/\/ hostPort returns the host port mapped for the container.\nfunc (c *container) hostPort() (string, error) {\n\tif c.Port == \"\" {\n\t\treturn \"\", errors.New(\"Container does not contain any mapped port\")\n\t}\n\tdata, err := c.inspect()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tmappedPorts := data[\"NetworkSettings\"].(map[string]interface{})[\"PortMapping\"].(map[string]interface{})\n\tif port, ok := mappedPorts[c.Port]; ok {\n\t\treturn port.(string), nil\n\t}\n\treturn \"\", fmt.Errorf(\"Container port %s is not mapped to any host port\", c.Port)\n}\n\n\/\/ ip returns the ip for the container.\nfunc (c *container) ip() (string, error) {\n\tresult, err := c.inspect()\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"error(%s) parsing json from docker when trying to get ipaddress\", err)\n\t\tlog.Print(msg)\n\t\treturn \"\", errors.New(msg)\n\t}\n\tif ns, ok := result[\"NetworkSettings\"]; !ok || ns == nil {\n\t\tmsg := \"Error when getting container information. NetworkSettings is missing.\"\n\t\tlog.Print(msg)\n\t\treturn \"\", errors.New(msg)\n\t}\n\tnetworkSettings := result[\"NetworkSettings\"].(map[string]interface{})\n\tinstanceIp := networkSettings[\"IpAddress\"].(string)\n\tif instanceIp == \"\" {\n\t\tmsg := \"error: Can't get ipaddress...\"\n\t\tlog.Print(msg)\n\t\treturn \"\", errors.New(msg)\n\t}\n\tlog.Printf(\"Instance IpAddress: %s\", instanceIp)\n\treturn instanceIp, nil\n}\n\n\/\/ create creates a docker container with base template by default.\n\/\/\n\/\/ It receives the application's platform in order to choose the correct\n\/\/ docker image and the repository to pass to the script that will take\n\/\/ care of the deploy, and a function to generate the correct command ran by\n\/\/ docker, which might be to deploy a container or to run and expose a\n\/\/ container for an application.\nfunc (c *container) create(app provision.App) error {\n\thostAddr, err := config.Get(\"docker:host-address\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd, port, err := runContainerCmd(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\tid, err := runCmd(cmd[0], cmd[1:]...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tid = strings.Replace(id, \"\\n\", \"\", -1)\n\tlog.Printf(\"docker id=%s\", id)\n\tc.Id = strings.TrimSpace(id)\n\tc.Port = port\n\tip, err := c.ip()\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Ip = ip\n\tcoll := collection()\n\tdefer coll.Database.Session.Close()\n\tif err := coll.Insert(c); err != nil {\n\t\tlog.Print(err)\n\t\treturn err\n\t}\n\tr, err := getRouter()\n\tif err != nil {\n\t\treturn err\n\t}\n\thostPort, err := c.hostPort()\n\tif err != nil {\n\t\thostPort = c.Port\n\t}\n\treturn r.AddRoute(app.GetName(), fmt.Sprintf(\"%s:%s\", hostAddr, hostPort))\n}\n\n\/\/ start starts a docker container.\nfunc (c *container) start() error {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Stating container %s\", c.Id)\n\tout, err := runCmd(docker, \"start\", c.Id)\n\tlog.Printf(\"docker start output: %s\", out)\n\treturn err\n}\n\n\/\/ stop stops a docker container.\nfunc (c *container) stop() error {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/TODO: better error handling\n\tlog.Printf(\"Stopping container %s\", c.Id)\n\toutput, err := runCmd(docker, \"stop\", c.Id)\n\tlog.Printf(\"docker stop output: %s\", output)\n\treturn err\n}\n\n\/\/ remove removes a docker container.\nfunc (c *container) remove() error {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Removing container %s from docker\", c.Id)\n\tout, err := runCmd(docker, \"rm\", c.Id)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to remove container from docker: %s\", err.Error())\n\t\tlog.Printf(\"Command output: %s\", out)\n\t\treturn err\n\t}\n\tlog.Printf(\"Removing container %s from database\", c.Id)\n\tcoll := collection()\n\tdefer coll.Database.Session.Close()\n\tif err := coll.RemoveId(c.Id); err != nil {\n\t\tlog.Printf(\"Failed to remove container from database: %s\", err.Error())\n\t\treturn err\n\t}\n\tr, err := getRouter()\n\tr.RemoveRoute(c.AppName)\n\treturn nil\n}\n\n\/\/ image represents a docker image.\ntype image struct {\n\tName string\n\tId   string\n}\n\n\/\/ repositoryName returns the image repository name for a given image.\n\/\/\n\/\/ Repository is a docker concept, the image actually does not have a name,\n\/\/ it has a repository, that is a composed name, e.g.: tsuru\/base.\n\/\/ Tsuru will always use a namespace, defined in tsuru.conf.\n\/\/ Additionally, tsuru will use the application's name to do that composition.\nfunc (img *image) repositoryName() string {\n\trepoNamespace, err := config.GetString(\"docker:repository-namespace\")\n\tif err != nil {\n\t\tlog.Printf(\"Tsuru is misconfigured. docker:repository-namespace config is missing.\")\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%s\/%s\", repoNamespace, img.Name)\n}\n\n\/\/ commit commits an image in docker\n\/\/\n\/\/ This is another docker concept, in order to generate an image from a container\n\/\/ one must commit it.\nfunc (img *image) commit(cId string) (string, error) {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\tlog.Printf(\"Tsuru is misconfigured. docker:binary config is missing.\")\n\t\treturn \"\", err\n\t}\n\tlog.Printf(\"attempting to commit image from container %s\", cId)\n\trName := img.repositoryName()\n\tid, err := runCmd(docker, \"commit\", cId, rName)\n\tif err != nil {\n\t\tlog.Printf(\"Could not commit docker image: %s\", err.Error())\n\t\treturn \"\", err\n\t}\n\timg.Id = strings.Replace(id, \"\\n\", \"\", -1)\n\tif err := imagesCollection().Insert(&img); err != nil {\n\t\tlog.Printf(\"Could not store image information %s\", err.Error())\n\t\treturn \"\", err\n\t}\n\treturn img.Id, nil\n}\n\n\/\/ remove removes an image from docker registry\nfunc (img *image) remove() error {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\tlog.Printf(\"Tsuru is misconfigured. docker:binary config is missing.\")\n\t\treturn err\n\t}\n\tlog.Printf(\"attempting to remove image %s from docker\", img.repositoryName())\n\t_, err = runCmd(docker, \"rmi\", img.Id)\n\tif err != nil {\n\t\tlog.Printf(\"Could not remove image %s from docker: %s\", img.Id, err.Error())\n\t\treturn err\n\t}\n\terr = imagesCollection().Remove(bson.M{\"name\": img.Name})\n\tif err != nil {\n\t\tlog.Printf(\"Could not remove image %s from mongo: %s\", img.Id, err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc getContainer(id string) (*container, error) {\n\tvar c container\n\tcoll := collection()\n\tdefer coll.Database.Session.Close()\n\terr := coll.Find(bson.M{\"_id\": id}).One(&c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}\n\nfunc getContainers(appName string) ([]container, error) {\n\tvar containers []container\n\terr := collection().Find(bson.M{\"appname\": appName}).All(&containers)\n\treturn containers, err\n}\n<commit_msg>provision\/docker\/docker: handling error when get router and removing route<commit_after>\/\/ Copyright 2013 tsuru authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage docker\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/globocom\/config\"\n\t\"github.com\/globocom\/tsuru\/fs\"\n\t\"github.com\/globocom\/tsuru\/log\"\n\t\"github.com\/globocom\/tsuru\/provision\"\n\t\"github.com\/globocom\/tsuru\/repository\"\n\t\"io\/ioutil\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\"\n\t\"strings\"\n)\n\nvar fsystem fs.Fs\n\nfunc filesystem() fs.Fs {\n\tif fsystem == nil {\n\t\tfsystem = fs.OsFs{}\n\t}\n\treturn fsystem\n}\n\n\/\/ runCmd executes commands and log the given stdout and stderror.\nfunc runCmd(cmd string, args ...string) (string, error) {\n\tout := bytes.Buffer{}\n\terr := executor().Execute(cmd, args, nil, &out, &out)\n\tlog.Printf(\"running the cmd: %s with the args: %s\", cmd, args)\n\treturn out.String(), err\n}\n\nfunc getSSHCommands() ([]string, error) {\n\taddKeyCommand, err := config.GetString(\"docker:ssh:add-key-cmd\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkeyFile, err := config.GetString(\"docker:ssh:public-key\")\n\tif err != nil {\n\t\tif u, err := user.Current(); err == nil {\n\t\t\tkeyFile = path.Join(u.HomeDir, \".ssh\", \"id_rsa.pub\")\n\t\t} else {\n\t\t\tkeyFile = os.ExpandEnv(\"${HOME}\/.ssh\/id_rsa.pub\")\n\t\t}\n\t}\n\tf, err := filesystem().Open(keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tkeyContent, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsshdPath, err := config.GetString(\"docker:ssh:sshd-path\")\n\tif err != nil {\n\t\tsshdPath = \"\/usr\/sbin\/sshd\"\n\t}\n\treturn []string{\n\t\tfmt.Sprintf(\"%s %s\", addKeyCommand, keyContent),\n\t\tsshdPath,\n\t}, nil\n}\n\nfunc runContainerCmd(app provision.App) ([]string, string, error) {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\trepoNamespace, err := config.GetString(\"docker:repository-namespace\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tdeployCmd, err := config.GetString(\"docker:deploy-cmd\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tappRepo := repository.GetReadOnlyUrl(app.GetName())\n\trunBin, err := config.GetString(\"docker:run-cmd:bin\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\trunArgs, err := config.GetString(\"docker:run-cmd:args\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tport, err := config.GetString(\"docker:run-cmd:port\")\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tcommands, err := getSSHCommands()\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\tcommands = append(commands, fmt.Sprintf(\"%s %s\", deployCmd, appRepo), fmt.Sprintf(\"%s %s\", runBin, runArgs))\n\timageName := fmt.Sprintf(\"%s\/%s\", repoNamespace, app.GetPlatform()) \/\/ TODO (flaviamissi): should use same algorithm as image.repositoryName\n\tcontainerCmd := strings.Join(commands, \" && \")\n\twholeCmd := []string{docker, \"run\", \"-d\", \"-t\", \"-p\", port, imageName, \"\/bin\/bash\", \"-c\", containerCmd}\n\treturn wholeCmd, port, nil\n}\n\ntype container struct {\n\tId      string `bson:\"_id\"`\n\tAppName string\n\tType    string\n\tIp      string\n\tPort    string\n}\n\n\/\/ newContainer creates a new container in Docker and stores it in the database.\n\/\/\n\/\/ TODO (flaviamissi): make it atomic\nfunc newContainer(app provision.App) (*container, error) {\n\tappName := app.GetName()\n\tc := container{\n\t\tAppName: appName,\n\t\tType:    app.GetPlatform(),\n\t}\n\terr := c.create(app)\n\tif err != nil {\n\t\tlog.Printf(\"Error creating container %s\", appName)\n\t\tlog.Printf(\"Error was: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}\n\nfunc (c *container) inspect() (map[string]interface{}, error) {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout, err := runCmd(docker, \"inspect\", c.Id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar r map[string]interface{}\n\terr = json.Unmarshal([]byte(out), &r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r, nil\n}\n\n\/\/ hostPort returns the host port mapped for the container.\nfunc (c *container) hostPort() (string, error) {\n\tif c.Port == \"\" {\n\t\treturn \"\", errors.New(\"Container does not contain any mapped port\")\n\t}\n\tdata, err := c.inspect()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tmappedPorts := data[\"NetworkSettings\"].(map[string]interface{})[\"PortMapping\"].(map[string]interface{})\n\tif port, ok := mappedPorts[c.Port]; ok {\n\t\treturn port.(string), nil\n\t}\n\treturn \"\", fmt.Errorf(\"Container port %s is not mapped to any host port\", c.Port)\n}\n\n\/\/ ip returns the ip for the container.\nfunc (c *container) ip() (string, error) {\n\tresult, err := c.inspect()\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"error(%s) parsing json from docker when trying to get ipaddress\", err)\n\t\tlog.Print(msg)\n\t\treturn \"\", errors.New(msg)\n\t}\n\tif ns, ok := result[\"NetworkSettings\"]; !ok || ns == nil {\n\t\tmsg := \"Error when getting container information. NetworkSettings is missing.\"\n\t\tlog.Print(msg)\n\t\treturn \"\", errors.New(msg)\n\t}\n\tnetworkSettings := result[\"NetworkSettings\"].(map[string]interface{})\n\tinstanceIp := networkSettings[\"IpAddress\"].(string)\n\tif instanceIp == \"\" {\n\t\tmsg := \"error: Can't get ipaddress...\"\n\t\tlog.Print(msg)\n\t\treturn \"\", errors.New(msg)\n\t}\n\tlog.Printf(\"Instance IpAddress: %s\", instanceIp)\n\treturn instanceIp, nil\n}\n\n\/\/ create creates a docker container with base template by default.\n\/\/\n\/\/ It receives the application's platform in order to choose the correct\n\/\/ docker image and the repository to pass to the script that will take\n\/\/ care of the deploy, and a function to generate the correct command ran by\n\/\/ docker, which might be to deploy a container or to run and expose a\n\/\/ container for an application.\nfunc (c *container) create(app provision.App) error {\n\thostAddr, err := config.Get(\"docker:host-address\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tcmd, port, err := runContainerCmd(app)\n\tif err != nil {\n\t\treturn err\n\t}\n\tid, err := runCmd(cmd[0], cmd[1:]...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tid = strings.Replace(id, \"\\n\", \"\", -1)\n\tlog.Printf(\"docker id=%s\", id)\n\tc.Id = strings.TrimSpace(id)\n\tc.Port = port\n\tip, err := c.ip()\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Ip = ip\n\tcoll := collection()\n\tdefer coll.Database.Session.Close()\n\tif err := coll.Insert(c); err != nil {\n\t\tlog.Print(err)\n\t\treturn err\n\t}\n\tr, err := getRouter()\n\tif err != nil {\n\t\treturn err\n\t}\n\thostPort, err := c.hostPort()\n\tif err != nil {\n\t\thostPort = c.Port\n\t}\n\treturn r.AddRoute(app.GetName(), fmt.Sprintf(\"%s:%s\", hostAddr, hostPort))\n}\n\n\/\/ start starts a docker container.\nfunc (c *container) start() error {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Stating container %s\", c.Id)\n\tout, err := runCmd(docker, \"start\", c.Id)\n\tlog.Printf(\"docker start output: %s\", out)\n\treturn err\n}\n\n\/\/ stop stops a docker container.\nfunc (c *container) stop() error {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/TODO: better error handling\n\tlog.Printf(\"Stopping container %s\", c.Id)\n\toutput, err := runCmd(docker, \"stop\", c.Id)\n\tlog.Printf(\"docker stop output: %s\", output)\n\treturn err\n}\n\n\/\/ remove removes a docker container.\nfunc (c *container) remove() error {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Removing container %s from docker\", c.Id)\n\tout, err := runCmd(docker, \"rm\", c.Id)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to remove container from docker: %s\", err.Error())\n\t\tlog.Printf(\"Command output: %s\", out)\n\t\treturn err\n\t}\n\tlog.Printf(\"Removing container %s from database\", c.Id)\n\tcoll := collection()\n\tdefer coll.Database.Session.Close()\n\tif err := coll.RemoveId(c.Id); err != nil {\n\t\tlog.Printf(\"Failed to remove container from database: %s\", err.Error())\n\t\treturn err\n\t}\n\tr, err := getRouter()\n\tif err != nil {\n\t\tlog.Printf(\"Failed to obtain router: %s\", err.Error())\n\t\treturn err\n\t}\n\tif err := r.RemoveRoute(c.AppName); err != nil {\n\t\tlog.Printf(\"Failed to remove route: %s\", err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ image represents a docker image.\ntype image struct {\n\tName string\n\tId   string\n}\n\n\/\/ repositoryName returns the image repository name for a given image.\n\/\/\n\/\/ Repository is a docker concept, the image actually does not have a name,\n\/\/ it has a repository, that is a composed name, e.g.: tsuru\/base.\n\/\/ Tsuru will always use a namespace, defined in tsuru.conf.\n\/\/ Additionally, tsuru will use the application's name to do that composition.\nfunc (img *image) repositoryName() string {\n\trepoNamespace, err := config.GetString(\"docker:repository-namespace\")\n\tif err != nil {\n\t\tlog.Printf(\"Tsuru is misconfigured. docker:repository-namespace config is missing.\")\n\t\treturn \"\"\n\t}\n\treturn fmt.Sprintf(\"%s\/%s\", repoNamespace, img.Name)\n}\n\n\/\/ commit commits an image in docker\n\/\/\n\/\/ This is another docker concept, in order to generate an image from a container\n\/\/ one must commit it.\nfunc (img *image) commit(cId string) (string, error) {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\tlog.Printf(\"Tsuru is misconfigured. docker:binary config is missing.\")\n\t\treturn \"\", err\n\t}\n\tlog.Printf(\"attempting to commit image from container %s\", cId)\n\trName := img.repositoryName()\n\tid, err := runCmd(docker, \"commit\", cId, rName)\n\tif err != nil {\n\t\tlog.Printf(\"Could not commit docker image: %s\", err.Error())\n\t\treturn \"\", err\n\t}\n\timg.Id = strings.Replace(id, \"\\n\", \"\", -1)\n\tif err := imagesCollection().Insert(&img); err != nil {\n\t\tlog.Printf(\"Could not store image information %s\", err.Error())\n\t\treturn \"\", err\n\t}\n\treturn img.Id, nil\n}\n\n\/\/ remove removes an image from docker registry\nfunc (img *image) remove() error {\n\tdocker, err := config.GetString(\"docker:binary\")\n\tif err != nil {\n\t\tlog.Printf(\"Tsuru is misconfigured. docker:binary config is missing.\")\n\t\treturn err\n\t}\n\tlog.Printf(\"attempting to remove image %s from docker\", img.repositoryName())\n\t_, err = runCmd(docker, \"rmi\", img.Id)\n\tif err != nil {\n\t\tlog.Printf(\"Could not remove image %s from docker: %s\", img.Id, err.Error())\n\t\treturn err\n\t}\n\terr = imagesCollection().Remove(bson.M{\"name\": img.Name})\n\tif err != nil {\n\t\tlog.Printf(\"Could not remove image %s from mongo: %s\", img.Id, err.Error())\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc getContainer(id string) (*container, error) {\n\tvar c container\n\tcoll := collection()\n\tdefer coll.Database.Session.Close()\n\terr := coll.Find(bson.M{\"_id\": id}).One(&c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &c, nil\n}\n\nfunc getContainers(appName string) ([]container, error) {\n\tvar containers []container\n\terr := collection().Find(bson.M{\"appname\": appName}).All(&containers)\n\treturn containers, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package util\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/spacemonkeygo\/errors\"\n\t\"github.com\/spacemonkeygo\/errors\/try\"\n\t\"polydawn.net\/repeatr\/def\"\n\t\"polydawn.net\/repeatr\/input\"\n\t\"polydawn.net\/repeatr\/io\"\n\t\"polydawn.net\/repeatr\/output\"\n)\n\n\/\/ Run inputs\nfunc ProvisionInputs(transmat integrity.Transmat, assemblerFn integrity.Assembler, inputs []def.Input, rootfs string, journal io.Writer) integrity.Assembly {\n\t\/\/ start having all filesystems\n\tfilesystems := make(map[def.Input]integrity.Arena, len(inputs))\n\tfsGather := make(chan map[def.Input]materializerReport)\n\tfor _, in := range inputs {\n\t\tgo func(in def.Input) {\n\t\t\ttry.Do(func() {\n\t\t\t\tfsGather <- map[def.Input]materializerReport{\n\t\t\t\t\tin: materializerReport{Arena: transmat.Materialize(\n\t\t\t\t\t\tintegrity.TransmatKind(in.Type),\n\t\t\t\t\t\tintegrity.CommitID(in.Hash),\n\t\t\t\t\t\t[]integrity.SiloURI{integrity.SiloURI(in.URI)},\n\t\t\t\t\t)},\n\t\t\t\t}\n\t\t\t}).Catch(input.Error, func(err *errors.Error) {\n\t\t\t\tfsGather <- map[def.Input]materializerReport{\n\t\t\t\t\tin: materializerReport{Err: err},\n\t\t\t\t}\n\t\t\t}).Done()\n\t\t}(in)\n\t}\n\n\t\/\/ (we don't have any output setup at this point, but if we do in the future, that'll be here.)\n\n\t\/\/ gather materialized inputs\n\tfor range inputs {\n\t\tfor in, report := range <-fsGather {\n\t\t\tif report.Err != nil {\n\t\t\t\tpanic(report.Err)\n\t\t\t}\n\t\t\tfilesystems[in] = report.Arena\n\t\t}\n\t}\n\n\t\/\/ assemble them into the final tree\n\tassemblyParts := make([]integrity.AssemblyPart, 0, len(filesystems))\n\tfor input, arena := range filesystems {\n\t\tassemblyParts = append(assemblyParts, integrity.AssemblyPart{\n\t\t\tSourcePath: arena.Path(),\n\t\t\tTargetPath: input.Location,\n\t\t\tWritable:   true, \/\/ TODO input config should have a word about this\n\t\t})\n\t}\n\tassembly := assemblerFn(rootfs, assemblyParts)\n\treturn assembly\n}\n\ntype materializerReport struct {\n\tArena integrity.Arena \/\/ if success\n\tErr   *errors.Error   \/\/ subtype of input.Error.  (others are forbidden by contract and treated as fatal.)\n}\n\n\/\/ Output folders should exist\n\/\/ TODO: discussion\nfunc ProvisionOutputs(outputs []def.Output, rootfs string, journal io.Writer) {\n\tfor _, output := range outputs {\n\t\tpath := filepath.Join(rootfs, output.Location)\n\t\terr := os.MkdirAll(path, 0755)\n\t\tif err != nil {\n\t\t\tpanic(errors.IOError.Wrap(err))\n\t\t}\n\t}\n}\n\n\/\/ Run outputs\n\/\/ TODO: run all simultaneously, waitgroup out the errors\nfunc PreserveOutputs(transmat integrity.Transmat, outputs []def.Output, rootfs string, journal io.Writer) []def.Output {\n\t\/\/ run commit on the outputs\n\tscanGather := make(chan scanReport)\n\tfor _, out := range outputs {\n\t\tgo func() {\n\t\t\ttry.Do(func() {\n\t\t\t\tcommitID := transmat.Scan(\n\t\t\t\t\tintegrity.TransmatKind(out.Type),\n\t\t\t\t\tfilepath.Join(rootfs, out.Location),\n\t\t\t\t\t[]integrity.SiloURI{integrity.SiloURI(out.URI)},\n\t\t\t\t)\n\t\t\t\tout.Hash = string(commitID)\n\t\t\t\tscanGather <- scanReport{Output: out}\n\t\t\t}).Catch(output.Error, func(err *errors.Error) {\n\t\t\t\tscanGather <- scanReport{Err: err}\n\t\t\t}).Done()\n\t\t}()\n\t}\n\n\t\/\/ gather reports\n\tvar results []def.Output\n\tfor report := range scanGather {\n\t\tif report.Err != nil {\n\t\t\tpanic(report.Err)\n\t\t}\n\t\tresults = append(results, report.Output)\n\t}\n\n\treturn results\n}\n\ntype scanReport struct {\n\tOutput def.Output    \/\/ now including the hash\n\tErr    *errors.Error \/\/ subtype of output.Error.  (others are forbidden by contract and treated as fatal.)\n}\n<commit_msg>Fix data race and don't block forever on a channel we don't close.<commit_after>package util\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/spacemonkeygo\/errors\"\n\t\"github.com\/spacemonkeygo\/errors\/try\"\n\t\"polydawn.net\/repeatr\/def\"\n\t\"polydawn.net\/repeatr\/input\"\n\t\"polydawn.net\/repeatr\/io\"\n\t\"polydawn.net\/repeatr\/output\"\n)\n\n\/\/ Run inputs\nfunc ProvisionInputs(transmat integrity.Transmat, assemblerFn integrity.Assembler, inputs []def.Input, rootfs string, journal io.Writer) integrity.Assembly {\n\t\/\/ start having all filesystems\n\tfilesystems := make(map[def.Input]integrity.Arena, len(inputs))\n\tfsGather := make(chan map[def.Input]materializerReport)\n\tfor _, in := range inputs {\n\t\tgo func(in def.Input) {\n\t\t\ttry.Do(func() {\n\t\t\t\tfsGather <- map[def.Input]materializerReport{\n\t\t\t\t\tin: materializerReport{Arena: transmat.Materialize(\n\t\t\t\t\t\tintegrity.TransmatKind(in.Type),\n\t\t\t\t\t\tintegrity.CommitID(in.Hash),\n\t\t\t\t\t\t[]integrity.SiloURI{integrity.SiloURI(in.URI)},\n\t\t\t\t\t)},\n\t\t\t\t}\n\t\t\t}).Catch(input.Error, func(err *errors.Error) {\n\t\t\t\tfsGather <- map[def.Input]materializerReport{\n\t\t\t\t\tin: materializerReport{Err: err},\n\t\t\t\t}\n\t\t\t}).Done()\n\t\t}(in)\n\t}\n\n\t\/\/ (we don't have any output setup at this point, but if we do in the future, that'll be here.)\n\n\t\/\/ gather materialized inputs\n\tfor range inputs {\n\t\tfor in, report := range <-fsGather {\n\t\t\tif report.Err != nil {\n\t\t\t\tpanic(report.Err)\n\t\t\t}\n\t\t\tfilesystems[in] = report.Arena\n\t\t}\n\t}\n\n\t\/\/ assemble them into the final tree\n\tassemblyParts := make([]integrity.AssemblyPart, 0, len(filesystems))\n\tfor input, arena := range filesystems {\n\t\tassemblyParts = append(assemblyParts, integrity.AssemblyPart{\n\t\t\tSourcePath: arena.Path(),\n\t\t\tTargetPath: input.Location,\n\t\t\tWritable:   true, \/\/ TODO input config should have a word about this\n\t\t})\n\t}\n\tassembly := assemblerFn(rootfs, assemblyParts)\n\treturn assembly\n}\n\ntype materializerReport struct {\n\tArena integrity.Arena \/\/ if success\n\tErr   *errors.Error   \/\/ subtype of input.Error.  (others are forbidden by contract and treated as fatal.)\n}\n\n\/\/ Output folders should exist\n\/\/ TODO: discussion\nfunc ProvisionOutputs(outputs []def.Output, rootfs string, journal io.Writer) {\n\tfor _, output := range outputs {\n\t\tpath := filepath.Join(rootfs, output.Location)\n\t\terr := os.MkdirAll(path, 0755)\n\t\tif err != nil {\n\t\t\tpanic(errors.IOError.Wrap(err))\n\t\t}\n\t}\n}\n\n\/\/ Run outputs\n\/\/ TODO: run all simultaneously, waitgroup out the errors\nfunc PreserveOutputs(transmat integrity.Transmat, outputs []def.Output, rootfs string, journal io.Writer) []def.Output {\n\t\/\/ run commit on the outputs\n\tscanGather := make(chan scanReport)\n\tfor _, out := range outputs {\n\t\tgo func(out def.Output) {\n\t\t\tscanPath := filepath.Join(rootfs, out.Location)\n\t\t\tfmt.Fprintf(journal, \"Starting scan on %q\\n\", scanPath)\n\t\t\ttry.Do(func() {\n\t\t\t\tcommitID := transmat.Scan(\n\t\t\t\t\tintegrity.TransmatKind(out.Type),\n\t\t\t\t\tscanPath,\n\t\t\t\t\t[]integrity.SiloURI{integrity.SiloURI(out.URI)},\n\t\t\t\t)\n\t\t\t\tout.Hash = string(commitID)\n\t\t\t\tfmt.Fprintf(journal, \"Finished scan on %q\\n\", scanPath)\n\t\t\t\tscanGather <- scanReport{Output: out}\n\t\t\t}).Catch(output.Error, func(err *errors.Error) {\n\t\t\t\tfmt.Fprintf(journal, \"Errored scan on %q\\n\", scanPath)\n\t\t\t\tscanGather <- scanReport{Err: err}\n\t\t\t}).Done()\n\t\t}(out)\n\t}\n\n\t\/\/ gather reports\n\tvar results []def.Output\n\tfor range outputs {\n\t\treport := <-scanGather\n\t\tif report.Err != nil {\n\t\t\tpanic(report.Err)\n\t\t}\n\t\tresults = append(results, report.Output)\n\t}\n\n\treturn results\n}\n\ntype scanReport struct {\n\tOutput def.Output    \/\/ now including the hash\n\tErr    *errors.Error \/\/ subtype of output.Error.  (others are forbidden by contract and treated as fatal.)\n}\n<|endoftext|>"}
{"text":"<commit_before>package experiments\n\nvar experiments = make(map[string]bool)\n\n\/\/ Enable a particular experiment in the agent\nfunc Enable(experiment string) {\n\texperiments[experiment] = true\n}\n\n\/\/ Disable a particular experiment in the agent\nfunc Disable(experiment string) {\n\tdelete(experiments, experiment)\n}\n\n\/\/ IsEnabled returns whether the named experiment is enabled\nfunc IsEnabled(experiment string) bool {\n\treturn experiments[experiment] \/\/ map[T]bool returns false for missing keys\n}\n\n\/\/ Enabled returns the keys of all the enabled experiments\nfunc Enabled() []string {\n\tvar enabled []string\n\tfor exp, ok := range experiments {\n\t\tif ok {\n\t\t\tenabled = append(enabled, exp)\n\t\t}\n\t}\n\treturn enabled\n}\n<commit_msg>experiments: local var name refactor<commit_after>package experiments\n\nvar experiments = make(map[string]bool)\n\n\/\/ Enable a particular experiment in the agent\nfunc Enable(key string) {\n\texperiments[key] = true\n}\n\n\/\/ Disable a particular experiment in the agent\nfunc Disable(key string) {\n\tdelete(experiments, key)\n}\n\n\/\/ IsEnabled returns whether the named experiment is enabled\nfunc IsEnabled(key string) bool {\n\treturn experiments[key] \/\/ map[T]bool returns false for missing keys\n}\n\n\/\/ Enabled returns the keys of all the enabled experiments\nfunc Enabled() []string {\n\tvar keys []string\n\tfor key, enabled := range experiments {\n\t\tif enabled {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t}\n\treturn keys\n}\n<|endoftext|>"}
{"text":"<commit_before>package experiments\n\nvar experiments = make(map[string]bool)\n\n\/\/ Enable a particular experiment in the agent\nfunc Enable(experiment string) {\n\texperiments[experiment] = true\n}\n\n\/\/ Disable a particular experiment in the agent\nfunc Disable(experiment string) {\n\tdelete(experiments, experiment)\n}\n\n\/\/ Check if an experiment has been enabled\nfunc IsEnabled(experiment string) bool {\n\tif val, ok := experiments[experiment]; ok {\n\t\treturn val\n\t} else {\n\t\treturn false\n\t}\n}\n\n\/\/ Enabled returns the keys of all the enabled experiments\nfunc Enabled() []string {\n\tvar enabled []string\n\tfor exp, ok := range experiments {\n\t\tif ok {\n\t\t\tenabled = append(enabled, exp)\n\t\t}\n\t}\n\treturn enabled\n}\n<commit_msg>experiments.IsEnabled() simplified using map's zero value.<commit_after>package experiments\n\nvar experiments = make(map[string]bool)\n\n\/\/ Enable a particular experiment in the agent\nfunc Enable(experiment string) {\n\texperiments[experiment] = true\n}\n\n\/\/ Disable a particular experiment in the agent\nfunc Disable(experiment string) {\n\tdelete(experiments, experiment)\n}\n\n\/\/ IsEnabled returns whether the named experiment is enabled\nfunc IsEnabled(experiment string) bool {\n\treturn experiments[experiment] \/\/ map[T]bool returns false for missing keys\n}\n\n\/\/ Enabled returns the keys of all the enabled experiments\nfunc Enabled() []string {\n\tvar enabled []string\n\tfor exp, ok := range experiments {\n\t\tif ok {\n\t\t\tenabled = append(enabled, exp)\n\t\t}\n\t}\n\treturn enabled\n}\n<|endoftext|>"}
{"text":"<commit_before>package discovery\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tbh \"github.com\/kandoo\/beehive\"\n\t\"github.com\/kandoo\/beehive-netctrl\/net\/ethernet\"\n\t\"github.com\/kandoo\/beehive-netctrl\/nom\"\n\t\"github.com\/kandoo\/beehive\/Godeps\/_workspace\/src\/github.com\/golang\/glog\"\n)\n\ntype LinkDiscovered struct {\n}\n\nconst (\n\tnodeDict = \"N\"\n)\n\ntype nodePortsAndLinks struct {\n\tN nom.Node\n\tP []nom.Port\n\tL []nom.Link\n}\n\nfunc (np *nodePortsAndLinks) hasPort(port nom.Port) bool {\n\tfor _, p := range np.P {\n\t\tif p.ID == port.ID {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (np *nodePortsAndLinks) removePort(port nom.Port) bool {\n\tfor i, p := range np.P {\n\t\tif p.ID == port.ID {\n\t\t\tnp.P = append(np.P[:i], np.P[i+1:]...)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (np *nodePortsAndLinks) linkFrom(from nom.UID) (nom.Link, bool) {\n\tfor _, l := range np.L {\n\t\tif l.From == from {\n\t\t\treturn l, true\n\t\t}\n\t}\n\treturn nom.Link{}, false\n}\n\nfunc (np *nodePortsAndLinks) hasLinkFrom(from nom.UID) bool {\n\t_, ok := np.linkFrom(from)\n\treturn ok\n}\n\nfunc (np *nodePortsAndLinks) hasLink(link nom.Link) bool {\n\tid := link.UID()\n\tfor _, l := range np.L {\n\t\tif l.UID() == id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (np *nodePortsAndLinks) removeLink(link nom.Link) bool {\n\tfor i, l := range np.L {\n\t\tif l.From == link.From {\n\t\t\tnp.L = append(np.L[:i], np.L[i+1:]...)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\ntype nodeJoinedHandler struct{}\n\nfunc (h *nodeJoinedHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tjoined := msg.Data().(nom.NodeJoined)\n\td := ctx.Dict(nodeDict)\n\tn := nom.Node(joined)\n\tk := string(n.UID())\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\tglog.Warningf(\"%v rejoins\", n)\n\t}\n\tnp.N = n\n\t\/\/ TODO(soheil): Add a flow entry to forward lldp packets to the controller.\n\treturn d.PutGob(k, &np)\n}\n\nfunc (h *nodeJoinedHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(nom.Node(msg.Data().(nom.NodeJoined)).UID())},\n\t}\n}\n\ntype nodeLeftHandler struct{}\n\nfunc (h *nodeLeftHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tn := nom.Node(msg.Data().(nom.NodeLeft))\n\td := ctx.Dict(nodeDict)\n\tk := string(n.UID())\n\tif _, err := d.Get(k); err != nil {\n\t\treturn fmt.Errorf(\"%v is not joined\", n)\n\t}\n\td.Del(k)\n\treturn nil\n}\n\nfunc (h *nodeLeftHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(nom.Node(msg.Data().(nom.NodeLeft)).UID())},\n\t}\n}\n\ntype portUpdateHandler struct{}\n\nfunc (h *portUpdateHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tp := nom.Port(msg.Data().(nom.PortUpdated))\n\td := ctx.Dict(nodeDict)\n\tk := string(p.Node)\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\tglog.Warningf(\"%v added before its node\", p)\n\t\tctx.Snooze(1 * time.Second)\n\t\treturn nil\n\t}\n\n\tif np.hasPort(p) {\n\t\tglog.Warningf(\"%v readded\")\n\t\tnp.removePort(p)\n\t}\n\n\tsendLLDPPacket(np.N, p, ctx)\n\n\tnp.P = append(np.P, p)\n\treturn d.PutGob(k, &np)\n}\n\nfunc (h *portUpdateHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(msg.Data().(nom.PortUpdated).Node)},\n\t}\n}\n\ntype lldpTimeout struct{}\n\ntype timeoutHandler struct{}\n\nfunc (h *timeoutHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\td := ctx.Dict(nodeDict)\n\td.ForEach(func(k string, v []byte) {\n\t\tvar np nodePortsAndLinks\n\t\tif err := nom.ObjGoDecode(&np, v); err != nil {\n\t\t\tglog.Errorf(\"Error in decoding value: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tfor _, p := range np.P {\n\t\t\tsendLLDPPacket(np.N, p, ctx)\n\t\t}\n\t})\n\treturn nil\n}\n\nfunc (h *timeoutHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{}\n}\n\ntype pktInHandler struct{}\n\nfunc (h *pktInHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tpin := msg.Data().(nom.PacketIn)\n\te := ethernet.NewEthernetWithBuf([]byte(pin.Packet))\n\tif e.Type() != uint16(ethernet.ETH_T_LLDP) {\n\t\treturn nil\n\t}\n\n\t_, port, err := decodeLLDP([]byte(pin.Packet))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td := ctx.Dict(nodeDict)\n\tk := string(pin.Node)\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\treturn fmt.Errorf(\"Node %v not found\", pin.Node)\n\t}\n\n\tl := nom.Link{\n\t\tID:    nom.LinkID(port.UID()),\n\t\tFrom:  pin.InPort,\n\t\tTo:    []nom.UID{port.UID()},\n\t\tState: nom.LinkStateUp,\n\t}\n\tctx.Emit(NewLink(l))\n\n\tl = nom.Link{\n\t\tID:    nom.LinkID(pin.InPort),\n\t\tFrom:  port.UID(),\n\t\tTo:    []nom.UID{pin.InPort},\n\t\tState: nom.LinkStateUp,\n\t}\n\tctx.Emit(NewLink(l))\n\n\treturn nil\n}\n\nfunc (h *pktInHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(msg.Data().(nom.PacketIn).Node)},\n\t}\n}\n\ntype NewLink nom.Link\n\ntype newLinkHandler struct{}\n\nfunc (h *newLinkHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tl := nom.Link(msg.Data().(NewLink))\n\tn, _ := nom.ParsePortUID(l.From)\n\td := ctx.Dict(nodeDict)\n\tk := string(n)\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\treturn err\n\t}\n\n\tif oldl, ok := np.linkFrom(l.From); ok {\n\t\tif oldl.UID() == l.UID() {\n\t\t\treturn nil\n\t\t}\n\t\tnp.removeLink(oldl)\n\t\tctx.Emit(nom.LinkRemoved(oldl))\n\t}\n\n\tglog.V(2).Infof(\"Link detected %v\", l)\n\tctx.Emit(nom.LinkAdded(l))\n\tnp.L = append(np.L, l)\n\treturn d.PutGob(k, &np)\n}\n\nfunc (h *newLinkHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\tn, _ := nom.ParsePortUID(msg.Data().(NewLink).From)\n\treturn bh.MappedCells{{nodeDict, string(n)}}\n}\n\n\/\/ RegisterDiscovery registers the handlers for topology discovery on the hive.\nfunc RegisterDiscovery(h bh.Hive) {\n\ta := h.NewApp(\"discovery\")\n\ta.Handle(nom.NodeJoined{}, &nodeJoinedHandler{})\n\ta.Handle(nom.NodeLeft{}, &nodeLeftHandler{})\n\ta.Handle(nom.PortUpdated{}, &portUpdateHandler{})\n\t\/\/ TODO(soheil): Handle PortRemoved.\n\ta.Handle(nom.PacketIn{}, &pktInHandler{})\n\ta.Handle(NewLink{}, &newLinkHandler{})\n\ta.Handle(lldpTimeout{}, &timeoutHandler{})\n\tgo func() {\n\t\tfor {\n\t\t\th.Emit(lldpTimeout{})\n\t\t\ttime.Sleep(60 * time.Second)\n\t\t}\n\t}()\n}\n<commit_msg>Remove LinkDiscovered<commit_after>package discovery\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tbh \"github.com\/kandoo\/beehive\"\n\t\"github.com\/kandoo\/beehive-netctrl\/net\/ethernet\"\n\t\"github.com\/kandoo\/beehive-netctrl\/nom\"\n\t\"github.com\/kandoo\/beehive\/Godeps\/_workspace\/src\/github.com\/golang\/glog\"\n)\n\nconst (\n\tnodeDict = \"N\"\n)\n\ntype nodePortsAndLinks struct {\n\tN nom.Node\n\tP []nom.Port\n\tL []nom.Link\n}\n\nfunc (np *nodePortsAndLinks) hasPort(port nom.Port) bool {\n\tfor _, p := range np.P {\n\t\tif p.ID == port.ID {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (np *nodePortsAndLinks) removePort(port nom.Port) bool {\n\tfor i, p := range np.P {\n\t\tif p.ID == port.ID {\n\t\t\tnp.P = append(np.P[:i], np.P[i+1:]...)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (np *nodePortsAndLinks) linkFrom(from nom.UID) (nom.Link, bool) {\n\tfor _, l := range np.L {\n\t\tif l.From == from {\n\t\t\treturn l, true\n\t\t}\n\t}\n\treturn nom.Link{}, false\n}\n\nfunc (np *nodePortsAndLinks) hasLinkFrom(from nom.UID) bool {\n\t_, ok := np.linkFrom(from)\n\treturn ok\n}\n\nfunc (np *nodePortsAndLinks) hasLink(link nom.Link) bool {\n\tid := link.UID()\n\tfor _, l := range np.L {\n\t\tif l.UID() == id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (np *nodePortsAndLinks) removeLink(link nom.Link) bool {\n\tfor i, l := range np.L {\n\t\tif l.From == link.From {\n\t\t\tnp.L = append(np.L[:i], np.L[i+1:]...)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\ntype nodeJoinedHandler struct{}\n\nfunc (h *nodeJoinedHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tjoined := msg.Data().(nom.NodeJoined)\n\td := ctx.Dict(nodeDict)\n\tn := nom.Node(joined)\n\tk := string(n.UID())\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\tglog.Warningf(\"%v rejoins\", n)\n\t}\n\tnp.N = n\n\t\/\/ TODO(soheil): Add a flow entry to forward lldp packets to the controller.\n\treturn d.PutGob(k, &np)\n}\n\nfunc (h *nodeJoinedHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(nom.Node(msg.Data().(nom.NodeJoined)).UID())},\n\t}\n}\n\ntype nodeLeftHandler struct{}\n\nfunc (h *nodeLeftHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tn := nom.Node(msg.Data().(nom.NodeLeft))\n\td := ctx.Dict(nodeDict)\n\tk := string(n.UID())\n\tif _, err := d.Get(k); err != nil {\n\t\treturn fmt.Errorf(\"%v is not joined\", n)\n\t}\n\td.Del(k)\n\treturn nil\n}\n\nfunc (h *nodeLeftHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(nom.Node(msg.Data().(nom.NodeLeft)).UID())},\n\t}\n}\n\ntype portUpdateHandler struct{}\n\nfunc (h *portUpdateHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tp := nom.Port(msg.Data().(nom.PortUpdated))\n\td := ctx.Dict(nodeDict)\n\tk := string(p.Node)\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\tglog.Warningf(\"%v added before its node\", p)\n\t\tctx.Snooze(1 * time.Second)\n\t\treturn nil\n\t}\n\n\tif np.hasPort(p) {\n\t\tglog.Warningf(\"%v readded\")\n\t\tnp.removePort(p)\n\t}\n\n\tsendLLDPPacket(np.N, p, ctx)\n\n\tnp.P = append(np.P, p)\n\treturn d.PutGob(k, &np)\n}\n\nfunc (h *portUpdateHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(msg.Data().(nom.PortUpdated).Node)},\n\t}\n}\n\ntype lldpTimeout struct{}\n\ntype timeoutHandler struct{}\n\nfunc (h *timeoutHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\td := ctx.Dict(nodeDict)\n\td.ForEach(func(k string, v []byte) {\n\t\tvar np nodePortsAndLinks\n\t\tif err := nom.ObjGoDecode(&np, v); err != nil {\n\t\t\tglog.Errorf(\"Error in decoding value: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tfor _, p := range np.P {\n\t\t\tsendLLDPPacket(np.N, p, ctx)\n\t\t}\n\t})\n\treturn nil\n}\n\nfunc (h *timeoutHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{}\n}\n\ntype pktInHandler struct{}\n\nfunc (h *pktInHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tpin := msg.Data().(nom.PacketIn)\n\te := ethernet.NewEthernetWithBuf([]byte(pin.Packet))\n\tif e.Type() != uint16(ethernet.ETH_T_LLDP) {\n\t\treturn nil\n\t}\n\n\t_, port, err := decodeLLDP([]byte(pin.Packet))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td := ctx.Dict(nodeDict)\n\tk := string(pin.Node)\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\treturn fmt.Errorf(\"Node %v not found\", pin.Node)\n\t}\n\n\tl := nom.Link{\n\t\tID:    nom.LinkID(port.UID()),\n\t\tFrom:  pin.InPort,\n\t\tTo:    []nom.UID{port.UID()},\n\t\tState: nom.LinkStateUp,\n\t}\n\tctx.Emit(NewLink(l))\n\n\tl = nom.Link{\n\t\tID:    nom.LinkID(pin.InPort),\n\t\tFrom:  port.UID(),\n\t\tTo:    []nom.UID{pin.InPort},\n\t\tState: nom.LinkStateUp,\n\t}\n\tctx.Emit(NewLink(l))\n\n\treturn nil\n}\n\nfunc (h *pktInHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(msg.Data().(nom.PacketIn).Node)},\n\t}\n}\n\ntype NewLink nom.Link\n\ntype newLinkHandler struct{}\n\nfunc (h *newLinkHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tl := nom.Link(msg.Data().(NewLink))\n\tn, _ := nom.ParsePortUID(l.From)\n\td := ctx.Dict(nodeDict)\n\tk := string(n)\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\treturn err\n\t}\n\n\tif oldl, ok := np.linkFrom(l.From); ok {\n\t\tif oldl.UID() == l.UID() {\n\t\t\treturn nil\n\t\t}\n\t\tnp.removeLink(oldl)\n\t\tctx.Emit(nom.LinkRemoved(oldl))\n\t}\n\n\tglog.V(2).Infof(\"Link detected %v\", l)\n\tctx.Emit(nom.LinkAdded(l))\n\tnp.L = append(np.L, l)\n\treturn d.PutGob(k, &np)\n}\n\nfunc (h *newLinkHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\tn, _ := nom.ParsePortUID(msg.Data().(NewLink).From)\n\treturn bh.MappedCells{{nodeDict, string(n)}}\n}\n\n\/\/ RegisterDiscovery registers the handlers for topology discovery on the hive.\nfunc RegisterDiscovery(h bh.Hive) {\n\ta := h.NewApp(\"discovery\")\n\ta.Handle(nom.NodeJoined{}, &nodeJoinedHandler{})\n\ta.Handle(nom.NodeLeft{}, &nodeLeftHandler{})\n\ta.Handle(nom.PortUpdated{}, &portUpdateHandler{})\n\t\/\/ TODO(soheil): Handle PortRemoved.\n\ta.Handle(nom.PacketIn{}, &pktInHandler{})\n\ta.Handle(NewLink{}, &newLinkHandler{})\n\ta.Handle(lldpTimeout{}, &timeoutHandler{})\n\tgo func() {\n\t\tfor {\n\t\t\th.Emit(lldpTimeout{})\n\t\t\ttime.Sleep(60 * time.Second)\n\t\t}\n\t}()\n}\n<|endoftext|>"}
{"text":"<commit_before>package discovery\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/kandoo\/beehive\/Godeps\/_workspace\/src\/github.com\/golang\/glog\"\n\tbh \"github.com\/kandoo\/beehive\"\n\t\"github.com\/kandoo\/beehive-netctrl\/net\/ethernet\"\n\t\"github.com\/kandoo\/beehive-netctrl\/nom\"\n)\n\ntype LinkDiscovered struct {\n}\n\nconst (\n\tnodeDict = \"N\"\n)\n\ntype nodePortsAndLinks struct {\n\tN nom.Node\n\tP []nom.Port\n\tL []nom.Link\n}\n\nfunc (np *nodePortsAndLinks) hasPort(port nom.Port) bool {\n\tfor _, p := range np.P {\n\t\tif p.ID == port.ID {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (np *nodePortsAndLinks) removePort(port nom.Port) bool {\n\tfor i, p := range np.P {\n\t\tif p.ID == port.ID {\n\t\t\tnp.P = append(np.P[:i], np.P[i+1:]...)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (np *nodePortsAndLinks) hasLinkFrom(from nom.UID) bool {\n\tfor _, l := range np.L {\n\t\tif l.From == from {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (np *nodePortsAndLinks) hasLink(link nom.Link) bool {\n\tid := link.UID()\n\tfor _, l := range np.L {\n\t\tif l.UID() == id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (np *nodePortsAndLinks) removeLink(link nom.Link) bool {\n\tfor i, l := range np.L {\n\t\tif l.From == link.From {\n\t\t\tnp.L = append(np.L[:i], np.L[i+1:]...)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\ntype nodeJoinedHandler struct{}\n\nfunc (h *nodeJoinedHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tjoined := msg.Data().(nom.NodeJoined)\n\td := ctx.Dict(nodeDict)\n\tn := nom.Node(joined)\n\tk := string(n.UID())\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\tglog.Warningf(\"%v rejoins\", n)\n\t}\n\tnp.N = n\n\t\/\/ TODO(soheil): Add a flow entry to forward lldp packets to the controller.\n\treturn d.PutGob(k, &np)\n}\n\nfunc (h *nodeJoinedHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(nom.Node(msg.Data().(nom.NodeJoined)).UID())},\n\t}\n}\n\ntype nodeLeftHandler struct{}\n\nfunc (h *nodeLeftHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tn := nom.Node(msg.Data().(nom.NodeLeft))\n\td := ctx.Dict(nodeDict)\n\tk := string(n.UID())\n\tif _, err := d.Get(k); err != nil {\n\t\treturn fmt.Errorf(\"%v is not joined\", n)\n\t}\n\td.Del(k)\n\treturn nil\n}\n\nfunc (h *nodeLeftHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(nom.Node(msg.Data().(nom.NodeLeft)).UID())},\n\t}\n}\n\ntype portUpdateHandler struct{}\n\nfunc (h *portUpdateHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tp := nom.Port(msg.Data().(nom.PortUpdated))\n\td := ctx.Dict(nodeDict)\n\tk := string(p.Node)\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\tglog.Warningf(\"%v added before its node\", p)\n\t\tctx.Snooze(1 * time.Second)\n\t\treturn nil\n\t}\n\n\tif np.hasPort(p) {\n\t\tglog.Warningf(\"%v readded\")\n\t\tnp.removePort(p)\n\t}\n\n\tsendLLDPPacket(np.N, p, ctx)\n\n\tnp.P = append(np.P, p)\n\treturn d.PutGob(k, &np)\n}\n\nfunc (h *portUpdateHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(msg.Data().(nom.PortUpdated).Node)},\n\t}\n}\n\ntype lldpTimeout struct{}\n\ntype timeoutHandler struct{}\n\nfunc (h *timeoutHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\td := ctx.Dict(nodeDict)\n\td.ForEach(func(k string, v []byte) {\n\t\tvar np nodePortsAndLinks\n\t\tif err := nom.ObjGoDecode(&np, v); err != nil {\n\t\t\tglog.Errorf(\"Error in decoding value: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tfor _, p := range np.P {\n\t\t\tsendLLDPPacket(np.N, p, ctx)\n\t\t}\n\t})\n\treturn nil\n}\n\nfunc (h *timeoutHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{}\n}\n\ntype pktInHandler struct{}\n\nfunc (h *pktInHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tpin := msg.Data().(nom.PacketIn)\n\te := ethernet.NewEthernetWithBuf([]byte(pin.Packet))\n\tif e.Type() != uint16(ethernet.ETH_T_LLDP) {\n\t\treturn nil\n\t}\n\n\t_, port, err := decodeLLDP([]byte(pin.Packet))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td := ctx.Dict(nodeDict)\n\tk := string(pin.Node)\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\treturn fmt.Errorf(\"Node %v not found\", pin.Node)\n\t}\n\n\tl := nom.Link{\n\t\tID:    nom.LinkID(port.UID()),\n\t\tFrom:  pin.InPort,\n\t\tTo:    []nom.UID{port.UID()},\n\t\tState: nom.LinkStateUp,\n\t}\n\tctx.Emit(NewLink(l))\n\n\tl = nom.Link{\n\t\tID:    nom.LinkID(pin.InPort),\n\t\tFrom:  port.UID(),\n\t\tTo:    []nom.UID{pin.InPort},\n\t\tState: nom.LinkStateUp,\n\t}\n\tctx.Emit(NewLink(l))\n\n\treturn nil\n}\n\nfunc (h *pktInHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(msg.Data().(nom.PacketIn).Node)},\n\t}\n}\n\ntype NewLink nom.Link\n\ntype newLinkHandler struct{}\n\nfunc (h *newLinkHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tl := nom.Link(msg.Data().(NewLink))\n\tn, _ := nom.ParsePortUID(l.From)\n\td := ctx.Dict(nodeDict)\n\tk := string(n)\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\treturn err\n\t}\n\n\tif np.hasLinkFrom(l.From) {\n\t\tif np.hasLink(l) {\n\t\t\treturn nil\n\t\t}\n\t\tnp.removeLink(l)\n\t\tctx.Emit(nom.LinkRemoved(l))\n\t}\n\n\tglog.V(2).Infof(\"Link detected %v\", l)\n\tctx.Emit(nom.LinkAdded(l))\n\tnp.L = append(np.L, l)\n\treturn d.PutGob(k, &np)\n}\n\nfunc (h *newLinkHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\tn, _ := nom.ParsePortUID(msg.Data().(NewLink).From)\n\treturn bh.MappedCells{{nodeDict, string(n)}}\n}\n\n\/\/ RegisterDiscovery registers the handlers for topology discovery on the hive.\nfunc RegisterDiscovery(h bh.Hive) {\n\ta := h.NewApp(\"discovery\")\n\ta.Handle(nom.NodeJoined{}, &nodeJoinedHandler{})\n\ta.Handle(nom.NodeLeft{}, &nodeLeftHandler{})\n\ta.Handle(nom.PortUpdated{}, &portUpdateHandler{})\n\t\/\/ TODO(soheil): Handle PortRemoved.\n\ta.Handle(nom.PacketIn{}, &pktInHandler{})\n\ta.Handle(NewLink{}, &newLinkHandler{})\n\ta.Handle(lldpTimeout{}, &timeoutHandler{})\n\tgo func() {\n\t\tfor {\n\t\t\th.Emit(lldpTimeout{})\n\t\t\ttime.Sleep(60 * time.Second)\n\t\t}\n\t}()\n}\n<commit_msg>Fix spurious link removed events in discovery<commit_after>package discovery\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tbh \"github.com\/kandoo\/beehive\"\n\t\"github.com\/kandoo\/beehive-netctrl\/net\/ethernet\"\n\t\"github.com\/kandoo\/beehive-netctrl\/nom\"\n\t\"github.com\/kandoo\/beehive\/Godeps\/_workspace\/src\/github.com\/golang\/glog\"\n)\n\ntype LinkDiscovered struct {\n}\n\nconst (\n\tnodeDict = \"N\"\n)\n\ntype nodePortsAndLinks struct {\n\tN nom.Node\n\tP []nom.Port\n\tL []nom.Link\n}\n\nfunc (np *nodePortsAndLinks) hasPort(port nom.Port) bool {\n\tfor _, p := range np.P {\n\t\tif p.ID == port.ID {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (np *nodePortsAndLinks) removePort(port nom.Port) bool {\n\tfor i, p := range np.P {\n\t\tif p.ID == port.ID {\n\t\t\tnp.P = append(np.P[:i], np.P[i+1:]...)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (np *nodePortsAndLinks) linkFrom(from nom.UID) (nom.Link, bool) {\n\tfor _, l := range np.L {\n\t\tif l.From == from {\n\t\t\treturn l, true\n\t\t}\n\t}\n\treturn nom.Link{}, false\n}\n\nfunc (np *nodePortsAndLinks) hasLinkFrom(from nom.UID) bool {\n\t_, ok := np.linkFrom(from)\n\treturn ok\n}\n\nfunc (np *nodePortsAndLinks) hasLink(link nom.Link) bool {\n\tid := link.UID()\n\tfor _, l := range np.L {\n\t\tif l.UID() == id {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (np *nodePortsAndLinks) removeLink(link nom.Link) bool {\n\tfor i, l := range np.L {\n\t\tif l.From == link.From {\n\t\t\tnp.L = append(np.L[:i], np.L[i+1:]...)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\ntype nodeJoinedHandler struct{}\n\nfunc (h *nodeJoinedHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tjoined := msg.Data().(nom.NodeJoined)\n\td := ctx.Dict(nodeDict)\n\tn := nom.Node(joined)\n\tk := string(n.UID())\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\tglog.Warningf(\"%v rejoins\", n)\n\t}\n\tnp.N = n\n\t\/\/ TODO(soheil): Add a flow entry to forward lldp packets to the controller.\n\treturn d.PutGob(k, &np)\n}\n\nfunc (h *nodeJoinedHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(nom.Node(msg.Data().(nom.NodeJoined)).UID())},\n\t}\n}\n\ntype nodeLeftHandler struct{}\n\nfunc (h *nodeLeftHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tn := nom.Node(msg.Data().(nom.NodeLeft))\n\td := ctx.Dict(nodeDict)\n\tk := string(n.UID())\n\tif _, err := d.Get(k); err != nil {\n\t\treturn fmt.Errorf(\"%v is not joined\", n)\n\t}\n\td.Del(k)\n\treturn nil\n}\n\nfunc (h *nodeLeftHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(nom.Node(msg.Data().(nom.NodeLeft)).UID())},\n\t}\n}\n\ntype portUpdateHandler struct{}\n\nfunc (h *portUpdateHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tp := nom.Port(msg.Data().(nom.PortUpdated))\n\td := ctx.Dict(nodeDict)\n\tk := string(p.Node)\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\tglog.Warningf(\"%v added before its node\", p)\n\t\tctx.Snooze(1 * time.Second)\n\t\treturn nil\n\t}\n\n\tif np.hasPort(p) {\n\t\tglog.Warningf(\"%v readded\")\n\t\tnp.removePort(p)\n\t}\n\n\tsendLLDPPacket(np.N, p, ctx)\n\n\tnp.P = append(np.P, p)\n\treturn d.PutGob(k, &np)\n}\n\nfunc (h *portUpdateHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(msg.Data().(nom.PortUpdated).Node)},\n\t}\n}\n\ntype lldpTimeout struct{}\n\ntype timeoutHandler struct{}\n\nfunc (h *timeoutHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\td := ctx.Dict(nodeDict)\n\td.ForEach(func(k string, v []byte) {\n\t\tvar np nodePortsAndLinks\n\t\tif err := nom.ObjGoDecode(&np, v); err != nil {\n\t\t\tglog.Errorf(\"Error in decoding value: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tfor _, p := range np.P {\n\t\t\tsendLLDPPacket(np.N, p, ctx)\n\t\t}\n\t})\n\treturn nil\n}\n\nfunc (h *timeoutHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{}\n}\n\ntype pktInHandler struct{}\n\nfunc (h *pktInHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tpin := msg.Data().(nom.PacketIn)\n\te := ethernet.NewEthernetWithBuf([]byte(pin.Packet))\n\tif e.Type() != uint16(ethernet.ETH_T_LLDP) {\n\t\treturn nil\n\t}\n\n\t_, port, err := decodeLLDP([]byte(pin.Packet))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\td := ctx.Dict(nodeDict)\n\tk := string(pin.Node)\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\treturn fmt.Errorf(\"Node %v not found\", pin.Node)\n\t}\n\n\tl := nom.Link{\n\t\tID:    nom.LinkID(port.UID()),\n\t\tFrom:  pin.InPort,\n\t\tTo:    []nom.UID{port.UID()},\n\t\tState: nom.LinkStateUp,\n\t}\n\tctx.Emit(NewLink(l))\n\n\tl = nom.Link{\n\t\tID:    nom.LinkID(pin.InPort),\n\t\tFrom:  port.UID(),\n\t\tTo:    []nom.UID{pin.InPort},\n\t\tState: nom.LinkStateUp,\n\t}\n\tctx.Emit(NewLink(l))\n\n\treturn nil\n}\n\nfunc (h *pktInHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\treturn bh.MappedCells{\n\t\t{nodeDict, string(msg.Data().(nom.PacketIn).Node)},\n\t}\n}\n\ntype NewLink nom.Link\n\ntype newLinkHandler struct{}\n\nfunc (h *newLinkHandler) Rcv(msg bh.Msg, ctx bh.RcvContext) error {\n\tl := nom.Link(msg.Data().(NewLink))\n\tn, _ := nom.ParsePortUID(l.From)\n\td := ctx.Dict(nodeDict)\n\tk := string(n)\n\tvar np nodePortsAndLinks\n\tif err := d.GetGob(k, &np); err != nil {\n\t\treturn err\n\t}\n\n\tif oldl, ok := np.linkFrom(l.From); ok {\n\t\tif oldl.UID() == l.UID() {\n\t\t\treturn nil\n\t\t}\n\t\tnp.removeLink(oldl)\n\t\tctx.Emit(nom.LinkRemoved(oldl))\n\t}\n\n\tglog.V(2).Infof(\"Link detected %v\", l)\n\tctx.Emit(nom.LinkAdded(l))\n\tnp.L = append(np.L, l)\n\treturn d.PutGob(k, &np)\n}\n\nfunc (h *newLinkHandler) Map(msg bh.Msg, ctx bh.MapContext) bh.MappedCells {\n\tn, _ := nom.ParsePortUID(msg.Data().(NewLink).From)\n\treturn bh.MappedCells{{nodeDict, string(n)}}\n}\n\n\/\/ RegisterDiscovery registers the handlers for topology discovery on the hive.\nfunc RegisterDiscovery(h bh.Hive) {\n\ta := h.NewApp(\"discovery\")\n\ta.Handle(nom.NodeJoined{}, &nodeJoinedHandler{})\n\ta.Handle(nom.NodeLeft{}, &nodeLeftHandler{})\n\ta.Handle(nom.PortUpdated{}, &portUpdateHandler{})\n\t\/\/ TODO(soheil): Handle PortRemoved.\n\ta.Handle(nom.PacketIn{}, &pktInHandler{})\n\ta.Handle(NewLink{}, &newLinkHandler{})\n\ta.Handle(lldpTimeout{}, &timeoutHandler{})\n\tgo func() {\n\t\tfor {\n\t\t\th.Emit(lldpTimeout{})\n\t\t\ttime.Sleep(60 * time.Second)\n\t\t}\n\t}()\n}\n<|endoftext|>"}
{"text":"<commit_before>package library\n\nimport (\n\t\"encoding\/json\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"github.com\/mikedewar\/aws4\"\n\t\"github.com\/nytlabs\/streamtools\/st\/blocks\" \/\/ blocks\n\t\"github.com\/nytlabs\/streamtools\/st\/util\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\/\/\"reflect\"\n\t\/\/\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype sqsMessage struct {\n\tBody          []string `xml:\"ReceiveMessageResult>Message>Body\"`\n\tReceiptHandle []string `xml:\"ReceiveMessageResult>Message>ReceiptHandle\"`\n}\n\nfunc dialTimeout(network, addr string) (net.Conn, error) {\n\treturn net.DialTimeout(network, addr, time.Duration(2*time.Second))\n}\n\nfunc (b *FromSQS) listener() {\n\tlog.Println(\"Starting new SQS listener\")\n\tb.lock.Lock()\n\tlAuth := map[string]string{}\n\tvar err error\n\tfor k, _ := range b.auth {\n\t\tlAuth[k], err = util.ParseString(b.auth, k)\n\t\tif err != nil {\n\t\t\tb.Error(err)\n\t\t\tbreak\n\t\t}\n\t}\n\tb.listening = true\n\tb.lock.Unlock()\n\n\ttransport := http.Transport{\n\t\tDial: dialTimeout,\n\t}\n\n\thttpclient := &http.Client{\n\t\tTransport: &transport,\n\t}\n\n\tkeys := &aws4.Keys{\n\t\tAccessKey: lAuth[\"AccessKey\"],\n\t\tSecretKey: lAuth[\"AccessSecret\"],\n\t}\n\n\tsqsclient := &aws4.Client{Keys: keys, Client: httpclient}\n\n\tparsedUrl, err := url.Parse(lAuth[\"SQSEndpoint\"])\n\tif err != nil {\n\t\tb.Error(err)\n\t\treturn\n\t}\n\n\tquery := url.Values{}\n\tquery.Set(\"Action\", \"ReceiveMessage\")\n\tquery.Set(\"AttributeName\", \"All\")\n\tquery.Set(\"Version\", lAuth[\"APIVersion\"])\n\tquery.Set(\"SignatureVersion\", lAuth[\"SignatureVersion\"])\n\tquery.Set(\"WaitTimeSeconds\", lAuth[\"WaitTimeSeconds\"])\n\tquery.Set(\"MaxNumberOfMessages\", lAuth[\"MaxNumberOfMessages\"])\n\n\tparsedUrl.RawQuery = query.Encode()\n\n\tqueryurl := parsedUrl.String()\n\n\tlog.Println(\"Starting SQS read loop\")\n\n\tfor {\n\t\tselect {\n\t\tcase <-b.stop:\n\t\t\tlog.Println(\"Exiting SQS read loop\")\n\t\t\treturn\n\t\tdefault:\n\t\t\tvar m sqsMessage\n\n\t\t\tresp, err := sqsclient.Get(queryurl)\n\n\t\t\tif err != nil {\n\t\t\t\tb.Error(\"could not connect to SQS endpoint\")\n\t\t\t\tb.Error(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\tb.Error(\"could not read Body\")\n\t\t\t\tb.Error(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresp.Body.Close()\n\n\t\t\terr = xml.Unmarshal(body, &m)\n\t\t\tif err != nil {\n\t\t\t\tb.Error(\"could not unmarshal XML\")\n\t\t\t\tb.Error(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif len(m.Body) == 0 {\n\t\t\t\t\/\/ no messages on queue\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\t\/\/log.Println(\"sleeping for a second\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, body := range m.Body {\n\t\t\t\tselect {\n\t\t\t\tcase b.fromListener <- []byte(body):\n\t\t\t\tdefault:\n\t\t\t\t\tlog.Println(\"discarding messages\")\n\t\t\t\t\tlog.Println(len(b.fromListener))\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tparsedUrl, err := url.Parse(lAuth[\"SQSEndpoint\"])\n\t\t\tif err != nil {\n\t\t\t\tb.Error(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tdelquery := url.Values{}\n\t\t\tdelquery.Set(\"Action\", \"DeleteMessageBatch\")\n\t\t\tdelquery.Set(\"Version\", lAuth[\"APIVersion\"])\n\t\t\tdelquery.Set(\"SignatureVersion\", lAuth[\"SignatureVersion\"])\n\n\t\t\tfor i, r := range m.ReceiptHandle {\n\t\t\t\tid := fmt.Sprintf(\"DeleteMessageBatchRequestEntry.%d.Id\", (i + 1))\n\t\t\t\treceipt := fmt.Sprintf(\"DeleteMessageBatchRequestEntry.%d.ReceiptHandle\", (i + 1))\n\t\t\t\tdelquery.Add(id, fmt.Sprintf(\"msg%d\", (i+1)))\n\t\t\t\tdelquery.Add(receipt, r)\n\t\t\t}\n\t\t\tparsedUrl.RawQuery = delquery.Encode()\n\t\t\tdelurl := parsedUrl.String()\n\n\t\t\tresp, err = sqsclient.Get(delurl)\n\t\t\tif err != nil {\n\t\t\t\tb.Error(\"could not delete messages\")\n\t\t\t\tb.Error(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresp.Body.Close()\n\t\t}\n\t}\n}\n\n\/\/ specify those channels we're going to use to communicate with streamtools\ntype FromSQS struct {\n\tblocks.Block\n\tqueryrule chan blocks.MsgChan\n\tinrule    blocks.MsgChan\n\tout       blocks.MsgChan\n\tquit      blocks.MsgChan\n\n\tlock         sync.Mutex\n\tlistening    bool\n\tfromListener chan []byte\n\tauth         map[string]interface{}\n\tstop         chan bool\n}\n\n\/\/ we need to build a simple factory so that streamtools can make new blocks of this kind\nfunc NewFromSQS() blocks.BlockInterface {\n\treturn &FromSQS{}\n}\n\n\/\/ Setup is called once before running the block. We build up the channels and specify what kind of block this is.\nfunc (b *FromSQS) Setup() {\n\tb.Kind = \"fromSQS\"\n\tb.Desc = \"reads from Amazon's SQS, emitting each line of JSON as a separate message\"\n\tb.inrule = b.InRoute(\"rule\")\n\tb.queryrule = b.QueryRoute(\"rule\")\n\tb.quit = b.Quit()\n\tb.out = b.Broadcast()\n\tb.fromListener = make(chan []byte, 1000)\n\tb.stop = make(chan bool)\n\tb.auth = map[string]interface{}{\n\t\t\"SQSEndpoint\":         \"\",\n\t\t\"AccessKey\":           \"\",\n\t\t\"AccessSecret\":        \"\",\n\t\t\"APIVersion\":          \"2012-11-05\",\n\t\t\"SignatureVersion\":    \"4\",\n\t\t\"WaitTimeSeconds\":     \"0\",\n\t\t\"MaxNumberOfMessages\": \"10\",\n\t}\n}\n\nfunc (b *FromSQS) stopListening() {\n\tif b.listening {\n\t\tb.stop <- true\n\t\tb.listening = false\n\t}\n}\n\n\/\/ Run is the block's main loop. Here we listen on the different channels we set up.\nfunc (b *FromSQS) Run() {\n\tvar err error\n\n\tfor {\n\t\tselect {\n\t\tcase msgI := <-b.inrule:\n\t\t\tfor k, _ := range b.auth {\n\t\t\t\tb.auth[k], err = util.ParseString(msgI, k)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Error(err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tb.stopListening()\n\t\t\tgo b.listener()\n\t\tcase <-b.quit:\n\t\t\tb.stopListening()\n\t\t\treturn\n\t\tcase msg := <-b.fromListener:\n\t\t\tvar outMsg interface{}\n\t\t\terr := json.Unmarshal(msg, &outMsg)\n\t\t\tif err != nil {\n\t\t\t\tb.Error(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tb.out <- outMsg\n\t\tcase MsgChan := <-b.queryrule:\n\t\t\t\/\/ deal with a query request\n\t\t\tMsgChan <- b.auth\n\t\t}\n\t}\n}\n<commit_msg>added logging, more backoffs<commit_after>package library\n\nimport (\n\t\"encoding\/json\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"github.com\/mikedewar\/aws4\"\n\t\"github.com\/nytlabs\/streamtools\/st\/blocks\" \/\/ blocks\n\t\"github.com\/nytlabs\/streamtools\/st\/util\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\/\/\"reflect\"\n\t\/\/\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype sqsMessage struct {\n\tBody          []string `xml:\"ReceiveMessageResult>Message>Body\"`\n\tReceiptHandle []string `xml:\"ReceiveMessageResult>Message>ReceiptHandle\"`\n}\n\nfunc dialTimeout(network, addr string) (net.Conn, error) {\n\treturn net.DialTimeout(network, addr, time.Duration(2*time.Second))\n}\n\nfunc (b *FromSQS) listener() {\n\tlog.Println(\"Starting new SQS listener\")\n\tb.lock.Lock()\n\tlAuth := map[string]string{}\n\tvar err error\n\tfor k, _ := range b.auth {\n\t\tlAuth[k], err = util.ParseString(b.auth, k)\n\t\tif err != nil {\n\t\t\tb.Error(err)\n\t\t\tbreak\n\t\t}\n\t}\n\tb.listening = true\n\tb.lock.Unlock()\n\n\ttransport := http.Transport{\n\t\tDial: dialTimeout,\n\t}\n\n\thttpclient := &http.Client{\n\t\tTransport: &transport,\n\t}\n\n\tkeys := &aws4.Keys{\n\t\tAccessKey: lAuth[\"AccessKey\"],\n\t\tSecretKey: lAuth[\"AccessSecret\"],\n\t}\n\n\tsqsclient := &aws4.Client{Keys: keys, Client: httpclient}\n\n\tparsedUrl, err := url.Parse(lAuth[\"SQSEndpoint\"])\n\tif err != nil {\n\t\tb.Error(err)\n\t\treturn\n\t}\n\n\tquery := url.Values{}\n\tquery.Set(\"Action\", \"ReceiveMessage\")\n\tquery.Set(\"AttributeName\", \"All\")\n\tquery.Set(\"Version\", lAuth[\"APIVersion\"])\n\tquery.Set(\"SignatureVersion\", lAuth[\"SignatureVersion\"])\n\tquery.Set(\"WaitTimeSeconds\", lAuth[\"WaitTimeSeconds\"])\n\tquery.Set(\"MaxNumberOfMessages\", lAuth[\"MaxNumberOfMessages\"])\n\n\tparsedUrl.RawQuery = query.Encode()\n\n\tqueryurl := parsedUrl.String()\n\n\tlog.Println(\"Starting SQS read loop\")\n\n\tfor {\n\t\tselect {\n\t\tcase <-b.stop:\n\t\t\tlog.Println(\"Exiting SQS read loop\")\n\t\t\treturn\n\t\tdefault:\n\t\t\tvar m sqsMessage\n\n\t\t\tresp, err := sqsclient.Get(queryurl)\n\n\t\t\tif err != nil {\n\t\t\t\tb.Error(\"could not connect to SQS endpoint. waiting 1s\")\n\t\t\t\tb.Error(err)\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\t\tif err != nil {\n\t\t\t\tb.Error(\"could not read Body\")\n\t\t\t\tb.Error(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresp.Body.Close()\n\n\t\t\terr = xml.Unmarshal(body, &m)\n\t\t\tif err != nil {\n\t\t\t\tb.Error(\"could not unmarshal XML\")\n\t\t\t\tb.Error(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif len(m.Body) == 0 {\n\t\t\t\t\/\/ no messages on queue\n\t\t\t\tb.Error(\"no messages on queue. waiting 1s\")\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, body := range m.Body {\n\t\t\t\tselect {\n\t\t\t\tcase b.fromListener <- []byte(body):\n\t\t\t\tdefault:\n\t\t\t\t\tlog.Println(\"discarding messages\")\n\t\t\t\t\tlog.Println(len(b.fromListener))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tparsedUrl, err := url.Parse(lAuth[\"SQSEndpoint\"])\n\t\t\tif err != nil {\n\t\t\t\tb.Error(err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tdelquery := url.Values{}\n\t\t\tdelquery.Set(\"Action\", \"DeleteMessageBatch\")\n\t\t\tdelquery.Set(\"Version\", lAuth[\"APIVersion\"])\n\t\t\tdelquery.Set(\"SignatureVersion\", lAuth[\"SignatureVersion\"])\n\n\t\t\tfor i, r := range m.ReceiptHandle {\n\t\t\t\tid := fmt.Sprintf(\"DeleteMessageBatchRequestEntry.%d.Id\", (i + 1))\n\t\t\t\treceipt := fmt.Sprintf(\"DeleteMessageBatchRequestEntry.%d.ReceiptHandle\", (i + 1))\n\t\t\t\tdelquery.Add(id, fmt.Sprintf(\"msg%d\", (i+1)))\n\t\t\t\tdelquery.Add(receipt, r)\n\t\t\t}\n\t\t\tparsedUrl.RawQuery = delquery.Encode()\n\t\t\tdelurl := parsedUrl.String()\n\n\t\t\tresp, err = sqsclient.Get(delurl)\n\t\t\tif err != nil {\n\t\t\t\tb.Error(\"could not delete messages. waiting 1s\")\n\t\t\t\tb.Error(err)\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tresp.Body.Close()\n\t\t}\n\t}\n}\n\n\/\/ specify those channels we're going to use to communicate with streamtools\ntype FromSQS struct {\n\tblocks.Block\n\tqueryrule chan blocks.MsgChan\n\tinrule    blocks.MsgChan\n\tout       blocks.MsgChan\n\tquit      blocks.MsgChan\n\n\tlock         sync.Mutex\n\tlistening    bool\n\tfromListener chan []byte\n\tauth         map[string]interface{}\n\tstop         chan bool\n}\n\n\/\/ we need to build a simple factory so that streamtools can make new blocks of this kind\nfunc NewFromSQS() blocks.BlockInterface {\n\treturn &FromSQS{}\n}\n\n\/\/ Setup is called once before running the block. We build up the channels and specify what kind of block this is.\nfunc (b *FromSQS) Setup() {\n\tb.Kind = \"fromSQS\"\n\tb.Desc = \"reads from Amazon's SQS, emitting each line of JSON as a separate message\"\n\tb.inrule = b.InRoute(\"rule\")\n\tb.queryrule = b.QueryRoute(\"rule\")\n\tb.quit = b.Quit()\n\tb.out = b.Broadcast()\n\tb.fromListener = make(chan []byte, 1000)\n\tb.stop = make(chan bool)\n\tb.auth = map[string]interface{}{\n\t\t\"SQSEndpoint\":         \"\",\n\t\t\"AccessKey\":           \"\",\n\t\t\"AccessSecret\":        \"\",\n\t\t\"APIVersion\":          \"2012-11-05\",\n\t\t\"SignatureVersion\":    \"4\",\n\t\t\"WaitTimeSeconds\":     \"0\",\n\t\t\"MaxNumberOfMessages\": \"10\",\n\t}\n}\n\nfunc (b *FromSQS) stopListening() {\n\tlog.Println(\"attempting to stop SQS reader\")\n\tif b.listening {\n\t\tb.stop <- true\n\t\tb.listening = false\n\t}\n}\n\n\/\/ Run is the block's main loop. Here we listen on the different channels we set up.\nfunc (b *FromSQS) Run() {\n\tvar err error\n\n\tfor {\n\t\tselect {\n\t\tcase msgI := <-b.inrule:\n\t\t\tfor k, _ := range b.auth {\n\t\t\t\tb.auth[k], err = util.ParseString(msgI, k)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Error(err)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tb.stopListening()\n\t\t\tgo b.listener()\n\t\tcase <-b.quit:\n\t\t\tb.stopListening()\n\t\t\treturn\n\t\tcase msg := <-b.fromListener:\n\t\t\tvar outMsg interface{}\n\t\t\terr := json.Unmarshal(msg, &outMsg)\n\t\t\tif err != nil {\n\t\t\t\tb.Error(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tb.out <- outMsg\n\t\tcase MsgChan := <-b.queryrule:\n\t\t\t\/\/ deal with a query request\n\t\t\tMsgChan <- b.auth\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (C) 2013 The Docker Cloud authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/googlecloudplatform\/docker-cloud\/dockercloud\"\n)\n\n\/\/ Try to connect to a tunnel to the docker dameon if it exists.\n\/\/ url is the URL to test.\n\/\/ returns true, if the connection was successful, false otherwise\ntype Tunnel struct {\n\turl.URL\n}\n\nfunc (t Tunnel) isActive() bool {\n\t_, err := http.Get(t.String())\n\treturn err == nil\n}\n\ntype ProxyServer struct {\n\tcloud dockercloud.Cloud\n}\n\nfunc (server ProxyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\terr := server.doServe(w, r)\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %s\\n\", err)\n\t\tw.WriteHeader(500)\n\t\tfmt.Fprintf(w, \"{'error': '%s'}\", err)\n\t}\n}\n\nfunc (server ProxyServer) doServe(w http.ResponseWriter, r *http.Request) error {\n\tvar err error\n\tvar ip string\n\tpath := r.URL.Path\n\tquery := r.URL.RawQuery\n\thost := fmt.Sprintf(\"localhost:%d\", *tunnelPort)\n\ttargetUrl := fmt.Sprintf(\"http:\/\/%s%s?%s\", host, path, query)\n\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\n\t\/\/ Try to find a VM instance.\n\tip, err = server.cloud.GetPublicIPAddress(*instanceName, *zone)\n\tinstanceRunning := len(ip) > 0\n\t\/\/ err is 404 if the instance doesn't exist, so we only error out when\n\t\/\/ instanceRunning is true.\n\tif err != nil && instanceRunning {\n\t\treturn err\n\t}\n\n\t\/\/ If there's no VM instance, and the request is 'ps' just return []\n\tif r.Method == \"GET\" && strings.HasSuffix(path, \"\/containers\/json\") && !instanceRunning {\n\t\tw.WriteHeader(200)\n\t\tfmt.Fprintf(w, \"[]\")\n\t\treturn nil\n\t}\n\n\t\/\/ Otherwise create a new VM.\n\tif !instanceRunning {\n\t\tip, err = server.cloud.CreateInstance(*instanceName, *zone)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Test for the SSH tunnel, create if it doesn't exist.\n\ttunnelUrl, err := url.Parse(\"http:\/\/\" + host + \"\/v1.6\/containers\/json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\ttunnel := Tunnel{*tunnelUrl}\n\n\tif !tunnel.isActive() {\n\t\tfmt.Printf(\"Creating tunnel\")\n\t\t_, err = server.cloud.OpenSecureTunnel(*instanceName, *zone, *tunnelPort, *dockerPort)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = proxyRequest(targetUrl, r, w)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif strings.HasSuffix(path, \"\/stop\") {\n\t\tserver.maybeDelete(host, *instanceName, *zone)\n\t}\n\treturn nil\n}\n\nfunc proxyRequest(url string, r *http.Request, w http.ResponseWriter) error {\n\tvar res *http.Response\n\tvar err error\n\n\t\/\/ Proxy the request.\n\tif r.Method == \"GET\" {\n\t\tres, err = http.Get(url)\n\t}\n\tif r.Method == \"POST\" {\n\t\tres, err = http.Post(url, \"application\/json\", r.Body)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.WriteHeader(res.StatusCode)\n\tdefer res.Body.Close()\n\t\/\/ TODO(bburns) : Intercept 'ps' here and substitute in the ip address.\n\t_, err = io.Copy(w, res.Body)\n\treturn err\n}\n\n\/\/ TODO(bburns) : clone this from docker somehow?\ntype ContainerPort struct {\n\tPrivatePort float64\n\tPublicPort  float64\n\tType        string\n}\n\ntype ContainerStatus struct {\n\tId         string\n\tImage      string\n\tCommand    string\n\tCreated    float64\n\tStatus     string\n\tPorts      []ContainerPort\n\tSizeRW     float64\n\tSizeRootFs float64\n}\n\nfunc (server ProxyServer) maybeDelete(host string, instanceName string, zone string) error {\n\tres, err := http.Get(fmt.Sprintf(\"http:\/\/%s\/v1.6\/containers\/json\", host))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(string(body))\n\tvar containers []ContainerStatus\n\terr = json.Unmarshal(body, &containers)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(containers) == 0 {\n\t\terr = server.cloud.DeleteInstance(instanceName, zone)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nvar (\n\tclientId     = flag.String(\"id\", \"676599397109-0te3n95co16j9mkinnq6vdhphp4nnd06.apps.googleusercontent.com\", \"Client id\")\n\tclientSecret = flag.String(\"secret\", \"JnMnI5z9iH7YItv_jy_TZ1Hg\", \"Client Secret\")\n\tscope        = flag.String(\"scope\", \"https:\/\/www.googleapis.com\/auth\/userinfo.profile https:\/\/www.googleapis.com\/auth\/compute https:\/\/www.googleapis.com\/auth\/devstorage.read_write\", \"OAuth Scope\")\n\tcode         = flag.String(\"code\", \"\", \"Authorization code\")\n\tprojectId    = flag.String(\"project\", \"\", \"Google Cloud Project Name\")\n\tproxyPort    = flag.Int(\"port\", 8080, \"The local port to run on.\")\n\tdockerPort   = flag.Int(\"dockerport\", 8000, \"The remote port to run docker on\")\n\ttunnelPort   = flag.Int(\"tunnelport\", 8001, \"The local port open the tunnel to docker\")\n\tinstanceName = flag.String(\"instancename\", \"docker-instance\", \"The name of the instance\")\n\tzone         = flag.String(\"zone\", \"us-central1-a\", \"The zone to run in\")\n)\n\nfunc main() {\n\tflag.Parse()\n\tserver := ProxyServer{\n\t\tcloud: dockercloud.NewCloudGce(*clientId, *clientSecret, *scope, *code, *projectId),\n\t}\n\thttp.Handle(\"\/\", server)\n\taddr := fmt.Sprintf(\":%d\", *proxyPort)\n\tlog.Print(\"listening on \", addr)\n\tlog.Fatal(http.ListenAndServe(addr, nil))\n}\n<commit_msg>Provide instructions how to use the proxy server on startup.<commit_after>\/\/\n\/\/ Copyright (C) 2013 The Docker Cloud authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/googlecloudplatform\/docker-cloud\/dockercloud\"\n)\n\n\/\/ Try to connect to a tunnel to the docker dameon if it exists.\n\/\/ url is the URL to test.\n\/\/ returns true, if the connection was successful, false otherwise\ntype Tunnel struct {\n\turl.URL\n}\n\nfunc (t Tunnel) isActive() bool {\n\t_, err := http.Get(t.String())\n\treturn err == nil\n}\n\ntype ProxyServer struct {\n\tcloud dockercloud.Cloud\n}\n\nfunc (server ProxyServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\terr := server.doServe(w, r)\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %s\\n\", err)\n\t\tw.WriteHeader(500)\n\t\tfmt.Fprintf(w, \"{'error': '%s'}\", err)\n\t}\n}\n\nfunc (server ProxyServer) doServe(w http.ResponseWriter, r *http.Request) error {\n\tvar err error\n\tvar ip string\n\tpath := r.URL.Path\n\tquery := r.URL.RawQuery\n\thost := fmt.Sprintf(\"localhost:%d\", *tunnelPort)\n\ttargetUrl := fmt.Sprintf(\"http:\/\/%s%s?%s\", host, path, query)\n\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\n\t\/\/ Try to find a VM instance.\n\tip, err = server.cloud.GetPublicIPAddress(*instanceName, *zone)\n\tinstanceRunning := len(ip) > 0\n\t\/\/ err is 404 if the instance doesn't exist, so we only error out when\n\t\/\/ instanceRunning is true.\n\tif err != nil && instanceRunning {\n\t\treturn err\n\t}\n\n\t\/\/ If there's no VM instance, and the request is 'ps' just return []\n\tif r.Method == \"GET\" && strings.HasSuffix(path, \"\/containers\/json\") && !instanceRunning {\n\t\tw.WriteHeader(200)\n\t\tfmt.Fprintf(w, \"[]\")\n\t\treturn nil\n\t}\n\n\t\/\/ Otherwise create a new VM.\n\tif !instanceRunning {\n\t\tip, err = server.cloud.CreateInstance(*instanceName, *zone)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Test for the SSH tunnel, create if it doesn't exist.\n\ttunnelUrl, err := url.Parse(\"http:\/\/\" + host + \"\/v1.6\/containers\/json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\ttunnel := Tunnel{*tunnelUrl}\n\n\tif !tunnel.isActive() {\n\t\tfmt.Printf(\"Creating tunnel\")\n\t\t_, err = server.cloud.OpenSecureTunnel(*instanceName, *zone, *tunnelPort, *dockerPort)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = proxyRequest(targetUrl, r, w)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif strings.HasSuffix(path, \"\/stop\") {\n\t\tserver.maybeDelete(host, *instanceName, *zone)\n\t}\n\treturn nil\n}\n\nfunc proxyRequest(url string, r *http.Request, w http.ResponseWriter) error {\n\tvar res *http.Response\n\tvar err error\n\n\t\/\/ Proxy the request.\n\tif r.Method == \"GET\" {\n\t\tres, err = http.Get(url)\n\t}\n\tif r.Method == \"POST\" {\n\t\tres, err = http.Post(url, \"application\/json\", r.Body)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.WriteHeader(res.StatusCode)\n\tdefer res.Body.Close()\n\t\/\/ TODO(bburns) : Intercept 'ps' here and substitute in the ip address.\n\t_, err = io.Copy(w, res.Body)\n\treturn err\n}\n\n\/\/ TODO(bburns) : clone this from docker somehow?\ntype ContainerPort struct {\n\tPrivatePort float64\n\tPublicPort  float64\n\tType        string\n}\n\ntype ContainerStatus struct {\n\tId         string\n\tImage      string\n\tCommand    string\n\tCreated    float64\n\tStatus     string\n\tPorts      []ContainerPort\n\tSizeRW     float64\n\tSizeRootFs float64\n}\n\nfunc (server ProxyServer) maybeDelete(host string, instanceName string, zone string) error {\n\tres, err := http.Get(fmt.Sprintf(\"http:\/\/%s\/v1.6\/containers\/json\", host))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Printf(string(body))\n\tvar containers []ContainerStatus\n\terr = json.Unmarshal(body, &containers)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(containers) == 0 {\n\t\terr = server.cloud.DeleteInstance(instanceName, zone)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nvar (\n\tclientId     = flag.String(\"id\", \"676599397109-0te3n95co16j9mkinnq6vdhphp4nnd06.apps.googleusercontent.com\", \"Client id\")\n\tclientSecret = flag.String(\"secret\", \"JnMnI5z9iH7YItv_jy_TZ1Hg\", \"Client Secret\")\n\tscope        = flag.String(\"scope\", \"https:\/\/www.googleapis.com\/auth\/userinfo.profile https:\/\/www.googleapis.com\/auth\/compute https:\/\/www.googleapis.com\/auth\/devstorage.read_write\", \"OAuth Scope\")\n\tcode         = flag.String(\"code\", \"\", \"Authorization code\")\n\tprojectId    = flag.String(\"project\", \"\", \"Google Cloud Project Name\")\n\tproxyPort    = flag.Int(\"port\", 8080, \"The local port to run on.\")\n\tdockerPort   = flag.Int(\"dockerport\", 8000, \"The remote port to run docker on\")\n\ttunnelPort   = flag.Int(\"tunnelport\", 8001, \"The local port open the tunnel to docker\")\n\tinstanceName = flag.String(\"instancename\", \"docker-instance\", \"The name of the instance\")\n\tzone         = flag.String(\"zone\", \"us-central1-a\", \"The zone to run in\")\n)\n\nfunc main() {\n\tflag.Parse()\n\tserver := ProxyServer{\n\t\tcloud: dockercloud.NewCloudGce(*clientId, *clientSecret, *scope, *code, *projectId),\n\t}\n\thttp.Handle(\"\/\", server)\n\taddr := fmt.Sprintf(\":%d\", *proxyPort)\n\tlog.Printf(\"Server started, now you can use docker -H http:\/\/localhost%s\", addr)\n\tlog.Fatal(http.ListenAndServe(addr, nil))\n}\n<|endoftext|>"}
{"text":"<commit_before>package topgun_test\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"regexp\"\n\t\"time\"\n\n\t_ \"github.com\/lib\/pq\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"[#129726011] Worker landing\", func() {\n\tContext(\"with two workers available\", func() {\n\t\tBeforeEach(func() {\n\t\t\tSkip(\"unreliable; if worker restarts too fast, test will fail. we should use 'bosh stop' but it turns out that retires, not lands.\")\n\n\t\t\tDeploy(\"deployments\/concourse-separate-forwarded-worker.yml\", \"-o\", \"operations\/separate-worker-two.yml\")\n\t\t})\n\n\t\tDescribe(\"restarting the worker\", func() {\n\t\t\tvar restartingWorkerName string\n\t\t\tvar restartSession *gexec.Session\n\n\t\t\tJustBeforeEach(func() {\n\t\t\t\trestartSession = spawnBosh(\"restart\", \"worker\/0\")\n\t\t\t\trestartingWorkerName = waitForLandingOrLandedWorker()\n\t\t\t})\n\n\t\t\tAfterEach(func() {\n\t\t\t\t<-restartSession.Exited\n\t\t\t})\n\n\t\t\tContext(\"while in landing or landed state\", func() {\n\t\t\t\t\/\/ technically this is timing-dependent but it doesn't seem worth the\n\t\t\t\t\/\/ time cost of explicit tests for both\n\n\t\t\t\tIt(\"is not used for new workloads\", func() {\n\t\t\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\t\t\tfly(\"execute\", \"-c\", \"tasks\/tiny.yml\")\n\t\t\t\t\t\tusedWorkers := workersWithContainers()\n\t\t\t\t\t\tExpect(usedWorkers).To(HaveLen(1))\n\t\t\t\t\t\tExpect(usedWorkers).ToNot(ContainElement(restartingWorkerName))\n\t\t\t\t\t}\n\t\t\t\t})\n\n\t\t\t\tIt(\"can be pruned\", func() {\n\t\t\t\t\tfly(\"prune-worker\", \"-w\", restartingWorkerName)\n\t\t\t\t\twaitForWorkersToBeRunning()\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n\n\tdescribeRestartingTheWorker := func() {\n\t\tDescribe(\"restarting the worker\", func() {\n\t\t\tvar restartSession *gexec.Session\n\n\t\t\tJustBeforeEach(func() {\n\t\t\t\trestartSession = spawnBosh(\"restart\", \"worker\/0\")\n\t\t\t\t_ = waitForLandingOrLandedWorker()\n\t\t\t})\n\n\t\t\tAfterEach(func() {\n\t\t\t\t<-restartSession.Exited\n\t\t\t})\n\n\t\t\tContext(\"with volumes and containers present\", func() {\n\t\t\t\tvar preservedContainerID string\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tBy(\"setting pipeline that creates volumes for image\")\n\t\t\t\t\tfly(\"set-pipeline\", \"-n\", \"-c\", \"pipelines\/get-task.yml\", \"-p\", \"topgun\")\n\n\t\t\t\t\tBy(\"unpausing the pipeline\")\n\t\t\t\t\tfly(\"unpause-pipeline\", \"-p\", \"topgun\")\n\n\t\t\t\t\tBy(\"triggering a job\")\n\t\t\t\t\tbuildSession := spawnFly(\"trigger-job\", \"-w\", \"-j\", \"topgun\/simple-job\")\n\t\t\t\t\tEventually(buildSession).Should(gbytes.Say(\"Pulling .*busybox.*\"))\n\t\t\t\t\t<-buildSession.Exited\n\t\t\t\t\tExpect(buildSession.ExitCode()).To(Equal(0))\n\n\t\t\t\t\tBy(\"getting identifier for check container\")\n\t\t\t\t\thijackSession := spawnFly(\"hijack\", \"-c\", \"topgun\/tick-tock\", \"--\", \"hostname\")\n\t\t\t\t\t<-hijackSession.Exited\n\t\t\t\t\tExpect(buildSession.ExitCode()).To(Equal(0))\n\n\t\t\t\t\tpreservedContainerID = string(hijackSession.Out.Contents())\n\t\t\t\t})\n\n\t\t\t\tIt(\"keeps volumes and containers after restart\", func() {\n\t\t\t\t\tBy(\"completing the restart\")\n\t\t\t\t\t<-restartSession.Exited\n\t\t\t\t\tExpect(restartSession.ExitCode()).To(Equal(0))\n\n\t\t\t\t\tBy(\"retaining cached image resource in second job build\")\n\t\t\t\t\tbuildSession := spawnFly(\"trigger-job\", \"-w\", \"-j\", \"topgun\/simple-job\")\n\t\t\t\t\t<-buildSession.Exited\n\t\t\t\t\tExpect(buildSession).NotTo(gbytes.Say(\"Pulling .*busybox.*\"))\n\t\t\t\t\tExpect(buildSession.ExitCode()).To(Equal(0))\n\n\t\t\t\t\tBy(\"retaining check containers\")\n\t\t\t\t\thijackSession := spawnFly(\"hijack\", \"-c\", \"topgun\/tick-tock\", \"--\", \"hostname\")\n\t\t\t\t\t<-hijackSession.Exited\n\t\t\t\t\tExpect(buildSession.ExitCode()).To(Equal(0))\n\n\t\t\t\t\tcurrentContainerID := string(hijackSession.Out.Contents())\n\t\t\t\t\tExpect(currentContainerID).To(Equal(preservedContainerID))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"with an interruptible build in-flight\", func() {\n\t\t\t\tvar buildSession *gexec.Session\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tBy(\"setting pipeline that has an infinite but interruptible job\")\n\t\t\t\t\tfly(\"set-pipeline\", \"-n\", \"-c\", \"pipelines\/interruptible.yml\", \"-p\", \"topgun\")\n\n\t\t\t\t\tBy(\"unpausing the pipeline\")\n\t\t\t\t\tfly(\"unpause-pipeline\", \"-p\", \"topgun\")\n\n\t\t\t\t\tBy(\"triggering a job\")\n\t\t\t\t\tbuildSession = spawnFly(\"trigger-job\", \"-w\", \"-j\", \"topgun\/interruptible-job\")\n\t\t\t\t\tEventually(buildSession).Should(gbytes.Say(\"waiting forever\"))\n\t\t\t\t})\n\n\t\t\t\tIt(\"does not wait for the build\", func() {\n\t\t\t\t\tBy(\"completing the restart without the drain timeout kicking in\")\n\t\t\t\t\tEventually(restartSession, 5*time.Minute).Should(gexec.Exit(0))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"with uninterruptible build in-flight\", func() {\n\t\t\t\tvar buildSession *gexec.Session\n\t\t\t\tvar buildID string\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tbuildSession = spawnFly(\"execute\", \"-c\", \"tasks\/wait.yml\")\n\t\t\t\t\tEventually(buildSession).Should(gbytes.Say(\"executing build\"))\n\n\t\t\t\t\tbuildRegex := regexp.MustCompile(`executing build (\\d+)`)\n\t\t\t\t\tmatches := buildRegex.FindSubmatch(buildSession.Out.Contents())\n\t\t\t\t\tbuildID = string(matches[1])\n\n\t\t\t\t\tEventually(buildSession).Should(gbytes.Say(\"waiting for \/tmp\/stop-waiting\"))\n\t\t\t\t})\n\n\t\t\t\tAfterEach(func() {\n\t\t\t\t\tbuildSession.Signal(os.Interrupt)\n\t\t\t\t\t<-buildSession.Exited\n\t\t\t\t})\n\n\t\t\t\tIt(\"waits for the build\", func() {\n\t\t\t\t\tEventually(restartSession).Should(gbytes.Say(`Updating (instance|job)`))\n\t\t\t\t\tConsistently(restartSession, 5*time.Minute).ShouldNot(gexec.Exit())\n\t\t\t\t})\n\n\t\t\t\tIt(\"finishes restarting once the build is done\", func() {\n\t\t\t\t\tBy(\"hijacking the build to tell it to finish\")\n\t\t\t\t\t<-flyHijackTask(\n\t\t\t\t\t\t\"-b\", buildID,\n\t\t\t\t\t\t\"-s\", \"one-off\",\n\t\t\t\t\t\t\"touch\", \"\/tmp\/stop-waiting\",\n\t\t\t\t\t).Exited\n\n\t\t\t\t\tBy(\"waiting for the build to exit\")\n\t\t\t\t\tEventually(buildSession).Should(gbytes.Say(\"done\"))\n\t\t\t\t\t<-buildSession.Exited\n\t\t\t\t\tExpect(buildSession.ExitCode()).To(Equal(0))\n\n\t\t\t\t\tBy(\"successfully restarting\")\n\t\t\t\t\t<-restartSession.Exited\n\t\t\t\t\tExpect(restartSession.ExitCode()).To(Equal(0))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t}\n\n\tContext(\"with one worker\", func() {\n\t\tBeforeEach(func() {\n\t\t\tDeploy(\"deployments\/concourse-separate-forwarded-worker.yml\")\n\t\t\twaitForRunningWorker()\n\t\t})\n\n\t\tdescribeRestartingTheWorker()\n\t})\n\n\tContext(\"with a single team worker\", func() {\n\t\tBeforeEach(func() {\n\t\t\tDeploy(\"deployments\/concourse-separate-forwarded-worker.yml\", \"-o\", \"operations\/separate-worker-team.yml\")\n\n\t\t\tsetTeam := spawnFlyInteractive(bytes.NewBufferString(\"y\\n\"), \"set-team\", \"-n\", \"team-a\", \"--allow-all-users\")\n\t\t\t<-setTeam.Exited\n\t\t\tExpect(setTeam.ExitCode()).To(Equal(0))\n\n\t\t\tfly(\"login\", \"-c\", atcExternalURL, \"-n\", \"team-a\", \"-u\", atcUsername, \"-p\", atcPassword)\n\n\t\t\t\/\/ wait for the team's worker to arrive now that team exists\n\t\t\twaitForRunningWorker()\n\t\t})\n\n\t\tdescribeRestartingTheWorker()\n\t})\n})\n<commit_msg>fix image fetching output assertion<commit_after>package topgun_test\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"regexp\"\n\t\"time\"\n\n\t_ \"github.com\/lib\/pq\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"[#129726011] Worker landing\", func() {\n\tContext(\"with two workers available\", func() {\n\t\tBeforeEach(func() {\n\t\t\tSkip(\"unreliable; if worker restarts too fast, test will fail. we should use 'bosh stop' but it turns out that retires, not lands.\")\n\n\t\t\tDeploy(\"deployments\/concourse-separate-forwarded-worker.yml\", \"-o\", \"operations\/separate-worker-two.yml\")\n\t\t})\n\n\t\tDescribe(\"restarting the worker\", func() {\n\t\t\tvar restartingWorkerName string\n\t\t\tvar restartSession *gexec.Session\n\n\t\t\tJustBeforeEach(func() {\n\t\t\t\trestartSession = spawnBosh(\"restart\", \"worker\/0\")\n\t\t\t\trestartingWorkerName = waitForLandingOrLandedWorker()\n\t\t\t})\n\n\t\t\tAfterEach(func() {\n\t\t\t\t<-restartSession.Exited\n\t\t\t})\n\n\t\t\tContext(\"while in landing or landed state\", func() {\n\t\t\t\t\/\/ technically this is timing-dependent but it doesn't seem worth the\n\t\t\t\t\/\/ time cost of explicit tests for both\n\n\t\t\t\tIt(\"is not used for new workloads\", func() {\n\t\t\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\t\t\tfly(\"execute\", \"-c\", \"tasks\/tiny.yml\")\n\t\t\t\t\t\tusedWorkers := workersWithContainers()\n\t\t\t\t\t\tExpect(usedWorkers).To(HaveLen(1))\n\t\t\t\t\t\tExpect(usedWorkers).ToNot(ContainElement(restartingWorkerName))\n\t\t\t\t\t}\n\t\t\t\t})\n\n\t\t\t\tIt(\"can be pruned\", func() {\n\t\t\t\t\tfly(\"prune-worker\", \"-w\", restartingWorkerName)\n\t\t\t\t\twaitForWorkersToBeRunning()\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n\n\tdescribeRestartingTheWorker := func() {\n\t\tDescribe(\"restarting the worker\", func() {\n\t\t\tvar restartSession *gexec.Session\n\n\t\t\tJustBeforeEach(func() {\n\t\t\t\trestartSession = spawnBosh(\"restart\", \"worker\/0\")\n\t\t\t\t_ = waitForLandingOrLandedWorker()\n\t\t\t})\n\n\t\t\tAfterEach(func() {\n\t\t\t\t<-restartSession.Exited\n\t\t\t})\n\n\t\t\tContext(\"with volumes and containers present\", func() {\n\t\t\t\tvar preservedContainerID string\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tBy(\"setting pipeline that creates volumes for image\")\n\t\t\t\t\tfly(\"set-pipeline\", \"-n\", \"-c\", \"pipelines\/get-task.yml\", \"-p\", \"topgun\")\n\n\t\t\t\t\tBy(\"unpausing the pipeline\")\n\t\t\t\t\tfly(\"unpause-pipeline\", \"-p\", \"topgun\")\n\n\t\t\t\t\tBy(\"triggering a job\")\n\t\t\t\t\tbuildSession := spawnFly(\"trigger-job\", \"-w\", \"-j\", \"topgun\/simple-job\")\n\t\t\t\t\tEventually(buildSession).Should(gbytes.Say(\"fetching .*busybox.*\"))\n\t\t\t\t\t<-buildSession.Exited\n\t\t\t\t\tExpect(buildSession.ExitCode()).To(Equal(0))\n\n\t\t\t\t\tBy(\"getting identifier for check container\")\n\t\t\t\t\thijackSession := spawnFly(\"hijack\", \"-c\", \"topgun\/tick-tock\", \"--\", \"hostname\")\n\t\t\t\t\t<-hijackSession.Exited\n\t\t\t\t\tExpect(buildSession.ExitCode()).To(Equal(0))\n\n\t\t\t\t\tpreservedContainerID = string(hijackSession.Out.Contents())\n\t\t\t\t})\n\n\t\t\t\tIt(\"keeps volumes and containers after restart\", func() {\n\t\t\t\t\tBy(\"completing the restart\")\n\t\t\t\t\t<-restartSession.Exited\n\t\t\t\t\tExpect(restartSession.ExitCode()).To(Equal(0))\n\n\t\t\t\t\tBy(\"retaining cached image resource in second job build\")\n\t\t\t\t\tbuildSession := spawnFly(\"trigger-job\", \"-w\", \"-j\", \"topgun\/simple-job\")\n\t\t\t\t\t<-buildSession.Exited\n\t\t\t\t\tExpect(buildSession).NotTo(gbytes.Say(\"fetching .*busybox.*\"))\n\t\t\t\t\tExpect(buildSession.ExitCode()).To(Equal(0))\n\n\t\t\t\t\tBy(\"retaining check containers\")\n\t\t\t\t\thijackSession := spawnFly(\"hijack\", \"-c\", \"topgun\/tick-tock\", \"--\", \"hostname\")\n\t\t\t\t\t<-hijackSession.Exited\n\t\t\t\t\tExpect(buildSession.ExitCode()).To(Equal(0))\n\n\t\t\t\t\tcurrentContainerID := string(hijackSession.Out.Contents())\n\t\t\t\t\tExpect(currentContainerID).To(Equal(preservedContainerID))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"with an interruptible build in-flight\", func() {\n\t\t\t\tvar buildSession *gexec.Session\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tBy(\"setting pipeline that has an infinite but interruptible job\")\n\t\t\t\t\tfly(\"set-pipeline\", \"-n\", \"-c\", \"pipelines\/interruptible.yml\", \"-p\", \"topgun\")\n\n\t\t\t\t\tBy(\"unpausing the pipeline\")\n\t\t\t\t\tfly(\"unpause-pipeline\", \"-p\", \"topgun\")\n\n\t\t\t\t\tBy(\"triggering a job\")\n\t\t\t\t\tbuildSession = spawnFly(\"trigger-job\", \"-w\", \"-j\", \"topgun\/interruptible-job\")\n\t\t\t\t\tEventually(buildSession).Should(gbytes.Say(\"waiting forever\"))\n\t\t\t\t})\n\n\t\t\t\tIt(\"does not wait for the build\", func() {\n\t\t\t\t\tBy(\"completing the restart without the drain timeout kicking in\")\n\t\t\t\t\tEventually(restartSession, 5*time.Minute).Should(gexec.Exit(0))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"with uninterruptible build in-flight\", func() {\n\t\t\t\tvar buildSession *gexec.Session\n\t\t\t\tvar buildID string\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tbuildSession = spawnFly(\"execute\", \"-c\", \"tasks\/wait.yml\")\n\t\t\t\t\tEventually(buildSession).Should(gbytes.Say(\"executing build\"))\n\n\t\t\t\t\tbuildRegex := regexp.MustCompile(`executing build (\\d+)`)\n\t\t\t\t\tmatches := buildRegex.FindSubmatch(buildSession.Out.Contents())\n\t\t\t\t\tbuildID = string(matches[1])\n\n\t\t\t\t\tEventually(buildSession).Should(gbytes.Say(\"waiting for \/tmp\/stop-waiting\"))\n\t\t\t\t})\n\n\t\t\t\tAfterEach(func() {\n\t\t\t\t\tbuildSession.Signal(os.Interrupt)\n\t\t\t\t\t<-buildSession.Exited\n\t\t\t\t})\n\n\t\t\t\tIt(\"waits for the build\", func() {\n\t\t\t\t\tEventually(restartSession).Should(gbytes.Say(`Updating (instance|job)`))\n\t\t\t\t\tConsistently(restartSession, 5*time.Minute).ShouldNot(gexec.Exit())\n\t\t\t\t})\n\n\t\t\t\tIt(\"finishes restarting once the build is done\", func() {\n\t\t\t\t\tBy(\"hijacking the build to tell it to finish\")\n\t\t\t\t\t<-flyHijackTask(\n\t\t\t\t\t\t\"-b\", buildID,\n\t\t\t\t\t\t\"-s\", \"one-off\",\n\t\t\t\t\t\t\"touch\", \"\/tmp\/stop-waiting\",\n\t\t\t\t\t).Exited\n\n\t\t\t\t\tBy(\"waiting for the build to exit\")\n\t\t\t\t\tEventually(buildSession).Should(gbytes.Say(\"done\"))\n\t\t\t\t\t<-buildSession.Exited\n\t\t\t\t\tExpect(buildSession.ExitCode()).To(Equal(0))\n\n\t\t\t\t\tBy(\"successfully restarting\")\n\t\t\t\t\t<-restartSession.Exited\n\t\t\t\t\tExpect(restartSession.ExitCode()).To(Equal(0))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t}\n\n\tContext(\"with one worker\", func() {\n\t\tBeforeEach(func() {\n\t\t\tDeploy(\"deployments\/concourse-separate-forwarded-worker.yml\")\n\t\t\twaitForRunningWorker()\n\t\t})\n\n\t\tdescribeRestartingTheWorker()\n\t})\n\n\tContext(\"with a single team worker\", func() {\n\t\tBeforeEach(func() {\n\t\t\tDeploy(\"deployments\/concourse-separate-forwarded-worker.yml\", \"-o\", \"operations\/separate-worker-team.yml\")\n\n\t\t\tsetTeam := spawnFlyInteractive(bytes.NewBufferString(\"y\\n\"), \"set-team\", \"-n\", \"team-a\", \"--allow-all-users\")\n\t\t\t<-setTeam.Exited\n\t\t\tExpect(setTeam.ExitCode()).To(Equal(0))\n\n\t\t\tfly(\"login\", \"-c\", atcExternalURL, \"-n\", \"team-a\", \"-u\", atcUsername, \"-p\", atcPassword)\n\n\t\t\t\/\/ wait for the team's worker to arrive now that team exists\n\t\t\twaitForRunningWorker()\n\t\t})\n\n\t\tdescribeRestartingTheWorker()\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package isolated\n\nimport (\n\t\"os\"\n\n\t\"code.cloudfoundry.org\/cli\/api\/cloudcontroller\/ccversion\"\n\t\"code.cloudfoundry.org\/cli\/integration\/helpers\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gbytes\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"update-user-provided-service command\", func() {\n\tBeforeEach(func() {\n\t\thelpers.SkipIfClientCredentialsTestMode()\n\t\thelpers.SkipIfVersionLessThan(ccversion.MinVersionTagsOnUserProvidedServices)\n\t})\n\n\tDescribe(\"help\", func() {\n\t\tWhen(\"--help flag is set\", func() {\n\t\t\tIt(\"displays command usage to output\", func() {\n\t\t\t\tsession := helpers.CF(\"update-user-provided-service\", \"--help\")\n\t\t\t\teventuallyExpectHelpMessage(session)\n\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t})\n\t\t})\n\t})\n\n\tWhen(\"the environment is not setup correctly\", func() {\n\t\tIt(\"fails with the appropriate errors\", func() {\n\t\t\thelpers.CheckEnvironmentTargetedCorrectly(true, true, ReadOnlyOrg, \"update-user-provided-service\", \"foo\")\n\t\t})\n\t})\n\n\tWhen(\"an api is targeted, the user is logged in, and an org and space are targeted\", func() {\n\t\tconst userName = \"admin\"\n\n\t\tvar (\n\t\t\torgName   string\n\t\t\tspaceName string\n\t\t)\n\n\t\tBeforeEach(func() {\n\t\t\torgName = helpers.NewOrgName()\n\t\t\tspaceName = helpers.NewSpaceName()\n\t\t\thelpers.SetupCF(orgName, spaceName)\n\t\t})\n\n\t\tAfterEach(func() {\n\t\t\thelpers.QuickDeleteOrg(orgName)\n\t\t})\n\n\t\tWhen(\"the user-provided service instance name is not provided\", func() {\n\t\t\tIt(\"displays the help message and exits 1\", func() {\n\t\t\t\tsession := helpers.CF(\"update-user-provided-service\")\n\t\t\t\teventuallyExpectHelpMessage(session)\n\t\t\t\tEventually(session).Should(Exit(1))\n\t\t\t})\n\t\t})\n\n\t\tWhen(\"there are unknown additional arguments\", func() {\n\t\t\tIt(\"displays the help message and exits 1\", func() {\n\t\t\t\tsession := helpers.CF(\"update-user-provided-service\", \"service-name\", \"additional\", \"invalid\", \"arguments\")\n\t\t\t\teventuallyExpectHelpMessage(session)\n\t\t\t\tEventually(session).Should(Exit(1))\n\t\t\t})\n\t\t})\n\n\t\tWhen(\"the user-provided service instance does not exist\", func() {\n\t\t\tIt(\"displays an informative error and exits 1\", func() {\n\t\t\t\tsession := helpers.CF(\"update-user-provided-service\", \"non-existent-service\")\n\t\t\t\tEventually(session.Err).Should(Say(\"Service instance non-existent-service not found\"))\n\t\t\t\tEventually(session.Out).Should(Say(\"FAILED\"))\n\t\t\t\tEventually(session).Should(Exit(1))\n\t\t\t})\n\t\t})\n\n\t\tWhen(\"the user-provided service exists\", func() {\n\t\t\tvar serviceName string\n\n\t\t\tBeforeEach(func() {\n\t\t\t\tserviceName = randomUserProvidedServiceName()\n\t\t\t\tcreateUserProvidedService(serviceName)\n\t\t\t})\n\n\t\t\tAfterEach(func() {\n\t\t\t\tdeleteUserProvidedService(serviceName)\n\t\t\t})\n\n\t\t\tWhen(\"no flags are provided\", func() {\n\t\t\t\tIt(\"displays an informative message and exits 0\", func() {\n\t\t\t\t\tsession := helpers.CF(\"update-user-provided-service\", serviceName)\n\t\t\t\t\tEventually(session.Out).Should(Say(\"No flags specified. No changes were made.\"))\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tWhen(\"flags are provided\", func() {\n\t\t\t\tIt(\"displays success message, exits 0, and updates the service\", func() {\n\t\t\t\t\tsession := helpers.CF(\n\t\t\t\t\t\t`update-user-provided-service`, serviceName,\n\t\t\t\t\t\t`-l`, `syslog:\/\/example.com`,\n\t\t\t\t\t\t`-p`, `{\"some\": \"credentials\"}`,\n\t\t\t\t\t\t`-r`, `https:\/\/example.com`,\n\t\t\t\t\t\t`-t`, `\"tag1,tag2\"`,\n\t\t\t\t\t)\n\n\t\t\t\t\teventuallyExpectOKMessage(session, serviceName, orgName, spaceName, userName)\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\n\t\t\t\t\tsession = helpers.CF(\"service\", serviceName)\n\t\t\t\t\tEventually(session).Should(Say(`tags:\\s+tag1,\\s*tag2`))\n\t\t\t\t\tEventually(session).Should(Say(`route service url:\\s+https:\/\/example.com`))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"when the user-provided service already has values\", func() {\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tsession := helpers.CF(\n\t\t\t\t\t\t`update-user-provided-service`, serviceName,\n\t\t\t\t\t\t`-l`, `syslog:\/\/example.com`,\n\t\t\t\t\t\t`-p`, `{\"some\": \"credentials\"}`,\n\t\t\t\t\t\t`-r`, `https:\/\/example.com`,\n\t\t\t\t\t\t`-t`, `\"tag1,tag2\"`,\n\t\t\t\t\t)\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\n\t\t\t\t\tsession = helpers.CF(\"service\", serviceName)\n\t\t\t\t\tEventually(session).Should(Say(`tags:\\s+tag1,\\s*tag2`))\n\t\t\t\t\tEventually(session).Should(Say(`route service url:\\s+https:\/\/example.com`))\n\t\t\t\t})\n\n\t\t\t\tIt(\"can unset previous values provideding empty strings as flag values\", func() {\n\t\t\t\t\tsession := helpers.CF(\n\t\t\t\t\t\t`update-user-provided-service`, serviceName,\n\t\t\t\t\t\t`-l`, `\"\"`,\n\t\t\t\t\t\t`-p`, `\"\"`,\n\t\t\t\t\t\t`-r`, `\"\"`,\n\t\t\t\t\t\t`-t`, `\"\"`,\n\t\t\t\t\t)\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\n\t\t\t\t\tsession = helpers.CF(\"service\", serviceName)\n\t\t\t\t\tConsistently(session).ShouldNot(Say(`tags:\\s+tag1,\\s*tag2`))\n\t\t\t\t\tConsistently(session).ShouldNot(Say(`route service url:\\s+https:\/\/example.com`))\n\t\t\t\t})\n\n\t\t\t\tIt(\"does not unset previous values for flags that are not provided\", func() {\n\t\t\t\t\tsession := helpers.CF(\n\t\t\t\t\t\t`update-user-provided-service`, serviceName,\n\t\t\t\t\t\t`-l`, `\"\"`,\n\t\t\t\t\t\t`-p`, `\"\"`,\n\t\t\t\t\t)\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\n\t\t\t\t\tsession = helpers.CF(\"service\", serviceName)\n\t\t\t\t\tEventually(session).Should(Say(`tags:\\s+tag1,\\s*tag2`))\n\t\t\t\t\tEventually(session).Should(Say(`route service url:\\s+https:\/\/example.com`))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tWhen(\"requesting interactive credentials\", func() {\n\t\t\t\tvar buffer *Buffer\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tbuffer = NewBuffer()\n\t\t\t\t\t_, err := buffer.Write([]byte(\"fake-username\\nfake-password\\n\"))\n\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t})\n\n\t\t\t\tIt(\"requests the credentials at a prompt\", func() {\n\t\t\t\t\tsession := helpers.CFWithStdin(buffer, \"update-user-provided-service\", serviceName, \"-p\", `\"username,password\"`)\n\n\t\t\t\t\tEventually(session).Should(Say(\"username: \"))\n\t\t\t\t\tEventually(session).Should(Say(\"password: \"))\n\t\t\t\t\tConsistently(session).ShouldNot(Say(\"fake-username\"), \"credentials should not be echoed to the user\")\n\t\t\t\t\tConsistently(session).ShouldNot(Say(\"fake-password\"), \"credentials should not be echoed to the user\")\n\t\t\t\t\teventuallyExpectOKMessage(session, serviceName, orgName, spaceName, userName)\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tWhen(\"reading JSON credentials from a file\", func() {\n\t\t\t\tvar path string\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tpath = helpers.TempFileWithContent(`{\"some\": \"credentials\"}`)\n\t\t\t\t})\n\n\t\t\t\tAfterEach(func() {\n\t\t\t\t\tExpect(os.Remove(path)).To(Succeed())\n\t\t\t\t})\n\n\t\t\t\tIt(\"accepts a file path\", func() {\n\t\t\t\t\tsession := helpers.CF(\"update-user-provided-service\", serviceName, \"-p\", path)\n\n\t\t\t\t\tBy(\"checking that it does not interpret the file name as request for an interactive credential prompt\")\n\t\t\t\t\tConsistently(session.Out.Contents()).ShouldNot(ContainSubstring(path))\n\n\t\t\t\t\tBy(\"succeeding\")\n\t\t\t\t\teventuallyExpectOKMessage(session, serviceName, orgName, spaceName, userName)\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n})\n\nfunc eventuallyExpectHelpMessage(session *Session) {\n\tEventually(session).Should(Say(`NAME:`))\n\tEventually(session).Should(Say(`\\s+update-user-provided-service - Update user-provided service instance`))\n\tEventually(session).Should(Say(`USAGE:`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service SERVICE_INSTANCE \\[-p CREDENTIALS\\] \\[-l SYSLOG_DRAIN_URL\\] \\[-r ROUTE_SERVICE_URL\\] \\[-t TAGS\\]`))\n\tEventually(session).Should(Say(`\\s+Pass comma separated credential parameter names to enable interactive mode:`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service SERVICE_INSTANCE -p \"comma, separated, parameter, names\"`))\n\tEventually(session).Should(Say(`\\s+Pass credential parameters as JSON to create a service non-interactively:`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service SERVICE_INSTANCE -p '{\"key1\":\"value1\",\"key2\":\"value2\"}'`))\n\tEventually(session).Should(Say(`\\s+Specify a path to a file containing JSON:`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service SERVICE_INSTANCE -p PATH_TO_FILE`))\n\tEventually(session).Should(Say(`EXAMPLES:`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service my-db-mine -p '{\"username\":\"admin\", \"password\":\"pa55woRD\"}'`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service my-db-mine -p \/path\/to\/credentials.json`))\n\tEventually(session).Should(Say(`\\s+cf create-user-provided-service my-db-mine -t \"list, of, tags\"`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service my-drain-service -l syslog:\/\/example.com`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service my-route-service -r https:\/\/example.com`))\n\tEventually(session).Should(Say(`ALIAS:`))\n\tEventually(session).Should(Say(`\\s+uups`))\n\tEventually(session).Should(Say(`OPTIONS:`))\n\tEventually(session).Should(Say(`\\s+-l\\s+URL to which logs for bound applications will be streamed`))\n\tEventually(session).Should(Say(`\\s+-p\\s+Credentials, provided inline or in a file, to be exposed in the VCAP_SERVICES environment variable for bound applications. Provided credentials will override existing credentials.`))\n\tEventually(session).Should(Say(`\\s+-r\\s+URL to which requests for bound routes will be forwarded. Scheme for this URL must be https`))\n\tEventually(session).Should(Say(`\\s+-t\\s+User provided tags`))\n\tEventually(session).Should(Say(`SEE ALSO:`))\n\tEventually(session).Should(Say(`\\s+rename-service, services, update-service`))\n}\n\nfunc eventuallyExpectOKMessage(session *Session, serviceName, orgName, spaceName, userName string) {\n\tEventually(session.Out).Should(Say(\"Updating user provided service %s in org %s \/ space %s as %s...\", serviceName, orgName, spaceName, userName))\n\tEventually(session.Out).Should(Say(\"OK\"))\n\tEventually(session.Out).Should(Say(\"TIP: Use 'cf restage' for any bound apps to ensure your env variable changes take effect\"))\n}\n\nfunc randomUserProvidedServiceName() string {\n\treturn helpers.PrefixedRandomName(\"ups\")\n}\n\nfunc createUserProvidedService(name string) {\n\tEventually(helpers.CF(\"create-user-provided-service\", name)).Should(Exit(0))\n}\n\nfunc deleteUserProvidedService(name string) {\n\tEventually(helpers.CF(\"delete-service\", name)).Should(Exit(0))\n}\n<commit_msg>Run more isi tests in client credentials mode<commit_after>package isolated\n\nimport (\n\t\"os\"\n\n\t\"code.cloudfoundry.org\/cli\/api\/cloudcontroller\/ccversion\"\n\t\"code.cloudfoundry.org\/cli\/integration\/helpers\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gbytes\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"update-user-provided-service command\", func() {\n\tBeforeEach(func() {\n\t\thelpers.SkipIfVersionLessThan(ccversion.MinVersionTagsOnUserProvidedServices)\n\t})\n\n\tDescribe(\"help\", func() {\n\t\tWhen(\"--help flag is set\", func() {\n\t\t\tIt(\"displays command usage to output\", func() {\n\t\t\t\tsession := helpers.CF(\"update-user-provided-service\", \"--help\")\n\t\t\t\teventuallyExpectHelpMessage(session)\n\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t})\n\t\t})\n\t})\n\n\tWhen(\"the environment is not setup correctly\", func() {\n\t\tIt(\"fails with the appropriate errors\", func() {\n\t\t\thelpers.CheckEnvironmentTargetedCorrectly(true, true, ReadOnlyOrg, \"update-user-provided-service\", \"foo\")\n\t\t})\n\t})\n\n\tWhen(\"an api is targeted, the user is logged in, and an org and space are targeted\", func() {\n\t\tvar (\n\t\t\tuserName  string\n\t\t\torgName   string\n\t\t\tspaceName string\n\t\t)\n\n\t\tBeforeEach(func() {\n\t\t\torgName = helpers.NewOrgName()\n\t\t\tspaceName = helpers.NewSpaceName()\n\t\t\thelpers.SetupCF(orgName, spaceName)\n\t\t\tuserName, _ = helpers.GetCredentials()\n\t\t})\n\n\t\tAfterEach(func() {\n\t\t\thelpers.QuickDeleteOrg(orgName)\n\t\t})\n\n\t\tWhen(\"the user-provided service instance name is not provided\", func() {\n\t\t\tIt(\"displays the help message and exits 1\", func() {\n\t\t\t\tsession := helpers.CF(\"update-user-provided-service\")\n\t\t\t\teventuallyExpectHelpMessage(session)\n\t\t\t\tEventually(session).Should(Exit(1))\n\t\t\t})\n\t\t})\n\n\t\tWhen(\"there are unknown additional arguments\", func() {\n\t\t\tIt(\"displays the help message and exits 1\", func() {\n\t\t\t\tsession := helpers.CF(\"update-user-provided-service\", \"service-name\", \"additional\", \"invalid\", \"arguments\")\n\t\t\t\teventuallyExpectHelpMessage(session)\n\t\t\t\tEventually(session).Should(Exit(1))\n\t\t\t})\n\t\t})\n\n\t\tWhen(\"the user-provided service instance does not exist\", func() {\n\t\t\tIt(\"displays an informative error and exits 1\", func() {\n\t\t\t\tsession := helpers.CF(\"update-user-provided-service\", \"non-existent-service\")\n\t\t\t\tEventually(session.Err).Should(Say(\"Service instance non-existent-service not found\"))\n\t\t\t\tEventually(session.Out).Should(Say(\"FAILED\"))\n\t\t\t\tEventually(session).Should(Exit(1))\n\t\t\t})\n\t\t})\n\n\t\tWhen(\"the user-provided service exists\", func() {\n\t\t\tvar serviceName string\n\n\t\t\tBeforeEach(func() {\n\t\t\t\tserviceName = randomUserProvidedServiceName()\n\t\t\t\tcreateUserProvidedService(serviceName)\n\t\t\t})\n\n\t\t\tAfterEach(func() {\n\t\t\t\tdeleteUserProvidedService(serviceName)\n\t\t\t})\n\n\t\t\tWhen(\"no flags are provided\", func() {\n\t\t\t\tIt(\"displays an informative message and exits 0\", func() {\n\t\t\t\t\tsession := helpers.CF(\"update-user-provided-service\", serviceName)\n\t\t\t\t\tEventually(session.Out).Should(Say(\"No flags specified. No changes were made.\"))\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tWhen(\"flags are provided\", func() {\n\t\t\t\tIt(\"displays success message, exits 0, and updates the service\", func() {\n\t\t\t\t\tsession := helpers.CF(\n\t\t\t\t\t\t`update-user-provided-service`, serviceName,\n\t\t\t\t\t\t`-l`, `syslog:\/\/example.com`,\n\t\t\t\t\t\t`-p`, `{\"some\": \"credentials\"}`,\n\t\t\t\t\t\t`-r`, `https:\/\/example.com`,\n\t\t\t\t\t\t`-t`, `\"tag1,tag2\"`,\n\t\t\t\t\t)\n\n\t\t\t\t\teventuallyExpectOKMessage(session, serviceName, orgName, spaceName, userName)\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\n\t\t\t\t\tsession = helpers.CF(\"service\", serviceName)\n\t\t\t\t\tEventually(session).Should(Say(`tags:\\s+tag1,\\s*tag2`))\n\t\t\t\t\tEventually(session).Should(Say(`route service url:\\s+https:\/\/example.com`))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"when the user-provided service already has values\", func() {\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tsession := helpers.CF(\n\t\t\t\t\t\t`update-user-provided-service`, serviceName,\n\t\t\t\t\t\t`-l`, `syslog:\/\/example.com`,\n\t\t\t\t\t\t`-p`, `{\"some\": \"credentials\"}`,\n\t\t\t\t\t\t`-r`, `https:\/\/example.com`,\n\t\t\t\t\t\t`-t`, `\"tag1,tag2\"`,\n\t\t\t\t\t)\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\n\t\t\t\t\tsession = helpers.CF(\"service\", serviceName)\n\t\t\t\t\tEventually(session).Should(Say(`tags:\\s+tag1,\\s*tag2`))\n\t\t\t\t\tEventually(session).Should(Say(`route service url:\\s+https:\/\/example.com`))\n\t\t\t\t})\n\n\t\t\t\tIt(\"can unset previous values provideding empty strings as flag values\", func() {\n\t\t\t\t\tsession := helpers.CF(\n\t\t\t\t\t\t`update-user-provided-service`, serviceName,\n\t\t\t\t\t\t`-l`, `\"\"`,\n\t\t\t\t\t\t`-p`, `\"\"`,\n\t\t\t\t\t\t`-r`, `\"\"`,\n\t\t\t\t\t\t`-t`, `\"\"`,\n\t\t\t\t\t)\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\n\t\t\t\t\tsession = helpers.CF(\"service\", serviceName)\n\t\t\t\t\tConsistently(session).ShouldNot(Say(`tags:\\s+tag1,\\s*tag2`))\n\t\t\t\t\tConsistently(session).ShouldNot(Say(`route service url:\\s+https:\/\/example.com`))\n\t\t\t\t})\n\n\t\t\t\tIt(\"does not unset previous values for flags that are not provided\", func() {\n\t\t\t\t\tsession := helpers.CF(\n\t\t\t\t\t\t`update-user-provided-service`, serviceName,\n\t\t\t\t\t\t`-l`, `\"\"`,\n\t\t\t\t\t\t`-p`, `\"\"`,\n\t\t\t\t\t)\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\n\t\t\t\t\tsession = helpers.CF(\"service\", serviceName)\n\t\t\t\t\tEventually(session).Should(Say(`tags:\\s+tag1,\\s*tag2`))\n\t\t\t\t\tEventually(session).Should(Say(`route service url:\\s+https:\/\/example.com`))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tWhen(\"requesting interactive credentials\", func() {\n\t\t\t\tvar buffer *Buffer\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tbuffer = NewBuffer()\n\t\t\t\t\t_, err := buffer.Write([]byte(\"fake-username\\nfake-password\\n\"))\n\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t})\n\n\t\t\t\tIt(\"requests the credentials at a prompt\", func() {\n\t\t\t\t\tsession := helpers.CFWithStdin(buffer, \"update-user-provided-service\", serviceName, \"-p\", `\"username,password\"`)\n\n\t\t\t\t\tEventually(session).Should(Say(\"username: \"))\n\t\t\t\t\tEventually(session).Should(Say(\"password: \"))\n\t\t\t\t\tConsistently(session).ShouldNot(Say(\"fake-username\"), \"credentials should not be echoed to the user\")\n\t\t\t\t\tConsistently(session).ShouldNot(Say(\"fake-password\"), \"credentials should not be echoed to the user\")\n\t\t\t\t\teventuallyExpectOKMessage(session, serviceName, orgName, spaceName, userName)\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tWhen(\"reading JSON credentials from a file\", func() {\n\t\t\t\tvar path string\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tpath = helpers.TempFileWithContent(`{\"some\": \"credentials\"}`)\n\t\t\t\t})\n\n\t\t\t\tAfterEach(func() {\n\t\t\t\t\tExpect(os.Remove(path)).To(Succeed())\n\t\t\t\t})\n\n\t\t\t\tIt(\"accepts a file path\", func() {\n\t\t\t\t\tsession := helpers.CF(\"update-user-provided-service\", serviceName, \"-p\", path)\n\n\t\t\t\t\tBy(\"checking that it does not interpret the file name as request for an interactive credential prompt\")\n\t\t\t\t\tConsistently(session.Out.Contents()).ShouldNot(ContainSubstring(path))\n\n\t\t\t\t\tBy(\"succeeding\")\n\t\t\t\t\teventuallyExpectOKMessage(session, serviceName, orgName, spaceName, userName)\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n})\n\nfunc eventuallyExpectHelpMessage(session *Session) {\n\tEventually(session).Should(Say(`NAME:`))\n\tEventually(session).Should(Say(`\\s+update-user-provided-service - Update user-provided service instance`))\n\tEventually(session).Should(Say(`USAGE:`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service SERVICE_INSTANCE \\[-p CREDENTIALS\\] \\[-l SYSLOG_DRAIN_URL\\] \\[-r ROUTE_SERVICE_URL\\] \\[-t TAGS\\]`))\n\tEventually(session).Should(Say(`\\s+Pass comma separated credential parameter names to enable interactive mode:`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service SERVICE_INSTANCE -p \"comma, separated, parameter, names\"`))\n\tEventually(session).Should(Say(`\\s+Pass credential parameters as JSON to create a service non-interactively:`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service SERVICE_INSTANCE -p '{\"key1\":\"value1\",\"key2\":\"value2\"}'`))\n\tEventually(session).Should(Say(`\\s+Specify a path to a file containing JSON:`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service SERVICE_INSTANCE -p PATH_TO_FILE`))\n\tEventually(session).Should(Say(`EXAMPLES:`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service my-db-mine -p '{\"username\":\"admin\", \"password\":\"pa55woRD\"}'`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service my-db-mine -p \/path\/to\/credentials.json`))\n\tEventually(session).Should(Say(`\\s+cf create-user-provided-service my-db-mine -t \"list, of, tags\"`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service my-drain-service -l syslog:\/\/example.com`))\n\tEventually(session).Should(Say(`\\s+cf update-user-provided-service my-route-service -r https:\/\/example.com`))\n\tEventually(session).Should(Say(`ALIAS:`))\n\tEventually(session).Should(Say(`\\s+uups`))\n\tEventually(session).Should(Say(`OPTIONS:`))\n\tEventually(session).Should(Say(`\\s+-l\\s+URL to which logs for bound applications will be streamed`))\n\tEventually(session).Should(Say(`\\s+-p\\s+Credentials, provided inline or in a file, to be exposed in the VCAP_SERVICES environment variable for bound applications. Provided credentials will override existing credentials.`))\n\tEventually(session).Should(Say(`\\s+-r\\s+URL to which requests for bound routes will be forwarded. Scheme for this URL must be https`))\n\tEventually(session).Should(Say(`\\s+-t\\s+User provided tags`))\n\tEventually(session).Should(Say(`SEE ALSO:`))\n\tEventually(session).Should(Say(`\\s+rename-service, services, update-service`))\n}\n\nfunc eventuallyExpectOKMessage(session *Session, serviceName, orgName, spaceName, userName string) {\n\tEventually(session.Out).Should(Say(\"Updating user provided service %s in org %s \/ space %s as %s...\", serviceName, orgName, spaceName, userName))\n\tEventually(session.Out).Should(Say(\"OK\"))\n\tEventually(session.Out).Should(Say(\"TIP: Use 'cf restage' for any bound apps to ensure your env variable changes take effect\"))\n}\n\nfunc randomUserProvidedServiceName() string {\n\treturn helpers.PrefixedRandomName(\"ups\")\n}\n\nfunc createUserProvidedService(name string) {\n\tEventually(helpers.CF(\"create-user-provided-service\", name)).Should(Exit(0))\n}\n\nfunc deleteUserProvidedService(name string) {\n\tEventually(helpers.CF(\"delete-service\", name)).Should(Exit(0))\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>(go-deeper) Fix `git apply: bad git-diff - inconsistent old filename`<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage lease_test\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"testing\"\n\t\"testing\/iotest\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/lease\"\n\t\"github.com\/googlecloudplatform\/gcsfuse\/lease\/mock_lease\"\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/oglemock\"\n\t. \"github.com\/jacobsa\/ogletest\"\n)\n\nfunc TestAutoRefreshingReadLease(t *testing.T) { RunTests(t) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst contents = \"taco\"\n\n\/\/ A function that always successfully returns our contents constant.\nfunc returnContents() (rc io.ReadCloser, err error) {\n\trc = ioutil.NopCloser(strings.NewReader(contents))\n\treturn\n}\n\nfunc successfulWrite(p []byte) (n int, err error) {\n\tn = len(p)\n\treturn\n}\n\n\/\/ A ReadCloser that returns the supplied error when closing.\ntype closeErrorReader struct {\n\tWrapped io.Reader\n\tErr     error\n}\n\nfunc (rc *closeErrorReader) Read(p []byte) (n int, err error) {\n\tn, err = rc.Wrapped.Read(p)\n\treturn\n}\n\nfunc (rc *closeErrorReader) Close() (err error) {\n\terr = rc.Err\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Boilerplate\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype AutoRefreshingReadLeaseTest struct {\n\t\/\/ A function that will be invoked for each call to the function given to\n\t\/\/ NewAutoRefreshingReadLease.\n\tf func() (io.ReadCloser, error)\n\n\tmockController Controller\n\tleaser         mock_lease.MockFileLeaser\n\tlease          lease.ReadLease\n}\n\nvar _ SetUpInterface = &AutoRefreshingReadLeaseTest{}\n\nfunc init() { RegisterTestSuite(&AutoRefreshingReadLeaseTest{}) }\n\nfunc (t *AutoRefreshingReadLeaseTest) SetUp(ti *TestInfo) {\n\tt.mockController = ti.MockController\n\n\t\/\/ Set up a function that defers to whatever is currently set as t.f.\n\tf := func() (rc io.ReadCloser, err error) {\n\t\tAssertNe(nil, t.f)\n\t\trc, err = t.f()\n\t\treturn\n\t}\n\n\t\/\/ Set up the leaser.\n\tt.leaser = mock_lease.NewMockFileLeaser(ti.MockController, \"leaser\")\n\n\t\/\/ Set up the lease.\n\tt.lease = lease.NewAutoRefreshingReadLease(\n\t\tt.leaser,\n\t\tint64(len(contents)),\n\t\tf)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *AutoRefreshingReadLeaseTest) Size() {\n\tExpectEq(len(contents), t.lease.Size())\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) LeaserReturnsError() {\n\tvar err error\n\n\t\/\/ NewFile\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(nil, errors.New(\"taco\")))\n\n\t\/\/ Attempt to read.\n\t_, err = t.lease.Read([]byte{})\n\tExpectThat(err, Error(HasSubstr(\"taco\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) CallsFunc() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Downgrade\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(nil, errors.New(\"\")))\n\n\t\/\/ Function\n\tvar called bool\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\tAssertFalse(called)\n\t\tcalled = true\n\n\t\terr = errors.New(\"\")\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\tt.lease.Read([]byte{})\n\tExpectTrue(called)\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) FuncReturnsError() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Downgrade and Revoke\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\tExpectCall(rl, \"Revoke\")()\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\terr = errors.New(\"taco\")\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\t_, err := t.lease.Read([]byte{})\n\tExpectThat(err, Error(HasSubstr(\"taco\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) ContentsReturnReadError() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillRepeatedly(Invoke(successfulWrite))\n\n\t\/\/ Downgrade and Revoke\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\tExpectCall(rl, \"Revoke\")()\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = ioutil.NopCloser(\n\t\t\tiotest.TimeoutReader(\n\t\t\t\tiotest.OneByteReader(\n\t\t\t\t\tstrings.NewReader(contents))))\n\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\t_, err := t.lease.Read([]byte{})\n\tExpectThat(err, Error(HasSubstr(\"Copy\")))\n\tExpectThat(err, Error(HasSubstr(\"timeout\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) ContentsReturnCloseError() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillRepeatedly(Invoke(successfulWrite))\n\n\t\/\/ Downgrade and Revoke\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\tExpectCall(rl, \"Revoke\")()\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = &closeErrorReader{\n\t\t\tWrapped: strings.NewReader(contents),\n\t\t\tErr:     errors.New(\"taco\"),\n\t\t}\n\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\t_, err := t.lease.Read([]byte{})\n\tExpectThat(err, Error(HasSubstr(\"Close\")))\n\tExpectThat(err, Error(HasSubstr(\"taco\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) ContentsAreWrongLength() {\n\tAssertEq(4, len(contents))\n\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillRepeatedly(Invoke(successfulWrite))\n\n\t\/\/ Downgrade and Revoke\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\tExpectCall(rl, \"Revoke\")()\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = ioutil.NopCloser(strings.NewReader(contents[:3]))\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\t_, err := t.lease.Read([]byte{})\n\tExpectThat(err, Error(HasSubstr(\"Copied 3\")))\n\tExpectThat(err, Error(HasSubstr(\"expected 4\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) WritesCorrectData() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tvar written []byte\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillRepeatedly(Invoke(successfulWrite))\n\n\t\/\/ Downgrade and Revoke\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\tExpectCall(rl, \"Revoke\")()\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = ioutil.NopCloser(strings.NewReader(contents))\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\tt.lease.Read([]byte{})\n\tExpectEq(contents, string(written))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) WriteError() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillOnce(Return(0, errors.New(\"taco\")))\n\n\t\/\/ Downgrade and Revoke\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\tExpectCall(rl, \"Revoke\")()\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = ioutil.NopCloser(strings.NewReader(contents))\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\t_, err := t.lease.Read([]byte{})\n\tExpectThat(err, Error(HasSubstr(\"Copy\")))\n\tExpectThat(err, Error(HasSubstr(\"taco\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Read_Error() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillRepeatedly(Invoke(successfulWrite))\n\n\t\/\/ Read\n\tExpectCall(rwl, \"Read\")(Any()).\n\t\tWillOnce(Return(0, errors.New(\"taco\")))\n\n\t\/\/ Downgrade\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = ioutil.NopCloser(strings.NewReader(contents))\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\tbuf := make([]byte, 1)\n\t_, err := t.lease.Read(buf)\n\n\tExpectThat(err, Error(HasSubstr(\"taco\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Read_Successful() {\n\tconst readLength = 3\n\tAssertLt(readLength, len(contents))\n\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillRepeatedly(Invoke(successfulWrite))\n\n\t\/\/ Read\n\tExpectCall(rwl, \"Read\")(Any()).\n\t\tWillOnce(Invoke(func(p []byte) (n int, err error) {\n\t\tn = copy(p, []byte(contents[0:readLength]))\n\t\treturn\n\t}))\n\n\t\/\/ Downgrade\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = ioutil.NopCloser(strings.NewReader(contents))\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\tbuf := make([]byte, readLength)\n\tn, err := t.lease.Read(buf)\n\n\tAssertEq(nil, err)\n\tAssertEq(readLength, n)\n\tExpectEq(contents[0:n], string(buf[0:n]))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) DowngradesAfterReadAt() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) DowngradesAfterSeek() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Upgrade_Error() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Upgrade_Success() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Upgrade_Failure() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) SecondRead_StillValid() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) SecondRead_Revoked_ErrorReading() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) SecondRead_Revoked_Successful() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Revoke() {\n\tAssertTrue(false, \"TODO\")\n}\n<commit_msg>Fixed up test names.<commit_after>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage lease_test\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"testing\"\n\t\"testing\/iotest\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/lease\"\n\t\"github.com\/googlecloudplatform\/gcsfuse\/lease\/mock_lease\"\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/oglemock\"\n\t. \"github.com\/jacobsa\/ogletest\"\n)\n\nfunc TestAutoRefreshingReadLease(t *testing.T) { RunTests(t) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nconst contents = \"taco\"\n\n\/\/ A function that always successfully returns our contents constant.\nfunc returnContents() (rc io.ReadCloser, err error) {\n\trc = ioutil.NopCloser(strings.NewReader(contents))\n\treturn\n}\n\nfunc successfulWrite(p []byte) (n int, err error) {\n\tn = len(p)\n\treturn\n}\n\n\/\/ A ReadCloser that returns the supplied error when closing.\ntype closeErrorReader struct {\n\tWrapped io.Reader\n\tErr     error\n}\n\nfunc (rc *closeErrorReader) Read(p []byte) (n int, err error) {\n\tn, err = rc.Wrapped.Read(p)\n\treturn\n}\n\nfunc (rc *closeErrorReader) Close() (err error) {\n\terr = rc.Err\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Boilerplate\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype AutoRefreshingReadLeaseTest struct {\n\t\/\/ A function that will be invoked for each call to the function given to\n\t\/\/ NewAutoRefreshingReadLease.\n\tf func() (io.ReadCloser, error)\n\n\tmockController Controller\n\tleaser         mock_lease.MockFileLeaser\n\tlease          lease.ReadLease\n}\n\nvar _ SetUpInterface = &AutoRefreshingReadLeaseTest{}\n\nfunc init() { RegisterTestSuite(&AutoRefreshingReadLeaseTest{}) }\n\nfunc (t *AutoRefreshingReadLeaseTest) SetUp(ti *TestInfo) {\n\tt.mockController = ti.MockController\n\n\t\/\/ Set up a function that defers to whatever is currently set as t.f.\n\tf := func() (rc io.ReadCloser, err error) {\n\t\tAssertNe(nil, t.f)\n\t\trc, err = t.f()\n\t\treturn\n\t}\n\n\t\/\/ Set up the leaser.\n\tt.leaser = mock_lease.NewMockFileLeaser(ti.MockController, \"leaser\")\n\n\t\/\/ Set up the lease.\n\tt.lease = lease.NewAutoRefreshingReadLease(\n\t\tt.leaser,\n\t\tint64(len(contents)),\n\t\tf)\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *AutoRefreshingReadLeaseTest) Size() {\n\tExpectEq(len(contents), t.lease.Size())\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) LeaserReturnsError() {\n\tvar err error\n\n\t\/\/ NewFile\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(nil, errors.New(\"taco\")))\n\n\t\/\/ Attempt to read.\n\t_, err = t.lease.Read([]byte{})\n\tExpectThat(err, Error(HasSubstr(\"taco\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) CallsFunc() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Downgrade\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(nil, errors.New(\"\")))\n\n\t\/\/ Function\n\tvar called bool\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\tAssertFalse(called)\n\t\tcalled = true\n\n\t\terr = errors.New(\"\")\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\tt.lease.Read([]byte{})\n\tExpectTrue(called)\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) FuncReturnsError() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Downgrade and Revoke\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\tExpectCall(rl, \"Revoke\")()\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\terr = errors.New(\"taco\")\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\t_, err := t.lease.Read([]byte{})\n\tExpectThat(err, Error(HasSubstr(\"taco\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) ContentsReturnReadError() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillRepeatedly(Invoke(successfulWrite))\n\n\t\/\/ Downgrade and Revoke\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\tExpectCall(rl, \"Revoke\")()\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = ioutil.NopCloser(\n\t\t\tiotest.TimeoutReader(\n\t\t\t\tiotest.OneByteReader(\n\t\t\t\t\tstrings.NewReader(contents))))\n\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\t_, err := t.lease.Read([]byte{})\n\tExpectThat(err, Error(HasSubstr(\"Copy\")))\n\tExpectThat(err, Error(HasSubstr(\"timeout\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) ContentsReturnCloseError() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillRepeatedly(Invoke(successfulWrite))\n\n\t\/\/ Downgrade and Revoke\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\tExpectCall(rl, \"Revoke\")()\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = &closeErrorReader{\n\t\t\tWrapped: strings.NewReader(contents),\n\t\t\tErr:     errors.New(\"taco\"),\n\t\t}\n\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\t_, err := t.lease.Read([]byte{})\n\tExpectThat(err, Error(HasSubstr(\"Close\")))\n\tExpectThat(err, Error(HasSubstr(\"taco\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) ContentsAreWrongLength() {\n\tAssertEq(4, len(contents))\n\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillRepeatedly(Invoke(successfulWrite))\n\n\t\/\/ Downgrade and Revoke\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\tExpectCall(rl, \"Revoke\")()\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = ioutil.NopCloser(strings.NewReader(contents[:3]))\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\t_, err := t.lease.Read([]byte{})\n\tExpectThat(err, Error(HasSubstr(\"Copied 3\")))\n\tExpectThat(err, Error(HasSubstr(\"expected 4\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) WritesCorrectData() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tvar written []byte\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillRepeatedly(Invoke(successfulWrite))\n\n\t\/\/ Downgrade and Revoke\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\tExpectCall(rl, \"Revoke\")()\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = ioutil.NopCloser(strings.NewReader(contents))\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\tt.lease.Read([]byte{})\n\tExpectEq(contents, string(written))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) WriteError() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillOnce(Return(0, errors.New(\"taco\")))\n\n\t\/\/ Downgrade and Revoke\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\tExpectCall(rl, \"Revoke\")()\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = ioutil.NopCloser(strings.NewReader(contents))\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\t_, err := t.lease.Read([]byte{})\n\tExpectThat(err, Error(HasSubstr(\"Copy\")))\n\tExpectThat(err, Error(HasSubstr(\"taco\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Read_Error() {\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillRepeatedly(Invoke(successfulWrite))\n\n\t\/\/ Read\n\tExpectCall(rwl, \"Read\")(Any()).\n\t\tWillOnce(Return(0, errors.New(\"taco\")))\n\n\t\/\/ Downgrade\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = ioutil.NopCloser(strings.NewReader(contents))\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\tbuf := make([]byte, 1)\n\t_, err := t.lease.Read(buf)\n\n\tExpectThat(err, Error(HasSubstr(\"taco\")))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Read_Successful() {\n\tconst readLength = 3\n\tAssertLt(readLength, len(contents))\n\n\t\/\/ NewFile\n\trwl := mock_lease.NewMockReadWriteLease(t.mockController, \"rwl\")\n\tExpectCall(t.leaser, \"NewFile\")().\n\t\tWillOnce(Return(rwl, nil))\n\n\t\/\/ Write\n\tExpectCall(rwl, \"Write\")(Any()).\n\t\tWillRepeatedly(Invoke(successfulWrite))\n\n\t\/\/ Read\n\tExpectCall(rwl, \"Read\")(Any()).\n\t\tWillOnce(Invoke(func(p []byte) (n int, err error) {\n\t\tn = copy(p, []byte(contents[0:readLength]))\n\t\treturn\n\t}))\n\n\t\/\/ Downgrade\n\trl := mock_lease.NewMockReadLease(t.mockController, \"rl\")\n\tExpectCall(rwl, \"Downgrade\")().WillOnce(Return(rl, nil))\n\n\t\/\/ Function\n\tt.f = func() (rc io.ReadCloser, err error) {\n\t\trc = ioutil.NopCloser(strings.NewReader(contents))\n\t\treturn\n\t}\n\n\t\/\/ Attempt to read.\n\tbuf := make([]byte, readLength)\n\tn, err := t.lease.Read(buf)\n\n\tAssertEq(nil, err)\n\tAssertEq(readLength, n)\n\tExpectEq(contents[0:n], string(buf[0:n]))\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) ReadAt_Error() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) ReadAt_Successful() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Seek_Error() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Seek_Successful() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Upgrade_Error() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Upgrade_Success() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Upgrade_Failure() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) SecondRead_StillValid() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) SecondRead_Revoked_ErrorReading() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) SecondRead_Revoked_Successful() {\n\tAssertTrue(false, \"TODO\")\n}\n\nfunc (t *AutoRefreshingReadLeaseTest) Revoke() {\n\tAssertTrue(false, \"TODO\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/base32\"\n\t\"flag\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"golang.org\/x\/crypto\/curve25519\"\n\n\tpond \"github.com\/unixninja92\/Div-III-Server\/protos\"\n\t\"github.com\/unixninja92\/Div-III-Server\/server\/protos\"\n\t\"github.com\/unixninja92\/Div-III-Server\/transport\"\n)\n\nvar (\n\tbaseDirectory *string = flag.String(\"base-directory\", \"\", \"directory to store server state and config\")\n\tinitFlag      *bool   = flag.Bool(\"init\", false, \"if true, setup a new base directory\")\n\tport          *int    = flag.Int(\"port\", 16333, \"TCP port to use when setting up a new base directory\")\n\tmakeAnnounce  *string = flag.String(\"make-announce\", \"\", \"If set, the location of a text file containing an announcement message which will be written to stdout in binary.\")\n\tlifelineFd    *int    = flag.Int(\"lifeline-fd\", -1, \"If set, the server will exit when this descriptor returns EOF\")\n)\n\nconst configFilename = \"config\"\nconst identityFilename = \"identity\"\n\nfunc main() {\n\tflag.Parse()\n\n\tif len(*makeAnnounce) > 0 {\n\t\tmsgBytes, err := ioutil.ReadFile(*makeAnnounce)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tannounce := &pond.Message{\n\t\t\tId:           proto.Uint64(0),\n\t\t\tTime:         proto.Int64(time.Now().Unix()),\n\t\t\tBody:         msgBytes,\n\t\t\tMyNextDh:     []byte{},\n\t\t\tBodyEncoding: pond.Message_RAW.Enum(),\n\t\t}\n\t\tannounceBytes, err := proto.Marshal(announce)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tos.Stdout.Write(announceBytes)\n\t\treturn\n\t}\n\n\tif len(*baseDirectory) == 0 {\n\t\tlog.Fatalf(\"Must give --base-directory\")\n\t\treturn\n\t}\n\tconfigPath := filepath.Join(*baseDirectory, configFilename)\n\n\tvar identity [32]byte\n\tif *initFlag {\n\t\tif err := os.MkdirAll(*baseDirectory, 0700); err != nil {\n\t\t\tlog.Fatalf(\"Failed to create base directory: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif _, err := io.ReadFull(rand.Reader, identity[:]); err != nil {\n\t\t\tlog.Fatalf(\"Failed to read random bytes: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif err := ioutil.WriteFile(filepath.Join(*baseDirectory, identityFilename), identity[:], 0600); err != nil {\n\t\t\tlog.Fatalf(\"Failed to write identity file: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tdefaultConfig := &protos.Config{\n\t\t\tPort: proto.Uint32(uint32(*port)),\n\t\t}\n\n\t\tconfigFile, err := os.OpenFile(configPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to create config file: %s\", err)\n\t\t}\n\t\tproto.MarshalText(configFile, defaultConfig)\n\t\tconfigFile.Close()\n\t}\n\n\tidentityBytes, err := ioutil.ReadFile(filepath.Join(*baseDirectory, identityFilename))\n\tif err != nil {\n\t\tlog.Print(\"Use --init to setup a new base directory\")\n\t\tlog.Fatalf(\"Failed to read identity file: %s\", err)\n\t\treturn\n\t}\n\tif len(identityBytes) != 32 {\n\t\tlog.Fatalf(\"Identity file is not 32 bytes long\")\n\t\treturn\n\t}\n\tcopy(identity[:], identityBytes)\n\n\tconfig := new(protos.Config)\n\tconfigBytes, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"No config file found\")\n\t}\n\n\tif err := proto.UnmarshalText(string(configBytes), config); err != nil {\n\t\tlog.Fatalf(\"Failed to parse config: %s\", err)\n\t}\n\n\tif err := maybeConvertMessagesToNewFormat(*baseDirectory); err != nil {\n\t\tlog.Fatalf(\"Failed to convert messages to new naming scheme: %s\", err)\n\t}\n\n\tip := net.IPv4(127, 0, 0, 1) \/\/ IPv4 loopback interface\n\n\tif config.Address != nil {\n\t\tif ip = net.ParseIP(*config.Address); ip == nil {\n\t\t\tlog.Fatalf(\"Failed to parse address from config: %s\", ip)\n\t\t}\n\t}\n\n\tlistenAddr := net.TCPAddr{\n\t\tIP:   ip,\n\t\tPort: int(*config.Port),\n\t}\n\tlistener, err := net.ListenTCP(\"tcp\", &listenAddr)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to listen on port: %s\", err)\n\t}\n\n\tvar identityPublic [32]byte\n\tcurve25519.ScalarBaseMult(&identityPublic, &identity)\n\tidentityString := strings.Replace(base32.StdEncoding.EncodeToString(identityPublic[:]), \"=\", \"\", -1)\n\tlog.Printf(\"Started. Listening on port %d with identity %s\", listener.Addr().(*net.TCPAddr).Port, identityString)\n\n\tserver := NewServer(*baseDirectory, config.GetAllowRegistration())\n\n\tif *lifelineFd > -1 {\n\t\tlifeline := os.NewFile(uintptr(*lifelineFd), \"lifeline\")\n\t\tgo func() {\n\t\t\tvar buf [1]byte\n\t\t\tlifeline.Read(buf[:])\n\t\t\tos.Exit(255)\n\t\t}()\n\t}\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error accepting connection: %s\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo handleConnection(server, conn, &identity)\n\t}\n}\n\nfunc handleConnection(server *Server, rawConn net.Conn, identity *[32]byte) {\n\trawConn.SetDeadline(time.Now().Add(30 * time.Second))\n\tconn := transport.NewServer(rawConn, identity)\n\n\tif err := conn.Handshake(); err != nil {\n\t\tlog.Printf(\"Error from handshake: %s\", err)\n\t\treturn\n\t}\n\n\tserver.Process(conn)\n\tconn.Close()\n}\n\n\/\/ maybeConvertMessagesToNewFormat scans the accounts directory for messages\n\/\/ under the old naming scheme and updates them to use the new\n\/\/ naming scheme that includes millisecond delivery time at the beginning.\nfunc maybeConvertMessagesToNewFormat(baseDirectory string) error {\n\taccountsPath := filepath.Join(baseDirectory, \"accounts\")\n\taccountsDir, err := os.Open(accountsPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tdefer accountsDir.Close()\n\n\taccounts, err := accountsDir.Readdir(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, ent := range accounts {\n\t\taccount := ent.Name()\n\t\tif len(account) != 64 || strings.IndexFunc(account, notLowercaseHex) != -1 {\n\t\t\tcontinue\n\t\t}\n\n\t\taccountPath := filepath.Join(accountsPath, account)\n\t\taccountDir, err := os.Open(accountPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tents, err := accountDir.Readdir(0)\n\t\taccountDir.Close()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, ent := range ents {\n\t\t\tname := ent.Name()\n\t\t\tif len(name) != 64 || strings.IndexFunc(name, notLowercaseHex) != -1 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\toldName := filepath.Join(accountPath, name)\n\t\t\tnewName := filepath.Join(accountPath, timeToFilenamePrefix(ent.ModTime())+name)\n\t\t\tif err := os.Rename(oldName, newName); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>Upped timeout on connections<commit_after>package main\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/base32\"\n\t\"flag\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"golang.org\/x\/crypto\/curve25519\"\n\n\tpond \"github.com\/unixninja92\/Div-III-Server\/protos\"\n\t\"github.com\/unixninja92\/Div-III-Server\/server\/protos\"\n\t\"github.com\/unixninja92\/Div-III-Server\/transport\"\n)\n\nvar (\n\tbaseDirectory *string = flag.String(\"base-directory\", \"\", \"directory to store server state and config\")\n\tinitFlag      *bool   = flag.Bool(\"init\", false, \"if true, setup a new base directory\")\n\tport          *int    = flag.Int(\"port\", 16333, \"TCP port to use when setting up a new base directory\")\n\tmakeAnnounce  *string = flag.String(\"make-announce\", \"\", \"If set, the location of a text file containing an announcement message which will be written to stdout in binary.\")\n\tlifelineFd    *int    = flag.Int(\"lifeline-fd\", -1, \"If set, the server will exit when this descriptor returns EOF\")\n)\n\nconst configFilename = \"config\"\nconst identityFilename = \"identity\"\n\nfunc main() {\n\tflag.Parse()\n\n\tif len(*makeAnnounce) > 0 {\n\t\tmsgBytes, err := ioutil.ReadFile(*makeAnnounce)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tannounce := &pond.Message{\n\t\t\tId:           proto.Uint64(0),\n\t\t\tTime:         proto.Int64(time.Now().Unix()),\n\t\t\tBody:         msgBytes,\n\t\t\tMyNextDh:     []byte{},\n\t\t\tBodyEncoding: pond.Message_RAW.Enum(),\n\t\t}\n\t\tannounceBytes, err := proto.Marshal(announce)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tos.Stdout.Write(announceBytes)\n\t\treturn\n\t}\n\n\tif len(*baseDirectory) == 0 {\n\t\tlog.Fatalf(\"Must give --base-directory\")\n\t\treturn\n\t}\n\tconfigPath := filepath.Join(*baseDirectory, configFilename)\n\n\tvar identity [32]byte\n\tif *initFlag {\n\t\tif err := os.MkdirAll(*baseDirectory, 0700); err != nil {\n\t\t\tlog.Fatalf(\"Failed to create base directory: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif _, err := io.ReadFull(rand.Reader, identity[:]); err != nil {\n\t\t\tlog.Fatalf(\"Failed to read random bytes: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif err := ioutil.WriteFile(filepath.Join(*baseDirectory, identityFilename), identity[:], 0600); err != nil {\n\t\t\tlog.Fatalf(\"Failed to write identity file: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tdefaultConfig := &protos.Config{\n\t\t\tPort: proto.Uint32(uint32(*port)),\n\t\t}\n\n\t\tconfigFile, err := os.OpenFile(configPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to create config file: %s\", err)\n\t\t}\n\t\tproto.MarshalText(configFile, defaultConfig)\n\t\tconfigFile.Close()\n\t}\n\n\tidentityBytes, err := ioutil.ReadFile(filepath.Join(*baseDirectory, identityFilename))\n\tif err != nil {\n\t\tlog.Print(\"Use --init to setup a new base directory\")\n\t\tlog.Fatalf(\"Failed to read identity file: %s\", err)\n\t\treturn\n\t}\n\tif len(identityBytes) != 32 {\n\t\tlog.Fatalf(\"Identity file is not 32 bytes long\")\n\t\treturn\n\t}\n\tcopy(identity[:], identityBytes)\n\n\tconfig := new(protos.Config)\n\tconfigBytes, err := ioutil.ReadFile(configPath)\n\tif err != nil {\n\t\tlog.Fatalf(\"No config file found\")\n\t}\n\n\tif err := proto.UnmarshalText(string(configBytes), config); err != nil {\n\t\tlog.Fatalf(\"Failed to parse config: %s\", err)\n\t}\n\n\tif err := maybeConvertMessagesToNewFormat(*baseDirectory); err != nil {\n\t\tlog.Fatalf(\"Failed to convert messages to new naming scheme: %s\", err)\n\t}\n\n\tip := net.IPv4(127, 0, 0, 1) \/\/ IPv4 loopback interface\n\n\tif config.Address != nil {\n\t\tif ip = net.ParseIP(*config.Address); ip == nil {\n\t\t\tlog.Fatalf(\"Failed to parse address from config: %s\", ip)\n\t\t}\n\t}\n\n\tlistenAddr := net.TCPAddr{\n\t\tIP:   ip,\n\t\tPort: int(*config.Port),\n\t}\n\tlistener, err := net.ListenTCP(\"tcp\", &listenAddr)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to listen on port: %s\", err)\n\t}\n\n\tvar identityPublic [32]byte\n\tcurve25519.ScalarBaseMult(&identityPublic, &identity)\n\tidentityString := strings.Replace(base32.StdEncoding.EncodeToString(identityPublic[:]), \"=\", \"\", -1)\n\tlog.Printf(\"Started. Listening on port %d with identity %s\", listener.Addr().(*net.TCPAddr).Port, identityString)\n\n\tserver := NewServer(*baseDirectory, config.GetAllowRegistration())\n\n\tif *lifelineFd > -1 {\n\t\tlifeline := os.NewFile(uintptr(*lifelineFd), \"lifeline\")\n\t\tgo func() {\n\t\t\tvar buf [1]byte\n\t\t\tlifeline.Read(buf[:])\n\t\t\tos.Exit(255)\n\t\t}()\n\t}\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error accepting connection: %s\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tgo handleConnection(server, conn, &identity)\n\t}\n}\n\nfunc handleConnection(server *Server, rawConn net.Conn, identity *[32]byte) {\n\trawConn.SetDeadline(time.Now().Add(120 * time.Second))\n\tconn := transport.NewServer(rawConn, identity)\n\n\tif err := conn.Handshake(); err != nil {\n\t\tlog.Printf(\"Error from handshake: %s\", err)\n\t\treturn\n\t}\n\n\tserver.Process(conn)\n\tconn.Close()\n}\n\n\/\/ maybeConvertMessagesToNewFormat scans the accounts directory for messages\n\/\/ under the old naming scheme and updates them to use the new\n\/\/ naming scheme that includes millisecond delivery time at the beginning.\nfunc maybeConvertMessagesToNewFormat(baseDirectory string) error {\n\taccountsPath := filepath.Join(baseDirectory, \"accounts\")\n\taccountsDir, err := os.Open(accountsPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tdefer accountsDir.Close()\n\n\taccounts, err := accountsDir.Readdir(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, ent := range accounts {\n\t\taccount := ent.Name()\n\t\tif len(account) != 64 || strings.IndexFunc(account, notLowercaseHex) != -1 {\n\t\t\tcontinue\n\t\t}\n\n\t\taccountPath := filepath.Join(accountsPath, account)\n\t\taccountDir, err := os.Open(accountPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tents, err := accountDir.Readdir(0)\n\t\taccountDir.Close()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, ent := range ents {\n\t\t\tname := ent.Name()\n\t\t\tif len(name) != 64 || strings.IndexFunc(name, notLowercaseHex) != -1 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\toldName := filepath.Join(accountPath, name)\n\t\t\tnewName := filepath.Join(accountPath, timeToFilenamePrefix(ent.ModTime())+name)\n\t\t\tif err := os.Rename(oldName, newName); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/codegangsta\/martini\"\n\t\"github.com\/martini-contrib\/sessions\"\n\n\t\"io\/ioutil\"\n)\n\nfunc main() {\n\ts := NewServer()\n\tm := martini.Classic()\n\n\n\tsecret,err := ioutil.ReadFile(\".secret\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tstore := sessions.NewCookieStore(secret)\n\tm.Use(sessions.Sessions(\"ask_eecs_auth_session\", store))\n\n\tm.Get(\"\/q\", s.HandleGetQuestions)\n\tm.Post(\"\/q\", s.HandlePostQuestion)\n\tm.Get(\"\/q\/:id\", s.HandleGetQuestion)\n\tm.Put(\"\/q\/:id\", s.HandleEditQuestion)\n\tm.Get(\"\/q\/:id\/vote\/:opt\", s.HandleVote)\n\tm.Post(\"\/q\/:id\/response\", s.HandleQuestionResponse)\n\tm.Post(\"\/q\/:id\/comment\", s.HandleQuestionComment)\n\n\tm.Post(\"\/login\", s.HandleLogin)\n\tm.Post(\"\/register\", s.HandleRegister)\n\tm.Post(\"\/logout\", s.HandleLogout)\n\tm.Post(\"\/me\", s.HandleMe);\n\tm.Run()\n}\n<commit_msg>can comment on responses<commit_after>package main\n\nimport (\n\t\"github.com\/codegangsta\/martini\"\n\t\"github.com\/martini-contrib\/sessions\"\n\n\t\"io\/ioutil\"\n)\n\nfunc main() {\n\ts := NewServer()\n\tm := martini.Classic()\n\n\n\tsecret,err := ioutil.ReadFile(\".secret\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tstore := sessions.NewCookieStore(secret)\n\tm.Use(sessions.Sessions(\"ask_eecs_auth_session\", store))\n\n\tm.Get(\"\/q\", s.HandleGetQuestions)\n\tm.Post(\"\/q\", s.HandlePostQuestion)\n\tm.Get(\"\/q\/:id\", s.HandleGetQuestion)\n\tm.Put(\"\/q\/:id\", s.HandleEditQuestion)\n\tm.Get(\"\/q\/:id\/vote\/:opt\", s.HandleVote)\n\tm.Post(\"\/q\/:id\/response\", s.HandleQuestionResponse)\n\tm.Post(\"\/q\/:id\/response\/:resp\/comment\", s.HandleResponseComment)\n\tm.Post(\"\/q\/:id\/comment\", s.HandleQuestionComment)\n\n\tm.Post(\"\/login\", s.HandleLogin)\n\tm.Post(\"\/register\", s.HandleRegister)\n\tm.Post(\"\/logout\", s.HandleLogout)\n\tm.Post(\"\/me\", s.HandleMe);\n\tm.Run()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"github.com\/marpio\/ownPocket\/server\/contentextractor\"\n\t\"github.com\/marpio\/ownPocket\/server\/dto\"\n)\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"inside req\")\n\tdecoder := json.NewDecoder(r.Body)\n\n\tvar url dto.URL\n\terr := decoder.Decode(&url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tc, err := contentextractor.Extract(url.URL)\n\tlog.Println(c)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", handler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n<commit_msg>Add website extractor package<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"github.com\/marpio\/ownPocket\/server\/dto\"\n\t\"github.com\/marpio\/ownPocket\/server\/websiteextractor\"\n)\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"inside req\")\n\tdecoder := json.NewDecoder(r.Body)\n\n\tvar url dto.URL\n\terr := decoder.Decode(&url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tc, err := contentextractor.Extract(url.URL)\n\tlog.Println(c)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", handler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage sql\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ MySQLConfig is specific to this database\ntype MySQLConfig struct {\n\tHost     string\n\tPort     int\n\tDb       string\n\tUser     string\n\tPassword string\n}\n\nfunc (config *MySQLConfig) getDSN(db string) string {\n\tvar password string\n\tif config.Password != \"\" {\n\t\tpassword = \":\" + config.Password\n\t}\n\n\treturn fmt.Sprintf(\"%v%v@tcp(%v:%d)\/%s?parseTime=True\",\n\t\tconfig.User,\n\t\tpassword,\n\t\tconfig.Host,\n\t\tconfig.Port,\n\t\tdb)\n}\n\n\/\/ CreateDatabase for the MySQLConfig\nfunc (config *MySQLConfig) CreateDatabase() (*gorm.DB, error) {\n\tdb, err := gorm.Open(\"mysql\", config.getDSN(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb.Exec(fmt.Sprintf(\"CREATE DATABASE IF NOT EXISTS %v;\", config.Db))\n\tdb.Close()\n\n\tdb, err = gorm.Open(\"mysql\", config.getDSN(config.Db))\n\terr = db.AutoMigrate(&Issue{}, &IssueEvent{}, &Label{}, &Comment{}).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ We manually print errors.\n\t\/\/db.LogMode(false)\n\n\treturn db, nil\n}\n\n\/\/ AddFlags parses options for database configuration\nfunc (config *MySQLConfig) AddFlags(cmd *cobra.Command) {\n\tcmd.PersistentFlags().StringVar(&config.User, \"user\", \"root\", \"MySql user\")\n\tcmd.PersistentFlags().StringVar(&config.Password, \"password\", \"\", \"MySql password\")\n\tcmd.PersistentFlags().StringVar(&config.Host, \"host\", \"localhost\", \"MySql server IP\")\n\tcmd.PersistentFlags().IntVar(&config.Port, \"port\", 3306, \"MySql server port\")\n\tcmd.PersistentFlags().StringVar(&config.Db, \"database\", \"github\", \"MySql server database name\")\n}\n<commit_msg>velodrome: mysql: Re-activate logs<commit_after>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage sql\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ MySQLConfig is specific to this database\ntype MySQLConfig struct {\n\tHost     string\n\tPort     int\n\tDb       string\n\tUser     string\n\tPassword string\n}\n\nfunc (config *MySQLConfig) getDSN(db string) string {\n\tvar password string\n\tif config.Password != \"\" {\n\t\tpassword = \":\" + config.Password\n\t}\n\n\treturn fmt.Sprintf(\"%v%v@tcp(%v:%d)\/%s?parseTime=True\",\n\t\tconfig.User,\n\t\tpassword,\n\t\tconfig.Host,\n\t\tconfig.Port,\n\t\tdb)\n}\n\n\/\/ CreateDatabase for the MySQLConfig\nfunc (config *MySQLConfig) CreateDatabase() (*gorm.DB, error) {\n\tdb, err := gorm.Open(\"mysql\", config.getDSN(\"\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdb.Exec(fmt.Sprintf(\"CREATE DATABASE IF NOT EXISTS %v;\", config.Db))\n\tdb.Close()\n\n\tdb, err = gorm.Open(\"mysql\", config.getDSN(config.Db))\n\terr = db.AutoMigrate(&Issue{}, &IssueEvent{}, &Label{}, &Comment{}).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn db, nil\n}\n\n\/\/ AddFlags parses options for database configuration\nfunc (config *MySQLConfig) AddFlags(cmd *cobra.Command) {\n\tcmd.PersistentFlags().StringVar(&config.User, \"user\", \"root\", \"MySql user\")\n\tcmd.PersistentFlags().StringVar(&config.Password, \"password\", \"\", \"MySql password\")\n\tcmd.PersistentFlags().StringVar(&config.Host, \"host\", \"localhost\", \"MySql server IP\")\n\tcmd.PersistentFlags().IntVar(&config.Port, \"port\", 3306, \"MySql server port\")\n\tcmd.PersistentFlags().StringVar(&config.Db, \"database\", \"github\", \"MySql server database name\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package btelegram\n\nimport (\n\t\"github.com\/42wim\/matterbridge\/bridge\/config\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/go-telegram-bot-api\/telegram-bot-api\"\n\t\"strconv\"\n)\n\ntype Btelegram struct {\n\tc       *tgbotapi.BotAPI\n\tConfig  *config.Protocol\n\tRemote  chan config.Message\n\tAccount string\n}\n\nvar flog *log.Entry\nvar protocol = \"telegram\"\n\nfunc init() {\n\tflog = log.WithFields(log.Fields{\"module\": protocol})\n}\n\nfunc New(cfg config.Protocol, account string, c chan config.Message) *Btelegram {\n\tb := &Btelegram{}\n\tb.Config = &cfg\n\tb.Remote = c\n\tb.Account = account\n\treturn b\n}\n\nfunc (b *Btelegram) Connect() error {\n\tvar err error\n\tflog.Info(\"Connecting\")\n\tb.c, err = tgbotapi.NewBotAPI(b.Config.Token)\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tupdates, err := b.c.GetUpdatesChan(tgbotapi.NewUpdate(0))\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tflog.Info(\"Connection succeeded\")\n\tgo b.handleRecv(updates)\n\treturn nil\n}\n\nfunc (b *Btelegram) JoinChannel(channel string) error {\n\treturn nil\n}\n\nfunc (b *Btelegram) Send(msg config.Message) error {\n\tflog.Debugf(\"Receiving %#v\", msg)\n\tchatid, err := strconv.ParseInt(msg.Channel, 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm := tgbotapi.NewMessage(chatid, msg.Username + msg.Text)\n\t_, err = b.c.Send(m)\n\treturn err\n}\n\nfunc (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {\n\tfor update := range updates {\n\t\tif update.Message == nil {\n\t\t\tcontinue\n\t\t}\n\t\tflog.Debugf(\"Sending message from %s on %s to gateway\", update.Message.From.UserName, b.Account)\n\t\tb.Remote <- config.Message{Username: update.Message.From.UserName, Text: update.Message.Text, Channel: strconv.FormatInt(update.Message.Chat.ID, 10), Account: b.Account}\n\n\t}\n}\n<commit_msg>Telegram: add markdown (#103)<commit_after>package btelegram\n\nimport (\n\t\"bytes\"\n\t\"html\"\n\t\"strconv\"\n\n\t\"github.com\/42wim\/matterbridge\/bridge\/config\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/go-telegram-bot-api\/telegram-bot-api\"\n\t\"github.com\/russross\/blackfriday\"\n)\n\ntype Btelegram struct {\n\tc       *tgbotapi.BotAPI\n\tConfig  *config.Protocol\n\tRemote  chan config.Message\n\tAccount string\n}\n\nvar flog *log.Entry\nvar protocol = \"telegram\"\n\nfunc init() {\n\tflog = log.WithFields(log.Fields{\"module\": protocol})\n}\n\nfunc New(cfg config.Protocol, account string, c chan config.Message) *Btelegram {\n\tb := &Btelegram{}\n\tb.Config = &cfg\n\tb.Remote = c\n\tb.Account = account\n\treturn b\n}\n\nfunc (b *Btelegram) Connect() error {\n\tvar err error\n\tflog.Info(\"Connecting\")\n\tb.c, err = tgbotapi.NewBotAPI(b.Config.Token)\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tupdates, err := b.c.GetUpdatesChan(tgbotapi.NewUpdate(0))\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tflog.Info(\"Connection succeeded\")\n\tgo b.handleRecv(updates)\n\treturn nil\n}\n\nfunc (b *Btelegram) JoinChannel(channel string) error {\n\treturn nil\n}\n\ntype customHtml struct {\n\tblackfriday.Renderer\n}\n\nfunc (options *customHtml) Paragraph(out *bytes.Buffer, text func() bool) {\n\tmarker := out.Len()\n\n\tif !text() {\n\t\tout.Truncate(marker)\n\t\treturn\n\t}\n\tout.WriteString(\"\\n\")\n}\n\nfunc (options *customHtml) BlockCode(out *bytes.Buffer, text []byte, lang string) {\n\tout.WriteString(\"<pre>\")\n\n\tout.WriteString(html.EscapeString(string(text)))\n\tout.WriteString(\"<\/pre>\\n\")\n}\n\nfunc (options *customHtml) Header(out *bytes.Buffer, text func() bool, level int, id string) {\n\toptions.Paragraph(out, text)\n}\n\nfunc (options *customHtml) HRule(out *bytes.Buffer) {\n\tout.WriteByte('\\n')\n}\n\nfunc (options *customHtml) BlockQuote(out *bytes.Buffer, text []byte) {\n\tout.WriteString(\"> \")\n\tout.Write(text)\n\tout.WriteByte('\\n')\n}\n\nfunc (options *customHtml) List(out *bytes.Buffer, text func() bool, flags int) {\n\toptions.Paragraph(out, text)\n}\n\nfunc (options *customHtml) ListItem(out *bytes.Buffer, text []byte, flags int) {\n\tout.WriteString(\"- \")\n\tout.Write(text)\n\tout.WriteByte('\\n')\n}\n\nfunc (b *Btelegram) Send(msg config.Message) error {\n\tflog.Debugf(\"Receiving %#v\", msg)\n\tchatid, err := strconv.ParseInt(msg.Channel, 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tparsed := blackfriday.Markdown([]byte(msg.Text),\n\t\t&customHtml{blackfriday.HtmlRenderer(blackfriday.HTML_USE_XHTML|blackfriday.HTML_SKIP_IMAGES, \"\", \"\")},\n\t\tblackfriday.EXTENSION_NO_INTRA_EMPHASIS|\n\t\t\tblackfriday.EXTENSION_FENCED_CODE|\n\t\t\tblackfriday.EXTENSION_AUTOLINK|\n\t\t\tblackfriday.EXTENSION_SPACE_HEADERS|\n\t\t\tblackfriday.EXTENSION_HEADER_IDS|\n\t\t\tblackfriday.EXTENSION_BACKSLASH_LINE_BREAK|\n\t\t\tblackfriday.EXTENSION_DEFINITION_LISTS)\n\n\tm := tgbotapi.NewMessage(chatid, msg.Username+string(parsed))\n\tm.ParseMode = \"HTML\"\n\t_, err = b.c.Send(m)\n\treturn err\n}\n\nfunc (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {\n\tfor update := range updates {\n\t\tif update.Message == nil {\n\t\t\tcontinue\n\t\t}\n\t\tflog.Debugf(\"Sending message from %s on %s to gateway\", update.Message.From.UserName, b.Account)\n\t\tb.Remote <- config.Message{Username: update.Message.From.UserName, Text: update.Message.Text, Channel: strconv.FormatInt(update.Message.Chat.ID, 10), Account: b.Account}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package graph\n\nfunc isBipartite(graph [][]int) bool {\n\t\/\/ return useDFS(graph)\n\treturn useBFS(graph)\n}\n\n\/\/ useDFS time complexity O(N), space complexity O(N)\nfunc useDFS(graph [][]int) bool {\n\tn := len(graph)\n\tcolors := make([]int, n)\n\tfor i := range graph {\n\t\tif colors[i] == 0 && !helper(graph, colors, 1, i) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc helper(graph [][]int, colors []int, color, node int) bool {\n\tif colors[node] != 0 {\n\t\treturn colors[node] == color\n\t}\n\t\/\/ mark node with color\n\tcolors[node] = color\n\t\/\/ traverse node's adjances\n\tfor _, adj := range graph[node] {\n\t\tif !helper(graph, colors, -color, adj) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ useBFS time complexity O(N), space complexity O(N)\nfunc useBFS(graph [][]int) bool {\n\tn := len(graph)\n\tcolors := make([]int, n)\n\tq := make([]int, 0, n)\n\t\/\/ the graph may not be connected just traverse all the nodes.\n\tfor i := range graph {\n\t\tif colors[i] != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tcolors[i] = 1\n\t\tq = append(q, i)\n\t\tfor len(q) != 0 {\n\t\t\ttop := q[0]\n\t\t\tq = q[1:]\n\t\t\tfor _, adj := range graph[top] {\n\t\t\t\tif colors[adj] == 0 {\n\t\t\t\t\tcolors[adj] = -colors[top]\n\t\t\t\t\tq = append(q, adj)\n\t\t\t\t} else if colors[adj] == colors[top] {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n<commit_msg>update time complexity for 785 when use bfs<commit_after>package graph\n\nfunc isBipartite(graph [][]int) bool {\n\t\/\/ return useDFS(graph)\n\treturn useBFS(graph)\n}\n\n\/\/ useDFS time complexity O(N), space complexity O(N)\nfunc useDFS(graph [][]int) bool {\n\tn := len(graph)\n\tcolors := make([]int, n)\n\tfor i := range graph {\n\t\tif colors[i] == 0 && !helper(graph, colors, 1, i) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc helper(graph [][]int, colors []int, color, node int) bool {\n\tif colors[node] != 0 {\n\t\treturn colors[node] == color\n\t}\n\t\/\/ mark node with color\n\tcolors[node] = color\n\t\/\/ traverse node's adjances\n\tfor _, adj := range graph[node] {\n\t\tif !helper(graph, colors, -color, adj) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ useBFS time complexity O(V+E), space complexity O(V)\nfunc useBFS(graph [][]int) bool {\n\tn := len(graph)\n\tcolors := make([]int, n)\n\tq := make([]int, 0, n)\n\t\/\/ the graph may not be connected just traverse all the nodes.\n\tfor i := range graph {\n\t\tif colors[i] != 0 {\n\t\t\tcontinue\n\t\t}\n\t\tcolors[i] = 1\n\t\tq = append(q, i)\n\t\tfor len(q) != 0 {\n\t\t\ttop := q[0]\n\t\t\tq = q[1:]\n\t\t\tfor _, adj := range graph[top] {\n\t\t\t\tif colors[adj] == 0 {\n\t\t\t\t\tcolors[adj] = -colors[top]\n\t\t\t\t\tq = append(q, adj)\n\t\t\t\t} else if colors[adj] == colors[top] {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>package admin\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/jinzhu\/now\"\n\t\"github.com\/qor\/qor\"\n\t\"github.com\/qor\/qor\/media_library\"\n\t\"github.com\/qor\/qor\/resource\"\n\t\"github.com\/qor\/qor\/roles\"\n\t\"github.com\/qor\/qor\/utils\"\n)\n\ntype Meta struct {\n\tbase          *Resource\n\tName          string\n\tAlias         string\n\tLabel         string\n\tType          string\n\tValuer        func(interface{}, *qor.Context) interface{}\n\tSetter        func(resource interface{}, metaValues *resource.MetaValues, context *qor.Context)\n\tMetas         []resource.Metaor\n\tResource      resource.Resourcer\n\tCollection    interface{}\n\tGetCollection func(interface{}, *qor.Context) [][]string\n\tPermission    *roles.Permission\n}\n\nfunc (meta *Meta) GetName() string {\n\treturn meta.Name\n}\n\nfunc (meta *Meta) GetAlias() string {\n\treturn meta.Alias\n}\n\nfunc (meta *Meta) GetMetas() []resource.Metaor {\n\tif len(meta.Metas) > 0 {\n\t\treturn meta.Metas\n\t} else if meta.Resource == nil {\n\t\treturn []resource.Metaor{}\n\t} else {\n\t\treturn meta.Resource.GetMetas()\n\t}\n}\n\nfunc (meta *Meta) GetResource() resource.Resourcer {\n\treturn meta.Resource\n}\n\nfunc (meta *Meta) GetValuer() func(interface{}, *qor.Context) interface{} {\n\treturn meta.Valuer\n}\n\nfunc (meta *Meta) GetSetter() func(resource interface{}, metaValues *resource.MetaValues, context *qor.Context) {\n\treturn meta.Setter\n}\n\nfunc (meta *Meta) HasPermission(mode roles.PermissionMode, context *qor.Context) bool {\n\tif meta.Permission == nil {\n\t\treturn true\n\t}\n\treturn meta.Permission.HasPermission(mode, context.Roles...)\n}\n\nfunc (meta *Meta) updateMeta() {\n\tif meta.Name == \"\" {\n\t\tqor.ExitWithMsg(\"Meta should have name: %v\", reflect.ValueOf(meta).Type())\n\t}\n\n\tif meta.Label == \"\" {\n\t\tmeta.Label = utils.HumanizeString(meta.Name)\n\t}\n\n\tif meta.Alias == \"\" {\n\t\tmeta.Alias = meta.Name\n\t}\n\tmeta.Alias = gorm.SnakeToUpperCamel(meta.Alias)\n\n\tvar (\n\t\tbase        = meta.base\n\t\tscope       = &gorm.Scope{Value: base.Value}\n\t\tfield       *gorm.Field\n\t\thasColumn   bool\n\t\tnestedField = strings.Contains(meta.Alias, \".\")\n\t\tvalueType   string\n\t)\n\tif nestedField {\n\t\tsubmodel, name := parseNestedField(reflect.ValueOf(base.Value), meta.Alias)\n\t\tsubscope := &gorm.Scope{Value: submodel.Interface()}\n\t\tfield, hasColumn = subscope.FieldByName(name)\n\t} else {\n\t\tfield, hasColumn = scope.FieldByName(meta.Alias)\n\t}\n\tif hasColumn {\n\t\tvalueType = field.Field.Type().Kind().String()\n\t}\n\n\t\/\/ Set Meta Type\n\tif meta.Type == \"\" {\n\t\tif relationship := field.Relationship; relationship != nil {\n\t\t\tif relationship.Kind == \"belongs_to\" || relationship.Kind == \"has_one\" {\n\t\t\t\tmeta.Type = \"single_edit\"\n\t\t\t} else if relationship.Kind == \"has_many\" {\n\t\t\t\tmeta.Type = \"collection_edit\"\n\t\t\t} else if relationship.Kind == \"many_to_many\" {\n\t\t\t\tmeta.Type = \"select_many\"\n\t\t\t}\n\t\t} else {\n\t\t\tswitch valueType {\n\t\t\tcase \"string\":\n\t\t\t\tmeta.Type = \"string\"\n\t\t\tcase \"bool\":\n\t\t\t\tmeta.Type = \"checkbox\"\n\t\t\tdefault:\n\t\t\t\tif regexp.MustCompile(`^(u)?(int|float)(\\d+)?`).MatchString(valueType) {\n\t\t\t\t\tmeta.Type = \"number\"\n\t\t\t\t} else if _, ok := field.Field.Interface().(time.Time); ok {\n\t\t\t\t\tmeta.Type = \"datetime\"\n\t\t\t\t} else if _, ok := field.Field.Interface().(media_library.MediaLibrary); ok {\n\t\t\t\t\tmeta.Type = \"file\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Set Meta Resource\n\tif meta.Resource == nil {\n\t\tif hasColumn && (field.Relationship != nil) {\n\t\t\tvar result interface{}\n\t\t\tif valueType == \"struct\" {\n\t\t\t\tresult = reflect.New(field.Field.Type()).Interface()\n\t\t\t} else if valueType == \"slice\" {\n\t\t\t\tresult = reflect.New(field.Field.Type().Elem()).Interface()\n\t\t\t}\n\t\t\tnewRes := &Resource{}\n\t\t\tnewRes.Value = result\n\t\t\tmeta.Resource = newRes\n\t\t}\n\t}\n\n\t\/\/ Set Meta Value\n\tif meta.Valuer == nil {\n\t\tif hasColumn {\n\t\t\tmeta.Valuer = func(value interface{}, context *qor.Context) interface{} {\n\t\t\t\tscope := &gorm.Scope{Value: value}\n\t\t\t\talias := meta.Alias\n\t\t\t\tif nestedField {\n\t\t\t\t\tfields := strings.Split(alias, \".\")\n\t\t\t\t\talias = fields[len(fields)-1]\n\t\t\t\t}\n\n\t\t\t\tif f, ok := scope.FieldByName(alias); ok {\n\t\t\t\t\tif field.Relationship != nil {\n\t\t\t\t\t\tif f.Field.CanAddr() {\n\t\t\t\t\t\t\tcontext.GetDB().Model(value).Related(f.Field.Addr().Interface(), meta.Alias)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif f.Field.CanAddr() {\n\t\t\t\t\t\treturn f.Field.Addr().Interface()\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn f.Field.Interface()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t} else {\n\t\t\tqor.ExitWithMsg(\"Unsupported meta name %v for resource %v\", meta.Name, reflect.TypeOf(base.Value))\n\t\t}\n\t}\n\n\t\/\/ Set Meta Collection\n\tif meta.Collection != nil {\n\t\tif maps, ok := meta.Collection.([]string); ok {\n\t\t\tmeta.GetCollection = func(interface{}, *qor.Context) (results [][]string) {\n\t\t\t\tfor _, value := range maps {\n\t\t\t\t\tresults = append(results, []string{value, value})\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if maps, ok := meta.Collection.([][]string); ok {\n\t\t\tmeta.GetCollection = func(interface{}, *qor.Context) [][]string {\n\t\t\t\treturn maps\n\t\t\t}\n\t\t} else if f, ok := meta.Collection.(func(interface{}, *qor.Context) [][]string); ok {\n\t\t\tmeta.GetCollection = f\n\t\t} else {\n\t\t\tqor.ExitWithMsg(\"Unsupported Collection format for meta %v of resource %v\", meta.Name, reflect.TypeOf(base.Value))\n\t\t}\n\t} else if meta.Type == \"select_one\" || meta.Type == \"select_many\" {\n\t\tqor.ExitWithMsg(\"%v meta type %v needs Collection\", meta.Name, meta.Type)\n\t}\n\n\tscopeField, _ := scope.FieldByName(meta.Alias)\n\n\tif meta.Setter == nil {\n\t\tmeta.Setter = func(resource interface{}, metaValues *resource.MetaValues, context *qor.Context) {\n\t\t\tmetaValue := metaValues.Get(meta.Name)\n\t\t\tif metaValue == nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvalue := metaValue.Value\n\t\t\tscope := &gorm.Scope{Value: resource}\n\t\t\talias := meta.Alias\n\t\t\tif nestedField {\n\t\t\t\tfields := strings.Split(alias, \".\")\n\t\t\t\talias = fields[len(fields)-1]\n\t\t\t}\n\t\t\tfield := reflect.Indirect(reflect.ValueOf(resource)).FieldByName(alias)\n\n\t\t\tif field.IsValid() && field.CanAddr() {\n\t\t\t\tvar relationship string\n\t\t\t\tif scopeField != nil && scopeField.Relationship != nil {\n\t\t\t\t\trelationship = scopeField.Relationship.Kind\n\t\t\t\t}\n\t\t\t\tif relationship == \"many_to_many\" {\n\t\t\t\t\tcontext.GetDB().Where(ToArray(value)).Find(field.Addr().Interface())\n\t\t\t\t\tif !scope.PrimaryKeyZero() {\n\t\t\t\t\t\tcontext.GetDB().Model(resource).Association(meta.Alias).Replace(field.Interface())\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tswitch field.Kind() {\n\t\t\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t\t\t\tfield.SetInt(ToInt(value))\n\t\t\t\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\t\t\tfield.SetUint(ToUint(value))\n\t\t\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\t\t\tfield.SetFloat(ToFloat(value))\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif scanner, ok := field.Addr().Interface().(sql.Scanner); ok {\n\t\t\t\t\t\t\tscanner.Scan(ToString(value))\n\t\t\t\t\t\t} else if reflect.TypeOf(\"\").ConvertibleTo(field.Type()) {\n\t\t\t\t\t\t\tfield.Set(reflect.ValueOf(ToString(value)).Convert(field.Type()))\n\t\t\t\t\t\t} else if reflect.TypeOf([]string{}).ConvertibleTo(field.Type()) {\n\t\t\t\t\t\t\tfield.Set(reflect.ValueOf(ToArray(value)).Convert(field.Type()))\n\t\t\t\t\t\t} else if rvalue := reflect.ValueOf(value); reflect.TypeOf(rvalue.Type()).ConvertibleTo(field.Type()) {\n\t\t\t\t\t\t\tfield.Set(rvalue.Convert(field.Type()))\n\t\t\t\t\t\t} else if _, ok := field.Addr().Interface().(*time.Time); ok {\n\t\t\t\t\t\t\tif str := ToString(value); str != \"\" {\n\t\t\t\t\t\t\t\tif newTime, err := now.Parse(str); err == nil {\n\t\t\t\t\t\t\t\t\tfield.Set(reflect.ValueOf(newTime))\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvar buf = bytes.NewBufferString(\"\")\n\t\t\t\t\t\t\tjson.NewEncoder(buf).Encode(value)\n\t\t\t\t\t\t\tif err := json.NewDecoder(strings.NewReader(buf.String())).Decode(field.Addr().Interface()); err != nil {\n\t\t\t\t\t\t\t\tqor.ExitWithMsg(\"Can't set value %v to %v [meta %v]\", reflect.ValueOf(value).Type(), field.Type(), meta)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif nestedField {\n\t\toldvalue := meta.Valuer\n\t\tmeta.Valuer = func(value interface{}, context *qor.Context) interface{} {\n\t\t\treturn oldvalue(getNestedModel(value, meta.Alias, context), context)\n\t\t}\n\t\toldSetter := meta.Setter\n\t\tmeta.Setter = func(resource interface{}, metaValues *resource.MetaValues, context *qor.Context) {\n\t\t\toldSetter(getNestedModel(resource, meta.Alias, context), metaValues, context)\n\t\t}\n\t}\n}\nfunc getNestedModel(value interface{}, alias string, context *qor.Context) interface{} {\n\tmodel := reflect.Indirect(reflect.ValueOf(value))\n\tfields := strings.Split(alias, \".\")\n\tfor _, field := range fields[:len(fields)-1] {\n\t\tif model.CanAddr() {\n\t\t\tsubmodel := model.FieldByName(field)\n\t\t\tif key := submodel.FieldByName(\"Id\"); !key.IsValid() || key.Uint() == 0 {\n\t\t\t\tif submodel.CanAddr() {\n\t\t\t\t\tcontext.GetDB().Model(model.Addr().Interface()).Related(submodel.Addr().Interface())\n\t\t\t\t\tmodel = submodel\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmodel = submodel\n\t\t\t}\n\t\t}\n\t}\n\n\tif model.CanAddr() {\n\t\treturn model.Addr().Interface()\n\t} else {\n\t\treturn nil\n\t}\n}\n\n\/\/ Profile.Name\nfunc parseNestedField(value reflect.Value, name string) (reflect.Value, string) {\n\tfields := strings.Split(name, \".\")\n\tvalue = reflect.Indirect(value)\n\tfor _, field := range fields[:len(fields)-1] {\n\t\tvalue = value.FieldByName(field)\n\t}\n\n\treturn value, fields[len(fields)-1]\n}\n\nfunc ToArray(value interface{}) (values []string) {\n\tswitch value := value.(type) {\n\tcase []string:\n\t\tvalues = value\n\tcase []interface{}:\n\t\tfor _, v := range value {\n\t\t\tvalues = append(values, fmt.Sprintf(\"%v\", v))\n\t\t}\n\tdefault:\n\t\tvalues = []string{fmt.Sprintf(\"%v\", value)}\n\t}\n\treturn\n}\n\nfunc ToString(value interface{}) string {\n\tif v, ok := value.([]string); ok && len(v) > 0 {\n\t\treturn v[0]\n\t} else if v, ok := value.(string); ok {\n\t\treturn v\n\t} else if v, ok := value.([]interface{}); ok && len(v) > 0 {\n\t\treturn fmt.Sprintf(\"%v\", v[0])\n\t} else {\n\t\tpanic(value)\n\t}\n}\n\nfunc ToInt(value interface{}) int64 {\n\tvar result string\n\tif v, ok := value.([]string); ok && len(v) > 0 {\n\t\tresult = v[0]\n\t} else if v, ok := value.(string); ok {\n\t\tresult = v\n\t} else {\n\t\treturn ToInt(fmt.Sprintf(\"%v\", value))\n\t}\n\n\tif i, err := strconv.ParseInt(result, 10, 64); err == nil {\n\t\treturn i\n\t} else if result == \"\" {\n\t\treturn 0\n\t} else {\n\t\tpanic(\"failed to parse int: \" + result)\n\t}\n}\n\nfunc ToUint(value interface{}) uint64 {\n\tvar result string\n\tif v, ok := value.([]string); ok && len(v) > 0 {\n\t\tresult = v[0]\n\t} else if v, ok := value.(string); ok {\n\t\tresult = v\n\t} else {\n\t\treturn ToUint(fmt.Sprintf(\"%v\", value))\n\t}\n\n\tif i, err := strconv.ParseUint(result, 10, 64); err == nil {\n\t\treturn i\n\t} else if result == \"\" {\n\t\treturn 0\n\t} else {\n\t\tpanic(\"failed to parse uint: \" + result)\n\t}\n}\n\nfunc ToFloat(value interface{}) float64 {\n\tvar result string\n\tif v, ok := value.([]string); ok && len(v) > 0 {\n\t\tresult = v[0]\n\t} else if v, ok := value.(string); ok {\n\t\tresult = v\n\t} else {\n\t\treturn ToFloat(fmt.Sprintf(\"%v\", value))\n\t}\n\n\tif i, err := strconv.ParseFloat(result, 64); err == nil {\n\t\treturn i\n\t} else if result == \"\" {\n\t\treturn 0\n\t} else {\n\t\tpanic(\"failed to parse float: \" + result)\n\t}\n}\n<commit_msg>Fix Scanner for Media Library<commit_after>package admin\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/jinzhu\/now\"\n\t\"github.com\/qor\/qor\"\n\t\"github.com\/qor\/qor\/media_library\"\n\t\"github.com\/qor\/qor\/resource\"\n\t\"github.com\/qor\/qor\/roles\"\n\t\"github.com\/qor\/qor\/utils\"\n)\n\ntype Meta struct {\n\tbase          *Resource\n\tName          string\n\tAlias         string\n\tLabel         string\n\tType          string\n\tValuer        func(interface{}, *qor.Context) interface{}\n\tSetter        func(resource interface{}, metaValues *resource.MetaValues, context *qor.Context)\n\tMetas         []resource.Metaor\n\tResource      resource.Resourcer\n\tCollection    interface{}\n\tGetCollection func(interface{}, *qor.Context) [][]string\n\tPermission    *roles.Permission\n}\n\nfunc (meta *Meta) GetName() string {\n\treturn meta.Name\n}\n\nfunc (meta *Meta) GetAlias() string {\n\treturn meta.Alias\n}\n\nfunc (meta *Meta) GetMetas() []resource.Metaor {\n\tif len(meta.Metas) > 0 {\n\t\treturn meta.Metas\n\t} else if meta.Resource == nil {\n\t\treturn []resource.Metaor{}\n\t} else {\n\t\treturn meta.Resource.GetMetas()\n\t}\n}\n\nfunc (meta *Meta) GetResource() resource.Resourcer {\n\treturn meta.Resource\n}\n\nfunc (meta *Meta) GetValuer() func(interface{}, *qor.Context) interface{} {\n\treturn meta.Valuer\n}\n\nfunc (meta *Meta) GetSetter() func(resource interface{}, metaValues *resource.MetaValues, context *qor.Context) {\n\treturn meta.Setter\n}\n\nfunc (meta *Meta) HasPermission(mode roles.PermissionMode, context *qor.Context) bool {\n\tif meta.Permission == nil {\n\t\treturn true\n\t}\n\treturn meta.Permission.HasPermission(mode, context.Roles...)\n}\n\nfunc (meta *Meta) updateMeta() {\n\tif meta.Name == \"\" {\n\t\tqor.ExitWithMsg(\"Meta should have name: %v\", reflect.ValueOf(meta).Type())\n\t}\n\n\tif meta.Label == \"\" {\n\t\tmeta.Label = utils.HumanizeString(meta.Name)\n\t}\n\n\tif meta.Alias == \"\" {\n\t\tmeta.Alias = meta.Name\n\t}\n\tmeta.Alias = gorm.SnakeToUpperCamel(meta.Alias)\n\n\tvar (\n\t\tbase        = meta.base\n\t\tscope       = &gorm.Scope{Value: base.Value}\n\t\tfield       *gorm.Field\n\t\thasColumn   bool\n\t\tnestedField = strings.Contains(meta.Alias, \".\")\n\t\tvalueType   string\n\t)\n\tif nestedField {\n\t\tsubmodel, name := parseNestedField(reflect.ValueOf(base.Value), meta.Alias)\n\t\tsubscope := &gorm.Scope{Value: submodel.Interface()}\n\t\tfield, hasColumn = subscope.FieldByName(name)\n\t} else {\n\t\tfield, hasColumn = scope.FieldByName(meta.Alias)\n\t}\n\tif hasColumn {\n\t\tvalueType = field.Field.Type().Kind().String()\n\t}\n\n\t\/\/ Set Meta Type\n\tif meta.Type == \"\" {\n\t\tif relationship := field.Relationship; relationship != nil {\n\t\t\tif relationship.Kind == \"belongs_to\" || relationship.Kind == \"has_one\" {\n\t\t\t\tmeta.Type = \"single_edit\"\n\t\t\t} else if relationship.Kind == \"has_many\" {\n\t\t\t\tmeta.Type = \"collection_edit\"\n\t\t\t} else if relationship.Kind == \"many_to_many\" {\n\t\t\t\tmeta.Type = \"select_many\"\n\t\t\t}\n\t\t} else {\n\t\t\tswitch valueType {\n\t\t\tcase \"string\":\n\t\t\t\tmeta.Type = \"string\"\n\t\t\tcase \"bool\":\n\t\t\t\tmeta.Type = \"checkbox\"\n\t\t\tdefault:\n\t\t\t\tif regexp.MustCompile(`^(u)?(int|float)(\\d+)?`).MatchString(valueType) {\n\t\t\t\t\tmeta.Type = \"number\"\n\t\t\t\t} else if _, ok := field.Field.Interface().(time.Time); ok {\n\t\t\t\t\tmeta.Type = \"datetime\"\n\t\t\t\t} else if _, ok := field.Field.Interface().(media_library.MediaLibrary); ok {\n\t\t\t\t\tmeta.Type = \"file\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Set Meta Resource\n\tif meta.Resource == nil {\n\t\tif hasColumn && (field.Relationship != nil) {\n\t\t\tvar result interface{}\n\t\t\tif valueType == \"struct\" {\n\t\t\t\tresult = reflect.New(field.Field.Type()).Interface()\n\t\t\t} else if valueType == \"slice\" {\n\t\t\t\tresult = reflect.New(field.Field.Type().Elem()).Interface()\n\t\t\t}\n\t\t\tnewRes := &Resource{}\n\t\t\tnewRes.Value = result\n\t\t\tmeta.Resource = newRes\n\t\t}\n\t}\n\n\t\/\/ Set Meta Value\n\tif meta.Valuer == nil {\n\t\tif hasColumn {\n\t\t\tmeta.Valuer = func(value interface{}, context *qor.Context) interface{} {\n\t\t\t\tscope := &gorm.Scope{Value: value}\n\t\t\t\talias := meta.Alias\n\t\t\t\tif nestedField {\n\t\t\t\t\tfields := strings.Split(alias, \".\")\n\t\t\t\t\talias = fields[len(fields)-1]\n\t\t\t\t}\n\n\t\t\t\tif f, ok := scope.FieldByName(alias); ok {\n\t\t\t\t\tif field.Relationship != nil {\n\t\t\t\t\t\tif f.Field.CanAddr() {\n\t\t\t\t\t\t\tcontext.GetDB().Model(value).Related(f.Field.Addr().Interface(), meta.Alias)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif f.Field.CanAddr() {\n\t\t\t\t\t\treturn f.Field.Addr().Interface()\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn f.Field.Interface()\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t} else {\n\t\t\tqor.ExitWithMsg(\"Unsupported meta name %v for resource %v\", meta.Name, reflect.TypeOf(base.Value))\n\t\t}\n\t}\n\n\t\/\/ Set Meta Collection\n\tif meta.Collection != nil {\n\t\tif maps, ok := meta.Collection.([]string); ok {\n\t\t\tmeta.GetCollection = func(interface{}, *qor.Context) (results [][]string) {\n\t\t\t\tfor _, value := range maps {\n\t\t\t\t\tresults = append(results, []string{value, value})\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if maps, ok := meta.Collection.([][]string); ok {\n\t\t\tmeta.GetCollection = func(interface{}, *qor.Context) [][]string {\n\t\t\t\treturn maps\n\t\t\t}\n\t\t} else if f, ok := meta.Collection.(func(interface{}, *qor.Context) [][]string); ok {\n\t\t\tmeta.GetCollection = f\n\t\t} else {\n\t\t\tqor.ExitWithMsg(\"Unsupported Collection format for meta %v of resource %v\", meta.Name, reflect.TypeOf(base.Value))\n\t\t}\n\t} else if meta.Type == \"select_one\" || meta.Type == \"select_many\" {\n\t\tqor.ExitWithMsg(\"%v meta type %v needs Collection\", meta.Name, meta.Type)\n\t}\n\n\tscopeField, _ := scope.FieldByName(meta.Alias)\n\n\tif meta.Setter == nil {\n\t\tmeta.Setter = func(resource interface{}, metaValues *resource.MetaValues, context *qor.Context) {\n\t\t\tmetaValue := metaValues.Get(meta.Name)\n\t\t\tif metaValue == nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvalue := metaValue.Value\n\t\t\tscope := &gorm.Scope{Value: resource}\n\t\t\talias := meta.Alias\n\t\t\tif nestedField {\n\t\t\t\tfields := strings.Split(alias, \".\")\n\t\t\t\talias = fields[len(fields)-1]\n\t\t\t}\n\t\t\tfield := reflect.Indirect(reflect.ValueOf(resource)).FieldByName(alias)\n\n\t\t\tif field.IsValid() && field.CanAddr() {\n\t\t\t\tvar relationship string\n\t\t\t\tif scopeField != nil && scopeField.Relationship != nil {\n\t\t\t\t\trelationship = scopeField.Relationship.Kind\n\t\t\t\t}\n\t\t\t\tif relationship == \"many_to_many\" {\n\t\t\t\t\tcontext.GetDB().Where(ToArray(value)).Find(field.Addr().Interface())\n\t\t\t\t\tif !scope.PrimaryKeyZero() {\n\t\t\t\t\t\tcontext.GetDB().Model(resource).Association(meta.Alias).Replace(field.Interface())\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tswitch field.Kind() {\n\t\t\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:\n\t\t\t\t\t\tfield.SetInt(ToInt(value))\n\t\t\t\t\tcase reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\t\t\tfield.SetUint(ToUint(value))\n\t\t\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\t\t\tfield.SetFloat(ToFloat(value))\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif scanner, ok := field.Addr().Interface().(sql.Scanner); ok {\n\t\t\t\t\t\t\tif scanner.Scan(value) != nil {\n\t\t\t\t\t\t\t\tscanner.Scan(ToString(value))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if reflect.TypeOf(\"\").ConvertibleTo(field.Type()) {\n\t\t\t\t\t\t\tfield.Set(reflect.ValueOf(ToString(value)).Convert(field.Type()))\n\t\t\t\t\t\t} else if reflect.TypeOf([]string{}).ConvertibleTo(field.Type()) {\n\t\t\t\t\t\t\tfield.Set(reflect.ValueOf(ToArray(value)).Convert(field.Type()))\n\t\t\t\t\t\t} else if rvalue := reflect.ValueOf(value); reflect.TypeOf(rvalue.Type()).ConvertibleTo(field.Type()) {\n\t\t\t\t\t\t\tfield.Set(rvalue.Convert(field.Type()))\n\t\t\t\t\t\t} else if _, ok := field.Addr().Interface().(*time.Time); ok {\n\t\t\t\t\t\t\tif str := ToString(value); str != \"\" {\n\t\t\t\t\t\t\t\tif newTime, err := now.Parse(str); err == nil {\n\t\t\t\t\t\t\t\t\tfield.Set(reflect.ValueOf(newTime))\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvar buf = bytes.NewBufferString(\"\")\n\t\t\t\t\t\t\tjson.NewEncoder(buf).Encode(value)\n\t\t\t\t\t\t\tif err := json.NewDecoder(strings.NewReader(buf.String())).Decode(field.Addr().Interface()); err != nil {\n\t\t\t\t\t\t\t\tqor.ExitWithMsg(\"Can't set value %v to %v [meta %v]\", reflect.ValueOf(value).Type(), field.Type(), meta)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif nestedField {\n\t\toldvalue := meta.Valuer\n\t\tmeta.Valuer = func(value interface{}, context *qor.Context) interface{} {\n\t\t\treturn oldvalue(getNestedModel(value, meta.Alias, context), context)\n\t\t}\n\t\toldSetter := meta.Setter\n\t\tmeta.Setter = func(resource interface{}, metaValues *resource.MetaValues, context *qor.Context) {\n\t\t\toldSetter(getNestedModel(resource, meta.Alias, context), metaValues, context)\n\t\t}\n\t}\n}\nfunc getNestedModel(value interface{}, alias string, context *qor.Context) interface{} {\n\tmodel := reflect.Indirect(reflect.ValueOf(value))\n\tfields := strings.Split(alias, \".\")\n\tfor _, field := range fields[:len(fields)-1] {\n\t\tif model.CanAddr() {\n\t\t\tsubmodel := model.FieldByName(field)\n\t\t\tif key := submodel.FieldByName(\"Id\"); !key.IsValid() || key.Uint() == 0 {\n\t\t\t\tif submodel.CanAddr() {\n\t\t\t\t\tcontext.GetDB().Model(model.Addr().Interface()).Related(submodel.Addr().Interface())\n\t\t\t\t\tmodel = submodel\n\t\t\t\t} else {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmodel = submodel\n\t\t\t}\n\t\t}\n\t}\n\n\tif model.CanAddr() {\n\t\treturn model.Addr().Interface()\n\t} else {\n\t\treturn nil\n\t}\n}\n\n\/\/ Profile.Name\nfunc parseNestedField(value reflect.Value, name string) (reflect.Value, string) {\n\tfields := strings.Split(name, \".\")\n\tvalue = reflect.Indirect(value)\n\tfor _, field := range fields[:len(fields)-1] {\n\t\tvalue = value.FieldByName(field)\n\t}\n\n\treturn value, fields[len(fields)-1]\n}\n\nfunc ToArray(value interface{}) (values []string) {\n\tswitch value := value.(type) {\n\tcase []string:\n\t\tvalues = value\n\tcase []interface{}:\n\t\tfor _, v := range value {\n\t\t\tvalues = append(values, fmt.Sprintf(\"%v\", v))\n\t\t}\n\tdefault:\n\t\tvalues = []string{fmt.Sprintf(\"%v\", value)}\n\t}\n\treturn\n}\n\nfunc ToString(value interface{}) string {\n\tif v, ok := value.([]string); ok && len(v) > 0 {\n\t\treturn v[0]\n\t} else if v, ok := value.(string); ok {\n\t\treturn v\n\t} else if v, ok := value.([]interface{}); ok && len(v) > 0 {\n\t\treturn fmt.Sprintf(\"%v\", v[0])\n\t} else {\n\t\tpanic(value)\n\t}\n}\n\nfunc ToInt(value interface{}) int64 {\n\tvar result string\n\tif v, ok := value.([]string); ok && len(v) > 0 {\n\t\tresult = v[0]\n\t} else if v, ok := value.(string); ok {\n\t\tresult = v\n\t} else {\n\t\treturn ToInt(fmt.Sprintf(\"%v\", value))\n\t}\n\n\tif i, err := strconv.ParseInt(result, 10, 64); err == nil {\n\t\treturn i\n\t} else if result == \"\" {\n\t\treturn 0\n\t} else {\n\t\tpanic(\"failed to parse int: \" + result)\n\t}\n}\n\nfunc ToUint(value interface{}) uint64 {\n\tvar result string\n\tif v, ok := value.([]string); ok && len(v) > 0 {\n\t\tresult = v[0]\n\t} else if v, ok := value.(string); ok {\n\t\tresult = v\n\t} else {\n\t\treturn ToUint(fmt.Sprintf(\"%v\", value))\n\t}\n\n\tif i, err := strconv.ParseUint(result, 10, 64); err == nil {\n\t\treturn i\n\t} else if result == \"\" {\n\t\treturn 0\n\t} else {\n\t\tpanic(\"failed to parse uint: \" + result)\n\t}\n}\n\nfunc ToFloat(value interface{}) float64 {\n\tvar result string\n\tif v, ok := value.([]string); ok && len(v) > 0 {\n\t\tresult = v[0]\n\t} else if v, ok := value.(string); ok {\n\t\tresult = v\n\t} else {\n\t\treturn ToFloat(fmt.Sprintf(\"%v\", value))\n\t}\n\n\tif i, err := strconv.ParseFloat(result, 64); err == nil {\n\t\treturn i\n\t} else if result == \"\" {\n\t\treturn 0\n\t} else {\n\t\tpanic(\"failed to parse float: \" + result)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n\t\"mime\/multipart\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"io\"\n)\n\nvar conf = Configuration{\n\tServer: struct {\n\t\tPort int\n\t}{\n\t\t1234,\n\t},\n\tStorage: struct {\n\t\tDirectory string\n\t}{\n\t\t\"testdata\",\n\t},\n}\n\nfunc TestGet(t *testing.T) {\n\t\/\/ Setup\n\tbody, _ := os.Open(path.Join(conf.Storage.Directory, \"e3158990bdee63f8594c260cd51a011d\"))\n\tdata, _ := ioutil.ReadAll(body)\n\n\te := echo.New()\n\treq := httptest.NewRequest(echo.GET, \"\/\", nil)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\tc.SetParamNames(\"id\")\n\tc.SetParamValues(\"e3158990bdee63f8594c260cd51a011d\")\n\tcc := &CustomContext{c, conf}\n\n\t\/\/ Assertions\n\tif assert.NoError(t, get(cc)) {\n\t\tassert.Equal(t, http.StatusOK, rec.Code)\n\t\tassert.Equal(t, data, rec.Body.Bytes())\n\t}\n}\n\nfunc TestPost(t *testing.T) {\n\tfile, _ := os.Open(path.Join(conf.Storage.Directory, \"e3158990bdee63f8594c260cd51a011d\"))\n\tdata, _ := ioutil.ReadAll(file)\n\tfile.Close()\n\n\tbody := new(bytes.Buffer)\n\twriter := multipart.NewWriter(body)\n\tpart, _ := writer.CreateFormFile(\"photo\", file.Name())\n\tpart.Write(data)\n\twriter.Close()\n\n\te := echo.New()\n\treq := httptest.NewRequest(echo.POST, \"\/\", body)\n\treq.Header.Add(\"Content-Type\", writer.FormDataContentType())\n\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\tcc := &CustomContext{c, conf}\n\n\terr := post(cc)\n\n\tvar res map[string]string\n\tjson.Unmarshal(rec.Body.Bytes(), &res)\n\n\tactualFile, _ := os.Open(path.Join(conf.Storage.Directory, res[\"Id\"]))\n\tactual, _ := ioutil.ReadAll(actualFile)\n\n\t\/\/ Assertions\n\tif assert.NoError(t, err) {\n\t\tassert.Equal(t, http.StatusCreated, rec.Code)\n\t\tassert.Equal(t, actual, data)\n\t}\n}\n\nfunc TestPut(t *testing.T) {\n\tfile, _ := os.Open(path.Join(conf.Storage.Directory, \"e3158990bdee63f8594c260cd51a011d\"))\n\tdata, _ := ioutil.ReadAll(file)\n\tfile.Close()\n\n\tbody := new(bytes.Buffer)\n\twriter := multipart.NewWriter(body)\n\tpart, _ := writer.CreateFormFile(\"photo\", file.Name())\n\tpart.Write(data)\n\twriter.Close()\n\n\te := echo.New()\n\treq := httptest.NewRequest(echo.PUT, \"\/\", body)\n\treq.Header.Add(\"Content-Type\", writer.FormDataContentType())\n\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\tc.SetPath(\"\/:id\")\n\tc.SetParamNames(\"id\")\n\tc.SetParamValues(\"test\")\n\tcc := &CustomContext{c, conf}\n\n\terr := put(cc)\n\n\tactualFile, _ := os.Open(path.Join(conf.Storage.Directory, \"test\"))\n\tactual, _ := ioutil.ReadAll(actualFile)\n\n\t\/\/ Assertions\n\tif assert.NoError(t, err) {\n\t\tassert.Equal(t, http.StatusOK, rec.Code)\n\t\tassert.Equal(t, actual, data)\n\t}\n}\n\nfunc TestDelete(t *testing.T) {\n\tsrc, _ := os.Open(path.Join(conf.Storage.Directory, \"e3158990bdee63f8594c260cd51a011d\"))\n\tsrc.Close()\n\n\tdst, _ := os.Create(path.Join(conf.Storage.Directory, \"test\"))\n\tdst.Close()\n\n\tio.Copy(dst, src)\n\n\te := echo.New()\n\treq := httptest.NewRequest(echo.DELETE, \"\/\", nil)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\tc.SetPath(\"\/:id\")\n\tc.SetParamNames(\"id\")\n\tc.SetParamValues(\"test\")\n\tcc := &CustomContext{c, conf}\n\n\terr := delete(cc)\n\t_, exist := os.Stat(path.Join(conf.Storage.Directory, \"test\"))\n\n\t\/\/ Assertions\n\tif assert.NoError(t, err) {\n\t\tassert.Equal(t, http.StatusOK, rec.Code)\n\t\tassert.Error(t, exist)\n\t}\n}\n<commit_msg>Add test cases for get<commit_after>package main\n\nimport (\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"path\"\n\t\"testing\"\n\t\"mime\/multipart\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"io\"\n)\n\nvar conf = Configuration{\n\tServer: struct {\n\t\tPort int\n\t}{\n\t\t1234,\n\t},\n\tStorage: struct {\n\t\tDirectory string\n\t}{\n\t\t\"testdata\",\n\t},\n}\n\nfunc TestGet(t *testing.T) {\n\t\/\/ Setup\n\tbody, _ := os.Open(path.Join(conf.Storage.Directory, \"e3158990bdee63f8594c260cd51a011d\"))\n\tdata, _ := ioutil.ReadAll(body)\n\n\te := echo.New()\n\treq := httptest.NewRequest(echo.GET, \"\/\", nil)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\tc.SetParamNames(\"id\")\n\tc.SetParamValues(\"e3158990bdee63f8594c260cd51a011d\")\n\tcc := &CustomContext{c, conf}\n\n\t\/\/ Assertions\n\tif assert.NoError(t, get(cc)) {\n\t\tassert.Equal(t, http.StatusOK, rec.Code)\n\t\tassert.Equal(t, data, rec.Body.Bytes())\n\t}\n}\n\nfunc TestGetNotFound(t *testing.T) {\n\t\/\/ Setup\n\te := echo.New()\n\treq := httptest.NewRequest(echo.GET, \"\/\", nil)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\tc.SetPath(\"\/:id\")\n\tc.SetParamNames(\"id\")\n\tc.SetParamValues(\"not_found\")\n\tcc := &CustomContext{c, conf}\n\n\t\/\/ Assertions\n\tassert.Error(t, get(cc))\n}\n\nfunc TestGetDirectory(t *testing.T) {\n\t\/\/ Setup\n\te := echo.New()\n\treq := httptest.NewRequest(echo.GET, \"\/\", nil)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\tc.SetPath(\"\/:id\")\n\tc.SetParamNames(\"id\")\n\tc.SetParamValues(\"dir\")\n\tcc := &CustomContext{c, conf}\n\n\t\/\/ Assertions\n\tassert.Error(t, get(cc))\n}\n\nfunc TestPost(t *testing.T) {\n\tfile, _ := os.Open(path.Join(conf.Storage.Directory, \"e3158990bdee63f8594c260cd51a011d\"))\n\tdata, _ := ioutil.ReadAll(file)\n\tfile.Close()\n\n\tbody := new(bytes.Buffer)\n\twriter := multipart.NewWriter(body)\n\tpart, _ := writer.CreateFormFile(\"photo\", file.Name())\n\tpart.Write(data)\n\twriter.Close()\n\n\te := echo.New()\n\treq := httptest.NewRequest(echo.POST, \"\/\", body)\n\treq.Header.Add(\"Content-Type\", writer.FormDataContentType())\n\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\tcc := &CustomContext{c, conf}\n\n\terr := post(cc)\n\n\tvar res map[string]string\n\tjson.Unmarshal(rec.Body.Bytes(), &res)\n\n\tactualFile, _ := os.Open(path.Join(conf.Storage.Directory, res[\"Id\"]))\n\tactual, _ := ioutil.ReadAll(actualFile)\n\n\t\/\/ Assertions\n\tif assert.NoError(t, err) {\n\t\tassert.Equal(t, http.StatusCreated, rec.Code)\n\t\tassert.Equal(t, actual, data)\n\t}\n}\n\nfunc TestPut(t *testing.T) {\n\tfile, _ := os.Open(path.Join(conf.Storage.Directory, \"e3158990bdee63f8594c260cd51a011d\"))\n\tdata, _ := ioutil.ReadAll(file)\n\tfile.Close()\n\n\tbody := new(bytes.Buffer)\n\twriter := multipart.NewWriter(body)\n\tpart, _ := writer.CreateFormFile(\"photo\", file.Name())\n\tpart.Write(data)\n\twriter.Close()\n\n\te := echo.New()\n\treq := httptest.NewRequest(echo.PUT, \"\/\", body)\n\treq.Header.Add(\"Content-Type\", writer.FormDataContentType())\n\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\tc.SetPath(\"\/:id\")\n\tc.SetParamNames(\"id\")\n\tc.SetParamValues(\"test\")\n\tcc := &CustomContext{c, conf}\n\n\terr := put(cc)\n\n\tactualFile, _ := os.Open(path.Join(conf.Storage.Directory, \"test\"))\n\tactual, _ := ioutil.ReadAll(actualFile)\n\n\t\/\/ Assertions\n\tif assert.NoError(t, err) {\n\t\tassert.Equal(t, http.StatusOK, rec.Code)\n\t\tassert.Equal(t, actual, data)\n\t}\n}\n\nfunc TestDelete(t *testing.T) {\n\tsrc, _ := os.Open(path.Join(conf.Storage.Directory, \"e3158990bdee63f8594c260cd51a011d\"))\n\tsrc.Close()\n\n\tdst, _ := os.Create(path.Join(conf.Storage.Directory, \"test\"))\n\tdst.Close()\n\n\tio.Copy(dst, src)\n\n\te := echo.New()\n\treq := httptest.NewRequest(echo.DELETE, \"\/\", nil)\n\trec := httptest.NewRecorder()\n\tc := e.NewContext(req, rec)\n\tc.SetPath(\"\/:id\")\n\tc.SetParamNames(\"id\")\n\tc.SetParamValues(\"test\")\n\tcc := &CustomContext{c, conf}\n\n\terr := delete(cc)\n\t_, exist := os.Stat(path.Join(conf.Storage.Directory, \"test\"))\n\n\t\/\/ Assertions\n\tif assert.NoError(t, err) {\n\t\tassert.Equal(t, http.StatusOK, rec.Code)\n\t\tassert.Error(t, exist)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package rep\n\nimport (\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry-incubator\/rep\"\n\t\"github.com\/onsi\/say\"\n)\n\nfunc RepState(out io.Writer) (err error) {\n\tclient := rep.NewClient(&http.Client{\n\t\tTimeout: 5 * time.Second,\n\t}, \"http:\/\/localhost:1800\")\n\n\tt := time.Now()\n\tstate, err := client.State()\n\tdt := time.Since(t)\n\n\tif err != nil {\n\t\tsay.Println(0, \"Cell State [%s] - Error:%s\", dt, say.Red(err.Error()))\n\t\treturn err\n\t}\n\n\tname := say.Green(\"Cell State\")\n\tif state.Evacuating {\n\t\tname = say.Red(\"Cell State - EVAC -\")\n\t}\n\n\trootFSes := []string{}\n\tfor key := range state.RootFSProviders {\n\t\tif key != \"preloaded\" {\n\t\t\trootFSes = append(rootFSes, say.Yellow(key))\n\t\t}\n\t}\n\n\tfor key := range state.RootFSProviders[\"preloaded\"].(rep.FixedSetRootFSProvider).FixedSet {\n\t\trootFSes = append(rootFSes, say.Green(\"preloaded:%s\", key))\n\t}\n\n\tsay.Println(0, \"%s [%s] - Zone:%s | %s Tasks, %s LRPs | C:%d\/%d M:%d\/%d D:%d\/%d | %s\",\n\t\tname,\n\t\tdt,\n\t\tsay.Cyan(state.Zone),\n\t\tsay.Cyan(\"%d\", len(state.Tasks)),\n\t\tsay.Cyan(\"%d\", len(state.LRPs)),\n\t\tstate.AvailableResources.Containers,\n\t\tstate.TotalResources.Containers,\n\t\tstate.AvailableResources.MemoryMB,\n\t\tstate.TotalResources.MemoryMB,\n\t\tstate.AvailableResources.DiskMB,\n\t\tstate.TotalResources.DiskMB,\n\t\tstrings.Join(rootFSes, \", \"),\n\t)\n\n\treturn nil\n}\n<commit_msg>Update veritas to pass second http client when creating rep client<commit_after>package rep\n\nimport (\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry-incubator\/rep\"\n\t\"github.com\/onsi\/say\"\n)\n\nfunc RepState(out io.Writer) (err error) {\n\thttpClient := &http.Client{\n\t\tTimeout: 5 * time.Second,\n\t}\n\tclient := rep.NewClient(httpClient, httpClient, \"http:\/\/localhost:1800\")\n\n\tt := time.Now()\n\tstate, err := client.State()\n\tdt := time.Since(t)\n\n\tif err != nil {\n\t\tsay.Println(0, \"Cell State [%s] - Error:%s\", dt, say.Red(err.Error()))\n\t\treturn err\n\t}\n\n\tname := say.Green(\"Cell State\")\n\tif state.Evacuating {\n\t\tname = say.Red(\"Cell State - EVAC -\")\n\t}\n\n\trootFSes := []string{}\n\tfor key := range state.RootFSProviders {\n\t\tif key != \"preloaded\" {\n\t\t\trootFSes = append(rootFSes, say.Yellow(key))\n\t\t}\n\t}\n\n\tfor key := range state.RootFSProviders[\"preloaded\"].(rep.FixedSetRootFSProvider).FixedSet {\n\t\trootFSes = append(rootFSes, say.Green(\"preloaded:%s\", key))\n\t}\n\n\tsay.Println(0, \"%s [%s] - Zone:%s | %s Tasks, %s LRPs | C:%d\/%d M:%d\/%d D:%d\/%d | %s\",\n\t\tname,\n\t\tdt,\n\t\tsay.Cyan(state.Zone),\n\t\tsay.Cyan(\"%d\", len(state.Tasks)),\n\t\tsay.Cyan(\"%d\", len(state.LRPs)),\n\t\tstate.AvailableResources.Containers,\n\t\tstate.TotalResources.Containers,\n\t\tstate.AvailableResources.MemoryMB,\n\t\tstate.TotalResources.MemoryMB,\n\t\tstate.AvailableResources.DiskMB,\n\t\tstate.TotalResources.DiskMB,\n\t\tstrings.Join(rootFSes, \", \"),\n\t)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package logpeck\n\nimport (\n\t\"github.com\/Sirupsen\/logrus\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype AggregatorConfig struct {\n\tTags         []string `json:\"Tags\"`\n\tAggregations []string `json:\"Aggregations\"`\n\tTarget       string   `json:\"Target\"`\n\tPreFields    string   `json:\"PreFields\"`\n\tTimestamp    string   `json:\"Timestamp\"`\n}\n\ntype Aggregator struct {\n\tInterval          int64\n\tFieldsKey         string\n\tAggregatorConfigs map[string]AggregatorConfig\n\tbuckets           map[string]map[string][]int64\n\tpostTime          int64\n}\n\nfunc NewAggregator(interval int64, fieldsKey string, aggregators *map[string]AggregatorConfig) *Aggregator {\n\taggregator := &Aggregator{\n\t\tInterval:          interval,\n\t\tFieldsKey:         fieldsKey,\n\t\tAggregatorConfigs: *aggregators,\n\t\tbuckets:           make(map[string]map[string][]int64),\n\t\tpostTime:          0,\n\t}\n\treturn aggregator\n}\n\nfunc getSampleTime(ts int64, interval int64) int64 {\n\treturn ts \/ interval\n}\n\nfunc (p *Aggregator) IsDeadline(timestamp int64) bool {\n\tinterval := p.Interval\n\tnowTime := getSampleTime(timestamp, interval)\n\tif p.postTime != nowTime {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (p *Aggregator) Record(fields map[string]interface{}) int64 {\n\tbucketName := fields[p.FieldsKey].(string)\n\tbucketTag := \"\"\n\taggregatorConfig := p.AggregatorConfigs[bucketName]\n\ttags := aggregatorConfig.Tags\n\taggregations := aggregatorConfig.Aggregations\n\ttarget := aggregatorConfig.Target\n\ttimestamp := aggregatorConfig.Timestamp\n\tpreFields := aggregatorConfig.PreFields\n\tif target == \"\" {\n\t\treturn time.Now().Unix()\n\t}\n\tfor i := 0; i < len(tags); i++ {\n\t\tbucketTag += \",\" + tags[i] + \"=\" + fields[tags[i]].(string)\n\t}\n\tif preFields == \"\" {\n\t\tbucketTag += \" \"\n\t} else {\n\t\tbucketTag += \" \" + fields[preFields].(string) + \"_\"\n\t}\n\tint_bool := false\n\tfor i := 0; i < len(aggregations); i++ {\n\t\tif aggregations[i] != \"cnt\" {\n\t\t\tint_bool = true\n\t\t}\n\t}\n\n\taggValue := fields[target].(string)\n\n\t\/\/get time\n\tnow, err := strconv.ParseInt(fields[timestamp].(string), 10, 64)\n\tif err != nil {\n\t\tlogrus.Infof(\"[Record] timestamp:%v can't use strconv.ParseInt\", fields[timestamp].(string))\n\t\tnow = time.Now().Unix()\n\t}\n\n\tif _, ok := p.buckets[bucketName]; !ok {\n\t\tp.buckets[bucketName] = make(map[string][]int64)\n\t}\n\tif int_bool == false {\n\t\tp.buckets[bucketName][bucketTag] = append(p.buckets[bucketName][bucketTag], 1)\n\t} else {\n\t\taggValue, err := strconv.ParseInt(aggValue, 10, 64)\n\t\tif err != nil {\n\t\t\tlogrus.Infof(\"[Record] target:%v can't use strconv.ParseInt\", aggValue)\n\t\t\treturn now\n\t\t}\n\t\tp.buckets[bucketName][bucketTag] = append(p.buckets[bucketName][bucketTag], aggValue)\n\t}\n\n\treturn now\n}\n\nfunc quickSort(values []int64, left, right int64) {\n\ttemp := values[left]\n\tp := left\n\ti, j := left, right\n\tfor i <= j {\n\t\tfor j >= p && values[j] >= temp {\n\t\t\tj--\n\t\t}\n\t\tif j >= p {\n\t\t\tvalues[p] = values[j]\n\t\t\tp = j\n\t\t}\n\t\tfor i <= p && values[i] <= temp {\n\t\t\ti++\n\t\t}\n\t\tif i <= p {\n\t\t\tvalues[p] = values[i]\n\t\t\tp = i\n\t\t}\n\t}\n\tvalues[p] = temp\n\n\tif p-left > 1 {\n\t\tquickSort(values, left, p-1)\n\t}\n\tif right-p > 1 {\n\t\tquickSort(values, p+1, right)\n\t}\n}\n\nfunc getAggregation(targetValue []int64, aggregations []string) map[string]int64 {\n\taggregationResults := map[string]int64{}\n\tcnt := int64(len(targetValue))\n\tavg := int64(0)\n\tsum := int64(0)\n\tmin := int64(0)\n\tmax := int64(0)\n\tif cnt > 0 {\n\t\tmin = targetValue[0]\n\t\tmax = targetValue[0]\n\t}\n\tquickSort(targetValue, int64(0), int64(len(targetValue)-1))\n\tfor _, value := range targetValue {\n\t\tsum += value\n\t\tif value > max {\n\t\t\tmax = value\n\t\t}\n\t\tif value < min {\n\t\t\tmin = value\n\t\t}\n\t}\n\tavg = sum \/ cnt\n\tfor i := 0; i < len(aggregations); i++ {\n\t\tswitch aggregations[i] {\n\t\tcase \"cnt\":\n\t\t\taggregationResults[\"cnt\"] = int64(len(targetValue))\n\t\tcase \"sum\":\n\t\t\taggregationResults[\"sum\"] = sum\n\t\tcase \"avg\":\n\t\t\taggregationResults[\"avg\"] = avg\n\t\tcase \"min\":\n\t\t\taggregationResults[\"min\"] = min\n\t\tcase \"max\":\n\t\t\taggregationResults[\"max\"] = max\n\t\tdefault:\n\t\t\tif aggregations[i][0] == 'p' {\n\t\t\t\tproportion, err := strconv.ParseInt(aggregations[i][1:], 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(aggregations[i])\n\t\t\t\t}\n\t\t\t\tpercentile := targetValue[cnt*proportion\/100-1]\n\t\t\t\taggregationResults[aggregations[i]] = percentile\n\t\t\t}\n\t\t}\n\t}\n\treturn aggregationResults\n}\n\nfunc (p *Aggregator) Dump(timestamp int64) map[string]interface{} {\n\tfields := map[string]interface{}{}\n\t\/\/now := strconv.FormatInt(timestamp, 10)\n\tfor bucketName, bucketTag_value := range p.buckets {\n\t\tfor bucketTag, targetValue := range bucketTag_value {\n\t\t\taggregations := p.AggregatorConfigs[bucketName].Aggregations\n\t\t\tfields[bucketName+bucketTag] = getAggregation(targetValue, aggregations)\n\t\t}\n\t}\n\tfields[\"timestamp\"] = timestamp\n\tp.postTime = getSampleTime(timestamp, p.Interval)\n\tp.buckets = map[string]map[string][]int64{}\n\tlog.Infof(\"[Dump] fields is : %v\", fields)\n\treturn fields\n}\n<commit_msg>Modify the error of type conversion<commit_after>package logpeck\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype AggregatorConfig struct {\n\tTags         []string `json:\"Tags\"`\n\tAggregations []string `json:\"Aggregations\"`\n\tTarget       string   `json:\"Target\"`\n\tPreFields    string   `json:\"PreFields\"`\n\tTimestamp    string   `json:\"Timestamp\"`\n}\n\ntype Aggregator struct {\n\tInterval          int64\n\tFieldsKey         string\n\tAggregatorConfigs map[string]AggregatorConfig\n\tbuckets           map[string]map[string][]int64\n\tpostTime          int64\n}\n\nfunc NewAggregator(interval int64, fieldsKey string, aggregators *map[string]AggregatorConfig) *Aggregator {\n\taggregator := &Aggregator{\n\t\tInterval:          interval,\n\t\tFieldsKey:         fieldsKey,\n\t\tAggregatorConfigs: *aggregators,\n\t\tbuckets:           make(map[string]map[string][]int64),\n\t\tpostTime:          0,\n\t}\n\treturn aggregator\n}\n\nfunc getSampleTime(ts int64, interval int64) int64 {\n\treturn ts \/ interval\n}\n\nfunc (p *Aggregator) IsDeadline(timestamp int64) bool {\n\tinterval := p.Interval\n\tnowTime := getSampleTime(timestamp, interval)\n\tif p.postTime != nowTime {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (p *Aggregator) Record(fields map[string]interface{}) int64 {\n\tbucketName := fields[p.FieldsKey].(string)\n\tbucketTag := \"\"\n\taggregatorConfig := p.AggregatorConfigs[bucketName]\n\ttags := aggregatorConfig.Tags\n\ttarget := aggregatorConfig.Target\n\ttimestamp := aggregatorConfig.Timestamp\n\tpreFields := aggregatorConfig.PreFields\n\tif target == \"\" {\n\t\treturn time.Now().Unix()\n\t}\n\tfor i := 0; i < len(tags); i++ {\n\t\tbucketTag += \",\" + tags[i] + \"=\" + fields[tags[i]].(string)\n\t}\n\tif preFields == \"\" {\n\t\tbucketTag += \" \"\n\t} else {\n\t\tbucketTag += \" \" + fields[preFields].(string) + \"_\"\n\t}\n\taggValue := fields[target].(string)\n\n\t\/\/get time\n\tnow, err := strconv.ParseInt(fields[timestamp].(string), 10, 64)\n\tif err != nil {\n\t\tlog.Debug(\"[Record] timestamp:%v can't use strconv.ParseInt\", fields[timestamp].(string))\n\t\tnow = time.Now().Unix()\n\t}\n\n\tif _, ok := p.buckets[bucketName]; !ok {\n\t\tp.buckets[bucketName] = make(map[string][]int64)\n\t}\n\taggValueInt, err := strconv.ParseInt(aggValue, 10, 64)\n\tif err != nil {\n\t\tlog.Infof(\"[Record] target:%v can't use strconv.ParseInt\", aggValue)\n\t\tp.buckets[bucketName][bucketTag] = append(p.buckets[bucketName][bucketTag], 1)\n\t} else {\n\t\tp.buckets[bucketName][bucketTag] = append(p.buckets[bucketName][bucketTag], aggValueInt)\n\t}\n\treturn now\n}\n\nfunc quickSort(values []int64, left, right int64) {\n\ttemp := values[left]\n\tp := left\n\ti, j := left, right\n\tfor i <= j {\n\t\tfor j >= p && values[j] >= temp {\n\t\t\tj--\n\t\t}\n\t\tif j >= p {\n\t\t\tvalues[p] = values[j]\n\t\t\tp = j\n\t\t}\n\t\tfor i <= p && values[i] <= temp {\n\t\t\ti++\n\t\t}\n\t\tif i <= p {\n\t\t\tvalues[p] = values[i]\n\t\t\tp = i\n\t\t}\n\t}\n\tvalues[p] = temp\n\n\tif p-left > 1 {\n\t\tquickSort(values, left, p-1)\n\t}\n\tif right-p > 1 {\n\t\tquickSort(values, p+1, right)\n\t}\n}\n\nfunc getAggregation(targetValue []int64, aggregations []string) map[string]int64 {\n\tlog.Infof(\"[getAggregation] targetValue is : %v\", targetValue)\n\taggregationResults := map[string]int64{}\n\tcnt := int64(len(targetValue))\n\tavg := int64(0)\n\tsum := int64(0)\n\tmin := int64(0)\n\tmax := int64(0)\n\tif cnt > 0 {\n\t\tmin = targetValue[0]\n\t\tmax = targetValue[0]\n\t}\n\tquickSort(targetValue, int64(0), int64(len(targetValue)-1))\n\tfor _, value := range targetValue {\n\t\tsum += value\n\t\tif value > max {\n\t\t\tmax = value\n\t\t}\n\t\tif value < min {\n\t\t\tmin = value\n\t\t}\n\t}\n\tavg = sum \/ cnt\n\tfor i := 0; i < len(aggregations); i++ {\n\t\tswitch aggregations[i] {\n\t\tcase \"cnt\":\n\t\t\taggregationResults[\"cnt\"] = int64(len(targetValue))\n\t\tcase \"sum\":\n\t\t\taggregationResults[\"sum\"] = sum\n\t\tcase \"avg\":\n\t\t\taggregationResults[\"avg\"] = avg\n\t\tcase \"min\":\n\t\t\taggregationResults[\"min\"] = min\n\t\tcase \"max\":\n\t\t\taggregationResults[\"max\"] = max\n\t\tdefault:\n\t\t\tif aggregations[i][0] == 'p' {\n\t\t\t\tproportion, err := strconv.ParseInt(aggregations[i][1:], 10, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(aggregations[i])\n\t\t\t\t}\n\t\t\t\tindex := cnt*proportion\/100 - 1\n\t\t\t\tif cnt*proportion\/100-1 < 0 {\n\t\t\t\t\tindex = 0\n\t\t\t\t}\n\t\t\t\tpercentile := targetValue[index]\n\t\t\t\taggregationResults[aggregations[i]] = percentile\n\t\t\t}\n\t\t}\n\t}\n\treturn aggregationResults\n}\n\nfunc (p *Aggregator) Dump(timestamp int64) map[string]interface{} {\n\tfields := map[string]interface{}{}\n\tlog.Infof(\"[Dump] bucket is : %v\", p.buckets)\n\t\/\/now := strconv.FormatInt(timestamp, 10)\n\tfor bucketName, bucketTag_value := range p.buckets {\n\t\tfor bucketTag, targetValue := range bucketTag_value {\n\t\t\taggregations := p.AggregatorConfigs[bucketName].Aggregations\n\t\t\tfields[bucketName+bucketTag] = getAggregation(targetValue, aggregations)\n\t\t}\n\t}\n\tfields[\"timestamp\"] = timestamp\n\tp.postTime = getSampleTime(timestamp, p.Interval)\n\tp.buckets = map[string]map[string][]int64{}\n\tlog.Infof(\"[Dump] fields is : %v\", fields)\n\treturn fields\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ example to demonstrate reading query parameters (with multiple values in the below format) using net\/http library.\n\/\/ example input: https:\/\/localhost:8080\/customer?country=usa&country=india\n\/\/ required output: a slice of string with values usa and india like this []string{\"usa\",\"india\"}\n\/\/\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n)\n\nfunc queryParamHandler(w http.ResponseWriter, r *http.Request) {\n\tvars, err := url.ParseQuery(r.URL.RawQuery)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t}\n\tvar country []string\n\tcountry = vars[\"country\"]\n\n\tfmt.Fprintln(w, country)\n}\n\nfunc main() {\n\n\thttp.HandleFunc(\"\/customer\", queryParamHandler)\n\n\terr := http.ListenAndServe(\":8080\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n<commit_msg>Update read-query-param-multiple2.go<commit_after>\/\/ example to demonstrate reading query parameters (with multiple values in the below format) using net\/http library.\n\/\/ example input: http:\/\/localhost:8080\/customer?country=usa&country=india\n\/\/ required output: a slice of string with values usa and india like this []string{\"usa\",\"india\"}\n\/\/\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n)\n\nfunc queryParamHandler(w http.ResponseWriter, r *http.Request) {\n\tvars, err := url.ParseQuery(r.URL.RawQuery)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t}\n\tvar country []string\n\tcountry = vars[\"country\"]\n\n\tfmt.Fprintln(w, country)\n}\n\nfunc main() {\n\n\thttp.HandleFunc(\"\/customer\", queryParamHandler)\n\n\terr := http.ListenAndServe(\":8080\", nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 Jigsaw Operations LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage service\n\nimport (\n\t\"bytes\"\n\t\"container\/list\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\tonet \"github.com\/Jigsaw-Code\/outline-ss-server\/net\"\n\t\"github.com\/Jigsaw-Code\/outline-ss-server\/service\/metrics\"\n\tss \"github.com\/Jigsaw-Code\/outline-ss-server\/shadowsocks\"\n\tlogging \"github.com\/op\/go-logging\"\n\t\"github.com\/shadowsocks\/go-shadowsocks2\/socks\"\n)\n\nfunc remoteIP(conn net.Conn) net.IP {\n\taddr := conn.RemoteAddr()\n\tif addr == nil {\n\t\treturn nil\n\t}\n\tif tcpaddr, ok := addr.(*net.TCPAddr); ok {\n\t\treturn tcpaddr.IP\n\t}\n\tipstr, _, err := net.SplitHostPort(addr.String())\n\tif err == nil {\n\t\treturn net.ParseIP(ipstr)\n\t}\n\treturn nil\n}\n\n\/\/ Wrapper for logger.Debugf during TCP access key searches.\nfunc debugTCP(cipherID, template string, val interface{}) {\n\t\/\/ This is an optimization to reduce unnecessary allocations due to an interaction\n\t\/\/ between Go's inlining\/escape analysis and varargs functions like logger.Debugf.\n\tif logger.IsEnabledFor(logging.DEBUG) {\n\t\tlogger.Debugf(\"TCP(%s): \"+template, cipherID, val)\n\t}\n}\n\nfunc findAccessKey(clientReader io.Reader, clientIP net.IP, cipherList CipherList) (*CipherEntry, io.Reader, []byte, time.Duration, error) {\n\t\/\/ We snapshot the list because it may be modified while we use it.\n\ttcpTrialSize, ciphers := cipherList.SnapshotForClientIP(clientIP)\n\tfirstBytes := make([]byte, tcpTrialSize)\n\tif n, err := io.ReadFull(clientReader, firstBytes); err != nil {\n\t\treturn nil, clientReader, nil, 0, fmt.Errorf(\"Reading header failed after %d bytes: %v\", n, err)\n\t}\n\n\tfindStartTime := time.Now()\n\tentry, elt := findEntry(firstBytes, ciphers)\n\ttimeToCipher := time.Now().Sub(findStartTime)\n\tif entry == nil {\n\t\t\/\/ TODO: Ban and log client IPs with too many failures too quick to protect against DoS.\n\t\treturn nil, clientReader, nil, timeToCipher, fmt.Errorf(\"Could not find valid TCP cipher\")\n\t}\n\n\t\/\/ Move the active cipher to the front, so that the search is quicker next time.\n\tcipherList.MarkUsedByClientIP(elt, clientIP)\n\tsalt := firstBytes[:entry.Cipher.SaltSize()]\n\treturn entry, io.MultiReader(bytes.NewReader(firstBytes), clientReader), salt, timeToCipher, nil\n}\n\n\/\/ Implements a trial decryption search.  This assumes that all ciphers are AEAD.\nfunc findEntry(firstBytes []byte, ciphers []*list.Element) (*CipherEntry, *list.Element) {\n\t\/\/ Constant of zeroes to use as the start chunk count.\n\tzeroCountBuf := [maxNonceSize]byte{}\n\t\/\/ To hold the decrypted chunk length.\n\tchunkLenBuf := [2]byte{}\n\tfor ci, elt := range ciphers {\n\t\tentry := elt.Value.(*CipherEntry)\n\t\tid, cipher := entry.ID, entry.Cipher\n\t\tsaltsize := cipher.SaltSize()\n\t\tsalt := firstBytes[:saltsize]\n\t\taead, err := cipher.Decrypter(salt)\n\t\tif err != nil {\n\t\t\tdebugTCP(id, \"Failed to create decrypter: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tcipherTextLength := 2 + aead.Overhead()\n\t\tcipherText := firstBytes[saltsize : saltsize+cipherTextLength]\n\t\t_, err = aead.Open(chunkLenBuf[:0], zeroCountBuf[:aead.NonceSize()], cipherText, nil)\n\t\tif err != nil {\n\t\t\tdebugTCP(id, \"Failed to decrypt length: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tdebugTCP(id, \"Found cipher at index %d\", ci)\n\t\t\/\/ Move the active cipher to the front, so that the search is quicker next time.\n\t\treturn entry, elt\n\t}\n\treturn nil, nil\n}\n\ntype tcpService struct {\n\tmu          sync.RWMutex \/\/ Protects .listeners and .stopped\n\tlistener    *net.TCPListener\n\tstopped     bool\n\tciphers     CipherList\n\tm           metrics.ShadowsocksMetrics\n\trunning     sync.WaitGroup\n\treadTimeout time.Duration\n\t\/\/ `replayCache` is a pointer to SSServer.replayCache, to share the cache among all ports.\n\treplayCache       *ReplayCache\n\ttargetIPValidator onet.TargetIPValidator\n}\n\n\/\/ NewTCPService creates a TCPService\n\/\/ `replayCache` is a pointer to SSServer.replayCache, to share the cache among all ports.\nfunc NewTCPService(ciphers CipherList, replayCache *ReplayCache, m metrics.ShadowsocksMetrics, timeout time.Duration) TCPService {\n\treturn &tcpService{\n\t\tciphers:           ciphers,\n\t\tm:                 m,\n\t\treadTimeout:       timeout,\n\t\treplayCache:       replayCache,\n\t\ttargetIPValidator: onet.RequirePublicIP,\n\t}\n}\n\n\/\/ TCPService is a Shadowsocks TCP service that can be started and stopped.\ntype TCPService interface {\n\t\/\/ SetTargetIPValidator sets the function to be used to validate the target IP addresses.\n\tSetTargetIPValidator(targetIPValidator onet.TargetIPValidator)\n\t\/\/ Serve adopts the listener, which will be closed before Serve returns.  Serve returns an error unless Stop() was called.\n\tServe(listener *net.TCPListener) error\n\t\/\/ Stop closes the listener but does not interfere with existing connections.\n\tStop() error\n\t\/\/ GracefulStop calls Stop(), and then blocks until all resources have been cleaned up.\n\tGracefulStop() error\n}\n\nfunc (s *tcpService) SetTargetIPValidator(targetIPValidator onet.TargetIPValidator) {\n\ts.targetIPValidator = targetIPValidator\n}\n\n\/\/ proxyConnection will route the clientConn according to the address read from the connection.\nfunc proxyConnection(clientSSConn onet.DuplexConn, tgtAddr socks.Addr, proxyMetrics *metrics.ProxyMetrics, targetIPValidator onet.TargetIPValidator) *onet.ConnectionError {\n\ttgtTCPAddr, err := net.ResolveTCPAddr(\"tcp\", tgtAddr.String())\n\tif err != nil {\n\t\treturn onet.NewConnectionError(\"ERR_RESOLVE_ADDRESS\", fmt.Sprintf(\"Failed to resolve target address %v\", tgtAddr.String()), err)\n\t}\n\tif err := targetIPValidator(tgtTCPAddr.IP); err != nil {\n\t\treturn err\n\t}\n\n\ttgtTCPConn, err := net.DialTCP(\"tcp\", nil, tgtTCPAddr)\n\tif err != nil {\n\t\treturn onet.NewConnectionError(\"ERR_CONNECT\", \"Failed to connect to target\", err)\n\t}\n\tdefer tgtTCPConn.Close()\n\ttgtTCPConn.SetKeepAlive(true)\n\ttgtConn := metrics.MeasureConn(tgtTCPConn, &proxyMetrics.ProxyTarget, &proxyMetrics.TargetProxy)\n\n\tlogger.Debugf(\"proxy %s <-> %s\", clientSSConn.RemoteAddr().String(), tgtConn.RemoteAddr().String())\n\tfromClientErrCh := make(chan error)\n\tgo func() {\n\t\t_, fromClientErr := clientSSConn.(io.WriterTo).WriteTo(tgtConn)\n\t\t\/\/ Send FIN to target.\n\t\ttgtConn.CloseWrite()\n\t\tif fromClientErr != nil {\n\t\t\t\/\/ Drain to prevent a close on cipher error.\n\t\t\t\/\/ TODO: Need to drain the underlying connections instead.\n\t\t\tclientSSConn.(io.WriterTo).WriteTo(ioutil.Discard)\n\t\t}\n\t\tclientSSConn.CloseRead()\n\t\tfromClientErrCh <- fromClientErr\n\t}()\n\t_, fromTargetErr := clientSSConn.(io.ReaderFrom).ReadFrom(tgtConn)\n\t\/\/ Send FIN to client.\n\tclientSSConn.CloseWrite()\n\ttgtConn.CloseRead()\n\n\tfromClientErr := <-fromClientErrCh\n\tif fromClientErr != nil {\n\t\treturn onet.NewConnectionError(\"ERR_RELAY_CLIENT\", \"Failed to relay traffic from client\", fromClientErr)\n\t}\n\tif fromTargetErr != nil {\n\t\treturn onet.NewConnectionError(\"ERR_RELAY_TARGET\", \"Failed to relay traffic from target\", fromTargetErr)\n\t}\n\treturn nil\n}\n\nfunc (s *tcpService) Serve(listener *net.TCPListener) error {\n\ts.mu.Lock()\n\tif s.listener != nil {\n\t\ts.mu.Unlock()\n\t\tlistener.Close()\n\t\treturn errors.New(\"Serve can only be called once\")\n\t}\n\tif s.stopped {\n\t\ts.mu.Unlock()\n\t\treturn listener.Close()\n\t}\n\ts.listener = listener\n\ts.running.Add(1)\n\ts.mu.Unlock()\n\n\tdefer s.running.Done()\n\tfor {\n\t\tclientConn, err := listener.AcceptTCP()\n\t\tif err != nil {\n\t\t\ts.mu.RLock()\n\t\t\tstopped := s.stopped\n\t\t\ts.mu.RUnlock()\n\t\t\tif stopped {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tlogger.Errorf(\"Accept failed: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\ts.running.Add(1)\n\t\tgo func() {\n\t\t\tdefer s.running.Done()\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tlogger.Errorf(\"Panic in TCP handler: %v\", r)\n\t\t\t\t}\n\t\t\t}()\n\t\t\ts.handleConnection(listener.Addr().(*net.TCPAddr).Port, clientConn)\n\t\t}()\n\t}\n}\n\nfunc (s *tcpService) handleConnection(listenerPort int, clientTCPConn *net.TCPConn) {\n\tclientLocation, err := s.m.GetLocation(clientTCPConn.RemoteAddr())\n\tif err != nil {\n\t\tlogger.Warningf(\"Failed location lookup: %v\", err)\n\t}\n\tlogger.Debugf(\"Got location \\\"%v\\\" for IP %v\", clientLocation, clientTCPConn.RemoteAddr().String())\n\ts.m.AddOpenTCPConnection(clientLocation)\n\n\tconnStart := time.Now()\n\tclientTCPConn.SetKeepAlive(true)\n\t\/\/ Set a deadline to receive the address to the target.\n\tclientTCPConn.SetReadDeadline(connStart.Add(s.readTimeout))\n\tvar proxyMetrics metrics.ProxyMetrics\n\tclientConn := metrics.MeasureConn(clientTCPConn, &proxyMetrics.ProxyClient, &proxyMetrics.ClientProxy)\n\tcipherEntry, clientReader, clientSalt, timeToCipher, keyErr := findAccessKey(clientConn, remoteIP(clientConn), s.ciphers)\n\n\tconnError := func() *onet.ConnectionError {\n\t\tif keyErr != nil {\n\t\t\tlogger.Debugf(\"Failed to find a valid cipher after reading %v bytes: %v\", proxyMetrics.ClientProxy, keyErr)\n\t\t\tconst status = \"ERR_CIPHER\"\n\t\t\ts.absorbProbe(listenerPort, clientConn, clientLocation, status, &proxyMetrics)\n\t\t\treturn onet.NewConnectionError(status, \"Failed to find a valid cipher\", keyErr)\n\t\t}\n\n\t\tisServerSalt := cipherEntry.SaltGenerator.IsServerSalt(clientSalt)\n\t\t\/\/ Only check the cache if findAccessKey succeeded and the salt is unrecognized.\n\t\tif isServerSalt || !s.replayCache.Add(cipherEntry.ID, clientSalt) {\n\t\t\tvar status string\n\t\t\tif isServerSalt {\n\t\t\t\tstatus = \"ERR_REPLAY_SERVER\"\n\t\t\t} else {\n\t\t\t\tstatus = \"ERR_REPLAY_CLIENT\"\n\t\t\t}\n\t\t\ts.absorbProbe(listenerPort, clientConn, clientLocation, status, &proxyMetrics)\n\t\t\tlogger.Debugf(status+\": %v in %s sent %d bytes\", clientConn.RemoteAddr(), clientLocation, proxyMetrics.ClientProxy)\n\t\t\treturn onet.NewConnectionError(status, \"Replay detected\", nil)\n\t\t}\n\n\t\tssr := ss.NewShadowsocksReader(clientReader, cipherEntry.Cipher)\n\t\ttgtAddr, err := socks.ReadAddr(ssr)\n\t\tif err != nil {\n\t\t\t\/\/ Drain to prevent a close on cipher error.\n\t\t\tclientConn.(io.WriterTo).WriteTo(ioutil.Discard)\n\t\t\treturn onet.NewConnectionError(\"ERR_READ_ADDRESS\", \"Failed to get target address\", err)\n\t\t}\n\n\t\t\/\/ Clear the deadline for the target address\n\t\tclientConn.SetReadDeadline(time.Time{})\n\t\tssw := ss.NewShadowsocksWriter(clientConn, cipherEntry.Cipher)\n\t\tssw.SetSaltGenerator(cipherEntry.SaltGenerator)\n\t\tclientSSConn := onet.WrapConn(clientConn, ssr, ssw)\n\t\treturn proxyConnection(clientSSConn, tgtAddr, &proxyMetrics, s.targetIPValidator)\n\t}()\n\n\tconnDuration := time.Now().Sub(connStart)\n\tstatus := \"OK\"\n\tif connError != nil {\n\t\tlogger.Debugf(\"TCP Error: %v: %v\", connError.Message, connError.Cause)\n\t\tstatus = connError.Status\n\t}\n\tvar id string\n\tif cipherEntry != nil {\n\t\tid = cipherEntry.ID\n\t}\n\ts.m.AddClosedTCPConnection(clientLocation, id, status, proxyMetrics, timeToCipher, connDuration)\n\tclientConn.Close() \/\/ Closing after the metrics are added aids integration testing.\n\tlogger.Debugf(\"Done with status %v, duration %v\", status, connDuration)\n}\n\n\/\/ Keep the connection open until we hit the authentication deadline to protect against probing attacks\n\/\/ `proxyMetrics` is a pointer because its value is being mutated by `clientConn`.\nfunc (s *tcpService) absorbProbe(listenerPort int, clientConn io.ReadCloser, clientLocation, status string, proxyMetrics *metrics.ProxyMetrics) {\n\t_, drainErr := io.Copy(ioutil.Discard, clientConn) \/\/ drain socket\n\tdrainResult := drainErrToString(drainErr)\n\tlogger.Debugf(\"Drain error: %v, drain result: %v\", drainErr, drainResult)\n\ts.m.AddTCPProbe(clientLocation, status, drainResult, listenerPort, *proxyMetrics)\n}\n\nfunc drainErrToString(drainErr error) string {\n\tnetErr, ok := drainErr.(net.Error)\n\tswitch {\n\tcase drainErr == nil:\n\t\treturn \"eof\"\n\tcase ok && netErr.Timeout():\n\t\treturn \"timeout\"\n\tdefault:\n\t\treturn \"other\"\n\t}\n}\n\nfunc (s *tcpService) Stop() error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.stopped = true\n\tif s.listener == nil {\n\t\treturn nil\n\t}\n\treturn s.listener.Close()\n}\n\nfunc (s *tcpService) GracefulStop() error {\n\terr := s.Stop()\n\ts.running.Wait()\n\treturn err\n}\n<commit_msg>Move tgtConn.CloseWrite<commit_after>\/\/ Copyright 2018 Jigsaw Operations LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage service\n\nimport (\n\t\"bytes\"\n\t\"container\/list\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\tonet \"github.com\/Jigsaw-Code\/outline-ss-server\/net\"\n\t\"github.com\/Jigsaw-Code\/outline-ss-server\/service\/metrics\"\n\tss \"github.com\/Jigsaw-Code\/outline-ss-server\/shadowsocks\"\n\tlogging \"github.com\/op\/go-logging\"\n\t\"github.com\/shadowsocks\/go-shadowsocks2\/socks\"\n)\n\nfunc remoteIP(conn net.Conn) net.IP {\n\taddr := conn.RemoteAddr()\n\tif addr == nil {\n\t\treturn nil\n\t}\n\tif tcpaddr, ok := addr.(*net.TCPAddr); ok {\n\t\treturn tcpaddr.IP\n\t}\n\tipstr, _, err := net.SplitHostPort(addr.String())\n\tif err == nil {\n\t\treturn net.ParseIP(ipstr)\n\t}\n\treturn nil\n}\n\n\/\/ Wrapper for logger.Debugf during TCP access key searches.\nfunc debugTCP(cipherID, template string, val interface{}) {\n\t\/\/ This is an optimization to reduce unnecessary allocations due to an interaction\n\t\/\/ between Go's inlining\/escape analysis and varargs functions like logger.Debugf.\n\tif logger.IsEnabledFor(logging.DEBUG) {\n\t\tlogger.Debugf(\"TCP(%s): \"+template, cipherID, val)\n\t}\n}\n\nfunc findAccessKey(clientReader io.Reader, clientIP net.IP, cipherList CipherList) (*CipherEntry, io.Reader, []byte, time.Duration, error) {\n\t\/\/ We snapshot the list because it may be modified while we use it.\n\ttcpTrialSize, ciphers := cipherList.SnapshotForClientIP(clientIP)\n\tfirstBytes := make([]byte, tcpTrialSize)\n\tif n, err := io.ReadFull(clientReader, firstBytes); err != nil {\n\t\treturn nil, clientReader, nil, 0, fmt.Errorf(\"Reading header failed after %d bytes: %v\", n, err)\n\t}\n\n\tfindStartTime := time.Now()\n\tentry, elt := findEntry(firstBytes, ciphers)\n\ttimeToCipher := time.Now().Sub(findStartTime)\n\tif entry == nil {\n\t\t\/\/ TODO: Ban and log client IPs with too many failures too quick to protect against DoS.\n\t\treturn nil, clientReader, nil, timeToCipher, fmt.Errorf(\"Could not find valid TCP cipher\")\n\t}\n\n\t\/\/ Move the active cipher to the front, so that the search is quicker next time.\n\tcipherList.MarkUsedByClientIP(elt, clientIP)\n\tsalt := firstBytes[:entry.Cipher.SaltSize()]\n\treturn entry, io.MultiReader(bytes.NewReader(firstBytes), clientReader), salt, timeToCipher, nil\n}\n\n\/\/ Implements a trial decryption search.  This assumes that all ciphers are AEAD.\nfunc findEntry(firstBytes []byte, ciphers []*list.Element) (*CipherEntry, *list.Element) {\n\t\/\/ Constant of zeroes to use as the start chunk count.\n\tzeroCountBuf := [maxNonceSize]byte{}\n\t\/\/ To hold the decrypted chunk length.\n\tchunkLenBuf := [2]byte{}\n\tfor ci, elt := range ciphers {\n\t\tentry := elt.Value.(*CipherEntry)\n\t\tid, cipher := entry.ID, entry.Cipher\n\t\tsaltsize := cipher.SaltSize()\n\t\tsalt := firstBytes[:saltsize]\n\t\taead, err := cipher.Decrypter(salt)\n\t\tif err != nil {\n\t\t\tdebugTCP(id, \"Failed to create decrypter: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tcipherTextLength := 2 + aead.Overhead()\n\t\tcipherText := firstBytes[saltsize : saltsize+cipherTextLength]\n\t\t_, err = aead.Open(chunkLenBuf[:0], zeroCountBuf[:aead.NonceSize()], cipherText, nil)\n\t\tif err != nil {\n\t\t\tdebugTCP(id, \"Failed to decrypt length: %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tdebugTCP(id, \"Found cipher at index %d\", ci)\n\t\t\/\/ Move the active cipher to the front, so that the search is quicker next time.\n\t\treturn entry, elt\n\t}\n\treturn nil, nil\n}\n\ntype tcpService struct {\n\tmu          sync.RWMutex \/\/ Protects .listeners and .stopped\n\tlistener    *net.TCPListener\n\tstopped     bool\n\tciphers     CipherList\n\tm           metrics.ShadowsocksMetrics\n\trunning     sync.WaitGroup\n\treadTimeout time.Duration\n\t\/\/ `replayCache` is a pointer to SSServer.replayCache, to share the cache among all ports.\n\treplayCache       *ReplayCache\n\ttargetIPValidator onet.TargetIPValidator\n}\n\n\/\/ NewTCPService creates a TCPService\n\/\/ `replayCache` is a pointer to SSServer.replayCache, to share the cache among all ports.\nfunc NewTCPService(ciphers CipherList, replayCache *ReplayCache, m metrics.ShadowsocksMetrics, timeout time.Duration) TCPService {\n\treturn &tcpService{\n\t\tciphers:           ciphers,\n\t\tm:                 m,\n\t\treadTimeout:       timeout,\n\t\treplayCache:       replayCache,\n\t\ttargetIPValidator: onet.RequirePublicIP,\n\t}\n}\n\n\/\/ TCPService is a Shadowsocks TCP service that can be started and stopped.\ntype TCPService interface {\n\t\/\/ SetTargetIPValidator sets the function to be used to validate the target IP addresses.\n\tSetTargetIPValidator(targetIPValidator onet.TargetIPValidator)\n\t\/\/ Serve adopts the listener, which will be closed before Serve returns.  Serve returns an error unless Stop() was called.\n\tServe(listener *net.TCPListener) error\n\t\/\/ Stop closes the listener but does not interfere with existing connections.\n\tStop() error\n\t\/\/ GracefulStop calls Stop(), and then blocks until all resources have been cleaned up.\n\tGracefulStop() error\n}\n\nfunc (s *tcpService) SetTargetIPValidator(targetIPValidator onet.TargetIPValidator) {\n\ts.targetIPValidator = targetIPValidator\n}\n\n\/\/ proxyConnection will route the clientConn according to the address read from the connection.\nfunc proxyConnection(clientSSConn onet.DuplexConn, tgtAddr socks.Addr, proxyMetrics *metrics.ProxyMetrics, targetIPValidator onet.TargetIPValidator) *onet.ConnectionError {\n\ttgtTCPAddr, err := net.ResolveTCPAddr(\"tcp\", tgtAddr.String())\n\tif err != nil {\n\t\treturn onet.NewConnectionError(\"ERR_RESOLVE_ADDRESS\", fmt.Sprintf(\"Failed to resolve target address %v\", tgtAddr.String()), err)\n\t}\n\tif err := targetIPValidator(tgtTCPAddr.IP); err != nil {\n\t\treturn err\n\t}\n\n\ttgtTCPConn, err := net.DialTCP(\"tcp\", nil, tgtTCPAddr)\n\tif err != nil {\n\t\treturn onet.NewConnectionError(\"ERR_CONNECT\", \"Failed to connect to target\", err)\n\t}\n\tdefer tgtTCPConn.Close()\n\ttgtTCPConn.SetKeepAlive(true)\n\ttgtConn := metrics.MeasureConn(tgtTCPConn, &proxyMetrics.ProxyTarget, &proxyMetrics.TargetProxy)\n\n\tlogger.Debugf(\"proxy %s <-> %s\", clientSSConn.RemoteAddr().String(), tgtConn.RemoteAddr().String())\n\tfromClientErrCh := make(chan error)\n\tgo func() {\n\t\t_, fromClientErr := clientSSConn.(io.WriterTo).WriteTo(tgtConn)\n\t\tif fromClientErr != nil {\n\t\t\t\/\/ Drain to prevent a close on cipher error.\n\t\t\t\/\/ TODO: Need to drain the underlying connections instead.\n\t\t\tclientSSConn.(io.WriterTo).WriteTo(ioutil.Discard)\n\t\t}\n\t\tclientSSConn.CloseRead()\n\t\t\/\/ Send FIN to target.\n\t\t\/\/ We must do this after the drain is completed, otherwise the target will close its\n\t\t\/\/ connection with the proxy, which will, in turn, close the connection with the client.\n\t\ttgtConn.CloseWrite()\n\t\tfromClientErrCh <- fromClientErr\n\t}()\n\t_, fromTargetErr := clientSSConn.(io.ReaderFrom).ReadFrom(tgtConn)\n\t\/\/ Send FIN to client.\n\tclientSSConn.CloseWrite()\n\ttgtConn.CloseRead()\n\n\tfromClientErr := <-fromClientErrCh\n\tif fromClientErr != nil {\n\t\treturn onet.NewConnectionError(\"ERR_RELAY_CLIENT\", \"Failed to relay traffic from client\", fromClientErr)\n\t}\n\tif fromTargetErr != nil {\n\t\treturn onet.NewConnectionError(\"ERR_RELAY_TARGET\", \"Failed to relay traffic from target\", fromTargetErr)\n\t}\n\treturn nil\n}\n\nfunc (s *tcpService) Serve(listener *net.TCPListener) error {\n\ts.mu.Lock()\n\tif s.listener != nil {\n\t\ts.mu.Unlock()\n\t\tlistener.Close()\n\t\treturn errors.New(\"Serve can only be called once\")\n\t}\n\tif s.stopped {\n\t\ts.mu.Unlock()\n\t\treturn listener.Close()\n\t}\n\ts.listener = listener\n\ts.running.Add(1)\n\ts.mu.Unlock()\n\n\tdefer s.running.Done()\n\tfor {\n\t\tclientConn, err := listener.AcceptTCP()\n\t\tif err != nil {\n\t\t\ts.mu.RLock()\n\t\t\tstopped := s.stopped\n\t\t\ts.mu.RUnlock()\n\t\t\tif stopped {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tlogger.Errorf(\"Accept failed: %v\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\ts.running.Add(1)\n\t\tgo func() {\n\t\t\tdefer s.running.Done()\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tlogger.Errorf(\"Panic in TCP handler: %v\", r)\n\t\t\t\t}\n\t\t\t}()\n\t\t\ts.handleConnection(listener.Addr().(*net.TCPAddr).Port, clientConn)\n\t\t}()\n\t}\n}\n\nfunc (s *tcpService) handleConnection(listenerPort int, clientTCPConn *net.TCPConn) {\n\tclientLocation, err := s.m.GetLocation(clientTCPConn.RemoteAddr())\n\tif err != nil {\n\t\tlogger.Warningf(\"Failed location lookup: %v\", err)\n\t}\n\tlogger.Debugf(\"Got location \\\"%v\\\" for IP %v\", clientLocation, clientTCPConn.RemoteAddr().String())\n\ts.m.AddOpenTCPConnection(clientLocation)\n\n\tconnStart := time.Now()\n\tclientTCPConn.SetKeepAlive(true)\n\t\/\/ Set a deadline to receive the address to the target.\n\tclientTCPConn.SetReadDeadline(connStart.Add(s.readTimeout))\n\tvar proxyMetrics metrics.ProxyMetrics\n\tclientConn := metrics.MeasureConn(clientTCPConn, &proxyMetrics.ProxyClient, &proxyMetrics.ClientProxy)\n\tcipherEntry, clientReader, clientSalt, timeToCipher, keyErr := findAccessKey(clientConn, remoteIP(clientConn), s.ciphers)\n\n\tconnError := func() *onet.ConnectionError {\n\t\tif keyErr != nil {\n\t\t\tlogger.Debugf(\"Failed to find a valid cipher after reading %v bytes: %v\", proxyMetrics.ClientProxy, keyErr)\n\t\t\tconst status = \"ERR_CIPHER\"\n\t\t\ts.absorbProbe(listenerPort, clientConn, clientLocation, status, &proxyMetrics)\n\t\t\treturn onet.NewConnectionError(status, \"Failed to find a valid cipher\", keyErr)\n\t\t}\n\n\t\tisServerSalt := cipherEntry.SaltGenerator.IsServerSalt(clientSalt)\n\t\t\/\/ Only check the cache if findAccessKey succeeded and the salt is unrecognized.\n\t\tif isServerSalt || !s.replayCache.Add(cipherEntry.ID, clientSalt) {\n\t\t\tvar status string\n\t\t\tif isServerSalt {\n\t\t\t\tstatus = \"ERR_REPLAY_SERVER\"\n\t\t\t} else {\n\t\t\t\tstatus = \"ERR_REPLAY_CLIENT\"\n\t\t\t}\n\t\t\ts.absorbProbe(listenerPort, clientConn, clientLocation, status, &proxyMetrics)\n\t\t\tlogger.Debugf(status+\": %v in %s sent %d bytes\", clientConn.RemoteAddr(), clientLocation, proxyMetrics.ClientProxy)\n\t\t\treturn onet.NewConnectionError(status, \"Replay detected\", nil)\n\t\t}\n\n\t\tssr := ss.NewShadowsocksReader(clientReader, cipherEntry.Cipher)\n\t\ttgtAddr, err := socks.ReadAddr(ssr)\n\t\tif err != nil {\n\t\t\t\/\/ Drain to prevent a close on cipher error.\n\t\t\tclientConn.(io.WriterTo).WriteTo(ioutil.Discard)\n\t\t\treturn onet.NewConnectionError(\"ERR_READ_ADDRESS\", \"Failed to get target address\", err)\n\t\t}\n\n\t\t\/\/ Clear the deadline for the target address\n\t\tclientConn.SetReadDeadline(time.Time{})\n\t\tssw := ss.NewShadowsocksWriter(clientConn, cipherEntry.Cipher)\n\t\tssw.SetSaltGenerator(cipherEntry.SaltGenerator)\n\t\tclientSSConn := onet.WrapConn(clientConn, ssr, ssw)\n\t\treturn proxyConnection(clientSSConn, tgtAddr, &proxyMetrics, s.targetIPValidator)\n\t}()\n\n\tconnDuration := time.Now().Sub(connStart)\n\tstatus := \"OK\"\n\tif connError != nil {\n\t\tlogger.Debugf(\"TCP Error: %v: %v\", connError.Message, connError.Cause)\n\t\tstatus = connError.Status\n\t}\n\tvar id string\n\tif cipherEntry != nil {\n\t\tid = cipherEntry.ID\n\t}\n\ts.m.AddClosedTCPConnection(clientLocation, id, status, proxyMetrics, timeToCipher, connDuration)\n\tclientConn.Close() \/\/ Closing after the metrics are added aids integration testing.\n\tlogger.Debugf(\"Done with status %v, duration %v\", status, connDuration)\n}\n\n\/\/ Keep the connection open until we hit the authentication deadline to protect against probing attacks\n\/\/ `proxyMetrics` is a pointer because its value is being mutated by `clientConn`.\nfunc (s *tcpService) absorbProbe(listenerPort int, clientConn io.ReadCloser, clientLocation, status string, proxyMetrics *metrics.ProxyMetrics) {\n\t_, drainErr := io.Copy(ioutil.Discard, clientConn) \/\/ drain socket\n\tdrainResult := drainErrToString(drainErr)\n\tlogger.Debugf(\"Drain error: %v, drain result: %v\", drainErr, drainResult)\n\ts.m.AddTCPProbe(clientLocation, status, drainResult, listenerPort, *proxyMetrics)\n}\n\nfunc drainErrToString(drainErr error) string {\n\tnetErr, ok := drainErr.(net.Error)\n\tswitch {\n\tcase drainErr == nil:\n\t\treturn \"eof\"\n\tcase ok && netErr.Timeout():\n\t\treturn \"timeout\"\n\tdefault:\n\t\treturn \"other\"\n\t}\n}\n\nfunc (s *tcpService) Stop() error {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.stopped = true\n\tif s.listener == nil {\n\t\treturn nil\n\t}\n\treturn s.listener.Close()\n}\n\nfunc (s *tcpService) GracefulStop() error {\n\terr := s.Stop()\n\ts.running.Wait()\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ SPDX-License-Identifier: BSD-3-Clause\n\/\/\n\npackage gofish\n\nimport (\n\t\"encoding\/json\"\n\n\t\"github.com\/stmcginnis\/gofish\/common\"\n\t\"github.com\/stmcginnis\/gofish\/redfish\"\n\t\"github.com\/stmcginnis\/gofish\/swordfish\"\n)\n\n\/\/ Expand shall contain information about the support of the $expand query\n\/\/ parameter by the service.\ntype Expand struct {\n\t\/\/ ExpandAll shall be a boolean indicating whether this service supports the\n\t\/\/ use of asterisk (expand all entries) as a value for the $expand query\n\t\/\/ parameter as described by the specification.\n\tExpandAll bool\n\t\/\/ Levels shall be a boolean indicating whether this service supports the\n\t\/\/ use of $levels as a value for the $expand query parameter as described by\n\t\/\/ the specification.\n\tLevels bool\n\t\/\/ Links shall be a boolean indicating whether this service supports the use\n\t\/\/ of tilde (expand only entries in the Links section) as a value for the\n\t\/\/ $expand query parameter as described by the specification.\n\tLinks bool\n\t\/\/ MaxLevels shall be the maximum value of the $levels qualifier supported\n\t\/\/ by the service and shall only be included if the value of the Levels\n\t\/\/ property is true.\n\tMaxLevels int\n\t\/\/ NoLinks shall be a boolean indicating whether this service supports the\n\t\/\/ use of period (expand only entries not in the Links section) as a value\n\t\/\/ for the $expand query parameter as described by the specification.\n\tNoLinks bool\n}\n\n\/\/ ProtocolFeaturesSupported contains information about protocol features\n\/\/ supported by the service.\ntype ProtocolFeaturesSupported struct {\n\t\/\/ ExcerptQuery shall be a boolean indicating whether this service supports\n\t\/\/ the use of the 'excerpt' query parameter as described by the\n\t\/\/ specification.\n\tExcerptQuery bool\n\t\/\/ ExpandQuery shall contain information about the support of the $expand\n\t\/\/ query parameter by the service.\n\tExpandQuery Expand\n\t\/\/ FilterQuery shall be a boolean indicating whether this service supports\n\t\/\/ the use of the $filter query parameter as described by the specification.\n\tFilterQuery bool\n\t\/\/ OnlyMemberQuery shall be a boolean indicating whether this service\n\t\/\/ supports the use of the 'only' query parameter as described by the\n\t\/\/ specification.\n\tOnlyMemberQuery bool\n\t\/\/ SelectQuery shall be a boolean indicating whether this service supports\n\t\/\/ the use of the $select query parameter as described by the specification.\n\tSelectQuery bool\n}\n\n\/\/ Service represents the root Redfish service. All values for resources\n\/\/ described by this schema shall comply to the requirements as described in the\n\/\/ Redfish specification.\ntype Service struct {\n\tcommon.Entity\n\n\t\/\/ ODataContext is the odata context.\n\tODataContext string `json:\"@odata.context\"`\n\t\/\/ ODataID is the odata identifier.\n\tODataID string `json:\"@odata.id\"`\n\t\/\/ ODataType is the odata type.\n\tODataType string `json:\"@odata.type\"`\n\t\/\/ AccountService shall only contain a reference to a resource that complies\n\t\/\/ to the AccountService schema.\n\taccountService string\n\t\/\/ CertificateService shall be a link to the CertificateService.\n\tcertificateService string\n\t\/\/ Chassis shall only contain a reference to a collection of resources that\n\t\/\/ comply to the Chassis schema.\n\tchassis string\n\t\/\/ CompositionService shall only contain a reference to a resource that\n\t\/\/ complies to the CompositionService schema.\n\tcompositionService string\n\t\/\/ Description provides a description of this resource.\n\tDescription string\n\t\/\/ EventService shall only contain a reference to a resource that complies\n\t\/\/ to the EventService schema.\n\teventService string\n\t\/\/ Fabrics shall contain references to all Fabric instances.\n\tfabrics string\n\t\/\/ JobService shall only contain a reference to a resource that conforms to\n\t\/\/ the JobService schema.\n\tjobService string\n\t\/\/ JsonSchemas shall only contain a reference to a collection of resources\n\t\/\/ that comply to the SchemaFile schema where the files are Json-Schema\n\t\/\/ files.\n\tjsonSchemas string\n\t\/\/ Managers shall only contain a reference to a collection of resources that\n\t\/\/ comply to the Managers schema.\n\tmanagers string\n\t\/\/ Product shall include the name of the product represented by this Redfish\n\t\/\/ service.\n\tProduct string\n\t\/\/ ProtocolFeaturesSupported contains information about protocol features\n\t\/\/ supported by the service.\n\tProtocolFeaturesSupported ProtocolFeaturesSupported\n\t\/\/ RedfishVersion shall represent the version of the Redfish service. The\n\t\/\/ format of this string shall be of the format\n\t\/\/ majorversion.minorversion.errata in compliance with Protocol Version\n\t\/\/ section of the Redfish specification.\n\tRedfishVersion string\n\t\/\/ Registries shall contain a reference to Message Registry.\n\tregistries string\n\t\/\/ ResourceBlocks shall contain references to all Resource Block instances.\n\tresourceBlocks string\n\t\/\/ SessionService shall only contain a reference to a resource that complies\n\t\/\/ to the SessionService schema.\n\tsessionService string\n\t\/\/ StorageServices shall contain references to all StorageService instances.\n\tstorageServices string\n\t\/\/ StorageSystems shall contain computer systems that act as storage\n\t\/\/ servers. The HostingRoles attribute of each such computer system shall\n\t\/\/ have an entry for StorageServer.\n\tstorageSystems string\n\t\/\/ Systems shall only contain a reference to a collection of resources that\n\t\/\/ comply to the Systems schema.\n\tsystems string\n\t\/\/ Tasks shall only contain a reference to a resource that complies to the\n\t\/\/ TaskService schema.\n\ttasks string\n\t\/\/ TelemetryService shall be a link to the TelemetryService.\n\ttelemetryService string\n\t\/\/ UUID shall be an exact match of the UUID value returned in a 200OK from\n\t\/\/ an SSDP M-SEARCH request during discovery. RFC4122 describes methods that\n\t\/\/ can be used to create a UUID value. The value should be considered to be\n\t\/\/ opaque. Client software should only treat the overall value as a\n\t\/\/ universally unique identifier and should not interpret any sub-fields\n\t\/\/ within the UUID.\n\tUUID string\n\t\/\/ UpdateService shall only contain a reference to a resource that complies\n\t\/\/ to the UpdateService schema.\n\tupdateService string\n\t\/\/ Vendor shall include the name of the manufacturer or vendor represented\n\t\/\/ by this Redfish service. If this property is supported, the vendor name\n\t\/\/ shall not be included in the value of the Product property.\n\tVendor string\n\t\/\/ Sessions shall contain the link to a collection of Sessions.\n\tsessions string\n}\n\n\/\/ UnmarshalJSON unmarshals a Service object from the raw JSON.\nfunc (serviceroot *Service) UnmarshalJSON(b []byte) error {\n\ttype temp Service\n\tvar t struct {\n\t\ttemp\n\t\tCertificateService common.Link\n\t\tChassis            common.Link\n\t\tManagers           common.Link\n\t\tTasks              common.Link\n\t\tStorageServices    common.Link\n\t\tStorageSystems     common.Link\n\t\tAccountService     common.Link\n\t\tEventService       common.Link\n\t\tRegistries         common.Link\n\t\tSystems            common.Link\n\t\tCompositionService common.Link\n\t\tFabrics            common.Link\n\t\tJobService         common.Link\n\t\tJSONSchemas        common.Link `json:\"JsonSchemas\"`\n\t\tResourceBlocks     common.Link\n\t\tSessionService     common.Link\n\t\tTelemetryService   common.Link\n\t\tUpdateService      common.Link\n\t\tLinks              struct {\n\t\t\tSessions common.Link\n\t\t}\n\t}\n\n\terr := json.Unmarshal(b, &t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Extract the links to other entities for later\n\t*serviceroot = Service(t.temp)\n\tserviceroot.certificateService = string(t.CertificateService)\n\tserviceroot.chassis = string(t.Chassis)\n\tserviceroot.managers = string(t.Managers)\n\tserviceroot.tasks = string(t.Tasks)\n\tserviceroot.sessions = string(t.Links.Sessions)\n\tserviceroot.storageServices = string(t.StorageServices)\n\tserviceroot.storageSystems = string(t.StorageSystems)\n\tserviceroot.accountService = string(t.AccountService)\n\tserviceroot.eventService = string(t.EventService)\n\tserviceroot.registries = string(t.Registries)\n\tserviceroot.systems = string(t.Systems)\n\tserviceroot.compositionService = string(t.CompositionService)\n\tserviceroot.fabrics = string(t.Fabrics)\n\tserviceroot.jobService = string(t.JobService)\n\tserviceroot.jsonSchemas = string(t.JSONSchemas)\n\tserviceroot.resourceBlocks = string(t.ResourceBlocks)\n\tserviceroot.sessionService = string(t.SessionService)\n\tserviceroot.telemetryService = string(t.TelemetryService)\n\tserviceroot.updateService = string(t.UpdateService)\n\n\treturn nil\n}\n\n\/\/ ServiceRoot will get a Service instance from the service.\nfunc ServiceRoot(c common.Client) (*Service, error) {\n\tresp, err := c.Get(common.DefaultServiceRoot)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar serviceroot Service\n\terr = json.NewDecoder(resp.Body).Decode(&serviceroot)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserviceroot.SetClient(c)\n\treturn &serviceroot, nil\n}\n\n\/\/ Chassis gets the chassis instances managed by this service.\nfunc (serviceroot *Service) Chassis() ([]*redfish.Chassis, error) {\n\treturn redfish.ListReferencedChassis(serviceroot.Client, serviceroot.chassis)\n}\n\n\/\/ Managers gets the manager instances of this service.\nfunc (serviceroot *Service) Managers() ([]*redfish.Manager, error) {\n\treturn redfish.ListReferencedManagers(serviceroot.Client, serviceroot.managers)\n}\n\n\/\/ StorageSystems gets the storage system instances managed by this service.\nfunc (serviceroot *Service) StorageSystems() ([]*swordfish.StorageSystem, error) {\n\treturn swordfish.ListReferencedStorageSystems(serviceroot.Client, serviceroot.storageSystems)\n}\n\n\/\/ StorageServices gets the Swordfish storage services\nfunc (serviceroot *Service) StorageServices() ([]*swordfish.StorageService, error) {\n\treturn swordfish.ListReferencedStorageServices(serviceroot.Client, serviceroot.storageServices)\n}\n\n\/\/ Tasks gets the system's tasks\nfunc (serviceroot *Service) Tasks() ([]*redfish.Task, error) {\n\treturn redfish.ListReferencedTasks(serviceroot.Client, serviceroot.tasks)\n}\n\n\/\/ CreateSession creates a new session and returns the token and id\nfunc (serviceroot *Service) CreateSession(username string, password string) (*redfish.AuthToken, error) {\n\treturn redfish.CreateSession(serviceroot.Client, serviceroot.sessions, username, password)\n}\n\n\/\/ Sessions gets the system's active sessions\nfunc (serviceroot *Service) Sessions() ([]*redfish.Session, error) {\n\treturn redfish.ListReferencedSessions(serviceroot.Client, serviceroot.sessions)\n}\n\n\/\/ DeleteSession logout the specified session\nfunc (serviceroot *Service) DeleteSession(url string) error {\n\treturn redfish.DeleteSession(serviceroot.Client, url)\n}\n\n\/\/ AccountService gets the Redfish AccountService\nfunc (serviceroot *Service) AccountService() (*redfish.AccountService, error) {\n\treturn redfish.GetAccountService(serviceroot.Client, serviceroot.accountService)\n}\n\n\/\/ EventService gets the Redfish EventService\nfunc (serviceroot *Service) EventService() (*redfish.EventService, error) {\n\treturn redfish.GetEventService(serviceroot.Client, serviceroot.eventService)\n}\n\n\/\/ Registries gets the Redfish Registries\nfunc (serviceroot *Service) Registries() ([]*redfish.MessageRegistryFile, error) {\n\treturn redfish.ListReferencedMessageRegistryFiles(serviceroot.Client, serviceroot.registries)\n}\n\n\/\/ MessageRegistries gets all the available message registries in all languages\nfunc (serviceroot *Service) MessageRegistries() ([]*redfish.MessageRegistry, error) {\n\treturn redfish.ListReferencedMessageRegistries(serviceroot.Client, serviceroot.registries)\n}\n\n\/\/ MessageRegistriesByLanguage gets the message registries by language.\n\/\/ language is the RFC5646-conformant language code for the message registry, for example: \"en\".\nfunc (serviceroot *Service) MessageRegistriesByLanguage(language string) ([]*redfish.MessageRegistry, error) {\n\treturn redfish.ListReferencedMessageRegistriesByLanguage(serviceroot.Client, serviceroot.registries, language)\n}\n\n\/\/ MessageRegistryByLanguage gets a specific message registry by language.\n\/\/ registry is used to identify the correct Message Registry file and it shall\n\/\/ contain the Message Registry name and it major and minor versions, as defined\n\/\/ by the Redfish Specification, for example: \"Alert.1.0.0\".\n\/\/ language is the RFC5646-conformant language code for the message registry, for example: \"en\".\nfunc (serviceroot *Service) MessageRegistryByLanguage(registry string, language string) (*redfish.MessageRegistry, error) {\n\treturn redfish.GetMessageRegistryByLanguage(serviceroot.Client, serviceroot.registries, registry, language)\n}\n\n\/\/ MessageByLanguage tries to find and get the message in the correct language from the informed messageID.\n\/\/ messageID is the key used to find the registry, version and message, for example: \"Alert.1.0.LanDisconnect\"\n\/\/  - The segment before the 1st period is the Registry Name (Registry Prefix): Alert\n\/\/  - The segment between the 1st and 2nd period is the major version: 1\n\/\/  - The segment between the 2nd and 3rd period is the minor version: 0\n\/\/  - The segment after the 3rd period is the Message Identifier in the Registry: LanDisconnect\n\/\/ language is the RFC5646-conformant language code for the message registry, for example: \"en\".\nfunc (serviceroot *Service) MessageByLanguage(messageID string, language string) (*redfish.MessageRegistryMessage, error) {\n\treturn redfish.GetMessageFromMessageRegistryByLanguage(serviceroot.Client, serviceroot.registries, messageID, language)\n}\n\n\/\/ Systems get the system instances from the service\nfunc (serviceroot *Service) Systems() ([]*redfish.ComputerSystem, error) {\n\treturn redfish.ListReferencedComputerSystems(serviceroot.Client, serviceroot.systems)\n}\n\n\/\/ CompositionService gets the composition service instance\nfunc (serviceroot *Service) CompositionService() (*redfish.CompositionService, error) {\n\treturn redfish.GetCompositionService(serviceroot.Client, serviceroot.compositionService)\n}\n\n\/\/ UpdateService gets the update service instance\nfunc (serviceroot *Service) UpdateService() (*redfish.UpdateService, error) {\n\treturn redfish.GetUpdateService(serviceroot.Client, serviceroot.updateService)\n}\n<commit_msg>The search for the Redfish message registry by registry\/language can be very slow depending on the environment (existing number of registries \/ size of the registries). Created new function to get the MessageRegistry directly from the uri avoiding doing unecessary searches to find it.<commit_after>\/\/\n\/\/ SPDX-License-Identifier: BSD-3-Clause\n\/\/\n\npackage gofish\n\nimport (\n\t\"encoding\/json\"\n\n\t\"github.com\/stmcginnis\/gofish\/common\"\n\t\"github.com\/stmcginnis\/gofish\/redfish\"\n\t\"github.com\/stmcginnis\/gofish\/swordfish\"\n)\n\n\/\/ Expand shall contain information about the support of the $expand query\n\/\/ parameter by the service.\ntype Expand struct {\n\t\/\/ ExpandAll shall be a boolean indicating whether this service supports the\n\t\/\/ use of asterisk (expand all entries) as a value for the $expand query\n\t\/\/ parameter as described by the specification.\n\tExpandAll bool\n\t\/\/ Levels shall be a boolean indicating whether this service supports the\n\t\/\/ use of $levels as a value for the $expand query parameter as described by\n\t\/\/ the specification.\n\tLevels bool\n\t\/\/ Links shall be a boolean indicating whether this service supports the use\n\t\/\/ of tilde (expand only entries in the Links section) as a value for the\n\t\/\/ $expand query parameter as described by the specification.\n\tLinks bool\n\t\/\/ MaxLevels shall be the maximum value of the $levels qualifier supported\n\t\/\/ by the service and shall only be included if the value of the Levels\n\t\/\/ property is true.\n\tMaxLevels int\n\t\/\/ NoLinks shall be a boolean indicating whether this service supports the\n\t\/\/ use of period (expand only entries not in the Links section) as a value\n\t\/\/ for the $expand query parameter as described by the specification.\n\tNoLinks bool\n}\n\n\/\/ ProtocolFeaturesSupported contains information about protocol features\n\/\/ supported by the service.\ntype ProtocolFeaturesSupported struct {\n\t\/\/ ExcerptQuery shall be a boolean indicating whether this service supports\n\t\/\/ the use of the 'excerpt' query parameter as described by the\n\t\/\/ specification.\n\tExcerptQuery bool\n\t\/\/ ExpandQuery shall contain information about the support of the $expand\n\t\/\/ query parameter by the service.\n\tExpandQuery Expand\n\t\/\/ FilterQuery shall be a boolean indicating whether this service supports\n\t\/\/ the use of the $filter query parameter as described by the specification.\n\tFilterQuery bool\n\t\/\/ OnlyMemberQuery shall be a boolean indicating whether this service\n\t\/\/ supports the use of the 'only' query parameter as described by the\n\t\/\/ specification.\n\tOnlyMemberQuery bool\n\t\/\/ SelectQuery shall be a boolean indicating whether this service supports\n\t\/\/ the use of the $select query parameter as described by the specification.\n\tSelectQuery bool\n}\n\n\/\/ Service represents the root Redfish service. All values for resources\n\/\/ described by this schema shall comply to the requirements as described in the\n\/\/ Redfish specification.\ntype Service struct {\n\tcommon.Entity\n\n\t\/\/ ODataContext is the odata context.\n\tODataContext string `json:\"@odata.context\"`\n\t\/\/ ODataID is the odata identifier.\n\tODataID string `json:\"@odata.id\"`\n\t\/\/ ODataType is the odata type.\n\tODataType string `json:\"@odata.type\"`\n\t\/\/ AccountService shall only contain a reference to a resource that complies\n\t\/\/ to the AccountService schema.\n\taccountService string\n\t\/\/ CertificateService shall be a link to the CertificateService.\n\tcertificateService string\n\t\/\/ Chassis shall only contain a reference to a collection of resources that\n\t\/\/ comply to the Chassis schema.\n\tchassis string\n\t\/\/ CompositionService shall only contain a reference to a resource that\n\t\/\/ complies to the CompositionService schema.\n\tcompositionService string\n\t\/\/ Description provides a description of this resource.\n\tDescription string\n\t\/\/ EventService shall only contain a reference to a resource that complies\n\t\/\/ to the EventService schema.\n\teventService string\n\t\/\/ Fabrics shall contain references to all Fabric instances.\n\tfabrics string\n\t\/\/ JobService shall only contain a reference to a resource that conforms to\n\t\/\/ the JobService schema.\n\tjobService string\n\t\/\/ JsonSchemas shall only contain a reference to a collection of resources\n\t\/\/ that comply to the SchemaFile schema where the files are Json-Schema\n\t\/\/ files.\n\tjsonSchemas string\n\t\/\/ Managers shall only contain a reference to a collection of resources that\n\t\/\/ comply to the Managers schema.\n\tmanagers string\n\t\/\/ Product shall include the name of the product represented by this Redfish\n\t\/\/ service.\n\tProduct string\n\t\/\/ ProtocolFeaturesSupported contains information about protocol features\n\t\/\/ supported by the service.\n\tProtocolFeaturesSupported ProtocolFeaturesSupported\n\t\/\/ RedfishVersion shall represent the version of the Redfish service. The\n\t\/\/ format of this string shall be of the format\n\t\/\/ majorversion.minorversion.errata in compliance with Protocol Version\n\t\/\/ section of the Redfish specification.\n\tRedfishVersion string\n\t\/\/ Registries shall contain a reference to Message Registry.\n\tregistries string\n\t\/\/ ResourceBlocks shall contain references to all Resource Block instances.\n\tresourceBlocks string\n\t\/\/ SessionService shall only contain a reference to a resource that complies\n\t\/\/ to the SessionService schema.\n\tsessionService string\n\t\/\/ StorageServices shall contain references to all StorageService instances.\n\tstorageServices string\n\t\/\/ StorageSystems shall contain computer systems that act as storage\n\t\/\/ servers. The HostingRoles attribute of each such computer system shall\n\t\/\/ have an entry for StorageServer.\n\tstorageSystems string\n\t\/\/ Systems shall only contain a reference to a collection of resources that\n\t\/\/ comply to the Systems schema.\n\tsystems string\n\t\/\/ Tasks shall only contain a reference to a resource that complies to the\n\t\/\/ TaskService schema.\n\ttasks string\n\t\/\/ TelemetryService shall be a link to the TelemetryService.\n\ttelemetryService string\n\t\/\/ UUID shall be an exact match of the UUID value returned in a 200OK from\n\t\/\/ an SSDP M-SEARCH request during discovery. RFC4122 describes methods that\n\t\/\/ can be used to create a UUID value. The value should be considered to be\n\t\/\/ opaque. Client software should only treat the overall value as a\n\t\/\/ universally unique identifier and should not interpret any sub-fields\n\t\/\/ within the UUID.\n\tUUID string\n\t\/\/ UpdateService shall only contain a reference to a resource that complies\n\t\/\/ to the UpdateService schema.\n\tupdateService string\n\t\/\/ Vendor shall include the name of the manufacturer or vendor represented\n\t\/\/ by this Redfish service. If this property is supported, the vendor name\n\t\/\/ shall not be included in the value of the Product property.\n\tVendor string\n\t\/\/ Sessions shall contain the link to a collection of Sessions.\n\tsessions string\n}\n\n\/\/ UnmarshalJSON unmarshals a Service object from the raw JSON.\nfunc (serviceroot *Service) UnmarshalJSON(b []byte) error {\n\ttype temp Service\n\tvar t struct {\n\t\ttemp\n\t\tCertificateService common.Link\n\t\tChassis            common.Link\n\t\tManagers           common.Link\n\t\tTasks              common.Link\n\t\tStorageServices    common.Link\n\t\tStorageSystems     common.Link\n\t\tAccountService     common.Link\n\t\tEventService       common.Link\n\t\tRegistries         common.Link\n\t\tSystems            common.Link\n\t\tCompositionService common.Link\n\t\tFabrics            common.Link\n\t\tJobService         common.Link\n\t\tJSONSchemas        common.Link `json:\"JsonSchemas\"`\n\t\tResourceBlocks     common.Link\n\t\tSessionService     common.Link\n\t\tTelemetryService   common.Link\n\t\tUpdateService      common.Link\n\t\tLinks              struct {\n\t\t\tSessions common.Link\n\t\t}\n\t}\n\n\terr := json.Unmarshal(b, &t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Extract the links to other entities for later\n\t*serviceroot = Service(t.temp)\n\tserviceroot.certificateService = string(t.CertificateService)\n\tserviceroot.chassis = string(t.Chassis)\n\tserviceroot.managers = string(t.Managers)\n\tserviceroot.tasks = string(t.Tasks)\n\tserviceroot.sessions = string(t.Links.Sessions)\n\tserviceroot.storageServices = string(t.StorageServices)\n\tserviceroot.storageSystems = string(t.StorageSystems)\n\tserviceroot.accountService = string(t.AccountService)\n\tserviceroot.eventService = string(t.EventService)\n\tserviceroot.registries = string(t.Registries)\n\tserviceroot.systems = string(t.Systems)\n\tserviceroot.compositionService = string(t.CompositionService)\n\tserviceroot.fabrics = string(t.Fabrics)\n\tserviceroot.jobService = string(t.JobService)\n\tserviceroot.jsonSchemas = string(t.JSONSchemas)\n\tserviceroot.resourceBlocks = string(t.ResourceBlocks)\n\tserviceroot.sessionService = string(t.SessionService)\n\tserviceroot.telemetryService = string(t.TelemetryService)\n\tserviceroot.updateService = string(t.UpdateService)\n\n\treturn nil\n}\n\n\/\/ ServiceRoot will get a Service instance from the service.\nfunc ServiceRoot(c common.Client) (*Service, error) {\n\tresp, err := c.Get(common.DefaultServiceRoot)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar serviceroot Service\n\terr = json.NewDecoder(resp.Body).Decode(&serviceroot)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tserviceroot.SetClient(c)\n\treturn &serviceroot, nil\n}\n\n\/\/ Chassis gets the chassis instances managed by this service.\nfunc (serviceroot *Service) Chassis() ([]*redfish.Chassis, error) {\n\treturn redfish.ListReferencedChassis(serviceroot.Client, serviceroot.chassis)\n}\n\n\/\/ Managers gets the manager instances of this service.\nfunc (serviceroot *Service) Managers() ([]*redfish.Manager, error) {\n\treturn redfish.ListReferencedManagers(serviceroot.Client, serviceroot.managers)\n}\n\n\/\/ StorageSystems gets the storage system instances managed by this service.\nfunc (serviceroot *Service) StorageSystems() ([]*swordfish.StorageSystem, error) {\n\treturn swordfish.ListReferencedStorageSystems(serviceroot.Client, serviceroot.storageSystems)\n}\n\n\/\/ StorageServices gets the Swordfish storage services\nfunc (serviceroot *Service) StorageServices() ([]*swordfish.StorageService, error) {\n\treturn swordfish.ListReferencedStorageServices(serviceroot.Client, serviceroot.storageServices)\n}\n\n\/\/ Tasks gets the system's tasks\nfunc (serviceroot *Service) Tasks() ([]*redfish.Task, error) {\n\treturn redfish.ListReferencedTasks(serviceroot.Client, serviceroot.tasks)\n}\n\n\/\/ CreateSession creates a new session and returns the token and id\nfunc (serviceroot *Service) CreateSession(username string, password string) (*redfish.AuthToken, error) {\n\treturn redfish.CreateSession(serviceroot.Client, serviceroot.sessions, username, password)\n}\n\n\/\/ Sessions gets the system's active sessions\nfunc (serviceroot *Service) Sessions() ([]*redfish.Session, error) {\n\treturn redfish.ListReferencedSessions(serviceroot.Client, serviceroot.sessions)\n}\n\n\/\/ DeleteSession logout the specified session\nfunc (serviceroot *Service) DeleteSession(url string) error {\n\treturn redfish.DeleteSession(serviceroot.Client, url)\n}\n\n\/\/ AccountService gets the Redfish AccountService\nfunc (serviceroot *Service) AccountService() (*redfish.AccountService, error) {\n\treturn redfish.GetAccountService(serviceroot.Client, serviceroot.accountService)\n}\n\n\/\/ EventService gets the Redfish EventService\nfunc (serviceroot *Service) EventService() (*redfish.EventService, error) {\n\treturn redfish.GetEventService(serviceroot.Client, serviceroot.eventService)\n}\n\n\/\/ Registries gets the Redfish Registries\nfunc (serviceroot *Service) Registries() ([]*redfish.MessageRegistryFile, error) {\n\treturn redfish.ListReferencedMessageRegistryFiles(serviceroot.Client, serviceroot.registries)\n}\n\n\/\/ MessageRegistries gets all the available message registries in all languages\nfunc (serviceroot *Service) MessageRegistries() ([]*redfish.MessageRegistry, error) {\n\treturn redfish.ListReferencedMessageRegistries(serviceroot.Client, serviceroot.registries)\n}\n\n\/\/ MessageRegistry gets a specific message registry.\n\/\/ uri is the uri for the message registry\nfunc (serviceroot *Service) MessageRegistry(uri string) (*redfish.MessageRegistry, error) {\n\treturn redfish.GetMessageRegistry(serviceroot.Client, uri)\n}\n\n\/\/ MessageRegistriesByLanguage gets the message registries by language.\n\/\/ language is the RFC5646-conformant language code for the message registry, for example: \"en\".\nfunc (serviceroot *Service) MessageRegistriesByLanguage(language string) ([]*redfish.MessageRegistry, error) {\n\treturn redfish.ListReferencedMessageRegistriesByLanguage(serviceroot.Client, serviceroot.registries, language)\n}\n\n\/\/ MessageRegistryByLanguage gets a specific message registry by language.\n\/\/ registry is used to identify the correct Message Registry file and it shall\n\/\/ contain the Message Registry name and it major and minor versions, as defined\n\/\/ by the Redfish Specification, for example: \"Alert.1.0.0\".\n\/\/ language is the RFC5646-conformant language code for the message registry, for example: \"en\".\nfunc (serviceroot *Service) MessageRegistryByLanguage(registry string, language string) (*redfish.MessageRegistry, error) {\n\treturn redfish.GetMessageRegistryByLanguage(serviceroot.Client, serviceroot.registries, registry, language)\n}\n\n\/\/ MessageByLanguage tries to find and get the message in the correct language from the informed messageID.\n\/\/ messageID is the key used to find the registry, version and message, for example: \"Alert.1.0.LanDisconnect\"\n\/\/  - The segment before the 1st period is the Registry Name (Registry Prefix): Alert\n\/\/  - The segment between the 1st and 2nd period is the major version: 1\n\/\/  - The segment between the 2nd and 3rd period is the minor version: 0\n\/\/  - The segment after the 3rd period is the Message Identifier in the Registry: LanDisconnect\n\/\/ language is the RFC5646-conformant language code for the message registry, for example: \"en\".\nfunc (serviceroot *Service) MessageByLanguage(messageID string, language string) (*redfish.MessageRegistryMessage, error) {\n\treturn redfish.GetMessageFromMessageRegistryByLanguage(serviceroot.Client, serviceroot.registries, messageID, language)\n}\n\n\/\/ Systems get the system instances from the service\nfunc (serviceroot *Service) Systems() ([]*redfish.ComputerSystem, error) {\n\treturn redfish.ListReferencedComputerSystems(serviceroot.Client, serviceroot.systems)\n}\n\n\/\/ CompositionService gets the composition service instance\nfunc (serviceroot *Service) CompositionService() (*redfish.CompositionService, error) {\n\treturn redfish.GetCompositionService(serviceroot.Client, serviceroot.compositionService)\n}\n\n\/\/ UpdateService gets the update service instance\nfunc (serviceroot *Service) UpdateService() (*redfish.UpdateService, error) {\n\treturn redfish.GetUpdateService(serviceroot.Client, serviceroot.updateService)\n}\n<|endoftext|>"}
{"text":"<commit_before>package simplebp\n\nimport (\n\t\"github.com\/google\/blueprint\"\n\t\"github.com\/google\/blueprint\/pathtools\"\n\n\t\"bytes\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"text\/template\"\n)\n\nvar (\n\tscriptRule = pctx.StaticRule(\"script\",\n\t\tblueprint.RuleParams{\n\t\t\tCommand:     \"$script $args\",\n\t\t\tDescription: \"RUN $script\",\n\t\t},\n\t\t\"script\", \"args\")\n)\n\ntype ScriptModule struct {\n\tproperties struct {\n\t\tScript string\n\t\tInputs []string\n\t\tOutput string\n\t\tArgs   string\n\t}\n}\n\nfunc NewScript() (blueprint.Module, []interface{}) {\n\tmodule := new(ScriptModule)\n\tproperties := &module.properties\n\treturn module, []interface{}{properties}\n}\n\ntype scriptInput struct {\n\tName      string\n\tBasename  string\n\tExtension string\n}\n\ntype scriptArgs struct {\n\tInput  scriptInput\n\tOutput string\n}\n\nfunc (m *ScriptModule) GenerateBuildActions(ctx blueprint.ModuleContext) {\n\tconfig := ctx.Config().(*config)\n\n\tvar scriptPath string\n\tif s := m.properties.Script; strings.HasPrefix(s, \"\/\/\") {\n\t\tscriptPath = filepath.Join(config.srcDir, s[2:])\n\t} else {\n\t\tscriptPath = filepath.Join(ctx.ModuleDir(), s)\n\t}\n\n\tif stat, err := os.Stat(scriptPath); err != nil {\n\t\tctx.ModuleErrorf(\"Could not stat %v: %v\", scriptPath, err)\n\t\treturn\n\t} else if stat.Mode()&0111 == 0 {\n\t\tctx.ModuleErrorf(\"%s is not an executable\", scriptPath)\n\t\treturn\n\t}\n\n\tsrcs := pathtools.PrefixPaths(m.properties.Inputs, ctx.ModuleDir())\n\n\targsTmpl, argsErr := template.New(\"args\").Parse(m.properties.Args)\n\tif argsErr != nil {\n\t\tctx.ModuleErrorf(\"Could not parse script args: %v\", argsErr)\n\t\treturn\n\t}\n\toutTmpl, outErr := template.New(\"out\").Parse(m.properties.Output)\n\tif outErr != nil {\n\t\tctx.ModuleErrorf(\"Could not parse output template: %v\", outErr)\n\t\treturn\n\t}\n\n\tfor _, s := range srcs {\n\t\targs := &scriptArgs{\n\t\t\tInput: scriptInput{\n\t\t\t\tName:      s,\n\t\t\t\tBasename:  strings.TrimSuffix(s, filepath.Ext(s)),\n\t\t\t\tExtension: filepath.Ext(s),\n\t\t\t},\n\t\t}\n\n\t\toutBuf := &bytes.Buffer{}\n\t\tif err := outTmpl.Execute(outBuf, args); err != nil {\n\t\t\tctx.ModuleErrorf(\"Could not generate output: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\targs.Output = filepath.Join(config.buildDir, outBuf.String())\n\t\targsBuf := &bytes.Buffer{}\n\t\tif err := argsTmpl.Execute(argsBuf, args); err != nil {\n\t\t\tctx.ModuleErrorf(\"Could not generate args: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tctx.Build(pctx, blueprint.BuildParams{\n\t\t\tRule:    scriptRule,\n\t\t\tInputs:  []string{s},\n\t\t\tOutputs: []string{args.Output},\n                        Implicits: []string{scriptPath},\n\t\t\tArgs: map[string]string{\n\t\t\t\t\"script\": scriptPath,\n\t\t\t\t\"args\":   argsBuf.String(),\n\t\t\t},\n\t\t})\n\t}\n}\n<commit_msg>run gofmt<commit_after>package simplebp\n\nimport (\n\t\"github.com\/google\/blueprint\"\n\t\"github.com\/google\/blueprint\/pathtools\"\n\n\t\"bytes\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"text\/template\"\n)\n\nvar (\n\tscriptRule = pctx.StaticRule(\"script\",\n\t\tblueprint.RuleParams{\n\t\t\tCommand:     \"$script $args\",\n\t\t\tDescription: \"RUN $script\",\n\t\t},\n\t\t\"script\", \"args\")\n)\n\ntype ScriptModule struct {\n\tproperties struct {\n\t\tScript string\n\t\tInputs []string\n\t\tOutput string\n\t\tArgs   string\n\t}\n}\n\nfunc NewScript() (blueprint.Module, []interface{}) {\n\tmodule := new(ScriptModule)\n\tproperties := &module.properties\n\treturn module, []interface{}{properties}\n}\n\ntype scriptInput struct {\n\tName      string\n\tBasename  string\n\tExtension string\n}\n\ntype scriptArgs struct {\n\tInput  scriptInput\n\tOutput string\n}\n\nfunc (m *ScriptModule) GenerateBuildActions(ctx blueprint.ModuleContext) {\n\tconfig := ctx.Config().(*config)\n\n\tvar scriptPath string\n\tif s := m.properties.Script; strings.HasPrefix(s, \"\/\/\") {\n\t\tscriptPath = filepath.Join(config.srcDir, s[2:])\n\t} else {\n\t\tscriptPath = filepath.Join(ctx.ModuleDir(), s)\n\t}\n\n\tif stat, err := os.Stat(scriptPath); err != nil {\n\t\tctx.ModuleErrorf(\"Could not stat %v: %v\", scriptPath, err)\n\t\treturn\n\t} else if stat.Mode()&0111 == 0 {\n\t\tctx.ModuleErrorf(\"%s is not an executable\", scriptPath)\n\t\treturn\n\t}\n\n\tsrcs := pathtools.PrefixPaths(m.properties.Inputs, ctx.ModuleDir())\n\n\targsTmpl, argsErr := template.New(\"args\").Parse(m.properties.Args)\n\tif argsErr != nil {\n\t\tctx.ModuleErrorf(\"Could not parse script args: %v\", argsErr)\n\t\treturn\n\t}\n\toutTmpl, outErr := template.New(\"out\").Parse(m.properties.Output)\n\tif outErr != nil {\n\t\tctx.ModuleErrorf(\"Could not parse output template: %v\", outErr)\n\t\treturn\n\t}\n\n\tfor _, s := range srcs {\n\t\targs := &scriptArgs{\n\t\t\tInput: scriptInput{\n\t\t\t\tName:      s,\n\t\t\t\tBasename:  strings.TrimSuffix(s, filepath.Ext(s)),\n\t\t\t\tExtension: filepath.Ext(s),\n\t\t\t},\n\t\t}\n\n\t\toutBuf := &bytes.Buffer{}\n\t\tif err := outTmpl.Execute(outBuf, args); err != nil {\n\t\t\tctx.ModuleErrorf(\"Could not generate output: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\targs.Output = filepath.Join(config.buildDir, outBuf.String())\n\t\targsBuf := &bytes.Buffer{}\n\t\tif err := argsTmpl.Execute(argsBuf, args); err != nil {\n\t\t\tctx.ModuleErrorf(\"Could not generate args: %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tctx.Build(pctx, blueprint.BuildParams{\n\t\t\tRule:      scriptRule,\n\t\t\tInputs:    []string{s},\n\t\t\tOutputs:   []string{args.Output},\n\t\t\tImplicits: []string{scriptPath},\n\t\t\tArgs: map[string]string{\n\t\t\t\t\"script\": scriptPath,\n\t\t\t\t\"args\":   argsBuf.String(),\n\t\t\t},\n\t\t})\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package images\n\nimport(\n  \"io\"\n  \"io\/ioutil\"\n  \"encoding\/json\"\n  \"github.com\/ricallinson\/forgery\"\n  \"github.com\/spacedock-io\/registry\/db\"\n  \"github.com\/spacedock-io\/registry\/models\"\n  \"github.com\/spacedock-io\/registry\/cloudfiles\"\n)\n\nfunc GetJson(req *f.Request, res *f.Response) {\n  var image models.Image\n  q := db.DB.Where(&models.Image{Uuid: req.Params[\"id\"]}).First(&image)\n  if q.Error != nil {\n    res.Send(404)\n    return\n  }\n\n  res.Set(\"X-Docker-Size\", string(image.Size))\n  res.Set(\"X-Docker-Checksum\", image.Checksum)\n\n  res.Send(image.Json)\n}\n\nfunc PutJson(req *f.Request, res *f.Response) {\n  var image models.Image\n  var err error\n\n  q := db.DB.Where(&models.Image{Uuid: req.Params[\"id\"]}).First(&image)\n  if !q.RecordNotFound() && q.Error != nil {\n    res.Send(404)\n    return\n  }\n\n  image.Json, err = ioutil.ReadAll(req.Request.Request.Body)\n\n  if err == nil {\n    db.DB.Save(&image)\n  } else {\n    res.Send(500)\n  }\n}\n\nfunc GetLayer(req *f.Request, res *f.Response) {\n  _, err := cloudfiles.Cloudfiles.ObjectGet(\n    \"default\", req.Params[\"id\"], res.Response.Writer, true, nil)\n  if err == nil {\n    res.Send(200)\n  } else { res.Send(500) }\n}\n\nfunc PutLayer(req *f.Request, res *f.Response) {\n  obj, err := cloudfiles.Cloudfiles.ObjectCreate(\n    \"default\", req.Params[\"id\"], true, \"\", \"\", nil)\n  if err == nil {\n    io.Copy(obj, req.Request.Request.Body)\n    res.Send(200)\n  } else { res.Send(500) }\n}\n\nfunc GetAncestry(req *f.Request, res *f.Response) {\n  var image models.Image\n  q := db.DB.First(&models.Image{Uuid: req.Params[\"id\"]}).First(&image)\n  if q.Error != nil {\n    res.Send(404)\n    return\n  }\n\n  data, err := json.Marshal(image.Ancestry)\n\n  if err == nil {\n    res.Send(data)\n  } else { res.Send(500) }\n}\n<commit_msg>Let's see what the query is returning<commit_after>package images\n\nimport(\n  \"fmt\"\n  \"io\"\n  \"io\/ioutil\"\n  \"encoding\/json\"\n  \"github.com\/ricallinson\/forgery\"\n  \"github.com\/spacedock-io\/registry\/db\"\n  \"github.com\/spacedock-io\/registry\/models\"\n  \"github.com\/spacedock-io\/registry\/cloudfiles\"\n)\n\nfunc GetJson(req *f.Request, res *f.Response) {\n  var image models.Image\n  q := db.DB.Where(&models.Image{Uuid: req.Params[\"id\"]}).First(&image)\n  if q.Error != nil {\n    res.Send(404)\n    return\n  }\n\n  res.Set(\"X-Docker-Size\", string(image.Size))\n  res.Set(\"X-Docker-Checksum\", image.Checksum)\n\n  res.Send(image.Json)\n}\n\nfunc PutJson(req *f.Request, res *f.Response) {\n  var image models.Image\n  var err error\n\n  q := db.DB.Where(&models.Image{Uuid: req.Params[\"id\"]}).First(&image)\n  fmt.Printf(\"q: %+v\\n\", q)\n  if !q.RecordNotFound() && q.Error != nil {\n    res.Send(404)\n    return\n  }\n\n  image.Json, err = ioutil.ReadAll(req.Request.Request.Body)\n\n  if err == nil {\n    db.DB.Save(&image)\n  } else {\n    res.Send(500)\n  }\n}\n\nfunc GetLayer(req *f.Request, res *f.Response) {\n  _, err := cloudfiles.Cloudfiles.ObjectGet(\n    \"default\", req.Params[\"id\"], res.Response.Writer, true, nil)\n  if err == nil {\n    res.Send(200)\n  } else { res.Send(500) }\n}\n\nfunc PutLayer(req *f.Request, res *f.Response) {\n  obj, err := cloudfiles.Cloudfiles.ObjectCreate(\n    \"default\", req.Params[\"id\"], true, \"\", \"\", nil)\n  if err == nil {\n    io.Copy(obj, req.Request.Request.Body)\n    res.Send(200)\n  } else { res.Send(500) }\n}\n\nfunc GetAncestry(req *f.Request, res *f.Response) {\n  var image models.Image\n  q := db.DB.First(&models.Image{Uuid: req.Params[\"id\"]}).First(&image)\n  if q.Error != nil {\n    res.Send(404)\n    return\n  }\n\n  data, err := json.Marshal(image.Ancestry)\n\n  if err == nil {\n    res.Send(data)\n  } else { res.Send(500) }\n}\n<|endoftext|>"}
{"text":"<commit_before>package memory\n\nfunc createTestCache() *MemoryCache {\n\treturn New(20 * 1024 * 1024)\n}\n<commit_msg>add tests for MemoryCache<commit_after>package memory\n\nimport (\n\t\"github.com\/pierrre\/imageserver\/cache\/cachetest\"\n\t\"testing\"\n)\n\nfunc TestGetSet(t *testing.T) {\n\tcache := createTestCache()\n\n\tcachetest.CacheTestGetSetAllImages(t, cache)\n}\n\nfunc TestGetErrorMiss(t *testing.T) {\n\tcache := createTestCache()\n\n\tcachetest.CacheTestGetErrorMiss(t, cache)\n}\n\nfunc createTestCache() *MemoryCache {\n\treturn New(20 * 1024 * 1024)\n}\n<|endoftext|>"}
{"text":"<commit_before>package parse\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestStandardAddress(t *testing.T) {\n\tfor i, test := range []struct {\n\t\tinput      string\n\t\thost, port string\n\t\tshouldErr  bool\n\t}{\n\t\t{`localhost`, \"localhost\", \"\", false},\n\t\t{`localhost:1234`, \"localhost\", \"1234\", false},\n\t\t{`localhost:`, \"localhost\", \"\", false},\n\t\t{`0.0.0.0`, \"0.0.0.0\", \"\", false},\n\t\t{`127.0.0.1:1234`, \"127.0.0.1\", \"1234\", false},\n\t\t{`:1234`, \"\", \"1234\", false},\n\t\t{`[::1]`, \"::1\", \"\", false},\n\t\t{`[::1]:1234`, \"::1\", \"1234\", false},\n\t\t{`:`, \"\", \"\", false},\n\t\t{`localhost:http`, \"localhost\", \"http\", false},\n\t\t{`localhost:https`, \"localhost\", \"https\", false},\n\t\t{`:http`, \"\", \"http\", false},\n\t\t{`:https`, \"\", \"https\", false},\n\t\t{`http:\/\/localhost`, \"localhost\", \"http\", false},\n\t\t{`https:\/\/localhost`, \"localhost\", \"https\", false},\n\t\t{`http:\/\/127.0.0.1`, \"127.0.0.1\", \"http\", false},\n\t\t{`https:\/\/127.0.0.1`, \"127.0.0.1\", \"https\", false},\n\t\t{`http:\/\/[::1]`, \"::1\", \"http\", false},\n\t\t{`http:\/\/localhost:1234`, \"localhost\", \"1234\", false},\n\t\t{`https:\/\/127.0.0.1:1234`, \"127.0.0.1\", \"1234\", false},\n\t\t{`http:\/\/[::1]:1234`, \"::1\", \"1234\", false},\n\t\t{``, \"\", \"\", false},\n\t\t{`::1`, \"::1\", \"\", true},\n\t\t{`localhost::`, \"localhost::\", \"\", true},\n\t\t{`#$%@`, \"#$%@\", \"\", true},\n\t} {\n\t\thost, port, err := standardAddress(test.input)\n\n\t\tif err != nil && !test.shouldErr {\n\t\t\tt.Errorf(\"Test %d: Expected no error, but had error: %v\", i, err)\n\t\t}\n\t\tif err == nil && test.shouldErr {\n\t\t\tt.Errorf(\"Test %d: Expected error, but had none\", i)\n\t\t}\n\n\t\tif host != test.host {\n\t\t\tt.Errorf(\"Test %d: Expected host '%s', got '%s'\", i, test.host, host)\n\t\t}\n\n\t\tif port != test.port {\n\t\t\tt.Errorf(\"Test %d: Expected port '%s', got '%s'\", i, test.port, port)\n\t\t}\n\t}\n}\n\nfunc TestParseOneAndImport(t *testing.T) {\n\tsetupParseTests()\n\n\ttestParseOne := func(input string) (serverBlock, error) {\n\t\tp := testParser(input)\n\t\tp.Next() \/\/ parseOne doesn't call Next() to start, so we must\n\t\terr := p.parseOne()\n\t\treturn p.block, err\n\t}\n\n\tfor i, test := range []struct {\n\t\tinput     string\n\t\tshouldErr bool\n\t\taddresses []address\n\t\ttokens    map[string]int \/\/ map of directive name to number of tokens expected\n\t}{\n\t\t{`localhost`, false, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{}},\n\n\t\t{`localhost\n\t\t  dir1`, false, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 1,\n\t\t}},\n\n\t\t{`localhost:1234\n\t\t  dir1 foo bar`, false, []address{\n\t\t\t{\"localhost\", \"1234\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`localhost {\n\t\t    dir1\n\t\t  }`, false, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 1,\n\t\t}},\n\n\t\t{`localhost:1234 {\n\t\t    dir1 foo bar\n\t\t    dir2\n\t\t  }`, false, []address{\n\t\t\t{\"localhost\", \"1234\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t\t\"dir2\": 1,\n\t\t}},\n\n\t\t{`http:\/\/localhost https:\/\/localhost\n\t\t  dir1 foo bar`, false, []address{\n\t\t\t{\"localhost\", \"http\"},\n\t\t\t{\"localhost\", \"https\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`http:\/\/localhost https:\/\/localhost {\n\t\t    dir1 foo bar\n\t\t  }`, false, []address{\n\t\t\t{\"localhost\", \"http\"},\n\t\t\t{\"localhost\", \"https\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`http:\/\/localhost, https:\/\/localhost {\n\t\t    dir1 foo bar\n\t\t  }`, false, []address{\n\t\t\t{\"localhost\", \"http\"},\n\t\t\t{\"localhost\", \"https\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`http:\/\/localhost, {\n\t\t  }`, true, []address{\n\t\t\t{\"localhost\", \"http\"},\n\t\t}, map[string]int{}},\n\n\t\t{`host1:80, http:\/\/host2.com\n\t\t  dir1 foo bar\n\t\t  dir2 baz`, false, []address{\n\t\t\t{\"host1\", \"80\"},\n\t\t\t{\"host2.com\", \"http\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t\t\"dir2\": 2,\n\t\t}},\n\n\t\t{`http:\/\/host1.com,\n\t\t  http:\/\/host2.com,\n\t\t  https:\/\/host3.com`, false, []address{\n\t\t\t{\"host1.com\", \"http\"},\n\t\t\t{\"host2.com\", \"http\"},\n\t\t\t{\"host3.com\", \"https\"},\n\t\t}, map[string]int{}},\n\n\t\t{`http:\/\/host1.com:1234, https:\/\/host2.com\n\t\t  dir1 foo {\n\t\t    bar baz\n\t\t  }\n\t\t  dir2`, false, []address{\n\t\t\t{\"host1.com\", \"1234\"},\n\t\t\t{\"host2.com\", \"https\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 6,\n\t\t\t\"dir2\": 1,\n\t\t}},\n\n\t\t{`127.0.0.1\n\t\t  dir1 {\n\t\t    bar baz\n\t\t  }\n\t\t  dir2 {\n\t\t    foo bar\n\t\t  }`, false, []address{\n\t\t\t{\"127.0.0.1\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 5,\n\t\t\t\"dir2\": 5,\n\t\t}},\n\n\t\t{`127.0.0.1\n\t\t  unknown_directive`, true, []address{\n\t\t\t{\"127.0.0.1\", \"\"},\n\t\t}, map[string]int{}},\n\n\t\t{`localhost\n\t\t  dir1 {\n\t\t    foo`, true, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`localhost\n\t\t  dir1 {\n\t\t  }`, false, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`localhost\n\t\t  dir1 {\n\t\t  } }`, true, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`localhost\n\t\t  dir1 {\n\t\t    nested {\n\t\t      foo\n\t\t    }\n\t\t  }\n\t\t  dir2 foo bar`, false, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 7,\n\t\t\t\"dir2\": 3,\n\t\t}},\n\n\t\t{``, false, []address{}, map[string]int{}},\n\n\t\t{`localhost\n\t\t  dir1 arg1\n\t\t  import import_test1.txt`, false, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 2,\n\t\t\t\"dir2\": 3,\n\t\t\t\"dir3\": 1,\n\t\t}},\n\n\t\t{`import import_test2.txt`, false, []address{\n\t\t\t{\"host1\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 1,\n\t\t\t\"dir2\": 2,\n\t\t}},\n\n\t\t{`import import_test1.txt import_test2.txt`, true, []address{}, map[string]int{}},\n\n\t\t{`import not_found.txt`, true, []address{}, map[string]int{}},\n\n\t\t{`\"\"`, false, []address{}, map[string]int{}},\n\n\t\t{``, false, []address{}, map[string]int{}},\n\t} {\n\t\tresult, err := testParseOne(test.input)\n\n\t\tif test.shouldErr && err == nil {\n\t\t\tt.Errorf(\"Test %d: Expected an error, but didn't get one\", i)\n\t\t}\n\t\tif !test.shouldErr && err != nil {\n\t\t\tt.Errorf(\"Test %d: Expected no error, but got: %v\", i, err)\n\t\t}\n\n\t\tif len(result.Addresses) != len(test.addresses) {\n\t\t\tt.Errorf(\"Test %d: Expected %d addresses, got %d\",\n\t\t\t\ti, len(test.addresses), len(result.Addresses))\n\t\t\tcontinue\n\t\t}\n\t\tfor j, addr := range result.Addresses {\n\t\t\tif addr.Host != test.addresses[j].Host {\n\t\t\t\tt.Errorf(\"Test %d, address %d: Expected host to be '%s', but was '%s'\",\n\t\t\t\t\ti, j, test.addresses[j].Host, addr.Host)\n\t\t\t}\n\t\t\tif addr.Port != test.addresses[j].Port {\n\t\t\t\tt.Errorf(\"Test %d, address %d: Expected port to be '%s', but was '%s'\",\n\t\t\t\t\ti, j, test.addresses[j].Port, addr.Port)\n\t\t\t}\n\t\t}\n\n\t\tif len(result.Tokens) != len(test.tokens) {\n\t\t\tt.Errorf(\"Test %d: Expected %d directives, had %d\",\n\t\t\t\ti, len(test.tokens), len(result.Tokens))\n\t\t\tcontinue\n\t\t}\n\t\tfor directive, tokens := range result.Tokens {\n\t\t\tif len(tokens) != test.tokens[directive] {\n\t\t\t\tt.Errorf(\"Test %d, directive '%s': Expected %d tokens, counted %d\",\n\t\t\t\t\ti, directive, test.tokens[directive], len(tokens))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestParseAll(t *testing.T) {\n\tsetupParseTests()\n\n\tfor i, test := range []struct {\n\t\tinput     string\n\t\tshouldErr bool\n\t\taddresses [][]address \/\/ addresses per server block, in order\n\t}{\n\t\t{`localhost`, false, [][]address{\n\t\t\t{{\"localhost\", \"\"}},\n\t\t}},\n\n\t\t{`localhost:1234`, false, [][]address{\n\t\t\t[]address{{\"localhost\", \"1234\"}},\n\t\t}},\n\n\t\t{`localhost:1234 {\n\t\t  }\n\t\t  localhost:2015 {\n\t\t  }`, false, [][]address{\n\t\t\t[]address{{\"localhost\", \"1234\"}},\n\t\t\t[]address{{\"localhost\", \"2015\"}},\n\t\t}},\n\n\t\t{`localhost:1234, http:\/\/host2`, false, [][]address{\n\t\t\t[]address{{\"localhost\", \"1234\"}, {\"host2\", \"http\"}},\n\t\t}},\n\n\t\t{`localhost:1234, http:\/\/host2,`, true, [][]address{}},\n\n\t\t{`http:\/\/host1.com, http:\/\/host2.com {\n\t\t  }\n\t\t  https:\/\/host3.com, https:\/\/host4.com {\n\t\t  }`, false, [][]address{\n\t\t\t[]address{{\"host1.com\", \"http\"}, {\"host2.com\", \"http\"}},\n\t\t\t[]address{{\"host3.com\", \"https\"}, {\"host4.com\", \"https\"}},\n\t\t}},\n\t} {\n\t\tp := testParser(test.input)\n\t\tblocks, err := p.parseAll()\n\n\t\tif test.shouldErr && err == nil {\n\t\t\tt.Errorf(\"Test %d: Expected an error, but didn't get one\", i)\n\t\t}\n\t\tif !test.shouldErr && err != nil {\n\t\t\tt.Errorf(\"Test %d: Expected no error, but got: %v\", i, err)\n\t\t}\n\n\t\tif len(blocks) != len(test.addresses) {\n\t\t\tt.Errorf(\"Test %d: Expected %d server blocks, got %d\",\n\t\t\t\ti, len(test.addresses), len(blocks))\n\t\t\tcontinue\n\t\t}\n\t\tfor j, block := range blocks {\n\t\t\tif len(block.Addresses) != len(test.addresses[j]) {\n\t\t\t\tt.Errorf(\"Test %d: Expected %d addresses in block %d, got %d\",\n\t\t\t\t\ti, len(test.addresses[j]), j, len(block.Addresses))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor k, addr := range block.Addresses {\n\t\t\t\tif addr.Host != test.addresses[j][k].Host {\n\t\t\t\t\tt.Errorf(\"Test %d, block %d, address %d: Expected host to be '%s', but was '%s'\",\n\t\t\t\t\t\ti, j, k, test.addresses[j][k].Host, addr.Host)\n\t\t\t\t}\n\t\t\t\tif addr.Port != test.addresses[j][k].Port {\n\t\t\t\t\tt.Errorf(\"Test %d, block %d, address %d: Expected port to be '%s', but was '%s'\",\n\t\t\t\t\t\ti, j, k, test.addresses[j][k].Port, addr.Port)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc setupParseTests() {\n\t\/\/ Set up some bogus directives for testing\n\tValidDirectives = map[string]struct{}{\n\t\t\"dir1\": {},\n\t\t\"dir2\": {},\n\t\t\"dir3\": {},\n\t}\n}\n\nfunc testParser(input string) parser {\n\tbuf := strings.NewReader(input)\n\tp := parser{Dispenser: NewDispenser(\"Test\", buf), checkDirectives: true}\n\treturn p\n}\n<commit_msg>Added test for environment replacement.<commit_after>package parse\n\nimport (\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestStandardAddress(t *testing.T) {\n\tfor i, test := range []struct {\n\t\tinput      string\n\t\thost, port string\n\t\tshouldErr  bool\n\t}{\n\t\t{`localhost`, \"localhost\", \"\", false},\n\t\t{`localhost:1234`, \"localhost\", \"1234\", false},\n\t\t{`localhost:`, \"localhost\", \"\", false},\n\t\t{`0.0.0.0`, \"0.0.0.0\", \"\", false},\n\t\t{`127.0.0.1:1234`, \"127.0.0.1\", \"1234\", false},\n\t\t{`:1234`, \"\", \"1234\", false},\n\t\t{`[::1]`, \"::1\", \"\", false},\n\t\t{`[::1]:1234`, \"::1\", \"1234\", false},\n\t\t{`:`, \"\", \"\", false},\n\t\t{`localhost:http`, \"localhost\", \"http\", false},\n\t\t{`localhost:https`, \"localhost\", \"https\", false},\n\t\t{`:http`, \"\", \"http\", false},\n\t\t{`:https`, \"\", \"https\", false},\n\t\t{`http:\/\/localhost`, \"localhost\", \"http\", false},\n\t\t{`https:\/\/localhost`, \"localhost\", \"https\", false},\n\t\t{`http:\/\/127.0.0.1`, \"127.0.0.1\", \"http\", false},\n\t\t{`https:\/\/127.0.0.1`, \"127.0.0.1\", \"https\", false},\n\t\t{`http:\/\/[::1]`, \"::1\", \"http\", false},\n\t\t{`http:\/\/localhost:1234`, \"localhost\", \"1234\", false},\n\t\t{`https:\/\/127.0.0.1:1234`, \"127.0.0.1\", \"1234\", false},\n\t\t{`http:\/\/[::1]:1234`, \"::1\", \"1234\", false},\n\t\t{``, \"\", \"\", false},\n\t\t{`::1`, \"::1\", \"\", true},\n\t\t{`localhost::`, \"localhost::\", \"\", true},\n\t\t{`#$%@`, \"#$%@\", \"\", true},\n\t} {\n\t\thost, port, err := standardAddress(test.input)\n\n\t\tif err != nil && !test.shouldErr {\n\t\t\tt.Errorf(\"Test %d: Expected no error, but had error: %v\", i, err)\n\t\t}\n\t\tif err == nil && test.shouldErr {\n\t\t\tt.Errorf(\"Test %d: Expected error, but had none\", i)\n\t\t}\n\n\t\tif host != test.host {\n\t\t\tt.Errorf(\"Test %d: Expected host '%s', got '%s'\", i, test.host, host)\n\t\t}\n\n\t\tif port != test.port {\n\t\t\tt.Errorf(\"Test %d: Expected port '%s', got '%s'\", i, test.port, port)\n\t\t}\n\t}\n}\n\nfunc TestParseOneAndImport(t *testing.T) {\n\tsetupParseTests()\n\n\ttestParseOne := func(input string) (serverBlock, error) {\n\t\tp := testParser(input)\n\t\tp.Next() \/\/ parseOne doesn't call Next() to start, so we must\n\t\terr := p.parseOne()\n\t\treturn p.block, err\n\t}\n\n\tfor i, test := range []struct {\n\t\tinput     string\n\t\tshouldErr bool\n\t\taddresses []address\n\t\ttokens    map[string]int \/\/ map of directive name to number of tokens expected\n\t}{\n\t\t{`localhost`, false, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{}},\n\n\t\t{`localhost\n\t\t  dir1`, false, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 1,\n\t\t}},\n\n\t\t{`localhost:1234\n\t\t  dir1 foo bar`, false, []address{\n\t\t\t{\"localhost\", \"1234\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`localhost {\n\t\t    dir1\n\t\t  }`, false, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 1,\n\t\t}},\n\n\t\t{`localhost:1234 {\n\t\t    dir1 foo bar\n\t\t    dir2\n\t\t  }`, false, []address{\n\t\t\t{\"localhost\", \"1234\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t\t\"dir2\": 1,\n\t\t}},\n\n\t\t{`http:\/\/localhost https:\/\/localhost\n\t\t  dir1 foo bar`, false, []address{\n\t\t\t{\"localhost\", \"http\"},\n\t\t\t{\"localhost\", \"https\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`http:\/\/localhost https:\/\/localhost {\n\t\t    dir1 foo bar\n\t\t  }`, false, []address{\n\t\t\t{\"localhost\", \"http\"},\n\t\t\t{\"localhost\", \"https\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`http:\/\/localhost, https:\/\/localhost {\n\t\t    dir1 foo bar\n\t\t  }`, false, []address{\n\t\t\t{\"localhost\", \"http\"},\n\t\t\t{\"localhost\", \"https\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`http:\/\/localhost, {\n\t\t  }`, true, []address{\n\t\t\t{\"localhost\", \"http\"},\n\t\t}, map[string]int{}},\n\n\t\t{`host1:80, http:\/\/host2.com\n\t\t  dir1 foo bar\n\t\t  dir2 baz`, false, []address{\n\t\t\t{\"host1\", \"80\"},\n\t\t\t{\"host2.com\", \"http\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t\t\"dir2\": 2,\n\t\t}},\n\n\t\t{`http:\/\/host1.com,\n\t\t  http:\/\/host2.com,\n\t\t  https:\/\/host3.com`, false, []address{\n\t\t\t{\"host1.com\", \"http\"},\n\t\t\t{\"host2.com\", \"http\"},\n\t\t\t{\"host3.com\", \"https\"},\n\t\t}, map[string]int{}},\n\n\t\t{`http:\/\/host1.com:1234, https:\/\/host2.com\n\t\t  dir1 foo {\n\t\t    bar baz\n\t\t  }\n\t\t  dir2`, false, []address{\n\t\t\t{\"host1.com\", \"1234\"},\n\t\t\t{\"host2.com\", \"https\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 6,\n\t\t\t\"dir2\": 1,\n\t\t}},\n\n\t\t{`127.0.0.1\n\t\t  dir1 {\n\t\t    bar baz\n\t\t  }\n\t\t  dir2 {\n\t\t    foo bar\n\t\t  }`, false, []address{\n\t\t\t{\"127.0.0.1\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 5,\n\t\t\t\"dir2\": 5,\n\t\t}},\n\n\t\t{`127.0.0.1\n\t\t  unknown_directive`, true, []address{\n\t\t\t{\"127.0.0.1\", \"\"},\n\t\t}, map[string]int{}},\n\n\t\t{`localhost\n\t\t  dir1 {\n\t\t    foo`, true, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`localhost\n\t\t  dir1 {\n\t\t  }`, false, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`localhost\n\t\t  dir1 {\n\t\t  } }`, true, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 3,\n\t\t}},\n\n\t\t{`localhost\n\t\t  dir1 {\n\t\t    nested {\n\t\t      foo\n\t\t    }\n\t\t  }\n\t\t  dir2 foo bar`, false, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 7,\n\t\t\t\"dir2\": 3,\n\t\t}},\n\n\t\t{``, false, []address{}, map[string]int{}},\n\n\t\t{`localhost\n\t\t  dir1 arg1\n\t\t  import import_test1.txt`, false, []address{\n\t\t\t{\"localhost\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 2,\n\t\t\t\"dir2\": 3,\n\t\t\t\"dir3\": 1,\n\t\t}},\n\n\t\t{`import import_test2.txt`, false, []address{\n\t\t\t{\"host1\", \"\"},\n\t\t}, map[string]int{\n\t\t\t\"dir1\": 1,\n\t\t\t\"dir2\": 2,\n\t\t}},\n\n\t\t{`import import_test1.txt import_test2.txt`, true, []address{}, map[string]int{}},\n\n\t\t{`import not_found.txt`, true, []address{}, map[string]int{}},\n\n\t\t{`\"\"`, false, []address{}, map[string]int{}},\n\n\t\t{``, false, []address{}, map[string]int{}},\n\t} {\n\t\tresult, err := testParseOne(test.input)\n\n\t\tif test.shouldErr && err == nil {\n\t\t\tt.Errorf(\"Test %d: Expected an error, but didn't get one\", i)\n\t\t}\n\t\tif !test.shouldErr && err != nil {\n\t\t\tt.Errorf(\"Test %d: Expected no error, but got: %v\", i, err)\n\t\t}\n\n\t\tif len(result.Addresses) != len(test.addresses) {\n\t\t\tt.Errorf(\"Test %d: Expected %d addresses, got %d\",\n\t\t\t\ti, len(test.addresses), len(result.Addresses))\n\t\t\tcontinue\n\t\t}\n\t\tfor j, addr := range result.Addresses {\n\t\t\tif addr.Host != test.addresses[j].Host {\n\t\t\t\tt.Errorf(\"Test %d, address %d: Expected host to be '%s', but was '%s'\",\n\t\t\t\t\ti, j, test.addresses[j].Host, addr.Host)\n\t\t\t}\n\t\t\tif addr.Port != test.addresses[j].Port {\n\t\t\t\tt.Errorf(\"Test %d, address %d: Expected port to be '%s', but was '%s'\",\n\t\t\t\t\ti, j, test.addresses[j].Port, addr.Port)\n\t\t\t}\n\t\t}\n\n\t\tif len(result.Tokens) != len(test.tokens) {\n\t\t\tt.Errorf(\"Test %d: Expected %d directives, had %d\",\n\t\t\t\ti, len(test.tokens), len(result.Tokens))\n\t\t\tcontinue\n\t\t}\n\t\tfor directive, tokens := range result.Tokens {\n\t\t\tif len(tokens) != test.tokens[directive] {\n\t\t\t\tt.Errorf(\"Test %d, directive '%s': Expected %d tokens, counted %d\",\n\t\t\t\t\ti, directive, test.tokens[directive], len(tokens))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestParseAll(t *testing.T) {\n\tsetupParseTests()\n\n\tfor i, test := range []struct {\n\t\tinput     string\n\t\tshouldErr bool\n\t\taddresses [][]address \/\/ addresses per server block, in order\n\t}{\n\t\t{`localhost`, false, [][]address{\n\t\t\t{{\"localhost\", \"\"}},\n\t\t}},\n\n\t\t{`localhost:1234`, false, [][]address{\n\t\t\t[]address{{\"localhost\", \"1234\"}},\n\t\t}},\n\n\t\t{`localhost:1234 {\n\t\t  }\n\t\t  localhost:2015 {\n\t\t  }`, false, [][]address{\n\t\t\t[]address{{\"localhost\", \"1234\"}},\n\t\t\t[]address{{\"localhost\", \"2015\"}},\n\t\t}},\n\n\t\t{`localhost:1234, http:\/\/host2`, false, [][]address{\n\t\t\t[]address{{\"localhost\", \"1234\"}, {\"host2\", \"http\"}},\n\t\t}},\n\n\t\t{`localhost:1234, http:\/\/host2,`, true, [][]address{}},\n\n\t\t{`http:\/\/host1.com, http:\/\/host2.com {\n\t\t  }\n\t\t  https:\/\/host3.com, https:\/\/host4.com {\n\t\t  }`, false, [][]address{\n\t\t\t[]address{{\"host1.com\", \"http\"}, {\"host2.com\", \"http\"}},\n\t\t\t[]address{{\"host3.com\", \"https\"}, {\"host4.com\", \"https\"}},\n\t\t}},\n\t} {\n\t\tp := testParser(test.input)\n\t\tblocks, err := p.parseAll()\n\n\t\tif test.shouldErr && err == nil {\n\t\t\tt.Errorf(\"Test %d: Expected an error, but didn't get one\", i)\n\t\t}\n\t\tif !test.shouldErr && err != nil {\n\t\t\tt.Errorf(\"Test %d: Expected no error, but got: %v\", i, err)\n\t\t}\n\n\t\tif len(blocks) != len(test.addresses) {\n\t\t\tt.Errorf(\"Test %d: Expected %d server blocks, got %d\",\n\t\t\t\ti, len(test.addresses), len(blocks))\n\t\t\tcontinue\n\t\t}\n\t\tfor j, block := range blocks {\n\t\t\tif len(block.Addresses) != len(test.addresses[j]) {\n\t\t\t\tt.Errorf(\"Test %d: Expected %d addresses in block %d, got %d\",\n\t\t\t\t\ti, len(test.addresses[j]), j, len(block.Addresses))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor k, addr := range block.Addresses {\n\t\t\t\tif addr.Host != test.addresses[j][k].Host {\n\t\t\t\t\tt.Errorf(\"Test %d, block %d, address %d: Expected host to be '%s', but was '%s'\",\n\t\t\t\t\t\ti, j, k, test.addresses[j][k].Host, addr.Host)\n\t\t\t\t}\n\t\t\t\tif addr.Port != test.addresses[j][k].Port {\n\t\t\t\t\tt.Errorf(\"Test %d, block %d, address %d: Expected port to be '%s', but was '%s'\",\n\t\t\t\t\t\ti, j, k, test.addresses[j][k].Port, addr.Port)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestEnvironmentReplacement(t *testing.T) {\n\tsetupParseTests()\n\n\tos.Setenv(\"MY_PORT\", \"8080\")\n\tos.Setenv(\"MY_ADDRESS\", \"servername.com\")\n\tos.Setenv(\"MY_ADDRESS2\", \"127.0.0.1\")\n\n\tfor i, test := range []struct {\n\t\tinput     string\n\t\taddresses [][]address \/\/ addresses per server block, in order\n\t}{\n\t\t{`{$MY_ADDRESS}`, [][]address{\n\t\t\t{{\"servername.com\", \"\"}},\n\t\t}},\n\n\t\t{`{$MY_ADDRESS}:{$MY_PORT}`, [][]address{\n\t\t\t[]address{{\"servername.com\", \"8080\"}},\n\t\t}},\n\n\t\t{`{$MY_ADDRESS2}:1234 {\n\t\t  }\n\t\t  localhost:{$MY_PORT} {\n\t\t  }`, [][]address{\n\t\t\t[]address{{\"127.0.0.1\", \"1234\"}},\n\t\t\t[]address{{\"localhost\", \"8080\"}},\n\t\t}},\n\t} {\n\t\tp := testParser(test.input)\n\t\tblocks, err := p.parseAll()\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test %d: Expected no error, but got: %v\", i, err)\n\t\t}\n\n\t\tif len(blocks) != len(test.addresses) {\n\t\t\tt.Errorf(\"Test %d: Expected %d server blocks, got %d\",\n\t\t\t\ti, len(test.addresses), len(blocks))\n\t\t\tcontinue\n\t\t}\n\t\tfor j, block := range blocks {\n\t\t\tif len(block.Addresses) != len(test.addresses[j]) {\n\t\t\t\tt.Errorf(\"Test %d: Expected %d addresses in block %d, got %d\",\n\t\t\t\t\ti, len(test.addresses[j]), j, len(block.Addresses))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor k, addr := range block.Addresses {\n\t\t\t\tif addr.Host != test.addresses[j][k].Host {\n\t\t\t\t\tt.Errorf(\"Test %d, block %d, address %d: Expected host to be '%s', but was '%s'\",\n\t\t\t\t\t\ti, j, k, test.addresses[j][k].Host, addr.Host)\n\t\t\t\t}\n\t\t\t\tif addr.Port != test.addresses[j][k].Port {\n\t\t\t\t\tt.Errorf(\"Test %d, block %d, address %d: Expected port to be '%s', but was '%s'\",\n\t\t\t\t\t\ti, j, k, test.addresses[j][k].Port, addr.Port)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc setupParseTests() {\n\t\/\/ Set up some bogus directives for testing\n\tValidDirectives = map[string]struct{}{\n\t\t\"dir1\": {},\n\t\t\"dir2\": {},\n\t\t\"dir3\": {},\n\t}\n}\n\nfunc testParser(input string) parser {\n\tbuf := strings.NewReader(input)\n\tp := parser{Dispenser: NewDispenser(\"Test\", buf), checkDirectives: true}\n\treturn p\n}\n<|endoftext|>"}
{"text":"<commit_before>package cgroups\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"golang.org\/x\/sys\/unix\"\n\n\tspecs \"github.com\/opencontainers\/runtime-spec\/specs-go\"\n)\n\nfunc NewMemory(root string) *memoryController {\n\treturn &memoryController{\n\t\troot: filepath.Join(root, string(Memory)),\n\t}\n}\n\ntype memoryController struct {\n\troot string\n}\n\nfunc (m *memoryController) Name() Name {\n\treturn Memory\n}\n\nfunc (m *memoryController) Path(path string) string {\n\treturn filepath.Join(m.root, path)\n}\n\nfunc (m *memoryController) Create(path string, resources *specs.LinuxResources) error {\n\tif err := os.MkdirAll(m.Path(path), defaultDirPerm); err != nil {\n\t\treturn err\n\t}\n\tif resources.Memory == nil {\n\t\treturn nil\n\t}\n\tif resources.Memory.Kernel != nil {\n\t\t\/\/ Check if kernel memory is enabled\n\t\t\/\/ We have to limit the kernel memory here as it won't be accounted at all\n\t\t\/\/ until a limit is set on the cgroup and limit cannot be set once the\n\t\t\/\/ cgroup has children, or if there are already tasks in the cgroup.\n\t\tfor _, i := range []int64{1, -1} {\n\t\t\tif err := ioutil.WriteFile(\n\t\t\t\tfilepath.Join(m.Path(path), \"memory.kmem.limit_in_bytes\"),\n\t\t\t\t[]byte(strconv.FormatInt(i, 10)),\n\t\t\t\tdefaultFilePerm,\n\t\t\t); err != nil {\n\t\t\t\treturn checkEBUSY(err)\n\t\t\t}\n\t\t}\n\t}\n\treturn m.set(path, getMemorySettings(resources))\n}\n\nfunc (m *memoryController) Update(path string, resources *specs.LinuxResources) error {\n\tif resources.Memory == nil {\n\t\treturn nil\n\t}\n\tg := func(v *int64) bool {\n\t\treturn v != nil && *v > 0\n\t}\n\tsettings := getMemorySettings(resources)\n\tif g(resources.Memory.Limit) && g(resources.Memory.Swap) {\n\t\t\/\/ if the updated swap value is larger than the current memory limit set the swap changes first\n\t\t\/\/ then set the memory limit as swap must always be larger than the current limit\n\t\tcurrent, err := readUint(filepath.Join(m.Path(path), \"memory.limit_in_bytes\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif current < uint64(*resources.Memory.Swap) {\n\t\t\tsettings[0], settings[1] = settings[1], settings[0]\n\t\t}\n\t}\n\treturn m.set(path, settings)\n}\n\nfunc (m *memoryController) Stat(path string, stats *Metrics) error {\n\tf, err := os.Open(filepath.Join(m.Path(path), \"memory.stat\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tstats.Memory = &MemoryStat{\n\t\tUsage:     &MemoryEntry{},\n\t\tSwap:      &MemoryEntry{},\n\t\tKernel:    &MemoryEntry{},\n\t\tKernelTCP: &MemoryEntry{},\n\t}\n\tif err := m.parseStats(f, stats.Memory); err != nil {\n\t\treturn err\n\t}\n\tfor _, t := range []struct {\n\t\tmodule string\n\t\tentry  *MemoryEntry\n\t}{\n\t\t{\n\t\t\tmodule: \"\",\n\t\t\tentry:  stats.Memory.Usage,\n\t\t},\n\t\t{\n\t\t\tmodule: \"memsw\",\n\t\t\tentry:  stats.Memory.Swap,\n\t\t},\n\t\t{\n\t\t\tmodule: \"kmem\",\n\t\t\tentry:  stats.Memory.Kernel,\n\t\t},\n\t\t{\n\t\t\tmodule: \"kmem.tcp\",\n\t\t\tentry:  stats.Memory.KernelTCP,\n\t\t},\n\t} {\n\t\tfor _, tt := range []struct {\n\t\t\tname  string\n\t\t\tvalue *uint64\n\t\t}{\n\t\t\t{\n\t\t\t\tname:  \"usage_in_bytes\",\n\t\t\t\tvalue: &t.entry.Usage,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:  \"max_usage_in_bytes\",\n\t\t\t\tvalue: &t.entry.Max,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:  \"failcnt\",\n\t\t\t\tvalue: &t.entry.Failcnt,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:  \"limit_in_bytes\",\n\t\t\t\tvalue: &t.entry.Limit,\n\t\t\t},\n\t\t} {\n\t\t\tparts := []string{\"memory\"}\n\t\t\tif t.module != \"\" {\n\t\t\t\tparts = append(parts, t.module)\n\t\t\t}\n\t\t\tparts = append(parts, tt.name)\n\t\t\tv, err := readUint(filepath.Join(m.Path(path), strings.Join(parts, \".\")))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*tt.value = v\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *memoryController) OOMEventFD(path string) (uintptr, error) {\n\troot := m.Path(path)\n\tf, err := os.Open(filepath.Join(root, \"memory.oom_control\"))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer f.Close()\n\tfd, _, serr := unix.RawSyscall(unix.SYS_EVENTFD2, 0, unix.FD_CLOEXEC, 0)\n\tif serr != 0 {\n\t\treturn 0, serr\n\t}\n\tif err := writeEventFD(root, f.Fd(), fd); err != nil {\n\t\tunix.Close(int(fd))\n\t\treturn 0, err\n\t}\n\treturn fd, nil\n}\n\nfunc writeEventFD(root string, cfd, efd uintptr) error {\n\tf, err := os.OpenFile(filepath.Join(root, \"cgroup.event_control\"), os.O_WRONLY, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = f.WriteString(fmt.Sprintf(\"%d %d\", efd, cfd))\n\tf.Close()\n\treturn err\n}\n\nfunc (m *memoryController) parseStats(r io.Reader, stat *MemoryStat) error {\n\tvar (\n\t\traw  = make(map[string]uint64)\n\t\tsc   = bufio.NewScanner(r)\n\t\tline int\n\t)\n\tfor sc.Scan() {\n\t\tif err := sc.Err(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkey, v, err := parseKV(sc.Text())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%d: %v\", line, err)\n\t\t}\n\t\traw[key] = v\n\t\tline++\n\t}\n\tstat.Cache = raw[\"cache\"]\n\tstat.RSS = raw[\"rss\"]\n\tstat.RSSHuge = raw[\"rss_huge\"]\n\tstat.MappedFile = raw[\"mapped_file\"]\n\tstat.Dirty = raw[\"dirty\"]\n\tstat.Writeback = raw[\"writeback\"]\n\tstat.PgPgIn = raw[\"pgpgin\"]\n\tstat.PgPgOut = raw[\"pgpgout\"]\n\tstat.PgFault = raw[\"pgfault\"]\n\tstat.PgMajFault = raw[\"pgmajfault\"]\n\tstat.InactiveAnon = raw[\"inactive_anon\"]\n\tstat.ActiveAnon = raw[\"active_anon\"]\n\tstat.InactiveFile = raw[\"inactive_file\"]\n\tstat.ActiveFile = raw[\"active_file\"]\n\tstat.Unevictable = raw[\"unevictable\"]\n\tstat.HierarchicalMemoryLimit = raw[\"hierarchical_memory_limit\"]\n\tstat.HierarchicalSwapLimit = raw[\"hierarchical_memsw_limit\"]\n\tstat.TotalCache = raw[\"total_cache\"]\n\tstat.TotalRSS = raw[\"total_rss\"]\n\tstat.TotalRSSHuge = raw[\"total_rss_huge\"]\n\tstat.TotalMappedFile = raw[\"total_mapped_file\"]\n\tstat.TotalDirty = raw[\"total_dirty\"]\n\tstat.TotalWriteback = raw[\"total_writeback\"]\n\tstat.TotalPgPgIn = raw[\"total_pgpgin\"]\n\tstat.TotalPgPgOut = raw[\"total_pgpgout\"]\n\tstat.TotalPgFault = raw[\"total_pgfault\"]\n\tstat.TotalPgMajFault = raw[\"total_pgmajfault\"]\n\tstat.TotalInactiveAnon = raw[\"total_inactive_anon\"]\n\tstat.TotalActiveAnon = raw[\"total_active_anon\"]\n\tstat.TotalInactiveFile = raw[\"total_inactive_file\"]\n\tstat.TotalActiveFile = raw[\"total_active_file\"]\n\tstat.TotalUnevictable = raw[\"total_unevictable\"]\n\treturn nil\n}\n\nfunc (m *memoryController) set(path string, settings []memorySettings) error {\n\tfor _, t := range settings {\n\t\tif t.value != nil {\n\t\t\tif err := ioutil.WriteFile(\n\t\t\t\tfilepath.Join(m.Path(path), fmt.Sprintf(\"memory.%s\", t.name)),\n\t\t\t\t[]byte(strconv.FormatInt(*t.value, 10)),\n\t\t\t\tdefaultFilePerm,\n\t\t\t); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\ntype memorySettings struct {\n\tname  string\n\tvalue *int64\n}\n\nfunc getMemorySettings(resources *specs.LinuxResources) []memorySettings {\n\tmem := resources.Memory\n\tvar swappiness *int64\n\tif mem.Swappiness != nil {\n\t\tv := int64(*mem.Swappiness)\n\t\tswappiness = &v\n\t}\n\treturn []memorySettings{\n\t\t{\n\t\t\tname:  \"limit_in_bytes\",\n\t\t\tvalue: mem.Limit,\n\t\t},\n\t\t{\n\t\t\tname:  \"memsw.limit_in_bytes\",\n\t\t\tvalue: mem.Swap,\n\t\t},\n\t\t{\n\t\t\tname:  \"kmem.limit_in_bytes\",\n\t\t\tvalue: mem.Kernel,\n\t\t},\n\t\t{\n\t\t\tname:  \"kmem.tcp.limit_in_bytes\",\n\t\t\tvalue: mem.KernelTCP,\n\t\t},\n\t\t{\n\t\t\tname:  \"oom_control\",\n\t\t\tvalue: getOomControlValue(mem),\n\t\t},\n\t\t{\n\t\t\tname:  \"swappiness\",\n\t\t\tvalue: swappiness,\n\t\t},\n\t}\n}\n\nfunc checkEBUSY(err error) error {\n\tif pathErr, ok := err.(*os.PathError); ok {\n\t\tif errNo, ok := pathErr.Err.(syscall.Errno); ok {\n\t\t\tif errNo == unix.EBUSY {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"failed to set memory.kmem.limit_in_bytes, because either tasks have already joined this cgroup or it has children\")\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}\n\nfunc getOomControlValue(mem *specs.LinuxMemory) *int64 {\n\tif mem.DisableOOMKiller != nil && *mem.DisableOOMKiller {\n\t\ti := int64(1)\n\t\treturn &i\n\t}\n\treturn nil\n}\n<commit_msg>Pass proper close-on-exec flags with eventfd()<commit_after>package cgroups\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"golang.org\/x\/sys\/unix\"\n\n\tspecs \"github.com\/opencontainers\/runtime-spec\/specs-go\"\n)\n\nfunc NewMemory(root string) *memoryController {\n\treturn &memoryController{\n\t\troot: filepath.Join(root, string(Memory)),\n\t}\n}\n\ntype memoryController struct {\n\troot string\n}\n\nfunc (m *memoryController) Name() Name {\n\treturn Memory\n}\n\nfunc (m *memoryController) Path(path string) string {\n\treturn filepath.Join(m.root, path)\n}\n\nfunc (m *memoryController) Create(path string, resources *specs.LinuxResources) error {\n\tif err := os.MkdirAll(m.Path(path), defaultDirPerm); err != nil {\n\t\treturn err\n\t}\n\tif resources.Memory == nil {\n\t\treturn nil\n\t}\n\tif resources.Memory.Kernel != nil {\n\t\t\/\/ Check if kernel memory is enabled\n\t\t\/\/ We have to limit the kernel memory here as it won't be accounted at all\n\t\t\/\/ until a limit is set on the cgroup and limit cannot be set once the\n\t\t\/\/ cgroup has children, or if there are already tasks in the cgroup.\n\t\tfor _, i := range []int64{1, -1} {\n\t\t\tif err := ioutil.WriteFile(\n\t\t\t\tfilepath.Join(m.Path(path), \"memory.kmem.limit_in_bytes\"),\n\t\t\t\t[]byte(strconv.FormatInt(i, 10)),\n\t\t\t\tdefaultFilePerm,\n\t\t\t); err != nil {\n\t\t\t\treturn checkEBUSY(err)\n\t\t\t}\n\t\t}\n\t}\n\treturn m.set(path, getMemorySettings(resources))\n}\n\nfunc (m *memoryController) Update(path string, resources *specs.LinuxResources) error {\n\tif resources.Memory == nil {\n\t\treturn nil\n\t}\n\tg := func(v *int64) bool {\n\t\treturn v != nil && *v > 0\n\t}\n\tsettings := getMemorySettings(resources)\n\tif g(resources.Memory.Limit) && g(resources.Memory.Swap) {\n\t\t\/\/ if the updated swap value is larger than the current memory limit set the swap changes first\n\t\t\/\/ then set the memory limit as swap must always be larger than the current limit\n\t\tcurrent, err := readUint(filepath.Join(m.Path(path), \"memory.limit_in_bytes\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif current < uint64(*resources.Memory.Swap) {\n\t\t\tsettings[0], settings[1] = settings[1], settings[0]\n\t\t}\n\t}\n\treturn m.set(path, settings)\n}\n\nfunc (m *memoryController) Stat(path string, stats *Metrics) error {\n\tf, err := os.Open(filepath.Join(m.Path(path), \"memory.stat\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tstats.Memory = &MemoryStat{\n\t\tUsage:     &MemoryEntry{},\n\t\tSwap:      &MemoryEntry{},\n\t\tKernel:    &MemoryEntry{},\n\t\tKernelTCP: &MemoryEntry{},\n\t}\n\tif err := m.parseStats(f, stats.Memory); err != nil {\n\t\treturn err\n\t}\n\tfor _, t := range []struct {\n\t\tmodule string\n\t\tentry  *MemoryEntry\n\t}{\n\t\t{\n\t\t\tmodule: \"\",\n\t\t\tentry:  stats.Memory.Usage,\n\t\t},\n\t\t{\n\t\t\tmodule: \"memsw\",\n\t\t\tentry:  stats.Memory.Swap,\n\t\t},\n\t\t{\n\t\t\tmodule: \"kmem\",\n\t\t\tentry:  stats.Memory.Kernel,\n\t\t},\n\t\t{\n\t\t\tmodule: \"kmem.tcp\",\n\t\t\tentry:  stats.Memory.KernelTCP,\n\t\t},\n\t} {\n\t\tfor _, tt := range []struct {\n\t\t\tname  string\n\t\t\tvalue *uint64\n\t\t}{\n\t\t\t{\n\t\t\t\tname:  \"usage_in_bytes\",\n\t\t\t\tvalue: &t.entry.Usage,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:  \"max_usage_in_bytes\",\n\t\t\t\tvalue: &t.entry.Max,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:  \"failcnt\",\n\t\t\t\tvalue: &t.entry.Failcnt,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:  \"limit_in_bytes\",\n\t\t\t\tvalue: &t.entry.Limit,\n\t\t\t},\n\t\t} {\n\t\t\tparts := []string{\"memory\"}\n\t\t\tif t.module != \"\" {\n\t\t\t\tparts = append(parts, t.module)\n\t\t\t}\n\t\t\tparts = append(parts, tt.name)\n\t\t\tv, err := readUint(filepath.Join(m.Path(path), strings.Join(parts, \".\")))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t*tt.value = v\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *memoryController) OOMEventFD(path string) (uintptr, error) {\n\troot := m.Path(path)\n\tf, err := os.Open(filepath.Join(root, \"memory.oom_control\"))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer f.Close()\n\tfd, _, serr := unix.RawSyscall(unix.SYS_EVENTFD2, 0, unix.EFD_CLOEXEC, 0)\n\tif serr != 0 {\n\t\treturn 0, serr\n\t}\n\tif err := writeEventFD(root, f.Fd(), fd); err != nil {\n\t\tunix.Close(int(fd))\n\t\treturn 0, err\n\t}\n\treturn fd, nil\n}\n\nfunc writeEventFD(root string, cfd, efd uintptr) error {\n\tf, err := os.OpenFile(filepath.Join(root, \"cgroup.event_control\"), os.O_WRONLY, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = f.WriteString(fmt.Sprintf(\"%d %d\", efd, cfd))\n\tf.Close()\n\treturn err\n}\n\nfunc (m *memoryController) parseStats(r io.Reader, stat *MemoryStat) error {\n\tvar (\n\t\traw  = make(map[string]uint64)\n\t\tsc   = bufio.NewScanner(r)\n\t\tline int\n\t)\n\tfor sc.Scan() {\n\t\tif err := sc.Err(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tkey, v, err := parseKV(sc.Text())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%d: %v\", line, err)\n\t\t}\n\t\traw[key] = v\n\t\tline++\n\t}\n\tstat.Cache = raw[\"cache\"]\n\tstat.RSS = raw[\"rss\"]\n\tstat.RSSHuge = raw[\"rss_huge\"]\n\tstat.MappedFile = raw[\"mapped_file\"]\n\tstat.Dirty = raw[\"dirty\"]\n\tstat.Writeback = raw[\"writeback\"]\n\tstat.PgPgIn = raw[\"pgpgin\"]\n\tstat.PgPgOut = raw[\"pgpgout\"]\n\tstat.PgFault = raw[\"pgfault\"]\n\tstat.PgMajFault = raw[\"pgmajfault\"]\n\tstat.InactiveAnon = raw[\"inactive_anon\"]\n\tstat.ActiveAnon = raw[\"active_anon\"]\n\tstat.InactiveFile = raw[\"inactive_file\"]\n\tstat.ActiveFile = raw[\"active_file\"]\n\tstat.Unevictable = raw[\"unevictable\"]\n\tstat.HierarchicalMemoryLimit = raw[\"hierarchical_memory_limit\"]\n\tstat.HierarchicalSwapLimit = raw[\"hierarchical_memsw_limit\"]\n\tstat.TotalCache = raw[\"total_cache\"]\n\tstat.TotalRSS = raw[\"total_rss\"]\n\tstat.TotalRSSHuge = raw[\"total_rss_huge\"]\n\tstat.TotalMappedFile = raw[\"total_mapped_file\"]\n\tstat.TotalDirty = raw[\"total_dirty\"]\n\tstat.TotalWriteback = raw[\"total_writeback\"]\n\tstat.TotalPgPgIn = raw[\"total_pgpgin\"]\n\tstat.TotalPgPgOut = raw[\"total_pgpgout\"]\n\tstat.TotalPgFault = raw[\"total_pgfault\"]\n\tstat.TotalPgMajFault = raw[\"total_pgmajfault\"]\n\tstat.TotalInactiveAnon = raw[\"total_inactive_anon\"]\n\tstat.TotalActiveAnon = raw[\"total_active_anon\"]\n\tstat.TotalInactiveFile = raw[\"total_inactive_file\"]\n\tstat.TotalActiveFile = raw[\"total_active_file\"]\n\tstat.TotalUnevictable = raw[\"total_unevictable\"]\n\treturn nil\n}\n\nfunc (m *memoryController) set(path string, settings []memorySettings) error {\n\tfor _, t := range settings {\n\t\tif t.value != nil {\n\t\t\tif err := ioutil.WriteFile(\n\t\t\t\tfilepath.Join(m.Path(path), fmt.Sprintf(\"memory.%s\", t.name)),\n\t\t\t\t[]byte(strconv.FormatInt(*t.value, 10)),\n\t\t\t\tdefaultFilePerm,\n\t\t\t); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\ntype memorySettings struct {\n\tname  string\n\tvalue *int64\n}\n\nfunc getMemorySettings(resources *specs.LinuxResources) []memorySettings {\n\tmem := resources.Memory\n\tvar swappiness *int64\n\tif mem.Swappiness != nil {\n\t\tv := int64(*mem.Swappiness)\n\t\tswappiness = &v\n\t}\n\treturn []memorySettings{\n\t\t{\n\t\t\tname:  \"limit_in_bytes\",\n\t\t\tvalue: mem.Limit,\n\t\t},\n\t\t{\n\t\t\tname:  \"memsw.limit_in_bytes\",\n\t\t\tvalue: mem.Swap,\n\t\t},\n\t\t{\n\t\t\tname:  \"kmem.limit_in_bytes\",\n\t\t\tvalue: mem.Kernel,\n\t\t},\n\t\t{\n\t\t\tname:  \"kmem.tcp.limit_in_bytes\",\n\t\t\tvalue: mem.KernelTCP,\n\t\t},\n\t\t{\n\t\t\tname:  \"oom_control\",\n\t\t\tvalue: getOomControlValue(mem),\n\t\t},\n\t\t{\n\t\t\tname:  \"swappiness\",\n\t\t\tvalue: swappiness,\n\t\t},\n\t}\n}\n\nfunc checkEBUSY(err error) error {\n\tif pathErr, ok := err.(*os.PathError); ok {\n\t\tif errNo, ok := pathErr.Err.(syscall.Errno); ok {\n\t\t\tif errNo == unix.EBUSY {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"failed to set memory.kmem.limit_in_bytes, because either tasks have already joined this cgroup or it has children\")\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}\n\nfunc getOomControlValue(mem *specs.LinuxMemory) *int64 {\n\tif mem.DisableOOMKiller != nil && *mem.DisableOOMKiller {\n\t\ti := int64(1)\n\t\treturn &i\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package controller\n\n\/*\nCopyright 2019 Crunchy Data Solutions, Inc.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\nimport (\n\t\"context\"\n\n\t\"github.com\/crunchydata\/postgres-operator\/config\"\n\t\"github.com\/crunchydata\/postgres-operator\/operator\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/fields\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/rest\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n)\n\n\/\/ NamespaceController holds the connections for the controller\ntype NamespaceController struct {\n\tNamespaceClient        *rest.RESTClient\n\tNamespaceClientset     *kubernetes.Clientset\n\tCtx                    context.Context\n\tThePodController       *PodController\n\tTheJobController       *JobController\n\tThePgpolicyController  *PgpolicyController\n\tThePgbackupController  *PgbackupController\n\tThePgreplicaController *PgreplicaController\n\tThePgclusterController *PgclusterController\n\tThePgtaskController    *PgtaskController\n}\n\n\/\/ Run starts a namespace resource controller\nfunc (c *NamespaceController) Run() error {\n\n\terr := c.watchNamespaces(c.Ctx)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to register watch for namespace resource: %v\", err)\n\t\treturn err\n\t}\n\n\t<-c.Ctx.Done()\n\treturn c.Ctx.Err()\n}\n\n\/\/ watchNamespaces is the event loop for namespace resources\nfunc (c *NamespaceController) watchNamespaces(ctx context.Context) error {\n\tlog.Info(\"starting namespace controller\")\n\n\t\/\/watch all namespaces\n\tns := \"\"\n\n\tsource := cache.NewListWatchFromClient(\n\t\tc.NamespaceClientset.CoreV1().RESTClient(),\n\t\t\"namespaces\",\n\t\tns,\n\t\tfields.Everything())\n\n\t_, controller := cache.NewInformer(\n\t\tsource,\n\n\t\t\/\/ The object type.\n\t\t&v1.Namespace{},\n\n\t\t\/\/ resyncPeriod\n\t\t\/\/ Every resyncPeriod, all resources in the cache will retrigger events.\n\t\t\/\/ Set to 0 to disable the resync.\n\t\t0,\n\n\t\t\/\/ Your custom resource event handlers.\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc:    c.onAdd,\n\t\t\tUpdateFunc: c.onUpdate,\n\t\t\tDeleteFunc: c.onDelete,\n\t\t})\n\n\tgo controller.Run(ctx.Done())\n\n\treturn nil\n}\n\nfunc (c *NamespaceController) onAdd(obj interface{}) {\n\tnewNs := obj.(*v1.Namespace)\n\n\tlog.Debugf(\"[NamespaceController] OnAdd ns=%s\", newNs.ObjectMeta.SelfLink)\n\tlabels := newNs.GetObjectMeta().GetLabels()\n\tif labels[config.LABEL_VENDOR] != config.LABEL_CRUNCHY || labels[config.LABEL_PGO_INSTALLATION_NAME] != operator.InstallationName {\n\t\tlog.Debugf(\"NamespaceController: onAdd skipping namespace that is not crunchydata or not belonging to this Operator installation %s\", newNs.ObjectMeta.SelfLink)\n\t\treturn\n\t} else {\n\t\tlog.Debugf(\"NamespaceController: onAdd crunchy namespace %s created\", newNs.ObjectMeta.SelfLink)\n\t\tc.ThePodController.SetupWatch(newNs.Name)\n\t\tc.TheJobController.SetupWatch(newNs.Name)\n\t\tc.ThePgpolicyController.SetupWatch(newNs.Name)\n\t\tc.ThePgbackupController.SetupWatch(newNs.Name)\n\t\tc.ThePgreplicaController.SetupWatch(newNs.Name)\n\t\tc.ThePgclusterController.SetupWatch(newNs.Name)\n\t\tc.ThePgtaskController.SetupWatch(newNs.Name)\n\t}\n\n}\n\n\/\/ onUpdate is called when a pgcluster is updated\nfunc (c *NamespaceController) onUpdate(oldObj, newObj interface{}) {\n\t\/\/oldNs := oldObj.(*v1.Namespace)\n\tnewNs := newObj.(*v1.Namespace)\n\tlog.Debugf(\"[NamespaceController] onUpdate ns=%s\", newNs.ObjectMeta.SelfLink)\n\n\tlabels := newNs.GetObjectMeta().GetLabels()\n\tif labels[config.LABEL_VENDOR] != config.LABEL_CRUNCHY {\n\t\tlog.Debugf(\"NamespaceController: onUpdate skipping namespace that is not crunchydata %s\", newNs.ObjectMeta.SelfLink)\n\t\treturn\n\t} else {\n\t\tlog.Debugf(\"NamespaceController: onUpdate crunchy namespace updated %s\", newNs.ObjectMeta.SelfLink)\n\t\tc.ThePodController.SetupWatch(newNs.Name)\n\t\tc.TheJobController.SetupWatch(newNs.Name)\n\t\tc.ThePgpolicyController.SetupWatch(newNs.Name)\n\t\tc.ThePgbackupController.SetupWatch(newNs.Name)\n\t\tc.ThePgreplicaController.SetupWatch(newNs.Name)\n\t\tc.ThePgclusterController.SetupWatch(newNs.Name)\n\t\tc.ThePgtaskController.SetupWatch(newNs.Name)\n\t}\n\n}\n\nfunc (c *NamespaceController) onDelete(obj interface{}) {\n\tns := obj.(*v1.Namespace)\n\n\tlog.Debugf(\"[NamespaceController] onDelete ns=%s\", ns.ObjectMeta.SelfLink)\n\tlabels := ns.GetObjectMeta().GetLabels()\n\tif labels[config.LABEL_VENDOR] != config.LABEL_CRUNCHY {\n\t\tlog.Debugf(\"NamespaceController: onDelete skipping namespace that is not crunchydata %s\", ns.ObjectMeta.SelfLink)\n\t\treturn\n\t} else {\n\t\tlog.Debugf(\"NamespaceController: onDelete crunchy operator namespace %s is deleted\", ns.ObjectMeta.SelfLink)\n\t}\n\n}\n<commit_msg>Added additional label check to support multiple operator deployments on a single kube\/openshift cluster.<commit_after>package controller\n\n\/*\nCopyright 2019 Crunchy Data Solutions, Inc.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\nimport (\n\t\"context\"\n\n\t\"github.com\/crunchydata\/postgres-operator\/config\"\n\t\"github.com\/crunchydata\/postgres-operator\/operator\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/fields\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/rest\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n)\n\n\/\/ NamespaceController holds the connections for the controller\ntype NamespaceController struct {\n\tNamespaceClient        *rest.RESTClient\n\tNamespaceClientset     *kubernetes.Clientset\n\tCtx                    context.Context\n\tThePodController       *PodController\n\tTheJobController       *JobController\n\tThePgpolicyController  *PgpolicyController\n\tThePgbackupController  *PgbackupController\n\tThePgreplicaController *PgreplicaController\n\tThePgclusterController *PgclusterController\n\tThePgtaskController    *PgtaskController\n}\n\n\/\/ Run starts a namespace resource controller\nfunc (c *NamespaceController) Run() error {\n\n\terr := c.watchNamespaces(c.Ctx)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to register watch for namespace resource: %v\", err)\n\t\treturn err\n\t}\n\n\t<-c.Ctx.Done()\n\treturn c.Ctx.Err()\n}\n\n\/\/ watchNamespaces is the event loop for namespace resources\nfunc (c *NamespaceController) watchNamespaces(ctx context.Context) error {\n\tlog.Info(\"starting namespace controller\")\n\n\t\/\/watch all namespaces\n\tns := \"\"\n\n\tsource := cache.NewListWatchFromClient(\n\t\tc.NamespaceClientset.CoreV1().RESTClient(),\n\t\t\"namespaces\",\n\t\tns,\n\t\tfields.Everything())\n\n\t_, controller := cache.NewInformer(\n\t\tsource,\n\n\t\t\/\/ The object type.\n\t\t&v1.Namespace{},\n\n\t\t\/\/ resyncPeriod\n\t\t\/\/ Every resyncPeriod, all resources in the cache will retrigger events.\n\t\t\/\/ Set to 0 to disable the resync.\n\t\t0,\n\n\t\t\/\/ Your custom resource event handlers.\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tAddFunc:    c.onAdd,\n\t\t\tUpdateFunc: c.onUpdate,\n\t\t\tDeleteFunc: c.onDelete,\n\t\t})\n\n\tgo controller.Run(ctx.Done())\n\n\treturn nil\n}\n\nfunc (c *NamespaceController) onAdd(obj interface{}) {\n\tnewNs := obj.(*v1.Namespace)\n\n\tlog.Debugf(\"[NamespaceController] OnAdd ns=%s\", newNs.ObjectMeta.SelfLink)\n\tlabels := newNs.GetObjectMeta().GetLabels()\n\tif labels[config.LABEL_VENDOR] != config.LABEL_CRUNCHY || labels[config.LABEL_PGO_INSTALLATION_NAME] != operator.InstallationName {\n\t\tlog.Debugf(\"NamespaceController: onAdd skipping namespace that is not crunchydata or not belonging to this Operator installation %s\", newNs.ObjectMeta.SelfLink)\n\t\treturn\n\t} else {\n\t\tlog.Debugf(\"NamespaceController: onAdd crunchy namespace %s created\", newNs.ObjectMeta.SelfLink)\n\t\tc.ThePodController.SetupWatch(newNs.Name)\n\t\tc.TheJobController.SetupWatch(newNs.Name)\n\t\tc.ThePgpolicyController.SetupWatch(newNs.Name)\n\t\tc.ThePgbackupController.SetupWatch(newNs.Name)\n\t\tc.ThePgreplicaController.SetupWatch(newNs.Name)\n\t\tc.ThePgclusterController.SetupWatch(newNs.Name)\n\t\tc.ThePgtaskController.SetupWatch(newNs.Name)\n\t}\n\n}\n\n\/\/ onUpdate is called when a pgcluster is updated\nfunc (c *NamespaceController) onUpdate(oldObj, newObj interface{}) {\n\t\/\/oldNs := oldObj.(*v1.Namespace)\n\tnewNs := newObj.(*v1.Namespace)\n\tlog.Debugf(\"[NamespaceController] onUpdate ns=%s\", newNs.ObjectMeta.SelfLink)\n\n\tlabels := newNs.GetObjectMeta().GetLabels()\n\tif labels[config.LABEL_VENDOR] != config.LABEL_CRUNCHY || labels[config.LABEL_PGO_INSTALLATION_NAME] != operator.InstallationName {\n\t\tlog.Debugf(\"NamespaceController: onUpdate skipping namespace that is not crunchydata %s\", newNs.ObjectMeta.SelfLink)\n\t\treturn\n\t} else {\n\t\tlog.Debugf(\"NamespaceController: onUpdate crunchy namespace updated %s\", newNs.ObjectMeta.SelfLink)\n\t\tc.ThePodController.SetupWatch(newNs.Name)\n\t\tc.TheJobController.SetupWatch(newNs.Name)\n\t\tc.ThePgpolicyController.SetupWatch(newNs.Name)\n\t\tc.ThePgbackupController.SetupWatch(newNs.Name)\n\t\tc.ThePgreplicaController.SetupWatch(newNs.Name)\n\t\tc.ThePgclusterController.SetupWatch(newNs.Name)\n\t\tc.ThePgtaskController.SetupWatch(newNs.Name)\n\t}\n\n}\n\nfunc (c *NamespaceController) onDelete(obj interface{}) {\n\tns := obj.(*v1.Namespace)\n\n\tlog.Debugf(\"[NamespaceController] onDelete ns=%s\", ns.ObjectMeta.SelfLink)\n\tlabels := ns.GetObjectMeta().GetLabels()\n\tif labels[config.LABEL_VENDOR] != config.LABEL_CRUNCHY {\n\t\tlog.Debugf(\"NamespaceController: onDelete skipping namespace that is not crunchydata %s\", ns.ObjectMeta.SelfLink)\n\t\treturn\n\t} else {\n\t\tlog.Debugf(\"NamespaceController: onDelete crunchy operator namespace %s is deleted\", ns.ObjectMeta.SelfLink)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014 Ludovic Fauvet\n\/\/ Licensed under the MIT license\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/op\/go-logging\"\n\tstdlog \"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar (\n\tlog     = logging.MustGetLogger(\"main\")\n\trlogger RuntimeLogger\n\tdlogger DownloadsLogger\n)\n\ntype RuntimeLogger struct {\n\tf *os.File\n}\n\ntype DownloadsLogger struct {\n\tsync.RWMutex\n\tl *stdlog.Logger\n\tf *os.File\n}\n\n\/\/ ReloadLogs will reopen the logs to allow rotations\nfunc ReloadLogs() {\n\tReloadRuntimeLogs()\n\tReloadDownloadLogs()\n}\n\nfunc ReloadRuntimeLogs() {\n\tlogging.SetFormatter(logging.MustStringFormatter(\"%{time:2006\/01\/02 15:04:05.000 MST} %{message}\"))\n\tlogFlags := 0\n\n\tif os.Getenv(\"DEBUG\") != \"\" {\n\t\tlogFlags = stdlog.Lshortfile\n\t\tlogging.SetLevel(logging.DEBUG, \"main\")\n\t} else {\n\t\tlogging.SetLevel(logging.INFO, \"main\")\n\t}\n\n\tlogColor := false\n\n\tstat, _ := os.Stdout.Stat()\n\tif (stat.Mode() & os.ModeCharDevice) != 0 {\n\t\tlogColor = true \/\/TODO make it optionnal\n\t}\n\n\tif rlogger.f != nil {\n\t\trlogger.f.Close()\n\t} else {\n\t\trlogger.f = os.Stderr\n\t}\n\n\tif runLog != \"\" {\n\t\tvar err error\n\t\trlogger.f, err = os.OpenFile(runLog, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, \"Cannot open log file for writing\")\n\t\t\trlogger.f = os.Stderr\n\t\t} else {\n\t\t\tlogColor = false\n\t\t}\n\t}\n\n\tlogBackend := logging.NewLogBackend(rlogger.f, \"\", logFlags)\n\tlogBackend.Color = logColor\n\n\tlogging.SetBackend(logBackend)\n}\n\nfunc ReloadDownloadLogs() {\n\tdlogger.Lock()\n\tdefer dlogger.Unlock()\n\n\tif GetConfig().LogDir == \"\" {\n\t\tif dlogger.f != nil {\n\t\t\tdlogger.f.Close()\n\t\t}\n\t\tdlogger.f = nil\n\t\tdlogger.l = nil\n\t\treturn\n\t}\n\n\tlogfile := GetConfig().LogDir + \"\/downloads.log\"\n\tcreateHeader := true\n\n\ts, err := os.Stat(logfile)\n\tif err == nil && s.Size() > 0 {\n\t\tcreateHeader = false\n\t}\n\n\tif dlogger.f != nil {\n\t\tdlogger.f.Close()\n\t}\n\tdlogger.f, err = os.OpenFile(logfile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)\n\n\tif err != nil {\n\t\tlog.Critical(\"Warning: cannot open log file %s\", logfile)\n\t\treturn\n\t}\n\n\tif createHeader {\n\t\tvar buf bytes.Buffer\n\t\thostname, _ := os.Hostname()\n\t\tfmt.Fprintf(&buf, \"# Log file created at: %s\\n\", time.Now().Format(\"2006\/01\/02 15:04:05\"))\n\t\tfmt.Fprintf(&buf, \"# Running on machine: %s\\n\", hostname)\n\t\tfmt.Fprintf(&buf, \"# Binary: Built with %s %s for %s\/%s\\n\", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH)\n\t\tdlogger.f.Write(buf.Bytes())\n\t}\n\n\tdlogger.l = stdlog.New(dlogger.f, \"\", stdlog.Ldate|stdlog.Lmicroseconds)\n}\n\n\/\/ This function will write a download result in the logs.\nfunc logDownload(typ string, statuscode int, p *MirrorlistPage, err error) {\n\tdlogger.RLock()\n\tdefer dlogger.RUnlock()\n\n\tif dlogger.l == nil {\n\t\t\/\/ Logs are disabled\n\t\treturn\n\t}\n\n\tif statuscode == 302 || statuscode == 200 {\n\t\tvar distance, countries string\n\t\tm := p.MirrorList[0]\n\t\tdistance = strconv.FormatFloat(float64(m.Distance), 'f', 2, 32)\n\t\tcountries = strings.Join(m.CountryFields, \",\")\n\t\tfallback := \"\"\n\t\tif p.Fallback == true {\n\t\t\tfallback = \" fallback:true\"\n\t\t}\n\t\tsameASNum := \"\"\n\t\tif m.Asnum > 0 && m.Asnum == p.ClientInfo.ASNum {\n\t\t\tsameASNum = \"same\"\n\t\t}\n\n\t\tdlogger.l.Printf(\"%s %d \\\"%s\\\" ip:%s mirror:%s%s %sasn:%d distance:%skm countries:%s\",\n\t\t\ttyp, statuscode, p.FileInfo.Path, p.IP, m.ID, fallback, sameASNum, m.Asnum, distance, countries)\n\t} else if statuscode == 404 {\n\t\tdlogger.l.Printf(\"%s 404 \\\"%s\\\" %s\", typ, p.FileInfo.Path, p.IP)\n\t} else if statuscode == 500 {\n\t\tmirrorID := \"unknown\"\n\t\tif len(p.MirrorList) > 0 {\n\t\t\tmirrorID = p.MirrorList[0].ID\n\t\t}\n\t\tdlogger.l.Printf(\"%s 500 \\\"%s\\\" ip:%s mirror:%s error:%s\", typ, p.FileInfo.Path, p.IP, mirrorID, err.Error())\n\t} else {\n\t\tdlogger.l.Printf(\"%s %d \\\"%s\\\" ip:%s error:%s\", typ, statuscode, p.FileInfo.Path, p.IP, err.Error())\n\t}\n}\n<commit_msg>Improve the logger output in debug and non-debug<commit_after>\/\/ Copyright (c) 2014 Ludovic Fauvet\n\/\/ Licensed under the MIT license\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/op\/go-logging\"\n\tstdlog \"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar (\n\tlog     = logging.MustGetLogger(\"main\")\n\trlogger RuntimeLogger\n\tdlogger DownloadsLogger\n)\n\ntype RuntimeLogger struct {\n\tf *os.File\n}\n\ntype DownloadsLogger struct {\n\tsync.RWMutex\n\tl *stdlog.Logger\n\tf *os.File\n}\n\n\/\/ ReloadLogs will reopen the logs to allow rotations\nfunc ReloadLogs() {\n\tReloadRuntimeLogs()\n\tReloadDownloadLogs()\n}\n\nfunc ReloadRuntimeLogs() {\n\tlogColor := false\n\n\tstat, _ := os.Stdout.Stat()\n\tif (stat.Mode() & os.ModeCharDevice) != 0 {\n\t\tlogColor = true \/\/TODO make it optionnal\n\t}\n\n\tif rlogger.f != nil {\n\t\trlogger.f.Close()\n\t} else {\n\t\trlogger.f = os.Stderr\n\t}\n\n\tif runLog != \"\" {\n\t\tvar err error\n\t\trlogger.f, err = os.OpenFile(runLog, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, \"Cannot open log file for writing\")\n\t\t\trlogger.f = os.Stderr\n\t\t} else {\n\t\t\tlogColor = false\n\t\t}\n\t}\n\n\tlogBackend := logging.NewLogBackend(rlogger.f, \"\", 0)\n\tlogBackend.Color = logColor\n\n\tlogging.SetBackend(logBackend)\n\n\tif debug {\n\t\tlogging.SetFormatter(logging.MustStringFormatter(\"%{shortfile:-20s}%{time:2006\/01\/02 15:04:05.000 MST} %{message}\"))\n\t\tlogging.SetLevel(logging.DEBUG, \"main\")\n\t} else {\n\t\tlogging.SetFormatter(logging.MustStringFormatter(\"%{time:2006\/01\/02 15:04:05.000 MST} %{message}\"))\n\t\tlogging.SetLevel(logging.INFO, \"main\")\n\t}\n}\n\nfunc ReloadDownloadLogs() {\n\tdlogger.Lock()\n\tdefer dlogger.Unlock()\n\n\tif GetConfig().LogDir == \"\" {\n\t\tif dlogger.f != nil {\n\t\t\tdlogger.f.Close()\n\t\t}\n\t\tdlogger.f = nil\n\t\tdlogger.l = nil\n\t\treturn\n\t}\n\n\tlogfile := GetConfig().LogDir + \"\/downloads.log\"\n\tcreateHeader := true\n\n\ts, err := os.Stat(logfile)\n\tif err == nil && s.Size() > 0 {\n\t\tcreateHeader = false\n\t}\n\n\tif dlogger.f != nil {\n\t\tdlogger.f.Close()\n\t}\n\tdlogger.f, err = os.OpenFile(logfile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)\n\n\tif err != nil {\n\t\tlog.Critical(\"Warning: cannot open log file %s\", logfile)\n\t\treturn\n\t}\n\n\tif createHeader {\n\t\tvar buf bytes.Buffer\n\t\thostname, _ := os.Hostname()\n\t\tfmt.Fprintf(&buf, \"# Log file created at: %s\\n\", time.Now().Format(\"2006\/01\/02 15:04:05\"))\n\t\tfmt.Fprintf(&buf, \"# Running on machine: %s\\n\", hostname)\n\t\tfmt.Fprintf(&buf, \"# Binary: Built with %s %s for %s\/%s\\n\", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH)\n\t\tdlogger.f.Write(buf.Bytes())\n\t}\n\n\tdlogger.l = stdlog.New(dlogger.f, \"\", stdlog.Ldate|stdlog.Lmicroseconds)\n}\n\n\/\/ This function will write a download result in the logs.\nfunc logDownload(typ string, statuscode int, p *MirrorlistPage, err error) {\n\tdlogger.RLock()\n\tdefer dlogger.RUnlock()\n\n\tif dlogger.l == nil {\n\t\t\/\/ Logs are disabled\n\t\treturn\n\t}\n\n\tif statuscode == 302 || statuscode == 200 {\n\t\tvar distance, countries string\n\t\tm := p.MirrorList[0]\n\t\tdistance = strconv.FormatFloat(float64(m.Distance), 'f', 2, 32)\n\t\tcountries = strings.Join(m.CountryFields, \",\")\n\t\tfallback := \"\"\n\t\tif p.Fallback == true {\n\t\t\tfallback = \" fallback:true\"\n\t\t}\n\t\tsameASNum := \"\"\n\t\tif m.Asnum > 0 && m.Asnum == p.ClientInfo.ASNum {\n\t\t\tsameASNum = \"same\"\n\t\t}\n\n\t\tdlogger.l.Printf(\"%s %d \\\"%s\\\" ip:%s mirror:%s%s %sasn:%d distance:%skm countries:%s\",\n\t\t\ttyp, statuscode, p.FileInfo.Path, p.IP, m.ID, fallback, sameASNum, m.Asnum, distance, countries)\n\t} else if statuscode == 404 {\n\t\tdlogger.l.Printf(\"%s 404 \\\"%s\\\" %s\", typ, p.FileInfo.Path, p.IP)\n\t} else if statuscode == 500 {\n\t\tmirrorID := \"unknown\"\n\t\tif len(p.MirrorList) > 0 {\n\t\t\tmirrorID = p.MirrorList[0].ID\n\t\t}\n\t\tdlogger.l.Printf(\"%s 500 \\\"%s\\\" ip:%s mirror:%s error:%s\", typ, p.FileInfo.Path, p.IP, mirrorID, err.Error())\n\t} else {\n\t\tdlogger.l.Printf(\"%s %d \\\"%s\\\" ip:%s error:%s\", typ, statuscode, p.FileInfo.Path, p.IP, err.Error())\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package contains the entry point for the commitfmt command.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/gcurtis\/commitfmt\/rules\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Fprintln(os.Stderr, \"You must provide a path to a file containing\"+\n\t\t\t\" the commit message.\")\n\t\tos.Exit(1)\n\t}\n\n\tpath := os.Args[1]\n\tbytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Couldn't open file \\\"%s\\\".\\n\", path)\n\t\tos.Exit(1)\n\t}\n\tmsg := string(bytes)\n\n\treport := runRules(msg)\n\tfmt.Println(report.string())\n\tif len(report.violations) > 0 {\n\t\tos.Exit(1)\n\t}\n}\n\n\/\/ runRules parses a commit message and then enforces every rule found in the\n\/\/ rules package.\nfunc runRules(msg string) (rep *report) {\n\tmsg = strings.TrimSpace(msg)\n\trep = &report{msg: msg}\n\tsubject, body := parseMsg(msg)\n\n\tfor _, rule := range rules.All {\n\t\tviolations := rule.Enforce(subject, body)\n\t\trep.append(violations...)\n\t}\n\n\treturn\n}\n\n\/\/ parseMsg parses a message by breaking it up into a subject and a body.\nfunc parseMsg(msg string) (subject string, body string) {\n\tsplit := strings.SplitN(msg, \"\\n\\n\", 2)\n\tsubject = split[0]\n\tif len(split) > 1 {\n\t\tbody = split[1]\n\t}\n\treturn\n}\n<commit_msg>Strip comment lines starting with #<commit_after>\/\/ Package contains the entry point for the commitfmt command.\npackage main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/gcurtis\/commitfmt\/rules\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Fprintln(os.Stderr, \"You must provide a path to a file containing\"+\n\t\t\t\" the commit message.\")\n\t\tos.Exit(1)\n\t}\n\n\tpath := os.Args[1]\n\tbytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Couldn't open file \\\"%s\\\".\\n\", path)\n\t\tos.Exit(1)\n\t}\n\tmsg := string(bytes)\n\n\treport := runRules(msg)\n\tfmt.Println(report.string())\n\tif len(report.violations) > 0 {\n\t\tos.Exit(1)\n\t}\n}\n\n\/\/ runRules parses a commit message and then enforces every rule found in the\n\/\/ rules package.\nfunc runRules(msg string) (rep *report) {\n\tmsg = strings.TrimSpace(msg)\n\trep = &report{msg: msg}\n\tsubject, body := parseMsg(msg)\n\n\tfor _, rule := range rules.All {\n\t\tviolations := rule.Enforce(subject, body)\n\t\trep.append(violations...)\n\t}\n\n\treturn\n}\n\n\/\/ parseMsg parses a message by breaking it up into a subject and a body.\nfunc parseMsg(msg string) (subject string, body string) {\n\tremComments := bytes.Buffer{}\n\tsplit := strings.SplitAfter(msg, \"\\n\")\n\tfor _, line := range split {\n\t\ttrim := strings.TrimSpace(line)\n\t\tif !strings.HasPrefix(trim, \"#\") {\n\t\t\tremComments.WriteString(line)\n\t\t}\n\t}\n\n\tsplit = strings.SplitN(strings.TrimSpace(remComments.String()), \"\\n\\n\", 2)\n\tsubject = split[0]\n\tif len(split) > 1 {\n\t\tbody = split[1]\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/line\/line-bot-sdk-go\/linebot\"\n)\n\nvar bot *linebot.Client\n\nfunc main() {\n\tvar err error\n\tbot, err = linebot.New(os.Getenv(\"ChannelSecret\"), os.Getenv(\"ChannelAccessToken\"))\n\tlog.Println(\"Bot:\", bot, \" err:\", err)\n\thttp.HandleFunc(\"\/callback\", callbackHandler)\n\tport := os.Getenv(\"PORT\")\n\taddr := fmt.Sprintf(\":%s\", port)\n\thttp.ListenAndServe(addr, nil)\n}\n\nfunc callbackHandler(w http.ResponseWriter, r *http.Request) {\n\tevents, err := bot.ParseRequest(r)\n\n\tresp, err := http.PostForm(\"https:\/\/hr.hiyes.tw:443\/getMessage.php\",\n        url.Values{\"mid\": {event.ReplyToken}, \"message\": {message.Text}})\n    if err != nil {\n        fmt.Println(err)\n    } else {\n        body, _ := ioutil.ReadAll(resp.Body)\n        fmt.Println(\"POST OK: \", string(body), resp)\n    }\n\n\n\n\tif err != nil {\n\t\tif err == linebot.ErrInvalidSignature {\n\t\t\tw.WriteHeader(400)\n\t\t} else {\n\t\t\tw.WriteHeader(500)\n\t\t}\n\t\treturn\n\t}\n\n\tfor _, event := range events {\n\t\tif event.Type == linebot.EventTypeMessage {\n\t\t\tswitch message := event.Message.(type) {\n\t\t\tcase *linebot.TextMessage:\n\t\t\t\tif _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(event.ReplyToken+\"---\"+message.Text+\" OK!\")).Do(); err != nil {\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>add URL<commit_after>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"net\/url\"\n\t\n\t\"github.com\/line\/line-bot-sdk-go\/linebot\"\n)\n\nvar bot *linebot.Client\n\nfunc main() {\n\tvar err error\n\tbot, err = linebot.New(os.Getenv(\"ChannelSecret\"), os.Getenv(\"ChannelAccessToken\"))\n\tlog.Println(\"Bot:\", bot, \" err:\", err)\n\thttp.HandleFunc(\"\/callback\", callbackHandler)\n\tport := os.Getenv(\"PORT\")\n\taddr := fmt.Sprintf(\":%s\", port)\n\thttp.ListenAndServe(addr, nil)\n}\n\nfunc callbackHandler(w http.ResponseWriter, r *http.Request) {\n\tevents, err := bot.ParseRequest(r)\n\n\tresp, err := http.PostForm(\"https:\/\/hr.hiyes.tw:443\/getMessage.php\",\n        url.Values{\"mid\": {event.ReplyToken}, \"message\": {message.Text}})\n    if err != nil {\n        fmt.Println(err)\n    } else {\n        body, _ := ioutil.ReadAll(resp.Body)\n        fmt.Println(\"POST OK: \", string(body), resp)\n    }\n\n\n\n\tif err != nil {\n\t\tif err == linebot.ErrInvalidSignature {\n\t\t\tw.WriteHeader(400)\n\t\t} else {\n\t\t\tw.WriteHeader(500)\n\t\t}\n\t\treturn\n\t}\n\n\tfor _, event := range events {\n\t\tif event.Type == linebot.EventTypeMessage {\n\t\t\tswitch message := event.Message.(type) {\n\t\t\tcase *linebot.TextMessage:\n\t\t\t\tif _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(event.ReplyToken+\"---\"+message.Text+\" OK!\")).Do(); err != nil {\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t_ \"net\/http\/pprof\"\n\t\"os\"\n\t\"os\/signal\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/redBorder\/rbforwarder\"\n\t\"github.com\/redBorder\/rbforwarder\/senders\/httpsender\"\n\t\"github.com\/x-cray\/logrus-prefixed-formatter\"\n)\n\nconst (\n\tdefaultQueueSize = 10000\n\tdefaultWorkers   = 1\n\tdefaultRetries   = 0\n\tdefaultBackoff   = 2\n)\n\nvar (\n\tconfigFile *string\n\tdebug      *bool\n\tlogger     *logrus.Entry\n)\n\nfunc init() {\n\tconfigFile = flag.String(\"config\", \"\", \"Config file\")\n\tdebug = flag.Bool(\"debug\", false, \"Show debug info\")\n\n\tflag.Parse()\n\n\tif len(*configFile) == 0 {\n\t\tfmt.Println(\"No config file provided\")\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tlog := logrus.New()\n\t\/\/ Show debug info if required\n\tif *debug {\n\t\tlog.Level = logrus.DebugLevel\n\t}\n\tlog.Formatter = new(prefixed.TextFormatter)\n\n\tlogger = log.WithFields(logrus.Fields{\n\t\t\"prefix\": \"k2http\",\n\t})\n}\n\nfunc main() {\n\n\t\/\/ Load the configuration from file\n\tconfigData, err := LoadConfigFile(*configFile)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\tlogger.Debug(\"Showing debug info\")\n\n\t\/\/ Capture ctrl-c\n\tctrlc := make(chan os.Signal, 1)\n\tsignal.Notify(ctrlc, os.Interrupt)\n\n\t\/\/ Parse the backend configuration\n\trbForwarderConfig := rbforwarder.Config{}\n\n\t\/\/ Get number of workers\n\tif workers, ok := configData.Backend[\"workers\"].(int); ok {\n\t\trbForwarderConfig.Workers = workers\n\t} else {\n\t\trbForwarderConfig.Workers = defaultWorkers\n\t}\n\n\t\/\/ Get number of retries per message\n\tif retries, ok := configData.Backend[\"retries\"].(int); ok {\n\t\trbForwarderConfig.Retries = retries\n\t} else {\n\t\trbForwarderConfig.Retries = defaultRetries\n\t}\n\n\t\/\/ Time to wait between retries\n\tif backoff, ok := configData.Backend[\"backoff\"].(int); ok {\n\t\trbForwarderConfig.Backoff = backoff\n\t} else {\n\t\trbForwarderConfig.Backoff = defaultBackoff\n\t}\n\n\t\/\/ Get queue size\n\tif queue, ok := configData.Backend[\"queue\"].(int); ok {\n\t\trbForwarderConfig.QueueSize = queue\n\t} else {\n\t\trbForwarderConfig.QueueSize = defaultQueueSize\n\t}\n\n\t\/\/ Get max message rate\n\tif maxMessages, ok := configData.Backend[\"max_messages\"].(int); ok {\n\t\trbForwarderConfig.MaxMessages = maxMessages\n\t}\n\n\t\/\/ Get max bytes rate\n\tif maxBytes, ok := configData.Backend[\"max_bytes\"].(int); ok {\n\t\trbForwarderConfig.MaxBytes = maxBytes\n\t}\n\n\t\/\/ Show debug info\n\tif *debug {\n\t\trbForwarderConfig.Debug = true\n\t}\n\n\t\/\/ Get the interval to show message rate\n\tif interval, ok := configData.Backend[\"showcounter\"].(int); ok {\n\t\trbForwarderConfig.ShowCounter = interval\n\t}\n\n\t\/\/ Create forwarder\n\tforwarder := rbforwarder.NewRBForwarder(rbForwarderConfig)\n\n\t\/\/ Initialize kafka\n\tkafka := new(KafkaConsumer)\n\tkafka.ParseKafkaConfig(configData.Kafka)\n\tkafka.backend = forwarder\n\n\t\/\/ Get the HTTP sender helper\n\thttpSenderHelper := httpsender.NewHelper(configData.HTTP)\n\tforwarder.SetSenderHelper(httpSenderHelper)\n\n\t\/\/ Start the backend\n\tforwarder.Start()\n\n\t\/\/ Wait for ctrl-c to close the consumer\n\tgo func() {\n\t\t<-ctrlc\n\t\tforwarder.Close()\n\t\tkafka.Close()\n\t}()\n\n\t\/\/ Start getting messages\n\tkafka.Start()\n\n\tdefer recoverPanic()\n}\n<commit_msg>Close Kafka Consumer prior to rbforwarder<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t_ \"net\/http\/pprof\"\n\t\"os\"\n\t\"os\/signal\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/redBorder\/rbforwarder\"\n\t\"github.com\/redBorder\/rbforwarder\/senders\/httpsender\"\n\t\"github.com\/x-cray\/logrus-prefixed-formatter\"\n)\n\nconst (\n\tdefaultQueueSize = 10000\n\tdefaultWorkers   = 1\n\tdefaultRetries   = 0\n\tdefaultBackoff   = 2\n)\n\nvar (\n\tconfigFile *string\n\tdebug      *bool\n\tlogger     *logrus.Entry\n)\n\nfunc init() {\n\tconfigFile = flag.String(\"config\", \"\", \"Config file\")\n\tdebug = flag.Bool(\"debug\", false, \"Show debug info\")\n\n\tflag.Parse()\n\n\tif len(*configFile) == 0 {\n\t\tfmt.Println(\"No config file provided\")\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tlog := logrus.New()\n\t\/\/ Show debug info if required\n\tif *debug {\n\t\tlog.Level = logrus.DebugLevel\n\t}\n\tlog.Formatter = new(prefixed.TextFormatter)\n\n\tlogger = log.WithFields(logrus.Fields{\n\t\t\"prefix\": \"k2http\",\n\t})\n}\n\nfunc main() {\n\n\t\/\/ Load the configuration from file\n\tconfigData, err := LoadConfigFile(*configFile)\n\tif err != nil {\n\t\tlogger.Fatal(err)\n\t}\n\n\tlogger.Debug(\"Showing debug info\")\n\n\t\/\/ Capture ctrl-c\n\tctrlc := make(chan os.Signal, 1)\n\tsignal.Notify(ctrlc, os.Interrupt)\n\n\t\/\/ Parse the backend configuration\n\trbForwarderConfig := rbforwarder.Config{}\n\n\t\/\/ Get number of workers\n\tif workers, ok := configData.Backend[\"workers\"].(int); ok {\n\t\trbForwarderConfig.Workers = workers\n\t} else {\n\t\trbForwarderConfig.Workers = defaultWorkers\n\t}\n\n\t\/\/ Get number of retries per message\n\tif retries, ok := configData.Backend[\"retries\"].(int); ok {\n\t\trbForwarderConfig.Retries = retries\n\t} else {\n\t\trbForwarderConfig.Retries = defaultRetries\n\t}\n\n\t\/\/ Time to wait between retries\n\tif backoff, ok := configData.Backend[\"backoff\"].(int); ok {\n\t\trbForwarderConfig.Backoff = backoff\n\t} else {\n\t\trbForwarderConfig.Backoff = defaultBackoff\n\t}\n\n\t\/\/ Get queue size\n\tif queue, ok := configData.Backend[\"queue\"].(int); ok {\n\t\trbForwarderConfig.QueueSize = queue\n\t} else {\n\t\trbForwarderConfig.QueueSize = defaultQueueSize\n\t}\n\n\t\/\/ Get max message rate\n\tif maxMessages, ok := configData.Backend[\"max_messages\"].(int); ok {\n\t\trbForwarderConfig.MaxMessages = maxMessages\n\t}\n\n\t\/\/ Get max bytes rate\n\tif maxBytes, ok := configData.Backend[\"max_bytes\"].(int); ok {\n\t\trbForwarderConfig.MaxBytes = maxBytes\n\t}\n\n\t\/\/ Show debug info\n\tif *debug {\n\t\trbForwarderConfig.Debug = true\n\t}\n\n\t\/\/ Get the interval to show message rate\n\tif interval, ok := configData.Backend[\"showcounter\"].(int); ok {\n\t\trbForwarderConfig.ShowCounter = interval\n\t}\n\n\t\/\/ Create forwarder\n\tforwarder := rbforwarder.NewRBForwarder(rbForwarderConfig)\n\n\t\/\/ Initialize kafka\n\tkafka := new(KafkaConsumer)\n\tkafka.ParseKafkaConfig(configData.Kafka)\n\tkafka.backend = forwarder\n\n\t\/\/ Get the HTTP sender helper\n\thttpSenderHelper := httpsender.NewHelper(configData.HTTP)\n\tforwarder.SetSenderHelper(httpSenderHelper)\n\n\t\/\/ Start the backend\n\tforwarder.Start()\n\n\t\/\/ Wait for ctrl-c to close the consumer\n\tgo func() {\n\t\t<-ctrlc\n\t\tkafka.Close()\n\t\tforwarder.Close()\n\t}()\n\n\t\/\/ Start getting messages\n\tkafka.Start()\n\n\tdefer recoverPanic()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"log\"\n)\n\nfunc main() {\n\tres, err := ping(\"google.com\", 5)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Min: %f ms\\n\", res.Min)\n\tlog.Printf(\"Avg: %f ms\\n\", res.Avg)\n\tlog.Printf(\"Max: %f ms\\n\", res.Max)\n\tlog.Printf(\"Mdev: %f ms\\n\", res.Mdev)\n}\n<commit_msg>Use a ticker to schedule pings<commit_after>package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n)\n\nfunc main() {\n\tticker := time.NewTicker(10 * time.Second)\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tlog.Println(\"ping google.com -c 5\")\n\t\t\tres, err := ping(\"google.com\", 5)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tlog.Printf(\"Min: %f ms\\n\", res.Min)\n\t\t\tlog.Printf(\"Avg: %f ms\\n\", res.Avg)\n\t\t\tlog.Printf(\"Max: %f ms\\n\", res.Max)\n\t\t\tlog.Printf(\"Mdev: %f ms\\n\", res.Mdev)\n\t\t}\n\t}()\n\n\tch := make(chan os.Signal)\n\tsignal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)\n\tlog.Printf(\"Received signal: %v\\n\", <-ch)\n\tlog.Println(\"Shutting down\")\n\tticker.Stop()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/RangelReale\/osin\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/buger\/goterm\"\n\t\"github.com\/docopt\/docopt.go\"\n\t\"github.com\/justinas\/alice\"\n\t\"github.com\/rcrowley\/goagain\"\n\t\"html\/template\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar log = logrus.New()\nvar authManager = AuthorisationManager{}\nvar config = Config{}\nvar templates = &template.Template{}\nvar analytics = RedisAnalyticsHandler{}\nvar profileFile = &os.File{}\nvar doMemoryProfile bool\nvar genericOsinStorage *RedisOsinStorageInterface\n\n\/\/ Generic system error\nconst (\n\tE_SYSTEM_ERROR          string = \"{\\\"status\\\": \\\"system error, please contact administrator\\\"}\"\n\tOAUTH_AUTH_CODE_TIMEOUT int    = 60 * 60\n\tOAUTH_PREFIX            string = \"oauth-data.\"\n)\n\n\/\/ Display introductory details\nfunc intro() {\n\tfmt.Print(\"\\n\\n\")\n\tfmt.Println(goterm.Bold(goterm.Color(\"Tyk.io Gateway API v1.0\", goterm.GREEN)))\n\tfmt.Println(goterm.Bold(goterm.Color(\"=======================\", goterm.GREEN)))\n\tfmt.Print(\"Copyright Jively Ltd. 2014\")\n\tfmt.Print(\"\\nhttp:\/\/www.tyk.io\\n\\n\")\n}\n\n\/\/ Display configuration options\nfunc displayConfig() {\n\tconfigTable := goterm.NewTable(0, 10, 5, ' ', 0)\n\tfmt.Fprintf(configTable, \"Listening on port:\\t%d\\n\", config.ListenPort)\n\n\tfmt.Println(configTable)\n\tfmt.Println(\"\")\n}\n\n\/\/ Create all globals and init connection handlers\nfunc setupGlobals() {\n\tif config.Storage.Type == \"memory\" {\n\t\tlog.Warning(\"Using in-memory storage. Warning: this is not scalable.\")\n\t\tauthManager = AuthorisationManager{\n\t\t\t&InMemoryStorageManager{\n\t\t\t\tmap[string]string{}}}\n\t} else if config.Storage.Type == \"redis\" {\n\t\tlog.Info(\"Using Redis storage manager.\")\n\t\tauthManager = AuthorisationManager{\n\t\t\t&RedisStorageManager{KeyPrefix: \"apikey-\"}}\n\n\t\tauthManager.Store.Connect()\n\t}\n\n\tif (config.EnableAnalytics == true) && (config.Storage.Type != \"redis\") {\n\t\tlog.Panic(\"Analytics requires Redis Storage backend, please enable Redis in the tyk.conf file.\")\n\t}\n\n\tif config.EnableAnalytics {\n\t\tAnalyticsStore := RedisStorageManager{KeyPrefix: \"analytics-\"}\n\t\tlog.Info(\"Setting up analytics DB connection\")\n\n\t\tif config.AnalyticsConfig.Type == \"csv\" {\n\t\t\tlog.Info(\"Using CSV cache purge\")\n\t\t\tanalytics = RedisAnalyticsHandler{\n\t\t\t\tStore: &AnalyticsStore,\n\t\t\t\tClean: &CSVPurger{&AnalyticsStore}}\n\n\t\t} else if config.AnalyticsConfig.Type == \"mongo\" {\n\t\t\tlog.Info(\"Using MongoDB cache purge\")\n\t\t\tanalytics = RedisAnalyticsHandler{\n\t\t\t\tStore: &AnalyticsStore,\n\t\t\t\tClean: &MongoPurger{&AnalyticsStore, nil}}\n\t\t}\n\n\t\tanalytics.Store.Connect()\n\t\tgo analytics.Clean.StartPurgeLoop(config.AnalyticsConfig.PurgeDelay)\n\t}\n\n\tgenericOsinStorage = MakeNewOsinServer()\n\n\ttemplateFile := fmt.Sprintf(\"%s\/error.json\", config.TemplatePath)\n\ttemplates = template.Must(template.ParseFiles(templateFile))\n}\n\n\/\/ Pull API Specs from configuration\nfunc getAPISpecs() []APISpec {\n\tvar APISpecs []APISpec\n\tthisAPILoader := APIDefinitionLoader{}\n\n\tif config.UseDBAppConfigs {\n\t\tlog.Info(\"Using App Configuration from Mongo DB\")\n\t\tAPISpecs = thisAPILoader.LoadDefinitionsFromMongo()\n\t} else {\n\t\tAPISpecs = thisAPILoader.LoadDefinitions(config.AppPath)\n\t}\n\n\treturn APISpecs\n}\n\n\/\/ Set up default Tyk control API endpoints - these are global, so need to be added first\nfunc loadAPIEndpoints(Muxer *http.ServeMux) {\n\t\/\/ set up main API handlers\n\tMuxer.HandleFunc(\"\/tyk\/keys\/create\", CheckIsAPIOwner(createKeyHandler))\n\tMuxer.HandleFunc(\"\/tyk\/keys\/\", CheckIsAPIOwner(keyHandler))\n\tMuxer.HandleFunc(\"\/tyk\/reload\/\", CheckIsAPIOwner(resetHandler))\n\tMuxer.HandleFunc(\"\/tyk\/oauth\/clients\/create\", CheckIsAPIOwner(createOauthClient))\n\tMuxer.HandleFunc(\"\/tyk\/oauth\/clients\/\", CheckIsAPIOwner(oAuthClientHandler))\n}\n\n\/\/ Create API-specific OAuth handlers and respective auth servers\nfunc addOAuthHandlers(spec APISpec, Muxer *http.ServeMux, test bool) {\n\tapiAuthorizePath := spec.Proxy.ListenPath + \"tyk\/oauth\/authorize-client\/\"\n\tclientAuthPath := spec.Proxy.ListenPath + \"oauth\/authorize\/\"\n\tclientAccessPath := spec.Proxy.ListenPath + \"oauth\/token\/\"\n\n\tserverConfig := osin.NewServerConfig()\n\tserverConfig.ErrorStatusCode = 403\n\tserverConfig.AllowedAccessTypes = spec.Oauth2Meta.AllowedAccessTypes\n\tserverConfig.AllowedAuthorizeTypes = spec.Oauth2Meta.AllowedAuthorizeTypes\n\n\tOAuthPrefix := OAUTH_PREFIX + spec.APIID + \".\"\n\tstorageManager := RedisStorageManager{KeyPrefix: OAuthPrefix}\n\tstorageManager.Connect()\n\tosinStorage := RedisOsinStorageInterface{&storageManager}\n\n\tif test {\n\t\tlog.Warning(\"Adding test client\")\n\t\ttestClient := osin.DefaultClient{\n\t\t\tId:          \"1234\",\n\t\t\tSecret:      \"aabbccdd\",\n\t\t\tRedirectUri: \"http:\/\/client.oauth.com\",\n\t\t}\n\t\tosinStorage.SetClient(testClient.Id, &testClient, false)\n\t\tlog.Warning(\"Test client added\")\n\t}\n\tosinServer := osin.NewServer(serverConfig, osinStorage)\n\tosinServer.AccessTokenGen = &AccessTokenGenTyk{}\n\n\toauthManager := OAuthManager{spec, osinServer}\n\toauthHandlers := OAuthHandlers{oauthManager}\n\n\tMuxer.HandleFunc(apiAuthorizePath, CheckIsAPIOwner(oauthHandlers.HandleGenerateAuthCodeData))\n\tMuxer.HandleFunc(clientAuthPath, oauthHandlers.HandleAuthorizePassthrough)\n\tMuxer.HandleFunc(clientAccessPath, oauthHandlers.HandleAccessRequest)\n}\n\n\/\/ Create the individual API (app) specs based on live configurations and assign middleware\nfunc loadApps(APISpecs []APISpec, Muxer *http.ServeMux) {\n\t\/\/ load the APi defs\n\tlog.Info(\"Loading API configurations.\")\n\n\tfor _, spec := range APISpecs {\n\t\t\/\/ Create a new handler for each API spec\n\t\tremote, err := url.Parse(spec.APIDefinition.Proxy.TargetURL)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Culdn't parse target URL\")\n\t\t\tlog.Error(err)\n\t\t}\n\n\t\tif spec.UseOauth2 {\n\t\t\taddOAuthHandlers(spec, Muxer, false)\n\t\t}\n\n\t\tproxy := TykNewSingleHostReverseProxy(remote)\n\t\tspec.target = remote\n\n\t\tproxyHandler := http.HandlerFunc(ProxyHandler(proxy, spec))\n\t\ttykMiddleware := TykMiddleware{spec, proxy}\n\n\t\tif spec.APIDefinition.UseKeylessAccess {\n\t\t\t\/\/ for KeyLessAccess we can't support rate limiting, versioning or access rules\n\t\t\tchain := alice.New().Then(proxyHandler)\n\t\t\tMuxer.Handle(spec.Proxy.ListenPath, chain)\n\n\t\t} else {\n\n\t\t\t\/\/ Select the keying method to use for setting session states\n\t\t\tvar keyCheck func(http.Handler) http.Handler\n\n\t\t\tif spec.APIDefinition.UseOauth2 {\n\t\t\t\t\/\/ Oauth2\n\t\t\t\tkeyCheck = CreateMiddleware(&Oauth2KeyExists{tykMiddleware}, tykMiddleware)\n\t\t\t} else if spec.APIDefinition.UseBasicAuth {\n\t\t\t\t\/\/ Basic Auth\n\t\t\t\tkeyCheck = CreateMiddleware(&BasicAuthKeyIsValid{tykMiddleware}, tykMiddleware)\n\t\t\t} else if spec.EnableSignatureChecking {\n\t\t\t\t\/\/ HMAC Auth\n\t\t\t\tkeyCheck = CreateMiddleware(&HMACMiddleware{tykMiddleware}, tykMiddleware)\n\t\t\t} else {\n\t\t\t\t\/\/ Auth key\n\t\t\t\tkeyCheck = CreateMiddleware(&AuthKey{tykMiddleware}, tykMiddleware)\n\t\t\t}\n\n\t\t\t\/\/ Use CreateMiddleware(&ModifiedMiddleware{tykMiddleware}, tykMiddleware)  to run custom middleware\n\t\t\tchain := alice.New(\n\t\t\t\tkeyCheck,\n\t\t\t\tCreateMiddleware(&KeyExpired{tykMiddleware}, tykMiddleware),\n\t\t\t\tCreateMiddleware(&VersionCheck{tykMiddleware}, tykMiddleware),\n\t\t\t\tCreateMiddleware(&AccessRightsCheck{tykMiddleware}, tykMiddleware),\n\t\t\t\tCreateMiddleware(&RateLimitAndQuotaCheck{tykMiddleware}, tykMiddleware)).Then(proxyHandler)\n\n\t\t\tMuxer.Handle(spec.Proxy.ListenPath, chain)\n\t\t}\n\n\t}\n}\n\n\/\/ ReloadURLStructure will create a new muxer, reload all the app configs for an\n\/\/ instance and then replace the DefaultServeMux with the new one, this enables a\n\/\/ reconfiguration to take place without stopping any requests from being handled.\nfunc ReloadURLStructure() {\n\tnewMuxes := http.NewServeMux()\n\tloadAPIEndpoints(newMuxes)\n\tspecs := getAPISpecs()\n\tloadApps(specs, newMuxes)\n\n\thttp.DefaultServeMux = newMuxes\n\tlog.Info(\"Reload complete\")\n}\n\nfunc init() {\n\tintro()\n\n\tusage := `Tyk API Gateway.\n\n\tUsage:\n\t\ttyk [options]\n\n\tOptions:\n\t\t-h --help      Show this screen\n\t\t--conf=FILE    Load a named configuration file\n\t\t--port=PORT    Listen on PORT (overrides confg file)\n\t\t--memprofile   Generate a memory profile\n\t\t--debug\t\t   Enable Debug output\n\n\t`\n\n\targuments, err := docopt.Parse(usage, nil, true, \"v1.0\", false)\n\tif err != nil {\n\t\tlog.Println(\"Error while parsing arguments.\")\n\t\tlog.Fatal(err)\n\t}\n\n\tfilename := \"\/etc\/tyk\/tyk.conf\"\n\tvalue, _ := arguments[\"--conf\"]\n\tif value != nil {\n\t\tlog.Info(fmt.Sprintf(\"Using %s for configuration\", value.(string)))\n\t\tfilename = arguments[\"--conf\"].(string)\n\t} else {\n\t\tlog.Info(\"No configuration file defined, will try to use default (.\/tyk.conf)\")\n\t}\n\n\tloadConfig(filename, &config)\n\n\tif config.Storage.Type != \"redis\" {\n\t\tlog.Fatal(\"Redis connection details not set, please ensure that the storage type is set to Redis and that the connection parameters are correct.\")\n\t}\n\n\tsetupGlobals()\n\n\tport, _ := arguments[\"--port\"]\n\tif port != nil {\n\t\tportNum, err := strconv.Atoi(port.(string))\n\t\tif err != nil {\n\t\t\tlog.Error(\"Port specified in flags must be a number!\")\n\t\t\tlog.Error(err)\n\t\t} else {\n\t\t\tconfig.ListenPort = portNum\n\t\t}\n\t}\n\n\tdoMemoryProfile, _ = arguments[\"--memprofile\"].(bool)\n\n\tdoDebug, _ := arguments[\"--debug\"]\n\tlog.Level = logrus.Info\n\tif doDebug == true {\n\t\tlog.Level = logrus.Debug\n\t\tlog.Debug(\"Enabling debug-level output\")\n\t}\n\n}\n\nfunc main() {\n\tdisplayConfig()\n\n\tif doMemoryProfile {\n\t\tlog.Info(\"Memory profiling active\")\n\t\tprofileFile, _ = os.Create(\"tyk.mprof\")\n\t\tdefer profileFile.Close()\n\t}\n\n\ttargetPort := fmt.Sprintf(\":%d\", config.ListenPort)\n\tloadAPIEndpoints(http.DefaultServeMux)\n\n\t\/\/ Handle reload when SIGUSR2 is received\n\tl, err := goagain.Listener()\n\tif nil != err {\n\n\t\t\/\/ Listen on a TCP or a UNIX domain socket (TCP here).\n\t\tl, err = net.Listen(\"tcp\", targetPort)\n\t\tif nil != err {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tlog.Println(\"Listening on\", l.Addr())\n\n\t\t\/\/ Accept connections in a new goroutine.\n\t\tspecs := getAPISpecs()\n\t\tloadApps(specs, http.DefaultServeMux)\n\t\tgo http.Serve(l, nil)\n\n\t} else {\n\n\t\t\/\/ Resume accepting connections in a new goroutine.\n\t\tlog.Println(\"Resuming listening on\", l.Addr())\n\t\tspecs := getAPISpecs()\n\t\tloadApps(specs, http.DefaultServeMux)\n\t\tgo http.Serve(l, nil)\n\n\t\t\/\/ Kill the parent, now that the child has started successfully.\n\t\tif err := goagain.Kill(); nil != err {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t}\n\n\t\/\/ Block the main goroutine awaiting signals.\n\tif _, err := goagain.Wait(l); nil != err {\n\t\tlog.Fatalln(err)\n\t}\n\n\t\/\/ Do whatever's necessary to ensure a graceful exit like waiting for\n\t\/\/ goroutines to terminate or a channel to become closed.\n\t\/\/\n\t\/\/ In this case, we'll simply stop listening and wait one second.\n\tif err := l.Close(); nil != err {\n\t\tlog.Fatalln(err)\n\t}\n\ttime.Sleep(1e9)\n}\n<commit_msg>Update logrus usage to latest API<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/RangelReale\/osin\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/buger\/goterm\"\n\t\"github.com\/docopt\/docopt.go\"\n\t\"github.com\/justinas\/alice\"\n\t\"github.com\/rcrowley\/goagain\"\n\t\"html\/template\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar log = logrus.New()\nvar authManager = AuthorisationManager{}\nvar config = Config{}\nvar templates = &template.Template{}\nvar analytics = RedisAnalyticsHandler{}\nvar profileFile = &os.File{}\nvar doMemoryProfile bool\nvar genericOsinStorage *RedisOsinStorageInterface\n\n\/\/ Generic system error\nconst (\n\tE_SYSTEM_ERROR          string = \"{\\\"status\\\": \\\"system error, please contact administrator\\\"}\"\n\tOAUTH_AUTH_CODE_TIMEOUT int    = 60 * 60\n\tOAUTH_PREFIX            string = \"oauth-data.\"\n)\n\n\/\/ Display introductory details\nfunc intro() {\n\tfmt.Print(\"\\n\\n\")\n\tfmt.Println(goterm.Bold(goterm.Color(\"Tyk.io Gateway API v1.0\", goterm.GREEN)))\n\tfmt.Println(goterm.Bold(goterm.Color(\"=======================\", goterm.GREEN)))\n\tfmt.Print(\"Copyright Jively Ltd. 2014\")\n\tfmt.Print(\"\\nhttp:\/\/www.tyk.io\\n\\n\")\n}\n\n\/\/ Display configuration options\nfunc displayConfig() {\n\tconfigTable := goterm.NewTable(0, 10, 5, ' ', 0)\n\tfmt.Fprintf(configTable, \"Listening on port:\\t%d\\n\", config.ListenPort)\n\n\tfmt.Println(configTable)\n\tfmt.Println(\"\")\n}\n\n\/\/ Create all globals and init connection handlers\nfunc setupGlobals() {\n\tif config.Storage.Type == \"memory\" {\n\t\tlog.Warning(\"Using in-memory storage. Warning: this is not scalable.\")\n\t\tauthManager = AuthorisationManager{\n\t\t\t&InMemoryStorageManager{\n\t\t\t\tmap[string]string{}}}\n\t} else if config.Storage.Type == \"redis\" {\n\t\tlog.Info(\"Using Redis storage manager.\")\n\t\tauthManager = AuthorisationManager{\n\t\t\t&RedisStorageManager{KeyPrefix: \"apikey-\"}}\n\n\t\tauthManager.Store.Connect()\n\t}\n\n\tif (config.EnableAnalytics == true) && (config.Storage.Type != \"redis\") {\n\t\tlog.Panic(\"Analytics requires Redis Storage backend, please enable Redis in the tyk.conf file.\")\n\t}\n\n\tif config.EnableAnalytics {\n\t\tAnalyticsStore := RedisStorageManager{KeyPrefix: \"analytics-\"}\n\t\tlog.Info(\"Setting up analytics DB connection\")\n\n\t\tif config.AnalyticsConfig.Type == \"csv\" {\n\t\t\tlog.Info(\"Using CSV cache purge\")\n\t\t\tanalytics = RedisAnalyticsHandler{\n\t\t\t\tStore: &AnalyticsStore,\n\t\t\t\tClean: &CSVPurger{&AnalyticsStore}}\n\n\t\t} else if config.AnalyticsConfig.Type == \"mongo\" {\n\t\t\tlog.Info(\"Using MongoDB cache purge\")\n\t\t\tanalytics = RedisAnalyticsHandler{\n\t\t\t\tStore: &AnalyticsStore,\n\t\t\t\tClean: &MongoPurger{&AnalyticsStore, nil}}\n\t\t}\n\n\t\tanalytics.Store.Connect()\n\t\tgo analytics.Clean.StartPurgeLoop(config.AnalyticsConfig.PurgeDelay)\n\t}\n\n\tgenericOsinStorage = MakeNewOsinServer()\n\n\ttemplateFile := fmt.Sprintf(\"%s\/error.json\", config.TemplatePath)\n\ttemplates = template.Must(template.ParseFiles(templateFile))\n}\n\n\/\/ Pull API Specs from configuration\nfunc getAPISpecs() []APISpec {\n\tvar APISpecs []APISpec\n\tthisAPILoader := APIDefinitionLoader{}\n\n\tif config.UseDBAppConfigs {\n\t\tlog.Info(\"Using App Configuration from Mongo DB\")\n\t\tAPISpecs = thisAPILoader.LoadDefinitionsFromMongo()\n\t} else {\n\t\tAPISpecs = thisAPILoader.LoadDefinitions(config.AppPath)\n\t}\n\n\treturn APISpecs\n}\n\n\/\/ Set up default Tyk control API endpoints - these are global, so need to be added first\nfunc loadAPIEndpoints(Muxer *http.ServeMux) {\n\t\/\/ set up main API handlers\n\tMuxer.HandleFunc(\"\/tyk\/keys\/create\", CheckIsAPIOwner(createKeyHandler))\n\tMuxer.HandleFunc(\"\/tyk\/keys\/\", CheckIsAPIOwner(keyHandler))\n\tMuxer.HandleFunc(\"\/tyk\/reload\/\", CheckIsAPIOwner(resetHandler))\n\tMuxer.HandleFunc(\"\/tyk\/oauth\/clients\/create\", CheckIsAPIOwner(createOauthClient))\n\tMuxer.HandleFunc(\"\/tyk\/oauth\/clients\/\", CheckIsAPIOwner(oAuthClientHandler))\n}\n\n\/\/ Create API-specific OAuth handlers and respective auth servers\nfunc addOAuthHandlers(spec APISpec, Muxer *http.ServeMux, test bool) {\n\tapiAuthorizePath := spec.Proxy.ListenPath + \"tyk\/oauth\/authorize-client\/\"\n\tclientAuthPath := spec.Proxy.ListenPath + \"oauth\/authorize\/\"\n\tclientAccessPath := spec.Proxy.ListenPath + \"oauth\/token\/\"\n\n\tserverConfig := osin.NewServerConfig()\n\tserverConfig.ErrorStatusCode = 403\n\tserverConfig.AllowedAccessTypes = spec.Oauth2Meta.AllowedAccessTypes\n\tserverConfig.AllowedAuthorizeTypes = spec.Oauth2Meta.AllowedAuthorizeTypes\n\n\tOAuthPrefix := OAUTH_PREFIX + spec.APIID + \".\"\n\tstorageManager := RedisStorageManager{KeyPrefix: OAuthPrefix}\n\tstorageManager.Connect()\n\tosinStorage := RedisOsinStorageInterface{&storageManager}\n\n\tif test {\n\t\tlog.Warning(\"Adding test client\")\n\t\ttestClient := osin.DefaultClient{\n\t\t\tId:          \"1234\",\n\t\t\tSecret:      \"aabbccdd\",\n\t\t\tRedirectUri: \"http:\/\/client.oauth.com\",\n\t\t}\n\t\tosinStorage.SetClient(testClient.Id, &testClient, false)\n\t\tlog.Warning(\"Test client added\")\n\t}\n\tosinServer := osin.NewServer(serverConfig, osinStorage)\n\tosinServer.AccessTokenGen = &AccessTokenGenTyk{}\n\n\toauthManager := OAuthManager{spec, osinServer}\n\toauthHandlers := OAuthHandlers{oauthManager}\n\n\tMuxer.HandleFunc(apiAuthorizePath, CheckIsAPIOwner(oauthHandlers.HandleGenerateAuthCodeData))\n\tMuxer.HandleFunc(clientAuthPath, oauthHandlers.HandleAuthorizePassthrough)\n\tMuxer.HandleFunc(clientAccessPath, oauthHandlers.HandleAccessRequest)\n}\n\n\/\/ Create the individual API (app) specs based on live configurations and assign middleware\nfunc loadApps(APISpecs []APISpec, Muxer *http.ServeMux) {\n\t\/\/ load the APi defs\n\tlog.Info(\"Loading API configurations.\")\n\n\tfor _, spec := range APISpecs {\n\t\t\/\/ Create a new handler for each API spec\n\t\tremote, err := url.Parse(spec.APIDefinition.Proxy.TargetURL)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Culdn't parse target URL\")\n\t\t\tlog.Error(err)\n\t\t}\n\n\t\tif spec.UseOauth2 {\n\t\t\taddOAuthHandlers(spec, Muxer, false)\n\t\t}\n\n\t\tproxy := TykNewSingleHostReverseProxy(remote)\n\t\tspec.target = remote\n\n\t\tproxyHandler := http.HandlerFunc(ProxyHandler(proxy, spec))\n\t\ttykMiddleware := TykMiddleware{spec, proxy}\n\n\t\tif spec.APIDefinition.UseKeylessAccess {\n\t\t\t\/\/ for KeyLessAccess we can't support rate limiting, versioning or access rules\n\t\t\tchain := alice.New().Then(proxyHandler)\n\t\t\tMuxer.Handle(spec.Proxy.ListenPath, chain)\n\n\t\t} else {\n\n\t\t\t\/\/ Select the keying method to use for setting session states\n\t\t\tvar keyCheck func(http.Handler) http.Handler\n\n\t\t\tif spec.APIDefinition.UseOauth2 {\n\t\t\t\t\/\/ Oauth2\n\t\t\t\tkeyCheck = CreateMiddleware(&Oauth2KeyExists{tykMiddleware}, tykMiddleware)\n\t\t\t} else if spec.APIDefinition.UseBasicAuth {\n\t\t\t\t\/\/ Basic Auth\n\t\t\t\tkeyCheck = CreateMiddleware(&BasicAuthKeyIsValid{tykMiddleware}, tykMiddleware)\n\t\t\t} else if spec.EnableSignatureChecking {\n\t\t\t\t\/\/ HMAC Auth\n\t\t\t\tkeyCheck = CreateMiddleware(&HMACMiddleware{tykMiddleware}, tykMiddleware)\n\t\t\t} else {\n\t\t\t\t\/\/ Auth key\n\t\t\t\tkeyCheck = CreateMiddleware(&AuthKey{tykMiddleware}, tykMiddleware)\n\t\t\t}\n\n\t\t\t\/\/ Use CreateMiddleware(&ModifiedMiddleware{tykMiddleware}, tykMiddleware)  to run custom middleware\n\t\t\tchain := alice.New(\n\t\t\t\tkeyCheck,\n\t\t\t\tCreateMiddleware(&KeyExpired{tykMiddleware}, tykMiddleware),\n\t\t\t\tCreateMiddleware(&VersionCheck{tykMiddleware}, tykMiddleware),\n\t\t\t\tCreateMiddleware(&AccessRightsCheck{tykMiddleware}, tykMiddleware),\n\t\t\t\tCreateMiddleware(&RateLimitAndQuotaCheck{tykMiddleware}, tykMiddleware)).Then(proxyHandler)\n\n\t\t\tMuxer.Handle(spec.Proxy.ListenPath, chain)\n\t\t}\n\n\t}\n}\n\n\/\/ ReloadURLStructure will create a new muxer, reload all the app configs for an\n\/\/ instance and then replace the DefaultServeMux with the new one, this enables a\n\/\/ reconfiguration to take place without stopping any requests from being handled.\nfunc ReloadURLStructure() {\n\tnewMuxes := http.NewServeMux()\n\tloadAPIEndpoints(newMuxes)\n\tspecs := getAPISpecs()\n\tloadApps(specs, newMuxes)\n\n\thttp.DefaultServeMux = newMuxes\n\tlog.Info(\"Reload complete\")\n}\n\nfunc init() {\n\tintro()\n\n\tusage := `Tyk API Gateway.\n\n\tUsage:\n\t\ttyk [options]\n\n\tOptions:\n\t\t-h --help      Show this screen\n\t\t--conf=FILE    Load a named configuration file\n\t\t--port=PORT    Listen on PORT (overrides confg file)\n\t\t--memprofile   Generate a memory profile\n\t\t--debug\t\t   Enable Debug output\n\n\t`\n\n\targuments, err := docopt.Parse(usage, nil, true, \"v1.0\", false)\n\tif err != nil {\n\t\tlog.Println(\"Error while parsing arguments.\")\n\t\tlog.Fatal(err)\n\t}\n\n\tfilename := \"\/etc\/tyk\/tyk.conf\"\n\tvalue, _ := arguments[\"--conf\"]\n\tif value != nil {\n\t\tlog.Info(fmt.Sprintf(\"Using %s for configuration\", value.(string)))\n\t\tfilename = arguments[\"--conf\"].(string)\n\t} else {\n\t\tlog.Info(\"No configuration file defined, will try to use default (.\/tyk.conf)\")\n\t}\n\n\tloadConfig(filename, &config)\n\n\tif config.Storage.Type != \"redis\" {\n\t\tlog.Fatal(\"Redis connection details not set, please ensure that the storage type is set to Redis and that the connection parameters are correct.\")\n\t}\n\n\tsetupGlobals()\n\n\tport, _ := arguments[\"--port\"]\n\tif port != nil {\n\t\tportNum, err := strconv.Atoi(port.(string))\n\t\tif err != nil {\n\t\t\tlog.Error(\"Port specified in flags must be a number!\")\n\t\t\tlog.Error(err)\n\t\t} else {\n\t\t\tconfig.ListenPort = portNum\n\t\t}\n\t}\n\n\tdoMemoryProfile, _ = arguments[\"--memprofile\"].(bool)\n\n\tdoDebug, _ := arguments[\"--debug\"]\n\tlog.Level = logrus.InfoLevel\n\tif doDebug == true {\n\t\tlog.Level = logrus.DebugLevel\n\t\tlog.Debug(\"Enabling debug-level output\")\n\t}\n\n}\n\nfunc main() {\n\tdisplayConfig()\n\n\tif doMemoryProfile {\n\t\tlog.Info(\"Memory profiling active\")\n\t\tprofileFile, _ = os.Create(\"tyk.mprof\")\n\t\tdefer profileFile.Close()\n\t}\n\n\ttargetPort := fmt.Sprintf(\":%d\", config.ListenPort)\n\tloadAPIEndpoints(http.DefaultServeMux)\n\n\t\/\/ Handle reload when SIGUSR2 is received\n\tl, err := goagain.Listener()\n\tif nil != err {\n\n\t\t\/\/ Listen on a TCP or a UNIX domain socket (TCP here).\n\t\tl, err = net.Listen(\"tcp\", targetPort)\n\t\tif nil != err {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tlog.Println(\"Listening on\", l.Addr())\n\n\t\t\/\/ Accept connections in a new goroutine.\n\t\tspecs := getAPISpecs()\n\t\tloadApps(specs, http.DefaultServeMux)\n\t\tgo http.Serve(l, nil)\n\n\t} else {\n\n\t\t\/\/ Resume accepting connections in a new goroutine.\n\t\tlog.Println(\"Resuming listening on\", l.Addr())\n\t\tspecs := getAPISpecs()\n\t\tloadApps(specs, http.DefaultServeMux)\n\t\tgo http.Serve(l, nil)\n\n\t\t\/\/ Kill the parent, now that the child has started successfully.\n\t\tif err := goagain.Kill(); nil != err {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t}\n\n\t\/\/ Block the main goroutine awaiting signals.\n\tif _, err := goagain.Wait(l); nil != err {\n\t\tlog.Fatalln(err)\n\t}\n\n\t\/\/ Do whatever's necessary to ensure a graceful exit like waiting for\n\t\/\/ goroutines to terminate or a channel to become closed.\n\t\/\/\n\t\/\/ In this case, we'll simply stop listening and wait one second.\n\tif err := l.Close(); nil != err {\n\t\tlog.Fatalln(err)\n\t}\n\ttime.Sleep(1e9)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"os\"\n\n\t\"github.com\/yapdns\/yapdns-client\/beater\"\n\t\"github.com\/yapdns\/yapdns-client\/outputs\/http\"\n\t\"github.com\/elastic\/beats\/libbeat\/beat\"\n\t\"github.com\/elastic\/beats\/libbeat\/outputs\"\n)\n\nvar Name = \"filebeat\"\n\n\/\/ The basic model of execution:\n\/\/ - prospector: finds files in paths\/globs to harvest, starts harvesters\n\/\/ - harvester: reads a file, sends events to the spooler\n\/\/ - spooler: buffers events until ready to flush to the publisher\n\/\/ - publisher: writes to the network, notifies registrar\n\/\/ - registrar: records positions of files read\n\/\/ Finally, prospector uses the registrar information, on restart, to\n\/\/ determine where in each file to restart a harvester.\n\nfunc init() {\n\toutputs.RegisterOutputPlugin(\"http\", http.New)\n}\n\nfunc main() {\n\tif err := beat.Run(Name, \"\", beater.New()); err != nil {\n\t\tos.Exit(1)\n\t}\n}\n<commit_msg>create libbeat output plugin the nice way<commit_after>package main\n\nimport (\n\t\"os\"\n\n\t\"github.com\/yapdns\/yapdns-client\/beater\"\n\t\"github.com\/elastic\/beats\/libbeat\/beat\"\n\t_ \"github.com\/yapdns\/yapdns-client\/outputs\/http\"\n)\n\nvar Name = \"filebeat\"\n\n\/\/ The basic model of execution:\n\/\/ - prospector: finds files in paths\/globs to harvest, starts harvesters\n\/\/ - harvester: reads a file, sends events to the spooler\n\/\/ - spooler: buffers events until ready to flush to the publisher\n\/\/ - publisher: writes to the network, notifies registrar\n\/\/ - registrar: records positions of files read\n\/\/ Finally, prospector uses the registrar information, on restart, to\n\/\/ determine where in each file to restart a harvester.\n\nfunc main() {\n\tif err := beat.Run(Name, \"\", beater.New()); err != nil {\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\nimport (\n    \"bytes\"\n    \"crypto\/sha1\"\n    \"encoding\/hex\"\n    \"flag\"\n    \"fmt\"\n    \"image\"\n    \"image\/gif\"\n    \"image\/png\"\n    \"image\/jpeg\"\n    \"io\"\n    \"io\/ioutil\"\n    \"net\/http\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n    \"github.com\/nfnt\/resize\"\n    \"github.com\/bradfitz\/gomemcache\/memcache\"\n)\n\ntype JobDescription struct {\n    Url string\n    Key string\n    Format string\n    MaxHeight uint64\n    MaxWidth uint64\n}\n\nvar (\n    globalMaxWidth uint64\n    globalMaxHeight uint64\n    maxInDim uint64\n    maxInSize uint64\n    errorPicName string\n    standByPicName string\n    listenAddr string\n    memcacheAddr string\n    jpegQuality int\n\n    marshaledTimeLength int\n    errorPic image.Image\n    standByPic image.Image\n    mc *memcache.Client\n    hc http.Client\n    workChan chan *JobDescription = make(chan *JobDescription, 100)\n)\nvar formatsMime = map[string]string{\n        \"gif\": \"image\/gif\",\n        \"png\": \"image\/png\",\n        \"jpg\": \"image\/jpeg\",\n}\n\nfunc init() {\n    flag.Uint64Var(&globalMaxWidth, \"maxwidth\", 512, \"max thumbnail width in pixels\")\n    flag.Uint64Var(&globalMaxHeight, \"maxheight\", 512, \"max thumbnail height in pixels\")\n    flag.Uint64Var(&maxInDim, \"maxindim\", 1024, \"max input image height or width in pixels\")\n    flag.Uint64Var(&maxInSize, \"maxinsize\", 20*1024*1024, \"max input image size in bytes\")\n    flag.IntVar(&jpegQuality, \"quality\", 80, \"jpeg quality, 0 to 100\")\n    flag.StringVar(&errorPicName, \"errorpic\", \"\", \"error picture\")\n    flag.StringVar(&memcacheAddr, \"memcache\", \"127.0.0.1:11211\", \"comma-separated list of memcache servers\")\n    flag.StringVar(&listenAddr, \"listen\", \"127.0.0.1:8080\", \"address and port to listen on\")\n}\n\nfunc parseOrDefault(s string, min uint64, max uint64, def uint64) uint64 {\n    if s == \"\" {\n        return def\n    }\n    n, err := strconv.ParseUint(s, 10, 64)\n    switch {\n        case err != nil:\n            return def\n        case n < min:\n            return min\n        case n > max:\n            return max\n    }\n    return n\n}\n\nfunc encodeImage(w io.Writer, img image.Image, fmt string) error {\n    switch fmt {\n        case \"png\": return png.Encode(w, img)\n        case \"gif\": return gif.Encode(w, img, &gif.Options{NumColors: 256})\n    }\n    return jpeg.Encode(w, img, &jpeg.Options{Quality: jpegQuality} )\n}\n\nfunc renderThumbnail(img image.Image, key string, lastMod time.Time,\n                        maxWidth uint64, maxHeight uint64, fmt string) {\n    thumb := resize.Thumbnail(uint(maxWidth), uint(maxHeight), img, resize.NearestNeighbor)\n    var outbuf bytes.Buffer\n    encodeImage(&outbuf, thumb, fmt)\n    thumbHash := sha1.New()\n    bytes.NewReader(outbuf.Bytes()).WriteTo(thumbHash)\n    etag := hex.EncodeToString(thumbHash.Sum(nil))\n    if len(etag) != 40 { return }\n    saveThumb(key, []byte(etag), []byte{}, lastMod, outbuf.Bytes())\n    return\n}\n\nfunc thumbHandler(w http.ResponseWriter, r *http.Request) {\n    if r.Method != \"GET\" {\n        http.Error(w,\"Method not allowed\", http.StatusMethodNotAllowed)\n        return\n    }\n    r.ParseForm()\n    var maxWidth uint64\n    var maxHeight uint64\n    argUrl := r.Form.Get(\"img\")\n    argFmt := r.Form.Get(\"fmt\")\n    mimeType,ok := formatsMime[argFmt]\n    if !ok {\n        argFmt = \"png\"\n        mimeType = formatsMime[\"png\"]\n    }\n    hdr := w.Header()\n    hdr[\"Content-Type\"] = []string{mimeType}\n    argMax := r.Form.Get(\"max\")\n    if argMax != \"\" {\n        maxWidth = parseOrDefault(argMax, 1, globalMaxWidth, globalMaxHeight)\n        maxHeight = parseOrDefault(argMax, 1, globalMaxHeight, globalMaxHeight)\n    } else {\n        maxWidth = parseOrDefault(r.Form.Get(\"mx\"), 1, globalMaxWidth, globalMaxWidth)\n        maxHeight = parseOrDefault(r.Form.Get(\"my\"), 1, globalMaxHeight, globalMaxHeight)\n    }\n    if mc != nil {\n        h := sha1.New()\n        io.WriteString(h, argUrl)\n        key := fmt.Sprintf(\"%s-%dx%d-%s\", argFmt, maxWidth, maxHeight, hex.EncodeToString(h.Sum(nil)))[:250]\n        item, err := mc.Get(key)\n        if err == nil { \n            if len(item.Value) >= 86 {\n                thumbEtag := item.Value[0:40]\n                \/\/originalEtag := item.Value[40:80]\n                lastModBytes := item.Value[80:80+marshaledTimeLength]\n                lastMod := time.Time{}\n                lastMod.UnmarshalBinary(lastModBytes)\n                dataBytes := item.Value[80+marshaledTimeLength:]\n                hdr.Set(\"Last-Modified\", lastMod.Format(http.TimeFormat))\n                hdr.Set(\"Etag\", string(thumbEtag))\n                hdr.Set(\"Content-Length\", strconv.Itoa(len(dataBytes)))\n                w.Write(dataBytes)\n                return\n            }\n        } else if err == memcache.ErrCacheMiss {\n            err = mc.Add(&memcache.Item{Key: key, Value: []byte(\"X\")})\n            if err != memcache.ErrNotStored {\n                workChan <- &JobDescription{\n                    Url: argUrl, Key: key, Format: argFmt,\n                    MaxHeight: maxHeight, MaxWidth: maxWidth,\n                }\n            }\n        }\n    }\n\n    thumb := resize.Thumbnail(uint(maxWidth), uint(maxHeight), standByPic, resize.NearestNeighbor)\n    hdr.Set(\"Last-Modified\", time.Now().UTC().Format(http.TimeFormat))\n    hdr.Set(\"Cache-control\", \"max-age=5, public\")\n    hdr.Set(\"Etag\", fmt.Sprintf(\"standby-%d-%d-%s\", maxWidth, maxHeight, argFmt))\n    encodeImage(w, thumb, argFmt)\n    return\n}\n\nfunc saveThumb(Key string, Etag []byte, OriginEtag []byte, LastMod time.Time, data []byte) error {\n    if mc != nil {\n        value := make([]byte, 0, 128)\n        lastModBytes, _ := LastMod.MarshalBinary()\n        OriginEtag := []byte(\"0000000000000000000000000000000000000000\") \/\/ not used yet\n        value = append(value, Etag...)\n        value = append(value, OriginEtag...)\n        value = append(value, lastModBytes...)\n        value = append(value, data...)\n        return mc.Set(&memcache.Item{Key: Key, Value: value })\n    }\n    return nil\n}\n\nfunc renderWorker() {\n    for job := range workChan {\n        closeBody := false\n        req, err := http.NewRequest(\"GET\", job.Url, nil)\n        if err != nil { goto Error }\n        req.Header.Set(\"User-Agent\", \"bnw-thumb\/1.0 (http:\/\/github.com\/stiletto\/bnw-thumb)\")\n        resp, err := hc.Do(req)\n        if err != nil { goto Error }\n        closeBody = true\n        if resp.StatusCode != 200 || uint64(resp.ContentLength) > maxInSize { goto Error }\n        bytebuf, err := ioutil.ReadAll(resp.Body)\n        if err != nil { goto Error }\n        bufreader := bytes.NewReader(bytebuf)\n        config, _, err := image.DecodeConfig(bufreader)\n        if err != nil || uint64(config.Width) > maxInDim || uint64(config.Height) > maxInDim { goto Error }\n        bufreader.Seek(0,0)\n        img, _, err := image.Decode(bufreader)\n        if err != nil { goto Error }\n        if closeBody { resp.Body.Close() }\n        renderThumbnail(img, job.Key, time.Now(), job.MaxWidth, job.MaxHeight, job.Format)\n        return\n    Error:\n        if closeBody { resp.Body.Close() }\n        renderThumbnail(errorPic, job.Key, time.Now(), job.MaxWidth, job.MaxHeight, job.Format)\n        return\n    }\n}\n\nfunc loadPicOrEmpty(name string) image.Image {\n    var pic image.Image\n    if name != \"\" {\n        var fmtinfo string\n        img, err := os.Open(name)\n        defer img.Close()\n        if err == nil {\n            pic, fmtinfo, err = image.Decode(img)\n        }\n        if err != nil {\n            pic = nil\n            fmt.Fprintf(os.Stderr, \"Unable to load picture %s: %s\\n\", name, err)\n        } else {\n            ebounds := pic.Bounds()\n            fmt.Fprintf(os.Stderr, \"Loaded picture %s (%s, %dx%d)\\n\",\n                name, fmtinfo, ebounds.Max.X-ebounds.Min.X,\n                ebounds.Max.Y-ebounds.Min.Y)\n        }\n    }\n    if pic == nil {\n        pic = image.NewRGBA(image.Rect(0, 0, 1, 1))\n    }\n    return pic\n}\n\nfunc main() {\n    flag.Parse()\n    mc = nil\n    if memcacheAddr != \"\" {\n        mc = memcache.New(strings.Split(memcacheAddr, \",\")...)\n    } else {\n        fmt.Fprintf(os.Stderr, \"Warning: Memcache is required for bnw-thumb to work.\\n\")\n        fmt.Fprintf(os.Stderr, \"Warning: Without memcache no thumbnails will be actually generated. Use only for testing.\\n\")\n    }\n    marshaledNow, _ := time.Now().MarshalBinary()\n    \/\/ we know that time.Time always has the same length when marshaled\n    \/\/ but this is kinda implementation dependant hack\n    marshaledTimeLength = len(marshaledNow)\n    errorPic = loadPicOrEmpty(errorPicName)\n    standByPic = loadPicOrEmpty(standByPicName)\n    http.HandleFunc(\"\/\", thumbHandler)\n    http.ListenAndServe(listenAddr, nil)\n}\n<commit_msg>Somewhat working<commit_after>package main\nimport (\n    \"bytes\"\n    \"crypto\/sha1\"\n    \"encoding\/hex\"\n    \"flag\"\n    \"fmt\"\n    \"image\"\n    \"image\/gif\"\n    \"image\/png\"\n    \"image\/jpeg\"\n    \"io\"\n    \"io\/ioutil\"\n    \"net\/http\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n    \"github.com\/nfnt\/resize\"\n    \"github.com\/bradfitz\/gomemcache\/memcache\"\n)\n\ntype JobDescription struct {\n    Url string\n    Key string\n    Format string\n    MaxHeight uint64\n    MaxWidth uint64\n}\n\nvar (\n    globalMaxWidth uint64\n    globalMaxHeight uint64\n    maxInDim uint64\n    maxInSize uint64\n    errorPicName string\n    standByPicName string\n    listenAddr string\n    memcacheAddr string\n    jpegQuality int\n\n    marshaledTimeLength int\n    errorPic image.Image\n    standByPic image.Image\n    mc *memcache.Client\n    hc http.Client\n    workChan chan *JobDescription = make(chan *JobDescription, 100)\n)\nvar formatsMime = map[string]string{\n        \"gif\": \"image\/gif\",\n        \"png\": \"image\/png\",\n        \"jpg\": \"image\/jpeg\",\n}\n\nfunc init() {\n    flag.Uint64Var(&globalMaxWidth, \"maxwidth\", 512, \"max thumbnail width in pixels\")\n    flag.Uint64Var(&globalMaxHeight, \"maxheight\", 512, \"max thumbnail height in pixels\")\n    flag.Uint64Var(&maxInDim, \"maxindim\", 1024, \"max input image height or width in pixels\")\n    flag.Uint64Var(&maxInSize, \"maxinsize\", 20*1024*1024, \"max input image size in bytes\")\n    flag.IntVar(&jpegQuality, \"quality\", 80, \"jpeg quality, 0 to 100\")\n    flag.StringVar(&errorPicName, \"errorpic\", \"\", \"error picture\")\n    flag.StringVar(&standByPicName, \"standbypic\", \"\", \"standby picture\")\n    flag.StringVar(&memcacheAddr, \"memcache\", \"127.0.0.1:11211\", \"comma-separated list of memcache servers\")\n    flag.StringVar(&listenAddr, \"listen\", \"127.0.0.1:8080\", \"address and port to listen on\")\n}\n\nfunc parseOrDefault(s string, min uint64, max uint64, def uint64) uint64 {\n    if s == \"\" {\n        return def\n    }\n    n, err := strconv.ParseUint(s, 10, 64)\n    switch {\n        case err != nil:\n            return def\n        case n < min:\n            return min\n        case n > max:\n            return max\n    }\n    return n\n}\n\nfunc encodeImage(w io.Writer, img image.Image, fmt string) error {\n    switch fmt {\n        case \"png\": return png.Encode(w, img)\n        case \"gif\": return gif.Encode(w, img, &gif.Options{NumColors: 256})\n    }\n    return jpeg.Encode(w, img, &jpeg.Options{Quality: jpegQuality} )\n}\n\nfunc renderThumbnail(img image.Image, key string, lastMod time.Time,\n                        maxWidth uint64, maxHeight uint64, fmt string) {\n    thumb := resize.Thumbnail(uint(maxWidth), uint(maxHeight), img, resize.NearestNeighbor)\n    var outbuf bytes.Buffer\n    encodeImage(&outbuf, thumb, fmt)\n    thumbHash := sha1.New()\n    bytes.NewReader(outbuf.Bytes()).WriteTo(thumbHash)\n    etag := hex.EncodeToString(thumbHash.Sum(nil))\n    if len(etag) != 40 { return }\n    saveThumb(key, []byte(etag), []byte{}, lastMod, outbuf.Bytes())\n    return\n}\n\nfunc thumbHandler(w http.ResponseWriter, r *http.Request) {\n    if r.Method != \"GET\" {\n        http.Error(w,\"Method not allowed\", http.StatusMethodNotAllowed)\n        return\n    }\n    r.ParseForm()\n    var maxWidth uint64\n    var maxHeight uint64\n    argUrl := r.Form.Get(\"img\")\n    argFmt := r.Form.Get(\"fmt\")\n    mimeType,ok := formatsMime[argFmt]\n    if !ok {\n        argFmt = \"png\"\n        mimeType = formatsMime[\"png\"]\n    }\n    hdr := w.Header()\n    hdr[\"Content-Type\"] = []string{mimeType}\n    argMax := r.Form.Get(\"max\")\n    if argMax != \"\" {\n        maxWidth = parseOrDefault(argMax, 1, globalMaxWidth, globalMaxHeight)\n        maxHeight = parseOrDefault(argMax, 1, globalMaxHeight, globalMaxHeight)\n    } else {\n        maxWidth = parseOrDefault(r.Form.Get(\"mx\"), 1, globalMaxWidth, globalMaxWidth)\n        maxHeight = parseOrDefault(r.Form.Get(\"my\"), 1, globalMaxHeight, globalMaxHeight)\n    }\n    if mc != nil {\n        h := sha1.New()\n        io.WriteString(h, argUrl)\n        key := fmt.Sprintf(\"%s-%dx%d-%s\", argFmt, maxWidth, maxHeight, hex.EncodeToString(h.Sum(nil)))\n        if len(key)> 250 { key=key[:250] }\n        item, err := mc.Get(key)\n        if err == nil { \n            if len(item.Value) >= 86 {\n                thumbEtag := item.Value[0:40]\n                \/\/originalEtag := item.Value[40:80]\n                lastModBytes := item.Value[80:80+marshaledTimeLength]\n                lastMod := time.Time{}\n                lastMod.UnmarshalBinary(lastModBytes)\n                dataBytes := item.Value[80+marshaledTimeLength:]\n                hdr.Set(\"Last-Modified\", lastMod.Format(http.TimeFormat))\n                hdr.Set(\"Etag\", string(thumbEtag))\n                hdr.Set(\"Content-Length\", strconv.Itoa(len(dataBytes)))\n                w.Write(dataBytes)\n                return\n            }\n        } else if err == memcache.ErrCacheMiss {\n            err = mc.Add(&memcache.Item{Key: key, Value: []byte(\"X\")})\n            if err != memcache.ErrNotStored {\n                workChan <- &JobDescription{\n                    Url: argUrl, Key: key, Format: argFmt,\n                    MaxHeight: maxHeight, MaxWidth: maxWidth,\n                }\n            }\n        }\n    }\n\n    thumb := resize.Thumbnail(uint(maxWidth), uint(maxHeight), standByPic, resize.NearestNeighbor)\n    hdr.Set(\"Last-Modified\", time.Now().UTC().Format(http.TimeFormat))\n    hdr.Set(\"Cache-control\", \"max-age=5, public\")\n    hdr.Set(\"Etag\", fmt.Sprintf(\"standby-%d-%d-%s\", maxWidth, maxHeight, argFmt))\n    encodeImage(w, thumb, argFmt)\n    return\n}\n\nfunc saveThumb(Key string, Etag []byte, OriginEtag []byte, LastMod time.Time, data []byte) error {\n    if mc != nil {\n        value := make([]byte, 0, 128)\n        lastModBytes, _ := LastMod.MarshalBinary()\n        OriginEtag := []byte(\"0000000000000000000000000000000000000000\") \/\/ not used yet\n        value = append(value, Etag...)\n        value = append(value, OriginEtag...)\n        value = append(value, lastModBytes...)\n        value = append(value, data...)\n        return mc.Set(&memcache.Item{Key: Key, Value: value })\n    }\n    return nil\n}\n\nfunc renderWorker() {\n    for job := range workChan {\n        fmt.Fprintf(os.Stderr, \"Generating \\\"%s\\\" %s %dx%d\\n\", job.Url, job.Format, job.MaxWidth, job.MaxHeight)\n        req, err := http.NewRequest(\"GET\", job.Url, nil)\n        if err == nil {\n            req.Header.Set(\"User-Agent\", \"bnw-thumb\/1.0 (http:\/\/github.com\/stiletto\/bnw-thumb)\")\n            closeBody := false\n            resp, err := hc.Do(req)\n            if err == nil {\n                closeBody = true\n                if resp.StatusCode == 200 || uint64(resp.ContentLength) <= maxInSize {\n                    bytebuf, err := ioutil.ReadAll(resp.Body)\n                    if err == nil {\n                        bufreader := bytes.NewReader(bytebuf)\n                        config, _, err := image.DecodeConfig(bufreader)\n                        if err == nil && uint64(config.Width) <= maxInDim && uint64(config.Height) <= maxInDim {\n                            bufreader.Seek(0,0)\n                            img, _, err := image.Decode(bufreader)\n                            if err == nil {\n                                if closeBody { resp.Body.Close() }\n                                fmt.Fprintf(os.Stderr, \"Generated \\\"%s\\\" %s %dx%d\\n\", job.Url, job.Format, job.MaxWidth, job.MaxHeight)\n                                renderThumbnail(img, job.Key, time.Now(), job.MaxWidth, job.MaxHeight, job.Format)\n                                continue\n                            }\n                        }\n                    }\n                }\n            }\n            fmt.Fprintf(os.Stderr, \"Failed to generate \\\"%s\\\" %s %dx%d (%d, %d)\\n\", job.Url, job.Format,\n                job.MaxWidth, job.MaxHeight, resp.StatusCode, resp.ContentLength )\n            if closeBody { resp.Body.Close() }\n        }\n        renderThumbnail(errorPic, job.Key, time.Now(), job.MaxWidth, job.MaxHeight, job.Format)\n    }\n}\n\nfunc loadPicOrEmpty(name string) image.Image {\n    var pic image.Image\n    if name != \"\" {\n        var fmtinfo string\n        img, err := os.Open(name)\n        defer img.Close()\n        if err == nil {\n            pic, fmtinfo, err = image.Decode(img)\n        }\n        if err != nil {\n            pic = nil\n            fmt.Fprintf(os.Stderr, \"Unable to load picture %s: %s\\n\", name, err)\n        } else {\n            ebounds := pic.Bounds()\n            fmt.Fprintf(os.Stderr, \"Loaded picture %s (%s, %dx%d)\\n\",\n                name, fmtinfo, ebounds.Max.X-ebounds.Min.X,\n                ebounds.Max.Y-ebounds.Min.Y)\n        }\n    }\n    if pic == nil {\n        pic = image.NewRGBA(image.Rect(0, 0, 1, 1))\n    }\n    return pic\n}\n\nfunc main() {\n    flag.Parse()\n    mc = nil\n    if memcacheAddr != \"\" {\n        mc = memcache.New(strings.Split(memcacheAddr, \",\")...)\n    } else {\n        fmt.Fprintf(os.Stderr, \"Warning: Memcache is required for bnw-thumb to work.\\n\")\n        fmt.Fprintf(os.Stderr, \"Warning: Without memcache no thumbnails will be actually generated. Use only for testing.\\n\")\n    }\n    marshaledNow, _ := time.Now().MarshalBinary()\n    \/\/ we know that time.Time always has the same length when marshaled\n    \/\/ but this is kinda implementation dependant hack\n    marshaledTimeLength = len(marshaledNow)\n    errorPic = loadPicOrEmpty(errorPicName)\n    standByPic = loadPicOrEmpty(standByPicName)\n    http.HandleFunc(\"\/\", thumbHandler)\n    go renderWorker()\n    fmt.Fprintf(os.Stderr, \"Going to listen on %s\\n\", listenAddr)\n    http.ListenAndServe(listenAddr, nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\/\/\"net\/url\"\n\t\/\/\"io\/ioutil\"\n\n\t\"github.com\/line\/line-bot-sdk-go\/linebot\"\n)\n\nvar bot *linebot.Client\n\nfunc main() {\n\tvar err error\n\tbot, err = linebot.New(os.Getenv(\"ChannelSecret\"), os.Getenv(\"ChannelAccessToken\"))\n\tlog.Println(\"Bot:\", bot, \" err:\", err)\n\thttp.HandleFunc(\"\/callback\", callbackHandler)\n\tport := os.Getenv(\"PORT\")\n\taddr := fmt.Sprintf(\":%s\", port)\n\thttp.ListenAndServe(addr, nil)\n}\n\nfunc callbackHandler(w http.ResponseWriter, r *http.Request) {\n\tevents, err := bot.ParseRequest(r)\n\n\n    \/*resp, err := http.Get(\"https:\/\/hr.hiyes.tw:443\/getMessage.php?mid=Kordan&message=Ou\")\n    if err != nil {\n        fmt.Println(err)\n    } else {\n        body, _ := ioutil.ReadAll(resp.Body)\n        fmt.Println(\"GET OK: \", string(body), resp)\n    }*\/\n\n\n\tif err != nil {\n\t\tif err == linebot.ErrInvalidSignature {\n\t\t\tw.WriteHeader(400)\n\t\t} else {\n\t\t\tw.WriteHeader(500)\n\t\t}\n\t\treturn\n\t}\n    var msg string\n\tfor _, event := range events {\n\t\tif event.Type == linebot.EventTypeMessage {\n\t\t\tswitch message := event.Message.(type) {\n\t\t\tcase *linebot.TextMessage:\n\t\t\t\t\/\/if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(event.ReplyToken+\":\"+message.ID+\"-\"+message.Text+\" OK!\")).Do(); err != nil {\n\t\t\t\tif message.Text == \"勤耕延吉\"{\n\t\t\t\t\tmsg = \"勤耕延吉\"\n\t\t\t\t}\n\t\t\t\tif _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(msg)).Do(); err != nil {\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>add link<commit_after>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\/\/\"net\/url\"\n\t\/\/\"io\/ioutil\"\n\n\t\"github.com\/line\/line-bot-sdk-go\/linebot\"\n)\n\nvar bot *linebot.Client\n\nfunc main() {\n\tvar err error\n\tbot, err = linebot.New(os.Getenv(\"ChannelSecret\"), os.Getenv(\"ChannelAccessToken\"))\n\tlog.Println(\"Bot:\", bot, \" err:\", err)\n\thttp.HandleFunc(\"\/callback\", callbackHandler)\n\tport := os.Getenv(\"PORT\")\n\taddr := fmt.Sprintf(\":%s\", port)\n\thttp.ListenAndServe(addr, nil)\n}\n\nfunc callbackHandler(w http.ResponseWriter, r *http.Request) {\n\tevents, err := bot.ParseRequest(r)\n\n\n    \/*resp, err := http.Get(\"https:\/\/hr.hiyes.tw:443\/getMessage.php?mid=Kordan&message=Ou\")\n    if err != nil {\n        fmt.Println(err)\n    } else {\n        body, _ := ioutil.ReadAll(resp.Body)\n        fmt.Println(\"GET OK: \", string(body), resp)\n    }*\/\n\n\n\tif err != nil {\n\t\tif err == linebot.ErrInvalidSignature {\n\t\t\tw.WriteHeader(400)\n\t\t} else {\n\t\t\tw.WriteHeader(500)\n\t\t}\n\t\treturn\n\t}\n    var msg string\n\tfor _, event := range events {\n\t\tif event.Type == linebot.EventTypeMessage {\n\t\t\tswitch message := event.Message.(type) {\n\t\t\tcase *linebot.TextMessage:\n\t\t\t\t\/\/if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(event.ReplyToken+\":\"+message.ID+\"-\"+message.Text+\" OK!\")).Do(); err != nil {\n\t\t\t\tif message.Text == \"勤耕延吉\"{\n\t\t\t\t\tmsg = \"勤耕延吉 http:\/\/www.hiyes.tw\/allcase\/yanji\/index.html\"\t\t\t\t\n\t\t\t\t}\n\t\t\t\tif message.Text == \"幸福莊園\"{\n\t\t\t\t\tmsg = \"幸福莊園 http:\/\/www.hiyes.tw\/allcase\/happymanor\/index.html\"\t\t\t\t\n\t\t\t\t}\n\t\t\t\tif _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(msg)).Do(); err != nil {\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ main.go - onionwrap\n\/\/\n\/\/ To the extent possible under law, Yawning Angel waived all copyright\n\/\/ and related or neighboring rights to onionwrap, using the creative\n\/\/ commons \"cc0\" public domain dedication. See LICENSE or\n\/\/ <http:\/\/creativecommons.org\/publicdomain\/zero\/1.0\/> for full details.\n\n\/\/ onionwrap serves delicious Onion Service Wraps.\npackage main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\tgofmt \"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/yawning\/bulb\"\n\t\"github.com\/yawning\/bulb\/utils\"\n)\n\nconst (\n\tcontrolPortEnv       = \"TOR_CONTROL_PORT\"\n\tcontrolPortPasswdEnv = \"TOR_CONTROL_PASSWD\"\n\n\tlocalhost          = \"127.0.0.1\"\n\tdefaultControlPort = \"tcp:\/\/\" + localhost + \":9051\"\n)\n\nvar debugSpew bool\nvar quietSpew bool\nvar noRewriteArgs bool\n\nfunc infof(fmt string, args ...interface{}) {\n\tif !quietSpew {\n\t\tgofmt.Fprintf(os.Stderr, \"INFO: \"+fmt, args...)\n\t}\n}\n\nfunc errorf(fmt string, args ...interface{}) {\n\tgofmt.Fprintf(os.Stderr, \"ERROR: \"+fmt, args...)\n\tos.Exit(-1)\n}\n\nfunc debugf(fmt string, args ...interface{}) {\n\t\/\/ This explicitly overrides quietSpew.\n\tif debugSpew {\n\t\tgofmt.Fprintf(os.Stderr, \"DEBUG: \"+fmt, args...)\n\t}\n}\n\nfunc parsePort(portStr string) (uint16, error) {\n\tp, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif p == 0 {\n\t\treturn 0, errors.New(\"invalid port '0'\")\n\t}\n\treturn uint16(p), nil\n}\n\nfunc parsePortArg(arg string) (virtPort, targetPort, target string, err error) {\n\t\/\/ This is formated as VIRTPORT[,TARGET], which is identical to\n\t\/\/ what the ADD_ONION command expects out of the 'Port' arguments.\n\t\/\/ If the 'TARGET' is omitted, 'VIRTPORT' is mirrored.  If 'TARGET'\n\t\/\/ only a naked port, then '127.0.0.1:TARGET' is used, otherwise\n\t\/\/ 'TARGET' is treated as an address.\n\t\/\/\n\t\/\/ TODO: Figure out what to do with AF_UNIX.\n\tif arg == \"\" {\n\t\treturn \"\", \"\", \"\", errors.New(\"no Onion Service port specified\")\n\t}\n\tsplitArg := strings.SplitN(arg, \",\", 2)\n\tvirtPort = splitArg[0]\n\tif _, err = parsePort(virtPort); err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\tif len(splitArg) == 1 {\n\t\t\/\/ Only a 'VIRTPORT' was provided, mirror it onto the target.\n\t\treturn virtPort, virtPort, localhost + \":\" + virtPort, nil\n\t}\n\n\ttarget = splitArg[1]\n\tif _, err = parsePort(target); err == nil {\n\t\t\/\/ The 'TARGET' is a naked port.\n\t\treturn virtPort, target, localhost + \":\" + target, nil\n\t}\n\ttcpAddr, err := net.ResolveTCPAddr(\"tcp\", target)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\tif tcpAddr.Port == 0 {\n\t\treturn \"\", \"\", \"\", errors.New(\"target has invalid port '0'\")\n\t}\n\ttargetPort = strconv.Itoa(tcpAddr.Port)\n\treturn\n}\n\nfunc main() {\n\t\/\/\n\t\/\/ Parse\/validate the command line arguments.\n\t\/\/\n\n\tconst controlPortArg = \"control-port\"\n\tctrlPortArg := flag.String(controlPortArg, \"\", \"Tor control port\")\n\tflag.Lookup(controlPortArg).DefValue = defaultControlPort\n\thsPortArg := flag.String(\"port\", \"\", \"Onion Service port\")\n\tflag.BoolVar(&debugSpew, \"debug\", false, \"Print debug messages to stderr\")\n\tflag.BoolVar(&quietSpew, \"quiet\", false, \"Suppress non-error messages\")\n\tflag.BoolVar(&noRewriteArgs, \"no-rewrite\", false, \"Disable rewriting subprocess arguments\")\n\tflag.Parse()\n\n\t\/\/ The control port is taken from the argument, the env var, and then\n\t\/\/ the hardcoded default in that order.\n\tif *ctrlPortArg == \"\" {\n\t\t*ctrlPortArg = os.Getenv(controlPortEnv)\n\t\tif *ctrlPortArg == \"\" {\n\t\t\t*ctrlPortArg = defaultControlPort\n\t\t}\n\t}\n\tctrlNet, ctrlAddr, err := utils.ParseControlPortString(*ctrlPortArg)\n\tif err != nil {\n\t\terrorf(\"Invalid control port: %v\\n\", err)\n\t}\n\n\tvirtPort, targetPort, target, err := parsePortArg(*hsPortArg)\n\tif err != nil {\n\t\terrorf(\"Invalid virtual port: %v\\n\", err)\n\t}\n\n\t\/\/ The command that will be fork\/execed.\n\tcmdVec := flag.Args()\n\tvar cmd *exec.Cmd\n\tswitch len(cmdVec) {\n\tcase 0:\n\t\terrorf(\"No command specified to wrap.\\n\")\n\tcase 1:\n\t\tcmd = exec.Command(cmdVec[0])\n\tdefault:\n\t\tcmd = exec.Command(cmdVec[0], cmdVec[1:]...)\n\t}\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif !noRewriteArgs {\n\t\t\/\/ Unless explicitly disabled, replace certain variables in the\n\t\t\/\/ subprocess command line arguments with values propagated from\n\t\t\/\/ the onionwrap command line.\n\t\t\/\/\n\t\t\/\/  * %VPORT - The 'VIRTPORT'.\n\t\t\/\/  * %TPORT - The port component of 'TARGET'.\n\t\t\/\/  * %TADDR - The entire 'TARGET'.\n\t\tfor i := 1; i < len(cmd.Args); i++ {\n\t\t\tv := cmd.Args[i]\n\t\t\tv = strings.Replace(v, \"%VPORT\", virtPort, -1)\n\t\t\tv = strings.Replace(v, \"%TPORT\", targetPort, -1)\n\t\t\tv = strings.Replace(v, \"%TADDR\", target, -1)\n\t\t\tcmd.Args[i] = v\n\t\t}\n\t}\n\n\tdebugf(\"Cmd: %v\\n\", cmd.Args)\n\tdebugf(\"CtrlPort: %v, %v\\n\", ctrlNet, ctrlAddr)\n\tdebugf(\"VirtPort: %v Target: %v\\n\", virtPort, target)\n\n\t\/\/\n\t\/\/ Do the actual work.\n\t\/\/\n\n\t\/\/ Setup the Onion Service, after connecting to the control port.\n\tctrlConn, err := bulb.Dial(ctrlNet, ctrlAddr)\n\tif err != nil {\n\t\terrorf(\"Failed to connect to the control port: %v\\n\", err)\n\t}\n\tdefer ctrlConn.Close()\n\tif err = ctrlConn.Authenticate(os.Getenv(controlPortPasswdEnv)); err != nil {\n\t\terrorf(\"Failed to authenticate with the control port: %v\\n\", err)\n\t}\n\n\t\/\/ TODO: Support saving the PK\/Loading a PK.\n\tresp, err := ctrlConn.Request(\"ADD_ONION NEW:BEST Port=%s Flags=DiscardPK\", *hsPortArg)\n\tif err != nil {\n\t\terrorf(\"Failed to create onion service: %v\\n\", err)\n\t}\n\tvar serviceID string\n\tfor _, l := range resp.Data {\n\t\tserviceID = strings.TrimPrefix(l, \"ServiceID=\")\n\t\tif serviceID != l {\n\t\t\tbreak\n\t\t}\n\t}\n\tif serviceID == \"\" {\n\t\t\/\/ This should *NEVER* happen since the command succeded, and\n\t\t\/\/ the spec guarantees that this will be sent.\n\t\terrorf(\"Failed to determine service ID.\")\n\t}\n\tinfof(\"Created onion: %s.onion:%s -> %s\\n\", serviceID, virtPort, target)\n\n\t\/\/ Launch the actual process, and block till it exits.  Cleanup\n\t\/\/ is automatic because tor will tear down the Onion Service\n\t\/\/ when the control connection gets closed.\n\terr = cmd.Run()\n\tif !cmd.ProcessState.Success() {\n\t\tos.Exit(-1)\n\t}\n}\n<commit_msg>Try harder to ensure that the child process dies.<commit_after>\/\/ main.go - onionwrap\n\/\/\n\/\/ To the extent possible under law, Yawning Angel waived all copyright\n\/\/ and related or neighboring rights to onionwrap, using the creative\n\/\/ commons \"cc0\" public domain dedication. See LICENSE or\n\/\/ <http:\/\/creativecommons.org\/publicdomain\/zero\/1.0\/> for full details.\n\n\/\/ onionwrap serves delicious Onion Service Wraps.\npackage main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\tgofmt \"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/yawning\/bulb\"\n\t\"github.com\/yawning\/bulb\/utils\"\n)\n\nconst (\n\tcontrolPortEnv       = \"TOR_CONTROL_PORT\"\n\tcontrolPortPasswdEnv = \"TOR_CONTROL_PASSWD\"\n\n\tlocalhost          = \"127.0.0.1\"\n\tdefaultControlPort = \"tcp:\/\/\" + localhost + \":9051\"\n\n\tsigKillDelay = 5 * time.Second\n)\n\nvar debugSpew bool\nvar quietSpew bool\nvar noRewriteArgs bool\n\nfunc infof(fmt string, args ...interface{}) {\n\tif !quietSpew {\n\t\tgofmt.Fprintf(os.Stderr, \"INFO: \"+fmt, args...)\n\t}\n}\n\nfunc errorf(fmt string, args ...interface{}) {\n\tgofmt.Fprintf(os.Stderr, \"ERROR: \"+fmt, args...)\n\tos.Exit(-1)\n}\n\nfunc debugf(fmt string, args ...interface{}) {\n\t\/\/ This explicitly overrides quietSpew.\n\tif debugSpew {\n\t\tgofmt.Fprintf(os.Stderr, \"DEBUG: \"+fmt, args...)\n\t}\n}\n\nfunc parsePort(portStr string) (uint16, error) {\n\tp, err := strconv.ParseUint(portStr, 10, 16)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif p == 0 {\n\t\treturn 0, errors.New(\"invalid port '0'\")\n\t}\n\treturn uint16(p), nil\n}\n\nfunc parsePortArg(arg string) (virtPort, targetPort, target string, err error) {\n\t\/\/ This is formated as VIRTPORT[,TARGET], which is identical to\n\t\/\/ what the ADD_ONION command expects out of the 'Port' arguments.\n\t\/\/ If the 'TARGET' is omitted, 'VIRTPORT' is mirrored.  If 'TARGET'\n\t\/\/ only a naked port, then '127.0.0.1:TARGET' is used, otherwise\n\t\/\/ 'TARGET' is treated as an address.\n\t\/\/\n\t\/\/ TODO: Figure out what to do with AF_UNIX.\n\tif arg == \"\" {\n\t\treturn \"\", \"\", \"\", errors.New(\"no Onion Service port specified\")\n\t}\n\tsplitArg := strings.SplitN(arg, \",\", 2)\n\tvirtPort = splitArg[0]\n\tif _, err = parsePort(virtPort); err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\tif len(splitArg) == 1 {\n\t\t\/\/ Only a 'VIRTPORT' was provided, mirror it onto the target.\n\t\treturn virtPort, virtPort, localhost + \":\" + virtPort, nil\n\t}\n\n\ttarget = splitArg[1]\n\tif _, err = parsePort(target); err == nil {\n\t\t\/\/ The 'TARGET' is a naked port.\n\t\treturn virtPort, target, localhost + \":\" + target, nil\n\t}\n\ttcpAddr, err := net.ResolveTCPAddr(\"tcp\", target)\n\tif err != nil {\n\t\treturn \"\", \"\", \"\", err\n\t}\n\tif tcpAddr.Port == 0 {\n\t\treturn \"\", \"\", \"\", errors.New(\"target has invalid port '0'\")\n\t}\n\ttargetPort = strconv.Itoa(tcpAddr.Port)\n\treturn\n}\n\nfunc main() {\n\t\/\/\n\t\/\/ Parse\/validate the command line arguments.\n\t\/\/\n\n\tconst controlPortArg = \"control-port\"\n\tctrlPortArg := flag.String(controlPortArg, \"\", \"Tor control port\")\n\tflag.Lookup(controlPortArg).DefValue = defaultControlPort\n\thsPortArg := flag.String(\"port\", \"\", \"Onion Service port\")\n\tflag.BoolVar(&debugSpew, \"debug\", false, \"Print debug messages to stderr\")\n\tflag.BoolVar(&quietSpew, \"quiet\", false, \"Suppress non-error messages\")\n\tflag.BoolVar(&noRewriteArgs, \"no-rewrite\", false, \"Disable rewriting subprocess arguments\")\n\tflag.Parse()\n\n\t\/\/ The control port is taken from the argument, the env var, and then\n\t\/\/ the hardcoded default in that order.\n\tif *ctrlPortArg == \"\" {\n\t\t*ctrlPortArg = os.Getenv(controlPortEnv)\n\t\tif *ctrlPortArg == \"\" {\n\t\t\t*ctrlPortArg = defaultControlPort\n\t\t}\n\t}\n\tctrlNet, ctrlAddr, err := utils.ParseControlPortString(*ctrlPortArg)\n\tif err != nil {\n\t\terrorf(\"Invalid control port: %v\\n\", err)\n\t}\n\n\tvirtPort, targetPort, target, err := parsePortArg(*hsPortArg)\n\tif err != nil {\n\t\terrorf(\"Invalid virtual port: %v\\n\", err)\n\t}\n\n\t\/\/ The command that will be fork\/execed.\n\tcmdVec := flag.Args()\n\tvar cmd *exec.Cmd\n\tswitch len(cmdVec) {\n\tcase 0:\n\t\terrorf(\"No command specified to wrap.\\n\")\n\tcase 1:\n\t\tcmd = exec.Command(cmdVec[0])\n\tdefault:\n\t\tcmd = exec.Command(cmdVec[0], cmdVec[1:]...)\n\t}\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif !noRewriteArgs {\n\t\t\/\/ Unless explicitly disabled, replace certain variables in the\n\t\t\/\/ subprocess command line arguments with values propagated from\n\t\t\/\/ the onionwrap command line.\n\t\t\/\/\n\t\t\/\/  * %VPORT - The 'VIRTPORT'.\n\t\t\/\/  * %TPORT - The port component of 'TARGET'.\n\t\t\/\/  * %TADDR - The entire 'TARGET'.\n\t\tfor i := 1; i < len(cmd.Args); i++ {\n\t\t\tv := cmd.Args[i]\n\t\t\tv = strings.Replace(v, \"%VPORT\", virtPort, -1)\n\t\t\tv = strings.Replace(v, \"%TPORT\", targetPort, -1)\n\t\t\tv = strings.Replace(v, \"%TADDR\", target, -1)\n\t\t\tcmd.Args[i] = v\n\t\t}\n\t}\n\n\tdebugf(\"Cmd: %v\\n\", cmd.Args)\n\tdebugf(\"CtrlPort: %v, %v\\n\", ctrlNet, ctrlAddr)\n\tdebugf(\"VirtPort: %v Target: %v\\n\", virtPort, target)\n\n\t\/\/\n\t\/\/ Do the actual work.\n\t\/\/\n\n\t\/\/ Setup the Onion Service, after connecting to the control port.\n\tctrlConn, err := bulb.Dial(ctrlNet, ctrlAddr)\n\tif err != nil {\n\t\terrorf(\"Failed to connect to the control port: %v\\n\", err)\n\t}\n\tdefer ctrlConn.Close()\n\tif err = ctrlConn.Authenticate(os.Getenv(controlPortPasswdEnv)); err != nil {\n\t\terrorf(\"Failed to authenticate with the control port: %v\\n\", err)\n\t}\n\n\t\/\/ TODO: Support saving the PK\/Loading a PK.\n\tresp, err := ctrlConn.Request(\"ADD_ONION NEW:BEST Port=%s Flags=DiscardPK\", *hsPortArg)\n\tif err != nil {\n\t\terrorf(\"Failed to create onion service: %v\\n\", err)\n\t}\n\tvar serviceID string\n\tfor _, l := range resp.Data {\n\t\tserviceID = strings.TrimPrefix(l, \"ServiceID=\")\n\t\tif serviceID != l {\n\t\t\tbreak\n\t\t}\n\t}\n\tif serviceID == \"\" {\n\t\t\/\/ This should *NEVER* happen since the command succeded, and\n\t\t\/\/ the spec guarantees that this will be sent.\n\t\terrorf(\"Failed to determine service ID.\")\n\t}\n\tinfof(\"Created onion: %s.onion:%s -> %s\\n\", serviceID, virtPort, target)\n\n\t\/\/ TODO: Wait till the HS descriptor has been published.\n\n\t\/\/ Initialize the signal handling and launch the process.\n\tsigChan := make(chan os.Signal)\n\tsignal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)\n\terr = cmd.Start()\n\tif err != nil {\n\t\tos.Exit(-1)\n\t}\n\tdoneChan := make(chan error)\n\tgo func() {\n\t\tdoneChan <- cmd.Wait()\n\t}()\n\n\tonChildExit := func() {\n\t\t\/\/ Child terminated.\n\t\tdebugf(\"child process terminated\\n\")\n\t\tif !cmd.ProcessState.Success() {\n\t\t\t\/\/ ProcessState doesn't give the exact return value. :(\n\t\t\tos.Exit(-1)\n\t\t}\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Wait for the child to finish, or the wrapper to receive\n\t\/\/ SIGINT\/SIGTERM.\n\tselect {\n\tcase <-doneChan:\n\t\tonChildExit()\n\tcase sig := <-sigChan:\n\t\t\/\/ Propagate the signal to the child, and wait for it to die.\n\t\tdebugf(\"received signal: %v\\n\", sig)\n\t\tcmd.Process.Signal(sig)\n\t\tselect {\n\t\tcase <-doneChan:\n\t\t\tonChildExit()\n\t\tcase <-time.After(sigKillDelay):\n\t\t\tdebugf(\"post signal delay elapsed, killing child\\n\")\n\t\t\tcmd.Process.Kill()\n\t\t\tos.Exit(-1)\n\t\t}\n\t}\n\tpanic(\"BUG: fell through the select???\") \/\/ NOTREACHED\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2011-2014 gtalent2@gmail.com\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"flag\"\n)\n\nconst (\n\tDEFAULT_LICENSE_FILE = \".liccor\"\n\tSUFFIX_GO = \".go\"\n\tSUFFIX_C = \".c\"\n\tSUFFIX_CPP = \".cpp\"\n\tSUFFIX_CXX = \".cxx\"\n\tSUFFIX_H = \".h\"\n\tSUFFIX_HPP = \".hpp\"\n\tSUFFIX_JAVA = \".java\"\n\tSUFFIX_JS = \".js\"\n)\n\nvar (\n\tflagLicenseFile string\n\tflagVerbose bool\n)\n\nfunc verboseLog(msg string) {\n\tif flagVerbose {\n\t\tfmt.Println(msg);\n\t}\n}\n\nfunc findLicense(dir string) (string, error) {\n\tverboseLog(\"Search for '\" + flagLicenseFile + \"' file at directory '\" + dir + \"'\")\n\n\td, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not find \" + flagLicenseFile + \" file\")\n\t}\n\tfor _, v := range d {\n\t\tif v.Name() == flagLicenseFile {\n\t\t\tlicenseData, err := ioutil.ReadFile(dir + \"\/\" + v.Name())\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Could not access \" + flagLicenseFile + \" file\")\n\t\t\t}\n\t\t\treturn string(licenseData), err\n\t\t}\n\t}\n\n\treturn findLicense(dir + \".\/.\")\n}\n\nfunc findSrcFiles(dir string) ([]string, error) {\n\tverboseLog(\"Search source files at '\" + dir + \"'\")\n\n\tl, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toutput := make([]string, 0)\n\tfor _, v := range l {\n\t\tif v.IsDir() {\n\t\t\t\/\/ ignore .git dir\n\t\t\tif v.Name() != \".git\" {\n\t\t\t\tfiles, err := findSrcFiles(dir + \"\/\" + v.Name())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn output, err\n\t\t\t\t}\n\t\t\t\tfor _, v2 := range files {\n\t\t\t\t\toutput = append(output, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tpt := strings.LastIndex(v.Name(), \".\")\n\t\t\tif pt == -1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch v.Name()[pt:] {\n\t\t\tcase SUFFIX_GO, SUFFIX_C, SUFFIX_CPP, SUFFIX_CXX, SUFFIX_H, SUFFIX_HPP, SUFFIX_JAVA, SUFFIX_JS:\n\t\t\t\tsrcPath := dir+\"\/\"+v.Name()\n\t\t\t\toutput = append(output, srcPath)\n\t\t\t\tverboseLog(\"Found source '\" + srcPath + \"'\");\n\t\t\t}\n\t\t}\n\t}\n\treturn output, err\n}\n\nfunc hasLicense(file string) (bool, int) {\n\tfor i, c := range file {\n\t\tswitch c {\n\t\tcase ' ', '\\t', '\\n':\n\t\t\tcontinue\n\t\tcase '\/':\n\t\t\ti++\n\t\t\tif len(file) > i && file[i] == '*' {\n\t\t\t\treturn true, i\n\t\t\t}\n\t\tdefault:\n\t\t\treturn false, -1\n\t\t}\n\t}\n\treturn false, -1\n}\n\nfunc correct(path, license string) (bool, error) {\n\tinput, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfile := string(input)\n\torig := file\n\tif hasLicense, licenseStart := hasLicense(file); hasLicense {\n\t\t\/\/remove old license\n\t\tfor i := licenseStart; i < len(file); i++ {\n\t\t\tif file[i] == '*' && file[i+1] == '\/' {\n\t\t\t\ti += 2\n\t\t\t\tif file[i] == '\\n' {\n\t\t\t\t\ti += 1\n\t\t\t\t}\n\t\t\t\tfile = file[i:len(file)]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tfile = license + file\n\toutput := []byte(file)\n\tif file != orig {\n\t\terr = ioutil.WriteFile(path, output, 0)\n\t\treturn true, err\n\t}\n\treturn false, nil\n}\n\nfunc init() {\n\tflag.StringVar(&flagLicenseFile, \"license\", DEFAULT_LICENSE_FILE, \"the name of the license file\")\n\tflag.StringVar(&flagLicenseFile, \"l\", DEFAULT_LICENSE_FILE, \"shortcut for license\")\n\tflag.BoolVar(&flagVerbose, \"verbose\", false, \"print verbose output\")\n\tflag.BoolVar(&flagVerbose, \"v\", false, \"shortcut for verbose\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tlicenseData, err := findLicense(\".\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tlicenseData = licenseData[0 : len(licenseData)-1]\n\tlics := make(map[string]string)\n\tlics[\"c-like\"] = \"\/*\\n * \" + strings.Replace(string(licenseData), \"\\n\", \"\\n * \", -1) + \"\\n *\/\\n\"\n\tlics[\"go\"] = func() string {\n\t\tgolic := \"\/*\\n   \" + strings.Replace(string(licenseData), \"\\n\", \"\\n   \", -1) + \"\\n*\/\\n\"\n\t\tgolic = strings.Replace(golic, \"\\n   \\n\", \"\\n\\n\", -1)\n\t\treturn golic\n\t}()\n\n\tfiles, err := findSrcFiles(\".\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor i := 0; i < len(files); i++ {\n\t\tpt := strings.LastIndex(files[i], \".\")\n\t\tlic := \"\"\n\t\t\/\/determine how to format the license\n\t\tswitch files[i][pt:] {\n\t\tcase SUFFIX_GO:\n\t\t\tlic = lics[\"go\"]\n\t\tcase SUFFIX_C, SUFFIX_CPP, SUFFIX_CXX, SUFFIX_H, SUFFIX_HPP, SUFFIX_JAVA, SUFFIX_JS:\n\t\t\tlic = lics[\"c-like\"]\n\t\t}\n\t\tchanged, err := correct(files[i], lic)\n\t\tif changed {\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Correcting '\" + files[i][2:]+\"'... Failure!\")\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Correcting '\" + files[i][2:]+\"'... Success!\")\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"All files up to date!\");\n\t\t}\n\t}\n}\n<commit_msg>Customize Usage out<commit_after>\/*\n   Copyright 2011-2014 gtalent2@gmail.com\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"flag\"\n)\n\nconst (\n\tDEFAULT_LICENSE_FILE = \".liccor\"\n\tSUFFIX_GO = \".go\"\n\tSUFFIX_C = \".c\"\n\tSUFFIX_CPP = \".cpp\"\n\tSUFFIX_CXX = \".cxx\"\n\tSUFFIX_H = \".h\"\n\tSUFFIX_HPP = \".hpp\"\n\tSUFFIX_JAVA = \".java\"\n\tSUFFIX_JS = \".js\"\n)\n\nvar (\n\tflagLicenseFile string\n\tflagVerbose bool\n)\n\nfunc verboseLog(msg string) {\n\tif flagVerbose {\n\t\tfmt.Println(msg);\n\t}\n}\n\nfunc findLicense(dir string) (string, error) {\n\tverboseLog(\"Search for '\" + flagLicenseFile + \"' file at directory '\" + dir + \"'\")\n\n\td, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not find \" + flagLicenseFile + \" file\")\n\t}\n\tfor _, v := range d {\n\t\tif v.Name() == flagLicenseFile {\n\t\t\tlicenseData, err := ioutil.ReadFile(dir + \"\/\" + v.Name())\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"Could not access \" + flagLicenseFile + \" file\")\n\t\t\t}\n\t\t\treturn string(licenseData), err\n\t\t}\n\t}\n\n\treturn findLicense(dir + \".\/.\")\n}\n\nfunc findSrcFiles(dir string) ([]string, error) {\n\tverboseLog(\"Search source files at '\" + dir + \"'\")\n\n\tl, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toutput := make([]string, 0)\n\tfor _, v := range l {\n\t\tif v.IsDir() {\n\t\t\t\/\/ ignore .git dir\n\t\t\tif v.Name() != \".git\" {\n\t\t\t\tfiles, err := findSrcFiles(dir + \"\/\" + v.Name())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn output, err\n\t\t\t\t}\n\t\t\t\tfor _, v2 := range files {\n\t\t\t\t\toutput = append(output, v2)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tpt := strings.LastIndex(v.Name(), \".\")\n\t\t\tif pt == -1 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch v.Name()[pt:] {\n\t\t\tcase SUFFIX_GO, SUFFIX_C, SUFFIX_CPP, SUFFIX_CXX, SUFFIX_H, SUFFIX_HPP, SUFFIX_JAVA, SUFFIX_JS:\n\t\t\t\tsrcPath := dir+\"\/\"+v.Name()\n\t\t\t\toutput = append(output, srcPath)\n\t\t\t\tverboseLog(\"Found source '\" + srcPath + \"'\");\n\t\t\t}\n\t\t}\n\t}\n\treturn output, err\n}\n\nfunc hasLicense(file string) (bool, int) {\n\tfor i, c := range file {\n\t\tswitch c {\n\t\tcase ' ', '\\t', '\\n':\n\t\t\tcontinue\n\t\tcase '\/':\n\t\t\ti++\n\t\t\tif len(file) > i && file[i] == '*' {\n\t\t\t\treturn true, i\n\t\t\t}\n\t\tdefault:\n\t\t\treturn false, -1\n\t\t}\n\t}\n\treturn false, -1\n}\n\nfunc correct(path, license string) (bool, error) {\n\tinput, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tfile := string(input)\n\torig := file\n\tif hasLicense, licenseStart := hasLicense(file); hasLicense {\n\t\t\/\/remove old license\n\t\tfor i := licenseStart; i < len(file); i++ {\n\t\t\tif file[i] == '*' && file[i+1] == '\/' {\n\t\t\t\ti += 2\n\t\t\t\tif file[i] == '\\n' {\n\t\t\t\t\ti += 1\n\t\t\t\t}\n\t\t\t\tfile = file[i:len(file)]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tfile = license + file\n\toutput := []byte(file)\n\tif file != orig {\n\t\terr = ioutil.WriteFile(path, output, 0)\n\t\treturn true, err\n\t}\n\treturn false, nil\n}\n\nfunc init() {\n\tflag.StringVar(&flagLicenseFile, \"license\", DEFAULT_LICENSE_FILE, \"the name of the license file\")\n\tflag.StringVar(&flagLicenseFile, \"l\", DEFAULT_LICENSE_FILE, \"shortcut for license\")\n\tflag.BoolVar(&flagVerbose, \"verbose\", false, \"print verbose output\")\n\tflag.BoolVar(&flagVerbose, \"v\", false, \"shortcut for verbose\")\n\tflag.Usage = func() {\n\t\tfmt.Print(\"\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tfmt.Println(\"\\nOptions:\")\n\t\tflag.PrintDefaults()\n\t\tfmt.Println(\"\\nExample usage:\")\n\t\tfmt.Println(\"  .\/liccor -verbose\")\n\t\tfmt.Print(\"\\n\\n\")\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tlicenseData, err := findLicense(\".\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tlicenseData = licenseData[0 : len(licenseData)-1]\n\tlics := make(map[string]string)\n\tlics[\"c-like\"] = \"\/*\\n * \" + strings.Replace(string(licenseData), \"\\n\", \"\\n * \", -1) + \"\\n *\/\\n\"\n\tlics[\"go\"] = func() string {\n\t\tgolic := \"\/*\\n   \" + strings.Replace(string(licenseData), \"\\n\", \"\\n   \", -1) + \"\\n*\/\\n\"\n\t\tgolic = strings.Replace(golic, \"\\n   \\n\", \"\\n\\n\", -1)\n\t\treturn golic\n\t}()\n\n\tfiles, err := findSrcFiles(\".\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor i := 0; i < len(files); i++ {\n\t\tpt := strings.LastIndex(files[i], \".\")\n\t\tlic := \"\"\n\t\t\/\/determine how to format the license\n\t\tswitch files[i][pt:] {\n\t\tcase SUFFIX_GO:\n\t\t\tlic = lics[\"go\"]\n\t\tcase SUFFIX_C, SUFFIX_CPP, SUFFIX_CXX, SUFFIX_H, SUFFIX_HPP, SUFFIX_JAVA, SUFFIX_JS:\n\t\t\tlic = lics[\"c-like\"]\n\t\t}\n\t\tchanged, err := correct(files[i], lic)\n\t\tif changed {\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Correcting '\" + files[i][2:]+\"'... Failure!\")\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Correcting '\" + files[i][2:]+\"'... Success!\")\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"All files up to date!\");\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2015 The Radio Noise Project Members\n\/\/ See COPYING for the license terms and complete list of copyright holders\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/gorilla\/handlers\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/radionoiseproject\/rnp-server\/hub\"\n\t\"github.com\/radionoiseproject\/rnp-server\/user\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n)\n\nvar (\n\tbind = flag.String(\"bind\", \":8080\", \"address and port to listen on\")\n)\n\ntype misakaNotFoundHandler struct{}\n\nfunc (_ misakaNotFoundHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tw.WriteHeader(404)\n\tfmt.Fprintf(w, \"“‘You seem to be a bit lost,’ MISAKA says as she looks on with a concerned expression.”\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\th := hub.New()\n\tgo h.Run()\n\n\trouter := mux.NewRouter()\n\trouter.NotFoundHandler = misakaNotFoundHandler{}\n\trouter.Handle(\"\/rnp\", user.Handler(h))\n\n\tloggedRouter := handlers.CombinedLoggingHandler(os.Stderr, router)\n\n\thttp.Handle(\"\/\", loggedRouter)\n\n\tvar l net.Listener\n\tvar listenFields log.Fields\n\tif strings.ContainsRune(*bind, '\/') {\n\t\tlistenFields = log.Fields{\"bind\": *bind, \"listener\": \"unix\"}\n\t\ta, err := net.ResolveUnixAddr(\"unix\", *bind)\n\t\tif err != nil {\n\t\t\tlog.WithFields(listenFields).Fatal(err)\n\t\t}\n\t\tl, err = net.ListenUnix(\"unix\", a)\n\t\tif err != nil {\n\t\t\tlog.WithFields(listenFields).Fatal(err)\n\t\t}\n\t} else {\n\t\tlistenFields = log.Fields{\"bind\": *bind, \"listener\": \"tcp\"}\n\t\ta, err := net.ResolveTCPAddr(\"tcp\", *bind)\n\t\tif err != nil {\n\t\t\tlog.WithFields(listenFields).Fatal(err)\n\t\t}\n\t\tl, err = net.ListenTCP(\"tcp\", a)\n\t\tif err != nil {\n\t\t\tlog.WithFields(listenFields).Fatal(err)\n\t\t}\n\t}\n\n\tlog.WithFields(listenFields).Info(\"Radio Noise Project listening\")\n\n\tif err := http.Serve(l, nil); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\th.Done()\n}\n<commit_msg>Unlink unix socket on exit<commit_after>\/\/ Copyright (c) 2015 The Radio Noise Project Members\n\/\/ See COPYING for the license terms and complete list of copyright holders\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/gorilla\/handlers\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/radionoiseproject\/rnp-server\/hub\"\n\t\"github.com\/radionoiseproject\/rnp-server\/user\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nvar (\n\tbind     = flag.String(\"bind\", \":8080\", \"address and port to listen on\")\n\tloglevel = flag.String(\"loglevel\", \"info\", \"level of log output (debug, info, warn, error, fatal, panic)\")\n)\n\ntype misakaNotFoundHandler struct{}\n\nfunc (_ misakaNotFoundHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tw.WriteHeader(404)\n\tfmt.Fprintf(w, \"“‘You seem to be a bit lost,’ MISAKA says as she looks on with a concerned expression.”\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\t\/\/ Logging setup\n\tlevel, err := log.ParseLevel(*loglevel)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.SetLevel(level)\n\n\th := hub.New()\n\tgo h.Run()\n\n\trouter := mux.NewRouter()\n\trouter.NotFoundHandler = misakaNotFoundHandler{}\n\trouter.Handle(\"\/rnp\", user.Handler(h))\n\n\tlogHandler := handlers.CombinedLoggingHandler(os.Stderr, router)\n\tproxyHeaderHandler := handlers.ProxyHeaders(logHandler)\n\n\thttp.Handle(\"\/\", proxyHeaderHandler)\n\n\tvar l net.Listener\n\tvar listenFields log.Fields\n\tif strings.ContainsRune(*bind, '\/') {\n\t\tlistenFields = log.Fields{\"bind\": *bind, \"listener\": \"unix\"}\n\t\ta, err := net.ResolveUnixAddr(\"unix\", *bind)\n\t\tif err != nil {\n\t\t\tlog.WithFields(listenFields).Fatal(err)\n\t\t}\n\t\tl, err = net.ListenUnix(\"unix\", a)\n\t\tif err != nil {\n\t\t\tlog.WithFields(listenFields).Fatal(err)\n\t\t}\n\t\tdefer func() {\n\t\t\tlog.WithFields(listenFields).Debug(\"Cleaning up socket\")\n\t\t\terr = os.Remove(*bind)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithFields(listenFields).Fatalf(\n\t\t\t\t\t\"Failed to unlink socket: %s\", err)\n\t\t\t}\n\t\t}()\n\t\terr = os.Chmod(*bind, os.ModePerm)\n\t\tif err != nil {\n\t\t\tlog.WithFields(listenFields).Fatalf(\"Could not set socket permissions: %s\", err)\n\t\t}\n\t} else {\n\t\tlistenFields = log.Fields{\"bind\": *bind, \"listener\": \"tcp\"}\n\t\ta, err := net.ResolveTCPAddr(\"tcp\", *bind)\n\t\tif err != nil {\n\t\t\tlog.WithFields(listenFields).Fatal(err)\n\t\t}\n\t\tl, err = net.ListenTCP(\"tcp\", a)\n\t\tif err != nil {\n\t\t\tlog.WithFields(listenFields).Fatal(err)\n\t\t}\n\t}\n\n\tgo func() {\n\t\tif err := http.Serve(l, nil); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\tlog.WithFields(listenFields).Info(\"Radio Noise Project listening\")\n\n\tsigChan := make(chan os.Signal)\n\tsignal.Notify(sigChan, syscall.SIGINT, syscall.SIGQUIT)\n\n\tsig := <-sigChan\n\tlog.WithFields(log.Fields{\"signal\": sig}).Info(\"Exiting due to signal\")\n\n\th.Done()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Jacob Taylor jacob@ablox.io\n\/\/ License: Apache2 - http:\/\/www.apache.org\/licenses\/LICENSE-2.0\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/fsnotify\/fsnotify\"\n\t\"github.com\/urfave\/cli\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\n\/\/ settings for the server\ntype Settings struct {\n\tDirectory string\n}\n\nvar globalSettings Settings = Settings{\n\tDirectory: \"\",\n}\n\nfunc main() {\n\tfmt.Printf(\"replicat initializing....\\n\")\n\n\tapp := cli.NewApp()\n\tapp.Name = \"Replicat\"\n\tapp.Usage = \"rsync for the cloud\"\n\tapp.Action = func(c *cli.Context) error {\n\t\tglobalSettings.Directory = c.GlobalString(\"directory\")\n\n\t\tif globalSettings.Directory == \"\" {\n\t\t\tpanic(\"directory is required to serve files\\n\")\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:   \"directory, d\",\n\t\t\tValue:  globalSettings.Directory,\n\t\t\tUsage:  \"Specify a directory where the files to share are located.\",\n\t\t\tEnvVar: \"DIRECTORY\",\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n\n\tfmt.Printf(\"replicat online....\\n\")\n\tfmt.Printf(\"serving files from: %s\\n\", globalSettings.Directory)\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer watcher.Close()\n\tdefer fmt.Printf(\"End of line\\n\")\n\n\tdone := make(chan bool)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-watcher.Events:\n\t\t\t\tif event.Op&fsnotify.Write == fsnotify.Write {\n\t\t\t\t\tlog.Println(\"file updated:\", event.Name)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"event:\", event)\n\t\t\t\t}\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tlog.Println(\"error:\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tlistOfFolders, err := createListOfFolders(globalSettings.Directory)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, folder := range listOfFolders {\n\t\terr = watcher.Add(folder)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tfmt.Printf(\"Now listing on: %d folders under: %s\\n\", len(listOfFolders), globalSettings.Directory)\n\n\t\/\/ Let's read the\n\t<-done\n\n}\n\nfunc createListOfFolders(basePath string) ([]string, error) {\n\tpaths := make([]string, 0, 100)\n\tpendingPaths := make([]string, 0, 100)\n\tpendingPaths = append(pendingPaths, basePath)\n\n\tfor len(pendingPaths) > 0 {\n\t\tcurrentPath := pendingPaths[0]\n\t\tpaths = append(paths, currentPath)\n\t\tpendingPaths = pendingPaths[1:]\n\n\t\t\/\/ Read the directories in the path\n\t\tf, err := os.Open(currentPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdirEntries, err := f.Readdir(-1)\n\t\tfor _, entry := range dirEntries {\n\t\t\tif entry.IsDir() {\n\t\t\t\tentry.Mode()\n\t\t\t\tnewDirectory := filepath.Join(currentPath, entry.Name())\n\t\t\t\tpendingPaths = append(pendingPaths, newDirectory)\n\t\t\t}\n\t\t}\n\t\tf.Close()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn paths, nil\n}\n<commit_msg>building file list with slop code<commit_after>\/\/ Copyright 2016 Jacob Taylor jacob@ablox.io\n\/\/ License: Apache2 - http:\/\/www.apache.org\/licenses\/LICENSE-2.0\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/fsnotify\/fsnotify\"\n\t\"github.com\/urfave\/cli\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\n\/\/ settings for the server\ntype Settings struct {\n\tDirectory string\n}\n\nvar globalSettings Settings = Settings{\n\tDirectory: \"\",\n}\n\nfunc main() {\n\tfmt.Printf(\"replicat initializing....\\n\")\n\n\tapp := cli.NewApp()\n\tapp.Name = \"Replicat\"\n\tapp.Usage = \"rsync for the cloud\"\n\tapp.Action = func(c *cli.Context) error {\n\t\tglobalSettings.Directory = c.GlobalString(\"directory\")\n\n\t\tif globalSettings.Directory == \"\" {\n\t\t\tpanic(\"directory is required to serve files\\n\")\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:   \"directory, d\",\n\t\t\tValue:  globalSettings.Directory,\n\t\t\tUsage:  \"Specify a directory where the files to share are located.\",\n\t\t\tEnvVar: \"DIRECTORY\",\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n\n\tfmt.Printf(\"replicat online....\\n\")\n\tfmt.Printf(\"serving files from: %s\\n\", globalSettings.Directory)\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer watcher.Close()\n\tdefer fmt.Printf(\"End of line\\n\")\n\n\tdone := make(chan bool)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-watcher.Events:\n\t\t\t\tif event.Op&fsnotify.Write == fsnotify.Write {\n\t\t\t\t\tlog.Println(\"file updated:\", event.Name)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"event:\", event)\n\t\t\t\t}\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tlog.Println(\"error:\", err)\n\t\t\t}\n\t\t}\n\t}()\n\n\tlistOfFolders, err := createListOfFolders(globalSettings.Directory)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, folder := range listOfFolders {\n\t\terr = watcher.Add(folder)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tfmt.Printf(\"Now listing on: %d folders under: %s\\n\", len(listOfFolders), globalSettings.Directory)\n\n\tfmt.Println(\"Scanning files\")\n\n\t\/\/listOfFiles := make(map[string][]string)\n\t\/\/\n\t\/\/sort.Strings(listOfFolders)\n\t\/\/for _, folder := range listOfFolders {\n\t\/\/\tfmt.Printf(\"%s\\n\", folder)\n\t\/\/\n\t\/\/\n\t\/\/}\n\n\n\t\/\/ Let's read the\n\t<-done\n\n}\n\nfunc createListOfFolders(basePath string) ([]string, error) {\n\tpaths := make([]string, 0, 100)\n\tpendingPaths := make([]string, 0, 100)\n\tpendingPaths = append(pendingPaths, basePath)\n\tlistOfFileInfo := make(map[string][]os.FileInfo)\n\n\tfor len(pendingPaths) > 0 {\n\t\tcurrentPath := pendingPaths[0]\n\t\tpaths = append(paths, currentPath)\n\t\tfileList := make([]os.FileInfo, 0, 100)\n\t\tpendingPaths = pendingPaths[1:]\n\n\t\t\/\/ Read the directories in the path\n\t\tf, err := os.Open(currentPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdirEntries, err := f.Readdir(-1)\n\t\tfor _, entry := range dirEntries {\n\t\t\tif entry.IsDir() {\n\t\t\t\tentry.Mode()\n\t\t\t\tnewDirectory := filepath.Join(currentPath, entry.Name())\n\t\t\t\tpendingPaths = append(pendingPaths, newDirectory)\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Before Adding %s to %v\", entry, fileList)\n\t\t\t\tfileList = append(fileList, entry)\n\t\t\t\tfmt.Println(\"Done   Adding %s to %v\", entry, fileList)\n\t\t\t}\n\t\t}\n\t\tf.Close()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfmt.Printf(\"setting %s files to %v\\n\", currentPath, fileList)\n\t\tlistOfFileInfo[currentPath] = fileList\n\t}\n\n\tfmt.Println(\"About to print\")\n\tfor _, folder := range paths {\n\t\tfmt.Printf(\"PATH: %s\\n\", folder)\n\t\tfor _, entry := range listOfFileInfo[folder] {\n\t\t\tfmt.Printf(\"%s\\n\", entry)\n\t\t}\n\t}\n\n\treturn paths, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype ItemFrequency struct {\n\titem string\n\tfreq int\n}\n\nfunc GetFrequencies(str string, max_len int) (freqs []ItemFrequency) {\n\tfreq_map := make(map[string]int, 10)\n\n\tfor start := range str {\n\t\tfor end := start + 1; end < len(str) && end-start <= max_len; end++ {\n\t\t\tslice := str[start:end]\n\t\t\tif _, ok := freq_map[slice]; ok {\n\t\t\t\tfreq_map[slice] += 1\n\t\t\t} else {\n\t\t\t\tfreq_map[slice] = 1\n\t\t\t}\n\t\t}\n\t}\n\n\tfreqs = make([]ItemFrequency, len(freq_map))\n\ti := 0\n\tfor item, freq := range freq_map {\n\t\tfreqs[i] = ItemFrequency{\n\t\t\titem: item,\n\t\t\tfreq: freq}\n\t\ti += 1\n\t}\n\n\tsort.Slice(freqs, func(i, j int) bool { return freqs[i].freq > freqs[j].freq })\n\treturn\n}\n\nfunc main() {\n\tinput_flag := flag.String(\"input\", \"\", \"Input string for the compression algorithm\")\n\n\tflag.Parse()\n\n\tinput := *input_flag\n\n\tfreqs := GetFrequencies(input, 2)\n\n\tfmt.Printf(\"input = %s\\n\\n\", input)\n\tfmt.Printf(\"freqs =\\n\")\n\n\tfor _, pair := range freqs {\n\t\tfmt.Printf(\"%d\\t'%s'\\n\", pair.freq, pair.item)\n\t}\n\n}\n<commit_msg>added reading from file or stdin<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sort\"\n)\n\ntype ItemFrequency struct {\n\titem string\n\tfreq int\n}\n\nfunc GetFrequencies(str string, max_len int) (freqs []ItemFrequency) {\n\tfreq_map := make(map[string]int, 10)\n\n\tfor start := range str {\n\t\tfor end := start + 1; end < len(str) && end-start <= max_len; end++ {\n\t\t\tslice := str[start:end]\n\t\t\tif _, ok := freq_map[slice]; ok {\n\t\t\t\tfreq_map[slice] += 1\n\t\t\t} else {\n\t\t\t\tfreq_map[slice] = 1\n\t\t\t}\n\t\t}\n\t}\n\n\tfreqs = make([]ItemFrequency, len(freq_map))\n\ti := 0\n\tfor item, freq := range freq_map {\n\t\tfreqs[i] = ItemFrequency{\n\t\t\titem: item,\n\t\t\tfreq: freq}\n\t\ti += 1\n\t}\n\n\tsort.Slice(freqs, func(i, j int) bool { return freqs[i].freq > freqs[j].freq })\n\treturn\n}\n\nfunc main() {\n\n\tfile_name := flag.String(\"i\", \"\", \"Input file\")\n\tmax_freq_group_len := flag.Int(\"mfgl\", 2, \"Maximum length in bytes for grouping in algorithm\")\n\tflag.Parse()\n\n\tvar file *os.File\n\n\tif *file_name == \"\" {\n\t\tfile = os.Stdin\n\t} else {\n\t\tvar err interface{}\n\t\tfile, err = os.Open(*file_name)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif *max_freq_group_len < 1 || *max_freq_group_len >= 8 {\n\t\tpanic(\"Specified max_freq_group_len is not allowed\")\n\t}\n\n\tvar input_buff bytes.Buffer\n\tio.Copy(&input_buff, file)\n\n\tinput := input_buff.String()\n\n\tfreqs := GetFrequencies(input, *max_freq_group_len)\n\n\tfor _, pair := range freqs {\n\t\tfmt.Printf(\"%d\\t'%s'\\n\", pair.freq, pair.item)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\nconst VERSION = \"1.2\"\n\nfunc init() {\n\t\/\/ make sure we only have one process and that it runs on the main thread (so that ideally, when we Exec, we keep our user switches and stuff)\n\truntime.GOMAXPROCS(1)\n\truntime.LockOSThread()\n}\n\nfunc main() {\n\tlog.SetFlags(0) \/\/ no timestamps on our logs\n\n\tif len(os.Args) <= 2 {\n\t\tlog.Printf(\"Usage: %s user-spec command [args]\", os.Args[0])\n\t\tlog.Printf(\"   ie: %s tianon bash\", os.Args[0])\n\t\tlog.Printf(\"       %s nobody:root bash -c 'whoami && id'\", os.Args[0])\n\t\tlog.Printf(\"       %s 1000:1 id\", os.Args[0])\n\t\tlog.Println()\n\t\tlog.Printf(\"%s version: %s (%s on %s\/%s; %s)\", os.Args[0], VERSION, runtime.Version(), runtime.GOOS, runtime.GOARCH, runtime.Compiler)\n\t\tlog.Println()\n\t\tos.Exit(1)\n\t}\n\n\terr := SetupUser(os.Args[1])\n\tif err != nil {\n\t\tlog.Fatalf(\"error: failed switching to %q: %v\", os.Args[1], err)\n\t}\n\n\tname, err := exec.LookPath(os.Args[2])\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\n\terr = syscall.Exec(name, os.Args[2:], os.Environ())\n\tif err != nil {\n\t\tlog.Fatalf(\"error: exec failed: %v\", err)\n\t}\n}\n<commit_msg>Add golang.org\/s\/go14customimport<commit_after>package main \/\/ import \"github.com\/tianon\/gosu\"\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\nconst VERSION = \"1.2\"\n\nfunc init() {\n\t\/\/ make sure we only have one process and that it runs on the main thread (so that ideally, when we Exec, we keep our user switches and stuff)\n\truntime.GOMAXPROCS(1)\n\truntime.LockOSThread()\n}\n\nfunc main() {\n\tlog.SetFlags(0) \/\/ no timestamps on our logs\n\n\tif len(os.Args) <= 2 {\n\t\tlog.Printf(\"Usage: %s user-spec command [args]\", os.Args[0])\n\t\tlog.Printf(\"   ie: %s tianon bash\", os.Args[0])\n\t\tlog.Printf(\"       %s nobody:root bash -c 'whoami && id'\", os.Args[0])\n\t\tlog.Printf(\"       %s 1000:1 id\", os.Args[0])\n\t\tlog.Println()\n\t\tlog.Printf(\"%s version: %s (%s on %s\/%s; %s)\", os.Args[0], VERSION, runtime.Version(), runtime.GOOS, runtime.GOARCH, runtime.Compiler)\n\t\tlog.Println()\n\t\tos.Exit(1)\n\t}\n\n\terr := SetupUser(os.Args[1])\n\tif err != nil {\n\t\tlog.Fatalf(\"error: failed switching to %q: %v\", os.Args[1], err)\n\t}\n\n\tname, err := exec.LookPath(os.Args[2])\n\tif err != nil {\n\t\tlog.Fatalf(\"error: %v\", err)\n\t}\n\n\terr = syscall.Exec(name, os.Args[2:], os.Environ())\n\tif err != nil {\n\t\tlog.Fatalf(\"error: exec failed: %v\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/captncraig\/github-webhooks\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nvar scriptDir string\nvar scriptExt = \".sh\"\n\nfunc init() {\n\tscriptDir = os.Getenv(\"TINYCI-SCRIPT-DIR\")\n\n\tif scriptDir == \"\" {\n\t\tvar err error\n\t\tscriptDir, err = os.Getwd()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tscriptDir = filepath.Join(scriptDir, \"scripts\")\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\tscriptExt = \".bat\"\n\t}\n}\n\nfunc main() {\n\n\tgitHooks := webhooks.WebhookListener{}\n\tgitHooks.OnPush = githubHook\n\thttp.HandleFunc(\"\/gh\", gitHooks.GetHttpListener())\n\thttp.ListenAndServe(\":4567\", nil)\n}\n\nfunc githubHook(event *webhooks.PushEvent, _ *webhooks.WebhookContext) {\n\trepo := strings.Replace(event.Repository.FullName, \"\/\", \".\", -1)\n\trefPath := strings.Split(event.Ref, \"\/\")\n\tref := refPath[len(refPath)-1]\n\trunScriptIfExists(fmt.Sprintf(\"%s\", repo))\n\trunScriptIfExists(fmt.Sprintf(\"%s:%s\", repo, ref))\n}\n\nfunc runScriptIfExists(name string) {\n\tfilename := filepath.Join(scriptDir, name+scriptExt)\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\t\tfmt.Printf(\"no such file or directory: %s\", filename)\n\t\treturn\n\t}\n\tcmd := exec.Command(filename)\n\toutput, err := cmd.CombinedOutput()\n\tfmt.Println(output, err)\n}\n<commit_msg>better message<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/captncraig\/github-webhooks\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nvar scriptDir string\nvar scriptExt = \".sh\"\n\nfunc init() {\n\tscriptDir = os.Getenv(\"TINYCI-SCRIPT-DIR\")\n\n\tif scriptDir == \"\" {\n\t\tvar err error\n\t\tscriptDir, err = os.Getwd()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tscriptDir = filepath.Join(scriptDir, \"scripts\")\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\tscriptExt = \".bat\"\n\t}\n}\n\nfunc main() {\n\n\tgitHooks := webhooks.WebhookListener{}\n\tgitHooks.OnPush = githubHook\n\thttp.HandleFunc(\"\/gh\", gitHooks.GetHttpListener())\n\thttp.ListenAndServe(\":4567\", nil)\n}\n\nfunc githubHook(event *webhooks.PushEvent, _ *webhooks.WebhookContext) {\n\trepo := strings.Replace(event.Repository.FullName, \"\/\", \".\", -1)\n\trefPath := strings.Split(event.Ref, \"\/\")\n\tref := refPath[len(refPath)-1]\n\trunScriptIfExists(fmt.Sprintf(\"%s\", repo))\n\trunScriptIfExists(fmt.Sprintf(\"%s:%s\", repo, ref))\n}\n\nfunc runScriptIfExists(name string) {\n\tfilename := filepath.Join(scriptDir, name+scriptExt)\n\tif _, err := os.Stat(filename); os.IsNotExist(err) {\n\t\tfmt.Println(\"Script does not exist: %s. Skipping\\n\", filename)\n\t\treturn\n\t}\n\tcmd := exec.Command(filename)\n\toutput, err := cmd.CombinedOutput()\n\tfmt.Println(output, err)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\n\t\"github.com\/concourse\/atc\/auth\/provider\"\n\t\"github.com\/concourse\/fly\/commands\"\n\t\"github.com\/concourse\/fly\/rc\"\n\t\"github.com\/concourse\/fly\/ui\"\n\t\"github.com\/concourse\/go-concourse\/concourse\"\n\t\"github.com\/jessevdk\/go-flags\"\n\n\t_ \"github.com\/concourse\/atc\/auth\/genericoauth\"\n\t_ \"github.com\/concourse\/atc\/auth\/github\"\n\t_ \"github.com\/concourse\/atc\/auth\/uaa\"\n)\n\nfunc main() {\n\tparser := flags.NewParser(&commands.Fly, flags.HelpFlag|flags.PassDoubleDash)\n\tparser.NamespaceDelimiter = \"-\"\n\n\tsetTeamCommand := parser.Find(\"set-team\")\n\tauthConfigs := make(provider.AuthConfigs)\n\n\tfor name, p := range provider.GetProviders() {\n\t\tauthConfigs[name] = p.AddAuthGroup(setTeamCommand.Group)\n\t}\n\n\tcommands.Fly.SetTeam.ProviderAuth = authConfigs\n\n\t_, err := parser.Parse()\n\tif err != nil {\n\t\tif err == concourse.ErrUnauthorized {\n\t\t\tfmt.Fprintln(ui.Stderr, \"not authorized. run the following to log in:\")\n\t\t\tfmt.Fprintln(ui.Stderr, \"\")\n\t\t\tfmt.Fprintln(ui.Stderr, \"    \"+ui.Embolden(\"fly -t %s login\", commands.Fly.Target))\n\t\t\tfmt.Fprintln(ui.Stderr, \"\")\n\t\t} else if err == rc.ErrNoTargetSpecified {\n\t\t\tfmt.Fprintln(ui.Stderr, \"no target specified. specify the target with \"+ui.Embolden(\"-t\")+\" or log in like so:\")\n\t\t\tfmt.Fprintln(ui.Stderr, \"\")\n\t\t\tfmt.Fprintln(ui.Stderr, \"    \"+ui.Embolden(\"fly -t (alias) login -c (concourse url)\"))\n\t\t\tfmt.Fprintln(ui.Stderr, \"\")\n\t\t} else if versionErr, ok := err.(rc.ErrVersionMismatch); ok {\n\t\t\tfmt.Fprintln(ui.Stderr, versionErr.Error())\n\t\t\tfmt.Fprintln(ui.Stderr, ui.WarningColor(\"cowardly refusing to run due to significant version discrepancy\"))\n\t\t} else if netErr, ok := err.(net.Error); ok {\n\t\t\tfmt.Fprintf(ui.Stderr, \"could not reach the Concourse server called %s:\\n\", ui.Embolden(\"%s\", commands.Fly.Target))\n\n\t\t\tfmt.Fprintln(ui.Stderr, \"\")\n\t\t\tfmt.Fprintln(ui.Stderr, \"    \"+ui.Embolden(\"%s\", netErr))\n\t\t\tfmt.Fprintln(ui.Stderr, \"\")\n\t\t\tfmt.Fprintln(ui.Stderr, \"is the targeted Concourse running? better go catch it lol\")\n\t\t} else if err == commands.ErrShowHelpMessage {\n\t\t\thelpParser := flags.NewParser(&commands.Fly, flags.HelpFlag)\n\t\t\thelpParser.NamespaceDelimiter = \"-\"\n\t\t\thelpParser.ParseArgs([]string{\"-h\"})\n\t\t\thelpParser.WriteHelp(os.Stdout)\n\t\t\tos.Exit(0)\n\t\t} else {\n\t\t\tfmt.Fprintf(ui.Stderr, \"error: %s\\n\", err)\n\t\t}\n\n\t\tos.Exit(1)\n\t}\n}\n<commit_msg>fix setting up auth flags<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\n\t\"github.com\/concourse\/atc\/auth\/provider\"\n\t\"github.com\/concourse\/fly\/commands\"\n\t\"github.com\/concourse\/fly\/rc\"\n\t\"github.com\/concourse\/fly\/ui\"\n\t\"github.com\/concourse\/go-concourse\/concourse\"\n\t\"github.com\/jessevdk\/go-flags\"\n\n\t_ \"github.com\/concourse\/atc\/auth\/genericoauth\"\n\t_ \"github.com\/concourse\/atc\/auth\/github\"\n\t_ \"github.com\/concourse\/atc\/auth\/uaa\"\n)\n\nfunc main() {\n\tparser := flags.NewParser(&commands.Fly, flags.HelpFlag|flags.PassDoubleDash)\n\tparser.NamespaceDelimiter = \"-\"\n\n\tsetTeamCommand := parser.Find(\"set-team\")\n\tauthConfigs := make(provider.AuthConfigs)\n\n\tfor name, p := range provider.GetProviders() {\n\t\tauthGroup := p.AuthGroup()\n\n\t\tgroup, err := setTeamCommand.Group.AddGroup(authGroup.Name(), \"\", authGroup.AuthConfig())\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tgroup.Namespace = authGroup.Namespace()\n\n\t\tauthConfigs[name] = authGroup.AuthConfig()\n\t}\n\n\tcommands.Fly.SetTeam.ProviderAuth = authConfigs\n\n\t_, err := parser.Parse()\n\tif err != nil {\n\t\tif err == concourse.ErrUnauthorized {\n\t\t\tfmt.Fprintln(ui.Stderr, \"not authorized. run the following to log in:\")\n\t\t\tfmt.Fprintln(ui.Stderr, \"\")\n\t\t\tfmt.Fprintln(ui.Stderr, \"    \"+ui.Embolden(\"fly -t %s login\", commands.Fly.Target))\n\t\t\tfmt.Fprintln(ui.Stderr, \"\")\n\t\t} else if err == rc.ErrNoTargetSpecified {\n\t\t\tfmt.Fprintln(ui.Stderr, \"no target specified. specify the target with \"+ui.Embolden(\"-t\")+\" or log in like so:\")\n\t\t\tfmt.Fprintln(ui.Stderr, \"\")\n\t\t\tfmt.Fprintln(ui.Stderr, \"    \"+ui.Embolden(\"fly -t (alias) login -c (concourse url)\"))\n\t\t\tfmt.Fprintln(ui.Stderr, \"\")\n\t\t} else if versionErr, ok := err.(rc.ErrVersionMismatch); ok {\n\t\t\tfmt.Fprintln(ui.Stderr, versionErr.Error())\n\t\t\tfmt.Fprintln(ui.Stderr, ui.WarningColor(\"cowardly refusing to run due to significant version discrepancy\"))\n\t\t} else if netErr, ok := err.(net.Error); ok {\n\t\t\tfmt.Fprintf(ui.Stderr, \"could not reach the Concourse server called %s:\\n\", ui.Embolden(\"%s\", commands.Fly.Target))\n\n\t\t\tfmt.Fprintln(ui.Stderr, \"\")\n\t\t\tfmt.Fprintln(ui.Stderr, \"    \"+ui.Embolden(\"%s\", netErr))\n\t\t\tfmt.Fprintln(ui.Stderr, \"\")\n\t\t\tfmt.Fprintln(ui.Stderr, \"is the targeted Concourse running? better go catch it lol\")\n\t\t} else if err == commands.ErrShowHelpMessage {\n\t\t\thelpParser := flags.NewParser(&commands.Fly, flags.HelpFlag)\n\t\t\thelpParser.NamespaceDelimiter = \"-\"\n\t\t\thelpParser.ParseArgs([]string{\"-h\"})\n\t\t\thelpParser.WriteHelp(os.Stdout)\n\t\t\tos.Exit(0)\n\t\t} else {\n\t\t\tfmt.Fprintf(ui.Stderr, \"error: %s\\n\", err)\n\t\t}\n\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/jmoiron\/sqlx\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nvar semSize int\n\nfunc init() {\n\tsemSizeStr := os.Args[1]\n\tvar err error\n\tsemSize, err = strconv.Atoi(semSizeStr)\n\tif err != nil {\n\t\tpanic(\"invalid sem size\")\n\t}\n\n\tgo func() {\n\t\terr = http.ListenAndServe(\":28888\", nil)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n}\n\ntype ShopInfo struct {\n\tQq            string\n\tAuthenticated int\n\tWw_nickname   string \/\/ 旺旺号\n\tWechat        string\n\tContacts_name string\n\tTelephone     []string\n\tMarketName    string \/\/ 市场\n\tName          string \/\/ 档口名\n\tId            int\n\tPosition      string \/\/ 档口\n\tFloor         int    \/\/ 市场楼层\n\tBid           int    \/\/ ?\n\tShop_category string \/\/ 主营\n\tCid           int    \/\/ ?\n\tStatus        int    \/\/ ?\n}\n\ntype Image struct {\n\tGoodId int `db:\"good_id\"`\n\tUrl    string\n\tSha512 []byte\n}\n\ntype Url struct {\n\tUrlId  int `db:\"url_id\"`\n\tUrl    string\n\tSha512 []byte\n}\n\nfunc main() {\n\tif len(os.Args) > 2 {\n\t\tcollectShops()\n\t\tcollectGoods()\n\t\thashImages()\n\t} else {\n\t\thashImages()\n\t\tcollectShops()\n\t\tcollectGoods()\n\t}\n}\n\nfunc collectShops() {\n\t\/\/ collect pages\n\tpage := 1\n\tinfos := []ShopInfo{}\n\tfor {\n\t\tpageUrl := fmt.Sprintf(\"http:\/\/www.vvic.com\/api\/shop\/navigation?bid=&currentPage=%d&pageSize=500\",\n\t\t\tpage)\n\t\tvar data struct {\n\t\t\tCode int\n\t\t\tData struct {\n\t\t\t\tCurrentPage int\n\t\t\t\tPageSize    int\n\t\t\t\tPageCount   int \/\/ 无用\n\t\t\t\tRecordCount int \/\/ 不等于len(RecordList)\n\t\t\t\tRecordList  []ShopInfo\n\t\t\t}\n\t\t}\n\t\tce(decodeFromUrl(pageUrl, &data), \"decode\")\n\t\tif len(data.Data.RecordList) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tinfos = append(infos, data.Data.RecordList...)\n\t\tpage++\n\t\tpt(\"%d %d\\n\", page, len(infos))\n\t}\n\n\tskip := make(map[int]bool)\n\tvar ids []int\n\tts := time.Now().Add(-time.Hour * 8).Unix()\n\terr := db.Select(&ids, `SELECT shop_id\n\t\tFROM shops \n\t\tWHERE last_update_time > $1`,\n\t\tts)\n\tce(err, \"select skip shop ids\")\n\tfor _, id := range ids {\n\t\tskip[id] = true\n\t}\n\n\tsem := make(chan bool, semSize)\n\twg := new(sync.WaitGroup)\n\twg.Add(len(infos))\n\tfor i, shop := range infos {\n\t\tsem <- true\n\t\ti := i\n\t\tshop := shop\n\t\tgo func() {\n\t\t\tdefer func() {\n\t\t\t\twg.Done()\n\t\t\t\t<-sem\n\t\t\t}()\n\t\t\terr := collectShop(skip, i, shop)\n\t\t\tif err != nil {\n\t\t\t\tpt(\"%v\\n\", err)\n\t\t\t}\n\t\t}()\n\t}\n\twg.Wait()\n\n\tpt(\"shops collected\\n\")\n}\n\nfunc collectShop(skip map[int]bool, i int, shop ShopInfo) (err error) {\n\tdefer ct(&err)\n\tpt(\"%20s %d\\n\", \"shop\", i)\n\n\t\/\/ 近期采集过的不管\n\tif _, ok := skip[shop.Id]; ok {\n\t\treturn\n\t}\n\n\tdb.MustExec(`INSERT INTO shops (\n\t\t\t\tshop_id, name, market_name, floor, position\n\t\t\t) VALUES ($1, $2, $3, $4, $5)\n\t\t\tON CONFLICT (shop_id) DO UPDATE SET \n\t\t\t\tname = $2, market_name = $3, floor = $4, position = $5`,\n\t\tshop.Id,\n\t\tshop.Name,\n\t\tshop.MarketName,\n\t\tshop.Floor,\n\t\tshop.Position,\n\t)\n\n\t\/\/ set existing goods' status to 0\n\tdb.MustExec(`UPDATE goods SET\n\t\tstatus = 0\n\t\tWHERE shop_id = $1`,\n\t\tshop.Id)\n\n\t\/\/ collect in sale goods\n\tmaxPage := 9999\n\tpage := 1\n\tfor {\n\t\tif page > maxPage {\n\t\t\tbreak\n\t\t}\n\n\t\tvar data struct {\n\t\t\tCode int\n\t\t\tData struct {\n\t\t\t\t\/\/CurrentPage int\n\t\t\t\tPageCount int \/\/ 总页数\n\t\t\t\t\/\/PageSize    int\n\t\t\t\t\/\/RecordCount int \/\/ 总商品数\n\t\t\t\tRecordList []struct {\n\t\t\t\t\tDiscount_price interface{} \/\/ 拿货价\n\t\t\t\t\t\/\/Tid            string  \/\/ ??\n\t\t\t\t\t\/\/Is_shop_auth   int     \/\/ ?\n\t\t\t\t\t\/\/Price          float64 \/\/ 原价\n\t\t\t\t\tId     string\n\t\t\t\t\tArt_no string \/\/ 档口货号\n\t\t\t\t\t\/\/Sub_name       string \/\/ 市场名\n\t\t\t\t\t\/\/Shop_name      string \/\/ 档口名\n\t\t\t\t\t\/\/Shop_id        int\n\t\t\t\t\tUp_time int64 \/\/ 上架时间，millisecond\n\t\t\t\t\t\/\/Position       string  \/\/ 档口位置\n\t\t\t\t\t\/\/Upload_num     int     \/\/ ?\n\t\t\t\t\tIs_tx int \/\/ 是否退现\n\t\t\t\t\t\/\/Is_df          int     \/\/ 是否代发\n\t\t\t\t\t\/\/Is_sp          int     \/\/ 是否实拍\n\t\t\t\t\t\/\/Index_img_url  string  \/\/ 主图地址\n\t\t\t\t\tTitle string \/\/ 标题\n\t\t\t\t\t\/\/Bname          string  \/\/ ?\n\t\t\t\t\t\/\/Bid            string  \/\/ ?\n\t\t\t\t\tTcid       string  \/\/ 分类id\n\t\t\t\t\tScore      float64 \/\/ 分数 ？\n\t\t\t\t\tSort_score float64 \/\/ 排序分数 ？\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\turl := fmt.Sprintf(\"http:\/\/www.vvic.com\/rest\/shop\/search-item?shop_id=%d&q=&currentPage=%d\",\n\t\t\tshop.Id, page)\n\t\tretry := 5\n\tdecode:\n\t\terr := decodeFromUrl(url, &data)\n\t\tif err != nil {\n\t\t\tif retry > 0 {\n\t\t\t\tretry--\n\t\t\t\tgoto decode\n\t\t\t}\n\t\t\tce(err, \"decode data %s\", url)\n\t\t}\n\t\tif page == 1 { \/\/ 第一页\n\t\t\tmaxPage = data.Data.PageCount\n\t\t}\n\t\tce(withTx(db, func(tx *sqlx.Tx) (err error) {\n\t\t\tdefer ct(&err)\n\t\t\tfor _, item := range data.Data.RecordList {\n\n\t\t\t\tif item.Discount_price == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tvar price float64\n\t\t\t\tswitch p := item.Discount_price.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tprice, err = strconv.ParseFloat(p, 64)\n\t\t\t\t\tce(err, \"parse price\")\n\t\t\t\tcase float64:\n\t\t\t\t\tprice = p\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(fmt.Sprintf(\"invalid price %T\", item.Discount_price))\n\t\t\t\t}\n\t\t\t\tif price == 0 { \/\/ 没有批发价的不理\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tvar imagesCollected bool\n\t\t\t\terr := tx.QueryRow(`INSERT INTO goods (\n\t\t\t\t\tgood_id,\n\t\t\t\t\tprice,\n\t\t\t\t\tshop_id,\n\t\t\t\t\tadded_at,\n\t\t\t\t\tcategory,\n\t\t\t\t\tscore,\n\t\t\t\t\tsort_score,\n\t\t\t\t\ttitle,\n\t\t\t\t\tstatus,\n\t\t\t\t\tinternal_id\n\t\t\t\t) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9)\n\t\t\t\t\tON CONFLICT (good_id) DO UPDATE SET\n\t\t\t\t\tprice = $2,\n\t\t\t\t\tscore = $6,\n\t\t\t\t\tsort_score = $7,\n\t\t\t\t\ttitle = $8,\n\t\t\t\t\tstatus = 1,\n\t\t\t\t\tinternal_id = $9\n\t\t\t\t\tRETURNING images_collected\n\t\t\t\t`,\n\t\t\t\t\titem.Id,\n\t\t\t\t\tprice,\n\t\t\t\t\tshop.Id,\n\t\t\t\t\ttime.Unix(item.Up_time\/1000, 0).Format(\"2006-01-02\"),\n\t\t\t\t\titem.Tcid,\n\t\t\t\t\titem.Score,\n\t\t\t\t\titem.Sort_score,\n\t\t\t\t\titem.Title,\n\t\t\t\t\titem.Art_no,\n\t\t\t\t).Scan(&imagesCollected)\n\t\t\t\tce(err, \"insert goods\")\n\t\t\t\tif !imagesCollected { \/\/ insert into images_not_collected\n\t\t\t\t\t_, err = tx.Exec(`INSERT INTO images_not_collected (good_id)\n\t\t\t\t\t\tVALUES ($1)\n\t\t\t\t\t\tON CONFLICT (good_id) DO NOTHING\n\t\t\t\t\t\t`,\n\t\t\t\t\t\titem.Id,\n\t\t\t\t\t)\n\t\t\t\t\tce(err, \"insert into images_not_collected\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t\treturn\n\t\t}), \"tx\")\n\t\tpage++\n\t}\n\n\t\/\/ 更新\n\tdb.MustExec(`UPDATE shops SET last_update_time = $1\n\t\tWHERE shop_id = $2`,\n\t\ttime.Now().Unix(),\n\t\tshop.Id)\n\n\treturn\n}\n<commit_msg>fixes<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/jmoiron\/sqlx\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nvar semSize int\n\nfunc init() {\n\tsemSizeStr := os.Args[1]\n\tvar err error\n\tsemSize, err = strconv.Atoi(semSizeStr)\n\tif err != nil {\n\t\tpanic(\"invalid sem size\")\n\t}\n\n\tgo func() {\n\t\terr = http.ListenAndServe(\":28888\", nil)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n}\n\ntype ShopInfo struct {\n\tQq            string\n\tAuthenticated int\n\tWw_nickname   string \/\/ 旺旺号\n\tWechat        string\n\tContacts_name string\n\t\/\/Telephone     []string \/\/ may be string\n\tMarketName    string \/\/ 市场\n\tName          string \/\/ 档口名\n\tId            int\n\tPosition      string \/\/ 档口\n\tFloor         int    \/\/ 市场楼层\n\tBid           int    \/\/ ?\n\tShop_category string \/\/ 主营\n\tCid           int    \/\/ ?\n\tStatus        int    \/\/ ?\n}\n\ntype Image struct {\n\tGoodId int `db:\"good_id\"`\n\tUrl    string\n\tSha512 []byte\n}\n\ntype Url struct {\n\tUrlId  int `db:\"url_id\"`\n\tUrl    string\n\tSha512 []byte\n}\n\nfunc main() {\n\t\/\/collectShop(nil, 0, ShopInfo{\n\t\/\/\tId: 14885,\n\t\/\/})\n\n\t\/\/return \/\/TODO\n\n\tif len(os.Args) > 2 {\n\t\tcollectShops()\n\t\tcollectGoods()\n\t\thashImages()\n\t} else {\n\t\thashImages()\n\t\tcollectShops()\n\t\tcollectGoods()\n\t}\n}\n\nfunc collectShops() {\n\t\/\/ collect pages\n\tpage := 1\n\tinfos := []ShopInfo{}\n\tfor {\n\t\tpageUrl := fmt.Sprintf(\"http:\/\/www.vvic.com\/api\/shop\/navigation?bid=&currentPage=%d&pageSize=500\",\n\t\t\tpage)\n\t\tvar data struct {\n\t\t\tCode int\n\t\t\tData struct {\n\t\t\t\tCurrentPage int\n\t\t\t\tPageSize    int\n\t\t\t\tPageCount   int \/\/ 无用\n\t\t\t\tRecordCount int \/\/ 不等于len(RecordList)\n\t\t\t\tRecordList  []ShopInfo\n\t\t\t}\n\t\t}\n\t\tbody, err := getBody(pageUrl)\n\t\tce(err, \"get body %s\\n\", pageUrl)\n\t\tce(json.NewDecoder(bytes.NewReader(body)).Decode(&data), \"decode \\n %s\\n\", body)\n\t\t\/\/ce(decodeFromUrl(pageUrl, &data), \"decode\")\n\t\tif len(data.Data.RecordList) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tinfos = append(infos, data.Data.RecordList...)\n\t\tpage++\n\t\tpt(\"%d %d\\n\", page, len(infos))\n\t}\n\n\tskip := make(map[int]bool)\n\tvar ids []int\n\tts := time.Now().Add(-time.Hour * 8).Unix()\n\terr := db.Select(&ids, `SELECT shop_id\n\t\tFROM shops \n\t\tWHERE last_update_time > $1`,\n\t\tts)\n\tce(err, \"select skip shop ids\")\n\tfor _, id := range ids {\n\t\tskip[id] = true\n\t}\n\n\tsem := make(chan bool, semSize)\n\twg := new(sync.WaitGroup)\n\twg.Add(len(infos))\n\tfor i, shop := range infos {\n\t\tsem <- true\n\t\ti := i\n\t\tshop := shop\n\t\tgo func() {\n\t\t\tdefer func() {\n\t\t\t\twg.Done()\n\t\t\t\t<-sem\n\t\t\t}()\n\t\t\terr := collectShop(skip, i, shop)\n\t\t\tif err != nil {\n\t\t\t\tpt(\"%v\\n\", err)\n\t\t\t}\n\t\t}()\n\t}\n\twg.Wait()\n\n\tpt(\"shops collected\\n\")\n}\n\nfunc collectShop(skip map[int]bool, i int, shop ShopInfo) (err error) {\n\tdefer ct(&err)\n\n\t\/\/ 近期采集过的不管\n\tif _, ok := skip[shop.Id]; ok {\n\t\treturn\n\t}\n\n\tdb.MustExec(`INSERT INTO shops (\n\t\t\t\tshop_id, name, market_name, floor, position\n\t\t\t) VALUES ($1, $2, $3, $4, $5)\n\t\t\tON CONFLICT (shop_id) DO UPDATE SET \n\t\t\t\tname = $2, market_name = $3, floor = $4, position = $5`,\n\t\tshop.Id,\n\t\tshop.Name,\n\t\tshop.MarketName,\n\t\tshop.Floor,\n\t\tshop.Position,\n\t)\n\n\t\/\/ set existing goods' status to 0\n\tdb.MustExec(`UPDATE goods SET\n\t\tstatus = 0\n\t\tWHERE shop_id = $1`,\n\t\tshop.Id)\n\n\t\/\/ collect in sale goods\n\titemCount := 0\n\tmaxPage := 9999\n\tpage := 1\n\tfor {\n\t\tif page > maxPage {\n\t\t\tbreak\n\t\t}\n\n\t\tvar data struct {\n\t\t\tCode int\n\t\t\tData struct {\n\t\t\t\t\/\/CurrentPage int\n\t\t\t\tPageCount int \/\/ 总页数\n\t\t\t\t\/\/PageSize    int\n\t\t\t\t\/\/RecordCount int \/\/ 总商品数\n\t\t\t\tRecordList []struct {\n\t\t\t\t\tDiscount_price interface{} \/\/ 拿货价\n\t\t\t\t\t\/\/Tid            string  \/\/ ??\n\t\t\t\t\t\/\/Is_shop_auth   int     \/\/ ?\n\t\t\t\t\t\/\/Price          float64 \/\/ 原价\n\t\t\t\t\tId     string\n\t\t\t\t\tArt_no string \/\/ 档口货号\n\t\t\t\t\t\/\/Sub_name       string \/\/ 市场名\n\t\t\t\t\t\/\/Shop_name      string \/\/ 档口名\n\t\t\t\t\t\/\/Shop_id        int\n\t\t\t\t\tUp_time int64 \/\/ 上架时间，millisecond\n\t\t\t\t\t\/\/Position       string  \/\/ 档口位置\n\t\t\t\t\t\/\/Upload_num     int     \/\/ ?\n\t\t\t\t\tIs_tx int \/\/ 是否退现\n\t\t\t\t\t\/\/Is_df          int     \/\/ 是否代发\n\t\t\t\t\t\/\/Is_sp          int     \/\/ 是否实拍\n\t\t\t\t\t\/\/Index_img_url  string  \/\/ 主图地址\n\t\t\t\t\tTitle string \/\/ 标题\n\t\t\t\t\t\/\/Bname          string  \/\/ ?\n\t\t\t\t\t\/\/Bid            string  \/\/ ?\n\t\t\t\t\tTcid       string  \/\/ 分类id\n\t\t\t\t\tScore      float64 \/\/ 分数 ？\n\t\t\t\t\tSort_score float64 \/\/ 排序分数 ？\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\turl := fmt.Sprintf(\"http:\/\/www.vvic.com\/rest\/shop\/search-item?shop_id=%d&q=&currentPage=%d\",\n\t\t\tshop.Id, page)\n\t\tretry := 5\n\tdecode:\n\t\terr := decodeFromUrl(url, &data)\n\t\tif err != nil {\n\t\t\tif retry > 0 {\n\t\t\t\tretry--\n\t\t\t\tgoto decode\n\t\t\t}\n\t\t\tce(err, \"decode data %s\", url)\n\t\t}\n\t\tif page == 1 { \/\/ 第一页\n\t\t\tmaxPage = data.Data.PageCount\n\t\t}\n\t\tce(withTx(db, func(tx *sqlx.Tx) (err error) {\n\t\t\tdefer ct(&err)\n\t\t\tfor _, item := range data.Data.RecordList {\n\n\t\t\t\tif item.Discount_price == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tvar price float64\n\t\t\t\tswitch p := item.Discount_price.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tprice, err = strconv.ParseFloat(p, 64)\n\t\t\t\t\tce(err, \"parse price\")\n\t\t\t\tcase float64:\n\t\t\t\t\tprice = p\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(fmt.Sprintf(\"invalid price %T\", item.Discount_price))\n\t\t\t\t}\n\t\t\t\tif price == 0 { \/\/ 没有批发价的不理\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tvar imagesCollected bool\n\t\t\t\terr := tx.QueryRow(`INSERT INTO goods (\n\t\t\t\t\tgood_id,\n\t\t\t\t\tprice,\n\t\t\t\t\tshop_id,\n\t\t\t\t\tadded_at,\n\t\t\t\t\tcategory,\n\t\t\t\t\tscore,\n\t\t\t\t\tsort_score,\n\t\t\t\t\ttitle,\n\t\t\t\t\tstatus,\n\t\t\t\t\tinternal_id\n\t\t\t\t) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 1, $9)\n\t\t\t\t\tON CONFLICT (good_id) DO UPDATE SET\n\t\t\t\t\tprice = $2,\n\t\t\t\t\tscore = $6,\n\t\t\t\t\tsort_score = $7,\n\t\t\t\t\ttitle = $8,\n\t\t\t\t\tstatus = 1,\n\t\t\t\t\tinternal_id = $9\n\t\t\t\t\tRETURNING images_collected\n\t\t\t\t`,\n\t\t\t\t\titem.Id,\n\t\t\t\t\tprice,\n\t\t\t\t\tshop.Id,\n\t\t\t\t\ttime.Unix(item.Up_time\/1000, 0).Format(\"2006-01-02\"),\n\t\t\t\t\titem.Tcid,\n\t\t\t\t\titem.Score,\n\t\t\t\t\titem.Sort_score,\n\t\t\t\t\titem.Title,\n\t\t\t\t\titem.Art_no,\n\t\t\t\t).Scan(&imagesCollected)\n\t\t\t\tce(err, \"insert goods\")\n\t\t\t\tif !imagesCollected { \/\/ insert into images_not_collected\n\t\t\t\t\t_, err = tx.Exec(`INSERT INTO images_not_collected (good_id)\n\t\t\t\t\t\tVALUES ($1)\n\t\t\t\t\t\tON CONFLICT (good_id) DO NOTHING\n\t\t\t\t\t\t`,\n\t\t\t\t\t\titem.Id,\n\t\t\t\t\t)\n\t\t\t\t\tce(err, \"insert into images_not_collected\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t\treturn\n\t\t}), \"tx\")\n\t\titemCount += len(data.Data.RecordList)\n\t\tpage++\n\t}\n\n\t\/\/ 更新\n\tdb.MustExec(`UPDATE shops SET last_update_time = $1\n\t\tWHERE shop_id = $2`,\n\t\ttime.Now().Unix(),\n\t\tshop.Id)\n\n\tpt(\"No.%d shop %d %d items\\n\", i, shop.Id, itemCount)\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package main - Server entrypoint for signature service\npackage main\n\nimport (\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/gorilla\/pat\"\n\t\"github.com\/hashicorp\/logutils\"\n\t\"github.com\/husobee\/dockerspew\/content\"\n\t\"github.com\/husobee\/dockerspew\/controllers\"\n\t\"github.com\/husobee\/dockerspew\/middlewares\"\n\t\"github.com\/husobee\/dockerspew\/models\"\n\t\"github.com\/spf13\/viper\"\n\t\"gopkg.in\/unrolled\/render.v1\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nfunc init() {\n\t\/\/ set some defaults\n\tviper.SetDefault(\"server_host\", \":8080\")\n\tviper.SetDefault(\"log_level\", \"WARN\")\n\tviper.SetDefault(\"gomaxprocs\", runtime.NumCPU())\n\tviper.SetDefault(\"docker_endpoint\", \"unix:\/\/\/var\/run\/docker.sock\")\n\t\/\/ get vars from viper env binding\n\tviper.SetEnvPrefix(\"dockerspew\") \/\/ will be uppercased automatically\n\tviper.BindEnv(\"server_host\")\n\tviper.BindEnv(\"log_level\")\n\tviper.BindEnv(\"docker_endpoint\")\n\t\/\/ setup logging\n\tfilter := &logutils.LevelFilter{\n\t\tLevels:   []logutils.LogLevel{\"DEBUG\", \"INFO\", \"WARN\", \"ERROR\", \"PANIC\"},\n\t\tMinLevel: logutils.LogLevel(strings.ToUpper(viper.GetString(\"log_level\"))),\n\t\tWriter:   os.Stderr,\n\t}\n\tlog.SetOutput(filter)\n\truntime.GOMAXPROCS(viper.GetInt(\"gomaxprocs\"))\n}\n\nfunc main() {\n\tlog.Print(\"[DEBUG] Starting Server, config options: docker_endpoint:\",\n\t\tviper.GetString(\"docker_endpoint\"),\n\t\t\" server_host=\",\n\t\tviper.GetString(\"server_host\"),\n\t\t\" log_level=\",\n\t\tviper.GetString(\"log_level\"))\n\t\/\/ setup renderer\n\trend := render.New()\n\t\/\/ setup a docker client\n\tdockerClient, err := models.NewDockerClient(viper.GetString(\"docker_endpoint\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"[PANIC] Docker enpoint not accessable, bailing\")\n\t}\n\t\/\/ define routes\n\tr := pat.New()\n\t\/\/ setup a websocketUpgrader\n\twebSocketUpgrader := content.NewWebSocketUpgrader(1024, 1024)\n\t\/\/ setup our spew controller\n\tspewController := controllers.NewSpewController(rend, dockerClient, webSocketUpgrader)\n\tr.Get(\"\/spew\", spewController.SpewHandler)\n\tr.Get(\"\/spew\/\", spewController.SpewHandler)\n\t\/\/ startup classic negroni\n\tn := negroni.Classic()\n\tn.Use(middlewares.NewContentNegotiate(rend))\n\t\/\/ attach router to negroni\n\tn.UseHandler(r)\n\t\/\/ run negroni\n\trunServer(n)\n}\n\n\/\/runServer - run the server, broken out for unit tests\nvar runServer = func(n *negroni.Negroni) {\n\tlog.Print(\"[DEBUG] Server starting to accept requests\")\n\tn.Run(viper.GetString(\"server_host\"))\n}\n<commit_msg> more tests<commit_after>\/\/ Package main - Server entrypoint for signature service\npackage main\n\nimport (\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/gorilla\/pat\"\n\t\"github.com\/hashicorp\/logutils\"\n\t\"github.com\/husobee\/dockerspew\/content\"\n\t\"github.com\/husobee\/dockerspew\/controllers\"\n\t\"github.com\/husobee\/dockerspew\/middlewares\"\n\t\"github.com\/husobee\/dockerspew\/models\"\n\t\"github.com\/spf13\/viper\"\n\t\"gopkg.in\/unrolled\/render.v1\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nfunc init() {\n\t\/\/ set some defaults\n\tviper.SetDefault(\"server_host\", \":8080\")\n\tviper.SetDefault(\"log_level\", \"WARN\")\n\tviper.SetDefault(\"gomaxprocs\", runtime.NumCPU())\n\tviper.SetDefault(\"docker_endpoint\", \"unix:\/\/\/var\/run\/docker.sock\")\n\t\/\/ get vars from viper env binding\n\tviper.SetEnvPrefix(\"dockerspew\") \/\/ will be uppercased automatically\n\tviper.BindEnv(\"server_host\")\n\tviper.BindEnv(\"log_level\")\n\tviper.BindEnv(\"docker_endpoint\")\n\t\/\/ setup logging\n\tfilter := &logutils.LevelFilter{\n\t\tLevels:   []logutils.LogLevel{\"DEBUG\", \"INFO\", \"WARN\", \"ERROR\", \"PANIC\"},\n\t\tMinLevel: logutils.LogLevel(strings.ToUpper(viper.GetString(\"log_level\"))),\n\t\tWriter:   os.Stderr,\n\t}\n\tlog.SetOutput(filter)\n\truntime.GOMAXPROCS(viper.GetInt(\"gomaxprocs\"))\n}\n\nvar modelsNewDockerClient = models.NewDockerClient\n\nfunc main() {\n\tlog.Print(\"[DEBUG] Starting Server, config options: docker_endpoint:\",\n\t\tviper.GetString(\"docker_endpoint\"),\n\t\t\" server_host=\",\n\t\tviper.GetString(\"server_host\"),\n\t\t\" log_level=\",\n\t\tviper.GetString(\"log_level\"))\n\t\/\/ setup renderer\n\trend := render.New()\n\t\/\/ setup a docker client\n\tdockerClient, err := modelsNewDockerClient(viper.GetString(\"docker_endpoint\"))\n\tif err != nil {\n\t\tlog.Panic(\"[PANIC] Docker enpoint not accessable, bailing\")\n\t}\n\t\/\/ define routes\n\tr := pat.New()\n\t\/\/ setup a websocketUpgrader\n\twebSocketUpgrader := content.NewWebSocketUpgrader(1024, 1024)\n\t\/\/ setup our spew controller\n\tspewController := controllers.NewSpewController(rend, dockerClient, webSocketUpgrader)\n\tr.Get(\"\/spew\", spewController.SpewHandler)\n\tr.Get(\"\/spew\/\", spewController.SpewHandler)\n\t\/\/ startup classic negroni\n\tn := negroni.Classic()\n\tn.Use(middlewares.NewContentNegotiate(rend))\n\t\/\/ attach router to negroni\n\tn.UseHandler(r)\n\t\/\/ run negroni\n\trunServer(n)\n}\n\n\/\/runServer - run the server, broken out for unit tests\nvar runServer = func(n *negroni.Negroni) {\n\tlog.Print(\"[DEBUG] Server starting to accept requests\")\n\tn.Run(viper.GetString(\"server_host\"))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n)\n\nfunc main() {\n\turls := getUrls()\n\tfor _, url := range urls {\n\t\tfmt.Println(url)\n\t}\n\tfmt.Println(\"Total\", len(urls))\n}\n\nfunc getUrls() []string {\n\turls := []string{}\n\tr := regexp.MustCompile(`<a class=\"audibleTile__artworkLink\" href=\"(.*)\">`)\n\n\t\/\/ Read lines from stdin\n\ts := bufio.NewScanner(os.Stdin)\n\tfor s.Scan() {\n\t\tline := s.Text()\n\t\tmatch := r.FindStringSubmatch(line)\n\t\tif len(match) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\turls = append(urls, \"https:\/\/soundcloud.com\"+match[1])\n\t}\n\treturn urls\n}\n<commit_msg>Get waveform urls<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"regexp\"\n)\n\n\/\/ Usage: cat ~\/Desktop\/sclikes_html.txt | go run main.go\nfunc main() {\n\turls := getBrowserUrls()\n\tfor _, url := range urls {\n\t\twurl := getWaveFormUrl(url)\n\t\tfmt.Println(wurl)\n\t}\n\tfmt.Println(\"Total\", len(urls))\n}\n\nfunc getWaveFormUrl(browserUrl string) string {\n\t\/\/ input\n\t\/\/ browserUrl := \"https:\/\/soundcloud.com\/lana-del-rey\/ultraviolence-disciples-remix-1\"\n\tresp, err := http.Get(browserUrl)\n\tif err != nil {\n\t\tfmt.Println(\"Error getting\", browserUrl)\n\t}\n\n\trespBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tfmt.Println(\"Error reading\", browserUrl)\n\t}\n\trespString := string(respBytes)\n\n\tr := regexp.MustCompile(`\"waveform_url\":\"(http.*\\.json)\"`)\n\n\tmatch := r.FindStringSubmatch(respString)\n\twaveformUrl := match[1]\n\n\t\/\/ output\n\t\/\/ waveformUrl := \"https:\/\/wis.sndcdn.com\/iCvi12jhGTIQ_m.json\"\n\treturn waveformUrl\n}\n\nfunc getBrowserUrls() []string {\n\turls := []string{}\n\tr := regexp.MustCompile(`<a class=\"audibleTile__artworkLink\" href=\"(.*)\">`)\n\n\t\/\/ Read lines from stdin\n\ts := bufio.NewScanner(os.Stdin)\n\tfor s.Scan() {\n\t\tline := s.Text()\n\t\tmatch := r.FindStringSubmatch(line)\n\t\tif len(match) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\turls = append(urls, \"https:\/\/soundcloud.com\"+match[1])\n\t}\n\treturn urls\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"runtime\"\n\n\t\"github.com\/WeCanHearYou\/wechy\/app\/models\"\n\t\"github.com\/WeCanHearYou\/wechy\/app\/pkg\/dbx\"\n\t\"github.com\/WeCanHearYou\/wechy\/app\/pkg\/env\"\n\t\"github.com\/WeCanHearYou\/wechy\/app\/pkg\/oauth\"\n\t\"github.com\/WeCanHearYou\/wechy\/app\/storage\/postgres\"\n\t_ \"github.com\/lib\/pq\"\n\tmig \"github.com\/mattes\/migrate\"\n\t_ \"github.com\/mattes\/migrate\/database\/postgres\"\n\t_ \"github.com\/mattes\/migrate\/source\/file\"\n\n\t\"fmt\"\n)\n\nvar buildtime string\nvar version = \"0.2.0\"\n\nfunc migrate() {\n\tfmt.Printf(\"Running migrations... \\n\")\n\tm, err := mig.New(\n\t\t\"file:\/\/.\/\"+env.Path(\"\/migrations\"),\n\t\tenv.MustGet(\"DATABASE_URL\"),\n\t)\n\n\tif err == nil {\n\t\terr = m.Up()\n\t}\n\n\tif err != nil && err != mig.ErrNoChange {\n\t\tfmt.Printf(\"Error: %s.\\n\", err)\n\n\t\tpanic(\"Migrations failed.\")\n\t} else {\n\t\tfmt.Printf(\"Migrations finished with success.\\n\")\n\t}\n}\n\nfunc init() {\n\tfmt.Printf(\"Application is starting...\\n\")\n\tfmt.Printf(\"GO_ENV: %s\\n\", env.Current())\n\tmigrate()\n}\n\nfunc main() {\n\tdb, err := dbx.New()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tctx := &AppServices{\n\t\tOAuth:  &oauth.HTTPService{},\n\t\tIdea:   &postgres.IdeaStorage{DB: db},\n\t\tUser:   &postgres.UserStorage{DB: db},\n\t\tTenant: &postgres.TenantStorage{DB: db},\n\t\tSettings: &models.AppSettings{\n\t\t\tBuildTime:   buildtime,\n\t\t\tVersion:     version,\n\t\t\tCompiler:    runtime.Version(),\n\t\t\tEnvironment: env.Current(),\n\t\t},\n\t}\n\n\te := GetMainEngine(ctx)\n\te.Start(\":\" + env.GetEnvOrDefault(\"PORT\", \"3000\"))\n}\n<commit_msg>fix path<commit_after>package main\n\nimport (\n\t\"runtime\"\n\n\t\"github.com\/WeCanHearYou\/wechy\/app\/models\"\n\t\"github.com\/WeCanHearYou\/wechy\/app\/pkg\/dbx\"\n\t\"github.com\/WeCanHearYou\/wechy\/app\/pkg\/env\"\n\t\"github.com\/WeCanHearYou\/wechy\/app\/pkg\/oauth\"\n\t\"github.com\/WeCanHearYou\/wechy\/app\/storage\/postgres\"\n\t_ \"github.com\/lib\/pq\"\n\tmig \"github.com\/mattes\/migrate\"\n\t_ \"github.com\/mattes\/migrate\/database\/postgres\"\n\t_ \"github.com\/mattes\/migrate\/source\/file\"\n\n\t\"fmt\"\n)\n\nvar buildtime string\nvar version = \"0.2.0\"\n\nfunc migrate() {\n\tfmt.Printf(\"Running migrations... \\n\")\n\tm, err := mig.New(\n\t\t\"file:\/\/.\/migrations\",\n\t\tenv.MustGet(\"DATABASE_URL\"),\n\t)\n\n\tif err == nil {\n\t\terr = m.Up()\n\t}\n\n\tif err != nil && err != mig.ErrNoChange {\n\t\tfmt.Printf(\"Error: %s.\\n\", err)\n\n\t\tpanic(\"Migrations failed.\")\n\t} else {\n\t\tfmt.Printf(\"Migrations finished with success.\\n\")\n\t}\n}\n\nfunc init() {\n\tfmt.Printf(\"Application is starting...\\n\")\n\tfmt.Printf(\"GO_ENV: %s\\n\", env.Current())\n\tmigrate()\n}\n\nfunc main() {\n\tdb, err := dbx.New()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tctx := &AppServices{\n\t\tOAuth:  &oauth.HTTPService{},\n\t\tIdea:   &postgres.IdeaStorage{DB: db},\n\t\tUser:   &postgres.UserStorage{DB: db},\n\t\tTenant: &postgres.TenantStorage{DB: db},\n\t\tSettings: &models.AppSettings{\n\t\t\tBuildTime:   buildtime,\n\t\t\tVersion:     version,\n\t\t\tCompiler:    runtime.Version(),\n\t\t\tEnvironment: env.Current(),\n\t\t},\n\t}\n\n\te := GetMainEngine(ctx)\n\te.Start(\":\" + env.GetEnvOrDefault(\"PORT\", \"3000\"))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"image\"\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com\/crgimenes\/metal\/cmd\"\n\t\"github.com\/crgimenes\/metal\/fonts\"\n\t\"github.com\/hajimehoshi\/ebiten\"\n)\n\nconst (\n\tscreenWidth  = 320 \/\/ 40 columns\n\tscreenHeight = 240 \/\/ 30 rows\n\n\trows     = 30\n\tcolumns  = 40\n\trgbaSize = 4\n)\n\nvar (\n\tvideoTextMemory [rows * columns * 2]byte\n\tcursor          int\n\timg             *image.RGBA\n\tsquare          *ebiten.Image\n\tfont            fonts.Expert118x8\n\tcurrentColor    byte = 0x0f\n)\n\nvar CGAColors = []struct {\n\tR byte\n\tG byte\n\tB byte\n}{\n\t{0, 0, 0},\n\t{0, 0, 170},\n\t{0, 170, 0},\n\t{0, 170, 170},\n\t{170, 0, 0},\n\t{170, 0, 170},\n\t{170, 85, 0},\n\t{170, 170, 170},\n\t{85, 85, 85},\n\t{85, 85, 255},\n\t{85, 255, 85},\n\t{85, 255, 255},\n\t{255, 85, 85},\n\t{255, 85, 255},\n\t{255, 255, 85},\n\t{255, 255, 255},\n}\n\nfunc mergeColorCode(b, f byte) byte {\n\treturn (f & 0xff) | (b << 4)\n}\n\nfunc drawPix(x, y int, color byte) {\n\tpos := 4*y*screenWidth + 4*x\n\timg.Pix[pos] = CGAColors[color].R\n\timg.Pix[pos+1] = CGAColors[color].G\n\timg.Pix[pos+2] = CGAColors[color].B\n\timg.Pix[pos+3] = 0xff\n}\n\nfunc getBit(n int, pos uint64) bool {\n\t\/\/ from right to left\n\tval := n & (1 << pos)\n\treturn (val > 0)\n}\n\nfunc drawChar(index, fgColor, bgColor byte, x, y int) {\n\tvar a, b uint64\n\tfor a = 0; a < 8; a++ {\n\t\tfor b = 0; b < 8; b++ {\n\t\t\tif font.Bitmap[index][b]&(0x80>>a) != 0 {\n\t\t\t\tdrawPix(int(a)+x, int(b)+y, fgColor)\n\t\t\t} else {\n\t\t\t\tdrawPix(int(a)+x, int(b)+y, bgColor)\n\t\t\t}\n\t\t}\n\t}\n}\n\nvar cursorBlinkTimer int\nvar cursorSetBlink bool = true\n\nfunc drawCursor(index, fgColor, bgColor byte, x, y int) {\n\tif cursorSetBlink {\n\t\tif cursorBlinkTimer < 15 {\n\t\t\tdrawChar(index, fgColor, bgColor, x, y)\n\t\t} else {\n\t\t\tdrawChar(index, bgColor, fgColor, x, y)\n\t\t}\n\t\tcursorBlinkTimer++\n\t\tif cursorBlinkTimer > 30 {\n\t\t\tcursorBlinkTimer = 0\n\t\t}\n\t} else {\n\t\tdrawChar(index, bgColor, fgColor, x, y)\n\t}\n}\n\nfunc drawVideoTextMode() {\n\ti := 0\n\tfor r := 0; r < rows; r++ {\n\t\tfor c := 0; c < columns; c++ {\n\t\t\tcolor := videoTextMemory[i]\n\t\t\tf := color & 0x0f\n\t\t\tb := color & 0xf0 >> 4\n\t\t\ti++\n\t\t\tif i-1 == cursor {\n\t\t\t\tdrawCursor(videoTextMemory[i], f, b, c*8, r*8)\n\t\t\t} else {\n\t\t\t\tdrawChar(videoTextMemory[i], f, b, c*8, r*8)\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t}\n}\n\nfunc clearVideoTextMode() {\n\tcopy(videoTextMemory[:], make([]byte, len(videoTextMemory)))\n\tfor i := 0; i < len(videoTextMemory); i += 2 {\n\t\tvideoTextMemory[i] = currentColor\n\t}\n}\n\nfunc moveLineUp() {\n\tcopy(videoTextMemory[0:], videoTextMemory[columns*2:])\n\tcopy(videoTextMemory[len(videoTextMemory)-columns*2:], make([]byte, columns*2))\n\tfor i := len(videoTextMemory) - columns*2; i < len(videoTextMemory); i += 2 {\n\t\tvideoTextMemory[i] = currentColor\n\t}\n\n}\n\nfunc correctVideoCursor() {\n\tif cursor < 0 {\n\t\tcursor = 0\n\t}\n\tfor cursor >= rows*columns*2 {\n\t\tcursor -= columns * 2\n\t\tmoveLineUp()\n\t}\n}\n\nfunc putChar(c byte) {\n\tcorrectVideoCursor()\n\tvideoTextMemory[cursor] = currentColor\n\tcursor++\n\tcorrectVideoCursor()\n\tvideoTextMemory[cursor] = c\n\tcursor++\n\tcorrectVideoCursor()\n}\n\nfunc bPrint(msg string) {\n\tfor i := 0; i < len(msg); i++ {\n\t\tc := msg[i]\n\n\t\tswitch c {\n\t\tcase 13:\n\t\t\tcursor += columns * 2\n\t\t\tcontinue\n\t\tcase 10:\n\t\t\taux := cursor \/ (columns * 2)\n\t\t\taux = aux * (columns * 2)\n\t\t\tcursor = aux\n\t\t\tcontinue\n\t\t}\n\t\tputChar(msg[i])\n\t}\n}\n\nfunc bPrintln(msg string) {\n\tmsg += \"\\r\\n\"\n\tbPrint(msg)\n}\n\nvar lastKey = struct {\n\tTime uint64\n\tChar byte\n}{\n\t0,\n\t0,\n}\n\nvar uTime uint64\nvar c byte\n\nvar machine int\n\n\/\/var countaux int\nvar noKey bool\n\nfunc keyTreatment(c byte, f func(c byte)) {\n\tif noKey || lastKey.Char != c || lastKey.Time+20 < uTime {\n\t\tf(c)\n\t\tnoKey = false\n\t\tlastKey.Char = c\n\t\tlastKey.Time = uTime\n\t}\n}\n\nfunc getLine() string {\n\taux := cursor \/ (columns * 2)\n\tvar ret string\n\tfor i := aux*(columns*2) + 1; i < aux*(columns*2)+columns*2; i += 2 {\n\t\tc := videoTextMemory[i]\n\t\tif c == 0 {\n\t\t\tbreak\n\t\t}\n\t\tret += string(videoTextMemory[i])\n\t}\n\n\tret = strings.TrimSpace(ret)\n\treturn ret\n}\n\nfunc keyboard() {\n\tfor c := 'A'; c <= 'Z'; c++ {\n\t\tif ebiten.IsKeyPressed(ebiten.Key(c) - 'A' + ebiten.KeyA) {\n\t\t\tkeyTreatment(byte(c), func(c byte) {\n\t\t\t\tputChar(c)\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t}\n\n\tif ebiten.IsKeyPressed(ebiten.KeySpace) {\n\t\tkeyTreatment(byte(' '), func(c byte) {\n\t\t\tputChar(c)\n\t\t})\n\t\treturn\n\t}\n\n\tif ebiten.IsKeyPressed(ebiten.KeyEnter) {\n\t\tkeyTreatment(0, func(c byte) {\n\t\t\tcmd.Eval(getLine())\n\t\t\tcursor += columns * 2\n\t\t\taux := cursor \/ (columns * 2)\n\t\t\taux = aux * (columns * 2)\n\t\t\tcursor = aux\n\t\t\tcorrectVideoCursor()\n\t\t})\n\t\treturn\n\t}\n\n\tif ebiten.IsKeyPressed(ebiten.KeyBackspace) {\n\t\tkeyTreatment(0, func(c byte) {\n\t\t\tcursor -= 2\n\t\t\tcorrectVideoCursor()\n\t\t})\n\t\treturn\n\t}\n\n\tif ebiten.IsKeyPressed(ebiten.KeyUp) {\n\t\tkeyTreatment(0, func(c byte) {\n\t\t\tcursor -= columns * 2\n\t\t\tcorrectVideoCursor()\n\t\t})\n\t\treturn\n\t} else if ebiten.IsKeyPressed(ebiten.KeyDown) {\n\t\tkeyTreatment(0, func(c byte) {\n\t\t\tcursor += columns * 2\n\t\t\tcorrectVideoCursor()\n\t\t})\n\t\treturn\n\t} else if ebiten.IsKeyPressed(ebiten.KeyLeft) {\n\t\tkeyTreatment(0, func(c byte) {\n\t\t\tcursor -= 2\n\t\t\tcorrectVideoCursor()\n\t\t})\n\t\treturn\n\t} else if ebiten.IsKeyPressed(ebiten.KeyRight) {\n\t\tkeyTreatment(0, func(c byte) {\n\t\t\tcursor += 2\n\t\t\tcorrectVideoCursor()\n\t\t})\n\t\treturn\n\t}\n\n\t\/\/ When the \"left mouse button\" is pressed...\n\tif ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) {\n\t\t\/\/ebitenutil.DebugPrint(screen, \"You're pressing the 'LEFT' mouse button.\")\n\t}\n\t\/\/ When the \"right mouse button\" is pressed...\n\tif ebiten.IsMouseButtonPressed(ebiten.MouseButtonRight) {\n\t\t\/\/ebitenutil.DebugPrint(screen, \"\\nYou're pressing the 'RIGHT' mouse button.\")\n\t}\n\t\/\/ When the \"middle mouse button\" is pressed...\n\tif ebiten.IsMouseButtonPressed(ebiten.MouseButtonMiddle) {\n\t\t\/\/ebitenutil.DebugPrint(screen, \"\\n\\nYou're pressing the 'MIDDLE' mouse button.\")\n\t}\n\n\t\/\/x, y := ebiten.CursorPosition()\n\t\/\/fmt.Printf(\"X: %d, Y: %d\\n\", x, y)\n\n\t\/\/ Display the information with \"X: xx, Y: xx\" format\n\t\/\/ebitenutil.DebugPrint(screen, fmt.Sprintf(\"X: %d, Y: %d\", x, y))\n\n\tnoKey = true\n\n}\n\nfunc update(screen *ebiten.Image) error {\n\n\tuTime++\n\t\/\/putChar(2)\n\t\/\/cursor -= 2\n\n\tif machine == 0 {\n\t\tbPrintln(\"METAL BASIC 0.01\")\n\t\tbPrintln(\"http:\/\/crg.eti.br\")\n\t\tmachine++\n\t}\n\n\t\/*\n\t\tif countaux > 10 {\n\t\t\tcountaux = 0\n\t\t\tputChar(dt)\n\t\t\tdt++\n\t\t\tcurrentColor = mergeColorCode(0x0, c)\n\t\t\tc++\n\t\t\tif c > 15 {\n\t\t\t\tc = 0\n\t\t\t}\n\t\t}\n\t\tcountaux++\n\t*\/\n\tdrawVideoTextMode()\n\tscreen.ReplacePixels(img.Pix)\n\tkeyboard()\n\treturn nil\n}\n\nfunc main() {\n\n\tfont.Load()\n\tclearVideoTextMode()\n\n\timg = image.NewRGBA(image.Rect(0, 0, screenWidth, screenHeight))\n\tif err := ebiten.Run(update, screenWidth, screenHeight, 2, \"METAL BASIC 0.01\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}\n<commit_msg>add Comma and numbers<commit_after>package main\n\nimport (\n\t\"image\"\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com\/crgimenes\/metal\/cmd\"\n\t\"github.com\/crgimenes\/metal\/fonts\"\n\t\"github.com\/hajimehoshi\/ebiten\"\n)\n\nconst (\n\tscreenWidth  = 320 \/\/ 40 columns\n\tscreenHeight = 240 \/\/ 30 rows\n\n\trows     = 30\n\tcolumns  = 40\n\trgbaSize = 4\n)\n\nvar (\n\tvideoTextMemory [rows * columns * 2]byte\n\tcursor          int\n\timg             *image.RGBA\n\tsquare          *ebiten.Image\n\tfont            fonts.Expert118x8\n\tcurrentColor    byte = 0x0f\n)\n\nvar CGAColors = []struct {\n\tR byte\n\tG byte\n\tB byte\n}{\n\t{0, 0, 0},\n\t{0, 0, 170},\n\t{0, 170, 0},\n\t{0, 170, 170},\n\t{170, 0, 0},\n\t{170, 0, 170},\n\t{170, 85, 0},\n\t{170, 170, 170},\n\t{85, 85, 85},\n\t{85, 85, 255},\n\t{85, 255, 85},\n\t{85, 255, 255},\n\t{255, 85, 85},\n\t{255, 85, 255},\n\t{255, 255, 85},\n\t{255, 255, 255},\n}\n\nfunc mergeColorCode(b, f byte) byte {\n\treturn (f & 0xff) | (b << 4)\n}\n\nfunc drawPix(x, y int, color byte) {\n\tpos := 4*y*screenWidth + 4*x\n\timg.Pix[pos] = CGAColors[color].R\n\timg.Pix[pos+1] = CGAColors[color].G\n\timg.Pix[pos+2] = CGAColors[color].B\n\timg.Pix[pos+3] = 0xff\n}\n\nfunc getBit(n int, pos uint64) bool {\n\t\/\/ from right to left\n\tval := n & (1 << pos)\n\treturn (val > 0)\n}\n\nfunc drawChar(index, fgColor, bgColor byte, x, y int) {\n\tvar a, b uint64\n\tfor a = 0; a < 8; a++ {\n\t\tfor b = 0; b < 8; b++ {\n\t\t\tif font.Bitmap[index][b]&(0x80>>a) != 0 {\n\t\t\t\tdrawPix(int(a)+x, int(b)+y, fgColor)\n\t\t\t} else {\n\t\t\t\tdrawPix(int(a)+x, int(b)+y, bgColor)\n\t\t\t}\n\t\t}\n\t}\n}\n\nvar cursorBlinkTimer int\nvar cursorSetBlink bool = true\n\nfunc drawCursor(index, fgColor, bgColor byte, x, y int) {\n\tif cursorSetBlink {\n\t\tif cursorBlinkTimer < 15 {\n\t\t\tdrawChar(index, fgColor, bgColor, x, y)\n\t\t} else {\n\t\t\tdrawChar(index, bgColor, fgColor, x, y)\n\t\t}\n\t\tcursorBlinkTimer++\n\t\tif cursorBlinkTimer > 30 {\n\t\t\tcursorBlinkTimer = 0\n\t\t}\n\t} else {\n\t\tdrawChar(index, bgColor, fgColor, x, y)\n\t}\n}\n\nfunc drawVideoTextMode() {\n\ti := 0\n\tfor r := 0; r < rows; r++ {\n\t\tfor c := 0; c < columns; c++ {\n\t\t\tcolor := videoTextMemory[i]\n\t\t\tf := color & 0x0f\n\t\t\tb := color & 0xf0 >> 4\n\t\t\ti++\n\t\t\tif i-1 == cursor {\n\t\t\t\tdrawCursor(videoTextMemory[i], f, b, c*8, r*8)\n\t\t\t} else {\n\t\t\t\tdrawChar(videoTextMemory[i], f, b, c*8, r*8)\n\t\t\t}\n\t\t\ti++\n\t\t}\n\t}\n}\n\nfunc clearVideoTextMode() {\n\tcopy(videoTextMemory[:], make([]byte, len(videoTextMemory)))\n\tfor i := 0; i < len(videoTextMemory); i += 2 {\n\t\tvideoTextMemory[i] = currentColor\n\t}\n}\n\nfunc moveLineUp() {\n\tcopy(videoTextMemory[0:], videoTextMemory[columns*2:])\n\tcopy(videoTextMemory[len(videoTextMemory)-columns*2:], make([]byte, columns*2))\n\tfor i := len(videoTextMemory) - columns*2; i < len(videoTextMemory); i += 2 {\n\t\tvideoTextMemory[i] = currentColor\n\t}\n\n}\n\nfunc correctVideoCursor() {\n\tif cursor < 0 {\n\t\tcursor = 0\n\t}\n\tfor cursor >= rows*columns*2 {\n\t\tcursor -= columns * 2\n\t\tmoveLineUp()\n\t}\n}\n\nfunc putChar(c byte) {\n\tcorrectVideoCursor()\n\tvideoTextMemory[cursor] = currentColor\n\tcursor++\n\tcorrectVideoCursor()\n\tvideoTextMemory[cursor] = c\n\tcursor++\n\tcorrectVideoCursor()\n}\n\nfunc bPrint(msg string) {\n\tfor i := 0; i < len(msg); i++ {\n\t\tc := msg[i]\n\n\t\tswitch c {\n\t\tcase 13:\n\t\t\tcursor += columns * 2\n\t\t\tcontinue\n\t\tcase 10:\n\t\t\taux := cursor \/ (columns * 2)\n\t\t\taux = aux * (columns * 2)\n\t\t\tcursor = aux\n\t\t\tcontinue\n\t\t}\n\t\tputChar(msg[i])\n\t}\n}\n\nfunc bPrintln(msg string) {\n\tmsg += \"\\r\\n\"\n\tbPrint(msg)\n}\n\nvar lastKey = struct {\n\tTime uint64\n\tChar byte\n}{\n\t0,\n\t0,\n}\n\nvar uTime uint64\nvar c byte\n\nvar machine int\n\n\/\/var countaux int\nvar noKey bool\n\nfunc keyTreatment(c byte, f func(c byte)) {\n\tif noKey || lastKey.Char != c || lastKey.Time+20 < uTime {\n\t\tf(c)\n\t\tnoKey = false\n\t\tlastKey.Char = c\n\t\tlastKey.Time = uTime\n\t}\n}\n\nfunc getLine() string {\n\taux := cursor \/ (columns * 2)\n\tvar ret string\n\tfor i := aux*(columns*2) + 1; i < aux*(columns*2)+columns*2; i += 2 {\n\t\tc := videoTextMemory[i]\n\t\tif c == 0 {\n\t\t\tbreak\n\t\t}\n\t\tret += string(videoTextMemory[i])\n\t}\n\n\tret = strings.TrimSpace(ret)\n\treturn ret\n}\n\nfunc keyboard() {\n\tfor c := 'A'; c <= 'Z'; c++ {\n\t\tif ebiten.IsKeyPressed(ebiten.Key(c) - 'A' + ebiten.KeyA) {\n\t\t\tkeyTreatment(byte(c), func(c byte) {\n\t\t\t\tputChar(c)\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor c := '0'; c <= '9'; c++ {\n\t\tif ebiten.IsKeyPressed(ebiten.Key(c) - '0' + ebiten.Key0) {\n\t\t\tkeyTreatment(byte(c), func(c byte) {\n\t\t\t\tputChar(c)\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t}\n\n\tif ebiten.IsKeyPressed(ebiten.KeySpace) {\n\t\tkeyTreatment(byte(' '), func(c byte) {\n\t\t\tputChar(c)\n\t\t})\n\t\treturn\n\t}\n\n\tif ebiten.IsKeyPressed(ebiten.KeyComma) {\n\t\tkeyTreatment(byte(','), func(c byte) {\n\t\t\tputChar(c)\n\t\t})\n\t\treturn\n\t}\n\n\tif ebiten.IsKeyPressed(ebiten.KeyEnter) {\n\t\tkeyTreatment(0, func(c byte) {\n\t\t\tcmd.Eval(getLine())\n\t\t\tcursor += columns * 2\n\t\t\taux := cursor \/ (columns * 2)\n\t\t\taux = aux * (columns * 2)\n\t\t\tcursor = aux\n\t\t\tcorrectVideoCursor()\n\t\t})\n\t\treturn\n\t}\n\n\tif ebiten.IsKeyPressed(ebiten.KeyBackspace) {\n\t\tkeyTreatment(0, func(c byte) {\n\t\t\tcursor -= 2\n\t\t\tcorrectVideoCursor()\n\t\t})\n\t\treturn\n\t}\n\n\tif ebiten.IsKeyPressed(ebiten.KeyUp) {\n\t\tkeyTreatment(0, func(c byte) {\n\t\t\tcursor -= columns * 2\n\t\t\tcorrectVideoCursor()\n\t\t})\n\t\treturn\n\t} else if ebiten.IsKeyPressed(ebiten.KeyDown) {\n\t\tkeyTreatment(0, func(c byte) {\n\t\t\tcursor += columns * 2\n\t\t\tcorrectVideoCursor()\n\t\t})\n\t\treturn\n\t} else if ebiten.IsKeyPressed(ebiten.KeyLeft) {\n\t\tkeyTreatment(0, func(c byte) {\n\t\t\tcursor -= 2\n\t\t\tcorrectVideoCursor()\n\t\t})\n\t\treturn\n\t} else if ebiten.IsKeyPressed(ebiten.KeyRight) {\n\t\tkeyTreatment(0, func(c byte) {\n\t\t\tcursor += 2\n\t\t\tcorrectVideoCursor()\n\t\t})\n\t\treturn\n\t}\n\n\t\/\/ When the \"left mouse button\" is pressed...\n\tif ebiten.IsMouseButtonPressed(ebiten.MouseButtonLeft) {\n\t\t\/\/ebitenutil.DebugPrint(screen, \"You're pressing the 'LEFT' mouse button.\")\n\t}\n\t\/\/ When the \"right mouse button\" is pressed...\n\tif ebiten.IsMouseButtonPressed(ebiten.MouseButtonRight) {\n\t\t\/\/ebitenutil.DebugPrint(screen, \"\\nYou're pressing the 'RIGHT' mouse button.\")\n\t}\n\t\/\/ When the \"middle mouse button\" is pressed...\n\tif ebiten.IsMouseButtonPressed(ebiten.MouseButtonMiddle) {\n\t\t\/\/ebitenutil.DebugPrint(screen, \"\\n\\nYou're pressing the 'MIDDLE' mouse button.\")\n\t}\n\n\t\/\/x, y := ebiten.CursorPosition()\n\t\/\/fmt.Printf(\"X: %d, Y: %d\\n\", x, y)\n\n\t\/\/ Display the information with \"X: xx, Y: xx\" format\n\t\/\/ebitenutil.DebugPrint(screen, fmt.Sprintf(\"X: %d, Y: %d\", x, y))\n\n\tnoKey = true\n\n}\n\nfunc update(screen *ebiten.Image) error {\n\n\tuTime++\n\t\/\/putChar(2)\n\t\/\/cursor -= 2\n\n\tif machine == 0 {\n\t\tbPrintln(\"METAL BASIC 0.01\")\n\t\tbPrintln(\"http:\/\/crg.eti.br\")\n\t\tmachine++\n\t}\n\n\t\/*\n\t\tif countaux > 10 {\n\t\t\tcountaux = 0\n\t\t\tputChar(dt)\n\t\t\tdt++\n\t\t\tcurrentColor = mergeColorCode(0x0, c)\n\t\t\tc++\n\t\t\tif c > 15 {\n\t\t\t\tc = 0\n\t\t\t}\n\t\t}\n\t\tcountaux++\n\t*\/\n\tdrawVideoTextMode()\n\tscreen.ReplacePixels(img.Pix)\n\tkeyboard()\n\treturn nil\n}\n\nfunc main() {\n\n\tfont.Load()\n\tclearVideoTextMode()\n\n\timg = image.NewRGBA(image.Rect(0, 0, screenWidth, screenHeight))\n\tif err := ebiten.Run(update, screenWidth, screenHeight, 2, \"METAL BASIC 0.01\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/oschwald\/geoip2-golang\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ The GeoIP database containing data on what IP match to what city\/country blah\n\/\/ blah.\nvar db *geoip2.Reader\n\nfunc main() {\n\t\/\/ Initialize the database.\n\tvar err error\n\tdb, err = geoip2.Open(\"GeoLite2-City.mmdb\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Get the HTTP server rollin'\n\thttp.HandleFunc(\"\/\", HTTPRequestHandler)\n\tlog.Println(\"Server listening!\")\n\thttp.ListenAndServe(\":61430\", nil)\n}\n\n\/\/ Standard request handler if there's no static file to be served.\nfunc HTTPRequestHandler(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Get the current time, so that we can then calculate the execution time.\n\tstart := time.Now()\n\n\tvar requestIP string\n\t\/\/ The request is most likely being done through a reverse proxy.\n\tif realIP, ok := r.Header[\"X-Real-Ip\"]; ok && len(r.Header[\"X-Real-Ip\"]) > 0 {\n\t\trequestIP = realIP[0]\n\t} else {\n\t\t\/\/ Get the real actual request IP without the trolls\n\t\trequestIP = UnfuckRequestIP(r.RemoteAddr)\n\t}\n\n\t\/\/ There's a very good reason for which we aren't using regexes.\n\t\/\/ http:\/\/ideone.com\/jNEMob\n\t\/\/ (tl;dr: regex is holy shit fucking slow)\n\tisConnectingFromBrowser := strings.Index(r.UserAgent(), \"mozilla\") != -1 ||\n\t\tstrings.Index(r.UserAgent(), \"webkit\") != -1 ||\n\t\tstrings.Index(r.UserAgent(), \"opera\") != -1\n\n\t\/\/ Log how much time it took to respond to the request, when we're done.\n\tdefer log.Printf(\n\t\t\"[rq] %s %s %s %dns\",\n\t\trequestIP,\n\t\tr.Method,\n\t\tr.URL.Path,\n\t\ttime.Since(start).Nanoseconds())\n\n\t\/\/ Index, redirect to github.com page.\n\tif r.URL.Path == \"\/\" && isConnectingFromBrowser {\n\t\thttp.Redirect(w, r, \"https:\/\/github.com\/TheHowl\/ip.zxq.co\/blob\/master\/README.md\", 301)\n\t\treturn\n\t}\n\n\t\/\/ Separate two strings when there is a \/ in the URL requested.\n\trequestedThings := strings.Split(r.URL.Path, \"\/\")\n\n\tvar IPAddress string\n\tvar Which string\n\t\/\/ How in the world the user would manage to even send a request to\n\t\/\/ something without even having Path = \"\/\"?\n\t\/\/ I... have no idea. But I'm paranoid. So let's just do it anyway.\n\tif len(requestedThings) < 2 {\n\t\tIPAddress = \"\"\n\t} else {\n\t\tIPAddress = requestedThings[1]\n\t}\n\t\/\/ In case the user didn't write a specific index, let's specify it for\n\t\/\/ them.\n\tif len(requestedThings) < 3 {\n\t\tWhich = \"\"\n\t} else {\n\t\tWhich = requestedThings[2]\n\t}\n\n\t\/\/ Set the requested IP to the user's request request IP, if we got no address.\n\tif IPAddress == \"\" || IPAddress == \"self\" {\n\t\tIPAddress = requestIP\n\t}\n\n\t\/\/ Query parameters array making\n\tqueryParamsRaw, _ := url.ParseQuery(r.URL.RawQuery)\n\tqueryParams := SimplifyQueryMap(queryParamsRaw)\n\tqueryParams = AppendDefaultIfNotSet(queryParams, \"callback\", \"#none#\")\n\tqueryParams = AppendDefaultIfNotSet(queryParams, \"pretty\", \"0\")\n\n\t\/\/ Get the geodata of the requested IP.\n\to, contentType := IPToResponse(IPAddress, Which, queryParams)\n\n\t\/\/ Set the content type as the one given by IPToResponse.\n\tw.Header().Set(\"Content-Type\", contentType+\"; charset=utf-8\")\n\t\/\/ Write the data out to the response.\n\tfmt.Fprint(w, o)\n}\n\n\/\/ Appends a default value to a map only if the key, defined as k, doesn't\n\/\/ already exist in the array.\nfunc AppendDefaultIfNotSet(sl map[string]string, k string, dv string) map[string]string {\n\tif _, ok := sl[k]; !ok {\n\t\tsl[k] = dv\n\t}\n\treturn sl\n}\n\n\/\/ url.ParseQuery returns a map containing as a value a slice with often just\n\/\/ one value. We're fixing that.\nfunc SimplifyQueryMap(sl url.Values) map[string]string {\n\tvar ret map[string]string = map[string]string{}\n\tfor k, v := range sl {\n\t\t\/\/ We're getting only the last element, because we take as granted that\n\t\t\/\/ what the use actually means is the last element, if he has provided\n\t\t\/\/ multiple values for the same key.\n\t\tif len(v) > 0 {\n\t\t\tret[k] = v[len(v)-1]\n\t\t}\n\t}\n\treturn ret\n}\n\n\/\/ Remove from the IP eventual [ or ], and remove the port part of the IP.\nfunc UnfuckRequestIP(ip string) string {\n\tip = strings.Replace(ip, \"[\", \"\", 1)\n\tip = strings.Replace(ip, \"]\", \"\", 1)\n\tss := strings.Split(ip, \":\")\n\tip = strings.Join(ss[:len(ss)-1], \":\")\n\treturn ip\n}\n\n\/\/ Turn the IP into a JSON string containing geodata.\n\/\/\n\/\/ * i: the raw IP string.\n\/\/ * specific: the specific value to get from the geodata array. Default is \"\"\n\/\/ * params: Set callback in the map to a non-\"#none#\" value to use it as a\n\/\/   JSONP callback. Set \"pretty\" to 1 if you want a 2-space indented JSON\n\/\/   output.\nfunc IPToResponse(i string, specific string, params map[string]string) (string, string) {\n\tip := net.ParseIP(i)\n\tif ip == nil {\n\t\treturn \"Please provide a valid IP address\", \"text\/html\"\n\t}\n\n\t\/\/ Query the maxmind database for that IP address.\n\trecord, err := db.City(ip)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ String containing the region\/subdivision of the IP. (E.g.: Scotland, or\n\t\/\/ California).\n\tvar sd string\n\t\/\/ If there are subdivisions for this IP, set sd as the first element in the\n\t\/\/ array's name.\n\tif record.Subdivisions != nil {\n\t\tsd = record.Subdivisions[0].Names[\"en\"]\n\t}\n\n\t\/\/ Create a new instance of all the data to be returned to the user.\n\tdata := map[string]string{}\n\t\/\/ Fill up the data array with the geoip data.\n\tdata[\"ip\"] = ip.String()\n\tdata[\"country\"] = record.Country.IsoCode\n\tdata[\"country_full\"] = record.Country.Names[\"en\"]\n\tdata[\"city\"] = record.City.Names[\"en\"]\n\tdata[\"region\"] = sd\n\tdata[\"continent\"] = record.Continent.Code\n\tdata[\"continent_full\"] = record.Continent.Names[\"en\"]\n\tdata[\"postal\"] = record.Postal.Code\n\t\/\/ precision of latitude\/longitude is up to 4 decimal places (even on\n\t\/\/ ipinfo.io).\n\tdata[\"loc\"] = fmt.Sprintf(\"%.4f,%.4f\", record.Location.Latitude, record.Location.Longitude)\n\n\t\/\/ Since we don't have HTML output, nor other data from geo data,\n\t\/\/ everything is the same if you do \/8.8.8.8, \/8.8.8.8\/json or \/8.8.8.8\/geo.\n\tif specific == \"\" || specific == \"json\" || specific == \"geo\" {\n\t\tvar bytes_output []byte\n\t\tif params[\"pretty\"] == \"1\" {\n\t\t\tbytes_output, _ = json.MarshalIndent(data, \"\", \"  \")\n\t\t} else {\n\t\t\tbytes_output, _ = json.Marshal(data)\n\t\t}\n\t\treturn JSONPify(params[\"callback\"], string(bytes_output[:])),\n\t\t\t\"application\/json\"\n\t} else if val, ok := data[specific]; ok {\n\t\t\/\/ If we got a specific value for what the user requested, return only\n\t\t\/\/ that specific value.\n\t\treturn val, \"text\/html\"\n\t} else {\n\t\t\/\/ We got nothing to show to the user.\n\t\treturn \"undefined\", \"text\/html\"\n\t}\n}\n\n\/\/ Wraps wrapData into a JSONP callback, if the callback name is valid.\nfunc JSONPify(callback string, wrapData string) string {\n\t\/\/ If you have a callback name longer than 2000 characters, I gotta say, you\n\t\/\/ really should learn to minify your javascript code!\n\tif callback != \"#none#\" && callback != \"\" && len(callback) < 2000 {\n\t\t\/\/ In case you're wondering, yes, there is a reason for the empty\n\t\t\/\/ comment! http:\/\/stackoverflow.com\/a\/16048976\/5328069\n\t\twrapData = fmt.Sprintf(\"\/**\/ typeof %s === 'function' \"+\n\t\t\t\"&& %s(%s);\", callback, callback, wrapData)\n\t}\n\treturn wrapData\n}\n<commit_msg>Check that it's a browser only when requesting \/<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/oschwald\/geoip2-golang\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ The GeoIP database containing data on what IP match to what city\/country blah\n\/\/ blah.\nvar db *geoip2.Reader\n\nfunc main() {\n\t\/\/ Initialize the database.\n\tvar err error\n\tdb, err = geoip2.Open(\"GeoLite2-City.mmdb\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Get the HTTP server rollin'\n\thttp.HandleFunc(\"\/\", HTTPRequestHandler)\n\tlog.Println(\"Server listening!\")\n\thttp.ListenAndServe(\":61430\", nil)\n}\n\n\/\/ Standard request handler if there's no static file to be served.\nfunc HTTPRequestHandler(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Get the current time, so that we can then calculate the execution time.\n\tstart := time.Now()\n\n\tvar requestIP string\n\t\/\/ The request is most likely being done through a reverse proxy.\n\tif realIP, ok := r.Header[\"X-Real-Ip\"]; ok && len(r.Header[\"X-Real-Ip\"]) > 0 {\n\t\trequestIP = realIP[0]\n\t} else {\n\t\t\/\/ Get the real actual request IP without the trolls\n\t\trequestIP = UnfuckRequestIP(r.RemoteAddr)\n\t}\n\n\t\/\/ Log how much time it took to respond to the request, when we're done.\n\tdefer log.Printf(\n\t\t\"[rq] %s %s %s %dns\",\n\t\trequestIP,\n\t\tr.Method,\n\t\tr.URL.Path,\n\t\ttime.Since(start).Nanoseconds())\n\n\t\/\/ Index, redirect to github.com page if the request is sent from a browser.\n\t\/\/ There's a very good reason for which we aren't using regexes.\n\t\/\/ http:\/\/ideone.com\/jNEMob\n\t\/\/ (tl;dr: regex is holy shit fucking slow)\n\tif r.URL.Path == \"\/\" && (strings.Index(r.UserAgent(), \"mozilla\") != -1 ||\n\t\tstrings.Index(r.UserAgent(), \"webkit\") != -1 ||\n\t\tstrings.Index(r.UserAgent(), \"opera\") != -1) {\n\t\thttp.Redirect(w, r, \"https:\/\/github.com\/TheHowl\/ip.zxq.co\/blob\/master\/README.md\", 301)\n\t\treturn\n\t}\n\n\t\/\/ Separate two strings when there is a \/ in the URL requested.\n\trequestedThings := strings.Split(r.URL.Path, \"\/\")\n\n\tvar IPAddress string\n\tvar Which string\n\t\/\/ How in the world the user would manage to even send a request to\n\t\/\/ something without even having Path = \"\/\"?\n\t\/\/ I... have no idea. But I'm paranoid. So let's just do it anyway.\n\tif len(requestedThings) < 2 {\n\t\tIPAddress = \"\"\n\t} else {\n\t\tIPAddress = requestedThings[1]\n\t}\n\t\/\/ In case the user didn't write a specific index, let's specify it for\n\t\/\/ them.\n\tif len(requestedThings) < 3 {\n\t\tWhich = \"\"\n\t} else {\n\t\tWhich = requestedThings[2]\n\t}\n\n\t\/\/ Set the requested IP to the user's request request IP, if we got no address.\n\tif IPAddress == \"\" || IPAddress == \"self\" {\n\t\tIPAddress = requestIP\n\t}\n\n\t\/\/ Query parameters array making\n\tqueryParamsRaw, _ := url.ParseQuery(r.URL.RawQuery)\n\tqueryParams := SimplifyQueryMap(queryParamsRaw)\n\tqueryParams = AppendDefaultIfNotSet(queryParams, \"callback\", \"#none#\")\n\tqueryParams = AppendDefaultIfNotSet(queryParams, \"pretty\", \"0\")\n\n\t\/\/ Get the geodata of the requested IP.\n\to, contentType := IPToResponse(IPAddress, Which, queryParams)\n\n\t\/\/ Set the content type as the one given by IPToResponse.\n\tw.Header().Set(\"Content-Type\", contentType+\"; charset=utf-8\")\n\t\/\/ Write the data out to the response.\n\tfmt.Fprint(w, o)\n}\n\n\/\/ Appends a default value to a map only if the key, defined as k, doesn't\n\/\/ already exist in the array.\nfunc AppendDefaultIfNotSet(sl map[string]string, k string, dv string) map[string]string {\n\tif _, ok := sl[k]; !ok {\n\t\tsl[k] = dv\n\t}\n\treturn sl\n}\n\n\/\/ url.ParseQuery returns a map containing as a value a slice with often just\n\/\/ one value. We're fixing that.\nfunc SimplifyQueryMap(sl url.Values) map[string]string {\n\tvar ret map[string]string = map[string]string{}\n\tfor k, v := range sl {\n\t\t\/\/ We're getting only the last element, because we take as granted that\n\t\t\/\/ what the use actually means is the last element, if he has provided\n\t\t\/\/ multiple values for the same key.\n\t\tif len(v) > 0 {\n\t\t\tret[k] = v[len(v)-1]\n\t\t}\n\t}\n\treturn ret\n}\n\n\/\/ Remove from the IP eventual [ or ], and remove the port part of the IP.\nfunc UnfuckRequestIP(ip string) string {\n\tip = strings.Replace(ip, \"[\", \"\", 1)\n\tip = strings.Replace(ip, \"]\", \"\", 1)\n\tss := strings.Split(ip, \":\")\n\tip = strings.Join(ss[:len(ss)-1], \":\")\n\treturn ip\n}\n\n\/\/ Turn the IP into a JSON string containing geodata.\n\/\/\n\/\/ * i: the raw IP string.\n\/\/ * specific: the specific value to get from the geodata array. Default is \"\"\n\/\/ * params: Set callback in the map to a non-\"#none#\" value to use it as a\n\/\/   JSONP callback. Set \"pretty\" to 1 if you want a 2-space indented JSON\n\/\/   output.\nfunc IPToResponse(i string, specific string, params map[string]string) (string, string) {\n\tip := net.ParseIP(i)\n\tif ip == nil {\n\t\treturn \"Please provide a valid IP address\", \"text\/html\"\n\t}\n\n\t\/\/ Query the maxmind database for that IP address.\n\trecord, err := db.City(ip)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ String containing the region\/subdivision of the IP. (E.g.: Scotland, or\n\t\/\/ California).\n\tvar sd string\n\t\/\/ If there are subdivisions for this IP, set sd as the first element in the\n\t\/\/ array's name.\n\tif record.Subdivisions != nil {\n\t\tsd = record.Subdivisions[0].Names[\"en\"]\n\t}\n\n\t\/\/ Create a new instance of all the data to be returned to the user.\n\tdata := map[string]string{}\n\t\/\/ Fill up the data array with the geoip data.\n\tdata[\"ip\"] = ip.String()\n\tdata[\"country\"] = record.Country.IsoCode\n\tdata[\"country_full\"] = record.Country.Names[\"en\"]\n\tdata[\"city\"] = record.City.Names[\"en\"]\n\tdata[\"region\"] = sd\n\tdata[\"continent\"] = record.Continent.Code\n\tdata[\"continent_full\"] = record.Continent.Names[\"en\"]\n\tdata[\"postal\"] = record.Postal.Code\n\t\/\/ precision of latitude\/longitude is up to 4 decimal places (even on\n\t\/\/ ipinfo.io).\n\tdata[\"loc\"] = fmt.Sprintf(\"%.4f,%.4f\", record.Location.Latitude, record.Location.Longitude)\n\n\t\/\/ Since we don't have HTML output, nor other data from geo data,\n\t\/\/ everything is the same if you do \/8.8.8.8, \/8.8.8.8\/json or \/8.8.8.8\/geo.\n\tif specific == \"\" || specific == \"json\" || specific == \"geo\" {\n\t\tvar bytes_output []byte\n\t\tif params[\"pretty\"] == \"1\" {\n\t\t\tbytes_output, _ = json.MarshalIndent(data, \"\", \"  \")\n\t\t} else {\n\t\t\tbytes_output, _ = json.Marshal(data)\n\t\t}\n\t\treturn JSONPify(params[\"callback\"], string(bytes_output[:])),\n\t\t\t\"application\/json\"\n\t} else if val, ok := data[specific]; ok {\n\t\t\/\/ If we got a specific value for what the user requested, return only\n\t\t\/\/ that specific value.\n\t\treturn val, \"text\/html\"\n\t} else {\n\t\t\/\/ We got nothing to show to the user.\n\t\treturn \"undefined\", \"text\/html\"\n\t}\n}\n\n\/\/ Wraps wrapData into a JSONP callback, if the callback name is valid.\nfunc JSONPify(callback string, wrapData string) string {\n\t\/\/ If you have a callback name longer than 2000 characters, I gotta say, you\n\t\/\/ really should learn to minify your javascript code!\n\tif callback != \"#none#\" && callback != \"\" && len(callback) < 2000 {\n\t\t\/\/ In case you're wondering, yes, there is a reason for the empty\n\t\t\/\/ comment! http:\/\/stackoverflow.com\/a\/16048976\/5328069\n\t\twrapData = fmt.Sprintf(\"\/**\/ typeof %s === 'function' \"+\n\t\t\t\"&& %s(%s);\", callback, callback, wrapData)\n\t}\n\treturn wrapData\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/rpc\"\n\t\"time\"\n)\n\n\/\/ TODO the rest\n\nvar serverRoot = flag.String(\"serverRoot\", \"\", \"Path to the root directory in the prod machine\")\nvar mode = flag.String(\"mode\", \"client\", \"'server' or 'client'\")\nvar port = flag.Int(\"port\", 8000, \"port to serve on \/ connect to\")\nvar runBackgroundCheck = flag.Bool(\"enforce\", false, \"Run background enforcer\")\nvar deployFile = flag.String(\"cfg\", \"deploy.json\", \"Deploy config file\")\nvar targetName = flag.String(\"target\", \"prod\", \"Target backend\")\n\nfunc main() {\n\twelcome()\n\tflag.Parse()\n\tif *mode == \"server\" {\n\t\tserverMain()\n\t} else {\n\t\tclientMain()\n\t}\n}\n\nfunc serverMain() {\n\tserver, err := NewServerImpl(\n\t\t*serverRoot,\n\t\t*runBackgroundCheck,\n\t\t*port)\n\tif err != nil {\n\t\tlog.Fatal(\"NewServer:\", err)\n\t}\n\trpcServer := &RpcServer{server}\n\trpc.Register(rpcServer)\n\trpc.HandleHTTP()\n\n\t\/\/ Localhost only, in case it's not behind a firewall!\n\tportStr := fmt.Sprintf(\"localhost:%d\", *port)\n\tl, err := net.Listen(\"tcp\", portStr)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to listen:\", err)\n\t}\n\tfmt.Printf(\"Listening on %s\\n\", portStr)\n\thttp.Serve(l, nil)\n}\n\nfunc clientMain() {\n\tclient, err := NewClientImpl(*deployFile, *targetName)\n\tif err != nil {\n\t\tlog.Fatal(\"NewClient:\", err)\n\t}\n\terr = NewTerminalClient(flag.CommandLine, client).Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc welcome() {\n\tprintln()\n\tprintln(\"  \" + QUOTES[time.Now().UnixNano()%int64(len(QUOTES))])\n\tprintln(\"      -- Camus\")\n\tprintln()\n}\n\nfunc sleepSeconds(seconds int) {\n\ttime.Sleep(time.Duration(seconds) * time.Second)\n}\n<commit_msg>Use -server as a flag instead of -mode server.<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/rpc\"\n\t\"time\"\n)\n\n\/\/ TODO the rest\n\nvar serverRoot = flag.String(\"serverRoot\", \"\", \"Path to the root directory in the prod machine\")\nvar port = flag.Int(\"port\", 8000, \"port to serve on \/ connect to\")\nvar serverMode = flag.Bool(\"server\", false, \"If true, run as a server.\")\nvar runBackgroundCheck = flag.Bool(\"enforce\", false, \"Run background enforcer\")\nvar deployFile = flag.String(\"cfg\", \"deploy.json\", \"Deploy config file\")\nvar targetName = flag.String(\"target\", \"prod\", \"Target backend\")\n\nfunc main() {\n\twelcome()\n\tflag.Parse()\n\tif *serverMode {\n\t\tserverMain()\n\t} else {\n\t\tclientMain()\n\t}\n}\n\nfunc serverMain() {\n\tserver, err := NewServerImpl(\n\t\t*serverRoot,\n\t\t*runBackgroundCheck,\n\t\t*port)\n\tif err != nil {\n\t\tlog.Fatal(\"NewServer:\", err)\n\t}\n\trpcServer := &RpcServer{server}\n\trpc.Register(rpcServer)\n\trpc.HandleHTTP()\n\n\t\/\/ Localhost only, in case it's not behind a firewall!\n\tportStr := fmt.Sprintf(\"localhost:%d\", *port)\n\tl, err := net.Listen(\"tcp\", portStr)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to listen:\", err)\n\t}\n\tfmt.Printf(\"Listening on %s\\n\", portStr)\n\thttp.Serve(l, nil)\n}\n\nfunc clientMain() {\n\tclient, err := NewClientImpl(*deployFile, *targetName)\n\tif err != nil {\n\t\tlog.Fatal(\"NewClient:\", err)\n\t}\n\terr = NewTerminalClient(flag.CommandLine, client).Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc welcome() {\n\tprintln()\n\tprintln(\"  \" + QUOTES[time.Now().UnixNano()%int64(len(QUOTES))])\n\tprintln(\"      -- Camus\")\n\tprintln()\n}\n\nfunc sleepSeconds(seconds int) {\n\ttime.Sleep(time.Duration(seconds) * time.Second)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"runtime\"\n\n\t\"github.com\/techjanitor\/pram-post\/config\"\n\tc \"github.com\/techjanitor\/pram-post\/controllers\"\n\tm \"github.com\/techjanitor\/pram-post\/middleware\"\n\tu \"github.com\/techjanitor\/pram-post\/utils\"\n)\n\nfunc init() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\tconfig.Print()\n\n\t\/\/ Set up DB connection\n\tu.NewDb()\n\n\t\/\/ Set up Redis connection\n\tu.NewRedisCache()\n}\n\nfunc main() {\n\tr := gin.Default()\n\n\tr.Use(gin.ForwardedFor(\"127.0.0.1\/32\"))\n\t\/\/ Checks for antispam cookie\n\tr.Use(m.GetAntiSpamCookie())\n\n\tr.POST(\"\/thread\/new\", c.ThreadController)\n\tr.POST(\"\/thread\/reply\", c.ReplyController)\n\tr.POST(\"\/tag\/new\", c.NewTagController)\n\tr.POST(\"\/tag\/add\", c.AddTagController)\n\tr.NoRoute(c.ErrorController)\n\n\tr.Run(fmt.Sprintf(\"%s:%d\", config.Settings.General.Address, config.Settings.General.Port))\n\n}\n<commit_msg>add graceful shutdown<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/facebookgo\/grace\/gracehttp\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"runtime\"\n\n\t\"github.com\/techjanitor\/pram-post\/config\"\n\tc \"github.com\/techjanitor\/pram-post\/controllers\"\n\tm \"github.com\/techjanitor\/pram-post\/middleware\"\n\tu \"github.com\/techjanitor\/pram-post\/utils\"\n)\n\nfunc init() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\tconfig.Print()\n\n\t\/\/ Set up DB connection\n\tu.NewDb()\n\n\t\/\/ Set up Redis connection\n\tu.NewRedisCache()\n}\n\nfunc main() {\n\tr := gin.Default()\n\n\tr.Use(gin.ForwardedFor(\"127.0.0.1\/32\"))\n\t\/\/ Checks for antispam cookie\n\tr.Use(m.GetAntiSpamCookie())\n\n\tr.POST(\"\/thread\/new\", c.ThreadController)\n\tr.POST(\"\/thread\/reply\", c.ReplyController)\n\tr.POST(\"\/tag\/new\", c.NewTagController)\n\tr.POST(\"\/tag\/add\", c.AddTagController)\n\tr.NoRoute(c.ErrorController)\n\n\ts := &http.Server{\n\t\tAddr:    fmt.Sprintf(\"%s:%d\", config.Settings.General.Address, config.Settings.General.Port),\n\t\tHandler: r,\n\t}\n\n\tgracehttp.Serve(s)\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Joe Walnes and the websocketd team.\n\/\/ All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/joewalnes\/websocketd\/libwebsocketd\"\n)\n\nfunc log(l *libwebsocketd.LogScope, level libwebsocketd.LogLevel, levelName string, category string, msg string, args ...interface{}) {\n\tif level < l.MinLevel {\n\t\treturn\n\t}\n\tfullMsg := fmt.Sprintf(msg, args...)\n\n\tassocDump := \"\"\n\tfor index, pair := range l.Associated {\n\t\tif index > 0 {\n\t\t\tassocDump += \" \"\n\t\t}\n\t\tassocDump += fmt.Sprintf(\"%s:'%s'\", pair.Key, pair.Value)\n\t}\n\n\tl.Mutex.Lock()\n\tfmt.Printf(\"%s | %-6s | %-10s | %s | %s\\n\", libwebsocketd.Timestamp(), levelName, category, assocDump, fullMsg)\n\tl.Mutex.Unlock()\n}\n\nfunc main() {\n\tconfig := parseCommandLine()\n\n\tlog := libwebsocketd.RootLogScope(config.LogLevel, log)\n\n\tif config.DevConsole {\n\t\tif config.StaticDir != \"\" {\n\t\t\tlog.Fatal(\"server\", \"Invalid parameters: --devconsole cannot be used with --staticdir. Pick one.\")\n\t\t\tos.Exit(4)\n\t\t}\n\t\tif config.CgiDir != \"\" {\n\t\t\tlog.Fatal(\"server\", \"Invalid parameters: --devconsole cannot be used with --cgidir. Pick one.\")\n\t\t\tos.Exit(4)\n\t\t}\n\t}\n\n\tos.Clearenv() \/\/ it's ok to wipe it clean, we already read env variables from passenv into config\n\thandler := libwebsocketd.NewWebsocketdServer(config.Config, log, config.MaxForks)\n\thttp.Handle(\"\/\", handler)\n\n\tif config.UsingScriptDir {\n\t\tlog.Info(\"server\", \"Serving from directory      : %s\", config.ScriptDir)\n\t} else if config.CommandName != \"\" {\n\t\tlog.Info(\"server\", \"Serving using application   : %s %s\", config.CommandName, strings.Join(config.CommandArgs, \" \"))\n\t}\n\tif config.StaticDir != \"\" {\n\t\tlog.Info(\"server\", \"Serving static content from : %s\", config.StaticDir)\n\t}\n\tif config.CgiDir != \"\" {\n\t\tlog.Info(\"server\", \"Serving CGI scripts from    : %s\", config.CgiDir)\n\t}\n\n\trejects := make(chan error, 1)\n\tfor _, addrSingle := range config.Addr {\n\t\tlog.Info(\"server\", \"Starting WebSocket server   : %s\", handler.TellURL(\"ws\", addrSingle, \"\/\"))\n\t\tif config.DevConsole {\n\t\t\tlog.Info(\"server\", \"Developer console enabled   : %s\", handler.TellURL(\"http\", addrSingle, \"\/\"))\n\t\t} else if config.StaticDir != \"\" || config.CgiDir != \"\" {\n\t\t\tlog.Info(\"server\", \"Serving CGI or static files : %s\", handler.TellURL(\"http\", addrSingle, \"\/\"))\n\t\t}\n\t\t\/\/ ListenAndServe is blocking function. Let's run it in\n\t\t\/\/ go routine, reporting result to control channel.\n\t\t\/\/ Since it's blocking it'll never return non-error.\n\n\t\tgo func(addr string) {\n\t\t\tif config.Ssl {\n\t\t\t\trejects <- http.ListenAndServeTLS(addr, config.CertFile, config.KeyFile, nil)\n\t\t\t} else {\n\t\t\t\trejects <- http.ListenAndServe(addr, nil)\n\t\t\t}\n\t\t\tfmt.Println(config.RedirPort)\n\t\t}(addrSingle)\n\n\t\tif config.RedirPort != 0 {\n\t\t\tgo func(addr string) {\n\t\t\t\tpos := strings.IndexByte(addr, ':')\n\t\t\t\trediraddr := addr[:pos] + \":\" + strconv.Itoa(config.RedirPort) \/\/ it would be silly to optimize this one\n\t\t\t\tredir := &http.Server{Addr: rediraddr, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\t\t\t\/\/ redirect to same hostname as in request but different port and probably schema\n\t\t\t\t\turi := \"https:\/\/\"\n\t\t\t\t\tif !config.Ssl {\n\t\t\t\t\t\turi = \"http:\/\/\"\n\t\t\t\t\t}\n\t\t\t\t\turi += r.Host[:strings.IndexByte(r.Host, ':')] + addr[pos:] + \"\/\"\n\n\t\t\t\t\thttp.Redirect(w, r, uri, http.StatusMovedPermanently)\n\t\t\t\t})}\n\t\t\t\tlog.Info(\"server\", \"Starting redirect server   : http:\/\/%s\/\", rediraddr)\n\t\t\t\trejects <- redir.ListenAndServe()\n\t\t\t}(addrSingle)\n\t\t}\n\t}\n\tselect {\n\tcase err := <-rejects:\n\t\tlog.Fatal(\"server\", \"Can't start server: %s\", err)\n\t\tos.Exit(3)\n\t}\n}\n<commit_msg>Removed debug code<commit_after>\/\/ Copyright 2013 Joe Walnes and the websocketd team.\n\/\/ All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/joewalnes\/websocketd\/libwebsocketd\"\n)\n\nfunc log(l *libwebsocketd.LogScope, level libwebsocketd.LogLevel, levelName string, category string, msg string, args ...interface{}) {\n\tif level < l.MinLevel {\n\t\treturn\n\t}\n\tfullMsg := fmt.Sprintf(msg, args...)\n\n\tassocDump := \"\"\n\tfor index, pair := range l.Associated {\n\t\tif index > 0 {\n\t\t\tassocDump += \" \"\n\t\t}\n\t\tassocDump += fmt.Sprintf(\"%s:'%s'\", pair.Key, pair.Value)\n\t}\n\n\tl.Mutex.Lock()\n\tfmt.Printf(\"%s | %-6s | %-10s | %s | %s\\n\", libwebsocketd.Timestamp(), levelName, category, assocDump, fullMsg)\n\tl.Mutex.Unlock()\n}\n\nfunc main() {\n\tconfig := parseCommandLine()\n\n\tlog := libwebsocketd.RootLogScope(config.LogLevel, log)\n\n\tif config.DevConsole {\n\t\tif config.StaticDir != \"\" {\n\t\t\tlog.Fatal(\"server\", \"Invalid parameters: --devconsole cannot be used with --staticdir. Pick one.\")\n\t\t\tos.Exit(4)\n\t\t}\n\t\tif config.CgiDir != \"\" {\n\t\t\tlog.Fatal(\"server\", \"Invalid parameters: --devconsole cannot be used with --cgidir. Pick one.\")\n\t\t\tos.Exit(4)\n\t\t}\n\t}\n\n\tos.Clearenv() \/\/ it's ok to wipe it clean, we already read env variables from passenv into config\n\thandler := libwebsocketd.NewWebsocketdServer(config.Config, log, config.MaxForks)\n\thttp.Handle(\"\/\", handler)\n\n\tif config.UsingScriptDir {\n\t\tlog.Info(\"server\", \"Serving from directory      : %s\", config.ScriptDir)\n\t} else if config.CommandName != \"\" {\n\t\tlog.Info(\"server\", \"Serving using application   : %s %s\", config.CommandName, strings.Join(config.CommandArgs, \" \"))\n\t}\n\tif config.StaticDir != \"\" {\n\t\tlog.Info(\"server\", \"Serving static content from : %s\", config.StaticDir)\n\t}\n\tif config.CgiDir != \"\" {\n\t\tlog.Info(\"server\", \"Serving CGI scripts from    : %s\", config.CgiDir)\n\t}\n\n\trejects := make(chan error, 1)\n\tfor _, addrSingle := range config.Addr {\n\t\tlog.Info(\"server\", \"Starting WebSocket server   : %s\", handler.TellURL(\"ws\", addrSingle, \"\/\"))\n\t\tif config.DevConsole {\n\t\t\tlog.Info(\"server\", \"Developer console enabled   : %s\", handler.TellURL(\"http\", addrSingle, \"\/\"))\n\t\t} else if config.StaticDir != \"\" || config.CgiDir != \"\" {\n\t\t\tlog.Info(\"server\", \"Serving CGI or static files : %s\", handler.TellURL(\"http\", addrSingle, \"\/\"))\n\t\t}\n\t\t\/\/ ListenAndServe is blocking function. Let's run it in\n\t\t\/\/ go routine, reporting result to control channel.\n\t\t\/\/ Since it's blocking it'll never return non-error.\n\n\t\tgo func(addr string) {\n\t\t\tif config.Ssl {\n\t\t\t\trejects <- http.ListenAndServeTLS(addr, config.CertFile, config.KeyFile, nil)\n\t\t\t} else {\n\t\t\t\trejects <- http.ListenAndServe(addr, nil)\n\t\t\t}\n\t\t}(addrSingle)\n\n\t\tif config.RedirPort != 0 {\n\t\t\tgo func(addr string) {\n\t\t\t\tpos := strings.IndexByte(addr, ':')\n\t\t\t\trediraddr := addr[:pos] + \":\" + strconv.Itoa(config.RedirPort) \/\/ it would be silly to optimize this one\n\t\t\t\tredir := &http.Server{Addr: rediraddr, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\t\t\t\/\/ redirect to same hostname as in request but different port and probably schema\n\t\t\t\t\turi := \"https:\/\/\"\n\t\t\t\t\tif !config.Ssl {\n\t\t\t\t\t\turi = \"http:\/\/\"\n\t\t\t\t\t}\n\t\t\t\t\turi += r.Host[:strings.IndexByte(r.Host, ':')] + addr[pos:] + \"\/\"\n\n\t\t\t\t\thttp.Redirect(w, r, uri, http.StatusMovedPermanently)\n\t\t\t\t})}\n\t\t\t\tlog.Info(\"server\", \"Starting redirect server   : http:\/\/%s\/\", rediraddr)\n\t\t\t\trejects <- redir.ListenAndServe()\n\t\t\t}(addrSingle)\n\t\t}\n\t}\n\tselect {\n\tcase err := <-rejects:\n\t\tlog.Fatal(\"server\", \"Can't start server: %s\", err)\n\t\tos.Exit(3)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/drone\/drone-plugin-go\/plugin\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar debug bool\n\nfunc doRequest(param ReqEnvelope) (bool, error) {\n\tif debug {\n\t\tlog.Println(\"doRequest \")\n\t}\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\tvar req *http.Request\n\tvar err error\n\t\/\/ post payload to each artifact\n\tif param.Json == nil {\n\t\treq, err = http.NewRequest(param.Verb, param.Url, nil)\n\t} else {\n\t\treq, err = http.NewRequest(param.Verb, param.Url, bytes.NewBuffer(param.Json))\n\t}\n\n\tif param.Verb == \"PATCH\" {\n\t\treq.Header.Set(\"Content-Type\", \"application\/strategic-merge-patch+json \")\n\t} else {\n\t\treq.Header.Set(\"Content-Type\", \"application\/json \")\n\t}\n\n\tif debug {\n\t\tlog.Println(\"HTTP Request %s\", param.Verb)\n\t\tlog.Println(\"HTTP Request %s\", param.Url)\n\t\tlog.Println(\"HTTP Request %s\", string(param.Json))\n\t}\n\n\treq.Header.Set(\"Authorization\", \"Bearer \"+param.Token)\n\tresponse, err := client.Do(req)\n\tif debug {\n\t\tcontents, err := ioutil.ReadAll(response.Body)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tlog.Printf(\"%s\\n\", string(contents))\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else {\n\t\tdefer response.Body.Close()\n\n\t\tif response.StatusCode == 200 {\n\t\t\treturn true, err\n\t\t}\n\t}\n\treturn false, err\n}\n\nfunc readArtifactFromFile(workspace string, artifactFile string, apiserver string, namespace string) (Artifact, error) {\n\tartifactFilename := workspace + \"\/\" + artifactFile\n\tif debug {\n\t\tlog.Println(\"readArtifactFromFile \" + artifactFilename)\n\t}\n\tfile, err := ioutil.ReadFile(artifactFilename)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tartifact := Artifact{}\n\tif strings.HasSuffix(artifactFilename, \".yaml\") {\n\t\tfile = yaml2Json(file)\n\t}\n\n\tjson.Unmarshal(file, &artifact)\n\tartifact.Data = file\n\n\tif artifact.Kind == \"ReplicationController\" {\n\t\tartifact.Url = fmt.Sprintf(\"%s\/api\/v1\/namespaces\/%s\/replicationcontrollers\", apiserver, namespace)\n\t}\n\tif artifact.Kind == \"Service\" {\n\t\tartifact.Url = fmt.Sprintf(\"%s\/api\/v1\/namespaces\/%s\/services\", apiserver, namespace)\n\t}\n\n\treturn artifact, err\n}\n\nfunc makeTimestamp() int64 {\n\treturn time.Now().UnixNano() \/ int64(time.Millisecond)\n}\n\nfunc sendWebhook(wh *WebHook) {\n\n\tjwh, err := json.Marshal(wh)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t\treturn\n\t}\n\treq := ReqEnvelope{\n\t\tVerb:  \"POST\",\n\t\tToken: wh.Token,\n\t\tUrl:   wh.Url,\n\t\tJson:  []byte(jwh),\n\t}\n\tdoRequest(req)\n}\n\nvar deployments []string\n\nfunc main() {\n\tvar vargs = struct {\n\t\tReplicationControllers []string `json:replicationcontrollers`\n\t\tServices               []string `json:services`\n\t\tApiServer              string   `json:apiserver`\n\t\tToken                  string   `json:token`\n\t\tNamespace              string   `json:namespace`\n\t\tDebug                  string   `json:debug`\n\t\tSource                 string   `json:source`\n\t}{}\n\n\tworkspace := plugin.Workspace{}\n\tplugin.Param(\"workspace\", &workspace)\n\tplugin.Param(\"vargs\", &vargs)\n\tplugin.Parse()\n\tdebug = true\n\tif vargs.Debug == \"true\" {\n\t\tdebug = true\n\t}\n\n\tif debug {\n\t\tlog.Println(\"Workspace Root: \" + workspace.Root)\n\t\tlog.Println(\"Workspace Path: \" + workspace.Path)\n\t}\n\n\t\/\/ Iterate over rcs and svcs\n\tfor _, rc := range vargs.ReplicationControllers {\n\t\tartifact, err := readArtifactFromFile(workspace.Path, rc, vargs.ApiServer, vargs.Namespace)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif debug {\n\t\t\tlog.Println(\"Artifact loaded: \" + artifact.Url)\n\t\t}\n\t\tif b, _ := existsArtifact(artifact, vargs.Token); b {\n\t\t\tdeleteArtifact(artifact, vargs.Token)\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t}\n\t\tcreateArtifact(artifact, vargs.Token)\n\t}\n\tfor _, rc := range vargs.Services {\n\t\tartifact, err := readArtifactFromFile(workspace.Path, rc, vargs.ApiServer, vargs.Namespace)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tcreateArtifact(artifact, vargs.Token)\n\t}\n\t\/\/ if vargs.Webhook != \"\" {\n\t\/\/ \twh := &WebHook{\n\t\/\/ \t\tTimestamp: makeTimestamp(),\n\t\/\/ \t\tImages:    deployments,\n\t\/\/ \t\tNamespace: vargs.Namespace,\n\t\/\/ \t\tSource:    vargs.Source,\n\t\/\/ \t\tTarget:    vargs.ApiServer,\n\t\/\/ \t\tUrl:       vargs.Webhook,\n\t\/\/ \t\tToken:     vargs.WebHookToken,\n\t\/\/ \t}\n\t\/\/ \tsendWebhook(wh)\n\t\/\/ }\n}\n<commit_msg>debug print env vars<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/drone\/drone-plugin-go\/plugin\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar debug bool\n\nfunc doRequest(param ReqEnvelope) (bool, error) {\n\tif debug {\n\t\tlog.Println(\"doRequest \")\n\t}\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\tvar req *http.Request\n\tvar err error\n\t\/\/ post payload to each artifact\n\tif param.Json == nil {\n\t\treq, err = http.NewRequest(param.Verb, param.Url, nil)\n\t} else {\n\t\treq, err = http.NewRequest(param.Verb, param.Url, bytes.NewBuffer(param.Json))\n\t}\n\n\tif param.Verb == \"PATCH\" {\n\t\treq.Header.Set(\"Content-Type\", \"application\/strategic-merge-patch+json \")\n\t} else {\n\t\treq.Header.Set(\"Content-Type\", \"application\/json \")\n\t}\n\n\tif debug {\n\t\tlog.Println(\"HTTP Request %s\", param.Verb)\n\t\tlog.Println(\"HTTP Request %s\", param.Url)\n\t\tlog.Println(\"HTTP Request %s\", string(param.Json))\n\t}\n\n\treq.Header.Set(\"Authorization\", \"Bearer \"+param.Token)\n\tresponse, err := client.Do(req)\n\tif debug {\n\t\tcontents, err := ioutil.ReadAll(response.Body)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tlog.Printf(\"%s\\n\", string(contents))\n\t}\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t} else {\n\t\tdefer response.Body.Close()\n\n\t\tif response.StatusCode == 200 {\n\t\t\treturn true, err\n\t\t}\n\t}\n\treturn false, err\n}\n\nfunc readArtifactFromFile(workspace string, artifactFile string, apiserver string, namespace string) (Artifact, error) {\n\tartifactFilename := workspace + \"\/\" + artifactFile\n\tif debug {\n\t\tlog.Println(\"readArtifactFromFile \" + artifactFilename)\n\t}\n\tfile, err := ioutil.ReadFile(artifactFilename)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tartifact := Artifact{}\n\tif strings.HasSuffix(artifactFilename, \".yaml\") {\n\t\tfile = yaml2Json(file)\n\t}\n\n\tjson.Unmarshal(file, &artifact)\n\tartifact.Data = file\n\n\tif artifact.Kind == \"ReplicationController\" {\n\t\tartifact.Url = fmt.Sprintf(\"%s\/api\/v1\/namespaces\/%s\/replicationcontrollers\", apiserver, namespace)\n\t}\n\tif artifact.Kind == \"Service\" {\n\t\tartifact.Url = fmt.Sprintf(\"%s\/api\/v1\/namespaces\/%s\/services\", apiserver, namespace)\n\t}\n\n\treturn artifact, err\n}\n\nfunc makeTimestamp() int64 {\n\treturn time.Now().UnixNano() \/ int64(time.Millisecond)\n}\n\nfunc sendWebhook(wh *WebHook) {\n\n\tjwh, err := json.Marshal(wh)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t\treturn\n\t}\n\treq := ReqEnvelope{\n\t\tVerb:  \"POST\",\n\t\tToken: wh.Token,\n\t\tUrl:   wh.Url,\n\t\tJson:  []byte(jwh),\n\t}\n\tdoRequest(req)\n}\n\nvar deployments []string\n\nfunc main() {\n\tvar vargs = struct {\n\t\tReplicationControllers []string `json:replicationcontrollers`\n\t\tServices               []string `json:services`\n\t\tApiServer              string   `json:apiserver`\n\t\tToken                  string   `json:token`\n\t\tNamespace              string   `json:namespace`\n\t\tDebug                  string   `json:debug`\n\t\tSource                 string   `json:source`\n\t}{}\n\n\tworkspace := plugin.Workspace{}\n\tplugin.Param(\"workspace\", &workspace)\n\tplugin.Param(\"vargs\", &vargs)\n\tplugin.Parse()\n\tdebug = true\n\tif vargs.Debug == \"true\" {\n\t\tdebug = true\n\t}\n\n\tif debug {\n\t\tlog.Println(\"Workspace Root: \" + workspace.Root)\n\t\tlog.Println(\"Workspace Path: \" + workspace.Path)\n\n\t\tfor _, e := range os.Environ() {\n\t\t\tpair := strings.Split(e, \"=\")\n\t\t\tlog.Println(pair[0])\n\t\t}\n\t}\n\n\t\/\/ Iterate over rcs and svcs\n\tfor _, rc := range vargs.ReplicationControllers {\n\t\tartifact, err := readArtifactFromFile(workspace.Path, rc, vargs.ApiServer, vargs.Namespace)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif debug {\n\t\t\tlog.Println(\"Artifact loaded: \" + artifact.Url)\n\t\t}\n\t\tif b, _ := existsArtifact(artifact, vargs.Token); b {\n\t\t\tdeleteArtifact(artifact, vargs.Token)\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t}\n\t\tcreateArtifact(artifact, vargs.Token)\n\t}\n\tfor _, rc := range vargs.Services {\n\t\tartifact, err := readArtifactFromFile(workspace.Path, rc, vargs.ApiServer, vargs.Namespace)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tcreateArtifact(artifact, vargs.Token)\n\t}\n\t\/\/ if vargs.Webhook != \"\" {\n\t\/\/ \twh := &WebHook{\n\t\/\/ \t\tTimestamp: makeTimestamp(),\n\t\/\/ \t\tImages:    deployments,\n\t\/\/ \t\tNamespace: vargs.Namespace,\n\t\/\/ \t\tSource:    vargs.Source,\n\t\/\/ \t\tTarget:    vargs.ApiServer,\n\t\/\/ \t\tUrl:       vargs.Webhook,\n\t\/\/ \t\tToken:     vargs.WebHookToken,\n\t\/\/ \t}\n\t\/\/ \tsendWebhook(wh)\n\t\/\/ }\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\n\tjd \"github.com\/josephburnett\/jd\/lib\"\n)\n\nvar patch = flag.Bool(\"p\", false, \"Patch mode\")\nvar output = flag.String(\"o\", \"\", \"Output file\")\nvar set = flag.Bool(\"set\", false, \"Arrays as sets\")\nvar mset = flag.Bool(\"mset\", false, \"Arrays as multisets\")\nvar setkeys = flag.String(\"setkeys\", \"\", \"Keys to identify set objects\")\n\nfunc main() {\n\tflag.Parse()\n\tvar a, b string\n\tswitch len(flag.Args()) {\n\tcase 1:\n\t\ta = readFile(flag.Arg(0))\n\t\tb = readStdin()\n\tcase 2:\n\t\ta = readFile(flag.Arg(0))\n\t\tb = readFile(flag.Arg(1))\n\tdefault:\n\t\tprintUsageAndExit()\n\t}\n\tif *patch {\n\t\tpatchJson(a, b)\n\t} else {\n\t\tdiffJson(a, b)\n\t}\n}\n\nfunc printUsageAndExit() {\n\tfor _, line := range []string{\n\t\t``,\n\t\t`Usage: jd [OPTION]... FILE1 [FILE2]`,\n\t\t`Diff and patch JSON files.`,\n\t\t``,\n\t\t`Prints the diff of FILE1 and FILE2 to STDOUT.`,\n\t\t`When FILE2 is omitted the second input is read from STDIN.`,\n\t\t`When patching (-p) FILE1 is a diff.`,\n\t\t``,\n\t\t`Options:`,\n\t\t`  -p        Apply patch FILE1 to FILE2 or STDIN.`,\n\t\t`  -o=FILE3  Write to FILE3 instead of STDOUT.`,\n\t\t`  -set      Treat arrays as sets.`,\n\t\t`  -mset     Treat arrays as multisets (bags).`,\n\t\t``,\n\t\t`Examples:`,\n\t\t`  jd a.json b.json`,\n\t\t`  cat b.json | jd a.json`,\n\t\t`  jd -o patch a.json b.json; jd patch a.json`,\n\t\t`  jd -set a.json b.json`,\n\t\t``,\n\t} {\n\t\tfmt.Println(line)\n\t}\n\tos.Exit(1)\n}\n\nfunc diffJson(a, b string) {\n\taNode, err := readJsonString(a)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\tbNode, err := readJsonString(b)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\tdiff := aNode.Diff(bNode)\n\tif *output == \"\" {\n\t\tfmt.Print(diff.Render())\n\t} else {\n\t\tioutil.WriteFile(*output, []byte(diff.Render()), 0644)\n\t}\n}\n\nfunc patchJson(p, a string) {\n\tdiff, err := readDiffString(p)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\taNode, err := readJsonString(a)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\tbNode, err := aNode.Patch(diff)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\tif *output == \"\" {\n\t\tfmt.Print(bNode.Json())\n\t} else {\n\t\tioutil.WriteFile(*output, []byte(bNode.Json()), 0644)\n\t}\n}\n\nfunc readJsonString(s string) (jd.JsonNode, error) {\n\tif *set {\n\t\treturn jd.ReadJsonString(s, jd.SET)\n\t}\n\tif *mset {\n\t\treturn jd.ReadJsonString(s, jd.MULTISET)\n\t}\n\treturn jd.ReadJsonString(s)\n}\n\nfunc readDiffString(s string) (jd.Diff, error) {\n\tif *set {\n\t\treturn jd.ReadDiffString(s, jd.SET)\n\t}\n\tif *mset {\n\t\treturn jd.ReadDiffString(s, jd.MULTISET)\n\t}\n\treturn jd.ReadDiffString(s)\n}\n\nfunc readFile(filename string) string {\n\tbytes, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\treturn string(bytes)\n}\n\nfunc readStdin() string {\n\tr := bufio.NewReader(os.Stdin)\n\tbytes, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\treturn string(bytes)\n}\n<commit_msg>Pass setkeys option when unmarshalling.<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\tjd \"github.com\/josephburnett\/jd\/lib\"\n)\n\nvar patch = flag.Bool(\"p\", false, \"Patch mode\")\nvar output = flag.String(\"o\", \"\", \"Output file\")\nvar set = flag.Bool(\"set\", false, \"Arrays as sets\")\nvar mset = flag.Bool(\"mset\", false, \"Arrays as multisets\")\nvar setkeys = flag.String(\"setkeys\", \"\", \"Keys to identify set objects\")\n\nfunc main() {\n\tflag.Parse()\n\toptions, err := parseOptions()\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\tvar a, b string\n\tswitch len(flag.Args()) {\n\tcase 1:\n\t\ta = readFile(flag.Arg(0))\n\t\tb = readStdin()\n\tcase 2:\n\t\ta = readFile(flag.Arg(0))\n\t\tb = readFile(flag.Arg(1))\n\tdefault:\n\t\tprintUsageAndExit()\n\t}\n\tif *patch {\n\t\tpatchJson(a, b, options)\n\t} else {\n\t\tdiffJson(a, b, options)\n\t}\n}\n\nfunc parseOptions() ([]jd.Option, error) {\n\toptions := make([]jd.Option, 0)\n\tif *set {\n\t\toptions = append(options, jd.SET)\n\t}\n\tif *mset {\n\t\toptions = append(options, jd.MULTISET)\n\t}\n\tif *setkeys != \"\" {\n\t\tkeys := make([]string, 0)\n\t\tks := strings.Split(*setkeys, \",\")\n\t\tfor _, k := range ks {\n\t\t\ttrimmed := strings.TrimSpace(k)\n\t\t\tif trimmed == \"\" {\n\t\t\t\treturn nil, fmt.Errorf(\"Invalid set key: %v\", k)\n\t\t\t}\n\t\t\tkeys = append(keys, trimmed)\n\t\t}\n\t\toptions = append(options, jd.SetkeysOption(keys))\n\t}\n\treturn options, nil\n}\n\nfunc printUsageAndExit() {\n\tfor _, line := range []string{\n\t\t``,\n\t\t`Usage: jd [OPTION]... FILE1 [FILE2]`,\n\t\t`Diff and patch JSON files.`,\n\t\t``,\n\t\t`Prints the diff of FILE1 and FILE2 to STDOUT.`,\n\t\t`When FILE2 is omitted the second input is read from STDIN.`,\n\t\t`When patching (-p) FILE1 is a diff.`,\n\t\t``,\n\t\t`Options:`,\n\t\t`  -p        Apply patch FILE1 to FILE2 or STDIN.`,\n\t\t`  -o=FILE3  Write to FILE3 instead of STDOUT.`,\n\t\t`  -set      Treat arrays as sets.`,\n\t\t`  -mset     Treat arrays as multisets (bags).`,\n\t\t``,\n\t\t`Examples:`,\n\t\t`  jd a.json b.json`,\n\t\t`  cat b.json | jd a.json`,\n\t\t`  jd -o patch a.json b.json; jd patch a.json`,\n\t\t`  jd -set a.json b.json`,\n\t\t``,\n\t} {\n\t\tfmt.Println(line)\n\t}\n\tos.Exit(1)\n}\n\nfunc diffJson(a, b string, options []jd.Option) {\n\taNode, err := jd.ReadJsonString(a, options...)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\tbNode, err := jd.ReadJsonString(b, options...)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\tdiff := aNode.Diff(bNode)\n\tif *output == \"\" {\n\t\tfmt.Print(diff.Render())\n\t} else {\n\t\tioutil.WriteFile(*output, []byte(diff.Render()), 0644)\n\t}\n}\n\nfunc patchJson(p, a string, options []jd.Option) {\n\tdiff, err := jd.ReadDiffString(p, options...)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\taNode, err := jd.ReadJsonString(a, options...)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\tbNode, err := aNode.Patch(diff)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\tif *output == \"\" {\n\t\tfmt.Print(bNode.Json())\n\t} else {\n\t\tioutil.WriteFile(*output, []byte(bNode.Json()), 0644)\n\t}\n}\n\nfunc readFile(filename string) string {\n\tbytes, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\treturn string(bytes)\n}\n\nfunc readStdin() string {\n\tr := bufio.NewReader(os.Stdin)\n\tbytes, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\treturn string(bytes)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"github.com\/drone\/drone-plugin-go\/plugin\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n)\n\nvar kubeConf *KubeConf\n\ntype KubeConf struct {\n\tApiServer string `json:apiserver`\n\tToken     string `json:token`\n\tNamespace string `json:namespace`\n}\n\ntype Artifact struct {\n\tName      string\n\tUpdate    string \/\/ overwrite, rolling-update\n\tNamespace string\n\tType      string \/\/ rcs, svcs\n}\n\nfunc (a Artifact) Exists() bool {\n\treturn true\n}\n\nfunc createArtifact(artifact string, url string, token string, workspace string) {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\n\tfile, e := ioutil.ReadFile(workspace + \"\/\" + artifact)\n\tfmt.Println(string(file))\n\tif e != nil {\n\t\tfmt.Println(e)\n\t\tos.Exit(1)\n\t}\n\t\/\/ post payload to each artifact\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(file))\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+token)\n\tclient := &http.Client{Transport: tr}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\tcontents, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\tfmt.Printf(\"%s\\n\", string(contents))\n\n}\n\nfunc main() {\n\tvar vargs = struct {\n\t\tReplicationControllers []string `json:\"replicationcontrollers\"`\n\t\tServices               []string `json:\"services\"`\n\t\tApiServer              string   `json:apiserver`\n\t\tToken                  string   `json:token`\n\t\tNamespace              string   `json:namespace`\n\t}{}\n\n\tworkspace := plugin.Workspace{}\n\tplugin.Param(\"workspace\", &workspace)\n\tplugin.Param(\"vargs\", &vargs)\n\tplugin.Parse()\n\n\trc_url := fmt.Sprintf(\"%s\/api\/v1\/namespaces\/%s\/replicationcontrollers\", vargs.ApiServer, vargs.Namespace)\n\tsvc_url := fmt.Sprintf(\"%s\/api\/v1\/namespaces\/%s\/services\", vargs.ApiServer, vargs.Namespace)\n\n\t\/\/ Iterate over rcs and svcs\n\tfor _, rc := range vargs.ReplicationControllers {\n\t\tcreateArtifact(rc, rc_url, vargs.Token, workspace.Path)\n\t}\n\tfor _, rc := range vargs.Services {\n\t\tcreateArtifact(rc, svc_url, vargs.Token, workspace.Path)\n\t}\n}\n<commit_msg>check before create to delete<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"github.com\/drone\/drone-plugin-go\/plugin\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n)\n\ntype Artifact struct {\n\tApiVersion string\n\tKind       string\n\tData       []byte\n\tMetadata   struct {\n\t\tName string\n\t}\n\tUrl string\n}\n\n\/\/ Kubernetes API doesn't delete pods when deleting an RC\n\/\/ to cleanly remove the rc we have to set `replicas=0`\n\/\/ and then delete the RC\nfunc deleteArtifact(artifact Artifact, token string) (bool, error) {\n\turl := fmt.Sprintf(\"%s\/%s\", artifact.Url, artifact.Metadata.Name)\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\t\/\/ post payload to each artifact\n\treq, err := http.NewRequest(\"DELETE\", url, nil)\n\treq.Header.Set(\"Authorization\", \"Bearer \"+token)\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tfmt.Printf(\"%s\", err)\n\t\tos.Exit(1)\n\t} else {\n\t\tdefer response.Body.Close()\n\t\tcontents, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", string(contents))\n\t\tif response.StatusCode == 200 {\n\t\t\treturn true, err\n\t\t}\n\t}\n\treturn false, err\n}\n\nfunc existsArtifact(artifact Artifact, token string) (bool, error) {\n\turl := fmt.Sprintf(\"%s\/%s\", artifact.Url, artifact.Metadata.Name)\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\t\/\/ post payload to each artifact\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Set(\"Authorization\", \"Bearer \"+token)\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tfmt.Printf(\"%s\", err)\n\t\tos.Exit(1)\n\t} else {\n\t\tdefer response.Body.Close()\n\t\tif response.StatusCode == 200 {\n\t\t\treturn true, err\n\t\t}\n\t}\n\treturn false, err\n}\n\nfunc createArtifact(artifact Artifact, token string) {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\n\t\/\/ post payload to each artifact\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(artifact.Data))\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+token)\n\tclient := &http.Client{Transport: tr}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer resp.Body.Close()\n\tcontents, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\tfmt.Printf(\"%s\\n\", string(contents))\n\n}\n\nfunc readArtifactFromFile(workspace string, artifact string, apiserver string, namespace string) (Artifact, error) {\n\tfile, e := ioutil.ReadFile(workspace + \"\/\" + artifact)\n\t\/\/ fmt.Println(string(file))\n\tif e != nil {\n\t\tfmt.Println(e)\n\t\tos.Exit(1)\n\t}\n\tartifact := Artifact{}\n\tjson.Unmarshal(file, &artifact)\n\tartifact.Data = file\n\tif artifact.Kind == \"ReplicationController\" {\n\t\tartifact.Url = fmt.Sprintf(\"%s\/api\/v1\/namespaces\/%s\/replicationcontrollers\", apiserver, namespace)\n\t}\n\tif artifact.Kind == \"Service\" {\n\t\tartifact.Url = fmt.Sprintf(\"%s\/api\/v1\/namespaces\/%s\/services\", apiserver, namespace)\n\t}\n\n\treturn artifact, e\n}\n\nfunc main() {\n\tvar vargs = struct {\n\t\tReplicationControllers []string `json:replicationcontrollers`\n\t\tServices               []string `json:services`\n\t\tApiServer              string   `json:apiserver`\n\t\tToken                  string   `json:token`\n\t\tNamespace              string   `json:namespace`\n\t}{}\n\n\tworkspace := plugin.Workspace{}\n\tplugin.Param(\"workspace\", &workspace)\n\tplugin.Param(\"vargs\", &vargs)\n\tplugin.Parse()\n\n\t\/\/ Iterate over rcs and svcs\n\tfor _, rc := range vargs.ReplicationControllers {\n\t\tartifact, e := readArtifactFromFile(workspace, rc, vargs.ApiServer, vargs.Namespace)\n\t\tif b, _ := existsArtifact(artifact, token); b {\n\t\t\tdeleteArtifact(artifact, token)\n\t\t}\n\t\tcreateArtifact(artifact, vargs.Token)\n\t}\n\tfor _, rc := range vargs.Services {\n\t\tcreateArtifact(artifact, vargs.Token)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2009-2013 Phil Pennock\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage sks_spider\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\nvar (\n\tflSpiderStartHost    = flag.String(\"spider-start-host\", \"sks-peer.spodhuis.org\", \"Host to query to start things rolling\")\n\tflListen             = flag.String(\"listen\", \"localhost:8001\", \"port to listen on with web-server\")\n\tflMaintEmail         = flag.String(\"maint-email\", \"webmaster@spodhuis.org\", \"Email address of local maintainer\")\n\tflHostname           = flag.String(\"hostname\", \"sks.spodhuis.org\", \"Hostname to use in generated pages\")\n\tflMyStylesheet       = flag.String(\"stylesheet\", \"\/styles\/sks-peers.css\", \"CSS Style sheet to use\")\n\tflSksMembershipFile  = flag.String(\"sks-membership-file\", \"\/var\/sks\/membership\", \"SKS Membership file\")\n\tflSksPortRecon       = flag.Int(\"sks-port-recon\", 11370, \"Default SKS recon port\")\n\tflSksPortHkp         = flag.Int(\"sks-port-hkp\", 11371, \"Default SKS HKP port\")\n\tflTimeoutStatsFetch  = flag.Int(\"timeout-stats-fetch\", 30, \"Timeout for fetching stats from a remote server\")\n\tflCountriesZone      = flag.String(\"countries-zone\", \"zz.countries.nerd.dk.\", \"DNS zone for determining IP locations\")\n\tflKeysSanityMin      = flag.Int(\"keys-sanity-min\", 3100000, \"Minimum number of keys that's sane, or we're broken\")\n\tflKeysDailyJitter    = flag.Int(\"keys-daily-jitter\", 500, \"Max daily jitter in key count\")\n\tflScanIntervalSecs   = flag.Int(\"scan-interval\", 3600*8, \"How often to trigger a scan\")\n\tflScanIntervalJitter = flag.Int(\"scan-interval-jitter\", 120, \"Jitter in scan interval\")\n\tflLogFile            = flag.String(\"log-file\", \"sksdaemon.log\", \"Where to write logfiles\")\n\tflLogStdout          = flag.Bool(\"log-stdout\", false, \"Log to stdout instead of log-file\")\n\tflJsonDump           = flag.String(\"json-dump\", \"\", \"File to dump JSON of spidered hosts to\")\n\tflJsonLoad           = flag.String(\"json-load\", \"\", \"File to load JSON hosts from instead of spidering\")\n\tflJsonPersistPath    = flag.String(\"json-persist\", \"\", \"File to load at startup if exists, and write to at SIGUSR1\")\n\tflStartedFlagfile    = flag.String(\"started-file\", \"\", \"Create this file after started and running\")\n\tflHttpFetchTimeout   = flag.Duration(\"http-fetch-timeout\", 2*time.Minute, \"Timeout for HTTP fetch from SKS servers\")\n)\n\nvar serverHeadersNative = map[string]bool{\n\t\"sks_www\": true,\n\t\"gnuks\":   true,\n}\nvar defaultSoftware = \"SKS\"\n\n\/\/ People put dumb things in their membership files\nvar blacklistedQueryHosts = []string{\n\t\"localhost\",\n\t\"127.0.0.1\",\n\t\"::1\",\n}\n\nvar Log *log.Logger\n\nfunc setupLogging() {\n\tif *flLogStdout {\n\t\tLog = log.New(os.Stdout, \"\", log.LstdFlags|log.Lshortfile)\n\t\treturn\n\t}\n\tfh, err := os.OpenFile(*flLogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to open logfile \\\"%s\\\": %s\\n\", *flLogFile, err)\n\t\tos.Exit(1)\n\t}\n\tLog = log.New(fh, \"\", log.LstdFlags|log.Lshortfile)\n}\n\ntype PersistedHostInfo struct {\n\tHostMap      HostMap\n\tAliasMap     AliasMap\n\tIPCountryMap IPCountryMap\n\tSorted       []string\n\tDepthSorted  []string\n\tGraph        *HostGraph\n\tTimestamp    time.Time\n}\n\nvar (\n\tcurrentHostInfo    *PersistedHostInfo\n\tcurrentHostMapLock sync.RWMutex\n)\n\nfunc GetCurrentPersisted() *PersistedHostInfo {\n\tcurrentHostMapLock.RLock()\n\tdefer currentHostMapLock.RUnlock()\n\treturn currentHostInfo\n}\n\nfunc GetCurrentHosts() HostMap {\n\tcurrentHostMapLock.RLock()\n\tdefer currentHostMapLock.RUnlock()\n\tif currentHostInfo == nil {\n\t\treturn nil\n\t}\n\treturn currentHostInfo.HostMap\n}\n\nfunc GetCurrentHostlist() []string {\n\tcurrentHostMapLock.RLock()\n\tdefer currentHostMapLock.RUnlock()\n\tif currentHostInfo == nil {\n\t\treturn nil\n\t}\n\treturn currentHostInfo.Sorted\n}\n\nfunc SetCurrentPersisted(p *PersistedHostInfo) {\n\tp.Timestamp = time.Now()\n\tp.LogInformation()\n\tcurrentHostMapLock.Lock()\n\tdefer currentHostMapLock.Unlock()\n\tcurrentHostInfo = p\n}\n\nfunc normaliseMeshAndSet(spider *Spider, dumpJson bool) {\n\tgo func(s *Spider) {\n\t\tpersisted := GeneratePersistedInformation(s)\n\t\tSetCurrentPersisted(persisted)\n\t\tpersisted.UpdateStatsCounters(spider)\n\t\truntime.GC()\n\t\tif dumpJson && *flJsonDump != \"\" {\n\t\t\tLog.Printf(\"Saving JSON to \\\"%s\\\"\", *flJsonDump)\n\t\t\terr := persisted.HostMap.DumpJSONToFile(*flJsonDump)\n\t\t\tif err != nil {\n\t\t\t\tLog.Printf(\"Error saving JSON to \\\"%s\\\": %s\", *flJsonDump, err)\n\t\t\t\t\/\/ continue anyway\n\t\t\t}\n\t\t\truntime.GC()\n\t\t}\n\t}(spider)\n}\n\nfunc respiderPeriodically() {\n\tfor {\n\t\tvar delay time.Duration = time.Duration(*flScanIntervalSecs) * time.Second\n\t\tif *flScanIntervalJitter > 0 {\n\t\t\tjitter := rand.Int63n(int64(*flScanIntervalJitter) * int64(time.Second))\n\t\t\tjitter -= int64(*flScanIntervalJitter) * int64(time.Second) \/ 2\n\t\t\tdelay += time.Duration(jitter)\n\t\t}\n\t\tminDelay := time.Minute * 30\n\t\tif delay < minDelay {\n\t\t\tLog.Printf(\"respider period too low, capping %d up to %d\", delay, minDelay)\n\t\t\tdelay = minDelay\n\t\t}\n\t\tLog.Printf(\"Sleeping %s before next respider\", delay)\n\t\ttime.Sleep(delay)\n\t\tLog.Printf(\"Awoken!  Time to spider.\")\n\t\tvar spider *Spider\n\t\tfunc() {\n\t\t\tspider = StartSpider()\n\t\t\tdefer func(sp *Spider) {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tLog.Printf(\"Spider paniced: %s\", r)\n\t\t\t\t}\n\t\t\t\tsp.Terminate()\n\t\t\t}(spider)\n\t\t\tspider.AddHost(*flSpiderStartHost, 0)\n\t\t\tspider.Wait()\n\t\t}()\n\t\tnormaliseMeshAndSet(spider, false)\n\t}\n}\n\nvar httpServing sync.WaitGroup\n\nfunc startHttpServing() {\n\tLog.Printf(\"Will Listen on <%s>\", *flListen)\n\tserver := setupHttpServer(*flListen)\n\terr := server.ListenAndServe()\n\tif err != nil {\n\t\tLog.Printf(\"ListenAndServe(%s): %s\", *flListen, err)\n\t}\n\thttpServing.Done()\n}\n\nfunc shutdownRunner(ch <-chan os.Signal) {\n\tsignal, ok := <-ch\n\tif !ok {\n\t\treturn\n\t}\n\tpersisted := GetCurrentPersisted()\n\tif persisted != nil {\n\t\tLog.Printf(\"Received signal %s; saving JSON to \\\"%s\\\"\", signal, *flJsonPersistPath)\n\t\terr := persisted.HostMap.DumpJSONToFile(*flJsonPersistPath)\n\t\tif err != nil {\n\t\t\tLog.Printf(\"Error saving shutdown JSON: %s\", err)\n\t\t} else {\n\t\t\tLog.Print(\"Wrote shutdown JSON\")\n\t\t}\n\t}\n\thttpServing.Done()\n}\n\nfunc Main() {\n\tflag.Parse()\n\n\tif *flScanIntervalJitter < 0 {\n\t\tfmt.Fprintf(os.Stderr, \"Bad jitter, must be >= 0 [got: %d]\\n\", *flScanIntervalJitter)\n\t\tos.Exit(1)\n\t}\n\n\tsetupLogging()\n\tLog.Printf(\"started\")\n\n\thttpServing.Add(1)\n\tgo startHttpServing()\n\n\tif *flJsonPersistPath != \"\" {\n\t\tif _, err := os.Stat(*flJsonPersistPath); err == nil {\n\t\t\tif *flJsonLoad == \"\" {\n\t\t\t\t*flJsonLoad = *flJsonPersistPath\n\t\t\t}\n\t\t}\n\t}\n\n\tvar doneRespider bool\n\n\tif *flJsonLoad != \"\" {\n\t\tLog.Printf(\"Loading hosts from \\\"%s\\\" instead of spidering\", *flJsonLoad)\n\t\thostmap, err := LoadJSONFromFile(*flJsonLoad)\n\t\tif err != nil {\n\t\t\tLog.Fatalf(\"Failed to load JSON from \\\"%s\\\": %s\", *flJsonLoad, err)\n\t\t}\n\t\tLog.Printf(\"Loaded %d hosts from JSON\", len(hostmap))\n\t\thostnames := GenerateHostlistSorted(hostmap)\n\t\tcountryMap := GetFreshCountryForHostmap(hostmap)\n\t\taliasMap := GetAliasMapForHostmap(hostmap)\n\t\tSetCurrentPersisted(&PersistedHostInfo{\n\t\t\tHostMap:      hostmap,\n\t\t\tAliasMap:     aliasMap,\n\t\t\tIPCountryMap: countryMap,\n\t\t\tSorted:       hostnames,\n\t\t\tDepthSorted:  GenerateDepthSorted(hostmap),\n\t\t\tGraph:        GenerateGraph(hostnames, hostmap, aliasMap),\n\t\t})\n\t} else {\n\t\tspider := StartSpider()\n\t\tspider.AddHost(*flSpiderStartHost, 0)\n\t\tspider.Wait()\n\t\tspider.Terminate()\n\t\tLog.Printf(\"Spidering complete\")\n\t\tnormaliseMeshAndSet(spider, true)\n\t\tgo respiderPeriodically()\n\t\tdoneRespider = true\n\t}\n\n\tif *flJsonPersistPath != \"\" {\n\t\tsignalChan := make(chan os.Signal)\n\t\tif !doneRespider {\n\t\t\tgo respiderPeriodically()\n\t\t}\n\t\tgo shutdownRunner(signalChan)\n\t\t\/\/ Warning: Unix-specific, need to figure out how to make this signal-handling\n\t\t\/\/ replacable with another notification mechanism which is system-local and easily\n\t\t\/\/ triggered from an rc script\n\t\tsignal.Notify(signalChan, syscall.SIGUSR1)\n\t}\n\n\tif *flStartedFlagfile != \"\" {\n\t\tfh, err := os.Create(*flStartedFlagfile)\n\t\tif err == nil {\n\t\t\tfmt.Fprintf(fh, \"Started %s\\n\", os.Args[0])\n\t\t\terr = fh.Close()\n\t\t\tif err != nil {\n\t\t\t\tLog.Printf(\"Error in close(%s): %s\", *flStartedFlagfile, err)\n\t\t\t}\n\t\t} else {\n\t\t\tLog.Printf(\"Failed to create -started-file: %s\", err)\n\t\t}\n\t}\n\n\thttpServing.Wait()\n}\n<commit_msg>Clarify start-up log message.<commit_after>\/*\n   Copyright 2009-2013 Phil Pennock\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage sks_spider\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\nvar (\n\tflSpiderStartHost    = flag.String(\"spider-start-host\", \"sks-peer.spodhuis.org\", \"Host to query to start things rolling\")\n\tflListen             = flag.String(\"listen\", \"localhost:8001\", \"port to listen on with web-server\")\n\tflMaintEmail         = flag.String(\"maint-email\", \"webmaster@spodhuis.org\", \"Email address of local maintainer\")\n\tflHostname           = flag.String(\"hostname\", \"sks.spodhuis.org\", \"Hostname to use in generated pages\")\n\tflMyStylesheet       = flag.String(\"stylesheet\", \"\/styles\/sks-peers.css\", \"CSS Style sheet to use\")\n\tflSksMembershipFile  = flag.String(\"sks-membership-file\", \"\/var\/sks\/membership\", \"SKS Membership file\")\n\tflSksPortRecon       = flag.Int(\"sks-port-recon\", 11370, \"Default SKS recon port\")\n\tflSksPortHkp         = flag.Int(\"sks-port-hkp\", 11371, \"Default SKS HKP port\")\n\tflTimeoutStatsFetch  = flag.Int(\"timeout-stats-fetch\", 30, \"Timeout for fetching stats from a remote server\")\n\tflCountriesZone      = flag.String(\"countries-zone\", \"zz.countries.nerd.dk.\", \"DNS zone for determining IP locations\")\n\tflKeysSanityMin      = flag.Int(\"keys-sanity-min\", 3100000, \"Minimum number of keys that's sane, or we're broken\")\n\tflKeysDailyJitter    = flag.Int(\"keys-daily-jitter\", 500, \"Max daily jitter in key count\")\n\tflScanIntervalSecs   = flag.Int(\"scan-interval\", 3600*8, \"How often to trigger a scan\")\n\tflScanIntervalJitter = flag.Int(\"scan-interval-jitter\", 120, \"Jitter in scan interval\")\n\tflLogFile            = flag.String(\"log-file\", \"sksdaemon.log\", \"Where to write logfiles\")\n\tflLogStdout          = flag.Bool(\"log-stdout\", false, \"Log to stdout instead of log-file\")\n\tflJsonDump           = flag.String(\"json-dump\", \"\", \"File to dump JSON of spidered hosts to\")\n\tflJsonLoad           = flag.String(\"json-load\", \"\", \"File to load JSON hosts from instead of spidering\")\n\tflJsonPersistPath    = flag.String(\"json-persist\", \"\", \"File to load at startup if exists, and write to at SIGUSR1\")\n\tflStartedFlagfile    = flag.String(\"started-file\", \"\", \"Create this file after started and running\")\n\tflHttpFetchTimeout   = flag.Duration(\"http-fetch-timeout\", 2*time.Minute, \"Timeout for HTTP fetch from SKS servers\")\n)\n\nvar serverHeadersNative = map[string]bool{\n\t\"sks_www\": true,\n\t\"gnuks\":   true,\n}\nvar defaultSoftware = \"SKS\"\n\n\/\/ People put dumb things in their membership files\nvar blacklistedQueryHosts = []string{\n\t\"localhost\",\n\t\"127.0.0.1\",\n\t\"::1\",\n}\n\nvar Log *log.Logger\n\nfunc setupLogging() {\n\tif *flLogStdout {\n\t\tLog = log.New(os.Stdout, \"\", log.LstdFlags|log.Lshortfile)\n\t\treturn\n\t}\n\tfh, err := os.OpenFile(*flLogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Unable to open logfile \\\"%s\\\": %s\\n\", *flLogFile, err)\n\t\tos.Exit(1)\n\t}\n\tLog = log.New(fh, \"\", log.LstdFlags|log.Lshortfile)\n}\n\ntype PersistedHostInfo struct {\n\tHostMap      HostMap\n\tAliasMap     AliasMap\n\tIPCountryMap IPCountryMap\n\tSorted       []string\n\tDepthSorted  []string\n\tGraph        *HostGraph\n\tTimestamp    time.Time\n}\n\nvar (\n\tcurrentHostInfo    *PersistedHostInfo\n\tcurrentHostMapLock sync.RWMutex\n)\n\nfunc GetCurrentPersisted() *PersistedHostInfo {\n\tcurrentHostMapLock.RLock()\n\tdefer currentHostMapLock.RUnlock()\n\treturn currentHostInfo\n}\n\nfunc GetCurrentHosts() HostMap {\n\tcurrentHostMapLock.RLock()\n\tdefer currentHostMapLock.RUnlock()\n\tif currentHostInfo == nil {\n\t\treturn nil\n\t}\n\treturn currentHostInfo.HostMap\n}\n\nfunc GetCurrentHostlist() []string {\n\tcurrentHostMapLock.RLock()\n\tdefer currentHostMapLock.RUnlock()\n\tif currentHostInfo == nil {\n\t\treturn nil\n\t}\n\treturn currentHostInfo.Sorted\n}\n\nfunc SetCurrentPersisted(p *PersistedHostInfo) {\n\tp.Timestamp = time.Now()\n\tp.LogInformation()\n\tcurrentHostMapLock.Lock()\n\tdefer currentHostMapLock.Unlock()\n\tcurrentHostInfo = p\n}\n\nfunc normaliseMeshAndSet(spider *Spider, dumpJson bool) {\n\tgo func(s *Spider) {\n\t\tpersisted := GeneratePersistedInformation(s)\n\t\tSetCurrentPersisted(persisted)\n\t\tpersisted.UpdateStatsCounters(spider)\n\t\truntime.GC()\n\t\tif dumpJson && *flJsonDump != \"\" {\n\t\t\tLog.Printf(\"Saving JSON to \\\"%s\\\"\", *flJsonDump)\n\t\t\terr := persisted.HostMap.DumpJSONToFile(*flJsonDump)\n\t\t\tif err != nil {\n\t\t\t\tLog.Printf(\"Error saving JSON to \\\"%s\\\": %s\", *flJsonDump, err)\n\t\t\t\t\/\/ continue anyway\n\t\t\t}\n\t\t\truntime.GC()\n\t\t}\n\t}(spider)\n}\n\nfunc respiderPeriodically() {\n\tfor {\n\t\tvar delay time.Duration = time.Duration(*flScanIntervalSecs) * time.Second\n\t\tif *flScanIntervalJitter > 0 {\n\t\t\tjitter := rand.Int63n(int64(*flScanIntervalJitter) * int64(time.Second))\n\t\t\tjitter -= int64(*flScanIntervalJitter) * int64(time.Second) \/ 2\n\t\t\tdelay += time.Duration(jitter)\n\t\t}\n\t\tminDelay := time.Minute * 30\n\t\tif delay < minDelay {\n\t\t\tLog.Printf(\"respider period too low, capping %d up to %d\", delay, minDelay)\n\t\t\tdelay = minDelay\n\t\t}\n\t\tLog.Printf(\"Sleeping %s before next respider\", delay)\n\t\ttime.Sleep(delay)\n\t\tLog.Printf(\"Awoken!  Time to spider.\")\n\t\tvar spider *Spider\n\t\tfunc() {\n\t\t\tspider = StartSpider()\n\t\t\tdefer func(sp *Spider) {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tLog.Printf(\"Spider paniced: %s\", r)\n\t\t\t\t}\n\t\t\t\tsp.Terminate()\n\t\t\t}(spider)\n\t\t\tspider.AddHost(*flSpiderStartHost, 0)\n\t\t\tspider.Wait()\n\t\t}()\n\t\tnormaliseMeshAndSet(spider, false)\n\t}\n}\n\nvar httpServing sync.WaitGroup\n\nfunc startHttpServing() {\n\tLog.Printf(\"Will Listen on <%s>\", *flListen)\n\tserver := setupHttpServer(*flListen)\n\terr := server.ListenAndServe()\n\tif err != nil {\n\t\tLog.Printf(\"ListenAndServe(%s): %s\", *flListen, err)\n\t}\n\thttpServing.Done()\n}\n\nfunc shutdownRunner(ch <-chan os.Signal) {\n\tsignal, ok := <-ch\n\tif !ok {\n\t\treturn\n\t}\n\tpersisted := GetCurrentPersisted()\n\tif persisted != nil {\n\t\tLog.Printf(\"Received signal %s; saving JSON to \\\"%s\\\"\", signal, *flJsonPersistPath)\n\t\terr := persisted.HostMap.DumpJSONToFile(*flJsonPersistPath)\n\t\tif err != nil {\n\t\t\tLog.Printf(\"Error saving shutdown JSON: %s\", err)\n\t\t} else {\n\t\t\tLog.Print(\"Wrote shutdown JSON\")\n\t\t}\n\t}\n\thttpServing.Done()\n}\n\nfunc Main() {\n\tflag.Parse()\n\n\tif *flScanIntervalJitter < 0 {\n\t\tfmt.Fprintf(os.Stderr, \"Bad jitter, must be >= 0 [got: %d]\\n\", *flScanIntervalJitter)\n\t\tos.Exit(1)\n\t}\n\n\tsetupLogging()\n\tLog.Printf(\"started\")\n\n\thttpServing.Add(1)\n\tgo startHttpServing()\n\n\tif *flJsonPersistPath != \"\" {\n\t\tif _, err := os.Stat(*flJsonPersistPath); err == nil {\n\t\t\tif *flJsonLoad == \"\" {\n\t\t\t\t*flJsonLoad = *flJsonPersistPath\n\t\t\t}\n\t\t}\n\t}\n\n\tvar doneRespider bool\n\n\tif *flJsonLoad != \"\" {\n\t\tLog.Printf(\"Loading hosts from \\\"%s\\\" instead of spidering\", *flJsonLoad)\n\t\thostmap, err := LoadJSONFromFile(*flJsonLoad)\n\t\tif err != nil {\n\t\t\tLog.Fatalf(\"Failed to load JSON from \\\"%s\\\": %s\", *flJsonLoad, err)\n\t\t}\n\t\tLog.Printf(\"Loaded %d hosts from JSON\", len(hostmap))\n\t\thostnames := GenerateHostlistSorted(hostmap)\n\t\tcountryMap := GetFreshCountryForHostmap(hostmap)\n\t\taliasMap := GetAliasMapForHostmap(hostmap)\n\t\tSetCurrentPersisted(&PersistedHostInfo{\n\t\t\tHostMap:      hostmap,\n\t\t\tAliasMap:     aliasMap,\n\t\t\tIPCountryMap: countryMap,\n\t\t\tSorted:       hostnames,\n\t\t\tDepthSorted:  GenerateDepthSorted(hostmap),\n\t\t\tGraph:        GenerateGraph(hostnames, hostmap, aliasMap),\n\t\t})\n\t} else {\n\t\tspider := StartSpider()\n\t\tspider.AddHost(*flSpiderStartHost, 0)\n\t\tspider.Wait()\n\t\tspider.Terminate()\n\t\tLog.Printf(\"Start-up initial spidering complete\")\n\t\tnormaliseMeshAndSet(spider, true)\n\t\tgo respiderPeriodically()\n\t\tdoneRespider = true\n\t}\n\n\tif *flJsonPersistPath != \"\" {\n\t\tsignalChan := make(chan os.Signal)\n\t\tif !doneRespider {\n\t\t\tgo respiderPeriodically()\n\t\t}\n\t\tgo shutdownRunner(signalChan)\n\t\t\/\/ Warning: Unix-specific, need to figure out how to make this signal-handling\n\t\t\/\/ replacable with another notification mechanism which is system-local and easily\n\t\t\/\/ triggered from an rc script\n\t\tsignal.Notify(signalChan, syscall.SIGUSR1)\n\t}\n\n\tif *flStartedFlagfile != \"\" {\n\t\tfh, err := os.Create(*flStartedFlagfile)\n\t\tif err == nil {\n\t\t\tfmt.Fprintf(fh, \"Started %s\\n\", os.Args[0])\n\t\t\terr = fh.Close()\n\t\t\tif err != nil {\n\t\t\t\tLog.Printf(\"Error in close(%s): %s\", *flStartedFlagfile, err)\n\t\t\t}\n\t\t} else {\n\t\t\tLog.Printf(\"Failed to create -started-file: %s\", err)\n\t\t}\n\t}\n\n\thttpServing.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"path\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nvar address = flag.String(\"address\", \":8080\", \"address to listen on\")\nvar repositories = flag.String(\"repositories\", \"scraperwiki\/tang\", \"colon separated list of repositories to watch\")\nvar allowedPushers = flag.String(\"allowed-pushers\", \"drj11:pwaller\", \"list of people allowed\")\n\nvar allowedPushersSet = map[string]bool{}\n\nfunc init() {\n\tflag.Parse()\n\tfor _, who := range strings.Split(*allowedPushers, \":\") {\n\t\tallowedPushersSet[who] = true\n\t}\n}\n\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc main() {\n\n\tgo func() {\n\t\thttp.HandleFunc(\"\/hook\", handleHook)\n\t\tlog.Println(\"Listening on:\", *address)\n\t\tlog.Fatal(http.ListenAndServe(*address, nil))\n\t}()\n\n\tconfigureHooks()\n\n\tsig := make(chan os.Signal)\n\tsignal.Notify(sig, syscall.SIGHUP, syscall.SIGINT)\n\t<-sig\n\tsignal.Stop(sig)\n\n\tlog.Print(\"HUPPING!\")\n\n\texe, err := os.Readlink(\"\/proc\/self\/exe\")\n\tcheck(err)\n\n\terr = syscall.Exec(exe, os.Args, os.Environ())\n\tcheck(err)\n}\n\nfunc configureHooks() {\n\n\tif *repositories == \"\" {\n\t\treturn\n\t}\n\n\tgithub_user := os.Getenv(\"GITHUB_USER\")\n\tgithub_password := os.Getenv(\"GITHUB_PASSWORD\")\n\n\tjson := `{\n\t\"name\": \"web\",\n\t\"config\": {\"url\": \"http:\/\/services.scraperwiki.com\/hook\",\n\t\t\"content_type\": \"json\"},\n\t\"events\": [\"push\", \"issues\", \"issue_comment\",\n\t\t\"commit_comment\", \"create\", \"delete\",\n\t\t\"pull_request\", \"pull_request_review_comment\",\n\t\t\"gollum\", \"watch\", \"release\", \"fork\", \"member\",\n\t\t\"public\", \"team_add\", \"status\"],\n\t\"active\": true\n\t}`\n\n\tendpoint := \"https:\/\/\" + github_user + \":\" + github_password + \"@\" + \"api.github.com\"\n\n\trepos := strings.Split(*repositories, \":\")\n\n\tfor _, repo := range repos {\n\t\tlog.Print(\"Repo: \", repo)\n\n\t\tbuffer := strings.NewReader(json)\n\t\tresp, err := http.Post(endpoint+\"\/repos\/\"+repo+\"\/hooks\", \"application\/json\", buffer)\n\t\tcheck(err)\n\n\t\tlog.Println(\"Rate Limit:\", resp.Header[\"X-Ratelimit-Remaining\"][0])\n\n\t\tswitch resp.StatusCode {\n\t\tdefault:\n\t\t\tresponse, err := ioutil.ReadAll(resp.Body)\n\t\t\tcheck(err)\n\n\t\t\tlog.Print(string(response))\n\n\t\tcase 422:\n\t\t\tlog.Println(\"Already hooked for\", repo)\n\t\t}\n\t}\n\n}\n\ntype Repository struct {\n\tName         string `json:\"name\"`\n\tUrl          string `json:\"url\"`\n\tOrganization string `json:\"organization\"`\n}\n\ntype Pusher struct {\n\tName string `json:\"name\"`\n}\n\ntype PushEvent struct {\n\tRef        string     `json:\"ref\"`\n\tRepository Repository `json:\"repository\"`\n\tAfter      string     `json:\"after\"`\n\tPusher     Pusher     `json:\"pusher\"`\n}\n\nfunc handleEvent(eventType string, document []byte) (err error) {\n\n\tlog.Println(\"Incoming request:\", string(document))\n\n\tswitch eventType {\n\tcase \"push\":\n\t\tvar event PushEvent\n\t\terr = json.Unmarshal(document, &event)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\terr = eventPush(event)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\tdefault:\n\t\tlog.Println(\"Unhandled event:\", eventType)\n\t}\n\n\treturn\n}\n\nfunc handleHook(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"OK\\n\")\n\n\trequest, err := ioutil.ReadAll(r.Body)\n\tcheck(err)\n\n\tvar buf bytes.Buffer\n\tr.Header.Write(&buf)\n\tlog.Println(\"Incoming request headers: \", string(buf.Bytes()))\n\n\tbuf.Reset()\n\terr = json.Indent(&buf, request, \"\", \"  \")\n\tcheck(err)\n\n\teventType := r.Header[\"X-Github-Event\"][0]\n\tdata := buf.Bytes()\n\n\terr = handleEvent(eventType, data)\n\tcheck(err)\n}\n\nfunc Command(workdir, command string, args ...string) *exec.Cmd {\n\t\/\/ log.Printf(\"wd = %s cmd = %s, args = %q\", workdir, command, append([]string{}, args...))\n\tcmd := exec.Command(command, args...)\n\tcmd.Dir = workdir\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd\n}\n\nconst GIT_BASE_DIR = \"repo\"\n\nvar (\n\tErrEmptyRepoName         = errors.New(\"Empty repository name\")\n\tErrEmptyRepoOrganization = errors.New(\"Empty repository organization\")\n\tErrUserNotAllowed        = errors.New(\"User not in the allowed set\")\n)\n\n\/\/ Creates or updates a mirror of `url` at `git_dir` using `git clone --mirror`\nfunc gitLocalMirror(url, git_dir string) (err error) {\n\n\terr = os.MkdirAll(git_dir, 0777)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = Command(\".\", \"git\", \"clone\", \"-q\", \"--mirror\", url, git_dir).Run()\n\n\tif err == nil {\n\t\tlog.Println(\"Cloned\", url)\n\n\t} else if _, ok := err.(*exec.ExitError); ok {\n\n\t\t\/\/ Try \"git remote update\"\n\t\terr = Command(git_dir, \"git\", \"fetch\").Run()\n\n\t\tif err != nil {\n\t\t\t\/\/ git fetch where there is no update is exit status 1.\n\t\t\tif err.Error() != \"exit status 1\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tlog.Println(\"Remote updated\", url)\n\n\t} else {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc gitCheckout(git_dir, checkout_dir, ref string) (err error) {\n\n\terr = os.MkdirAll(path.Join(git_dir, checkout_dir), 0777)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlog.Println(\"Populating\", checkout_dir)\n\n\targs := []string{\"--work-tree\", checkout_dir, \"checkout\", ref, \".\"}\n\terr = Command(git_dir, \"git\", args...).Run()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc runTang(path string) (err error) {\n\treturn Command(path, \".\/tang.hook\").Run()\n}\n\nfunc eventPush(event PushEvent) (err error) {\n\tif event.Repository.Name == \"\" {\n\t\treturn ErrEmptyRepoName\n\t}\n\n\tif event.Repository.Organization == \"\" {\n\t\treturn ErrEmptyRepoOrganization\n\t}\n\n\tif _, ok := allowedPushersSet[event.Pusher.Name]; !ok {\n\t\tlog.Printf(\"Ignoring %q, not allowed\", event.Pusher.Name)\n\t\treturn ErrUserNotAllowed\n\t}\n\n\tref := event.Ref\n\turl := event.Repository.Url\n\tafter := event.After\n\n\tlog.Println(\"Push to\", url, ref, \"after\", after)\n\n\t\/\/ The name of the subdirectory where the git\n\t\/\/ mirror is (or will appear, if it hasn't been\n\t\/\/ cloned yet).\n\tgit_dir := path.Join(GIT_BASE_DIR, event.Repository.Organization,\n\t\tevent.Repository.Name)\n\terr = gitLocalMirror(url, git_dir)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcheckout_dir := path.Join(\"checkout\", after)\n\terr = gitCheckout(git_dir, checkout_dir, after)\n\tif err != nil {\n\t\treturn\n\t}\n\tlog.Println(\"Created\", checkout_dir)\n\n\terr = runTang(path.Join(git_dir, checkout_dir))\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n<commit_msg>Re-enable command logging<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"path\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nvar address = flag.String(\"address\", \":8080\", \"address to listen on\")\nvar repositories = flag.String(\"repositories\", \"scraperwiki\/tang\", \"colon separated list of repositories to watch\")\nvar allowedPushers = flag.String(\"allowed-pushers\", \"drj11:pwaller\", \"list of people allowed\")\n\nvar allowedPushersSet = map[string]bool{}\n\nfunc init() {\n\tflag.Parse()\n\tfor _, who := range strings.Split(*allowedPushers, \":\") {\n\t\tallowedPushersSet[who] = true\n\t}\n}\n\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc main() {\n\n\tgo func() {\n\t\thttp.HandleFunc(\"\/hook\", handleHook)\n\t\tlog.Println(\"Listening on:\", *address)\n\t\tlog.Fatal(http.ListenAndServe(*address, nil))\n\t}()\n\n\tconfigureHooks()\n\n\tsig := make(chan os.Signal)\n\tsignal.Notify(sig, syscall.SIGHUP, syscall.SIGINT)\n\t<-sig\n\tsignal.Stop(sig)\n\n\tlog.Print(\"HUPPING!\")\n\n\texe, err := os.Readlink(\"\/proc\/self\/exe\")\n\tcheck(err)\n\n\terr = syscall.Exec(exe, os.Args, os.Environ())\n\tcheck(err)\n}\n\nfunc configureHooks() {\n\n\tif *repositories == \"\" {\n\t\treturn\n\t}\n\n\tgithub_user := os.Getenv(\"GITHUB_USER\")\n\tgithub_password := os.Getenv(\"GITHUB_PASSWORD\")\n\n\tjson := `{\n\t\"name\": \"web\",\n\t\"config\": {\"url\": \"http:\/\/services.scraperwiki.com\/hook\",\n\t\t\"content_type\": \"json\"},\n\t\"events\": [\"push\", \"issues\", \"issue_comment\",\n\t\t\"commit_comment\", \"create\", \"delete\",\n\t\t\"pull_request\", \"pull_request_review_comment\",\n\t\t\"gollum\", \"watch\", \"release\", \"fork\", \"member\",\n\t\t\"public\", \"team_add\", \"status\"],\n\t\"active\": true\n\t}`\n\n\tendpoint := \"https:\/\/\" + github_user + \":\" + github_password + \"@\" + \"api.github.com\"\n\n\trepos := strings.Split(*repositories, \":\")\n\n\tfor _, repo := range repos {\n\t\tlog.Print(\"Repo: \", repo)\n\n\t\tbuffer := strings.NewReader(json)\n\t\tresp, err := http.Post(endpoint+\"\/repos\/\"+repo+\"\/hooks\", \"application\/json\", buffer)\n\t\tcheck(err)\n\n\t\tlog.Println(\"Rate Limit:\", resp.Header[\"X-Ratelimit-Remaining\"][0])\n\n\t\tswitch resp.StatusCode {\n\t\tdefault:\n\t\t\tresponse, err := ioutil.ReadAll(resp.Body)\n\t\t\tcheck(err)\n\n\t\t\tlog.Print(string(response))\n\n\t\tcase 422:\n\t\t\tlog.Println(\"Already hooked for\", repo)\n\t\t}\n\t}\n\n}\n\ntype Repository struct {\n\tName         string `json:\"name\"`\n\tUrl          string `json:\"url\"`\n\tOrganization string `json:\"organization\"`\n}\n\ntype Pusher struct {\n\tName string `json:\"name\"`\n}\n\ntype PushEvent struct {\n\tRef        string     `json:\"ref\"`\n\tRepository Repository `json:\"repository\"`\n\tAfter      string     `json:\"after\"`\n\tPusher     Pusher     `json:\"pusher\"`\n}\n\nfunc handleEvent(eventType string, document []byte) (err error) {\n\n\tlog.Println(\"Incoming request:\", string(document))\n\n\tswitch eventType {\n\tcase \"push\":\n\t\tvar event PushEvent\n\t\terr = json.Unmarshal(document, &event)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\terr = eventPush(event)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\tdefault:\n\t\tlog.Println(\"Unhandled event:\", eventType)\n\t}\n\n\treturn\n}\n\nfunc handleHook(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"OK\\n\")\n\n\trequest, err := ioutil.ReadAll(r.Body)\n\tcheck(err)\n\n\tvar buf bytes.Buffer\n\tr.Header.Write(&buf)\n\tlog.Println(\"Incoming request headers: \", string(buf.Bytes()))\n\n\tbuf.Reset()\n\terr = json.Indent(&buf, request, \"\", \"  \")\n\tcheck(err)\n\n\teventType := r.Header[\"X-Github-Event\"][0]\n\tdata := buf.Bytes()\n\n\terr = handleEvent(eventType, data)\n\tcheck(err)\n}\n\nfunc Command(workdir, command string, args ...string) *exec.Cmd {\n\tlog.Printf(\"wd = %s cmd = %s, args = %q\", workdir, command, append([]string{}, args...))\n\tcmd := exec.Command(command, args...)\n\tcmd.Dir = workdir\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\treturn cmd\n}\n\nconst GIT_BASE_DIR = \"repo\"\n\nvar (\n\tErrEmptyRepoName         = errors.New(\"Empty repository name\")\n\tErrEmptyRepoOrganization = errors.New(\"Empty repository organization\")\n\tErrUserNotAllowed        = errors.New(\"User not in the allowed set\")\n)\n\n\/\/ Creates or updates a mirror of `url` at `git_dir` using `git clone --mirror`\nfunc gitLocalMirror(url, git_dir string) (err error) {\n\n\terr = os.MkdirAll(git_dir, 0777)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = Command(\".\", \"git\", \"clone\", \"-q\", \"--mirror\", url, git_dir).Run()\n\n\tif err == nil {\n\t\tlog.Println(\"Cloned\", url)\n\n\t} else if _, ok := err.(*exec.ExitError); ok {\n\n\t\t\/\/ Try \"git remote update\"\n\t\terr = Command(git_dir, \"git\", \"fetch\").Run()\n\n\t\tif err != nil {\n\t\t\t\/\/ git fetch where there is no update is exit status 1.\n\t\t\tif err.Error() != \"exit status 1\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tlog.Println(\"Remote updated\", url)\n\n\t} else {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc gitCheckout(git_dir, checkout_dir, ref string) (err error) {\n\n\terr = os.MkdirAll(path.Join(git_dir, checkout_dir), 0777)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlog.Println(\"Populating\", checkout_dir)\n\n\targs := []string{\"--work-tree\", checkout_dir, \"checkout\", ref, \".\"}\n\terr = Command(git_dir, \"git\", args...).Run()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc runTang(path string) (err error) {\n\treturn Command(path, \".\/tang.hook\").Run()\n}\n\nfunc eventPush(event PushEvent) (err error) {\n\tif event.Repository.Name == \"\" {\n\t\treturn ErrEmptyRepoName\n\t}\n\n\tif event.Repository.Organization == \"\" {\n\t\treturn ErrEmptyRepoOrganization\n\t}\n\n\tif _, ok := allowedPushersSet[event.Pusher.Name]; !ok {\n\t\tlog.Printf(\"Ignoring %q, not allowed\", event.Pusher.Name)\n\t\treturn ErrUserNotAllowed\n\t}\n\n\tref := event.Ref\n\turl := event.Repository.Url\n\tafter := event.After\n\n\tlog.Println(\"Push to\", url, ref, \"after\", after)\n\n\t\/\/ The name of the subdirectory where the git\n\t\/\/ mirror is (or will appear, if it hasn't been\n\t\/\/ cloned yet).\n\tgit_dir := path.Join(GIT_BASE_DIR, event.Repository.Organization,\n\t\tevent.Repository.Name)\n\terr = gitLocalMirror(url, git_dir)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcheckout_dir := path.Join(\"checkout\", after)\n\terr = gitCheckout(git_dir, checkout_dir, after)\n\tif err != nil {\n\t\treturn\n\t}\n\tlog.Println(\"Created\", checkout_dir)\n\n\terr = runTang(path.Join(git_dir, checkout_dir))\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/cbednarski\/mkdeb\/deb\"\n)\n\nfunc main() {\n\targs := os.Args\n\n\tif len(args) < 2 {\n\t\tshowUsage()\n\t}\n\n\tswitch args[1] {\n\tcase \"archs\":\n\t\tshowArchs()\n\tcase \"build\":\n\t\tbuildCommand := flag.NewFlagSet(\"build\", flag.ExitOnError)\n\t\tversion := buildCommand.String(\"version\", \"1.0\", \"Package version\")\n\t\ttarget := buildCommand.String(\"target\", \"\", \"Target folder with generated filename\")\n\t\tbuildCommand.Parse(args[2:])\n\t\tbuild(checkConfig(buildCommand.Args()), *version, *target)\n\tcase \"init\":\n\t\tinitialize()\n\tcase \"validate\":\n\t\tcommandArgs := flag.Args()\n\n\t\tvalidate(checkConfig(commandArgs))\n\tdefault:\n\t\tshowUsage()\n\t}\n\tos.Exit(0)\n}\n\nfunc checkConfig(args []string) string {\n\tif len(args) < 1 {\n\t\tfmt.Printf(\"Missing config file\\n\")\n\t\tos.Exit(1)\n\t}\n\tif len(args) > 1 {\n\t\tfmt.Printf(\"Too many arguments\\n\")\n\t\tos.Exit(1)\n\t}\n\treturn args[0]\n}\n\n\/\/ getAbsPaths takes a relative path to a file and returns both the containing\n\/\/ directory and the absolute path to the file.\n\/\/\n\/\/ Example: cat -> \/bin \/bin\/cat\nfunc getAbsPaths(filename string) (string, string) {\n\tpath, err := filepath.Abs(filename)\n\tif err != nil {\n\t\tfmt.Printf(\"Can't find %q\", filename)\n\t\tos.Exit(1)\n\t}\n\tdir, _ := filepath.Split(path)\n\treturn dir, path\n}\n\nfunc showArchs() {\n\tfmt.Printf(\"mkdeb supported architectures: %s\\n\", strings.Join(deb.SupportedArchitectures(), \", \"))\n}\n\n\/\/ initialize creates a new mkdeb config. This function is not called init()\n\/\/ because that has a special meaning in Go.\nfunc initialize() {\n\t\/\/ Get abs path to PWD\n\tworkdir, err := os.Getwd()\n\thandleError(err)\n\tworkdir, err = filepath.Abs(workdir)\n\thandleError(err)\n\n\t\/\/ Get config file name\n\ttarget := path.Join(workdir, \"mkdeb.json\")\n\tif deb.FileExists(target) {\n\t\thandleError(fmt.Errorf(\"mkdir.json already exists in this directory\"))\n\t}\n\n\t\/\/ Create config file\n\tfile, err := os.Create(target)\n\thandleError(err)\n\tdefer file.Close()\n\n\t\/\/ Create config struct\n\tprojectName := filepath.Base(workdir)\n\tp := deb.DefaultPackageSpec()\n\tp.Package = projectName\n\tp.Maintainer = \"Your Name <you@example.com>\"\n\tp.Architecture = \"amd64\"\n\tp.Description = projectName + \" is an awsome project for...\"\n\tp.Homepage = \"https:\/\/www.example.com\/project\"\n\tp.Files = map[string]string{projectName: \"\/usr\/local\/bin\/\" + projectName}\n\n\tdata, err := json.MarshalIndent(p, \"\", \"  \")\n\thandleError(err)\n\n\t_, err = file.Write(data)\n\thandleError(err)\n}\n\nfunc validate(config string) {\n\t\/\/ Change to config path\n\tback, err := os.Getwd()\n\thandleError(err)\n\tworkdir, filename := getAbsPaths(config)\n\terr = os.Chdir(workdir)\n\thandleError(err)\n\tdefer os.Chdir(back)\n\n\t\/\/ Validate\n\tp, err := deb.NewPackageSpecFromFile(filename)\n\thandleError(err)\n\thandleError(p.Validate(false))\n}\n\nfunc build(config, version, target string) {\n\t\/\/ Change to config path\n\tback, err := os.Getwd()\n\thandleError(err)\n\n\t\/\/ Get the working directory to cd into and the absolute path to the file\n\tworkdir, abspath := getAbsPaths(config)\n\terr = os.Chdir(workdir)\n\thandleError(err)\n\tdefer os.Chdir(back)\n\n\tp, err := deb.NewPackageSpecFromFile(abspath)\n\thandleError(err)\n\n\t\/\/ Set version\n\tp.Version = version\n\n\t\/\/ Set target filename\n\tif target == \"\" {\n\t\ttarget = workdir\n\t} else {\n\t\tif !isDir(target) {\n\t\t\thandleError(fmt.Errorf(\"%q is not a directory\", target))\n\t\t}\n\t}\n\n\t\/\/ Validate\n\thandleError(p.Validate(true))\n\n\t\/\/ Build\n\thandleError(p.Build(target))\n\tfmt.Printf(\"Built package %s\\n\", path.Join(target, p.Filename()))\n}\n\nfunc isDir(path string) bool {\n\tinfo, err := os.Stat(path)\n\treturn err == nil && info.IsDir()\n}\n\nfunc handleError(err error) {\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc showUsage() {\n\tfmt.Print(usage)\n\tos.Exit(1)\n}\n\nconst usage = `ABOUT\n\n  mkdeb is a tool for building debian packages\n\n  Report issues or get updates from https:\/\/github.com\/cbednarski\/mkdeb\n\nCOMMANDS\n\n  build       Build a package based on the specified config file\n  init        Create a new mkdeb config file in the current directory\n  archs       List supported CPU architectures\n  validate    Validate your config file\n\nBUILD COMMAND\n\n  mkdeb build -version=1.2.0 config.json\n\n  Options:\n\n    -version (required) Package version\n\n    -target (optional) output artifact to this path\n\n    -targetDir (optional) output artifact to this folder, use generated filename\n\n  By default the build artifact\n\n  The build command will change to the directory where the config file is\n  located, so paths should always be specified relative to the config file.\n\nPACKAGING CONFIGURATION\n\n  Required Fields\n\n  - package: The name of your package\n  - version: Must adhere to debian version syntax.\n  - architecture: CPU arch for your binaries, or \"all\"\n  - maintainer: Your Name <email@example.com>\n  - description: Brief explanation of your package\n\n  Optional Fields\n\n  - depends: Other packages you depend on. E.g: \"python\" or \"curl (>= 7.0.0)\"\n  - conflicts: Packages your package are not compatible with\n  - breaks: Packages your package breaks\n  - replaces: Packages your package replaces\n  - homepage: URL to your project homepage or source repository, if you have one\n\n  For more details on how to specify various config options, refer to the\n  debian package specification:\n\n  - https:\/\/www.debian.org\/doc\/debian-policy\/ch-controlfields.html\n  - https:\/\/www.debian.org\/doc\/manuals\/debian-faq\/ch-pkg_basics.en.html\n\nPACKAGING LAYOUT\n\n  autoPath\n\n  mkdeb will automatically include any files deb-pkg, the default autoPath\n  directory. For example, the following files will be automatically included and\n  installed to their corresponding paths:\n\n    deb-pkg\/etc\/mysqld\/my.conf  -> \/etc\/mysqld\/my.conf\n    deb-pkg\/usr\/bin\/mysqld      -> \/usr\/bin\/mysqld\n\n  You can override this behavior by setting autoPath to - (dash character) and \/\n  or by using the Files map to create a custom source -> dest mapping.\n\n  Control Scripts\n\n  Control scripts allow you to take action at various stages of your package's\n  lifecycle. These are commonly used to create users, start or stop services, or\n  perform cleanup.\n\n  By default mkdeb will use any of these files if they are present in deb-pkg:\n\n  - preinst\n  - postinst\n  - prerm\n  - postrm\n\n  You can override this behavior by setting the relevant fields in your config.\n\nBUILD OPTIONS\n\n  The following options change how mkdeb runs when building packages.\n\n  - tempPath: Controls where intermediate files are written during the build.\n    This defaults to the system temp directory.\n\n  - upgradeConfigs: Indicates whether apt should replace files under \/etc when\n    installing a new package version. By default these files are not upgraded.\n\n  - preserveSymlinks: By default contents of symlink targets are copied. This\n    option writes symlinks to the archive instead.\n\nLICENSE\n\n  Copyright 2016 Chris Bednarski <banzaimonkey@gmail.com>, and others\n\n  Portions of mkdeb are licensed under the MIT, BSD and Go Licenses. Please\n  refer to the project source for full license text and details.\n\n  https:\/\/github.com\/cbednarski\/mkdeb\n`\n<commit_msg>Removed unused param<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/cbednarski\/mkdeb\/deb\"\n)\n\nfunc main() {\n\targs := os.Args\n\n\tif len(args) < 2 {\n\t\tshowUsage()\n\t}\n\n\tswitch args[1] {\n\tcase \"archs\":\n\t\tshowArchs()\n\tcase \"build\":\n\t\tbuildCommand := flag.NewFlagSet(\"build\", flag.ExitOnError)\n\t\tversion := buildCommand.String(\"version\", \"1.0\", \"Package version\")\n\t\ttarget := buildCommand.String(\"target\", \"\", \"Target folder with generated filename\")\n\t\tbuildCommand.Parse(args[2:])\n\t\tbuild(checkConfig(buildCommand.Args()), *version, *target)\n\tcase \"init\":\n\t\tinitialize()\n\tcase \"validate\":\n\t\tcommandArgs := flag.Args()\n\n\t\tvalidate(checkConfig(commandArgs))\n\tdefault:\n\t\tshowUsage()\n\t}\n\tos.Exit(0)\n}\n\nfunc checkConfig(args []string) string {\n\tif len(args) < 1 {\n\t\tfmt.Printf(\"Missing config file\\n\")\n\t\tos.Exit(1)\n\t}\n\tif len(args) > 1 {\n\t\tfmt.Printf(\"Too many arguments\\n\")\n\t\tos.Exit(1)\n\t}\n\treturn args[0]\n}\n\n\/\/ getAbsPaths takes a relative path to a file and returns both the containing\n\/\/ directory and the absolute path to the file.\n\/\/\n\/\/ Example: cat -> \/bin \/bin\/cat\nfunc getAbsPaths(filename string) (string, string) {\n\tpath, err := filepath.Abs(filename)\n\tif err != nil {\n\t\tfmt.Printf(\"Can't find %q\", filename)\n\t\tos.Exit(1)\n\t}\n\tdir, _ := filepath.Split(path)\n\treturn dir, path\n}\n\nfunc showArchs() {\n\tfmt.Printf(\"mkdeb supported architectures: %s\\n\", strings.Join(deb.SupportedArchitectures(), \", \"))\n}\n\n\/\/ initialize creates a new mkdeb config. This function is not called init()\n\/\/ because that has a special meaning in Go.\nfunc initialize() {\n\t\/\/ Get abs path to PWD\n\tworkdir, err := os.Getwd()\n\thandleError(err)\n\tworkdir, err = filepath.Abs(workdir)\n\thandleError(err)\n\n\t\/\/ Get config file name\n\ttarget := path.Join(workdir, \"mkdeb.json\")\n\tif deb.FileExists(target) {\n\t\thandleError(fmt.Errorf(\"mkdir.json already exists in this directory\"))\n\t}\n\n\t\/\/ Create config file\n\tfile, err := os.Create(target)\n\thandleError(err)\n\tdefer file.Close()\n\n\t\/\/ Create config struct\n\tprojectName := filepath.Base(workdir)\n\tp := deb.DefaultPackageSpec()\n\tp.Package = projectName\n\tp.Maintainer = \"Your Name <you@example.com>\"\n\tp.Architecture = \"amd64\"\n\tp.Description = projectName + \" is an awsome project for...\"\n\tp.Homepage = \"https:\/\/www.example.com\/project\"\n\tp.Files = map[string]string{projectName: \"\/usr\/local\/bin\/\" + projectName}\n\n\tdata, err := json.MarshalIndent(p, \"\", \"  \")\n\thandleError(err)\n\n\t_, err = file.Write(data)\n\thandleError(err)\n}\n\nfunc validate(config string) {\n\t\/\/ Change to config path\n\tback, err := os.Getwd()\n\thandleError(err)\n\tworkdir, filename := getAbsPaths(config)\n\terr = os.Chdir(workdir)\n\thandleError(err)\n\tdefer os.Chdir(back)\n\n\t\/\/ Validate\n\tp, err := deb.NewPackageSpecFromFile(filename)\n\thandleError(err)\n\thandleError(p.Validate(false))\n}\n\nfunc build(config, version, target string) {\n\t\/\/ Change to config path\n\tback, err := os.Getwd()\n\thandleError(err)\n\n\t\/\/ Get the working directory to cd into and the absolute path to the file\n\tworkdir, abspath := getAbsPaths(config)\n\terr = os.Chdir(workdir)\n\thandleError(err)\n\tdefer os.Chdir(back)\n\n\tp, err := deb.NewPackageSpecFromFile(abspath)\n\thandleError(err)\n\n\t\/\/ Set version\n\tp.Version = version\n\n\t\/\/ Set target filename\n\tif target == \"\" {\n\t\ttarget = workdir\n\t} else {\n\t\tif !isDir(target) {\n\t\t\thandleError(fmt.Errorf(\"%q is not a directory\", target))\n\t\t}\n\t}\n\n\t\/\/ Validate\n\thandleError(p.Validate(true))\n\n\t\/\/ Build\n\thandleError(p.Build(target))\n\tfmt.Printf(\"Built package %s\\n\", path.Join(target, p.Filename()))\n}\n\nfunc isDir(path string) bool {\n\tinfo, err := os.Stat(path)\n\treturn err == nil && info.IsDir()\n}\n\nfunc handleError(err error) {\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc showUsage() {\n\tfmt.Print(usage)\n\tos.Exit(1)\n}\n\nconst usage = `ABOUT\n\n  mkdeb is a tool for building debian packages\n\n  Report issues or get updates from https:\/\/github.com\/cbednarski\/mkdeb\n\nCOMMANDS\n\n  build       Build a package based on the specified config file\n  init        Create a new mkdeb config file in the current directory\n  archs       List supported CPU architectures\n  validate    Validate your config file\n\nBUILD COMMAND\n\n  mkdeb build -version=1.2.0 config.json\n\n  Options:\n\n    -version (required) Package version\n\n    -target (optional) output artifact to this path\n\n  By default the build artifact\n\n  The build command will change to the directory where the config file is\n  located, so paths should always be specified relative to the config file.\n\nPACKAGING CONFIGURATION\n\n  Required Fields\n\n  - package: The name of your package\n  - version: Must adhere to debian version syntax.\n  - architecture: CPU arch for your binaries, or \"all\"\n  - maintainer: Your Name <email@example.com>\n  - description: Brief explanation of your package\n\n  Optional Fields\n\n  - depends: Other packages you depend on. E.g: \"python\" or \"curl (>= 7.0.0)\"\n  - conflicts: Packages your package are not compatible with\n  - breaks: Packages your package breaks\n  - replaces: Packages your package replaces\n  - homepage: URL to your project homepage or source repository, if you have one\n\n  For more details on how to specify various config options, refer to the\n  debian package specification:\n\n  - https:\/\/www.debian.org\/doc\/debian-policy\/ch-controlfields.html\n  - https:\/\/www.debian.org\/doc\/manuals\/debian-faq\/ch-pkg_basics.en.html\n\nPACKAGING LAYOUT\n\n  autoPath\n\n  mkdeb will automatically include any files deb-pkg, the default autoPath\n  directory. For example, the following files will be automatically included and\n  installed to their corresponding paths:\n\n    deb-pkg\/etc\/mysqld\/my.conf  -> \/etc\/mysqld\/my.conf\n    deb-pkg\/usr\/bin\/mysqld      -> \/usr\/bin\/mysqld\n\n  You can override this behavior by setting autoPath to - (dash character) and \/\n  or by using the Files map to create a custom source -> dest mapping.\n\n  Control Scripts\n\n  Control scripts allow you to take action at various stages of your package's\n  lifecycle. These are commonly used to create users, start or stop services, or\n  perform cleanup.\n\n  By default mkdeb will use any of these files if they are present in deb-pkg:\n\n  - preinst\n  - postinst\n  - prerm\n  - postrm\n\n  You can override this behavior by setting the relevant fields in your config.\n\nBUILD OPTIONS\n\n  The following options change how mkdeb runs when building packages.\n\n  - tempPath: Controls where intermediate files are written during the build.\n    This defaults to the system temp directory.\n\n  - upgradeConfigs: Indicates whether apt should replace files under \/etc when\n    installing a new package version. By default these files are not upgraded.\n\n  - preserveSymlinks: By default contents of symlink targets are copied. This\n    option writes symlinks to the archive instead.\n\nLICENSE\n\n  Copyright 2016 Chris Bednarski <banzaimonkey@gmail.com>, and others\n\n  Portions of mkdeb are licensed under the MIT, BSD and Go Licenses. Please\n  refer to the project source for full license text and details.\n\n  https:\/\/github.com\/cbednarski\/mkdeb\n`\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"syscall\"\n\t\"encoding\/json\"\n\n\t\"github.com\/mailgun\/kafka-pixy\/Godeps\/_workspace\/src\/github.com\/mailgun\/log\"\n\t\"github.com\/mailgun\/kafka-pixy\/pixy\"\n)\n\nconst (\n\tdefaultBrokers    = \"localhost:9092\"\n\tdefaultUnixAddr   = \"\/var\/run\/kafka-pixy.sock\"\n\tdefaultPIDFile    = \"\/var\/run\/kafka-pixy.pid\"\n\tdefaultLoggingCfg = `[{\"name\": \"console\", \"severity\": \"info\"}]`\n)\n\nvar (\n\tserviceCfg     pixy.ServiceCfg\n\tpidFile        string\n\tloggingJSONCfg string\n)\n\nfunc init() {\n\tflag.StringVar(&serviceCfg.UnixAddr, \"unixAddr\", defaultUnixAddr,\n\t\t\"Unix domain socket address that the HTTP API should listen on\")\n\tflag.StringVar(&serviceCfg.TCPAddr, \"tcpAddr\", \"\",\n\t\t\"TCP address that the HTTP API should listen on\")\n\tb := flag.String(\"brokers\", defaultBrokers, \"Comma separated list of brokers\")\n\tflag.StringVar(&pidFile, \"pidFile\", defaultPIDFile, \"Path to the PID file\")\n\tflag.StringVar(&loggingJSONCfg, \"logging\", defaultLoggingCfg, \"Logging configuration\")\n\tflag.Parse()\n\tserviceCfg.BrokerAddrs = strings.Split(*b, \",\")\n}\n\nfunc main() {\n\tif err := initLogging(); err != nil {\n\t\tfmt.Printf(\"Failed to initialize logger, cause=(%v)\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tif err := writePID(pidFile); err != nil {\n\t\tlog.Errorf(\"Failed to write PID file, cause=(%v)\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlog.Infof(\"Starting with config: %+v\", serviceCfg)\n\tsvc, err := pixy.SpawnService(&serviceCfg)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to start service, cause=(%v)\", err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Spawn OS signal listener to ensure graceful stop.\n\tosSigCh := make(chan os.Signal)\n\tsignal.Notify(osSigCh, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)\n\tgo func() {\n\t\t<-osSigCh\n\t\tsvc.Stop()\n\t}()\n\n\tsvc.Wait4Stop()\n}\n\nfunc initLogging() error {\n\tvar loggingCfg []log.Config\n\tif err := json.Unmarshal([]byte(loggingJSONCfg), &loggingCfg); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse logger config, cause=(%v)\", err)\n\t}\n\tif err := log.InitWithConfig(loggingCfg...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc writePID(path string) error {\n\tpid := os.Getpid()\n\treturn ioutil.WriteFile(path, []byte(fmt.Sprint(pid)), 0644)\n}\n<commit_msg>Clean up abandoned unix socket file (fixes #4)<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"syscall\"\n\t\"encoding\/json\"\n\n\t\"github.com\/mailgun\/kafka-pixy\/Godeps\/_workspace\/src\/github.com\/mailgun\/log\"\n\t\"github.com\/mailgun\/kafka-pixy\/pixy\"\n)\n\nconst (\n\tdefaultBrokers    = \"localhost:9092\"\n\tdefaultUnixAddr   = \"\/var\/run\/kafka-pixy.sock\"\n\tdefaultPIDFile    = \"\/var\/run\/kafka-pixy.pid\"\n\tdefaultLoggingCfg = `[{\"name\": \"console\", \"severity\": \"info\"}]`\n)\n\nvar (\n\tserviceCfg     pixy.ServiceCfg\n\tpidFile        string\n\tloggingJSONCfg string\n)\n\nfunc init() {\n\tflag.StringVar(&serviceCfg.UnixAddr, \"unixAddr\", defaultUnixAddr,\n\t\t\"Unix domain socket address that the HTTP API should listen on\")\n\tflag.StringVar(&serviceCfg.TCPAddr, \"tcpAddr\", \"\",\n\t\t\"TCP address that the HTTP API should listen on\")\n\tb := flag.String(\"brokers\", defaultBrokers, \"Comma separated list of brokers\")\n\tflag.StringVar(&pidFile, \"pidFile\", defaultPIDFile, \"Path to the PID file\")\n\tflag.StringVar(&loggingJSONCfg, \"logging\", defaultLoggingCfg, \"Logging configuration\")\n\tflag.Parse()\n\tserviceCfg.BrokerAddrs = strings.Split(*b, \",\")\n}\n\nfunc main() {\n\tif err := initLogging(); err != nil {\n\t\tfmt.Printf(\"Failed to initialize logger, cause=(%v)\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tif err := writePID(pidFile); err != nil {\n\t\tlog.Errorf(\"Failed to write PID file, cause=(%v)\", err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Clean up the unix domain socket file in case we failed to clean up on\n\t\/\/ shutdown the last time. Otherwise the service won't be able to listen\n\t\/\/ on this address and the service will terminated immediately.\n\tif err := os.Remove(serviceCfg.UnixAddr); err != nil && err.(*os.PathError).Err != os.ErrNotExist {\n\t\tlog.Errorf(\"Cannot remove %s\", serviceCfg.UnixAddr)\n\t}\n\n\tlog.Infof(\"Starting with config: %+v\", serviceCfg)\n\tsvc, err := pixy.SpawnService(&serviceCfg)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to start service, cause=(%v)\", err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Spawn OS signal listener to ensure graceful stop.\n\tosSigCh := make(chan os.Signal)\n\tsignal.Notify(osSigCh, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)\n\tgo func() {\n\t\t<-osSigCh\n\t\tsvc.Stop()\n\t}()\n\n\tsvc.Wait4Stop()\n}\n\nfunc initLogging() error {\n\tvar loggingCfg []log.Config\n\tif err := json.Unmarshal([]byte(loggingJSONCfg), &loggingCfg); err != nil {\n\t\treturn fmt.Errorf(\"failed to parse logger config, cause=(%v)\", err)\n\t}\n\tif err := log.InitWithConfig(loggingCfg...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc writePID(path string) error {\n\tpid := os.Getpid()\n\treturn ioutil.WriteFile(path, []byte(fmt.Sprint(pid)), 0644)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"github.com\/akwick\/sqinco\/sqlInjections\"\n\nfunc main() {\n\t\/\/ 10er examples\n\tsqlInjections.UnprepStmtArg()\n\tsqlInjections.UnprepStmtConst()\n\tsqlInjections.UnprepStmtConstDecl()\n\tsqlInjections.UnprepStmtConstDeclUntypedString()\n\tsqlInjections.UnprepStmtConstDeclTypedString()\n\tsqlInjections.UnprepStmtConstIsConstRetVal()\n\tsqlInjections.UnprepStmtConstIsConstRetValFlowSens()\n\tsqlInjections.UnprepStmtConstDeclChangeAfterQueryFunCall()\n\n\t\/\/ 20er examples\n\tsqlInjections.UnprepStmtConstDeclUntypedStringQueryRow()\n\tsqlInjections.UnprepStmtDeclStringQueryRow()\n\tsqlInjections.UnprepStmtFormatedString()\n\tsqlInjections.UnprepStmtConstDeclSmallKeywords()\n\tsqlInjections.WrappedFunc()\n\tsqlInjections.NotQuerry()\n}\n<commit_msg>Update called functions<commit_after>package main\n\nimport \"github.com\/akwick\/sqinco\/sqlInjections\"\n\nfunc main() {\n\t\/\/ 10er examples\n\tsqlInjections.UnprepStmtConst()\n\tsqlInjections.UnprepStmtConstDecl()\n\tsqlInjections.UnprepStmtConstDeclUntypedString()\n\tsqlInjections.UnprepStmtConstDeclTypedString()\n\tsqlInjections.UnprepStmtConstIsConstRetVal()\n\tsqlInjections.UnprepStmtConstIsConstRetValFlowSens()\n\tsqlInjections.UnprepStmtConstDeclChangeAfterQueryFunCall()\n\n\t\/\/ 20er examples\n\tsqlInjections.UnprepStmtConstDeclUntypedStringQueryRow()\n\tsqlInjections.UnprepStmtDeclStringQueryRow()\n\tsqlInjections.UnprepStmtFormatedString()\n\tsqlInjections.UnprepStmtConstDeclSmallKeywords()\n\tsqlInjections.WrappedFunc()\n\tsqlInjections.NotQuerry()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n)\n\nfunc writeStringToFile(filePath, content string) error {\n\tif filePath == \"\" {\n\t\treturn errors.New(\"No path provided!\")\n\t}\n\n\tfile, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t_, err = file.Write([]byte(content))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc transformIfSpecialEnv(envKeyValuePair EnvKeyValuePair) (EnvKeyValuePair, error) {\n\tif envKeyValuePair.Key == \"__INPUT_FILE__\" {\n\t\tlog.Println(\" (i) Special key: __INPUT_FILE__\")\n\t\tusr, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn EnvKeyValuePair{}, err\n\t\t}\n\t\ttmpFolderPath := filepath.Join(usr.HomeDir, \"bitrise\/tmp\")\n\t\tif err := os.MkdirAll(tmpFolderPath, 0777); err != nil {\n\t\t\treturn EnvKeyValuePair{}, err\n\t\t}\n\t\tstepInputStoreFilePath := filepath.Join(tmpFolderPath, \"step_input_store\")\n\t\tif err := writeStringToFile(stepInputStoreFilePath, envKeyValuePair.Value); err != nil {\n\t\t\treturn EnvKeyValuePair{}, err\n\t\t}\n\t\tenvKeyValuePair.Value = stepInputStoreFilePath\n\t}\n\treturn envKeyValuePair, nil\n}\n\nfunc filterEnvironmentKeyValuePairs(envKeyValuePair []EnvKeyValuePair) []EnvKeyValuePair {\n\tfilteredPairs := []EnvKeyValuePair{}\n\n\tfor _, aPair := range envKeyValuePair {\n\t\tif aPair.Key == \"\" {\n\t\t\tlog.Println(\"[i] Key is missing - won't add it to the environment. Value: \", aPair.Value)\n\t\t\tcontinue\n\t\t}\n\t\tif aPair.Value == \"\" {\n\t\t\tlog.Printf(\"[i] Value is missing - won't add it to the environment (default value will be used by the Step) (Key: %s)\\n\", aPair.Key)\n\t\t\tcontinue\n\t\t}\n\n\t\taPair, err := transformIfSpecialEnv(aPair)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[i] Failed to convert special Env - ignored (Key: %s | Value: %s)\\n\", aPair.Key, aPair.Value)\n\t\t\tcontinue\n\t\t}\n\t\tfilteredPairs = append(filteredPairs, aPair)\n\t}\n\n\treturn filteredPairs\n}\n\nfunc runStepWithAdditionalEnvironment(commandPath string, envsToAdd []EnvKeyValuePair) error {\n\tcommandDir := filepath.Dir(commandPath)\n\tcommandName := filepath.Base(commandPath)\n\tc := exec.Command(\"bash\", commandName)\n\n\tenvLength := len(envsToAdd)\n\tif envLength > 0 {\n\t\tenvStringPairs := make([]string, len(envsToAdd), len(envsToAdd))\n\t\tfor idx, aEnvPair := range envsToAdd {\n\t\t\tenvStringPairs[idx] = aEnvPair.ToStringWithExpand()\n\t\t}\n\t\tc.Env = append(os.Environ(), envStringPairs...)\n\t}\n\tc.Dir = commandDir\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\tif err := c.Run(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc runCommandWithArgs(command string, cmdArgs ...string) error {\n\tc := exec.Command(command, cmdArgs...)\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\tif err := c.Run(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc perform(encodedStepPath, encodedCombinedStepEnvs string) error {\n\tif encodedStepPath == \"\" {\n\t\treturn errors.New(\"No Step Path provided\")\n\t}\n\n\tdecodedStepCommand, err := decodeSingleValue(encodedStepPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdecodedStepCommand = ExpandPath(decodedStepCommand)\n\tdecodedStepEnvPairs, err := decodeCombinedEnvs(encodedCombinedStepEnvs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfilteredEnvPairs := filterEnvironmentKeyValuePairs(decodedStepEnvPairs)\n\n\tfmt.Println(\"Perform: \", decodedStepCommand, filteredEnvPairs)\n\treturn runStepWithAdditionalEnvironment(decodedStepCommand, filteredEnvPairs)\n}\n\nfunc usage() {\n\tfmt.Fprintf(os.Stderr, \"Usage: %s [FLAGS]\\n\", os.Args[0])\n\tflag.PrintDefaults()\n}\n\nfunc main() {\n\tvar (\n\t\tflagEncodedStepPath         = flag.String(\"steppath\", \"\", \"[REQUIRED] step's path (base64 encoded)\")\n\t\tflagEncodedCombinedStepEnvs = flag.String(\"stepenvs\", \"\", \"[REQUIRED] step's encoded-combined environment key-value pairs\")\n\t)\n\n\tflag.Usage = usage\n\tflag.Parse()\n\n\tif *flagEncodedStepPath == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tif err := perform(*flagEncodedStepPath, *flagEncodedCombinedStepEnvs); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>expand the environment with the processed environments, so subsequent envs can use previous ones, even for the same step<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n)\n\nfunc writeStringToFile(filePath, content string) error {\n\tif filePath == \"\" {\n\t\treturn errors.New(\"No path provided!\")\n\t}\n\n\tfile, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t_, err = file.Write([]byte(content))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc transformIfSpecialEnv(envKeyValuePair EnvKeyValuePair) (EnvKeyValuePair, error) {\n\tif envKeyValuePair.Key == \"__INPUT_FILE__\" {\n\t\tlog.Println(\" (i) Special key: __INPUT_FILE__\")\n\t\tusr, err := user.Current()\n\t\tif err != nil {\n\t\t\treturn EnvKeyValuePair{}, err\n\t\t}\n\t\ttmpFolderPath := filepath.Join(usr.HomeDir, \"bitrise\/tmp\")\n\t\tif err := os.MkdirAll(tmpFolderPath, 0777); err != nil {\n\t\t\treturn EnvKeyValuePair{}, err\n\t\t}\n\t\tstepInputStoreFilePath := filepath.Join(tmpFolderPath, \"step_input_store\")\n\t\tif err := writeStringToFile(stepInputStoreFilePath, envKeyValuePair.Value); err != nil {\n\t\t\treturn EnvKeyValuePair{}, err\n\t\t}\n\t\tenvKeyValuePair.Value = stepInputStoreFilePath\n\t}\n\treturn envKeyValuePair, nil\n}\n\nfunc filterEnvironmentKeyValuePairs(envKeyValuePair []EnvKeyValuePair) []EnvKeyValuePair {\n\tfilteredPairs := []EnvKeyValuePair{}\n\n\tfor _, aPair := range envKeyValuePair {\n\t\tif aPair.Key == \"\" {\n\t\t\tlog.Println(\"[i] Key is missing - won't add it to the environment. Value: \", aPair.Value)\n\t\t\tcontinue\n\t\t}\n\t\tif aPair.Value == \"\" {\n\t\t\tlog.Printf(\"[i] Value is missing - won't add it to the environment (default value will be used by the Step) (Key: %s)\\n\", aPair.Key)\n\t\t\tcontinue\n\t\t}\n\n\t\taPair, err := transformIfSpecialEnv(aPair)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[i] Failed to convert special Env - ignored (Key: %s | Value: %s)\\n\", aPair.Key, aPair.Value)\n\t\t\tcontinue\n\t\t}\n\t\tfilteredPairs = append(filteredPairs, aPair)\n\t}\n\n\treturn filteredPairs\n}\n\nfunc runStepWithAdditionalEnvironment(commandPath string, envsToAdd []EnvKeyValuePair) error {\n\tcommandDir := filepath.Dir(commandPath)\n\tcommandName := filepath.Base(commandPath)\n\tc := exec.Command(\"bash\", commandName)\n\n\tenvLength := len(envsToAdd)\n\tif envLength > 0 {\n\t\tenvStringPairs := make([]string, len(envsToAdd), len(envsToAdd))\n\t\tfor idx, aEnvPair := range envsToAdd {\n\t\t\tenvStringPairs[idx] = aEnvPair.ToStringWithExpand()\n\t\t\t\/\/ set as env, so subsequent expansions can use it\n\t\t\tif err := os.Setenv(aEnvPair.Key, os.ExpandEnv(aEnvPair.Value)); err != nil {\n\t\t\t\tfmt.Println(\" [!] Failed to set Env: \", aEnvPair)\n\t\t\t}\n\t\t}\n\t\tc.Env = append(os.Environ(), envStringPairs...)\n\t}\n\tc.Dir = commandDir\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\tif err := c.Run(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc runCommandWithArgs(command string, cmdArgs ...string) error {\n\tc := exec.Command(command, cmdArgs...)\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stderr\n\tif err := c.Run(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc perform(encodedStepPath, encodedCombinedStepEnvs string) error {\n\tif encodedStepPath == \"\" {\n\t\treturn errors.New(\"No Step Path provided\")\n\t}\n\n\tdecodedStepCommand, err := decodeSingleValue(encodedStepPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdecodedStepCommand = ExpandPath(decodedStepCommand)\n\tdecodedStepEnvPairs, err := decodeCombinedEnvs(encodedCombinedStepEnvs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfilteredEnvPairs := filterEnvironmentKeyValuePairs(decodedStepEnvPairs)\n\n\tfmt.Println(\"Perform: \", decodedStepCommand, filteredEnvPairs)\n\treturn runStepWithAdditionalEnvironment(decodedStepCommand, filteredEnvPairs)\n}\n\nfunc usage() {\n\tfmt.Fprintf(os.Stderr, \"Usage: %s [FLAGS]\\n\", os.Args[0])\n\tflag.PrintDefaults()\n}\n\nfunc main() {\n\tvar (\n\t\tflagEncodedStepPath         = flag.String(\"steppath\", \"\", \"[REQUIRED] step's path (base64 encoded)\")\n\t\tflagEncodedCombinedStepEnvs = flag.String(\"stepenvs\", \"\", \"[REQUIRED] step's encoded-combined environment key-value pairs\")\n\t)\n\n\tflag.Usage = usage\n\tflag.Parse()\n\n\tif *flagEncodedStepPath == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tif err := perform(*flagEncodedStepPath, *flagEncodedCombinedStepEnvs); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/gogap\/errors\"\n\t\"github.com\/gogap\/logs\"\n\t\"github.com\/gogap\/spirit\"\n\t\"github.com\/spirit-contrib\/inlet_http\"\n)\n\nconst (\n\tSPIRIT_NAME    = \"inlet_http_api\"\n\tMETHOD_OPTIONS = \"OPTIONS\"\n)\n\nvar (\n\tconf InletHTTPAPIConfig\n\n\tproxyAPI = make(map[string]bool)\n)\n\nfunc main() {\n\tconf = LoadConfig(\".\/conf\/inlet_http_api.conf\")\n\n\tgraphProvider := NewAPIGraphProvider(API_HEADER, conf.Address, conf.Graphs)\n\n\thttpConf := inlet_http.Config{Address: conf.HTTP.Address, Domain: conf.HTTP.CookiesDomain}\n\n\tinletHTTP := inlet_http.NewInletHTTP(\n\t\tinlet_http.SetHTTPConfig(httpConf),\n\t\tinlet_http.SetGraphProvider(graphProvider),\n\t\tinlet_http.SetResponseHandler(responseHandle),\n\t\tinlet_http.SetErrorResponseHandler(errorResponseHandler),\n\t\tinlet_http.SetRequestDecoder(requestDecoder),\n\t\tinlet_http.SetRequestPayloadHook(requestPayloadHook))\n\n\thttpAPISpirit := spirit.NewClassicSpirit(SPIRIT_NAME, \"an http inlet with POST request\", \"1.0.0\")\n\thttpAPIComponent := spirit.NewBaseComponent(SPIRIT_NAME)\n\n\thttpAPIComponent.RegisterHandler(\"callback\", inletHTTP.CallBack)\n\thttpAPIComponent.RegisterHandler(\"error\", inletHTTP.Error)\n\n\thttpAPISpirit.Hosting(httpAPIComponent).Build()\n\n\tinletHTTP.Requester().SetMessageSenderFactory(httpAPISpirit.GetMessageSenderFactory())\n\n\tgo inletHTTP.Run(optionHandle)\n\thttpAPISpirit.Run()\n}\n\ntype APIResponse struct {\n\tCode           uint64      `json:\"code\"`\n\tErrorId        string      `json:\"error_id,omitempty\"`\n\tErrorNamespace string      `json:\"error_namespace,omitempty\"`\n\tMessage        string      `json:\"message\"`\n\tResult         interface{} `json:\"result\"`\n}\n\nfunc requestDecoder(data []byte) (ret map[string]interface{}, err error) {\n\tstr := strings.TrimSpace(string(data))\n\tif str != \"\" {\n\t\tret = make(map[string]interface{})\n\t\terr = json.Unmarshal(data, &ret)\n\t}\n\treturn\n}\n\nfunc requestPayloadHook(r *http.Request, body []byte, payload *spirit.Payload) {\n\tapiName := r.Header.Get(conf.HTTP.APIHeader)\n\n\tif apiName == \"\" {\n\t\treturn\n\t}\n\n\tif proxyAPI != nil {\n\t\tif isProxy, _ := proxyAPI[apiName]; isProxy {\n\t\t\tnewPayload := spirit.Payload{}\n\n\t\t\tif e := newPayload.UnSerialize(body); e != nil {\n\t\t\t\tlogs.Error(e)\n\t\t\t} else {\n\t\t\t\tpayload.CopyFrom(&newPayload)\n\t\t\t}\n\t\t}\n\t}\n\n\tpayload.SetContext(conf.HTTP.APIHeader, apiName)\n}\n\nfunc optionHandle(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == METHOD_OPTIONS {\n\t\twriteAccessHeaders(w, r)\n\t\twriteBasicHeaders(w, r)\n\t\tw.Write([]byte(\"\"))\n\t}\n}\n\nfunc errorResponseHandler(err error, w http.ResponseWriter, r *http.Request) {\n\tvar resp APIResponse\n\tif errCode, ok := err.(errors.ErrCode); ok {\n\t\tresp = APIResponse{\n\t\t\tCode:           errCode.Code(),\n\t\t\tErrorId:        errCode.Id(),\n\t\t\tErrorNamespace: errCode.Namespace(),\n\t\t\tMessage:        errCode.Error(),\n\t\t\tResult:         nil,\n\t\t}\n\t} else {\n\t\tresp = APIResponse{\n\t\t\tCode:           500,\n\t\t\tErrorId:        \"\",\n\t\t\tErrorNamespace: INLET_HTTP_API_ERR_NS,\n\t\t\tMessage:        err.Error(),\n\t\t\tResult:         nil,\n\t\t}\n\t}\n\n\tstatusCode := http.StatusInternalServerError\n\n\tif ERR_API_GRAPH_IS_NOT_EXIST.IsEqual(err) {\n\t\tstatusCode = http.StatusNotFound\n\t} else if inlet_http.ERR_REQUEST_TIMEOUT.IsEqual(err) {\n\t\tstatusCode = http.StatusRequestTimeout\n\t}\n\n\twriteErrorResponse(&resp, w, r, statusCode)\n}\n\nfunc responseHandle(payload spirit.Payload, w http.ResponseWriter, r *http.Request) {\n\tif payload.IsCorrect() {\n\t\tcorrectHandle(payload, w, r)\n\t} else {\n\t\terrorHandle(payload, w, r)\n\t}\n}\n\nfunc correctHandle(payload spirit.Payload, w http.ResponseWriter, r *http.Request) {\n\tresp := APIResponse{\n\t\tCode:   payload.Error().Code,\n\t\tResult: payload.GetContent(),\n\t}\n\twriteResponse(&resp, w, r)\n}\n\nfunc errorHandle(payload spirit.Payload, w http.ResponseWriter, r *http.Request) {\n\tresp := APIResponse{\n\t\tCode:           payload.Error().Code,\n\t\tErrorId:        payload.Error().Id,\n\t\tErrorNamespace: payload.Error().Namespace,\n\t\tMessage:        payload.Error().Message,\n\t\tResult:         nil,\n\t}\n\n\twriteErrorResponse(&resp, w, r, http.StatusInternalServerError)\n}\n\nfunc writeResponse(v interface{}, w http.ResponseWriter, r *http.Request) {\n\tif data, e := json.Marshal(v); e != nil {\n\t\terr := ERR_MARSHAL_STRUCT_ERROR.New(errors.Params{\"err\": e})\n\t\tlogs.Error(err)\n\t\tif _, ok := v.(error); !ok {\n\t\t\twriteResponse(&err, w, r)\n\t\t}\n\t} else {\n\t\twriteAccessHeaders(w, r)\n\t\twriteBasicHeaders(w, r)\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.Write(data)\n\t}\n}\n\nfunc writeErrorResponse(v interface{}, w http.ResponseWriter, r *http.Request, code int) {\n\tif data, e := json.Marshal(v); e != nil {\n\t\terr := ERR_MARSHAL_STRUCT_ERROR.New(errors.Params{\"err\": e})\n\t\tlogs.Error(err)\n\t\tif _, ok := v.(error); !ok {\n\t\t\twriteErrorResponse(&err, w, r, code)\n\t\t}\n\t} else {\n\t\twriteAccessHeaders(w, r)\n\t\twriteBasicHeaders(w, r)\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\thttp.Error(w, string(data), code)\n\t}\n}\n\nfunc writeAccessHeaders(w http.ResponseWriter, r *http.Request) {\n\trefer := r.Referer()\n\tif refer == \"\" {\n\t\trefer = r.Header.Get(\"Origin\")\n\t}\n\n\tif refProtocol, refDomain, isAllowd := conf.HTTP.ParseOrigin(refer); isAllowd {\n\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\torigin := refProtocol + \":\/\/\" + refDomain\n\t\tif origin == \":\/\/\" ||\n\t\t\trefProtocol == \"chrome-extension\" { \/\/issue of post man, chrome limit.\n\t\t\torigin = \"*\"\n\t\t}\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t}\n\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", conf.HTTP.allowHeaders())\n}\n\nfunc writeBasicHeaders(w http.ResponseWriter, r *http.Request) {\n\tfor key, value := range conf.HTTP.responseHeaders {\n\t\tw.Header().Set(key, value)\n\t}\n}\n<commit_msg>fix responses error to status ok<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/gogap\/errors\"\n\t\"github.com\/gogap\/logs\"\n\t\"github.com\/gogap\/spirit\"\n\t\"github.com\/spirit-contrib\/inlet_http\"\n)\n\nconst (\n\tSPIRIT_NAME    = \"inlet_http_api\"\n\tMETHOD_OPTIONS = \"OPTIONS\"\n)\n\nvar (\n\tconf InletHTTPAPIConfig\n\n\tproxyAPI = make(map[string]bool)\n)\n\nfunc main() {\n\tconf = LoadConfig(\".\/conf\/inlet_http_api.conf\")\n\n\tgraphProvider := NewAPIGraphProvider(API_HEADER, conf.Address, conf.Graphs)\n\n\thttpConf := inlet_http.Config{Address: conf.HTTP.Address, Domain: conf.HTTP.CookiesDomain}\n\n\tinletHTTP := inlet_http.NewInletHTTP(\n\t\tinlet_http.SetHTTPConfig(httpConf),\n\t\tinlet_http.SetGraphProvider(graphProvider),\n\t\tinlet_http.SetResponseHandler(responseHandle),\n\t\tinlet_http.SetErrorResponseHandler(errorResponseHandler),\n\t\tinlet_http.SetRequestDecoder(requestDecoder),\n\t\tinlet_http.SetRequestPayloadHook(requestPayloadHook))\n\n\thttpAPISpirit := spirit.NewClassicSpirit(SPIRIT_NAME, \"an http inlet with POST request\", \"1.0.0\")\n\thttpAPIComponent := spirit.NewBaseComponent(SPIRIT_NAME)\n\n\thttpAPIComponent.RegisterHandler(\"callback\", inletHTTP.CallBack)\n\thttpAPIComponent.RegisterHandler(\"error\", inletHTTP.Error)\n\n\thttpAPISpirit.Hosting(httpAPIComponent).Build()\n\n\tinletHTTP.Requester().SetMessageSenderFactory(httpAPISpirit.GetMessageSenderFactory())\n\n\tgo inletHTTP.Run(optionHandle)\n\thttpAPISpirit.Run()\n}\n\ntype APIResponse struct {\n\tCode           uint64      `json:\"code\"`\n\tErrorId        string      `json:\"error_id,omitempty\"`\n\tErrorNamespace string      `json:\"error_namespace,omitempty\"`\n\tMessage        string      `json:\"message\"`\n\tResult         interface{} `json:\"result\"`\n}\n\nfunc requestDecoder(data []byte) (ret map[string]interface{}, err error) {\n\tstr := strings.TrimSpace(string(data))\n\tif str != \"\" {\n\t\tret = make(map[string]interface{})\n\t\terr = json.Unmarshal(data, &ret)\n\t}\n\treturn\n}\n\nfunc requestPayloadHook(r *http.Request, body []byte, payload *spirit.Payload) {\n\tapiName := r.Header.Get(conf.HTTP.APIHeader)\n\n\tif apiName == \"\" {\n\t\treturn\n\t}\n\n\tif proxyAPI != nil {\n\t\tif isProxy, _ := proxyAPI[apiName]; isProxy {\n\t\t\tnewPayload := spirit.Payload{}\n\n\t\t\tif e := newPayload.UnSerialize(body); e != nil {\n\t\t\t\tlogs.Error(e)\n\t\t\t} else {\n\t\t\t\tpayload.CopyFrom(&newPayload)\n\t\t\t}\n\t\t}\n\t}\n\n\tpayload.SetContext(conf.HTTP.APIHeader, apiName)\n}\n\nfunc optionHandle(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == METHOD_OPTIONS {\n\t\twriteAccessHeaders(w, r)\n\t\twriteBasicHeaders(w, r)\n\t\tw.Write([]byte(\"\"))\n\t}\n}\n\nfunc errorResponseHandler(err error, w http.ResponseWriter, r *http.Request) {\n\tvar resp APIResponse\n\tif errCode, ok := err.(errors.ErrCode); ok {\n\t\tresp = APIResponse{\n\t\t\tCode:           errCode.Code(),\n\t\t\tErrorId:        errCode.Id(),\n\t\t\tErrorNamespace: errCode.Namespace(),\n\t\t\tMessage:        errCode.Error(),\n\t\t\tResult:         nil,\n\t\t}\n\t} else {\n\t\tresp = APIResponse{\n\t\t\tCode:           500,\n\t\t\tErrorId:        \"\",\n\t\t\tErrorNamespace: INLET_HTTP_API_ERR_NS,\n\t\t\tMessage:        err.Error(),\n\t\t\tResult:         nil,\n\t\t}\n\t}\n\n\tstatusCode := http.StatusInternalServerError\n\n\tif ERR_API_GRAPH_IS_NOT_EXIST.IsEqual(err) {\n\t\tstatusCode = http.StatusNotFound\n\t} else if inlet_http.ERR_REQUEST_TIMEOUT.IsEqual(err) {\n\t\tstatusCode = http.StatusRequestTimeout\n\t}\n\n\twriteErrorResponse(&resp, w, r, statusCode)\n}\n\nfunc responseHandle(payload spirit.Payload, w http.ResponseWriter, r *http.Request) {\n\tif payload.IsCorrect() {\n\t\tcorrectHandle(payload, w, r)\n\t} else {\n\t\terrorHandle(payload, w, r)\n\t}\n}\n\nfunc correctHandle(payload spirit.Payload, w http.ResponseWriter, r *http.Request) {\n\tresp := APIResponse{\n\t\tCode:   payload.Error().Code,\n\t\tResult: payload.GetContent(),\n\t}\n\twriteResponse(&resp, w, r)\n}\n\nfunc errorHandle(payload spirit.Payload, w http.ResponseWriter, r *http.Request) {\n\tresp := APIResponse{\n\t\tCode:           payload.Error().Code,\n\t\tErrorId:        payload.Error().Id,\n\t\tErrorNamespace: payload.Error().Namespace,\n\t\tMessage:        payload.Error().Message,\n\t\tResult:         nil,\n\t}\n\n\twriteErrorResponse(&resp, w, r, http.StatusOK)\n}\n\nfunc writeResponse(v interface{}, w http.ResponseWriter, r *http.Request) {\n\tif data, e := json.Marshal(v); e != nil {\n\t\terr := ERR_MARSHAL_STRUCT_ERROR.New(errors.Params{\"err\": e})\n\t\tlogs.Error(err)\n\t\tif _, ok := v.(error); !ok {\n\t\t\twriteResponse(&err, w, r)\n\t\t}\n\t} else {\n\t\twriteAccessHeaders(w, r)\n\t\twriteBasicHeaders(w, r)\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.Write(data)\n\t}\n}\n\nfunc writeErrorResponse(v interface{}, w http.ResponseWriter, r *http.Request, code int) {\n\tif data, e := json.Marshal(v); e != nil {\n\t\terr := ERR_MARSHAL_STRUCT_ERROR.New(errors.Params{\"err\": e})\n\t\tlogs.Error(err)\n\t\tif _, ok := v.(error); !ok {\n\t\t\twriteErrorResponse(&err, w, r, code)\n\t\t}\n\t} else {\n\t\twriteAccessHeaders(w, r)\n\t\twriteBasicHeaders(w, r)\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\thttp.Error(w, string(data), code)\n\t}\n}\n\nfunc writeAccessHeaders(w http.ResponseWriter, r *http.Request) {\n\trefer := r.Referer()\n\tif refer == \"\" {\n\t\trefer = r.Header.Get(\"Origin\")\n\t}\n\n\tif refProtocol, refDomain, isAllowd := conf.HTTP.ParseOrigin(refer); isAllowd {\n\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\torigin := refProtocol + \":\/\/\" + refDomain\n\t\tif origin == \":\/\/\" ||\n\t\t\trefProtocol == \"chrome-extension\" { \/\/issue of post man, chrome limit.\n\t\t\torigin = \"*\"\n\t\t}\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", origin)\n\t}\n\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", conf.HTTP.allowHeaders())\n}\n\nfunc writeBasicHeaders(w http.ResponseWriter, r *http.Request) {\n\tfor key, value := range conf.HTTP.responseHeaders {\n\t\tw.Header().Set(key, value)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/Lukasa\/GoBot\/irc\"\n\t\"github.com\/Lukasa\/GoBot\/sck\"\n\t\"github.com\/Lukasa\/GoBot\/struc\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"strconv\"\n)\n\n\/\/ main is the entry point for GoBot.\nfunc main() {\n\tsendChan := make(chan []byte)\n\trecvChan := make(chan []byte)\n\targs := parseArgs()\n\tusername := genUsername()\n\tserverStr := args[0]\n\n\t\/\/ Parse this string into an IRC server.\n\tserver, err := struc.NewIRCServerFromHostnamePort(serverStr)\n\tif err != nil {\n\t\tfmt.Printf(\"Could not parse %v. Exiting.\", serverStr)\n\t\tos.Exit(1)\n\t}\n\n\t_, err = sck.Connect(server, sendChan, recvChan)\n\tif err != nil {\n\t\tfmt.Printf(\"Could not connect to %v:%v. Exiting.\", server.IPAddr, server.Port)\n\t\tos.Exit(2)\n\t}\n\n\t\/\/ Prepare the botscripts. For this simple case we'll log everything, so add a YesFilter and a logger to stdout.\n\twriteAction := irc.LogAction(os.Stdout)\n\tregexFilter, _ := irc.RegexFilterFromRegex(\"!m (.*)\")\n\tprintAction := irc.PrintAction(\"You're doing truly excellent work, ${1}!\")\n\tlogscript := irc.BuildBotscript([]irc.Filter{irc.YesFilter}, []irc.Action{writeAction})\n\tprintscript := irc.BuildBotscript([]irc.Filter{regexFilter}, []irc.Action{printAction})\n\n\t\/\/ We need a few extra channels. One from the parsing loop to the dispatch loop, one from the goroutines to the\n\t\/\/ unparsing loop.\n\tparsingOut := make(chan *struc.IRCMessage)\n\tunparsingIn := make(chan *struc.IRCMessage)\n\n\t\/\/ Set the loops going.\n\tgo irc.ParsingLoop(recvChan, parsingOut)\n\tgo irc.UnParsingLoop(unparsingIn, sendChan)\n\n\t\/\/ Send a test registration just to prove we can.\n\tnick := []byte(fmt.Sprintf(\"NICK %v\\r\\n\", username))\n\tsendChan <- nick\n\n\tuser := []byte(fmt.Sprintf(\"USER %v 1 1 1 :%v\\r\\n\", username, username))\n\tsendChan <- user\n\n\tjoin := []byte(\"JOIN #python-requests\\r\\n\")\n\tsendChan <- join\n\n\t\/\/ Run forever, dispatching messages.\n\terr = irc.DispatchMessages(parsingOut, unparsingIn, []irc.Botscript{logscript, printscript})\n\n\treturn\n}\n\n\/\/ parseArgs parses the command line arguments and flags. Currently this is the world's most boring function, but\n\/\/ I'll extend it as I go.\nfunc parseArgs() []string {\n\tflag.Parse()\n\targs := flag.Args()\n\treturn args\n}\n\nfunc genUsername() string {\n\tbase := \"GoBot-\"\n\tuniqId := strconv.Itoa(int(rand.Int31()))\n\treturn base + uniqId\n}\n<commit_msg>Refactor the login.<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/Lukasa\/GoBot\/irc\"\n\t\"github.com\/Lukasa\/GoBot\/sck\"\n\t\"github.com\/Lukasa\/GoBot\/struc\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"strconv\"\n)\n\n\/\/ main is the entry point for GoBot.\nfunc main() {\n\tsendChan := make(chan []byte)\n\trecvChan := make(chan []byte)\n\targs := parseArgs()\n\tusername := genUsername()\n\tserverStr := args[0]\n\n\t\/\/ Parse this string into an IRC server.\n\tserver, err := struc.NewIRCServerFromHostnamePort(serverStr)\n\tif err != nil {\n\t\tfmt.Printf(\"Could not parse %v. Exiting.\", serverStr)\n\t\tos.Exit(1)\n\t}\n\n\t_, err = sck.Connect(server, sendChan, recvChan)\n\tif err != nil {\n\t\tfmt.Printf(\"Could not connect to %v:%v. Exiting.\", server.IPAddr, server.Port)\n\t\tos.Exit(2)\n\t}\n\n\t\/\/ Prepare the botscripts. For this simple case we'll log everything, so add a YesFilter and a logger to stdout.\n\twriteAction := irc.LogAction(os.Stdout)\n\tregexFilter, _ := irc.RegexFilterFromRegex(\"!m (.*)\")\n\tprintAction := irc.PrintAction(\"You're doing truly excellent work, ${1}!\")\n\tlogscript := irc.BuildBotscript([]irc.Filter{irc.YesFilter}, []irc.Action{writeAction})\n\tprintscript := irc.BuildBotscript([]irc.Filter{regexFilter}, []irc.Action{printAction})\n\n\t\/\/ We need a few extra channels. One from the parsing loop to the dispatch loop, one from the goroutines to the\n\t\/\/ unparsing loop.\n\tparsingOut := make(chan *struc.IRCMessage)\n\tunparsingIn := make(chan *struc.IRCMessage)\n\n\t\/\/ Set the loops going.\n\tgo irc.ParsingLoop(recvChan, parsingOut)\n\tgo irc.UnParsingLoop(unparsingIn, sendChan)\n\n\t\/\/ Send a test registration just to prove we can.\n\tlogin(username, \"#python-requests\", sendChan)\n\n\t\/\/ Run forever, dispatching messages.\n\terr = irc.DispatchMessages(parsingOut, unparsingIn, []irc.Botscript{logscript, printscript})\n\n\treturn\n}\n\n\/\/ parseArgs parses the command line arguments and flags. Currently this is the world's most boring function, but\n\/\/ I'll extend it as I go.\nfunc parseArgs() []string {\n\tflag.Parse()\n\targs := flag.Args()\n\treturn args\n}\n\nfunc genUsername() string {\n\tbase := \"GoBot-\"\n\tuniqId := strconv.Itoa(int(rand.Int31()))\n\treturn base + uniqId\n}\n\n\/\/ Send the messages needed to login\nfunc login(username, channel string, out chan []byte) {\n\tnick := []byte(fmt.Sprintf(\"NICK %v\\r\\n\", username))\n\tout <- nick\n\n\tuser := []byte(fmt.Sprintf(\"USER %v 1 1 1 :%v\\r\\n\", username, username))\n\tout <- user\n\n\tjoin := []byte(fmt.Sprintf(\"JOIN %v\\r\\n\", channel))\n\tout <- join\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"syscall\"\n\t\"text\/template\"\n\t\"time\"\n)\n\nvar version = \"master\"\n\ntype request struct {\n\tcommand   string\n\temails    string\n\ttimeout   time.Duration\n\ttransport string\n\tverbose   bool\n}\n\ntype result struct {\n\trequest request\n\tstdout  bytes.Buffer\n\tstderr  bytes.Buffer\n\tstarted time.Time\n\tstopped time.Time\n\tkilled  bool\n\tcode    int\n}\n\nfunc main() {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tcommand := flag.String(\"c\", \"\", `Command to run, like '-c \"ls\"'`)\n\temails := flag.String(\"e\", \"\", `Emails to send reports when the command fails or exceeds timeout, like '-e \"john@example.com,doe@example.com\"'`)\n\ttimeout := flag.Duration(\"t\", 1*time.Hour, `Timeout for the command, like \"-t 2h\", \"-t 2m\", or \"-t 30s\". After the timeout, the command is killed, defaults to 1 hour \"-t 3600\"`)\n\ttransport := flag.String(\"p\", \"auto\", `Transport to use, like \"-p auto\", \"-p mail\", \"-p sendmail\"`)\n\tverbose := flag.Bool(\"v\", false, \"Enable sending emails even if command is successful\")\n\tflag.Parse()\n\n\treq := request{\n\t\tcommand:   *command,\n\t\temails:    *emails,\n\t\ttimeout:   *timeout,\n\t\ttransport: *transport,\n\t\tverbose:   *verbose,\n\t}\n\n\tr := execCmd(wd, req)\n\n\tif r.killed || r.code != 0 || r.request.verbose {\n\t\tif r.request.emails == \"\" {\n\t\t\tfmt.Println(r.render().String())\n\t\t} else {\n\t\t\tr.sendEmail()\n\t\t}\n\t}\n}\n\nfunc execCmd(path string, req request) result {\n\tr := result{\n\t\tstarted: time.Now(),\n\t\trequest: req,\n\t}\n\tcmd := exec.Command(\"sh\", \"-c\", req.command)\n\tcmd.Dir = path\n\tcmd.Stdout = &r.stdout\n\tcmd.Stderr = &r.stderr\n\tcmd.Env = []string{fmt.Sprintf(\"HOME=%s\", os.Getenv(\"HOME\"))}\n\tif err := cmd.Start(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\ttimer := time.NewTimer(req.timeout)\n\tgo func(timer *time.Timer, cmd *exec.Cmd) {\n\t\tfor _ = range timer.C {\n\t\t\tr.killed = true\n\t\t\tif err := cmd.Process.Kill(); err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}(timer, cmd)\n\n\tif err := cmd.Wait(); err != nil {\n\t\t\/\/ unsuccessful exit code?\n\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\tr.code = exitError.Sys().(syscall.WaitStatus).ExitStatus()\n\t\t} else {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\tr.stopped = time.Now()\n\n\treturn r\n}\n\nfunc (r *result) sendEmail() {\n\temails := strings.Split(r.request.emails, \",\")\n\tpaths := make(map[string]string)\n\n\tif r.request.transport == \"auto\" {\n\t\tpaths = map[string]string{\"sendmail\": \"sendmail\", \"\/usr\/sbin\/sendmail\": \"sendmail\", \"mail\": \"mail\", \"\/usr\/bin\/mail\": \"mail\"}\n\t} else if r.request.transport == \"sendmail\" {\n\t\tpaths = map[string]string{\"sendmail\": \"sendmail\", \"\/usr\/sbin\/sendmail\": \"sendmail\"}\n\t} else if r.request.transport == \"mail\" {\n\t\tpaths = map[string]string{\"mail\": \"mail\", \"\/usr\/bin\/mail\": \"mail\"}\n\t} else {\n\t\tfmt.Printf(\"Unsupported transport %s\\n\", r.request.transport)\n\t\tos.Exit(1)\n\t}\n\n\tvar err error\n\tvar transportType string\n\tvar transportPath string\n\tfor p, t := range paths {\n\t\tp, err = exec.LookPath(p)\n\t\tif err == nil {\n\t\t\ttransportType = t\n\t\t\ttransportPath = p\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif transportType == \"\" {\n\t\tfmt.Printf(\"Unable to find a path for %s\\n\", r.request.transport)\n\t\tos.Exit(1)\n\t}\n\n\tif transportType == \"mail\" {\n\t\tfor _, email := range emails {\n\t\t\tcmd := exec.Command(transportPath, \"-s\", r.subject(), strings.TrimSpace(email))\n\t\t\tcmd.Stdin = r.render()\n\t\t\tcmd.Env = []string{fmt.Sprintf(\"HOME=%s\", os.Getenv(\"HOME\"))}\n\t\t\tif err := cmd.Run(); err != nil {\n\t\t\t\tfmt.Printf(\"Could not send email to %s: %s\\n\", email, err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\tif transportType == \"sendmail\" {\n\t\tmessage := fmt.Sprintf(\"To: %s\\r\\nCc: %s\\r\\nSubject: %s\\r\\n\\r\\n%s\", emails[0], strings.Join(emails[1:], \",\"), r.subject(), r.render().String())\n\t\tcmd := exec.Command(transportPath, \"-t\")\n\t\tcmd.Stdin = strings.NewReader(message)\n\t\tcmd.Env = []string{fmt.Sprintf(\"HOME=%s\", os.Getenv(\"HOME\"))}\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tfmt.Printf(\"Could not send email to %s: %s\\n\", emails, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\treturn\n\t}\n}\n\nfunc (r *result) subject() string {\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\thostname = \"undefined\"\n\t}\n\n\tif r.killed {\n\t\treturn fmt.Sprintf(\"Cron on host %s: Timeout\", hostname)\n\t}\n\n\tif r.code == 0 {\n\t\treturn fmt.Sprintf(\"Cron on host %s: Command Successful\", hostname)\n\t}\n\n\treturn fmt.Sprintf(\"Cron on host %s: Failure\", hostname)\n}\n\nfunc (r *result) title() string {\n\tvar msg string\n\n\tif r.killed {\n\t\tmsg = \"Cron timeout detected\"\n\t} else if r.code == 0 {\n\t\tmsg = \"Cron success\"\n\t} else {\n\t\tmsg = \"Cron failure detected\"\n\t}\n\n\treturn msg + \"\\n\" + strings.Repeat(\"=\", len(msg))\n}\n\nfunc (r *result) duration() time.Duration {\n\treturn r.stopped.Sub(r.started)\n}\n\nfunc (r *result) render() *bytes.Buffer {\n\ttpl := template.Must(template.New(\"email\").Parse(`{{.Title}}\n\n{{.Command}}\n\nMETADATA\n--------\n\nExit Code: {{.Code}}\nStart:     {{.Started}}\nStop:      {{.Stopped}}\nDuration:  {{.Duration}}\n\nERROR OUTPUT\n------------\n\n{{.Stderr}}\n\nSTANDARD OUTPUT\n---------------\n\n{{.Stdout}}\n`))\n\n\tdata := struct {\n\t\tTitle    string\n\t\tCommand  string\n\t\tStarted  time.Time\n\t\tStopped  time.Time\n\t\tDuration time.Duration\n\t\tCode     int\n\t\tStderr   string\n\t\tStdout   string\n\t}{\n\t\tTitle:    r.title(),\n\t\tCommand:  r.request.command,\n\t\tStarted:  r.started,\n\t\tStopped:  r.stopped,\n\t\tDuration: r.duration(),\n\t\tCode:     r.code,\n\t\tStderr:   r.stderr.String(),\n\t\tStdout:   r.stdout.String(),\n\t}\n\n\tcontents := bytes.Buffer{}\n\tif err := tpl.Execute(&contents, data); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\treturn &contents\n}\n<commit_msg>fixed edge case<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"syscall\"\n\t\"text\/template\"\n\t\"time\"\n)\n\nvar version = \"master\"\n\ntype request struct {\n\tcommand   string\n\temails    string\n\ttimeout   time.Duration\n\ttransport string\n\tverbose   bool\n}\n\ntype result struct {\n\trequest request\n\tstdout  bytes.Buffer\n\tstderr  bytes.Buffer\n\tstarted time.Time\n\tstopped time.Time\n\tkilled  bool\n\tcode    int\n}\n\nfunc main() {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tcommand := flag.String(\"c\", \"\", `Command to run, like '-c \"ls\"'`)\n\temails := flag.String(\"e\", \"\", `Emails to send reports when the command fails or exceeds timeout, like '-e \"john@example.com,doe@example.com\"'`)\n\ttimeout := flag.Duration(\"t\", 1*time.Hour, `Timeout for the command, like \"-t 2h\", \"-t 2m\", or \"-t 30s\". After the timeout, the command is killed, defaults to 1 hour \"-t 3600\"`)\n\ttransport := flag.String(\"p\", \"auto\", `Transport to use, like \"-p auto\", \"-p mail\", \"-p sendmail\"`)\n\tverbose := flag.Bool(\"v\", false, \"Enable sending emails even if command is successful\")\n\tflag.Parse()\n\n\treq := request{\n\t\tcommand:   *command,\n\t\temails:    *emails,\n\t\ttimeout:   *timeout,\n\t\ttransport: *transport,\n\t\tverbose:   *verbose,\n\t}\n\n\tr := execCmd(wd, req)\n\n\tif r.killed || r.code != 0 || r.request.verbose {\n\t\tif r.request.emails == \"\" {\n\t\t\tfmt.Println(r.render().String())\n\t\t} else {\n\t\t\tr.sendEmail()\n\t\t}\n\t}\n}\n\nfunc execCmd(path string, req request) result {\n\tr := result{\n\t\tstarted: time.Now(),\n\t\trequest: req,\n\t}\n\tcmd := exec.Command(\"sh\", \"-c\", req.command)\n\tcmd.Dir = path\n\tcmd.Stdout = &r.stdout\n\tcmd.Stderr = &r.stderr\n\tcmd.Env = []string{fmt.Sprintf(\"HOME=%s\", os.Getenv(\"HOME\"))}\n\tif err := cmd.Start(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\ttimer := time.NewTimer(req.timeout)\n\tgo func(timer *time.Timer, cmd *exec.Cmd) {\n\t\tfor _ = range timer.C {\n\t\t\tr.killed = true\n\t\t\tif err := cmd.Process.Kill(); err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}(timer, cmd)\n\n\terr := cmd.Wait()\n\ttimer.Stop()\n\tif err != nil {\n\t\t\/\/ unsuccessful exit code?\n\t\tif exitError, ok := err.(*exec.ExitError); ok {\n\t\t\tr.code = exitError.Sys().(syscall.WaitStatus).ExitStatus()\n\t\t} else {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\tr.stopped = time.Now()\n\n\treturn r\n}\n\nfunc (r *result) sendEmail() {\n\temails := strings.Split(r.request.emails, \",\")\n\tpaths := make(map[string]string)\n\n\tif r.request.transport == \"auto\" {\n\t\tpaths = map[string]string{\"sendmail\": \"sendmail\", \"\/usr\/sbin\/sendmail\": \"sendmail\", \"mail\": \"mail\", \"\/usr\/bin\/mail\": \"mail\"}\n\t} else if r.request.transport == \"sendmail\" {\n\t\tpaths = map[string]string{\"sendmail\": \"sendmail\", \"\/usr\/sbin\/sendmail\": \"sendmail\"}\n\t} else if r.request.transport == \"mail\" {\n\t\tpaths = map[string]string{\"mail\": \"mail\", \"\/usr\/bin\/mail\": \"mail\"}\n\t} else {\n\t\tfmt.Printf(\"Unsupported transport %s\\n\", r.request.transport)\n\t\tos.Exit(1)\n\t}\n\n\tvar err error\n\tvar transportType string\n\tvar transportPath string\n\tfor p, t := range paths {\n\t\tp, err = exec.LookPath(p)\n\t\tif err == nil {\n\t\t\ttransportType = t\n\t\t\ttransportPath = p\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif transportType == \"\" {\n\t\tfmt.Printf(\"Unable to find a path for %s\\n\", r.request.transport)\n\t\tos.Exit(1)\n\t}\n\n\tif transportType == \"mail\" {\n\t\tfor _, email := range emails {\n\t\t\tcmd := exec.Command(transportPath, \"-s\", r.subject(), strings.TrimSpace(email))\n\t\t\tcmd.Stdin = r.render()\n\t\t\tcmd.Env = []string{fmt.Sprintf(\"HOME=%s\", os.Getenv(\"HOME\"))}\n\t\t\tif err := cmd.Run(); err != nil {\n\t\t\t\tfmt.Printf(\"Could not send email to %s: %s\\n\", email, err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\tif transportType == \"sendmail\" {\n\t\tmessage := fmt.Sprintf(\"To: %s\\r\\nCc: %s\\r\\nSubject: %s\\r\\n\\r\\n%s\", emails[0], strings.Join(emails[1:], \",\"), r.subject(), r.render().String())\n\t\tcmd := exec.Command(transportPath, \"-t\")\n\t\tcmd.Stdin = strings.NewReader(message)\n\t\tcmd.Env = []string{fmt.Sprintf(\"HOME=%s\", os.Getenv(\"HOME\"))}\n\t\tif err := cmd.Run(); err != nil {\n\t\t\tfmt.Printf(\"Could not send email to %s: %s\\n\", emails, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\treturn\n\t}\n}\n\nfunc (r *result) subject() string {\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\thostname = \"undefined\"\n\t}\n\n\tif r.killed {\n\t\treturn fmt.Sprintf(\"Cron on host %s: Timeout\", hostname)\n\t}\n\n\tif r.code == 0 {\n\t\treturn fmt.Sprintf(\"Cron on host %s: Command Successful\", hostname)\n\t}\n\n\treturn fmt.Sprintf(\"Cron on host %s: Failure\", hostname)\n}\n\nfunc (r *result) title() string {\n\tvar msg string\n\n\tif r.killed {\n\t\tmsg = \"Cron timeout detected\"\n\t} else if r.code == 0 {\n\t\tmsg = \"Cron success\"\n\t} else {\n\t\tmsg = \"Cron failure detected\"\n\t}\n\n\treturn msg + \"\\n\" + strings.Repeat(\"=\", len(msg))\n}\n\nfunc (r *result) duration() time.Duration {\n\treturn r.stopped.Sub(r.started)\n}\n\nfunc (r *result) render() *bytes.Buffer {\n\ttpl := template.Must(template.New(\"email\").Parse(`{{.Title}}\n\n{{.Command}}\n\nMETADATA\n--------\n\nExit Code: {{.Code}}\nStart:     {{.Started}}\nStop:      {{.Stopped}}\nDuration:  {{.Duration}}\n\nERROR OUTPUT\n------------\n\n{{.Stderr}}\n\nSTANDARD OUTPUT\n---------------\n\n{{.Stdout}}\n`))\n\n\tdata := struct {\n\t\tTitle    string\n\t\tCommand  string\n\t\tStarted  time.Time\n\t\tStopped  time.Time\n\t\tDuration time.Duration\n\t\tCode     int\n\t\tStderr   string\n\t\tStdout   string\n\t}{\n\t\tTitle:    r.title(),\n\t\tCommand:  r.request.command,\n\t\tStarted:  r.started,\n\t\tStopped:  r.stopped,\n\t\tDuration: r.duration(),\n\t\tCode:     r.code,\n\t\tStderr:   r.stderr.String(),\n\t\tStdout:   r.stdout.String(),\n\t}\n\n\tcontents := bytes.Buffer{}\n\tif err := tpl.Execute(&contents, data); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\treturn &contents\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/nsf\/termbox-go\"\n\t\/\/ \"github.com\/gdamore\/tcell\"\n\t\/\/ \"time\"\n\t\/\/ \"os\"\n\t\"math\/rand\"\n\t\"time\"\n)\n\nconst DELAY_MS = 150 * time.Millisecond\n\nfunc main() {\n\terr := termbox.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer termbox.Close()\n\n\tfinishGame := make(chan bool)\n\n\tgo handleTerminalEvents(finishGame)\n\tlaunchLife(finishGame)\n}\n\nfunc handleTerminalEvents(finishGame chan bool) {\n\t\/\/wait for esc or ctrl+q pressed, and then exit\n\tterminalEventsLoop:\n\tfor {\n\t\tswitch ev := termbox.PollEvent(); ev.Type {\n\t\tcase termbox.EventKey:\n\t\t\tif ev.Key == termbox.KeyEsc ||\n\t\t\t\tev.Key == termbox.KeyCtrlQ {\n\t\t\t\tbreak terminalEventsLoop\n\t\t\t}\n\t\tcase termbox.EventError:\n\t\t\tpanic(ev.Err)\n\t\t}\n\t}\n\n\tfinishGame <- true\n}\n\nfunc launchLife(finishGame chan bool) {\n\tgameMap := initGameMap(termbox.Size())\n\tfillMapRandomValues(gameMap)\n\tprintGameMap(gameMap)\n\n\ttimer := time.NewTimer(DELAY_MS)\n\n\tlifeLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-finishGame:\n\t\t\tbreak lifeLoop\n\t\tdefault:\n\t\t\tgameMap.Update()\n\n\t\t\t<-timer.C \/\/wait until timer expire, usually longer than map update\n\t\t\ttimer.Reset(DELAY_MS)\n\n\t\t\tprintGameMap(gameMap)\n\t\t}\n\t}\n\n\t\/\/termbox.SetCell(5, 10, '⏣', termbox.ColorWhite, termbox.ColorBlack)\n\t\/\/termbox.SetCell(1, 2, '⏺', termbox.ColorWhite, termbox.ColorBlack)\n\t\/\/termbox.SetCell(10, 5, '⏹', termbox.ColorWhite, termbox.ColorBlack)\n\t\/\/termbox.Flush()\n}\n\nfunc initGameMap(width, height int) *GameMap {\n\tcellAutoMap := make([][]bool, height)\n\n\tfor i := 0; i < height; i++ {\n\t\tcellAutoMap[i] = make([]bool, width)\n\t}\n\n\treturn &GameMap{cellMap: cellAutoMap}\n}\n\nfunc fillMapRandomValues(gameMap *GameMap) {\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\twidth, height := gameMap.GetSize()\n\n\tfor i := 0; i < width; i++ {\n\t\tfor j := 0; j < height; j++ {\n\t\t\tgameMap.SetValue(i, j, getRandomBoolValue())\n\t\t}\n\t}\n}\n\nfunc getRandomBoolValue() bool {\n\trandomValue := rand.Intn(10)\n\treturn randomValue == 0\n}\n\nfunc printGameMap(gameMap *GameMap) {\n\twidth, height := gameMap.GetSize()\n\n\tfor i := 0; i < width; i++ {\n\t\tfor j := 0; j < height; j++ {\n\t\t\tcellAlive := gameMap.GetValue(i, j)\n\t\t\tprintGameMapCell(i, j, cellAlive)\n\t\t}\n\t}\n\n\ttermbox.Flush()\n}\n\nfunc printGameMapCell(height, width int, cellAlive bool) {\n\tif cellAlive {\n\t\ttermbox.SetCell(height, width, '█', termbox.ColorWhite, termbox.ColorBlack)\n\t} else {\n\t\ttermbox.SetCell(height, width, '█', termbox.ColorBlack, termbox.ColorWhite)\n\t}\n}\n<commit_msg>Obsolete code removed<commit_after>package main\n\nimport (\n\t\"github.com\/nsf\/termbox-go\"\n\t\/\/ \"github.com\/gdamore\/tcell\"\n\t\/\/ \"time\"\n\t\/\/ \"os\"\n\t\"math\/rand\"\n\t\"time\"\n)\n\nconst DELAY_MS = 150 * time.Millisecond\n\nfunc main() {\n\terr := termbox.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer termbox.Close()\n\n\tfinishGame := make(chan bool)\n\n\tgo handleTerminalEvents(finishGame)\n\tlaunchLife(finishGame)\n}\n\nfunc handleTerminalEvents(finishGame chan bool) {\n\t\/\/wait for esc or ctrl+q pressed, and then exit\n\tterminalEventsLoop:\n\tfor {\n\t\tswitch ev := termbox.PollEvent(); ev.Type {\n\t\tcase termbox.EventKey:\n\t\t\tif ev.Key == termbox.KeyEsc ||\n\t\t\t\tev.Key == termbox.KeyCtrlQ {\n\t\t\t\tbreak terminalEventsLoop\n\t\t\t}\n\t\tcase termbox.EventError:\n\t\t\tpanic(ev.Err)\n\t\t}\n\t}\n\n\tfinishGame <- true\n}\n\nfunc launchLife(finishGame chan bool) {\n\tgameMap := initGameMap(termbox.Size())\n\tfillMapRandomValues(gameMap)\n\tprintGameMap(gameMap)\n\n\ttimer := time.NewTimer(DELAY_MS)\n\n\tlifeLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-finishGame:\n\t\t\tbreak lifeLoop\n\t\tdefault:\n\t\t\tgameMap.Update()\n\n\t\t\t<-timer.C \/\/wait until timer expire, usually longer than map update\n\t\t\ttimer.Reset(DELAY_MS)\n\n\t\t\tprintGameMap(gameMap)\n\t\t}\n\t}\n}\n\nfunc initGameMap(width, height int) *GameMap {\n\tcellAutoMap := make([][]bool, height)\n\n\tfor i := 0; i < height; i++ {\n\t\tcellAutoMap[i] = make([]bool, width)\n\t}\n\n\treturn &GameMap{cellMap: cellAutoMap}\n}\n\nfunc fillMapRandomValues(gameMap *GameMap) {\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\twidth, height := gameMap.GetSize()\n\n\tfor i := 0; i < width; i++ {\n\t\tfor j := 0; j < height; j++ {\n\t\t\tgameMap.SetValue(i, j, getRandomBoolValue())\n\t\t}\n\t}\n}\n\nfunc getRandomBoolValue() bool {\n\trandomValue := rand.Intn(10)\n\treturn randomValue == 0\n}\n\nfunc printGameMap(gameMap *GameMap) {\n\twidth, height := gameMap.GetSize()\n\n\tfor i := 0; i < width; i++ {\n\t\tfor j := 0; j < height; j++ {\n\t\t\tcellAlive := gameMap.GetValue(i, j)\n\t\t\tprintGameMapCell(i, j, cellAlive)\n\t\t}\n\t}\n\n\ttermbox.Flush()\n}\n\nfunc printGameMapCell(height, width int, cellAlive bool) {\n\tif cellAlive {\n\t\ttermbox.SetCell(height, width, '█', termbox.ColorWhite, termbox.ColorBlack)\n\t} else {\n\t\ttermbox.SetCell(height, width, '█', termbox.ColorBlack, termbox.ColorWhite)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/clearblade\/cblib\"\n\t\"os\"\n)\n\nfunc main() {\n\ttheArgs := os.Args\n\tif len(theArgs) < 2 {\n\t\tfmt.Printf(\"No command provided\\n\")\n\t\tos.Exit(1)\n\t}\n\tsubCommand, err := cblib.GetCommand(theArgs[1])\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n\terr = subCommand.Execute( \/*client,*\/ theArgs[2:])\n\tif err != nil {\n\t\tfmt.Printf(\"Aborting: %s\\n\", err.Error())\n\t}\n}\n<commit_msg>Probable fix for Error while importing portals<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/clearblade\/cblib\"\n\t\"os\"\n)\n\nfunc main() {\n\ttheArgs := os.Args\n\tif len(theArgs) < 2 {\n\t\tfmt.Printf(\"No command provided\\n\")\n\t\tos.Exit(1)\n\t}\n\tsubCommand, err := cblib.GetCommand(theArgs[1])\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n\terr = subCommand.Execute( \/*client,*\/ theArgs[2:])\n\tif err != nil {\n\t\tfmt.Printf(\"Aborting: %s\\n\", err.Error())\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n  \"bytes\"\n  \"bufio\"\n  \"fmt\"\n  \"os\"\n  \"io\"\n  \"time\"\n  \"errors\"\n  \"io\/ioutil\"\n  \"log\"\n  \"net\/url\"\n  \"os\/exec\"\n  \"net\/http\"\n  \"mime\/multipart\"\n  \"path\/filepath\"\n  \"encoding\/json\"\n\n  \"github.com\/skratchdot\/open-golang\/open\"\n  \"github.com\/mitchellh\/go-homedir\"\n  \"github.com\/briandowns\/spinner\"\n  \"github.com\/deiwin\/interact\"\n  \"github.com\/jhoonb\/archivex\"\n  \"github.com\/satori\/go.uuid\"\n  \"github.com\/howeyc\/gopass\"\n  \"github.com\/fatih\/color\"\n  \"github.com\/urfave\/cli\"\n)\n\nvar (\n  platformHost = \"https:\/\/notable.zurb.com\"\n  codeHost = \"https:\/\/code.zurb.com\"\n  version = \"0.0.8\"\n  captureDirectoryPrefix = \"notable-captures\"\n\n  captureDirectory string\n  authPath string\n  s = spinner.New(spinner.CharSets[6], 100*time.Millisecond)\n  checkNotEmpty = func(input string) error {\n    if input == \"\" {\n      return errors.New(\"Input should not be empty!\")\n    }\n    return nil\n  }\n)\n\nfunc check(e error) {\n  if e != nil {\n    panic(e)\n  }\n}\n\ntype CaptureConfig struct {\n  ID        string\n  Recursive string\n  Url       string\n  Agent     string\n  Path      string\n  AuthToken string\n}\n\n\/\/ Configuration is the global configuration object\ntype EnvConfig struct {\n  AuthToken      string `json:\"token\"`\n}\n\nvar envConfig = EnvConfig{}\n\nfunc main() {\n  url := fmt.Sprintf(\"%s\/api\/cli\/sites\", codeHost)\n  directoryID := fmt.Sprintf(\"%s\", uuid.NewV4())\n  captureDirectory = fmt.Sprintf(\"%s-%s\", captureDirectoryPrefix, directoryID)\n  authRoot, err := homedir.Dir()\n  if err != nil {\n    color.Red(\"Cannot access your home directory to check for authentication.\")\n    os.Exit(1)\n  }\n  authPath = fmt.Sprintf(\"%s\/.notable_auth\", authRoot)\n  app := cli.NewApp()\n  app.EnableBashCompletion = true\n  app.Name = \"notable\"\n  app.Usage = \"Interface with Notable (http:\/\/zurb.com\/notable)\"\n  app.Version = version\n  app.Author = \"Jordan Humphreys (jordan@zurb.com)\"\n  app.Copyright = \"ZURB, Inc. 2016 (http:\/\/zurb.com)\"\n\n  app.Commands = []cli.Command{\n    {\n      Name:      \"code\",\n      Aliases:   []string{\"c\"},\n      Usage:     \"Send site to Notable, local or live!\",\n      Flags: []cli.Flag {\n        cli.StringFlag{\n          Name: \"dest, d\",\n          Value: \".\",\n          Usage: \"destination\",\n        },\n      },\n      Action: func(c *cli.Context) error {\n        loadAndCheckEnv()\n\n        id := fmt.Sprintf(\"%s\", uuid.NewV4())\n        config := CaptureConfig{\n          Recursive: \"false\",\n          Agent: \"Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/48.0.2564.116 Safari\/537.36\",\n          Url: c.Args().First(),\n          Path: c.String(\"dest\"),\n          ID: id,\n        }\n\n        if len(config.Url) == 0 {\n          color.Red(\"Code requires a url to capture, example:\")\n          color.White(fmt.Sprintf(\"%s code zurb.com\", os.Args[0]))\n          os.Exit(1)\n        }\n\n        fetch(config)\n        zip(config)\n        upload(config, url)\n        return nil\n      },\n    },\n    {\n      Name:      \"login\",\n      Aliases:   []string{\"l\"},\n      Usage:     \"Authenticate the CLI\",\n      Action: func(c *cli.Context) error {\n        actor := interact.NewActor(os.Stdin, os.Stdout)\n        message := \"Please enter your Notable email address\"\n        email, err := actor.PromptAndRetry(message, checkNotEmpty)\n        if err != nil {\n          log.Fatal(err)\n        }\n\n        fmt.Printf(\"Please enter your Notable password: \")\n        password, err := gopass.GetPasswdMasked()\n        if err != nil {\n          log.Fatal(err)\n        }\n        fetchToken(email, string(password))\n        return nil\n      },\n    },\n    {\n      Name:      \"logout\",\n      Aliases:   []string{\"lo\"},\n      Usage:     \"Deauthorize this computer\",\n      Action: func(c *cli.Context) error {\n        removeAuth()\n        return nil\n      },\n    },\n  }\n\n  app.Run(os.Args)\n}\n\nfunc loadAndCheckEnv() {\n  config, err := readAuth()\n\n  if err != nil {\n    log.Fatal(err)\n  }\n\n  envConfig = config\n}\n\nfunc writeAuth(t string) {\n  token_data := []byte(t)\n  err := ioutil.WriteFile(authPath, token_data, 0644)\n  check(err)\n  color.Green(\"You are now authenticated with Notable!\")\n}\n\nfunc removeAuth() {\n  err := os.Remove(authPath)\n\n  if err != nil {\n    fmt.Println(err)\n    return\n  }\n\n  color.Green(\"Signed out successfully!\")\n}\n\nfunc readAuth() (EnvConfig, error) {\n  file, err := ioutil.ReadFile(authPath)\n\n  if err != nil {\n    color.Red(\"You are not authenticated! Please run:\")\n    color.Green(\"%s login\", os.Args[0])\n    os.Exit(1)\n  }\n\n  return EnvConfig{\n    AuthToken: string(file),\n  }, nil\n}\n\nfunc fetchToken(e string, p string) {\n  endpoint := fmt.Sprintf(\"%s\/api\/v5\/platform_users\/auth_cli\", platformHost)\n  v := url.Values{}\n  v.Set(\"email\", e)\n  v.Add(\"password\", p)\n  var err error\n\n  resp, err := http.PostForm(endpoint, v)\n  if nil != err {\n    panic(err.Error())\n  }\n\n  defer resp.Body.Close()\n  body, err := ioutil.ReadAll(resp.Body)\n\n  err = json.Unmarshal(body, &envConfig)\n  if err != nil {\n    fmt.Printf(\"ERROR: %s\", err)\n    os.Exit(1)\n  }\n\n  if len(envConfig.AuthToken) != 0 {\n    writeAuth(envConfig.AuthToken)\n  } else {\n    color.Red(\"Invalid credentials! Try again.\")\n    os.Exit(1)\n  }\n}\n\nfunc fetch(c CaptureConfig) {\n  wGetCheck()\n  s.Prefix = \"\"\n  s.Suffix = \" Capture: running...\"\n  s.Start()\n  args := []string{\n    fmt.Sprintf(\"-U '%s'\", c.Agent),\n    \"--no-clobber\",\n    \"--adjust-extension\",\n    \"--span-hosts\",\n    \"--page-requisites\",\n    \"--backup-converted\",\n    \"--html-extension\",\n    \"--convert-links\",\n    \"--no-parent\",\n    fmt.Sprintf(\"--directory-prefix=%s\/%s\", captureDirectory, c.ID),\n    c.Url,\n  }\n  cmd := exec.Command(\"wget\", args...)\n\n  cmdReader, err := cmd.StdoutPipe()\n  if err != nil {\n    fmt.Fprintln(os.Stderr, \"Error creating StdoutPipe for Notable\", err)\n    os.Exit(1)\n  }\n\n  scanner := bufio.NewScanner(cmdReader)\n\n  go func() {\n    for scanner.Scan() {\n      fmt.Printf(\"Notable capture | %s\\n\", scanner.Text())\n    }\n  }()\n\n  err = cmd.Start()\n  if err != nil {\n    fmt.Fprintln(os.Stderr, \"Error starting Cmd\", err)\n    os.Exit(1)\n  }\n\n  err = cmd.Wait()\n  if err != nil {\n    text := fmt.Sprintf(\"%s\", err)\n    if text == \"exit status 4\" {\n      color.Red(\"The URL you specified is not accessible.\")\n      os.Exit(1)\n    }\n  }\n  s.Stop()\n  color.Cyan(\"✓ Capture: complete!\\n\")\n\n}\n\nfunc zip(config CaptureConfig) {\n  s.Suffix = \" Compress: running...\"\n  s.Start()\n  path := fmt.Sprintf(\"%s\/%s\", captureDirectory, config.ID)\n  zip := new(archivex.ZipFile)\n  zip.Create(path)\n  zip.AddAll(path, true)\n  zip.Close()\n  os.RemoveAll(path)\n  s.Stop()\n  color.Cyan(\"✓ Compress: complete!\\n\")\n}\n\nfunc upload(config CaptureConfig, url string) {\n  s.Suffix = \" Upload: running...\"\n  s.Start()\n  path := fmt.Sprintf(\"%s\/%s\/%s.zip\", currentPath(), captureDirectory, config.ID)\n  post(path, config, url)\n}\n\nfunc wGetCheck() {\n  _, err := exec.LookPath(\"wget\")\n  if err != nil {\n    color.Red(\"Missing dependency!\\n\")\n    color.Red(\"Please install wget using Homebrew or some other fancy way:\\n\")\n    color.Green(\"brew up && brew install wget\\n\")\n    os.Exit(1)\n  }\n}\n\nfunc currentPath() string {\n  dir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n  if err != nil {\n    log.Fatal(err)\n  }\n  return dir\n}\n\nfunc post(path string, config CaptureConfig, url string){\n  file, err := os.Open(path)\n  if err != nil {\n    log.Fatal(err)\n  }\n  defer file.Close()\n\n  \/* Create a buffer to hold this multi-part form *\/\n  body_buf := bytes.NewBufferString(\"\")\n  body_writer := multipart.NewWriter(body_buf)\n  content_type := body_writer.FormDataContentType()\n\n  \/* Create a Form Field in a simpler way *\/\n  body_writer.WriteField(\"name\", config.Url)\n  body_writer.WriteField(\"token\", envConfig.AuthToken)\n\n  \/* Create a completely custom Form Part (or in this case, a file) *\/\n  \/\/ http:\/\/golang.org\/src\/pkg\/mime\/multipart\/writer.go?s=2274:2352#L86\n  part, err := body_writer.CreateFormFile(\"upload\", filepath.Base(path))\n  if err != nil {\n    log.Fatal(err)\n  }\n  _, err = io.Copy(part, file)\n\n  \/* Close the body and send the request *\/\n  body_writer.Close()\n  resp, err := http.Post(url, content_type, body_buf)\n  if nil != err {\n    panic(err.Error())\n  }\n\n  \/* Handle the response *\/\n  defer resp.Body.Close()\n  body, err := ioutil.ReadAll(resp.Body)\n\n  if nil != err {\n    fmt.Println(\"Error happened reading the body\", err)\n    return\n  }\n\n  var data map[string]interface{}\n  if err := json.Unmarshal(body, &data); err != nil {\n    panic(err)\n  }\n\n  os.Remove(path)\n  os.Remove(fmt.Sprintf(\"%s\/%s\/\", currentPath(), captureDirectory))\n\n  s.Stop()\n  color.Cyan(\"✓ Upload: complete!\\n\\n\")\n  color.Cyan(\"Done! Go give feedback!\")\n  responseUrl := data[\"url\"].(string)\n  color.Magenta(responseUrl)\n\n  open.Run(responseUrl)\n}\n<commit_msg>Small variable definition cleanup.<commit_after>package main\n\nimport (\n  \"bytes\"\n  \"bufio\"\n  \"fmt\"\n  \"os\"\n  \"io\"\n  \"time\"\n  \"errors\"\n  \"io\/ioutil\"\n  \"log\"\n  \"net\/url\"\n  \"os\/exec\"\n  \"net\/http\"\n  \"mime\/multipart\"\n  \"path\/filepath\"\n  \"encoding\/json\"\n\n  \"github.com\/skratchdot\/open-golang\/open\"\n  \"github.com\/mitchellh\/go-homedir\"\n  \"github.com\/briandowns\/spinner\"\n  \"github.com\/deiwin\/interact\"\n  \"github.com\/jhoonb\/archivex\"\n  \"github.com\/satori\/go.uuid\"\n  \"github.com\/howeyc\/gopass\"\n  \"github.com\/fatih\/color\"\n  \"github.com\/urfave\/cli\"\n)\n\nvar (\n  captureDirectoryPrefix = \"notable-captures\"\n  platformHost = \"https:\/\/notable.zurb.com\"\n  codeHost = \"https:\/\/code.zurb.com\"\n  version = \"0.0.8\"\n\n  authPath string\n  captureDirectory string\n  s = spinner.New(spinner.CharSets[6], 100*time.Millisecond)\n  checkNotEmpty = func(input string) error {\n    if input == \"\" {\n      return errors.New(\"Input should not be empty!\")\n    }\n    return nil\n  }\n)\n\nfunc check(e error) {\n  if e != nil {\n    panic(e)\n  }\n}\n\ntype CaptureConfig struct {\n  ID        string\n  Recursive string\n  Url       string\n  Agent     string\n  Path      string\n  AuthToken string\n}\n\n\/\/ Configuration is the global configuration object\ntype EnvConfig struct {\n  AuthToken      string `json:\"token\"`\n}\n\nvar envConfig = EnvConfig{}\n\nfunc main() {\n  url := fmt.Sprintf(\"%s\/api\/cli\/sites\", codeHost)\n  directoryID := fmt.Sprintf(\"%s\", uuid.NewV4())\n  captureDirectory = fmt.Sprintf(\"%s-%s\", captureDirectoryPrefix, directoryID)\n  authRoot, err := homedir.Dir()\n  if err != nil {\n    color.Red(\"Cannot access your home directory to check for authentication.\")\n    os.Exit(1)\n  }\n  authPath = fmt.Sprintf(\"%s\/.notable_auth\", authRoot)\n  app := cli.NewApp()\n  app.EnableBashCompletion = true\n  app.Name = \"notable\"\n  app.Usage = \"Interface with Notable (http:\/\/zurb.com\/notable)\"\n  app.Version = version\n  app.Author = \"Jordan Humphreys (jordan@zurb.com)\"\n  app.Copyright = \"ZURB, Inc. 2016 (http:\/\/zurb.com)\"\n\n  app.Commands = []cli.Command{\n    {\n      Name:      \"code\",\n      Aliases:   []string{\"c\"},\n      Usage:     \"Send site to Notable, local or live!\",\n      Flags: []cli.Flag {\n        cli.StringFlag{\n          Name: \"dest, d\",\n          Value: \".\",\n          Usage: \"destination\",\n        },\n      },\n      Action: func(c *cli.Context) error {\n        loadAndCheckEnv()\n\n        id := fmt.Sprintf(\"%s\", uuid.NewV4())\n        config := CaptureConfig{\n          Recursive: \"false\",\n          Agent: \"Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/48.0.2564.116 Safari\/537.36\",\n          Url: c.Args().First(),\n          Path: c.String(\"dest\"),\n          ID: id,\n        }\n\n        if len(config.Url) == 0 {\n          color.Red(\"Code requires a url to capture, example:\")\n          color.White(fmt.Sprintf(\"%s code zurb.com\", os.Args[0]))\n          os.Exit(1)\n        }\n\n        fetch(config)\n        zip(config)\n        upload(config, url)\n        return nil\n      },\n    },\n    {\n      Name:      \"login\",\n      Aliases:   []string{\"l\"},\n      Usage:     \"Authenticate the CLI\",\n      Action: func(c *cli.Context) error {\n        actor := interact.NewActor(os.Stdin, os.Stdout)\n        message := \"Please enter your Notable email address\"\n        email, err := actor.PromptAndRetry(message, checkNotEmpty)\n        if err != nil {\n          log.Fatal(err)\n        }\n\n        fmt.Printf(\"Please enter your Notable password: \")\n        password, err := gopass.GetPasswdMasked()\n        if err != nil {\n          log.Fatal(err)\n        }\n        fetchToken(email, string(password))\n        return nil\n      },\n    },\n    {\n      Name:      \"logout\",\n      Aliases:   []string{\"lo\"},\n      Usage:     \"Deauthorize this computer\",\n      Action: func(c *cli.Context) error {\n        removeAuth()\n        return nil\n      },\n    },\n  }\n\n  app.Run(os.Args)\n}\n\nfunc loadAndCheckEnv() {\n  config, err := readAuth()\n\n  if err != nil {\n    log.Fatal(err)\n  }\n\n  envConfig = config\n}\n\nfunc writeAuth(t string) {\n  token_data := []byte(t)\n  err := ioutil.WriteFile(authPath, token_data, 0644)\n  check(err)\n  color.Green(\"You are now authenticated with Notable!\")\n}\n\nfunc removeAuth() {\n  err := os.Remove(authPath)\n\n  if err != nil {\n    fmt.Println(err)\n    return\n  }\n\n  color.Green(\"Signed out successfully!\")\n}\n\nfunc readAuth() (EnvConfig, error) {\n  file, err := ioutil.ReadFile(authPath)\n\n  if err != nil {\n    color.Red(\"You are not authenticated! Please run:\")\n    color.Green(\"%s login\", os.Args[0])\n    os.Exit(1)\n  }\n\n  return EnvConfig{\n    AuthToken: string(file),\n  }, nil\n}\n\nfunc fetchToken(e string, p string) {\n  endpoint := fmt.Sprintf(\"%s\/api\/v5\/platform_users\/auth_cli\", platformHost)\n  v := url.Values{}\n  v.Set(\"email\", e)\n  v.Add(\"password\", p)\n  var err error\n\n  resp, err := http.PostForm(endpoint, v)\n  if nil != err {\n    panic(err.Error())\n  }\n\n  defer resp.Body.Close()\n  body, err := ioutil.ReadAll(resp.Body)\n\n  err = json.Unmarshal(body, &envConfig)\n  if err != nil {\n    fmt.Printf(\"ERROR: %s\", err)\n    os.Exit(1)\n  }\n\n  if len(envConfig.AuthToken) != 0 {\n    writeAuth(envConfig.AuthToken)\n  } else {\n    color.Red(\"Invalid credentials! Try again.\")\n    os.Exit(1)\n  }\n}\n\nfunc fetch(c CaptureConfig) {\n  wGetCheck()\n  s.Prefix = \"\"\n  s.Suffix = \" Capture: running...\"\n  s.Start()\n  args := []string{\n    fmt.Sprintf(\"-U '%s'\", c.Agent),\n    \"--no-clobber\",\n    \"--adjust-extension\",\n    \"--span-hosts\",\n    \"--page-requisites\",\n    \"--backup-converted\",\n    \"--html-extension\",\n    \"--convert-links\",\n    \"--no-parent\",\n    fmt.Sprintf(\"--directory-prefix=%s\/%s\", captureDirectory, c.ID),\n    c.Url,\n  }\n  cmd := exec.Command(\"wget\", args...)\n\n  cmdReader, err := cmd.StdoutPipe()\n  if err != nil {\n    fmt.Fprintln(os.Stderr, \"Error creating StdoutPipe for Notable\", err)\n    os.Exit(1)\n  }\n\n  scanner := bufio.NewScanner(cmdReader)\n\n  go func() {\n    for scanner.Scan() {\n      fmt.Printf(\"Notable capture | %s\\n\", scanner.Text())\n    }\n  }()\n\n  err = cmd.Start()\n  if err != nil {\n    fmt.Fprintln(os.Stderr, \"Error starting Cmd\", err)\n    os.Exit(1)\n  }\n\n  err = cmd.Wait()\n  if err != nil {\n    text := fmt.Sprintf(\"%s\", err)\n    if text == \"exit status 4\" {\n      color.Red(\"The URL you specified is not accessible.\")\n      os.Exit(1)\n    }\n  }\n  s.Stop()\n  color.Cyan(\"✓ Capture: complete!\\n\")\n\n}\n\nfunc zip(config CaptureConfig) {\n  s.Suffix = \" Compress: running...\"\n  s.Start()\n  path := fmt.Sprintf(\"%s\/%s\", captureDirectory, config.ID)\n  zip := new(archivex.ZipFile)\n  zip.Create(path)\n  zip.AddAll(path, true)\n  zip.Close()\n  os.RemoveAll(path)\n  s.Stop()\n  color.Cyan(\"✓ Compress: complete!\\n\")\n}\n\nfunc upload(config CaptureConfig, url string) {\n  s.Suffix = \" Upload: running...\"\n  s.Start()\n  path := fmt.Sprintf(\"%s\/%s\/%s.zip\", currentPath(), captureDirectory, config.ID)\n  post(path, config, url)\n}\n\nfunc wGetCheck() {\n  _, err := exec.LookPath(\"wget\")\n  if err != nil {\n    color.Red(\"Missing dependency!\\n\")\n    color.Red(\"Please install wget using Homebrew or some other fancy way:\\n\")\n    color.Green(\"brew up && brew install wget\\n\")\n    os.Exit(1)\n  }\n}\n\nfunc currentPath() string {\n  dir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n  if err != nil {\n    log.Fatal(err)\n  }\n  return dir\n}\n\nfunc post(path string, config CaptureConfig, url string){\n  file, err := os.Open(path)\n  if err != nil {\n    log.Fatal(err)\n  }\n  defer file.Close()\n\n  \/* Create a buffer to hold this multi-part form *\/\n  body_buf := bytes.NewBufferString(\"\")\n  body_writer := multipart.NewWriter(body_buf)\n  content_type := body_writer.FormDataContentType()\n\n  \/* Create a Form Field in a simpler way *\/\n  body_writer.WriteField(\"name\", config.Url)\n  body_writer.WriteField(\"token\", envConfig.AuthToken)\n\n  \/* Create a completely custom Form Part (or in this case, a file) *\/\n  \/\/ http:\/\/golang.org\/src\/pkg\/mime\/multipart\/writer.go?s=2274:2352#L86\n  part, err := body_writer.CreateFormFile(\"upload\", filepath.Base(path))\n  if err != nil {\n    log.Fatal(err)\n  }\n  _, err = io.Copy(part, file)\n\n  \/* Close the body and send the request *\/\n  body_writer.Close()\n  resp, err := http.Post(url, content_type, body_buf)\n  if nil != err {\n    panic(err.Error())\n  }\n\n  \/* Handle the response *\/\n  defer resp.Body.Close()\n  body, err := ioutil.ReadAll(resp.Body)\n\n  if nil != err {\n    fmt.Println(\"Error happened reading the body\", err)\n    return\n  }\n\n  var data map[string]interface{}\n  if err := json.Unmarshal(body, &data); err != nil {\n    panic(err)\n  }\n\n  os.Remove(path)\n  os.Remove(fmt.Sprintf(\"%s\/%s\/\", currentPath(), captureDirectory))\n\n  s.Stop()\n  color.Cyan(\"✓ Upload: complete!\\n\\n\")\n  color.Cyan(\"Done! Go give feedback!\")\n  responseUrl := data[\"url\"].(string)\n  color.Magenta(responseUrl)\n\n  open.Run(responseUrl)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"github.com\/astaxie\/beego\"\n\t\"github.com\/astaxie\/beego\/orm\"\n\t\"myblog\/controllers\/admin\"\n\t\"myblog\/controllers\/blog\"\n\t\"myblog\/models\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\nfunc init() {\n\tvar config_file string\n\tflag.StringVar(&config_file, \"config-file\", \"\", \"the path of the config file\")\n\tflag.Parse()\n\tif config_file != \"\" {\n\t\tbeego.AppConfigPath, _ = filepath.Abs(config_file)\n\t\tbeego.ParseConfig()\n\t} else {\n\t\tif config_file = os.Getenv(\"BEEGO_APP_CONFIG_FILE\"); config_file != \"\" {\n\t\t\tbeego.AppConfigPath, _ = filepath.Abs(config_file)\n\t\t\tbeego.ParseConfig()\n\t\t}\n\t}\n\n\tmodels.Init()\n}\n\nfunc main() {\n\tif beego.AppConfig.String(\"runmode\") == \"dev\" {\n\t\torm.Debug = true\n\t}\n\n\t\/\/前台路由\n\tbeego.Router(\"\/\", &blog.MainController{}, \"*:Index\")\n\tbeego.Router(\"\/page\/:page:int\", &blog.MainController{}, \"*:Index\")\n\tbeego.Router(\"\/article\/:id:int\", &blog.MainController{}, \"*:Show\")      \/\/ID访问\n\tbeego.Router(\"\/article\/:urlname(.+)\", &blog.MainController{}, \"*:Show\") \/\/别名访问\n\tbeego.Router(\"\/archives\", &blog.MainController{}, \"*:Archives\")\n\tbeego.Router(\"\/archives\/page\/:page:int\", &blog.MainController{}, \"*:Archives\")\n\tbeego.Router(\"\/category\/:name(.+?)\", &blog.MainController{}, \"*:Category\")\n\tbeego.Router(\"\/category\/:name(.+?)\/page\/:page:int\", &blog.MainController{}, \"*:Category\")\n\tbeego.Router(\"\/:urlname(.+)\", &blog.MainController{}, \"*:Show\") \/\/别名访问\n\n\t\/\/后台路由\n\tbeego.Router(\"\/admin\", &admin.IndexController{}, \"*:Index\")\n\tbeego.Router(\"\/admin\/login\", &admin.AccountController{}, \"*:Login\")\n\tbeego.Router(\"\/admin\/logout\", &admin.AccountController{}, \"*:Logout\")\n\tbeego.Router(\"\/admin\/account\/profile\", &admin.AccountController{}, \"*:Profile\")\n\t\/\/系统管理\n\tbeego.Router(\"\/admin\/system\/setting\", &admin.SystemController{}, \"*:Setting\")\n\t\/\/内容管理\n\tbeego.Router(\"\/admin\/article\/list\", &admin.ArticleController{}, \"*:List\")\n\tbeego.Router(\"\/admin\/article\/add\", &admin.ArticleController{}, \"*:Add\")\n\tbeego.Router(\"\/admin\/article\/edit\", &admin.ArticleController{}, \"*:Edit\")\n\tbeego.Router(\"\/admin\/article\/save\", &admin.ArticleController{}, \"post:Save\")\n\tbeego.Router(\"\/admin\/article\/delete\", &admin.ArticleController{}, \"*:Delete\")\n\tbeego.Router(\"\/admin\/article\/batch\", &admin.ArticleController{}, \"*:Batch\")\n\tbeego.Router(\"\/admin\/article\/upload\", &admin.ArticleController{}, \"*:Upload\")\n\tbeego.Router(\"\/admin\/tag\", &admin.TagController{}, \"*:Index\")\n\t\/\/用户管理\n\tbeego.Router(\"\/admin\/user\/list\", &admin.UserController{}, \"*:List\")\n\tbeego.Router(\"\/admin\/user\/add\", &admin.UserController{}, \"*:Add\")\n\tbeego.Router(\"\/admin\/user\/edit\", &admin.UserController{}, \"*:Edit\")\n\tbeego.Router(\"\/admin\/user\/delete\", &admin.UserController{}, \"*:Delete\")\n\n\tbeego.Run()\n}\n<commit_msg>modify main.go<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"github.com\/astaxie\/beego\"\n\t\"github.com\/astaxie\/beego\/orm\"\n\t\"myblog\/controllers\/admin\"\n\t\"myblog\/controllers\/blog\"\n\t\"myblog\/models\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\nfunc init() {\n\tvar config_file string\n\tflag.StringVar(&config_file, \"config-file\", \"\", \"the path of the config file\")\n\tflag.Parse()\n\tif config_file != \"\" {\n\t\tbeego.AppConfigPath, _ = filepath.Abs(config_file)\n\t\tbeego.ParseConfig()\n\t} else {\n\t\tif config_file = os.Getenv(\"BEEGO_APP_CONFIG_FILE\"); config_file != \"\" {\n\t\t\tbeego.AppConfigPath, _ = filepath.Abs(config_file)\n\t\t\tbeego.ParseConfig()\n\t\t}\n\t}\n\n\tmodels.Init()\n}\n\nfunc main() {\n\tif beego.AppConfig.String(\"runmode\") == \"dev\" {\n\t\torm.Debug = true\n\t}\n\n\t\/\/前台路由\n\tbeego.Router(\"\/\", &blog.MainController{}, \"*:Index\")\n\tbeego.Router(\"\/page\/:page:int\", &blog.MainController{}, \"*:Index\")\n\tbeego.Router(\"\/article\/:id:int\", &blog.MainController{}, \"*:Show\")      \/\/ID访问\n\tbeego.Router(\"\/article\/:urlname(.+)\", &blog.MainController{}, \"*:Show\") \/\/别名访问\n\tbeego.Router(\"\/archives\", &blog.MainController{}, \"*:Archives\")\n\tbeego.Router(\"\/archives\/page\/:page:int\", &blog.MainController{}, \"*:Archives\")\n\tbeego.Router(\"\/category\/:name(.+?)\", &blog.MainController{}, \"*:Category\")\n\tbeego.Router(\"\/category\/:name(.+?)\/page\/:page:int\", &blog.MainController{}, \"*:Category\")\n\tbeego.Router(\"\/:urlname(.+)\", &blog.MainController{}, \"*:Show\") \/\/别名访问\n\n\t\/\/后台路由\n\tbeego.Router(\"\/admin\", &admin.IndexController{}, \"*:Index\")\n\tbeego.Router(\"\/admin\/login\", &admin.AccountController{}, \"*:Login\")\n\tbeego.Router(\"\/admin\/logout\", &admin.AccountController{}, \"*:Logout\")\n\tbeego.Router(\"\/admin\/account\/profile\", &admin.AccountController{}, \"*:Profile\")\n\t\n\t\/\/系统管理\n\tbeego.Router(\"\/admin\/system\/setting\", &admin.SystemController{}, \"*:Setting\")\n\t\n\t\/\/内容管理\n\tbeego.Router(\"\/admin\/article\/list\", &admin.ArticleController{}, \"*:List\")\n\tbeego.Router(\"\/admin\/article\/add\", &admin.ArticleController{}, \"*:Add\")\n\tbeego.Router(\"\/admin\/article\/edit\", &admin.ArticleController{}, \"*:Edit\")\n\tbeego.Router(\"\/admin\/article\/save\", &admin.ArticleController{}, \"post:Save\")\n\tbeego.Router(\"\/admin\/article\/delete\", &admin.ArticleController{}, \"*:Delete\")\n\tbeego.Router(\"\/admin\/article\/batch\", &admin.ArticleController{}, \"*:Batch\")\n\tbeego.Router(\"\/admin\/article\/upload\", &admin.ArticleController{}, \"*:Upload\")\n\tbeego.Router(\"\/admin\/tag\", &admin.TagController{}, \"*:Index\")\n\t\n\t\/\/用户管理\n\tbeego.Router(\"\/admin\/user\/list\", &admin.UserController{}, \"*:List\")\n\tbeego.Router(\"\/admin\/user\/add\", &admin.UserController{}, \"*:Add\")\n\tbeego.Router(\"\/admin\/user\/edit\", &admin.UserController{}, \"*:Edit\")\n\tbeego.Router(\"\/admin\/user\/delete\", &admin.UserController{}, \"*:Delete\")\n\n\tbeego.Run()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/logzer0\/vegeta\"\n)\n\nfunc main() {\n\turl := \"https:\/\/api.meetup.com\/find\/groups?&sign=true&photo-host=public&zip=75063&category=34&page=20&key=629f7e19624e182a5c5117743\"\n\tvar resp []byte\n\tvar err error\n\thandler := vegeta.NewHandler()\n\tif resp, err = handler.GetRequest(url); err != nil {\n\t\tfmt.Errorf(\"Expected:\", nil, \" Received: \", err)\n\t}\n\tif len(resp) < 1 {\n\t\tfmt.Errorf(\"Expected length to be greater than 0 got \", len(resp))\n\t}\n\tfmt.Println(string(resp))\n}\n\ntype Group struct {\n\tScore                int     `json:\"score\"`\n\tID                   int     `json:\"id\"`\n\tName                 string  `json:\"name\"`\n\tLink                 string  `json:\"link\"`\n\tUrlname              string  `json:\"urlname\"`\n\tDescription          string  `json:\"description\"`\n\tCreated              int64   `json:\"created\"`\n\tCity                 string  `json:\"city\"`\n\tCountry              string  `json:\"country\"`\n\tLocalizedCountryName string  `json:\"localized_country_name\"`\n\tState                string  `json:\"state\"`\n\tJoinMode             string  `json:\"join_mode\"`\n\tVisibility           string  `json:\"visibility\"`\n\tLat                  float64 `json:\"lat\"`\n\tLon                  float64 `json:\"lon\"`\n\tMembers              int     `json:\"members\"`\n\tOrganizer            struct {\n\t\tID    int    `json:\"id\"`\n\t\tName  string `json:\"name\"`\n\t\tBio   string `json:\"bio\"`\n\t\tPhoto struct {\n\t\t\tID          int    `json:\"id\"`\n\t\t\tHighresLink string `json:\"highres_link\"`\n\t\t\tPhotoLink   string `json:\"photo_link\"`\n\t\t\tThumbLink   string `json:\"thumb_link\"`\n\t\t} `json:\"photo\"`\n\t} `json:\"organizer\"`\n\tWho        string `json:\"who\"`\n\tGroupPhoto struct {\n\t\tID          int    `json:\"id\"`\n\t\tHighresLink string `json:\"highres_link\"`\n\t\tPhotoLink   string `json:\"photo_link\"`\n\t\tThumbLink   string `json:\"thumb_link\"`\n\t} `json:\"group_photo\"`\n\tTimezone  string `json:\"timezone\"`\n\tNextEvent struct {\n\t\tID           string `json:\"id\"`\n\t\tName         string `json:\"name\"`\n\t\tYesRsvpCount int    `json:\"yes_rsvp_count\"`\n\t\tTime         int64  `json:\"time\"`\n\t\tUtcOffset    int    `json:\"utc_offset\"`\n\t} `json:\"next_event\"`\n\tCategory struct {\n\t\tID        int    `json:\"id\"`\n\t\tName      string `json:\"name\"`\n\t\tShortname string `json:\"shortname\"`\n\t\tSortName  string `json:\"sort_name\"`\n\t} `json:\"category\"`\n\tPhotos []struct {\n\t\tID          int    `json:\"id\"`\n\t\tHighresLink string `json:\"highres_link\"`\n\t\tPhotoLink   string `json:\"photo_link\"`\n\t\tThumbLink   string `json:\"thumb_link\"`\n\t} `json:\"photos\"`\n}\n\ntype Event struct {\n\tCreated       int64  `json:\"created\"`\n\tDuration      int    `json:\"duration\"`\n\tID            string `json:\"id\"`\n\tName          string `json:\"name\"`\n\tRsvpLimit     int    `json:\"rsvp_limit\"`\n\tStatus        string `json:\"status\"`\n\tTime          int64  `json:\"time\"`\n\tUpdated       int64  `json:\"updated\"`\n\tUtcOffset     int    `json:\"utc_offset\"`\n\tWaitlistCount int    `json:\"waitlist_count\"`\n\tYesRsvpCount  int    `json:\"yes_rsvp_count\"`\n\tGroup         struct {\n\t\tCreated  int64   `json:\"created\"`\n\t\tName     string  `json:\"name\"`\n\t\tID       int     `json:\"id\"`\n\t\tJoinMode string  `json:\"join_mode\"`\n\t\tLat      float64 `json:\"lat\"`\n\t\tLon      float64 `json:\"lon\"`\n\t\tUrlname  string  `json:\"urlname\"`\n\t\tWho      string  `json:\"who\"`\n\t} `json:\"group\"`\n\tLink        string `json:\"link\"`\n\tDescription string `json:\"description\"`\n\tVenue       struct {\n\t\tID                   int     `json:\"id\"`\n\t\tName                 string  `json:\"name\"`\n\t\tLat                  float64 `json:\"lat\"`\n\t\tLon                  float64 `json:\"lon\"`\n\t\tRepinned             bool    `json:\"repinned\"`\n\t\tAddress1             string  `json:\"address_1\"`\n\t\tCity                 string  `json:\"city\"`\n\t\tCountry              string  `json:\"country\"`\n\t\tLocalizedCountryName string  `json:\"localized_country_name\"`\n\t} `json:\"venue\"`\n\tVisibility string `json:\"visibility\"`\n}\n<commit_msg>legacy<commit_after><|endoftext|>"}
{"text":"<commit_before>package main\n\n\/\/ Note: In my $GOPATH\/src I have github.com\/midnightfreddie\/goleveldb\/leveldb (addzlib branch) in place of github.com\/syndtr\/goleveldb\/leveldb\n\/\/   This adds zlib decompression to the reader as compression type 2 which is needed to read MCPE ldb files\nimport (\n\t\"bytes\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/quag\/mcobj\/nbt\"\n\t\"github.com\/syndtr\/goleveldb\/leveldb\"\n\t\"github.com\/syndtr\/goleveldb\/leveldb\/opt\"\n\t\"github.com\/urfave\/cli\"\n)\n\nfunc proofOfConcept() {\n\to := &opt.Options{\n\t\tReadOnly: true,\n\t}\n\tdb, err := leveldb.OpenFile(\"db\", o)\n\tif err != nil {\n\t\tpanic(\"error\")\n\t}\n\tdefer db.Close()\n\n\tplayer, err := db.Get([]byte(\"~local_player\"), nil)\n\tif err != nil {\n\t\tpanic(\"error\")\n\t}\n\tfmt.Println(hex.Dump(player[:]))\n\tnbtr := bytes.NewReader(player)\n\tmynbt := nbt.NewReader(nbtr)\n\tid, out, err := mynbt.ReadTag()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Println(\"\\n\\n\")\n\tfmt.Printf(\"\\n%d%s\\n\", id, out)\n\n\t\/\/ iterate and print the first 10 key\/value pairs\n\titer := db.NewIterator(nil, nil)\n\tfor i := 1; i < 10; iter.Next() {\n\t\tkey := iter.Key()\n\t\tvalue := iter.Value()\n\t\tfmt.Println(key)\n\t\tfmt.Println(value)\n\t\ti++\n\t}\n\titer.Release()\n\terr = iter.Error()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"MCPE Tool\"\n\tapp.Version = \"0.0.0\"\n\tapp.Usage = \"A utility to access Minecraft Portable Edition .mcworld exported world files.\"\n\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:    \"keys\",\n\t\t\tAliases: []string{\"k\"},\n\t\t\tUsage:   \"Lists all keys in the database. Be sure to include the path to the db, e.g. 'McpeTool keys db'\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\to := &opt.Options{\n\t\t\t\t\tReadOnly: true,\n\t\t\t\t}\n\t\t\t\tdb, err := leveldb.OpenFile(c.Args().First(), o)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(\"error\")\n\t\t\t\t}\n\t\t\t\tdefer db.Close()\n\n\t\t\t\titer := db.NewIterator(nil, nil)\n\t\t\t\tfor iter.Next() {\n\t\t\t\t\tfmt.Println(iter.Key())\n\t\t\t\t}\n\t\t\t\titer.Release()\n\t\t\t\terr = iter.Error()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err.Error())\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:    \"proofofconcept\",\n\t\t\tAliases: []string{\"poc\"},\n\t\t\tUsage:   \"Run the original POC code which assumes a folder \\\"db\\\" is present with the *.ldb and other level files\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\tproofOfConcept()\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n}\n<commit_msg>some keys printed as strings<commit_after>package main\n\n\/\/ Note: In my $GOPATH\/src I have github.com\/midnightfreddie\/goleveldb\/leveldb (addzlib branch) in place of github.com\/syndtr\/goleveldb\/leveldb\n\/\/   This adds zlib decompression to the reader as compression type 2 which is needed to read MCPE ldb files\nimport (\n\t\"bytes\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/quag\/mcobj\/nbt\"\n\t\"github.com\/syndtr\/goleveldb\/leveldb\"\n\t\"github.com\/syndtr\/goleveldb\/leveldb\/opt\"\n\t\"github.com\/urfave\/cli\"\n)\n\nfunc proofOfConcept() {\n\to := &opt.Options{\n\t\tReadOnly: true,\n\t}\n\tdb, err := leveldb.OpenFile(\"db\", o)\n\tif err != nil {\n\t\tpanic(\"error\")\n\t}\n\tdefer db.Close()\n\n\tplayer, err := db.Get([]byte(\"~local_player\"), nil)\n\tif err != nil {\n\t\tpanic(\"error\")\n\t}\n\tfmt.Println(hex.Dump(player[:]))\n\tnbtr := bytes.NewReader(player)\n\tmynbt := nbt.NewReader(nbtr)\n\tid, out, err := mynbt.ReadTag()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Println(\"\\n\\n\")\n\tfmt.Printf(\"\\n%d%s\\n\", id, out)\n\n\t\/\/ iterate and print the first 10 key\/value pairs\n\titer := db.NewIterator(nil, nil)\n\tfor i := 1; i < 10; iter.Next() {\n\t\tkey := iter.Key()\n\t\tvalue := iter.Value()\n\t\tfmt.Println(key)\n\t\tfmt.Println(value)\n\t\ti++\n\t}\n\titer.Release()\n\terr = iter.Error()\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"MCPE Tool\"\n\tapp.Version = \"0.0.0\"\n\tapp.Usage = \"A utility to access Minecraft Portable Edition .mcworld exported world files.\"\n\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:    \"keys\",\n\t\t\tAliases: []string{\"k\"},\n\t\t\tUsage:   \"Lists all keys in the database. Be sure to include the path to the db, e.g. 'McpeTool keys db'\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\to := &opt.Options{\n\t\t\t\t\tReadOnly: true,\n\t\t\t\t}\n\t\t\t\tdb, err := leveldb.OpenFile(c.Args().First(), o)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(\"error\")\n\t\t\t\t}\n\t\t\t\tdefer db.Close()\n\n\t\t\t\titer := db.NewIterator(nil, nil)\n\t\t\t\tfor iter.Next() {\n\t\t\t\t\tkey := iter.Key()\n\t\t\t\t\tswitch {\n\t\t\t\t\tcase len(key) == 9:\n\t\t\t\t\t\tswitch key[8] {\n\t\t\t\t\t\tcase 0x30, 0x31, 0x32, 0x76:\n\t\t\t\t\t\t\tfmt.Println(key)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tfmt.Println(string(key[:]))\n\t\t\t\t\t\t}\n\t\t\t\t\tcase len(key) == 13:\n\t\t\t\t\t\tfmt.Println(key)\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tfmt.Println(string(key[:]))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\titer.Release()\n\t\t\t\terr = iter.Error()\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err.Error())\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:    \"proofofconcept\",\n\t\t\tAliases: []string{\"poc\"},\n\t\t\tUsage:   \"Run the original POC code which assumes a folder \\\"db\\\" is present with the *.ldb and other level files\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\tproofOfConcept()\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"image\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"time\"\n\n\t\"github.com\/Ariemeth\/termloop\"\n)\n\n\/\/ CrunchConfig defines the crunching board.\ntype CrunchConfig struct {\n\tNumCol           int\n\tColVSpace        int\n\tColSpace         int\n\tColDepth         int\n\tCritterSizeSmall int\n\tCritterSizeLarge int\n}\n\nfunc (conf *CrunchConfig) boardSize() image.Point {\n\treturn image.Point{\n\t\tX: conf.NumCol*conf.CritterSizeLarge + (conf.NumCol+1)*conf.ColSpace,\n\t\tY: (conf.ColDepth+1)*(conf.CritterSizeLarge+conf.ColVSpace) + conf.CritterSizeLarge, \/\/ extra depth for death indication -- below vine\n\t}\n}\n\nfunc (conf *CrunchConfig) colLength() int {\n\treturn conf.ColDepth * (conf.CritterSizeLarge + conf.ColVSpace)\n}\n\nfunc main() {\n\tconfig := &CrunchConfig{\n\t\tNumCol:           6,\n\t\tColSpace:         2,\n\t\tColDepth:         5,\n\t\tCritterSizeSmall: 1,\n\t\tCritterSizeLarge: 1,\n\t}\n\n\tsize := config.boardSize()\n\tlog.Printf(\"size: %v\", size)\n\n\tgame := termloop.NewGame()\n\n\tlevel := termloop.NewBaseLevel(termloop.Cell{\n\t\tBg: termloop.ColorBlack,\n\t\tFg: termloop.ColorWhite,\n\t})\n\n\tboard := termloop.NewBaseLevel(termloop.Cell{})\n\tboard.SetOffset(2, 1)\n\n\tborder := termloop.NewEntity(0, 0, size.X+2, size.Y+2)\n\tfor i := 0; i < size.X+2; i++ {\n\t\tborder.SetCell(i, 0, &termloop.Cell{Fg: termloop.ColorGreen, Ch: '~'})\n\t\tborder.SetCell(i, size.Y+1, &termloop.Cell{Fg: termloop.ColorGreen, Ch: 'v'})\n\t}\n\tfor j := 1; j < size.Y+1; j++ {\n\t\tborder.SetCell(0, j, &termloop.Cell{Fg: termloop.ColorGreen, Ch: '|'})\n\t\tborder.SetCell(size.X+1, j, &termloop.Cell{Fg: termloop.ColorGreen, Ch: '|'})\n\t}\n\tboard.AddEntity(border)\n\t\/\/board.AddEntity(termloop.NewRectangle(1, 1, size.X, size.Y, termloop.ColorCyan))\n\n\tfor i := 0; i < config.NumCol; i++ {\n\t\tposX := 1 + config.ColSpace + config.CritterSizeLarge\/2 + i*(config.ColSpace+config.CritterSizeLarge)\n\t\tcolumn := termloop.NewEntity(posX, 1, 1, config.colLength())\n\t\tfor j := 0; j < config.colLength(); j++ {\n\t\t\tcolumn.SetCell(0, j, &termloop.Cell{Fg: termloop.ColorGreen, Ch: '|'})\n\t\t}\n\t\tboard.AddEntity(column)\n\t}\n\n\tcrunch := NewCrunchGame(config, board)\n\n\tlevel.AddEntity(crunch)\n\n\tgame.Screen().SetLevel(level)\n\tgame.Start()\n}\n\n\/\/ Color is the a color in a crunch game.\ntype Color uint8\n\n\/\/ Color constants with special significance.\nconst (\n\tColorNone Color = iota\n\tColorMulti\n\tColorBomb\n\tColorPlayer\n\tColorBug\n)\n\n\/\/ ColorMap maps game colors to their actual representation in a terminal.\ntype ColorMap interface {\n\tColor(Color) termloop.Attr\n}\n\n\/\/ SetCellColor sets the foreground of m according to a color map\nfunc SetCellColor(c *termloop.Cell, m ColorMap, fg Color) {\n\tc.Fg = m.Color(fg)\n}\n\n\/\/ BugType enumerates the types of possible bugs\ntype BugType uint8\n\n\/\/ BugType values that are acceptable\nconst (\n\tBugSmall BugType = iota\n\tBugLarge\n\tBugGnat\n\tBugMagic\n\tBugBomb\n)\n\n\/\/ Bug is a bug that crawls down the vines.  Bugs have distinct color.  Large\n\/\/ bugs can only eat smaller bugs of the same color.\ntype Bug struct {\n\tType   BugType\n\tColor  Color\n\tEaten  int8\n\tRune   rune\n\tentity *termloop.Entity\n}\n\n\/\/ CrunchGame contains a player, critters, a score, and other game state.\ntype CrunchGame struct {\n\tconfig     *CrunchConfig\n\tplayerPos  int\n\tplayer     *Player\n\tvines      [][]*Bug\n\trand       Rand\n\tspawnTime  time.Time\n\tmultis     map[*Bug]struct{}\n\tmultisTime time.Time\n\tlevel      *termloop.BaseLevel\n}\n\n\/\/ NewCrunchGame initializes a new CrunchGame.\nfunc NewCrunchGame(config *CrunchConfig, level *termloop.BaseLevel) *CrunchGame {\n\tg := &CrunchGame{\n\t\tconfig: config,\n\t\trand:   defaultRand(),\n\t\tmultis: make(map[*Bug]struct{}),\n\t\tlevel:  level,\n\t}\n\tg.vines = make([][]*Bug, config.NumCol)\n\tfor i := range g.vines {\n\t\tg.vines[i] = make([]*Bug, 0, config.ColDepth+1)\n\t}\n\n\tg.playerPos = config.NumCol\n\tg.player = &Player{\n\t\tentity: termloop.NewEntity(g.colX(g.playerPos), g.config.boardSize().Y, 1, 1),\n\t\tlevel:  level,\n\t}\n\tg.player.entity.SetCell(0, 0, g.player.cell())\n\tg.level.AddEntity(g.player.entity)\n\n\treturn g\n}\n\nfunc (g *CrunchGame) colX(i int) int {\n\tif i >= g.config.NumCol {\n\t\treturn g.config.boardSize().X\n\t}\n\treturn 1 + g.config.ColSpace + i*(g.config.ColSpace+1+g.config.CritterSizeLarge\/2)\n}\n\nfunc defaultRand() Rand {\n\treturn rand.New(rand.NewSource(time.Now().UnixNano()))\n}\n\nfunc (g *CrunchGame) gameOver() bool {\n\tfor i := range g.vines {\n\t\tif len(g.vines[i]) >= g.config.NumCol {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (g *CrunchGame) randomColorBug(n int) Color {\n\treturn ColorBug + Color(g.rand.Intn(n))\n}\n\nfunc (g *CrunchGame) randomBug() *Bug {\n\troll := g.rand.Intn(100) + 1\n\n\troll -= 30\n\tif roll < 0 {\n\t\treturn g.createBug(BugSmall, g.randomColorBug(2))\n\t}\n\n\troll -= 30\n\tif roll < 0 {\n\t\treturn g.createBug(BugLarge, g.randomColorBug(2))\n\t}\n\n\troll -= 30\n\tif roll < 0 {\n\t\treturn g.createBug(BugGnat, ColorNone)\n\t}\n\n\troll -= 8\n\tif roll < 0 {\n\t\treturn g.createBug(BugBomb, ColorBomb)\n\t}\n\n\treturn g.createBug(BugMagic, ColorMulti)\n}\n\nfunc (g *CrunchGame) createBug(typ BugType, c Color) *Bug {\n\tb := &Bug{\n\t\tType:  typ,\n\t\tColor: c,\n\t}\n\tb.Rune = g.assignRune(b)\n\treturn b\n}\n\nfunc (g *CrunchGame) assignRune(bug *Bug) rune {\n\tswitch bug.Type {\n\tcase BugSmall:\n\t\tif bug.Eaten > 0 {\n\t\t\treturn '⊛'\n\t\t}\n\t\treturn 'o'\n\tcase BugLarge:\n\t\tif bug.Eaten > 0 {\n\t\t\treturn '@'\n\t\t}\n\t\treturn 'O'\n\tcase BugGnat:\n\t\tconst gnats = \"`'~\"\n\t\treturn rune(gnats[g.rand.Intn(len(gnats))])\n\tcase BugBomb:\n\t\tif bug.Eaten > 0 {\n\t\t\treturn '&'\n\t\t}\n\t\treturn '8'\n\tcase BugMagic:\n\t\tif bug.Eaten > 0 {\n\t\t\treturn '*'\n\t\t}\n\t\treturn '+'\n\t}\n\treturn 'x'\n}\n\nfunc (g *CrunchGame) spawnBugs() {\n\t\/\/ for now we do something simple and spawn bugs in all rows simultaneously\n\tfor i := range g.vines {\n\t\tg.vines[i] = g.vines[i][:len(g.vines[i])+1]\n\t\tcopy(g.vines[i][1:], g.vines[i][0:]) \/\/ shift bugs \"down\"\n\t\tg.vines[i][0] = g.randomBug()\n\t\tg.vines[i][0].entity = termloop.NewEntity(0, 0, 1, 1)\n\t\tif g.vines[i][0].Color == ColorMulti {\n\t\t\tg.multis[g.vines[i][0]] = struct{}{}\n\t\t\tg.vines[i][0].entity.SetCell(0, 0, &termloop.Cell{\n\t\t\t\tFg: defaultColorMap.Color(g.randMultiColor()),\n\t\t\t\tCh: g.vines[i][0].Rune,\n\t\t\t})\n\t\t} else {\n\t\t\tg.vines[i][0].entity.SetCell(0, 0, &termloop.Cell{\n\t\t\t\tFg: defaultColorMap.Color(g.vines[i][0].Color),\n\t\t\t\tCh: g.vines[i][0].Rune,\n\t\t\t})\n\t\t}\n\t\tg.level.AddEntity(g.vines[i][0].entity)\n\t\tcx := g.colX(i)\n\t\tsize := g.config.boardSize()\n\t\tfor j := range g.vines[i] {\n\t\t\ty := size.Y\n\t\t\tif j < g.config.ColDepth {\n\t\t\t\ty = 1 + j\n\t\t\t}\n\t\t\tg.vines[i][j].entity.SetPosition(cx, y)\n\t\t}\n\t}\n}\n\nfunc (g *CrunchGame) assignMultiColors() {\n\tfor bug := range g.multis {\n\t\tcolor := ColorBomb\n\t\tswitch g.rand.Intn(3) {\n\t\tcase 0:\n\t\t\tcolor = ColorBug + 0\n\t\tcase 1:\n\t\t\tcolor = ColorBug + 1\n\t\t}\n\t\tcell := &termloop.Cell{\n\t\t\tFg: defaultColorMap.Color(color),\n\t\t\tCh: bug.Rune,\n\t\t}\n\t\tbug.entity.SetCell(0, 0, cell)\n\t}\n}\n\nfunc (g *CrunchGame) randMultiColor() Color {\n\tswitch g.rand.Intn(3) {\n\tcase 0:\n\t\treturn ColorBug + 0\n\tcase 1:\n\t\treturn ColorBug + 1\n\t}\n\treturn ColorBomb\n}\n\n\/\/ Draw implements termloop.Drawable\nfunc (g *CrunchGame) Draw(screen *termloop.Screen) {\n\tdefer g.level.Draw(screen)\n\n\tnow := time.Now()\n\n\ttwinkle := true\n\n\tif g.gameOver() {\n\t\t\/\/ TODO: do something here\n\t} else {\n\t\tif now.Sub(g.spawnTime) > 2*time.Second {\n\t\t\tg.spawnTime = now\n\t\t\tg.spawnBugs()\n\t\t}\n\t}\n\tif twinkle && now.Sub(g.multisTime) > 100*time.Millisecond {\n\t\tg.multisTime = now\n\t\tg.assignMultiColors()\n\t}\n}\n\n\/\/ Tick implements termloop.Drawable\nfunc (g *CrunchGame) Tick(event termloop.Event) {\n\tif event.Type == termloop.EventKey { \/\/ Is it a keyboard event?\n\t\tswitch event.Ch { \/\/ If so, switch on the pressed key.\n\t\tcase 'l':\n\t\t\tif g.playerPos < g.config.NumCol {\n\t\t\t\tg.playerPos++\n\t\t\t\tg.player.entity.SetPosition(g.colX(g.playerPos), g.config.boardSize().Y)\n\t\t\t}\n\t\tcase 'h':\n\t\t\tif g.playerPos > 0 {\n\t\t\t\tg.playerPos--\n\t\t\t\tg.player.entity.SetPosition(g.colX(g.playerPos), g.config.boardSize().Y)\n\t\t\t}\n\t\tcase 'k':\n\t\t\tif g.player.contains != nil {\n\t\t\t\tg.player.contains = nil\n\t\t\t} else {\n\t\t\t\tg.player.contains = &Bug{Type: BugSmall, Color: ColorBug}\n\t\t\t}\n\t\t\tg.player.entity.SetCell(0, 0, g.player.cell())\n\t\tcase 'j':\n\t\t\t\/\/ TODO: puke on the side of the screen when your buddy is around\n\t\t}\n\t}\n}\n\n\/\/ Player is a player in a CrunchGame\ntype Player struct {\n\tconfig   *CrunchConfig\n\tentity   *termloop.Entity\n\tcontains *Bug \/\/ any contained bug will have its entity removed\n\tprevX    int\n\tprevY    int\n\tlevel    *termloop.BaseLevel\n}\n\n\/\/ Draw implements termloop.Drawable\nfunc (p *Player) Draw(screen *termloop.Screen) {\n\tp.entity.Draw(screen)\n}\n\nfunc (p Player) cell() *termloop.Cell {\n\tcell := &termloop.Cell{}\n\tif p.contains != nil {\n\t\tcell.Ch = '@'\n\t\tSetCellColor(cell, defaultColorMap, p.contains.Color)\n\t} else {\n\t\tcell.Ch = 'O'\n\t\tSetCellColor(cell, defaultColorMap, ColorPlayer)\n\t}\n\treturn cell\n}\n\n\/\/ Tick implements termloop.Drawable\nfunc (p *Player) Tick(event termloop.Event) {\n\tp.entity.Tick(event)\n}\n\nvar defaultColorMap = simpleColorMap{\n\tColorNone:   termloop.ColorWhite,\n\tColorMulti:  termloop.ColorWhite, \/\/ ColorMulti is not used\n\tColorBomb:   termloop.ColorRed,\n\tColorPlayer: termloop.ColorMagenta,\n\n\tColorBug + 0: termloop.ColorYellow,\n\tColorBug + 1: termloop.ColorBlue,\n}\n\ntype simpleColorMap []termloop.Attr\n\nfunc (m simpleColorMap) Color(c Color) termloop.Attr {\n\tif len(m) == 0 {\n\t\tpanic(\"empty color map\")\n\t}\n\tif int(c) < len(m) {\n\t\treturn m[c]\n\t}\n\treturn m[ColorNone]\n}\n\nfunc cell(c rune) *termloop.Cell {\n\treturn &termloop.Cell{Ch: c}\n}\n\n\/\/ Rand wraps PRNG implementations so that behavior of randomized things can be\n\/\/ tested more easily.\ntype Rand interface {\n\tIntn(n int) int\n}\n<commit_msg>a player can grab and spit bugs now -- no chain reactions yet<commit_after>package main\n\nimport (\n\t\"image\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"time\"\n\n\t\"github.com\/Ariemeth\/termloop\"\n)\n\n\/\/ CrunchConfig defines the crunching board.\ntype CrunchConfig struct {\n\tNumCol           int\n\tColVSpace        int\n\tColSpace         int\n\tColDepth         int\n\tCritterSizeSmall int\n\tCritterSizeLarge int\n}\n\nfunc (conf *CrunchConfig) boardSize() image.Point {\n\treturn image.Point{\n\t\tX: conf.NumCol*conf.CritterSizeLarge + (conf.NumCol+1)*conf.ColSpace,\n\t\tY: (conf.ColDepth+1)*(conf.CritterSizeLarge+conf.ColVSpace) + conf.CritterSizeLarge, \/\/ extra depth for death indication -- below vine\n\t}\n}\n\nfunc (conf *CrunchConfig) colLength() int {\n\treturn conf.ColDepth * (conf.CritterSizeLarge + conf.ColVSpace)\n}\n\nfunc main() {\n\tconfig := &CrunchConfig{\n\t\tNumCol:           6,\n\t\tColSpace:         2,\n\t\tColDepth:         5,\n\t\tCritterSizeSmall: 1,\n\t\tCritterSizeLarge: 1,\n\t}\n\n\tsize := config.boardSize()\n\tlog.Printf(\"size: %v\", size)\n\n\tgame := termloop.NewGame()\n\n\tlevel := termloop.NewBaseLevel(termloop.Cell{\n\t\tBg: termloop.ColorBlack,\n\t\tFg: termloop.ColorWhite,\n\t})\n\n\tboard := termloop.NewBaseLevel(termloop.Cell{})\n\tboard.SetOffset(2, 1)\n\n\tborder := termloop.NewEntity(0, 0, size.X+2, size.Y+2)\n\tfor i := 0; i < size.X+2; i++ {\n\t\tborder.SetCell(i, 0, &termloop.Cell{Fg: termloop.ColorGreen, Ch: '~'})\n\t\tborder.SetCell(i, size.Y+1, &termloop.Cell{Fg: termloop.ColorGreen, Ch: 'v'})\n\t}\n\tfor j := 1; j < size.Y+1; j++ {\n\t\tborder.SetCell(0, j, &termloop.Cell{Fg: termloop.ColorGreen, Ch: '|'})\n\t\tborder.SetCell(size.X+1, j, &termloop.Cell{Fg: termloop.ColorGreen, Ch: '|'})\n\t}\n\tboard.AddEntity(border)\n\t\/\/board.AddEntity(termloop.NewRectangle(1, 1, size.X, size.Y, termloop.ColorCyan))\n\n\tfor i := 0; i < config.NumCol; i++ {\n\t\tposX := 1 + config.ColSpace + config.CritterSizeLarge\/2 + i*(config.ColSpace+config.CritterSizeLarge)\n\t\tcolumn := termloop.NewEntity(posX, 1, 1, config.colLength())\n\t\tfor j := 0; j < config.colLength(); j++ {\n\t\t\tcolumn.SetCell(0, j, &termloop.Cell{Fg: termloop.ColorGreen, Ch: '|'})\n\t\t}\n\t\tboard.AddEntity(column)\n\t}\n\n\tcrunch := NewCrunchGame(config, board)\n\n\tlevel.AddEntity(crunch)\n\n\tgame.Screen().SetLevel(level)\n\tgame.Start()\n}\n\n\/\/ Color is the a color in a crunch game.\ntype Color uint8\n\n\/\/ Color constants with special significance.\nconst (\n\tColorNone Color = iota\n\tColorMulti\n\tColorBomb\n\tColorPlayer\n\tColorBug\n)\n\n\/\/ ColorMap maps game colors to their actual representation in a terminal.\ntype ColorMap interface {\n\tColor(Color) termloop.Attr\n}\n\n\/\/ SetCellColor sets the foreground of c according to a color map\nfunc SetCellColor(c *termloop.Cell, m ColorMap, fg Color) {\n\tc.Bg = termloop.ColorBlack\n\tc.Fg = m.Color(fg)\n}\n\n\/\/ SetCellColorBg sets the foreground and background of c according to a color\n\/\/ map\nfunc SetCellColorBg(c *termloop.Cell, m ColorMap, fg, bg Color) {\n\tc.Fg = m.Color(fg)\n\tc.Bg = m.Color(bg)\n}\n\n\/\/ BugType enumerates the types of possible bugs\ntype BugType uint8\n\n\/\/ BugType values that are acceptable\nconst (\n\tBugSmall BugType = iota\n\tBugLarge\n\tBugGnat\n\tBugMagic\n\tBugBomb\n)\n\n\/\/ Bug is a bug that crawls down the vines.  Bugs have distinct color.  Large\n\/\/ bugs can only eat smaller bugs of the same color.\ntype Bug struct {\n\tType   BugType\n\tColor  Color\n\tEaten  int8\n\tRune   rune\n\tentity *termloop.Entity\n}\n\n\/\/ CrunchGame contains a player, critters, a score, and other game state.\ntype CrunchGame struct {\n\tconfig     *CrunchConfig\n\tplayerPos  int\n\tplayer     *Player\n\tvines      [][]*Bug\n\trand       Rand\n\tspawnTime  time.Time\n\tmultis     map[*Bug]struct{}\n\tmultisTime time.Time\n\tlevel      *termloop.BaseLevel\n}\n\n\/\/ NewCrunchGame initializes a new CrunchGame.\nfunc NewCrunchGame(config *CrunchConfig, level *termloop.BaseLevel) *CrunchGame {\n\tg := &CrunchGame{\n\t\tconfig: config,\n\t\trand:   defaultRand(),\n\t\tmultis: make(map[*Bug]struct{}),\n\t\tlevel:  level,\n\t}\n\tg.vines = make([][]*Bug, config.NumCol)\n\tfor i := range g.vines {\n\t\tg.vines[i] = make([]*Bug, 0, config.ColDepth+1)\n\t}\n\n\tg.playerPos = config.NumCol\n\tg.player = &Player{\n\t\tentity: termloop.NewEntity(g.colX(g.playerPos), g.config.boardSize().Y, 1, 1),\n\t\tlevel:  level,\n\t}\n\tg.player.entity.SetCell(0, 0, g.player.cell())\n\tg.level.AddEntity(g.player.entity)\n\n\treturn g\n}\n\nfunc (g *CrunchGame) colX(i int) int {\n\tif i >= g.config.NumCol {\n\t\treturn g.config.boardSize().X\n\t}\n\treturn 1 + g.config.ColSpace + i*(g.config.ColSpace+1+g.config.CritterSizeLarge\/2)\n}\n\nfunc defaultRand() Rand {\n\treturn rand.New(rand.NewSource(time.Now().UnixNano()))\n}\n\nfunc (g *CrunchGame) gameOver() bool {\n\tfor i := range g.vines {\n\t\tif len(g.vines[i]) >= g.config.NumCol {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (g *CrunchGame) randomColorBug(n int) Color {\n\treturn ColorBug + Color(g.rand.Intn(n))\n}\n\nfunc (g *CrunchGame) randomBug() *Bug {\n\troll := g.rand.Intn(100) + 1\n\n\troll -= 30\n\tif roll < 0 {\n\t\treturn g.createBug(BugSmall, g.randomColorBug(2))\n\t}\n\n\troll -= 30\n\tif roll < 0 {\n\t\treturn g.createBug(BugLarge, g.randomColorBug(2))\n\t}\n\n\troll -= 30\n\tif roll < 0 {\n\t\treturn g.createBug(BugGnat, ColorNone)\n\t}\n\n\troll -= 8\n\tif roll < 0 {\n\t\treturn g.createBug(BugBomb, ColorBomb)\n\t}\n\n\treturn g.createBug(BugMagic, ColorMulti)\n}\n\nfunc (g *CrunchGame) createBug(typ BugType, c Color) *Bug {\n\tb := &Bug{\n\t\tType:  typ,\n\t\tColor: c,\n\t}\n\tb.Rune = g.assignRune(b)\n\treturn b\n}\n\nfunc (g *CrunchGame) assignRune(bug *Bug) rune {\n\tswitch bug.Type {\n\tcase BugSmall:\n\t\tif bug.Eaten > 0 {\n\t\t\treturn '⊛'\n\t\t}\n\t\treturn 'o'\n\tcase BugLarge:\n\t\tif bug.Eaten > 0 {\n\t\t\treturn '@'\n\t\t}\n\t\treturn 'O'\n\tcase BugGnat:\n\t\tconst gnats = \"`'~\"\n\t\treturn rune(gnats[g.rand.Intn(len(gnats))])\n\tcase BugBomb:\n\t\tif bug.Eaten > 0 {\n\t\t\treturn '&'\n\t\t}\n\t\treturn '8'\n\tcase BugMagic:\n\t\tif bug.Eaten > 0 {\n\t\t\treturn '*'\n\t\t}\n\t\treturn '+'\n\t}\n\treturn 'x'\n}\n\nfunc (g *CrunchGame) spawnBugs() {\n\t\/\/ for now we do something simple and spawn bugs in all rows simultaneously\n\tfor i := range g.vines {\n\t\tg.vines[i] = g.vines[i][:len(g.vines[i])+1]\n\t\tcopy(g.vines[i][1:], g.vines[i][0:]) \/\/ shift bugs \"down\"\n\t\tg.vines[i][0] = g.randomBug()\n\t\tg.vines[i][0].entity = termloop.NewEntity(0, 0, 1, 1)\n\t\tif g.vines[i][0].Color == ColorMulti {\n\t\t\tg.multis[g.vines[i][0]] = struct{}{}\n\t\t\tg.vines[i][0].entity.SetCell(0, 0, &termloop.Cell{\n\t\t\t\tFg: defaultColorMap.Color(g.randMultiColor()),\n\t\t\t\tCh: g.vines[i][0].Rune,\n\t\t\t})\n\t\t} else {\n\t\t\tg.vines[i][0].entity.SetCell(0, 0, &termloop.Cell{\n\t\t\t\tFg: defaultColorMap.Color(g.vines[i][0].Color),\n\t\t\t\tCh: g.vines[i][0].Rune,\n\t\t\t})\n\t\t}\n\t\tg.level.AddEntity(g.vines[i][0].entity)\n\t\tcx := g.colX(i)\n\t\tsize := g.config.boardSize()\n\t\tfor j := range g.vines[i] {\n\t\t\ty := size.Y\n\t\t\tif j < g.config.ColDepth {\n\t\t\t\ty = 1 + j\n\t\t\t}\n\t\t\tg.vines[i][j].entity.SetPosition(cx, y)\n\t\t}\n\t}\n}\n\nfunc (g *CrunchGame) assignMultiColors() {\n\tfor bug := range g.multis {\n\t\tcolor := ColorBomb\n\t\tswitch g.rand.Intn(3) {\n\t\tcase 0:\n\t\t\tcolor = ColorBug + 0\n\t\tcase 1:\n\t\t\tcolor = ColorBug + 1\n\t\t}\n\t\tcell := &termloop.Cell{\n\t\t\tFg: defaultColorMap.Color(color),\n\t\t\tCh: bug.Rune,\n\t\t}\n\t\tbug.entity.SetCell(0, 0, cell)\n\t}\n}\n\nfunc (g *CrunchGame) randMultiColor() Color {\n\tswitch g.rand.Intn(3) {\n\tcase 0:\n\t\treturn ColorBug + 0\n\tcase 1:\n\t\treturn ColorBug + 1\n\t}\n\treturn ColorBomb\n}\n\n\/\/ Draw implements termloop.Drawable\nfunc (g *CrunchGame) Draw(screen *termloop.Screen) {\n\tdefer g.level.Draw(screen)\n\n\tnow := time.Now()\n\n\ttwinkle := true\n\n\tif g.gameOver() {\n\t\t\/\/ TODO: do something here\n\t} else {\n\t\tif now.Sub(g.spawnTime) > 2*time.Second {\n\t\t\tg.spawnTime = now\n\t\t\tg.spawnBugs()\n\t\t}\n\t}\n\tif twinkle && now.Sub(g.multisTime) > 100*time.Millisecond {\n\t\tg.multisTime = now\n\t\tg.assignMultiColors()\n\t}\n}\n\nfunc (g *CrunchGame) grabBug(i int) bool {\n\tif i >= g.config.NumCol {\n\t\treturn false\n\t}\n\tif len(g.vines[i]) == 0 {\n\t\treturn false\n\t}\n\tg.player.contains = g.vines[i][len(g.vines[i])-1]\n\tg.vines[i] = g.vines[i][:len(g.vines[i])-1]\n\tg.level.RemoveEntity(g.player.contains.entity)\n\treturn true\n}\n\nfunc (g *CrunchGame) bugEats(i int, other *Bug) bool {\n\tif i >= g.config.NumCol {\n\t\treturn false\n\t}\n\tbottom := g.vines[i][len(g.vines[i])-1]\n\teats := false\n\t\/\/ Determine if the bottom bug can eat the bug being spit.  Large bugs eat\n\t\/\/ small bugs.  Small bugs eat gnats.  Magic bug and bomb bugs eat\n\t\/\/ anything.\n\tswitch bottom.Type {\n\tcase BugLarge:\n\t\tif other.Type == BugSmall && other.Color == bottom.Color {\n\t\t\teats = true\n\t\t}\n\tcase BugSmall:\n\t\tif other.Type == BugGnat {\n\t\t\teats = true\n\t\t}\n\tcase BugMagic, BugBomb:\n\t\teats = true\n\t}\n\n\tif !eats {\n\t\treturn false\n\t}\n\n\tbottom.Eaten++\n\t\/\/ TODO: begin to trigger the chain reaction if necessary.\n\n\treturn true\n}\n\nfunc (g *CrunchGame) spitBug(i int) bool {\n\tif i >= g.config.NumCol {\n\t\treturn false\n\t}\n\tif len(g.vines[i]) >= g.config.ColDepth {\n\t\treturn false\n\t}\n\n\tspat := g.player.contains\n\tg.player.contains = nil\n\n\tif !g.bugEats(i, spat) {\n\t\tg.vines[i] = g.vines[i][:len(g.vines[i])+1]\n\t\tg.vines[i][len(g.vines[i])-1] = spat\n\t\tspat.entity.SetPosition(g.colX(i), len(g.vines[i]))\n\t\tg.level.AddEntity(spat.entity)\n\t}\n\n\treturn true\n}\n\n\/\/ Tick implements termloop.Drawable\nfunc (g *CrunchGame) Tick(event termloop.Event) {\n\tif g.gameOver() {\n\t\treturn\n\t}\n\n\tif event.Type == termloop.EventKey { \/\/ Is it a keyboard event?\n\t\tswitch event.Ch { \/\/ If so, switch on the pressed key.\n\t\tcase 'l':\n\t\t\tif g.playerPos < g.config.NumCol {\n\t\t\t\tg.playerPos++\n\t\t\t\tg.player.entity.SetPosition(g.colX(g.playerPos), g.config.boardSize().Y)\n\t\t\t}\n\t\tcase 'h':\n\t\t\tif g.playerPos > 0 {\n\t\t\t\tg.playerPos--\n\t\t\t\tg.player.entity.SetPosition(g.colX(g.playerPos), g.config.boardSize().Y)\n\t\t\t}\n\t\tcase 'k':\n\t\t\tif g.player.contains != nil {\n\t\t\t\tif g.spitBug(g.playerPos) {\n\t\t\t\t\tg.player.entity.SetCell(0, 0, g.player.cell())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif g.grabBug(g.playerPos) {\n\t\t\t\t\tg.player.entity.SetCell(0, 0, g.player.cell())\n\t\t\t\t}\n\t\t\t}\n\t\tcase 'j':\n\t\t\t\/\/ TODO: puke on the side of the screen when your buddy is around\n\t\t}\n\t}\n}\n\n\/\/ Player is a player in a CrunchGame\ntype Player struct {\n\tconfig   *CrunchConfig\n\tentity   *termloop.Entity\n\tcontains *Bug \/\/ any contained bug will have its entity removed\n\tprevX    int\n\tprevY    int\n\tlevel    *termloop.BaseLevel\n}\n\n\/\/ Draw implements termloop.Drawable\nfunc (p *Player) Draw(screen *termloop.Screen) {\n\tp.entity.Draw(screen)\n}\n\nfunc (p Player) cell() *termloop.Cell {\n\tcell := &termloop.Cell{}\n\tif p.contains != nil {\n\t\tcell.Ch = '@'\n\t} else {\n\t\tcell.Ch = 'O'\n\t}\n\tSetCellColor(cell, defaultColorMap, ColorPlayer)\n\treturn cell\n}\n\n\/\/ Tick implements termloop.Drawable\nfunc (p *Player) Tick(event termloop.Event) {\n\tp.entity.Tick(event)\n}\n\nvar defaultColorMap = simpleColorMap{\n\tColorNone:   termloop.ColorWhite,\n\tColorMulti:  termloop.ColorWhite, \/\/ ColorMulti is not used\n\tColorBomb:   termloop.ColorRed,\n\tColorPlayer: termloop.ColorMagenta,\n\n\tColorBug + 0: termloop.ColorYellow,\n\tColorBug + 1: termloop.ColorBlue,\n}\n\ntype simpleColorMap []termloop.Attr\n\nfunc (m simpleColorMap) Color(c Color) termloop.Attr {\n\tif len(m) == 0 {\n\t\tpanic(\"empty color map\")\n\t}\n\tif int(c) < len(m) {\n\t\treturn m[c]\n\t}\n\treturn m[ColorNone]\n}\n\nfunc cell(c rune) *termloop.Cell {\n\treturn &termloop.Cell{Ch: c}\n}\n\n\/\/ Rand wraps PRNG implementations so that behavior of randomized things can be\n\/\/ tested more easily.\ntype Rand interface {\n\tIntn(n int) int\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"github.com\/leptonyu\/goeast\/db\"\n\t\"github.com\/leptonyu\/goeast\/util\"\n\t\"os\"\n)\n\nfunc main() {\n\tport := flag.Int(\"port\", 8080, \"Web service port\")\n\tapi := flag.String(\"api\", \"api\", \"http:\/\/localhost\/$api, Also use as database name with prefix wechat_\")\n\tappid := flag.String(\"appid\", \"\", \"App id\")\n\tsecret := flag.String(\"secret\", \"\", \"App secret\")\n\ttoken := flag.String(\"token\", \"\", \"Token\")\n\tinit := flag.Bool(\"init\", false, \"Init \")\n\thelp := flag.Bool(\"h\", false, \"Help\")\n\tflag.Parse()\n\tif *help {\n\t\tflag.PrintDefaults()\n\t\tos.Exit(0)\n\t}\n\tconfig := db.NewDBConfig(*api)\n\tif *init {\n\t\tconfig.Init(*appid, *secret, *token)\n\t\tos.Exit(0)\n\t}\n\tutil.StartWeb(*port, config)\n}\n<commit_msg>WeChat<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"github.com\/leptonyu\/goeast\/db\"\n\t\"github.com\/leptonyu\/goeast\/util\"\n\t\"os\"\n)\n\nfunc main() {\n\tport := flag.Int(\"port\", 8080, \"Web service port\")\n\tapi := flag.String(\"api\", \"api\", \"http:\/\/localhost\/$api,\\n Also use as database name with prefix wechat_\")\n\tappid := flag.String(\"appid\", \"\", \"App id\")\n\tsecret := flag.String(\"secret\", \"\", \"App secret\")\n\ttoken := flag.String(\"token\", \"\", \"Token\")\n\tinit := flag.Bool(\"init\", false, \"Init \")\n\thelp := flag.Bool(\"h\", false, \"Help\")\n\tflag.Parse()\n\tif *help {\n\t\tflag.PrintDefaults()\n\t\tos.Exit(0)\n\t}\n\tconfig := db.NewDBConfig(*api)\n\tif *init {\n\t\tconfig.Init(*appid, *secret, *token)\n\t\tos.Exit(0)\n\t}\n\tutil.StartWeb(*port, config)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"flag\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/pprof\"\n\n\t\"cloud.google.com\/go\/preview\/logging\"\n\t\"github.com\/Xe\/hideyhole-site\/database\"\n\t\"github.com\/Xe\/hideyhole-site\/interop\"\n\t\"github.com\/Xe\/hideyhole-site\/oauth2\/discord\"\n\t\"github.com\/Xe\/martini-oauth2\"\n\t\"github.com\/facebookgo\/flagconfig\"\n\t\"github.com\/facebookgo\/flagenv\"\n\t\"github.com\/go-martini\/martini\"\n\t\"github.com\/martini-contrib\/csrf\"\n\t\"github.com\/martini-contrib\/sessions\"\n\t\"github.com\/yosssi\/ace\"\n\t\"github.com\/yosssi\/martini-acerender\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nvar (\n\tclientID                 = flag.String(\"discord-client-id\", \"\", \"discord oauth client id\")\n\tclientSecret             = flag.String(\"discord-client-secret\", \"\", \"discord oauth client secret\")\n\tgoogleProjectID          = flag.String(\"google-project-id\", \"\", \"google project ID\")\n\tgoogleDatastoreNamespace = flag.String(\"google-datastore-namespace\", \"hideyhole-other\", \"google datastore namespace\")\n\tport                     = flag.String(\"port\", \"3093\", \"TCP port to listen on for HTTP requests\")\n\tguildID                  = flag.String(\"guild-id\", \"\", \"guild ID for allowing membership\")\n\tcookieKey                = flag.String(\"cookie-key\", \"\", \"random cookie key\")\n\tsalt                     = flag.String(\"salt\", \"\", \"salt for any passwords or crypto stuff\")\n\tdebug                    = flag.Bool(\"debug\", false, \"add \/debug routes? pprof, etc.\")\n\n\tdiscordOAuthClient *oauth2.Config\n)\n\ntype Site struct {\n\tdb        *database.Database\n\tlogClient *logging.Client\n\tlog       *log.Logger\n}\n\n\/\/hack\nfunc init() {\n\thttp.DefaultServeMux = http.NewServeMux()\n}\n\nfunc (si *Site) populateInfo(s sessions.Session, t moauth2.Tokens) error {\n\totoken := s.Get(\"oauth2_token\")\n\tif otoken == nil {\n\t\treturn nil\n\t}\n\n\tuid := s.Get(\"uid\")\n\tif uid == nil {\n\t\tdUser, err := interop.GetOwnDiscordUser(t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ts.Set(\"uid\", dUser.ID)\n\t\ts.Set(\"username\", dUser.Username)\n\t\ts.Set(\"avatarhash\", dUser.Avatar)\n\n\t\terr = si.db.PutUser(dUser)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tguilds, err := interop.GetOwnDiscordGuilds(t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tok := false\n\n\t\tfor _, guild := range guilds {\n\t\t\tif guild.ID == *guildID {\n\t\t\t\tok = true\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !ok {\n\t\t\treturn errors.New(\"Not in target guild\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\tflagenv.Parse()\n\tflag.Parse()\n\tflagconfig.Parse()\n\n\tdiscordOAuthClient = &oauth2.Config{\n\t\tClientID:     *clientID,\n\t\tClientSecret: *clientSecret,\n\t\tEndpoint:     discord.Endpoint,\n\t\tScopes:       []string{\"identify\", \"email\", \"guilds\"},\n\t\tRedirectURL:  \"http:\/\/greedo.xeserv.us:3093\" + moauth2.PathCallback,\n\t}\n\n\tlogClient, err := logging.NewClient(context.Background(), *googleProjectID)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlogger := logClient.Logger(\n\t\t*googleDatastoreNamespace+\"_\"+martini.Env,\n\t\tlogging.CommonLabels(map[string]string{\n\t\t\t\"namespace\": *googleDatastoreNamespace,\n\t\t\t\"env\":       martini.Env,\n\t\t}),\n\t).StandardLogger(\n\t\tlogging.Default,\n\t)\n\n\tdb, err := database.Init(*googleDatastoreNamespace, *googleProjectID)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tsi := &Site{\n\t\tdb:        db,\n\t\tlogClient: logClient,\n\t\tlog:       logger,\n\t}\n\n\tm := martini.Classic()\n\tstore := sessions.NewCookieStore([]byte(*cookieKey))\n\n\tm.Use(sessions.Sessions(\"backplane.cadeyforum\", store))\n\tm.Use(acerender.Renderer(&acerender.Options{\n\t\tAceOptions: &ace.Options{\n\t\t\tBaseDir:       \"views\",\n\t\t\tDynamicReload: martini.Env == martini.Dev,\n\t\t\tFuncMap: template.FuncMap{\n\t\t\t\t\"equals\": func(a, b interface{}) bool {\n\t\t\t\t\treturn a == b\n\t\t\t\t},\n\t\t\t\t\"notequals\": func(a, b interface{}) bool {\n\t\t\t\t\treturn a != b\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}))\n\n\tm.Use(moauth2.NewOAuth2Provider(discordOAuthClient, si.populateInfo))\n\tm.Use(csrf.Generate(&csrf.Options{\n\t\tSecret:     *cookieKey,\n\t\tSessionKey: *guildID,\n\t\tErrorFunc: func(w http.ResponseWriter) {\n\t\t\thttp.Error(w, \"Bad request\", http.StatusBadRequest)\n\t\t},\n\t}))\n\tm.Use(si.populateInfo)\n\n\tm.Get(\"\/\", si.getIndex)\n\tm.Get(\"\/chat\", si.getChat)\n\tm.Get(\"\/health\", si.getHealth)\n\n\tm.Get(\"\/profile\/me\", moauth2.LoginRequired, si.getMyProfile)\n\tm.Get(\"\/profile\/:id\", moauth2.LoginRequired, si.getUserByID)\n\n\tif *debug {\n\t\tlog.Printf(\"Adding \/debug routes\")\n\t\tif martini.Env == martini.Prod {\n\t\t\tlog.Printf(\"The pprof routes are enabled in production!!! Please act with care.\")\n\t\t}\n\n\t\tm.Get(\"\/debug\/pprof\", pprof.Index)\n\t\tm.Get(\"\/debug\/pprof\/cmdline\", pprof.Cmdline)\n\t\tm.Get(\"\/debug\/pprof\/profile\", pprof.Profile)\n\t\tm.Get(\"\/debug\/pprof\/symbol\", pprof.Symbol)\n\t\tm.Post(\"\/debug\/pprof\/symbol\", pprof.Symbol)\n\t\tm.Get(\"\/debug\/pprof\/block\", pprof.Handler(\"block\").ServeHTTP)\n\t\tm.Get(\"\/debug\/pprof\/heap\", pprof.Handler(\"heap\").ServeHTTP)\n\t\tm.Get(\"\/debug\/pprof\/goroutine\", pprof.Handler(\"goroutine\").ServeHTTP)\n\t\tm.Get(\"\/debug\/pprof\/threadcreate\", pprof.Handler(\"threadcreate\").ServeHTTP)\n\t}\n\n\tm.RunOnAddr(\":\" + *port)\n}\n<commit_msg>main: parameterize oauth redirection<commit_after>package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"flag\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/pprof\"\n\n\t\"cloud.google.com\/go\/preview\/logging\"\n\t\"github.com\/Xe\/hideyhole-site\/database\"\n\t\"github.com\/Xe\/hideyhole-site\/interop\"\n\t\"github.com\/Xe\/hideyhole-site\/oauth2\/discord\"\n\t\"github.com\/Xe\/martini-oauth2\"\n\t\"github.com\/facebookgo\/flagconfig\"\n\t\"github.com\/facebookgo\/flagenv\"\n\t\"github.com\/go-martini\/martini\"\n\t\"github.com\/martini-contrib\/csrf\"\n\t\"github.com\/martini-contrib\/sessions\"\n\t\"github.com\/yosssi\/ace\"\n\t\"github.com\/yosssi\/martini-acerender\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nvar (\n\tclientID                 = flag.String(\"discord-client-id\", \"\", \"discord oauth client id\")\n\tclientSecret             = flag.String(\"discord-client-secret\", \"\", \"discord oauth client secret\")\n\tgoogleProjectID          = flag.String(\"google-project-id\", \"\", \"google project ID\")\n\tgoogleDatastoreNamespace = flag.String(\"google-datastore-namespace\", \"hideyhole-other\", \"google datastore namespace\")\n\tport                     = flag.String(\"port\", \"3093\", \"TCP port to listen on for HTTP requests\")\n\tguildID                  = flag.String(\"guild-id\", \"\", \"guild ID for allowing membership\")\n\tcookieKey                = flag.String(\"cookie-key\", \"\", \"random cookie key\")\n\tsalt                     = flag.String(\"salt\", \"\", \"salt for any passwords or crypto stuff\")\n\tdebug                    = flag.Bool(\"debug\", false, \"add \/debug routes? pprof, etc.\")\n\tdomain                   = flag.String(\"domain\", \"localhost:3093\", \"redirect URL base for OAuth\")\n\n\tdiscordOAuthClient *oauth2.Config\n)\n\ntype Site struct {\n\tdb        *database.Database\n\tlogClient *logging.Client\n\tlog       *log.Logger\n}\n\n\/\/hack\nfunc init() {\n\thttp.DefaultServeMux = http.NewServeMux()\n}\n\nfunc (si *Site) populateInfo(s sessions.Session, t moauth2.Tokens) error {\n\totoken := s.Get(\"oauth2_token\")\n\tif otoken == nil {\n\t\treturn nil\n\t}\n\n\tuid := s.Get(\"uid\")\n\tif uid == nil {\n\t\tdUser, err := interop.GetOwnDiscordUser(t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ts.Set(\"uid\", dUser.ID)\n\t\ts.Set(\"username\", dUser.Username)\n\t\ts.Set(\"avatarhash\", dUser.Avatar)\n\n\t\terr = si.db.PutUser(dUser)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tguilds, err := interop.GetOwnDiscordGuilds(t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tok := false\n\n\t\tfor _, guild := range guilds {\n\t\t\tif guild.ID == *guildID {\n\t\t\t\tok = true\n\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !ok {\n\t\t\treturn errors.New(\"Not in target guild\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\tflagenv.Parse()\n\tflag.Parse()\n\tflagconfig.Parse()\n\n\tdiscordOAuthClient = &oauth2.Config{\n\t\tClientID:     *clientID,\n\t\tClientSecret: *clientSecret,\n\t\tEndpoint:     discord.Endpoint,\n\t\tScopes:       []string{\"identify\", \"email\", \"guilds\"},\n\t\tRedirectURL:  *domain + moauth2.PathCallback,\n\t}\n\n\tlogClient, err := logging.NewClient(context.Background(), *googleProjectID)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlogger := logClient.Logger(\n\t\t*googleDatastoreNamespace+\"_\"+martini.Env,\n\t\tlogging.CommonLabels(map[string]string{\n\t\t\t\"namespace\": *googleDatastoreNamespace,\n\t\t\t\"env\":       martini.Env,\n\t\t}),\n\t).StandardLogger(\n\t\tlogging.Default,\n\t)\n\n\tdb, err := database.Init(*googleDatastoreNamespace, *googleProjectID)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tsi := &Site{\n\t\tdb:        db,\n\t\tlogClient: logClient,\n\t\tlog:       logger,\n\t}\n\n\tm := martini.Classic()\n\tstore := sessions.NewCookieStore([]byte(*cookieKey))\n\n\tm.Use(sessions.Sessions(\"backplane.cadeyforum\", store))\n\tm.Use(acerender.Renderer(&acerender.Options{\n\t\tAceOptions: &ace.Options{\n\t\t\tBaseDir:       \"views\",\n\t\t\tDynamicReload: martini.Env == martini.Dev,\n\t\t\tFuncMap: template.FuncMap{\n\t\t\t\t\"equals\": func(a, b interface{}) bool {\n\t\t\t\t\treturn a == b\n\t\t\t\t},\n\t\t\t\t\"notequals\": func(a, b interface{}) bool {\n\t\t\t\t\treturn a != b\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}))\n\n\tm.Use(moauth2.NewOAuth2Provider(discordOAuthClient, si.populateInfo))\n\tm.Use(csrf.Generate(&csrf.Options{\n\t\tSecret:     *cookieKey,\n\t\tSessionKey: *guildID,\n\t\tErrorFunc: func(w http.ResponseWriter) {\n\t\t\thttp.Error(w, \"Bad request\", http.StatusBadRequest)\n\t\t},\n\t}))\n\tm.Use(si.populateInfo)\n\n\tm.Get(\"\/\", si.getIndex)\n\tm.Get(\"\/chat\", si.getChat)\n\tm.Get(\"\/health\", si.getHealth)\n\n\tm.Get(\"\/profile\/me\", moauth2.LoginRequired, si.getMyProfile)\n\tm.Get(\"\/profile\/:id\", moauth2.LoginRequired, si.getUserByID)\n\n\tif *debug {\n\t\tlog.Printf(\"Adding \/debug routes\")\n\t\tif martini.Env == martini.Prod {\n\t\t\tlog.Printf(\"The pprof routes are enabled in production!!! Please act with care.\")\n\t\t}\n\n\t\tm.Get(\"\/debug\/pprof\", pprof.Index)\n\t\tm.Get(\"\/debug\/pprof\/cmdline\", pprof.Cmdline)\n\t\tm.Get(\"\/debug\/pprof\/profile\", pprof.Profile)\n\t\tm.Get(\"\/debug\/pprof\/symbol\", pprof.Symbol)\n\t\tm.Post(\"\/debug\/pprof\/symbol\", pprof.Symbol)\n\t\tm.Get(\"\/debug\/pprof\/block\", pprof.Handler(\"block\").ServeHTTP)\n\t\tm.Get(\"\/debug\/pprof\/heap\", pprof.Handler(\"heap\").ServeHTTP)\n\t\tm.Get(\"\/debug\/pprof\/goroutine\", pprof.Handler(\"goroutine\").ServeHTTP)\n\t\tm.Get(\"\/debug\/pprof\/threadcreate\", pprof.Handler(\"threadcreate\").ServeHTTP)\n\t}\n\n\tm.RunOnAddr(\":\" + *port)\n}\n<|endoftext|>"}
{"text":"<commit_before>package ami\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ Socket holds the socket client connection data.\ntype Socket struct {\n\tconn     net.Conn\n\tincoming chan string\n\tshutdown chan struct{}\n\twg       sync.WaitGroup\n}\n\n\/\/ NewSocket provides a new socket client, connecting to a tcp server.\nfunc NewSocket(ctx context.Context, address string) (*Socket, error) {\n\tvar dialer net.Dialer\n\tconn, err := dialer.DialContext(ctx, \"tcp\", address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts := &Socket{\n\t\tconn:     conn,\n\t\tincoming: make(chan string, 32),\n\t\tshutdown: make(chan struct{}),\n\t}\n\ts.run(ctx, conn)\n\treturn s, nil\n}\n\n\/\/ Connected returns the socket status, true for connected,\n\/\/ false for disconnected.\nfunc (s *Socket) Connected() bool {\n\treturn s.conn != nil\n}\n\n\/\/ Close closes socket connection.\nfunc (s *Socket) Close(ctx context.Context) error {\n\tclose(s.shutdown)\n\n\t\/\/ wait for shutdown of run process\n\tdone := make(chan struct{})\n\tgo func() {\n\t\ts.wg.Wait()\n\t\tclose(done)\n\t}()\n\n\tselect {\n\tcase <-done:\n\tcase <-time.NewTimer(150 * time.Millisecond).C:\n\tcase <-ctx.Done():\n\t\treturn s.terminate()\n\t}\n\treturn nil\n}\n\n\/\/ Send sends data to socket using fprintf format.\nfunc (s *Socket) Send(message string) error {\n\t_, err := fmt.Fprintf(s.conn, message)\n\treturn err\n}\n\n\/\/ Recv receives a string from socket server.\nfunc (s *Socket) Recv(ctx context.Context) (string, error) {\n\tvar buffer bytes.Buffer\n\tfor {\n\t\tselect {\n\t\tcase msg, ok := <-s.incoming:\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbuffer.WriteString(msg)\n\t\t\tif strings.HasSuffix(buffer.String(), \"\\r\\n\") {\n\t\t\t\treturn buffer.String(), nil\n\t\t\t}\n\t\tcase <-s.shutdown:\n\t\tcase <-ctx.Done():\n\t\t\treturn buffer.String(), io.EOF\n\t\t}\n\t}\n}\n\nfunc (s *Socket) run(ctx context.Context, conn net.Conn) {\n\ts.wg.Add(1)\n\tgo func() {\n\t\tdefer s.wg.Done()\n\t\treader := bufio.NewReader(conn)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-s.shutdown:\n\t\t\tcase <-ctx.Done():\n\t\t\t\ts.terminate()\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tmsg, err := reader.ReadString('\\n')\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ts.incoming <- msg\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (s *Socket) terminate() error {\n\tif s.conn != nil {\n\t\treturn s.conn.Close()\n\t}\n\treturn nil\n}\n<commit_msg>fix: socket.Recv function doesn't returns error when connection is lost (#33)<commit_after>package ami\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ Socket holds the socket client connection data.\ntype Socket struct {\n\tconn     net.Conn\n\tincoming chan string\n\tshutdown chan struct{}\n\terrors   chan error\n\twg       sync.WaitGroup\n}\n\n\/\/ NewSocket provides a new socket client, connecting to a tcp server.\nfunc NewSocket(ctx context.Context, address string) (*Socket, error) {\n\tvar dialer net.Dialer\n\tconn, err := dialer.DialContext(ctx, \"tcp\", address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts := &Socket{\n\t\tconn:     conn,\n\t\tincoming: make(chan string, 32),\n\t\tshutdown: make(chan struct{}),\n\t\terrors:   make(chan error),\n\t}\n\ts.run(ctx, conn)\n\treturn s, nil\n}\n\n\/\/ Connected returns the socket status, true for connected,\n\/\/ false for disconnected.\nfunc (s *Socket) Connected() bool {\n\treturn s.conn != nil\n}\n\n\/\/ Close closes socket connection.\nfunc (s *Socket) Close(ctx context.Context) error {\n\tclose(s.shutdown)\n\n\t\/\/ wait for shutdown of run process\n\tdone := make(chan struct{})\n\tgo func() {\n\t\ts.wg.Wait()\n\t\tclose(done)\n\t}()\n\n\tselect {\n\tcase <-done:\n\t\treturn s.terminate()\n\tcase <-time.NewTimer(150 * time.Millisecond).C:\n\t\treturn s.terminate()\n\tcase <-ctx.Done():\n\t\treturn s.terminate()\n\t}\n}\n\n\/\/ Send sends data to socket using fprintf format.\nfunc (s *Socket) Send(message string) error {\n\t_, err := fmt.Fprintf(s.conn, message)\n\treturn err\n}\n\n\/\/ Recv receives a string from socket server.\nfunc (s *Socket) Recv(ctx context.Context) (string, error) {\n\tvar buffer bytes.Buffer\n\tfor {\n\t\tselect {\n\t\tcase msg, ok := <-s.incoming:\n\t\t\tif !ok {\n\t\t\t\treturn buffer.String(), io.EOF\n\t\t\t}\n\t\t\tbuffer.WriteString(msg)\n\t\t\tif strings.HasSuffix(buffer.String(), \"\\r\\n\") {\n\t\t\t\treturn buffer.String(), nil\n\t\t\t}\n\t\tcase err := <-s.errors:\n\t\t\treturn buffer.String(), err\n\t\tcase <-s.shutdown:\n\t\t\treturn buffer.String(), io.EOF\n\t\tcase <-ctx.Done():\n\t\t\treturn buffer.String(), io.EOF\n\t\t}\n\t}\n}\n\nfunc (s *Socket) run(ctx context.Context, conn net.Conn) {\n\ts.wg.Add(1)\n\tgo func() {\n\t\tdefer s.wg.Done()\n\t\treader := bufio.NewReader(conn)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-s.shutdown:\n\t\t\t\ts.terminate()\n\t\t\t\treturn\n\t\t\tcase <-ctx.Done():\n\t\t\t\ts.terminate()\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tmsg, err := reader.ReadString('\\n')\n\t\t\t\tif err != nil {\n\t\t\t\t\ts.errors <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ts.incoming <- msg\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (s *Socket) terminate() error {\n\tif s.conn != nil {\n\t\treturn s.conn.Close()\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jipiboily\/forwardlytics\/integrations\"\n\n\t_ \"github.com\/jipiboily\/forwardlytics\/integrations\/drip\"\n\t_ \"github.com\/jipiboily\/forwardlytics\/integrations\/intercom\"\n\t_ \"github.com\/jipiboily\/forwardlytics\/integrations\/keen\"\n\t_ \"github.com\/jipiboily\/forwardlytics\/integrations\/mixpanel\"\n)\n\nfunc main() {\n\tif os.Getenv(\"FORWARDLYTICS_API_KEY\") == \"\" {\n\t\tlog.Fatal(\"You need to set FORWARDLYTICS_API_KEY\")\n\t}\n\n\thttp.HandleFunc(\"\/identify\", identifyHandler)\n\tlog.Println(\"Forwardlytics started on port 8080\")\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n\n}\n\nfunc identifyHandler(w http.ResponseWriter, r *http.Request) {\n\t\/\/ This is the soonest we can do that, pretty much at least.\n\treceivedAt := time.Now().Unix()\n\n\t\/\/ This endpoint is a POST, everything else be a 404\n\tif r.Method != \"POST\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\t\/\/ API key validation. Should be moved to a middleware.\n\tapiKey := r.Header.Get(\"FORWARDLYTICS_API_KEY\")\n\tif apiKey != os.Getenv(\"FORWARDLYTICS_API_KEY\") {\n\t\tlog.Printf(\"Wrong API key. We had '%s' but it should be '%s'\\n\", apiKey, os.Getenv(\"FORWARDLYTICS_API_KEY\"))\n\n\t\terrorMsg := \"Invalid API KEY. The FORWARDLYTICS_API_KEY header must be specified, with the proper API key.\"\n\t\twriteResponse(w, errorMsg, http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t\/\/ Unmarshal input JSON\n\tdecoder := json.NewDecoder(r.Body)\n\tvar event integrations.Event\n\terr := decoder.Decode(&event)\n\tif err != nil {\n\t\tlog.Println(\"Bad request:\", r.Body)\n\t\twriteResponse(w, \"Invalid request.\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tevent.ReceivedAt = receivedAt\n\n\t\/\/ Input validation\n\tmissingParameters := event.Validate()\n\tif len(missingParameters) != 0 {\n\t\tmsg := \"Missing parameters: \"\n\t\tmsg = msg + strings.Join(missingParameters, \", \") + \".\"\n\t\twriteResponse(w, msg, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Yay, it worked so far, let's send all the things to integrations!\n\tfor _, integrationName := range integrations.IntegrationList() {\n\t\tintegration := integrations.GetIntegration(integrationName)\n\t\tif integration.Enabled() {\n\t\t\tlog.Println(\"Forwarding idenitify to\", integrationName)\n\t\t\tintegration.Identify(event)\n\t\t}\n\n\t}\n\n\twriteResponse(w, \"Forwarding identify to integrations.\", http.StatusOK)\n}\n\nfunc writeResponse(w http.ResponseWriter, body string, statusCode int) {\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.WriteHeader(statusCode)\n\n\tbody = fmt.Sprintf(`{\"message\": \"%s\"}`, body)\n\tw.Write([]byte(body))\n\n}\n<commit_msg>add some error handling<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jipiboily\/forwardlytics\/integrations\"\n\n\t_ \"github.com\/jipiboily\/forwardlytics\/integrations\/drip\"\n\t_ \"github.com\/jipiboily\/forwardlytics\/integrations\/intercom\"\n\t_ \"github.com\/jipiboily\/forwardlytics\/integrations\/keen\"\n\t_ \"github.com\/jipiboily\/forwardlytics\/integrations\/mixpanel\"\n)\n\nfunc main() {\n\tif os.Getenv(\"FORWARDLYTICS_API_KEY\") == \"\" {\n\t\tlog.Fatal(\"You need to set FORWARDLYTICS_API_KEY\")\n\t}\n\n\thttp.HandleFunc(\"\/identify\", identifyHandler)\n\tlog.Println(\"Forwardlytics started on port 8080\")\n\tlog.Fatal(http.ListenAndServe(\":8080\", nil))\n\n}\n\nfunc identifyHandler(w http.ResponseWriter, r *http.Request) {\n\t\/\/ This is the soonest we can do that, pretty much at least.\n\treceivedAt := time.Now().Unix()\n\n\t\/\/ This endpoint is a POST, everything else be a 404\n\tif r.Method != \"POST\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\t\/\/ API key validation. Should be moved to a middleware.\n\tapiKey := r.Header.Get(\"FORWARDLYTICS_API_KEY\")\n\tif apiKey != os.Getenv(\"FORWARDLYTICS_API_KEY\") {\n\t\tlog.Printf(\"Wrong API key. We had '%s' but it should be '%s'\\n\", apiKey, os.Getenv(\"FORWARDLYTICS_API_KEY\"))\n\n\t\terrorMsg := \"Invalid API KEY. The FORWARDLYTICS_API_KEY header must be specified, with the proper API key.\"\n\t\twriteResponse(w, errorMsg, http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t\/\/ Unmarshal input JSON\n\tdecoder := json.NewDecoder(r.Body)\n\tvar event integrations.Event\n\terr := decoder.Decode(&event)\n\tif err != nil {\n\t\tlog.Println(\"Bad request:\", r.Body)\n\t\twriteResponse(w, \"Invalid request.\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tevent.ReceivedAt = receivedAt\n\n\t\/\/ Input validation\n\tmissingParameters := event.Validate()\n\tif len(missingParameters) != 0 {\n\t\tmsg := \"Missing parameters: \"\n\t\tmsg = msg + strings.Join(missingParameters, \", \") + \".\"\n\t\twriteResponse(w, msg, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/ Yay, it worked so far, let's send all the things to integrations!\n\tfor _, integrationName := range integrations.IntegrationList() {\n\t\tintegration := integrations.GetIntegration(integrationName)\n\t\tif integration.Enabled() {\n\t\t\tlog.Println(\"Forwarding idenitify to\", integrationName)\n\t\t\terr := integration.Identify(event)\n\t\t\tif err != nil {\n\t\t\t\terrMsg := fmt.Sprintf(\"Fatal error during identification with an integration (%s): %s\", integrationName, err)\n\t\t\t\tlog.Println(errMsg)\n\t\t\t\twriteResponse(w, errMsg, 500)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t}\n\n\twriteResponse(w, \"Forwarding identify to integrations.\", http.StatusOK)\n}\n\nfunc writeResponse(w http.ResponseWriter, body string, statusCode int) {\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.WriteHeader(statusCode)\n\n\tbody = fmt.Sprintf(`{\"message\": \"%s\"}`, body)\n\tw.Write([]byte(body))\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Author  Raido Pahtma\n\/\/ License MIT\n\npackage main\n\nimport \"fmt\"\nimport \"os\"\nimport \"os\/signal\"\nimport \"log\"\nimport \"time\"\n\nimport \"github.com\/jessevdk\/go-flags\"\nimport \"github.com\/proactivity-lab\/go-sfconnection\"\n\nconst ApplicationVersionMajor = 0\nconst ApplicationVersionMinor = 1\nconst ApplicationVersionPatch = 1\n\nvar ApplicationBuildDate string\nvar ApplicationBuildDistro string\n\nfunc main() {\n\n\tvar opts struct {\n\t\tPositional struct {\n\t\t\tConnectionString string `description:\"Connectionstring sf@HOST:PORT\"`\n\t\t} `positional-args:\"yes\"`\n\n\t\tReconnect uint `long:\"reconnect\" default:\"30\" description:\"Reconnect period, seconds\"`\n\n\t\tDebug       []bool `short:\"D\" long:\"debug\" description:\"Debug mode, print raw packets\"`\n\t\tShowVersion func() `short:\"V\" long:\"version\" description:\"Show application version\"`\n\t}\n\n\topts.ShowVersion = func() {\n\t\tif ApplicationBuildDate == \"\" {\n\t\t\tApplicationBuildDate = \"YYYY-mm-dd_HH:MM:SS\"\n\t\t}\n\t\tif ApplicationBuildDistro == \"\" {\n\t\t\tApplicationBuildDistro = \"unknown\"\n\t\t}\n\t\tfmt.Printf(\"amlistener %d.%d.%d (%s %s)\\n\", ApplicationVersionMajor, ApplicationVersionMinor, ApplicationVersionPatch, ApplicationBuildDate, ApplicationBuildDistro)\n\t\tos.Exit(0)\n\t}\n\n\t_, err := flags.Parse(&opts)\n\tif err != nil {\n\t\tfmt.Printf(\"Argument parser error: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\thost, port, err := sfconnection.ParseSfConnectionString(opts.Positional.ConnectionString)\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tdsp := sfconnection.NewMessageDispatcher(new(sfconnection.Message))\n\treceive := make(chan sfconnection.Packet)\n\tdsp.RegisterMessageSnooper(receive)\n\n\tsfc := sfconnection.NewSfConnection()\n\tsfc.AddDispatcher(dsp)\n\n\t\/\/ Configure logging\n\tlogformat := log.Ldate | log.Ltime | log.Lmicroseconds\n\tvar logger *log.Logger\n\tif len(opts.Debug) > 0 {\n\t\tif len(opts.Debug) > 1 {\n\t\t\tlogformat = logformat | log.Lshortfile\n\t\t}\n\t\tlogger = log.New(os.Stdout, \"INFO:  \", logformat)\n\t\tsfc.SetDebugLogger(log.New(os.Stdout, \"DEBUG: \", logformat))\n\t\tsfc.SetInfoLogger(logger)\n\t} else {\n\t\tlogger = log.New(os.Stdout, \"\", logformat)\n\t}\n\tsfc.SetWarningLogger(log.New(os.Stdout, \"WARN:  \", logformat))\n\tsfc.SetErrorLogger(log.New(os.Stdout, \"ERROR: \", logformat))\n\n\t\/\/ Connect to the host\n\tsfc.Autoconnect(host, port, time.Duration(opts.Reconnect)*time.Second)\n\n\t\/\/ Set up signals to close nicely on Control+C\n\tsignals := make(chan os.Signal)\n\tsignal.Notify(signals, os.Interrupt, os.Kill)\n\n\tfor interrupted := false; interrupted == false; {\n\t\tselect {\n\t\tcase msg := <-receive:\n\t\t\tlogger.Printf(\"%s\\n\", msg)\n\t\tcase sig := <-signals:\n\t\t\tsignal.Stop(signals)\n\t\t\tlogger.Printf(\"signal %s\\n\", sig)\n\t\t\tsfc.Disconnect()\n\t\t\tinterrupted = true\n\t\t}\n\t}\n}\n<commit_msg>SF interfaces changed a bit.<commit_after>\/\/ Author  Raido Pahtma\n\/\/ License MIT\n\npackage main\n\nimport \"fmt\"\nimport \"os\"\nimport \"os\/signal\"\nimport \"log\"\nimport \"time\"\n\nimport \"github.com\/jessevdk\/go-flags\"\nimport \"github.com\/proactivity-lab\/go-sfconnection\"\n\nconst ApplicationVersionMajor = 0\nconst ApplicationVersionMinor = 1\nconst ApplicationVersionPatch = 2\n\nvar ApplicationBuildDate string\nvar ApplicationBuildDistro string\n\nfunc main() {\n\n\tvar opts struct {\n\t\tPositional struct {\n\t\t\tConnectionString string `description:\"Connectionstring sf@HOST:PORT\"`\n\t\t} `positional-args:\"yes\"`\n\n\t\tReconnect uint `long:\"reconnect\" default:\"30\" description:\"Reconnect period, seconds\"`\n\n\t\tDebug       []bool `short:\"D\" long:\"debug\" description:\"Debug mode, print raw packets\"`\n\t\tShowVersion func() `short:\"V\" long:\"version\" description:\"Show application version\"`\n\t}\n\n\topts.ShowVersion = func() {\n\t\tif ApplicationBuildDate == \"\" {\n\t\t\tApplicationBuildDate = \"YYYY-mm-dd_HH:MM:SS\"\n\t\t}\n\t\tif ApplicationBuildDistro == \"\" {\n\t\t\tApplicationBuildDistro = \"unknown\"\n\t\t}\n\t\tfmt.Printf(\"amlistener %d.%d.%d (%s %s)\\n\", ApplicationVersionMajor, ApplicationVersionMinor, ApplicationVersionPatch, ApplicationBuildDate, ApplicationBuildDistro)\n\t\tos.Exit(0)\n\t}\n\n\t_, err := flags.Parse(&opts)\n\tif err != nil {\n\t\tfmt.Printf(\"Argument parser error: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\thost, port, err := sfconnection.ParseSfConnectionString(opts.Positional.ConnectionString)\n\tif err != nil {\n\t\tfmt.Printf(\"ERROR: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tdsp := sfconnection.NewMessageDispatcher(sfconnection.NewMessage(0, 0))\n\treceive := make(chan *sfconnection.Message)\n\tdsp.RegisterMessageSnooper(receive)\n\n\tsfc := sfconnection.NewSfConnection()\n\tsfc.AddDispatcher(dsp)\n\n\t\/\/ Configure logging\n\tlogformat := log.Ldate | log.Ltime | log.Lmicroseconds\n\tvar logger *log.Logger\n\tif len(opts.Debug) > 0 {\n\t\tif len(opts.Debug) > 1 {\n\t\t\tlogformat = logformat | log.Lshortfile\n\t\t}\n\t\tlogger = log.New(os.Stdout, \"INFO:  \", logformat)\n\t\tsfc.SetDebugLogger(log.New(os.Stdout, \"DEBUG: \", logformat))\n\t\tsfc.SetInfoLogger(logger)\n\t} else {\n\t\tlogger = log.New(os.Stdout, \"\", logformat)\n\t}\n\tsfc.SetWarningLogger(log.New(os.Stdout, \"WARN:  \", logformat))\n\tsfc.SetErrorLogger(log.New(os.Stdout, \"ERROR: \", logformat))\n\n\t\/\/ Connect to the host\n\tsfc.Autoconnect(host, port, time.Duration(opts.Reconnect)*time.Second)\n\n\t\/\/ Set up signals to close nicely on Control+C\n\tsignals := make(chan os.Signal)\n\tsignal.Notify(signals, os.Interrupt, os.Kill)\n\n\tfor interrupted := false; interrupted == false; {\n\t\tselect {\n\t\tcase msg := <-receive:\n\t\t\tlogger.Printf(\"%s\\n\", msg)\n\t\tcase sig := <-signals:\n\t\t\tsignal.Stop(signals)\n\t\t\tlogger.Printf(\"signal %s\\n\", sig)\n\t\t\tsfc.Disconnect()\n\t\t\tinterrupted = true\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *\n * k6 - a next-generation load testing tool\n * Copyright (C) 2016 Load Impact\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\npackage main\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"gopkg.in\/urfave\/cli.v1\"\n\t\"os\"\n)\n\nfunc main() {\n\t\/\/ This won't be needed in cli v2\n\tcli.VersionFlag.Name = \"version\"\n\tcli.HelpFlag.Name = \"help\"\n\tcli.HelpFlag.Hidden = true\n\n\tapp := cli.NewApp()\n\tapp.Name = \"k6\"\n\tapp.Usage = \"a next generation load generator\"\n\tapp.Version = \"0.4.2\"\n\tapp.Commands = []cli.Command{\n\t\tcommandRun,\n\t\tcommandInspect,\n\t\tcommandStatus,\n\t\tcommandStats,\n\t\tcommandScale,\n\t\tcommandStart,\n\t\tcommandPause,\n\t}\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName:  \"verbose, v\",\n\t\t\tUsage: \"show debug messages\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"address, a\",\n\t\t\tUsage: \"address for the API\",\n\t\t\tValue: \"127.0.0.1:6565\",\n\t\t},\n\t}\n\tapp.Before = func(cc *cli.Context) error {\n\t\tgin.SetMode(gin.ReleaseMode)\n\n\t\tif cc.Bool(\"verbose\") {\n\t\t\tlog.SetLevel(log.DebugLevel)\n\t\t}\n\n\t\treturn nil\n\t}\n\tif err := app.Run(os.Args); err != nil {\n\t\tos.Exit(1)\n\t}\n}\n<commit_msg>[release] v0.4.3<commit_after>\/*\n *\n * k6 - a next-generation load testing tool\n * Copyright (C) 2016 Load Impact\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n *\n *\/\n\npackage main\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"gopkg.in\/urfave\/cli.v1\"\n\t\"os\"\n)\n\nfunc main() {\n\t\/\/ This won't be needed in cli v2\n\tcli.VersionFlag.Name = \"version\"\n\tcli.HelpFlag.Name = \"help\"\n\tcli.HelpFlag.Hidden = true\n\n\tapp := cli.NewApp()\n\tapp.Name = \"k6\"\n\tapp.Usage = \"a next generation load generator\"\n\tapp.Version = \"0.4.3\"\n\tapp.Commands = []cli.Command{\n\t\tcommandRun,\n\t\tcommandInspect,\n\t\tcommandStatus,\n\t\tcommandStats,\n\t\tcommandScale,\n\t\tcommandStart,\n\t\tcommandPause,\n\t}\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName:  \"verbose, v\",\n\t\t\tUsage: \"show debug messages\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"address, a\",\n\t\t\tUsage: \"address for the API\",\n\t\t\tValue: \"127.0.0.1:6565\",\n\t\t},\n\t}\n\tapp.Before = func(cc *cli.Context) error {\n\t\tgin.SetMode(gin.ReleaseMode)\n\n\t\tif cc.Bool(\"verbose\") {\n\t\t\tlog.SetLevel(log.DebugLevel)\n\t\t}\n\n\t\treturn nil\n\t}\n\tif err := app.Run(os.Args); err != nil {\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"math\/rand\"\n\t\"time\"\n\t\"html\/template\"\n\t\/\/\"io\/ioutil\"\n\n\n)\n\nvar (\n\tmandrillApiUrl string\n\tmandrillKey    string\n\tcasgoDestination string\n\tcasgoAPIKey string\n)\n\nfunc main() {\n\n\tif os.Getenv(\"CASGO_API_KEY\") == \"\" {\n\t\tlog.Println(\"Generating Random API Key...\")\n\t\tcasgoAPIKey = GenerateAPIKey(20)\n\t\tlog.Println(\"CASGO_API_KEY:\",getKey())\n\t}else{\n\t\tcasgoAPIKey = os.Getenv(\"CASGO_API_KEY\")\n\t}\n\tport := flag.String(\"port\", \"8080\", \"HTTP Port to listen on\")\n\tflag.Parse()\n\n\tmandrillApiUrl = \"https:\/\/mandrillapp.com\/api\/1.0\/\"\n\tmandrillKey = os.Getenv(\"MANDRILL_KEY\")\n\tif mandrillKey == \"\" {\n\t\tlog.Fatal(\"MANDRILL_KEY is Crucial. Type: export MANDRILL_KEY=123456789\")\n\t\tos.Exit(1)\n\t}\n\n\n\tcasgoDestination = os.Getenv(\"CASGO_DESTINATION\")\n\tif casgoDestination == \"\" {\n\t\tlog.Fatal(\"CASGO_DESTINATION is Crucial. Type: export CASGO_DESTINATION=\\\"your@email.com\\\"\")\n\t\tos.Exit(1)\n\t}\n\n\tlog.Printf(\"Starting Server on http:\/\/127.0.0.1:%s\", *port)\n\n\n\tr := mux.NewRouter()\n\n\tr.NotFoundHandler = http.HandlerFunc(RedirectHomeHandler)\n\tr.HandleFunc(\"\/\", HomeHandler)\n\n\tr.HandleFunc(\"\/contact\", ContactHandler)\n\tr.HandleFunc(\"\/contact\/\", ContactHandler)\n\n\tr.HandleFunc(\"\/{whatever}\", LoveHandler)\n\n\tr.HandleFunc(\"\/\" + casgoAPIKey + \"\/send\", EmailHandler)\n\thttp.Handle(\"\/\", r)\n\t\/\/http.NotFound() NotFoundHandler()\n\tlog.Fatal(http.ListenAndServe(\":\"+*port, r))\n\tlog.Println(\"Switching Logs to debug.log\")\n\tOpenLog()\n\tlog.Println(\"info: Listening on\", *port)\n}\n\n\n\n\/\/ RANDOM STUFF\n\n\nfunc init() {\n\t\trand.Seed(time.Now().UnixNano())\n}\n\nvar runes = []rune(\"____ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890123456789012345678901234567890\")\n\nfunc GenerateAPIKey(n int) string {\n\t\tb := make([]rune, n)\n\t\tfor i := range b {\n\t\t\t\tb[i] = runes[rand.Intn(len(runes))]\n\t\t}\nreturn string(b)\n\n}\n\nfunc getKey() string {\n\nreturn casgoAPIKey\n\n}\n\n\n\/\/ This function opens a log file. \"debug.log\"\n\nfunc OpenLog(){\nf, err := os.OpenFile(\".\/debug.log\", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)\nif err != nil {\n    log.Fatal(\"error opening file: %v\", err)\n\t\tlog.Fatal(\"MANDRILL_KEY is Crucial.\")\n\t\tos.Exit(1)\n}\n\nlog.SetOutput(f)\n}\n\n\/\/ This is the home page it is blank. \"This server is broken\"\n\nfunc HomeHandler(w http.ResponseWriter, r *http.Request) {\n\t fmt.Fprint(w, \"Fatal Error\")\n\t\/\/ http.ServeFile(\".\/templates\/form.html\")\n}\n\n\/\/ I love lamp. This displays affection for r.URL.Path[1:]\n\nfunc LoveHandler(w http.ResponseWriter, r *http.Request) {\n\t fmt.Fprintf(w, \"I love %s!\", r.URL.Path[1:])\n\t log.Printf(\"I love %s says %s at %s\", r.URL.Path[1:], r.UserAgent(), r.RemoteAddr)\n}\n\n\/\/ Display contact form with CSRF and a Cookie. And maybe a captcha and drawbridge.\nfunc ContactHandler(w http.ResponseWriter, r *http.Request) {\n\n\t\tvar key string\n\t\t\/\/var err string\n\t\tkey = getKey()\n\t\tt, err := template.New(\"Contact\").ParseFiles(\"templates\/form.html\")\n\t\tlog.Println(err)\n\n  \/\/  t, _ := template.ParseFiles(\"templates\/form.html\")\n    \/\/ t.Execute(w, p)\n\t\tlog.Println(t.ExecuteTemplate(w, \"Contact\", key,))\n\t\t\/\/t.Execute(w, template.HTML(`<b>World<\/b>`))\n\t\/\/\terr, response = http.FileServer(http.Dir(\"\/usr\/share\/doc\"))\n    \/\/fmt.Fprint(w, \"Contact form here\")\n\t log.Printf(\"pre-contact: %s at %s\", r.UserAgent(), r.RemoteAddr)\n}\n\n\/\/ Redirect everything \/\nfunc RedirectHomeHandler(rw http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(rw, r, \"\/\", 301)\n}\n\n\n\/\/ Uses mandrillapp.com default sender address.\nfunc EmailHandler(rw http.ResponseWriter, r *http.Request) {\n\tdestination := casgoDestination\n\tvar query url.Values\n\tif r.Method == \"GET\" {\n\t\tquery = r.URL.Query()\n\t} else if r.Method == \"POST\" {\n\t\tr.ParseForm()\n\t\tquery = r.Form\n\t} else {\n\t\tfmt.Fprintln(rw, \"Please submit via GET or POST.\")\n\t}\n\tEmailSender(rw, r, destination, query)\n\n}\n\n\nfunc EmailSender(rw http.ResponseWriter, r *http.Request, destination string, query url.Values) {\n\tform := ParseQuery(query)\n\tif form.Email == \"\" {\n\t\thttp.Redirect(rw, r, \"\/\", 301)\n\t\treturn\n\t}\n\tif sendEmail(destination, form) {\n\t\tfmt.Fprintln(rw, \"0 Success! Your message has been delivered.\")\n\t\tlog.Printf(\"SUCCESS-contact: %s at %s\", r.UserAgent(), r.RemoteAddr)\n\t} else {\n\t\tlog.Printf(\"debug: %s at %s\", form, destination)\n\t\tfmt.Fprintln(rw, \"1 Uh-oh! We were unable to deliver your message. Please confirm that you entered a valid email address.\")\n\t\tlog.Printf(\"FAIL-contact: %s at %s\", r.UserAgent(), r.RemoteAddr)\n\t}\n}\n\nfunc ParseQuery(query url.Values) *Form {\n\tform := new(Form)\n\tadditionalFields := \"\"\n\tfor k, v := range query {\n\t\tk = strings.ToLower(k)\n\t\tif (k == \"email\") {\n\t\t\tform.Email = v[0]\n\t\t\/\/} else if (k == \"name\") {\n\t\t\/\/\tform.Name = v[0]\n\t\t} else if (k == \"subject\") {\n\t\t\tform.Subject = v[0]\n\t\t} else if (k == \"message\") {\n\t\t\tform.Message = k + \": \" + v[0] + \"<br>\\n\"\n\t\t} else {\n\t\t\tadditionalFields = additionalFields + k + \": \" + v[0] + \"<br>\\n\"\n\t\t}\n\t}\n\tif form.Subject == \"\" {\n\t\tform.Subject = \"You have mail!\"\n\t}\n\tif additionalFields != \"\" {\n\t\tif form.Message == \"\" {\n\t\t\tform.Message = form.Message + \"Message:\\n<br>\" + additionalFields\n\t\t} else {\n\t\t\tform.Message = form.Message + \"\\n<br>Additional:\\n<br>\" + additionalFields\n\t\t}\n\t}\n\treturn form\n}\n<commit_msg>About to add CSRF token to form<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/gorilla\/csrf\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"math\/rand\"\n\t\"time\"\n\t\"html\/template\"\n\t\/\/\"io\/ioutil\"\n\n\n)\n\nvar (\n\tmandrillApiUrl string\n\tmandrillKey    string\n\tcasgoDestination string\n\tcasgoAPIKey string\n)\n\nfunc main() {\n\n\tif os.Getenv(\"CASGO_API_KEY\") == \"\" {\n\t\tlog.Println(\"Generating Random API Key...\")\n\t\tcasgoAPIKey = GenerateAPIKey(20)\n\t\tlog.Println(\"CASGO_API_KEY:\",getKey())\n\t}else{\n\t\tcasgoAPIKey = os.Getenv(\"CASGO_API_KEY\")\n\t}\n\tport := flag.String(\"port\", \"8080\", \"HTTP Port to listen on\")\n\tflag.Parse()\n\n\tmandrillApiUrl = \"https:\/\/mandrillapp.com\/api\/1.0\/\"\n\tmandrillKey = os.Getenv(\"MANDRILL_KEY\")\n\tif mandrillKey == \"\" {\n\t\tlog.Fatal(\"MANDRILL_KEY is Crucial. Type: export MANDRILL_KEY=123456789\")\n\t\tos.Exit(1)\n\t}\n\n\n\tcasgoDestination = os.Getenv(\"CASGO_DESTINATION\")\n\tif casgoDestination == \"\" {\n\t\tlog.Fatal(\"CASGO_DESTINATION is Crucial. Type: export CASGO_DESTINATION=\\\"your@email.com\\\"\")\n\t\tos.Exit(1)\n\t}\n\n\tlog.Printf(\"Starting Server on http:\/\/127.0.0.1:%s\", *port)\n\n\n\tr := mux.NewRouter()\n\n\tr.NotFoundHandler = http.HandlerFunc(RedirectHomeHandler)\n\tr.HandleFunc(\"\/\", HomeHandler)\n\n\tr.HandleFunc(\"\/contact\", ContactHandler)\n\tr.HandleFunc(\"\/contact\/\", ContactHandler)\n\n\tr.HandleFunc(\"\/{whatever}\", LoveHandler)\n\n\tr.HandleFunc(\"\/\" + casgoAPIKey + \"\/send\", EmailHandler)\n\thttp.Handle(\"\/\", r)\n\t\/\/http.NotFound() NotFoundHandler()\n\tlog.Fatal(http.ListenAndServe(\":\"+*port, csrf.Protect([]byte(\"32-byte-long-auth-key\"))(r)))\n\tlog.Println(\"Switching Logs to debug.log\")\n\tOpenLog()\n\tlog.Println(\"info: Listening on\", *port)\n}\n\n\n\n\/\/ RANDOM STUFF\n\n\nfunc init() {\n\t\trand.Seed(time.Now().UnixNano())\n}\n\nvar runes = []rune(\"____ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890123456789012345678901234567890\")\n\nfunc GenerateAPIKey(n int) string {\n\t\tb := make([]rune, n)\n\t\tfor i := range b {\n\t\t\t\tb[i] = runes[rand.Intn(len(runes))]\n\t\t}\nreturn string(b)\n\n}\n\nfunc getKey() string {\n\nreturn casgoAPIKey\n\n}\n\n\n\/\/ This function opens a log file. \"debug.log\"\n\nfunc OpenLog(){\nf, err := os.OpenFile(\".\/debug.log\", os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)\nif err != nil {\n    log.Fatal(\"error opening file: %v\", err)\n\t\tlog.Fatal(\"MANDRILL_KEY is Crucial.\")\n\t\tos.Exit(1)\n}\n\nlog.SetOutput(f)\n}\n\n\/\/ This is the home page it is blank. \"This server is broken\"\n\nfunc HomeHandler(w http.ResponseWriter, r *http.Request) {\n\t fmt.Fprint(w, \"Fatal Error\")\n\t\/\/ http.ServeFile(\".\/templates\/form.html\")\n}\n\n\/\/ I love lamp. This displays affection for r.URL.Path[1:]\n\nfunc LoveHandler(w http.ResponseWriter, r *http.Request) {\n\t fmt.Fprintf(w, \"I love %s!\", r.URL.Path[1:])\n\t log.Printf(\"I love %s says %s at %s\", r.URL.Path[1:], r.UserAgent(), r.RemoteAddr)\n}\n\n\/\/ Display contact form with CSRF and a Cookie. And maybe a captcha and drawbridge.\nfunc ContactHandler(w http.ResponseWriter, r *http.Request) {\n\t\t\/\/w.Header().Set(\"X-CSRF-Token\", csrf.Token(r))\n\t\tvar key string\n\t\t\/\/var err string\n\t\tkey = getKey()\n\t\tt, err := template.New(\"Contact\").ParseFiles(\"templates\/form.html\")\n\t\tlog.Println(err)\n\n  \/\/  t, _ := template.ParseFiles(\"templates\/form.html\")\n    \/\/ t.Execute(w, p)\n\t\tlog.Println(t.ExecuteTemplate(w, \"Contact\", key,))\n\t\t\/\/t.Execute(w, template.HTML(`<b>World<\/b>`))\n\t\/\/\terr, response = http.FileServer(http.Dir(\"\/usr\/share\/doc\"))\n    \/\/fmt.Fprint(w, \"Contact form here\")\n\t log.Printf(\"pre-contact: %s at %s\", r.UserAgent(), r.RemoteAddr)\n}\n\n\/\/ Redirect everything \/\nfunc RedirectHomeHandler(rw http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(rw, r, \"\/\", 301)\n}\n\n\n\/\/ Uses mandrillapp.com default sender address.\nfunc EmailHandler(rw http.ResponseWriter, r *http.Request) {\n\tdestination := casgoDestination\n\tvar query url.Values\n\tif r.Method == \"GET\" {\n\t\tquery = r.URL.Query()\n\t} else if r.Method == \"POST\" {\n\t\tr.ParseForm()\n\t\tquery = r.Form\n\t} else {\n\t\tfmt.Fprintln(rw, \"Please submit via GET or POST.\")\n\t}\n\tEmailSender(rw, r, destination, query)\n\n}\n\n\nfunc EmailSender(rw http.ResponseWriter, r *http.Request, destination string, query url.Values) {\n\tform := ParseQuery(query)\n\tif form.Email == \"\" {\n\t\thttp.Redirect(rw, r, \"\/\", 301)\n\t\treturn\n\t}\n\tif sendEmail(destination, form) {\n\t\tfmt.Fprintln(rw, \"0 Success! Your message has been delivered.\")\n\t\tlog.Printf(\"SUCCESS-contact: %s at %s\", r.UserAgent(), r.RemoteAddr)\n\t} else {\n\t\tlog.Printf(\"debug: %s at %s\", form, destination)\n\t\tfmt.Fprintln(rw, \"1 Uh-oh! We were unable to deliver your message. Please confirm that you entered a valid email address.\")\n\t\tlog.Printf(\"FAIL-contact: %s at %s\", r.UserAgent(), r.RemoteAddr)\n\t}\n}\n\nfunc ParseQuery(query url.Values) *Form {\n\tform := new(Form)\n\tadditionalFields := \"\"\n\tfor k, v := range query {\n\t\tk = strings.ToLower(k)\n\t\tif (k == \"email\") {\n\t\t\tform.Email = v[0]\n\t\t\/\/} else if (k == \"name\") {\n\t\t\/\/\tform.Name = v[0]\n\t\t} else if (k == \"subject\") {\n\t\t\tform.Subject = v[0]\n\t\t} else if (k == \"message\") {\n\t\t\tform.Message = k + \": \" + v[0] + \"<br>\\n\"\n\t\t} else {\n\t\t\tadditionalFields = additionalFields + k + \": \" + v[0] + \"<br>\\n\"\n\t\t}\n\t}\n\tif form.Subject == \"\" {\n\t\tform.Subject = \"You have mail!\"\n\t}\n\tif additionalFields != \"\" {\n\t\tif form.Message == \"\" {\n\t\t\tform.Message = form.Message + \"Message:\\n<br>\" + additionalFields\n\t\t} else {\n\t\t\tform.Message = form.Message + \"\\n<br>Additional:\\n<br>\" + additionalFields\n\t\t}\n\t}\n\treturn form\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"os\"\n\n\t\"github.com\/rebuy-de\/aws-nuke\/v2\/cmd\"\n)\n\ntype NukeParameters struct {\n\tConfigPath string\n\n\tProfile         string\n\tAccessKeyID     string\n\tSecretAccessKey string\n\n\tNoDryRun   bool\n\tForce      bool\n\tForceSleep int\n\tQuiet      bool\n\n\tMaxWaitRetries int\n}\n\nfunc main() {\n\tif err := cmd.NewRootCommand().Execute(); err != nil {\n\t\tos.Exit(-1)\n\t}\n}\n<commit_msg>Remove unused type NukeParameters in main.go (#822)<commit_after>package main\n\nimport (\n\t\"os\"\n\n\t\"github.com\/rebuy-de\/aws-nuke\/v2\/cmd\"\n)\n\nfunc main() {\n\tif err := cmd.NewRootCommand().Execute(); err != nil {\n\t\tos.Exit(-1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/evolsnow\/robot\/conn\"\n\t\"golang.org\/x\/net\/websocket\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n)\n\nfunc main() {\n\tvar configFile string\n\tvar debug bool\n\tflag.StringVar(&configFile, \"c\", \"config.json\", \"specify config file\")\n\tflag.BoolVar(&debug, \"d\", false, \"debug mode\")\n\n\tflag.Parse()\n\tconfig, err := ParseConfig(configFile)\n\tif err != nil {\n\t\tlog.Fatal(\"a vailid json config file must exist\")\n\t}\n\n\tredisPort := strconv.Itoa(config.RedisPort)\n\tredisServer := net.JoinHostPort(config.RedisAddress, redisPort)\n\tif !conn.Ping(redisServer, config.RedisPassword) {\n\t\tlog.Fatal(\"connect to redis server failed\")\n\t}\n\tconn.Pool = conn.NewPool(redisServer, config.RedisPassword, config.RedisDB)\n\trobot := newRobot(config.RobotToken, config.RobotName, config.WebHookUrl)\n\trobot.bot.Debug = debug\n\tgo robot.run()\n\tsrvPort := strconv.Itoa(config.Port)\n\thttp.HandleFunc(\"\/ajax\", ajax)\n\thttp.Handle(\"\/websocket\", websocket.Handler(socketHandler))\n\t\/\/\tlog.Fatal(http.ListenAndServe(net.JoinHostPort(config.Server, srvPort), nil))\n\tlog.Fatal(http.ListenAndServeTLS(net.JoinHostPort(config.Server, srvPort), config.Cert, config.CertKey, nil))\n\n}\n\n\/\/used for web samaritan robot\nfunc socketHandler(ws *websocket.Conn) {\n\tfor {\n\t\tvar in, response string\n\t\tvar ret []string\n\t\tsf := func(c rune) bool {\n\t\t\treturn c == ',' || c == '，' || c == ';' || c == '。' || c == '.' || c == '？' || c == '?'\n\t\t}\n\t\tif err := websocket.Message.Receive(ws, &in); err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"Received: %s\\n\", in)\n\t\tzh := false\n\t\tfor _, r := range in {\n\t\t\tif unicode.Is(unicode.Scripts[\"Han\"], r) {\n\t\t\t\tlog.Printf(in)\n\t\t\t\tzh = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif zh {\n\t\t\tresponse = tlAI(in)\n\t\t\t\/\/ Separate into fields with func.\n\t\t\tret = strings.FieldsFunc(response, sf)\n\n\t\t} else {\n\t\t\tresponse = mitAI(in)\n\t\t\tret = strings.FieldsFunc(response, sf)\n\t\t}\n\t\tfor i := range ret {\n\t\t\twebsocket.Message.Send(ws, ret[i])\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t\twebsocket.Message.Send(ws, \"\")\n\t}\n}\nfunc ajax(w http.ResponseWriter, r *http.Request) {\n\tvar messages = make(chan string)\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\tbody := r.FormValue(\"text\")\n\tif body != \"\" {\n\t\tgo func(string) {\n\t\t\tret := receive(body)\n\t\t\tfor i := range ret {\n\t\t\t\tmessages <- ret[i]\n\t\t\t}\n\n\t\t}(body)\n\t}\n\tio.WriteString(w, <-messages)\n}\n\nfunc receive(in string) (ret []string) {\n\tif in == \"\" {\n\t\treturn\n\t}\n\tfmt.Printf(\"Received: %s\\n\", in)\n\tvar response string\n\tsf := func(c rune) bool {\n\t\treturn c == ',' || c == '，' || c == ';' || c == '。' || c == '.' || c == '？' || c == '?'\n\t}\n\tzh := false\n\tfor _, r := range in {\n\t\tif unicode.Is(unicode.Scripts[\"Han\"], r) {\n\t\t\tlog.Printf(in)\n\t\t\tzh = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif zh {\n\t\tresponse = tlAI(in)\n\t\t\/\/ Separate into fields with func.\n\t\tret = strings.FieldsFunc(response, sf)\n\n\t} else {\n\t\tresponse = mitAI(in)\n\t\tret = strings.FieldsFunc(response, sf)\n\t}\n\treturn\n}\n<commit_msg>GET or POST<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/evolsnow\/robot\/conn\"\n\t\"golang.org\/x\/net\/websocket\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n)\n\nvar messages = make(chan string)\n\nfunc main() {\n\tvar configFile string\n\tvar debug bool\n\tflag.StringVar(&configFile, \"c\", \"config.json\", \"specify config file\")\n\tflag.BoolVar(&debug, \"d\", false, \"debug mode\")\n\n\tflag.Parse()\n\tconfig, err := ParseConfig(configFile)\n\tif err != nil {\n\t\tlog.Fatal(\"a vailid json config file must exist\")\n\t}\n\n\tredisPort := strconv.Itoa(config.RedisPort)\n\tredisServer := net.JoinHostPort(config.RedisAddress, redisPort)\n\tif !conn.Ping(redisServer, config.RedisPassword) {\n\t\tlog.Fatal(\"connect to redis server failed\")\n\t}\n\tconn.Pool = conn.NewPool(redisServer, config.RedisPassword, config.RedisDB)\n\trobot := newRobot(config.RobotToken, config.RobotName, config.WebHookUrl)\n\trobot.bot.Debug = debug\n\tgo robot.run()\n\tsrvPort := strconv.Itoa(config.Port)\n\thttp.HandleFunc(\"\/ajax\", ajax)\n\thttp.Handle(\"\/websocket\", websocket.Handler(socketHandler))\n\t\/\/\tlog.Fatal(http.ListenAndServe(net.JoinHostPort(config.Server, srvPort), nil))\n\tlog.Fatal(http.ListenAndServeTLS(net.JoinHostPort(config.Server, srvPort), config.Cert, config.CertKey, nil))\n\n}\n\n\/\/used for web samaritan robot\nfunc socketHandler(ws *websocket.Conn) {\n\tfor {\n\t\tvar in, response string\n\t\tvar ret []string\n\t\tsf := func(c rune) bool {\n\t\t\treturn c == ',' || c == '，' || c == ';' || c == '。' || c == '.' || c == '？' || c == '?'\n\t\t}\n\t\tif err := websocket.Message.Receive(ws, &in); err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"Received: %s\\n\", in)\n\t\tzh := false\n\t\tfor _, r := range in {\n\t\t\tif unicode.Is(unicode.Scripts[\"Han\"], r) {\n\t\t\t\tlog.Printf(in)\n\t\t\t\tzh = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif zh {\n\t\t\tresponse = tlAI(in)\n\t\t\t\/\/ Separate into fields with func.\n\t\t\tret = strings.FieldsFunc(response, sf)\n\n\t\t} else {\n\t\t\tresponse = mitAI(in)\n\t\t\tret = strings.FieldsFunc(response, sf)\n\t\t}\n\t\tfor i := range ret {\n\t\t\twebsocket.Message.Send(ws, ret[i])\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t\twebsocket.Message.Send(ws, \"\")\n\t}\n}\nfunc ajax(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\n\tif r.Method == \"GET\" {\n\t\tio.WriteString(w, <-messages)\n\n\t} else {\n\t\tbody := r.FormValue(\"text\")\n\t\tif body != \"\" {\n\t\t\tgo func(string) {\n\t\t\t\tret := receive(body)\n\t\t\t\tfor i := range ret {\n\t\t\t\t\tmessages <- ret[i]\n\t\t\t\t}\n\n\t\t\t}(body)\n\t\t}\n\t}\n}\n\nfunc receive(in string) (ret []string) {\n\tfmt.Printf(\"Received: %s\\n\", in)\n\tvar response string\n\tsf := func(c rune) bool {\n\t\treturn c == ',' || c == '，' || c == ';' || c == '。' || c == '.' || c == '？' || c == '?'\n\t}\n\tzh := false\n\tfor _, r := range in {\n\t\tif unicode.Is(unicode.Scripts[\"Han\"], r) {\n\t\t\tlog.Printf(in)\n\t\t\tzh = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif zh {\n\t\tresponse = tlAI(in)\n\t\t\/\/ Separate into fields with func.\n\t\tret = strings.FieldsFunc(response, sf)\n\n\t} else {\n\t\tresponse = mitAI(in)\n\t\tret = strings.FieldsFunc(response, sf)\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"compress\/gzip\"\n\t\"encoding\/csv\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/nishanths\/fullstory\"\n\n\t\"github.com\/fullstorydev\/hauser\/config\"\n\t\"github.com\/fullstorydev\/hauser\/warehouse\"\n)\n\nvar (\n\tconf               *config.Config\n\tcurrentBackoffStep = uint(0)\n\tbundleFieldsMap    = warehouse.BundleFields()\n)\n\n\/\/ Record represents a single export row in the export file\ntype Record map[string]interface{}\n\ntype ExportProcessor func(warehouse.Warehouse, *fullstory.Client, []fullstory.ExportMeta) (int, error)\n\n\/\/ TransformExportJSONRecord transforms the record map (extracted from the API response json) to a\n\/\/ slice of strings. The slice of strings contains values in the same order as the existing export table.\n\/\/ For existing export table fields that do not exist in the json record, an empty string is populated.\nfunc TransformExportJSONRecord(wh warehouse.Warehouse, rec map[string]interface{}) ([]string, error) {\n\tvar line []string\n\t\/\/ Change all record keys to lower case. We do this because columns are case insensitive for most warehouse solutions.\n\trec = getRecordWithLowerCaseKeys(rec)\n\n\t\/\/ Map of CustomVars\n\tcustomVarsMap := make(map[string]interface{})\n\tfor key, val := range rec {\n\t\tif field, ok := bundleFieldsMap[key]; !ok {\n\t\t\tcustomVarsMap[field.Name] = val\n\t\t}\n\t}\n\n\t\/\/ Fetch the table columns so can build the csv with a column order that matches the export table\n\ttableColumns := wh.GetExportTableColumns()\n\tfor _, col := range tableColumns {\n\t\tfield, isPartOfExportBundle := bundleFieldsMap[col]\n\n\t\t\/\/ These are columns in the export table that we are not going to populate\n\t\tif !isPartOfExportBundle {\n\t\t\tline = append(line, \"\")\n\t\t\tcontinue;\n\t\t}\n\n\t\tif field.IsCustomVar {\n\t\t\tcustomVars, err := json.Marshal(customVarsMap)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tline = append(line, string(customVars))\n\t\t} else {\n\t\t\tif val, valExists := rec[col]; valExists {\n\t\t\t\tline = append(line, wh.ValueToString(val, field.IsTime))\n\t\t\t} else {\n\t\t\t\tline = append(line, \"\")\n\t\t\t}\n\t\t}\n\t}\n\treturn line, nil\n}\n\nfunc ProcessExportsSince(wh warehouse.Warehouse, since time.Time, exportProcessor ExportProcessor) (int, error) {\n\tlog.Printf(\"Checking for new export files since %s\", since)\n\n\tfs := fullstory.NewClient(conf.FsApiToken)\n\tif conf.ExportURL != \"\" {\n\t\tfs.Config.BaseURL = conf.ExportURL\n\t}\n\texports, err := fs.ExportList(since)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to fetch export list: %s\", err)\n\t\treturn 0, err\n\t}\n\n\treturn exportProcessor(wh, fs, exports)\n}\n\n\/\/ ProcessFilesIndividually iterates over the list of available export files and processes them one by one, until an error\n\/\/ occurs, or until they are all processed.\nfunc ProcessFilesIndividually(wh warehouse.Warehouse, fs *fullstory.Client, exports []fullstory.ExportMeta) (int, error) {\n\tfor _, e := range exports {\n\t\tlog.Printf(\"Processing bundle %d (start: %s, end: %s)\", e.ID, e.Start.UTC(), e.Stop.UTC())\n\t\tfilename := filepath.Join(conf.TmpDir, fmt.Sprintf(\"%d.csv\", e.ID))\n\t\tmark := time.Now()\n\t\toutfile, err := os.Create(filename)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to create tmp file: %s\", err)\n\t\t\treturn 0, err\n\t\t}\n\t\tdefer os.Remove(filename)\n\t\tdefer outfile.Close()\n\t\tcsvOut := csv.NewWriter(outfile)\n\n\t\trecordCount, err := WriteBundleToCSV(fs, e.ID, csvOut, wh)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tif err := LoadBundles(wh, filename, e); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tlog.Printf(\"Processing of bundle %d (%d records) took %s\", e.ID, recordCount,\n\t\t\ttime.Since(mark))\n\t}\n\n\t\/\/ return how many files were processed\n\treturn len(exports), nil\n}\n\n\/\/ ProcessFilesByDay creates a single intermediate CSV file for all the export bundles on a given day.  It assumes the\n\/\/ day to be processed is the day from the first export bundle's Start value.  When all the bundles with that same day\n\/\/ have been written to the CSV file, it is loaded to the warehouse, and the function quits without attempting to\n\/\/ process remaining bundles (they'll get picked up on the next call to ProcessExportsSince)\nfunc ProcessFilesByDay(wh warehouse.Warehouse, fs *fullstory.Client, exports []fullstory.ExportMeta) (int, error) {\n\tif len(exports) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tlog.Printf(\"Creating group file starting with bundle %d (start: %s)\", exports[0].ID, exports[0].Start.UTC())\n\tfilename := filepath.Join(conf.TmpDir, fmt.Sprintf(\"%d-%s.csv\", exports[0].ID, exports[0].Start.UTC().Format(\"20060102\")))\n\tmark := time.Now()\n\toutfile, err := os.Create(filename)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to create tmp file: %s\", err)\n\t\treturn 0, err\n\t}\n\tdefer os.Remove(filename)\n\tdefer outfile.Close()\n\tcsvOut := csv.NewWriter(outfile)\n\n\tvar processedBundles []fullstory.ExportMeta\n\tvar totalRecords int\n\tgroupDay := exports[0].Start.UTC().Truncate(24 * time.Hour)\n\tfor _, e := range exports {\n\t\tif !groupDay.Equal(e.Start.UTC().Truncate(24 * time.Hour)) {\n\t\t\tbreak\n\t\t}\n\n\t\trecordCount, err := WriteBundleToCSV(fs, e.ID, csvOut, wh)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tlog.Printf(\"Wrote bundle %d (%d records, start: %s, stop: %s)\", e.ID, recordCount, e.Start.UTC(), e.Stop.UTC())\n\t\ttotalRecords += recordCount\n\t\tprocessedBundles = append(processedBundles, e)\n\t}\n\n\tif err := LoadBundles(wh, filename, processedBundles...); err != nil {\n\t\treturn 0, err\n\t}\n\n\tlog.Printf(\"Processing of %d bundles (%d records) took %s\", len(processedBundles), totalRecords,\n\t\ttime.Since(mark))\n\n\t\/\/ return how many files were processed\n\treturn len(processedBundles), nil\n}\n\nfunc LoadBundles (wh warehouse.Warehouse, filename string, bundles ...fullstory.ExportMeta) error {\n\tvar objPath string\n\tvar err error\n\tif objPath, err = wh.UploadFile(filename); err != nil {\n\t\tlog.Printf(wh.GetUploadFailedMsg(filename, err))\n\t\treturn err\n\t}\n\n\tif wh.IsUploadOnly() {\n\t\treturn nil\n\t}\n\n\tdefer wh.DeleteFile(objPath)\n\n\tif err := wh.LoadToWarehouse(objPath, bundles...); err != nil {\n\t\tlog.Printf(\"Failed to load file '%s' to warehouse: %s\", filename, err)\n\t\treturn err\n\t}\n\n\t\/\/ If we've already copied in the data but fail to save the sync point, we're\n\t\/\/ still okay - the next call to LastSyncPoint() will see that there are export\n\t\/\/ records beyond the sync point and remove them - ie, we will reprocess the\n\t\/\/ current export file\n\tif err := wh.SaveSyncPoints(bundles...); err != nil {\n\t\tlog.Printf(\"Failed to save sync points for bundles ending with %d: %s\", bundles[len(bundles)].ID, err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ WriteBundleToCSV writes the bundle corresponding to the given bundleID to the csv Writer\nfunc WriteBundleToCSV(fs *fullstory.Client, bundleID int, csvOut *csv.Writer, wh warehouse.Warehouse) (numRecords int, err error) {\n\tstream, err := fs.ExportData(bundleID)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to fetch bundle %d: %s\", bundleID, err)\n\t\treturn 0, err\n\t}\n\tdefer stream.Close()\n\n\tgzstream, err := gzip.NewReader(stream)\n\tif err != nil {\n\t\tlog.Printf(\"Failed gzip reader: %s\", err)\n\t\treturn 0, err\n\t}\n\n\tdecoder := json.NewDecoder(gzstream)\n\tdecoder.UseNumber()\n\n\t\/\/ skip array open delimiter\n\tif _, err := decoder.Token(); err != nil {\n\t\tlog.Printf(\"Failed json decode of array open token: %s\", err)\n\t\treturn 0, err\n\t}\n\n\tvar recordCount int\n\tfor decoder.More() {\n\t\tvar r Record\n\t\tif err := decoder.Decode(&r); err != nil {\n\t\t\tlog.Printf(\"failed json decode of record: %s\", err)\n\t\t\treturn recordCount, err\n\t\t}\n\t\tline, err := TransformExportJSONRecord(wh, r)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed object transform, bundle %d; skipping record. %s\", bundleID, err)\n\t\t\tcontinue\n\t\t}\n\t\tcsvOut.Write(line)\n\t\trecordCount++\n\t}\n\n\tif _, err := decoder.Token(); err != nil {\n\t\tlog.Printf(\"Failed json decode of array close token: %s\", err)\n\t\treturn recordCount, err\n\t}\n\n\tcsvOut.Flush()\n\treturn recordCount, nil\n}\n\nfunc BackoffOnError(err error) bool {\n\tif err != nil {\n\t\tif currentBackoffStep == uint(conf.BackoffStepsMax) {\n\t\t\tlog.Fatalf(\"Reached max retries; exiting\")\n\t\t}\n\t\tdur := conf.Backoff.Duration * (1 << currentBackoffStep)\n\t\tlog.Printf(\"Pausing; will retry operation in %s\", dur)\n\t\ttime.Sleep(dur)\n\t\tcurrentBackoffStep++\n\t\treturn true\n\t}\n\tcurrentBackoffStep = 0\n\treturn false\n}\n\nfunc getRecordWithLowerCaseKeys(rec map[string]interface{}) map[string]interface{} {\n\tm := make(map[string]interface{})\n\tfor k, v := range rec {\n\t\tm[strings.ToLower(k)] = v\n\t}\n\treturn m\n}\n\nfunc main() {\n\tconffile := flag.String(\"c\", \"config.toml\", \"configuration file\")\n\tflag.Parse()\n\n\tvar err error\n\tif conf, err = config.Load(*conffile); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\texportProcessor := ProcessFilesIndividually\n\tif conf.GroupFilesByDay {\n\t\texportProcessor = ProcessFilesByDay\n\t}\n\n\tvar wh warehouse.Warehouse\n\tswitch conf.Warehouse {\n\tcase \"redshift\":\n\t\twh = warehouse.NewRedshift(conf)\n\tcase \"bigquery\":\n\t\twh = warehouse.NewBigQuery(conf)\n\tdefault:\n\t\tif len(conf.Warehouse) == 0 {\n\t\t\tlog.Fatal(\"Warehouse type must be specified in configuration\")\n\t\t} else {\n\t\t\tlog.Fatalf(\"Warehouse type '%s' unrecognized\", conf.Warehouse)\n\t\t}\n\t}\n\n\tif err := wh.EnsureCompatibleExportTable(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor {\n\t\tlastSyncedRecord, err := wh.LastSyncPoint()\n\t\tif BackoffOnError(err) {\n\t\t\tcontinue\n\t\t}\n\n\t\tnumBundles, err := ProcessExportsSince(wh, lastSyncedRecord, exportProcessor)\n\t\tif BackoffOnError(err) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ if we processed any bundles, there may be more - check until nothing comes back\n\t\tif numBundles > 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Printf(\"No exports pending; sleeping %s\", conf.CheckInterval.Duration)\n\t\ttime.Sleep(conf.CheckInterval.Duration)\n\t}\n}\n<commit_msg>Reduce warehouse DB calls by figuring out the export table columns once<commit_after>package main\n\nimport (\n\t\"compress\/gzip\"\n\t\"encoding\/csv\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/nishanths\/fullstory\"\n\n\t\"github.com\/fullstorydev\/hauser\/config\"\n\t\"github.com\/fullstorydev\/hauser\/warehouse\"\n)\n\nvar (\n\tconf               *config.Config\n\tcurrentBackoffStep = uint(0)\n\tbundleFieldsMap    = warehouse.BundleFields()\n)\n\n\/\/ Record represents a single export row in the export file\ntype Record map[string]interface{}\n\ntype ExportProcessor func(warehouse.Warehouse, []string, *fullstory.Client, []fullstory.ExportMeta) (int, error)\n\n\/\/ TransformExportJSONRecord transforms the record map (extracted from the API response json) to a\n\/\/ slice of strings. The slice of strings contains values in the same order as the existing export table.\n\/\/ For existing export table fields that do not exist in the json record, an empty string is populated.\nfunc TransformExportJSONRecord(wh warehouse.Warehouse, tableColumns []string, rec map[string]interface{}) ([]string, error) {\n\tvar line []string\n\t\/\/ Change all record keys to lower case. We do this because columns are case insensitive for most warehouse solutions.\n\trec = getRecordWithLowerCaseKeys(rec)\n\n\t\/\/ Map of CustomVars\n\tcustomVarsMap := make(map[string]interface{})\n\tfor key, val := range rec {\n\t\tif field, ok := bundleFieldsMap[key]; !ok {\n\t\t\tcustomVarsMap[field.Name] = val\n\t\t}\n\t}\n\n\t\/\/ Fetch the table columns so can build the csv with a column order that matches the export table\n\tfor _, col := range tableColumns {\n\t\tfield, isPartOfExportBundle := bundleFieldsMap[col]\n\n\t\t\/\/ These are columns in the export table that we are not going to populate\n\t\tif !isPartOfExportBundle {\n\t\t\tline = append(line, \"\")\n\t\t\tcontinue;\n\t\t}\n\n\t\tif field.IsCustomVar {\n\t\t\tcustomVars, err := json.Marshal(customVarsMap)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tline = append(line, string(customVars))\n\t\t} else {\n\t\t\tif val, valExists := rec[col]; valExists {\n\t\t\t\tline = append(line, wh.ValueToString(val, field.IsTime))\n\t\t\t} else {\n\t\t\t\tline = append(line, \"\")\n\t\t\t}\n\t\t}\n\t}\n\treturn line, nil\n}\n\nfunc ProcessExportsSince(wh warehouse.Warehouse, tableColumns []string, since time.Time, exportProcessor ExportProcessor) (int, error) {\n\tlog.Printf(\"Checking for new export files since %s\", since)\n\n\tfs := fullstory.NewClient(conf.FsApiToken)\n\tif conf.ExportURL != \"\" {\n\t\tfs.Config.BaseURL = conf.ExportURL\n\t}\n\texports, err := fs.ExportList(since)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to fetch export list: %s\", err)\n\t\treturn 0, err\n\t}\n\n\treturn exportProcessor(wh, tableColumns, fs, exports)\n}\n\n\/\/ ProcessFilesIndividually iterates over the list of available export files and processes them one by one, until an error\n\/\/ occurs, or until they are all processed.\nfunc ProcessFilesIndividually(wh warehouse.Warehouse, tableColumns []string, fs *fullstory.Client, exports []fullstory.ExportMeta) (int, error) {\n\tfor _, e := range exports {\n\t\tlog.Printf(\"Processing bundle %d (start: %s, end: %s)\", e.ID, e.Start.UTC(), e.Stop.UTC())\n\t\tfilename := filepath.Join(conf.TmpDir, fmt.Sprintf(\"%d.csv\", e.ID))\n\t\tmark := time.Now()\n\t\toutfile, err := os.Create(filename)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed to create tmp file: %s\", err)\n\t\t\treturn 0, err\n\t\t}\n\t\tdefer os.Remove(filename)\n\t\tdefer outfile.Close()\n\t\tcsvOut := csv.NewWriter(outfile)\n\n\t\trecordCount, err := WriteBundleToCSV(fs, e.ID, tableColumns, csvOut, wh)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tif err := LoadBundles(wh, filename, e); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tlog.Printf(\"Processing of bundle %d (%d records) took %s\", e.ID, recordCount,\n\t\t\ttime.Since(mark))\n\t}\n\n\t\/\/ return how many files were processed\n\treturn len(exports), nil\n}\n\n\/\/ ProcessFilesByDay creates a single intermediate CSV file for all the export bundles on a given day.  It assumes the\n\/\/ day to be processed is the day from the first export bundle's Start value.  When all the bundles with that same day\n\/\/ have been written to the CSV file, it is loaded to the warehouse, and the function quits without attempting to\n\/\/ process remaining bundles (they'll get picked up on the next call to ProcessExportsSince)\nfunc ProcessFilesByDay(wh warehouse.Warehouse, tableColumns []string, fs *fullstory.Client, exports []fullstory.ExportMeta) (int, error) {\n\tif len(exports) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tlog.Printf(\"Creating group file starting with bundle %d (start: %s)\", exports[0].ID, exports[0].Start.UTC())\n\tfilename := filepath.Join(conf.TmpDir, fmt.Sprintf(\"%d-%s.csv\", exports[0].ID, exports[0].Start.UTC().Format(\"20060102\")))\n\tmark := time.Now()\n\toutfile, err := os.Create(filename)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to create tmp file: %s\", err)\n\t\treturn 0, err\n\t}\n\tdefer os.Remove(filename)\n\tdefer outfile.Close()\n\tcsvOut := csv.NewWriter(outfile)\n\n\tvar processedBundles []fullstory.ExportMeta\n\tvar totalRecords int\n\tgroupDay := exports[0].Start.UTC().Truncate(24 * time.Hour)\n\tfor _, e := range exports {\n\t\tif !groupDay.Equal(e.Start.UTC().Truncate(24 * time.Hour)) {\n\t\t\tbreak\n\t\t}\n\n\t\trecordCount, err := WriteBundleToCSV(fs, e.ID, tableColumns, csvOut, wh)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tlog.Printf(\"Wrote bundle %d (%d records, start: %s, stop: %s)\", e.ID, recordCount, e.Start.UTC(), e.Stop.UTC())\n\t\ttotalRecords += recordCount\n\t\tprocessedBundles = append(processedBundles, e)\n\t}\n\n\tif err := LoadBundles(wh, filename, processedBundles...); err != nil {\n\t\treturn 0, err\n\t}\n\n\tlog.Printf(\"Processing of %d bundles (%d records) took %s\", len(processedBundles), totalRecords,\n\t\ttime.Since(mark))\n\n\t\/\/ return how many files were processed\n\treturn len(processedBundles), nil\n}\n\nfunc LoadBundles (wh warehouse.Warehouse, filename string, bundles ...fullstory.ExportMeta) error {\n\tvar objPath string\n\tvar err error\n\tif objPath, err = wh.UploadFile(filename); err != nil {\n\t\tlog.Printf(wh.GetUploadFailedMsg(filename, err))\n\t\treturn err\n\t}\n\n\tif wh.IsUploadOnly() {\n\t\treturn nil\n\t}\n\n\tdefer wh.DeleteFile(objPath)\n\n\tif err := wh.LoadToWarehouse(objPath, bundles...); err != nil {\n\t\tlog.Printf(\"Failed to load file '%s' to warehouse: %s\", filename, err)\n\t\treturn err\n\t}\n\n\t\/\/ If we've already copied in the data but fail to save the sync point, we're\n\t\/\/ still okay - the next call to LastSyncPoint() will see that there are export\n\t\/\/ records beyond the sync point and remove them - ie, we will reprocess the\n\t\/\/ current export file\n\tif err := wh.SaveSyncPoints(bundles...); err != nil {\n\t\tlog.Printf(\"Failed to save sync points for bundles ending with %d: %s\", bundles[len(bundles)].ID, err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ WriteBundleToCSV writes the bundle corresponding to the given bundleID to the csv Writer\nfunc WriteBundleToCSV(fs *fullstory.Client, bundleID int, tableColumns []string, csvOut *csv.Writer, wh warehouse.Warehouse) (numRecords int, err error) {\n\tstream, err := fs.ExportData(bundleID)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to fetch bundle %d: %s\", bundleID, err)\n\t\treturn 0, err\n\t}\n\tdefer stream.Close()\n\n\tgzstream, err := gzip.NewReader(stream)\n\tif err != nil {\n\t\tlog.Printf(\"Failed gzip reader: %s\", err)\n\t\treturn 0, err\n\t}\n\n\tdecoder := json.NewDecoder(gzstream)\n\tdecoder.UseNumber()\n\n\t\/\/ skip array open delimiter\n\tif _, err := decoder.Token(); err != nil {\n\t\tlog.Printf(\"Failed json decode of array open token: %s\", err)\n\t\treturn 0, err\n\t}\n\n\tvar recordCount int\n\tfor decoder.More() {\n\t\tvar r Record\n\t\tif err := decoder.Decode(&r); err != nil {\n\t\t\tlog.Printf(\"failed json decode of record: %s\", err)\n\t\t\treturn recordCount, err\n\t\t}\n\t\tline, err := TransformExportJSONRecord(wh, tableColumns, r)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Failed object transform, bundle %d; skipping record. %s\", bundleID, err)\n\t\t\tcontinue\n\t\t}\n\t\tcsvOut.Write(line)\n\t\trecordCount++\n\t}\n\n\tif _, err := decoder.Token(); err != nil {\n\t\tlog.Printf(\"Failed json decode of array close token: %s\", err)\n\t\treturn recordCount, err\n\t}\n\n\tcsvOut.Flush()\n\treturn recordCount, nil\n}\n\nfunc BackoffOnError(err error) bool {\n\tif err != nil {\n\t\tif currentBackoffStep == uint(conf.BackoffStepsMax) {\n\t\t\tlog.Fatalf(\"Reached max retries; exiting\")\n\t\t}\n\t\tdur := conf.Backoff.Duration * (1 << currentBackoffStep)\n\t\tlog.Printf(\"Pausing; will retry operation in %s\", dur)\n\t\ttime.Sleep(dur)\n\t\tcurrentBackoffStep++\n\t\treturn true\n\t}\n\tcurrentBackoffStep = 0\n\treturn false\n}\n\nfunc getRecordWithLowerCaseKeys(rec map[string]interface{}) map[string]interface{} {\n\tm := make(map[string]interface{})\n\tfor k, v := range rec {\n\t\tm[strings.ToLower(k)] = v\n\t}\n\treturn m\n}\n\nfunc main() {\n\tconffile := flag.String(\"c\", \"config.toml\", \"configuration file\")\n\tflag.Parse()\n\n\tvar err error\n\tif conf, err = config.Load(*conffile); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\texportProcessor := ProcessFilesIndividually\n\tif conf.GroupFilesByDay {\n\t\texportProcessor = ProcessFilesByDay\n\t}\n\n\tvar wh warehouse.Warehouse\n\tswitch conf.Warehouse {\n\tcase \"redshift\":\n\t\twh = warehouse.NewRedshift(conf)\n\tcase \"bigquery\":\n\t\twh = warehouse.NewBigQuery(conf)\n\tdefault:\n\t\tif len(conf.Warehouse) == 0 {\n\t\t\tlog.Fatal(\"Warehouse type must be specified in configuration\")\n\t\t} else {\n\t\t\tlog.Fatalf(\"Warehouse type '%s' unrecognized\", conf.Warehouse)\n\t\t}\n\t}\n\n\tif err := wh.EnsureCompatibleExportTable(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ NB: We SHOULD fetch the table columns ONLY after the call to EnsureCompatibleExportTable.\n\t\/\/ The EnsureCompatibleExportTable function potentially alters the schema of the export table in the client warehouse.\n\ttableColumns := wh.GetExportTableColumns()\n\tfor {\n\t\tlastSyncedRecord, err := wh.LastSyncPoint()\n\t\tif BackoffOnError(err) {\n\t\t\tcontinue\n\t\t}\n\n\t\tnumBundles, err := ProcessExportsSince(wh, tableColumns, lastSyncedRecord, exportProcessor)\n\t\tif BackoffOnError(err) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ if we processed any bundles, there may be more - check until nothing comes back\n\t\tif numBundles > 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Printf(\"No exports pending; sleeping %s\", conf.CheckInterval.Duration)\n\t\ttime.Sleep(conf.CheckInterval.Duration)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n   \"bufio\"\n   \"fmt\"\n   \"os\"\n)\n\nfunc cat(c chan string, e chan error, quit chan struct{}) {\n   scanner := bufio.NewScanner(os.Stdin)\n   for scanner.Scan() {\n      c <- scanner.Text()\n   }\n   if err := scanner.Err(); err != nil {\n      e <- err\n   }\n   quit <- struct{}{}\n}\n\nfunc main() {\n   c := make(chan string)\n   quit := make(chan struct{})\n   err := make(chan error)\n   go cat(c, err, quit)\n   for {\n      select {\n         case x := <-c:\n            fmt.Println(x)\n         case x := <-err:\n            fmt.Fprintln(os.Stderr, \"reading standard input:\", x)\n         case <-quit:\n            return\n      }\n   }\n}\n<commit_msg>format<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc cat(c chan string, e chan error, quit chan struct{}) {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfor scanner.Scan() {\n\t\tc <- scanner.Text()\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\te <- err\n\t}\n\tquit <- struct{}{}\n}\n\nfunc main() {\n\tc := make(chan string)\n\tquit := make(chan struct{})\n\terr := make(chan error)\n\tgo cat(c, err, quit)\n\tfor {\n\t\tselect {\n\t\tcase x := <-c:\n\t\t\tfmt.Println(x)\n\t\tcase x := <-err:\n\t\t\tfmt.Fprintln(os.Stderr, \"reading standard input:\", x)\n\t\tcase <-quit:\n\t\t\treturn\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"code.google.com\/p\/go.crypto\/ssh\"\n\t\"code.google.com\/p\/gopass\"\n\t\"flag\"\n\t\"github.com\/sudharsh\/henchman\/henchman\"\n\t\"log\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\"\n)\n\nfunc currentUsername() *user.User {\n\tu, err := user.Current()\n\tif err != nil {\n\t\tpanic(\"Couldn't get current username: \" + err.Error())\n\t}\n\treturn u\n}\n\nfunc defaultKeyFile() string {\n\tu := currentUsername()\n\treturn path.Join(u.HomeDir, \".ssh\", \"id_rsa\")\n}\n\nfunc main() {\n\tusername := flag.String(\"user\", currentUsername().Username, \"User to run as\")\n\tusePassword := flag.Bool(\"password\", false, \"Use password authentication\")\n\tkeyfile := flag.String(\"private-keyfile\", defaultKeyFile(), \"Path to the keyfile\")\n\n\tflag.Parse()\n\tplanFile := flag.Arg(0)\n\tif *username == \"\" {\n\t\tos.Exit(1)\n\t}\n\n\tvar sshAuth ssh.ClientAuth\n\tvar err error\n\tif *usePassword {\n\t\tvar password string\n\t\tif password, err = gopass.GetPass(\"Password:\"); err != nil {\n\t\t\tlog.Fatalf(\"Couldn't get password: \" + err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t\tsshAuth, err = henchman.PasswordAuth(password)\n\t} else {\n\t\tsshAuth, err = henchman.ClientKeyAuth(*keyfile)\n\t}\n\tif err != nil {\n\t\tlog.Fatalf(\"SSH Auth prep failed: \" + err.Error())\n\t}\n\tconfig := &ssh.ClientConfig{\n\t\tUser: *username,\n\t\tAuth: []ssh.ClientAuth{sshAuth},\n\t}\n\n\tplan, err := henchman.ParsePlan(planFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Couldn't read the plan: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\tsem := make(chan int, 100)\n\tfor _, hostname := range plan.Hosts {\n\t\tgo func() {\n\t\t\tmachine := henchman.Machine{hostname, config}\n\t\t\tfor _, task := range plan.Tasks {\n\t\t\t\tmachine.RunTask(&task)\n\t\t\t}\n\t\t\tsem <- 1\n\t\t}()\n\t\t<-sem\n\t}\n\n}\n<commit_msg>Get all tasks first and then run each task on the machine<commit_after>package main\n\nimport (\n\t\"code.google.com\/p\/go.crypto\/ssh\"\n\t\"code.google.com\/p\/gopass\"\n\t\"flag\"\n\t\"github.com\/sudharsh\/henchman\/henchman\"\n\t\"log\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\"\n)\n\nfunc currentUsername() *user.User {\n\tu, err := user.Current()\n\tif err != nil {\n\t\tpanic(\"Couldn't get current username: \" + err.Error())\n\t}\n\treturn u\n}\n\nfunc defaultKeyFile() string {\n\tu := currentUsername()\n\treturn path.Join(u.HomeDir, \".ssh\", \"id_rsa\")\n}\n\nfunc main() {\n\tusername := flag.String(\"user\", currentUsername().Username, \"User to run as\")\n\tusePassword := flag.Bool(\"password\", false, \"Use password authentication\")\n\tkeyfile := flag.String(\"private-keyfile\", defaultKeyFile(), \"Path to the keyfile\")\n\n\tflag.Parse()\n\tplanFile := flag.Arg(0)\n\tif *username == \"\" {\n\t\tos.Exit(1)\n\t}\n\n\tvar sshAuth ssh.ClientAuth\n\tvar err error\n\tif *usePassword {\n\t\tvar password string\n\t\tif password, err = gopass.GetPass(\"Password:\"); err != nil {\n\t\t\tlog.Fatalf(\"Couldn't get password: \" + err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t\tsshAuth, err = henchman.PasswordAuth(password)\n\t} else {\n\t\tsshAuth, err = henchman.ClientKeyAuth(*keyfile)\n\t}\n\tif err != nil {\n\t\tlog.Fatalf(\"SSH Auth prep failed: \" + err.Error())\n\t}\n\tconfig := &ssh.ClientConfig{\n\t\tUser: *username,\n\t\tAuth: []ssh.ClientAuth{sshAuth},\n\t}\n\n\tplan, err := henchman.ParsePlan(planFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Couldn't read the plan: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\tsem := make(chan int, 100)\n\tfor _, task := range plan.Tasks {\n\t\tfor _, hostname := range plan.Hosts {\n\t\t\tgo func() {\n\t\t\t\tmachine := henchman.Machine{hostname, config}\n\t\t\t\tmachine.RunTask(&task)\n\t\t\t\tsem <- 1\n\t\t\t}()\n\t\t\t<- sem\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/jessevdk\/go-flags\"\n\n\t\"github.com\/ivanilves\/lstags\/auth\"\n\t\"github.com\/ivanilves\/lstags\/docker\/jsonconfig\"\n\t\"github.com\/ivanilves\/lstags\/tag\"\n\t\"github.com\/ivanilves\/lstags\/tag\/local\"\n\t\"github.com\/ivanilves\/lstags\/tag\/registry\"\n)\n\ntype options struct {\n\tDefaultRegistry    string `short:\"r\" long:\"default-registry\" default:\"registry.hub.docker.com\" description:\"Docker registry to use by default\" env:\"DEFAULT_REGISTRY\"`\n\tUsername           string `short:\"u\" long:\"username\" default:\"\" description:\"Docker registry username\" env:\"USERNAME\"`\n\tPassword           string `short:\"p\" long:\"password\" default:\"\" description:\"Docker registry password\" env:\"PASSWORD\"`\n\tDockerJSON         string `shord:\"j\" long:\"docker-json\" default:\"~\/.docker\/config.json\" env:\"DOCKER_JSON\"`\n\tConcurrentRequests int    `short:\"c\" long:\"concurrent-requests\" default:\"32\" description:\"Limit of concurrent requests to the registry\" env:\"CONCURRENT_REQUESTS\"`\n\tPull               bool   `short:\"P\" long:\"pull\" description:\"Pull images matched by filter\" env:\"PULL\"`\n\tInsecureRegistry   bool   `short:\"i\" long:\"insecure-registry\" description:\"Use insecure plain-HTTP registriy\" env:\"INSECURE_REGISTRY\"`\n\tTraceRequests      bool   `short:\"T\" long:\"trace-requests\" description:\"Trace registry HTTP requests\" env:\"TRACE_REQUESTS\"`\n\tVersion            bool   `short:\"V\" long:\"version\" description:\"Show version and exit\"`\n\tPositional         struct {\n\t\tRepositories []string `positional-arg-name:\"REPO1 REPO2\" description:\"Docker repositories to operate on\"`\n\t} `positional-args:\"yes\"`\n}\n\nfunc suicide(err error) {\n\tfmt.Printf(\"%s\\n\", err.Error())\n\tos.Exit(1)\n}\n\nfunc getVersion() string {\n\treturn VERSION\n}\n\nfunc trimFilter(repoWithFilter string) (string, string, error) {\n\tparts := strings.Split(repoWithFilter, \"~\")\n\n\trepository := parts[0]\n\n\tif len(parts) < 2 {\n\t\treturn repository, \".*\", nil\n\t}\n\n\tif len(parts) > 2 {\n\t\treturn \"\", \"\", errors.New(\"Unable to trim filter from repository (too many '~'!): \" + repoWithFilter)\n\t}\n\n\tf := parts[1]\n\n\tif !strings.HasPrefix(f, \"\/\") || !strings.HasSuffix(f, \"\/\") {\n\t\treturn \"\", \"\", errors.New(\"Filter should be passed in a form: \/REGEXP\/\")\n\t}\n\n\tfilter := f[1 : len(f)-1]\n\n\treturn repository, filter, nil\n}\n\nfunc matchesFilter(s, filter string) bool {\n\tmatched, err := regexp.MatchString(filter, s)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn matched\n}\n\nfunc isHostname(s string) bool {\n\tif strings.Contains(s, \".\") {\n\t\treturn true\n\t}\n\n\tif strings.Contains(s, \":\") {\n\t\treturn true\n\t}\n\n\tif s == \"localhost\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc getRegistryName(repository, defaultRegistry string) string {\n\tr := strings.Split(repository, \"\/\")[0]\n\n\tif isHostname(r) {\n\t\treturn r\n\t}\n\n\treturn defaultRegistry\n}\n\nfunc assignCredentials(registry, passedUsername, passedPassword, dockerJSON string) (string, string, error) {\n\tuseDefaultDockerJSON := dockerJSON == \"~\/.docker\/config.json\"\n\tareCredentialsPassed := passedUsername != \"\" && passedPassword != \"\"\n\n\tc, err := jsonconfig.Load(dockerJSON)\n\tif err != nil {\n\t\tif useDefaultDockerJSON {\n\t\t\treturn passedUsername, passedPassword, nil\n\t\t}\n\n\t\treturn \"\", \"\", err\n\t}\n\n\tusername, password, defined := c.GetCredentials(registry)\n\tif !defined || areCredentialsPassed {\n\t\treturn passedUsername, passedPassword, nil\n\t}\n\n\treturn username, password, nil\n}\n\nfunc getAuthorization(t auth.TokenResponse) string {\n\treturn t.Method() + \" \" + t.Token()\n}\n\nfunc main() {\n\to := options{}\n\n\t_, err := flags.Parse(&o)\n\tif err != nil {\n\t\tsuicide(err)\n\t}\n\tif o.Version {\n\t\tprintln(getVersion())\n\t\tos.Exit(0)\n\t}\n\tif len(o.Positional.Repositories) == 0 {\n\t\tsuicide(errors.New(\"Need at least one repository name, e.g. 'nginx~\/^1\\\\\\\\.13\/' or 'mesosphere\/chronos'\"))\n\t}\n\n\tif o.InsecureRegistry {\n\t\tauth.WebSchema = \"http:\/\/\"\n\t\tregistry.WebSchema = \"http:\/\/\"\n\t}\n\n\tregistry.TraceRequests = o.TraceRequests\n\n\tconst format = \"%-12s %-45s %-15s %-25s %s\\n\"\n\tfmt.Printf(format, \"<STATE>\", \"<DIGEST>\", \"<(local) ID>\", \"<Created At>\", \"<TAG>\")\n\n\trepoCount := len(o.Positional.Repositories)\n\n\ttype tagResult struct {\n\t\tTags []*tag.Tag\n\t\tRepo string\n\t}\n\n\ttrc := make(chan tagResult, repoCount)\n\n\tfor _, r := range o.Positional.Repositories {\n\t\tgo func(r string, o options, trc chan tagResult) {\n\t\t\trepository, filter, err := trimFilter(r)\n\t\t\tif err != nil {\n\t\t\t\tsuicide(err)\n\t\t\t}\n\n\t\t\tregistryName := getRegistryName(repository, o.DefaultRegistry)\n\n\t\t\trepoRegistryName := registry.FormatRepoName(repository, registryName)\n\t\t\trepoLocalName := local.FormatRepoName(repository, registryName)\n\n\t\t\tusername, password, err := assignCredentials(registryName, o.Username, o.Password, o.DockerJSON)\n\t\t\tif err != nil {\n\t\t\t\tsuicide(err)\n\t\t\t}\n\n\t\t\ttresp, err := auth.NewToken(registryName, repoRegistryName, username, password)\n\t\t\tif err != nil {\n\t\t\t\tsuicide(err)\n\t\t\t}\n\n\t\t\tauthorization := getAuthorization(tresp)\n\n\t\t\tregistryTags, err := registry.FetchTags(registryName, repoRegistryName, authorization, o.ConcurrentRequests)\n\t\t\tif err != nil {\n\t\t\t\tsuicide(err)\n\t\t\t}\n\t\t\tlocalTags, err := local.FetchTags(repoLocalName)\n\t\t\tif err != nil {\n\t\t\t\tsuicide(err)\n\t\t\t}\n\n\t\t\tsortedKeys, names, joinedTags := tag.Join(registryTags, localTags)\n\n\t\t\ttags := make([]*tag.Tag, 0)\n\t\t\tfor _, key := range sortedKeys {\n\t\t\t\tname := names[key]\n\n\t\t\t\ttg := joinedTags[name]\n\n\t\t\t\tif !matchesFilter(tg.GetName(), filter) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\ttags = append(tags, tg)\n\t\t\t}\n\n\t\t\ttrc <- tagResult{Tags: tags, Repo: repoLocalName}\n\t\t}(r, o, trc)\n\t}\n\n\ttagResults := make([]tagResult, repoCount)\n\trepoNumber := 0\n\tfor tr := range trc {\n\t\trepoNumber++\n\t\ttagResults = append(tagResults, tr)\n\t\tif repoNumber >= repoCount {\n\t\t\tclose(trc)\n\t\t}\n\t}\n\n\tfor _, tr := range tagResults {\n\t\tfor _, tg := range tr.Tags {\n\t\t\tfmt.Printf(\n\t\t\t\tformat,\n\t\t\t\ttg.GetState(),\n\t\t\t\ttg.GetShortDigest(),\n\t\t\t\ttg.GetImageID(),\n\t\t\t\ttg.GetCreatedString(),\n\t\t\t\ttr.Repo+\":\"+tg.GetName(),\n\t\t\t)\n\t\t}\n\t}\n\n\tif o.Pull {\n\t\tdone := make(chan bool, repoCount)\n\n\t\tfor _, tr := range tagResults {\n\t\t\tgo func(tags []*tag.Tag, repo string, done chan bool) {\n\t\t\t\tfor _, tg := range tags {\n\t\t\t\t\tif tg.NeedsPull() {\n\t\t\t\t\t\tref := repo + \":\" + tg.GetName()\n\n\t\t\t\t\t\tfmt.Printf(\"PULLING %s\\n\", ref)\n\t\t\t\t\t\terr := local.Pull(ref)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tsuicide(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tdone <- true\n\t\t\t\t}\n\t\t\t}(tr.Tags, tr.Repo, done)\n\t\t}\n\n\t\trepoNumber := 0\n\t\tfor range done {\n\t\t\trepoNumber++\n\n\t\t\tif repoNumber >= repoCount {\n\t\t\t\tclose(done)\n\t\t\t}\n\t\t}\n\t}\n\n}\n<commit_msg>Fix fuzzy CLI help<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/jessevdk\/go-flags\"\n\n\t\"github.com\/ivanilves\/lstags\/auth\"\n\t\"github.com\/ivanilves\/lstags\/docker\/jsonconfig\"\n\t\"github.com\/ivanilves\/lstags\/tag\"\n\t\"github.com\/ivanilves\/lstags\/tag\/local\"\n\t\"github.com\/ivanilves\/lstags\/tag\/registry\"\n)\n\ntype options struct {\n\tDefaultRegistry    string `short:\"r\" long:\"default-registry\" default:\"registry.hub.docker.com\" description:\"Default Docker registry to use\" env:\"DEFAULT_REGISTRY\"`\n\tDockerJSON         string `short:\"j\" long:\"docker-json\" default:\"~\/.docker\/config.json\" description:\"JSON file with credentials (use it, please <3)\" env:\"DOCKER_JSON\"`\n\tUsername           string `short:\"u\" long:\"username\" default:\"\" description:\"Override Docker registry username (not recommended, please use JSON file)\" env:\"USERNAME\"`\n\tPassword           string `short:\"p\" long:\"password\" default:\"\" description:\"Override Docker registry password (not recommended, please use JSON file)\" env:\"PASSWORD\"`\n\tConcurrentRequests int    `short:\"c\" long:\"concurrent-requests\" default:\"32\" description:\"Limit of concurrent requests to the registry\" env:\"CONCURRENT_REQUESTS\"`\n\tPull               bool   `short:\"P\" long:\"pull\" description:\"Pull Docker images matched by filter (will use local Docker deamon)\" env:\"PULL\"`\n\tInsecureRegistry   bool   `short:\"i\" long:\"insecure-registry\" description:\"Use insecure plain-HTTP connection to registries (not recommended!)\" env:\"INSECURE_REGISTRY\"`\n\tTraceRequests      bool   `short:\"T\" long:\"trace-requests\" description:\"Trace Docker registry HTTP requests\" env:\"TRACE_REQUESTS\"`\n\tVersion            bool   `short:\"V\" long:\"version\" description:\"Show version and exit\"`\n\tPositional         struct {\n\t\tRepositories []string `positional-arg-name:\"REPO1 REPO2 REPOn\" description:\"Docker repositories to operate on, e.g.: alpine nginx~\/1\\\\.13\\\\.5$\/ busybox~\/1.27.2\/\"`\n\t} `positional-args:\"yes\" required:\"yes\"`\n}\n\nfunc suicide(err error) {\n\tfmt.Printf(\"%s\\n\", err.Error())\n\tos.Exit(1)\n}\n\nfunc getVersion() string {\n\treturn VERSION\n}\n\nfunc trimFilter(repoWithFilter string) (string, string, error) {\n\tparts := strings.Split(repoWithFilter, \"~\")\n\n\trepository := parts[0]\n\n\tif len(parts) < 2 {\n\t\treturn repository, \".*\", nil\n\t}\n\n\tif len(parts) > 2 {\n\t\treturn \"\", \"\", errors.New(\"Unable to trim filter from repository (too many '~'!): \" + repoWithFilter)\n\t}\n\n\tf := parts[1]\n\n\tif !strings.HasPrefix(f, \"\/\") || !strings.HasSuffix(f, \"\/\") {\n\t\treturn \"\", \"\", errors.New(\"Filter should be passed in a form: \/REGEXP\/\")\n\t}\n\n\tfilter := f[1 : len(f)-1]\n\n\treturn repository, filter, nil\n}\n\nfunc matchesFilter(s, filter string) bool {\n\tmatched, err := regexp.MatchString(filter, s)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn matched\n}\n\nfunc isHostname(s string) bool {\n\tif strings.Contains(s, \".\") {\n\t\treturn true\n\t}\n\n\tif strings.Contains(s, \":\") {\n\t\treturn true\n\t}\n\n\tif s == \"localhost\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc getRegistryName(repository, defaultRegistry string) string {\n\tr := strings.Split(repository, \"\/\")[0]\n\n\tif isHostname(r) {\n\t\treturn r\n\t}\n\n\treturn defaultRegistry\n}\n\nfunc assignCredentials(registry, passedUsername, passedPassword, dockerJSON string) (string, string, error) {\n\tuseDefaultDockerJSON := dockerJSON == \"~\/.docker\/config.json\"\n\tareCredentialsPassed := passedUsername != \"\" && passedPassword != \"\"\n\n\tc, err := jsonconfig.Load(dockerJSON)\n\tif err != nil {\n\t\tif useDefaultDockerJSON {\n\t\t\treturn passedUsername, passedPassword, nil\n\t\t}\n\n\t\treturn \"\", \"\", err\n\t}\n\n\tusername, password, defined := c.GetCredentials(registry)\n\tif !defined || areCredentialsPassed {\n\t\treturn passedUsername, passedPassword, nil\n\t}\n\n\treturn username, password, nil\n}\n\nfunc getAuthorization(t auth.TokenResponse) string {\n\treturn t.Method() + \" \" + t.Token()\n}\n\nfunc main() {\n\to := options{}\n\n\t_, err := flags.Parse(&o)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\tif o.Version {\n\t\tprintln(getVersion())\n\t\tos.Exit(0)\n\t}\n\tif len(o.Positional.Repositories) == 0 {\n\t\tsuicide(errors.New(\"Need at least one repository name, e.g. 'nginx~\/^1\\\\\\\\.13\/' or 'mesosphere\/chronos'\"))\n\t}\n\n\tif o.InsecureRegistry {\n\t\tauth.WebSchema = \"http:\/\/\"\n\t\tregistry.WebSchema = \"http:\/\/\"\n\t}\n\n\tregistry.TraceRequests = o.TraceRequests\n\n\tconst format = \"%-12s %-45s %-15s %-25s %s\\n\"\n\tfmt.Printf(format, \"<STATE>\", \"<DIGEST>\", \"<(local) ID>\", \"<Created At>\", \"<TAG>\")\n\n\trepoCount := len(o.Positional.Repositories)\n\n\ttype tagResult struct {\n\t\tTags []*tag.Tag\n\t\tRepo string\n\t}\n\n\ttrc := make(chan tagResult, repoCount)\n\n\tfor _, r := range o.Positional.Repositories {\n\t\tgo func(r string, o options, trc chan tagResult) {\n\t\t\trepository, filter, err := trimFilter(r)\n\t\t\tif err != nil {\n\t\t\t\tsuicide(err)\n\t\t\t}\n\n\t\t\tregistryName := getRegistryName(repository, o.DefaultRegistry)\n\n\t\t\trepoRegistryName := registry.FormatRepoName(repository, registryName)\n\t\t\trepoLocalName := local.FormatRepoName(repository, registryName)\n\n\t\t\tusername, password, err := assignCredentials(registryName, o.Username, o.Password, o.DockerJSON)\n\t\t\tif err != nil {\n\t\t\t\tsuicide(err)\n\t\t\t}\n\n\t\t\ttresp, err := auth.NewToken(registryName, repoRegistryName, username, password)\n\t\t\tif err != nil {\n\t\t\t\tsuicide(err)\n\t\t\t}\n\n\t\t\tauthorization := getAuthorization(tresp)\n\n\t\t\tregistryTags, err := registry.FetchTags(registryName, repoRegistryName, authorization, o.ConcurrentRequests)\n\t\t\tif err != nil {\n\t\t\t\tsuicide(err)\n\t\t\t}\n\t\t\tlocalTags, err := local.FetchTags(repoLocalName)\n\t\t\tif err != nil {\n\t\t\t\tsuicide(err)\n\t\t\t}\n\n\t\t\tsortedKeys, names, joinedTags := tag.Join(registryTags, localTags)\n\n\t\t\ttags := make([]*tag.Tag, 0)\n\t\t\tfor _, key := range sortedKeys {\n\t\t\t\tname := names[key]\n\n\t\t\t\ttg := joinedTags[name]\n\n\t\t\t\tif !matchesFilter(tg.GetName(), filter) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\ttags = append(tags, tg)\n\t\t\t}\n\n\t\t\ttrc <- tagResult{Tags: tags, Repo: repoLocalName}\n\t\t}(r, o, trc)\n\t}\n\n\ttagResults := make([]tagResult, repoCount)\n\trepoNumber := 0\n\tfor tr := range trc {\n\t\trepoNumber++\n\t\ttagResults = append(tagResults, tr)\n\t\tif repoNumber >= repoCount {\n\t\t\tclose(trc)\n\t\t}\n\t}\n\n\tfor _, tr := range tagResults {\n\t\tfor _, tg := range tr.Tags {\n\t\t\tfmt.Printf(\n\t\t\t\tformat,\n\t\t\t\ttg.GetState(),\n\t\t\t\ttg.GetShortDigest(),\n\t\t\t\ttg.GetImageID(),\n\t\t\t\ttg.GetCreatedString(),\n\t\t\t\ttr.Repo+\":\"+tg.GetName(),\n\t\t\t)\n\t\t}\n\t}\n\n\tif o.Pull {\n\t\tdone := make(chan bool, repoCount)\n\n\t\tfor _, tr := range tagResults {\n\t\t\tgo func(tags []*tag.Tag, repo string, done chan bool) {\n\t\t\t\tfor _, tg := range tags {\n\t\t\t\t\tif tg.NeedsPull() {\n\t\t\t\t\t\tref := repo + \":\" + tg.GetName()\n\n\t\t\t\t\t\tfmt.Printf(\"PULLING %s\\n\", ref)\n\t\t\t\t\t\terr := local.Pull(ref)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tsuicide(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tdone <- true\n\t\t\t\t}\n\t\t\t}(tr.Tags, tr.Repo, done)\n\t\t}\n\n\t\trepoNumber := 0\n\t\tfor range done {\n\t\t\trepoNumber++\n\n\t\t\tif repoNumber >= repoCount {\n\t\t\t\tclose(done)\n\t\t\t}\n\t\t}\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\t\"text\/template\"\n\n\t\"github.com\/jrperritt\/rack\/commands\/blockstoragecommands\"\n\t\"github.com\/jrperritt\/rack\/commands\/filescommands\"\n\t\"github.com\/jrperritt\/rack\/commands\/networkscommands\"\n\t\"github.com\/jrperritt\/rack\/commands\/serverscommands\"\n\t\"github.com\/jrperritt\/rack\/setup\"\n\t\"github.com\/jrperritt\/rack\/util\"\n\n\t\"github.com\/jrperritt\/rack\/internal\/github.com\/codegangsta\/cli\"\n)\n\nfunc main() {\n\tcli.HelpPrinter = printHelp\n\tcli.CommandHelpTemplate = `NAME: {{.Name}} - {{.Usage}}{{if .Description}}\n\nDESCRIPTION: {{.Description}}{{end}}{{if .Flags}}\n\nOPTIONS:\n{{range .Flags}}{{flag .}}\n{{end}}{{ end }}\n`\n\tapp := cli.NewApp()\n\tapp.Name = \"rack\"\n\tapp.Usage = Usage()\n\tapp.HideVersion = true\n\tapp.EnableBashCompletion = true\n\tapp.Commands = Cmds()\n\tapp.Before = func(c *cli.Context) error {\n\t\t\/\/fmt.Printf(\"c.Args: %+v\\n\", c.Args())\n\t\treturn nil\n\t}\n\tapp.CommandNotFound = commandNotFound\n\tapp.Run(os.Args)\n}\n\n\/\/ Usage returns, you guessed it, the usage information\nfunc Usage() string {\n\treturn \"An opinionated CLI for the Rackspace cloud\"\n}\n\n\/\/ Desc returns, you guessed it, the description\nfunc Desc() string {\n\treturn `Rack is an opinionated command-line tool that allows Rackspace users\nto accomplish tasks in a simple, idiomatic way. It seeks to provide\nflexibility through common Unix practices like piping and composability. All\ncommands have been tested against Rackspace's live API.`\n}\n\n\/\/ Cmds returns a list of commands supported by the tool\nfunc Cmds() []cli.Command {\n\treturn []cli.Command{\n\t\t{\n\t\t\tName:  \"init\",\n\t\t\tUsage: \"[Linux\/OS X only] Creates the rack man page and sets up command completion for the Bash shell.\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup.Init(c)\n\t\t\t\tman()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:   \"configure\",\n\t\t\tUsage:  \"Interactively create a config file for Rackspace authentication.\",\n\t\t\tAction: configure,\n\t\t},\n\t\t{\n\t\t\tName:   \"version\",\n\t\t\tUsage:  \"Print the version of this binary.\",\n\t\t\tAction: version,\n\t\t},\n\t\t{\n\t\t\tName:        \"servers\",\n\t\t\tUsage:       \"Operations on cloud servers, both virtual and bare metal.\",\n\t\t\tSubcommands: serverscommands.Get(),\n\t\t},\n\t\t{\n\t\t\tName:        \"files\",\n\t\t\tUsage:       \"Object storage for files and media.\",\n\t\t\tSubcommands: filescommands.Get(),\n\t\t},\n\t\t{\n\t\t\tName:        \"networks\",\n\t\t\tUsage:       \"Software-defined networking.\",\n\t\t\tSubcommands: networkscommands.Get(),\n\t\t},\n\t\t{\n\t\t\tName:        \"block-storage\",\n\t\t\tUsage:       \"Block-level storage, exposed as volumes to mount to host servers. Work with volumes and their associated snapshots.\",\n\t\t\tSubcommands: blockstoragecommands.Get(),\n\t\t},\n\t}\n}\n\nfunc printHelp(out io.Writer, templ string, data interface{}) {\n\tfuncMap := template.FuncMap{\n\t\t\"join\": strings.Join,\n\t\t\"flag\": flag,\n\t}\n\n\tw := tabwriter.NewWriter(out, 0, 8, 1, '\\t', 0)\n\tt := template.Must(template.New(\"help\").Funcs(funcMap).Parse(templ))\n\terr := t.Execute(w, data)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tw.Flush()\n}\n\nfunc flag(flag cli.Flag) string {\n\tswitch flag.(type) {\n\tcase cli.StringFlag:\n\t\tflagType := flag.(cli.StringFlag)\n\t\treturn fmt.Sprintf(\"%s\\t%s\", flagType.Name, flagType.Usage)\n\tcase cli.IntFlag:\n\t\tflagType := flag.(cli.IntFlag)\n\t\treturn fmt.Sprintf(\"%s\\t%s\", flagType.Name, flagType.Usage)\n\tcase cli.BoolFlag:\n\t\tflagType := flag.(cli.BoolFlag)\n\t\treturn fmt.Sprintf(\"%s\\t%s\", flagType.Name, flagType.Usage)\n\tcase cli.StringSliceFlag:\n\t\tflagType := flag.(cli.StringSliceFlag)\n\t\treturn fmt.Sprintf(\"%s\\t%s\", flagType.Name, flagType.Usage)\n\t}\n\treturn \"\"\n}\n\nfunc version(c *cli.Context) {\n\tfmt.Fprintf(c.App.Writer, \"%v version %v\\ncommit: %v\", c.App.Name, util.Version, util.Commit)\n}\n<commit_msg>add new line after 'rack version'<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\t\"text\/template\"\n\n\t\"github.com\/jrperritt\/rack\/commands\/blockstoragecommands\"\n\t\"github.com\/jrperritt\/rack\/commands\/filescommands\"\n\t\"github.com\/jrperritt\/rack\/commands\/networkscommands\"\n\t\"github.com\/jrperritt\/rack\/commands\/serverscommands\"\n\t\"github.com\/jrperritt\/rack\/setup\"\n\t\"github.com\/jrperritt\/rack\/util\"\n\n\t\"github.com\/jrperritt\/rack\/internal\/github.com\/codegangsta\/cli\"\n)\n\nfunc main() {\n\tcli.HelpPrinter = printHelp\n\tcli.CommandHelpTemplate = `NAME: {{.Name}} - {{.Usage}}{{if .Description}}\n\nDESCRIPTION: {{.Description}}{{end}}{{if .Flags}}\n\nOPTIONS:\n{{range .Flags}}{{flag .}}\n{{end}}{{ end }}\n`\n\tapp := cli.NewApp()\n\tapp.Name = \"rack\"\n\tapp.Usage = Usage()\n\tapp.HideVersion = true\n\tapp.EnableBashCompletion = true\n\tapp.Commands = Cmds()\n\tapp.Before = func(c *cli.Context) error {\n\t\t\/\/fmt.Printf(\"c.Args: %+v\\n\", c.Args())\n\t\treturn nil\n\t}\n\tapp.CommandNotFound = commandNotFound\n\tapp.Run(os.Args)\n}\n\n\/\/ Usage returns, you guessed it, the usage information\nfunc Usage() string {\n\treturn \"An opinionated CLI for the Rackspace cloud\"\n}\n\n\/\/ Desc returns, you guessed it, the description\nfunc Desc() string {\n\treturn `Rack is an opinionated command-line tool that allows Rackspace users\nto accomplish tasks in a simple, idiomatic way. It seeks to provide\nflexibility through common Unix practices like piping and composability. All\ncommands have been tested against Rackspace's live API.`\n}\n\n\/\/ Cmds returns a list of commands supported by the tool\nfunc Cmds() []cli.Command {\n\treturn []cli.Command{\n\t\t{\n\t\t\tName:  \"init\",\n\t\t\tUsage: \"[Linux\/OS X only] Creates the rack man page and sets up command completion for the Bash shell.\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tsetup.Init(c)\n\t\t\t\tman()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:   \"configure\",\n\t\t\tUsage:  \"Interactively create a config file for Rackspace authentication.\",\n\t\t\tAction: configure,\n\t\t},\n\t\t{\n\t\t\tName:   \"version\",\n\t\t\tUsage:  \"Print the version of this binary.\",\n\t\t\tAction: version,\n\t\t},\n\t\t{\n\t\t\tName:        \"servers\",\n\t\t\tUsage:       \"Operations on cloud servers, both virtual and bare metal.\",\n\t\t\tSubcommands: serverscommands.Get(),\n\t\t},\n\t\t{\n\t\t\tName:        \"files\",\n\t\t\tUsage:       \"Object storage for files and media.\",\n\t\t\tSubcommands: filescommands.Get(),\n\t\t},\n\t\t{\n\t\t\tName:        \"networks\",\n\t\t\tUsage:       \"Software-defined networking.\",\n\t\t\tSubcommands: networkscommands.Get(),\n\t\t},\n\t\t{\n\t\t\tName:        \"block-storage\",\n\t\t\tUsage:       \"Block-level storage, exposed as volumes to mount to host servers. Work with volumes and their associated snapshots.\",\n\t\t\tSubcommands: blockstoragecommands.Get(),\n\t\t},\n\t}\n}\n\nfunc printHelp(out io.Writer, templ string, data interface{}) {\n\tfuncMap := template.FuncMap{\n\t\t\"join\": strings.Join,\n\t\t\"flag\": flag,\n\t}\n\n\tw := tabwriter.NewWriter(out, 0, 8, 1, '\\t', 0)\n\tt := template.Must(template.New(\"help\").Funcs(funcMap).Parse(templ))\n\terr := t.Execute(w, data)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tw.Flush()\n}\n\nfunc flag(flag cli.Flag) string {\n\tswitch flag.(type) {\n\tcase cli.StringFlag:\n\t\tflagType := flag.(cli.StringFlag)\n\t\treturn fmt.Sprintf(\"%s\\t%s\", flagType.Name, flagType.Usage)\n\tcase cli.IntFlag:\n\t\tflagType := flag.(cli.IntFlag)\n\t\treturn fmt.Sprintf(\"%s\\t%s\", flagType.Name, flagType.Usage)\n\tcase cli.BoolFlag:\n\t\tflagType := flag.(cli.BoolFlag)\n\t\treturn fmt.Sprintf(\"%s\\t%s\", flagType.Name, flagType.Usage)\n\tcase cli.StringSliceFlag:\n\t\tflagType := flag.(cli.StringSliceFlag)\n\t\treturn fmt.Sprintf(\"%s\\t%s\", flagType.Name, flagType.Usage)\n\t}\n\treturn \"\"\n}\n\nfunc version(c *cli.Context) {\n\tfmt.Fprintf(c.App.Writer, \"%v version %v\\ncommit: %v\\n\", c.App.Name, util.Version, util.Commit)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\n\tmanifest \"github.com\/estafette\/estafette-ci-manifest\"\n\t\"github.com\/rs\/zerolog\"\n\t\"github.com\/rs\/zerolog\/log\"\n\n\tstdlog \"log\"\n)\n\nvar (\n\tversion   string\n\tbranch    string\n\trevision  string\n\tbuildDate string\n\tgoVersion = runtime.Version()\n)\n\nfunc main() {\n\n\t\/\/ bootstrap\n\tenvvarHelper := NewEnvvarHelper(\"ESTAFETTE_\")\n\twhenEvaluator := NewWhenEvaluator(envvarHelper)\n\tdockerRunner := NewDockerRunner(envvarHelper)\n\tpipelineRunner := NewPipelineRunner(envvarHelper, whenEvaluator, dockerRunner)\n\tendOfLifeHelper := NewEndOfLifeHelper(envvarHelper)\n\n\t\/\/ detect controlling server\n\tciServer := envvarHelper.getEstafetteEnv(\"ESTAFETTE_CI_SERVER\")\n\n\tif ciServer == \"gocd\" {\n\n\t\t\/\/ pretty print for go.cd integration\n\t\tlog.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr}).With().\n\t\t\tTimestamp().\n\t\t\tLogger()\n\n\t\tstdlog.SetFlags(0)\n\t\tstdlog.SetOutput(log.Logger)\n\n\t\t\/\/ log startup message\n\t\tlog.Info().\n\t\t\tStr(\"branch\", branch).\n\t\t\tStr(\"revision\", revision).\n\t\t\tStr(\"buildDate\", buildDate).\n\t\t\tStr(\"goVersion\", goVersion).\n\t\t\tMsg(\"Starting estafette-ci-builder...\")\n\n\t\t\/\/ read yaml\n\t\tmanifest, err := manifest.ReadManifestFromFile(\".estafette.yaml\")\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Reading .estafette.yaml manifest failed\")\n\t\t}\n\n\t\t\/\/ get current working directory\n\t\tdir, err := os.Getwd()\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Getting current working directory failed\")\n\t\t}\n\n\t\tlog.Info().Msgf(\"Running %v pipelines\", len(manifest.Pipelines))\n\n\t\terr = envvarHelper.setEstafetteGlobalEnvvars()\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Setting global environment variables failed\")\n\t\t}\n\n\t\tenvvars := envvarHelper.collectEstafetteEnvvars(manifest)\n\n\t\tresult, err := pipelineRunner.runPipelines(manifest, dir, envvars)\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Executing pipelines from manifest failed\")\n\t\t}\n\n\t\trenderStats(result)\n\n\t\thandleExit(result)\n\n\t} else if ciServer == \"estafette\" {\n\n\t\t\/\/ log as severity for stackdriver logging to recognize the level\n\t\tzerolog.LevelFieldName = \"severity\"\n\n\t\tgitName := envvarHelper.getEstafetteEnv(\"ESTAFETTE_GIT_NAME\")\n\t\tgitBranch := envvarHelper.getEstafetteEnv(\"ESTAFETTE_GIT_BRANCH\")\n\t\tgitRevision := envvarHelper.getEstafetteEnv(\"ESTAFETTE_GIT_REVISION\")\n\t\tjobName := envvarHelper.getEstafetteEnv(\"ESTAFETTE_BUILD_JOB_NAME\")\n\t\tbuilderTrack := envvarHelper.getEstafetteEnv(\"ESTAFETTE_CI_BUILDER_TRACK\")\n\t\tif builderTrack == \"\" {\n\t\t\tbuilderTrack = \"stable\"\n\t\t}\n\n\t\t\/\/ set some default fields added to all logs\n\t\tlog.Logger = zerolog.New(os.Stdout).With().\n\t\t\tTimestamp().\n\t\t\tStr(\"app\", \"estafette-ci-builder\").\n\t\t\tStr(\"version\", version).\n\t\t\tStr(\"jobName\", jobName).\n\t\t\tStr(\"gitName\", gitName).\n\t\t\tStr(\"gitBranch\", gitBranch).\n\t\t\tStr(\"gitRevision\", gitRevision).\n\t\t\tLogger()\n\n\t\tstdlog.SetFlags(0)\n\t\tstdlog.SetOutput(log.Logger)\n\n\t\t\/\/ log startup message\n\t\tlog.Info().\n\t\t\tStr(\"branch\", branch).\n\t\t\tStr(\"revision\", revision).\n\t\t\tStr(\"buildDate\", buildDate).\n\t\t\tStr(\"goVersion\", goVersion).\n\t\t\tMsg(\"Starting estafette-ci-builder...\")\n\n\t\t\/\/ start docker daemon\n\t\terr := dockerRunner.startDockerDaemon()\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Error starting docker daemon\")\n\t\t}\n\n\t\t\/\/ wait for docker daemon to be ready for usage\n\t\tdockerRunner.waitForDockerDaemon()\n\n\t\t\/\/ get current working directory\n\t\tdir, err := os.Getwd()\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Getting current working directory failed\")\n\t\t}\n\n\t\t\/\/ set some envvars\n\t\terr = envvarHelper.setEstafetteGlobalEnvvars()\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Setting global environment variables failed\")\n\t\t}\n\n\t\t\/\/ run git clone via pipeline runner\n\t\testafetteGitCloneManifest := manifest.EstafetteManifest{\n\t\t\tPipelines: []*manifest.EstafettePipeline{\n\t\t\t\t&manifest.EstafettePipeline{\n\t\t\t\t\tName:             \"git-clone\",\n\t\t\t\t\tContainerImage:   fmt.Sprintf(\"extensions\/git-clone:%v\", builderTrack),\n\t\t\t\t\tShell:            \"\/bin\/sh\",\n\t\t\t\t\tWorkingDirectory: \"\/estafette-work\",\n\t\t\t\t\tWhen:             \"status == 'succeeded'\",\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\t\/\/ collect estafette envvars and run the git clone step\n\t\tenvvars := envvarHelper.collectEstafetteEnvvars(estafetteGitCloneManifest)\n\t\tgitCloneResult, err := pipelineRunner.runPipelines(estafetteGitCloneManifest, dir, envvars)\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Executing git clone step failed\")\n\t\t}\n\n\t\t\/\/ check if manifest exists\n\t\tif !manifest.Exists(\".estafette.yaml\") {\n\t\t\tlog.Info().Msg(\".estafette.yaml file does not exist, exiting...\")\n\t\t\tendOfLifeHelper.sendBuildFinishedEvent(\"builder:nomanifest\")\n\t\t\tos.Exit(0)\n\t\t}\n\n\t\t\/\/ read .estafette.yaml manifest\n\t\tmanifest, err := manifest.ReadManifestFromFile(\".estafette.yaml\")\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Reading .estafette.yaml manifest failed\")\n\t\t}\n\n\t\t\/\/ collect estafette envvars and run pipelines from manifest\n\t\tlog.Info().Msgf(\"Running %v pipelines\", len(manifest.Pipelines))\n\t\tenvvars = envvarHelper.collectEstafetteEnvvars(manifest)\n\t\tresult, err := pipelineRunner.runPipelines(manifest, dir, envvars)\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Executing pipelines from manifest failed\")\n\t\t}\n\n\t\t\/\/ merge git clone and manifest result\n\t\tresult.PipelineResults = append(gitCloneResult.PipelineResults, result.PipelineResults...)\n\n\t\t\/\/ send result to ci-api\n\t\tlog.Info().Interface(\"result\", result).Msg(\"Finished running pipelines\")\n\t\tendOfLifeHelper.sendBuildFinishedEvent(\"builder:succeeded\")\n\t\tos.Exit(0)\n\t}\n}\n}\n<commit_msg>fix vs code save error<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\n\tmanifest \"github.com\/estafette\/estafette-ci-manifest\"\n\t\"github.com\/rs\/zerolog\"\n\t\"github.com\/rs\/zerolog\/log\"\n\n\tstdlog \"log\"\n)\n\nvar (\n\tversion   string\n\tbranch    string\n\trevision  string\n\tbuildDate string\n\tgoVersion = runtime.Version()\n)\n\nfunc main() {\n\n\t\/\/ bootstrap\n\tenvvarHelper := NewEnvvarHelper(\"ESTAFETTE_\")\n\twhenEvaluator := NewWhenEvaluator(envvarHelper)\n\tdockerRunner := NewDockerRunner(envvarHelper)\n\tpipelineRunner := NewPipelineRunner(envvarHelper, whenEvaluator, dockerRunner)\n\tendOfLifeHelper := NewEndOfLifeHelper(envvarHelper)\n\n\t\/\/ detect controlling server\n\tciServer := envvarHelper.getEstafetteEnv(\"ESTAFETTE_CI_SERVER\")\n\n\tif ciServer == \"gocd\" {\n\n\t\t\/\/ pretty print for go.cd integration\n\t\tlog.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr}).With().\n\t\t\tTimestamp().\n\t\t\tLogger()\n\n\t\tstdlog.SetFlags(0)\n\t\tstdlog.SetOutput(log.Logger)\n\n\t\t\/\/ log startup message\n\t\tlog.Info().\n\t\t\tStr(\"branch\", branch).\n\t\t\tStr(\"revision\", revision).\n\t\t\tStr(\"buildDate\", buildDate).\n\t\t\tStr(\"goVersion\", goVersion).\n\t\t\tMsg(\"Starting estafette-ci-builder...\")\n\n\t\t\/\/ read yaml\n\t\tmanifest, err := manifest.ReadManifestFromFile(\".estafette.yaml\")\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Reading .estafette.yaml manifest failed\")\n\t\t}\n\n\t\t\/\/ get current working directory\n\t\tdir, err := os.Getwd()\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Getting current working directory failed\")\n\t\t}\n\n\t\tlog.Info().Msgf(\"Running %v pipelines\", len(manifest.Pipelines))\n\n\t\terr = envvarHelper.setEstafetteGlobalEnvvars()\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Setting global environment variables failed\")\n\t\t}\n\n\t\tenvvars := envvarHelper.collectEstafetteEnvvars(manifest)\n\n\t\tresult, err := pipelineRunner.runPipelines(manifest, dir, envvars)\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Executing pipelines from manifest failed\")\n\t\t}\n\n\t\trenderStats(result)\n\n\t\thandleExit(result)\n\n\t} else if ciServer == \"estafette\" {\n\n\t\t\/\/ log as severity for stackdriver logging to recognize the level\n\t\tzerolog.LevelFieldName = \"severity\"\n\n\t\tgitName := envvarHelper.getEstafetteEnv(\"ESTAFETTE_GIT_NAME\")\n\t\tgitBranch := envvarHelper.getEstafetteEnv(\"ESTAFETTE_GIT_BRANCH\")\n\t\tgitRevision := envvarHelper.getEstafetteEnv(\"ESTAFETTE_GIT_REVISION\")\n\t\tjobName := envvarHelper.getEstafetteEnv(\"ESTAFETTE_BUILD_JOB_NAME\")\n\t\tbuilderTrack := envvarHelper.getEstafetteEnv(\"ESTAFETTE_CI_BUILDER_TRACK\")\n\t\tif builderTrack == \"\" {\n\t\t\tbuilderTrack = \"stable\"\n\t\t}\n\n\t\t\/\/ set some default fields added to all logs\n\t\tlog.Logger = zerolog.New(os.Stdout).With().\n\t\t\tTimestamp().\n\t\t\tStr(\"app\", \"estafette-ci-builder\").\n\t\t\tStr(\"version\", version).\n\t\t\tStr(\"jobName\", jobName).\n\t\t\tStr(\"gitName\", gitName).\n\t\t\tStr(\"gitBranch\", gitBranch).\n\t\t\tStr(\"gitRevision\", gitRevision).\n\t\t\tLogger()\n\n\t\tstdlog.SetFlags(0)\n\t\tstdlog.SetOutput(log.Logger)\n\n\t\t\/\/ log startup message\n\t\tlog.Info().\n\t\t\tStr(\"branch\", branch).\n\t\t\tStr(\"revision\", revision).\n\t\t\tStr(\"buildDate\", buildDate).\n\t\t\tStr(\"goVersion\", goVersion).\n\t\t\tMsg(\"Starting estafette-ci-builder...\")\n\n\t\t\/\/ start docker daemon\n\t\terr := dockerRunner.startDockerDaemon()\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Error starting docker daemon\")\n\t\t}\n\n\t\t\/\/ wait for docker daemon to be ready for usage\n\t\tdockerRunner.waitForDockerDaemon()\n\n\t\t\/\/ get current working directory\n\t\tdir, err := os.Getwd()\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Getting current working directory failed\")\n\t\t}\n\n\t\t\/\/ set some envvars\n\t\terr = envvarHelper.setEstafetteGlobalEnvvars()\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Setting global environment variables failed\")\n\t\t}\n\n\t\t\/\/ run git clone via pipeline runner\n\t\testafetteGitCloneManifest := manifest.EstafetteManifest{\n\t\t\tPipelines: []*manifest.EstafettePipeline{\n\t\t\t\t&manifest.EstafettePipeline{\n\t\t\t\t\tName:             \"git-clone\",\n\t\t\t\t\tContainerImage:   fmt.Sprintf(\"extensions\/git-clone:%v\", builderTrack),\n\t\t\t\t\tShell:            \"\/bin\/sh\",\n\t\t\t\t\tWorkingDirectory: \"\/estafette-work\",\n\t\t\t\t\tWhen:             \"status == 'succeeded'\",\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\n\t\t\/\/ collect estafette envvars and run the git clone step\n\t\tenvvars := envvarHelper.collectEstafetteEnvvars(estafetteGitCloneManifest)\n\t\tgitCloneResult, err := pipelineRunner.runPipelines(estafetteGitCloneManifest, dir, envvars)\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Executing git clone step failed\")\n\t\t}\n\n\t\t\/\/ check if manifest exists\n\t\tif !manifest.Exists(\".estafette.yaml\") {\n\t\t\tlog.Info().Msg(\".estafette.yaml file does not exist, exiting...\")\n\t\t\tendOfLifeHelper.sendBuildFinishedEvent(\"builder:nomanifest\")\n\t\t\tos.Exit(0)\n\t\t}\n\n\t\t\/\/ read .estafette.yaml manifest\n\t\tmanifest, err := manifest.ReadManifestFromFile(\".estafette.yaml\")\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Reading .estafette.yaml manifest failed\")\n\t\t}\n\n\t\t\/\/ collect estafette envvars and run pipelines from manifest\n\t\tlog.Info().Msgf(\"Running %v pipelines\", len(manifest.Pipelines))\n\t\tenvvars = envvarHelper.collectEstafetteEnvvars(manifest)\n\t\tresult, err := pipelineRunner.runPipelines(manifest, dir, envvars)\n\t\tif err != nil {\n\t\t\tendOfLifeHelper.handleFatal(err, \"Executing pipelines from manifest failed\")\n\t\t}\n\n\t\t\/\/ merge git clone and manifest result\n\t\tresult.PipelineResults = append(gitCloneResult.PipelineResults, result.PipelineResults...)\n\n\t\t\/\/ send result to ci-api\n\t\tlog.Info().Interface(\"result\", result).Msg(\"Finished running pipelines\")\n\t\tendOfLifeHelper.sendBuildFinishedEvent(\"builder:succeeded\")\n\t\tos.Exit(0)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar remoteAddr = flag.String(\"r\", \"\", \"remote addr\")\nvar payloadSize = flag.Int(\"s\", 64, \"payload size\")\nvar interval = flag.Int64(\"i\", 100, \"interval in milliseconds\")\nvar count = flag.Int(\"c\", 50, \"send count\")\nvar number = flag.Int(\"n\", 1, \"how many connections\")\nvar protocol = flag.String(\"p\", \"tcp\", \"protocol: tcp or udp\")\nvar genCharts = flag.Bool(\"g\", false, \"generate charts\")\n\nvar payload string\n\nconst headSize = 15\n\ntype Result struct {\n\tmax, min, avg int\n\tdata          []int\n}\n\nfunc init() {\n\tpayload = randString(*payloadSize)\n}\n\nfunc encodePacket() []byte {\n\tsendTime, _ := time.Now().MarshalBinary()\n\tsendTime = append(sendTime, payload...)\n\treturn sendTime\n}\n\nfunc decodeLatency(bs []byte) int {\n\tbefore := time.Time{}\n\terr := before.UnmarshalBinary(bs)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt := time.Since(before) \/ time.Millisecond\n\treturn int(t)\n}\n\nfunc handleReceive(conn net.Conn, notify chan Result) {\n\tbs := make([]byte, headSize)\n\tps := make([]byte, *payloadSize)\n\tall := int64(0)\n\tmax := 0\n\tmin := 0xFFFFFFFFFFFFFFF\n\tavg := (0)\n\tdata := make([]int, *count)\n\tfor i := 0; i < *count; i++ {\n\t\t_, err := io.ReadFull(conn, bs)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbreak\n\t\t}\n\t\telapsed := decodeLatency(bs)\n\t\tif elapsed > max {\n\t\t\tmax = elapsed\n\t\t}\n\t\tif elapsed < min {\n\t\t\tmin = elapsed\n\t\t}\n\t\tlog.Printf(\"[%d] packet RTT: [%d] ms\", i, elapsed)\n\t\tdata[i] = elapsed\n\t\t_, err = io.ReadFull(conn, ps)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbreak\n\t\t}\n\t\tall = all + int64(elapsed)\n\t\tavg = int(all \/ int64(i+1))\n\t}\n\tnotify <- Result{max, min, avg, data}\n}\n\nfunc runOne(remoteAddr string, notify chan Result) {\n\tconn, err := net.Dial(*protocol, remoteAddr)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tdefer conn.Close()\n\tgo handleReceive(conn, notify)\n\tfor i := 0; i < *count; i++ {\n\t\tbuf := strings.NewReader(string(encodePacket()))\n\t\t_, err := io.CopyN(conn, buf, int64(buf.Len()))\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Duration(*interval) * time.Millisecond)\n\t}\n}\n\nfunc makeCharts(idx int, data []int) {\n\tt := time.Now()\n\tnow := fmt.Sprintf(\"%d-%d-%dH%dM%dS%d-%d\", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), idx)\n\tconst header = `\n# The chart type , option : spline\/line\/bar\/column\/area\nChartType = spline\nTitle = packet RTT latency (ms)\nSubTitle = %s\nValueSuffix = ms \n\n# The x Axis numbers. The count this numbers MUST be the same with the data series\nXAxisNumbers = %s\n\n# The y Axis text\nYAxisText = Latency (ms)\n\n# The data and the name of the lines\nData|Latency = %s\n`\n\tx := []string{}\n\td := []string{}\n\tfor i := 0; i < len(data); i++ {\n\t\tx = append(x, strconv.Itoa(i))\n\t\td = append(d, strconv.Itoa(data[i]))\n\t}\n\tsx := strings.Join(x, \", \")\n\tsd := strings.Join(d, \", \")\n\n\tall := fmt.Sprintf(header, now, sx, sd)\n\tioutil.WriteFile(now+\".chart\", []byte(all), os.ModePerm)\n}\n\nfunc main() {\n\tflag.Parse()\n\tresults := make(chan Result, *number)\n\twg := &sync.WaitGroup{}\n\tfor i := 0; i < *number; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\trunOne(*remoteAddr, results)\n\t\t}()\n\t}\n\twg.Wait()\n\tfor i := 0; i < *number; i++ {\n\t\tret := <-results\n\t\tif *genCharts {\n\t\t\tmakeCharts(i, ret.data)\n\t\t}\n\t\tlog.Printf(\"RTT min: [%d] ms, RTT max: [%d] ms, RTT avg: [%d] ms\\n\", ret.min, ret.max, ret.avg)\n\t}\n}\n\nvar src = rand.NewSource(time.Now().UnixNano())\n\nconst letterBytes = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst (\n\tletterIdxBits = 6                    \/\/ 6 bits to represent a letter index\n\tletterIdxMask = 1<<letterIdxBits - 1 \/\/ All 1-bits, as many as letterIdxBits\n\tletterIdxMax  = 63 \/ letterIdxBits   \/\/ # of letter indices fitting in 63 bits\n)\n\nfunc randString(n int) string {\n\tb := make([]byte, n)\n\t\/\/ A src.Int63() generates 63 random bits, enough for letterIdxMax characters!\n\tfor i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {\n\t\tif remain == 0 {\n\t\t\tcache, remain = src.Int63(), letterIdxMax\n\t\t}\n\t\tif idx := int(cache & letterIdxMask); idx < len(letterBytes) {\n\t\t\tb[i] = letterBytes[idx]\n\t\t\ti--\n\t\t}\n\t\tcache >>= letterIdxBits\n\t\tremain--\n\t}\n\n\treturn string(b)\n}\n<commit_msg>log with file&line<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar remoteAddr = flag.String(\"r\", \"\", \"remote addr\")\nvar payloadSize = flag.Int(\"s\", 64, \"payload size\")\nvar interval = flag.Int64(\"i\", 100, \"interval in milliseconds\")\nvar count = flag.Int(\"c\", 50, \"send count\")\nvar number = flag.Int(\"n\", 1, \"how many connections\")\nvar protocol = flag.String(\"p\", \"tcp\", \"protocol: tcp or udp\")\nvar genCharts = flag.Bool(\"g\", false, \"generate charts\")\n\nvar payload string\n\nconst headSize = 15\n\ntype Result struct {\n\tmax, min, avg int\n\tdata          []int\n}\n\nfunc init() {\n\tpayload = randString(*payloadSize)\n}\n\nfunc encodePacket() []byte {\n\tsendTime, _ := time.Now().MarshalBinary()\n\tsendTime = append(sendTime, payload...)\n\treturn sendTime\n}\n\nfunc decodeLatency(bs []byte) int {\n\tbefore := time.Time{}\n\terr := before.UnmarshalBinary(bs)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tt := time.Since(before) \/ time.Millisecond\n\treturn int(t)\n}\n\nfunc handleReceive(conn net.Conn, notify chan Result) {\n\tbs := make([]byte, headSize)\n\tps := make([]byte, *payloadSize)\n\tall := int64(0)\n\tmax := 0\n\tmin := 0xFFFFFFFFFFFFFFF\n\tavg := (0)\n\tdata := make([]int, *count)\n\tfor i := 0; i < *count; i++ {\n\t\t_, err := io.ReadFull(conn, bs)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbreak\n\t\t}\n\t\telapsed := decodeLatency(bs)\n\t\tif elapsed > max {\n\t\t\tmax = elapsed\n\t\t}\n\t\tif elapsed < min {\n\t\t\tmin = elapsed\n\t\t}\n\t\tlog.Printf(\"[%d] packet RTT: [%d] ms\", i, elapsed)\n\t\tdata[i] = elapsed\n\t\t_, err = io.ReadFull(conn, ps)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbreak\n\t\t}\n\t\tall = all + int64(elapsed)\n\t\tavg = int(all \/ int64(i+1))\n\t}\n\tnotify <- Result{max, min, avg, data}\n}\n\nfunc runOne(remoteAddr string, notify chan Result) {\n\tconn, err := net.Dial(*protocol, remoteAddr)\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\tdefer conn.Close()\n\tgo handleReceive(conn, notify)\n\tfor i := 0; i < *count; i++ {\n\t\tbuf := strings.NewReader(string(encodePacket()))\n\t\t_, err := io.CopyN(conn, buf, int64(buf.Len()))\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(time.Duration(*interval) * time.Millisecond)\n\t}\n}\n\nfunc makeCharts(idx int, data []int) {\n\tt := time.Now()\n\tnow := fmt.Sprintf(\"%d-%d-%dH%dM%dS%d-%d\", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), idx)\n\tconst header = `\n# The chart type , option : spline\/line\/bar\/column\/area\nChartType = spline\nTitle = packet RTT latency (ms)\nSubTitle = %s\nValueSuffix = ms \n\n# The x Axis numbers. The count this numbers MUST be the same with the data series\nXAxisNumbers = %s\n\n# The y Axis text\nYAxisText = Latency (ms)\n\n# The data and the name of the lines\nData|Latency = %s\n`\n\tx := []string{}\n\td := []string{}\n\tfor i := 0; i < len(data); i++ {\n\t\tx = append(x, strconv.Itoa(i))\n\t\td = append(d, strconv.Itoa(data[i]))\n\t}\n\tsx := strings.Join(x, \", \")\n\tsd := strings.Join(d, \", \")\n\n\tall := fmt.Sprintf(header, now, sx, sd)\n\tioutil.WriteFile(now+\".chart\", []byte(all), os.ModePerm)\n}\n\nfunc main() {\n\tflag.Parse()\n\tlog.SetFlags(log.Flags() | log.Lshortfile)\n\tresults := make(chan Result, *number)\n\twg := &sync.WaitGroup{}\n\tfor i := 0; i < *number; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\trunOne(*remoteAddr, results)\n\t\t}()\n\t}\n\twg.Wait()\n\tfor i := 0; i < *number; i++ {\n\t\tret := <-results\n\t\tif *genCharts {\n\t\t\tmakeCharts(i, ret.data)\n\t\t}\n\t\tlog.Printf(\"RTT min: [%d] ms, RTT max: [%d] ms, RTT avg: [%d] ms\\n\", ret.min, ret.max, ret.avg)\n\t}\n}\n\nvar src = rand.NewSource(time.Now().UnixNano())\n\nconst letterBytes = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nconst (\n\tletterIdxBits = 6                    \/\/ 6 bits to represent a letter index\n\tletterIdxMask = 1<<letterIdxBits - 1 \/\/ All 1-bits, as many as letterIdxBits\n\tletterIdxMax  = 63 \/ letterIdxBits   \/\/ # of letter indices fitting in 63 bits\n)\n\nfunc randString(n int) string {\n\tb := make([]byte, n)\n\t\/\/ A src.Int63() generates 63 random bits, enough for letterIdxMax characters!\n\tfor i, cache, remain := n-1, src.Int63(), letterIdxMax; i >= 0; {\n\t\tif remain == 0 {\n\t\t\tcache, remain = src.Int63(), letterIdxMax\n\t\t}\n\t\tif idx := int(cache & letterIdxMask); idx < len(letterBytes) {\n\t\t\tb[i] = letterBytes[idx]\n\t\t\ti--\n\t\t}\n\t\tcache >>= letterIdxBits\n\t\tremain--\n\t}\n\n\treturn string(b)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"crypto\/tls\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\/\/ hardcoded program settings\nconst baseDir string = \"muck\"\nconst inFile string = \"in\"\nconst outFile string = \"out\"\nconst timeString string = \"2006-01-02T150405\"\nconst bufferSize int = 1024\n\n\/\/ Program level switches set from command line\nvar debugMode bool\nvar disableLogRotate bool\n\n\/\/ MuckServer stores all connection settings\ntype MuckServer struct {\n\tname     string\n\thost     string\n\tport     uint\n\tssl      bool\n\tinsecure bool\n}\n\n\/\/ Simplify returning connection strings by making it the String method\nfunc (m *MuckServer) String() string {\n\ts := fmt.Sprintf(\"%s:%d\", m.host, m.port)\n\treturn s\n}\n\nfunc debugLog(log ...interface{}) {\n\tif debugMode {\n\t\tfmt.Print(\"DEBUG: \")\n\t\tfmt.Println(log...)\n\t}\n}\n\nfunc checkError(err error) {\n\tif err != nil {\n\t\tdebugLog(\"checkError caught\", err.Error())\n\t\tpanic(err.Error())\n\t}\n}\n\nfunc getTimestamp() string {\n\treturn time.Now().Format(timeString)\n}\n\nfunc initArgs() MuckServer {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, \"    %v [<flags>] <name> <server> <port>\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\n\t\/\/ Global program flags\n\tflag.BoolVar(&debugMode, \"debug\", false, \"Enable debug\")\n\tflag.BoolVar(&disableLogRotate, \"nolog\", false, \"Disable log rotation on quit\")\n\t\/\/ Connection flags\n\tssl := flag.Bool(\"ssl\", false, \"Enable ssl\")\n\tinsecure := flag.Bool(\"insecure\", false, \"Disable strict SSL checking\")\n\tflag.Parse()\n\n\tif flag.NArg() != 3 {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\targs := flag.Args()\n\tp, err := strconv.Atoi(args[2])\n\tcheckError(err)\n\ts := MuckServer{name: args[0], host: args[1], port: uint(p), ssl: *ssl, insecure: *insecure}\n\n\tdebugLog(\"rotate log disabled?:\", disableLogRotate)\n\tdebugLog(\"name:\", s.name)\n\tdebugLog(\"host:\", s.host)\n\tdebugLog(\"port:\", s.port)\n\tdebugLog(\"SSL?:\", s.ssl)\n\tdebugLog(\"insecure ssl check?:\", s.insecure)\n\n\treturn s\n}\n\nfunc getWorkingDir(main string, sub string) string {\n\tu, err := user.Current()\n\tcheckError(err)\n\th := u.HomeDir\n\tdebugLog(\"home directory\", h)\n\n\tw := filepath.Join(h, main, sub)\n\tdebugLog(\"working directory\", w)\n\treturn w\n}\n\nfunc makeFIFO(file string) *os.File {\n\tif _, err := os.Stat(file); err == nil {\n\t\tfmt.Println(\"FIFO already exists. Unlink or exit\")\n\t\tfmt.Println(\"If you run multiple connection with the same name you're gonna have a bad time\")\n\t\tfmt.Print(\"Type YES to unlink and recreate: \")\n\t\ti := bufio.NewReader(os.Stdin)\n\t\ta, err := i.ReadString('\\n')\n\t\tcheckError(err)\n\t\tif a != \"YES\\n\" {\n\t\t\tfmt.Println(\"Canceling. Please remove FIFO before running\")\n\t\t\tpanic(\"User Canceled at FIFO removal prompt\")\n\t\t}\n\t\terrUn := syscall.Unlink(file)\n\t\tcheckError(errUn)\n\t\tdebugLog(file, \"unlinked\")\n\t}\n\terr := syscall.Mkfifo(file, 0644)\n\tcheckError(err)\n\tdebugLog(\"FIFO created as\", file)\n\tf, err := os.OpenFile(file, os.O_RDONLY|syscall.O_NONBLOCK, 0666)\n\tcheckError(err)\n\tdebugLog(\"FIFO opened as\", f.Name())\n\treturn f\n}\n\nfunc makeOut(file string) *os.File {\n\tif _, err := os.Stat(file); err == nil {\n\t\tfmt.Printf(\"Warning: %v already exists; appending.\\n\", file)\n\t}\n\tout, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)\n\tcheckError(err)\n\tdebugLog(\"logfile created as\", out.Name())\n\treturn out\n}\n\nfunc lookupHostname(s string) *net.TCPAddr {\n\ta, err := net.ResolveTCPAddr(\"tcp\", s)\n\tcheckError(err)\n\tdebugLog(\"server resolves to\", a)\n\treturn a\n}\n\nfunc setupConnection(s *MuckServer) net.Conn {\n\ttcpAddr := lookupHostname(s.String())\n\tconnection, err := net.DialTCP(\"tcp\", nil, tcpAddr)\n\tcheckError(err)\n\tdebugLog(\"connected to Server\")\n\n\t\/\/ We keep alive for mucks\n\terrSka := connection.SetKeepAlive(true)\n\tcheckError(errSka)\n\tkeepalive := 15 * time.Minute\n\terrSkap := connection.SetKeepAlivePeriod(keepalive)\n\tcheckError(errSkap)\n\treturn connection\n}\n\nfunc setupTLSConnextion(s *MuckServer) net.Conn {\n\tvar conf *tls.Config\n\tif s.insecure {\n\t\tconf = &tls.Config{InsecureSkipVerify: true}\n\t} else {\n\t\tconf = &tls.Config{ServerName: s.host}\n\t}\n\ttcpAddr := lookupHostname(s.String())\n\tconnection, err := tls.Dial(\"tcp\", tcpAddr.String(), conf)\n\tcheckError(err)\n\treturn connection\n}\n\nfunc readToConn(f *os.File, c net.Conn, quit chan bool) {\n\ttmpError := fmt.Sprintf(\"read %v: resource temporarily unavailable\", f.Name())\n\tfor {\n\t\tselect {\n\t\tcase <-quit:\n\t\t\tdebugLog(\"readtoConn recieved quit; returning\")\n\t\t\treturn\n\t\tdefault:\n\t\t\t\/\/ This pause between reads from the FIFO. This is the difference between\n\t\t\t\/\/ 0.1% and 100% cpu usage. Also without this you will get excessive \"read\n\t\t\t\/\/ %v: resource temporarily unavailable\" errors.\n\t\t\ttime.Sleep(time.Second \/ 10)\n\t\t\tbuf := make([]byte, bufferSize)\n\t\t\tbi, err := f.Read(buf)\n\t\t\tif err != nil && err.Error() != \"EOF\" && err.Error() != tmpError {\n\t\t\t\tcheckError(err)\n\t\t\t} else if bi == 0 {\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdebugLog(bi, \"bytes read from FIFO\")\n\t\t\tbo, err := c.Write(buf[:bi])\n\t\t\tcheckError(err)\n\t\t\tdebugLog(bo, \"bytes written to file\")\n\t\t}\n\t}\n}\n\nfunc readToFile(c net.Conn, f *os.File, quit chan bool) {\n\t_, err := f.WriteString(fmt.Sprintf(\"~Connected at %v\\n\", getTimestamp()))\n\tcheckError(err)\n\tfor {\n\t\tbuf := make([]byte, bufferSize)\n\t\tbi, err := c.Read(buf)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Server disconnected with\", err.Error())\n\t\t\t_, err := f.WriteString(fmt.Sprintf(\"\\n~Connection lost at %v\\n\", getTimestamp()))\n\t\t\tcheckError(err)\n\t\t\tquit <- true\n\t\t\treturn\n\t\t}\n\t\tdebugLog(bi, \"bytes read from connection\")\n\n\t\tbo, err := f.Write(buf[:bi])\n\t\tcheckError(err)\n\t\tdebugLog(bo, \"bytes written to file\")\n\t}\n}\n\nfunc closeConnection(c net.Conn) {\n\terr := c.Close()\n\tif err != nil {\n\t\tdebugLog(err.Error())\n\t}\n\tdebugLog(\"connection closed\")\n}\n\nfunc closeFIFO(f *os.File) {\n\tn := f.Name()\n\tdebugLog(\"closing and deleting FIFO\", n)\n\terrC := f.Close()\n\tif errC != nil {\n\t\tdebugLog(errC.Error())\n\t}\n\terrU := syscall.Unlink(n)\n\tif errU != nil {\n\t\tdebugLog(errU.Error())\n\t}\n\tdebugLog(n, \"closed and deleted\")\n}\n\nfunc closeLog(f *os.File) {\n\tn := f.Name()\n\tdebugLog(\"closing and rotating file\", n)\n\terrC := f.Close()\n\tif errC != nil {\n\t\tdebugLog(errC.Error())\n\t}\n\tdebugLog(n, \"closed\")\n\tif disableLogRotate {\n\t\tdebugLog(\"log rotation is disabled\")\n\t\treturn\n\t}\n\terrR := os.Rename(outFile, getTimestamp())\n\tif errR != nil {\n\t\tdebugLog(errR.Error())\n\t}\n\tdebugLog(n, \"rotated\")\n}\n\nfunc main() {\n\t\/\/ checkError throws a panic, catch it at the end and return error to user\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Println(\"FATAL ERROR\", r)\n\t\t}\n\t}()\n\n\tfmt.Println(\"Started at\", getTimestamp())\n\tserver := initArgs()\n\n\t\/\/ Make and move to working directory\n\tworkingDir := getWorkingDir(baseDir, server.name)\n\terrMk := os.MkdirAll(workingDir, 0755)\n\tcheckError(errMk)\n\n\terrCh := os.Chdir(workingDir)\n\tcheckError(errCh)\n\n\t\/\/ Make the in FIFO\n\tin := makeFIFO(inFile)\n\tdefer closeFIFO(in)\n\n\t\/\/ Make the out file\n\tout := makeOut(outFile)\n\tdefer closeLog(out)\n\n\t\/\/create connection\n\tvar connection net.Conn\n\tif server.ssl {\n\t\tconnection = setupTLSConnextion(&server)\n\t} else {\n\t\tconnection = setupConnection(&server)\n\t}\n\tdefer closeConnection(connection)\n\n\tquit := make(chan bool)\n\tgo readToFile(connection, out, quit)\n\treadToConn(in, connection, quit)\n\n\tfmt.Println(\"Quit at\", getTimestamp())\n\tfmt.Println(\"Thanks for playing!\")\n\tdebugLog(\"end of main hit\")\n}\n<commit_msg>Reduce delay to a Millisecond to minimize type lag<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"crypto\/tls\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\/\/ hardcoded program settings\nconst baseDir string = \"muck\"\nconst inFile string = \"in\"\nconst outFile string = \"out\"\nconst timeString string = \"2006-01-02T150405\"\nconst bufferSize int = 1024\n\n\/\/ Program level switches set from command line\nvar debugMode bool\nvar disableLogRotate bool\n\n\/\/ MuckServer stores all connection settings\ntype MuckServer struct {\n\tname     string\n\thost     string\n\tport     uint\n\tssl      bool\n\tinsecure bool\n}\n\n\/\/ Simplify returning connection strings by making it the String method\nfunc (m *MuckServer) String() string {\n\ts := fmt.Sprintf(\"%s:%d\", m.host, m.port)\n\treturn s\n}\n\nfunc debugLog(log ...interface{}) {\n\tif debugMode {\n\t\tfmt.Print(\"DEBUG: \")\n\t\tfmt.Println(log...)\n\t}\n}\n\nfunc checkError(err error) {\n\tif err != nil {\n\t\tdebugLog(\"checkError caught\", err.Error())\n\t\tpanic(err.Error())\n\t}\n}\n\nfunc getTimestamp() string {\n\treturn time.Now().Format(timeString)\n}\n\nfunc initArgs() MuckServer {\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s:\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, \"    %v [<flags>] <name> <server> <port>\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\n\t\/\/ Global program flags\n\tflag.BoolVar(&debugMode, \"debug\", false, \"Enable debug\")\n\tflag.BoolVar(&disableLogRotate, \"nolog\", false, \"Disable log rotation on quit\")\n\t\/\/ Connection flags\n\tssl := flag.Bool(\"ssl\", false, \"Enable ssl\")\n\tinsecure := flag.Bool(\"insecure\", false, \"Disable strict SSL checking\")\n\tflag.Parse()\n\n\tif flag.NArg() != 3 {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\targs := flag.Args()\n\tp, err := strconv.Atoi(args[2])\n\tcheckError(err)\n\ts := MuckServer{name: args[0], host: args[1], port: uint(p), ssl: *ssl, insecure: *insecure}\n\n\tdebugLog(\"rotate log disabled?:\", disableLogRotate)\n\tdebugLog(\"name:\", s.name)\n\tdebugLog(\"host:\", s.host)\n\tdebugLog(\"port:\", s.port)\n\tdebugLog(\"SSL?:\", s.ssl)\n\tdebugLog(\"insecure ssl check?:\", s.insecure)\n\n\treturn s\n}\n\nfunc getWorkingDir(main string, sub string) string {\n\tu, err := user.Current()\n\tcheckError(err)\n\th := u.HomeDir\n\tdebugLog(\"home directory\", h)\n\n\tw := filepath.Join(h, main, sub)\n\tdebugLog(\"working directory\", w)\n\treturn w\n}\n\nfunc makeFIFO(file string) *os.File {\n\tif _, err := os.Stat(file); err == nil {\n\t\tfmt.Println(\"FIFO already exists. Unlink or exit\")\n\t\tfmt.Println(\"If you run multiple connection with the same name you're gonna have a bad time\")\n\t\tfmt.Print(\"Type YES to unlink and recreate: \")\n\t\ti := bufio.NewReader(os.Stdin)\n\t\ta, err := i.ReadString('\\n')\n\t\tcheckError(err)\n\t\tif a != \"YES\\n\" {\n\t\t\tfmt.Println(\"Canceling. Please remove FIFO before running\")\n\t\t\tpanic(\"User Canceled at FIFO removal prompt\")\n\t\t}\n\t\terrUn := syscall.Unlink(file)\n\t\tcheckError(errUn)\n\t\tdebugLog(file, \"unlinked\")\n\t}\n\terr := syscall.Mkfifo(file, 0644)\n\tcheckError(err)\n\tdebugLog(\"FIFO created as\", file)\n\tf, err := os.OpenFile(file, os.O_RDONLY|syscall.O_NONBLOCK, 0666)\n\tcheckError(err)\n\tdebugLog(\"FIFO opened as\", f.Name())\n\treturn f\n}\n\nfunc makeOut(file string) *os.File {\n\tif _, err := os.Stat(file); err == nil {\n\t\tfmt.Printf(\"Warning: %v already exists; appending.\\n\", file)\n\t}\n\tout, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)\n\tcheckError(err)\n\tdebugLog(\"logfile created as\", out.Name())\n\treturn out\n}\n\nfunc lookupHostname(s string) *net.TCPAddr {\n\ta, err := net.ResolveTCPAddr(\"tcp\", s)\n\tcheckError(err)\n\tdebugLog(\"server resolves to\", a)\n\treturn a\n}\n\nfunc setupConnection(s *MuckServer) net.Conn {\n\ttcpAddr := lookupHostname(s.String())\n\tconnection, err := net.DialTCP(\"tcp\", nil, tcpAddr)\n\tcheckError(err)\n\tdebugLog(\"connected to Server\")\n\n\t\/\/ We keep alive for mucks\n\terrSka := connection.SetKeepAlive(true)\n\tcheckError(errSka)\n\tkeepalive := 15 * time.Minute\n\terrSkap := connection.SetKeepAlivePeriod(keepalive)\n\tcheckError(errSkap)\n\treturn connection\n}\n\nfunc setupTLSConnextion(s *MuckServer) net.Conn {\n\tvar conf *tls.Config\n\tif s.insecure {\n\t\tconf = &tls.Config{InsecureSkipVerify: true}\n\t} else {\n\t\tconf = &tls.Config{ServerName: s.host}\n\t}\n\ttcpAddr := lookupHostname(s.String())\n\tconnection, err := tls.Dial(\"tcp\", tcpAddr.String(), conf)\n\tcheckError(err)\n\treturn connection\n}\n\nfunc readToConn(f *os.File, c net.Conn, quit chan bool) {\n\ttmpError := fmt.Sprintf(\"read %v: resource temporarily unavailable\", f.Name())\n\tfor {\n\t\tselect {\n\t\tcase <-quit:\n\t\t\tdebugLog(\"readtoConn recieved quit; returning\")\n\t\t\treturn\n\t\tdefault:\n\t\t\t\/\/ This pause between reads from the FIFO. This is the difference between\n\t\t\t\/\/ 0.1% and 100% cpu usage. Also without this you will get excessive \"read\n\t\t\t\/\/ %v: resource temporarily unavailable\" errors.\n\t\t\ttime.Sleep(time.Millisecond)\n\t\t\tbuf := make([]byte, bufferSize)\n\t\t\tbi, err := f.Read(buf)\n\t\t\tif err != nil && err.Error() != \"EOF\" && err.Error() != tmpError {\n\t\t\t\tcheckError(err)\n\t\t\t} else if bi == 0 {\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tdebugLog(bi, \"bytes read from FIFO\")\n\t\t\tbo, err := c.Write(buf[:bi])\n\t\t\tcheckError(err)\n\t\t\tdebugLog(bo, \"bytes written to file\")\n\t\t}\n\t}\n}\n\nfunc readToFile(c net.Conn, f *os.File, quit chan bool) {\n\t_, err := f.WriteString(fmt.Sprintf(\"~Connected at %v\\n\", getTimestamp()))\n\tcheckError(err)\n\tfor {\n\t\tbuf := make([]byte, bufferSize)\n\t\tbi, err := c.Read(buf)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Server disconnected with\", err.Error())\n\t\t\t_, err := f.WriteString(fmt.Sprintf(\"\\n~Connection lost at %v\\n\", getTimestamp()))\n\t\t\tcheckError(err)\n\t\t\tquit <- true\n\t\t\treturn\n\t\t}\n\t\tdebugLog(bi, \"bytes read from connection\")\n\n\t\tbo, err := f.Write(buf[:bi])\n\t\tcheckError(err)\n\t\tdebugLog(bo, \"bytes written to file\")\n\t}\n}\n\nfunc closeConnection(c net.Conn) {\n\terr := c.Close()\n\tif err != nil {\n\t\tdebugLog(err.Error())\n\t}\n\tdebugLog(\"connection closed\")\n}\n\nfunc closeFIFO(f *os.File) {\n\tn := f.Name()\n\tdebugLog(\"closing and deleting FIFO\", n)\n\terrC := f.Close()\n\tif errC != nil {\n\t\tdebugLog(errC.Error())\n\t}\n\terrU := syscall.Unlink(n)\n\tif errU != nil {\n\t\tdebugLog(errU.Error())\n\t}\n\tdebugLog(n, \"closed and deleted\")\n}\n\nfunc closeLog(f *os.File) {\n\tn := f.Name()\n\tdebugLog(\"closing and rotating file\", n)\n\terrC := f.Close()\n\tif errC != nil {\n\t\tdebugLog(errC.Error())\n\t}\n\tdebugLog(n, \"closed\")\n\tif disableLogRotate {\n\t\tdebugLog(\"log rotation is disabled\")\n\t\treturn\n\t}\n\terrR := os.Rename(outFile, getTimestamp())\n\tif errR != nil {\n\t\tdebugLog(errR.Error())\n\t}\n\tdebugLog(n, \"rotated\")\n}\n\nfunc main() {\n\t\/\/ checkError throws a panic, catch it at the end and return error to user\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Println(\"FATAL ERROR\", r)\n\t\t}\n\t}()\n\n\tfmt.Println(\"Started at\", getTimestamp())\n\tserver := initArgs()\n\n\t\/\/ Make and move to working directory\n\tworkingDir := getWorkingDir(baseDir, server.name)\n\terrMk := os.MkdirAll(workingDir, 0755)\n\tcheckError(errMk)\n\n\terrCh := os.Chdir(workingDir)\n\tcheckError(errCh)\n\n\t\/\/ Make the in FIFO\n\tin := makeFIFO(inFile)\n\tdefer closeFIFO(in)\n\n\t\/\/ Make the out file\n\tout := makeOut(outFile)\n\tdefer closeLog(out)\n\n\t\/\/create connection\n\tvar connection net.Conn\n\tif server.ssl {\n\t\tconnection = setupTLSConnextion(&server)\n\t} else {\n\t\tconnection = setupConnection(&server)\n\t}\n\tdefer closeConnection(connection)\n\n\tquit := make(chan bool)\n\tgo readToFile(connection, out, quit)\n\treadToConn(in, connection, quit)\n\n\tfmt.Println(\"Quit at\", getTimestamp())\n\tfmt.Println(\"Thanks for playing!\")\n\tdebugLog(\"end of main hit\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"expvar\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"sync\"\n\t\"text\/template\"\n\t\"time\"\n\n\t\"github.com\/go-recaptcha\/recaptcha\"\n\t\"github.com\/gorilla\/handlers\"\n\t\"github.com\/kelseyhightower\/envconfig\"\n\t\"github.com\/nlopes\/slack\"\n\t\"github.com\/oxtoacart\/bpool\"\n\t\"github.com\/paulbellamy\/ratecounter\"\n)\n\nvar captcha *recaptcha.Recaptcha\nvar api *slack.Client\nvar bufpool *bpool.BufferPool\nvar indexTemplate = template.Must(template.New(\"index.tmpl\").ParseFiles(\"templates\/index.tmpl\"))\n\n\/\/ Slack statistics\nvar userCount int\nvar activeUserCount int\nvar statsMutex sync.RWMutex \/\/ Guards slack statistics variables\n\nvar m = expvar.NewMap(\"metrics\")\nvar counter *ratecounter.RateCounter\nvar hitsPerMinute expvar.Int\nvar requests expvar.Int\nvar inviteErrors expvar.Int\nvar missingFirstName expvar.Int\nvar missingLastName expvar.Int\nvar missingEmail expvar.Int\nvar missingCoC expvar.Int\nvar successfulCaptcha expvar.Int\nvar failedCaptcha expvar.Int\nvar invalidCaptcha expvar.Int\n\n\/\/ config\nvar c Specification\n\ntype Specification struct {\n\tPort           string `required:\"true\"`\n\tCaptchaSitekey string `required:\"true\"`\n\tCaptchaSecret  string `required:\"true\"`\n\tSlackToken     string `required:\"true\"`\n}\n\nfunc init() {\n\terr := envconfig.Process(\"slackinviter\", &c)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\tcounter = ratecounter.NewRateCounter(1 * time.Minute)\n\tm.Set(\"hits_per_minute\", &hitsPerMinute)\n\tm.Set(\"requests\", &requests)\n\tm.Set(\"invite_errors\", &inviteErrors)\n\tm.Set(\"missing_first_name\", &missingFirstName)\n\tm.Set(\"missing_last_name\", &missingLastName)\n\tm.Set(\"missing_email\", &missingEmail)\n\tm.Set(\"missing_coc\", &missingCoC)\n\tm.Set(\"failed_captcha\", &failedCaptcha)\n\tm.Set(\"invalid_captcha\", &invalidCaptcha)\n\tm.Set(\"successful_captcha\", &successfulCaptcha)\n\t\/\/ Init stuff\n\tcaptcha = recaptcha.New(c.CaptchaSecret)\n\tapi = slack.New(c.SlackToken)\n\tbufpool = bpool.NewBufferPool(64)\n}\nfunc main() {\n\tgo pollSlack()\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"\/invite\/\", handleInvite)\n\tmux.Handle(\"\/static\/\", http.StripPrefix(\"\/static\/\", http.FileServer(http.Dir(\".\/static\"))))\n\tmux.HandleFunc(\"\/\", homepage)\n\tmux.Handle(\"\/debug\/vars\", onlyLocalhost(http.DefaultServeMux))\n\terr := http.ListenAndServe(\":\"+c.Port, handlers.CombinedLoggingHandler(os.Stdout, mux))\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n}\nfunc pollSlack() {\n\tfor {\n\t\tusers, err := api.GetUsers()\n\t\tif err != nil {\n\t\t\tlog.Println(\"error polling slack for users:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tuCount := 0 \/\/ users\n\t\taCount := 0 \/\/ active users\n\t\tfor _, u := range users {\n\t\t\tif u.ID != \"USLACKBOT\" && !u.IsBot && !u.Deleted {\n\t\t\t\tuCount += 1\n\t\t\t\tif u.Presence == \"active\" {\n\t\t\t\t\taCount += 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstatsMutex.Lock()\n\t\tuserCount = uCount\n\t\tactiveUserCount = aCount\n\t\tstatsMutex.Unlock()\n\t\ttime.Sleep(10 * time.Minute)\n\t}\n}\n\n\/\/ Homepage renders the homepage\nfunc homepage(w http.ResponseWriter, r *http.Request) {\n\tcounter.Incr(1)\n\thitsPerMinute.Set(counter.Rate())\n\trequests.Add(1)\n\tstatsMutex.RLock()\n\tdata := map[string]interface{}{\"SiteKey\": c.CaptchaSitekey, \"UserCount\": userCount, \"ActiveCount\": activeUserCount}\n\tstatsMutex.RUnlock()\n\tbuf := bufpool.Get()\n\tdefer bufpool.Put(buf)\n\terr := indexTemplate.Execute(buf, data)\n\tif err != nil {\n\t\tlog.Println(\"error rendering template:\", err)\n\t\thttp.Error(w, \"error rendering template :-(\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\t\/\/ Set the header and write the buffer to the http.ResponseWriter\n\tw.Header().Set(\"Content-Type\", \"text\/html; charset=utf-8\")\n\tbuf.WriteTo(w)\n}\n\n\/\/ ShowPost renders a single post\nfunc handleInvite(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"POST\" {\n\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t\treturn\n\t}\n\tcaptchaResponse := r.FormValue(\"g-recaptcha-response\")\n\tremoteIP, _, err := net.SplitHostPort(r.RemoteAddr)\n\tif err != nil {\n\t\tfailedCaptcha.Add(1)\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvalid, err := captcha.Verify(captchaResponse, remoteIP)\n\tif err != nil {\n\t\tfailedCaptcha.Add(1)\n\t\thttp.Error(w, \"Error validating recaptcha.. Did you click it?\", http.StatusPreconditionFailed)\n\t\treturn\n\t}\n\tif !valid {\n\t\tinvalidCaptcha.Add(1)\n\t\thttp.Error(w, \"Invalid recaptcha\", http.StatusInternalServerError)\n\t\treturn\n\n\t}\n\tsuccessfulCaptcha.Add(1)\n\tfname := r.FormValue(\"fname\")\n\tlname := r.FormValue(\"lname\")\n\temail := r.FormValue(\"email\")\n\tcoc := r.FormValue(\"coc\")\n\tif email == \"\" {\n\t\tmissingEmail.Add(1)\n\t\thttp.Error(w, \"Missing email\", http.StatusPreconditionFailed)\n\t\treturn\n\t}\n\tif fname == \"\" {\n\t\tmissingFirstName.Add(1)\n\t\thttp.Error(w, \"Missing first name\", http.StatusPreconditionFailed)\n\t\treturn\n\t}\n\tif lname == \"\" {\n\t\tmissingLastName.Add(1)\n\t\thttp.Error(w, \"Missing last name\", http.StatusPreconditionFailed)\n\t\treturn\n\t}\n\tif coc != \"1\" {\n\t\tmissingCoC.Add(1)\n\t\thttp.Error(w, \"You need to accept the code of conduct\", http.StatusPreconditionFailed)\n\t\treturn\n\t}\n\terr = api.InviteToTeam(\"Gophers\", fname, lname, email)\n\tif err != nil {\n\t\tlog.Println(\"InviteToTeam error:\", err)\n\t\tinviteErrors.Add(1)\n\t\thttp.Error(w, \"Error inviting you :-(\", http.StatusInternalServerError)\n\t\treturn\n\t}\n}\nfunc onlyLocalhost(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\thost, _, err := net.SplitHostPort(r.RemoteAddr)\n\t\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tif host == \"127.0.0.1\" {\n\t\t\tnext.ServeHTTP(w, r)\n\t\t} else {\n\t\t\thttp.Error(w, http.StatusText(404), 404)\n\t\t}\n\t})\n}\n<commit_msg>Since we are using environment variables now, we can show expvars to everyone<commit_after>package main\n\nimport (\n\t\"expvar\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"sync\"\n\t\"text\/template\"\n\t\"time\"\n\n\t\"github.com\/go-recaptcha\/recaptcha\"\n\t\"github.com\/gorilla\/handlers\"\n\t\"github.com\/kelseyhightower\/envconfig\"\n\t\"github.com\/nlopes\/slack\"\n\t\"github.com\/oxtoacart\/bpool\"\n\t\"github.com\/paulbellamy\/ratecounter\"\n)\n\nvar captcha *recaptcha.Recaptcha\nvar api *slack.Client\nvar bufpool *bpool.BufferPool\nvar indexTemplate = template.Must(template.New(\"index.tmpl\").ParseFiles(\"templates\/index.tmpl\"))\n\n\/\/ Slack statistics\nvar userCount int\nvar activeUserCount int\nvar statsMutex sync.RWMutex \/\/ Guards slack statistics variables\n\nvar m = expvar.NewMap(\"metrics\")\nvar counter *ratecounter.RateCounter\nvar hitsPerMinute expvar.Int\nvar requests expvar.Int\nvar inviteErrors expvar.Int\nvar missingFirstName expvar.Int\nvar missingLastName expvar.Int\nvar missingEmail expvar.Int\nvar missingCoC expvar.Int\nvar successfulCaptcha expvar.Int\nvar failedCaptcha expvar.Int\nvar invalidCaptcha expvar.Int\n\n\/\/ config\nvar c Specification\n\ntype Specification struct {\n\tPort           string `required:\"true\"`\n\tCaptchaSitekey string `required:\"true\"`\n\tCaptchaSecret  string `required:\"true\"`\n\tSlackToken     string `required:\"true\"`\n}\n\nfunc init() {\n\terr := envconfig.Process(\"slackinviter\", &c)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\tcounter = ratecounter.NewRateCounter(1 * time.Minute)\n\tm.Set(\"hits_per_minute\", &hitsPerMinute)\n\tm.Set(\"requests\", &requests)\n\tm.Set(\"invite_errors\", &inviteErrors)\n\tm.Set(\"missing_first_name\", &missingFirstName)\n\tm.Set(\"missing_last_name\", &missingLastName)\n\tm.Set(\"missing_email\", &missingEmail)\n\tm.Set(\"missing_coc\", &missingCoC)\n\tm.Set(\"failed_captcha\", &failedCaptcha)\n\tm.Set(\"invalid_captcha\", &invalidCaptcha)\n\tm.Set(\"successful_captcha\", &successfulCaptcha)\n\t\/\/ Init stuff\n\tcaptcha = recaptcha.New(c.CaptchaSecret)\n\tapi = slack.New(c.SlackToken)\n\tbufpool = bpool.NewBufferPool(64)\n}\nfunc main() {\n\tgo pollSlack()\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"\/invite\/\", handleInvite)\n\tmux.Handle(\"\/static\/\", http.StripPrefix(\"\/static\/\", http.FileServer(http.Dir(\".\/static\"))))\n\tmux.HandleFunc(\"\/\", homepage)\n\tmux.Handle(\"\/debug\/vars\", http.DefaultServeMux)\n\terr := http.ListenAndServe(\":\"+c.Port, handlers.CombinedLoggingHandler(os.Stdout, mux))\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n}\nfunc pollSlack() {\n\tfor {\n\t\tusers, err := api.GetUsers()\n\t\tif err != nil {\n\t\t\tlog.Println(\"error polling slack for users:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tuCount := 0 \/\/ users\n\t\taCount := 0 \/\/ active users\n\t\tfor _, u := range users {\n\t\t\tif u.ID != \"USLACKBOT\" && !u.IsBot && !u.Deleted {\n\t\t\t\tuCount += 1\n\t\t\t\tif u.Presence == \"active\" {\n\t\t\t\t\taCount += 1\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstatsMutex.Lock()\n\t\tuserCount = uCount\n\t\tactiveUserCount = aCount\n\t\tstatsMutex.Unlock()\n\t\ttime.Sleep(10 * time.Minute)\n\t}\n}\n\n\/\/ Homepage renders the homepage\nfunc homepage(w http.ResponseWriter, r *http.Request) {\n\tcounter.Incr(1)\n\thitsPerMinute.Set(counter.Rate())\n\trequests.Add(1)\n\tstatsMutex.RLock()\n\tdata := map[string]interface{}{\"SiteKey\": c.CaptchaSitekey, \"UserCount\": userCount, \"ActiveCount\": activeUserCount}\n\tstatsMutex.RUnlock()\n\tbuf := bufpool.Get()\n\tdefer bufpool.Put(buf)\n\terr := indexTemplate.Execute(buf, data)\n\tif err != nil {\n\t\tlog.Println(\"error rendering template:\", err)\n\t\thttp.Error(w, \"error rendering template :-(\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\t\/\/ Set the header and write the buffer to the http.ResponseWriter\n\tw.Header().Set(\"Content-Type\", \"text\/html; charset=utf-8\")\n\tbuf.WriteTo(w)\n}\n\n\/\/ ShowPost renders a single post\nfunc handleInvite(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"POST\" {\n\t\thttp.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\t\treturn\n\t}\n\tcaptchaResponse := r.FormValue(\"g-recaptcha-response\")\n\tremoteIP, _, err := net.SplitHostPort(r.RemoteAddr)\n\tif err != nil {\n\t\tfailedCaptcha.Add(1)\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvalid, err := captcha.Verify(captchaResponse, remoteIP)\n\tif err != nil {\n\t\tfailedCaptcha.Add(1)\n\t\thttp.Error(w, \"Error validating recaptcha.. Did you click it?\", http.StatusPreconditionFailed)\n\t\treturn\n\t}\n\tif !valid {\n\t\tinvalidCaptcha.Add(1)\n\t\thttp.Error(w, \"Invalid recaptcha\", http.StatusInternalServerError)\n\t\treturn\n\n\t}\n\tsuccessfulCaptcha.Add(1)\n\tfname := r.FormValue(\"fname\")\n\tlname := r.FormValue(\"lname\")\n\temail := r.FormValue(\"email\")\n\tcoc := r.FormValue(\"coc\")\n\tif email == \"\" {\n\t\tmissingEmail.Add(1)\n\t\thttp.Error(w, \"Missing email\", http.StatusPreconditionFailed)\n\t\treturn\n\t}\n\tif fname == \"\" {\n\t\tmissingFirstName.Add(1)\n\t\thttp.Error(w, \"Missing first name\", http.StatusPreconditionFailed)\n\t\treturn\n\t}\n\tif lname == \"\" {\n\t\tmissingLastName.Add(1)\n\t\thttp.Error(w, \"Missing last name\", http.StatusPreconditionFailed)\n\t\treturn\n\t}\n\tif coc != \"1\" {\n\t\tmissingCoC.Add(1)\n\t\thttp.Error(w, \"You need to accept the code of conduct\", http.StatusPreconditionFailed)\n\t\treturn\n\t}\n\terr = api.InviteToTeam(\"Gophers\", fname, lname, email)\n\tif err != nil {\n\t\tlog.Println(\"InviteToTeam error:\", err)\n\t\tinviteErrors.Add(1)\n\t\thttp.Error(w, \"Error inviting you :-(\", http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ SVFS implements a virtual file system for Openstack Swift.\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/ncw\/swift\"\n\t\"github.com\/xlucas\/svfs\/svfs\"\n\n\tfuse \"bazil.org\/fuse\"\n\tfusefs \"bazil.org\/fuse\/fs\"\n)\n\nfunc main() {\n\tsc := swift.Connection{}\n\tlog.SetOutput(os.Stderr)\n\n\t\/\/ FS options\n\tflag.StringVar(&sc.UserName, \"u\", \"\", \"User name\")\n\tflag.StringVar(&sc.ApiKey, \"p\", \"\", \"User password\")\n\tflag.StringVar(&sc.AuthUrl, \"a\", \"https:\/\/auth.cloud.ovh.net\/v2.0\", \"Authentication URL\")\n\tflag.StringVar(&sc.Region, \"r\", \"\", \"Region\")\n\tflag.StringVar(&sc.Tenant, \"t\", \"\", \"Tenant name\")\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s :\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\tflag.Parse()\n\n\t\/\/ Mountpoint is mandatory\n\tif flag.NArg() != 1 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\tmountpoint := os.Args[len(os.Args)-1]\n\n\t\/\/ Mount SVFS\n\tc, err := fuse.Mount(\n\t\tmountpoint,\n\t\tfuse.FSName(\"svfs\"),\n\t\tfuse.Subtype(\"svfs\"),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\t\/\/ Pre-Serve: authenticate to identity endpoint\n\tif err = sc.Authenticate(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Init SVFS\n\tsvfs := &svfs.SVFS{}\n\tif err = svfs.Init(&sc); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Serve SVFS\n\tsrv := fusefs.New(c, nil)\n\tif err = srv.Serve(svfs); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Check for mount errors\n\t<-c.Ready\n\tif err = c.MountError; err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>Bugfix: closes #4<commit_after>\/\/ SVFS implements a virtual file system for Openstack Swift.\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/ncw\/swift\"\n\t\"github.com\/xlucas\/svfs\/svfs\"\n\n\tfuse \"bazil.org\/fuse\"\n\tfusefs \"bazil.org\/fuse\/fs\"\n)\n\nfunc main() {\n\tvar (\n\t\tfs  *svfs.SVFS\n\t\tsrv *fusefs.Server\n\t\tsc  = swift.Connection{}\n\t)\n\n\t\/\/ Logger\n\tlog.SetOutput(os.Stderr)\n\n\t\/\/ FS options\n\tflag.StringVar(&sc.UserName, \"u\", \"\", \"User name\")\n\tflag.StringVar(&sc.ApiKey, \"p\", \"\", \"User password\")\n\tflag.StringVar(&sc.AuthUrl, \"a\", \"https:\/\/auth.cloud.ovh.net\/v2.0\", \"Authentication URL\")\n\tflag.StringVar(&sc.Region, \"r\", \"\", \"Region\")\n\tflag.StringVar(&sc.Tenant, \"t\", \"\", \"Tenant name\")\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of %s :\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\tflag.Parse()\n\n\t\/\/ Mountpoint is mandatory\n\tif flag.NArg() != 1 {\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\tmountpoint := os.Args[len(os.Args)-1]\n\n\t\/\/ Mount SVFS\n\tc, err := fuse.Mount(\n\t\tmountpoint,\n\t\tfuse.FSName(\"svfs\"),\n\t\tfuse.Subtype(\"svfs\"),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\t\/\/ Pre-Serve: authenticate to identity endpoint\n\tif err = sc.Authenticate(); err != nil {\n\t\tgoto Err\n\t}\n\n\t\/\/ Init SVFS\n\tfs = &svfs.SVFS{}\n\tif err = fs.Init(&sc); err != nil {\n\t\tgoto Err\n\t}\n\n\t\/\/ Serve SVFS\n\tsrv = fusefs.New(c, nil)\n\tif err = srv.Serve(fs); err != nil {\n\t\tgoto Err\n\t}\n\n\t\/\/ Check for mount errors\n\t<-c.Ready\n\tif err = c.MountError; err != nil {\n\t\tgoto Err\n\t}\n\n\treturn\n\nErr:\n\tfuse.Unmount(mountpoint)\n\tlog.Fatal(err)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/kylelemons\/go-gypsy\/yaml\"\n\t\"github.com\/shawnps\/gr\"\n\t\"github.com\/shawnps\/rt\"\n\t\"github.com\/shawnps\/sp\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"sync\"\n)\n\nvar (\n\tport       = flag.String(\"p\", \"8000\", \"Port number (default 8000)\")\n\tconfigFile = flag.String(\"c\", \"config.yml\", \"Config file (default config.yml)\")\n)\n\nfunc getYAMLString(n yaml.Node, key string) string {\n\treturn strings.TrimSpace(n.(yaml.Map)[key].(yaml.Scalar).String())\n}\n\nfunc parseYAML() (rtKey, grKey, grSecret string) {\n\tconfig, err := yaml.ReadFile(*configFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconfigRoot, _ := config.Root.(yaml.Map)\n\trtKey = configRoot[\"rt\"].(yaml.Scalar).String()\n\tg := configRoot[\"gr\"]\n\tgrKey = getYAMLString(g, \"key\")\n\tgrSecret = getYAMLString(g, \"secret\")\n\n\treturn rtKey, grKey, grSecret\n}\n\n\/\/ Search Rotten Tomatoes, Goodreads, and Spotify.\nfunc Search(q string, rtClient rt.RottenTomatoes, grClient gr.Goodreads, spClient sp.Spotify) (m []rt.Movie, g gr.GoodreadsResponse, s sp.SearchAlbumsResponse) {\n\tvar wg sync.WaitGroup\n\twg.Add(3)\n\tgo func(q string) {\n\t\tdefer wg.Done()\n\t\tmovies, err := rtClient.SearchMovies(q)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR (rt): \", err.Error())\n\t\t}\n\t\tfor _, mov := range movies {\n\t\t\tm = append(m, mov)\n\t\t}\n\t}(q)\n\tgo func(q string) {\n\t\tdefer wg.Done()\n\t\tbooks, err := grClient.SearchBooks(q)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR (gr): \", err.Error())\n\t\t}\n\t\tg = books\n\t}(q)\n\tgo func(q string) {\n\t\tdefer wg.Done()\n\t\talbums, err := spClient.SearchAlbums(q)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR (sp): \", err.Error())\n\t\t}\n\t\ts = albums\n\t}(q)\n\twg.Wait()\n\treturn m, g, s\n}\n\nfunc HomeHandler(w http.ResponseWriter, r *http.Request) {\n\tt, err := template.New(\"index.html\").ParseFiles(\"templates\/index.html\", \"templates\/base.html\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\t\/\/ Render the template\n\terr = t.ExecuteTemplate(w, \"base\", nil)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}\n\nfunc SearchHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tq := vars[\"query\"]\n\tq, err := url.QueryUnescape(q)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\trtKey, grKey, grSecret := parseYAML()\n\trtClient := rt.RottenTomatoes{rtKey}\n\tgrClient := gr.Goodreads{grKey, grSecret}\n\tspClient := sp.Spotify{}\n\tm, g, s := Search(q, rtClient, grClient, spClient)\n\t\/\/ Since spotify: URIs are not trusted, have to pass a\n\t\/\/ URL function to the template to use in hrefs\n\tfuncMap := template.FuncMap{\n\t\t\"URL\": func(q string) template.URL { return template.URL(q) },\n\t}\n\tt, err := template.New(\"search.html\").Funcs(funcMap).ParseFiles(\"templates\/search.html\", \"templates\/base.html\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\t\/\/ Render the template\n\terr = t.ExecuteTemplate(w, \"base\", map[string]interface{}{\"Movies\": m, \"Books\": g, \"Albums\": s.Albums})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}\n\nfunc main() {\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"\/\", HomeHandler)\n\tr.HandleFunc(\"\/search\/{query}\", SearchHandler)\n\thttp.Handle(\"\/\", r)\n\tfmt.Println(\"Running on localhost:\" + *port)\n\n\tlog.Fatal(http.ListenAndServe(\":\"+*port, nil))\n}\n<commit_msg>add createDb function<commit_after>package main\n\nimport (\n\t\"database\/sql\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/kylelemons\/go-gypsy\/yaml\"\n\t_ \"github.com\/mattn\/go-sqlite3\"\n\t\"github.com\/shawnps\/gr\"\n\t\"github.com\/shawnps\/rt\"\n\t\"github.com\/shawnps\/sp\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"sync\"\n)\n\nvar (\n\tport       = flag.String(\"p\", \"8000\", \"Port number (default 8000)\")\n\tconfigFile = flag.String(\"c\", \"config.yml\", \"Config file (default config.yml)\")\n)\n\nfunc getYAMLString(n yaml.Node, key string) string {\n\treturn strings.TrimSpace(n.(yaml.Map)[key].(yaml.Scalar).String())\n}\n\nfunc parseYAML() (rtKey, grKey, grSecret string) {\n\tconfig, err := yaml.ReadFile(*configFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconfigRoot, _ := config.Root.(yaml.Map)\n\trtKey = configRoot[\"rt\"].(yaml.Scalar).String()\n\tg := configRoot[\"gr\"]\n\tgrKey = getYAMLString(g, \"key\")\n\tgrSecret = getYAMLString(g, \"secret\")\n\n\treturn rtKey, grKey, grSecret\n}\n\nfunc createDb() {\n\tdb, err := sql.Open(\"sqlite3\", \".\/watchreadlisten.db\")\n\tif err != nil {\n\t\tlog.Println(\"Error opening or creating deploy_log.db: \" + err.Error())\n\t\treturn\n\t}\n\tdefer db.Close()\n\tsql := `create table if not exists entries (id integer not null primary key autoincrement, title text, link text, media_type text, timestamp datetime default current_timestamp);`\n\t_, err = db.Exec(sql)\n\tif err != nil {\n\t\tlog.Println(\"Error creating logs table: \" + err.Error())\n\t\treturn\n\t}\n}\n\n\/\/ Search Rotten Tomatoes, Goodreads, and Spotify.\nfunc Search(q string, rtClient rt.RottenTomatoes, grClient gr.Goodreads, spClient sp.Spotify) (m []rt.Movie, g gr.GoodreadsResponse, s sp.SearchAlbumsResponse) {\n\tvar wg sync.WaitGroup\n\twg.Add(3)\n\tgo func(q string) {\n\t\tdefer wg.Done()\n\t\tmovies, err := rtClient.SearchMovies(q)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR (rt): \", err.Error())\n\t\t}\n\t\tfor _, mov := range movies {\n\t\t\tm = append(m, mov)\n\t\t}\n\t}(q)\n\tgo func(q string) {\n\t\tdefer wg.Done()\n\t\tbooks, err := grClient.SearchBooks(q)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR (gr): \", err.Error())\n\t\t}\n\t\tg = books\n\t}(q)\n\tgo func(q string) {\n\t\tdefer wg.Done()\n\t\talbums, err := spClient.SearchAlbums(q)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"ERROR (sp): \", err.Error())\n\t\t}\n\t\ts = albums\n\t}(q)\n\twg.Wait()\n\treturn m, g, s\n}\n\nfunc HomeHandler(w http.ResponseWriter, r *http.Request) {\n\tt, err := template.New(\"index.html\").ParseFiles(\"templates\/index.html\", \"templates\/base.html\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\t\/\/ Render the template\n\terr = t.ExecuteTemplate(w, \"base\", nil)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}\n\nfunc SearchHandler(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tq := vars[\"query\"]\n\tq, err := url.QueryUnescape(q)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\trtKey, grKey, grSecret := parseYAML()\n\trtClient := rt.RottenTomatoes{rtKey}\n\tgrClient := gr.Goodreads{grKey, grSecret}\n\tspClient := sp.Spotify{}\n\tm, g, s := Search(q, rtClient, grClient, spClient)\n\t\/\/ Since spotify: URIs are not trusted, have to pass a\n\t\/\/ URL function to the template to use in hrefs\n\tfuncMap := template.FuncMap{\n\t\t\"URL\": func(q string) template.URL { return template.URL(q) },\n\t}\n\tt, err := template.New(\"search.html\").Funcs(funcMap).ParseFiles(\"templates\/search.html\", \"templates\/base.html\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\t\/\/ Render the template\n\terr = t.ExecuteTemplate(w, \"base\", map[string]interface{}{\"Movies\": m, \"Books\": g, \"Albums\": s.Albums})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}\n\nfunc main() {\n\tcreateDb()\n\tr := mux.NewRouter()\n\tr.HandleFunc(\"\/\", HomeHandler)\n\tr.HandleFunc(\"\/search\/{query}\", SearchHandler)\n\thttp.Handle(\"\/\", r)\n\tfmt.Println(\"Running on localhost:\" + *port)\n\n\tlog.Fatal(http.ListenAndServe(\":\"+*port, nil))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/ark-lang\/ark\/codegen\"\n\t\"github.com\/ark-lang\/ark\/codegen\/LLVMCodegen\"\n\t\"github.com\/ark-lang\/ark\/codegen\/arkcodegen\"\n\t\"github.com\/ark-lang\/ark\/common\"\n\t\"github.com\/ark-lang\/ark\/doc\"\n\t\"github.com\/ark-lang\/ark\/lexer\"\n\t\"github.com\/ark-lang\/ark\/parser\"\n\t\"github.com\/ark-lang\/ark\/util\"\n)\n\nfunc main() {\n\tstartTime := time.Now()\n\n\tverbose := true\n\tcodegenFlag := \"llvm\" \/\/ defaults to none\n\tdocFlag := false\n\n\tsourcefiles := make([]*common.Sourcefile, 0)\n\n\t\/\/ TODO write nice arg parser, should be POSIX-based\n\targuments := os.Args[1:]\n\tfor _, arg := range arguments {\n\t\tif strings.HasSuffix(arg, \".ark\") {\n\t\t\tinput, err := common.NewSourcefile(arg)\n\t\t\tcheck(err)\n\t\t\tsourcefiles = append(sourcefiles, input)\n\t\t} else if strings.HasPrefix(arg, \"--codegen=\") {\n\t\t\tcodegenFlag = arg[len(\"--codegen=\"):]\n\t\t\tswitch codegenFlag {\n\t\t\tcase \"none\", \"llvm\", \"ark\":\n\t\t\t\t\/\/ nothing to do\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Invalid argument to --codegen:\", codegenFlag)\n\t\t\t\tfmt.Println(\"Valid arguments: none, llvm, ark\")\n\t\t\t\tos.Exit(99)\n\t\t\t}\n\t\t} else if arg == \"--version\" {\n\t\t\tversion()\n\t\t\treturn\n\t\t} else if arg == \"-v\" {\n\t\t\tverbose = true\n\t\t} else if arg == \"--docgen\" {\n\t\t\tdocFlag = true\n\t\t} else {\n\t\t\tfmt.Println(\"Unknown command:\", arg)\n\t\t\tos.Exit(98)\n\t\t}\n\t}\n\n\tfor _, file := range sourcefiles {\n\t\tfile.Tokens = lexer.Lex(file.Contents, file.Filename, verbose)\n\t}\n\n\tparsedFiles := make([]*parser.File, 0)\n\tfor _, file := range sourcefiles {\n\t\tparsedFiles = append(parsedFiles, parser.Parse(file, verbose))\n\t}\n\n\tif docFlag {\n\t\tdocgen := &doc.Docgen{\n\t\t\tInput: parsedFiles,\n\t\t}\n\t\tdocgen.Generate(verbose)\n\t} else if codegenFlag != \"none\" {\n\t\tvar gen codegen.Codegen\n\n\t\tswitch codegenFlag {\n\t\tcase \"ark\":\n\t\t\tgen = &arkcodegen.Codegen{}\n\t\tcase \"llvm\":\n\t\t\tgen = &LLVMCodegen.Codegen{\n\t\t\t\tOutputName: \"out\",\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(\"whoops\")\n\t\t}\n\n\t\tgen.Generate(parsedFiles, verbose)\n\t}\n\n\tdur := time.Since(startTime)\n\tfmt.Printf(\"%s %d file(s) (%.2fms)\\n\",\n\t\tutil.TEXT_GREEN+util.TEXT_BOLD+\"Finished compiling\"+util.TEXT_RESET,\n\t\tlen(sourcefiles), float32(dur.Nanoseconds())\/1000000)\n}\n\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc version() {\n\tfmt.Println(\"ark 2015 - experimental\")\n}\n<commit_msg>updated version<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/ark-lang\/ark\/codegen\"\n\t\"github.com\/ark-lang\/ark\/codegen\/LLVMCodegen\"\n\t\"github.com\/ark-lang\/ark\/codegen\/arkcodegen\"\n\t\"github.com\/ark-lang\/ark\/common\"\n\t\"github.com\/ark-lang\/ark\/doc\"\n\t\"github.com\/ark-lang\/ark\/lexer\"\n\t\"github.com\/ark-lang\/ark\/parser\"\n\t\"github.com\/ark-lang\/ark\/util\"\n)\n\nfunc main() {\n\tstartTime := time.Now()\n\n\tverbose := true\n\tcodegenFlag := \"llvm\" \/\/ defaults to none\n\tdocFlag := false\n\n\tsourcefiles := make([]*common.Sourcefile, 0)\n\n\t\/\/ TODO write nice arg parser, should be POSIX-based\n\targuments := os.Args[1:]\n\tfor _, arg := range arguments {\n\t\tif strings.HasSuffix(arg, \".ark\") {\n\t\t\tinput, err := common.NewSourcefile(arg)\n\t\t\tcheck(err)\n\t\t\tsourcefiles = append(sourcefiles, input)\n\t\t} else if strings.HasPrefix(arg, \"--codegen=\") {\n\t\t\tcodegenFlag = arg[len(\"--codegen=\"):]\n\t\t\tswitch codegenFlag {\n\t\t\tcase \"none\", \"llvm\", \"ark\":\n\t\t\t\t\/\/ nothing to do\n\t\t\tdefault:\n\t\t\t\tfmt.Println(\"Invalid argument to --codegen:\", codegenFlag)\n\t\t\t\tfmt.Println(\"Valid arguments: none, llvm, ark\")\n\t\t\t\tos.Exit(99)\n\t\t\t}\n\t\t} else if arg == \"--version\" {\n\t\t\tversion()\n\t\t\treturn\n\t\t} else if arg == \"-v\" {\n\t\t\tverbose = true\n\t\t} else if arg == \"--docgen\" {\n\t\t\tdocFlag = true\n\t\t} else {\n\t\t\tfmt.Println(\"Unknown command:\", arg)\n\t\t\tos.Exit(98)\n\t\t}\n\t}\n\n\tfor _, file := range sourcefiles {\n\t\tfile.Tokens = lexer.Lex(file.Contents, file.Filename, verbose)\n\t}\n\n\tparsedFiles := make([]*parser.File, 0)\n\tfor _, file := range sourcefiles {\n\t\tparsedFiles = append(parsedFiles, parser.Parse(file, verbose))\n\t}\n\n\tif docFlag {\n\t\tdocgen := &doc.Docgen{\n\t\t\tInput: parsedFiles,\n\t\t}\n\t\tdocgen.Generate(verbose)\n\t} else if codegenFlag != \"none\" {\n\t\tvar gen codegen.Codegen\n\n\t\tswitch codegenFlag {\n\t\tcase \"ark\":\n\t\t\tgen = &arkcodegen.Codegen{}\n\t\tcase \"llvm\":\n\t\t\tgen = &LLVMCodegen.Codegen{\n\t\t\t\tOutputName: \"out\",\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(\"whoops\")\n\t\t}\n\n\t\tgen.Generate(parsedFiles, verbose)\n\t}\n\n\tdur := time.Since(startTime)\n\tfmt.Printf(\"%s %d file(s) (%.2fms)\\n\",\n\t\tutil.TEXT_GREEN+util.TEXT_BOLD+\"Finished compiling\"+util.TEXT_RESET,\n\t\tlen(sourcefiles), float32(dur.Nanoseconds())\/1000000)\n}\n\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc version() {\n\t\/\/ 0.2 since LLVM\/Go?\n\tfmt.Println(\"Ark version 0.2.0\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package GraphiteBase\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ The time and measured value of a metric.\ntype MetricValues struct {\n\tTime  int64\n\tValue float64\n}\n\n\/\/ A whole metric, whith name, time and value.\ntype Metric struct {\n\tMetricValues\n\tName string\n}\n\n\/\/ Create a new metric from the given parameters.\nfunc NewMetric(name string, value float64, timestamp int64) *Metric {\n\treturn &Metric{\n\t\tName: name,\n\t\tMetricValues: MetricValues{\n\t\t\tValue: value,\n\t\t\tTime: timestamp,\n\t\t},\n\t}\n}\n\n\/\/ Stringifies metric with \"<Name> <Value> <Time>\", to match Graphites Text\n\/\/ protocol.\nfunc (m *Metric) String() string {\n\treturn fmt.Sprintf(\"%s %v %d\", m.Name, m.Value, m.Time)\n}\n<commit_msg>non-fmt'ed code slipped through.<commit_after>package GraphiteBase\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ The time and measured value of a metric.\ntype MetricValues struct {\n\tTime  int64\n\tValue float64\n}\n\n\/\/ A whole metric, whith name, time and value.\ntype Metric struct {\n\tMetricValues\n\tName string\n}\n\n\/\/ Create a new metric from the given parameters.\nfunc NewMetric(name string, value float64, timestamp int64) *Metric {\n\treturn &Metric{\n\t\tName: name,\n\t\tMetricValues: MetricValues{\n\t\t\tValue: value,\n\t\t\tTime:  timestamp,\n\t\t},\n\t}\n}\n\n\/\/ Stringifies metric with \"<Name> <Value> <Time>\", to match Graphites Text\n\/\/ protocol.\nfunc (m *Metric) String() string {\n\treturn fmt.Sprintf(\"%s %v %d\", m.Name, m.Value, m.Time)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com\/gojp\/goreportcard\/handlers\"\n\n\t\"github.com\/boltdb\/bolt\"\n)\n\nvar (\n\taddr = flag.String(\"http\", \":8000\", \"HTTP listen address\")\n\tdev  = flag.Bool(\"dev\", false, \"dev mode\")\n)\n\nfunc makeHandler(name string, dev bool, fn func(http.ResponseWriter, *http.Request, string, bool)) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvalidPath := regexp.MustCompile(fmt.Sprintf(`^\/%s\/([a-zA-Z0-9\\-_\\\/\\.]+)$`, name))\n\n\t\tm := validPath.FindStringSubmatch(r.URL.Path)\n\n\t\tif m == nil {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\tif len(m) < 1 || m[1] == \"\" {\n\t\t\thttp.Error(w, \"Please enter a repository\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\trepo := m[1]\n\n\t\t\/\/ for backwards-compatibility, we must support URLs formatted as\n\t\t\/\/   \/report\/[org]\/[repo]\n\t\t\/\/ and they will be assumed to be github.com URLs. This is because\n\t\t\/\/ at first Go Report Card only supported github.com URLs, and assumed\n\t\t\/\/ took only the org name and repo name as parameters. This is no longer the\n\t\t\/\/ case, but we do not want external links to break.\n\t\toldFormat := regexp.MustCompile(fmt.Sprintf(`^\/%s\/([a-zA-Z0-9\\-_]+)\/([a-zA-Z0-9\\-_]+)$`, name))\n\t\tm2 := oldFormat.FindStringSubmatch(r.URL.Path)\n\t\tif m2 != nil {\n\t\t\t\/\/ old format is being used\n\t\t\trepo = \"github.com\/\" + repo\n\t\t\tlog.Printf(\"Assuming intended repo is %q, redirecting\", repo)\n\t\t\thttp.Redirect(w, r, fmt.Sprintf(\"\/%s\/%s\", name, repo), http.StatusMovedPermanently)\n\t\t\treturn\n\t\t}\n\n\t\tfn(w, r, repo, dev)\n\t}\n}\n\n\/\/ initDB opens the bolt database file (or creates it if it does not exist), and creates\n\/\/ a bucket for saving the repos, also only if it does not exist.\nfunc initDB() error {\n\tdb, err := bolt.Open(handlers.DBPath, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(handlers.RepoBucket))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(handlers.MetaBucket))\n\t\treturn err\n\t})\n\treturn err\n}\n\nfunc main() {\n\tflag.Parse()\n\tif err := os.MkdirAll(\"_repos\/src\/github.com\", 0755); err != nil && !os.IsExist(err) {\n\t\tlog.Fatal(\"ERROR: could not create repos dir: \", err)\n\t}\n\n\t\/\/ initialize database\n\tif err := initDB(); err != nil {\n\t\tlog.Fatal(\"ERROR: could not open bolt db: \", err)\n\t}\n\n\thttp.HandleFunc(\"\/assets\/\", handlers.AssetsHandler)\n\thttp.HandleFunc(\"\/favicon.ico\", handlers.FaviconHandler)\n\thttp.HandleFunc(\"\/checks\", handlers.CheckHandler)\n\thttp.HandleFunc(\"\/report\/\", makeHandler(\"report\", *dev, handlers.ReportHandler))\n\thttp.HandleFunc(\"\/badge\/\", makeHandler(\"badge\", *dev, handlers.BadgeHandler))\n\thttp.HandleFunc(\"\/high_scores\/\", handlers.HighScoresHandler)\n\thttp.HandleFunc(\"\/about\/\", handlers.AboutHandler)\n\thttp.HandleFunc(\"\/\", handlers.HomeHandler)\n\n\tlog.Printf(\"Running on %s ...\", *addr)\n\tlog.Fatal(http.ListenAndServe(*addr, nil))\n}\n<commit_msg>fix typo<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com\/gojp\/goreportcard\/handlers\"\n\n\t\"github.com\/boltdb\/bolt\"\n)\n\nvar (\n\taddr = flag.String(\"http\", \":8000\", \"HTTP listen address\")\n\tdev  = flag.Bool(\"dev\", false, \"dev mode\")\n)\n\nfunc makeHandler(name string, dev bool, fn func(http.ResponseWriter, *http.Request, string, bool)) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvalidPath := regexp.MustCompile(fmt.Sprintf(`^\/%s\/([a-zA-Z0-9\\-_\\\/\\.]+)$`, name))\n\n\t\tm := validPath.FindStringSubmatch(r.URL.Path)\n\n\t\tif m == nil {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\tif len(m) < 1 || m[1] == \"\" {\n\t\t\thttp.Error(w, \"Please enter a repository\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\trepo := m[1]\n\n\t\t\/\/ for backwards-compatibility, we must support URLs formatted as\n\t\t\/\/   \/report\/[org]\/[repo]\n\t\t\/\/ and they will be assumed to be github.com URLs. This is because\n\t\t\/\/ at first Go Report Card only supported github.com URLs, and\n\t\t\/\/ took only the org name and repo name as parameters. This is no longer the\n\t\t\/\/ case, but we do not want external links to break.\n\t\toldFormat := regexp.MustCompile(fmt.Sprintf(`^\/%s\/([a-zA-Z0-9\\-_]+)\/([a-zA-Z0-9\\-_]+)$`, name))\n\t\tm2 := oldFormat.FindStringSubmatch(r.URL.Path)\n\t\tif m2 != nil {\n\t\t\t\/\/ old format is being used\n\t\t\trepo = \"github.com\/\" + repo\n\t\t\tlog.Printf(\"Assuming intended repo is %q, redirecting\", repo)\n\t\t\thttp.Redirect(w, r, fmt.Sprintf(\"\/%s\/%s\", name, repo), http.StatusMovedPermanently)\n\t\t\treturn\n\t\t}\n\n\t\tfn(w, r, repo, dev)\n\t}\n}\n\n\/\/ initDB opens the bolt database file (or creates it if it does not exist), and creates\n\/\/ a bucket for saving the repos, also only if it does not exist.\nfunc initDB() error {\n\tdb, err := bolt.Open(handlers.DBPath, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer db.Close()\n\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\t_, err := tx.CreateBucketIfNotExists([]byte(handlers.RepoBucket))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.CreateBucketIfNotExists([]byte(handlers.MetaBucket))\n\t\treturn err\n\t})\n\treturn err\n}\n\nfunc main() {\n\tflag.Parse()\n\tif err := os.MkdirAll(\"_repos\/src\/github.com\", 0755); err != nil && !os.IsExist(err) {\n\t\tlog.Fatal(\"ERROR: could not create repos dir: \", err)\n\t}\n\n\t\/\/ initialize database\n\tif err := initDB(); err != nil {\n\t\tlog.Fatal(\"ERROR: could not open bolt db: \", err)\n\t}\n\n\thttp.HandleFunc(\"\/assets\/\", handlers.AssetsHandler)\n\thttp.HandleFunc(\"\/favicon.ico\", handlers.FaviconHandler)\n\thttp.HandleFunc(\"\/checks\", handlers.CheckHandler)\n\thttp.HandleFunc(\"\/report\/\", makeHandler(\"report\", *dev, handlers.ReportHandler))\n\thttp.HandleFunc(\"\/badge\/\", makeHandler(\"badge\", *dev, handlers.BadgeHandler))\n\thttp.HandleFunc(\"\/high_scores\/\", handlers.HighScoresHandler)\n\thttp.HandleFunc(\"\/about\/\", handlers.AboutHandler)\n\thttp.HandleFunc(\"\/\", handlers.HomeHandler)\n\n\tlog.Printf(\"Running on %s ...\", *addr)\n\tlog.Fatal(http.ListenAndServe(*addr, nil))\n}\n<|endoftext|>"}
{"text":"<commit_before>package uploads\n\nimport (\n\t\"github.com\/materials-commons\/mcstore\/pkg\/app\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/db\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/db\/dai\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/db\/schema\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/domain\"\n)\n\ntype UploadsService interface {\n\tCreate(req CreateRequest) (*schema.Upload, error)\n}\n\ntype uploadsService struct {\n\tdirs     dai.Dirs\n\tprojects dai.Projects\n\tuploads  dai.Uploads\n\taccess   domain.Access\n}\n\nfunc NewUploadsService() *uploadsService {\n\tsession := db.RSessionMust()\n\taccess := domain.NewAccess(dai.NewRGroups(session), dai.NewRFiles(session), dai.NewRUsers(session))\n\treturn &uploadsService{\n\t\tdirs:     dai.NewRDirs(session),\n\t\tprojects: dai.NewRProjects(session),\n\t\tuploads:  dai.NewRUploads(session),\n\t\taccess:   access,\n\t}\n}\n\nfunc NewUploadsServiceFrom(dirs dai.Dirs, projects dai.Projects, uploads dai.Uploads, access domain.Access) *uploadsService {\n\treturn &uploadsService{\n\t\tdirs:     dirs,\n\t\tprojects: projects,\n\t\tuploads:  uploads,\n\t\taccess:   access,\n\t}\n}\n\nfunc (s *uploadsService) Create(req CreateRequest) (*schema.Upload, error) {\n\tproj, err := s.getProj(req.ProjectID, req.User)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdir, err := s.getDir(req.DirectoryID, proj.ID, req.User)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tupload := schema.CUpload().\n\t\tOwner(req.User).\n\t\tProject(req.ProjectID, proj.Name).\n\t\tDirectory(req.DirectoryID, dir.Name).\n\t\tHost(req.Host).\n\t\tCreate()\n\treturn s.uploads.Insert(&upload)\n}\n\nfunc (s *uploadsService) getProj(projectID, user string) (*schema.Project, error) {\n\tproject, err := s.projects.ByID(projectID)\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase !s.access.AllowedByOwner(project.Owner, user):\n\t\treturn nil, app.ErrNoAccess\n\tdefault:\n\t\treturn project, nil\n\t}\n}\n\nfunc (s *uploadsService) getDir(directoryID, projectID, user string) (*schema.Directory, error) {\n\tdir, err := s.dirs.ByID(directoryID)\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase !s.access.AllowedByOwner(dir.Owner, user):\n\t\treturn nil, app.ErrNoAccess\n\tcase !s.projects.HasDirectory(projectID, directoryID):\n\t\treturn nil, app.ErrInvalid\n\tdefault:\n\t\treturn dir, nil\n\t}\n}\n<commit_msg>Change service to a create service.<commit_after>package uploads\n\nimport (\n\t\"github.com\/materials-commons\/mcstore\/pkg\/app\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/db\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/db\/dai\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/db\/schema\"\n\t\"github.com\/materials-commons\/mcstore\/pkg\/domain\"\n)\n\ntype CreateService interface {\n\tCreate(req CreateRequest) (*schema.Upload, error)\n}\n\ntype createService struct {\n\tdirs     dai.Dirs\n\tprojects dai.Projects\n\tuploads  dai.Uploads\n\taccess   domain.Access\n}\n\nfunc NewCreateService() *createService {\n\tsession := db.RSessionMust()\n\taccess := domain.NewAccess(dai.NewRGroups(session), dai.NewRFiles(session), dai.NewRUsers(session))\n\treturn &createService{\n\t\tdirs:     dai.NewRDirs(session),\n\t\tprojects: dai.NewRProjects(session),\n\t\tuploads:  dai.NewRUploads(session),\n\t\taccess:   access,\n\t}\n}\n\nfunc NewCreateServiceFrom(dirs dai.Dirs, projects dai.Projects, uploads dai.Uploads, access domain.Access) *createService {\n\treturn &createService{\n\t\tdirs:     dirs,\n\t\tprojects: projects,\n\t\tuploads:  uploads,\n\t\taccess:   access,\n\t}\n}\n\nfunc (s *createService) Create(req CreateRequest) (*schema.Upload, error) {\n\tproj, err := s.getProj(req.ProjectID, req.User)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdir, err := s.getDir(req.DirectoryID, proj.ID, req.User)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tupload := schema.CUpload().\n\t\tOwner(req.User).\n\t\tProject(req.ProjectID, proj.Name).\n\t\tDirectory(req.DirectoryID, dir.Name).\n\t\tHost(req.Host).\n\t\tCreate()\n\treturn s.uploads.Insert(&upload)\n}\n\nfunc (s *createService) getProj(projectID, user string) (*schema.Project, error) {\n\tproject, err := s.projects.ByID(projectID)\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase !s.access.AllowedByOwner(project.Owner, user):\n\t\treturn nil, app.ErrNoAccess\n\tdefault:\n\t\treturn project, nil\n\t}\n}\n\nfunc (s *createService) getDir(directoryID, projectID, user string) (*schema.Directory, error) {\n\tdir, err := s.dirs.ByID(directoryID)\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase !s.access.AllowedByOwner(dir.Owner, user):\n\t\treturn nil, app.ErrNoAccess\n\tcase !s.projects.HasDirectory(projectID, directoryID):\n\t\treturn nil, app.ErrInvalid\n\tdefault:\n\t\treturn dir, nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/mpdroog\/beanstalkd\" \/\/\"github.com\/maxid\/beanstalkd\"\n\t\"gopkg.in\/gomail.v1\"\n\t\"os\"\n\t\"smtpw\/config\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst ERR_WAIT_SEC = 5\n\nvar verbose bool\nvar readonly bool\nvar hostname string\n\nfunc proc(m config.Email) error {\n\tconf, ok := config.C.From[m.From]\n\tif !ok {\n\t\treturn errors.New(\"From does not exist: \" + m.From)\n\t}\n\n\tmsg := gomail.NewMessage()\n\tmsg.SetHeader(\"Message-ID\", fmt.Sprintf(\"<%s@%s>\", RandText(32), hostname))\n\tif conf.Bounce == nil {\n\t\tmsg.SetHeader(\"From\", conf.Display+\" <\"+conf.From+\">\")\n\t} else {\n\t\t\/\/ Set bounce handling\n\t\t\/\/ From receives bounces\n\t\t\/\/ Human-clients send to Reply-To\n\t\tmsg.SetHeader(\"From\", fmt.Sprintf(\"%s <%s>\", conf.Display, *conf.Bounce))\n\t\tmsg.SetHeader(\"Reply-To\", fmt.Sprintf(\"%s <%s>\", conf.Display, conf.From))\n\t}\n\tmsg.SetHeader(\"To\", m.To...)\n\tmsg.SetHeader(\"Bcc\", conf.Bcc...)\n\tmsg.SetHeader(\"Subject\", m.Subject)\n\tmsg.SetBody(\"text\/plain\", m.Text)\n\tif len(m.Html) > 0 {\n\t\tmsg.AddAlternative(\"text\/html\", m.Html)\n\t}\n\n\tfor name, embed := range m.HtmlEmbed {\n\t\traw, e := base64.StdEncoding.DecodeString(embed)\n\t\tif e != nil {\n\t\t\treturn errors.New(\"HtmlEmbed: \" + name + \" is not base64!\")\n\t\t}\n\t\tif !strings.Contains(m.Html, fmt.Sprintf(\"cid:\"+name)) {\n\t\t\treturn errors.New(\"HtmlEmbed: \" + name + \" is not used in the HTML!\")\n\t\t}\n\t\tmsg.Embed(gomail.CreateFile(name, raw))\n\t}\n\tfor name, attachment := range m.Attachments {\n\t\traw, e := base64.StdEncoding.DecodeString(embed)\n\t\tif e != nil {\n\t\t\treturn errors.New(\"Attachment: \" + name + \" is not base64!\")\n\t\t}\n\t\tmsg.Embed(gomail.CreateFile(name, raw))\n\t}\n\n\tif readonly {\n\t\tfmt.Println(\"From: \" + conf.Display + \" <\" + conf.From + \">\")\n\t\tfmt.Println(fmt.Sprintf(\"To: %v\", m.To))\n\t\tfmt.Println(fmt.Sprintf(\"Bcc: %v\", conf.Bcc))\n\t\tfmt.Println(\"Subject: \" + m.Subject)\n\t\tfmt.Println(\"\\ntext\/plain\")\n\t\tfmt.Println(m.Text)\n\t\tfmt.Println(\"\\ntext\/html\")\n\t\tfmt.Println(m.Html)\n\t\tfmt.Println(\"\\n\")\n\t\treturn nil\n\t}\n\n\tmailer := gomail.NewMailer(conf.Host, conf.User, conf.Pass, conf.Port)\n\treturn mailer.Send(msg)\n}\n\nfunc connect() (*beanstalkd.BeanstalkdClient, error) {\n\tqueue, e := beanstalkd.Dial(config.C.Beanstalk)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\t\/\/ Only listen to email queue.\n\tqueue.Use(\"email\")\n\tif _, e := queue.Watch(\"email\"); e != nil {\n\t\treturn nil, e\n\t}\n\tqueue.Ignore(\"default\")\n\treturn queue, nil\n}\n\nfunc main() {\n\tvar (\n\t\tconfigPath string\n\t\tskipOne    bool\n\t)\n\tflag.BoolVar(&verbose, \"v\", false, \"Verbose-mode\")\n\tflag.BoolVar(&skipOne, \"s\", false, \"Delete e-mail on deverr\")\n\tflag.BoolVar(&readonly, \"r\", false, \"Don't email but flush to stdout\")\n\tflag.StringVar(&configPath, \"c\", \".\/config.json\", \"Path to config.json\")\n\tflag.Parse()\n\n\tif e := config.Init(configPath); e != nil {\n\t\tpanic(e)\n\t}\n\tif verbose {\n\t\tfmt.Printf(\"%+v\\n\", config.C)\n\t}\n\t\/\/ TODO: Test config before starting?\n\n\tqueue, e := connect()\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\thostname, e = os.Hostname()\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\n\tif verbose {\n\t\tfmt.Println(\"SMTPw(\" + hostname + \") email-tube (ignoring default)\")\n\t}\n\tif readonly {\n\t\tfmt.Println(\"!! ReadOnly mode !!\")\n\t}\n\tfor {\n\t\tjob, e := queue.Reserve(0)\n\t\tif e != nil {\n\t\t\tfmt.Println(\"Beanstalkd err: \" + e.Error())\n\t\t\ttime.Sleep(time.Second * ERR_WAIT_SEC)\n\t\t\tif strings.HasSuffix(e.Error(), \"broken pipe\") {\n\t\t\t\t\/\/ Beanstalkd down, reconnect!\n\t\t\t\tq, e := connect()\n\t\t\t\tif e != nil {\n\t\t\t\t\tfmt.Println(\"Reconnect err: \" + e.Error())\n\t\t\t\t}\n\t\t\t\tif q != nil {\n\t\t\t\t\tqueue = q\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif verbose {\n\t\t\tfmt.Println(fmt.Sprintf(\"Parse job %d\", job.Id))\n\t\t\tfmt.Println(\"JSON:\\r\\n\" + string(job.Data))\n\t\t}\n\t\t\/\/ Parse\n\t\tvar m config.Email\n\t\tif e := json.Unmarshal(job.Data, &m); e != nil {\n\t\t\t\/\/ Broken JSON\n\t\t\tif skipOne {\n\t\t\t\tfmt.Println(\"WARN: Skip job as JSON is invalid\")\n\t\t\t\tqueue.Delete(job.Id)\n\t\t\t\tskipOne = false\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ Ignore decode trouble\n\t\t\tfmt.Println(\"CRIT: Invalid JSON received (msg=\" + e.Error() + \")\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif e := proc(m); e != nil {\n\t\t\t\/\/ TODO: Isolate deverr from senderr\n\t\t\t\/\/ Processing trouble?\n\t\t\tfmt.Println(\"WARN: Failed sending, retry in 20sec (msg=\" + e.Error() + \")\")\n\t\t\tcontinue\n\t\t}\n\t\tqueue.Delete(job.Id)\n\t\tif verbose {\n\t\t\tfmt.Println(fmt.Sprintf(\"Finished job %d\", job.Id))\n\t\t}\n\t}\n\tqueue.Quit()\n}\n<commit_msg>Bugfix. No such var embed<commit_after>package main\n\nimport (\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/mpdroog\/beanstalkd\" \/\/\"github.com\/maxid\/beanstalkd\"\n\t\"gopkg.in\/gomail.v1\"\n\t\"os\"\n\t\"smtpw\/config\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst ERR_WAIT_SEC = 5\n\nvar verbose bool\nvar readonly bool\nvar hostname string\n\nfunc proc(m config.Email) error {\n\tconf, ok := config.C.From[m.From]\n\tif !ok {\n\t\treturn errors.New(\"From does not exist: \" + m.From)\n\t}\n\n\tmsg := gomail.NewMessage()\n\tmsg.SetHeader(\"Message-ID\", fmt.Sprintf(\"<%s@%s>\", RandText(32), hostname))\n\tif conf.Bounce == nil {\n\t\tmsg.SetHeader(\"From\", conf.Display+\" <\"+conf.From+\">\")\n\t} else {\n\t\t\/\/ Set bounce handling\n\t\t\/\/ From receives bounces\n\t\t\/\/ Human-clients send to Reply-To\n\t\tmsg.SetHeader(\"From\", fmt.Sprintf(\"%s <%s>\", conf.Display, *conf.Bounce))\n\t\tmsg.SetHeader(\"Reply-To\", fmt.Sprintf(\"%s <%s>\", conf.Display, conf.From))\n\t}\n\tmsg.SetHeader(\"To\", m.To...)\n\tmsg.SetHeader(\"Bcc\", conf.Bcc...)\n\tmsg.SetHeader(\"Subject\", m.Subject)\n\tmsg.SetBody(\"text\/plain\", m.Text)\n\tif len(m.Html) > 0 {\n\t\tmsg.AddAlternative(\"text\/html\", m.Html)\n\t}\n\n\tfor name, embed := range m.HtmlEmbed {\n\t\traw, e := base64.StdEncoding.DecodeString(embed)\n\t\tif e != nil {\n\t\t\treturn errors.New(\"HtmlEmbed: \" + name + \" is not base64!\")\n\t\t}\n\t\tif !strings.Contains(m.Html, fmt.Sprintf(\"cid:\"+name)) {\n\t\t\treturn errors.New(\"HtmlEmbed: \" + name + \" is not used in the HTML!\")\n\t\t}\n\t\tmsg.Embed(gomail.CreateFile(name, raw))\n\t}\n\tfor name, attachment := range m.Attachments {\n\t\traw, e := base64.StdEncoding.DecodeString(attachment)\n\t\tif e != nil {\n\t\t\treturn errors.New(\"Attachment: \" + name + \" is not base64!\")\n\t\t}\n\t\tmsg.Embed(gomail.CreateFile(name, raw))\n\t}\n\n\tif readonly {\n\t\tfmt.Println(\"From: \" + conf.Display + \" <\" + conf.From + \">\")\n\t\tfmt.Println(fmt.Sprintf(\"To: %v\", m.To))\n\t\tfmt.Println(fmt.Sprintf(\"Bcc: %v\", conf.Bcc))\n\t\tfmt.Println(\"Subject: \" + m.Subject)\n\t\tfmt.Println(\"\\ntext\/plain\")\n\t\tfmt.Println(m.Text)\n\t\tfmt.Println(\"\\ntext\/html\")\n\t\tfmt.Println(m.Html)\n\t\tfmt.Println(\"\\n\")\n\t\treturn nil\n\t}\n\n\tmailer := gomail.NewMailer(conf.Host, conf.User, conf.Pass, conf.Port)\n\treturn mailer.Send(msg)\n}\n\nfunc connect() (*beanstalkd.BeanstalkdClient, error) {\n\tqueue, e := beanstalkd.Dial(config.C.Beanstalk)\n\tif e != nil {\n\t\treturn nil, e\n\t}\n\t\/\/ Only listen to email queue.\n\tqueue.Use(\"email\")\n\tif _, e := queue.Watch(\"email\"); e != nil {\n\t\treturn nil, e\n\t}\n\tqueue.Ignore(\"default\")\n\treturn queue, nil\n}\n\nfunc main() {\n\tvar (\n\t\tconfigPath string\n\t\tskipOne    bool\n\t)\n\tflag.BoolVar(&verbose, \"v\", false, \"Verbose-mode\")\n\tflag.BoolVar(&skipOne, \"s\", false, \"Delete e-mail on deverr\")\n\tflag.BoolVar(&readonly, \"r\", false, \"Don't email but flush to stdout\")\n\tflag.StringVar(&configPath, \"c\", \".\/config.json\", \"Path to config.json\")\n\tflag.Parse()\n\n\tif e := config.Init(configPath); e != nil {\n\t\tpanic(e)\n\t}\n\tif verbose {\n\t\tfmt.Printf(\"%+v\\n\", config.C)\n\t}\n\t\/\/ TODO: Test config before starting?\n\n\tqueue, e := connect()\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\thostname, e = os.Hostname()\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\n\tif verbose {\n\t\tfmt.Println(\"SMTPw(\" + hostname + \") email-tube (ignoring default)\")\n\t}\n\tif readonly {\n\t\tfmt.Println(\"!! ReadOnly mode !!\")\n\t}\n\tfor {\n\t\tjob, e := queue.Reserve(0)\n\t\tif e != nil {\n\t\t\tfmt.Println(\"Beanstalkd err: \" + e.Error())\n\t\t\ttime.Sleep(time.Second * ERR_WAIT_SEC)\n\t\t\tif strings.HasSuffix(e.Error(), \"broken pipe\") {\n\t\t\t\t\/\/ Beanstalkd down, reconnect!\n\t\t\t\tq, e := connect()\n\t\t\t\tif e != nil {\n\t\t\t\t\tfmt.Println(\"Reconnect err: \" + e.Error())\n\t\t\t\t}\n\t\t\t\tif q != nil {\n\t\t\t\t\tqueue = q\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif verbose {\n\t\t\tfmt.Println(fmt.Sprintf(\"Parse job %d\", job.Id))\n\t\t\tfmt.Println(\"JSON:\\r\\n\" + string(job.Data))\n\t\t}\n\t\t\/\/ Parse\n\t\tvar m config.Email\n\t\tif e := json.Unmarshal(job.Data, &m); e != nil {\n\t\t\t\/\/ Broken JSON\n\t\t\tif skipOne {\n\t\t\t\tfmt.Println(\"WARN: Skip job as JSON is invalid\")\n\t\t\t\tqueue.Delete(job.Id)\n\t\t\t\tskipOne = false\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ Ignore decode trouble\n\t\t\tfmt.Println(\"CRIT: Invalid JSON received (msg=\" + e.Error() + \")\")\n\t\t\tcontinue\n\t\t}\n\n\t\tif e := proc(m); e != nil {\n\t\t\t\/\/ TODO: Isolate deverr from senderr\n\t\t\t\/\/ Processing trouble?\n\t\t\tfmt.Println(\"WARN: Failed sending, retry in 20sec (msg=\" + e.Error() + \")\")\n\t\t\tcontinue\n\t\t}\n\t\tqueue.Delete(job.Id)\n\t\tif verbose {\n\t\t\tfmt.Println(fmt.Sprintf(\"Finished job %d\", job.Id))\n\t\t}\n\t}\n\tqueue.Quit()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tDEFAULT_PORT     = \"8080\"\n\tCF_FORWARDED_URL = \"X-Cf-Forwarded-Url\"\n\tDEFAULT_LIMIT    = 10\n)\n\nvar (\n\tlimit       int\n\trateLimiter *RateLimiter\n)\n\nfunc main() {\n\tlog.SetOutput(os.Stdout)\n\n\tlimit = getEnv(\"rate_limit\", DEFAULT_LIMIT)\n\tfmt.Printf(\"limit per sec [%d]\\n\", limit)\n\n\trateLimiter = NewRateLimiter(limit)\n\n\thttp.HandleFunc(\"\/stats\", statsHandler)\n\thttp.Handle(\"\/\", newProxy())\n\tlog.Fatal(http.ListenAndServe(\":\"+getPort(), nil))\n}\n\nfunc newProxy() http.Handler {\n\tproxy := &httputil.ReverseProxy{\n\t\tDirector: func(req *http.Request) {\n\t\t\tforwardedURL := req.Header.Get(CF_FORWARDED_URL)\n\n\t\t\turl, err := url.Parse(forwardedURL)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err.Error())\n\t\t\t}\n\n\t\t\treq.URL = url\n\t\t\treq.Host = url.Host\n\t\t},\n\t\tTransport: newRateLimitedRoundTripper(),\n\t}\n\treturn proxy\n}\n\nfunc statsHandler(w http.ResponseWriter, r *http.Request) {\n\tstats, err := json.Marshal(rateLimiter.GetStats())\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\tfmt.Fprintf(w, string(stats))\n}\n\nfunc getPort() string {\n\tvar port string\n\tif port = os.Getenv(\"PORT\"); len(port) == 0 {\n\t\tport = DEFAULT_PORT\n\t}\n\treturn port\n}\n\nfunc getEnv(env string, defaultValue int) int {\n\tvar (\n\t\tv      string\n\t\tconfig int\n\t)\n\tif v = os.Getenv(env); len(v) == 0 {\n\t\treturn defaultValue\n\t}\n\n\tconfig, err := strconv.Atoi(v)\n\tif err != nil {\n\t\treturn defaultValue\n\t}\n\treturn config\n}\n\ntype RateLimitedRoundTripper struct {\n\trateLimiter *RateLimiter\n\ttransport   http.RoundTripper\n}\n\nfunc newRateLimitedRoundTripper() *RateLimitedRoundTripper {\n\treturn &RateLimitedRoundTripper{\n\t\trateLimiter: rateLimiter,\n\t\ttransport:   http.DefaultTransport,\n\t}\n}\n\nfunc (r *RateLimitedRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\tvar err error\n\tvar res *http.Response\n\n\tremoteIP := strings.Split(req.RemoteAddr, \":\")[0]\n\n\tfmt.Printf(\"request from [%s]\\n\", remoteIP)\n\tif r.rateLimiter.ExceedsLimit(remoteIP) {\n\t\tresp := &http.Response{\n\t\t\tStatusCode: 429,\n\t\t\tBody:       ioutil.NopCloser(bytes.NewBufferString(\"Too many requests\")),\n\t\t}\n\t\treturn resp, nil\n\t}\n\n\tres, err = r.transport.RoundTrip(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, err\n}\n<commit_msg>Fix logging :taco:<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tDEFAULT_PORT     = \"8080\"\n\tCF_FORWARDED_URL = \"X-Cf-Forwarded-Url\"\n\tDEFAULT_LIMIT    = 10\n)\n\nvar (\n\tlimit       int\n\trateLimiter *RateLimiter\n)\n\nfunc main() {\n\tlog.SetOutput(os.Stdout)\n\n\tlimit = getEnv(\"rate_limit\", DEFAULT_LIMIT)\n\tlog.Printf(\"limit per sec [%d]\\n\", limit)\n\n\trateLimiter = NewRateLimiter(limit)\n\n\thttp.HandleFunc(\"\/stats\", statsHandler)\n\thttp.Handle(\"\/\", newProxy())\n\tlog.Fatal(http.ListenAndServe(\":\"+getPort(), nil))\n}\n\nfunc newProxy() http.Handler {\n\tproxy := &httputil.ReverseProxy{\n\t\tDirector: func(req *http.Request) {\n\t\t\tforwardedURL := req.Header.Get(CF_FORWARDED_URL)\n\n\t\t\turl, err := url.Parse(forwardedURL)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalln(err.Error())\n\t\t\t}\n\n\t\t\treq.URL = url\n\t\t\treq.Host = url.Host\n\t\t},\n\t\tTransport: newRateLimitedRoundTripper(),\n\t}\n\treturn proxy\n}\n\nfunc statsHandler(w http.ResponseWriter, r *http.Request) {\n\tstats, err := json.Marshal(rateLimiter.GetStats())\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(stats))\n}\n\nfunc getPort() string {\n\tvar port string\n\tif port = os.Getenv(\"PORT\"); len(port) == 0 {\n\t\tport = DEFAULT_PORT\n\t}\n\treturn port\n}\n\nfunc getEnv(env string, defaultValue int) int {\n\tvar (\n\t\tv      string\n\t\tconfig int\n\t)\n\tif v = os.Getenv(env); len(v) == 0 {\n\t\treturn defaultValue\n\t}\n\n\tconfig, err := strconv.Atoi(v)\n\tif err != nil {\n\t\treturn defaultValue\n\t}\n\treturn config\n}\n\ntype RateLimitedRoundTripper struct {\n\trateLimiter *RateLimiter\n\ttransport   http.RoundTripper\n}\n\nfunc newRateLimitedRoundTripper() *RateLimitedRoundTripper {\n\treturn &RateLimitedRoundTripper{\n\t\trateLimiter: rateLimiter,\n\t\ttransport:   http.DefaultTransport,\n\t}\n}\n\nfunc (r *RateLimitedRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\tvar err error\n\tvar res *http.Response\n\n\tremoteIP := strings.Split(req.RemoteAddr, \":\")[0]\n\n\tlog.Printf(\"request from [%s]\\n\", remoteIP)\n\tif r.rateLimiter.ExceedsLimit(remoteIP) {\n\t\tresp := &http.Response{\n\t\t\tStatusCode: 429,\n\t\t\tBody:       ioutil.NopCloser(bytes.NewBufferString(\"Too many requests\")),\n\t\t}\n\t\treturn resp, nil\n\t}\n\n\tres, err = r.transport.RoundTrip(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\tadrianConfig \"github.com\/daveross\/adrian\/config\"\n\tadrianFonts \"github.com\/daveross\/adrian\/fonts\"\n\tadrianServer \"github.com\/daveross\/adrian\/server\"\n\n\t\"github.com\/labstack\/echo\"\n)\n\nfunc main() {\n\n\tlog.Println(\"Starting Adrian 2.0\")\n\tlog.Println(\"Loading adrian.yaml\")\n\tconfig := adrianConfig.LoadConfig(\".\/adrian.yaml\")\n\tlog.Println(\"Initializing web server\")\n\te := adrianServer.Instantiate(config)\n\tlog.Println(\"Loading fonts and starting watchers\")\n\tfor _, folder := range config.Global.Directories {\n\t\tadrianFonts.FindFonts(folder, config)\n\t\tadrianFonts.InstantiateWatcher(folder, config)\n\t}\n\tlog.Println(\"Defining paths\")\n\n\te.GET(\"\/css\/\", func(c echo.Context) error {\n\t\tc.Response().Header().Set(echo.HeaderContentType, \"text\/css\")\n\t\tfontFilenames := strings.Split(c.QueryParam(\"family\"), \"|\")\n\t\tvar fontsCSS string\n\t\tfor _, fontFilename := range fontFilenames {\n\t\t\tfontData, err := adrianFonts.GetFont(fontFilename)\n\t\t\tif err != nil {\n\t\t\t\treturn adrianServer.Return404(c)\n\t\t\t}\n\t\t\tfontsCSS = fontsCSS + \"\\n\" + fontData.CSS\n\t\t}\n\t\treturn c.String(http.StatusOK, fontsCSS)\n\t})\n\n\te.GET(\"\/font\/:filename\/\", func(c echo.Context) error {\n\t\tswitch filepath.Ext(url.QueryUnescape(c.Param(\"filename\"))) {\n\t\tcase \".ttf\":\n\t\t\treturn outputFont(c, \"font\/truetype\")\n\t\tcase \".woff\":\n\t\t\treturn outputFont(c, \"font\/woff\")\n\t\tcase \".woff2\":\n\t\t\treturn outputFont(c, \"font\/woff2\")\n\t\tcase \".otf\":\n\t\t\treturn outputFont(c, \"font\/opentype\")\n\t\t}\n\n\t\treturn adrianServer.Return404(c)\n\t})\n\n\tlog.Printf(\"Listening on port %d\", config.Global.Port)\n\te.Logger.Fatal(e.Start(fmt.Sprintf(\":%d\", config.Global.Port)))\n}\n\n\/\/ Basename gets the base filename (minus the last extension)\nfunc basename(s string) string {\n\tn := strings.LastIndexByte(s, '.')\n\tif n >= 0 {\n\t\treturn s[:n]\n\t}\n\treturn s\n}\n\nfunc outputFont(c echo.Context, mimeType string) error {\n\n\tfontVariant, err := adrianFonts.GetFontVariantByUniqueID(basename(c.Param(\"filename\")))\n\tif err != nil {\n\t\treturn adrianServer.Return404(c)\n\t}\n\n\tfontFileData, ok := fontVariant.Files[adrianFonts.GetCanonicalExtension(c.Param(\"filename\"))]\n\tif !ok {\n\t\tlog.Fatal(\"Invalid font format\" + adrianFonts.GetCanonicalExtension(c.Param(\"filename\")))\n\t}\n\n\tfontBinary, err := ioutil.ReadFile(fontFileData.Path) \/\/ just pass the file name\n\tif err != nil {\n\t\tlog.Fatal(\"Can't read font file \" + fontFileData.FileName)\n\t}\n\n\tc.Response().Header().Set(\"Content-Transfer-Encoding\", \"binary\")\n\treturn c.Blob(http.StatusOK, mimeType, fontBinary)\n\n}\n<commit_msg>QueryUnescape returns two values<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\tadrianConfig \"github.com\/daveross\/adrian\/config\"\n\tadrianFonts \"github.com\/daveross\/adrian\/fonts\"\n\tadrianServer \"github.com\/daveross\/adrian\/server\"\n\n\t\"github.com\/labstack\/echo\"\n)\n\nfunc main() {\n\n\tlog.Println(\"Starting Adrian 2.0\")\n\tlog.Println(\"Loading adrian.yaml\")\n\tconfig := adrianConfig.LoadConfig(\".\/adrian.yaml\")\n\tlog.Println(\"Initializing web server\")\n\te := adrianServer.Instantiate(config)\n\tlog.Println(\"Loading fonts and starting watchers\")\n\tfor _, folder := range config.Global.Directories {\n\t\tadrianFonts.FindFonts(folder, config)\n\t\tadrianFonts.InstantiateWatcher(folder, config)\n\t}\n\tlog.Println(\"Defining paths\")\n\n\te.GET(\"\/css\/\", func(c echo.Context) error {\n\t\tc.Response().Header().Set(echo.HeaderContentType, \"text\/css\")\n\t\tfontFilenames := strings.Split(c.QueryParam(\"family\"), \"|\")\n\t\tvar fontsCSS string\n\t\tfor _, fontFilename := range fontFilenames {\n\t\t\tfontData, err := adrianFonts.GetFont(fontFilename)\n\t\t\tif err != nil {\n\t\t\t\treturn adrianServer.Return404(c)\n\t\t\t}\n\t\t\tfontsCSS = fontsCSS + \"\\n\" + fontData.CSS\n\t\t}\n\t\treturn c.String(http.StatusOK, fontsCSS)\n\t})\n\n\te.GET(\"\/font\/:filename\/\", func(c echo.Context) error {\n\t\tfilename, error := url.QueryUnescape(c.Param(\"filename\"))\n\t\tif error != nil {\n\t\t\treturn adrianServer.Return404(c)\n\t\t}\n\n\t\tswitch filepath.Ext(filename) {\n\t\tcase \".ttf\":\n\t\t\treturn outputFont(c, \"font\/truetype\")\n\t\tcase \".woff\":\n\t\t\treturn outputFont(c, \"font\/woff\")\n\t\tcase \".woff2\":\n\t\t\treturn outputFont(c, \"font\/woff2\")\n\t\tcase \".otf\":\n\t\t\treturn outputFont(c, \"font\/opentype\")\n\t\t}\n\n\t\treturn adrianServer.Return404(c)\n\t})\n\n\tlog.Printf(\"Listening on port %d\", config.Global.Port)\n\te.Logger.Fatal(e.Start(fmt.Sprintf(\":%d\", config.Global.Port)))\n}\n\n\/\/ Basename gets the base filename (minus the last extension)\nfunc basename(s string) string {\n\tn := strings.LastIndexByte(s, '.')\n\tif n >= 0 {\n\t\treturn s[:n]\n\t}\n\treturn s\n}\n\nfunc outputFont(c echo.Context, mimeType string) error {\n\n\tfontVariant, err := adrianFonts.GetFontVariantByUniqueID(basename(c.Param(\"filename\")))\n\tif err != nil {\n\t\treturn adrianServer.Return404(c)\n\t}\n\n\tfontFileData, ok := fontVariant.Files[adrianFonts.GetCanonicalExtension(c.Param(\"filename\"))]\n\tif !ok {\n\t\tlog.Fatal(\"Invalid font format\" + adrianFonts.GetCanonicalExtension(c.Param(\"filename\")))\n\t}\n\n\tfontBinary, err := ioutil.ReadFile(fontFileData.Path) \/\/ just pass the file name\n\tif err != nil {\n\t\tlog.Fatal(\"Can't read font file \" + fontFileData.FileName)\n\t}\n\n\tc.Response().Header().Set(\"Content-Transfer-Encoding\", \"binary\")\n\treturn c.Blob(http.StatusOK, mimeType, fontBinary)\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\n\/*\n * A shiny status page.\n *\n * Want it to combine my existing idle page and tiny-care-terminal.\n *\n * Things to include:\n *  - some twitter accounts\n *      - @tinycarebot, @selfcare_bot and @magicrealismbot. Maybe that boat one instead of magic realism.\n *  - weather\n *  - recent git commits\n *  - system status:\n *      - User\/hostname\n *      - Kerberos ticket status\n *      - Current time\n *      - Uptime\n *      - Battery and time left\n *      - Audio status and volume\n *      - Network\n *          - Local, docker, wireless\n *      - Disk\n *          - Mounts, free\/used\/total\/percentage w\/ color\n *      - CPU\n *          - Load average w\/ color\n *          - Percentage\n *          - Top processes?\n *      - Status of git repos\n *\n * Minimum terminal size to support:\n *  - 189x77 (half monitor with some stacks)\n *  - 104x56ish? (half the laptop screen with some stacks)\n *  - 100x50? (nice and round)\n *  - 80x40? (my default putty)\n *\n *\/\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/user\"\n\t\"time\"\n\n\tlinuxproc \"github.com\/c9s\/goprocinfo\/linux\"\n\tui \"github.com\/gizak\/termui\"\n)\n\nvar timerCounter uint64 = 0\nvar lastTimer uint64 = 0\n\n\/**\n * Make a string as wide as requested, with stuff left justified and right justified.\n *\n * width:       How wide to get.\n * left:        What text goes on the left?\n * right:       What text goes on the right?\n * fillChar:    What character to use as the filler.\n *\/\nfunc fitAStringToWidth(width int, left string, right string, fillChar string) string {\n\t\/\/ TODO: This\n\treturn left + fillChar + right\n}\n\nfunc makeP(l string) *ui.Par {\n\tp := ui.NewPar(l)\n\tp.Height = 5\n\tp.BorderLabel = l\n\n\treturn p\n}\n\nfunc execAndGetOutput(name string, args ...string) (string, error) {\n\tcmd := exec.Command(name, args...)\n\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\n\terr := cmd.Run()\n\n\treturn out.String(), err\n}\n\nfunc getUsername() string {\n\tcurUser, userErr := user.Current()\n\tuserName := \"unknown\"\n\tif userErr == nil {\n\t\tuserName = curUser.Username\n\t}\n\n\treturn userName\n}\n\nfunc getHostname() (string, string) {\n\thostName, hostErr := os.Hostname()\n\tif hostErr != nil {\n\t\thostName = \"unknown\"\n\t}\n\n\tprettyName, prettyNameErr := execAndGetOutput(\"pretty-hostname\")\n\n\tif prettyNameErr == nil {\n\t\treturn hostName, prettyName\n\t} else {\n\t\treturn hostName, hostName\n\t}\n}\n\nfunc getTime() (time.Time, *linuxproc.Uptime) {\n\tnow := time.Now().UTC()\n\tuptime, err := linuxproc.ReadUptime(\"\/proc\/uptime\")\n\n\tif err != nil {\n\t\tuptime = nil\n\t}\n\n\treturn now, uptime\n\n}\n\n\/\/ Header: User @ hostname\nfunc makeHeader() (*ui.Par, func(uint64)) {\n\t\/\/ Create widget\n\tw := ui.NewPar(\"\")\n\tw.Height = 3\n\n\t\/\/ Static information\n\tuserName := getUsername()\n\thostName, prettyName := getHostname()\n\tvar userHostHeader string\n\n\tif prettyName != hostName {\n\t\t\/\/ Host\/pretty name are different\n\t\tuserHostHeader = fmt.Sprintf(\" %v @ %v (%v) \", userName, prettyName, hostName)\n\t} else {\n\t\t\/\/ Host\/pretty name are the same (or pretty failed)\n\t\tuserHostHeader = fmt.Sprintf(\" %v @ %v \", userName, hostName)\n\t}\n\n\t\/\/ Function for dynamic information\n\tf := func(count uint64) {\n\t\tnow, uptime := getTime()\n\t\tnowStr := now.Format(time.RFC1123Z)\n\t\tuptimeStr := uptime.GetTotalDuration()\n\n\t\ttimeStr := fmt.Sprintf(\"%v (%v)\", nowStr, uptimeStr)\n\n\t\tw.BorderLabel = fitAStringToWidth(ui.TermWidth()-4, userHostHeader, timeStr, \"-\")\n\t}\n\n\t\/\/ Load dynamic info\n\tf(0)\n\n\treturn w, f\n}\n\nfunc makeNetwork() (*ui.Par, *ui.Table, func(uint64), func()) {\n\t\/\/ Create container\n\tc := ui.NewPar(\"Networking\")\n\n\t\/\/ Create widget\n\tw := ui.NewTable()\n\tw.Height = 8\n\tw.Border = false\n\n\tvar lastCount uint64 = 0\n\n\t\/\/ Function for dynamic information\n\tf := func(count uint64) {\n\t\tif (count == 0) || ((count - lastCount) >= 30000) {\n\t\t\t\/\/ First try, or after a period of time\n\t\t\tlastCount = count\n\n\t\t\t\/\/ Load network interfaces and information\n\t\t\trows := [][]string{\n\t\t\t\t[]string{\"interface0\", \"interface2\", \"interface3\"},\n\t\t\t\t[]string{\"123.456.789.123\", \"123.456.789.123\", \"123.456.789.123\"},\n\t\t\t}\n\n\t\t\tw.Rows = rows\n\n\t\t\tw.Analysis()\n\t\t\tw.SetSize()\n\t\t}\n\t}\n\n\t\/\/ Function for resizes\n\tr := func() {\n\t\tc.X = w.X\n\t\tc.Y = w.Y\n\t\tc.Width = w.Width\n\t\tc.Height = w.Height\n\t}\n\n\t\/\/ Load dynamic info\n\tf(0)\n\tr()\n\n\treturn c, w, f, r\n}\n\nfunc makeTime() (*ui.Par, func(uint64)) {\n\t\/\/ Create widget\n\tw := ui.NewPar(\"Time\")\n\tw.Height = 4\n\n\tc := 1\n\n\t\/\/ Function for dynamic information\n\tf := func(count uint64) {\n\t\tw.BorderLabel = fmt.Sprintf(\"Time (%v)\", c)\n\t\tc = c + 1\n\n\t\tnow, uptime := getTime()\n\t\tnowStr := now.Format(time.RFC1123Z)\n\t\tuptimeStr := uptime.GetTotalDuration()\n\n\t\tw.Text = fmt.Sprintf(\"Now: %v\\nUptime: %v\", nowStr, uptimeStr)\n\t}\n\n\t\/\/ Load dynamic info\n\tf(0)\n\n\treturn w, f\n}\n\nfunc makeBattAudio() (*ui.Par, func(uint64)) {\n\t\/\/ Create widget\n\tw := ui.NewPar(\"\")\n\tw.Height = 3\n\n\t\/\/ Static information\n\tcurUser, userErr := user.Current()\n\tuserName := \"unknown\"\n\tif userErr == nil {\n\t\tuserName = curUser.Username\n\t}\n\n\thostName, hostErr := os.Hostname()\n\tif hostErr != nil {\n\t\thostName = \"unknown\"\n\t}\n\n\tprettyName, prettyNameErr := execAndGetOutput(\"pretty-hostname\")\n\n\tif (prettyNameErr == nil) && (prettyName != hostName) {\n\t\t\/\/ Host\/pretty name are different\n\t\tw.BorderLabel = fmt.Sprintf(\" %v @ %v (%v) \", userName, prettyName, hostName)\n\t} else {\n\t\t\/\/ Host\/pretty name are the same (or pretty failed)\n\t\tw.BorderLabel = fmt.Sprintf(\" %v @ %v \", userName, hostName)\n\t}\n\n\t\/\/ Function for dynamic information\n\tf := func(count uint64) {\n\t\tif count == 0 {\n\t\t\t\/\/ Invoked at startup\n\t\t} else {\n\t\t\t\/\/ Invoked on timer\n\t\t}\n\t}\n\n\t\/\/ Load dynamic info\n\tf(0)\n\n\treturn w, f\n}\n\nfunc main() {\n\t\/\/ Set up the console UI\n\terr := ui.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer log.Printf(\"Final Timer: %v (%v)\", timerCounter, lastTimer)\n\tdefer ui.Close()\n\n\tui.DefaultEvtStream.Merge(\"timer\", ui.NewTimerCh(5*time.Second))\n\n\t\/\/\n\t\/\/ Create the widgets\n\t\/\/\n\n\theader, headerFunc := makeHeader()\n\tnetworkContainer, network, networkFunc, networkResize := makeNetwork()\n\ttime, timeFunc := makeTime()\n\n\tbattAudio := makeP(\"battery\/audio\")\n\tdisk := makeP(\"disk\")\n\tcpu := makeP(\"cpu\")\n\trepo := makeP(\"repos\")\n\tcommits := makeP(\"commits\")\n\ttwitter1 := makeP(\"tinycare\")\n\ttwitter2 := makeP(\"selfcare\")\n\ttwitter3 := makeP(\"a strange voyage\")\n\tweather := makeP(\"weather\")\n\n\t\/\/\n\t\/\/ Create the layout\n\t\/\/\n\n\t\/\/ Header box\n\theader.X = 0\n\theader.Y = 0\n\theader.Width = ui.TermWidth()\n\theader.Height = ui.TermHeight()\n\n\t\/\/ Allow the header box to wrap all around\n\tui.Body.Width = ui.TermWidth() - 2\n\tui.Body.X = 1\n\tui.Body.Y = 1\n\n\tui.Body.AddRows(\n\t\tui.NewRow(\n\t\t\tui.NewCol(3, 0, network),\n\t\t\tui.NewCol(3, 0, disk),\n\t\t\tui.NewCol(3, 0, cpu),\n\t\t\tui.NewCol(3, 0, battAudio)),\n\t\tui.NewRow(\n\t\t\tui.NewCol(12, 0, time)),\n\t\tui.NewRow(\n\t\t\tui.NewCol(6, 0, repo),\n\t\t\tui.NewCol(6, 0, commits)),\n\t\tui.NewRow(\n\t\t\tui.NewCol(3, 0, weather),\n\t\t\tui.NewCol(3, 0, twitter1),\n\t\t\tui.NewCol(3, 0, twitter2),\n\t\t\tui.NewCol(3, 0, twitter3)))\n\n\tui.Body.Align()\n\n\trender := func() {\n\t\tui.Body.Align()\n\t\tui.Clear()\n\t\tui.Render(header, networkContainer, ui.Body)\n\t}\n\n\t\/\/\n\t\/\/  Activate\n\t\/\/\n\n\tlog.Printf(\"Failed: %v\", timerCounter)\n\n\trender()\n\n\tui.Handle(\"\/sys\/kbd\/q\", func(ui.Event) {\n\t\t\/\/ press q to quit\n\t\tui.StopLoop()\n\t})\n\n\tui.Handle(\"\/sys\/kbd\/C-c\", func(ui.Event) {\n\t\t\/\/ ctrl-c to quit\n\t\tui.StopLoop()\n\t})\n\n\tui.Handle(\"\/timer\/5s\", func(e ui.Event) {\n\t\tt := e.Data.(ui.EvtTimer)\n\t\ti := t.Count\n\n\t\ttimerCounter++\n\t\tlastTimer = i\n\n\t\tlog.Printf(\"Timer: %v (%v)\", timerCounter, lastTimer)\n\n\t\t\/\/ Call all update funcs\n\t\theaderFunc(lastTimer)\n\t\tnetworkFunc(lastTimer)\n\t\ttimeFunc(lastTimer)\n\n\t\t\/\/ Re-render\n\t\trender()\n\t})\n\n\tui.Handle(\"\/sys\/wnd\/resize\", func(ui.Event) {\n\t\t\/\/ Update header on resize\n\t\theader.Width = ui.TermWidth()\n\t\theader.Height = ui.TermHeight()\n\n\t\t\/\/ Re-layout on resize\n\t\tui.Body.Width = ui.TermWidth() - 2\n\n\t\t\/\/ Update resize funcs\n\t\tnetworkResize()\n\n\t\t\/\/ Re-render\n\t\trender()\n\t})\n\n\tui.Loop()\n}\n<commit_msg>Fixed header stuff.<commit_after>package main\n\n\/*\n * A shiny status page.\n *\n * Want it to combine my existing idle page and tiny-care-terminal.\n *\n * Things to include:\n *  - some twitter accounts\n *      - @tinycarebot, @selfcare_bot and @magicrealismbot. Maybe that boat one instead of magic realism.\n *  - weather\n *  - recent git commits\n *  - system status:\n *      - User\/hostname\n *      - Kerberos ticket status\n *      - Current time\n *      - Uptime\n *      - Battery and time left\n *      - Audio status and volume\n *      - Network\n *          - Local, docker, wireless\n *      - Disk\n *          - Mounts, free\/used\/total\/percentage w\/ color\n *      - CPU\n *          - Load average w\/ color\n *          - Percentage\n *          - Top processes?\n *      - Status of git repos\n *\n * Minimum terminal size to support:\n *  - 189x77 (half monitor with some stacks)\n *  - 104x56ish? (half the laptop screen with some stacks)\n *  - 100x50? (nice and round)\n *  - 80x40? (my default putty)\n *\n *\/\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/user\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\/utf8\"\n\n\tlinuxproc \"github.com\/c9s\/goprocinfo\/linux\"\n\tui \"github.com\/gizak\/termui\"\n)\n\nvar timerCounter uint64 = 0\nvar lastTimer uint64 = 0\n\n\/**\n * Make a string as wide as requested, with stuff left justified and right justified.\n *\n * width:       How wide to get.\n * left:        What text goes on the left?\n * right:       What text goes on the right?\n * fillChar:    What character to use as the filler.\n *\/\nfunc fitAStringToWidth(width int, left string, right string, fillChar string) string {\n\tleftLen := utf8.RuneCountInString(left)\n\trightLen := utf8.RuneCountInString(right)\n\tfillCharLen := utf8.RuneCountInString(fillChar) \/\/ Usually 1\n\n\t\/\/ Figure out how many filler chars we need\n\tfillLen := width - (leftLen + rightLen)\n\tfillRunes := (fillLen - 1 + fillCharLen) \/ fillCharLen\n\tfillStr := strings.Repeat(fillChar, fillRunes)\n\n\treturn fmt.Sprintf(\"%s %s %s\", left, fillStr, right)\n}\n\nfunc makeP(l string) *ui.Par {\n\tp := ui.NewPar(l)\n\tp.Height = 5\n\tp.BorderLabel = l\n\n\treturn p\n}\n\nfunc execAndGetOutput(name string, args ...string) (string, error) {\n\tcmd := exec.Command(name, args...)\n\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\n\terr := cmd.Run()\n\n\treturn out.String(), err\n}\n\nfunc getUsername() string {\n\tcurUser, userErr := user.Current()\n\tuserName := \"unknown\"\n\tif userErr == nil {\n\t\tuserName = curUser.Username\n\t}\n\n\treturn userName\n}\n\nfunc getHostname() (string, string) {\n\thostName, hostErr := os.Hostname()\n\tif hostErr != nil {\n\t\thostName = \"unknown\"\n\t}\n\n\tprettyName, prettyNameErr := execAndGetOutput(\"pretty-hostname\")\n\n\tif prettyNameErr == nil {\n\t\treturn hostName, prettyName\n\t} else {\n\t\treturn hostName, hostName\n\t}\n}\n\nfunc getTime() (time.Time, *linuxproc.Uptime) {\n\tnow := time.Now().UTC()\n\tuptime, err := linuxproc.ReadUptime(\"\/proc\/uptime\")\n\n\tif err != nil {\n\t\tuptime = nil\n\t}\n\n\treturn now, uptime\n\n}\n\n\/\/ Header: User @ hostname\nfunc makeHeader() (*ui.Par, func(uint64)) {\n\t\/\/ Create widget\n\tw := ui.NewPar(\"\")\n\tw.Height = 3\n\n\t\/\/ Static information\n\tuserName := getUsername()\n\thostName, prettyName := getHostname()\n\tvar userHostHeader string\n\n\tif prettyName != hostName {\n\t\t\/\/ Host\/pretty name are different\n\t\tuserHostHeader = fmt.Sprintf(\" %v @ %v (%v)\", userName, prettyName, hostName)\n\t} else {\n\t\t\/\/ Host\/pretty name are the same (or pretty failed)\n\t\tuserHostHeader = fmt.Sprintf(\"%v @ %v\", userName, hostName)\n\t}\n\n\t\/\/ Function for dynamic information\n\tf := func(count uint64) {\n\t\tnow, uptime := getTime()\n\t\tnowStr := now.Format(time.RFC1123Z)\n\t\tuptimeStr := uptime.GetTotalDuration()\n\n\t\ttimeStr := fmt.Sprintf(\"%v (%v) \", nowStr, uptimeStr)\n\n\t\tw.BorderLabel = fitAStringToWidth(ui.TermWidth()-4, userHostHeader, timeStr, \"-\")\n\t}\n\n\t\/\/ Load dynamic info\n\tf(0)\n\n\treturn w, f\n}\n\nfunc makeNetwork() (*ui.Par, *ui.Table, func(uint64), func()) {\n\t\/\/ Create container\n\tc := ui.NewPar(\"Networking\")\n\n\t\/\/ Create widget\n\tw := ui.NewTable()\n\tw.Height = 8\n\tw.Border = false\n\n\tvar lastCount uint64 = 0\n\n\t\/\/ Function for dynamic information\n\tf := func(count uint64) {\n\t\tif (count == 0) || ((count - lastCount) >= 30000) {\n\t\t\t\/\/ First try, or after a period of time\n\t\t\tlastCount = count\n\n\t\t\t\/\/ Load network interfaces and information\n\t\t\trows := [][]string{\n\t\t\t\t[]string{\"interface0\", \"interface2\", \"interface3\"},\n\t\t\t\t[]string{\"123.456.789.123\", \"123.456.789.123\", \"123.456.789.123\"},\n\t\t\t}\n\n\t\t\tw.Rows = rows\n\n\t\t\tw.Analysis()\n\t\t\tw.SetSize()\n\t\t}\n\t}\n\n\t\/\/ Function for resizes\n\tr := func() {\n\t\tc.X = w.X\n\t\tc.Y = w.Y\n\t\tc.Width = w.Width\n\t\tc.Height = w.Height\n\t}\n\n\t\/\/ Load dynamic info\n\tf(0)\n\tr()\n\n\treturn c, w, f, r\n}\n\nfunc makeTime() (*ui.Par, func(uint64)) {\n\t\/\/ Create widget\n\tw := ui.NewPar(\"Time\")\n\tw.Height = 4\n\n\tc := 1\n\n\t\/\/ Function for dynamic information\n\tf := func(count uint64) {\n\t\tw.BorderLabel = fmt.Sprintf(\"Time (%v)\", c)\n\t\tc = c + 1\n\n\t\tnow, uptime := getTime()\n\t\tnowStr := now.Format(time.RFC1123Z)\n\t\tuptimeStr := uptime.GetTotalDuration()\n\n\t\tw.Text = fmt.Sprintf(\"Now: %v\\nUptime: %v\", nowStr, uptimeStr)\n\t}\n\n\t\/\/ Load dynamic info\n\tf(0)\n\n\treturn w, f\n}\n\nfunc makeBattAudio() (*ui.Par, func(uint64)) {\n\t\/\/ Create widget\n\tw := ui.NewPar(\"\")\n\tw.Height = 3\n\n\t\/\/ Static information\n\tcurUser, userErr := user.Current()\n\tuserName := \"unknown\"\n\tif userErr == nil {\n\t\tuserName = curUser.Username\n\t}\n\n\thostName, hostErr := os.Hostname()\n\tif hostErr != nil {\n\t\thostName = \"unknown\"\n\t}\n\n\tprettyName, prettyNameErr := execAndGetOutput(\"pretty-hostname\")\n\n\tif (prettyNameErr == nil) && (prettyName != hostName) {\n\t\t\/\/ Host\/pretty name are different\n\t\tw.BorderLabel = fmt.Sprintf(\" %v @ %v (%v) \", userName, prettyName, hostName)\n\t} else {\n\t\t\/\/ Host\/pretty name are the same (or pretty failed)\n\t\tw.BorderLabel = fmt.Sprintf(\" %v @ %v \", userName, hostName)\n\t}\n\n\t\/\/ Function for dynamic information\n\tf := func(count uint64) {\n\t\tif count == 0 {\n\t\t\t\/\/ Invoked at startup\n\t\t} else {\n\t\t\t\/\/ Invoked on timer\n\t\t}\n\t}\n\n\t\/\/ Load dynamic info\n\tf(0)\n\n\treturn w, f\n}\n\nfunc main() {\n\t\/\/ Set up the console UI\n\terr := ui.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer log.Printf(\"Final Timer: %v (%v)\", timerCounter, lastTimer)\n\tdefer ui.Close()\n\n\tui.DefaultEvtStream.Merge(\"timer\", ui.NewTimerCh(5*time.Second))\n\n\t\/\/\n\t\/\/ Create the widgets\n\t\/\/\n\n\theader, headerFunc := makeHeader()\n\t\/\/networkContainer, network, networkFunc, networkResize := makeNetwork()\n\t_, network, networkFunc, networkResize := makeNetwork()\n\ttime, timeFunc := makeTime()\n\n\tbattAudio := makeP(\"battery\/audio\")\n\tdisk := makeP(\"disk\")\n\tcpu := makeP(\"cpu\")\n\trepo := makeP(\"repos\")\n\tcommits := makeP(\"commits\")\n\ttwitter1 := makeP(\"tinycare\")\n\ttwitter2 := makeP(\"selfcare\")\n\ttwitter3 := makeP(\"a strange voyage\")\n\tweather := makeP(\"weather\")\n\n\t\/\/\n\t\/\/ Create the layout\n\t\/\/\n\n\t\/\/ Header box\n\theader.X = 0\n\theader.Y = 0\n\theader.Width = ui.TermWidth()\n\theader.Height = ui.TermHeight()\n\n\t\/\/ Allow the header box to wrap all around\n\tui.Body.Width = ui.TermWidth() - 2\n\tui.Body.X = 1\n\tui.Body.Y = 1\n\n\tui.Body.AddRows(\n\t\tui.NewRow(\n\t\t\tui.NewCol(3, 0, network),\n\t\t\tui.NewCol(3, 0, disk),\n\t\t\tui.NewCol(3, 0, cpu),\n\t\t\tui.NewCol(3, 0, battAudio)),\n\t\tui.NewRow(\n\t\t\tui.NewCol(12, 0, time)),\n\t\tui.NewRow(\n\t\t\tui.NewCol(6, 0, repo),\n\t\t\tui.NewCol(6, 0, commits)),\n\t\tui.NewRow(\n\t\t\tui.NewCol(3, 0, weather),\n\t\t\tui.NewCol(3, 0, twitter1),\n\t\t\tui.NewCol(3, 0, twitter2),\n\t\t\tui.NewCol(3, 0, twitter3)))\n\n\tui.Body.Align()\n\n\trender := func() {\n\t\tui.Body.Align()\n\t\tui.Clear()\n\t\t\/\/ui.Render(header, networkContainer, ui.Body)\n\t\tui.Render(header, ui.Body)\n\t}\n\n\t\/\/\n\t\/\/  Activate\n\t\/\/\n\n\tlog.Printf(\"Failed: %v\", timerCounter)\n\n\trender()\n\n\tui.Handle(\"\/sys\/kbd\/q\", func(ui.Event) {\n\t\t\/\/ press q to quit\n\t\tui.StopLoop()\n\t})\n\n\tui.Handle(\"\/sys\/kbd\/C-c\", func(ui.Event) {\n\t\t\/\/ ctrl-c to quit\n\t\tui.StopLoop()\n\t})\n\n\tui.Handle(\"\/timer\/5s\", func(e ui.Event) {\n\t\tt := e.Data.(ui.EvtTimer)\n\t\ti := t.Count\n\n\t\ttimerCounter++\n\t\tlastTimer = i\n\n\t\tlog.Printf(\"Timer: %v (%v)\", timerCounter, lastTimer)\n\n\t\t\/\/ Call all update funcs\n\t\theaderFunc(lastTimer)\n\t\tnetworkFunc(lastTimer)\n\t\ttimeFunc(lastTimer)\n\n\t\t\/\/ Re-render\n\t\trender()\n\t})\n\n\tui.Handle(\"\/sys\/wnd\/resize\", func(ui.Event) {\n\t\t\/\/ Update header on resize\n\t\theader.Width = ui.TermWidth()\n\t\theader.Height = ui.TermHeight()\n\n\t\t\/\/ Re-layout on resize\n\t\tui.Body.Width = ui.TermWidth() - 2\n\n\t\t\/\/ Update resize funcs\n\t\tnetworkResize()\n\n\t\t\/\/ Re-render\n\t\trender()\n\t})\n\n\tui.Loop()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n)\n\nvar streams []stream\nvar commands []*exec.Cmd\n\ntype stream struct {\n\tName   string\n\tStream string\n\tImage  string\n}\n\nfunc main() {\n\t\/\/Read in urls of webcams from configuration file\n\tdata, err := ioutil.ReadFile(\"streams.json\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := json.Unmarshal(data, &streams); err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/Startup webserver to listen to commands to execute video player\n\thttp.HandleFunc(\"\/\", serveIndex)\n\thttp.HandleFunc(\"\/all\", serveAll)\n\thttp.HandleFunc(\"\/pick\", serveOne)\n\t\/\/ showAll()\n\tlog.Fatal(http.ListenAndServe(\":2000\", nil))\n}\n\nfunc renderWebsite(w http.ResponseWriter) {\n\tconst tpl = `\n<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<meta charset=\"UTF-8\">\n\t\t<title>Zoo Cam Viewer<\/title>\n\t<\/head>\n\t<body>\n    <div><h1><a href=\"\/all\">All<\/a><\/h1><\/div>\n\t\t{{range .Streams}}<div>{{ .Name }}<\/div><div><a href=\"\/pick?name={{.Name}}\"><img src=\"{{.Image}}\"\/><\/a><\/div>{{else}}<div><strong>no streams<\/strong><\/div>{{end}}\n\t<\/body>\n<\/html>`\n\tt, err := template.New(\"webpage\").Parse(tpl)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tt.Execute(w, struct{ Streams []stream }{Streams: streams})\n}\n\nfunc serveIndex(w http.ResponseWriter, r *http.Request) {\n\t\/\/Serve up basic website with icons to choose from with \"all\" option\n\trenderWebsite(w)\n}\n\nfunc serveAll(w http.ResponseWriter, r *http.Request) {\n\t\/\/Close all existing processes, and fire up all the videos\n\tshowAll()\n\trenderWebsite(w)\n}\n\nfunc serveOne(w http.ResponseWriter, r *http.Request) {\n\t\/\/Close all existing processes, and fire up the single video passed in\n\tname := r.FormValue(\"name\")\n\tlog.Println(\"got stream name of \" + name)\n\tfor _, stream := range streams {\n\t\tif stream.Name == name {\n\t\t\tlog.Println(\"Starting stream \" + stream.Name)\n\t\t\tshowOne(stream)\n\t\t}\n\t}\n\trenderWebsite(w)\n}\n\nfunc showAll() {\n\tkillAll()\n\twidth := 1900\n\theight := 1200\n\tstreamCount := len(streams)\n\n\t\/\/Determine how many streams we have to make even boxed grids\n\tboxes := 1\n\tfor ; boxes*boxes < streamCount; boxes++ {\n\t}\n\n\tstartWidth := 0\n\tstartHeight := 0\n\twidthStep := width \/ boxes\n\theightStep := height \/ boxes\n\t\/\/We now have a box X box width screen (say 3x3), so split the screen appropriately\n\tfor index, s := range streams {\n\t\tendWidth := startWidth + (index * widthStep)\n\t\tendHeight := startHeight + (index * heightStep)\n\t\tlog.Printf(\"end width is %v and end height is %v\\n\", endWidth, endHeight)\n\t\tcmd := exec.Command(\"omxplayer\", \"--win\", fmt.Sprintf(\"%v,%v,%v,%v\", startWidth, startHeight, endWidth, endHeight), s.Stream)\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Start()\n\t\tcommands = append(commands, cmd)\n\t}\n}\n\nfunc showOne(s stream) {\n\tkillAll()\n\t\/\/Startup in fullscreen\n\tcmd := exec.Command(\"omxplayer\", s.Stream)\n\tcmd.Start()\n\tcommands = append(commands, cmd)\n}\n\nfunc killAll() {\n\tlog.Println(\"killing all existing streams\")\n\tfor _, proc := range commands {\n\t\tproc.Process.Kill()\n\t}\n}\n<commit_msg>switching back to mplayer for additional testing, leaving omxplayer commented for easy switching<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"html\/template\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n)\n\nvar streams []stream\nvar commands []*exec.Cmd\n\ntype stream struct {\n\tName   string\n\tStream string\n\tImage  string\n}\n\nfunc main() {\n\t\/\/Read in urls of webcams from configuration file\n\tdata, err := ioutil.ReadFile(\"streams.json\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := json.Unmarshal(data, &streams); err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/Startup webserver to listen to commands to execute video player\n\thttp.HandleFunc(\"\/\", serveIndex)\n\thttp.HandleFunc(\"\/all\", serveAll)\n\thttp.HandleFunc(\"\/pick\", serveOne)\n\t\/\/ showAll()\n\tlog.Fatal(http.ListenAndServe(\":2000\", nil))\n}\n\nfunc renderWebsite(w http.ResponseWriter) {\n\tconst tpl = `\n<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<meta charset=\"UTF-8\">\n\t\t<title>Zoo Cam Viewer<\/title>\n\t<\/head>\n\t<body>\n    <div><h1><a href=\"\/all\">All<\/a><\/h1><\/div>\n\t\t{{range .Streams}}<div>{{ .Name }}<\/div><div><a href=\"\/pick?name={{.Name}}\"><img src=\"{{.Image}}\"\/><\/a><\/div>{{else}}<div><strong>no streams<\/strong><\/div>{{end}}\n\t<\/body>\n<\/html>`\n\tt, err := template.New(\"webpage\").Parse(tpl)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tt.Execute(w, struct{ Streams []stream }{Streams: streams})\n}\n\nfunc serveIndex(w http.ResponseWriter, r *http.Request) {\n\t\/\/Serve up basic website with icons to choose from with \"all\" option\n\trenderWebsite(w)\n}\n\nfunc serveAll(w http.ResponseWriter, r *http.Request) {\n\t\/\/Close all existing processes, and fire up all the videos\n\tshowAll()\n\trenderWebsite(w)\n}\n\nfunc serveOne(w http.ResponseWriter, r *http.Request) {\n\t\/\/Close all existing processes, and fire up the single video passed in\n\tname := r.FormValue(\"name\")\n\tlog.Println(\"got stream name of \" + name)\n\tfor _, stream := range streams {\n\t\tif stream.Name == name {\n\t\t\tlog.Println(\"Starting stream \" + stream.Name)\n\t\t\tshowOne(stream)\n\t\t}\n\t}\n\trenderWebsite(w)\n}\n\nfunc showAll() {\n\tkillAll()\n\twidth := 1900\n\theight := 1200\n\tstreamCount := len(streams)\n\n\t\/\/Determine how many streams we have to make even boxed grids\n\tboxes := 1\n\tfor ; boxes*boxes < streamCount; boxes++ {\n\t}\n\n\tstartWidth := 0\n\tstartHeight := 0\n\twidthStep := width \/ boxes\n\theightStep := height \/ boxes\n\t\/\/We now have a box X box width screen (say 3x3), so split the screen appropriately\n\tfor index, s := range streams {\n\t\tendWidth := startWidth + (index * widthStep)\n\t\tendHeight := startHeight + (index * heightStep)\n\t\tlog.Printf(\"end width is %v and end height is %v\\n\", endWidth, endHeight)\n\t\t\/\/ cmd := exec.Command(\"omxplayer\", \"--win\", fmt.Sprintf(\"%v,%v,%v,%v\", startWidth, startHeight, endWidth, endHeight), s.Stream)\n\t\tcmd := exec.Command(\"mplayer\", s.Stream)\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Start()\n\t\tcommands = append(commands, cmd)\n\t}\n}\n\nfunc showOne(s stream) {\n\tkillAll()\n\t\/\/Startup in fullscreen\n\t\/\/ cmd := exec.Command(\"omxplayer\", s.Stream)\n\tcmd := exec.Command(\"mplayer\", s.Stream)\n\tcmd.Start()\n\tcommands = append(commands, cmd)\n}\n\nfunc killAll() {\n\tlog.Println(\"killing all existing streams\")\n\tfor _, proc := range commands {\n\t\tproc.Process.Kill()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/astaxie\/beego\"\n\t\"github.com\/mingzhehao\/beego-blog\/g\"\n\t_ \"github.com\/mingzhehao\/beego-blog\/routers\"\n)\n\nfunc main() {\n\tg.InitEnv()\n\tbeego.Run()\n}\n<commit_msg>目录名称调整<commit_after>package main\n\nimport (\n\t\"github.com\/astaxie\/beego\"\n\t\"github.com\/mingzhehao\/scloud\/g\"\n\t_ \"github.com\/mingzhehao\/scloud\/routers\"\n)\n\nfunc main() {\n\tg.InitEnv()\n\tbeego.Run()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"gopkg.in\/urfave\/cli.v1\"\n)\n\nvar version string\nvar pathToData string\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"linkcrawler\"\n\tapp.Usage = \"crawl a site for links, or download a list of sites\"\n\tapp.Version = version\n\tapp.Compiled = time.Now()\n\tapp.Action = func(c *cli.Context) error {\n\t\tif !c.GlobalBool(\"debug\") {\n\t\t\tturnOffDebugger()\n\t\t}\n\t\tpathToData = c.GlobalString(\"data\")\n\t\tos.MkdirAll(pathToData, 0755)\n\t\tfmt.Printf(\"\\nRunning CowYo at http:\/\/%s:%s\\n\\n\", GetLocalIP(), c.GlobalString(\"port\"))\n\t\tserve(c.GlobalString(\"port\"))\n\t\treturn nil\n\t}\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"data\",\n\t\t\tValue: \"data\",\n\t\t\tUsage: \"data folder to use\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"olddata\",\n\t\t\tValue: \"\",\n\t\t\tUsage: \"data folder for migrating\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"port,p\",\n\t\t\tValue: \"8050\",\n\t\t\tUsage: \"port to use\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"debug, d\",\n\t\t\tUsage: \"turn on debugging\",\n\t\t},\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:    \"migrate\",\n\t\t\tAliases: []string{\"m\"},\n\t\t\tUsage:   \"migrate from the old cowyo\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\tif !c.GlobalBool(\"debug\") {\n\t\t\t\t\tturnOffDebugger()\n\t\t\t\t}\n\t\t\t\tpathToData = c.GlobalString(\"data\")\n\t\t\t\tpathToOldData := c.GlobalString(\"olddata\")\n\t\t\t\tif len(pathToOldData) == 0 {\n\t\t\t\t\tfmt.Printf(\"You need to specify folder with -olddata\")\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tos.MkdirAll(pathToData, 0755)\n\t\t\t\tif !exists(pathToOldData) {\n\t\t\t\t\tfmt.Printf(\"Can not find '%s', does it exist?\", pathToOldData)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tmigrate(pathToOldData, pathToData)\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n\n}\n<commit_msg>Changed app info<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"gopkg.in\/urfave\/cli.v1\"\n)\n\nvar version string\nvar pathToData string\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"cowyo\"\n\tapp.Usage = \"a simple wiki\"\n\tapp.Version = version\n\tapp.Compiled = time.Now()\n\tapp.Action = func(c *cli.Context) error {\n\t\tif !c.GlobalBool(\"debug\") {\n\t\t\tturnOffDebugger()\n\t\t}\n\t\tpathToData = c.GlobalString(\"data\")\n\t\tos.MkdirAll(pathToData, 0755)\n\t\tfmt.Printf(\"\\nRunning CowYo at http:\/\/%s:%s\\n\\n\", GetLocalIP(), c.GlobalString(\"port\"))\n\t\tserve(c.GlobalString(\"port\"))\n\t\treturn nil\n\t}\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"data\",\n\t\t\tValue: \"data\",\n\t\t\tUsage: \"data folder to use\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"olddata\",\n\t\t\tValue: \"\",\n\t\t\tUsage: \"data folder for migrating\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"port,p\",\n\t\t\tValue: \"8050\",\n\t\t\tUsage: \"port to use\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"debug, d\",\n\t\t\tUsage: \"turn on debugging\",\n\t\t},\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:    \"migrate\",\n\t\t\tAliases: []string{\"m\"},\n\t\t\tUsage:   \"migrate from the old cowyo\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\tif !c.GlobalBool(\"debug\") {\n\t\t\t\t\tturnOffDebugger()\n\t\t\t\t}\n\t\t\t\tpathToData = c.GlobalString(\"data\")\n\t\t\t\tpathToOldData := c.GlobalString(\"olddata\")\n\t\t\t\tif len(pathToOldData) == 0 {\n\t\t\t\t\tfmt.Printf(\"You need to specify folder with -olddata\")\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tos.MkdirAll(pathToData, 0755)\n\t\t\t\tif !exists(pathToOldData) {\n\t\t\t\t\tfmt.Printf(\"Can not find '%s', does it exist?\", pathToOldData)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tmigrate(pathToOldData, pathToData)\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/alecthomas\/kingpin\"\n)\n\ntype Severity string\n\n\/\/ Linter message severity levels.\nconst (\n\tWarning Severity = \"warning\"\n\tError   Severity = \"error\"\n)\n\ntype Linter string\n\nfunc (l Linter) Command() string {\n\ts := lintersFlag[string(l)]\n\treturn s[0:strings.Index(s, \":\")]\n}\n\nfunc (l Linter) Pattern() string {\n\ts := lintersFlag[string(l)]\n\treturn s[strings.Index(s, \":\"):]\n}\n\nfunc (l Linter) InstallFrom() string {\n\treturn installMap[string(l)]\n}\n\nfunc (l Linter) Severity() string {\n\treturn linterSeverityFlag[string(l)]\n}\n\nfunc (l Linter) MessageOverride() string {\n\treturn linterMessageOverrideFlag[string(l)]\n}\n\nvar (\n\tpredefinedPatterns = map[string]string{\n\t\t\"PATH:LINE:COL:MESSAGE\": `(?P<path>[^:]+):(?P<line>\\d+):(?P<col>\\d+):\\s*(?P<message>.*)`,\n\t\t\"PATH:LINE:MESSAGE\":     `(?P<path>[^:]+):(?P<line>\\d+):\\s*(?P<message>.*)`,\n\t}\n\tlintersFlag = map[string]string{\n\t\t\/\/ main.go:8:10: should omit type map[string]string from declaration of var linters; it will be inferred from the right-hand side\n\t\t\"golint\": \"golint {path}:PATH:LINE:COL:MESSAGE\",\n\t\t\/\/ test\/stutter.go:19: missing argument for Printf(\"%d\"): format reads arg 1, have only 0 args\n\t\t\"vet\":         \"go vet {path}:PATH:LINE:MESSAGE\",\n\t\t\"gotype\":      \"gotype {path}:PATH:LINE:COL:MESSAGE\",\n\t\t\"errcheck\":    `errcheck {path}:(?P<path>[^:]+):(?P<line>\\d+):(?P<col>\\d+)\\t(?P<message>.*)`,\n\t\t\"varcheck\":    \"varcheck {path}:PATH:LINE:MESSAGE\",\n\t\t\"structcheck\": \"structcheck {path}:PATH:LINE:MESSAGE\",\n\t\t\"defercheck\":  \"defercheck {path}:PATH:LINE:MESSAGE\",\n\t\t\"deadcode\":    `deadcode {path}:deadcode: (?P<path>[^:]+):(?P<line>\\d+):(?P<col>\\d+):\\s*(?P<message>.*)`,\n\t\t\"gocyclo\":     `gocyclo -over {mincyclo} {path}:(?P<cyclo>\\d+)\\s+\\S+\\s(?P<function>\\S+)\\s+(?P<path>[^:]+):(?P<line>\\d+):(?P<col>\\d+)`,\n\t}\n\tlinterMessageOverrideFlag = map[string]string{\n\t\t\"errcheck\":    \"error return value not checked ({message})\",\n\t\t\"varcheck\":    \"unused global variable {message}\",\n\t\t\"structcheck\": \"unused struct field {message}\",\n\t\t\"gocyclo\":     \"cyclomatic complexity {cyclo} of function {function}() is high (> {mincyclo})\",\n\t}\n\tlinterSeverityFlag = map[string]string{\n\t\t\"errcheck\":    \"warning\",\n\t\t\"golint\":      \"warning\",\n\t\t\"varcheck\":    \"warning\",\n\t\t\"structcheck\": \"warning\",\n\t\t\"deadcode\":    \"warning\",\n\t\t\"gocyclo\":     \"warning\",\n\t}\n\tinstallMap = map[string]string{\n\t\t\"golint\":      \"github.com\/golang\/lint\/golint\",\n\t\t\"gotype\":      \"golang.org\/x\/tools\/cmd\/gotype\",\n\t\t\"errcheck\":    \"github.com\/alecthomas\/errcheck\",\n\t\t\"defercheck\":  \"github.com\/opennota\/check\/cmd\/defercheck\",\n\t\t\"varcheck\":    \"github.com\/opennota\/check\/cmd\/varcheck\",\n\t\t\"structcheck\": \"github.com\/opennota\/check\/cmd\/structcheck\",\n\t\t\"vet\":         \"golang.org\/x\/tools\/cmd\/vet\",\n\t\t\"deadcode\":    \"github.com\/remyoudompheng\/go-misc\/deadcode\",\n\t\t\"gocyclo\":     \"github.com\/alecthomas\/gocyclo\",\n\t}\n\tslowLinters = []string{\"structcheck\", \"varcheck\", \"errcheck\"}\n\n\tpathArg            = kingpin.Arg(\"path\", \"Directory to lint.\").Default(\".\").String()\n\tfastFlag           = kingpin.Flag(\"fast\", \"Only run fast linters.\").Bool()\n\tinstallFlag        = kingpin.Flag(\"install\", \"Attempt to install all known linters.\").Short('i').Bool()\n\tupdateFlag         = kingpin.Flag(\"update\", \"Pass -u to go tool when installing.\").Short('u').Bool()\n\tdisableLintersFlag = kingpin.Flag(\"disable\", \"List of linters to disable.\").PlaceHolder(\"LINTER\").Short('D').Strings()\n\tdebugFlag          = kingpin.Flag(\"debug\", \"Display messages for failed linters, etc.\").Short('d').Bool()\n\tconcurrencyFlag    = kingpin.Flag(\"concurrency\", \"Number of concurrent linters to run.\").Default(\"16\").Short('j').Int()\n\texcludeFlag        = kingpin.Flag(\"exclude\", \"Exclude messages matching this regular expression.\").PlaceHolder(\"REGEXP\").String()\n\tcycloFlag          = kingpin.Flag(\"cyclo-over\", \"Report functions with cyclomatic complexity over N (using gocyclo).\").Default(\"10\").String()\n)\n\nfunc init() {\n\tkingpin.Flag(\"linter\", \"Specify a linter.\").PlaceHolder(\"NAME:COMMAND:PATTERN\").StringMapVar(&lintersFlag)\n\tkingpin.Flag(\"message-overrides\", \"Override message from linter. {message} will be expanded to the original message.\").PlaceHolder(\"LINTER:MESSAGE\").StringMapVar(&linterMessageOverrideFlag)\n\tkingpin.Flag(\"severity\", \"Map of linter severities.\").PlaceHolder(\"LINTER:SEVERITY\").StringMapVar(&linterSeverityFlag)\n}\n\ntype Issue struct {\n\tseverity Severity\n\tpath     string\n\tline     int\n\tcol      int\n\tmessage  string\n}\n\nfunc (m *Issue) String() string {\n\tcol := \"\"\n\tif m.col != 0 {\n\t\tcol = fmt.Sprintf(\"%d\", m.col)\n\t}\n\treturn fmt.Sprintf(\"%s:%d:%s:%s: %s\", m.path, m.line, col, m.severity, m.message)\n}\n\nfunc debug(format string, args ...interface{}) {\n\tif *debugFlag {\n\t\tfmt.Fprintf(os.Stderr, \"DEBUG: \"+format+\"\\n\", args...)\n\t}\n}\n\nfunc formatLinters() string {\n\tw := bytes.NewBuffer(nil)\n\tfor name := range lintersFlag {\n\t\tlinter := Linter(name)\n\t\tfmt.Fprintf(w, \"    %s (%s)\\n        %s\\n        %s\\n\", name, linter.InstallFrom(), linter.Command(), linter.Pattern())\n\t}\n\treturn w.String()\n}\n\nfunc formatSeverity() string {\n\tw := bytes.NewBuffer(nil)\n\tfor name, severity := range linterSeverityFlag {\n\t\tfmt.Fprintf(w, \"    %s -> %s\\n\", name, severity)\n\t}\n\treturn w.String()\n}\n\nfunc exArgs() (arg0 string, arg1 string) {\n\tif runtime.GOOS == \"windows\" {\n\t\targ0 = \"cmd\"\n\t\targ1 = \"\/C\"\n\t} else {\n\t\targ0 = \"\/bin\/sh\"\n\t\targ1 = \"-c\"\n\t}\n\treturn\n}\n\ntype Vars map[string]string\n\nfunc (v Vars) Replace(s string) string {\n\tfor k, v := range v {\n\t\ts = strings.Replace(s, fmt.Sprintf(\"{%s}\", k), v, -1)\n\t}\n\treturn s\n}\n\nfunc main() {\n\tkingpin.CommandLine.Help = fmt.Sprintf(`Aggregate and normalise the output of a whole bunch of Go linters.\n\nDefault linters:\n\n%s\n\nSeverity override map (default is \"error\"):\n\n%s\n`, formatLinters(), formatSeverity())\n\tkingpin.Parse()\n\tvar filter *regexp.Regexp\n\tif *excludeFlag != \"\" {\n\t\tfilter = regexp.MustCompile(*excludeFlag)\n\t}\n\n\tif *fastFlag {\n\t\t*disableLintersFlag = append(*disableLintersFlag, slowLinters...)\n\t}\n\n\tif *installFlag {\n\t\tfor name, target := range installMap {\n\t\t\tcmd := \"go get\"\n\t\t\tif *debugFlag {\n\t\t\t\tcmd += \" -v\"\n\t\t\t}\n\t\t\tif *updateFlag {\n\t\t\t\tcmd += \" -u\"\n\t\t\t}\n\t\t\tcmd += \" \" + target\n\t\t\tfmt.Printf(\"Installing %s -> %s\\n\", name, cmd)\n\t\t\targ0, arg1 := exArgs()\n\t\t\tc := exec.Command(arg0, arg1, cmd)\n\t\t\tc.Stdout = os.Stdout\n\t\t\tc.Stderr = os.Stderr\n\t\t\terr := c.Run()\n\t\t\tif err != nil {\n\t\t\t\tkingpin.CommandLine.Errorf(os.Stderr, \"failed to install %s: %s\", name, err)\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\truntime.GOMAXPROCS(*concurrencyFlag)\n\n\tdisable := map[string]bool{}\n\tfor _, linter := range *disableLintersFlag {\n\t\tdisable[linter] = true\n\t}\n\n\tstart := time.Now()\n\tpaths := *pathArg\n\tconcurrency := make(chan bool, *concurrencyFlag)\n\tissues := make(chan *Issue, 100000)\n\twg := &sync.WaitGroup{}\n\tfor name, description := range lintersFlag {\n\t\tif _, ok := disable[name]; ok {\n\t\t\tdebug(\"linter %s disabled\", name)\n\t\t\tcontinue\n\t\t}\n\t\tparts := strings.SplitN(description, \":\", 2)\n\t\tcommand := parts[0]\n\t\tpattern := parts[1]\n\n\t\twg.Add(1)\n\t\tvars := Vars{\n\t\t\t\"mincyclo\": *cycloFlag,\n\t\t}\n\t\tgo func(name, command, pattern string) {\n\t\t\tconcurrency <- true\n\t\t\texecuteLinter(issues, name, command, pattern, paths, vars)\n\t\t\t<-concurrency\n\t\t\twg.Done()\n\t\t}(name, command, pattern)\n\t}\n\n\twg.Wait()\n\tclose(issues)\n\tfor issue := range issues {\n\t\tif filter != nil && filter.MatchString(issue.String()) {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", issue)\n\t}\n\telapsed := time.Now().Sub(start)\n\tdebug(\"total elapsed time %s\", elapsed)\n}\n\nfunc executeLinter(issues chan *Issue, name, command, pattern, paths string, vars Vars) {\n\tdebug(\"linting with %s: %s\", name, command)\n\n\tstart := time.Now()\n\tif p, ok := predefinedPatterns[pattern]; ok {\n\t\tpattern = p\n\t}\n\tregexp.Compile(pattern)\n\tre, err := regexp.Compile(pattern)\n\tkingpin.FatalIfError(err, \"invalid pattern for '\"+command+\"'\")\n\n\tvars[\"path\"] = paths\n\tcommand = vars.Replace(command)\n\tdebug(\"executing %s\", command)\n\targ0, arg1 := exArgs()\n\tcmd := exec.Command(arg0, arg1, command)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tif _, ok := err.(*exec.ExitError); !ok {\n\t\t\tdebug(\"warning: %s failed: %s\", command, err)\n\t\t\treturn\n\t\t}\n\t\tdebug(\"warning: %s returned %s\", command, err)\n\t}\n\n\tfor _, line := range bytes.Split(out, []byte(\"\\n\")) {\n\t\tgroups := re.FindAllSubmatch(line, -1)\n\t\tif groups == nil {\n\t\t\tdebug(\"%s (didn't match): '%s'\", name, line)\n\t\t\tcontinue\n\t\t}\n\t\tissue := &Issue{}\n\t\tfor i, name := range re.SubexpNames() {\n\t\t\tpart := string(groups[0][i])\n\t\t\tif name != \"\" {\n\t\t\t\tvars[name] = part\n\t\t\t}\n\t\t\tswitch name {\n\t\t\tcase \"path\":\n\t\t\t\tissue.path = part\n\n\t\t\tcase \"line\":\n\t\t\t\tn, err := strconv.ParseInt(part, 10, 32)\n\t\t\t\tkingpin.FatalIfError(err, \"line matched invalid integer\")\n\t\t\t\tissue.line = int(n)\n\n\t\t\tcase \"col\":\n\t\t\t\tn, err := strconv.ParseInt(part, 10, 32)\n\t\t\t\tkingpin.FatalIfError(err, \"col matched invalid integer\")\n\t\t\t\tissue.col = int(n)\n\n\t\t\tcase \"message\":\n\t\t\t\tissue.message = part\n\n\t\t\tcase \"\":\n\t\t\t}\n\t\t}\n\t\tif m, ok := linterMessageOverrideFlag[name]; ok {\n\t\t\tissue.message = vars.Replace(m)\n\t\t}\n\t\tif sev, ok := linterSeverityFlag[name]; ok {\n\t\t\tissue.severity = Severity(sev)\n\t\t} else {\n\t\t\tissue.severity = \"error\"\n\t\t}\n\t\tissues <- issue\n\t}\n\n\telapsed := time.Now().Sub(start)\n\tdebug(\"%s linter took %s\", name, elapsed)\n}\n<commit_msg>Support sorting of issues.<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/alecthomas\/kingpin\"\n)\n\ntype Severity string\n\n\/\/ Linter message severity levels.\nconst (\n\tWarning Severity = \"warning\"\n\tError   Severity = \"error\"\n)\n\ntype Linter string\n\nfunc (l Linter) Command() string {\n\ts := lintersFlag[string(l)]\n\treturn s[0:strings.Index(s, \":\")]\n}\n\nfunc (l Linter) Pattern() string {\n\ts := lintersFlag[string(l)]\n\treturn s[strings.Index(s, \":\"):]\n}\n\nfunc (l Linter) InstallFrom() string {\n\treturn installMap[string(l)]\n}\n\nfunc (l Linter) Severity() string {\n\treturn linterSeverityFlag[string(l)]\n}\n\nfunc (l Linter) MessageOverride() string {\n\treturn linterMessageOverrideFlag[string(l)]\n}\n\nvar (\n\tpredefinedPatterns = map[string]string{\n\t\t\"PATH:LINE:COL:MESSAGE\": `(?P<path>[^:]+):(?P<line>\\d+):(?P<col>\\d+):\\s*(?P<message>.*)`,\n\t\t\"PATH:LINE:MESSAGE\":     `(?P<path>[^:]+):(?P<line>\\d+):\\s*(?P<message>.*)`,\n\t}\n\tlintersFlag = map[string]string{\n\t\t\/\/ main.go:8:10: should omit type map[string]string from declaration of var linters; it will be inferred from the right-hand side\n\t\t\"golint\": \"golint {path}:PATH:LINE:COL:MESSAGE\",\n\t\t\/\/ test\/stutter.go:19: missing argument for Printf(\"%d\"): format reads arg 1, have only 0 args\n\t\t\"vet\":         \"go vet {path}:PATH:LINE:MESSAGE\",\n\t\t\"gotype\":      \"gotype {path}:PATH:LINE:COL:MESSAGE\",\n\t\t\"errcheck\":    `errcheck {path}:(?P<path>[^:]+):(?P<line>\\d+):(?P<col>\\d+)\\t(?P<message>.*)`,\n\t\t\"varcheck\":    \"varcheck {path}:PATH:LINE:MESSAGE\",\n\t\t\"structcheck\": \"structcheck {path}:PATH:LINE:MESSAGE\",\n\t\t\"defercheck\":  \"defercheck {path}:PATH:LINE:MESSAGE\",\n\t\t\"deadcode\":    `deadcode {path}:deadcode: (?P<path>[^:]+):(?P<line>\\d+):(?P<col>\\d+):\\s*(?P<message>.*)`,\n\t\t\"gocyclo\":     `gocyclo -over {mincyclo} {path}:(?P<cyclo>\\d+)\\s+\\S+\\s(?P<function>\\S+)\\s+(?P<path>[^:]+):(?P<line>\\d+):(?P<col>\\d+)`,\n\t}\n\tlinterMessageOverrideFlag = map[string]string{\n\t\t\"errcheck\":    \"error return value not checked ({message})\",\n\t\t\"varcheck\":    \"unused global variable {message}\",\n\t\t\"structcheck\": \"unused struct field {message}\",\n\t\t\"gocyclo\":     \"cyclomatic complexity {cyclo} of function {function}() is high (> {mincyclo})\",\n\t}\n\tlinterSeverityFlag = map[string]string{\n\t\t\"errcheck\":    \"warning\",\n\t\t\"golint\":      \"warning\",\n\t\t\"varcheck\":    \"warning\",\n\t\t\"structcheck\": \"warning\",\n\t\t\"deadcode\":    \"warning\",\n\t\t\"gocyclo\":     \"warning\",\n\t}\n\tinstallMap = map[string]string{\n\t\t\"golint\":      \"github.com\/golang\/lint\/golint\",\n\t\t\"gotype\":      \"golang.org\/x\/tools\/cmd\/gotype\",\n\t\t\"errcheck\":    \"github.com\/alecthomas\/errcheck\",\n\t\t\"defercheck\":  \"github.com\/opennota\/check\/cmd\/defercheck\",\n\t\t\"varcheck\":    \"github.com\/opennota\/check\/cmd\/varcheck\",\n\t\t\"structcheck\": \"github.com\/opennota\/check\/cmd\/structcheck\",\n\t\t\"vet\":         \"golang.org\/x\/tools\/cmd\/vet\",\n\t\t\"deadcode\":    \"github.com\/remyoudompheng\/go-misc\/deadcode\",\n\t\t\"gocyclo\":     \"github.com\/alecthomas\/gocyclo\",\n\t}\n\tslowLinters = []string{\"structcheck\", \"varcheck\", \"errcheck\"}\n\tsortKeys    = []string{\"none\", \"path\", \"line\", \"column\", \"severity\", \"message\"}\n\n\tpathArg            = kingpin.Arg(\"path\", \"Directory to lint.\").Default(\".\").String()\n\tfastFlag           = kingpin.Flag(\"fast\", \"Only run fast linters.\").Bool()\n\tinstallFlag        = kingpin.Flag(\"install\", \"Attempt to install all known linters.\").Short('i').Bool()\n\tupdateFlag         = kingpin.Flag(\"update\", \"Pass -u to go tool when installing.\").Short('u').Bool()\n\tdisableLintersFlag = kingpin.Flag(\"disable\", \"List of linters to disable.\").PlaceHolder(\"LINTER\").Short('D').Strings()\n\tdebugFlag          = kingpin.Flag(\"debug\", \"Display messages for failed linters, etc.\").Short('d').Bool()\n\tconcurrencyFlag    = kingpin.Flag(\"concurrency\", \"Number of concurrent linters to run.\").Default(\"16\").Short('j').Int()\n\texcludeFlag        = kingpin.Flag(\"exclude\", \"Exclude messages matching this regular expression.\").PlaceHolder(\"REGEXP\").String()\n\tcycloFlag          = kingpin.Flag(\"cyclo-over\", \"Report functions with cyclomatic complexity over N (using gocyclo).\").Default(\"10\").String()\n\tsortFlag           = kingpin.Flag(\"sort\", fmt.Sprintf(\"Sort output by any of %s.\", strings.Join(sortKeys, \", \"))).Default(\"none\").Enums(sortKeys...)\n)\n\nfunc init() {\n\tkingpin.Flag(\"linter\", \"Specify a linter.\").PlaceHolder(\"NAME:COMMAND:PATTERN\").StringMapVar(&lintersFlag)\n\tkingpin.Flag(\"message-overrides\", \"Override message from linter. {message} will be expanded to the original message.\").PlaceHolder(\"LINTER:MESSAGE\").StringMapVar(&linterMessageOverrideFlag)\n\tkingpin.Flag(\"severity\", \"Map of linter severities.\").PlaceHolder(\"LINTER:SEVERITY\").StringMapVar(&linterSeverityFlag)\n}\n\ntype Issue struct {\n\tseverity Severity\n\tpath     string\n\tline     int\n\tcol      int\n\tmessage  string\n}\n\nfunc (m *Issue) String() string {\n\tcol := \"\"\n\tif m.col != 0 {\n\t\tcol = fmt.Sprintf(\"%d\", m.col)\n\t}\n\treturn fmt.Sprintf(\"%s:%d:%s:%s: %s\", m.path, m.line, col, m.severity, m.message)\n}\n\nfunc debug(format string, args ...interface{}) {\n\tif *debugFlag {\n\t\tfmt.Fprintf(os.Stderr, \"DEBUG: \"+format+\"\\n\", args...)\n\t}\n}\n\nfunc formatLinters() string {\n\tw := bytes.NewBuffer(nil)\n\tfor name := range lintersFlag {\n\t\tlinter := Linter(name)\n\t\tfmt.Fprintf(w, \"    %s (%s)\\n        %s\\n        %s\\n\", name, linter.InstallFrom(), linter.Command(), linter.Pattern())\n\t}\n\treturn w.String()\n}\n\nfunc formatSeverity() string {\n\tw := bytes.NewBuffer(nil)\n\tfor name, severity := range linterSeverityFlag {\n\t\tfmt.Fprintf(w, \"    %s -> %s\\n\", name, severity)\n\t}\n\treturn w.String()\n}\n\nfunc exArgs() (arg0 string, arg1 string) {\n\tif runtime.GOOS == \"windows\" {\n\t\targ0 = \"cmd\"\n\t\targ1 = \"\/C\"\n\t} else {\n\t\targ0 = \"\/bin\/sh\"\n\t\targ1 = \"-c\"\n\t}\n\treturn\n}\n\ntype Vars map[string]string\n\nfunc (v Vars) Replace(s string) string {\n\tfor k, v := range v {\n\t\ts = strings.Replace(s, fmt.Sprintf(\"{%s}\", k), v, -1)\n\t}\n\treturn s\n}\n\nfunc main() {\n\tkingpin.CommandLine.Help = fmt.Sprintf(`Aggregate and normalise the output of a whole bunch of Go linters.\n\nDefault linters:\n\n%s\n\nSeverity override map (default is \"error\"):\n\n%s\n`, formatLinters(), formatSeverity())\n\tkingpin.Parse()\n\tvar filter *regexp.Regexp\n\tif *excludeFlag != \"\" {\n\t\tfilter = regexp.MustCompile(*excludeFlag)\n\t}\n\n\tif *fastFlag {\n\t\t*disableLintersFlag = append(*disableLintersFlag, slowLinters...)\n\t}\n\n\tif *installFlag {\n\t\tfor name, target := range installMap {\n\t\t\tcmd := \"go get\"\n\t\t\tif *debugFlag {\n\t\t\t\tcmd += \" -v\"\n\t\t\t}\n\t\t\tif *updateFlag {\n\t\t\t\tcmd += \" -u\"\n\t\t\t}\n\t\t\tcmd += \" \" + target\n\t\t\tfmt.Printf(\"Installing %s -> %s\\n\", name, cmd)\n\t\t\targ0, arg1 := exArgs()\n\t\t\tc := exec.Command(arg0, arg1, cmd)\n\t\t\tc.Stdout = os.Stdout\n\t\t\tc.Stderr = os.Stderr\n\t\t\terr := c.Run()\n\t\t\tif err != nil {\n\t\t\t\tkingpin.CommandLine.Errorf(os.Stderr, \"failed to install %s: %s\", name, err)\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\truntime.GOMAXPROCS(*concurrencyFlag)\n\n\tdisable := map[string]bool{}\n\tfor _, linter := range *disableLintersFlag {\n\t\tdisable[linter] = true\n\t}\n\n\tstart := time.Now()\n\tpaths := *pathArg\n\tconcurrency := make(chan bool, *concurrencyFlag)\n\tincomingIssues := make(chan *Issue, 100000)\n\tprocessedIssues := maybeSortIssues(incomingIssues)\n\twg := &sync.WaitGroup{}\n\tfor name, description := range lintersFlag {\n\t\tif _, ok := disable[name]; ok {\n\t\t\tdebug(\"linter %s disabled\", name)\n\t\t\tcontinue\n\t\t}\n\t\tparts := strings.SplitN(description, \":\", 2)\n\t\tcommand := parts[0]\n\t\tpattern := parts[1]\n\n\t\twg.Add(1)\n\t\tvars := Vars{\n\t\t\t\"mincyclo\": *cycloFlag,\n\t\t}\n\t\tgo func(name, command, pattern string) {\n\t\t\tconcurrency <- true\n\t\t\texecuteLinter(incomingIssues, name, command, pattern, paths, vars)\n\t\t\t<-concurrency\n\t\t\twg.Done()\n\t\t}(name, command, pattern)\n\t}\n\n\twg.Wait()\n\tclose(incomingIssues)\n\tfor issue := range processedIssues {\n\t\tif filter != nil && filter.MatchString(issue.String()) {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", issue)\n\t}\n\telapsed := time.Now().Sub(start)\n\tdebug(\"total elapsed time %s\", elapsed)\n}\n\ntype sortedIssues struct {\n\tissues []*Issue\n\torder  []string\n}\n\nfunc (s *sortedIssues) Len() int      { return len(s.issues) }\nfunc (s *sortedIssues) Swap(i, j int) { s.issues[i], s.issues[j] = s.issues[j], s.issues[i] }\nfunc (s *sortedIssues) Less(i, j int) bool {\n\tl, r := s.issues[i], s.issues[j]\n\tfor _, key := range s.order {\n\t\tswitch key {\n\t\tcase \"path\":\n\t\t\tif l.path < r.path {\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase \"line\":\n\t\t\tif l.line < r.line {\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase \"column\":\n\t\t\tif l.col < r.col {\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase \"severity\":\n\t\t\tif l.severity < r.severity {\n\t\t\t\treturn true\n\t\t\t}\n\t\tcase \"message\":\n\t\t\tif l.message < r.message {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc maybeSortIssues(issues chan *Issue) chan *Issue {\n\tif reflect.DeepEqual([]string{\"none\"}, *sortFlag) {\n\t\treturn issues\n\t}\n\tout := make(chan *Issue, 100000)\n\tsorted := &sortedIssues{\n\t\tissues: []*Issue{},\n\t\torder:  *sortFlag,\n\t}\n\tgo func() {\n\t\tfor issue := range issues {\n\t\t\tsorted.issues = append(sorted.issues, issue)\n\t\t}\n\t\tsort.Sort(sorted)\n\t\tfor _, issue := range sorted.issues {\n\t\t\tout <- issue\n\t\t}\n\t\tclose(out)\n\t}()\n\treturn out\n}\n\nfunc executeLinter(issues chan *Issue, name, command, pattern, paths string, vars Vars) {\n\tdebug(\"linting with %s: %s\", name, command)\n\n\tstart := time.Now()\n\tif p, ok := predefinedPatterns[pattern]; ok {\n\t\tpattern = p\n\t}\n\tregexp.Compile(pattern)\n\tre, err := regexp.Compile(pattern)\n\tkingpin.FatalIfError(err, \"invalid pattern for '\"+command+\"'\")\n\n\tvars[\"path\"] = paths\n\tcommand = vars.Replace(command)\n\tdebug(\"executing %s\", command)\n\targ0, arg1 := exArgs()\n\tcmd := exec.Command(arg0, arg1, command)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\tif _, ok := err.(*exec.ExitError); !ok {\n\t\t\tdebug(\"warning: %s failed: %s\", command, err)\n\t\t\treturn\n\t\t}\n\t\tdebug(\"warning: %s returned %s\", command, err)\n\t}\n\n\tfor _, line := range bytes.Split(out, []byte(\"\\n\")) {\n\t\tgroups := re.FindAllSubmatch(line, -1)\n\t\tif groups == nil {\n\t\t\tdebug(\"%s (didn't match): '%s'\", name, line)\n\t\t\tcontinue\n\t\t}\n\t\tissue := &Issue{}\n\t\tfor i, name := range re.SubexpNames() {\n\t\t\tpart := string(groups[0][i])\n\t\t\tif name != \"\" {\n\t\t\t\tvars[name] = part\n\t\t\t}\n\t\t\tswitch name {\n\t\t\tcase \"path\":\n\t\t\t\tissue.path = part\n\n\t\t\tcase \"line\":\n\t\t\t\tn, err := strconv.ParseInt(part, 10, 32)\n\t\t\t\tkingpin.FatalIfError(err, \"line matched invalid integer\")\n\t\t\t\tissue.line = int(n)\n\n\t\t\tcase \"col\":\n\t\t\t\tn, err := strconv.ParseInt(part, 10, 32)\n\t\t\t\tkingpin.FatalIfError(err, \"col matched invalid integer\")\n\t\t\t\tissue.col = int(n)\n\n\t\t\tcase \"message\":\n\t\t\t\tissue.message = part\n\n\t\t\tcase \"\":\n\t\t\t}\n\t\t}\n\t\tif m, ok := linterMessageOverrideFlag[name]; ok {\n\t\t\tissue.message = vars.Replace(m)\n\t\t}\n\t\tif sev, ok := linterSeverityFlag[name]; ok {\n\t\t\tissue.severity = Severity(sev)\n\t\t} else {\n\t\t\tissue.severity = \"error\"\n\t\t}\n\t\tissues <- issue\n\t}\n\n\telapsed := time.Now().Sub(start)\n\tdebug(\"%s linter took %s\", name, elapsed)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n    \"cahbot\/tgbotapi\"\n    \"log\"\n)\n\nfunc main() {\n    bot, err := NewCAHBot(Token)\n    if err != nil {\n        log.Panic(err)\n    }\n\n    bot.Debug = true\n\n    log.Printf(\"Authorized on account %s\", bot.Self.UserName)\n\n    u := tgbotapi.NewUpdate(0)\n    u.Timeout = 60\n\n    updates, err := bot.UpdatesChan(u)\n\n    for update := range updates {\n        go bot.HandleUpdate(&update)\n    }\n}<commit_msg>Adjust the way we handle secrets<commit_after>package main\n\nimport (\n    \"cahbot\/tgbotapi\"\n    \"log\"\n    \"cahbot\/secrets\"\n)\n\nfunc main() {\n    bot, err := NewCAHBot(secrets.Token)\n    if err != nil {\n        log.Panic(err)\n    }\n\n    bot.Debug = true\n\n    log.Printf(\"Authorized on account %s\", bot.Self.UserName)\n\n    u := tgbotapi.NewUpdate(0)\n    u.Timeout = 60\n\n    updates, err := bot.UpdatesChan(u)\n\n    for update := range updates {\n        go bot.HandleUpdate(&update)\n    }\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/golang\/groupcache\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/mitchellh\/goamz\/aws\"\n\t\"github.com\/mitchellh\/goamz\/s3\"\n\t\"log\"\n\t\"log\/syslog\"\n\t\"net\/http\"\n\t\"os\"\n\t\"vip\/fetch\"\n\t\"vip\/peer\"\n\t\"vip\/store\"\n)\n\nconst (\n\tKeyFilePath  = \"\/etc\/vip\/application.key\"\n\tCertFilePath = \"\/etc\/vip\/application.pem\"\n)\n\nvar (\n\tcache     *groupcache.Group\n\tpeers     peer.CachePool\n\tstorage   store.ImageStore\n\tauthToken string\n\n\tverbose  *bool   = flag.Bool(\"verbose\", false, \"verbose logging\")\n\thttpport *string = flag.String(\"httpport\", \"8080\", \"target port\")\n\tsecure   bool    = false\n)\n\nfunc listenHttp() {\n\tlog.Printf(\"Listening on port :%s\\n\", *httpport)\n\n\tport := fmt.Sprintf(\":%s\", *httpport)\n\n\tif secure {\n\t\tlog.Println(\"Serving via TSL\")\n\t\tif err := http.ListenAndServeTLS(port, CertFilePath, KeyFilePath, nil); err != nil {\n\t\t\tlog.Fatalf(\"Error starting server: %s\\n\", err.Error())\n\t\t}\n\t} else {\n\t\tif err := http.ListenAndServe(port, nil); err != nil {\n\t\t\tlog.Fatalf(\"Error starting server: %s\\n\", err.Error())\n\t\t}\n\t}\n}\n\nfunc getRegion() aws.Region {\n\tregion := os.Getenv(\"AWS_REGION\")\n\taws_region, ok := aws.Regions[region]\n\tif ok {\n\t\treturn aws_region\n\t} else {\n\t\tlog.Printf(\n\t\t\t\"\\\"%s\\\" is not a valid AWS_REGION parameter provided, defaulting to us-east-1\",\n\t\t\tregion)\n\t\treturn aws.USEast\n\t}\n}\n\nfunc init() {\n\tflag.Parse()\n\tvar err error\n\tvar hasKey bool\n\tvar hasCert bool\n\t_, err = os.Stat(KeyFilePath)\n\tif err != nil {\n\t\tlog.Printf(\"No key found at %s\\n\", KeyFilePath)\n\t\thasKey = false\n\t}\n\n\t_, err = os.Stat(CertFilePath)\n\tif err != nil {\n\t\tlog.Printf(\"No certificate found at %s\\n\", CertFilePath)\n\t\thasCert = false\n\t}\n\n\tsecure = hasCert && hasKey\n\n\tr := mux.NewRouter()\n\n\tauthToken = os.Getenv(\"AUTH_TOKEN\")\n\tif authToken == \"\" {\n\t\tlog.Println(\"No AUTH_TOKEN parameter provided, uploads are insecure\")\n\t}\n\n\tr.Handle(\"\/upload\/{bucket_id}\", verifyAuth(handleUpload))\n\tr.HandleFunc(\"\/{bucket_id}\/{image_id}\", handleImageRequest)\n\tr.HandleFunc(\"\/ping\", handlePing)\n\thttp.Handle(\"\/\", r)\n}\n\nfunc main() {\n\tawsAuth, err := aws.EnvAuth()\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\n\ts3conn := s3.New(awsAuth, getRegion())\n\tstorage = store.NewS3Store(s3conn)\n\n\tpeers = peer.DebugPool()\n\n\tpeers.SetContext(func(r *http.Request) groupcache.Context {\n\t\treturn fetch.RequestContext(r)\n\t})\n\n\tcache = groupcache.NewGroup(\"ImageProxyCache\", 64<<20, groupcache.GetterFunc(\n\t\tfunc(c groupcache.Context, key string, dest groupcache.Sink) error {\n\t\t\tlog.Printf(\"Cache MISS for key -> %s\", key)\n\t\t\t\/\/ Get image data from S3\n\t\t\tb, err := fetch.ImageData(storage, c)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn dest.SetBytes(b)\n\t\t}))\n\n\tif !*verbose {\n\t\tlogwriter, err := syslog.Dial(\"udp\", \"app_syslog:514\", syslog.LOG_NOTICE, \"vip\")\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\tlog.Println(\"using default logger\")\n\t\t} else {\n\t\t\tlog.SetOutput(logwriter)\n\t\t}\n\t}\n\n\tgo peers.Listen()\n\tgo listenHttp()\n\n\tlog.Println(\"Cache listening on port :\" + peers.Port())\n\ts := &http.Server{\n\t\tAddr:    \":\" + peers.Port(),\n\t\tHandler: peers,\n\t}\n\ts.ListenAndServe()\n}\n<commit_msg>ssl bug fix<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/golang\/groupcache\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/mitchellh\/goamz\/aws\"\n\t\"github.com\/mitchellh\/goamz\/s3\"\n\t\"log\"\n\t\"log\/syslog\"\n\t\"net\/http\"\n\t\"os\"\n\t\"vip\/fetch\"\n\t\"vip\/peer\"\n\t\"vip\/store\"\n)\n\nconst (\n\tKeyFilePath  = \"\/etc\/vip\/application.key\"\n\tCertFilePath = \"\/etc\/vip\/application.pem\"\n)\n\nvar (\n\tcache     *groupcache.Group\n\tpeers     peer.CachePool\n\tstorage   store.ImageStore\n\tauthToken string\n\n\tverbose  *bool   = flag.Bool(\"verbose\", false, \"verbose logging\")\n\thttpport *string = flag.String(\"httpport\", \"8080\", \"target port\")\n\tsecure   bool    = false\n)\n\nfunc listenHttp() {\n\tlog.Printf(\"Listening on port :%s\\n\", *httpport)\n\n\tport := fmt.Sprintf(\":%s\", *httpport)\n\n\tif secure {\n\t\tlog.Println(\"Serving via TSL\")\n\t\tif err := http.ListenAndServeTLS(port, CertFilePath, KeyFilePath, nil); err != nil {\n\t\t\tlog.Fatalf(\"Error starting server: %s\\n\", err.Error())\n\t\t}\n\t} else {\n\t\tif err := http.ListenAndServe(port, nil); err != nil {\n\t\t\tlog.Fatalf(\"Error starting server: %s\\n\", err.Error())\n\t\t}\n\t}\n}\n\nfunc getRegion() aws.Region {\n\tregion := os.Getenv(\"AWS_REGION\")\n\taws_region, ok := aws.Regions[region]\n\tif ok {\n\t\treturn aws_region\n\t} else {\n\t\tlog.Printf(\n\t\t\t\"\\\"%s\\\" is not a valid AWS_REGION parameter provided, defaulting to us-east-1\",\n\t\t\tregion)\n\t\treturn aws.USEast\n\t}\n}\n\nfunc init() {\n\tflag.Parse()\n\tvar err error\n\thaskey := true\n\thasCert := true\n\t_, err = os.Stat(KeyFilePath)\n\tif err != nil {\n\t\tlog.Printf(\"No key found at %s\\n\", KeyFilePath)\n\t\thasKey = false\n\t}\n\n\t_, err = os.Stat(CertFilePath)\n\tif err != nil {\n\t\tlog.Printf(\"No certificate found at %s\\n\", CertFilePath)\n\t\thasCert = false\n\t}\n\n\tsecure = hasCert && hasKey\n\n\tr := mux.NewRouter()\n\n\tauthToken = os.Getenv(\"AUTH_TOKEN\")\n\tif authToken == \"\" {\n\t\tlog.Println(\"No AUTH_TOKEN parameter provided, uploads are insecure\")\n\t}\n\n\tr.Handle(\"\/upload\/{bucket_id}\", verifyAuth(handleUpload))\n\tr.HandleFunc(\"\/{bucket_id}\/{image_id}\", handleImageRequest)\n\tr.HandleFunc(\"\/ping\", handlePing)\n\thttp.Handle(\"\/\", r)\n}\n\nfunc main() {\n\tawsAuth, err := aws.EnvAuth()\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\n\ts3conn := s3.New(awsAuth, getRegion())\n\tstorage = store.NewS3Store(s3conn)\n\n\tpeers = peer.DebugPool()\n\n\tpeers.SetContext(func(r *http.Request) groupcache.Context {\n\t\treturn fetch.RequestContext(r)\n\t})\n\n\tcache = groupcache.NewGroup(\"ImageProxyCache\", 64<<20, groupcache.GetterFunc(\n\t\tfunc(c groupcache.Context, key string, dest groupcache.Sink) error {\n\t\t\tlog.Printf(\"Cache MISS for key -> %s\", key)\n\t\t\t\/\/ Get image data from S3\n\t\t\tb, err := fetch.ImageData(storage, c)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn dest.SetBytes(b)\n\t\t}))\n\n\tif !*verbose {\n\t\tlogwriter, err := syslog.Dial(\"udp\", \"app_syslog:514\", syslog.LOG_NOTICE, \"vip\")\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\tlog.Println(\"using default logger\")\n\t\t} else {\n\t\t\tlog.SetOutput(logwriter)\n\t\t}\n\t}\n\n\tgo peers.Listen()\n\tgo listenHttp()\n\n\tlog.Println(\"Cache listening on port :\" + peers.Port())\n\ts := &http.Server{\n\t\tAddr:    \":\" + peers.Port(),\n\t\tHandler: peers,\n\t}\n\ts.ListenAndServe()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/xml\"\n\t\/\/\t\"fmt\"\n\t\"github.com\/finkf\/gocropy\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc main() {\n\t\/\/ llocs, err := gocropy.ReadLlocs(os.Args[1])\n\t\/\/ if err != nil {\n\t\/\/ \tpanic(err)\n\t\/\/ }\n\t\/\/ for i := range llocs {\n\t\/\/ \tfmt.Printf(\"%s\\n\", llocs[i])\n\t\/\/ }\n\tif len(os.Args) != 3 {\n\t\tlog.Fatal(\"Usage: %s <hocr> <dir> \", os.Args[0])\n\t}\n\thocr := gocropy.MustReadHocr(os.Args[1])\n\terr := hocr.ConvertToHocr(os.Args[2])\n\tif err == nil {\n\t\tenc := xml.NewEncoder(os.Stdout)\n\t\tenc.Indent(\" \", \" \")\n\t\tenc.Encode(hocr)\n\t} else {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>rename Hocr to HOCR<commit_after>package main\n\nimport (\n\t\"encoding\/xml\"\n\t\/\/\t\"fmt\"\n\t\"github.com\/finkf\/gocropy\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc main() {\n\tif len(os.Args) != 3 {\n\t\tlog.Fatal(\"Usage: %s <hocr> <dir> \", os.Args[0])\n\t}\n\thocr := gocropy.MustReadHOCR(os.Args[1])\n\terr := hocr.ConvertToHOCR(os.Args[2])\n\tif err == nil {\n\t\tenc := xml.NewEncoder(os.Stdout)\n\t\tenc.Indent(\" \", \" \")\n\t\tenc.Encode(hocr)\n\t} else {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2010 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\n\t\"github.com\/pointlander\/peg\/tree\"\n)\n\nconst VERSION string = \"v1.1.0\"\n\nvar (\n\tinline   = flag.Bool(\"inline\", false, \"parse rule inlining\")\n\t_switch  = flag.Bool(\"switch\", false, \"replace if-else if-else like blocks with switch blocks\")\n\tprint    = flag.Bool(\"print\", false, \"directly dump the syntax tree\")\n\tsyntax   = flag.Bool(\"syntax\", false, \"print out the syntax tree\")\n\tnoast    = flag.Bool(\"noast\", false, \"disable AST\")\n\tstrict   = flag.Bool(\"strict\", false, \"treat compiler warnings as errors\")\n\tfilename = flag.String(\"output\", \"\", \"specify name of output file\")\n\tshowVersion = flag.Bool(\"version\", false, \"print the version and exit\")\n)\n\nfunc main() {\n\truntime.GOMAXPROCS(2)\n\tflag.Parse()\n\n\tif *showVersion {\n\t\tfmt.Println(\"version:\",VERSION)\n\t\treturn\n\t}\n\t\n\tif flag.NArg() != 1 {\n\t\tflag.Usage()\n\t\tlog.Fatalf(\"FILE: the peg file to compile\")\n\t}\n\tfile := flag.Arg(0)\n\n\tbuffer, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tp := &Peg{Tree: tree.New(*inline, *_switch, *noast), Buffer: string(buffer)}\n\tp.Init(Pretty(true), Size(1<<15))\n\tif err := p.Parse(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tp.Execute()\n\n\tif *print {\n\t\tp.Print()\n\t}\n\tif *syntax {\n\t\tp.PrintSyntaxTree()\n\t}\n\n\tif *filename == \"\" {\n\t\t*filename = file + \".go\"\n\t}\n\tout, err := os.OpenFile(*filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\tfmt.Printf(\"%v: %v\\n\", *filename, err)\n\t\treturn\n\t}\n\tdefer out.Close()\n\n\tp.Strict = *strict\n\tif err = p.Compile(*filename, os.Args, out); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>improved version flag<commit_after>\/\/ Copyright 2010 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\n\t\"github.com\/pointlander\/peg\/tree\"\n)\n\nvar (\n\tinline   = flag.Bool(\"inline\", false, \"parse rule inlining\")\n\t_switch  = flag.Bool(\"switch\", false, \"replace if-else if-else like blocks with switch blocks\")\n\tprint    = flag.Bool(\"print\", false, \"directly dump the syntax tree\")\n\tsyntax   = flag.Bool(\"syntax\", false, \"print out the syntax tree\")\n\tnoast    = flag.Bool(\"noast\", false, \"disable AST\")\n\tstrict   = flag.Bool(\"strict\", false, \"treat compiler warnings as errors\")\n\tfilename = flag.String(\"output\", \"\", \"specify name of output file\")\n\tshowVersion = flag.Bool(\"version\", false, \"print the version and exit\")\n)\n\n\/\/ whether running with -version should\n\/\/ show the last time `build.go buildinfo` was ran \nconst Show_BUILDTIME = false\n\nfunc main() {\n\truntime.GOMAXPROCS(2)\n\tflag.Parse()\n\n\tif *showVersion {\n\t\tif IS_TAGGED {\n\t\t\tfmt.Println(\"version:\",VERSION)\n\t\t} else {\n\t\t\tfmt.Printf(\"version: %s-%s\\n\",VERSION,COMMIT)\n\t\t}\n\t\tif Show_BUILDTIME {fmt.Println(\"time:\",BUILDTIME)}\n\t\treturn\n\t}\n\t\n\tif flag.NArg() != 1 {\n\t\tflag.Usage()\n\t\tlog.Fatalf(\"FILE: the peg file to compile\")\n\t}\n\tfile := flag.Arg(0)\n\n\tbuffer, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tp := &Peg{Tree: tree.New(*inline, *_switch, *noast), Buffer: string(buffer)}\n\tp.Init(Pretty(true), Size(1<<15))\n\tif err := p.Parse(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tp.Execute()\n\n\tif *print {\n\t\tp.Print()\n\t}\n\tif *syntax {\n\t\tp.PrintSyntaxTree()\n\t}\n\n\tif *filename == \"\" {\n\t\t*filename = file + \".go\"\n\t}\n\tout, err := os.OpenFile(*filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)\n\tif err != nil {\n\t\tfmt.Printf(\"%v: %v\\n\", *filename, err)\n\t\treturn\n\t}\n\tdefer out.Close()\n\n\tp.Strict = *strict\n\tif err = p.Compile(*filename, os.Args, out); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n)\n\nvar (\n\tpkgs map[string]*build.Package\n\tids  map[string]string\n\n\tignored = map[string]bool{\n\t\t\"C\": true,\n\t}\n\tignoredPrefixes []string\n\tonlyPrefixes    []string\n\n\tignoreStdlib   = flag.Bool(\"nostdlib\", false, \"ignore packages in the Go standard library\")\n\tignoreVendor   = flag.Bool(\"novendor\", false, \"ignore packages in the vendor directory\")\n\tstopOnError    = flag.Bool(\"stoponerror\", true, \"stop on package import errors\")\n\twithGoroot     = flag.Bool(\"withgoroot\", false, \"show dependencies of packages in the Go standard library\")\n\tignorePrefixes = flag.String(\"ignoreprefixes\", \"\", \"a comma-separated list of prefixes to ignore\")\n\tignorePackages = flag.String(\"ignorepackages\", \"\", \"a comma-separated list of packages to ignore\")\n\tonlyPrefix     = flag.String(\"onlyprefixes\", \"\", \"a comma-separated list of prefixes to include\")\n\ttagList        = flag.String(\"tags\", \"\", \"a comma-separated list of build tags to consider satisfied during the build\")\n\thorizontal     = flag.Bool(\"horizontal\", false, \"lay out the dependency graph horizontally instead of vertically\")\n\twithTests      = flag.Bool(\"withtests\", false, \"include test packages\")\n\tmaxLevel       = flag.Int(\"maxlevel\", 256, \"max level of go dependency graph\")\n\n\tbuildTags    []string\n\tbuildContext = build.Default\n)\n\nfunc init() {\n\tflag.BoolVar(ignoreStdlib, \"s\", false, \"(alias for -nostdlib) ignore packages in the Go standard library\")\n\tflag.StringVar(ignorePrefixes, \"p\", \"\", \"(alias for -ignoreprefixes) a comma-separated list of prefixes to ignore\")\n\tflag.StringVar(ignorePackages, \"i\", \"\", \"(alias for -ignorepackages) a comma-separated list of packages to ignore\")\n\tflag.StringVar(onlyPrefix, \"o\", \"\", \"(alias for -onlyprefixes) a comma-separated list of prefixes to include\")\n\tflag.BoolVar(withTests, \"t\", false, \"(alias for -withtests) include test packages\")\n\tflag.IntVar(maxLevel, \"l\", 256, \"(alias for -maxlevel) maximum level of the go dependency graph\")\n\tflag.BoolVar(withGoroot, \"d\", false, \"(alias for -withgoroot) show dependencies of packages in the Go standard library\")\n}\n\nfunc main() {\n\tpkgs = make(map[string]*build.Package)\n\tids = make(map[string]string)\n\tflag.Parse()\n\n\targs := flag.Args()\n\n\tif len(args) < 1 {\n\t\tlog.Fatal(\"need one package name to process\")\n\t}\n\n\tif *ignorePrefixes != \"\" {\n\t\tignoredPrefixes = strings.Split(*ignorePrefixes, \",\")\n\t}\n\tif *onlyPrefix != \"\" {\n\t\tonlyPrefixes = strings.Split(*onlyPrefix, \",\")\n\t}\n\tif *ignorePackages != \"\" {\n\t\tfor _, p := range strings.Split(*ignorePackages, \",\") {\n\t\t\tignored[p] = true\n\t\t}\n\t}\n\tif *tagList != \"\" {\n\t\tbuildTags = strings.Split(*tagList, \",\")\n\t}\n\tbuildContext.BuildTags = buildTags\n\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to get cwd: %s\", err)\n\t}\n\tfor _, a := range args {\n\t\tif err := processPackage(cwd, a, 0, \"\", *stopOnError); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tfmt.Println(\"digraph godep {\")\n\tif *horizontal {\n\t\tfmt.Println(`rankdir=\"LR\"`)\n\t}\n\tfmt.Print(`splines=ortho\nnodesep=0.4\nranksep=0.8\nnode [shape=\"box\",style=\"rounded,filled\"]\nedge [arrowsize=\"0.5\"]\n`)\n\n\t\/\/ sort packages\n\tpkgKeys := []string{}\n\tfor k := range pkgs {\n\t\tpkgKeys = append(pkgKeys, k)\n\t}\n\tsort.Strings(pkgKeys)\n\n\tfor _, pkgName := range pkgKeys {\n\t\tpkg := pkgs[pkgName]\n\t\tpkgId := getId(pkgName)\n\n\t\tif isIgnored(pkg) {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar color string\n\t\tswitch {\n\t\tcase pkg.Goroot:\n\t\t\tcolor = \"palegreen\"\n\t\tcase len(pkg.CgoFiles) > 0:\n\t\t\tcolor = \"darkgoldenrod1\"\n\t\tcase isVendored(pkg.ImportPath):\n\t\t\tcolor = \"palegoldenrod\"\n\t\tdefault:\n\t\t\tcolor = \"paleturquoise\"\n\t\t}\n\n\t\tfmt.Printf(\"%s [label=\\\"%s\\\" color=\\\"%s\\\" URL=\\\"%s\\\" target=\\\"_blank\\\"];\\n\", pkgId, pkgName, color, pkgURL(pkgName))\n\n\t\t\/\/ Don't render imports from packages in Goroot\n\t\tif pkg.Goroot && !*withGoroot {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, imp := range getImports(pkg) {\n\t\t\timpPkg := pkgs[imp]\n\t\t\tif impPkg == nil || isIgnored(impPkg) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\timpId := getId(imp)\n\t\t\tfmt.Printf(\"%s -> %s;\\n\", pkgId, impId)\n\t\t}\n\t}\n\tfmt.Println(\"}\")\n}\n\nfunc pkgURL(pkgName string) string {\n\treturn \"https:\/\/godoc.org\/\" + pkgName\n}\n\nfunc processPackage(root string, pkgName string, level int, importedBy string, stopOnError bool) error {\n\tif level++; level > *maxLevel {\n\t\treturn nil\n\t}\n\tif ignored[pkgName] {\n\t\treturn nil\n\t}\n\n\tpkg, err := buildContext.Import(pkgName, root, 0)\n\tif err != nil {\n\t\tif stopOnError {\n\t\t\treturn fmt.Errorf(\"failed to import %s (imported at level %d by %s): %s\", pkgName, level, importedBy, err)\n\t\t} else {\n\t\t\t\/\/ TODO: mark the package so that it is rendered with a different color\n\t\t}\n\t}\n\n\tif isIgnored(pkg) {\n\t\treturn nil\n\t}\n\n\tpkgs[normalizeVendor(pkg.ImportPath)] = pkg\n\n\t\/\/ Don't worry about dependencies for stdlib packages\n\tif pkg.Goroot && !*withGoroot {\n\t\treturn nil\n\t}\n\n\tfor _, imp := range getImports(pkg) {\n\t\tif _, ok := pkgs[imp]; !ok {\n\t\t\tif err := processPackage(pkg.Dir, imp, level, pkgName, stopOnError); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc getImports(pkg *build.Package) []string {\n\tallImports := pkg.Imports\n\tif *withTests {\n\t\tallImports = append(allImports, pkg.TestImports...)\n\t\tallImports = append(allImports, pkg.XTestImports...)\n\t}\n\tvar imports []string\n\tfound := make(map[string]struct{})\n\tfor _, imp := range allImports {\n\t\tif imp == normalizeVendor(pkg.ImportPath) {\n\t\t\t\/\/ Don't draw a self-reference when foo_test depends on foo.\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := found[imp]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tfound[imp] = struct{}{}\n\t\timports = append(imports, imp)\n\t}\n\treturn imports\n}\n\nfunc deriveNodeID(packageName string) string {\n\t\/\/TODO: improve implementation?\n\tid := \"\\\"\" + packageName + \"\\\"\"\n\treturn id\n}\n\nfunc getId(name string) string {\n\tid, ok := ids[name]\n\tif !ok {\n\t\tid = deriveNodeID(name)\n\t\tids[name] = id\n\t}\n\treturn id\n}\n\nfunc hasPrefixes(s string, prefixes []string) bool {\n\tfor _, p := range prefixes {\n\t\tif strings.HasPrefix(s, p) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc isIgnored(pkg *build.Package) bool {\n\tif len(onlyPrefixes) > 0 && !hasPrefixes(normalizeVendor(pkg.ImportPath), onlyPrefixes) {\n\t\treturn true\n\t}\n\n\tif *ignoreVendor && isVendored(pkg.ImportPath) {\n\t\treturn true\n\t}\n\treturn ignored[normalizeVendor(pkg.ImportPath)] || (pkg.Goroot && *ignoreStdlib) || hasPrefixes(normalizeVendor(pkg.ImportPath), ignoredPrefixes)\n}\n\nfunc debug(args ...interface{}) {\n\tfmt.Fprintln(os.Stderr, args...)\n}\n\nfunc debugf(s string, args ...interface{}) {\n\tfmt.Fprintf(os.Stderr, s, args...)\n}\n\nfunc isVendored(path string) bool {\n\treturn strings.Contains(path, \"\/vendor\/\")\n}\n\nfunc normalizeVendor(path string) string {\n\tpieces := strings.Split(path, \"vendor\/\")\n\treturn pieces[len(pieces)-1]\n}\n<commit_msg>Implement 'continue on error' behaviour<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n)\n\nvar (\n\tpkgs        map[string]*build.Package\n\terroredPkgs map[string]bool\n\tids         map[string]string\n\n\tignored = map[string]bool{\n\t\t\"C\": true,\n\t}\n\tignoredPrefixes []string\n\tonlyPrefixes    []string\n\n\tignoreStdlib   = flag.Bool(\"nostdlib\", false, \"ignore packages in the Go standard library\")\n\tignoreVendor   = flag.Bool(\"novendor\", false, \"ignore packages in the vendor directory\")\n\tstopOnError    = flag.Bool(\"stoponerror\", true, \"stop on package import errors\")\n\twithGoroot     = flag.Bool(\"withgoroot\", false, \"show dependencies of packages in the Go standard library\")\n\tignorePrefixes = flag.String(\"ignoreprefixes\", \"\", \"a comma-separated list of prefixes to ignore\")\n\tignorePackages = flag.String(\"ignorepackages\", \"\", \"a comma-separated list of packages to ignore\")\n\tonlyPrefix     = flag.String(\"onlyprefixes\", \"\", \"a comma-separated list of prefixes to include\")\n\ttagList        = flag.String(\"tags\", \"\", \"a comma-separated list of build tags to consider satisfied during the build\")\n\thorizontal     = flag.Bool(\"horizontal\", false, \"lay out the dependency graph horizontally instead of vertically\")\n\twithTests      = flag.Bool(\"withtests\", false, \"include test packages\")\n\tmaxLevel       = flag.Int(\"maxlevel\", 256, \"max level of go dependency graph\")\n\n\tbuildTags    []string\n\tbuildContext = build.Default\n)\n\nfunc init() {\n\tflag.BoolVar(ignoreStdlib, \"s\", false, \"(alias for -nostdlib) ignore packages in the Go standard library\")\n\tflag.StringVar(ignorePrefixes, \"p\", \"\", \"(alias for -ignoreprefixes) a comma-separated list of prefixes to ignore\")\n\tflag.StringVar(ignorePackages, \"i\", \"\", \"(alias for -ignorepackages) a comma-separated list of packages to ignore\")\n\tflag.StringVar(onlyPrefix, \"o\", \"\", \"(alias for -onlyprefixes) a comma-separated list of prefixes to include\")\n\tflag.BoolVar(withTests, \"t\", false, \"(alias for -withtests) include test packages\")\n\tflag.IntVar(maxLevel, \"l\", 256, \"(alias for -maxlevel) maximum level of the go dependency graph\")\n\tflag.BoolVar(withGoroot, \"d\", false, \"(alias for -withgoroot) show dependencies of packages in the Go standard library\")\n}\n\nfunc main() {\n\tpkgs = make(map[string]*build.Package)\n\terroredPkgs = make(map[string]bool)\n\tids = make(map[string]string)\n\tflag.Parse()\n\n\targs := flag.Args()\n\n\tif len(args) < 1 {\n\t\tlog.Fatal(\"need one package name to process\")\n\t}\n\n\tif *ignorePrefixes != \"\" {\n\t\tignoredPrefixes = strings.Split(*ignorePrefixes, \",\")\n\t}\n\tif *onlyPrefix != \"\" {\n\t\tonlyPrefixes = strings.Split(*onlyPrefix, \",\")\n\t}\n\tif *ignorePackages != \"\" {\n\t\tfor _, p := range strings.Split(*ignorePackages, \",\") {\n\t\t\tignored[p] = true\n\t\t}\n\t}\n\tif *tagList != \"\" {\n\t\tbuildTags = strings.Split(*tagList, \",\")\n\t}\n\tbuildContext.BuildTags = buildTags\n\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to get cwd: %s\", err)\n\t}\n\tfor _, a := range args {\n\t\tif err := processPackage(cwd, a, 0, \"\", *stopOnError); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tfmt.Println(\"digraph godep {\")\n\tif *horizontal {\n\t\tfmt.Println(`rankdir=\"LR\"`)\n\t}\n\tfmt.Print(`splines=ortho\nnodesep=0.4\nranksep=0.8\nnode [shape=\"box\",style=\"rounded,filled\"]\nedge [arrowsize=\"0.5\"]\n`)\n\n\t\/\/ sort packages\n\tpkgKeys := []string{}\n\tfor k := range pkgs {\n\t\tpkgKeys = append(pkgKeys, k)\n\t}\n\tsort.Strings(pkgKeys)\n\n\tfor _, pkgName := range pkgKeys {\n\t\tpkg := pkgs[pkgName]\n\t\tpkgId := getId(pkgName)\n\n\t\tif isIgnored(pkg) {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar color string\n\t\tswitch {\n\t\tcase pkg.Goroot:\n\t\t\tcolor = \"palegreen\"\n\t\tcase len(pkg.CgoFiles) > 0:\n\t\t\tcolor = \"darkgoldenrod1\"\n\t\tcase isVendored(pkg.ImportPath):\n\t\t\tcolor = \"palegoldenrod\"\n\t\tcase hasBuildErrors(pkg):\n\t\t\tcolor = \"red\"\n\t\tdefault:\n\t\t\tcolor = \"paleturquoise\"\n\t\t}\n\n\t\tfmt.Printf(\"%s [label=\\\"%s\\\" color=\\\"%s\\\" URL=\\\"%s\\\" target=\\\"_blank\\\"];\\n\", pkgId, pkgName, color, pkgDocsURL(pkgName))\n\n\t\t\/\/ Don't render imports from packages in Goroot\n\t\tif pkg.Goroot && !*withGoroot {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, imp := range getImports(pkg) {\n\t\t\timpPkg := pkgs[imp]\n\t\t\tif impPkg == nil || isIgnored(impPkg) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\timpId := getId(imp)\n\t\t\tfmt.Printf(\"%s -> %s;\\n\", pkgId, impId)\n\t\t}\n\t}\n\tfmt.Println(\"}\")\n}\n\nfunc pkgDocsURL(pkgName string) string {\n\treturn \"https:\/\/godoc.org\/\" + pkgName\n}\n\nfunc processPackage(root string, pkgName string, level int, importedBy string, stopOnError bool) error {\n\tif level++; level > *maxLevel {\n\t\treturn nil\n\t}\n\tif ignored[pkgName] {\n\t\treturn nil\n\t}\n\n\tpkg, buildErr := buildContext.Import(pkgName, root, 0)\n\tif buildErr != nil {\n\t\tif stopOnError {\n\t\t\treturn fmt.Errorf(\"failed to import %s (imported at level %d by %s):\\n%s\", pkgName, level, importedBy, buildErr)\n\t\t}\n\t}\n\n\tif isIgnored(pkg) {\n\t\treturn nil\n\t}\n\n\timportPath := normalizeVendor(pkgName)\n\tif buildErr != nil {\n\t\terroredPkgs[importPath] = true\n\t}\n\n\tpkgs[importPath] = pkg\n\n\t\/\/ Don't worry about dependencies for stdlib packages\n\tif pkg.Goroot && !*withGoroot {\n\t\treturn nil\n\t}\n\n\tfor _, imp := range getImports(pkg) {\n\t\tif _, ok := pkgs[imp]; !ok {\n\t\t\tif err := processPackage(pkg.Dir, imp, level, pkgName, stopOnError); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc getImports(pkg *build.Package) []string {\n\tallImports := pkg.Imports\n\tif *withTests {\n\t\tallImports = append(allImports, pkg.TestImports...)\n\t\tallImports = append(allImports, pkg.XTestImports...)\n\t}\n\tvar imports []string\n\tfound := make(map[string]struct{})\n\tfor _, imp := range allImports {\n\t\tif imp == normalizeVendor(pkg.ImportPath) {\n\t\t\t\/\/ Don't draw a self-reference when foo_test depends on foo.\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := found[imp]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tfound[imp] = struct{}{}\n\t\timports = append(imports, imp)\n\t}\n\treturn imports\n}\n\nfunc deriveNodeID(packageName string) string {\n\t\/\/TODO: improve implementation?\n\tid := \"\\\"\" + packageName + \"\\\"\"\n\treturn id\n}\n\nfunc getId(name string) string {\n\tid, ok := ids[name]\n\tif !ok {\n\t\tid = deriveNodeID(name)\n\t\tids[name] = id\n\t}\n\treturn id\n}\n\nfunc hasPrefixes(s string, prefixes []string) bool {\n\tfor _, p := range prefixes {\n\t\tif strings.HasPrefix(s, p) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc isIgnored(pkg *build.Package) bool {\n\tif len(onlyPrefixes) > 0 && !hasPrefixes(normalizeVendor(pkg.ImportPath), onlyPrefixes) {\n\t\treturn true\n\t}\n\n\tif *ignoreVendor && isVendored(pkg.ImportPath) {\n\t\treturn true\n\t}\n\treturn ignored[normalizeVendor(pkg.ImportPath)] || (pkg.Goroot && *ignoreStdlib) || hasPrefixes(normalizeVendor(pkg.ImportPath), ignoredPrefixes)\n}\n\nfunc hasBuildErrors(pkg *build.Package) bool {\n\tif len(erroredPkgs) == 0 {\n\t\treturn false\n\t}\n\n\tv, ok := erroredPkgs[normalizeVendor(pkg.ImportPath)]\n\tif !ok {\n\t\treturn false\n\t}\n\treturn v\n}\n\nfunc debug(args ...interface{}) {\n\tfmt.Fprintln(os.Stderr, args...)\n}\n\nfunc debugf(s string, args ...interface{}) {\n\tfmt.Fprintf(os.Stderr, s, args...)\n}\n\nfunc isVendored(path string) bool {\n\treturn strings.Contains(path, \"\/vendor\/\")\n}\n\nfunc normalizeVendor(path string) string {\n\tpieces := strings.Split(path, \"vendor\/\")\n\treturn pieces[len(pieces)-1]\n}\n<|endoftext|>"}
{"text":"<commit_before>package printer\n\nimport (\n\t\"fmt\"\n\t\"lupo\/event\"\n\t\"lupo\/out\"\n)\n\nconst maxPayloadCharsToPrint = 32\nconst maxPayloadBytesToPrint = 16\n\nfunc Accept() {\n\tfor {\n\t\tselect {\n\t\tcase o := <-event.Events:\n\t\t\tswitch ev := o.(type) {\n\t\t\tcase *event.Event:\n\t\t\t\tprintEvent(ev)\n\t\t\tcase *event.HttpEvent:\n\t\t\t\tprintHttpEvent(ev)\n\t\t\t}\t\t\t\n\t\t}\n\t}\n}\n\n\/\/ Print the event.\n\/\/\n\/\/ Generic event examples:\n\/\/ 15:04:05.000  [1    Opened from localhost:23123\n\/\/ 15:04:05.000 ->1    some text data\n\/\/ 15:04:05.000 <-10   32 bytes [81 4f d3 c2 ...]\n\/\/ 15:04:05.000  ]10   Closed\nfunc printEvent(ev *event.Event) {\n\tout.Stamp(ev.Stamp)\n\tprintKind(ev.Kind)\n\tout.Cid(ev.Cid)\n\tprintDesc(ev)\n}\n\n\/\/ HTTP event examples:\n\/\/ 15:04:05.000 ->1    GET \/ HTTP\/1.0\n\/\/ 15:04:05.000 <-1    HTTP\/1.0 OK\nfunc printHttpEvent(ev *event.HttpEvent) {\n\tout.Stamp(ev.Stamp)\n\tprintKind(ev.Kind)\n\tout.Cid(ev.Cid)\n\tprintHttpDesc(ev)\n}\n\nfunc printKind(k event.EventKind) {\n\tswitch k {\n\tcase event.Connect:\n\t\tout.Out.WriteString(\" [\")\n\tcase event.Disconnect:\n\t\tout.Out.WriteString(\" ]\")\n\tcase event.Send:\n\t\tout.Out.WriteString(\"->\")\n\tcase event.Receive:\n\t\tout.Out.WriteString(\"<-\")\n\t}\n}\n\nfunc printDesc(e *event.Event) {\n\tswitch e.Kind {\n\tcase event.Connect:\n\t\tout.Out.WriteString(\"Opened from \")\n\t\tout.Out.Write(e.Payload)\n\t\tout.Out.WriteString(\"\\n\")\n\tcase event.Disconnect:\n\t\tout.Out.WriteString(\"Closed\\n\")\n\tcase event.Send:\n\t\tfallthrough\n\tcase event.Receive:\n\t\tprintPayload(e.Payload)\n\t}\n}\n\nfunc printHttpDesc(e *event.HttpEvent) {\n\t\/\/ Can only be Send or Receive\n\tout.Out.Write(e.Start)\n\n\t\/\/ TODO make configurable if headers are printed\n\n\tprintPayload(e.Body)\n}\n\nfunc printPayload(d []byte) {\n\ttextual := d[:min(len(d), maxPayloadCharsToPrint)]\n\tif isPrintable(textual) {\n\t\tout.WriteWithoutNewlines(textual)\n\t\tout.Out.WriteString(\"\\n\")\n\t} else {\n\t\tout.Out.WriteString(fmt.Sprintf(\"%d bytes [\", len(d)))\n\t\tprintBinary(d[:min(len(d), maxPayloadBytesToPrint)])\n\t\tout.Out.WriteString(fmt.Sprintf(\"]\\n\"))\n\t}\n}\n\nconst hextable = \"0123456789abcdef\"\n\nfunc printBinary(d []byte) {\n\tfor i, b := range d {\n\t\tif i > 0 && i%8 == 0 {\n\t\t\tout.Out.WriteString(\" \")\n\t\t}\n\t\t\/\/ TODO ugly\n\t\tout.Out.WriteString(string(hextable[b>>4]))\n\t\tout.Out.WriteString(string(hextable[b&0x0f]))\n\t}\n}\n\nfunc isPrintable(d []byte) bool {\n\tfor _, b := range d {\n\t\tif !(b == 0x0d || b == 0x0a || (b >= 0x20 && b <= 0x7e)) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc min(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\n\/*\n\/\/ Special Writer which writes head + nicely formatted binary \/ textual chunks + tail\ntype transferLog struct {\n\thead string\n\ttail string\n}\n\n\n\/\/ Write nicely formatted binary \/ textual chunk\nfunc (l *transferLog) Write(p []byte) (n int, err error) {\n\tutil.Print(l.head)\n\n\tbinChunk := false\n\tchunkStart := 0\n\tprintableCount := 0\n\n\tfor i, b := range p {\n\t\tif isPrintable(b) {\n\t\t\tprintableCount++\n\n\t\t\t\/\/ char chunks have a minimum length\n\t\t\tif binChunk && printableCount >= 5 {\n\t\t\t\t\/\/ Write the previous binary chunk\n\t\t\t\tchunkEnd := i - printableCount + 1\n\t\t\t\twriteHexChunk(p[chunkStart:chunkEnd])\n\n\t\t\t\tbinChunk = false\n\t\t\t\tchunkStart = chunkEnd\n\t\t\t}\n\t\t} else {\n\t\t\tprintableCount = 0\n\n\t\t\tif !binChunk {\n\t\t\t\t\/\/ Write the previous char chunk\n\t\t\t\tos.Stdout.Write(p[chunkStart:i])\n\n\t\t\t\tbinChunk = true\n\t\t\t\tchunkStart = i\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Final chunk\n\tif binChunk {\n\t\twriteHexChunk(p[chunkStart:])\n\t} else {\n\t\tos.Stdout.Write(p[chunkStart:])\n\t}\n\n\tos.Stdout.WriteString(l.tail)\n\treturn len(p), nil\n}\n\n\nfunc writeHexChunk(p []byte) {\n\tdumper := hex.Dumper(os.Stdout)\n\tdumper.Write(p)\n\tdumper.Close()\n}\n\nfunc isPrintable(b byte) bool {\n\treturn b == 0x0d || b == 0x0a || (b >= 0x20 && b <= 0x7e)\n}\n*\/\n<commit_msg>Nicer output<commit_after>package printer\n\nimport (\n\t\"fmt\"\n\t\"lupo\/event\"\n\t\"lupo\/out\"\n)\n\nconst (\n\tmaxPayloadCharsToPrint = 80\n\tmaxPayloadBytesToPrint = 40\n)\n\nfunc Accept() {\n\tfor {\n\t\tselect {\n\t\tcase o := <-event.Events:\n\t\t\tswitch ev := o.(type) {\n\t\t\tcase *event.Event:\n\t\t\t\tprintEvent(ev)\n\t\t\tcase *event.HttpEvent:\n\t\t\t\tprintHttpEvent(ev)\n\t\t\t}\t\t\t\n\t\t}\n\t}\n}\n\n\/\/ Print the event.\n\/\/\n\/\/ Generic event examples:\n\/\/ 15:04:05.000  [1    Opened from localhost:23123\n\/\/ 15:04:05.000 ->1    some text data\n\/\/ 15:04:05.000 <-10   32 bytes [81 4f d3 c2 ...]\n\/\/ 15:04:05.000  ]10   Closed\nfunc printEvent(ev *event.Event) {\n\tout.Stamp(ev.Stamp)\n\tprintKind(ev.Kind)\n\tout.Cid(ev.Cid)\n\tprintDesc(ev)\n}\n\n\/\/ HTTP event examples:\n\/\/ 15:04:05.000 ->1    GET \/ HTTP\/1.0\n\/\/ 15:04:05.000 <-1    HTTP\/1.0 OK\nfunc printHttpEvent(ev *event.HttpEvent) {\n\tout.Stamp(ev.Stamp)\n\tprintKind(ev.Kind)\n\tout.Cid(ev.Cid)\n\tprintHttpDesc(ev)\n}\n\nfunc printKind(k event.EventKind) {\n\tswitch k {\n\tcase event.Connect:\n\t\tout.Out.WriteString(\" [\")\n\tcase event.Disconnect:\n\t\tout.Out.WriteString(\" ]\")\n\tcase event.Send:\n\t\tout.Out.WriteString(\"->\")\n\tcase event.Receive:\n\t\tout.Out.WriteString(\"<-\")\n\t}\n}\n\nfunc printDesc(e *event.Event) {\n\tswitch e.Kind {\n\tcase event.Connect:\n\t\tout.Out.WriteString(\"New connection from \")\n\t\tout.Out.Write(e.Payload)\n\t\tout.Out.WriteString(\"\\n\")\n\tcase event.Disconnect:\n\t\tout.Out.WriteString(\"Closed\\n\")\n\tcase event.Send:\n\t\tfallthrough\n\tcase event.Receive:\n\t\tprintPayload(e.Payload)\n\t}\n}\n\nfunc printHttpDesc(e *event.HttpEvent) {\n\t\/\/ Can only be Send or Receive\n\tout.Out.Write(e.Start)\n\n\t\/\/ TODO make configurable if headers are printed\n\n\tprintPayload(e.Body)\n}\n\nfunc printPayload(d []byte) {\n\ttextual := d[:min(len(d), maxPayloadCharsToPrint)]\n\tif isPrintable(textual) {\n\t\tout.WriteWithoutNewlines(textual)\n\t\tif len(d) > maxPayloadCharsToPrint {\n\t\t\tout.Out.WriteString(\" (...)\")\n\t\t}\n\t\tout.Out.WriteString(\"\\n\")\n\t} else {\n\t\tout.Out.WriteString(fmt.Sprintf(\"%d bytes [\", len(d)))\n\t\tprintBinary(d[:min(len(d), maxPayloadBytesToPrint)])\t\t\n\t\tif len(d) > maxPayloadBytesToPrint {\n\t\t\tout.Out.WriteString(\" (...)\")\n\t\t}\n\t\tout.Out.WriteString(fmt.Sprintf(\"]\\n\"))\n\t}\n}\n\nconst hextable = \"0123456789abcdef\"\n\nfunc printBinary(d []byte) {\n\tfor i, b := range d {\n\t\tif i > 0 && i%8 == 0 {\n\t\t\tout.Out.WriteString(\" \")\n\t\t}\n\t\t\/\/ TODO ugly\n\t\tout.Out.WriteString(string(hextable[b>>4]))\n\t\tout.Out.WriteString(string(hextable[b&0x0f]))\n\t}\n}\n\nfunc isPrintable(d []byte) bool {\n\tfor _, b := range d {\n\t\tif !(b == 0x0d || b == 0x0a || (b >= 0x20 && b <= 0x7e)) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc min(a, b int) int {\n\tif a > b {\n\t\treturn b\n\t} else {\n\t\treturn a\n\t}\n}\n\n\/*\n\/\/ Special Writer which writes head + nicely formatted binary \/ textual chunks + tail\ntype transferLog struct {\n\thead string\n\ttail string\n}\n\n\n\/\/ Write nicely formatted binary \/ textual chunk\nfunc (l *transferLog) Write(p []byte) (n int, err error) {\n\tutil.Print(l.head)\n\n\tbinChunk := false\n\tchunkStart := 0\n\tprintableCount := 0\n\n\tfor i, b := range p {\n\t\tif isPrintable(b) {\n\t\t\tprintableCount++\n\n\t\t\t\/\/ char chunks have a minimum length\n\t\t\tif binChunk && printableCount >= 5 {\n\t\t\t\t\/\/ Write the previous binary chunk\n\t\t\t\tchunkEnd := i - printableCount + 1\n\t\t\t\twriteHexChunk(p[chunkStart:chunkEnd])\n\n\t\t\t\tbinChunk = false\n\t\t\t\tchunkStart = chunkEnd\n\t\t\t}\n\t\t} else {\n\t\t\tprintableCount = 0\n\n\t\t\tif !binChunk {\n\t\t\t\t\/\/ Write the previous char chunk\n\t\t\t\tos.Stdout.Write(p[chunkStart:i])\n\n\t\t\t\tbinChunk = true\n\t\t\t\tchunkStart = i\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Final chunk\n\tif binChunk {\n\t\twriteHexChunk(p[chunkStart:])\n\t} else {\n\t\tos.Stdout.Write(p[chunkStart:])\n\t}\n\n\tos.Stdout.WriteString(l.tail)\n\treturn len(p), nil\n}\n\n\nfunc writeHexChunk(p []byte) {\n\tdumper := hex.Dumper(os.Stdout)\n\tdumper.Write(p)\n\tdumper.Close()\n}\n\nfunc isPrintable(b byte) bool {\n\treturn b == 0x0d || b == 0x0a || (b >= 0x20 && b <= 0x7e)\n}\n*\/\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/docker\/libcluster\/discovery\"\n\t\"github.com\/docker\/libcluster\/swarm\"\n)\n\ntype logHandler struct {\n}\n\nfunc (h *logHandler) Handle(e *swarm.Event) error {\n\tlog.Printf(\"event -> type: %q time: %q image: %q container: %q\", e.Type, e.Time.Format(time.RubyDate), e.Container.Image, e.Container.Id)\n\treturn nil\n}\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"swarm\"\n\tapp.Usage = \"docker clustering\"\n\tapp.Version = \"0.0.1\"\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName:   \"debug\",\n\t\t\tUsage:  \"debug mode\",\n\t\t\tEnvVar: \"DEBUG\",\n\t\t},\n\t}\n\n\tapp.Before = func(c *cli.Context) error {\n\t\tlog.SetOutput(os.Stderr)\n\t\tif c.Bool(\"debug\") {\n\t\t\tlog.SetLevel(log.DebugLevel)\n\t\t}\n\t\treturn nil\n\t}\n\n\tclusterFlags := []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:   \"token\",\n\t\t\tValue:  \"\",\n\t\t\tUsage:  \"cluster token\",\n\t\t\tEnvVar: \"SWARM_TOKEN\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"addr\",\n\t\t\tValue:  \"127.0.0.1:4243\",\n\t\t\tUsage:  \"ip to advertise\",\n\t\t\tEnvVar: \"SWARM_ADDR\",\n\t\t},\n\t}\n\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:      \"create\",\n\t\t\tShortName: \"c\",\n\t\t\tUsage:     \"create a cluster\",\n\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\ttoken, err := discovery.CreateCluster()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\tfmt.Println(token)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"manage\",\n\t\t\tShortName: \"m\",\n\t\t\tUsage:     \"manage a docker cluster\",\n\t\t\tFlags:     clusterFlags,\n\t\t\tAction:    manage,\n\t\t},\n\t\t{\n\t\t\tName:      \"join\",\n\t\t\tShortName: \"j\",\n\t\t\tUsage:     \"join a docker cluster\",\n\t\t\tFlags:     clusterFlags,\n\t\t\tAction:    join,\n\t\t},\n\t}\n\n\tif err := app.Run(os.Args); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>add 'list'<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/docker\/libcluster\/discovery\"\n\t\"github.com\/docker\/libcluster\/swarm\"\n)\n\ntype logHandler struct {\n}\n\nfunc (h *logHandler) Handle(e *swarm.Event) error {\n\tlog.Printf(\"event -> type: %q time: %q image: %q container: %q\", e.Type, e.Time.Format(time.RubyDate), e.Container.Image, e.Container.Id)\n\treturn nil\n}\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"swarm\"\n\tapp.Usage = \"docker clustering\"\n\tapp.Version = \"0.0.1\"\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName:   \"debug\",\n\t\t\tUsage:  \"debug mode\",\n\t\t\tEnvVar: \"DEBUG\",\n\t\t},\n\t}\n\n\t\/\/ logs\n\tapp.Before = func(c *cli.Context) error {\n\t\tlog.SetOutput(os.Stderr)\n\t\tif c.Bool(\"debug\") {\n\t\t\tlog.SetLevel(log.DebugLevel)\n\t\t}\n\t\treturn nil\n\t}\n\n\t\/\/ flags\n\tflToken := cli.StringFlag{\n\t\tName:   \"token\",\n\t\tValue:  \"\",\n\t\tUsage:  \"cluster token\",\n\t\tEnvVar: \"SWARM_TOKEN\",\n\t}\n\tflAddr := cli.StringFlag{\n\t\tName:   \"addr\",\n\t\tValue:  \"127.0.0.1:4243\",\n\t\tUsage:  \"ip to advertise\",\n\t\tEnvVar: \"SWARM_ADDR\",\n\t}\n\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:      \"create\",\n\t\t\tShortName: \"c\",\n\t\t\tUsage:     \"create a cluster\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\ttoken, err := discovery.CreateCluster()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\tfmt.Println(token)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"list\",\n\t\t\tShortName: \"l\",\n\t\t\tUsage:     \"list nodes in a cluster\",\n\t\t\tFlags:     []cli.Flag{flToken},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tnodes, err := discovery.FetchSlaves(c.String(\"token\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\tfor _, node := range nodes {\n\t\t\t\t\tfmt.Println(node)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:      \"manage\",\n\t\t\tShortName: \"m\",\n\t\t\tUsage:     \"manage a docker cluster\",\n\t\t\tFlags:     []cli.Flag{flToken, flAddr},\n\t\t\tAction:    manage,\n\t\t},\n\t\t{\n\t\t\tName:      \"join\",\n\t\t\tShortName: \"j\",\n\t\t\tUsage:     \"join a docker cluster\",\n\t\t\tFlags:     []cli.Flag{flToken, flAddr},\n\t\t\tAction:    join,\n\t\t},\n\t}\n\n\tif err := app.Run(os.Args); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime\/debug\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/stvp\/rollbar\"\n)\n\n\/\/ Version is the version of the v4 cli.\n\/\/ This is set by a build flag in the `Rakefile`.\n\/\/ If it is set to `dev` it will not autoupdate.\nvar Version = \"dev\"\n\n\/\/ Channel is the git branch the code was compiled on.\n\/\/ This is set by a build flag in the `Rakefile` based on the git branch.\nvar Channel = \"?\"\n\nvar cli = &Cli{}\n\n\/\/ BuiltinPlugins are the core plugins that will be autoinstalled\nvar BuiltinPlugins = []string{\n\t\"heroku-apps\",\n\t\"heroku-cli-addons\",\n\t\"heroku-fork\",\n\t\"heroku-git\",\n\t\"heroku-local\",\n\t\"heroku-orgs\",\n\t\"heroku-pipelines\",\n\t\"heroku-run\",\n\t\"heroku-spaces\",\n\t\"heroku-status\",\n}\n\nfunc init() {\n\tcli.Topics = TopicSet{\n\t\tauthTopic,\n\t\tcommandsTopic,\n\t\tdebugTopic,\n\t\tloginTopic,\n\t\tlogoutTopic,\n\t\tpluginsTopic,\n\t\ttwoFactorTopic,\n\t\ttwoFactorTopicAlias,\n\t\tupdateTopic,\n\t\tversionTopic,\n\t\twhichTopic,\n\t}\n\tcli.Commands = CommandSet{\n\t\tauthLoginCmd,\n\t\tauthLogoutCmd,\n\t\tauthTokenCmd,\n\t\tcommandsListCmd,\n\t\tdebugErrlogCmd,\n\t\tloginCmd,\n\t\tlogoutCmd,\n\t\tpluginsInstallCmd,\n\t\tpluginsLinkCmd,\n\t\tpluginsListCmd,\n\t\tpluginsUninstallCmd,\n\t\ttwoFactorCmd,\n\t\ttwoFactorCmdAlias,\n\t\ttwoFactorDisableCmd,\n\t\ttwoFactorDisableCmdAlias,\n\t\ttwoFactorGenerateCmd,\n\t\ttwoFactorGenerateCmdAlias,\n\t\tupdateCmd,\n\t\tversionCmd,\n\t\twhichCmd,\n\t\twhoamiCmd,\n\t}\n\trollbar.Platform = \"client\"\n\trollbar.Token = \"b40226d5e8a743cf963ca320f7be17bd\"\n\trollbar.Environment = Channel\n\trollbar.ErrorWriter = nil\n}\n\nfunc main() {\n\tdefer handlePanic()\n\tvar wg sync.WaitGroup\n\truntime.GOMAXPROCS(1) \/\/ more procs causes runtime: failed to create new OS thread on Ubuntu\n\tShowDebugInfo()\n\tif !(len(os.Args) >= 2 && os.Args[1] == \"update\") {\n\t\t\/\/ skip blocking update if the command is to update\n\t\t\/\/ otherwise it will update twice\n\t\tUpdate(Channel, \"block\")\n\t}\n\tSetupNode()\n\twg.Add(1)\n\tgo RecordAnalytics(&wg)\n\terr := cli.Run(os.Args)\n\tSetupBuiltinPlugins()\n\tTriggerBackgroundUpdate()\n\tif err == ErrHelp {\n\t\t\/\/ Command wasn't found so load the plugins and try again\n\t\tcli.LoadPlugins(GetPlugins())\n\t\terr = cli.Run(os.Args)\n\t}\n\tif err == ErrHelp {\n\t\thelp()\n\t}\n\tif err != nil {\n\t\tPrintError(err, false)\n\t\tos.Exit(2)\n\t}\n\twg.Wait()\n}\n\nfunc handlePanic() {\n\tif rec := recover(); rec != nil {\n\t\terr, ok := rec.(error)\n\t\tif !ok {\n\t\t\terr = errors.New(rec.(string))\n\t\t}\n\t\tErrln(\"ERROR:\", err)\n\t\tif Channel == \"?\" {\n\t\t\tdebug.PrintStack()\n\t\t} else {\n\t\t\trollbar.Error(rollbar.ERR, err, rollbarFields()...)\n\t\t\trollbar.Wait()\n\t\t}\n\t\tExit(1)\n\t}\n}\n\nfunc rollbarFields() []*rollbar.Field {\n\tvar cmd string\n\tif len(os.Args) > 1 {\n\t\tcmd = os.Args[1]\n\t}\n\treturn []*rollbar.Field{\n\t\t{\"Version\", Version},\n\t\t{\"GOOS\", runtime.GOOS},\n\t\t{\"GOARCH\", runtime.GOARCH},\n\t\t{\"command\", cmd},\n\t}\n}\n\n\/\/ ShowDebugInfo prints debugging information if HEROKU_DEBUG=1\nfunc ShowDebugInfo() {\n\tif !isDebugging() {\n\t\treturn\n\t}\n\tinfo := []string{version(), binPath}\n\tif len(os.Args) > 1 {\n\t\tinfo = append(info, fmt.Sprintf(\"cmd: %s\", os.Args[1]))\n\t}\n\tproxy := getProxy()\n\tif proxy != nil {\n\t\tinfo = append(info, fmt.Sprintf(\"proxy: %s\", proxy))\n\t}\n\tDebugln(strings.Join(info, \" \"))\n}\n\nfunc getProxy() *url.URL {\n\treq, err := http.NewRequest(\"GET\", \"https:\/\/api.heroku.com\", nil)\n\tPrintError(err, false)\n\tproxy, err := http.ProxyFromEnvironment(req)\n\tPrintError(err, false)\n\treturn proxy\n}\n<commit_msg>attempt to background update cli when panicing<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime\/debug\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/stvp\/rollbar\"\n)\n\n\/\/ Version is the version of the v4 cli.\n\/\/ This is set by a build flag in the `Rakefile`.\n\/\/ If it is set to `dev` it will not autoupdate.\nvar Version = \"dev\"\n\n\/\/ Channel is the git branch the code was compiled on.\n\/\/ This is set by a build flag in the `Rakefile` based on the git branch.\nvar Channel = \"?\"\n\nvar cli = &Cli{}\n\n\/\/ BuiltinPlugins are the core plugins that will be autoinstalled\nvar BuiltinPlugins = []string{\n\t\"heroku-apps\",\n\t\"heroku-cli-addons\",\n\t\"heroku-fork\",\n\t\"heroku-git\",\n\t\"heroku-local\",\n\t\"heroku-orgs\",\n\t\"heroku-pipelines\",\n\t\"heroku-run\",\n\t\"heroku-spaces\",\n\t\"heroku-status\",\n}\n\nfunc init() {\n\tcli.Topics = TopicSet{\n\t\tauthTopic,\n\t\tcommandsTopic,\n\t\tdebugTopic,\n\t\tloginTopic,\n\t\tlogoutTopic,\n\t\tpluginsTopic,\n\t\ttwoFactorTopic,\n\t\ttwoFactorTopicAlias,\n\t\tupdateTopic,\n\t\tversionTopic,\n\t\twhichTopic,\n\t}\n\tcli.Commands = CommandSet{\n\t\tauthLoginCmd,\n\t\tauthLogoutCmd,\n\t\tauthTokenCmd,\n\t\tcommandsListCmd,\n\t\tdebugErrlogCmd,\n\t\tloginCmd,\n\t\tlogoutCmd,\n\t\tpluginsInstallCmd,\n\t\tpluginsLinkCmd,\n\t\tpluginsListCmd,\n\t\tpluginsUninstallCmd,\n\t\ttwoFactorCmd,\n\t\ttwoFactorCmdAlias,\n\t\ttwoFactorDisableCmd,\n\t\ttwoFactorDisableCmdAlias,\n\t\ttwoFactorGenerateCmd,\n\t\ttwoFactorGenerateCmdAlias,\n\t\tupdateCmd,\n\t\tversionCmd,\n\t\twhichCmd,\n\t\twhoamiCmd,\n\t}\n\trollbar.Platform = \"client\"\n\trollbar.Token = \"b40226d5e8a743cf963ca320f7be17bd\"\n\trollbar.Environment = Channel\n\trollbar.ErrorWriter = nil\n}\n\nfunc main() {\n\tdefer handlePanic()\n\tvar wg sync.WaitGroup\n\truntime.GOMAXPROCS(1) \/\/ more procs causes runtime: failed to create new OS thread on Ubuntu\n\tShowDebugInfo()\n\tif !(len(os.Args) >= 2 && os.Args[1] == \"update\") {\n\t\t\/\/ skip blocking update if the command is to update\n\t\t\/\/ otherwise it will update twice\n\t\tUpdate(Channel, \"block\")\n\t}\n\tSetupNode()\n\twg.Add(1)\n\tgo RecordAnalytics(&wg)\n\terr := cli.Run(os.Args)\n\tSetupBuiltinPlugins()\n\tTriggerBackgroundUpdate()\n\tif err == ErrHelp {\n\t\t\/\/ Command wasn't found so load the plugins and try again\n\t\tcli.LoadPlugins(GetPlugins())\n\t\terr = cli.Run(os.Args)\n\t}\n\tif err == ErrHelp {\n\t\thelp()\n\t}\n\tif err != nil {\n\t\tPrintError(err, false)\n\t\tos.Exit(2)\n\t}\n\twg.Wait()\n}\n\nfunc handlePanic() {\n\tif rec := recover(); rec != nil {\n\t\terr, ok := rec.(error)\n\t\tif !ok {\n\t\t\terr = errors.New(rec.(string))\n\t\t}\n\t\tErrln(\"ERROR:\", err)\n\t\tif Channel == \"?\" {\n\t\t\tdebug.PrintStack()\n\t\t} else {\n\t\t\trollbar.Error(rollbar.ERR, err, rollbarFields()...)\n\t\t\trollbar.Wait()\n\t\t}\n\t\tTriggerBackgroundUpdate()\n\t\tExit(1)\n\t}\n}\n\nfunc rollbarFields() []*rollbar.Field {\n\tvar cmd string\n\tif len(os.Args) > 1 {\n\t\tcmd = os.Args[1]\n\t}\n\treturn []*rollbar.Field{\n\t\t{\"Version\", Version},\n\t\t{\"GOOS\", runtime.GOOS},\n\t\t{\"GOARCH\", runtime.GOARCH},\n\t\t{\"command\", cmd},\n\t}\n}\n\n\/\/ ShowDebugInfo prints debugging information if HEROKU_DEBUG=1\nfunc ShowDebugInfo() {\n\tif !isDebugging() {\n\t\treturn\n\t}\n\tinfo := []string{version(), binPath}\n\tif len(os.Args) > 1 {\n\t\tinfo = append(info, fmt.Sprintf(\"cmd: %s\", os.Args[1]))\n\t}\n\tproxy := getProxy()\n\tif proxy != nil {\n\t\tinfo = append(info, fmt.Sprintf(\"proxy: %s\", proxy))\n\t}\n\tDebugln(strings.Join(info, \" \"))\n}\n\nfunc getProxy() *url.URL {\n\treq, err := http.NewRequest(\"GET\", \"https:\/\/api.heroku.com\", nil)\n\tPrintError(err, false)\n\tproxy, err := http.ProxyFromEnvironment(req)\n\tPrintError(err, false)\n\treturn proxy\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package main defines a command line interface for the sqlboiler package\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n\t\"github.com\/volatiletech\/sqlboiler\/boilingcore\"\n\t\"github.com\/volatiletech\/sqlboiler\/drivers\"\n\t\"github.com\/volatiletech\/sqlboiler\/importers\"\n)\n\n\/\/go:generate go-bindata -pkg templatebin -o templatebin\/bindata.go templates templates\/singleton templates_test templates_test\/singleton\n\nconst sqlBoilerVersion = \"3.0.0-rc1\"\n\nvar (\n\tflagConfigFile string\n\tcmdState       *boilingcore.State\n\tcmdConfig      *boilingcore.Config\n)\n\nfunc initConfig() {\n\tif len(flagConfigFile) != 0 {\n\t\tviper.SetConfigFile(flagConfigFile)\n\t\tif err := viper.ReadInConfig(); err != nil {\n\t\t\tfmt.Println(\"Can't read config:\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\treturn\n\t}\n\n\tvar err error\n\tviper.SetConfigName(\"sqlboiler\")\n\n\tconfigHome := os.Getenv(\"XDG_CONFIG_HOME\")\n\thomePath := os.Getenv(\"HOME\")\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\twd = \".\/\"\n\t}\n\n\tconfigPaths := []string{wd}\n\tif len(configHome) > 0 {\n\t\tconfigPaths = append(configPaths, filepath.Join(configHome, \"sqlboiler\"))\n\t} else {\n\t\tconfigPaths = append(configPaths, filepath.Join(homePath, \".config\/sqlboiler\"))\n\t}\n\n\tfor _, p := range configPaths {\n\t\tviper.AddConfigPath(p)\n\t}\n\n\t\/\/ Ignore errors here, fallback to other validation methods.\n\t\/\/ Users can use environment variables if a config is not found.\n\t_ = viper.ReadInConfig()\n}\n\nfunc main() {\n\t\/\/ Too much happens between here and cobra's argument handling, for\n\t\/\/ something so simple just do it immediately.\n\tfor _, arg := range os.Args {\n\t\tif arg == \"--version\" {\n\t\t\tfmt.Println(\"SQLBoiler v\" + sqlBoilerVersion)\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ Set up the cobra root command\n\tvar rootCmd = &cobra.Command{\n\t\tUse:   \"sqlboiler [flags] <driver>\",\n\t\tShort: \"SQL Boiler generates an ORM tailored to your database schema.\",\n\t\tLong: \"SQL Boiler generates a Go ORM from template files, tailored to your database schema.\\n\" +\n\t\t\t`Complete documentation is available at http:\/\/github.com\/volatiletech\/sqlboiler`,\n\t\tExample:       `sqlboiler psql`,\n\t\tPreRunE:       preRun,\n\t\tRunE:          run,\n\t\tPostRunE:      postRun,\n\t\tSilenceErrors: true,\n\t\tSilenceUsage:  true,\n\t}\n\n\tcobra.OnInitialize(initConfig)\n\n\t\/\/ Set up the cobra root command flags\n\trootCmd.PersistentFlags().StringVarP(&flagConfigFile, \"config\", \"c\", \"\", \"Filename of config file to override default lookup\")\n\trootCmd.PersistentFlags().StringP(\"output\", \"o\", \"models\", \"The name of the folder to output to\")\n\trootCmd.PersistentFlags().StringP(\"pkgname\", \"p\", \"models\", \"The name you wish to assign to your generated package\")\n\trootCmd.PersistentFlags().StringSliceP(\"templates\", \"\", nil, \"A templates directory, overrides the bindata'd template folders in sqlboiler\")\n\trootCmd.PersistentFlags().StringSliceP(\"tag\", \"t\", nil, \"Struct tags to be included on your models in addition to json, yaml, toml\")\n\trootCmd.PersistentFlags().StringSliceP(\"replace\", \"\", nil, \"Replace templates by directory: relpath\/to_file.tpl:relpath\/to_replacement.tpl\")\n\trootCmd.PersistentFlags().BoolP(\"debug\", \"d\", false, \"Debug mode prints stack traces on error\")\n\trootCmd.PersistentFlags().BoolP(\"no-context\", \"\", false, \"Disable context.Context usage in the generated code\")\n\trootCmd.PersistentFlags().BoolP(\"no-tests\", \"\", false, \"Disable generated go test files\")\n\trootCmd.PersistentFlags().BoolP(\"no-hooks\", \"\", false, \"Disable hooks feature for your models\")\n\trootCmd.PersistentFlags().BoolP(\"no-rows-affected\", \"\", false, \"Disable rows affected in the generated API\")\n\trootCmd.PersistentFlags().BoolP(\"no-auto-timestamps\", \"\", false, \"Disable automatic timestamps for created_at\/updated_at\")\n\trootCmd.PersistentFlags().BoolP(\"add-global-variants\", \"\", false, \"Enable generation for global variants\")\n\trootCmd.PersistentFlags().BoolP(\"add-panic-variants\", \"\", false, \"Enable generation for panic variants\")\n\trootCmd.PersistentFlags().BoolP(\"version\", \"\", false, \"Print the version\")\n\trootCmd.PersistentFlags().BoolP(\"wipe\", \"\", false, \"Delete the output folder (rm -rf) before generation to ensure sanity\")\n\trootCmd.PersistentFlags().StringP(\"struct-tag-casing\", \"\", \"snake\", \"Decides the casing for go structure tag names. camel or snake (default snake)\")\n\n\t\/\/ hide flags not recommended for use\n\trootCmd.PersistentFlags().MarkHidden(\"replace\")\n\n\tviper.BindPFlags(rootCmd.PersistentFlags())\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\tviper.AutomaticEnv()\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tif e, ok := err.(commandFailure); ok {\n\t\t\tfmt.Printf(\"Error: %v\\n\\n\", string(e))\n\t\t\trootCmd.Help()\n\t\t} else if !viper.GetBool(\"debug\") {\n\t\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\t} else {\n\t\t\tfmt.Printf(\"Error: %+v\\n\", err)\n\t\t}\n\n\t\tos.Exit(1)\n\t}\n}\n\ntype commandFailure string\n\nfunc (c commandFailure) Error() string {\n\treturn string(c)\n}\n\nfunc preRun(cmd *cobra.Command, args []string) error {\n\tvar err error\n\n\tif len(args) == 0 {\n\t\treturn commandFailure(\"must provide a driver name\")\n\t}\n\n\tdriverName := args[0]\n\tdriverPath := args[0]\n\n\tif strings.ContainsRune(driverName, os.PathSeparator) {\n\t\tdriverName = strings.Replace(filepath.Base(driverName), \"sqlboiler-\", \"\", 1)\n\t} else {\n\t\tdriverPath = \"sqlboiler-\" + driverPath\n\t\tif p, err := exec.LookPath(driverPath); err == nil {\n\t\t\tdriverPath = p\n\t\t}\n\t}\n\n\tdriverPath, err = filepath.Abs(driverPath)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not find absolute path to driver\")\n\t}\n\tdrivers.RegisterBinary(driverName, driverPath)\n\n\tcmdConfig = &boilingcore.Config{\n\t\tDriverName:       driverName,\n\t\tOutFolder:        viper.GetString(\"output\"),\n\t\tPkgName:          viper.GetString(\"pkgname\"),\n\t\tDebug:            viper.GetBool(\"debug\"),\n\t\tAddGlobal:        viper.GetBool(\"add-global-variants\"),\n\t\tAddPanic:         viper.GetBool(\"add-panic-variants\"),\n\t\tNoContext:        viper.GetBool(\"no-context\"),\n\t\tNoTests:          viper.GetBool(\"no-tests\"),\n\t\tNoHooks:          viper.GetBool(\"no-hooks\"),\n\t\tNoRowsAffected:   viper.GetBool(\"no-rows-affected\"),\n\t\tNoAutoTimestamps: viper.GetBool(\"no-auto-timestamps\"),\n\t\tWipe:             viper.GetBool(\"wipe\"),\n\t\tStructTagCasing:  strings.ToLower(viper.GetString(\"struct-tag-casing\")), \/\/ camel | snake\n\t\tTemplateDirs:     viper.GetStringSlice(\"templates\"),\n\t\tTags:             viper.GetStringSlice(\"tag\"),\n\t\tReplacements:     viper.GetStringSlice(\"replace\"),\n\t\tAliases:          boilingcore.ConvertAliases(viper.Get(\"aliases\")),\n\t\tTypeReplaces:     boilingcore.ConvertTypeReplace(viper.Get(\"types\")),\n\t}\n\n\tif cmdConfig.Debug {\n\t\tfmt.Fprintln(os.Stderr, \"using driver:\", driverPath)\n\t}\n\n\t\/\/ Configure the driver\n\tcmdConfig.DriverConfig = map[string]interface{}{\n\t\t\"whitelist\": viper.GetStringSlice(driverName + \".whitelist\"),\n\t\t\"blacklist\": viper.GetStringSlice(driverName + \".blacklist\"),\n\t}\n\n\tkeys := allKeys(driverName)\n\tfor _, key := range keys {\n\t\tprefixedKey := fmt.Sprintf(\"%s.%s\", driverName, key)\n\t\tcmdConfig.DriverConfig[key] = viper.Get(prefixedKey)\n\t}\n\n\tcmdConfig.Imports = configureImports()\n\n\tcmdState, err = boilingcore.New(cmdConfig)\n\treturn err\n}\n\nfunc configureImports() importers.Collection {\n\timports := importers.NewDefaultImports()\n\n\tmustMap := func(m importers.Map, err error) importers.Map {\n\t\tif err != nil {\n\t\t\tpanic(\"failed to change viper interface into importers.Map: \" + err.Error())\n\t\t}\n\n\t\treturn m\n\t}\n\n\tif viper.IsSet(\"imports.all.standard\") {\n\t\timports.All.Standard = viper.GetStringSlice(\"imports.all.standard\")\n\t}\n\tif viper.IsSet(\"imports.all.third_party\") {\n\t\timports.All.ThirdParty = viper.GetStringSlice(\"imports.all.third_party\")\n\t}\n\tif viper.IsSet(\"imports.test.standard\") {\n\t\timports.Test.Standard = viper.GetStringSlice(\"imports.test.standard\")\n\t}\n\tif viper.IsSet(\"imports.test.third_party\") {\n\t\timports.Test.ThirdParty = viper.GetStringSlice(\"imports.test.third_party\")\n\t}\n\tif viper.IsSet(\"imports.singleton\") {\n\t\timports.Singleton = mustMap(importers.MapFromInterface(viper.Get(\"imports.singleton\")))\n\t}\n\tif viper.IsSet(\"imports.test_singleton\") {\n\t\timports.TestSingleton = mustMap(importers.MapFromInterface(viper.Get(\"imports.test_singleton\")))\n\t}\n\tif viper.IsSet(\"imports.based_on_type\") {\n\t\timports.BasedOnType = mustMap(importers.MapFromInterface(viper.Get(\"imports.based_on_type\")))\n\t}\n\n\treturn imports\n}\n\nfunc run(cmd *cobra.Command, args []string) error {\n\treturn cmdState.Run()\n}\n\nfunc postRun(cmd *cobra.Command, args []string) error {\n\treturn cmdState.Cleanup()\n}\n\nfunc allKeys(prefix string) []string {\n\tkeys := make(map[string]bool)\n\n\tprefix = prefix + \".\"\n\n\tfor _, e := range os.Environ() {\n\t\tsplits := strings.SplitN(e, \"=\", 2)\n\t\tkey := strings.Replace(strings.ToLower(splits[0]), \"_\", \".\", -1)\n\n\t\tif strings.HasPrefix(key, prefix) {\n\t\t\tkeys[strings.Replace(key, prefix, \"\", -1)] = true\n\t\t}\n\t}\n\n\tfor _, key := range viper.AllKeys() {\n\t\tif strings.HasPrefix(key, prefix) {\n\t\t\tkeys[strings.Replace(key, prefix, \"\", -1)] = true\n\t\t}\n\t}\n\n\tkeySlice := make([]string, 0, len(keys))\n\tfor k := range keys {\n\t\tkeySlice = append(keySlice, k)\n\t}\n\treturn keySlice\n}\n<commit_msg>Bump version<commit_after>\/\/ Package main defines a command line interface for the sqlboiler package\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n\t\"github.com\/volatiletech\/sqlboiler\/boilingcore\"\n\t\"github.com\/volatiletech\/sqlboiler\/drivers\"\n\t\"github.com\/volatiletech\/sqlboiler\/importers\"\n)\n\n\/\/go:generate go-bindata -pkg templatebin -o templatebin\/bindata.go templates templates\/singleton templates_test templates_test\/singleton\n\nconst sqlBoilerVersion = \"3.0.0-rc2\"\n\nvar (\n\tflagConfigFile string\n\tcmdState       *boilingcore.State\n\tcmdConfig      *boilingcore.Config\n)\n\nfunc initConfig() {\n\tif len(flagConfigFile) != 0 {\n\t\tviper.SetConfigFile(flagConfigFile)\n\t\tif err := viper.ReadInConfig(); err != nil {\n\t\t\tfmt.Println(\"Can't read config:\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\treturn\n\t}\n\n\tvar err error\n\tviper.SetConfigName(\"sqlboiler\")\n\n\tconfigHome := os.Getenv(\"XDG_CONFIG_HOME\")\n\thomePath := os.Getenv(\"HOME\")\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\twd = \".\/\"\n\t}\n\n\tconfigPaths := []string{wd}\n\tif len(configHome) > 0 {\n\t\tconfigPaths = append(configPaths, filepath.Join(configHome, \"sqlboiler\"))\n\t} else {\n\t\tconfigPaths = append(configPaths, filepath.Join(homePath, \".config\/sqlboiler\"))\n\t}\n\n\tfor _, p := range configPaths {\n\t\tviper.AddConfigPath(p)\n\t}\n\n\t\/\/ Ignore errors here, fallback to other validation methods.\n\t\/\/ Users can use environment variables if a config is not found.\n\t_ = viper.ReadInConfig()\n}\n\nfunc main() {\n\t\/\/ Too much happens between here and cobra's argument handling, for\n\t\/\/ something so simple just do it immediately.\n\tfor _, arg := range os.Args {\n\t\tif arg == \"--version\" {\n\t\t\tfmt.Println(\"SQLBoiler v\" + sqlBoilerVersion)\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ Set up the cobra root command\n\tvar rootCmd = &cobra.Command{\n\t\tUse:   \"sqlboiler [flags] <driver>\",\n\t\tShort: \"SQL Boiler generates an ORM tailored to your database schema.\",\n\t\tLong: \"SQL Boiler generates a Go ORM from template files, tailored to your database schema.\\n\" +\n\t\t\t`Complete documentation is available at http:\/\/github.com\/volatiletech\/sqlboiler`,\n\t\tExample:       `sqlboiler psql`,\n\t\tPreRunE:       preRun,\n\t\tRunE:          run,\n\t\tPostRunE:      postRun,\n\t\tSilenceErrors: true,\n\t\tSilenceUsage:  true,\n\t}\n\n\tcobra.OnInitialize(initConfig)\n\n\t\/\/ Set up the cobra root command flags\n\trootCmd.PersistentFlags().StringVarP(&flagConfigFile, \"config\", \"c\", \"\", \"Filename of config file to override default lookup\")\n\trootCmd.PersistentFlags().StringP(\"output\", \"o\", \"models\", \"The name of the folder to output to\")\n\trootCmd.PersistentFlags().StringP(\"pkgname\", \"p\", \"models\", \"The name you wish to assign to your generated package\")\n\trootCmd.PersistentFlags().StringSliceP(\"templates\", \"\", nil, \"A templates directory, overrides the bindata'd template folders in sqlboiler\")\n\trootCmd.PersistentFlags().StringSliceP(\"tag\", \"t\", nil, \"Struct tags to be included on your models in addition to json, yaml, toml\")\n\trootCmd.PersistentFlags().StringSliceP(\"replace\", \"\", nil, \"Replace templates by directory: relpath\/to_file.tpl:relpath\/to_replacement.tpl\")\n\trootCmd.PersistentFlags().BoolP(\"debug\", \"d\", false, \"Debug mode prints stack traces on error\")\n\trootCmd.PersistentFlags().BoolP(\"no-context\", \"\", false, \"Disable context.Context usage in the generated code\")\n\trootCmd.PersistentFlags().BoolP(\"no-tests\", \"\", false, \"Disable generated go test files\")\n\trootCmd.PersistentFlags().BoolP(\"no-hooks\", \"\", false, \"Disable hooks feature for your models\")\n\trootCmd.PersistentFlags().BoolP(\"no-rows-affected\", \"\", false, \"Disable rows affected in the generated API\")\n\trootCmd.PersistentFlags().BoolP(\"no-auto-timestamps\", \"\", false, \"Disable automatic timestamps for created_at\/updated_at\")\n\trootCmd.PersistentFlags().BoolP(\"add-global-variants\", \"\", false, \"Enable generation for global variants\")\n\trootCmd.PersistentFlags().BoolP(\"add-panic-variants\", \"\", false, \"Enable generation for panic variants\")\n\trootCmd.PersistentFlags().BoolP(\"version\", \"\", false, \"Print the version\")\n\trootCmd.PersistentFlags().BoolP(\"wipe\", \"\", false, \"Delete the output folder (rm -rf) before generation to ensure sanity\")\n\trootCmd.PersistentFlags().StringP(\"struct-tag-casing\", \"\", \"snake\", \"Decides the casing for go structure tag names. camel or snake (default snake)\")\n\n\t\/\/ hide flags not recommended for use\n\trootCmd.PersistentFlags().MarkHidden(\"replace\")\n\n\tviper.BindPFlags(rootCmd.PersistentFlags())\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\n\tviper.AutomaticEnv()\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tif e, ok := err.(commandFailure); ok {\n\t\t\tfmt.Printf(\"Error: %v\\n\\n\", string(e))\n\t\t\trootCmd.Help()\n\t\t} else if !viper.GetBool(\"debug\") {\n\t\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\t} else {\n\t\t\tfmt.Printf(\"Error: %+v\\n\", err)\n\t\t}\n\n\t\tos.Exit(1)\n\t}\n}\n\ntype commandFailure string\n\nfunc (c commandFailure) Error() string {\n\treturn string(c)\n}\n\nfunc preRun(cmd *cobra.Command, args []string) error {\n\tvar err error\n\n\tif len(args) == 0 {\n\t\treturn commandFailure(\"must provide a driver name\")\n\t}\n\n\tdriverName := args[0]\n\tdriverPath := args[0]\n\n\tif strings.ContainsRune(driverName, os.PathSeparator) {\n\t\tdriverName = strings.Replace(filepath.Base(driverName), \"sqlboiler-\", \"\", 1)\n\t} else {\n\t\tdriverPath = \"sqlboiler-\" + driverPath\n\t\tif p, err := exec.LookPath(driverPath); err == nil {\n\t\t\tdriverPath = p\n\t\t}\n\t}\n\n\tdriverPath, err = filepath.Abs(driverPath)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not find absolute path to driver\")\n\t}\n\tdrivers.RegisterBinary(driverName, driverPath)\n\n\tcmdConfig = &boilingcore.Config{\n\t\tDriverName:       driverName,\n\t\tOutFolder:        viper.GetString(\"output\"),\n\t\tPkgName:          viper.GetString(\"pkgname\"),\n\t\tDebug:            viper.GetBool(\"debug\"),\n\t\tAddGlobal:        viper.GetBool(\"add-global-variants\"),\n\t\tAddPanic:         viper.GetBool(\"add-panic-variants\"),\n\t\tNoContext:        viper.GetBool(\"no-context\"),\n\t\tNoTests:          viper.GetBool(\"no-tests\"),\n\t\tNoHooks:          viper.GetBool(\"no-hooks\"),\n\t\tNoRowsAffected:   viper.GetBool(\"no-rows-affected\"),\n\t\tNoAutoTimestamps: viper.GetBool(\"no-auto-timestamps\"),\n\t\tWipe:             viper.GetBool(\"wipe\"),\n\t\tStructTagCasing:  strings.ToLower(viper.GetString(\"struct-tag-casing\")), \/\/ camel | snake\n\t\tTemplateDirs:     viper.GetStringSlice(\"templates\"),\n\t\tTags:             viper.GetStringSlice(\"tag\"),\n\t\tReplacements:     viper.GetStringSlice(\"replace\"),\n\t\tAliases:          boilingcore.ConvertAliases(viper.Get(\"aliases\")),\n\t\tTypeReplaces:     boilingcore.ConvertTypeReplace(viper.Get(\"types\")),\n\t}\n\n\tif cmdConfig.Debug {\n\t\tfmt.Fprintln(os.Stderr, \"using driver:\", driverPath)\n\t}\n\n\t\/\/ Configure the driver\n\tcmdConfig.DriverConfig = map[string]interface{}{\n\t\t\"whitelist\": viper.GetStringSlice(driverName + \".whitelist\"),\n\t\t\"blacklist\": viper.GetStringSlice(driverName + \".blacklist\"),\n\t}\n\n\tkeys := allKeys(driverName)\n\tfor _, key := range keys {\n\t\tprefixedKey := fmt.Sprintf(\"%s.%s\", driverName, key)\n\t\tcmdConfig.DriverConfig[key] = viper.Get(prefixedKey)\n\t}\n\n\tcmdConfig.Imports = configureImports()\n\n\tcmdState, err = boilingcore.New(cmdConfig)\n\treturn err\n}\n\nfunc configureImports() importers.Collection {\n\timports := importers.NewDefaultImports()\n\n\tmustMap := func(m importers.Map, err error) importers.Map {\n\t\tif err != nil {\n\t\t\tpanic(\"failed to change viper interface into importers.Map: \" + err.Error())\n\t\t}\n\n\t\treturn m\n\t}\n\n\tif viper.IsSet(\"imports.all.standard\") {\n\t\timports.All.Standard = viper.GetStringSlice(\"imports.all.standard\")\n\t}\n\tif viper.IsSet(\"imports.all.third_party\") {\n\t\timports.All.ThirdParty = viper.GetStringSlice(\"imports.all.third_party\")\n\t}\n\tif viper.IsSet(\"imports.test.standard\") {\n\t\timports.Test.Standard = viper.GetStringSlice(\"imports.test.standard\")\n\t}\n\tif viper.IsSet(\"imports.test.third_party\") {\n\t\timports.Test.ThirdParty = viper.GetStringSlice(\"imports.test.third_party\")\n\t}\n\tif viper.IsSet(\"imports.singleton\") {\n\t\timports.Singleton = mustMap(importers.MapFromInterface(viper.Get(\"imports.singleton\")))\n\t}\n\tif viper.IsSet(\"imports.test_singleton\") {\n\t\timports.TestSingleton = mustMap(importers.MapFromInterface(viper.Get(\"imports.test_singleton\")))\n\t}\n\tif viper.IsSet(\"imports.based_on_type\") {\n\t\timports.BasedOnType = mustMap(importers.MapFromInterface(viper.Get(\"imports.based_on_type\")))\n\t}\n\n\treturn imports\n}\n\nfunc run(cmd *cobra.Command, args []string) error {\n\treturn cmdState.Run()\n}\n\nfunc postRun(cmd *cobra.Command, args []string) error {\n\treturn cmdState.Cleanup()\n}\n\nfunc allKeys(prefix string) []string {\n\tkeys := make(map[string]bool)\n\n\tprefix = prefix + \".\"\n\n\tfor _, e := range os.Environ() {\n\t\tsplits := strings.SplitN(e, \"=\", 2)\n\t\tkey := strings.Replace(strings.ToLower(splits[0]), \"_\", \".\", -1)\n\n\t\tif strings.HasPrefix(key, prefix) {\n\t\t\tkeys[strings.Replace(key, prefix, \"\", -1)] = true\n\t\t}\n\t}\n\n\tfor _, key := range viper.AllKeys() {\n\t\tif strings.HasPrefix(key, prefix) {\n\t\t\tkeys[strings.Replace(key, prefix, \"\", -1)] = true\n\t\t}\n\t}\n\n\tkeySlice := make([]string, 0, len(keys))\n\tfor k := range keys {\n\t\tkeySlice = append(keySlice, k)\n\t}\n\treturn keySlice\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tgit2go \"gopkg.in\/libgit2\/git2go.v26\"\n\n\t\"github.com\/josledp\/termcolor\"\n)\n\nconst (\n\tdownArrow   = \"↓\"\n\tupArrow     = \"↑\"\n\tthreePoints = \"…\"\n\tdot         = \"●\"\n\tcheck       = \"✔\"\n\tflag        = \"⚑\"\n)\n\nvar logger *log.Logger\n\nfunc getPythonVirtualEnv() string {\n\tvirtualEnv, ve := os.LookupEnv(\"VIRTUAL_ENV\")\n\tif ve {\n\t\tave := strings.Split(virtualEnv, \"\/\")\n\t\tvirtualEnv = fmt.Sprintf(\"(%s) \", ave[len(ave)-1])\n\t}\n\treturn virtualEnv\n}\n\nfunc getAwsInfo() string {\n\trole := os.Getenv(\"AWS_ROLE\")\n\tif role != \"\" {\n\t\ttmp := strings.Split(role, \":\")\n\t\trole = tmp[0]\n\t\ttmp = strings.Split(tmp[1], \"-\")\n\t\trole += \":\" + tmp[2]\n\t}\n\treturn role\n}\n\nfunc getGitInfo() gitInfo {\n\tgi := gitInfo{}\n\n\tgitpath, err := git2go.Discover(\".\", false, []string{\"\/\"})\n\tif err == nil {\n\t\trepository, err := git2go.OpenRepository(gitpath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error opening repository at %s: %v\", gitpath, err)\n\t\t}\n\t\tdefer repository.Free()\n\n\t\t\/\/Get current tracked & untracked files status\n\t\tstatusOpts := git2go.StatusOptions{\n\t\t\tFlags: git2go.StatusOptIncludeUntracked | git2go.StatusOptRenamesHeadToIndex,\n\t\t}\n\t\trepostate, err := repository.StatusList(&statusOpts)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error getting repository status at %s: %v\", gitpath, err)\n\t\t}\n\t\tdefer repostate.Free()\n\t\tn, err := repostate.EntryCount()\n\t\tfor i := 0; i < n; i++ {\n\t\t\tentry, _ := repostate.ByIndex(i)\n\t\t\tgot := false\n\t\t\tif entry.Status&git2go.StatusCurrent > 0 {\n\t\t\t\tlogger.Println(\"StatusCurrent\")\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusIndexNew > 0 {\n\t\t\t\tlogger.Println(\"StatusIndexNew\")\n\t\t\t\tgi.staged++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusIndexModified > 0 {\n\t\t\t\tlogger.Println(\"StatusIndexModified\")\n\t\t\t\tgi.staged++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusIndexDeleted > 0 {\n\t\t\t\tlogger.Println(\"StatusIndexDeleted\")\n\t\t\t\tgi.staged++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusIndexRenamed > 0 {\n\t\t\t\tlogger.Println(\"StatusIndexRenamed\")\n\t\t\t\tgi.staged++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusIndexTypeChange > 0 {\n\t\t\t\tlogger.Println(\"StatusIndexTypeChange\")\n\t\t\t\tgi.staged++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusWtNew > 0 {\n\t\t\t\tlogger.Println(\"StatusWtNew\")\n\t\t\t\tgi.untracked++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusWtModified > 0 {\n\t\t\t\tlogger.Println(\"StatusWtModified\")\n\t\t\t\tgi.changed++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusWtDeleted > 0 {\n\t\t\t\tlogger.Println(\"StatusWtDeleted\")\n\t\t\t\tgi.changed++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusWtTypeChange > 0 {\n\t\t\t\tlogger.Println(\"StatusWtTypeChange\")\n\t\t\t\tgi.changed++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusWtRenamed > 0 {\n\t\t\t\tlogger.Println(\"StatusWtRenamed\")\n\t\t\t\tgi.changed++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusIgnored > 0 {\n\t\t\t\tlogger.Println(\"StatusIgnored\")\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusConflicted > 0 {\n\t\t\t\tlogger.Println(\"StatusConflicted\")\n\t\t\t\tgi.conflict = true\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif !got {\n\t\t\t\tlogger.Println(\"Unknown: \", entry.Status)\n\t\t\t}\n\t\t}\n\t\t\/\/Get current branch name\n\t\tlocalRef, err := repository.Head()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"error getting head: \", err)\n\t\t}\n\t\tdefer localRef.Free()\n\n\t\tref := strings.Split(localRef.Name(), \"\/\")\n\t\tgi.branch = ref[len(ref)-1]\n\t\t\/\/Get commits Ahead\/Behind\n\n\t\tlocalBranch := localRef.Branch()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Error getting local branch: \", err)\n\t\t}\n\n\t\tremoteRef, err := localBranch.Upstream()\n\t\tif err == nil {\n\t\t\tgi.upstream = true\n\t\t\tdefer remoteRef.Free()\n\n\t\t\tif !remoteRef.Target().Equal(localRef.Target()) {\n\t\t\t\tlogger.Println(\"Local & remore differ:\", remoteRef.Target().String(), localRef.Target().String())\n\t\t\t\t\/\/git rev-list --left-right localRef...remoteRef\n\t\t\t\toids, err := repository.MergeBases(localRef.Target(), remoteRef.Target())\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalln(\"Error getting merge bases\")\n\t\t\t\t}\n\n\t\t\t\tgi.commitsAhead = gitCount(repository, localRef.Target(), oids)\n\t\t\t\tgi.commitsBehind = gitCount(repository, remoteRef.Target(), oids)\n\t\t\t\tlogger.Println(gi.commitsAhead, gi.commitsBehind)\n\t\t\t}\n\t\t}\n\n\t}\n\treturn gi\n}\n\nfunc gitCount(r *git2go.Repository, oid *git2go.Oid, until []*git2go.Oid) int {\n\tc, err := r.LookupCommit(oid)\n\tdefer c.Free()\n\tif err != nil {\n\t\tlog.Fatalln(\"Error getting commit from oid \", oid, \": \", err)\n\t}\n\tmUntil := make(map[string]struct{})\n\tfor _, u := range until {\n\t\tmUntil[u.String()] = struct{}{}\n\t}\n\treturn _gitCount(r, c, mUntil)\n\n}\nfunc _gitCount(r *git2go.Repository, c *git2go.Commit, until map[string]struct{}) int {\n\tvar s int\n\tfor i := uint(0); i < c.ParentCount(); i++ {\n\t\ts++\n\t\tpc := c.ParentId(i)\n\t\tif _, ok := until[pc.String()]; !ok {\n\t\t\ts += _gitCount(r, c.Parent(i), until)\n\t\t}\n\n\t}\n\treturn s\n}\n\ntype gitInfo struct {\n\tconflict      bool\n\tchanged       int\n\tstaged        int\n\tuntracked     int\n\tcommitsAhead  int\n\tcommitsBehind int\n\tstashed       int\n\tbranch        string\n\tupstream      bool\n}\n\ntype termInfo struct {\n\tlastrc     string\n\tpwd        string\n\tuser       string\n\thostname   string\n\tvirtualEnv string\n\tawsRole    string\n\tawsExpire  time.Time\n\tgi         gitInfo\n}\n\nfunc main() {\n\tvar err error\n\tvar debug bool\n\n\tflag.BoolVar(&debug, \"debug\", false, \"enable debug messages\")\n\tflag.Parse()\n\tlogger = log.New(os.Stderr, \"\", log.LstdFlags)\n\n\tif !debug {\n\t\tlogger.SetOutput(ioutil.Discard)\n\t}\n\tti := termInfo{}\n\t\/\/Get basicinfo\n\tti.pwd, err = os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalln(\"Unable to get current path\", err)\n\t}\n\thome := os.Getenv(\"HOME\")\n\tif home != \"\" {\n\t\tti.pwd = strings.Replace(ti.pwd, home, \"~\", -1)\n\t}\n\tti.user = os.Getenv(\"USER\")\n\tti.hostname, err = os.Hostname()\n\tif err != nil {\n\t\tlog.Fatalln(\"Unable to get hostname\", err)\n\t}\n\tti.lastrc = os.Getenv(\"LAST_COMMAND_RC\")\n\n\t\/\/Get Python VirtualEnv info\n\tti.virtualEnv = getPythonVirtualEnv()\n\n\t\/\/AWS\n\tti.awsRole = getAwsInfo()\n\tiExpire, _ := strconv.ParseInt(os.Getenv(\"AWS_SESSION_EXPIRE\"), 10, 0)\n\tti.awsExpire = time.Unix(iExpire, int64(0))\n\n\t\/\/Get git information\n\t_ = git2go.Repository{}\n\n\tti.gi = getGitInfo()\n\n\tfmt.Println(makePrompt(ti))\n}\n\nfunc makePrompt(ti termInfo) string {\n\t\/\/Formatting\n\tvar userInfo, lastCommandInfo, pwdInfo, virtualEnvInfo, awsInfo, gitInfo string\n\n\tpromptEnd := \"$\"\n\n\tif ti.user == \"root\" {\n\t\tuserInfo = termcolor.EscapedFormat(ti.hostname, termcolor.Bold, termcolor.FgRed)\n\t\tpromptEnd = \"#\"\n\t} else {\n\t\tuserInfo = termcolor.EscapedFormat(ti.hostname, termcolor.Bold, termcolor.FgGreen)\n\t}\n\tif ti.lastrc != \"\" {\n\t\tlastCommandInfo = termcolor.EscapedFormat(ti.lastrc, termcolor.FgHiYellow) + \" \"\n\t}\n\n\tpwdInfo = termcolor.EscapedFormat(ti.pwd, termcolor.Bold, termcolor.FgBlue)\n\tif ti.virtualEnv != \"\" {\n\t\tvirtualEnvInfo = termcolor.EscapedFormat(ti.virtualEnv, termcolor.FgBlue)\n\t}\n\tif ti.gi.branch != \"\" {\n\t\tgitInfo = \" \" + termcolor.EscapedFormat(ti.gi.branch, termcolor.FgMagenta)\n\t\tspace := \" \"\n\t\tif ti.gi.commitsBehind > 0 {\n\t\t\tgitInfo += space + downArrow + \"·\" + strconv.Itoa(ti.gi.commitsBehind)\n\t\t\tspace = \"\"\n\t\t}\n\t\tif ti.gi.commitsAhead > 0 {\n\t\t\tgitInfo += space + upArrow + \"·\" + strconv.Itoa(ti.gi.commitsAhead)\n\t\t\tspace = \"\"\n\t\t}\n\t\tif !ti.gi.upstream {\n\t\t\tgitInfo += space + \"*\"\n\t\t\tspace = \"\"\n\t\t}\n\t\tgitInfo += \"|\"\n\t\tsynced := true\n\t\tif ti.gi.staged > 0 {\n\t\t\tgitInfo += termcolor.EscapedFormat(dot+strconv.Itoa(ti.gi.staged), termcolor.FgCyan)\n\t\t\tsynced = false\n\t\t}\n\t\tif ti.gi.changed > 0 {\n\t\t\tgitInfo += termcolor.EscapedFormat(\"+\"+strconv.Itoa(ti.gi.changed), termcolor.FgCyan)\n\t\t\tsynced = false\n\t\t}\n\t\tif ti.gi.untracked > 0 {\n\t\t\tgitInfo += termcolor.EscapedFormat(threePoints+strconv.Itoa(ti.gi.untracked), termcolor.FgCyan)\n\t\t\tsynced = false\n\t\t}\n\t\tif synced {\n\t\t\tgitInfo += termcolor.EscapedFormat(check, termcolor.FgHiGreen)\n\t\t}\n\t}\n\tif ti.awsRole != \"\" {\n\t\tt := termcolor.FgGreen\n\t\td := time.Until(ti.awsExpire).Seconds()\n\t\tif d < 0 {\n\t\t\tt = termcolor.FgRed\n\t\t} else if d < 600 {\n\t\t\tt = termcolor.FgYellow\n\t\t}\n\t\tawsInfo = termcolor.EscapedFormat(ti.awsRole, t) + \"|\"\n\t}\n\n\treturn fmt.Sprintf(\"%s[%s%s %s%s%s]%s \", virtualEnvInfo, awsInfo, userInfo, lastCommandInfo, pwdInfo, gitInfo, promptEnd)\n}\n<commit_msg>stashes on gi info, lacking on prompt<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tgit2go \"gopkg.in\/libgit2\/git2go.v26\"\n\n\t\"github.com\/josledp\/termcolor\"\n)\n\nconst (\n\tdownArrow   = \"↓\"\n\tupArrow     = \"↑\"\n\tthreePoints = \"…\"\n\tdot         = \"●\"\n\tcheck       = \"✔\"\n\tflag        = \"⚑\"\n)\n\nvar logger *log.Logger\n\nfunc getPythonVirtualEnv() string {\n\tvirtualEnv, ve := os.LookupEnv(\"VIRTUAL_ENV\")\n\tif ve {\n\t\tave := strings.Split(virtualEnv, \"\/\")\n\t\tvirtualEnv = fmt.Sprintf(\"(%s) \", ave[len(ave)-1])\n\t}\n\treturn virtualEnv\n}\n\nfunc getAwsInfo() string {\n\trole := os.Getenv(\"AWS_ROLE\")\n\tif role != \"\" {\n\t\ttmp := strings.Split(role, \":\")\n\t\trole = tmp[0]\n\t\ttmp = strings.Split(tmp[1], \"-\")\n\t\trole += \":\" + tmp[2]\n\t}\n\treturn role\n}\n\nfunc getGitInfo() gitInfo {\n\tgi := gitInfo{}\n\n\tgitpath, err := git2go.Discover(\".\", false, []string{\"\/\"})\n\tif err == nil {\n\t\trepository, err := git2go.OpenRepository(gitpath)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error opening repository at %s: %v\", gitpath, err)\n\t\t}\n\t\tdefer repository.Free()\n\n\t\t\/\/Get current tracked & untracked files status\n\t\tstatusOpts := git2go.StatusOptions{\n\t\t\tFlags: git2go.StatusOptIncludeUntracked | git2go.StatusOptRenamesHeadToIndex,\n\t\t}\n\t\trepostate, err := repository.StatusList(&statusOpts)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error getting repository status at %s: %v\", gitpath, err)\n\t\t}\n\t\tdefer repostate.Free()\n\t\tn, err := repostate.EntryCount()\n\t\tfor i := 0; i < n; i++ {\n\t\t\tentry, _ := repostate.ByIndex(i)\n\t\t\tgot := false\n\t\t\tif entry.Status&git2go.StatusCurrent > 0 {\n\t\t\t\tlogger.Println(\"StatusCurrent\")\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusIndexNew > 0 {\n\t\t\t\tlogger.Println(\"StatusIndexNew\")\n\t\t\t\tgi.staged++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusIndexModified > 0 {\n\t\t\t\tlogger.Println(\"StatusIndexModified\")\n\t\t\t\tgi.staged++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusIndexDeleted > 0 {\n\t\t\t\tlogger.Println(\"StatusIndexDeleted\")\n\t\t\t\tgi.staged++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusIndexRenamed > 0 {\n\t\t\t\tlogger.Println(\"StatusIndexRenamed\")\n\t\t\t\tgi.staged++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusIndexTypeChange > 0 {\n\t\t\t\tlogger.Println(\"StatusIndexTypeChange\")\n\t\t\t\tgi.staged++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusWtNew > 0 {\n\t\t\t\tlogger.Println(\"StatusWtNew\")\n\t\t\t\tgi.untracked++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusWtModified > 0 {\n\t\t\t\tlogger.Println(\"StatusWtModified\")\n\t\t\t\tgi.changed++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusWtDeleted > 0 {\n\t\t\t\tlogger.Println(\"StatusWtDeleted\")\n\t\t\t\tgi.changed++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusWtTypeChange > 0 {\n\t\t\t\tlogger.Println(\"StatusWtTypeChange\")\n\t\t\t\tgi.changed++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusWtRenamed > 0 {\n\t\t\t\tlogger.Println(\"StatusWtRenamed\")\n\t\t\t\tgi.changed++\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusIgnored > 0 {\n\t\t\t\tlogger.Println(\"StatusIgnored\")\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif entry.Status&git2go.StatusConflicted > 0 {\n\t\t\t\tlogger.Println(\"StatusConflicted\")\n\t\t\t\tgi.conflict = true\n\t\t\t\tgot = true\n\t\t\t}\n\t\t\tif !got {\n\t\t\t\tlogger.Println(\"Unknown: \", entry.Status)\n\t\t\t}\n\t\t}\n\t\t\/\/Get current branch name\n\t\tlocalRef, err := repository.Head()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"error getting head: \", err)\n\t\t}\n\t\tdefer localRef.Free()\n\n\t\tref := strings.Split(localRef.Name(), \"\/\")\n\t\tgi.branch = ref[len(ref)-1]\n\t\t\/\/Get commits Ahead\/Behind\n\n\t\tlocalBranch := localRef.Branch()\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Error getting local branch: \", err)\n\t\t}\n\n\t\tremoteRef, err := localBranch.Upstream()\n\t\tif err == nil {\n\t\t\tgi.upstream = true\n\t\t\tdefer remoteRef.Free()\n\n\t\t\tif !remoteRef.Target().Equal(localRef.Target()) {\n\t\t\t\tlogger.Println(\"Local & remore differ:\", remoteRef.Target().String(), localRef.Target().String())\n\t\t\t\t\/\/git rev-list --left-right localRef...remoteRef\n\t\t\t\toids, err := repository.MergeBases(localRef.Target(), remoteRef.Target())\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalln(\"Error getting merge bases\")\n\t\t\t\t}\n\n\t\t\t\tgi.commitsAhead = gitCount(repository, localRef.Target(), oids)\n\t\t\t\tgi.commitsBehind = gitCount(repository, remoteRef.Target(), oids)\n\t\t\t\tlogger.Println(gi.commitsAhead, gi.commitsBehind)\n\t\t\t}\n\t\t}\n\t\t\/\/ stash\n\t\trepository.Stashes.Foreach(func(i int, m string, o *git2go.Oid) error {\n\t\t\tgi.stashed = i + 1\n\t\t\treturn nil\n\t\t})\n\t\tlogger.Println(\"Stashes: \", gi.stashed)\n\t}\n\treturn gi\n}\n\nfunc gitCount(r *git2go.Repository, oid *git2go.Oid, until []*git2go.Oid) int {\n\tc, err := r.LookupCommit(oid)\n\tdefer c.Free()\n\tif err != nil {\n\t\tlog.Fatalln(\"Error getting commit from oid \", oid, \": \", err)\n\t}\n\tmUntil := make(map[string]struct{})\n\tfor _, u := range until {\n\t\tmUntil[u.String()] = struct{}{}\n\t}\n\treturn _gitCount(r, c, mUntil)\n\n}\nfunc _gitCount(r *git2go.Repository, c *git2go.Commit, until map[string]struct{}) int {\n\tvar s int\n\tfor i := uint(0); i < c.ParentCount(); i++ {\n\t\ts++\n\t\tpc := c.ParentId(i)\n\t\tif _, ok := until[pc.String()]; !ok {\n\t\t\ts += _gitCount(r, c.Parent(i), until)\n\t\t}\n\n\t}\n\treturn s\n}\n\ntype gitInfo struct {\n\tconflict      bool\n\tchanged       int\n\tstaged        int\n\tuntracked     int\n\tcommitsAhead  int\n\tcommitsBehind int\n\tstashed       int\n\tbranch        string\n\tupstream      bool\n}\n\ntype termInfo struct {\n\tlastrc     string\n\tpwd        string\n\tuser       string\n\thostname   string\n\tvirtualEnv string\n\tawsRole    string\n\tawsExpire  time.Time\n\tgi         gitInfo\n}\n\nfunc main() {\n\tvar err error\n\tvar debug bool\n\n\tflag.BoolVar(&debug, \"debug\", false, \"enable debug messages\")\n\tflag.Parse()\n\tlogger = log.New(os.Stderr, \"\", log.LstdFlags)\n\n\tif !debug {\n\t\tlogger.SetOutput(ioutil.Discard)\n\t}\n\tti := termInfo{}\n\t\/\/Get basicinfo\n\tti.pwd, err = os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalln(\"Unable to get current path\", err)\n\t}\n\thome := os.Getenv(\"HOME\")\n\tif home != \"\" {\n\t\tti.pwd = strings.Replace(ti.pwd, home, \"~\", -1)\n\t}\n\tti.user = os.Getenv(\"USER\")\n\tti.hostname, err = os.Hostname()\n\tif err != nil {\n\t\tlog.Fatalln(\"Unable to get hostname\", err)\n\t}\n\tti.lastrc = os.Getenv(\"LAST_COMMAND_RC\")\n\n\t\/\/Get Python VirtualEnv info\n\tti.virtualEnv = getPythonVirtualEnv()\n\n\t\/\/AWS\n\tti.awsRole = getAwsInfo()\n\tiExpire, _ := strconv.ParseInt(os.Getenv(\"AWS_SESSION_EXPIRE\"), 10, 0)\n\tti.awsExpire = time.Unix(iExpire, int64(0))\n\n\t\/\/Get git information\n\t_ = git2go.Repository{}\n\n\tti.gi = getGitInfo()\n\n\tfmt.Println(makePrompt(ti))\n}\n\nfunc makePrompt(ti termInfo) string {\n\t\/\/Formatting\n\tvar userInfo, lastCommandInfo, pwdInfo, virtualEnvInfo, awsInfo, gitInfo string\n\n\tpromptEnd := \"$\"\n\n\tif ti.user == \"root\" {\n\t\tuserInfo = termcolor.EscapedFormat(ti.hostname, termcolor.Bold, termcolor.FgRed)\n\t\tpromptEnd = \"#\"\n\t} else {\n\t\tuserInfo = termcolor.EscapedFormat(ti.hostname, termcolor.Bold, termcolor.FgGreen)\n\t}\n\tif ti.lastrc != \"\" {\n\t\tlastCommandInfo = termcolor.EscapedFormat(ti.lastrc, termcolor.FgHiYellow) + \" \"\n\t}\n\n\tpwdInfo = termcolor.EscapedFormat(ti.pwd, termcolor.Bold, termcolor.FgBlue)\n\tif ti.virtualEnv != \"\" {\n\t\tvirtualEnvInfo = termcolor.EscapedFormat(ti.virtualEnv, termcolor.FgBlue)\n\t}\n\tif ti.gi.branch != \"\" {\n\t\tgitInfo = \" \" + termcolor.EscapedFormat(ti.gi.branch, termcolor.FgMagenta)\n\t\tspace := \" \"\n\t\tif ti.gi.commitsBehind > 0 {\n\t\t\tgitInfo += space + downArrow + \"·\" + strconv.Itoa(ti.gi.commitsBehind)\n\t\t\tspace = \"\"\n\t\t}\n\t\tif ti.gi.commitsAhead > 0 {\n\t\t\tgitInfo += space + upArrow + \"·\" + strconv.Itoa(ti.gi.commitsAhead)\n\t\t\tspace = \"\"\n\t\t}\n\t\tif !ti.gi.upstream {\n\t\t\tgitInfo += space + \"*\"\n\t\t\tspace = \"\"\n\t\t}\n\t\tgitInfo += \"|\"\n\t\tsynced := true\n\t\tif ti.gi.staged > 0 {\n\t\t\tgitInfo += termcolor.EscapedFormat(dot+strconv.Itoa(ti.gi.staged), termcolor.FgCyan)\n\t\t\tsynced = false\n\t\t}\n\t\tif ti.gi.changed > 0 {\n\t\t\tgitInfo += termcolor.EscapedFormat(\"+\"+strconv.Itoa(ti.gi.changed), termcolor.FgCyan)\n\t\t\tsynced = false\n\t\t}\n\t\tif ti.gi.untracked > 0 {\n\t\t\tgitInfo += termcolor.EscapedFormat(threePoints+strconv.Itoa(ti.gi.untracked), termcolor.FgCyan)\n\t\t\tsynced = false\n\t\t}\n\t\tif synced {\n\t\t\tgitInfo += termcolor.EscapedFormat(check, termcolor.FgHiGreen)\n\t\t}\n\t}\n\tif ti.awsRole != \"\" {\n\t\tt := termcolor.FgGreen\n\t\td := time.Until(ti.awsExpire).Seconds()\n\t\tif d < 0 {\n\t\t\tt = termcolor.FgRed\n\t\t} else if d < 600 {\n\t\t\tt = termcolor.FgYellow\n\t\t}\n\t\tawsInfo = termcolor.EscapedFormat(ti.awsRole, t) + \"|\"\n\t}\n\n\treturn fmt.Sprintf(\"%s[%s%s %s%s%s]%s \", virtualEnvInfo, awsInfo, userInfo, lastCommandInfo, pwdInfo, gitInfo, promptEnd)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"io\/ioutil\"\n\t\"encoding\/json\"\n\t\"strings\"\n\t\"github.com\/line\/line-bot-sdk-go\/linebot\"\n\t\"github.com\/go-redis\/redis\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype device struct {\n\t\/\/ Gps_num float32 `json:\"gps_num\"`\n\t\/\/ App string `json:\"app\"`\n\t\/\/ Gps_alt float32 `json:\"gps_alt\"`\n\t\/\/ Fmt_opt int `json:\"fmt_opt\"`\n\t\/\/ Device string `json:\"device\"`\n\t\/\/ S_d2 float32 `json:\"s_d2\"`\n\tS_d0 float32 `json:\"s_d0\"`\n\t\/\/ S_d1 float32 `json:\"s_d1\"`\n\tS_h0 float32 `json:\"s_h0\"`\n\tSiteName string `json:\"SiteName\"`\n\t\/\/ Gps_fix float32 `json:\"gps_fix\"`\n\t\/\/ Ver_app string `json:\"ver_app\"`\n\tGps_lat float32 `json:\"gps_lat\"`\n\tS_t0 float32 `json:\"s_t0\"`\n\tTimestamp string `json:\"timestamp\"`\n\tGps_lon float32 `json:\"gps_lon\"`\n\t\/\/ Date string `json:\"date\"`\n\t\/\/ Tick float32 `json:\"tick\"`\n\tDevice_id string `json:\"device_id\"`\n\t\/\/ S_1 float32 `json:\"s_1\"`\n\t\/\/ S_0 float32 `json:\"s_0\"`\n\t\/\/ S_3 float32 `json:\"s_3\"`\n\t\/\/ S_2 float32 `json:\"s_2\"`\n\t\/\/ Ver_format string `json:\"ver_format\"`\n\t\/\/ Time string `json:\"time\"`\n}\n\ntype airbox struct {\n\tSource string `json:\"source\"`\n\tFeeds []device `json:\"feeds\"`\n\tVersion string `json:\"version\"`\n\tNum_of_records int `json:\"num_of_records\"`\n}\n\nvar bot *linebot.Client\nvar airbox_json airbox\nvar\tclient=redis.NewClient(&redis.Options{\n\t\tAddr:\"hipposerver.ddns.net:6379\",\n\t\tPassword:\"\",\n\t\tDB:0,\n\t})\n\nfunc main() {\n\turl := \"https:\/\/data.lass-net.org\/data\/last-all-airbox.json\"\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\tres, _ := http.DefaultClient.Do(req)\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\terrs := json.Unmarshal(body, &airbox_json)\n\tif errs != nil {\n\t\tfmt.Println(errs)\n\t}\n\n\t\/\/ fmt.Println(airbox_json)\n\tvar err error\n\tbot, err = linebot.New(os.Getenv(\"ChannelSecret\"), os.Getenv(\"ChannelAccessToken\"))\n\tlog.Println(\"Bot:\", bot, \" err:\", err)\n\thttp.HandleFunc(\"\/callback\", callbackHandler)\n\tport := os.Getenv(\"PORT\")\n\taddr := fmt.Sprintf(\":%s\", port)\n\thttp.ListenAndServe(addr, nil)\n\n\tt:=time.Now()\n\t_, min, _:=t.Clock()\n\tif min==5{\n\t\tpushmessage()\n\t}\n}\nfunc pushmessage(){\n\t_,err:=bot.PushMessage(\"U3617adbdd46283d7e859f36302f4f471\", \"hi!\").Do()\n\tif err!=nil{\n\t\tpanic(err)\n\t}\n}\nfunc callbackHandler(w http.ResponseWriter, r *http.Request) {\n\tevents, err := bot.ParseRequest(r)\n\n\tif err != nil {\n\t\tif err == linebot.ErrInvalidSignature {\n\t\t\tw.WriteHeader(400)\n\t\t} else {\n\t\t\tw.WriteHeader(500)\n\t\t}\n\t\treturn\n\t}\n\n\tfor _, event := range events {\n\t\tif event.Type == linebot.EventTypeMessage {\n\t\t\tswitch message := event.Message.(type) {\n\t\t\tcase *linebot.TextMessage:\n\t\t\t\tvar txtmessage string\n\t\t\t\tinText := strings.ToLower(message.Text)\n\t\t\t\tif strings.Contains(inText,\"訂閱\"){\n\t\t\t\t\tuserID:=event.Source.UserID\n\t\t\t\t\t\/\/ pong, _ := client.Ping().Result()\n\t\t\t\t\t\/\/ txtmessage=pong\n\t\t\t\t\tfor i:=0; i<len(airbox_json.Feeds); i++ {\n\t\t\t\t\t\tif strings.Contains(inText,strings.ToLower(airbox_json.Feeds[i].Device_id)) {\n\t\t\t\t\t\t\tval, err:=client.Get(airbox_json.Feeds[i].Device_id).Result()\n\t\t\t\t\t\t\tif err!=nil{\n\t\t\t\t\t\t\t\tclient.Set(airbox_json.Feeds[i].Device_id,userID,0)\n\t\t\t\t\t\t\t\ttxtmessage=\"訂閱成功!\"\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstringSlice:=strings.Split(val,\",\")\n\t\t\t\t\t\t\tif stringInSlice(userID,stringSlice){\n\t\t\t\t\t\t\t\ttxtmessage=\"您已訂閱過此ID!\"\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t} else{\n\t\t\t\t\t\t\t\tval=val+\",\"+userID\n\t\t\t\t\t\t\t\tclient.Set(airbox_json.Feeds[i].Device_id,val,0)\n\t\t\t\t\t\t\t\ttxtmessage=\"訂閱成功!\"\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else{\n\t\t\t\t\tfor i:=0; i<len(airbox_json.Feeds); i++ {\n\t\t\t\t\t\tif strings.Contains(inText,strings.ToLower(airbox_json.Feeds[i].Device_id)) {\n\t\t\t\t\t\t\ttxtmessage=\"Device_id: \"+airbox_json.Feeds[i].Device_id+\"\\n\"\n\t\t\t\t\t\t\ttxtmessage=txtmessage+\"Site Name: \"+airbox_json.Feeds[i].SiteName+\"\\n\"\n\t\t\t\t\t\t\ttxtmessage=txtmessage+\"Location: (\"+strconv.FormatFloat(float64(airbox_json.Feeds[i].Gps_lon),'f',3,64)+\",\"+strconv.FormatFloat(float64(airbox_json.Feeds[i].Gps_lat),'f',3,64)+\")\"+\"\\n\"\n\t\t\t\t\t\t\ttxtmessage=txtmessage+\"Timestamp: \"+airbox_json.Feeds[i].Timestamp+\"\\n\"\n\t\t\t\t\t\t\ttxtmessage=txtmessage+\"PM2.5: \"+strconv.FormatFloat(float64(airbox_json.Feeds[i].S_d0),'f',0,64)+\"\\n\"\n\t\t\t\t\t\t\ttxtmessage=txtmessage+\"Humidity: \"+strconv.FormatFloat(float64(airbox_json.Feeds[i].S_h0),'f',0,64)+\"\\n\"\n\t\t\t\t\t\t\ttxtmessage=txtmessage+\"Temperature: \"+strconv.FormatFloat(float64(airbox_json.Feeds[i].S_t0),'f',0,64)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(txtmessage)==0{\n\t\t\t\t\ttxtmessage=\"Sorry! No this device ID, please check again.\"\n\t\t\t\t}\n\t\t\t\tif _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(txtmessage)).Do(); err != nil {\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc stringInSlice(a string, list []string) bool {\n    for _, b := range list {\n        if b == a {\n            return true\n        }\n    }\n    return false\n}\n<commit_msg>test push<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"io\/ioutil\"\n\t\"encoding\/json\"\n\t\"strings\"\n\t\"github.com\/line\/line-bot-sdk-go\/linebot\"\n\t\"github.com\/go-redis\/redis\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype device struct {\n\t\/\/ Gps_num float32 `json:\"gps_num\"`\n\t\/\/ App string `json:\"app\"`\n\t\/\/ Gps_alt float32 `json:\"gps_alt\"`\n\t\/\/ Fmt_opt int `json:\"fmt_opt\"`\n\t\/\/ Device string `json:\"device\"`\n\t\/\/ S_d2 float32 `json:\"s_d2\"`\n\tS_d0 float32 `json:\"s_d0\"`\n\t\/\/ S_d1 float32 `json:\"s_d1\"`\n\tS_h0 float32 `json:\"s_h0\"`\n\tSiteName string `json:\"SiteName\"`\n\t\/\/ Gps_fix float32 `json:\"gps_fix\"`\n\t\/\/ Ver_app string `json:\"ver_app\"`\n\tGps_lat float32 `json:\"gps_lat\"`\n\tS_t0 float32 `json:\"s_t0\"`\n\tTimestamp string `json:\"timestamp\"`\n\tGps_lon float32 `json:\"gps_lon\"`\n\t\/\/ Date string `json:\"date\"`\n\t\/\/ Tick float32 `json:\"tick\"`\n\tDevice_id string `json:\"device_id\"`\n\t\/\/ S_1 float32 `json:\"s_1\"`\n\t\/\/ S_0 float32 `json:\"s_0\"`\n\t\/\/ S_3 float32 `json:\"s_3\"`\n\t\/\/ S_2 float32 `json:\"s_2\"`\n\t\/\/ Ver_format string `json:\"ver_format\"`\n\t\/\/ Time string `json:\"time\"`\n}\n\ntype airbox struct {\n\tSource string `json:\"source\"`\n\tFeeds []device `json:\"feeds\"`\n\tVersion string `json:\"version\"`\n\tNum_of_records int `json:\"num_of_records\"`\n}\n\nvar bot *linebot.Client\nvar airbox_json airbox\nvar\tclient=redis.NewClient(&redis.Options{\n\t\tAddr:\"hipposerver.ddns.net:6379\",\n\t\tPassword:\"\",\n\t\tDB:0,\n\t})\n\nfunc main() {\n\turl := \"https:\/\/data.lass-net.org\/data\/last-all-airbox.json\"\n\treq, _ := http.NewRequest(\"GET\", url, nil)\n\tres, _ := http.DefaultClient.Do(req)\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\terrs := json.Unmarshal(body, &airbox_json)\n\tif errs != nil {\n\t\tfmt.Println(errs)\n\t}\n\n\t\/\/ fmt.Println(airbox_json)\n\tvar err error\n\tbot, err = linebot.New(os.Getenv(\"ChannelSecret\"), os.Getenv(\"ChannelAccessToken\"))\n\tlog.Println(\"Bot:\", bot, \" err:\", err)\n\thttp.HandleFunc(\"\/callback\", callbackHandler)\n\tport := os.Getenv(\"PORT\")\n\taddr := fmt.Sprintf(\":%s\", port)\n\thttp.ListenAndServe(addr, nil)\n\n\tt:=time.Now()\n\t_, min, _:=t.Clock()\n\tif min==45{\n\t\tpushmessage()\n\t}\n}\nfunc pushmessage(){\n\t_,err:=bot.PushMessage(\"U3617adbdd46283d7e859f36302f4f471\", \"hi!\").Do()\n\tif err!=nil{\n\t\tpanic(err)\n\t}\n}\nfunc callbackHandler(w http.ResponseWriter, r *http.Request) {\n\tevents, err := bot.ParseRequest(r)\n\n\tif err != nil {\n\t\tif err == linebot.ErrInvalidSignature {\n\t\t\tw.WriteHeader(400)\n\t\t} else {\n\t\t\tw.WriteHeader(500)\n\t\t}\n\t\treturn\n\t}\n\n\tfor _, event := range events {\n\t\tif event.Type == linebot.EventTypeMessage {\n\t\t\tswitch message := event.Message.(type) {\n\t\t\tcase *linebot.TextMessage:\n\t\t\t\tvar txtmessage string\n\t\t\t\tinText := strings.ToLower(message.Text)\n\t\t\t\tif strings.Contains(inText,\"訂閱\"){\n\t\t\t\t\tuserID:=event.Source.UserID\n\t\t\t\t\t\/\/ pong, _ := client.Ping().Result()\n\t\t\t\t\t\/\/ txtmessage=pong\n\t\t\t\t\tfor i:=0; i<len(airbox_json.Feeds); i++ {\n\t\t\t\t\t\tif strings.Contains(inText,strings.ToLower(airbox_json.Feeds[i].Device_id)) {\n\t\t\t\t\t\t\tval, err:=client.Get(airbox_json.Feeds[i].Device_id).Result()\n\t\t\t\t\t\t\tif err!=nil{\n\t\t\t\t\t\t\t\tclient.Set(airbox_json.Feeds[i].Device_id,userID,0)\n\t\t\t\t\t\t\t\ttxtmessage=\"訂閱成功!\"\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tstringSlice:=strings.Split(val,\",\")\n\t\t\t\t\t\t\tif stringInSlice(userID,stringSlice){\n\t\t\t\t\t\t\t\ttxtmessage=\"您已訂閱過此ID!\"\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t} else{\n\t\t\t\t\t\t\t\tval=val+\",\"+userID\n\t\t\t\t\t\t\t\tclient.Set(airbox_json.Feeds[i].Device_id,val,0)\n\t\t\t\t\t\t\t\ttxtmessage=\"訂閱成功!\"\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else{\n\t\t\t\t\tfor i:=0; i<len(airbox_json.Feeds); i++ {\n\t\t\t\t\t\tif strings.Contains(inText,strings.ToLower(airbox_json.Feeds[i].Device_id)) {\n\t\t\t\t\t\t\ttxtmessage=\"Device_id: \"+airbox_json.Feeds[i].Device_id+\"\\n\"\n\t\t\t\t\t\t\ttxtmessage=txtmessage+\"Site Name: \"+airbox_json.Feeds[i].SiteName+\"\\n\"\n\t\t\t\t\t\t\ttxtmessage=txtmessage+\"Location: (\"+strconv.FormatFloat(float64(airbox_json.Feeds[i].Gps_lon),'f',3,64)+\",\"+strconv.FormatFloat(float64(airbox_json.Feeds[i].Gps_lat),'f',3,64)+\")\"+\"\\n\"\n\t\t\t\t\t\t\ttxtmessage=txtmessage+\"Timestamp: \"+airbox_json.Feeds[i].Timestamp+\"\\n\"\n\t\t\t\t\t\t\ttxtmessage=txtmessage+\"PM2.5: \"+strconv.FormatFloat(float64(airbox_json.Feeds[i].S_d0),'f',0,64)+\"\\n\"\n\t\t\t\t\t\t\ttxtmessage=txtmessage+\"Humidity: \"+strconv.FormatFloat(float64(airbox_json.Feeds[i].S_h0),'f',0,64)+\"\\n\"\n\t\t\t\t\t\t\ttxtmessage=txtmessage+\"Temperature: \"+strconv.FormatFloat(float64(airbox_json.Feeds[i].S_t0),'f',0,64)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif len(txtmessage)==0{\n\t\t\t\t\ttxtmessage=\"Sorry! No this device ID, please check again.\"\n\t\t\t\t}\n\t\t\t\tif _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(txtmessage)).Do(); err != nil {\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc stringInSlice(a string, list []string) bool {\n    for _, b := range list {\n        if b == a {\n            return true\n        }\n    }\n    return false\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2020 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"cloud.google.com\/go\/compute\/metadata\"\n)\n\nvar (\n\tcomputeZone string\n)\n\nfunc main() {\n\tif !metadata.OnGCE() {\n\t\tlog.Println(\"warn: not running with metadata service present\")\n\t} else {\n\t\tzone, err := metadata.Zone()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to get compute zone: %+v\", err)\n\t\t}\n\t\tcomputeZone = zone\n\t\tlog.Printf(\"info: determined zone: %q\", zone)\n\t}\n\n\tport := \"8080\"\n\tif v := os.Getenv(\"PORT\"); v != \"\" {\n\t\tport = v\n\t}\n\tlog.Println(\"starting to listen on port \" + port)\n\thttp.HandleFunc(\"\/\", handle)\n\terr := http.ListenAndServe(\":\"+port, nil)\n\tlog.Fatal(err)\n}\n\nfunc handle(w http.ResponseWriter, r *http.Request) {\n\tvar srcIP string\n\tif ipHeader := r.Header.Get(\"X-Forwarded-For\"); ipHeader != \"\" {\n\t\tsrcIP = ipHeader\n\t} else {\n\t\tsrcIP = r.RemoteAddr\n\t}\n\tlog.Printf(\"received request method=%s path=%q src=%q\", r.Method, r.URL.Path, srcIP)\n\n\tif computeZone == \"\" {\n\t\tfmt.Fprintf(w, `<!DOCTYPE html>\n\t\t\t\t<h1>Cannot determine the compute zone :(<\/h1>\n\t\t\t\t<p>Is it running on a Google Compute Engine or Cloud Run?<\/p>`)\n\t\treturn\n\t}\n\n\tregion := computeZone[:strings.LastIndex(computeZone, \"-\")]\n\tdc, ok := datacenters[region]\n\n\tfmt.Fprintf(w, `<!DOCTYPE html>\n\t<h4>Welcome from Google Cloud datacenters at:<h4>`)\n\tif !ok {\n\t\t\/\/ cannot determine datacenter from zone, just use zone name\n\t\tfmt.Fprintf(w, `<h1>%s!<\/h1>`, computeZone)\n\n\t} else {\n\t\tfmt.Fprintf(w, `<h1>%s<\/h1>\n\t\t<h3>You are now connected to &quot;%s&quot;<\/h3>\n\t\t<img src=\"%s\" style=\"width: 480px; height: auto; border: 1px solid #444;\"\/>`, dc.location, computeZone, dc.flagURL)\n\t}\n\tfmt.Fprintf(w, `\n\t\t<p>\n\t\t\tBased on where you visit from, Google Cloud Load Balancer routes your request\n\t\t\tto the closest compute region the application is deployed in.\n\t\t<\/p>\n\t\t<p>\n\t\t\t<small><a href=\"https:\/\/github.com\/ahmetb\/zone-printer\">[source code]<\/a><\/small>\n\t\t<\/p>`)\n}\n\nvar (\n\t\/\/ Datacenter list is adopted from https:\/\/cloud.google.com\/compute\/docs\/regions-zones\/\n\t\/\/ also Cloud Run regions are at https:\/\/cloud.google.com\/run\/docs\/locations\n\tdatacenters = map[string]struct {\n\t\tlocation string\n\t\tflagURL  string \/\/ flag images must be public domain\n\t}{\n\t\t\"northamerica-northeast1\": {\n\t\t\tlocation: \"Montréal, Canada\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/d\/d9\/Flag_of_Canada_%28Pantone%29.svg\",\n\t\t},\n\t\t\"us-central1\": {\n\t\t\tlocation: \"Council Bluffs, Iowa, USA\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/a\/a4\/Flag_of_the_United_States.svg\",\n\t\t},\n\t\t\"us-west1\": {\n\t\t\tlocation: \"The Dalles, Oregon, USA\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/a\/a4\/Flag_of_the_United_States.svg\",\n\t\t},\n\t\t\"us-east4\": {\n\t\t\tlocation: \"Ashburn, Virginia, USA\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/a\/a4\/Flag_of_the_United_States.svg\",\n\t\t},\n\t\t\"us-east1\": {\n\t\t\tlocation: \"Moncks Corner, South Carolina, USA\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/a\/a4\/Flag_of_the_United_States.svg\",\n\t\t},\n\t\t\"southamerica-east1\": {\n\t\t\tlocation: \"São Paulo, Brazil\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/0\/05\/Flag_of_Brazil.svg\",\n\t\t},\n\t\t\"europe-north1\": {\n\t\t\tlocation: \"Hamina, Finland\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/b\/bc\/Flag_of_Finland.svg\",\n\t\t},\n\t\t\"europe-west1\": {\n\t\t\tlocation: \"St. Ghislain, Belgium\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/6\/65\/Flag_of_Belgium.svg\",\n\t\t},\n\t\t\"europe-west2\": {\n\t\t\tlocation: \"London, U.K.\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/a\/ae\/Flag_of_the_United_Kingdom.svg\",\n\t\t},\n\t\t\"europe-west3\": {\n\t\t\tlocation: \"Frankfurt, Germany\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/b\/ba\/Flag_of_Germany.svg\",\n\t\t},\n\t\t\"europe-west4\": {\n\t\t\tlocation: \"Eemshaven, Netherlands\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/2\/20\/Flag_of_the_Netherlands.svg\",\n\t\t},\n\t\t\"asia-south1\": {\n\t\t\tlocation: \"Mumbai, India\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/4\/41\/Flag_of_India.svg\",\n\t\t},\n\t\t\"asia-southeast1\": {\n\t\t\tlocation: \"Jurong West, Singapore\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/4\/48\/Flag_of_Singapore.svg\",\n\t\t},\n\t\t\"asia-east1\": {\n\t\t\tlocation: \"Changhua County, Taiwan\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/7\/72\/Flag_of_the_Republic_of_China.svg\",\n\t\t},\n\t\t\"asia-northeast1\": {\n\t\t\tlocation: \"Tokyo, Japan\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/9\/9e\/Flag_of_Japan.svg\",\n\t\t},\n\t\t\"australia-southeast1\": {\n\t\t\tlocation: \"Sydney, Australia\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/b\/b9\/Flag_of_Australia.svg\",\n\t\t},\n\t}\n)\n<commit_msg>add asia-northeast2<commit_after>\/\/ Copyright 2020 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"cloud.google.com\/go\/compute\/metadata\"\n)\n\nvar (\n\tcomputeZone string\n)\n\nfunc main() {\n\tif !metadata.OnGCE() {\n\t\tlog.Println(\"warn: not running with metadata service present\")\n\t} else {\n\t\tzone, err := metadata.Zone()\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"failed to get compute zone: %+v\", err)\n\t\t}\n\t\tcomputeZone = zone\n\t\tlog.Printf(\"info: determined zone: %q\", zone)\n\t}\n\n\tport := \"8080\"\n\tif v := os.Getenv(\"PORT\"); v != \"\" {\n\t\tport = v\n\t}\n\tlog.Println(\"starting to listen on port \" + port)\n\thttp.HandleFunc(\"\/\", handle)\n\terr := http.ListenAndServe(\":\"+port, nil)\n\tlog.Fatal(err)\n}\n\nfunc handle(w http.ResponseWriter, r *http.Request) {\n\tvar srcIP string\n\tif ipHeader := r.Header.Get(\"X-Forwarded-For\"); ipHeader != \"\" {\n\t\tsrcIP = ipHeader\n\t} else {\n\t\tsrcIP = r.RemoteAddr\n\t}\n\tlog.Printf(\"received request method=%s path=%q src=%q\", r.Method, r.URL.Path, srcIP)\n\n\tif computeZone == \"\" {\n\t\tfmt.Fprintf(w, `<!DOCTYPE html>\n\t\t\t\t<h1>Cannot determine the compute zone :(<\/h1>\n\t\t\t\t<p>Is it running on a Google Compute Engine or Cloud Run?<\/p>`)\n\t\treturn\n\t}\n\n\tregion := computeZone[:strings.LastIndex(computeZone, \"-\")]\n\tdc, ok := datacenters[region]\n\n\tfmt.Fprintf(w, `<!DOCTYPE html>\n\t<h4>Welcome from Google Cloud datacenters at:<h4>`)\n\tif !ok {\n\t\t\/\/ cannot determine datacenter from zone, just use zone name\n\t\tfmt.Fprintf(w, `<h1>%s!<\/h1>`, computeZone)\n\n\t} else {\n\t\tfmt.Fprintf(w, `<h1>%s<\/h1>\n\t\t<h3>You are now connected to &quot;%s&quot;<\/h3>\n\t\t<img src=\"%s\" style=\"width: 480px; height: auto; border: 1px solid #444;\"\/>`, dc.location, computeZone, dc.flagURL)\n\t}\n\tfmt.Fprintf(w, `\n\t\t<p>\n\t\t\tBased on where you visit from, Google Cloud Load Balancer routes your request\n\t\t\tto the closest compute region the application is deployed in.\n\t\t<\/p>\n\t\t<p>\n\t\t\t<small><a href=\"https:\/\/github.com\/ahmetb\/zone-printer\">[source code]<\/a><\/small>\n\t\t<\/p>`)\n}\n\nvar (\n\t\/\/ Datacenter list is adopted from https:\/\/cloud.google.com\/compute\/docs\/regions-zones\/\n\t\/\/ also Cloud Run regions are at https:\/\/cloud.google.com\/run\/docs\/locations\n\tdatacenters = map[string]struct {\n\t\tlocation string\n\t\tflagURL  string \/\/ flag images must be public domain\n\t}{\n\t\t\"northamerica-northeast1\": {\n\t\t\tlocation: \"Montréal, Canada\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/d\/d9\/Flag_of_Canada_%28Pantone%29.svg\",\n\t\t},\n\t\t\"us-central1\": {\n\t\t\tlocation: \"Council Bluffs, Iowa, USA\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/a\/a4\/Flag_of_the_United_States.svg\",\n\t\t},\n\t\t\"us-west1\": {\n\t\t\tlocation: \"The Dalles, Oregon, USA\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/a\/a4\/Flag_of_the_United_States.svg\",\n\t\t},\n\t\t\"us-east4\": {\n\t\t\tlocation: \"Ashburn, Virginia, USA\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/a\/a4\/Flag_of_the_United_States.svg\",\n\t\t},\n\t\t\"us-east1\": {\n\t\t\tlocation: \"Moncks Corner, South Carolina, USA\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/a\/a4\/Flag_of_the_United_States.svg\",\n\t\t},\n\t\t\"southamerica-east1\": {\n\t\t\tlocation: \"São Paulo, Brazil\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/0\/05\/Flag_of_Brazil.svg\",\n\t\t},\n\t\t\"europe-north1\": {\n\t\t\tlocation: \"Hamina, Finland\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/b\/bc\/Flag_of_Finland.svg\",\n\t\t},\n\t\t\"europe-west1\": {\n\t\t\tlocation: \"St. Ghislain, Belgium\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/6\/65\/Flag_of_Belgium.svg\",\n\t\t},\n\t\t\"europe-west2\": {\n\t\t\tlocation: \"London, U.K.\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/a\/ae\/Flag_of_the_United_Kingdom.svg\",\n\t\t},\n\t\t\"europe-west3\": {\n\t\t\tlocation: \"Frankfurt, Germany\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/b\/ba\/Flag_of_Germany.svg\",\n\t\t},\n\t\t\"europe-west4\": {\n\t\t\tlocation: \"Eemshaven, Netherlands\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/2\/20\/Flag_of_the_Netherlands.svg\",\n\t\t},\n\t\t\"asia-south1\": {\n\t\t\tlocation: \"Mumbai, India\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/4\/41\/Flag_of_India.svg\",\n\t\t},\n\t\t\"asia-southeast1\": {\n\t\t\tlocation: \"Jurong West, Singapore\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/4\/48\/Flag_of_Singapore.svg\",\n\t\t},\n\t\t\"asia-east1\": {\n\t\t\tlocation: \"Changhua County, Taiwan\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/commons\/7\/72\/Flag_of_the_Republic_of_China.svg\",\n\t\t},\n\t\t\"asia-northeast1\": {\n\t\t\tlocation: \"Tokyo, Japan\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/9\/9e\/Flag_of_Japan.svg\",\n\t\t},\n\t\t\"asia-northeast2\": {\n\t\t\tlocation: \"Osaka, Japan\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/9\/9e\/Flag_of_Japan.svg\",\n\t\t},\n\t\t\"australia-southeast1\": {\n\t\t\tlocation: \"Sydney, Australia\",\n\t\t\tflagURL:  \"https:\/\/upload.wikimedia.org\/wikipedia\/en\/b\/b9\/Flag_of_Australia.svg\",\n\t\t},\n\t}\n)\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"os\"\n\n\t\"github.com\/rliebz\/tusk\/appcli\"\n\t\"github.com\/rliebz\/tusk\/ui\"\n)\n\nfunc main() {\n\tmeta, err := appcli.GetConfigMetadata(os.Args)\n\tif err != nil {\n\t\tui.Error(err)\n\t\tappcli.ShowDefaultHelp()\n\t\treturn\n\t}\n\n\tui.Quiet = meta.Quiet\n\tui.Verbose = meta.Verbose\n\tif err = os.Chdir(meta.Directory); err != nil {\n\t\tui.Error(err)\n\t\treturn\n\t}\n\n\tif meta.RunVersion {\n\t\tui.Print(\"0.0.0\")\n\t\tos.Exit(0)\n\t}\n\n\tapp, err := appcli.NewApp(meta.CfgText)\n\tif err != nil {\n\t\tui.Error(err)\n\t\tappcli.ShowDefaultHelp()\n\t\treturn\n\t}\n\n\tif err := app.Run(os.Args); err != nil {\n\t\t\/\/ TODO: Determine when this should print\n\t\tui.Error(err)\n\t}\n}\n<commit_msg>Preserve original exit code for exec failures<commit_after>package main\n\nimport (\n\t\"os\"\n\t\"os\/exec\"\n\t\"syscall\"\n\n\t\"github.com\/rliebz\/tusk\/appcli\"\n\t\"github.com\/rliebz\/tusk\/ui\"\n)\n\nfunc main() {\n\tmeta, err := appcli.GetConfigMetadata(os.Args)\n\tif err != nil {\n\t\tui.Error(err)\n\t\tappcli.ShowDefaultHelp()\n\t\treturn\n\t}\n\n\tui.Quiet = meta.Quiet\n\tui.Verbose = meta.Verbose\n\tif err = os.Chdir(meta.Directory); err != nil {\n\t\tui.Error(err)\n\t\treturn\n\t}\n\n\tif meta.RunVersion {\n\t\tui.Print(\"0.0.0\")\n\t\tos.Exit(0)\n\t}\n\n\tapp, err := appcli.NewApp(meta.CfgText)\n\tif err != nil {\n\t\tui.Error(err)\n\t\tappcli.ShowDefaultHelp()\n\t\treturn\n\t}\n\n\tif err := app.Run(os.Args); err != nil {\n\t\tif exitErr, ok := err.(*exec.ExitError); ok {\n\t\t\tws := exitErr.Sys().(syscall.WaitStatus)\n\t\t\tos.Exit(ws.ExitStatus())\n\t\t} else {\n\t\t\tui.Error(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main \/\/ import \"github.com\/mopsalarm\/pr0gramm-meta-rest\"\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/bobziuchkovski\/writ\"\n\n\t\"github.com\/gorilla\/handlers\"\n\t\"github.com\/gorilla\/mux\"\n\t\"net\/http\"\n\n\t\"database\/sql\"\n\t_ \"github.com\/lib\/pq\"\n\n\t\"github.com\/rcrowley\/go-metrics\"\n\t\"github.com\/vistarmedia\/go-datadog\"\n\n\t\"github.com\/mopsalarm\/pr0gramm-meta-rest\/app\"\n)\n\nconst SAMPLE_PERIOD = time.Minute\n\ntype Args struct {\n\tHelpFlag bool   `flag:\"help\" description:\"Display this help message and exit\"`\n\tPort     int    `option:\"p, port\" default:\"8080\" description:\"The port to open the rest service on\"`\n\tPostgres string `option:\"postgres\" default:\"host=localhost user=postgres password=password sslmode=disable\" description:\"Postgres DSN for database connection\"`\n\tDatadog  string `option:\"datadog\" description:\"Datadog api key for reporting\"`\n}\n\ntype Route struct {\n\tname    string\n\turl     string\n\thandler app.HandleFunc\n}\n\nfunc main() {\n\tvar err error\n\targs := &Args{}\n\tcmd := writ.New(\"webapp\", args)\n\n\t\/\/ Use cmd.Decode(os.Args[1:]) in a real application\n\t_, _, err = cmd.Decode(os.Args[1:])\n\tif err != nil || args.HelpFlag {\n\t\tcmd.ExitHelp(err)\n\t}\n\n\t\/\/ open database connection\n\tdb, err := sql.Open(\"postgres\", args.Postgres)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdb.SetMaxOpenConns(4)\n\n\t\/\/ check if it is valid\n\tif err = db.Ping(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ get info about the runtime every few seconds\n\tmetrics.RegisterRuntimeMemStats(metrics.DefaultRegistry)\n\tgo metrics.CaptureRuntimeMemStats(metrics.DefaultRegistry, SAMPLE_PERIOD)\n\n\tif len(args.Datadog) > 0 {\n\t\thost, _ := os.Hostname()\n\n\t\tfmt.Printf(\"Starting datadog reporter on host %s\\n\", host)\n\t\tgo datadog.New(host, args.Datadog).DefaultReporter().Start(SAMPLE_PERIOD)\n\t}\n\n\trouter := mux.NewRouter().StrictSlash(true)\n\n\troutes := []Route{\n\t\tRoute{\"user\", \"\/user\/{user}\", handleUser},\n\t\tRoute{\"user-suggest\", \"\/user\/suggest\/{prefix}\", handleUserSuggest},\n\t}\n\n\tfor _, route := range routes {\n\t\ttimer := metrics.NewRegisteredTimer(\"pr0gramm.meta.webapp.request.\"+route.name, nil)\n\t\trouter.Handle(route.url, app.TimeHandler{timer, app.Handler{db, route.handler}})\n\t}\n\n\tlog.Fatal(http.ListenAndServe(fmt.Sprintf(\":%d\", args.Port),\n\t\thandlers.RecoveryHandler()(\n\t\t\thandlers.LoggingHandler(os.Stdout,\n\t\t\t\thandlers.CORS()(router)))))\n}\n<commit_msg>Limit database connections<commit_after>package main \/\/ import \"github.com\/mopsalarm\/pr0gramm-meta-rest\"\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/bobziuchkovski\/writ\"\n\n\t\"github.com\/gorilla\/handlers\"\n\t\"github.com\/gorilla\/mux\"\n\t\"net\/http\"\n\n\t\"database\/sql\"\n\t_ \"github.com\/lib\/pq\"\n\n\t\"github.com\/rcrowley\/go-metrics\"\n\t\"github.com\/vistarmedia\/go-datadog\"\n\n\t\"github.com\/mopsalarm\/pr0gramm-meta-rest\/app\"\n)\n\nconst SAMPLE_PERIOD = time.Minute\n\ntype Args struct {\n\tHelpFlag bool   `flag:\"help\" description:\"Display this help message and exit\"`\n\tPort     int    `option:\"p, port\" default:\"8080\" description:\"The port to open the rest service on\"`\n\tPostgres string `option:\"postgres\" default:\"host=localhost user=postgres password=password sslmode=disable\" description:\"Postgres DSN for database connection\"`\n\tDatadog  string `option:\"datadog\" description:\"Datadog api key for reporting\"`\n}\n\ntype Route struct {\n\tname    string\n\turl     string\n\thandler app.HandleFunc\n}\n\nfunc main() {\n\tvar err error\n\targs := &Args{}\n\tcmd := writ.New(\"webapp\", args)\n\n\t\/\/ Use cmd.Decode(os.Args[1:]) in a real application\n\t_, _, err = cmd.Decode(os.Args[1:])\n\tif err != nil || args.HelpFlag {\n\t\tcmd.ExitHelp(err)\n\t}\n\n\t\/\/ open database connection\n\tdb, err := sql.Open(\"postgres\", args.Postgres)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdefer db.Close()\n\tdb.SetMaxOpenConns(2)\n\tdb.SetMaxIdleConns(1)\n\tdb.SetConnMaxLifetime(5*time.Minute)\n\n\t\/\/ check if it is valid\n\tif err = db.Ping(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ get info about the runtime every few seconds\n\tmetrics.RegisterRuntimeMemStats(metrics.DefaultRegistry)\n\tgo metrics.CaptureRuntimeMemStats(metrics.DefaultRegistry, SAMPLE_PERIOD)\n\n\tif len(args.Datadog) > 0 {\n\t\thost, _ := os.Hostname()\n\n\t\tfmt.Printf(\"Starting datadog reporter on host %s\\n\", host)\n\t\tgo datadog.New(host, args.Datadog).DefaultReporter().Start(SAMPLE_PERIOD)\n\t}\n\n\trouter := mux.NewRouter().StrictSlash(true)\n\n\troutes := []Route{\n\t\tRoute{\"user\", \"\/user\/{user}\", handleUser},\n\t\tRoute{\"user-suggest\", \"\/user\/suggest\/{prefix}\", handleUserSuggest},\n\t}\n\n\tfor _, route := range routes {\n\t\ttimer := metrics.NewRegisteredTimer(\"pr0gramm.meta.webapp.request.\"+route.name, nil)\n\t\trouter.Handle(route.url, app.TimeHandler{timer, app.Handler{db, route.handler}})\n\t}\n\n\tlog.Fatal(http.ListenAndServe(fmt.Sprintf(\":%d\", args.Port),\n\t\thandlers.RecoveryHandler()(\n\t\t\thandlers.LoggingHandler(os.Stdout,\n\t\t\t\thandlers.CORS()(router)))))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/yursan9\/tulis\/pkg\/post\"\n)\n\nfunc main() {\n\tp := post.GetPosts(\"posts\")\n\tfmt.Println(p)\n}\n<commit_msg>Change main for basic use<commit_after>package main\n\nimport (\n\t\"context\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"time\"\n\n\t\"github.com\/yursan9\/tulis\/pkg\/server\"\n)\n\nfunc main() {\n\tstop := make(chan os.Signal)\n\tsignal.Notify(stop, os.Interrupt)\n\topt := &server.Options{}\n\n\tapp := server.New(opt)\n\tgo func() {\n\t\tlog.Println(\"Listening to port http:\/\/127.0.0.1\" + app.Addr)\n\t\tlog.Fatal(app.ListenAndServe())\n\t}()\n\t<-stop\n\n\tctx, _ := context.WithTimeout(context.Background(), 5*time.Second)\n\tlog.Println(\"Shutting down the server...\")\n\tapp.Shutdown(ctx)\n\tlog.Println(\"Server stopped.\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"expvar\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"net\/url\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"code.google.com\/p\/gogoprotobuf\/proto\"\n\tpb \"github.com\/dgryski\/carbonzipper\/carbonzipperpb\"\n\n\t\"github.com\/bradfitz\/gomemcache\/memcache\"\n\t\"github.com\/peterbourgon\/g2g\"\n)\n\ntype zipper string\n\nvar Zipper zipper\n\nvar Metrics = struct {\n\tRequests         *expvar.Int\n\tRequestCacheHits *expvar.Int\n\n\tFindRequests  *expvar.Int\n\tFindCacheHits *expvar.Int\n\n\tRenderRequests *expvar.Int\n}{\n\tRequests:         expvar.NewInt(\"requests\"),\n\tRequestCacheHits: expvar.NewInt(\"request_cache_hits\"),\n\n\tFindRequests:  expvar.NewInt(\"find_requests\"),\n\tFindCacheHits: expvar.NewInt(\"find_cache_hits\"),\n\n\tRenderRequests: expvar.NewInt(\"render_requests\"),\n}\n\nvar queryCache bytesCache\nvar findCache bytesCache\n\nvar timeFormats = []string{\"15:04 20060102\", \"20060102\", \"01\/02\/06\"}\n\n\/\/ dateParamToEpoch turns a passed string parameter into an epoch we can send to the Zipper\nfunc dateParamToEpoch(s string, d int64) int32 {\n\n\tif s == \"\" {\n\t\t\/\/ return the default if nothing was passed\n\t\treturn int32(d)\n\t}\n\n\t\/\/ relative timestamp\n\tif s[0] == '-' {\n\n\t\toffset, err := intervalString(s[1:])\n\t\tif err != nil {\n\t\t\treturn int32(d)\n\t\t}\n\n\t\treturn int32(timeNow().Add(-time.Duration(offset) * time.Second).Unix())\n\t}\n\n\tif s == \"now\" {\n\t\treturn int32(timeNow().Unix())\n\t}\n\n\tsint, err := strconv.Atoi(s)\n\tif err == nil && len(s) > 8 {\n\t\treturn int32(sint) \/\/ We got a timestamp so returning it\n\t}\n\n\tif strings.Contains(s, \"_\") {\n\t\ts = strings.Replace(s, \"_\", \" \", 1) \/\/ Go can't parse _ in date strings\n\t}\n\n\tfor _, format := range timeFormats {\n\t\tt, err := time.Parse(format, s)\n\t\tif err == nil {\n\t\t\treturn int32(t.Unix())\n\t\t}\n\t}\n\treturn int32(d)\n}\n\nfunc intervalString(s string) (int32, error) {\n\n\t\/\/ TODO(dgryski): add defaultSign param for use if there is no +\/- sign provided by string\n\n\tvar j int\n\n\tfor j < len(s) && s[j] >= '0' && s[j] <= '9' {\n\t\tj++\n\t}\n\toffsetStr, unitStr := s[:j], s[j:]\n\n\tvar units int\n\tswitch unitStr {\n\tcase \"s\", \"sec\", \"secs\", \"second\", \"seconds\":\n\t\tunits = 1\n\tcase \"min\", \"minute\", \"minutes\":\n\t\tunits = 60\n\tcase \"h\", \"hour\", \"hours\":\n\t\tunits = 60 * 60\n\tcase \"d\", \"day\", \"days\":\n\t\tunits = 24 * 60 * 60\n\tcase \"w\", \"week\", \"weeks\":\n\t\tunits = 7 * 24 * 60 * 60\n\tcase \"mon\", \"month\", \"months\":\n\t\tunits = 30 * 24 * 60 * 60\n\tcase \"y\", \"year\", \"years\":\n\t\tunits = 365 * 24 * 60 * 60\n\tdefault:\n\t\treturn 0, errors.New(\"unknown time units\")\n\t}\n\n\toffset, err := strconv.Atoi(offsetStr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn int32(offset * units), nil\n}\n\n\/\/ FIXME(dgryski): extract the http.Get + unproto code into its own function\n\nfunc (z zipper) Find(metric string) (pb.GlobResponse, error) {\n\n\tu, _ := url.Parse(string(z) + \"\/metrics\/find\/\")\n\n\tu.RawQuery = url.Values{\n\t\t\"query\":  []string{metric},\n\t\t\"format\": []string{\"protobuf\"},\n\t}.Encode()\n\n\tresp, err := http.Get(u.String())\n\tif err != nil {\n\t\tlog.Printf(\"Find: http.Get: %+v\\n\", err)\n\t\treturn pb.GlobResponse{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Find: ioutil.ReadAll: %+v\\n\", err)\n\t\treturn pb.GlobResponse{}, err\n\t}\n\n\tvar pbresp pb.GlobResponse\n\n\terr = proto.Unmarshal(body, &pbresp)\n\tif err != nil {\n\t\tlog.Printf(\"Find: proto.Unmarshal: %+v\\n\", err)\n\t\treturn pb.GlobResponse{}, err\n\t}\n\n\treturn pbresp, nil\n}\n\nfunc (z zipper) Render(metric string, from, until int32) (pb.FetchResponse, error) {\n\n\tu, _ := url.Parse(string(z) + \"\/render\/\")\n\n\tu.RawQuery = url.Values{\n\t\t\"target\": []string{metric},\n\t\t\"format\": []string{\"protobuf\"},\n\t\t\"from\":   []string{strconv.Itoa(int(from))},\n\t\t\"until\":  []string{strconv.Itoa(int(until))},\n\t}.Encode()\n\n\tresp, err := http.Get(u.String())\n\tif err != nil {\n\t\tlog.Printf(\"Render: http.Get: %s: %+v\\n\", metric, err)\n\t\treturn pb.FetchResponse{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Render: ioutil.ReadAll: %s: %+v\\n\", metric, err)\n\t\treturn pb.FetchResponse{}, err\n\t}\n\n\tvar pbresp pb.FetchResponse\n\n\terr = proto.Unmarshal(body, &pbresp)\n\tif err != nil {\n\t\tlog.Printf(\"Render: proto.Unmarshal: %s: %+v\\n\", metric, err)\n\t\treturn pb.FetchResponse{}, err\n\t}\n\n\treturn pbresp, nil\n}\n\ntype limiter chan struct{}\n\nfunc (l limiter) enter() { l <- struct{}{} }\nfunc (l limiter) leave() { <-l }\n\nvar Limiter limiter\n\n\/\/ for testing\nvar timeNow = time.Now\n\ntype graphitePoint struct {\n\tvalue float64\n\tt     int32\n}\n\nfunc (g graphitePoint) MarshalJSON() ([]byte, error) {\n\t\/\/ TODO(dgryski): fmt.Sprintf() is slow, use strconv.Append{Float,Int}\n\t\/\/ TODO(dgryski): MarshalJSON call should be on jsonResponse to reduce overhead\n\tif math.IsNaN(g.value) {\n\t\treturn []byte(fmt.Sprintf(\"[null,%d]\", g.t)), nil\n\t}\n\treturn []byte(fmt.Sprintf(\"[%g,%d]\", g.value, g.t)), nil\n}\n\ntype jsonResponse struct {\n\tTarget     string          `json:\"target\"`\n\tDatapoints []graphitePoint `json:\"datapoints\"`\n}\n\nfunc renderHandler(w http.ResponseWriter, r *http.Request) {\n\n\tMetrics.Requests.Add(1)\n\n\terr := r.ParseForm()\n\tif err != nil {\n\t\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\t\treturn\n\t}\n\n\ttargets := r.Form[\"target\"]\n\tfrom := r.FormValue(\"from\")\n\tuntil := r.FormValue(\"until\")\n\tuseCache := r.FormValue(\"noCache\") == \"\"\n\n\t\/\/ make sure the cache key doesn't say noCache, because it will never hit\n\tr.Form.Del(\"noCache\")\n\n\tcacheKey := r.Form.Encode()\n\n\tif response, ok := queryCache.get(cacheKey); useCache && ok {\n\t\tMetrics.RequestCacheHits.Add(1)\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.Write(response)\n\t\treturn\n\t}\n\n\t\/\/ normalize from and until values\n\t\/\/ BUG(dgryski): doesn't handle timezones the same as graphite-web\n\tfrom32 := dateParamToEpoch(from, timeNow().Add(-24*time.Hour).Unix())\n\tuntil32 := dateParamToEpoch(until, timeNow().Unix())\n\n\tvar results []*pb.FetchResponse\n\tmetricMap := make(map[metricRequest][]*pb.FetchResponse)\n\n\tfor _, target := range targets {\n\n\t\texp, e, err := parseExpr(target)\n\t\tif err != nil || e != \"\" {\n\t\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tfor _, m := range exp.metrics() {\n\n\t\t\tmfetch := m\n\t\t\tmfetch.from += from32\n\t\t\tmfetch.until += until32\n\n\t\t\tif _, ok := metricMap[mfetch]; ok {\n\t\t\t\t\/\/ already fetched this metric for this request\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar glob pb.GlobResponse\n\t\t\tvar haveCacheData bool\n\n\t\t\tif response, ok := findCache.get(m.metric); useCache && ok {\n\t\t\t\tMetrics.FindCacheHits.Add(1)\n\t\t\t\terr := proto.Unmarshal(response, &glob)\n\t\t\t\thaveCacheData = err == nil\n\t\t\t}\n\n\t\t\tif !haveCacheData {\n\t\t\t\tvar err error\n\t\t\t\tMetrics.FindRequests.Add(1)\n\t\t\t\tglob, err = Zipper.Find(m.metric)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tb, err := proto.Marshal(&glob)\n\t\t\t\tif err == nil {\n\t\t\t\t\tfindCache.set(m.metric, b)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ For each metric returned in the Find response, query Render\n\t\t\t\/\/ This is a conscious decision to *not* cache render data\n\t\t\trch := make(chan *pb.FetchResponse, len(glob.GetMatches()))\n\t\t\tleaves := 0\n\t\t\tfor _, m := range glob.GetMatches() {\n\t\t\t\tif !m.GetIsLeaf() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tMetrics.RenderRequests.Add(1)\n\t\t\t\tleaves++\n\t\t\t\tLimiter.enter()\n\t\t\t\tgo func(m *pb.GlobMatch, from, until int32) {\n\t\t\t\t\tvar rptr *pb.FetchResponse\n\t\t\t\t\tr, err := Zipper.Render(m.GetPath(), from, until)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\trptr = &r\n\t\t\t\t\t}\n\t\t\t\t\trch <- rptr\n\t\t\t\t\tLimiter.leave()\n\t\t\t\t}(m, mfetch.from, mfetch.until)\n\t\t\t}\n\n\t\t\tfor i := 0; i < leaves; i++ {\n\t\t\t\tr := <-rch\n\t\t\t\tif r != nil {\n\t\t\t\t\tmetricMap[mfetch] = append(metricMap[mfetch], r)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\texprs := evalExpr(exp, from32, until32, metricMap)\n\t\tresults = append(results, exprs...)\n\t}\n\n\tvar jresults []jsonResponse\n\n\tfor _, r := range results {\n\t\tif r == nil {\n\t\t\tlog.Println(\"skipping nil result\")\n\t\t}\n\t\tdatapoints := make([]graphitePoint, 0, len(r.Values))\n\t\tt := *r.StartTime\n\t\tfor i, v := range r.Values {\n\t\t\tif r.IsAbsent[i] {\n\t\t\t\tv = math.NaN()\n\t\t\t}\n\t\t\tdatapoints = append(datapoints, graphitePoint{value: v, t: t})\n\t\t\tt += *r.StepTime\n\t\t}\n\t\tjresults = append(jresults, jsonResponse{Target: r.GetName(), Datapoints: datapoints})\n\t}\n\n\tjout, err := json.Marshal(jresults)\n\tif err != nil {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tqueryCache.set(cacheKey, jout)\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(jout)\n}\n\nfunc lbcheckHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Ok\\n\")\n}\n\nfunc main() {\n\n\tz := flag.String(\"z\", \"\", \"zipper\")\n\tport := flag.Int(\"p\", 8080, \"port\")\n\tl := flag.Int(\"l\", 20, \"concurrency limit\")\n\tmc := flag.String(\"mc\", \"\", \"comma separated memcached server list\")\n\tcpus := flag.Int(\"cpus\", 0, \"number of CPUs to use\")\n\n\tflag.Parse()\n\n\tif p := os.Getenv(\"PORT\"); p != \"\" {\n\t\t*port, _ = strconv.Atoi(p)\n\t}\n\n\tLimiter = make(chan struct{}, *l)\n\n\tif *z == \"\" {\n\t\tlog.Fatal(\"no zipper provided\")\n\t}\n\n\tif _, err := url.Parse(*z); err != nil {\n\t\tlog.Fatal(\"unable to parze zipper:\", err)\n\t}\n\n\tlog.Println(\"using zipper\", *z)\n\n\tif *mc != \"\" {\n\t\tservers := strings.Split(*mc, \",\")\n\t\tlog.Println(\"using memcache servers:\", servers)\n\t\tqueryCache = &memcachedCache{client: memcache.New(servers...)}\n\t\tfindCache = &memcachedCache{client: memcache.New(servers...)}\n\t} else {\n\t\tqueryCache = &expireCache{cache: make(map[string]cacheElement)}\n\t\tgo queryCache.(*expireCache).cleaner()\n\n\t\tfindCache = &expireCache{cache: make(map[string]cacheElement)}\n\t\tgo findCache.(*expireCache).cleaner()\n\t}\n\n\tZipper = zipper(*z)\n\n\tif *cpus != 0 {\n\t\tlog.Println(\"using GOMAXPROCS\", *cpus)\n\t\truntime.GOMAXPROCS(*cpus)\n\t}\n\n\tif host := os.Getenv(\"GRAPHITEHOST\") + \":\" + os.Getenv(\"GRAPHITEPORT\"); host != \":\" {\n\n\t\tlog.Println(\"Using graphite host\", host)\n\n\t\t\/\/ register our metrics with graphite\n\t\tgraphite, err := g2g.NewGraphite(host, 60*time.Second, 10*time.Second)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"unable to connect to to graphite: \", host, \":\", err)\n\t\t}\n\n\t\thostname, _ := os.Hostname()\n\t\thostname = strings.Replace(hostname, \".\", \"_\", -1)\n\n\t\tgraphite.Register(fmt.Sprintf(\"carbon.api.%s.requests\", hostname), Metrics.Requests)\n\t\tgraphite.Register(fmt.Sprintf(\"carbon.api.%s.request_cache_hits\", hostname), Metrics.RequestCacheHits)\n\n\t\tgraphite.Register(fmt.Sprintf(\"carbon.api.%s.find_requests\", hostname), Metrics.FindRequests)\n\t\tgraphite.Register(fmt.Sprintf(\"carbon.api.%s.find_cache_hits\", hostname), Metrics.FindCacheHits)\n\n\t\tgraphite.Register(fmt.Sprintf(\"carbon.api.%s.render_requests\", hostname), Metrics.RenderRequests)\n\t}\n\n\thttp.HandleFunc(\"\/render\/\", renderHandler)\n\thttp.HandleFunc(\"\/lbcheck\", lbcheckHandler)\n\n\tlog.Println(\"listening on port\", *port)\n\tlog.Fatalln(http.ListenAndServe(\":\"+strconv.Itoa(*port), nil))\n}\n<commit_msg>gofmt++<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"expvar\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"net\/url\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"code.google.com\/p\/gogoprotobuf\/proto\"\n\tpb \"github.com\/dgryski\/carbonzipper\/carbonzipperpb\"\n\n\t\"github.com\/bradfitz\/gomemcache\/memcache\"\n\t\"github.com\/peterbourgon\/g2g\"\n)\n\ntype zipper string\n\nvar Zipper zipper\n\nvar Metrics = struct {\n\tRequests         *expvar.Int\n\tRequestCacheHits *expvar.Int\n\n\tFindRequests  *expvar.Int\n\tFindCacheHits *expvar.Int\n\n\tRenderRequests *expvar.Int\n}{\n\tRequests:         expvar.NewInt(\"requests\"),\n\tRequestCacheHits: expvar.NewInt(\"request_cache_hits\"),\n\n\tFindRequests:  expvar.NewInt(\"find_requests\"),\n\tFindCacheHits: expvar.NewInt(\"find_cache_hits\"),\n\n\tRenderRequests: expvar.NewInt(\"render_requests\"),\n}\n\nvar queryCache bytesCache\nvar findCache bytesCache\n\nvar timeFormats = []string{\"15:04 20060102\", \"20060102\", \"01\/02\/06\"}\n\n\/\/ dateParamToEpoch turns a passed string parameter into an epoch we can send to the Zipper\nfunc dateParamToEpoch(s string, d int64) int32 {\n\n\tif s == \"\" {\n\t\t\/\/ return the default if nothing was passed\n\t\treturn int32(d)\n\t}\n\n\t\/\/ relative timestamp\n\tif s[0] == '-' {\n\n\t\toffset, err := intervalString(s[1:])\n\t\tif err != nil {\n\t\t\treturn int32(d)\n\t\t}\n\n\t\treturn int32(timeNow().Add(-time.Duration(offset) * time.Second).Unix())\n\t}\n\n\tif s == \"now\" {\n\t\treturn int32(timeNow().Unix())\n\t}\n\n\tsint, err := strconv.Atoi(s)\n\tif err == nil && len(s) > 8 {\n\t\treturn int32(sint) \/\/ We got a timestamp so returning it\n\t}\n\n\tif strings.Contains(s, \"_\") {\n\t\ts = strings.Replace(s, \"_\", \" \", 1) \/\/ Go can't parse _ in date strings\n\t}\n\n\tfor _, format := range timeFormats {\n\t\tt, err := time.Parse(format, s)\n\t\tif err == nil {\n\t\t\treturn int32(t.Unix())\n\t\t}\n\t}\n\treturn int32(d)\n}\n\nfunc intervalString(s string) (int32, error) {\n\n\t\/\/ TODO(dgryski): add defaultSign param for use if there is no +\/- sign provided by string\n\n\tvar j int\n\n\tfor j < len(s) && s[j] >= '0' && s[j] <= '9' {\n\t\tj++\n\t}\n\toffsetStr, unitStr := s[:j], s[j:]\n\n\tvar units int\n\tswitch unitStr {\n\tcase \"s\", \"sec\", \"secs\", \"second\", \"seconds\":\n\t\tunits = 1\n\tcase \"min\", \"minute\", \"minutes\":\n\t\tunits = 60\n\tcase \"h\", \"hour\", \"hours\":\n\t\tunits = 60 * 60\n\tcase \"d\", \"day\", \"days\":\n\t\tunits = 24 * 60 * 60\n\tcase \"w\", \"week\", \"weeks\":\n\t\tunits = 7 * 24 * 60 * 60\n\tcase \"mon\", \"month\", \"months\":\n\t\tunits = 30 * 24 * 60 * 60\n\tcase \"y\", \"year\", \"years\":\n\t\tunits = 365 * 24 * 60 * 60\n\tdefault:\n\t\treturn 0, errors.New(\"unknown time units\")\n\t}\n\n\toffset, err := strconv.Atoi(offsetStr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn int32(offset * units), nil\n}\n\n\/\/ FIXME(dgryski): extract the http.Get + unproto code into its own function\n\nfunc (z zipper) Find(metric string) (pb.GlobResponse, error) {\n\n\tu, _ := url.Parse(string(z) + \"\/metrics\/find\/\")\n\n\tu.RawQuery = url.Values{\n\t\t\"query\":  []string{metric},\n\t\t\"format\": []string{\"protobuf\"},\n\t}.Encode()\n\n\tresp, err := http.Get(u.String())\n\tif err != nil {\n\t\tlog.Printf(\"Find: http.Get: %+v\\n\", err)\n\t\treturn pb.GlobResponse{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Find: ioutil.ReadAll: %+v\\n\", err)\n\t\treturn pb.GlobResponse{}, err\n\t}\n\n\tvar pbresp pb.GlobResponse\n\n\terr = proto.Unmarshal(body, &pbresp)\n\tif err != nil {\n\t\tlog.Printf(\"Find: proto.Unmarshal: %+v\\n\", err)\n\t\treturn pb.GlobResponse{}, err\n\t}\n\n\treturn pbresp, nil\n}\n\nfunc (z zipper) Render(metric string, from, until int32) (pb.FetchResponse, error) {\n\n\tu, _ := url.Parse(string(z) + \"\/render\/\")\n\n\tu.RawQuery = url.Values{\n\t\t\"target\": []string{metric},\n\t\t\"format\": []string{\"protobuf\"},\n\t\t\"from\":   []string{strconv.Itoa(int(from))},\n\t\t\"until\":  []string{strconv.Itoa(int(until))},\n\t}.Encode()\n\n\tresp, err := http.Get(u.String())\n\tif err != nil {\n\t\tlog.Printf(\"Render: http.Get: %s: %+v\\n\", metric, err)\n\t\treturn pb.FetchResponse{}, err\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Render: ioutil.ReadAll: %s: %+v\\n\", metric, err)\n\t\treturn pb.FetchResponse{}, err\n\t}\n\n\tvar pbresp pb.FetchResponse\n\n\terr = proto.Unmarshal(body, &pbresp)\n\tif err != nil {\n\t\tlog.Printf(\"Render: proto.Unmarshal: %s: %+v\\n\", metric, err)\n\t\treturn pb.FetchResponse{}, err\n\t}\n\n\treturn pbresp, nil\n}\n\ntype limiter chan struct{}\n\nfunc (l limiter) enter() { l <- struct{}{} }\nfunc (l limiter) leave() { <-l }\n\nvar Limiter limiter\n\n\/\/ for testing\nvar timeNow = time.Now\n\ntype graphitePoint struct {\n\tvalue float64\n\tt     int32\n}\n\nfunc (g graphitePoint) MarshalJSON() ([]byte, error) {\n\t\/\/ TODO(dgryski): fmt.Sprintf() is slow, use strconv.Append{Float,Int}\n\t\/\/ TODO(dgryski): MarshalJSON call should be on jsonResponse to reduce overhead\n\tif math.IsNaN(g.value) {\n\t\treturn []byte(fmt.Sprintf(\"[null,%d]\", g.t)), nil\n\t}\n\treturn []byte(fmt.Sprintf(\"[%g,%d]\", g.value, g.t)), nil\n}\n\ntype jsonResponse struct {\n\tTarget     string          `json:\"target\"`\n\tDatapoints []graphitePoint `json:\"datapoints\"`\n}\n\nfunc renderHandler(w http.ResponseWriter, r *http.Request) {\n\n\tMetrics.Requests.Add(1)\n\n\terr := r.ParseForm()\n\tif err != nil {\n\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\ttargets := r.Form[\"target\"]\n\tfrom := r.FormValue(\"from\")\n\tuntil := r.FormValue(\"until\")\n\tuseCache := r.FormValue(\"noCache\") == \"\"\n\n\t\/\/ make sure the cache key doesn't say noCache, because it will never hit\n\tr.Form.Del(\"noCache\")\n\n\tcacheKey := r.Form.Encode()\n\n\tif response, ok := queryCache.get(cacheKey); useCache && ok {\n\t\tMetrics.RequestCacheHits.Add(1)\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.Write(response)\n\t\treturn\n\t}\n\n\t\/\/ normalize from and until values\n\t\/\/ BUG(dgryski): doesn't handle timezones the same as graphite-web\n\tfrom32 := dateParamToEpoch(from, timeNow().Add(-24*time.Hour).Unix())\n\tuntil32 := dateParamToEpoch(until, timeNow().Unix())\n\n\tvar results []*pb.FetchResponse\n\tmetricMap := make(map[metricRequest][]*pb.FetchResponse)\n\n\tfor _, target := range targets {\n\n\t\texp, e, err := parseExpr(target)\n\t\tif err != nil || e != \"\" {\n\t\t\thttp.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tfor _, m := range exp.metrics() {\n\n\t\t\tmfetch := m\n\t\t\tmfetch.from += from32\n\t\t\tmfetch.until += until32\n\n\t\t\tif _, ok := metricMap[mfetch]; ok {\n\t\t\t\t\/\/ already fetched this metric for this request\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tvar glob pb.GlobResponse\n\t\t\tvar haveCacheData bool\n\n\t\t\tif response, ok := findCache.get(m.metric); useCache && ok {\n\t\t\t\tMetrics.FindCacheHits.Add(1)\n\t\t\t\terr := proto.Unmarshal(response, &glob)\n\t\t\t\thaveCacheData = err == nil\n\t\t\t}\n\n\t\t\tif !haveCacheData {\n\t\t\t\tvar err error\n\t\t\t\tMetrics.FindRequests.Add(1)\n\t\t\t\tglob, err = Zipper.Find(m.metric)\n\t\t\t\tif err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tb, err := proto.Marshal(&glob)\n\t\t\t\tif err == nil {\n\t\t\t\t\tfindCache.set(m.metric, b)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ For each metric returned in the Find response, query Render\n\t\t\t\/\/ This is a conscious decision to *not* cache render data\n\t\t\trch := make(chan *pb.FetchResponse, len(glob.GetMatches()))\n\t\t\tleaves := 0\n\t\t\tfor _, m := range glob.GetMatches() {\n\t\t\t\tif !m.GetIsLeaf() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tMetrics.RenderRequests.Add(1)\n\t\t\t\tleaves++\n\t\t\t\tLimiter.enter()\n\t\t\t\tgo func(m *pb.GlobMatch, from, until int32) {\n\t\t\t\t\tvar rptr *pb.FetchResponse\n\t\t\t\t\tr, err := Zipper.Render(m.GetPath(), from, until)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\trptr = &r\n\t\t\t\t\t}\n\t\t\t\t\trch <- rptr\n\t\t\t\t\tLimiter.leave()\n\t\t\t\t}(m, mfetch.from, mfetch.until)\n\t\t\t}\n\n\t\t\tfor i := 0; i < leaves; i++ {\n\t\t\t\tr := <-rch\n\t\t\t\tif r != nil {\n\t\t\t\t\tmetricMap[mfetch] = append(metricMap[mfetch], r)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\texprs := evalExpr(exp, from32, until32, metricMap)\n\t\tresults = append(results, exprs...)\n\t}\n\n\tvar jresults []jsonResponse\n\n\tfor _, r := range results {\n\t\tif r == nil {\n\t\t\tlog.Println(\"skipping nil result\")\n\t\t}\n\t\tdatapoints := make([]graphitePoint, 0, len(r.Values))\n\t\tt := *r.StartTime\n\t\tfor i, v := range r.Values {\n\t\t\tif r.IsAbsent[i] {\n\t\t\t\tv = math.NaN()\n\t\t\t}\n\t\t\tdatapoints = append(datapoints, graphitePoint{value: v, t: t})\n\t\t\tt += *r.StepTime\n\t\t}\n\t\tjresults = append(jresults, jsonResponse{Target: r.GetName(), Datapoints: datapoints})\n\t}\n\n\tjout, err := json.Marshal(jresults)\n\tif err != nil {\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tqueryCache.set(cacheKey, jout)\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(jout)\n}\n\nfunc lbcheckHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Ok\\n\")\n}\n\nfunc main() {\n\n\tz := flag.String(\"z\", \"\", \"zipper\")\n\tport := flag.Int(\"p\", 8080, \"port\")\n\tl := flag.Int(\"l\", 20, \"concurrency limit\")\n\tmc := flag.String(\"mc\", \"\", \"comma separated memcached server list\")\n\tcpus := flag.Int(\"cpus\", 0, \"number of CPUs to use\")\n\n\tflag.Parse()\n\n\tif p := os.Getenv(\"PORT\"); p != \"\" {\n\t\t*port, _ = strconv.Atoi(p)\n\t}\n\n\tLimiter = make(chan struct{}, *l)\n\n\tif *z == \"\" {\n\t\tlog.Fatal(\"no zipper provided\")\n\t}\n\n\tif _, err := url.Parse(*z); err != nil {\n\t\tlog.Fatal(\"unable to parze zipper:\", err)\n\t}\n\n\tlog.Println(\"using zipper\", *z)\n\n\tif *mc != \"\" {\n\t\tservers := strings.Split(*mc, \",\")\n\t\tlog.Println(\"using memcache servers:\", servers)\n\t\tqueryCache = &memcachedCache{client: memcache.New(servers...)}\n\t\tfindCache = &memcachedCache{client: memcache.New(servers...)}\n\t} else {\n\t\tqueryCache = &expireCache{cache: make(map[string]cacheElement)}\n\t\tgo queryCache.(*expireCache).cleaner()\n\n\t\tfindCache = &expireCache{cache: make(map[string]cacheElement)}\n\t\tgo findCache.(*expireCache).cleaner()\n\t}\n\n\tZipper = zipper(*z)\n\n\tif *cpus != 0 {\n\t\tlog.Println(\"using GOMAXPROCS\", *cpus)\n\t\truntime.GOMAXPROCS(*cpus)\n\t}\n\n\tif host := os.Getenv(\"GRAPHITEHOST\") + \":\" + os.Getenv(\"GRAPHITEPORT\"); host != \":\" {\n\n\t\tlog.Println(\"Using graphite host\", host)\n\n\t\t\/\/ register our metrics with graphite\n\t\tgraphite, err := g2g.NewGraphite(host, 60*time.Second, 10*time.Second)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"unable to connect to to graphite: \", host, \":\", err)\n\t\t}\n\n\t\thostname, _ := os.Hostname()\n\t\thostname = strings.Replace(hostname, \".\", \"_\", -1)\n\n\t\tgraphite.Register(fmt.Sprintf(\"carbon.api.%s.requests\", hostname), Metrics.Requests)\n\t\tgraphite.Register(fmt.Sprintf(\"carbon.api.%s.request_cache_hits\", hostname), Metrics.RequestCacheHits)\n\n\t\tgraphite.Register(fmt.Sprintf(\"carbon.api.%s.find_requests\", hostname), Metrics.FindRequests)\n\t\tgraphite.Register(fmt.Sprintf(\"carbon.api.%s.find_cache_hits\", hostname), Metrics.FindCacheHits)\n\n\t\tgraphite.Register(fmt.Sprintf(\"carbon.api.%s.render_requests\", hostname), Metrics.RenderRequests)\n\t}\n\n\thttp.HandleFunc(\"\/render\/\", renderHandler)\n\thttp.HandleFunc(\"\/lbcheck\", lbcheckHandler)\n\n\tlog.Println(\"listening on port\", *port)\n\tlog.Fatalln(http.ListenAndServe(\":\"+strconv.Itoa(*port), nil))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"net\/url\"\n\n\t\"github.com\/line\/line-bot-sdk-go\/linebot\"\n)\n\nvar bot *linebot.Client\n\nfunc main() {\n\tvar err error\n\tbot, err = linebot.New(os.Getenv(\"ChannelSecret\"), os.Getenv(\"ChannelAccessToken\"))\n\tlog.Println(\"Bot:\", bot, \" err:\", err)\n\thttp.HandleFunc(\"\/callback\", callbackHandler)\n\tport := os.Getenv(\"PORT\")\n\taddr := fmt.Sprintf(\":%s\", port)\n\thttp.ListenAndServe(addr, nil)\n}\n\nfunc callbackHandler(w http.ResponseWriter, r *http.Request) {\n\tevents, err := bot.ParseRequest(r)\n\n\tresp, err := http.PostForm(\"https:\/\/hr.hiyes.tw:443\/getMessage.php\",\n        url.Values{\"mid\": {\"ziv\"}, \"message\": {\"test\"}})\n    if err != nil {\n        fmt.Println(err)\n    } else {\n        body, _ := ioutil.ReadAll(resp.Body)\n        fmt.Println(\"POST OK: \", string(body), resp)\n    }\n\n\n\n\tif err != nil {\n\t\tif err == linebot.ErrInvalidSignature {\n\t\t\tw.WriteHeader(400)\n\t\t} else {\n\t\t\tw.WriteHeader(500)\n\t\t}\n\t\treturn\n\t}\n\n\tfor _, event := range events {\n\t\tif event.Type == linebot.EventTypeMessage {\n\t\t\tswitch message := event.Message.(type) {\n\t\t\tcase *linebot.TextMessage:\n\t\t\t\tif _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(event.ReplyToken+\"---\"+message.Text+\" OK!\")).Do(); err != nil {\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>add \"io\/ioutil\"<commit_after>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"net\/url\"\n\t\"io\/ioutil\"\n\t\n\t\"github.com\/line\/line-bot-sdk-go\/linebot\"\n)\n\nvar bot *linebot.Client\n\nfunc main() {\n\tvar err error\n\tbot, err = linebot.New(os.Getenv(\"ChannelSecret\"), os.Getenv(\"ChannelAccessToken\"))\n\tlog.Println(\"Bot:\", bot, \" err:\", err)\n\thttp.HandleFunc(\"\/callback\", callbackHandler)\n\tport := os.Getenv(\"PORT\")\n\taddr := fmt.Sprintf(\":%s\", port)\n\thttp.ListenAndServe(addr, nil)\n}\n\nfunc callbackHandler(w http.ResponseWriter, r *http.Request) {\n\tevents, err := bot.ParseRequest(r)\n\n\tresp, err := http.PostForm(\"https:\/\/hr.hiyes.tw:443\/getMessage.php\",\n        url.Values{\"mid\": {\"ziv\"}, \"message\": {\"test\"}})\n    if err != nil {\n        fmt.Println(err)\n    } else {\n        body, _ := ioutil.ReadAll(resp.Body)\n        fmt.Println(\"POST OK: \", string(body), resp)\n    }\n\n\n\n\tif err != nil {\n\t\tif err == linebot.ErrInvalidSignature {\n\t\t\tw.WriteHeader(400)\n\t\t} else {\n\t\t\tw.WriteHeader(500)\n\t\t}\n\t\treturn\n\t}\n\n\tfor _, event := range events {\n\t\tif event.Type == linebot.EventTypeMessage {\n\t\t\tswitch message := event.Message.(type) {\n\t\t\tcase *linebot.TextMessage:\n\t\t\t\tif _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(event.ReplyToken+\"---\"+message.Text+\" OK!\")).Do(); err != nil {\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/koron\/gomigemo\/migemo\"\n)\n\nfunc dictdir() string {\n\td := os.Getenv(\"GMIGEMO_DICTDIR\")\n\tif d != \"\" {\n\t\treturn d\n\t}\n\td = os.Getenv(\"GOPATH\")\n\tif d == \"\" {\n\t\td = \".\"\n\t}\n\tfor _, p := range strings.Split(d, string(filepath.ListSeparator)) {\n\t\tcandidate := filepath.Join(p, \"src\", \"github.com\", \"koron\", \"gomigemo\", \"_dict\")\n\t\tif _, err := os.Stat(candidate); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\treturn candidate\n\t}\n\n\t\/\/ fallback to current directory\n\treturn d\n}\n\nvar dictPath = flag.String(\"d\", dictdir(), \"Location to dictionary\")\n\nfunc grep(r io.Reader, re *regexp.Regexp) error {\n\tbuf := bufio.NewReader(r)\n\tfor {\n\t\tb, _, err := buf.ReadLine()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tline := string(b)\n\t\tif re.MatchString(line) {\n\t\t\tfmt.Println(line)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintln(os.Stderr, \"Usage of main: [pattern] [files...]\")\n\t}\n\n\tflag.Parse()\n\n\tif flag.NArg() != 1 && flag.NArg() != 2 {\n\t\tflag.Usage()\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\t}\n\n\tdict, err := migemo.Load(*dictPath)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\tre, err := migemo.Compile(dict, flag.Arg(0))\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\tif flag.NArg() == 1 {\n\t\tif err = grep(os.Stdin, re); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t} else {\n\t\tfor _, arg := range flag.Args()[1:] {\n\t\t\tf, err := os.Open(arg)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tdefer f.Close()\n\t\t\tif err = grep(f, re); err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}\n}<commit_msg>Annotate so I can start digging<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/koron\/gomigemo\/migemo\"\n)\n\n\/\/ Looks for possible dictionary directories.\n\/\/ We should expand this to more unix-y locations, too\nfunc dictdir() string {\n\t\/\/ I want to change this to G*O*MIGEMO_DICTDIR\n\td := os.Getenv(\"GMIGEMO_DICTDIR\")\n\tif d != \"\" {\n\t\treturn d\n\t}\n\td = os.Getenv(\"GOPATH\")\n\tif d == \"\" {\n\t\td = \".\"\n\t}\n\tfor _, p := range strings.Split(d, string(filepath.ListSeparator)) {\n\t\tcandidate := filepath.Join(p, \"src\", \"github.com\", \"koron\", \"gomigemo\", \"_dict\")\n\t\tif _, err := os.Stat(candidate); err != nil {\n\t\t\tcontinue\n\t\t}\n\t\treturn candidate\n\t}\n\n\t\/\/ fallback to current directory\n\treturn d\n}\n\nvar dictPath = flag.String(\"d\", dictdir(), \"Location to dictionary\")\n\n\/\/ Does the grepping\nfunc grep(r io.Reader, re *regexp.Regexp) error {\n\tbuf := bufio.NewReader(r)\n\tfor {\n\t\tb, _, err := buf.ReadLine()\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tline := string(b)\n\t\tif re.MatchString(line) {\n\t\t\tfmt.Println(line)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintln(os.Stderr, \"Usage of main: [pattern] [files...]\")\n\t}\n\n\tflag.Parse()\n\n\tif flag.NArg() != 1 && flag.NArg() != 2 {\n\t\tflag.Usage()\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\t}\n\n\tdict, err := migemo.Load(*dictPath)\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\tre, err := migemo.Compile(dict, flag.Arg(0))\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\n\t\/\/ If there's only one arg, then we need to match against the input\n\tif flag.NArg() == 1 {\n\t\tif err = grep(os.Stdin, re); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\t\/\/ We got here, we're fine.\n\t\treturn\n\t}\n\n\n\t\/\/ More than one arg. We must be searching against a file\n\tfor _, arg := range flag.Args()[1:] {\n\t\tf, err := os.Open(arg)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tdefer f.Close()\n\t\tif err = grep(f, re); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n    \"flag\"\n    \"fmt\"\n    \"log\"\n    \"milo\/utils\"\n    \"os\"\n    \"path\/filepath\"\n    \"regexp\"\n    \"runtime\"\n    \"strings\"\n)\n\nvar root string\nvar extensions []string\nvar pattern *regexp.Regexp\n\n\/\/ getNames creates a filepath.WalkFunc suitable for passing to\n\/\/ filepath.Walk which passes the filenames found into a channel.\nfunc getNames(c chan string) filepath.WalkFunc {\n    return func(path string, info os.FileInfo, err error) error {\n        if info.Mode().IsRegular() {\n            c <- path\n        }\n        return nil\n    }\n}\n\n\/\/ init parses the command-line arguments into the values\n\/\/ used to execute. There should be a pattern at the very\n\/\/ least. Optionally, a path (defaulting to \".\"), and\n\/\/ file extensions to search may be provided.\nfunc init() {\n    flag.Parse()\n    args := flag.Args()\n    if len(args) == 0 {\n        log.Fatalf(\"No arguments passed.\")\n    }\n    args = getExts(args)\n    args = getRoot(args)\n    if len(args) != 1 {\n        log.Fatalf(\"Unable to find pattern.\\n\")\n    }\n    p, err := regexp.Compile(args[0])\n    if err != nil {\n        log.Fatal(err)\n    }\n    pattern = p\n    runtime.GOMAXPROCS(runtime.NumCPU())\n}\n\n\/\/ getExts sets the extensions global variable,\n\/\/ removes any extension arguments from args,\n\/\/ and returns args for further processing.\nfunc getExts(args []string) []string {\n    var unused []string\n    for _, val := range args {\n        if strings.HasPrefix(val, \"--\") {\n            extensions = append(extensions, val)\n        } else {\n            unused = append(unused, val)\n        }\n    }\n    return unused\n}\n\n\/\/ getRoot finds a valid directory in the command-line\n\/\/ args, sets it to the global \"root\" variable, and\n\/\/ returns the remaining arguments.\nfunc getRoot(args []string) []string {\n    var unused []string\n    for _, val := range args {\n        if utils.IsDir(val) {\n            if root != \"\" {\n                log.Fatalf(\"Too many directory arguments\\n\")\n            } else {\n                root = val\n            }\n        } else {\n            unused = append(unused, val)\n        }\n    }\n    if root == \"\" {\n        root = \".\"\n    }\n    return unused\n}\n\nfunc main() {\n\n    filenames := make(chan string, 3333)\n\n    \/\/ Make a function containing this channel.\n    f := getNames(filenames)\n\n    go func() {\n        filepath.Walk(root, f)\n        close(filenames)\n    }()\n\n    count := 0\n\n    for _ = range filenames {\n        count += 1\n    }\n\n    fmt.Printf(\"%d files found.\\n\", count)\n\n}\n<commit_msg>updates getNames to use extensions global<commit_after>package main\n\nimport (\n    \"flag\"\n    \"fmt\"\n    \"log\"\n    \"milo\/utils\"\n    \"os\"\n    \"path\/filepath\"\n    \"regexp\"\n    \"runtime\"\n    \"strings\"\n)\n\nvar root string\nvar extensions []string\nvar pattern *regexp.Regexp\n\n\/\/ getNames creates a filepath.WalkFunc suitable for passing to\n\/\/ filepath.Walk which passes the filenames found into a channel.\nfunc getNames(c chan string) filepath.WalkFunc {\n    return func(path string, info os.FileInfo, err error) error {\n        if !info.Mode().IsRegular() {\n            return nil\n        }\n        if extensions {\n            for _, ext := range extensions {\n                if filepath.Ext(path) == ext {\n                    c <- path\n                    return nil\n                }\n            }\n            return nil\n        } \n        c <- path\n        return nil\n    }\n}\n\n\/\/ init parses the command-line arguments into the values\n\/\/ used to execute. There should be a pattern at the very\n\/\/ least. Optionally, a path (defaulting to \".\"), and\n\/\/ file extensions to search may be provided.\nfunc init() {\n    flag.Parse()\n    args := flag.Args()\n    if len(args) == 0 {\n        log.Fatalf(\"No arguments passed.\")\n    }\n    args = getExts(args)\n    args = getRoot(args)\n    if len(args) != 1 {\n        log.Fatalf(\"Unable to find pattern.\\n\")\n    }\n    p, err := regexp.Compile(args[0])\n    if err != nil {\n        log.Fatal(err)\n    }\n    pattern = p\n    runtime.GOMAXPROCS(runtime.NumCPU())\n}\n\n\/\/ getExts sets the extensions global variable,\n\/\/ removes any extension arguments from args,\n\/\/ and returns args for further processing.\nfunc getExts(args []string) []string {\n    var unused []string\n    for _, val := range args {\n        if strings.HasPrefix(val, \"--\") {\n            if len(val) < 3 {\n                log.Fatalf(\"Invalid extension: '%s'\\n\", val)\n            }\n            extensions = append(extensions, val[2:])\n        } else {\n            unused = append(unused, val)\n        }\n    }\n    return unused\n}\n\n\/\/ getRoot finds a valid directory in the command-line\n\/\/ args, sets it to the global \"root\" variable, and\n\/\/ returns the remaining arguments.\nfunc getRoot(args []string) []string {\n    var unused []string\n    for _, val := range args {\n        if utils.IsDir(val) {\n            if root != \"\" {\n                log.Fatalf(\"Too many directory arguments\\n\")\n            } else {\n                root = val\n            }\n        } else {\n            unused = append(unused, val)\n        }\n    }\n    if root == \"\" {\n        root = \".\"\n    }\n    return unused\n}\n\nfunc main() {\n    filenames := make(chan string, 3333)\n    f := getNames(filenames)\n    go func() {\n        filepath.Walk(root, f)\n        close(filenames)\n    }()\n    count := 0\n    for _ = range filenames {\n        count += 1\n    }\n    fmt.Printf(\"%d files found.\\n\", count)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/nitishparkar\/jobberknoll\/controllers\"\n\t\"net\/http\"\n\t\"os\"\n\t\"text\/template\"\n\t\"github.com\/nitishparkar\/jobberknoll\/models\"\n)\n\nfunc main() {\n\trouter := mux.NewRouter()\n\n\tmodels.RunMigrations()\n\n\trouter.HandleFunc(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"Hello, World!\"))\n\t})\n\n\ttemplates := populateTemplates()\n\n\tpc := new(controllers.PeopleController)\n\tpc.Template = templates.Lookup(\"index.html\")\n\trouter.HandleFunc(\"\/people\", pc.Index)\n\n\tnpc := new(controllers.NewPersonController)\n\tnpc.Template = templates.Lookup(\"new.html\")\n\trouter.HandleFunc(\"\/people\/new\", npc.New)\n\trouter.HandleFunc(\"\/people\/create\", npc.Create)\n\n\tpersonController := new(controllers.PersonController)\n\tpersonController.Template = templates.Lookup(\"show.html\")\n\trouter.HandleFunc(\"\/people\/{id}\", personController.Show)\n\n\tepc := new(controllers.NewPersonController)\n\tepc.Template = templates.Lookup(\"edit.html\")\n\trouter.HandleFunc(\"\/people\/{id}\/edit\", epc.Edit)\n\trouter.HandleFunc(\"\/people\/{id}\/update\", epc.Update)\n\n\thttp.Handle(\"\/\", router)\n\thttp.ListenAndServe(\":9090\", nil)\n}\n\nfunc populateTemplates() *template.Template {\n\tresult := template.New(\"templates\")\n\n\tbasePath := \"templates\"\n\ttemplateFolder, _ := os.Open(basePath)\n\tdefer templateFolder.Close()\n\n\ttemplatePathsRaw, _ := templateFolder.Readdir(-1)\n\ttemplatePaths := new([]string)\n\n\tfor _, pathInfo := range templatePathsRaw {\n\t\tif !pathInfo.IsDir() {\n\t\t\t*templatePaths = append(*templatePaths, basePath+\"\/\"+pathInfo.Name())\n\t\t}\n\t}\n\n\tresult.ParseFiles(*templatePaths...)\n\n\treturn result\n}\n<commit_msg>Print a message indicating that the web server is starting<commit_after>package main\n\nimport (\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/nitishparkar\/jobberknoll\/controllers\"\n\t\"net\/http\"\n\t\"os\"\n\t\"text\/template\"\n\t\"github.com\/nitishparkar\/jobberknoll\/models\"\n)\n\nvar port = \":9090\"\n\nfunc main() {\n\trouter := mux.NewRouter()\n\n\tmodels.RunMigrations()\n\n\trouter.HandleFunc(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"Hello, World!\"))\n\t})\n\n\ttemplates := populateTemplates()\n\n\tpc := new(controllers.PeopleController)\n\tpc.Template = templates.Lookup(\"index.html\")\n\trouter.HandleFunc(\"\/people\", pc.Index)\n\n\tnpc := new(controllers.NewPersonController)\n\tnpc.Template = templates.Lookup(\"new.html\")\n\trouter.HandleFunc(\"\/people\/new\", npc.New)\n\trouter.HandleFunc(\"\/people\/create\", npc.Create)\n\n\tpersonController := new(controllers.PersonController)\n\tpersonController.Template = templates.Lookup(\"show.html\")\n\trouter.HandleFunc(\"\/people\/{id}\", personController.Show)\n\n\tepc := new(controllers.NewPersonController)\n\tepc.Template = templates.Lookup(\"edit.html\")\n\trouter.HandleFunc(\"\/people\/{id}\/edit\", epc.Edit)\n\trouter.HandleFunc(\"\/people\/{id}\/update\", epc.Update)\n\n\thttp.Handle(\"\/\", router)\n\n\tprintln(\"Starting web server at port\", port)\n\thttp.ListenAndServe(port, nil)\n\tprintln(\"Web server stopped\")\n}\n\nfunc populateTemplates() *template.Template {\n\tresult := template.New(\"templates\")\n\n\tbasePath := \"templates\"\n\ttemplateFolder, _ := os.Open(basePath)\n\tdefer templateFolder.Close()\n\n\ttemplatePathsRaw, _ := templateFolder.Readdir(-1)\n\ttemplatePaths := new([]string)\n\n\tfor _, pathInfo := range templatePathsRaw {\n\t\tif !pathInfo.IsDir() {\n\t\t\t*templatePaths = append(*templatePaths, basePath+\"\/\"+pathInfo.Name())\n\t\t}\n\t}\n\n\tresult.ParseFiles(*templatePaths...)\n\n\treturn result\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"mime\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n<<<<<<< HEAD\n=======\n\n\tmgo \"gopkg.in\/mgo.v2\"\n>>>>>>> 41f63c1f... optionally write to mongo\n\n\t\"github.com\/ONSdigital\/florence\/assets\"\n\t\"github.com\/ONSdigital\/go-ns\/handlers\/reverseProxy\"\n\t\"github.com\/ONSdigital\/go-ns\/log\"\n\t\"github.com\/ONSdigital\/go-ns\/server\"\n\t\"github.com\/gorilla\/pat\"\n\t\"github.com\/gorilla\/websocket\"\n)\n\nvar bindAddr = \":8080\"\nvar babbageURL = \"http:\/\/localhost:8080\"\nvar zebedeeURL = \"http:\/\/localhost:8082\"\nvar enableNewApp = false\nvar mongoURI = \"localhost:27017\"\n\nvar getAsset = assets.Asset\nvar upgrader = websocket.Upgrader{}\nvar session *mgo.Session\n\nfunc main() {\n\tif v := os.Getenv(\"BIND_ADDR\"); len(v) > 0 {\n\t\tbindAddr = v\n\t}\n\tif v := os.Getenv(\"BABBAGE_URL\"); len(v) > 0 {\n\t\tbabbageURL = v\n\t}\n\tif v := os.Getenv(\"ZEBEDEE_URL\"); len(v) > 0 {\n\t\tzebedeeURL = v\n\t}\n\tif v := os.Getenv(\"ENABLE_NEW_APP\"); len(v) > 0 {\n\t\tenableNewApp, _ = strconv.ParseBool(v)\n\t}\n\tif v := os.Getenv(\"MONGO_URI\"); len(v) > 0 {\n\t\tif v == \"-\" {\n\t\t\tmongoURI = \"\"\n\t\t} else {\n\t\t\tmongoURI = v\n\t\t}\n\t}\n\n\tlog.Namespace = \"florence\"\n\n\t\/*\n\t\tNOTE:\n\t\tIf there's any issues with this Florence server proxying redirects\n\t\tfrom either Babbage or Zebedee then the code in the previous Java\n\t\tFlorence server might give some clues for a solution: https:\/\/github.com\/ONSdigital\/florence\/blob\/b13df0708b30493b98e9ce239103c59d7f409f98\/src\/main\/java\/com\/github\/onsdigital\/florence\/filter\/Proxy.java#L125-L135\n\n\t\tThe code has purposefully not been included in this Go replacement\n\t\tbecause we can't see what issue it's fixing and whether it's necessary.\n\t*\/\n\n\tvar err error\n\tif len(mongoURI) > 0 {\n\t\tsession, err = mgo.Dial(mongoURI)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer session.Close()\n\t}\n\n\tbabbageURL, err := url.Parse(babbageURL)\n\tif err != nil {\n\t\tlog.Error(err, nil)\n\t\tos.Exit(1)\n\t}\n\n\tbabbageProxy := reverseProxy.Create(babbageURL, nil)\n\n\tzebedeeURL, err := url.Parse(zebedeeURL)\n\tif err != nil {\n\t\tlog.Error(err, nil)\n\t\tos.Exit(1)\n\t}\n\n\tzebedeeProxy := reverseProxy.Create(zebedeeURL, zebedeeDirector)\n\n\trouter := pat.New()\n\n\tnewAppHandler := refactoredIndexFile\n\n\tif !enableNewApp {\n\t\tnewAppHandler = legacyIndexFile\n\t}\n\n\trouter.Handle(\"\/zebedee\/{uri:.*}\", zebedeeProxy)\n\trouter.HandleFunc(\"\/florence\/dist\/{uri:.*}\", staticFiles)\n\trouter.HandleFunc(\"\/florence\", newAppHandler)\n\trouter.HandleFunc(\"\/florence\/index.html\", legacyIndexFile)\n\trouter.HandleFunc(\"\/florence\/websocket\", websocketHandler)\n\trouter.HandleFunc(\"\/florence{uri:|\/.*}\", newAppHandler)\n\trouter.Handle(\"\/{uri:.*}\", babbageProxy)\n\n\tlog.Debug(\"Starting server\", log.Data{\n\t\t\"bind_addr\":      bindAddr,\n\t\t\"babbage_url\":    babbageURL,\n\t\t\"zebedee_url\":    zebedeeURL,\n\t\t\"enable_new_app\": enableNewApp,\n\t})\n\n\ts := server.New(bindAddr, router)\n\t\/\/ TODO need to reconsider default go-ns server timeouts\n\ts.Server.IdleTimeout = 120 * time.Second\n\ts.Server.WriteTimeout = 120 * time.Second\n\ts.Server.ReadTimeout = 30 * time.Second\n\ts.MiddlewareOrder = []string{\"RequestID\", \"Log\"}\n\n\t\/\/ FIXME temporary hack to remove timeout middleware (doesn't support hijacker interface)\n\tmo := s.MiddlewareOrder\n\tvar newMo []string\n\tfor _, mw := range mo {\n\t\tif mw != \"Timeout\" {\n\t\t\tnewMo = append(newMo, mw)\n\t\t}\n\t}\n\ts.MiddlewareOrder = newMo\n\n\tif err := s.ListenAndServe(); err != nil {\n\t\tlog.Error(err, nil)\n\t\tos.Exit(2)\n\t}\n}\n\nfunc staticFiles(w http.ResponseWriter, req *http.Request) {\n\tpath := req.URL.Query().Get(\":uri\")\n\n\tb, err := getAsset(\"..\/dist\/\" + path)\n\tif err != nil {\n\t\tlog.Error(err, nil)\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\tw.Header().Set(`Content-Type`, mime.TypeByExtension(filepath.Ext(path)))\n\tw.WriteHeader(200)\n\tw.Write(b)\n}\n\nfunc legacyIndexFile(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"Getting legacy HTML file\", nil)\n\n\tb, err := getAsset(\"..\/dist\/legacy-assets\/index.html\")\n\tif err != nil {\n\t\tlog.Error(err, nil)\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\tw.Header().Set(`Content-Type`, \"text\/html\")\n\tw.WriteHeader(200)\n\tw.Write(b)\n}\n\nfunc refactoredIndexFile(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"Getting refactored HTML file\", nil)\n\n\tb, err := getAsset(\"..\/dist\/refactored.html\")\n\tif err != nil {\n\t\tlog.Error(err, nil)\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\tw.Header().Set(`Content-Type`, \"text\/html\")\n\tw.WriteHeader(200)\n\tw.Write(b)\n}\n\nfunc zebedeeDirector(req *http.Request) {\n\tif c, err := req.Cookie(`access_token`); err == nil && len(c.Value) > 0 {\n\t\treq.Header.Set(`X-Florence-Token`, c.Value)\n\t}\n\treq.URL.Path = strings.TrimPrefix(req.URL.Path, \"\/zebedee\")\n}\n\nfunc websocketHandler(w http.ResponseWriter, req *http.Request) {\n\tc, err := upgrader.Upgrade(w, req, nil)\n\tif err != nil {\n\t\tlog.ErrorR(req, err, nil)\n\t\treturn\n\t}\n\n\tdefer c.Close()\n\n\tfor {\n\t\t_, message, err := c.ReadMessage()\n\t\tif err != nil {\n\t\t\tlog.ErrorR(req, err, nil)\n\t\t\tbreak\n\t\t}\n\n\t\tlog.DebugR(req, \"websocket recv\", log.Data{\"data\": string(message)})\n\n\t\trdr := bufio.NewReader(bytes.NewReader(message))\n\t\tb, err := rdr.ReadBytes(':')\n\t\tif err != nil {\n\t\t\tlog.ErrorR(req, err, nil)\n\t\t\tcontinue\n\t\t}\n\n\t\teventType := string(b[:len(b)-1])\n\t\teventData := message[len(eventType)+1:]\n\n\t\tswitch eventType {\n\t\tcase \"event\":\n\t\t\tlog.DebugR(req, \"event\", log.Data{\"type\": eventType, \"data\": string(eventData)})\n\t\t\tvar e florenceLogEvent\n\t\t\terr = json.Unmarshal(eventData, &e)\n\t\t\tif err != nil {\n\t\t\t\tlog.ErrorR(req, err, nil)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\twriteToDB(e)\n\t\tdefault:\n\t\t\tlog.DebugR(req, \"unknown event type\", log.Data{\"type\": eventType, \"data\": string(eventData)})\n\t\t}\n\n\t\t\/\/ err = c.WriteMessage(mt, message)\n\t\t\/\/ if err != nil {\n\t\t\/\/ \tlog.ErrorR(req, err, nil)\n\t\t\/\/ \tbreak\n\t\t\/\/ }\n\t}\n}\n\ntype florenceLogEvent struct {\n\tCreated         time.Time   `json:\"-\"`\n\tClientTimestamp time.Time   `json:\"clientTimestamp\"`\n\tType            string      `json:\"type\"`\n\tLocation        string      `json:\"location\"`\n\tInstanceID      int         `json:\"instanceID\"`\n\tPayload         interface{} `json:\"payload\"`\n}\n\nfunc writeToDB(e florenceLogEvent) {\n\te.Created = time.Now()\n\n\tif session == nil {\n\t\tlog.Debug(\"FLORENCE LOG EVENT!\", log.Data{\"event\": e})\n\t\treturn\n\t}\n\n\ts := session.New()\n\tdefer s.Close()\n\tif err := s.DB(\"florence\").C(\"client_log\").Insert(&e); err != nil {\n\t\tlog.Error(err, log.Data{\"event\": e})\n\t}\n}\n<commit_msg>remove mongo<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"mime\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n<<<<<<< HEAD\n=======\n\n\tmgo \"gopkg.in\/mgo.v2\"\n>>>>>>> 41f63c1f... optionally write to mongo\n\n\t\"github.com\/ONSdigital\/florence\/assets\"\n\t\"github.com\/ONSdigital\/go-ns\/handlers\/reverseProxy\"\n\t\"github.com\/ONSdigital\/go-ns\/log\"\n\t\"github.com\/ONSdigital\/go-ns\/server\"\n\t\"github.com\/gorilla\/pat\"\n\t\"github.com\/gorilla\/websocket\"\n)\n\nvar bindAddr = \":8080\"\nvar babbageURL = \"http:\/\/localhost:8080\"\nvar zebedeeURL = \"http:\/\/localhost:8082\"\nvar enableNewApp = false\nvar mongoURI = \"localhost:27017\"\n\nvar getAsset = assets.Asset\nvar upgrader = websocket.Upgrader{}\nvar session *mgo.Session\n\nfunc main() {\n\tif v := os.Getenv(\"BIND_ADDR\"); len(v) > 0 {\n\t\tbindAddr = v\n\t}\n\tif v := os.Getenv(\"BABBAGE_URL\"); len(v) > 0 {\n\t\tbabbageURL = v\n\t}\n\tif v := os.Getenv(\"ZEBEDEE_URL\"); len(v) > 0 {\n\t\tzebedeeURL = v\n\t}\n\tif v := os.Getenv(\"ENABLE_NEW_APP\"); len(v) > 0 {\n\t\tenableNewApp, _ = strconv.ParseBool(v)\n\t}\n\n\tlog.Namespace = \"florence\"\n\n\t\/*\n\t\tNOTE:\n\t\tIf there's any issues with this Florence server proxying redirects\n\t\tfrom either Babbage or Zebedee then the code in the previous Java\n\t\tFlorence server might give some clues for a solution: https:\/\/github.com\/ONSdigital\/florence\/blob\/b13df0708b30493b98e9ce239103c59d7f409f98\/src\/main\/java\/com\/github\/onsdigital\/florence\/filter\/Proxy.java#L125-L135\n\n\t\tThe code has purposefully not been included in this Go replacement\n\t\tbecause we can't see what issue it's fixing and whether it's necessary.\n\t*\/\n\n\tbabbageURL, err := url.Parse(babbageURL)\n\tif err != nil {\n\t\tlog.Error(err, nil)\n\t\tos.Exit(1)\n\t}\n\n\tbabbageProxy := reverseProxy.Create(babbageURL, nil)\n\n\tzebedeeURL, err := url.Parse(zebedeeURL)\n\tif err != nil {\n\t\tlog.Error(err, nil)\n\t\tos.Exit(1)\n\t}\n\n\tzebedeeProxy := reverseProxy.Create(zebedeeURL, zebedeeDirector)\n\n\trouter := pat.New()\n\n\tnewAppHandler := refactoredIndexFile\n\n\tif !enableNewApp {\n\t\tnewAppHandler = legacyIndexFile\n\t}\n\n\trouter.Handle(\"\/zebedee\/{uri:.*}\", zebedeeProxy)\n\trouter.HandleFunc(\"\/florence\/dist\/{uri:.*}\", staticFiles)\n\trouter.HandleFunc(\"\/florence\", newAppHandler)\n\trouter.HandleFunc(\"\/florence\/index.html\", legacyIndexFile)\n\trouter.HandleFunc(\"\/florence\/websocket\", websocketHandler)\n\trouter.HandleFunc(\"\/florence{uri:|\/.*}\", newAppHandler)\n\trouter.Handle(\"\/{uri:.*}\", babbageProxy)\n\n\tlog.Debug(\"Starting server\", log.Data{\n\t\t\"bind_addr\":      bindAddr,\n\t\t\"babbage_url\":    babbageURL,\n\t\t\"zebedee_url\":    zebedeeURL,\n\t\t\"enable_new_app\": enableNewApp,\n\t})\n\n\ts := server.New(bindAddr, router)\n\t\/\/ TODO need to reconsider default go-ns server timeouts\n\ts.Server.IdleTimeout = 120 * time.Second\n\ts.Server.WriteTimeout = 120 * time.Second\n\ts.Server.ReadTimeout = 30 * time.Second\n\ts.MiddlewareOrder = []string{\"RequestID\", \"Log\"}\n\n\t\/\/ FIXME temporary hack to remove timeout middleware (doesn't support hijacker interface)\n\tmo := s.MiddlewareOrder\n\tvar newMo []string\n\tfor _, mw := range mo {\n\t\tif mw != \"Timeout\" {\n\t\t\tnewMo = append(newMo, mw)\n\t\t}\n\t}\n\ts.MiddlewareOrder = newMo\n\n\tif err := s.ListenAndServe(); err != nil {\n\t\tlog.Error(err, nil)\n\t\tos.Exit(2)\n\t}\n}\n\nfunc staticFiles(w http.ResponseWriter, req *http.Request) {\n\tpath := req.URL.Query().Get(\":uri\")\n\n\tb, err := getAsset(\"..\/dist\/\" + path)\n\tif err != nil {\n\t\tlog.Error(err, nil)\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\tw.Header().Set(`Content-Type`, mime.TypeByExtension(filepath.Ext(path)))\n\tw.WriteHeader(200)\n\tw.Write(b)\n}\n\nfunc legacyIndexFile(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"Getting legacy HTML file\", nil)\n\n\tb, err := getAsset(\"..\/dist\/legacy-assets\/index.html\")\n\tif err != nil {\n\t\tlog.Error(err, nil)\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\tw.Header().Set(`Content-Type`, \"text\/html\")\n\tw.WriteHeader(200)\n\tw.Write(b)\n}\n\nfunc refactoredIndexFile(w http.ResponseWriter, req *http.Request) {\n\tlog.Debug(\"Getting refactored HTML file\", nil)\n\n\tb, err := getAsset(\"..\/dist\/refactored.html\")\n\tif err != nil {\n\t\tlog.Error(err, nil)\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\tw.Header().Set(`Content-Type`, \"text\/html\")\n\tw.WriteHeader(200)\n\tw.Write(b)\n}\n\nfunc zebedeeDirector(req *http.Request) {\n\tif c, err := req.Cookie(`access_token`); err == nil && len(c.Value) > 0 {\n\t\treq.Header.Set(`X-Florence-Token`, c.Value)\n\t}\n\treq.URL.Path = strings.TrimPrefix(req.URL.Path, \"\/zebedee\")\n}\n\nfunc websocketHandler(w http.ResponseWriter, req *http.Request) {\n\tc, err := upgrader.Upgrade(w, req, nil)\n\tif err != nil {\n\t\tlog.ErrorR(req, err, nil)\n\t\treturn\n\t}\n\n\tdefer c.Close()\n\n\tfor {\n\t\t_, message, err := c.ReadMessage()\n\t\tif err != nil {\n\t\t\tlog.ErrorR(req, err, nil)\n\t\t\tbreak\n\t\t}\n\n\t\tlog.DebugR(req, \"websocket recv\", log.Data{\"data\": string(message)})\n\n\t\trdr := bufio.NewReader(bytes.NewReader(message))\n\t\tb, err := rdr.ReadBytes(':')\n\t\tif err != nil {\n\t\t\tlog.ErrorR(req, err, nil)\n\t\t\tcontinue\n\t\t}\n\n\t\teventType := string(b[:len(b)-1])\n\t\teventData := message[len(eventType)+1:]\n\n\t\tswitch eventType {\n\t\tcase \"event\":\n\t\t\tlog.DebugR(req, \"event\", log.Data{\"type\": eventType, \"data\": string(eventData)})\n\t\t\tvar e florenceLogEvent\n\t\t\terr = json.Unmarshal(eventData, &e)\n\t\t\tif err != nil {\n\t\t\t\tlog.ErrorR(req, err, nil)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlog.Debug(\"client log\", log.Data{\"data\": e})\n\t\tdefault:\n\t\t\tlog.DebugR(req, \"unknown event type\", log.Data{\"type\": eventType, \"data\": string(eventData)})\n\t\t}\n\n\t\t\/\/ err = c.WriteMessage(mt, message)\n\t\t\/\/ if err != nil {\n\t\t\/\/ \tlog.ErrorR(req, err, nil)\n\t\t\/\/ \tbreak\n\t\t\/\/ }\n\t}\n}\n\ntype florenceLogEvent struct {\n\tCreated         time.Time   `json:\"-\"`\n\tClientTimestamp time.Time   `json:\"clientTimestamp\"`\n\tType            string      `json:\"type\"`\n\tLocation        string      `json:\"location\"`\n\tInstanceID      int         `json:\"instanceID\"`\n\tPayload         interface{} `json:\"payload\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"archive\/zip\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/kardianos\/osext\"\n)\n\nvar configFile = flag.String(\"config\", \"\", \"\")\n\ntype Config struct {\n\tFiles   []Action `json:\"files\"`\n\tCommand string   `json:\"command\"`\n\tArgs    []string `json:\"args\"`\n}\n\ntype Action struct {\n\tType        string `json:\"type\"`\n\tSource      string `json:\"source\"`\n\tDestination string `json:\"destination\"`\n}\n\nfunc main() {\n\tflag.Parse()\n\texecFolder, err := osext.ExecutableFolder()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tparts := filepath.SplitList(execFolder)\n\tbundleDir := \"${BUNDLE_DIR}\"\n\tif len(parts) >= 2 {\n\t\tbundleDir = filepath.Join(parts[0 : len(parts)-2]...)\n\t}\n\tif *configFile == \"\" {\n\t\tlog.Println(\"-config flag is not set, trying catalyst.json near binary\")\n\t\t*configFile = filepath.Join(execFolder, \"catalyst.json\")\n\t}\n\tf, err := os.Open(*configFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar config Config\n\tdec := json.NewDecoder(f)\n\terr = dec.Decode(&config)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tf.Close()\n\troot, err := catalystDir()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = os.Mkdir(root, 0755)\n\tif err != nil && !os.IsExist(err) {\n\t\tlog.Fatal(err)\n\t}\n\tfor _, file := range config.Files {\n\t\tsrc := file.Source\n\t\tdst := filepath.Join(root, file.Destination)\n\t\tif _, err := os.Stat(dst); err == nil {\n\t\t\tlog.Println(\"File exists: \", dst)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Println(\"Downloading\", src)\n\t\ttmp, err := ioutil.TempFile(\"\", \"catalyst-\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tresp, err := http.Get(src)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t_, err = io.Copy(tmp, resp.Body)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tresp.Body.Close()\n\t\tif resp.Header.Get(\"Content-Type\") == \"application\/zip\" {\n\t\t\tlog.Println(\"Extracting zip file\")\n\t\t\t_, err = tmp.Seek(0, os.SEEK_SET)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tfi, err := tmp.Stat()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\terr = os.Mkdir(dst, 0755)\n\t\t\tif err != nil && !os.IsExist(err) {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tr, err := zip.NewReader(tmp, fi.Size())\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tfor _, f := range r.File {\n\t\t\t\tlog.Println(f.Name)\n\t\t\t\tname := filepath.Join(dst, f.Name)\n\t\t\t\tfi := f.FileInfo()\n\t\t\t\tif fi.IsDir() {\n\t\t\t\t\terr = os.Mkdir(name, 0755)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tsrcfile, err := f.Open()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\tdstfile, err := os.Create(name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\t_, err = io.CopyN(dstfile, srcfile, fi.Size())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\terr = dstfile.Close()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t\t}\n\t\t\t\t\tsrcfile.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t\ttmp.Close()\n\t\t\tos.Remove(tmp.Name())\n\t\t} else {\n\t\t\ttmp.Close()\n\t\t\terr = os.Rename(tmp.Name(), dst)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\t}\n\tfor i := range config.Args {\n\t\tconfig.Args[i] = strings.Replace(config.Args[i], \"${CATALYST_DIR}\", root, -1)\n\t\tconfig.Args[i] = strings.Replace(config.Args[i], \"${BUNDLE_DIR}\", bundleDir, -1)\n\t}\n\tcmd := exec.Command(config.Command, config.Args...)\n\terr = cmd.Run()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>panic<commit_after>package main\n\nimport (\n\t\"archive\/zip\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/kardianos\/osext\"\n)\n\nvar configFile = flag.String(\"config\", \"\", \"\")\n\ntype Config struct {\n\tFiles   []Action `json:\"files\"`\n\tCommand string   `json:\"command\"`\n\tArgs    []string `json:\"args\"`\n}\n\ntype Action struct {\n\tType        string `json:\"type\"`\n\tSource      string `json:\"source\"`\n\tDestination string `json:\"destination\"`\n}\n\nfunc main() {\n\tflag.Parse()\n\texecFolder, err := osext.ExecutableFolder()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tparts := filepath.SplitList(execFolder)\n\tbundleDir := \"${BUNDLE_DIR}\"\n\tif len(parts) >= 2 {\n\t\tbundleDir = filepath.Join(parts[0 : len(parts)-2]...)\n\t}\n\tif *configFile == \"\" {\n\t\tlog.Println(\"-config flag is not set, trying catalyst.json near binary\")\n\t\t*configFile = filepath.Join(execFolder, \"catalyst.json\")\n\t}\n\tf, err := os.Open(*configFile)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tvar config Config\n\tdec := json.NewDecoder(f)\n\terr = dec.Decode(&config)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tf.Close()\n\troot, err := catalystDir()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\terr = os.Mkdir(root, 0755)\n\tif err != nil && !os.IsExist(err) {\n\t\tlog.Panic(err)\n\t}\n\tfor _, file := range config.Files {\n\t\tsrc := file.Source\n\t\tdst := filepath.Join(root, file.Destination)\n\t\tif _, err := os.Stat(dst); err == nil {\n\t\t\tlog.Println(\"File exists: \", dst)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Println(\"Downloading\", src)\n\t\ttmp, err := ioutil.TempFile(\"\", \"catalyst-\")\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\tresp, err := http.Get(src)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\t_, err = io.Copy(tmp, resp.Body)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t\tresp.Body.Close()\n\t\tif resp.Header.Get(\"Content-Type\") == \"application\/zip\" {\n\t\t\tlog.Println(\"Extracting zip file\")\n\t\t\t_, err = tmp.Seek(0, os.SEEK_SET)\n\t\t\tif err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t\tfi, err := tmp.Stat()\n\t\t\tif err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t\terr = os.Mkdir(dst, 0755)\n\t\t\tif err != nil && !os.IsExist(err) {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t\tr, err := zip.NewReader(tmp, fi.Size())\n\t\t\tif err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t\tfor _, f := range r.File {\n\t\t\t\tlog.Println(f.Name)\n\t\t\t\tname := filepath.Join(dst, f.Name)\n\t\t\t\tfi := f.FileInfo()\n\t\t\t\tif fi.IsDir() {\n\t\t\t\t\terr = os.Mkdir(name, 0755)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tsrcfile, err := f.Open()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t}\n\t\t\t\t\tdstfile, err := os.Create(name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t}\n\t\t\t\t\t_, err = io.CopyN(dstfile, srcfile, fi.Size())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t}\n\t\t\t\t\terr = dstfile.Close()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Panic(err)\n\t\t\t\t\t}\n\t\t\t\t\tsrcfile.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t\ttmp.Close()\n\t\t\tos.Remove(tmp.Name())\n\t\t} else {\n\t\t\ttmp.Close()\n\t\t\terr = os.Rename(tmp.Name(), dst)\n\t\t\tif err != nil {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\t}\n\tfor i := range config.Args {\n\t\tconfig.Args[i] = strings.Replace(config.Args[i], \"${CATALYST_DIR}\", root, -1)\n\t\tconfig.Args[i] = strings.Replace(config.Args[i], \"${BUNDLE_DIR}\", bundleDir, -1)\n\t}\n\tcmd := exec.Command(config.Command, config.Args...)\n\terr = cmd.Run()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/PuerkitoBio\/goquery\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc departureTime(departure string) (int, int) {\n\tret, _ := regexp.MatchString(\"^[0-9]{1,2}:[0-9]{1,2}$\", departure)\n\tvar hour int\n\tvar minute int\n\tif ret {\n\t\tre := regexp.MustCompile(\"^([0-9]{1,2}):([0-9]{1,2})$\")\n\t\tbs := []byte(departure)\n\t\tgroup := re.FindSubmatch(bs)\n\t\th, _ := strconv.Atoi(string(group[1]))\n\t\tm, _ := strconv.Atoi(string(group[2]))\n\t\tif h >= 0 && h < 24 && m >= 0 && m < 60 {\n\t\t\thour = h\n\t\t\tminute = m\n\t\t} else {\n\t\t\tnow := time.Now()\n\t\t\thour = now.Hour()\n\t\t\tminute = now.Minute()\n\t\t}\n\t} else {\n\t\tnow := time.Now()\n\t\thour = now.Hour()\n\t\tminute = now.Minute()\n\t}\n\treturn hour, minute\n}\n\nfunc getSelector() string {\n\tweekday := time.Now().Weekday().String()\n\tif weekday == \"Saturday\" {\n\t\treturn \"#tab-2 .standard2\"\n\t} else if weekday == \"Sunday\" {\n\t\treturn \"#tab-3 .standard2\"\n\t} else {\n\t\treturn \"#tab-1 .standard2\"\n\t}\n}\n\nfunc createTimetable(selector string) [][]int {\n\tvar timetable = make([][]int, 24)\n\tdoc, _ := goquery.NewDocument(\"http:\/\/www.keiseibus.co.jp\/jikoku\/bs_tt.php?key=04159_01a\")\n\tdoc.Find(selector).Each(func(_ int, s *goquery.Selection) {\n\t\ts.Find(\"tbody tr\").Each(func(_ int, s *goquery.Selection) {\n\t\t\tkey, _ := strconv.Atoi(s.Find(\"th\").Text())\n\t\t\ts.Find(\"td>span\").Each(func(_ int, s *goquery.Selection) {\n\t\t\t\ts.Find(\".notes\").Remove()\n\t\t\t\ts.Find(\"br\").Remove()\n\t\t\t\tif s.Text() != \"\" {\n\t\t\t\t\tvalue, _ := strconv.Atoi(s.Text())\n\t\t\t\t\ttimetable[key] = append(timetable[key], value)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t})\n\treturn timetable\n}\n\nfunc printTimes(hour int, minuteses []int) {\n\tfor _, v := range minuteses {\n\t\tif v < 10 {\n\t\t\tfmt.Println(fmt.Sprintf(\"%d:0%d \", hour, v))\n\t\t} else {\n\t\t\tfmt.Println(fmt.Sprintf(\"%d:%d \", hour, v))\n\t\t}\n\t}\n}\n\nfunc main() {\n\tvar departure string\n\tflag.StringVar(&departure, \"t\", \"\", \"specify departure time.\")\n\tflag.Parse()\n\thour, minute := departureTime(departure)\n\ttimetable := createTimetable(getSelector())\n\n\tarrivals := timetable[hour]\n\tresult := make([]int, 0, 3)\n\tfor _, v := range arrivals {\n\t\tif v > minute {\n\t\t\tresult = append(result, v)\n\t\t\tif len(result) >= 3 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tprintTimes(hour, result)\n\n\tif hour != 23 && len(result) < 3 {\n\t\tmax := 3 - len(result)\n\t\tarrivals = timetable[hour+1]\n\t\tresult2 := make([]int, 0, max)\n\t\tfor _, v := range arrivals {\n\t\t\tresult2 = append(result2, v)\n\t\t\tif len(result2) >= max {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tprintTimes(hour+1, result2)\n\t}\n}\n<commit_msg>use const value rather than hardcoded integer for number of result to show.<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/PuerkitoBio\/goquery\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n)\n\nconst (\n\tDefaultNumOfResultToShow = 3\n)\n\nfunc departureTime(departure string) (int, int) {\n\tret, _ := regexp.MatchString(\"^[0-9]{1,2}:[0-9]{1,2}$\", departure)\n\tvar hour int\n\tvar minute int\n\tif ret {\n\t\tre := regexp.MustCompile(\"^([0-9]{1,2}):([0-9]{1,2})$\")\n\t\tbs := []byte(departure)\n\t\tgroup := re.FindSubmatch(bs)\n\t\th, _ := strconv.Atoi(string(group[1]))\n\t\tm, _ := strconv.Atoi(string(group[2]))\n\t\tif h >= 0 && h < 24 && m >= 0 && m < 60 {\n\t\t\thour = h\n\t\t\tminute = m\n\t\t} else {\n\t\t\tnow := time.Now()\n\t\t\thour = now.Hour()\n\t\t\tminute = now.Minute()\n\t\t}\n\t} else {\n\t\tnow := time.Now()\n\t\thour = now.Hour()\n\t\tminute = now.Minute()\n\t}\n\treturn hour, minute\n}\n\nfunc getSelector() string {\n\tweekday := time.Now().Weekday().String()\n\tif weekday == \"Saturday\" {\n\t\treturn \"#tab-2 .standard2\"\n\t} else if weekday == \"Sunday\" {\n\t\treturn \"#tab-3 .standard2\"\n\t} else {\n\t\treturn \"#tab-1 .standard2\"\n\t}\n}\n\nfunc createTimetable(selector string) [][]int {\n\tvar timetable = make([][]int, 24)\n\tdoc, _ := goquery.NewDocument(\"http:\/\/www.keiseibus.co.jp\/jikoku\/bs_tt.php?key=04159_01a\")\n\tdoc.Find(selector).Each(func(_ int, s *goquery.Selection) {\n\t\ts.Find(\"tbody tr\").Each(func(_ int, s *goquery.Selection) {\n\t\t\tkey, _ := strconv.Atoi(s.Find(\"th\").Text())\n\t\t\ts.Find(\"td>span\").Each(func(_ int, s *goquery.Selection) {\n\t\t\t\ts.Find(\".notes\").Remove()\n\t\t\t\ts.Find(\"br\").Remove()\n\t\t\t\tif s.Text() != \"\" {\n\t\t\t\t\tvalue, _ := strconv.Atoi(s.Text())\n\t\t\t\t\ttimetable[key] = append(timetable[key], value)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t})\n\treturn timetable\n}\n\nfunc printTimes(hour int, minuteses []int) {\n\tfor _, v := range minuteses {\n\t\tif v < 10 {\n\t\t\tfmt.Println(fmt.Sprintf(\"%d:0%d \", hour, v))\n\t\t} else {\n\t\t\tfmt.Println(fmt.Sprintf(\"%d:%d \", hour, v))\n\t\t}\n\t}\n}\n\nfunc main() {\n\tvar departure string\n\tflag.StringVar(&departure, \"t\", \"\", \"specify departure time.\")\n\tflag.Parse()\n\thour, minute := departureTime(departure)\n\ttimetable := createTimetable(getSelector())\n\tnumOfResult := DefaultNumOfResultToShow\n\n\tarrivals := timetable[hour]\n\tresult := make([]int, 0, numOfResult)\n\tfor _, v := range arrivals {\n\t\tif v > minute {\n\t\t\tresult = append(result, v)\n\t\t\tif len(result) >= numOfResult {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tprintTimes(hour, result)\n\n\tif hour != 23 && len(result) < numOfResult {\n\t\tmax := numOfResult - len(result)\n\t\tarrivals = timetable[hour+1]\n\t\tresult2 := make([]int, 0, max)\n\t\tfor _, v := range arrivals {\n\t\t\tresult2 = append(result2, v)\n\t\t\tif len(result2) >= max {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tprintTimes(hour+1, result2)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ csvsplit: Split a .csv into multiple files.\n\/\/ https:\/\/github.com\/JeffPaine\/csvsplit\npackage main\n\nimport (\n\t\"encoding\/csv\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\nvar (\n\tflagRecords = flag.Int(\"records\", 0, \"The number of records per output file\")\n\tflagOutput  = flag.String(\"output\", \"\", \"Filename \/ path of the output file (leave blank for current directory)\")\n\tflagHeaders = flag.Int(\"headers\", 0, \"Number of header lines in the input file to preserve in each output file\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\t\/\/ Sanity check command line flags.\n\tcheckFlags()\n\n\t\/\/ Get input from a given file or stdin\n\tvar r *csv.Reader\n\tif len(flag.Args()) == 1 {\n\t\tf, err := os.Open(flag.Args()[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer f.Close()\n\t\tr = csv.NewReader(f)\n\t} else {\n\t\tr = csv.NewReader(os.Stdin)\n\t}\n\n\t\/\/ Read the input .csv file line by line. Save to a new file after reaching\n\t\/\/ the amount of records prescribed by the -records flag.\n\tvar recs [][]string\n\tcount := 1\n\tfor {\n\t\trecord, err := r.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\trecs = append(recs, record)\n\t\tif len(recs) == *flagRecords {\n\t\t\tsave(&recs, count)\n\t\t\t\/\/ Reset records to include just the header lines (if any)\n\t\t\trecs = recs[:*flagHeaders]\n\t\t\tcount++\n\t\t}\n\t}\n\tif len(recs) > 0 {\n\t\tsave(&recs, count)\n\t}\n}\n\n\/\/ save() saves the given *[][]string of csv data to a .csv file. Files are named\n\/\/ sequentially in the form of 1.csv, 2.csv, etc.\nfunc save(recs *[][]string, c int) {\n\tname := fmt.Sprintf(\"%v%d%v\", *flagOutput, c, \".csv\")\n\n\t\/\/ Make sure we don't overwrite existing files\n\tif _, err := os.Stat(name); err == nil {\n\t\tlog.Fatal(\"file exists: \", name)\n\t}\n\n\t\/\/ If a directory is specified, make sure that directory exists\n\tif filepath.Dir(*flagOutput) != \".\" {\n\t\t_, err := os.Stat(filepath.Dir(*flagOutput))\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"no such directory:\", *flagOutput)\n\t\t}\n\t}\n\n\tf, err := os.Create(name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\tw := csv.NewWriter(f)\n\tw.WriteAll(*recs)\n}\n\n\/\/ checkFlags checks our command line flags for basic sanity.\nfunc checkFlags() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintln(os.Stderr, \"usage: csvsplit [options] -records <number of records> <file>\")\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\t}\n\n\tif *flagRecords < 1 {\n\t\tfmt.Fprintln(os.Stderr, \"-records must be > 1\")\n\t\tflag.Usage()\n\t}\n\n\tif *flagHeaders < 0 {\n\t\tfmt.Fprintln(os.Stderr, \"-headers must be > 0\")\n\t\tflag.Usage()\n\t}\n\n\tif *flagHeaders >= *flagRecords {\n\t\tfmt.Fprintln(os.Stderr, \"-headers must be >= -records\")\n\t\tflag.Usage()\n\t}\n}\n<commit_msg>Put docs at top of main to be more golang-y<commit_after>\/*\ncsvsplit\n\nSplit a .csv into multiple files. https:\/\/github.com\/JeffPaine\/csvsplit\n\nInstall\n    # The command below requires you to have Go installed\n    # https:\/\/golang.org\/doc\/install\n    $ go get github.com\/JeffPaine\/csvsplit\n\nExamples\n    # Basic usage\n    $ csvsplit -records <number of records> <file>\n\n    # Split file.csv into files with 300 records a piece\n    $ csvplit -records 300 file.csv\n\n    # Split file.csv into files with 37 records a piece into the subfolder 'stuff'\n    $ csvplit -records 37 -output stuff\/ file.csv\n\n    # Split file.csv into files with 40 records a piece and two header lines\n    $ csvplit -records 40 -headers 2 file.csv\n\n    # Accept csv data from stdin\n    $ cat file.csv | csvsplit -records 20\n\n    # You can use the -output flag to customize the resulting filenames.\n    # The below will generate custom_filename-001.csv, custom_filename-002.csv, etc.\n    $ cat file.csv | csvsplit -records 20 -output custom_filename-\n\nFlags\n    -records: Number of records per file  \n    -output: Output filename \/ path (optional)  \n    -headers: Number of header lines in the input file to add to each ouput file (optional, default=0)\n*\/\n\npackage main\n\nimport (\n\t\"encoding\/csv\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\nvar (\n\tflagRecords = flag.Int(\"records\", 0, \"The number of records per output file\")\n\tflagOutput  = flag.String(\"output\", \"\", \"Filename \/ path of the output file (leave blank for current directory)\")\n\tflagHeaders = flag.Int(\"headers\", 0, \"Number of header lines in the input file to preserve in each output file\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\t\/\/ Sanity check command line flags.\n\tcheckFlags()\n\n\t\/\/ Get input from a given file or stdin\n\tvar r *csv.Reader\n\tif len(flag.Args()) == 1 {\n\t\tf, err := os.Open(flag.Args()[0])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer f.Close()\n\t\tr = csv.NewReader(f)\n\t} else {\n\t\tr = csv.NewReader(os.Stdin)\n\t}\n\n\t\/\/ Read the input .csv file line by line. Save to a new file after reaching\n\t\/\/ the amount of records prescribed by the -records flag.\n\tvar recs [][]string\n\tcount := 1\n\tfor {\n\t\trecord, err := r.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\trecs = append(recs, record)\n\t\tif len(recs) == *flagRecords {\n\t\t\tsave(&recs, count)\n\t\t\t\/\/ Reset records to include just the header lines (if any)\n\t\t\trecs = recs[:*flagHeaders]\n\t\t\tcount++\n\t\t}\n\t}\n\tif len(recs) > 0 {\n\t\tsave(&recs, count)\n\t}\n}\n\n\/\/ save() saves the given *[][]string of csv data to a .csv file. Files are named\n\/\/ sequentially in the form of 1.csv, 2.csv, etc.\nfunc save(recs *[][]string, c int) {\n\tname := fmt.Sprintf(\"%v%d%v\", *flagOutput, c, \".csv\")\n\n\t\/\/ Make sure we don't overwrite existing files\n\tif _, err := os.Stat(name); err == nil {\n\t\tlog.Fatal(\"file exists: \", name)\n\t}\n\n\t\/\/ If a directory is specified, make sure that directory exists\n\tif filepath.Dir(*flagOutput) != \".\" {\n\t\t_, err := os.Stat(filepath.Dir(*flagOutput))\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"no such directory:\", *flagOutput)\n\t\t}\n\t}\n\n\tf, err := os.Create(name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer f.Close()\n\n\tw := csv.NewWriter(f)\n\tw.WriteAll(*recs)\n}\n\n\/\/ checkFlags checks our command line flags for basic sanity.\nfunc checkFlags() {\n\tflag.Usage = func() {\n\t\tfmt.Fprintln(os.Stderr, \"usage: csvsplit [options] -records <number of records> <file>\")\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\t}\n\n\tif *flagRecords < 1 {\n\t\tfmt.Fprintln(os.Stderr, \"-records must be > 1\")\n\t\tflag.Usage()\n\t}\n\n\tif *flagHeaders < 0 {\n\t\tfmt.Fprintln(os.Stderr, \"-headers must be > 0\")\n\t\tflag.Usage()\n\t}\n\n\tif *flagHeaders >= *flagRecords {\n\t\tfmt.Fprintln(os.Stderr, \"-headers must be >= -records\")\n\t\tflag.Usage()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nThe MIT License (MIT)\n\ntransfer.sh was originally written by and\nCopyright (c) 2014 DutchCoders [https:\/\/github.com\/dutchcoders\/]\n\nSome modifications\nCopyright (c) 2015 John Ko\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/PuerkitoBio\/ghost\/handlers\"\n\t\"github.com\/gorilla\/mux\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n)\n\nconst SERVER_INFO = \"dtfc\"\nconst SERVER_VERSION = \"0.0.1\"\n\n\/\/ we use these commands to reduce the amount of garbage collection golang needs to do\nconst cmdSHASUMFreeBSD = \"\/usr\/local\/bin\/shasum\"\n\n\/\/ or on Apple using Macports\nconst cmdSHASUMApple = \"\/opt\/local\/bin\/shasum\"\nconst cmdSHA512 = \"\/sbin\/sha512\"\nconst cmdTAIL = \"\/usr\/bin\/tail\"\n\nconst timeLayout = \"2006-01-02 15:04:05 MST\"\nconst timeHTTPLayout = \"Mon, 2 Jan 2006 15:04:05 MST\"\n\n\/\/ parse request with maximum memory of _24Kilobits\nconst _24K = (1 << 20) * 24\n\nvar config struct {\n\tALLOWDELETE string\n\tALLOWGET    string\n\tALLOWPUT    string\n\tTemp        string\n\tME          string\n\tPEERS       []string\n}\n\nvar storage Storage\n\nvar cmdSHASUM string\n\nfunc init() {\n\tconfig.Temp = os.TempDir()\n}\n\nfunc main() {\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tvar err error\n\tif _, err = os.Lstat(cmdSHASUMFreeBSD); err == nil {\n\t\tcmdSHASUM = cmdSHASUMFreeBSD\n\t}\n\tif _, err = os.Lstat(cmdSHASUMApple); err == nil {\n\t\tcmdSHASUM = cmdSHASUMApple\n\t}\n\tif _, err = os.Lstat(cmdSHASUM); err != nil {\n\t\tlog.Panic(\"Error while looking for shasum executable.\")\n\t}\n\tif _, err = os.Lstat(cmdTAIL); err != nil {\n\t\tlog.Panic(\"Error while looking for tail executable.\")\n\t}\n\n\tport := flag.String(\"port\", \"8080\", \"port number, default: 8080\")\n\ttemp := flag.String(\"temp\", config.Temp, \"\")\n\tbasedir := flag.String(\"basedir\", \"\", \"\")\n\tlogpath := flag.String(\"log\", \"\", \"\")\n\tprovider := flag.String(\"provider\", \"local\", \"\")\n\tallowdelete := flag.String(\"allowdelete\", \"true\", \"true or false, default: true\")\n\tallowget := flag.String(\"allowget\", \"true\", \"true or false, default: true\")\n\tallowput := flag.String(\"allowput\", \"true\", \"true or false, default: true\")\n\tme := flag.String(\"me\", \"\", \"example http:\/\/127.0.0.1:8080\/\")\n\tmelist := flag.String(\"melist\", \"\", \"text file with first line as me\")\n\tpeerlist := flag.String(\"peerlist\", \"\", \"text file with one peer per line\")\n\n\tflag.Parse()\n\n\tif *logpath != \"\" {\n\t\tf, err := os.OpenFile(*logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error opening file: %v\", err)\n\t\t}\n\t\tdefer f.Close()\n\t\tlog.SetOutput(f)\n\t}\n\n\tconfig.Temp = *temp\n\tconfig.ALLOWDELETE = *allowdelete\n\tconfig.ALLOWGET = *allowget\n\tconfig.ALLOWPUT = *allowput\n\t\/\/ usually string empty test is == \"\"\n\t\/\/ the following test can be nil because *string can be nil\n\tif me != nil {\n\t\tconfig.ME = *me\n\t}\n\tif (config.ME == \"\") && (melist != nil) {\n\t\tvar arraystring []string\n\t\tarraystring, err = readLines(*melist)\n\t\tif err != nil {\n\t\t\tlog.Panic(\"Error while reading melist.\", err)\n\t\t} else {\n\t\t\tconfig.ME = arraystring[0]\n\t\t}\n\t}\n\tif config.ME == \"\" {\n\t\tlog.Panic(\"Error while trying to figure out me.\")\n\t}\n\tlog.Printf(\"config.ME: %s\", config.ME)\n\tconfig.PEERS, err = readLines(*peerlist)\n\tif err != nil {\n\t\tlog.Panic(\"Error while reading peerlist.\", err)\n\t}\n\n\tr := mux.NewRouter()\n\n\tr.HandleFunc(\"\/health.html\", healthHandler).Methods(\"GET\")\n\tr.HandleFunc(\"\/{hash}\", getHandler).Methods(\"GET\")\n\n\t\/\/r.HandleFunc(\"\/{hash}\", headHandler).Methods(\"HEAD\")\n\n\tr.HandleFunc(\"\/{filename}\", putHandler).Methods(\"PUT\")\n\n\tr.NotFoundHandler = http.HandlerFunc(notFoundHandler)\n\n\tswitch *provider {\n\tcase \"local\":\n\t\tif *basedir == \"\" {\n\t\t\tlog.Panic(\"Error basedir not set.\")\n\t\t}\n\t\tstorage, err = NewLocalStorage(*basedir)\n\t}\n\tif err != nil {\n\t\tlog.Panic(\"Error while creating storage.\", err)\n\t}\n\n\tlog.Printf(\"%s\/%s server started. listening on port: %v\",\n\t\tSERVER_INFO, SERVER_VERSION, *port)\n\tlog.Printf(\"using temp folder: %s, using storage provider: %s\",\n\t\tconfig.Temp, *provider)\n\tlog.Printf(\"allow delete: %s, allow get: %s, allow put: %s\",\n\t\tconfig.ALLOWDELETE, config.ALLOWGET, config.ALLOWPUT)\n\tlog.Printf(\"---------------------------\")\n\n\ts := &http.Server{\n\t\tAddr:    fmt.Sprintf(\":%s\", *port),\n\t\tHandler: handlers.PanicHandler(RedirectHandler(handlers.LogHandler(r, handlers.NewLogOptions(log.Printf, \"_default_\"))), nil),\n\t}\n\n\tlog.Panic(s.ListenAndServe())\n\tlog.Printf(\"Server stopped.\")\n}\n<commit_msg>trim config.ME and test if empty<commit_after>\/*\nThe MIT License (MIT)\n\ntransfer.sh was originally written by and\nCopyright (c) 2014 DutchCoders [https:\/\/github.com\/dutchcoders\/]\n\nSome modifications\nCopyright (c) 2015 John Ko\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/PuerkitoBio\/ghost\/handlers\"\n\t\"github.com\/gorilla\/mux\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n)\n\nconst SERVER_INFO = \"dtfc\"\nconst SERVER_VERSION = \"0.0.1\"\n\n\/\/ we use these commands to reduce the amount of garbage collection golang needs to do\nconst cmdSHASUMFreeBSD = \"\/usr\/local\/bin\/shasum\"\n\n\/\/ or on Apple using Macports\nconst cmdSHASUMApple = \"\/opt\/local\/bin\/shasum\"\nconst cmdSHA512 = \"\/sbin\/sha512\"\nconst cmdTAIL = \"\/usr\/bin\/tail\"\n\nconst timeLayout = \"2006-01-02 15:04:05 MST\"\nconst timeHTTPLayout = \"Mon, 2 Jan 2006 15:04:05 MST\"\n\n\/\/ parse request with maximum memory of _24Kilobits\nconst _24K = (1 << 20) * 24\n\nvar config struct {\n\tALLOWDELETE string\n\tALLOWGET    string\n\tALLOWPUT    string\n\tTemp        string\n\tME          string\n\tPEERS       []string\n}\n\nvar storage Storage\n\nvar cmdSHASUM string\n\nfunc init() {\n\tconfig.Temp = os.TempDir()\n}\n\nfunc main() {\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tvar err error\n\tif _, err = os.Lstat(cmdSHASUMFreeBSD); err == nil {\n\t\tcmdSHASUM = cmdSHASUMFreeBSD\n\t}\n\tif _, err = os.Lstat(cmdSHASUMApple); err == nil {\n\t\tcmdSHASUM = cmdSHASUMApple\n\t}\n\tif _, err = os.Lstat(cmdSHASUM); err != nil {\n\t\tlog.Panic(\"Error while looking for shasum executable.\")\n\t}\n\tif _, err = os.Lstat(cmdTAIL); err != nil {\n\t\tlog.Panic(\"Error while looking for tail executable.\")\n\t}\n\n\tport := flag.String(\"port\", \"8080\", \"port number, default: 8080\")\n\ttemp := flag.String(\"temp\", config.Temp, \"\")\n\tbasedir := flag.String(\"basedir\", \"\", \"\")\n\tlogpath := flag.String(\"log\", \"\", \"\")\n\tprovider := flag.String(\"provider\", \"local\", \"\")\n\tallowdelete := flag.String(\"allowdelete\", \"true\", \"true or false, default: true\")\n\tallowget := flag.String(\"allowget\", \"true\", \"true or false, default: true\")\n\tallowput := flag.String(\"allowput\", \"true\", \"true or false, default: true\")\n\tme := flag.String(\"me\", \"\", \"example http:\/\/127.0.0.1:8080\/\")\n\tmelist := flag.String(\"melist\", \"\", \"text file with first line as me\")\n\tpeerlist := flag.String(\"peerlist\", \"\", \"text file with one peer per line\")\n\n\tflag.Parse()\n\n\tif *logpath != \"\" {\n\t\tf, err := os.OpenFile(*logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error opening file: %v\", err)\n\t\t}\n\t\tdefer f.Close()\n\t\tlog.SetOutput(f)\n\t}\n\n\tconfig.Temp = *temp\n\tconfig.ALLOWDELETE = *allowdelete\n\tconfig.ALLOWGET = *allowget\n\tconfig.ALLOWPUT = *allowput\n\t\/\/ usually string empty test is == \"\"\n\t\/\/ the following test can be nil because *string can be nil\n\tif me != nil {\n\t\tconfig.ME = *me\n\t}\n\tif (config.ME == \"\") && (melist != nil) {\n\t\tvar arraystring []string\n\t\tarraystring, err = readLines(*melist)\n\t\tif err != nil {\n\t\t\tlog.Panic(\"Error while reading melist.\", err)\n\t\t} else {\n\t\t\tconfig.ME = arraystring[0]\n\t\t}\n\t}\n\tif strings.Trim(config.ME, \" \") == \"\" {\n\t\tlog.Panic(\"Error while trying to figure out me.\")\n\t}\n\tlog.Printf(\"config.ME: %s\", config.ME)\n\tconfig.PEERS, err = readLines(*peerlist)\n\tif err != nil {\n\t\tlog.Panic(\"Error while reading peerlist.\", err)\n\t}\n\n\tr := mux.NewRouter()\n\n\tr.HandleFunc(\"\/health.html\", healthHandler).Methods(\"GET\")\n\tr.HandleFunc(\"\/{hash}\", getHandler).Methods(\"GET\")\n\n\t\/\/r.HandleFunc(\"\/{hash}\", headHandler).Methods(\"HEAD\")\n\n\tr.HandleFunc(\"\/{filename}\", putHandler).Methods(\"PUT\")\n\n\tr.NotFoundHandler = http.HandlerFunc(notFoundHandler)\n\n\tswitch *provider {\n\tcase \"local\":\n\t\tif *basedir == \"\" {\n\t\t\tlog.Panic(\"Error basedir not set.\")\n\t\t}\n\t\tstorage, err = NewLocalStorage(*basedir)\n\t}\n\tif err != nil {\n\t\tlog.Panic(\"Error while creating storage.\", err)\n\t}\n\n\tlog.Printf(\"%s\/%s server started. listening on port: %v\",\n\t\tSERVER_INFO, SERVER_VERSION, *port)\n\tlog.Printf(\"using temp folder: %s, using storage provider: %s\",\n\t\tconfig.Temp, *provider)\n\tlog.Printf(\"allow delete: %s, allow get: %s, allow put: %s\",\n\t\tconfig.ALLOWDELETE, config.ALLOWGET, config.ALLOWPUT)\n\tlog.Printf(\"---------------------------\")\n\n\ts := &http.Server{\n\t\tAddr:    fmt.Sprintf(\":%s\", *port),\n\t\tHandler: handlers.PanicHandler(RedirectHandler(handlers.LogHandler(r, handlers.NewLogOptions(log.Printf, \"_default_\"))), nil),\n\t}\n\n\tlog.Panic(s.ListenAndServe())\n\tlog.Printf(\"Server stopped.\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"net\/http\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"github.com\/dghubble\/sling\"\n)\n\nvar (\n\tcaptureFlag = kingpin.Command(\"capture\", \"Set hoverfly to capture mode\")\n)\n\n\nfunc main() {\n\tswitch kingpin.Parse() {\n\t\tcase \"capture\":\n\t\t\tcaptureHandler()\n\t}\n}\n\nfunc captureHandler() {\n\trequest, _ := sling.New().Post(\"http:\/\/localhost:8888\/api\/state\").Body(strings.NewReader(`{\"mode\":\"capture\"}`)).Request()\n\tresponse, _ := http.DefaultClient.Do(request)\n\tdefer response.Body.Close()\n\tfmt.Println(response.Status)\n\tfmt.Println(\"I am capturing\")\n}\n<commit_msg>Refactored a little bit ready for more modes.<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"net\/http\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"github.com\/dghubble\/sling\"\n)\n\nvar (\n\tcaptureFlag = kingpin.Command(\"capture\", \"Set hoverfly to capture mode\")\n)\n\n\nfunc main() {\n\tswitch kingpin.Parse() {\n\t\tcase \"capture\":\n\t\t\tcaptureHandler()\n\t}\n}\n\nfunc captureHandler() {\n\tresponse := setHoverflyMode(\"capture\")\n\tdefer response.Body.Close()\n\tfmt.Println(\"Hoverfly set to capture mode\")\n}\n\nfunc setHoverflyMode(mode string) (*http.Response) {\n\trequest, _ := sling.New().Post(\"http:\/\/localhost:8888\/api\/state\").Body(strings.NewReader(`{\"mode\":\"` + mode + `\"}`)).Request()\n\tresponse, _ := http.DefaultClient.Do(request)\n\treturn response\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n    \"log\"\n    \"net\/http\"\n)\n\n\nfunc pingServer(w http.ResponseWriter, req *http.Request) {\n    w.Write([]byte(\"ping Drone!\"))\n}\n\nfunc main() {\n    http.HandleFunc(\"\/\", pingServer)\n    err := http.ListenAndServe(\":8080\", nil)\n    if err != nil {\n        log.Fatal(\"ListenAndServe: \", err)\n    }\n}\n<commit_msg>trigger<commit_after>package main\n\nimport (\n    \"log\"\n    \"net\/http\"\n)\n\n\nfunc pingServer(w http.ResponseWriter, req *http.Request) {\n    w.Write([]byte(\"Hello Drone!\"))\n}\n\nfunc main() {\n    http.HandleFunc(\"\/\", pingServer)\n    err := http.ListenAndServe(\":8080\", nil)\n    if err != nil {\n        log.Fatal(\"ListenAndServe: \", err)\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n)\n\nconst VERSION = \"0.0.1\"\n\nvar fset *token.FileSet\n\nfunc main() {\n\tif len(os.Args) != 2 {\n\t\tprintUsage()\n\t\tos.Exit(1)\n\t}\n\n\tfilename := os.Args[1]\n\n\tfset = token.NewFileSet()\n\ttags := make(sort.StringSlice, 0)\n\n\tf, err := parser.ParseFile(fset, filename, nil, 0)\n\tif err != nil {\n\t\t\/\/ TODO: fix error handling; it should still result in a valid ctags file\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ header\n\ttags = append(tags, \"!_TAG_FILE_FORMAT\\t2\\t\")\n\ttags = append(tags, \"!_TAG_FILE_SORTED\\t1\\t\")\n\n\t\/\/ package\n\tif f.Name != nil {\n\t\ttags = append(tags, createTag(f.Name.Name, f.Name.Pos(), \"p\").String())\n\t}\n\n\t\/\/ imports\n\tfor _, im := range f.Imports {\n\t\tif im.Path != nil {\n\t\t\tname := strings.Trim(im.Path.Value, \"\\\"\")\n\t\t\ttags = append(tags, createTag(name, im.Path.Pos(), \"i\").String())\n\t\t}\n\t}\n\n\t\/\/ declarations\n\tfor _, d := range f.Decls {\n\t\tswitch decl := d.(type) {\n\t\tcase *ast.FuncDecl:\n\t\t\ttags = append(tags, createFuncTag(decl))\n\t\tcase *ast.GenDecl:\n\t\t\tfor _, s := range decl.Specs {\n\t\t\t\tif ts, ok := s.(*ast.TypeSpec); ok {\n\t\t\t\t\ttags = append(tags, createTag(ts.Name.Name, ts.Pos(), \"s\").String())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ sort and print tags\n\tsort.Sort(tags)\n\tfor _, tag := range tags {\n\t\tfmt.Println(tag)\n\t}\n}\n\nfunc printUsage() {\n\tfmt.Printf(\"gotags version %s\\n\\n\", VERSION)\n\tfmt.Printf(\"Usage: %s file\\n\", os.Args[0])\n}\n\nfunc createTag(name string, pos token.Pos, tagtype string) *Tag {\n\treturn NewTag(name, fset.File(pos).Name(), fset.Position(pos).Line, tagtype)\n}\n\nfunc createFuncTag(f *ast.FuncDecl) string {\n\tif f == nil || f.Name == nil {\n\t\treturn \"\"\n\t}\n\n\ttag := createTag(f.Name.Name, f.Pos(), \"f\")\n\n\t\/\/ access\n\tif ast.IsExported(tag.Name) {\n\t\ttag.Fields[\"access\"] = \"public\"\n\t} else {\n\t\ttag.Fields[\"access\"] = \"private\"\n\t}\n\n\t\/\/ signature\n\tvar sig bytes.Buffer\n\tsig.WriteByte('(')\n\tfor i, param := range f.Type.Params.List {\n\t\t\/\/ parameter names\n\t\tfor j, n := range param.Names {\n\t\t\tsig.WriteString(n.Name)\n\t\t\tif j < len(param.Names)-1 {\n\t\t\t\tsig.WriteString(\", \")\n\t\t\t}\n\t\t}\n\n\t\t\/\/ parameter type\n\t\tif t, ok := param.Type.(*ast.Ident); ok {\n\t\t\tsig.WriteByte(' ')\n\t\t\tsig.WriteString(t.Name)\n\t\t}\n\n\t\tif i < len(f.Type.Params.List)-1 {\n\t\t\tsig.WriteString(\", \")\n\t\t}\n\t}\n\tsig.WriteByte(')')\n\ttag.Fields[\"signature\"] = sig.String()\n\n\t\/\/ TODO: receiver\n\n\treturn tag.String()\n}\n<commit_msg>Correctly generate function signatures<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n)\n\nconst VERSION = \"0.0.1\"\n\nvar fset *token.FileSet\n\nfunc main() {\n\tif len(os.Args) != 2 {\n\t\tprintUsage()\n\t\tos.Exit(1)\n\t}\n\n\tfilename := os.Args[1]\n\n\tfset = token.NewFileSet()\n\ttags := make(sort.StringSlice, 0)\n\n\tf, err := parser.ParseFile(fset, filename, nil, 0)\n\tif err != nil {\n\t\t\/\/ TODO: fix error handling; it should still result in a valid ctags file\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ header\n\ttags = append(tags, \"!_TAG_FILE_FORMAT\\t2\\t\")\n\ttags = append(tags, \"!_TAG_FILE_SORTED\\t1\\t\")\n\n\t\/\/ package\n\tif f.Name != nil {\n\t\ttags = append(tags, createTag(f.Name.Name, f.Name.Pos(), \"p\").String())\n\t}\n\n\t\/\/ imports\n\tfor _, im := range f.Imports {\n\t\tif im.Path != nil {\n\t\t\tname := strings.Trim(im.Path.Value, \"\\\"\")\n\t\t\ttags = append(tags, createTag(name, im.Path.Pos(), \"i\").String())\n\t\t}\n\t}\n\n\t\/\/ declarations\n\tfor _, d := range f.Decls {\n\t\tswitch decl := d.(type) {\n\t\tcase *ast.FuncDecl:\n\t\t\ttags = append(tags, createFuncTag(decl))\n\t\tcase *ast.GenDecl:\n\t\t\tfor _, s := range decl.Specs {\n\t\t\t\tif ts, ok := s.(*ast.TypeSpec); ok {\n\t\t\t\t\ttags = append(tags, createTag(ts.Name.Name, ts.Pos(), \"s\").String())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ sort and print tags\n\tsort.Sort(tags)\n\tfor _, tag := range tags {\n\t\tfmt.Println(tag)\n\t}\n}\n\nfunc printUsage() {\n\tfmt.Printf(\"gotags version %s\\n\\n\", VERSION)\n\tfmt.Printf(\"Usage: %s file\\n\", os.Args[0])\n}\n\nfunc createTag(name string, pos token.Pos, tagtype string) *Tag {\n\treturn NewTag(name, fset.File(pos).Name(), fset.Position(pos).Line, tagtype)\n}\n\nfunc createFuncTag(f *ast.FuncDecl) string {\n\tif f == nil || f.Name == nil {\n\t\treturn \"\"\n\t}\n\n\ttag := createTag(f.Name.Name, f.Pos(), \"f\")\n\n\t\/\/ access\n\tif ast.IsExported(tag.Name) {\n\t\ttag.Fields[\"access\"] = \"public\"\n\t} else {\n\t\ttag.Fields[\"access\"] = \"private\"\n\t}\n\n\t\/\/ signature\n\tvar sig bytes.Buffer\n\tsig.WriteByte('(')\n\tfor i, param := range f.Type.Params.List {\n\t\t\/\/ parameter names\n\t\tfor j, n := range param.Names {\n\t\t\tsig.WriteString(n.Name)\n\t\t\tif j < len(param.Names)-1 {\n\t\t\t\tsig.WriteString(\", \")\n\t\t\t}\n\t\t}\n\n\t\t\/\/ parameter type\n\t\tsig.WriteByte(' ')\n\t\tsig.WriteString(getParamType(param.Type))\n\n\t\tif i < len(f.Type.Params.List)-1 {\n\t\t\tsig.WriteString(\", \")\n\t\t}\n\t}\n\tsig.WriteByte(')')\n\ttag.Fields[\"signature\"] = sig.String()\n\n\t\/\/ TODO: receiver\n\n\treturn tag.String()\n}\n\nfunc getParamType(node ast.Node) (paramType string) {\n\tswitch t := node.(type) {\n\tcase *ast.Ident:\n\t\tparamType = t.Name\n\tcase *ast.StarExpr:\n\t\tparamType = \"*\" + getParamType(t.X)\n\tcase *ast.SelectorExpr:\n\t\tparamType = getParamType(t.X) + \".\" + getParamType(t.Sel)\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/hawx\/img\/utils\"\n\t\"github.com\/hawx\/hadfield\"\n\t\"bytes\"\n\t\"path\/filepath\"\n\t\"os\/exec\"\n\t\"os\"\n\t\"strings\"\n\t\"flag\"\n)\n\ntype External struct {\n\tPath, Usage, Short, Long  string\n}\n\nfunc (e External) String() string {\n\treturn \"External{\" + e.Path + \"}\"\n}\n\nfunc (e *External) Name() string {\n\treturn filepath.Base(e.Path)[4:]\n}\n\nfunc (e *External) Data() interface{} {\n\treturn map[string]interface{}{\n\t\t\"Callable\": e.Callable(),\n\t\t\"Category\": e.Category(),\n\t\t\"Usage\":    e.Usage,\n\t\t\"Short\":    e.Short,\n\t\t\"Long\":     e.Long,\n\t\t\"Name\":     e.Name(),\n\t}\n}\n\nfunc (e *External) Category() string {\n\treturn \"External\"\n}\n\nfunc (e *External) Callable() bool {\n\treturn true\n}\n\nfunc (e *External) Call(cmd hadfield.Interface, templates hadfield.Templates, args []string) {\n\t\/\/ args[0] is set to the executable's name, so we can safely replace it with\n\t\/\/ the output type. This is always going to be something, so needs to be\n\t\/\/ checked for, removed, and respected!\n\targs[0] = string(utils.Output)\n\n\tex := exec.Command(e.Path, args...)\n\tex.Stdin  = os.Stdin\n\tex.Stdout = os.Stdout\n\tex.Stderr = os.Stderr\n\terr := ex.Run()\n\tif err != nil {\n\t\tos.Exit(2)\n\t}\n\treturn\n}\n\nfunc findExternalsIn(dir string) ([]string, error) {\n\tfound := []string{}\n\n\tdirs, _ := filepath.Glob(dir + \"\/\" + \"*\")\n\tfor _, possible := range dirs {\n\t\tif strings.HasPrefix(filepath.Base(possible), \"img-\") {\n\t\t\tfound = append(found, possible)\n\t\t}\n\t}\n\n\treturn found, nil\n}\n\nfunc runExternal(ext string, flags... string) string {\n\tcmd := exec.Command(ext, flags...)\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\terr := cmd.Run()\n\tif err != nil {\n\t\t\/\/ handle\n\t}\n\treturn out.String()\n}\n\nfunc lookupExternals() hadfield.Commands {\n\tfound := hadfield.Commands{}\n\tpathenv := os.Getenv(\"PATH\")\n\toutput := string(utils.Output)\n\n\tfor _, dir := range strings.Split(pathenv, \":\") {\n\t\tif dir == \"\" {\n\t\t\tdir = \".\"\n\t\t}\n\n\t\tif exts, err := findExternalsIn(dir); err == nil {\n\t\t\tfor _, ext := range exts {\n\t\t\t\tusage := runExternal(ext, output, \"--usage\")\n\t\t\t\tshort := runExternal(ext, output, \"--short\")\n\t\t\t\tlong  := runExternal(ext, output, \"--long\")\n\n\t\t\t\tfound = append(found, &External{ext, usage, short, long})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn found\n}\n\n\/\/ Commands list the available commands and help topics. The order here is the\n\/\/ order in which they are printed by 'img help'.\nvar commands = hadfield.Commands{\n\tcmdBlend,\n\tcmdBlur,\n\tcmdChannel,\n\tcmdContrast,\n\tcmdCrop,\n\tcmdGamma,\n\tcmdGreyscale,\n\tcmdHxl,\n\tcmdLevels,\n\tcmdPixelate,\n\tcmdPxl,\n\tcmdSharpen,\n\tcmdShuffle,\n\tcmdTint,\n\tcmdVxl,\n}\n\nvar templates = hadfield.Templates{\nUsage: `Usage: img [command] [arguments]\n\n\tImg is a set of image manipulation tools. They each take an image from STDIN\n\tand print the result to STDOUT (in some cases they may also require a second\n\timage, consult the help for the particular command).\n\n\tAn example usage,\n\n\t\t$ img greyscale < input.png > output.png\n\n\tAs standard input and output are used throughout, commands can be easily\n\tchained together using pipes (and parentheses for clarity),\n\n\t\t$ (img greyscale | img pxl | img contrast --by 0.05) < input.png > output.png\n\n\tCommands: {{range .}}{{if .Callable}}{{if category . \"Command\"}}\n\t\t{{.Name | printf \"%-15s\"}} # {{.Short | trim}}{{end}}{{end}}{{end}}\n\n\tExternal Commands: {{range .}}{{if .Callable}}{{if category . \"External\"}}\n\t\t{{.Name | printf \"%-15s\"}} # {{.Short | trim}}{{end}}{{end}}{{end}}\n\nUse \"img help [command]\" for more information about a command.\n`,\nHelp: `{{if .Callable}}Usage: img {{.Usage}}\n{{end}}{{.Long}}\n`,\n}\n\nvar builtIn = []string{\n\t\"blend\", \"blur\", \"channel\", \"contrast\", \"crop\", \"gamma\", \"greyscale\", \"hxl\",\n\t\"levels\", \"pixelate\", \"pxl\", \"sharpen\", \"shuffle\", \"tint\", \"vxl\",\n}\n\nfunc isRunningBuiltin(args []string) bool {\n\tfor _, v := range builtIn {\n\t\tif args[0] == v { return true }\n\t}\n\n\treturn false\n}\n\nfunc main() {\n\tvar jpeg, png, tiff bool\n\tflag.BoolVar(&jpeg, \"jpg\",  false, \"\")\n\tflag.BoolVar(&jpeg, \"jpeg\", false, \"\")\n\tflag.BoolVar(&png,  \"png\",  false, \"\")\n\tflag.BoolVar(&tiff, \"tiff\", false, \"\")\n\tflag.BoolVar(&tiff, \"tif\",  false, \"\")\n\n\tflag.Parse()\n\tif jpeg { utils.Output = utils.JPEG }\n\tif png  { utils.Output = utils.PNG }\n\tif tiff { utils.Output = utils.TIFF }\n\n\tif !isRunningBuiltin(flag.Args()) {\n\t\texternals := lookupExternals()\n\t\tcommands = append(commands, externals...)\n\t}\n\n\thadfield.Run(commands, templates)\n}\n<commit_msg>Fixed indentation of img help<commit_after>package main\n\nimport (\n\t\"github.com\/hawx\/img\/utils\"\n\t\"github.com\/hawx\/hadfield\"\n\t\"bytes\"\n\t\"path\/filepath\"\n\t\"os\/exec\"\n\t\"os\"\n\t\"strings\"\n\t\"flag\"\n)\n\ntype External struct {\n\tPath, Usage, Short, Long  string\n}\n\nfunc (e External) String() string {\n\treturn \"External{\" + e.Path + \"}\"\n}\n\nfunc (e *External) Name() string {\n\treturn filepath.Base(e.Path)[4:]\n}\n\nfunc (e *External) Data() interface{} {\n\treturn map[string]interface{}{\n\t\t\"Callable\": e.Callable(),\n\t\t\"Category\": e.Category(),\n\t\t\"Usage\":    e.Usage,\n\t\t\"Short\":    e.Short,\n\t\t\"Long\":     e.Long,\n\t\t\"Name\":     e.Name(),\n\t}\n}\n\nfunc (e *External) Category() string {\n\treturn \"External\"\n}\n\nfunc (e *External) Callable() bool {\n\treturn true\n}\n\nfunc (e *External) Call(cmd hadfield.Interface, templates hadfield.Templates, args []string) {\n\t\/\/ args[0] is set to the executable's name, so we can safely replace it with\n\t\/\/ the output type. This is always going to be something, so needs to be\n\t\/\/ checked for, removed, and respected!\n\targs[0] = string(utils.Output)\n\n\tex := exec.Command(e.Path, args...)\n\tex.Stdin  = os.Stdin\n\tex.Stdout = os.Stdout\n\tex.Stderr = os.Stderr\n\terr := ex.Run()\n\tif err != nil {\n\t\tos.Exit(2)\n\t}\n\treturn\n}\n\nfunc findExternalsIn(dir string) ([]string, error) {\n\tfound := []string{}\n\n\tdirs, _ := filepath.Glob(dir + \"\/\" + \"*\")\n\tfor _, possible := range dirs {\n\t\tif strings.HasPrefix(filepath.Base(possible), \"img-\") {\n\t\t\tfound = append(found, possible)\n\t\t}\n\t}\n\n\treturn found, nil\n}\n\nfunc runExternal(ext string, flags... string) string {\n\tcmd := exec.Command(ext, flags...)\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\terr := cmd.Run()\n\tif err != nil {\n\t\t\/\/ handle\n\t}\n\treturn out.String()\n}\n\nfunc lookupExternals() hadfield.Commands {\n\tfound := hadfield.Commands{}\n\tpathenv := os.Getenv(\"PATH\")\n\toutput := string(utils.Output)\n\n\tfor _, dir := range strings.Split(pathenv, \":\") {\n\t\tif dir == \"\" {\n\t\t\tdir = \".\"\n\t\t}\n\n\t\tif exts, err := findExternalsIn(dir); err == nil {\n\t\t\tfor _, ext := range exts {\n\t\t\t\tusage := runExternal(ext, output, \"--usage\")\n\t\t\t\tshort := runExternal(ext, output, \"--short\")\n\t\t\t\tlong  := runExternal(ext, output, \"--long\")\n\n\t\t\t\tfound = append(found, &External{ext, usage, short, long})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn found\n}\n\n\/\/ Commands list the available commands and help topics. The order here is the\n\/\/ order in which they are printed by 'img help'.\nvar commands = hadfield.Commands{\n\tcmdBlend,\n\tcmdBlur,\n\tcmdChannel,\n\tcmdContrast,\n\tcmdCrop,\n\tcmdGamma,\n\tcmdGreyscale,\n\tcmdHxl,\n\tcmdLevels,\n\tcmdPixelate,\n\tcmdPxl,\n\tcmdSharpen,\n\tcmdShuffle,\n\tcmdTint,\n\tcmdVxl,\n}\n\nvar templates = hadfield.Templates{\nUsage: `Usage: img [command] [arguments]\n\n  Img is a set of image manipulation tools. They each take an image from STDIN\n  and print the result to STDOUT (in some cases they may also require a second\n  image, consult the help for the particular command).\n\n  An example usage,\n\n    $ img greyscale < input.png > output.png\n\n  As standard input and output are used throughout, commands can be easily\n  chained together using pipes (and parentheses for clarity),\n\n    $ (img greyscale | img pxl | img contrast --by 0.05) < input.png > output.png\n\n  Commands: {{range .}}{{if .Callable}}{{if category . \"Command\"}}\n    {{.Name | printf \"%-15s\"}} # {{.Short | trim}}{{end}}{{end}}{{end}}\n\n  External Commands: {{range .}}{{if .Callable}}{{if category . \"External\"}}\n    {{.Name | printf \"%-15s\"}} # {{.Short | trim}}{{end}}{{end}}{{end}}\n\nUse \"img help [command]\" for more information about a command.\n`,\nHelp: `{{if .Callable}}Usage: img {{.Usage}}\n{{end}}{{.Long}}\n`,\n}\n\nvar builtIn = []string{\n\t\"blend\", \"blur\", \"channel\", \"contrast\", \"crop\", \"gamma\", \"greyscale\", \"hxl\",\n\t\"levels\", \"pixelate\", \"pxl\", \"sharpen\", \"shuffle\", \"tint\", \"vxl\",\n}\n\nfunc isRunningBuiltin(args []string) bool {\n\tfor _, v := range builtIn {\n\t\tif args[0] == v { return true }\n\t}\n\n\treturn false\n}\n\nfunc main() {\n\tvar jpeg, png, tiff bool\n\tflag.BoolVar(&jpeg, \"jpg\",  false, \"\")\n\tflag.BoolVar(&jpeg, \"jpeg\", false, \"\")\n\tflag.BoolVar(&png,  \"png\",  false, \"\")\n\tflag.BoolVar(&tiff, \"tiff\", false, \"\")\n\tflag.BoolVar(&tiff, \"tif\",  false, \"\")\n\n\tflag.Parse()\n\tif jpeg { utils.Output = utils.JPEG }\n\tif png  { utils.Output = utils.PNG }\n\tif tiff { utils.Output = utils.TIFF }\n\n\tif !isRunningBuiltin(flag.Args()) {\n\t\texternals := lookupExternals()\n\t\tcommands = append(commands, externals...)\n\t}\n\n\thadfield.Run(commands, templates)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/juju\/loggo\"\n\t\"github.com\/naoina\/toml\"\n)\n\nvar logger = loggo.GetLogger(\"main\")\n\nfunc main() {\n\tsetupLogging()\n\tsetupCLI()\n}\n\nfunc setupLogging() {\n\tconfig := os.Getenv(\"LEMONCRYPT_LOGGING\")\n\tif config == \"\" {\n\t\tconfig = \"<root>=DEBUG\"\n\t}\n\tloggo.ConfigureLoggers(config)\n\tlogger.Tracef(\"logging set up\")\n}\n\nfunc setupCLI() {\n\tapp := cli.NewApp()\n\tapp.Name = \"lemoncrypt\"\n\tapp.Usage = \"archive and encrypt the messages in your mailbox\"\n\tapp.Version = \"0.1\"\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:   \"config\",\n\t\t\tUsage:  \"path to your config file\",\n\t\t\tEnvVar: \"LIMECRYPT_CONFIG\",\n\t\t},\n\t}\n\tea := &EncryptAction{}\n\tapp.Action = ea.Run\n\tapp.Run(os.Args)\n}\n\n\/\/ EncryptAction provides the context for the default encrypt action.\ntype EncryptAction struct {\n\tctx  *cli.Context\n\tcfg  *Config\n\tconn *IMAPWalker\n}\n\n\/\/ Config defines the structure of the TOML config file and represents the\n\/\/ stored values.\ntype Config struct {\n\tServer struct {\n\t\tAddress  string\n\t\tUsername string\n\t\tPassword string\n\t}\n}\n\n\/\/ Run starts the EncryptAction.\nfunc (a *EncryptAction) Run(ctx *cli.Context) {\n\ta.ctx = ctx\n\terr := a.loadConfig()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\terr = a.setupServer()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\terr = a.process()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\tdefer a.closeServer()\n}\n\nfunc (a *EncryptAction) loadConfig() error {\n\tpath := a.ctx.String(\"config\")\n\tif path == \"\" {\n\t\tpath = \"lemoncrypt.cfg\"\n\t}\n\tlogger.Debugf(\"trying to load config file %s\", path)\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to read config file: %s\", err)\n\t\treturn err\n\t}\n\ta.cfg = &Config{}\n\terr = toml.Unmarshal(content, a.cfg)\n\tif err != nil {\n\t\tlogger.Errorf(\"unable to parse config file: %s\", err)\n\t\treturn err\n\t}\n\tlogger.Debugf(\"config loaded successfully\")\n\treturn nil\n}\n\nfunc (a *EncryptAction) setupServer() error {\n\ta.conn = NewIMAPWalker()\n\terr := a.conn.Dial(a.cfg.Server.Address)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn a.conn.Login(a.cfg.Server.Username, a.cfg.Server.Password)\n}\n\nfunc (a *EncryptAction) closeServer() error {\n\treturn a.conn.Close()\n}\n\nfunc (a *EncryptAction) callback(mail []byte) error {\n\tlogger.Infof(\"callback: %d bytes\", len(mail))\n\treturn nil\n}\n\nfunc (a *EncryptAction) process() error {\n\treturn a.conn.Walk(\"INBOX\", a.callback)\n}\n<commit_msg>main: make source mailbox configurable<commit_after>package main\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/juju\/loggo\"\n\t\"github.com\/naoina\/toml\"\n)\n\nvar logger = loggo.GetLogger(\"main\")\n\nfunc main() {\n\tsetupLogging()\n\tsetupCLI()\n}\n\nfunc setupLogging() {\n\tconfig := os.Getenv(\"LEMONCRYPT_LOGGING\")\n\tif config == \"\" {\n\t\tconfig = \"<root>=DEBUG\"\n\t}\n\tloggo.ConfigureLoggers(config)\n\tlogger.Tracef(\"logging set up\")\n}\n\nfunc setupCLI() {\n\tapp := cli.NewApp()\n\tapp.Name = \"lemoncrypt\"\n\tapp.Usage = \"archive and encrypt the messages in your mailbox\"\n\tapp.Version = \"0.1\"\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:   \"config\",\n\t\t\tUsage:  \"path to your config file\",\n\t\t\tEnvVar: \"LIMECRYPT_CONFIG\",\n\t\t},\n\t}\n\tea := &EncryptAction{}\n\tapp.Action = ea.Run\n\tapp.Run(os.Args)\n}\n\n\/\/ EncryptAction provides the context for the default encrypt action.\ntype EncryptAction struct {\n\tctx  *cli.Context\n\tcfg  *Config\n\tconn *IMAPWalker\n}\n\n\/\/ Config defines the structure of the TOML config file and represents the\n\/\/ stored values.\ntype Config struct {\n\tServer struct {\n\t\tAddress  string\n\t\tUsername string\n\t\tPassword string\n\t}\n\tMailbox struct {\n\t\tSource string\n\t\tTarget string\n\t}\n}\n\n\/\/ Run starts the EncryptAction.\nfunc (a *EncryptAction) Run(ctx *cli.Context) {\n\ta.ctx = ctx\n\terr := a.loadConfig()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\terr = a.setupServer()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\terr = a.process()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\tdefer a.closeServer()\n}\n\nfunc (a *EncryptAction) loadConfig() error {\n\tpath := a.ctx.String(\"config\")\n\tif path == \"\" {\n\t\tpath = \"lemoncrypt.cfg\"\n\t}\n\tlogger.Debugf(\"trying to load config file %s\", path)\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to read config file: %s\", err)\n\t\treturn err\n\t}\n\ta.cfg = &Config{}\n\terr = toml.Unmarshal(content, a.cfg)\n\tif err != nil {\n\t\tlogger.Errorf(\"unable to parse config file: %s\", err)\n\t\treturn err\n\t}\n\tlogger.Debugf(\"config loaded successfully\")\n\treturn nil\n}\n\nfunc (a *EncryptAction) setupServer() error {\n\ta.conn = NewIMAPWalker()\n\terr := a.conn.Dial(a.cfg.Server.Address)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn a.conn.Login(a.cfg.Server.Username, a.cfg.Server.Password)\n}\n\nfunc (a *EncryptAction) closeServer() error {\n\treturn a.conn.Close()\n}\n\nfunc (a *EncryptAction) callback(mail []byte) error {\n\tlogger.Infof(\"callback: %d bytes\", len(mail))\n\treturn nil\n}\n\nfunc (a *EncryptAction) process() error {\n\treturn a.conn.Walk(a.cfg.Mailbox.Source, a.callback)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\n\t\".\/lexer\"\n\t\".\/parser\"\n\t\".\/print\"\n\t\".\/query\"\n)\n\nfunc main() {\n\tdat, err := ioutil.ReadFile(\"sample.dtodo\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ttodo(string(dat))\n}\n\nfunc todo(src string) {\n\ttokenChan := make(chan lexer.Token)\n\ttreeChan := make(chan parser.Todo)\n\tgo lexer.Run(tokenChan, &src)\n\tgo parser.Run(treeChan, tokenChan)\n\troot := <-treeChan\n\tfmt.Printf(\"%s\\n\", print.Stringify(root))\n\n\tquery.New(root)\n\treturn\n}\n<commit_msg>Can query todo list on main application.<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\n\t\".\/lexer\"\n\t\".\/parser\"\n\t\".\/print\"\n\t\".\/query\"\n)\n\nfunc main() {\n\tdat, err := ioutil.ReadFile(\"sample.dtodo\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ttodo(string(dat))\n}\n\nfunc todo(src string) {\n\ttokenChan := make(chan lexer.Token)\n\ttreeChan := make(chan parser.Todo)\n\tgo lexer.Run(tokenChan, &src)\n\tgo parser.Run(treeChan, tokenChan)\n\troot := <-treeChan\n\tfmt.Printf(\"Input:\\n%s\\n\", print.Stringify(root))\n\n\tfmt.Println()\n\n\tq := query.New(root)\n\n\tin := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tfmt.Printf(\"To do .. (type something): \")\n\t\tline, _ := in.ReadString('\\n')\n\t\tline = strings.Trim(line, \"\\n\")\n\t\tif line == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\ttodos := q.GetTodo(line)\n\t\tif len(todos) == 1 {\n\t\t\tfmt.Printf(\"Do \\\"%s\\\"!\\n\", todos[0])\n\t\t} else {\n\t\t\tfmt.Println(\"Here are your todo list\")\n\t\t\tfor _, todo := range todos {\n\t\t\t\tfmt.Printf(\" - %s\\n\", todo)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"github.com\/UniversityRadioYork\/bifrost-go\"\n\t\"github.com\/UniversityRadioYork\/bifrost-server\/request\"\n\t\"github.com\/UniversityRadioYork\/bifrost-server\/tcpserver\"\n\t\/\/\"github.com\/docopt\/docopt-go\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nvar hostport = flag.String(\"hostport\", \"localhost:8123\", \"The host and port on which trackd should listen (host:port).\")\nvar resolver = flag.String(\"resolver\", \"resolve\", \"The two-argument command to which trackids will be sent on stdin.\")\n\nfunc resolve(recordid, trackid string) (out string, err error) {\n\tcmd := exec.Command(*resolver, recordid, trackid)\n\n\tvar outb []byte\n\toutb, err = cmd.Output()\n\tout = string(outb)\n\n\treturn\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tsample, serr := resolve(\"recordid\", \"trackid\")\n\tif serr != nil {\n\t\tlog.Fatal(serr)\n\t}\n\n\tlog.Printf(\"example resolve: %s recordid trackid -> %s\", *resolver, sample)\n\n\tdb, err := getDB()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer func() {\n\t\tif err := db.Close(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\n\tt := NewTrackDB(db, resolve)\n\n\t\/\/ TODO(CaptainHayashi): factor this out?\n\trtree := bifrost.NewDirectoryResourceNode(\n\t\tmap[string]bifrost.ResourceNoder{\n\t\t\t\"control\": bifrost.NewDirectoryResourceNode(\n\t\t\t\t\/\/ TODO: put state here\n\t\t\t\tmap[string]bifrost.ResourceNoder{},\n\t\t\t),\n\t\t\t\"tracks\": &TrackResourceNode{\n\t\t\t\ttrackdb: t,\n\t\t\t},\n\t\t},\n\t)\n\n\tlog.Printf(\"listening on %s\", *hostport)\n\ttcpserver.Serve(request.Map{\n\t\tbifrost.RqRead:  handleRead,\n\t\tbifrost.RqWrite: handleWrite,\n\t}, rtree, \"trackd\", *hostport)\n}\n\ntype TrackResourceNode struct {\n\tbifrost.ResourceNode\n\n\ttrackdb *TrackDB\n}\n\nfunc (r *TrackResourceNode) NRead(prefix, relpath []string) ([]bifrost.Resource, error) {\n\t\/\/ Is this about us, or one of our children?\n\tif len(relpath) == 0 {\n\t\t\/\/ TODO(CaptainHayashi): This should be something else.\n\t\t\/\/ Like, maybe, a Query?\n\t\treturn bifrost.ToResource(prefix, struct{}{}), nil\n\t}\n\t\/\/ We're expecting relpath to contain the trackID and nothing else.\n\t\/\/ Bail out if this isn't the case.\n\tif len(relpath) != 1 {\n\t\treturn []bifrost.Resource{}, fmt.Errorf(\"expected only one child, got %q\", relpath)\n\t}\n\treturn r.trackdb.LookupTrack(prefix, relpath[0])\n}\n\nfunc (r *TrackResourceNode) NWrite(_, _ []string, _ bifrost.BifrostType) error {\n\t\/\/ TODO(CaptainHayashi): correct error\n\treturn fmt.Errorf(\"can't write to trackdb\")\n}\n\nfunc (r *TrackResourceNode) NDelete(_, _ []string) error {\n\t\/\/ TODO(CaptainHayashi): correct error\n\treturn fmt.Errorf(\"can't delete trackdb\")\n}\n\nfunc (r *TrackResourceNode) NAdd(_, _ []string, _ bifrost.ResourceNoder) error {\n\t\/\/ TODO(CaptainHayashi): correct error\n\treturn fmt.Errorf(\"can't add to trackdb\")\n}\n\nfunc handleRead(_ chan<- *bifrost.Message, response chan<- *bifrost.Message, args []string, it interface{}) (bool, error) {\n\tt := it.(bifrost.ResourceNoder)\n\n\t\/\/ read TAG PATH\n\tif 2 == len(args) {\n\t\t\/\/ Reading can never quit the server (we hope).\n\t\tres := bifrost.Read(t, args[1])\n\t\t\/\/ TODO(CaptainHayashi): don't unpack this?\n\t\tif res.Status.Code != bifrost.StatusOk {\n\t\t\treturn false, fmt.Errorf(\"fixme: %q\", res.Status.String())\n\t\t}\n\t\tfor _, r := range res.Resources {\n\t\t\tresponse <- r.Message(args[0])\n\t\t}\n\n\t\treturn false, nil\n\t}\n\n\treturn false, fmt.Errorf(\"FIXME: bad read %q\", args)\n}\n\nfunc handleWrite(_ chan<- *bifrost.Message, response chan<- *bifrost.Message, args []string, _ interface{}) (bool, error) {\n\t\/\/ write TAG(ignored) PATH VALUE\n\tif 3 == len(args) {\n\t\tresources := strings.Split(strings.Trim(args[1], \"\/\"), \"\/\")\n\t\tif len(resources) == 2 && resources[0] == \"control\" && resources[1] == \"state\" {\n\t\t\tif strings.EqualFold(args[2], \"Quitting\") {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, fmt.Errorf(\"FIXME: unknown state %q\", args[2])\n\t\t}\n\t\treturn false, fmt.Errorf(\"FIXME: unknown write %q\", resources)\n\t}\n\n\treturn false, fmt.Errorf(\"FIXME: bad write %q\", args)\n}\n<commit_msg>Implement basic, initial state resource node.<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"github.com\/UniversityRadioYork\/bifrost-go\"\n\t\"github.com\/UniversityRadioYork\/bifrost-server\/request\"\n\t\"github.com\/UniversityRadioYork\/bifrost-server\/tcpserver\"\n\t\/\/\"github.com\/docopt\/docopt-go\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nvar hostport = flag.String(\"hostport\", \"localhost:8123\", \"The host and port on which trackd should listen (host:port).\")\nvar resolver = flag.String(\"resolver\", \"resolve\", \"The two-argument command to which trackids will be sent on stdin.\")\n\nfunc resolve(recordid, trackid string) (out string, err error) {\n\tcmd := exec.Command(*resolver, recordid, trackid)\n\n\tvar outb []byte\n\toutb, err = cmd.Output()\n\tout = string(outb)\n\n\treturn\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tsample, serr := resolve(\"recordid\", \"trackid\")\n\tif serr != nil {\n\t\tlog.Fatal(serr)\n\t}\n\n\tlog.Printf(\"example resolve: %s recordid trackid -> %s\", *resolver, sample)\n\n\tdb, err := getDB()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer func() {\n\t\tif err := db.Close(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\n\tt := NewTrackDB(db, resolve)\n\n\t\/\/ TODO(CaptainHayashi): factor this out?\n\trtree := bifrost.NewDirectoryResourceNode(\n\t\tmap[string]bifrost.ResourceNoder{\n\t\t\t\"control\": bifrost.NewDirectoryResourceNode(\n\t\t\t\t\/\/ TODO: put state here\n\t\t\t\tmap[string]bifrost.ResourceNoder{\n\t\t\t\t\t\"state\": &StateResourceNode{\n\t\t\t\t\t\tstate: \"running\",\n\t\t\t\t\t\tstateChangeFn: func(x string) (string, error) { return \"\", fmt.Errorf(\"cannot change state to %q\", x) },\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t),\n\t\t\t\"tracks\": &TrackResourceNode{\n\t\t\t\ttrackdb: t,\n\t\t\t},\n\t\t},\n\t)\n\n\tlog.Printf(\"listening on %s\", *hostport)\n\ttcpserver.Serve(request.Map{\n\t\tbifrost.RqRead:  handleRead,\n\t\tbifrost.RqWrite: handleWrite,\n\t}, rtree, \"trackd\", *hostport)\n}\n\ntype StateResourceNode struct {\n\tbifrost.ResourceNode\n\n\t\/\/ TODO(CaptainHayashi): tighten this up?\n\tstate string\n\n\t\/\/ Called when the state is changed to something other than quitting.\n\t\/\/ Passed the new state verbatim -- please use strings.EqualFold etc. to compare.\n\t\/\/ Return (new state, nil) if the state change is allowed; (_, error) otherwise.\n\tstateChangeFn func(string) (string, error)\n}\n\nfunc (r *StateResourceNode) NRead(prefix, relpath []string) ([]bifrost.Resource, error) {\n\t\/\/ We don't have any children (though eventually enums will be a thing?)\n\tif len(relpath) != 0 {\n\t\treturn []bifrost.Resource{}, fmt.Errorf(\"state has no children, got %q\", relpath)\n\t}\n\n\treturn bifrost.ToResource(prefix, r.state), nil\n}\nfunc (r *StateResourceNode) NWrite(prefix, relpath []string, val bifrost.BifrostType) error {\n\tlog.Printf(\"trying to set state to %s\", val)\n\n\tif len(relpath) != 0 {\n\t\treturn fmt.Errorf(\"state has no children, got %q\", relpath)\n\t}\n\n\t\/\/ TODO(CaptainHayashi): support more than strings here?\n\tst, ok := val.(bifrost.BifrostTypeString)\n\tif !ok {\n\t\treturn fmt.Errorf(\"state must be a string, got %q\", val)\n\t}\n\t_, s := st.ResourceBody()\n\n\t\/\/ Quitting is monotonic: once you've quit, you can't unquit.\n\tif strings.EqualFold(r.state, \"quitting\") {\n\t\treturn fmt.Errorf(\"cannot change state, server is quitting\")\n\t}\n\n\t\/\/ Don't allow changes from one state to itself.\n\tif strings.EqualFold(r.state, s) {\n\t\treturn nil\n\t}\n\n\t\/\/ We handle quitting on our own.\n\tnews := \"quitting\"\n\tvar err error\n\tif !strings.EqualFold(s, \"quitting\") {\n\t\tnews, err = r.stateChangeFn(s)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tr.state = news\n\treturn nil\n}\n\nfunc (r *StateResourceNode) NDelete(prefix, relpath []string) error {\n\t\/\/ Deleting = writing \"quitting\" by design.\n\t\/\/ Since we can't write to children of a state node, this is sound.\n\treturn r.NWrite(prefix, relpath, bifrost.BifrostTypeString(\"quitting\"))\n}\n\nfunc (r *StateResourceNode) NAdd(_, _ []string, _ bifrost.ResourceNoder) error {\n\t\/\/ TODO(CaptainHayashi): correct error\n\treturn fmt.Errorf(\"can't add to state\")\n}\n\ntype TrackResourceNode struct {\n\tbifrost.ResourceNode\n\n\ttrackdb *TrackDB\n}\n\nfunc (r *TrackResourceNode) NRead(prefix, relpath []string) ([]bifrost.Resource, error) {\n\t\/\/ Is this about us, or one of our children?\n\tif len(relpath) == 0 {\n\t\t\/\/ TODO(CaptainHayashi): This should be something else.\n\t\t\/\/ Like, maybe, a Query?\n\t\treturn bifrost.ToResource(prefix, struct{}{}), nil\n\t}\n\t\/\/ We're expecting relpath to contain the trackID and nothing else.\n\t\/\/ Bail out if this isn't the case.\n\tif len(relpath) != 1 {\n\t\treturn []bifrost.Resource{}, fmt.Errorf(\"expected only one child, got %q\", relpath)\n\t}\n\treturn r.trackdb.LookupTrack(prefix, relpath[0])\n}\n\nfunc (r *TrackResourceNode) NWrite(_, _ []string, _ bifrost.BifrostType) error {\n\t\/\/ TODO(CaptainHayashi): correct error\n\treturn fmt.Errorf(\"can't write to trackdb\")\n}\n\nfunc (r *TrackResourceNode) NDelete(_, _ []string) error {\n\t\/\/ TODO(CaptainHayashi): correct error\n\treturn fmt.Errorf(\"can't delete trackdb\")\n}\n\nfunc (r *TrackResourceNode) NAdd(_, _ []string, _ bifrost.ResourceNoder) error {\n\t\/\/ TODO(CaptainHayashi): correct error\n\treturn fmt.Errorf(\"can't add to trackdb\")\n}\n\nfunc handleRead(_ chan<- *bifrost.Message, response chan<- *bifrost.Message, args []string, it interface{}) (bool, error) {\n\tt := it.(bifrost.ResourceNoder)\n\n\t\/\/ read TAG PATH\n\tif 2 == len(args) {\n\t\t\/\/ Reading can never quit the server (we hope).\n\t\tres := bifrost.Read(t, args[1])\n\t\t\/\/ TODO(CaptainHayashi): don't unpack this?\n\t\tif res.Status.Code != bifrost.StatusOk {\n\t\t\treturn false, fmt.Errorf(\"fixme: %q\", res.Status.String())\n\t\t}\n\t\tfor _, r := range res.Resources {\n\t\t\tresponse <- r.Message(args[0])\n\t\t}\n\n\t\treturn false, nil\n\t}\n\n\treturn false, fmt.Errorf(\"FIXME: bad read %q\", args)\n}\n\nfunc handleWrite(_ chan<- *bifrost.Message, response chan<- *bifrost.Message, args []string, it interface{}) (bool, error) {\n\tt := it.(bifrost.ResourceNoder)\n\n\t\/\/ write TAG(ignored) PATH VALUE\n\tif 3 == len(args) {\n\t\t\/\/ TODO(CaptainHayashi): figuring out if the server has quit is very convoluted at the moment\n\n\t\tres := bifrost.Write(t, args[1], args[2])\n\t\t\/\/ TODO(CaptainHayashi): don't unpack this (as above)?\n\t\tif res.Status.Code != bifrost.StatusOk {\n\t\t\treturn false, fmt.Errorf(\"fixme: %q\", res.Status.String())\n\t\t}\n\n\t\t\/\/ Ugh... please fix this.\n\t\treturn args[1] == \"\/control\/state\" && strings.EqualFold(args[2], \"quitting\"), nil\n\t}\n\n\treturn false, fmt.Errorf(\"FIXME: bad write %q\", args)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"os\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/cli\"\n)\n\nconst version = \"0.0.1\"\n\nvar commands []cli.Command\n\nfunc init() {\n\tcommands = []cli.Command{}\n}\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"zodiac\"\n\tapp.Version = version\n\tapp.Usage = \"Simple Docker deployment utility.\"\n\tapp.Authors = []cli.Author{{\"CenturyLink Labs\", \"clt-labs-futuretech@centurylink.com\"}}\n\tapp.Commands = commands\n\tapp.Before = initializeCLI\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName:  \"debug\",\n\t\t\tUsage: \"Enable verbose logging\",\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n}\n\nfunc initializeCLI(c *cli.Context) error {\n\tif c.GlobalBool(\"debug\") {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\n\treturn nil\n}\n<commit_msg>Actually set the initial loglevel.<commit_after>package main\n\nimport (\n\t\"os\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/cli\"\n)\n\nconst version = \"0.0.1\"\n\nvar commands []cli.Command\n\nfunc init() {\n\tlog.SetLevel(log.WarnLevel)\n\tcommands = []cli.Command{}\n}\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"zodiac\"\n\tapp.Version = version\n\tapp.Usage = \"Simple Docker deployment utility.\"\n\tapp.Authors = []cli.Author{{\"CenturyLink Labs\", \"clt-labs-futuretech@centurylink.com\"}}\n\tapp.Commands = commands\n\tapp.Before = initializeCLI\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName:  \"debug\",\n\t\t\tUsage: \"Enable verbose logging\",\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n}\n\nfunc initializeCLI(c *cli.Context) error {\n\tif c.GlobalBool(\"debug\") {\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2013 Mathieu Lonjaret.\n*\/\n\n\/\/ Package scgiclient implements the client side of the\n\/\/ Simple Common Gateway Interface protocol, as described\n\/\/ at http:\/\/python.ca\/scgi\/protocol.txt\npackage scgiclient\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ Send sends and scgi request to addr, with\n\/\/ all the data read from r as the body of the request.\n\/\/ The received response is returned and the connection\n\/\/ to addr is closed.\nfunc Send(addr string, r io.Reader) (*Response, error) {\n\tconn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\tbody, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq := NewRequest(addr, body)\n\treq.conn = conn\n\tif _, err = req.Send(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn req.Receive()\n}\n\ntype Request struct {\n\tAddr   string\n\tHeader []byte\n\tBody   []byte\n\tconn   net.Conn\n}\n\n\/\/ NewRequest returns a Request ready to be sent with\n\/\/ Request.Send().\nfunc NewRequest(addr string, body []byte) *Request {\n\treturn &Request{\n\t\tAddr:   addr,\n\t\tHeader: defaultHeader(len(body)),\n\t\tBody:   body,\n\t}\n}\n\n\/\/ Close closes the connection to r.Addr.\nfunc (r *Request) Close() error {\n\treturn r.conn.Close()\n}\n\n\/\/ Send sends an scgi message built with\n\/\/ r.Header and r.Body, to r.Addr. It returns the\n\/\/ number of bytes sent and an error, if any.\nfunc (r *Request) Send() (int64, error) {\n\tvar err error\n\tif r.conn == nil {\n\t\tr.conn, err = net.Dial(\"tcp\", r.Addr)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\tmsg := append(netstring(r.Header), r.Body...)\n\treturn io.Copy(r.conn, bytes.NewReader(msg))\n}\n\n\/\/ Receive reads the response from r.Addr and returns\n\/\/ it in a Response. The connection to r.Addr must already\n\/\/ be established.\nfunc (r *Request) Receive() (*Response, error) {\n\tif r.conn == nil {\n\t\treturn nil, errors.New(\"Can not receive on a closed connection\")\n\t}\n\treturn receive(r.conn)\n}\n\ntype Response struct {\n\tHeader map[string]string\n\tBody   []byte\n\tconn   net.Conn\n}\n\n\/\/ Close closes the connection to r.Addr.\nfunc (r *Response) Close() error {\n\treturn r.conn.Close()\n}\n\nfunc receive(conn net.Conn) (*Response, error) {\n\tr := bufio.NewReader(conn)\n\theader := make(map[string]string)\n\tterminator := string([]byte{13, 10})\n\tfor {\n\t\tline, err := r.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tline = strings.TrimRight(line, terminator)\n\t\tif line == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tkeyValue := strings.SplitN(line, \": \", 2)\n\t\tif len(keyValue) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"Bogus header line in response: %q\", line)\n\t\t}\n\t\theader[keyValue[0]] = keyValue[1]\n\t}\n\n\tresp := &Response{\n\t\tHeader: header,\n\t\tconn:   conn,\n\t}\n\tstatus, ok := header[\"Status\"]\n\tif !ok {\n\t\treturn nil, errors.New(\"Did not get a status line in response header\")\n\t}\n\tif status != \"200 OK\" {\n\t\treturn resp, fmt.Errorf(\"Got %v as response status\", status)\n\t}\n\tvar body bytes.Buffer\n\tif _, err := io.Copy(&body, r); err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not read response: %v\", err)\n\t}\n\tresp.Body = body.Bytes()\n\treturn resp, nil\n}\n\nfunc defaultHeader(bodyLen int) []byte {\n\tvar dh []byte\n\tdefaultHeaderFields[\"CONTENT_LENGTH\"] = strconv.Itoa(bodyLen)\n\tfor k, v := range defaultHeaderFields {\n\t\tdh = append(dh, header(k, v)...)\n\t}\n\treturn dh\n}\n\nfunc header(name, value string) []byte {\n\th := append([]byte(name), 0)\n\th = append(h, []byte(value)...)\n\treturn append(h, 0)\n}\n\nvar defaultHeaderFields = map[string]string{\n\t\"CONTENT_LENGTH\":  \"\",\n\t\"SCGI\":            \"1\",\n\t\"REQUEST_METHOD\":  \"POST\",\n\t\"SERVER_PROTOCOL\": \"HTTP\/1.1\",\n}\n\nconst (\n\tcomma = byte(',')\n\tcolon = byte(':')\n)\n\nfunc netstring(s []byte) []byte {\n\tle := []byte(strconv.Itoa(len(s)))\n\tns := append(le, colon)\n\tns = append(ns, s...)\n\tns = append(ns, comma)\n\treturn ns\n}\n<commit_msg>allow unix domain sockets<commit_after>\/*\nCopyright 2013 Mathieu Lonjaret.\n*\/\n\n\/\/ Package scgiclient implements the client side of the\n\/\/ Simple Common Gateway Interface protocol, as described\n\/\/ at http:\/\/python.ca\/scgi\/protocol.txt\npackage scgiclient\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ Send sends and scgi request to addr, with\n\/\/ all the data read from r as the body of the request.\n\/\/ The received response is returned and the connection\n\/\/ to addr is closed.\nfunc Send(addr string, r io.Reader) (*Response, error) {\n\tvar conn net.Conn\n\n\tfi, err := os.Stat(addr)\n\n\tif err == nil && fi.Mode()&os.ModeSocket != 0 {\n\t\tconn, err = net.Dial(\"unix\", addr)\n\t} else {\n\t\tconn, err = net.Dial(\"tcp\", addr)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\tbody, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq := NewRequest(addr, body)\n\treq.conn = conn\n\tif _, err = req.Send(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn req.Receive()\n}\n\ntype Request struct {\n\tAddr   string\n\tHeader []byte\n\tBody   []byte\n\tconn   net.Conn\n}\n\n\/\/ NewRequest returns a Request ready to be sent with\n\/\/ Request.Send().\nfunc NewRequest(addr string, body []byte) *Request {\n\treturn &Request{\n\t\tAddr:   addr,\n\t\tHeader: defaultHeader(len(body)),\n\t\tBody:   body,\n\t}\n}\n\n\/\/ Close closes the connection to r.Addr.\nfunc (r *Request) Close() error {\n\treturn r.conn.Close()\n}\n\n\/\/ Send sends an scgi message built with\n\/\/ r.Header and r.Body, to r.Addr. It returns the\n\/\/ number of bytes sent and an error, if any.\nfunc (r *Request) Send() (int64, error) {\n\tvar err error\n\tif r.conn == nil {\n\t\tr.conn, err = net.Dial(\"tcp\", r.Addr)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\tmsg := append(netstring(r.Header), r.Body...)\n\treturn io.Copy(r.conn, bytes.NewReader(msg))\n}\n\n\/\/ Receive reads the response from r.Addr and returns\n\/\/ it in a Response. The connection to r.Addr must already\n\/\/ be established.\nfunc (r *Request) Receive() (*Response, error) {\n\tif r.conn == nil {\n\t\treturn nil, errors.New(\"Can not receive on a closed connection\")\n\t}\n\treturn receive(r.conn)\n}\n\ntype Response struct {\n\tHeader map[string]string\n\tBody   []byte\n\tconn   net.Conn\n}\n\n\/\/ Close closes the connection to r.Addr.\nfunc (r *Response) Close() error {\n\treturn r.conn.Close()\n}\n\nfunc receive(conn net.Conn) (*Response, error) {\n\tr := bufio.NewReader(conn)\n\theader := make(map[string]string)\n\tterminator := string([]byte{13, 10})\n\tfor {\n\t\tline, err := r.ReadString('\\n')\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tline = strings.TrimRight(line, terminator)\n\t\tif line == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tkeyValue := strings.SplitN(line, \": \", 2)\n\t\tif len(keyValue) != 2 {\n\t\t\treturn nil, fmt.Errorf(\"Bogus header line in response: %q\", line)\n\t\t}\n\t\theader[keyValue[0]] = keyValue[1]\n\t}\n\n\tresp := &Response{\n\t\tHeader: header,\n\t\tconn:   conn,\n\t}\n\tstatus, ok := header[\"Status\"]\n\tif !ok {\n\t\treturn nil, errors.New(\"Did not get a status line in response header\")\n\t}\n\tif status != \"200 OK\" {\n\t\treturn resp, fmt.Errorf(\"Got %v as response status\", status)\n\t}\n\tvar body bytes.Buffer\n\tif _, err := io.Copy(&body, r); err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not read response: %v\", err)\n\t}\n\tresp.Body = body.Bytes()\n\treturn resp, nil\n}\n\nfunc defaultHeader(bodyLen int) []byte {\n\tvar dh []byte\n\tdefaultHeaderFields[\"CONTENT_LENGTH\"] = strconv.Itoa(bodyLen)\n\tfor k, v := range defaultHeaderFields {\n\t\tdh = append(dh, header(k, v)...)\n\t}\n\treturn dh\n}\n\nfunc header(name, value string) []byte {\n\th := append([]byte(name), 0)\n\th = append(h, []byte(value)...)\n\treturn append(h, 0)\n}\n\nvar defaultHeaderFields = map[string]string{\n\t\"CONTENT_LENGTH\":  \"\",\n\t\"SCGI\":            \"1\",\n\t\"REQUEST_METHOD\":  \"POST\",\n\t\"SERVER_PROTOCOL\": \"HTTP\/1.1\",\n}\n\nconst (\n\tcomma = byte(',')\n\tcolon = byte(':')\n)\n\nfunc netstring(s []byte) []byte {\n\tle := []byte(strconv.Itoa(len(s)))\n\tns := append(le, colon)\n\tns = append(ns, s...)\n\tns = append(ns, comma)\n\treturn ns\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"time\"\n\n\t\"github.com\/hybridgroup\/gobot\"\n\t\"github.com\/hybridgroup\/gobot\/platforms\/gpio\"\n\t\"github.com\/hybridgroup\/gobot\/platforms\/intel-iot\/edison\"\n)\n\nfunc main() {\n\tgbot := gobot.NewGobot()\n\n\te := edison.NewEdisonAdaptor(\"edison\")\n\tled := gpio.NewLedDriver(e, \"led\", \"13\")\n\n\twork := func() {\n\t\tgobot.Every(1*time.Second, func() {\n\t\t\tled.Toggle()\n\t\t})\n\t}\n\n\trobot := gobot.NewRobot(\"blinkBot\",\n\t\t[]gobot.Connection{e},\n\t\t[]gobot.Device{led},\n\t\twork,\n\t)\n\n\tgbot.AddRobot(robot)\n\n\tgbot.Start()\n}\n<commit_msg>ble stuff<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/acmacalister\/gatt\"\n)\n\nfunc main() {\n\n\tsrv := gatt.NewServer(gatt.Name(\"gophergatt\"))\n\tsvc := srv.AddService(gatt.MustParseUUID(\"09fc95c0-c111-11e3-9904-0002a5d5c51b\"))\n\n\t\/\/ Add a read characteristic that prints how many times it has been read\n\tn := 0\n\trchar := svc.AddCharacteristic(gatt.MustParseUUID(\"11fac9e0-c111-11e3-9246-0002a5d5c51b\"))\n\trchar.HandleRead(\n\t\tgatt.ReadHandlerFunc(\n\t\t\tfunc(resp gatt.ReadResponseWriter, req *gatt.ReadRequest) {\n\t\t\t\tfmt.Fprintf(resp, \"count: %d\", n)\n\t\t\t\tn++\n\t\t\t}),\n\t)\n\n\t\/\/ Add a write characteristic that logs when written to\n\twchar := svc.AddCharacteristic(gatt.MustParseUUID(\"16fe0d80-c111-11e3-b8c8-0002a5d5c51b\"))\n\twchar.HandleWriteFunc(\n\t\tfunc(r gatt.Request, data []byte) (status byte) {\n\t\t\tlog.Println(\"Wrote:\", string(data))\n\t\t\treturn gatt.StatusSuccess\n\t\t})\n\n\t\/\/ Add a notify characteristic that updates once a second\n\tnchar := svc.AddCharacteristic(gatt.MustParseUUID(\"1c927b50-c116-11e3-8a33-0800200c9a66\"))\n\tnchar.HandleNotifyFunc(\n\t\tfunc(r gatt.Request, n gatt.Notifier) {\n\t\t\tgo func() {\n\t\t\t\tcount := 0\n\t\t\t\tfor !n.Done() {\n\t\t\t\t\tfmt.Fprintf(n, \"Count: %d\", count)\n\t\t\t\t\tcount++\n\t\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\t}\n\t\t\t}()\n\t\t})\n\n\tfmt.Println(\"advertising...\")\n\t\/\/ Start the server\n\tlog.Fatal(srv.AdvertiseAndServe())\n}\n\n\/\/ c := &serial.Config{Name: \"\/dev\/ttyMFD1\", Baud: 9600}\n\/\/ s, err := serial.OpenPort(c)\n\/\/ if err != nil {\n\/\/ \tlog.Fatal(err)\n\/\/ }\n\n\/\/ go func() {\n\/\/ \tfor {\n\/\/ \t\treader := bufio.NewReader(os.Stdin)\n\/\/ \t\tfmt.Print(\"Enter text: \")\n\/\/ \t\ttext, _ := reader.ReadString('\\n')\n\/\/ \t\t_, err := s.Write([]byte(text))\n\/\/ \t\tif err != nil {\n\/\/ \t\t\tlog.Fatal(err)\n\/\/ \t\t}\n\/\/ \t}\n\/\/ }()\n\n\/\/ for {\n\/\/ \tbuf := make([]byte, 128)\n\/\/ \tn, err := s.Read(buf)\n\/\/ \tif err != nil {\n\/\/ \t\tlog.Fatal(err)\n\/\/ \t}\n\/\/ \tlog.Println(\"stuff:\", string(buf[:n]))\n\/\/ }\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"log\"\n\t\"flag\"\n\t\"os\"\n\t\"time\"\n\t\n\t\"github.com\/hanwen\/gitfs\/fs\"\n\t\"github.com\/hanwen\/go-fuse\/fuse\/nodefs\"\n\n\tgit \"github.com\/libgit2\/git2go\"\n)\n\nfunc main() {\n\ttree := flag.String(\"tree\", \"master\", \"tree to mount\")\n\tflag.Parse()\n\t\n\tif len(flag.Args()) < 2 {\n\t\tlog.Fatalf(\"usage: %s REPO MOUNT\", os.Args[0])\n\t}\n\n\trepoDir := flag.Args()[0]\n\tmntDir := flag.Args()[1]\n\n\trepo, err := git.OpenRepository(repoDir)\n\tif err != nil {\n\t\tlog.Fatalf(\"OpenRepository(%q): %v\", repoDir, err)\n\t}\n\n\tfs, err := fs.NewTreeFS(repo, *tree)\n\tif err != nil {\n\t\tlog.Fatalf(\"NewTreeFS(%q): %v\", *tree, err)\n\t}\n\n\tserver, _, err := nodefs.MountFileSystem(mntDir, fs, &nodefs.Options{\n\t\tEntryTimeout: time.Hour,\n\t\tNegativeTimeout: time.Hour,\n\t\tAttrTimeout: time.Hour,\n\t\tPortableInodes: true,\n\t})\n\tlog.Printf(\"Started gitfs FUSE on %s\", mntDir)\n\tserver.Serve()\n}\n<commit_msg>Make main driver use multifs.<commit_after>package main\n\nimport (\n\t\"log\"\n\t\"flag\"\n\t\"os\"\n\t\"time\"\n\t\n\t\"github.com\/hanwen\/gitfs\/fs\"\n\t\"github.com\/hanwen\/go-fuse\/fuse\/nodefs\"\n)\n\nfunc main() {\n\tflag.Parse()\n\tif len(flag.Args()) < 1 {\n\t\tlog.Fatalf(\"usage: %s MOUNT\", os.Args[0])\n\t}\n\n\tmntDir := flag.Args()[0]\n\n\tfs := fs.NewMultiGitFS()\n\tserver, _, err := nodefs.MountFileSystem(mntDir, fs, &nodefs.Options{\n\t\tEntryTimeout: time.Hour,\n\t\tNegativeTimeout: time.Hour,\n\t\tAttrTimeout: time.Hour,\n\t\tPortableInodes: true,\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"MountFileSystem: %v\", err)\n\t}\n\tlog.Printf(\"Started git multi fs FUSE on %s\", mntDir)\n\tserver.Serve()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/user\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/hpcloud\/tail\"\n\t\"github.com\/yext\/errgo\"\n)\n\ntype EdwardConfiguration struct {\n\tDir       string\n\tLogDir    string\n\tPidDir    string\n\tScriptDir string\n}\n\nvar EdwardConfig EdwardConfiguration = EdwardConfiguration{}\n\nfunc createDirIfNeeded(path string) {\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\tos.MkdirAll(path, 0777)\n\t}\n}\n\nfunc (e *EdwardConfiguration) initialize() error {\n\tuser, err := user.Current()\n\tif err != nil {\n\t\treturn err\n\t}\n\te.Dir = path.Join(user.HomeDir, \".edward\")\n\te.LogDir = path.Join(e.Dir, \"logs\")\n\te.PidDir = path.Join(e.Dir, \"pidFiles\")\n\te.ScriptDir = path.Join(e.Dir, \"scriptFiles\")\n\tcreateDirIfNeeded(e.Dir)\n\tcreateDirIfNeeded(e.LogDir)\n\tcreateDirIfNeeded(e.PidDir)\n\tcreateDirIfNeeded(e.ScriptDir)\n\treturn nil\n}\n\nvar groups map[string]*ServiceGroupConfig\nvar services map[string]*ServiceConfig\n\nfunc thirdPartyService(name string, startCommand string, stopCommand string, started string) *ServiceConfig {\n\tpathStr := \"$ALPHA\"\n\treturn &ServiceConfig{\n\t\tName: name,\n\t\tPath: &pathStr,\n\t\tEnv:  []string{\"YEXT_RABBITMQ=localhost\"},\n\t\tCommands: ServiceConfigCommands{\n\t\t\tLaunch: startCommand,\n\t\t\tStop:   stopCommand,\n\t\t},\n\t\tProperties: ServiceConfigProperties{\n\t\t\tStarted: started,\n\t\t},\n\t}\n}\n\nfunc getAlpha() string {\n\tfor _, env := range os.Environ() {\n\t\tpair := strings.Split(env, \"=\")\n\t\tif pair[0] == \"ALPHA\" {\n\t\t\treturn pair[1]\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc addFoundServices() {\n\tfoundServices, _, err := generateServices(getAlpha())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, s := range foundServices {\n\t\tif _, found := services[s.Name]; !found {\n\t\t\tservices[s.Name] = s\n\t\t}\n\t}\n}\n\nfunc getConfigPath() string {\n\twd, _ := os.Getwd()\n\treturn filepath.Join(wd, \"edward.json\")\n}\n\nfunc loadConfig() {\n\tgroups = make(map[string]*ServiceGroupConfig)\n\tservices = make(map[string]*ServiceConfig)\n\n\tconfigPath := getConfigPath()\n\n\tif _, err := os.Stat(configPath); err == nil {\n\t\tprintln(\"Loading configuration from\", configPath)\n\t\tr, err := os.Open(configPath)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tconfig, err := LoadConfig(r)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tservices = config.ServiceMap\n\t\tgroups = config.GroupMap\n\t\treturn\n\t} else {\n\t\taddFoundServices()\n\t\tapplyHardCodedServicesAndGroups()\n\t}\n\n}\n\nfunc getServicesOrGroups(names []string) ([]ServiceOrGroup, error) {\n\tvar outSG []ServiceOrGroup\n\tfor _, name := range names {\n\t\tsg, err := getServiceOrGroup(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\toutSG = append(outSG, sg)\n\t}\n\treturn outSG, nil\n}\n\nfunc getServiceOrGroup(name string) (ServiceOrGroup, error) {\n\tif group, ok := groups[name]; ok {\n\t\treturn group, nil\n\t}\n\tif service, ok := services[name]; ok {\n\t\treturn service, nil\n\t}\n\treturn nil, errors.New(\"Service or group not found\")\n}\n\nfunc list(c *cli.Context) error {\n\n\tvar groupNames []string\n\tvar serviceNames []string\n\tfor name, _ := range groups {\n\t\tgroupNames = append(groupNames, name)\n\t}\n\tfor name, _ := range services {\n\t\tserviceNames = append(serviceNames, name)\n\t}\n\n\tsort.Strings(groupNames)\n\tsort.Strings(serviceNames)\n\n\tprintln(\"Services and groups\")\n\tprintln(\"Groups:\")\n\tfor _, name := range groupNames {\n\t\tprintln(\"\\t\", name)\n\t}\n\tprintln(\"Services:\")\n\tfor _, name := range serviceNames {\n\t\tprintln(\"\\t\", name)\n\t}\n\n\treturn nil\n}\n\nfunc generate(c *cli.Context) error {\n\n\t\/\/ Add any new services to the config as appropriate\n\taddFoundServices()\n\n\tconfigPath := getConfigPath()\n\n\tif err := generateConfigFile(configPath); err != nil {\n\t\treturn err\n\t}\n\tprintln(\"Wrote to\", configPath)\n\n\treturn nil\n}\n\nfunc allStatus() {\n\tvar statuses []ServiceStatus\n\tfor _, service := range services {\n\t\tstatuses = append(statuses, service.GetStatus()...)\n\t}\n\tfor _, status := range statuses {\n\t\tif status.Status != \"STOPPED\" {\n\t\t\tprintln(status.Service.Name, \":\", status.Status)\n\t\t}\n\t}\n}\n\nfunc status(c *cli.Context) error {\n\n\tif len(c.Args()) == 0 {\n\t\tallStatus()\n\t\treturn nil\n\t}\n\n\tsgs, err := getServicesOrGroups(c.Args())\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, s := range sgs {\n\t\tstatuses := s.GetStatus()\n\t\tfor _, status := range statuses {\n\t\t\tprintln(status.Service.Name, \":\", status.Status)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc messages(c *cli.Context) error {\n\treturn errors.New(\"Unimplemented\")\n}\n\nfunc start(c *cli.Context) error {\n\tsgs, err := getServicesOrGroups(c.Args())\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, s := range sgs {\n\t\tprintln(\"==== Build Phase ====\")\n\t\terr = s.Build()\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Error building \" + s.GetName() + \": \" + err.Error())\n\t\t}\n\t\tprintln(\"==== Launch Phase ====\")\n\t\terr = s.Start()\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Error launching \" + s.GetName() + \": \" + err.Error())\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc allServices() []ServiceOrGroup {\n\tvar as []ServiceOrGroup\n\tfor _, service := range services {\n\t\tas = append(as, service)\n\t}\n\treturn as\n}\n\nfunc stop(c *cli.Context) error {\n\tvar sgs []ServiceOrGroup\n\tvar err error\n\tif len(c.Args()) == 0 {\n\t\tsgs = allServices()\n\t} else {\n\t\tsgs, err = getServicesOrGroups(c.Args())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor _, s := range sgs {\n\t\t_ = s.Stop()\n\t}\n\treturn nil\n}\n\nfunc restart(c *cli.Context) error {\n\tsgs, err := getServicesOrGroups(c.Args())\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, s := range sgs {\n\t\t_ = s.Stop()\n\t\terr = s.Build()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = s.Start()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc doLog(c *cli.Context) error {\n\tif len(c.Args()) > 1 {\n\t\treturn errors.New(\"Cannot output multiple service logs\")\n\t}\n\tname := c.Args()[0]\n\tif _, ok := groups[name]; ok {\n\t\treturn errors.New(\"Cannot output group logs\")\n\t}\n\tif service, ok := services[name]; ok {\n\t\tcommand := service.GetCommand()\n\t\trunLog := command.Logs.Run\n\t\tt, err := tail.TailFile(runLog, tail.Config{Follow: true})\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tfor line := range t.Lines {\n\t\t\tprintln(line.Text)\n\t\t}\n\t\treturn nil\n\t}\n\treturn errors.New(\"Service not found: \" + name)\n}\n\nfunc checkNotSudo() {\n\tuser, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif user.Uid == \"0\" {\n\t\tlog.Fatal(\"edward should not be run with sudo\")\n\t}\n}\n\nfunc createScriptFile(suffix string, content string) (*os.File, error) {\n\tfile, err := ioutil.TempFile(os.TempDir(), suffix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfile.WriteString(content)\n\tfile.Close()\n\n\terr = os.Chmod(file.Name(), 0777)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn file, nil\n}\n\nfunc ensureSudoAble() {\n\tvar buffer bytes.Buffer\n\n\tbuffer.WriteString(\"#!\/bin\/bash\\n\")\n\tbuffer.WriteString(\"sudo echo Test > \/dev\/null\\n\")\n\tbuffer.WriteString(\"ISCHILD=YES \")\n\tbuffer.WriteString(strings.Join(os.Args, \" \"))\n\tbuffer.WriteString(\"\\n\")\n\n\tfile, err := createScriptFile(\"sudoAbility\", buffer.String())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = syscall.Exec(file.Name(), []string{file.Name()}, os.Environ())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc prepareForSudo() {\n\tcheckNotSudo()\n\n\tisChild := os.Getenv(\"ISCHILD\")\n\tif isChild == \"\" {\n\t\tensureSudoAble()\n\t\treturn\n\t}\n}\n\nfunc RemoveContents(dir string) error {\n\td, err := os.Open(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer d.Close()\n\tnames, err := d.Readdirnames(-1)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, name := range names {\n\t\terr = os.RemoveAll(filepath.Join(dir, name))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc refreshForReboot() error {\n\trebootFile := path.Join(EdwardConfig.Dir, \".lastreboot\")\n\n\trebootMarker, _ := ioutil.ReadFile(rebootFile)\n\n\tcommand := exec.Command(\"last\", \"-1\", \"reboot\")\n\toutput, err := command.CombinedOutput()\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\tif string(output) != string(rebootMarker) {\n\t\terr = RemoveContents(EdwardConfig.PidDir)\n\t\tif err != nil {\n\t\t\treturn errgo.Mask(err)\n\t\t}\n\t\terr = ioutil.WriteFile(rebootFile, output, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn errgo.Mask(err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\n\tapp := cli.NewApp()\n\tapp.Name = \"Edward\"\n\tapp.Usage = \"Manage local microservices\"\n\tapp.Before = func(c *cli.Context) error {\n\t\tcommand := c.Args().First()\n\t\tif command == \"start\" || command == \"stop\" || command == \"restart\" {\n\t\t\tprepareForSudo()\n\t\t}\n\n\t\terr := EdwardConfig.initialize()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = refreshForReboot()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tloadConfig()\n\t\treturn nil\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:   \"list\",\n\t\t\tUsage:  \"List available services\",\n\t\t\tAction: list,\n\t\t},\n\t\t{\n\t\t\tName:   \"generate\",\n\t\t\tUsage:  \"Generate Edward config for a source tree\",\n\t\t\tAction: generate,\n\t\t},\n\t\t{\n\t\t\tName:   \"status\",\n\t\t\tUsage:  \"Display service status\",\n\t\t\tAction: status,\n\t\t},\n\t\t{\n\t\t\tName:   \"messages\",\n\t\t\tUsage:  \"Show messages from services\",\n\t\t\tAction: messages,\n\t\t},\n\t\t{\n\t\t\tName:   \"start\",\n\t\t\tUsage:  \"Build and launch a service\",\n\t\t\tAction: start,\n\t\t},\n\t\t{\n\t\t\tName:   \"stop\",\n\t\t\tUsage:  \"Stop a service\",\n\t\t\tAction: stop,\n\t\t},\n\t\t{\n\t\t\tName:   \"restart\",\n\t\t\tUsage:  \"Rebuild and relaunch a service\",\n\t\t\tAction: restart,\n\t\t},\n\t\t{\n\t\t\tName:    \"log\",\n\t\t\tAliases: []string{\"tail\"},\n\t\t\tUsage:   \"Tail the log for a service\",\n\t\t\tAction:  doLog,\n\t\t},\n\t}\n\n\terr := app.Run(os.Args)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>Search for a config file first in the current working directory, then the root of the current working dir's git repo, then the Edward home dir.<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/user\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/hpcloud\/tail\"\n\t\"github.com\/yext\/errgo\"\n)\n\ntype EdwardConfiguration struct {\n\tDir       string\n\tLogDir    string\n\tPidDir    string\n\tScriptDir string\n}\n\nvar EdwardConfig EdwardConfiguration = EdwardConfiguration{}\n\nfunc createDirIfNeeded(path string) {\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\tos.MkdirAll(path, 0777)\n\t}\n}\n\nfunc (e *EdwardConfiguration) initialize() error {\n\tuser, err := user.Current()\n\tif err != nil {\n\t\treturn err\n\t}\n\te.Dir = path.Join(user.HomeDir, \".edward\")\n\te.LogDir = path.Join(e.Dir, \"logs\")\n\te.PidDir = path.Join(e.Dir, \"pidFiles\")\n\te.ScriptDir = path.Join(e.Dir, \"scriptFiles\")\n\tcreateDirIfNeeded(e.Dir)\n\tcreateDirIfNeeded(e.LogDir)\n\tcreateDirIfNeeded(e.PidDir)\n\tcreateDirIfNeeded(e.ScriptDir)\n\treturn nil\n}\n\nvar groups map[string]*ServiceGroupConfig\nvar services map[string]*ServiceConfig\n\nfunc thirdPartyService(name string, startCommand string, stopCommand string, started string) *ServiceConfig {\n\tpathStr := \"$ALPHA\"\n\treturn &ServiceConfig{\n\t\tName: name,\n\t\tPath: &pathStr,\n\t\tEnv:  []string{\"YEXT_RABBITMQ=localhost\"},\n\t\tCommands: ServiceConfigCommands{\n\t\t\tLaunch: startCommand,\n\t\t\tStop:   stopCommand,\n\t\t},\n\t\tProperties: ServiceConfigProperties{\n\t\t\tStarted: started,\n\t\t},\n\t}\n}\n\nfunc getAlpha() string {\n\tfor _, env := range os.Environ() {\n\t\tpair := strings.Split(env, \"=\")\n\t\tif pair[0] == \"ALPHA\" {\n\t\t\treturn pair[1]\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc addFoundServices() {\n\tfoundServices, _, err := generateServices(getAlpha())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, s := range foundServices {\n\t\tif _, found := services[s.Name]; !found {\n\t\t\tservices[s.Name] = s\n\t\t}\n\t}\n}\n\n\/\/ getConfigPath identifies the location of edward.json, if any exists\nfunc getConfigPath() string {\n\tvar pathOptions []string\n\n\t\/\/ Config file in current working directory\n\twd, err := os.Getwd()\n\tif err == nil {\n\t\tpathOptions = append(pathOptions, filepath.Join(wd, \"edward.json\"))\n\t}\n\n\t\/\/ Config file at root of working dir's git repo, if any\n\tgitRoot, err := gitRoot()\n\tif err == nil {\n\t\tpathOptions = append(pathOptions, filepath.Join(gitRoot, \"edward.json\"))\n\n\t}\n\n\t\/\/ Config file in Edward Config dir\n\tpathOptions = append(pathOptions, filepath.Join(EdwardConfig.Dir, \"edward.json\"))\n\n\tfor _, path := range pathOptions {\n\t\tif _, err := os.Stat(path); err == nil {\n\t\t\treturn path\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\nfunc gitRoot() (string, error) {\n\toutput, err := exec.Command(\"git\", \"rev-parse\", \"--show-toplevel\").CombinedOutput()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"%v\\n%v\", string(output), err)\n\t}\n\treturn strings.TrimSpace(string(output)), nil\n}\n\nfunc loadConfig() {\n\tgroups = make(map[string]*ServiceGroupConfig)\n\tservices = make(map[string]*ServiceConfig)\n\n\tconfigPath := getConfigPath()\n\n\tif configPath != \"\" {\n\t\tprintln(\"Loading configuration from\", configPath)\n\t\tr, err := os.Open(configPath)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tconfig, err := LoadConfig(r)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tservices = config.ServiceMap\n\t\tgroups = config.GroupMap\n\t\treturn\n\t} else {\n\t\taddFoundServices()\n\t\tapplyHardCodedServicesAndGroups()\n\t}\n\n}\n\nfunc getServicesOrGroups(names []string) ([]ServiceOrGroup, error) {\n\tvar outSG []ServiceOrGroup\n\tfor _, name := range names {\n\t\tsg, err := getServiceOrGroup(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\toutSG = append(outSG, sg)\n\t}\n\treturn outSG, nil\n}\n\nfunc getServiceOrGroup(name string) (ServiceOrGroup, error) {\n\tif group, ok := groups[name]; ok {\n\t\treturn group, nil\n\t}\n\tif service, ok := services[name]; ok {\n\t\treturn service, nil\n\t}\n\treturn nil, errors.New(\"Service or group not found\")\n}\n\nfunc list(c *cli.Context) error {\n\n\tvar groupNames []string\n\tvar serviceNames []string\n\tfor name, _ := range groups {\n\t\tgroupNames = append(groupNames, name)\n\t}\n\tfor name, _ := range services {\n\t\tserviceNames = append(serviceNames, name)\n\t}\n\n\tsort.Strings(groupNames)\n\tsort.Strings(serviceNames)\n\n\tprintln(\"Services and groups\")\n\tprintln(\"Groups:\")\n\tfor _, name := range groupNames {\n\t\tprintln(\"\\t\", name)\n\t}\n\tprintln(\"Services:\")\n\tfor _, name := range serviceNames {\n\t\tprintln(\"\\t\", name)\n\t}\n\n\treturn nil\n}\n\nfunc generate(c *cli.Context) error {\n\n\t\/\/ Add any new services to the config as appropriate\n\taddFoundServices()\n\n\tconfigPath := getConfigPath()\n\tif configPath == \"\" {\n\t\twd, err := os.Getwd()\n\t\tif err == nil {\n\t\t\tconfigPath = filepath.Join(wd, \"edward.json\")\n\t\t}\n\t}\n\n\tif err := generateConfigFile(configPath); err != nil {\n\t\treturn err\n\t}\n\tprintln(\"Wrote to\", configPath)\n\n\treturn nil\n}\n\nfunc allStatus() {\n\tvar statuses []ServiceStatus\n\tfor _, service := range services {\n\t\tstatuses = append(statuses, service.GetStatus()...)\n\t}\n\tfor _, status := range statuses {\n\t\tif status.Status != \"STOPPED\" {\n\t\t\tprintln(status.Service.Name, \":\", status.Status)\n\t\t}\n\t}\n}\n\nfunc status(c *cli.Context) error {\n\n\tif len(c.Args()) == 0 {\n\t\tallStatus()\n\t\treturn nil\n\t}\n\n\tsgs, err := getServicesOrGroups(c.Args())\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, s := range sgs {\n\t\tstatuses := s.GetStatus()\n\t\tfor _, status := range statuses {\n\t\t\tprintln(status.Service.Name, \":\", status.Status)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc messages(c *cli.Context) error {\n\treturn errors.New(\"Unimplemented\")\n}\n\nfunc start(c *cli.Context) error {\n\tsgs, err := getServicesOrGroups(c.Args())\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, s := range sgs {\n\t\tprintln(\"==== Build Phase ====\")\n\t\terr = s.Build()\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Error building \" + s.GetName() + \": \" + err.Error())\n\t\t}\n\t\tprintln(\"==== Launch Phase ====\")\n\t\terr = s.Start()\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Error launching \" + s.GetName() + \": \" + err.Error())\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc allServices() []ServiceOrGroup {\n\tvar as []ServiceOrGroup\n\tfor _, service := range services {\n\t\tas = append(as, service)\n\t}\n\treturn as\n}\n\nfunc stop(c *cli.Context) error {\n\tvar sgs []ServiceOrGroup\n\tvar err error\n\tif len(c.Args()) == 0 {\n\t\tsgs = allServices()\n\t} else {\n\t\tsgs, err = getServicesOrGroups(c.Args())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor _, s := range sgs {\n\t\t_ = s.Stop()\n\t}\n\treturn nil\n}\n\nfunc restart(c *cli.Context) error {\n\tsgs, err := getServicesOrGroups(c.Args())\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, s := range sgs {\n\t\t_ = s.Stop()\n\t\terr = s.Build()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = s.Start()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc doLog(c *cli.Context) error {\n\tif len(c.Args()) > 1 {\n\t\treturn errors.New(\"Cannot output multiple service logs\")\n\t}\n\tname := c.Args()[0]\n\tif _, ok := groups[name]; ok {\n\t\treturn errors.New(\"Cannot output group logs\")\n\t}\n\tif service, ok := services[name]; ok {\n\t\tcommand := service.GetCommand()\n\t\trunLog := command.Logs.Run\n\t\tt, err := tail.TailFile(runLog, tail.Config{Follow: true})\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tfor line := range t.Lines {\n\t\t\tprintln(line.Text)\n\t\t}\n\t\treturn nil\n\t}\n\treturn errors.New(\"Service not found: \" + name)\n}\n\nfunc checkNotSudo() {\n\tuser, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif user.Uid == \"0\" {\n\t\tlog.Fatal(\"edward should not be run with sudo\")\n\t}\n}\n\nfunc createScriptFile(suffix string, content string) (*os.File, error) {\n\tfile, err := ioutil.TempFile(os.TempDir(), suffix)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfile.WriteString(content)\n\tfile.Close()\n\n\terr = os.Chmod(file.Name(), 0777)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn file, nil\n}\n\nfunc ensureSudoAble() {\n\tvar buffer bytes.Buffer\n\n\tbuffer.WriteString(\"#!\/bin\/bash\\n\")\n\tbuffer.WriteString(\"sudo echo Test > \/dev\/null\\n\")\n\tbuffer.WriteString(\"ISCHILD=YES \")\n\tbuffer.WriteString(strings.Join(os.Args, \" \"))\n\tbuffer.WriteString(\"\\n\")\n\n\tfile, err := createScriptFile(\"sudoAbility\", buffer.String())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = syscall.Exec(file.Name(), []string{file.Name()}, os.Environ())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc prepareForSudo() {\n\tcheckNotSudo()\n\n\tisChild := os.Getenv(\"ISCHILD\")\n\tif isChild == \"\" {\n\t\tensureSudoAble()\n\t\treturn\n\t}\n}\n\nfunc RemoveContents(dir string) error {\n\td, err := os.Open(dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer d.Close()\n\tnames, err := d.Readdirnames(-1)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, name := range names {\n\t\terr = os.RemoveAll(filepath.Join(dir, name))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc refreshForReboot() error {\n\trebootFile := path.Join(EdwardConfig.Dir, \".lastreboot\")\n\n\trebootMarker, _ := ioutil.ReadFile(rebootFile)\n\n\tcommand := exec.Command(\"last\", \"-1\", \"reboot\")\n\toutput, err := command.CombinedOutput()\n\tif err != nil {\n\t\treturn errgo.Mask(err)\n\t}\n\n\tif string(output) != string(rebootMarker) {\n\t\terr = RemoveContents(EdwardConfig.PidDir)\n\t\tif err != nil {\n\t\t\treturn errgo.Mask(err)\n\t\t}\n\t\terr = ioutil.WriteFile(rebootFile, output, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn errgo.Mask(err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\n\tapp := cli.NewApp()\n\tapp.Name = \"Edward\"\n\tapp.Usage = \"Manage local microservices\"\n\tapp.Before = func(c *cli.Context) error {\n\t\tcommand := c.Args().First()\n\t\tif command == \"start\" || command == \"stop\" || command == \"restart\" {\n\t\t\tprepareForSudo()\n\t\t}\n\n\t\terr := EdwardConfig.initialize()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = refreshForReboot()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tloadConfig()\n\t\treturn nil\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:   \"list\",\n\t\t\tUsage:  \"List available services\",\n\t\t\tAction: list,\n\t\t},\n\t\t{\n\t\t\tName:   \"generate\",\n\t\t\tUsage:  \"Generate Edward config for a source tree\",\n\t\t\tAction: generate,\n\t\t},\n\t\t{\n\t\t\tName:   \"status\",\n\t\t\tUsage:  \"Display service status\",\n\t\t\tAction: status,\n\t\t},\n\t\t{\n\t\t\tName:   \"messages\",\n\t\t\tUsage:  \"Show messages from services\",\n\t\t\tAction: messages,\n\t\t},\n\t\t{\n\t\t\tName:   \"start\",\n\t\t\tUsage:  \"Build and launch a service\",\n\t\t\tAction: start,\n\t\t},\n\t\t{\n\t\t\tName:   \"stop\",\n\t\t\tUsage:  \"Stop a service\",\n\t\t\tAction: stop,\n\t\t},\n\t\t{\n\t\t\tName:   \"restart\",\n\t\t\tUsage:  \"Rebuild and relaunch a service\",\n\t\t\tAction: restart,\n\t\t},\n\t\t{\n\t\t\tName:    \"log\",\n\t\t\tAliases: []string{\"tail\"},\n\t\t\tUsage:   \"Tail the log for a service\",\n\t\t\tAction:  doLog,\n\t\t},\n\t}\n\n\terr := app.Run(os.Args)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"mime\"\n\t\"net\/mail\"\n\t\"net\/smtp\"\n\t\"os\"\n\t\"strconv\"\n\n\tmessage \"github.com\/matsuev\/go-message\"\n\tcharset \"github.com\/matsuev\/go-message\/charset\"\n\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\nfunc main() {\n\t\/\/ Перенаправление логов в файл\n\t\/\/ создать файл лога, установить права доступа\n\t\/\/ l, err := os.OpenFile(\".\/klshmail.log\", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)\n\t\/\/ l, err := os.OpenFile(\"\/var\/log\/klshmail.log\", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)\n\t\/\/ logFatal(err)\n\t\/\/ defer l.Close()\n\n\t\/\/ log.SetOutput(l)\n\n\t\/\/ Заголовки исходного сообщения,\n\t\/\/ которые нужно оставить\n\thh := []string{\n\t\t\"MIME-Version\",\n\t\t\"Message-Id\",\n\t\t\"Content-Type\",\n\t\t\"Content-Transfer-Encoding\",\n\t\t\"In-Reply-To\",\n\t\t\"References\",\n\t\t\/\/ \"Subject\",\n\t}\n\n\tr, err := os.Open(\".\/testmessage.eml\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\n\t\/\/ Читаем сообщение из стандартного ввода\n\t\/\/ msg, err := message.Read(os.Stdin)\n\tmsg, err := message.Read(r)\n\tlogFatal(err)\n\tlog.Println(\"New message accepted...\")\n\n\t\/\/ Разбор заголовков сообщения\n\tto, err := getMailHeader(\"To\", msg.Header)\n\tlogFatal(err)\n\tlog.Printf(\"To: %s <%s>\\n\", to.Name, to.Address)\n\n\tfrom, err := getMailHeader(\"From\", msg.Header)\n\tlogFatal(err)\n\tlog.Printf(\"From: %s <%s>\\n\", from.Name, from.Address)\n\n\thSubject, err := charset.DecodeHeader(msg.Header.Get(\"Subject\"))\n\tlogFatal(err)\n\n\tsubj := mime.BEncoding.Encode(\"utf-8\", hSubject)\n\n\tif to.Address == \"\" || from.Address == \"\" {\n\t\tlog.Fatalln(\"Empty address. Reject message.\")\n\t}\n\n\t\/\/ Сокдинение с сервером БД\n\tdb, err := sql.Open(\"mysql\", \"klshmail:euXoe8uSha1xu4sh@\/klshmail?charset=utf8\")\n\tlogFatal(err)\n\n\t\/\/ Проверка соединения с сервером БД\n\terr = db.Ping()\n\tlogFatal(err)\n\n\t\/\/ Запрос данных о списке рассылки\n\tvar lid uint64\n\tvar lprefix string\n\n\terr = db.QueryRow(`\n\t\tSELECT list.id, list.prefix\n\t\tFROM list\n\t\tWHERE LCASE(list.email)=TRIM(LCASE(?))\n\t\tAND list.active\n\t\t`, to.Address).Scan(&lid, &lprefix)\n\tif err != nil {\n\t\tlog.Println(\"No list with address:\", to.Address)\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Запрос на проверку прав пользователя на отправку сообщений в список\n\tvar uid uint64\n\terr = db.QueryRow(`\n\t\tSELECT user.id\n\t\tFROM user\n\t\tINNER JOIN user_list\n\t\tON (user_list.lid=?\n\t\t\tAND user.id=user_list.uid\n\t\t\tAND user_list.canwrite\n\t\t)\n\t\tWHERE LCASE(user.email)=TRIM(LCASE(?))\n\t\tAND user.active\n\t\t`, lid, from.Address).Scan(&uid)\n\tif err != nil {\n\t\tlog.Println(\"User\", from.Address, \"can't send messages to\", to.Address)\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Формирование заголовков нового сообщения\n\tnewHeader := make(message.Header)\n\tfor _, hk := range hh {\n\t\tif hv := msg.Header.Get(hk); hv != \"\" {\n\t\t\tnewHeader.Set(hk, hv)\n\t\t}\n\t}\n\n\tsender := new(mail.Address)\n\tsender.Name = from.Name\n\tsender.Address = from.Address\n\n\tfrom.Name = fmt.Sprintf(\"%s\", lprefix)\n\tfrom.Address = to.Address\n\n\tnewHeader.Set(\"From\", from.String())\n\tnewHeader.Set(\"Reply-To\", to.Address)\n\tnewHeader.Set(\"Subject\", subj)\n\tnewHeader.Set(\"X-KLSH-Sender\", strconv.FormatUint(uid, 10))\n\n\tvar b bytes.Buffer\n\tw, err := message.CreateWriter(&b, newHeader)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer w.Close()\n\n\tif err := transform(w, msg, sender); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Подключение к SMTP серверу\n\tc, err := smtp.Dial(\"127.0.0.1:25\")\n\tif err != nil {\n\t\tlog.Println(\"SMTP connection error\")\n\t\tlog.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\t\/\/ \/\/ Заголовки для отправки\n\t\/\/ c.Mail(to.Address)\n\t\/\/ c.Rcpt(fmt.Sprintf(\"%v@klshmail\", lid))\n\t\/\/\n\t\/\/ wc, err := c.Data()\n\t\/\/ logFatal(err)\n\t\/\/ defer wc.Close()\n\t\/\/\n\t\/\/ \/\/ Отправка сообщения\n\t\/\/ br := bytes.NewReader(b.Bytes())\n\t\/\/ if _, err = io.Copy(wc, br); err != nil {\n\t\/\/ \tlog.Println(\"SMTP send body error\")\n\t\/\/ \tlog.Fatalln(err)\n\t\/\/ }\n\n\tfmt.Println(b.String())\n\n\t\/\/ Завершение работы\n\tlog.Println(\"Message processing done.\")\n\n}\n\nfunc logFatal(e error) {\n\tif e != nil {\n\t\tlog.Fatalln(e)\n\t}\n}\n\nconst senderHtml string = `<p><b>Сообщение от:<\/b> %s &lt;<a href=\"mailto:%s\">%s<\/a>&gt;<p>`\nconst senderPlain string = \"| Сообщение от:  %s <%s>\\n——\\n\\n\"\n\nfunc transform(w *message.Writer, e *message.Entity, sender *mail.Address) error {\n\tif mr := e.MultipartReader(); mr != nil {\n\t\t\/\/ This is a multipart entity, transform each of its parts\n\t\tfor {\n\t\t\tp, err := mr.NextPart()\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t} else if err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpw, err := w.CreatePart(p.Header)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := transform(pw, p, sender); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpw.Close()\n\t\t}\n\t\treturn nil\n\t} else {\n\t\tbody := e.Body\n\t\t\/\/ var newLine string\n\t\t\/\/ if strings.HasPrefix(e.Header.Get(\"Content-Type\"), \"text\/plain\") {\n\t\t\/\/ \tnewLine = fmt.Sprintf(senderPlain, sender.Name, sender.Address)\n\t\t\/\/ }\n\t\t\/\/ if strings.HasPrefix(e.Header.Get(\"Content-Type\"), \"text\/html\") {\n\t\t\/\/ \tnewLine = fmt.Sprintf(senderHtml, sender.Name, sender.Address, sender.Address)\n\t\t\/\/ }\n\t\t\/\/ body = io.MultiReader(strings.NewReader(newLine), body)\n\t\t_, err := io.Copy(w, body)\n\t\treturn err\n\t}\n}\n\nfunc getMailHeader(k string, h message.Header) (*mail.Address, error) {\n\tdh, err := charset.DecodeHeader(h.Get(k))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trh, err := mail.ParseAddress(dh)\n\treturn rh, err\n}\n<commit_msg>Update main.go<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"mime\"\n\t\"net\/mail\"\n\t\"net\/smtp\"\n\t\"os\"\n\t\"strconv\"\n\n\tmessage \"github.com\/matsuev\/go-message\"\n\tcharset \"github.com\/matsuev\/go-message\/charset\"\n\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\nfunc main() {\n\t\/\/ Перенаправление логов в файл\n\t\/\/ создать файл лога, установить права доступа\n\t\/\/ l, err := os.OpenFile(\".\/klshmail.log\", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)\n\t\/\/ l, err := os.OpenFile(\"\/var\/log\/klshmail.log\", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)\n\t\/\/ logFatal(err)\n\t\/\/ defer l.Close()\n\n\t\/\/ log.SetOutput(l)\n\n\t\/\/ Заголовки исходного сообщения,\n\t\/\/ которые нужно оставить\n\thh := []string{\n\t\t\"MIME-Version\",\n\t\t\"Message-Id\",\n\t\t\"Content-Type\",\n\t\t\"Content-Transfer-Encoding\",\n\t\t\"In-Reply-To\",\n\t\t\"References\",\n\t\t\/\/ \"Subject\",\n\t}\n\n\tr, err := os.Open(\".\/testmessage.eml\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer r.Close()\n\n\t\/\/ Читаем сообщение из стандартного ввода\n\t\/\/ msg, err := message.Read(os.Stdin)\n\tmsg, err := message.Read(r)\n\tlogFatal(err)\n\tlog.Println(\"New message accepted...\")\n\n\t\/\/ Разбор заголовков сообщения\n\tto, err := getMailHeader(\"To\", msg.Header)\n\tlogFatal(err)\n\tlog.Printf(\"To: %s <%s>\\n\", to.Name, to.Address)\n\n\tfrom, err := getMailHeader(\"From\", msg.Header)\n\tlogFatal(err)\n\tlog.Printf(\"From: %s <%s>\\n\", from.Name, from.Address)\n\n\thSubject, err := charset.DecodeHeader(msg.Header.Get(\"Subject\"))\n\tlogFatal(err)\n\n\tsubj := mime.BEncoding.Encode(\"utf-8\", hSubject)\n\n\tif to.Address == \"\" || from.Address == \"\" {\n\t\tlog.Fatalln(\"Empty address. Reject message.\")\n\t}\n\n\t\/\/ Сокдинение с сервером БД\n\tdb, err := sql.Open(\"mysql\", \"klshmail:euXoe8uSha1xu4sh@\/klshmail?charset=utf8\")\n\tlogFatal(err)\n\n\t\/\/ Проверка соединения с сервером БД\n\terr = db.Ping()\n\tlogFatal(err)\n\n\t\/\/ Запрос данных о списке рассылки\n\tvar lid uint64\n\tvar lprefix string\n\n\terr = db.QueryRow(`\n\t\tSELECT list.id, list.prefix\n\t\tFROM list\n\t\tWHERE LCASE(list.email)=TRIM(LCASE(?))\n\t\tAND list.active\n\t\t`, to.Address).Scan(&lid, &lprefix)\n\tif err != nil {\n\t\tlog.Println(\"No list with address:\", to.Address)\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Запрос на проверку прав пользователя на отправку сообщений в список\n\tvar uid uint64\n\terr = db.QueryRow(`\n\t\tSELECT user.id\n\t\tFROM user\n\t\tINNER JOIN user_list\n\t\tON (user_list.lid=?\n\t\t\tAND user.id=user_list.uid\n\t\t\tAND user_list.canwrite\n\t\t)\n\t\tWHERE LCASE(user.email)=TRIM(LCASE(?))\n\t\tAND user.active\n\t\t`, lid, from.Address).Scan(&uid)\n\tif err != nil {\n\t\tlog.Println(\"User\", from.Address, \"can't send messages to\", to.Address)\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Формирование заголовков нового сообщения\n\tnewHeader := make(message.Header)\n\tfor _, hk := range hh {\n\t\tif hv := msg.Header.Get(hk); hv != \"\" {\n\t\t\tnewHeader.Set(hk, hv)\n\t\t}\n\t}\n\n\tsender := new(mail.Address)\n\tsender.Name = from.Name\n\tsender.Address = from.Address\n\n\tfrom.Name = fmt.Sprintf(\"%s\", lprefix)\n\tfrom.Address = to.Address\n\n\tnewHeader.Set(\"From\", from.String())\n\tnewHeader.Set(\"Reply-To\", to.Address)\n\tnewHeader.Set(\"Subject\", subj)\n\tnewHeader.Set(\"X-KLSH-Sender\", strconv.FormatUint(uid, 10))\n\n\tvar b bytes.Buffer\n\tw, err := message.CreateWriter(&b, newHeader)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer w.Close()\n\n\tif err := transform(w, msg, sender); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Подключение к SMTP серверу\n\tc, err := smtp.Dial(\"127.0.0.1:25\")\n\tif err != nil {\n\t\tlog.Println(\"SMTP connection error\")\n\t\tlog.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\t\/\/ \/\/ Заголовки для отправки\n\t\/\/ c.Mail(to.Address)\n\t\/\/ c.Rcpt(fmt.Sprintf(\"%v@klshmail\", lid))\n\t\/\/\n\t\/\/ wc, err := c.Data()\n\t\/\/ logFatal(err)\n\t\/\/ defer wc.Close()\n\t\/\/\n\t\/\/ \/\/ Отправка сообщения\n\t\/\/ br := bytes.NewReader(b.Bytes())\n\t\/\/ if _, err = io.Copy(wc, br); err != nil {\n\t\/\/ \tlog.Println(\"SMTP send body error\")\n\t\/\/ \tlog.Fatalln(err)\n\t\/\/ }\n\n\tfmt.Println(b.String())\n\n\t\/\/ Завершение работы\n\tlog.Println(\"Message processing done.\")\n\n}\n\nfunc logFatal(e error) {\n\tif e != nil {\n\t\tlog.Fatalln(e)\n\t}\n}\n\nconst senderHtml string = `<p><b>Сообщение от:<\/b> %s &lt;<a href=\"mailto:%s\">%s<\/a>&gt;<p>`\nconst senderPlain string = \"| Сообщение от:  %s <%s>\\n——\\n\\n\"\n\nfunc transform(w *message.Writer, e *message.Entity, sender *mail.Address) error {\n\tif mr := e.MultipartReader(); mr != nil {\n\t\t\/\/ This is a multipart entity, transform each of its parts\n\t\tfor {\n\t\t\tp, err := mr.NextPart()\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t} else if err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfmt.Println(p.Header)\n\n\t\t\tpw, err := w.CreatePart(p.Header)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := transform(pw, p, sender); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpw.Close()\n\t\t}\n\t\treturn nil\n\t} else {\n\t\tbody := e.Body\n\t\t\/\/ var newLine string\n\t\t\/\/ if strings.HasPrefix(e.Header.Get(\"Content-Type\"), \"text\/plain\") {\n\t\t\/\/ \tnewLine = fmt.Sprintf(senderPlain, sender.Name, sender.Address)\n\t\t\/\/ }\n\t\t\/\/ if strings.HasPrefix(e.Header.Get(\"Content-Type\"), \"text\/html\") {\n\t\t\/\/ \tnewLine = fmt.Sprintf(senderHtml, sender.Name, sender.Address, sender.Address)\n\t\t\/\/ }\n\t\t\/\/ body = io.MultiReader(strings.NewReader(newLine), body)\n\t\t_, err := io.Copy(w, body)\n\t\treturn err\n\t}\n}\n\nfunc getMailHeader(k string, h message.Header) (*mail.Address, error) {\n\tdh, err := charset.DecodeHeader(h.Get(k))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trh, err := mail.ParseAddress(dh)\n\treturn rh, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\npackage main\n\nimport (\n\t\"context\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"time\"\n\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/codes\"\n\t\"google.golang.org\/grpc\/credentials\"\n\thealthpb \"google.golang.org\/grpc\/health\/grpc_health_v1\"\n\t\"google.golang.org\/grpc\/status\"\n)\n\nvar (\n\tflAddr          string\n\tflService       string\n\tflUserAgent     string\n\tflConnTimeout   time.Duration\n\tflRPCTimeout    time.Duration\n\tflTLS           bool\n\tflTLSNoVerify   bool\n\tflTLSCACert     string\n\tflTLSClientCert string\n\tflTLSClientKey  string\n\tflTLSServerName string\n\tflVerbose       bool\n)\n\nconst (\n\t\/\/ StatusInvalidArguments indicates specified invalid arguments.\n\tStatusInvalidArguments = 1\n\t\/\/ StatusConnectionFailure indicates connection failed.\n\tStatusConnectionFailure = 2\n\t\/\/ StatusRPCFailure indicates rpc failed.\n\tStatusRPCFailure = 3\n\t\/\/ StatusUnhealthy indicates rpc succeeded but indicates unhealthy service.\n\tStatusUnhealthy = 4\n)\n\nfunc init() {\n\tlog.SetFlags(0)\n\tflag.StringVar(&flAddr, \"addr\", \"\", \"(required) tcp host:port to connect\")\n\tflag.StringVar(&flService, \"service\", \"\", \"service name to check (default: \\\"\\\")\")\n\tflag.StringVar(&flUserAgent, \"user-agent\", \"grpc_health_probe\", \"user-agent header value of health check requests\")\n\t\/\/ timeouts\n\tflag.DurationVar(&flConnTimeout, \"connect-timeout\", time.Second, \"timeout for establishing connection\")\n\tflag.DurationVar(&flRPCTimeout, \"rpc-timeout\", time.Second, \"timeout for health check rpc\")\n\t\/\/ tls settings\n\tflag.BoolVar(&flTLS, \"tls\", false, \"use TLS (default: false, INSECURE plaintext transport)\")\n\tflag.BoolVar(&flTLSNoVerify, \"tls-no-verify\", false, \"(with -tls) don't verify the certificate (INSECURE) presented by the server (default: false)\")\n\tflag.StringVar(&flTLSCACert, \"tls-ca-cert\", \"\", \"(with -tls, optional) file containing trusted certificates for verifying server\")\n\tflag.StringVar(&flTLSClientCert, \"tls-client-cert\", \"\", \"(with -tls, optional) client certificate for authenticating to the server (requires -tls-client-key)\")\n\tflag.StringVar(&flTLSClientKey, \"tls-client-key\", \"\", \"(with -tls) client private key for authenticating to the server (requires -tls-client-cert)\")\n\tflag.StringVar(&flTLSServerName, \"tls-server-name\", \"\", \"(with -tls) override the hostname used to verify the server certificate\")\n\tflag.BoolVar(&flVerbose, \"v\", false, \"verbose logs\")\n\n\tflag.Parse()\n\n\targError := func(s string, v ...interface{}) {\n\t\tlog.Printf(\"error: \"+s, v...)\n\t\tos.Exit(StatusInvalidArguments)\n\t}\n\n\tif flAddr == \"\" {\n\t\targError(\"-addr not specified\")\n\t}\n\tif flConnTimeout <= 0 {\n\t\targError(\"-connect-timeout must be greater than zero (specified: %v)\", flConnTimeout)\n\t}\n\tif flRPCTimeout <= 0 {\n\t\targError(\"-rpc-timeout must be greater than zero (specified: %v)\", flRPCTimeout)\n\t}\n\tif !flTLS && flTLSNoVerify {\n\t\targError(\"specified -tls-no-verify without specifying -tls\")\n\t}\n\tif !flTLS && flTLSCACert != \"\" {\n\t\targError(\"specified -tls-ca-cert without specifying -tls\")\n\t}\n\tif !flTLS && flTLSClientCert != \"\" {\n\t\targError(\"specified -tls-client-cert without specifying -tls\")\n\t}\n\tif !flTLS && flTLSServerName != \"\" {\n\t\targError(\"specified -tls-server-name without specifying -tls\")\n\t}\n\tif flTLSClientCert != \"\" && flTLSClientKey == \"\" {\n\t\targError(\"specified -tls-client-cert without specifying -tls-client-key\")\n\t}\n\tif flTLSClientCert == \"\" && flTLSClientKey != \"\" {\n\t\targError(\"specified -tls-client-key without specifying -tls-client-cert\")\n\t}\n\tif flTLSNoVerify && flTLSCACert != \"\" {\n\t\targError(\"cannot specify -tls-ca-cert with -tls-no-verify (CA cert would not be used)\")\n\t}\n\tif flTLSNoVerify && flTLSServerName != \"\" {\n\t\targError(\"cannot specify -tls-server-name with -tls-no-verify (server name would not be used)\")\n\t}\n\n\tif flVerbose {\n\t\tlog.Printf(\"parsed options:\")\n\t\tlog.Printf(\"> addr=%s conn_timeout=%v rpc_timeout=%v\", flAddr, flConnTimeout, flRPCTimeout)\n\t\tlog.Printf(\"> tls=%v\", flTLS)\n\t\tif flTLS {\n\t\t\tlog.Printf(\"  > no-verify=%v \", flTLSNoVerify)\n\t\t\tlog.Printf(\"  > ca-cert=%s\", flTLSCACert)\n\t\t\tlog.Printf(\"  > client-cert=%s\", flTLSClientCert)\n\t\t\tlog.Printf(\"  > client-key=%s\", flTLSClientKey)\n\t\t\tlog.Printf(\"  > server-name=%s\", flTLSServerName)\n\t\t}\n\t}\n}\n\nfunc buildCredentials(skipVerify bool, caCerts, clientCert, clientKey, serverName string) (credentials.TransportCredentials, error) {\n\tvar cfg tls.Config\n\n\tif clientCert != \"\" && clientKey != \"\" {\n\t\tkeyPair, err := tls.LoadX509KeyPair(clientCert, clientKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to load tls client cert\/key pair. error=%v\", err)\n\t\t}\n\t\tcfg.Certificates = []tls.Certificate{keyPair}\n\t}\n\n\tif skipVerify {\n\t\tcfg.InsecureSkipVerify = true\n\t} else if caCerts != \"\" {\n\t\t\/\/ override system roots\n\t\trootCAs := x509.NewCertPool()\n\t\tpem, err := ioutil.ReadFile(caCerts)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to load root CA certificates from file (%s) error=%v\", caCerts, err)\n\t\t}\n\t\tif !rootCAs.AppendCertsFromPEM(pem) {\n\t\t\treturn nil, fmt.Errorf(\"no root CA certs parsed from file %s\", caCerts)\n\t\t}\n\t\tcfg.RootCAs = rootCAs\n\t}\n\tif serverName != \"\" {\n\t\tcfg.ServerName = serverName\n\t}\n\treturn credentials.NewTLS(&cfg), nil\n}\n\nfunc main() {\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\tsig := <-c\n\t\tif sig == os.Interrupt {\n\t\t\tlog.Printf(\"cancellation received\")\n\t\t\tcancel()\n\t\t\treturn\n\t\t}\n\t}()\n\n\topts := []grpc.DialOption{\n\t\tgrpc.WithUserAgent(flUserAgent),\n\t\tgrpc.WithBlock()}\n\tif flTLS {\n\t\tcreds, err := buildCredentials(flTLSNoVerify, flTLSCACert, flTLSClientCert, flTLSClientKey, flTLSServerName)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"failed to initialize tls credentials. error=%v\", err)\n\t\t\tos.Exit(StatusInvalidArguments)\n\t\t}\n\t\topts = append(opts, grpc.WithTransportCredentials(creds))\n\t} else {\n\t\topts = append(opts, grpc.WithInsecure())\n\t}\n\n\tif flVerbose {\n\t\tlog.Print(\"establishing connection\")\n\t}\n\tconnStart := time.Now()\n\tdialCtx, cancel2 := context.WithTimeout(ctx, flConnTimeout)\n\tdefer cancel2()\n\tconn, err := grpc.DialContext(dialCtx, flAddr, opts...)\n\tif err != nil {\n\t\tif err == context.DeadlineExceeded {\n\t\t\tlog.Printf(\"timeout: failed to connect service %q within %v\", flAddr, flConnTimeout)\n\t\t} else {\n\t\t\tlog.Printf(\"error: failed to connect service at %q: %+v\", flAddr, err)\n\t\t}\n\t\tos.Exit(StatusConnectionFailure)\n\t}\n\tconnDuration := time.Since(connStart)\n\tdefer conn.Close()\n\tif flVerbose {\n\t\tlog.Printf(\"connection establisted (took %v)\", connDuration)\n\t}\n\n\trpcStart := time.Now()\n\trpcCtx, rpcCancel := context.WithTimeout(ctx, flRPCTimeout)\n\tdefer rpcCancel()\n\tresp, err := healthpb.NewHealthClient(conn).Check(rpcCtx, &healthpb.HealthCheckRequest{Service: flService})\n\tif err != nil {\n\t\tif stat, ok := status.FromError(err); ok && stat.Code() == codes.Unimplemented {\n\t\t\tlog.Printf(\"error: this server does not implement the grpc health protocol (grpc.health.v1.Health)\")\n\t\t} else if stat, ok := status.FromError(err); ok && stat.Code() == codes.DeadlineExceeded {\n\t\t\tlog.Printf(\"timeout: health rpc did not complete within %v\", flRPCTimeout)\n\t\t} else {\n\t\t\tlog.Printf(\"error: health rpc failed: %+v\", err)\n\t\t}\n\t\tos.Exit(StatusRPCFailure)\n\t}\n\trpcDuration := time.Since(rpcStart)\n\n\tif resp.GetStatus() != healthpb.HealthCheckResponse_SERVING {\n\t\tlog.Printf(\"service unhealthy (responded with %q)\", resp.GetStatus().String())\n\t\tos.Exit(StatusUnhealthy)\n\t}\n\tif flVerbose {\n\t\tlog.Printf(\"time elapsed: connect=%v rpc=%v\", connDuration, rpcDuration)\n\t}\n\tlog.Printf(\"status: %v\", resp.GetStatus().String())\n}\n<commit_msg>Close connection before exiting (#36)<commit_after>\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\npackage main\n\nimport (\n\t\"context\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"time\"\n\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/codes\"\n\t\"google.golang.org\/grpc\/credentials\"\n\thealthpb \"google.golang.org\/grpc\/health\/grpc_health_v1\"\n\t\"google.golang.org\/grpc\/status\"\n)\n\nvar (\n\tflAddr          string\n\tflService       string\n\tflUserAgent     string\n\tflConnTimeout   time.Duration\n\tflRPCTimeout    time.Duration\n\tflTLS           bool\n\tflTLSNoVerify   bool\n\tflTLSCACert     string\n\tflTLSClientCert string\n\tflTLSClientKey  string\n\tflTLSServerName string\n\tflVerbose       bool\n)\n\nconst (\n\t\/\/ StatusInvalidArguments indicates specified invalid arguments.\n\tStatusInvalidArguments = 1\n\t\/\/ StatusConnectionFailure indicates connection failed.\n\tStatusConnectionFailure = 2\n\t\/\/ StatusRPCFailure indicates rpc failed.\n\tStatusRPCFailure = 3\n\t\/\/ StatusUnhealthy indicates rpc succeeded but indicates unhealthy service.\n\tStatusUnhealthy = 4\n)\n\nfunc init() {\n\tlog.SetFlags(0)\n\tflag.StringVar(&flAddr, \"addr\", \"\", \"(required) tcp host:port to connect\")\n\tflag.StringVar(&flService, \"service\", \"\", \"service name to check (default: \\\"\\\")\")\n\tflag.StringVar(&flUserAgent, \"user-agent\", \"grpc_health_probe\", \"user-agent header value of health check requests\")\n\t\/\/ timeouts\n\tflag.DurationVar(&flConnTimeout, \"connect-timeout\", time.Second, \"timeout for establishing connection\")\n\tflag.DurationVar(&flRPCTimeout, \"rpc-timeout\", time.Second, \"timeout for health check rpc\")\n\t\/\/ tls settings\n\tflag.BoolVar(&flTLS, \"tls\", false, \"use TLS (default: false, INSECURE plaintext transport)\")\n\tflag.BoolVar(&flTLSNoVerify, \"tls-no-verify\", false, \"(with -tls) don't verify the certificate (INSECURE) presented by the server (default: false)\")\n\tflag.StringVar(&flTLSCACert, \"tls-ca-cert\", \"\", \"(with -tls, optional) file containing trusted certificates for verifying server\")\n\tflag.StringVar(&flTLSClientCert, \"tls-client-cert\", \"\", \"(with -tls, optional) client certificate for authenticating to the server (requires -tls-client-key)\")\n\tflag.StringVar(&flTLSClientKey, \"tls-client-key\", \"\", \"(with -tls) client private key for authenticating to the server (requires -tls-client-cert)\")\n\tflag.StringVar(&flTLSServerName, \"tls-server-name\", \"\", \"(with -tls) override the hostname used to verify the server certificate\")\n\tflag.BoolVar(&flVerbose, \"v\", false, \"verbose logs\")\n\n\tflag.Parse()\n\n\targError := func(s string, v ...interface{}) {\n\t\tlog.Printf(\"error: \"+s, v...)\n\t\tos.Exit(StatusInvalidArguments)\n\t}\n\n\tif flAddr == \"\" {\n\t\targError(\"-addr not specified\")\n\t}\n\tif flConnTimeout <= 0 {\n\t\targError(\"-connect-timeout must be greater than zero (specified: %v)\", flConnTimeout)\n\t}\n\tif flRPCTimeout <= 0 {\n\t\targError(\"-rpc-timeout must be greater than zero (specified: %v)\", flRPCTimeout)\n\t}\n\tif !flTLS && flTLSNoVerify {\n\t\targError(\"specified -tls-no-verify without specifying -tls\")\n\t}\n\tif !flTLS && flTLSCACert != \"\" {\n\t\targError(\"specified -tls-ca-cert without specifying -tls\")\n\t}\n\tif !flTLS && flTLSClientCert != \"\" {\n\t\targError(\"specified -tls-client-cert without specifying -tls\")\n\t}\n\tif !flTLS && flTLSServerName != \"\" {\n\t\targError(\"specified -tls-server-name without specifying -tls\")\n\t}\n\tif flTLSClientCert != \"\" && flTLSClientKey == \"\" {\n\t\targError(\"specified -tls-client-cert without specifying -tls-client-key\")\n\t}\n\tif flTLSClientCert == \"\" && flTLSClientKey != \"\" {\n\t\targError(\"specified -tls-client-key without specifying -tls-client-cert\")\n\t}\n\tif flTLSNoVerify && flTLSCACert != \"\" {\n\t\targError(\"cannot specify -tls-ca-cert with -tls-no-verify (CA cert would not be used)\")\n\t}\n\tif flTLSNoVerify && flTLSServerName != \"\" {\n\t\targError(\"cannot specify -tls-server-name with -tls-no-verify (server name would not be used)\")\n\t}\n\n\tif flVerbose {\n\t\tlog.Printf(\"parsed options:\")\n\t\tlog.Printf(\"> addr=%s conn_timeout=%v rpc_timeout=%v\", flAddr, flConnTimeout, flRPCTimeout)\n\t\tlog.Printf(\"> tls=%v\", flTLS)\n\t\tif flTLS {\n\t\t\tlog.Printf(\"  > no-verify=%v \", flTLSNoVerify)\n\t\t\tlog.Printf(\"  > ca-cert=%s\", flTLSCACert)\n\t\t\tlog.Printf(\"  > client-cert=%s\", flTLSClientCert)\n\t\t\tlog.Printf(\"  > client-key=%s\", flTLSClientKey)\n\t\t\tlog.Printf(\"  > server-name=%s\", flTLSServerName)\n\t\t}\n\t}\n}\n\nfunc buildCredentials(skipVerify bool, caCerts, clientCert, clientKey, serverName string) (credentials.TransportCredentials, error) {\n\tvar cfg tls.Config\n\n\tif clientCert != \"\" && clientKey != \"\" {\n\t\tkeyPair, err := tls.LoadX509KeyPair(clientCert, clientKey)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to load tls client cert\/key pair. error=%v\", err)\n\t\t}\n\t\tcfg.Certificates = []tls.Certificate{keyPair}\n\t}\n\n\tif skipVerify {\n\t\tcfg.InsecureSkipVerify = true\n\t} else if caCerts != \"\" {\n\t\t\/\/ override system roots\n\t\trootCAs := x509.NewCertPool()\n\t\tpem, err := ioutil.ReadFile(caCerts)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to load root CA certificates from file (%s) error=%v\", caCerts, err)\n\t\t}\n\t\tif !rootCAs.AppendCertsFromPEM(pem) {\n\t\t\treturn nil, fmt.Errorf(\"no root CA certs parsed from file %s\", caCerts)\n\t\t}\n\t\tcfg.RootCAs = rootCAs\n\t}\n\tif serverName != \"\" {\n\t\tcfg.ServerName = serverName\n\t}\n\treturn credentials.NewTLS(&cfg), nil\n}\n\nfunc main() {\n\tretcode := 0\n\tdefer func() { os.Exit(retcode) }()\n\n\tctx, cancel := context.WithCancel(context.Background())\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\tsig := <-c\n\t\tif sig == os.Interrupt {\n\t\t\tlog.Printf(\"cancellation received\")\n\t\t\tcancel()\n\t\t\treturn\n\t\t}\n\t}()\n\n\topts := []grpc.DialOption{\n\t\tgrpc.WithUserAgent(flUserAgent),\n\t\tgrpc.WithBlock()}\n\tif flTLS {\n\t\tcreds, err := buildCredentials(flTLSNoVerify, flTLSCACert, flTLSClientCert, flTLSClientKey, flTLSServerName)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"failed to initialize tls credentials. error=%v\", err)\n\t\t\tretcode = StatusInvalidArguments\n\t\t\treturn\n\t\t}\n\t\topts = append(opts, grpc.WithTransportCredentials(creds))\n\t} else {\n\t\topts = append(opts, grpc.WithInsecure())\n\t}\n\n\tif flVerbose {\n\t\tlog.Print(\"establishing connection\")\n\t}\n\tconnStart := time.Now()\n\tdialCtx, cancel2 := context.WithTimeout(ctx, flConnTimeout)\n\tdefer cancel2()\n\tconn, err := grpc.DialContext(dialCtx, flAddr, opts...)\n\tif err != nil {\n\t\tif err == context.DeadlineExceeded {\n\t\t\tlog.Printf(\"timeout: failed to connect service %q within %v\", flAddr, flConnTimeout)\n\t\t} else {\n\t\t\tlog.Printf(\"error: failed to connect service at %q: %+v\", flAddr, err)\n\t\t}\n\t\tretcode = StatusConnectionFailure\n\t\treturn\n\t}\n\tconnDuration := time.Since(connStart)\n\tdefer conn.Close()\n\tif flVerbose {\n\t\tlog.Printf(\"connection establisted (took %v)\", connDuration)\n\t}\n\n\trpcStart := time.Now()\n\trpcCtx, rpcCancel := context.WithTimeout(ctx, flRPCTimeout)\n\tdefer rpcCancel()\n\tresp, err := healthpb.NewHealthClient(conn).Check(rpcCtx, &healthpb.HealthCheckRequest{Service: flService})\n\tif err != nil {\n\t\tif stat, ok := status.FromError(err); ok && stat.Code() == codes.Unimplemented {\n\t\t\tlog.Printf(\"error: this server does not implement the grpc health protocol (grpc.health.v1.Health)\")\n\t\t} else if stat, ok := status.FromError(err); ok && stat.Code() == codes.DeadlineExceeded {\n\t\t\tlog.Printf(\"timeout: health rpc did not complete within %v\", flRPCTimeout)\n\t\t} else {\n\t\t\tlog.Printf(\"error: health rpc failed: %+v\", err)\n\t\t}\n\t\tretcode = StatusRPCFailure\n\t\treturn\n\t}\n\trpcDuration := time.Since(rpcStart)\n\n\tif resp.GetStatus() != healthpb.HealthCheckResponse_SERVING {\n\t\tlog.Printf(\"service unhealthy (responded with %q)\", resp.GetStatus().String())\n\t\tretcode = StatusUnhealthy\n\t\treturn\n\t}\n\tif flVerbose {\n\t\tlog.Printf(\"time elapsed: connect=%v rpc=%v\", connDuration, rpcDuration)\n\t}\n\tlog.Printf(\"status: %v\", resp.GetStatus().String())\n}\n<|endoftext|>"}
{"text":"<commit_before>package gopwt\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/mattn\/go-isatty\"\n)\n\nvar (\n\ttermw    = 0\n\ttestdata = flag.String(\"testdata\", \"testdata\", \"name of test data directories. e.g. -testdata testdata,migrations\")\n\tverbose  = false\n)\n\nfunc Empower() {\n\tif os.Getenv(\"GOPWT_OFF\") != \"\" {\n\t\treturn\n\t}\n\n\tif err := doMain(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err.Error())\n\n\t\tif exiterr, ok := err.(*exec.ExitError); ok {\n\t\t\tif s, ok := exiterr.Sys().(syscall.WaitStatus); ok {\n\t\t\t\tos.Exit(s.ExitStatus())\n\t\t\t} else {\n\t\t\t\tpanic(fmt.Errorf(\"Unimplemented for system where exec.ExitError.Sys() is not syscall.WaitStatus.\"))\n\t\t\t}\n\t\t}\n\n\t\tos.Exit(127)\n\t}\n\tos.Exit(0)\n}\nfunc doMain() error {\n\tif runtime.Version() == \"go1.4\" {\n\t\treturn fmt.Errorf(\"go1.4 is not supported. please bump to go1.4.1 or later\")\n\t}\n\n\tif !flag.Parsed() {\n\t\tflag.Parse()\n\t}\n\n\tflag.VisitAll(func(f *flag.Flag) {\n\t\tif f.Name == \"test.v\" {\n\t\t\tif f.Value.String() == \"false\" {\n\t\t\t\tverbose = true\n\t\t\t}\n\t\t}\n\t})\n\n\tif isatty.IsTerminal(os.Stdout.Fd()) {\n\t\ttermw = getTermCols(os.Stdin.Fd())\n\t}\n\n\ttempGoPath, err := ioutil.TempDir(os.TempDir(), \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(tempGoPath)\n\n\troot := flag.Arg(0)\n\n\tpkgInfo, err := newPackageInfo(root)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = rewrite(tempGoPath, pkgInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = runTest(tempGoPath, pkgInfo, os.Stdout, os.Stderr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc rewrite(tempGoPath string, pkgInfo *packageInfo) error {\n\ttempGoSrcDir := filepath.Join(tempGoPath, \"src\")\n\n\terr := filepath.Walk(pkgInfo.dirPath, func(path string, fInfo os.FileInfo, err error) error {\n\t\tif fInfo.Mode()&os.ModeSymlink == os.ModeSymlink {\n\t\t\treturn nil\n\t\t}\n\n\t\tif !fInfo.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tfiles, err := ioutil.ReadDir(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !containsGoFile(files) {\n\t\t\t\/\/ sub-packages maybe have gofiles, even if itself don't has gofiles\n\t\t\tif containsDirectory(files) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn filepath.SkipDir\n\t\t}\n\n\t\trel, err := filepath.Rel(pkgInfo.dirPath, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, tdata := range strings.Split(*testdata, \",\") {\n\t\t\tif strings.Split(rel, \"\/\")[0] == tdata {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t}\n\n\t\tif rel != \".\" {\n\t\t\tif filepath.HasPrefix(rel, \".\") {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\n\t\t\tif !pkgInfo.recursive {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t}\n\n\t\timportPath := filepath.Join(pkgInfo.importPath, rel)\n\n\t\terr = os.MkdirAll(filepath.Join(tempGoSrcDir, importPath), os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = rewritePackage(path, importPath, tempGoSrcDir)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc runTest(goPath string, pkgInfo *packageInfo, stdout, stderr io.Writer) error {\n\terr := os.Setenv(\"GOPATH\", goPath+\":\"+os.Getenv(\"GOPATH\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd := exec.Command(\"go\", \"test\")\n\n\tif verbose {\n\t\tcmd.Args = append(cmd.Args, \"-v\")\n\t}\n\tcmd.Dir = path.Join(goPath, \"src\", pkgInfo.importPath)\n\t\/\/ cmd.Args = append(cmd.Args, pkgInfo.ToGoTestArg())\n\tcmd.Stdout = stdout\n\tcmd.Stderr = stderr\n\treturn cmd.Run()\n}\n<commit_msg>fix(gopwt): wtf<commit_after>package gopwt\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/mattn\/go-isatty\"\n)\n\nvar (\n\ttermw    = 0\n\ttestdata = flag.String(\"testdata\", \"testdata\", \"name of test data directories. e.g. -testdata testdata,migrations\")\n\tverbose  = false\n)\n\nfunc Empower() {\n\tif os.Getenv(\"GOPWT_OFF\") != \"\" {\n\t\treturn\n\t}\n\n\tif err := doMain(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err.Error())\n\n\t\tif exiterr, ok := err.(*exec.ExitError); ok {\n\t\t\tif s, ok := exiterr.Sys().(syscall.WaitStatus); ok {\n\t\t\t\tos.Exit(s.ExitStatus())\n\t\t\t} else {\n\t\t\t\tpanic(fmt.Errorf(\"Unimplemented for system where exec.ExitError.Sys() is not syscall.WaitStatus.\"))\n\t\t\t}\n\t\t}\n\n\t\tos.Exit(127)\n\t}\n\tos.Exit(0)\n}\nfunc doMain() error {\n\tif runtime.Version() == \"go1.4\" {\n\t\treturn fmt.Errorf(\"go1.4 is not supported. please bump to go1.4.1 or later\")\n\t}\n\n\tif !flag.Parsed() {\n\t\tflag.Parse()\n\t}\n\n\tflag.VisitAll(func(f *flag.Flag) {\n\t\tif f.Name == \"test.v\" {\n\t\t\tif f.Value.String() != \"false\" {\n\t\t\t\tverbose = true\n\t\t\t}\n\t\t}\n\t})\n\n\tif isatty.IsTerminal(os.Stdout.Fd()) {\n\t\ttermw = getTermCols(os.Stdin.Fd())\n\t}\n\n\ttempGoPath, err := ioutil.TempDir(os.TempDir(), \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(tempGoPath)\n\n\troot := flag.Arg(0)\n\n\tpkgInfo, err := newPackageInfo(root)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = rewrite(tempGoPath, pkgInfo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = runTest(tempGoPath, pkgInfo, os.Stdout, os.Stderr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc rewrite(tempGoPath string, pkgInfo *packageInfo) error {\n\ttempGoSrcDir := filepath.Join(tempGoPath, \"src\")\n\n\terr := filepath.Walk(pkgInfo.dirPath, func(path string, fInfo os.FileInfo, err error) error {\n\t\tif fInfo.Mode()&os.ModeSymlink == os.ModeSymlink {\n\t\t\treturn nil\n\t\t}\n\n\t\tif !fInfo.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\tfiles, err := ioutil.ReadDir(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !containsGoFile(files) {\n\t\t\t\/\/ sub-packages maybe have gofiles, even if itself don't has gofiles\n\t\t\tif containsDirectory(files) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn filepath.SkipDir\n\t\t}\n\n\t\trel, err := filepath.Rel(pkgInfo.dirPath, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, tdata := range strings.Split(*testdata, \",\") {\n\t\t\tif strings.Split(rel, \"\/\")[0] == tdata {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t}\n\n\t\tif rel != \".\" {\n\t\t\tif filepath.HasPrefix(rel, \".\") {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\n\t\t\tif !pkgInfo.recursive {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\t\t}\n\n\t\timportPath := filepath.Join(pkgInfo.importPath, rel)\n\n\t\terr = os.MkdirAll(filepath.Join(tempGoSrcDir, importPath), os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = rewritePackage(path, importPath, tempGoSrcDir)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc runTest(goPath string, pkgInfo *packageInfo, stdout, stderr io.Writer) error {\n\terr := os.Setenv(\"GOPATH\", goPath+\":\"+os.Getenv(\"GOPATH\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd := exec.Command(\"go\", \"test\")\n\n\tif verbose {\n\t\tcmd.Args = append(cmd.Args, \"-v\")\n\t}\n\tcmd.Dir = path.Join(goPath, \"src\", pkgInfo.importPath)\n\t\/\/ cmd.Args = append(cmd.Args, pkgInfo.ToGoTestArg())\n\tcmd.Stdout = stdout\n\tcmd.Stderr = stderr\n\treturn cmd.Run()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 tsuru-admin authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ tsuru-admin is under development.\npackage main\n\nimport (\n\t\"os\"\n\n\t\"github.com\/tsuru\/tsuru\/cmd\"\n\t\"github.com\/tsuru\/tsuru\/provision\"\n\t_ \"github.com\/tsuru\/tsuru\/provision\/docker\"\n)\n\nconst (\n\tversion = \"0.8.0\"\n\theader  = \"Supported-Tsuru-Admin\"\n)\n\nfunc buildManager(name string) *cmd.Manager {\n\tm := cmd.BuildBaseManager(name, version, header, nil)\n\tm.Register(&tokenGen{})\n\tm.Register(&logRemove{})\n\tm.Register(&platformAdd{})\n\tm.Register(&platformUpdate{})\n\tm.Register(&platformRemove{})\n\tm.RegisterDeprecated(&machineList{}, \"machines-list\")\n\tm.Register(&machineDestroy{})\n\tm.Register(&appLockDelete{})\n\tm.Register(viewUserQuota{})\n\tm.Register(changeUserQuota{})\n\tm.Register(viewAppQuota{})\n\tm.Register(changeAppQuota{})\n\tm.Register(&planCreate{})\n\tm.Register(&planRemove{})\n\tm.Register(&templateList{})\n\tm.Register(&templateAdd{})\n\tm.Register(&templateRemove{})\n\tregisterProvisionersCommands(m)\n\treturn m\n}\n\nfunc registerProvisionersCommands(m *cmd.Manager) {\n\tprovisioners := provision.Registry()\n\tfor _, p := range provisioners {\n\t\tif c, ok := p.(cmd.AdminCommandable); ok {\n\t\t\tcommands := c.AdminCommands()\n\t\t\tfor _, cmd := range commands {\n\t\t\t\tm.Register(cmd)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc main() {\n\tname := cmd.ExtractProgramName(os.Args[0])\n\tmanager := buildManager(name)\n\targs := os.Args[1:]\n\tmanager.Run(args)\n}\n<commit_msg>main: bump to 0.8.1<commit_after>\/\/ Copyright 2014 tsuru-admin authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ tsuru-admin is under development.\npackage main\n\nimport (\n\t\"os\"\n\n\t\"github.com\/tsuru\/tsuru\/cmd\"\n\t\"github.com\/tsuru\/tsuru\/provision\"\n\t_ \"github.com\/tsuru\/tsuru\/provision\/docker\"\n)\n\nconst (\n\tversion = \"0.8.1\"\n\theader  = \"Supported-Tsuru-Admin\"\n)\n\nfunc buildManager(name string) *cmd.Manager {\n\tm := cmd.BuildBaseManager(name, version, header, nil)\n\tm.Register(&tokenGen{})\n\tm.Register(&logRemove{})\n\tm.Register(&platformAdd{})\n\tm.Register(&platformUpdate{})\n\tm.Register(&platformRemove{})\n\tm.RegisterDeprecated(&machineList{}, \"machines-list\")\n\tm.Register(&machineDestroy{})\n\tm.Register(&appLockDelete{})\n\tm.Register(viewUserQuota{})\n\tm.Register(changeUserQuota{})\n\tm.Register(viewAppQuota{})\n\tm.Register(changeAppQuota{})\n\tm.Register(&planCreate{})\n\tm.Register(&planRemove{})\n\tm.Register(&templateList{})\n\tm.Register(&templateAdd{})\n\tm.Register(&templateRemove{})\n\tregisterProvisionersCommands(m)\n\treturn m\n}\n\nfunc registerProvisionersCommands(m *cmd.Manager) {\n\tprovisioners := provision.Registry()\n\tfor _, p := range provisioners {\n\t\tif c, ok := p.(cmd.AdminCommandable); ok {\n\t\t\tcommands := c.AdminCommands()\n\t\t\tfor _, cmd := range commands {\n\t\t\t\tm.Register(cmd)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc main() {\n\tname := cmd.ExtractProgramName(os.Args[0])\n\tmanager := buildManager(name)\n\targs := os.Args[1:]\n\tmanager.Run(args)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*-\n * Copyright 2016 Square Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/square\/certigo\/jceks\"\n\t\"golang.org\/x\/crypto\/pkcs12\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\nvar (\n\tapp = kingpin.New(\"certigo\", \"A command line certificate examination utility.\")\n\n\tdump     = app.Command(\"dump\", \"Display information about a certificate.\")\n\tdumpFile = dump.Arg(\"file\", \"Certificate file to dump.\").Required().String()\n\tdumpType = dump.Flag(\"format\", \"Format of given input. If unspecified, certigo guesses based on file extension\").Short('f').String()\n)\n\nvar fileExtToFormat = map[string]string{\n\t\".pem\":   \"PEM\",\n\t\".crt\":   \"PEM\",\n\t\".p12\":   \"PKCS12\",\n\t\".pfx\":   \"PKCS12\",\n\t\".jceks\": \"JCEKS\",\n}\n\nfunc main() {\n\tswitch kingpin.MustParse(app.Parse(os.Args[1:])) {\n\tcase dump.FullCommand(): \/\/ Dump certificate\n\t\tformat, ok := formatForFile(*dumpFile, *dumpType)\n\t\tif !ok {\n\t\t\tfmt.Fprint(os.Stderr, \"unable to guess file type\\n\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tcerts, err := getCerts(*dumpFile, format)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tfor i, cert := range certs {\n\t\t\tfmt.Println(\"CERTIFICATE\", i+1)\n\t\t\tdisplayCert(cert)\n\t\t\tfmt.Println()\n\t\t}\n\t}\n}\n\n\/\/ formatForFile returns the file format (either from flags or\n\/\/ based on file extension).\nfunc formatForFile(filename, format string) (string, bool) {\n\tif format == \"\" {\n\t\tguess, ok := fileExtToFormat[strings.ToLower(filepath.Ext(filename))]\n\t\treturn guess, ok\n\t}\n\treturn format, true\n}\n\n\/\/ getCerts takes in a filename and format type and returns an\n\/\/ array of all the certificates found in that file. If no format\n\/\/ is specified for the file, getCerts guesses what format was used\n\/\/ based on the file extension used in the file name. If it can't\n\/\/ guess based on this it returns and error.\nfunc getCerts(file, format string) ([]*x509.Certificate, error) {\n\tvar certs []*x509.Certificate\n\tdata, _ := ioutil.ReadFile(file)\n\tswitch format {\n\tcase \"PEM\":\n\t\tblock, data := pem.Decode(data)\n\t\tfor block != nil {\n\t\t\tcert, err := x509.ParseCertificate(block.Bytes)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcerts = append(certs, cert)\n\t\t\tblock, data = pem.Decode(data)\n\t\t}\n\tcase \"PKCS12\":\n\t\tscanner := bufio.NewReader(os.Stdin)\n\t\tfmt.Print(\"Enter password: \")\n\t\tpassword, _ := scanner.ReadString('\\n')\n\t\tblocks, err := pkcs12.ToPEM(data, strings.TrimSuffix(password, \"\\n\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, block := range blocks {\n\t\t\tif block.Type == \"CERTIFICATE\" {\n\t\t\t\tcert, err := x509.ParseCertificate(block.Bytes)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tcerts = append(certs, cert)\n\t\t\t}\n\t\t}\n\tcase \"JKS\":\n\t\tscanner := bufio.NewReader(os.Stdin)\n\t\tfmt.Print(\"Enter password: \")\n\t\tpassword, _ := scanner.ReadString('\\n')\n\t\tkeyStore, err := jceks.Load(file, []byte(strings.TrimSuffix(password, \"\\n\")))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, certName := range keyStore.ListCerts() {\n\t\t\tcert, _ := keyStore.GetCert(certName)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcerts = append(certs, cert)\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown file type: %s\", format)\n\t}\n\treturn certs, nil\n}\n<commit_msg>Changed case checking for user input of JKS to check for JCEKS<commit_after>\/*-\n * Copyright 2016 Square Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/square\/certigo\/jceks\"\n\t\"golang.org\/x\/crypto\/pkcs12\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\nvar (\n\tapp = kingpin.New(\"certigo\", \"A command line certificate examination utility.\")\n\n\tdump     = app.Command(\"dump\", \"Display information about a certificate.\")\n\tdumpFile = dump.Arg(\"file\", \"Certificate file to dump.\").Required().String()\n\tdumpType = dump.Flag(\"format\", \"Format of given input. If unspecified, certigo guesses based on file extension\").Short('f').String()\n)\n\nvar fileExtToFormat = map[string]string{\n\t\".pem\":   \"PEM\",\n\t\".crt\":   \"PEM\",\n\t\".p12\":   \"PKCS12\",\n\t\".pfx\":   \"PKCS12\",\n\t\".jceks\": \"JCEKS\",\n}\n\nfunc main() {\n\tswitch kingpin.MustParse(app.Parse(os.Args[1:])) {\n\tcase dump.FullCommand(): \/\/ Dump certificate\n\t\tformat, ok := formatForFile(*dumpFile, *dumpType)\n\t\tif !ok {\n\t\t\tfmt.Fprint(os.Stderr, \"unable to guess file type\\n\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tcerts, err := getCerts(*dumpFile, format)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tfor i, cert := range certs {\n\t\t\tfmt.Println(\"CERTIFICATE\", i+1)\n\t\t\tdisplayCert(cert)\n\t\t\tfmt.Println()\n\t\t}\n\t}\n}\n\n\/\/ formatForFile returns the file format (either from flags or\n\/\/ based on file extension).\nfunc formatForFile(filename, format string) (string, bool) {\n\tif format == \"\" {\n\t\tguess, ok := fileExtToFormat[strings.ToLower(filepath.Ext(filename))]\n\t\treturn guess, ok\n\t}\n\treturn format, true\n}\n\n\/\/ getCerts takes in a filename and format type and returns an\n\/\/ array of all the certificates found in that file. If no format\n\/\/ is specified for the file, getCerts guesses what format was used\n\/\/ based on the file extension used in the file name. If it can't\n\/\/ guess based on this it returns and error.\nfunc getCerts(file, format string) ([]*x509.Certificate, error) {\n\tvar certs []*x509.Certificate\n\tdata, _ := ioutil.ReadFile(file)\n\tswitch format {\n\tcase \"PEM\":\n\t\tblock, data := pem.Decode(data)\n\t\tfor block != nil {\n\t\t\tcert, err := x509.ParseCertificate(block.Bytes)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcerts = append(certs, cert)\n\t\t\tblock, data = pem.Decode(data)\n\t\t}\n\tcase \"PKCS12\":\n\t\tscanner := bufio.NewReader(os.Stdin)\n\t\tfmt.Print(\"Enter password: \")\n\t\tpassword, _ := scanner.ReadString('\\n')\n\t\tblocks, err := pkcs12.ToPEM(data, strings.TrimSuffix(password, \"\\n\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, block := range blocks {\n\t\t\tif block.Type == \"CERTIFICATE\" {\n\t\t\t\tcert, err := x509.ParseCertificate(block.Bytes)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tcerts = append(certs, cert)\n\t\t\t}\n\t\t}\n\tcase \"JCEKS\":\n\t\tscanner := bufio.NewReader(os.Stdin)\n\t\tfmt.Print(\"Enter password: \")\n\t\tpassword, _ := scanner.ReadString('\\n')\n\t\tkeyStore, err := jceks.Load(file, []byte(strings.TrimSuffix(password, \"\\n\")))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, certName := range keyStore.ListCerts() {\n\t\t\tcert, _ := keyStore.GetCert(certName)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcerts = append(certs, cert)\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown file type: %s\", format)\n\t}\n\treturn certs, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Logs the status of a user from Lotus Notes SameTime Instant Messager.\n\/\/ Usage:\n\/\/\n\/\/    go run main.go -userid=USER_ID\n\/\/\n\/\/ @requires Lotus Notes 8+, Google Go 1.2\n\/\/ @project https:\/\/github.com\/LarryBattle\/SameTimeTrackStatus\/\n\/\/ @author Larry Battle\n\/\/ @version 0.1.0\n\/\/ @todo Add new flags : -users=id1,id2,id3 -verbose=bool -api_url=string\n\/\/ @todo add check for Lotus Notes and setting.\n\/\/ @todo refactor into objects; webapi, storage, cli, settings, user\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n)\n\nconst (\n\tVERSION             = \"0.1.0\"\n\tTIME_STAMP_FORMAT   = \"01\/02\/2006 03:04:05pm\"\n\tDEFAULT_OUTPUT_FILE = \"output.txt\"\n)\n\nvar (\n\tsametime_getstatus_URL = `http:\/\/localhost:59449\/stwebapi\/getstatus?userId=`\n\toutputFile             string\n\tuserId                 string\n\tshowVersion            bool\n)\n\n\/\/ Used to only contain the essenential properties from the json response\ntype essential_ST_JSON struct {\n\tTimeStamp     string `json:\"timestamp\"`\n\tUnixTimeStamp int64  `json:\"unixTimestamp\"`\n\tDisplayName   string `json:\"displayName\"`\n\tStatus        int    `json:\"status\"`\n\tStatusMessage string `json:\"statusMessage\"`\n\tUserName      string `json:\"username\"`\n}\n\n\/\/ Processes the flag information.\nfunc processFlags() {\n\tflag.StringVar(&userId, \"userid\", \"\", \"REQUIRED. Sametime User Id. Try your id if you don't know.\")\n\tflag.StringVar(&outputFile, \"output\", DEFAULT_OUTPUT_FILE, \"Output file to store logs. Defaults to output.txt\")\n\tflag.BoolVar(&showVersion, \"version\", false, \"Shows version information.\")\n\tflag.Parse()\n}\n\n\/\/ Checks if all required flags are set.\nfunc checkSettings() {\n\tif showVersion {\n\t\tfmt.Printf(\"Version %s\\n\", VERSION)\n\t\tos.Exit(1)\n\t}\n\tif userId == \"\" {\n\t\tfmt.Println(\"The argument `userid` is required.\")\n\t\tos.Exit(1)\n\t}\n}\n\n\/\/ Shows a message when the tool is called.\nfunc printGreeting() {\n\tfmt.Println(`SameTime IM Status Tracking Tool by Larry Battle`)\n}\nfunc checkError(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\n\/\/ Returns a date time timestamp\nfunc getTimeStamp() string {\n\treturn time.Now().Format(TIME_STAMP_FORMAT)\n}\n\n\/\/ Returns the timestamp used by Javascript.\n\/\/ Ex. new Date( timestamp )\nfunc getJSTimeStamp() int64 {\n\treturn time.Now().UnixNano() \/ 1e6\n}\n\n\/\/ Returns only the desired properties from the json response\nfunc extractInfoFromJSON(json_string []byte) []byte {\n\tvar obj essential_ST_JSON\n\tjson.Unmarshal(json_string, &obj)\n\tobj.TimeStamp = getTimeStamp()\n\tobj.UnixTimeStamp = getJSTimeStamp()\n\tb, err := json.Marshal(obj)\n\tcheckError(err)\n\treturn b\n}\n\n\/\/ Returns the JSON response from a `getstatus` webapi call for a specific userId\nfunc getSameTimeStatusOfUser(userId string) []byte {\n\tres, err := http.Get(sametime_getstatus_URL + userId)\n\tcheckError(err)\n\tdefer res.Body.Close()\n\tjson_response, err := ioutil.ReadAll(res.Body)\n\tcheckError(err)\n\treturn json_response\n}\n\n\/\/ Appends a string with a new line to a file\nfunc appendStringToFile(filename string, data []byte) {\n\tf, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)\n\tdefer f.Close()\n\tcheckError(err)\n\t_, err = f.WriteString(string(data) + \"\\n\")\n\tcheckError(err)\n}\n\n\/\/ Sends status request then saves response to a file.\nfunc logSameTimeStatus(userId string) {\n\tappendStringToFile(outputFile, extractInfoFromJSON(getSameTimeStatusOfUser(userId)))\n}\n\n\/\/ Calls a function every t times.\nfunc startCounter(t time.Duration, fn func()) {\n\ti := 0\n\tfor _ = range time.Tick(t) {\n\t\ti++\n\t\tlog.Println(\"Logging status #\", i)\n\t\tfn()\n\t}\n}\nfunc main() {\n\tprintGreeting()\n\tprocessFlags()\n\tcheckSettings()\n\tlog.Printf(\"Saving status for %s to %s\\n\", userId, outputFile)\n\tstartCounter(2*time.Second, func() {\n\t\tlogSameTimeStatus(userId)\n\t})\n}\n<commit_msg>Update main.go<commit_after>\/\/ Logs the status of a user from Lotus Notes SameTime Instant Messager.\n\/\/ Usage:\n\/\/\n\/\/    go run main.go -userid=USER_ID\n\/\/\n\/\/ @requires Lotus Notes 8+, Google Go 1.2\n\/\/ @project https:\/\/github.com\/LarryBattle\/SameTimeTrackStatus\/\n\/\/ @author Larry Battle\n\/\/ @version 0.1.1\n\/\/ @todo Add new flags : -users=id1,id2,id3 -verbose=bool -api_url=string -interval=#minutes\n\/\/ @todo add check for Lotus Notes and setting.\n\/\/ @todo refactor into objects; webapi, storage, cli, settings, user\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n)\n\nconst (\n\tVERSION             = \"0.1.1\"\n\tTIME_STAMP_FORMAT   = \"01\/02\/2006 03:04:05pm\"\n\tDEFAULT_OUTPUT_FILE = \"output.txt\"\n)\n\nvar (\n\tsametime_getstatus_URL = `http:\/\/localhost:59449\/stwebapi\/getstatus?userId=`\n\toutputFile             string\n\tuserId                 string\n\tshowVersion            bool\n\tnumOfMinutes\tuint\n)\n\n\/\/ Used to only contain the essenential properties from the json response\ntype essential_ST_JSON struct {\n\tTimeStamp     string `json:\"timestamp\"`\n\tUnixTimeStamp int64  `json:\"unixTimestamp\"`\n\tDisplayName   string `json:\"displayName\"`\n\tStatus        int    `json:\"status\"`\n\tStatusMessage string `json:\"statusMessage\"`\n\tUserName      string `json:\"username\"`\n}\n\n\/\/ Processes the flag information.\nfunc processFlags() {\n\tflag.StringVar(&userId, \"userid\", \"\", \"REQUIRED. Sametime User Id. Try your id if you don't know.\")\n\tflag.StringVar(&outputFile, \"output\", DEFAULT_OUTPUT_FILE, \"Output file to store logs.\")\n\tflag.BoolVar(&showVersion, \"version\", false, \"Shows version information.\")\n\tflag.UintVar(&numOfMinutes, \"interval\", 5, \"Interval to check status.\")\n\tflag.Parse()\n}\n\n\/\/ Checks if all required flags are set.\nfunc checkSettings() {\n\tif showVersion {\n\t\tfmt.Printf(\"Version %s\\n\", VERSION)\n\t\tos.Exit(1)\n\t}\n\tif userId == \"\" {\n\t\tfmt.Println(\"The argument `userid` is required.\")\n\t\tos.Exit(1)\n\t}\n\tif numOfMinutes < 1 || 200 < numOfMinutes {\n\t\tfmt.Println(\"The argument `userid` is required.\")\n\t\tos.Exit(1)\n\t}\n}\n\n\/\/ Shows a message when the tool is called.\nfunc printGreeting() {\n\tfmt.Println(`SameTime IM Status Tracking Tool by Larry Battle`)\n}\nfunc checkError(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n\n\/\/ Returns a date time timestamp\nfunc getTimeStamp() string {\n\treturn time.Now().Format(TIME_STAMP_FORMAT)\n}\n\n\/\/ Returns the timestamp used by Javascript.\n\/\/ Ex. new Date( timestamp )\nfunc getJSTimeStamp() int64 {\n\treturn time.Now().UnixNano() \/ 1e6\n}\n\n\/\/ Returns only the desired properties from the json response\nfunc extractInfoFromJSON(json_string []byte) []byte {\n\tvar obj essential_ST_JSON\n\tjson.Unmarshal(json_string, &obj)\n\tobj.TimeStamp = getTimeStamp()\n\tobj.UnixTimeStamp = getJSTimeStamp()\n\tb, err := json.Marshal(obj)\n\tcheckError(err)\n\treturn b\n}\n\n\/\/ Returns the JSON response from a `getstatus` webapi call for a specific userId\nfunc getSameTimeStatusOfUser(userId string) []byte {\n\tres, err := http.Get(sametime_getstatus_URL + userId)\n\tcheckError(err)\n\tdefer res.Body.Close()\n\tjson_response, err := ioutil.ReadAll(res.Body)\n\tcheckError(err)\n\treturn json_response\n}\n\n\/\/ Appends a string with a new line to a file\nfunc appendStringToFile(filename string, data []byte) {\n\tf, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0660)\n\tdefer f.Close()\n\tcheckError(err)\n\t_, err = f.WriteString(string(data) + \"\\n\")\n\tcheckError(err)\n}\n\n\/\/ Sends status request then saves response to a file.\nfunc logSameTimeStatus(userId string) {\n\tappendStringToFile(outputFile, extractInfoFromJSON(getSameTimeStatusOfUser(userId)))\n}\n\n\/\/ Calls a function every t times.\nfunc startCounter(t time.Duration, fn func()) {\n\ti := 0\n\tfor _ = range time.Tick(t) {\n\t\ti++\n\t\tlog.Println(\"Logging status #\", i)\n\t\tfn()\n\t}\n}\nfunc main() {\n\tprintGreeting()\n\tprocessFlags()\n\tcheckSettings()\n\tlog.Printf(\"Every %d minutes: Saving status for %s to %s\\n\", numOfMinutes, userId, outputFile)\n\tstartCounter( time.Duration(numOfMinutes) *time.Minute, func() {\n\t\tlogSameTimeStatus(userId)\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/grafana\/grafana\/pkg\/cmd\"\n\t\"github.com\/grafana\/grafana\/pkg\/log\"\n\t\"github.com\/grafana\/grafana\/pkg\/login\"\n\t\"github.com\/grafana\/grafana\/pkg\/metrics\"\n\t\"github.com\/grafana\/grafana\/pkg\/plugins\"\n\t\"github.com\/grafana\/grafana\/pkg\/services\/eventpublisher\"\n\t\"github.com\/grafana\/grafana\/pkg\/services\/notifications\"\n\t\"github.com\/grafana\/grafana\/pkg\/services\/search\"\n\t\"github.com\/grafana\/grafana\/pkg\/services\/sqlstore\"\n\t\"github.com\/grafana\/grafana\/pkg\/setting\"\n\t\"github.com\/grafana\/grafana\/pkg\/social\"\n)\n\nvar version = \"master\"\nvar commit = \"NA\"\nvar buildstamp string\n\nvar configFile = flag.String(\"config\", \"\", \"path to config file\")\nvar homePath = flag.String(\"homepath\", \"\", \"path to grafana install\/home path, defaults to working directory\")\nvar pidFile = flag.String(\"pidfile\", \"\", \"path to pid file\")\n\nfunc init() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n}\n\nfunc main() {\n\tbuildstampInt64, _ := strconv.ParseInt(buildstamp, 10, 64)\n\n\tsetting.BuildVersion = version\n\tsetting.BuildCommit = commit\n\tsetting.BuildStamp = buildstampInt64\n\n\tgo func() {\n\t\tc := make(chan os.Signal, 1)\n\t\tsignal.Notify(c, os.Interrupt)\n\t\t<-c\n\t\tos.Exit(0)\n\t}()\n\n\tflag.Parse()\n\n\twritePIDFile()\n\tinitRuntime()\n\n\tsearch.Init()\n\tlogin.Init()\n\tsocial.NewOAuthService()\n\teventpublisher.Init()\n\tplugins.Init()\n\n\tif err := notifications.Init(); err != nil {\n\t\tlog.Fatal(3, \"Notification service failed to initialize\", err)\n\t}\n\n\tif setting.ReportingEnabled {\n\t\tgo metrics.StartUsageReportLoop()\n\t}\n\n\tcmd.StartServer()\n\n\tlog.Close()\n}\n\nfunc initRuntime() {\n\tsetting.NewConfigContext(&setting.CommandLineArgs{\n\t\tConfig:   *configFile,\n\t\tHomePath: *homePath,\n\t\tArgs:     flag.Args(),\n\t})\n\n\tlog.Info(\"Starting Grafana\")\n\tlog.Info(\"Version: %v, Commit: %v, Build date: %v\", setting.BuildVersion, setting.BuildCommit, time.Unix(setting.BuildStamp, 0))\n\tsetting.LogConfigurationInfo()\n\n\tsqlstore.NewEngine()\n\tsqlstore.EnsureAdminUser()\n}\n\nfunc writePIDFile() {\n\tif *pidFile == \"\" {\n\t\treturn\n\t}\n\n\t\/\/ Ensure the required directory structure exists.\n\terr := os.MkdirAll(filepath.Dir(*pidFile), 0700)\n\tif err != nil {\n\t\tlog.Fatal(3, \"Failed to verify pid directory\", err)\n\t}\n\n\t\/\/ Retrieve the PID and write it.\n\tpid := strconv.Itoa(os.Getpid())\n\tif err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil {\n\t\tlog.Fatal(3, \"Failed to write pidfile\", err)\n\t}\n}\n<commit_msg>fix(shutdown flow): improved shutdown flow and log closing, listing to kill and and SIGTERM as well, closes #2516<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/grafana\/grafana\/pkg\/cmd\"\n\t\"github.com\/grafana\/grafana\/pkg\/log\"\n\t\"github.com\/grafana\/grafana\/pkg\/login\"\n\t\"github.com\/grafana\/grafana\/pkg\/metrics\"\n\t\"github.com\/grafana\/grafana\/pkg\/plugins\"\n\t\"github.com\/grafana\/grafana\/pkg\/services\/eventpublisher\"\n\t\"github.com\/grafana\/grafana\/pkg\/services\/notifications\"\n\t\"github.com\/grafana\/grafana\/pkg\/services\/search\"\n\t\"github.com\/grafana\/grafana\/pkg\/services\/sqlstore\"\n\t\"github.com\/grafana\/grafana\/pkg\/setting\"\n\t\"github.com\/grafana\/grafana\/pkg\/social\"\n)\n\nvar version = \"master\"\nvar commit = \"NA\"\nvar buildstamp string\n\nvar configFile = flag.String(\"config\", \"\", \"path to config file\")\nvar homePath = flag.String(\"homepath\", \"\", \"path to grafana install\/home path, defaults to working directory\")\nvar pidFile = flag.String(\"pidfile\", \"\", \"path to pid file\")\nvar exitChan = make(chan int)\n\nfunc init() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n}\n\nfunc main() {\n\tbuildstampInt64, _ := strconv.ParseInt(buildstamp, 10, 64)\n\n\tsetting.BuildVersion = version\n\tsetting.BuildCommit = commit\n\tsetting.BuildStamp = buildstampInt64\n\n\tgo listenToSystemSignels()\n\n\tflag.Parse()\n\twritePIDFile()\n\tinitRuntime()\n\n\tsearch.Init()\n\tlogin.Init()\n\tsocial.NewOAuthService()\n\teventpublisher.Init()\n\tplugins.Init()\n\n\tif err := notifications.Init(); err != nil {\n\t\tlog.Fatal(3, \"Notification service failed to initialize\", err)\n\t}\n\n\tif setting.ReportingEnabled {\n\t\tgo metrics.StartUsageReportLoop()\n\t}\n\n\tcmd.StartServer()\n\texitChan <- 0\n}\n\nfunc initRuntime() {\n\tsetting.NewConfigContext(&setting.CommandLineArgs{\n\t\tConfig:   *configFile,\n\t\tHomePath: *homePath,\n\t\tArgs:     flag.Args(),\n\t})\n\n\tlog.Info(\"Starting Grafana\")\n\tlog.Info(\"Version: %v, Commit: %v, Build date: %v\", setting.BuildVersion, setting.BuildCommit, time.Unix(setting.BuildStamp, 0))\n\tsetting.LogConfigurationInfo()\n\n\tsqlstore.NewEngine()\n\tsqlstore.EnsureAdminUser()\n}\n\nfunc writePIDFile() {\n\tif *pidFile == \"\" {\n\t\treturn\n\t}\n\n\t\/\/ Ensure the required directory structure exists.\n\terr := os.MkdirAll(filepath.Dir(*pidFile), 0700)\n\tif err != nil {\n\t\tlog.Fatal(3, \"Failed to verify pid directory\", err)\n\t}\n\n\t\/\/ Retrieve the PID and write it.\n\tpid := strconv.Itoa(os.Getpid())\n\tif err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil {\n\t\tlog.Fatal(3, \"Failed to write pidfile\", err)\n\t}\n}\n\nfunc listenToSystemSignels() {\n\tsignalChan := make(chan os.Signal, 1)\n\tcode := 0\n\n\tsignal.Notify(signalChan, os.Interrupt)\n\tsignal.Notify(signalChan, os.Kill)\n\tsignal.Notify(signalChan, syscall.SIGTERM)\n\n\tselect {\n\tcase sig := <-signalChan:\n\t\tlog.Info(\"Received signal %s. shutting down\", sig)\n\tcase code = <-exitChan:\n\t\tswitch code {\n\t\tcase 0:\n\t\t\tlog.Info(\"Shutting down\")\n\t\tdefault:\n\t\t\tlog.Warn(\"Shutting down\")\n\t\t}\n\t}\n\n\tlog.Close()\n\tos.Exit(code)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"flag\"\nimport \"fmt\"\nimport \"log\"\nimport \"strconv\"\nimport \"time\"\nimport \"net\"\n\/\/import \"os\"\nimport \"encoding\/json\"\n\/\/import \"github.com\/Shopify\/sarama\"\nimport \"github.com\/google\/gopacket\"\nimport \"github.com\/google\/gopacket\/pcap\"\nimport \"github.com\/google\/gopacket\/layers\"\n\n\n\/*\n    logging to file\n    debug logging\n    ttlcache for failed queries\n    documentation\nrelease v1    \n    \n    stats output\n    perf testing\n    TCP flow support\nrelease v2\n\n    logging to kafka\n    add PF_RING support\nrelease v3\n    \n    maybe use something with a larger keyspace than the query ID for the conntable map\n    maybe not so many string conversions?\n    maybe move the dnsLogEntry struct -> JSON encoding to the log channel?\n    add more Types to gopacket\n*\/\n\n\n\n\/*\n\nDNS log entry struct and helper functions\n\n*\/\ntype dnsLogEntry struct {\n    Query_ID        uint16          `json:\"query_id\"`\n    Response_Code   int             `json:\"response_code\"`\n\tQuestion        string          `json:\"question\"`\n\tQuestion_Type   string          `json:\"question_type\"`\n\tAnswer          string          `json:\"answer\"`\n\tAnswer_Type     string          `json:\"answer_type\"`\n\tTTL             uint32          `json:\"ttl\"`\n\tServer          net.IP          `json:\"server\"`\n\tClient          net.IP          `json:\"client\"`\n\tTimestamp       string          `json:\"timestamp\"`\n\n\tencoded []byte  \/\/to hold the marshaled data structure\n\terr     error   \/\/encoding errors\n}\n\n\nfunc (dle *dnsLogEntry) ensureEncoded() {\n\tif dle.encoded == nil && dle.err == nil {\n\t\tdle.encoded, dle.err = json.Marshal(dle)\n\t}\n}\n\nfunc (dle *dnsLogEntry) Length() int {\n\tdle.ensureEncoded()\n\treturn len(dle.encoded)\n}\n\nfunc (dle *dnsLogEntry) Encode() ([]byte, error) {\n\tdle.ensureEncoded()\n\treturn dle.encoded, dle.err\n}\n\n\/* validate if DNS, make conntable entry and output \n   to log channel if there is a match \n   *\/\nfunc handlePacket(packets chan gopacket.Packet, logC chan dnsLogEntry){\n    \n    \/\/DNS IDs are stored as uint16s by the gopacket DNS layer\n    \/\/TODO: fix the memory leak of failed lookups by making this a ttlcache\n    var conntable = make(map[uint16]*layers.DNS)\n    \n    for packet := range packets {\n        \/\/TODO: there must be a better way of doing this with gopacket\n        var srcIP net.IP\n        var dstIP net.IP\n\n        if ipLayer := packet.Layer(layers.LayerTypeIPv4); ipLayer != nil {\n            ipData, _ := ipLayer.(*layers.IPv4)\n            srcIP = ipData.SrcIP\n            dstIP = ipData.DstIP\n        }else if ipLayer := packet.Layer(layers.LayerTypeIPv6); ipLayer != nil {\n            ipData, _ := ipLayer.(*layers.IPv6)\n            srcIP = ipData.SrcIP\n            dstIP = ipData.DstIP\n        }else{\n            \/\/non-IP transport?  Ignore this packet\n            \/\/TODO: debug message here\n            continue\n        }\n        \n        if dnsLayer := packet.Layer(layers.LayerTypeDNS); dnsLayer != nil {\n            \/\/ Get actual DNS data from this layer\n            dns, _ := dnsLayer.(*layers.DNS)\n            \n            \/\/skip non-query stuff (Updates, AXFRs, etc)\n            if dns.OpCode != layers.DNSOpCodeQuery {\n                \/\/TODO: debug message here \"saw non query packet with ID NNNN\"\n                continue\n            }\n            \n            \/\/this is a Query Response packet\n            if dns.QR == true{\n                if question, ok := conntable[dns.ID]; ok != false {\n                    \/\/We have both legs of the connection, so drop the connection from the table\n                    \/\/TODO: debug message here \"got second leg of query ID NNNN\"\n                    delete(conntable, question.ID)\n                    \n                    \/*\n                        http:\/\/forums.devshed.com\/dns-36\/dns-packet-question-section-1-a-183026.html\n                        multiple questions isn't really a thing, so we'll loop over the answers and\n                        insert the question section from the original query.  This means a successful\n                        ANY query may result in a lot of seperate log entries.  The query ID will be\n                        the same on all of those entries, however, so you can rebuild the query that\n                        way.\n                    *\/\n                    \n                    \/*\n                        The gopacket DNS layer doesn't have a lot of good String()\n                        conversion methods, so we have to do a lot of that ourselves\n                        here.  Much of this should move back into gopacket.  Also a\n                        little worried about the perf impact of doing string conversions\n                        in this thread...\n                    \n                    *\/\n\n                    var questionType string\n                \n                    switch question.Questions[0].Type {\n                        default:\n                            questionType = strconv.Itoa(int(question.Questions[0].Type))\n                        case layers.DNSTypeA:\n                            questionType = \"A\"\n                        case layers.DNSTypeAAAA:\n                            questionType = \"AAAA\"\n                        case layers.DNSTypeCNAME:\n                            questionType = \"CNAME\"\n                        case layers.DNSTypeMX:\n                            questionType = \"MX\"\n                        case layers.DNSTypeNS:\n                            questionType = \"NS\"\n                        case layers.DNSTypePTR:\n                            questionType = \"PTR\"\n                        case layers.DNSTypeTXT:\n                            questionType = \"TXT\"\n                        case layers.DNSTypeSOA:\n                            questionType = \"SOA\"\n                        case layers.DNSTypeSRV:\n                            questionType = \"SRV\" \n                        case 255:   \/\/ANY query per http:\/\/tools.ietf.org\/html\/rfc1035#page-12\n                            questionType = \"ANY\"\n                    }\n                    \n                    \/\/a response code of 0 means success\n                    if dns.ResponseCode != 0 {\n                    \n                        \/\/TODO: debug message here \"query failure code N for query ID NNNN\"\n                    \n                        logEntry := dnsLogEntry{\n                            Query_ID:       dns.ID,\n    \t\t            \tQuestion:       string(question.Questions[0].Name),\n    \t\t            \tResponse_Code:  int(dns.ResponseCode),\n                \t\t\tQuestion_Type:  questionType,\n    \t\t\t            Answer:         dns.ResponseCode.String(),\n                \t\t\tAnswer_Type:    \"\",\n    \t\t\t            TTL:            0,\n    \t\t\t            \/\/this is the answer packet, which comes from the server...\n    \t\t\t            Server:         srcIP,\n    \t\t\t            \/\/...and goes to the client\n    \t\t\t            Client:         dstIP,\n    \t\t\t            Timestamp:      time.Now().UTC().Format(time.RFC3339),\n                \t\t}\n                \t\t\n                \t\t\/\/marshal to JSON.  Maybe we should do this in the log thread?\n                \t\t\/\/encoded, _ := logEntry.Encode()\n                        \/\/\n                        \/\/logC <- string(encoded)\n                        \n                        logC <- logEntry\n                        \n                        continue\n                    \n                    }\n                    \n                    for _, answer := range dns.Answers {\n                    \n                        var answerString string\n                        var typeString string\n                    \n                        switch answer.Type {\n                            default:\n                                \/\/take a blind stab...at least this shouldn't *lose* data\n                                answerString = string(answer.Data)\n                                typeString = strconv.Itoa(int(answer.Type))\n                            case layers.DNSTypeA:\n                                answerString = answer.IP.String()\n                                typeString = \"A\"\n                            case layers.DNSTypeAAAA:\n                                answerString = answer.IP.String()\n                                typeString = \"AAAA\"\n                            case layers.DNSTypeCNAME:\n                                answerString = string(answer.CNAME)\n                                typeString = \"CNAME\"\n                            case layers.DNSTypeMX:\n                                \/\/TODO: add the priority\n                                answerString = string(answer.MX.Name)\n                                typeString = \"MX\"\n                            case layers.DNSTypeNS:\n                                answerString = string(answer.NS)\n                                typeString = \"NS\"\n                            case layers.DNSTypePTR:\n                                answerString = string(answer.PTR)\n                                typeString = \"PTR\"\n                            case layers.DNSTypeTXT:\n                                answerString = string(answer.TXT)\n                                typeString = \"TXT\"\n                            case layers.DNSTypeSOA:\n                                \/\/TODO: rebuild the full SOA string\n                                answerString = string(answer.SOA.RName)\n                                typeString = \"SOA\"\n                            case layers.DNSTypeSRV:\n                                \/\/TODO: rebuild the full SRV string\n                                answerString = string(answer.SRV.Name)\n                                typeString = \"SRV\"\n                        }\n\n                        logEntry := dnsLogEntry{\n                            Query_ID:       dns.ID,\n    \t\t            \tQuestion:       string(question.Questions[0].Name),\n    \t\t            \tResponse_Code:  int(dns.ResponseCode),\n                \t\t\tQuestion_Type:  questionType,\n    \t\t\t            Answer:         answerString,\n                \t\t\tAnswer_Type:    typeString,\n    \t\t\t            TTL:            answer.TTL,\n    \t\t\t            \/\/this is the answer packet, which comes from the server...\n    \t\t\t            Server:         srcIP,\n    \t\t\t            \/\/...and goes to the client\n    \t\t\t            Client:         dstIP,\n    \t\t\t            Timestamp:      time.Now().UTC().Format(time.RFC3339),\n                \t\t}\n                \t\t\n                \t\t\/\/marshal to JSON.  Maybe we should do this in the log thread?\n                \t\t\/\/encoded, _ := logEntry.Encode()\n                        \/\/\n                        \/\/logC <- string(encoded)\n                        \n                        logC <- logEntry\n                        \n                    }\n                }else{\n                    \/\/This might happen if we get a query ID collision\n                    \/\/TODO: debug message here \n                    log.Println(\"got a Query Response and can't find a query!\")\n                    continue\n                }\n            }else{\n                \/\/This is the initial query.  save it for later.\n                \/\/TODO: debug message here \"got first leg of query ID NNNN\"\n                conntable[dns.ID] = dns\n            }\n        }\n    }\n}\n\nfunc logConn(logC chan dnsLogEntry){\n    for message := range logC {\n        \/\/marshal to JSON.  Maybe we should do this in the log thread?\n        encoded, _ := message.Encode()\n\n        fmt.Println(string(encoded))\n    }\n}\n\nfunc main(){\n\n    var dev = flag.String(\"dev\", \"\", \"Capture Device\")\n\/\/    var kafka_brokers   = flag.String(\"kafka_brokers\", os.Getenv(\"KAFKA_PEERS\"), \"The Kafka brokers to connect to, as a comma separated list\")\n\/\/    var kafka_topic = flag.String(\"kafka_topic\",\"\",\"Kafka topic for output\")\n    var bpf = flag.String(\"bpf\",\"port 53\",\"BPF Filter\")\n    var pcapFile = flag.String(\"pcap\",\"\",\"pcap file\")\n\/\/    var logfile = flag.String(\"logfile\",\"\",\"log file (recommended for debug only\")\n    \n    flag.Parse()\n    \n    var handle *pcap.Handle\n    var err error\n    \n    if(*dev != \"\"){\n        handle, err = pcap.OpenLive(*dev, 65536, true, pcap.BlockForever)\n        if err != nil {log.Fatal(err) }\n    }else if(*pcapFile != \"\"){\n        handle, err = pcap.OpenOffline(*pcapFile)\n        if err != nil { log.Fatal(err) }\n    }else{\n        log.Fatal(\"You must specify either a capture device or a pcap file\")\n    }\n    \n    defer handle.Close()\n    \n    err = handle.SetBPFFilter(*bpf)\n    if err != nil { log.Fatal(err) }\n \n    \/* spin up logging thread *\/\n    var logChan = make(chan dnsLogEntry)\n    go logConn(logChan)\n \n    \/* init channels for the packet handlers and kick off handler threads *\/\n    var channels [8]chan gopacket.Packet\n    for i := 0; i < 8; i++ {\n        channels[i] = make(chan gopacket.Packet)\n        go handlePacket(channels[i], logChan)\n    }\n    \n    \/\/ Use the handle as a packet source to process all packets\n    packetSource := gopacket.NewPacketSource(handle, handle.LinkType())\n    for packet := range packetSource.Packets() {\n        \/\/ Dispatch packets here\n        if net := packet.NetworkLayer(); net != nil {\n            \/*  load balance the processiing over 8 threads\n                FashHash is consistant for A->B and B->A hashes, which simplifies\n                our connection tracking problem a bit by letting us keep\n                per-worker connection pools instead of a global pool.\n            *\/\n            channels[int(net.NetworkFlow().FastHash()) & 0x7] <- packet\n        }\n    }    \n}\n<commit_msg>implement a fan-out logging pattern that enables multiple logging sinks<commit_after>package main\n\nimport \"flag\"\nimport \"fmt\"\nimport \"log\"\nimport \"strconv\"\nimport \"time\"\nimport \"net\"\nimport \"os\"\nimport \"encoding\/json\"\n\/\/import \"github.com\/Shopify\/sarama\"\nimport \"github.com\/google\/gopacket\"\nimport \"github.com\/google\/gopacket\/pcap\"\nimport \"github.com\/google\/gopacket\/layers\"\n\n\n\/*\n    -logging to file\n    debug logging\n    ttlcache for failed queries\n    -documentation\nrelease v1    \n    \n    stats output\n    perf testing\n    TCP flow support\nrelease v2\n\n    logging to kafka\n    add PF_RING support\nrelease v3\n    \n    maybe use something with a larger keyspace than the query ID for the conntable map\n    maybe not so many string conversions?\n    maybe move the dnsLogEntry struct -> JSON encoding to the log channel?\n    add more Types to gopacket\n*\/\n\n\n\n\/*\n\nDNS log entry struct and helper functions\n\n*\/\ntype dnsLogEntry struct {\n    Query_ID        uint16          `json:\"query_id\"`\n    Response_Code   int             `json:\"response_code\"`\n\tQuestion        string          `json:\"question\"`\n\tQuestion_Type   string          `json:\"question_type\"`\n\tAnswer          string          `json:\"answer\"`\n\tAnswer_Type     string          `json:\"answer_type\"`\n\tTTL             uint32          `json:\"ttl\"`\n\tServer          net.IP          `json:\"server\"`\n\tClient          net.IP          `json:\"client\"`\n\tTimestamp       string          `json:\"timestamp\"`\n\n\tencoded []byte  \/\/to hold the marshaled data structure\n\terr     error   \/\/encoding errors\n}\n\n\nfunc (dle *dnsLogEntry) ensureEncoded() {\n\tif dle.encoded == nil && dle.err == nil {\n\t\tdle.encoded, dle.err = json.Marshal(dle)\n\t}\n}\n\nfunc (dle *dnsLogEntry) Length() int {\n\tdle.ensureEncoded()\n\treturn len(dle.encoded)\n}\n\nfunc (dle *dnsLogEntry) Encode() ([]byte, error) {\n\tdle.ensureEncoded()\n\treturn dle.encoded, dle.err\n}\n\n\/* validate if DNS, make conntable entry and output \n   to log channel if there is a match \n   *\/\nfunc handlePacket(packets chan gopacket.Packet, logC chan dnsLogEntry){\n    \n    \/\/DNS IDs are stored as uint16s by the gopacket DNS layer\n    \/\/TODO: fix the memory leak of failed lookups by making this a ttlcache\n    var conntable = make(map[uint16]*layers.DNS)\n    \n    for packet := range packets {\n        \/\/TODO: there must be a better way of doing this with gopacket\n        var srcIP net.IP\n        var dstIP net.IP\n\n        if ipLayer := packet.Layer(layers.LayerTypeIPv4); ipLayer != nil {\n            ipData, _ := ipLayer.(*layers.IPv4)\n            srcIP = ipData.SrcIP\n            dstIP = ipData.DstIP\n        }else if ipLayer := packet.Layer(layers.LayerTypeIPv6); ipLayer != nil {\n            ipData, _ := ipLayer.(*layers.IPv6)\n            srcIP = ipData.SrcIP\n            dstIP = ipData.DstIP\n        }else{\n            \/\/non-IP transport?  Ignore this packet\n            \/\/TODO: debug message here\n            continue\n        }\n        \n        if dnsLayer := packet.Layer(layers.LayerTypeDNS); dnsLayer != nil {\n            \/\/ Get actual DNS data from this layer\n            dns, _ := dnsLayer.(*layers.DNS)\n            \n            \/\/skip non-query stuff (Updates, AXFRs, etc)\n            if dns.OpCode != layers.DNSOpCodeQuery {\n                \/\/TODO: debug message here \"saw non query packet with ID NNNN\"\n                continue\n            }\n            \n            \/\/this is a Query Response packet\n            if dns.QR == true{\n                if question, ok := conntable[dns.ID]; ok != false {\n                    \/\/We have both legs of the connection, so drop the connection from the table\n                    \/\/TODO: debug message here \"got second leg of query ID NNNN\"\n                    delete(conntable, question.ID)\n                    \n                    \/*\n                        http:\/\/forums.devshed.com\/dns-36\/dns-packet-question-section-1-a-183026.html\n                        multiple questions isn't really a thing, so we'll loop over the answers and\n                        insert the question section from the original query.  This means a successful\n                        ANY query may result in a lot of seperate log entries.  The query ID will be\n                        the same on all of those entries, however, so you can rebuild the query that\n                        way.\n                    *\/\n                    \n                    \/*\n                        The gopacket DNS layer doesn't have a lot of good String()\n                        conversion methods, so we have to do a lot of that ourselves\n                        here.  Much of this should move back into gopacket.  Also a\n                        little worried about the perf impact of doing string conversions\n                        in this thread...\n                    \n                    *\/\n\n                    var questionType string\n                \n                    switch question.Questions[0].Type {\n                        default:\n                            questionType = strconv.Itoa(int(question.Questions[0].Type))\n                        case layers.DNSTypeA:\n                            questionType = \"A\"\n                        case layers.DNSTypeAAAA:\n                            questionType = \"AAAA\"\n                        case layers.DNSTypeCNAME:\n                            questionType = \"CNAME\"\n                        case layers.DNSTypeMX:\n                            questionType = \"MX\"\n                        case layers.DNSTypeNS:\n                            questionType = \"NS\"\n                        case layers.DNSTypePTR:\n                            questionType = \"PTR\"\n                        case layers.DNSTypeTXT:\n                            questionType = \"TXT\"\n                        case layers.DNSTypeSOA:\n                            questionType = \"SOA\"\n                        case layers.DNSTypeSRV:\n                            questionType = \"SRV\" \n                        case 255:   \/\/ANY query per http:\/\/tools.ietf.org\/html\/rfc1035#page-12\n                            questionType = \"ANY\"\n                    }\n                    \n                    \/\/a response code of 0 means success\n                    if dns.ResponseCode != 0 {\n                    \n                        \/\/TODO: debug message here \"query failure code N for query ID NNNN\"\n                    \n                        logEntry := dnsLogEntry{\n                            Query_ID:       dns.ID,\n    \t\t            \tQuestion:       string(question.Questions[0].Name),\n    \t\t            \tResponse_Code:  int(dns.ResponseCode),\n                \t\t\tQuestion_Type:  questionType,\n    \t\t\t            Answer:         dns.ResponseCode.String(),\n                \t\t\tAnswer_Type:    \"\",\n    \t\t\t            TTL:            0,\n    \t\t\t            \/\/this is the answer packet, which comes from the server...\n    \t\t\t            Server:         srcIP,\n    \t\t\t            \/\/...and goes to the client\n    \t\t\t            Client:         dstIP,\n    \t\t\t            Timestamp:      time.Now().UTC().Format(time.RFC3339),\n                \t\t}\n                \t\t\n                \t\t\/\/marshal to JSON.  Maybe we should do this in the log thread?\n                \t\t\/\/encoded, _ := logEntry.Encode()\n                        \/\/\n                        \/\/logC <- string(encoded)\n                        \n                        logC <- logEntry\n                        \n                        continue\n                    \n                    }\n                    \n                    for _, answer := range dns.Answers {\n                    \n                        var answerString string\n                        var typeString string\n                    \n                        switch answer.Type {\n                            default:\n                                \/\/take a blind stab...at least this shouldn't *lose* data\n                                answerString = string(answer.Data)\n                                typeString = strconv.Itoa(int(answer.Type))\n                            case layers.DNSTypeA:\n                                answerString = answer.IP.String()\n                                typeString = \"A\"\n                            case layers.DNSTypeAAAA:\n                                answerString = answer.IP.String()\n                                typeString = \"AAAA\"\n                            case layers.DNSTypeCNAME:\n                                answerString = string(answer.CNAME)\n                                typeString = \"CNAME\"\n                            case layers.DNSTypeMX:\n                                \/\/TODO: add the priority\n                                answerString = string(answer.MX.Name)\n                                typeString = \"MX\"\n                            case layers.DNSTypeNS:\n                                answerString = string(answer.NS)\n                                typeString = \"NS\"\n                            case layers.DNSTypePTR:\n                                answerString = string(answer.PTR)\n                                typeString = \"PTR\"\n                            case layers.DNSTypeTXT:\n                                answerString = string(answer.TXT)\n                                typeString = \"TXT\"\n                            case layers.DNSTypeSOA:\n                                \/\/TODO: rebuild the full SOA string\n                                answerString = string(answer.SOA.RName)\n                                typeString = \"SOA\"\n                            case layers.DNSTypeSRV:\n                                \/\/TODO: rebuild the full SRV string\n                                answerString = string(answer.SRV.Name)\n                                typeString = \"SRV\"\n                        }\n\n                        logEntry := dnsLogEntry{\n                            Query_ID:       dns.ID,\n    \t\t            \tQuestion:       string(question.Questions[0].Name),\n    \t\t            \tResponse_Code:  int(dns.ResponseCode),\n                \t\t\tQuestion_Type:  questionType,\n    \t\t\t            Answer:         answerString,\n                \t\t\tAnswer_Type:    typeString,\n    \t\t\t            TTL:            answer.TTL,\n    \t\t\t            \/\/this is the answer packet, which comes from the server...\n    \t\t\t            Server:         srcIP,\n    \t\t\t            \/\/...and goes to the client\n    \t\t\t            Client:         dstIP,\n    \t\t\t            Timestamp:      time.Now().UTC().Format(time.RFC3339),\n                \t\t}\n                        \n                        logC <- logEntry\n                        \n                    }\n                }else{\n                    \/\/This might happen if we get a query ID collision\n                    \/\/TODO: debug message here \n                    log.Println(\"got a Query Response and can't find a query!\")\n                    continue\n                }\n            }else{\n                \/\/This is the initial query.  save it for later.\n                \/\/TODO: debug message here \"got first leg of query ID NNNN\"\n                conntable[dns.ID] = dns\n            }\n        }\n    }\n}\n\n\/\/Round-robin log messages to log sinks\nfunc logConn(logC chan dnsLogEntry, stdout bool, file bool, kafka bool, \n            filename string, kafka_brokers string, kafka_topic string){\n    \n    var logs []chan dnsLogEntry\n    \n    if stdout {\n        stdoutChan := make(chan dnsLogEntry)\n        logs = append(logs, stdoutChan)\n        go logConnStdout(stdoutChan)\n    }\n    \n    if file {\n        fileChan := make(chan dnsLogEntry)\n        logs = append(logs, fileChan)\n        go logConnFile(fileChan, filename)\n    }\n    \n    if kafka && false {\n        kafkaChan := make(chan dnsLogEntry)\n        logs = append(logs, kafkaChan)\n        go logConnKafka(kafkaChan, kafka_brokers, kafka_topic)\n    }\n    \n    for message := range logC {\n        for _, logChan := range logs {\n            logChan <- message\n        }\n    }\n}\n\nfunc logConnStdout(logC chan dnsLogEntry){\n    for message := range logC {\n        \/\/marshal to JSON.  Maybe we should do this in the log thread?\n        encoded, _ := message.Encode()\n        fmt.Println(string(encoded))\n    }\n}\n\nfunc logConnFile(logC chan dnsLogEntry, filename string){\n    \n    f, err := os.OpenFile(filename, os.O_WRONLY | os.O_CREATE | os.O_APPEND, 0666)\n    if err != nil {\n        panic(err)\n    }\n    \n    defer f.Close()\n    \n    for message := range logC {\n        \/\/marshal to JSON.  Maybe we should do this in the log thread?\n        encoded, _ := message.Encode()\n        f.WriteString(string(encoded)+\"\\n\")\n    }\n}\n\nfunc logConnKafka(logC chan dnsLogEntry, kafka_brokers string, kafka_topic string){\n    for message := range logC {\n        \/\/marshal to JSON.  Maybe we should do this in the log thread?\n        encoded, _ := message.Encode()\n        fmt.Println(\"Kafka: \"+string(encoded))\n    }\n}\n\n\nfunc main(){\n\n    var dev = flag.String(\"dev\", \"\", \"Capture Device\")\n    var kafka_brokers   = flag.String(\"kafka_brokers\", os.Getenv(\"KAFKA_PEERS\"), \"The Kafka brokers to connect to, as a comma separated list\")\n    var kafka_topic = flag.String(\"kafka_topic\",\"\",\"Kafka topic for output\")\n    var bpf = flag.String(\"bpf\",\"port 53\",\"BPF Filter\")\n    var pcapFile = flag.String(\"pcap\",\"\",\"pcap file\")\n    var logfile = flag.String(\"logfile\",\"\",\"log file (recommended for debug only\")\n    var quiet = flag.Bool(\"quiet\", false, \"do not log to stdout\")\n    \n    flag.Parse()\n    \n    var handle *pcap.Handle\n    var err error\n    \n    if(*dev != \"\"){\n        handle, err = pcap.OpenLive(*dev, 65536, true, pcap.BlockForever)\n        if err != nil {log.Fatal(err) }\n    }else if(*pcapFile != \"\"){\n        handle, err = pcap.OpenOffline(*pcapFile)\n        if err != nil { log.Fatal(err) }\n    }else{\n        log.Fatal(\"You must specify either a capture device or a pcap file\")\n    }\n    \n    defer handle.Close()\n    \n    err = handle.SetBPFFilter(*bpf)\n    if err != nil { log.Fatal(err) }\n \n    \/* spin up logging thread *\/\n    var logChan = make(chan dnsLogEntry)\n    var log_file bool = false\n    var log_kafka bool = false\n    \n    if *logfile != \"\" {\n        log_file = true\n    }\n    \n    if *kafka_brokers != \"\" && *kafka_topic != \"\" {\n        log_kafka = true\n    }\n    \n    go logConn(logChan, !*quiet, log_file, log_kafka, *logfile, *kafka_brokers, *kafka_topic)\n \n    \/* init channels for the packet handlers and kick off handler threads *\/\n    var channels [8]chan gopacket.Packet\n    for i := 0; i < 8; i++ {\n        channels[i] = make(chan gopacket.Packet)\n        go handlePacket(channels[i], logChan)\n    }\n    \n    \/\/ Use the handle as a packet source to process all packets\n    packetSource := gopacket.NewPacketSource(handle, handle.LinkType())\n    for packet := range packetSource.Packets() {\n        \/\/ Dispatch packets here\n        if net := packet.NetworkLayer(); net != nil {\n            \/*  load balance the processiing over 8 threads\n                FashHash is consistant for A->B and B->A hashes, which simplifies\n                our connection tracking problem a bit by letting us keep\n                per-worker connection pools instead of a global pool.\n            *\/\n            channels[int(net.NetworkFlow().FastHash()) & 0x7] <- packet\n        }\n    }    \n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/chzyer\/readline\"\n)\n\nvar db *bolt.DB\n\n\/\/ commandInfo struct is stored as the value to commands\ntype commandInfo struct {\n\ttime  time.Time\n\tcount int\n}\n\nfunc (ci commandInfo) String() string {\n\treturn fmt.Sprintf(\"%s:%d\", ci.time.String(), ci.count)\n}\n\nfunc (ci commandInfo) Update(ciString string) commandInfo {\n\tinfo := strings.Split(os.Getenv(\"PATH\"), \":\")\n\tnewCI := commandInfo{}\n\n\tcount, err := strconv.Atoi(info[1])\n\tif err != nil {\n\t\tcount = 0\n\t}\n\n\tnewCI.time = time.Now()\n\tnewCI.count = count + 1\n\n\treturn newCI\n}\n\nfunc (ci commandInfo) NewFromString(ciString string) commandInfo {\n\tinfo := strings.Split(os.Getenv(\"PATH\"), \":\")\n\tnewCI := commandInfo{}\n\n\tdate, err := time.Parse(time.RFC3339, info[0])\n\tif err != nil {\n\t\tdate = time.Now()\n\t}\n\n\tcount, err := strconv.Atoi(info[1])\n\tif err != nil {\n\t\tcount = 0\n\t}\n\n\tnewCI.time = date\n\tnewCI.count = count\n\n\treturn newCI\n}\n\nfunc main() {\n\t\/\/ Setup flags\n\t\/\/ statsPtr := flag.Bool(\"stats\", false, \"show stats and usage of `r`\")\n\t\/\/ completePtr := flag.String(\"complete\", \"\", \"show all results for `r`\")\n\tcommandPtr := flag.Bool(\"command\", false, \"show last command selected from `r`\")\n\taddPtr := flag.String(\"add\", \"\", \"show stats and usage of `r`\")\n\tflag.Parse()\n\n\t\/\/ Setup bolt db\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tboltPath := filepath.Join(usr.HomeDir, \".r.db\")\n\t\/\/ It will be created if it doesn't exist.\n\tdb, err = bolt.Open(boltPath, 0600, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\t\/\/ Check if `results` flag is passed\n\t\/\/ if *completePtr != \"\" {\n\t\/\/ \tresults := showResults(*completePtr)\n\t\/\/ \tfor _, result := range results {\n\t\/\/ \t\tfmt.Println(result)\n\t\/\/ \t}\n\t\/\/ \tos.Exit(0)\n\t\/\/ }\n\n\tif *commandPtr {\n\t\tprintLastCommand()\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Check if `add` flag is passed\n\tif *addPtr != \"\" {\n\t\targs := strings.Split(*addPtr, \":\")\n\t\terr := add(args[0], args[1])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ reset last command to blank\n\t\/\/ set line as stored command\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\tb, err := tx.CreateBucketIfNotExists([]byte(\"command\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = b.Put([]byte(\"command\"), []byte(\"\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treadLine()\n}\n\n\/\/ readLine used the readline library create a prompt to\n\/\/ show the command history\nfunc readLine() {\n\t\/\/ create completer from results\n\tresults, err := showResults()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tvar pcItems []*readline.PrefixCompleter\n\tfor _, result := range results {\n\t\tpcItems = append(pcItems, readline.PcItem(result))\n\t}\n\tvar completer = readline.NewPrefixCompleter(pcItems...)\n\n\trl, err := readline.NewEx(&readline.Config{\n\t\tPrompt:       \"> \",\n\t\tAutoComplete: completer,\n\t})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer rl.Close()\n\n\tfor {\n\t\tline, err := rl.Readline()\n\t\tif err != nil { \/\/ io.EOF\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Only execute if the command typed is in the list of results\n\t\tif !containsCmd(strings.TrimSpace(line), results) {\n\t\t\tfmt.Println(\"Command not found in `r` history.\")\n\t\t\tos.Exit(0)\n\t\t}\n\n\t\t\/\/ set line as stored command\n\t\terr = db.Update(func(tx *bolt.Tx) error {\n\t\t\tb, err := tx.CreateBucketIfNotExists([]byte(\"command\"))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = b.Put([]byte(\"command\"), []byte(line))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tos.Exit(0)\n\t}\n}\n\n\/\/ printLastCommand is used with the --command flag\n\/\/ it shows the last command selected from the readline prompt\nfunc printLastCommand() {\n\tvar val string\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\tb, err := tx.CreateBucketIfNotExists([]byte(\"command\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tval = string(b.Get([]byte(\"command\")))\n\t\treturn nil\n\t})\n\n\tfmt.Println(val)\n}\n\n\/\/ showResults reads the boltdb and returns the command history\n\/\/ based on your current working directory\nfunc showResults() ([]string, error) {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ results := []string{\"git status\", \"git clone\", \"go install\", \"cd \/Users\/jesse\/\", \"cd \/Users\/jesse\/gocode\/src\/github.com\/jesselucas\", \"ls -Glah\"}\n\tvar results []string\n\terr = db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(\"DirectoryBucket\"))\n\t\tpathBucket := b.Bucket([]byte(wd))\n\t\treturn pathBucket.ForEach(func(k, v []byte) error {\n\t\t\tresults = append(results, string(k))\n\t\t\treturn nil\n\t\t})\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn results, nil\n\n\t\/\/ filter\n\t\/\/ var filtered []string\n\t\/\/ for _, result := range results {\n\t\/\/ \tif strings.HasPrefix(result, input) {\n\t\/\/ \t\tfiltered = append(filtered, result)\n\t\/\/ \t}\n\t\/\/ }\n\t\/\/\n\t\/\/ return filtered\n\n}\n\n\/\/ add checks if command being passed is in the listCommands\n\/\/ then stores the command and workding directory\nfunc add(path string, promptCmd string) error {\n\t\/\/ get the first command in the promptCmd string\n\tcmd := strings.Split(promptCmd, \" \")[0]\n\n\tcommands, err := listCommands()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ check if the command is valid\n\tif !containsCmd(cmd, commands) {\n\t\treturn nil\n\t}\n\n\t\/\/ Add command to db\n\t\/\/ fmt.Printf(\"adding. cmd: %s, path: %s \\n\", promptCmd, path)\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\tdirectoryBucket, err := tx.CreateBucketIfNotExists([]byte(\"DirectoryBucket\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpathBucket, err := directoryBucket.CreateBucketIfNotExists([]byte(path))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Store path and command for contextual path sorting\n\t\tcmdBucket, err := tx.CreateBucketIfNotExists([]byte(\"CommandBucket\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Don't store if the command is r\n\t\tif cmd == \"r\" {\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ TODO first look up command and then increment it's count\n\n\t\t\/\/ Create commandInfo struct\n\t\tci := commandInfo{}\n\t\tci.time = time.Now()\n\t\tci.count = 1\n\n\t\t\/\/ Check if there is a command info value already\n\t\tv := cmdBucket.Get([]byte(promptCmd))\n\t\tif v != nil {\n\t\t\t\/\/ There is a previous command info value\n\t\t\t\/\/ Let's update the count and time\n\t\t\tci = ci.Update(string(v))\n\t\t}\n\n\t\terr = cmdBucket.Put([]byte(promptCmd), []byte(ci.String()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Now let's do the same thing for the pathBucket\n\t\tv = pathBucket.Get([]byte(promptCmd))\n\t\tif v != nil {\n\t\t\t\/\/ There is a previous command info value\n\t\t\t\/\/ Let's update the count and time\n\t\t\tci = ci.Update(string(v))\n\t\t}\n\n\t\terr = pathBucket.Put([]byte(promptCmd), []byte(ci.String()))\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\n\/\/ containsCmd checks if a command string is is in a slice of strings\nfunc containsCmd(cmd string, commands []string) bool {\n\tfor _, c := range commands {\n\t\t\/\/ check first command against list of commands\n\t\tif c == cmd {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ listCommands use $PATH to find directories\n\/\/ Then reads each directory and looks for executables\nfunc listCommands() ([]string, error) {\n\t\/\/ Split $PATH directories into slice\n\tpaths := strings.Split(os.Getenv(\"PATH\"), \":\")\n\tvar commands []string\n\n\t\/\/ created buffered error chan\n\terrc := make(chan error, 1)\n\n\t\/\/ sync go routines\n\tvar wg sync.WaitGroup\n\n\t\/\/ find commands appends results to commands slice\n\tfindCommands := func(p string) {\n\t\tdefer wg.Done()\n\n\t\tfiles, err := ioutil.ReadDir(p)\n\t\tif err != nil {\n\t\t\terrc <- err \/\/ write err into error chan\n\t\t\treturn\n\t\t}\n\n\t\tfor _, f := range files {\n\t\t\tm := f.Mode()\n\n\t\t\t\/\/ Check if file is executable\n\t\t\tif m&0111 != 0 {\n\t\t\t\tcommands = append(commands, f.Name())\n\t\t\t}\n\t\t}\n\n\t\terrc <- nil \/\/ write nil into error chan\n\t}\n\n\t\/\/ Check each path for commands\n\tfor _, p := range paths {\n\t\twg.Add(1)\n\t\tgo findCommands(p)\n\n\t\t\/\/ read any error that is in error chan\n\t\tif err := <-errc; err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\twg.Wait() \/\/ Wait for the paths to be checked\n\n\treturn commands, nil\n}\n\n\/\/ stats TODO print stats and usage of r\nfunc stats() {\n\tfmt.Println(\"stats\")\n}\n<commit_msg>Fixing time parsing<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/chzyer\/readline\"\n)\n\nvar db *bolt.DB\n\n\/\/ commandInfo struct is stored as the value to commands\ntype commandInfo struct {\n\ttime  time.Time\n\tcount int\n}\n\nfunc (ci commandInfo) String() string {\n\t\/\/ Store the time in RFC3339 format for easy parsing\n\treturn fmt.Sprintf(\"%s%s%d\", ci.time.Format(time.RFC3339), \",\", ci.count)\n}\n\nfunc (ci commandInfo) Update(ciString string) commandInfo {\n\tinfo := strings.Split(ciString, \",\")\n\tnewCI := commandInfo{}\n\n\tcount, err := strconv.Atoi(info[1])\n\tif err != nil {\n\t\tcount = 0\n\t}\n\n\tnewCI.time = time.Now()\n\tnewCI.count = count + 1\n\n\treturn newCI\n}\n\nfunc (ci commandInfo) NewFromString(ciString string) commandInfo {\n\tinfo := strings.Split(ciString, \",\")\n\tnewCI := commandInfo{}\n\n\t\/\/ Parse the time as RFC3339 format\n\tdate, err := time.Parse(time.RFC3339, info[0])\n\tif err != nil {\n\t\tdate = time.Now()\n\t}\n\n\tcount, err := strconv.Atoi(info[1])\n\tif err != nil {\n\t\tcount = 0\n\t}\n\n\tnewCI.time = date\n\tnewCI.count = count\n\n\treturn newCI\n}\n\nfunc main() {\n\t\/\/ Setup flags\n\t\/\/ statsPtr := flag.Bool(\"stats\", false, \"show stats and usage of `r`\")\n\t\/\/ completePtr := flag.String(\"complete\", \"\", \"show all results for `r`\")\n\tcommandPtr := flag.Bool(\"command\", false, \"show last command selected from `r`\")\n\taddPtr := flag.String(\"add\", \"\", \"show stats and usage of `r`\")\n\tflag.Parse()\n\n\t\/\/ Setup bolt db\n\tusr, err := user.Current()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tboltPath := filepath.Join(usr.HomeDir, \".r.db\")\n\t\/\/ It will be created if it doesn't exist.\n\tdb, err = bolt.Open(boltPath, 0600, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\t\/\/ Check if `results` flag is passed\n\t\/\/ if *completePtr != \"\" {\n\t\/\/ \tresults := showResults(*completePtr)\n\t\/\/ \tfor _, result := range results {\n\t\/\/ \t\tfmt.Println(result)\n\t\/\/ \t}\n\t\/\/ \tos.Exit(0)\n\t\/\/ }\n\n\tif *commandPtr {\n\t\tprintLastCommand()\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Check if `add` flag is passed\n\tif *addPtr != \"\" {\n\t\targs := strings.Split(*addPtr, \":\")\n\t\terr := add(args[0], args[1])\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ reset last command to blank\n\t\/\/ set line as stored command\n\terr = db.Update(func(tx *bolt.Tx) error {\n\t\tb, err := tx.CreateBucketIfNotExists([]byte(\"command\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = b.Put([]byte(\"command\"), []byte(\"\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treadLine()\n}\n\n\/\/ readLine used the readline library create a prompt to\n\/\/ show the command history\nfunc readLine() {\n\t\/\/ create completer from results\n\tresults, err := showResults()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tvar pcItems []*readline.PrefixCompleter\n\tfor _, result := range results {\n\t\tpcItems = append(pcItems, readline.PcItem(result))\n\t}\n\tvar completer = readline.NewPrefixCompleter(pcItems...)\n\n\trl, err := readline.NewEx(&readline.Config{\n\t\tPrompt:       \"> \",\n\t\tAutoComplete: completer,\n\t})\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\tdefer rl.Close()\n\n\tfor {\n\t\tline, err := rl.Readline()\n\t\tif err != nil { \/\/ io.EOF\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Only execute if the command typed is in the list of results\n\t\tif !containsCmd(strings.TrimSpace(line), results) {\n\t\t\tfmt.Println(\"Command not found in `r` history.\")\n\t\t\tos.Exit(0)\n\t\t}\n\n\t\t\/\/ set line as stored command\n\t\terr = db.Update(func(tx *bolt.Tx) error {\n\t\t\tb, err := tx.CreateBucketIfNotExists([]byte(\"command\"))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\terr = b.Put([]byte(\"command\"), []byte(line))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tos.Exit(0)\n\t}\n}\n\n\/\/ printLastCommand is used with the --command flag\n\/\/ it shows the last command selected from the readline prompt\nfunc printLastCommand() {\n\tvar val string\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\tb, err := tx.CreateBucketIfNotExists([]byte(\"command\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tval = string(b.Get([]byte(\"command\")))\n\t\treturn nil\n\t})\n\n\tfmt.Println(val)\n}\n\n\/\/ showResults reads the boltdb and returns the command history\n\/\/ based on your current working directory\nfunc showResults() ([]string, error) {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ results := []string{\"git status\", \"git clone\", \"go install\", \"cd \/Users\/jesse\/\", \"cd \/Users\/jesse\/gocode\/src\/github.com\/jesselucas\", \"ls -Glah\"}\n\tvar results []string\n\terr = db.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(\"DirectoryBucket\"))\n\t\tpathBucket := b.Bucket([]byte(wd))\n\t\treturn pathBucket.ForEach(func(k, v []byte) error {\n\t\t\tci := commandInfo{}\n\t\t\tfmt.Printf(\"%s: %s \\n\", string(k), string(v))\n\t\t\tfmt.Printf(\"%s: %s \\n\", string(k), ci.NewFromString(string(v)))\n\t\t\tresults = append(results, string(k))\n\t\t\treturn nil\n\t\t})\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn results, nil\n\n\t\/\/ filter\n\t\/\/ var filtered []string\n\t\/\/ for _, result := range results {\n\t\/\/ \tif strings.HasPrefix(result, input) {\n\t\/\/ \t\tfiltered = append(filtered, result)\n\t\/\/ \t}\n\t\/\/ }\n\t\/\/\n\t\/\/ return filtered\n\n}\n\n\/\/ add checks if command being passed is in the listCommands\n\/\/ then stores the command and workding directory\nfunc add(path string, promptCmd string) error {\n\t\/\/ get the first command in the promptCmd string\n\tcmd := strings.Split(promptCmd, \" \")[0]\n\n\tcommands, err := listCommands()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ check if the command is valid\n\tif !containsCmd(cmd, commands) {\n\t\treturn nil\n\t}\n\n\t\/\/ Add command to db\n\t\/\/ fmt.Printf(\"adding. cmd: %s, path: %s \\n\", promptCmd, path)\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\tdirectoryBucket, err := tx.CreateBucketIfNotExists([]byte(\"DirectoryBucket\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpathBucket, err := directoryBucket.CreateBucketIfNotExists([]byte(path))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Store path and command for contextual path sorting\n\t\tcmdBucket, err := tx.CreateBucketIfNotExists([]byte(\"CommandBucket\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Don't store if the command is r\n\t\tif cmd == \"r\" {\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ TODO first look up command and then increment it's count\n\n\t\t\/\/ Create commandInfo struct\n\t\tci := commandInfo{}\n\t\tci.time = time.Now()\n\t\tci.count = 1\n\n\t\t\/\/ Check if there is a command info value already\n\t\tv := cmdBucket.Get([]byte(promptCmd))\n\t\tif v != nil {\n\t\t\t\/\/ There is a previous command info value\n\t\t\t\/\/ Let's update the count and time\n\t\t\tci = ci.Update(string(v))\n\t\t}\n\n\t\terr = cmdBucket.Put([]byte(promptCmd), []byte(ci.String()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Now let's do the same thing for the pathBucket\n\t\tv = pathBucket.Get([]byte(promptCmd))\n\t\tif v != nil {\n\t\t\t\/\/ There is a previous command info value\n\t\t\t\/\/ Let's update the count and time\n\t\t\tci = ci.Update(string(v))\n\t\t\tfmt.Println(ci)\n\t\t}\n\n\t\terr = pathBucket.Put([]byte(promptCmd), []byte(ci.String()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\n\/\/ containsCmd checks if a command string is is in a slice of strings\nfunc containsCmd(cmd string, commands []string) bool {\n\tfor _, c := range commands {\n\t\t\/\/ check first command against list of commands\n\t\tif c == cmd {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ listCommands use $PATH to find directories\n\/\/ Then reads each directory and looks for executables\nfunc listCommands() ([]string, error) {\n\t\/\/ Split $PATH directories into slice\n\tpaths := strings.Split(os.Getenv(\"PATH\"), \":\")\n\tvar commands []string\n\n\t\/\/ created buffered error chan\n\terrc := make(chan error, 1)\n\n\t\/\/ sync go routines\n\tvar wg sync.WaitGroup\n\n\t\/\/ find commands appends results to commands slice\n\tfindCommands := func(p string) {\n\t\tdefer wg.Done()\n\n\t\tfiles, err := ioutil.ReadDir(p)\n\t\tif err != nil {\n\t\t\terrc <- err \/\/ write err into error chan\n\t\t\treturn\n\t\t}\n\n\t\tfor _, f := range files {\n\t\t\tm := f.Mode()\n\n\t\t\t\/\/ Check if file is executable\n\t\t\tif m&0111 != 0 {\n\t\t\t\tcommands = append(commands, f.Name())\n\t\t\t}\n\t\t}\n\n\t\terrc <- nil \/\/ write nil into error chan\n\t}\n\n\t\/\/ Check each path for commands\n\tfor _, p := range paths {\n\t\twg.Add(1)\n\t\tgo findCommands(p)\n\n\t\t\/\/ read any error that is in error chan\n\t\tif err := <-errc; err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\twg.Wait() \/\/ Wait for the paths to be checked\n\n\treturn commands, nil\n}\n\n\/\/ stats TODO print stats and usage of r\nfunc stats() {\n\tfmt.Println(\"stats\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n  \"fmt\"\n  \"os\"\n  \"flag\"\n)\n\nvar (\n  Version string\n  Build string\n)\n\nfunc main() {\n  pwd, err := os.Getwd()\n  if (err != nil) {\n    fmt.Println(\"Error: could not determine your current directory: \", err)\n    os.Exit(1)\n  }\n\n  \/\/ Setup usage arguments and options.\n  cmdName := \"docker-unisync\"\n  flag.Usage = func() {\n    fmt.Printf(\"Example usage:\\n\\t%v [options] DOCKER-MACHINE-NAME...\", cmdName)\n    fmt.Println(\"\\nOptions:\")\n    flag.PrintDefaults()\n  }\n\n  help := flag.Bool(\"help\", false, \"Show this message\")\n  verbose := flag.Bool(\"verbose\", false, \"Verbose output\")\n  showVersion := flag.Bool(\"version\", false, \"Show version\")\n\n  flag.Parse()\n\n  if *showVersion {\n    fmt.Printf(\"%v version %v, build %v\\n\", cmdName, Version, Build)\n    return\n  }\n\n  if *help {\n    flag.Usage()\n    return\n  }\n\n  fmt.Println(*help)\n  fmt.Println(*verbose)\n  fmt.Println(\"Hello, yo!\")\n  fmt.Println(pwd)\n}\n<commit_msg>Formatting updates.<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n)\n\nvar (\n\tVersion string\n\tBuild   string\n)\n\nfunc main() {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\tfmt.Println(\"Error: could not determine your current directory: \", err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Setup usage arguments and options.\n\tcmdName := \"docker-unisync\"\n\tflag.Usage = func() {\n\t\tfmt.Printf(\"Example usage:\\n\\t%v [options] DOCKER-MACHINE-NAME...\", cmdName)\n\t\tfmt.Println(\"\\nOptions:\")\n\t\tflag.PrintDefaults()\n\t}\n\n\thelp := flag.Bool(\"help\", false, \"Show this message\")\n\tverbose := flag.Bool(\"verbose\", false, \"Verbose output\")\n\tshowVersion := flag.Bool(\"version\", false, \"Show version\")\n\n\tflag.Parse()\n\n\tif *showVersion {\n\t\tfmt.Printf(\"%v version %v, build %v\\n\", cmdName, Version, Build)\n\t\treturn\n\t}\n\n\tif *help {\n\t\tflag.Usage()\n\t\treturn\n\t}\n\n\tfmt.Println(*help)\n\tfmt.Println(*verbose)\n\tfmt.Println(\"Hello, yo!\")\n\tfmt.Println(pwd)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"cloud.google.com\/go\/profiler\"\n\t\"contrib.go.opencensus.io\/exporter\/stackdriver\"\n\t\"github.com\/metal-tile\/land\/dqn\"\n\t\"github.com\/metal-tile\/land\/firedb\"\n\t\"github.com\/sinmetal\/gcpmetadata\"\n\t\"go.opencensus.io\/trace\"\n)\n\nfunc main() {\n\tprojectID, err := gcpmetadata.GetProjectID()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := profiler.Start(profiler.Config{Service: \"land\", ServiceVersion: \"0.0.1\"}); err != nil {\n\t\tfmt.Printf(\"failed stackdriver.profiler.Start %+v\", err)\n\t}\n\texporter, err := stackdriver.NewExporter(stackdriver.Options{\n\t\tProjectID: projectID,\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttrace.RegisterExporter(exporter)\n\n\ths, err := os.Hostname()\n\tif err != nil {\n\t\tfmt.Printf(\"Fail os.Hostname. %s\\n\", err.Error())\n\t}\n\tfmt.Printf(\"Hostname is %s\\n\", hs)\n\tfmt.Println(\"\")\n\tfmt.Println(os.Environ())\n\n\tonlyFuncActivate := flag.String(\"onlyFuncActivate\", \"\", \"Activate only specified function\")\n\tflag.Parse()\n\tfmt.Printf(\"onlyFuncActivate is %s\\n\", *onlyFuncActivate)\n\n\tctx := context.Background()\n\tfiredb.SetUp(ctx, projectID)\n\n\tch := make(chan error)\n\n\tfieldStore := firedb.NewFieldStore()\n\tif *onlyFuncActivate == \"\" || *onlyFuncActivate == \"field\" {\n\t\tfmt.Println(\"Start WatchField\")\n\t\tgo func() {\n\t\t\tch <- fieldStore.Watch(ctx, \"world-default20170908-land-home\")\n\t\t}()\n\t}\n\n\tplayerStore := firedb.NewPlayerStore()\n\tif *onlyFuncActivate == \"\" || *onlyFuncActivate == \"playerPosition\" {\n\t\tfmt.Println(\"Start WatchPlayerPositions\")\n\t\tgo func() {\n\t\t\tch <- playerStore.Watch(ctx, \"world-default-player-position\")\n\t\t}()\n\t}\n\n\tif *onlyFuncActivate == \"\" || *onlyFuncActivate == \"monster\" {\n\t\tfmt.Println(\"Start Monster Control\")\n\t\tgo func() {\n\t\t\tc := &MonsterClient{\n\t\t\t\tDQN:         dqn.NewClient(),\n\t\t\t\tPlayerStore: playerStore,\n\t\t\t}\n\t\t\tch <- RunControlMonster(c)\n\t\t}()\n\t}\n\n\tif *onlyFuncActivate == \"\" || *onlyFuncActivate == \"watchPassivePlayer\" {\n\t\tfmt.Println(\"Start WatchPassivePlayer\")\n\t\tgo func() {\n\t\t\tch <- WatchPassivePlayer()\n\t\t}()\n\t}\n\n\t\/\/ Debug HTTP Handler\n\tgo func() {\n\t\thttp.HandleFunc(\"\/\", helthHandler)\n\t\thttp.HandleFunc(\"\/field\", fieldHandler)\n\t\thttp.HandleFunc(\"\/player\", playerHandler)\n\t\thttp.HandleFunc(\"\/healthz\", helthHandler)\n\t\thttp.ListenAndServe(\":8080\", nil)\n\t}()\n\n\terr = <-ch\n\tfmt.Printf(\"%+v\", err)\n}\n<commit_msg>エラーハンドリングしそこねていたのを修正<commit_after>package main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"cloud.google.com\/go\/profiler\"\n\t\"contrib.go.opencensus.io\/exporter\/stackdriver\"\n\t\"github.com\/metal-tile\/land\/dqn\"\n\t\"github.com\/metal-tile\/land\/firedb\"\n\t\"github.com\/sinmetal\/gcpmetadata\"\n\t\"go.opencensus.io\/trace\"\n)\n\nfunc main() {\n\tprojectID, err := gcpmetadata.GetProjectID()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := profiler.Start(profiler.Config{Service: \"land\", ServiceVersion: \"0.0.1\"}); err != nil {\n\t\tfmt.Printf(\"failed stackdriver.profiler.Start %+v\", err)\n\t}\n\texporter, err := stackdriver.NewExporter(stackdriver.Options{\n\t\tProjectID: projectID,\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttrace.RegisterExporter(exporter)\n\n\ths, err := os.Hostname()\n\tif err != nil {\n\t\tfmt.Printf(\"Fail os.Hostname. %s\\n\", err.Error())\n\t}\n\tfmt.Printf(\"Hostname is %s\\n\", hs)\n\tfmt.Println(\"\")\n\tfmt.Println(os.Environ())\n\n\tonlyFuncActivate := flag.String(\"onlyFuncActivate\", \"\", \"Activate only specified function\")\n\tflag.Parse()\n\tfmt.Printf(\"onlyFuncActivate is %s\\n\", *onlyFuncActivate)\n\n\tctx := context.Background()\n\tif err := firedb.SetUp(ctx, projectID); err != nil {\n\t\tpanic(err)\n\t}\n\n\tch := make(chan error)\n\n\tfieldStore := firedb.NewFieldStore()\n\tif *onlyFuncActivate == \"\" || *onlyFuncActivate == \"field\" {\n\t\tfmt.Println(\"Start WatchField\")\n\t\tgo func() {\n\t\t\tch <- fieldStore.Watch(ctx, \"world-default20170908-land-home\")\n\t\t}()\n\t}\n\n\tplayerStore := firedb.NewPlayerStore()\n\tif *onlyFuncActivate == \"\" || *onlyFuncActivate == \"playerPosition\" {\n\t\tfmt.Println(\"Start WatchPlayerPositions\")\n\t\tgo func() {\n\t\t\tch <- playerStore.Watch(ctx, \"world-default-player-position\")\n\t\t}()\n\t}\n\n\tif *onlyFuncActivate == \"\" || *onlyFuncActivate == \"monster\" {\n\t\tfmt.Println(\"Start Monster Control\")\n\t\tgo func() {\n\t\t\tc := &MonsterClient{\n\t\t\t\tDQN:         dqn.NewClient(),\n\t\t\t\tPlayerStore: playerStore,\n\t\t\t}\n\t\t\tch <- RunControlMonster(c)\n\t\t}()\n\t}\n\n\tif *onlyFuncActivate == \"\" || *onlyFuncActivate == \"watchPassivePlayer\" {\n\t\tfmt.Println(\"Start WatchPassivePlayer\")\n\t\tgo func() {\n\t\t\tch <- WatchPassivePlayer()\n\t\t}()\n\t}\n\n\t\/\/ Debug HTTP Handler\n\tgo func() {\n\t\thttp.HandleFunc(\"\/\", helthHandler)\n\t\thttp.HandleFunc(\"\/field\", fieldHandler)\n\t\thttp.HandleFunc(\"\/player\", playerHandler)\n\t\thttp.HandleFunc(\"\/healthz\", helthHandler)\n\t\tif err := http.ListenAndServe(\":8080\", nil); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\terr = <-ch\n\tfmt.Printf(\"%+v\", err)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nfunc main() {\n}\n<commit_msg>Added http<commit_after>package main\n\nimport (\n\t\"os\"\n\t\"net\/http\"\n\t\"log\"\n\t\"fmt\"\n)\n\nfunc getEnv(key string, defVal string) (env string) {\n\tenv = os.Getenv(key)\n\n\tif env == \"\" {\n\t\tenv = defVal\n\t}\n\treturn\n}\n\n\nfunc main() {\n\thost := getEnv(\"HOST\", \"\")\n\tport := getEnv(\"PORT\", \"8080\")\n\twsPort := getEnv(\"WSPORT\", \"8080\")\n\/\/\tmongoURL := getEnv(\"MONGOHQ_URL\", \"localhost\")\n\n\tbind := fmt.Sprintf(\"%s:%s\", host, port)\n\tlog.Println(\"Starting server on\", bind, \"with websocket on port\", wsPort)\n\n\terr := http.ListenAndServe(bind, nil)\n\tif err != nil {\n\t\tlog.Fatal(\"ListenAndServe: \", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/ingrammicro\/concerto\/admin\"\n\t\"github.com\/ingrammicro\/concerto\/audit\"\n\t\"github.com\/ingrammicro\/concerto\/blueprint\/scripts\"\n\t\"github.com\/ingrammicro\/concerto\/blueprint\/services\"\n\t\"github.com\/ingrammicro\/concerto\/blueprint\/templates\"\n\t\"github.com\/ingrammicro\/concerto\/brownfield\"\n\tcl_prov \"github.com\/ingrammicro\/concerto\/cloud\/cloud_providers\"\n\t\"github.com\/ingrammicro\/concerto\/cloud\/generic_images\"\n\t\"github.com\/ingrammicro\/concerto\/cloud\/saas_providers\"\n\t\"github.com\/ingrammicro\/concerto\/cloud\/server_plan\"\n\t\"github.com\/ingrammicro\/concerto\/cloud\/servers\"\n\t\"github.com\/ingrammicro\/concerto\/cloud\/ssh_profiles\"\n\t\"github.com\/ingrammicro\/concerto\/cloud\/workspaces\"\n\t\"github.com\/ingrammicro\/concerto\/cluster\"\n\t\"github.com\/ingrammicro\/concerto\/cmdpolling\"\n\t\"github.com\/ingrammicro\/concerto\/converge\"\n\t\"github.com\/ingrammicro\/concerto\/dispatcher\"\n\t\"github.com\/ingrammicro\/concerto\/dns\"\n\t\"github.com\/ingrammicro\/concerto\/firewall\"\n\t\"github.com\/ingrammicro\/concerto\/licensee\"\n\t\"github.com\/ingrammicro\/concerto\/network\/firewall_profiles\"\n\t\"github.com\/ingrammicro\/concerto\/network\/load_balancers\"\n\t\"github.com\/ingrammicro\/concerto\/node\"\n\t\"github.com\/ingrammicro\/concerto\/settings\/cloud_accounts\"\n\t\"github.com\/ingrammicro\/concerto\/settings\/reports\"\n\t\"github.com\/ingrammicro\/concerto\/settings\/saas_accounts\"\n\t\"github.com\/ingrammicro\/concerto\/setup\"\n\t\"github.com\/ingrammicro\/concerto\/utils\"\n\t\"github.com\/ingrammicro\/concerto\/utils\/format\"\n\t\"github.com\/ingrammicro\/concerto\/wizard\/apps\"\n\t\"github.com\/ingrammicro\/concerto\/wizard\/cloud_providers\"\n\t\"github.com\/ingrammicro\/concerto\/wizard\/locations\"\n\t\"github.com\/ingrammicro\/concerto\/wizard\/server_plans\"\n)\n\nvar ServerCommands = []cli.Command{\n\t{\n\t\tName:  \"firewall\",\n\t\tUsage: \"Manages Firewall Policies within a Host\",\n\t\tSubcommands: append(\n\t\t\tfirewall.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"scripts\",\n\t\tUsage: \"Manages Execution Scripts within a Host\",\n\t\tSubcommands: append(\n\t\t\tdispatcher.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:   \"converge\",\n\t\tUsage:  \"Converges Host to original Blueprint\",\n\t\tAction: converge.CmbConverge,\n\t},\n\t{\n\t\tName:  \"brownfield\",\n\t\tUsage: \"Manages registration and configuration within an imported brownfield Host\",\n\t\tSubcommands: append(\n\t\t\tbrownfield.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"polling\",\n\t\tUsage: \"Manages polling commands\",\n\t\tSubcommands: append(\n\t\t\tcmdpolling.SubCommands(),\n\t\t),\n\t},\n}\n\nvar BlueprintCommands = []cli.Command{\n\t{\n\t\tName:  \"scripts\",\n\t\tUsage: \"Allow the user to manage the scripts they want to run on the servers\",\n\t\tSubcommands: append(\n\t\t\tscripts.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"services\",\n\t\tUsage: \"Provides information on services\",\n\t\tSubcommands: append(\n\t\t\tservices.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"templates\",\n\t\tUsage: \"Provides information on templates\",\n\t\tSubcommands: append(\n\t\t\ttemplates.SubCommands(),\n\t\t),\n\t},\n}\n\nvar CloudCommands = []cli.Command{\n\t{\n\t\tName:  \"workspaces\",\n\t\tUsage: \"Provides information on workspaces\",\n\t\tSubcommands: append(\n\t\t\tworkspaces.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"servers\",\n\t\tUsage: \"Provides information on servers\",\n\t\tSubcommands: append(\n\t\t\tservers.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"generic_images\",\n\t\tUsage: \"Provides information on generic images\",\n\t\tSubcommands: append(\n\t\t\tgeneric_images.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"ssh_profiles\",\n\t\tUsage: \"Provides information on SSH profiles\",\n\t\tSubcommands: append(\n\t\t\tssh_profiles.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"cloud_providers\",\n\t\tUsage: \"Provides information on cloud providers\",\n\t\tSubcommands: append(\n\t\t\tcl_prov.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"server_plans\",\n\t\tUsage: \"Provides information on server plans\",\n\t\tSubcommands: append(\n\t\t\tserver_plan.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"saas_providers\",\n\t\tUsage: \"Provides information about SAAS providers\",\n\t\tSubcommands: append(\n\t\t\tsaas_providers.SubCommands(),\n\t\t),\n\t},\n}\n\nvar NetCommands = []cli.Command{\n\t{\n\t\tName:  \"firewall_profiles\",\n\t\tUsage: \"Provides information about firewall profiles\",\n\t\tSubcommands: append(\n\t\t\tfirewall_profiles.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"load_balancers\",\n\t\tUsage: \"Provides information about load balancers\",\n\t\tSubcommands: append(\n\t\t\tload_balancers.SubCommands(),\n\t\t),\n\t},\n}\n\nvar SettingsCommands = []cli.Command{\n\t{\n\t\tName:  \"cloud_accounts\",\n\t\tUsage: \"Provides information about cloud accounts\",\n\t\tSubcommands: append(\n\t\t\tcloud_accounts.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"reports\",\n\t\tUsage: \"Provides information about reports\",\n\t\tSubcommands: append(\n\t\t\treports.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"saas_accounts\",\n\t\tUsage: \"Provides information about SaaS accounts\",\n\t\tSubcommands: append(\n\t\t\tsaas_accounts.SubCommands(),\n\t\t),\n\t},\n}\n\nvar WizardCommands = []cli.Command{\n\t{\n\t\tName:  \"apps\",\n\t\tUsage: \"Provides information about apps\",\n\t\tSubcommands: append(\n\t\t\tapps.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"cloud_providers\",\n\t\tUsage: \"Provides information about cloud providers\",\n\t\tSubcommands: append(\n\t\t\tcloud_providers.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"locations\",\n\t\tUsage: \"Provides information about locations\",\n\t\tSubcommands: append(\n\t\t\tlocations.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"server_plans\",\n\t\tUsage: \"Provides information about server plans\",\n\t\tSubcommands: append(\n\t\t\tserver_plans.SubCommands(),\n\t\t),\n\t},\n}\n\nvar ClientCommands = []cli.Command{\n\t{\n\t\tName:      \"setup\",\n\t\tShortName: \"se\",\n\t\tUsage:     \"Configures and setups concerto cli enviroment\",\n\t\tSubcommands: append(\n\t\t\tsetup.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:      \"nodes\",\n\t\tShortName: \"no\",\n\t\tUsage:     \"Manages Docker Nodes\",\n\t\tSubcommands: append(\n\t\t\tnode.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:      \"cluster\",\n\t\tShortName: \"clu\",\n\t\tUsage:     \"Manages a Kubernetes Cluster\",\n\t\tSubcommands: append(\n\t\t\tcluster.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:      \"reports\",\n\t\tShortName: \"rep\",\n\t\tUsage:     \"Provides historical uptime of servers\",\n\t\tSubcommands: append(\n\t\t\tadmin.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:      \"events\",\n\t\tShortName: \"ev\",\n\t\tUsage:     \"Events allow the user to track their actions and the state of their servers\",\n\t\tSubcommands: append(\n\t\t\taudit.SubCommands(),\n\t\t),\n\t},\n\n\t{\n\t\tName:      \"blueprint\",\n\t\tShortName: \"bl\",\n\t\tUsage:     \"Manages blueprint commands for scripts, services and templates\",\n\t\tSubcommands: append(\n\t\t\tBlueprintCommands,\n\t\t),\n\t},\n\t{\n\t\tName:      \"cloud\",\n\t\tShortName: \"clo\",\n\t\tUsage:     \"Manages cloud related commands for workspaces, servers, generic images, ssh profiles, cloud providers, server plans and Saas providers\",\n\t\tSubcommands: append(\n\t\t\tCloudCommands,\n\t\t),\n\t},\n\t{\n\t\tName:      \"dns_domains\",\n\t\tShortName: \"dns\",\n\t\tUsage:     \"Provides information about DNS records\",\n\t\tSubcommands: append(\n\t\t\tdns.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:      \"licensee_reports\",\n\t\tShortName: \"lic\",\n\t\tUsage:     \"Provides information about licensee reports\",\n\t\tSubcommands: append(\n\t\t\tlicensee.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:      \"network\",\n\t\tShortName: \"net\",\n\t\tUsage:     \"Manages network related commands for firewall profiles and load balancers\",\n\t\tSubcommands: append(\n\t\t\tNetCommands,\n\t\t),\n\t},\n\t{\n\t\tName:      \"settings\",\n\t\tShortName: \"set\",\n\t\tUsage:     \"Provides settings for cloud and Saas accounts as well as reports\",\n\t\tSubcommands: append(\n\t\t\tSettingsCommands,\n\t\t),\n\t},\n\t{\n\t\tName:      \"wizard\",\n\t\tShortName: \"wiz\",\n\t\tUsage:     \"Manages wizard related commands for apps, locations, cloud providers, server plans\",\n\t\tSubcommands: append(\n\t\t\tWizardCommands,\n\t\t),\n\t},\n}\n\nfunc cmdNotFound(c *cli.Context, command string) {\n\tlog.Fatalf(\n\t\t\"%s: '%s' is not a %s command. See '%s --help'.\",\n\t\tc.App.Name,\n\t\tcommand,\n\t\tc.App.Name,\n\t\tc.App.Name,\n\t)\n}\n\nfunc prepareFlags(c *cli.Context) error {\n\n\tif c.Bool(\"debug\") {\n\t\tos.Setenv(\"DEBUG\", \"1\")\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\n\t\/\/ try to read configuration\n\tconfig, err := utils.InitializeConcertoConfig(c)\n\tif err != nil {\n\t\tlog.Errorf(\"Error reading Concerto configuration: %s\", err)\n\t\treturn err\n\t}\n\n\t\/\/ validate formatter\n\tif c.String(\"formatter\") != \"text\" && c.String(\"formatter\") != \"json\" {\n\t\tlog.Errorf(\"Unrecognized formatter %s. Please, use one of [ text | json ]\", c.String(\"formatter\"))\n\t\treturn fmt.Errorf(\"Unrecognized formatter %s. Please, use one of [ text | json ]\", c.String(\"formatter\"))\n\t}\n\tformat.InitializeFormatter(c.String(\"formatter\"), os.Stdout)\n\n\tif config.IsHost || config.BrownfieldToken != \"\" || (config.CommandPollingToken != \"\" && config.ServerID != \"\") {\n\t\tlog.Debug(\"Setting server commands to concerto\")\n\t\tc.App.Commands = ServerCommands\n\t} else {\n\t\tlog.Debug(\"Setting client commands to concerto\")\n\t\tc.App.Commands = ClientCommands\n\t}\n\n\t\/\/ hack: substitute commands in category ... we should evaluate cobra\/viper\n\tcat := c.App.Categories()\n\n\tfor _, category := range cat {\n\t\tcategory.Commands = category.Commands[:0]\n\t}\n\n\tfor _, command := range c.App.Commands {\n\t\tcat = cat.AddCommand(command.Category, command)\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\n\tapp := cli.NewApp()\n\tapp.Name = \"concerto\"\n\tapp.Author = \"Concerto Contributors\"\n\tapp.Email = \"https:\/\/github.com\/ingrammicro\/concerto\"\n\n\tapp.CommandNotFound = cmdNotFound\n\tapp.Usage = \"Manages comunication between Host and Concerto Platform\"\n\tapp.Version = utils.VERSION\n\n\tapp.Before = prepareFlags\n\n\t\/\/ set client commands by default to populate categories\n\tapp.Commands = ClientCommands\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName:  \"debug, D\",\n\t\t\tUsage: \"Enable debug mode\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_CA_CERT\",\n\t\t\tName:   \"ca-cert\",\n\t\t\tUsage:  \"CA to verify remote connections\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_CLIENT_CERT\",\n\t\t\tName:   \"client-cert\",\n\t\t\tUsage:  \"Client cert to use for Concerto\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_CLIENT_KEY\",\n\t\t\tName:   \"client-key\",\n\t\t\tUsage:  \"Private key used in client Concerto auth\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_CONFIG\",\n\t\t\tName:   \"concerto-config\",\n\t\t\tUsage:  \"Concerto Config File\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_ENDPOINT\",\n\t\t\tName:   \"concerto-endpoint\",\n\t\t\tUsage:  \"Concerto Endpoint\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_URL\",\n\t\t\tName:   \"concerto-url\",\n\t\t\tUsage:  \"Concerto Web URL\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_BROWNFIELD_TOKEN\",\n\t\t\tName:   \"concerto-brownfield-token\",\n\t\t\tUsage:  \"Concerto Brownfield Token\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_COMMAND_POLLING_TOKEN\",\n\t\t\tName:   \"concerto-command-polling-token\",\n\t\t\tUsage:  \"Concerto Command Polling Token\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_SERVER_ID\",\n\t\t\tName:   \"concerto-server-id\",\n\t\t\tUsage:  \"Concerto Server ID\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_FORMATTER\",\n\t\t\tName:   \"formatter\",\n\t\t\tUsage:  \"Output formatter [ text | json ] \",\n\t\t\tValue:  \"text\",\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n\n}\n<commit_msg>Exclude ServerId as requirement for detection as an agent<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/ingrammicro\/concerto\/admin\"\n\t\"github.com\/ingrammicro\/concerto\/audit\"\n\t\"github.com\/ingrammicro\/concerto\/blueprint\/scripts\"\n\t\"github.com\/ingrammicro\/concerto\/blueprint\/services\"\n\t\"github.com\/ingrammicro\/concerto\/blueprint\/templates\"\n\t\"github.com\/ingrammicro\/concerto\/brownfield\"\n\tcl_prov \"github.com\/ingrammicro\/concerto\/cloud\/cloud_providers\"\n\t\"github.com\/ingrammicro\/concerto\/cloud\/generic_images\"\n\t\"github.com\/ingrammicro\/concerto\/cloud\/saas_providers\"\n\t\"github.com\/ingrammicro\/concerto\/cloud\/server_plan\"\n\t\"github.com\/ingrammicro\/concerto\/cloud\/servers\"\n\t\"github.com\/ingrammicro\/concerto\/cloud\/ssh_profiles\"\n\t\"github.com\/ingrammicro\/concerto\/cloud\/workspaces\"\n\t\"github.com\/ingrammicro\/concerto\/cluster\"\n\t\"github.com\/ingrammicro\/concerto\/cmdpolling\"\n\t\"github.com\/ingrammicro\/concerto\/converge\"\n\t\"github.com\/ingrammicro\/concerto\/dispatcher\"\n\t\"github.com\/ingrammicro\/concerto\/dns\"\n\t\"github.com\/ingrammicro\/concerto\/firewall\"\n\t\"github.com\/ingrammicro\/concerto\/licensee\"\n\t\"github.com\/ingrammicro\/concerto\/network\/firewall_profiles\"\n\t\"github.com\/ingrammicro\/concerto\/network\/load_balancers\"\n\t\"github.com\/ingrammicro\/concerto\/node\"\n\t\"github.com\/ingrammicro\/concerto\/settings\/cloud_accounts\"\n\t\"github.com\/ingrammicro\/concerto\/settings\/reports\"\n\t\"github.com\/ingrammicro\/concerto\/settings\/saas_accounts\"\n\t\"github.com\/ingrammicro\/concerto\/setup\"\n\t\"github.com\/ingrammicro\/concerto\/utils\"\n\t\"github.com\/ingrammicro\/concerto\/utils\/format\"\n\t\"github.com\/ingrammicro\/concerto\/wizard\/apps\"\n\t\"github.com\/ingrammicro\/concerto\/wizard\/cloud_providers\"\n\t\"github.com\/ingrammicro\/concerto\/wizard\/locations\"\n\t\"github.com\/ingrammicro\/concerto\/wizard\/server_plans\"\n)\n\nvar ServerCommands = []cli.Command{\n\t{\n\t\tName:  \"firewall\",\n\t\tUsage: \"Manages Firewall Policies within a Host\",\n\t\tSubcommands: append(\n\t\t\tfirewall.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"scripts\",\n\t\tUsage: \"Manages Execution Scripts within a Host\",\n\t\tSubcommands: append(\n\t\t\tdispatcher.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:   \"converge\",\n\t\tUsage:  \"Converges Host to original Blueprint\",\n\t\tAction: converge.CmbConverge,\n\t},\n\t{\n\t\tName:  \"brownfield\",\n\t\tUsage: \"Manages registration and configuration within an imported brownfield Host\",\n\t\tSubcommands: append(\n\t\t\tbrownfield.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"polling\",\n\t\tUsage: \"Manages polling commands\",\n\t\tSubcommands: append(\n\t\t\tcmdpolling.SubCommands(),\n\t\t),\n\t},\n}\n\nvar BlueprintCommands = []cli.Command{\n\t{\n\t\tName:  \"scripts\",\n\t\tUsage: \"Allow the user to manage the scripts they want to run on the servers\",\n\t\tSubcommands: append(\n\t\t\tscripts.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"services\",\n\t\tUsage: \"Provides information on services\",\n\t\tSubcommands: append(\n\t\t\tservices.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"templates\",\n\t\tUsage: \"Provides information on templates\",\n\t\tSubcommands: append(\n\t\t\ttemplates.SubCommands(),\n\t\t),\n\t},\n}\n\nvar CloudCommands = []cli.Command{\n\t{\n\t\tName:  \"workspaces\",\n\t\tUsage: \"Provides information on workspaces\",\n\t\tSubcommands: append(\n\t\t\tworkspaces.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"servers\",\n\t\tUsage: \"Provides information on servers\",\n\t\tSubcommands: append(\n\t\t\tservers.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"generic_images\",\n\t\tUsage: \"Provides information on generic images\",\n\t\tSubcommands: append(\n\t\t\tgeneric_images.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"ssh_profiles\",\n\t\tUsage: \"Provides information on SSH profiles\",\n\t\tSubcommands: append(\n\t\t\tssh_profiles.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"cloud_providers\",\n\t\tUsage: \"Provides information on cloud providers\",\n\t\tSubcommands: append(\n\t\t\tcl_prov.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"server_plans\",\n\t\tUsage: \"Provides information on server plans\",\n\t\tSubcommands: append(\n\t\t\tserver_plan.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"saas_providers\",\n\t\tUsage: \"Provides information about SAAS providers\",\n\t\tSubcommands: append(\n\t\t\tsaas_providers.SubCommands(),\n\t\t),\n\t},\n}\n\nvar NetCommands = []cli.Command{\n\t{\n\t\tName:  \"firewall_profiles\",\n\t\tUsage: \"Provides information about firewall profiles\",\n\t\tSubcommands: append(\n\t\t\tfirewall_profiles.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"load_balancers\",\n\t\tUsage: \"Provides information about load balancers\",\n\t\tSubcommands: append(\n\t\t\tload_balancers.SubCommands(),\n\t\t),\n\t},\n}\n\nvar SettingsCommands = []cli.Command{\n\t{\n\t\tName:  \"cloud_accounts\",\n\t\tUsage: \"Provides information about cloud accounts\",\n\t\tSubcommands: append(\n\t\t\tcloud_accounts.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"reports\",\n\t\tUsage: \"Provides information about reports\",\n\t\tSubcommands: append(\n\t\t\treports.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"saas_accounts\",\n\t\tUsage: \"Provides information about SaaS accounts\",\n\t\tSubcommands: append(\n\t\t\tsaas_accounts.SubCommands(),\n\t\t),\n\t},\n}\n\nvar WizardCommands = []cli.Command{\n\t{\n\t\tName:  \"apps\",\n\t\tUsage: \"Provides information about apps\",\n\t\tSubcommands: append(\n\t\t\tapps.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"cloud_providers\",\n\t\tUsage: \"Provides information about cloud providers\",\n\t\tSubcommands: append(\n\t\t\tcloud_providers.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"locations\",\n\t\tUsage: \"Provides information about locations\",\n\t\tSubcommands: append(\n\t\t\tlocations.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:  \"server_plans\",\n\t\tUsage: \"Provides information about server plans\",\n\t\tSubcommands: append(\n\t\t\tserver_plans.SubCommands(),\n\t\t),\n\t},\n}\n\nvar ClientCommands = []cli.Command{\n\t{\n\t\tName:      \"setup\",\n\t\tShortName: \"se\",\n\t\tUsage:     \"Configures and setups concerto cli enviroment\",\n\t\tSubcommands: append(\n\t\t\tsetup.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:      \"nodes\",\n\t\tShortName: \"no\",\n\t\tUsage:     \"Manages Docker Nodes\",\n\t\tSubcommands: append(\n\t\t\tnode.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:      \"cluster\",\n\t\tShortName: \"clu\",\n\t\tUsage:     \"Manages a Kubernetes Cluster\",\n\t\tSubcommands: append(\n\t\t\tcluster.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:      \"reports\",\n\t\tShortName: \"rep\",\n\t\tUsage:     \"Provides historical uptime of servers\",\n\t\tSubcommands: append(\n\t\t\tadmin.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:      \"events\",\n\t\tShortName: \"ev\",\n\t\tUsage:     \"Events allow the user to track their actions and the state of their servers\",\n\t\tSubcommands: append(\n\t\t\taudit.SubCommands(),\n\t\t),\n\t},\n\n\t{\n\t\tName:      \"blueprint\",\n\t\tShortName: \"bl\",\n\t\tUsage:     \"Manages blueprint commands for scripts, services and templates\",\n\t\tSubcommands: append(\n\t\t\tBlueprintCommands,\n\t\t),\n\t},\n\t{\n\t\tName:      \"cloud\",\n\t\tShortName: \"clo\",\n\t\tUsage:     \"Manages cloud related commands for workspaces, servers, generic images, ssh profiles, cloud providers, server plans and Saas providers\",\n\t\tSubcommands: append(\n\t\t\tCloudCommands,\n\t\t),\n\t},\n\t{\n\t\tName:      \"dns_domains\",\n\t\tShortName: \"dns\",\n\t\tUsage:     \"Provides information about DNS records\",\n\t\tSubcommands: append(\n\t\t\tdns.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:      \"licensee_reports\",\n\t\tShortName: \"lic\",\n\t\tUsage:     \"Provides information about licensee reports\",\n\t\tSubcommands: append(\n\t\t\tlicensee.SubCommands(),\n\t\t),\n\t},\n\t{\n\t\tName:      \"network\",\n\t\tShortName: \"net\",\n\t\tUsage:     \"Manages network related commands for firewall profiles and load balancers\",\n\t\tSubcommands: append(\n\t\t\tNetCommands,\n\t\t),\n\t},\n\t{\n\t\tName:      \"settings\",\n\t\tShortName: \"set\",\n\t\tUsage:     \"Provides settings for cloud and Saas accounts as well as reports\",\n\t\tSubcommands: append(\n\t\t\tSettingsCommands,\n\t\t),\n\t},\n\t{\n\t\tName:      \"wizard\",\n\t\tShortName: \"wiz\",\n\t\tUsage:     \"Manages wizard related commands for apps, locations, cloud providers, server plans\",\n\t\tSubcommands: append(\n\t\t\tWizardCommands,\n\t\t),\n\t},\n}\n\nfunc cmdNotFound(c *cli.Context, command string) {\n\tlog.Fatalf(\n\t\t\"%s: '%s' is not a %s command. See '%s --help'.\",\n\t\tc.App.Name,\n\t\tcommand,\n\t\tc.App.Name,\n\t\tc.App.Name,\n\t)\n}\n\nfunc prepareFlags(c *cli.Context) error {\n\n\tif c.Bool(\"debug\") {\n\t\tos.Setenv(\"DEBUG\", \"1\")\n\t\tlog.SetOutput(os.Stderr)\n\t\tlog.SetLevel(log.DebugLevel)\n\t}\n\n\t\/\/ try to read configuration\n\tconfig, err := utils.InitializeConcertoConfig(c)\n\tif err != nil {\n\t\tlog.Errorf(\"Error reading Concerto configuration: %s\", err)\n\t\treturn err\n\t}\n\n\t\/\/ validate formatter\n\tif c.String(\"formatter\") != \"text\" && c.String(\"formatter\") != \"json\" {\n\t\tlog.Errorf(\"Unrecognized formatter %s. Please, use one of [ text | json ]\", c.String(\"formatter\"))\n\t\treturn fmt.Errorf(\"Unrecognized formatter %s. Please, use one of [ text | json ]\", c.String(\"formatter\"))\n\t}\n\tformat.InitializeFormatter(c.String(\"formatter\"), os.Stdout)\n\n\tif config.IsHost || config.BrownfieldToken != \"\" || config.CommandPollingToken != \"\" {\n\t\tlog.Debug(\"Setting server commands to concerto\")\n\t\tc.App.Commands = ServerCommands\n\t} else {\n\t\tlog.Debug(\"Setting client commands to concerto\")\n\t\tc.App.Commands = ClientCommands\n\t}\n\n\t\/\/ hack: substitute commands in category ... we should evaluate cobra\/viper\n\tcat := c.App.Categories()\n\n\tfor _, category := range cat {\n\t\tcategory.Commands = category.Commands[:0]\n\t}\n\n\tfor _, command := range c.App.Commands {\n\t\tcat = cat.AddCommand(command.Category, command)\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\n\tapp := cli.NewApp()\n\tapp.Name = \"concerto\"\n\tapp.Author = \"Concerto Contributors\"\n\tapp.Email = \"https:\/\/github.com\/ingrammicro\/concerto\"\n\n\tapp.CommandNotFound = cmdNotFound\n\tapp.Usage = \"Manages comunication between Host and Concerto Platform\"\n\tapp.Version = utils.VERSION\n\n\tapp.Before = prepareFlags\n\n\t\/\/ set client commands by default to populate categories\n\tapp.Commands = ClientCommands\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName:  \"debug, D\",\n\t\t\tUsage: \"Enable debug mode\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_CA_CERT\",\n\t\t\tName:   \"ca-cert\",\n\t\t\tUsage:  \"CA to verify remote connections\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_CLIENT_CERT\",\n\t\t\tName:   \"client-cert\",\n\t\t\tUsage:  \"Client cert to use for Concerto\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_CLIENT_KEY\",\n\t\t\tName:   \"client-key\",\n\t\t\tUsage:  \"Private key used in client Concerto auth\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_CONFIG\",\n\t\t\tName:   \"concerto-config\",\n\t\t\tUsage:  \"Concerto Config File\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_ENDPOINT\",\n\t\t\tName:   \"concerto-endpoint\",\n\t\t\tUsage:  \"Concerto Endpoint\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_URL\",\n\t\t\tName:   \"concerto-url\",\n\t\t\tUsage:  \"Concerto Web URL\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_BROWNFIELD_TOKEN\",\n\t\t\tName:   \"concerto-brownfield-token\",\n\t\t\tUsage:  \"Concerto Brownfield Token\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_COMMAND_POLLING_TOKEN\",\n\t\t\tName:   \"concerto-command-polling-token\",\n\t\t\tUsage:  \"Concerto Command Polling Token\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_SERVER_ID\",\n\t\t\tName:   \"concerto-server-id\",\n\t\t\tUsage:  \"Concerto Server ID\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tEnvVar: \"CONCERTO_FORMATTER\",\n\t\t\tName:   \"formatter\",\n\t\t\tUsage:  \"Output formatter [ text | json ] \",\n\t\t\tValue:  \"text\",\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\tflags \"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/monochromegane\/terminal\"\n\t\"github.com\/monochromegane\/the_platinum_searcher\/search\"\n\t\"github.com\/monochromegane\/the_platinum_searcher\/search\/option\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nconst version = \"1.5.1\"\n\nvar opts option.Option\n\nfunc init() {\n\tif cpu := runtime.NumCPU(); cpu == 1 {\n\t\truntime.GOMAXPROCS(2)\n\t} else {\n\t\truntime.GOMAXPROCS(cpu)\n\t}\n}\n\nfunc main() {\n\n\topts.Color = opts.SetEnableColor\n\topts.NoColor = opts.SetDisableColor\n\tif runtime.GOOS == \"windows\" && os.Getenv(\"ANSICON\") == \"\" {\n\t\topts.EnableColor = false\n\t} else {\n\t\topts.EnableColor = true\n\t}\n\n\tparser := flags.NewParser(&opts, flags.Default)\n\tparser.Name = \"pt\"\n\tparser.Usage = \"[OPTIONS] PATTERN [PATH]\"\n\n\targs, err := parser.Parse()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tif opts.Version {\n\t\tfmt.Printf(\"%s\\n\", version)\n\t\tos.Exit(0)\n\t}\n\n\tif len(args) == 0 && opts.FilesWithRegexp == \"\" {\n\t\tparser.WriteHelp(os.Stdout)\n\t\tos.Exit(1)\n\t}\n\n\topts.SearchStream = false\n\tif len(args) == 1 {\n\t\tif !terminal.IsTerminal(os.Stdin) {\n\t\t\topts.SearchStream = true\n\t\t\topts.NoGroup = true\n\t\t}\n\t}\n\n\tvar root = \".\"\n\tif len(args) == 2 {\n\t\troot = strings.TrimRight(args[1], \"\\\"\")\n\t\t_, err := os.Lstat(root)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\topts.Proc = runtime.NumCPU()\n\n\tif !terminal.IsTerminal(os.Stdout) {\n\t\topts.EnableColor = false\n\t\topts.NoGroup = true\n\t}\n\n\tif opts.Context > 0 {\n\t\topts.Before = opts.Context\n\t\topts.After = opts.Context\n\t}\n\n\tpattern := \"\"\n\tif len(args) > 0 {\n\t\tpattern = args[0]\n\t}\n\tsearcher := search.Searcher{root, pattern, &opts}\n\terr = searcher.Search()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n<commit_msg>Bumped version to 1.5.2.<commit_after>package main\n\nimport (\n\t\"fmt\"\n\tflags \"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/monochromegane\/terminal\"\n\t\"github.com\/monochromegane\/the_platinum_searcher\/search\"\n\t\"github.com\/monochromegane\/the_platinum_searcher\/search\/option\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nconst version = \"1.5.2\"\n\nvar opts option.Option\n\nfunc init() {\n\tif cpu := runtime.NumCPU(); cpu == 1 {\n\t\truntime.GOMAXPROCS(2)\n\t} else {\n\t\truntime.GOMAXPROCS(cpu)\n\t}\n}\n\nfunc main() {\n\n\topts.Color = opts.SetEnableColor\n\topts.NoColor = opts.SetDisableColor\n\tif runtime.GOOS == \"windows\" && os.Getenv(\"ANSICON\") == \"\" {\n\t\topts.EnableColor = false\n\t} else {\n\t\topts.EnableColor = true\n\t}\n\n\tparser := flags.NewParser(&opts, flags.Default)\n\tparser.Name = \"pt\"\n\tparser.Usage = \"[OPTIONS] PATTERN [PATH]\"\n\n\targs, err := parser.Parse()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tif opts.Version {\n\t\tfmt.Printf(\"%s\\n\", version)\n\t\tos.Exit(0)\n\t}\n\n\tif len(args) == 0 && opts.FilesWithRegexp == \"\" {\n\t\tparser.WriteHelp(os.Stdout)\n\t\tos.Exit(1)\n\t}\n\n\topts.SearchStream = false\n\tif len(args) == 1 {\n\t\tif !terminal.IsTerminal(os.Stdin) {\n\t\t\topts.SearchStream = true\n\t\t\topts.NoGroup = true\n\t\t}\n\t}\n\n\tvar root = \".\"\n\tif len(args) == 2 {\n\t\troot = strings.TrimRight(args[1], \"\\\"\")\n\t\t_, err := os.Lstat(root)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\n\topts.Proc = runtime.NumCPU()\n\n\tif !terminal.IsTerminal(os.Stdout) {\n\t\topts.EnableColor = false\n\t\topts.NoGroup = true\n\t}\n\n\tif opts.Context > 0 {\n\t\topts.Before = opts.Context\n\t\topts.After = opts.Context\n\t}\n\n\tpattern := \"\"\n\tif len(args) > 0 {\n\t\tpattern = args[0]\n\t}\n\tsearcher := search.Searcher{root, pattern, &opts}\n\terr = searcher.Search()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/cloudfoundry-community\/firehose-to-syslog\/caching\"\n\t\"github.com\/cloudfoundry-community\/firehose-to-syslog\/events\"\n\t\"github.com\/cloudfoundry-community\/firehose-to-syslog\/extrafields\"\n\t\"github.com\/cloudfoundry-community\/firehose-to-syslog\/firehose\"\n\t\"github.com\/cloudfoundry-community\/firehose-to-syslog\/logging\"\n\t\"github.com\/cloudfoundry-community\/go-cfclient\"\n\t\"github.com\/pkg\/profile\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"log\"\n\t\"os\"\n\t\"time\"\n)\n\nvar (\n\tdebug              = kingpin.Flag(\"debug\", \"Enable debug mode. This disables forwarding to syslog\").Default(\"false\").OverrideDefaultFromEnvar(\"DEBUG\").Bool()\n\tapiEndpoint        = kingpin.Flag(\"api-endpoint\", \"Api endpoint address. For bosh-lite installation of CF: https:\/\/api.10.244.0.34.xip.io\").OverrideDefaultFromEnvar(\"API_ENDPOINT\").Required().String()\n\tdopplerEndpoint    = kingpin.Flag(\"doppler-endpoint\", \"Overwrite default doppler endpoint return by \/v2\/info\").OverrideDefaultFromEnvar(\"DOPPLER_ENDPOINT\").String()\n\tsyslogServer       = kingpin.Flag(\"syslog-server\", \"Syslog server.\").OverrideDefaultFromEnvar(\"SYSLOG_ENDPOINT\").String()\n\tsubscriptionId     = kingpin.Flag(\"subscription-id\", \"Id for the subscription.\").Default(\"firehose\").OverrideDefaultFromEnvar(\"FIREHOSE_SUBSCRIPTION_ID\").String()\n\tuser               = kingpin.Flag(\"user\", \"Admin user.\").Default(\"admin\").OverrideDefaultFromEnvar(\"FIREHOSE_USER\").String()\n\tpassword           = kingpin.Flag(\"password\", \"Admin password.\").Default(\"admin\").OverrideDefaultFromEnvar(\"FIREHOSE_PASSWORD\").String()\n\tskipSSLValidation  = kingpin.Flag(\"skip-ssl-validation\", \"Please don't\").Default(\"false\").OverrideDefaultFromEnvar(\"SKIP_SSL_VALIDATION\").Bool()\n\tlogEventTotals     = kingpin.Flag(\"log-event-totals\", \"Logs the counters for all selected events since nozzle was last started.\").Default(\"false\").OverrideDefaultFromEnvar(\"LOG_EVENT_TOTALS\").Bool()\n\tlogEventTotalsTime = kingpin.Flag(\"log-event-totals-time\", \"How frequently the event totals are calculated (in sec).\").Default(\"30s\").OverrideDefaultFromEnvar(\"LOG_EVENT_TOTALS_TIME\").Duration()\n\twantedEvents       = kingpin.Flag(\"events\", fmt.Sprintf(\"Comma separated list of events you would like. Valid options are %s\", events.GetListAuthorizedEventEvents())).Default(\"LogMessage\").OverrideDefaultFromEnvar(\"EVENTS\").String()\n\tboltDatabasePath   = kingpin.Flag(\"boltdb-path\", \"Bolt Database path \").Default(\"my.db\").OverrideDefaultFromEnvar(\"BOLTDB_PATH\").String()\n\ttickerTime         = kingpin.Flag(\"cc-pull-time\", \"CloudController Polling time in sec\").Default(\"60s\").OverrideDefaultFromEnvar(\"CF_PULL_TIME\").Duration()\n\textraFields        = kingpin.Flag(\"extra-fields\", \"Extra fields you want to annotate your events with, example: '--extra-fields=env:dev,something:other \").Default(\"\").OverrideDefaultFromEnvar(\"EXTRA_FIELDS\").String()\n\tmodeProf           = kingpin.Flag(\"mode-prof\", \"Enable profiling mode, one of [cpu, mem, block]\").Default(\"\").OverrideDefaultFromEnvar(\"MODE_PROF\").String()\n\tpathProf           = kingpin.Flag(\"path-prof\", \"Set the Path to write profiling file\").Default(\"\").OverrideDefaultFromEnvar(\"PATH_PROF\").String()\n)\n\nconst (\n\tversion = \"1.3.0 - 84c87578\"\n)\n\nfunc main() {\n\tkingpin.Version(version)\n\tkingpin.Parse()\n\tlogging.LogStd(fmt.Sprintf(\"Starting firehose-to-syslog %s \", version), true)\n\n\tlogging.SetupLogging(*syslogServer, *debug)\n\n\tc := cfclient.Config{\n\t\tApiAddress:        *apiEndpoint,\n\t\tUsername:          *user,\n\t\tPassword:          *password,\n\t\tSkipSslValidation: *skipSSLValidation,\n\t}\n\tcfClient := cfclient.NewClient(&c)\n\n\tif len(*dopplerEndpoint) > 0 {\n\t\tcfClient.Endpoint.DopplerEndpoint = *dopplerEndpoint\n\t}\n\tlogging.LogStd(fmt.Sprintf(\"Using %s as doppler endpoint\", cfClient.Endpoint.DopplerEndpoint), true)\n\n\tlogging.LogStd(\"Setting up event routing!\", true)\n\terr := events.SetupEventRouting(*wantedEvents)\n\tif err != nil {\n\t\tlog.Fatal(\"Error setting up event routing: \", err)\n\t\tos.Exit(1)\n\n\t}\n\n\t\/\/Use bolt for in-memory  - file caching\n\tdb, err := bolt.Open(*boltDatabasePath, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening bolt db: \", err)\n\t\tos.Exit(1)\n\n\t}\n\tdefer db.Close()\n\n\tif *modeProf != \"\" {\n\t\tswitch *modeProf {\n\t\tcase \"cpu\":\n\t\t\tdefer profile.Start(profile.CPUProfile, profile.ProfilePath(*pathProf)).Stop()\n\t\tcase \"mem\":\n\t\t\tdefer profile.Start(profile.MemProfile, profile.ProfilePath(*pathProf)).Stop()\n\t\tcase \"block\":\n\t\t\tdefer profile.Start(profile.BlockProfile, profile.ProfilePath(*pathProf)).Stop()\n\t\tdefault:\n\t\t\t\/\/ do nothing\n\t\t}\n\t}\n\n\tcaching.SetCfClient(cfClient)\n\tcaching.SetAppDb(db)\n\tcaching.CreateBucket()\n\n\t\/\/Let's Update the database the first time\n\tlogging.LogStd(\"Start filling app\/space\/org cache.\", true)\n\tapps := caching.GetAllApp()\n\tlogging.LogStd(fmt.Sprintf(\"Done filling cache! Found [%d] Apps\", len(apps)), true)\n\n\t\/\/ Ticker Pooling the CC every X sec\n\tccPooling := time.NewTicker(*tickerTime)\n\n\tgo func() {\n\t\tfor range ccPooling.C {\n\t\t\tapps = caching.GetAllApp()\n\t\t}\n\t}()\n\n\t\/\/ Parse extra fields from cmd call\n\textraFields, err := extrafields.ParseExtraFields(*extraFields)\n\tif err != nil {\n\t\tlog.Fatal(\"Error parsing extra fields: \", err)\n\t\tos.Exit(1)\n\t}\n\n\tif *logEventTotals == true {\n\t\tevents.LogEventTotals(*logEventTotalsTime, *dopplerEndpoint)\n\t}\n\n\tif logging.Connect() || *debug {\n\n\t\tlogging.LogStd(\"Connected to Syslog Server! Connecting to Firehose...\", true)\n\n\t\tfirehose := firehose.CreateFirehoseChan(cfClient.Endpoint.DopplerEndpoint, cfClient.GetToken(), *subscriptionId, *skipSSLValidation)\n\t\tif firehose != nil {\n\t\t\tlogging.LogStd(\"Firehose Subscription Succesfull! Routing events...\", true)\n\t\t\tevents.RouteEvents(firehose, extraFields)\n\t\t} else {\n\t\t\tlogging.LogError(\"Failed connecting to Firehose...Please check settings and try again!\", \"\")\n\t\t}\n\n\t} else {\n\t\tlogging.LogError(\"Failed connecting to the Syslog Server...Please check settings and try again!\", \"\")\n\t}\n}\n<commit_msg>Bump Version<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/cloudfoundry-community\/firehose-to-syslog\/caching\"\n\t\"github.com\/cloudfoundry-community\/firehose-to-syslog\/events\"\n\t\"github.com\/cloudfoundry-community\/firehose-to-syslog\/extrafields\"\n\t\"github.com\/cloudfoundry-community\/firehose-to-syslog\/firehose\"\n\t\"github.com\/cloudfoundry-community\/firehose-to-syslog\/logging\"\n\t\"github.com\/cloudfoundry-community\/go-cfclient\"\n\t\"github.com\/pkg\/profile\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"log\"\n\t\"os\"\n\t\"time\"\n)\n\nvar (\n\tdebug              = kingpin.Flag(\"debug\", \"Enable debug mode. This disables forwarding to syslog\").Default(\"false\").OverrideDefaultFromEnvar(\"DEBUG\").Bool()\n\tapiEndpoint        = kingpin.Flag(\"api-endpoint\", \"Api endpoint address. For bosh-lite installation of CF: https:\/\/api.10.244.0.34.xip.io\").OverrideDefaultFromEnvar(\"API_ENDPOINT\").Required().String()\n\tdopplerEndpoint    = kingpin.Flag(\"doppler-endpoint\", \"Overwrite default doppler endpoint return by \/v2\/info\").OverrideDefaultFromEnvar(\"DOPPLER_ENDPOINT\").String()\n\tsyslogServer       = kingpin.Flag(\"syslog-server\", \"Syslog server.\").OverrideDefaultFromEnvar(\"SYSLOG_ENDPOINT\").String()\n\tsubscriptionId     = kingpin.Flag(\"subscription-id\", \"Id for the subscription.\").Default(\"firehose\").OverrideDefaultFromEnvar(\"FIREHOSE_SUBSCRIPTION_ID\").String()\n\tuser               = kingpin.Flag(\"user\", \"Admin user.\").Default(\"admin\").OverrideDefaultFromEnvar(\"FIREHOSE_USER\").String()\n\tpassword           = kingpin.Flag(\"password\", \"Admin password.\").Default(\"admin\").OverrideDefaultFromEnvar(\"FIREHOSE_PASSWORD\").String()\n\tskipSSLValidation  = kingpin.Flag(\"skip-ssl-validation\", \"Please don't\").Default(\"false\").OverrideDefaultFromEnvar(\"SKIP_SSL_VALIDATION\").Bool()\n\tlogEventTotals     = kingpin.Flag(\"log-event-totals\", \"Logs the counters for all selected events since nozzle was last started.\").Default(\"false\").OverrideDefaultFromEnvar(\"LOG_EVENT_TOTALS\").Bool()\n\tlogEventTotalsTime = kingpin.Flag(\"log-event-totals-time\", \"How frequently the event totals are calculated (in sec).\").Default(\"30s\").OverrideDefaultFromEnvar(\"LOG_EVENT_TOTALS_TIME\").Duration()\n\twantedEvents       = kingpin.Flag(\"events\", fmt.Sprintf(\"Comma separated list of events you would like. Valid options are %s\", events.GetListAuthorizedEventEvents())).Default(\"LogMessage\").OverrideDefaultFromEnvar(\"EVENTS\").String()\n\tboltDatabasePath   = kingpin.Flag(\"boltdb-path\", \"Bolt Database path \").Default(\"my.db\").OverrideDefaultFromEnvar(\"BOLTDB_PATH\").String()\n\ttickerTime         = kingpin.Flag(\"cc-pull-time\", \"CloudController Polling time in sec\").Default(\"60s\").OverrideDefaultFromEnvar(\"CF_PULL_TIME\").Duration()\n\textraFields        = kingpin.Flag(\"extra-fields\", \"Extra fields you want to annotate your events with, example: '--extra-fields=env:dev,something:other \").Default(\"\").OverrideDefaultFromEnvar(\"EXTRA_FIELDS\").String()\n\tmodeProf           = kingpin.Flag(\"mode-prof\", \"Enable profiling mode, one of [cpu, mem, block]\").Default(\"\").OverrideDefaultFromEnvar(\"MODE_PROF\").String()\n\tpathProf           = kingpin.Flag(\"path-prof\", \"Set the Path to write profiling file\").Default(\"\").OverrideDefaultFromEnvar(\"PATH_PROF\").String()\n)\n\nconst (\n\tversion = \"1.3.1\"\n)\n\nfunc main() {\n\tkingpin.Version(version)\n\tkingpin.Parse()\n\tlogging.LogStd(fmt.Sprintf(\"Starting firehose-to-syslog %s \", version), true)\n\n\tlogging.SetupLogging(*syslogServer, *debug)\n\n\tc := cfclient.Config{\n\t\tApiAddress:        *apiEndpoint,\n\t\tUsername:          *user,\n\t\tPassword:          *password,\n\t\tSkipSslValidation: *skipSSLValidation,\n\t}\n\tcfClient := cfclient.NewClient(&c)\n\n\tif len(*dopplerEndpoint) > 0 {\n\t\tcfClient.Endpoint.DopplerEndpoint = *dopplerEndpoint\n\t}\n\tlogging.LogStd(fmt.Sprintf(\"Using %s as doppler endpoint\", cfClient.Endpoint.DopplerEndpoint), true)\n\n\tlogging.LogStd(\"Setting up event routing!\", true)\n\terr := events.SetupEventRouting(*wantedEvents)\n\tif err != nil {\n\t\tlog.Fatal(\"Error setting up event routing: \", err)\n\t\tos.Exit(1)\n\n\t}\n\n\t\/\/Use bolt for in-memory  - file caching\n\tdb, err := bolt.Open(*boltDatabasePath, 0600, &bolt.Options{Timeout: 1 * time.Second})\n\tif err != nil {\n\t\tlog.Fatal(\"Error opening bolt db: \", err)\n\t\tos.Exit(1)\n\n\t}\n\tdefer db.Close()\n\n\tif *modeProf != \"\" {\n\t\tswitch *modeProf {\n\t\tcase \"cpu\":\n\t\t\tdefer profile.Start(profile.CPUProfile, profile.ProfilePath(*pathProf)).Stop()\n\t\tcase \"mem\":\n\t\t\tdefer profile.Start(profile.MemProfile, profile.ProfilePath(*pathProf)).Stop()\n\t\tcase \"block\":\n\t\t\tdefer profile.Start(profile.BlockProfile, profile.ProfilePath(*pathProf)).Stop()\n\t\tdefault:\n\t\t\t\/\/ do nothing\n\t\t}\n\t}\n\n\tcaching.SetCfClient(cfClient)\n\tcaching.SetAppDb(db)\n\tcaching.CreateBucket()\n\n\t\/\/Let's Update the database the first time\n\tlogging.LogStd(\"Start filling app\/space\/org cache.\", true)\n\tapps := caching.GetAllApp()\n\tlogging.LogStd(fmt.Sprintf(\"Done filling cache! Found [%d] Apps\", len(apps)), true)\n\n\t\/\/ Ticker Pooling the CC every X sec\n\tccPooling := time.NewTicker(*tickerTime)\n\n\tgo func() {\n\t\tfor range ccPooling.C {\n\t\t\tapps = caching.GetAllApp()\n\t\t}\n\t}()\n\n\t\/\/ Parse extra fields from cmd call\n\textraFields, err := extrafields.ParseExtraFields(*extraFields)\n\tif err != nil {\n\t\tlog.Fatal(\"Error parsing extra fields: \", err)\n\t\tos.Exit(1)\n\t}\n\n\tif *logEventTotals == true {\n\t\tevents.LogEventTotals(*logEventTotalsTime, *dopplerEndpoint)\n\t}\n\n\tif logging.Connect() || *debug {\n\n\t\tlogging.LogStd(\"Connected to Syslog Server! Connecting to Firehose...\", true)\n\n\t\tfirehose := firehose.CreateFirehoseChan(cfClient.Endpoint.DopplerEndpoint, cfClient.GetToken(), *subscriptionId, *skipSSLValidation)\n\t\tif firehose != nil {\n\t\t\tlogging.LogStd(\"Firehose Subscription Succesfull! Routing events...\", true)\n\t\t\tevents.RouteEvents(firehose, extraFields)\n\t\t} else {\n\t\t\tlogging.LogError(\"Failed connecting to Firehose...Please check settings and try again!\", \"\")\n\t\t}\n\n\t} else {\n\t\tlogging.LogError(\"Failed connecting to the Syslog Server...Please check settings and try again!\", \"\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com\/samertm\/meowy\/server\"\n)\n\nfunc main() {\n\thost := flag.String(\"host\", \"localhost\", \"sets the host name.\")\n\tport := flag.String(\"port\", \"5849\", \"sets the port.\")\n\tprefix := flag.String(\"prefix\", \"\", \"sets prefix (for if meowy listens on a path that isn't \\\"\/\\\"\")\n\tflag.Parse()\n\tip := *host + \":\" + *port\n\tfmt.Println(\"listening on\", ip)\n\tif *prefix != \"\" {\n\t\tfmt.Println(\"with prefix\", *prefix)\n\t\tvar front, back string\n\t\tif (*prefix)[0] != '\/' {\n\t\t\tfront = \"\/\"\n\t\t}\n\t\tif (*prefix)[len(*prefix)-1] != '\/' {\n\t\t\tback = \"\/\"\n\t\t}\n\t\t*prefix = front + *prefix + back\n\t}\n\tserver.ListenAndServe(ip, *prefix)\n}\n<commit_msg>Show prefix after fixing it<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"github.com\/samertm\/meowy\/server\"\n)\n\nfunc main() {\n\thost := flag.String(\"host\", \"localhost\", \"sets the host name.\")\n\tport := flag.String(\"port\", \"5849\", \"sets the port.\")\n\tprefix := flag.String(\"prefix\", \"\", \"sets prefix (for if meowy listens on a path that isn't \\\"\/\\\"\")\n\tflag.Parse()\n\tip := *host + \":\" + *port\n\tfmt.Println(\"listening on\", ip)\n\tif *prefix != \"\" {\n\t\tvar front, back string\n\t\tif (*prefix)[0] != '\/' {\n\t\t\tfront = \"\/\"\n\t\t}\n\t\tif (*prefix)[len(*prefix)-1] != '\/' {\n\t\t\tback = \"\/\"\n\t\t}\n\t\t*prefix = front + *prefix + back\n\t\tfmt.Println(\"with prefix\", *prefix)\n\t}\n\tserver.ListenAndServe(ip, *prefix)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"github.com\/EE-Tools\/ApiProxy\/proxy\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n)\n\n\/\/ listen http port\nvar port = flag.String(\"port\", \"8080\", \"http serve port\")\nvar mode = flag.String(\"mode\", \"debug\", \"project run mode,default is debug\")\n\nfunc init() {\n\tflag.Parse()\n}\n\n\/\/ entry point.\nfunc main() {\n\t\/\/ startup info.\n\tlog.Println(\"run mode is\", *mode)\n\tlog.Println(\"startup and listen\", *port)\n\n\thlist := []proxy.Handler{\n\t\t\/\/ print debug log handler\n\t\t&proxy.DebugHandler{},\n\t}\n\n\t\/\/ add handle\n\ts := &http.Server{\n\t\tAddr: \":\" + *port,\n\t\tHandler: &DefaultHandleChain{\n\t\t\tHandleList: hlist,\n\t\t},\n\t\tReadTimeout:    10 * time.Second,\n\t\tWriteTimeout:   10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\tlog.Fatal(s.ListenAndServe())\n}\n\ntype DefaultHandleChain struct {\n\tHandleList []proxy.Handler\n}\n\nfunc (this *DefaultHandleChain) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tfor _, handle := range this.HandleList {\n\t\thandle.ServeHTTP(w, r)\n\t}\n}\n<commit_msg>add proxy handler<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"github.com\/EE-Tools\/ApiProxy\/proxy\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n)\n\n\/\/ listen http port\nvar port = flag.String(\"port\", \"8080\", \"http serve port\")\nvar mode = flag.String(\"mode\", \"debug\", \"project run mode,default is debug\")\n\nfunc init() {\n\tflag.Parse()\n}\n\n\/\/ entry point.\nfunc main() {\n\t\/\/ startup info.\n\tlog.Println(\"run mode is\", *mode)\n\tlog.Println(\"startup and listen\", *port)\n\n\thlist := []proxy.Handler{\n\t\t\/\/ print debug log handler\n\t\t&proxy.DebugHandler{},\n\t\t&proxy.ProxyHandler{},\n\t}\n\n\t\/\/ add handle\n\ts := &http.Server{\n\t\tAddr: \":\" + *port,\n\t\tHandler: &DefaultHandleChain{\n\t\t\tHandleList: hlist,\n\t\t},\n\t\tReadTimeout:    10 * time.Second,\n\t\tWriteTimeout:   10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\tlog.Fatal(s.ListenAndServe())\n}\n\ntype DefaultHandleChain struct {\n\tHandleList []proxy.Handler\n}\n\nfunc (this *DefaultHandleChain) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tfor _, handle := range this.HandleList {\n\t\thandle.ServeHTTP(w, r)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/meatballhat\/negroni-logrus\"\n\t\"gopkg.in\/unrolled\/render.v1\"\n\n\t\"github.com\/alphagov\/metadata-api\/content_api\"\n\t\"github.com\/alphagov\/metadata-api\/need_api\"\n)\n\nvar (\n\tcontentAPIBearerToken = getEnvDefault(\"CONTENT_API_BEARER_TOKEN\", \"foo\")\n\tneedAPIBearerToken    = getEnvDefault(\"NEED_API_BEARER_TOKEN\", \"foo\")\n\tappDomain             = getEnvDefault(\"GOVUK_APP_DOMAIN\", \"alphagov.co.uk\")\n\tport                  = getEnvDefault(\"HTTP_PORT\", \"3000\")\n\n\tcontentAPI = \"contentapi.\" + appDomain\n\tneedAPI    = \"need-api.\" + appDomain\n\n\trenderer = render.New(render.Options{})\n)\n\nfunc HealthCheckHandler(w http.ResponseWriter, r *http.Request) {\n\trenderer.JSON(w, http.StatusOK, map[string]string{\"status\": \"OK\"})\n}\n\nfunc InfoHandler(contentAPI, needAPI, contentAPIBearerToken, needAPIBearerToken string) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvar needs []*need_api.Need\n\n\t\tslug := r.URL.Path[len(\"\/info\"):]\n\n\t\tif len(slug) <= 1 || slug == \"\/\" {\n\t\t\trenderError(w, http.StatusNotFound, \"not found\")\n\t\t\treturn\n\t\t}\n\n\t\tartefact, err := content_api.FetchArtefact(contentAPI, contentAPIBearerToken, slug)\n\t\tif err != nil {\n\t\t\trenderError(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tfor _, needID := range artefact.Details.NeedIDs {\n\t\t\tneed, err := need_api.FetchNeed(needAPI, needAPIBearerToken, needID)\n\t\t\tif err != nil {\n\t\t\t\trenderError(w, http.StatusInternalServerError, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tneeds = append(needs, need)\n\t\t}\n\n\t\tmetadata := &Metadata{\n\t\t\tArtefact:     artefact,\n\t\t\tNeeds:        needs,\n\t\t\tResponseInfo: &ResponseInfo{Status: \"ok\"},\n\t\t}\n\n\t\trenderer.JSON(w, http.StatusOK, metadata)\n\t}\n}\n\nfunc main() {\n\thttpMux := http.NewServeMux()\n\thttpMux.HandleFunc(\"\/healthcheck\", HealthCheckHandler)\n\thttpMux.HandleFunc(\"\/info\", InfoHandler(contentAPI, needAPI,\n\t\tcontentAPIBearerToken, needAPIBearerToken))\n\n\tmiddleware := negroni.New()\n\tmiddleware.Use(negronilogrus.NewCustomMiddleware(\n\t\tlogrus.InfoLevel, &logrus.JSONFormatter{}, \"metadata-api\"))\n\tmiddleware.UseHandler(httpMux)\n\n\tmiddleware.Run(\":\" + port)\n}\n\nfunc renderError(w http.ResponseWriter, status int, errorString string) {\n\trenderer.JSON(w, status, &Metadata{ResponseInfo: &ResponseInfo{Status: errorString}})\n}\n\nfunc getEnvDefault(key string, defaultVal string) string {\n\tval := os.Getenv(key)\n\tif val == \"\" {\n\t\treturn defaultVal\n\t}\n\n\treturn val\n}\n<commit_msg>Prefix the bearer token ENV variable with `BEARER_TOKEN_`<commit_after>package main\n\nimport (\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/meatballhat\/negroni-logrus\"\n\t\"gopkg.in\/unrolled\/render.v1\"\n\n\t\"github.com\/alphagov\/metadata-api\/content_api\"\n\t\"github.com\/alphagov\/metadata-api\/need_api\"\n)\n\nvar (\n\tcontentAPIBearerToken = getEnvDefault(\"BEARER_TOKEN_CONTENT_API\", \"foo\")\n\tneedAPIBearerToken    = getEnvDefault(\"BEARER_TOKEN_NEED_API\", \"bar\")\n\tappDomain             = getEnvDefault(\"GOVUK_APP_DOMAIN\", \"alphagov.co.uk\")\n\tport                  = getEnvDefault(\"HTTP_PORT\", \"3000\")\n\n\tcontentAPI = \"contentapi.\" + appDomain\n\tneedAPI    = \"need-api.\" + appDomain\n\n\trenderer = render.New(render.Options{})\n)\n\nfunc HealthCheckHandler(w http.ResponseWriter, r *http.Request) {\n\trenderer.JSON(w, http.StatusOK, map[string]string{\"status\": \"OK\"})\n}\n\nfunc InfoHandler(contentAPI, needAPI, contentAPIBearerToken, needAPIBearerToken string) func(http.ResponseWriter, *http.Request) {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tvar needs []*need_api.Need\n\n\t\tslug := r.URL.Path[len(\"\/info\"):]\n\n\t\tif len(slug) <= 1 || slug == \"\/\" {\n\t\t\trenderError(w, http.StatusNotFound, \"not found\")\n\t\t\treturn\n\t\t}\n\n\t\tartefact, err := content_api.FetchArtefact(contentAPI, contentAPIBearerToken, slug)\n\t\tif err != nil {\n\t\t\trenderError(w, http.StatusInternalServerError, err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tfor _, needID := range artefact.Details.NeedIDs {\n\t\t\tneed, err := need_api.FetchNeed(needAPI, needAPIBearerToken, needID)\n\t\t\tif err != nil {\n\t\t\t\trenderError(w, http.StatusInternalServerError, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tneeds = append(needs, need)\n\t\t}\n\n\t\tmetadata := &Metadata{\n\t\t\tArtefact:     artefact,\n\t\t\tNeeds:        needs,\n\t\t\tResponseInfo: &ResponseInfo{Status: \"ok\"},\n\t\t}\n\n\t\trenderer.JSON(w, http.StatusOK, metadata)\n\t}\n}\n\nfunc main() {\n\thttpMux := http.NewServeMux()\n\thttpMux.HandleFunc(\"\/healthcheck\", HealthCheckHandler)\n\thttpMux.HandleFunc(\"\/info\", InfoHandler(contentAPI, needAPI,\n\t\tcontentAPIBearerToken, needAPIBearerToken))\n\n\tmiddleware := negroni.New()\n\tmiddleware.Use(negronilogrus.NewCustomMiddleware(\n\t\tlogrus.InfoLevel, &logrus.JSONFormatter{}, \"metadata-api\"))\n\tmiddleware.UseHandler(httpMux)\n\n\tmiddleware.Run(\":\" + port)\n}\n\nfunc renderError(w http.ResponseWriter, status int, errorString string) {\n\trenderer.JSON(w, status, &Metadata{ResponseInfo: &ResponseInfo{Status: errorString}})\n}\n\nfunc getEnvDefault(key string, defaultVal string) string {\n\tval := os.Getenv(key)\n\tif val == \"\" {\n\t\treturn defaultVal\n\t}\n\n\treturn val\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\n\tcorelog \"log\"\n\n\t\"github.com\/go-kit\/kit\/log\"\n\tkitprometheus \"github.com\/go-kit\/kit\/metrics\/prometheus\"\n\t\"github.com\/microservices-demo\/user\/api\"\n\t\"github.com\/microservices-demo\/user\/db\"\n\t\"github.com\/microservices-demo\/user\/db\/mongodb\"\n\tstdopentracing \"github.com\/opentracing\/opentracing-go\"\n\tzipkin \"github.com\/openzipkin\/zipkin-go-opentracing\"\n\tstdprometheus \"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar (\n\tdev  bool\n\tport string\n\tacc  string\n\tzip  string\n)\n\nconst (\n\tServiceName = \"user\"\n)\n\nfunc init() {\n\n\tflag.StringVar(&zip, \"zipkin\", os.Getenv(\"ZIPKIN\"), \"Zipkin address\")\n\tflag.StringVar(&port, \"port\", \"8084\", \"Port on which to run\")\n\tdb.Register(\"mongodb\", &mongodb.Mongo{})\n}\n\nfunc main() {\n\n\tflag.Parse()\n\t\/\/ Mechanical stuff.\n\terrc := make(chan error)\n\tctx := context.Background()\n\n\t\/\/ Log domain.\n\tvar logger log.Logger\n\t{\n\t\tlogger = log.NewLogfmtLogger(os.Stderr)\n\t\tlogger = log.NewContext(logger).With(\"ts\", log.DefaultTimestampUTC)\n\t\tlogger = log.NewContext(logger).With(\"caller\", log.DefaultCaller)\n\t}\n\n\tvar tracer stdopentracing.Tracer\n\t{\n\t\tlogger := log.NewContext(logger).With(\"tracer\", \"Zipkin\")\n\t\tlogger.Log(\"addr\", zip)\n\t\tcollector, err := zipkin.NewHTTPCollector(\n\t\t\tzip,\n\t\t\tzipkin.HTTPLogger(logger),\n\t\t)\n\t\tif err != nil {\n\t\t\tlogger.Log(\"err\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\ttracer, err = zipkin.NewTracer(\n\t\t\tzipkin.NewRecorder(collector, false, fmt.Sprintf(\"localhost:%v\", port), ServiceName),\n\t\t)\n\t\tif err != nil {\n\t\t\tlogger.Log(\"err\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tstdopentracing.InitGlobalTracer(tracer)\n\t}\n\tdbconn := false\n\tfor !dbconn {\n\t\terr := db.Init()\n\t\tif err != nil {\n\t\t\tif err == db.ErrNoDatabaseSelected {\n\t\t\t\tcorelog.Fatal(err)\n\t\t\t}\n\t\t\tcorelog.Print(err)\n\t\t} else {\n\t\t\tdbconn = true\n\t\t}\n\t}\n\n\tfieldKeys := []string{\"method\"}\n\t\/\/ Service domain.\n\tvar service api.Service\n\t{\n\t\tservice = api.NewFixedService()\n\t\tservice = api.LoggingMiddleware(logger)(service)\n\t\tservice = api.NewInstrumentingService(\n\t\t\tkitprometheus.NewCounterFrom(\n\t\t\t\tstdprometheus.CounterOpts{\n\t\t\t\t\tNamespace: \"microservices_demo\",\n\t\t\t\t\tSubsystem: \"user\",\n\t\t\t\t\tName:      \"request_count\",\n\t\t\t\t\tHelp:      \"Number of requests received.\",\n\t\t\t\t},\n\t\t\t\tfieldKeys),\n\t\t\tkitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{\n\t\t\t\tNamespace: \"microservices_demo\",\n\t\t\t\tSubsystem: \"user\",\n\t\t\t\tName:      \"request_latency_microseconds\",\n\t\t\t\tHelp:      \"Total duration of requests in microseconds.\",\n\t\t\t}, fieldKeys),\n\t\t\tservice,\n\t\t)\n\t}\n\n\t\/\/ Endpoint domain.\n\tendpoints := api.MakeEndpoints(service, tracer)\n\n\t\/\/ Create and launch the HTTP server.\n\tgo func() {\n\t\tlogger.Log(\"transport\", \"HTTP\", \"port\", port)\n\t\thandler := api.MakeHTTPHandler(ctx, endpoints, logger, tracer)\n\t\terrc <- http.ListenAndServe(fmt.Sprintf(\":%v\", port), handler)\n\t}()\n\n\t\/\/ Capture interrupts.\n\tgo func() {\n\t\tc := make(chan os.Signal)\n\t\tsignal.Notify(c, syscall.SIGINT, syscall.SIGTERM)\n\t\terrc <- fmt.Errorf(\"%s\", <-c)\n\t}()\n\n\tlogger.Log(\"exit\", <-errc)\n}\n<commit_msg>added a check for flag to set noop tracer<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\n\tcorelog \"log\"\n\n\t\"github.com\/go-kit\/kit\/log\"\n\tkitprometheus \"github.com\/go-kit\/kit\/metrics\/prometheus\"\n\t\"github.com\/microservices-demo\/user\/api\"\n\t\"github.com\/microservices-demo\/user\/db\"\n\t\"github.com\/microservices-demo\/user\/db\/mongodb\"\n\tstdopentracing \"github.com\/opentracing\/opentracing-go\"\n\tzipkin \"github.com\/openzipkin\/zipkin-go-opentracing\"\n\tstdprometheus \"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nvar (\n\tdev  bool\n\tport string\n\tacc  string\n\tzip  string\n)\n\nconst (\n\tServiceName = \"user\"\n)\n\nfunc init() {\n\n\tflag.StringVar(&zip, \"zipkin\", os.Getenv(\"ZIPKIN\"), \"Zipkin address\")\n\tflag.StringVar(&port, \"port\", \"8084\", \"Port on which to run\")\n\tdb.Register(\"mongodb\", &mongodb.Mongo{})\n}\n\nfunc main() {\n\n\tflag.Parse()\n\t\/\/ Mechanical stuff.\n\terrc := make(chan error)\n\tctx := context.Background()\n\n\t\/\/ Log domain.\n\tvar logger log.Logger\n\t{\n\t\tlogger = log.NewLogfmtLogger(os.Stderr)\n\t\tlogger = log.NewContext(logger).With(\"ts\", log.DefaultTimestampUTC)\n\t\tlogger = log.NewContext(logger).With(\"caller\", log.DefaultCaller)\n\t}\n\n\tvar tracer stdopentracing.Tracer\n\t{\n\t\tif zip == \"\" {\n\t\t\ttracer = stdopentracing.NoopTracer{}\n\t\t} else {\n\t\t\tlogger := log.NewContext(logger).With(\"tracer\", \"Zipkin\")\n\t\t\tlogger.Log(\"addr\", zip)\n\t\t\tcollector, err := zipkin.NewHTTPCollector(\n\t\t\t\tzip,\n\t\t\t\tzipkin.HTTPLogger(logger),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Log(\"err\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\ttracer, err = zipkin.NewTracer(\n\t\t\t\tzipkin.NewRecorder(collector, false, fmt.Sprintf(\"localhost:%v\", port), ServiceName),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Log(\"err\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t\tstdopentracing.InitGlobalTracer(tracer)\n\t}\n\tdbconn := false\n\tfor !dbconn {\n\t\terr := db.Init()\n\t\tif err != nil {\n\t\t\tif err == db.ErrNoDatabaseSelected {\n\t\t\t\tcorelog.Fatal(err)\n\t\t\t}\n\t\t\tcorelog.Print(err)\n\t\t} else {\n\t\t\tdbconn = true\n\t\t}\n\t}\n\n\tfieldKeys := []string{\"method\"}\n\t\/\/ Service domain.\n\tvar service api.Service\n\t{\n\t\tservice = api.NewFixedService()\n\t\tservice = api.LoggingMiddleware(logger)(service)\n\t\tservice = api.NewInstrumentingService(\n\t\t\tkitprometheus.NewCounterFrom(\n\t\t\t\tstdprometheus.CounterOpts{\n\t\t\t\t\tNamespace: \"microservices_demo\",\n\t\t\t\t\tSubsystem: \"user\",\n\t\t\t\t\tName:      \"request_count\",\n\t\t\t\t\tHelp:      \"Number of requests received.\",\n\t\t\t\t},\n\t\t\t\tfieldKeys),\n\t\t\tkitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{\n\t\t\t\tNamespace: \"microservices_demo\",\n\t\t\t\tSubsystem: \"user\",\n\t\t\t\tName:      \"request_latency_microseconds\",\n\t\t\t\tHelp:      \"Total duration of requests in microseconds.\",\n\t\t\t}, fieldKeys),\n\t\t\tservice,\n\t\t)\n\t}\n\n\t\/\/ Endpoint domain.\n\tendpoints := api.MakeEndpoints(service, tracer)\n\n\t\/\/ Create and launch the HTTP server.\n\tgo func() {\n\t\tlogger.Log(\"transport\", \"HTTP\", \"port\", port)\n\t\thandler := api.MakeHTTPHandler(ctx, endpoints, logger, tracer)\n\t\terrc <- http.ListenAndServe(fmt.Sprintf(\":%v\", port), handler)\n\t}()\n\n\t\/\/ Capture interrupts.\n\tgo func() {\n\t\tc := make(chan os.Signal)\n\t\tsignal.Notify(c, syscall.SIGINT, syscall.SIGTERM)\n\t\terrc <- fmt.Errorf(\"%s\", <-c)\n\t}()\n\n\tlogger.Log(\"exit\", <-errc)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/jessevdk\/go-flags\"\n\n\t\"github.com\/ivanilves\/lstags\/auth\"\n\t\"github.com\/ivanilves\/lstags\/tag\/local\"\n\t\"github.com\/ivanilves\/lstags\/tag\/registry\"\n)\n\ntype options struct {\n\tRegistry   string `short:\"r\" long:\"registry\" default:\"registry.hub.docker.com\" description:\"Docker registry to use\" env:\"REGISTRY\"`\n\tUsername   string `short:\"u\" long:\"username\" default:\"\" description:\"Docker registry username\" env:\"USERNAME\"`\n\tPassword   string `short:\"p\" long:\"password\" default:\"\" description:\"Docker registry password\" env:\"PASSWORD\"`\n\tPositional struct {\n\t\tRepository string `positional-arg-name:\"REPOSITORY\" description:\"Docker repository to list tags from\"`\n\t} `positional-args:\"yes\" required:\"yes\"`\n}\n\nfunc concatTagNames(registryTags, localTags map[string]string) []string {\n\ttagNames := make([]string, 0)\n\n\tfor tagName, _ := range registryTags {\n\t\ttagNames = append(tagNames, tagName)\n\t}\n\n\tfor tagName, _ := range localTags {\n\t\t_, defined := registryTags[tagName]\n\t\tif !defined {\n\t\t\ttagNames = append(tagNames, tagName)\n\t\t}\n\t}\n\n\treturn tagNames\n}\n\nfunc getDigest(tagName string, registryTags, localTags map[string]string) string {\n\tregistryDigest, defined := registryTags[tagName]\n\tif defined && registryDigest != \"\" {\n\t\treturn registryDigest\n\t}\n\n\tlocalDigest, defined := localTags[tagName]\n\tif defined && localDigest != \"\" {\n\t\treturn localDigest\n\t}\n\n\treturn \"n\/a\"\n}\n\nfunc getState(tagName string, registryTags, localTags map[string]string) string {\n\tregistryDigest, definedInRegistry := registryTags[tagName]\n\tlocalDigest, definedLocally := localTags[tagName]\n\n\tif definedInRegistry && !definedLocally {\n\t\treturn \"ABSENT\"\n\t}\n\n\tif !definedInRegistry && definedLocally {\n\t\treturn \"LOCAL-ONLY\"\n\t}\n\n\tif definedInRegistry && definedLocally {\n\t\tif registryDigest == localDigest {\n\t\t\treturn \"PRESENT\"\n\t\t} else {\n\t\t\treturn \"CHANGED\"\n\t\t}\n\t}\n\n\treturn \"UNKNOWN\"\n}\n\nfunc getRepoRegistryName(repository, registry string) string {\n\tif !strings.Contains(repository, \"\/\") {\n\t\treturn \"library\/\" + repository\n\t}\n\n\tif strings.HasPrefix(repository, registry) {\n\t\treturn strings.Replace(repository, registry+\"\/\", \"\", 1)\n\t}\n\n\treturn repository\n}\n\nfunc getRepoLocalName(repository, registry string) string {\n\tif registry == \"registry.hub.docker.com\" {\n\t\treturn repository\n\t}\n\n\treturn registry + \"\/\" + repository\n}\n\nfunc main() {\n\to := options{}\n\n\t_, err := flags.Parse(&o)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\trepoRegistryName := getRepoRegistryName(o.Positional.Repository, o.Registry)\n\trepoLocalName := getRepoLocalName(o.Positional.Repository, o.Registry)\n\n\tauthorization, err := auth.NewAuthorization(o.Registry, repoRegistryName, o.Username, o.Password)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tregistryTags, err := registry.FetchTags(o.Registry, repoRegistryName, authorization)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlocalTags, err := local.FetchTags(repoLocalName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ttagNames := concatTagNames(registryTags, localTags)\n\tfor _, tagName := range tagNames {\n\t\tdigest := getDigest(tagName, registryTags, localTags)\n\t\tstate := getState(tagName, registryTags, localTags)\n\n\t\tfmt.Printf(\"%-12s %-80s %s\\n\", state, digest, o.Positional.Repository+\":\"+tagName)\n\t}\n}\n<commit_msg>Sort by tags...<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/jessevdk\/go-flags\"\n\n\t\"github.com\/ivanilves\/lstags\/auth\"\n\t\"github.com\/ivanilves\/lstags\/tag\/local\"\n\t\"github.com\/ivanilves\/lstags\/tag\/registry\"\n)\n\ntype options struct {\n\tRegistry   string `short:\"r\" long:\"registry\" default:\"registry.hub.docker.com\" description:\"Docker registry to use\" env:\"REGISTRY\"`\n\tUsername   string `short:\"u\" long:\"username\" default:\"\" description:\"Docker registry username\" env:\"USERNAME\"`\n\tPassword   string `short:\"p\" long:\"password\" default:\"\" description:\"Docker registry password\" env:\"PASSWORD\"`\n\tPositional struct {\n\t\tRepository string `positional-arg-name:\"REPOSITORY\" description:\"Docker repository to list tags from\"`\n\t} `positional-args:\"yes\" required:\"yes\"`\n}\n\nfunc concatTagNames(registryTags, localTags map[string]string) []string {\n\ttagNames := make([]string, 0)\n\n\tfor tagName, _ := range registryTags {\n\t\ttagNames = append(tagNames, tagName)\n\t}\n\n\tfor tagName, _ := range localTags {\n\t\t_, defined := registryTags[tagName]\n\t\tif !defined {\n\t\t\ttagNames = append(tagNames, tagName)\n\t\t}\n\t}\n\n\tsort.Strings(tagNames)\n\n\treturn tagNames\n}\n\nfunc getDigest(tagName string, registryTags, localTags map[string]string) string {\n\tregistryDigest, defined := registryTags[tagName]\n\tif defined && registryDigest != \"\" {\n\t\treturn registryDigest\n\t}\n\n\tlocalDigest, defined := localTags[tagName]\n\tif defined && localDigest != \"\" {\n\t\treturn localDigest\n\t}\n\n\treturn \"n\/a\"\n}\n\nfunc getState(tagName string, registryTags, localTags map[string]string) string {\n\tregistryDigest, definedInRegistry := registryTags[tagName]\n\tlocalDigest, definedLocally := localTags[tagName]\n\n\tif definedInRegistry && !definedLocally {\n\t\treturn \"ABSENT\"\n\t}\n\n\tif !definedInRegistry && definedLocally {\n\t\treturn \"LOCAL-ONLY\"\n\t}\n\n\tif definedInRegistry && definedLocally {\n\t\tif registryDigest == localDigest {\n\t\t\treturn \"PRESENT\"\n\t\t} else {\n\t\t\treturn \"CHANGED\"\n\t\t}\n\t}\n\n\treturn \"UNKNOWN\"\n}\n\nfunc getRepoRegistryName(repository, registry string) string {\n\tif !strings.Contains(repository, \"\/\") {\n\t\treturn \"library\/\" + repository\n\t}\n\n\tif strings.HasPrefix(repository, registry) {\n\t\treturn strings.Replace(repository, registry+\"\/\", \"\", 1)\n\t}\n\n\treturn repository\n}\n\nfunc getRepoLocalName(repository, registry string) string {\n\tif registry == \"registry.hub.docker.com\" {\n\t\treturn repository\n\t}\n\n\treturn registry + \"\/\" + repository\n}\n\nfunc main() {\n\to := options{}\n\n\t_, err := flags.Parse(&o)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\trepoRegistryName := getRepoRegistryName(o.Positional.Repository, o.Registry)\n\trepoLocalName := getRepoLocalName(o.Positional.Repository, o.Registry)\n\n\tauthorization, err := auth.NewAuthorization(o.Registry, repoRegistryName, o.Username, o.Password)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tregistryTags, err := registry.FetchTags(o.Registry, repoRegistryName, authorization)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlocalTags, err := local.FetchTags(repoLocalName)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ttagNames := concatTagNames(registryTags, localTags)\n\tfor _, tagName := range tagNames {\n\t\tdigest := getDigest(tagName, registryTags, localTags)\n\t\tstate := getState(tagName, registryTags, localTags)\n\n\t\tfmt.Printf(\"%-12s %-80s %s\\n\", state, digest, o.Positional.Repository+\":\"+tagName)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-debug-server\"\n\t\"github.com\/cloudfoundry-incubator\/cf-lager\"\n\tBbs \"github.com\/cloudfoundry-incubator\/runtime-schema\/bbs\"\n\t\"github.com\/cloudfoundry-incubator\/tps\/handler\"\n\t\"github.com\/cloudfoundry-incubator\/tps\/heartbeat\"\n\t\"github.com\/cloudfoundry\/dropsonde\/autowire\"\n\t\"github.com\/cloudfoundry\/gunk\/group_runner\"\n\t\"github.com\/cloudfoundry\/gunk\/natsclientrunner\"\n\t\"github.com\/cloudfoundry\/gunk\/timeprovider\"\n\t\"github.com\/cloudfoundry\/storeadapter\/etcdstoreadapter\"\n\t\"github.com\/cloudfoundry\/storeadapter\/workerpool\"\n\t\"github.com\/cloudfoundry\/yagnats\"\n\t\"github.com\/pivotal-golang\/lager\"\n\t\"github.com\/tedsuo\/ifrit\"\n\t\"github.com\/tedsuo\/ifrit\/http_server\"\n\t\"github.com\/tedsuo\/ifrit\/sigmon\"\n)\n\nvar listenAddr = flag.String(\n\t\"listenAddr\",\n\t\"0.0.0.0:1518\", \/\/ p and s's offset in the alphabet, do not change\n\t\"listening address of api server\",\n)\n\nvar etcdCluster = flag.String(\n\t\"etcdCluster\",\n\t\"http:\/\/127.0.0.1:4001\",\n\t\"comma-separated list of etcd addresses (http:\/\/ip:port)\",\n)\n\nvar natsAddresses = flag.String(\n\t\"natsAddresses\",\n\t\"127.0.0.1:4222\",\n\t\"comma-separated list of NATS addresses (ip:port)\",\n)\n\nvar natsUsername = flag.String(\n\t\"natsUsername\",\n\t\"nats\",\n\t\"Username to connect to nats\",\n)\n\nvar natsPassword = flag.String(\n\t\"natsPassword\",\n\t\"nats\",\n\t\"Password for nats user\",\n)\n\nvar heartbeatInterval = flag.Duration(\n\t\"heartbeatInterval\",\n\t60*time.Second,\n\t\"the interval, in seconds, between heartbeats for maintaining presence\",\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tlogger := cf_lager.New(\"tps\")\n\tbbs := initializeBbs(logger)\n\tapiHandler := initializeHandler(logger, bbs)\n\n\tvar natsClient yagnats.NATSConn\n\tcf_debug_server.Run()\n\n\theartbeatRunner := ifrit.RunFunc(func(signals <-chan os.Signal, ready chan<- struct{}) error {\n\t\tactual := heartbeat.New(\n\t\t\tnatsClient,\n\t\t\t*heartbeatInterval,\n\t\t\tfmt.Sprintf(\"http:\/\/%s\", *listenAddr),\n\t\t\tlogger)\n\t\treturn actual.Run(signals, ready)\n\t})\n\n\tgroup := group_runner.New([]group_runner.Member{\n\t\t{\"natsClient\", natsclientrunner.New(*natsAddresses, *natsUsername, *natsPassword, logger, &natsClient)},\n\t\t{\"heartbeat\", heartbeatRunner},\n\t\t{\"api\", http_server.New(*listenAddr, apiHandler)},\n\t})\n\n\tmonitor := ifrit.Envoke(sigmon.New(group))\n\n\tlogger.Info(\"started\")\n\n\terr := <-monitor.Wait()\n\tif err != nil {\n\t\tlogger.Error(\"exited\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlogger.Info(\"exited\")\n\tos.Exit(0)\n}\n\nfunc initializeBbs(logger lager.Logger) Bbs.TPSBBS {\n\tetcdAdapter := etcdstoreadapter.NewETCDStoreAdapter(\n\t\tstrings.Split(*etcdCluster, \",\"),\n\t\tworkerpool.NewWorkerPool(10),\n\t)\n\n\terr := etcdAdapter.Connect()\n\tif err != nil {\n\t\tlogger.Fatal(\"failed-to-connect-to-etcd\", err)\n\t}\n\n\treturn Bbs.NewTPSBBS(etcdAdapter, timeprovider.NewTimeProvider(), logger)\n}\n\nfunc initializeHandler(logger lager.Logger, bbs Bbs.TPSBBS) http.Handler {\n\tapiHandler, err := handler.New(bbs, logger)\n\tif err != nil {\n\t\tlogger.Fatal(\"initialize-handler.failed\", err)\n\t}\n\n\treturn autowire.InstrumentedHandler(apiHandler)\n}\n<commit_msg>replace group_runner with grouper OrderedGroup<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-debug-server\"\n\t\"github.com\/cloudfoundry-incubator\/cf-lager\"\n\tBbs \"github.com\/cloudfoundry-incubator\/runtime-schema\/bbs\"\n\t\"github.com\/cloudfoundry-incubator\/tps\/handler\"\n\t\"github.com\/cloudfoundry-incubator\/tps\/heartbeat\"\n\t\"github.com\/cloudfoundry\/dropsonde\/autowire\"\n\t\"github.com\/cloudfoundry\/gunk\/natsclientrunner\"\n\t\"github.com\/cloudfoundry\/gunk\/timeprovider\"\n\t\"github.com\/cloudfoundry\/storeadapter\/etcdstoreadapter\"\n\t\"github.com\/cloudfoundry\/storeadapter\/workerpool\"\n\t\"github.com\/cloudfoundry\/yagnats\"\n\t\"github.com\/pivotal-golang\/lager\"\n\t\"github.com\/tedsuo\/ifrit\"\n\t\"github.com\/tedsuo\/ifrit\/grouper\"\n\t\"github.com\/tedsuo\/ifrit\/http_server\"\n\t\"github.com\/tedsuo\/ifrit\/sigmon\"\n)\n\nvar listenAddr = flag.String(\n\t\"listenAddr\",\n\t\"0.0.0.0:1518\", \/\/ p and s's offset in the alphabet, do not change\n\t\"listening address of api server\",\n)\n\nvar etcdCluster = flag.String(\n\t\"etcdCluster\",\n\t\"http:\/\/127.0.0.1:4001\",\n\t\"comma-separated list of etcd addresses (http:\/\/ip:port)\",\n)\n\nvar natsAddresses = flag.String(\n\t\"natsAddresses\",\n\t\"127.0.0.1:4222\",\n\t\"comma-separated list of NATS addresses (ip:port)\",\n)\n\nvar natsUsername = flag.String(\n\t\"natsUsername\",\n\t\"nats\",\n\t\"Username to connect to nats\",\n)\n\nvar natsPassword = flag.String(\n\t\"natsPassword\",\n\t\"nats\",\n\t\"Password for nats user\",\n)\n\nvar heartbeatInterval = flag.Duration(\n\t\"heartbeatInterval\",\n\t60*time.Second,\n\t\"the interval, in seconds, between heartbeats for maintaining presence\",\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tlogger := cf_lager.New(\"tps\")\n\tbbs := initializeBbs(logger)\n\tapiHandler := initializeHandler(logger, bbs)\n\n\tvar natsClient yagnats.NATSConn\n\tcf_debug_server.Run()\n\n\theartbeatRunner := ifrit.RunFunc(func(signals <-chan os.Signal, ready chan<- struct{}) error {\n\t\tactual := heartbeat.New(\n\t\t\tnatsClient,\n\t\t\t*heartbeatInterval,\n\t\t\tfmt.Sprintf(\"http:\/\/%s\", *listenAddr),\n\t\t\tlogger)\n\t\treturn actual.Run(signals, ready)\n\t})\n\n\tgroup := grouper.NewOrdered(os.Interrupt, grouper.Members{\n\t\t{\"natsClient\", natsclientrunner.New(*natsAddresses, *natsUsername, *natsPassword, logger, &natsClient)},\n\t\t{\"heartbeat\", heartbeatRunner},\n\t\t{\"api\", http_server.New(*listenAddr, apiHandler)},\n\t})\n\n\tmonitor := ifrit.Envoke(sigmon.New(group))\n\n\tlogger.Info(\"started\")\n\n\terr := <-monitor.Wait()\n\tif err != nil {\n\t\tlogger.Error(\"exited\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlogger.Info(\"exited\")\n\tos.Exit(0)\n}\n\nfunc initializeBbs(logger lager.Logger) Bbs.TPSBBS {\n\tetcdAdapter := etcdstoreadapter.NewETCDStoreAdapter(\n\t\tstrings.Split(*etcdCluster, \",\"),\n\t\tworkerpool.NewWorkerPool(10),\n\t)\n\n\terr := etcdAdapter.Connect()\n\tif err != nil {\n\t\tlogger.Fatal(\"failed-to-connect-to-etcd\", err)\n\t}\n\n\treturn Bbs.NewTPSBBS(etcdAdapter, timeprovider.NewTimeProvider(), logger)\n}\n\nfunc initializeHandler(logger lager.Logger, bbs Bbs.TPSBBS) http.Handler {\n\tapiHandler, err := handler.New(bbs, logger)\n\tif err != nil {\n\t\tlogger.Fatal(\"initialize-handler.failed\", err)\n\t}\n\n\treturn autowire.InstrumentedHandler(apiHandler)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc uploadHandler(w http.ResponseWriter, r *http.Request) {\n\n\tfile, header, err := r.FormFile(\"file\")\n\n\tif err != nil {\n\t\tfmt.Fprintln(w, err)\n\t\treturn\n\t}\n\tdefer file.Close()\n\tlog.Println(\"Incoming: \", header.Filename)\n\n\tout, err := os.Create(path.Join(\"files\", header.Filename))\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Unable to create the file for writing. Check your write access privilege\")\n\t\treturn\n\t}\n\n\tdefer out.Close()\n\n\t_, err = io.Copy(out, file)\n\tif err != nil {\n\t\tfmt.Fprintln(w, err)\n\t}\n\n\tfmt.Fprintf(w, \"File uploaded successfully: \")\n\tfmt.Fprintf(w, header.Filename)\n\tlog.Println(\"Received: \", header.Filename)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \".\/form.html\")\n\t\treturn\n\t})\n\thttp.Handle(\"\/uploads\/\", http.StripPrefix(\"\/files\/\", http.FileServer(http.Dir(\"uploads\"))))\n\thttp.HandleFunc(\"\/post\", uploadHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n<commit_msg>Fix typo<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc uploadHandler(w http.ResponseWriter, r *http.Request) {\n\n\tfile, header, err := r.FormFile(\"file\")\n\n\tif err != nil {\n\t\tfmt.Fprintln(w, err)\n\t\treturn\n\t}\n\tdefer file.Close()\n\tlog.Println(\"Incoming: \", header.Filename)\n\n\tout, err := os.Create(path.Join(\"uploads\", header.Filename))\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Unable to create the file for writing. Check your write access privilege\")\n\t\treturn\n\t}\n\n\tdefer out.Close()\n\n\t_, err = io.Copy(out, file)\n\tif err != nil {\n\t\tfmt.Fprintln(w, err)\n\t}\n\n\tfmt.Fprintf(w, \"File uploaded successfully: \")\n\tfmt.Fprintf(w, header.Filename)\n\tlog.Println(\"Received: \", header.Filename)\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \".\/form.html\")\n\t\treturn\n\t})\n\thttp.Handle(\"\/uploads\/\", http.StripPrefix(\"\/uploads\/\", http.FileServer(http.Dir(\"uploads\"))))\n\thttp.HandleFunc(\"\/post\", uploadHandler)\n\thttp.ListenAndServe(\":8080\", nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\/s3manager\"\n\n\t\"gopkg.in\/asaskevich\/govalidator.v6\"\n)\n\ntype DashboardSearchResult struct {\n\tId    int    `json:\"id\"`\n\tTitle string `json:\"title\"`\n\tUri   string `json:\"uri\"`\n}\n\nfunc httpGet(url string) (*http.Response, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error retrieving dashboards from URL %v: %v\", url, err)\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"Unexpected status code returned from Grafana API (got: %d, expected: 200, msg:%s)\", resp.StatusCode, resp.Status)\n\t}\n\treturn resp, nil\n}\n\nfunc main() {\n\tgrafanaURL := flag.String(\"grafanaURL\", \"\", \"The URL of the grafana server to be backed up\")\n\ts3Bucket := flag.String(\"s3Bucket\", \"\", \"The name of the S3 bucket where the backup should be stored\")\n\tflag.Parse()\n\n\tif *grafanaURL == \"\" || *s3Bucket == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tif !govalidator.IsURL(*grafanaURL) {\n\t\tlog.Fatalf(\"Invalid grafanaURL: %v\", *grafanaURL)\n\t}\n\n\t\/\/ S3 client\n\tsess := session.Must(session.NewSession())\n\tuploader := s3manager.NewUploader(sess)\n\n\tgetAllDashboardsURL := *grafanaURL + \"\/api\/search\"\n\tsearchResults := make([]DashboardSearchResult, 0)\n\tresp, err := httpGet(getAllDashboardsURL)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error retrieving dashboard list from URL %v: %v\", getAllDashboardsURL, err)\n\t}\n\tdefer resp.Body.Close()\n\terr = json.NewDecoder(resp.Body).Decode(&searchResults)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error retrieving decoding response body: %v\", err)\n\t}\n\n\tgetDashBaseURL := *grafanaURL + \"\/api\/dashboards\/\"\n\n\ttimeStr := time.Now().UTC().Format(\"2006-01-02T15:04:05-0700\")\n\tbackupDir := \"grafana-backup_\" + timeStr + \"\/dashboards\/\"\n\tfor _, searchResult := range searchResults {\n\t\t\/\/ retrieve dashboard\n\t\tgetDashURL := getDashBaseURL + searchResult.Uri\n\t\tresp, err := httpGet(getDashURL)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error retrieving dashboard from URL %v: %v\", getDashURL, err)\n\t\t}\n\n\t\t\/\/upload to S3\n\t\tfilename := backupDir + strconv.Itoa(searchResult.Id)\n\t\tui := &s3manager.UploadInput{\n\t\t\tBucket: s3Bucket,\n\t\t\tKey:    &filename,\n\t\t\tBody:   resp.Body,\n\t\t}\n\n\t\t_, err = uploader.Upload(ui)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error uploading dashboard json for dashboard from URL %v: %v\", getDashURL, err)\n\t\t}\n\t\tresp.Body.Close()\n\t}\n\n\tlog.Printf(\"Backup to directory %v in bucket %v completed at %v\", backupDir, s3Bucket, time.Now())\n}\n<commit_msg>remove unused import<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\/s3manager\"\n\n\t\"gopkg.in\/asaskevich\/govalidator.v6\"\n)\n\ntype DashboardSearchResult struct {\n\tId    int    `json:\"id\"`\n\tTitle string `json:\"title\"`\n\tUri   string `json:\"uri\"`\n}\n\nfunc httpGet(url string) (*http.Response, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error retrieving dashboards from URL %v: %v\", url, err)\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"Unexpected status code returned from Grafana API (got: %d, expected: 200, msg:%s)\", resp.StatusCode, resp.Status)\n\t}\n\treturn resp, nil\n}\n\nfunc main() {\n\tgrafanaURL := flag.String(\"grafanaURL\", \"\", \"The URL of the grafana server to be backed up\")\n\ts3Bucket := flag.String(\"s3Bucket\", \"\", \"The name of the S3 bucket where the backup should be stored\")\n\tflag.Parse()\n\n\tif *grafanaURL == \"\" || *s3Bucket == \"\" {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tif !govalidator.IsURL(*grafanaURL) {\n\t\tlog.Fatalf(\"Invalid grafanaURL: %v\", *grafanaURL)\n\t}\n\n\t\/\/ S3 client\n\tsess := session.Must(session.NewSession())\n\tuploader := s3manager.NewUploader(sess)\n\n\tgetAllDashboardsURL := *grafanaURL + \"\/api\/search\"\n\tsearchResults := make([]DashboardSearchResult, 0)\n\tresp, err := httpGet(getAllDashboardsURL)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error retrieving dashboard list from URL %v: %v\", getAllDashboardsURL, err)\n\t}\n\tdefer resp.Body.Close()\n\terr = json.NewDecoder(resp.Body).Decode(&searchResults)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error retrieving decoding response body: %v\", err)\n\t}\n\n\tgetDashBaseURL := *grafanaURL + \"\/api\/dashboards\/\"\n\n\ttimeStr := time.Now().UTC().Format(\"2006-01-02T15:04:05-0700\")\n\tbackupDir := \"grafana-backup_\" + timeStr + \"\/dashboards\/\"\n\tfor _, searchResult := range searchResults {\n\t\t\/\/ retrieve dashboard\n\t\tgetDashURL := getDashBaseURL + searchResult.Uri\n\t\tresp, err := httpGet(getDashURL)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error retrieving dashboard from URL %v: %v\", getDashURL, err)\n\t\t}\n\n\t\t\/\/upload to S3\n\t\tfilename := backupDir + strconv.Itoa(searchResult.Id)\n\t\tui := &s3manager.UploadInput{\n\t\t\tBucket: s3Bucket,\n\t\t\tKey:    &filename,\n\t\t\tBody:   resp.Body,\n\t\t}\n\n\t\t_, err = uploader.Upload(ui)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error uploading dashboard json for dashboard from URL %v: %v\", getDashURL, err)\n\t\t}\n\t\tresp.Body.Close()\n\t}\n\n\tlog.Printf(\"Backup to directory %v in bucket %v completed at %v\", backupDir, s3Bucket, time.Now())\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ `tyu` is a small command line utility to display basic system informations\n\/\/ in the terminal.\npackage main\n\nimport (\n\tui \"github.com\/gizak\/termui\"\n)\n\nfunc main() {\n\t\/\/init termui\n\tif err := ui.Init(); err != nil {\n\t\tpanic(err) \/\/TODO do not panic but manage the error\n\t}\n\tdefer ui.Close()\n\n\t\/\/ display physical RAM and swap memory informations\n\tmemGauge := ui.NewGauge() \/\/TODO try to draw the border around gauge, used, free and total\n\tmemGauge.BorderLabel = \"Memory usage \"\n\tmemGauge.BarColor = ui.ColorBlue\n\tmemGauge.Width = 39\n\tmemGauge.Height = 3\n\tmemGauge.X = 0\n\tmemGauge.Y = 0\n\n\tmemUsed := ui.NewPar(\"Used\")\n\tmemUsed.Height = 1\n\tmemUsed.Width = 13\n\tmemUsed.X = 1\n\tmemUsed.Y = 3\n\tmemUsed.Border = false\n\n\tmemFree := ui.NewPar(\"Free\")\n\tmemFree.Height = 1\n\tmemFree.Width = 13\n\tmemFree.X = 14\n\tmemFree.Y = 3\n\tmemFree.Border = false\n\n\tmemTotal := ui.NewPar(\"Total\")\n\tmemTotal.Height = 1\n\tmemTotal.Width = 13\n\tmemTotal.X = 27\n\tmemTotal.Y = 3\n\tmemTotal.Border = false\n\n\tswapGauge := ui.NewGauge()\n\tswapGauge.BorderLabel = \"Swap usage \"\n\tswapGauge.BarColor = ui.ColorBlue\n\tswapGauge.Width = 39\n\tswapGauge.Height = 3\n\tswapGauge.X = 0\n\tswapGauge.Y = 4\n\n\tswapUsed := ui.NewPar(\"Used\")\n\tswapUsed.Height = 1\n\tswapUsed.Width = 13\n\tswapUsed.X = 1\n\tswapUsed.Y = 7\n\tswapUsed.Border = false\n\n\tswapFree := ui.NewPar(\"Free\")\n\tswapFree.Height = 1\n\tswapFree.Width = 13\n\tswapFree.X = 14\n\tswapFree.Y = 7\n\tswapFree.Border = false\n\n\tswapTotal := ui.NewPar(\"Total\")\n\tswapTotal.Height = 1\n\tswapTotal.Width = 13\n\tswapTotal.X = 27\n\tswapTotal.Y = 7\n\tswapTotal.Border = false\n\n\t\/\/ display informations about the physical disks\n\t\/\/ TODO only two or 3 physical disk add check and a for loop\n\tdisk := getDiskinfo()\n\tdisk1Gauge := ui.NewGauge()\n\tdisk1Gauge.BorderLabel = disk[0].device + \" disk usage \"\n\tdisk1Gauge.BarColor = ui.ColorBlue\n\tdisk1Gauge.Width = 39\n\tdisk1Gauge.Height = 3\n\tdisk1Gauge.X = 0\n\tdisk1Gauge.Y = 8\n\tdisk1Gauge.Percent = disk[0].usedPercent\n\n\tdisk2Gauge := ui.NewGauge()\n\tdisk2Gauge.BorderLabel = disk[1].device + \" disk usage \" \/\/TODO this fail if only one disk\n\tdisk2Gauge.BarColor = ui.ColorBlue\n\tdisk2Gauge.Width = 39\n\tdisk2Gauge.Height = 3\n\tdisk2Gauge.X = 0\n\tdisk2Gauge.Y = 11\n\tdisk2Gauge.Percent = disk[1].usedPercent\n\n\t\/\/ display system informations about the host\n\thost := getHostinfo()\n\thostinfo := ui.NewList()\n\thostinfo.BorderLabel = \"Host \"\n\thostinfo.Items = []string{\n\t\t\"[Hostname         ](fg-cyan)\" + host.hostname,\n\t\t\"[Domain           ](fg-cyan)\" + host.domainname,\n\t\t\"[OS               ](fg-cyan)\" + host.os,\n\t\t\"[OS version       ](fg-cyan)\" + host.osRelease,\n\t\t\"[Platform         ](fg-cyan)\" + host.platform,\n\t\t\"[Platform version ](fg-cyan)\" + host.platformVersion,\n\t\t\"[Architecture     ](fg-cyan)\" + host.arch,\n\t}\n\thostinfo.Width = 39\n\thostinfo.Height = 9\n\thostinfo.X = 40\n\thostinfo.Y = 0\n\n\t\/\/ display informations about the CPUs\n\tcpu := getCPUinfo()\n\tcpuinfo := ui.NewList()\n\tcpuinfo.BorderLabel = \"CPU \"\n\tcpuinfo.Items = []string{\n\t\t\"[CPUs        ](fg-cyan)\" + cpu.count, \/\/TODO review item names compared to other cpu utilities\n\t\t\"[Vendor      ](fg-cyan)\" + cpu.vendorID,\n\t\t\"[Model       ](fg-cyan)\" + cpu.modelName, \/\/TODO use refreshing rate to display roll long text ?\n\t\t\"[Speed       ](fg-cyan)\" + cpu.cpuMhz + \" Mhz\",\n\t\t\"[Temperature ](fg-cyan)\", \/\/TODO\n\t}\n\tcpuinfo.Width = 39\n\tcpuinfo.Height = 7\n\tcpuinfo.X = 40\n\tcpuinfo.Y = 9\n\n\t\/\/ display bios and motherboard informations\n\tbios := getBIOSinfo()\n\tbiosinfo := ui.NewList()\n\tbiosinfo.BorderLabel = \"BIOS \"\n\tbiosinfo.Items = []string{\n\t\t\"[Motherboard ](fg-cyan)\" + bios.boardName,\n\t\t\"[Vendor      ](fg-cyan)\" + bios.boardVendor,\n\t\t\"[BIOS        ](fg-cyan)\" + bios.biosVendor,\n\t\t\"[Version     ](fg-cyan)\" + bios.biosVersion + \"  \" + bios.biosDate,\n\t}\n\tbiosinfo.Width = 39\n\tbiosinfo.Height = 6\n\tbiosinfo.X = 40\n\tbiosinfo.Y = 16\n\n\t\/\/ display a quit help text\n\tquit := ui.NewPar(\"[Type 'q' to exit](fg-white,bg-blue)\")\n\tquit.Height = 1\n\tquit.Width = 39\n\tquit.X = 1\n\tquit.Y = 23\n\tquit.Border = false\n\n\t\/\/ render the dashboard with 26x80 fixed size\n\tdraw := func(t int) {\n\t\t\/\/ update memory informations\n\t\tmem := getMeminfo()\n\t\tmemGauge.Percent = mem.memUsedPercent\n\t\tmemUsed.Text = \"[Used](fg-cyan) \" + mem.memUsed + \"MB\"\n\t\tmemFree.Text = \"[Free](fg-cyan) \" + mem.memFree + \"MB\"\n\t\tmemTotal.Text = \"[Total](fg-cyan) \" + mem.memTotal + \"MB\"\n\t\tswapGauge.Percent = mem.swapUsedPercent\n\t\tswapUsed.Text = \"[Used](fg-cyan) \" + mem.swapUsed + \"MB\"\n\t\tswapFree.Text = \"[Free](fg-cyan) \" + mem.swapFree + \"MB\"\n\t\tswapTotal.Text = \"[Total](fg-cyan) \" + mem.swapTotal + \"MB\"\n\n\t\tui.Render(\n\t\t\tmemGauge,\n\t\t\tmemUsed,\n\t\t\tmemFree,\n\t\t\tmemTotal,\n\t\t\tswapGauge,\n\t\t\tswapUsed,\n\t\t\tswapFree,\n\t\t\tswapTotal,\n\t\t\tdisk1Gauge, \/\/TODO rename and or stack gauges together\n\t\t\tdisk2Gauge, \/\/TODO rename\n\t\t\thostinfo,\n\t\t\tcpuinfo,\n\t\t\tbiosinfo,\n\t\t\tquit,\n\t\t)\n\t}\n\n\t\/\/ quit on `q` keystroke handler\n\tui.Handle(\"\/sys\/kbd\/q\", func(ui.Event) {\n\t\tui.StopLoop()\n\t})\n\t\/\/ quit on `CTRL+c` keystroke handler\n\tui.Handle(\"\/sys\/kbd\/C-c\", func(ui.Event) {\n\t\tui.StopLoop()\n\t})\n\t\/\/ timer handler to refresh every second\n\tui.Handle(\"\/timer\/1s\", func(e ui.Event) {\n\t\tt := e.Data.(ui.EvtTimer)\n\t\tdraw(int(t.Count))\n\t})\n\tui.Loop()\n}\n\n\/\/ the dashboard is 26x80\n<commit_msg>Update dashboard display<commit_after>\/\/ `tyu` is a small command line utility to display basic system informations\n\/\/ in the terminal.\npackage main\n\nimport (\n\tui \"github.com\/gizak\/termui\"\n)\n\nfunc main() {\n\t\/\/init termui\n\tif err := ui.Init(); err != nil {\n\t\tpanic(err) \/\/TODO do not panic but manage the error\n\t}\n\tdefer ui.Close()\n\n\t\/\/ display physical RAM and swap memory informations\n\tmemGauge := ui.NewGauge() \/\/TODO try to draw the border around gauge, used, free and total\n\tmemGauge.BorderLabel = \"Memory usage \"\n\tmemGauge.BarColor = ui.ColorBlue\n\tmemGauge.Width = 39\n\tmemGauge.Height = 3\n\tmemGauge.X = 0\n\tmemGauge.Y = 0\n\n\tmemUsed := ui.NewPar(\"Used\")\n\tmemUsed.Height = 1\n\tmemUsed.Width = 13\n\tmemUsed.X = 1\n\tmemUsed.Y = 3\n\tmemUsed.Border = false\n\n\tmemFree := ui.NewPar(\"Free\")\n\tmemFree.Height = 1\n\tmemFree.Width = 13\n\tmemFree.X = 14\n\tmemFree.Y = 3\n\tmemFree.Border = false\n\n\tmemTotal := ui.NewPar(\"Total\")\n\tmemTotal.Height = 1\n\tmemTotal.Width = 13\n\tmemTotal.X = 27\n\tmemTotal.Y = 3\n\tmemTotal.Border = false\n\n\tswapGauge := ui.NewGauge()\n\tswapGauge.BorderLabel = \"Swap usage \"\n\tswapGauge.BarColor = ui.ColorBlue\n\tswapGauge.Width = 39\n\tswapGauge.Height = 3\n\tswapGauge.X = 0\n\tswapGauge.Y = 4\n\n\tswapUsed := ui.NewPar(\"Used\")\n\tswapUsed.Height = 1\n\tswapUsed.Width = 13\n\tswapUsed.X = 1\n\tswapUsed.Y = 7\n\tswapUsed.Border = false\n\n\tswapFree := ui.NewPar(\"Free\")\n\tswapFree.Height = 1\n\tswapFree.Width = 13\n\tswapFree.X = 14\n\tswapFree.Y = 7\n\tswapFree.Border = false\n\n\tswapTotal := ui.NewPar(\"Total\")\n\tswapTotal.Height = 1\n\tswapTotal.Width = 13\n\tswapTotal.X = 27\n\tswapTotal.Y = 7\n\tswapTotal.Border = false\n\n\tcpuGauge := ui.NewGauge()\n\tcpuGauge.BorderLabel = \"CPU usage \"\n\tcpuGauge.BarColor = ui.ColorBlue\n\tcpuGauge.Width = 39\n\tcpuGauge.Height = 3\n\tcpuGauge.X = 0\n\tcpuGauge.Y = 8\n\n\t\/\/ display informations about the physical disks\n\t\/\/ TODO only two or 3 physical disk add check and a for loop\n\tdisk := getDiskinfo()\n\tdisk1Gauge := ui.NewGauge()\n\tdisk1Gauge.BorderLabel = disk[0].device + \" disk usage \"\n\tdisk1Gauge.BarColor = ui.ColorBlue\n\tdisk1Gauge.Width = 39\n\tdisk1Gauge.Height = 3\n\tdisk1Gauge.X = 0\n\tdisk1Gauge.Y = 11\n\tdisk1Gauge.Percent = disk[0].usedPercent\n\n\tdisk2Gauge := ui.NewGauge()\n\tdisk2Gauge.BorderLabel = disk[1].device + \" disk usage \" \/\/TODO this fail if only one disk\n\tdisk2Gauge.BarColor = ui.ColorBlue\n\tdisk2Gauge.Width = 39\n\tdisk2Gauge.Height = 3\n\tdisk2Gauge.X = 0\n\tdisk2Gauge.Y = 14\n\tdisk2Gauge.Percent = disk[1].usedPercent\n\n\t\/\/ display system informations about the host\n\thost := getHostinfo()\n\thostinfo := ui.NewList()\n\thostinfo.BorderLabel = \"Host \"\n\thostinfo.Items = []string{\n\t\t\"[Hostname         ](fg-cyan)\" + host.hostname,\n\t\t\"[Domain           ](fg-cyan)\" + host.domainname,\n\t\t\"[OS               ](fg-cyan)\" + host.os,\n\t\t\"[OS version       ](fg-cyan)\" + host.osRelease,\n\t\t\"[Platform         ](fg-cyan)\" + host.platform,\n\t\t\"[Platform version ](fg-cyan)\" + host.platformVersion,\n\t\t\"[Architecture     ](fg-cyan)\" + host.arch,\n\t}\n\thostinfo.Width = 39\n\thostinfo.Height = 9\n\thostinfo.X = 40\n\thostinfo.Y = 0\n\n\t\/\/ display informations about the CPUs\n\tcpu := getCPUinfo()\n\tcpuinfo := ui.NewList()\n\tcpuinfo.BorderLabel = \"CPU \"\n\tcpuinfo.Items = []string{\n\t\t\"[CPUs        ](fg-cyan)\" + cpu.count, \/\/TODO review item names compared to other cpu utilities\n\t\t\"[Vendor      ](fg-cyan)\" + cpu.vendorID,\n\t\t\"[Model       ](fg-cyan)\" + cpu.modelName, \/\/TODO use refreshing rate to display roll long text ?\n\t\t\"[Speed       ](fg-cyan)\" + cpu.cpuMhz + \" Mhz\",\n\t\t\"[Temperature ](fg-cyan)\", \/\/TODO\n\t}\n\tcpuinfo.Width = 39\n\tcpuinfo.Height = 7\n\tcpuinfo.X = 40\n\tcpuinfo.Y = 9\n\n\t\/\/ display bios and motherboard informations\n\tbios := getBIOSinfo()\n\tbiosinfo := ui.NewList()\n\tbiosinfo.BorderLabel = \"BIOS \"\n\tbiosinfo.Items = []string{\n\t\t\"[Motherboard ](fg-cyan)\" + bios.boardName,\n\t\t\"[Vendor      ](fg-cyan)\" + bios.boardVendor,\n\t\t\"[BIOS        ](fg-cyan)\" + bios.biosVendor,\n\t\t\"[Version     ](fg-cyan)\" + bios.biosVersion + \"  \" + bios.biosDate,\n\t}\n\tbiosinfo.Width = 39\n\tbiosinfo.Height = 6\n\tbiosinfo.X = 40\n\tbiosinfo.Y = 16\n\n\t\/\/ display a quit help text\n\tquit := ui.NewPar(\"[Type 'q' to exit](fg-white,bg-blue)\")\n\tquit.Height = 1\n\tquit.Width = 39\n\tquit.X = 1\n\tquit.Y = 23\n\tquit.Border = false\n\n\t\/\/ render the dashboard with 26x80 fixed size\n\tdraw := func(t int) {\n\t\t\/\/ update memory informations\n\t\tmem := getMeminfo()\n\t\tmemGauge.Percent = mem.memUsedPercent\n\t\tmemUsed.Text = \"[Used](fg-cyan) \" + mem.memUsed + \"MB\"\n\t\tmemFree.Text = \"[Free](fg-cyan) \" + mem.memFree + \"MB\"\n\t\tmemTotal.Text = \"[Total](fg-cyan) \" + mem.memTotal + \"MB\"\n\t\tswapGauge.Percent = mem.swapUsedPercent\n\t\tswapUsed.Text = \"[Used](fg-cyan) \" + mem.swapUsed + \"MB\"\n\t\tswapFree.Text = \"[Free](fg-cyan) \" + mem.swapFree + \"MB\"\n\t\tswapTotal.Text = \"[Total](fg-cyan) \" + mem.swapTotal + \"MB\"\n\n\t\tcpuGauge.Percent = getCPUpercent()\n\n\t\tui.Render(\n\t\t\tmemGauge,\n\t\t\tmemUsed,\n\t\t\tmemFree,\n\t\t\tmemTotal,\n\t\t\tswapGauge,\n\t\t\tswapUsed,\n\t\t\tswapFree,\n\t\t\tswapTotal,\n\t\t\tcpuGauge,\n\t\t\tdisk1Gauge, \/\/TODO rename and or stack gauges together\n\t\t\tdisk2Gauge, \/\/TODO rename\n\t\t\thostinfo,\n\t\t\tcpuinfo,\n\t\t\tbiosinfo,\n\t\t\tquit,\n\t\t)\n\t}\n\n\t\/\/ quit on `q` keystroke handler\n\tui.Handle(\"\/sys\/kbd\/q\", func(ui.Event) {\n\t\tui.StopLoop()\n\t})\n\t\/\/ quit on `CTRL+c` keystroke handler\n\tui.Handle(\"\/sys\/kbd\/C-c\", func(ui.Event) {\n\t\tui.StopLoop()\n\t})\n\t\/\/ timer handler to refresh every second\n\tui.Handle(\"\/timer\/1s\", func(e ui.Event) {\n\t\tt := e.Data.(ui.EvtTimer)\n\t\tdraw(int(t.Count))\n\t})\n\tui.Loop()\n}\n\n\/\/ the dashboard is 26x80\n<|endoftext|>"}
{"text":"<commit_before>\/*\nThis program takes a list of domains and queries each against the OpenDNS\nInvestigate API, optionally outputting a CSV file.\n\nBecause querying every endpoint can be very time consuming, this program uses\na TOML file to configure which information should be queried.\n\nFor full documentation of usage, see the GitHub page:\nhttps:\/\/github.com\/dead10ck\/domainstats\n*\/\npackage main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/csv\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"sync\"\n\n\tdomainstats \"github.com\/dead10ck\/domainstats\/lib\"\n\t\"github.com\/dead10ck\/goinvestigate\"\n)\n\ntype opt struct {\n\tverbose       bool\n\tsetup         string\n\toutFile       string\n\tconfigPath    string\n\tmaxGoroutines int\n}\n\nvar (\n\topts       opt\n\tnumDomains int\n)\n\nconst (\n\tDEFAULT_MAX_GOROUTINES = 5\n)\n\nfunc init() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n}\n\nfunc main() {\n\n\tflag.IntVar(&opts.maxGoroutines, \"m\", DEFAULT_MAX_GOROUTINES,\n\t\t\"Maximum number of goroutines to use for parallel HTTP requests\")\n\tflag.BoolVar(&opts.verbose, \"v\", false, \"Print out verbose log messages.\")\n\tflag.StringVar(&opts.setup, \"setup\", \"\",\n\t\t\"Generate a default config file in ~\/.domainstats\/default.toml with\"+\n\t\t\t\" the given API key.\")\n\tflag.StringVar(&opts.outFile, \"out\", \"\", \"Output matching IPs to the given file\")\n\tflag.StringVar(&opts.configPath, \"c\", domainstats.DefaultConfigPath, \"The config file to use\")\n\tflag.Parse()\n\n\tif opts.setup != \"\" {\n\t\terr := domainstats.GenerateDefaultConfig(opts.setup)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"error creating default config file: %v\", err)\n\t\t}\n\n\t\tfmt.Printf(fmt.Sprintf(\"Config file generated in %s\\n\", domainstats.DefaultConfigPath))\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ if the default config file does not exist and the user did not specify\n\t\/\/ a different config file, then the program cannot proceed\n\tif _, err := os.Stat(domainstats.DefaultConfigPath); os.IsNotExist(err) && opts.configPath == domainstats.DefaultConfigPath {\n\t\tlog.Fatal(\"Default config file missing, and no other config file specified.\" +\n\t\t\t\" Please run domainstats with the -setup option to set up a default \" +\n\t\t\t\"config file.\")\n\t}\n\n\tconfig, err := domainstats.NewConfig(opts.configPath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar outWriter *csv.Writer\n\tinv := goinvestigate.New(config.APIKey)\n\tdomainListFileName := flag.Arg(flag.NArg() - 1)\n\tif domainListFileName == \"\" {\n\t\tfmt.Println(\"Need a file name\")\n\t\tos.Exit(-1)\n\t}\n\tinChan := readDomainsFrom(domainListFileName)\n\n\tif opts.verbose {\n\t\tinv.SetVerbose(true)\n\t}\n\n\tif opts.outFile != \"\" {\n\t\toutFile, err := os.Create(opts.outFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\toutWriter = csv.NewWriter(outFile)\n\t\toutWriter.Comma = rune('\\t')\n\t\toutWriter.Write(config.DeriveHeader())\n\t\tdefer func() {\n\t\t\toutWriter.Flush()\n\t\t\toutFile.Close()\n\t\t}()\n\t}\n\n\toutChan := getInfo(config, inv, inChan)\n\tmainWg := new(sync.WaitGroup)\n\n\tmainWg.Add(1)\n\tgo writeOut(outWriter, outChan, mainWg)\n\n\tmainWg.Wait()\n}\n\nfunc writeOut(outWriter *csv.Writer, outChan <-chan []string, wg *sync.WaitGroup) {\n\tnumProcessed := 0\n\tmsgChan := make(chan string, 10)\n\tgo printStdOut(msgChan)\n\n\tfor respRow := range outChan {\n\t\tnumProcessed++\n\t\tmsgChan <- fmt.Sprintf(\"\\r%d\/%d: %s\", numProcessed, numDomains, respRow[0])\n\t\tif outWriter != nil {\n\t\t\toutWriter.Write(respRow)\n\t\t}\n\t}\n\n\tclose(msgChan)\n\twg.Done()\n}\n\nfunc printStdOut(msgChan <-chan string) {\n\tfor msg := range msgChan {\n\t\tfmt.Printf(\"\\r%120s\", \" \")\n\t\tfmt.Print(msg)\n\t}\n\tfmt.Println()\n}\n\n\/\/ The goroutine which does the HTTP queries\nfunc query(qChan <-chan *domainstats.DomainQueryMessage) {\n\tfor m := range qChan {\n\t\tm.RespChan <- m.Q.Query()\n\t}\n}\n\nfunc process(inv *goinvestigate.Investigate, config *domainstats.Config,\n\tdomainChan <-chan string,\n\tqChan chan<- *domainstats.DomainQueryMessage,\n\toutChan chan<- []string,\n\twg *sync.WaitGroup) {\n\ndomainLoop:\n\tfor domain := range domainChan {\n\n\t\t\/\/ generate the list of queries to make for each domain\n\t\tqueries := config.DeriveMessages(inv, domain)\n\n\t\t\/\/ send each query on the query channel for the query goroutines\n\t\t\/\/ to receive\n\t\tfor _, q := range queries {\n\t\t\tqChan <- q\n\t\t}\n\n\t\trow := []string{domain}\n\t\t\/\/ receive once for each query that was sent\n\t\tfor _, q := range queries {\n\t\t\tqmResp := <-q.RespChan\n\t\t\tif qmResp.Err != nil {\n\t\t\t\tlog.Printf(\"error during query for %v: %v\\nskipping this domain\",\n\t\t\t\t\tdomain, qmResp.Err)\n\t\t\t\tcontinue domainLoop\n\t\t\t}\n\t\t\tsubRow, err := config.ExtractCSVSubRow(qmResp.Resp)\n\t\t\tif err != nil {\n\t\t\t\tinv.Logf(\"error extracting CSV sub row: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trow = append(row, subRow...)\n\t\t}\n\n\t\toutChan <- row\n\t}\n\twg.Done()\n}\n\nfunc getInfo(config *domainstats.Config, inv *goinvestigate.Investigate, domainChan <-chan string) <-chan []string {\n\toutChan := make(chan []string, 100)\n\tqChan := make(chan *domainstats.DomainQueryMessage)\n\twg := new(sync.WaitGroup)\n\n\t\/\/ launch the query goroutines\n\tfor i := 0; i < opts.maxGoroutines; i++ {\n\t\tgo query(qChan)\n\t}\n\n\t\/\/ launch the processor goroutines\n\tfor i := 0; i < opts.maxGoroutines; i++ {\n\t\twg.Add(1)\n\t\tgo process(inv, config, domainChan, qChan, outChan, wg)\n\t}\n\n\t\/\/ launch a goroutine which closes the output channel when the processor\n\t\/\/ goroutines are finished\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(qChan)\n\t\tclose(outChan)\n\t}()\n\n\treturn outChan\n}\n\nfunc readDomainsFrom(fName string) <-chan string {\n\tfile, err := os.Open(fName)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"\\nError opening domain list %s: %v\\n\", fName, err)\n\t}\n\n\tdomainChan := make(chan string, 100)\n\n\tscanner := bufio.NewScanner(file)\n\n\tgo func() {\n\t\tfor scanner.Scan() {\n\t\t\tdomainChan <- scanner.Text()\n\t\t\tnumDomains++\n\t\t}\n\t\tclose(domainChan)\n\t}()\n\n\treturn domainChan\n}\n<commit_msg>Close the input file when done<commit_after>\/*\nThis program takes a list of domains and queries each against the OpenDNS\nInvestigate API, optionally outputting a CSV file.\n\nBecause querying every endpoint can be very time consuming, this program uses\na TOML file to configure which information should be queried.\n\nFor full documentation of usage, see the GitHub page:\nhttps:\/\/github.com\/dead10ck\/domainstats\n*\/\npackage main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/csv\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"sync\"\n\n\tdomainstats \"github.com\/dead10ck\/domainstats\/lib\"\n\t\"github.com\/dead10ck\/goinvestigate\"\n)\n\ntype opt struct {\n\tverbose       bool\n\tsetup         string\n\toutFile       string\n\tconfigPath    string\n\tmaxGoroutines int\n}\n\nvar (\n\topts       opt\n\tnumDomains int\n)\n\nconst (\n\tDEFAULT_MAX_GOROUTINES = 5\n)\n\nfunc init() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n}\n\nfunc main() {\n\n\tflag.IntVar(&opts.maxGoroutines, \"m\", DEFAULT_MAX_GOROUTINES,\n\t\t\"Maximum number of goroutines to use for parallel HTTP requests\")\n\tflag.BoolVar(&opts.verbose, \"v\", false, \"Print out verbose log messages.\")\n\tflag.StringVar(&opts.setup, \"setup\", \"\",\n\t\t\"Generate a default config file in ~\/.domainstats\/default.toml with\"+\n\t\t\t\" the given API key.\")\n\tflag.StringVar(&opts.outFile, \"out\", \"\", \"Output matching IPs to the given file\")\n\tflag.StringVar(&opts.configPath, \"c\", domainstats.DefaultConfigPath, \"The config file to use\")\n\tflag.Parse()\n\n\tif opts.setup != \"\" {\n\t\terr := domainstats.GenerateDefaultConfig(opts.setup)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"error creating default config file: %v\", err)\n\t\t}\n\n\t\tfmt.Printf(fmt.Sprintf(\"Config file generated in %s\\n\", domainstats.DefaultConfigPath))\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ if the default config file does not exist and the user did not specify\n\t\/\/ a different config file, then the program cannot proceed\n\tif _, err := os.Stat(domainstats.DefaultConfigPath); os.IsNotExist(err) && opts.configPath == domainstats.DefaultConfigPath {\n\t\tlog.Fatal(\"Default config file missing, and no other config file specified.\" +\n\t\t\t\" Please run domainstats with the -setup option to set up a default \" +\n\t\t\t\"config file.\")\n\t}\n\n\tconfig, err := domainstats.NewConfig(opts.configPath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar outWriter *csv.Writer\n\tinv := goinvestigate.New(config.APIKey)\n\tdomainListFileName := flag.Arg(flag.NArg() - 1)\n\tif domainListFileName == \"\" {\n\t\tfmt.Println(\"Need a file name\")\n\t\tos.Exit(-1)\n\t}\n\tinChan := readDomainsFrom(domainListFileName)\n\n\tif opts.verbose {\n\t\tinv.SetVerbose(true)\n\t}\n\n\tif opts.outFile != \"\" {\n\t\toutFile, err := os.Create(opts.outFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\toutWriter = csv.NewWriter(outFile)\n\t\toutWriter.Comma = rune('\\t')\n\t\toutWriter.Write(config.DeriveHeader())\n\t\tdefer func() {\n\t\t\toutWriter.Flush()\n\t\t\toutFile.Close()\n\t\t}()\n\t}\n\n\toutChan := getInfo(config, inv, inChan)\n\tmainWg := new(sync.WaitGroup)\n\n\tmainWg.Add(1)\n\tgo writeOut(outWriter, outChan, mainWg)\n\n\tmainWg.Wait()\n}\n\nfunc writeOut(outWriter *csv.Writer, outChan <-chan []string, wg *sync.WaitGroup) {\n\tnumProcessed := 0\n\tmsgChan := make(chan string, 10)\n\tgo printStdOut(msgChan)\n\n\tfor respRow := range outChan {\n\t\tnumProcessed++\n\t\tmsgChan <- fmt.Sprintf(\"\\r%d\/%d: %s\", numProcessed, numDomains, respRow[0])\n\t\tif outWriter != nil {\n\t\t\toutWriter.Write(respRow)\n\t\t}\n\t}\n\n\tclose(msgChan)\n\twg.Done()\n}\n\nfunc printStdOut(msgChan <-chan string) {\n\tfor msg := range msgChan {\n\t\tfmt.Printf(\"\\r%120s\", \" \")\n\t\tfmt.Print(msg)\n\t}\n\tfmt.Println()\n}\n\n\/\/ The goroutine which does the HTTP queries\nfunc query(qChan <-chan *domainstats.DomainQueryMessage) {\n\tfor m := range qChan {\n\t\tm.RespChan <- m.Q.Query()\n\t}\n}\n\nfunc process(inv *goinvestigate.Investigate, config *domainstats.Config,\n\tdomainChan <-chan string,\n\tqChan chan<- *domainstats.DomainQueryMessage,\n\toutChan chan<- []string,\n\twg *sync.WaitGroup) {\n\ndomainLoop:\n\tfor domain := range domainChan {\n\n\t\t\/\/ generate the list of queries to make for each domain\n\t\tqueries := config.DeriveMessages(inv, domain)\n\n\t\t\/\/ send each query on the query channel for the query goroutines\n\t\t\/\/ to receive\n\t\tfor _, q := range queries {\n\t\t\tqChan <- q\n\t\t}\n\n\t\trow := []string{domain}\n\t\t\/\/ receive once for each query that was sent\n\t\tfor _, q := range queries {\n\t\t\tqmResp := <-q.RespChan\n\t\t\tif qmResp.Err != nil {\n\t\t\t\tlog.Printf(\"error during query for %v: %v\\nskipping this domain\",\n\t\t\t\t\tdomain, qmResp.Err)\n\t\t\t\tcontinue domainLoop\n\t\t\t}\n\t\t\tsubRow, err := config.ExtractCSVSubRow(qmResp.Resp)\n\t\t\tif err != nil {\n\t\t\t\tinv.Logf(\"error extracting CSV sub row: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trow = append(row, subRow...)\n\t\t}\n\n\t\toutChan <- row\n\t}\n\twg.Done()\n}\n\nfunc getInfo(config *domainstats.Config, inv *goinvestigate.Investigate, domainChan <-chan string) <-chan []string {\n\toutChan := make(chan []string, 100)\n\tqChan := make(chan *domainstats.DomainQueryMessage)\n\twg := new(sync.WaitGroup)\n\n\t\/\/ launch the query goroutines\n\tfor i := 0; i < opts.maxGoroutines; i++ {\n\t\tgo query(qChan)\n\t}\n\n\t\/\/ launch the processor goroutines\n\tfor i := 0; i < opts.maxGoroutines; i++ {\n\t\twg.Add(1)\n\t\tgo process(inv, config, domainChan, qChan, outChan, wg)\n\t}\n\n\t\/\/ launch a goroutine which closes the output channel when the processor\n\t\/\/ goroutines are finished\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(qChan)\n\t\tclose(outChan)\n\t}()\n\n\treturn outChan\n}\n\nfunc readDomainsFrom(fName string) <-chan string {\n\tfile, err := os.Open(fName)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"\\nError opening domain list %s: %v\\n\", fName, err)\n\t}\n\n\tdomainChan := make(chan string, 100)\n\n\tscanner := bufio.NewScanner(file)\n\n\tgo func() {\n\t\tfor scanner.Scan() {\n\t\t\tdomainChan <- scanner.Text()\n\t\t\tnumDomains++\n\t\t}\n\t\tclose(domainChan)\n\t\tfile.Close()\n\t}()\n\n\treturn domainChan\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"database\/sql\"\n\t\"flag\"\n\t\"fmt\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"sync\"\n)\n\nconst (\n\t\/\/ Timeout for DNS queries\n\ttimeout = 3 * 1e9\n\n\t\/\/ maximum number of attempts for a query\n\tmaxAttempts = 3\n)\n\nvar (\n\tpending         = make(chan *job, 100)\n\tfinished        = make(chan *job, 100)\n\tdone            sync.WaitGroup\n\tworkersCount    = 1\n\treferenceServer = \"8.8.8.8\"\n\tconnection      string\n\tdomainArg       string\n)\n\nfunc main() {\n\tdatabaseArg := flag.String(\"database\", \"database.yml\", \"Path to file containing the database configuration\")\n\tflag.StringVar(&domainArg, \"domains\", \"domains.txt\", \"Path to file containing the domain list\")\n\tflag.StringVar(&geoDbPath, \"geodb\", \"GeoLite2-City.mmdb\", \"Path to GeoDB database\")\n\tflag.StringVar(&referenceServer, \"reference\", referenceServer, \"The nameserver that every other is compared with\")\n\tworkersPerCore := flag.Int(\"workers-per-core\", 8, \"Number of worker routines per CPU core\")\n\tflag.Parse()\n\n\tdnsClient.ReadTimeout = timeout\n\n\tenvironment := os.Getenv(\"RAILS_ENV\")\n\tif environment == \"\" {\n\t\tenvironment = \"development\"\n\t}\n\n\t\/\/ read domain list\n\tif err := readDomains(domainArg); err != nil {\n\t\tfmt.Println(\"unable to read domain list\")\n\t\tpanic(err)\n\t}\n\n\t\/\/ load database configuration\n\tconnection = databasePath(*databaseArg, environment)\n\n\t\/\/ check the GeoDB\n\tlocation(referenceServer)\n\n\t\/\/ Use all cores\n\tcpuCount := runtime.NumCPU()\n\truntime.GOMAXPROCS(cpuCount)\n\n\tworkersCount = *workersPerCore * cpuCount\n\tfmt.Println(\"Starting\", workersCount, \"workers\")\n\tdone.Add(workersCount)\n\n\t\/\/ Get results from the reference nameserver\n\tres, err := resolveDomains(referenceServer)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\texpectedResults = res\n\n\t\/\/ Start result writer\n\tgo resultWriter()\n\n\t\/\/ Start workers\n\tfor i := 0; i < workersCount; i++ {\n\t\tgo worker()\n\t}\n\n\tcreateJobs()\n\n\t\/\/ wait for workers to finish\n\tdone.Wait()\n\n\tclose(finished)\n}\n\nfunc createJobs() {\n\tcurrentId := 0\n\tbatchSize := 1000\n\tfound := batchSize\n\n\t\/\/ Open SQL connection\n\tdb, err := sql.Open(\"mysql\", connection)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer db.Close()\n\n\tfor batchSize == found {\n\t\t\/\/ Read the next batch\n\t\trows, err := db.Query(\"SELECT id, ip FROM nameservers WHERE id > ? LIMIT ?\", currentId, batchSize)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfound = 0\n\t\tfor rows.Next() {\n\t\t\tj := new(job)\n\n\t\t\t\/\/ get RawBytes from data\n\t\t\terr = rows.Scan(&j.id, &j.address)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tpending <- j\n\t\t\tcurrentId = j.id\n\t\t\tfound += 1\n\t\t}\n\t\trows.Close()\n\t}\n\tclose(pending)\n}\n\nfunc worker() {\n\tfor job := range pending {\n\t\texecuteJob(job)\n\t\tfinished <- job\n\t}\n\tdone.Done()\n}\n\nfunc resultWriter() {\n\t\/\/ Open SQL connection\n\tdb, err := sql.Open(\"mysql\", connection)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer db.Close()\n\n\tstm, err := db.Prepare(\n\t\t\"UPDATE nameservers SET name=?, state=?, error=?, version=?, checked_at=NOW(), country_id=?, city=?,\" +\n\t\t\t\"state_changed_at = (CASE WHEN ? != state THEN NOW() ELSE state_changed_at END )\" +\n\t\t\t\"WHERE id=?\")\n\tdefer stm.Close()\n\n\tfor res := range finished {\n\t\tlog.Println(res)\n\t\tstm.Exec(res.name, res.state, res.err, res.version, res.country, res.city, res.state, res.id)\n\t}\n}\n\n\/\/ consumes a job and writes the result in the given job\nfunc executeJob(job *job) {\n\t\/\/ log.Println(\"received job\", job.id)\n\n\t\/\/ GeoDB lookup\n\tjob.country, job.city = location(job.address)\n\n\t\/\/ Run the check\n\terr := check(job)\n\tjob.name = ptrName(job.address)\n\n\t\/\/ query the bind version\n\tif err == nil || err.Error() != \"i\/o timeout\" {\n\t\tjob.version = version(job.address)\n\t}\n\n\tif err == nil {\n\t\tjob.state = \"valid\"\n\t\tjob.err = \"\"\n\t} else {\n\t\tjob.state = \"invalid\"\n\t\tjob.err = err.Error()\n\t}\n}\n<commit_msg>Simplfy workers setting<commit_after>package main\n\nimport (\n\t\"database\/sql\"\n\t\"flag\"\n\t\"fmt\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"log\"\n\t\"os\"\n\t\"sync\"\n)\n\nconst (\n\t\/\/ Timeout for DNS queries\n\ttimeout = 3 * 1e9\n\n\t\/\/ maximum number of attempts for a query\n\tmaxAttempts = 3\n)\n\nvar (\n\tpending         = make(chan *job, 100)\n\tfinished        = make(chan *job, 100)\n\tdone            sync.WaitGroup\n\tworkersCount    = 32\n\treferenceServer = \"8.8.8.8\"\n\tconnection      string\n\tdomainArg       string\n)\n\nfunc main() {\n\tdatabaseArg := flag.String(\"database\", \"database.yml\", \"Path to file containing the database configuration\")\n\tflag.StringVar(&domainArg, \"domains\", \"domains.txt\", \"Path to file containing the domain list\")\n\tflag.StringVar(&geoDbPath, \"geodb\", \"GeoLite2-City.mmdb\", \"Path to GeoDB database\")\n\tflag.StringVar(&referenceServer, \"reference\", referenceServer, \"The nameserver that every other is compared with\")\n\tflag.IntVar(&workersCount, \"workers\", workersCount, \"Number of worker routines\")\n\tflag.Parse()\n\n\tdnsClient.ReadTimeout = timeout\n\n\tenvironment := os.Getenv(\"RAILS_ENV\")\n\tif environment == \"\" {\n\t\tenvironment = \"development\"\n\t}\n\n\t\/\/ read domain list\n\tif err := readDomains(domainArg); err != nil {\n\t\tfmt.Println(\"unable to read domain list\")\n\t\tpanic(err)\n\t}\n\n\t\/\/ load database configuration\n\tconnection = databasePath(*databaseArg, environment)\n\n\t\/\/ check the GeoDB\n\tlocation(referenceServer)\n\n\t\/\/ Use all cores\n\n\t\/\/ Get results from the reference nameserver\n\tres, err := resolveDomains(referenceServer)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\texpectedResults = res\n\n\t\/\/ Start result writer\n\tgo resultWriter()\n\n\t\/\/ Start workers\n\tdone.Add(workersCount)\n\tfor i := 0; i < workersCount; i++ {\n\t\tgo worker()\n\t}\n\n\tcreateJobs()\n\n\t\/\/ wait for workers to finish\n\tdone.Wait()\n\n\tclose(finished)\n}\n\nfunc createJobs() {\n\tcurrentId := 0\n\tbatchSize := 1000\n\tfound := batchSize\n\n\t\/\/ Open SQL connection\n\tdb, err := sql.Open(\"mysql\", connection)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer db.Close()\n\n\tfor batchSize == found {\n\t\t\/\/ Read the next batch\n\t\trows, err := db.Query(\"SELECT id, ip FROM nameservers WHERE id > ? LIMIT ?\", currentId, batchSize)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfound = 0\n\t\tfor rows.Next() {\n\t\t\tj := new(job)\n\n\t\t\t\/\/ get RawBytes from data\n\t\t\terr = rows.Scan(&j.id, &j.address)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tpending <- j\n\t\t\tcurrentId = j.id\n\t\t\tfound += 1\n\t\t}\n\t\trows.Close()\n\t}\n\tclose(pending)\n}\n\nfunc worker() {\n\tfor job := range pending {\n\t\texecuteJob(job)\n\t\tfinished <- job\n\t}\n\tdone.Done()\n}\n\nfunc resultWriter() {\n\t\/\/ Open SQL connection\n\tdb, err := sql.Open(\"mysql\", connection)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer db.Close()\n\n\tstm, err := db.Prepare(\n\t\t\"UPDATE nameservers SET name=?, state=?, error=?, version=?, checked_at=NOW(), country_id=?, city=?,\" +\n\t\t\t\"state_changed_at = (CASE WHEN ? != state THEN NOW() ELSE state_changed_at END )\" +\n\t\t\t\"WHERE id=?\")\n\tdefer stm.Close()\n\n\tfor res := range finished {\n\t\tlog.Println(res)\n\t\tstm.Exec(res.name, res.state, res.err, res.version, res.country, res.city, res.state, res.id)\n\t}\n}\n\n\/\/ consumes a job and writes the result in the given job\nfunc executeJob(job *job) {\n\t\/\/ log.Println(\"received job\", job.id)\n\n\t\/\/ GeoDB lookup\n\tjob.country, job.city = location(job.address)\n\n\t\/\/ Run the check\n\terr := check(job)\n\tjob.name = ptrName(job.address)\n\n\t\/\/ query the bind version\n\tif err == nil || err.Error() != \"i\/o timeout\" {\n\t\tjob.version = version(job.address)\n\t}\n\n\tif err == nil {\n\t\tjob.state = \"valid\"\n\t\tjob.err = \"\"\n\t} else {\n\t\tjob.state = \"invalid\"\n\t\tjob.err = err.Error()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/russross\/blackfriday\"\n\t\"io\/ioutil\"\n\t\"mime\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"syscall\"\n)\n\ntype Options struct {\n\tInputFile  string `long:\"input\" short:\"i\" description:\"input Markdown\"`\n\tOutputFile string `long:\"output\" short:\"o\" description:\"output HTML\"`\n\tEmbedImage bool   `long:\"embed\" short:\"e\" description:\"embed image by base64 encoding\"`\n}\n\nconst (\n\ttemplate = `<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"UTF-8\">\n<title>%s<\/title>\n%s\n<\/head>\n<body>\n<div class=\"markdown-body\">%s<\/div>\n<\/body>\n<\/html>`\n\n\textensions = blackfriday.EXTENSION_NO_INTRA_EMPHASIS |\n\t\tblackfriday.EXTENSION_TABLES |\n\t\tblackfriday.EXTENSION_FENCED_CODE |\n\t\tblackfriday.EXTENSION_AUTOLINK |\n\t\tblackfriday.EXTENSION_STRIKETHROUGH |\n\t\tblackfriday.EXTENSION_SPACE_HEADERS\n)\n\nfunc main() {\n\tvar opts Options\n\tinputs, err := flags.Parse(&opts)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tif len(opts.InputFile) > 0 {\n\t\tinputs = []string{opts.InputFile}\n\t}\n\n\tif len(inputs) <= 0 {\n\t\tfmt.Fprintln(os.Stderr, \"Please specify input Markdown\")\n\t\tos.Exit(1)\n\t}\n\n\tfor _, input := range inputs {\n\t\tfiles, err := filepath.Glob(input)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif len(files) <= 0 {\n\t\t\tfmt.Fprintln(os.Stderr, \"File is not found\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tif len(opts.OutputFile) > 0 {\n\t\t\tif err := writeHtmlConcat(files, opts.OutputFile, opts.EmbedImage); err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, file := range files {\n\t\t\t\tif err := writeHtml(file, file+\".html\", opts.EmbedImage); err != nil {\n\t\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc writeHtml(input, output string, embed bool) error {\n\tfi, err := os.Open(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fi.Close()\n\n\tmd, err := ioutil.ReadAll(fi)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tjs := string(js_bytes[:len(js_bytes)])\n\tcss := string(css_bytes[:len(css_bytes)])\n\thtml := string(blackfriday.MarkdownCommon(md))\n\n\tif embed {\n\t\thtml, err = embedImage(html, filepath.Dir(input))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfo, err := os.Create(output)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fo.Close()\n\n\tfmt.Fprintf(fo, template, input, js+\"\\n\"+css, html)\n\treturn nil\n}\n\nfunc writeHtmlConcat(inputs []string, output string, embed bool) error {\n\tjs := string(js_bytes[:len(js_bytes)])\n\tcss := string(css_bytes[:len(css_bytes)])\n\thtml := \"\"\n\n\tfor _, input := range inputs {\n\t\tfi, err := os.Open(input)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer fi.Close()\n\n\t\tmd, err := ioutil.ReadAll(fi)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\th := string(blackfriday.MarkdownCommon(md))\n\n\t\tif embed {\n\t\t\th, err = embedImage(h, filepath.Dir(input))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\thtml += h\n\t}\n\n\tfo, err := os.Create(output)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fo.Close()\n\n\tre := regexp.MustCompile(filepath.Ext(output) + \"$\")\n\ttitle := filepath.Base(re.ReplaceAllString(output, \"\"))\n\tfmt.Fprintf(fo, template, title, js+\"\\n\"+css, html)\n\treturn nil\n}\n\nfunc embedImage(src, parent string) (string, error) {\n\tre_find, err := regexp.Compile(`(<img[\\S\\s]+?src=\")([\\S\\s]+?)(\"[\\S\\s]+?\/>)`)\n\tif err != nil {\n\t\treturn src, err\n\t}\n\timg_tags := re_find.FindAllString(src, -1)\n\n\tdest := src\n\tfor _, t := range img_tags {\n\t\timg_src := re_find.ReplaceAllString(t, \"$2\")\n\t\timg_path := img_src\n\t\tif !filepath.IsAbs(img_src) {\n\t\t\timg_path = filepath.Join(parent, img_src)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tf, err := os.Open(img_path)\n\t\tif err != nil {\n\t\t\tpathErr := err.(*os.PathError)\n\t\t\terrno := pathErr.Err.(syscall.Errno)\n\t\t\tif errno != 0x7B { \/\/ suppress ERROR_INVALID_NAME\n\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tdefer f.Close()\n\n\t\td, err := ioutil.ReadAll(f)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tb64img := base64.StdEncoding.EncodeToString(d)\n\t\tre_replace, err := regexp.Compile(`(<img[\\S\\s]+?src=\")` + regexp.QuoteMeta(img_src) + `(\"[\\S\\s]+?\/>)`)\n\t\tif err != nil {\n\t\t\treturn src, err\n\t\t}\n\n\t\text := filepath.Ext(img_src)\n\t\tmime_type := mime.TypeByExtension(ext)\n\t\tif len(mime_type) <= 0 {\n\t\t\tmime_type = \"image\"\n\t\t}\n\t\tdest = re_replace.ReplaceAllString(dest, \"${1}data:\"+mime_type+\";base64,\"+b64img+\"${2}\")\n\t}\n\treturn dest, nil\n}\n<commit_msg>Use forked blackfriday<commit_after>package main\n\nimport (\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/nocd5\/blackfriday\"\n\t\"io\/ioutil\"\n\t\"mime\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"syscall\"\n)\n\ntype Options struct {\n\tInputFile  string `long:\"input\" short:\"i\" description:\"input Markdown\"`\n\tOutputFile string `long:\"output\" short:\"o\" description:\"output HTML\"`\n\tEmbedImage bool   `long:\"embed\" short:\"e\" description:\"embed image by base64 encoding\"`\n}\n\nconst (\n\ttemplate = `<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"UTF-8\">\n<title>%s<\/title>\n%s\n<\/head>\n<body>\n<div class=\"markdown-body\">%s<\/div>\n<\/body>\n<\/html>`\n\n\textensions = blackfriday.EXTENSION_NO_INTRA_EMPHASIS |\n\t\tblackfriday.EXTENSION_TABLES |\n\t\tblackfriday.EXTENSION_FENCED_CODE |\n\t\tblackfriday.EXTENSION_AUTOLINK |\n\t\tblackfriday.EXTENSION_STRIKETHROUGH |\n\t\tblackfriday.EXTENSION_SPACE_HEADERS\n)\n\nfunc main() {\n\tvar opts Options\n\tinputs, err := flags.Parse(&opts)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tif len(opts.InputFile) > 0 {\n\t\tinputs = []string{opts.InputFile}\n\t}\n\n\tif len(inputs) <= 0 {\n\t\tfmt.Fprintln(os.Stderr, \"Please specify input Markdown\")\n\t\tos.Exit(1)\n\t}\n\n\tfor _, input := range inputs {\n\t\tfiles, err := filepath.Glob(input)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif len(files) <= 0 {\n\t\t\tfmt.Fprintln(os.Stderr, \"File is not found\")\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tif len(opts.OutputFile) > 0 {\n\t\t\tif err := writeHtmlConcat(files, opts.OutputFile, opts.EmbedImage); err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, file := range files {\n\t\t\t\tif err := writeHtml(file, file+\".html\", opts.EmbedImage); err != nil {\n\t\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc writeHtml(input, output string, embed bool) error {\n\tfi, err := os.Open(input)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fi.Close()\n\n\tmd, err := ioutil.ReadAll(fi)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tjs := string(js_bytes[:len(js_bytes)])\n\tcss := string(css_bytes[:len(css_bytes)])\n\thtml := string(blackfriday.MarkdownCommon(md))\n\n\tif embed {\n\t\thtml, err = embedImage(html, filepath.Dir(input))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfo, err := os.Create(output)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fo.Close()\n\n\tfmt.Fprintf(fo, template, input, js+\"\\n\"+css, html)\n\treturn nil\n}\n\nfunc writeHtmlConcat(inputs []string, output string, embed bool) error {\n\tjs := string(js_bytes[:len(js_bytes)])\n\tcss := string(css_bytes[:len(css_bytes)])\n\thtml := \"\"\n\n\tfor _, input := range inputs {\n\t\tfi, err := os.Open(input)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer fi.Close()\n\n\t\tmd, err := ioutil.ReadAll(fi)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\th := string(blackfriday.MarkdownCommon(md))\n\n\t\tif embed {\n\t\t\th, err = embedImage(h, filepath.Dir(input))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\thtml += h\n\t}\n\n\tfo, err := os.Create(output)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fo.Close()\n\n\tre := regexp.MustCompile(filepath.Ext(output) + \"$\")\n\ttitle := filepath.Base(re.ReplaceAllString(output, \"\"))\n\tfmt.Fprintf(fo, template, title, js+\"\\n\"+css, html)\n\treturn nil\n}\n\nfunc embedImage(src, parent string) (string, error) {\n\tre_find, err := regexp.Compile(`(<img[\\S\\s]+?src=\")([\\S\\s]+?)(\"[\\S\\s]+?\/>)`)\n\tif err != nil {\n\t\treturn src, err\n\t}\n\timg_tags := re_find.FindAllString(src, -1)\n\n\tdest := src\n\tfor _, t := range img_tags {\n\t\timg_src := re_find.ReplaceAllString(t, \"$2\")\n\t\timg_path := img_src\n\t\tif !filepath.IsAbs(img_src) {\n\t\t\timg_path = filepath.Join(parent, img_src)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tf, err := os.Open(img_path)\n\t\tif err != nil {\n\t\t\tpathErr := err.(*os.PathError)\n\t\t\terrno := pathErr.Err.(syscall.Errno)\n\t\t\tif errno != 0x7B { \/\/ suppress ERROR_INVALID_NAME\n\t\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tdefer f.Close()\n\n\t\td, err := ioutil.ReadAll(f)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tb64img := base64.StdEncoding.EncodeToString(d)\n\t\tre_replace, err := regexp.Compile(`(<img[\\S\\s]+?src=\")` + regexp.QuoteMeta(img_src) + `(\"[\\S\\s]+?\/>)`)\n\t\tif err != nil {\n\t\t\treturn src, err\n\t\t}\n\n\t\text := filepath.Ext(img_src)\n\t\tmime_type := mime.TypeByExtension(ext)\n\t\tif len(mime_type) <= 0 {\n\t\t\tmime_type = \"image\"\n\t\t}\n\t\tdest = re_replace.ReplaceAllString(dest, \"${1}data:\"+mime_type+\";base64,\"+b64img+\"${2}\")\n\t}\n\treturn dest, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/arjantop\/imageoptimizer\/optimizer\"\n)\n\ntype ImageDescription struct {\n\tOptimizer string\n\tPath      string\n\tMimeType  string\n\tSize      int64\n}\n\nfunc reportError(w http.ResponseWriter, msg string, err error) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tlog.Printf(\"%s err=%s\", msg, err)\n}\n\nfunc parseAcceptedTypes(acceptHeader string) []string {\n\tacceptedTypes := make([]string, 0, 1)\n\tfor _, part := range strings.Split(acceptHeader, \",\") {\n\t\tacceptedType := part\n\t\tif strings.Contains(part, \";\") {\n\t\t\tacceptedType = strings.SplitN(part, \";\", 2)[0]\n\t\t}\n\t\tacceptedTypes = append(acceptedTypes, acceptedType)\n\t}\n\treturn acceptedTypes\n}\n\nvar baseUrl = flag.String(\"baseurl\", \"\", \"Base url to which proxied requests are appended\")\n\nfunc main() {\n\tflag.Parse()\n\n\tif _, err := url.Parse(*baseUrl); *baseUrl == \"\" || err != nil {\n\t\tlog.Fatalf(\"Invalid base url: %s\", *baseUrl)\n\t}\n\n\toptimizers := []optimizer.ImageOptimizer{\n\t\t&optimizer.WebpLosslessOptimizer{\n\t\t\tArgs: []string{\"-z\", \"9\"},\n\t\t},\n\t\toptimizer.NewWebpLossyPngOptimizer(0.998),\n\t\toptimizer.NewWebpLossyJpegOptimizer(0.995),\n\t\t&optimizer.OptipngOptimizer{\n\t\t\tArgs: []string{\"-strip\", \"all\"},\n\t\t},\n\t\t&optimizer.MozjpegOptimizer{\n\t\t\tArgs: []string{\"-copy\", \"none\", \"-optimize\"},\n\t\t},\n\t\toptimizer.NewMozjpegPngLossyOptimizer(0.997),\n\t\toptimizer.NewMozjpegLossyOptimizer(0.994),\n\t}\n\n\tclient := &http.Client{}\n\n\thttp.HandleFunc(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tacceptedTypes := parseAcceptedTypes(r.Header.Get(\"Accept\"))\n\n\t\trequestUrl, err := url.ParseRequestURI(r.RequestURI)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Invalid url\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\thidpi := strings.Contains(requestUrl.Path, \"@2x.\")\n\n\t\tlog.Printf(\"Proxying: %s (hidpi=%t)\", requestUrl.Path, hidpi)\n\t\tresp, err := client.Get(*baseUrl + requestUrl.Path)\n\t\tif err != nil {\n\t\t\treportError(w, \"Call failed\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tif !optimizer.CanOptimize(optimizers, resp.Header.Get(\"Content-Type\"), acceptedTypes) {\n\t\t\tfor key, vals := range resp.Header {\n\t\t\t\tfor _, val := range vals {\n\t\t\t\t\tw.Header().Add(key, val)\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.WriteHeader(resp.StatusCode)\n\t\t\t_, err = io.Copy(w, resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treportError(w, \"Could not copy data to client\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\ttempFile, err := ioutil.TempFile(os.TempDir(), strings.Replace(r.RequestURI, \"\/\", \"\", -1))\n\t\tif err != nil {\n\t\t\treportError(w, \"Could not create temp file\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer tempFile.Close()\n\n\t\t_, err = io.Copy(tempFile, resp.Body)\n\t\tif err != nil {\n\t\t\treportError(w, \"Could not copy data to temp file\", err)\n\t\t\treturn\n\t\t}\n\n\t\toptimizedImage, err := optimizer.Optimize(r.Context(), optimizers, optimizer.OptimizeParams{\n\t\t\tAcceptedTypes: acceptedTypes,\n\t\t\tSourcePath:    tempFile.Name(),\n\t\t\tHidpi:         hidpi,\n\t\t})\n\t\tif err != nil {\n\t\t\treportError(w, \"Could not optimize the file\", err)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Printf(\"Chosen optimizer: %s\", optimizedImage.Optimizer)\n\n\t\tfile, err := os.Open(optimizedImage.Path)\n\t\tif err != nil {\n\t\t\treportError(w, \"opening file\", err)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", optimizedImage.MimeType)\n\t\tw.Header().Set(\"Content-Length\", strconv.FormatInt(optimizedImage.Size, 10))\n\t\tw.WriteHeader(http.StatusOK)\n\n\t\t_, err = io.Copy(w, file)\n\t\tif err != nil {\n\t\t\treportError(w, \"reading file\", err)\n\t\t\treturn\n\t\t}\n\t})\n\n\tlog.Fatal(http.ListenAndServe(\":8888\", nil))\n}\n<commit_msg>Forward all headers.<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/arjantop\/imageoptimizer\/optimizer\"\n)\n\ntype ImageDescription struct {\n\tOptimizer string\n\tPath      string\n\tMimeType  string\n\tSize      int64\n}\n\nfunc reportError(w http.ResponseWriter, msg string, err error) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tlog.Printf(\"%s err=%s\", msg, err)\n}\n\nfunc parseAcceptedTypes(acceptHeader string) []string {\n\tacceptedTypes := make([]string, 0, 1)\n\tfor _, part := range strings.Split(acceptHeader, \",\") {\n\t\tacceptedType := part\n\t\tif strings.Contains(part, \";\") {\n\t\t\tacceptedType = strings.SplitN(part, \";\", 2)[0]\n\t\t}\n\t\tacceptedTypes = append(acceptedTypes, acceptedType)\n\t}\n\treturn acceptedTypes\n}\n\nvar baseUrl = flag.String(\"baseurl\", \"\", \"Base url to which proxied requests are appended\")\n\nfunc main() {\n\tflag.Parse()\n\n\tif _, err := url.Parse(*baseUrl); *baseUrl == \"\" || err != nil {\n\t\tlog.Fatalf(\"Invalid base url: %s\", *baseUrl)\n\t}\n\n\toptimizers := []optimizer.ImageOptimizer{\n\t\t&optimizer.WebpLosslessOptimizer{\n\t\t\tArgs: []string{\"-z\", \"9\"},\n\t\t},\n\t\toptimizer.NewWebpLossyPngOptimizer(0.998),\n\t\toptimizer.NewWebpLossyJpegOptimizer(0.995),\n\t\t&optimizer.OptipngOptimizer{\n\t\t\tArgs: []string{\"-strip\", \"all\"},\n\t\t},\n\t\t&optimizer.MozjpegOptimizer{\n\t\t\tArgs: []string{\"-copy\", \"none\", \"-optimize\"},\n\t\t},\n\t\toptimizer.NewMozjpegPngLossyOptimizer(0.997),\n\t\toptimizer.NewMozjpegLossyOptimizer(0.994),\n\t}\n\n\tclient := &http.Client{}\n\n\thttp.HandleFunc(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tacceptedTypes := parseAcceptedTypes(r.Header.Get(\"Accept\"))\n\n\t\trequestUrl, err := url.ParseRequestURI(r.RequestURI)\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Invalid url\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\thidpi := strings.Contains(requestUrl.Path, \"@2x.\")\n\n\t\tlog.Printf(\"Proxying: %s (hidpi=%t)\", requestUrl.Path+\"?\"+requestUrl.RawQuery, hidpi)\n\n\t\treq, err := http.NewRequest(http.MethodGet, *baseUrl+requestUrl.Path+\"?\"+requestUrl.RawQuery, nil)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Invalid request\")\n\t\t}\n\t\tfor key, vals := range r.Header {\n\t\t\tfor _, val := range vals {\n\t\t\t\treq.Header.Set(key, val)\n\t\t\t}\n\t\t}\n\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\treportError(w, \"Call failed\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tif !optimizer.CanOptimize(optimizers, resp.Header.Get(\"Content-Type\"), acceptedTypes) {\n\t\t\tfor key, vals := range resp.Header {\n\t\t\t\tfor _, val := range vals {\n\t\t\t\t\tw.Header().Add(key, val)\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.WriteHeader(resp.StatusCode)\n\t\t\t_, err = io.Copy(w, resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treportError(w, \"Could not copy data to client\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\ttempFile, err := ioutil.TempFile(os.TempDir(), strings.Replace(r.RequestURI, \"\/\", \"\", -1))\n\t\tif err != nil {\n\t\t\treportError(w, \"Could not create temp file\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer tempFile.Close()\n\n\t\t_, err = io.Copy(tempFile, resp.Body)\n\t\tif err != nil {\n\t\t\treportError(w, \"Could not copy data to temp file\", err)\n\t\t\treturn\n\t\t}\n\n\t\toptimizedImage, err := optimizer.Optimize(r.Context(), optimizers, optimizer.OptimizeParams{\n\t\t\tAcceptedTypes: acceptedTypes,\n\t\t\tSourcePath:    tempFile.Name(),\n\t\t\tHidpi:         hidpi,\n\t\t})\n\t\tif err != nil {\n\t\t\treportError(w, \"Could not optimize the file\", err)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Printf(\"Chosen optimizer: %s\", optimizedImage.Optimizer)\n\n\t\tfile, err := os.Open(optimizedImage.Path)\n\t\tif err != nil {\n\t\t\treportError(w, \"opening file\", err)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", optimizedImage.MimeType)\n\t\tw.Header().Set(\"Content-Length\", strconv.FormatInt(optimizedImage.Size, 10))\n\t\tw.WriteHeader(http.StatusOK)\n\n\t\t_, err = io.Copy(w, file)\n\t\tif err != nil {\n\t\t\treportError(w, \"reading file\", err)\n\t\t\treturn\n\t\t}\n\t})\n\n\tlog.Fatal(http.ListenAndServe(\":8888\", nil))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\n\/\/ The import section defines libraries that we are going to use in our program.\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"encoding\/json\"\n\t\"github.com\/rs\/cors\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/ory-am\/common\/pkg\"\n\t\"github.com\/ory-am\/common\/env\"\n)\n\n\/\/ In a 12 factor app, we must obey the environment variables.\nvar envHost = env.Getenv(\"HOST\", \"\")\nvar envPort = env.Getenv(\"PORT\", \"5678\")\n\n\/\/ Contact defines the structure of a contact which including name, department and company.\ntype Contact struct {\n\tID string `json:\"id\"`\n\n\t\/\/ Name is the contact's full name.\n\tName string `json:\"name\"`\n\n\t\/\/ Department is the contact's department in a company.\n\tDepartment string `json:\"department\"`\n\n\t\/\/ Company is the name of the company the contact works for.\n\tCompany string `json:\"company\"`\n}\n\n\/\/ Contacts is a list of contact structs.\ntype Contacts map[string]Contact\n\n\/\/ MyContacts is an exemplary list of contacts.\nvar MyContacts = Contacts{\n\t\"john-bravo\": Contact{\n\t\tName:       \"John Bravo\",\n\t\tDepartment: \"IT\",\n\t\tCompany:    \"ACME Inc\",\n\t},\n\t\"cathrine-mueller\": Contact{\n\t\tName:       \"Cathrine Müller\",\n\t\tDepartment: \"HR\",\n\t\tCompany:    \"Grove AG\",\n\t},\n\t\"maximilian-schmidt\": Contact{\n\t\tName:       \"Maximilian Schmidt\",\n\t\tDepartment: \"PR\",\n\t\tCompany:    \"Titanpad AG\",\n\t},\n}\n\n\/\/ The main routine is going the \"entry\" point.\nfunc main() {\n\t\/\/ Create a new router.\n\trouter := mux.NewRouter()\n\n\t\/\/ RESTful defines operations\n\t\/\/ * GET for fetching data\n\t\/\/ * POST for inserting data\n\t\/\/ * PUT for updating existing data\n\t\/\/ * DELETE for deleting data\n\trouter.HandleFunc(\"\/contacts\/{id}\", UpdateContact(MyContacts)).Methods(\"PUT\")\n\trouter.HandleFunc(\"\/contacts\/{id}\", DeleteContact(MyContacts)).Methods(\"DELETE\")\n\trouter.HandleFunc(\"\/contacts\", ListContacts(MyContacts)).Methods(\"GET\")\n\trouter.HandleFunc(\"\/contacts\", AddContact(MyContacts)).Methods(\"POST\")\n\n\t\/\/ Print some information.\n\tfmt.Printf(\"Listening on %s\\n\", \"http:\/\/localhost:5678\")\n\n\t\/\/ Cross origin resource requests\n\tc := cors.New(cors.Options{AllowedOrigins: []string{\"*\"}})\n\n\t\/\/ Start up the server and check for errors.\n\tlistenOn := fmt.Sprintf(\"%s:%s\", envHost, envPort)\n\terr := http.ListenAndServe(listenOn, c.Handler(router))\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not set up server because %s\", err)\n\t}\n}\n\n\/\/ ListContacts takes a contact list and outputs it.\nfunc ListContacts(contacts Contacts) func(rw http.ResponseWriter, r *http.Request) {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\n\t\t\/\/ Write contact list to output\n\t\tpkg.WriteIndentJSON(rw, contacts)\n\t}\n}\n\n\/\/ AddContact will add a contact to the list\nfunc AddContact(contacts Contacts) func(rw http.ResponseWriter, r *http.Request) {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\n\t\t\/\/ We parse the request's information into contactToBeAdded\n\t\tcontactToBeAdded, err := ReadContactData(rw, r)\n\n\t\t\/\/ Abort handling the request if an error occurs.\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Save newContact to the list of contacts.\n\t\tcontacts[contactToBeAdded.ID] = contactToBeAdded\n\n\t\t\/\/ Output our newly created contact\n\t\tpkg.WriteIndentJSON(rw, contactToBeAdded)\n\t}\n}\n\n\/\/ DeleteContact will delete a contact from the list\nfunc DeleteContact(contacts Contacts) func(rw http.ResponseWriter, r *http.Request) {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\t\t\/\/ Fetch the ID of the contact that is going to be deleted\n\t\tcontactToBeDeleted := mux.Vars(r)[\"id\"]\n\n\t\t\/\/ Check if the contact exists and return an error if not\n\t\tif _, found := contacts[contactToBeDeleted]; !found {\n\t\t\thttp.Error(rw, \"I do not know any contact by that ID.\", http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Delete the contact from the list\n\t\tdelete(contacts, contactToBeDeleted)\n\n\t\t\/\/ Per specification, RESTful may return an empty response when a DELETE request was successful\n\t\trw.WriteHeader(http.StatusNoContent)\n\t}\n}\n\n\/\/ UpdateContact will update a contact on the list\nfunc UpdateContact(contacts Contacts) func(rw http.ResponseWriter, r *http.Request) {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\t\t\/\/ Fetch the ID of the contact that is going to be updated\n\t\tcontactToBeUpdated := mux.Vars(r)[\"id\"]\n\n\t\t\/\/ Check if the contact exists\n\t\tif _, found := contacts[contactToBeUpdated]; !found {\n\t\t\thttp.Error(rw, \"I don't know any contact by that ID.\", http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ We parse the request's information into newContactData.\n\t\tnewContactData, err := ReadContactData(rw, r)\n\n\t\t\/\/ Abort handling the request if an error occurs.\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Update the data in the contact list.\n\t\tdelete(contacts, contactToBeUpdated)\n\t\tcontacts[newContactData.ID] = newContactData\n\n\t\t\/\/ Set the new data\n\t\tpkg.WriteIndentJSON(rw, newContactData)\n\t}\n}\n\n\/\/ ReadContactData is a helper function for parsing a HTTP request body. It returns a contact on success and an\n\/\/ error if something went wrong.\nfunc ReadContactData(rw http.ResponseWriter, r *http.Request) (contact Contact, err error) {\n\terr = json.NewDecoder(r.Body).Decode(&contact)\n\tif err != nil {\n\t\thttp.Error(rw, fmt.Sprintf(\"Could not read input data because %s\", err), http.StatusBadRequest)\n\t\treturn contact, err\n\t}\n\n\treturn contact, nil\n}<commit_msg>fixed tests<commit_after>package main\n\n\/\/ The import section defines libraries that we are going to use in our program.\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"encoding\/json\"\n\t\"github.com\/rs\/cors\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/ory-am\/common\/pkg\"\n\t\"github.com\/ory-am\/common\/env\"\n)\n\n\/\/ In a 12 factor app, we must obey the environment variables.\nvar envHost = env.Getenv(\"HOST\", \"\")\nvar envPort = env.Getenv(\"PORT\", \"5678\")\n\n\/\/ Contact defines the structure of a contact which including name, department and company.\ntype Contact struct {\n\tID         string `json:\"id,omitempty\"`\n\n\t\/\/ Name is the contact's full name.\n\tName       string `json:\"name\"`\n\n\t\/\/ Department is the contact's department in a company.\n\tDepartment string `json:\"department\"`\n\n\t\/\/ Company is the name of the company the contact works for.\n\tCompany    string `json:\"company\"`\n}\n\n\/\/ Contacts is a list of contact structs.\ntype Contacts map[string]Contact\n\n\/\/ MyContacts is an exemplary list of contacts.\nvar MyContacts = Contacts{\n\t\"john-bravo\": Contact{\n\t\tName:       \"John Bravo\",\n\t\tDepartment: \"IT\",\n\t\tCompany:    \"ACME Inc\",\n\t},\n\t\"cathrine-mueller\": Contact{\n\t\tName:       \"Cathrine Müller\",\n\t\tDepartment: \"HR\",\n\t\tCompany:    \"Grove AG\",\n\t},\n\t\"maximilian-schmidt\": Contact{\n\t\tName:       \"Maximilian Schmidt\",\n\t\tDepartment: \"PR\",\n\t\tCompany:    \"Titanpad AG\",\n\t},\n}\n\n\/\/ The main routine is going the \"entry\" point.\nfunc main() {\n\t\/\/ Create a new router.\n\trouter := mux.NewRouter()\n\n\t\/\/ RESTful defines operations\n\t\/\/ * GET for fetching data\n\t\/\/ * POST for inserting data\n\t\/\/ * PUT for updating existing data\n\t\/\/ * DELETE for deleting data\n\trouter.HandleFunc(\"\/contacts\/{id}\", UpdateContact(MyContacts)).Methods(\"PUT\")\n\trouter.HandleFunc(\"\/contacts\/{id}\", DeleteContact(MyContacts)).Methods(\"DELETE\")\n\trouter.HandleFunc(\"\/contacts\", ListContacts(MyContacts)).Methods(\"GET\")\n\trouter.HandleFunc(\"\/contacts\", AddContact(MyContacts)).Methods(\"POST\")\n\n\t\/\/ Print some information.\n\tfmt.Printf(\"Listening on %s\\n\", \"http:\/\/localhost:5678\")\n\n\t\/\/ Cross origin resource requests\n\tc := cors.New(cors.Options{\n\t\tAllowedOrigins: []string{\"*\"},\n\t\tAllowedMethods: []string{\"GET\", \"POST\", \"DELETE\", \"PUT\"}},\n\t)\n\n\t\/\/ Start up the server and check for errors.\n\tlistenOn := fmt.Sprintf(\"%s:%s\", envHost, envPort)\n\terr := http.ListenAndServe(listenOn, c.Handler(router))\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not set up server because %s\", err)\n\t}\n}\n\n\/\/ ListContacts takes a contact list and outputs it.\nfunc ListContacts(contacts Contacts) func(rw http.ResponseWriter, r *http.Request) {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\n\t\t\/\/ Write contact list to output\n\t\tpkg.WriteIndentJSON(rw, contacts)\n\t}\n}\n\n\/\/ AddContact will add a contact to the list\nfunc AddContact(contacts Contacts) func(rw http.ResponseWriter, r *http.Request) {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\n\t\t\/\/ We parse the request's information into contactToBeAdded\n\t\tcontactToBeAdded, err := ReadContactData(rw, r)\n\n\t\t\/\/ Abort handling the request if an error occurs.\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Save newContact to the list of contacts.\n\t\tcontacts[contactToBeAdded.ID] = contactToBeAdded\n\n\t\t\/\/ Output our newly created contact\n\t\tpkg.WriteIndentJSON(rw, contactToBeAdded)\n\t}\n}\n\n\/\/ DeleteContact will delete a contact from the list\nfunc DeleteContact(contacts Contacts) func(rw http.ResponseWriter, r *http.Request) {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\t\t\/\/ Fetch the ID of the contact that is going to be deleted\n\t\tcontactToBeDeleted := mux.Vars(r)[\"id\"]\n\n\t\t\/\/ Check if the contact exists and return an error if not\n\t\tif _, found := contacts[contactToBeDeleted]; !found {\n\t\t\thttp.Error(rw, \"I do not know any contact by that ID.\", http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Delete the contact from the list\n\t\tdelete(contacts, contactToBeDeleted)\n\n\t\t\/\/ Per specification, RESTful may return an empty response when a DELETE request was successful\n\t\trw.WriteHeader(http.StatusNoContent)\n\t}\n}\n\n\/\/ UpdateContact will update a contact on the list\nfunc UpdateContact(contacts Contacts) func(rw http.ResponseWriter, r *http.Request) {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\t\t\/\/ Fetch the ID of the contact that is going to be updated\n\t\tcontactToBeUpdated := mux.Vars(r)[\"id\"]\n\n\t\t\/\/ Check if the contact exists\n\t\tif _, found := contacts[contactToBeUpdated]; !found {\n\t\t\thttp.Error(rw, \"I don't know any contact by that ID.\", http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ We parse the request's information into newContactData.\n\t\tnewContactData, err := ReadContactData(rw, r)\n\n\t\t\/\/ Abort handling the request if an error occurs.\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Update the data in the contact list.\n\t\tdelete(contacts, contactToBeUpdated)\n\t\tcontacts[newContactData.ID] = newContactData\n\n\t\t\/\/ Set the new data\n\t\tpkg.WriteIndentJSON(rw, newContactData)\n\t}\n}\n\n\/\/ ReadContactData is a helper function for parsing a HTTP request body. It returns a contact on success and an\n\/\/ error if something went wrong.\nfunc ReadContactData(rw http.ResponseWriter, r *http.Request) (contact Contact, err error) {\n\terr = json.NewDecoder(r.Body).Decode(&contact)\n\tif err != nil {\n\t\thttp.Error(rw, fmt.Sprintf(\"Could not read input data because %s\", err), http.StatusBadRequest)\n\t\treturn contact, err\n\t}\n\n\treturn contact, nil\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/alexflint\/go-arg\"\n\t\"github.com\/brentp\/gargs\/process\"\n\t\"github.com\/fatih\/color\"\n\tisatty \"github.com\/mattn\/go-isatty\"\n\t\"github.com\/valyala\/fasttemplate\"\n)\n\n\/\/ Version is the current version\nconst Version = \"0.3.4-dev\"\n\n\/\/ ExitCode is the highest exit code seen in any command\nvar ExitCode = 0\n\n\/\/ Params are the user-specified command-line arguments\ntype Params struct {\n\tProcs       int      `arg:\"-p,help:number of processes to use.\"`\n\tNlines      int      `arg:\"-n,help:number of lines to consume for each command. -s and -n are mutually exclusive.\"`\n\tRetry       int      `arg:\"-r,help:number of times to retry a command if it fails (default is 0).\"`\n\tSep         string   `arg:\"-s,help:regular expression split line with to fill multiple template spots default is not to split. -s and -n are mutually exclusive.\"`\n\tVerbose     bool     `arg:\"-v,help:print commands to stderr as they are executed.\"`\n\tStopOnError bool     `arg:\"-s,--stop-on-error,help:stop execution on any error. default is to report errors and continue execution.\"`\n\tDryRun      bool     `arg:\"-d,--dry-run,help:print (but do not run) the commands.\"`\n\tLog         string   `arg:\"-l,--log,help:file to log commands. Successful commands are prefixed with '#'.\"`\n\tCommand     string   `arg:\"positional,required,help:command to execute.\"`\n\tlog         *os.File `arg:\"-\"`\n}\n\n\/\/ isStdin checks if we are getting data from stdin.\nfunc isStdin() bool {\n\t\/\/ http:\/\/stackoverflow.com\/a\/26567513\n\tstat, err := os.Stdin.Stat()\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn (stat.Mode() & os.ModeCharDevice) == 0\n}\n\nfunc main() {\n\targs := Params{Procs: 1, Nlines: 1}\n\tp := arg.MustParse(&args)\n\tif args.Sep != \"\" && args.Nlines > 1 {\n\t\tp.Fail(\"must specify either sep (-s) or n-lines (-n), not both\")\n\t}\n\t\/\/ if neither is specified then we default to whitespace\n\tif args.Nlines == 1 && args.Sep == \"\" {\n\t\targs.Sep = \"\\\\s+\"\n\t}\n\tif !isStdin() {\n\t\tfmt.Fprintln(os.Stderr, color.RedString(\"ERROR: expecting input on STDIN\"))\n\t\tos.Exit(255)\n\t}\n\tif args.Log != \"\" {\n\t\tvar err error\n\t\targs.log, err = os.Create(args.Log)\n\t\tcheck(err)\n\t}\n\truntime.GOMAXPROCS(args.Procs)\n\trun(args)\n\tos.Exit(ExitCode)\n}\n\nfunc check(e error) {\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n}\n\nfunc handleCommand(args *Params, cmd string, ch chan string) {\n\tif args.DryRun {\n\t\tfmt.Fprintf(os.Stdout, \"%s\\n\", cmd)\n\t\treturn\n\t}\n\tch <- cmd\n}\n\nfunc fillTmplMap(toks []string, line string) map[string]interface{} {\n\tm := make(map[string]interface{}, 5)\n\tif toks != nil {\n\t\tfor i, t := range toks {\n\t\t\tm[strconv.FormatInt(int64(i), 10)] = t\n\t\t}\n\t}\n\tm[\"Line\"] = line\n\treturn m\n}\n\nfunc getScanner() *bufio.Scanner {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Buffer(make([]byte, 0, 16384), 5e9)\n\t\/\/if rs := os.Getenv(\"RS\"); rs != \"\" && rs != \"\\n\" && rs != \"\\r\\n\" {\n\tif rs := os.Getenv(\"RS\"); rs != \"\" {\n\t\tbrs := []byte(rs)\n\t\tscanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {\n\t\t\tif atEOF && len(data) == 0 {\n\t\t\t\treturn 0, nil, nil\n\t\t\t}\n\t\t\tif i := bytes.Index(data, brs); i >= 0 {\n\t\t\t\t\/\/ Note that by adding the length here, we include the delimiter.\n\t\t\t\treturn i + 1, data[:i+len(brs)], nil\n\t\t\t}\n\t\t\tif atEOF {\n\t\t\t\treturn len(data), data, nil\n\t\t\t}\n\t\t\treturn 0, nil, nil\n\t\t})\n\t}\n\treturn scanner\n}\n\nfunc genCommands(args *Params, tmpl *fasttemplate.Template) <-chan string {\n\tch := make(chan string)\n\tvar resep *regexp.Regexp\n\tif args.Sep != \"\" {\n\t\tresep = regexp.MustCompile(args.Sep)\n\t}\n\n\tscanner := getScanner()\n\tfs := os.Getenv(\"FS\")\n\tif fs == \"\" {\n\t\tfs = \" \"\n\t}\n\n\tgo func() {\n\t\tvar lines []string\n\t\tif resep == nil {\n\t\t\tlines = make([]string, 0, args.Nlines)\n\t\t}\n\t\tvar buf bytes.Buffer\n\t\tfor scanner.Scan() {\n\t\t\tbuf.Reset()\n\t\t\tline := scanner.Text()\n\t\t\tserr := scanner.Err()\n\t\t\tif serr == nil || (serr == io.EOF && len(line) > 0) {\n\t\t\t\t\/\/ TODO: make dropping bytes optional.\n\t\t\t\tif resep != nil {\n\t\t\t\t\ttoks := resep.Split(line, -1)\n\t\t\t\t\ttargs := fillTmplMap(toks, line)\n\t\t\t\t\t_, err := tmpl.Execute(&buf, targs)\n\t\t\t\t\tcheck(err)\n\t\t\t\t\thandleCommand(args, buf.String(), ch)\n\t\t\t\t} else {\n\t\t\t\t\tlines = append(lines, line)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif serr == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tlog.Fatal(serr)\n\t\t\t}\n\t\t\tif len(lines) >= args.Nlines {\n\t\t\t\ttargs := fillTmplMap(lines, strings.Join(lines, fs))\n\t\t\t\t_, err := tmpl.Execute(&buf, targs)\n\t\t\t\tcheck(err)\n\t\t\t\tlines = lines[:0]\n\t\t\t\thandleCommand(args, buf.String(), ch)\n\t\t\t}\n\t\t}\n\t\tif len(lines) > 0 {\n\t\t\ttargs := fillTmplMap(lines, strings.Join(lines, fs))\n\t\t\t_, err := tmpl.Execute(&buf, targs)\n\t\t\tcheck(err)\n\t\t\thandleCommand(args, buf.String(), ch)\n\t\t}\n\t\tclose(ch)\n\t}()\n\treturn ch\n}\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc init() {\n\tcolor.NoColor = !isatty.IsTerminal(os.Stderr.Fd())\n}\n\nfunc run(args Params) {\n\n\ttmpl := makeCommandTmpl(args.Command)\n\tcmds := genCommands(&args, tmpl)\n\n\tstdout := bufio.NewWriter(os.Stdout)\n\tdefer stdout.Flush()\n\n\tcancel := make(chan bool)\n\tdefer close(cancel)\n\tfails := 0\n\n\t\/\/ flush stdout every 2 seconds.\n\tlast := time.Now().Add(2 * time.Second)\n\tfor p := range process.Runner(cmds, args.Retry, cancel) {\n\t\tif ex := p.ExitCode(); ex != 0 {\n\t\t\tc := color.New(color.BgRed).Add(color.Bold)\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", c.SprintFunc()(fmt.Sprintf(\"ERROR with command: %s\", p)))\n\t\t\tExitCode = max(ExitCode, ex)\n\t\t\tfails++\n\t\t\tif args.StopOnError {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif args.Verbose {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", p)\n\t\t}\n\t\t_, err := io.Copy(stdout, p)\n\t\tcheck(err)\n\n\t\tp.Cleanup()\n\t\tif t := time.Now(); t.After(last) {\n\t\t\tstdout.Flush()\n\t\t\tlast = t.Add(2 * time.Second)\n\t\t}\n\t\tif args.log != nil {\n\t\t\t\/\/ if no error prefix the command with '#'\n\t\t\tif p.ExitCode() == 0 {\n\t\t\t\targs.log.WriteString(\"# \" + strings.Replace(p.CmdStr, \"\\n\", \"\\n# \", -1) + \"\\n\")\n\t\t\t} else {\n\t\t\t\targs.log.WriteString(p.CmdStr + \"\\n\")\n\t\t\t}\n\t\t\tstdout.Flush()\n\t\t}\n\t}\n\tstdout.Flush()\n\tif ExitCode == 0 && args.log != nil {\n\t\targs.log.WriteString(\"# SUCCESS\\n\")\n\t} else if args.log != nil {\n\t\tfmt.Fprintf(args.log, \"# FAILED %d commands\\n\", fails)\n\t}\n\n}\n\nfunc makeCommandTmpl(cmd string) *fasttemplate.Template {\n\tv := strings.Replace(cmd, \"{}\", \"{Line}\", -1)\n\treturn fasttemplate.New(v, \"{\", \"}\")\n}\n<commit_msg>version<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/alexflint\/go-arg\"\n\t\"github.com\/brentp\/gargs\/process\"\n\t\"github.com\/fatih\/color\"\n\tisatty \"github.com\/mattn\/go-isatty\"\n\t\"github.com\/valyala\/fasttemplate\"\n)\n\n\/\/ Version is the current version\nconst Version = \"0.3.5\"\n\n\/\/ ExitCode is the highest exit code seen in any command\nvar ExitCode = 0\n\n\/\/ Params are the user-specified command-line arguments\ntype Params struct {\n\tProcs       int      `arg:\"-p,help:number of processes to use.\"`\n\tNlines      int      `arg:\"-n,help:number of lines to consume for each command. -s and -n are mutually exclusive.\"`\n\tRetry       int      `arg:\"-r,help:number of times to retry a command if it fails (default is 0).\"`\n\tSep         string   `arg:\"-s,help:regular expression split line with to fill multiple template spots default is not to split. -s and -n are mutually exclusive.\"`\n\tVerbose     bool     `arg:\"-v,help:print commands to stderr as they are executed.\"`\n\tStopOnError bool     `arg:\"-s,--stop-on-error,help:stop execution on any error. default is to report errors and continue execution.\"`\n\tDryRun      bool     `arg:\"-d,--dry-run,help:print (but do not run) the commands.\"`\n\tLog         string   `arg:\"-l,--log,help:file to log commands. Successful commands are prefixed with '#'.\"`\n\tCommand     string   `arg:\"positional,required,help:command to execute.\"`\n\tlog         *os.File `arg:\"-\"`\n}\n\n\/\/ isStdin checks if we are getting data from stdin.\nfunc isStdin() bool {\n\t\/\/ http:\/\/stackoverflow.com\/a\/26567513\n\tstat, err := os.Stdin.Stat()\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn (stat.Mode() & os.ModeCharDevice) == 0\n}\n\nfunc main() {\n\targs := Params{Procs: 1, Nlines: 1}\n\tp := arg.MustParse(&args)\n\tif args.Sep != \"\" && args.Nlines > 1 {\n\t\tp.Fail(\"must specify either sep (-s) or n-lines (-n), not both\")\n\t}\n\t\/\/ if neither is specified then we default to whitespace\n\tif args.Nlines == 1 && args.Sep == \"\" {\n\t\targs.Sep = \"\\\\s+\"\n\t}\n\tif !isStdin() {\n\t\tfmt.Fprintln(os.Stderr, color.RedString(\"ERROR: expecting input on STDIN\"))\n\t\tos.Exit(255)\n\t}\n\tif args.Log != \"\" {\n\t\tvar err error\n\t\targs.log, err = os.Create(args.Log)\n\t\tcheck(err)\n\t}\n\truntime.GOMAXPROCS(args.Procs)\n\trun(args)\n\tos.Exit(ExitCode)\n}\n\nfunc check(e error) {\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n}\n\nfunc handleCommand(args *Params, cmd string, ch chan string) {\n\tif args.DryRun {\n\t\tfmt.Fprintf(os.Stdout, \"%s\\n\", cmd)\n\t\treturn\n\t}\n\tch <- cmd\n}\n\nfunc fillTmplMap(toks []string, line string) map[string]interface{} {\n\tm := make(map[string]interface{}, 5)\n\tif toks != nil {\n\t\tfor i, t := range toks {\n\t\t\tm[strconv.FormatInt(int64(i), 10)] = t\n\t\t}\n\t}\n\tm[\"Line\"] = line\n\treturn m\n}\n\nfunc getScanner() *bufio.Scanner {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Buffer(make([]byte, 0, 16384), 5e9)\n\t\/\/if rs := os.Getenv(\"RS\"); rs != \"\" && rs != \"\\n\" && rs != \"\\r\\n\" {\n\tif rs := os.Getenv(\"RS\"); rs != \"\" {\n\t\tbrs := []byte(rs)\n\t\tscanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {\n\t\t\tif atEOF && len(data) == 0 {\n\t\t\t\treturn 0, nil, nil\n\t\t\t}\n\t\t\tif i := bytes.Index(data, brs); i >= 0 {\n\t\t\t\t\/\/ Note that by adding the length here, we include the delimiter.\n\t\t\t\treturn i + 1, data[:i+len(brs)], nil\n\t\t\t}\n\t\t\tif atEOF {\n\t\t\t\treturn len(data), data, nil\n\t\t\t}\n\t\t\treturn 0, nil, nil\n\t\t})\n\t}\n\treturn scanner\n}\n\nfunc genCommands(args *Params, tmpl *fasttemplate.Template) <-chan string {\n\tch := make(chan string)\n\tvar resep *regexp.Regexp\n\tif args.Sep != \"\" {\n\t\tresep = regexp.MustCompile(args.Sep)\n\t}\n\n\tscanner := getScanner()\n\tfs := os.Getenv(\"FS\")\n\tif fs == \"\" {\n\t\tfs = \" \"\n\t}\n\n\tgo func() {\n\t\tvar lines []string\n\t\tif resep == nil {\n\t\t\tlines = make([]string, 0, args.Nlines)\n\t\t}\n\t\tvar buf bytes.Buffer\n\t\tfor scanner.Scan() {\n\t\t\tbuf.Reset()\n\t\t\tline := scanner.Text()\n\t\t\tserr := scanner.Err()\n\t\t\tif serr == nil || (serr == io.EOF && len(line) > 0) {\n\t\t\t\t\/\/ TODO: make dropping bytes optional.\n\t\t\t\tif resep != nil {\n\t\t\t\t\ttoks := resep.Split(line, -1)\n\t\t\t\t\ttargs := fillTmplMap(toks, line)\n\t\t\t\t\t_, err := tmpl.Execute(&buf, targs)\n\t\t\t\t\tcheck(err)\n\t\t\t\t\thandleCommand(args, buf.String(), ch)\n\t\t\t\t} else {\n\t\t\t\t\tlines = append(lines, line)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif serr == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tlog.Fatal(serr)\n\t\t\t}\n\t\t\tif len(lines) >= args.Nlines {\n\t\t\t\ttargs := fillTmplMap(lines, strings.Join(lines, fs))\n\t\t\t\t_, err := tmpl.Execute(&buf, targs)\n\t\t\t\tcheck(err)\n\t\t\t\tlines = lines[:0]\n\t\t\t\thandleCommand(args, buf.String(), ch)\n\t\t\t}\n\t\t}\n\t\tif len(lines) > 0 {\n\t\t\ttargs := fillTmplMap(lines, strings.Join(lines, fs))\n\t\t\t_, err := tmpl.Execute(&buf, targs)\n\t\t\tcheck(err)\n\t\t\thandleCommand(args, buf.String(), ch)\n\t\t}\n\t\tclose(ch)\n\t}()\n\treturn ch\n}\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc init() {\n\tcolor.NoColor = !isatty.IsTerminal(os.Stderr.Fd())\n}\n\nfunc run(args Params) {\n\n\ttmpl := makeCommandTmpl(args.Command)\n\tcmds := genCommands(&args, tmpl)\n\n\tstdout := bufio.NewWriter(os.Stdout)\n\tdefer stdout.Flush()\n\n\tcancel := make(chan bool)\n\tdefer close(cancel)\n\tfails := 0\n\n\t\/\/ flush stdout every 2 seconds.\n\tlast := time.Now().Add(2 * time.Second)\n\tfor p := range process.Runner(cmds, args.Retry, cancel) {\n\t\tif ex := p.ExitCode(); ex != 0 {\n\t\t\tc := color.New(color.BgRed).Add(color.Bold)\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", c.SprintFunc()(fmt.Sprintf(\"ERROR with command: %s\", p)))\n\t\t\tExitCode = max(ExitCode, ex)\n\t\t\tfails++\n\t\t\tif args.StopOnError {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif args.Verbose {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", p)\n\t\t}\n\t\t_, err := io.Copy(stdout, p)\n\t\tcheck(err)\n\n\t\tp.Cleanup()\n\t\tif t := time.Now(); t.After(last) {\n\t\t\tstdout.Flush()\n\t\t\tlast = t.Add(2 * time.Second)\n\t\t}\n\t\tif args.log != nil {\n\t\t\t\/\/ if no error prefix the command with '#'\n\t\t\tif p.ExitCode() == 0 {\n\t\t\t\targs.log.WriteString(\"# \" + strings.Replace(p.CmdStr, \"\\n\", \"\\n# \", -1) + \"\\n\")\n\t\t\t} else {\n\t\t\t\targs.log.WriteString(p.CmdStr + \"\\n\")\n\t\t\t}\n\t\t\tstdout.Flush()\n\t\t}\n\t}\n\tstdout.Flush()\n\tif ExitCode == 0 && args.log != nil {\n\t\targs.log.WriteString(\"# SUCCESS\\n\")\n\t} else if args.log != nil {\n\t\tfmt.Fprintf(args.log, \"# FAILED %d commands\\n\", fails)\n\t}\n\n}\n\nfunc makeCommandTmpl(cmd string) *fasttemplate.Template {\n\tv := strings.Replace(cmd, \"{}\", \"{Line}\", -1)\n\treturn fasttemplate.New(v, \"{\", \"}\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/neurodrone\/aws-sqs\/sqs\"\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tawsAccessKey = flag.String(\"accesskey\", \"\", \"AWS Access Key\")\n\tawsSecret    = flag.String(\"secret\", \"\", \"AWS Secret Key\")\n\n\tregionId  = flag.String(\"region\", \"\", \"AWS Region ID\")\n\tuuid      = flag.String(\"uuid\", \"\", \"AWS Unique ID\")\n\tqueueName = flag.String(\"queue\", \"\", \"AWS Queue Name\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\te := validateInputs()\n\tif e.hasErrors() {\n\t\te.printErrors(os.Stderr)\n\t\tlog.Fatalf(\"Aborting.\")\n\t}\n\n\tsqsReq := &sqs.SQSRequest{\n\t\t*regionId,\n\t\t*uuid,\n\t\t*queueName,\n\t\t*awsAccessKey,\n\t\t*awsSecret,\n\t}\n\n\t\/*\n\t\tmessage := \"Message\"\n\t\t_, err := sqsReq.SendSQSMessage(message)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Unable to enqueue message: %s\", err)\n\t\t}\n\n\t\tlog.Println(\"Message sent.\")\n\t*\/\n\tmsgResp, err := sqsReq.ReceiveSQSMessage()\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to receive message: %s\", err)\n\t}\n\n\tlog.Println(msgResp.MessageId, \"received.\")\n\tlog.Println(msgResp.MessageBody)\n\n\t_, err = sqsReq.DeleteSQSMessage(msgResp.ReceiptHandle)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to delete message: %s\", msgResp.MessageId)\n\t}\n\n\tlog.Println(\"Successfully received and deleted.\")\n}\n\nfunc validateInputs() Errors {\n\terrs := make(Errors, 0)\n\n\tflag.VisitAll(func(fl *flag.Flag) {\n\t\tif fl.Value.String() == fl.DefValue {\n\t\t\terrs = append(errs, fmt.Errorf(\"%s needs to be set.\", fl.Usage))\n\t\t}\n\t})\n\n\treturn errs\n}\n<commit_msg>Add gobs to the main stub to ensure the transcoding is handled fine for it<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/neurodrone\/aws-sqs\/sqs\"\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tawsAccessKey = flag.String(\"accesskey\", \"\", \"AWS Access Key\")\n\tawsSecret    = flag.String(\"secret\", \"\", \"AWS Secret Key\")\n\n\tregionId  = flag.String(\"region\", \"\", \"AWS Region ID\")\n\tuuid      = flag.String(\"uuid\", \"\", \"AWS Unique ID\")\n\tqueueName = flag.String(\"queue\", \"\", \"AWS Queue Name\")\n)\n\ntype SampleMessageStruct struct {\n\tSomeStr string\n\tSomeInt int\n}\n\nfunc main() {\n\tflag.Parse()\n\n\te := validateInputs()\n\tif e.hasErrors() {\n\t\te.printErrors(os.Stderr)\n\t\tlog.Fatalf(\"Aborting.\")\n\t}\n\n\tsqsReq := &sqs.SQSRequest{\n\t\t*regionId,\n\t\t*uuid,\n\t\t*queueName,\n\t\t*awsAccessKey,\n\t\t*awsSecret,\n\t}\n\n\tvar buf bytes.Buffer\n\tvar message string\n\tvar m *SampleMessageStruct\n\n\tm = &SampleMessageStruct{\"strVal\", 7}\n\tgob.NewEncoder(&buf).Encode(m)\n\n\tmessage = buf.String()\n\t_, err := sqsReq.SendSQSMessage(message)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to enqueue message: %s\", err)\n\t}\n\tlog.Println(\"Message sent.\")\n\n\tmsgResp, err := sqsReq.ReceiveSQSMessage()\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to receive message: %s\", err)\n\t}\n\n\tlog.Println(msgResp.MessageId, \"received.\")\n\tmessage = msgResp.MessageBody\n\n\tm = new(SampleMessageStruct)\n\tgob.NewDecoder(bytes.NewBufferString(message)).Decode(m)\n\tlog.Println(m)\n\n\t_, err = sqsReq.DeleteSQSMessage(msgResp.ReceiptHandle)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to delete message: %s\", msgResp.MessageId)\n\t}\n\n\tlog.Println(\"Successfully received and deleted.\")\n}\n\nfunc validateInputs() Errors {\n\terrs := make(Errors, 0)\n\n\tflag.VisitAll(func(fl *flag.Flag) {\n\t\tif fl.Value.String() == fl.DefValue {\n\t\t\terrs = append(errs, fmt.Errorf(\"%s needs to be set.\", fl.Usage))\n\t\t}\n\t})\n\n\treturn errs\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\ntype Service struct {\n\tName    string\n\tAddress string\n\tPort    int\n}\n\nfunc (s Service) AddressAndPort() string {\n\treturn fmt.Sprintf(\"%s:%d\", s.Address, s.Port)\n}\n\nfunc main() {\n\tservices := loadServicesFromEnv()\n\tlog.Printf(\"Services: %#v\", services)\n\n\tvar wg sync.WaitGroup\n\tcancel := make(chan struct{})\n\n\tfor _, service := range services {\n\t\twg.Add(1)\n\t\tgo func(service Service) {\n\t\t\twaitForTcpConn(service, cancel)\n\t\t\twg.Done()\n\t\t}(service)\n\t}\n\n\ttimer := time.AfterFunc(10*time.Second, func() {\n\t\tclose(cancel)\n\t})\n\n\twg.Wait()\n\n\t\/\/ There's a race here that might result in assuming that a timeout happend\n\t\/\/ although none happend. It appears when the timer fires after the connection\n\t\/\/ succeeded, but before the check via Stop() below.\n\t\/\/ That shouldn't happen very often and the service was pretty short of timing out\n\t\/\/ anyway, so I guess that's ok for now.\n\tif !timer.Stop() {\n\t\tlog.Printf(\"Error: One or more services timed out\")\n\t\tos.Exit(1)\n\t}\n\tlog.Printf(\"All services are up!\")\n}\n\nfunc loadServicesFromEnv() []Service {\n\tservices := make([]Service, 0)\n\tfor _, line := range os.Environ() {\n\t\tkeyAndValue := strings.SplitN(line, \"=\", 2)\n\t\taddrKey := keyAndValue[0]\n\t\tif strings.HasSuffix(addrKey, \"_TCP_ADDR\") {\n\t\t\taddr := os.Getenv(addrKey)\n\t\t\tname := addrKey[:len(addrKey)-9] \/\/ cut off \"_TCP_ADDR\"\n\n\t\t\tportKey := name + \"_TCP_PORT\"\n\t\t\tportStr := os.Getenv(portKey)\n\t\t\tport, err := strconv.Atoi(portStr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Failed to convert '%v' to int, value: '%v' - skipping service '%v'\",\n\t\t\t\t\tportKey, portStr, name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tservices = append(services, Service{Name: name, Address: addr, Port: port})\n\t\t}\n\t}\n\treturn services\n}\n\nfunc waitForTcpConn(service Service, cancel <-chan struct{}) {\n\tvar cancelled int32 = 0\n\tgo func() {\n\t\t<-cancel\n\t\tatomic.StoreInt32(&cancelled, 1)\n\t}()\n\n\tvar conn net.Conn\n\terr := errors.New(\"init\")\n\tfor err != nil {\n\t\tconn, err = net.DialTimeout(\"tcp\", service.AddressAndPort(), 1*time.Second)\n\n\t\tif cancelled == 1 && err != nil {\n\t\t\tlog.Printf(\"Service %v (%v) timed out. Last error: %v\",\n\t\t\t\tservice.Name, service.AddressAndPort(), err)\n\t\t\treturn\n\t\t}\n\t}\n\tconn.Close()\n\tlog.Printf(\"Service %v (%v) is up\", service.Name, service.AddressAndPort())\n}\n<commit_msg>Make timeout configurable<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\ntype Service struct {\n\tName    string\n\tAddress string\n\tPort    int\n}\n\nfunc (s Service) AddressAndPort() string {\n\treturn fmt.Sprintf(\"%s:%d\", s.Address, s.Port)\n}\n\nvar timeout = flag.Int64(\"timeout\", 60, \"time to wait for all services to be up (seconds)\")\n\nfunc main() {\n\tflag.Parse()\n\n\tservices := loadServicesFromEnv()\n\tlog.Printf(\"Services: %#v\", services)\n\n\tvar wg sync.WaitGroup\n\tcancel := make(chan struct{})\n\n\tfor _, service := range services {\n\t\twg.Add(1)\n\t\tgo func(service Service) {\n\t\t\twaitForTcpConn(service, cancel)\n\t\t\twg.Done()\n\t\t}(service)\n\t}\n\n\ttimer := time.AfterFunc(time.Duration(*timeout)*time.Second, func() {\n\t\tclose(cancel)\n\t})\n\n\twg.Wait()\n\n\t\/\/ There's a race here that might result in assuming that a timeout happend\n\t\/\/ although none happend. It appears when the timer fires after the connection\n\t\/\/ succeeded, but before the check via Stop() below.\n\t\/\/ That shouldn't happen very often and the service was pretty short of timing out\n\t\/\/ anyway, so I guess that's ok for now.\n\tif !timer.Stop() {\n\t\tlog.Printf(\"Error: One or more services timed out after %d second(s)\", *timeout)\n\t\tos.Exit(1)\n\t}\n\tlog.Printf(\"All services are up!\")\n}\n\nfunc loadServicesFromEnv() []Service {\n\tservices := make([]Service, 0)\n\tfor _, line := range os.Environ() {\n\t\tkeyAndValue := strings.SplitN(line, \"=\", 2)\n\t\taddrKey := keyAndValue[0]\n\t\tif strings.HasSuffix(addrKey, \"_TCP_ADDR\") {\n\t\t\taddr := os.Getenv(addrKey)\n\t\t\tname := addrKey[:len(addrKey)-9] \/\/ cut off \"_TCP_ADDR\"\n\n\t\t\tportKey := name + \"_TCP_PORT\"\n\t\t\tportStr := os.Getenv(portKey)\n\t\t\tport, err := strconv.Atoi(portStr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Failed to convert '%v' to int, value: '%v' - skipping service '%v'\",\n\t\t\t\t\tportKey, portStr, name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tservices = append(services, Service{Name: name, Address: addr, Port: port})\n\t\t}\n\t}\n\treturn services\n}\n\nfunc waitForTcpConn(service Service, cancel <-chan struct{}) {\n\tvar cancelled int32 = 0\n\tgo func() {\n\t\t<-cancel\n\t\tatomic.StoreInt32(&cancelled, 1)\n\t}()\n\n\tvar conn net.Conn\n\terr := errors.New(\"init\")\n\tfor err != nil {\n\t\tconn, err = net.DialTimeout(\"tcp\", service.AddressAndPort(), 1*time.Second)\n\n\t\tif cancelled == 1 && err != nil {\n\t\t\tlog.Printf(\"Service %v (%v) timed out. Last error: %v\",\n\t\t\t\tservice.Name, service.AddressAndPort(), err)\n\t\t\treturn\n\t\t}\n\t}\n\tconn.Close()\n\tlog.Printf(\"Service %v (%v) is up\", service.Name, service.AddressAndPort())\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/feeds\"\n\trss \"github.com\/jteeuwen\/go-pkg-rss\"\n)\n\nvar podcastEpisodePrefix = regexp.MustCompile(`^\\d+: `)\n\nvar sourceFeeds = []sourceFeed{\n\t{uri: \"https:\/\/robots.thoughtbot.com\/summaries.xml\", name: \"Giant Robots blog\"},\n\t{uri: \"http:\/\/simplecast.fm\/podcasts\/271\/rss\", name: \"Giant Robots podcast\"},\n\t{uri: \"http:\/\/simplecast.fm\/podcasts\/272\/rss\", name: \"Build Phase podcast\"},\n\t{uri: \"http:\/\/simplecast.fm\/podcasts\/282\/rss\", name: \"The Bike Shed podcast\"},\n\t{uri: \"http:\/\/simplecast.fm\/podcasts\/1088\/rss\", name: \"Tentative podcast\"},\n\t{uri: \"https:\/\/simplecast.com\/podcasts\/2025\/rss\", name: \"The Laila and Brenda Show podcast\"},\n\t{uri: \"https:\/\/upcase.com\/the-weekly-iteration.rss\", name: \"The Weekly Iteration videos\"},\n}\n\nfunc main() {\n\tport := flag.String(\"port\", \"8080\", \"HTTP Port to listen on\")\n\tflag.Parse()\n\thttp.Handle(\"\/\", rssHandler(sourceFeeds))\n\tlog.Fatal(http.ListenAndServe(\":\"+*port, nil))\n}\n\nfunc rssHandler(sourceFeeds []sourceFeed) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tif req.Referer() == \"http:\/\/rss.thoughtbot.com\" {\n\t\t\thttp.Redirect(\n\t\t\t\tw,\n\t\t\t\treq,\n\t\t\t\t\"https:\/\/rss.thoughtbot.com\/\",\n\t\t\t\thttp.StatusMovedPermanently,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\tmaster := &feeds.Feed{\n\t\t\tTitle:       \"thoughtbot\",\n\t\t\tLink:        &feeds.Link{Href: \"https:\/\/rss.thoughtbot.com\"},\n\t\t\tDescription: \"All the thoughts fit to bot.\",\n\t\t\tAuthor:      &feeds.Author{Name: \"thoughtbot\", Email: \"hello@thoughtbot.com\"},\n\t\t\tCreated:     time.Now(),\n\t\t}\n\n\t\tfor _, feed := range sourceFeeds {\n\t\t\tfetch(feed, master)\n\t\t}\n\n\t\tsort.Sort(byCreated(master.Items))\n\n\t\tresult, err := master.ToAtom()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error generating feed: %v\", err)\n\t\t\thttp.Error(w, \"error generating feed\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t_, err = fmt.Fprintln(w, result)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error printing feed: %v\", err)\n\t\t\thttp.Error(w, \"error printing feed\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t})\n}\n\nfunc fetch(feed sourceFeed, master *feeds.Feed) {\n\tfetcher := rss.New(5, true, chanHandler, makeHandler(master, feed.name))\n\tclient := &http.Client{\n\t\tTimeout: time.Second,\n\t}\n\n\terr := fetcher.FetchClient(feed.uri, client, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc chanHandler(feed *rss.Feed, newchannels []*rss.Channel) {\n\t\/\/ no need to do anything...\n}\n\nfunc makeHandler(master *feeds.Feed, sourceName string) rss.ItemHandlerFunc {\n\treturn func(feed *rss.Feed, ch *rss.Channel, items []*rss.Item) {\n\t\tfor i := 0; i < len(items); i++ {\n\t\t\tpublished, err := items[i].ParsedPubDate()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"error parsing publication date: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tweekAgo := time.Now().AddDate(0, 0, -7)\n\n\t\t\tif published.After(weekAgo) {\n\t\t\t\titem := &feeds.Item{\n\t\t\t\t\tTitle:       stripPodcastEpisodePrefix(items[i].Title),\n\t\t\t\t\tLink:        &feeds.Link{Href: items[i].Links[0].Href},\n\t\t\t\t\tDescription: items[i].Description,\n\t\t\t\t\tAuthor:      &feeds.Author{Name: sourceName},\n\t\t\t\t\tCreated:     published,\n\t\t\t\t}\n\t\t\t\tmaster.Add(item)\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype byCreated []*feeds.Item\n\nfunc (s byCreated) Len() int {\n\treturn len(s)\n}\n\nfunc (s byCreated) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\nfunc (s byCreated) Less(i, j int) bool {\n\treturn s[j].Created.Before(s[i].Created)\n}\n\nfunc stripPodcastEpisodePrefix(s string) string {\n\treturn podcastEpisodePrefix.ReplaceAllString(s, \"\")\n}\n\ntype sourceFeed struct {\n\turi  string\n\tname string\n}\n<commit_msg>Use more generic technique to force SSL redirect<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/feeds\"\n\trss \"github.com\/jteeuwen\/go-pkg-rss\"\n)\n\nvar podcastEpisodePrefix = regexp.MustCompile(`^\\d+: `)\n\nvar sourceFeeds = []sourceFeed{\n\t{uri: \"https:\/\/robots.thoughtbot.com\/summaries.xml\", name: \"Giant Robots blog\"},\n\t{uri: \"http:\/\/simplecast.fm\/podcasts\/271\/rss\", name: \"Giant Robots podcast\"},\n\t{uri: \"http:\/\/simplecast.fm\/podcasts\/272\/rss\", name: \"Build Phase podcast\"},\n\t{uri: \"http:\/\/simplecast.fm\/podcasts\/282\/rss\", name: \"The Bike Shed podcast\"},\n\t{uri: \"http:\/\/simplecast.fm\/podcasts\/1088\/rss\", name: \"Tentative podcast\"},\n\t{uri: \"https:\/\/simplecast.com\/podcasts\/2025\/rss\", name: \"The Laila and Brenda Show podcast\"},\n\t{uri: \"https:\/\/upcase.com\/the-weekly-iteration.rss\", name: \"The Weekly Iteration videos\"},\n}\n\nfunc main() {\n\tport := flag.String(\"port\", \"8080\", \"HTTP Port to listen on\")\n\tflag.Parse()\n\thttp.Handle(\"\/\", rssHandler(sourceFeeds))\n\tlog.Fatal(http.ListenAndServe(\":\"+*port, nil))\n}\n\nfunc rssHandler(sourceFeeds []sourceFeed) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\tif req.Header.Get(\"X-Forwarded-Proto\") == \"http\" {\n\t\t\tdestination := *req.URL\n\t\t\tdestination.Host = req.Host\n\t\t\tdestination.Scheme = \"https\"\n\t\t\thttp.Redirect(w, req, destination.String(), http.StatusFound)\n\t\t\treturn\n\t\t}\n\n\t\tmaster := &feeds.Feed{\n\t\t\tTitle:       \"thoughtbot\",\n\t\t\tLink:        &feeds.Link{Href: \"https:\/\/rss.thoughtbot.com\"},\n\t\t\tDescription: \"All the thoughts fit to bot.\",\n\t\t\tAuthor:      &feeds.Author{Name: \"thoughtbot\", Email: \"hello@thoughtbot.com\"},\n\t\t\tCreated:     time.Now(),\n\t\t}\n\n\t\tfor _, feed := range sourceFeeds {\n\t\t\tfetch(feed, master)\n\t\t}\n\n\t\tsort.Sort(byCreated(master.Items))\n\n\t\tresult, err := master.ToAtom()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error generating feed: %v\", err)\n\t\t\thttp.Error(w, \"error generating feed\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t_, err = fmt.Fprintln(w, result)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error printing feed: %v\", err)\n\t\t\thttp.Error(w, \"error printing feed\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t})\n}\n\nfunc fetch(feed sourceFeed, master *feeds.Feed) {\n\tfetcher := rss.New(5, true, chanHandler, makeHandler(master, feed.name))\n\tclient := &http.Client{\n\t\tTimeout: time.Second,\n\t}\n\n\terr := fetcher.FetchClient(feed.uri, client, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc chanHandler(feed *rss.Feed, newchannels []*rss.Channel) {\n\t\/\/ no need to do anything...\n}\n\nfunc makeHandler(master *feeds.Feed, sourceName string) rss.ItemHandlerFunc {\n\treturn func(feed *rss.Feed, ch *rss.Channel, items []*rss.Item) {\n\t\tfor i := 0; i < len(items); i++ {\n\t\t\tpublished, err := items[i].ParsedPubDate()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"error parsing publication date: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tweekAgo := time.Now().AddDate(0, 0, -7)\n\n\t\t\tif published.After(weekAgo) {\n\t\t\t\titem := &feeds.Item{\n\t\t\t\t\tTitle:       stripPodcastEpisodePrefix(items[i].Title),\n\t\t\t\t\tLink:        &feeds.Link{Href: items[i].Links[0].Href},\n\t\t\t\t\tDescription: items[i].Description,\n\t\t\t\t\tAuthor:      &feeds.Author{Name: sourceName},\n\t\t\t\t\tCreated:     published,\n\t\t\t\t}\n\t\t\t\tmaster.Add(item)\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype byCreated []*feeds.Item\n\nfunc (s byCreated) Len() int {\n\treturn len(s)\n}\n\nfunc (s byCreated) Swap(i, j int) {\n\ts[i], s[j] = s[j], s[i]\n}\n\nfunc (s byCreated) Less(i, j int) bool {\n\treturn s[j].Created.Before(s[i].Created)\n}\n\nfunc stripPodcastEpisodePrefix(s string) string {\n\treturn podcastEpisodePrefix.ReplaceAllString(s, \"\")\n}\n\ntype sourceFeed struct {\n\turi  string\n\tname string\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/line\/line-bot-sdk-go\/linebot\"\n)\n\n\/*\n<<<<<<< HEAD\n<<<<<<< HEAD\n=======\n>>>>>>> 09a61a620751c49e8b67d3244f5280b4b309e1ae\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\nvar bot *linebot.Client\nvar eggyoID = \"ufa92a3a52f197e19bfddeb5ca0595e93\"\nvar logNof = \"open\"\n\ntype GeoContent struct {\n\tLatLong string `json:\"latLon\"`\n\tUtm     string `json:\"utm\"`\n\tMgrs    string `json:\"mgrs\"`\n}\n\ntype ResultGeoLoc struct {\n\tResults GeoContent `json:\"result\"`\n}\n\nfunc getGeoLoc(body []byte) (*ResultGeoLoc, error) {\n\tvar s = new(ResultGeoLoc)\n\terr := json.Unmarshal(body, &s)\n\tif err != nil {\n\t\tfmt.Println(\"whoops:\", err)\n\t}\n\treturn s, err\n<<<<<<< HEAD\n<<<<<<< HEAD\n<<<<<<< HEAD\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n}*\/\n\nfunc main() {\n\n\tbot, err := linebot.New(\n\t\tos.Getenv(\"ChannelSecret\"),\n\t\tos.Getenv(\"MID\"),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ Setup HTTP Server for receiving requests from LINE platform\n\thttp.HandleFunc(\"\/callback\", func(w http.ResponseWriter, req *http.Request) {\n\t\tevents, err := bot.ParseRequest(req)\n\t\tif err != nil {\n\t\t\tif err == linebot.ErrInvalidSignature {\n\t\t\t\tw.WriteHeader(400)\n\t\t\t} else {\n\t\t\t\tw.WriteHeader(500)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tfor _, event := range events {\n\t\t\tif event.Type == linebot.EventTypeMessage {\n\t\t\t\tswitch message := event.Message.(type) {\n\t\t\t\tcase *linebot.TextMessage:\n\t\t\t\t\tif _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(message.Text)).Do(); err != nil {\n\t\t\t\t\t\tlog.Print(err)\n\t\t\t\t\t}\n\n\t\t\t\tcase *linebot.ImageMessage:\n\n\t\t\t\t\tcontent, err := bot.GetMessageContent(message.ID).Do()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tdefer content.Content.Close()\n\t\t\t\t\tlog.Printf(\"Got file: %s\", content.ContentType)\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\t})\n\t\/\/ This is just sample code.\n\t\/\/ For actual use, you must support HTTPS by using `ListenAndServeTLS`, a reverse proxy or something else.\n\tif err := http.ListenAndServe(\":\"+os.Getenv(\"PORT\"), nil); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\/*\n<<<<<<< HEAD\n<<<<<<< HEAD\n=======\n}\n\nfunc main() {\n\tgetAllUser()\n\t\/\/ line bot\n\tstrID := os.Getenv(\"ChannelID\")\n\tnumID, err := strconv.ParseInt(strID, 10, 64)\n\tif err != nil {\n\t\tlog.Fatal(\"Wrong environment setting about ChannelID\")\n\t}\n\n\tbot, err = linebot.NewClient(numID, os.Getenv(\"ChannelSecret\"), os.Getenv(\"MID\"))\n\tlog.Println(\"Bot:\", bot, \" err:\", err)\n\thttp.HandleFunc(\"\/callback\", callbackHandler)\n\tport := os.Getenv(\"PORT\")\n\taddr := fmt.Sprintf(\":%s\", port)\n\thttp.ListenAndServe(addr, nil)\n\t\/\/test\n\n}\n>>>>>>> 09a61a620751c49e8b67d3244f5280b4b309e1ae\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\nfunc callbackHandler(w http.ResponseWriter, r *http.Request) {\n\n\treceived, err := bot.ParseRequest(r)\n\tif err != nil {\n\t\tif err == linebot.ErrInvalidSignature {\n\t\t\tw.WriteHeader(400)\n\t\t} else {\n\t\t\tw.WriteHeader(500)\n\t\t}\n\t\treturn\n\t}\n\tfor _, result := range received.Results {\n\t\tcontent := result.Content()\n\t\tlog.Println(\"-->\", content)\n\n\t\t\/\/Log detail receive content\n\t\tif content != nil {\n\t\t\tlog.Println(\"RECEIVE Msg:\", content.IsMessage, \" OP:\", content.IsOperation, \" type:\", content.ContentType, \" from:\", content.From, \"to:\", content.To, \" ID:\", content.ID)\n\t\t}\n\t\t\/\/ user add friend\n\t\tif content != nil && content.IsOperation && content.OpType == linebot.OpTypeAddedAsFriend {\n\t\t\tout := fmt.Sprintf(\"Bot แปลงพิกัด Eggyo\\nวิธีใช้\\nเพียงแค่กดแชร์ Location ที่ต้องการ ระบบจะทำการแปลง Location เป็นพิกัดระบบต่างๆ และหาความสูงจากระดับน้ำทะเลให้\\n\\nหรือจะพูดคุยกับ bot ก็ได้\\nกด #help เพื่อดูวิธีใช้อื่นๆ \\nติดต่อผู้พัฒนา LINE ID : eggyo\")\n\t\t\t\/\/result.RawContent.Params[0] is who send your bot friend added operation, otherwise you cannot get in content or operation content.\n\t\t\t_, err = bot.SendText([]string{content.From}, out)\n\t\t\tif logNof == \"open\" {\n\t\t\t\tbot.SendText([]string{eggyoID}, \"bot has a new friend :\"+content.From)\n\t\t\t}\n\n\t\t\taddNewUser(content.From)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\n\t\tif content != nil && content.IsMessage && content.ContentType == linebot.ContentTypeText {\n\n\t\t\ttext, err := content.TextContent()\n\t\t\tif logNof == \"open\" {\n\t\t\t\tbot.SendText([]string{eggyoID}, \"bot get msg:\"+text.Text+\"\\nfrom :\"+content.From)\n\t\t\t}\n\t\t\t\/\/ reply message\n\t\t\tvar processedText = messageCheck(text.Text)\n\t\t\t_, err = bot.SendText([]string{content.From}, processedText)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\t\tif content != nil && content.ContentType == linebot.ContentTypeLocation {\n\t\t\t_, err = bot.SendText([]string{content.From}, \"ระบบกำลังประมวลผล...\")\n\n\t\t\tloc, err := content.LocationContent()\n\n<<<<<<< HEAD\n<<<<<<< HEAD\n<<<<<<< HEAD\n\t\t\t\/\/ add eggyo geo test\/\/\n\t\t\tresp, err := http.Get(\"http:\/\/eggyo-geo-node.herokuapp.com\/geo\/\" + FloatToString(loc.Latitude) + \",\" + FloatToString(loc.Longitude))\n=======\n\t\t\t\/\/ add eggyo geo test\n\t\t\tresp, err := http.Get(\"http:\/\/eggyo-geo-node.herokuapp.com\/geo\/\" + FloatToString(loc.Latitude) + \"\/\" + FloatToString(loc.Longitude))\n>>>>>>> 09a61a620751c49e8b67d3244f5280b4b309e1ae\n=======\n\t\t\t\/\/ add eggyo geo test\/\/\n\t\t\tresp, err := http.Get(\"http:\/\/eggyo-geo-node.herokuapp.com\/geo\/\" + FloatToString(loc.Latitude) + \",\" + FloatToString(loc.Longitude))\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n=======\n\t\t\t\/\/ add eggyo geo test\/\/\n\t\t\tresp, err := http.Get(\"http:\/\/eggyo-geo-node.herokuapp.com\/geo\/\" + FloatToString(loc.Latitude) + \",\" + FloatToString(loc.Longitude))\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n\t\t\tif err != nil {\n\t\t\t\tprintln(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\t\tlog.Println(string(body))\n\n\t\t\tvar elev = callGoogleElev(loc.Latitude, loc.Longitude)\n\t\t\tgeo, err := getGeoLoc([]byte(body))\n\t\t\t_, err = bot.SendText([]string{content.From}, \"LatLong :\"+geo.Results.LatLong)\n\t\t\t_, err = bot.SendText([]string{content.From}, \"Utm :\"+geo.Results.Utm+\"\\n\\nMgrs :\"+geo.Results.Mgrs+\"\\n\\nAltitude :\"+elev)\n\t\t\tif logNof == \"open\" {\n\t\t\t\tbot.SendText([]string{eggyoID}, \"bot get loc:\"+geo.Results.Mgrs+\"\\nfrom :\"+content.From)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\t}\n<<<<<<< HEAD\n<<<<<<< HEAD\n<<<<<<< HEAD\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n*\/\n<commit_msg>v.5.1.2<commit_after>\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/line\/line-bot-sdk-go\/linebot\"\n)\n\n\/*\n<<<<<<< HEAD\n<<<<<<< HEAD\n=======\n>>>>>>> 09a61a620751c49e8b67d3244f5280b4b309e1ae\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\nvar bot *linebot.Client\nvar eggyoID = \"ufa92a3a52f197e19bfddeb5ca0595e93\"\nvar logNof = \"open\"\n\ntype GeoContent struct {\n\tLatLong string `json:\"latLon\"`\n\tUtm     string `json:\"utm\"`\n\tMgrs    string `json:\"mgrs\"`\n}\n\ntype ResultGeoLoc struct {\n\tResults GeoContent `json:\"result\"`\n}\n\nfunc getGeoLoc(body []byte) (*ResultGeoLoc, error) {\n\tvar s = new(ResultGeoLoc)\n\terr := json.Unmarshal(body, &s)\n\tif err != nil {\n\t\tfmt.Println(\"whoops:\", err)\n\t}\n\treturn s, err\n<<<<<<< HEAD\n<<<<<<< HEAD\n<<<<<<< HEAD\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n}*\/\n\nfunc main() {\n\n\tbot, err := linebot.New(\n\t\tos.Getenv(\"ChannelSecret\"),\n\t\tos.Getenv(\"MID\"),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ Setup HTTP Server for receiving requests from LINE platform\n\thttp.HandleFunc(\"\/callback\", func(w http.ResponseWriter, req *http.Request) {\n\t\tevents, err := bot.ParseRequest(req)\n\t\tif err != nil {\n\t\t\tif err == linebot.ErrInvalidSignature {\n\t\t\t\tw.WriteHeader(400)\n\t\t\t} else {\n\t\t\t\tw.WriteHeader(500)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tfor _, event := range events {\n\t\t\tif event.Type == linebot.EventTypeMessage {\n\t\t\t\tswitch message := event.Message.(type) {\n\t\t\t\tcase *linebot.TextMessage:\n\t\t\t\t\tif _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(message.Text)).Do(); err != nil {\n\t\t\t\t\t\tlog.Print(err)\n\t\t\t\t\t}\n\n\t\t\t\tcase *linebot.ImageMessage:\n\n\t\t\t\t\tcontent, err := bot.GetMessageContent(message.ID).Do()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Print(err)\n\t\t\t\t\t}\n\t\t\t\t\tdefer content.Content.Close()\n\t\t\t\t\tlog.Printf(\"Got file: %s\", content.ContentType)\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\t})\n\t\/\/ This is just sample code.\n\t\/\/ For actual use, you must support HTTPS by using `ListenAndServeTLS`, a reverse proxy or something else.\n\tif err := http.ListenAndServe(\":\"+os.Getenv(\"PORT\"), nil); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\n\/*\n<<<<<<< HEAD\n<<<<<<< HEAD\n=======\n}\n\nfunc main() {\n\tgetAllUser()\n\t\/\/ line bot\n\tstrID := os.Getenv(\"ChannelID\")\n\tnumID, err := strconv.ParseInt(strID, 10, 64)\n\tif err != nil {\n\t\tlog.Fatal(\"Wrong environment setting about ChannelID\")\n\t}\n\n\tbot, err = linebot.NewClient(numID, os.Getenv(\"ChannelSecret\"), os.Getenv(\"MID\"))\n\tlog.Println(\"Bot:\", bot, \" err:\", err)\n\thttp.HandleFunc(\"\/callback\", callbackHandler)\n\tport := os.Getenv(\"PORT\")\n\taddr := fmt.Sprintf(\":%s\", port)\n\thttp.ListenAndServe(addr, nil)\n\t\/\/test\n\n}\n>>>>>>> 09a61a620751c49e8b67d3244f5280b4b309e1ae\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\nfunc callbackHandler(w http.ResponseWriter, r *http.Request) {\n\n\treceived, err := bot.ParseRequest(r)\n\tif err != nil {\n\t\tif err == linebot.ErrInvalidSignature {\n\t\t\tw.WriteHeader(400)\n\t\t} else {\n\t\t\tw.WriteHeader(500)\n\t\t}\n\t\treturn\n\t}\n\tfor _, result := range received.Results {\n\t\tcontent := result.Content()\n\t\tlog.Println(\"-->\", content)\n\n\t\t\/\/Log detail receive content\n\t\tif content != nil {\n\t\t\tlog.Println(\"RECEIVE Msg:\", content.IsMessage, \" OP:\", content.IsOperation, \" type:\", content.ContentType, \" from:\", content.From, \"to:\", content.To, \" ID:\", content.ID)\n\t\t}\n\t\t\/\/ user add friend\n\t\tif content != nil && content.IsOperation && content.OpType == linebot.OpTypeAddedAsFriend {\n\t\t\tout := fmt.Sprintf(\"Bot แปลงพิกัด Eggyo\\nวิธีใช้\\nเพียงแค่กดแชร์ Location ที่ต้องการ ระบบจะทำการแปลง Location เป็นพิกัดระบบต่างๆ และหาความสูงจากระดับน้ำทะเลให้\\n\\nหรือจะพูดคุยกับ bot ก็ได้\\nกด #help เพื่อดูวิธีใช้อื่นๆ \\nติดต่อผู้พัฒนา LINE ID : eggyo\")\n\t\t\t\/\/result.RawContent.Params[0] is who send your bot friend added operation, otherwise you cannot get in content or operation content.\n\t\t\t_, err = bot.SendText([]string{content.From}, out)\n\t\t\tif logNof == \"open\" {\n\t\t\t\tbot.SendText([]string{eggyoID}, \"bot has a new friend :\"+content.From)\n\t\t\t}\n\n\t\t\taddNewUser(content.From)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\n\t\tif content != nil && content.IsMessage && content.ContentType == linebot.ContentTypeText {\n\n\t\t\ttext, err := content.TextContent()\n\t\t\tif logNof == \"open\" {\n\t\t\t\tbot.SendText([]string{eggyoID}, \"bot get msg:\"+text.Text+\"\\nfrom :\"+content.From)\n\t\t\t}\n\t\t\t\/\/ reply message\n\t\t\tvar processedText = messageCheck(text.Text)\n\t\t\t_, err = bot.SendText([]string{content.From}, processedText)\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\t\tif content != nil && content.ContentType == linebot.ContentTypeLocation {\n\t\t\t_, err = bot.SendText([]string{content.From}, \"ระบบกำลังประมวลผล...\")\n\n\t\t\tloc, err := content.LocationContent()\n\n<<<<<<< HEAD\n<<<<<<< HEAD\n<<<<<<< HEAD\n\t\t\t\/\/ add eggyo geo test\/\/\n\t\t\tresp, err := http.Get(\"http:\/\/eggyo-geo-node.herokuapp.com\/geo\/\" + FloatToString(loc.Latitude) + \",\" + FloatToString(loc.Longitude))\n=======\n\t\t\t\/\/ add eggyo geo test\n\t\t\tresp, err := http.Get(\"http:\/\/eggyo-geo-node.herokuapp.com\/geo\/\" + FloatToString(loc.Latitude) + \"\/\" + FloatToString(loc.Longitude))\n>>>>>>> 09a61a620751c49e8b67d3244f5280b4b309e1ae\n=======\n\t\t\t\/\/ add eggyo geo test\/\/\n\t\t\tresp, err := http.Get(\"http:\/\/eggyo-geo-node.herokuapp.com\/geo\/\" + FloatToString(loc.Latitude) + \",\" + FloatToString(loc.Longitude))\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n=======\n\t\t\t\/\/ add eggyo geo test\/\/\n\t\t\tresp, err := http.Get(\"http:\/\/eggyo-geo-node.herokuapp.com\/geo\/\" + FloatToString(loc.Latitude) + \",\" + FloatToString(loc.Longitude))\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n\t\t\tif err != nil {\n\t\t\t\tprintln(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\t\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\t\tlog.Println(string(body))\n\n\t\t\tvar elev = callGoogleElev(loc.Latitude, loc.Longitude)\n\t\t\tgeo, err := getGeoLoc([]byte(body))\n\t\t\t_, err = bot.SendText([]string{content.From}, \"LatLong :\"+geo.Results.LatLong)\n\t\t\t_, err = bot.SendText([]string{content.From}, \"Utm :\"+geo.Results.Utm+\"\\n\\nMgrs :\"+geo.Results.Mgrs+\"\\n\\nAltitude :\"+elev)\n\t\t\tif logNof == \"open\" {\n\t\t\t\tbot.SendText([]string{eggyoID}, \"bot get loc:\"+geo.Results.Mgrs+\"\\nfrom :\"+content.From)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\t}\n<<<<<<< HEAD\n<<<<<<< HEAD\n<<<<<<< HEAD\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n=======\n>>>>>>> 66cf34abf6b2ed7caa5c018b73c50380be01e401\n*\/\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/zerok\/statusd\/Godeps\/_workspace\/src\/gopkg.in\/v2\/yaml\"\n)\n\nconst (\n\tDEFAULT_TIMEOUT = 30\n\tDEFAULT_DELAY   = 30\n\tSTATUS_OFFLINE  = \"offline\"\n\tSTATUS_ONLINE   = \"online\"\n)\n\ntype ServerConfiguration struct {\n\tIsAliveUrl string `yaml:\"isAliveUrl\"`\n\tTimeout    int    `yaml:\"timeout\"`\n\tDelay      int    `yaml:\"delay\"`\n}\n\ntype HttpConfiguration struct {\n\tHostAddr string `yaml:\"addr\"`\n}\n\ntype SlackConfiguration struct {\n\tToken            string              `yaml:\"token\"`\n\tTeam             string              `yaml:\"team\"`\n\tNotifiedChannels map[string][]string `yaml:\"channels\"`\n}\n\ntype Configuration struct {\n\tServers map[string]ServerConfiguration `yaml:\"servers\"`\n\tSlack   SlackConfiguration             `yaml:\"slack\"`\n\tHttp    HttpConfiguration              `yaml:\"http\"`\n}\n\nvar statusRegistryManager StatusRegistryManager = NewStatusRegistryManager()\n\n\/\/ NewConfiguration parses YAML data provided through a Reader\n\/\/ into our configuration object. If any error occurs, no\n\/\/ Configuration will be returned and an error is generated.\nfunc NewConfiguration(r io.Reader) (*Configuration, error) {\n\tresult := &Configuration{}\n\trawData, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = yaml.Unmarshal(rawData, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\n\/\/ NewConfigurationFromFile creates a new Configuration struct from\n\/\/ the file behind the given path.\nfunc NewConfigurationFromFile(filepath string) (*Configuration, error) {\n\tfile, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\treturn NewConfiguration(file)\n}\n\n\/\/ The StatusHandler updates the global server status mapping and triggers notifications\n\/\/ if a server's status has changed.\nfunc StatusHandler(config Configuration, statusUpdateChannel <-chan StatusUpdate, exitChannel chan struct{}, doneGroup *sync.WaitGroup) {\n\tnotificationChannel := make(chan StatusUpdate, 10)\n\tnotificationDoneGroup := sync.WaitGroup{}\n\tvar notifySlack bool = (len(config.Slack.NotifiedChannels) != 0)\n\tif notifySlack {\n\t\tnotificationDoneGroup.Add(1)\n\t\tgo SlackNotifier(config, notificationChannel, &notificationDoneGroup)\n\t}\nloop:\n\tfor {\n\t\tselect {\n\t\tcase status := <-statusUpdateChannel:\n\t\t\tpreviousStatus := statusRegistryManager.GetStatus(status.ServerName)\n\t\t\tstatusRegistryManager.SetStatus(status)\n\t\t\tlog.Println(status)\n\t\t\tif notifySlack {\n\t\t\t\t\/\/ If this was the first time the server got a status, don't send out a notification to avoid\n\t\t\t\t\/\/ noise during restarts.\n\t\t\t\tif previousStatus != \"\" {\n\t\t\t\t\tnotificationChannel <- status\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"Skipping first status from entering the notification chain\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\tcase <-exitChannel:\n\t\t\tbreak loop\n\t\t}\n\t}\n\tclose(notificationChannel)\n\tlog.Println(\"Waiting for notification handlers to shut down.\")\n\tnotificationDoneGroup.Wait()\n\tdoneGroup.Done()\n}\n\n\/\/ ServerHandler is responsible for checking a single server periodically and\n\/\/ reporting any status changes through the statusUpdateChannel.\nfunc ServerHandler(serverName string, serverConfig ServerConfiguration, statusUpdateChannel chan<- StatusUpdate, exitChannel chan struct{}, doneGroup *sync.WaitGroup) {\n\tclient := http.Client{}\n\tclient.CheckRedirect = func(req *http.Request, via []*http.Request) error {\n\t\treturn fmt.Errorf(\"Received a redirection as response\")\n\t}\n\tpreviousStatus := \"\"\n\tnewStatus := \"\"\n\ttimeout := serverConfig.Timeout\n\tdelay := serverConfig.Delay\n\tif timeout == 0 {\n\t\ttimeout = DEFAULT_TIMEOUT\n\t}\n\tif delay == 0 {\n\t\tdelay = DEFAULT_DELAY\n\t}\n\tfinalTimeout, err := time.ParseDuration(fmt.Sprintf(\"%ds\", timeout))\n\tif err != nil {\n\t\tfinalTimeout = DEFAULT_TIMEOUT * time.Second\n\t}\n\tfinalDelay, err := time.ParseDuration(fmt.Sprintf(\"%ds\", delay))\n\tif err != nil {\n\t\tfinalDelay = DEFAULT_DELAY * time.Second\n\t}\n\tclient.Timeout = finalTimeout\n\tlog.Printf(\"Processing server %v with a timeout of %vs\\n\", serverName, finalTimeout.Seconds())\n\tvar nextPlannedCheck time.Time\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-exitChannel:\n\t\t\tlog.Printf(\"Handler for %s received exit signal\\n\", serverName)\n\t\t\tbreak loop\n\t\tdefault:\n\t\t}\n\n\t\tif time.Now().Before(nextPlannedCheck) {\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Printf(\"Checking %s\\n\", serverName)\n\t\tstartTime := time.Now()\n\t\tresp, err := client.Get(serverConfig.IsAliveUrl)\n\t\tduration := time.Now().Sub(startTime)\n\t\tif err != nil {\n\t\t\tnewStatus = STATUS_OFFLINE\n\t\t} else {\n\t\t\tif resp.StatusCode != 200 {\n\t\t\t\tnewStatus = STATUS_OFFLINE\n\n\t\t\t} else {\n\t\t\t\tnewStatus = STATUS_ONLINE\n\t\t\t}\n\t\t\tresp.Body.Close()\n\t\t}\n\t\tif newStatus != previousStatus {\n\t\t\tstatusUpdateChannel <- StatusUpdate{ServerName: serverName, Status: newStatus, Duration: duration}\n\t\t}\n\t\tpreviousStatus = newStatus\n\n\t\t\/\/ Check the server periodically\n\t\tif newStatus == STATUS_OFFLINE {\n\t\t\tnextPlannedCheck = time.Now().Add(finalDelay * 2)\n\t\t} else {\n\t\t\tnextPlannedCheck = time.Now().Add(finalDelay)\n\t\t}\n\t}\n\tlog.Printf(\"Shutting down %s worker\\n\", serverName)\n\tdoneGroup.Done()\n}\n\nfunc main() {\n\tvar configPath string\n\t\/\/ First we have to determine what servers should be checked and how. For that we\n\t\/\/ parse our configuration file.\n\tflag.StringVar(&configPath, \"config\", \"\", \"Path to a configuration file\")\n\tflag.Parse()\n\tif configPath == \"\" {\n\t\tlog.Fatalln(\"Please specify a configuration file using the -config flag\")\n\t}\n\tconfig, err := NewConfigurationFromFile(configPath)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tif config.Servers == nil || len(config.Servers) == 0 {\n\t\tlog.Fatalln(\"No servers configured\")\n\t}\n\n\tdoneGroup := sync.WaitGroup{}\n\texitChannel := make(chan struct{}, len(config.Servers))\n\tstatusUpdateChannel := make(chan StatusUpdate, len(config.Servers))\n\tsignalChannel := make(chan os.Signal)\n\n\tdoneGroup.Add(1)\n\tgo StatusHandler(*config, statusUpdateChannel, exitChannel, &doneGroup)\n\n\t\/\/ For every server we create a seperate go-routine that checks the server periodically\n\tfor serverName, serverConfig := range config.Servers {\n\t\tdoneGroup.Add(1)\n\t\tgo ServerHandler(serverName, serverConfig, statusUpdateChannel, exitChannel, &doneGroup)\n\t}\n\n\tif config.Http.HostAddr != \"\" {\n\t\t\/\/ Can't add a waitgroup handler for the HTTP server just yet. Perhaps in Go 1.4 ;)\n\t\tgo HttpHandler(config.Http.HostAddr, &doneGroup)\n\t} else {\n\t\tlog.Println(\"No HTTP configuration present. Not starting HTTP server.\")\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tsign := <-signalChannel\n\t\t\tstatusRegistryManager.ShowDown()\n\t\t\tlog.Printf(\"Received %v. Shutting down workers\", sign)\n\t\t\tfor _ = range config.Servers {\n\t\t\t\texitChannel <- struct{}{}\n\t\t\t}\n\t\t\t\/\/ An additional notification for the status handler and the web interface\n\t\t\texitChannel <- struct{}{}\n\t\t\texitChannel <- struct{}{}\n\t\t}\n\t}()\n\n\tsignal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)\n\n\tlog.Println(\"Waiting for threads to exit.\")\n\tdoneGroup.Wait()\n\tclose(exitChannel)\n\tclose(statusUpdateChannel)\n}\n<commit_msg>Make things work for broken TLS certs<commit_after>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/zerok\/statusd\/Godeps\/_workspace\/src\/gopkg.in\/v2\/yaml\"\n)\n\nconst (\n\tDEFAULT_TIMEOUT = 30\n\tDEFAULT_DELAY   = 30\n\tSTATUS_OFFLINE  = \"offline\"\n\tSTATUS_ONLINE   = \"online\"\n)\n\ntype ServerConfiguration struct {\n\tIsAliveUrl string `yaml:\"isAliveUrl\"`\n\tTimeout    int    `yaml:\"timeout\"`\n\tDelay      int    `yaml:\"delay\"`\n}\n\ntype HttpConfiguration struct {\n\tHostAddr string `yaml:\"addr\"`\n}\n\ntype SlackConfiguration struct {\n\tToken            string              `yaml:\"token\"`\n\tTeam             string              `yaml:\"team\"`\n\tNotifiedChannels map[string][]string `yaml:\"channels\"`\n}\n\ntype Configuration struct {\n\tServers map[string]ServerConfiguration `yaml:\"servers\"`\n\tSlack   SlackConfiguration             `yaml:\"slack\"`\n\tHttp    HttpConfiguration              `yaml:\"http\"`\n}\n\nvar statusRegistryManager StatusRegistryManager = NewStatusRegistryManager()\n\n\/\/ NewConfiguration parses YAML data provided through a Reader\n\/\/ into our configuration object. If any error occurs, no\n\/\/ Configuration will be returned and an error is generated.\nfunc NewConfiguration(r io.Reader) (*Configuration, error) {\n\tresult := &Configuration{}\n\trawData, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = yaml.Unmarshal(rawData, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\n\/\/ NewConfigurationFromFile creates a new Configuration struct from\n\/\/ the file behind the given path.\nfunc NewConfigurationFromFile(filepath string) (*Configuration, error) {\n\tfile, err := os.Open(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\treturn NewConfiguration(file)\n}\n\n\/\/ The StatusHandler updates the global server status mapping and triggers notifications\n\/\/ if a server's status has changed.\nfunc StatusHandler(config Configuration, statusUpdateChannel <-chan StatusUpdate, exitChannel chan struct{}, doneGroup *sync.WaitGroup) {\n\tnotificationChannel := make(chan StatusUpdate, 10)\n\tnotificationDoneGroup := sync.WaitGroup{}\n\tvar notifySlack bool = (len(config.Slack.NotifiedChannels) != 0)\n\tif notifySlack {\n\t\tnotificationDoneGroup.Add(1)\n\t\tgo SlackNotifier(config, notificationChannel, &notificationDoneGroup)\n\t}\nloop:\n\tfor {\n\t\tselect {\n\t\tcase status := <-statusUpdateChannel:\n\t\t\tpreviousStatus := statusRegistryManager.GetStatus(status.ServerName)\n\t\t\tstatusRegistryManager.SetStatus(status)\n\t\t\tlog.Println(status)\n\t\t\tif notifySlack {\n\t\t\t\t\/\/ If this was the first time the server got a status, don't send out a notification to avoid\n\t\t\t\t\/\/ noise during restarts.\n\t\t\t\tif previousStatus != \"\" {\n\t\t\t\t\tnotificationChannel <- status\n\t\t\t\t} else {\n\t\t\t\t\tlog.Println(\"Skipping first status from entering the notification chain\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\tcase <-exitChannel:\n\t\t\tbreak loop\n\t\t}\n\t}\n\tclose(notificationChannel)\n\tlog.Println(\"Waiting for notification handlers to shut down.\")\n\tnotificationDoneGroup.Wait()\n\tdoneGroup.Done()\n}\n\n\/\/ ServerHandler is responsible for checking a single server periodically and\n\/\/ reporting any status changes through the statusUpdateChannel.\nfunc ServerHandler(serverName string, serverConfig ServerConfiguration, statusUpdateChannel chan<- StatusUpdate, exitChannel chan struct{}, doneGroup *sync.WaitGroup) {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := http.Client{Transport: tr}\n\tclient.CheckRedirect = func(req *http.Request, via []*http.Request) error {\n\t\treturn fmt.Errorf(\"Received a redirection as response\")\n\t}\n\tpreviousStatus := \"\"\n\tnewStatus := \"\"\n\ttimeout := serverConfig.Timeout\n\tdelay := serverConfig.Delay\n\tif timeout == 0 {\n\t\ttimeout = DEFAULT_TIMEOUT\n\t}\n\tif delay == 0 {\n\t\tdelay = DEFAULT_DELAY\n\t}\n\tfinalTimeout, err := time.ParseDuration(fmt.Sprintf(\"%ds\", timeout))\n\tif err != nil {\n\t\tfinalTimeout = DEFAULT_TIMEOUT * time.Second\n\t}\n\tfinalDelay, err := time.ParseDuration(fmt.Sprintf(\"%ds\", delay))\n\tif err != nil {\n\t\tfinalDelay = DEFAULT_DELAY * time.Second\n\t}\n\tclient.Timeout = finalTimeout\n\tlog.Printf(\"Processing server %v with a timeout of %vs\\n\", serverName, finalTimeout.Seconds())\n\tvar nextPlannedCheck time.Time\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-exitChannel:\n\t\t\tlog.Printf(\"Handler for %s received exit signal\\n\", serverName)\n\t\t\tbreak loop\n\t\tdefault:\n\t\t}\n\n\t\tif time.Now().Before(nextPlannedCheck) {\n\t\t\ttime.Sleep(time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\tstartTime := time.Now()\n\t\tresp, err := client.Get(serverConfig.IsAliveUrl)\n\t\tduration := time.Now().Sub(startTime)\n\t\tif err != nil {\n\t\t\tlog.Printf(err.Error())\n\t\t\tnewStatus = STATUS_OFFLINE\n\t\t} else {\n\t\t\tif resp.StatusCode != 200 {\n\t\t\t\tlog.Printf(\"Returned status %v\", resp.StatusCode)\n\t\t\t\tnewStatus = STATUS_OFFLINE\n\n\t\t\t} else {\n\t\t\t\tnewStatus = STATUS_ONLINE\n\t\t\t}\n\t\t\tresp.Body.Close()\n\t\t}\n\t\tif newStatus == STATUS_ONLINE {\n\t\t\tlog.Printf(\"%s is online\\n\", serverName)\n\t\t} else {\n\t\t\tlog.Printf(\"%s is offline\\n\", serverName)\n\t\t}\n\t\tif newStatus != previousStatus {\n\t\t\tstatusUpdateChannel <- StatusUpdate{ServerName: serverName, Status: newStatus, Duration: duration}\n\t\t}\n\t\tpreviousStatus = newStatus\n\n\t\t\/\/ Check the server periodically\n\t\tif newStatus == STATUS_OFFLINE {\n\t\t\tnextPlannedCheck = time.Now().Add(finalDelay * 2)\n\t\t} else {\n\t\t\tnextPlannedCheck = time.Now().Add(finalDelay)\n\t\t}\n\t}\n\tlog.Printf(\"Shutting down %s worker\\n\", serverName)\n\tdoneGroup.Done()\n}\n\nfunc main() {\n\tvar configPath string\n\t\/\/ First we have to determine what servers should be checked and how. For that we\n\t\/\/ parse our configuration file.\n\tflag.StringVar(&configPath, \"config\", \"\", \"Path to a configuration file\")\n\tflag.Parse()\n\tif configPath == \"\" {\n\t\tlog.Fatalln(\"Please specify a configuration file using the -config flag\")\n\t}\n\tconfig, err := NewConfigurationFromFile(configPath)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tif config.Servers == nil || len(config.Servers) == 0 {\n\t\tlog.Fatalln(\"No servers configured\")\n\t}\n\n\tdoneGroup := sync.WaitGroup{}\n\texitChannel := make(chan struct{}, len(config.Servers))\n\tstatusUpdateChannel := make(chan StatusUpdate, len(config.Servers))\n\tsignalChannel := make(chan os.Signal)\n\n\tdoneGroup.Add(1)\n\tgo StatusHandler(*config, statusUpdateChannel, exitChannel, &doneGroup)\n\n\t\/\/ For every server we create a seperate go-routine that checks the server periodically\n\tfor serverName, serverConfig := range config.Servers {\n\t\tdoneGroup.Add(1)\n\t\tgo ServerHandler(serverName, serverConfig, statusUpdateChannel, exitChannel, &doneGroup)\n\t}\n\n\tif config.Http.HostAddr != \"\" {\n\t\t\/\/ Can't add a waitgroup handler for the HTTP server just yet. Perhaps in Go 1.4 ;)\n\t\tgo HttpHandler(config.Http.HostAddr, &doneGroup)\n\t} else {\n\t\tlog.Println(\"No HTTP configuration present. Not starting HTTP server.\")\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tsign := <-signalChannel\n\t\t\tstatusRegistryManager.ShowDown()\n\t\t\tlog.Printf(\"Received %v. Shutting down workers\", sign)\n\t\t\tfor _ = range config.Servers {\n\t\t\t\texitChannel <- struct{}{}\n\t\t\t}\n\t\t\t\/\/ An additional notification for the status handler and the web interface\n\t\t\texitChannel <- struct{}{}\n\t\t\texitChannel <- struct{}{}\n\t\t}\n\t}()\n\n\tsignal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)\n\n\tlog.Println(\"Waiting for threads to exit.\")\n\tdoneGroup.Wait()\n\tclose(exitChannel)\n\tclose(statusUpdateChannel)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\n\t\"github.com\/golang\/glog\"\n\n\t\"github.com\/liyinan926\/spark-operator\/pkg\/initializer\"\n\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/rest\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n\t\/\/ Uncomment the following line to load the gcp plugin (only required to authenticate against GKE clusters).\n\t\/\/ _ \"k8s.io\/client-go\/plugin\/pkg\/client\/auth\/gcp\"\n)\n\nfunc main() {\n\tkubeconfig := flag.String(\"kubeconfig\", \"\", \"Path to a kube config. Only required if out-of-cluster.\")\n\tinitializerThreads := flag.Int(\"initializer-threads\", 10, \"Number of worker threads in the initializer controller.\")\n\tflag.Parse()\n\n\tglog.Info(\"Starting the Spark operator...\")\n\n\t\/\/ Create the client config. Use kubeconfig if given, otherwise assume in-cluster.\n\tconfig, err := buildConfig(*kubeconfig)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tkubeClient, err := clientset.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tstopCh := make(chan struct{})\n\terrCh := make(chan error)\n\n\tinitializerController := initializer.NewController(kubeClient)\n\tgo initializerController.Run(*initializerThreads, stopCh, errCh)\n\n\tsignalCh := make(chan os.Signal, 1)\n\tsignal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)\n\t<-signalCh\n\n\tglog.Info(\"Shutting down the Spark operator...\")\n\t\/\/ This causes the custom controller and initializer to stop.\n\tclose(stopCh)\n\n\terr = <-errCh\n\tif err != nil {\n\t\tglog.Errorf(\"Spark operator failed with error: %v\", err)\n\t}\n}\n\nfunc buildConfig(kubeconfig string) (*rest.Config, error) {\n\tif kubeconfig != \"\" {\n\t\treturn clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t}\n\treturn rest.InClusterConfig()\n}\n<commit_msg>Enabled the client-go gcp auth plugin<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\n\t\"github.com\/golang\/glog\"\n\n\t\"github.com\/liyinan926\/spark-operator\/pkg\/initializer\"\n\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\t_ \"k8s.io\/client-go\/plugin\/pkg\/client\/auth\/gcp\"\n\t\"k8s.io\/client-go\/rest\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n)\n\nfunc main() {\n\tkubeconfig := flag.String(\"kubeconfig\", \"\", \"Path to a kube config. Only required if out-of-cluster.\")\n\tinitializerThreads := flag.Int(\"initializer-threads\", 10, \"Number of worker threads in the initializer controller.\")\n\tflag.Parse()\n\n\tglog.Info(\"Starting the Spark operator...\")\n\n\t\/\/ Create the client config. Use kubeconfig if given, otherwise assume in-cluster.\n\tconfig, err := buildConfig(*kubeconfig)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tkubeClient, err := clientset.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tstopCh := make(chan struct{})\n\terrCh := make(chan error)\n\n\tinitializerController := initializer.NewController(kubeClient)\n\tgo initializerController.Run(*initializerThreads, stopCh, errCh)\n\n\tsignalCh := make(chan os.Signal, 1)\n\tsignal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM)\n\t<-signalCh\n\n\tglog.Info(\"Shutting down the Spark operator...\")\n\t\/\/ This causes the custom controller and initializer to stop.\n\tclose(stopCh)\n\n\terr = <-errCh\n\tif err != nil {\n\t\tglog.Errorf(\"Spark operator failed with error: %v\", err)\n\t}\n}\n\nfunc buildConfig(kubeconfig string) (*rest.Config, error) {\n\tif kubeconfig != \"\" {\n\t\treturn clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t}\n\treturn rest.InClusterConfig()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/ContainerLabs\/terraform-provider-marathon\/marathon\"\n\t\"github.com\/hashicorp\/terraform\/plugin\"\n)\n\nfunc main() {\n\tplugin.Serve(&plugin.ServeOpts{\n\t\tProviderFunc: marathon.Provider,\n\t})\n}\n<commit_msg>fix main.go deps<commit_after>package main\n\nimport (\n\t\"github.com\/hashicorp\/terraform\/plugin\"\n\t\"github.com\/nicgrayson\/terraform-provider-marathon\/marathon\"\n)\n\nfunc main() {\n\tplugin.Serve(&plugin.ServeOpts{\n\t\tProviderFunc: marathon.Provider,\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n    \"fmt\"\n\t\"encoding\/csv\"\n\t\"os\"\n\t\"io\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"log\"\n\t\"time\"\n\t\"strings\"\n\t\"sort\"\n\t\"strconv\"\n\t\"math\"\n\t\"github.com\/garyburd\/redigo\/redis\"\n)\n\n\/\/ Structure to hold filenames to be ordered by the time part\ntype Event struct {\n\tpath string\n\tts time.Time\t\n}\n\ntype Events []Event\n\n\/\/ Declare methods needed to sort implementation on events\n\/\/\nfunc (this Events) Len() int {\n    return len(this)\n}\nfunc (this Events) Less(i, j int) bool {\n    return this[i].ts.Unix() < this[j].ts.Unix()\n}\nfunc (this Events) Swap(i, j int) {\n    this[i], this[j] = this[j], this[i]\n}\n\n\n\/\/ Dum error checking function\n\nfunc check(e error) {\n    if e != nil {\n        panic(e)\n    }\n}\n\n\/\/ Function called to create a summary file for Key with same Timestamp \n\/\/ and then delete all those eys from DB\n\nfunc searchAndDestroy(key int64) {\n\t\n\t\/\/ Open output file for Key\n\t\n\t\tfilename := fmt.Sprintf(\"\/Volumes\/BigBud\/data\/vf\/results\/%d.txt\", key)\n\t   \tfile, err := os.Create(filename)\n\t   \tcheck(err)\n\t   \tdefer file.Close()\n\t\n\t\t\/\/ Write Headers\n\t    _, err = file.WriteString(\"Cell, Count\\n\")\n\t\n\t\t\/\/ Issue a Sync to flush writes to stable storage.\n\t    file.Sync()\n\t\n\t\/\/ Get Connection from the pool. Only way to be thread-safe with Redis\n\t\tc := pool.Get()\t\n\t\tif c == nil {\n\t\t\t\tlog.Fatal(\"Cannot get connection from Redis Pool\")\n\t\t}\n\t\tdefer c.Close()\n\t\n\t\/\/ Scan the database to find all entries starting with provided key\n\t\/\/ Write line with count computed for cell by Hyperloglog\n\t\/\/ Delete keys\n\/*\n\tif _, err := c.Do(\"SCAN\", redis.Args{}.Add(\"id1\").AddFlat(&p1)...); err != nil {\n\t   \tpanic(err)\n\t}\n\t\n\t\t\ts, err := redis.String(c.Do(\"scan \", key))\n\n\t\t\tcount, err = redis.Uint64(cnx.Do(\"PFCOUNT\", key))\t\t\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Can't find key: \" + key)\t\t\tfmt.Println(\"Error: \")\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Redis: %s = %d\\n\", key, count)\n\t\t\t}\n*\/\n\n}\n\n\n\/\/ Function listen for Timestamps ready to be summarized\n\/\/ and then cleaned-up\n\nfunc listenUp(channel chan int64, count int) {\n\t\n\tfor key := range channel {\n\t\tsearchAndDestroy(key)\n\t}\n} \n\n\/\/ Read all the files names in all directories from provided root\n\/\/ Return an ordered list of file names to process\n\nfunc processFile(inFile string) error {\n\n\/\/ Get Connection from the pool. Only way to be thread-safe with Redis\n\tc := pool.Get()\t\n\tif c == nil {\n\t\t\tlog.Fatal(\"Cannot get connection from Redis Pool\")\n\t}\n\tdefer c.Close()\n\t\t\n\/\/\tprintln(\">> Processing: \", inFile)\n\tfile, err := os.Open(inFile) \/\/ For read access.\n\t\n\tif err != nil {\n\t\tif err == os.ErrNotExist {\n\t\t\tlog.Fatal(\"No such file!\")\n\t\t} else {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tdefer file.Close()\n\n\tr := csv.NewReader(file)\n\t\t\n\t\/\/ Read First Line\n\trow, err := r.Read()\n\t\n\ti := 0\n\t\n\tvar count int64\n\t\n\t\/\/ Get ride of the unused variable error when printf is commented!\n\tvar _ = count\n\t\n\tcount = 0\n\tvar pipeCount float64 = 0\n\t\n\tstartTime := time.Now()\n\tfmt.Printf(\"%s - %s Procesing starts \", startTime.Format(\"2006\/01\/2 - 15:04:05\"), inFile)\n \t\n\tfor (err != io.EOF) && (len(row) >1) {\n\t\t\n\t\t\/\/ Could optimize in the case of 5mins files (always same round t)\n\t\t\/\/ But will break if process larger files\n\t\t\n\t\tutime, _ := strconv.ParseInt(row[1], 10, 64)\n\t\t\n\t\tt := time.Unix(utime, 0).In(time.UTC)\n\t\t\n\t\t\/\/ t, _ := time.Parse(time.RFC3339, row[0])\n\t\t\n\t\t\/\/ Could use Truncate to take lower interval\n\t\ttt := t.Truncate(5 * time.Minute)\n\t\n\t\tkey := fmt.Sprintf(\"%d:%s\", tt.Unix(), row[3])\n\t\timsi := row[2]\n\t\t\t\t\n\/\/\t\tfmt.Printf(\"     %d - Time=%s Key=%s Imsi=%s\\n\", i, tt.String(), key, imsi)\n\t\t\/\/ Add imsi value for that key (Time:Cell) value to Redis\n\t\t\n\t\t\/\/Manage Pipeline of command\n\t\tif pipeCount == 0 {\n\t\t\tc.Send(\"Multi\")\n\t\t} else { \/\/ we have a least one command in pipe\n\t\t\tif math.Mod(pipeCount, 20000) == 0.0 {\n\t\t\t\tpipeCount = 0\n\t\t\t\t_, err := c.Do(\"EXEC\")\n\t\t\t\t\/\/ fmt.Print(\"exec\")\n\t\t\t\tcheck (err)\n\t\t\t\tc.Send(\"Multi\")\n\t\t\t}\n\t\t}\n\t\t \/\/ just add one more command\n\t\tc.Send (\"PFADD\", key, imsi)\n\t\tpipeCount += 1\n\n\t\t\/\/ Next line\n     \trow, err = r.Read()\n\t\ti += 1 \n\t}\n\t\n\t\/\/ Still stuff in pipe to finish?\n\tif pipeCount != 0 {\n\t\t_, err := c.Do(\"EXEC\")\n\t\tcheck (err)\n\t}\n\t\n\tendTime := time.Now()\n\tduration := endTime.Sub(startTime)\n\t\t\n \tif err != nil && err != io.EOF {\n   \t\tfmt.Println(\"Error:\", err)\n \t}\n    fmt.Print(\" lasted: \", duration)\n\tfmt.Printf(\" for %d keys inserted\\n\", i)\n\n\treturn nil\n}\n\n\/\/ Utility function to allocate pool\n\nfunc newPool(server, password string) *redis.Pool {\n    return &redis.Pool{\n        MaxIdle: 3,\n        IdleTimeout: 240 * time.Second,\n        Dial: func () (redis.Conn, error) {\n            c, err := redis.Dial(\"tcp\", server)\n            if err != nil {\n                return nil, err\n            }\n\t\t\tif password != \"\" {\n            \tif _, err := c.Do(\"AUTH\", password); err != nil {\n                \tc.Close()\n                \treturn nil, err\n            \t}\n\t\t\t}\n            return c, err\n        },\n        TestOnBorrow: func(c redis.Conn, t time.Time) error {\n            _, err := c.Do(\"PING\")\n            return err\n        },\n    }\n}\n\n\/\/ Global variables\n\nvar (\n    pool *redis.Pool\n    redisServer = \"localhost:6379\"\n    redisPassword = \"\"\n)\n\n\/\/ Main function\nfunc main() {\n\n\/\/ Create Channel for inter routine communication\n\tchannel := make (chan int64, 10)\n\t\n\/\/ Open Connection to Redis Server\n\/\/\tconst proto = \"tcp\"\n\/\/\tconst port = \":6379\"\n\/\/\tc, err := redis.Dial(proto, port)\n\t\n\tpool = newPool(redisServer, redisPassword)\n\n\tif pool == nil {\n\t\t\tlog.Fatal(\"Cannot Create Redis Pool\")\n\t}\n\n\/\/ Get Connection from the pool. Only way to be thread-safe with Redis\n\tc := pool.Get()\t\n\tif c == nil {\n\t\t\tlog.Fatal(\"Cannot get connection from Redis Pool\")\n\t}\n\tdefer c.Close()\n\t\n\t\/\/ Create list of file to be processed\n\teList := make(Events, 0, 100)\n\t\n\t\/\/ Launch 5 processing functions\n\tfor i :=0; i < 5; i++ {\n\t\tgo listenUp(channel, i)\n\t}\n\t \n\t\/\/ Recursive walk to get all the csv files\n\tfilepath.Walk(\"\/Volumes\/BigBud\/data\/vf\", func(aPath string, info os.FileInfo, err error) error {\n\t\t\/\/ fmt.Println(path)\n\t\tif (!info.IsDir() && strings.HasSuffix(info.Name(), \".csv\")) {\n\t\t\tslice := strings.Split(path.Base(aPath), \".\")\n\t\t\tsDate := slice[0] +\":\"+ slice[1]\n\t\t\tt, err := time.ParseInLocation(\"20060102:150405\", sDate, time.UTC)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tlog.Fatal(\"Abort: Bad Filename with date: \", sDate)\n\t\t\t}\n\t\t\te := Event{aPath, t}\n\t\t\teList = append(eList, e)\n\t\t}\n\t\treturn nil\n\t})\n\n\t\/\/ Order the events by date\n\tsort.Sort(eList)\n\t\n\t\/\/ Loop thru the files, ordered by time and file the unique counts\n\t\/\/ Breaks on 5 min boundaries to geterate cumulated result file and purge redis for those keys\n\t\/\/ Need to slow down ingestion process if too much data being inserted\n\t\n\tvar count int = 0\n\t\n\tstartTime := time.Now()\n\tfmt.Println(\"Let's get started: \", startTime)\t\n\t\n\t\/\/ Initialize first timestamp\n\t\n\tvar pTime time.Time\n\t\n\tif eList.Len() > 0 {\n\t\tpTime = eList[0].ts\n\t}\n\t\t\n\tfor _, v := range eList {\n\n\t\tif pTime != v.ts {\n\t\t\tfmt.Printf(\"Process time %s with key: %d\\n\", pTime, pTime.Unix())\n\t\t\tchannel <- pTime.Unix()\n\t\t\tpTime = v.ts\n\t\t}\t\t\n\t\t\n\/\/\t\tfmt.Printf (\"Processing: %s - %s\\n\", v.ts, v.path)\t\t\n\t\terr := processFile(v.path)\n\t\t\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t\/\/ For test only\n\t\tif count += 1; count > 10000 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\/\/ Close all and Cleanup\n\tclose(channel)\n\t\t\n\tprintln(\"Total File List \", eList.Len())\n\n\tendTime := time.Now()\n\tduration := endTime.Sub(startTime)\n\n    fmt.Println(\"Let's end: \", duration)\n\t\t\n\tos.Exit(0)\n}<commit_msg>small optim and set for cells<commit_after>package main\n\nimport (\n    \"fmt\"\n\t\"encoding\/csv\"\n\t\"os\"\n\t\"io\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"log\"\n\t\"time\"\n\t\"strings\"\n\t\"sort\"\n\t\"strconv\"\n\t\"math\"\n\t\"github.com\/garyburd\/redigo\/redis\"\n)\n\n\/\/ Structure to hold filenames to be ordered by the time part\ntype Event struct {\n\tpath string\n\tts time.Time\t\n}\n\ntype Events []Event\n\n\/\/ Declare methods needed to sort implementation on events\n\/\/\nfunc (this Events) Len() int {\n    return len(this)\n}\nfunc (this Events) Less(i, j int) bool {\n    return this[i].ts.Unix() < this[j].ts.Unix()\n}\nfunc (this Events) Swap(i, j int) {\n    this[i], this[j] = this[j], this[i]\n}\n\n\n\/\/ Dum error checking function\n\nfunc check(e error) {\n    if e != nil {\n        panic(e)\n    }\n}\n\n\/\/ Function called to create a summary file for Key with same Timestamp \n\/\/ and then delete all those eys from DB\n\nfunc searchAndDestroy(key int64) {\n\t\n\t\/\/ Open output file for Key\n\t\n\t\tfilename := fmt.Sprintf(\"\/Volumes\/BigBud\/data\/vf\/results\/%d.txt\", key)\n\t   \tfile, err := os.Create(filename)\n\t   \tcheck(err)\n\t   \tdefer file.Close()\n\t\n\t\t\/\/ Write Headers\n\t    _, err = file.WriteString(\"Cell, Count\\n\")\n\t\n\t\t\/\/ Issue a Sync to flush writes to stable storage.\n\t    file.Sync()\n\t\n\t\/\/ Get Connection from the pool. Only way to be thread-safe with Redis\n\t\tc := pool.Get()\t\n\t\tif c == nil {\n\t\t\t\tlog.Fatal(\"Cannot get connection from Redis Pool\")\n\t\t}\n\t\tdefer c.Close()\n\t\n\t\/\/ Scan the database to find all entries starting with provided key\n\t\/\/ Write line with count computed for cell by Hyperloglog\n\t\/\/ Delete keys\n\/*\n\tif _, err := c.Do(\"SCAN\", redis.Args{}.Add(\"id1\").AddFlat(&p1)...); err != nil {\n\t   \tpanic(err)\n\t}\n\t\n\t\t\ts, err := redis.String(c.Do(\"scan \", key))\n\n\t\t\tcount, err = redis.Uint64(cnx.Do(\"PFCOUNT\", key))\t\t\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Can't find key: \" + key)\t\t\tfmt.Println(\"Error: \")\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Redis: %s = %d\\n\", key, count)\n\t\t\t}\n*\/\n\n}\n\n\n\/\/ Function listen for Timestamps ready to be summarized\n\/\/ and then cleaned-up\n\nfunc listenUp(channel chan int64, count int) {\n\t\n\tfor key := range channel {\n\t\tsearchAndDestroy(key)\n\t}\n} \n\n\/\/ Read all the files names in all directories from provided root\n\/\/ Return an ordered list of file names to process\n\nfunc processFile(inFile string) error {\n\n\/\/ Get Connection from the pool. Only way to be thread-safe with Redis\n\tc := pool.Get()\t\n\tif c == nil {\n\t\t\tlog.Fatal(\"Cannot get connection from Redis Pool\")\n\t}\n\tdefer c.Close()\n\t\t\n\/\/\tprintln(\">> Processing: \", inFile)\n\tfile, err := os.Open(inFile) \/\/ For read access.\n\t\n\tif err != nil {\n\t\tif err == os.ErrNotExist {\n\t\t\tlog.Fatal(\"No such file!\")\n\t\t} else {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tdefer file.Close()\n\n\tr := csv.NewReader(file)\n\t\t\n\t\/\/ Read First Line\n\trow, err := r.Read()\n\t\n\ti := 0\n\t\n\tvar count int64\n\t\n\t\/\/ Get ride of the unused variable error when printf is commented!\n\tvar _ = count\n\t\n\tcount = 0\n\tvar pipeCount float64 = 0\n\tvar tt time.Time\n\/\/\tvar set string\n\tstartTime := time.Now()\n\tfmt.Printf(\"%s - %s Procesing starts \", startTime.Format(\"2006\/01\/2 - 15:04:05\"), inFile)\n \t\n\tfor (err != io.EOF) && (len(row) >1) {\n\t\t\n\t\t\n\t\t\t\t\n\t\t\/\/ Add imsi value for that key (Time:Cell) value to Redis\n\t\t\/\/ Create a set per key with all the cell for that period\n\t\t\n\t\t\/\/Manage Pipeline of command\n\t\t\n\t\tif pipeCount == 0 {\n\t\t\/\/ Optimize in the case of 5mins files take the time of the first line (rounded)\n\t\t\/\/ This will break if files contain more than 5 mins splits\n\t\t\tutime, _ := strconv.ParseInt(row[1], 10, 64)\n\t\t\tt := time.Unix(utime, 0).In(time.UTC)\n\t\t\ttt = t.Truncate(5 * time.Minute)\t\n\/\/\t\t\tset = fmt.Sprintf(\"set:%d\", tt.Unix())\t\t\t\n\t\t\t\/\/ Init pipeline\n\t\t\tc.Send(\"Multi\")\n\t\t} \/\/ we have a least one command in pipe\n\n\t\tkey := fmt.Sprintf(\"%d:%s\", tt.Unix(), row[3])\n\t\timsi := row[2]\n\t\t\n\t\tif math.Mod(pipeCount, 5000) == 0.0 && pipeCount != 0 {\n\t\t\t\tpipeCount = 0\n\t\t\t\t_, err := c.Do(\"EXEC\")\n\t\t\t\tcheck (err)\n\t\t\t\tc.Send(\"Multi\")\n\t\t}\n\t\t\n\t\t \/\/ just add one more command\n\t\tc.Send (\"PFADD\", key, imsi)\n\/\/\t\tc.Send (\"SADD\", set, row[3])\n\t\tpipeCount += 1\n\n\t\t\/\/ Next line\n     \trow, err = r.Read()\n\t\ti += 1 \n\t}\n\t\n\t\/\/ Still stuff in pipe to finish?\n\tif pipeCount != 0 {\n\t\t_, err := c.Do(\"EXEC\")\n\t\tcheck (err)\n\t}\n\t\n\tendTime := time.Now()\n\tduration := endTime.Sub(startTime)\n\t\t\n \tif err != nil && err != io.EOF {\n   \t\tfmt.Println(\"Error:\", err)\n \t}\n    fmt.Print(\" lasted: \", duration)\n\tfmt.Printf(\" for %d keys inserted\\n\", i)\n\n\treturn nil\n}\n\n\/\/ Utility function to allocate pool\n\nfunc newPool(server, password string) *redis.Pool {\n    return &redis.Pool{\n        MaxIdle: 3,\n        IdleTimeout: 240 * time.Second,\n        Dial: func () (redis.Conn, error) {\n            c, err := redis.Dial(\"tcp\", server)\n            if err != nil {\n                return nil, err\n            }\n\t\t\tif password != \"\" {\n            \tif _, err := c.Do(\"AUTH\", password); err != nil {\n                \tc.Close()\n                \treturn nil, err\n            \t}\n\t\t\t}\n            return c, err\n        },\n        TestOnBorrow: func(c redis.Conn, t time.Time) error {\n            _, err := c.Do(\"PING\")\n            return err\n        },\n    }\n}\n\n\/\/ Global variables\n\nvar (\n    pool *redis.Pool\n    redisServer = \"localhost:6379\"\n    redisPassword = \"\"\n)\n\n\/\/ Main function\nfunc main() {\n\n\/\/ Create Channel for inter routine communication\n\tchannel := make (chan int64, 10)\n\t\n\/\/ Open Connection to Redis Server\n\/\/\tconst proto = \"tcp\"\n\/\/\tconst port = \":6379\"\n\/\/\tc, err := redis.Dial(proto, port)\n\t\n\tpool = newPool(redisServer, redisPassword)\n\n\tif pool == nil {\n\t\t\tlog.Fatal(\"Cannot Create Redis Pool\")\n\t}\n\n\/\/ Get Connection from the pool. Only way to be thread-safe with Redis\n\tc := pool.Get()\t\n\tif c == nil {\n\t\t\tlog.Fatal(\"Cannot get connection from Redis Pool\")\n\t}\n\tdefer c.Close()\n\t\n\t\/\/ Create list of file to be processed\n\teList := make(Events, 0, 100)\n\t\n\t\/\/ Launch 5 processing functions\n\tfor i :=0; i < 5; i++ {\n\t\tgo listenUp(channel, i)\n\t}\n\t \n\t\/\/ Recursive walk to get all the csv files\n\tfilepath.Walk(\"\/Volumes\/BigBud\/data\/vf\", func(aPath string, info os.FileInfo, err error) error {\n\t\t\/\/ fmt.Println(path)\n\t\tif (!info.IsDir() && strings.HasSuffix(info.Name(), \".csv\")) {\n\t\t\tslice := strings.Split(path.Base(aPath), \".\")\n\t\t\tsDate := slice[0] +\":\"+ slice[1]\n\t\t\tt, err := time.ParseInLocation(\"20060102:150405\", sDate, time.UTC)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tlog.Fatal(\"Abort: Bad Filename with date: \", sDate)\n\t\t\t}\n\t\t\te := Event{aPath, t}\n\t\t\teList = append(eList, e)\n\t\t}\n\t\treturn nil\n\t})\n\n\t\/\/ Order the events by date\n\tsort.Sort(eList)\n\t\n\t\/\/ Loop thru the files, ordered by time and file the unique counts\n\t\/\/ Breaks on 5 min boundaries to geterate cumulated result file and purge redis for those keys\n\t\/\/ Need to slow down ingestion process if too much data being inserted\n\t\n\tvar count int = 0\n\t\n\tstartTime := time.Now()\n\tfmt.Println(\"Let's get started: \", startTime)\t\n\t\n\t\/\/ Initialize first timestamp\n\t\n\tvar pTime time.Time\n\t\n\tif eList.Len() > 0 {\n\t\tpTime = eList[0].ts\n\t}\n\t\t\n\tfor _, v := range eList {\n\n\t\tif pTime != v.ts {\n\t\t\tfmt.Printf(\"Process time %s with key: %d\\n\", pTime, pTime.Unix())\n\t\t\tchannel <- pTime.Unix()\n\t\t\tpTime = v.ts\n\t\t}\t\t\n\t\t\n\/\/\t\tfmt.Printf (\"Processing: %s - %s\\n\", v.ts, v.path)\t\t\n\t\terr := processFile(v.path)\n\t\t\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t\/\/ For test only\n\t\tif count += 1; count > 10000 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\/\/ Close all and Cleanup\n\tclose(channel)\n\t\t\n\tprintln(\"Total File List \", eList.Len())\n\n\tendTime := time.Now()\n\tduration := endTime.Sub(startTime)\n\n    fmt.Println(\"Let's end: \", duration)\n\t\t\n\tos.Exit(0)\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/CiscoCloud\/mantl-api\/api\"\n\t\"github.com\/CiscoCloud\/mantl-api\/install\"\n\t\"github.com\/CiscoCloud\/mantl-api\/marathon\"\n\t\"github.com\/CiscoCloud\/mantl-api\/mesos\"\n\t\"github.com\/CiscoCloud\/mantl-api\/utils\/http\"\n\t\"github.com\/CiscoCloud\/mantl-api\/zookeeper\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\tconsul \"github.com\/hashicorp\/consul\/api\"\n\t\"github.com\/hashicorp\/go-cleanhttp\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n\t\"github.com\/spf13\/viper\"\n)\n\nconst Name = \"mantl-api\"\nconst Version = \"0.1.8\"\n\nvar wg sync.WaitGroup\n\nfunc main() {\n\trootCmd := &cobra.Command{\n\t\tUse:   \"mantl-api\",\n\t\tShort: \"runs the mantl-api\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tstart()\n\t\t},\n\t\tPersistentPreRun: func(cmd *cobra.Command, args []string) {\n\t\t\treadConfigFile()\n\t\t\tsetupLogging()\n\t\t},\n\t}\n\n\trootCmd.PersistentFlags().String(\"log-level\", \"info\", \"one of debug, info, warn, error, or fatal\")\n\trootCmd.PersistentFlags().String(\"log-format\", \"text\", \"specify output (text or json)\")\n\trootCmd.PersistentFlags().String(\"consul\", \"http:\/\/localhost:8500\", \"Consul Api address\")\n\trootCmd.PersistentFlags().Bool(\"consul-no-verify-ssl\", false, \"Consul SSL verification\")\n\trootCmd.PersistentFlags().String(\"marathon\", \"\", \"Marathon Api address\")\n\trootCmd.PersistentFlags().String(\"marathon-user\", \"\", \"Marathon Api user\")\n\trootCmd.PersistentFlags().String(\"marathon-password\", \"\", \"Marathon Api password\")\n\trootCmd.PersistentFlags().Bool(\"marathon-no-verify-ssl\", false, \"Marathon SSL verification\")\n\trootCmd.PersistentFlags().String(\"mesos\", \"\", \"Mesos Api address\")\n\trootCmd.PersistentFlags().String(\"mesos-principal\", \"\", \"Mesos principal for framework authentication\")\n\trootCmd.PersistentFlags().String(\"mesos-secret\", \"\", \"Deprecated. Use mesos-secret-path instead\")\n\trootCmd.PersistentFlags().String(\"mesos-secret-path\", \"\/etc\/sysconfig\/mantl-api\", \"Path to a file on host sytem that contains the mesos secret for framework authentication\")\n\trootCmd.PersistentFlags().Bool(\"mesos-no-verify-ssl\", false, \"Mesos SSL verification\")\n\trootCmd.PersistentFlags().String(\"listen\", \":4001\", \"mantl-api listen address\")\n\trootCmd.PersistentFlags().String(\"zookeeper\", \"\", \"Comma-delimited list of zookeeper servers\")\n\trootCmd.PersistentFlags().Bool(\"force-sync\", false, \"Force a synchronization of all sources\")\n\trootCmd.PersistentFlags().String(\"config-file\", \"\", \"The path to a configuration file\")\n\trootCmd.PersistentFlags().Int(\"consul-refresh-interval\", 10, \"The number of seconds after which to check consul for package requests\")\n\n\tfor _, flags := range []*pflag.FlagSet{rootCmd.PersistentFlags()} {\n\t\terr := viper.BindPFlags(flags)\n\t\tif err != nil {\n\t\t\tlog.WithField(\"error\", err).Fatal(\"could not bind flags\")\n\t\t}\n\t}\n\n\tviper.SetEnvPrefix(\"mantl_api\")\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\"-\", \"_\"))\n\tviper.AutomaticEnv()\n\n\tsyncCommand := &cobra.Command{\n\t\tUse:   \"sync\",\n\t\tShort: \"Synchronize universe repositories\",\n\t\tLong:  \"Forces a synchronization of all configured sources\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tsyncRepo(nil, true)\n\t\t},\n\t}\n\trootCmd.AddCommand(syncCommand)\n\n\tversionCommand := &cobra.Command{\n\t\tUse:   \"version\",\n\t\tShort: fmt.Sprintf(\"Print the version number of %s\", Name),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Printf(\"%s v%s\\n\", Name, Version)\n\t\t},\n\t}\n\trootCmd.AddCommand(versionCommand)\n\n\trootCmd.Execute()\n}\n\nfunc start() {\n\tlog.Infof(\"Starting %s v%s\", Name, Version)\n\tclient := consulClient()\n\n\tmarathonUrl := viper.GetString(\"marathon\")\n\tif marathonUrl == \"\" {\n\t\tmarathonUrl = NewDiscovery(client, \"marathon\", \"\", \"http\", \"http:\/\/localhost:8080\").discoveredUrl\n\t}\n\tmarathonClient, err := marathon.NewMarathon(\n\t\tmarathonUrl,\n\t\tviper.GetString(\"marathon-user\"),\n\t\tviper.GetString(\"marathon-password\"),\n\t\tviper.GetBool(\"marathon-no-verify-ssl\"),\n\t)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create marathon client: %v\", err)\n\t}\n\n\tmesosUrl := viper.GetString(\"mesos\")\n\tif mesosUrl == \"\" {\n\t\tmesosUrl = NewDiscovery(client, \"mesos\", \"leader\", \"http\", \"http:\/\/localhost:5050\").discoveredUrl\n\t}\n\tmesosClient, err := mesos.NewMesos(\n\t\tmesosUrl,\n\t\tviper.GetString(\"mesos-principal\"),\n\t\tviper.GetString(\"mesos-secret-path\"),\n\t\tviper.GetBool(\"mesos-no-verify-ssl\"),\n\t)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create mesos client: %v\", err)\n\t}\n\n\tzkUrls := viper.GetString(\"zookeeper\")\n\tif zkUrls == \"\" {\n\t\tzkUrls = NewDiscovery(client, \"zookeeper\", \"\", \"\", \"localhost:2181\").discoveredUrl\n\t}\n\tzkServers := strings.Split(zkUrls, \",\")\n\tzk := zookeeper.NewZookeeper(zkServers)\n\n\tinst, err := install.NewInstall(client, marathonClient, mesosClient, zk)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create install client: %v\", err)\n\t}\n\n\t\/\/ sync sources to consul\n\tsyncRepo(inst, viper.GetBool(\"force-sync\"))\n\n\twg.Add(1)\n\tgo inst.Watch(time.Duration(viper.GetInt(\"consul-refresh-interval\")))\n\tgo api.NewApi(Name, viper.GetString(\"listen\"), inst, mesosClient, wg).Start()\n\twg.Wait()\n}\n\nfunc consulClient() *consul.Client {\n\tconsulConfig := consul.DefaultConfig()\n\tscheme, address, _, err := http.ParseUrl(viper.GetString(\"consul\"))\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create consul client: %v\", err)\n\t}\n\tconsulConfig.Scheme = scheme\n\tconsulConfig.Address = address\n\n\tlog.Debugf(\"Using Consul at %s over %s\", consulConfig.Address, consulConfig.Scheme)\n\n\tif viper.GetBool(\"consul-no-verify-ssl\") {\n\t\ttransport := cleanhttp.DefaultTransport()\n\t\ttransport.TLSClientConfig = &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t}\n\t\tconsulConfig.HttpClient.Transport = transport\n\t}\n\n\tclient, err := consul.NewClient(consulConfig)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create consul client: %v\", err)\n\t}\n\n\t\/\/ abort if we cannot connect to consul\n\terr = testConsul(client)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not connect to consul: %v\", err)\n\t}\n\n\treturn client\n}\n\nfunc testConsul(client *consul.Client) error {\n\tkv := client.KV()\n\t_, _, err := kv.Get(\"mantl-install\", nil)\n\treturn err\n}\n\nfunc syncRepo(inst *install.Install, force bool) {\n\tvar err error\n\tif inst == nil {\n\t\tclient := consulClient()\n\t\tinst, err = install.NewInstall(client, nil, nil, nil)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Could not create install client: %v\", err)\n\t\t}\n\t}\n\n\tdefaultSources := []*install.Source{\n\t\t&install.Source{\n\t\t\tName:       \"mantl\",\n\t\t\tPath:       \"https:\/\/github.com\/CiscoCloud\/mantl-universe.git\",\n\t\t\tSourceType: install.Git,\n\t\t\tBranch:     \"version-0.7\",\n\t\t\tIndex:      0,\n\t\t},\n\t}\n\n\tsources := []*install.Source{}\n\n\tconfiguredSources := viper.GetStringMap(\"sources\")\n\n\tif len(configuredSources) > 0 {\n\t\tfor name, val := range configuredSources {\n\t\t\tsource := &install.Source{Name: name, SourceType: install.FileSystem}\n\t\t\tsourceConfig := val.(map[string]interface{})\n\n\t\t\tif path, ok := sourceConfig[\"path\"].(string); ok {\n\t\t\t\tsource.Path = path\n\t\t\t}\n\n\t\t\tif index, ok := sourceConfig[\"index\"].(int64); ok {\n\t\t\t\tsource.Index = int(index)\n\t\t\t}\n\n\t\t\tif sourceType, ok := sourceConfig[\"type\"].(string); ok {\n\t\t\t\tif strings.EqualFold(sourceType, \"git\") {\n\t\t\t\t\tsource.SourceType = install.Git\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif branch, ok := sourceConfig[\"branch\"].(string); ok {\n\t\t\t\tsource.Branch = branch\n\t\t\t}\n\n\t\t\tif source.IsValid() {\n\t\t\t\tsources = append(sources, source)\n\t\t\t} else {\n\t\t\t\tlog.Warnf(\"Invalid source configuration for %s\", name)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(sources) == 0 {\n\t\tsources = defaultSources\n\t}\n\n\tif err := inst.SyncSources(sources, force); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc readConfigFile() {\n\t\/\/ read configuration file if specified\n\tconfigFile := viper.GetString(\"config-file\")\n\tif configFile != \"\" {\n\t\tconfigFile = os.ExpandEnv(configFile)\n\t\tif _, err := os.Stat(configFile); err == nil {\n\t\t\tviper.SetConfigFile(configFile)\n\t\t\terr = viper.ReadInConfig()\n\t\t\tif err != nil {\n\t\t\t\tlog.Warnf(\"Could not read configuration file: %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warnf(\"Could not find configuration file: %s\", configFile)\n\t\t}\n\t}\n}\n\nfunc setupLogging() {\n\tswitch viper.GetString(\"log-level\") {\n\tcase \"debug\":\n\t\tlog.SetLevel(log.DebugLevel)\n\tcase \"info\":\n\t\tlog.SetLevel(log.InfoLevel)\n\tcase \"warn\":\n\t\tlog.SetLevel(log.WarnLevel)\n\tcase \"error\":\n\t\tlog.SetLevel(log.ErrorLevel)\n\tcase \"fatal\":\n\t\tlog.SetLevel(log.FatalLevel)\n\tdefault:\n\t\tlog.WithField(\"log-level\", viper.GetString(\"log-level\")).Warning(\"invalid log level. defaulting to info.\")\n\t\tlog.SetLevel(log.InfoLevel)\n\t}\n\n\tswitch viper.GetString(\"log-format\") {\n\tcase \"text\":\n\t\tlog.SetFormatter(new(log.TextFormatter))\n\tcase \"json\":\n\t\tlog.SetFormatter(new(log.JSONFormatter))\n\tdefault:\n\t\tlog.WithField(\"log-format\", viper.GetString(\"log-format\")).Warning(\"invalid log format. defaulting to text.\")\n\t\tlog.SetFormatter(new(log.TextFormatter))\n\t}\n}\n<commit_msg>version 0.1.9<commit_after>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/CiscoCloud\/mantl-api\/api\"\n\t\"github.com\/CiscoCloud\/mantl-api\/install\"\n\t\"github.com\/CiscoCloud\/mantl-api\/marathon\"\n\t\"github.com\/CiscoCloud\/mantl-api\/mesos\"\n\t\"github.com\/CiscoCloud\/mantl-api\/utils\/http\"\n\t\"github.com\/CiscoCloud\/mantl-api\/zookeeper\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\tconsul \"github.com\/hashicorp\/consul\/api\"\n\t\"github.com\/hashicorp\/go-cleanhttp\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n\t\"github.com\/spf13\/viper\"\n)\n\nconst Name = \"mantl-api\"\nconst Version = \"0.1.9\"\n\nvar wg sync.WaitGroup\n\nfunc main() {\n\trootCmd := &cobra.Command{\n\t\tUse:   \"mantl-api\",\n\t\tShort: \"runs the mantl-api\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tstart()\n\t\t},\n\t\tPersistentPreRun: func(cmd *cobra.Command, args []string) {\n\t\t\treadConfigFile()\n\t\t\tsetupLogging()\n\t\t},\n\t}\n\n\trootCmd.PersistentFlags().String(\"log-level\", \"info\", \"one of debug, info, warn, error, or fatal\")\n\trootCmd.PersistentFlags().String(\"log-format\", \"text\", \"specify output (text or json)\")\n\trootCmd.PersistentFlags().String(\"consul\", \"http:\/\/localhost:8500\", \"Consul Api address\")\n\trootCmd.PersistentFlags().Bool(\"consul-no-verify-ssl\", false, \"Consul SSL verification\")\n\trootCmd.PersistentFlags().String(\"marathon\", \"\", \"Marathon Api address\")\n\trootCmd.PersistentFlags().String(\"marathon-user\", \"\", \"Marathon Api user\")\n\trootCmd.PersistentFlags().String(\"marathon-password\", \"\", \"Marathon Api password\")\n\trootCmd.PersistentFlags().Bool(\"marathon-no-verify-ssl\", false, \"Marathon SSL verification\")\n\trootCmd.PersistentFlags().String(\"mesos\", \"\", \"Mesos Api address\")\n\trootCmd.PersistentFlags().String(\"mesos-principal\", \"\", \"Mesos principal for framework authentication\")\n\trootCmd.PersistentFlags().String(\"mesos-secret\", \"\", \"Deprecated. Use mesos-secret-path instead\")\n\trootCmd.PersistentFlags().String(\"mesos-secret-path\", \"\/etc\/sysconfig\/mantl-api\", \"Path to a file on host sytem that contains the mesos secret for framework authentication\")\n\trootCmd.PersistentFlags().Bool(\"mesos-no-verify-ssl\", false, \"Mesos SSL verification\")\n\trootCmd.PersistentFlags().String(\"listen\", \":4001\", \"mantl-api listen address\")\n\trootCmd.PersistentFlags().String(\"zookeeper\", \"\", \"Comma-delimited list of zookeeper servers\")\n\trootCmd.PersistentFlags().Bool(\"force-sync\", false, \"Force a synchronization of all sources\")\n\trootCmd.PersistentFlags().String(\"config-file\", \"\", \"The path to a configuration file\")\n\trootCmd.PersistentFlags().Int(\"consul-refresh-interval\", 10, \"The number of seconds after which to check consul for package requests\")\n\n\tfor _, flags := range []*pflag.FlagSet{rootCmd.PersistentFlags()} {\n\t\terr := viper.BindPFlags(flags)\n\t\tif err != nil {\n\t\t\tlog.WithField(\"error\", err).Fatal(\"could not bind flags\")\n\t\t}\n\t}\n\n\tviper.SetEnvPrefix(\"mantl_api\")\n\tviper.SetEnvKeyReplacer(strings.NewReplacer(\"-\", \"_\"))\n\tviper.AutomaticEnv()\n\n\tsyncCommand := &cobra.Command{\n\t\tUse:   \"sync\",\n\t\tShort: \"Synchronize universe repositories\",\n\t\tLong:  \"Forces a synchronization of all configured sources\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tsyncRepo(nil, true)\n\t\t},\n\t}\n\trootCmd.AddCommand(syncCommand)\n\n\tversionCommand := &cobra.Command{\n\t\tUse:   \"version\",\n\t\tShort: fmt.Sprintf(\"Print the version number of %s\", Name),\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tfmt.Printf(\"%s v%s\\n\", Name, Version)\n\t\t},\n\t}\n\trootCmd.AddCommand(versionCommand)\n\n\trootCmd.Execute()\n}\n\nfunc start() {\n\tlog.Infof(\"Starting %s v%s\", Name, Version)\n\tclient := consulClient()\n\n\tmarathonUrl := viper.GetString(\"marathon\")\n\tif marathonUrl == \"\" {\n\t\tmarathonUrl = NewDiscovery(client, \"marathon\", \"\", \"http\", \"http:\/\/localhost:8080\").discoveredUrl\n\t}\n\tmarathonClient, err := marathon.NewMarathon(\n\t\tmarathonUrl,\n\t\tviper.GetString(\"marathon-user\"),\n\t\tviper.GetString(\"marathon-password\"),\n\t\tviper.GetBool(\"marathon-no-verify-ssl\"),\n\t)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create marathon client: %v\", err)\n\t}\n\n\tmesosUrl := viper.GetString(\"mesos\")\n\tif mesosUrl == \"\" {\n\t\tmesosUrl = NewDiscovery(client, \"mesos\", \"leader\", \"http\", \"http:\/\/localhost:5050\").discoveredUrl\n\t}\n\tmesosClient, err := mesos.NewMesos(\n\t\tmesosUrl,\n\t\tviper.GetString(\"mesos-principal\"),\n\t\tviper.GetString(\"mesos-secret-path\"),\n\t\tviper.GetBool(\"mesos-no-verify-ssl\"),\n\t)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create mesos client: %v\", err)\n\t}\n\n\tzkUrls := viper.GetString(\"zookeeper\")\n\tif zkUrls == \"\" {\n\t\tzkUrls = NewDiscovery(client, \"zookeeper\", \"\", \"\", \"localhost:2181\").discoveredUrl\n\t}\n\tzkServers := strings.Split(zkUrls, \",\")\n\tzk := zookeeper.NewZookeeper(zkServers)\n\n\tinst, err := install.NewInstall(client, marathonClient, mesosClient, zk)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create install client: %v\", err)\n\t}\n\n\t\/\/ sync sources to consul\n\tsyncRepo(inst, viper.GetBool(\"force-sync\"))\n\n\twg.Add(1)\n\tgo inst.Watch(time.Duration(viper.GetInt(\"consul-refresh-interval\")))\n\tgo api.NewApi(Name, viper.GetString(\"listen\"), inst, mesosClient, wg).Start()\n\twg.Wait()\n}\n\nfunc consulClient() *consul.Client {\n\tconsulConfig := consul.DefaultConfig()\n\tscheme, address, _, err := http.ParseUrl(viper.GetString(\"consul\"))\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create consul client: %v\", err)\n\t}\n\tconsulConfig.Scheme = scheme\n\tconsulConfig.Address = address\n\n\tlog.Debugf(\"Using Consul at %s over %s\", consulConfig.Address, consulConfig.Scheme)\n\n\tif viper.GetBool(\"consul-no-verify-ssl\") {\n\t\ttransport := cleanhttp.DefaultTransport()\n\t\ttransport.TLSClientConfig = &tls.Config{\n\t\t\tInsecureSkipVerify: true,\n\t\t}\n\t\tconsulConfig.HttpClient.Transport = transport\n\t}\n\n\tclient, err := consul.NewClient(consulConfig)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not create consul client: %v\", err)\n\t}\n\n\t\/\/ abort if we cannot connect to consul\n\terr = testConsul(client)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not connect to consul: %v\", err)\n\t}\n\n\treturn client\n}\n\nfunc testConsul(client *consul.Client) error {\n\tkv := client.KV()\n\t_, _, err := kv.Get(\"mantl-install\", nil)\n\treturn err\n}\n\nfunc syncRepo(inst *install.Install, force bool) {\n\tvar err error\n\tif inst == nil {\n\t\tclient := consulClient()\n\t\tinst, err = install.NewInstall(client, nil, nil, nil)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Could not create install client: %v\", err)\n\t\t}\n\t}\n\n\tdefaultSources := []*install.Source{\n\t\t&install.Source{\n\t\t\tName:       \"mantl\",\n\t\t\tPath:       \"https:\/\/github.com\/CiscoCloud\/mantl-universe.git\",\n\t\t\tSourceType: install.Git,\n\t\t\tBranch:     \"version-0.7\",\n\t\t\tIndex:      0,\n\t\t},\n\t}\n\n\tsources := []*install.Source{}\n\n\tconfiguredSources := viper.GetStringMap(\"sources\")\n\n\tif len(configuredSources) > 0 {\n\t\tfor name, val := range configuredSources {\n\t\t\tsource := &install.Source{Name: name, SourceType: install.FileSystem}\n\t\t\tsourceConfig := val.(map[string]interface{})\n\n\t\t\tif path, ok := sourceConfig[\"path\"].(string); ok {\n\t\t\t\tsource.Path = path\n\t\t\t}\n\n\t\t\tif index, ok := sourceConfig[\"index\"].(int64); ok {\n\t\t\t\tsource.Index = int(index)\n\t\t\t}\n\n\t\t\tif sourceType, ok := sourceConfig[\"type\"].(string); ok {\n\t\t\t\tif strings.EqualFold(sourceType, \"git\") {\n\t\t\t\t\tsource.SourceType = install.Git\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif branch, ok := sourceConfig[\"branch\"].(string); ok {\n\t\t\t\tsource.Branch = branch\n\t\t\t}\n\n\t\t\tif source.IsValid() {\n\t\t\t\tsources = append(sources, source)\n\t\t\t} else {\n\t\t\t\tlog.Warnf(\"Invalid source configuration for %s\", name)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(sources) == 0 {\n\t\tsources = defaultSources\n\t}\n\n\tif err := inst.SyncSources(sources, force); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc readConfigFile() {\n\t\/\/ read configuration file if specified\n\tconfigFile := viper.GetString(\"config-file\")\n\tif configFile != \"\" {\n\t\tconfigFile = os.ExpandEnv(configFile)\n\t\tif _, err := os.Stat(configFile); err == nil {\n\t\t\tviper.SetConfigFile(configFile)\n\t\t\terr = viper.ReadInConfig()\n\t\t\tif err != nil {\n\t\t\t\tlog.Warnf(\"Could not read configuration file: %v\", err)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Warnf(\"Could not find configuration file: %s\", configFile)\n\t\t}\n\t}\n}\n\nfunc setupLogging() {\n\tswitch viper.GetString(\"log-level\") {\n\tcase \"debug\":\n\t\tlog.SetLevel(log.DebugLevel)\n\tcase \"info\":\n\t\tlog.SetLevel(log.InfoLevel)\n\tcase \"warn\":\n\t\tlog.SetLevel(log.WarnLevel)\n\tcase \"error\":\n\t\tlog.SetLevel(log.ErrorLevel)\n\tcase \"fatal\":\n\t\tlog.SetLevel(log.FatalLevel)\n\tdefault:\n\t\tlog.WithField(\"log-level\", viper.GetString(\"log-level\")).Warning(\"invalid log level. defaulting to info.\")\n\t\tlog.SetLevel(log.InfoLevel)\n\t}\n\n\tswitch viper.GetString(\"log-format\") {\n\tcase \"text\":\n\t\tlog.SetFormatter(new(log.TextFormatter))\n\tcase \"json\":\n\t\tlog.SetFormatter(new(log.JSONFormatter))\n\tdefault:\n\t\tlog.WithField(\"log-format\", viper.GetString(\"log-format\")).Warning(\"invalid log format. defaulting to text.\")\n\t\tlog.SetFormatter(new(log.TextFormatter))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n)\n\nvar db *bolt.DB\nvar primaryBucketName []byte\nvar markov *Chain\nvar domain string\n\nfunc init() {\n\tmarkov = buildMarkov()\n\tprimaryBucketName = []byte(\"Links\")\n\tdomain = os.Getenv(\"DOMAIN\")\n}\n\ntype shortenerResponse struct {\n\tKey         string `json:\",omitempty\"`\n\tDestination string `json:\",omitempty\"`\n\tError       string `json:\",omitempty\"`\n}\n\nfunc returnJSONFromStruct(s shortenerResponse) []byte {\n\to, err := json.Marshal(s)\n\tif err != nil {\n\t\tlog.Printf(\"error occurred marshalling notFoundError response: %v\\n\", err)\n\t}\n\treturn o\n}\n\nfunc createBucket(name []byte) error {\n\t\/\/ Start a writable transaction.\n\ttx, err := db.Begin(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Rollback()\n\n\t\/\/ Use the transaction...\n\t_, err = tx.CreateBucket(name)\n\tif err != nil {\n\t\tlog.Println(\"Bucket already exists!\")\n\t}\n\n\t\/\/ Commit the transaction and check for error.\n\tif err = tx.Commit(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc readKeyFromBucket(bucketName []byte, key []byte) []byte {\n\tvar r []byte\n\tdb.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket(bucketName)\n\t\tr = b.Get(key)\n\t\treturn nil\n\t})\n\treturn r\n}\n\nfunc addKeyValueToBucket(bucketName []byte, key []byte, value []byte) {\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket(bucketName)\n\t\terr := b.Put(key, value)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"there was an error:\\n\\t%v\", err)\n\t\t}\n\t\treturn err\n\t})\n}\n\n\/\/ prints a list of all keys. Not used in any routes, but handy to keep around, should the need arise.\nfunc keys() {\n\tdb.View(func(tx *bolt.Tx) error {\n\t\t\/\/ Assume bucket exists and has keys\n\t\tb := tx.Bucket(primaryBucketName)\n\t\tc := b.Cursor()\n\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\tlog.Printf(\"key=%s, value=%s\\n\", k, v)\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\nfunc apiAddValue(w http.ResponseWriter, r *http.Request) {\n\turl := r.URL.Query().Get(\"url\")\n\n\tif strings.Contains(url, domain) {\n\t\t\/\/ If the url provided contains the domain name we're running, we respond with an error\n\t\trespondWithError(w, r, \"Invalid URL Provided! You musn't shorten links to the service itself!\")\n\t\treturn\n\t}\n\n\tif len(url) == 0 {\n\t\t\/\/ If no url query param is provided, we respond with an error\n\t\trespondWithError(w, r, \"Empty URL Provided!\")\n\t\treturn\n\t}\n\n\tvar result shortenerResponse\n\tvar v []byte\n\tm := []byte(\" \")\n\n\tfor len(m) != 0 {\n\t\tv = generateMarkovString(markov)\n\t\tm = readKeyFromBucket(primaryBucketName, v)\n\t}\n\n\tresult.Key = string(v)\n\to, err := json.Marshal(result)\n\tif err != nil {\n\t\tlog.Printf(\"error encountered marshalling json: %v\\n\", err)\n\t}\n\n\taddKeyValueToBucket(primaryBucketName, v, []byte(url))\n\tw.Write(o)\n}\n\nfunc apiGetValue(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tk := []byte(vars[\"key\"])\n\tif len(k) != 0 {\n\t\trv := readKeyFromBucket(primaryBucketName, k)\n\t\thttp.Redirect(w, r, string(rv), 301)\n\t} else {\n\t\tnotFoundError(w, r)\n\t}\n}\n\nfunc respondWithError(w http.ResponseWriter, r *http.Request, e string) {\n\tw.Write(returnJSONFromStruct(\n\t\tshortenerResponse{\n\t\t\tError: e,\n\t\t}))\n}\n\nfunc homepage(w http.ResponseWriter, r *http.Request) {\n\tindexPage, err := ioutil.ReadFile(\"index.html\")\n\tif err != nil {\n\t\tlog.Printf(\"error occurred reading indexPage: %v\\n\", err)\n\t}\n\tw.Write(indexPage)\n}\n\nfunc notFoundError(w http.ResponseWriter, r *http.Request) {\n\tresponse := shortenerResponse{\n\t\tError: \"Sorry, 404! :(\",\n\t}\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Write(returnJSONFromStruct(response))\n}\n\nfunc main() {\n\tvar err error\n\t\/\/ Open the db data file in your current directory.\n\t\/\/ It will be created if it doesn't exist.\n\tdb, err = bolt.Open(\"whatever.db\", 0600, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\t\/\/ ensure our default bucket exists\n\terr = createBucket(primaryBucketName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"\/\", homepage)\n\trouter.HandleFunc(\"\/favicon.ico\", func(w http.ResponseWriter, r *http.Request) {})\n\t\/\/ I know I need to actually serve the above files, but\n\t\/\/ I don't feel like it at the moment, sue me if you must.\n\n\trouter.HandleFunc(\"\/api\/add\", apiAddValue)\n\trouter.HandleFunc(\"\/{key}\", apiGetValue)\n\trouter.NotFoundHandler = http.HandlerFunc(notFoundError)\n\n\thttp.Handle(\"\/\", router)\n\thttp.ListenAndServe(\":80\", nil)\n}\n<commit_msg>Address issue where keys with encoded characters return no matches<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/boltdb\/bolt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n)\n\nvar db *bolt.DB\nvar primaryBucketName []byte\nvar markov *Chain\nvar domain string\n\nfunc init() {\n\tmarkov = buildMarkov()\n\tprimaryBucketName = []byte(\"Links\")\n\tdomain = os.Getenv(\"DOMAIN\")\n}\n\ntype shortenerResponse struct {\n\tKey         string `json:\",omitempty\"`\n\tDestination string `json:\",omitempty\"`\n\tError       string `json:\",omitempty\"`\n}\n\nfunc returnJSONFromStruct(s shortenerResponse) []byte {\n\to, err := json.Marshal(s)\n\tif err != nil {\n\t\tlog.Printf(\"error occurred marshalling notFoundError response: %v\\n\", err)\n\t}\n\treturn o\n}\n\nfunc createBucket(name []byte) error {\n\t\/\/ Start a writable transaction.\n\ttx, err := db.Begin(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tx.Rollback()\n\n\t\/\/ Use the transaction...\n\t_, err = tx.CreateBucket(name)\n\tif err != nil {\n\t\tlog.Println(\"Bucket already exists!\")\n\t}\n\n\t\/\/ Commit the transaction and check for error.\n\tif err = tx.Commit(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc readKeyFromBucket(bucketName []byte, key []byte) []byte {\n\tvar r []byte\n\tdb.View(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket(bucketName)\n\t\tr = b.Get(key)\n\t\treturn nil\n\t})\n\treturn r\n}\n\nfunc addKeyValueToBucket(bucketName []byte, key []byte, value []byte) {\n\tdb.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket(bucketName)\n\t\terr := b.Put(key, value)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"there was an error:\\n\\t%v\", err)\n\t\t}\n\t\treturn err\n\t})\n}\n\n\/\/ prints a list of all keys. Not used in any routes, but handy to keep around, should the need arise.\nfunc keys() {\n\tdb.View(func(tx *bolt.Tx) error {\n\t\t\/\/ Assume bucket exists and has keys\n\t\tb := tx.Bucket(primaryBucketName)\n\t\tc := b.Cursor()\n\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\tlog.Printf(\"key=%s, value=%s\\n\", k, v)\n\t\t}\n\n\t\treturn nil\n\t})\n}\n\nfunc apiAddValue(w http.ResponseWriter, r *http.Request) {\n\turl := r.URL.Query().Get(\"url\")\n\n\tif strings.Contains(url, domain) {\n\t\t\/\/ If the url provided contains the domain name we're running, we respond with an error\n\t\trespondWithError(w, r, \"Invalid URL Provided! You musn't shorten links to the service itself!\")\n\t\treturn\n\t}\n\n\tif len(url) == 0 {\n\t\t\/\/ If no url query param is provided, we respond with an error\n\t\trespondWithError(w, r, \"Empty URL Provided!\")\n\t\treturn\n\t}\n\n\tvar result shortenerResponse\n\tvar v []byte\n\tm := []byte(\" \")\n\n\tfor len(m) != 0 {\n\t\tv = generateMarkovString(markov)\n\t\tm = readKeyFromBucket(primaryBucketName, v)\n\t}\n\n\tresult.Key = string(v)\n\to, err := json.Marshal(result)\n\tif err != nil {\n\t\tlog.Printf(\"error encountered marshalling json: %v\\n\", err)\n\t}\n\n\taddKeyValueToBucket(primaryBucketName, v, []byte(url))\n\tw.Write(o)\n}\n\nfunc apiGetValue(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tk := url.QueryEscape(vars[\"key\"])\n\tif len(k) != 0 {\n\t\trv := readKeyFromBucket(primaryBucketName, []byte(k))\n\t\thttp.Redirect(w, r, string(rv), 301)\n\t} else {\n\t\tnotFoundError(w, r)\n\t}\n}\n\nfunc respondWithError(w http.ResponseWriter, r *http.Request, e string) {\n\tw.Write(returnJSONFromStruct(\n\t\tshortenerResponse{\n\t\t\tError: e,\n\t\t}))\n}\n\nfunc homepage(w http.ResponseWriter, r *http.Request) {\n\tindexPage, err := ioutil.ReadFile(\"index.html\")\n\tif err != nil {\n\t\tlog.Printf(\"error occurred reading indexPage: %v\\n\", err)\n\t}\n\tw.Write(indexPage)\n}\n\nfunc notFoundError(w http.ResponseWriter, r *http.Request) {\n\tresponse := shortenerResponse{\n\t\tError: \"Sorry, 404! :(\",\n\t}\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Write(returnJSONFromStruct(response))\n}\n\nfunc main() {\n\tvar err error\n\t\/\/ Open the db data file in your current directory.\n\t\/\/ It will be created if it doesn't exist.\n\tdb, err = bolt.Open(\"whatever.db\", 0600, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\t\/\/ ensure our default bucket exists\n\terr = createBucket(primaryBucketName)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trouter := mux.NewRouter()\n\trouter.HandleFunc(\"\/\", homepage)\n\trouter.HandleFunc(\"\/favicon.ico\", func(w http.ResponseWriter, r *http.Request) {})\n\t\/\/ I know I need to actually serve the above files, but\n\t\/\/ I don't feel like it at the moment, sue me if you must.\n\n\trouter.HandleFunc(\"\/api\/add\", apiAddValue)\n\trouter.HandleFunc(\"\/{key}\", apiGetValue)\n\trouter.NotFoundHandler = http.HandlerFunc(notFoundError)\n\n\thttp.Handle(\"\/\", router)\n\thttp.ListenAndServe(\":80\", nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"time\"\n\n\t\"golang.org\/x\/mobile\/app\"\n\t\"golang.org\/x\/mobile\/audio\"\n\t\"golang.org\/x\/mobile\/f32\"\n\t\"golang.org\/x\/mobile\/gl\"\n\t\"golang.org\/x\/mobile\/gl\/glutil\"\n)\n\nconst (\n\tnumBeats  = 16\n\tnumTracks = 8\n)\n\nvar (\n\tprogram  gl.Program\n\tposition gl.Attrib\n\toffset   gl.Uniform\n\tcolor    gl.Uniform\n\tbuf      gl.Buffer\n\n\tindex    int\n\tgreen    float32\n\tgreenDec bool\n\n\tstopped bool\n)\n\nvar (\n\thits    [numBeats][numTracks]bool\n\tsamples [numTracks]io.Closer\n\tplayers [numTracks]*audio.Player\n)\n\nfunc main() {\n\tapp.Run(app.Callbacks{\n\t\tStart: start,\n\t\tStop:  stop,\n\t\tDraw:  draw,\n\t})\n}\n\nfunc start() {\n\tvar err error\n\tprogram, err = glutil.CreateProgram(vertexShader, fragmentShader)\n\tif err != nil {\n\t\tlog.Printf(\"error creating GL program: %v\", err)\n\t\treturn\n\t}\n\n\tbuf = gl.CreateBuffer()\n\tgl.BindBuffer(gl.ARRAY_BUFFER, buf)\n\tgl.BufferData(gl.ARRAY_BUFFER, rectData, gl.STATIC_DRAW)\n\n\tposition = gl.GetAttribLocation(program, \"position\")\n\tcolor = gl.GetUniformLocation(program, \"color\")\n\toffset = gl.GetUniformLocation(program, \"offset\")\n\n\tfor i := 0; i < numTracks; i++ {\n\t\trc, err := app.Open(fmt.Sprintf(\"track%d.wav\", i))\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tsamples[i] = rc\n\t\tp, err := audio.NewPlayer(rc, audio.Stereo16, 44100)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tplayers[i] = p\n\t}\n\n\t\/\/ hi hat\n\thits[0][1] = true\n\thits[2][1] = true\n\thits[4][1] = true\n\thits[6][1] = true\n\thits[8][1] = true\n\thits[10][1] = true\n\thits[12][1] = true\n\thits[14][1] = true\n\n\t\/\/ kick\n\thits[5][2] = true\n\thits[7][2] = true\n\thits[11][2] = true\n\thits[13][2] = true\n\thits[14][2] = true\n\thits[15][2] = true\n\n\t\/\/ bass\n\thits[0][4] = true\n\thits[3][4] = true\n\thits[5][4] = true\n\thits[6][4] = true\n\thits[8][4] = true\n\thits[11][4] = true\n\thits[13][4] = true\n\n\t\/\/ bass2\n\thits[2][6] = true\n\thits[10][6] = true\n\n\tgo func() {\n\t\tfor {\n\t\t\tif stopped {\n\t\t\t\tstopped = false\n\t\t\t\treturn\n\t\t\t}\n\t\t\tindex = (index + 1) % numBeats\n\t\t\tfor t := 0; t < numTracks; t++ {\n\t\t\t\tgo func(t int) {\n\t\t\t\t\tif hits[index][t] {\n\t\t\t\t\t\tplayers[t].Play()\n\t\t\t\t\t}\n\t\t\t\t}(t)\n\t\t\t}\n\t\t\t\/\/ bpm=140\n\t\t\ttime.Sleep(time.Minute \/ 140)\n\t\t}\n\t}()\n}\n\nfunc stop() {\n\tfor _, p := range players {\n\t\tp.Destroy()\n\t}\n\tfor _, s := range samples {\n\t\ts.Close()\n\t}\n\tgl.DeleteProgram(program)\n\tgl.DeleteBuffer(buf)\n\tstopped = true\n}\n\nvar rectData = f32.Bytes(binary.LittleEndian,\n\t0, 0,\n\t0, 0.1,\n\t0.1, 0,\n\t0.1, 0.1,\n)\n\nfunc draw() {\n\tgl.ClearColor(0, 0, 0, 1)\n\tgl.Clear(gl.COLOR_BUFFER_BIT)\n\tgl.UseProgram(program)\n\n\tif greenDec {\n\t\tgreen -= 0.01\n\t} else {\n\t\tgreen += 0.01\n\t}\n\tif green <= 0.2 {\n\t\tgreenDec = false\n\t}\n\tif green >= 0.5 {\n\t\tgreenDec = true\n\t}\n\n\tfor i := 0; i < numBeats; i++ {\n\t\tfor j := 0; j < numTracks; j++ {\n\t\t\tvar c float32\n\t\t\tswitch {\n\t\t\tcase hits[i][j]:\n\t\t\t\tc = 1\n\t\t\tcase i == index:\n\t\t\t\tc = green\n\t\t\tdefault:\n\t\t\t\tc = 0\n\t\t\t}\n\t\t\tdrawButton(c, float32(i)*1\/numBeats, float32(j)*1\/numTracks)\n\t\t}\n\t}\n}\n\nfunc drawButton(g, x, y float32) {\n\tgl.Uniform4f(color, 0.1, g, 0.4, 1) \/\/ color\n\tgl.Uniform2f(offset, x, y)          \/\/ position\n\n\tgl.BindBuffer(gl.ARRAY_BUFFER, buf)\n\tgl.EnableVertexAttribArray(position)\n\tgl.VertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0)\n\tgl.DrawArrays(gl.TRIANGLE_STRIP, 0, 4)\n\tgl.DisableVertexAttribArray(position)\n}\n\nconst vertexShader = `#version 100\nuniform vec2 offset;\nattribute vec4 position;\nvoid main() {\n  \/\/ offset comes in with x\/y values between 0 and 1.\n  \/\/ position bounds are -1 to 1.\n  vec4 offset4 = vec4(2.0*offset.x-1.0, 1.0-2.0*offset.y, 0, 0);\n  gl_Position = position + offset4;\n}`\n\nconst fragmentShader = `#version 100\nprecision mediump float;\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}`\n<commit_msg>add todo to handle touch events.<commit_after>\/\/ Copyright 2015 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"time\"\n\n\t\"golang.org\/x\/mobile\/app\"\n\t\"golang.org\/x\/mobile\/audio\"\n\t\"golang.org\/x\/mobile\/f32\"\n\t\"golang.org\/x\/mobile\/gl\"\n\t\"golang.org\/x\/mobile\/gl\/glutil\"\n)\n\nconst (\n\tnumBeats  = 16\n\tnumTracks = 8\n)\n\nvar (\n\tprogram  gl.Program\n\tposition gl.Attrib\n\toffset   gl.Uniform\n\tcolor    gl.Uniform\n\tbuf      gl.Buffer\n\n\tindex    int\n\tgreen    float32\n\tgreenDec bool\n\n\tstopped bool\n)\n\nvar (\n\thits    [numBeats][numTracks]bool\n\tsamples [numTracks]io.Closer\n\tplayers [numTracks]*audio.Player\n)\n\nfunc main() {\n\t\/\/ TODO(jbd): Handle touch to turn on\/off the beats.\n\tapp.Run(app.Callbacks{\n\t\tStart: start,\n\t\tStop:  stop,\n\t\tDraw:  draw,\n\t})\n}\n\nfunc start() {\n\tvar err error\n\tprogram, err = glutil.CreateProgram(vertexShader, fragmentShader)\n\tif err != nil {\n\t\tlog.Printf(\"error creating GL program: %v\", err)\n\t\treturn\n\t}\n\n\tbuf = gl.CreateBuffer()\n\tgl.BindBuffer(gl.ARRAY_BUFFER, buf)\n\tgl.BufferData(gl.ARRAY_BUFFER, rectData, gl.STATIC_DRAW)\n\n\tposition = gl.GetAttribLocation(program, \"position\")\n\tcolor = gl.GetUniformLocation(program, \"color\")\n\toffset = gl.GetUniformLocation(program, \"offset\")\n\n\tfor i := 0; i < numTracks; i++ {\n\t\trc, err := app.Open(fmt.Sprintf(\"track%d.wav\", i))\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tsamples[i] = rc\n\t\tp, err := audio.NewPlayer(rc, audio.Stereo16, 44100)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tplayers[i] = p\n\t}\n\n\t\/\/ hi hat\n\thits[0][1] = true\n\thits[2][1] = true\n\thits[4][1] = true\n\thits[6][1] = true\n\thits[8][1] = true\n\thits[10][1] = true\n\thits[12][1] = true\n\thits[14][1] = true\n\n\t\/\/ kick\n\thits[5][2] = true\n\thits[7][2] = true\n\thits[11][2] = true\n\thits[13][2] = true\n\thits[14][2] = true\n\thits[15][2] = true\n\n\t\/\/ bass\n\thits[0][4] = true\n\thits[3][4] = true\n\thits[5][4] = true\n\thits[6][4] = true\n\thits[8][4] = true\n\thits[11][4] = true\n\thits[13][4] = true\n\n\t\/\/ bass2\n\thits[2][6] = true\n\thits[10][6] = true\n\n\tgo func() {\n\t\tfor {\n\t\t\tif stopped {\n\t\t\t\tstopped = false\n\t\t\t\treturn\n\t\t\t}\n\t\t\tindex = (index + 1) % numBeats\n\t\t\tfor t := 0; t < numTracks; t++ {\n\t\t\t\tgo func(t int) {\n\t\t\t\t\tif hits[index][t] {\n\t\t\t\t\t\tplayers[t].Play()\n\t\t\t\t\t}\n\t\t\t\t}(t)\n\t\t\t}\n\t\t\t\/\/ bpm=140\n\t\t\ttime.Sleep(time.Minute \/ 140)\n\t\t}\n\t}()\n}\n\nfunc stop() {\n\tfor _, p := range players {\n\t\tp.Destroy()\n\t}\n\tfor _, s := range samples {\n\t\ts.Close()\n\t}\n\tgl.DeleteProgram(program)\n\tgl.DeleteBuffer(buf)\n\tstopped = true\n}\n\nvar rectData = f32.Bytes(binary.LittleEndian,\n\t0, 0,\n\t0, 0.1,\n\t0.1, 0,\n\t0.1, 0.1,\n)\n\nfunc draw() {\n\tgl.ClearColor(0, 0, 0, 1)\n\tgl.Clear(gl.COLOR_BUFFER_BIT)\n\tgl.UseProgram(program)\n\n\tif greenDec {\n\t\tgreen -= 0.01\n\t} else {\n\t\tgreen += 0.01\n\t}\n\tif green <= 0.2 {\n\t\tgreenDec = false\n\t}\n\tif green >= 0.5 {\n\t\tgreenDec = true\n\t}\n\n\tfor i := 0; i < numBeats; i++ {\n\t\tfor j := 0; j < numTracks; j++ {\n\t\t\tvar c float32\n\t\t\tswitch {\n\t\t\tcase hits[i][j]:\n\t\t\t\tc = 1\n\t\t\tcase i == index:\n\t\t\t\tc = green\n\t\t\tdefault:\n\t\t\t\tc = 0\n\t\t\t}\n\t\t\tdrawButton(c, float32(i)*1\/numBeats, float32(j)*1\/numTracks)\n\t\t}\n\t}\n}\n\nfunc drawButton(g, x, y float32) {\n\tgl.Uniform4f(color, 0.1, g, 0.4, 1) \/\/ color\n\tgl.Uniform2f(offset, x, y)          \/\/ position\n\n\tgl.BindBuffer(gl.ARRAY_BUFFER, buf)\n\tgl.EnableVertexAttribArray(position)\n\tgl.VertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0)\n\tgl.DrawArrays(gl.TRIANGLE_STRIP, 0, 4)\n\tgl.DisableVertexAttribArray(position)\n}\n\nconst vertexShader = `#version 100\nuniform vec2 offset;\nattribute vec4 position;\nvoid main() {\n  \/\/ offset comes in with x\/y values between 0 and 1.\n  \/\/ position bounds are -1 to 1.\n  vec4 offset4 = vec4(2.0*offset.x-1.0, 1.0-2.0*offset.y, 0, 0);\n  gl_Position = position + offset4;\n}`\n\nconst fragmentShader = `#version 100\nprecision mediump float;\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}`\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strconv\"\n\n\t\"github.com\/zenazn\/goji\"\n\t\"github.com\/zenazn\/goji\/web\"\n\n\t\"github.com\/flosch\/pongo2\"\n)\n\ntype Page struct {\n\tTitle              string\n\tCurrentTemperature float64\n\tTargetTemperature  float64\n\tIsHeating          string\n}\n\nfunc root(c web.C, w http.ResponseWriter, r *http.Request) {\n\n\tvar page Page\n\tpage.Title = \"My Cooker\"\n\n\tpage.TargetTemperature = getTargetTemp()\n\tpage.CurrentTemperature = getCurrentTemp()\n\tpage.IsHeating = isHeating()\n\n\ttpl, err := pongo2.DefaultSet.FromFile(\"template.tpl\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttpl.ExecuteWriter(pongo2.Context{\"page\": page}, w)\n}\n\nfunc setTarget(c web.C, w http.ResponseWriter, r *http.Request) {\n\ttarget := c.URLParams[\"target\"]\n\tfmt.Println(target)\n\n\tt, err := strconv.ParseFloat(target, 32)\n\tif err != nil || t < 0 || t > 100 {\n\t\t\/\/ Invalid format or out of correct range\n\t\thttp.Redirect(w, r, \"\/\", 400)\n\t\treturn\n\t}\n\n\tfmt.Println(\"Set \" + target)\n\tsetTargetTemp(target)\n\thttp.Redirect(w, r, \"\/\", 200)\n}\n\nfunc main() {\n\tgoji.Get(\"\/\", root)\n\tgoji.Get(\"\/set\/:target\", setTarget)\n\tgoji.Serve()\n}\n<commit_msg>avoid to show transition page<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strconv\"\n\n\t\"github.com\/zenazn\/goji\"\n\t\"github.com\/zenazn\/goji\/web\"\n\n\t\"github.com\/flosch\/pongo2\"\n)\n\ntype Page struct {\n\tTitle              string\n\tCurrentTemperature float64\n\tTargetTemperature  float64\n\tIsHeating          string\n}\n\nfunc root(c web.C, w http.ResponseWriter, r *http.Request) {\n\n\tvar page Page\n\tpage.Title = \"My Cooker\"\n\n\tpage.TargetTemperature = getTargetTemp()\n\tpage.CurrentTemperature = getCurrentTemp()\n\tpage.IsHeating = isHeating()\n\n\ttpl, err := pongo2.DefaultSet.FromFile(\"template.tpl\")\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttpl.ExecuteWriter(pongo2.Context{\"page\": page}, w)\n}\n\nfunc setTarget(c web.C, w http.ResponseWriter, r *http.Request) {\n\ttarget := c.URLParams[\"target\"]\n\tfmt.Println(target)\n\n\tt, err := strconv.ParseFloat(target, 32)\n\tif err != nil || t < 0 || t > 100 {\n\t\t\/\/ Invalid format or out of correct range\n\t\thttp.Redirect(w, r, \"\/\", 400)\n\t\treturn\n\t}\n\n\tfmt.Println(\"Set \" + target)\n\tsetTargetTemp(target)\n\thttp.Redirect(w, r, \"\/\", http.StatusMovedPermanently)\t\/\/ workaround to suppress transition page.\n}\n\nfunc forceOff(c web.C, w http.ResponseWriter, r *http.Request) {\n\tsetTargetTemp(\"0.0\")\n\thttp.Redirect(w, r, \"\/\", http.StatusMovedPermanently)\n}\n\nfunc forceOn(c web.C, w http.ResponseWriter, r *http.Request) {\n\tsetTargetTemp(\"100.0\")\n\thttp.Redirect(w, r, \"\/\", http.StatusMovedPermanently)\n}\n\nfunc main() {\n\tgoji.Get(\"\/\", root)\n\tgoji.Get(\"\/set\/:target\", setTarget)\n\tgoji.Get(\"\/force_on\", forceOn)\n\tgoji.Get(\"\/force_off\", forceOff)\n\tgoji.Serve()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\twhisper \"github.com\/grobian\/go-whisper\"\n\tpickle \"github.com\/kisielk\/og-rek\"\n\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar config = struct {\n\tWhisperData string\n}{\n\tWhisperData: \"\/var\/lib\/carbon\/whisper\",\n}\n\ntype WhisperFetchResponse struct {\n\tName      string    `json:\"name\"`\n\tStartTime int       `json:\"startTime\"`\n\tStopTime  int       `json:\"stopTime\"`\n\tStepTime  int       `json:\"stepTime\"`\n\tValues    []float64 `json:\"values\"`\n\tIsAbsent  []bool    `json:\"isAbsent\"`\n}\n\ntype WhisperGlobResponse struct {\n\tName  string   `json:\"name\"`\n\tPaths []string `json:\"paths\"`\n}\n\nvar log Logger\n\nfunc findHandler(wr http.ResponseWriter, req *http.Request) {\n\t\/\/\tGET \/metrics\/find\/?local=1&format=pickle&query=general.hadoop.lhr4.ha201jobtracker-01.jobtracker.NonHeapMemoryUsage.committed HTTP\/1.1\n\t\/\/\thttp:\/\/localhost:8080\/metrics\/find\/?query=test\n\treq.ParseForm()\n\tglob := req.FormValue(\"query\")\n\tformat := req.FormValue(\"format\")\n\n\tif format != \"json\" && format != \"pickle\" {\n\t\tlog.Warn(\"dropping invalid uri (format=%s): %s\",\n\t\t\tformat, req.URL.RequestURI())\n\t\thttp.Error(wr, \"Bad request (unsupported format)\",\n\t\t\thttp.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif glob == \"\" {\n\t\tlog.Warn(\"dropping invalid request (query=): %s\", req.URL.RequestURI())\n\t\thttp.Error(wr, \"Bad request (no query)\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/* things to glob:\n\t * - carbon.relays  -> carbon.relays\n\t * - carbon.re      -> carbon.relays, carbon.rewhatever\n\t * - carbon.[rz]    -> carbon.relays, carbon.zipper\n\t * - carbon.{re,zi} -> carbon.relays, carbon.zipper\n\t * - implicit * at the end of each query\n\t * - match is either dir or .wsp file\n\t * unfortunately, filepath.Glob doesn't handle the curly brace\n\t * expansion for us *\/\n\tlbrace := strings.Index(glob, \"{\")\n\trbrace := -1\n\tif lbrace > -1 {\n\t\trbrace = strings.Index(glob[lbrace:], \"}\")\n\t\tif rbrace > -1 {\n\t\t\trbrace += lbrace\n\t\t}\n\t}\n\tfiles := make([]string, 0)\n\tif lbrace > -1 && rbrace > -1 {\n\t\texpansion := glob[lbrace+1 : rbrace]\n\t\tparts := strings.Split(expansion, \",\")\n\t\tfor _, sub := range parts {\n\t\t\tsglob := glob[:lbrace] + sub + glob[rbrace+1:]\n\t\t\tpath := config.WhisperData + \"\/\" + strings.Replace(sglob, \".\", \"\/\", -1) + \"*\"\n\t\t\tnfiles, err := filepath.Glob(path)\n\t\t\tif err == nil {\n\t\t\t\tfiles = append(files, nfiles...)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tpath := config.WhisperData + \"\/\" + strings.Replace(glob, \".\", \"\/\", -1) + \"*\"\n\t\tnfiles, err := filepath.Glob(path)\n\t\tif err == nil {\n\t\t\tfiles = append(files, nfiles...)\n\t\t}\n\t}\n\n\tleafs := make([]bool, len(files))\n\tfor i, p := range files {\n\t\tp = p[len(config.WhisperData+\"\/\"):]\n\t\tif strings.HasSuffix(p, \".wsp\") {\n\t\t\tp = p[:len(p)-4]\n\t\t\tleafs[i] = true\n\t\t} else {\n\t\t\tleafs[i] = false\n\t\t}\n\t\tfiles[i] = strings.Replace(p, \"\/\", \".\", -1)\n\t}\n\n\tif format == \"json\" {\n\t\tresponse := WhisperGlobResponse{\n\t\t\tName:  glob,\n\t\t\tPaths: make([]string, 0),\n\t\t}\n\t\tfor _, p := range files {\n\t\t\tresponse.Paths = append(response.Paths, p)\n\t\t}\n\t\tb, err := json.Marshal(response)\n\t\tif err != nil {\n\t\t\tlog.Error(\"failed to create JSON data for glob %s: %s\", glob, err)\n\t\t\treturn\n\t\t}\n\t\twr.Write(b)\n\t} else if format == \"pickle\" {\n\t\t\/\/ [{'metric_path': 'metric', 'intervals': [(x,y)], 'isLeaf': True},]\n\t\tvar metrics []map[string]interface{}\n\t\tvar m map[string]interface{}\n\n\t\tfor i, p := range files {\n\t\t\tm = make(map[string]interface{})\n\t\t\tm[\"metric_path\"] = p\n\t\t\t\/\/ m[\"intervals\"] = dunno how to do a tuple here\n\t\t\tm[\"isLeaf\"] = leafs[i]\n\t\t\tmetrics = append(metrics, m)\n\t\t}\n\n\t\twr.Header().Set(\"Content-Type\", \"application\/pickle\")\n\t\tpEnc := pickle.NewEncoder(wr)\n\t\tpEnc.Encode(metrics)\n\t}\n\tlog.Info(\"find: %d hits for %s\", len(files), glob)\n\treturn\n}\n\nfunc fetchHandler(wr http.ResponseWriter, req *http.Request) {\n\t\/\/\tGET \/render\/?target=general.me.1.percent_time_active.pfnredis&format=pickle&from=1396008021&until=1396022421 HTTP\/1.1\n\t\/\/\thttp:\/\/localhost:8080\/render\/?target=testmetric&format=json&from=1395961200&until=1395961800\n\treq.ParseForm()\n\tmetric := req.FormValue(\"target\")\n\tformat := req.FormValue(\"format\")\n\tfrom := req.FormValue(\"from\")\n\tuntil := req.FormValue(\"until\")\n\n\tif format != \"json\" && format != \"pickle\" {\n\t\tlog.Warn(\"dropping invalid uri (format=%s): %s\",\n\t\t\tformat, req.URL.RequestURI())\n\t\thttp.Error(wr, \"Bad request (unsupported format)\",\n\t\t\thttp.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpath := config.WhisperData + \"\/\" + strings.Replace(metric, \".\", \"\/\", -1) + \".wsp\"\n\tw, err := whisper.Open(path)\n\tif err != nil {\n\t\t\/\/ the FE\/carbonzipper often requests metrics we don't have\n\t\tlog.Debug(\"failed to %s\", err)\n\t\thttp.Error(wr, \"Metric not found\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\ti, err := strconv.Atoi(from)\n\tif err != nil {\n\t\tlog.Debug(\"fromTime (%s) invalid: %s (in %s)\",\n\t\t\tfrom, err, req.URL.RequestURI)\n\t\tif w != nil {\n\t\t\tw.Close()\n\t\t}\n\t\tw = nil\n\t}\n\tfromTime := int(i)\n\ti, err = strconv.Atoi(until)\n\tif err != nil {\n\t\tlog.Debug(\"untilTime (%s) invalid: %s (in %s)\",\n\t\t\tfrom, err, req.URL.RequestURI)\n\t\tif w != nil {\n\t\t\tw.Close()\n\t\t}\n\t\tw = nil\n\t}\n\tuntilTime := int(i)\n\n\tif w != nil {\n\t\tdefer w.Close()\n\t} else {\n\t\thttp.Error(wr, \"Bad request (invalid from\/until time)\",\n\t\t\thttp.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpoints, err := w.Fetch(fromTime, untilTime)\n\tif err != nil {\n\t\tlog.Error(\"failed to fetch points from %s: %s\", path, err)\n\t\thttp.Error(wr, \"Fetching data points failed\",\n\t\t\thttp.StatusInternalServerError)\n\t\treturn\n\t}\n\tvalues := points.Values()\n\n\tif format == \"json\" {\n\t\tresponse := WhisperFetchResponse{\n\t\t\tName:      metric,\n\t\t\tStartTime: points.FromTime(),\n\t\t\tStopTime:  points.UntilTime(),\n\t\t\tStepTime:  points.Step(),\n\t\t\tValues:    make([]float64, len(values)),\n\t\t\tIsAbsent:  make([]bool, len(values)),\n\t\t}\n\n\t\tfor i, p := range values {\n\t\t\tif math.IsNaN(p) {\n\t\t\t\tresponse.Values[i] = 0\n\t\t\t\tresponse.IsAbsent[i] = true\n\t\t\t} else {\n\t\t\t\tresponse.Values[i] = p\n\t\t\t\tresponse.IsAbsent[i] = false\n\t\t\t}\n\t\t}\n\n\t\tb, err := json.Marshal(response)\n\t\tif err != nil {\n\t\t\tlog.Error(\"failed to create JSON data for %s: %s\", path, err)\n\t\t\treturn\n\t\t}\n\t\twr.Write(b)\n\t} else if format == \"pickle\" {\n\t\t\/\/[{'start': 1396271100, 'step': 60, 'name': 'metric',\n\t\t\/\/'values': [9.0, 19.0, None], 'end': 1396273140}\n\t\tvar metrics []map[string]interface{}\n\t\tvar m map[string]interface{}\n\n\t\tm = make(map[string]interface{})\n\t\tm[\"start\"] = points.FromTime()\n\t\tm[\"step\"] = points.Step()\n\t\tm[\"end\"] = points.UntilTime()\n\t\tm[\"name\"] = metric\n\n\t\tmv := make([]interface{}, len(values))\n\t\tfor i, p := range values {\n\t\t\tif math.IsNaN(p) {\n\t\t\t\tmv[i] = nil\n\t\t\t} else {\n\t\t\t\tmv[i] = p\n\t\t\t}\n\t\t}\n\n\t\tm[\"values\"] = mv\n\t\tmetrics = append(metrics, m)\n\n\t\twr.Header().Set(\"Content-Type\", \"application\/pickle\")\n\t\tpEnc := pickle.NewEncoder(wr)\n\t\tpEnc.Encode(metrics)\n\t}\n\n\tlog.Info(\"served %d points for %s\", len(values), metric)\n\treturn\n}\n\nfunc main() {\n\tport := flag.Int(\"p\", 8080, \"port to bind to\")\n\tverbose := flag.Bool(\"v\", false, \"enable verbose logging\")\n\tdebug := flag.Bool(\"vv\", false, \"enable more verbose (debug) logging\")\n\twhisperdata := flag.String(\"w\", config.WhisperData, \"location where whisper files are stored\")\n\n\tflag.Parse()\n\n\tloglevel := WARN\n\tif *verbose {\n\t\tloglevel = INFO\n\t}\n\tif *debug {\n\t\tloglevel = DEBUG\n\t}\n\tlog = NewOutputLogger(loglevel)\n\n\tconfig.WhisperData = *whisperdata\n\tlog.Info(\"reading whisper files from: %s\", config.WhisperData)\n\n\thttp.HandleFunc(\"\/metrics\/find\/\", findHandler)\n\thttp.HandleFunc(\"\/render\/\", fetchHandler)\n\n\tlisten := fmt.Sprintf(\":%d\", *port)\n\tlog.Info(\"listening on %s\", listen)\n\terr := http.ListenAndServe(listen, nil)\n\tif err != nil {\n\t\tlog.Fatal(\"%s\", err)\n\t}\n\tlog.Info(\"stopped\")\n}\n\n\/\/ Simple wrapper to enable\/disable lots of spam\ntype Logger interface {\n\tInfo(format string, a ...interface{})\n\tWarn(format string, a ...interface{})\n\tError(format string, a ...interface{})\n\tFatal(format string, a ...interface{})\n\tDebug(format string, a ...interface{})\n}\n\ntype LogLevel int\n\nconst (\n\tFATAL LogLevel = 0\n\tERROR LogLevel = 1\n\tWARN  LogLevel = 2\n\tINFO  LogLevel = 3\n\tDEBUG LogLevel = 4\n)\n\ntype outputLogger struct {\n\tlevel LogLevel\n\tout   *os.File\n\terr   *os.File\n}\n\nfunc NewOutputLogger(level LogLevel) *outputLogger {\n\tr := new(outputLogger)\n\tr.level = level\n\tr.out = os.Stdout\n\tr.err = os.Stderr\n\n\treturn r\n}\n\nfunc (l *outputLogger) Debug(format string, a ...interface{}) {\n\tif l.level >= DEBUG {\n\t\tl.out.WriteString(fmt.Sprintf(\"DEBUG: \"+format+\"\\n\", a...))\n\t}\n}\n\nfunc (l *outputLogger) Info(format string, a ...interface{}) {\n\tif l.level >= INFO {\n\t\tl.out.WriteString(fmt.Sprintf(\"INFO: \"+format+\"\\n\", a...))\n\t}\n}\n\nfunc (l *outputLogger) Warn(format string, a ...interface{}) {\n\tif l.level >= WARN {\n\t\tl.out.WriteString(fmt.Sprintf(\"WARN: \"+format+\"\\n\", a...))\n\t}\n}\n\nfunc (l *outputLogger) Error(format string, a ...interface{}) {\n\tif l.level >= ERROR {\n\t\tl.err.WriteString(fmt.Sprintf(\"ERROR: \"+format+\"\\n\", a...))\n\t}\n}\n\nfunc (l *outputLogger) Fatal(format string, a ...interface{}) {\n\tif l.level >= FATAL {\n\t\tl.err.WriteString(fmt.Sprintf(\"ERROR: \"+format+\"\\n\", a...))\n\t}\n\tos.Exit(1)\n}\n<commit_msg>Remove useless make()<commit_after>package main\n\nimport (\n\twhisper \"github.com\/grobian\/go-whisper\"\n\tpickle \"github.com\/kisielk\/og-rek\"\n\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"math\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar config = struct {\n\tWhisperData string\n}{\n\tWhisperData: \"\/var\/lib\/carbon\/whisper\",\n}\n\ntype WhisperFetchResponse struct {\n\tName      string    `json:\"name\"`\n\tStartTime int       `json:\"startTime\"`\n\tStopTime  int       `json:\"stopTime\"`\n\tStepTime  int       `json:\"stepTime\"`\n\tValues    []float64 `json:\"values\"`\n\tIsAbsent  []bool    `json:\"isAbsent\"`\n}\n\ntype WhisperGlobResponse struct {\n\tName  string   `json:\"name\"`\n\tPaths []string `json:\"paths\"`\n}\n\nvar log Logger\n\nfunc findHandler(wr http.ResponseWriter, req *http.Request) {\n\t\/\/\tGET \/metrics\/find\/?local=1&format=pickle&query=general.hadoop.lhr4.ha201jobtracker-01.jobtracker.NonHeapMemoryUsage.committed HTTP\/1.1\n\t\/\/\thttp:\/\/localhost:8080\/metrics\/find\/?query=test\n\treq.ParseForm()\n\tglob := req.FormValue(\"query\")\n\tformat := req.FormValue(\"format\")\n\n\tif format != \"json\" && format != \"pickle\" {\n\t\tlog.Warn(\"dropping invalid uri (format=%s): %s\",\n\t\t\tformat, req.URL.RequestURI())\n\t\thttp.Error(wr, \"Bad request (unsupported format)\",\n\t\t\thttp.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif glob == \"\" {\n\t\tlog.Warn(\"dropping invalid request (query=): %s\", req.URL.RequestURI())\n\t\thttp.Error(wr, \"Bad request (no query)\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/* things to glob:\n\t * - carbon.relays  -> carbon.relays\n\t * - carbon.re      -> carbon.relays, carbon.rewhatever\n\t * - carbon.[rz]    -> carbon.relays, carbon.zipper\n\t * - carbon.{re,zi} -> carbon.relays, carbon.zipper\n\t * - implicit * at the end of each query\n\t * - match is either dir or .wsp file\n\t * unfortunately, filepath.Glob doesn't handle the curly brace\n\t * expansion for us *\/\n\tlbrace := strings.Index(glob, \"{\")\n\trbrace := -1\n\tif lbrace > -1 {\n\t\trbrace = strings.Index(glob[lbrace:], \"}\")\n\t\tif rbrace > -1 {\n\t\t\trbrace += lbrace\n\t\t}\n\t}\n\tvar files []string\n\tif lbrace > -1 && rbrace > -1 {\n\t\texpansion := glob[lbrace+1 : rbrace]\n\t\tparts := strings.Split(expansion, \",\")\n\t\tfor _, sub := range parts {\n\t\t\tsglob := glob[:lbrace] + sub + glob[rbrace+1:]\n\t\t\tpath := config.WhisperData + \"\/\" + strings.Replace(sglob, \".\", \"\/\", -1) + \"*\"\n\t\t\tnfiles, err := filepath.Glob(path)\n\t\t\tif err == nil {\n\t\t\t\tfiles = append(files, nfiles...)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tpath := config.WhisperData + \"\/\" + strings.Replace(glob, \".\", \"\/\", -1) + \"*\"\n\t\tnfiles, err := filepath.Glob(path)\n\t\tif err == nil {\n\t\t\tfiles = append(files, nfiles...)\n\t\t}\n\t}\n\n\tleafs := make([]bool, len(files))\n\tfor i, p := range files {\n\t\tp = p[len(config.WhisperData+\"\/\"):]\n\t\tif strings.HasSuffix(p, \".wsp\") {\n\t\t\tp = p[:len(p)-4]\n\t\t\tleafs[i] = true\n\t\t} else {\n\t\t\tleafs[i] = false\n\t\t}\n\t\tfiles[i] = strings.Replace(p, \"\/\", \".\", -1)\n\t}\n\n\tif format == \"json\" {\n\t\tresponse := WhisperGlobResponse{\n\t\t\tName:  glob,\n\t\t\tPaths: make([]string, 0),\n\t\t}\n\t\tfor _, p := range files {\n\t\t\tresponse.Paths = append(response.Paths, p)\n\t\t}\n\t\tb, err := json.Marshal(response)\n\t\tif err != nil {\n\t\t\tlog.Error(\"failed to create JSON data for glob %s: %s\", glob, err)\n\t\t\treturn\n\t\t}\n\t\twr.Write(b)\n\t} else if format == \"pickle\" {\n\t\t\/\/ [{'metric_path': 'metric', 'intervals': [(x,y)], 'isLeaf': True},]\n\t\tvar metrics []map[string]interface{}\n\t\tvar m map[string]interface{}\n\n\t\tfor i, p := range files {\n\t\t\tm = make(map[string]interface{})\n\t\t\tm[\"metric_path\"] = p\n\t\t\t\/\/ m[\"intervals\"] = dunno how to do a tuple here\n\t\t\tm[\"isLeaf\"] = leafs[i]\n\t\t\tmetrics = append(metrics, m)\n\t\t}\n\n\t\twr.Header().Set(\"Content-Type\", \"application\/pickle\")\n\t\tpEnc := pickle.NewEncoder(wr)\n\t\tpEnc.Encode(metrics)\n\t}\n\tlog.Info(\"find: %d hits for %s\", len(files), glob)\n\treturn\n}\n\nfunc fetchHandler(wr http.ResponseWriter, req *http.Request) {\n\t\/\/\tGET \/render\/?target=general.me.1.percent_time_active.pfnredis&format=pickle&from=1396008021&until=1396022421 HTTP\/1.1\n\t\/\/\thttp:\/\/localhost:8080\/render\/?target=testmetric&format=json&from=1395961200&until=1395961800\n\treq.ParseForm()\n\tmetric := req.FormValue(\"target\")\n\tformat := req.FormValue(\"format\")\n\tfrom := req.FormValue(\"from\")\n\tuntil := req.FormValue(\"until\")\n\n\tif format != \"json\" && format != \"pickle\" {\n\t\tlog.Warn(\"dropping invalid uri (format=%s): %s\",\n\t\t\tformat, req.URL.RequestURI())\n\t\thttp.Error(wr, \"Bad request (unsupported format)\",\n\t\t\thttp.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpath := config.WhisperData + \"\/\" + strings.Replace(metric, \".\", \"\/\", -1) + \".wsp\"\n\tw, err := whisper.Open(path)\n\tif err != nil {\n\t\t\/\/ the FE\/carbonzipper often requests metrics we don't have\n\t\tlog.Debug(\"failed to %s\", err)\n\t\thttp.Error(wr, \"Metric not found\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\ti, err := strconv.Atoi(from)\n\tif err != nil {\n\t\tlog.Debug(\"fromTime (%s) invalid: %s (in %s)\",\n\t\t\tfrom, err, req.URL.RequestURI)\n\t\tif w != nil {\n\t\t\tw.Close()\n\t\t}\n\t\tw = nil\n\t}\n\tfromTime := int(i)\n\ti, err = strconv.Atoi(until)\n\tif err != nil {\n\t\tlog.Debug(\"untilTime (%s) invalid: %s (in %s)\",\n\t\t\tfrom, err, req.URL.RequestURI)\n\t\tif w != nil {\n\t\t\tw.Close()\n\t\t}\n\t\tw = nil\n\t}\n\tuntilTime := int(i)\n\n\tif w != nil {\n\t\tdefer w.Close()\n\t} else {\n\t\thttp.Error(wr, \"Bad request (invalid from\/until time)\",\n\t\t\thttp.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpoints, err := w.Fetch(fromTime, untilTime)\n\tif err != nil {\n\t\tlog.Error(\"failed to fetch points from %s: %s\", path, err)\n\t\thttp.Error(wr, \"Fetching data points failed\",\n\t\t\thttp.StatusInternalServerError)\n\t\treturn\n\t}\n\tvalues := points.Values()\n\n\tif format == \"json\" {\n\t\tresponse := WhisperFetchResponse{\n\t\t\tName:      metric,\n\t\t\tStartTime: points.FromTime(),\n\t\t\tStopTime:  points.UntilTime(),\n\t\t\tStepTime:  points.Step(),\n\t\t\tValues:    make([]float64, len(values)),\n\t\t\tIsAbsent:  make([]bool, len(values)),\n\t\t}\n\n\t\tfor i, p := range values {\n\t\t\tif math.IsNaN(p) {\n\t\t\t\tresponse.Values[i] = 0\n\t\t\t\tresponse.IsAbsent[i] = true\n\t\t\t} else {\n\t\t\t\tresponse.Values[i] = p\n\t\t\t\tresponse.IsAbsent[i] = false\n\t\t\t}\n\t\t}\n\n\t\tb, err := json.Marshal(response)\n\t\tif err != nil {\n\t\t\tlog.Error(\"failed to create JSON data for %s: %s\", path, err)\n\t\t\treturn\n\t\t}\n\t\twr.Write(b)\n\t} else if format == \"pickle\" {\n\t\t\/\/[{'start': 1396271100, 'step': 60, 'name': 'metric',\n\t\t\/\/'values': [9.0, 19.0, None], 'end': 1396273140}\n\t\tvar metrics []map[string]interface{}\n\t\tvar m map[string]interface{}\n\n\t\tm = make(map[string]interface{})\n\t\tm[\"start\"] = points.FromTime()\n\t\tm[\"step\"] = points.Step()\n\t\tm[\"end\"] = points.UntilTime()\n\t\tm[\"name\"] = metric\n\n\t\tmv := make([]interface{}, len(values))\n\t\tfor i, p := range values {\n\t\t\tif math.IsNaN(p) {\n\t\t\t\tmv[i] = nil\n\t\t\t} else {\n\t\t\t\tmv[i] = p\n\t\t\t}\n\t\t}\n\n\t\tm[\"values\"] = mv\n\t\tmetrics = append(metrics, m)\n\n\t\twr.Header().Set(\"Content-Type\", \"application\/pickle\")\n\t\tpEnc := pickle.NewEncoder(wr)\n\t\tpEnc.Encode(metrics)\n\t}\n\n\tlog.Info(\"served %d points for %s\", len(values), metric)\n\treturn\n}\n\nfunc main() {\n\tport := flag.Int(\"p\", 8080, \"port to bind to\")\n\tverbose := flag.Bool(\"v\", false, \"enable verbose logging\")\n\tdebug := flag.Bool(\"vv\", false, \"enable more verbose (debug) logging\")\n\twhisperdata := flag.String(\"w\", config.WhisperData, \"location where whisper files are stored\")\n\n\tflag.Parse()\n\n\tloglevel := WARN\n\tif *verbose {\n\t\tloglevel = INFO\n\t}\n\tif *debug {\n\t\tloglevel = DEBUG\n\t}\n\tlog = NewOutputLogger(loglevel)\n\n\tconfig.WhisperData = *whisperdata\n\tlog.Info(\"reading whisper files from: %s\", config.WhisperData)\n\n\thttp.HandleFunc(\"\/metrics\/find\/\", findHandler)\n\thttp.HandleFunc(\"\/render\/\", fetchHandler)\n\n\tlisten := fmt.Sprintf(\":%d\", *port)\n\tlog.Info(\"listening on %s\", listen)\n\terr := http.ListenAndServe(listen, nil)\n\tif err != nil {\n\t\tlog.Fatal(\"%s\", err)\n\t}\n\tlog.Info(\"stopped\")\n}\n\n\/\/ Simple wrapper to enable\/disable lots of spam\ntype Logger interface {\n\tInfo(format string, a ...interface{})\n\tWarn(format string, a ...interface{})\n\tError(format string, a ...interface{})\n\tFatal(format string, a ...interface{})\n\tDebug(format string, a ...interface{})\n}\n\ntype LogLevel int\n\nconst (\n\tFATAL LogLevel = 0\n\tERROR LogLevel = 1\n\tWARN  LogLevel = 2\n\tINFO  LogLevel = 3\n\tDEBUG LogLevel = 4\n)\n\ntype outputLogger struct {\n\tlevel LogLevel\n\tout   *os.File\n\terr   *os.File\n}\n\nfunc NewOutputLogger(level LogLevel) *outputLogger {\n\tr := new(outputLogger)\n\tr.level = level\n\tr.out = os.Stdout\n\tr.err = os.Stderr\n\n\treturn r\n}\n\nfunc (l *outputLogger) Debug(format string, a ...interface{}) {\n\tif l.level >= DEBUG {\n\t\tl.out.WriteString(fmt.Sprintf(\"DEBUG: \"+format+\"\\n\", a...))\n\t}\n}\n\nfunc (l *outputLogger) Info(format string, a ...interface{}) {\n\tif l.level >= INFO {\n\t\tl.out.WriteString(fmt.Sprintf(\"INFO: \"+format+\"\\n\", a...))\n\t}\n}\n\nfunc (l *outputLogger) Warn(format string, a ...interface{}) {\n\tif l.level >= WARN {\n\t\tl.out.WriteString(fmt.Sprintf(\"WARN: \"+format+\"\\n\", a...))\n\t}\n}\n\nfunc (l *outputLogger) Error(format string, a ...interface{}) {\n\tif l.level >= ERROR {\n\t\tl.err.WriteString(fmt.Sprintf(\"ERROR: \"+format+\"\\n\", a...))\n\t}\n}\n\nfunc (l *outputLogger) Fatal(format string, a ...interface{}) {\n\tif l.level >= FATAL {\n\t\tl.err.WriteString(fmt.Sprintf(\"ERROR: \"+format+\"\\n\", a...))\n\t}\n\tos.Exit(1)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"github.com\/gizak\/termui\"\n\nfunc main() {\n\terr := termui.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer termui.Close()\n\n\tp := termui.NewPar(\":PRESS q or Esc TO QUIT DEMO Hello World\")\n\tp.Height = 3\n\tp.Width = 50\n\tp.TextFgColor = termui.ColorWhite\n\tp.BorderLabel = \"Hello-World\"\n\tp.BorderFg = termui.ColorCyan\n\n\ttermui.Render(p)\n\n\ttermui.Handle(\"\/sys\", func(e termui.Event) {\n\t\tk, ok := e.Data.(termui.EvtKbd)\n\t\tif ok && (k.KeyStr == \"q\" || k.KeyStr == \"<escape>\") {\n\t\t\ttermui.StopLoop()\n\t\t}\n\t})\n\ttermui.Loop()\n}\n<commit_msg>Ajout Courbe<commit_after>package main\n\nimport \"github.com\/gizak\/termui\"\nimport \"math\"\nfunc main() {\n\n\terr := termui.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer termui.Close()\n\t\n\tsinps := (func() []float64 {\n\t\tn := 220\n\t\tps := make([]float64, n)\n\t\tfor i := range ps {\n\t\t\tps[i] = 1 + math.Sin(float64(i)\/5)\n\t\t}\n\t\treturn ps\n\t})()\n\n\tp := termui.NewPar(\":PRESS q or Esc TO QUIT DEMO Hello World\")\n\tp.Height = 3\n\tp.Width = 50\n\tp.TextFgColor = termui.ColorWhite\n\tp.BorderLabel = \"Hello-World\"\n\tp.BorderFg = termui.ColorCyan\n\n\tlc1 := termui.NewLineChart()\n\tlc1.BorderLabel = \"dot-mode Line Chart\"\n\tlc1.Mode = \"dot\"\n\tlc1.Data = sinps\n\tlc1.Width = 26\n\tlc1.Height = 12\n\tlc1.X = 51\n\tlc1.DotStyle = '+'\n\tlc1.AxesColor = termui.ColorWhite\n\tlc1.LineColor = termui.ColorYellow | termui.AttrBold\n\ttermui.Render(p, lc1)\n\n\ttermui.Handle(\"\/sys\", func(e termui.Event) {\n\t\tk, ok := e.Data.(termui.EvtKbd)\n\t\tif ok && (k.KeyStr == \"q\" || k.KeyStr == \"<escape>\") {\n\t\t\ttermui.StopLoop()\n\t\t}\n\t})\n\ttermui.Loop()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/PuerkitoBio\/goquery\"\n\t\"github.com\/codegangsta\/martini\"\n\t\"github.com\/martini-contrib\/render\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"os\"\n\ts \"strings\"\n\t\"time\"\n)\n\nvar data = make(map[string]interface{})\n\nconst filename = \"db.txt\"\n\ntype Proj struct {\n\tTitle       string\n\tDescription string\n}\n\nfunc ScrapProj() {\n\tfmt.Println(\"scraping ..\")\n\tdoc, err := goquery.NewDocument(\"https:\/\/github.com\/karan\/Projects\/blob\/master\/README.md\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif !isFileExist(filename) {\n\t\t\/\/ if the file doesn't exist, create a new one\n\t\tw, err := os.Create(filename)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer w.Close()\n\n\t\t\/\/ write empty one first\n\t\terr = ioutil.WriteFile(filename, []byte(\"\"), 0644)\n\n\t\tdoc.Find(\".markdown-body p\").Slice(7, 95).Each(func(i int, s *goquery.Selection) {\n\t\t\ttxt := s.Text() + \"\\n\"\n\t\t\tf, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tdefer f.Close()\n\n\t\t\tif _, err = f.WriteString(txt); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc ReadProjFromFile() []string {\n\tfmt.Println(\"reading from file ..\")\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s.Split(string(b), \"\\n\")\n}\n\nfunc GetRandomProj(projs []string) Proj {\n\ti := random(0, len(projs))\n\tproject := projs[i]\n\n\ttitle := s.Split(project, \" - \")[0]\n\tdesc := s.Split(project, \" - \")[1]\n\n\treturn Proj{title, desc}\n}\n\nfunc random(min, max int) int {\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn rand.Intn(max-min) + min\n}\n\nfunc main() {\n\n\t\/\/ If the file doesn't exist, scrap it\n\tif !isFileExist(filename) {\n\t\tScrapProj()\n\t}\n\n\tm := martini.Classic()\n\tm.Use(render.Renderer(render.Options{\n\t\tLayout: \"layout\",\n\t}))\n\n\tm.Get(\"\/suggest\", func(ren render.Render) {\n\t\tren.HTML(200, \"index\", GetRandomProj(ReadProjFromFile()))\n\t})\n\n\tm.Get(\"\/\", func(ren render.Render) {\n\t\tren.HTML(200, \"index\", nil)\n\t})\n\n\tm.Run()\n}\n\n\/\/ Check if file already exists or not\nfunc isFileExist(filename string) bool {\n\tif _, err := os.Stat(filename); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}\n<commit_msg>remove unused data<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/PuerkitoBio\/goquery\"\n\t\"github.com\/codegangsta\/martini\"\n\t\"github.com\/martini-contrib\/render\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"os\"\n\ts \"strings\"\n\t\"time\"\n)\n\nconst filename = \"db.txt\"\n\ntype Proj struct {\n\tTitle       string\n\tDescription string\n}\n\nfunc ScrapProj() {\n\tfmt.Println(\"scraping ..\")\n\tdoc, err := goquery.NewDocument(\"https:\/\/github.com\/karan\/Projects\/blob\/master\/README.md\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif !isFileExist(filename) {\n\t\t\/\/ if the file doesn't exist, create a new one\n\t\tw, err := os.Create(filename)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tdefer w.Close()\n\n\t\t\/\/ write empty one first\n\t\terr = ioutil.WriteFile(filename, []byte(\"\"), 0644)\n\n\t\tdoc.Find(\".markdown-body p\").Slice(7, 95).Each(func(i int, s *goquery.Selection) {\n\t\t\ttxt := s.Text() + \"\\n\"\n\t\t\tf, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\tdefer f.Close()\n\n\t\t\tif _, err = f.WriteString(txt); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc ReadProjFromFile() []string {\n\tfmt.Println(\"reading from file ..\")\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s.Split(string(b), \"\\n\")\n}\n\nfunc GetRandomProj(projs []string) Proj {\n\ti := random(0, len(projs))\n\tproject := projs[i]\n\n\ttitle := s.Split(project, \" - \")[0]\n\tdesc := s.Split(project, \" - \")[1]\n\n\treturn Proj{title, desc}\n}\n\nfunc random(min, max int) int {\n\trand.Seed(time.Now().UTC().UnixNano())\n\treturn rand.Intn(max-min) + min\n}\n\nfunc main() {\n\n\t\/\/ If the file doesn't exist, scrap it\n\tif !isFileExist(filename) {\n\t\tScrapProj()\n\t}\n\n\tm := martini.Classic()\n\tm.Use(render.Renderer(render.Options{\n\t\tLayout: \"layout\",\n\t}))\n\n\tm.Get(\"\/suggest\", func(ren render.Render) {\n\t\tren.HTML(200, \"index\", GetRandomProj(ReadProjFromFile()))\n\t})\n\n\tm.Get(\"\/\", func(ren render.Render) {\n\t\tren.HTML(200, \"index\", nil)\n\t})\n\n\tm.Run()\n}\n\n\/\/ Check if file already exists or not\nfunc isFileExist(filename string) bool {\n\tif _, err := os.Stat(filename); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n    \"fmt\"\n    \"net\"\n    \"log\"\n    \"os\"\n    \"os\/signal\"\n    \"syscall\"\n    \"io\"\n)\n\n\n\/\/ Signal handler catches SIGINT and SIGTERM and sends a \"done\" flag to the main loop\nfunc signalHandler(signalChannel chan os.Signal, doneChannel chan bool){\n    \/\/ block the goroutine until we get a signal\n    signal := <-signalChannel\n    log.Printf(\"Got signal %v, exiting...\\n\", signal)\n    \/\/ Send the message to terminate the app\n    doneChannel <- true\n}\n\n\/\/ Collects data from the socket and sends it to where it needs to go\nfunc aggregateCollectorData(socket net.Listener, doneChannel, finishedChannel chan bool) {\n    for {\n        select {\n        case <- doneChannel:\n            log.Println(\"Ceasing to accept collector connections...\")\n            finishedChannel <- true\n            return\n        default:\n            log.Println(\"Accepting a collector connection...\")\n            data, err := readDataFromClient(socket)\n            if err != nil {\n                log.Printf(\"Error: %v\\n\", err)\n            } else {\n                log.Println(data)\n            }\n        }\n    }\n}\n\n\/\/ Accept a connection from the socket and read 512 bytes of data into a buffer\nfunc readDataFromClient(socket net.Listener) ([]byte, error) {\n    readBuffer := make([]byte, 512)\n\n    fd, err := socket.Accept()\n    if err != nil {\n        return nil, fmt.Errorf(\"Failed to accept a connection: err: %v\\n\", err)\n    }\n\n    defer fd.Close()\n\n    bytesRead, err := fd.Read(readBuffer)\n\n    if err == io.EOF {\n        return nil, fmt.Errorf(\"Received no data from client connection\")\n    }\n\n    if err != nil {\n        return nil, fmt.Errorf(\"Failed to read from the socket into the buffer: err: %v\\n\", err)\n    }\n\n    return readBuffer[:bytesRead], nil\n}\n\n\/\/ Connect to the socket as a client to unblock the Accept call\nfunc mimicFinalClient(socketUrl string) {\n    log.Println(\"Creating a mimic client to terminate socket accept thread\")\n    conn, err := net.Dial(\"unix\", socketUrl)\n    if err != nil {\n        log.Fatalf(\"Failed to open the final client connection to Garnet\")\n    }\n    conn.Close()\n}\n\nfunc main() {\n    \/\/ Create a channel to pass to os.Notify for OS signal handling\n    signalChannel := make(chan os.Signal, 1)\n    signalDoneChannel := make(chan bool, 1)\n    signal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)\n    go signalHandler(signalChannel, signalDoneChannel)\n\n    socket, err := net.Listen(\"unix\", \"\/tmp\/garnet.sock\")\n    if err != nil {\n        log.Fatalf(\"Failed to create a new Unix socket: err: %v\\n\", err)\n    }\n    defer socket.Close()\n\n    log.Printf(\"Opened a socket connection '\/tmp\/garnet.sock'\\n\")\n\n    \/\/ Start the aggregation collector\n    aggregationDoneChannel := make(chan bool, 1)\n    cleanUpChannel := make(chan bool, 1)\n    go aggregateCollectorData(socket, aggregationDoneChannel, cleanUpChannel)\n\n    \/\/ Wait until we get a catchable signal before cleaning up\n    <- signalDoneChannel\n    aggregationDoneChannel <- true\n    mimicFinalClient(\"\/tmp\/garnet.sock\")\n    <- cleanUpChannel\n}\n<commit_msg>Add comments surrounding waiting for a \"done\" message from a channel<commit_after>package main\n\nimport (\n    \"fmt\"\n    \"net\"\n    \"log\"\n    \"os\"\n    \"os\/signal\"\n    \"syscall\"\n    \"io\"\n)\n\n\n\/\/ Signal handler catches SIGINT and SIGTERM and sends a \"done\" flag to the main loop\nfunc signalHandler(signalChannel chan os.Signal, doneChannel chan bool){\n    \/\/ block the goroutine until we get a signal\n    signal := <-signalChannel\n    log.Printf(\"Got signal %v, exiting...\\n\", signal)\n    \/\/ Send the message to terminate the app\n    doneChannel <- true\n}\n\n\/\/ Collects data from the socket and sends it to where it needs to go\nfunc aggregateCollectorData(socket net.Listener, doneChannel, finishedChannel chan bool) {\n    for {\n        select {\n        case <- doneChannel:\n            log.Println(\"Ceasing to accept collector connections...\")\n            finishedChannel <- true\n            return\n        default:\n            log.Println(\"Accepting a collector connection...\")\n            data, err := readDataFromClient(socket)\n            if err != nil {\n                log.Printf(\"Error: %v\\n\", err)\n            } else {\n                log.Println(data)\n            }\n        }\n    }\n}\n\n\/\/ Accept a connection from the socket and read 512 bytes of data into a buffer\nfunc readDataFromClient(socket net.Listener) ([]byte, error) {\n    readBuffer := make([]byte, 512)\n\n    fd, err := socket.Accept()\n    if err != nil {\n        return nil, fmt.Errorf(\"Failed to accept a connection: err: %v\\n\", err)\n    }\n\n    defer fd.Close()\n\n    bytesRead, err := fd.Read(readBuffer)\n\n    if err == io.EOF {\n        return nil, fmt.Errorf(\"Received no data from client connection\")\n    }\n\n    if err != nil {\n        return nil, fmt.Errorf(\"Failed to read from the socket into the buffer: err: %v\\n\", err)\n    }\n\n    return readBuffer[:bytesRead], nil\n}\n\n\/\/ Connect to the socket as a client to unblock the Accept call\nfunc mimicFinalClient(socketUrl string) {\n    log.Println(\"Creating a mimic client to terminate socket accept thread\")\n    conn, err := net.Dial(\"unix\", socketUrl)\n    if err != nil {\n        log.Fatalf(\"Failed to open the final client connection to Garnet\")\n    }\n    conn.Close()\n}\n\nfunc main() {\n    \/\/ Create a channel to pass to os.Notify for OS signal handling\n    signalChannel := make(chan os.Signal, 1)\n    signalDoneChannel := make(chan bool, 1)\n    signal.Notify(signalChannel, syscall.SIGINT, syscall.SIGTERM)\n    go signalHandler(signalChannel, signalDoneChannel)\n\n    socket, err := net.Listen(\"unix\", \"\/tmp\/garnet.sock\")\n    if err != nil {\n        log.Fatalf(\"Failed to create a new Unix socket: err: %v\\n\", err)\n    }\n    defer socket.Close()\n\n    log.Printf(\"Opened a socket connection '\/tmp\/garnet.sock'\\n\")\n\n    \/\/ Start the aggregation collector\n    aggregationDoneChannel := make(chan bool, 1)\n    aggregationCleanUpChannel := make(chan bool, 1)\n    go aggregateCollectorData(socket, aggregationDoneChannel, aggregationCleanUpChannel)\n\n    \/\/ Wait until we get a catchable signal before cleaning up\n    <- signalDoneChannel\n\n    \/\/ Tell the collector aggregator to stop processing connections\n    aggregationDoneChannel <- true\n    mimicFinalClient(\"\/tmp\/garnet.sock\")\n    <- aggregationCleanUpChannel\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\n\t\"github.com\/gwenn\/gosqlite\"\n\t\"github.com\/minio\/go-homedir\"\n)\n\nvar (\n\toutputDir = \"Databases\"\n\tfileName = \"72mb.sqlite\"\n\tnumRows = 100000 \/\/ 100000 makes a 72MB file (taking ~4.5 seconds) on my Linux desktop.  Adjust to suit your desired target file size\n)\n\ntype oneRow struct {\n\tkey_data int\n\tint_data int\n\tsigned_data int\n\tfloat_data float32\n\tdouble_data float64\n\tdecim_data string\n\tdate_data string\n\tcode_data string\n\tname_data string\n\taddress_data string\n}\n\nfunc main() {\n\t\/\/ Determine full path to target file\n\tuserHome, err := homedir.Dir()\n\tif err != nil {\n\t\tlog.Printf(\"User home directory couldn't be determined: %s\", \"\\n\")\n\t\treturn\n\t}\n\tfn := filepath.Join(userHome, outputDir, fileName)\n\n\t\/\/ If the database file already exists, nuke the file\n\t_, err = os.Stat(fn)\n\tif err == nil {\n\t\t\/\/ No error occurred when looking for an existing file, which means something is there.  For now, we're just\n\t\t\/\/ going to blindly kill the existing thing without any kind of better safeguard\n\t\tlog.Printf(\"A SQLite database appears to be there already... removing it\")\n\t\tos.Remove(fn)\n\t}\n\n\t\/\/ Create empty SQLite database\n\tlog.Printf(\"Creating new SQLite database file '%s'\\n\", fn)\n\tsdb, err := sqlite.Open(fn, sqlite.OpenCreate | sqlite.OpenReadWrite)\n\tif err != nil {\n\t\tlog.Printf(\"Couldn't open database: %s\", err)\n\t\treturn\n\t}\n\tdefer sdb.Close()\n\n\t\/\/ Disable the journal\n\terr = sdb.Select(\"PRAGMA journal_mode=OFF\", func(s *sqlite.Stmt) error {\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"Error when disabling the journal: %s\\n\", err)\n\t\treturn\n\t}\n\n\t\/\/ Turn off synchronous mode\n\terr = sdb.Exec(\"PRAGMA synchronous=OFF\")\n\tif err != nil {\n\t\tlog.Printf(\"Error when setting synchronous mode: %s\\n\", err)\n\t\treturn\n\t}\n\n\t\/\/ Create the schema\n\tlog.Println(\"Creating tables\")\n\ttableNames := []string{\"uniques\", \"updates\", \"hundred\", \"tenpct\", \"tiny\"}\n\tvar dbQuery string\n\tfor _, tbl := range tableNames {\n\t\tdbQuery = fmt.Sprintf(`\n\t\t\tCREATE TABLE IF NOT EXISTS %s (\n\t\t\t\t'col_key'     INTEGER NOT NULL,\n\t\t\t\t'col_int'     INTEGER NOT NULL,\n\t\t\t\t'col_signed'  INTEGER NOT NULL,\n\t\t\t\t'col_float'   REAL NOT NULL,\n\t\t\t\t'col_double'  REAL NOT NULL,\n\t\t\t\t'col_decim'   NUMERIC NOT NULL,\n\t\t\t\t'col_date'    TEXT NOT NULL,\n\t\t\t\t'col_code'    TEXT NOT NULL,\n\t\t\t\t'col_name'    TEXT NOT NULL,\n\t\t\t\t'col_address' TEXT NOT NULL\n\t\t\t)`, tbl)\n\t\terr := sdb.Exec(dbQuery)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error when creating table '%s': %s\\n\", tbl, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ Launch a worker pool generating row data\n\tcpus := runtime.NumCPU()\n\tlog.Printf(\"# of cpu's detected: %d.  Launching %d data generation workers\\n\", cpus, cpus)\n\tresults := make(chan *oneRow, cpus * 5) \/\/ 5 seems ok, less than 5 seems slightly slower (not properly measured though!)\n\tfor w := 0; w < cpus; w++ {\n\t\tgo worker(results)\n\t}\n\n\t\/\/ Bulk insert row data (inside a single transaction per table)\n\tlog.Println(\"Adding data\")\n\tvar r *oneRow\n\tfor _, tbl := range tableNames {\n\t\terr = sdb.Begin()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error for Begin(): %s\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Prepare the insert statement\n\t\tdbQuery := sqlite.Mprintf(`\n\t\t\tINSERT into %w (col_key, col_int, col_signed, col_float, col_double, col_decim, col_date, col_code, col_name, col_address)\n\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, tbl)\n\t\tstmt, err := sdb.Prepare(dbQuery)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error when preparing statement for inserts: %s\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Insert the data\n\t\tfor i := 0; i < numRows; i++ {\n\t\t\tr = <- results\n\t\t\terr = stmt.Exec(r.key_data, r.int_data, r.signed_data, r.float_data, r.double_data, r.decim_data,\n\t\t\t\tr.date_data, r.code_data, r.name_data, r.address_data)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error when inserting data: %s\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Clean up for this loop\n\t\tstmt.Finalize()\n\n\t\t\/\/ Commit the transaction\n\t\tsdb.Commit()\n\t}\n\n\t\/\/ TODO: Create indexes ?\n\n\t\/\/ Let the user know the program completed ok\n\tlog.Printf(\"SQLite database generation completed\")\n}\n\n\/\/ Generate a random string\nfunc randomString(length int) string {\n\tconst alphaNum = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n\trandomString := make([]byte, length)\n\tfor i := range randomString {\n\t\trandomString[i] = alphaNum[rand.Intn(len(alphaNum))]\n\t}\n\treturn string(randomString)\n}\n\n\/\/ Goroutine which generates rows of test data\nfunc worker(results chan <- *oneRow) {\n\tfor {\n\t\trow := new(oneRow)\n\t\trow.key_data = rand.Int()\n\t\trow.int_data = rand.Int()\n\t\trow.signed_data = rand.Int()\n\t\trow.float_data = rand.Float32()\n\t\trow.double_data = rand.Float64()\n\t\trow.decim_data = fmt.Sprintf(\"%d.%d\", rand.Intn(100000000000000000), rand.Intn(100))\n\t\trow.date_data = fmt.Sprintf(\"%d%d%d%d-%d%d-%d%d\", rand.Intn(10), rand.Intn(10), rand.Intn(10),\n\t\t\trand.Intn(10), rand.Intn(10), rand.Intn(10), rand.Intn(10), rand.Intn(10))\n\t\trow.code_data = randomString(10)\n\t\trow.name_data = randomString(20)\n\t\taddLen := rand.Intn(80)\n\t\tif addLen < 8 {\n\t\t\taddLen = 8\n\t\t}\n\t\trow.address_data = randomString(addLen)\n\t\tresults <- row\n\t}\n}\n<commit_msg>Generates the file in the current directory<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\n\t\"github.com\/gwenn\/gosqlite\"\n)\n\nvar (\n\tfileName = \"72mb.sqlite\"\n\tnumRows  = 100000 \/\/ 100000 makes a 72MB file (taking ~4.5 seconds) on my Linux desktop.  Adjust to suit your desired target file size\n)\n\ntype oneRow struct {\n\tkey_data     int\n\tint_data     int\n\tsigned_data  int\n\tfloat_data   float32\n\tdouble_data  float64\n\tdecim_data   string\n\tdate_data    string\n\tcode_data    string\n\tname_data    string\n\taddress_data string\n}\n\nfunc main() {\n\t\/\/ Determine full path to target file\n\td, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\tfn := filepath.Join(d, fileName)\n\n\t\/\/ If the database file already exists, nuke the file\n\t_, err = os.Stat(fn)\n\tif err == nil {\n\t\t\/\/ No error occurred when looking for an existing file, which means something is there.  For now, we're just\n\t\t\/\/ going to blindly kill the existing thing without any kind of better safeguard\n\t\tlog.Printf(\"A SQLite database appears to be there already... removing it\")\n\t\tos.Remove(fn)\n\t}\n\n\t\/\/ Create empty SQLite database\n\tlog.Printf(\"Creating new SQLite database file '%s'\\n\", fn)\n\tsdb, err := sqlite.Open(fn, sqlite.OpenCreate|sqlite.OpenReadWrite)\n\tif err != nil {\n\t\tlog.Printf(\"Couldn't open database: %s\", err)\n\t\treturn\n\t}\n\tdefer sdb.Close()\n\n\t\/\/ Disable the journal\n\terr = sdb.Select(\"PRAGMA journal_mode=OFF\", func(s *sqlite.Stmt) error {\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"Error when disabling the journal: %s\\n\", err)\n\t\treturn\n\t}\n\n\t\/\/ Turn off synchronous mode\n\terr = sdb.Exec(\"PRAGMA synchronous=OFF\")\n\tif err != nil {\n\t\tlog.Printf(\"Error when setting synchronous mode: %s\\n\", err)\n\t\treturn\n\t}\n\n\t\/\/ Create the schema\n\tlog.Println(\"Creating tables\")\n\ttableNames := []string{\"uniques\", \"updates\", \"hundred\", \"tenpct\", \"tiny\"}\n\tvar dbQuery string\n\tfor _, tbl := range tableNames {\n\t\tdbQuery = fmt.Sprintf(`\n\t\t\tCREATE TABLE IF NOT EXISTS %s (\n\t\t\t\t'col_key'     INTEGER NOT NULL,\n\t\t\t\t'col_int'     INTEGER NOT NULL,\n\t\t\t\t'col_signed'  INTEGER NOT NULL,\n\t\t\t\t'col_float'   REAL NOT NULL,\n\t\t\t\t'col_double'  REAL NOT NULL,\n\t\t\t\t'col_decim'   NUMERIC NOT NULL,\n\t\t\t\t'col_date'    TEXT NOT NULL,\n\t\t\t\t'col_code'    TEXT NOT NULL,\n\t\t\t\t'col_name'    TEXT NOT NULL,\n\t\t\t\t'col_address' TEXT NOT NULL\n\t\t\t)`, tbl)\n\t\terr := sdb.Exec(dbQuery)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error when creating table '%s': %s\\n\", tbl, err)\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ Launch a worker pool generating row data\n\tcpus := runtime.NumCPU()\n\tlog.Printf(\"# of cpu's detected: %d.  Launching %d data generation workers\\n\", cpus, cpus)\n\tresults := make(chan *oneRow, cpus*5) \/\/ 5 seems ok, less than 5 seems slightly slower (not properly measured though!)\n\tfor w := 0; w < cpus; w++ {\n\t\tgo worker(results)\n\t}\n\n\t\/\/ Bulk insert row data (inside a single transaction per table)\n\tlog.Println(\"Adding data\")\n\tvar r *oneRow\n\tfor _, tbl := range tableNames {\n\t\terr = sdb.Begin()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error for Begin(): %s\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Prepare the insert statement\n\t\tdbQuery := sqlite.Mprintf(`\n\t\t\tINSERT into %w (col_key, col_int, col_signed, col_float, col_double, col_decim, col_date, col_code, col_name, col_address)\n\t\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, tbl)\n\t\tstmt, err := sdb.Prepare(dbQuery)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error when preparing statement for inserts: %s\\n\", err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Insert the data\n\t\tfor i := 0; i < numRows; i++ {\n\t\t\tr = <-results\n\t\t\terr = stmt.Exec(r.key_data, r.int_data, r.signed_data, r.float_data, r.double_data, r.decim_data,\n\t\t\t\tr.date_data, r.code_data, r.name_data, r.address_data)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error when inserting data: %s\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Clean up for this loop\n\t\tstmt.Finalize()\n\n\t\t\/\/ Commit the transaction\n\t\tsdb.Commit()\n\t}\n\n\t\/\/ TODO: Create indexes ?\n\n\t\/\/ Let the user know the program completed ok\n\tlog.Printf(\"SQLite database generation completed\")\n}\n\n\/\/ Generate a random string\nfunc randomString(length int) string {\n\tconst alphaNum = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n\trandomString := make([]byte, length)\n\tfor i := range randomString {\n\t\trandomString[i] = alphaNum[rand.Intn(len(alphaNum))]\n\t}\n\treturn string(randomString)\n}\n\n\/\/ Goroutine which generates rows of test data\nfunc worker(results chan<- *oneRow) {\n\tfor {\n\t\trow := new(oneRow)\n\t\trow.key_data = rand.Int()\n\t\trow.int_data = rand.Int()\n\t\trow.signed_data = rand.Int()\n\t\trow.float_data = rand.Float32()\n\t\trow.double_data = rand.Float64()\n\t\trow.decim_data = fmt.Sprintf(\"%d.%d\", rand.Intn(100000000000000000), rand.Intn(100))\n\t\trow.date_data = fmt.Sprintf(\"%d%d%d%d-%d%d-%d%d\", rand.Intn(10), rand.Intn(10), rand.Intn(10),\n\t\t\trand.Intn(10), rand.Intn(10), rand.Intn(10), rand.Intn(10), rand.Intn(10))\n\t\trow.code_data = randomString(10)\n\t\trow.name_data = randomString(20)\n\t\taddLen := rand.Intn(80)\n\t\tif addLen < 8 {\n\t\t\taddLen = 8\n\t\t}\n\t\trow.address_data = randomString(addLen)\n\t\tresults <- row\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nfunc in(slice []string, str string) bool {\n\tfor _, s := range slice {\n\t\tif s == str {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nvar acceptedImageExt = []string{\".jpg\", \".jpeg\"}\nvar images = []string{}\nvar dirThumbs = fmt.Sprintf(\"%s%s\", os.Getenv(\"HOME\"), \"\/.cache\/sxiv\")\nvar dirPath = \".\"\n\nfunc main() {\n\n\tflag.Parse()\n\n\tdirectory := flag.Arg(0)\n\tdirPath, _ = filepath.Abs(directory)\n\n\tfmt.Println(\"lk is serving\", dirPath, \"from http:\/\/0.0.0.0:3000\")\n\n\tfilepath.Walk(dirPath, func(filePath string, info os.FileInfo, err error) error {\n\t\tif err == nil && in(acceptedImageExt, strings.ToLower(path.Ext(filePath))) {\n\t\t\tthumbnail := fmt.Sprintf(\"%s%s.jpg\", dirThumbs, filePath)\n\t\t\tif _, err := os.Stat(thumbnail); os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Missing thumbnail:\", thumbnail)\n\t\t\t\tgenthumb(filePath, thumbnail)\n\t\t\t}\n\t\t\timages = append(images, filePath)\n\t\t}\n\t\treturn nil\n\t})\n\n\thttp.Handle(\"\/o\/\", http.StripPrefix(\"\/o\/\", http.FileServer(http.Dir(\"\/\"))))\n\thttp.Handle(\"\/t\/\", http.StripPrefix(\"\/t\/\", (http.FileServer(http.Dir(dirThumbs)))))\n\thttp.HandleFunc(\"\/\", lk)\n\thttp.ListenAndServe(\":3000\", nil)\n}\n\nfunc loggingHandler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"right\", r.Method, r.URL.Path)\n\t\th.ServeHTTP(w, r)\n\t})\n}\n\nfunc lk(w http.ResponseWriter, r *http.Request) {\n\n\tt, err := template.New(\"foo\").Parse(`{{ range . }}<a title={{ . }} href=\/o{{ . }}>\n<img width=160 src=\"\/t{{ . }}.jpg\">\n<\/a>\n{{ end }}`)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tt.Execute(w, images)\n}\n<commit_msg>Only show files from dirPath<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nfunc in(slice []string, str string) bool {\n\tfor _, s := range slice {\n\t\tif s == str {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nvar acceptedImageExt = []string{\".jpg\", \".jpeg\"}\nvar images = []string{}\nvar dirThumbs = fmt.Sprintf(\"%s%s\", os.Getenv(\"HOME\"), \"\/.cache\/sxiv\")\nvar dirPath = \".\"\n\nfunc main() {\n\n\tflag.Parse()\n\n\tdirectory := flag.Arg(0)\n\tdirPath, _ = filepath.Abs(directory)\n\n\tfmt.Println(\"lk is serving\", dirPath, \"from http:\/\/0.0.0.0:3000\")\n\n\tfilepath.Walk(dirPath, func(filePath string, info os.FileInfo, err error) error {\n\t\tif err == nil && in(acceptedImageExt, strings.ToLower(path.Ext(filePath))) {\n\t\t\tthumbnail := fmt.Sprintf(\"%s%s.jpg\", dirThumbs, filePath)\n\t\t\tif _, err := os.Stat(thumbnail); os.IsNotExist(err) {\n\t\t\t\tfmt.Println(\"Missing thumbnail:\", thumbnail)\n\t\t\t\tgenthumb(filePath, thumbnail)\n\t\t\t}\n\t\t\timages = append(images, filePath)\n\t\t}\n\t\treturn nil\n\t})\n\n\t\/\/ Don't allow path under dirPath to be viewed\n\t\/\/ http:\/\/www.reddit.com\/r\/golang\/comments\/2l59wk\/web_based_jpg_viewer_for_sharing_images_on_a_lan\/clrpbyo\n\thttp.Handle(\"\/o\/\", http.StripPrefix(path.Join(\"\/o\", dirPath), http.FileServer(http.Dir(dirPath))))\n\thttp.Handle(\"\/t\/\", http.StripPrefix(path.Join(\"\/t\", dirPath), http.FileServer(http.Dir(path.Join(dirThumbs, dirPath)))))\n\n\thttp.HandleFunc(\"\/\", lk)\n\thttp.ListenAndServe(\":3000\", nil)\n}\n\nfunc loggingHandler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Println(\"right\", r.Method, r.URL.Path)\n\t\th.ServeHTTP(w, r)\n\t})\n}\n\nfunc lk(w http.ResponseWriter, r *http.Request) {\n\n\tt, err := template.New(\"foo\").Parse(`{{ range . }}<a title={{ . }} href=\/o{{ . }}>\n<img width=160 src=\"\/t{{ . }}.jpg\">\n<\/a>\n{{ end }}`)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tt.Execute(w, images)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014-2016 Bitmark Inc.\n\/\/ Use of this source code is governed by an ISC\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"github.com\/bitmark-inc\/bitmark-mgmt\/api\"\n\t\"github.com\/bitmark-inc\/bitmark-mgmt\/configuration\"\n\t\"github.com\/bitmark-inc\/bitmark-mgmt\/fault\"\n\t\"github.com\/bitmark-inc\/bitmark-mgmt\/templates\"\n\t\"github.com\/bitmark-inc\/bitmark-mgmt\/utils\"\n\t\"github.com\/bitmark-inc\/exitwithstatus\"\n\t\"github.com\/bitmark-inc\/logger\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"golang.org\/x\/crypto\/bcrypt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"syscall\"\n\t\"text\/template\"\n\t\"time\"\n)\n\nvar GlobalConfig *configuration.Configuration\nvar BitmarkMgmtConfigFile string\n\nvar mainLog *logger.L\n\nfunc main() {\n\t\/\/ ensure exit handler is first\n\tdefer exitwithstatus.Handler()\n\n\tvar configFile string\n\n\tapp := cli.NewApp()\n\tapp.Name = \"bitmark-mgmt\"\n\tapp.Usage = \"Configuration program for bitmarkd\"\n\tapp.Version = Version()\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:        \"config-file, c\",\n\t\t\tValue:       \"\",\n\t\t\tUsage:       \"*bitmark-mgmt config file\",\n\t\t\tDestination: &configFile,\n\t\t},\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:  \"setup\",\n\t\t\tUsage: \"Initialise bitmark-mgmt configuration\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"hostname, H\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t\tUsage: \"generate server certificate with the hostname [localhost]\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"data-directory, d\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t\tUsage: \"the direcotry of web and log\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\trunSetup(c, configFile)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"start\",\n\t\t\tUsage: \"start bitmark-mgmt\",\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\trunStart(c, configFile)\n\t\t\t},\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n}\n\nfunc runSetup(c *cli.Context, configFile string) {\n\n\t\/\/ set data-directory\n\tdataDir := c.String(\"data-directory\")\n\tdefaultConfig, err := configuration.GetDefaultConfiguration(dataDir)\n\tif nil != err {\n\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t}\n\n\t\/\/ set logger\n\tsetupLogger(&defaultConfig.Logging)\n\tdefer logger.Finalise()\n\n\tif nil != err {\n\t\tmainLog.Errorf(\"get config file path: %s error: %v\", configFile, err)\n\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t}\n\n\t\/\/ Check if file exist\n\tif !utils.EnsureFileExists(configFile) {\n\t\tfile, err := os.Create(configFile)\n\t\tif nil != err {\n\t\t\tmainLog.Errorf(\"create config file: %s failed: %v\", configFile, err)\n\t\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t\t}\n\n\t\tencryptPassword, err := bcrypt.GenerateFromPassword([]byte(defaultConfig.Password), bcrypt.DefaultCost)\n\t\tif nil != err {\n\t\t\tmainLog.Errorf(\"Encrypt password failed: %v\", err)\n\t\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t\t}\n\n\t\tdefaultConfig.Password = string(encryptPassword)\n\n\t\t\/\/ generate config file\n\t\tconfTemp := template.Must(template.New(\"config\").Parse(templates.ConfigurationTemplate))\n\t\tif err := confTemp.Execute(file, defaultConfig); nil != err {\n\t\t\tmainLog.Errorf(\"Generate config template failed: %v\", err)\n\t\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t\t}\n\t\tmainLog.Info(\"Successfully setup bitmark-mgmt configuration file\")\n\n\t\t\/\/ gen certificate\n\t\thostname := c.String(\"hostname\")\n\t\tif \"\" != hostname {\n\t\t\t\/\/ gen certs\n\t\t\tcert, key, newCreate, err := utils.GetTLSCertFile(defaultConfig.DataDirectory)\n\t\t\tif nil != err {\n\t\t\t\tmainLog.Errorf(\"get TLS file failed: %v\", err)\n\t\t\t\texitwithstatus.Message(\"get TLS file failed: %v\\n\", err)\n\t\t\t}\n\n\t\t\tif newCreate {\n\t\t\t\tmainLog.Infof(\"Generate self signed certificate for hostname: %s\", hostname)\n\t\t\t\thostnames := []string{hostname}\n\t\t\t\tif err := utils.MakeSelfSignedCertificate(\"bitmark-mgmt\", cert, key, false, hostnames); nil != err {\n\t\t\t\t\tmainLog.Errorf(\"generate TLS file failed: %v\", err)\n\t\t\t\t\texitwithstatus.Message(\"generate TLS file failed: %v\\n\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmainLog.Error(\"TLS file existed\")\n\t\t\t\texitwithstatus.Message(\"TLS file existed\\n\")\n\t\t\t}\n\t\t\tmainLog.Info(\"Successfully generate TLS files\")\n\t\t}\n\t} else {\n\t\tmainLog.Errorf(\"config file %s existed\", configFile)\n\t\texitwithstatus.Message(\"Error: %s existed\\n\", configFile)\n\t}\n\n}\n\nfunc runStart(c *cli.Context, configFile string) {\n\n\tif !utils.EnsureFileExists(configFile) {\n\t\texitwithstatus.Message(\"Error: %v\\n\", fault.ErrNotFoundConfigFile)\n\t}\n\n\tBitmarkMgmtConfigFile = configFile\n\n\t\/\/ read bitmark-mgmt config file\n\tif configs, err := configuration.GetConfiguration(configFile); nil != err {\n\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t} else {\n\t\tGlobalConfig = configs\n\n\t\tsetupLogger(&configs.Logging)\n\t\tdefer logger.Finalise()\n\n\t\t\/\/ initialise services\n\t\tif err := InitialiseBackgroundService(configs.BitmarkConfigFile); nil != err {\n\t\t\tmainLog.Criticalf(\"initialise background services failed: %v\", err)\n\t\t\texitwithstatus.Exit(1)\n\t\t}\n\t\tdefer FinaliseBackgroundService()\n\n\t\tgo func() {\n\t\t\tif err := startWebServer(GlobalConfig); err != nil {\n\t\t\t\tmainLog.Criticalf(\"%s\", err)\n\t\t\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t\t\t}\n\t\t}()\n\n\t\t\/\/ turn Signals into channel messages\n\t\tch := make(chan os.Signal)\n\t\tsignal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)\n\t\tsig := <-ch\n\t\tmainLog.Infof(\"received signal: %v\", sig)\n\t\tmainLog.Info(\"shutting down...\")\n\t}\n}\n\nfunc setupLogger(logging *configuration.LoggerType) {\n\t\/\/ start logging\n\tif err := logger.Initialise(logging.File, logging.Size, logging.Count); nil != err {\n\t\texitwithstatus.Message(\"%s: logger setup failed with error: %v\", err)\n\t}\n\n\tlogger.LoadLevels(logging.Levels)\n\n\t\/\/ create a logger channel for the main program\n\tmainLog = logger.New(\"main\")\n\tmainLog.Info(\"starting…\")\n\tmainLog.Debugf(\"loggerType: %v\", logging)\n}\n\nfunc startWebServer(configs *configuration.Configuration) error {\n\thost := \"0.0.0.0\"\n\tport := strconv.Itoa(configs.Port)\n\n\t\/\/ serve web pages\n\tmainLog.Info(\"Set up server files\")\n\tbaseWebDir := configs.DataDirectory + \"\/webpages\"\n\thttp.Handle(\"\/lib\/\", http.StripPrefix(\"\/lib\/\", http.FileServer(http.Dir(baseWebDir+\"\/lib\/\"))))\n\thttp.Handle(\"\/scripts\/\", http.StripPrefix(\"\/scripts\/\", http.FileServer(http.Dir(baseWebDir+\"\/scripts\/\"))))\n\thttp.Handle(\"\/images\/\", http.StripPrefix(\"\/images\/\", http.FileServer(http.Dir(baseWebDir+\"\/images\/\"))))\n\thttp.Handle(\"\/styles\/\", http.StripPrefix(\"\/styles\/\", http.FileServer(http.Dir(baseWebDir+\"\/styles\/\"))))\n\thttp.Handle(\"\/\", http.FileServer(http.Dir(baseWebDir+\"\/\")))\n\n\t\/\/ serve api\n\tmainLog.Info(\"Set up server api\")\n\thttp.HandleFunc(\"\/api\/config\", handleConfig)\n\thttp.HandleFunc(\"\/api\/password\", handleSetPassword)\n\thttp.HandleFunc(\"\/api\/login\", handleLogin)\n\thttp.HandleFunc(\"\/api\/logout\", handleLogout)\n\thttp.HandleFunc(\"\/api\/bitmarkd\", handleBitmarkd)\n\n\tserver := &http.Server{\n\t\tAddr:           host + \":\" + port,\n\t\tReadTimeout:    10 * time.Second,\n\t\tWriteTimeout:   10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\n\tif configs.EnableHttps {\n\t\tmainLog.Info(\"Starting https server...\")\n\t\t\/\/ gen certs\n\t\tcert, key, newCreate, err := utils.GetTLSCertFile(configs.DataDirectory)\n\t\tif nil != err {\n\t\t\treturn err\n\t\t}\n\n\t\tif newCreate {\n\t\t\tmainLog.Info(\"Generate self signed certificate...\")\n\t\t\tif err := utils.MakeSelfSignedCertificate(\"bitmark-mgmt\", cert, key, false, nil); nil != err {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif err := server.ListenAndServeTLS(cert, key); nil != err {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tmainLog.Info(\"Starting http server...\")\n\t\tif err := server.ListenAndServe(); nil != err {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\ntype webPagesConfigType struct {\n\tHost        string\n\tPort        string\n\tEnableHttps bool\n}\n\nfunc checkAuthorization(w http.ResponseWriter, req *http.Request, writeHeader bool, log *logger.L) bool {\n\tif GlobalConfig.EnableHttps {\n\t\tif err := api.GetAndCheckCookie(w, req, log); nil != err {\n\t\t\tlog.Errorf(\"Error: %v\", err)\n\t\t\tif writeHeader {\n\t\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc handleConfig(w http.ResponseWriter, req *http.Request) {\n\tlog := logger.New(\"api-config\")\n\n\tapi.SetCORSHeader(w, req)\n\n\tswitch req.Method {\n\tcase `GET`: \/\/ list bitmark config\n\t\tif !checkAuthorization(w, req, true, log) {\n\t\t\treturn\n\t\t}\n\t\tapi.ListConfig(w, req, GlobalConfig.BitmarkConfigFile, log)\n\tcase `POST`:\n\t\tif !checkAuthorization(w, req, true, log) {\n\t\t\treturn\n\t\t}\n\t\tapi.UpdateConfig(w, req, GlobalConfig.BitmarkConfigFile, log)\n\tcase `OPTIONS`:\n\t\treturn\n\tdefault:\n\t\tlog.Error(\"Error: Unknow method\")\n\t}\n}\n\nfunc handleSetPassword(w http.ResponseWriter, req *http.Request) {\n\tlog := logger.New(\"api-bitmarkmgmt\")\n\tapi.SetCORSHeader(w, req)\n\n\tif req.Method == \"OPTIONS\" || !checkAuthorization(w, req, true, log) {\n\t\treturn\n\t}\n\n\tswitch req.Method {\n\tcase `POST`:\n\t\tif !utils.EnsureFileExists(BitmarkMgmtConfigFile) {\n\t\t\texitwithstatus.Message(\"Error: %s\\n\", fault.ErrNotFoundConfigFile)\n\t\t}\n\t\tif configs, err := configuration.GetConfiguration(BitmarkMgmtConfigFile); nil != err {\n\t\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t\t} else {\n\t\t\tGlobalConfig = configs\n\t\t\tapi.SetBitmarkMgmtPassword(w, req, BitmarkMgmtConfigFile, GlobalConfig.Password, log)\n\t\t}\n\tcase `OPTIONS`:\n\t\treturn\n\tdefault:\n\t\tlog.Error(\"Error: Unknow method\")\n\t}\n}\n\nfunc handleLogin(w http.ResponseWriter, req *http.Request) {\n\tlog := logger.New(\"api-login\")\n\tapi.SetCORSHeader(w, req)\n\n\tswitch req.Method {\n\tcase `GET`:\n\t\tif !checkAuthorization(w, req, true, log) {\n\t\t\treturn\n\t\t}\n\t\tapi.LoginStatus(w, log)\n\tcase `POST`:\n\t\tif GlobalConfig.EnableHttps && checkAuthorization(w, req, false, log) {\n\t\t\tif err := api.WriteGlobalErrorResponse(w, fault.ApiErrAlreadyLoggedIn, log); nil != err {\n\t\t\t\tlog.Errorf(\"Error: %v\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tapi.LoginBitmarkMgmt(w, req, GlobalConfig.Password, log)\n\tcase `OPTIONS`:\n\t\treturn\n\tdefault:\n\t\tlog.Error(\"Error: Unknow method\")\n\t}\n}\n\nfunc handleLogout(w http.ResponseWriter, req *http.Request) {\n\tlog := logger.New(\"api-logout\")\n\tapi.SetCORSHeader(w, req)\n\n\tif req.Method == \"OPTIONS\" || !checkAuthorization(w, req, true, log) {\n\t\treturn\n\t}\n\n\tswitch req.Method {\n\tcase `POST`:\n\t\tapi.LogoutBitmarkMgmt(w, log)\n\tcase `OPTIONS`:\n\t\treturn\n\tdefault:\n\t\tlog.Error(\"Error: Unknow method\")\n\t}\n}\n\nfunc handleBitmarkd(w http.ResponseWriter, req *http.Request) {\n\tlog := logger.New(\"api-bitmarkd\")\n\tapi.SetCORSHeader(w, req)\n\n\tif req.Method == \"OPTIONS\" || !checkAuthorization(w, req, true, log) {\n\t\treturn\n\t}\n\n\tswitch req.Method {\n\tcase `POST`:\n\t\tapi.Bitmarkd(w, req, GlobalConfig.BitmarkConfigFile, log)\n\tcase `OPTIONS`:\n\t\treturn\n\tdefault:\n\t\tlog.Error(\"Error: Unknow method\")\n\t}\n}\n<commit_msg>update to fit cli lib change<commit_after>\/\/ Copyright (c) 2014-2016 Bitmark Inc.\n\/\/ Use of this source code is governed by an ISC\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"github.com\/bitmark-inc\/bitmark-mgmt\/api\"\n\t\"github.com\/bitmark-inc\/bitmark-mgmt\/configuration\"\n\t\"github.com\/bitmark-inc\/bitmark-mgmt\/fault\"\n\t\"github.com\/bitmark-inc\/bitmark-mgmt\/templates\"\n\t\"github.com\/bitmark-inc\/bitmark-mgmt\/utils\"\n\t\"github.com\/bitmark-inc\/exitwithstatus\"\n\t\"github.com\/bitmark-inc\/logger\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"golang.org\/x\/crypto\/bcrypt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"syscall\"\n\t\"text\/template\"\n\t\"time\"\n)\n\nvar GlobalConfig *configuration.Configuration\nvar BitmarkMgmtConfigFile string\n\nvar mainLog *logger.L\n\nfunc main() {\n\t\/\/ ensure exit handler is first\n\tdefer exitwithstatus.Handler()\n\n\tvar configFile string\n\n\tapp := cli.NewApp()\n\tapp.Name = \"bitmark-mgmt\"\n\tapp.Usage = \"Configuration program for bitmarkd\"\n\tapp.Version = Version()\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:        \"config-file, c\",\n\t\t\tValue:       \"\",\n\t\t\tUsage:       \"*bitmark-mgmt config file\",\n\t\t\tDestination: &configFile,\n\t\t},\n\t}\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:  \"setup\",\n\t\t\tUsage: \"Initialise bitmark-mgmt configuration\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"hostname, H\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t\tUsage: \"generate server certificate with the hostname [localhost]\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName:  \"data-directory, d\",\n\t\t\t\t\tValue: \"\",\n\t\t\t\t\tUsage: \"the direcotry of web and log\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\trunSetup(c, configFile)\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:  \"start\",\n\t\t\tUsage: \"start bitmark-mgmt\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\trunStart(c, configFile)\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n}\n\nfunc runSetup(c *cli.Context, configFile string) {\n\n\t\/\/ set data-directory\n\tdataDir := c.String(\"data-directory\")\n\tdefaultConfig, err := configuration.GetDefaultConfiguration(dataDir)\n\tif nil != err {\n\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t}\n\n\t\/\/ set logger\n\tsetupLogger(&defaultConfig.Logging)\n\tdefer logger.Finalise()\n\n\tif nil != err {\n\t\tmainLog.Errorf(\"get config file path: %s error: %v\", configFile, err)\n\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t}\n\n\t\/\/ Check if file exist\n\tif !utils.EnsureFileExists(configFile) {\n\t\tfile, err := os.Create(configFile)\n\t\tif nil != err {\n\t\t\tmainLog.Errorf(\"create config file: %s failed: %v\", configFile, err)\n\t\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t\t}\n\n\t\tencryptPassword, err := bcrypt.GenerateFromPassword([]byte(defaultConfig.Password), bcrypt.DefaultCost)\n\t\tif nil != err {\n\t\t\tmainLog.Errorf(\"Encrypt password failed: %v\", err)\n\t\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t\t}\n\n\t\tdefaultConfig.Password = string(encryptPassword)\n\n\t\t\/\/ generate config file\n\t\tconfTemp := template.Must(template.New(\"config\").Parse(templates.ConfigurationTemplate))\n\t\tif err := confTemp.Execute(file, defaultConfig); nil != err {\n\t\t\tmainLog.Errorf(\"Generate config template failed: %v\", err)\n\t\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t\t}\n\t\tmainLog.Info(\"Successfully setup bitmark-mgmt configuration file\")\n\n\t\t\/\/ gen certificate\n\t\thostname := c.String(\"hostname\")\n\t\tif \"\" != hostname {\n\t\t\t\/\/ gen certs\n\t\t\tcert, key, newCreate, err := utils.GetTLSCertFile(defaultConfig.DataDirectory)\n\t\t\tif nil != err {\n\t\t\t\tmainLog.Errorf(\"get TLS file failed: %v\", err)\n\t\t\t\texitwithstatus.Message(\"get TLS file failed: %v\\n\", err)\n\t\t\t}\n\n\t\t\tif newCreate {\n\t\t\t\tmainLog.Infof(\"Generate self signed certificate for hostname: %s\", hostname)\n\t\t\t\thostnames := []string{hostname}\n\t\t\t\tif err := utils.MakeSelfSignedCertificate(\"bitmark-mgmt\", cert, key, false, hostnames); nil != err {\n\t\t\t\t\tmainLog.Errorf(\"generate TLS file failed: %v\", err)\n\t\t\t\t\texitwithstatus.Message(\"generate TLS file failed: %v\\n\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmainLog.Error(\"TLS file existed\")\n\t\t\t\texitwithstatus.Message(\"TLS file existed\\n\")\n\t\t\t}\n\t\t\tmainLog.Info(\"Successfully generate TLS files\")\n\t\t}\n\t} else {\n\t\tmainLog.Errorf(\"config file %s existed\", configFile)\n\t\texitwithstatus.Message(\"Error: %s existed\\n\", configFile)\n\t}\n\n}\n\nfunc runStart(c *cli.Context, configFile string) {\n\n\tif !utils.EnsureFileExists(configFile) {\n\t\texitwithstatus.Message(\"Error: %v\\n\", fault.ErrNotFoundConfigFile)\n\t}\n\n\tBitmarkMgmtConfigFile = configFile\n\n\t\/\/ read bitmark-mgmt config file\n\tif configs, err := configuration.GetConfiguration(configFile); nil != err {\n\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t} else {\n\t\tGlobalConfig = configs\n\n\t\tsetupLogger(&configs.Logging)\n\t\tdefer logger.Finalise()\n\n\t\t\/\/ initialise services\n\t\tif err := InitialiseBackgroundService(configs.BitmarkConfigFile); nil != err {\n\t\t\tmainLog.Criticalf(\"initialise background services failed: %v\", err)\n\t\t\texitwithstatus.Exit(1)\n\t\t}\n\t\tdefer FinaliseBackgroundService()\n\n\t\tgo func() {\n\t\t\tif err := startWebServer(GlobalConfig); err != nil {\n\t\t\t\tmainLog.Criticalf(\"%s\", err)\n\t\t\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t\t\t}\n\t\t}()\n\n\t\t\/\/ turn Signals into channel messages\n\t\tch := make(chan os.Signal)\n\t\tsignal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)\n\t\tsig := <-ch\n\t\tmainLog.Infof(\"received signal: %v\", sig)\n\t\tmainLog.Info(\"shutting down...\")\n\t}\n}\n\nfunc setupLogger(logging *configuration.LoggerType) {\n\t\/\/ start logging\n\tif err := logger.Initialise(logging.File, logging.Size, logging.Count); nil != err {\n\t\texitwithstatus.Message(\"%s: logger setup failed with error: %v\", err)\n\t}\n\n\tlogger.LoadLevels(logging.Levels)\n\n\t\/\/ create a logger channel for the main program\n\tmainLog = logger.New(\"main\")\n\tmainLog.Info(\"starting…\")\n\tmainLog.Debugf(\"loggerType: %v\", logging)\n}\n\nfunc startWebServer(configs *configuration.Configuration) error {\n\thost := \"0.0.0.0\"\n\tport := strconv.Itoa(configs.Port)\n\n\t\/\/ serve web pages\n\tmainLog.Info(\"Set up server files\")\n\tbaseWebDir := configs.DataDirectory + \"\/webpages\"\n\thttp.Handle(\"\/lib\/\", http.StripPrefix(\"\/lib\/\", http.FileServer(http.Dir(baseWebDir+\"\/lib\/\"))))\n\thttp.Handle(\"\/scripts\/\", http.StripPrefix(\"\/scripts\/\", http.FileServer(http.Dir(baseWebDir+\"\/scripts\/\"))))\n\thttp.Handle(\"\/images\/\", http.StripPrefix(\"\/images\/\", http.FileServer(http.Dir(baseWebDir+\"\/images\/\"))))\n\thttp.Handle(\"\/styles\/\", http.StripPrefix(\"\/styles\/\", http.FileServer(http.Dir(baseWebDir+\"\/styles\/\"))))\n\thttp.Handle(\"\/\", http.FileServer(http.Dir(baseWebDir+\"\/\")))\n\n\t\/\/ serve api\n\tmainLog.Info(\"Set up server api\")\n\thttp.HandleFunc(\"\/api\/config\", handleConfig)\n\thttp.HandleFunc(\"\/api\/password\", handleSetPassword)\n\thttp.HandleFunc(\"\/api\/login\", handleLogin)\n\thttp.HandleFunc(\"\/api\/logout\", handleLogout)\n\thttp.HandleFunc(\"\/api\/bitmarkd\", handleBitmarkd)\n\n\tserver := &http.Server{\n\t\tAddr:           host + \":\" + port,\n\t\tReadTimeout:    10 * time.Second,\n\t\tWriteTimeout:   10 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\n\tif configs.EnableHttps {\n\t\tmainLog.Info(\"Starting https server...\")\n\t\t\/\/ gen certs\n\t\tcert, key, newCreate, err := utils.GetTLSCertFile(configs.DataDirectory)\n\t\tif nil != err {\n\t\t\treturn err\n\t\t}\n\n\t\tif newCreate {\n\t\t\tmainLog.Info(\"Generate self signed certificate...\")\n\t\t\tif err := utils.MakeSelfSignedCertificate(\"bitmark-mgmt\", cert, key, false, nil); nil != err {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tif err := server.ListenAndServeTLS(cert, key); nil != err {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tmainLog.Info(\"Starting http server...\")\n\t\tif err := server.ListenAndServe(); nil != err {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\ntype webPagesConfigType struct {\n\tHost        string\n\tPort        string\n\tEnableHttps bool\n}\n\nfunc checkAuthorization(w http.ResponseWriter, req *http.Request, writeHeader bool, log *logger.L) bool {\n\tif GlobalConfig.EnableHttps {\n\t\tif err := api.GetAndCheckCookie(w, req, log); nil != err {\n\t\t\tlog.Errorf(\"Error: %v\", err)\n\t\t\tif writeHeader {\n\t\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc handleConfig(w http.ResponseWriter, req *http.Request) {\n\tlog := logger.New(\"api-config\")\n\n\tapi.SetCORSHeader(w, req)\n\n\tswitch req.Method {\n\tcase `GET`: \/\/ list bitmark config\n\t\tif !checkAuthorization(w, req, true, log) {\n\t\t\treturn\n\t\t}\n\t\tapi.ListConfig(w, req, GlobalConfig.BitmarkConfigFile, log)\n\tcase `POST`:\n\t\tif !checkAuthorization(w, req, true, log) {\n\t\t\treturn\n\t\t}\n\t\tapi.UpdateConfig(w, req, GlobalConfig.BitmarkConfigFile, log)\n\tcase `OPTIONS`:\n\t\treturn\n\tdefault:\n\t\tlog.Error(\"Error: Unknow method\")\n\t}\n}\n\nfunc handleSetPassword(w http.ResponseWriter, req *http.Request) {\n\tlog := logger.New(\"api-bitmarkmgmt\")\n\tapi.SetCORSHeader(w, req)\n\n\tif req.Method == \"OPTIONS\" || !checkAuthorization(w, req, true, log) {\n\t\treturn\n\t}\n\n\tswitch req.Method {\n\tcase `POST`:\n\t\tif !utils.EnsureFileExists(BitmarkMgmtConfigFile) {\n\t\t\texitwithstatus.Message(\"Error: %s\\n\", fault.ErrNotFoundConfigFile)\n\t\t}\n\t\tif configs, err := configuration.GetConfiguration(BitmarkMgmtConfigFile); nil != err {\n\t\t\texitwithstatus.Message(\"Error: %v\\n\", err)\n\t\t} else {\n\t\t\tGlobalConfig = configs\n\t\t\tapi.SetBitmarkMgmtPassword(w, req, BitmarkMgmtConfigFile, GlobalConfig.Password, log)\n\t\t}\n\tcase `OPTIONS`:\n\t\treturn\n\tdefault:\n\t\tlog.Error(\"Error: Unknow method\")\n\t}\n}\n\nfunc handleLogin(w http.ResponseWriter, req *http.Request) {\n\tlog := logger.New(\"api-login\")\n\tapi.SetCORSHeader(w, req)\n\n\tswitch req.Method {\n\tcase `GET`:\n\t\tif !checkAuthorization(w, req, true, log) {\n\t\t\treturn\n\t\t}\n\t\tapi.LoginStatus(w, log)\n\tcase `POST`:\n\t\tif GlobalConfig.EnableHttps && checkAuthorization(w, req, false, log) {\n\t\t\tif err := api.WriteGlobalErrorResponse(w, fault.ApiErrAlreadyLoggedIn, log); nil != err {\n\t\t\t\tlog.Errorf(\"Error: %v\", err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tapi.LoginBitmarkMgmt(w, req, GlobalConfig.Password, log)\n\tcase `OPTIONS`:\n\t\treturn\n\tdefault:\n\t\tlog.Error(\"Error: Unknow method\")\n\t}\n}\n\nfunc handleLogout(w http.ResponseWriter, req *http.Request) {\n\tlog := logger.New(\"api-logout\")\n\tapi.SetCORSHeader(w, req)\n\n\tif req.Method == \"OPTIONS\" || !checkAuthorization(w, req, true, log) {\n\t\treturn\n\t}\n\n\tswitch req.Method {\n\tcase `POST`:\n\t\tapi.LogoutBitmarkMgmt(w, log)\n\tcase `OPTIONS`:\n\t\treturn\n\tdefault:\n\t\tlog.Error(\"Error: Unknow method\")\n\t}\n}\n\nfunc handleBitmarkd(w http.ResponseWriter, req *http.Request) {\n\tlog := logger.New(\"api-bitmarkd\")\n\tapi.SetCORSHeader(w, req)\n\n\tif req.Method == \"OPTIONS\" || !checkAuthorization(w, req, true, log) {\n\t\treturn\n\t}\n\n\tswitch req.Method {\n\tcase `POST`:\n\t\tapi.Bitmarkd(w, req, GlobalConfig.BitmarkConfigFile, log)\n\tcase `OPTIONS`:\n\t\treturn\n\tdefault:\n\t\tlog.Error(\"Error: Unknow method\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014 Soichiro Kashima\n\/\/ Licensed under MIT license.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nconst (\n\tExitCodeSuccess = 0\n\tExitCodeError   = 1\n)\n\ntype Options struct {\n\tInFile string\n\tOutDir string\n\tLang   string\n}\n\ntype Markdown struct {\n\tElements []MarkdownElement\n}\n\ntype MarkdownElement struct {\n\tH1 []Inline\n\tH2 []Inline\n\tP  []Inline\n}\n\ntype Inline struct {\n\tHref    string\n\tValue   string\n\tNewLine bool\n}\n\nfunc main() {\n\tvar (\n\t\tin   = flag.String(\"in\", \"\", \"Input Markdown file\")\n\t\tout  = flag.String(\"out\", \"out\", \"Output directory for generated codes\")\n\t\tlang = flag.String(\"lang\", \"html\", \"Output language: Available: html\")\n\t)\n\tflag.Parse()\n\n\topt := Options{\n\t\tInFile: *in,\n\t\tOutDir: *out,\n\t\tLang:   *lang,\n\t}\n\n\tif *in == \"\" {\n\t\tfmt.Println(\"Input file name(-in) is required.\")\n\t\treturn\n\t}\n\n\tmd := parse(&opt)\n\n\tvar c MarkdownConverter\n\tswitch opt.Lang {\n\tcase \"html\":\n\t\tfallthrough\n\tdefault:\n\t\tc = &HtmlConverter{}\n\t}\n\n\tfor _, e := range md.Elements {\n\t\tif 0 < len(e.H1) {\n\t\t\tfmt.Println(c.ToH1(e.H1))\n\t\t} else if 0 < len(e.H2) {\n\t\t\tfmt.Println(c.ToH2(e.H2))\n\t\t} else if 0 < len(e.P) {\n\t\t\tfmt.Println(c.ToP(e.P))\n\t\t}\n\t}\n}\n\nfunc parse(opt *Options) (md Markdown) {\n\tfilename := filepath.Join(opt.InFile)\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\tfmt.Println(\"Error opening file\", err)\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\tb, _ := ioutil.ReadAll(file)\n\tbuf := []Inline{}\n\tfor _, s := range strings.Split(string(b), \"\\n\") {\n\t\tif strings.HasPrefix(s, \"# \") {\n\t\t\t\/\/ H1\n\t\t\tmd.Elements = append(md.Elements, MarkdownElement{H1: parseInline(strings.TrimPrefix(s, \"# \"))})\n\t\t} else if strings.HasPrefix(s, \"## \") {\n\t\t\t\/\/ H2\n\t\t\tmd.Elements = append(md.Elements, MarkdownElement{H2: parseInline(strings.TrimPrefix(s, \"## \"))})\n\t\t} else if s == \"\" {\n\t\t\tif 0 < len(buf) {\n\t\t\t\t\/\/ End of paragraph\n\t\t\t\tmd.Elements = append(md.Elements, MarkdownElement{P: buf})\n\t\t\t\tbuf = []Inline{}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ P\n\t\t\tif strings.HasSuffix(s, \"  \") {\n\t\t\t\t\/\/ New line\n\t\t\t\tbuf = append(buf, parseInline(strings.TrimSuffix(s, \"  \"))...)\n\t\t\t\tbuf = append(buf, Inline{NewLine: true})\n\t\t\t} else {\n\t\t\t\tbuf = append(buf, parseInline(s)...)\n\t\t\t}\n\t\t}\n\t}\n\tif 0 < len(buf) {\n\t\tmd.Elements = append(md.Elements, MarkdownElement{P: buf})\n\t}\n\treturn\n}\n\nfunc parseInline(content string) (result []Inline) {\n\ttmp := content\n\tfor {\n\t\texp := regexp.MustCompile(\"^(.*)\\\\[([^\\\\]]*)\\\\]\\\\(([^\\\\)]*)\\\\)(.*)$\")\n\t\tgroups := exp.FindStringSubmatch(tmp)\n\t\tif groups == nil || len(groups) < 1 {\n\t\t\treturn append(result, Inline{Value: tmp})\n\t\t} else {\n\t\t\tresult = append(result, Inline{Value: groups[1]})\n\t\t\tresult = append(result, Inline{Href: groups[3], Value: groups[2]})\n\t\t\ttmp = groups[4]\n\t\t}\n\t}\n\treturn result\n}\n\ntype MarkdownConverter interface {\n\tToH1(content []Inline) string\n\tToH2(content []Inline) string\n\tToP(content []Inline) string\n}\n\ntype HtmlConverter struct {\n}\n\nfunc (c *HtmlConverter) ToH1(content []Inline) string {\n\treturn \"<h1>\" + c.constructInlines(content) + \"<\/h1>\"\n}\n\nfunc (c *HtmlConverter) ToH2(content []Inline) string {\n\treturn \"<h2>\" + c.constructInlines(content) + \"<\/h2>\"\n}\n\nfunc (c *HtmlConverter) ToP(content []Inline) string {\n\treturn \"<p>\" + c.constructInlines(content) + \"<\/p>\"\n}\n\nfunc (c *HtmlConverter) constructInlines(content []Inline) string {\n\ts := \"\"\n\tfor _, i := range content {\n\t\tif i.NewLine {\n\t\t\ts += \"<br \/>\"\n\t\t} else if i.Href != \"\" {\n\t\t\ts += \"<a href=\\\"\" + i.Href + \"\\\">\" + i.Value + \"<\/a>\"\n\t\t} else {\n\t\t\ts += i.Value\n\t\t}\n\t}\n\treturn s\n}\n<commit_msg>Changed H1, H2 and P element to bool.<commit_after>\/\/ Copyright (c) 2014 Soichiro Kashima\n\/\/ Licensed under MIT license.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nconst (\n\tExitCodeSuccess = 0\n\tExitCodeError   = 1\n)\n\ntype Options struct {\n\tInFile string\n\tOutDir string\n\tLang   string\n}\n\ntype Markdown struct {\n\tElements []MarkdownElement\n}\n\ntype MarkdownElement struct {\n\tH1     bool\n\tH2     bool\n\tP      bool\n\tValues []Inline\n}\n\ntype Inline struct {\n\tHref    string\n\tValue   string\n\tNewLine bool\n}\n\nfunc main() {\n\tvar (\n\t\tin   = flag.String(\"in\", \"\", \"Input Markdown file\")\n\t\tout  = flag.String(\"out\", \"out\", \"Output directory for generated codes\")\n\t\tlang = flag.String(\"lang\", \"html\", \"Output language: Available: html\")\n\t)\n\tflag.Parse()\n\n\topt := Options{\n\t\tInFile: *in,\n\t\tOutDir: *out,\n\t\tLang:   *lang,\n\t}\n\n\tif *in == \"\" {\n\t\tfmt.Println(\"Input file name(-in) is required.\")\n\t\treturn\n\t}\n\n\tmd := parse(&opt)\n\n\tvar c MarkdownConverter\n\tswitch opt.Lang {\n\tcase \"html\":\n\t\tfallthrough\n\tdefault:\n\t\tc = &HtmlConverter{}\n\t}\n\n\tfor _, e := range md.Elements {\n\t\tif e.H1 {\n\t\t\tfmt.Println(c.ToH1(e.Values))\n\t\t} else if e.H2 {\n\t\t\tfmt.Println(c.ToH2(e.Values))\n\t\t} else if e.P {\n\t\t\tfmt.Println(c.ToP(e.Values))\n\t\t}\n\t}\n}\n\nfunc parse(opt *Options) (md Markdown) {\n\tfilename := filepath.Join(opt.InFile)\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\tfmt.Println(\"Error opening file\", err)\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\tb, _ := ioutil.ReadAll(file)\n\tbuf := []Inline{}\n\tfor _, s := range strings.Split(string(b), \"\\n\") {\n\t\tif strings.HasPrefix(s, \"# \") {\n\t\t\t\/\/ H1\n\t\t\tmd.Elements = append(md.Elements, MarkdownElement{H1: true, Values: parseInline(strings.TrimPrefix(s, \"# \"))})\n\t\t} else if strings.HasPrefix(s, \"## \") {\n\t\t\t\/\/ H2\n\t\t\tmd.Elements = append(md.Elements, MarkdownElement{H2: true, Values: parseInline(strings.TrimPrefix(s, \"## \"))})\n\t\t} else if s == \"\" {\n\t\t\tif 0 < len(buf) {\n\t\t\t\t\/\/ End of paragraph\n\t\t\t\tmd.Elements = append(md.Elements, MarkdownElement{P: true, Values: buf})\n\t\t\t\tbuf = []Inline{}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ P\n\t\t\tif strings.HasSuffix(s, \"  \") {\n\t\t\t\t\/\/ New line\n\t\t\t\tbuf = append(buf, parseInline(strings.TrimSuffix(s, \"  \"))...)\n\t\t\t\tbuf = append(buf, Inline{NewLine: true})\n\t\t\t} else {\n\t\t\t\tbuf = append(buf, parseInline(s)...)\n\t\t\t}\n\t\t}\n\t}\n\tif 0 < len(buf) {\n\t\tmd.Elements = append(md.Elements, MarkdownElement{P: true, Values: buf})\n\t}\n\treturn\n}\n\nfunc parseInline(content string) (result []Inline) {\n\ttmp := content\n\tfor {\n\t\texp := regexp.MustCompile(\"^(.*)\\\\[([^\\\\]]*)\\\\]\\\\(([^\\\\)]*)\\\\)(.*)$\")\n\t\tgroups := exp.FindStringSubmatch(tmp)\n\t\tif groups == nil || len(groups) < 1 {\n\t\t\treturn append(result, Inline{Value: tmp})\n\t\t} else {\n\t\t\tresult = append(result, Inline{Value: groups[1]})\n\t\t\tresult = append(result, Inline{Href: groups[3], Value: groups[2]})\n\t\t\ttmp = groups[4]\n\t\t}\n\t}\n\treturn result\n}\n\ntype MarkdownConverter interface {\n\tToH1(content []Inline) string\n\tToH2(content []Inline) string\n\tToP(content []Inline) string\n}\n\ntype HtmlConverter struct {\n}\n\nfunc (c *HtmlConverter) ToH1(content []Inline) string {\n\treturn \"<h1>\" + c.constructInlines(content) + \"<\/h1>\"\n}\n\nfunc (c *HtmlConverter) ToH2(content []Inline) string {\n\treturn \"<h2>\" + c.constructInlines(content) + \"<\/h2>\"\n}\n\nfunc (c *HtmlConverter) ToP(content []Inline) string {\n\treturn \"<p>\" + c.constructInlines(content) + \"<\/p>\"\n}\n\nfunc (c *HtmlConverter) constructInlines(content []Inline) string {\n\ts := \"\"\n\tfor _, i := range content {\n\t\tif i.NewLine {\n\t\t\ts += \"<br \/>\"\n\t\t} else if i.Href != \"\" {\n\t\t\ts += \"<a href=\\\"\" + i.Href + \"\\\">\" + i.Value + \"<\/a>\"\n\t\t} else {\n\t\t\ts += i.Value\n\t\t}\n\t}\n\treturn s\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"text\/template\"\n)\n\nfunc main() {\n\tvar (\n\t\tindexFile  = flag.String(\"index\", \"\", \"index file (required)\")\n\t\tconfigFile = flag.String(\"config\", \"\", \"config file (required)\")\n\t\ttoDir      = flag.String(\"to\", \"\", \"target dir (required)\")\n\t)\n\tflag.Parse()\n\n\tif *indexFile == \"\" || *configFile == \"\" || *toDir == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"Error: reqired parameter not specified\\n\")\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\t}\n\n\tindex, err := readIndex(*indexFile)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading config: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tindexDir := filepath.Dir(*indexFile)\n\n\tconfig, err := readConfig(*configFile)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading data: %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\terr = generateFiles(index, config, indexDir, *toDir)\n\tif err != nil {\n\t\tlog.Printf(\"Error generating files: %v\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc generateFiles(index index, config interface{}, indexDir, toDir string) error {\n\t\/\/Apply config to targets filepath\n\tfor i := range index.Files {\n\t\tt, err := tmplToString(index.Files[i].Target, config)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error in file mapping: %v\", err)\n\t\t}\n\t\tindex.Files[i].Target = filepath.Join(toDir, t)\n\t}\n\n\tfor _, mapping := range index.Files {\n\t\tfmt.Printf(\"%#v\\n\", mapping)\n\t\tswitch {\n\t\tcase mapping.Before != \"\":\n\t\t\t\/\/insert snippet into file\n\t\t\trenderedSnippet, err := tmplFileToString(mapping.Template, config)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error in file mapping: %v\", err)\n\t\t\t}\n\t\t\terr = insertBefore(mapping.Target, mapping.Before, renderedSnippet)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error inserting into %q:  %v\", mapping.Target, err)\n\t\t\t}\n\t\tdefault:\n\t\t\t\/\/create new file\n\t\t\terr := tmplFileToFile(filepath.Join(indexDir, mapping.Template), mapping.Target, config)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error applying template: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc insertBefore(target, pattern string, snippet string) error {\n\tptn, err := regexp.Compile(pattern)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvar buf bytes.Buffer\n\tf, err := os.Open(target)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not open taget file %s: %v\", target, err)\n\t}\n\tdefer f.Close()\n\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tline := scanner.Bytes()\n\t\tif !ptn.Match(line) {\n\t\t\tbuf.Write(line)\n\t\t\tbuf.WriteByte('\\n')\n\t\t\tcontinue\n\t\t}\n\t\tbuf.WriteString(snippet)\n\t\tbuf.WriteByte('\\n')\n\t\tbuf.Write(line)\n\t\tbuf.WriteByte('\\n')\n\t\tfor scanner.Scan() {\n\t\t\tbuf.Write(scanner.Bytes())\n\t\t\tbuf.WriteByte('\\n')\n\t\t}\n\t\tf.Close()\n\t\tioutil.WriteFile(target, buf.Bytes(), 0644)\n\t\tbreak\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn fmt.Errorf(\"error during inserting snippet into %q:%v\", target, err)\n\t}\n\treturn nil\n}\n\nfunc tmplFileToString(tmplFile string, data interface{}) (string, error) {\n\tvar buf bytes.Buffer\n\ttmpl, err := template.ParseFiles(tmplFile)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"parsing template %s: %v\", tmplFile, err)\n\t}\n\terr = tmpl.Execute(&buf, data)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"executing template %s: %v\", tmplFile, err)\n\t}\n\treturn buf.String(), nil\n}\n\nfunc tmplFileToFile(tmplFile, target string, data interface{}) error {\n\ttargetDir := filepath.Dir(target)\n\terr := os.MkdirAll(targetDir, 0755)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating target dir %q:%v\", targetDir, err)\n\t}\n\tf, err := os.Create(target)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating target file %q:%v\", target, err)\n\t}\n\tdefer f.Close()\n\ttmpl, err := template.ParseFiles(tmplFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing template %s: %v\", tmplFile, err)\n\t}\n\treturn tmpl.Execute(f, data)\n}\n\nfunc tmplToString(textTemplate string, data interface{}) (string, error) {\n\ttmpl := template.New(\"\")\n\tt, err := tmpl.Parse(textTemplate)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"parsing template %q: %v\", textTemplate, err)\n\t}\n\tvar buf bytes.Buffer\n\terr = t.Execute(&buf, data)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"executing template %q with data %v: %v\", textTemplate, data, err)\n\t}\n\treturn buf.String(), nil\n}\n\nfunc readConfig(file string) (interface{}, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn index{}, fmt.Errorf(\"opening data file %s: %v\", file, err)\n\t}\n\tdefer f.Close()\n\tvar v interface{}\n\terr = json.NewDecoder(f).Decode(&v)\n\tif err != nil {\n\t\treturn index{}, fmt.Errorf(\"decoding data file %s: %v\", file, err)\n\t}\n\treturn v, nil\n}\n\nfunc readIndex(file string) (index, error) {\n\tfmt.Printf(\"config %#v\\n\", file)\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn index{}, fmt.Errorf(\"opening config file %s: %v\", file, err)\n\t}\n\tdefer f.Close()\n\tvar v index\n\terr = json.NewDecoder(f).Decode(&v)\n\tif err != nil {\n\t\treturn index{}, fmt.Errorf(\"decoding config file %s: %v\", file, err)\n\t}\n\treturn v, nil\n}\n\ntype index struct {\n\tFiles []fileMapping\n}\n\ntype fileMapping struct {\n\tTemplate string `json:\"from\"`\n\tTarget   string `json:\"to\"`\n\tBefore   string `json:\"before\"`\n}\n<commit_msg>bugfix<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"text\/template\"\n)\n\nfunc main() {\n\tvar (\n\t\tindexFile  = flag.String(\"index\", \"\", \"index file (required)\")\n\t\tconfigFile = flag.String(\"config\", \"\", \"config file (required)\")\n\t\ttoDir      = flag.String(\"to\", \"\", \"target dir (required)\")\n\t)\n\tflag.Parse()\n\n\tif *indexFile == \"\" || *configFile == \"\" || *toDir == \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"Error: reqired parameter not specified\\n\")\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\t}\n\n\tindex, err := readIndex(*indexFile)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading config: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tindexDir := filepath.Dir(*indexFile)\n\n\tconfig, err := readConfig(*configFile)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading data: %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\terr = generateFiles(index, config, indexDir, *toDir)\n\tif err != nil {\n\t\tlog.Printf(\"Error generating files: %v\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc generateFiles(index index, config interface{}, indexDir, toDir string) error {\n\t\/\/Apply config to targets filepath\n\tfor i := range index.Files {\n\t\tt, err := tmplToString(index.Files[i].Target, config)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error in file mapping: %v\", err)\n\t\t}\n\t\tindex.Files[i].Target = filepath.Join(toDir, t)\n\t}\n\n\tfor _, mapping := range index.Files {\n\t\tfmt.Printf(\"%#v\\n\", mapping)\n\t\tswitch {\n\t\tcase mapping.Before != \"\":\n\t\t\t\/\/insert snippet into file\n\t\t\trenderedSnippet, err := tmplFileToString(filepath.Join(indexDir, mapping.Template), config)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error in file mapping: %v\", err)\n\t\t\t}\n\t\t\terr = insertBefore(mapping.Target, mapping.Before, renderedSnippet)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error inserting into %q:  %v\", mapping.Target, err)\n\t\t\t}\n\t\tdefault:\n\t\t\t\/\/create new file\n\t\t\terr := tmplFileToFile(filepath.Join(indexDir, mapping.Template), mapping.Target, config)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error applying template: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc insertBefore(target, pattern string, snippet string) error {\n\tptn, err := regexp.Compile(pattern)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tf, err := os.Open(target)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not open taget file %s: %v\", target, err)\n\t}\n\tdefer f.Close()\n\n\tvar buf bytes.Buffer\n\tscanner := bufio.NewScanner(f)\n\tfor scanner.Scan() {\n\t\tline := scanner.Bytes()\n\t\tif !ptn.Match(line) {\n\t\t\tbuf.Write(line)\n\t\t\tbuf.WriteByte('\\n')\n\t\t\tcontinue\n\t\t}\n\t\tbuf.WriteString(snippet)\n\t\tbuf.WriteByte('\\n')\n\t\tbuf.Write(line)\n\t\tbuf.WriteByte('\\n')\n\t\tfor scanner.Scan() {\n\t\t\tbuf.Write(scanner.Bytes())\n\t\t\tbuf.WriteByte('\\n')\n\t\t}\n\t\tf.Close()\n\t\tioutil.WriteFile(target, buf.Bytes(), 0644)\n\t\tbreak\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn fmt.Errorf(\"error during inserting snippet into %q:%v\", target, err)\n\t}\n\treturn nil\n}\n\nfunc tmplFileToString(tmplFile string, data interface{}) (string, error) {\n\tvar buf bytes.Buffer\n\ttmpl, err := template.ParseFiles(tmplFile)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"parsing template %s: %v\", tmplFile, err)\n\t}\n\terr = tmpl.Execute(&buf, data)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"executing template %s: %v\", tmplFile, err)\n\t}\n\treturn buf.String(), nil\n}\n\nfunc tmplFileToFile(tmplFile, target string, data interface{}) error {\n\ttargetDir := filepath.Dir(target)\n\terr := os.MkdirAll(targetDir, 0755)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating target dir %q:%v\", targetDir, err)\n\t}\n\tf, err := os.Create(target)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"creating target file %q:%v\", target, err)\n\t}\n\tdefer f.Close()\n\ttmpl, err := template.ParseFiles(tmplFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing template %s: %v\", tmplFile, err)\n\t}\n\treturn tmpl.Execute(f, data)\n}\n\nfunc tmplToString(textTemplate string, data interface{}) (string, error) {\n\ttmpl := template.New(\"\")\n\tt, err := tmpl.Parse(textTemplate)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"parsing template %q: %v\", textTemplate, err)\n\t}\n\tvar buf bytes.Buffer\n\terr = t.Execute(&buf, data)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"executing template %q with data %v: %v\", textTemplate, data, err)\n\t}\n\treturn buf.String(), nil\n}\n\nfunc readConfig(file string) (interface{}, error) {\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn index{}, fmt.Errorf(\"opening data file %s: %v\", file, err)\n\t}\n\tdefer f.Close()\n\tvar v interface{}\n\terr = json.NewDecoder(f).Decode(&v)\n\tif err != nil {\n\t\treturn index{}, fmt.Errorf(\"decoding data file %s: %v\", file, err)\n\t}\n\treturn v, nil\n}\n\nfunc readIndex(file string) (index, error) {\n\tfmt.Printf(\"config %#v\\n\", file)\n\tf, err := os.Open(file)\n\tif err != nil {\n\t\treturn index{}, fmt.Errorf(\"opening config file %s: %v\", file, err)\n\t}\n\tdefer f.Close()\n\tvar v index\n\terr = json.NewDecoder(f).Decode(&v)\n\tif err != nil {\n\t\treturn index{}, fmt.Errorf(\"decoding config file %s: %v\", file, err)\n\t}\n\treturn v, nil\n}\n\ntype index struct {\n\tFiles []fileMapping\n}\n\ntype fileMapping struct {\n\tTemplate string `json:\"from\"`\n\tTarget   string `json:\"to\"`\n\tBefore   string `json:\"before\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-lager\"\n\t\"github.com\/cloudfoundry-incubator\/garden\/server\"\n\t\"github.com\/pivotal-cf-experimental\/garden-dot-net\/backend\"\n\t\"github.com\/pivotal-golang\/lager\"\n)\n\nvar listenNetwork = flag.String(\n\t\"listenNetwork\",\n\t\"tcp\",\n\t\"how to listen on the address (unix, tcp, etc.)\",\n)\n\nvar containerGraceTime = flag.Duration(\n\t\"containerGraceTime\",\n\t0,\n\t\"time after which to destroy idle containers\",\n)\n\nfunc main() {\n\tiface := \"0.0.0.0:3333\"\n\tif os.Getenv(\"PORT\") != \"\" {\n\t\tiface = \"0.0.0.0:\" + os.Getenv(\"PORT\")\n\t}\n\tvar listenAddr = flag.String(\n\t\t\"listenAddr\",\n\t\tiface,\n\t\t\"address to listen on\",\n\t)\n\n\tlogger := cf_lager.New(\"garden-dotnet\")\n\n\tnetBackend := backend.DotNetBackend{}\n\n\tgardenServer := server.New(*listenNetwork, *listenAddr, *containerGraceTime, netBackend, logger)\n\terr := gardenServer.Start()\n\tif err != nil {\n\t\tlogger.Fatal(\"Server Failed to Start\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlogger.Info(\"started\", lager.Data{\n\t\t\"network\": *listenNetwork,\n\t\t\"addr\":    *listenAddr,\n\t})\n\n\tsignals := make(chan os.Signal, 1)\n\n\tgo func() {\n\t\t<-signals\n\t\tgardenServer.Stop()\n\t\tos.Exit(0)\n\t}()\n\n\tsignal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)\n\tselect {}\n}\n<commit_msg>Simplify listen port setup<commit_after>package main\n\nimport (\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-lager\"\n\t\"github.com\/cloudfoundry-incubator\/garden\/server\"\n\t\"github.com\/pivotal-cf-experimental\/garden-dot-net\/backend\"\n\t\"github.com\/pivotal-golang\/lager\"\n)\n\nfunc main() {\n\tlistenAddr := \"0.0.0.0:3000\"\n\tif os.Getenv(\"PORT\") != \"\" {\n\t\tlistenAddr = \"0.0.0.0:\" + os.Getenv(\"PORT\")\n\t}\n\n\tlogger := cf_lager.New(\"garden-dotnet\")\n\n\tnetBackend := backend.DotNetBackend{}\n\n\tgardenServer := server.New(\"tcp\", listenAddr, 0, netBackend, logger)\n\terr := gardenServer.Start()\n\tif err != nil {\n\t\tlogger.Fatal(\"Server Failed to Start\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlogger.Info(\"started\", lager.Data{\n\t\t\"addr\":    listenAddr,\n\t})\n\n\tsignals := make(chan os.Signal, 1)\n\n\tgo func() {\n\t\t<-signals\n\t\tgardenServer.Stop()\n\t\tos.Exit(0)\n\t}()\n\n\tsignal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)\n\tselect {}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/google\/subcommands\"\n\t\"github.com\/kotakanbe\/goval-dictionary\/commands\"\n)\n\n\/\/ Name ... Name\nconst Name string = \"goval-dictionary\"\n\n\/\/ Version ... Version\nvar version = \"0.0.3\"\n\n\/\/ Revision of Git\nvar revision string\n\nfunc main() {\n\tsubcommands.Register(subcommands.HelpCommand(), \"\")\n\tsubcommands.Register(subcommands.FlagsCommand(), \"\")\n\tsubcommands.Register(subcommands.CommandsCommand(), \"\")\n\n\tsubcommands.Register(&commands.FetchRedHatCmd{}, \"fetch-redhat\")\n\tsubcommands.Register(&commands.FetchDebianCmd{}, \"fetch-debian\")\n\tsubcommands.Register(&commands.FetchUbuntuCmd{}, \"fetch-ubuntu\")\n\tsubcommands.Register(&commands.FetchSUSECmd{}, \"fetch-suse\")\n\tsubcommands.Register(&commands.FetchOracleCmd{}, \"fetch-oracle\")\n\tsubcommands.Register(&commands.FetchAlpineCmd{}, \"fetch-alpine\")\n\tsubcommands.Register(&commands.FetchAmazonCmd{}, \"fetch-amazon\")\n\tsubcommands.Register(&commands.SelectCmd{}, \"select\")\n\tsubcommands.Register(&commands.ServerCmd{}, \"server\")\n\n\tvar v = flag.Bool(\"v\", false, \"Show version\")\n\n\tif envArgs := os.Getenv(\"GOVAL_DICTIONARY_ARGS\"); 0 < len(envArgs) {\n\t\tflag.CommandLine.Parse(strings.Fields(envArgs))\n\t} else {\n\t\tflag.Parse()\n\t}\n\n\tif *v {\n\t\tfmt.Printf(\"goval-dictionary %s %s\\n\", version, revision)\n\t\tos.Exit(int(subcommands.ExitSuccess))\n\t}\n\n\tctx := context.Background()\n\tos.Exit(int(subcommands.Execute(ctx)))\n}\n<commit_msg>bump up version<commit_after>package main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/google\/subcommands\"\n\t\"github.com\/kotakanbe\/goval-dictionary\/commands\"\n)\n\n\/\/ Name ... Name\nconst Name string = \"goval-dictionary\"\n\n\/\/ Version ... Version\nvar version = \"0.1.0\"\n\n\/\/ Revision of Git\nvar revision string\n\nfunc main() {\n\tsubcommands.Register(subcommands.HelpCommand(), \"\")\n\tsubcommands.Register(subcommands.FlagsCommand(), \"\")\n\tsubcommands.Register(subcommands.CommandsCommand(), \"\")\n\n\tsubcommands.Register(&commands.FetchRedHatCmd{}, \"fetch-redhat\")\n\tsubcommands.Register(&commands.FetchDebianCmd{}, \"fetch-debian\")\n\tsubcommands.Register(&commands.FetchUbuntuCmd{}, \"fetch-ubuntu\")\n\tsubcommands.Register(&commands.FetchSUSECmd{}, \"fetch-suse\")\n\tsubcommands.Register(&commands.FetchOracleCmd{}, \"fetch-oracle\")\n\tsubcommands.Register(&commands.FetchAlpineCmd{}, \"fetch-alpine\")\n\tsubcommands.Register(&commands.FetchAmazonCmd{}, \"fetch-amazon\")\n\tsubcommands.Register(&commands.SelectCmd{}, \"select\")\n\tsubcommands.Register(&commands.ServerCmd{}, \"server\")\n\n\tvar v = flag.Bool(\"v\", false, \"Show version\")\n\n\tif envArgs := os.Getenv(\"GOVAL_DICTIONARY_ARGS\"); 0 < len(envArgs) {\n\t\tflag.CommandLine.Parse(strings.Fields(envArgs))\n\t} else {\n\t\tflag.Parse()\n\t}\n\n\tif *v {\n\t\tfmt.Printf(\"goval-dictionary %s %s\\n\", version, revision)\n\t\tos.Exit(int(subcommands.ExitSuccess))\n\t}\n\n\tctx := context.Background()\n\tos.Exit(int(subcommands.Execute(ctx)))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nrqlite -- a replicated SQLite database.\n\nrqlite is a distributed system that provides a replicated SQLite database.\nrqlite is written in Go and uses Raft to achieve consensus across all the\ninstances of the SQLite databases. rqlite ensures that every change made to\nthe database is made to a majority of underlying SQLite files, or none-at-all.\n*\/\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"runtime\/pprof\"\n\t\"time\"\n\n\t\"github.com\/otoolep\/rqlite\/server\"\n\n\tlog \"code.google.com\/p\/log4go\"\n)\n\nvar host string\nvar port int\nvar join string\nvar dbfile string\nvar cpuprofile string\nvar logFile string\nvar logLevel string\nvar snapAfter int\nvar disableReporting bool\n\nfunc init() {\n\tflag.StringVar(&host, \"h\", \"localhost\", \"hostname\")\n\tflag.IntVar(&port, \"p\", 4001, \"port\")\n\tflag.StringVar(&join, \"join\", \"\", \"host:port of leader to join\")\n\tflag.StringVar(&dbfile, \"dbfile\", \"db.sqlite\", \"sqlite filename\")\n\tflag.StringVar(&cpuprofile, \"cpuprofile\", \"\", \"write CPU profile to file\")\n\tflag.StringVar(&logFile, \"logfile\", \"stdout\", \"log file path\")\n\tflag.StringVar(&logLevel, \"loglevel\", \"INFO\", \"log level (ERROR|WARN|INFO|DEBUG|TRACE)\")\n\tflag.IntVar(&snapAfter, \"s\", 100, \"Snapshot and compact after this number of new log entries\")\n\tflag.BoolVar(&disableReporting, \"noreport\", false, \"Disable anonymised launch reporting\")\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s [arguments] <data-path> \\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n}\n\nfunc setupLogging(loggingLevel, logFile string) {\n\tlevel := log.DEBUG\n\tswitch loggingLevel {\n\tcase \"TRACE\":\n\t\tlevel = log.TRACE\n\tcase \"DEBUG\":\n\t\tlevel = log.DEBUG\n\tcase \"INFO\":\n\t\tlevel = log.INFO\n\tcase \"WARN\":\n\t\tlevel = log.WARNING\n\tcase \"ERROR\":\n\t\tlevel = log.ERROR\n\t}\n\n\tlog.Global = make(map[string]*log.Filter)\n\n\tif logFile == \"stdout\" {\n\t\tflw := log.NewConsoleLogWriter()\n\t\tlog.AddFilter(\"stdout\", level, flw)\n\n\t} else {\n\t\tlogFileDir := filepath.Dir(logFile)\n\t\tos.MkdirAll(logFileDir, 0744)\n\n\t\tflw := log.NewFileLogWriter(logFile, false)\n\t\tlog.AddFilter(\"file\", level, flw)\n\n\t\tflw.SetFormat(\"[%D %T] [%L] (%S) %M\")\n\t\tflw.SetRotate(true)\n\t\tflw.SetRotateSize(0)\n\t\tflw.SetRotateLines(0)\n\t\tflw.SetRotateDaily(true)\n\t}\n\n\tlog.Info(\"Redirectoring logging to %s\", logFile)\n}\n\nfunc main() {\n\tflag.Parse()\n\n\t\/\/ Set up profiling, if requested.\n\tif cpuprofile != \"\" {\n\t\tlog.Info(\"Profiling enabled\")\n\t\tf, err := os.Create(cpuprofile)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Unable to create path: %s\", err.Error())\n\t\t}\n\t\tdefer f.Close()\n\n\t\tpprof.StartCPUProfile(f)\n\t\tdefer pprof.StopCPUProfile()\n\t}\n\tif !disableReporting {\n\t\treportLaunch()\n\t}\n\n\tsetupLogging(logLevel, logFile)\n\n\t\/\/ Set the data directory.\n\tif flag.NArg() == 0 {\n\t\tflag.Usage()\n\t\tprintln(\"Data path argument required\")\n\t\tlog.Error(\"No data path supplied -- aborting\")\n\t\tos.Exit(1)\n\t}\n\tpath := flag.Arg(0)\n\tif err := os.MkdirAll(path, 0744); err != nil {\n\t\tlog.Error(\"Unable to create path: %s\", err.Error())\n\t}\n\n\ts := server.NewServer(path, dbfile, snapAfter, host, port)\n\tgo func() {\n\t\tlog.Error(s.ListenAndServe(join))\n\t}()\n\n\tterminate := make(chan os.Signal, 1)\n\tsignal.Notify(terminate, os.Interrupt)\n\t<-terminate\n\tlog.Info(\"rqlite server stopped\")\n}\n\nfunc reportLaunch() {\n\tjson := fmt.Sprintf(`{\"os\": \"%s\", \"arch\": \"%s\"}`, runtime.GOOS, runtime.GOARCH)\n\tdata := bytes.NewBufferString(json)\n\tclient := http.Client{Timeout: time.Duration(5 * time.Second)}\n\tgo client.Post(\"https:\/\/logs-01.loggly.com\/inputs\/8a0edd84-92ba-46e4-ada8-c529d0f105af\/tag\/rqlite\/\",\n\t\t\"application\/json\", data)\n}\n<commit_msg>Use newer-style reporting tag<commit_after>\/*\nrqlite -- a replicated SQLite database.\n\nrqlite is a distributed system that provides a replicated SQLite database.\nrqlite is written in Go and uses Raft to achieve consensus across all the\ninstances of the SQLite databases. rqlite ensures that every change made to\nthe database is made to a majority of underlying SQLite files, or none-at-all.\n*\/\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"runtime\/pprof\"\n\t\"time\"\n\n\t\"github.com\/otoolep\/rqlite\/server\"\n\n\tlog \"code.google.com\/p\/log4go\"\n)\n\nvar host string\nvar port int\nvar join string\nvar dbfile string\nvar cpuprofile string\nvar logFile string\nvar logLevel string\nvar snapAfter int\nvar disableReporting bool\n\nfunc init() {\n\tflag.StringVar(&host, \"h\", \"localhost\", \"hostname\")\n\tflag.IntVar(&port, \"p\", 4001, \"port\")\n\tflag.StringVar(&join, \"join\", \"\", \"host:port of leader to join\")\n\tflag.StringVar(&dbfile, \"dbfile\", \"db.sqlite\", \"sqlite filename\")\n\tflag.StringVar(&cpuprofile, \"cpuprofile\", \"\", \"write CPU profile to file\")\n\tflag.StringVar(&logFile, \"logfile\", \"stdout\", \"log file path\")\n\tflag.StringVar(&logLevel, \"loglevel\", \"INFO\", \"log level (ERROR|WARN|INFO|DEBUG|TRACE)\")\n\tflag.IntVar(&snapAfter, \"s\", 100, \"Snapshot and compact after this number of new log entries\")\n\tflag.BoolVar(&disableReporting, \"noreport\", false, \"Disable anonymised launch reporting\")\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s [arguments] <data-path> \\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n}\n\nfunc setupLogging(loggingLevel, logFile string) {\n\tlevel := log.DEBUG\n\tswitch loggingLevel {\n\tcase \"TRACE\":\n\t\tlevel = log.TRACE\n\tcase \"DEBUG\":\n\t\tlevel = log.DEBUG\n\tcase \"INFO\":\n\t\tlevel = log.INFO\n\tcase \"WARN\":\n\t\tlevel = log.WARNING\n\tcase \"ERROR\":\n\t\tlevel = log.ERROR\n\t}\n\n\tlog.Global = make(map[string]*log.Filter)\n\n\tif logFile == \"stdout\" {\n\t\tflw := log.NewConsoleLogWriter()\n\t\tlog.AddFilter(\"stdout\", level, flw)\n\n\t} else {\n\t\tlogFileDir := filepath.Dir(logFile)\n\t\tos.MkdirAll(logFileDir, 0744)\n\n\t\tflw := log.NewFileLogWriter(logFile, false)\n\t\tlog.AddFilter(\"file\", level, flw)\n\n\t\tflw.SetFormat(\"[%D %T] [%L] (%S) %M\")\n\t\tflw.SetRotate(true)\n\t\tflw.SetRotateSize(0)\n\t\tflw.SetRotateLines(0)\n\t\tflw.SetRotateDaily(true)\n\t}\n\n\tlog.Info(\"Redirectoring logging to %s\", logFile)\n}\n\nfunc main() {\n\tflag.Parse()\n\n\t\/\/ Set up profiling, if requested.\n\tif cpuprofile != \"\" {\n\t\tlog.Info(\"Profiling enabled\")\n\t\tf, err := os.Create(cpuprofile)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Unable to create path: %s\", err.Error())\n\t\t}\n\t\tdefer f.Close()\n\n\t\tpprof.StartCPUProfile(f)\n\t\tdefer pprof.StopCPUProfile()\n\t}\n\tsetupLogging(logLevel, logFile)\n\n\t\/\/ Set the data directory.\n\tif flag.NArg() == 0 {\n\t\tflag.Usage()\n\t\tprintln(\"Data path argument required\")\n\t\tlog.Error(\"No data path supplied -- aborting\")\n\t\tos.Exit(1)\n\t}\n\tpath := flag.Arg(0)\n\tif err := os.MkdirAll(path, 0744); err != nil {\n\t\tlog.Error(\"Unable to create path: %s\", err.Error())\n\t}\n\n\ts := server.NewServer(path, dbfile, snapAfter, host, port)\n\tgo func() {\n\t\tlog.Error(s.ListenAndServe(join))\n\t}()\n\n\tif !disableReporting {\n\t\treportLaunch()\n\t}\n\n\tterminate := make(chan os.Signal, 1)\n\tsignal.Notify(terminate, os.Interrupt)\n\t<-terminate\n\tlog.Info(\"rqlite server stopped\")\n}\n\nfunc reportLaunch() {\n\tjson := fmt.Sprintf(`{\"os\": \"%s\", \"arch\": \"%s\", \"app\": \"rqlite\"}`, runtime.GOOS, runtime.GOARCH)\n\tdata := bytes.NewBufferString(json)\n\tclient := http.Client{Timeout: time.Duration(5 * time.Second)}\n\tgo client.Post(\"https:\/\/logs-01.loggly.com\/inputs\/8a0edd84-92ba-46e4-ada8-c529d0f105af\/tag\/reporting\/\",\n\t\t\"application\/json\", data)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/TykTechnologies\/goverify\"\n\t\"github.com\/TykTechnologies\/tykcommon\"\n\n\t\"archive\/zip\"\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto\/md5\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n)\n\n\/\/ tyk-cli <module> <submodule> <command> [--options] args...\n\nvar module, submodule, command string\n\nvar bundleOutput, privKey string\nvar forceInsecure *bool\n\nconst (\n\tdefaultBundleOutput = \"bundle.zip\"\n)\n\nfunc init() {\n\tif len(os.Args) == 1 {\n\t\tfmt.Println(\"No module specified!\")\n\t\tos.Exit(1)\n\t}\n\tif len(os.Args) == 2 {\n\t\tfmt.Println(\"No command specified!\")\n\t\tos.Exit(1)\n\t}\n\n\tmodule = os.Args[1]\n\tcommand = os.Args[2]\n\n\tos.Args = os.Args[2:]\n\n\tflag.StringVar(&bundleOutput, \"output\", \"\", \"Bundle output\")\n\tflag.StringVar(&privKey, \"key\", \"\", \"Key for bundle signature\")\n\tforceInsecure = flag.Bool(\"y\", false, \"Skip bundle signing\")\n\n\tflag.Parse()\n}\n\n\/\/ main is the entrypoint.\nfunc main() {\n\tfmt.Println(\"tyk-cli:\", flag.CommandLine, os.Args)\n\n\tfmt.Println(\"module =\", module)\n\tfmt.Println(\"command =\", command)\n\n\tvar err error\n\n\tswitch module {\n\tcase \"bundle\":\n\t\tfmt.Println(\"Using bundle module.\")\n\t\terr = bundle(command)\n\tdefault:\n\t\terr = errors.New(\"Invalid module\")\n\t}\n\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t\tos.Exit(1)\n\t}\n}\n\n\/\/ bundle will handle the bundle command calls.\nfunc bundle(command string) (err error) {\n\tswitch command {\n\tcase \"build\":\n\t\tvar manifestPath = \".\/manifest.json\"\n\t\tif _, err := os.Stat(manifestPath); err == nil {\n\t\t\tvar manifestData []byte\n\t\t\tmanifestData, err = ioutil.ReadFile(manifestPath)\n\n\t\t\tvar manifest tykcommon.BundleManifest\n\t\t\terr = json.Unmarshal(manifestData, &manifest)\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Couldn't parse manifest file!\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\terr = bundleValidateManifest(&manifest)\n\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Bundle validation error:\")\n\t\t\t\tfmt.Println(err)\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ The manifest is valid, we should do the checksum and sign step at this point.\n\t\t\tbundleBuild(&manifest)\n\n\t\t} else {\n\t\t\terr = errors.New(\"Manifest file doesn't exist.\")\n\t\t}\n\tdefault:\n\t\terr = errors.New(\"Invalid command.\")\n\t}\n\treturn err\n}\n\n\/\/ bundleValidateManifest will validate the manifest file before building a bundle.\nfunc bundleValidateManifest(manifest *tykcommon.BundleManifest) (err error) {\n\t\/\/ Validate manifest file list:\n\tfor _, file := range manifest.FileList {\n\t\tif _, statErr := os.Stat(file); statErr != nil {\n\t\t\terr = errors.New(\"Referencing a nonexistent file: \" + file)\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/ The custom middleware block must specify at least one hook:\n\tvar definedHooks int\n\tdefinedHooks = len(manifest.CustomMiddleware.Pre) + len(manifest.CustomMiddleware.Post) + len(manifest.CustomMiddleware.PostKeyAuth)\n\n\t\/\/ We should count the auth check middleware (single), if it's present:\n\tif manifest.CustomMiddleware.AuthCheck.Name != \"\" {\n\t\tdefinedHooks++\n\t}\n\n\tif definedHooks == 0 {\n\t\terr = errors.New(\"No hooks defined!\")\n\t\treturn err\n\t}\n\n\t\/\/ The custom middleware block must specify a driver:\n\tif manifest.CustomMiddleware.Driver == \"\" {\n\t\terr = errors.New(\"No driver specified!\")\n\t\treturn err\n\t}\n\n\treturn err\n}\n\n\/\/ bundleBuild will build and generate a bundle file.\nfunc bundleBuild(manifest *tykcommon.BundleManifest) (err error) {\n\tvar useSignature bool\n\n\tif bundleOutput == \"\" {\n\t\tfmt.Println(\"No output specified, using bundle.zip\")\n\t\tbundleOutput = defaultBundleOutput\n\t}\n\n\tif privKey != \"\" {\n\t\tfmt.Println(\"The bundle will be signed.\")\n\t\tuseSignature = true\n\t}\n\n\tvar bundleData bytes.Buffer\n\n\tfor _, file := range manifest.FileList {\n\t\tvar data []byte\n\t\tdata, err = ioutil.ReadFile(file)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"*** Error: \", err)\n\t\t\treturn err\n\t\t}\n\n\t\tbundleData.Write(data)\n\t}\n\n\t\/\/ Update the manifest file:\n\tmanifest.Checksum = fmt.Sprintf(\"%x\", md5.Sum(bundleData.Bytes()))\n\n\t\/\/ If a private key is specified, sign the data:\n\tif useSignature {\n\t\tvar signer goverify.Signer\n\t\tsigner, err = goverify.LoadPrivateKeyFromFile(privKey)\n\n\t\tif err != nil {\n\t\t\t\/\/ Error: Couldn't read the private key\n\t\t\treturn err\n\t\t}\n\t\tvar signed []byte\n\t\tsigned, err = signer.Sign(bundleData.Bytes())\n\n\t\tif err != nil {\n\t\t\t\/\/ Error: Couldn't sign the data.\n\t\t\treturn err\n\t\t}\n\n\t\tmanifest.Signature = base64.StdEncoding.EncodeToString(signed)\n\t} else {\n\t\tif *forceInsecure == false {\n\t\t\tfmt.Print(\"The bundle will be unsigned, type \\\"y\\\" to confirm: \")\n\t\t\treader := bufio.NewReader(os.Stdin)\n\t\t\ttext, _ := reader.ReadString('\\n')\n\t\t\tif text != \"y\\n\" {\n\t\t\t\tfmt.Println(\"Aborting\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}\n\n\tvar newManifestData []byte\n\tnewManifestData, err = json.Marshal(&manifest)\n\n\t\/\/ Write the bundle file:\n\tbuf := new(bytes.Buffer)\n\tbundleWriter := zip.NewWriter(buf)\n\n\tfor _, file := range manifest.FileList {\n\t\tvar outputFile io.Writer\n\t\toutputFile, err = bundleWriter.Create(file)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tvar data []byte\n\t\tdata, err = ioutil.ReadFile(file)\n\n\t\t_, err = outputFile.Write(data)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Write manifest file:\n\tvar newManifest io.Writer\n\tnewManifest, err = bundleWriter.Create(\"manifest.json\")\n\t_, err = newManifest.Write(newManifestData)\n\n\terr = bundleWriter.Close()\n\terr = ioutil.WriteFile(bundleOutput, buf.Bytes(), 0755)\n\n\treturn err\n}\n<commit_msg>tyk-85: better structure for the CLI commands.<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\tbundle \"github.com\/TykTechnologies\/tyk-cli\/bundle\"\n)\n\n\/\/ tyk-cli <module> <submodule> <command> [--options] args...\n\nvar module, submodule, command string\n\nvar bundleOutput, privKey string\nvar forceInsecure *bool\n\nfunc init() {\n\tif len(os.Args) == 1 {\n\t\tfmt.Println(\"No module specified!\")\n\t\tos.Exit(1)\n\t}\n\tif len(os.Args) == 2 {\n\t\tfmt.Println(\"No command specified!\")\n\t\tos.Exit(1)\n\t}\n\n\tmodule = os.Args[1]\n\tcommand = os.Args[2]\n\n\tos.Args = os.Args[2:]\n\n\tflag.StringVar(&bundleOutput, \"output\", \"\", \"Bundle output\")\n\tflag.StringVar(&privKey, \"key\", \"\", \"Key for bundle signature\")\n\tforceInsecure = flag.Bool(\"y\", false, \"Skip bundle signing\")\n\n\tflag.Parse()\n}\n\n\/\/ main is the entrypoint.\nfunc main() {\n\tfmt.Println(\"tyk-cli:\", flag.CommandLine, os.Args)\n\n\tfmt.Println(\"module =\", module)\n\tfmt.Println(\"command =\", command)\n\n\tvar err error\n\n\tswitch module {\n\tcase \"bundle\":\n\t\tfmt.Println(\"Using bundle module.\")\n\t\terr = bundle.Bundle(command, bundleOutput, privKey, forceInsecure)\n\tdefault:\n\t\terr = errors.New(\"Invalid module\")\n\t}\n\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\t\"time\"\n\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\n\t\"github.com\/rackerlabs\/libcarina\"\n)\n\nfunc writeCluster(w *tabwriter.Writer, cluster *libcarina.Cluster) {\n\ts := strings.Join([]string{cluster.ClusterName,\n\t\tcluster.Username,\n\t\tcluster.Flavor,\n\t\tcluster.Image,\n\t\tfmt.Sprintf(\"%v\", cluster.Nodes),\n\t\tcluster.Status}, \"\\t\")\n\tw.Write([]byte(s + \"\\n\"))\n}\n\nfunc writeCredentials(w *tabwriter.Writer, creds *libcarina.Credentials, pth string) (err error) {\n\t\/\/ TODO: Prompt when file already exists?\n\tfor fname, b := range creds.Files {\n\t\tp := path.Join(pth, fname)\n\t\terr = ioutil.WriteFile(p, b, 0600)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Application is, our, well, application\ntype Application struct {\n\t*Context\n\t*kingpin.Application\n}\n\n\/\/ Command is a command needing a ClusterClient\ntype Command struct {\n\t*Context\n\t*kingpin.CmdClause\n}\n\n\/\/ Context context for the  App\ntype Context struct {\n\tClusterClient *libcarina.ClusterClient\n\tTabWriter     *tabwriter.Writer\n\tUsername      string\n\tAPIKey        string\n\tEndpoint      string\n}\n\n\/\/ ClusterCommand is a Command with a ClusterName set\ntype ClusterCommand struct {\n\t*Command\n\tClusterName string\n}\n\n\/\/ CredentialsCommand keeps context about the download command\ntype CredentialsCommand struct {\n\t*ClusterCommand\n\tPath string\n}\n\n\/\/ CreateCommand keeps context about the create command\ntype CreateCommand struct {\n\t*ClusterCommand\n\n\tWait bool\n\n\t\/\/ Options passed along to Carina's API\n\tNodes     int\n\tAutoScale bool\n\n\t\/\/ TODO: See if setting flavor or image makes sense, even if the API takes it\n\t\/\/ Flavor    string\n\t\/\/ Image     string\n}\n\n\/\/ GrowCommand keeps context about the number of nodes to scale by\ntype GrowCommand struct {\n\t*ClusterCommand\n\tNodes int\n}\n\n\/\/ New creates a new Application\nfunc New() *Application {\n\n\tapp := kingpin.New(\"carina\", \"command line interface to launch and work with Docker Swarm clusters\")\n\n\tcap := new(Application)\n\tctx := new(Context)\n\n\tcap.Application = app\n\tcap.Context = ctx\n\n\tcap.PreAction(cap.Auth)\n\n\tcap.Flag(\"username\", \"Rackspace username - can also set env var RACKSPACE_USERNAME\").OverrideDefaultFromEnvar(\"RACKSPACE_USERNAME\").StringVar(&ctx.Username)\n\tcap.Flag(\"api-key\", \"Rackspace API Key - can also set env var RACKSPACE_APIKEY\").OverrideDefaultFromEnvar(\"RACKSPACE_APIKEY\").PlaceHolder(\"RACKSPACE_APIKEY\").StringVar(&ctx.APIKey)\n\tcap.Flag(\"endpoint\", \"Carina API endpoint\").Default(libcarina.BetaEndpoint).StringVar(&ctx.Endpoint)\n\n\twriter := new(tabwriter.Writer)\n\twriter.Init(os.Stdout, 0, 8, 1, '\\t', 0)\n\n\tctx.TabWriter = writer\n\n\tlistCommand := cap.NewCommand(ctx, \"list\", \"list swarm clusters\")\n\tlistCommand.Action(listCommand.List)\n\n\tgetCommand := cap.NewClusterCommand(ctx, \"get\", \"get information about a swarm cluster\")\n\tgetCommand.Action(getCommand.Get)\n\n\tdeleteCommand := cap.NewClusterCommand(ctx, \"delete\", \"delete a swarm cluster\")\n\tdeleteCommand.Action(deleteCommand.Delete)\n\n\tcreateCommand := new(CreateCommand)\n\tcreateCommand.ClusterCommand = cap.NewClusterCommand(ctx, \"create\", \"create a swarm cluster\")\n\tcreateCommand.Flag(\"wait\", \"wait for swarm cluster completion\").BoolVar(&createCommand.Wait)\n\tcreateCommand.Flag(\"nodes\", \"number of nodes for the initial cluster\").Default(\"1\").IntVar(&createCommand.Nodes)\n\tcreateCommand.Flag(\"autoscale\", \"whether autoscale is on or off\").BoolVar(&createCommand.AutoScale)\n\tcreateCommand.Action(createCommand.Create)\n\n\tcredentialsCommand := new(CredentialsCommand)\n\tcredentialsCommand.ClusterCommand = cap.NewClusterCommand(ctx, \"credentials\", \"download credentials\")\n\tcredentialsCommand.Flag(\"path\", \"path to write credentials out to\").StringVar(&credentialsCommand.Path)\n\tcredentialsCommand.Action(credentialsCommand.Download)\n\n\tgrowCommand := new(GrowCommand)\n\tgrowCommand.ClusterCommand = cap.NewClusterCommand(ctx, \"grow\", \"Grow a cluster by the requested number of nodes\")\n\tgrowCommand.Flag(\"nodes\", \"number of nodes to increase the cluster by\").Required().IntVar(&growCommand.Nodes)\n\tgrowCommand.Action(growCommand.Grow)\n\n\treturn cap\n}\n\n\/\/ NewCommand creates a command that relies on Auth\nfunc (app *Application) NewCommand(ctx *Context, name, help string) *Command {\n\tcarina := new(Command)\n\tcarina.Context = ctx\n\tcarina.CmdClause = app.Command(name, help)\n\treturn carina\n}\n\n\/\/ NewClusterCommand is a command that uses a cluster name\nfunc (app *Application) NewClusterCommand(ctx *Context, name, help string) *ClusterCommand {\n\tcc := new(ClusterCommand)\n\tcc.Command = app.NewCommand(ctx, name, help)\n\tcc.Arg(\"cluster-name\", \"name of the cluster\").Required().StringVar(&cc.ClusterName)\n\treturn cc\n}\n\n\/\/ Auth does the authentication\nfunc (app *Application) Auth(pc *kingpin.ParseContext) (err error) {\n\tcarina := app.Context\n\tcarina.ClusterClient, err = libcarina.NewClusterClient(carina.Endpoint, carina.Username, carina.APIKey)\n\treturn err\n}\n\n\/\/ List the current swarm clusters\nfunc (carina *Command) List(pc *kingpin.ParseContext) (err error) {\n\tclusterList, err := carina.ClusterClient.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\theaderFields := []string{\n\t\t\"ClusterName\",\n\t\t\"Username\",\n\t\t\"Flavor\",\n\t\t\"Image\",\n\t\t\"Nodes\",\n\t\t\"Status\",\n\t}\n\ts := strings.Join(headerFields, \"\\t\")\n\n\tcarina.TabWriter.Write([]byte(s + \"\\n\"))\n\n\tfor _, cluster := range clusterList {\n\t\twriteCluster(carina.TabWriter, &cluster)\n\t}\n\tcarina.TabWriter.Flush()\n\n\treturn nil\n}\n\n\/\/ Get an individual cluster\nfunc (carina *ClusterCommand) Get(pc *kingpin.ParseContext) (err error) {\n\tcluster, err := carina.ClusterClient.Get(carina.ClusterName)\n\tif err == nil {\n\t\twriteCluster(carina.TabWriter, cluster)\n\t}\n\tcarina.TabWriter.Flush()\n\treturn err\n}\n\n\/\/ Delete a cluster\nfunc (carina *ClusterCommand) Delete(pc *kingpin.ParseContext) (err error) {\n\tcluster, err := carina.ClusterClient.Delete(carina.ClusterName)\n\tif err == nil {\n\t\twriteCluster(carina.TabWriter, cluster)\n\t}\n\tcarina.TabWriter.Flush()\n\treturn err\n}\n\n\/\/ Create a cluster\nfunc (carina *CreateCommand) Create(pc *kingpin.ParseContext) (err error) {\n\tif carina.Nodes < 1 {\n\t\treturn errors.New(\"nodes must be >= 1\")\n\t}\n\n\tnodes := libcarina.Number(carina.Nodes)\n\n\tc := libcarina.Cluster{\n\t\tClusterName: carina.ClusterName,\n\t\tNodes:       nodes,\n\t\tAutoScale:   carina.AutoScale,\n\t}\n\n\tcluster, err := carina.ClusterClient.Create(c)\n\n\t\/\/ Transitions past point of \"new\" or \"building\" are assumed to be states we\n\t\/\/ can stop on.\n\tif carina.Wait {\n\t\tfor cluster.Status == \"new\" || cluster.Status == \"building\" {\n\t\t\ttime.Sleep(13 * time.Second)\n\t\t\tcluster, err = carina.ClusterClient.Get(carina.ClusterName)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif err == nil {\n\t\twriteCluster(carina.TabWriter, cluster)\n\t}\n\tcarina.TabWriter.Flush()\n\treturn err\n}\n\n\/\/ Grow increase the size of the given cluster\nfunc (carina *GrowCommand) Grow(pc *kingpin.ParseContext) (err error) {\n\tcluster, err := carina.ClusterClient.Grow(carina.ClusterName, carina.Nodes)\n\tif err == nil {\n\t\twriteCluster(carina.TabWriter, cluster)\n\t}\n\tcarina.TabWriter.Flush()\n\treturn err\n}\n\n\/\/ Download credentials for a cluster\nfunc (carina *CredentialsCommand) Download(pc *kingpin.ParseContext) (err error) {\n\tcredentials, err := carina.ClusterClient.GetCredentials(carina.ClusterName)\n\n\tp := path.Clean(carina.Path)\n\n\tif p != \".\" {\n\t\tos.MkdirAll(p, 0777)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twriteCredentials(carina.TabWriter, credentials, p)\n\t\/\/ TODO: Handle Windows conditionally\n\tfmt.Fprintf(os.Stdout, \"source \\\"%v\\\"\\n\", path.Join(p, \"docker.env\"))\n\tfmt.Fprintf(os.Stdout, \"# Run the above or eval a subshell with your arguments to %v\\n\", os.Args[0])\n\tfmt.Fprintf(os.Stdout, \"# eval \\\"$( %v command... )\\\" \\n\", os.Args[0])\n\n\tcarina.TabWriter.Flush()\n\treturn err\n}\n\nfunc main() {\n\tapp := New()\n\tkingpin.MustParse(app.Parse(os.Args[1:]))\n}\n<commit_msg>Provide different instructions for Windows users.<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\t\"time\"\n\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\n\t\"github.com\/rackerlabs\/libcarina\"\n)\n\nfunc writeCluster(w *tabwriter.Writer, cluster *libcarina.Cluster) {\n\ts := strings.Join([]string{cluster.ClusterName,\n\t\tcluster.Username,\n\t\tcluster.Flavor,\n\t\tcluster.Image,\n\t\tfmt.Sprintf(\"%v\", cluster.Nodes),\n\t\tcluster.Status}, \"\\t\")\n\tw.Write([]byte(s + \"\\n\"))\n}\n\nfunc writeCredentials(w *tabwriter.Writer, creds *libcarina.Credentials, pth string) (err error) {\n\t\/\/ TODO: Prompt when file already exists?\n\tfor fname, b := range creds.Files {\n\t\tp := path.Join(pth, fname)\n\t\terr = ioutil.WriteFile(p, b, 0600)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Application is, our, well, application\ntype Application struct {\n\t*Context\n\t*kingpin.Application\n}\n\n\/\/ Command is a command needing a ClusterClient\ntype Command struct {\n\t*Context\n\t*kingpin.CmdClause\n}\n\n\/\/ Context context for the  App\ntype Context struct {\n\tClusterClient *libcarina.ClusterClient\n\tTabWriter     *tabwriter.Writer\n\tUsername      string\n\tAPIKey        string\n\tEndpoint      string\n}\n\n\/\/ ClusterCommand is a Command with a ClusterName set\ntype ClusterCommand struct {\n\t*Command\n\tClusterName string\n}\n\n\/\/ CredentialsCommand keeps context about the download command\ntype CredentialsCommand struct {\n\t*ClusterCommand\n\tPath string\n}\n\n\/\/ CreateCommand keeps context about the create command\ntype CreateCommand struct {\n\t*ClusterCommand\n\n\tWait bool\n\n\t\/\/ Options passed along to Carina's API\n\tNodes     int\n\tAutoScale bool\n\n\t\/\/ TODO: See if setting flavor or image makes sense, even if the API takes it\n\t\/\/ Flavor    string\n\t\/\/ Image     string\n}\n\n\/\/ GrowCommand keeps context about the number of nodes to scale by\ntype GrowCommand struct {\n\t*ClusterCommand\n\tNodes int\n}\n\n\/\/ New creates a new Application\nfunc New() *Application {\n\n\tapp := kingpin.New(\"carina\", \"command line interface to launch and work with Docker Swarm clusters\")\n\n\tcap := new(Application)\n\tctx := new(Context)\n\n\tcap.Application = app\n\tcap.Context = ctx\n\n\tcap.PreAction(cap.Auth)\n\n\tcap.Flag(\"username\", \"Rackspace username - can also set env var RACKSPACE_USERNAME\").OverrideDefaultFromEnvar(\"RACKSPACE_USERNAME\").StringVar(&ctx.Username)\n\tcap.Flag(\"api-key\", \"Rackspace API Key - can also set env var RACKSPACE_APIKEY\").OverrideDefaultFromEnvar(\"RACKSPACE_APIKEY\").PlaceHolder(\"RACKSPACE_APIKEY\").StringVar(&ctx.APIKey)\n\tcap.Flag(\"endpoint\", \"Carina API endpoint\").Default(libcarina.BetaEndpoint).StringVar(&ctx.Endpoint)\n\n\twriter := new(tabwriter.Writer)\n\twriter.Init(os.Stdout, 0, 8, 1, '\\t', 0)\n\n\tctx.TabWriter = writer\n\n\tlistCommand := cap.NewCommand(ctx, \"list\", \"list swarm clusters\")\n\tlistCommand.Action(listCommand.List)\n\n\tgetCommand := cap.NewClusterCommand(ctx, \"get\", \"get information about a swarm cluster\")\n\tgetCommand.Action(getCommand.Get)\n\n\tdeleteCommand := cap.NewClusterCommand(ctx, \"delete\", \"delete a swarm cluster\")\n\tdeleteCommand.Action(deleteCommand.Delete)\n\n\tcreateCommand := new(CreateCommand)\n\tcreateCommand.ClusterCommand = cap.NewClusterCommand(ctx, \"create\", \"create a swarm cluster\")\n\tcreateCommand.Flag(\"wait\", \"wait for swarm cluster completion\").BoolVar(&createCommand.Wait)\n\tcreateCommand.Flag(\"nodes\", \"number of nodes for the initial cluster\").Default(\"1\").IntVar(&createCommand.Nodes)\n\tcreateCommand.Flag(\"autoscale\", \"whether autoscale is on or off\").BoolVar(&createCommand.AutoScale)\n\tcreateCommand.Action(createCommand.Create)\n\n\tcredentialsCommand := new(CredentialsCommand)\n\tcredentialsCommand.ClusterCommand = cap.NewClusterCommand(ctx, \"credentials\", \"download credentials\")\n\tcredentialsCommand.Flag(\"path\", \"path to write credentials out to\").StringVar(&credentialsCommand.Path)\n\tcredentialsCommand.Action(credentialsCommand.Download)\n\n\tgrowCommand := new(GrowCommand)\n\tgrowCommand.ClusterCommand = cap.NewClusterCommand(ctx, \"grow\", \"Grow a cluster by the requested number of nodes\")\n\tgrowCommand.Flag(\"nodes\", \"number of nodes to increase the cluster by\").Required().IntVar(&growCommand.Nodes)\n\tgrowCommand.Action(growCommand.Grow)\n\n\treturn cap\n}\n\n\/\/ NewCommand creates a command that relies on Auth\nfunc (app *Application) NewCommand(ctx *Context, name, help string) *Command {\n\tcarina := new(Command)\n\tcarina.Context = ctx\n\tcarina.CmdClause = app.Command(name, help)\n\treturn carina\n}\n\n\/\/ NewClusterCommand is a command that uses a cluster name\nfunc (app *Application) NewClusterCommand(ctx *Context, name, help string) *ClusterCommand {\n\tcc := new(ClusterCommand)\n\tcc.Command = app.NewCommand(ctx, name, help)\n\tcc.Arg(\"cluster-name\", \"name of the cluster\").Required().StringVar(&cc.ClusterName)\n\treturn cc\n}\n\n\/\/ Auth does the authentication\nfunc (app *Application) Auth(pc *kingpin.ParseContext) (err error) {\n\tcarina := app.Context\n\tcarina.ClusterClient, err = libcarina.NewClusterClient(carina.Endpoint, carina.Username, carina.APIKey)\n\treturn err\n}\n\n\/\/ List the current swarm clusters\nfunc (carina *Command) List(pc *kingpin.ParseContext) (err error) {\n\tclusterList, err := carina.ClusterClient.List()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\theaderFields := []string{\n\t\t\"ClusterName\",\n\t\t\"Username\",\n\t\t\"Flavor\",\n\t\t\"Image\",\n\t\t\"Nodes\",\n\t\t\"Status\",\n\t}\n\ts := strings.Join(headerFields, \"\\t\")\n\n\tcarina.TabWriter.Write([]byte(s + \"\\n\"))\n\n\tfor _, cluster := range clusterList {\n\t\twriteCluster(carina.TabWriter, &cluster)\n\t}\n\tcarina.TabWriter.Flush()\n\n\treturn nil\n}\n\n\/\/ Get an individual cluster\nfunc (carina *ClusterCommand) Get(pc *kingpin.ParseContext) (err error) {\n\tcluster, err := carina.ClusterClient.Get(carina.ClusterName)\n\tif err == nil {\n\t\twriteCluster(carina.TabWriter, cluster)\n\t}\n\tcarina.TabWriter.Flush()\n\treturn err\n}\n\n\/\/ Delete a cluster\nfunc (carina *ClusterCommand) Delete(pc *kingpin.ParseContext) (err error) {\n\tcluster, err := carina.ClusterClient.Delete(carina.ClusterName)\n\tif err == nil {\n\t\twriteCluster(carina.TabWriter, cluster)\n\t}\n\tcarina.TabWriter.Flush()\n\treturn err\n}\n\n\/\/ Create a cluster\nfunc (carina *CreateCommand) Create(pc *kingpin.ParseContext) (err error) {\n\tif carina.Nodes < 1 {\n\t\treturn errors.New(\"nodes must be >= 1\")\n\t}\n\n\tnodes := libcarina.Number(carina.Nodes)\n\n\tc := libcarina.Cluster{\n\t\tClusterName: carina.ClusterName,\n\t\tNodes:       nodes,\n\t\tAutoScale:   carina.AutoScale,\n\t}\n\n\tcluster, err := carina.ClusterClient.Create(c)\n\n\t\/\/ Transitions past point of \"new\" or \"building\" are assumed to be states we\n\t\/\/ can stop on.\n\tif carina.Wait {\n\t\tfor cluster.Status == \"new\" || cluster.Status == \"building\" {\n\t\t\ttime.Sleep(13 * time.Second)\n\t\t\tcluster, err = carina.ClusterClient.Get(carina.ClusterName)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif err == nil {\n\t\twriteCluster(carina.TabWriter, cluster)\n\t}\n\tcarina.TabWriter.Flush()\n\treturn err\n}\n\n\/\/ Grow increase the size of the given cluster\nfunc (carina *GrowCommand) Grow(pc *kingpin.ParseContext) (err error) {\n\tcluster, err := carina.ClusterClient.Grow(carina.ClusterName, carina.Nodes)\n\tif err == nil {\n\t\twriteCluster(carina.TabWriter, cluster)\n\t}\n\tcarina.TabWriter.Flush()\n\treturn err\n}\n\n\/\/ Download credentials for a cluster\nfunc (carina *CredentialsCommand) Download(pc *kingpin.ParseContext) (err error) {\n\tcredentials, err := carina.ClusterClient.GetCredentials(carina.ClusterName)\n\n\tp := path.Clean(carina.Path)\n\n\tif p != \".\" {\n\t\tos.MkdirAll(p, 0777)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twriteCredentials(carina.TabWriter, credentials, p)\n\n\tif runtime.GOOS == \"windows\" {\n\t\tfmt.Fprintf(os.Stdout, \"\\\"%v\\\"\\n\", path.Join(p, \"docker.cmd\"))\n\t\tfmt.Fprintf(os.Stdout, \"# Run the above to set your docker environment\\n\")\n\t} else {\n\t\tfmt.Fprintf(os.Stdout, \"source \\\"%v\\\"\\n\", path.Join(p, \"docker.env\"))\n\t\tfmt.Fprintf(os.Stdout, \"# Run the above or eval a subshell with your arguments to %v\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stdout, \"# eval \\\"$( %v command... )\\\" \\n\", os.Args[0])\n\t}\n\n\tcarina.TabWriter.Flush()\n\treturn err\n}\n\nfunc main() {\n\tapp := New()\n\tkingpin.MustParse(app.Parse(os.Args[1:]))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"container\/ring\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n)\n\nfunc main() {\n\tring := ring.New(10)\n\n\tticker := time.NewTicker(10 * time.Second)\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tlog.Println(\"ping google.com -c 5\")\n\t\t\tres, err := ping(\"google.com\", 5)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tring.Value = res\n\t\t\tring.Next()\n\t\t\tlog.Printf(\"Time: %v\\n\", res.Time)\n\t\t\tlog.Printf(\"Min: %f ms\\n\", res.Min)\n\t\t\tlog.Printf(\"Avg: %f ms\\n\", res.Avg)\n\t\t\tlog.Printf(\"Max: %f ms\\n\", res.Max)\n\t\t\tlog.Printf(\"Mdev: %f ms\\n\", res.Mdev)\n\t\t}\n\t}()\n\n\tch := make(chan os.Signal)\n\tsignal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)\n\tlog.Printf(\"Received signal: %v\\n\", <-ch)\n\tlog.Println(\"Shutting down\")\n\tticker.Stop()\n}\n<commit_msg>Don't kill process if ping errors<commit_after>package main\n\nimport (\n\t\"container\/ring\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n)\n\nfunc main() {\n\tring := ring.New(10)\n\n\tticker := time.NewTicker(10 * time.Second)\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tlog.Println(\"ping google.com -c 5\")\n\t\t\tres, err := ping(\"google.com\", 5)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error from ping: %v\\n\", err)\n\t\t\t} else {\n\t\t\t\tring.Value = res\n\t\t\t\tring.Next()\n\t\t\t\tlog.Printf(\"Time: %v\\n\", res.Time)\n\t\t\t\tlog.Printf(\"Min: %f ms\\n\", res.Min)\n\t\t\t\tlog.Printf(\"Avg: %f ms\\n\", res.Avg)\n\t\t\t\tlog.Printf(\"Max: %f ms\\n\", res.Max)\n\t\t\t\tlog.Printf(\"Mdev: %f ms\\n\", res.Mdev)\n\t\t\t}\n\t\t}\n\t}()\n\n\tch := make(chan os.Signal)\n\tsignal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)\n\tlog.Printf(\"Received signal: %v\\n\", <-ch)\n\tlog.Println(\"Shutting down\")\n\tticker.Stop()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\nfunc init() {\n\truntime.GOMAXPROCS(1)\n\truntime.LockOSThread()\n}\n\nconst Version = \"0.1.0\"\n\nfunc main() {\n\tlog.SetFlags(0)\n\n\tif len(os.Args) < 2 {\n\t\tlog.Println(\"!! no command to run\")\n\t\tlog.Printf(\"usage: %s [command]\", os.Args[0])\n\t\tlog.Println()\n\t\tlog.Printf(\"%s version: %s (%s on %s\/%s; %s)\", os.Args[0], Version, runtime.Version(), runtime.GOOS, runtime.GOARCH, runtime.Compiler)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ first, test to make sure the nginx config is valid, if not error early so we can see the error\n\ttest := exec.Command(\"nginx\", \"-t\")\n\ttest.Stdout = os.Stdout\n\ttest.Stderr = os.Stderr\n\tif err := test.Run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ next, spawn our child process and follow it's std{err,out}\n\tchild := exec.Command(os.Args[1], os.Args[2:]...)\n\tchild.Stdout = os.Stdout\n\tchild.Stderr = os.Stderr\n\tif err := child.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ lastly spawn nginx, but we don't care about it's std{err,out}\n\tnginx := exec.Command(\"nginx\", \"-g\", \"daemon off;\")\n\tif err := nginx.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ wait for either of the processes to exit\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tchild.Wait()\n\t\tdone <- struct{}{}\n\t}()\n\tgo func() {\n\t\tnginx.Wait()\n\t\tdone <- struct{}{}\n\t}()\n\n\t\/\/ intercept our signals\n\tsignals := make(chan os.Signal, 1)\n\tsignal.Notify(signals)\n\tgo func() {\n\t\tfor sig := range signals {\n\t\t\tif sig == syscall.SIGTERM {\n\t\t\t\t\/\/ `docker stop` sends a SIGTERM, but we want to incercept and convert to SIGQUIT\n\t\t\t\t\/\/ because nginx will gracefully exit with SIGQUIT.\n\t\t\t\tnginx.Process.Signal(syscall.SIGQUIT)\n\t\t\t} else {\n\t\t\t\tchild.Process.Signal(sig)\n\t\t\t}\n\t\t}\n\t}()\n\t<-done\n\t\/\/ shut down\n\tchild.Process.Signal(syscall.SIGTERM)\n\tnginx.Process.Signal(syscall.SIGTERM)\n\tchild.Wait()\n\tnginx.Wait()\n}\n<commit_msg>0.1.1<commit_after>package main\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"syscall\"\n)\n\nfunc init() {\n\truntime.GOMAXPROCS(1)\n\truntime.LockOSThread()\n}\n\nconst Version = \"0.1.1\"\n\nfunc main() {\n\tlog.SetFlags(0)\n\n\tif len(os.Args) < 2 {\n\t\tlog.Println(\"!! no command to run\")\n\t\tlog.Printf(\"usage: %s [command]\", os.Args[0])\n\t\tlog.Println()\n\t\tlog.Printf(\"%s version: %s (%s on %s\/%s; %s)\", os.Args[0], Version, runtime.Version(), runtime.GOOS, runtime.GOARCH, runtime.Compiler)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ first, test to make sure the nginx config is valid, if not error early so we can see the error\n\ttest := exec.Command(\"nginx\", \"-t\")\n\ttest.Stdout = os.Stdout\n\ttest.Stderr = os.Stderr\n\tif err := test.Run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ next, spawn our child process and follow it's std{err,out}\n\tchild := exec.Command(os.Args[1], os.Args[2:]...)\n\tchild.Stdout = os.Stdout\n\tchild.Stderr = os.Stderr\n\tif err := child.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ lastly spawn nginx, but we don't care about it's std{err,out}\n\tnginx := exec.Command(\"nginx\", \"-g\", \"daemon off;\")\n\tif err := nginx.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ wait for either of the processes to exit\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tchild.Wait()\n\t\tdone <- struct{}{}\n\t}()\n\tgo func() {\n\t\tnginx.Wait()\n\t\tdone <- struct{}{}\n\t}()\n\n\t\/\/ intercept our signals\n\tsignals := make(chan os.Signal, 1)\n\tsignal.Notify(signals)\n\tgo func() {\n\t\tfor sig := range signals {\n\t\t\tif sig == syscall.SIGTERM {\n\t\t\t\t\/\/ `docker stop` sends a SIGTERM, but we want to incercept and convert to SIGQUIT\n\t\t\t\t\/\/ because nginx will gracefully exit with SIGQUIT.\n\t\t\t\tnginx.Process.Signal(syscall.SIGQUIT)\n\t\t\t} else {\n\t\t\t\tchild.Process.Signal(sig)\n\t\t\t}\n\t\t}\n\t}()\n\t<-done\n\t\/\/ shut down\n\tchild.Process.Signal(syscall.SIGTERM)\n\tnginx.Process.Signal(syscall.SIGTERM)\n\tchild.Wait()\n\tnginx.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/xml\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"golang.org\/x\/tools\/blog\/atom\"\n\n\t\"github.com\/ChimeraCoder\/anaconda\"\n\t\"github.com\/joho\/godotenv\"\n)\n\nconst (\n\tMaxStatuses = 200\n\tMaxEntries  = 100\n)\n\ntype atomEntryArray []*atom.Entry\n\nfunc (a atomEntryArray) Len() int {\n\treturn len(a)\n}\n\nfunc (a atomEntryArray) Less(i, j int) bool {\n\tit, err := time.Parse(time.RFC3339, string(a[i].Updated))\n\tif err != nil {\n\t\treturn false\n\t}\n\tjt, err := time.Parse(time.RFC3339, string(a[j].Updated))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn it.After(jt)\n}\n\nfunc (a atomEntryArray) Swap(i, j int) {\n\ta[i], a[j] = a[j], a[i]\n}\n\nfunc main() {\n\tlog.SetFlags(log.Lshortfile)\n\n\tif len(os.Args) > 0 {\n\t\tif err := godotenv.Load(os.Args...); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tanaconda.SetConsumerKey(os.Getenv(\"TWITTER_CONSUMER_KEY\"))\n\tanaconda.SetConsumerSecret(os.Getenv(\"TWITTER_CONSUMER_SECRET\"))\n\n\tapi := anaconda.NewTwitterApi(os.Getenv(\"TWITTER_OAUTH_TOKEN\"), os.Getenv(\"TWITTER_OAUTH_TOKEN_SECRET\"))\n\tdefer api.Close()\n\n\tfeedUrl := os.Getenv(\"FEED_URL\")\n\tif feedUrl == \"\" {\n\t\tlog.Fatal(\"FEED_URL is required.\")\n\t}\n\ttemplate := os.Getenv(\"TEMPLATE\")\n\tif template == \"\" {\n\t\tlog.Fatal(\"TEMPLATE is required.\")\n\t}\n\n\tuserId := strings.SplitN(os.Getenv(\"TWITTER_OAUTH_TOKEN\"), \"-\", 2)[0]\n\tif _, err := strconv.ParseInt(userId, 10, 64); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trecentUrls := make(map[string]struct{})\n\t{\n\t\tv := url.Values{}\n\t\tv.Set(\"user_id\", userId)\n\t\tv.Set(\"count\", strconv.Itoa(MaxStatuses))\n\t\ttimeline, err := api.GetUserTimeline(v)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfor _, status := range timeline {\n\t\t\tfor _, url := range status.Entities.Urls {\n\t\t\t\trecentUrls[url.Expanded_url] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar atom atom.Feed\n\t{\n\t\tresp, err := http.Get(feedUrl)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tif err := xml.Unmarshal(body, &atom); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t}\n\n\t{\n\t\tentries := atomEntryArray(atom.Entry)\n\t\tsort.Sort(entries)\n\t\tslice := entries[0:MaxEntries]\n\t\tsort.Sort(sort.Reverse(atomEntryArray(slice)))\n\tentries:\n\t\tfor _, entry := range slice {\n\t\t\tif len(entry.Link) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlink := entry.Link[0]\n\t\t\tif _, ok := recentUrls[link.Href]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treplacer := strings.NewReplacer(\"{title}\", entry.Title, \"{url}\", link.Href)\n\t\t\ttext := replacer.Replace(template)\n\t\t\t_, err := api.PostTweet(text, url.Values{})\n\t\t\tif err != nil {\n\t\t\t\tif apiErr, ok := err.(*anaconda.ApiError); ok {\n\t\t\t\t\tfor _, err := range apiErr.Decoded.Errors {\n\t\t\t\t\t\tif err.Code == anaconda.TwitterErrorStatusIsADuplicate {\n\t\t\t\t\t\t\tcontinue entries\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlog.Fatal(apiErr)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Reduce sorting<commit_after>package main\n\nimport (\n\t\"encoding\/xml\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"golang.org\/x\/tools\/blog\/atom\"\n\n\t\"github.com\/ChimeraCoder\/anaconda\"\n\t\"github.com\/joho\/godotenv\"\n)\n\nconst (\n\tMaxStatuses = 200\n\tMaxEntries  = 100\n)\n\ntype atomEntryArray []*atom.Entry\n\nfunc (a atomEntryArray) Len() int {\n\treturn len(a)\n}\n\nfunc (a atomEntryArray) Less(i, j int) bool {\n\tit, err := time.Parse(time.RFC3339, string(a[i].Updated))\n\tif err != nil {\n\t\treturn false\n\t}\n\tjt, err := time.Parse(time.RFC3339, string(a[j].Updated))\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn it.After(jt)\n}\n\nfunc (a atomEntryArray) Swap(i, j int) {\n\ta[i], a[j] = a[j], a[i]\n}\n\nfunc main() {\n\tlog.SetFlags(log.Lshortfile)\n\n\tif len(os.Args) > 0 {\n\t\tif err := godotenv.Load(os.Args...); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tanaconda.SetConsumerKey(os.Getenv(\"TWITTER_CONSUMER_KEY\"))\n\tanaconda.SetConsumerSecret(os.Getenv(\"TWITTER_CONSUMER_SECRET\"))\n\n\tapi := anaconda.NewTwitterApi(os.Getenv(\"TWITTER_OAUTH_TOKEN\"), os.Getenv(\"TWITTER_OAUTH_TOKEN_SECRET\"))\n\tdefer api.Close()\n\n\tfeedUrl := os.Getenv(\"FEED_URL\")\n\tif feedUrl == \"\" {\n\t\tlog.Fatal(\"FEED_URL is required.\")\n\t}\n\ttemplate := os.Getenv(\"TEMPLATE\")\n\tif template == \"\" {\n\t\tlog.Fatal(\"TEMPLATE is required.\")\n\t}\n\n\tuserId := strings.SplitN(os.Getenv(\"TWITTER_OAUTH_TOKEN\"), \"-\", 2)[0]\n\tif _, err := strconv.ParseInt(userId, 10, 64); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\trecentUrls := make(map[string]struct{})\n\t{\n\t\tv := url.Values{}\n\t\tv.Set(\"user_id\", userId)\n\t\tv.Set(\"count\", strconv.Itoa(MaxStatuses))\n\t\ttimeline, err := api.GetUserTimeline(v)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tfor _, status := range timeline {\n\t\t\tfor _, url := range status.Entities.Urls {\n\t\t\t\trecentUrls[url.Expanded_url] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\n\tvar atom atom.Feed\n\t{\n\t\tresp, err := http.Get(feedUrl)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tif err := xml.Unmarshal(body, &atom); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t}\n\n\t{\n\t\tentries := atomEntryArray(atom.Entry)\n\t\tsort.Sort(sort.Reverse(entries))\n\t\tn := len(entries) - MaxEntries\n\t\tif n < 0 {\n\t\t\tn = 0\n\t\t}\n\tentries:\n\t\tfor _, entry := range entries[n:] {\n\t\t\tif len(entry.Link) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlink := entry.Link[0]\n\t\t\tif _, ok := recentUrls[link.Href]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treplacer := strings.NewReplacer(\"{title}\", entry.Title, \"{url}\", link.Href)\n\t\t\ttext := replacer.Replace(template)\n\t\t\t_, err := api.PostTweet(text, url.Values{})\n\t\t\tif err != nil {\n\t\t\t\tif apiErr, ok := err.(*anaconda.ApiError); ok {\n\t\t\t\t\tfor _, err := range apiErr.Decoded.Errors {\n\t\t\t\t\t\tif err.Code == anaconda.TwitterErrorStatusIsADuplicate {\n\t\t\t\t\t\t\tcontinue entries\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlog.Fatal(apiErr)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"net\"\n\tnurl \"net\/url\"\n\t\"time\"\n\n\t\/\/ third-party dependencies\n\n\tpq \"github.com\/bmizerany\/pq\"\n\t\"github.com\/monnand\/goredis\"\n\n\t\/\/ local packages\n\t\"github.com\/lincolnloop\/botbot-bot\/common\"\n\t\"github.com\/lincolnloop\/botbot-bot\/dispatch\"\n\t\"github.com\/lincolnloop\/botbot-bot\/line\"\n\t\"github.com\/lincolnloop\/botbot-bot\/network\"\n\t\"github.com\/lincolnloop\/botbot-bot\/user\"\n\n\t\/\/ stdlib package\n\t\"database\/sql\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nfunc main() {\n\n\tlog.Println(\"START. Use 'botbot -help' for command line options.\")\n\n\tstorage := NewPostgresStorage()\n\tdefer storage.Close()\n\tredisUrlString := os.Getenv(\"REDIS_PLUGIN_QUEUE_URL\")\n\tif redisUrlString == \"\" {\n\t\tredisUrlString = \"redis:\/\/localhost:6379\/0\"\n\t}\n\tredisUrl, err := nurl.Parse(redisUrlString)\n\tif err != nil {\n\t\tlog.Fatal(\"Could not read Redis string\", err)\n\t}\n\tredisQueue := goredis.Client{Addr: redisUrl.Host}\n\tqueue := newReliableQueue(&redisQueue)\n\n\tbotbot := NewBotBot(storage, queue)\n\n\t\/\/ Listen for incoming commands\n\tgo botbot.listen(redisUrl.Path[1:])\n\n\t\/\/ Start the main loop\n\tgo botbot.mainLoop()\n\n\t\/\/ Trap stop signal (Ctrl-C, kill) to exit\n\tkill := make(chan os.Signal)\n\tsignal.Notify(kill, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM)\n\n\t\/\/ Wait for stop signal\n\tfor {\n\t\t<-kill\n\t\tlog.Println(\"Graceful shutdown\")\n\t\tbotbot.shutdown()\n\t\tbreak\n\t}\n\n\tlog.Println(\"Bye\")\n}\n\n\/*\n * BOTBOT - the main object\n *\/\n\ntype BotBot struct {\n\tnetMan     *network.NetworkManager\n\tdis        *dispatch.Dispatcher\n\tusers      *user.UserManager\n\tstorage    common.Storage\n\tqueue      common.Queue\n\tfromServer chan *line.Line\n\tfromBus    chan string\n}\n\nfunc NewBotBot(storage common.Storage, queue common.Queue) *BotBot {\n\n\tfromServer := make(chan *line.Line)\n\tfromBus := make(chan string)\n\n\tnetMan := network.NewNetworkManager(storage, fromServer)\n\tnetMan.RefreshChatbots()\n\tgo netMan.MonitorChatbots()\n\n\tdis := dispatch.NewDispatcher(queue)\n\n\tusers := user.NewUserManager()\n\n\treturn &BotBot{\n\t\tnetMan:     netMan,\n\t\tdis:        dis,\n\t\tusers:      users,\n\t\tqueue:      queue,\n\t\tstorage:    storage,\n\t\tfromServer: fromServer,\n\t\tfromBus:    fromBus}\n}\n\n\/\/ Listen for incoming commands\nfunc (self *BotBot) listen(queueName string) {\n\n\tvar msg []byte\n\tvar err error\n\n\tfor {\n\t\t_, msg, err = self.queue.Blpop([]string{queueName}, 0)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error reading (BLPOP) from queue. \", err)\n\t\t}\n\t\tif len(msg) != 0 {\n\t\t\tlog.Println(\"Command: \", string(msg))\n\t\t\tself.fromBus <- string(msg)\n\t\t}\n\t}\n}\n\nfunc (self *BotBot) mainLoop() {\n\n\tgo self.recordUserCounts()\n\n\tvar busCommand string\n\tvar args string\n\tfor {\n\t\tselect {\n\n\t\tcase serverLine, ok := <-self.fromServer:\n\t\t\tif !ok {\n\t\t\t\t\/\/ Channel is closed, we're offline. Stop.\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tswitch serverLine.Command {\n\n\t\t\t\/\/ QUIT and NICK don't have a channel name\n\t\t\t\/\/ They need to go to all channels the user is in\n\t\t\tcase \"QUIT\", \"NICK\":\n\t\t\t\tself.dis.DispatchMany(serverLine, self.users.In(serverLine.User))\n\n\t\t\tdefault:\n\t\t\t\tself.dis.Dispatch(serverLine)\n\t\t\t}\n\n\t\t\tself.users.Act(serverLine)\n\n\t\tcase busMessage, ok := <-self.fromBus:\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tparts := strings.SplitN(busMessage, \" \", 2)\n\t\t\tbusCommand = parts[0]\n\t\t\tif len(parts) > 1 {\n\t\t\t\targs = parts[1]\n\t\t\t}\n\n\t\t\tself.handleCommand(busCommand, args)\n\t\t}\n\t}\n}\n\n\/\/ Handle a command send from a plugin.\n\/\/ Current commands:\n\/\/  - WRITE <chatbotid> <channel> <msg>: Send message to server\n\/\/  - REFRESH: Reload plugin configuration\nfunc (self *BotBot) handleCommand(cmd string, args string) {\n\tswitch cmd {\n\tcase \"WRITE\":\n\t\tparts := strings.SplitN(args, \" \", 3)\n\t\tchatbotId, err := strconv.Atoi(parts[0])\n\t\tif err != nil {\n\t\t\tlog.Println(\"Invalid chatbot id: \", parts[0])\n\t\t\treturn\n\t\t}\n\n\t\tself.netMan.Send(chatbotId, parts[1], parts[2])\n\n\t\t\/\/ Now send it back to ourself, so other plugins see it\n\t\tinternalLine := &line.Line{\n\t\t\tChatBotId: chatbotId,\n\t\t\tRaw:       args,\n\t\t\tUser:      self.netMan.GetUserByChatbotId(chatbotId),\n\t\t\tCommand:   \"PRIVMSG\",\n\t\t\tReceived:  time.Now().UTC().Format(time.RFC3339Nano),\n\t\t\tContent:   parts[2],\n\t\t\tChannel:   parts[1]}\n\t\tself.dis.Dispatch(internalLine)\n\n\tcase \"REFRESH\":\n\t\tlog.Println(\"Reloading configuration from database\")\n\t\tself.netMan.RefreshChatbots()\n\t}\n}\n\n\/\/ Writes the number of users per channel, every hour. Run in go routine.\nfunc (self *BotBot) recordUserCounts() {\n\n\tfor {\n\n\t\tfor ch, _ := range self.users.Channels() {\n\t\t\tself.storage.SetCount(ch, self.users.Count(ch))\n\t\t}\n\t\ttime.Sleep(1 * time.Hour)\n\t}\n}\n\n\/\/ Stop\nfunc (self *BotBot) shutdown() {\n\tself.netMan.Shutdown()\n}\n\n\/*\n * POSTGRES STORAGE\n *\/\n\ntype PostgresStorage struct {\n\tdb *sql.DB\n}\n\n\/\/ Connect to the database.\nfunc NewPostgresStorage() *PostgresStorage {\n\tpostgresUrlString := os.Getenv(\"DATABASE_URL\")\n\tif postgresUrlString == \"\" {\n\t\tpostgresUrlString = \"postgres:\/\/localhost\/botbot\"\n\t}\n\tdataSource, err := pq.ParseURL(postgresUrlString)\n\tif err != nil {\n\t\tlog.Fatal(\"Could not read database string\", err)\n\t}\n\tdb, err := sql.Open(\"postgres\", dataSource+\" sslmode=disable\")\n\tif err != nil {\n\t\tlog.Fatal(\"Could not connect to database.\", err)\n\t}\n\n\treturn &PostgresStorage{db}\n}\n\nfunc (self *PostgresStorage) BotConfig() []*common.BotConfig {\n\n\tvar err error\n\tvar rows *sql.Rows\n\n\tconfigs := make([]*common.BotConfig, 0)\n\n\tsql := \"SELECT id, server, server_password, nick, password, real_name FROM bots_chatbot WHERE is_active=true\"\n\trows, err = self.db.Query(sql)\n\tif err != nil {\n\t\tlog.Fatal(\"Error running: \", sql, \" \", err)\n\t}\n\n\tvar chatbotId int\n\tvar server, server_password, nick, password, real_name []byte\n\n\tfor rows.Next() {\n\t\trows.Scan(&chatbotId, &server, &server_password, &nick, &password, &real_name)\n\n\t\tconfMap := map[string]string{\n\t\t\t\"server\":          string(server),\n\t\t\t\"server_password\": string(server_password),\n\t\t\t\"nick\":            string(nick),\n\t\t\t\"password\":        string(password),\n\t\t\t\"realname\":        string(real_name),\n\t\t}\n\n\t\tconfig := &common.BotConfig{\n\t\t\tId:       chatbotId,\n\t\t\tConfig:   confMap,\n\t\t\tChannels: make([]string, 0),\n\t\t}\n\n\t\tconfigs = append(configs, config)\n\t}\n\tfor i := range configs {\n\t\tconfig := configs[i]\n\t\trows, err = self.db.Query(\"SELECT id, name, password FROM bots_channel WHERE is_active=true and chatbot_id=$1\", config.Id)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error running:\", err)\n\t\t}\n\t\tvar channelId int\n\t\tvar channelName string\n\t\tvar channelPwd string\n\t\tfor rows.Next() {\n\t\t\trows.Scan(&channelId, &channelName, &channelPwd)\n\t\t\tconfig.Channels = append(config.Channels, channelName+\" \"+channelPwd)\n\t\t}\n\t\tlog.Println(\"config.Channel:\", config.Channels)\n\t}\n\n\treturn configs\n}\n\nfunc (self *PostgresStorage) SetCount(channel string, count int) error {\n\n\tnow := time.Now()\n\thour := now.Hour()\n\n\tchannelId, err := self.channelId(channel)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Write the count\n\n\tupdateSQL := \"UPDATE bots_usercount SET counts[$1] = $2 WHERE channel_id = $3 AND dt = $4\"\n\n\tvar res sql.Result\n\tres, err = self.db.Exec(updateSQL, hour, count, channelId, now)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar rowCount int64\n\trowCount, err = res.RowsAffected()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif rowCount == 1 {\n\t\t\/\/ Success - the update worked\n\t\treturn nil\n\t}\n\n\t\/\/ Update failed, need to create the row first\n\n\tinsSQL := \"INSERT INTO bots_usercount (channel_id, dt, counts) VALUES ($1, $2, '{NULL}')\"\n\n\t_, err = self.db.Exec(insSQL, channelId, now)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Run the update again\n\t_, err = self.db.Query(updateSQL, hour, count, channelId, now)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ The channel Id for a given channel name\nfunc (self *PostgresStorage) channelId(name string) (int, error) {\n\n\tvar channelId int\n\tquery := \"SELECT id from bots_channel WHERE name = $1\"\n\n\trows, err := self.db.Query(query, name)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\trows.Next()\n\trows.Scan(&channelId)\n\n\tif rows.Next() {\n\t\tlog.Fatal(\"More than one result. \"+\n\t\t\t\"Same name channels on different nets not yet supported. \", query)\n\t}\n\n\treturn channelId, nil\n}\n\nfunc (self *PostgresStorage) Close() error {\n\treturn self.db.Close()\n}\n\n\/*\n * REDIS WRAPPER\n * Survives Redis restarts, waits for Redis to be available.\n * Implements common.Queue\n *\/\ntype reliableQueue struct {\n\tqueue common.Queue\n}\n\nfunc newReliableQueue(queue common.Queue) common.Queue {\n\ts := reliableQueue{queue: queue}\n\ts.waitForRedis()\n\treturn &s\n}\n\nfunc (self *reliableQueue) waitForRedis() {\n\n\t_, err := self.queue.Ping()\n\tfor err != nil {\n\t\tlog.Println(\"Waiting for redis...\")\n\t\ttime.Sleep(1 * time.Second)\n\n\t\t_, err = self.queue.Ping()\n\t}\n}\n\nfunc (self *reliableQueue) Publish(queue string, message []byte) error {\n\n\terr := self.queue.Publish(queue, message)\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tnetErr := err.(net.Error)\n\tif netErr.Timeout() || netErr.Temporary() {\n\t\treturn err\n\t}\n\n\tself.waitForRedis()\n\treturn self.Publish(queue, message) \/\/ Recurse\n}\n\nfunc (self *reliableQueue) Blpop(keys []string, timeoutsecs uint) (*string, []byte, error) {\n\n\tkey, val, err := self.queue.Blpop(keys, timeoutsecs)\n\tif err == nil {\n\t\treturn key, val, nil\n\t}\n\n\tnetErr := err.(net.Error)\n\tif netErr.Timeout() || netErr.Temporary() {\n\t\treturn key, val, err\n\t}\n\n\tself.waitForRedis()\n\treturn self.Blpop(keys, timeoutsecs) \/\/ Recurse\n}\n\nfunc (self *reliableQueue) Rpush(key string, val []byte) error {\n\n\terr := self.queue.Rpush(key, val)\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tnetErr := err.(net.Error)\n\tif netErr.Timeout() || netErr.Temporary() {\n\t\treturn err\n\t}\n\n\tself.waitForRedis()\n\treturn self.Rpush(key, val) \/\/ Recurse\n}\n\nfunc (self *reliableQueue) Llen(key string) (int, error) {\n\n\tsize, err := self.queue.Llen(key)\n\tif err == nil {\n\t\treturn size, nil\n\t}\n\n\tnetErr := err.(net.Error)\n\tif netErr.Timeout() || netErr.Temporary() {\n\t\treturn size, err\n\t}\n\n\tself.waitForRedis()\n\treturn self.Llen(key) \/\/ Recurse\n}\n\nfunc (self *reliableQueue) Ltrim(key string, start int, end int) error {\n\n\terr := self.queue.Ltrim(key, start, end)\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tnetErr := err.(net.Error)\n\tif netErr.Timeout() || netErr.Temporary() {\n\t\treturn err\n\t}\n\n\tself.waitForRedis()\n\treturn self.Ltrim(key, start, end) \/\/ Recurse\n}\n\nfunc (self *reliableQueue) Ping() (string, error) {\n\treturn self.queue.Ping()\n}\n<commit_msg>Fix listen queue name<commit_after>package main\n\nimport (\n\t\"net\"\n\tnurl \"net\/url\"\n\t\"time\"\n\n\t\/\/ third-party dependencies\n\n\tpq \"github.com\/bmizerany\/pq\"\n\t\"github.com\/monnand\/goredis\"\n\n\t\/\/ local packages\n\t\"github.com\/lincolnloop\/botbot-bot\/common\"\n\t\"github.com\/lincolnloop\/botbot-bot\/dispatch\"\n\t\"github.com\/lincolnloop\/botbot-bot\/line\"\n\t\"github.com\/lincolnloop\/botbot-bot\/network\"\n\t\"github.com\/lincolnloop\/botbot-bot\/user\"\n\n\t\/\/ stdlib package\n\t\"database\/sql\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nconst (\n\t\/\/ Prefix of Redis channel to listen for messages on\n\tLISTEN_QUEUE_PREFIX   = \"bot\"\n)\n\nfunc main() {\n\n\tlog.Println(\"START. Use 'botbot -help' for command line options.\")\n\n\tstorage := NewPostgresStorage()\n\tdefer storage.Close()\n\tredisUrlString := os.Getenv(\"REDIS_PLUGIN_QUEUE_URL\")\n\tif redisUrlString == \"\" {\n\t\tredisUrlString = \"redis:\/\/localhost:6379\/0\"\n\t}\n\tredisUrl, err := nurl.Parse(redisUrlString)\n\tif err != nil {\n\t\tlog.Fatal(\"Could not read Redis string\", err)\n\t}\n\tredisQueue := goredis.Client{Addr: redisUrl.Host}\n\tqueue := newReliableQueue(&redisQueue)\n\n\tbotbot := NewBotBot(storage, queue)\n\n\t\/\/ Listen for incoming commands\n\tgo botbot.listen(LISTEN_QUEUE_PREFIX)\n\n\t\/\/ Start the main loop\n\tgo botbot.mainLoop()\n\n\t\/\/ Trap stop signal (Ctrl-C, kill) to exit\n\tkill := make(chan os.Signal)\n\tsignal.Notify(kill, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM)\n\n\t\/\/ Wait for stop signal\n\tfor {\n\t\t<-kill\n\t\tlog.Println(\"Graceful shutdown\")\n\t\tbotbot.shutdown()\n\t\tbreak\n\t}\n\n\tlog.Println(\"Bye\")\n}\n\n\/*\n * BOTBOT - the main object\n *\/\n\ntype BotBot struct {\n\tnetMan     *network.NetworkManager\n\tdis        *dispatch.Dispatcher\n\tusers      *user.UserManager\n\tstorage    common.Storage\n\tqueue      common.Queue\n\tfromServer chan *line.Line\n\tfromBus    chan string\n}\n\nfunc NewBotBot(storage common.Storage, queue common.Queue) *BotBot {\n\n\tfromServer := make(chan *line.Line)\n\tfromBus := make(chan string)\n\n\tnetMan := network.NewNetworkManager(storage, fromServer)\n\tnetMan.RefreshChatbots()\n\tgo netMan.MonitorChatbots()\n\n\tdis := dispatch.NewDispatcher(queue)\n\n\tusers := user.NewUserManager()\n\n\treturn &BotBot{\n\t\tnetMan:     netMan,\n\t\tdis:        dis,\n\t\tusers:      users,\n\t\tqueue:      queue,\n\t\tstorage:    storage,\n\t\tfromServer: fromServer,\n\t\tfromBus:    fromBus}\n}\n\n\/\/ Listen for incoming commands\nfunc (self *BotBot) listen(queueName string) {\n\n\tvar msg []byte\n\tvar err error\n\n\tfor {\n\t\t_, msg, err = self.queue.Blpop([]string{queueName}, 0)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error reading (BLPOP) from queue. \", err)\n\t\t}\n\t\tif len(msg) != 0 {\n\t\t\tlog.Println(\"Command: \", string(msg))\n\t\t\tself.fromBus <- string(msg)\n\t\t}\n\t}\n}\n\nfunc (self *BotBot) mainLoop() {\n\n\tgo self.recordUserCounts()\n\n\tvar busCommand string\n\tvar args string\n\tfor {\n\t\tselect {\n\n\t\tcase serverLine, ok := <-self.fromServer:\n\t\t\tif !ok {\n\t\t\t\t\/\/ Channel is closed, we're offline. Stop.\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tswitch serverLine.Command {\n\n\t\t\t\/\/ QUIT and NICK don't have a channel name\n\t\t\t\/\/ They need to go to all channels the user is in\n\t\t\tcase \"QUIT\", \"NICK\":\n\t\t\t\tself.dis.DispatchMany(serverLine, self.users.In(serverLine.User))\n\n\t\t\tdefault:\n\t\t\t\tself.dis.Dispatch(serverLine)\n\t\t\t}\n\n\t\t\tself.users.Act(serverLine)\n\n\t\tcase busMessage, ok := <-self.fromBus:\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tparts := strings.SplitN(busMessage, \" \", 2)\n\t\t\tbusCommand = parts[0]\n\t\t\tif len(parts) > 1 {\n\t\t\t\targs = parts[1]\n\t\t\t}\n\n\t\t\tself.handleCommand(busCommand, args)\n\t\t}\n\t}\n}\n\n\/\/ Handle a command send from a plugin.\n\/\/ Current commands:\n\/\/  - WRITE <chatbotid> <channel> <msg>: Send message to server\n\/\/  - REFRESH: Reload plugin configuration\nfunc (self *BotBot) handleCommand(cmd string, args string) {\n\tswitch cmd {\n\tcase \"WRITE\":\n\t\tparts := strings.SplitN(args, \" \", 3)\n\t\tchatbotId, err := strconv.Atoi(parts[0])\n\t\tif err != nil {\n\t\t\tlog.Println(\"Invalid chatbot id: \", parts[0])\n\t\t\treturn\n\t\t}\n\n\t\tself.netMan.Send(chatbotId, parts[1], parts[2])\n\n\t\t\/\/ Now send it back to ourself, so other plugins see it\n\t\tinternalLine := &line.Line{\n\t\t\tChatBotId: chatbotId,\n\t\t\tRaw:       args,\n\t\t\tUser:      self.netMan.GetUserByChatbotId(chatbotId),\n\t\t\tCommand:   \"PRIVMSG\",\n\t\t\tReceived:  time.Now().UTC().Format(time.RFC3339Nano),\n\t\t\tContent:   parts[2],\n\t\t\tChannel:   parts[1]}\n\t\tself.dis.Dispatch(internalLine)\n\n\tcase \"REFRESH\":\n\t\tlog.Println(\"Reloading configuration from database\")\n\t\tself.netMan.RefreshChatbots()\n\t}\n}\n\n\/\/ Writes the number of users per channel, every hour. Run in go routine.\nfunc (self *BotBot) recordUserCounts() {\n\n\tfor {\n\n\t\tfor ch, _ := range self.users.Channels() {\n\t\t\tself.storage.SetCount(ch, self.users.Count(ch))\n\t\t}\n\t\ttime.Sleep(1 * time.Hour)\n\t}\n}\n\n\/\/ Stop\nfunc (self *BotBot) shutdown() {\n\tself.netMan.Shutdown()\n}\n\n\/*\n * POSTGRES STORAGE\n *\/\n\ntype PostgresStorage struct {\n\tdb *sql.DB\n}\n\n\/\/ Connect to the database.\nfunc NewPostgresStorage() *PostgresStorage {\n\tpostgresUrlString := os.Getenv(\"DATABASE_URL\")\n\tif postgresUrlString == \"\" {\n\t\tpostgresUrlString = \"postgres:\/\/localhost\/botbot\"\n\t}\n\tdataSource, err := pq.ParseURL(postgresUrlString)\n\tif err != nil {\n\t\tlog.Fatal(\"Could not read database string\", err)\n\t}\n\tdb, err := sql.Open(\"postgres\", dataSource+\" sslmode=disable\")\n\tif err != nil {\n\t\tlog.Fatal(\"Could not connect to database.\", err)\n\t}\n\n\treturn &PostgresStorage{db}\n}\n\nfunc (self *PostgresStorage) BotConfig() []*common.BotConfig {\n\n\tvar err error\n\tvar rows *sql.Rows\n\n\tconfigs := make([]*common.BotConfig, 0)\n\n\tsql := \"SELECT id, server, server_password, nick, password, real_name FROM bots_chatbot WHERE is_active=true\"\n\trows, err = self.db.Query(sql)\n\tif err != nil {\n\t\tlog.Fatal(\"Error running: \", sql, \" \", err)\n\t}\n\n\tvar chatbotId int\n\tvar server, server_password, nick, password, real_name []byte\n\n\tfor rows.Next() {\n\t\trows.Scan(&chatbotId, &server, &server_password, &nick, &password, &real_name)\n\n\t\tconfMap := map[string]string{\n\t\t\t\"server\":          string(server),\n\t\t\t\"server_password\": string(server_password),\n\t\t\t\"nick\":            string(nick),\n\t\t\t\"password\":        string(password),\n\t\t\t\"realname\":        string(real_name),\n\t\t}\n\n\t\tconfig := &common.BotConfig{\n\t\t\tId:       chatbotId,\n\t\t\tConfig:   confMap,\n\t\t\tChannels: make([]string, 0),\n\t\t}\n\n\t\tconfigs = append(configs, config)\n\t}\n\tfor i := range configs {\n\t\tconfig := configs[i]\n\t\trows, err = self.db.Query(\"SELECT id, name, password FROM bots_channel WHERE is_active=true and chatbot_id=$1\", config.Id)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Error running:\", err)\n\t\t}\n\t\tvar channelId int\n\t\tvar channelName string\n\t\tvar channelPwd string\n\t\tfor rows.Next() {\n\t\t\trows.Scan(&channelId, &channelName, &channelPwd)\n\t\t\tconfig.Channels = append(config.Channels, channelName+\" \"+channelPwd)\n\t\t}\n\t\tlog.Println(\"config.Channel:\", config.Channels)\n\t}\n\n\treturn configs\n}\n\nfunc (self *PostgresStorage) SetCount(channel string, count int) error {\n\n\tnow := time.Now()\n\thour := now.Hour()\n\n\tchannelId, err := self.channelId(channel)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Write the count\n\n\tupdateSQL := \"UPDATE bots_usercount SET counts[$1] = $2 WHERE channel_id = $3 AND dt = $4\"\n\n\tvar res sql.Result\n\tres, err = self.db.Exec(updateSQL, hour, count, channelId, now)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar rowCount int64\n\trowCount, err = res.RowsAffected()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif rowCount == 1 {\n\t\t\/\/ Success - the update worked\n\t\treturn nil\n\t}\n\n\t\/\/ Update failed, need to create the row first\n\n\tinsSQL := \"INSERT INTO bots_usercount (channel_id, dt, counts) VALUES ($1, $2, '{NULL}')\"\n\n\t_, err = self.db.Exec(insSQL, channelId, now)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Run the update again\n\t_, err = self.db.Query(updateSQL, hour, count, channelId, now)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ The channel Id for a given channel name\nfunc (self *PostgresStorage) channelId(name string) (int, error) {\n\n\tvar channelId int\n\tquery := \"SELECT id from bots_channel WHERE name = $1\"\n\n\trows, err := self.db.Query(query, name)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\trows.Next()\n\trows.Scan(&channelId)\n\n\tif rows.Next() {\n\t\tlog.Fatal(\"More than one result. \"+\n\t\t\t\"Same name channels on different nets not yet supported. \", query)\n\t}\n\n\treturn channelId, nil\n}\n\nfunc (self *PostgresStorage) Close() error {\n\treturn self.db.Close()\n}\n\n\/*\n * REDIS WRAPPER\n * Survives Redis restarts, waits for Redis to be available.\n * Implements common.Queue\n *\/\ntype reliableQueue struct {\n\tqueue common.Queue\n}\n\nfunc newReliableQueue(queue common.Queue) common.Queue {\n\ts := reliableQueue{queue: queue}\n\ts.waitForRedis()\n\treturn &s\n}\n\nfunc (self *reliableQueue) waitForRedis() {\n\n\t_, err := self.queue.Ping()\n\tfor err != nil {\n\t\tlog.Println(\"Waiting for redis...\")\n\t\ttime.Sleep(1 * time.Second)\n\n\t\t_, err = self.queue.Ping()\n\t}\n}\n\nfunc (self *reliableQueue) Publish(queue string, message []byte) error {\n\n\terr := self.queue.Publish(queue, message)\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tnetErr := err.(net.Error)\n\tif netErr.Timeout() || netErr.Temporary() {\n\t\treturn err\n\t}\n\n\tself.waitForRedis()\n\treturn self.Publish(queue, message) \/\/ Recurse\n}\n\nfunc (self *reliableQueue) Blpop(keys []string, timeoutsecs uint) (*string, []byte, error) {\n\n\tkey, val, err := self.queue.Blpop(keys, timeoutsecs)\n\tif err == nil {\n\t\treturn key, val, nil\n\t}\n\n\tnetErr := err.(net.Error)\n\tif netErr.Timeout() || netErr.Temporary() {\n\t\treturn key, val, err\n\t}\n\n\tself.waitForRedis()\n\treturn self.Blpop(keys, timeoutsecs) \/\/ Recurse\n}\n\nfunc (self *reliableQueue) Rpush(key string, val []byte) error {\n\n\terr := self.queue.Rpush(key, val)\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tnetErr := err.(net.Error)\n\tif netErr.Timeout() || netErr.Temporary() {\n\t\treturn err\n\t}\n\n\tself.waitForRedis()\n\treturn self.Rpush(key, val) \/\/ Recurse\n}\n\nfunc (self *reliableQueue) Llen(key string) (int, error) {\n\n\tsize, err := self.queue.Llen(key)\n\tif err == nil {\n\t\treturn size, nil\n\t}\n\n\tnetErr := err.(net.Error)\n\tif netErr.Timeout() || netErr.Temporary() {\n\t\treturn size, err\n\t}\n\n\tself.waitForRedis()\n\treturn self.Llen(key) \/\/ Recurse\n}\n\nfunc (self *reliableQueue) Ltrim(key string, start int, end int) error {\n\n\terr := self.queue.Ltrim(key, start, end)\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tnetErr := err.(net.Error)\n\tif netErr.Timeout() || netErr.Temporary() {\n\t\treturn err\n\t}\n\n\tself.waitForRedis()\n\treturn self.Ltrim(key, start, end) \/\/ Recurse\n}\n\nfunc (self *reliableQueue) Ping() (string, error) {\n\treturn self.queue.Ping()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"github.com\/drone\/drone-plugin-go\/plugin\"\n)\n\ntype S3 struct {\n\tKey    string `json:\"access_key\"`\n\tSecret string `json:\"secret_key\"`\n\tBucket string `json:\"bucket\"`\n\n\t\/\/ us-east-1\n\t\/\/ us-west-1\n\t\/\/ us-west-2\n\t\/\/ eu-west-1\n\t\/\/ ap-southeast-1\n\t\/\/ ap-southeast-2\n\t\/\/ ap-northeast-1\n\t\/\/ sa-east-1\n\tRegion string `json:\"region\"`\n\n\t\/\/ Indicates the files ACL, which should be one\n\t\/\/ of the following:\n\t\/\/     private\n\t\/\/     public-read\n\t\/\/     public-read-write\n\t\/\/     authenticated-read\n\t\/\/     bucket-owner-read\n\t\/\/     bucket-owner-full-control\n\tAccess string `json:\"acl\"`\n\n\t\/\/ Copies the files from the specified directory.\n\t\/\/ Regexp matching will apply to match multiple\n\t\/\/ files\n\t\/\/\n\t\/\/ Examples:\n\t\/\/    \/path\/to\/file\n\t\/\/    \/path\/to\/*.txt\n\t\/\/    \/path\/to\/*\/*.txt\n\t\/\/    \/path\/to\/**\n\tSource string `json:\"source\"`\n\tTarget string `json:\"target\"`\n\n\t\/\/ Recursive uploads\n\tRecursive bool `json:\"recursive\"`\n}\n\nfunc main() {\n\tworkspace := plugin.Workspace{}\n\tvargs := S3{}\n\n\tplugin.Param(\"workspace\", &workspace)\n\tplugin.Param(\"vargs\", &vargs)\n\tplugin.MustParse()\n\n\t\/\/ skip if AWS key or SECRET are empty. A good example for this would\n\t\/\/ be forks building a project. S3 might be configured in the source\n\t\/\/ repo, but not in the fork\n\tif len(vargs.Key) == 0 || len(vargs.Secret) == 0 {\n\t\treturn\n\t}\n\n\t\/\/ make sure a default region is set\n\tif len(vargs.Region) == 0 {\n\t\tvargs.Region = \"us-east-1\"\n\t}\n\n\t\/\/ make sure a default access is set\n\t\/\/ let's be conservative and assume private\n\tif len(vargs.Access) == 0 {\n\t\tvargs.Access = \"private\"\n\t}\n\n\t\/\/ if the target starts with a \"\/\" we need\n\t\/\/ to remove it, otherwise we might adding\n\t\/\/ a 3rd slash to s3:\/\/\n\tif strings.HasPrefix(vargs.Target, \"\/\") {\n\t\tvargs.Target = vargs.Target[1:]\n\t}\n\n\tcmd := command(vargs)\n\tcmd.Env = os.Environ()\n\tcmd.Env = append(cmd.Env, \"AWS_ACCESS_KEY_ID=\"+vargs.Key)\n\tcmd.Env = append(cmd.Env, \"AWS_SECRET_ACCESS_KEY=\"+vargs.Secret)\n\tcmd.Dir = workspace.Path\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\ttrace(cmd)\n\n\t\/\/ run the command and exit if failed.\n\terr := cmd.Run()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n}\n\n\/\/ command is a helper function that returns the command\n\/\/ and arguments to upload to aws from the command line.\nfunc command(s S3) *exec.Cmd {\n\n\t\/\/ remote path S3 uri\n\tpath := fmt.Sprintf(\"s3:\/\/%s\/%s\", s.Bucket, s.Target)\n\n\t\/\/ command line args\n\targs := []string{\n\t\t\"s3\",\n\t\t\"cp\",\n\t\ts.Source,\n\t\tpath,\n\t\t\"--recursive\",\n\t\t\"--acl\",\n\t\ts.Access,\n\t\t\"--region\",\n\t\ts.Region,\n\t}\n\n\t\/\/ if not recursive, remove from the\n\t\/\/ above arguments.\n\tif !s.Recursive {\n\t\targs[4] = \"\"\n\t}\n\n\treturn exec.Command(\"aws\", args...)\n}\n\n\/\/ trace writes each command to standard error (preceded by a ‘$ ’) before it\n\/\/ is executed. Used for debugging your build.\nfunc trace(cmd *exec.Cmd) {\n\tfmt.Println(\"$\", strings.Join(cmd.Args, \" \"))\n}\n<commit_msg>correctly remove --remote from args<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"github.com\/drone\/drone-plugin-go\/plugin\"\n)\n\ntype S3 struct {\n\tKey    string `json:\"access_key\"`\n\tSecret string `json:\"secret_key\"`\n\tBucket string `json:\"bucket\"`\n\n\t\/\/ us-east-1\n\t\/\/ us-west-1\n\t\/\/ us-west-2\n\t\/\/ eu-west-1\n\t\/\/ ap-southeast-1\n\t\/\/ ap-southeast-2\n\t\/\/ ap-northeast-1\n\t\/\/ sa-east-1\n\tRegion string `json:\"region\"`\n\n\t\/\/ Indicates the files ACL, which should be one\n\t\/\/ of the following:\n\t\/\/     private\n\t\/\/     public-read\n\t\/\/     public-read-write\n\t\/\/     authenticated-read\n\t\/\/     bucket-owner-read\n\t\/\/     bucket-owner-full-control\n\tAccess string `json:\"acl\"`\n\n\t\/\/ Copies the files from the specified directory.\n\t\/\/ Regexp matching will apply to match multiple\n\t\/\/ files\n\t\/\/\n\t\/\/ Examples:\n\t\/\/    \/path\/to\/file\n\t\/\/    \/path\/to\/*.txt\n\t\/\/    \/path\/to\/*\/*.txt\n\t\/\/    \/path\/to\/**\n\tSource string `json:\"source\"`\n\tTarget string `json:\"target\"`\n\n\t\/\/ Recursive uploads\n\tRecursive bool `json:\"recursive\"`\n}\n\nfunc main() {\n\tworkspace := plugin.Workspace{}\n\tvargs := S3{}\n\n\tplugin.Param(\"workspace\", &workspace)\n\tplugin.Param(\"vargs\", &vargs)\n\tplugin.MustParse()\n\n\t\/\/ skip if AWS key or SECRET are empty. A good example for this would\n\t\/\/ be forks building a project. S3 might be configured in the source\n\t\/\/ repo, but not in the fork\n\tif len(vargs.Key) == 0 || len(vargs.Secret) == 0 {\n\t\treturn\n\t}\n\n\t\/\/ make sure a default region is set\n\tif len(vargs.Region) == 0 {\n\t\tvargs.Region = \"us-east-1\"\n\t}\n\n\t\/\/ make sure a default access is set\n\t\/\/ let's be conservative and assume private\n\tif len(vargs.Access) == 0 {\n\t\tvargs.Access = \"private\"\n\t}\n\n\t\/\/ if the target starts with a \"\/\" we need\n\t\/\/ to remove it, otherwise we might adding\n\t\/\/ a 3rd slash to s3:\/\/\n\tif strings.HasPrefix(vargs.Target, \"\/\") {\n\t\tvargs.Target = vargs.Target[1:]\n\t}\n\n\tcmd := command(vargs)\n\tcmd.Env = os.Environ()\n\tcmd.Env = append(cmd.Env, \"AWS_ACCESS_KEY_ID=\"+vargs.Key)\n\tcmd.Env = append(cmd.Env, \"AWS_SECRET_ACCESS_KEY=\"+vargs.Secret)\n\tcmd.Dir = workspace.Path\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\ttrace(cmd)\n\n\t\/\/ run the command and exit if failed.\n\terr := cmd.Run()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n}\n\n\/\/ command is a helper function that returns the command\n\/\/ and arguments to upload to aws from the command line.\nfunc command(s S3) *exec.Cmd {\n\n\t\/\/ remote path S3 uri\n\tpath := fmt.Sprintf(\"s3:\/\/%s\/%s\", s.Bucket, s.Target)\n\n\t\/\/ command line args\n\targs := []string{\n\t\t\"s3\",\n\t\t\"cp\",\n\t\ts.Source,\n\t\tpath,\n\t\t\"--recursive\",\n\t\t\"--acl\",\n\t\ts.Access,\n\t\t\"--region\",\n\t\ts.Region,\n\t}\n\n\t\/\/ if not recursive, remove from the\n\t\/\/ above arguments.\n\tif !s.Recursive {\n\t\targs = append(args[:4], args[4+1:]...)\n\t}\n\n\treturn exec.Command(\"aws\", args...)\n}\n\n\/\/ trace writes each command to standard error (preceded by a ‘$ ’) before it\n\/\/ is executed. Used for debugging your build.\nfunc trace(cmd *exec.Cmd) {\n\tfmt.Println(\"$\", strings.Join(cmd.Args, \" \"))\n}\n<|endoftext|>"}
{"text":"<commit_before>package dictutil\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\nvar (\n\ttoken_file = flag.String(\"token\", \"\", \"File contains token\")\n)\n\ntype dictionary struct {\n\tbase     string\n\tword_idx map[string]string\n}\n\n\/\/ NewDictionary returns new dictionary\nfunc NewDictionary(b string) *dictionary {\n\treturn &dictionary{\n\t\tbase:     b,\n\t\tword_idx: make(map[string]string),\n\t}\n}\n\n\/\/ PrepareIndex defines a function to index all the links\nfunc (d *dictionary) PrepareIndex() {\n\t\/\/ read  dictionary\n\tidx_data, err := ioutil.ReadFile(d.base + \".idx\")\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to open the dictionary: %s\\n\", err.Error())\n\t}\n\n\tdict_data, err := os.Open(d.base + \".dict\")\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to open the dictionary: %s\\n\", err.Error())\n\t}\n\n\t\/\/ close fi on exit and check for its returned error\n\tdefer func() {\n\t\tif err := dict_data.Close(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\treader := bytes.NewBuffer(idx_data)\n\n\tfor {\n\t\tword, err := reader.ReadString('\\x00')\n\t\tword = strings.TrimRight(word, \"\\x00\")\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ offset\n\t\toffset, err := GetNumber(reader)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ length\n\t\tlength, err := GetNumber(reader)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ desc\n\t\tdesc := make([]byte, length)\n\t\tdict_data.ReadAt(desc, int64(offset))\n\t\td.word_idx[word] = string(desc)\n\t}\n}\n\n\/\/ Check defines function to check whether word existed\nfunc (d *dictionary) Check(word string) (string, error) {\n\tdesc, exists := d.word_idx[word]\n\tif !exists {\n\t\treturn \"\", errors.New(\"notFound\")\n\t}\n\treturn desc, nil\n}\n\n\/\/ Change base of folder\nfunc (d *dictionary) ChangeBase(base string) {\n\td.base = base\n}\n\n\/\/ GetNumber is function to get Number\nfunc GetNumber(b *bytes.Buffer) (int32, error) {\n\tvar length int32\n\tb_length := make([]byte, 4)\n\tif n, err := b.Read(b_length); err != nil || n != 4 {\n\t\tfmt.Println(\"length err\", n, err)\n\t\treturn 0, errors.New(\"length err\")\n\t}\n\tbinary.Read(bytes.NewBuffer(b_length), binary.BigEndian,\n\t\t&length)\n\treturn length, nil\n}\n\n\/\/ GetToken is function to get token\nfunc GetToken() string {\n\tflag.Parse()\n\tif *token_file == \"\" {\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\t}\n\ttoken, err := ioutil.ReadFile(*token_file)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn \"\"\n\t}\n\treturn string(token)\n}\n\n\/\/ LogInit init logging\nfunc LogInit() {\n\tlog.SetFormatter(&log.JSONFormatter{})\n}\n\n\/\/ LogInfo defines logging info\nfunc LogInfo(e string, t int64, info interface{}) {\n\tlog.WithFields(log.Fields{\n\t\t\"event\": e,\n\t\t\"user\":  t,\n\t}).Info(info)\n}\n\n\/\/ LogWarn defines logging warning\nfunc LogWarn(e string, t int64, info interface{}) {\n\tlog.WithFields(log.Fields{\n\t\t\"event\": e,\n\t\t\"user\":  t,\n\t}).Warn(info)\n}\n\n\/\/ LogError defines logging error\nfunc LogError(e string, t int64, info interface{}) {\n\tlog.WithFields(log.Fields{\n\t\t\"event\": e,\n\t\t\"user\":  t,\n\t}).Error(info)\n}\n<commit_msg>rename var<commit_after>package dictutil\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\nvar (\n\ttokenFile = flag.String(\"token\", \"\", \"File contains token\")\n)\n\ntype dictionary struct {\n\tbase    string\n\twordIdx map[string]string\n}\n\n\/\/ NewDictionary returns new dictionary\nfunc NewDictionary(b string) *dictionary {\n\treturn &dictionary{\n\t\tbase:    b,\n\t\twordIdx: make(map[string]string),\n\t}\n}\n\n\/\/ PrepareIndex defines a function to index all the links\nfunc (d *dictionary) PrepareIndex() {\n\t\/\/ read  dictionary\n\tidxData, err := ioutil.ReadFile(d.base + \".idx\")\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to open the dictionary: %s\\n\", err.Error())\n\t}\n\n\tdictData, err := os.Open(d.base + \".dict\")\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to open the dictionary: %s\\n\", err.Error())\n\t}\n\n\t\/\/ close fi on exit and check for its returned error\n\tdefer func() {\n\t\tif err := dictData.Close(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}()\n\n\treader := bytes.NewBuffer(idxData)\n\n\tfor {\n\t\tword, err := reader.ReadString('\\x00')\n\t\tword = strings.TrimRight(word, \"\\x00\")\n\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ offset\n\t\toffset, err := GetNumber(reader)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ length\n\t\tlength, err := GetNumber(reader)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ desc\n\t\tdesc := make([]byte, length)\n\t\tdictData.ReadAt(desc, int64(offset))\n\t\td.wordIdx[word] = string(desc)\n\t}\n}\n\n\/\/ Check defines function to check whether word existed\nfunc (d *dictionary) Check(word string) (string, error) {\n\tdesc, exists := d.wordIdx[word]\n\tif !exists {\n\t\treturn \"\", errors.New(\"notFound\")\n\t}\n\treturn desc, nil\n}\n\n\/\/ Change base of folder\nfunc (d *dictionary) ChangeBase(base string) {\n\td.base = base\n}\n\n\/\/ GetNumber is function to get Number\nfunc GetNumber(b *bytes.Buffer) (int32, error) {\n\tvar length int32\n\tbLength := make([]byte, 4)\n\tif n, err := b.Read(bLength); err != nil || n != 4 {\n\t\tfmt.Println(\"length err\", n, err)\n\t\treturn 0, errors.New(\"length err\")\n\t}\n\tbinary.Read(bytes.NewBuffer(bLength), binary.BigEndian,\n\t\t&length)\n\treturn length, nil\n}\n\n\/\/ GetToken is function to get token\nfunc GetToken() string {\n\tflag.Parse()\n\tif *tokenFile == \"\" {\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\t}\n\ttoken, err := ioutil.ReadFile(*tokenFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn \"\"\n\t}\n\treturn string(token)\n}\n\n\/\/ LogInit init logging\nfunc LogInit() {\n\tlog.SetFormatter(&log.JSONFormatter{})\n}\n\n\/\/ LogInfo defines logging info\nfunc LogInfo(e string, t int64, info interface{}) {\n\tlog.WithFields(log.Fields{\n\t\t\"event\": e,\n\t\t\"user\":  t,\n\t}).Info(info)\n}\n\n\/\/ LogWarn defines logging warning\nfunc LogWarn(e string, t int64, info interface{}) {\n\tlog.WithFields(log.Fields{\n\t\t\"event\": e,\n\t\t\"user\":  t,\n\t}).Warn(info)\n}\n\n\/\/ LogError defines logging error\nfunc LogError(e string, t int64, info interface{}) {\n\tlog.WithFields(log.Fields{\n\t\t\"event\": e,\n\t\t\"user\":  t,\n\t}).Error(info)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package c2go contains the main function for running the executable.\n\/\/\n\/\/ Installation\n\/\/\n\/\/     go get -u github.com\/elliotchance\/c2go\n\/\/\n\/\/ Usage\n\/\/\n\/\/     c2go myfile.c\n\/\/\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"errors\"\n\n\t\"github.com\/elliotchance\/c2go\/ast\"\n\t\"github.com\/elliotchance\/c2go\/preprocessor\"\n\t\"github.com\/elliotchance\/c2go\/program\"\n\t\"github.com\/elliotchance\/c2go\/transpiler\"\n)\n\n\/\/ Version can be requested through the command line with:\n\/\/\n\/\/     c2go -v\n\/\/\n\/\/ See https:\/\/github.com\/elliotchance\/c2go\/wiki\/Release-Process\nconst Version = \"v0.18.1 Tantalum 2017-12-05\"\n\nvar stderr io.Writer = os.Stderr\n\n\/\/ ProgramArgs defines the options available when processing the program. There\n\/\/ is no constructor since the zeroed out values are the appropriate defaults -\n\/\/ you need only set the options you need.\n\/\/\n\/\/ TODO: Better separation on CLI modes\n\/\/ https:\/\/github.com\/elliotchance\/c2go\/issues\/134\n\/\/\n\/\/ Do not instantiate this directly. Instead use DefaultProgramArgs(); then\n\/\/ modify any specific attributes.\ntype ProgramArgs struct {\n\tverbose     bool\n\tast         bool\n\tinputFiles  []string\n\tclangFlags  []string\n\toutputFile  string\n\tpackageName string\n\n\t\/\/ A private option to output the Go as a *_test.go file.\n\toutputAsTest bool\n}\n\n\/\/ DefaultProgramArgs default value of ProgramArgs\nfunc DefaultProgramArgs() ProgramArgs {\n\treturn ProgramArgs{\n\t\tverbose:      false,\n\t\tast:          false,\n\t\tpackageName:  \"main\",\n\t\tclangFlags:   []string{},\n\t\toutputAsTest: false,\n\t}\n}\n\nfunc readAST(data []byte) []string {\n\treturn strings.Split(string(data), \"\\n\")\n}\n\ntype treeNode struct {\n\tindent int\n\tnode   ast.Node\n}\n\nfunc convertLinesToNodes(lines []string) []treeNode {\n\tnodes := make([]treeNode, len(lines))\n\tvar counter int\n\tfor _, line := range lines {\n\t\tif strings.TrimSpace(line) == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ It is tempting to discard null AST nodes, but these may\n\t\t\/\/ have semantic importance: for example, they represent omitted\n\t\t\/\/ for-loop conditions, as in for(;;).\n\t\tline = strings.Replace(line, \"<<<NULL>>>\", \"NullStmt\", 1)\n\t\ttrimmed := strings.TrimLeft(line, \"|\\\\- `\")\n\t\tnode := ast.Parse(trimmed)\n\t\tindentLevel := (len(line) - len(trimmed)) \/ 2\n\t\tnodes[counter] = treeNode{indentLevel, node}\n\t\tcounter++\n\t}\n\tnodes = nodes[0:counter]\n\n\treturn nodes\n}\n\nfunc convertLinesToNodesParallel(lines []string) []treeNode {\n\t\/\/ function f separate full list on 2 parts and\n\t\/\/ then each part can recursive run function f\n\tvar f func([]string, int) []treeNode\n\n\tf = func(lines []string, deep int) []treeNode {\n\t\tdeep = deep - 2\n\t\tpart := len(lines) \/ 2\n\n\t\tvar tr1 = make(chan []treeNode)\n\t\tvar tr2 = make(chan []treeNode)\n\n\t\tgo func(lines []string, deep int) {\n\t\t\tif deep <= 0 || len(lines) < deep {\n\t\t\t\ttr1 <- convertLinesToNodes(lines)\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttr1 <- f(lines, deep)\n\t\t}(lines[0:part], deep)\n\n\t\tgo func(lines []string, deep int) {\n\t\t\tif deep <= 0 || len(lines) < deep {\n\t\t\t\ttr2 <- convertLinesToNodes(lines)\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttr2 <- f(lines, deep)\n\t\t}(lines[part:], deep)\n\n\t\tdefer close(tr1)\n\t\tdefer close(tr2)\n\n\t\treturn append(<-tr1, <-tr2...)\n\t}\n\n\t\/\/ Parameter of deep - can be any, but effective to use\n\t\/\/ same amount of CPU\n\treturn f(lines, runtime.NumCPU())\n}\n\n\/\/ buildTree converts an array of nodes, each prefixed with a depth into a tree.\nfunc buildTree(nodes []treeNode, depth int) []ast.Node {\n\tif len(nodes) == 0 {\n\t\treturn []ast.Node{}\n\t}\n\n\t\/\/ Split the list into sections, treat each section as a tree with its own\n\t\/\/ root.\n\tsections := [][]treeNode{}\n\tfor _, node := range nodes {\n\t\tif node.indent == depth {\n\t\t\tsections = append(sections, []treeNode{node})\n\t\t} else {\n\t\t\tsections[len(sections)-1] = append(sections[len(sections)-1], node)\n\t\t}\n\t}\n\n\tresults := []ast.Node{}\n\tfor _, section := range sections {\n\t\tslice := []treeNode{}\n\t\tfor _, n := range section {\n\t\t\tif n.indent > depth {\n\t\t\t\tslice = append(slice, n)\n\t\t\t}\n\t\t}\n\n\t\tchildren := buildTree(slice, depth+1)\n\t\tfor _, child := range children {\n\t\t\tsection[0].node.AddChild(child)\n\t\t}\n\t\tresults = append(results, section[0].node)\n\t}\n\n\treturn results\n}\n\n\/\/ Start begins transpiling an input file.\nfunc Start(args ProgramArgs) (err error) {\n\tif args.verbose {\n\t\tfmt.Println(\"Start tanspiling ...\")\n\t}\n\n\tif os.Getenv(\"GOPATH\") == \"\" {\n\t\treturn fmt.Errorf(\"The $GOPATH must be set\")\n\t}\n\n\t\/\/ 1. Compile it first (checking for errors)\n\tfor _, in := range args.inputFiles {\n\t\t_, err := os.Stat(in)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Input file %s is not found\", in)\n\t\t}\n\t}\n\n\t\/\/ 2. Preprocess\n\tif args.verbose {\n\t\tfmt.Println(\"Running clang preprocessor...\")\n\t}\n\n\tpp, err := preprocessor.Analyze(args.inputFiles, args.clangFlags)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif args.verbose {\n\t\tfmt.Println(\"Writing preprocessor ...\")\n\t}\n\tdir, err := ioutil.TempDir(\"\", \"c2go\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot create temp folder: %v\", err)\n\t}\n\tdefer os.RemoveAll(dir) \/\/ clean up\n\n\tppFilePath := path.Join(dir, \"pp.c\")\n\terr = ioutil.WriteFile(ppFilePath, pp, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"writing to %s failed: %v\", ppFilePath, err)\n\t}\n\n\t\/\/ 3. Generate JSON from AST\n\tif args.verbose {\n\t\tfmt.Println(\"Running clang for AST tree...\")\n\t}\n\tastPP, err := exec.Command(\"clang\", \"-Xclang\", \"-ast-dump\", \"-fsyntax-only\", \"-fno-color-diagnostics\", ppFilePath).Output()\n\tif err != nil {\n\t\t\/\/ If clang fails it still prints out the AST, so we have to run it\n\t\t\/\/ again to get the real error.\n\t\terrBody, _ := exec.Command(\"clang\", ppFilePath).CombinedOutput()\n\n\t\tpanic(\"clang failed: \" + err.Error() + \":\\n\\n\" + string(errBody))\n\t}\n\n\tif args.verbose {\n\t\tfmt.Println(\"Reading clang AST tree...\")\n\t}\n\tlines := readAST(astPP)\n\tif args.ast {\n\t\tfor _, l := range lines {\n\t\t\tfmt.Println(l)\n\t\t}\n\t\tfmt.Println()\n\n\t\treturn nil\n\t}\n\n\tp := program.NewProgram()\n\tp.Verbose = args.verbose\n\tp.OutputAsTest = args.outputAsTest\n\n\t\/\/ Converting to nodes\n\tif args.verbose {\n\t\tfmt.Println(\"Converting to nodes...\")\n\t}\n\tnodes := convertLinesToNodesParallel(lines)\n\n\t\/\/ build tree\n\tif args.verbose {\n\t\tfmt.Println(\"Building tree...\")\n\t}\n\ttree := buildTree(nodes, 0)\n\tast.FixPositions(tree)\n\n\t\/\/ Repair the floating literals. See RepairFloatingLiteralsFromSource for\n\t\/\/ more information.\n\tfloatingErrors := ast.RepairFloatingLiteralsFromSource(tree[0], ppFilePath)\n\n\tfor _, fErr := range floatingErrors {\n\t\tmessage := fmt.Sprintf(\"could not read exact floating literal: %s\",\n\t\t\tfErr.Err.Error())\n\t\tp.AddMessage(p.GenerateWarningMessage(errors.New(message), fErr.Node))\n\t}\n\n\toutputFilePath := args.outputFile\n\n\tif outputFilePath == \"\" {\n\t\t\/\/ Choose inputFile for creating name of output file\n\t\tinput := args.inputFiles[0]\n\t\t\/\/ We choose name for output Go code at the base\n\t\t\/\/ on filename for choosed input file\n\t\tcleanFileName := filepath.Clean(filepath.Base(input))\n\t\textension := filepath.Ext(input)\n\t\toutputFilePath = cleanFileName[0:len(cleanFileName)-len(extension)] + \".go\"\n\t}\n\n\t\/\/ transpile ast tree\n\tif args.verbose {\n\t\tfmt.Println(\"Transpiling tree...\")\n\t}\n\n\terr = transpiler.TranspileAST(args.outputFile, args.packageName, p, tree[0].(ast.Node))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot transpile AST : %v\", err)\n\t}\n\n\t\/\/ write the output Go code\n\tif args.verbose {\n\t\tfmt.Println(\"Writing the output Go code...\")\n\t}\n\terr = ioutil.WriteFile(outputFilePath, []byte(p.String()), 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"writing Go output file failed: %v\", err)\n\t}\n\n\treturn nil\n}\n\ntype inputDataFlags []string\n\nfunc (i *inputDataFlags) String() (s string) {\n\tfor pos, item := range *i {\n\t\ts += fmt.Sprintf(\"Flag %d. %s\\n\", pos, item)\n\t}\n\treturn\n}\n\nfunc (i *inputDataFlags) Set(value string) error {\n\t*i = append(*i, value)\n\treturn nil\n}\n\nvar clangFlags inputDataFlags\n\nfunc init() {\n\ttranspileCommand.Var(&clangFlags, \"clang-flag\", \"Pass arguments to clang. You may provide multiple -clang-flag items.\")\n}\n\nvar (\n\tversionFlag       = flag.Bool(\"v\", false, \"print the version and exit\")\n\ttranspileCommand  = flag.NewFlagSet(\"transpile\", flag.ContinueOnError)\n\tverboseFlag       = transpileCommand.Bool(\"V\", false, \"print progress as comments\")\n\toutputFlag        = transpileCommand.String(\"o\", \"\", \"output Go generated code to the specified file\")\n\tpackageFlag       = transpileCommand.String(\"p\", \"main\", \"set the name of the generated package\")\n\ttranspileHelpFlag = transpileCommand.Bool(\"h\", false, \"print help information\")\n\tastCommand        = flag.NewFlagSet(\"ast\", flag.ContinueOnError)\n\tastHelpFlag       = astCommand.Bool(\"h\", false, \"print help information\")\n)\n\nfunc main() {\n\tcode := runCommand()\n\tif code != 0 {\n\t\tos.Exit(code)\n\t}\n}\n\nfunc runCommand() int {\n\n\tflag.Usage = func() {\n\t\tusage := \"Usage: %s [-v] [<command>] [<flags>] file1.c ...\\n\\n\"\n\t\tusage += \"Commands:\\n\"\n\t\tusage += \"  transpile\\ttranspile an input C source file or files to Go\\n\"\n\t\tusage += \"  ast\\t\\tprint AST before translated Go code\\n\\n\"\n\n\t\tusage += \"Flags:\\n\"\n\t\tfmt.Fprintf(stderr, usage, os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\n\ttranspileCommand.SetOutput(stderr)\n\tastCommand.SetOutput(stderr)\n\n\tflag.Parse()\n\n\tif *versionFlag {\n\t\t\/\/ Simply print out the version and exit.\n\t\tfmt.Println(Version)\n\t\treturn 0\n\t}\n\n\tif flag.NArg() < 1 {\n\t\tflag.Usage()\n\t\treturn 1\n\t}\n\n\targs := DefaultProgramArgs()\n\n\tswitch os.Args[1] {\n\tcase \"ast\":\n\t\terr := astCommand.Parse(os.Args[2:])\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"ast command cannot parse: %v\", err)\n\t\t\treturn 1\n\t\t}\n\n\t\tif *astHelpFlag || astCommand.NArg() == 0 {\n\t\t\tfmt.Fprintf(stderr, \"Usage: %s ast file.c\\n\", os.Args[0])\n\t\t\tastCommand.PrintDefaults()\n\t\t\treturn 1\n\t\t}\n\n\t\targs.ast = true\n\t\targs.inputFiles = astCommand.Args()\n\tcase \"transpile\":\n\t\terr := transpileCommand.Parse(os.Args[2:])\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"transpile command cannot parse: %v\", err)\n\t\t\treturn 1\n\t\t}\n\n\t\tif *transpileHelpFlag || transpileCommand.NArg() == 0 {\n\t\t\tfmt.Fprintf(stderr, \"Usage: %s transpile [-V] [-o file.go] [-p package] file1.c ...\\n\", os.Args[0])\n\t\t\ttranspileCommand.PrintDefaults()\n\t\t\treturn 1\n\t\t}\n\n\t\targs.inputFiles = transpileCommand.Args()\n\t\targs.outputFile = *outputFlag\n\t\targs.packageName = *packageFlag\n\t\targs.verbose = *verboseFlag\n\t\targs.clangFlags = clangFlags\n\tdefault:\n\t\tflag.Usage()\n\t\treturn 1\n\t}\n\n\tif err := Start(args); err != nil {\n\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n<commit_msg>Bump version: v0.18.2 Tantalum 2017-12-07<commit_after>\/\/ Package c2go contains the main function for running the executable.\n\/\/\n\/\/ Installation\n\/\/\n\/\/     go get -u github.com\/elliotchance\/c2go\n\/\/\n\/\/ Usage\n\/\/\n\/\/     c2go myfile.c\n\/\/\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"errors\"\n\n\t\"github.com\/elliotchance\/c2go\/ast\"\n\t\"github.com\/elliotchance\/c2go\/preprocessor\"\n\t\"github.com\/elliotchance\/c2go\/program\"\n\t\"github.com\/elliotchance\/c2go\/transpiler\"\n)\n\n\/\/ Version can be requested through the command line with:\n\/\/\n\/\/     c2go -v\n\/\/\n\/\/ See https:\/\/github.com\/elliotchance\/c2go\/wiki\/Release-Process\nconst Version = \"v0.18.2 Tantalum 2017-12-07\"\n\nvar stderr io.Writer = os.Stderr\n\n\/\/ ProgramArgs defines the options available when processing the program. There\n\/\/ is no constructor since the zeroed out values are the appropriate defaults -\n\/\/ you need only set the options you need.\n\/\/\n\/\/ TODO: Better separation on CLI modes\n\/\/ https:\/\/github.com\/elliotchance\/c2go\/issues\/134\n\/\/\n\/\/ Do not instantiate this directly. Instead use DefaultProgramArgs(); then\n\/\/ modify any specific attributes.\ntype ProgramArgs struct {\n\tverbose     bool\n\tast         bool\n\tinputFiles  []string\n\tclangFlags  []string\n\toutputFile  string\n\tpackageName string\n\n\t\/\/ A private option to output the Go as a *_test.go file.\n\toutputAsTest bool\n}\n\n\/\/ DefaultProgramArgs default value of ProgramArgs\nfunc DefaultProgramArgs() ProgramArgs {\n\treturn ProgramArgs{\n\t\tverbose:      false,\n\t\tast:          false,\n\t\tpackageName:  \"main\",\n\t\tclangFlags:   []string{},\n\t\toutputAsTest: false,\n\t}\n}\n\nfunc readAST(data []byte) []string {\n\treturn strings.Split(string(data), \"\\n\")\n}\n\ntype treeNode struct {\n\tindent int\n\tnode   ast.Node\n}\n\nfunc convertLinesToNodes(lines []string) []treeNode {\n\tnodes := make([]treeNode, len(lines))\n\tvar counter int\n\tfor _, line := range lines {\n\t\tif strings.TrimSpace(line) == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ It is tempting to discard null AST nodes, but these may\n\t\t\/\/ have semantic importance: for example, they represent omitted\n\t\t\/\/ for-loop conditions, as in for(;;).\n\t\tline = strings.Replace(line, \"<<<NULL>>>\", \"NullStmt\", 1)\n\t\ttrimmed := strings.TrimLeft(line, \"|\\\\- `\")\n\t\tnode := ast.Parse(trimmed)\n\t\tindentLevel := (len(line) - len(trimmed)) \/ 2\n\t\tnodes[counter] = treeNode{indentLevel, node}\n\t\tcounter++\n\t}\n\tnodes = nodes[0:counter]\n\n\treturn nodes\n}\n\nfunc convertLinesToNodesParallel(lines []string) []treeNode {\n\t\/\/ function f separate full list on 2 parts and\n\t\/\/ then each part can recursive run function f\n\tvar f func([]string, int) []treeNode\n\n\tf = func(lines []string, deep int) []treeNode {\n\t\tdeep = deep - 2\n\t\tpart := len(lines) \/ 2\n\n\t\tvar tr1 = make(chan []treeNode)\n\t\tvar tr2 = make(chan []treeNode)\n\n\t\tgo func(lines []string, deep int) {\n\t\t\tif deep <= 0 || len(lines) < deep {\n\t\t\t\ttr1 <- convertLinesToNodes(lines)\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttr1 <- f(lines, deep)\n\t\t}(lines[0:part], deep)\n\n\t\tgo func(lines []string, deep int) {\n\t\t\tif deep <= 0 || len(lines) < deep {\n\t\t\t\ttr2 <- convertLinesToNodes(lines)\n\t\t\t\treturn\n\t\t\t}\n\t\t\ttr2 <- f(lines, deep)\n\t\t}(lines[part:], deep)\n\n\t\tdefer close(tr1)\n\t\tdefer close(tr2)\n\n\t\treturn append(<-tr1, <-tr2...)\n\t}\n\n\t\/\/ Parameter of deep - can be any, but effective to use\n\t\/\/ same amount of CPU\n\treturn f(lines, runtime.NumCPU())\n}\n\n\/\/ buildTree converts an array of nodes, each prefixed with a depth into a tree.\nfunc buildTree(nodes []treeNode, depth int) []ast.Node {\n\tif len(nodes) == 0 {\n\t\treturn []ast.Node{}\n\t}\n\n\t\/\/ Split the list into sections, treat each section as a tree with its own\n\t\/\/ root.\n\tsections := [][]treeNode{}\n\tfor _, node := range nodes {\n\t\tif node.indent == depth {\n\t\t\tsections = append(sections, []treeNode{node})\n\t\t} else {\n\t\t\tsections[len(sections)-1] = append(sections[len(sections)-1], node)\n\t\t}\n\t}\n\n\tresults := []ast.Node{}\n\tfor _, section := range sections {\n\t\tslice := []treeNode{}\n\t\tfor _, n := range section {\n\t\t\tif n.indent > depth {\n\t\t\t\tslice = append(slice, n)\n\t\t\t}\n\t\t}\n\n\t\tchildren := buildTree(slice, depth+1)\n\t\tfor _, child := range children {\n\t\t\tsection[0].node.AddChild(child)\n\t\t}\n\t\tresults = append(results, section[0].node)\n\t}\n\n\treturn results\n}\n\n\/\/ Start begins transpiling an input file.\nfunc Start(args ProgramArgs) (err error) {\n\tif args.verbose {\n\t\tfmt.Println(\"Start tanspiling ...\")\n\t}\n\n\tif os.Getenv(\"GOPATH\") == \"\" {\n\t\treturn fmt.Errorf(\"The $GOPATH must be set\")\n\t}\n\n\t\/\/ 1. Compile it first (checking for errors)\n\tfor _, in := range args.inputFiles {\n\t\t_, err := os.Stat(in)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Input file %s is not found\", in)\n\t\t}\n\t}\n\n\t\/\/ 2. Preprocess\n\tif args.verbose {\n\t\tfmt.Println(\"Running clang preprocessor...\")\n\t}\n\n\tpp, err := preprocessor.Analyze(args.inputFiles, args.clangFlags)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif args.verbose {\n\t\tfmt.Println(\"Writing preprocessor ...\")\n\t}\n\tdir, err := ioutil.TempDir(\"\", \"c2go\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot create temp folder: %v\", err)\n\t}\n\tdefer os.RemoveAll(dir) \/\/ clean up\n\n\tppFilePath := path.Join(dir, \"pp.c\")\n\terr = ioutil.WriteFile(ppFilePath, pp, 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"writing to %s failed: %v\", ppFilePath, err)\n\t}\n\n\t\/\/ 3. Generate JSON from AST\n\tif args.verbose {\n\t\tfmt.Println(\"Running clang for AST tree...\")\n\t}\n\tastPP, err := exec.Command(\"clang\", \"-Xclang\", \"-ast-dump\", \"-fsyntax-only\", \"-fno-color-diagnostics\", ppFilePath).Output()\n\tif err != nil {\n\t\t\/\/ If clang fails it still prints out the AST, so we have to run it\n\t\t\/\/ again to get the real error.\n\t\terrBody, _ := exec.Command(\"clang\", ppFilePath).CombinedOutput()\n\n\t\tpanic(\"clang failed: \" + err.Error() + \":\\n\\n\" + string(errBody))\n\t}\n\n\tif args.verbose {\n\t\tfmt.Println(\"Reading clang AST tree...\")\n\t}\n\tlines := readAST(astPP)\n\tif args.ast {\n\t\tfor _, l := range lines {\n\t\t\tfmt.Println(l)\n\t\t}\n\t\tfmt.Println()\n\n\t\treturn nil\n\t}\n\n\tp := program.NewProgram()\n\tp.Verbose = args.verbose\n\tp.OutputAsTest = args.outputAsTest\n\n\t\/\/ Converting to nodes\n\tif args.verbose {\n\t\tfmt.Println(\"Converting to nodes...\")\n\t}\n\tnodes := convertLinesToNodesParallel(lines)\n\n\t\/\/ build tree\n\tif args.verbose {\n\t\tfmt.Println(\"Building tree...\")\n\t}\n\ttree := buildTree(nodes, 0)\n\tast.FixPositions(tree)\n\n\t\/\/ Repair the floating literals. See RepairFloatingLiteralsFromSource for\n\t\/\/ more information.\n\tfloatingErrors := ast.RepairFloatingLiteralsFromSource(tree[0], ppFilePath)\n\n\tfor _, fErr := range floatingErrors {\n\t\tmessage := fmt.Sprintf(\"could not read exact floating literal: %s\",\n\t\t\tfErr.Err.Error())\n\t\tp.AddMessage(p.GenerateWarningMessage(errors.New(message), fErr.Node))\n\t}\n\n\toutputFilePath := args.outputFile\n\n\tif outputFilePath == \"\" {\n\t\t\/\/ Choose inputFile for creating name of output file\n\t\tinput := args.inputFiles[0]\n\t\t\/\/ We choose name for output Go code at the base\n\t\t\/\/ on filename for choosed input file\n\t\tcleanFileName := filepath.Clean(filepath.Base(input))\n\t\textension := filepath.Ext(input)\n\t\toutputFilePath = cleanFileName[0:len(cleanFileName)-len(extension)] + \".go\"\n\t}\n\n\t\/\/ transpile ast tree\n\tif args.verbose {\n\t\tfmt.Println(\"Transpiling tree...\")\n\t}\n\n\terr = transpiler.TranspileAST(args.outputFile, args.packageName, p, tree[0].(ast.Node))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot transpile AST : %v\", err)\n\t}\n\n\t\/\/ write the output Go code\n\tif args.verbose {\n\t\tfmt.Println(\"Writing the output Go code...\")\n\t}\n\terr = ioutil.WriteFile(outputFilePath, []byte(p.String()), 0644)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"writing Go output file failed: %v\", err)\n\t}\n\n\treturn nil\n}\n\ntype inputDataFlags []string\n\nfunc (i *inputDataFlags) String() (s string) {\n\tfor pos, item := range *i {\n\t\ts += fmt.Sprintf(\"Flag %d. %s\\n\", pos, item)\n\t}\n\treturn\n}\n\nfunc (i *inputDataFlags) Set(value string) error {\n\t*i = append(*i, value)\n\treturn nil\n}\n\nvar clangFlags inputDataFlags\n\nfunc init() {\n\ttranspileCommand.Var(&clangFlags, \"clang-flag\", \"Pass arguments to clang. You may provide multiple -clang-flag items.\")\n}\n\nvar (\n\tversionFlag       = flag.Bool(\"v\", false, \"print the version and exit\")\n\ttranspileCommand  = flag.NewFlagSet(\"transpile\", flag.ContinueOnError)\n\tverboseFlag       = transpileCommand.Bool(\"V\", false, \"print progress as comments\")\n\toutputFlag        = transpileCommand.String(\"o\", \"\", \"output Go generated code to the specified file\")\n\tpackageFlag       = transpileCommand.String(\"p\", \"main\", \"set the name of the generated package\")\n\ttranspileHelpFlag = transpileCommand.Bool(\"h\", false, \"print help information\")\n\tastCommand        = flag.NewFlagSet(\"ast\", flag.ContinueOnError)\n\tastHelpFlag       = astCommand.Bool(\"h\", false, \"print help information\")\n)\n\nfunc main() {\n\tcode := runCommand()\n\tif code != 0 {\n\t\tos.Exit(code)\n\t}\n}\n\nfunc runCommand() int {\n\n\tflag.Usage = func() {\n\t\tusage := \"Usage: %s [-v] [<command>] [<flags>] file1.c ...\\n\\n\"\n\t\tusage += \"Commands:\\n\"\n\t\tusage += \"  transpile\\ttranspile an input C source file or files to Go\\n\"\n\t\tusage += \"  ast\\t\\tprint AST before translated Go code\\n\\n\"\n\n\t\tusage += \"Flags:\\n\"\n\t\tfmt.Fprintf(stderr, usage, os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\n\ttranspileCommand.SetOutput(stderr)\n\tastCommand.SetOutput(stderr)\n\n\tflag.Parse()\n\n\tif *versionFlag {\n\t\t\/\/ Simply print out the version and exit.\n\t\tfmt.Println(Version)\n\t\treturn 0\n\t}\n\n\tif flag.NArg() < 1 {\n\t\tflag.Usage()\n\t\treturn 1\n\t}\n\n\targs := DefaultProgramArgs()\n\n\tswitch os.Args[1] {\n\tcase \"ast\":\n\t\terr := astCommand.Parse(os.Args[2:])\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"ast command cannot parse: %v\", err)\n\t\t\treturn 1\n\t\t}\n\n\t\tif *astHelpFlag || astCommand.NArg() == 0 {\n\t\t\tfmt.Fprintf(stderr, \"Usage: %s ast file.c\\n\", os.Args[0])\n\t\t\tastCommand.PrintDefaults()\n\t\t\treturn 1\n\t\t}\n\n\t\targs.ast = true\n\t\targs.inputFiles = astCommand.Args()\n\tcase \"transpile\":\n\t\terr := transpileCommand.Parse(os.Args[2:])\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"transpile command cannot parse: %v\", err)\n\t\t\treturn 1\n\t\t}\n\n\t\tif *transpileHelpFlag || transpileCommand.NArg() == 0 {\n\t\t\tfmt.Fprintf(stderr, \"Usage: %s transpile [-V] [-o file.go] [-p package] file1.c ...\\n\", os.Args[0])\n\t\t\ttranspileCommand.PrintDefaults()\n\t\t\treturn 1\n\t\t}\n\n\t\targs.inputFiles = transpileCommand.Args()\n\t\targs.outputFile = *outputFlag\n\t\targs.packageName = *packageFlag\n\t\targs.verbose = *verboseFlag\n\t\targs.clangFlags = clangFlags\n\tdefault:\n\t\tflag.Usage()\n\t\treturn 1\n\t}\n\n\tif err := Start(args); err != nil {\n\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\treturn 1\n\t}\n\n\treturn 0\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ses\"\n\t\"github.com\/hashicorp\/terraform\/helper\/acctest\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nfunc TestAccAWSSESReceiptRule_basic(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() {\n\t\t\ttestAccPreCheck(t)\n\t\t},\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckSESReceiptRuleDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSSESReceiptRuleBasicConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAwsSESReceiptRuleExists(\"aws_ses_receipt_rule.basic\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSSESReceiptRule_order(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() {\n\t\t\ttestAccPreCheck(t)\n\t\t},\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckSESReceiptRuleDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSSESReceiptRuleOrderConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAwsSESReceiptRuleOrder(\"aws_ses_receipt_rule.second\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSSESReceiptRule_actions(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() {\n\t\t\ttestAccPreCheck(t)\n\t\t},\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckSESReceiptRuleDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSSESReceiptRuleActionsConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAwsSESReceiptRuleActions(\"aws_ses_receipt_rule.actions\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckSESReceiptRuleDestroy(s *terraform.State) error {\n\tconn := testAccProvider.Meta().(*AWSClient).sesConn\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_ses_receipt_rule\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tparams := &ses.DescribeReceiptRuleInput{\n\t\t\tRuleName:    aws.String(rs.Primary.Attributes[\"name\"]),\n\t\t\tRuleSetName: aws.String(rs.Primary.Attributes[\"rule_set_name\"]),\n\t\t}\n\n\t\t_, err := conn.DescribeReceiptRule(params)\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"Receipt rule %s still exists. Failing!\", rs.Primary.ID)\n\t\t}\n\n\t\t\/\/ Verify the error is what we want\n\t\t_, ok := err.(awserr.Error)\n\t\tif !ok {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n\n}\n\nfunc testAccCheckAwsSESReceiptRuleExists(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"SES Receipt Rule not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"SES Receipt Rule name not set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).sesConn\n\n\t\tparams := &ses.DescribeReceiptRuleInput{\n\t\t\tRuleName:    aws.String(\"basic\"),\n\t\t\tRuleSetName: aws.String(fmt.Sprintf(\"test-me-%d\", srrsRandomInt)),\n\t\t}\n\n\t\tresponse, err := conn.DescribeReceiptRule(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !*response.Rule.Enabled {\n\t\t\treturn fmt.Errorf(\"Enabled (%v) was not set to true\", *response.Rule.Enabled)\n\t\t}\n\n\t\tif !reflect.DeepEqual(response.Rule.Recipients, []*string{aws.String(\"test@example.com\")}) {\n\t\t\treturn fmt.Errorf(\"Recipients (%v) was not set to [test@example.com]\", response.Rule.Recipients)\n\t\t}\n\n\t\tif !*response.Rule.ScanEnabled {\n\t\t\treturn fmt.Errorf(\"ScanEnabled (%v) was not set to true\", *response.Rule.ScanEnabled)\n\t\t}\n\n\t\tif *response.Rule.TlsPolicy != \"Require\" {\n\t\t\treturn fmt.Errorf(\"TLS Policy (%s) was not set to Require\", *response.Rule.TlsPolicy)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckAwsSESReceiptRuleOrder(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"SES Receipt Rule not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"SES Receipt Rule name not set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).sesConn\n\n\t\tparams := &ses.DescribeReceiptRuleSetInput{\n\t\t\tRuleSetName: aws.String(fmt.Sprintf(\"test-me-%d\", srrsRandomInt)),\n\t\t}\n\n\t\tresponse, err := conn.DescribeReceiptRuleSet(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(response.Rules) != 2 {\n\t\t\treturn fmt.Errorf(\"Number of rules (%d) was not equal to 2\", len(response.Rules))\n\t\t} else if *response.Rules[0].Name != \"first\" || *response.Rules[1].Name != \"second\" {\n\t\t\treturn fmt.Errorf(\"Order of rules (%v) was incorrect\", response.Rules)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckAwsSESReceiptRuleActions(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"SES Receipt Rule not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"SES Receipt Rule name not set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).sesConn\n\n\t\tparams := &ses.DescribeReceiptRuleInput{\n\t\t\tRuleName:    aws.String(\"actions4\"),\n\t\t\tRuleSetName: aws.String(fmt.Sprintf(\"test-me-%d\", srrsRandomInt)),\n\t\t}\n\n\t\tresponse, err := conn.DescribeReceiptRule(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tactions := response.Rule.Actions\n\n\t\tif len(actions) != 3 {\n\t\t\treturn fmt.Errorf(\"Number of rules (%d) was not equal to 3\", len(actions))\n\t\t}\n\n\t\taddHeaderAction := actions[0].AddHeaderAction\n\t\tif *addHeaderAction.HeaderName != \"Another-Header\" {\n\t\t\treturn fmt.Errorf(\"Header Name (%s) was not equal to Another-Header\", *addHeaderAction.HeaderName)\n\t\t}\n\n\t\tif *addHeaderAction.HeaderValue != \"First\" {\n\t\t\treturn fmt.Errorf(\"Header Value (%s) was not equal to First\", *addHeaderAction.HeaderValue)\n\t\t}\n\n\t\tsecondAddHeaderAction := actions[1].AddHeaderAction\n\t\tif *secondAddHeaderAction.HeaderName != \"Added-By\" {\n\t\t\treturn fmt.Errorf(\"Header Name (%s) was not equal to Added-By\", *secondAddHeaderAction.HeaderName)\n\t\t}\n\n\t\tif *secondAddHeaderAction.HeaderValue != \"Terraform\" {\n\t\t\treturn fmt.Errorf(\"Header Value (%s) was not equal to Terraform\", *secondAddHeaderAction.HeaderValue)\n\t\t}\n\n\t\tstopAction := actions[2].StopAction\n\t\tif *stopAction.Scope != \"RuleSet\" {\n\t\t\treturn fmt.Errorf(\"Scope (%s) was not equal to RuleSet\", *stopAction.Scope)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nvar srrsRandomInt = acctest.RandInt()\nvar testAccAWSSESReceiptRuleBasicConfig = fmt.Sprintf(`\nresource \"aws_ses_receipt_rule_set\" \"test\" {\n    rule_set_name = \"test-me-%d\"\n}\n\nresource \"aws_ses_receipt_rule\" \"basic\" {\n    name = \"basic\"\n    rule_set_name = \"${aws_ses_receipt_rule_set.test.rule_set_name}\"\n    recipients = [\"test@example.com\"]\n    enabled = true\n    scan_enabled = true\n    tls_policy = \"Require\"\n}\n`, srrsRandomInt)\n\nvar testAccAWSSESReceiptRuleOrderConfig = fmt.Sprintf(`\nresource \"aws_ses_receipt_rule_set\" \"test\" {\n    rule_set_name = \"test-me-%d\"\n}\n\nresource \"aws_ses_receipt_rule\" \"second\" {\n    name = \"second\"\n    rule_set_name = \"${aws_ses_receipt_rule_set.test.rule_set_name}\"\n    after = \"${aws_ses_receipt_rule.first.name}\"\n}\n\nresource \"aws_ses_receipt_rule\" \"first\" {\n    name = \"first\"\n    rule_set_name = \"${aws_ses_receipt_rule_set.test.rule_set_name}\"\n}\n`, srrsRandomInt)\n\nvar testAccAWSSESReceiptRuleActionsConfig = fmt.Sprintf(`\nresource \"aws_s3_bucket\" \"emails\" {\n    bucket = \"ses-terraform-emails\"\n}\n\nresource \"aws_ses_receipt_rule_set\" \"test\" {\n    rule_set_name = \"test-me-%d\"\n}\n\nresource \"aws_ses_receipt_rule\" \"actions\" {\n    name = \"actions4\"\n    rule_set_name = \"${aws_ses_receipt_rule_set.test.rule_set_name}\"\n\n    add_header_action {\n\t\t\theader_name = \"Added-By\"\n\t\t\theader_value = \"Terraform\"\n\t\t\tposition = 1\n    }\n\n    add_header_action {\n\t\t\theader_name = \"Another-Header\"\n\t\t\theader_value = \"First\"\n\t\t\tposition = 0\n    }\n\n    stop_action {\n\t\t\tscope = \"RuleSet\"\n\t\t\tposition = 2\n    }\n}\n`, srrsRandomInt)\n<commit_msg>provider\/aws: Fix test config for SES Receipt Rule (#14383)<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ses\"\n\t\"github.com\/hashicorp\/terraform\/helper\/acctest\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nfunc TestAccAWSSESReceiptRule_basic(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() {\n\t\t\ttestAccPreCheck(t)\n\t\t},\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckSESReceiptRuleDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSSESReceiptRuleBasicConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAwsSESReceiptRuleExists(\"aws_ses_receipt_rule.basic\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSSESReceiptRule_order(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() {\n\t\t\ttestAccPreCheck(t)\n\t\t},\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckSESReceiptRuleDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSSESReceiptRuleOrderConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAwsSESReceiptRuleOrder(\"aws_ses_receipt_rule.second\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSSESReceiptRule_actions(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() {\n\t\t\ttestAccPreCheck(t)\n\t\t},\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckSESReceiptRuleDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSSESReceiptRuleActionsConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAwsSESReceiptRuleActions(\"aws_ses_receipt_rule.actions\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckSESReceiptRuleDestroy(s *terraform.State) error {\n\tconn := testAccProvider.Meta().(*AWSClient).sesConn\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_ses_receipt_rule\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tparams := &ses.DescribeReceiptRuleInput{\n\t\t\tRuleName:    aws.String(rs.Primary.Attributes[\"name\"]),\n\t\t\tRuleSetName: aws.String(rs.Primary.Attributes[\"rule_set_name\"]),\n\t\t}\n\n\t\t_, err := conn.DescribeReceiptRule(params)\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"Receipt rule %s still exists. Failing!\", rs.Primary.ID)\n\t\t}\n\n\t\t\/\/ Verify the error is what we want\n\t\t_, ok := err.(awserr.Error)\n\t\tif !ok {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n\n}\n\nfunc testAccCheckAwsSESReceiptRuleExists(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"SES Receipt Rule not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"SES Receipt Rule name not set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).sesConn\n\n\t\tparams := &ses.DescribeReceiptRuleInput{\n\t\t\tRuleName:    aws.String(\"basic\"),\n\t\t\tRuleSetName: aws.String(fmt.Sprintf(\"test-me-%d\", srrsRandomInt)),\n\t\t}\n\n\t\tresponse, err := conn.DescribeReceiptRule(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !*response.Rule.Enabled {\n\t\t\treturn fmt.Errorf(\"Enabled (%v) was not set to true\", *response.Rule.Enabled)\n\t\t}\n\n\t\tif !reflect.DeepEqual(response.Rule.Recipients, []*string{aws.String(\"test@example.com\")}) {\n\t\t\treturn fmt.Errorf(\"Recipients (%v) was not set to [test@example.com]\", response.Rule.Recipients)\n\t\t}\n\n\t\tif !*response.Rule.ScanEnabled {\n\t\t\treturn fmt.Errorf(\"ScanEnabled (%v) was not set to true\", *response.Rule.ScanEnabled)\n\t\t}\n\n\t\tif *response.Rule.TlsPolicy != \"Require\" {\n\t\t\treturn fmt.Errorf(\"TLS Policy (%s) was not set to Require\", *response.Rule.TlsPolicy)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckAwsSESReceiptRuleOrder(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"SES Receipt Rule not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"SES Receipt Rule name not set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).sesConn\n\n\t\tparams := &ses.DescribeReceiptRuleSetInput{\n\t\t\tRuleSetName: aws.String(fmt.Sprintf(\"test-me-%d\", srrsRandomInt)),\n\t\t}\n\n\t\tresponse, err := conn.DescribeReceiptRuleSet(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(response.Rules) != 2 {\n\t\t\treturn fmt.Errorf(\"Number of rules (%d) was not equal to 2\", len(response.Rules))\n\t\t} else if *response.Rules[0].Name != \"first\" || *response.Rules[1].Name != \"second\" {\n\t\t\treturn fmt.Errorf(\"Order of rules (%v) was incorrect\", response.Rules)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckAwsSESReceiptRuleActions(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"SES Receipt Rule not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"SES Receipt Rule name not set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).sesConn\n\n\t\tparams := &ses.DescribeReceiptRuleInput{\n\t\t\tRuleName:    aws.String(\"actions4\"),\n\t\t\tRuleSetName: aws.String(fmt.Sprintf(\"test-me-%d\", srrsRandomInt)),\n\t\t}\n\n\t\tresponse, err := conn.DescribeReceiptRule(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tactions := response.Rule.Actions\n\n\t\tif len(actions) != 3 {\n\t\t\treturn fmt.Errorf(\"Number of rules (%d) was not equal to 3\", len(actions))\n\t\t}\n\n\t\taddHeaderAction := actions[0].AddHeaderAction\n\t\tif *addHeaderAction.HeaderName != \"Another-Header\" {\n\t\t\treturn fmt.Errorf(\"Header Name (%s) was not equal to Another-Header\", *addHeaderAction.HeaderName)\n\t\t}\n\n\t\tif *addHeaderAction.HeaderValue != \"First\" {\n\t\t\treturn fmt.Errorf(\"Header Value (%s) was not equal to First\", *addHeaderAction.HeaderValue)\n\t\t}\n\n\t\tsecondAddHeaderAction := actions[1].AddHeaderAction\n\t\tif *secondAddHeaderAction.HeaderName != \"Added-By\" {\n\t\t\treturn fmt.Errorf(\"Header Name (%s) was not equal to Added-By\", *secondAddHeaderAction.HeaderName)\n\t\t}\n\n\t\tif *secondAddHeaderAction.HeaderValue != \"Terraform\" {\n\t\t\treturn fmt.Errorf(\"Header Value (%s) was not equal to Terraform\", *secondAddHeaderAction.HeaderValue)\n\t\t}\n\n\t\tstopAction := actions[2].StopAction\n\t\tif *stopAction.Scope != \"RuleSet\" {\n\t\t\treturn fmt.Errorf(\"Scope (%s) was not equal to RuleSet\", *stopAction.Scope)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nvar srrsRandomInt = acctest.RandInt()\nvar testAccAWSSESReceiptRuleBasicConfig = fmt.Sprintf(`\nresource \"aws_ses_receipt_rule_set\" \"test\" {\n    rule_set_name = \"test-me-%d\"\n}\n\nresource \"aws_ses_receipt_rule\" \"basic\" {\n    name = \"basic\"\n    rule_set_name = \"${aws_ses_receipt_rule_set.test.rule_set_name}\"\n    recipients = [\"test@example.com\"]\n    enabled = true\n    scan_enabled = true\n    tls_policy = \"Require\"\n}\n`, srrsRandomInt)\n\nvar testAccAWSSESReceiptRuleOrderConfig = fmt.Sprintf(`\nresource \"aws_ses_receipt_rule_set\" \"test\" {\n    rule_set_name = \"test-me-%d\"\n}\n\nresource \"aws_ses_receipt_rule\" \"second\" {\n    name = \"second\"\n    rule_set_name = \"${aws_ses_receipt_rule_set.test.rule_set_name}\"\n    after = \"${aws_ses_receipt_rule.first.name}\"\n}\n\nresource \"aws_ses_receipt_rule\" \"first\" {\n    name = \"first\"\n    rule_set_name = \"${aws_ses_receipt_rule_set.test.rule_set_name}\"\n}\n`, srrsRandomInt)\n\nvar testAccAWSSESReceiptRuleActionsConfig = fmt.Sprintf(`\nresource \"aws_s3_bucket\" \"emails\" {\n    bucket = \"ses-terraform-emails\"\n}\n\nresource \"aws_ses_receipt_rule_set\" \"test\" {\n    rule_set_name = \"test-me-%d\"\n}\n\nresource \"aws_ses_receipt_rule\" \"actions\" {\n    name = \"actions4\"\n    rule_set_name = \"${aws_ses_receipt_rule_set.test.rule_set_name}\"\n\n    add_header_action {\n\t\t\theader_name = \"Added-By\"\n\t\t\theader_value = \"Terraform\"\n\t\t\tposition = 2\n    }\n\n    add_header_action {\n\t\t\theader_name = \"Another-Header\"\n\t\t\theader_value = \"First\"\n\t\t\tposition = 1\n    }\n\n    stop_action {\n\t\t\tscope = \"RuleSet\"\n\t\t\tposition = 3\n    }\n}\n`, srrsRandomInt)\n<|endoftext|>"}
{"text":"<commit_before>package handlers\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/DVI-GI-2017\/Jira__backend\/db\"\n\t\"github.com\/DVI-GI-2017\/Jira__backend\/tools\"\n)\n\nfunc AllUsers(w http.ResponseWriter, getParams map[string]string, pathParams map[string]string) {\n\ttools.JsonResponse(db.FakeUsers, w)\n}\n<commit_msg>Update all users route.<commit_after>package handlers\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/DVI-GI-2017\/Jira__backend\/db\"\n\t\"github.com\/DVI-GI-2017\/Jira__backend\/tools\"\n)\n\nfunc AllUsers(w http.ResponseWriter, _ *http.Request) {\n\ttools.JsonResponse(db.FakeUsers, w)\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Log port being listened on<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Update Fetcher comment<commit_after><|endoftext|>"}
{"text":"<commit_before>package docker_test\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\t\"github.com\/onsi\/gomega\/ghttp\"\n)\n\nvar _ = Describe(\"Building\", func() {\n\tvar (\n\t\tbuilderCmd                 *exec.Cmd\n\t\tdockerRef                  string\n\t\tdockerImageURL             string\n\t\tdockerRegistryHost         string\n\t\tdockerRegistryPort         string\n\t\tdockerRegistryIPs          string\n\t\tinsecureDockerRegistries   string\n\t\tdockerDaemonExecutablePath string\n\t\tcacheDockerImage           bool\n\t\tdockerLoginServer          string\n\t\tdockerUser                 string\n\t\tdockerPassword             string\n\t\tdockerEmail                string\n\t\toutputMetadataDir          string\n\t\toutputMetadataJSONFilename string\n\t\tfakeDockerRegistry         *ghttp.Server\n\t)\n\n\tsetupBuilder := func() *gexec.Session {\n\t\tsession, err := gexec.Start(\n\t\t\tbuilderCmd,\n\t\t\tGinkgoWriter,\n\t\t\tGinkgoWriter,\n\t\t)\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\treturn session\n\t}\n\n\tsetupFakeDockerRegistry := func() {\n\t\tfakeDockerRegistry.AppendHandlers(\n\t\t\tghttp.VerifyRequest(\"GET\", \"\/v1\/_ping\"),\n\t\t\tghttp.CombineHandlers(\n\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/v1\/repositories\/some-repo\/images\"),\n\t\t\t\thttp.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\t\t\tw.Header().Set(\"X-Docker-Token\", \"token-1,token-2\")\n\t\t\t\t\tw.Write([]byte(`[\n                            {\"id\": \"id-1\", \"checksum\": \"sha-1\"},\n                            {\"id\": \"id-2\", \"checksum\": \"sha-2\"},\n                            {\"id\": \"id-3\", \"checksum\": \"sha-3\"}\n                        ]`))\n\t\t\t\t}),\n\t\t\t),\n\t\t)\n\n\t\tfakeDockerRegistry.AppendHandlers(\n\t\t\tghttp.CombineHandlers(\n\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/v1\/repositories\/library\/some-repo\/tags\"),\n\t\t\t\thttp.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\t\t\tw.Write([]byte(`{\n                            \"latest\": \"id-1\",\n                            \"some-other-tag\": \"id-2\"\n                        }`))\n\t\t\t\t}),\n\t\t\t),\n\t\t)\n\t}\n\n\tBeforeEach(func() {\n\t\tvar err error\n\n\t\tdockerRef = \"\"\n\t\tdockerImageURL = \"\"\n\t\tdockerRegistryHost = \"\"\n\t\tdockerRegistryPort = \"\"\n\t\tdockerRegistryIPs = \"\"\n\t\tinsecureDockerRegistries = \"\"\n\t\tdockerDaemonExecutablePath = \"\/usr\/bin\/docker\"\n\t\tcacheDockerImage = true\n\t\tdockerLoginServer = \"\"\n\t\tdockerUser = \"\"\n\t\tdockerPassword = \"\"\n\t\tdockerEmail = \"\"\n\n\t\toutputMetadataDir, err = ioutil.TempDir(\"\", \"building-result\")\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\toutputMetadataJSONFilename = path.Join(outputMetadataDir, \"result.json\")\n\n\t\tfakeDockerRegistry = ghttp.NewServer()\n\t})\n\n\tJustBeforeEach(func() {\n\t\targs := []string{\"-dockerDaemonExecutablePath\", dockerDaemonExecutablePath,\n\t\t\t\"-outputMetadataJSONFilename\", outputMetadataJSONFilename}\n\n\t\tif len(dockerImageURL) > 0 {\n\t\t\targs = append(args, \"-dockerImageURL\", dockerImageURL)\n\t\t}\n\t\tif len(dockerRef) > 0 {\n\t\t\targs = append(args, \"-dockerRef\", dockerRef)\n\t\t}\n\t\tif len(dockerRegistryHost) > 0 {\n\t\t\targs = append(args, \"-dockerRegistryHost\", dockerRegistryHost)\n\t\t}\n\t\tif len(dockerRegistryPort) > 0 {\n\t\t\targs = append(args, \"-dockerRegistryPort\", dockerRegistryPort)\n\t\t}\n\t\tif len(dockerRegistryIPs) > 0 {\n\t\t\targs = append(args, \"-dockerRegistryIPs\", dockerRegistryIPs)\n\t\t}\n\t\tif len(insecureDockerRegistries) > 0 {\n\t\t\targs = append(args, \"-insecureDockerRegistries\", insecureDockerRegistries)\n\t\t}\n\t\tif cacheDockerImage {\n\t\t\targs = append(args, \"-cacheDockerImage\")\n\t\t}\n\t\tif len(dockerLoginServer) > 0 {\n\t\t\targs = append(args, \"-dockerLoginServer\", dockerLoginServer)\n\t\t}\n\t\tif len(dockerUser) > 0 {\n\t\t\targs = append(args, \"-dockerUser\", dockerUser)\n\t\t}\n\t\tif len(dockerPassword) > 0 {\n\t\t\targs = append(args, \"-dockerPassword\", dockerPassword)\n\t\t}\n\t\tif len(dockerEmail) > 0 {\n\t\t\targs = append(args, \"-dockerEmail\", dockerEmail)\n\t\t}\n\n\t\tbuilderCmd = exec.Command(builderPath, args...)\n\n\t\tbuilderCmd.Env = os.Environ()\n\t})\n\n\tbuildDockerImageURL := func() string {\n\t\tparts, err := url.Parse(fakeDockerRegistry.URL())\n\t\tExpect(err).NotTo(HaveOccurred())\n\t\treturn fmt.Sprintf(\"docker:\/\/%s\/some-repo\", parts.Host)\n\t}\n\n\tdockerPidExists := func() bool {\n\t\t_, err := os.Stat(\"\/var\/run\/docker.pid\")\n\t\treturn err == nil\n\t}\n\n\tContext(\"when running the main\", func() {\n\t\tvar session *gexec.Session\n\n\t\tBeforeEach(func() {\n\t\t\tdockerImageURL = buildDockerImageURL()\n\n\t\t\tdockerRegistryHost = \"docker-registry.service.cf.internal\"\n\t\t\tdockerRegistryPort = \"8080\"\n\n\t\t\tparts, err := url.Parse(fakeDockerRegistry.URL())\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tip, _, err := net.SplitHostPort(parts.Host)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tdockerRegistryIPs = ip\n\n\t\t\tsetupFakeDockerRegistry()\n\t\t\tfakeDockerRegistry.AppendHandlers(\n\t\t\t\tghttp.CombineHandlers(\n\t\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/v1\/images\/id-1\/json\"),\n\t\t\t\t\thttp.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\t\t\t\tw.Header().Add(\"X-Docker-Size\", \"789\")\n\t\t\t\t\t\tw.Write([]byte(`{\"id\":\"layer-1\",\"parent\":\"parent-1\",\"Config\":{\"Cmd\":[\"-bazbot\",\"-foobar\"],\"Entrypoint\":[\"\/dockerapp\",\"-t\"],\"WorkingDir\":\"\/workdir\"}}`))\n\n\t\t\t\t\t\t\/\/ give the tests time to send signals, while the builder is \"working\"\n\t\t\t\t\t\ttime.Sleep(2 * time.Second)\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t)\n\t\t})\n\n\t\tJustBeforeEach(func() {\n\t\t\tsession = setupBuilder()\n\t\t\tEventually(session.Out, 30).Should(gbytes.Say(\"Staging process started ...\"))\n\t\t})\n\n\t\tAfterEach(func() {\n\t\t\tEventually(dockerPidExists).Should(BeFalse())\n\t\t\tos.RemoveAll(outputMetadataDir)\n\t\t})\n\n\t\tContext(\"when signalled\", func() {\n\t\t\tContext(\"and builder is interrupted\", func() {\n\t\t\t\tJustBeforeEach(func() {\n\t\t\t\t\tsession.Interrupt()\n\t\t\t\t})\n\n\t\t\t\tIt(\"processes the signal and exits\", func() {\n\t\t\t\t\tEventually(session).Should(gexec.Exit(2))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"and docker is killed\", func() {\n\t\t\t\tJustBeforeEach(func() {\n\t\t\t\t\tcmd := exec.Command(\"\/usr\/bin\/killall\", \"docker\")\n\t\t\t\t\tcmd.Env = os.Environ()\n\t\t\t\t\terr := cmd.Run()\n\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\tos.Remove(\"\/var\/run\/docker.sock\")\n\t\t\t\t})\n\n\t\t\t\tIt(\"processes the signal and exits\", func() {\n\t\t\t\t\tEventually(session).Should(gexec.Exit(2))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when started\", func() {\n\t\t\tAfterEach(func() {\n\t\t\t\tsession.Interrupt()\n\t\t\t\tEventually(session).Should(gexec.Exit(2))\n\t\t\t})\n\n\t\t\tIt(\"creates \/etc\/hosts entry\", func() {\n\t\t\t\thostsContent, err := ioutil.ReadFile(\"\/etc\/hosts\")\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tExpect(hostsContent).To(ContainSubstring(\"%s %s\\n\", dockerRegistryIPs, dockerRegistryHost))\n\t\t\t})\n\t\t})\n\t})\n})\n<commit_msg>use only dockerRef for docker app lifecycle<commit_after>package docker_test\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\t\"github.com\/onsi\/gomega\/ghttp\"\n)\n\nvar _ = Describe(\"Building\", func() {\n\tvar (\n\t\tbuilderCmd                 *exec.Cmd\n\t\tdockerRef                  string\n\t\tdockerRegistryHost         string\n\t\tdockerRegistryPort         string\n\t\tdockerRegistryIPs          string\n\t\tinsecureDockerRegistries   string\n\t\tdockerDaemonExecutablePath string\n\t\tcacheDockerImage           bool\n\t\tdockerLoginServer          string\n\t\tdockerUser                 string\n\t\tdockerPassword             string\n\t\tdockerEmail                string\n\t\toutputMetadataDir          string\n\t\toutputMetadataJSONFilename string\n\t\tfakeDockerRegistry         *ghttp.Server\n\t)\n\n\tsetupBuilder := func() *gexec.Session {\n\t\tsession, err := gexec.Start(\n\t\t\tbuilderCmd,\n\t\t\tGinkgoWriter,\n\t\t\tGinkgoWriter,\n\t\t)\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\treturn session\n\t}\n\n\tsetupFakeDockerRegistry := func() {\n\t\tfakeDockerRegistry.AppendHandlers(\n\t\t\tghttp.VerifyRequest(\"GET\", \"\/v1\/_ping\"),\n\t\t\tghttp.CombineHandlers(\n\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/v1\/repositories\/some-repo\/images\"),\n\t\t\t\thttp.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\t\t\tw.Header().Set(\"X-Docker-Token\", \"token-1,token-2\")\n\t\t\t\t\tw.Write([]byte(`[\n                            {\"id\": \"id-1\", \"checksum\": \"sha-1\"},\n                            {\"id\": \"id-2\", \"checksum\": \"sha-2\"},\n                            {\"id\": \"id-3\", \"checksum\": \"sha-3\"}\n                        ]`))\n\t\t\t\t}),\n\t\t\t),\n\t\t)\n\n\t\tfakeDockerRegistry.AppendHandlers(\n\t\t\tghttp.CombineHandlers(\n\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/v1\/repositories\/library\/some-repo\/tags\"),\n\t\t\t\thttp.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\t\t\tw.Write([]byte(`{\n                            \"latest\": \"id-1\",\n                            \"some-other-tag\": \"id-2\"\n                        }`))\n\t\t\t\t}),\n\t\t\t),\n\t\t)\n\t}\n\n\tBeforeEach(func() {\n\t\tvar err error\n\n\t\tdockerRef = \"\"\n\t\tdockerRegistryHost = \"\"\n\t\tdockerRegistryPort = \"\"\n\t\tdockerRegistryIPs = \"\"\n\t\tinsecureDockerRegistries = \"\"\n\t\tdockerDaemonExecutablePath = \"\/usr\/bin\/docker\"\n\t\tcacheDockerImage = true\n\t\tdockerLoginServer = \"\"\n\t\tdockerUser = \"\"\n\t\tdockerPassword = \"\"\n\t\tdockerEmail = \"\"\n\n\t\toutputMetadataDir, err = ioutil.TempDir(\"\", \"building-result\")\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\toutputMetadataJSONFilename = path.Join(outputMetadataDir, \"result.json\")\n\n\t\tfakeDockerRegistry = ghttp.NewServer()\n\t})\n\n\tJustBeforeEach(func() {\n\t\targs := []string{\"-dockerDaemonExecutablePath\", dockerDaemonExecutablePath,\n\t\t\t\"-outputMetadataJSONFilename\", outputMetadataJSONFilename}\n\n\t\tif len(dockerRef) > 0 {\n\t\t\targs = append(args, \"-dockerRef\", dockerRef)\n\t\t}\n\t\tif len(dockerRegistryHost) > 0 {\n\t\t\targs = append(args, \"-dockerRegistryHost\", dockerRegistryHost)\n\t\t}\n\t\tif len(dockerRegistryPort) > 0 {\n\t\t\targs = append(args, \"-dockerRegistryPort\", dockerRegistryPort)\n\t\t}\n\t\tif len(dockerRegistryIPs) > 0 {\n\t\t\targs = append(args, \"-dockerRegistryIPs\", dockerRegistryIPs)\n\t\t}\n\t\tif len(insecureDockerRegistries) > 0 {\n\t\t\targs = append(args, \"-insecureDockerRegistries\", insecureDockerRegistries)\n\t\t}\n\t\tif cacheDockerImage {\n\t\t\targs = append(args, \"-cacheDockerImage\")\n\t\t}\n\t\tif len(dockerLoginServer) > 0 {\n\t\t\targs = append(args, \"-dockerLoginServer\", dockerLoginServer)\n\t\t}\n\t\tif len(dockerUser) > 0 {\n\t\t\targs = append(args, \"-dockerUser\", dockerUser)\n\t\t}\n\t\tif len(dockerPassword) > 0 {\n\t\t\targs = append(args, \"-dockerPassword\", dockerPassword)\n\t\t}\n\t\tif len(dockerEmail) > 0 {\n\t\t\targs = append(args, \"-dockerEmail\", dockerEmail)\n\t\t}\n\n\t\tbuilderCmd = exec.Command(builderPath, args...)\n\n\t\tbuilderCmd.Env = os.Environ()\n\t})\n\n\tbuildDockerRef := func() string {\n\t\tparts, err := url.Parse(fakeDockerRegistry.URL())\n\t\tExpect(err).NotTo(HaveOccurred())\n\t\treturn fmt.Sprintf(\"%s\/some-repo\", parts.Host)\n\t}\n\n\tdockerPidExists := func() bool {\n\t\t_, err := os.Stat(\"\/var\/run\/docker.pid\")\n\t\treturn err == nil\n\t}\n\n\tContext(\"when running the main\", func() {\n\t\tvar session *gexec.Session\n\n\t\tBeforeEach(func() {\n\t\t\tdockerRef = buildDockerRef()\n\n\t\t\tdockerRegistryHost = \"docker-registry.service.cf.internal\"\n\t\t\tdockerRegistryPort = \"8080\"\n\n\t\t\tparts, err := url.Parse(fakeDockerRegistry.URL())\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tip, _, err := net.SplitHostPort(parts.Host)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tdockerRegistryIPs = ip\n\n\t\t\tsetupFakeDockerRegistry()\n\t\t\tfakeDockerRegistry.AppendHandlers(\n\t\t\t\tghttp.CombineHandlers(\n\t\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/v1\/images\/id-1\/json\"),\n\t\t\t\t\thttp.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\t\t\t\tw.Header().Add(\"X-Docker-Size\", \"789\")\n\t\t\t\t\t\tw.Write([]byte(`{\"id\":\"layer-1\",\"parent\":\"parent-1\",\"Config\":{\"Cmd\":[\"-bazbot\",\"-foobar\"],\"Entrypoint\":[\"\/dockerapp\",\"-t\"],\"WorkingDir\":\"\/workdir\"}}`))\n\n\t\t\t\t\t\t\/\/ give the tests time to send signals, while the builder is \"working\"\n\t\t\t\t\t\ttime.Sleep(2 * time.Second)\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t)\n\t\t})\n\n\t\tJustBeforeEach(func() {\n\t\t\tsession = setupBuilder()\n\t\t\tEventually(session.Out, 30).Should(gbytes.Say(\"Staging process started ...\"))\n\t\t})\n\n\t\tAfterEach(func() {\n\t\t\tEventually(dockerPidExists).Should(BeFalse())\n\t\t\tos.RemoveAll(outputMetadataDir)\n\t\t})\n\n\t\tContext(\"when signalled\", func() {\n\t\t\tContext(\"and builder is interrupted\", func() {\n\t\t\t\tJustBeforeEach(func() {\n\t\t\t\t\tsession.Interrupt()\n\t\t\t\t})\n\n\t\t\t\tIt(\"processes the signal and exits\", func() {\n\t\t\t\t\tEventually(session).Should(gexec.Exit(2))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"and docker is killed\", func() {\n\t\t\t\tJustBeforeEach(func() {\n\t\t\t\t\tcmd := exec.Command(\"\/usr\/bin\/killall\", \"docker\")\n\t\t\t\t\tcmd.Env = os.Environ()\n\t\t\t\t\terr := cmd.Run()\n\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\tos.Remove(\"\/var\/run\/docker.sock\")\n\t\t\t\t})\n\n\t\t\t\tIt(\"processes the signal and exits\", func() {\n\t\t\t\t\tEventually(session).Should(gexec.Exit(2))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when started\", func() {\n\t\t\tAfterEach(func() {\n\t\t\t\tsession.Interrupt()\n\t\t\t\tEventually(session).Should(gexec.Exit(2))\n\t\t\t})\n\n\t\t\tIt(\"creates \/etc\/hosts entry\", func() {\n\t\t\t\thostsContent, err := ioutil.ReadFile(\"\/etc\/hosts\")\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tExpect(hostsContent).To(ContainSubstring(\"%s %s\\n\", dockerRegistryIPs, dockerRegistryHost))\n\t\t\t})\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package ike\n\nimport (\n\t\"github.com\/msgboxio\/ike\/protocol\"\n\t\"github.com\/pkg\/errors\"\n)\n\ntype InfoParams struct {\n\tIsInitiator bool\n\tIsResponse  bool\n\tSpiI, SpiR  protocol.Spi\n\tPayload     protocol.Payload\n}\n\ntype SessionNotificationType int\n\nconst (\n\tMSG_DELETE_IKE_SA SessionNotificationType = iota\n\tMSG_DELETE_ESP_SA\n\tMSG_EMPTY_REQUEST\n\tMSG_EMPTY_RESPONSE\n\tMSG_ERROR\n)\n\ntype InformationalEvent struct {\n\tSessionNotificationType\n\tMessage interface{}\n}\n\n\/\/ INFORMATIONAL\n\/\/ b<-a\n\/\/  HDR(SPIi=xxx, SPIr=yyy, INFORMATIONAL, Flags: none, Message ID=m),\n\/\/  SK {...}\n\/\/ a<-b\n\/\/ \tHDR(SPIi=xxx, SPIr=yyy, INFORMATIONAL, Flags: Initiator | Response, Message ID=m),\n\/\/  SK {}\n\/\/ Notification, Delete, and Configuration Payloads\n\/\/ Must be replied to\nfunc makeInformational(p InfoParams) *Message {\n\tvar flags protocol.IkeFlags\n\tif p.IsResponse {\n\t\tflags |= protocol.RESPONSE\n\t}\n\tif p.IsInitiator {\n\t\tflags |= protocol.INITIATOR\n\t}\n\tinfo := &Message{\n\t\tIkeHeader: &protocol.IkeHeader{\n\t\t\tSpiI:         p.SpiI,\n\t\t\tSpiR:         p.SpiR,\n\t\t\tNextPayload:  protocol.PayloadTypeSK,\n\t\t\tMajorVersion: protocol.IKEV2_MAJOR_VERSION,\n\t\t\tMinorVersion: protocol.IKEV2_MINOR_VERSION,\n\t\t\tExchangeType: protocol.INFORMATIONAL,\n\t\t\tFlags:        flags,\n\t\t},\n\t\tPayloads: protocol.MakePayloads(),\n\t}\n\tif p.Payload != nil {\n\t\tinfo.Payloads.Add(p.Payload)\n\t}\n\treturn info\n}\n\n\/\/ NotifyFromSession builds a Notification Request\nfunc NotifyFromSession(sess *Session, ie protocol.IkeErrorCode, isResponse bool) *Message {\n\tspi := sess.IkeSpiI\n\tif sess.isInitiator {\n\t\tspi = sess.IkeSpiR\n\t}\n\treturn makeInformational(InfoParams{\n\t\tIsInitiator: sess.isInitiator,\n\t\tIsResponse:  isResponse,\n\t\tSpiI:        sess.IkeSpiI,\n\t\tSpiR:        sess.IkeSpiR,\n\t\tPayload: &protocol.NotifyPayload{\n\t\t\tPayloadHeader:    &protocol.PayloadHeader{},\n\t\t\tProtocolId:       protocol.IKE,\n\t\t\tNotificationType: protocol.NotificationType(ie),\n\t\t\tSpi:              spi,\n\t\t},\n\t})\n}\n\n\/\/ DeleteFromSession builds an IKE delete Request\nfunc DeleteFromSession(sess *Session) *Message {\n\t\/\/ ike protocol ID, but no spi\n\t\/\/ always a request\n\treturn makeInformational(InfoParams{\n\t\tIsInitiator: sess.isInitiator,\n\t\tSpiI:        sess.IkeSpiI,\n\t\tSpiR:        sess.IkeSpiR,\n\t\tPayload: &protocol.DeletePayload{\n\t\t\tPayloadHeader: &protocol.PayloadHeader{},\n\t\t\tProtocolId:    protocol.IKE,\n\t\t\tSpis:          []protocol.Spi{},\n\t\t},\n\t})\n}\n\n\/\/ EmptyFromSession can build an empty Request or a Response\nfunc EmptyFromSession(sess *Session, isResponse bool) *Message {\n\treturn makeInformational(InfoParams{\n\t\tIsInitiator: sess.isInitiator,\n\t\tIsResponse:  isResponse,\n\t\tSpiI:        sess.IkeSpiI,\n\t\tSpiR:        sess.IkeSpiR,\n\t})\n}\n\nfunc HandleInformationalForSession(sess *Session, msg *Message) *InformationalEvent {\n\tplds := msg.Payloads\n\t\/\/ Empty\n\tif len(plds.Array) == 0 {\n\t\tevt := MSG_EMPTY_REQUEST\n\t\tif msg.IkeHeader.Flags.IsResponse() {\n\t\t\tevt = MSG_EMPTY_RESPONSE\n\t\t}\n\t\treturn &InformationalEvent{\n\t\t\tSessionNotificationType: evt,\n\t\t}\n\t}\n\t\/\/ Delete\n\tif del := plds.Get(protocol.PayloadTypeD); del != nil {\n\t\tdp := del.(*protocol.DeletePayload)\n\t\tif dp.ProtocolId == protocol.IKE {\n\t\t\treturn &InformationalEvent{\n\t\t\t\tSessionNotificationType: MSG_DELETE_IKE_SA,\n\t\t\t\tMessage:                 errors.Wrapf(errPeerRemovedIkeSa, \"SA: %#x\", msg.IkeHeader.SpiI),\n\t\t\t}\n\t\t}\n\t\tfor _, spi := range dp.Spis {\n\t\t\tif dp.ProtocolId == protocol.ESP {\n\t\t\t\tsess.Logger.Log(\"msg\", \"Peer removed ESP SA\", \"spi\", spi)\n\t\t\t\treturn &InformationalEvent{\n\t\t\t\t\tSessionNotificationType: MSG_DELETE_ESP_SA,\n\t\t\t\t\tMessage:                 errors.Wrapf(errPeerRemovedEspSa, \"SA: %#x\", spi),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Notification\n\t\/\/ delete the ike sa if notification is one of following\n\t\/\/ UNSUPPORTED_CRITICAL_PAYLOAD, INVALID_SYNTAX, an AUTHENTICATION_FAILED\n\tif note := plds.Get(protocol.PayloadTypeN); note != nil {\n\t\tnp := note.(*protocol.NotifyPayload)\n\t\tif err, ok := protocol.GetIkeErrorCode(np.NotificationType); ok {\n\t\t\tsess.Logger.Log(\"msg\", \"Received Informational Error\", \"err\", err)\n\t\t\treturn &InformationalEvent{\n\t\t\t\tSessionNotificationType: MSG_ERROR,\n\t\t\t\tMessage:                 err,\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Configuration\n\tif cfg := plds.Get(protocol.PayloadTypeCP); cfg != nil {\n\t\tcp := cfg.(*protocol.ConfigurationPayload)\n\t\tsess.Logger.Log(\"config\", cp)\n\t\t\/\/ TODO\n\t}\n\treturn nil\n}\n<commit_msg>unexport fields<commit_after>package ike\n\nimport (\n\t\"github.com\/msgboxio\/ike\/protocol\"\n\t\"github.com\/pkg\/errors\"\n)\n\ntype infoParams struct {\n\tisInitiator bool\n\tisResponse  bool\n\tspiI, spiR  protocol.Spi\n\tpayload     protocol.Payload\n}\n\ntype SessionNotificationType int\n\nconst (\n\tMSG_DELETE_IKE_SA SessionNotificationType = iota\n\tMSG_DELETE_ESP_SA\n\tMSG_EMPTY_REQUEST\n\tMSG_EMPTY_RESPONSE\n\tMSG_ERROR\n)\n\ntype InformationalEvent struct {\n\tSessionNotificationType\n\tMessage interface{}\n}\n\n\/\/ INFORMATIONAL\n\/\/ b<-a\n\/\/  HDR(SPIi=xxx, SPIr=yyy, INFORMATIONAL, Flags: none, Message ID=m),\n\/\/  SK {...}\n\/\/ a<-b\n\/\/ \tHDR(SPIi=xxx, SPIr=yyy, INFORMATIONAL, Flags: Initiator | Response, Message ID=m),\n\/\/  SK {}\n\/\/ Notification, Delete, and Configuration Payloads\n\/\/ Must be replied to\nfunc makeInformational(p infoParams) *Message {\n\tvar flags protocol.IkeFlags\n\tif p.isResponse {\n\t\tflags |= protocol.RESPONSE\n\t}\n\tif p.isInitiator {\n\t\tflags |= protocol.INITIATOR\n\t}\n\tinfo := &Message{\n\t\tIkeHeader: &protocol.IkeHeader{\n\t\t\tSpiI:         p.spiI,\n\t\t\tSpiR:         p.spiR,\n\t\t\tNextPayload:  protocol.PayloadTypeSK,\n\t\t\tMajorVersion: protocol.IKEV2_MAJOR_VERSION,\n\t\t\tMinorVersion: protocol.IKEV2_MINOR_VERSION,\n\t\t\tExchangeType: protocol.INFORMATIONAL,\n\t\t\tFlags:        flags,\n\t\t},\n\t\tPayloads: protocol.MakePayloads(),\n\t}\n\tif p.payload != nil {\n\t\tinfo.Payloads.Add(p.payload)\n\t}\n\treturn info\n}\n\n\/\/ NotifyFromSession builds a Notification Request\nfunc NotifyFromSession(sess *Session, ie protocol.IkeErrorCode, isResponse bool) *Message {\n\tspi := sess.IkeSpiI\n\tif sess.isInitiator {\n\t\tspi = sess.IkeSpiR\n\t}\n\treturn makeInformational(infoParams{\n\t\tisInitiator: sess.isInitiator,\n\t\tisResponse:  isResponse,\n\t\tspiI:        sess.IkeSpiI,\n\t\tspiR:        sess.IkeSpiR,\n\t\tpayload: &protocol.NotifyPayload{\n\t\t\tPayloadHeader:    &protocol.PayloadHeader{},\n\t\t\tProtocolId:       protocol.IKE,\n\t\t\tNotificationType: protocol.NotificationType(ie),\n\t\t\tSpi:              spi,\n\t\t},\n\t})\n}\n\n\/\/ DeleteFromSession builds an IKE delete Request\nfunc DeleteFromSession(sess *Session) *Message {\n\t\/\/ ike protocol ID, but no spi\n\t\/\/ always a request\n\treturn makeInformational(infoParams{\n\t\tisInitiator: sess.isInitiator,\n\t\tspiI:        sess.IkeSpiI,\n\t\tspiR:        sess.IkeSpiR,\n\t\tpayload: &protocol.DeletePayload{\n\t\t\tPayloadHeader: &protocol.PayloadHeader{},\n\t\t\tProtocolId:    protocol.IKE,\n\t\t\tSpis:          []protocol.Spi{},\n\t\t},\n\t})\n}\n\n\/\/ EmptyFromSession can build an empty Request or a Response\nfunc EmptyFromSession(sess *Session, isResponse bool) *Message {\n\treturn makeInformational(infoParams{\n\t\tisInitiator: sess.isInitiator,\n\t\tisResponse:  isResponse,\n\t\tspiI:        sess.IkeSpiI,\n\t\tspiR:        sess.IkeSpiR,\n\t})\n}\n\nfunc HandleInformationalForSession(sess *Session, msg *Message) *InformationalEvent {\n\tplds := msg.Payloads\n\t\/\/ Empty\n\tif len(plds.Array) == 0 {\n\t\tevt := MSG_EMPTY_REQUEST\n\t\tif msg.IkeHeader.Flags.IsResponse() {\n\t\t\tevt = MSG_EMPTY_RESPONSE\n\t\t}\n\t\treturn &InformationalEvent{\n\t\t\tSessionNotificationType: evt,\n\t\t}\n\t}\n\t\/\/ Delete\n\tif del := plds.Get(protocol.PayloadTypeD); del != nil {\n\t\tdp := del.(*protocol.DeletePayload)\n\t\tif dp.ProtocolId == protocol.IKE {\n\t\t\treturn &InformationalEvent{\n\t\t\t\tSessionNotificationType: MSG_DELETE_IKE_SA,\n\t\t\t\tMessage:                 errors.Wrapf(errPeerRemovedIkeSa, \"SA: %#x\", msg.IkeHeader.SpiI),\n\t\t\t}\n\t\t}\n\t\tfor _, spi := range dp.Spis {\n\t\t\tif dp.ProtocolId == protocol.ESP {\n\t\t\t\tsess.Logger.Log(\"msg\", \"Peer removed ESP SA\", \"spi\", spi)\n\t\t\t\treturn &InformationalEvent{\n\t\t\t\t\tSessionNotificationType: MSG_DELETE_ESP_SA,\n\t\t\t\t\tMessage:                 errors.Wrapf(errPeerRemovedEspSa, \"SA: %#x\", spi),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Notification\n\t\/\/ delete the ike sa if notification is one of following\n\t\/\/ UNSUPPORTED_CRITICAL_PAYLOAD, INVALID_SYNTAX, an AUTHENTICATION_FAILED\n\tif note := plds.Get(protocol.PayloadTypeN); note != nil {\n\t\tnp := note.(*protocol.NotifyPayload)\n\t\tif err, ok := protocol.GetIkeErrorCode(np.NotificationType); ok {\n\t\t\tsess.Logger.Log(\"msg\", \"Received Informational Error\", \"err\", err)\n\t\t\treturn &InformationalEvent{\n\t\t\t\tSessionNotificationType: MSG_ERROR,\n\t\t\t\tMessage:                 err,\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Configuration\n\tif cfg := plds.Get(protocol.PayloadTypeCP); cfg != nil {\n\t\tcp := cfg.(*protocol.ConfigurationPayload)\n\t\tsess.Logger.Log(\"config\", cp)\n\t\t\/\/ TODO\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package btelegram\n\nimport (\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"github.com\/42wim\/matterbridge\/bridge\/config\"\n\t\"github.com\/42wim\/matterbridge\/bridge\/helper\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/go-telegram-bot-api\/telegram-bot-api\"\n)\n\ntype Btelegram struct {\n\tc       *tgbotapi.BotAPI\n\tConfig  *config.Protocol\n\tRemote  chan config.Message\n\tAccount string\n}\n\nvar flog *log.Entry\nvar protocol = \"telegram\"\n\nfunc init() {\n\tflog = log.WithFields(log.Fields{\"module\": protocol})\n}\n\nfunc New(cfg config.Protocol, account string, c chan config.Message) *Btelegram {\n\tb := &Btelegram{}\n\tb.Config = &cfg\n\tb.Remote = c\n\tb.Account = account\n\treturn b\n}\n\nfunc (b *Btelegram) Connect() error {\n\tvar err error\n\tflog.Info(\"Connecting\")\n\tb.c, err = tgbotapi.NewBotAPI(b.Config.Token)\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tupdates, err := b.c.GetUpdatesChan(tgbotapi.NewUpdate(0))\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tflog.Info(\"Connection succeeded\")\n\tgo b.handleRecv(updates)\n\treturn nil\n}\n\nfunc (b *Btelegram) Disconnect() error {\n\treturn nil\n\n}\n\nfunc (b *Btelegram) JoinChannel(channel config.ChannelInfo) error {\n\treturn nil\n}\n\nfunc (b *Btelegram) Send(msg config.Message) (string, error) {\n\tflog.Debugf(\"Receiving %#v\", msg)\n\tchatid, err := strconv.ParseInt(msg.Channel, 10, 64)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif b.Config.MessageFormat == \"HTML\" {\n\t\tmsg.Text = makeHTML(msg.Text)\n\t}\n\n\tif msg.Event == config.EVENT_MSG_DELETE {\n\t\tif msg.ID == \"\" {\n\t\t\treturn \"\", nil\n\t\t}\n\t\tmsgid, err := strconv.Atoi(msg.ID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t_, err = b.c.DeleteMessage(tgbotapi.DeleteMessageConfig{ChatID: chatid, MessageID: msgid})\n\t\treturn \"\", err\n\t}\n\n\t\/\/ edit the message if we have a msg ID\n\tif msg.ID != \"\" {\n\t\tmsgid, err := strconv.Atoi(msg.ID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tm := tgbotapi.NewEditMessageText(chatid, msgid, msg.Username+msg.Text)\n\t\t_, err = b.c.Send(m)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn \"\", nil\n\t}\n\n\tif msg.Extra != nil {\n\t\t\/\/ check if we have files to upload (from slack, telegram or mattermost)\n\t\tif len(msg.Extra[\"file\"]) > 0 {\n\t\t\tvar c tgbotapi.Chattable\n\t\t\tfor _, f := range msg.Extra[\"file\"] {\n\t\t\t\tfi := f.(config.FileInfo)\n\t\t\t\tfile := tgbotapi.FileBytes{fi.Name, *fi.Data}\n\t\t\t\tre := regexp.MustCompile(\".(jpg|png)$\")\n\t\t\t\tif re.MatchString(fi.Name) {\n\t\t\t\t\tc = tgbotapi.NewPhotoUpload(chatid, file)\n\t\t\t\t} else {\n\t\t\t\t\tc = tgbotapi.NewDocumentUpload(chatid, file)\n\t\t\t\t}\n\t\t\t\t_, err := b.c.Send(c)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"file upload failed: %#v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tm := tgbotapi.NewMessage(chatid, msg.Username+msg.Text)\n\tif b.Config.MessageFormat == \"HTML\" {\n\t\tm.ParseMode = tgbotapi.ModeHTML\n\t}\n\tres, err := b.c.Send(m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strconv.Itoa(res.MessageID), nil\n\n}\n\nfunc (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {\n\tfor update := range updates {\n\t\tflog.Debugf(\"Receiving from telegram: %#v\", update.Message)\n\t\tvar message *tgbotapi.Message\n\t\tusername := \"\"\n\t\tchannel := \"\"\n\t\ttext := \"\"\n\n\t\tfmsg := config.Message{Extra: make(map[string][]interface{})}\n\n\t\t\/\/ handle channels\n\t\tif update.ChannelPost != nil {\n\t\t\tmessage = update.ChannelPost\n\t\t}\n\t\tif update.EditedChannelPost != nil && !b.Config.EditDisable {\n\t\t\tmessage = update.EditedChannelPost\n\t\t\tmessage.Text = message.Text + b.Config.EditSuffix\n\t\t}\n\t\t\/\/ handle groups\n\t\tif update.Message != nil {\n\t\t\tmessage = update.Message\n\t\t}\n\t\tif update.EditedMessage != nil && !b.Config.EditDisable {\n\t\t\tmessage = update.EditedMessage\n\t\t\tmessage.Text = message.Text + b.Config.EditSuffix\n\t\t}\n\t\tif message.From != nil {\n\t\t\tif b.Config.UseFirstName {\n\t\t\t\tusername = message.From.FirstName\n\t\t\t}\n\t\t\tif username == \"\" {\n\t\t\t\tusername = message.From.UserName\n\t\t\t\tif username == \"\" {\n\t\t\t\t\tusername = message.From.FirstName\n\t\t\t\t}\n\t\t\t}\n\t\t\ttext = message.Text\n\t\t\tchannel = strconv.FormatInt(message.Chat.ID, 10)\n\t\t}\n\n\t\tif username == \"\" {\n\t\t\tusername = \"unknown\"\n\t\t}\n\t\tif message.Sticker != nil {\n\t\t\tb.handleDownload(message.Sticker, &fmsg)\n\t\t}\n\t\tif message.Video != nil {\n\t\t\tb.handleDownload(message.Video, &fmsg)\n\t\t}\n\t\tif message.Photo != nil {\n\t\t\tb.handleDownload(message.Photo, &fmsg)\n\t\t}\n\t\tif message.Document != nil {\n\t\t\tb.handleDownload(message.Document, &fmsg)\n\t\t}\n\n\t\t\/\/ quote the previous message\n\t\tif message.ReplyToMessage != nil {\n\t\t\tusernameReply := \"\"\n\t\t\tif message.ReplyToMessage.From != nil {\n\t\t\t\tif b.Config.UseFirstName {\n\t\t\t\t\tusernameReply = message.ReplyToMessage.From.FirstName\n\t\t\t\t}\n\t\t\t\tif usernameReply == \"\" {\n\t\t\t\t\tusernameReply = message.ReplyToMessage.From.UserName\n\t\t\t\t\tif usernameReply == \"\" {\n\t\t\t\t\t\tusernameReply = message.ReplyToMessage.From.FirstName\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif usernameReply == \"\" {\n\t\t\t\tusernameReply = \"unknown\"\n\t\t\t}\n\t\t\ttext = text + \" (re @\" + usernameReply + \":\" + message.ReplyToMessage.Text + \")\"\n\t\t}\n\n\t\tif text != \"\" || len(fmsg.Extra) > 0 {\n\t\t\tflog.Debugf(\"Sending message from %s on %s to gateway\", username, b.Account)\n\t\t\tmsg := config.Message{Username: username, Text: text, Channel: channel, Account: b.Account, UserID: strconv.Itoa(message.From.ID), ID: strconv.Itoa(message.MessageID), Extra: fmsg.Extra}\n\t\t\tflog.Debugf(\"Message is %#v\", msg)\n\t\t\tb.Remote <- msg\n\t\t}\n\t}\n}\n\nfunc (b *Btelegram) getFileDirectURL(id string) string {\n\tres, err := b.c.GetFileDirectURL(id)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn res\n}\n\nfunc (b *Btelegram) handleDownload(file interface{}, msg *config.Message) {\n\tsize := 0\n\turl := \"\"\n\tname := \"\"\n\ttext := \"\"\n\tfileid := \"\"\n\tswitch v := file.(type) {\n\tcase *tgbotapi.Sticker:\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\tname = \"sticker\"\n\t\ttext = \" \" + url\n\t\tfileid = v.FileID\n\tcase *tgbotapi.Video:\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\tname = \"video\"\n\t\ttext = \" \" + url\n\t\tfileid = v.FileID\n\tcase *[]tgbotapi.PhotoSize:\n\t\tphotos := *v\n\t\tsize = photos[len(photos)-1].FileSize\n\t\turl = b.getFileDirectURL(photos[len(photos)-1].FileID)\n\t\tname = \"photo\"\n\t\ttext = \" \" + url\n\tcase *tgbotapi.Document:\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\tname = v.FileName\n\t\ttext = \" \" + v.FileName + \" : \" + url\n\t\tfileid = v.FileID\n\t}\n\tif b.Config.UseInsecureURL {\n\t\tmsg.Text = text\n\t\treturn\n\t}\n\t\/\/ if we have a file attached, download it (in memory) and put a pointer to it in msg.Extra\n\t\/\/ limit to 1MB for now\n\tflog.Debugf(\"trying to download %#v fileid %#v with size %#v\", name, fileid, size)\n\tif size <= 1000000 {\n\t\tdata, err := helper.DownloadFile(url)\n\t\tif err != nil {\n\t\t\tflog.Errorf(\"download %s failed %#v\", url, err)\n\t\t} else {\n\t\t\tflog.Debugf(\"download OK %#v %#v %#v\", name, len(*data), len(url))\n\t\t\tmsg.Extra[\"file\"] = append(msg.Extra[\"file\"], config.FileInfo{Name: name, Data: data})\n\t\t}\n\t}\n}\n<commit_msg>Add extension to sticker\/video\/photo (telegram)<commit_after>package btelegram\n\nimport (\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/42wim\/matterbridge\/bridge\/config\"\n\t\"github.com\/42wim\/matterbridge\/bridge\/helper\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/go-telegram-bot-api\/telegram-bot-api\"\n)\n\ntype Btelegram struct {\n\tc       *tgbotapi.BotAPI\n\tConfig  *config.Protocol\n\tRemote  chan config.Message\n\tAccount string\n}\n\nvar flog *log.Entry\nvar protocol = \"telegram\"\n\nfunc init() {\n\tflog = log.WithFields(log.Fields{\"module\": protocol})\n}\n\nfunc New(cfg config.Protocol, account string, c chan config.Message) *Btelegram {\n\tb := &Btelegram{}\n\tb.Config = &cfg\n\tb.Remote = c\n\tb.Account = account\n\treturn b\n}\n\nfunc (b *Btelegram) Connect() error {\n\tvar err error\n\tflog.Info(\"Connecting\")\n\tb.c, err = tgbotapi.NewBotAPI(b.Config.Token)\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tupdates, err := b.c.GetUpdatesChan(tgbotapi.NewUpdate(0))\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tflog.Info(\"Connection succeeded\")\n\tgo b.handleRecv(updates)\n\treturn nil\n}\n\nfunc (b *Btelegram) Disconnect() error {\n\treturn nil\n\n}\n\nfunc (b *Btelegram) JoinChannel(channel config.ChannelInfo) error {\n\treturn nil\n}\n\nfunc (b *Btelegram) Send(msg config.Message) (string, error) {\n\tflog.Debugf(\"Receiving %#v\", msg)\n\tchatid, err := strconv.ParseInt(msg.Channel, 10, 64)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif b.Config.MessageFormat == \"HTML\" {\n\t\tmsg.Text = makeHTML(msg.Text)\n\t}\n\n\tif msg.Event == config.EVENT_MSG_DELETE {\n\t\tif msg.ID == \"\" {\n\t\t\treturn \"\", nil\n\t\t}\n\t\tmsgid, err := strconv.Atoi(msg.ID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\t_, err = b.c.DeleteMessage(tgbotapi.DeleteMessageConfig{ChatID: chatid, MessageID: msgid})\n\t\treturn \"\", err\n\t}\n\n\t\/\/ edit the message if we have a msg ID\n\tif msg.ID != \"\" {\n\t\tmsgid, err := strconv.Atoi(msg.ID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tm := tgbotapi.NewEditMessageText(chatid, msgid, msg.Username+msg.Text)\n\t\t_, err = b.c.Send(m)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn \"\", nil\n\t}\n\n\tif msg.Extra != nil {\n\t\t\/\/ check if we have files to upload (from slack, telegram or mattermost)\n\t\tif len(msg.Extra[\"file\"]) > 0 {\n\t\t\tvar c tgbotapi.Chattable\n\t\t\tfor _, f := range msg.Extra[\"file\"] {\n\t\t\t\tfi := f.(config.FileInfo)\n\t\t\t\tfile := tgbotapi.FileBytes{fi.Name, *fi.Data}\n\t\t\t\tre := regexp.MustCompile(\".(jpg|png)$\")\n\t\t\t\tif re.MatchString(fi.Name) {\n\t\t\t\t\tc = tgbotapi.NewPhotoUpload(chatid, file)\n\t\t\t\t} else {\n\t\t\t\t\tc = tgbotapi.NewDocumentUpload(chatid, file)\n\t\t\t\t}\n\t\t\t\t_, err := b.c.Send(c)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"file upload failed: %#v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tm := tgbotapi.NewMessage(chatid, msg.Username+msg.Text)\n\tif b.Config.MessageFormat == \"HTML\" {\n\t\tm.ParseMode = tgbotapi.ModeHTML\n\t}\n\tres, err := b.c.Send(m)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strconv.Itoa(res.MessageID), nil\n\n}\n\nfunc (b *Btelegram) handleRecv(updates <-chan tgbotapi.Update) {\n\tfor update := range updates {\n\t\tflog.Debugf(\"Receiving from telegram: %#v\", update.Message)\n\t\tvar message *tgbotapi.Message\n\t\tusername := \"\"\n\t\tchannel := \"\"\n\t\ttext := \"\"\n\n\t\tfmsg := config.Message{Extra: make(map[string][]interface{})}\n\n\t\t\/\/ handle channels\n\t\tif update.ChannelPost != nil {\n\t\t\tmessage = update.ChannelPost\n\t\t}\n\t\tif update.EditedChannelPost != nil && !b.Config.EditDisable {\n\t\t\tmessage = update.EditedChannelPost\n\t\t\tmessage.Text = message.Text + b.Config.EditSuffix\n\t\t}\n\t\t\/\/ handle groups\n\t\tif update.Message != nil {\n\t\t\tmessage = update.Message\n\t\t}\n\t\tif update.EditedMessage != nil && !b.Config.EditDisable {\n\t\t\tmessage = update.EditedMessage\n\t\t\tmessage.Text = message.Text + b.Config.EditSuffix\n\t\t}\n\t\tif message.From != nil {\n\t\t\tif b.Config.UseFirstName {\n\t\t\t\tusername = message.From.FirstName\n\t\t\t}\n\t\t\tif username == \"\" {\n\t\t\t\tusername = message.From.UserName\n\t\t\t\tif username == \"\" {\n\t\t\t\t\tusername = message.From.FirstName\n\t\t\t\t}\n\t\t\t}\n\t\t\ttext = message.Text\n\t\t\tchannel = strconv.FormatInt(message.Chat.ID, 10)\n\t\t}\n\n\t\tif username == \"\" {\n\t\t\tusername = \"unknown\"\n\t\t}\n\t\tif message.Sticker != nil {\n\t\t\tb.handleDownload(message.Sticker, &fmsg)\n\t\t}\n\t\tif message.Video != nil {\n\t\t\tb.handleDownload(message.Video, &fmsg)\n\t\t}\n\t\tif message.Photo != nil {\n\t\t\tb.handleDownload(message.Photo, &fmsg)\n\t\t}\n\t\tif message.Document != nil {\n\t\t\tb.handleDownload(message.Document, &fmsg)\n\t\t}\n\n\t\t\/\/ quote the previous message\n\t\tif message.ReplyToMessage != nil {\n\t\t\tusernameReply := \"\"\n\t\t\tif message.ReplyToMessage.From != nil {\n\t\t\t\tif b.Config.UseFirstName {\n\t\t\t\t\tusernameReply = message.ReplyToMessage.From.FirstName\n\t\t\t\t}\n\t\t\t\tif usernameReply == \"\" {\n\t\t\t\t\tusernameReply = message.ReplyToMessage.From.UserName\n\t\t\t\t\tif usernameReply == \"\" {\n\t\t\t\t\t\tusernameReply = message.ReplyToMessage.From.FirstName\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif usernameReply == \"\" {\n\t\t\t\tusernameReply = \"unknown\"\n\t\t\t}\n\t\t\ttext = text + \" (re @\" + usernameReply + \":\" + message.ReplyToMessage.Text + \")\"\n\t\t}\n\n\t\tif text != \"\" || len(fmsg.Extra) > 0 {\n\t\t\tflog.Debugf(\"Sending message from %s on %s to gateway\", username, b.Account)\n\t\t\tmsg := config.Message{Username: username, Text: text, Channel: channel, Account: b.Account, UserID: strconv.Itoa(message.From.ID), ID: strconv.Itoa(message.MessageID), Extra: fmsg.Extra}\n\t\t\tflog.Debugf(\"Message is %#v\", msg)\n\t\t\tb.Remote <- msg\n\t\t}\n\t}\n}\n\nfunc (b *Btelegram) getFileDirectURL(id string) string {\n\tres, err := b.c.GetFileDirectURL(id)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn res\n}\n\nfunc (b *Btelegram) handleDownload(file interface{}, msg *config.Message) {\n\tsize := 0\n\turl := \"\"\n\tname := \"\"\n\ttext := \"\"\n\tfileid := \"\"\n\tswitch v := file.(type) {\n\tcase *tgbotapi.Sticker:\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\turlPart := strings.Split(url, \"\/\")\n\t\tname = urlPart[len(urlPart)-1]\n\t\ttext = \" \" + url\n\t\tfileid = v.FileID\n\tcase *tgbotapi.Video:\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\turlPart := strings.Split(url, \"\/\")\n\t\tname = urlPart[len(urlPart)-1]\n\t\ttext = \" \" + url\n\t\tfileid = v.FileID\n\tcase *[]tgbotapi.PhotoSize:\n\t\tphotos := *v\n\t\tsize = photos[len(photos)-1].FileSize\n\t\turl = b.getFileDirectURL(photos[len(photos)-1].FileID)\n\t\turlPart := strings.Split(url, \"\/\")\n\t\tname = urlPart[len(urlPart)-1]\n\t\ttext = \" \" + url\n\tcase *tgbotapi.Document:\n\t\tsize = v.FileSize\n\t\turl = b.getFileDirectURL(v.FileID)\n\t\tname = v.FileName\n\t\ttext = \" \" + v.FileName + \" : \" + url\n\t\tfileid = v.FileID\n\t}\n\tif b.Config.UseInsecureURL {\n\t\tmsg.Text = text\n\t\treturn\n\t}\n\t\/\/ if we have a file attached, download it (in memory) and put a pointer to it in msg.Extra\n\t\/\/ limit to 1MB for now\n\tflog.Debugf(\"trying to download %#v fileid %#v with size %#v\", name, fileid, size)\n\tif size <= 1000000 {\n\t\tdata, err := helper.DownloadFile(url)\n\t\tif err != nil {\n\t\t\tflog.Errorf(\"download %s failed %#v\", url, err)\n\t\t} else {\n\t\t\tflog.Debugf(\"download OK %#v %#v %#v\", name, len(*data), len(url))\n\t\t\tmsg.Extra[\"file\"] = append(msg.Extra[\"file\"], config.FileInfo{Name: name, Data: data})\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package handyfile\n\nimport (\n\t\"hash\/crc32\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n)\n\nfunc Checksum32(path string) uint32 {\n\tfile, _ := os.Open(path)\n\tdefer file.Close()\n\tc := crc32.NewIEEE()\n\tbytes, _ := ioutil.ReadAll(file)\n\twithcrc := c.Sum(bytes)\n\treturn crc32.ChecksumIEEE(withcrc)\n}\n\nfunc Exists(path string) bool {\n\t_, err := os.Stat(path)\n\treturn !os.IsNotExist(err)\n}\n\nfunc Copy(src, dest string) error {\n\tfsrc, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fsrc.Close()\n\n\tfdest, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fdest.Close()\n\n\tif _, err := io.Copy(fdest, fsrc); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>Add function for hash a file using anything hasher that returns []bytes. Make function so that it works on any size of file, rather than reading the file into memory.<commit_after>package handyfile\n\nimport (\n\t\"hash\"\n\t\"hash\/crc32\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n)\n\nfunc Checksum32(path string) uint32 {\n\tfile, _ := os.Open(path)\n\tdefer file.Close()\n\tc := crc32.NewIEEE()\n\tbytes, _ := ioutil.ReadAll(file)\n\twithcrc := c.Sum(bytes)\n\treturn crc32.ChecksumIEEE(withcrc)\n}\n\nfunc Hash(hasher hash.Hash, path string) ([]byte, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tif _, err := io.Copy(hasher, f); err != nil {\n\t\treturn nil, err\n\t}\n\treturn hasher.Sum(nil), nil\n}\n\nfunc Exists(path string) bool {\n\t_, err := os.Stat(path)\n\treturn !os.IsNotExist(err)\n}\n\nfunc Copy(src, dest string) error {\n\tfsrc, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fsrc.Close()\n\n\tfdest, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fdest.Close()\n\n\tif _, err := io.Copy(fdest, fsrc); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>fix(policy): remove commit header length from conventional commit policy (#102)<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage docker\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/docker\/libcontainer\"\n\t\"github.com\/docker\/libcontainer\/cgroups\"\n\t\"github.com\/docker\/libcontainer\/cgroups\/fs\"\n\t\"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/google\/cadvisor\/container\"\n\t\"github.com\/google\/cadvisor\/info\"\n)\n\ntype dockerContainerHandler struct {\n\tclient             *docker.Client\n\tname               string\n\taliases            []string\n\tmachineInfoFactory info.MachineInfoFactory\n}\n\nfunc newDockerContainerHandler(\n\tclient *docker.Client,\n\tname string,\n\tmachineInfoFactory info.MachineInfoFactory,\n) (container.ContainerHandler, error) {\n\thandler := &dockerContainerHandler{\n\t\tclient:             client,\n\t\tname:               name,\n\t\tmachineInfoFactory: machineInfoFactory,\n\t}\n\tif !handler.isDockerContainer() {\n\t\treturn handler, nil\n\t}\n\t_, id, err := handler.splitName()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid docker container %v: %v\", name, err)\n\t}\n\tctnr, err := client.InspectContainer(id)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to inspect container %v: %v\", name, err)\n\t}\n\thandler.aliases = append(handler.aliases, path.Join(\"\/docker\", ctnr.Name))\n\treturn handler, nil\n}\n\nfunc (self *dockerContainerHandler) ContainerReference() (info.ContainerReference, error) {\n\treturn info.ContainerReference{\n\t\tName:    self.name,\n\t\tAliases: self.aliases,\n\t}, nil\n}\n\nfunc (self *dockerContainerHandler) splitName() (string, string, error) {\n\tparent, id := path.Split(self.name)\n\tcgroupSelf, err := os.Open(\"\/proc\/self\/cgroup\")\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tscanner := bufio.NewScanner(cgroupSelf)\n\n\tsubsys := []string{\"memory\", \"cpu\"}\n\tnestedLevels := 0\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\telems := strings.Split(line, \":\")\n\t\tif len(elems) < 3 {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, s := range subsys {\n\t\t\tif elems[1] == s {\n\t\t\t\t\/\/ count how many nested docker containers are there.\n\t\t\t\tnestedLevels = strings.Count(elems[2], \"\/docker\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif nestedLevels > 0 {\n\t\t\/\/ we are running inside a docker container\n\t\tupperLevel := strings.Repeat(\"..\/..\/\", nestedLevels)\n\t\t\/\/parent = strings.Join([]string{parent, upperLevel}, \"\/\")\n\t\tparent = fmt.Sprintf(\"%v%v\", upperLevel, parent)\n\t}\n\treturn parent, id, nil\n}\n\nfunc (self *dockerContainerHandler) isDockerRoot() bool {\n\t\/\/ TODO(dengnan): Should we consider other cases?\n\treturn self.name == \"\/docker\"\n}\n\nfunc (self *dockerContainerHandler) isRootContainer() bool {\n\treturn self.name == \"\/\"\n}\n\nfunc (self *dockerContainerHandler) isDockerContainer() bool {\n\treturn (!self.isDockerRoot()) && (!self.isRootContainer())\n}\n\n\/\/ TODO(vmarmol): Switch to getting this from libcontainer once we have a solid API.\nfunc readLibcontainerSpec(id string) (spec *libcontainer.Config, err error) {\n\tdir := \"\/var\/lib\/docker\/execdriver\/native\"\n\tconfigPath := path.Join(dir, id, \"container.json\")\n\tf, err := os.Open(configPath)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\td := json.NewDecoder(f)\n\tret := new(libcontainer.Config)\n\terr = d.Decode(ret)\n\tif err != nil {\n\t\treturn\n\t}\n\tspec = ret\n\treturn\n}\n\nfunc libcontainerConfigToContainerSpec(config *libcontainer.Config, mi *info.MachineInfo) *info.ContainerSpec {\n\tspec := new(info.ContainerSpec)\n\tspec.Memory = new(info.MemorySpec)\n\tspec.Memory.Limit = math.MaxUint64\n\tspec.Memory.SwapLimit = math.MaxUint64\n\tif config.Cgroups.Memory > 0 {\n\t\tspec.Memory.Limit = uint64(config.Cgroups.Memory)\n\t}\n\tif config.Cgroups.MemorySwap > 0 {\n\t\tspec.Memory.SwapLimit = uint64(config.Cgroups.MemorySwap)\n\t}\n\n\t\/\/ Get CPU info\n\tspec.Cpu = new(info.CpuSpec)\n\tspec.Cpu.Limit = 1024\n\tif config.Cgroups.CpuShares != 0 {\n\t\tspec.Cpu.Limit = uint64(config.Cgroups.CpuShares)\n\t}\n\tn := (mi.NumCores + 63) \/ 64\n\tspec.Cpu.Mask.Data = make([]uint64, n)\n\tfor i := 0; i < n; i++ {\n\t\tspec.Cpu.Mask.Data[i] = math.MaxUint64\n\t}\n\t\/\/ TODO(vmarmol): Get CPUs from config.Cgroups.CpusetCpus\n\treturn spec\n}\n\nfunc (self *dockerContainerHandler) GetSpec() (spec *info.ContainerSpec, err error) {\n\tif !self.isDockerContainer() {\n\t\tspec = new(info.ContainerSpec)\n\t\treturn\n\t}\n\tmi, err := self.machineInfoFactory.GetMachineInfo()\n\tif err != nil {\n\t\treturn\n\t}\n\t_, id, err := self.splitName()\n\tif err != nil {\n\t\treturn\n\t}\n\tlibcontainerSpec, err := readLibcontainerSpec(id)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tspec = libcontainerConfigToContainerSpec(libcontainerSpec, mi)\n\treturn\n}\n\nfunc libcontainerToContainerStats(s *cgroups.Stats, mi *info.MachineInfo) *info.ContainerStats {\n\tret := new(info.ContainerStats)\n\tret.Timestamp = time.Now()\n\tret.Cpu = new(info.CpuStats)\n\tret.Cpu.Usage.User = s.CpuStats.CpuUsage.UsageInUsermode\n\tret.Cpu.Usage.System = s.CpuStats.CpuUsage.UsageInKernelmode\n\tn := len(s.CpuStats.CpuUsage.PercpuUsage)\n\tret.Cpu.Usage.PerCpu = make([]uint64, n)\n\n\tret.Cpu.Usage.Total = 0\n\tfor i := 0; i < n; i++ {\n\t\tret.Cpu.Usage.PerCpu[i] = s.CpuStats.CpuUsage.PercpuUsage[i]\n\t\tret.Cpu.Usage.Total += s.CpuStats.CpuUsage.PercpuUsage[i]\n\t}\n\tret.Memory = new(info.MemoryStats)\n\tret.Memory.Usage = s.MemoryStats.Usage\n\tif v, ok := s.MemoryStats.Stats[\"pgfault\"]; ok {\n\t\tret.Memory.ContainerData.Pgfault = v\n\t\tret.Memory.HierarchicalData.Pgfault = v\n\t}\n\tif v, ok := s.MemoryStats.Stats[\"pgmajfault\"]; ok {\n\t\tret.Memory.ContainerData.Pgmajfault = v\n\t\tret.Memory.HierarchicalData.Pgmajfault = v\n\t}\n\treturn ret\n}\n\nfunc (self *dockerContainerHandler) GetStats() (stats *info.ContainerStats, err error) {\n\tif !self.isDockerContainer() {\n\t\t\/\/ Return empty stats for root containers.\n\t\tstats = new(info.ContainerStats)\n\t\tstats.Timestamp = time.Now()\n\t\treturn\n\t}\n\tmi, err := self.machineInfoFactory.GetMachineInfo()\n\tif err != nil {\n\t\treturn\n\t}\n\tparent, id, err := self.splitName()\n\tif err != nil {\n\t\treturn\n\t}\n\tcg := &cgroups.Cgroup{\n\t\tParent: parent,\n\t\tName:   id,\n\t}\n\ts, err := fs.GetStats(cg)\n\tif err != nil {\n\t\treturn\n\t}\n\tstats = libcontainerToContainerStats(s, mi)\n\treturn\n}\n\nfunc (self *dockerContainerHandler) ListContainers(listType container.ListType) ([]info.ContainerReference, error) {\n\tif self.isDockerContainer() {\n\t\treturn nil, nil\n\t}\n\tif self.isRootContainer() && listType == container.LIST_SELF {\n\t\treturn []info.ContainerReference{info.ContainerReference{Name: \"\/docker\"}}, nil\n\t}\n\topt := docker.ListContainersOptions{\n\t\tAll: true,\n\t}\n\tcontainers, err := self.client.ListContainers(opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tret := make([]info.ContainerReference, 0, len(containers)+1)\n\tfor _, c := range containers {\n\t\tif !strings.HasPrefix(c.Status, \"Up \") {\n\t\t\tcontinue\n\t\t}\n\t\tpath := fmt.Sprintf(\"\/docker\/%v\", c.ID)\n\t\taliases := c.Names\n\t\tref := info.ContainerReference{\n\t\t\tName:    path,\n\t\t\tAliases: aliases,\n\t\t}\n\t\tret = append(ret, ref)\n\t}\n\tif self.isRootContainer() {\n\t\tret = append(ret, info.ContainerReference{Name: \"\/docker\"})\n\t}\n\treturn ret, nil\n}\n\nfunc (self *dockerContainerHandler) ListThreads(listType container.ListType) ([]int, error) {\n\treturn nil, nil\n}\n\nfunc (self *dockerContainerHandler) ListProcesses(listType container.ListType) ([]int, error) {\n\treturn nil, nil\n}\n<commit_msg>calculate working set based on #. pages in active LRU.<commit_after>\/\/ Copyright 2014 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage docker\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/docker\/libcontainer\"\n\t\"github.com\/docker\/libcontainer\/cgroups\"\n\t\"github.com\/docker\/libcontainer\/cgroups\/fs\"\n\t\"github.com\/fsouza\/go-dockerclient\"\n\t\"github.com\/google\/cadvisor\/container\"\n\t\"github.com\/google\/cadvisor\/info\"\n)\n\ntype dockerContainerHandler struct {\n\tclient             *docker.Client\n\tname               string\n\taliases            []string\n\tmachineInfoFactory info.MachineInfoFactory\n}\n\nfunc newDockerContainerHandler(\n\tclient *docker.Client,\n\tname string,\n\tmachineInfoFactory info.MachineInfoFactory,\n) (container.ContainerHandler, error) {\n\thandler := &dockerContainerHandler{\n\t\tclient:             client,\n\t\tname:               name,\n\t\tmachineInfoFactory: machineInfoFactory,\n\t}\n\tif !handler.isDockerContainer() {\n\t\treturn handler, nil\n\t}\n\t_, id, err := handler.splitName()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid docker container %v: %v\", name, err)\n\t}\n\tctnr, err := client.InspectContainer(id)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to inspect container %v: %v\", name, err)\n\t}\n\thandler.aliases = append(handler.aliases, path.Join(\"\/docker\", ctnr.Name))\n\treturn handler, nil\n}\n\nfunc (self *dockerContainerHandler) ContainerReference() (info.ContainerReference, error) {\n\treturn info.ContainerReference{\n\t\tName:    self.name,\n\t\tAliases: self.aliases,\n\t}, nil\n}\n\nfunc (self *dockerContainerHandler) splitName() (string, string, error) {\n\tparent, id := path.Split(self.name)\n\tcgroupSelf, err := os.Open(\"\/proc\/self\/cgroup\")\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tscanner := bufio.NewScanner(cgroupSelf)\n\n\tsubsys := []string{\"memory\", \"cpu\"}\n\tnestedLevels := 0\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\telems := strings.Split(line, \":\")\n\t\tif len(elems) < 3 {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, s := range subsys {\n\t\t\tif elems[1] == s {\n\t\t\t\t\/\/ count how many nested docker containers are there.\n\t\t\t\tnestedLevels = strings.Count(elems[2], \"\/docker\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif nestedLevels > 0 {\n\t\t\/\/ we are running inside a docker container\n\t\tupperLevel := strings.Repeat(\"..\/..\/\", nestedLevels)\n\t\t\/\/parent = strings.Join([]string{parent, upperLevel}, \"\/\")\n\t\tparent = fmt.Sprintf(\"%v%v\", upperLevel, parent)\n\t}\n\treturn parent, id, nil\n}\n\nfunc (self *dockerContainerHandler) isDockerRoot() bool {\n\t\/\/ TODO(dengnan): Should we consider other cases?\n\treturn self.name == \"\/docker\"\n}\n\nfunc (self *dockerContainerHandler) isRootContainer() bool {\n\treturn self.name == \"\/\"\n}\n\nfunc (self *dockerContainerHandler) isDockerContainer() bool {\n\treturn (!self.isDockerRoot()) && (!self.isRootContainer())\n}\n\n\/\/ TODO(vmarmol): Switch to getting this from libcontainer once we have a solid API.\nfunc readLibcontainerSpec(id string) (spec *libcontainer.Config, err error) {\n\tdir := \"\/var\/lib\/docker\/execdriver\/native\"\n\tconfigPath := path.Join(dir, id, \"container.json\")\n\tf, err := os.Open(configPath)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\td := json.NewDecoder(f)\n\tret := new(libcontainer.Config)\n\terr = d.Decode(ret)\n\tif err != nil {\n\t\treturn\n\t}\n\tspec = ret\n\treturn\n}\n\nfunc libcontainerConfigToContainerSpec(config *libcontainer.Config, mi *info.MachineInfo) *info.ContainerSpec {\n\tspec := new(info.ContainerSpec)\n\tspec.Memory = new(info.MemorySpec)\n\tspec.Memory.Limit = math.MaxUint64\n\tspec.Memory.SwapLimit = math.MaxUint64\n\tif config.Cgroups.Memory > 0 {\n\t\tspec.Memory.Limit = uint64(config.Cgroups.Memory)\n\t}\n\tif config.Cgroups.MemorySwap > 0 {\n\t\tspec.Memory.SwapLimit = uint64(config.Cgroups.MemorySwap)\n\t}\n\n\t\/\/ Get CPU info\n\tspec.Cpu = new(info.CpuSpec)\n\tspec.Cpu.Limit = 1024\n\tif config.Cgroups.CpuShares != 0 {\n\t\tspec.Cpu.Limit = uint64(config.Cgroups.CpuShares)\n\t}\n\tn := (mi.NumCores + 63) \/ 64\n\tspec.Cpu.Mask.Data = make([]uint64, n)\n\tfor i := 0; i < n; i++ {\n\t\tspec.Cpu.Mask.Data[i] = math.MaxUint64\n\t}\n\t\/\/ TODO(vmarmol): Get CPUs from config.Cgroups.CpusetCpus\n\treturn spec\n}\n\nfunc (self *dockerContainerHandler) GetSpec() (spec *info.ContainerSpec, err error) {\n\tif !self.isDockerContainer() {\n\t\tspec = new(info.ContainerSpec)\n\t\treturn\n\t}\n\tmi, err := self.machineInfoFactory.GetMachineInfo()\n\tif err != nil {\n\t\treturn\n\t}\n\t_, id, err := self.splitName()\n\tif err != nil {\n\t\treturn\n\t}\n\tlibcontainerSpec, err := readLibcontainerSpec(id)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tspec = libcontainerConfigToContainerSpec(libcontainerSpec, mi)\n\treturn\n}\n\nfunc libcontainerToContainerStats(s *cgroups.Stats, mi *info.MachineInfo) *info.ContainerStats {\n\tret := new(info.ContainerStats)\n\tret.Timestamp = time.Now()\n\tret.Cpu = new(info.CpuStats)\n\tret.Cpu.Usage.User = s.CpuStats.CpuUsage.UsageInUsermode\n\tret.Cpu.Usage.System = s.CpuStats.CpuUsage.UsageInKernelmode\n\tn := len(s.CpuStats.CpuUsage.PercpuUsage)\n\tret.Cpu.Usage.PerCpu = make([]uint64, n)\n\n\tret.Cpu.Usage.Total = 0\n\tfor i := 0; i < n; i++ {\n\t\tret.Cpu.Usage.PerCpu[i] = s.CpuStats.CpuUsage.PercpuUsage[i]\n\t\tret.Cpu.Usage.Total += s.CpuStats.CpuUsage.PercpuUsage[i]\n\t}\n\tret.Memory = new(info.MemoryStats)\n\tret.Memory.Usage = s.MemoryStats.Usage\n\tif v, ok := s.MemoryStats.Stats[\"pgfault\"]; ok {\n\t\tret.Memory.ContainerData.Pgfault = v\n\t\tret.Memory.HierarchicalData.Pgfault = v\n\t}\n\tif v, ok := s.MemoryStats.Stats[\"pgmajfault\"]; ok {\n\t\tret.Memory.ContainerData.Pgmajfault = v\n\t\tret.Memory.HierarchicalData.Pgmajfault = v\n\t}\n\tif v, ok := s.MemoryStats.Stats[\"active_anon\"]; ok {\n\t\tret.Memory.WorkingSet = v\n\t\tif v, ok := s.MemoryStats.Stats[\"active_file\"]; ok {\n\t\t\tret.Memory.WorkingSet += v\n\t\t}\n\t}\n\treturn ret\n}\n\nfunc (self *dockerContainerHandler) GetStats() (stats *info.ContainerStats, err error) {\n\tif !self.isDockerContainer() {\n\t\t\/\/ Return empty stats for root containers.\n\t\tstats = new(info.ContainerStats)\n\t\tstats.Timestamp = time.Now()\n\t\treturn\n\t}\n\tmi, err := self.machineInfoFactory.GetMachineInfo()\n\tif err != nil {\n\t\treturn\n\t}\n\tparent, id, err := self.splitName()\n\tif err != nil {\n\t\treturn\n\t}\n\tcg := &cgroups.Cgroup{\n\t\tParent: parent,\n\t\tName:   id,\n\t}\n\ts, err := fs.GetStats(cg)\n\tif err != nil {\n\t\treturn\n\t}\n\tstats = libcontainerToContainerStats(s, mi)\n\treturn\n}\n\nfunc (self *dockerContainerHandler) ListContainers(listType container.ListType) ([]info.ContainerReference, error) {\n\tif self.isDockerContainer() {\n\t\treturn nil, nil\n\t}\n\tif self.isRootContainer() && listType == container.LIST_SELF {\n\t\treturn []info.ContainerReference{info.ContainerReference{Name: \"\/docker\"}}, nil\n\t}\n\topt := docker.ListContainersOptions{\n\t\tAll: true,\n\t}\n\tcontainers, err := self.client.ListContainers(opt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tret := make([]info.ContainerReference, 0, len(containers)+1)\n\tfor _, c := range containers {\n\t\tif !strings.HasPrefix(c.Status, \"Up \") {\n\t\t\tcontinue\n\t\t}\n\t\tpath := fmt.Sprintf(\"\/docker\/%v\", c.ID)\n\t\taliases := c.Names\n\t\tref := info.ContainerReference{\n\t\t\tName:    path,\n\t\t\tAliases: aliases,\n\t\t}\n\t\tret = append(ret, ref)\n\t}\n\tif self.isRootContainer() {\n\t\tret = append(ret, info.ContainerReference{Name: \"\/docker\"})\n\t}\n\treturn ret, nil\n}\n\nfunc (self *dockerContainerHandler) ListThreads(listType container.ListType) ([]int, error) {\n\treturn nil, nil\n}\n\nfunc (self *dockerContainerHandler) ListProcesses(listType container.ListType) ([]int, error) {\n\treturn nil, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"google.golang.org\/protobuf\/encoding\/protojson\"\n\n\t\"vitess.io\/vitess\/go\/sqltypes\"\n\t\"vitess.io\/vitess\/go\/vt\/tlstest\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\n\t\"vitess.io\/vitess\/go\/mysql\"\n\n\t\"vitess.io\/vitess\/go\/vt\/vttest\"\n\n\t\"vitess.io\/vitess\/go\/vt\/proto\/logutil\"\n\t\"vitess.io\/vitess\/go\/vt\/proto\/vschema\"\n\t\"vitess.io\/vitess\/go\/vt\/vtctl\/vtctlclient\"\n)\n\ntype columnVindex struct {\n\tkeyspace   string\n\ttable      string\n\tvindex     string\n\tvindexType string\n\tcolumn     string\n}\n\nfunc TestRunsVschemaMigrations(t *testing.T) {\n\targs := os.Args\n\tconf := config\n\tdefer resetFlags(args, conf)\n\n\tcluster, err := startCluster()\n\tdefer cluster.TearDown()\n\n\tassert.NoError(t, err)\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"test_keyspace\", table: \"test_table\", vindex: \"my_vdx\", vindexType: \"hash\", column: \"id\"})\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"app_customer\", table: \"customers\", vindex: \"hash\", vindexType: \"hash\", column: \"id\"})\n\n\t\/\/ Add Hash vindex via vtgate execution on table\n\terr = addColumnVindex(cluster, \"test_keyspace\", \"alter vschema on test_table1 add vindex my_vdx (id)\")\n\tassert.NoError(t, err)\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"test_keyspace\", table: \"test_table1\", vindex: \"my_vdx\", vindexType: \"hash\", column: \"id\"})\n}\n\nfunc TestPersistentMode(t *testing.T) {\n\targs := os.Args\n\tconf := config\n\tdefer resetFlags(args, conf)\n\n\tdir, err := ioutil.TempDir(\"\/tmp\", \"vttestserver_persistent_mode_\")\n\tassert.NoError(t, err)\n\tdefer os.RemoveAll(dir)\n\n\tcluster, err := startPersistentCluster(dir)\n\tassert.NoError(t, err)\n\n\t\/\/ basic sanity checks similar to TestRunsVschemaMigrations\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"test_keyspace\", table: \"test_table\", vindex: \"my_vdx\", vindexType: \"hash\", column: \"id\"})\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"app_customer\", table: \"customers\", vindex: \"hash\", vindexType: \"hash\", column: \"id\"})\n\n\t\/\/ insert some data to ensure persistence across teardowns\n\terr = execOnCluster(cluster, \"app_customer\", func(conn *mysql.Conn) error {\n\t\t_, err := conn.ExecuteFetch(\"insert into customers (id, name) values (1, 'gopherson')\", 1, false)\n\t\treturn err\n\t})\n\tassert.NoError(t, err)\n\n\texpectedRows := [][]sqltypes.Value{\n\t\t{sqltypes.NewInt64(1), sqltypes.NewVarChar(\"gopherson\"), sqltypes.NULL},\n\t}\n\n\t\/\/ ensure data was actually inserted\n\tvar res *sqltypes.Result\n\terr = execOnCluster(cluster, \"app_customer\", func(conn *mysql.Conn) (err error) {\n\t\tres, err = conn.ExecuteFetch(\"SELECT * FROM customers\", 1, false)\n\t\treturn err\n\t})\n\tassert.NoError(t, err)\n\tassert.Equal(t, expectedRows, res.Rows)\n\n\t\/\/ reboot the persistent cluster\n\tcluster.TearDown()\n\tcluster, err = startPersistentCluster(dir)\n\tdefer cluster.TearDown()\n\tassert.NoError(t, err)\n\n\t\/\/ rerun our sanity checks to make sure vschema migrations are run during every startup\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"test_keyspace\", table: \"test_table\", vindex: \"my_vdx\", vindexType: \"hash\", column: \"id\"})\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"app_customer\", table: \"customers\", vindex: \"hash\", vindexType: \"hash\", column: \"id\"})\n\n\t\/\/ ensure previous data was successfully persisted\n\terr = execOnCluster(cluster, \"app_customer\", func(conn *mysql.Conn) (err error) {\n\t\tres, err = conn.ExecuteFetch(\"SELECT * FROM customers\", 1, false)\n\t\treturn err\n\t})\n\tassert.NoError(t, err)\n\tassert.Equal(t, expectedRows, res.Rows)\n}\n\nfunc TestCanVtGateExecute(t *testing.T) {\n\targs := os.Args\n\tconf := config\n\tdefer resetFlags(args, conf)\n\n\tcluster, err := startCluster()\n\tassert.NoError(t, err)\n\tdefer cluster.TearDown()\n\n\tclient, err := vtctlclient.New(fmt.Sprintf(\"localhost:%v\", cluster.GrpcPort()))\n\tassert.NoError(t, err)\n\tdefer client.Close()\n\tstream, err := client.ExecuteVtctlCommand(\n\t\tcontext.Background(),\n\t\t[]string{\n\t\t\t\"VtGateExecute\",\n\t\t\t\"-server\",\n\t\t\tfmt.Sprintf(\"localhost:%v\", cluster.GrpcPort()),\n\t\t\t\"select 'success';\",\n\t\t},\n\t\t30*time.Second,\n\t)\n\tassert.NoError(t, err)\n\n\tvar b strings.Builder\n\tb.Grow(1024)\n\nOut:\n\tfor {\n\t\te, err := stream.Recv()\n\t\tswitch err {\n\t\tcase nil:\n\t\t\tb.WriteString(e.Value)\n\t\tcase io.EOF:\n\t\t\tbreak Out\n\t\tdefault:\n\t\t\tassert.FailNow(t, err.Error())\n\t\t}\n\t}\n\n\tassert.Contains(t, b.String(), \"success\")\n}\n\nfunc TestMtlsAuth(t *testing.T) {\n\targs := os.Args\n\tconf := config\n\tdefer resetFlags(args, conf)\n\n\t\/\/ Our test root.\n\troot, err := ioutil.TempDir(\"\", \"tlstest\")\n\tif err != nil {\n\t\tt.Fatalf(\"TempDir failed: %v\", err)\n\t}\n\tdefer os.RemoveAll(root)\n\n\t\/\/ Create the certs and configs.\n\ttlstest.CreateCA(root)\n\tcaCert := path.Join(root, \"ca-cert.pem\")\n\n\ttlstest.CreateSignedCert(root, tlstest.CA, \"01\", \"vtctld\", \"vtctld.example.com\")\n\tcert := path.Join(root, \"vtctld-cert.pem\")\n\tkey := path.Join(root, \"vtctld-key.pem\")\n\n\ttlstest.CreateSignedCert(root, tlstest.CA, \"02\", \"client\", \"ClientApp\")\n\tclientCert := path.Join(root, \"client-cert.pem\")\n\tclientKey := path.Join(root, \"client-key.pem\")\n\n\t\/\/ When cluster starts it will apply SQL and VSchema migrations in the configured schema_dir folder\n\t\/\/ With mtls authorization enabled, the authorized CN must match the certificate's CN\n\tcluster, err := startCluster(\n\t\t\"-grpc_auth_mode=mtls\",\n\t\tfmt.Sprintf(\"-grpc_key=%s\", key),\n\t\tfmt.Sprintf(\"-grpc_cert=%s\", cert),\n\t\tfmt.Sprintf(\"-grpc_ca=%s\", caCert),\n\t\tfmt.Sprintf(\"-vtctld_grpc_key=%s\", clientKey),\n\t\tfmt.Sprintf(\"-vtctld_grpc_cert=%s\", clientCert),\n\t\tfmt.Sprintf(\"-vtctld_grpc_ca=%s\", caCert),\n\t\tfmt.Sprintf(\"-grpc_auth_mtls_allowed_substrings=%s\", \"CN=ClientApp\"))\n\tassert.NoError(t, err)\n\tdefer cluster.TearDown()\n\n\t\/\/ startCluster will apply vschema migrations using vtctl grpc and the clientCert.\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"test_keyspace\", table: \"test_table\", vindex: \"my_vdx\", vindexType: \"hash\", column: \"id\"})\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"app_customer\", table: \"customers\", vindex: \"hash\", vindexType: \"hash\", column: \"id\"})\n}\n\nfunc TestMtlsAuthUnauthorizedFails(t *testing.T) {\n\targs := os.Args\n\tconf := config\n\tdefer resetFlags(args, conf)\n\n\t\/\/ Our test root.\n\troot, err := ioutil.TempDir(\"\", \"tlstest\")\n\tif err != nil {\n\t\tt.Fatalf(\"TempDir failed: %v\", err)\n\t}\n\tdefer os.RemoveAll(root)\n\n\t\/\/ Create the certs and configs.\n\ttlstest.CreateCA(root)\n\tcaCert := path.Join(root, \"ca-cert.pem\")\n\n\ttlstest.CreateSignedCert(root, tlstest.CA, \"01\", \"vtctld\", \"vtctld.example.com\")\n\tcert := path.Join(root, \"vtctld-cert.pem\")\n\tkey := path.Join(root, \"vtctld-key.pem\")\n\n\ttlstest.CreateSignedCert(root, tlstest.CA, \"02\", \"client\", \"AnotherApp\")\n\tclientCert := path.Join(root, \"client-cert.pem\")\n\tclientKey := path.Join(root, \"client-key.pem\")\n\n\t\/\/ When cluster starts it will apply SQL and VSchema migrations in the configured schema_dir folder\n\t\/\/ For mtls authorization failure by providing a client certificate with different CN thant the\n\t\/\/ authorized in the configuration\n\tcluster, err := startCluster(\n\t\t\"-grpc_auth_mode=mtls\",\n\t\tfmt.Sprintf(\"-grpc_key=%s\", key),\n\t\tfmt.Sprintf(\"-grpc_cert=%s\", cert),\n\t\tfmt.Sprintf(\"-grpc_ca=%s\", caCert),\n\t\tfmt.Sprintf(\"-vtctld_grpc_key=%s\", clientKey),\n\t\tfmt.Sprintf(\"-vtctld_grpc_cert=%s\", clientCert),\n\t\tfmt.Sprintf(\"-vtctld_grpc_ca=%s\", caCert),\n\t\tfmt.Sprintf(\"-grpc_auth_mtls_allowed_substrings=%s\", \"CN=ClientApp\"))\n\tdefer cluster.TearDown()\n\n\tassert.Error(t, err)\n\tassert.Contains(t, err.Error(), \"code = Unauthenticated desc = client certificate not authorized\")\n}\n\nfunc startPersistentCluster(dir string, flags ...string) (vttest.LocalCluster, error) {\n\tflags = append(flags, []string{\n\t\t\"-persistent_mode\",\n\t\t\/\/ FIXME: if port is not provided, data_dir is not respected\n\t\tfmt.Sprintf(\"-port=%d\", randomPort()),\n\t\tfmt.Sprintf(\"-data_dir=%s\", dir),\n\t}...)\n\treturn startCluster(flags...)\n}\n\nfunc startCluster(flags ...string) (vttest.LocalCluster, error) {\n\tschemaDirArg := \"-schema_dir=data\/schema\"\n\ttabletHostname := \"-tablet_hostname=localhost\"\n\tkeyspaceArg := \"-keyspaces=test_keyspace,app_customer\"\n\tnumShardsArg := \"-num_shards=2,2\"\n\tvschemaDDLAuthorizedUsers := \"-vschema_ddl_authorized_users=%\"\n\tos.Args = append(os.Args, []string{schemaDirArg, keyspaceArg, numShardsArg, tabletHostname, vschemaDDLAuthorizedUsers}...)\n\tos.Args = append(os.Args, flags...)\n\treturn runCluster()\n}\n\nfunc addColumnVindex(cluster vttest.LocalCluster, keyspace string, vschemaMigration string) error {\n\treturn execOnCluster(cluster, keyspace, func(conn *mysql.Conn) error {\n\t\t_, err := conn.ExecuteFetch(vschemaMigration, 1, false)\n\t\treturn err\n\t})\n}\n\nfunc execOnCluster(cluster vttest.LocalCluster, keyspace string, f func(*mysql.Conn) error) error {\n\tctx := context.Background()\n\tvtParams := mysql.ConnParams{\n\t\tHost:   \"localhost\",\n\t\tDbName: keyspace,\n\t\tPort:   cluster.Env.PortForProtocol(\"vtcombo_mysql_port\", \"\"),\n\t}\n\n\tconn, err := mysql.Connect(ctx, &vtParams)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\treturn f(conn)\n}\n\nfunc assertColumnVindex(t *testing.T, cluster vttest.LocalCluster, expected columnVindex) {\n\tserver := fmt.Sprintf(\"localhost:%v\", cluster.GrpcPort())\n\targs := []string{\"GetVSchema\", expected.keyspace}\n\tctx := context.Background()\n\n\terr := vtctlclient.RunCommandAndWait(ctx, server, args, func(e *logutil.Event) {\n\t\tvar keyspace vschema.Keyspace\n\t\tif err := protojson.Unmarshal([]byte(e.Value), &keyspace); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\tcolumnVindex := keyspace.Tables[expected.table].ColumnVindexes[0]\n\t\tactualVindex := keyspace.Vindexes[expected.vindex]\n\t\tassertEqual(t, actualVindex.Type, expected.vindexType, \"Actual vindex type different from expected\")\n\t\tassertEqual(t, columnVindex.Name, expected.vindex, \"Actual vindex name different from expected\")\n\t\tassertEqual(t, columnVindex.Columns[0], expected.column, \"Actual vindex column different from expected\")\n\t})\n\trequire.NoError(t, err)\n}\n\nfunc assertEqual(t *testing.T, actual string, expected string, message string) {\n\tif actual != expected {\n\t\tt.Errorf(\"%s: actual %s, expected %s\", message, actual, expected)\n\t}\n}\n\nfunc resetFlags(args []string, conf vttest.Config) {\n\tos.Args = args\n\tconfig = conf\n}\n\nfunc randomPort() int {\n\tv := rand.Int31n(20000)\n\treturn int(v + 10000)\n}\n<commit_msg>go\/cmd\/vttestserver\/vttestserver_test.go:  + TestForeignKeys()<commit_after>\/*\nCopyright 2019 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"google.golang.org\/protobuf\/encoding\/protojson\"\n\n\t\"vitess.io\/vitess\/go\/sqltypes\"\n\t\"vitess.io\/vitess\/go\/vt\/tlstest\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\n\t\"vitess.io\/vitess\/go\/mysql\"\n\n\t\"vitess.io\/vitess\/go\/vt\/vttest\"\n\n\t\"vitess.io\/vitess\/go\/vt\/proto\/logutil\"\n\t\"vitess.io\/vitess\/go\/vt\/proto\/vschema\"\n\t\"vitess.io\/vitess\/go\/vt\/vtctl\/vtctlclient\"\n)\n\ntype columnVindex struct {\n\tkeyspace   string\n\ttable      string\n\tvindex     string\n\tvindexType string\n\tcolumn     string\n}\n\nfunc TestRunsVschemaMigrations(t *testing.T) {\n\targs := os.Args\n\tconf := config\n\tdefer resetFlags(args, conf)\n\n\tcluster, err := startCluster()\n\tdefer cluster.TearDown()\n\n\tassert.NoError(t, err)\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"test_keyspace\", table: \"test_table\", vindex: \"my_vdx\", vindexType: \"hash\", column: \"id\"})\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"app_customer\", table: \"customers\", vindex: \"hash\", vindexType: \"hash\", column: \"id\"})\n\n\t\/\/ Add Hash vindex via vtgate execution on table\n\terr = addColumnVindex(cluster, \"test_keyspace\", \"alter vschema on test_table1 add vindex my_vdx (id)\")\n\tassert.NoError(t, err)\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"test_keyspace\", table: \"test_table1\", vindex: \"my_vdx\", vindexType: \"hash\", column: \"id\"})\n}\n\nfunc TestPersistentMode(t *testing.T) {\n\targs := os.Args\n\tconf := config\n\tdefer resetFlags(args, conf)\n\n\tdir, err := ioutil.TempDir(\"\/tmp\", \"vttestserver_persistent_mode_\")\n\tassert.NoError(t, err)\n\tdefer os.RemoveAll(dir)\n\n\tcluster, err := startPersistentCluster(dir)\n\tassert.NoError(t, err)\n\n\t\/\/ basic sanity checks similar to TestRunsVschemaMigrations\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"test_keyspace\", table: \"test_table\", vindex: \"my_vdx\", vindexType: \"hash\", column: \"id\"})\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"app_customer\", table: \"customers\", vindex: \"hash\", vindexType: \"hash\", column: \"id\"})\n\n\t\/\/ insert some data to ensure persistence across teardowns\n\terr = execOnCluster(cluster, \"app_customer\", func(conn *mysql.Conn) error {\n\t\t_, err := conn.ExecuteFetch(\"insert into customers (id, name) values (1, 'gopherson')\", 1, false)\n\t\treturn err\n\t})\n\tassert.NoError(t, err)\n\n\texpectedRows := [][]sqltypes.Value{\n\t\t{sqltypes.NewInt64(1), sqltypes.NewVarChar(\"gopherson\"), sqltypes.NULL},\n\t}\n\n\t\/\/ ensure data was actually inserted\n\tvar res *sqltypes.Result\n\terr = execOnCluster(cluster, \"app_customer\", func(conn *mysql.Conn) (err error) {\n\t\tres, err = conn.ExecuteFetch(\"SELECT * FROM customers\", 1, false)\n\t\treturn err\n\t})\n\tassert.NoError(t, err)\n\tassert.Equal(t, expectedRows, res.Rows)\n\n\t\/\/ reboot the persistent cluster\n\tcluster.TearDown()\n\tcluster, err = startPersistentCluster(dir)\n\tdefer cluster.TearDown()\n\tassert.NoError(t, err)\n\n\t\/\/ rerun our sanity checks to make sure vschema migrations are run during every startup\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"test_keyspace\", table: \"test_table\", vindex: \"my_vdx\", vindexType: \"hash\", column: \"id\"})\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"app_customer\", table: \"customers\", vindex: \"hash\", vindexType: \"hash\", column: \"id\"})\n\n\t\/\/ ensure previous data was successfully persisted\n\terr = execOnCluster(cluster, \"app_customer\", func(conn *mysql.Conn) (err error) {\n\t\tres, err = conn.ExecuteFetch(\"SELECT * FROM customers\", 1, false)\n\t\treturn err\n\t})\n\tassert.NoError(t, err)\n\tassert.Equal(t, expectedRows, res.Rows)\n}\n\nfunc TestForeignKeys(t *testing.T) {\n\targs := os.Args\n\tconf := config\n\tdefer resetFlags(args, conf)\n\n\tcluster, err := startCluster(\"-foreign_key_mode=allow\")\n\tassert.NoError(t, err)\n\tdefer cluster.TearDown()\n\n\terr = execOnCluster(cluster, \"test_keyspace\", func(conn *mysql.Conn) error {\n\t\t_, err := conn.ExecuteFetch(`CREATE TABLE test_table_2 (\n\t\t\tid BIGINT,\n\t\t\ttest_table_id BIGINT,\n\t\t\tFOREIGN KEY (test_table_id) REFERENCES test_table(id)\n\t\t)`, 1, false)\n\t\treturn err\n\t})\n\tassert.NoError(t, err)\n\n\tcluster.TearDown()\n\tcluster, err = startCluster(\"-foreign_key_mode=disallow\")\n\tassert.NoError(t, err)\n\tdefer cluster.TearDown()\n\n\terr = execOnCluster(cluster, \"test_keyspace\", func(conn *mysql.Conn) error {\n\t\t_, err := conn.ExecuteFetch(`CREATE TABLE test_table_2 (\n\t\t\tid BIGINT,\n\t\t\ttest_table_id BIGINT,\n\t\t\tFOREIGN KEY (test_table_id) REFERENCES test_table(id)\n\t\t)`, 1, false)\n\t\treturn err\n\t})\n\tassert.Error(t, err)\n}\n\nfunc TestCanVtGateExecute(t *testing.T) {\n\targs := os.Args\n\tconf := config\n\tdefer resetFlags(args, conf)\n\n\tcluster, err := startCluster()\n\tassert.NoError(t, err)\n\tdefer cluster.TearDown()\n\n\tclient, err := vtctlclient.New(fmt.Sprintf(\"localhost:%v\", cluster.GrpcPort()))\n\tassert.NoError(t, err)\n\tdefer client.Close()\n\tstream, err := client.ExecuteVtctlCommand(\n\t\tcontext.Background(),\n\t\t[]string{\n\t\t\t\"VtGateExecute\",\n\t\t\t\"-server\",\n\t\t\tfmt.Sprintf(\"localhost:%v\", cluster.GrpcPort()),\n\t\t\t\"select 'success';\",\n\t\t},\n\t\t30*time.Second,\n\t)\n\tassert.NoError(t, err)\n\n\tvar b strings.Builder\n\tb.Grow(1024)\n\nOut:\n\tfor {\n\t\te, err := stream.Recv()\n\t\tswitch err {\n\t\tcase nil:\n\t\t\tb.WriteString(e.Value)\n\t\tcase io.EOF:\n\t\t\tbreak Out\n\t\tdefault:\n\t\t\tassert.FailNow(t, err.Error())\n\t\t}\n\t}\n\n\tassert.Contains(t, b.String(), \"success\")\n}\n\nfunc TestMtlsAuth(t *testing.T) {\n\targs := os.Args\n\tconf := config\n\tdefer resetFlags(args, conf)\n\n\t\/\/ Our test root.\n\troot, err := ioutil.TempDir(\"\", \"tlstest\")\n\tif err != nil {\n\t\tt.Fatalf(\"TempDir failed: %v\", err)\n\t}\n\tdefer os.RemoveAll(root)\n\n\t\/\/ Create the certs and configs.\n\ttlstest.CreateCA(root)\n\tcaCert := path.Join(root, \"ca-cert.pem\")\n\n\ttlstest.CreateSignedCert(root, tlstest.CA, \"01\", \"vtctld\", \"vtctld.example.com\")\n\tcert := path.Join(root, \"vtctld-cert.pem\")\n\tkey := path.Join(root, \"vtctld-key.pem\")\n\n\ttlstest.CreateSignedCert(root, tlstest.CA, \"02\", \"client\", \"ClientApp\")\n\tclientCert := path.Join(root, \"client-cert.pem\")\n\tclientKey := path.Join(root, \"client-key.pem\")\n\n\t\/\/ When cluster starts it will apply SQL and VSchema migrations in the configured schema_dir folder\n\t\/\/ With mtls authorization enabled, the authorized CN must match the certificate's CN\n\tcluster, err := startCluster(\n\t\t\"-grpc_auth_mode=mtls\",\n\t\tfmt.Sprintf(\"-grpc_key=%s\", key),\n\t\tfmt.Sprintf(\"-grpc_cert=%s\", cert),\n\t\tfmt.Sprintf(\"-grpc_ca=%s\", caCert),\n\t\tfmt.Sprintf(\"-vtctld_grpc_key=%s\", clientKey),\n\t\tfmt.Sprintf(\"-vtctld_grpc_cert=%s\", clientCert),\n\t\tfmt.Sprintf(\"-vtctld_grpc_ca=%s\", caCert),\n\t\tfmt.Sprintf(\"-grpc_auth_mtls_allowed_substrings=%s\", \"CN=ClientApp\"))\n\tassert.NoError(t, err)\n\tdefer cluster.TearDown()\n\n\t\/\/ startCluster will apply vschema migrations using vtctl grpc and the clientCert.\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"test_keyspace\", table: \"test_table\", vindex: \"my_vdx\", vindexType: \"hash\", column: \"id\"})\n\tassertColumnVindex(t, cluster, columnVindex{keyspace: \"app_customer\", table: \"customers\", vindex: \"hash\", vindexType: \"hash\", column: \"id\"})\n}\n\nfunc TestMtlsAuthUnauthorizedFails(t *testing.T) {\n\targs := os.Args\n\tconf := config\n\tdefer resetFlags(args, conf)\n\n\t\/\/ Our test root.\n\troot, err := ioutil.TempDir(\"\", \"tlstest\")\n\tif err != nil {\n\t\tt.Fatalf(\"TempDir failed: %v\", err)\n\t}\n\tdefer os.RemoveAll(root)\n\n\t\/\/ Create the certs and configs.\n\ttlstest.CreateCA(root)\n\tcaCert := path.Join(root, \"ca-cert.pem\")\n\n\ttlstest.CreateSignedCert(root, tlstest.CA, \"01\", \"vtctld\", \"vtctld.example.com\")\n\tcert := path.Join(root, \"vtctld-cert.pem\")\n\tkey := path.Join(root, \"vtctld-key.pem\")\n\n\ttlstest.CreateSignedCert(root, tlstest.CA, \"02\", \"client\", \"AnotherApp\")\n\tclientCert := path.Join(root, \"client-cert.pem\")\n\tclientKey := path.Join(root, \"client-key.pem\")\n\n\t\/\/ When cluster starts it will apply SQL and VSchema migrations in the configured schema_dir folder\n\t\/\/ For mtls authorization failure by providing a client certificate with different CN thant the\n\t\/\/ authorized in the configuration\n\tcluster, err := startCluster(\n\t\t\"-grpc_auth_mode=mtls\",\n\t\tfmt.Sprintf(\"-grpc_key=%s\", key),\n\t\tfmt.Sprintf(\"-grpc_cert=%s\", cert),\n\t\tfmt.Sprintf(\"-grpc_ca=%s\", caCert),\n\t\tfmt.Sprintf(\"-vtctld_grpc_key=%s\", clientKey),\n\t\tfmt.Sprintf(\"-vtctld_grpc_cert=%s\", clientCert),\n\t\tfmt.Sprintf(\"-vtctld_grpc_ca=%s\", caCert),\n\t\tfmt.Sprintf(\"-grpc_auth_mtls_allowed_substrings=%s\", \"CN=ClientApp\"))\n\tdefer cluster.TearDown()\n\n\tassert.Error(t, err)\n\tassert.Contains(t, err.Error(), \"code = Unauthenticated desc = client certificate not authorized\")\n}\n\nfunc startPersistentCluster(dir string, flags ...string) (vttest.LocalCluster, error) {\n\tflags = append(flags, []string{\n\t\t\"-persistent_mode\",\n\t\t\/\/ FIXME: if port is not provided, data_dir is not respected\n\t\tfmt.Sprintf(\"-port=%d\", randomPort()),\n\t\tfmt.Sprintf(\"-data_dir=%s\", dir),\n\t}...)\n\treturn startCluster(flags...)\n}\n\nfunc startCluster(flags ...string) (vttest.LocalCluster, error) {\n\tschemaDirArg := \"-schema_dir=data\/schema\"\n\ttabletHostname := \"-tablet_hostname=localhost\"\n\tkeyspaceArg := \"-keyspaces=test_keyspace,app_customer\"\n\tnumShardsArg := \"-num_shards=2,2\"\n\tvschemaDDLAuthorizedUsers := \"-vschema_ddl_authorized_users=%\"\n\tos.Args = append(os.Args, []string{schemaDirArg, keyspaceArg, numShardsArg, tabletHostname, vschemaDDLAuthorizedUsers}...)\n\tos.Args = append(os.Args, flags...)\n\treturn runCluster()\n}\n\nfunc addColumnVindex(cluster vttest.LocalCluster, keyspace string, vschemaMigration string) error {\n\treturn execOnCluster(cluster, keyspace, func(conn *mysql.Conn) error {\n\t\t_, err := conn.ExecuteFetch(vschemaMigration, 1, false)\n\t\treturn err\n\t})\n}\n\nfunc execOnCluster(cluster vttest.LocalCluster, keyspace string, f func(*mysql.Conn) error) error {\n\tctx := context.Background()\n\tvtParams := mysql.ConnParams{\n\t\tHost:   \"localhost\",\n\t\tDbName: keyspace,\n\t\tPort:   cluster.Env.PortForProtocol(\"vtcombo_mysql_port\", \"\"),\n\t}\n\n\tconn, err := mysql.Connect(ctx, &vtParams)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\treturn f(conn)\n}\n\nfunc assertColumnVindex(t *testing.T, cluster vttest.LocalCluster, expected columnVindex) {\n\tserver := fmt.Sprintf(\"localhost:%v\", cluster.GrpcPort())\n\targs := []string{\"GetVSchema\", expected.keyspace}\n\tctx := context.Background()\n\n\terr := vtctlclient.RunCommandAndWait(ctx, server, args, func(e *logutil.Event) {\n\t\tvar keyspace vschema.Keyspace\n\t\tif err := protojson.Unmarshal([]byte(e.Value), &keyspace); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\n\t\tcolumnVindex := keyspace.Tables[expected.table].ColumnVindexes[0]\n\t\tactualVindex := keyspace.Vindexes[expected.vindex]\n\t\tassertEqual(t, actualVindex.Type, expected.vindexType, \"Actual vindex type different from expected\")\n\t\tassertEqual(t, columnVindex.Name, expected.vindex, \"Actual vindex name different from expected\")\n\t\tassertEqual(t, columnVindex.Columns[0], expected.column, \"Actual vindex column different from expected\")\n\t})\n\trequire.NoError(t, err)\n}\n\nfunc assertEqual(t *testing.T, actual string, expected string, message string) {\n\tif actual != expected {\n\t\tt.Errorf(\"%s: actual %s, expected %s\", message, actual, expected)\n\t}\n}\n\nfunc resetFlags(args []string, conf vttest.Config) {\n\tos.Args = args\n\tconfig = conf\n}\n\nfunc randomPort() int {\n\tv := rand.Int31n(20000)\n\treturn int(v + 10000)\n}\n<|endoftext|>"}
{"text":"<commit_before>package kloud\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"koding\/kites\/kloud\/contexthelper\/request\"\n\t\"koding\/kites\/kloud\/contexthelper\/session\"\n\t\"koding\/kites\/kloud\/klient\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/koding\/kite\"\n)\n\ntype AdminRequest struct {\n\tMachineId string `json:\"machineId\"`\n\tGroupName string `json:\"groupName\"`\n}\n\nfunc (k *Kloud) AdminAdd(r *kite.Request) (interface{}, error) {\n\tkl, err := k.authorizedKlient(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := kl.AddUser(r.Username); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn true, nil\n}\n\nfunc (k *Kloud) AdminRemove(r *kite.Request) (interface{}, error) {\n\tkl, err := k.authorizedKlient(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := kl.RemoveUser(r.Username); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn true, nil\n}\n\nfunc (k *Kloud) authorizedKlient(r *kite.Request) (*klient.Klient, error) {\n\tif r.Args == nil {\n\t\treturn nil, NewError(ErrNoArguments)\n\t}\n\n\tvar args *AdminRequest\n\tif err := r.Args.One().Unmarshal(&args); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif args.MachineId == \"\" {\n\t\treturn nil, errors.New(\"machineId is not passed\")\n\t}\n\n\tif args.GroupName == \"\" {\n\t\treturn nil, errors.New(\"groupName is not passed\")\n\t}\n\n\tk.Log.Debug(\"Got arguments %+v for method: %s\", args, r.Method)\n\n\tisAdmin, err := modelhelper.IsAdmin(args.GroupName, r.Username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !isAdmin {\n\t\treturn nil, fmt.Errorf(\"User '%s' is not an admin of group '%s'\", r.Username, args.GroupName)\n\t}\n\n\tmachine, err := modelhelper.GetMachine(args.MachineId)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getMachine err: %s\", err)\n\t}\n\n\tg, err := modelhelper.GetGroup(args.GroupName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisGroupMember := false\n\tfor _, group := range machine.Groups {\n\t\tif group.Id.Hex() == g.Id.Hex() {\n\t\t\tisGroupMember = true\n\t\t}\n\t}\n\tif !isGroupMember {\n\t\treturn nil, fmt.Errorf(\"'%s' machine does not belong to '%s' group\",\n\t\t\targs.MachineId, args.GroupName)\n\t}\n\n\t\/\/ Now we are ready to go.\n\tctx := request.NewContext(context.Background(), r)\n\tctx = k.ContextCreator(ctx)\n\tsess, ok := session.FromContext(ctx)\n\tif !ok {\n\t\treturn nil, errors.New(\"internal server error (err: session context is not available)\")\n\t}\n\n\treturn klient.NewWithTimeout(sess.Kite, machine.QueryString, time.Second*10)\n}\n<commit_msg>kloud: add more debug<commit_after>package kloud\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"koding\/kites\/kloud\/contexthelper\/request\"\n\t\"koding\/kites\/kloud\/contexthelper\/session\"\n\t\"koding\/kites\/kloud\/klient\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/koding\/kite\"\n)\n\ntype AdminRequest struct {\n\tMachineId string `json:\"machineId\"`\n\tGroupName string `json:\"groupName\"`\n}\n\nfunc (k *Kloud) AdminAdd(r *kite.Request) (interface{}, error) {\n\tkl, err := k.authorizedKlient(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := kl.AddUser(r.Username); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn true, nil\n}\n\nfunc (k *Kloud) AdminRemove(r *kite.Request) (interface{}, error) {\n\tkl, err := k.authorizedKlient(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := kl.RemoveUser(r.Username); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn true, nil\n}\n\nfunc (k *Kloud) authorizedKlient(r *kite.Request) (*klient.Klient, error) {\n\tif r.Args == nil {\n\t\treturn nil, NewError(ErrNoArguments)\n\t}\n\n\tvar args *AdminRequest\n\tif err := r.Args.One().Unmarshal(&args); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif args.MachineId == \"\" {\n\t\treturn nil, errors.New(\"machineId is not passed\")\n\t}\n\n\tif args.GroupName == \"\" {\n\t\treturn nil, errors.New(\"groupName is not passed\")\n\t}\n\n\tk.Log.Debug(\"Got arguments %+v for method: %s\", args, r.Method)\n\n\tisAdmin, err := modelhelper.IsAdmin(args.GroupName, r.Username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif !isAdmin {\n\t\treturn nil, fmt.Errorf(\"User '%s' is not an admin of group '%s'\", r.Username, args.GroupName)\n\t}\n\n\tk.Log.Debug(\"User '%s' is an admin. Checking for machine permission\", r.Username)\n\n\tmachine, err := modelhelper.GetMachine(args.MachineId)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getMachine err: %s\", err)\n\t}\n\n\tg, err := modelhelper.GetGroup(args.GroupName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tisGroupMember := false\n\tfor _, group := range machine.Groups {\n\t\tif group.Id.Hex() == g.Id.Hex() {\n\t\t\tisGroupMember = true\n\t\t}\n\t}\n\tif !isGroupMember {\n\t\treturn nil, fmt.Errorf(\"'%s' machine does not belong to '%s' group\",\n\t\t\targs.MachineId, args.GroupName)\n\t}\n\n\tk.Log.Debug(\"Incoming user is authorized, setting up DB and Klient connection\")\n\n\t\/\/ Now we are ready to go.\n\tctx := request.NewContext(context.Background(), r)\n\tctx = k.ContextCreator(ctx)\n\tsess, ok := session.FromContext(ctx)\n\tif !ok {\n\t\treturn nil, errors.New(\"internal server error (err: session context is not available)\")\n\t}\n\n\tk.Log.Debug(\"Calling Klient method: %s\", r.Method)\n\treturn klient.NewWithTimeout(sess.Kite, machine.QueryString, time.Second*10)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ A library for easing the interaction with klient.\npackage klient\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"time\"\n\n\t\"koding\/klient\/client\"\n\t\"koding\/klient\/command\"\n\t\"koding\/klient\/fs\"\n\t\"koding\/klient\/remote\/req\"\n\t\"koding\/klientctl\/config\"\n\t\"koding\/klientctl\/list\"\n\n\t\"github.com\/koding\/kite\"\n\t\"github.com\/koding\/kite\/dnode\"\n)\n\n\/\/ defaultKlientTimeout is a general timeout for klient communications.\nconst defaultKlientTimeout = 5 * time.Second\n\n\/\/ Klient implements methods that klientctl uses when calling Klient, unmarshalling\n\/\/ automatically into the proper methods.\ntype Klient struct {\n\t\/\/ The Teller is Klient's main \"transport\" for communication with the internal\n\t\/\/ Client.\n\t\/\/\n\t\/\/ Why an interface here? Rather than Requiring a kite.Client specifically, the\n\t\/\/ Tell() method is the only thing required. As such, the Klient struct itself,\n\t\/\/ some older Transport structs, and pretty much any struct that talks to Kites\n\t\/\/ has this Tell method and Satisfies the interface.\n\tTeller interface {\n\t\tTell(string, ...interface{}) (*dnode.Partial, error)\n\t}\n\n\t\/\/ Client is exposed (and via GetClient() mainly to allow the Klient struct\n\t\/\/ to be backwards compatible with non-Klient using methods.\n\t\/\/\n\t\/\/ All actual communication is done via the Teller - this field purely exists\n\t\/\/ for the GetClient() method.\n\tClient *kite.Client\n}\n\n\/\/ NewKlient creates a Klient instance from the given kite.Client.\nfunc NewKlient(c *kite.Client) *Klient {\n\treturn &Klient{\n\t\tClient: c,\n\t\tTeller: c,\n\t}\n}\n\n\/\/ KlientOptions contains various fields for connecting to a klient.\ntype KlientOptions struct {\n\t\/\/ Address is the path to the Klient.\n\tAddress string\n\n\t\/\/ KiteKeyPath is the full path to kite.key, which will be loaded and used\n\t\/\/ to authorize kdbin requests to Klient.\n\tKiteKeyPath string\n\n\t\/\/ Name, as passed to the first argument in `kite.New()`.\n\tName string\n\n\t\/\/ Version, as passed to the second argument to `kite.New()`.\n\tVersion string\n\n\t\/\/ Environment for the kite.Config.Environemnt.\n\tEnvironment string\n}\n\n\/\/ NewKlientOptions returns KlientOptions initialized to default values.\nfunc NewKlientOptions() KlientOptions {\n\treturn KlientOptions{\n\t\tAddress:     config.Konfig.KlientURL,\n\t\tKiteKeyPath: config.Konfig.KiteKeyFile,\n\t\tName:        config.Name,\n\t\tVersion:     config.KiteVersion,\n\t\tEnvironment: config.Environment,\n\t}\n}\n\n\/\/ CreateKlientClient creates a kite with default KlientOptions and returns a\n\/\/ Kite Client to talk to that Klient.\nfunc CreateKlientWithDefaultOpts() (*kite.Client, error) {\n\treturn CreateKlientClient(NewKlientOptions())\n}\n\n\/\/ CreateKlientClient creates a kite to the klient specified by KlientOptions.\n\/\/ In most cases CreateKlientWithDefaultOpts should be used instead of this, ie\n\/\/ this should be used only if you want to override KlientOptions.\nfunc CreateKlientClient(opts KlientOptions) (*kite.Client, error) {\n\tif opts.Version == \"\" {\n\t\treturn nil, errors.New(\"CreateKlientClient: Version is required\")\n\t}\n\n\tif opts.Address == \"\" {\n\t\treturn nil, errors.New(\"CreateKlientClient: Address is required\")\n\t}\n\n\tk := kite.New(opts.Name, opts.Version)\n\tk.Config.Environment = opts.Environment\n\tc := k.NewClient(opts.Address)\n\n\t\/\/ If a key path is declared, load it and setup auth.\n\tif opts.KiteKeyPath != \"\" {\n\t\tdata, err := ioutil.ReadFile(opts.KiteKeyPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tc.Auth = &kite.Auth{\n\t\t\tType: \"kiteKey\",\n\t\t\tKey:  strings.TrimSpace(string(data)),\n\t\t}\n\t}\n\n\treturn c, nil\n}\n\n\/\/ NewDefaultDialedKlient creates a pre-dialed Klient instance using default\n\/\/ klient options.\nfunc NewDefaultDialedKlient() (*Klient, error) {\n\treturn NewDialedKlient(NewKlientOptions())\n}\n\n\/\/ NewDialedKlient creates a pre-dialed Klient instance. In most cases\n\/\/ NewDefaultDialedKlient should be used instead of this, ie this should be used\n\/\/ only if you want to override KlientOptions.\nfunc NewDialedKlient(opts KlientOptions) (*Klient, error) {\n\tc, err := CreateKlientClient(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := c.Dial(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewKlient(c), nil\n}\n\nfunc (k *Klient) Tell(methodName string, reqs ...interface{}) (*dnode.Partial, error) {\n\tif k.Teller == nil {\n\t\treturn nil, errors.New(\"Missing Teller on Klient struct\")\n\t}\n\n\treturn k.Teller.Tell(methodName, reqs...)\n}\n\n\/\/ GetClient is a utility function for getting the underlying kite Client\n\/\/ back from a Klient struct hidden behind an interface. Used mainly to\n\/\/ interact with legacy code.\nfunc (k *Klient) GetClient() *kite.Client {\n\treturn k.Client\n}\n\n\/\/ RemoteList the current machines.\nfunc (k *Klient) RemoteList() (list.KiteInfos, error) {\n\tres, err := k.Client.TellWithTimeout(\"remote.list\", defaultKlientTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar infos []list.KiteInfo\n\tif err := res.Unmarshal(&infos); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn infos, nil\n}\n\n\/\/ RemoteCache calls klient's remote.cache method.\n\/\/\n\/\/ Note that due to how the remote\/req library is setup, this function needs to\n\/\/ take the callback as a separate argument for now. This will be improved\n\/\/ in the future, in one way or another.\nfunc (k *Klient) RemoteCache(r req.Cache, cb func(par *dnode.Partial)) error {\n\tcacheReq := struct {\n\t\treq.Cache\n\t\tProgress dnode.Function `json:\"progress\"`\n\t}{\n\t\tCache: r,\n\t}\n\n\tif cb != nil {\n\t\tcacheReq.Progress = dnode.Callback(cb)\n\t}\n\n\t\/\/ No response from cacheFolder currently.\n\t_, err := k.Tell(\"remote.cacheFolder\", cacheReq)\n\treturn err\n}\n\n\/\/ RemoteMountFolder calls klient's remote.mountFolder method. If there are\n\/\/ any warnings, those are returned here.\nfunc (k *Klient) RemoteMountFolder(r req.MountFolder) (string, error) {\n\tresp, err := k.Tell(\"remote.mountFolder\", r)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar warning string\n\t\/\/ TODO: Ignore the nil unmarshal error, but return others.\n\tresp.Unmarshal(&warning)\n\n\treturn warning, nil\n}\n\n\/\/ RemoteStatus calls klients remote.status method.\nfunc (k *Klient) RemoteStatus(r req.Status) error {\n\t_, err := k.Tell(\"remote.status\", r)\n\treturn err\n}\n\n\/\/ RemoteMountInfo calls klients remote.mountInfo method.\nfunc (k *Klient) RemoteMountInfo(mountName string) (req.MountInfoResponse, error) {\n\tr := req.MountInfo{MountName: mountName}\n\tresp, err := k.Tell(\"remote.mountInfo\", r)\n\tif err != nil {\n\t\treturn req.MountInfoResponse{}, err\n\t}\n\n\tvar mountInfo req.MountInfoResponse\n\t\/\/ TODO: Ignore the nil unmarshal error, but return others.\n\tresp.Unmarshal(&mountInfo)\n\n\treturn mountInfo, nil\n}\n\n\/\/ RemoteRemount calls klient's remote.remount method.\nfunc (k *Klient) RemoteRemount(mountName string) error {\n\tr := req.Remount{MountName: mountName}\n\t_, err := k.Tell(\"remote.remount\", r)\n\treturn err\n}\n\n\/\/ RemoteExec calls the `remote.exec` method.\nfunc (k *Klient) RemoteExec(machineName, c string) (command.Output, error) {\n\tvar res command.Output\n\treq := req.Exec{Machine: machineName, Command: c}\n\tkRes, err := k.Tell(\"remote.exec\", req)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\n\treturn res, kRes.Unmarshal(&res)\n}\n\nfunc (k *Klient) RemoteReadDirectory(mountName, remotePath string) ([]fs.FileEntry, error) {\n\tr := req.ReadDirectoryOptions{\n\t\tMachine: mountName,\n\t\tReadDirectoryOptions: fs.ReadDirectoryOptions{\n\t\t\tPath: remotePath,\n\t\t},\n\t}\n\n\tres, err := k.Tell(\"remote.readDirectory\", r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresMap, err := res.Map()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpartial, ok := resMap[\"files\"]\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\tfilePartials, err := partial.Slice()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfiles := make([]fs.FileEntry, len(filePartials))\n\tfor i, p := range filePartials {\n\t\tvar fe fs.FileEntry\n\t\tif err := p.Unmarshal(&fe); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfiles[i] = fe\n\t}\n\n\treturn files, nil\n}\n\n\/\/ RemoteCurrentUsername calls klient's `remote.currentUsername` method\nfunc (k *Klient) RemoteCurrentUsername(opts req.CurrentUsernameOptions) (string, error) {\n\tvar username string\n\n\tkRes, err := k.Tell(\"remote.currentUsername\", opts)\n\tif err != nil {\n\t\treturn username, err\n\t}\n\n\treturn username, kRes.Unmarshal(&username)\n}\n\n\/\/ RemoteGetPathSize calls the klient's `remote.getPathSize` method\nfunc (k *Klient) RemoteGetPathSize(opts req.GetPathSizeOptions) (uint64, error) {\n\tvar size uint64\n\n\tkRes, err := k.Tell(\"remote.getPathSize\", opts)\n\tif err != nil {\n\t\treturn size, err\n\t}\n\n\treturn size, kRes.Unmarshal(&size)\n}\n\nfunc (k *Klient) LocalOpenFiles(files ...string) error {\n\t_, err := k.Tell(\"client.Publish\", FilesEvent{\n\t\tPublishRequest: client.PublishRequest{EventName: \"openFiles\"},\n\t\tFiles:          files,\n\t})\n\n\treturn err\n}\n<commit_msg>kd: fix reading kite.key<commit_after>\/\/ A library for easing the interaction with klient.\npackage klient\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"time\"\n\n\t\"koding\/klient\/client\"\n\t\"koding\/klient\/command\"\n\t\"koding\/klient\/fs\"\n\t\"koding\/klient\/remote\/req\"\n\t\"koding\/klientctl\/config\"\n\t\"koding\/klientctl\/list\"\n\n\t\"github.com\/koding\/kite\"\n\t\"github.com\/koding\/kite\/dnode\"\n)\n\n\/\/ defaultKlientTimeout is a general timeout for klient communications.\nconst defaultKlientTimeout = 5 * time.Second\n\n\/\/ Klient implements methods that klientctl uses when calling Klient, unmarshalling\n\/\/ automatically into the proper methods.\ntype Klient struct {\n\t\/\/ The Teller is Klient's main \"transport\" for communication with the internal\n\t\/\/ Client.\n\t\/\/\n\t\/\/ Why an interface here? Rather than Requiring a kite.Client specifically, the\n\t\/\/ Tell() method is the only thing required. As such, the Klient struct itself,\n\t\/\/ some older Transport structs, and pretty much any struct that talks to Kites\n\t\/\/ has this Tell method and Satisfies the interface.\n\tTeller interface {\n\t\tTell(string, ...interface{}) (*dnode.Partial, error)\n\t}\n\n\t\/\/ Client is exposed (and via GetClient() mainly to allow the Klient struct\n\t\/\/ to be backwards compatible with non-Klient using methods.\n\t\/\/\n\t\/\/ All actual communication is done via the Teller - this field purely exists\n\t\/\/ for the GetClient() method.\n\tClient *kite.Client\n}\n\n\/\/ NewKlient creates a Klient instance from the given kite.Client.\nfunc NewKlient(c *kite.Client) *Klient {\n\treturn &Klient{\n\t\tClient: c,\n\t\tTeller: c,\n\t}\n}\n\n\/\/ KlientOptions contains various fields for connecting to a klient.\ntype KlientOptions struct {\n\t\/\/ Address is the path to the Klient.\n\tAddress string\n\n\t\/\/ KiteKeyPath is the full path to kite.key, which will be loaded and used\n\t\/\/ to authorize kdbin requests to Klient.\n\tKiteKeyPath string\n\n\t\/\/ KiteKey is a content of kite.key, which is used for\n\t\/\/ authenticating kd with other klients.\n\t\/\/\n\t\/\/ If not empty, this fields is used instead of KiteKeyPath.\n\tKiteKey string\n\n\t\/\/ Name, as passed to the first argument in `kite.New()`.\n\tName string\n\n\t\/\/ Version, as passed to the second argument to `kite.New()`.\n\tVersion string\n\n\t\/\/ Environment for the kite.Config.Environemnt.\n\tEnvironment string\n}\n\n\/\/ NewKlientOptions returns KlientOptions initialized to default values.\nfunc NewKlientOptions() KlientOptions {\n\treturn KlientOptions{\n\t\tAddress:     config.Konfig.KlientURL,\n\t\tKiteKeyPath: config.Konfig.KiteKeyFile,\n\t\tKiteKey:     config.Konfig.KiteKey,\n\t\tName:        config.Name,\n\t\tVersion:     config.KiteVersion,\n\t\tEnvironment: config.Environment,\n\t}\n}\n\n\/\/ CreateKlientClient creates a kite with default KlientOptions and returns a\n\/\/ Kite Client to talk to that Klient.\nfunc CreateKlientWithDefaultOpts() (*kite.Client, error) {\n\treturn CreateKlientClient(NewKlientOptions())\n}\n\n\/\/ CreateKlientClient creates a kite to the klient specified by KlientOptions.\n\/\/ In most cases CreateKlientWithDefaultOpts should be used instead of this, ie\n\/\/ this should be used only if you want to override KlientOptions.\nfunc CreateKlientClient(opts KlientOptions) (*kite.Client, error) {\n\tif opts.Version == \"\" {\n\t\treturn nil, errors.New(\"CreateKlientClient: Version is required\")\n\t}\n\n\tif opts.Address == \"\" {\n\t\treturn nil, errors.New(\"CreateKlientClient: Address is required\")\n\t}\n\n\tk := kite.New(opts.Name, opts.Version)\n\tk.Config.Environment = opts.Environment\n\tc := k.NewClient(opts.Address)\n\n\tif opts.KiteKey != \"\" {\n\t\tc.Auth = &kite.Auth{\n\t\t\tType: \"kiteKey\",\n\t\t\tKey:  opts.KiteKey,\n\t\t}\n\t} else if opts.KiteKeyPath != \"\" {\n\t\t\/\/ If a key path is declared, load it and setup auth.\n\t\tdata, err := ioutil.ReadFile(opts.KiteKeyPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tc.Auth = &kite.Auth{\n\t\t\tType: \"kiteKey\",\n\t\t\tKey:  strings.TrimSpace(string(data)),\n\t\t}\n\t}\n\n\treturn c, nil\n}\n\n\/\/ NewDefaultDialedKlient creates a pre-dialed Klient instance using default\n\/\/ klient options.\nfunc NewDefaultDialedKlient() (*Klient, error) {\n\treturn NewDialedKlient(NewKlientOptions())\n}\n\n\/\/ NewDialedKlient creates a pre-dialed Klient instance. In most cases\n\/\/ NewDefaultDialedKlient should be used instead of this, ie this should be used\n\/\/ only if you want to override KlientOptions.\nfunc NewDialedKlient(opts KlientOptions) (*Klient, error) {\n\tc, err := CreateKlientClient(opts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := c.Dial(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewKlient(c), nil\n}\n\nfunc (k *Klient) Tell(methodName string, reqs ...interface{}) (*dnode.Partial, error) {\n\tif k.Teller == nil {\n\t\treturn nil, errors.New(\"Missing Teller on Klient struct\")\n\t}\n\n\treturn k.Teller.Tell(methodName, reqs...)\n}\n\n\/\/ GetClient is a utility function for getting the underlying kite Client\n\/\/ back from a Klient struct hidden behind an interface. Used mainly to\n\/\/ interact with legacy code.\nfunc (k *Klient) GetClient() *kite.Client {\n\treturn k.Client\n}\n\n\/\/ RemoteList the current machines.\nfunc (k *Klient) RemoteList() (list.KiteInfos, error) {\n\tres, err := k.Client.TellWithTimeout(\"remote.list\", defaultKlientTimeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar infos []list.KiteInfo\n\tif err := res.Unmarshal(&infos); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn infos, nil\n}\n\n\/\/ RemoteCache calls klient's remote.cache method.\n\/\/\n\/\/ Note that due to how the remote\/req library is setup, this function needs to\n\/\/ take the callback as a separate argument for now. This will be improved\n\/\/ in the future, in one way or another.\nfunc (k *Klient) RemoteCache(r req.Cache, cb func(par *dnode.Partial)) error {\n\tcacheReq := struct {\n\t\treq.Cache\n\t\tProgress dnode.Function `json:\"progress\"`\n\t}{\n\t\tCache: r,\n\t}\n\n\tif cb != nil {\n\t\tcacheReq.Progress = dnode.Callback(cb)\n\t}\n\n\t\/\/ No response from cacheFolder currently.\n\t_, err := k.Tell(\"remote.cacheFolder\", cacheReq)\n\treturn err\n}\n\n\/\/ RemoteMountFolder calls klient's remote.mountFolder method. If there are\n\/\/ any warnings, those are returned here.\nfunc (k *Klient) RemoteMountFolder(r req.MountFolder) (string, error) {\n\tresp, err := k.Tell(\"remote.mountFolder\", r)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar warning string\n\t\/\/ TODO: Ignore the nil unmarshal error, but return others.\n\tresp.Unmarshal(&warning)\n\n\treturn warning, nil\n}\n\n\/\/ RemoteStatus calls klients remote.status method.\nfunc (k *Klient) RemoteStatus(r req.Status) error {\n\t_, err := k.Tell(\"remote.status\", r)\n\treturn err\n}\n\n\/\/ RemoteMountInfo calls klients remote.mountInfo method.\nfunc (k *Klient) RemoteMountInfo(mountName string) (req.MountInfoResponse, error) {\n\tr := req.MountInfo{MountName: mountName}\n\tresp, err := k.Tell(\"remote.mountInfo\", r)\n\tif err != nil {\n\t\treturn req.MountInfoResponse{}, err\n\t}\n\n\tvar mountInfo req.MountInfoResponse\n\t\/\/ TODO: Ignore the nil unmarshal error, but return others.\n\tresp.Unmarshal(&mountInfo)\n\n\treturn mountInfo, nil\n}\n\n\/\/ RemoteRemount calls klient's remote.remount method.\nfunc (k *Klient) RemoteRemount(mountName string) error {\n\tr := req.Remount{MountName: mountName}\n\t_, err := k.Tell(\"remote.remount\", r)\n\treturn err\n}\n\n\/\/ RemoteExec calls the `remote.exec` method.\nfunc (k *Klient) RemoteExec(machineName, c string) (command.Output, error) {\n\tvar res command.Output\n\treq := req.Exec{Machine: machineName, Command: c}\n\tkRes, err := k.Tell(\"remote.exec\", req)\n\tif err != nil {\n\t\treturn res, err\n\t}\n\n\treturn res, kRes.Unmarshal(&res)\n}\n\nfunc (k *Klient) RemoteReadDirectory(mountName, remotePath string) ([]fs.FileEntry, error) {\n\tr := req.ReadDirectoryOptions{\n\t\tMachine: mountName,\n\t\tReadDirectoryOptions: fs.ReadDirectoryOptions{\n\t\t\tPath: remotePath,\n\t\t},\n\t}\n\n\tres, err := k.Tell(\"remote.readDirectory\", r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresMap, err := res.Map()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpartial, ok := resMap[\"files\"]\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\n\tfilePartials, err := partial.Slice()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfiles := make([]fs.FileEntry, len(filePartials))\n\tfor i, p := range filePartials {\n\t\tvar fe fs.FileEntry\n\t\tif err := p.Unmarshal(&fe); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfiles[i] = fe\n\t}\n\n\treturn files, nil\n}\n\n\/\/ RemoteCurrentUsername calls klient's `remote.currentUsername` method\nfunc (k *Klient) RemoteCurrentUsername(opts req.CurrentUsernameOptions) (string, error) {\n\tvar username string\n\n\tkRes, err := k.Tell(\"remote.currentUsername\", opts)\n\tif err != nil {\n\t\treturn username, err\n\t}\n\n\treturn username, kRes.Unmarshal(&username)\n}\n\n\/\/ RemoteGetPathSize calls the klient's `remote.getPathSize` method\nfunc (k *Klient) RemoteGetPathSize(opts req.GetPathSizeOptions) (uint64, error) {\n\tvar size uint64\n\n\tkRes, err := k.Tell(\"remote.getPathSize\", opts)\n\tif err != nil {\n\t\treturn size, err\n\t}\n\n\treturn size, kRes.Unmarshal(&size)\n}\n\nfunc (k *Klient) LocalOpenFiles(files ...string) error {\n\t_, err := k.Tell(\"client.Publish\", FilesEvent{\n\t\tPublishRequest: client.PublishRequest{EventName: \"openFiles\"},\n\t\tFiles:          files,\n\t})\n\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\tkodingmodels \"koding\/db\/models\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"socialapi\/models\"\n\t\"strconv\"\n\n\t\"labix.org\/v2\/mgo\/bson\"\n\n\t\"github.com\/koding\/bongo\"\n\t\"github.com\/koding\/logging\"\n)\n\nfunc setDefaults(log logging.Logger) {\n\tgroup, err := modelhelper.GetGroup(models.Channel_KODING_NAME)\n\tif err != nil {\n\t\tlog.Error(\"err while fetching koding group: %s\", err.Error())\n\t\treturn\n\t}\n\n\tlog.Debug(\"mongo group found\")\n\n\tsetPublicChannel(log, group)\n\tsetSetChangeLogChannel(log, group)\n\tlog.Info(\"socialApi defaults are created\")\n}\n\nfunc setPublicChannel(log logging.Logger, group *kodingmodels.Group) {\n\tc := models.NewChannel()\n\tselector := map[string]interface{}{\n\t\t\"type_constant\": models.Channel_TYPE_GROUP,\n\t\t\"group_name\":    models.Channel_KODING_NAME,\n\t}\n\n\terr := c.One(bongo.NewQS(selector))\n\tif err != nil && err != bongo.RecordNotFound {\n\t\tlog.Error(\"err while fetching koding channel:\", err.Error())\n\t\treturn\n\t}\n\n\tif err == bongo.RecordNotFound {\n\t\tlog.Debug(\"postgres group couldn't found, creating it\")\n\n\t\tacc, err := createChannelOwner(group)\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tc.Name = \"public\"\n\t\tc.CreatorId = acc.Id\n\t\tc.GroupName = models.Channel_KODING_NAME\n\t\tc.TypeConstant = models.Channel_TYPE_GROUP\n\t\tc.PrivacyConstant = models.Channel_PRIVACY_PUBLIC\n\t\tif err := c.Create(); err != nil {\n\t\t\tlog.Error(\"err while creating the koding channel: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\n\tsocialApiId := strconv.FormatInt(c.Id, 10)\n\tif group.SocialApiChannelId == socialApiId {\n\t\tlog.Error(\"mongo and postgres socialApiChannelId ids are same\")\n\t\treturn\n\t}\n\n\tlog.Debug(\"mongo and postgres socialApiChannelId ids are different, fixing it\")\n\tif err := updateGroupPartially(group.Id, \"socialApiChannelId\", socialApiId); err != nil {\n\t\tlog.Error(\"err while udpating socialApiChannelId: %s\", err.Error())\n\t\treturn\n\t}\n}\n\nfunc setSetChangeLogChannel(log logging.Logger, group *kodingmodels.Group) {\n\n\tc := models.NewChannel()\n\tselector := map[string]interface{}{\n\t\t\"type_constant\": models.Channel_TYPE_ANNOUNCEMENT,\n\t\t\"group_name\":    models.Channel_KODING_NAME,\n\t}\n\n\t\/\/ if err is nil\n\t\/\/ it means we already have that channel\n\terr := c.One(bongo.NewQS(selector))\n\tif err != nil && err != bongo.RecordNotFound {\n\t\tlog.Error(\"err while fetching changelog channel:\", err.Error())\n\t\treturn\n\t}\n\n\tif err == bongo.RecordNotFound {\n\t\tlog.Error(\"postgres changelog couldn't found, creating it\")\n\n\t\tacc, err := createChannelOwner(group)\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tc.Name = \"changelog\"\n\t\tc.CreatorId = acc.Id\n\t\tc.GroupName = models.Channel_KODING_NAME\n\t\tc.TypeConstant = models.Channel_TYPE_ANNOUNCEMENT\n\t\tc.PrivacyConstant = models.Channel_PRIVACY_PRIVATE\n\t\tif err := c.Create(); err != nil {\n\t\t\tlog.Error(\"err while creating the koding channel:\", err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\n\tsocialApiAnnouncementChannelId := strconv.FormatInt(c.Id, 10)\n\tif group.SocialApiAnnouncementChannelId == socialApiAnnouncementChannelId {\n\t\tlog.Info(\"mongo and postgres socialApiAnnouncementChannel ids are same\")\n\t\treturn\n\t}\n\n\tlog.Debug(\"mongo and postgres socialApiAnnouncementChannel ids are different, fixing it\")\n\tif err := updateGroupPartially(group.Id, \"socialApiAnnouncementChannelId\", strconv.FormatInt(c.Id, 10)); err != nil {\n\t\tlog.Error(\"err while udpating socialApiAnnouncementChannelId:\", err.Error())\n\t\treturn\n\t}\n}\n\nfunc createChannelOwner(group *kodingmodels.Group) (*models.Account, error) {\n\towner, err := modelhelper.GetGroupOwner(group)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"err while fetching koding owner: %s\", err.Error())\n\t}\n\n\tacc := models.NewAccount()\n\tacc.OldId = owner.Id.Hex()\n\tacc.Nick = owner.Profile.Nickname\n\tif err := acc.FetchOrCreate(); err != nil {\n\t\treturn nil, fmt.Errorf(\"err while fetching owner from postgres: %s\", err.Error())\n\t}\n\n\treturn acc, nil\n}\n\nfunc updateGroupPartially(groupId bson.ObjectId, property string, value string) error {\n\treturn modelhelper.UpdateGroupPartial(\n\t\tmodelhelper.Selector{\"_id\": groupId},\n\t\tmodelhelper.Selector{\n\t\t\t\"$set\": modelhelper.Selector{\n\t\t\t\tproperty: value,\n\t\t\t},\n\t\t},\n\t)\n}\n<commit_msg>Social: error to debug log<commit_after>package main\n\nimport (\n\t\"fmt\"\n\tkodingmodels \"koding\/db\/models\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"socialapi\/models\"\n\t\"strconv\"\n\n\t\"labix.org\/v2\/mgo\/bson\"\n\n\t\"github.com\/koding\/bongo\"\n\t\"github.com\/koding\/logging\"\n)\n\nfunc setDefaults(log logging.Logger) {\n\tgroup, err := modelhelper.GetGroup(models.Channel_KODING_NAME)\n\tif err != nil {\n\t\tlog.Error(\"err while fetching koding group: %s\", err.Error())\n\t\treturn\n\t}\n\n\tlog.Debug(\"mongo group found\")\n\n\tsetPublicChannel(log, group)\n\tsetSetChangeLogChannel(log, group)\n\tlog.Info(\"socialApi defaults are created\")\n}\n\nfunc setPublicChannel(log logging.Logger, group *kodingmodels.Group) {\n\tc := models.NewChannel()\n\tselector := map[string]interface{}{\n\t\t\"type_constant\": models.Channel_TYPE_GROUP,\n\t\t\"group_name\":    models.Channel_KODING_NAME,\n\t}\n\n\terr := c.One(bongo.NewQS(selector))\n\tif err != nil && err != bongo.RecordNotFound {\n\t\tlog.Error(\"err while fetching koding channel:\", err.Error())\n\t\treturn\n\t}\n\n\tif err == bongo.RecordNotFound {\n\t\tlog.Debug(\"postgres group couldn't found, creating it\")\n\n\t\tacc, err := createChannelOwner(group)\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tc.Name = \"public\"\n\t\tc.CreatorId = acc.Id\n\t\tc.GroupName = models.Channel_KODING_NAME\n\t\tc.TypeConstant = models.Channel_TYPE_GROUP\n\t\tc.PrivacyConstant = models.Channel_PRIVACY_PUBLIC\n\t\tif err := c.Create(); err != nil {\n\t\t\tlog.Error(\"err while creating the koding channel: %s\", err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\n\tsocialApiId := strconv.FormatInt(c.Id, 10)\n\tif group.SocialApiChannelId == socialApiId {\n\t\tlog.Debug(\"mongo and postgres socialApiChannelId ids are same\")\n\t\treturn\n\t}\n\n\tlog.Debug(\"mongo and postgres socialApiChannelId ids are different, fixing it\")\n\tif err := updateGroupPartially(group.Id, \"socialApiChannelId\", socialApiId); err != nil {\n\t\tlog.Error(\"err while udpating socialApiChannelId: %s\", err.Error())\n\t\treturn\n\t}\n}\n\nfunc setSetChangeLogChannel(log logging.Logger, group *kodingmodels.Group) {\n\n\tc := models.NewChannel()\n\tselector := map[string]interface{}{\n\t\t\"type_constant\": models.Channel_TYPE_ANNOUNCEMENT,\n\t\t\"group_name\":    models.Channel_KODING_NAME,\n\t}\n\n\t\/\/ if err is nil\n\t\/\/ it means we already have that channel\n\terr := c.One(bongo.NewQS(selector))\n\tif err != nil && err != bongo.RecordNotFound {\n\t\tlog.Error(\"err while fetching changelog channel:\", err.Error())\n\t\treturn\n\t}\n\n\tif err == bongo.RecordNotFound {\n\t\tlog.Error(\"postgres changelog couldn't found, creating it\")\n\n\t\tacc, err := createChannelOwner(group)\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tc.Name = \"changelog\"\n\t\tc.CreatorId = acc.Id\n\t\tc.GroupName = models.Channel_KODING_NAME\n\t\tc.TypeConstant = models.Channel_TYPE_ANNOUNCEMENT\n\t\tc.PrivacyConstant = models.Channel_PRIVACY_PRIVATE\n\t\tif err := c.Create(); err != nil {\n\t\t\tlog.Error(\"err while creating the koding channel:\", err.Error())\n\t\t\treturn\n\t\t}\n\t}\n\n\tsocialApiAnnouncementChannelId := strconv.FormatInt(c.Id, 10)\n\tif group.SocialApiAnnouncementChannelId == socialApiAnnouncementChannelId {\n\t\tlog.Info(\"mongo and postgres socialApiAnnouncementChannel ids are same\")\n\t\treturn\n\t}\n\n\tlog.Debug(\"mongo and postgres socialApiAnnouncementChannel ids are different, fixing it\")\n\tif err := updateGroupPartially(group.Id, \"socialApiAnnouncementChannelId\", strconv.FormatInt(c.Id, 10)); err != nil {\n\t\tlog.Error(\"err while udpating socialApiAnnouncementChannelId:\", err.Error())\n\t\treturn\n\t}\n}\n\nfunc createChannelOwner(group *kodingmodels.Group) (*models.Account, error) {\n\towner, err := modelhelper.GetGroupOwner(group)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"err while fetching koding owner: %s\", err.Error())\n\t}\n\n\tacc := models.NewAccount()\n\tacc.OldId = owner.Id.Hex()\n\tacc.Nick = owner.Profile.Nickname\n\tif err := acc.FetchOrCreate(); err != nil {\n\t\treturn nil, fmt.Errorf(\"err while fetching owner from postgres: %s\", err.Error())\n\t}\n\n\treturn acc, nil\n}\n\nfunc updateGroupPartially(groupId bson.ObjectId, property string, value string) error {\n\treturn modelhelper.UpdateGroupPartial(\n\t\tmodelhelper.Selector{\"_id\": groupId},\n\t\tmodelhelper.Selector{\n\t\t\t\"$set\": modelhelper.Selector{\n\t\t\t\tproperty: value,\n\t\t\t},\n\t\t},\n\t)\n}\n<|endoftext|>"}
{"text":"<commit_before>package opensds\r\n\r\nimport (\r\n\t\"fmt\"\r\n\t\"log\"\r\n\t\"os\"\r\n\t\"runtime\"\r\n\r\n\t\"google.golang.org\/grpc\/codes\"\r\n\r\n\t\"github.com\/container-storage-interface\/spec\/lib\/go\/csi\"\r\n\t\"github.com\/opensds\/nbp\/client\/iscsi\"\r\n\tsdscontroller \"github.com\/opensds\/nbp\/client\/opensds\"\r\n\t\"github.com\/opensds\/opensds\/pkg\/model\"\r\n\t\"golang.org\/x\/net\/context\"\r\n\t\"google.golang.org\/grpc\/status\"\r\n\t\"strings\"\r\n)\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/                            Node Service                                    \/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n\/\/ NodePublishVolume implementation\r\nfunc (p *Plugin) NodePublishVolume(\r\n\tctx context.Context,\r\n\treq *csi.NodePublishVolumeRequest) (\r\n\t*csi.NodePublishVolumeResponse, error) {\r\n\r\n\tlog.Println(\"start to NodePublishVolume\")\r\n\tdefer log.Println(\"end to NodePublishVolume\")\r\n\r\n\tif errCode := p.CheckVersionSupport(req.Version); errCode != codes.OK {\r\n\t\tmsg := \"the version specified in the request is not supported by the Plugin.\"\r\n\t\treturn nil, status.Error(errCode, msg)\r\n\t}\r\n\r\n\tclient := sdscontroller.GetClient(\"\")\r\n\r\n\t\/\/check volume is exist\r\n\tvolSpec, errVol := client.GetVolume(req.VolumeId)\r\n\tif errVol != nil || volSpec == nil {\r\n\t\tmsg := fmt.Sprintf(\"the volume %s is not exist\", req.VolumeId)\r\n\t\treturn nil, status.Error(codes.NotFound, msg)\r\n\t}\r\n\r\n\tatc, atcErr := client.GetVolumeAttachment(req.PublishVolumeInfo[\"atcid\"])\r\n\tif atcErr != nil || atc == nil {\r\n\t\treturn nil, status.Error(codes.FailedPrecondition, \"Failed to publish node.\")\r\n\t}\r\n\r\n\tvar targetPaths []string\r\n\tif tps, exist := atc.Metadata[\"target_path\"]; exist {\r\n\t\ttargetPaths = strings.Split(tps, \";\")\r\n\t\tfor _, tp := range targetPaths {\r\n\t\t\tif req.TargetPath == tp {\r\n\t\t\t\treturn &csi.NodePublishVolumeResponse{}, nil\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ if volume don't have MULTI_NODE capability, just termination.\r\n\t\tmode := req.VolumeCapability.AccessMode.Mode\r\n\t\tif mode != csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER &&\r\n\t\t\tmode != csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY &&\r\n\t\t\tmode != csi.VolumeCapability_AccessMode_MULTI_NODE_SINGLE_WRITER {\r\n\t\t\tmsg := fmt.Sprintf(\"the volume %s has been published to this node.\", req.VolumeId)\r\n\t\t\treturn nil, status.Error(codes.Aborted, msg)\r\n\t\t}\r\n\t}\r\n\r\n\tportal := req.PublishVolumeInfo[\"portal\"]\r\n\ttargetiqn := req.PublishVolumeInfo[\"targetiqn\"]\r\n\ttargetlun := req.PublishVolumeInfo[\"targetlun\"]\r\n\r\n\t\/\/ Connect Target\r\n\tlog.Printf(\"[NodePublishVolume] portal:%s targetiqn:%s targetlun:%s volumeid:%s\",\r\n\t\tportal, targetiqn, targetlun, req.VolumeId)\r\n\tdevice, err := iscsi.Connect(portal, targetiqn, targetlun)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\t\/\/ obtain attachments to decide if can format.\r\n\tatcs, err := client.ListVolumeAttachments()\r\n\tif err != nil {\r\n\t\treturn nil, status.Error(codes.FailedPrecondition, \"Failed to publish node.\")\r\n\t}\r\n\tformat := true\r\n\tfor _, attachSpec := range atcs {\r\n\t\tif attachSpec.VolumeId == req.VolumeId {\r\n\t\t\tif _, exist := attachSpec.Metadata[\"target_path\"]; exist {\r\n\t\t\t\t\/\/ The device is formatted, can't be reformat for shared storage.\r\n\t\t\t\tformat = false\r\n\t\t\t\tbreak\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/ Format and Mount\r\n\tlog.Printf(\"[NodePublishVolume] device:%s TargetPath:%s\", device, req.TargetPath)\r\n\tif format {\r\n\t\terr = iscsi.FormatandMount(device, \"\", req.TargetPath)\r\n\t} else {\r\n\t\terr = iscsi.Mount(device, req.TargetPath)\r\n\t}\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\ttargetPaths = append(targetPaths, req.TargetPath)\r\n\tatc.Metadata[\"target_path\"] = strings.Join(targetPaths, \";\")\r\n\t_, err = client.UpdateVolumeAttachment(atc.Id, atc)\r\n\tif err != nil {\r\n\t\treturn nil, status.Error(codes.FailedPrecondition, \"Failed to publish node.\")\r\n\t}\r\n\r\n\treturn &csi.NodePublishVolumeResponse{}, nil\r\n}\r\n\r\n\/\/ NodeUnpublishVolume implementation\r\nfunc (p *Plugin) NodeUnpublishVolume(\r\n\tctx context.Context,\r\n\treq *csi.NodeUnpublishVolumeRequest) (\r\n\t*csi.NodeUnpublishVolumeResponse, error) {\r\n\r\n\tlog.Println(\"start to NodeUnpublishVolume\")\r\n\tdefer log.Println(\"end to NodeUnpublishVolume\")\r\n\r\n\tif errCode := p.CheckVersionSupport(req.Version); errCode != codes.OK {\r\n\t\tmsg := \"the version specified in the request is not supported by the Plugin.\"\r\n\t\treturn nil, status.Error(errCode, msg)\r\n\t}\r\n\r\n\tclient := sdscontroller.GetClient(\"\")\r\n\r\n\t\/\/check volume is exist\r\n\tvolSpec, errVol := client.GetVolume(req.VolumeId)\r\n\tif errVol != nil || volSpec == nil {\r\n\t\tmsg := fmt.Sprintf(\"the volume %s is not exist\", req.VolumeId)\r\n\t\treturn nil, status.Error(codes.NotFound, msg)\r\n\t}\r\n\r\n\tattachments, err := client.ListVolumeAttachments()\r\n\tif err != nil {\r\n\t\treturn nil, status.Error(codes.FailedPrecondition, \"Failed to NodeUnpublish volume.\")\r\n\t}\r\n\r\n\tvar atc *model.VolumeAttachmentSpec\r\n\thostname, _ := os.Hostname()\r\n\tfor _, attachSpec := range attachments {\r\n\t\tif attachSpec.VolumeId == req.VolumeId && attachSpec.Host == hostname {\r\n\t\t\tatc = attachSpec\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\r\n\tif atc == nil {\r\n\t\treturn &csi.NodeUnpublishVolumeResponse{}, nil\r\n\t}\r\n\r\n\tif _, exist := atc.Metadata[\"target_path\"]; !exist {\r\n\t\treturn &csi.NodeUnpublishVolumeResponse{}, nil\r\n\t}\r\n\r\n\tvar modifyTargetPaths []string\r\n\ttpExist := false\r\n\ttargetPaths := strings.Split(atc.Metadata[\"target_path\"], \";\")\r\n\tfor index, path := range targetPaths {\r\n\t\tif path == req.TargetPath {\r\n\t\t\tmodifyTargetPaths = append(targetPaths[:index], targetPaths[index+1:]...)\r\n\t\t\ttpExist = true\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\tif !tpExist {\r\n\t\treturn &csi.NodeUnpublishVolumeResponse{}, nil\r\n\t}\r\n\r\n\t\/\/ Umount\r\n\tlog.Printf(\"[NodeUnpublishVolume] TargetPath:%s\", req.TargetPath)\r\n\terr = iscsi.Umount(req.TargetPath)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tif len(modifyTargetPaths) == 0 {\r\n\t\tiscsiCon := iscsi.ParseIscsiConnectInfo(atc.ConnectionData)\r\n\t\t\/\/ Disconnect\r\n\t\tif iscsiCon != nil {\r\n\t\t\terr = iscsi.Disconnect(iscsiCon.TgtPortal, iscsiCon.TgtIQN)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn nil, err\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tatc.Metadata[\"target_path\"] = strings.Join(modifyTargetPaths, \";\")\r\n\t_, err = client.UpdateVolumeAttachment(atc.Id, atc)\r\n\tif err != nil {\r\n\t\treturn nil, status.Error(codes.FailedPrecondition, \"Failed to NodeUnpublish volume.\")\r\n\t}\r\n\r\n\treturn &csi.NodeUnpublishVolumeResponse{}, nil\r\n}\r\n\r\n\/\/ GetNodeID implementation\r\nfunc (p *Plugin) GetNodeID(\r\n\tctx context.Context,\r\n\treq *csi.GetNodeIDRequest) (\r\n\t*csi.GetNodeIDResponse, error) {\r\n\r\n\tlog.Println(\"start to GetNodeID\")\r\n\tdefer log.Println(\"end to GetNodeID\")\r\n\r\n\t\/\/ Get host name from os\r\n\thostname, err := os.Hostname()\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn &csi.GetNodeIDResponse{\r\n\t\tNodeId: hostname,\r\n\t}, nil\r\n}\r\n\r\n\/\/ NodeProbe implementation\r\nfunc (p *Plugin) NodeProbe(\r\n\tctx context.Context,\r\n\treq *csi.NodeProbeRequest) (\r\n\t*csi.NodeProbeResponse, error) {\r\n\r\n\tlog.Println(\"start to NodeProbe\")\r\n\tdefer log.Println(\"end to NodeProbe\")\r\n\r\n\tswitch runtime.GOOS {\r\n\tcase \"linux\":\r\n\t\treturn &csi.NodeProbeResponse{}, nil\r\n\tdefault:\r\n\t\tmsg := \"unsupported operating system:\" + runtime.GOOS\r\n\t\tlog.Fatalf(msg)\r\n\t\t\/\/ csi.Error_NodeProbeError_MISSING_REQUIRED_HOST_DEPENDENCY\r\n\t\treturn nil, status.Error(codes.FailedPrecondition, msg)\r\n\t}\r\n}\r\n\r\n\/\/ NodeGetCapabilities implementation\r\nfunc (p *Plugin) NodeGetCapabilities(\r\n\tctx context.Context,\r\n\treq *csi.NodeGetCapabilitiesRequest) (\r\n\t*csi.NodeGetCapabilitiesResponse, error) {\r\n\r\n\tlog.Println(\"start to NodeGetCapabilities\")\r\n\tdefer log.Println(\"end to NodeGetCapabilities\")\r\n\r\n\treturn &csi.NodeGetCapabilitiesResponse{\r\n\t\tCapabilities: []*csi.NodeServiceCapability{\r\n\t\t\t&csi.NodeServiceCapability{\r\n\t\t\t\tType: &csi.NodeServiceCapability_Rpc{\r\n\t\t\t\t\tRpc: &csi.NodeServiceCapability_RPC{\r\n\t\t\t\t\t\tType: csi.NodeServiceCapability_RPC_UNKNOWN,\r\n\t\t\t\t\t},\r\n\t\t\t\t},\r\n\t\t\t},\r\n\t\t},\r\n\t}, nil\r\n}\r\n<commit_msg>add judgement of target_path field<commit_after>package opensds\r\n\r\nimport (\r\n\t\"fmt\"\r\n\t\"log\"\r\n\t\"os\"\r\n\t\"runtime\"\r\n\r\n\t\"google.golang.org\/grpc\/codes\"\r\n\r\n\t\"github.com\/container-storage-interface\/spec\/lib\/go\/csi\"\r\n\t\"github.com\/opensds\/nbp\/client\/iscsi\"\r\n\tsdscontroller \"github.com\/opensds\/nbp\/client\/opensds\"\r\n\t\"github.com\/opensds\/opensds\/pkg\/model\"\r\n\t\"golang.org\/x\/net\/context\"\r\n\t\"google.golang.org\/grpc\/status\"\r\n\t\"strings\"\r\n)\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/                            Node Service                                    \/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n\/\/ NodePublishVolume implementation\r\nfunc (p *Plugin) NodePublishVolume(\r\n\tctx context.Context,\r\n\treq *csi.NodePublishVolumeRequest) (\r\n\t*csi.NodePublishVolumeResponse, error) {\r\n\r\n\tlog.Println(\"start to NodePublishVolume\")\r\n\tdefer log.Println(\"end to NodePublishVolume\")\r\n\r\n\tif errCode := p.CheckVersionSupport(req.Version); errCode != codes.OK {\r\n\t\tmsg := \"the version specified in the request is not supported by the Plugin.\"\r\n\t\treturn nil, status.Error(errCode, msg)\r\n\t}\r\n\r\n\tclient := sdscontroller.GetClient(\"\")\r\n\r\n\t\/\/check volume is exist\r\n\tvolSpec, errVol := client.GetVolume(req.VolumeId)\r\n\tif errVol != nil || volSpec == nil {\r\n\t\tmsg := fmt.Sprintf(\"the volume %s is not exist\", req.VolumeId)\r\n\t\treturn nil, status.Error(codes.NotFound, msg)\r\n\t}\r\n\r\n\tatc, atcErr := client.GetVolumeAttachment(req.PublishVolumeInfo[\"atcid\"])\r\n\tif atcErr != nil || atc == nil {\r\n\t\treturn nil, status.Error(codes.FailedPrecondition, \"Failed to publish node.\")\r\n\t}\r\n\r\n\tvar targetPaths []string\r\n\tif tps, exist := atc.Metadata[\"target_path\"]; exist && len(tps) != 0 {\r\n\t\ttargetPaths = strings.Split(tps, \";\")\r\n\t\tfor _, tp := range targetPaths {\r\n\t\t\tif req.TargetPath == tp {\r\n\t\t\t\treturn &csi.NodePublishVolumeResponse{}, nil\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ if volume don't have MULTI_NODE capability, just termination.\r\n\t\tmode := req.VolumeCapability.AccessMode.Mode\r\n\t\tif mode != csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER &&\r\n\t\t\tmode != csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY &&\r\n\t\t\tmode != csi.VolumeCapability_AccessMode_MULTI_NODE_SINGLE_WRITER {\r\n\t\t\tmsg := fmt.Sprintf(\"the volume %s has been published to this node.\", req.VolumeId)\r\n\t\t\treturn nil, status.Error(codes.Aborted, msg)\r\n\t\t}\r\n\t}\r\n\r\n\tportal := req.PublishVolumeInfo[\"portal\"]\r\n\ttargetiqn := req.PublishVolumeInfo[\"targetiqn\"]\r\n\ttargetlun := req.PublishVolumeInfo[\"targetlun\"]\r\n\r\n\t\/\/ Connect Target\r\n\tlog.Printf(\"[NodePublishVolume] portal:%s targetiqn:%s targetlun:%s volumeid:%s\",\r\n\t\tportal, targetiqn, targetlun, req.VolumeId)\r\n\tdevice, err := iscsi.Connect(portal, targetiqn, targetlun)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\t\/\/ obtain attachments to decide if can format.\r\n\tatcs, err := client.ListVolumeAttachments()\r\n\tif err != nil {\r\n\t\treturn nil, status.Error(codes.FailedPrecondition, \"Failed to publish node.\")\r\n\t}\r\n\tformat := true\r\n\tfor _, attachSpec := range atcs {\r\n\t\tif attachSpec.VolumeId == req.VolumeId {\r\n\t\t\tif _, exist := attachSpec.Metadata[\"target_path\"]; exist {\r\n\t\t\t\t\/\/ The device is formatted, can't be reformat for shared storage.\r\n\t\t\t\tformat = false\r\n\t\t\t\tbreak\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t\/\/ Format and Mount\r\n\tlog.Printf(\"[NodePublishVolume] device:%s TargetPath:%s\", device, req.TargetPath)\r\n\tif format {\r\n\t\terr = iscsi.FormatandMount(device, \"\", req.TargetPath)\r\n\t} else {\r\n\t\terr = iscsi.Mount(device, req.TargetPath)\r\n\t}\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\ttargetPaths = append(targetPaths, req.TargetPath)\r\n\tatc.Metadata[\"target_path\"] = strings.Join(targetPaths, \";\")\r\n\t_, err = client.UpdateVolumeAttachment(atc.Id, atc)\r\n\tif err != nil {\r\n\t\treturn nil, status.Error(codes.FailedPrecondition, \"Failed to publish node.\")\r\n\t}\r\n\r\n\treturn &csi.NodePublishVolumeResponse{}, nil\r\n}\r\n\r\n\/\/ NodeUnpublishVolume implementation\r\nfunc (p *Plugin) NodeUnpublishVolume(\r\n\tctx context.Context,\r\n\treq *csi.NodeUnpublishVolumeRequest) (\r\n\t*csi.NodeUnpublishVolumeResponse, error) {\r\n\r\n\tlog.Println(\"start to NodeUnpublishVolume\")\r\n\tdefer log.Println(\"end to NodeUnpublishVolume\")\r\n\r\n\tif errCode := p.CheckVersionSupport(req.Version); errCode != codes.OK {\r\n\t\tmsg := \"the version specified in the request is not supported by the Plugin.\"\r\n\t\treturn nil, status.Error(errCode, msg)\r\n\t}\r\n\r\n\tclient := sdscontroller.GetClient(\"\")\r\n\r\n\t\/\/check volume is exist\r\n\tvolSpec, errVol := client.GetVolume(req.VolumeId)\r\n\tif errVol != nil || volSpec == nil {\r\n\t\tmsg := fmt.Sprintf(\"the volume %s is not exist\", req.VolumeId)\r\n\t\treturn nil, status.Error(codes.NotFound, msg)\r\n\t}\r\n\r\n\tattachments, err := client.ListVolumeAttachments()\r\n\tif err != nil {\r\n\t\treturn nil, status.Error(codes.FailedPrecondition, \"Failed to NodeUnpublish volume.\")\r\n\t}\r\n\r\n\tvar atc *model.VolumeAttachmentSpec\r\n\thostname, _ := os.Hostname()\r\n\tfor _, attachSpec := range attachments {\r\n\t\tif attachSpec.VolumeId == req.VolumeId && attachSpec.Host == hostname {\r\n\t\t\tatc = attachSpec\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\r\n\tif atc == nil {\r\n\t\treturn &csi.NodeUnpublishVolumeResponse{}, nil\r\n\t}\r\n\r\n\tif _, exist := atc.Metadata[\"target_path\"]; !exist {\r\n\t\treturn &csi.NodeUnpublishVolumeResponse{}, nil\r\n\t}\r\n\r\n\tvar modifyTargetPaths []string\r\n\ttpExist := false\r\n\ttargetPaths := strings.Split(atc.Metadata[\"target_path\"], \";\")\r\n\tfor index, path := range targetPaths {\r\n\t\tif path == req.TargetPath {\r\n\t\t\tmodifyTargetPaths = append(targetPaths[:index], targetPaths[index+1:]...)\r\n\t\t\ttpExist = true\r\n\t\t\tbreak\r\n\t\t}\r\n\t}\r\n\tif !tpExist {\r\n\t\treturn &csi.NodeUnpublishVolumeResponse{}, nil\r\n\t}\r\n\r\n\t\/\/ Umount\r\n\tlog.Printf(\"[NodeUnpublishVolume] TargetPath:%s\", req.TargetPath)\r\n\terr = iscsi.Umount(req.TargetPath)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tif len(modifyTargetPaths) == 0 {\r\n\t\tiscsiCon := iscsi.ParseIscsiConnectInfo(atc.ConnectionData)\r\n\t\t\/\/ Disconnect\r\n\t\tif iscsiCon != nil {\r\n\t\t\terr = iscsi.Disconnect(iscsiCon.TgtPortal, iscsiCon.TgtIQN)\r\n\t\t\tif err != nil {\r\n\t\t\t\treturn nil, err\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tatc.Metadata[\"target_path\"] = strings.Join(modifyTargetPaths, \";\")\r\n\t_, err = client.UpdateVolumeAttachment(atc.Id, atc)\r\n\tif err != nil {\r\n\t\treturn nil, status.Error(codes.FailedPrecondition, \"Failed to NodeUnpublish volume.\")\r\n\t}\r\n\r\n\treturn &csi.NodeUnpublishVolumeResponse{}, nil\r\n}\r\n\r\n\/\/ GetNodeID implementation\r\nfunc (p *Plugin) GetNodeID(\r\n\tctx context.Context,\r\n\treq *csi.GetNodeIDRequest) (\r\n\t*csi.GetNodeIDResponse, error) {\r\n\r\n\tlog.Println(\"start to GetNodeID\")\r\n\tdefer log.Println(\"end to GetNodeID\")\r\n\r\n\t\/\/ Get host name from os\r\n\thostname, err := os.Hostname()\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\treturn &csi.GetNodeIDResponse{\r\n\t\tNodeId: hostname,\r\n\t}, nil\r\n}\r\n\r\n\/\/ NodeProbe implementation\r\nfunc (p *Plugin) NodeProbe(\r\n\tctx context.Context,\r\n\treq *csi.NodeProbeRequest) (\r\n\t*csi.NodeProbeResponse, error) {\r\n\r\n\tlog.Println(\"start to NodeProbe\")\r\n\tdefer log.Println(\"end to NodeProbe\")\r\n\r\n\tswitch runtime.GOOS {\r\n\tcase \"linux\":\r\n\t\treturn &csi.NodeProbeResponse{}, nil\r\n\tdefault:\r\n\t\tmsg := \"unsupported operating system:\" + runtime.GOOS\r\n\t\tlog.Fatalf(msg)\r\n\t\t\/\/ csi.Error_NodeProbeError_MISSING_REQUIRED_HOST_DEPENDENCY\r\n\t\treturn nil, status.Error(codes.FailedPrecondition, msg)\r\n\t}\r\n}\r\n\r\n\/\/ NodeGetCapabilities implementation\r\nfunc (p *Plugin) NodeGetCapabilities(\r\n\tctx context.Context,\r\n\treq *csi.NodeGetCapabilitiesRequest) (\r\n\t*csi.NodeGetCapabilitiesResponse, error) {\r\n\r\n\tlog.Println(\"start to NodeGetCapabilities\")\r\n\tdefer log.Println(\"end to NodeGetCapabilities\")\r\n\r\n\treturn &csi.NodeGetCapabilitiesResponse{\r\n\t\tCapabilities: []*csi.NodeServiceCapability{\r\n\t\t\t&csi.NodeServiceCapability{\r\n\t\t\t\tType: &csi.NodeServiceCapability_Rpc{\r\n\t\t\t\t\tRpc: &csi.NodeServiceCapability_RPC{\r\n\t\t\t\t\t\tType: csi.NodeServiceCapability_RPC_UNKNOWN,\r\n\t\t\t\t\t},\r\n\t\t\t\t},\r\n\t\t\t},\r\n\t\t},\r\n\t}, nil\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>package dukedb\n\nimport (\n\t\"strconv\"\n)\n\ntype BaseModelIntID struct {\n\tID uint64\n}\n\nfunc (b BaseModelIntID) GetID() string {\n\treturn strconv.FormatUint(b.ID, 64)\n}\n\nfunc (b BaseModelIntID) SetID(rawId string) error {\n\tid, err := strconv.ParseUint(rawId, 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.ID = id\n\treturn nil\n}\n<commit_msg>fixed basemodelintid<commit_after>package dukedb\n\nimport (\n\t\"strconv\"\n)\n\ntype BaseModelIntID struct {\n\tID uint64\n}\n\nfunc (b BaseModelIntID) GetID() string {\n\treturn strconv.FormatUint(b.ID, 10)\n}\n\nfunc (b *BaseModelIntID) SetID(rawId string) error {\n\tid, err := strconv.ParseUint(rawId, 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.ID = id\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package goutube\n\ntype MediaType int\n\nconst (\n\tVIDEO MediaType = iota\n\tAUDIO\n)\n\nfunc (t MediaType) String() string {\n\tvar s string\n\tswitch t {\n\tcase VIDEO:\n\t\ts = \"VIDEO\"\n\tcase AUDIO:\n\t\ts = \"AUDIO\"\n\t}\n\treturn s\n}\n\ntype MediaFormat struct {\n\tType         string\n\tVideoCodec   string\n\tAudioCodec   string\n\tRaw          string\n}\n\ntype Link struct {\n\tURL          string\n\tType         MediaType\n\tSignature    string\n\tQuality      string\n\tFormat       MediaFormat\n}\n\ntype Result struct {\n\tDone         chan bool\n\tError        chan error\n\tLinks        []Link\n}\n<commit_msg>Made printing to the Link struct more human-readable<commit_after>package goutube\n\nimport \"fmt\"\n\ntype MediaType int\n\nconst (\n\tVIDEO MediaType = iota\n\tAUDIO\n)\n\nfunc (t MediaType) String() string {\n\tvar s string\n\tswitch t {\n\tcase VIDEO:\n\t\ts = \"VIDEO\"\n\tcase AUDIO:\n\t\ts = \"AUDIO\"\n\t}\n\treturn s\n}\n\ntype MediaFormat struct {\n\tType         string\n\tVideoCodec   string\n\tAudioCodec   string\n\tRaw          string\n}\n\ntype Link struct {\n\tURL          string\n\tType         MediaType\n\tSignature    string\n\tQuality      string\n\tFormat       MediaFormat\n}\n\nfunc (t Link) String() string {\n\tquality := t.Quality\n\tif len(quality) == 0 {\n\t\tquality = \"NA\"\n\t}\n\ts := fmt.Sprintf(\"URL: %s,\\n Type: %s,\\n Quality: %s,\\n Format(Raw): %s\\n\",\n\t\tt.URL, t.Type, quality, t.Format.Raw)\n\treturn s\n}\n\ntype Result struct {\n\tDone         chan bool\n\tError        chan error\n\tLinks        []Link\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/csv\"\n\t\"encoding\/xml\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/jmoiron\/sqlx\"\n\t_ \"github.com\/lib\/pq\"\n\t\"log\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype FiveMinuteObservation struct {\n\tYear_rtm              int\n\tDay_rtm               int\n\tHourminute_rtm        int\n\tAir_temp107_avg       sql.NullFloat64\n\tRelative_humidity_avg sql.NullFloat64\n\tLeaf_wetness_mv_avg   sql.NullFloat64\n\tSolar_radiation_avg   sql.NullFloat64\n\tWind_direction_d1_wvt sql.NullFloat64\n\tWind_speed_wvt        sql.NullFloat64\n\tRain_mm               sql.NullFloat64\n\tDatetime              time.Time\n}\n\ntype Rain struct {\n\tRain_mm  float64   `xml:\"rain-mm\"`\n\tDatetime time.Time `xml:\"datetime\"`\n}\n\nfunc (d *FiveMinuteObservation) toMawn() []string {\n\tvalues := []string{\n\t\t\"5\",\n\t\tstrconv.Itoa(d.Year_rtm),\n\t\tstrconv.Itoa(d.Day_rtm),\n\t\tstrconv.Itoa(d.Hourminute_rtm),\n\t\tfloatToString(d.Rain_mm),\n\t\tfloatToString(d.Leaf_wetness_mv_avg),\n\t\t\"\",\n\t\tfloatToString(d.Wind_speed_wvt),\n\t\tfloatToString(d.Air_temp107_avg),\n\t\tfloatToString(d.Relative_humidity_avg),\n\t\td.Datetime.Format(time.RFC3339),\n\t}\n\treturn values\n}\n\nfunc (d *FiveMinuteObservation) mawnHeader() []string {\n\tvalues := []string{\n\t\t\"#code\",\n\t\t\"year\",\n\t\t\"day\",\n\t\t\"time\",\n\t\t\"rain_mm\",\n\t\t\"leaf wetness A\",\n\t\t\"leaf wetnetss B\",\n\t\t\"wind speed\",\n\t\t\"air temperature\",\n\t\t\"relative humidity\",\n\t\t\"timestamp\",\n\t}\n\treturn values\n}\n\nfunc (d *FiveMinuteObservation) mawnUnit() []string {\n\tvalues := []string{\n\t\t\"#\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"mm\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"m\/s\",\n\t\t\"C\",\n\t\t\"%\",\n\t}\n\treturn values\n}\n\nfunc five_minute_observations(db *sqlx.DB, c *gin.Context) {\n\n\trows, err := db.Queryx(\"select * from (select air_temp107_avg, relative_humidity_avg, leaf_wetness_mv_avg, solar_radiation_avg, wind_direction_d1_wvt, wind_speed_wvt, rain_tipping_mm as rain_mm, lter_five_minute_a.datetime from weather.lter_five_minute_a order by datetime desc limit $1 ) t1 order by datetime\", limit(c, 1154))\n\n\tif err != nil {\n\t\tlog.Print(\"error in query\")\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\n\ti := 0\n\twriter := csv.NewWriter(c.Writer)\n\n\tobs := FiveMinuteObservation{}\n\twriter.Write(obs.mawnHeader())\n\twriter.Write(obs.mawnUnit())\n\tfor rows.Next() {\n\t\tif err := rows.StructScan(&obs); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tobs.Year_rtm, obs.Day_rtm, obs.Hourminute_rtm = CampbellTime(obs.Datetime.Local())\n\n\t\tobs.Relative_humidity_avg.Float64 = obs.Relative_humidity_avg.Float64 * 100\n\n\t\twriter.Write(obs.toMawn())\n\n\t\tif i%500 == 0 {\n\t\t\twriter.Flush()\n\t\t}\n\t\ti = i + 1\n\n\t}\n\twriter.Flush()\n}\n\nfunc five_minute_observations_js(db *sqlx.DB, c *gin.Context) {\n\tdatetime := c.Request.URL.Query().Get(\"datetime\")\n\n\tlog.Println(datetime)\n\tdata := []FiveMinuteObservation{}\n\n\tdb.Select(&data, \"select rain_mm, air_temp107_avg, datetime from weather.lter_five_minute_a where datetime > $1 order by datetime desc limit 1\", datetime)\n\tc.JSON(200, data)\n}\n\nfunc five_minute_observations_xml(db *sqlx.DB, c *gin.Context) {\n\tdata := []FiveMinuteObservation{}\n\n\tdb.Select(&data, \"select rain_mm, datetime from weather.lter_five_minute_a order by datetime desc limit $1\", limit(c, 3))\n\toutput := make([]Rain, len(data))\n\tfor key, value := range data {\n\t\toutput[key].Rain_mm = value.Rain_mm.Float64\n\t\toutput[key].Datetime = value.Datetime\n\t}\n\txmlOut, err := xml.MarshalIndent(output, \" \", \" \")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tc.Writer.Write(xmlOut)\n}\n<commit_msg>pick the oldest observation that is newer than the cutoff<commit_after>package main\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/csv\"\n\t\"encoding\/xml\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/jmoiron\/sqlx\"\n\t_ \"github.com\/lib\/pq\"\n\t\"log\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype FiveMinuteObservation struct {\n\tYear_rtm              int\n\tDay_rtm               int\n\tHourminute_rtm        int\n\tAir_temp107_avg       sql.NullFloat64\n\tRelative_humidity_avg sql.NullFloat64\n\tLeaf_wetness_mv_avg   sql.NullFloat64\n\tSolar_radiation_avg   sql.NullFloat64\n\tWind_direction_d1_wvt sql.NullFloat64\n\tWind_speed_wvt        sql.NullFloat64\n\tRain_mm               sql.NullFloat64\n\tDatetime              time.Time\n}\n\ntype Rain struct {\n\tRain_mm  float64   `xml:\"rain-mm\"`\n\tDatetime time.Time `xml:\"datetime\"`\n}\n\nfunc (d *FiveMinuteObservation) toMawn() []string {\n\tvalues := []string{\n\t\t\"5\",\n\t\tstrconv.Itoa(d.Year_rtm),\n\t\tstrconv.Itoa(d.Day_rtm),\n\t\tstrconv.Itoa(d.Hourminute_rtm),\n\t\tfloatToString(d.Rain_mm),\n\t\tfloatToString(d.Leaf_wetness_mv_avg),\n\t\t\"\",\n\t\tfloatToString(d.Wind_speed_wvt),\n\t\tfloatToString(d.Air_temp107_avg),\n\t\tfloatToString(d.Relative_humidity_avg),\n\t\td.Datetime.Format(time.RFC3339),\n\t}\n\treturn values\n}\n\nfunc (d *FiveMinuteObservation) mawnHeader() []string {\n\tvalues := []string{\n\t\t\"#code\",\n\t\t\"year\",\n\t\t\"day\",\n\t\t\"time\",\n\t\t\"rain_mm\",\n\t\t\"leaf wetness A\",\n\t\t\"leaf wetnetss B\",\n\t\t\"wind speed\",\n\t\t\"air temperature\",\n\t\t\"relative humidity\",\n\t\t\"timestamp\",\n\t}\n\treturn values\n}\n\nfunc (d *FiveMinuteObservation) mawnUnit() []string {\n\tvalues := []string{\n\t\t\"#\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"mm\",\n\t\t\"\",\n\t\t\"\",\n\t\t\"m\/s\",\n\t\t\"C\",\n\t\t\"%\",\n\t}\n\treturn values\n}\n\nfunc five_minute_observations(db *sqlx.DB, c *gin.Context) {\n\n\trows, err := db.Queryx(\"select * from (select air_temp107_avg, relative_humidity_avg, leaf_wetness_mv_avg, solar_radiation_avg, wind_direction_d1_wvt, wind_speed_wvt, rain_tipping_mm as rain_mm, lter_five_minute_a.datetime from weather.lter_five_minute_a order by datetime desc limit $1 ) t1 order by datetime\", limit(c, 1154))\n\n\tif err != nil {\n\t\tlog.Print(\"error in query\")\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\n\ti := 0\n\twriter := csv.NewWriter(c.Writer)\n\n\tobs := FiveMinuteObservation{}\n\twriter.Write(obs.mawnHeader())\n\twriter.Write(obs.mawnUnit())\n\tfor rows.Next() {\n\t\tif err := rows.StructScan(&obs); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tobs.Year_rtm, obs.Day_rtm, obs.Hourminute_rtm = CampbellTime(obs.Datetime.Local())\n\n\t\tobs.Relative_humidity_avg.Float64 = obs.Relative_humidity_avg.Float64 * 100\n\n\t\twriter.Write(obs.toMawn())\n\n\t\tif i%500 == 0 {\n\t\t\twriter.Flush()\n\t\t}\n\t\ti = i + 1\n\n\t}\n\twriter.Flush()\n}\n\nfunc five_minute_observations_js(db *sqlx.DB, c *gin.Context) {\n\tdatetime := c.Request.URL.Query().Get(\"datetime\")\n\n\tlog.Println(datetime)\n\tdata := []FiveMinuteObservation{}\n\n\tdb.Select(&data, \"select rain_mm, air_temp107_avg, datetime from weather.lter_five_minute_a where datetime > $1 order by datetime limit 1\", datetime)\n\tc.JSON(200, data)\n}\n\nfunc five_minute_observations_xml(db *sqlx.DB, c *gin.Context) {\n\tdata := []FiveMinuteObservation{}\n\n\tdb.Select(&data, \"select rain_mm, datetime from weather.lter_five_minute_a order by datetime desc limit $1\", limit(c, 3))\n\toutput := make([]Rain, len(data))\n\tfor key, value := range data {\n\t\toutput[key].Rain_mm = value.Rain_mm.Float64\n\t\toutput[key].Datetime = value.Datetime\n\t}\n\txmlOut, err := xml.MarshalIndent(output, \" \", \" \")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tc.Writer.Write(xmlOut)\n}\n<|endoftext|>"}
{"text":"<commit_before>package sources\n\nimport (\n\t\"net\/http\"\n\t\"fmt\"\n\t\"encoding\/json\"\n\t\"github.com\/golang\/glog\"\n\t\"bytes\")\n\ntype DmrContainer struct {\n\tName    string      `json:\"name,omitempty\"`\n\tHost    string      `json:\"host\"`\n\tDmrPort int         `json:\"dmrPort\"`\n\tStats   *StatsEntry `json:\"stats,omitempty\"`\n}\n\ntype DmrAttributeRequest struct {\n\tOperation \tstring\t`json:\"operation\"`\n\tName      \tstring\t`json:\"name\"`\n\tPretty\t\tint\t\t`json:\"json.pretty\"`\n}\n\ntype DmrResourceRequest struct {\n\tOperation \t\t\tstring\t\t`json:\"operation\"`\n\tIncludeRuntime      bool\t\t`json:\"include-runtime\"`\n\tAddress\t\t\t\t[]string\t`json:\"address\"`\n\tPretty\t\t\t\tint\t\t\t`json:\"json.pretty\"`\n}\n\ntype DmrResponse struct {\n\tOutcome \t\t\t\tstring\t\t`json:\"outcome\"`\n\tResult      \t\t\tinterface{}\t`json:\"result\"`\n\tFailureDescription      string\t\t`json:\"failure-description\"`\n\tRolledBacked      \t\tbool\t\t`json:\"rolled-back\"`\n}\n\ntype WebResult struct {\n\tBytesReceived\t\tStringInt\t\t\t`json:\"bytesReceived\"`\n\tBytesSent\t\t\tStringInt\t\t\t`json:\"bytesSent\"`\n\tEnableLookups\t\tbool\t\t\t\t`json:\"enable-lookups\"`\n\tEnabled\t\t\t\tbool\t\t\t\t`json:\"enabled\"`\n\tErrorCount\t\t\tStringInt\t\t\t`json:\"errorCount\"`\n\tExecutor\t\t\tstring\t\t\t\t`json:\"executor\"`\n\tMaxConnections\t\tint\t\t\t\t\t`json:\"max-connections\"`\n\tMaxPostSize\t\t\tint64\t\t\t\t`json:\"max-post-size\"`\n\tMaxSavePostSize\t\tint64\t\t\t\t`json:\"max-save-post-size\"`\n\tMaxTime\t\t\t\tStringInt\t\t\t`json:\"maxTime\"`\n\tName\t\t\t\tstring\t\t\t\t`json:\"name\"`\n\tProcessingTime\t\tStringInt\t\t\t`json:\"processingTime\"`\n\tProtocol\t\t\tstring\t\t\t\t`json:\"protocol\"`\n\tProxyName\t\t\tstring\t\t\t\t`json:\"proxy-name\"`\n\tProxyPort\t\t\tstring\t\t\t\t`json:\"proxy-port\"`\n\tRedirectPort\t\tint\t\t\t\t\t`json:\"redirect-port\"`\n\tRequestCount\t\tStringInt\t\t\t`json:\"requestCount\"`\n\tScheme\t\t\t\tstring\t\t\t\t`json:\"scheme\"`\n\tSecure\t\t\t\tbool\t\t\t\t`json:\"secure\"`\n\tSocketBinding\t\tstring\t\t\t\t`json:\"socket-binding\"`\n\tSSL\t\t\t\t\tstring\t\t\t\t`json:\"ssl\"`\n\tVirtualServer\t\tstring\t\t\t\t`json:\"virtual-server\"`\n}\n\nfunc (self *DmrContainer) GetName() string {\n\treturn self.Name\n}\n\nfunc (self *DmrContainer) GetStats() (*StatsEntry, error) {\n\tdmrRequest := DmrResourceRequest{\n\t\tOperation: \"read-resource\",\n\t\tIncludeRuntime: true,\n\t\tAddress: []string{\"subsystem\", \"web\", \"connector\", \"http\"},\n\t\tPretty: 1,\n\t}\n\n\twr := WebResult{}\n\tdmrResponse := DmrResponse{\n\t\tResult: &wr,\n\t}\n\n\terr := self.getStats(&dmrRequest, &dmrResponse)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tglog.Infof(\"outcome: %s, result: %s, failure: %s\", dmrResponse.Outcome, dmrResponse.Result, dmrResponse.FailureDescription)\n\n\treturn &StatsEntry{}, nil\n}\n\nfunc (self *DmrContainer) getStats(request interface{}, result interface{}) error {\n\treqBody, err := json.Marshal(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\turl := fmt.Sprintf(\"http:\/\/%s:%d\/management\", self.Host, self.DmrPort)\n\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(reqBody))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\n\terr = PostRequestAndGetValue(&http.Client{}, req, result)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>copying DMR response into struct<commit_after>package sources\n\nimport (\n\t\"net\/http\"\n\t\"fmt\"\n\t\"encoding\/json\"\n\t\"github.com\/golang\/glog\"\n\t\"bytes\")\n\ntype DmrContainer struct {\n\tName    string      `json:\"name,omitempty\"`\n\tHost    string      `json:\"host\"`\n\tDmrPort int         `json:\"dmrPort\"`\n\tStats   *StatsEntry `json:\"stats,omitempty\"`\n}\n\ntype DmrAttributeRequest struct {\n\tOperation \tstring\t`json:\"operation\"`\n\tName      \tstring\t`json:\"name\"`\n\tPretty\t\tint\t\t`json:\"json.pretty\"`\n}\n\ntype DmrResourceRequest struct {\n\tOperation \t\t\tstring\t\t`json:\"operation\"`\n\tIncludeRuntime      bool\t\t`json:\"include-runtime\"`\n\tAddress\t\t\t\t[]string\t`json:\"address\"`\n\tPretty\t\t\t\tint\t\t\t`json:\"json.pretty\"`\n}\n\ntype DmrResponse struct {\n\tOutcome \t\t\t\tstring\t\t`json:\"outcome\"`\n\tResult      \t\t\tinterface{}\t`json:\"result\"`\n\tFailureDescription      string\t\t`json:\"failure-description\"`\n\tRolledBacked      \t\tbool\t\t`json:\"rolled-back\"`\n}\n\ntype WebResult struct {\n\tBytesReceived\t\tStringInt\t\t\t`json:\"bytesReceived\"`\n\tBytesSent\t\t\tStringInt\t\t\t`json:\"bytesSent\"`\n\tEnableLookups\t\tbool\t\t\t\t`json:\"enable-lookups\"`\n\tEnabled\t\t\t\tbool\t\t\t\t`json:\"enabled\"`\n\tErrorCount\t\t\tStringInt\t\t\t`json:\"errorCount\"`\n\tExecutor\t\t\tstring\t\t\t\t`json:\"executor\"`\n\tMaxConnections\t\tint\t\t\t\t\t`json:\"max-connections\"`\n\tMaxPostSize\t\t\tint64\t\t\t\t`json:\"max-post-size\"`\n\tMaxSavePostSize\t\tint64\t\t\t\t`json:\"max-save-post-size\"`\n\tMaxTime\t\t\t\tStringInt\t\t\t`json:\"maxTime\"`\n\tName\t\t\t\tstring\t\t\t\t`json:\"name\"`\n\tProcessingTime\t\tStringInt\t\t\t`json:\"processingTime\"`\n\tProtocol\t\t\tstring\t\t\t\t`json:\"protocol\"`\n\tProxyName\t\t\tstring\t\t\t\t`json:\"proxy-name\"`\n\tProxyPort\t\t\tstring\t\t\t\t`json:\"proxy-port\"`\n\tRedirectPort\t\tint\t\t\t\t\t`json:\"redirect-port\"`\n\tRequestCount\t\tStringInt\t\t\t`json:\"requestCount\"`\n\tScheme\t\t\t\tstring\t\t\t\t`json:\"scheme\"`\n\tSecure\t\t\t\tbool\t\t\t\t`json:\"secure\"`\n\tSocketBinding\t\tstring\t\t\t\t`json:\"socket-binding\"`\n\tSSL\t\t\t\t\tstring\t\t\t\t`json:\"ssl\"`\n\tVirtualServer\t\tstring\t\t\t\t`json:\"virtual-server\"`\n}\n\nfunc (self *DmrContainer) GetName() string {\n\treturn self.Name\n}\n\nfunc (self *DmrContainer) GetStats() (*StatsEntry, error) {\n\tdmrRequest := DmrResourceRequest{\n\t\tOperation: \"read-resource\",\n\t\tIncludeRuntime: true,\n\t\tAddress: []string{\"subsystem\", \"web\", \"connector\", \"http\"},\n\t\tPretty: 1,\n\t}\n\n\twr := WebResult{}\n\tdmrResponse := DmrResponse{\n\t\tResult: &wr,\n\t}\n\n\terr := self.getStats(&dmrRequest, &dmrResponse)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tglog.Infof(\"outcome: %s, result: %s, failure: %s\", dmrResponse.Outcome, dmrResponse.Result, dmrResponse.FailureDescription)\n\n\tdmrStats := make(map[string]interface{})\n\tdmrStats[\"bytes_received\"] = wr.BytesReceived\n\tdmrStats[\"bytes_sent\"] = wr.BytesSent\n\tdmrStats[\"enable_lookups\"] = wr.EnableLookups\n\tdmrStats[\"enabled\"] = wr.Enabled\n\tdmrStats[\"error_count\"] = wr.ErrorCount\n\tdmrStats[\"executor\"] = wr.Executor\n\tdmrStats[\"max_connections\"] = wr.MaxConnections\n\tdmrStats[\"max_post_size\"] = wr.MaxPostSize\n\tdmrStats[\"max_save_post_size\"] = wr.MaxSavePostSize\n\tdmrStats[\"max_time\"] = wr.MaxTime\n\tdmrStats[\"name\"] = wr.Name\n\tdmrStats[\"processing_time\"] = wr.ProcessingTime\n\tdmrStats[\"protocol\"] = wr.Protocol\n\tdmrStats[\"proxy_name\"] = wr.ProxyName\n\tdmrStats[\"proxy_port\"] = wr.ProxyPort\n\tdmrStats[\"redirect_port\"] = wr.RedirectPort\n\tdmrStats[\"request_count\"] = wr.RequestCount\n\tdmrStats[\"scheme\"] = wr.Scheme\n\tdmrStats[\"secure\"] = wr.Secure\n\tdmrStats[\"socket_binding\"] = wr.SocketBinding\n\tdmrStats[\"ssl\"] = wr.SSL\n\tdmrStats[\"virtual_server\"] = wr.VirtualServer\n\t\n\tresponseStats := make(map[string]StatsValue)\n\tresponseStats[\"dmr\"] = dmrStats\n\t\n\tresult := &StatsEntry {\n\t\tTimestamp: time.Now().Local(),\n\t\tStats:     responseStats,\n\t}\n\t\n\tglog.V(2).Infof(\"Retrieved DMR stats: %v\", dmrStats)\n\n\treturn result, nil\n}\n\nfunc (self *DmrContainer) getStats(request interface{}, result interface{}) error {\n\treqBody, err := json.Marshal(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\turl := fmt.Sprintf(\"http:\/\/%s:%d\/management\", self.Host, self.DmrPort)\n\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(reqBody))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\n\terr = PostRequestAndGetValue(&http.Client{}, req, result)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2016 Abcum Ltd\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage orbit\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\n\t\"github.com\/robertkrimen\/otto\"\n)\n\nvar (\n\tbeg = \"(function(module) { var require = module.require; var exports = module.exports; var __dirname = module.__dirname; var __filename = module.__filename;\"\n\tend = \"})\"\n)\n\nfunc null() module {\n\treturn func(ctx *Orbit) (val otto.Value, err error) {\n\t\treturn otto.UndefinedValue(), nil\n\t}\n}\n\nfunc load(name string, fold string) module {\n\treturn func(ctx *Orbit) (val otto.Value, err error) {\n\n\t\t\/\/ Check loaded modules\n\t\tif module, ok := ctx.modules[name]; ok {\n\t\t\treturn module, nil\n\t\t}\n\n\t\t\/\/ Check global modules\n\t\tif module, ok := modules[name]; ok {\n\t\t\treturn module(ctx)\n\t\t}\n\n\t\tctx.modules[name], err = find(name, fold)(ctx)\n\n\t\treturn ctx.modules[name], err\n\n\t}\n}\n\nfunc find(name string, fold string) module {\n\treturn func(ctx *Orbit) (val otto.Value, err error) {\n\n\t\tif len(name) == 0 {\n\t\t\tpanic(ctx.MakeCustomError(\"Error\", fmt.Sprintf(\"Cannot find module '%s'\", name)))\n\t\t}\n\n\t\tvar files []string\n\n\t\tif path.IsAbs(name) == true {\n\t\t\tif path.Ext(name) != \"\" {\n\t\t\t\tfiles = append(files, name)\n\t\t\t}\n\t\t\tif path.Ext(name) == \"\" {\n\t\t\t\tfiles = append(files, name+\".js\")\n\t\t\t\tfiles = append(files, path.Join(name, \"index.js\"))\n\t\t\t}\n\t\t}\n\n\t\tif path.IsAbs(name) == false {\n\t\t\tif path.Ext(name) != \"\" {\n\t\t\t\tfiles = append(files, path.Join(fold, name))\n\t\t\t}\n\t\t\tif path.Ext(name) == \"\" {\n\t\t\t\tfiles = append(files, path.Join(fold, name)+\".js\")\n\t\t\t\tfiles = append(files, path.Join(fold, name, \"index.js\"))\n\t\t\t}\n\t\t}\n\n\t\tcode, file, err := finder(ctx, files)\n\t\tif err != nil {\n\t\t\tpanic(ctx.MakeCustomError(\"Error\", fmt.Sprintf(\"Cannot find module '%s'\", name)))\n\t\t}\n\n\t\treturn exec(code, file)(ctx)\n\n\t}\n}\n\nfunc main(code interface{}, full string) module {\n\treturn func(ctx *Orbit) (val otto.Value, err error) {\n\n\t\tfold, file := path.Split(full)\n\n\t\tscript := fmt.Sprintf(\"%s\\n%s\\n%s\", beg, code, end)\n\n\t\tmodule, _ := ctx.Object(`({ exports: {} })`)\n\n\t\tmodule.Set(\"id\", full)\n\t\tmodule.Set(\"loaded\", true)\n\t\tmodule.Set(\"filename\", full)\n\t\tmodule.Set(\"__dirname\", fold)\n\t\tmodule.Set(\"__filename\", file)\n\n\t\tmodule.Set(\"require\", func(call otto.FunctionCall) otto.Value {\n\t\t\targ := call.Argument(0).String()\n\t\t\tval, err := load(arg, fold)(ctx)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn val\n\t\t})\n\n\t\tslf, _ := module.Get(\"exports\")\n\n\t\tsct, err := ctx.Compile(full, script)\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\trun, err := ctx.Otto.Run(sct)\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\tret, err := run.Call(slf, module)\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\texp, err := module.Get(\"exports\")\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\tif exp.IsFunction() {\n\t\t\tval, err = module.Call(\"exports\")\n\t\t\treturn\n\t\t}\n\n\t\tif exp.IsDefined() {\n\t\t\tval = exp\n\t\t\treturn\n\t\t}\n\n\t\tif ret.IsDefined() {\n\t\t\tval = ret\n\t\t\treturn\n\t\t}\n\n\t\treturn\n\n\t}\n\n}\n\nfunc exec(code interface{}, full string) module {\n\treturn func(ctx *Orbit) (val otto.Value, err error) {\n\n\t\tif path.Ext(full) == \".json\" {\n\t\t\treturn ctx.Call(\"JSON.parse\", nil, fmt.Sprintf(\"%s\", code))\n\t\t}\n\n\t\tfold, file := path.Split(full)\n\n\t\tscript := fmt.Sprintf(\"%s\\n%s\\n%s\", beg, code, end)\n\n\t\tmodule, _ := ctx.Object(`({ exports: {} })`)\n\n\t\tmodule.Set(\"id\", full)\n\t\tmodule.Set(\"loaded\", true)\n\t\tmodule.Set(\"filename\", full)\n\t\tmodule.Set(\"__dirname\", fold)\n\t\tmodule.Set(\"__filename\", file)\n\n\t\tmodule.Set(\"require\", func(call otto.FunctionCall) otto.Value {\n\t\t\targ := call.Argument(0).String()\n\t\t\tval, err := load(arg, fold)(ctx)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn val\n\t\t})\n\n\t\tslf, _ := module.Get(\"exports\")\n\n\t\tsct, err := ctx.Compile(full, script)\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\trun, err := ctx.Otto.Run(sct)\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\tret, err := run.Call(slf, module)\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\texp, err := module.Get(\"exports\")\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\tif exp.IsDefined() {\n\t\t\tval = exp\n\t\t\treturn\n\t\t}\n\n\t\tif ret.IsDefined() {\n\t\t\tval = ret\n\t\t\treturn\n\t\t}\n\n\t\treturn\n\n\t}\n\n}\n<commit_msg>Don’t start node.js module code on second line<commit_after>\/\/ Copyright © 2016 Abcum Ltd\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage orbit\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\n\t\"github.com\/robertkrimen\/otto\"\n)\n\nvar (\n\tbeg = \"(function(module) { var require = module.require; var exports = module.exports; var __dirname = module.__dirname; var __filename = module.__filename;\"\n\tend = \"})\"\n)\n\nfunc null() module {\n\treturn func(ctx *Orbit) (val otto.Value, err error) {\n\t\treturn otto.UndefinedValue(), nil\n\t}\n}\n\nfunc load(name string, fold string) module {\n\treturn func(ctx *Orbit) (val otto.Value, err error) {\n\n\t\t\/\/ Check loaded modules\n\t\tif module, ok := ctx.modules[name]; ok {\n\t\t\treturn module, nil\n\t\t}\n\n\t\t\/\/ Check global modules\n\t\tif module, ok := modules[name]; ok {\n\t\t\treturn module(ctx)\n\t\t}\n\n\t\tctx.modules[name], err = find(name, fold)(ctx)\n\n\t\treturn ctx.modules[name], err\n\n\t}\n}\n\nfunc find(name string, fold string) module {\n\treturn func(ctx *Orbit) (val otto.Value, err error) {\n\n\t\tif len(name) == 0 {\n\t\t\tpanic(ctx.MakeCustomError(\"Error\", fmt.Sprintf(\"Cannot find module '%s'\", name)))\n\t\t}\n\n\t\tvar files []string\n\n\t\tif path.IsAbs(name) == true {\n\t\t\tif path.Ext(name) != \"\" {\n\t\t\t\tfiles = append(files, name)\n\t\t\t}\n\t\t\tif path.Ext(name) == \"\" {\n\t\t\t\tfiles = append(files, name+\".js\")\n\t\t\t\tfiles = append(files, path.Join(name, \"index.js\"))\n\t\t\t}\n\t\t}\n\n\t\tif path.IsAbs(name) == false {\n\t\t\tif path.Ext(name) != \"\" {\n\t\t\t\tfiles = append(files, path.Join(fold, name))\n\t\t\t}\n\t\t\tif path.Ext(name) == \"\" {\n\t\t\t\tfiles = append(files, path.Join(fold, name)+\".js\")\n\t\t\t\tfiles = append(files, path.Join(fold, name, \"index.js\"))\n\t\t\t}\n\t\t}\n\n\t\tcode, file, err := finder(ctx, files)\n\t\tif err != nil {\n\t\t\tpanic(ctx.MakeCustomError(\"Error\", fmt.Sprintf(\"Cannot find module '%s'\", name)))\n\t\t}\n\n\t\treturn exec(code, file)(ctx)\n\n\t}\n}\n\nfunc main(code interface{}, full string) module {\n\treturn func(ctx *Orbit) (val otto.Value, err error) {\n\n\t\tfold, file := path.Split(full)\n\n\t\tscript := fmt.Sprintf(\"%s %s %s\", beg, code, end)\n\n\t\tmodule, _ := ctx.Object(`({ exports: {} })`)\n\n\t\tmodule.Set(\"id\", full)\n\t\tmodule.Set(\"loaded\", true)\n\t\tmodule.Set(\"filename\", full)\n\t\tmodule.Set(\"__dirname\", fold)\n\t\tmodule.Set(\"__filename\", file)\n\n\t\tmodule.Set(\"require\", func(call otto.FunctionCall) otto.Value {\n\t\t\targ := call.Argument(0).String()\n\t\t\tval, err := load(arg, fold)(ctx)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn val\n\t\t})\n\n\t\tslf, _ := module.Get(\"exports\")\n\n\t\tsct, err := ctx.Compile(full, script)\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\trun, err := ctx.Otto.Run(sct)\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\tret, err := run.Call(slf, module)\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\texp, err := module.Get(\"exports\")\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\tif exp.IsFunction() {\n\t\t\tval, err = module.Call(\"exports\")\n\t\t\treturn\n\t\t}\n\n\t\tif exp.IsDefined() {\n\t\t\tval = exp\n\t\t\treturn\n\t\t}\n\n\t\tif ret.IsDefined() {\n\t\t\tval = ret\n\t\t\treturn\n\t\t}\n\n\t\treturn\n\n\t}\n\n}\n\nfunc exec(code interface{}, full string) module {\n\treturn func(ctx *Orbit) (val otto.Value, err error) {\n\n\t\tif path.Ext(full) == \".json\" {\n\t\t\treturn ctx.Call(\"JSON.parse\", nil, fmt.Sprintf(\"%s\", code))\n\t\t}\n\n\t\tfold, file := path.Split(full)\n\n\t\tscript := fmt.Sprintf(\"%s %s %s\", beg, code, end)\n\n\t\tmodule, _ := ctx.Object(`({ exports: {} })`)\n\n\t\tmodule.Set(\"id\", full)\n\t\tmodule.Set(\"loaded\", true)\n\t\tmodule.Set(\"filename\", full)\n\t\tmodule.Set(\"__dirname\", fold)\n\t\tmodule.Set(\"__filename\", file)\n\n\t\tmodule.Set(\"require\", func(call otto.FunctionCall) otto.Value {\n\t\t\targ := call.Argument(0).String()\n\t\t\tval, err := load(arg, fold)(ctx)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn val\n\t\t})\n\n\t\tslf, _ := module.Get(\"exports\")\n\n\t\tsct, err := ctx.Compile(full, script)\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\trun, err := ctx.Otto.Run(sct)\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\tret, err := run.Call(slf, module)\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\texp, err := module.Get(\"exports\")\n\t\tif err != nil {\n\t\t\treturn otto.UndefinedValue(), err\n\t\t}\n\n\t\tif exp.IsDefined() {\n\t\t\tval = exp\n\t\t\treturn\n\t\t}\n\n\t\tif ret.IsDefined() {\n\t\t\tval = ret\n\t\t\treturn\n\t\t}\n\n\t\treturn\n\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package build\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\n\t\"github.com\/google\/go-cmp\/cmp\"\n)\n\nfunc TestFlags(t *testing.T) {\n\tcases := []struct {\n\t\targs []string\n\t\twant Options\n\t}{{\n\t\t\/\/ Defaults\n\t\targs: []string{},\n\t\twant: Options{},\n\t}, {\n\t\targs: []string{\"-index\", \"\/tmp\"},\n\t\twant: Options{\n\t\t\tIndexDir: \"\/tmp\",\n\t\t},\n\t}, {\n\t\t\/\/ single large file pattern\n\t\targs: []string{\"-large_file\", \"*.md\"},\n\t\twant: Options{\n\t\t\tLargeFiles: []string{\"*.md\"},\n\t\t},\n\t}, {\n\t\t\/\/ multiple large file pattern\n\t\targs: []string{\"-large_file\", \"*.md\", \"-large_file\", \"*.yaml\"},\n\t\twant: Options{\n\t\t\tLargeFiles: []string{\"*.md\", \"*.yaml\"},\n\t\t},\n\t}}\n\n\tfor _, c := range cases {\n\t\tc.want.SetDefaults()\n\n\t\tgot := Options{}\n\t\tfs := flag.NewFlagSet(\"\", flag.ContinueOnError)\n\t\tgot.Flags(fs)\n\t\tif err := fs.Parse(c.args); err != nil {\n\t\t\tt.Errorf(\"failed to parse args %v: %v\", c.args, err)\n\t\t} else if !cmp.Equal(got, c.want) {\n\t\t\tt.Errorf(\"mismatch for %v (-want +got):\\n%s\", c.args, cmp.Diff(c.want, got))\n\t\t}\n\t}\n}\n<commit_msg>build: filter out CTags setting from flag parse test<commit_after>package build\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\n\t\"github.com\/google\/go-cmp\/cmp\"\n)\n\nfunc TestFlags(t *testing.T) {\n\tcases := []struct {\n\t\targs []string\n\t\twant Options\n\t}{{\n\t\t\/\/ Defaults\n\t\targs: []string{},\n\t\twant: Options{},\n\t}, {\n\t\targs: []string{\"-index\", \"\/tmp\"},\n\t\twant: Options{\n\t\t\tIndexDir: \"\/tmp\",\n\t\t},\n\t}, {\n\t\t\/\/ single large file pattern\n\t\targs: []string{\"-large_file\", \"*.md\"},\n\t\twant: Options{\n\t\t\tLargeFiles: []string{\"*.md\"},\n\t\t},\n\t}, {\n\t\t\/\/ multiple large file pattern\n\t\targs: []string{\"-large_file\", \"*.md\", \"-large_file\", \"*.yaml\"},\n\t\twant: Options{\n\t\t\tLargeFiles: []string{\"*.md\", \"*.yaml\"},\n\t\t},\n\t}}\n\n\tfor _, c := range cases {\n\t\tc.want.SetDefaults()\n\t\t\/\/ depends on $PATH setting.\n\t\tc.want.CTags = \"\"\n\n\t\tgot := Options{}\n\t\tfs := flag.NewFlagSet(\"\", flag.ContinueOnError)\n\t\tgot.Flags(fs)\n\t\tif err := fs.Parse(c.args); err != nil {\n\t\t\tt.Errorf(\"failed to parse args %v: %v\", c.args, err)\n\t\t} else if !cmp.Equal(got, c.want) {\n\t\t\tt.Errorf(\"mismatch for %v (-want +got):\\n%s\", c.args, cmp.Diff(c.want, got))\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package handlers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/gizak\/termui\"\n\t\"github.com\/nlopes\/slack\"\n\n\t\"github.com\/erroneousboat\/slack-term\/src\/context\"\n\t\"github.com\/erroneousboat\/slack-term\/src\/views\"\n)\n\nfunc RegisterEventHandlers(ctx *context.AppContext) {\n\ttermui.Handle(\"\/sys\/kbd\/\", anyKeyHandler(ctx))\n\ttermui.Handle(\"\/sys\/wnd\/resize\", resizeHandler(ctx))\n\ttermui.Handle(\"\/timer\/1s\", timeHandler(ctx))\n\n\t\/\/ TODO: check channel of message should be added to correct channel\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase msg := <-ctx.Service.RTM.IncomingEvents:\n\t\t\t\tswitch ev := msg.Data.(type) {\n\t\t\t\tcase *slack.MessageEvent:\n\t\t\t\t\tvar name string\n\t\t\t\t\tuser, err := ctx.Service.Client.GetUserInfo(ev.User)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tname = user.Name\n\t\t\t\t\t} else {\n\t\t\t\t\t\tname = \"unknown\"\n\t\t\t\t\t}\n\t\t\t\t\tmsg := fmt.Sprintf(\"[%s] %s\", name, ev.Text)\n\t\t\t\t\tctx.View.Chat.AddMessage(msg)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc anyKeyHandler(ctx *context.AppContext) func(termui.Event) {\n\treturn func(e termui.Event) {\n\t\tkey := e.Data.(termui.EvtKbd).KeyStr\n\n\t\tif ctx.Mode == context.CommandMode {\n\t\t\tswitch key {\n\t\t\tcase \"q\":\n\t\t\t\tactionQuit()\n\t\t\t\treturn\n\t\t\tcase \"i\":\n\t\t\t\tactionInsertMode(ctx)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if ctx.Mode == context.InsertMode {\n\t\t\tswitch key {\n\t\t\tcase \"<escape>\":\n\t\t\t\tactionCommandMode(ctx)\n\t\t\t\treturn\n\t\t\tcase \"<enter>\":\n\t\t\t\tactionSend(ctx)\n\t\t\t\treturn\n\t\t\tcase \"<space>\":\n\t\t\t\tactionInput(ctx.View, \" \")\n\t\t\t\treturn\n\t\t\tcase \"<backspace>\":\n\t\t\t\tactionBackSpace(ctx.View)\n\t\t\tcase \"C-8\":\n\t\t\t\tactionBackSpace(ctx.View)\n\t\t\tcase \"<right>\":\n\t\t\t\tactionMoveCursorRight(ctx.View)\n\t\t\tcase \"<left>\":\n\t\t\t\tactionMoveCursorLeft(ctx.View)\n\t\t\tdefault:\n\t\t\t\tactionInput(ctx.View, key)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\n\t}\n}\n\nfunc resizeHandler(ctx *context.AppContext) func(termui.Event) {\n\treturn func(e termui.Event) {\n\t\tactionResize(ctx)\n\t}\n}\n\nfunc timeHandler(ctx *context.AppContext) func(termui.Event) {\n\treturn func(e termui.Event) {\n\t}\n}\n\n\/\/ FIXME: resize only seems to work for width and resizing it too small\n\/\/ will cause termui to panic\nfunc actionResize(ctx *context.AppContext) {\n\ttermui.Body.Width = termui.TermWidth()\n\ttermui.Body.Align()\n\ttermui.Render(termui.Body)\n}\n\nfunc actionInput(view *views.View, key string) {\n\tview.Input.Insert(key)\n\ttermui.Render(view.Input)\n}\n\nfunc actionBackSpace(view *views.View) {\n\tview.Input.Remove()\n\ttermui.Render(view.Input)\n}\n\nfunc actionMoveCursorRight(view *views.View) {\n\tview.Input.MoveCursorRight()\n\ttermui.Render(view.Input)\n}\n\nfunc actionMoveCursorLeft(view *views.View) {\n\tview.Input.MoveCursorLeft()\n\ttermui.Render(view.Input)\n}\n\nfunc actionSend(ctx *context.AppContext) {\n\tif !ctx.View.Input.IsEmpty() {\n\t\t\/\/ FIXME\n\t\tctx.View.Chat.List.Items = append(ctx.View.Chat.List.Items, ctx.View.Input.Text())\n\t\tctx.View.Input.Clear()\n\t\tctx.View.Refresh()\n\t}\n}\n\nfunc actionQuit() {\n\ttermui.StopLoop()\n}\n\nfunc actionInsertMode(ctx *context.AppContext) {\n\tctx.Mode = context.InsertMode\n\tctx.View.Mode.Par.Text = \"INSERT\"\n\ttermui.Render(ctx.View.Mode)\n}\n\nfunc actionCommandMode(ctx *context.AppContext) {\n\tctx.Mode = context.CommandMode\n\tctx.View.Mode.Par.Text = \"NORMAL\"\n\ttermui.Render(ctx.View.Mode)\n}\n\n\/\/ TODO: get message for channel\nfunc actionGetMessages(ctx *context.AppContext) {\n\tctx.View.Chat.GetMessages(ctx.Service)\n\ttermui.Render(ctx.View.Chat)\n}\n\nfunc actionGetChannels(ctx *context.AppContext) {\n\tctx.View.Channels.GetChannels(ctx.Service)\n\ttermui.Render(ctx.View.Channels)\n}\n<commit_msg>Update event incomingMessageHandler<commit_after>package handlers\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/gizak\/termui\"\n\t\"github.com\/nlopes\/slack\"\n\n\t\"github.com\/erroneousboat\/slack-term\/src\/context\"\n\t\"github.com\/erroneousboat\/slack-term\/src\/views\"\n)\n\nfunc RegisterEventHandlers(ctx *context.AppContext) {\n\ttermui.Handle(\"\/sys\/kbd\/\", anyKeyHandler(ctx))\n\ttermui.Handle(\"\/sys\/wnd\/resize\", resizeHandler(ctx))\n\ttermui.Handle(\"\/timer\/1s\", timeHandler(ctx))\n\tincomingMessageHandler(ctx)\n}\n\nfunc anyKeyHandler(ctx *context.AppContext) func(termui.Event) {\n\treturn func(e termui.Event) {\n\t\tkey := e.Data.(termui.EvtKbd).KeyStr\n\n\t\tif ctx.Mode == context.CommandMode {\n\t\t\tswitch key {\n\t\t\tcase \"q\":\n\t\t\t\tactionQuit()\n\t\t\t\treturn\n\t\t\tcase \"i\":\n\t\t\t\tactionInsertMode(ctx)\n\t\t\t\treturn\n\t\t\t}\n\t\t} else if ctx.Mode == context.InsertMode {\n\t\t\tswitch key {\n\t\t\tcase \"<escape>\":\n\t\t\t\tactionCommandMode(ctx)\n\t\t\t\treturn\n\t\t\tcase \"<enter>\":\n\t\t\t\tactionSend(ctx)\n\t\t\t\treturn\n\t\t\tcase \"<space>\":\n\t\t\t\tactionInput(ctx.View, \" \")\n\t\t\t\treturn\n\t\t\tcase \"<backspace>\":\n\t\t\t\tactionBackSpace(ctx.View)\n\t\t\tcase \"C-8\":\n\t\t\t\tactionBackSpace(ctx.View)\n\t\t\tcase \"<right>\":\n\t\t\t\tactionMoveCursorRight(ctx.View)\n\t\t\tcase \"<left>\":\n\t\t\t\tactionMoveCursorLeft(ctx.View)\n\t\t\tdefault:\n\t\t\t\tactionInput(ctx.View, key)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\n\t}\n}\n\nfunc resizeHandler(ctx *context.AppContext) func(termui.Event) {\n\treturn func(e termui.Event) {\n\t\tactionResize(ctx)\n\t}\n}\n\nfunc timeHandler(ctx *context.AppContext) func(termui.Event) {\n\treturn func(e termui.Event) {\n\t}\n}\n\nfunc incomingMessageHandler(ctx *context.AppContext) {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase msg := <-ctx.Service.RTM.IncomingEvents:\n\t\t\t\tswitch ev := msg.Data.(type) {\n\t\t\t\tcase *slack.MessageEvent:\n\n\t\t\t\t\t\/\/ TODO: refactor this to CreateMessage\n\t\t\t\t\tvar name string\n\t\t\t\t\tuser, err := ctx.Service.Client.GetUserInfo(ev.User)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tname = user.Name\n\t\t\t\t\t} else {\n\t\t\t\t\t\tname = \"unknown\"\n\t\t\t\t\t}\n\t\t\t\t\tm := fmt.Sprintf(\"[%s] %s\", name, ev.Text)\n\n\t\t\t\t\t\/\/ Add message to the selected channel\n\t\t\t\t\t\/\/ fmt.Println(ev.Channel)\n\t\t\t\t\tif ev.Channel == ctx.View.Chat.SelectedChannel {\n\t\t\t\t\t\tctx.View.Chat.AddMessage(m)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\/\/ FIXME: resize only seems to work for width and resizing it too small\n\/\/ will cause termui to panic\nfunc actionResize(ctx *context.AppContext) {\n\ttermui.Body.Width = termui.TermWidth()\n\ttermui.Body.Align()\n\ttermui.Render(termui.Body)\n}\n\nfunc actionInput(view *views.View, key string) {\n\tview.Input.Insert(key)\n\ttermui.Render(view.Input)\n}\n\nfunc actionBackSpace(view *views.View) {\n\tview.Input.Remove()\n\ttermui.Render(view.Input)\n}\n\nfunc actionMoveCursorRight(view *views.View) {\n\tview.Input.MoveCursorRight()\n\ttermui.Render(view.Input)\n}\n\nfunc actionMoveCursorLeft(view *views.View) {\n\tview.Input.MoveCursorLeft()\n\ttermui.Render(view.Input)\n}\n\nfunc actionSend(ctx *context.AppContext) {\n\tif !ctx.View.Input.IsEmpty() {\n\t\t\/\/ FIXME\n\t\tctx.View.Chat.List.Items = append(ctx.View.Chat.List.Items, ctx.View.Input.Text())\n\t\tctx.View.Input.Clear()\n\t\tctx.View.Refresh()\n\t}\n}\n\nfunc actionQuit() {\n\ttermui.StopLoop()\n}\n\nfunc actionInsertMode(ctx *context.AppContext) {\n\tctx.Mode = context.InsertMode\n\tctx.View.Mode.Par.Text = \"INSERT\"\n\ttermui.Render(ctx.View.Mode)\n}\n\nfunc actionCommandMode(ctx *context.AppContext) {\n\tctx.Mode = context.CommandMode\n\tctx.View.Mode.Par.Text = \"NORMAL\"\n\ttermui.Render(ctx.View.Mode)\n}\n\n\/\/ TODO: get message for channel\nfunc actionGetMessages(ctx *context.AppContext) {\n\tctx.View.Chat.GetMessages(ctx.Service)\n\ttermui.Render(ctx.View.Chat)\n}\n\nfunc actionGetChannels(ctx *context.AppContext) {\n\tctx.View.Channels.GetChannels(ctx.Service)\n\ttermui.Render(ctx.View.Channels)\n}\n<|endoftext|>"}
{"text":"<commit_before>package hooks\n\nimport (\n\t\"compress\/gzip\"\n\t\"github.com\/imosquera\/uploadthis\/commands\"\n\t\"github.com\/imosquera\/uploadthis\/util\"\n\tlog \"github.com\/cihub\/seelog\"\n\t\"io\"\n\t\"path\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"crypto\/rand\"\n\t\"encoding\/hex\"\n)\n\n\/\/*********************\n\/\/ COMPRESSOR\n\/\/*********************\ntype GzipFileCompressor struct{}\n\nfunc (self *GzipFileCompressor) Compress(filepath string) (string, error) {\n\tinFile, err := util.Fs.Open(filepath)\n\tif err != nil {\n\t\tlog.Critical(\"Error for file \" + filepath + \" \" + err.Error())\n\t}\n\n\t\/\/create the gzip file\n\tgzipPath := path.Join(path.Dir(filepath), path.Base(filepath)+\".gz\")\n\toutFile, err := util.Fs.Create(gzipPath)\n\tutil.LogPanic(err)\n\n\t\/\/create a new gzip writer so we can copy the bytes\n\tgzipWriter, err := gzip.NewWriterLevel(outFile, gzip.BestCompression)\n\tutil.LogPanic(err)\n\t_, err = io.Copy(gzipWriter, inFile)\n\tutil.LogPanic(err)\n\n\tgzipWriter.Close()\n\treturn gzipPath, err\n}\n\ntype Compressor interface {\n\tCompress(filepath string) (string, error)\n}\n\nfunc NewCompressPrehook() *CompressPrehook {\n\treturn &CompressPrehook{\n\t\tcommands.NewFileStateCommand(),\n\t\t&GzipFileCompressor{},\n\t}\n}\n\ntype CompressPrehook struct {\n\t*commands.Command\n\tcompressor Compressor\n}\n\n\/\/this function will compress the infile and\n\/\/return a file pointer that is readible\nfunc (c CompressPrehook) Run() ([]string, error) {\n\tvar err error\n\tnewFiles := make([]string, 0, len(c.UploadFiles))\n\tfor _, uploadFile := range c.UploadFiles {\n\t\tuploadFile, _ := c.compressor.Compress(uploadFile)\n\t\tnewFiles = append(newFiles, uploadFile)\n\t}\n\treturn newFiles, err\n}\n\n\/\/**************\n\/\/ Renamer\n\/\/**************\ntype Renamer interface {\n\tRename(filepath string) (string, error)\n\tSetProperties(...interface {})\n}\n\ntype UniqueSuffixRenamer struct{\n\tRenamer\n\tsuffixLength int\n}\n\nfunc (self *UniqueSuffixRenamer) Rename(filename string) (string, error) {\n\tvar extension = filepath.Ext(filename)\n\tvar name = filename[0:len(filename)-len(extension)]\n\tsuffix, _ := self.GenerateRandomString(self.suffixLength)\n\tvar newName = name + \"-\" + suffix + extension\n\n\terr := os.Rename(filename, newName)\n\tif err != nil {\n\t\tlog.Critical(\"Error for file \" + filename + \" \" + err.Error())\n\t\tutil.LogPanic(err)\n\t}\n\treturn newName, err\n}\n\nfunc (self *UniqueSuffixRenamer) GenerateRandomString(length int) (string, error) {\n\tuuid := make([]byte, length)\n\t_, err := rand.Read(uuid)\n\tif err != nil {\n\t\tlog.Critical(\"Error generating random string \" + err.Error())\n\t\tutil.LogPanic(err)\n\t\treturn \"\", err\n\t}\n\treturn hex.EncodeToString(uuid), nil\n}\n\ntype RenamePrehook struct {\n\t*commands.Command\n\trenamer Renamer\n}\n\nfunc NewRenamePrehook() *RenamePrehook {\n\treturn &RenamePrehook{\n\t\tcommands.NewFileStateCommand(),\n\t\t&UniqueSuffixRenamer{suffixLength: 2},\n\t}\n}\n\n\/\/this function will rename the infile and\n\/\/return a new file name\nfunc (self RenamePrehook) Run() ([]string, error) {\n\tvar err error\n\tnewFiles := make([]string, 0, len(self.UploadFiles))\n\tfor _, uploadFile := range self.UploadFiles {\n\t\tnewFile, the_err := self.renamer.Rename(uploadFile)\n\t\tlog.Info(\"Rename: \", uploadFile, \" -> \", newFile)\n\t\tif the_err != nil {\n\t\t\terr = the_err\n\t\t}\n\t\tnewFiles = append(newFiles, newFile)\n\t}\n\treturn newFiles, err\n}\n<commit_msg>Fix bug: Uploader does not delete original files after compression https:\/\/www.pivotaltracker.com\/story\/show\/62644146<commit_after>package hooks\n\nimport (\n\t\"compress\/gzip\"\n\t\"github.com\/imosquera\/uploadthis\/commands\"\n\t\"github.com\/imosquera\/uploadthis\/util\"\n\tlog \"github.com\/cihub\/seelog\"\n\t\"io\"\n\t\"path\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"crypto\/rand\"\n\t\"encoding\/hex\"\n)\n\n\/\/*********************\n\/\/ COMPRESSOR\n\/\/*********************\ntype GzipFileCompressor struct{}\n\nfunc (self *GzipFileCompressor) Compress(filepath string) (string, error) {\n\tinFile, err := util.Fs.Open(filepath)\n\tif err != nil {\n\t\tlog.Critical(\"Error for file \" + filepath + \" \" + err.Error())\n\t}\n\n\t\/\/create the gzip file\n\tgzipPath := path.Join(path.Dir(filepath), path.Base(filepath)+\".gz\")\n\toutFile, err := util.Fs.Create(gzipPath)\n\tutil.LogPanic(err)\n\n\t\/\/create a new gzip writer so we can copy the bytes\n\tgzipWriter, err := gzip.NewWriterLevel(outFile, gzip.BestCompression)\n\tutil.LogPanic(err)\n\t_, err = io.Copy(gzipWriter, inFile)\n\tutil.LogPanic(err)\n\n\terr = os.Remove(filepath)\n\tutil.LogPanic(err)\n\n\tgzipWriter.Close()\n\treturn gzipPath, err\n}\n\ntype Compressor interface {\n\tCompress(filepath string) (string, error)\n}\n\nfunc NewCompressPrehook() *CompressPrehook {\n\treturn &CompressPrehook{\n\t\tcommands.NewFileStateCommand(),\n\t\t&GzipFileCompressor{},\n\t}\n}\n\ntype CompressPrehook struct {\n\t*commands.Command\n\tcompressor Compressor\n}\n\n\/\/this function will compress the infile and\n\/\/return a file pointer that is readible\nfunc (c CompressPrehook) Run() ([]string, error) {\n\tvar err error\n\tnewFiles := make([]string, 0, len(c.UploadFiles))\n\tfor _, uploadFile := range c.UploadFiles {\n\t\tuploadFile, _ := c.compressor.Compress(uploadFile)\n\t\tnewFiles = append(newFiles, uploadFile)\n\t}\n\treturn newFiles, err\n}\n\n\/\/**************\n\/\/ Renamer\n\/\/**************\ntype Renamer interface {\n\tRename(filepath string) (string, error)\n\tSetProperties(...interface {})\n}\n\ntype UniqueSuffixRenamer struct{\n\tRenamer\n\tsuffixLength int\n}\n\nfunc (self *UniqueSuffixRenamer) Rename(filename string) (string, error) {\n\tvar extension = filepath.Ext(filename)\n\tvar name = filename[0:len(filename)-len(extension)]\n\tsuffix, _ := self.GenerateRandomString(self.suffixLength)\n\tvar newName = name + \"-\" + suffix + extension\n\n\terr := os.Rename(filename, newName)\n\tif err != nil {\n\t\tlog.Critical(\"Error for file \" + filename + \" \" + err.Error())\n\t\tutil.LogPanic(err)\n\t}\n\treturn newName, err\n}\n\nfunc (self *UniqueSuffixRenamer) GenerateRandomString(length int) (string, error) {\n\tuuid := make([]byte, length)\n\t_, err := rand.Read(uuid)\n\tif err != nil {\n\t\tlog.Critical(\"Error generating random string \" + err.Error())\n\t\tutil.LogPanic(err)\n\t\treturn \"\", err\n\t}\n\treturn hex.EncodeToString(uuid), nil\n}\n\ntype RenamePrehook struct {\n\t*commands.Command\n\trenamer Renamer\n}\n\nfunc NewRenamePrehook() *RenamePrehook {\n\treturn &RenamePrehook{\n\t\tcommands.NewFileStateCommand(),\n\t\t&UniqueSuffixRenamer{suffixLength: 2},\n\t}\n}\n\n\/\/this function will rename the infile and\n\/\/return a new file name\nfunc (self RenamePrehook) Run() ([]string, error) {\n\tvar err error\n\tnewFiles := make([]string, 0, len(self.UploadFiles))\n\tfor _, uploadFile := range self.UploadFiles {\n\t\tnewFile, the_err := self.renamer.Rename(uploadFile)\n\t\tlog.Info(\"Rename: \", uploadFile, \" -> \", newFile)\n\t\tif the_err != nil {\n\t\t\terr = the_err\n\t\t}\n\t\tnewFiles = append(newFiles, newFile)\n\t}\n\treturn newFiles, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n *  Copyright 2014 Paul Querna\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *\/\n\npackage hotp\n\nimport (\n\t\"github.com\/pquerna\/otp\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\n\t\"encoding\/base32\"\n\t\"testing\"\n)\n\ntype tc struct {\n\tCounter uint64\n\tTOTP    string\n\tMode    otp.Algorithm\n\tSecret  string\n}\n\nvar (\n\tsecSha1 = base32.StdEncoding.EncodeToString([]byte(\"12345678901234567890\"))\n\n\trfcMatrixTCs = []tc{\n\t\ttc{0, \"755224\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{1, \"287082\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{2, \"359152\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{3, \"969429\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{4, \"338314\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{5, \"254676\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{6, \"287922\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{7, \"162583\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{8, \"399871\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{9, \"520489\", otp.AlgorithmSHA1, secSha1},\n\t}\n)\n\n\/\/ Test values from http:\/\/tools.ietf.org\/html\/rfc4226#appendix-D\nfunc TestValidateRFCMatrix(t *testing.T) {\n\n\tfor _, tx := range rfcMatrixTCs {\n\t\tvalid, err := ValidateCustom(tx.TOTP, tx.Counter, tx.Secret,\n\t\t\tValidateOpts{\n\t\t\t\tDigits:    otp.DigitsSix,\n\t\t\t\tAlgorithm: tx.Mode,\n\t\t\t})\n\t\trequire.NoError(t, err,\n\t\t\t\"unexpected error totp=%s mode=%v counter=%v\", tx.TOTP, tx.Mode, tx.Counter)\n\t\trequire.True(t, valid,\n\t\t\t\"unexpected totp failure totp=%s mode=%v counter=%v\", tx.TOTP, tx.Mode, tx.Counter)\n\t}\n}\n\nfunc TestGenerateRFCMatrix(t *testing.T) {\n\tfor _, tx := range rfcMatrixTCs {\n\t\tpasscode, err := GenerateCodeCustom(tx.Secret, tx.Counter,\n\t\t\tValidateOpts{\n\t\t\t\tDigits:    otp.DigitsSix,\n\t\t\t\tAlgorithm: tx.Mode,\n\t\t\t})\n\t\tassert.Nil(t, err)\n\t\tassert.Equal(t, tx.TOTP, passcode)\n\t}\n}\n\nfunc TestValidateInvalid(t *testing.T) {\n\tsecSha1 := base32.StdEncoding.EncodeToString([]byte(\"12345678901234567890\"))\n\n\tvalid, err := ValidateCustom(\"foo\", 11, secSha1,\n\t\tValidateOpts{\n\t\t\tDigits:    otp.DigitsSix,\n\t\t\tAlgorithm: otp.AlgorithmSHA1,\n\t\t})\n\trequire.Equal(t, otp.ErrValidateInputInvalidLength, err, \"Expected Invalid length error.\")\n\trequire.Equal(t, false, valid, \"Valid should be false when we have an error.\")\n\n\tvalid, err = ValidateCustom(\"foo\", 11, secSha1,\n\t\tValidateOpts{\n\t\t\tDigits:    otp.DigitsEight,\n\t\t\tAlgorithm: otp.AlgorithmSHA1,\n\t\t})\n\trequire.Equal(t, otp.ErrValidateInputInvalidLength, err, \"Expected Invalid length error.\")\n\trequire.Equal(t, false, valid, \"Valid should be false when we have an error.\")\n\n\tvalid, err = ValidateCustom(\"000000\", 11, secSha1,\n\t\tValidateOpts{\n\t\t\tDigits:    otp.DigitsSix,\n\t\t\tAlgorithm: otp.AlgorithmSHA1,\n\t\t})\n\trequire.NoError(t, err, \"Expected no error.\")\n\trequire.Equal(t, false, valid, \"Valid should be false.\")\n\n\tvalid = Validate(\"000000\", 11, secSha1)\n\trequire.Equal(t, false, valid, \"Valid should be false.\")\n}\n\nfunc TestGenerate(t *testing.T) {\n\tk, err := Generate(GenerateOpts{\n\t\tIssuer:      \"SnakeOil\",\n\t\tAccountName: \"alice@example.com\",\n\t})\n\trequire.NoError(t, err, \"generate basic TOTP\")\n\trequire.Equal(t, \"SnakeOil\", k.Issuer(), \"Extracting Issuer\")\n\trequire.Equal(t, \"alice@example.com\", k.AccountName(), \"Extracting Account Name\")\n\trequire.Equal(t, 16, len(k.Secret()), \"Secret is 16 bytes long as base32.\")\n\n\tk, err = Generate(GenerateOpts{\n\t\tIssuer:      \"SnakeOil\",\n\t\tAccountName: \"alice@example.com\",\n\t\tSecretSize:  20,\n\t})\n\trequire.NoError(t, err, \"generate larger TOTP\")\n\trequire.Equal(t, 32, len(k.Secret()), \"Secret is 32 bytes long as base32.\")\n\n\tk, err = Generate(GenerateOpts{\n\t\tIssuer:      \"\",\n\t\tAccountName: \"alice@example.com\",\n\t})\n\trequire.Equal(t, otp.ErrGenerateMissingIssuer, err, \"generate missing issuer\")\n\trequire.Nil(t, k, \"key should be nil on error.\")\n\n\tk, err = Generate(GenerateOpts{\n\t\tIssuer:      \"Foobar, Inc\",\n\t\tAccountName: \"\",\n\t})\n\trequire.Equal(t, otp.ErrGenerateMissingAccountName, err, \"generate missing account name.\")\n\trequire.Nil(t, k, \"key should be nil on error.\")\n}\n<commit_msg>#10 added spec to test secret without padding<commit_after>\/**\n *  Copyright 2014 Paul Querna\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *\/\n\npackage hotp\n\nimport (\n\t\"github.com\/pquerna\/otp\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\n\t\"encoding\/base32\"\n\t\"testing\"\n)\n\ntype tc struct {\n\tCounter uint64\n\tTOTP    string\n\tMode    otp.Algorithm\n\tSecret  string\n}\n\nvar (\n\tsecSha1 = base32.StdEncoding.EncodeToString([]byte(\"12345678901234567890\"))\n\n\trfcMatrixTCs = []tc{\n\t\ttc{0, \"755224\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{1, \"287082\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{2, \"359152\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{3, \"969429\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{4, \"338314\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{5, \"254676\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{6, \"287922\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{7, \"162583\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{8, \"399871\", otp.AlgorithmSHA1, secSha1},\n\t\ttc{9, \"520489\", otp.AlgorithmSHA1, secSha1},\n\t}\n)\n\n\/\/ Test values from http:\/\/tools.ietf.org\/html\/rfc4226#appendix-D\nfunc TestValidateRFCMatrix(t *testing.T) {\n\n\tfor _, tx := range rfcMatrixTCs {\n\t\tvalid, err := ValidateCustom(tx.TOTP, tx.Counter, tx.Secret,\n\t\t\tValidateOpts{\n\t\t\t\tDigits:    otp.DigitsSix,\n\t\t\t\tAlgorithm: tx.Mode,\n\t\t\t})\n\t\trequire.NoError(t, err,\n\t\t\t\"unexpected error totp=%s mode=%v counter=%v\", tx.TOTP, tx.Mode, tx.Counter)\n\t\trequire.True(t, valid,\n\t\t\t\"unexpected totp failure totp=%s mode=%v counter=%v\", tx.TOTP, tx.Mode, tx.Counter)\n\t}\n}\n\nfunc TestGenerateRFCMatrix(t *testing.T) {\n\tfor _, tx := range rfcMatrixTCs {\n\t\tpasscode, err := GenerateCodeCustom(tx.Secret, tx.Counter,\n\t\t\tValidateOpts{\n\t\t\t\tDigits:    otp.DigitsSix,\n\t\t\t\tAlgorithm: tx.Mode,\n\t\t\t})\n\t\tassert.Nil(t, err)\n\t\tassert.Equal(t, tx.TOTP, passcode)\n\t}\n}\n\nfunc TestValidateInvalid(t *testing.T) {\n\tsecSha1 := base32.StdEncoding.EncodeToString([]byte(\"12345678901234567890\"))\n\n\tvalid, err := ValidateCustom(\"foo\", 11, secSha1,\n\t\tValidateOpts{\n\t\t\tDigits:    otp.DigitsSix,\n\t\t\tAlgorithm: otp.AlgorithmSHA1,\n\t\t})\n\trequire.Equal(t, otp.ErrValidateInputInvalidLength, err, \"Expected Invalid length error.\")\n\trequire.Equal(t, false, valid, \"Valid should be false when we have an error.\")\n\n\tvalid, err = ValidateCustom(\"foo\", 11, secSha1,\n\t\tValidateOpts{\n\t\t\tDigits:    otp.DigitsEight,\n\t\t\tAlgorithm: otp.AlgorithmSHA1,\n\t\t})\n\trequire.Equal(t, otp.ErrValidateInputInvalidLength, err, \"Expected Invalid length error.\")\n\trequire.Equal(t, false, valid, \"Valid should be false when we have an error.\")\n\n\tvalid, err = ValidateCustom(\"000000\", 11, secSha1,\n\t\tValidateOpts{\n\t\t\tDigits:    otp.DigitsSix,\n\t\t\tAlgorithm: otp.AlgorithmSHA1,\n\t\t})\n\trequire.NoError(t, err, \"Expected no error.\")\n\trequire.Equal(t, false, valid, \"Valid should be false.\")\n\n\tvalid = Validate(\"000000\", 11, secSha1)\n\trequire.Equal(t, false, valid, \"Valid should be false.\")\n}\n\n\/\/ This tests for issue #10 - secrets without padding\nfunc TestValidatePadding(t *testing.T) {\n\tvalid, err := ValidateCustom(\"831097\", 0, \"JBSWY3DPEHPK3PX\",\n\t\tValidateOpts{\n\t\t\tDigits:    otp.DigitsSix,\n\t\t\tAlgorithm: otp.AlgorithmSHA1,\n\t\t})\n\trequire.NoError(t, err, \"Expected no error.\")\n\trequire.Equal(t, true, valid, \"Valid should be true.\")\n}\n\nfunc TestGenerate(t *testing.T) {\n\tk, err := Generate(GenerateOpts{\n\t\tIssuer:      \"SnakeOil\",\n\t\tAccountName: \"alice@example.com\",\n\t})\n\trequire.NoError(t, err, \"generate basic TOTP\")\n\trequire.Equal(t, \"SnakeOil\", k.Issuer(), \"Extracting Issuer\")\n\trequire.Equal(t, \"alice@example.com\", k.AccountName(), \"Extracting Account Name\")\n\trequire.Equal(t, 16, len(k.Secret()), \"Secret is 16 bytes long as base32.\")\n\n\tk, err = Generate(GenerateOpts{\n\t\tIssuer:      \"SnakeOil\",\n\t\tAccountName: \"alice@example.com\",\n\t\tSecretSize:  20,\n\t})\n\trequire.NoError(t, err, \"generate larger TOTP\")\n\trequire.Equal(t, 32, len(k.Secret()), \"Secret is 32 bytes long as base32.\")\n\n\tk, err = Generate(GenerateOpts{\n\t\tIssuer:      \"\",\n\t\tAccountName: \"alice@example.com\",\n\t})\n\trequire.Equal(t, otp.ErrGenerateMissingIssuer, err, \"generate missing issuer\")\n\trequire.Nil(t, k, \"key should be nil on error.\")\n\n\tk, err = Generate(GenerateOpts{\n\t\tIssuer:      \"Foobar, Inc\",\n\t\tAccountName: \"\",\n\t})\n\trequire.Equal(t, otp.ErrGenerateMissingAccountName, err, \"generate missing account name.\")\n\trequire.Nil(t, k, \"key should be nil on error.\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package endpoint\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\thttpExpiresAfter       = time.Second * 30\n\thttpRequestTimeout     = time.Second * 5\n\thttpMaxIdleConnections = 20\n)\n\ntype HTTPEndpointConn struct {\n\tmu     sync.Mutex\n\tep     Endpoint\n\tex     bool\n\tt      time.Time\n\tclient *http.Client\n}\n\nfunc newHTTPEndpointConn(ep Endpoint) *HTTPEndpointConn {\n\treturn &HTTPEndpointConn{\n\t\tep: ep,\n\t\tt:  time.Now(),\n\t}\n}\n\nfunc (conn *HTTPEndpointConn) Expired() bool {\n\tconn.mu.Lock()\n\tdefer conn.mu.Unlock()\n\tif !conn.ex {\n\t\tif time.Now().Sub(conn.t) > httpExpiresAfter {\n\t\t\tconn.ex = true\n\t\t\tconn.client = nil\n\t\t}\n\t}\n\treturn conn.ex\n}\n\nfunc (conn *HTTPEndpointConn) Send(msg string) error {\n\tconn.mu.Lock()\n\tdefer conn.mu.Unlock()\n\tif conn.ex {\n\t\treturn errExpired\n\t}\n\tconn.t = time.Now()\n\tif conn.client == nil {\n\t\tconn.client = &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tMaxIdleConnsPerHost: httpMaxIdleConnections,\n\t\t\t},\n\t\t\tTimeout: httpRequestTimeout,\n\t\t}\n\t}\n\treq, err := http.NewRequest(\"POST\", conn.ep.Original, bytes.NewBufferString(msg))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\tresp, err := conn.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ close the connection to reuse it\n\tdefer resp.Body.Close()\n\t\/\/ discard response\n\tif _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {\n\t\treturn err\n\t}\n\t\/\/ we only care about the 200 response\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"invalid status: %s\", resp.Status)\n\t}\n\treturn nil\n}\n<commit_msg>Fix leaking http connections (#147)<commit_after>package endpoint\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\thttpExpiresAfter       = time.Second * 30\n\thttpRequestTimeout     = time.Second * 5\n\thttpMaxIdleConnections = 20\n)\n\ntype HTTPEndpointConn struct {\n\tmu     sync.Mutex\n\tep     Endpoint\n\tclient *http.Client\n}\n\nfunc newHTTPEndpointConn(ep Endpoint) *HTTPEndpointConn {\n\treturn &HTTPEndpointConn{\n\t\tep: ep,\n\t}\n}\n\nfunc (conn *HTTPEndpointConn) Expired() bool {\n\treturn false\n}\n\nfunc (conn *HTTPEndpointConn) Send(msg string) error {\n\tconn.mu.Lock()\n\tdefer conn.mu.Unlock()\n\n\tif conn.client == nil {\n\t\tconn.client = &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tMaxIdleConnsPerHost: httpMaxIdleConnections,\n\t\t\t\tIdleConnTimeout:     httpExpiresAfter,\n\t\t\t},\n\t\t\tTimeout: httpRequestTimeout,\n\t\t}\n\t}\n\treq, err := http.NewRequest(\"POST\", conn.ep.Original, bytes.NewBufferString(msg))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\tresp, err := conn.client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ close the connection to reuse it\n\tdefer resp.Body.Close()\n\t\/\/ discard response\n\tif _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {\n\t\treturn err\n\t}\n\t\/\/ we only care about the 200 response\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"invalid status: %s\", resp.Status)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/mehrdadrad\/myping\/cli\"\n\t\"github.com\/mehrdadrad\/myping\/icmp\"\n\t\"github.com\/mehrdadrad\/myping\/icmp\/telia\"\n\t\"net\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype Provider interface {\n\tInit(host, version string)\n\tGetDefaultNode() string\n\tGetNodes() map[string]string\n\tPing() (string, error)\n}\n\nvar providers = map[string]Provider{\"telia\": new(telia.Provider)}\n\nfunc validateProvider(p string) (string, error) {\n\tp = strings.ToLower(p)\n\treturn p, nil\n}\n\nfunc main() {\n\tvar (\n\t\terr    error\n\t\tcPName string = \"local\"\n\t)\n\n\trep := make(chan string, 1)\n\tcmd := make(chan string, 1)\n\tnxt := make(chan struct{}, 1)\n\n\tc := cli.Init(\"local\")\n\tgo c.Run(cmd, nxt)\n\n\tr, _ := regexp.Compile(\"(ping|connect) (.*)\")\n\n\tfor {\n\t\tselect {\n\t\tcase req := <-cmd:\n\t\t\tsubReq := r.FindStringSubmatch(req)\n\t\t\tif len(subReq) == 0 {\n\t\t\t\tprintln(\"syntax error\")\n\t\t\t\tnxt <- struct{}{}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase subReq[1] == \"ping\" && cPName == \"local\":\n\t\t\t\tp := icmp.NewPing()\n\t\t\t\tra, err := net.ResolveIPAddr(\"ip\", subReq[2])\n\t\t\t\tif err != nil {\n\t\t\t\t\tprintln(\"cannot resolve\", subReq[2], \": Unknown host\")\n\t\t\t\t\tnxt <- struct{}{}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tp.IP(ra.String())\n\t\t\t\tfor n := 0; n < 4; n++ {\n\t\t\t\t\tp.Ping(rep)\n\t\t\t\t\tprintln(<-rep)\n\t\t\t\t}\n\t\t\t\tnxt <- struct{}{}\n\t\t\tcase subReq[1] == \"ping\" && cPName == \"telia\":\n\t\t\t\tproviders[cPName].Init(subReq[2], \"ipv4\")\n\t\t\t\tm, _ := providers[cPName].Ping()\n\t\t\t\tprintln(m)\n\t\t\t\tnxt <- struct{}{}\n\t\t\tcase subReq[1] == \"connect\":\n\t\t\t\tvar pName string\n\t\t\t\tif pName, err = validateProvider(subReq[2]); err != nil {\n\t\t\t\t\tprintln(\"provider not available\")\n\t\t\t\t\tnxt <- struct{}{}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcPName = pName\n\t\t\t\tc.SetPrompt(cPName + \"\/\" + providers[cPName].GetDefaultNode())\n\t\t\t\tnxt <- struct{}{}\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>fixed case extrnal ping logic<commit_after>package main\n\nimport (\n\t\"github.com\/mehrdadrad\/myping\/cli\"\n\t\"github.com\/mehrdadrad\/myping\/icmp\"\n\t\"github.com\/mehrdadrad\/myping\/icmp\/telia\"\n\t\"net\"\n\t\"regexp\"\n\t\"strings\"\n)\n\ntype Provider interface {\n\tInit(host, version string)\n\tGetDefaultNode() string\n\tGetNodes() map[string]string\n\tPing() (string, error)\n}\n\nvar providers = map[string]Provider{\"telia\": new(telia.Provider)}\n\nfunc validateProvider(p string) (string, error) {\n\tp = strings.ToLower(p)\n\treturn p, nil\n}\n\nfunc main() {\n\tvar (\n\t\terr    error\n\t\tcPName string = \"local\"\n\t)\n\n\trep := make(chan string, 1)\n\tcmd := make(chan string, 1)\n\tnxt := make(chan struct{}, 1)\n\n\tc := cli.Init(\"local\")\n\tgo c.Run(cmd, nxt)\n\n\tr, _ := regexp.Compile(\"(ping|connect) (.*)\")\n\n\tfor {\n\t\tselect {\n\t\tcase req := <-cmd:\n\t\t\tsubReq := r.FindStringSubmatch(req)\n\t\t\tif len(subReq) == 0 {\n\t\t\t\tprintln(\"syntax error\")\n\t\t\t\tnxt <- struct{}{}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase subReq[1] == \"ping\" && cPName == \"local\":\n\t\t\t\tp := icmp.NewPing()\n\t\t\t\tra, err := net.ResolveIPAddr(\"ip\", subReq[2])\n\t\t\t\tif err != nil {\n\t\t\t\t\tprintln(\"cannot resolve\", subReq[2], \": Unknown host\")\n\t\t\t\t\tnxt <- struct{}{}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tp.IP(ra.String())\n\t\t\t\tfor n := 0; n < 4; n++ {\n\t\t\t\t\tp.Ping(rep)\n\t\t\t\t\tprintln(<-rep)\n\t\t\t\t}\n\t\t\t\tnxt <- struct{}{}\n\t\t\tcase subReq[1] == \"ping\":\n\t\t\t\tproviders[cPName].Init(subReq[2], \"ipv4\")\n\t\t\t\tm, _ := providers[cPName].Ping()\n\t\t\t\tprintln(m)\n\t\t\t\tnxt <- struct{}{}\n\t\t\tcase subReq[1] == \"connect\":\n\t\t\t\tvar pName string\n\t\t\t\tif pName, err = validateProvider(subReq[2]); err != nil {\n\t\t\t\t\tprintln(\"provider not available\")\n\t\t\t\t\tnxt <- struct{}{}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcPName = pName\n\t\t\t\tc.SetPrompt(cPName + \"\/\" + providers[cPName].GetDefaultNode())\n\t\t\t\tnxt <- struct{}{}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ TODO: libraries should not use log.Fatal\n\/\/ TODO: ... perhaps not log.Printf either.\n\npackage doozerconfig\n\nimport (\n\t\"reflect\"\n\t\"github.com\/ActiveState\/doozer\"\n\t\"encoding\/json\"\n\t\"errors\" \/\/ TODO: create custom errors\n\t\"log\"\n)\n\ntype DoozerConfig struct {\n\tconn        *doozer.Conn\n\tconfigStruct interface{}\n\tprefix       string\n\tfields       map[string]reflect.Value\n}\n\nfunc New(conn *doozer.Conn, configStruct interface{}, prefix string) *DoozerConfig{\n\treturn &DoozerConfig{conn, configStruct, prefix, make(map[string]reflect.Value)}\n}\n\n\/\/ initialize the config data by loading from doozer.\n\/\/ will return error if any of the config is not found\nfunc (c *DoozerConfig) Load() error {\n\telem := reflect.ValueOf(c.configStruct).Elem()\n\telemType := elem.Type()\n\tfor i := 0; i < elem.NumField(); i++ {\n\t\tfield := elem.Field(i)\n\t\tfieldType := elemType.Field(i)\n\n\t\t\/\/ read json-encoded bytes from doozer\n\t\tpath := fieldType.Tag.Get(\"doozer\")\n\t\tif path == \"\" {\n\t\t\t\/\/ this field is not supposed to be loaded from doozer\n\t\t\tcontinue\n\t\t}\n\t\tpath = c.prefix + path\n\t\tdata, _, err := c.conn.Get(path, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.fields[path] = field\n\t\t\n\t\t\/\/ extract the value based on the field type\n\t\terr = setFieldWithData(field, data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (c *DoozerConfig) Monitor(glob string, rev int64) {\n\tfor evt := range doozerWatch(c.conn, glob, rev) {\n\t\tif field, ok := c.fields[evt.Path]; ok {\n\t\t\terr := setFieldWithData(field, evt.Body)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tlog.Printf(\"New Config: %+v\\n\", c.configStruct)\n\t\t}\n\t}\n}\n\n\n\/\/ set this struct field with data json-decoded as the same tyhpe\nfunc setFieldWithData(field reflect.Value, data []byte) error {\n\t\/\/ TODO: simplify this using interface{}\n\tswitch(field.Kind()){\n\tcase reflect.Int:\n\t\tvar val int64\n\t\tjson.Unmarshal(data, &val)\n\t\tfield.SetInt(val)\n\tcase reflect.String:\n\t\tvar val string\n\t\tjson.Unmarshal(data, &val)\n\t\tfield.SetString(val)\n\tdefault:\n\t\treturn errors.New(\"doozerconfig: unsupported field \" + string(field.Kind()))\n\t}\n\treturn nil\n}\n\n\n\/\/ monitor mutations on the given glob of keys and report them in the\n\/\/ returned channel\nfunc doozerWatch(c *doozer.Conn, glob string, rev int64) chan doozer.Event {\n\tch := make(chan doozer.Event)\n\tgo func() {\n\t\tfor {\n\t\t\tevt, err := c.Wait(glob, rev)\n\t\t\tif err != nil {\n\t\t\t\tclose(ch)\n\t\t\t\t\/\/ FIXME: on doozer watch errors, the entire basin process\n\t\t\t\t\/\/ must not go down. figure a way to report the error in\n\t\t\t\t\/\/ console and silently proceed.\n\t\t\t\tlog.Fatal(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trev = evt.Rev + 1\n\t\t\tch <- evt\n\t\t}\n\t}()\n\treturn ch\n}\n\n<commit_msg>doozerconfig: simplify setFieldWithData using reflection<commit_after>\/\/ TODO: libraries should not use log.Fatal\n\/\/ TODO: ... perhaps not log.Printf either.\n\npackage doozerconfig\n\nimport (\n\t\"reflect\"\n\t\"github.com\/ActiveState\/doozer\"\n\t\"encoding\/json\"\n\t\"log\"\n)\n\ntype DoozerConfig struct {\n\tconn        *doozer.Conn\n\tconfigStruct interface{}\n\tprefix       string\n\tfields       map[string]reflect.Value\n}\n\nfunc New(conn *doozer.Conn, configStruct interface{}, prefix string) *DoozerConfig{\n\treturn &DoozerConfig{conn, configStruct, prefix, make(map[string]reflect.Value)}\n}\n\n\/\/ initialize the config data by loading from doozer.\n\/\/ will return error if any of the config is not found\nfunc (c *DoozerConfig) Load() error {\n\telem := reflect.ValueOf(c.configStruct).Elem()\n\telemType := elem.Type()\n\tfor i := 0; i < elem.NumField(); i++ {\n\t\tfield := elem.Field(i)\n\t\tfieldType := elemType.Field(i)\n\n\t\t\/\/ read json-encoded bytes from doozer\n\t\tpath := fieldType.Tag.Get(\"doozer\")\n\t\tif path == \"\" {\n\t\t\t\/\/ this field is not supposed to be loaded from doozer\n\t\t\tcontinue\n\t\t}\n\t\tpath = c.prefix + path\n\t\tdata, _, err := c.conn.Get(path, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.fields[path] = field\n\t\t\n\t\t\/\/ extract the value based on the field type\n\t\terr = unmarshalIntoValue(data, field)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\nfunc (c *DoozerConfig) Monitor(glob string, rev int64) error {\n\tfor evt := range doozerWatch(c.conn, glob, rev) {\n\t\tif field, ok := c.fields[evt.Path]; ok {\n\t\t\terr := unmarshalIntoValue(evt.Body, field)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.Printf(\"New Config: %+v\\n\", c.configStruct)\n\t\t}\n\t}\n\treturn nil\n}\n\n\n\/\/ a version of json.Unmarshal that unmarshalls into a reflect.Value type\nfunc unmarshalIntoValue(data []byte, field reflect.Value) error {\n\tfieldInterface := field.Addr().Interface()\n\treturn json.Unmarshal(data, &fieldInterface)\n}\n\n\n\/\/ monitor mutations on the given glob of keys and report them in the\n\/\/ returned channel\nfunc doozerWatch(c *doozer.Conn, glob string, rev int64) chan doozer.Event {\n\tch := make(chan doozer.Event)\n\tgo func() {\n\t\tfor {\n\t\t\tevt, err := c.Wait(glob, rev)\n\t\t\tif err != nil {\n\t\t\t\tclose(ch)\n\t\t\t\t\/\/ FIXME: on doozer watch errors, the entire basin process\n\t\t\t\t\/\/ must not go down. figure a way to report the error in\n\t\t\t\t\/\/ console and silently proceed.\n\t\t\t\t\/\/ besides, it is not the library's job to crash a program.\n\t\t\t\tlog.Fatal(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trev = evt.Rev + 1\n\t\t\tch <- evt\n\t\t}\n\t}()\n\treturn ch\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package http\n\nimport (\n\t\"net\/http\"\n\t\"golib\/utils\"\n\t\"strings\"\n\t\"fmt\"\n)\n\n\nvar (\n\n)\n\ntype Handler interface {\n\thandler(url string) bool\n}\n\ntype handleFuncMap struct {\n\tsimple map[string]restHandlerFunc\n\trest *restHandlerMap\n}\n\nfunc (this handleFuncMap) getHandler(req *http.Request) (http.HandlerFunc,error)  {\n\tvar err error\n\turl := req.URL.Path\n\tmethod := req.Method\n\trest,ok:=this.simple[url]\n\tif ok {\n\t\tif rest.matchMethod(method) {\n\t\t\treturn rest.function,nil\n\t\t}else {\n\t\t\terr = fmt.Errorf(\"url:%s;method not match:methodStr is %s but %s\",url,rest.methodStr,method)\n\t\t}\n\t}\n\trestHandler,urlValues := this.rest.getHandler(url)\n\tif restHandler != nil {\n\t\tif restHandler.matchMethod(method){\n\t\t\tfor k,v:=range urlValues{\n\t\t\t\treq.Form.Add(k,v)\n\t\t\t}\n\t\t\treturn restHandler.function,nil\n\t\t}\n\t}\n\terr = fmt.Errorf(\"url:%s;not found macth url\",url)\n\treturn nil,err\n}\n\ntype restHandlerFunc struct {\n\tmethodStr string\n\tfunction http.HandlerFunc\n}\n\nfunc (this restHandlerFunc) matchMethod(method string) bool{\n\tif this.methodStr == \"\" || this.methodStr == \"*\" {\n\t\treturn true\n\t}\n\treturn strings.Index(this.methodStr, method) >= 0\n}\n\n\ntype restHandlerMap struct {\n\turls map[int][]urlInfo\n}\n\nfunc (this restHandlerMap) getHandler(url string) (restHandlerFunc,map[string]string) {\n\turlParaLen := len(utils.Split(url,\"\/\"))\n\turlInfos,ok := this.urls[urlParaLen]\n\tif ok {\n\t\tfor _,v := range urlInfos {\n\t\t\thandler,urlPara,err := v.match(url)\n\t\t\tif err != nil{\n\t\t\t\tcontinue\n\t\t\t}else{\n\t\t\t\treturn handler,urlPara\n\t\t\t}\n\t\t}\n\t}\n\treturn nil,nil\n}\n\nfunc (this Handler) ServeHTTP(res http.ResponseWriter, req *http.Request)  {\n\turl := req.URL.Path\n\turlParas := utils.Split(url , \"\/\")\n\turlLenGroup := urls[len(urlParas)]\n\n}\n\ntype urlMacthPara struct {\n\turlPara string\n\tmatchInfo string\n}\n\nfunc (this urlMacthPara) macth(para string) (bool,string) {\n\tswitch this.matchInfo {\n\tcase \"*\":\n\t\treturn true,\"*\"\n\tcase \"{}\":\n\t\treturn true,para\n\tcase \"\":\n\t\treturn this.urlPara == para , \"\"\n\tdefault:\n\t\treturn this.urlPara == para , \"\"\n\t}\n}\n\ntype urlInfo struct {\n\turlParas []urlMacthPara\n\thandler restHandlerFunc\n}\n\nfunc (this urlInfo) addUrlPara(para string)  {\n\tthis.urls = append(this.urls , para)\n}\n\nfunc (this urlInfo) addUrlMatchPara(para string)  {\n\tmatchIndex := len(this.urls)\n\tthis.matchIndex = append(this.matchIndex , matchIndex)\n\tthis.urls = append(this.urls , para)\n}\n\nfunc (this urlInfo) len() int  {\n\treturn len(this.urls)\n}\n\nfunc (this urlInfo) match(url string) (http.HandlerFunc,map[string]string,error) {\n\tvar urlParavalueMap map[string]string\n\turlParas := utils.Split(url,\"\/\")\n\tfor i , _ := range urlParas {\n\t\tshould := this.urlParas[i]\n\t\treal := urlParas[i]\n\t\tif macth,res:=should.macth(real);macth{\n\t\t\tswitch res {\n\t\t\tcase \"*\":\n\t\t\t\turlParavalueMap[\"*\"]=strings.Join(urlParas[i:],\"\/\")\n\t\t\t\treturn this.handler,urlParavalueMap,nil\n\t\t\tcase \"{}\":\n\t\t\t\turlParavalueMap[should.urlPara] = real\n\t\t\tdefault :\n\n\t\t\t}\n\t\t}else {\n\t\t\treturn nil,nil,fmt.Errorf(\"not macth\")\n\t\t}\n\t}\n\treturn this.handler,urlParavalueMap,nil\n}\n\nfunc AddHandlerFunc(url string, handler http.HandlerFunc){\n\tparas := utils.Split(url,\"\/\")\n\tfor _,v := range paras{\n\t\turlinfo := urlInfo{}\n\t\tpara := strings.TrimSpace(v)\n\t\tif para[0] == '{' && para[len(para) - 1] == '}' {\n\t\t\turlinfo.addUrlMatchPara(para[1:len(para)])\n\t\t}else if para == '*' {\n\t\t\turlinfo.addUrlMatchPara(para)\n\t\t}else {\n\t\t\turlinfo.addUrlPara(para)\n\t\t\tsimpleUrls[url] = handler\n\t\t\treturn\n\t\t}\n\t\turlinfo.handler = handler\n\t\tlen := urlinfo.len()\n\t\turls[len] = append(urls[len],urlinfo)\n\t}\n}<commit_msg>添加实现思路,还未完成<commit_after>package http\n\n\/*\n现实思路:\n    分为三种类型url\n\t1.普通的:如\/fff\/ddd\/lll\n\t2.有映射值的:如\/user\/{who}\/info\n\t3.尾部全部匹配的:如\/user\/*('*'只可以用于尾部)\n    先进行分组,将普通的于要进行取值的分开\n    普通的对于一个map,直接使用map[string]获取handlerFunc\n    要取值得将url利用\"\/\"切分成数组,匹配是再将实际url切分成数组进行比对并取值\n\n *\/\n\nimport (\n\t\"net\/http\"\n\t\"golib\/utils\"\n\t\"strings\"\n\t\"fmt\"\n)\n\n\nvar (\n\thandler handleFuncMap\n)\n\ntype Handler interface {\n\thandler(url string) bool\n}\n\ntype handleFuncMap struct {\n\tsimple map[string]restHandlerFunc\n\trest *restHandlerMap\n}\n\nfunc (this handleFuncMap) getHandler(req *http.Request) (http.HandlerFunc,error)  {\n\tvar err error\n\turl := req.URL.Path\n\tmethod := req.Method\n\trest,ok:=this.simple[url]\n\tif ok {\n\t\tif rest.matchMethod(method) {\n\t\t\treturn rest.function,nil\n\t\t}else {\n\t\t\terr = fmt.Errorf(\"url:%s;method not match:methodStr is %s but %s\",url,rest.methodStr,method)\n\t\t}\n\t}\n\trestHandler,urlValues := this.rest.getHandler(url)\n\tif restHandler != nil {\n\t\tif restHandler.matchMethod(method){\n\t\t\tfor k,v:=range urlValues{\n\t\t\t\treq.Form.Add(k,v)\n\t\t\t}\n\t\t\treturn restHandler.function,nil\n\t\t}\n\t}\n\terr = fmt.Errorf(\"url:%s;not found macth url\",url)\n\treturn nil,err\n}\n\ntype restHandlerFunc struct {\n\tmethodStr string\n\tfunction http.HandlerFunc\n}\n\nfunc (this restHandlerFunc) matchMethod(method string) bool{\n\tif this.methodStr == \"\" || this.methodStr == \"*\" {\n\t\treturn true\n\t}\n\treturn strings.Index(this.methodStr, method) >= 0\n}\n\n\ntype restHandlerMap struct {\n\turls map[int][]urlInfo\n}\n\nfunc (this restHandlerMap) getHandler(url string) (restHandlerFunc,map[string]string) {\n\turlParaLen := len(utils.Split(url,\"\/\"))\n\turlInfos,ok := this.urls[urlParaLen]\n\tif ok {\n\t\tfor _,v := range urlInfos {\n\t\t\thandler,urlPara,err := v.match(url)\n\t\t\tif err != nil{\n\t\t\t\tcontinue\n\t\t\t}else{\n\t\t\t\treturn handler,urlPara\n\t\t\t}\n\t\t}\n\t}\n\treturn nil,nil\n}\n\nfunc (this Handler) ServeHTTP(res http.ResponseWriter, req *http.Request)  {\n\turl := req.URL.Path\n\turlParas := utils.Split(url , \"\/\")\n\turlLenGroup := urls[len(urlParas)]\n\n}\n\ntype urlMacthPara struct {\n\turlPara string\n\tmatchInfo string\n}\n\nfunc (this urlMacthPara) macth(para string) (bool,string) {\n\tswitch this.matchInfo {\n\tcase \"*\":\n\t\treturn true,\"*\"\n\tcase \"{}\":\n\t\treturn true,para\n\tcase \"\":\n\t\treturn this.urlPara == para , \"\"\n\tdefault:\n\t\treturn this.urlPara == para , \"\"\n\t}\n}\n\ntype urlInfo struct {\n\turlParas []urlMacthPara\n\thandler restHandlerFunc\n}\n\nfunc (this urlInfo) addUrlPara(para string)  {\n\tthis.urls = append(this.urls , para)\n}\n\nfunc (this urlInfo) addUrlMatchPara(para string)  {\n\tmatchIndex := len(this.urls)\n\tthis.matchIndex = append(this.matchIndex , matchIndex)\n\tthis.urls = append(this.urls , para)\n}\n\nfunc (this urlInfo) len() int  {\n\treturn len(this.urls)\n}\n\nfunc (this urlInfo) match(url string) (http.HandlerFunc,map[string]string,error) {\n\tvar urlParavalueMap map[string]string\n\turlParas := utils.Split(url,\"\/\")\n\tfor i , _ := range urlParas {\n\t\tshould := this.urlParas[i]\n\t\treal := urlParas[i]\n\t\tif macth,res:=should.macth(real);macth{\n\t\t\tswitch res {\n\t\t\tcase \"*\":\n\t\t\t\turlParavalueMap[\"*\"]=strings.Join(urlParas[i:],\"\/\")\n\t\t\t\treturn this.handler,urlParavalueMap,nil\n\t\t\tcase \"{}\":\n\t\t\t\turlParavalueMap[should.urlPara] = real\n\t\t\tdefault :\n\n\t\t\t}\n\t\t}else {\n\t\t\treturn nil,nil,fmt.Errorf(\"not macth\")\n\t\t}\n\t}\n\treturn this.handler,urlParavalueMap,nil\n}\n\nfunc AddHandlerFunc(url string, handler http.HandlerFunc){\n\tparas := utils.Split(url,\"\/\")\n\tfor _,v := range paras{\n\t\turlinfo := urlInfo{}\n\t\tpara := strings.TrimSpace(v)\n\t\tif para[0] == '{' && para[len(para) - 1] == '}' {\n\t\t\turlinfo.addUrlMatchPara(para[1:len(para)])\n\t\t}else if para == '*' {\n\t\t\turlinfo.addUrlMatchPara(para)\n\t\t}else {\n\t\t\turlinfo.addUrlPara(para)\n\t\t\tsimpleUrls[url] = handler\n\t\t\treturn\n\t\t}\n\t\turlinfo.handler = handler\n\t\tlen := urlinfo.len()\n\t\turls[len] = append(urls[len],urlinfo)\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>package sudokustate\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/jkomoros\/sudoku\"\n)\n\ntype digest struct {\n\tPuzzle string\n\tMoves  []digestMove\n}\n\ntype digestMove struct {\n\tType   string\n\tCell   sudoku.CellRef\n\tMarks  map[int]bool\n\tTime   int\n\tNumber *int\n\tGroup  groupInfo\n}\n\n\/\/TODO: implement model.LoadDigest([]byte)\n\n\/\/Digest returns a []byte with the JSON that represents this model.\nfunc (m *Model) Digest() []byte {\n\tobj := m.makeDigest()\n\n\tresult, err := json.MarshalIndent(obj, \"\", \"  \")\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn result\n}\n\nfunc (m *Model) makeDigest() digest {\n\t\/\/TODO: test this\n\treturn digest{\n\t\tPuzzle: m.snapshot,\n\t\tMoves:  m.makeMovesDigest(),\n\t}\n}\n\nfunc (m *Model) makeMovesDigest() []digestMove {\n\tvar result []digestMove\n\n\t\/\/Move command cursor to the very first item in the linked list.\n\tcurrentCommand := m.commands\n\tif currentCommand == nil {\n\t\treturn nil\n\t}\n\tfor currentCommand.prev != nil {\n\t\tcurrentCommand = currentCommand.prev\n\t}\n\n\tfor currentCommand != nil {\n\n\t\tcommand := currentCommand.c\n\n\t\tgroupInfoPtr := command.GroupInfo()\n\n\t\tvar info groupInfo\n\n\t\tif groupInfoPtr == nil {\n\t\t\tinfo = groupInfo{}\n\t\t} else {\n\t\t\tinfo = *groupInfoPtr\n\t\t}\n\n\t\tfor _, subCommand := range command.SubCommands() {\n\t\t\tresult = append(result, digestMove{\n\t\t\t\tType: subCommand.Type(),\n\t\t\t\t\/\/TODO: this is a hack, we just happen to know that there's only one item\n\t\t\t\tCell:   subCommand.ModifiedCells(m)[0],\n\t\t\t\tGroup:  info,\n\t\t\t\tMarks:  subCommand.Marks(),\n\t\t\t\tNumber: subCommand.Number(),\n\t\t\t})\n\t\t}\n\n\t\tcurrentCommand = currentCommand.next\n\t}\n\n\treturn result\n}\n<commit_msg>Made it so group info is null if not in a group<commit_after>package sudokustate\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/jkomoros\/sudoku\"\n)\n\ntype digest struct {\n\tPuzzle string\n\tMoves  []digestMove\n}\n\ntype digestMove struct {\n\tType   string\n\tCell   sudoku.CellRef\n\tMarks  map[int]bool\n\tTime   int\n\tNumber *int\n\tGroup  *groupInfo\n}\n\n\/\/TODO: implement model.LoadDigest([]byte)\n\n\/\/Digest returns a []byte with the JSON that represents this model.\nfunc (m *Model) Digest() []byte {\n\tobj := m.makeDigest()\n\n\tresult, err := json.MarshalIndent(obj, \"\", \"  \")\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn result\n}\n\nfunc (m *Model) makeDigest() digest {\n\t\/\/TODO: test this\n\treturn digest{\n\t\tPuzzle: m.snapshot,\n\t\tMoves:  m.makeMovesDigest(),\n\t}\n}\n\nfunc (m *Model) makeMovesDigest() []digestMove {\n\tvar result []digestMove\n\n\t\/\/Move command cursor to the very first item in the linked list.\n\tcurrentCommand := m.commands\n\tif currentCommand == nil {\n\t\treturn nil\n\t}\n\tfor currentCommand.prev != nil {\n\t\tcurrentCommand = currentCommand.prev\n\t}\n\n\tfor currentCommand != nil {\n\n\t\tcommand := currentCommand.c\n\n\t\tfor _, subCommand := range command.SubCommands() {\n\t\t\tresult = append(result, digestMove{\n\t\t\t\tType: subCommand.Type(),\n\t\t\t\t\/\/TODO: this is a hack, we just happen to know that there's only one item\n\t\t\t\tCell:   subCommand.ModifiedCells(m)[0],\n\t\t\t\tGroup:  command.GroupInfo(),\n\t\t\t\tMarks:  subCommand.Marks(),\n\t\t\t\tNumber: subCommand.Number(),\n\t\t\t})\n\t\t}\n\n\t\tcurrentCommand = currentCommand.next\n\t}\n\n\treturn result\n}\n<|endoftext|>"}
{"text":"<commit_before>package randombytes\n\n\/\/ #cgo pkg-config: libsodium\n\/\/ #include <stdlib.h>\n\/\/ #include <sodium.h>\nimport \"C\"\nimport \"github.com\/GoKillers\/libsodium-go\/support\"\nimport \"unsafe\"\n\nfunc RandomBytesSeedBytes() int {\n\treturn int(C.randombytes_seedbytes())\n}\n\nfunc RandomBytes(size int) []byte {\n\tbuf := make([]byte, size)\n\tRandomBytesBuf(buf)\n\treturn buf\n}\n\nfunc RandomBytesBuf(buf []byte) {\n\tif len(buf) > 0 {\n\t\tC.randombytes_buf(unsafe.Pointer(&buf[0]), C.size_t(len(buf)))\n\t}\n}\n\nfunc RandomBytesBufDeterministic(buf []byte, seed []byte) {\n\tsupport.CheckSize(seed, RandomBytesSeedBytes(), \"seed\")\n\tif len(buf) > 0 {\n\t\tC.randombytes_buf_deterministic(\n\t\t\tunsafe.Pointer(&buf[0]),\n\t\t\tC.size_t(len(buf)),\n\t\t\t(*C.uchar)(&seed[0]))\n\t}\n}\n\nfunc RandomBytesRandom() uint32 {\n\treturn uint32(C.randombytes_random())\n}\n\nfunc RandomBytesUniform(upperBound uint32) uint32 {\n\treturn uint32(C.randombytes_uniform(C.uint32_t(upperBound)))\n}\n\nfunc RandomBytesStir() {\n\tC.randombytes_stir()\n}\n\nfunc RandomBytesClose() {\n\tC.randombytes_close()\n}\n\nfunc RandomBytesSetImplementation(impl *C.struct_randombytes_implementation) int {\n\treturn int(C.randombytes_set_implementation(impl))\n}\n\nfunc RandomBytesImplementationName() string {\n\treturn C.GoString(C.randombytes_implementation_name())\n}\n\n\/\/ From randombytes_salsa20_random.h\nvar RandomBytesSalsa20Implementation *C.struct_randombytes_implementation = &C.randombytes_salsa20_implementation\n\n\/\/ From randombytes_sysrandom.h\nvar RandomBytesSysRandomImplementation *C.struct_randombytes_implementation = &C.randombytes_sysrandom_implementation\n<commit_msg>Add comments to randombytes<commit_after>package randombytes\n\n\/\/ #cgo pkg-config: libsodium\n\/\/ #include <stdlib.h>\n\/\/ #include <sodium.h>\nimport \"C\"\nimport \"github.com\/GoKillers\/libsodium-go\/support\"\nimport \"unsafe\"\n\n\/\/ RandomBytesSeedBytes returns the number of bytes required\n\/\/ for seeding RandomBytesBufDeterministic.\nfunc RandomBytesSeedBytes() int {\n\treturn int(C.randombytes_seedbytes())\n}\n\n\/\/ RandomBytes returns a specified number of random bytes.\n\/\/ It is essentially a wrapper around RandomBytesBuf for convenience.\n\/\/ Note that this behaviour is different than in NaCl and libsodium,\n\/\/ where this function behaves the same as RandomBytesBuf.\nfunc RandomBytes(size int) []byte {\n\tbuf := make([]byte, size)\n\tRandomBytesBuf(buf)\n\treturn buf\n}\n\n\/\/ RandomBytesBuf fills a buffer with random bytes.\nfunc RandomBytesBuf(buf []byte) {\n\tif len(buf) > 0 {\n\t\tC.randombytes_buf(unsafe.Pointer(&buf[0]), C.size_t(len(buf)))\n\t}\n}\n\n\/\/ RandomBytesBufDeterministic fills a buffer with bytes that are\n\/\/ indistinguishable from random bytes without knowing seed.\nfunc RandomBytesBufDeterministic(buf []byte, seed []byte) {\n\tsupport.CheckSize(seed, RandomBytesSeedBytes(), \"seed\")\n\tif len(buf) > 0 {\n\t\tC.randombytes_buf_deterministic(\n\t\t\tunsafe.Pointer(&buf[0]),\n\t\t\tC.size_t(len(buf)),\n\t\t\t(*C.uchar)(&seed[0]))\n\t}\n}\n\n\/\/ RandomBytesRandom returns a random 32 bit unsigned integer.\nfunc RandomBytesRandom() uint32 {\n\treturn uint32(C.randombytes_random())\n}\n\n\/\/ RandomBytesUniform returns a random number between 0 and an upper bound.\n\/\/ The generated bytes have a uniform distribution between 0 and the upper bound.\nfunc RandomBytesUniform(upperBound uint32) uint32 {\n\treturn uint32(C.randombytes_uniform(C.uint32_t(upperBound)))\n}\n\n\/\/ RandomBytesStir reseeds the random number generator.\nfunc RandomBytesStir() {\n\tC.randombytes_stir()\n}\n\n\/\/ RandomBytesClose deallocates the resources used by the random number generator.\nfunc RandomBytesClose() {\n\tC.randombytes_close()\n}\n\n\/\/ RandomBytesSetImplementation sets the implementation of the random number generator.\nfunc RandomBytesSetImplementation(impl *C.struct_randombytes_implementation) int {\n\treturn int(C.randombytes_set_implementation(impl))\n}\n\n\/\/ RandomBytesImplementationName returns the name of the random number\n\/\/ generator that is being used.\nfunc RandomBytesImplementationName() string {\n\treturn C.GoString(C.randombytes_implementation_name())\n}\n\n\/\/ RandomBytesSalsa20Implementation contains a pointer to C.randombytes_salsa20_implementation\n\/\/ This means that it can be used as an argument to RandomBytesSetImplementation\nvar RandomBytesSalsa20Implementation *C.struct_randombytes_implementation = &C.randombytes_salsa20_implementation\n\n\/\/ RandomBytesSysRandomImplementation contains a pointer to C.randombytes_sysrandom_implementation\n\/\/ This means that it can be used as an argument to RandomBytesSetImplementation\nvar RandomBytesSysRandomImplementation *C.struct_randombytes_implementation = &C.randombytes_sysrandom_implementation\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"fmt\"\n\t\"mime\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/docker\/docker\/pkg\/system\"\n\t\"github.com\/docker\/engine-api\/types\"\n\t\"github.com\/docker\/libtrust\"\n)\n\n\/\/ Common constants for daemon and client.\nconst (\n\t\/\/ Version of Current REST API\n\tDefaultVersion string = \"1.25\"\n\n\t\/\/ MinVersion represents Minimum REST API version supported\n\tMinVersion string = \"1.12\"\n\n\t\/\/ NoBaseImageSpecifier is the symbol used by the FROM\n\t\/\/ command to specify that no base image is to be used.\n\tNoBaseImageSpecifier string = \"scratch\"\n)\n\n\/\/ byPortInfo is a temporary type used to sort types.Port by its fields\ntype byPortInfo []types.Port\n\nfunc (r byPortInfo) Len() int      { return len(r) }\nfunc (r byPortInfo) Swap(i, j int) { r[i], r[j] = r[j], r[i] }\nfunc (r byPortInfo) Less(i, j int) bool {\n\tif r[i].PrivatePort != r[j].PrivatePort {\n\t\treturn r[i].PrivatePort < r[j].PrivatePort\n\t}\n\n\tif r[i].IP != r[j].IP {\n\t\treturn r[i].IP < r[j].IP\n\t}\n\n\tif r[i].PublicPort != r[j].PublicPort {\n\t\treturn r[i].PublicPort < r[j].PublicPort\n\t}\n\n\treturn r[i].Type < r[j].Type\n}\n\n\/\/ DisplayablePorts returns formatted string representing open ports of container\n\/\/ e.g. \"0.0.0.0:80->9090\/tcp, 9988\/tcp\"\n\/\/ it's used by command 'docker ps'\nfunc DisplayablePorts(ports []types.Port) string {\n\ttype portGroup struct {\n\t\tfirst int\n\t\tlast  int\n\t}\n\tgroupMap := make(map[string]*portGroup)\n\tvar result []string\n\tvar hostMappings []string\n\tvar groupMapKeys []string\n\tsort.Sort(byPortInfo(ports))\n\tfor _, port := range ports {\n\t\tcurrent := port.PrivatePort\n\t\tportKey := port.Type\n\t\tif port.IP != \"\" {\n\t\t\tif port.PublicPort != current {\n\t\t\t\thostMappings = append(hostMappings, fmt.Sprintf(\"%s:%d->%d\/%s\", port.IP, port.PublicPort, port.PrivatePort, port.Type))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tportKey = fmt.Sprintf(\"%s\/%s\", port.IP, port.Type)\n\t\t}\n\t\tgroup := groupMap[portKey]\n\n\t\tif group == nil {\n\t\t\tgroupMap[portKey] = &portGroup{first: current, last: current}\n\t\t\t\/\/ record order that groupMap keys are created\n\t\t\tgroupMapKeys = append(groupMapKeys, portKey)\n\t\t\tcontinue\n\t\t}\n\t\tif current == (group.last + 1) {\n\t\t\tgroup.last = current\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = append(result, formGroup(portKey, group.first, group.last))\n\t\tgroupMap[portKey] = &portGroup{first: current, last: current}\n\t}\n\tfor _, portKey := range groupMapKeys {\n\t\tg := groupMap[portKey]\n\t\tresult = append(result, formGroup(portKey, g.first, g.last))\n\t}\n\tresult = append(result, hostMappings...)\n\treturn strings.Join(result, \", \")\n}\n\nfunc formGroup(key string, start, last int) string {\n\tparts := strings.Split(key, \"\/\")\n\tgroupType := parts[0]\n\tvar ip string\n\tif len(parts) > 1 {\n\t\tip = parts[0]\n\t\tgroupType = parts[1]\n\t}\n\tgroup := strconv.Itoa(start)\n\tif start != last {\n\t\tgroup = fmt.Sprintf(\"%s-%d\", group, last)\n\t}\n\tif ip != \"\" {\n\t\tgroup = fmt.Sprintf(\"%s:%s->%s\", ip, group, group)\n\t}\n\treturn fmt.Sprintf(\"%s\/%s\", group, groupType)\n}\n\n\/\/ MatchesContentType validates the content type against the expected one\nfunc MatchesContentType(contentType, expectedType string) bool {\n\tmimetype, _, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Error parsing media type: %s error: %v\", contentType, err)\n\t}\n\treturn err == nil && mimetype == expectedType\n}\n\n\/\/ LoadOrCreateTrustKey attempts to load the libtrust key at the given path,\n\/\/ otherwise generates a new one\nfunc LoadOrCreateTrustKey(trustKeyPath string) (libtrust.PrivateKey, error) {\n\terr := system.MkdirAll(filepath.Dir(trustKeyPath), 0700)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttrustKey, err := libtrust.LoadKeyFile(trustKeyPath)\n\tif err == libtrust.ErrKeyFileDoesNotExist {\n\t\ttrustKey, err = libtrust.GenerateECP256PrivateKey()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error generating key: %s\", err)\n\t\t}\n\t\tif err := libtrust.SaveKey(trustKeyPath, trustKey); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error saving key file: %s\", err)\n\t\t}\n\t} else if err != nil {\n\t\treturn nil, fmt.Errorf(\"Error loading key file %s: %s\", trustKeyPath, err)\n\t}\n\treturn trustKey, nil\n}\n<commit_msg>Atomically save libtrust key file<commit_after>package api\n\nimport (\n\t\"encoding\/json\"\n\t\"encoding\/pem\"\n\t\"fmt\"\n\t\"mime\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/docker\/docker\/pkg\/ioutils\"\n\t\"github.com\/docker\/docker\/pkg\/system\"\n\t\"github.com\/docker\/engine-api\/types\"\n\t\"github.com\/docker\/libtrust\"\n)\n\n\/\/ Common constants for daemon and client.\nconst (\n\t\/\/ Version of Current REST API\n\tDefaultVersion string = \"1.25\"\n\n\t\/\/ MinVersion represents Minimum REST API version supported\n\tMinVersion string = \"1.12\"\n\n\t\/\/ NoBaseImageSpecifier is the symbol used by the FROM\n\t\/\/ command to specify that no base image is to be used.\n\tNoBaseImageSpecifier string = \"scratch\"\n)\n\n\/\/ byPortInfo is a temporary type used to sort types.Port by its fields\ntype byPortInfo []types.Port\n\nfunc (r byPortInfo) Len() int      { return len(r) }\nfunc (r byPortInfo) Swap(i, j int) { r[i], r[j] = r[j], r[i] }\nfunc (r byPortInfo) Less(i, j int) bool {\n\tif r[i].PrivatePort != r[j].PrivatePort {\n\t\treturn r[i].PrivatePort < r[j].PrivatePort\n\t}\n\n\tif r[i].IP != r[j].IP {\n\t\treturn r[i].IP < r[j].IP\n\t}\n\n\tif r[i].PublicPort != r[j].PublicPort {\n\t\treturn r[i].PublicPort < r[j].PublicPort\n\t}\n\n\treturn r[i].Type < r[j].Type\n}\n\n\/\/ DisplayablePorts returns formatted string representing open ports of container\n\/\/ e.g. \"0.0.0.0:80->9090\/tcp, 9988\/tcp\"\n\/\/ it's used by command 'docker ps'\nfunc DisplayablePorts(ports []types.Port) string {\n\ttype portGroup struct {\n\t\tfirst int\n\t\tlast  int\n\t}\n\tgroupMap := make(map[string]*portGroup)\n\tvar result []string\n\tvar hostMappings []string\n\tvar groupMapKeys []string\n\tsort.Sort(byPortInfo(ports))\n\tfor _, port := range ports {\n\t\tcurrent := port.PrivatePort\n\t\tportKey := port.Type\n\t\tif port.IP != \"\" {\n\t\t\tif port.PublicPort != current {\n\t\t\t\thostMappings = append(hostMappings, fmt.Sprintf(\"%s:%d->%d\/%s\", port.IP, port.PublicPort, port.PrivatePort, port.Type))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tportKey = fmt.Sprintf(\"%s\/%s\", port.IP, port.Type)\n\t\t}\n\t\tgroup := groupMap[portKey]\n\n\t\tif group == nil {\n\t\t\tgroupMap[portKey] = &portGroup{first: current, last: current}\n\t\t\t\/\/ record order that groupMap keys are created\n\t\t\tgroupMapKeys = append(groupMapKeys, portKey)\n\t\t\tcontinue\n\t\t}\n\t\tif current == (group.last + 1) {\n\t\t\tgroup.last = current\n\t\t\tcontinue\n\t\t}\n\n\t\tresult = append(result, formGroup(portKey, group.first, group.last))\n\t\tgroupMap[portKey] = &portGroup{first: current, last: current}\n\t}\n\tfor _, portKey := range groupMapKeys {\n\t\tg := groupMap[portKey]\n\t\tresult = append(result, formGroup(portKey, g.first, g.last))\n\t}\n\tresult = append(result, hostMappings...)\n\treturn strings.Join(result, \", \")\n}\n\nfunc formGroup(key string, start, last int) string {\n\tparts := strings.Split(key, \"\/\")\n\tgroupType := parts[0]\n\tvar ip string\n\tif len(parts) > 1 {\n\t\tip = parts[0]\n\t\tgroupType = parts[1]\n\t}\n\tgroup := strconv.Itoa(start)\n\tif start != last {\n\t\tgroup = fmt.Sprintf(\"%s-%d\", group, last)\n\t}\n\tif ip != \"\" {\n\t\tgroup = fmt.Sprintf(\"%s:%s->%s\", ip, group, group)\n\t}\n\treturn fmt.Sprintf(\"%s\/%s\", group, groupType)\n}\n\n\/\/ MatchesContentType validates the content type against the expected one\nfunc MatchesContentType(contentType, expectedType string) bool {\n\tmimetype, _, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Error parsing media type: %s error: %v\", contentType, err)\n\t}\n\treturn err == nil && mimetype == expectedType\n}\n\n\/\/ LoadOrCreateTrustKey attempts to load the libtrust key at the given path,\n\/\/ otherwise generates a new one\nfunc LoadOrCreateTrustKey(trustKeyPath string) (libtrust.PrivateKey, error) {\n\terr := system.MkdirAll(filepath.Dir(trustKeyPath), 0700)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttrustKey, err := libtrust.LoadKeyFile(trustKeyPath)\n\tif err == libtrust.ErrKeyFileDoesNotExist {\n\t\ttrustKey, err = libtrust.GenerateECP256PrivateKey()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error generating key: %s\", err)\n\t\t}\n\t\tencodedKey, err := serializePrivateKey(trustKey, filepath.Ext(trustKeyPath))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error serializing key: %s\", err)\n\t\t}\n\t\tif err := ioutils.AtomicWriteFile(trustKeyPath, encodedKey, os.FileMode(0600)); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error saving key file: %s\", err)\n\t\t}\n\t} else if err != nil {\n\t\treturn nil, fmt.Errorf(\"Error loading key file %s: %s\", trustKeyPath, err)\n\t}\n\treturn trustKey, nil\n}\n\nfunc serializePrivateKey(key libtrust.PrivateKey, ext string) (encoded []byte, err error) {\n\tif ext == \".json\" || ext == \".jwk\" {\n\t\tencoded, err = json.Marshal(key)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to encode private key JWK: %s\", err)\n\t\t}\n\t} else {\n\t\tpemBlock, err := key.PEMBlock()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to encode private key PEM: %s\", err)\n\t\t}\n\t\tencoded = pem.EncodeToMemory(pemBlock)\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package self_test\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/lucas-clemente\/quic-go\/integrationtests\/tools\/testserver\"\n\n\tquic \"github.com\/lucas-clemente\/quic-go\"\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/testdata\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"Stream tests\", func() {\n\tvar server quic.Listener\n\tconst numStreams = 300\n\n\tBeforeEach(func() {\n\t\tvar err error\n\t\tserver, err = quic.ListenAddr(\"localhost:0\", testdata.GetTLSConfig(), nil)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t})\n\n\tAfterEach(func() {\n\t\tserver.Close()\n\t})\n\n\trunSendingPeer := func(sess quic.Session) {\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(numStreams)\n\t\tfor i := 0; i < numStreams; i++ {\n\t\t\tstr, err := sess.OpenStream()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tdata := testserver.GeneratePRData(25 * i)\n\t\t\t_, err = str.Write(data)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(str.Close()).To(Succeed())\n\t\t\tgo func() {\n\t\t\t\tdefer GinkgoRecover()\n\t\t\t\tdefer wg.Done()\n\t\t\t\tdataRead, err := ioutil.ReadAll(str)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\tExpect(dataRead).To(Equal(data))\n\t\t\t}()\n\t\t\ttime.Sleep(5 * time.Millisecond)\n\t\t}\n\t\twg.Wait()\n\t}\n\n\trunReceivingPeer := func(sess quic.Session) {\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(numStreams)\n\t\tfor i := 0; i < numStreams; i++ {\n\t\t\tstr, err := sess.AcceptStream()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tgo func() {\n\t\t\t\tdefer GinkgoRecover()\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_, err := io.Copy(str, str)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\tExpect(str.Close()).To(Succeed())\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t}\n\n\tIt(fmt.Sprintf(\"client opening %d streams to a client\", numStreams), func() {\n\t\tdone := make(chan struct{})\n\t\tgo func() {\n\t\t\tdefer GinkgoRecover()\n\t\t\tsess, err := server.Accept()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\trunReceivingPeer(sess)\n\t\t\tclose(done)\n\t\t}()\n\n\t\tclient, err := quic.DialAddr(server.Addr().String(), &tls.Config{InsecureSkipVerify: true}, nil)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\trunSendingPeer(client)\n\t\t<-done\n\t})\n\n\tIt(fmt.Sprintf(\"server opening %d streams to a client\", numStreams), func() {\n\t\tdone := make(chan struct{})\n\t\tgo func() {\n\t\t\tdefer GinkgoRecover()\n\t\t\tsess, err := server.Accept()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\trunSendingPeer(sess)\n\t\t\tclose(done)\n\t\t}()\n\n\t\tclient, err := quic.DialAddr(server.Addr().String(), &tls.Config{InsecureSkipVerify: true}, nil)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\trunReceivingPeer(client)\n\t\t<-done\n\t})\n\n\tIt(fmt.Sprintf(\"client and server opening %d each and sending data to the peer\", numStreams), func() {\n\t\tdone1 := make(chan struct{})\n\t\tgo func() {\n\t\t\tdefer GinkgoRecover()\n\t\t\tsess, err := server.Accept()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tdone := make(chan struct{})\n\t\t\tgo func() {\n\t\t\t\tdefer GinkgoRecover()\n\t\t\t\trunReceivingPeer(sess)\n\t\t\t\tclose(done)\n\t\t\t}()\n\t\t\trunSendingPeer(sess)\n\t\t\t<-done\n\t\t\tclose(done1)\n\t\t}()\n\n\t\tclient, err := quic.DialAddr(server.Addr().String(), &tls.Config{InsecureSkipVerify: true}, nil)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tdone2 := make(chan struct{})\n\t\tgo func() {\n\t\t\tdefer GinkgoRecover()\n\t\t\trunSendingPeer(client)\n\t\t\tclose(done2)\n\t\t}()\n\t\trunReceivingPeer(client)\n\t\t<-done1\n\t\t<-done2\n\t})\n})\n<commit_msg>fix concurrent streams integration test<commit_after>package self_test\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"sync\"\n\n\t\"github.com\/lucas-clemente\/quic-go\/integrationtests\/tools\/testserver\"\n\n\tquic \"github.com\/lucas-clemente\/quic-go\"\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/testdata\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"Stream tests\", func() {\n\tvar server quic.Listener\n\tconst numStreams = 300\n\n\tBeforeEach(func() {\n\t\tvar err error\n\t\tserver, err = quic.ListenAddr(\"localhost:0\", testdata.GetTLSConfig(), nil)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t})\n\n\tAfterEach(func() {\n\t\tserver.Close()\n\t})\n\n\trunSendingPeer := func(sess quic.Session) {\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(numStreams)\n\t\tfor i := 0; i < numStreams; i++ {\n\t\t\tstr, err := sess.OpenStreamSync()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tdata := testserver.GeneratePRData(25 * i)\n\t\t\tgo func() {\n\t\t\t\tdefer GinkgoRecover()\n\t\t\t\t_, err := str.Write(data)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\tExpect(str.Close()).To(Succeed())\n\t\t\t}()\n\t\t\tgo func() {\n\t\t\t\tdefer GinkgoRecover()\n\t\t\t\tdefer wg.Done()\n\t\t\t\tdataRead, err := ioutil.ReadAll(str)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\tExpect(dataRead).To(Equal(data))\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t}\n\n\trunReceivingPeer := func(sess quic.Session) {\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(numStreams)\n\t\tfor i := 0; i < numStreams; i++ {\n\t\t\tstr, err := sess.AcceptStream()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tgo func() {\n\t\t\t\tdefer GinkgoRecover()\n\t\t\t\tdefer wg.Done()\n\t\t\t\t_, err := io.Copy(str, str)\n\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\tExpect(str.Close()).To(Succeed())\n\t\t\t}()\n\t\t}\n\t\twg.Wait()\n\t}\n\n\tIt(fmt.Sprintf(\"client opening %d streams to a client\", numStreams), func() {\n\t\tdone := make(chan struct{})\n\t\tgo func() {\n\t\t\tdefer GinkgoRecover()\n\t\t\tsess, err := server.Accept()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\trunReceivingPeer(sess)\n\t\t\tclose(done)\n\t\t}()\n\n\t\tclient, err := quic.DialAddr(server.Addr().String(), &tls.Config{InsecureSkipVerify: true}, nil)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\trunSendingPeer(client)\n\t\t<-done\n\t})\n\n\tIt(fmt.Sprintf(\"server opening %d streams to a client\", numStreams), func() {\n\t\tdone := make(chan struct{})\n\t\tgo func() {\n\t\t\tdefer GinkgoRecover()\n\t\t\tsess, err := server.Accept()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\trunSendingPeer(sess)\n\t\t\tclose(done)\n\t\t}()\n\n\t\tclient, err := quic.DialAddr(server.Addr().String(), &tls.Config{InsecureSkipVerify: true}, nil)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\trunReceivingPeer(client)\n\t\t<-done\n\t})\n\n\tIt(fmt.Sprintf(\"client and server opening %d each and sending data to the peer\", numStreams), func() {\n\t\tdone1 := make(chan struct{})\n\t\tgo func() {\n\t\t\tdefer GinkgoRecover()\n\t\t\tsess, err := server.Accept()\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tdone := make(chan struct{})\n\t\t\tgo func() {\n\t\t\t\tdefer GinkgoRecover()\n\t\t\t\trunReceivingPeer(sess)\n\t\t\t\tclose(done)\n\t\t\t}()\n\t\t\trunSendingPeer(sess)\n\t\t\t<-done\n\t\t\tclose(done1)\n\t\t}()\n\n\t\tclient, err := quic.DialAddr(server.Addr().String(), &tls.Config{InsecureSkipVerify: true}, nil)\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tdone2 := make(chan struct{})\n\t\tgo func() {\n\t\t\tdefer GinkgoRecover()\n\t\t\trunSendingPeer(client)\n\t\t\tclose(done2)\n\t\t}()\n\t\trunReceivingPeer(client)\n\t\t<-done1\n\t\t<-done2\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package net\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"syscall\"\n\n\t\"github.com\/vishvananda\/netlink\"\n)\n\n\/\/ Wait for an interface to come up.\nfunc EnsureInterface(ifaceName string) (*net.Interface, error) {\n\tiface, err := ensureInterface(ifaceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn iface, err\n}\n\nfunc ensureInterface(ifaceName string) (*net.Interface, error) {\n\tch := make(chan netlink.LinkUpdate)\n\tdone := make(chan struct{})\n\tdefer close(done)\n\tif err := netlink.LinkSubscribe(ch, done); err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ check for currently-existing interface after subscribing, to avoid race\n\tif iface, err := findInterface(ifaceName); err == nil {\n\t\treturn iface, nil\n\t}\n\tfor update := range ch {\n\t\tif ifaceName == update.Link.Attrs().Name && update.IfInfomsg.Flags&syscall.IFF_UP != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tiface, err := findInterface(ifaceName)\n\treturn iface, err\n}\n\n\/\/ Wait for an interface to come up and have a route added to the multicast subnet.\n\/\/ This matches the behaviour in 'weave attach', which is the only context in which\n\/\/ we expect this to be called.  If you change one, change the other to match.\nfunc EnsureInterfaceAndMcastRoute(ifaceName string) (*net.Interface, error) {\n\tiface, err := ensureInterface(ifaceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tch := make(chan netlink.RouteUpdate)\n\tdone := make(chan struct{})\n\tdefer close(done)\n\tif err := netlink.RouteSubscribe(ch, done); err != nil {\n\t\treturn nil, err\n\t}\n\tdest := net.IPv4(224, 0, 0, 0)\n\tcheck := func(route netlink.Route) bool {\n\t\treturn route.LinkIndex == iface.Index && route.Dst.IP.Equal(dest)\n\t}\n\t\/\/ check for currently-existing route after subscribing, to avoid race\n\troutes, err := netlink.RouteList(nil, netlink.FAMILY_V4)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, route := range routes {\n\t\tif check(route) {\n\t\t\treturn iface, nil\n\t\t}\n\t}\n\tfor update := range ch {\n\t\tif check(update.Route) {\n\t\t\treturn iface, nil\n\t\t}\n\t}\n\t\/\/ should never get here\n\treturn iface, nil\n}\n\nfunc findInterface(ifaceName string) (iface *net.Interface, err error) {\n\tif iface, err = net.InterfaceByName(ifaceName); err != nil {\n\t\treturn iface, fmt.Errorf(\"Unable to find interface %s\", ifaceName)\n\t}\n\tif 0 == (net.FlagUp & iface.Flags) {\n\t\treturn iface, fmt.Errorf(\"Interface %s is not up\", ifaceName)\n\t}\n\treturn\n}\n<commit_msg>cope with nil route.Dst<commit_after>package net\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"syscall\"\n\n\t\"github.com\/vishvananda\/netlink\"\n)\n\n\/\/ Wait for an interface to come up.\nfunc EnsureInterface(ifaceName string) (*net.Interface, error) {\n\tiface, err := ensureInterface(ifaceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn iface, err\n}\n\nfunc ensureInterface(ifaceName string) (*net.Interface, error) {\n\tch := make(chan netlink.LinkUpdate)\n\tdone := make(chan struct{})\n\tdefer close(done)\n\tif err := netlink.LinkSubscribe(ch, done); err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ check for currently-existing interface after subscribing, to avoid race\n\tif iface, err := findInterface(ifaceName); err == nil {\n\t\treturn iface, nil\n\t}\n\tfor update := range ch {\n\t\tif ifaceName == update.Link.Attrs().Name && update.IfInfomsg.Flags&syscall.IFF_UP != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tiface, err := findInterface(ifaceName)\n\treturn iface, err\n}\n\n\/\/ Wait for an interface to come up and have a route added to the multicast subnet.\n\/\/ This matches the behaviour in 'weave attach', which is the only context in which\n\/\/ we expect this to be called.  If you change one, change the other to match.\nfunc EnsureInterfaceAndMcastRoute(ifaceName string) (*net.Interface, error) {\n\tiface, err := ensureInterface(ifaceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tch := make(chan netlink.RouteUpdate)\n\tdone := make(chan struct{})\n\tdefer close(done)\n\tif err := netlink.RouteSubscribe(ch, done); err != nil {\n\t\treturn nil, err\n\t}\n\tdest := net.IPv4(224, 0, 0, 0)\n\tcheck := func(route netlink.Route) bool {\n\t\treturn route.LinkIndex == iface.Index && route.Dst != nil && route.Dst.IP.Equal(dest)\n\t}\n\t\/\/ check for currently-existing route after subscribing, to avoid race\n\troutes, err := netlink.RouteList(nil, netlink.FAMILY_V4)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, route := range routes {\n\t\tif check(route) {\n\t\t\treturn iface, nil\n\t\t}\n\t}\n\tfor update := range ch {\n\t\tif check(update.Route) {\n\t\t\treturn iface, nil\n\t\t}\n\t}\n\t\/\/ should never get here\n\treturn iface, nil\n}\n\nfunc findInterface(ifaceName string) (iface *net.Interface, err error) {\n\tif iface, err = net.InterfaceByName(ifaceName); err != nil {\n\t\treturn iface, fmt.Errorf(\"Unable to find interface %s\", ifaceName)\n\t}\n\tif 0 == (net.FlagUp & iface.Flags) {\n\t\treturn iface, fmt.Errorf(\"Interface %s is not up\", ifaceName)\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package snapcraft implements the Pipe interface providing Snapcraft bindings.\npackage snapcraft\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/apex\/log\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/artifact\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/linux\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/pipe\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/semerrgroup\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/tmpl\"\n\t\"github.com\/goreleaser\/goreleaser\/pkg\/context\"\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\n\/\/ ErrNoSnapcraft is shown when snapcraft cannot be found in $PATH\nvar ErrNoSnapcraft = errors.New(\"snapcraft not present in $PATH\")\n\n\/\/ ErrNoDescription is shown when no description provided\nvar ErrNoDescription = errors.New(\"no description provided for snapcraft\")\n\n\/\/ ErrNoSummary is shown when no summary provided\nvar ErrNoSummary = errors.New(\"no summary provided for snapcraft\")\n\n\/\/ Metadata to generate the snap package\ntype Metadata struct {\n\tName          string\n\tVersion       string\n\tSummary       string\n\tDescription   string\n\tGrade         string `yaml:\",omitempty\"`\n\tConfinement   string `yaml:\",omitempty\"`\n\tArchitectures []string\n\tApps          map[string]AppMetadata\n}\n\n\/\/ AppMetadata for the binaries that will be in the snap package\ntype AppMetadata struct {\n\tCommand string\n\tPlugs   []string `yaml:\",omitempty\"`\n\tDaemon  string   `yaml:\",omitempty\"`\n}\n\nconst defaultNameTemplate = \"{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}\"\n\n\/\/ Pipe for snapcraft packaging\ntype Pipe struct{}\n\nfunc (Pipe) String() string {\n\treturn \"Snapcraft Packages\"\n}\n\n\/\/ Default sets the pipe defaults\nfunc (Pipe) Default(ctx *context.Context) error {\n\tvar snap = &ctx.Config.Snapcraft\n\tif snap.NameTemplate == \"\" {\n\t\tsnap.NameTemplate = defaultNameTemplate\n\t}\n\treturn nil\n}\n\n\/\/ Run the pipe\nfunc (Pipe) Run(ctx *context.Context) error {\n\tif ctx.Config.Snapcraft.Summary == \"\" && ctx.Config.Snapcraft.Description == \"\" {\n\t\treturn pipe.Skip(\"no summary nor description were provided\")\n\t}\n\tif ctx.Config.Snapcraft.Summary == \"\" {\n\t\treturn ErrNoSummary\n\t}\n\tif ctx.Config.Snapcraft.Description == \"\" {\n\t\treturn ErrNoDescription\n\t}\n\t_, err := exec.LookPath(\"snapcraft\")\n\tif err != nil {\n\t\treturn ErrNoSnapcraft\n\t}\n\n\tvar g = semerrgroup.New(ctx.Parallelism)\n\tfor platform, binaries := range ctx.Artifacts.Filter(\n\t\tartifact.And(\n\t\t\tartifact.ByGoos(\"linux\"),\n\t\t\tartifact.ByType(artifact.Binary),\n\t\t),\n\t).GroupByPlatform() {\n\t\tarch := linux.Arch(platform)\n\t\tif arch == \"armel\" {\n\t\t\tlog.WithField(\"arch\", arch).Warn(\"ignored unsupported arch\")\n\t\t\tcontinue\n\t\t}\n\t\tbinaries := binaries\n\t\tg.Go(func() error {\n\t\t\treturn create(ctx, arch, binaries)\n\t\t})\n\t}\n\treturn g.Wait()\n}\n\n\/\/ Publish packages\nfunc (Pipe) Publish(ctx *context.Context) error {\n\tsnaps := ctx.Artifacts.Filter(artifact.ByType(artifact.PublishableSnapcraft)).List()\n\tvar g = semerrgroup.New(ctx.Parallelism)\n\tfor _, snap := range snaps {\n\t\tsnap := snap\n\t\tg.Go(func() error {\n\t\t\treturn push(ctx, snap)\n\t\t})\n\t}\n\treturn g.Wait()\n}\n\nfunc create(ctx *context.Context, arch string, binaries []artifact.Artifact) error {\n\tvar log = log.WithField(\"arch\", arch)\n\tfolder, err := tmpl.New(ctx).\n\t\tWithArtifact(binaries[0], ctx.Config.Snapcraft.Replacements).\n\t\tApply(ctx.Config.Snapcraft.NameTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ prime is the directory that then will be compressed to make the .snap package.\n\tvar folderDir = filepath.Join(ctx.Config.Dist, folder)\n\tvar primeDir = filepath.Join(folderDir, \"prime\")\n\tvar metaDir = filepath.Join(primeDir, \"meta\")\n\t\/\/ #nosec\n\tif err = os.MkdirAll(metaDir, 0755); err != nil {\n\t\treturn err\n\t}\n\n\tvar file = filepath.Join(primeDir, \"meta\", \"snap.yaml\")\n\tlog.WithField(\"file\", file).Debug(\"creating snap metadata\")\n\n\tvar metadata = &Metadata{\n\t\tVersion:       ctx.Version,\n\t\tSummary:       ctx.Config.Snapcraft.Summary,\n\t\tDescription:   ctx.Config.Snapcraft.Description,\n\t\tGrade:         ctx.Config.Snapcraft.Grade,\n\t\tConfinement:   ctx.Config.Snapcraft.Confinement,\n\t\tArchitectures: []string{arch},\n\t\tApps:          make(map[string]AppMetadata),\n\t}\n\n\tmetadata.Name = ctx.Config.ProjectName\n\tif ctx.Config.Snapcraft.Name != \"\" {\n\t\tmetadata.Name = ctx.Config.Snapcraft.Name\n\t}\n\n\tfor _, binary := range binaries {\n\t\tlog.WithField(\"path\", binary.Path).\n\t\t\tWithField(\"name\", binary.Name).\n\t\t\tDebug(\"passed binary to snapcraft\")\n\t\tappMetadata := AppMetadata{\n\t\t\tCommand: binary.Name,\n\t\t}\n\t\tif configAppMetadata, ok := ctx.Config.Snapcraft.Apps[binary.Name]; ok {\n\t\t\tappMetadata.Plugs = configAppMetadata.Plugs\n\t\t\tappMetadata.Daemon = configAppMetadata.Daemon\n\t\t\tappMetadata.Command = strings.Join([]string{\n\t\t\t\tappMetadata.Command,\n\t\t\t\tconfigAppMetadata.Args,\n\t\t\t}, \" \")\n\t\t}\n\t\tmetadata.Apps[binary.Name] = appMetadata\n\n\t\tdestBinaryPath := filepath.Join(primeDir, filepath.Base(binary.Path))\n\t\tif err = os.Link(binary.Path, destBinaryPath); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif _, ok := metadata.Apps[metadata.Name]; !ok {\n\t\tmetadata.Apps[metadata.Name] = metadata.Apps[binaries[0].Name]\n\t}\n\n\tout, err := yaml.Marshal(metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = ioutil.WriteFile(file, out, 0644); err != nil {\n\t\treturn err\n\t}\n\n\tvar snap = filepath.Join(ctx.Config.Dist, folder+\".snap\")\n\tlog.WithField(\"snap\", snap).Info(\"creating\")\n\t\/* #nosec *\/\n\tvar cmd = exec.CommandContext(ctx, \"snapcraft\", \"pack\", primeDir, \"--output\", snap)\n\tif out, err = cmd.CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"failed to generate snap package: %s\", string(out))\n\t}\n\tif !ctx.Config.Snapcraft.Publish {\n\t\treturn nil\n\t}\n\tctx.Artifacts.Add(artifact.Artifact{\n\t\tType:   artifact.PublishableSnapcraft,\n\t\tName:   folder + \".snap\",\n\t\tPath:   snap,\n\t\tGoos:   binaries[0].Goos,\n\t\tGoarch: binaries[0].Goarch,\n\t\tGoarm:  binaries[0].Goarm,\n\t})\n\treturn nil\n}\n\nfunc push(ctx *context.Context, snap artifact.Artifact) error {\n\tlog.WithField(\"snap\", snap.Name).Info(\"pushing\")\n\t\/\/ TODO: customize --release based on snap.Grade?\n\t\/* #nosec *\/\n\tvar cmd = exec.CommandContext(ctx, \"snapcraft\", \"push\", \"--release=stable\", snap.Path)\n\tif out, err := cmd.CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"failed to push %s package: %s\", snap.Path, string(out))\n\t}\n\tsnap.Type = artifact.Snapcraft\n\tctx.Artifacts.Add(snap)\n\treturn nil\n}\n<commit_msg>chore: improved log<commit_after>\/\/ Package snapcraft implements the Pipe interface providing Snapcraft bindings.\npackage snapcraft\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/apex\/log\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/artifact\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/linux\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/pipe\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/semerrgroup\"\n\t\"github.com\/goreleaser\/goreleaser\/internal\/tmpl\"\n\t\"github.com\/goreleaser\/goreleaser\/pkg\/context\"\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\n\/\/ ErrNoSnapcraft is shown when snapcraft cannot be found in $PATH\nvar ErrNoSnapcraft = errors.New(\"snapcraft not present in $PATH\")\n\n\/\/ ErrNoDescription is shown when no description provided\nvar ErrNoDescription = errors.New(\"no description provided for snapcraft\")\n\n\/\/ ErrNoSummary is shown when no summary provided\nvar ErrNoSummary = errors.New(\"no summary provided for snapcraft\")\n\n\/\/ Metadata to generate the snap package\ntype Metadata struct {\n\tName          string\n\tVersion       string\n\tSummary       string\n\tDescription   string\n\tGrade         string `yaml:\",omitempty\"`\n\tConfinement   string `yaml:\",omitempty\"`\n\tArchitectures []string\n\tApps          map[string]AppMetadata\n}\n\n\/\/ AppMetadata for the binaries that will be in the snap package\ntype AppMetadata struct {\n\tCommand string\n\tPlugs   []string `yaml:\",omitempty\"`\n\tDaemon  string   `yaml:\",omitempty\"`\n}\n\nconst defaultNameTemplate = \"{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}\"\n\n\/\/ Pipe for snapcraft packaging\ntype Pipe struct{}\n\nfunc (Pipe) String() string {\n\treturn \"Snapcraft Packages\"\n}\n\n\/\/ Default sets the pipe defaults\nfunc (Pipe) Default(ctx *context.Context) error {\n\tvar snap = &ctx.Config.Snapcraft\n\tif snap.NameTemplate == \"\" {\n\t\tsnap.NameTemplate = defaultNameTemplate\n\t}\n\treturn nil\n}\n\n\/\/ Run the pipe\nfunc (Pipe) Run(ctx *context.Context) error {\n\tif ctx.Config.Snapcraft.Summary == \"\" && ctx.Config.Snapcraft.Description == \"\" {\n\t\treturn pipe.Skip(\"no summary nor description were provided\")\n\t}\n\tif ctx.Config.Snapcraft.Summary == \"\" {\n\t\treturn ErrNoSummary\n\t}\n\tif ctx.Config.Snapcraft.Description == \"\" {\n\t\treturn ErrNoDescription\n\t}\n\t_, err := exec.LookPath(\"snapcraft\")\n\tif err != nil {\n\t\treturn ErrNoSnapcraft\n\t}\n\n\tvar g = semerrgroup.New(ctx.Parallelism)\n\tfor platform, binaries := range ctx.Artifacts.Filter(\n\t\tartifact.And(\n\t\t\tartifact.ByGoos(\"linux\"),\n\t\t\tartifact.ByType(artifact.Binary),\n\t\t),\n\t).GroupByPlatform() {\n\t\tarch := linux.Arch(platform)\n\t\tif arch == \"armel\" {\n\t\t\tlog.WithField(\"arch\", arch).Warn(\"ignored unsupported arch\")\n\t\t\tcontinue\n\t\t}\n\t\tbinaries := binaries\n\t\tg.Go(func() error {\n\t\t\treturn create(ctx, arch, binaries)\n\t\t})\n\t}\n\treturn g.Wait()\n}\n\n\/\/ Publish packages\nfunc (Pipe) Publish(ctx *context.Context) error {\n\tsnaps := ctx.Artifacts.Filter(artifact.ByType(artifact.PublishableSnapcraft)).List()\n\tvar g = semerrgroup.New(ctx.Parallelism)\n\tfor _, snap := range snaps {\n\t\tsnap := snap\n\t\tg.Go(func() error {\n\t\t\treturn push(ctx, snap)\n\t\t})\n\t}\n\treturn g.Wait()\n}\n\nfunc create(ctx *context.Context, arch string, binaries []artifact.Artifact) error {\n\tvar log = log.WithField(\"arch\", arch)\n\tfolder, err := tmpl.New(ctx).\n\t\tWithArtifact(binaries[0], ctx.Config.Snapcraft.Replacements).\n\t\tApply(ctx.Config.Snapcraft.NameTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ prime is the directory that then will be compressed to make the .snap package.\n\tvar folderDir = filepath.Join(ctx.Config.Dist, folder)\n\tvar primeDir = filepath.Join(folderDir, \"prime\")\n\tvar metaDir = filepath.Join(primeDir, \"meta\")\n\t\/\/ #nosec\n\tif err = os.MkdirAll(metaDir, 0755); err != nil {\n\t\treturn err\n\t}\n\n\tvar file = filepath.Join(primeDir, \"meta\", \"snap.yaml\")\n\tlog.WithField(\"file\", file).Debug(\"creating snap metadata\")\n\n\tvar metadata = &Metadata{\n\t\tVersion:       ctx.Version,\n\t\tSummary:       ctx.Config.Snapcraft.Summary,\n\t\tDescription:   ctx.Config.Snapcraft.Description,\n\t\tGrade:         ctx.Config.Snapcraft.Grade,\n\t\tConfinement:   ctx.Config.Snapcraft.Confinement,\n\t\tArchitectures: []string{arch},\n\t\tApps:          make(map[string]AppMetadata),\n\t}\n\n\tmetadata.Name = ctx.Config.ProjectName\n\tif ctx.Config.Snapcraft.Name != \"\" {\n\t\tmetadata.Name = ctx.Config.Snapcraft.Name\n\t}\n\n\tfor _, binary := range binaries {\n\t\tlog.WithField(\"path\", binary.Path).\n\t\t\tWithField(\"name\", binary.Name).\n\t\t\tDebug(\"passed binary to snapcraft\")\n\t\tappMetadata := AppMetadata{\n\t\t\tCommand: binary.Name,\n\t\t}\n\t\tif configAppMetadata, ok := ctx.Config.Snapcraft.Apps[binary.Name]; ok {\n\t\t\tappMetadata.Plugs = configAppMetadata.Plugs\n\t\t\tappMetadata.Daemon = configAppMetadata.Daemon\n\t\t\tappMetadata.Command = strings.Join([]string{\n\t\t\t\tappMetadata.Command,\n\t\t\t\tconfigAppMetadata.Args,\n\t\t\t}, \" \")\n\t\t}\n\t\tmetadata.Apps[binary.Name] = appMetadata\n\n\t\tdestBinaryPath := filepath.Join(primeDir, filepath.Base(binary.Path))\n\t\tif err = os.Link(binary.Path, destBinaryPath); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif _, ok := metadata.Apps[metadata.Name]; !ok {\n\t\tmetadata.Apps[metadata.Name] = metadata.Apps[binaries[0].Name]\n\t}\n\n\tout, err := yaml.Marshal(metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = ioutil.WriteFile(file, out, 0644); err != nil {\n\t\treturn err\n\t}\n\n\tvar snap = filepath.Join(ctx.Config.Dist, folder+\".snap\")\n\tlog.WithField(\"snap\", snap).Info(\"creating\")\n\t\/* #nosec *\/\n\tvar cmd = exec.CommandContext(ctx, \"snapcraft\", \"pack\", primeDir, \"--output\", snap)\n\tif out, err = cmd.CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"failed to generate snap package: %s\", string(out))\n\t}\n\tif !ctx.Config.Snapcraft.Publish {\n\t\treturn nil\n\t}\n\tctx.Artifacts.Add(artifact.Artifact{\n\t\tType:   artifact.PublishableSnapcraft,\n\t\tName:   folder + \".snap\",\n\t\tPath:   snap,\n\t\tGoos:   binaries[0].Goos,\n\t\tGoarch: binaries[0].Goarch,\n\t\tGoarm:  binaries[0].Goarm,\n\t})\n\treturn nil\n}\n\nfunc push(ctx *context.Context, snap artifact.Artifact) error {\n\tlog.WithField(\"snap\", snap.Name).Info(\"pushing snap\")\n\t\/\/ TODO: customize --release based on snap.Grade?\n\t\/* #nosec *\/\n\tvar cmd = exec.CommandContext(ctx, \"snapcraft\", \"push\", \"--release=stable\", snap.Path)\n\tif out, err := cmd.CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"failed to push %s package: %s\", snap.Path, string(out))\n\t}\n\tsnap.Type = artifact.Snapcraft\n\tctx.Artifacts.Add(snap)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package ipfix decodes IPFIX packets\n\/\/: ----------------------------------------------------------------------------\n\/\/: Copyright (C) 2017 Verizon.  All Rights Reserved.\n\/\/: All Rights Reserved\n\/\/:\n\/\/: file:    decoder.go\n\/\/: details: TODO\n\/\/: author:  Mehrdad Arshad Rad\n\/\/: date:    02\/01\/2017\n\/\/:\n\/\/: Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/: you may not use this file except in compliance with the License.\n\/\/: You may obtain a copy of the License at\n\/\/:\n\/\/:     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/:\n\/\/: Unless required by applicable law or agreed to in writing, software\n\/\/: distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/: See the License for the specific language governing permissions and\n\/\/: limitations under the License.\n\/\/: ----------------------------------------------------------------------------\npackage ipfix\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"net\"\n)\n\n\/\/ Decoder represents IPFIX payload and remote address\ntype Decoder struct {\n\traddr  net.IP\n\treader *Reader\n}\n\n\/\/ MessageHeader represents IPFIX message header\ntype MessageHeader struct {\n\tVersion    uint16 \/\/ Version of IPFIX to which this Message conforms\n\tLength     uint16 \/\/ Total length of the IPFIX Message, measured in octets\n\tExportTime uint32 \/\/ Time at which the IPFIX Message Header leaves the Exporter\n\tSequenceNo uint32 \/\/ Incremental sequence counter modulo 2^32\n\tDomainID   uint32 \/\/ A 32-bit id that is locally unique to the Exporting Process\n}\n\n\/\/ TemplateHeader represents template fields\ntype TemplateHeader struct {\n\tTemplateID      uint16\n\tFieldCount      uint16\n\tScopeFieldCount uint16\n}\n\n\/\/ TemplateRecords represents template records\ntype TemplateRecords struct {\n\tTemplateID           uint16\n\tFieldCount           uint16\n\tFieldSpecifiers      []TemplateFieldSpecifier\n\tScopeFieldCount      uint16\n\tScopeFieldSpecifiers []TemplateFieldSpecifier\n}\n\n\/\/ TemplateFieldSpecifier represents field properties\ntype TemplateFieldSpecifier struct {\n\tElementID    uint16\n\tLength       uint16\n\tEnterpriseNo uint32\n}\n\n\/\/ Message represents IPFIX decoded data\ntype Message struct {\n\tAgentID  string\n\tHeader   MessageHeader\n\tDataSets [][]DecodedField\n}\n\n\/\/ DecodedField represents a decoded field\ntype DecodedField struct {\n\tID    uint16\n\tValue interface{}\n}\n\n\/\/ SetHeader represents set header fields\ntype SetHeader struct {\n\tSetID  uint16\n\tLength uint16\n}\n\nvar (\n\trpcChan = make(chan RPCRequest, 1)\n\n\terrInvalidVersion    = errors.New(\"invalid ipfix version\")\n\terrUnknownTemplateID = errors.New(\"unknown template id\")\n)\n\n\/\/ NewDecoder constructs a decoder\nfunc NewDecoder(raddr net.IP, b []byte) *Decoder {\n\treturn &Decoder{raddr, NewReader(b)}\n}\n\n\/\/ Decode decodes the IPFIX raw data\nfunc (d *Decoder) Decode(mem MemCache) (*Message, error) {\n\tvar (\n\t\tmsg = new(Message)\n\t\terr error\n\t)\n\n\t\/\/ IPFIX Message Header decoding\n\tif err = msg.Header.unmarshal(d.reader); err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ IPFIX Message Header validation\n\tif err = msg.Header.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Add source IP address as Agent ID\n\tmsg.AgentID = d.raddr.String()\n\n\tfor d.reader.Len() > 4 {\n\n\t\tsetHeader := new(SetHeader)\n\t\tsetHeader.unmarshal(d.reader)\n\n\t\tif setHeader.Length < 4 {\n\t\t\treturn nil, io.ErrUnexpectedEOF\n\t\t}\n\n\t\tswitch {\n\t\tcase setHeader.SetID == 2:\n\t\t\t\/\/ Template set\n\t\t\ttr := TemplateRecords{}\n\t\t\ttr.unmarshal(d.reader)\n\t\t\tmem.insert(tr.TemplateID, d.raddr, tr)\n\t\tcase setHeader.SetID == 3:\n\t\t\t\/\/ Option set\n\t\t\ttr := TemplateRecords{}\n\t\t\ttr.unmarshalOpts(d.reader)\n\t\t\tmem.insert(tr.TemplateID, d.raddr, tr)\n\t\tcase setHeader.SetID >= 4 && setHeader.SetID <= 255:\n\t\t\t\/\/ Reserved\n\t\tdefault:\n\t\t\t\/\/ data\n\t\t\tfor d.reader.Len() > 0 {\n\t\t\t\ttr, ok := mem.retrieve(setHeader.SetID, d.raddr)\n\t\t\t\tif !ok {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase rpcChan <- RPCRequest{}:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t\treturn msg, errUnknownTemplateID\n\t\t\t\t}\n\n\t\t\t\tdata := decodeData(d.reader, tr)\n\t\t\t\tmsg.DataSets = append(msg.DataSets, data)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn msg, nil\n}\n\n\/\/ RFC 7011 - part 3.1. Message Header Format\n\/\/ 0                   1                   2                   3\n\/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |       Version Number          |            Length             |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |                           Export Time                         |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |                       Sequence Number                         |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |                    Observation Domain ID                      |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (h *MessageHeader) unmarshal(r *Reader) error {\n\tvar err error\n\n\tif h.Version, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif h.Length, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif h.ExportTime, err = r.Uint32(); err != nil {\n\t\treturn err\n\t}\n\n\tif h.SequenceNo, err = r.Uint32(); err != nil {\n\t\treturn err\n\t}\n\n\tif h.DomainID, err = r.Uint32(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (h *MessageHeader) validate() error {\n\tif h.Version != 0x000a {\n\t\treturn errInvalidVersion\n\t}\n\n\t\/\/ TODO: needs more validation\n\n\treturn nil\n}\n\n\/\/ RFC 7011 - part 3.3.2 Set Header Format\n\/\/ 0                   1                   2                   3\n\/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |          Set ID               |          Length               |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (h *SetHeader) unmarshal(r *Reader) error {\n\tvar err error\n\n\tif h.SetID, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif h.Length, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ RFC 7011\n\/\/ 0                   1                   2                   3\n\/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |       Set ID = (2 or 3)       |          Length               |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |         Template ID           |         Field Count           |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (t *TemplateHeader) unmarshal(r *Reader) error {\n\tvar err error\n\n\tif t.TemplateID, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif t.FieldCount, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}\n\n\/\/ RFC 7011 3.4.2.2.  Options Template Record Format\n\/\/ 0                   1                   2                   3\n\/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |          Set ID = 3           |          Length               |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |         Template ID           |         Field Count = N + M   |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |     Scope Field Count = N     |0|  Scope 1 Infor. Element id. |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (t *TemplateHeader) unmarshalOpts(r *Reader) error {\n\tvar err error\n\n\tif t.TemplateID, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif t.FieldCount, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif t.ScopeFieldCount, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}\n\n\/\/ RFC 7011\n\/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |E|  Information Element ident. |        Field Length           |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |                      Enterprise Number                        |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (f *TemplateFieldSpecifier) unmarshal(r *Reader) error {\n\tvar err error\n\n\tif f.ElementID, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif f.Length, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif f.ElementID > 0x8000 {\n\t\tf.ElementID = f.ElementID & 0x7fff\n\t\tif f.EnterpriseNo, err = r.Uint32(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/  0                   1                   2                   3\n\/\/  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |          Set ID = 2           |          Length               |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |      Template ID = 256        |         Field Count = N       |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |1| Information Element id. 1.1 |        Field Length 1.1       |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |                    Enterprise Number  1.1                     |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |0| Information Element id. 1.2 |        Field Length 1.2       |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |             ...               |              ...              |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (tr *TemplateRecords) unmarshal(r *Reader) {\n\tvar (\n\t\tth = TemplateHeader{}\n\t\ttf = TemplateFieldSpecifier{}\n\t)\n\n\tth.unmarshal(r)\n\ttr.TemplateID = th.TemplateID\n\ttr.FieldCount = th.FieldCount\n\n\tfor i := th.FieldCount; i > 0; i-- {\n\t\ttf.unmarshal(r)\n\t\ttr.FieldSpecifiers = append(tr.FieldSpecifiers, tf)\n\t}\n}\n\n\/\/  0                   1                   2                   3\n\/\/  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |          Set ID = 3           |          Length               |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |         Template ID = X       |         Field Count = N + M   |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |     Scope Field Count = N     |0|  Scope 1 Infor. Element id. |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |     Scope 1 Field Length      |0|  Scope 2 Infor. Element id. |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |     Scope 2 Field Length      |             ...               |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |            ...                |1|  Scope N Infor. Element id. |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |     Scope N Field Length      |   Scope N Enterprise Number  ...\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ ...  Scope N Enterprise Number   |1| Option 1 Infor. Element id. |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |    Option 1 Field Length      |  Option 1 Enterprise Number  ...\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ ... Option 1 Enterprise Number   |              ...              |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |             ...               |0| Option M Infor. Element id. |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |     Option M Field Length     |      Padding (optional)       |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (tr *TemplateRecords) unmarshalOpts(r *Reader) {\n\tvar (\n\t\tth = TemplateHeader{}\n\t\ttf = TemplateFieldSpecifier{}\n\t)\n\n\tth.unmarshalOpts(r)\n\ttr.TemplateID = th.TemplateID\n\ttr.FieldCount = th.FieldCount\n\ttr.ScopeFieldCount = th.ScopeFieldCount\n\n\tfor i := th.ScopeFieldCount; i > 0; i-- {\n\t\ttf.unmarshal(r)\n\t\ttr.ScopeFieldSpecifiers = append(tr.FieldSpecifiers, tf)\n\t}\n\n\tfor i := th.FieldCount - th.ScopeFieldCount; i > 0; i-- {\n\t\ttf.unmarshal(r)\n\t\ttr.FieldSpecifiers = append(tr.FieldSpecifiers, tf)\n\t}\n}\n\nfunc decodeData(r *Reader, tr TemplateRecords) []DecodedField {\n\tvar (\n\t\tfields []DecodedField\n\t\tb      []byte\n\t)\n\n\tfor i := 0; i < len(tr.FieldSpecifiers); i++ {\n\t\tb, _ = r.Read(int(tr.FieldSpecifiers[i].Length))\n\t\tm := ipfixInfoModel[elementKey{\n\t\t\ttr.FieldSpecifiers[i].EnterpriseNo,\n\t\t\ttr.FieldSpecifiers[i].ElementID,\n\t\t}]\n\t\tfields = append(fields, DecodedField{\n\t\t\tID:    m.FieldID,\n\t\t\tValue: interpret(b, m.Type),\n\t\t})\n\t}\n\n\treturn fields\n}\n<commit_msg>init id and raddr to rpc request<commit_after>\/\/ Package ipfix decodes IPFIX packets\n\/\/: ----------------------------------------------------------------------------\n\/\/: Copyright (C) 2017 Verizon.  All Rights Reserved.\n\/\/: All Rights Reserved\n\/\/:\n\/\/: file:    decoder.go\n\/\/: details: TODO\n\/\/: author:  Mehrdad Arshad Rad\n\/\/: date:    02\/01\/2017\n\/\/:\n\/\/: Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/: you may not use this file except in compliance with the License.\n\/\/: You may obtain a copy of the License at\n\/\/:\n\/\/:     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/:\n\/\/: Unless required by applicable law or agreed to in writing, software\n\/\/: distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/: See the License for the specific language governing permissions and\n\/\/: limitations under the License.\n\/\/: ----------------------------------------------------------------------------\npackage ipfix\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"net\"\n)\n\n\/\/ Decoder represents IPFIX payload and remote address\ntype Decoder struct {\n\traddr  net.IP\n\treader *Reader\n}\n\n\/\/ MessageHeader represents IPFIX message header\ntype MessageHeader struct {\n\tVersion    uint16 \/\/ Version of IPFIX to which this Message conforms\n\tLength     uint16 \/\/ Total length of the IPFIX Message, measured in octets\n\tExportTime uint32 \/\/ Time at which the IPFIX Message Header leaves the Exporter\n\tSequenceNo uint32 \/\/ Incremental sequence counter modulo 2^32\n\tDomainID   uint32 \/\/ A 32-bit id that is locally unique to the Exporting Process\n}\n\n\/\/ TemplateHeader represents template fields\ntype TemplateHeader struct {\n\tTemplateID      uint16\n\tFieldCount      uint16\n\tScopeFieldCount uint16\n}\n\n\/\/ TemplateRecords represents template records\ntype TemplateRecords struct {\n\tTemplateID           uint16\n\tFieldCount           uint16\n\tFieldSpecifiers      []TemplateFieldSpecifier\n\tScopeFieldCount      uint16\n\tScopeFieldSpecifiers []TemplateFieldSpecifier\n}\n\n\/\/ TemplateFieldSpecifier represents field properties\ntype TemplateFieldSpecifier struct {\n\tElementID    uint16\n\tLength       uint16\n\tEnterpriseNo uint32\n}\n\n\/\/ Message represents IPFIX decoded data\ntype Message struct {\n\tAgentID  string\n\tHeader   MessageHeader\n\tDataSets [][]DecodedField\n}\n\n\/\/ DecodedField represents a decoded field\ntype DecodedField struct {\n\tID    uint16\n\tValue interface{}\n}\n\n\/\/ SetHeader represents set header fields\ntype SetHeader struct {\n\tSetID  uint16\n\tLength uint16\n}\n\nvar (\n\trpcChan = make(chan RPCRequest, 1)\n\n\terrInvalidVersion    = errors.New(\"invalid ipfix version\")\n\terrUnknownTemplateID = errors.New(\"unknown template id\")\n)\n\n\/\/ NewDecoder constructs a decoder\nfunc NewDecoder(raddr net.IP, b []byte) *Decoder {\n\treturn &Decoder{raddr, NewReader(b)}\n}\n\n\/\/ Decode decodes the IPFIX raw data\nfunc (d *Decoder) Decode(mem MemCache) (*Message, error) {\n\tvar (\n\t\tmsg = new(Message)\n\t\terr error\n\t)\n\n\t\/\/ IPFIX Message Header decoding\n\tif err = msg.Header.unmarshal(d.reader); err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ IPFIX Message Header validation\n\tif err = msg.Header.validate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Add source IP address as Agent ID\n\tmsg.AgentID = d.raddr.String()\n\n\tfor d.reader.Len() > 4 {\n\n\t\tsetHeader := new(SetHeader)\n\t\tsetHeader.unmarshal(d.reader)\n\n\t\tif setHeader.Length < 4 {\n\t\t\treturn nil, io.ErrUnexpectedEOF\n\t\t}\n\n\t\tswitch {\n\t\tcase setHeader.SetID == 2:\n\t\t\t\/\/ Template set\n\t\t\ttr := TemplateRecords{}\n\t\t\ttr.unmarshal(d.reader)\n\t\t\tmem.insert(tr.TemplateID, d.raddr, tr)\n\t\tcase setHeader.SetID == 3:\n\t\t\t\/\/ Option set\n\t\t\ttr := TemplateRecords{}\n\t\t\ttr.unmarshalOpts(d.reader)\n\t\t\tmem.insert(tr.TemplateID, d.raddr, tr)\n\t\tcase setHeader.SetID >= 4 && setHeader.SetID <= 255:\n\t\t\t\/\/ Reserved\n\t\tdefault:\n\t\t\t\/\/ data\n\t\t\tfor d.reader.Len() > 0 {\n\t\t\t\ttr, ok := mem.retrieve(setHeader.SetID, d.raddr)\n\t\t\t\tif !ok {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase rpcChan <- RPCRequest{\n\t\t\t\t\t\tID: setHeader.SetID,\n\t\t\t\t\t\tIP: d.raddr,\n\t\t\t\t\t}:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t\treturn msg, errUnknownTemplateID\n\t\t\t\t}\n\n\t\t\t\tdata := decodeData(d.reader, tr)\n\t\t\t\tmsg.DataSets = append(msg.DataSets, data)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn msg, nil\n}\n\n\/\/ RFC 7011 - part 3.1. Message Header Format\n\/\/ 0                   1                   2                   3\n\/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |       Version Number          |            Length             |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |                           Export Time                         |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |                       Sequence Number                         |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |                    Observation Domain ID                      |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (h *MessageHeader) unmarshal(r *Reader) error {\n\tvar err error\n\n\tif h.Version, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif h.Length, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif h.ExportTime, err = r.Uint32(); err != nil {\n\t\treturn err\n\t}\n\n\tif h.SequenceNo, err = r.Uint32(); err != nil {\n\t\treturn err\n\t}\n\n\tif h.DomainID, err = r.Uint32(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (h *MessageHeader) validate() error {\n\tif h.Version != 0x000a {\n\t\treturn errInvalidVersion\n\t}\n\n\t\/\/ TODO: needs more validation\n\n\treturn nil\n}\n\n\/\/ RFC 7011 - part 3.3.2 Set Header Format\n\/\/ 0                   1                   2                   3\n\/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |          Set ID               |          Length               |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (h *SetHeader) unmarshal(r *Reader) error {\n\tvar err error\n\n\tif h.SetID, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif h.Length, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ RFC 7011\n\/\/ 0                   1                   2                   3\n\/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |       Set ID = (2 or 3)       |          Length               |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |         Template ID           |         Field Count           |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (t *TemplateHeader) unmarshal(r *Reader) error {\n\tvar err error\n\n\tif t.TemplateID, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif t.FieldCount, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}\n\n\/\/ RFC 7011 3.4.2.2.  Options Template Record Format\n\/\/ 0                   1                   2                   3\n\/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |          Set ID = 3           |          Length               |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |         Template ID           |         Field Count = N + M   |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |     Scope Field Count = N     |0|  Scope 1 Infor. Element id. |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (t *TemplateHeader) unmarshalOpts(r *Reader) error {\n\tvar err error\n\n\tif t.TemplateID, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif t.FieldCount, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif t.ScopeFieldCount, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}\n\n\/\/ RFC 7011\n\/\/ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |E|  Information Element ident. |        Field Length           |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |                      Enterprise Number                        |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (f *TemplateFieldSpecifier) unmarshal(r *Reader) error {\n\tvar err error\n\n\tif f.ElementID, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif f.Length, err = r.Uint16(); err != nil {\n\t\treturn err\n\t}\n\n\tif f.ElementID > 0x8000 {\n\t\tf.ElementID = f.ElementID & 0x7fff\n\t\tif f.EnterpriseNo, err = r.Uint32(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/  0                   1                   2                   3\n\/\/  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |          Set ID = 2           |          Length               |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |      Template ID = 256        |         Field Count = N       |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |1| Information Element id. 1.1 |        Field Length 1.1       |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |                    Enterprise Number  1.1                     |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |0| Information Element id. 1.2 |        Field Length 1.2       |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ |             ...               |              ...              |\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (tr *TemplateRecords) unmarshal(r *Reader) {\n\tvar (\n\t\tth = TemplateHeader{}\n\t\ttf = TemplateFieldSpecifier{}\n\t)\n\n\tth.unmarshal(r)\n\ttr.TemplateID = th.TemplateID\n\ttr.FieldCount = th.FieldCount\n\n\tfor i := th.FieldCount; i > 0; i-- {\n\t\ttf.unmarshal(r)\n\t\ttr.FieldSpecifiers = append(tr.FieldSpecifiers, tf)\n\t}\n}\n\n\/\/  0                   1                   2                   3\n\/\/  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n\/\/ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |          Set ID = 3           |          Length               |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |         Template ID = X       |         Field Count = N + M   |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |     Scope Field Count = N     |0|  Scope 1 Infor. Element id. |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |     Scope 1 Field Length      |0|  Scope 2 Infor. Element id. |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |     Scope 2 Field Length      |             ...               |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |            ...                |1|  Scope N Infor. Element id. |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |     Scope N Field Length      |   Scope N Enterprise Number  ...\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ ...  Scope N Enterprise Number   |1| Option 1 Infor. Element id. |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |    Option 1 Field Length      |  Option 1 Enterprise Number  ...\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/ ... Option 1 Enterprise Number   |              ...              |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |             ...               |0| Option M Infor. Element id. |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\/\/  |     Option M Field Length     |      Padding (optional)       |\n\/\/  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nfunc (tr *TemplateRecords) unmarshalOpts(r *Reader) {\n\tvar (\n\t\tth = TemplateHeader{}\n\t\ttf = TemplateFieldSpecifier{}\n\t)\n\n\tth.unmarshalOpts(r)\n\ttr.TemplateID = th.TemplateID\n\ttr.FieldCount = th.FieldCount\n\ttr.ScopeFieldCount = th.ScopeFieldCount\n\n\tfor i := th.ScopeFieldCount; i > 0; i-- {\n\t\ttf.unmarshal(r)\n\t\ttr.ScopeFieldSpecifiers = append(tr.FieldSpecifiers, tf)\n\t}\n\n\tfor i := th.FieldCount - th.ScopeFieldCount; i > 0; i-- {\n\t\ttf.unmarshal(r)\n\t\ttr.FieldSpecifiers = append(tr.FieldSpecifiers, tf)\n\t}\n}\n\nfunc decodeData(r *Reader, tr TemplateRecords) []DecodedField {\n\tvar (\n\t\tfields []DecodedField\n\t\tb      []byte\n\t)\n\n\tfor i := 0; i < len(tr.FieldSpecifiers); i++ {\n\t\tb, _ = r.Read(int(tr.FieldSpecifiers[i].Length))\n\t\tm := ipfixInfoModel[elementKey{\n\t\t\ttr.FieldSpecifiers[i].EnterpriseNo,\n\t\t\ttr.FieldSpecifiers[i].ElementID,\n\t\t}]\n\t\tfields = append(fields, DecodedField{\n\t\t\tID:    m.FieldID,\n\t\t\tValue: interpret(b, m.Type),\n\t\t})\n\t}\n\n\treturn fields\n}\n<|endoftext|>"}
{"text":"<commit_before>package httpcache\n\nimport (\n\t\"github.com\/lostisland\/go-sawyer\"\n\t\"github.com\/lostisland\/go-sawyer\/hypermedia\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\nconst (\n\tresponseFilename = \"response\"\n\tbodyFilename     = \"body\"\n\tfileCreateFlag   = os.O_RDWR | os.O_CREATE | os.O_EXCL\n)\n\ntype FileCache struct {\n\tpath string\n}\n\nfunc NewFileCache(path string) *FileCache {\n\treturn &FileCache{path}\n}\n\nfunc (c *FileCache) Get(req *http.Request, v interface{}) *sawyer.Response {\n\tpath := c.requestPath(req)\n\n\tresponseFile, err := os.Open(filepath.Join(path, responseFilename))\n\tif err != nil {\n\t\treturn ResponseError(err)\n\t}\n\tdefer responseFile.Close()\n\n\tbodyFile, err := os.Open(filepath.Join(path, bodyFilename))\n\tif err != nil {\n\t\treturn ResponseError(err)\n\t}\n\tdefer bodyFile.Close()\n\n\treturn DecodeFrom(v, responseFile, bodyFile)\n}\n\nfunc (c *FileCache) Set(req *http.Request, res *sawyer.Response, v interface{}) error {\n\tpath := c.requestPath(req)\n\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\treturn err\n\t}\n\n\tresponseFile, err := os.OpenFile(filepath.Join(path, responseFilename), fileCreateFlag, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer responseFile.Close()\n\n\tbodyFile, err := os.OpenFile(filepath.Join(path, bodyFilename), fileCreateFlag, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer bodyFile.Close()\n\n\treturn EncodeTo(v, res, responseFile, bodyFile)\n}\n\nfunc (c *FileCache) Rels(req *http.Request) hypermedia.Relations {\n\tpath := c.requestPath(req)\n\n\tresponseFile, err := os.Create(filepath.Join(path, responseFilename))\n\tif err != nil {\n\t\treturn hypermedia.Relations{}\n\t}\n\tdefer responseFile.Close()\n\n\treturn Decode(responseFile).Rels\n}\n\nfunc (c *FileCache) requestPath(r *http.Request) string {\n\treturn filepath.Join(c.path, RequestSha(r))\n}\n<commit_msg>write the actual key so you can see what the requests are<commit_after>package httpcache\n\nimport (\n\t\"github.com\/lostisland\/go-sawyer\"\n\t\"github.com\/lostisland\/go-sawyer\/hypermedia\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\nconst (\n\tkeyFilename      = \"key\"\n\tresponseFilename = \"response\"\n\tbodyFilename     = \"body\"\n\tfileCreateFlag   = os.O_RDWR | os.O_CREATE | os.O_EXCL\n)\n\ntype FileCache struct {\n\tpath string\n}\n\nfunc NewFileCache(path string) *FileCache {\n\treturn &FileCache{path}\n}\n\nfunc (c *FileCache) Get(req *http.Request, v interface{}) *sawyer.Response {\n\tpath := c.requestPath(req)\n\n\tresponseFile, err := os.Open(filepath.Join(path, responseFilename))\n\tif err != nil {\n\t\treturn ResponseError(err)\n\t}\n\tdefer responseFile.Close()\n\n\tbodyFile, err := os.Open(filepath.Join(path, bodyFilename))\n\tif err != nil {\n\t\treturn ResponseError(err)\n\t}\n\tdefer bodyFile.Close()\n\n\treturn DecodeFrom(v, responseFile, bodyFile)\n}\n\nfunc (c *FileCache) Set(req *http.Request, res *sawyer.Response, v interface{}) error {\n\tpath := c.requestPath(req)\n\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\treturn err\n\t}\n\n\tkeyFile, err := os.OpenFile(filepath.Join(path, keyFilename), fileCreateFlag, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer keyFile.Close()\n\tkeyFile.Write([]byte(RequestKey(req)))\n\n\tresponseFile, err := os.OpenFile(filepath.Join(path, responseFilename), fileCreateFlag, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer responseFile.Close()\n\n\tbodyFile, err := os.OpenFile(filepath.Join(path, bodyFilename), fileCreateFlag, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer bodyFile.Close()\n\n\treturn EncodeTo(v, res, responseFile, bodyFile)\n}\n\nfunc (c *FileCache) Rels(req *http.Request) hypermedia.Relations {\n\tpath := c.requestPath(req)\n\n\tresponseFile, err := os.Create(filepath.Join(path, responseFilename))\n\tif err != nil {\n\t\treturn hypermedia.Relations{}\n\t}\n\tdefer responseFile.Close()\n\n\treturn Decode(responseFile).Rels\n}\n\nfunc (c *FileCache) requestPath(r *http.Request) string {\n\treturn filepath.Join(c.path, RequestSha(r))\n}\n<|endoftext|>"}
{"text":"<commit_before>package httpcheck\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Method int\n\nconst (\n\tGET Method = iota\n\tPOST\n)\n\n\/\/ A single HTTP action, with the expected results.\ntype Test struct {\n\tUrl           string            \/\/ A fully specified URL including the protocol\n\tContent       string            \",omitempty\" \/\/ Expected content as a regexp, e.g. \"Hello World\"\n\tCode          int               \",omitempty\" \/\/ Expected HTTP response code\n\tMethod        Method            \",omitempty\" \/\/ HTTP method, i.e. GET (default) or POST\n\tData          string            \",omitempty\" \/\/ Optional post data\n\tHeaders       map[string]string \",omitempty\" \/\/ Optional headers to add to the request\n\tSkipSSLVerify bool              \",omitempty\" \/\/ If true, SSL server verification is skipped\n}\n\n\/\/ Test makes a HTTP call and checks the response\nfunc (t Test) Test() (err error) {\n\terr = t.Validate()\n\n\tvar code int\n\tvar body string\n\tif err == nil {\n\t\tcode, body, err = t.DoRequest()\n\t}\n\tif err == nil {\n\t\terr = t.CheckCode(code)\n\t}\n\tif err == nil {\n\t\terr = t.CheckContent(body)\n\t}\n\n\t\/\/ Log an error\n\tif Verbose {\n\t\tif err == nil {\n\t\t\tfmt.Println(t.String() + \" OK\")\n\t\t} else {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n\treturn\n}\n\nfunc (t Test) Validate() error {\n\tscheme := regexp.MustCompile(\"^https?:\")\n\tif !scheme.MatchString(t.Url) {\n\t\treturn errors.New(\"URL is not absolute, must specify a base URL (-u): \" + t.Url)\n\t}\n\treturn nil\n}\n\n\/\/ DoRequest uses the global http object to send a HTTP request\nfunc (t Test) DoRequest() (code int, body string, err error) {\n\treq, err := http.NewRequest(t.MethodName(), t.Url, strings.NewReader(t.Data))\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\n\treq.Header.Add(\"User-Agent\", version)\n\tif t.Method == POST {\n\t\treq.Header.Add(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\t}\n\tfor k, v := range t.Headers {\n\t\treq.Header.Add(k, v)\n\t}\n\n\tclient.Timeout = time.Duration(int(RequestTimeout)) * time.Second\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\n\trcvdbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\tbody = string(rcvdbytes)\n\tcode = resp.StatusCode\n\n\tdefer resp.Body.Close()\n\n\treturn code, body, nil\n}\n\n\/\/ CheckCode inspects the received HTTP response code\nfunc (t Test) CheckCode(code int) error {\n\texpect := t.Code\n\tif expect == 0 {\n\t\texpect = 200\n\t}\n\tif code != expect {\n\t\treturn t.NewError(\"Expected status code \" + strconv.Itoa(expect) + \", received \" + strconv.Itoa(code))\n\t}\n\treturn nil\n}\n\n\/\/ CheckContent inspects the returned HTTP response body\nfunc (t Test) CheckContent(body string) error {\n\tif t.Content == \"\" {\n\t\treturn nil\n\t}\n\n\tmatch, err := regexp.MatchString(t.Content, body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !match {\n\t\treturn t.NewError(\"Expected content '\" + t.Content + \"', not found in response (\" + strconv.Itoa(len(body)) + \" bytes)\")\n\t}\n\n\treturn nil\n}\n\nfunc (t Test) NewError(message string) error {\n\treturn errors.New(t.String() + \" FAIL: \" + message)\n}\n\nfunc (t Test) String() string {\n\treturn strings.Title(strings.ToLower(t.MethodName())) + \" \" + t.Url\n}\n\nfunc (t Test) MethodName() string {\n\tswitch t.Method {\n\tcase GET:\n\t\treturn \"GET\"\n\tcase POST:\n\t\treturn \"POST\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n<commit_msg>test: change method from int to string to allow any user-specified method<commit_after>package httpcheck\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Method int\n\n\/\/ A single HTTP action, with the expected results.\ntype Test struct {\n\tUrl           string            \/\/ A fully specified URL including the protocol\n\tContent       string            \",omitempty\" \/\/ Expected content as a regexp, e.g. \"Hello World\"\n\tCode          int               \",omitempty\" \/\/ Expected HTTP response code\n\tMethod        string            \",omitempty\" \/\/ HTTP method, i.e. \"GET\" (default) or \"POST\"\n\tData          string            \",omitempty\" \/\/ Optional post data\n\tHeaders       map[string]string \",omitempty\" \/\/ Optional headers to add to the request\n\tSkipSSLVerify bool              \",omitempty\" \/\/ If true, SSL server verification is skipped\n}\n\n\/\/ Test makes a HTTP call and checks the response\nfunc (t Test) Test() (err error) {\n\terr = t.Validate()\n\n\tvar code int\n\tvar body string\n\tif err == nil {\n\t\tcode, body, err = t.DoRequest()\n\t}\n\tif err == nil {\n\t\terr = t.CheckCode(code)\n\t}\n\tif err == nil {\n\t\terr = t.CheckContent(body)\n\t}\n\n\t\/\/ Log an error\n\tif Verbose {\n\t\tif err == nil {\n\t\t\tfmt.Println(t.String() + \" OK\")\n\t\t} else {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n\treturn\n}\n\nfunc (t Test) Validate() error {\n\tscheme := regexp.MustCompile(\"^https?:\")\n\tif !scheme.MatchString(t.Url) {\n\t\treturn errors.New(\"URL is not absolute, must specify a base URL (-u): \" + t.Url)\n\t}\n\treturn nil\n}\n\n\/\/ DoRequest uses the global http object to send a HTTP request\nfunc (t Test) DoRequest() (code int, body string, err error) {\n\treq, err := http.NewRequest(t.MethodName(), t.Url, strings.NewReader(t.Data))\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\n\treq.Header.Add(\"User-Agent\", version)\n\tif t.Method == \"POST\" {\n\t\treq.Header.Add(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\t}\n\tfor k, v := range t.Headers {\n\t\treq.Header.Add(k, v)\n\t}\n\n\tclient.Timeout = time.Duration(int(RequestTimeout)) * time.Second\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\n\trcvdbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn 0, \"\", err\n\t}\n\tbody = string(rcvdbytes)\n\tcode = resp.StatusCode\n\n\tdefer resp.Body.Close()\n\n\treturn code, body, nil\n}\n\n\/\/ CheckCode inspects the received HTTP response code\nfunc (t Test) CheckCode(code int) error {\n\texpect := t.Code\n\tif expect == 0 {\n\t\texpect = 200\n\t}\n\tif code != expect {\n\t\treturn t.NewError(\"Expected status code \" + strconv.Itoa(expect) + \", received \" + strconv.Itoa(code))\n\t}\n\treturn nil\n}\n\n\/\/ CheckContent inspects the returned HTTP response body\nfunc (t Test) CheckContent(body string) error {\n\tif t.Content == \"\" {\n\t\treturn nil\n\t}\n\n\tmatch, err := regexp.MatchString(t.Content, body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !match {\n\t\treturn t.NewError(\"Expected content '\" + t.Content + \"', not found in response (\" + strconv.Itoa(len(body)) + \" bytes)\")\n\t}\n\n\treturn nil\n}\n\nfunc (t Test) NewError(message string) error {\n\treturn errors.New(t.String() + \" FAIL: \" + message)\n}\n\nfunc (t Test) String() string {\n\treturn strings.Title(strings.ToLower(t.MethodName())) + \" \" + t.Url\n}\n\nfunc (t Test) MethodName() string {\n\tif t.Method == \"\" {\n\t\treturn \"GET\"\n\t}\n\treturn t.Method\n}\n<|endoftext|>"}
{"text":"<commit_before>package httpcheck\n\nimport (\n\t\"encoding\/json\"\n\t\"encoding\/xml\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"net\/http\"\n\t\"testing\"\n)\n\ntype testPerson struct {\n\tName string\n\tAge  int\n}\n\ntype testHandler struct{}\n\nfunc (t *testHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tswitch req.URL.Path {\n\tcase \"\/some\":\n\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\tName:  \"some\",\n\t\t\tValue: \"cookie\",\n\t\t})\n\t\tw.Header().Add(\"some\", \"header\")\n\t\tw.WriteHeader(204)\n\tcase \"\/json\":\n\t\tbody, err := json.Marshal(testPerson{\n\t\t\tName: \"Some\",\n\t\t\tAge:  30,\n\t\t})\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.Write(body)\n\n\tcase \"\/xml\":\n\t\tbody, err := xml.Marshal(testPerson{\n\t\t\tName: \"Some\",\n\t\t\tAge:  30,\n\t\t})\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application\/xml\")\n\t\tw.Write(body)\n\tcase \"\/byte\":\n\t\tw.Write([]byte(\"hello world\"))\n\tcase \"\/nothing\":\n\n\t}\n}\n\nfunc makeTestChecker(t *testing.T) *Checker {\n\thandler := &testHandler{}\n\tport := \":3000\"\n\treturn New(t, handler, port)\n}\n\nfunc TestNew(t *testing.T) {\n\thandler := &testHandler{}\n\taddr := \":3000\"\n\tchecker := New(t, handler, addr)\n\n\tassert.NotNil(t, checker)\n\tassert.Exactly(t, t, checker.t)\n\tassert.Exactly(t, handler, checker.handler)\n\tassert.Exactly(t, addr, checker.addr)\n\tassert.NotNil(t, checker.server)\n}\n\nfunc TestTest(t *testing.T) {\n\tchecker := makeTestChecker(t)\n\tchecker.Test(\"GET\", \"\/some\")\n\n\tassert.NotNil(t, checker.request)\n\tassert.Exactly(t, \"GET\", checker.request.Method)\n\tassert.Exactly(t, \"\/some\", checker.request.URL.Path)\n}\n\nfunc TestRequest(t *testing.T) {\n\tchecker := makeTestChecker(t)\n\trequest := &http.Request{\n\t\tMethod: \"GET\",\n\t}\n\n\tchecker.TestRequest(request)\n\tassert.NotNil(t, checker.request)\n\tassert.Exactly(t, \"GET\", checker.request.Method)\n\tassert.Nil(t, checker.request.URL)\n}\n\nfunc TestWithHeader(t *testing.T) {\n\tchecker := makeTestChecker(t)\n\tchecker.Test(\"GET\", \"\/some\")\n\n\tchecker.WithHeader(\"key\", \"value\")\n\n\tassert.Equal(t, checker.request.Header.Get(\"key\"), \"value\")\n\tassert.Equal(t, \"\", checker.request.Header.Get(\"unknown\"))\n}\n\nfunc TestWithCookie(t *testing.T) {\n\tchecker := makeTestChecker(t)\n\tchecker.Test(\"GET\", \"\/some\")\n\n\tchecker.WithCookie(\"key\", \"value\")\n\n\tcookie, err := checker.request.Cookie(\"key\")\n\tassert.Nil(t, err)\n\tassert.Equal(t, cookie.Value, \"value\")\n\n\tcookie, err = checker.request.Cookie(\"unknown\")\n\tassert.NotNil(t, err)\n}\n\nfunc TestCheck(t *testing.T) {\n\tchecker := makeTestChecker(t)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tassert.NotNil(t, checker.response)\n\tassert.Exactly(t, 204, checker.response.StatusCode)\n}\n\nfunc TestHasStatus(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasStatus(202)\n\tassert.True(t, mockT.Failed())\n\n\tmockT = new(testing.T)\n\tchecker = makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasStatus(204)\n\tassert.False(t, mockT.Failed())\n}\n\nfunc TestHasHeader(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasHeader(\"some\", \"header\")\n\tassert.False(t, mockT.Failed())\n\n\tmockT = new(testing.T)\n\tchecker = makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasHeader(\"some\", \"unknown\")\n\tassert.True(t, mockT.Failed())\n\n\tmockT = new(testing.T)\n\tchecker = makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasHeader(\"unknown\", \"header\")\n\tassert.True(t, mockT.Failed())\n}\n\nfunc TestHasCookie(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasCookie(\"some\", \"cookie\")\n\tassert.False(t, mockT.Failed())\n\n\tmockT = new(testing.T)\n\tchecker = makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasCookie(\"some\", \"unknown\")\n\tassert.True(t, mockT.Failed())\n\n\tmockT = new(testing.T)\n\tchecker = makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasCookie(\"unknown\", \"cookie\")\n\tassert.True(t, mockT.Failed())\n}\n\nfunc TestHasJson(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/json\")\n\tchecker.Check()\n\n\tperson := &testPerson{\n\t\tName: \"Some\",\n\t\tAge:  30,\n\t}\n\tchecker.HasJson(person)\n\tassert.False(t, mockT.Failed())\n\n\tperson = &testPerson{\n\t\tName: \"Unknown\",\n\t\tAge:  30,\n\t}\n\tchecker.HasJson(person)\n\tassert.True(t, mockT.Failed())\n}\n\nfunc TestHasXml(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/xml\")\n\tchecker.Check()\n\n\tperson := &testPerson{\n\t\tName: \"Some\",\n\t\tAge:  30,\n\t}\n\tchecker.HasXml(person)\n\tassert.False(t, mockT.Failed())\n\n\tperson = &testPerson{\n\t\tName: \"Unknown\",\n\t\tAge:  30,\n\t}\n\tchecker.HasXml(person)\n\tassert.True(t, mockT.Failed())\n}\n\nfunc TestHasBody(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/byte\")\n\tchecker.Check()\n\n\tchecker.HasBody([]byte(\"hello world\"))\n}\n\nfunc TestCb(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/json\")\n\tchecker.Check()\n\n\tcalled := false\n\tchecker.Cb(func(response *http.Response) {\n\t\tcalled = true\n\t})\n\n\tassert.True(t, called)\n}\n\nfunc TestCookies(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.PersistCookie(\"some\")\n\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasCookie(\"some\", \"cookie\")\n\tassert.False(t, mockT.Failed())\n\n\tchecker.Test(\"GET\", \"\/nothing\")\n\tchecker.Check()\n\n\tchecker.HasCookie(\"some\", \"cookie\")\n\tassert.False(t, mockT.Failed())\n}\n\nfunc TestCookiesDelete(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasCookie(\"some\", \"cookie\")\n\tassert.False(t, mockT.Failed())\n\n\tchecker.Test(\"GET\", \"\/nothing\")\n\tchecker.Check()\n\n\tchecker.HasCookie(\"some\", \"cookie\")\n\tassert.True(t, mockT.Failed())\n}\n<commit_msg>refactor tests<commit_after>package httpcheck\n\nimport (\n\t\"encoding\/json\"\n\t\"encoding\/xml\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"net\/http\"\n\t\"testing\"\n)\n\ntype testPerson struct {\n\tName string\n\tAge  int\n}\n\ntype testHandler struct{}\n\nfunc (t *testHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tswitch req.URL.Path {\n\tcase \"\/some\":\n\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\tName:  \"some\",\n\t\t\tValue: \"cookie\",\n\t\t})\n\t\tw.Header().Add(\"some\", \"header\")\n\t\tw.WriteHeader(204)\n\tcase \"\/json\":\n\t\tbody, err := json.Marshal(testPerson{\n\t\t\tName: \"Some\",\n\t\t\tAge:  30,\n\t\t})\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.Write(body)\n\n\tcase \"\/xml\":\n\t\tbody, err := xml.Marshal(testPerson{\n\t\t\tName: \"Some\",\n\t\t\tAge:  30,\n\t\t})\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application\/xml\")\n\t\tw.Write(body)\n\tcase \"\/byte\":\n\t\tw.Write([]byte(\"hello world\"))\n\tcase \"\/cookies\":\n\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\tName:  \"some\",\n\t\t\tValue: \"cookie\",\n\t\t})\n\t\thttp.SetCookie(w, &http.Cookie{\n\t\t\tName:  \"other\",\n\t\t\tValue: \"secondcookie\",\n\t\t})\n\tcase \"\/nothing\":\n\n\t}\n}\n\nfunc makeTestChecker(t *testing.T) *Checker {\n\thandler := &testHandler{}\n\tport := \":3000\"\n\treturn New(t, handler, port)\n}\n\nfunc TestNew(t *testing.T) {\n\thandler := &testHandler{}\n\taddr := \":3000\"\n\tchecker := New(t, handler, addr)\n\n\tassert.NotNil(t, checker)\n\tassert.Exactly(t, t, checker.t)\n\tassert.Exactly(t, handler, checker.handler)\n\tassert.Exactly(t, addr, checker.addr)\n\tassert.NotNil(t, checker.server)\n}\n\nfunc TestTest(t *testing.T) {\n\tchecker := makeTestChecker(t)\n\tchecker.Test(\"GET\", \"\/some\")\n\n\tassert.NotNil(t, checker.request)\n\tassert.Exactly(t, \"GET\", checker.request.Method)\n\tassert.Exactly(t, \"\/some\", checker.request.URL.Path)\n}\n\nfunc TestRequest(t *testing.T) {\n\tchecker := makeTestChecker(t)\n\trequest := &http.Request{\n\t\tMethod: \"GET\",\n\t}\n\n\tchecker.TestRequest(request)\n\tassert.NotNil(t, checker.request)\n\tassert.Exactly(t, \"GET\", checker.request.Method)\n\tassert.Nil(t, checker.request.URL)\n}\n\nfunc TestWithHeader(t *testing.T) {\n\tchecker := makeTestChecker(t)\n\tchecker.Test(\"GET\", \"\/some\")\n\n\tchecker.WithHeader(\"key\", \"value\")\n\n\tassert.Equal(t, checker.request.Header.Get(\"key\"), \"value\")\n\tassert.Equal(t, \"\", checker.request.Header.Get(\"unknown\"))\n}\n\nfunc TestWithCookie(t *testing.T) {\n\tchecker := makeTestChecker(t)\n\tchecker.Test(\"GET\", \"\/some\")\n\n\tchecker.WithCookie(\"key\", \"value\")\n\n\tcookie, err := checker.request.Cookie(\"key\")\n\tassert.Nil(t, err)\n\tassert.Equal(t, cookie.Value, \"value\")\n\n\tcookie, err = checker.request.Cookie(\"unknown\")\n\tassert.NotNil(t, err)\n}\n\nfunc TestCheck(t *testing.T) {\n\tchecker := makeTestChecker(t)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tassert.NotNil(t, checker.response)\n\tassert.Exactly(t, 204, checker.response.StatusCode)\n}\n\nfunc TestHasStatus(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasStatus(202)\n\tassert.True(t, mockT.Failed())\n\n\tmockT = new(testing.T)\n\tchecker = makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasStatus(204)\n\tassert.False(t, mockT.Failed())\n}\n\nfunc TestHasHeader(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasHeader(\"some\", \"header\")\n\tassert.False(t, mockT.Failed())\n\n\tmockT = new(testing.T)\n\tchecker = makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasHeader(\"some\", \"unknown\")\n\tassert.True(t, mockT.Failed())\n\n\tmockT = new(testing.T)\n\tchecker = makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasHeader(\"unknown\", \"header\")\n\tassert.True(t, mockT.Failed())\n}\n\nfunc TestHasCookie(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasCookie(\"some\", \"cookie\")\n\tassert.False(t, mockT.Failed())\n\n\tmockT = new(testing.T)\n\tchecker = makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasCookie(\"some\", \"unknown\")\n\tassert.True(t, mockT.Failed())\n\n\tmockT = new(testing.T)\n\tchecker = makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/some\")\n\tchecker.Check()\n\n\tchecker.HasCookie(\"unknown\", \"cookie\")\n\tassert.True(t, mockT.Failed())\n}\n\nfunc TestHasJson(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/json\")\n\tchecker.Check()\n\n\tperson := &testPerson{\n\t\tName: \"Some\",\n\t\tAge:  30,\n\t}\n\tchecker.HasJson(person)\n\tassert.False(t, mockT.Failed())\n\n\tperson = &testPerson{\n\t\tName: \"Unknown\",\n\t\tAge:  30,\n\t}\n\tchecker.HasJson(person)\n\tassert.True(t, mockT.Failed())\n}\n\nfunc TestHasXml(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/xml\")\n\tchecker.Check()\n\n\tperson := &testPerson{\n\t\tName: \"Some\",\n\t\tAge:  30,\n\t}\n\tchecker.HasXml(person)\n\tassert.False(t, mockT.Failed())\n\n\tperson = &testPerson{\n\t\tName: \"Unknown\",\n\t\tAge:  30,\n\t}\n\tchecker.HasXml(person)\n\tassert.True(t, mockT.Failed())\n}\n\nfunc TestHasBody(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/byte\")\n\tchecker.Check()\n\n\tchecker.HasBody([]byte(\"hello world\"))\n}\n\nfunc TestCb(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.Test(\"GET\", \"\/json\")\n\tchecker.Check()\n\n\tcalled := false\n\tchecker.Cb(func(response *http.Response) {\n\t\tcalled = true\n\t})\n\n\tassert.True(t, called)\n}\n\nfunc TestCookies(t *testing.T) {\n\tmockT := new(testing.T)\n\tchecker := makeTestChecker(mockT)\n\tchecker.PersistCookie(\"some\")\n\n\tchecker.Test(\"GET\", \"\/cookies\")\n\tchecker.Check()\n\n\tchecker.HasCookie(\"some\", \"cookie\")\n\tchecker.HasCookie(\"other\", \"secondcookie\")\n\tassert.False(t, mockT.Failed())\n\n\tchecker.Test(\"GET\", \"\/nothing\")\n\tchecker.Check()\n\n\tchecker.HasCookie(\"some\", \"cookie\")\n\tassert.False(t, mockT.Failed())\n\n\tchecker.HasCookie(\"other\", \"secondcookie\")\n\tassert.True(t, mockT.Failed())\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012-2014 Jeremy Latt\n\/\/ Copyright (c) 2014-2015 Edmund Huber\n\/\/ Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>\n\/\/ released under the MIT license\n\npackage irc\n\nimport \"fmt\"\n\nconst (\n\t\/\/ SemVer is the semantic version of Oragono.\n\tSemVer = \"1.3.0-unreleased\"\n)\n\nvar (\n\t\/\/ Commit is the current git commit.\n\tCommit = \"\"\n\n\t\/\/ Ver is the full version of Oragono, used in responses to clients.\n\tVer = fmt.Sprintf(\"oragono-%s\", SemVer)\n\n\t\/\/ maxLastArgLength is used to simply cap off the final argument when creating general messages where we need to select a limit.\n\t\/\/ for instance, in MONITOR lists, RPL_ISUPPORT lists, etc.\n\tmaxLastArgLength = 400\n\t\/\/ maxTargets is the maximum number of targets for PRIVMSG and NOTICE.\n\tmaxTargets = 4\n)\n<commit_msg>bump version to 2.0.0-rc1<commit_after>\/\/ Copyright (c) 2012-2014 Jeremy Latt\n\/\/ Copyright (c) 2014-2015 Edmund Huber\n\/\/ Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>\n\/\/ released under the MIT license\n\npackage irc\n\nimport \"fmt\"\n\nconst (\n\t\/\/ SemVer is the semantic version of Oragono.\n\tSemVer = \"2.0.0-rc1\"\n)\n\nvar (\n\t\/\/ Commit is the current git commit.\n\tCommit = \"\"\n\n\t\/\/ Ver is the full version of Oragono, used in responses to clients.\n\tVer = fmt.Sprintf(\"oragono-%s\", SemVer)\n\n\t\/\/ maxLastArgLength is used to simply cap off the final argument when creating general messages where we need to select a limit.\n\t\/\/ for instance, in MONITOR lists, RPL_ISUPPORT lists, etc.\n\tmaxLastArgLength = 400\n\t\/\/ maxTargets is the maximum number of targets for PRIVMSG and NOTICE.\n\tmaxTargets = 4\n)\n<|endoftext|>"}
{"text":"<commit_before>package sup\n\n\/*\n\tThe maintainence actor.\n\n\tYour controller strategy code is running in another goroutine.  This one\n\tis in charge of operations like collecting child status, and is\n\tpurely internal so it can reliably handle its own blocking behavior.\n*\/\nfunc (svr *Supervisor) supmgr_actor() {\n\tstepFn := svr.supmgr_stepAccepting\n\tfor {\n\t\tif stepFn == nil {\n\t\t\tbreak\n\t\t}\n\t\tstepFn = stepFn()\n\t}\n}\n\n\/*\n\tSteps in the state machine of the supervisor's internal maint.\n\n\tThis pattern is awfully nice:\n\t  - you can see the transitions by clear name (returns highlight them)\n\t  - you *don't* see the visual clutter of code for transitions that are\n\t     not possible for whatever state you're currently looking at\n\t  - even if things really go poorly, your stack trace clearly indicates\n\t     exactly which state you were in (it's in the function name after all).\n*\/\ntype supmgr_step func() supmgr_step\n\nfunc (svr *Supervisor) supmgr_stepAccepting() supmgr_step {\n\tselect {\n\tcase reqSpawn := <-svr.ctrlChan_spawn:\n\t\tctrlr := newController()\n\t\tsvr.wards[ctrlr] = ctrlr\n\t\tctrlr.doneLatch.WaitSelectably(svr.childBellcord)\n\t\tgo func() {\n\t\t\tdefer ctrlr.doneLatch.Trigger()\n\t\t\treqSpawn.fn(ctrlr)\n\t\t}()\n\t\treqSpawn.ret <- ctrlr\n\t\treturn svr.supmgr_stepAccepting\n\n\tcase childDone := <-svr.childBellcord:\n\t\tdelete(svr.wards, childDone.(*controller))\n\t\treturn svr.supmgr_stepAccepting\n\n\tcase <-svr.ctrlChan_winddown:\n\t\tif len(svr.wards) == 0 {\n\t\t\treturn svr.supmgr_stepTerminated\n\t\t}\n\t\treturn svr.supmgr_stepWinddown\n\t}\n\tpanic(\"go-sup bug: missing transition\")\n}\n\nfunc (svr *Supervisor) supmgr_stepWinddown() supmgr_step {\n\tselect {\n\tcase _ = <-svr.ctrlChan_spawn:\n\t\tpanic(\"supervisor already winding down\") \/\/ TODO return a witness with an insta error instead?\n\t\treturn svr.supmgr_stepWinddown\n\tcase childDone := <-svr.childBellcord:\n\t\tdelete(svr.wards, childDone.(*controller))\n\t\tif len(svr.wards) == 0 {\n\t\t\treturn svr.supmgr_stepTerminated\n\t\t}\n\t\treturn svr.supmgr_stepWinddown\n\tcase <-svr.ctrlChan_winddown:\n\t\tpanic(\"go-sup bug, winddown transition cannot occur twice\")\n\t}\n\tpanic(\"go-sup bug: missing transition\")\n}\n\nfunc (svr *Supervisor) supmgr_stepTerminated() supmgr_step {\n\t\/\/ can we finally stop selecting?\n\t\/\/ ideally other people shouldn've have *any* writable channels into us\n\t\/\/  that they could possibly block on at this point.\n\tsvr.latch_done.Trigger()\n\treturn nil\n}\n<commit_msg>Move the check for transition to terminated phase to top of winddown (before any selects), which simplifies things enormously since anyone can now transition directly there without duplicating the already-termination-ready check.<commit_after>package sup\n\n\/*\n\tThe maintainence actor.\n\n\tYour controller strategy code is running in another goroutine.  This one\n\tis in charge of operations like collecting child status, and is\n\tpurely internal so it can reliably handle its own blocking behavior.\n*\/\nfunc (svr *Supervisor) supmgr_actor() {\n\tstepFn := svr.supmgr_stepAccepting\n\tfor {\n\t\tif stepFn == nil {\n\t\t\tbreak\n\t\t}\n\t\tstepFn = stepFn()\n\t}\n}\n\n\/*\n\tSteps in the state machine of the supervisor's internal maint.\n\n\tThis pattern is awfully nice:\n\t  - you can see the transitions by clear name (returns highlight them)\n\t  - you *don't* see the visual clutter of code for transitions that are\n\t     not possible for whatever state you're currently looking at\n\t  - even if things really go poorly, your stack trace clearly indicates\n\t     exactly which state you were in (it's in the function name after all).\n*\/\ntype supmgr_step func() supmgr_step\n\nfunc (svr *Supervisor) supmgr_stepAccepting() supmgr_step {\n\tselect {\n\tcase reqSpawn := <-svr.ctrlChan_spawn:\n\t\tctrlr := newController()\n\t\tsvr.wards[ctrlr] = ctrlr\n\t\tctrlr.doneLatch.WaitSelectably(svr.childBellcord)\n\t\tgo func() {\n\t\t\tdefer ctrlr.doneLatch.Trigger()\n\t\t\treqSpawn.fn(ctrlr)\n\t\t}()\n\t\treqSpawn.ret <- ctrlr\n\t\treturn svr.supmgr_stepAccepting\n\n\tcase childDone := <-svr.childBellcord:\n\t\tdelete(svr.wards, childDone.(*controller))\n\t\treturn svr.supmgr_stepAccepting\n\n\tcase <-svr.ctrlChan_winddown:\n\t\treturn svr.supmgr_stepWinddown\n\t}\n\tpanic(\"go-sup bug: missing transition\")\n}\n\nfunc (svr *Supervisor) supmgr_stepWinddown() supmgr_step {\n\tif len(svr.wards) == 0 {\n\t\treturn svr.supmgr_stepTerminated\n\t}\n\tselect {\n\tcase _ = <-svr.ctrlChan_spawn:\n\t\tpanic(\"supervisor already winding down\") \/\/ TODO return a witness with an insta error instead?\n\t\treturn svr.supmgr_stepWinddown\n\tcase childDone := <-svr.childBellcord:\n\t\tdelete(svr.wards, childDone.(*controller))\n\t\treturn svr.supmgr_stepWinddown\n\tcase <-svr.ctrlChan_winddown:\n\t\tpanic(\"go-sup bug, winddown transition cannot occur twice\")\n\t}\n\tpanic(\"go-sup bug: missing transition\")\n}\n\nfunc (svr *Supervisor) supmgr_stepTerminated() supmgr_step {\n\t\/\/ can we finally stop selecting?\n\t\/\/ ideally other people shouldn've have *any* writable channels into us\n\t\/\/  that they could possibly block on at this point.\n\tsvr.latch_done.Trigger()\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/cagedtornado\/centralconfig\/datastores\"\n)\n\nvar (\n\tWsHub = NewHub()\n)\n\nfunc ShowUI(rw http.ResponseWriter, req *http.Request) {\n\thttp.Redirect(rw, req, \"\/ui\/\", 301)\n}\n\n\/\/\tGets a specfic config item based on application and config item name\nfunc GetConfig(rw http.ResponseWriter, req *http.Request) {\n\t\/\/\treq.Body is a ReadCloser -- we need to remember to close it:\n\tdefer req.Body.Close()\n\n\t\/\/\tDecode the request:\n\trequest := datastores.ConfigItem{}\n\terr := json.NewDecoder(req.Body).Decode(request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/\tGet the current datastore:\n\tds := datastores.GetConfigDatastore()\n\n\t\/\/\tSend the request to the datastore and get a response:\n\tresponse, err := ds.Get(request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/\tIf we found an item, return it (otherwise, return an empty item):\n\tconfigItem := datastores.ConfigItem{}\n\tif response.Name != \"\" {\n\t\tconfigItem = response\n\t\tsendDataResponse(rw, \"Config item found\", configItem)\n\t\treturn\n\t}\n\n\tsendDataResponse(rw, \"No config item found with that application and name\", configItem)\n}\n\n\/\/\tSet a specific config item\nfunc SetConfig(rw http.ResponseWriter, req *http.Request) {\n\t\/\/\treq.Body is a ReadCloser -- we need to remember to close it:\n\tdefer req.Body.Close()\n\n\t\/\/\tDecode the request:\n\trequest := datastores.ConfigItem{}\n\terr := json.NewDecoder(req.Body).Decode(request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/\tGet the current datastore:\n\tds := datastores.GetConfigDatastore()\n\n\t\/\/\tSend the request to the datastore and get a response:\n\tresponse, err := ds.Set(request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusInternalServerError)\n\t} else {\n\t\tWsHub.Broadcast <- []byte(getWSResponse(\"Updated\", response))\n\t\tsendDataResponse(rw, \"Config item updated\", response)\n\t}\n}\n\n\/\/\tRemoves a specific config item\nfunc RemoveConfig(rw http.ResponseWriter, req *http.Request) {\n\t\/\/\treq.Body is a ReadCloser -- we need to remember to close it:\n\tdefer req.Body.Close()\n\n\t\/\/\tDecode the request:\n\trequest := datastores.ConfigItem{}\n\terr := json.NewDecoder(req.Body).Decode(request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/\tGet the current datastore:\n\tds := datastores.GetConfigDatastore()\n\n\t\/\/\tSend the request to the datastore and get a response:\n\terr = ds.Remove(request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusInternalServerError)\n\t} else {\n\t\tWsHub.Broadcast <- []byte(getWSResponse(\"Removed\", request))\n\t\tsendDataResponse(rw, \"Config item removed\", request)\n\t}\n}\n\n\/\/\tGets all config information for a given application\nfunc GetAllConfigForApp(rw http.ResponseWriter, req *http.Request) {\n\t\/\/\treq.Body is a ReadCloser -- we need to remember to close it:\n\tdefer req.Body.Close()\n\n\t\/\/\tDecode the request:\n\trequest := &datastores.ConfigItem{}\n\terr := json.NewDecoder(req.Body).Decode(request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/\tGet the current datastore:\n\tds := datastores.GetConfigDatastore()\n\n\t\/\/\tSend the request to the datastore and get a response:\n\tconfigItems, err := ds.GetAllForApplication(request.Application)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/\tIf we found an item, return it (otherwise, return an empty array):\n\tif len(configItems) > 0 {\n\t\tsendDataResponse(rw, \"Config items found\", configItems)\n\t\treturn\n\t}\n\n\tsendDataResponse(rw, \"No config items found with that application\", configItems)\n}\n\n\/\/\tGets all config information\nfunc GetAllConfig(rw http.ResponseWriter, req *http.Request) {\n\t\/\/\treq.Body is a ReadCloser -- we need to remember to close it:\n\tdefer req.Body.Close()\n\n\t\/\/\tGet the current datastore:\n\tds := datastores.GetConfigDatastore()\n\n\t\/\/\tSend the request to the datastore and get a response:\n\tconfigItems, err := ds.GetAll()\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/\tIf we found an item, return it (otherwise, return an empty array):\n\tif len(configItems) > 0 {\n\t\tsendDataResponse(rw, \"Config items found\", configItems)\n\t\treturn\n\t}\n\n\tsendDataResponse(rw, \"No config items found\", configItems)\n}\n\n\/\/\tGets all applications\nfunc GetAllApplications(rw http.ResponseWriter, req *http.Request) {\n\t\/\/\treq.Body is a ReadCloser -- we need to remember to close it:\n\tdefer req.Body.Close()\n\n\t\/\/\tGet the current datastore:\n\tds := datastores.GetConfigDatastore()\n\n\t\/\/\tSend the request to the datastore and get a response:\n\tapplications, err := ds.GetAllApplications()\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/\tIf we found an item, return it (otherwise, return an empty array):\n\tif len(applications) > 0 {\n\t\tsendDataResponse(rw, \"Applications found\", applications)\n\t\treturn\n\t}\n\n\tsendDataResponse(rw, \"No config items found\", applications)\n}\n\n\/\/\tInitializes a store\nfunc InitStore(rw http.ResponseWriter, req *http.Request) {\n\tfmt.Fprintln(rw, \"InitStore method\")\n}\n\n\/\/\tUsed to send back an error:\nfunc sendErrorResponse(rw http.ResponseWriter, err error, code int) {\n\t\/\/\tOur return value\n\tresponse := datastores.ConfigResponse{\n\t\tStatus:  code,\n\t\tMessage: \"Error: \" + err.Error()}\n\n\t\/\/\tSerialize to JSON & return the response:\n\trw.WriteHeader(code)\n\trw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tjson.NewEncoder(rw).Encode(response)\n}\n\n\/\/\tUsed to send back a response with data\nfunc sendDataResponse(rw http.ResponseWriter, message string, dataItems interface{}) {\n\t\/\/\tOur return value\n\tresponse := datastores.ConfigResponse{\n\t\tStatus:  http.StatusOK,\n\t\tMessage: message,\n\t\tData:    dataItems}\n\n\t\/\/\tSerialize to JSON & return the response:\n\trw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tjson.NewEncoder(rw).Encode(response)\n}\n\n\/\/\tGets a JSON formatted WebSocket event response\nfunc getWSResponse(messageType string, item datastores.ConfigItem) string {\n\t\/\/\tOur default return value:\n\tretval := \"\"\n\n\t\/\/\tOur WebSocket return value\n\tresponse := datastores.WebSocketResponse{\n\t\tData: item,\n\t\tType: messageType}\n\n\t\/\/\tSerialize to JSON and return as a string:\n\tresponseBytes := new(bytes.Buffer)\n\tif err := json.NewEncoder(responseBytes).Encode(&response); err == nil {\n\t\tretval = responseBytes.String()\n\t}\n\n\treturn retval\n}\n<commit_msg>Got a bit too aggresive with the refactoring... added back some pointers required for JSON deserialization<commit_after>package api\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/cagedtornado\/centralconfig\/datastores\"\n)\n\nvar (\n\tWsHub = NewHub()\n)\n\nfunc ShowUI(rw http.ResponseWriter, req *http.Request) {\n\thttp.Redirect(rw, req, \"\/ui\/\", 301)\n}\n\n\/\/\tGets a specfic config item based on application and config item name\nfunc GetConfig(rw http.ResponseWriter, req *http.Request) {\n\t\/\/\treq.Body is a ReadCloser -- we need to remember to close it:\n\tdefer req.Body.Close()\n\n\t\/\/\tDecode the request:\n\trequest := datastores.ConfigItem{}\n\terr := json.NewDecoder(req.Body).Decode(&request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/\tGet the current datastore:\n\tds := datastores.GetConfigDatastore()\n\n\t\/\/\tSend the request to the datastore and get a response:\n\tresponse, err := ds.Get(request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/\tIf we found an item, return it (otherwise, return an empty item):\n\tconfigItem := datastores.ConfigItem{}\n\tif response.Name != \"\" {\n\t\tconfigItem = response\n\t\tsendDataResponse(rw, \"Config item found\", configItem)\n\t\treturn\n\t}\n\n\tsendDataResponse(rw, \"No config item found with that application and name\", configItem)\n}\n\n\/\/\tSet a specific config item\nfunc SetConfig(rw http.ResponseWriter, req *http.Request) {\n\t\/\/\treq.Body is a ReadCloser -- we need to remember to close it:\n\tdefer req.Body.Close()\n\n\t\/\/\tDecode the request:\n\trequest := datastores.ConfigItem{}\n\terr := json.NewDecoder(req.Body).Decode(&request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/\tGet the current datastore:\n\tds := datastores.GetConfigDatastore()\n\n\t\/\/\tSend the request to the datastore and get a response:\n\tresponse, err := ds.Set(request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusInternalServerError)\n\t} else {\n\t\tWsHub.Broadcast <- []byte(getWSResponse(\"Updated\", response))\n\t\tsendDataResponse(rw, \"Config item updated\", response)\n\t}\n}\n\n\/\/\tRemoves a specific config item\nfunc RemoveConfig(rw http.ResponseWriter, req *http.Request) {\n\t\/\/\treq.Body is a ReadCloser -- we need to remember to close it:\n\tdefer req.Body.Close()\n\n\t\/\/\tDecode the request:\n\trequest := datastores.ConfigItem{}\n\terr := json.NewDecoder(req.Body).Decode(&request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/\tGet the current datastore:\n\tds := datastores.GetConfigDatastore()\n\n\t\/\/\tSend the request to the datastore and get a response:\n\terr = ds.Remove(request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusInternalServerError)\n\t} else {\n\t\tWsHub.Broadcast <- []byte(getWSResponse(\"Removed\", request))\n\t\tsendDataResponse(rw, \"Config item removed\", request)\n\t}\n}\n\n\/\/\tGets all config information for a given application\nfunc GetAllConfigForApp(rw http.ResponseWriter, req *http.Request) {\n\t\/\/\treq.Body is a ReadCloser -- we need to remember to close it:\n\tdefer req.Body.Close()\n\n\t\/\/\tDecode the request:\n\trequest := &datastores.ConfigItem{}\n\terr := json.NewDecoder(req.Body).Decode(&request)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t\/\/\tGet the current datastore:\n\tds := datastores.GetConfigDatastore()\n\n\t\/\/\tSend the request to the datastore and get a response:\n\tconfigItems, err := ds.GetAllForApplication(request.Application)\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/\tIf we found an item, return it (otherwise, return an empty array):\n\tif len(configItems) > 0 {\n\t\tsendDataResponse(rw, \"Config items found\", configItems)\n\t\treturn\n\t}\n\n\tsendDataResponse(rw, \"No config items found with that application\", configItems)\n}\n\n\/\/\tGets all config information\nfunc GetAllConfig(rw http.ResponseWriter, req *http.Request) {\n\t\/\/\treq.Body is a ReadCloser -- we need to remember to close it:\n\tdefer req.Body.Close()\n\n\t\/\/\tGet the current datastore:\n\tds := datastores.GetConfigDatastore()\n\n\t\/\/\tSend the request to the datastore and get a response:\n\tconfigItems, err := ds.GetAll()\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/\tIf we found an item, return it (otherwise, return an empty array):\n\tif len(configItems) > 0 {\n\t\tsendDataResponse(rw, \"Config items found\", configItems)\n\t\treturn\n\t}\n\n\tsendDataResponse(rw, \"No config items found\", configItems)\n}\n\n\/\/\tGets all applications\nfunc GetAllApplications(rw http.ResponseWriter, req *http.Request) {\n\t\/\/\treq.Body is a ReadCloser -- we need to remember to close it:\n\tdefer req.Body.Close()\n\n\t\/\/\tGet the current datastore:\n\tds := datastores.GetConfigDatastore()\n\n\t\/\/\tSend the request to the datastore and get a response:\n\tapplications, err := ds.GetAllApplications()\n\tif err != nil {\n\t\tsendErrorResponse(rw, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t\/\/\tIf we found an item, return it (otherwise, return an empty array):\n\tif len(applications) > 0 {\n\t\tsendDataResponse(rw, \"Applications found\", applications)\n\t\treturn\n\t}\n\n\tsendDataResponse(rw, \"No config items found\", applications)\n}\n\n\/\/\tInitializes a store\nfunc InitStore(rw http.ResponseWriter, req *http.Request) {\n\tfmt.Fprintln(rw, \"InitStore method\")\n}\n\n\/\/\tUsed to send back an error:\nfunc sendErrorResponse(rw http.ResponseWriter, err error, code int) {\n\t\/\/\tOur return value\n\tresponse := datastores.ConfigResponse{\n\t\tStatus:  code,\n\t\tMessage: \"Error: \" + err.Error()}\n\n\t\/\/\tSerialize to JSON & return the response:\n\trw.WriteHeader(code)\n\trw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tjson.NewEncoder(rw).Encode(response)\n}\n\n\/\/\tUsed to send back a response with data\nfunc sendDataResponse(rw http.ResponseWriter, message string, dataItems interface{}) {\n\t\/\/\tOur return value\n\tresponse := datastores.ConfigResponse{\n\t\tStatus:  http.StatusOK,\n\t\tMessage: message,\n\t\tData:    dataItems}\n\n\t\/\/\tSerialize to JSON & return the response:\n\trw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tjson.NewEncoder(rw).Encode(response)\n}\n\n\/\/\tGets a JSON formatted WebSocket event response\nfunc getWSResponse(messageType string, item datastores.ConfigItem) string {\n\t\/\/\tOur default return value:\n\tretval := \"\"\n\n\t\/\/\tOur WebSocket return value\n\tresponse := datastores.WebSocketResponse{\n\t\tData: item,\n\t\tType: messageType}\n\n\t\/\/\tSerialize to JSON and return as a string:\n\tresponseBytes := new(bytes.Buffer)\n\tif err := json.NewEncoder(responseBytes).Encode(&response); err == nil {\n\t\tretval = responseBytes.String()\n\t}\n\n\treturn retval\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"gopkg.in\/kataras\/iris.v6\"\n\t\"gopkg.in\/kataras\/iris.v6\/adaptors\/httprouter\"\n\t\"os\"\n\t\"gifjam\/gifGrabber\"\n\t\"net\/http\"\n\t\"log\"\n\t\"gopkg.in\/kataras\/iris.v6\/adaptors\/cors\"\n\t\"strconv\"\n\t\"io\"\n)\n\ntype obj map[string]interface{}\n\nfunc StartApiServer() {\n\tapp := iris.New()\n\tapp.Adapt(iris.DevLogger(), httprouter.New(), cors.New(cors.Options{AllowedOrigins: []string{\"*\"}}))\n\n\tapp.Post(\"\/gif\/:id\", serveGif)\n\tapp.Post(\"\/gifs\/visibility\/:id\/:visible\", gifVisibility)\n\tapp.Post(\"\/gifs\", GetGifs)\n\n\t\/\/ Setting address from ENV\n\tapp.Listen(os.Getenv(\"GIFJAM_SERVER_HOST\"))\n}\n\nfunc GetGifs(ctx *iris.Context) {\n\toffset, err := ctx.URLParamInt(\"offset\")\n\tif err != nil {\n\t\toffset = 0\n\t}\n\n\tlimit, err := ctx.URLParamInt(\"offset\")\n\tif err != nil {\n\t\tlimit = 10\n\t}\n\n\timages, err := gifGrabber.GetItems(offset, limit)\n\tif err != nil {\n\t\tlog.Println(\"Unable to get images from database -> \", err.Error())\n\t\tctx.JSON(http.StatusOK, obj{\"error\": \"Unable to get images!\"})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, obj{\"images\": images})\n}\n\nfunc serveGif(ctx *iris.Context) {\n\tfile_id := ctx.Param(\"id\")\n\tif len(file_id) != 24 {\n\t\tctx.JSON(http.StatusNotFound, obj{\"error\": \"Image Not Found!\"})\n\t\treturn\n\t}\n\n\tlength, r, err := gifGrabber.GetFileIO(file_id)\n\tif err != nil {\n\t\tlog.Println(\"Unable to get image from database -> \", err.Error())\n\t\tctx.JSON(http.StatusInternalServerError, obj{\"error\": \"Unable to read Image file\"})\n\t\treturn\n\t}\n\n\tdefer r.Close()\n\n\tctx.SetHeader(\"Content-Length\", strconv.FormatInt(length, 10))\n\tctx.SetHeader(\"Content-Type\", \"image\/gif\")\n\tio.Copy(ctx, r)\n}\n\nfunc gifVisibility(ctx *iris.Context) {\n\tfile_id := ctx.Param(\"id\")\n\tif len(file_id) != 24 {\n\t\tctx.JSON(http.StatusNotFound, obj{\"error\": \"Image Not Found!\"})\n\t\treturn\n\t}\n\n\tvisible := false\n\n\tvisible_param := ctx.Param(\"visible\")\n\tif visible_param == \"1\" {\n\t\tvisible = true\n\t}\n\n\terr := gifGrabber.SetVisibility(file_id, visible)\n\tif err != nil {\n\t\tlog.Println(\"Unable to set image to visible -> \", err.Error())\n\t\tctx.JSON(http.StatusInternalServerError, obj{\"error\": \"Unable to set image to visible\"})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, obj{})\n}<commit_msg>gif download using get request<commit_after>package api\n\nimport (\n\t\"gopkg.in\/kataras\/iris.v6\"\n\t\"gopkg.in\/kataras\/iris.v6\/adaptors\/httprouter\"\n\t\"os\"\n\t\"gifjam\/gifGrabber\"\n\t\"net\/http\"\n\t\"log\"\n\t\"gopkg.in\/kataras\/iris.v6\/adaptors\/cors\"\n\t\"strconv\"\n\t\"io\"\n)\n\ntype obj map[string]interface{}\n\nfunc StartApiServer() {\n\tapp := iris.New()\n\tapp.Adapt(iris.DevLogger(), httprouter.New(), cors.New(cors.Options{AllowedOrigins: []string{\"*\"}}))\n\n\tapp.Get(\"\/gif\/:id\", serveGif)\n\tapp.Post(\"\/gifs\/visibility\/:id\/:visible\", gifVisibility)\n\tapp.Post(\"\/gifs\", GetGifs)\n\n\t\/\/ Setting address from ENV\n\tapp.Listen(os.Getenv(\"GIFJAM_SERVER_HOST\"))\n}\n\nfunc GetGifs(ctx *iris.Context) {\n\toffset, err := ctx.URLParamInt(\"offset\")\n\tif err != nil {\n\t\toffset = 0\n\t}\n\n\tlimit, err := ctx.URLParamInt(\"offset\")\n\tif err != nil {\n\t\tlimit = 10\n\t}\n\n\timages, err := gifGrabber.GetItems(offset, limit)\n\tif err != nil {\n\t\tlog.Println(\"Unable to get images from database -> \", err.Error())\n\t\tctx.JSON(http.StatusOK, obj{\"error\": \"Unable to get images!\"})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, obj{\"images\": images})\n}\n\nfunc serveGif(ctx *iris.Context) {\n\tfile_id := ctx.Param(\"id\")\n\tif len(file_id) != 24 {\n\t\tctx.JSON(http.StatusNotFound, obj{\"error\": \"Image Not Found!\"})\n\t\treturn\n\t}\n\n\tlength, r, err := gifGrabber.GetFileIO(file_id)\n\tif err != nil {\n\t\tlog.Println(\"Unable to get image from database -> \", err.Error())\n\t\tctx.JSON(http.StatusInternalServerError, obj{\"error\": \"Unable to read Image file\"})\n\t\treturn\n\t}\n\n\tdefer r.Close()\n\n\tctx.SetHeader(\"Content-Length\", strconv.FormatInt(length, 10))\n\tctx.SetHeader(\"Content-Type\", \"image\/gif\")\n\tio.Copy(ctx, r)\n}\n\nfunc gifVisibility(ctx *iris.Context) {\n\tfile_id := ctx.Param(\"id\")\n\tif len(file_id) != 24 {\n\t\tctx.JSON(http.StatusNotFound, obj{\"error\": \"Image Not Found!\"})\n\t\treturn\n\t}\n\n\tvisible := false\n\n\tvisible_param := ctx.Param(\"visible\")\n\tif visible_param == \"1\" {\n\t\tvisible = true\n\t}\n\n\terr := gifGrabber.SetVisibility(file_id, visible)\n\tif err != nil {\n\t\tlog.Println(\"Unable to set image to visible -> \", err.Error())\n\t\tctx.JSON(http.StatusInternalServerError, obj{\"error\": \"Unable to set image to visible\"})\n\t\treturn\n\t}\n\n\tctx.JSON(http.StatusOK, obj{})\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n)\n\nfunc sigintCleanup() int {\n\t\/\/ TODO: close the database connection and do other cleanup jobs\n\treturn 0\n}\n\nfunc sigintCleanupSetup() error {\n\tlogger.Infof(\"setting up SIGINT cleanup\")\n\n\tc := make(chan os.Signal)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGINT)\n\tgo func() {\n\t\t<-c\n\t\tos.Exit(sigintCleanup())\n\t}()\n\n\treturn nil\n}\n<commit_msg>sigint.go: close DB connection before exit<commit_after>package main\n\nimport (\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n)\n\nfunc sigintCleanup() int {\n\tif db != nil {\n\t\terr := db.Close()\n\t\tif err == nil {\n\t\t\tlogger.Errorf(\"cannot close database connection: %v\", err)\n\t\t\treturn 1\n\t\t}\n\t}\n\n\treturn 0\n}\n\nfunc sigintCleanupSetup() error {\n\tlogger.Infof(\"setting up SIGINT cleanup\")\n\n\tc := make(chan os.Signal)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGINT)\n\tgo func() {\n\t\t<-c\n\t\tos.Exit(sigintCleanup())\n\t}()\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package context\n\nimport (\n\t\"github.com\/WE-Development\/mosel\/commons\"\n\t\"time\"\n\t\"github.com\/WE-Development\/mosel\/api\"\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"log\"\n)\n\ntype table struct {\n\tname        string\n\tcreateQuery string\n}\n\ntype result map[string]map[string]map[string]string\n\ntype dataPersistence interface {\n\tInit() error\n\tAdd(node string, t time.Time, info api.NodeInfo)\n\tGetAll() (result, error)\n}\n\ntype sqlDataPersistence struct {\n\tdb *sql.DB\n\tq  commons.SqlQueries\n\n\tdbState map[string]map[string][]string\n}\n\nfunc NewSqlDataPersistence(db *sql.DB, queries commons.SqlQueries) dataPersistence {\n\treturn sqlDataPersistence{\n\t\tdb:db,\n\t\tq:queries,\n\t}\n}\n\nfunc (pers sqlDataPersistence) query(name string, args ...interface{}) (*sql.Rows, error) {\n\tquery, exists := pers.q[name]\n\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"Quers %s is not registered\", name)\n\t}\n\n\treturn pers.db.Query(query, args...)\n}\n\nfunc (pers sqlDataPersistence) queryResultNotEmpty(name string, args ...interface{}) (bool, error) {\n\trows, err := pers.query(name, args...)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn !rows.Next(), nil\n}\n\nfunc (pers sqlDataPersistence) Init() error {\n\ttables := make([]table, 4)\n\ttables[0] = table{name:\"Nodes\", createQuery:\"createNodes\", }\n\ttables[1] = table{name:\"Diagrams\", createQuery:\"createDiagrams\", }\n\ttables[2] = table{name:\"Graphs\", createQuery:\"createGraphs\", }\n\ttables[3] = table{name:\"DataPoints\", createQuery:\"createDataPoints\", }\n\n\tfor _, table := range tables {\n\t\tif exists, err := pers.tableExists(table.name); err != nil {\n\t\t\treturn err\n\t\t} else if !exists {\n\t\t\tlog.Printf(\"Create table %s \", table)\n\t\t\t_, err := pers.query(table.createQuery)\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (pers sqlDataPersistence) tableExists(name string) (bool, error) {\n\t\/\/todo be clever bout this\n\trows, err := pers.db.Query(pers.q[\"tableExists\"] + \" '\" + name + \"'\")\n\tdefer rows.Close()\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn rows.Next(), nil\n}\n\nfunc (pers sqlDataPersistence) Add(node string, t time.Time, info api.NodeInfo) {\n\tif empty, err := pers.queryResultNotEmpty(\"nodeByName\", node); err != nil {\n\t\tlog.Println(err)\n\t} else if empty {\n\t\tpers.query(\"insertNode\", node, \"\")\n\t}\n\t\/*\n\t\tif empty, err := pers.queryResultNotEmpty(\"diagramByName\", node); err != nil {\n\t\t\tlog.Println(err)\n\t\t} else if empty {\n\t\t\tpers.query(\"insertDiagram\", node, \"\")\n\t\t}\n\n\t\tif empty, err := pers.queryResultNotEmpty(\"nodeByName\", node); err != nil {\n\t\t\tlog.Println(err)\n\t\t} else if empty {\n\t\t\tpers.query(\"insertNode\", node, \"\")\n\t\t}*\/\n}\n\nfunc (pers sqlDataPersistence) GetAll() (result, error) {\n\tres := make(result)\n\trows, err := pers.query(\"all\")\n\tdefer rows.Close()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor rows.Next() {\n\t\tvar value string\n\t\tvar timestamp []uint8\n\t\tvar graph string\n\t\tvar diagram string\n\t\tvar node string\n\t\tvar url string\n\t\terr := rows.Scan(&value, &timestamp, &graph, &diagram, &node, &url)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlog.Println(value, timestamp, graph, diagram, node, url)\n\t}\n\n\treturn res, nil\n}<commit_msg>update dbState internally<commit_after>package context\n\nimport (\n\t\"github.com\/WE-Development\/mosel\/commons\"\n\t\"time\"\n\t\"github.com\/WE-Development\/mosel\/api\"\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"log\"\n)\n\ntype table struct {\n\tname        string\n\tcreateQuery string\n}\n\ntype result map[string]map[string]map[string]string\n\ntype dbState map[string]map[string][]string\n\ntype dbResult struct {\n\tvalue     string\n\ttimestamp []uint8\n\tgraph     string\n\tdiagram   string\n\tnode      string\n\turl       string\n}\n\ntype dataPersistence interface {\n\tInit() error\n\tAdd(node string, t time.Time, info api.NodeInfo)\n\tGetAll() (result, error)\n}\n\ntype sqlDataPersistence struct {\n\tdb      *sql.DB\n\tq       commons.SqlQueries\n\n\tdbState dbState\n}\n\nfunc NewSqlDataPersistence(db *sql.DB, queries commons.SqlQueries) dataPersistence {\n\treturn sqlDataPersistence{\n\t\tdb:db,\n\t\tq:queries,\n\t}\n}\n\nfunc (pers sqlDataPersistence) query(name string, args ...interface{}) (*sql.Rows, error) {\n\tquery, exists := pers.q[name]\n\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"Quers %s is not registered\", name)\n\t}\n\n\treturn pers.db.Query(query, args...)\n}\n\nfunc (pers sqlDataPersistence) queryResultNotEmpty(name string, args ...interface{}) (bool, error) {\n\trows, err := pers.query(name, args...)\n\tdefer rows.Close()\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn !rows.Next(), nil\n}\n\nfunc (pers sqlDataPersistence) tableExists(name string) (bool, error) {\n\t\/\/todo be clever bout this\n\trows, err := pers.db.Query(pers.q[\"tableExists\"] + \" '\" + name + \"'\")\n\tdefer rows.Close()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn rows.Next(), nil\n}\n\nfunc (pers sqlDataPersistence) Init() error {\n\ttables := make([]table, 4)\n\ttables[0] = table{name:\"Nodes\", createQuery:\"createNodes\", }\n\ttables[1] = table{name:\"Diagrams\", createQuery:\"createDiagrams\", }\n\ttables[2] = table{name:\"Graphs\", createQuery:\"createGraphs\", }\n\ttables[3] = table{name:\"DataPoints\", createQuery:\"createDataPoints\", }\n\n\tfor _, table := range tables {\n\t\tif exists, err := pers.tableExists(table.name); err != nil {\n\t\t\treturn err\n\t\t} else if !exists {\n\t\t\tlog.Printf(\"Create table %s \", table)\n\t\t\t_, err := pers.query(table.createQuery)\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (pers sqlDataPersistence) Add(node string, t time.Time, info api.NodeInfo) {\n\n\n\n}\n\nfunc (pers sqlDataPersistence) GetAll() (result, error) {\n\tres := make(result)\n\trows, err := pers.query(\"all\")\n\tdefer rows.Close()\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor rows.Next() {\n\t\tvar dbRes dbResult\n\t\terr := rows.Scan(&dbRes.value, &dbRes.timestamp, &dbRes.graph, &dbRes.diagram, &dbRes.node, &dbRes.url)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpers.updateDbState(dbRes)\n\t}\n\tlog.Println(pers.dbState)\n\n\treturn res, nil\n}\n\nfunc (pers *sqlDataPersistence) updateDbState(dbRes dbResult) {\n\t\/\/log.Println(value, timestamp, graph, diagram, node, url)\n\tif dbRes.node == \"\" {\n\t\treturn\n\t}\n\n\tif pers.dbState == nil {\n\t\tpers.dbState = make(dbState)\n\t}\n\n\tdiagrams, ok := pers.dbState[dbRes.node]\n\tif !ok {\n\t\tdiagrams = make(map[string][]string)\n\t\tpers.dbState[dbRes.node] = diagrams\n\t}\n\n\tif dbRes.diagram == \"\" {\n\t\treturn\n\t}\n\n\tgraphs, ok := pers.dbState[dbRes.node][dbRes.diagram]\n\tif !ok {\n\t\tgraphs = make([]string, 0)\n\t\tpers.dbState[dbRes.node][dbRes.diagram] = graphs\n\t}\n\n\tif dbRes.graph == \"\" {\n\t\treturn\n\t}\n\n\tgraphs = append(graphs, dbRes.graph)\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2016 by Richard A. Wilkes. All rights reserved.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, version 2.0. If a copy of the MPL was not distributed with\n\/\/ this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\/\/ This Source Code Form is \"Incompatible With Secondary Licenses\", as\n\/\/ defined by the Mozilla Public License, version 2.0.\n\npackage draw\n\nimport (\n\t\"github.com\/richardwilkes\/ui\/color\"\n\t\"github.com\/richardwilkes\/ui\/geom\"\n\t\"unsafe\"\n)\n\nfunc (gc *graphics) platformSave() {\n\t\/\/ RAW: Implement platformSave for Linux\n}\n\nfunc (gc *graphics) platformRestore() {\n\t\/\/ RAW: Implement platformRestore for Linux\n}\n\nfunc (gc *graphics) platformSetOpacity(opacity float32) {\n\t\/\/ RAW: Implement platformSetOpacity for Linux\n}\n\nfunc (gc *graphics) platformSetFillColor(color color.Color) {\n\t\/\/ RAW: Implement platformSetFillColor for Linux\n}\n\nfunc (gc *graphics) platformSetStrokeColor(color color.Color) {\n\t\/\/ RAW: Implement platformSetStrokeColor for Linux\n}\n\nfunc (gc *graphics) platformSetStrokeWidth(width float32) {\n\t\/\/ RAW: Implement platformSetStrokeWidth for Linux\n}\n\nfunc (gc *graphics) platformFillRect(bounds geom.Rect) {\n\t\/\/ RAW: Implement platformFillRect for Linux\n}\n\nfunc (gc *graphics) platformStrokeRect(bounds geom.Rect) {\n\t\/\/ RAW: Implement platformFillRect for Linux\n}\n\nfunc (gc *graphics) platformFillEllipse(bounds geom.Rect) {\n\t\/\/ RAW: Implement platformFillEllipse for Linux\n}\n\nfunc (gc *graphics) platformStrokeEllipse(bounds geom.Rect) {\n\t\/\/ RAW: Implement platformStrokeEllipse for Linux\n}\n\nfunc (gc *graphics) platformFillPath() {\n\t\/\/ RAW: Implement platformFillPath for Linux\n}\n\nfunc (gc *graphics) platformFillPathEvenOdd() {\n\t\/\/ RAW: Implement platformFillPathEvenOdd for Linux\n}\n\nfunc (gc *graphics) platformStrokePath() {\n\t\/\/ RAW: Implement platformStrokePath for Linux\n}\n\nfunc (gc *graphics) platformFillAndStrokePath() {\n\t\/\/ RAW: Implement platformFillAndStrokePath for Linux\n}\n\nfunc (gc *graphics) platformBeginPath() {\n\t\/\/ RAW: Implement platformBeginPath for Linux\n}\n\nfunc (gc *graphics) platformClosePath() {\n\t\/\/ RAW: Implement platformClosePath for Linux\n}\n\nfunc (gc *graphics) platformMoveTo(x, y float32) {\n\t\/\/ RAW: Implement platformMoveTo for Linux\n}\n\nfunc (gc *graphics) platformLineTo(x, y float32) {\n\t\/\/ RAW: Implement platformLineTo for Linux\n}\n\nfunc (gc *graphics) platformArc(cx, cy, radius, startAngleRadians, endAngleRadians float32, clockwise bool) {\n\t\/\/ RAW: Implement platformArc for Linux\n}\n\nfunc (gc *graphics) platformArcTo(x1, y1, x2, y2, radius float32) {\n\t\/\/ RAW: Implement platformArcTo for Linux\n}\n\nfunc (gc *graphics) platformCurveTo(cp1x, cp1y, cp2x, cp2y, x, y float32) {\n\t\/\/ RAW: Implement platformCurveTo for Linux\n}\n\nfunc (gc *graphics) platformQuadCurveTo(cpx, cpy, x, y float32) {\n\t\/\/ RAW: Implement platformQuadCurveTo for Linux\n}\n\nfunc (gc *graphics) platformAddPath(path *geom.Path) {\n\t\/\/ RAW: Implement platformAddPath for Linux\n}\n\nfunc (gc *graphics) platformClip() {\n\t\/\/ RAW: Implement platformClip for Linux\n}\n\nfunc (gc *graphics) platformClipEvenOd() {\n\t\/\/ RAW: Implement platformClipEvenOd for Linux\n}\n\nfunc (gc *graphics) platformClipRect(bounds geom.Rect) {\n\t\/\/ RAW: Implement platformClipRect for Linux\n}\n\nfunc (gc *graphics) platformDrawLinearGradient(gradient *Gradient, sx, sy, ex, ey float32) {\n\t\/\/ RAW: Implement platformDrawLinearGradient for Linux\n}\n\nfunc (gc *graphics) platformDrawRadialGradient(gradient *Gradient, scx, scy, startRadius, ecx, ecy, endRadius float32) {\n\t\/\/ RAW: Implement platformDrawRadialGradient for Linux\n}\n\nfunc (gc *graphics) platformDrawImageInRect(img *Image, bounds geom.Rect) {\n\t\/\/ RAW: Implement platformDrawImageInRect for Linux\n}\n\nfunc (gc *graphics) platformDrawString(x, y float32, str string) {\n\t\/\/ RAW: Implement platformDrawString for Linux\n}\n\nfunc (gc *graphics) platformTranslate(x, y float32) {\n\t\/\/ RAW: Implement platformTranslate for Linux\n}\n\nfunc (gc *graphics) platformScale(x, y float32) {\n\t\/\/ RAW: Implement platformScale for Linux\n}\n\nfunc (gc *graphics) platformRotate(angleInRadians float32) {\n\t\/\/ RAW: Implement platformRotate for Linux\n}\n<commit_msg>Remove unused import<commit_after>\/\/ Copyright (c) 2016 by Richard A. Wilkes. All rights reserved.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, version 2.0. If a copy of the MPL was not distributed with\n\/\/ this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\/\/ This Source Code Form is \"Incompatible With Secondary Licenses\", as\n\/\/ defined by the Mozilla Public License, version 2.0.\n\npackage draw\n\nimport (\n\t\"github.com\/richardwilkes\/ui\/color\"\n\t\"github.com\/richardwilkes\/ui\/geom\"\n)\n\nfunc (gc *graphics) platformSave() {\n\t\/\/ RAW: Implement platformSave for Linux\n}\n\nfunc (gc *graphics) platformRestore() {\n\t\/\/ RAW: Implement platformRestore for Linux\n}\n\nfunc (gc *graphics) platformSetOpacity(opacity float32) {\n\t\/\/ RAW: Implement platformSetOpacity for Linux\n}\n\nfunc (gc *graphics) platformSetFillColor(color color.Color) {\n\t\/\/ RAW: Implement platformSetFillColor for Linux\n}\n\nfunc (gc *graphics) platformSetStrokeColor(color color.Color) {\n\t\/\/ RAW: Implement platformSetStrokeColor for Linux\n}\n\nfunc (gc *graphics) platformSetStrokeWidth(width float32) {\n\t\/\/ RAW: Implement platformSetStrokeWidth for Linux\n}\n\nfunc (gc *graphics) platformFillRect(bounds geom.Rect) {\n\t\/\/ RAW: Implement platformFillRect for Linux\n}\n\nfunc (gc *graphics) platformStrokeRect(bounds geom.Rect) {\n\t\/\/ RAW: Implement platformFillRect for Linux\n}\n\nfunc (gc *graphics) platformFillEllipse(bounds geom.Rect) {\n\t\/\/ RAW: Implement platformFillEllipse for Linux\n}\n\nfunc (gc *graphics) platformStrokeEllipse(bounds geom.Rect) {\n\t\/\/ RAW: Implement platformStrokeEllipse for Linux\n}\n\nfunc (gc *graphics) platformFillPath() {\n\t\/\/ RAW: Implement platformFillPath for Linux\n}\n\nfunc (gc *graphics) platformFillPathEvenOdd() {\n\t\/\/ RAW: Implement platformFillPathEvenOdd for Linux\n}\n\nfunc (gc *graphics) platformStrokePath() {\n\t\/\/ RAW: Implement platformStrokePath for Linux\n}\n\nfunc (gc *graphics) platformFillAndStrokePath() {\n\t\/\/ RAW: Implement platformFillAndStrokePath for Linux\n}\n\nfunc (gc *graphics) platformBeginPath() {\n\t\/\/ RAW: Implement platformBeginPath for Linux\n}\n\nfunc (gc *graphics) platformClosePath() {\n\t\/\/ RAW: Implement platformClosePath for Linux\n}\n\nfunc (gc *graphics) platformMoveTo(x, y float32) {\n\t\/\/ RAW: Implement platformMoveTo for Linux\n}\n\nfunc (gc *graphics) platformLineTo(x, y float32) {\n\t\/\/ RAW: Implement platformLineTo for Linux\n}\n\nfunc (gc *graphics) platformArc(cx, cy, radius, startAngleRadians, endAngleRadians float32, clockwise bool) {\n\t\/\/ RAW: Implement platformArc for Linux\n}\n\nfunc (gc *graphics) platformArcTo(x1, y1, x2, y2, radius float32) {\n\t\/\/ RAW: Implement platformArcTo for Linux\n}\n\nfunc (gc *graphics) platformCurveTo(cp1x, cp1y, cp2x, cp2y, x, y float32) {\n\t\/\/ RAW: Implement platformCurveTo for Linux\n}\n\nfunc (gc *graphics) platformQuadCurveTo(cpx, cpy, x, y float32) {\n\t\/\/ RAW: Implement platformQuadCurveTo for Linux\n}\n\nfunc (gc *graphics) platformAddPath(path *geom.Path) {\n\t\/\/ RAW: Implement platformAddPath for Linux\n}\n\nfunc (gc *graphics) platformClip() {\n\t\/\/ RAW: Implement platformClip for Linux\n}\n\nfunc (gc *graphics) platformClipEvenOd() {\n\t\/\/ RAW: Implement platformClipEvenOd for Linux\n}\n\nfunc (gc *graphics) platformClipRect(bounds geom.Rect) {\n\t\/\/ RAW: Implement platformClipRect for Linux\n}\n\nfunc (gc *graphics) platformDrawLinearGradient(gradient *Gradient, sx, sy, ex, ey float32) {\n\t\/\/ RAW: Implement platformDrawLinearGradient for Linux\n}\n\nfunc (gc *graphics) platformDrawRadialGradient(gradient *Gradient, scx, scy, startRadius, ecx, ecy, endRadius float32) {\n\t\/\/ RAW: Implement platformDrawRadialGradient for Linux\n}\n\nfunc (gc *graphics) platformDrawImageInRect(img *Image, bounds geom.Rect) {\n\t\/\/ RAW: Implement platformDrawImageInRect for Linux\n}\n\nfunc (gc *graphics) platformDrawString(x, y float32, str string) {\n\t\/\/ RAW: Implement platformDrawString for Linux\n}\n\nfunc (gc *graphics) platformTranslate(x, y float32) {\n\t\/\/ RAW: Implement platformTranslate for Linux\n}\n\nfunc (gc *graphics) platformScale(x, y float32) {\n\t\/\/ RAW: Implement platformScale for Linux\n}\n\nfunc (gc *graphics) platformRotate(angleInRadians float32) {\n\t\/\/ RAW: Implement platformRotate for Linux\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2016 Ivan Dejanovic\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\npackage codegen\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"mlpl\/types\"\n)\n\nconst (\n\tpc  int = 7 \/\/ pc = program counter\n\tmp  int = 6 \/\/ mp = \"memory pointer\" point to top of memory (for temp storage)\n\tgp  int = 5 \/\/ gp = \"global pointer\" points to bottom of memory for (global) variable storage\n\tac  int = 0 \/\/ accumulator\n\tac1 int = 1 \/\/ 2nd accumulator\n)\n\ntype codeBuffer struct {\n\tcode        []string\n\ttmpOffset   int \/\/ tmpOffset is the memory offset for temps. It is decremented each time a temp is stored, and incremeted when loaded again.\n\temitLoc     int \/\/ TM location number for current instruction emission\n\thighEmitLoc int \/\/ Highest TM location emitted so far. For use in conjunction with emitSkip, emitBackup, and emitRestore\n}\n\n\/* Procedure emitRO emits a register-only TM instruction\n   op = the opcode\n   r = target register\n   s = 1st source register\n   t = 2nd source register\n*\/\nfunc (codeBuf *codeBuffer) emitRO(op string, r int, s int, t int) {\n\tcode := fmt.Sprintf(\"%3d: %5s %d, %d, %d\", codeBuf.emitLoc, op, r, s, t)\n\tcodeBuf.emitLoc += 1\n\tif codeBuf.highEmitLoc < codeBuf.emitLoc {\n\t\tcodeBuf.highEmitLoc = codeBuf.emitLoc\n\t}\n\tcodeBuf.code = append(codeBuf.code, code)\n}\n\n\/* Procedure emitRM emits a register-to-memory TM instruction\n   op = the opcode\n   r = target register\n   d = the offset\n   s = the base register\n*\/\nfunc (codeBuf *codeBuffer) emitRM(op string, r int, d int, s int) {\n\tcode := fmt.Sprintf(\"%3d: %5s %d, %d(%d)\", codeBuf.emitLoc, op, r, d, s)\n\tcodeBuf.emitLoc += 1\n\tif codeBuf.highEmitLoc < codeBuf.emitLoc {\n\t\tcodeBuf.highEmitLoc = codeBuf.emitLoc\n\t}\n\tcodeBuf.code = append(codeBuf.code, code)\n}\n\n\/\/ Function emitSkip skips \"howMany\" code locations for later backpatch. It also returns the current code position\nfunc (codeBuf *codeBuffer) emitSkip(howMany int) int {\n\ti := codeBuf.emitLoc\n\tcodeBuf.emitLoc += howMany\n\tif codeBuf.highEmitLoc < codeBuf.emitLoc {\n\t\tcodeBuf.highEmitLoc = codeBuf.emitLoc\n\t}\n\n\treturn i\n}\n\n\/\/ Procedure emitRestore restores the current code position to the highest previously unemitted position\nfunc (codeBuf *codeBuffer) emitRestore() {\n\tcodeBuf.emitLoc = codeBuf.highEmitLoc\n}\n\n\/* Procedure emitRM_Abs converts an absolute reference to a pc-relative reference when emitting a register-to-memory TM instruction\n   op = the opcode\n   r = target register\n   a = the absolute location in memory\n*\/\nfunc (codeBuf *codeBuffer) emitRM_Abs(op string, r int, a int) {\n\tabs := a - codeBuf.emitLoc + 1\n\tcode := fmt.Sprintf(\"%3d: %5s %d, %d(%d)\", codeBuf.emitLoc, op, r, abs, pc)\n\tcodeBuf.emitLoc += 1\n\tif codeBuf.highEmitLoc < codeBuf.emitLoc {\n\t\tcodeBuf.highEmitLoc = codeBuf.emitLoc\n\t}\n\tcodeBuf.code = append(codeBuf.code, code)\n}\n\nfunc findLoc(bucketMap map[string]types.Bucket, name string) int {\n\tbucket, ok := bucketMap[name]\n\n\tif ok {\n\t\treturn bucket.MemLoc\n\t}\n\n\treturn -1\n}\n\n\/\/ Procedure genStmt generates code at a statement node\nfunc genStmt(treeNode *types.TreeNode, bucketMap map[string]types.Bucket, codeBuf *codeBuffer) {\n\tvar p1, p2, p3 *types.TreeNode = nil, nil, nil\n\tvar loc int\n\n\tswitch treeNode.Stmt {\n\tcase types.IfK:\n\t\tp1 = treeNode.Children[0]\n\t\tp2 = treeNode.Children[1]\n\t\tif len(treeNode.Children) == 3 {\n\t\t\tp3 = treeNode.Children[2]\n\t\t}\n\n\t\t\/\/ Generate code for test expression\n\t\tcGen(p1, bucketMap, codeBuf)\n\t\tcodeBuf.emitSkip(1)\n\n\t\t\/\/ Recurse on then part\n\t\tcGen(p2, bucketMap, codeBuf)\n\t\tcodeBuf.emitSkip(1)\n\t\tloc = codeBuf.emitSkip(0)\n\t\tcodeBuf.emitRM_Abs(\"JEQ\", ac, loc)\n\t\tcodeBuf.emitRestore()\n\n\t\t\/\/ Recurse on else part\n\t\tcGen(p3, bucketMap, codeBuf)\n\t\tloc = codeBuf.emitSkip(0)\n\t\tcodeBuf.emitRM_Abs(\"LDA\", pc, loc)\n\t\tcodeBuf.emitRestore()\n\tcase types.RepeatK:\n\t\tp1 = treeNode.Children[0]\n\t\tp2 = treeNode.Children[1]\n\t\tloc = codeBuf.emitSkip(0)\n\n\t\t\/\/ Generate code for body\n\t\tcGen(p1, bucketMap, codeBuf)\n\t\t\/\/ Generate code for test\n\t\tcGen(p2, bucketMap, codeBuf)\n\n\t\tcodeBuf.emitRM_Abs(\"JEQ\", ac, loc)\n\tcase types.AssignK:\n\t\t\/\/ Generate code for rhs\n\t\tp1 = treeNode.Children[0]\n\t\tcGen(p1, bucketMap, codeBuf)\n\t\t\/\/ Now store value\n\t\tloc = findLoc(bucketMap, treeNode.Name)\n\t\tcodeBuf.emitRM(\"ST\", ac, loc, gp)\n\tcase types.ReadK:\n\t\tcodeBuf.emitRO(\"IN\", ac, 0, 0)\n\t\tloc = findLoc(bucketMap, treeNode.Name)\n\t\tcodeBuf.emitRM(\"ST\", ac, loc, gp)\n\tcase types.WriteK:\n\t\t\/\/ Generate code for expression to write\n\t\tp1 = treeNode.Children[0]\n\t\tcGen(p1, bucketMap, codeBuf)\n\t\t\/\/ Now output it\n\t\tcodeBuf.emitRO(\"OUT\", ac, 0, 0)\n\t}\n}\n\n\/\/ Procedure genExp generates code at an expression node\nfunc genExp(treeNode *types.TreeNode, bucketMap map[string]types.Bucket, codeBuf *codeBuffer) {\n\tvar p1, p2 *types.TreeNode\n\tvar loc int\n\n\tswitch treeNode.Exp {\n\tcase types.ConstK:\n\t\t\/\/ Gen code to load integer constant using LDC\n\t\tcodeBuf.emitRM(\"LDC\", ac, treeNode.Val, 0)\n\tcase types.IdK:\n\t\tloc = findLoc(bucketMap, treeNode.Name)\n\t\tcodeBuf.emitRM(\"LD\", ac, loc, gp)\n\tcase types.OpK:\n\t\tp1 = treeNode.Children[0]\n\t\tp2 = treeNode.Children[1]\n\t\t\/\/ Gen code for ac = left arg\n\t\tcGen(p1, bucketMap, codeBuf)\n\t\t\/\/ Gen code to push left operand\n\t\tcodeBuf.emitRM(\"ST\", ac, codeBuf.tmpOffset, mp)\n\t\tcodeBuf.tmpOffset -= 1\n\t\t\/\/ Gen code for ac = right operand\n\t\tcGen(p2, bucketMap, codeBuf)\n\t\t\/\/ Now load left operand\n\t\tcodeBuf.tmpOffset += 1\n\t\tcodeBuf.emitRM(\"LD\", ac1, codeBuf.tmpOffset, mp)\n\t\tswitch treeNode.Op {\n\t\tcase types.PLUS:\n\t\t\tcodeBuf.emitRO(\"ADD\", ac, ac1, ac)\n\t\tcase types.MINUS:\n\t\t\tcodeBuf.emitRO(\"SUB\", ac, ac1, ac)\n\t\tcase types.TIMES:\n\t\t\tcodeBuf.emitRO(\"MUL\", ac, ac1, ac)\n\t\tcase types.OVER:\n\t\t\tcodeBuf.emitRO(\"DIV\", ac, ac1, ac)\n\t\tcase types.LT:\n\t\t\tcodeBuf.emitRO(\"SUB\", ac, ac1, ac)\n\t\t\tcodeBuf.emitRM(\"JLT\", ac, 2, pc)\n\t\t\tcodeBuf.emitRM(\"LDC\", ac, 0, ac)\n\t\t\tcodeBuf.emitRM(\"LDA\", pc, 1, pc)\n\t\t\tcodeBuf.emitRM(\"LDC\", ac, 1, ac)\n\t\tcase types.EQ:\n\t\t\tcodeBuf.emitRO(\"SUB\", ac, ac1, ac)\n\t\t\tcodeBuf.emitRM(\"JEQ\", ac, 2, pc)\n\t\t\tcodeBuf.emitRM(\"LDC\", ac, 0, ac)\n\t\t\tcodeBuf.emitRM(\"LDA\", pc, 1, pc)\n\t\t\tcodeBuf.emitRM(\"LDC\", ac, 1, ac)\n\t\tdefault:\n\t\t\tpanic(errors.New(\"Unknown operator\"))\n\t\t}\n\t}\n}\n\n\/\/Procedure cGen recursively generates code by tree traversal\nfunc cGen(treeNode *types.TreeNode, bucketMap map[string]types.Bucket, codeBuf *codeBuffer) {\n\tif treeNode != nil {\n\t\tswitch treeNode.Node {\n\t\tcase types.StmtK:\n\t\t\tgenStmt(treeNode, bucketMap, codeBuf)\n\t\tcase types.ExpK:\n\t\t\tgenExp(treeNode, bucketMap, codeBuf)\n\t\tdefault:\n\t\t\terr := errors.New(\"Unknow type for code generation\")\n\t\t\tpanic(err)\n\t\t}\n\t\tcGen(treeNode.Sibling, bucketMap, codeBuf)\n\t}\n}\n\nfunc CodeGen(treeNode *types.TreeNode, bucketMap map[string]types.Bucket) []string {\n\tcodeBuf := &codeBuffer{make([]string, 0, 0), 0, 0, 0}\n\n\tcodeBuf.emitRM(\"LD\", mp, 0, ac)\n\tcodeBuf.emitRM(\"ST\", ac, 0, ac)\n\tcGen(treeNode, bucketMap, codeBuf)\n\tcodeBuf.emitRO(\"HALT\", 0, 0, 0)\n\n\treturn codeBuf.code\n}\n<commit_msg>Fixed bugs in code generation.<commit_after>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2016 Ivan Dejanovic\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\npackage codegen\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"mlpl\/types\"\n)\n\nconst (\n\tpc  int = 7 \/\/ pc = program counter\n\tmp  int = 6 \/\/ mp = \"memory pointer\" point to top of memory (for temp storage)\n\tgp  int = 5 \/\/ gp = \"global pointer\" points to bottom of memory for (global) variable storage\n\tac  int = 0 \/\/ accumulator\n\tac1 int = 1 \/\/ 2nd accumulator\n)\n\ntype codeBuffer struct {\n\tcode        []string\n\ttmpOffset   int \/\/ tmpOffset is the memory offset for temps. It is decremented each time a temp is stored, and incremeted when loaded again.\n\temitLoc     int \/\/ TM location number for current instruction emission\n\thighEmitLoc int \/\/ Highest TM location emitted so far. For use in conjunction with emitSkip, emitBackup, and emitRestore\n}\n\n\/* Procedure emitRO emits a register-only TM instruction\n   op = the opcode\n   r = target register\n   s = 1st source register\n   t = 2nd source register\n*\/\nfunc (codeBuf *codeBuffer) emitRO(op string, r int, s int, t int) {\n\tcode := fmt.Sprintf(\"%3d: %5s %d, %d, %d\", codeBuf.emitLoc, op, r, s, t)\n\tcodeBuf.emitLoc += 1\n\tif codeBuf.highEmitLoc < codeBuf.emitLoc {\n\t\tcodeBuf.highEmitLoc = codeBuf.emitLoc\n\t}\n\tcodeBuf.code = append(codeBuf.code, code)\n}\n\n\/* Procedure emitRM emits a register-to-memory TM instruction\n   op = the opcode\n   r = target register\n   d = the offset\n   s = the base register\n*\/\nfunc (codeBuf *codeBuffer) emitRM(op string, r int, d int, s int) {\n\tcode := fmt.Sprintf(\"%3d: %5s %d, %d(%d)\", codeBuf.emitLoc, op, r, d, s)\n\tcodeBuf.emitLoc += 1\n\tif codeBuf.highEmitLoc < codeBuf.emitLoc {\n\t\tcodeBuf.highEmitLoc = codeBuf.emitLoc\n\t}\n\tcodeBuf.code = append(codeBuf.code, code)\n}\n\n\/\/ Function emitSkip skips \"howMany\" code locations for later backpatch. It also returns the current code position\nfunc (codeBuf *codeBuffer) emitSkip(howMany int) int {\n\ti := codeBuf.emitLoc\n\tcodeBuf.emitLoc += howMany\n\tif codeBuf.highEmitLoc < codeBuf.emitLoc {\n\t\tcodeBuf.highEmitLoc = codeBuf.emitLoc\n\t}\n\n\treturn i\n}\n\n\/\/ Procedure emitBackup backs up to loc = a previously skipped location\nfunc (codeBuf *codeBuffer) emitBackup(loc int) {\n\tcodeBuf.emitLoc = loc\n}\n\n\/\/ Procedure emitRestore restores the current code position to the highest previously unemitted position\nfunc (codeBuf *codeBuffer) emitRestore() {\n\tcodeBuf.emitLoc = codeBuf.highEmitLoc\n}\n\n\/* Procedure emitRM_Abs converts an absolute reference to a pc-relative reference when emitting a register-to-memory TM instruction\n   op = the opcode\n   r = target register\n   a = the absolute location in memory\n*\/\nfunc (codeBuf *codeBuffer) emitRM_Abs(op string, r int, a int) {\n\tabs := a - (codeBuf.emitLoc + 1)\n\tcode := fmt.Sprintf(\"%3d: %5s %d, %d(%d)\", codeBuf.emitLoc, op, r, abs, pc)\n\tcodeBuf.emitLoc += 1\n\tif codeBuf.highEmitLoc < codeBuf.emitLoc {\n\t\tcodeBuf.highEmitLoc = codeBuf.emitLoc\n\t}\n\tcodeBuf.code = append(codeBuf.code, code)\n}\n\nfunc findLoc(bucketMap map[string]types.Bucket, name string) int {\n\tbucket, ok := bucketMap[name]\n\n\tif ok {\n\t\treturn bucket.MemLoc\n\t}\n\n\treturn -1\n}\n\n\/\/ Procedure genStmt generates code at a statement node\nfunc genStmt(treeNode *types.TreeNode, bucketMap map[string]types.Bucket, codeBuf *codeBuffer) {\n\tvar p1, p2, p3 *types.TreeNode = nil, nil, nil\n\tvar savedLoc1, savedLoc2, loc int\n\n\tswitch treeNode.Stmt {\n\tcase types.IfK:\n\t\tp1 = treeNode.Children[0]\n\t\tp2 = treeNode.Children[1]\n\t\tif len(treeNode.Children) == 3 {\n\t\t\tp3 = treeNode.Children[2]\n\t\t}\n\n\t\t\/\/ Generate code for test expression\n\t\tcGen(p1, bucketMap, codeBuf)\n\t\tsavedLoc1 = codeBuf.emitSkip(1)\n\n\t\t\/\/ Recurse on then part\n\t\tcGen(p2, bucketMap, codeBuf)\n\t\tsavedLoc2 = codeBuf.emitSkip(1)\n\t\tloc = codeBuf.emitSkip(0)\n\t\tcodeBuf.emitBackup(savedLoc1)\n\t\tcodeBuf.emitRM_Abs(\"JEQ\", ac, loc)\n\t\tcodeBuf.emitRestore()\n\n\t\t\/\/ Recurse on else part\n\t\tcGen(p3, bucketMap, codeBuf)\n\t\tloc = codeBuf.emitSkip(0)\n\t\tcodeBuf.emitBackup(savedLoc2)\n\t\tcodeBuf.emitRM_Abs(\"LDA\", pc, loc)\n\t\tcodeBuf.emitRestore()\n\tcase types.RepeatK:\n\t\tp1 = treeNode.Children[0]\n\t\tp2 = treeNode.Children[1]\n\t\tloc = codeBuf.emitSkip(0)\n\n\t\t\/\/ Generate code for body\n\t\tcGen(p1, bucketMap, codeBuf)\n\t\t\/\/ Generate code for test\n\t\tcGen(p2, bucketMap, codeBuf)\n\n\t\tcodeBuf.emitRM_Abs(\"JEQ\", ac, loc)\n\tcase types.AssignK:\n\t\t\/\/ Generate code for rhs\n\t\tp1 = treeNode.Children[0]\n\t\tcGen(p1, bucketMap, codeBuf)\n\t\t\/\/ Now store value\n\t\tloc = findLoc(bucketMap, treeNode.Name)\n\t\tcodeBuf.emitRM(\"ST\", ac, loc, gp)\n\tcase types.ReadK:\n\t\tcodeBuf.emitRO(\"IN\", ac, 0, 0)\n\t\tloc = findLoc(bucketMap, treeNode.Name)\n\t\tcodeBuf.emitRM(\"ST\", ac, loc, gp)\n\tcase types.WriteK:\n\t\t\/\/ Generate code for expression to write\n\t\tp1 = treeNode.Children[0]\n\t\tcGen(p1, bucketMap, codeBuf)\n\t\t\/\/ Now output it\n\t\tcodeBuf.emitRO(\"OUT\", ac, 0, 0)\n\t}\n}\n\n\/\/ Procedure genExp generates code at an expression node\nfunc genExp(treeNode *types.TreeNode, bucketMap map[string]types.Bucket, codeBuf *codeBuffer) {\n\tvar p1, p2 *types.TreeNode\n\tvar loc int\n\n\tswitch treeNode.Exp {\n\tcase types.ConstK:\n\t\t\/\/ Gen code to load integer constant using LDC\n\t\tcodeBuf.emitRM(\"LDC\", ac, treeNode.Val, 0)\n\tcase types.IdK:\n\t\tloc = findLoc(bucketMap, treeNode.Name)\n\t\tcodeBuf.emitRM(\"LD\", ac, loc, gp)\n\tcase types.OpK:\n\t\tp1 = treeNode.Children[0]\n\t\tp2 = treeNode.Children[1]\n\t\t\/\/ Gen code for ac = left arg\n\t\tcGen(p1, bucketMap, codeBuf)\n\t\t\/\/ Gen code to push left operand\n\t\tcodeBuf.emitRM(\"ST\", ac, codeBuf.tmpOffset, mp)\n\t\tcodeBuf.tmpOffset -= 1\n\t\t\/\/ Gen code for ac = right operand\n\t\tcGen(p2, bucketMap, codeBuf)\n\t\t\/\/ Now load left operand\n\t\tcodeBuf.tmpOffset += 1\n\t\tcodeBuf.emitRM(\"LD\", ac1, codeBuf.tmpOffset, mp)\n\t\tswitch treeNode.Op {\n\t\tcase types.PLUS:\n\t\t\tcodeBuf.emitRO(\"ADD\", ac, ac1, ac)\n\t\tcase types.MINUS:\n\t\t\tcodeBuf.emitRO(\"SUB\", ac, ac1, ac)\n\t\tcase types.TIMES:\n\t\t\tcodeBuf.emitRO(\"MUL\", ac, ac1, ac)\n\t\tcase types.OVER:\n\t\t\tcodeBuf.emitRO(\"DIV\", ac, ac1, ac)\n\t\tcase types.LT:\n\t\t\tcodeBuf.emitRO(\"SUB\", ac, ac1, ac)\n\t\t\tcodeBuf.emitRM(\"JLT\", ac, 2, pc)\n\t\t\tcodeBuf.emitRM(\"LDC\", ac, 0, ac)\n\t\t\tcodeBuf.emitRM(\"LDA\", pc, 1, pc)\n\t\t\tcodeBuf.emitRM(\"LDC\", ac, 1, ac)\n\t\tcase types.EQ:\n\t\t\tcodeBuf.emitRO(\"SUB\", ac, ac1, ac)\n\t\t\tcodeBuf.emitRM(\"JEQ\", ac, 2, pc)\n\t\t\tcodeBuf.emitRM(\"LDC\", ac, 0, ac)\n\t\t\tcodeBuf.emitRM(\"LDA\", pc, 1, pc)\n\t\t\tcodeBuf.emitRM(\"LDC\", ac, 1, ac)\n\t\tdefault:\n\t\t\tpanic(errors.New(\"Unknown operator\"))\n\t\t}\n\t}\n}\n\n\/\/Procedure cGen recursively generates code by tree traversal\nfunc cGen(treeNode *types.TreeNode, bucketMap map[string]types.Bucket, codeBuf *codeBuffer) {\n\tif treeNode != nil {\n\t\tswitch treeNode.Node {\n\t\tcase types.StmtK:\n\t\t\tgenStmt(treeNode, bucketMap, codeBuf)\n\t\tcase types.ExpK:\n\t\t\tgenExp(treeNode, bucketMap, codeBuf)\n\t\tdefault:\n\t\t\terr := errors.New(\"Unknow type for code generation\")\n\t\t\tpanic(err)\n\t\t}\n\t\tcGen(treeNode.Sibling, bucketMap, codeBuf)\n\t}\n}\n\nfunc CodeGen(treeNode *types.TreeNode, bucketMap map[string]types.Bucket) []string {\n\tcodeBuf := &codeBuffer{make([]string, 0, 0), 0, 0, 0}\n\n\tcodeBuf.emitRM(\"LD\", mp, 0, ac)\n\tcodeBuf.emitRM(\"ST\", ac, 0, ac)\n\tcGen(treeNode, bucketMap, codeBuf)\n\tcodeBuf.emitRO(\"HALT\", 0, 0, 0)\n\n\treturn codeBuf.code\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2020 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package fieldalignment defines an Analyzer that detects structs that would use less\n\/\/ memory if their fields were sorted.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"golang.org\/x\/tools\/go\/analysis\"\n\t\"golang.org\/x\/tools\/go\/analysis\/passes\/inspect\"\n\t\"golang.org\/x\/tools\/go\/ast\/inspector\"\n)\n\nconst Doc = `find structs that would use less memory if their fields were sorted\n\nThis analyzer find structs that can be rearranged to use less memory, and provides\na suggested edit with the most compact order.\n\nNote that there are two different diagnostics reported. One checks struct size,\nand the other reports \"pointer bytes\" used. Pointer bytes is how many bytes of the\nobject that the garbage collector has to potentially scan for pointers, for example:\n\n\tstruct { uint32; string }\n\nhave 16 pointer bytes because the garbage collector has to scan up through the string's\ninner pointer.\n\n\tstruct { string; *uint32 }\n\nhas 24 pointer bytes because it has to scan further through the *uint32.\n\n\tstruct { string; uint32 }\n\nhas 8 because it can stop immediately after the string pointer.\n\nBe aware that the most compact order is not always the most efficient.\nIn rare cases it may cause two variables each updated by its own goroutine\nto occupy the same CPU cache line, inducing a form of memory contention\nknown as \"false sharing\" that slows down both goroutines.\n`\n\nvar Analyzer = &analysis.Analyzer{\n\tName:     \"fieldalignment\",\n\tDoc:      Doc,\n\tRequires: []*analysis.Analyzer{inspect.Analyzer},\n\tRun:      run,\n}\n\nfunc run(pass *analysis.Pass) (interface{}, error) {\n\tinspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)\n\tnodeFilter := []ast.Node{\n\t\t(*ast.File)(nil),\n\t\t(*ast.StructType)(nil),\n\t}\n\tvar ignore bool\n\tinspect.Preorder(nodeFilter, func(node ast.Node) {\n\t\tif ignore {\n\t\t\treturn\n\t\t}\n\n\t\tif nf, ok := node.(*ast.File); ok {\n\t\t\tf := pass.Fset.File(nf.Pos())\n\t\t\t\/\/ protobuf 自动生成的 go 文，其编解码器直接依赖其生成的字段顺序，不能优化\n\t\t\tif strings.HasSuffix(f.Name(), \".pb.go\") ||\n\t\t\t\tstrings.HasSuffix(f.Name(), \"_test.go\") ||\n\t\t\t\tdoNotEdit(nf) {\n\t\t\t\tignore = true\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tvar s *ast.StructType\n\t\tvar ok bool\n\t\tif s, ok = node.(*ast.StructType); !ok {\n\t\t\treturn\n\t\t}\n\t\tif tv, ok := pass.TypesInfo.Types[s]; ok {\n\t\t\tif ss, ok1 := tv.Type.(*types.Struct); ok1 {\n\t\t\t\tfieldalignment(pass, s, ss)\n\t\t\t}\n\t\t}\n\t})\n\treturn nil, nil\n}\n\nfunc doNotEdit(f *ast.File) bool {\n\tfor _, cg := range f.Comments {\n\t\tif strings.Contains(cg.Text(), \"DO NOT EDIT\") {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nvar unsafePointerTyp = types.Unsafe.Scope().Lookup(\"Pointer\").(*types.TypeName).Type()\n\nfunc fieldalignment(pass *analysis.Pass, node *ast.StructType, typ *types.Struct) {\n\twordSize := pass.TypesSizes.Sizeof(unsafePointerTyp)\n\tmaxAlign := pass.TypesSizes.Alignof(unsafePointerTyp)\n\n\ts := gcSizes{WordSize: wordSize, MaxAlign: maxAlign}\n\toptimal, indexes := optimalOrder(typ, &s)\n\toptsz, optptrs := s.Sizeof(optimal), s.ptrdata(optimal)\n\n\tvar message string\n\tif sz := s.Sizeof(typ); sz != optsz {\n\t\tmessage = fmt.Sprintf(\"struct of size %d could be %d\", sz, optsz)\n\t} else if ptrs := s.ptrdata(typ); ptrs != optptrs {\n\t\tmessage = fmt.Sprintf(\"struct with %d pointer bytes could be %d\", ptrs, optptrs)\n\t} else {\n\t\t\/\/ Already optimal order.\n\t\treturn\n\t}\n\n\tafter, err := doFix(pass, node, indexes)\n\tif err != nil {\n\t\tlog.Println(message)\n\t\tlog.Println(\"doFix has error:\", err.Error())\n\t\treturn\n\t}\n\n\tpass.Report(analysis.Diagnostic{\n\t\tPos:     node.Pos(),\n\t\tEnd:     node.Pos() + token.Pos(len(\"struct\")),\n\t\tMessage: message,\n\t\tSuggestedFixes: []analysis.SuggestedFix{{\n\t\t\tMessage: \"Rearrange fields\",\n\t\t\tTextEdits: []analysis.TextEdit{{\n\t\t\t\tPos:     node.Pos(),\n\t\t\t\tEnd:     node.End(),\n\t\t\t\tNewText: after,\n\t\t\t}},\n\t\t}},\n\t})\n}\n\nfunc optimalOrder(str *types.Struct, sizes *gcSizes) (*types.Struct, []int) {\n\tnf := str.NumFields()\n\n\ttype elem struct {\n\t\tindex   int\n\t\talignof int64\n\t\tsizeof  int64\n\t\tptrdata int64\n\t}\n\n\telems := make([]elem, nf)\n\tfor i := 0; i < nf; i++ {\n\t\tfield := str.Field(i)\n\t\tft := field.Type()\n\t\telems[i] = elem{\n\t\t\tindex:   i,\n\t\t\talignof: sizes.Alignof(ft),\n\t\t\tsizeof:  sizes.Sizeof(ft),\n\t\t\tptrdata: sizes.ptrdata(ft),\n\t\t}\n\t}\n\n\tsort.Slice(elems, func(i, j int) bool {\n\t\tei := &elems[i]\n\t\tej := &elems[j]\n\n\t\t\/\/ Place zero sized objects before non-zero sized objects.\n\t\tzeroi := ei.sizeof == 0\n\t\tzeroj := ej.sizeof == 0\n\t\tif zeroi != zeroj {\n\t\t\treturn zeroi\n\t\t}\n\n\t\t\/\/ Next, place more tightly aligned objects before less tightly aligned objects.\n\t\tif ei.alignof != ej.alignof {\n\t\t\treturn ei.alignof > ej.alignof\n\t\t}\n\n\t\t\/\/ Place pointerful objects before pointer-free objects.\n\t\tnoptrsi := ei.ptrdata == 0\n\t\tnoptrsj := ej.ptrdata == 0\n\t\tif noptrsi != noptrsj {\n\t\t\treturn noptrsj\n\t\t}\n\n\t\tif !noptrsi {\n\t\t\t\/\/ If both have pointers...\n\n\t\t\t\/\/ ... then place objects with less trailing\n\t\t\t\/\/ non-pointer bytes earlier. That is, place\n\t\t\t\/\/ the field with the most trailing\n\t\t\t\/\/ non-pointer bytes at the end of the\n\t\t\t\/\/ pointerful section.\n\t\t\ttraili := ei.sizeof - ei.ptrdata\n\t\t\ttrailj := ej.sizeof - ej.ptrdata\n\t\t\tif traili != trailj {\n\t\t\t\treturn traili < trailj\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Lastly, order by size.\n\t\tif ei.sizeof != ej.sizeof {\n\t\t\treturn ei.sizeof > ej.sizeof\n\t\t}\n\n\t\treturn false\n\t})\n\n\tfields := make([]*types.Var, nf)\n\tindexes := make([]int, nf)\n\tfor i, e := range elems {\n\t\tfields[i] = str.Field(e.index)\n\t\tindexes[i] = e.index\n\t}\n\treturn types.NewStruct(fields, nil), indexes\n}\n\n\/\/ Code below based on go\/types.StdSizes.\n\ntype gcSizes struct {\n\tWordSize int64\n\tMaxAlign int64\n}\n\nfunc (s *gcSizes) Alignof(T types.Type) int64 {\n\t\/\/ For arrays and structs, alignment is defined in terms\n\t\/\/ of alignment of the elements and fields, respectively.\n\tswitch t := T.Underlying().(type) {\n\tcase *types.Array:\n\t\t\/\/ spec: \"For a variable x of array type: unsafe.Alignof(x)\n\t\t\/\/ is the same as unsafe.Alignof(x[0]), but at least 1.\"\n\t\treturn s.Alignof(t.Elem())\n\tcase *types.Struct:\n\t\t\/\/ spec: \"For a variable x of struct type: unsafe.Alignof(x)\n\t\t\/\/ is the largest of the values unsafe.Alignof(x.f) for each\n\t\t\/\/ field f of x, but at least 1.\"\n\t\tmax := int64(1)\n\t\tfor i, nf := 0, t.NumFields(); i < nf; i++ {\n\t\t\tif a := s.Alignof(t.Field(i).Type()); a > max {\n\t\t\t\tmax = a\n\t\t\t}\n\t\t}\n\t\treturn max\n\t}\n\ta := s.Sizeof(T) \/\/ may be 0\n\t\/\/ spec: \"For a variable x of any type: unsafe.Alignof(x) is at least 1.\"\n\tif a < 1 {\n\t\treturn 1\n\t}\n\tif a > s.MaxAlign {\n\t\treturn s.MaxAlign\n\t}\n\treturn a\n}\n\nvar basicSizes = [...]byte{\n\ttypes.Bool:       1,\n\ttypes.Int8:       1,\n\ttypes.Int16:      2,\n\ttypes.Int32:      4,\n\ttypes.Int64:      8,\n\ttypes.Uint8:      1,\n\ttypes.Uint16:     2,\n\ttypes.Uint32:     4,\n\ttypes.Uint64:     8,\n\ttypes.Float32:    4,\n\ttypes.Float64:    8,\n\ttypes.Complex64:  8,\n\ttypes.Complex128: 16,\n}\n\nfunc (s *gcSizes) Sizeof(T types.Type) int64 {\n\tswitch t := T.Underlying().(type) {\n\tcase *types.Basic:\n\t\tk := t.Kind()\n\t\tif int(k) < len(basicSizes) {\n\t\t\tif s := basicSizes[k]; s > 0 {\n\t\t\t\treturn int64(s)\n\t\t\t}\n\t\t}\n\t\tif k == types.String {\n\t\t\treturn s.WordSize * 2\n\t\t}\n\tcase *types.Array:\n\t\treturn t.Len() * s.Sizeof(t.Elem())\n\tcase *types.Slice:\n\t\treturn s.WordSize * 3\n\tcase *types.Struct:\n\t\tnf := t.NumFields()\n\t\tif nf == 0 {\n\t\t\treturn 0\n\t\t}\n\n\t\tvar o int64\n\t\tmax := int64(1)\n\t\tfor i := 0; i < nf; i++ {\n\t\t\tft := t.Field(i).Type()\n\t\t\ta, sz := s.Alignof(ft), s.Sizeof(ft)\n\t\t\tif a > max {\n\t\t\t\tmax = a\n\t\t\t}\n\t\t\tif i == nf-1 && sz == 0 && o != 0 {\n\t\t\t\tsz = 1\n\t\t\t}\n\t\t\to = align(o, a) + sz\n\t\t}\n\t\treturn align(o, max)\n\tcase *types.Interface:\n\t\treturn s.WordSize * 2\n\t}\n\treturn s.WordSize \/\/ catch-all\n}\n\n\/\/ align returns the smallest y >= x such that y % a == 0.\nfunc align(x, a int64) int64 {\n\ty := x + a - 1\n\treturn y - y%a\n}\n\nfunc (s *gcSizes) ptrdata(T types.Type) int64 {\n\tswitch t := T.Underlying().(type) {\n\tcase *types.Basic:\n\t\tswitch t.Kind() {\n\t\tcase types.String, types.UnsafePointer:\n\t\t\treturn s.WordSize\n\t\t}\n\t\treturn 0\n\tcase *types.Chan, *types.Map, *types.Pointer, *types.Signature, *types.Slice:\n\t\treturn s.WordSize\n\tcase *types.Interface:\n\t\treturn 2 * s.WordSize\n\tcase *types.Array:\n\t\tn := t.Len()\n\t\tif n == 0 {\n\t\t\treturn 0\n\t\t}\n\t\ta := s.ptrdata(t.Elem())\n\t\tif a == 0 {\n\t\t\treturn 0\n\t\t}\n\t\tz := s.Sizeof(t.Elem())\n\t\treturn (n-1)*z + a\n\tcase *types.Struct:\n\t\tnf := t.NumFields()\n\t\tif nf == 0 {\n\t\t\treturn 0\n\t\t}\n\n\t\tvar o, p int64\n\t\tfor i := 0; i < nf; i++ {\n\t\t\tft := t.Field(i).Type()\n\t\t\ta, sz := s.Alignof(ft), s.Sizeof(ft)\n\t\t\tfp := s.ptrdata(ft)\n\t\t\to = align(o, a)\n\t\t\tif fp != 0 {\n\t\t\t\tp = o + fp\n\t\t\t}\n\t\t\to += sz\n\t\t}\n\t\treturn p\n\t}\n\n\tpanic(\"impossible\")\n}\n<commit_msg>update<commit_after>\/\/ Copyright 2020 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package fieldalignment defines an Analyzer that detects structs that would use less\n\/\/ memory if their fields were sorted.\npackage main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/format\"\n\t\"go\/token\"\n\t\"go\/types\"\n\t\"log\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"golang.org\/x\/tools\/go\/analysis\"\n\t\"golang.org\/x\/tools\/go\/analysis\/passes\/inspect\"\n\t\"golang.org\/x\/tools\/go\/ast\/inspector\"\n)\n\nconst Doc = `find structs that would use less memory if their fields were sorted\n\nThis analyzer find structs that can be rearranged to use less memory, and provides\na suggested edit with the most compact order.\n\nNote that there are two different diagnostics reported. One checks struct size,\nand the other reports \"pointer bytes\" used. Pointer bytes is how many bytes of the\nobject that the garbage collector has to potentially scan for pointers, for example:\n\n\tstruct { uint32; string }\n\nhave 16 pointer bytes because the garbage collector has to scan up through the string's\ninner pointer.\n\n\tstruct { string; *uint32 }\n\nhas 24 pointer bytes because it has to scan further through the *uint32.\n\n\tstruct { string; uint32 }\n\nhas 8 because it can stop immediately after the string pointer.\n\nBe aware that the most compact order is not always the most efficient.\nIn rare cases it may cause two variables each updated by its own goroutine\nto occupy the same CPU cache line, inducing a form of memory contention\nknown as \"false sharing\" that slows down both goroutines.\n`\n\nvar Analyzer = &analysis.Analyzer{\n\tName:     \"fieldalignment\",\n\tDoc:      Doc,\n\tRequires: []*analysis.Analyzer{inspect.Analyzer},\n\tRun:      run,\n}\n\nvar debug bool\n\nfunc run(pass *analysis.Pass) (interface{}, error) {\n\tif ft := flag.Lookup(\"v\"); ft != nil {\n\t\tdebug, _ = strconv.ParseBool(ft.Value.String())\n\t}\n\n\tinspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)\n\tnodeFilter := []ast.Node{\n\t\t(*ast.File)(nil),\n\t\t(*ast.StructType)(nil),\n\t}\n\n\tvar ignore bool\n\tinspect.Preorder(nodeFilter, func(node ast.Node) {\n\t\tif ignore {\n\t\t\treturn\n\t\t}\n\n\t\tif nf, ok := node.(*ast.File); ok {\n\t\t\tf := pass.Fset.File(nf.Pos())\n\t\t\t\/\/ protobuf 自动生成的 go 文，其编解码器直接依赖其生成的字段顺序，不能优化\n\t\t\tif strings.HasSuffix(f.Name(), \".pb.go\") ||\n\t\t\t\tstrings.HasSuffix(f.Name(), \"_test.go\") ||\n\t\t\t\tdoNotEdit(nf) {\n\t\t\t\tignore = true\n\t\t\t\tif debug {\n\t\t\t\t\tlog.Println(\"ignore:\", f.Name())\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tvar s *ast.StructType\n\t\tvar ok bool\n\t\tif s, ok = node.(*ast.StructType); !ok {\n\t\t\treturn\n\t\t}\n\t\tif tv, ok := pass.TypesInfo.Types[s]; ok {\n\t\t\tif ss, ok1 := tv.Type.(*types.Struct); ok1 {\n\t\t\t\tfieldalignment(pass, s, ss)\n\t\t\t}\n\t\t}\n\t})\n\treturn nil, nil\n}\n\nfunc doNotEdit(f *ast.File) bool {\n\tfor _, cg := range f.Comments {\n\t\tif strings.Contains(cg.Text(), \"DO NOT EDIT\") {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nvar unsafePointerTyp = types.Unsafe.Scope().Lookup(\"Pointer\").(*types.TypeName).Type()\n\nfunc fieldalignment(pass *analysis.Pass, node *ast.StructType, typ *types.Struct) {\n\twordSize := pass.TypesSizes.Sizeof(unsafePointerTyp)\n\tmaxAlign := pass.TypesSizes.Alignof(unsafePointerTyp)\n\n\ts := gcSizes{WordSize: wordSize, MaxAlign: maxAlign}\n\toptimal, indexes := optimalOrder(typ, &s)\n\toptsz, optptrs := s.Sizeof(optimal), s.ptrdata(optimal)\n\n\tbuf := &bytes.Buffer{}\n\t_ = format.Node(buf, pass.Fset, node)\n\n\tvar message string\n\tif sz := s.Sizeof(typ); sz != optsz {\n\t\tmessage += fmt.Sprintf(\"struct of size %d could be %d \", sz, optsz)\n\t} else if ptrs := s.ptrdata(typ); ptrs != optptrs {\n\t\tmessage += fmt.Sprintf(\"struct with %d pointer bytes could be %d \", ptrs, optptrs)\n\t} else {\n\t\t\/\/ Already optimal order.\n\t\tmessage += fmt.Sprintf(\"Already optimal order. struct of size %d, pointer bytes %d\", sz, ptrs)\n\t\tmessage += \"\\n\" + buf.String()\n\t\tif debug {\n\t\t\tpass.Report(analysis.Diagnostic{\n\t\t\t\tPos:     node.Pos(),\n\t\t\t\tEnd:     node.Pos() + token.Pos(len(\"struct\")),\n\t\t\t\tMessage: message,\n\t\t\t})\n\t\t}\n\t\treturn\n\t}\n\tif debug {\n\t\tmessage += \"\\n\" + buf.String()\n\t}\n\n\tafter, err := doFix(pass, node, indexes)\n\tif err != nil {\n\t\tlog.Println(message)\n\t\tlog.Println(\"doFix has error:\", err.Error())\n\t\treturn\n\t}\n\n\tif debug {\n\t\tmessage += \"\\nCurrent ↑↑↑\" + strings.Repeat(\">\", 100) + \"Expect ↓↓↓\\n\" + string(after)\n\t}\n\n\tpass.Report(analysis.Diagnostic{\n\t\tPos:     node.Pos(),\n\t\tEnd:     node.Pos() + token.Pos(len(\"struct\")),\n\t\tMessage: message,\n\t\tSuggestedFixes: []analysis.SuggestedFix{{\n\t\t\tMessage: \"Rearrange fields\",\n\t\t\tTextEdits: []analysis.TextEdit{{\n\t\t\t\tPos:     node.Pos(),\n\t\t\t\tEnd:     node.End(),\n\t\t\t\tNewText: after,\n\t\t\t}},\n\t\t}},\n\t})\n}\n\nfunc optimalOrder(str *types.Struct, sizes *gcSizes) (*types.Struct, []int) {\n\tnf := str.NumFields()\n\n\ttype elem struct {\n\t\tindex   int\n\t\talignof int64\n\t\tsizeof  int64\n\t\tptrdata int64\n\t}\n\n\telems := make([]elem, nf)\n\tfor i := 0; i < nf; i++ {\n\t\tfield := str.Field(i)\n\t\tft := field.Type()\n\t\telems[i] = elem{\n\t\t\tindex:   i,\n\t\t\talignof: sizes.Alignof(ft),\n\t\t\tsizeof:  sizes.Sizeof(ft),\n\t\t\tptrdata: sizes.ptrdata(ft),\n\t\t}\n\t}\n\n\tsort.Slice(elems, func(i, j int) bool {\n\t\tei := &elems[i]\n\t\tej := &elems[j]\n\n\t\t\/\/ Place zero sized objects before non-zero sized objects.\n\t\tzeroi := ei.sizeof == 0\n\t\tzeroj := ej.sizeof == 0\n\t\tif zeroi != zeroj {\n\t\t\treturn zeroi\n\t\t}\n\n\t\t\/\/ Next, place more tightly aligned objects before less tightly aligned objects.\n\t\tif ei.alignof != ej.alignof {\n\t\t\treturn ei.alignof > ej.alignof\n\t\t}\n\n\t\t\/\/ Place pointerful objects before pointer-free objects.\n\t\tnoptrsi := ei.ptrdata == 0\n\t\tnoptrsj := ej.ptrdata == 0\n\t\tif noptrsi != noptrsj {\n\t\t\treturn noptrsj\n\t\t}\n\n\t\tif !noptrsi {\n\t\t\t\/\/ If both have pointers...\n\n\t\t\t\/\/ ... then place objects with less trailing\n\t\t\t\/\/ non-pointer bytes earlier. That is, place\n\t\t\t\/\/ the field with the most trailing\n\t\t\t\/\/ non-pointer bytes at the end of the\n\t\t\t\/\/ pointerful section.\n\t\t\ttraili := ei.sizeof - ei.ptrdata\n\t\t\ttrailj := ej.sizeof - ej.ptrdata\n\t\t\tif traili != trailj {\n\t\t\t\treturn traili < trailj\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Lastly, order by size.\n\t\tif ei.sizeof != ej.sizeof {\n\t\t\treturn ei.sizeof > ej.sizeof\n\t\t}\n\n\t\treturn false\n\t})\n\n\tfields := make([]*types.Var, nf)\n\tindexes := make([]int, nf)\n\tfor i, e := range elems {\n\t\tfields[i] = str.Field(e.index)\n\t\tindexes[i] = e.index\n\t}\n\treturn types.NewStruct(fields, nil), indexes\n}\n\n\/\/ Code below based on go\/types.StdSizes.\n\ntype gcSizes struct {\n\tWordSize int64\n\tMaxAlign int64\n}\n\nfunc (s *gcSizes) Alignof(T types.Type) int64 {\n\t\/\/ For arrays and structs, alignment is defined in terms\n\t\/\/ of alignment of the elements and fields, respectively.\n\tswitch t := T.Underlying().(type) {\n\tcase *types.Array:\n\t\t\/\/ spec: \"For a variable x of array type: unsafe.Alignof(x)\n\t\t\/\/ is the same as unsafe.Alignof(x[0]), but at least 1.\"\n\t\treturn s.Alignof(t.Elem())\n\tcase *types.Struct:\n\t\t\/\/ spec: \"For a variable x of struct type: unsafe.Alignof(x)\n\t\t\/\/ is the largest of the values unsafe.Alignof(x.f) for each\n\t\t\/\/ field f of x, but at least 1.\"\n\t\tmax := int64(1)\n\t\tfor i, nf := 0, t.NumFields(); i < nf; i++ {\n\t\t\tif a := s.Alignof(t.Field(i).Type()); a > max {\n\t\t\t\tmax = a\n\t\t\t}\n\t\t}\n\t\treturn max\n\t}\n\ta := s.Sizeof(T) \/\/ may be 0\n\t\/\/ spec: \"For a variable x of any type: unsafe.Alignof(x) is at least 1.\"\n\tif a < 1 {\n\t\treturn 1\n\t}\n\tif a > s.MaxAlign {\n\t\treturn s.MaxAlign\n\t}\n\treturn a\n}\n\nvar basicSizes = [...]byte{\n\ttypes.Bool:       1,\n\ttypes.Int8:       1,\n\ttypes.Int16:      2,\n\ttypes.Int32:      4,\n\ttypes.Int64:      8,\n\ttypes.Uint8:      1,\n\ttypes.Uint16:     2,\n\ttypes.Uint32:     4,\n\ttypes.Uint64:     8,\n\ttypes.Float32:    4,\n\ttypes.Float64:    8,\n\ttypes.Complex64:  8,\n\ttypes.Complex128: 16,\n}\n\nfunc (s *gcSizes) Sizeof(T types.Type) int64 {\n\tswitch t := T.Underlying().(type) {\n\tcase *types.Basic:\n\t\tk := t.Kind()\n\t\tif int(k) < len(basicSizes) {\n\t\t\tif s := basicSizes[k]; s > 0 {\n\t\t\t\treturn int64(s)\n\t\t\t}\n\t\t}\n\t\tif k == types.String {\n\t\t\treturn s.WordSize * 2\n\t\t}\n\tcase *types.Array:\n\t\treturn t.Len() * s.Sizeof(t.Elem())\n\tcase *types.Slice:\n\t\treturn s.WordSize * 3\n\tcase *types.Struct:\n\t\tnf := t.NumFields()\n\t\tif nf == 0 {\n\t\t\treturn 0\n\t\t}\n\n\t\tvar o int64\n\t\tmax := int64(1)\n\t\tfor i := 0; i < nf; i++ {\n\t\t\tft := t.Field(i).Type()\n\t\t\ta, sz := s.Alignof(ft), s.Sizeof(ft)\n\t\t\tif a > max {\n\t\t\t\tmax = a\n\t\t\t}\n\t\t\tif i == nf-1 && sz == 0 && o != 0 {\n\t\t\t\tsz = 1\n\t\t\t}\n\t\t\to = align(o, a) + sz\n\t\t}\n\t\treturn align(o, max)\n\tcase *types.Interface:\n\t\treturn s.WordSize * 2\n\t}\n\treturn s.WordSize \/\/ catch-all\n}\n\n\/\/ align returns the smallest y >= x such that y % a == 0.\nfunc align(x, a int64) int64 {\n\ty := x + a - 1\n\treturn y - y%a\n}\n\nfunc (s *gcSizes) ptrdata(T types.Type) int64 {\n\tswitch t := T.Underlying().(type) {\n\tcase *types.Basic:\n\t\tswitch t.Kind() {\n\t\tcase types.String, types.UnsafePointer:\n\t\t\treturn s.WordSize\n\t\t}\n\t\treturn 0\n\tcase *types.Chan, *types.Map, *types.Pointer, *types.Signature, *types.Slice:\n\t\treturn s.WordSize\n\tcase *types.Interface:\n\t\treturn 2 * s.WordSize\n\tcase *types.Array:\n\t\tn := t.Len()\n\t\tif n == 0 {\n\t\t\treturn 0\n\t\t}\n\t\ta := s.ptrdata(t.Elem())\n\t\tif a == 0 {\n\t\t\treturn 0\n\t\t}\n\t\tz := s.Sizeof(t.Elem())\n\t\treturn (n-1)*z + a\n\tcase *types.Struct:\n\t\tnf := t.NumFields()\n\t\tif nf == 0 {\n\t\t\treturn 0\n\t\t}\n\n\t\tvar o, p int64\n\t\tfor i := 0; i < nf; i++ {\n\t\t\tft := t.Field(i).Type()\n\t\t\ta, sz := s.Alignof(ft), s.Sizeof(ft)\n\t\t\tfp := s.ptrdata(ft)\n\t\t\to = align(o, a)\n\t\t\tif fp != 0 {\n\t\t\t\tp = o + fp\n\t\t\t}\n\t\t\to += sz\n\t\t}\n\t\treturn p\n\t}\n\n\tpanic(\"impossible\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com\/keybase\/cli\"\n\t\"github.com\/keybase\/client\/go\/libcmdline\"\n\t\"github.com\/keybase\/client\/go\/libkb\"\n\t\"github.com\/keybase\/client\/go\/protocol\/chat1\"\n\t\"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n)\n\ntype CmdChatCreateChannel struct {\n\tg *libkb.GlobalContext\n\n\tresolvingRequest chatConversationResolvingRequest\n}\n\nfunc NewCmdChatCreateChannelRunner(g *libkb.GlobalContext) *CmdChatCreateChannel {\n\treturn &CmdChatCreateChannel{\n\t\tg: g,\n\t}\n}\n\nfunc newCmdChatCreateChannel(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {\n\treturn cli.Command{\n\t\tName:         \"create-channel\",\n\t\tUsage:        \"Create a conversation channel\",\n\t\tArgumentHelp: \"<team name> <channel name>\",\n\t\tAction: func(c *cli.Context) {\n\t\t\tcl.ChooseCommand(NewCmdChatCreateChannelRunner(g), \"create-channel\", c)\n\t\t},\n\t\tFlags: mustGetChatFlags(\"topic-type\"),\n\t}\n}\n\nfunc (c *CmdChatCreateChannel) Run() error {\n\tc.g.StartStandaloneChat()\n\treturn chatSend(context.TODO(), c.g, ChatSendArg{\n\t\tresolvingRequest: c.resolvingRequest,\n\t\tnonBlock:         false,\n\t\tteam:             true,\n\t\tmessage:          fmt.Sprintf(\"Welcome to #%s!\", c.resolvingRequest.TopicName),\n\t\tsetHeadline:      \"\",\n\t\tclearHeadline:    false,\n\t\thasTTY:           true,\n\t\tsetTopicName:     \"\",\n\t\tmustNotExist:     true,\n\t})\n}\n\nfunc (c *CmdChatCreateChannel) ParseArgv(ctx *cli.Context) (err error) {\n\n\tvar tlfName, topicName string\n\tvar topicType chat1.TopicType\n\n\tif len(ctx.Args()) == 2 {\n\t\ttlfName = ctx.Args().Get(0)\n\t\ttopicName = ctx.Args().Get(1)\n\t} else {\n\t\treturn fmt.Errorf(\"create channel takes two arguments.\")\n\t}\n\tif topicType, err = parseConversationTopicType(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tc.resolvingRequest.TlfName = tlfName\n\tc.resolvingRequest.TopicType = topicType\n\tc.resolvingRequest.TopicName = topicName\n\tc.resolvingRequest.MembersType = chat1.ConversationMembersType_TEAM\n\tc.resolvingRequest.Visibility = keybase1.TLFVisibility_PRIVATE\n\n\treturn nil\n}\n\nfunc (c *CmdChatCreateChannel) GetUsage() libkb.Usage {\n\treturn libkb.Usage{\n\t\tConfig: true,\n\t\tAPI:    true,\n\t}\n}\n<commit_msg>Fix chat create-channel to use NewConversation<commit_after>package client\n\nimport (\n\t\"errors\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/keybase\/cli\"\n\t\"github.com\/keybase\/client\/go\/libcmdline\"\n\t\"github.com\/keybase\/client\/go\/libkb\"\n\t\"github.com\/keybase\/client\/go\/protocol\/chat1\"\n\t\"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n)\n\ntype CmdChatCreateChannel struct {\n\tlibkb.Contextified\n\tteamName    string\n\tchannelName string\n\ttopicType   chat1.TopicType\n}\n\nfunc NewCmdChatCreateChannelRunner(g *libkb.GlobalContext) *CmdChatCreateChannel {\n\treturn &CmdChatCreateChannel{Contextified: libkb.NewContextified(g)}\n}\n\nfunc newCmdChatCreateChannel(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {\n\treturn cli.Command{\n\t\tName:         \"create-channel\",\n\t\tUsage:        \"Create a conversation channel\",\n\t\tArgumentHelp: \"<team name> <channel name>\",\n\t\tAction: func(c *cli.Context) {\n\t\t\tcl.ChooseCommand(NewCmdChatCreateChannelRunner(g), \"create-channel\", c)\n\t\t},\n\t\tFlags: mustGetChatFlags(\"topic-type\"),\n\t}\n}\n\nfunc (c *CmdChatCreateChannel) Run() error {\n\tc.G().StartStandaloneChat()\n\tchatClient, err := GetChatLocalClient(c.G())\n\tif err != nil {\n\t\treturn err\n\t}\n\tresolver := &chatConversationResolver{G: c.G(), ChatClient: chatClient}\n\n\treq := chatConversationResolvingRequest{\n\t\tTlfName:     c.teamName,\n\t\tTopicName:   c.channelName,\n\t\tTopicType:   c.topicType,\n\t\tMembersType: chat1.ConversationMembersType_TEAM,\n\t\tVisibility:  keybase1.TLFVisibility_PRIVATE,\n\t\tctx: &chatConversationResolvingRequestContext{\n\t\t\tcanonicalizedTlfName: c.teamName,\n\t\t},\n\t}\n\n\t_, err = resolver.create(context.Background(), req)\n\treturn err\n}\n\nfunc (c *CmdChatCreateChannel) ParseArgv(ctx *cli.Context) error {\n\tif len(ctx.Args()) != 2 {\n\t\treturn errors.New(\"create channel takes two arguments.\")\n\t}\n\n\tc.teamName = ctx.Args().Get(0)\n\tc.channelName = ctx.Args().Get(1)\n\n\tvar err error\n\tc.topicType, err = parseConversationTopicType(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *CmdChatCreateChannel) GetUsage() libkb.Usage {\n\treturn libkb.Usage{\n\t\tConfig:    true,\n\t\tAPI:       true,\n\t\tKbKeyring: true,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Code generated by go-bindata.\n\/\/ sources:\n\/\/ config.json\n\/\/ DO NOT EDIT!\n\npackage config\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc bindataRead(data []byte, name string) ([]byte, error) {\n\tgz, err := gzip.NewReader(bytes.NewBuffer(data))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Read %q: %v\", name, err)\n\t}\n\n\tvar buf bytes.Buffer\n\t_, err = io.Copy(&buf, gz)\n\tclErr := gz.Close()\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Read %q: %v\", name, err)\n\t}\n\tif clErr != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\ntype asset struct {\n\tbytes []byte\n\tinfo  os.FileInfo\n}\n\ntype bindataFileInfo struct {\n\tname    string\n\tsize    int64\n\tmode    os.FileMode\n\tmodTime time.Time\n}\n\nfunc (fi bindataFileInfo) Name() string {\n\treturn fi.name\n}\nfunc (fi bindataFileInfo) Size() int64 {\n\treturn fi.size\n}\nfunc (fi bindataFileInfo) Mode() os.FileMode {\n\treturn fi.mode\n}\nfunc (fi bindataFileInfo) ModTime() time.Time {\n\treturn fi.modTime\n}\nfunc (fi bindataFileInfo) IsDir() bool {\n\treturn false\n}\nfunc (fi bindataFileInfo) Sys() interface{} {\n\treturn nil\n}\n\nvar _configJson = []byte(\"\\x1f\\x8b\\x08\\x00\\x00\\x09\\x6e\\x88\\x00\\xff\\xd4\\x94\\xc1\\x6a\\xc3\\x30\\x0c\\x86\\xef\\x79\\x8a\\xa0\\x73\\x9a\\xac\\xbb\\x0c\\xfa\\x2a\\x63\\x87\\x2c\\x16\\xad\\x49\\x22\\x19\\x5b\\x09\\x1d\\x23\\xef\\x3e\\xc5\\x5e\\x37\\xb7\\x30\\xe8\\x2e\\x23\\xa3\\x27\\xff\\xbf\\xa4\\x7e\\x7c\\x87\\xbc\\x17\\x65\\x09\\x9e\\x27\\xc1\\x00\\x87\\x72\\x7d\\xe9\\xdb\\xe0\\x5c\\xf7\\x6c\\x2c\\x1d\\xeb\\x8e\\x47\\xcd\\x61\\xff\\xf8\\x54\\x3f\\xe8\\x6f\\x0f\\x3a\\xb1\\x54\\xeb\\x12\\x92\\x71\\x6c\\x49\\xb2\\x3d\\x99\\x88\\x70\\x08\\xe8\\x67\\xf4\\x9a\\x3e\\xc7\\xb4\\xfc\\x6c\\xe3\\x04\\xd2\\x6c\\x3d\\xd3\\x88\\x24\\xd9\\x40\\xac\\x9c\\x67\\x33\\x75\\x62\\x99\\xa0\\xca\\xf3\\xb1\\xa5\\xf6\\x88\\x06\\xbe\\xb2\\x97\\xef\\x1a\\x26\\x3f\\xac\\x78\\x27\\x11\\x77\\x68\\x9a\\xf4\\xff\\x7a\\xe8\\xfc\\x96\\xf1\\x37\\xbd\\x15\\xbc\\xac\\x2f\\xd5\\xaf\\xa0\\xd4\\x04\\x0e\\xec\\x62\\x55\\xdd\\x14\\x17\\xb0\\xab\\x3c\\xb4\\x64\\x5e\\xf9\\x7c\\x0f\\xad\\x9e\\xb8\\x07\\xb8\\xc8\\xae\\x80\\x75\\x7f\\xee\\x35\\x28\\xaa\\xcb\\xe9\\x76\\x8d\\x52\\x6c\\x4c\\x67\\x48\\x3e\\x77\\x3f\\x83\\xde\\x68\\xec\\x4e\\xd8\\xf5\\xdb\\x70\\x99\\x50\\xfe\\x8b\\xd0\\x6b\\xda\\x64\\x75\\xfd\\x26\\x14\\x4b\\xf1\\x11\\x00\\x00\\xff\\xff\\xcb\\xeb\\x6f\\x40\\x4c\\x04\\x00\\x00\")\n\nfunc configJsonBytes() ([]byte, error) {\n\treturn bindataRead(\n\t\t_configJson,\n\t\t\"config.json\",\n\t)\n}\n\nfunc configJson() (*asset, error) {\n\tbytes, err := configJsonBytes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinfo := bindataFileInfo{name: \"config.json\", size: 1100, mode: os.FileMode(420), modTime: time.Unix(1446555960, 0)}\n\ta := &asset{bytes: bytes, info: info}\n\treturn a, nil\n}\n\n\/\/ Asset loads and returns the asset for the given name.\n\/\/ It returns an error if the asset could not be found or\n\/\/ could not be loaded.\nfunc Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"\/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}\n\n\/\/ MustAsset is like Asset but panics when Asset would return an error.\n\/\/ It simplifies safe initialization of global variables.\nfunc MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif err != nil {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}\n\n\/\/ AssetInfo loads and returns the asset info for the given name.\n\/\/ It returns an error if the asset could not be found or\n\/\/ could not be loaded.\nfunc AssetInfo(name string) (os.FileInfo, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"\/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}\n\n\/\/ AssetNames returns the names of the assets.\nfunc AssetNames() []string {\n\tnames := make([]string, 0, len(_bindata))\n\tfor name := range _bindata {\n\t\tnames = append(names, name)\n\t}\n\treturn names\n}\n\n\/\/ _bindata is a table, holding each asset generator, mapped to its name.\nvar _bindata = map[string]func() (*asset, error){\n\t\"config.json\": configJson,\n}\n\n\/\/ AssetDir returns the file names below a certain\n\/\/ directory embedded in the file by go-bindata.\n\/\/ For example if you run go-bindata on data\/... and data contains the\n\/\/ following hierarchy:\n\/\/     data\/\n\/\/       foo.txt\n\/\/       img\/\n\/\/         a.png\n\/\/         b.png\n\/\/ then AssetDir(\"data\") would return []string{\"foo.txt\", \"img\"}\n\/\/ AssetDir(\"data\/img\") would return []string{\"a.png\", \"b.png\"}\n\/\/ AssetDir(\"foo.txt\") and AssetDir(\"notexist\") would return an error\n\/\/ AssetDir(\"\") will return []string{\"data\"}.\nfunc AssetDir(name string) ([]string, error) {\n\tnode := _bintree\n\tif len(name) != 0 {\n\t\tcannonicalName := strings.Replace(name, \"\\\\\", \"\/\", -1)\n\t\tpathList := strings.Split(cannonicalName, \"\/\")\n\t\tfor _, p := range pathList {\n\t\t\tnode = node.Children[p]\n\t\t\tif node == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n\t\t\t}\n\t\t}\n\t}\n\tif node.Func != nil {\n\t\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n\t}\n\trv := make([]string, 0, len(node.Children))\n\tfor childName := range node.Children {\n\t\trv = append(rv, childName)\n\t}\n\treturn rv, nil\n}\n\ntype bintree struct {\n\tFunc     func() (*asset, error)\n\tChildren map[string]*bintree\n}\nvar _bintree = &bintree{nil, map[string]*bintree{\n\t\"config.json\": &bintree{configJson, map[string]*bintree{}},\n}}\n\n\/\/ RestoreAsset restores an asset under the given directory\nfunc RestoreAsset(dir, name string) error {\n\tdata, err := Asset(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfo, err := AssetInfo(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ RestoreAssets restores an asset under the given directory recursively\nfunc RestoreAssets(dir, name string) error {\n\tchildren, err := AssetDir(name)\n\t\/\/ File\n\tif err != nil {\n\t\treturn RestoreAsset(dir, name)\n\t}\n\t\/\/ Dir\n\tfor _, child := range children {\n\t\terr = RestoreAssets(dir, filepath.Join(name, child))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc _filePath(dir, name string) string {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"\/\", -1)\n\treturn filepath.Join(append([]string{dir}, strings.Split(cannonicalName, \"\/\")...)...)\n}\n\n<commit_msg>go: run go generate<commit_after>\/\/ Code generated by go-bindata.\n\/\/ sources:\n\/\/ config.json\n\/\/ DO NOT EDIT!\n\npackage config\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc bindataRead(data []byte, name string) ([]byte, error) {\n\tgz, err := gzip.NewReader(bytes.NewBuffer(data))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Read %q: %v\", name, err)\n\t}\n\n\tvar buf bytes.Buffer\n\t_, err = io.Copy(&buf, gz)\n\tclErr := gz.Close()\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Read %q: %v\", name, err)\n\t}\n\tif clErr != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\ntype asset struct {\n\tbytes []byte\n\tinfo  os.FileInfo\n}\n\ntype bindataFileInfo struct {\n\tname    string\n\tsize    int64\n\tmode    os.FileMode\n\tmodTime time.Time\n}\n\nfunc (fi bindataFileInfo) Name() string {\n\treturn fi.name\n}\nfunc (fi bindataFileInfo) Size() int64 {\n\treturn fi.size\n}\nfunc (fi bindataFileInfo) Mode() os.FileMode {\n\treturn fi.mode\n}\nfunc (fi bindataFileInfo) ModTime() time.Time {\n\treturn fi.modTime\n}\nfunc (fi bindataFileInfo) IsDir() bool {\n\treturn false\n}\nfunc (fi bindataFileInfo) Sys() interface{} {\n\treturn nil\n}\n\nvar _configJson = []byte(\"\\x1f\\x8b\\x08\\x00\\x00\\x09\\x6e\\x88\\x00\\xff\\xd4\\x94\\x41\\x6b\\xc3\\x30\\x0c\\x85\\xef\\xf9\\x15\\x41\\xe7\\x34\\x59\\x77\\x19\\xf4\\xaf\\x8c\\x1d\\xb2\\x58\\xb4\\x26\\x89\\x64\\x6c\\x39\\x0c\\x46\\xfe\\xfb\\x64\\xb7\\xdd\\xdc\\x42\\x61\\xbb\\x8c\\x16\\x9f\\xf4\\x9e\\x9e\\xf9\\xfc\\x0e\\xfe\\xac\\xea\\x1a\\x3c\\x47\\xc1\\x00\\xbb\\x3a\\x4d\\x3a\\x1b\\x5c\\xda\\x91\\x8d\\xa5\\x7d\\x3b\\xf0\\xac\\x3a\\x6c\\x9f\\x5f\\xda\\x27\\x3d\\x5b\\xd0\\x8d\\xb5\\x49\\x21\\x24\\xe3\\xd8\\x92\\x14\\x39\\x89\\x44\\x38\\x05\\xf4\\x0b\\x7a\\x55\\x5f\\xb3\\x5a\\x9f\\xdc\\xbc\\x81\\xb4\\x58\\xcf\\x34\\x23\\x49\\xb1\\x90\\x2d\\xe7\\xd9\\xc4\\x41\\x2c\\x13\\x34\\xa5\\x3e\\xf7\\xd4\\xef\\xd1\\xc0\\xb7\\xf6\\xf6\\x63\\x43\\xf4\\x53\\xc2\\x3b\\x88\\xb8\\x5d\\xd7\\x49\\x41\\xdd\\x8d\\x56\\xf0\\x1c\\x5a\\x9b\\x3f\\xa1\\xe8\\xfb\\x71\\x62\\x97\\xad\\xe6\\xca\\x38\\xe3\\x5c\\xe8\\xa1\\x27\\xf3\\xce\\x1f\\xbf\\x61\\xd4\\x2b\\x36\\xb7\\x39\\xab\\x22\\x0c\\xd6\\xfd\\x7b\\x89\\x41\\x09\\x5d\\x49\\xb7\\xe9\\x94\\xe2\\xce\\x5a\\x0c\\xa7\\x1a\\x6f\\x83\\x5e\\xd5\\x38\\x1c\\x70\\x18\\xef\\xa3\\xcb\\x23\\xca\\xa3\\x14\\x7a\\x49\\x7b\\x6c\\x35\\x7d\\x00\\xd5\\x5a\\x7d\\x05\\x00\\x00\\xff\\xff\\x8a\\xd5\\x09\\x92\\x39\\x04\\x00\\x00\")\n\nfunc configJsonBytes() ([]byte, error) {\n\treturn bindataRead(\n\t\t_configJson,\n\t\t\"config.json\",\n\t)\n}\n\nfunc configJson() (*asset, error) {\n\tbytes, err := configJsonBytes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinfo := bindataFileInfo{name: \"config.json\", size: 1081, mode: os.FileMode(420), modTime: time.Unix(1446555960, 0)}\n\ta := &asset{bytes: bytes, info: info}\n\treturn a, nil\n}\n\n\/\/ Asset loads and returns the asset for the given name.\n\/\/ It returns an error if the asset could not be found or\n\/\/ could not be loaded.\nfunc Asset(name string) ([]byte, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"\/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Asset %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.bytes, nil\n\t}\n\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n}\n\n\/\/ MustAsset is like Asset but panics when Asset would return an error.\n\/\/ It simplifies safe initialization of global variables.\nfunc MustAsset(name string) []byte {\n\ta, err := Asset(name)\n\tif err != nil {\n\t\tpanic(\"asset: Asset(\" + name + \"): \" + err.Error())\n\t}\n\n\treturn a\n}\n\n\/\/ AssetInfo loads and returns the asset info for the given name.\n\/\/ It returns an error if the asset could not be found or\n\/\/ could not be loaded.\nfunc AssetInfo(name string) (os.FileInfo, error) {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"\/\", -1)\n\tif f, ok := _bindata[cannonicalName]; ok {\n\t\ta, err := f()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"AssetInfo %s can't read by error: %v\", name, err)\n\t\t}\n\t\treturn a.info, nil\n\t}\n\treturn nil, fmt.Errorf(\"AssetInfo %s not found\", name)\n}\n\n\/\/ AssetNames returns the names of the assets.\nfunc AssetNames() []string {\n\tnames := make([]string, 0, len(_bindata))\n\tfor name := range _bindata {\n\t\tnames = append(names, name)\n\t}\n\treturn names\n}\n\n\/\/ _bindata is a table, holding each asset generator, mapped to its name.\nvar _bindata = map[string]func() (*asset, error){\n\t\"config.json\": configJson,\n}\n\n\/\/ AssetDir returns the file names below a certain\n\/\/ directory embedded in the file by go-bindata.\n\/\/ For example if you run go-bindata on data\/... and data contains the\n\/\/ following hierarchy:\n\/\/     data\/\n\/\/       foo.txt\n\/\/       img\/\n\/\/         a.png\n\/\/         b.png\n\/\/ then AssetDir(\"data\") would return []string{\"foo.txt\", \"img\"}\n\/\/ AssetDir(\"data\/img\") would return []string{\"a.png\", \"b.png\"}\n\/\/ AssetDir(\"foo.txt\") and AssetDir(\"notexist\") would return an error\n\/\/ AssetDir(\"\") will return []string{\"data\"}.\nfunc AssetDir(name string) ([]string, error) {\n\tnode := _bintree\n\tif len(name) != 0 {\n\t\tcannonicalName := strings.Replace(name, \"\\\\\", \"\/\", -1)\n\t\tpathList := strings.Split(cannonicalName, \"\/\")\n\t\tfor _, p := range pathList {\n\t\t\tnode = node.Children[p]\n\t\t\tif node == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n\t\t\t}\n\t\t}\n\t}\n\tif node.Func != nil {\n\t\treturn nil, fmt.Errorf(\"Asset %s not found\", name)\n\t}\n\trv := make([]string, 0, len(node.Children))\n\tfor childName := range node.Children {\n\t\trv = append(rv, childName)\n\t}\n\treturn rv, nil\n}\n\ntype bintree struct {\n\tFunc     func() (*asset, error)\n\tChildren map[string]*bintree\n}\nvar _bintree = &bintree{nil, map[string]*bintree{\n\t\"config.json\": &bintree{configJson, map[string]*bintree{}},\n}}\n\n\/\/ RestoreAsset restores an asset under the given directory\nfunc RestoreAsset(dir, name string) error {\n\tdata, err := Asset(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinfo, err := AssetInfo(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(_filePath(dir, name), data, info.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime())\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ RestoreAssets restores an asset under the given directory recursively\nfunc RestoreAssets(dir, name string) error {\n\tchildren, err := AssetDir(name)\n\t\/\/ File\n\tif err != nil {\n\t\treturn RestoreAsset(dir, name)\n\t}\n\t\/\/ Dir\n\tfor _, child := range children {\n\t\terr = RestoreAssets(dir, filepath.Join(name, child))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc _filePath(dir, name string) string {\n\tcannonicalName := strings.Replace(name, \"\\\\\", \"\/\", -1)\n\treturn filepath.Join(append([]string{dir}, strings.Split(cannonicalName, \"\/\")...)...)\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nconst (\n\tSafe  = 0\n\tTroll = 1 << iota\n)\n\ntype MetaBits int16\n\n\/\/ IsSafe checks for data against if it is showable to the user\nfunc (m MetaBits) IsSafe() bool {\n\treturn (m == 0)\n}\n\nfunc (m *MetaBits) MarkTroll() {\n\t\/\/ set first bit as 1\n\t*m = *m | Troll\n}\n\nfunc (m MetaBits) IsTroll() bool {\n\t\/\/ get first bit\n\treturn (m & Troll) == Troll\n}\n<commit_msg>Social: cleanup metabits<commit_after>package models\n\nconst (\n\tTroll MetaBits = 1 << iota\n\t\/\/ all other bits will up be here\n\n\t\/\/ safe should be the last one assigned as 0\n\tSafe MetaBits = 0\n)\n\ntype MetaBits int16\n\nfunc (m *MetaBits) Mark(data MetaBits) {\n\t\/\/ bitwise OR\n\t*m = *m | data\n}\n\nfunc (m *MetaBits) UnMark(data MetaBits) {\n\t\/\/ bit clear (AND NOT)\n\t*m = *m &^ data\n}\n\nfunc (m MetaBits) Is(data MetaBits) bool {\n\treturn (m & data) == data\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ EVH is designed to be a single-use file transfer system.  Its purpose is to replace\n\/\/ aging methods of sharing files such as FTP.  With the advent of services like\n\/\/ DropBox, Box, Google Drive and the like, this type of service is becoming more\n\/\/ commonplace EVH has some differentiating features that make it an especially\n\/\/ good tool for corporations and\/or home use.\n\/\/\n\/\/ EVH runs in two modes: server and client.  Server hosts a web server interface for\n\/\/ uploading and downloading files.  The Client is for uploading only and runs\n\/\/ in a terminal.  This app is designed to run on all platforms that Go supports.\npackage main\n\nimport (\n\t\"flag\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n)\n\n\/\/ Flags\nvar ConfigFileFlag string\nvar DstEmailFlag string\nvar ExpirationFlag string\nvar FileDescrFlag string\nvar FilesFieldFlag string\nvar ProgressFlag bool\nvar ServerFlag bool\nvar SrcEmailFlag string\nvar UrlFlag string\n\n\/\/ Global Variables\nvar UploadUrlPath = \"\/upload\/\"\nvar DownloadUrlPath = \"\/download\/\"\nvar Files []string\nvar HttpProto = \"http\"\nvar SiteDown bool\nvar Templates *template.Template\n\n\/\/ Constants\nconst VERSION = \"2.0.3\"\nconst TimeLayout = \"Jan 2, 2006 at 3:04pm (MST)\"\n\nfunc init() {\n\tflag.StringVar(&ConfigFileFlag, \"c\", \"\", \"Location of the Configuration file\")\n\tflag.BoolVar(&ServerFlag, \"server\", false, \"Listen for incoming file uploads\")\n\n\t\/\/ Client flags\n\tflag.StringVar(&UrlFlag, \"url\", \"\", \"Remote server URL to send files to (client only)\")\n\tflag.StringVar(&FilesFieldFlag, \"field\", \"\", \"Field name of the form (client only)\")\n\tflag.StringVar(&SrcEmailFlag, \"from\", \"\", \"Email address of uploader (client only)\")\n\tflag.StringVar(&DstEmailFlag, \"to\", \"\", \"Comma separated set of email address(es) of file recipient(s) (client only)\")\n\tflag.StringVar(&FileDescrFlag, \"description\", \"\", \"File desription (use quotes) (client only)\")\n\tflag.BoolVar(&ProgressFlag, \"progress\", true, \"Show progress bar during upload (client only)\")\n\tflag.StringVar(&ExpirationFlag, \"expires\", \"\", \"Example 1:d for 1 day (client only)\")\n}\n\nfunc homeHandler(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Redirect to SSL if enabled\n\tif r.TLS == nil && Config.Server.Ssl {\n\t\tlog.Println(r.RequestURI)\n\t\tredirectToSsl(w, r)\n\t\treturn\n\t}\n\n\tvar page = NewPage()\n\tDisplayPage(w, r, \"home\", page)\n}\n\nfunc redirectToSsl(w http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(w, r, \"https:\/\/\"+Config.Server.Address+\":\"+Config.Server.SslPort+r.RequestURI, http.StatusTemporaryRedirect)\n\treturn\n}\n\nfunc main() {\n\tflag.Parse()\n\n\t\/\/ Load in our Config\n\tConfig = NewConfig(ConfigFileFlag)\n\tConfig.ImportFlags()\n\n\tif ServerFlag {\n\t\t\/\/ Final sanity check\n\t\tif Config.Server.Assets == \"\" {\n\t\t\tlog.Fatal(\"ERROR: Cannot continue without specifying assets path\")\n\t\t}\n\t\tif Config.Server.Templates == \"\" {\n\t\t\tlog.Fatal(\"ERROR: Cannot continue without specifying templates path\")\n\t\t}\n\t\tif Config.Server.ListenAddr == \"\" {\n\t\t\tlog.Fatal(\"ERROR: Cannot continue without specifying listenaddr value\")\n\t\t}\n\t\tif Config.Server.Mailserver == \"\" {\n\t\t\tlog.Println(\"WARNING: cannot send emails, mailserver not set\")\n\t\t}\n\n\t\t\/\/ Set so all generated URLs use https if enabled\n\t\tif Config.Server.Ssl {\n\t\t\tHttpProto = \"https\"\n\t\t}\n\n\t\t\/\/ Setup our assets dir (if it don't already exist)\n\t\terr := os.MkdirAll(Config.Server.Assets, 0700)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Cannot setup assetdir as needed: \" + err.Error())\n\t\t}\n\n\t\t\/\/ Parse our html templates\n\t\tgo RefreshTemplates()\n\t\tgo ScrubDownloads()\n\n\t\t\/\/ Register our handler functions\n\t\thttp.HandleFunc(UploadUrlPath, uploadHandler)\n\t\thttp.HandleFunc(DownloadUrlPath, assetHandler)\n\t\thttp.HandleFunc(\"\/\", homeHandler)\n\n\t\t\/\/ Listen\n\t\tlog.Println(\"Listening...\")\n\n\t\t\/\/ Spawn HTTPS listener in another thread\n\t\tgo func() {\n\t\t\tif Config.Server.Ssl == false || Config.Server.SslPort == \"\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar addrSsl = Config.Server.ListenAddr + \":\" + Config.Server.SslPort\n\t\t\tlistenErrSsl := http.ListenAndServeTLS(addrSsl, Config.Server.CertFile, Config.Server.KeyFile, nil)\n\t\t\tif listenErrSsl != nil {\n\t\t\t\tlog.Fatal(listenErrSsl.Error())\n\t\t\t}\n\t\t}()\n\n\t\t\/\/ Start non-SSL listener\n\t\tvar addrNonSsl = Config.Server.ListenAddr + \":\" + Config.Server.NonSslPort\n\t\tlistenErr := http.ListenAndServe(addrNonSsl, nil)\n\t\tif listenErr != nil {\n\t\t\tlog.Fatal(listenErr.Error())\n\t\t}\n\t} else {\n\t\t\/\/ Final sanity check\n\t\tif Config.Client.DestEmail == \"\" {\n\t\t\tlog.Println(\"WARNING: no -destemail value set, cannot send reciever an email\")\n\t\t}\n\t\tif Config.Client.Email == \"\" {\n\t\t\tlog.Println(\"WARNING: no -email value set, cannot send email to uploader\")\n\t\t}\n\t\tif Config.Client.Field == \"\" {\n\t\t\tlog.Println(\"WARNING: no -field value set, using \\\"file\\\" instead\")\n\t\t\tConfig.Client.Field = \"file\"\n\t\t}\n\t\tif Config.Client.Url == \"\" {\n\t\t\tlog.Fatal(\"ERROR: Cannot continue without specifying -url value\")\n\t\t}\n\n\t\t\/\/ All filenames are unflagged arguments, loop through them and uplod the file(s)\n\t\tfor _, fname := range flag.Args() {\n\t\t\tfi, err := os.Stat(fname)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"WARNING: Cannot read file, skipping \", fname, \": \", err.Error())\n\t\t\t} else {\n\t\t\t\tif fi.Mode().IsRegular() {\n\t\t\t\t\tFiles = append(Files, fname)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tUpload(Files)\n\t}\n}\n<commit_msg>Version bump to 2.0.4<commit_after>\/\/ EVH is designed to be a single-use file transfer system.  Its purpose is to replace\n\/\/ aging methods of sharing files such as FTP.  With the advent of services like\n\/\/ DropBox, Box, Google Drive and the like, this type of service is becoming more\n\/\/ commonplace EVH has some differentiating features that make it an especially\n\/\/ good tool for corporations and\/or home use.\n\/\/\n\/\/ EVH runs in two modes: server and client.  Server hosts a web server interface for\n\/\/ uploading and downloading files.  The Client is for uploading only and runs\n\/\/ in a terminal.  This app is designed to run on all platforms that Go supports.\npackage main\n\nimport (\n\t\"flag\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n)\n\n\/\/ Flags\nvar ConfigFileFlag string\nvar DstEmailFlag string\nvar ExpirationFlag string\nvar FileDescrFlag string\nvar FilesFieldFlag string\nvar ProgressFlag bool\nvar ServerFlag bool\nvar SrcEmailFlag string\nvar UrlFlag string\n\n\/\/ Global Variables\nvar UploadUrlPath = \"\/upload\/\"\nvar DownloadUrlPath = \"\/download\/\"\nvar Files []string\nvar HttpProto = \"http\"\nvar SiteDown bool\nvar Templates *template.Template\n\n\/\/ Constants\nconst VERSION = \"2.0.4\"\nconst TimeLayout = \"Jan 2, 2006 at 3:04pm (MST)\"\n\nfunc init() {\n\tflag.StringVar(&ConfigFileFlag, \"c\", \"\", \"Location of the Configuration file\")\n\tflag.BoolVar(&ServerFlag, \"server\", false, \"Listen for incoming file uploads\")\n\n\t\/\/ Client flags\n\tflag.StringVar(&UrlFlag, \"url\", \"\", \"Remote server URL to send files to (client only)\")\n\tflag.StringVar(&FilesFieldFlag, \"field\", \"\", \"Field name of the form (client only)\")\n\tflag.StringVar(&SrcEmailFlag, \"from\", \"\", \"Email address of uploader (client only)\")\n\tflag.StringVar(&DstEmailFlag, \"to\", \"\", \"Comma separated set of email address(es) of file recipient(s) (client only)\")\n\tflag.StringVar(&FileDescrFlag, \"description\", \"\", \"File desription (use quotes) (client only)\")\n\tflag.BoolVar(&ProgressFlag, \"progress\", true, \"Show progress bar during upload (client only)\")\n\tflag.StringVar(&ExpirationFlag, \"expires\", \"\", \"Example 1:d for 1 day (client only)\")\n}\n\nfunc homeHandler(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Redirect to SSL if enabled\n\tif r.TLS == nil && Config.Server.Ssl {\n\t\tlog.Println(r.RequestURI)\n\t\tredirectToSsl(w, r)\n\t\treturn\n\t}\n\n\tvar page = NewPage()\n\tDisplayPage(w, r, \"home\", page)\n}\n\nfunc redirectToSsl(w http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(w, r, \"https:\/\/\"+Config.Server.Address+\":\"+Config.Server.SslPort+r.RequestURI, http.StatusTemporaryRedirect)\n\treturn\n}\n\nfunc main() {\n\tflag.Parse()\n\n\t\/\/ Load in our Config\n\tConfig = NewConfig(ConfigFileFlag)\n\tConfig.ImportFlags()\n\n\tif ServerFlag {\n\t\t\/\/ Final sanity check\n\t\tif Config.Server.Assets == \"\" {\n\t\t\tlog.Fatal(\"ERROR: Cannot continue without specifying assets path\")\n\t\t}\n\t\tif Config.Server.Templates == \"\" {\n\t\t\tlog.Fatal(\"ERROR: Cannot continue without specifying templates path\")\n\t\t}\n\t\tif Config.Server.ListenAddr == \"\" {\n\t\t\tlog.Fatal(\"ERROR: Cannot continue without specifying listenaddr value\")\n\t\t}\n\t\tif Config.Server.Mailserver == \"\" {\n\t\t\tlog.Println(\"WARNING: cannot send emails, mailserver not set\")\n\t\t}\n\n\t\t\/\/ Set so all generated URLs use https if enabled\n\t\tif Config.Server.Ssl {\n\t\t\tHttpProto = \"https\"\n\t\t}\n\n\t\t\/\/ Setup our assets dir (if it don't already exist)\n\t\terr := os.MkdirAll(Config.Server.Assets, 0700)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Cannot setup assetdir as needed: \" + err.Error())\n\t\t}\n\n\t\t\/\/ Parse our html templates\n\t\tgo RefreshTemplates()\n\t\tgo ScrubDownloads()\n\n\t\t\/\/ Register our handler functions\n\t\thttp.HandleFunc(UploadUrlPath, uploadHandler)\n\t\thttp.HandleFunc(DownloadUrlPath, assetHandler)\n\t\thttp.HandleFunc(\"\/\", homeHandler)\n\n\t\t\/\/ Listen\n\t\tlog.Println(\"Listening...\")\n\n\t\t\/\/ Spawn HTTPS listener in another thread\n\t\tgo func() {\n\t\t\tif Config.Server.Ssl == false || Config.Server.SslPort == \"\" {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar addrSsl = Config.Server.ListenAddr + \":\" + Config.Server.SslPort\n\t\t\tlistenErrSsl := http.ListenAndServeTLS(addrSsl, Config.Server.CertFile, Config.Server.KeyFile, nil)\n\t\t\tif listenErrSsl != nil {\n\t\t\t\tlog.Fatal(listenErrSsl.Error())\n\t\t\t}\n\t\t}()\n\n\t\t\/\/ Start non-SSL listener\n\t\tvar addrNonSsl = Config.Server.ListenAddr + \":\" + Config.Server.NonSslPort\n\t\tlistenErr := http.ListenAndServe(addrNonSsl, nil)\n\t\tif listenErr != nil {\n\t\t\tlog.Fatal(listenErr.Error())\n\t\t}\n\t} else {\n\t\t\/\/ Final sanity check\n\t\tif Config.Client.DestEmail == \"\" {\n\t\t\tlog.Println(\"WARNING: no -destemail value set, cannot send reciever an email\")\n\t\t}\n\t\tif Config.Client.Email == \"\" {\n\t\t\tlog.Println(\"WARNING: no -email value set, cannot send email to uploader\")\n\t\t}\n\t\tif Config.Client.Field == \"\" {\n\t\t\tlog.Println(\"WARNING: no -field value set, using \\\"file\\\" instead\")\n\t\t\tConfig.Client.Field = \"file\"\n\t\t}\n\t\tif Config.Client.Url == \"\" {\n\t\t\tlog.Fatal(\"ERROR: Cannot continue without specifying -url value\")\n\t\t}\n\n\t\t\/\/ All filenames are unflagged arguments, loop through them and uplod the file(s)\n\t\tfor _, fname := range flag.Args() {\n\t\t\tfi, err := os.Stat(fname)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"WARNING: Cannot read file, skipping \", fname, \": \", err.Error())\n\t\t\t} else {\n\t\t\t\tif fi.Mode().IsRegular() {\n\t\t\t\t\tFiles = append(Files, fname)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tUpload(Files)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2010 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package pprof serves via its HTTP server runtime profiling data\n\/\/ in the format expected by the pprof visualization tool.\n\/\/ For more information about pprof, see\n\/\/ http:\/\/code.google.com\/p\/google-perftools\/.\n\/\/\n\/\/ The package is typically only imported for the side effect of\n\/\/ registering its HTTP handlers.\n\/\/ The handled paths all begin with \/debug\/pprof\/.\n\/\/\n\/\/ To use pprof, link this package into your program:\n\/\/\timport _ \"net\/http\/pprof\"\n\/\/\n\/\/ If your application is not already running an http server, you\n\/\/ need to start one.  Add \"net\/http\" and \"log\" to your imports and\n\/\/ the following code to your main function:\n\/\/\n\/\/ \tgo func() {\n\/\/ \t\tlog.Println(http.ListenAndServe(\"localhost:6060\", nil))\n\/\/ \t}()\n\/\/\n\/\/ Then use the pprof tool to look at the heap profile:\n\/\/\n\/\/\tgo tool pprof http:\/\/localhost:6060\/debug\/pprof\/heap\n\/\/\n\/\/ Or to look at a 30-second CPU profile:\n\/\/\n\/\/\tgo tool pprof http:\/\/localhost:6060\/debug\/pprof\/profile\n\/\/\n\/\/ Or to look at the goroutine blocking profile:\n\/\/\n\/\/\tgo tool pprof http:\/\/localhost:6060\/debug\/pprof\/block\n\/\/\n\/\/ To view all available profiles, open http:\/\/localhost:6060\/debug\/pprof\/\n\/\/ in your browser.\n\/\/\n\/\/ For a study of the facility in action, visit\n\/\/\n\/\/\thttp:\/\/blog.golang.org\/2011\/06\/profiling-go-programs.html\n\/\/\npackage pprof\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime\/pprof\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc init() {\n\thttp.Handle(\"\/debug\/pprof\/\", http.HandlerFunc(Index))\n\thttp.Handle(\"\/debug\/pprof\/cmdline\", http.HandlerFunc(Cmdline))\n\thttp.Handle(\"\/debug\/pprof\/profile\", http.HandlerFunc(Profile))\n\thttp.Handle(\"\/debug\/pprof\/symbol\", http.HandlerFunc(Symbol))\n}\n\n\/\/ Cmdline responds with the running program's\n\/\/ command line, with arguments separated by NUL bytes.\n\/\/ The package initialization registers it as \/debug\/pprof\/cmdline.\nfunc Cmdline(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=utf-8\")\n\tfmt.Fprintf(w, strings.Join(os.Args, \"\\x00\"))\n}\n\n\/\/ Profile responds with the pprof-formatted cpu profile.\n\/\/ The package initialization registers it as \/debug\/pprof\/profile.\nfunc Profile(w http.ResponseWriter, r *http.Request) {\n\tsec, _ := strconv.ParseInt(r.FormValue(\"seconds\"), 10, 64)\n\tif sec == 0 {\n\t\tsec = 30\n\t}\n\n\t\/\/ Set Content Type assuming StartCPUProfile will work,\n\t\/\/ because if it does it starts writing.\n\tw.Header().Set(\"Content-Type\", \"application\/octet-stream\")\n\tif err := pprof.StartCPUProfile(w); err != nil {\n\t\t\/\/ StartCPUProfile failed, so no writes yet.\n\t\t\/\/ Can change header back to text content\n\t\t\/\/ and send error code.\n\t\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=utf-8\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"Could not enable CPU profiling: %s\\n\", err)\n\t\treturn\n\t}\n\ttime.Sleep(time.Duration(sec) * time.Second)\n\tpprof.StopCPUProfile()\n}\n\n\/\/ Symbol looks up the program counters listed in the request,\n\/\/ responding with a table mapping program counters to function names.\n\/\/ The package initialization registers it as \/debug\/pprof\/symbol.\nfunc Symbol(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=utf-8\")\n\n\t\/\/ We have to read the whole POST body before\n\t\/\/ writing any output.  Buffer the output here.\n\tvar buf bytes.Buffer\n\n\t\/\/ We don't know how many symbols we have, but we\n\t\/\/ do have symbol information.  Pprof only cares whether\n\t\/\/ this number is 0 (no symbols available) or > 0.\n\tfmt.Fprintf(&buf, \"num_symbols: 1\\n\")\n\n\tvar b *bufio.Reader\n\tif r.Method == \"POST\" {\n\t\tb = bufio.NewReader(r.Body)\n\t} else {\n\t\tb = bufio.NewReader(strings.NewReader(r.URL.RawQuery))\n\t}\n\n\tfor {\n\t\tword, err := b.ReadSlice('+')\n\t\tif err == nil {\n\t\t\tword = word[0 : len(word)-1] \/\/ trim +\n\t\t}\n\t\tpc, _ := strconv.ParseUint(string(word), 0, 64)\n\t\tif pc != 0 {\n\t\t\tf := runtime.FuncForPC(uintptr(pc))\n\t\t\tif f != nil {\n\t\t\t\tfmt.Fprintf(&buf, \"%#x %s\\n\", pc, f.Name())\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Wait until here to check for err; the last\n\t\t\/\/ symbol will have an err because it doesn't end in +.\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tfmt.Fprintf(&buf, \"reading request: %v\\n\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tw.Write(buf.Bytes())\n}\n\n\/\/ Handler returns an HTTP handler that serves the named profile.\nfunc Handler(name string) http.Handler {\n\treturn handler(name)\n}\n\ntype handler string\n\nfunc (name handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=utf-8\")\n\tdebug, _ := strconv.Atoi(r.FormValue(\"debug\"))\n\tp := pprof.Lookup(string(name))\n\tif p == nil {\n\t\tw.WriteHeader(404)\n\t\tfmt.Fprintf(w, \"Unknown profile: %s\\n\", name)\n\t\treturn\n\t}\n\tp.WriteTo(w, debug)\n\treturn\n}\n\n\/\/ Index responds with the pprof-formatted profile named by the request.\n\/\/ For example, \"\/debug\/pprof\/heap\" serves the \"heap\" profile.\n\/\/ Index responds to a request for \"\/debug\/pprof\/\" with an HTML page\n\/\/ listing the available profiles.\nfunc Index(w http.ResponseWriter, r *http.Request) {\n\tif strings.HasPrefix(r.URL.Path, \"\/debug\/pprof\/\") {\n\t\tname := strings.TrimPrefix(r.URL.Path, \"\/debug\/pprof\/\")\n\t\tif name != \"\" {\n\t\t\thandler(name).ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\n\tprofiles := pprof.Profiles()\n\tif err := indexTmpl.Execute(w, profiles); err != nil {\n\t\tlog.Print(err)\n\t}\n}\n\nvar indexTmpl = template.Must(template.New(\"index\").Parse(`<html>\n<head>\n<title>\/debug\/pprof\/<\/title>\n<\/head>\n\/debug\/pprof\/<br>\n<br>\n<body>\nprofiles:<br>\n<table>\n{{range .}}\n<tr><td align=right>{{.Count}}<td><a href=\"\/debug\/pprof\/{{.Name}}?debug=1\">{{.Name}}<\/a>\n{{end}}\n<\/table>\n<br>\n<a href=\"\/debug\/pprof\/goroutine?debug=2\">full goroutine stack dump<\/a><br>\n<\/body>\n<\/html>\n`))\n<commit_msg>net\/http\/pprof: run GC for \/debug\/pprof\/heap?gc=1<commit_after>\/\/ Copyright 2010 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package pprof serves via its HTTP server runtime profiling data\n\/\/ in the format expected by the pprof visualization tool.\n\/\/ For more information about pprof, see\n\/\/ http:\/\/code.google.com\/p\/google-perftools\/.\n\/\/\n\/\/ The package is typically only imported for the side effect of\n\/\/ registering its HTTP handlers.\n\/\/ The handled paths all begin with \/debug\/pprof\/.\n\/\/\n\/\/ To use pprof, link this package into your program:\n\/\/\timport _ \"net\/http\/pprof\"\n\/\/\n\/\/ If your application is not already running an http server, you\n\/\/ need to start one.  Add \"net\/http\" and \"log\" to your imports and\n\/\/ the following code to your main function:\n\/\/\n\/\/ \tgo func() {\n\/\/ \t\tlog.Println(http.ListenAndServe(\"localhost:6060\", nil))\n\/\/ \t}()\n\/\/\n\/\/ Then use the pprof tool to look at the heap profile:\n\/\/\n\/\/\tgo tool pprof http:\/\/localhost:6060\/debug\/pprof\/heap\n\/\/\n\/\/ Or to look at a 30-second CPU profile:\n\/\/\n\/\/\tgo tool pprof http:\/\/localhost:6060\/debug\/pprof\/profile\n\/\/\n\/\/ Or to look at the goroutine blocking profile:\n\/\/\n\/\/\tgo tool pprof http:\/\/localhost:6060\/debug\/pprof\/block\n\/\/\n\/\/ To view all available profiles, open http:\/\/localhost:6060\/debug\/pprof\/\n\/\/ in your browser.\n\/\/\n\/\/ For a study of the facility in action, visit\n\/\/\n\/\/\thttp:\/\/blog.golang.org\/2011\/06\/profiling-go-programs.html\n\/\/\npackage pprof\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"runtime\/pprof\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc init() {\n\thttp.Handle(\"\/debug\/pprof\/\", http.HandlerFunc(Index))\n\thttp.Handle(\"\/debug\/pprof\/cmdline\", http.HandlerFunc(Cmdline))\n\thttp.Handle(\"\/debug\/pprof\/profile\", http.HandlerFunc(Profile))\n\thttp.Handle(\"\/debug\/pprof\/symbol\", http.HandlerFunc(Symbol))\n}\n\n\/\/ Cmdline responds with the running program's\n\/\/ command line, with arguments separated by NUL bytes.\n\/\/ The package initialization registers it as \/debug\/pprof\/cmdline.\nfunc Cmdline(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=utf-8\")\n\tfmt.Fprintf(w, strings.Join(os.Args, \"\\x00\"))\n}\n\n\/\/ Profile responds with the pprof-formatted cpu profile.\n\/\/ The package initialization registers it as \/debug\/pprof\/profile.\nfunc Profile(w http.ResponseWriter, r *http.Request) {\n\tsec, _ := strconv.ParseInt(r.FormValue(\"seconds\"), 10, 64)\n\tif sec == 0 {\n\t\tsec = 30\n\t}\n\n\t\/\/ Set Content Type assuming StartCPUProfile will work,\n\t\/\/ because if it does it starts writing.\n\tw.Header().Set(\"Content-Type\", \"application\/octet-stream\")\n\tif err := pprof.StartCPUProfile(w); err != nil {\n\t\t\/\/ StartCPUProfile failed, so no writes yet.\n\t\t\/\/ Can change header back to text content\n\t\t\/\/ and send error code.\n\t\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=utf-8\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprintf(w, \"Could not enable CPU profiling: %s\\n\", err)\n\t\treturn\n\t}\n\ttime.Sleep(time.Duration(sec) * time.Second)\n\tpprof.StopCPUProfile()\n}\n\n\/\/ Symbol looks up the program counters listed in the request,\n\/\/ responding with a table mapping program counters to function names.\n\/\/ The package initialization registers it as \/debug\/pprof\/symbol.\nfunc Symbol(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=utf-8\")\n\n\t\/\/ We have to read the whole POST body before\n\t\/\/ writing any output.  Buffer the output here.\n\tvar buf bytes.Buffer\n\n\t\/\/ We don't know how many symbols we have, but we\n\t\/\/ do have symbol information.  Pprof only cares whether\n\t\/\/ this number is 0 (no symbols available) or > 0.\n\tfmt.Fprintf(&buf, \"num_symbols: 1\\n\")\n\n\tvar b *bufio.Reader\n\tif r.Method == \"POST\" {\n\t\tb = bufio.NewReader(r.Body)\n\t} else {\n\t\tb = bufio.NewReader(strings.NewReader(r.URL.RawQuery))\n\t}\n\n\tfor {\n\t\tword, err := b.ReadSlice('+')\n\t\tif err == nil {\n\t\t\tword = word[0 : len(word)-1] \/\/ trim +\n\t\t}\n\t\tpc, _ := strconv.ParseUint(string(word), 0, 64)\n\t\tif pc != 0 {\n\t\t\tf := runtime.FuncForPC(uintptr(pc))\n\t\t\tif f != nil {\n\t\t\t\tfmt.Fprintf(&buf, \"%#x %s\\n\", pc, f.Name())\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Wait until here to check for err; the last\n\t\t\/\/ symbol will have an err because it doesn't end in +.\n\t\tif err != nil {\n\t\t\tif err != io.EOF {\n\t\t\t\tfmt.Fprintf(&buf, \"reading request: %v\\n\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tw.Write(buf.Bytes())\n}\n\n\/\/ Handler returns an HTTP handler that serves the named profile.\nfunc Handler(name string) http.Handler {\n\treturn handler(name)\n}\n\ntype handler string\n\nfunc (name handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=utf-8\")\n\tdebug, _ := strconv.Atoi(r.FormValue(\"debug\"))\n\tp := pprof.Lookup(string(name))\n\tif p == nil {\n\t\tw.WriteHeader(404)\n\t\tfmt.Fprintf(w, \"Unknown profile: %s\\n\", name)\n\t\treturn\n\t}\n\tgc, _ := strconv.Atoi(r.FormValue(\"gc\"))\n\tif name == \"heap\" && gc > 0 {\n\t\truntime.GC()\n\t}\n\tp.WriteTo(w, debug)\n\treturn\n}\n\n\/\/ Index responds with the pprof-formatted profile named by the request.\n\/\/ For example, \"\/debug\/pprof\/heap\" serves the \"heap\" profile.\n\/\/ Index responds to a request for \"\/debug\/pprof\/\" with an HTML page\n\/\/ listing the available profiles.\nfunc Index(w http.ResponseWriter, r *http.Request) {\n\tif strings.HasPrefix(r.URL.Path, \"\/debug\/pprof\/\") {\n\t\tname := strings.TrimPrefix(r.URL.Path, \"\/debug\/pprof\/\")\n\t\tif name != \"\" {\n\t\t\thandler(name).ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t}\n\n\tprofiles := pprof.Profiles()\n\tif err := indexTmpl.Execute(w, profiles); err != nil {\n\t\tlog.Print(err)\n\t}\n}\n\nvar indexTmpl = template.Must(template.New(\"index\").Parse(`<html>\n<head>\n<title>\/debug\/pprof\/<\/title>\n<\/head>\n\/debug\/pprof\/<br>\n<br>\n<body>\nprofiles:<br>\n<table>\n{{range .}}\n<tr><td align=right>{{.Count}}<td><a href=\"\/debug\/pprof\/{{.Name}}?debug=1\">{{.Name}}<\/a>\n{{end}}\n<\/table>\n<br>\n<a href=\"\/debug\/pprof\/goroutine?debug=2\">full goroutine stack dump<\/a><br>\n<\/body>\n<\/html>\n`))\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Build toolchain using Go 1.4.\n\/\/\n\/\/ The general strategy is to copy the source files we need into\n\/\/ a new GOPATH workspace, adjust import paths appropriately,\n\/\/ invoke the Go 1.4 go command to build those sources,\n\/\/ and then copy the binaries back.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\/\/ bootstrapDirs is a list of directories holding code that must be\n\/\/ compiled with a Go 1.4 toolchain to produce the bootstrapTargets.\n\/\/ All directories in this list are relative to and must be below $GOROOT\/src.\n\/\/\n\/\/ The list has two kinds of entries: names beginning with cmd\/ with\n\/\/ no other slashes, which are commands, and other paths, which are packages\n\/\/ supporting the commands. Packages in the standard library can be listed\n\/\/ if a newer copy needs to be substituted for the Go 1.4 copy when used\n\/\/ by the command packages. Paths ending with \/... automatically\n\/\/ include all packages within subdirectories as well.\n\/\/ These will be imported during bootstrap as bootstrap\/name, like bootstrap\/math\/big.\nvar bootstrapDirs = []string{\n\t\"cmd\/asm\",\n\t\"cmd\/asm\/internal\/...\",\n\t\"cmd\/cgo\",\n\t\"cmd\/compile\",\n\t\"cmd\/compile\/internal\/...\",\n\t\"cmd\/internal\/archive\",\n\t\"cmd\/internal\/bio\",\n\t\"cmd\/internal\/codesign\",\n\t\"cmd\/internal\/dwarf\",\n\t\"cmd\/internal\/edit\",\n\t\"cmd\/internal\/gcprog\",\n\t\"cmd\/internal\/goobj\",\n\t\"cmd\/internal\/notsha256\",\n\t\"cmd\/internal\/obj\/...\",\n\t\"cmd\/internal\/objabi\",\n\t\"cmd\/internal\/pkgpath\",\n\t\"cmd\/internal\/quoted\",\n\t\"cmd\/internal\/src\",\n\t\"cmd\/internal\/sys\",\n\t\"cmd\/link\",\n\t\"cmd\/link\/internal\/...\",\n\t\"compress\/flate\",\n\t\"compress\/zlib\",\n\t\"container\/heap\",\n\t\"debug\/dwarf\",\n\t\"debug\/elf\",\n\t\"debug\/macho\",\n\t\"debug\/pe\",\n\t\"go\/constant\",\n\t\"internal\/buildcfg\",\n\t\"internal\/goexperiment\",\n\t\"internal\/goversion\",\n\t\"internal\/pkgbits\",\n\t\"internal\/race\",\n\t\"internal\/unsafeheader\",\n\t\"internal\/xcoff\",\n\t\"math\/big\",\n\t\"math\/bits\",\n\t\"sort\",\n\t\"strconv\",\n}\n\n\/\/ File prefixes that are ignored by go\/build anyway, and cause\n\/\/ problems with editor generated temporary files (#18931).\nvar ignorePrefixes = []string{\n\t\".\",\n\t\"_\",\n\t\"#\",\n}\n\n\/\/ File suffixes that use build tags introduced since Go 1.4.\n\/\/ These must not be copied into the bootstrap build directory.\n\/\/ Also ignore test files.\nvar ignoreSuffixes = []string{\n\t\"_arm64.s\",\n\t\"_arm64.go\",\n\t\"_loong64.s\",\n\t\"_loong64.go\",\n\t\"_riscv64.s\",\n\t\"_riscv64.go\",\n\t\"_wasm.s\",\n\t\"_wasm.go\",\n\t\"_test.s\",\n\t\"_test.go\",\n}\n\nvar tryDirs = []string{\n\t\"sdk\/go1.17\",\n\t\"go1.17\",\n}\n\nfunc bootstrapBuildTools() {\n\tgoroot_bootstrap := os.Getenv(\"GOROOT_BOOTSTRAP\")\n\tif goroot_bootstrap == \"\" {\n\t\thome := os.Getenv(\"HOME\")\n\t\tgoroot_bootstrap = pathf(\"%s\/go1.4\", home)\n\t\tfor _, d := range tryDirs {\n\t\t\tif p := pathf(\"%s\/%s\", home, d); isdir(p) {\n\t\t\t\tgoroot_bootstrap = p\n\t\t\t}\n\t\t}\n\t}\n\txprintf(\"Building Go toolchain1 using %s.\\n\", goroot_bootstrap)\n\n\tmkbuildcfg(pathf(\"%s\/src\/internal\/buildcfg\/zbootstrap.go\", goroot))\n\tmkobjabi(pathf(\"%s\/src\/cmd\/internal\/objabi\/zbootstrap.go\", goroot))\n\n\t\/\/ Use $GOROOT\/pkg\/bootstrap as the bootstrap workspace root.\n\t\/\/ We use a subdirectory of $GOROOT\/pkg because that's the\n\t\/\/ space within $GOROOT where we store all generated objects.\n\t\/\/ We could use a temporary directory outside $GOROOT instead,\n\t\/\/ but it is easier to debug on failure if the files are in a known location.\n\tworkspace := pathf(\"%s\/pkg\/bootstrap\", goroot)\n\txremoveall(workspace)\n\txatexit(func() { xremoveall(workspace) })\n\tbase := pathf(\"%s\/src\/bootstrap\", workspace)\n\txmkdirall(base)\n\n\t\/\/ Copy source code into $GOROOT\/pkg\/bootstrap and rewrite import paths.\n\twritefile(\"module bootstrap\\n\", pathf(\"%s\/%s\", base, \"go.mod\"), 0)\n\tfor _, dir := range bootstrapDirs {\n\t\trecurse := strings.HasSuffix(dir, \"\/...\")\n\t\tdir = strings.TrimSuffix(dir, \"\/...\")\n\t\tfilepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\tfatalf(\"walking bootstrap dirs failed: %v: %v\", path, err)\n\t\t\t}\n\n\t\t\tname := filepath.Base(path)\n\t\t\tsrc := pathf(\"%s\/src\/%s\", goroot, path)\n\t\t\tdst := pathf(\"%s\/%s\", base, path)\n\n\t\t\tif info.IsDir() {\n\t\t\t\tif !recurse && path != dir || name == \"testdata\" {\n\t\t\t\t\treturn filepath.SkipDir\n\t\t\t\t}\n\n\t\t\t\txmkdirall(dst)\n\t\t\t\tif path == \"cmd\/cgo\" {\n\t\t\t\t\t\/\/ Write to src because we need the file both for bootstrap\n\t\t\t\t\t\/\/ and for later in the main build.\n\t\t\t\t\tmkzdefaultcc(\"\", pathf(\"%s\/zdefaultcc.go\", src))\n\t\t\t\t\tmkzdefaultcc(\"\", pathf(\"%s\/zdefaultcc.go\", dst))\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfor _, pre := range ignorePrefixes {\n\t\t\t\tif strings.HasPrefix(name, pre) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, suf := range ignoreSuffixes {\n\t\t\t\tif strings.HasSuffix(name, suf) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttext := bootstrapRewriteFile(src)\n\t\t\twritefile(text, dst, 0)\n\t\t\treturn nil\n\t\t})\n\t}\n\n\t\/\/ Set up environment for invoking Go 1.4 go command.\n\t\/\/ GOROOT points at Go 1.4 GOROOT,\n\t\/\/ GOPATH points at our bootstrap workspace,\n\t\/\/ GOBIN is empty, so that binaries are installed to GOPATH\/bin,\n\t\/\/ and GOOS, GOHOSTOS, GOARCH, and GOHOSTOS are empty,\n\t\/\/ so that Go 1.4 builds whatever kind of binary it knows how to build.\n\t\/\/ Restore GOROOT, GOPATH, and GOBIN when done.\n\t\/\/ Don't bother with GOOS, GOHOSTOS, GOARCH, and GOHOSTARCH,\n\t\/\/ because setup will take care of those when bootstrapBuildTools returns.\n\n\tdefer os.Setenv(\"GOROOT\", os.Getenv(\"GOROOT\"))\n\tos.Setenv(\"GOROOT\", goroot_bootstrap)\n\n\tdefer os.Setenv(\"GOPATH\", os.Getenv(\"GOPATH\"))\n\tos.Setenv(\"GOPATH\", workspace)\n\n\tdefer os.Setenv(\"GOBIN\", os.Getenv(\"GOBIN\"))\n\tos.Setenv(\"GOBIN\", \"\")\n\n\tos.Setenv(\"GOOS\", \"\")\n\tos.Setenv(\"GOHOSTOS\", \"\")\n\tos.Setenv(\"GOARCH\", \"\")\n\tos.Setenv(\"GOHOSTARCH\", \"\")\n\n\t\/\/ Run Go 1.4 to build binaries. Use -gcflags=-l to disable inlining to\n\t\/\/ workaround bugs in Go 1.4's compiler. See discussion thread:\n\t\/\/ https:\/\/groups.google.com\/d\/msg\/golang-dev\/Ss7mCKsvk8w\/Gsq7VYI0AwAJ\n\t\/\/ Use the math_big_pure_go build tag to disable the assembly in math\/big\n\t\/\/ which may contain unsupported instructions.\n\t\/\/ Note that if we are using Go 1.10 or later as bootstrap, the -gcflags=-l\n\t\/\/ only applies to the final cmd\/go binary, but that's OK: if this is Go 1.10\n\t\/\/ or later we don't need to disable inlining to work around bugs in the Go 1.4 compiler.\n\tcmd := []string{\n\t\tpathf(\"%s\/bin\/go\", goroot_bootstrap),\n\t\t\"install\",\n\t\t\"-gcflags=-l\",\n\t\t\"-tags=math_big_pure_go compiler_bootstrap\",\n\t}\n\tif vflag > 0 {\n\t\tcmd = append(cmd, \"-v\")\n\t}\n\tif tool := os.Getenv(\"GOBOOTSTRAP_TOOLEXEC\"); tool != \"\" {\n\t\tcmd = append(cmd, \"-toolexec=\"+tool)\n\t}\n\tcmd = append(cmd, \"bootstrap\/cmd\/...\")\n\trun(base, ShowOutput|CheckExit, cmd...)\n\n\t\/\/ Copy binaries into tool binary directory.\n\tfor _, name := range bootstrapDirs {\n\t\tif !strings.HasPrefix(name, \"cmd\/\") {\n\t\t\tcontinue\n\t\t}\n\t\tname = name[len(\"cmd\/\"):]\n\t\tif !strings.Contains(name, \"\/\") {\n\t\t\tcopyfile(pathf(\"%s\/%s%s\", tooldir, name, exe), pathf(\"%s\/bin\/%s%s\", workspace, name, exe), writeExec)\n\t\t}\n\t}\n\n\tif vflag > 0 {\n\t\txprintf(\"\\n\")\n\t}\n}\n\nvar ssaRewriteFileSubstring = filepath.FromSlash(\"src\/cmd\/compile\/internal\/ssa\/rewrite\")\n\n\/\/ isUnneededSSARewriteFile reports whether srcFile is a\n\/\/ src\/cmd\/compile\/internal\/ssa\/rewriteARCHNAME.go file for an\n\/\/ architecture that isn't for the current runtime.GOARCH.\n\/\/\n\/\/ When unneeded is true archCaps is the rewrite base filename without\n\/\/ the \"rewrite\" prefix or \".go\" suffix: AMD64, 386, ARM, ARM64, etc.\nfunc isUnneededSSARewriteFile(srcFile string) (archCaps string, unneeded bool) {\n\tif !strings.Contains(srcFile, ssaRewriteFileSubstring) {\n\t\treturn \"\", false\n\t}\n\tfileArch := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(srcFile), \"rewrite\"), \".go\")\n\tif fileArch == \"\" {\n\t\treturn \"\", false\n\t}\n\tb := fileArch[0]\n\tif b == '_' || ('a' <= b && b <= 'z') {\n\t\treturn \"\", false\n\t}\n\tarchCaps = fileArch\n\tfileArch = strings.ToLower(fileArch)\n\tfileArch = strings.TrimSuffix(fileArch, \"splitload\")\n\tif fileArch == os.Getenv(\"GOHOSTARCH\") {\n\t\treturn \"\", false\n\t}\n\tif fileArch == strings.TrimSuffix(runtime.GOARCH, \"le\") {\n\t\treturn \"\", false\n\t}\n\tif fileArch == strings.TrimSuffix(os.Getenv(\"GOARCH\"), \"le\") {\n\t\treturn \"\", false\n\t}\n\treturn archCaps, true\n}\n\nfunc bootstrapRewriteFile(srcFile string) string {\n\t\/\/ During bootstrap, generate dummy rewrite files for\n\t\/\/ irrelevant architectures. We only need to build a bootstrap\n\t\/\/ binary that works for the current runtime.GOARCH.\n\t\/\/ This saves 6+ seconds of bootstrap.\n\tif archCaps, ok := isUnneededSSARewriteFile(srcFile); ok {\n\t\treturn fmt.Sprintf(`\/\/ Code generated by go tool dist; DO NOT EDIT.\n\npackage ssa\n\nfunc rewriteValue%s(v *Value) bool { panic(\"unused during bootstrap\") }\nfunc rewriteBlock%s(b *Block) bool { panic(\"unused during bootstrap\") }\n`, archCaps, archCaps)\n\t}\n\n\treturn bootstrapFixImports(srcFile)\n}\n\nfunc bootstrapFixImports(srcFile string) string {\n\ttext := readfile(srcFile)\n\tif !strings.Contains(srcFile, \"\/cmd\/\") && !strings.Contains(srcFile, `\\cmd\\`) {\n\t\ttext = regexp.MustCompile(`\\bany\\b`).ReplaceAllString(text, \"interface{}\")\n\t}\n\tlines := strings.SplitAfter(text, \"\\n\")\n\tinBlock := false\n\tfor i, line := range lines {\n\t\tif strings.HasPrefix(line, \"import (\") {\n\t\t\tinBlock = true\n\t\t\tcontinue\n\t\t}\n\t\tif inBlock && strings.HasPrefix(line, \")\") {\n\t\t\tinBlock = false\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(line, `import \"`) || strings.HasPrefix(line, `import . \"`) ||\n\t\t\tinBlock && (strings.HasPrefix(line, \"\\t\\\"\") || strings.HasPrefix(line, \"\\t. \\\"\") || strings.HasPrefix(line, \"\\texec \\\"\")) {\n\t\t\tline = strings.Replace(line, `\"cmd\/`, `\"bootstrap\/cmd\/`, -1)\n\t\t\tfor _, dir := range bootstrapDirs {\n\t\t\t\tif strings.HasPrefix(dir, \"cmd\/\") {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tline = strings.Replace(line, `\"`+dir+`\"`, `\"bootstrap\/`+dir+`\"`, -1)\n\t\t\t}\n\t\t\tlines[i] = line\n\t\t}\n\t}\n\n\tlines[0] = \"\/\/ Code generated by go tool dist; DO NOT EDIT.\\n\/\/ This is a bootstrap copy of \" + srcFile + \"\\n\\n\/\/line \" + srcFile + \":1\\n\" + lines[0]\n\n\treturn strings.Join(lines, \"\")\n}\n<commit_msg>cmd\/dist: use gohostarch for ssa rewrite check<commit_after>\/\/ Copyright 2015 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Build toolchain using Go 1.4.\n\/\/\n\/\/ The general strategy is to copy the source files we need into\n\/\/ a new GOPATH workspace, adjust import paths appropriately,\n\/\/ invoke the Go 1.4 go command to build those sources,\n\/\/ and then copy the binaries back.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/\/ bootstrapDirs is a list of directories holding code that must be\n\/\/ compiled with a Go 1.4 toolchain to produce the bootstrapTargets.\n\/\/ All directories in this list are relative to and must be below $GOROOT\/src.\n\/\/\n\/\/ The list has two kinds of entries: names beginning with cmd\/ with\n\/\/ no other slashes, which are commands, and other paths, which are packages\n\/\/ supporting the commands. Packages in the standard library can be listed\n\/\/ if a newer copy needs to be substituted for the Go 1.4 copy when used\n\/\/ by the command packages. Paths ending with \/... automatically\n\/\/ include all packages within subdirectories as well.\n\/\/ These will be imported during bootstrap as bootstrap\/name, like bootstrap\/math\/big.\nvar bootstrapDirs = []string{\n\t\"cmd\/asm\",\n\t\"cmd\/asm\/internal\/...\",\n\t\"cmd\/cgo\",\n\t\"cmd\/compile\",\n\t\"cmd\/compile\/internal\/...\",\n\t\"cmd\/internal\/archive\",\n\t\"cmd\/internal\/bio\",\n\t\"cmd\/internal\/codesign\",\n\t\"cmd\/internal\/dwarf\",\n\t\"cmd\/internal\/edit\",\n\t\"cmd\/internal\/gcprog\",\n\t\"cmd\/internal\/goobj\",\n\t\"cmd\/internal\/notsha256\",\n\t\"cmd\/internal\/obj\/...\",\n\t\"cmd\/internal\/objabi\",\n\t\"cmd\/internal\/pkgpath\",\n\t\"cmd\/internal\/quoted\",\n\t\"cmd\/internal\/src\",\n\t\"cmd\/internal\/sys\",\n\t\"cmd\/link\",\n\t\"cmd\/link\/internal\/...\",\n\t\"compress\/flate\",\n\t\"compress\/zlib\",\n\t\"container\/heap\",\n\t\"debug\/dwarf\",\n\t\"debug\/elf\",\n\t\"debug\/macho\",\n\t\"debug\/pe\",\n\t\"go\/constant\",\n\t\"internal\/buildcfg\",\n\t\"internal\/goexperiment\",\n\t\"internal\/goversion\",\n\t\"internal\/pkgbits\",\n\t\"internal\/race\",\n\t\"internal\/unsafeheader\",\n\t\"internal\/xcoff\",\n\t\"math\/big\",\n\t\"math\/bits\",\n\t\"sort\",\n\t\"strconv\",\n}\n\n\/\/ File prefixes that are ignored by go\/build anyway, and cause\n\/\/ problems with editor generated temporary files (#18931).\nvar ignorePrefixes = []string{\n\t\".\",\n\t\"_\",\n\t\"#\",\n}\n\n\/\/ File suffixes that use build tags introduced since Go 1.4.\n\/\/ These must not be copied into the bootstrap build directory.\n\/\/ Also ignore test files.\nvar ignoreSuffixes = []string{\n\t\"_arm64.s\",\n\t\"_arm64.go\",\n\t\"_loong64.s\",\n\t\"_loong64.go\",\n\t\"_riscv64.s\",\n\t\"_riscv64.go\",\n\t\"_wasm.s\",\n\t\"_wasm.go\",\n\t\"_test.s\",\n\t\"_test.go\",\n}\n\nvar tryDirs = []string{\n\t\"sdk\/go1.17\",\n\t\"go1.17\",\n}\n\nfunc bootstrapBuildTools() {\n\tgoroot_bootstrap := os.Getenv(\"GOROOT_BOOTSTRAP\")\n\tif goroot_bootstrap == \"\" {\n\t\thome := os.Getenv(\"HOME\")\n\t\tgoroot_bootstrap = pathf(\"%s\/go1.4\", home)\n\t\tfor _, d := range tryDirs {\n\t\t\tif p := pathf(\"%s\/%s\", home, d); isdir(p) {\n\t\t\t\tgoroot_bootstrap = p\n\t\t\t}\n\t\t}\n\t}\n\txprintf(\"Building Go toolchain1 using %s.\\n\", goroot_bootstrap)\n\n\tmkbuildcfg(pathf(\"%s\/src\/internal\/buildcfg\/zbootstrap.go\", goroot))\n\tmkobjabi(pathf(\"%s\/src\/cmd\/internal\/objabi\/zbootstrap.go\", goroot))\n\n\t\/\/ Use $GOROOT\/pkg\/bootstrap as the bootstrap workspace root.\n\t\/\/ We use a subdirectory of $GOROOT\/pkg because that's the\n\t\/\/ space within $GOROOT where we store all generated objects.\n\t\/\/ We could use a temporary directory outside $GOROOT instead,\n\t\/\/ but it is easier to debug on failure if the files are in a known location.\n\tworkspace := pathf(\"%s\/pkg\/bootstrap\", goroot)\n\txremoveall(workspace)\n\txatexit(func() { xremoveall(workspace) })\n\tbase := pathf(\"%s\/src\/bootstrap\", workspace)\n\txmkdirall(base)\n\n\t\/\/ Copy source code into $GOROOT\/pkg\/bootstrap and rewrite import paths.\n\twritefile(\"module bootstrap\\n\", pathf(\"%s\/%s\", base, \"go.mod\"), 0)\n\tfor _, dir := range bootstrapDirs {\n\t\trecurse := strings.HasSuffix(dir, \"\/...\")\n\t\tdir = strings.TrimSuffix(dir, \"\/...\")\n\t\tfilepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\tfatalf(\"walking bootstrap dirs failed: %v: %v\", path, err)\n\t\t\t}\n\n\t\t\tname := filepath.Base(path)\n\t\t\tsrc := pathf(\"%s\/src\/%s\", goroot, path)\n\t\t\tdst := pathf(\"%s\/%s\", base, path)\n\n\t\t\tif info.IsDir() {\n\t\t\t\tif !recurse && path != dir || name == \"testdata\" {\n\t\t\t\t\treturn filepath.SkipDir\n\t\t\t\t}\n\n\t\t\t\txmkdirall(dst)\n\t\t\t\tif path == \"cmd\/cgo\" {\n\t\t\t\t\t\/\/ Write to src because we need the file both for bootstrap\n\t\t\t\t\t\/\/ and for later in the main build.\n\t\t\t\t\tmkzdefaultcc(\"\", pathf(\"%s\/zdefaultcc.go\", src))\n\t\t\t\t\tmkzdefaultcc(\"\", pathf(\"%s\/zdefaultcc.go\", dst))\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tfor _, pre := range ignorePrefixes {\n\t\t\t\tif strings.HasPrefix(name, pre) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, suf := range ignoreSuffixes {\n\t\t\t\tif strings.HasSuffix(name, suf) {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttext := bootstrapRewriteFile(src)\n\t\t\twritefile(text, dst, 0)\n\t\t\treturn nil\n\t\t})\n\t}\n\n\t\/\/ Set up environment for invoking Go 1.4 go command.\n\t\/\/ GOROOT points at Go 1.4 GOROOT,\n\t\/\/ GOPATH points at our bootstrap workspace,\n\t\/\/ GOBIN is empty, so that binaries are installed to GOPATH\/bin,\n\t\/\/ and GOOS, GOHOSTOS, GOARCH, and GOHOSTOS are empty,\n\t\/\/ so that Go 1.4 builds whatever kind of binary it knows how to build.\n\t\/\/ Restore GOROOT, GOPATH, and GOBIN when done.\n\t\/\/ Don't bother with GOOS, GOHOSTOS, GOARCH, and GOHOSTARCH,\n\t\/\/ because setup will take care of those when bootstrapBuildTools returns.\n\n\tdefer os.Setenv(\"GOROOT\", os.Getenv(\"GOROOT\"))\n\tos.Setenv(\"GOROOT\", goroot_bootstrap)\n\n\tdefer os.Setenv(\"GOPATH\", os.Getenv(\"GOPATH\"))\n\tos.Setenv(\"GOPATH\", workspace)\n\n\tdefer os.Setenv(\"GOBIN\", os.Getenv(\"GOBIN\"))\n\tos.Setenv(\"GOBIN\", \"\")\n\n\tos.Setenv(\"GOOS\", \"\")\n\tos.Setenv(\"GOHOSTOS\", \"\")\n\tos.Setenv(\"GOARCH\", \"\")\n\tos.Setenv(\"GOHOSTARCH\", \"\")\n\n\t\/\/ Run Go 1.4 to build binaries. Use -gcflags=-l to disable inlining to\n\t\/\/ workaround bugs in Go 1.4's compiler. See discussion thread:\n\t\/\/ https:\/\/groups.google.com\/d\/msg\/golang-dev\/Ss7mCKsvk8w\/Gsq7VYI0AwAJ\n\t\/\/ Use the math_big_pure_go build tag to disable the assembly in math\/big\n\t\/\/ which may contain unsupported instructions.\n\t\/\/ Note that if we are using Go 1.10 or later as bootstrap, the -gcflags=-l\n\t\/\/ only applies to the final cmd\/go binary, but that's OK: if this is Go 1.10\n\t\/\/ or later we don't need to disable inlining to work around bugs in the Go 1.4 compiler.\n\tcmd := []string{\n\t\tpathf(\"%s\/bin\/go\", goroot_bootstrap),\n\t\t\"install\",\n\t\t\"-gcflags=-l\",\n\t\t\"-tags=math_big_pure_go compiler_bootstrap\",\n\t}\n\tif vflag > 0 {\n\t\tcmd = append(cmd, \"-v\")\n\t}\n\tif tool := os.Getenv(\"GOBOOTSTRAP_TOOLEXEC\"); tool != \"\" {\n\t\tcmd = append(cmd, \"-toolexec=\"+tool)\n\t}\n\tcmd = append(cmd, \"bootstrap\/cmd\/...\")\n\trun(base, ShowOutput|CheckExit, cmd...)\n\n\t\/\/ Copy binaries into tool binary directory.\n\tfor _, name := range bootstrapDirs {\n\t\tif !strings.HasPrefix(name, \"cmd\/\") {\n\t\t\tcontinue\n\t\t}\n\t\tname = name[len(\"cmd\/\"):]\n\t\tif !strings.Contains(name, \"\/\") {\n\t\t\tcopyfile(pathf(\"%s\/%s%s\", tooldir, name, exe), pathf(\"%s\/bin\/%s%s\", workspace, name, exe), writeExec)\n\t\t}\n\t}\n\n\tif vflag > 0 {\n\t\txprintf(\"\\n\")\n\t}\n}\n\nvar ssaRewriteFileSubstring = filepath.FromSlash(\"src\/cmd\/compile\/internal\/ssa\/rewrite\")\n\n\/\/ isUnneededSSARewriteFile reports whether srcFile is a\n\/\/ src\/cmd\/compile\/internal\/ssa\/rewriteARCHNAME.go file for an\n\/\/ architecture that isn't for the given GOARCH.\n\/\/\n\/\/ When unneeded is true archCaps is the rewrite base filename without\n\/\/ the \"rewrite\" prefix or \".go\" suffix: AMD64, 386, ARM, ARM64, etc.\nfunc isUnneededSSARewriteFile(srcFile, goArch string) (archCaps string, unneeded bool) {\n\tif !strings.Contains(srcFile, ssaRewriteFileSubstring) {\n\t\treturn \"\", false\n\t}\n\tfileArch := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(srcFile), \"rewrite\"), \".go\")\n\tif fileArch == \"\" {\n\t\treturn \"\", false\n\t}\n\tb := fileArch[0]\n\tif b == '_' || ('a' <= b && b <= 'z') {\n\t\treturn \"\", false\n\t}\n\tarchCaps = fileArch\n\tfileArch = strings.ToLower(fileArch)\n\tfileArch = strings.TrimSuffix(fileArch, \"splitload\")\n\tif fileArch == goArch {\n\t\treturn \"\", false\n\t}\n\tif fileArch == strings.TrimSuffix(goArch, \"le\") {\n\t\treturn \"\", false\n\t}\n\treturn archCaps, true\n}\n\nfunc bootstrapRewriteFile(srcFile string) string {\n\t\/\/ During bootstrap, generate dummy rewrite files for\n\t\/\/ irrelevant architectures. We only need to build a bootstrap\n\t\/\/ binary that works for the current gohostarch.\n\t\/\/ This saves 6+ seconds of bootstrap.\n\tif archCaps, ok := isUnneededSSARewriteFile(srcFile, gohostarch); ok {\n\t\treturn fmt.Sprintf(`\/\/ Code generated by go tool dist; DO NOT EDIT.\n\npackage ssa\n\nfunc rewriteValue%s(v *Value) bool { panic(\"unused during bootstrap\") }\nfunc rewriteBlock%s(b *Block) bool { panic(\"unused during bootstrap\") }\n`, archCaps, archCaps)\n\t}\n\n\treturn bootstrapFixImports(srcFile)\n}\n\nfunc bootstrapFixImports(srcFile string) string {\n\ttext := readfile(srcFile)\n\tif !strings.Contains(srcFile, \"\/cmd\/\") && !strings.Contains(srcFile, `\\cmd\\`) {\n\t\ttext = regexp.MustCompile(`\\bany\\b`).ReplaceAllString(text, \"interface{}\")\n\t}\n\tlines := strings.SplitAfter(text, \"\\n\")\n\tinBlock := false\n\tfor i, line := range lines {\n\t\tif strings.HasPrefix(line, \"import (\") {\n\t\t\tinBlock = true\n\t\t\tcontinue\n\t\t}\n\t\tif inBlock && strings.HasPrefix(line, \")\") {\n\t\t\tinBlock = false\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(line, `import \"`) || strings.HasPrefix(line, `import . \"`) ||\n\t\t\tinBlock && (strings.HasPrefix(line, \"\\t\\\"\") || strings.HasPrefix(line, \"\\t. \\\"\") || strings.HasPrefix(line, \"\\texec \\\"\")) {\n\t\t\tline = strings.Replace(line, `\"cmd\/`, `\"bootstrap\/cmd\/`, -1)\n\t\t\tfor _, dir := range bootstrapDirs {\n\t\t\t\tif strings.HasPrefix(dir, \"cmd\/\") {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tline = strings.Replace(line, `\"`+dir+`\"`, `\"bootstrap\/`+dir+`\"`, -1)\n\t\t\t}\n\t\t\tlines[i] = line\n\t\t}\n\t}\n\n\tlines[0] = \"\/\/ Code generated by go tool dist; DO NOT EDIT.\\n\/\/ This is a bootstrap copy of \" + srcFile + \"\\n\\n\/\/line \" + srcFile + \":1\\n\" + lines[0]\n\n\treturn strings.Join(lines, \"\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2010 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Run \"make install\" to build package.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"template\"\n)\n\n\/\/ domake builds the package in dir.\n\/\/ If local is false, the package was copied from an external system.\n\/\/ For non-local packages or packages without Makefiles,\n\/\/ domake generates a standard Makefile and passes it\n\/\/ to make on standard input.\nfunc domake(dir, pkg string, local bool) (err os.Error) {\n\tneedMakefile := true\n\tif local {\n\t\t_, err := os.Stat(dir + \"\/Makefile\")\n\t\tif err == nil {\n\t\t\tneedMakefile = false\n\t\t}\n\t}\n\tcmd := []string{\"gomake\"}\n\tvar makefile []byte\n\tif needMakefile {\n\t\tif makefile, err = makeMakefile(dir, pkg); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcmd = append(cmd, \"-f-\")\n\t}\n\tif *clean {\n\t\tcmd = append(cmd, \"clean\")\n\t}\n\tcmd = append(cmd, \"install\")\n\treturn run(dir, makefile, cmd...)\n}\n\n\/\/ makeMakefile computes the standard Makefile for the directory dir\n\/\/ installing as package pkg.  It includes all *.go files in the directory\n\/\/ except those in package main and those ending in _test.go.\nfunc makeMakefile(dir, pkg string) ([]byte, os.Error) {\n\tdirInfo, err := scanDir(dir, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(dirInfo.cgoFiles) == 0 && len(dirInfo.cFiles) > 0 {\n\t\t\/\/ When using cgo, .c files are compiled with gcc.  Without cgo,\n\t\t\/\/ they may be intended for 6c.  Just error out for now.\n\t\treturn nil, os.ErrorString(\"C files found in non-cgo package\")\n\t}\n\n\tcgoFiles := dirInfo.cgoFiles\n\tisCgo := make(map[string]bool, len(cgoFiles))\n\tfor _, file := range cgoFiles {\n\t\tisCgo[file] = true\n\t}\n\n\toFiles := make([]string, 0, len(dirInfo.cFiles))\n\tfor _, file := range dirInfo.cFiles {\n\t\toFiles = append(oFiles, file[:len(file)-2]+\".o\")\n\t}\n\n\tgoFiles := make([]string, 0, len(dirInfo.goFiles))\n\tfor _, file := range dirInfo.goFiles {\n\t\tif !isCgo[file] {\n\t\t\tgoFiles = append(goFiles, file)\n\t\t}\n\t}\n\n\tvar buf bytes.Buffer\n\tmd := makedata{pkg, goFiles, cgoFiles, oFiles}\n\tif err := makefileTemplate.Execute(&md, &buf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}\n\n\/\/ makedata is the data type for the makefileTemplate.\ntype makedata struct {\n\tpkg      string   \/\/ package import path\n\tgoFiles  []string \/\/ list of non-cgo .go files\n\tcgoFiles []string \/\/ list of cgo .go files\n\toFiles   []string \/\/ list of ofiles for cgo\n}\n\nvar makefileTemplate = template.MustParse(`\ninclude $(GOROOT)\/src\/Make.inc\n\nTARG={pkg}\n\n{.section goFiles}\nGOFILES=\\\n{.repeated section goFiles}\n\t{@}\\\n{.end}\n\n{.end}\n{.section cgoFiles}\nCGOFILES=\\\n{.repeated section cgoFiles}\n\t{@}\\\n{.end}\n\n{.end}\n{.section oFiles}\nCGO_OFILES=\\\n{.repeated section oFiles}\n\t{@}\\\n{.end}\n\n{.end}\ninclude $(GOROOT)\/src\/Make.pkg\n`,\n\tnil)\n<commit_msg>goinstall: Fix template to use exported fields<commit_after>\/\/ Copyright 2010 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Run \"make install\" to build package.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"template\"\n)\n\n\/\/ domake builds the package in dir.\n\/\/ If local is false, the package was copied from an external system.\n\/\/ For non-local packages or packages without Makefiles,\n\/\/ domake generates a standard Makefile and passes it\n\/\/ to make on standard input.\nfunc domake(dir, pkg string, local bool) (err os.Error) {\n\tneedMakefile := true\n\tif local {\n\t\t_, err := os.Stat(dir + \"\/Makefile\")\n\t\tif err == nil {\n\t\t\tneedMakefile = false\n\t\t}\n\t}\n\tcmd := []string{\"gomake\"}\n\tvar makefile []byte\n\tif needMakefile {\n\t\tif makefile, err = makeMakefile(dir, pkg); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcmd = append(cmd, \"-f-\")\n\t}\n\tif *clean {\n\t\tcmd = append(cmd, \"clean\")\n\t}\n\tcmd = append(cmd, \"install\")\n\treturn run(dir, makefile, cmd...)\n}\n\n\/\/ makeMakefile computes the standard Makefile for the directory dir\n\/\/ installing as package pkg.  It includes all *.go files in the directory\n\/\/ except those in package main and those ending in _test.go.\nfunc makeMakefile(dir, pkg string) ([]byte, os.Error) {\n\tdirInfo, err := scanDir(dir, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(dirInfo.cgoFiles) == 0 && len(dirInfo.cFiles) > 0 {\n\t\t\/\/ When using cgo, .c files are compiled with gcc.  Without cgo,\n\t\t\/\/ they may be intended for 6c.  Just error out for now.\n\t\treturn nil, os.ErrorString(\"C files found in non-cgo package\")\n\t}\n\n\tcgoFiles := dirInfo.cgoFiles\n\tisCgo := make(map[string]bool, len(cgoFiles))\n\tfor _, file := range cgoFiles {\n\t\tisCgo[file] = true\n\t}\n\n\toFiles := make([]string, 0, len(dirInfo.cFiles))\n\tfor _, file := range dirInfo.cFiles {\n\t\toFiles = append(oFiles, file[:len(file)-2]+\".o\")\n\t}\n\n\tgoFiles := make([]string, 0, len(dirInfo.goFiles))\n\tfor _, file := range dirInfo.goFiles {\n\t\tif !isCgo[file] {\n\t\t\tgoFiles = append(goFiles, file)\n\t\t}\n\t}\n\n\tvar buf bytes.Buffer\n\tmd := makedata{pkg, goFiles, cgoFiles, oFiles}\n\tif err := makefileTemplate.Execute(&md, &buf); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}\n\n\/\/ makedata is the data type for the makefileTemplate.\ntype makedata struct {\n\tPkg      string   \/\/ package import path\n\tGoFiles  []string \/\/ list of non-cgo .go files\n\tCgoFiles []string \/\/ list of cgo .go files\n\tOFiles   []string \/\/ list of ofiles for cgo\n}\n\nvar makefileTemplate = template.MustParse(`\ninclude $(GOROOT)\/src\/Make.inc\n\nTARG={Pkg}\n\n{.section GoFiles}\nGOFILES=\\\n{.repeated section GoFiles}\n\t{@}\\\n{.end}\n\n{.end}\n{.section CgoFiles}\nCGOFILES=\\\n{.repeated section CgoFiles}\n\t{@}\\\n{.end}\n\n{.end}\n{.section OFiles}\nCGO_OFILES=\\\n{.repeated section OFiles}\n\t{@}\\\n{.end}\n\n{.end}\ninclude $(GOROOT)\/src\/Make.pkg\n`,\n\tnil)\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ A Go scanner. Takes a []byte as source which can then be\n\/\/ tokenized through repeated calls to the Scan() function.\n\/\/\n\/\/ Sample use:\n\/\/\n\/\/\timport \"token\"\n\/\/\timport \"scanner\"\n\/\/\n\/\/\tfunc tokenize(src []byte) {\n\/\/\t\tvar s scanner.Scanner;\n\/\/\t\ts.Init(src, nil \/* no error handler *\/, false \/* ignore comments *\/);\n\/\/\t\tfor {\n\/\/\t\t\tpos, tok, lit := s.Scan();\n\/\/\t\t\tif tok == Scanner.EOF {\n\/\/\t\t\t\treturn;\n\/\/\t\t\t}\n\/\/\t\t\tprintln(pos, token.TokenString(tok), string(lit));\n\/\/\t\t}\n\/\/\t}\n\/\/\npackage scanner\n\nimport (\n\t\"utf8\";\n\t\"unicode\";\n\t\"strconv\";\n\t\"token\";\n)\n\n\n\/\/ An implementation of an ErrorHandler must be provided to the Scanner.\n\/\/ If a syntax error is encountered, Error() is called with the exact\n\/\/ token position (the byte position of the token in the source) and the\n\/\/ error message.\n\/\/\ntype ErrorHandler interface {\n\tError(pos int, msg string);\n}\n\n\n\/\/ A Scanner holds the scanner's internal state while processing\n\/\/ a given text.  It can be allocated as part of another data\n\/\/ structure but must be initialized via Init() before use.\n\/\/ See also the package comment for a sample use.\n\/\/\ntype Scanner struct {\n\t\/\/ immutable state\n\tsrc []byte;  \/\/ source\n\terr ErrorHandler;  \/\/ error reporting\n\tscan_comments bool;  \/\/ if set, comments are reported as tokens\n\n\t\/\/ scanning state\n\tpos int;  \/\/ current reading position\n\tch int;  \/\/ one char look-ahead\n\tchpos int;  \/\/ position of ch\n}\n\n\nfunc isLetter(ch int) bool {\n\treturn\n\t\t'a' <= ch && ch <= 'z' ||\n\t\t'A' <= ch && ch <= 'Z' ||\n\t\tch == '_' ||\n\t\tch >= 0x80 && unicode.IsLetter(ch);\n}\n\n\nfunc digitVal(ch int) int {\n\tswitch {\n\tcase '0' <= ch && ch <= '9': return ch - '0';\n\tcase 'a' <= ch && ch <= 'f': return ch - 'a' + 10;\n\tcase 'A' <= ch && ch <= 'F': return ch - 'A' + 10;\n\t}\n\treturn 16;  \/\/ larger than any legal digit val\n}\n\n\n\/\/ Read the next Unicode char into S.ch.\n\/\/ S.ch < 0 means end-of-file.\nfunc (S *Scanner) next() {\n\tif S.pos < len(S.src) {\n\t\t\/\/ assume ASCII\n\t\tr, w := int(S.src[S.pos]), 1;\n\t\tif r >= 0x80 {\n\t\t\t\/\/ not ASCII\n\t\t\tr, w = utf8.DecodeRune(S.src[S.pos : len(S.src)]);\n\t\t}\n\t\tS.ch = r;\n\t\tS.chpos = S.pos;\n\t\tS.pos += w;\n\t} else {\n\t\tS.ch = -1;  \/\/ eof\n\t\tS.chpos = len(S.src);\n\t}\n}\n\n\n\/\/ Init() prepares the scanner S to tokenize the text src. Calls to Scan()\n\/\/ will use the error handler err if they encounter a syntax error. The boolean\n\/\/ scan_comments specifies whether newline characters and comments should be\n\/\/ recognized and returned by Scan as token.COMMENT. If scan_comments is false,\n\/\/ they are treated as white space and ignored.\n\/\/\nfunc (S *Scanner) Init(src []byte, err ErrorHandler, scan_comments bool) {\n\tS.src = src;\n\tS.err = err;\n\tS.scan_comments = scan_comments;\n\tS.next();\n}\n\n\nfunc charString(ch int) string {\n\ts := string(ch);\n\tswitch ch {\n\tcase '\\a': s = `\\a`;\n\tcase '\\b': s = `\\b`;\n\tcase '\\f': s = `\\f`;\n\tcase '\\n': s = `\\n`;\n\tcase '\\r': s = `\\r`;\n\tcase '\\t': s = `\\t`;\n\tcase '\\v': s = `\\v`;\n\tcase '\\\\': s = `\\\\`;\n\tcase '\\'': s = `\\'`;\n\t}\n\treturn \"'\" + s + \"' (U+\" + strconv.Itob(ch, 16) + \")\";\n}\n\n\nfunc (S *Scanner) error(pos int, msg string) {\n\tS.err.Error(pos, msg);\n}\n\n\nfunc (S *Scanner) expect(ch int) {\n\tif S.ch != ch {\n\t\tS.error(S.chpos, \"expected \" + charString(ch) + \", found \" + charString(S.ch));\n\t}\n\tS.next();  \/\/ always make progress\n}\n\n\nfunc (S *Scanner) skipWhitespace() {\n\tfor {\n\t\tswitch S.ch {\n\t\tcase '\\t', '\\r', ' ':\n\t\t\t\/\/ nothing to do\n\t\tcase '\\n':\n\t\t\tif S.scan_comments {\n\t\t\t\treturn;\n\t\t\t}\n\t\tdefault:\n\t\t\treturn;\n\t\t}\n\t\tS.next();\n\t}\n\tpanic(\"UNREACHABLE\");\n}\n\n\nfunc (S *Scanner) scanComment() []byte {\n\t\/\/ first '\/' already consumed\n\tpos := S.chpos - 1;\n\n\tif S.ch == '\/' {\n\t\t\/\/-style comment\n\t\tfor S.ch >= 0 {\n\t\t\tS.next();\n\t\t\tif S.ch == '\\n' {\n\t\t\t\t\/\/ '\\n' terminates comment but we do not include\n\t\t\t\t\/\/ it in the comment (otherwise we don't see the\n\t\t\t\t\/\/ start of a newline in skipWhitespace()).\n\t\t\t\treturn S.src[pos : S.chpos];\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\t\/*-style comment *\/\n\t\tS.expect('*');\n\t\tfor S.ch >= 0 {\n\t\t\tch := S.ch;\n\t\t\tS.next();\n\t\t\tif ch == '*' && S.ch == '\/' {\n\t\t\t\tS.next();\n\t\t\t\treturn S.src[pos : S.chpos];\n\t\t\t}\n\t\t}\n\t}\n\n\tS.error(pos, \"comment not terminated\");\n\treturn S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanIdentifier() (tok int, lit []byte) {\n\tpos := S.chpos;\n\tfor isLetter(S.ch) || digitVal(S.ch) < 10 {\n\t\tS.next();\n\t}\n\tlit = S.src[pos : S.chpos];\n\treturn token.Lookup(lit), lit;\n}\n\n\nfunc (S *Scanner) scanMantissa(base int) {\n\tfor digitVal(S.ch) < base {\n\t\tS.next();\n\t}\n}\n\n\nfunc (S *Scanner) scanNumber(seen_decimal_point bool) (tok int, lit []byte) {\n\tpos := S.chpos;\n\ttok = token.INT;\n\n\tif seen_decimal_point {\n\t\ttok = token.FLOAT;\n\t\tpos--;  \/\/ '.' is one byte\n\t\tS.scanMantissa(10);\n\t\tgoto exponent;\n\t}\n\n\tif S.ch == '0' {\n\t\t\/\/ int or float\n\t\tS.next();\n\t\tif S.ch == 'x' || S.ch == 'X' {\n\t\t\t\/\/ hexadecimal int\n\t\t\tS.next();\n\t\t\tS.scanMantissa(16);\n\t\t} else {\n\t\t\t\/\/ octal int or float\n\t\t\tS.scanMantissa(8);\n\t\t\tif digitVal(S.ch) < 10 || S.ch == '.' || S.ch == 'e' || S.ch == 'E' {\n\t\t\t\t\/\/ float\n\t\t\t\ttok = token.FLOAT;\n\t\t\t\tgoto mantissa;\n\t\t\t}\n\t\t\t\/\/ octal int\n\t\t}\n\t\tgoto exit;\n\t}\n\nmantissa:\n\t\/\/ decimal int or float\n\tS.scanMantissa(10);\n\n\tif S.ch == '.' {\n\t\t\/\/ float\n\t\ttok = token.FLOAT;\n\t\tS.next();\n\t\tS.scanMantissa(10)\n\t}\n\nexponent:\n\tif S.ch == 'e' || S.ch == 'E' {\n\t\t\/\/ float\n\t\ttok = token.FLOAT;\n\t\tS.next();\n\t\tif S.ch == '-' || S.ch == '+' {\n\t\t\tS.next();\n\t\t}\n\t\tS.scanMantissa(10);\n\t}\n\nexit:\n\treturn tok, S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanDigits(n int, base int) {\n\tfor digitVal(S.ch) < base {\n\t\tS.next();\n\t\tn--;\n\t}\n\tif n > 0 {\n\t\tS.error(S.chpos, \"illegal char escape\");\n\t}\n}\n\n\nfunc (S *Scanner) scanEscape(quote int) {\n\tch := S.ch;\n\tpos := S.chpos;\n\tS.next();\n\tswitch ch {\n\tcase 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\\\', quote:\n\t\t\/\/ nothing to do\n\tcase '0', '1', '2', '3', '4', '5', '6', '7':\n\t\tS.scanDigits(3 - 1, 8);  \/\/ 1 char read already\n\tcase 'x':\n\t\tS.scanDigits(2, 16);\n\tcase 'u':\n\t\tS.scanDigits(4, 16);\n\tcase 'U':\n\t\tS.scanDigits(8, 16);\n\tdefault:\n\t\tS.error(pos, \"illegal char escape\");\n\t}\n}\n\n\nfunc (S *Scanner) scanChar() []byte {\n\t\/\/ '\\'' already consumed\n\n\tpos := S.chpos - 1;\n\tch := S.ch;\n\tS.next();\n\tif ch == '\\\\' {\n\t\tS.scanEscape('\\'');\n\t}\n\n\tS.expect('\\'');\n\treturn S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanString() []byte {\n\t\/\/ '\"' already consumed\n\n\tpos := S.chpos - 1;\n\tfor S.ch != '\"' {\n\t\tch := S.ch;\n\t\tS.next();\n\t\tif ch == '\\n' || ch < 0 {\n\t\t\tS.error(pos, \"string not terminated\");\n\t\t\tbreak;\n\t\t}\n\t\tif ch == '\\\\' {\n\t\t\tS.scanEscape('\"');\n\t\t}\n\t}\n\n\tS.next();\n\treturn S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanRawString() []byte {\n\t\/\/ '`' already consumed\n\n\tpos := S.chpos - 1;\n\tfor S.ch != '`' {\n\t\tch := S.ch;\n\t\tS.next();\n\t\tif ch == '\\n' || ch < 0 {\n\t\t\tS.error(pos, \"string not terminated\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tS.next();\n\treturn S.src[pos : S.chpos];\n}\n\n\n\/\/ Helper functions for scanning multi-byte tokens such as >> += >>= .\n\/\/ Different routines recognize different length tok_i based on matches\n\/\/ of ch_i. If a token ends in '=', the result is tok1 or tok3\n\/\/ respectively. Otherwise, the result is tok0 if there was no other\n\/\/ matching character, or tok2 if the matching character was ch2.\n\nfunc (S *Scanner) switch2(tok0, tok1 int) int {\n\tif S.ch == '=' {\n\t\tS.next();\n\t\treturn tok1;\n\t}\n\treturn tok0;\n}\n\n\nfunc (S *Scanner) switch3(tok0, tok1, ch2, tok2 int) int {\n\tif S.ch == '=' {\n\t\tS.next();\n\t\treturn tok1;\n\t}\n\tif S.ch == ch2 {\n\t\tS.next();\n\t\treturn tok2;\n\t}\n\treturn tok0;\n}\n\n\nfunc (S *Scanner) switch4(tok0, tok1, ch2, tok2, tok3 int) int {\n\tif S.ch == '=' {\n\t\tS.next();\n\t\treturn tok1;\n\t}\n\tif S.ch == ch2 {\n\t\tS.next();\n\t\tif S.ch == '=' {\n\t\t\tS.next();\n\t\t\treturn tok3;\n\t\t}\n\t\treturn tok2;\n\t}\n\treturn tok0;\n}\n\n\n\/\/ Scan() scans the next token and returns the token byte position in the\n\/\/ source, its token value, and the corresponding literal text if the token\n\/\/ is an identifier, basic type literal (token.IsLiteral(tok) == true), or\n\/\/ comment.\n\/\/\nfunc (S *Scanner) Scan() (pos, tok int, lit []byte) {\nscan_again:\n\tS.skipWhitespace();\n\n\tpos, tok = S.chpos, token.ILLEGAL;\n\n\tswitch ch := S.ch; {\n\tcase isLetter(ch):\n\t\ttok, lit = S.scanIdentifier();\n\tcase digitVal(ch) < 10:\n\t\ttok, lit = S.scanNumber(false);\n\tdefault:\n\t\tS.next();  \/\/ always make progress\n\t\tswitch ch {\n\t\tcase -1  : tok = token.EOF;\n\t\tcase '\\n': tok, lit = token.COMMENT, []byte{'\\n'};\n\t\tcase '\"' : tok, lit = token.STRING, S.scanString();\n\t\tcase '\\'': tok, lit = token.CHAR, S.scanChar();\n\t\tcase '`' : tok, lit = token.STRING, S.scanRawString();\n\t\tcase ':' : tok = S.switch2(token.COLON, token.DEFINE);\n\t\tcase '.' :\n\t\t\tif digitVal(S.ch) < 10 {\n\t\t\t\ttok, lit = S.scanNumber(true);\n\t\t\t} else if S.ch == '.' {\n\t\t\t\tS.next();\n\t\t\t\tif S.ch == '.' {\n\t\t\t\t\tS.next();\n\t\t\t\t\ttok = token.ELLIPSIS;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttok = token.PERIOD;\n\t\t\t}\n\t\tcase ',': tok = token.COMMA;\n\t\tcase ';': tok = token.SEMICOLON;\n\t\tcase '(': tok = token.LPAREN;\n\t\tcase ')': tok = token.RPAREN;\n\t\tcase '[': tok = token.LBRACK;\n\t\tcase ']': tok = token.RBRACK;\n\t\tcase '{': tok = token.LBRACE;\n\t\tcase '}': tok = token.RBRACE;\n\t\tcase '+': tok = S.switch3(token.ADD, token.ADD_ASSIGN, '+', token.INC);\n\t\tcase '-': tok = S.switch3(token.SUB, token.SUB_ASSIGN, '-', token.DEC);\n\t\tcase '*': tok = S.switch2(token.MUL, token.MUL_ASSIGN);\n\t\tcase '\/':\n\t\t\tif S.ch == '\/' || S.ch == '*' {\n\t\t\t\ttok, lit = token.COMMENT, S.scanComment();\n\t\t\t\tif !S.scan_comments {\n\t\t\t\t\tgoto scan_again;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttok = S.switch2(token.QUO, token.QUO_ASSIGN);\n\t\t\t}\n\t\tcase '%': tok = S.switch2(token.REM, token.REM_ASSIGN);\n\t\tcase '^': tok = S.switch2(token.XOR, token.XOR_ASSIGN);\n\t\tcase '<':\n\t\t\tif S.ch == '-' {\n\t\t\t\tS.next();\n\t\t\t\ttok = token.ARROW;\n\t\t\t} else {\n\t\t\t\ttok = S.switch4(token.LSS, token.LEQ, '<', token.SHL, token.SHL_ASSIGN);\n\t\t\t}\n\t\tcase '>': tok = S.switch4(token.GTR, token.GEQ, '>', token.SHR, token.SHR_ASSIGN);\n\t\tcase '=': tok = S.switch2(token.ASSIGN, token.EQL);\n\t\tcase '!': tok = S.switch2(token.NOT, token.NEQ);\n\t\tcase '&': tok = S.switch3(token.AND, token.AND_ASSIGN, '&', token.LAND);\n\t\tcase '|': tok = S.switch3(token.OR, token.OR_ASSIGN, '|', token.LOR);\n\t\tdefault: S.error(pos, \"illegal character \" + charString(ch));\n\t\t}\n\t}\n\n\treturn pos, tok, lit;\n}\n<commit_msg>Fixing comment.<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ A scanner for Go source text. Takes a []byte as source which can\n\/\/ then be tokenized through repeated calls to the Scan() function.\n\/\/\n\/\/ Sample use:\n\/\/\n\/\/\timport \"token\"\n\/\/\timport \"scanner\"\n\/\/\n\/\/\tfunc tokenize(src []byte) {\n\/\/\t\tvar s scanner.Scanner;\n\/\/\t\ts.Init(src, nil \/* no error handler *\/, false \/* ignore comments *\/);\n\/\/\t\tfor {\n\/\/\t\t\tpos, tok, lit := s.Scan();\n\/\/\t\t\tif tok == Scanner.EOF {\n\/\/\t\t\t\treturn;\n\/\/\t\t\t}\n\/\/\t\t\tprintln(pos, token.TokenString(tok), string(lit));\n\/\/\t\t}\n\/\/\t}\n\/\/\npackage scanner\n\nimport (\n\t\"utf8\";\n\t\"unicode\";\n\t\"strconv\";\n\t\"token\";\n)\n\n\n\/\/ An implementation of an ErrorHandler must be provided to the Scanner.\n\/\/ If a syntax error is encountered, Error() is called with the exact\n\/\/ token position (the byte position of the token in the source) and the\n\/\/ error message.\n\/\/\ntype ErrorHandler interface {\n\tError(pos int, msg string);\n}\n\n\n\/\/ A Scanner holds the scanner's internal state while processing\n\/\/ a given text.  It can be allocated as part of another data\n\/\/ structure but must be initialized via Init() before use.\n\/\/ See also the package comment for a sample use.\n\/\/\ntype Scanner struct {\n\t\/\/ immutable state\n\tsrc []byte;  \/\/ source\n\terr ErrorHandler;  \/\/ error reporting\n\tscan_comments bool;  \/\/ if set, comments are reported as tokens\n\n\t\/\/ scanning state\n\tpos int;  \/\/ current reading position\n\tch int;  \/\/ one char look-ahead\n\tchpos int;  \/\/ position of ch\n}\n\n\nfunc isLetter(ch int) bool {\n\treturn\n\t\t'a' <= ch && ch <= 'z' ||\n\t\t'A' <= ch && ch <= 'Z' ||\n\t\tch == '_' ||\n\t\tch >= 0x80 && unicode.IsLetter(ch);\n}\n\n\nfunc digitVal(ch int) int {\n\tswitch {\n\tcase '0' <= ch && ch <= '9': return ch - '0';\n\tcase 'a' <= ch && ch <= 'f': return ch - 'a' + 10;\n\tcase 'A' <= ch && ch <= 'F': return ch - 'A' + 10;\n\t}\n\treturn 16;  \/\/ larger than any legal digit val\n}\n\n\n\/\/ Read the next Unicode char into S.ch.\n\/\/ S.ch < 0 means end-of-file.\nfunc (S *Scanner) next() {\n\tif S.pos < len(S.src) {\n\t\t\/\/ assume ASCII\n\t\tr, w := int(S.src[S.pos]), 1;\n\t\tif r >= 0x80 {\n\t\t\t\/\/ not ASCII\n\t\t\tr, w = utf8.DecodeRune(S.src[S.pos : len(S.src)]);\n\t\t}\n\t\tS.ch = r;\n\t\tS.chpos = S.pos;\n\t\tS.pos += w;\n\t} else {\n\t\tS.ch = -1;  \/\/ eof\n\t\tS.chpos = len(S.src);\n\t}\n}\n\n\n\/\/ Init() prepares the scanner S to tokenize the text src. Calls to Scan()\n\/\/ will use the error handler err if they encounter a syntax error. The boolean\n\/\/ scan_comments specifies whether newline characters and comments should be\n\/\/ recognized and returned by Scan as token.COMMENT. If scan_comments is false,\n\/\/ they are treated as white space and ignored.\n\/\/\nfunc (S *Scanner) Init(src []byte, err ErrorHandler, scan_comments bool) {\n\tS.src = src;\n\tS.err = err;\n\tS.scan_comments = scan_comments;\n\tS.next();\n}\n\n\nfunc charString(ch int) string {\n\ts := string(ch);\n\tswitch ch {\n\tcase '\\a': s = `\\a`;\n\tcase '\\b': s = `\\b`;\n\tcase '\\f': s = `\\f`;\n\tcase '\\n': s = `\\n`;\n\tcase '\\r': s = `\\r`;\n\tcase '\\t': s = `\\t`;\n\tcase '\\v': s = `\\v`;\n\tcase '\\\\': s = `\\\\`;\n\tcase '\\'': s = `\\'`;\n\t}\n\treturn \"'\" + s + \"' (U+\" + strconv.Itob(ch, 16) + \")\";\n}\n\n\nfunc (S *Scanner) error(pos int, msg string) {\n\tS.err.Error(pos, msg);\n}\n\n\nfunc (S *Scanner) expect(ch int) {\n\tif S.ch != ch {\n\t\tS.error(S.chpos, \"expected \" + charString(ch) + \", found \" + charString(S.ch));\n\t}\n\tS.next();  \/\/ always make progress\n}\n\n\nfunc (S *Scanner) skipWhitespace() {\n\tfor {\n\t\tswitch S.ch {\n\t\tcase '\\t', '\\r', ' ':\n\t\t\t\/\/ nothing to do\n\t\tcase '\\n':\n\t\t\tif S.scan_comments {\n\t\t\t\treturn;\n\t\t\t}\n\t\tdefault:\n\t\t\treturn;\n\t\t}\n\t\tS.next();\n\t}\n\tpanic(\"UNREACHABLE\");\n}\n\n\nfunc (S *Scanner) scanComment() []byte {\n\t\/\/ first '\/' already consumed\n\tpos := S.chpos - 1;\n\n\tif S.ch == '\/' {\n\t\t\/\/-style comment\n\t\tfor S.ch >= 0 {\n\t\t\tS.next();\n\t\t\tif S.ch == '\\n' {\n\t\t\t\t\/\/ '\\n' terminates comment but we do not include\n\t\t\t\t\/\/ it in the comment (otherwise we don't see the\n\t\t\t\t\/\/ start of a newline in skipWhitespace()).\n\t\t\t\treturn S.src[pos : S.chpos];\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\t\/*-style comment *\/\n\t\tS.expect('*');\n\t\tfor S.ch >= 0 {\n\t\t\tch := S.ch;\n\t\t\tS.next();\n\t\t\tif ch == '*' && S.ch == '\/' {\n\t\t\t\tS.next();\n\t\t\t\treturn S.src[pos : S.chpos];\n\t\t\t}\n\t\t}\n\t}\n\n\tS.error(pos, \"comment not terminated\");\n\treturn S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanIdentifier() (tok int, lit []byte) {\n\tpos := S.chpos;\n\tfor isLetter(S.ch) || digitVal(S.ch) < 10 {\n\t\tS.next();\n\t}\n\tlit = S.src[pos : S.chpos];\n\treturn token.Lookup(lit), lit;\n}\n\n\nfunc (S *Scanner) scanMantissa(base int) {\n\tfor digitVal(S.ch) < base {\n\t\tS.next();\n\t}\n}\n\n\nfunc (S *Scanner) scanNumber(seen_decimal_point bool) (tok int, lit []byte) {\n\tpos := S.chpos;\n\ttok = token.INT;\n\n\tif seen_decimal_point {\n\t\ttok = token.FLOAT;\n\t\tpos--;  \/\/ '.' is one byte\n\t\tS.scanMantissa(10);\n\t\tgoto exponent;\n\t}\n\n\tif S.ch == '0' {\n\t\t\/\/ int or float\n\t\tS.next();\n\t\tif S.ch == 'x' || S.ch == 'X' {\n\t\t\t\/\/ hexadecimal int\n\t\t\tS.next();\n\t\t\tS.scanMantissa(16);\n\t\t} else {\n\t\t\t\/\/ octal int or float\n\t\t\tS.scanMantissa(8);\n\t\t\tif digitVal(S.ch) < 10 || S.ch == '.' || S.ch == 'e' || S.ch == 'E' {\n\t\t\t\t\/\/ float\n\t\t\t\ttok = token.FLOAT;\n\t\t\t\tgoto mantissa;\n\t\t\t}\n\t\t\t\/\/ octal int\n\t\t}\n\t\tgoto exit;\n\t}\n\nmantissa:\n\t\/\/ decimal int or float\n\tS.scanMantissa(10);\n\n\tif S.ch == '.' {\n\t\t\/\/ float\n\t\ttok = token.FLOAT;\n\t\tS.next();\n\t\tS.scanMantissa(10)\n\t}\n\nexponent:\n\tif S.ch == 'e' || S.ch == 'E' {\n\t\t\/\/ float\n\t\ttok = token.FLOAT;\n\t\tS.next();\n\t\tif S.ch == '-' || S.ch == '+' {\n\t\t\tS.next();\n\t\t}\n\t\tS.scanMantissa(10);\n\t}\n\nexit:\n\treturn tok, S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanDigits(n int, base int) {\n\tfor digitVal(S.ch) < base {\n\t\tS.next();\n\t\tn--;\n\t}\n\tif n > 0 {\n\t\tS.error(S.chpos, \"illegal char escape\");\n\t}\n}\n\n\nfunc (S *Scanner) scanEscape(quote int) {\n\tch := S.ch;\n\tpos := S.chpos;\n\tS.next();\n\tswitch ch {\n\tcase 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\\\', quote:\n\t\t\/\/ nothing to do\n\tcase '0', '1', '2', '3', '4', '5', '6', '7':\n\t\tS.scanDigits(3 - 1, 8);  \/\/ 1 char read already\n\tcase 'x':\n\t\tS.scanDigits(2, 16);\n\tcase 'u':\n\t\tS.scanDigits(4, 16);\n\tcase 'U':\n\t\tS.scanDigits(8, 16);\n\tdefault:\n\t\tS.error(pos, \"illegal char escape\");\n\t}\n}\n\n\nfunc (S *Scanner) scanChar() []byte {\n\t\/\/ '\\'' already consumed\n\n\tpos := S.chpos - 1;\n\tch := S.ch;\n\tS.next();\n\tif ch == '\\\\' {\n\t\tS.scanEscape('\\'');\n\t}\n\n\tS.expect('\\'');\n\treturn S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanString() []byte {\n\t\/\/ '\"' already consumed\n\n\tpos := S.chpos - 1;\n\tfor S.ch != '\"' {\n\t\tch := S.ch;\n\t\tS.next();\n\t\tif ch == '\\n' || ch < 0 {\n\t\t\tS.error(pos, \"string not terminated\");\n\t\t\tbreak;\n\t\t}\n\t\tif ch == '\\\\' {\n\t\t\tS.scanEscape('\"');\n\t\t}\n\t}\n\n\tS.next();\n\treturn S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanRawString() []byte {\n\t\/\/ '`' already consumed\n\n\tpos := S.chpos - 1;\n\tfor S.ch != '`' {\n\t\tch := S.ch;\n\t\tS.next();\n\t\tif ch == '\\n' || ch < 0 {\n\t\t\tS.error(pos, \"string not terminated\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tS.next();\n\treturn S.src[pos : S.chpos];\n}\n\n\n\/\/ Helper functions for scanning multi-byte tokens such as >> += >>= .\n\/\/ Different routines recognize different length tok_i based on matches\n\/\/ of ch_i. If a token ends in '=', the result is tok1 or tok3\n\/\/ respectively. Otherwise, the result is tok0 if there was no other\n\/\/ matching character, or tok2 if the matching character was ch2.\n\nfunc (S *Scanner) switch2(tok0, tok1 int) int {\n\tif S.ch == '=' {\n\t\tS.next();\n\t\treturn tok1;\n\t}\n\treturn tok0;\n}\n\n\nfunc (S *Scanner) switch3(tok0, tok1, ch2, tok2 int) int {\n\tif S.ch == '=' {\n\t\tS.next();\n\t\treturn tok1;\n\t}\n\tif S.ch == ch2 {\n\t\tS.next();\n\t\treturn tok2;\n\t}\n\treturn tok0;\n}\n\n\nfunc (S *Scanner) switch4(tok0, tok1, ch2, tok2, tok3 int) int {\n\tif S.ch == '=' {\n\t\tS.next();\n\t\treturn tok1;\n\t}\n\tif S.ch == ch2 {\n\t\tS.next();\n\t\tif S.ch == '=' {\n\t\t\tS.next();\n\t\t\treturn tok3;\n\t\t}\n\t\treturn tok2;\n\t}\n\treturn tok0;\n}\n\n\n\/\/ Scan() scans the next token and returns the token byte position in the\n\/\/ source, its token value, and the corresponding literal text if the token\n\/\/ is an identifier, basic type literal (token.IsLiteral(tok) == true), or\n\/\/ comment.\n\/\/\nfunc (S *Scanner) Scan() (pos, tok int, lit []byte) {\nscan_again:\n\tS.skipWhitespace();\n\n\tpos, tok = S.chpos, token.ILLEGAL;\n\n\tswitch ch := S.ch; {\n\tcase isLetter(ch):\n\t\ttok, lit = S.scanIdentifier();\n\tcase digitVal(ch) < 10:\n\t\ttok, lit = S.scanNumber(false);\n\tdefault:\n\t\tS.next();  \/\/ always make progress\n\t\tswitch ch {\n\t\tcase -1  : tok = token.EOF;\n\t\tcase '\\n': tok, lit = token.COMMENT, []byte{'\\n'};\n\t\tcase '\"' : tok, lit = token.STRING, S.scanString();\n\t\tcase '\\'': tok, lit = token.CHAR, S.scanChar();\n\t\tcase '`' : tok, lit = token.STRING, S.scanRawString();\n\t\tcase ':' : tok = S.switch2(token.COLON, token.DEFINE);\n\t\tcase '.' :\n\t\t\tif digitVal(S.ch) < 10 {\n\t\t\t\ttok, lit = S.scanNumber(true);\n\t\t\t} else if S.ch == '.' {\n\t\t\t\tS.next();\n\t\t\t\tif S.ch == '.' {\n\t\t\t\t\tS.next();\n\t\t\t\t\ttok = token.ELLIPSIS;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttok = token.PERIOD;\n\t\t\t}\n\t\tcase ',': tok = token.COMMA;\n\t\tcase ';': tok = token.SEMICOLON;\n\t\tcase '(': tok = token.LPAREN;\n\t\tcase ')': tok = token.RPAREN;\n\t\tcase '[': tok = token.LBRACK;\n\t\tcase ']': tok = token.RBRACK;\n\t\tcase '{': tok = token.LBRACE;\n\t\tcase '}': tok = token.RBRACE;\n\t\tcase '+': tok = S.switch3(token.ADD, token.ADD_ASSIGN, '+', token.INC);\n\t\tcase '-': tok = S.switch3(token.SUB, token.SUB_ASSIGN, '-', token.DEC);\n\t\tcase '*': tok = S.switch2(token.MUL, token.MUL_ASSIGN);\n\t\tcase '\/':\n\t\t\tif S.ch == '\/' || S.ch == '*' {\n\t\t\t\ttok, lit = token.COMMENT, S.scanComment();\n\t\t\t\tif !S.scan_comments {\n\t\t\t\t\tgoto scan_again;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttok = S.switch2(token.QUO, token.QUO_ASSIGN);\n\t\t\t}\n\t\tcase '%': tok = S.switch2(token.REM, token.REM_ASSIGN);\n\t\tcase '^': tok = S.switch2(token.XOR, token.XOR_ASSIGN);\n\t\tcase '<':\n\t\t\tif S.ch == '-' {\n\t\t\t\tS.next();\n\t\t\t\ttok = token.ARROW;\n\t\t\t} else {\n\t\t\t\ttok = S.switch4(token.LSS, token.LEQ, '<', token.SHL, token.SHL_ASSIGN);\n\t\t\t}\n\t\tcase '>': tok = S.switch4(token.GTR, token.GEQ, '>', token.SHR, token.SHR_ASSIGN);\n\t\tcase '=': tok = S.switch2(token.ASSIGN, token.EQL);\n\t\tcase '!': tok = S.switch2(token.NOT, token.NEQ);\n\t\tcase '&': tok = S.switch3(token.AND, token.AND_ASSIGN, '&', token.LAND);\n\t\tcase '|': tok = S.switch3(token.OR, token.OR_ASSIGN, '|', token.LOR);\n\t\tdefault: S.error(pos, \"illegal character \" + charString(ch));\n\t\t}\n\t}\n\n\treturn pos, tok, lit;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage scanner\n\n\/\/ A Go scanner. Takes a []byte as source which can then be\n\/\/ tokenized through repeated calls to the Scan() function.\n\/\/\n\/\/ Sample use:\n\/\/\n\/\/\timport \"token\"\n\/\/\timport \"scanner\"\n\/\/\n\/\/\tfunc tokenize(src []byte) {\n\/\/\t\tvar s scanner.Scanner;\n\/\/\t\ts.Init(src, nil \/* no error handler *\/, false \/* ignore comments *\/);\n\/\/\t\tfor {\n\/\/\t\t\tpos, tok, lit := s.Scan();\n\/\/\t\t\tif tok == Scanner.EOF {\n\/\/\t\t\t\treturn;\n\/\/\t\t\t}\n\/\/\t\t\tprintln(pos, token.TokenString(tok), string(lit));\n\/\/\t\t}\n\/\/\t}\n\nimport (\n\t\"utf8\";\n\t\"unicode\";\n\t\"strconv\";\n\t\"token\";\n)\n\n\n\/\/ An implementation of an ErrorHandler must be provided to the Scanner.\n\/\/ If a syntax error is encountered, Error() is called with the exact\n\/\/ token position (the byte position of the token in the source) and the\n\/\/ error message.\n\ntype ErrorHandler interface {\n\tError(pos int, msg string);\n}\n\n\ntype Scanner struct {\n\t\/\/ immutable state\n\tsrc []byte;  \/\/ source\n\terr ErrorHandler;  \/\/ error reporting\n\tscan_comments bool;  \/\/ if set, comments are reported as tokens\n\n\t\/\/ scanning state\n\tpos int;  \/\/ current reading position\n\tch int;  \/\/ one char look-ahead\n\tchpos int;  \/\/ position of ch\n}\n\n\nfunc isLetter(ch int) bool {\n\treturn\n\t\t'a' <= ch && ch <= 'z' ||\n\t\t'A' <= ch && ch <= 'Z' ||\n\t\tch == '_' ||\n\t\tch >= 0x80 && unicode.IsLetter(ch);\n}\n\n\nfunc digitVal(ch int) int {\n\tswitch {\n\tcase '0' <= ch && ch <= '9': return ch - '0';\n\tcase 'a' <= ch && ch <= 'f': return ch - 'a' + 10;\n\tcase 'A' <= ch && ch <= 'F': return ch - 'A' + 10;\n\t}\n\treturn 16;  \/\/ larger than any legal digit val\n}\n\n\n\/\/ Read the next Unicode char into S.ch.\n\/\/ S.ch < 0 means end-of-file.\nfunc (S *Scanner) next() {\n\tif S.pos < len(S.src) {\n\t\t\/\/ assume ASCII\n\t\tr, w := int(S.src[S.pos]), 1;\n\t\tif r >= 0x80 {\n\t\t\t\/\/ not ASCII\n\t\t\tr, w = utf8.DecodeRune(S.src[S.pos : len(S.src)]);\n\t\t}\n\t\tS.ch = r;\n\t\tS.chpos = S.pos;\n\t\tS.pos += w;\n\t} else {\n\t\tS.ch = -1;  \/\/ eof\n\t\tS.chpos = len(S.src);\n\t}\n}\n\n\n\/\/ Initialize the scanner.\n\/\/\n\/\/ The error handler (err) is called when an illegal token is encountered.\n\/\/ If scan_comments is set to true, newline characters ('\\n') and comments\n\/\/ are recognized as token.COMMENT, otherwise they are treated as white\n\/\/ space and ignored.\n\nfunc (S *Scanner) Init(src []byte, err ErrorHandler, scan_comments bool) {\n\tS.src = src;\n\tS.err = err;\n\tS.scan_comments = scan_comments;\n\tS.next();\n}\n\n\nfunc charString(ch int) string {\n\ts := string(ch);\n\tswitch ch {\n\tcase '\\a': s = `\\a`;\n\tcase '\\b': s = `\\b`;\n\tcase '\\f': s = `\\f`;\n\tcase '\\n': s = `\\n`;\n\tcase '\\r': s = `\\r`;\n\tcase '\\t': s = `\\t`;\n\tcase '\\v': s = `\\v`;\n\tcase '\\\\': s = `\\\\`;\n\tcase '\\'': s = `\\'`;\n\t}\n\treturn \"'\" + s + \"' (U+\" + strconv.Itob(ch, 16) + \")\";\n}\n\n\nfunc (S *Scanner) error(pos int, msg string) {\n\tS.err.Error(pos, msg);\n}\n\n\nfunc (S *Scanner) expect(ch int) {\n\tif S.ch != ch {\n\t\tS.error(S.chpos, \"expected \" + charString(ch) + \", found \" + charString(S.ch));\n\t}\n\tS.next();  \/\/ always make progress\n}\n\n\nfunc (S *Scanner) skipWhitespace() {\n\tfor {\n\t\tswitch S.ch {\n\t\tcase '\\t', '\\r', ' ':\n\t\t\t\/\/ nothing to do\n\t\tcase '\\n':\n\t\t\tif S.scan_comments {\n\t\t\t\treturn;\n\t\t\t}\n\t\tdefault:\n\t\t\treturn;\n\t\t}\n\t\tS.next();\n\t}\n\tpanic(\"UNREACHABLE\");\n}\n\n\nfunc (S *Scanner) scanComment() []byte {\n\t\/\/ first '\/' already consumed\n\tpos := S.chpos - 1;\n\n\tif S.ch == '\/' {\n\t\t\/\/-style comment\n\t\tfor S.ch >= 0 {\n\t\t\tS.next();\n\t\t\tif S.ch == '\\n' {\n\t\t\t\t\/\/ '\\n' terminates comment but we do not include\n\t\t\t\t\/\/ it in the comment (otherwise we don't see the\n\t\t\t\t\/\/ start of a newline in skipWhitespace()).\n\t\t\t\treturn S.src[pos : S.chpos];\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\t\/*-style comment *\/\n\t\tS.expect('*');\n\t\tfor S.ch >= 0 {\n\t\t\tch := S.ch;\n\t\t\tS.next();\n\t\t\tif ch == '*' && S.ch == '\/' {\n\t\t\t\tS.next();\n\t\t\t\treturn S.src[pos : S.chpos];\n\t\t\t}\n\t\t}\n\t}\n\n\tS.error(pos, \"comment not terminated\");\n\treturn S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanIdentifier() (tok int, lit []byte) {\n\tpos := S.chpos;\n\tfor isLetter(S.ch) || digitVal(S.ch) < 10 {\n\t\tS.next();\n\t}\n\tlit = S.src[pos : S.chpos];\n\treturn token.Lookup(lit), lit;\n}\n\n\nfunc (S *Scanner) scanMantissa(base int) {\n\tfor digitVal(S.ch) < base {\n\t\tS.next();\n\t}\n}\n\n\nfunc (S *Scanner) scanNumber(seen_decimal_point bool) (tok int, lit []byte) {\n\tpos := S.chpos;\n\ttok = token.INT;\n\n\tif seen_decimal_point {\n\t\ttok = token.FLOAT;\n\t\tpos--;  \/\/ '.' is one byte\n\t\tS.scanMantissa(10);\n\t\tgoto exponent;\n\t}\n\n\tif S.ch == '0' {\n\t\t\/\/ int or float\n\t\tS.next();\n\t\tif S.ch == 'x' || S.ch == 'X' {\n\t\t\t\/\/ hexadecimal int\n\t\t\tS.next();\n\t\t\tS.scanMantissa(16);\n\t\t} else {\n\t\t\t\/\/ octal int or float\n\t\t\tS.scanMantissa(8);\n\t\t\tif digitVal(S.ch) < 10 || S.ch == '.' || S.ch == 'e' || S.ch == 'E' {\n\t\t\t\t\/\/ float\n\t\t\t\ttok = token.FLOAT;\n\t\t\t\tgoto mantissa;\n\t\t\t}\n\t\t\t\/\/ octal int\n\t\t}\n\t\tgoto exit;\n\t}\n\nmantissa:\n\t\/\/ decimal int or float\n\tS.scanMantissa(10);\n\n\tif S.ch == '.' {\n\t\t\/\/ float\n\t\ttok = token.FLOAT;\n\t\tS.next();\n\t\tS.scanMantissa(10)\n\t}\n\nexponent:\n\tif S.ch == 'e' || S.ch == 'E' {\n\t\t\/\/ float\n\t\ttok = token.FLOAT;\n\t\tS.next();\n\t\tif S.ch == '-' || S.ch == '+' {\n\t\t\tS.next();\n\t\t}\n\t\tS.scanMantissa(10);\n\t}\n\nexit:\n\treturn tok, S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanDigits(n int, base int) {\n\tfor digitVal(S.ch) < base {\n\t\tS.next();\n\t\tn--;\n\t}\n\tif n > 0 {\n\t\tS.error(S.chpos, \"illegal char escape\");\n\t}\n}\n\n\nfunc (S *Scanner) scanEscape(quote int) {\n\tch := S.ch;\n\tpos := S.chpos;\n\tS.next();\n\tswitch ch {\n\tcase 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\\\', quote:\n\t\t\/\/ nothing to do\n\tcase '0', '1', '2', '3', '4', '5', '6', '7':\n\t\tS.scanDigits(3 - 1, 8);  \/\/ 1 char read already\n\tcase 'x':\n\t\tS.scanDigits(2, 16);\n\tcase 'u':\n\t\tS.scanDigits(4, 16);\n\tcase 'U':\n\t\tS.scanDigits(8, 16);\n\tdefault:\n\t\tS.error(pos, \"illegal char escape\");\n\t}\n}\n\n\nfunc (S *Scanner) scanChar() []byte {\n\t\/\/ '\\'' already consumed\n\n\tpos := S.chpos - 1;\n\tch := S.ch;\n\tS.next();\n\tif ch == '\\\\' {\n\t\tS.scanEscape('\\'');\n\t}\n\n\tS.expect('\\'');\n\treturn S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanString() []byte {\n\t\/\/ '\"' already consumed\n\n\tpos := S.chpos - 1;\n\tfor S.ch != '\"' {\n\t\tch := S.ch;\n\t\tS.next();\n\t\tif ch == '\\n' || ch < 0 {\n\t\t\tS.error(pos, \"string not terminated\");\n\t\t\tbreak;\n\t\t}\n\t\tif ch == '\\\\' {\n\t\t\tS.scanEscape('\"');\n\t\t}\n\t}\n\n\tS.next();\n\treturn S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanRawString() []byte {\n\t\/\/ '`' already consumed\n\n\tpos := S.chpos - 1;\n\tfor S.ch != '`' {\n\t\tch := S.ch;\n\t\tS.next();\n\t\tif ch == '\\n' || ch < 0 {\n\t\t\tS.error(pos, \"string not terminated\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tS.next();\n\treturn S.src[pos : S.chpos];\n}\n\n\n\/\/ Helper functions for scanning multi-byte tokens such as >> += >>= .\n\/\/ Different routines recognize different length tok_i based on matches\n\/\/ of ch_i. If a token ends in '=', the result is tok1 or tok3\n\/\/ respectively. Otherwise, the result is tok0 if there was no other\n\/\/ matching character, or tok2 if the matching character was ch2.\n\nfunc (S *Scanner) switch2(tok0, tok1 int) int {\n\tif S.ch == '=' {\n\t\tS.next();\n\t\treturn tok1;\n\t}\n\treturn tok0;\n}\n\n\nfunc (S *Scanner) switch3(tok0, tok1, ch2, tok2 int) int {\n\tif S.ch == '=' {\n\t\tS.next();\n\t\treturn tok1;\n\t}\n\tif S.ch == ch2 {\n\t\tS.next();\n\t\treturn tok2;\n\t}\n\treturn tok0;\n}\n\n\nfunc (S *Scanner) switch4(tok0, tok1, ch2, tok2, tok3 int) int {\n\tif S.ch == '=' {\n\t\tS.next();\n\t\treturn tok1;\n\t}\n\tif S.ch == ch2 {\n\t\tS.next();\n\t\tif S.ch == '=' {\n\t\t\tS.next();\n\t\t\treturn tok3;\n\t\t}\n\t\treturn tok2;\n\t}\n\treturn tok0;\n}\n\n\n\/\/ Scans the next token. Returns the token byte position in the source,\n\/\/ its token value, and the corresponding literal text if the token is\n\/\/ an identifier or basic type literal (token.IsLiteral(tok) == true).\n\nfunc (S *Scanner) Scan() (pos, tok int, lit []byte) {\nscan_again:\n\tS.skipWhitespace();\n\n\tpos, tok = S.chpos, token.ILLEGAL;\n\n\tswitch ch := S.ch; {\n\tcase isLetter(ch):\n\t\ttok, lit = S.scanIdentifier();\n\tcase digitVal(ch) < 10:\n\t\ttok, lit = S.scanNumber(false);\n\tdefault:\n\t\tS.next();  \/\/ always make progress\n\t\tswitch ch {\n\t\tcase -1  : tok = token.EOF;\n\t\tcase '\\n': tok, lit = token.COMMENT, []byte{'\\n'};\n\t\tcase '\"' : tok, lit = token.STRING, S.scanString();\n\t\tcase '\\'': tok, lit = token.CHAR, S.scanChar();\n\t\tcase '`' : tok, lit = token.STRING, S.scanRawString();\n\t\tcase ':' : tok = S.switch2(token.COLON, token.DEFINE);\n\t\tcase '.' :\n\t\t\tif digitVal(S.ch) < 10 {\n\t\t\t\ttok, lit = S.scanNumber(true);\n\t\t\t} else if S.ch == '.' {\n\t\t\t\tS.next();\n\t\t\t\tif S.ch == '.' {\n\t\t\t\t\tS.next();\n\t\t\t\t\ttok = token.ELLIPSIS;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttok = token.PERIOD;\n\t\t\t}\n\t\tcase ',': tok = token.COMMA;\n\t\tcase ';': tok = token.SEMICOLON;\n\t\tcase '(': tok = token.LPAREN;\n\t\tcase ')': tok = token.RPAREN;\n\t\tcase '[': tok = token.LBRACK;\n\t\tcase ']': tok = token.RBRACK;\n\t\tcase '{': tok = token.LBRACE;\n\t\tcase '}': tok = token.RBRACE;\n\t\tcase '+': tok = S.switch3(token.ADD, token.ADD_ASSIGN, '+', token.INC);\n\t\tcase '-': tok = S.switch3(token.SUB, token.SUB_ASSIGN, '-', token.DEC);\n\t\tcase '*': tok = S.switch2(token.MUL, token.MUL_ASSIGN);\n\t\tcase '\/':\n\t\t\tif S.ch == '\/' || S.ch == '*' {\n\t\t\t\ttok, lit = token.COMMENT, S.scanComment();\n\t\t\t\tif !S.scan_comments {\n\t\t\t\t\tgoto scan_again;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttok = S.switch2(token.QUO, token.QUO_ASSIGN);\n\t\t\t}\n\t\tcase '%': tok = S.switch2(token.REM, token.REM_ASSIGN);\n\t\tcase '^': tok = S.switch2(token.XOR, token.XOR_ASSIGN);\n\t\tcase '<':\n\t\t\tif S.ch == '-' {\n\t\t\t\tS.next();\n\t\t\t\ttok = token.ARROW;\n\t\t\t} else {\n\t\t\t\ttok = S.switch4(token.LSS, token.LEQ, '<', token.SHL, token.SHL_ASSIGN);\n\t\t\t}\n\t\tcase '>': tok = S.switch4(token.GTR, token.GEQ, '>', token.SHR, token.SHR_ASSIGN);\n\t\tcase '=': tok = S.switch2(token.ASSIGN, token.EQL);\n\t\tcase '!': tok = S.switch2(token.NOT, token.NEQ);\n\t\tcase '&': tok = S.switch3(token.AND, token.AND_ASSIGN, '&', token.LAND);\n\t\tcase '|': tok = S.switch3(token.OR, token.OR_ASSIGN, '|', token.LOR);\n\t\tdefault: S.error(pos, \"illegal character \" + charString(ch));\n\t\t}\n\t}\n\n\treturn pos, tok, lit;\n}\n<commit_msg>scanner.go documentation<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ A Go scanner. Takes a []byte as source which can then be\n\/\/ tokenized through repeated calls to the Scan() function.\n\/\/\n\/\/ Sample use:\n\/\/\n\/\/\timport \"token\"\n\/\/\timport \"scanner\"\n\/\/\n\/\/\tfunc tokenize(src []byte) {\n\/\/\t\tvar s scanner.Scanner;\n\/\/\t\ts.Init(src, nil \/* no error handler *\/, false \/* ignore comments *\/);\n\/\/\t\tfor {\n\/\/\t\t\tpos, tok, lit := s.Scan();\n\/\/\t\t\tif tok == Scanner.EOF {\n\/\/\t\t\t\treturn;\n\/\/\t\t\t}\n\/\/\t\t\tprintln(pos, token.TokenString(tok), string(lit));\n\/\/\t\t}\n\/\/\t}\n\/\/\npackage scanner\n\nimport (\n\t\"utf8\";\n\t\"unicode\";\n\t\"strconv\";\n\t\"token\";\n)\n\n\n\/\/ An implementation of an ErrorHandler must be provided to the Scanner.\n\/\/ If a syntax error is encountered, Error() is called with the exact\n\/\/ token position (the byte position of the token in the source) and the\n\/\/ error message.\n\/\/\ntype ErrorHandler interface {\n\tError(pos int, msg string);\n}\n\n\n\/\/ A Scanner holds the scanner's internal state while processing\n\/\/ a given text.  It can be allocated as part of another data\n\/\/ structure but must be initialized via Init() before use.\n\/\/ See also the package comment for a sample use.\n\/\/\ntype Scanner struct {\n\t\/\/ immutable state\n\tsrc []byte;  \/\/ source\n\terr ErrorHandler;  \/\/ error reporting\n\tscan_comments bool;  \/\/ if set, comments are reported as tokens\n\n\t\/\/ scanning state\n\tpos int;  \/\/ current reading position\n\tch int;  \/\/ one char look-ahead\n\tchpos int;  \/\/ position of ch\n}\n\n\nfunc isLetter(ch int) bool {\n\treturn\n\t\t'a' <= ch && ch <= 'z' ||\n\t\t'A' <= ch && ch <= 'Z' ||\n\t\tch == '_' ||\n\t\tch >= 0x80 && unicode.IsLetter(ch);\n}\n\n\nfunc digitVal(ch int) int {\n\tswitch {\n\tcase '0' <= ch && ch <= '9': return ch - '0';\n\tcase 'a' <= ch && ch <= 'f': return ch - 'a' + 10;\n\tcase 'A' <= ch && ch <= 'F': return ch - 'A' + 10;\n\t}\n\treturn 16;  \/\/ larger than any legal digit val\n}\n\n\n\/\/ Read the next Unicode char into S.ch.\n\/\/ S.ch < 0 means end-of-file.\nfunc (S *Scanner) next() {\n\tif S.pos < len(S.src) {\n\t\t\/\/ assume ASCII\n\t\tr, w := int(S.src[S.pos]), 1;\n\t\tif r >= 0x80 {\n\t\t\t\/\/ not ASCII\n\t\t\tr, w = utf8.DecodeRune(S.src[S.pos : len(S.src)]);\n\t\t}\n\t\tS.ch = r;\n\t\tS.chpos = S.pos;\n\t\tS.pos += w;\n\t} else {\n\t\tS.ch = -1;  \/\/ eof\n\t\tS.chpos = len(S.src);\n\t}\n}\n\n\n\/\/ Init() prepares the scanner S to tokenize the text src. Calls to Scan()\n\/\/ will use the error handler err if they encounter a syntax error. The boolean\n\/\/ scan_comments specifies whether newline characters and comments should be\n\/\/ recognized and returned by Scan as token.COMMENT. If scan_comments is false,\n\/\/ they are treated as white space and ignored.\n\/\/\nfunc (S *Scanner) Init(src []byte, err ErrorHandler, scan_comments bool) {\n\tS.src = src;\n\tS.err = err;\n\tS.scan_comments = scan_comments;\n\tS.next();\n}\n\n\nfunc charString(ch int) string {\n\ts := string(ch);\n\tswitch ch {\n\tcase '\\a': s = `\\a`;\n\tcase '\\b': s = `\\b`;\n\tcase '\\f': s = `\\f`;\n\tcase '\\n': s = `\\n`;\n\tcase '\\r': s = `\\r`;\n\tcase '\\t': s = `\\t`;\n\tcase '\\v': s = `\\v`;\n\tcase '\\\\': s = `\\\\`;\n\tcase '\\'': s = `\\'`;\n\t}\n\treturn \"'\" + s + \"' (U+\" + strconv.Itob(ch, 16) + \")\";\n}\n\n\nfunc (S *Scanner) error(pos int, msg string) {\n\tS.err.Error(pos, msg);\n}\n\n\nfunc (S *Scanner) expect(ch int) {\n\tif S.ch != ch {\n\t\tS.error(S.chpos, \"expected \" + charString(ch) + \", found \" + charString(S.ch));\n\t}\n\tS.next();  \/\/ always make progress\n}\n\n\nfunc (S *Scanner) skipWhitespace() {\n\tfor {\n\t\tswitch S.ch {\n\t\tcase '\\t', '\\r', ' ':\n\t\t\t\/\/ nothing to do\n\t\tcase '\\n':\n\t\t\tif S.scan_comments {\n\t\t\t\treturn;\n\t\t\t}\n\t\tdefault:\n\t\t\treturn;\n\t\t}\n\t\tS.next();\n\t}\n\tpanic(\"UNREACHABLE\");\n}\n\n\nfunc (S *Scanner) scanComment() []byte {\n\t\/\/ first '\/' already consumed\n\tpos := S.chpos - 1;\n\n\tif S.ch == '\/' {\n\t\t\/\/-style comment\n\t\tfor S.ch >= 0 {\n\t\t\tS.next();\n\t\t\tif S.ch == '\\n' {\n\t\t\t\t\/\/ '\\n' terminates comment but we do not include\n\t\t\t\t\/\/ it in the comment (otherwise we don't see the\n\t\t\t\t\/\/ start of a newline in skipWhitespace()).\n\t\t\t\treturn S.src[pos : S.chpos];\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\t\/*-style comment *\/\n\t\tS.expect('*');\n\t\tfor S.ch >= 0 {\n\t\t\tch := S.ch;\n\t\t\tS.next();\n\t\t\tif ch == '*' && S.ch == '\/' {\n\t\t\t\tS.next();\n\t\t\t\treturn S.src[pos : S.chpos];\n\t\t\t}\n\t\t}\n\t}\n\n\tS.error(pos, \"comment not terminated\");\n\treturn S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanIdentifier() (tok int, lit []byte) {\n\tpos := S.chpos;\n\tfor isLetter(S.ch) || digitVal(S.ch) < 10 {\n\t\tS.next();\n\t}\n\tlit = S.src[pos : S.chpos];\n\treturn token.Lookup(lit), lit;\n}\n\n\nfunc (S *Scanner) scanMantissa(base int) {\n\tfor digitVal(S.ch) < base {\n\t\tS.next();\n\t}\n}\n\n\nfunc (S *Scanner) scanNumber(seen_decimal_point bool) (tok int, lit []byte) {\n\tpos := S.chpos;\n\ttok = token.INT;\n\n\tif seen_decimal_point {\n\t\ttok = token.FLOAT;\n\t\tpos--;  \/\/ '.' is one byte\n\t\tS.scanMantissa(10);\n\t\tgoto exponent;\n\t}\n\n\tif S.ch == '0' {\n\t\t\/\/ int or float\n\t\tS.next();\n\t\tif S.ch == 'x' || S.ch == 'X' {\n\t\t\t\/\/ hexadecimal int\n\t\t\tS.next();\n\t\t\tS.scanMantissa(16);\n\t\t} else {\n\t\t\t\/\/ octal int or float\n\t\t\tS.scanMantissa(8);\n\t\t\tif digitVal(S.ch) < 10 || S.ch == '.' || S.ch == 'e' || S.ch == 'E' {\n\t\t\t\t\/\/ float\n\t\t\t\ttok = token.FLOAT;\n\t\t\t\tgoto mantissa;\n\t\t\t}\n\t\t\t\/\/ octal int\n\t\t}\n\t\tgoto exit;\n\t}\n\nmantissa:\n\t\/\/ decimal int or float\n\tS.scanMantissa(10);\n\n\tif S.ch == '.' {\n\t\t\/\/ float\n\t\ttok = token.FLOAT;\n\t\tS.next();\n\t\tS.scanMantissa(10)\n\t}\n\nexponent:\n\tif S.ch == 'e' || S.ch == 'E' {\n\t\t\/\/ float\n\t\ttok = token.FLOAT;\n\t\tS.next();\n\t\tif S.ch == '-' || S.ch == '+' {\n\t\t\tS.next();\n\t\t}\n\t\tS.scanMantissa(10);\n\t}\n\nexit:\n\treturn tok, S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanDigits(n int, base int) {\n\tfor digitVal(S.ch) < base {\n\t\tS.next();\n\t\tn--;\n\t}\n\tif n > 0 {\n\t\tS.error(S.chpos, \"illegal char escape\");\n\t}\n}\n\n\nfunc (S *Scanner) scanEscape(quote int) {\n\tch := S.ch;\n\tpos := S.chpos;\n\tS.next();\n\tswitch ch {\n\tcase 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\\\', quote:\n\t\t\/\/ nothing to do\n\tcase '0', '1', '2', '3', '4', '5', '6', '7':\n\t\tS.scanDigits(3 - 1, 8);  \/\/ 1 char read already\n\tcase 'x':\n\t\tS.scanDigits(2, 16);\n\tcase 'u':\n\t\tS.scanDigits(4, 16);\n\tcase 'U':\n\t\tS.scanDigits(8, 16);\n\tdefault:\n\t\tS.error(pos, \"illegal char escape\");\n\t}\n}\n\n\nfunc (S *Scanner) scanChar() []byte {\n\t\/\/ '\\'' already consumed\n\n\tpos := S.chpos - 1;\n\tch := S.ch;\n\tS.next();\n\tif ch == '\\\\' {\n\t\tS.scanEscape('\\'');\n\t}\n\n\tS.expect('\\'');\n\treturn S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanString() []byte {\n\t\/\/ '\"' already consumed\n\n\tpos := S.chpos - 1;\n\tfor S.ch != '\"' {\n\t\tch := S.ch;\n\t\tS.next();\n\t\tif ch == '\\n' || ch < 0 {\n\t\t\tS.error(pos, \"string not terminated\");\n\t\t\tbreak;\n\t\t}\n\t\tif ch == '\\\\' {\n\t\t\tS.scanEscape('\"');\n\t\t}\n\t}\n\n\tS.next();\n\treturn S.src[pos : S.chpos];\n}\n\n\nfunc (S *Scanner) scanRawString() []byte {\n\t\/\/ '`' already consumed\n\n\tpos := S.chpos - 1;\n\tfor S.ch != '`' {\n\t\tch := S.ch;\n\t\tS.next();\n\t\tif ch == '\\n' || ch < 0 {\n\t\t\tS.error(pos, \"string not terminated\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tS.next();\n\treturn S.src[pos : S.chpos];\n}\n\n\n\/\/ Helper functions for scanning multi-byte tokens such as >> += >>= .\n\/\/ Different routines recognize different length tok_i based on matches\n\/\/ of ch_i. If a token ends in '=', the result is tok1 or tok3\n\/\/ respectively. Otherwise, the result is tok0 if there was no other\n\/\/ matching character, or tok2 if the matching character was ch2.\n\nfunc (S *Scanner) switch2(tok0, tok1 int) int {\n\tif S.ch == '=' {\n\t\tS.next();\n\t\treturn tok1;\n\t}\n\treturn tok0;\n}\n\n\nfunc (S *Scanner) switch3(tok0, tok1, ch2, tok2 int) int {\n\tif S.ch == '=' {\n\t\tS.next();\n\t\treturn tok1;\n\t}\n\tif S.ch == ch2 {\n\t\tS.next();\n\t\treturn tok2;\n\t}\n\treturn tok0;\n}\n\n\nfunc (S *Scanner) switch4(tok0, tok1, ch2, tok2, tok3 int) int {\n\tif S.ch == '=' {\n\t\tS.next();\n\t\treturn tok1;\n\t}\n\tif S.ch == ch2 {\n\t\tS.next();\n\t\tif S.ch == '=' {\n\t\t\tS.next();\n\t\t\treturn tok3;\n\t\t}\n\t\treturn tok2;\n\t}\n\treturn tok0;\n}\n\n\n\/\/ Scan() scans the next token and returns the token byte position in the\n\/\/ source, its token value, and the corresponding literal text if the token\n\/\/ is an identifier, basic type literal (token.IsLiteral(tok) == true), or\n\/\/ comment.\n\/\/\nfunc (S *Scanner) Scan() (pos, tok int, lit []byte) {\nscan_again:\n\tS.skipWhitespace();\n\n\tpos, tok = S.chpos, token.ILLEGAL;\n\n\tswitch ch := S.ch; {\n\tcase isLetter(ch):\n\t\ttok, lit = S.scanIdentifier();\n\tcase digitVal(ch) < 10:\n\t\ttok, lit = S.scanNumber(false);\n\tdefault:\n\t\tS.next();  \/\/ always make progress\n\t\tswitch ch {\n\t\tcase -1  : tok = token.EOF;\n\t\tcase '\\n': tok, lit = token.COMMENT, []byte{'\\n'};\n\t\tcase '\"' : tok, lit = token.STRING, S.scanString();\n\t\tcase '\\'': tok, lit = token.CHAR, S.scanChar();\n\t\tcase '`' : tok, lit = token.STRING, S.scanRawString();\n\t\tcase ':' : tok = S.switch2(token.COLON, token.DEFINE);\n\t\tcase '.' :\n\t\t\tif digitVal(S.ch) < 10 {\n\t\t\t\ttok, lit = S.scanNumber(true);\n\t\t\t} else if S.ch == '.' {\n\t\t\t\tS.next();\n\t\t\t\tif S.ch == '.' {\n\t\t\t\t\tS.next();\n\t\t\t\t\ttok = token.ELLIPSIS;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttok = token.PERIOD;\n\t\t\t}\n\t\tcase ',': tok = token.COMMA;\n\t\tcase ';': tok = token.SEMICOLON;\n\t\tcase '(': tok = token.LPAREN;\n\t\tcase ')': tok = token.RPAREN;\n\t\tcase '[': tok = token.LBRACK;\n\t\tcase ']': tok = token.RBRACK;\n\t\tcase '{': tok = token.LBRACE;\n\t\tcase '}': tok = token.RBRACE;\n\t\tcase '+': tok = S.switch3(token.ADD, token.ADD_ASSIGN, '+', token.INC);\n\t\tcase '-': tok = S.switch3(token.SUB, token.SUB_ASSIGN, '-', token.DEC);\n\t\tcase '*': tok = S.switch2(token.MUL, token.MUL_ASSIGN);\n\t\tcase '\/':\n\t\t\tif S.ch == '\/' || S.ch == '*' {\n\t\t\t\ttok, lit = token.COMMENT, S.scanComment();\n\t\t\t\tif !S.scan_comments {\n\t\t\t\t\tgoto scan_again;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ttok = S.switch2(token.QUO, token.QUO_ASSIGN);\n\t\t\t}\n\t\tcase '%': tok = S.switch2(token.REM, token.REM_ASSIGN);\n\t\tcase '^': tok = S.switch2(token.XOR, token.XOR_ASSIGN);\n\t\tcase '<':\n\t\t\tif S.ch == '-' {\n\t\t\t\tS.next();\n\t\t\t\ttok = token.ARROW;\n\t\t\t} else {\n\t\t\t\ttok = S.switch4(token.LSS, token.LEQ, '<', token.SHL, token.SHL_ASSIGN);\n\t\t\t}\n\t\tcase '>': tok = S.switch4(token.GTR, token.GEQ, '>', token.SHR, token.SHR_ASSIGN);\n\t\tcase '=': tok = S.switch2(token.ASSIGN, token.EQL);\n\t\tcase '!': tok = S.switch2(token.NOT, token.NEQ);\n\t\tcase '&': tok = S.switch3(token.AND, token.AND_ASSIGN, '&', token.LAND);\n\t\tcase '|': tok = S.switch3(token.OR, token.OR_ASSIGN, '|', token.LOR);\n\t\tdefault: S.error(pos, \"illegal character \" + charString(ch));\n\t\t}\n\t}\n\n\treturn pos, tok, lit;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011, 2012, 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage cloudinit_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\tgc \"launchpad.net\/gocheck\"\n\n\t\"launchpad.net\/juju-core\/cloudinit\"\n\t\"launchpad.net\/juju-core\/testing\/testbase\"\n\tsshtesting \"launchpad.net\/juju-core\/utils\/ssh\/testing\"\n)\n\n\/\/ TODO integration tests, but how?\n\ntype S struct {\n\ttestbase.LoggingSuite\n}\n\nvar _ = gc.Suite(S{})\n\nfunc Test1(t *testing.T) {\n\tgc.TestingT(t)\n}\n\nvar ctests = []struct {\n\tname      string\n\texpect    string\n\tsetOption func(cfg *cloudinit.Config)\n}{\n\t{\n\t\t\"User\",\n\t\t\"user: me\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetUser(\"me\")\n\t\t},\n\t},\n\t{\n\t\t\"AptUpgrade\",\n\t\t\"apt_upgrade: true\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetAptUpgrade(true)\n\t\t},\n\t},\n\t{\n\t\t\"AptUpdate\",\n\t\t\"apt_update: true\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetAptUpdate(true)\n\t\t},\n\t},\n\t{\n\t\t\"AptProxy\",\n\t\t\"apt_proxy: http:\/\/foo.com\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetAptProxy(\"http:\/\/foo.com\")\n\t\t},\n\t},\n\t{\n\t\t\"AptMirror\",\n\t\t\"apt_mirror: http:\/\/foo.com\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetAptMirror(\"http:\/\/foo.com\")\n\t\t},\n\t},\n\t{\n\t\t\"AptPreserveSourcesList\",\n\t\t\"apt_mirror: true\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetAptPreserveSourcesList(true)\n\t\t},\n\t},\n\t{\n\t\t\"DebconfSelections\",\n\t\t\"debconf_selections: '# Force debconf priority to critical.\\n\\n  debconf debconf\/priority select critical\\n\\n'\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetDebconfSelections(\"# Force debconf priority to critical.\\ndebconf debconf\/priority select critical\\n\")\n\t\t},\n\t},\n\t{\n\t\t\"DisableEC2Metadata\",\n\t\t\"disable_ec2_metadata: true\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetDisableEC2Metadata(true)\n\t\t},\n\t},\n\t{\n\t\t\"FinalMessage\",\n\t\t\"final_message: goodbye\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetFinalMessage(\"goodbye\")\n\t\t},\n\t},\n\t{\n\t\t\"Locale\",\n\t\t\"locale: en_us\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetLocale(\"en_us\")\n\t\t},\n\t},\n\t{\n\t\t\"DisableRoot\",\n\t\t\"disable_root: false\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetDisableRoot(false)\n\t\t},\n\t},\n\t{\n\t\t\"SSHAuthorizedKeys\",\n\t\tfmt.Sprintf(\n\t\t\t\"ssh_authorized_keys:\\n- %s Juju:user@host\\n- %s Juju:another@host\\n\",\n\t\t\tsshtesting.ValidKeyOne.Key, sshtesting.ValidKeyTwo.Key),\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddSSHAuthorizedKeys(sshtesting.ValidKeyOne.Key + \" Juju:user@host\")\n\t\t\tcfg.AddSSHAuthorizedKeys(sshtesting.ValidKeyTwo.Key + \" another@host\")\n\t\t},\n\t},\n\t{\n\t\t\"SSHAuthorizedKeys\",\n\t\tfmt.Sprintf(\n\t\t\t\"ssh_authorized_keys:\\n- %s Juju:sshkey\\n- %s Juju:user@host\\n- %s Juju:another@host\\n\",\n\t\t\tsshtesting.ValidKeyOne.Key, sshtesting.ValidKeyTwo.Key, sshtesting.ValidKeyThree.Key),\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddSSHAuthorizedKeys(\"#command\\n\" + sshtesting.ValidKeyOne.Key)\n\t\t\tcfg.AddSSHAuthorizedKeys(\n\t\t\t\tsshtesting.ValidKeyTwo.Key + \" user@host\\n# comment\\n\\n\" +\n\t\t\t\t\tsshtesting.ValidKeyThree.Key + \" another@host\")\n\t\t\tcfg.AddSSHAuthorizedKeys(\"\")\n\t\t},\n\t},\n\t{\n\t\t\"SSHKeys RSAPrivate\",\n\t\t\"ssh_keys:\\n  rsa_private: key1data\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddSSHKey(cloudinit.RSAPrivate, \"key1data\")\n\t\t},\n\t},\n\t{\n\t\t\"SSHKeys RSAPublic\",\n\t\t\"ssh_keys:\\n  rsa_public: key2data\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddSSHKey(cloudinit.RSAPublic, \"key2data\")\n\t\t},\n\t},\n\t{\n\t\t\"SSHKeys DSAPublic\",\n\t\t\"ssh_keys:\\n  dsa_public: key1data\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddSSHKey(cloudinit.DSAPublic, \"key1data\")\n\t\t},\n\t},\n\t{\n\t\t\"SSHKeys DSAPrivate\",\n\t\t\"ssh_keys:\\n  dsa_private: key2data\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddSSHKey(cloudinit.DSAPrivate, \"key2data\")\n\t\t},\n\t},\n\t{\n\t\t\"Output\",\n\t\t\"output:\\n  all:\\n  - '>foo'\\n  - '|bar'\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetOutput(\"all\", \">foo\", \"|bar\")\n\t\t},\n\t},\n\t{\n\t\t\"Output\",\n\t\t\"output:\\n  all: '>foo'\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetOutput(cloudinit.OutAll, \">foo\", \"\")\n\t\t},\n\t},\n\t{\n\t\t\"AptSources\",\n\t\t\"apt_sources:\\n- source: keyName\\n  key: someKey\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddAptSource(\"keyName\", \"someKey\")\n\t\t},\n\t},\n\t{\n\t\t\"Packages\",\n\t\t\"packages:\\n- juju\\n- ubuntu\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddPackage(\"juju\")\n\t\t\tcfg.AddPackage(\"ubuntu\")\n\t\t},\n\t},\n\t{\n\t\t\"BootCmd\",\n\t\t\"bootcmd:\\n- ls > \/dev\\n- - ls\\n  - '>with space'\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddBootCmd(\"ls > \/dev\")\n\t\t\tcfg.AddBootCmdArgs(\"ls\", \">with space\")\n\t\t},\n\t},\n\t{\n\t\t\"Mounts\",\n\t\t\"mounts:\\n- - x\\n  - \\\"y\\\"\\n- - z\\n  - w\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddMount(\"x\", \"y\")\n\t\t\tcfg.AddMount(\"z\", \"w\")\n\t\t},\n\t},\n\t{\n\t\t\"Attr\",\n\t\t\"arbitraryAttr: someValue\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetAttr(\"arbitraryAttr\", \"someValue\")\n\t\t},\n\t},\n\t{\n\t\t\"RunCmd\",\n\t\t\"runcmd:\\n- ifconfig\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddRunCmd(\"ifconfig\")\n\t\t},\n\t},\n\t{\n\t\t\"AddScripts\",\n\t\t\"runcmd:\\n- echo 'Hello World'\\n- ifconfig\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddScripts(\n\t\t\t\t\"echo 'Hello World'\",\n\t\t\t\t\"ifconfig\",\n\t\t\t)\n\t\t},\n\t},\n\t{\n\t\t\"AddFile\",\n\t\taddFileExpected,\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddFile(\n\t\t\t\t\"\/etc\/apt\/apt.conf.d\/99proxy\",\n\t\t\t\t`\"Acquire::http::Proxy \"http:\/\/10.0.3.1:3142\";`,\n\t\t\t\t0644,\n\t\t\t)\n\t\t},\n\t},\n}\n\nconst (\n\theader          = \"#cloud-config\\n\"\n\taddFileExpected = `runcmd:\n- install -m 644 \/dev\/null '\/etc\/apt\/apt.conf.d\/99proxy'\n- printf '%s\\n' '\"Acquire::http::Proxy \"http:\/\/10.0.3.1:3142\";' > '\/etc\/apt\/apt.conf.d\/99proxy'\n`\n)\n\nfunc (S) TestOutput(c *gc.C) {\n\tfor _, t := range ctests {\n\t\tcfg := cloudinit.New()\n\t\tt.setOption(cfg)\n\t\tdata, err := cfg.Render()\n\t\tc.Assert(err, gc.IsNil)\n\t\tc.Assert(data, gc.NotNil)\n\t\tc.Assert(string(data), gc.Equals, header+t.expect, gc.Commentf(\"test %q output differs\", t.name))\n\t}\n}\n\nfunc (S) TestRunCmds(c *gc.C) {\n\tcfg := cloudinit.New()\n\tc.Assert(cfg.RunCmds(), gc.HasLen, 0)\n\tcfg.AddScripts(\"a\", \"b\")\n\tcfg.AddRunCmdArgs(\"c\", \"d\")\n\tcfg.AddRunCmd(\"e\")\n\tc.Assert(cfg.RunCmds(), gc.DeepEquals, []interface{}{\n\t\t\t\"a\", \"b\", []string{\"c\", \"d\"}, \"e\",\n\t\t})\n}\n\nfunc (S) TestPackages(c *gc.C) {\n\tcfg := cloudinit.New()\n\tc.Assert(cfg.Packages(), gc.HasLen, 0)\n\tcfg.AddPackage(\"a b c\")\n\tcfg.AddPackage(\"d!\")\n\tc.Assert(cfg.Packages(), gc.DeepEquals, []string{\"a b c\", \"d!\"})\n}\n\nfunc (S) TestSetOutput(c *gc.C) {\n\ttype test struct {\n\t\tkind   cloudinit.OutputKind\n\t\tstdout string\n\t\tstderr string\n\t}\n\ttests := []test{{\n\t\tcloudinit.OutAll, \"a\", \"\",\n\t}, {\n\t\tcloudinit.OutAll, \"\", \"b\",\n\t}, {\n\t\tcloudinit.OutInit, \"a\", \"b\",\n\t}, {\n\t\tcloudinit.OutAll, \"a\", \"b\",\n\t}, {\n\t\tcloudinit.OutAll, \"\", \"\",\n\t}}\n\n\tcfg := cloudinit.New()\n\tstdout, stderr := cfg.Output(cloudinit.OutAll)\n\tc.Assert(stdout, gc.Equals, \"\")\n\tc.Assert(stderr, gc.Equals, \"\")\n\tfor i, t := range tests {\n\t\tc.Logf(\"test %d: %+v\", i, t)\n\t\tcfg.SetOutput(t.kind, t.stdout, t.stderr)\n\t\tstdout, stderr = cfg.Output(t.kind)\n\t\tc.Assert(stdout, gc.Equals, t.stdout)\n\t\tc.Assert(stderr, gc.Equals, t.stderr)\n\t}\n}\n\n\/\/#cloud-config\n\/\/packages:\n\/\/- juju\n\/\/- ubuntu\nfunc ExampleConfig() {\n\tcfg := cloudinit.New()\n\tcfg.AddPackage(\"juju\")\n\tcfg.AddPackage(\"ubuntu\")\n\tdata, err := cfg.Render()\n\tif err != nil {\n\t\tfmt.Printf(\"render error: %v\", err)\n\t\treturn\n\t}\n\tfmt.Printf(\"%s\", data)\n}\n<commit_msg>go fmt<commit_after>\/\/ Copyright 2011, 2012, 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage cloudinit_test\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\tgc \"launchpad.net\/gocheck\"\n\n\t\"launchpad.net\/juju-core\/cloudinit\"\n\t\"launchpad.net\/juju-core\/testing\/testbase\"\n\tsshtesting \"launchpad.net\/juju-core\/utils\/ssh\/testing\"\n)\n\n\/\/ TODO integration tests, but how?\n\ntype S struct {\n\ttestbase.LoggingSuite\n}\n\nvar _ = gc.Suite(S{})\n\nfunc Test1(t *testing.T) {\n\tgc.TestingT(t)\n}\n\nvar ctests = []struct {\n\tname      string\n\texpect    string\n\tsetOption func(cfg *cloudinit.Config)\n}{\n\t{\n\t\t\"User\",\n\t\t\"user: me\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetUser(\"me\")\n\t\t},\n\t},\n\t{\n\t\t\"AptUpgrade\",\n\t\t\"apt_upgrade: true\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetAptUpgrade(true)\n\t\t},\n\t},\n\t{\n\t\t\"AptUpdate\",\n\t\t\"apt_update: true\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetAptUpdate(true)\n\t\t},\n\t},\n\t{\n\t\t\"AptProxy\",\n\t\t\"apt_proxy: http:\/\/foo.com\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetAptProxy(\"http:\/\/foo.com\")\n\t\t},\n\t},\n\t{\n\t\t\"AptMirror\",\n\t\t\"apt_mirror: http:\/\/foo.com\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetAptMirror(\"http:\/\/foo.com\")\n\t\t},\n\t},\n\t{\n\t\t\"AptPreserveSourcesList\",\n\t\t\"apt_mirror: true\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetAptPreserveSourcesList(true)\n\t\t},\n\t},\n\t{\n\t\t\"DebconfSelections\",\n\t\t\"debconf_selections: '# Force debconf priority to critical.\\n\\n  debconf debconf\/priority select critical\\n\\n'\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetDebconfSelections(\"# Force debconf priority to critical.\\ndebconf debconf\/priority select critical\\n\")\n\t\t},\n\t},\n\t{\n\t\t\"DisableEC2Metadata\",\n\t\t\"disable_ec2_metadata: true\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetDisableEC2Metadata(true)\n\t\t},\n\t},\n\t{\n\t\t\"FinalMessage\",\n\t\t\"final_message: goodbye\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetFinalMessage(\"goodbye\")\n\t\t},\n\t},\n\t{\n\t\t\"Locale\",\n\t\t\"locale: en_us\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetLocale(\"en_us\")\n\t\t},\n\t},\n\t{\n\t\t\"DisableRoot\",\n\t\t\"disable_root: false\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetDisableRoot(false)\n\t\t},\n\t},\n\t{\n\t\t\"SSHAuthorizedKeys\",\n\t\tfmt.Sprintf(\n\t\t\t\"ssh_authorized_keys:\\n- %s Juju:user@host\\n- %s Juju:another@host\\n\",\n\t\t\tsshtesting.ValidKeyOne.Key, sshtesting.ValidKeyTwo.Key),\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddSSHAuthorizedKeys(sshtesting.ValidKeyOne.Key + \" Juju:user@host\")\n\t\t\tcfg.AddSSHAuthorizedKeys(sshtesting.ValidKeyTwo.Key + \" another@host\")\n\t\t},\n\t},\n\t{\n\t\t\"SSHAuthorizedKeys\",\n\t\tfmt.Sprintf(\n\t\t\t\"ssh_authorized_keys:\\n- %s Juju:sshkey\\n- %s Juju:user@host\\n- %s Juju:another@host\\n\",\n\t\t\tsshtesting.ValidKeyOne.Key, sshtesting.ValidKeyTwo.Key, sshtesting.ValidKeyThree.Key),\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddSSHAuthorizedKeys(\"#command\\n\" + sshtesting.ValidKeyOne.Key)\n\t\t\tcfg.AddSSHAuthorizedKeys(\n\t\t\t\tsshtesting.ValidKeyTwo.Key + \" user@host\\n# comment\\n\\n\" +\n\t\t\t\t\tsshtesting.ValidKeyThree.Key + \" another@host\")\n\t\t\tcfg.AddSSHAuthorizedKeys(\"\")\n\t\t},\n\t},\n\t{\n\t\t\"SSHKeys RSAPrivate\",\n\t\t\"ssh_keys:\\n  rsa_private: key1data\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddSSHKey(cloudinit.RSAPrivate, \"key1data\")\n\t\t},\n\t},\n\t{\n\t\t\"SSHKeys RSAPublic\",\n\t\t\"ssh_keys:\\n  rsa_public: key2data\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddSSHKey(cloudinit.RSAPublic, \"key2data\")\n\t\t},\n\t},\n\t{\n\t\t\"SSHKeys DSAPublic\",\n\t\t\"ssh_keys:\\n  dsa_public: key1data\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddSSHKey(cloudinit.DSAPublic, \"key1data\")\n\t\t},\n\t},\n\t{\n\t\t\"SSHKeys DSAPrivate\",\n\t\t\"ssh_keys:\\n  dsa_private: key2data\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddSSHKey(cloudinit.DSAPrivate, \"key2data\")\n\t\t},\n\t},\n\t{\n\t\t\"Output\",\n\t\t\"output:\\n  all:\\n  - '>foo'\\n  - '|bar'\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetOutput(\"all\", \">foo\", \"|bar\")\n\t\t},\n\t},\n\t{\n\t\t\"Output\",\n\t\t\"output:\\n  all: '>foo'\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetOutput(cloudinit.OutAll, \">foo\", \"\")\n\t\t},\n\t},\n\t{\n\t\t\"AptSources\",\n\t\t\"apt_sources:\\n- source: keyName\\n  key: someKey\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddAptSource(\"keyName\", \"someKey\")\n\t\t},\n\t},\n\t{\n\t\t\"Packages\",\n\t\t\"packages:\\n- juju\\n- ubuntu\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddPackage(\"juju\")\n\t\t\tcfg.AddPackage(\"ubuntu\")\n\t\t},\n\t},\n\t{\n\t\t\"BootCmd\",\n\t\t\"bootcmd:\\n- ls > \/dev\\n- - ls\\n  - '>with space'\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddBootCmd(\"ls > \/dev\")\n\t\t\tcfg.AddBootCmdArgs(\"ls\", \">with space\")\n\t\t},\n\t},\n\t{\n\t\t\"Mounts\",\n\t\t\"mounts:\\n- - x\\n  - \\\"y\\\"\\n- - z\\n  - w\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddMount(\"x\", \"y\")\n\t\t\tcfg.AddMount(\"z\", \"w\")\n\t\t},\n\t},\n\t{\n\t\t\"Attr\",\n\t\t\"arbitraryAttr: someValue\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.SetAttr(\"arbitraryAttr\", \"someValue\")\n\t\t},\n\t},\n\t{\n\t\t\"RunCmd\",\n\t\t\"runcmd:\\n- ifconfig\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddRunCmd(\"ifconfig\")\n\t\t},\n\t},\n\t{\n\t\t\"AddScripts\",\n\t\t\"runcmd:\\n- echo 'Hello World'\\n- ifconfig\\n\",\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddScripts(\n\t\t\t\t\"echo 'Hello World'\",\n\t\t\t\t\"ifconfig\",\n\t\t\t)\n\t\t},\n\t},\n\t{\n\t\t\"AddFile\",\n\t\taddFileExpected,\n\t\tfunc(cfg *cloudinit.Config) {\n\t\t\tcfg.AddFile(\n\t\t\t\t\"\/etc\/apt\/apt.conf.d\/99proxy\",\n\t\t\t\t`\"Acquire::http::Proxy \"http:\/\/10.0.3.1:3142\";`,\n\t\t\t\t0644,\n\t\t\t)\n\t\t},\n\t},\n}\n\nconst (\n\theader          = \"#cloud-config\\n\"\n\taddFileExpected = `runcmd:\n- install -m 644 \/dev\/null '\/etc\/apt\/apt.conf.d\/99proxy'\n- printf '%s\\n' '\"Acquire::http::Proxy \"http:\/\/10.0.3.1:3142\";' > '\/etc\/apt\/apt.conf.d\/99proxy'\n`\n)\n\nfunc (S) TestOutput(c *gc.C) {\n\tfor _, t := range ctests {\n\t\tcfg := cloudinit.New()\n\t\tt.setOption(cfg)\n\t\tdata, err := cfg.Render()\n\t\tc.Assert(err, gc.IsNil)\n\t\tc.Assert(data, gc.NotNil)\n\t\tc.Assert(string(data), gc.Equals, header+t.expect, gc.Commentf(\"test %q output differs\", t.name))\n\t}\n}\n\nfunc (S) TestRunCmds(c *gc.C) {\n\tcfg := cloudinit.New()\n\tc.Assert(cfg.RunCmds(), gc.HasLen, 0)\n\tcfg.AddScripts(\"a\", \"b\")\n\tcfg.AddRunCmdArgs(\"c\", \"d\")\n\tcfg.AddRunCmd(\"e\")\n\tc.Assert(cfg.RunCmds(), gc.DeepEquals, []interface{}{\n\t\t\"a\", \"b\", []string{\"c\", \"d\"}, \"e\",\n\t})\n}\n\nfunc (S) TestPackages(c *gc.C) {\n\tcfg := cloudinit.New()\n\tc.Assert(cfg.Packages(), gc.HasLen, 0)\n\tcfg.AddPackage(\"a b c\")\n\tcfg.AddPackage(\"d!\")\n\tc.Assert(cfg.Packages(), gc.DeepEquals, []string{\"a b c\", \"d!\"})\n}\n\nfunc (S) TestSetOutput(c *gc.C) {\n\ttype test struct {\n\t\tkind   cloudinit.OutputKind\n\t\tstdout string\n\t\tstderr string\n\t}\n\ttests := []test{{\n\t\tcloudinit.OutAll, \"a\", \"\",\n\t}, {\n\t\tcloudinit.OutAll, \"\", \"b\",\n\t}, {\n\t\tcloudinit.OutInit, \"a\", \"b\",\n\t}, {\n\t\tcloudinit.OutAll, \"a\", \"b\",\n\t}, {\n\t\tcloudinit.OutAll, \"\", \"\",\n\t}}\n\n\tcfg := cloudinit.New()\n\tstdout, stderr := cfg.Output(cloudinit.OutAll)\n\tc.Assert(stdout, gc.Equals, \"\")\n\tc.Assert(stderr, gc.Equals, \"\")\n\tfor i, t := range tests {\n\t\tc.Logf(\"test %d: %+v\", i, t)\n\t\tcfg.SetOutput(t.kind, t.stdout, t.stderr)\n\t\tstdout, stderr = cfg.Output(t.kind)\n\t\tc.Assert(stdout, gc.Equals, t.stdout)\n\t\tc.Assert(stderr, gc.Equals, t.stderr)\n\t}\n}\n\n\/\/#cloud-config\n\/\/packages:\n\/\/- juju\n\/\/- ubuntu\nfunc ExampleConfig() {\n\tcfg := cloudinit.New()\n\tcfg.AddPackage(\"juju\")\n\tcfg.AddPackage(\"ubuntu\")\n\tdata, err := cfg.Render()\n\tif err != nil {\n\t\tfmt.Printf(\"render error: %v\", err)\n\t\treturn\n\t}\n\tfmt.Printf(\"%s\", data)\n}\n<|endoftext|>"}
{"text":"<commit_before>package cluster\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/AsynkronIT\/protoactor-go\/actor\"\n)\n\nvar (\n\tmembershipPID *actor.PID\n)\n\nfunc spawnMembershipActor() {\n\tmembershipPID = actor.SpawnNamed(actor.FromProducer(NewMembershipActor()), \"#membership\")\n}\n\nfunc NewMembershipActor() actor.Producer {\n\treturn func() actor.Actor {\n\t\treturn &membershipActor{}\n\t}\n}\n\nfunc init() {\n\tspawnMembershipActor()\n\n\t\/\/subscribe the membership actor to the MemberStatusBatch event\n\tactor.EventStream.SubscribePID(func(m interface{}) bool {\n\t\t_, ok := m.(MemberStatusBatch)\n\t\treturn ok\n\t}, membershipPID)\n}\n\n\/\/membershipActor is responsible to keep track of the current cluster topology\n\/\/it does so by listening to changes from the ClusterProvider.\n\/\/the default ClusterProvider is consul_cluster.ConsulProvider which uses the Consul HTTP API to scan for changes\n\/\/TODO: we need some way of creating a hashring per \"kind\", maybe we should have a child actor to the membership actor that handles nodes\n\/\/per kind.\ntype membershipActor struct {\n\tmembers map[string]*MemberStatus\n}\n\ntype MemberStatusEvent interface {\n\tMemberStatusEvent()\n}\n\ntype MemberEvent struct {\n\tAddress string\n\tPort    int\n}\n\nfunc (*MemberEvent) MemberStatusEvent() {}\n\ntype MemberJoinedEvent struct {\n\tMemberEvent\n}\n\ntype MemberLeftEvent struct {\n\tMemberEvent\n}\n\ntype MemberUnavailableEvent struct {\n\tMemberEvent\n}\n\ntype MemberAvailableEvent struct {\n\tMemberEvent\n}\n\nfunc (a *membershipActor) Receive(ctx actor.Context) {\n\tswitch msg := ctx.Message().(type) {\n\tcase *actor.Started:\n\t\ta.members = make(map[string]*MemberStatus)\n\tcase MemberStatusBatch:\n\t\t\/\/TODO: keys that are present in the map but not in the message, are nodes that have left\/been deregistered\n\t\t\/\/we need to handle this too..\n\t\tfor _, new := range msg {\n\n\t\t\t\/\/key is address:port\n\t\t\tkey := fmt.Sprintf(\"%v:%v\", new.Address, new.Port)\n\t\t\told := a.members[key]\n\t\t\ta.members[key] = new\n\t\t\taddress := MemberEvent{\n\t\t\t\tAddress: new.Address,\n\t\t\t\tPort:    new.Port,\n\t\t\t}\n\t\t\tif old == nil {\n\t\t\t\t\/\/notify joined\n\t\t\t\tjoined := &MemberJoinedEvent{MemberEvent: address}\n\t\t\t\tactor.EventStream.Publish(joined)\n\t\t\t} else {\n\t\t\t\tif old.Alive && !new.Alive {\n\t\t\t\t\t\/\/notify node unavailable\n\t\t\t\t\tunavailable := &MemberUnavailableEvent{MemberEvent: address}\n\t\t\t\t\tactor.EventStream.Publish(unavailable)\n\t\t\t\t} else if !old.Alive && new.Alive {\n\t\t\t\t\t\/\/notify node reachable\n\t\t\t\t\tavailable := &MemberAvailableEvent{MemberEvent: address}\n\t\t\t\t\tactor.EventStream.Publish(available)\n\t\t\t\t} else {\n\t\t\t\t\t\/\/Ignore, no change...\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>cluster status notifications<commit_after>package cluster\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/AsynkronIT\/protoactor-go\/actor\"\n)\n\nvar (\n\tmembershipPID *actor.PID\n)\n\nfunc spawnMembershipActor() {\n\tmembershipPID = actor.SpawnNamed(actor.FromProducer(newMembershipActor()), \"#membership\")\n}\n\nfunc newMembershipActor() actor.Producer {\n\treturn func() actor.Actor {\n\t\treturn &membershipActor{}\n\t}\n}\n\nfunc init() {\n\tspawnMembershipActor()\n\n\t\/\/subscribe the membership actor to the MemberStatusBatch event\n\tactor.EventStream.SubscribePID(func(m interface{}) bool {\n\t\t_, ok := m.(MemberStatusBatch)\n\t\treturn ok\n\t}, membershipPID)\n}\n\n\/\/membershipActor is responsible to keep track of the current cluster topology\n\/\/it does so by listening to changes from the ClusterProvider.\n\/\/the default ClusterProvider is consul_cluster.ConsulProvider which uses the Consul HTTP API to scan for changes\n\/\/TODO: we need some way of creating a hashring per \"kind\", maybe we should have a child actor to the membership actor that handles nodes\n\/\/per kind.\ntype membershipActor struct {\n\tmembers map[string]*MemberStatus\n}\n\ntype MemberStatusEvent interface {\n\tMemberStatusEvent()\n}\n\ntype MemberEvent struct {\n\tAddress string\n\tPort    int\n}\n\nfunc (*MemberEvent) MemberStatusEvent() {}\n\ntype MemberJoinedEvent struct {\n\tMemberEvent\n}\n\ntype MemberLeftEvent struct {\n\tMemberEvent\n}\n\ntype MemberUnavailableEvent struct {\n\tMemberEvent\n}\n\ntype MemberAvailableEvent struct {\n\tMemberEvent\n}\n\nfunc (a *membershipActor) Receive(ctx actor.Context) {\n\tswitch msg := ctx.Message().(type) {\n\tcase *actor.Started:\n\t\ta.members = make(map[string]*MemberStatus)\n\tcase MemberStatusBatch:\n\n\t\t\/\/build a lookup for the new statuses\n\t\ttmp := make(map[string]*MemberStatus)\n\t\tfor _, new := range msg {\n\t\t\t\/\/key is address:port\n\t\t\tkey := fmt.Sprintf(\"%v:%v\", new.Address, new.Port)\n\t\t\ttmp[key] = new\n\t\t}\n\n\t\t\/\/find the entires that only exist in the old set but not in the new\n\t\tfor key, old := range a.members {\n\t\t\tnew := tmp[key]\n\t\t\tif new == nil {\n\t\t\t\ta.notify(new, old)\n\t\t\t}\n\t\t}\n\n\t\t\/\/find all the entries that exist in the new set\n\t\tfor key, new := range tmp {\n\t\t\told := a.members[key]\n\t\t\ta.members[key] = new\n\t\t\ta.notify(new, old)\n\t\t}\n\t}\n}\n\nfunc (a *membershipActor) notify(new *MemberStatus, old *MemberStatus) {\n\taddress := MemberEvent{\n\t\tAddress: new.Address,\n\t\tPort:    new.Port,\n\t}\n\tif new == nil && old == nil {\n\t\t\/\/ignore, not possible\n\t\treturn\n\t}\n\tif new == nil {\n\t\t\/\/notify left\n\t\tleft := &MemberLeftEvent{MemberEvent: address}\n\t\tactor.EventStream.Publish(left)\n\t\treturn\n\t}\n\tif old == nil {\n\t\t\/\/notify joined\n\t\tjoined := &MemberJoinedEvent{MemberEvent: address}\n\t\tactor.EventStream.Publish(joined)\n\t\treturn\n\t}\n\tif old.Alive && !new.Alive {\n\t\t\/\/notify node unavailable\n\t\tunavailable := &MemberUnavailableEvent{MemberEvent: address}\n\t\tactor.EventStream.Publish(unavailable)\n\t\treturn\n\t}\n\tif !old.Alive && new.Alive {\n\t\t\/\/notify node reachable\n\t\tavailable := &MemberAvailableEvent{MemberEvent: address}\n\t\tactor.EventStream.Publish(available)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package store\n\nimport (\n  \"encoding\/json\"\n  \"fmt\"\n  \"github.com\/vole\/gouuid\"\n  \"path\"\n  \"time\"\n)\n\n\/**\n * Post.\n *\/\ntype Post struct {\n  \/\/ Properties that should be saved to disk.\n  Id      string `json:\"id\"`\n  Title   string `json:\"title\"`\n  Created int64  `json:\"created\"`\n\n  \/\/ Properties that are used by Vole backend and frontend, but not saved to disk\n  \/\/ when the post is marshaled.\n  UserId     string `json:\"user_id,omitempty\"`\n  UserName   string `json:\"user_name,omitempty\"`\n  UserAvatar string `json:\"user_avatar,omitempty\"`\n  IsMyPost   bool   `json:\"is_my_post,omitempty\"`\n\n  \/\/ Properties that are only used by the backend and thus don't have\n  \/\/ to be marshaled to JSON for either the frontend or disk.\n  FullPath string `json:\"-\"`\n}\n\n\/**\n * InitNew()\n *\n * Initialize a new post creating the id and other fields.\n *\/\nfunc (post *Post) InitNew(title, userPath, userId, userName, userAvatar string, isMyUser bool) {\n  \/\/ Create a new UUID\n  uuidBytes, _ := uuid.NewV4()\n  uuid := fmt.Sprintf(\"%s\", uuidBytes)\n\n  \/\/ Get the timestamp.\n  created := time.Now().UnixNano()\n\n  \/\/ The full path to the post.\n  fullPath := path.Join(userPath, \"posts\", fmt.Sprintf(\"%d-post-%s.json\", created, uuid))\n\n  post.Id = uuid\n  post.Title = title\n  post.Created = created\n  post.UserId = userId\n  post.UserName = userName\n  post.UserAvatar = userAvatar\n  post.IsMyPost = isMyUser\n  post.FullPath = fullPath\n}\n\n\/**\n * InitFromJson()\n *\n * Initialize a new post from json data from disk.\n *\/\nfunc (post *Post) InitFromJson(rawJson []byte, fullPath string, userId string, userName string, userAvatar string, isMyUser bool) error {\n  if err := json.Unmarshal(rawJson, post); err != nil {\n    return err\n  }\n  post.UserId = userId\n  post.UserName = userName\n  post.UserAvatar = userAvatar\n  post.IsMyPost = isMyUser\n  post.FullPath = fullPath\n  return nil\n}\n\n\/**\n * Save()\n *\n * Save post to disk.\n *\/\nfunc (post *Post) Save() error {\n  \/\/ Before marshaling JSON for saving to disk, we set all properties\n  \/\/ that should not be saved to empty, so they are ignored by marshaller.\n  postClone := *post\n  postClone.UserId = \"\"\n  postClone.UserName = \"\"\n  postClone.UserAvatar = \"\"\n\n  rawJson, err := json.Marshal(postClone)\n  if err != nil {\n    return err\n  }\n\n  return Write(postClone.FullPath, rawJson)\n}\n\nfunc (post *Post) Delete() error {\n  return Delete(post.FullPath)\n}\n\n\/**\n * Collection()\n *\n * Return a post collection wrapping this user.\n *\/\nfunc (post *Post) Collection() *PostCollection {\n  return &PostCollection{[]Post{*post}}\n}\n\n\/**\n * Container()\n *\n * Return a post container wrapping this post.\n *\/\nfunc (post *Post) Container() *PostContainer {\n  return &PostContainer{*post}\n}\n<commit_msg>Dont save ismypost<commit_after>package store\n\nimport (\n  \"encoding\/json\"\n  \"fmt\"\n  \"github.com\/vole\/gouuid\"\n  \"path\"\n  \"time\"\n)\n\n\/**\n * Post.\n *\/\ntype Post struct {\n  \/\/ Properties that should be saved to disk.\n  Id      string `json:\"id\"`\n  Title   string `json:\"title\"`\n  Created int64  `json:\"created\"`\n\n  \/\/ Properties that are used by Vole backend and frontend, but not saved to disk\n  \/\/ when the post is marshaled.\n  UserId     string `json:\"user_id,omitempty\"`\n  UserName   string `json:\"user_name,omitempty\"`\n  UserAvatar string `json:\"user_avatar,omitempty\"`\n  IsMyPost   bool   `json:\"is_my_post,omitempty\"`\n\n  \/\/ Properties that are only used by the backend and thus don't have\n  \/\/ to be marshaled to JSON for either the frontend or disk.\n  FullPath string `json:\"-\"`\n}\n\n\/**\n * InitNew()\n *\n * Initialize a new post creating the id and other fields.\n *\/\nfunc (post *Post) InitNew(title, userPath, userId, userName, userAvatar string, isMyUser bool) {\n  \/\/ Create a new UUID\n  uuidBytes, _ := uuid.NewV4()\n  uuid := fmt.Sprintf(\"%s\", uuidBytes)\n\n  \/\/ Get the timestamp.\n  created := time.Now().UnixNano()\n\n  \/\/ The full path to the post.\n  fullPath := path.Join(userPath, \"posts\", fmt.Sprintf(\"%d-post-%s.json\", created, uuid))\n\n  post.Id = uuid\n  post.Title = title\n  post.Created = created\n  post.UserId = userId\n  post.UserName = userName\n  post.UserAvatar = userAvatar\n  post.IsMyPost = isMyUser\n  post.FullPath = fullPath\n}\n\n\/**\n * InitFromJson()\n *\n * Initialize a new post from json data from disk.\n *\/\nfunc (post *Post) InitFromJson(rawJson []byte, fullPath string, userId string, userName string, userAvatar string, isMyUser bool) error {\n  if err := json.Unmarshal(rawJson, post); err != nil {\n    return err\n  }\n  post.UserId = userId\n  post.UserName = userName\n  post.UserAvatar = userAvatar\n  post.IsMyPost = isMyUser\n  post.FullPath = fullPath\n  return nil\n}\n\n\/**\n * Save()\n *\n * Save post to disk.\n *\/\nfunc (post *Post) Save() error {\n  \/\/ Before marshaling JSON for saving to disk, we set all properties\n  \/\/ that should not be saved to empty, so they are ignored by marshaller.\n  postClone := *post\n  postClone.UserId = \"\"\n  postClone.UserName = \"\"\n  postClone.UserAvatar = \"\"\n  postClone.IsMyPost = false\n\n  rawJson, err := json.Marshal(postClone)\n  if err != nil {\n    return err\n  }\n\n  return Write(postClone.FullPath, rawJson)\n}\n\nfunc (post *Post) Delete() error {\n  return Delete(post.FullPath)\n}\n\n\/**\n * Collection()\n *\n * Return a post collection wrapping this user.\n *\/\nfunc (post *Post) Collection() *PostCollection {\n  return &PostCollection{[]Post{*post}}\n}\n\n\/**\n * Container()\n *\n * Return a post container wrapping this post.\n *\/\nfunc (post *Post) Container() *PostContainer {\n  return &PostContainer{*post}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n    \"github.com\/qmsk\/clusterf\/config\"\n    \"github.com\/qmsk\/clusterf\/docker\"\n\t\"github.com\/jessevdk\/go-flags\"\n    \"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n)\n\nvar Options struct {\n\tConfigWriter\tconfig.WriterOptions\t`group:\"Config Writer\"`\n\tDocker\t\t\tdocker.Options\n\n\tExitFlush\t\tbool\t`long:\"exit-flush\" description:\"Flush backends on exit signal\"`\n\n\tRouteNetwork\tstring  `long:\"route-network\" value-name:\"NETWORK-NAME\" description:\"Advertise docker network by name\"`\n\tRouteGateway4\tstring\t`long:\"route-gateway4\" value-name:\"IPV4-ADDRESS\" description:\"Advertise docker network routes with IPv4 gateway\"`\n\tRouteGateway6\tstring\t`long:\"route-gateway6\" value-name:\"IPV6-ADDRESS\" description:\"Advertise docker network routes with IPv6 gateway\"`\n\tRouteIPVSMethod string\t`long:\"route-ipvs-method\" value-name:\"masq|tunnel|droute\" description:\"Advertise docker network routes with ipvs-method\"`\n}\n\nvar flagsParser = flags.NewParser(&Options,  flags.Default)\n\n\/\/ Flush service backends when stopping\nfunc stop(configWriter *config.Writer) {\n\tlog.Printf(\"Flush.....\")\n\n\tif err := configWriter.Flush(); err != nil {\n\t\tlog.Fatalf(\"config:Writer.Flush: %v\", err)\n\t} else {\n\t\tlog.Printf(\"Flushed\")\n\t}\n}\n\n\/\/ Listen for updated docker.State, compile to config.Config and update config.Writer.\n\/\/\n\/\/ Stops on os.Signal\nfunc run(configWriter *config.Writer, dockerListen chan docker.State, stopChan chan os.Signal) {\n\tdefer stop(configWriter)\n\n\tfor {\n\t\tselect {\n\t\tcase dockerState, ok := <-dockerListen:\n\t\t\tif !ok {\n\t\t\t\t\/\/ docker quit? exit and restart\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif config, err := makeConfig(dockerState); err != nil {\n\t\t\t\tlog.Fatalf(\"configContainers: %v\", err)\n\t\t\t} else if err := configWriter.Write(config); err != nil {\n\t\t\t\tlog.Fatalf(\"config:Writer.Write: %v\", err)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Update config...\")\n\t\t\t}\n\n\t\tcase s := <-stopChan:\n\t\t\tlog.Printf(\"Stopping on %v...\", s)\n\n\t\t\t\/\/ reset signal in case stopping gets stuck\n\t\t\tsignal.Stop(stopChan)\n\n\t\t\treturn\n\t\t}\n\t}\n\n\tlog.Printf(\"Stop...\")\n}\n\nfunc main() {\n\tif _, err := flagsParser.Parse(); err != nil {\n\t\tlog.Fatalf(\"flags.Parser.Parse: %v\", err)\n\t}\n\n\tconfigWriter, err := Options.ConfigWriter.Writer()\n\tif err != nil {\n\t\tlog.Fatalf(\"config.Writer: %v\", err)\n\t}\n\n    docker, err := Options.Docker.Open()\n\tif err != nil {\n        log.Fatalf(\"docker:Docker.Open: %v\", err)\n    } else {\n        log.Printf(\"docker:Docker.Open: %v\", docker)\n    }\n\n    dockerChan, err := docker.Listen()\n\tif err != nil {\n        log.Fatalf(\"docker:Docker.Listen: %v\", err)\n    } else {\n        log.Printf(\"docker:Docker.Listen...\")\n\t}\n\n\t\/\/ optionally arrange to stop on signal\n\tvar stopChan chan os.Signal\n\n\tif Options.ExitFlush {\n\t\tstopChan = make(chan os.Signal)\n\n\t\tsignal.Notify(stopChan, syscall.SIGINT, syscall.SIGTERM)\n\t}\n\n\t\/\/ mainloop\n\trun(configWriter, dockerChan, stopChan)\n}\n<commit_msg>cmd\/clusterf-docker: fix stop logging<commit_after>package main\n\nimport (\n    \"github.com\/qmsk\/clusterf\/config\"\n    \"github.com\/qmsk\/clusterf\/docker\"\n\t\"github.com\/jessevdk\/go-flags\"\n    \"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n)\n\nvar Options struct {\n\tConfigWriter\tconfig.WriterOptions\t`group:\"Config Writer\"`\n\tDocker\t\t\tdocker.Options\n\n\tExitFlush\t\tbool\t`long:\"exit-flush\" description:\"Flush backends on exit signal\"`\n\n\tRouteNetwork\tstring  `long:\"route-network\" value-name:\"NETWORK-NAME\" description:\"Advertise docker network by name\"`\n\tRouteGateway4\tstring\t`long:\"route-gateway4\" value-name:\"IPV4-ADDRESS\" description:\"Advertise docker network routes with IPv4 gateway\"`\n\tRouteGateway6\tstring\t`long:\"route-gateway6\" value-name:\"IPV6-ADDRESS\" description:\"Advertise docker network routes with IPv6 gateway\"`\n\tRouteIPVSMethod string\t`long:\"route-ipvs-method\" value-name:\"masq|tunnel|droute\" description:\"Advertise docker network routes with ipvs-method\"`\n}\n\nvar flagsParser = flags.NewParser(&Options,  flags.Default)\n\n\/\/ Flush service backends when stopping\nfunc stop(configWriter *config.Writer) {\n\tlog.Printf(\"Flush.....\")\n\n\tif err := configWriter.Flush(); err != nil {\n\t\tlog.Fatalf(\"config:Writer.Flush: %v\", err)\n\t} else {\n\t\tlog.Printf(\"Flushed\")\n\t}\n}\n\n\/\/ Listen for updated docker.State, compile to config.Config and update config.Writer.\n\/\/\n\/\/ Stops on os.Signal\nfunc run(configWriter *config.Writer, dockerListen chan docker.State, stopChan chan os.Signal) {\n\tdefer stop(configWriter)\n\n\tfor {\n\t\tselect {\n\t\tcase dockerState, ok := <-dockerListen:\n\t\t\tif !ok {\n\t\t\t\t\/\/ docker quit? exit and restart\n\t\t\t\tlog.Printf(\"Stopping on Docker close...\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif config, err := makeConfig(dockerState); err != nil {\n\t\t\t\tlog.Fatalf(\"configContainers: %v\", err)\n\t\t\t} else if err := configWriter.Write(config); err != nil {\n\t\t\t\tlog.Fatalf(\"config:Writer.Write: %v\", err)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Update config...\")\n\t\t\t}\n\n\t\tcase s := <-stopChan:\n\t\t\tlog.Printf(\"Stopping on %v...\", s)\n\n\t\t\t\/\/ reset signal in case stopping gets stuck\n\t\t\tsignal.Stop(stopChan)\n\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc main() {\n\tif _, err := flagsParser.Parse(); err != nil {\n\t\tlog.Fatalf(\"flags.Parser.Parse: %v\", err)\n\t}\n\n\tconfigWriter, err := Options.ConfigWriter.Writer()\n\tif err != nil {\n\t\tlog.Fatalf(\"config.Writer: %v\", err)\n\t}\n\n    docker, err := Options.Docker.Open()\n\tif err != nil {\n        log.Fatalf(\"docker:Docker.Open: %v\", err)\n    } else {\n        log.Printf(\"docker:Docker.Open: %v\", docker)\n    }\n\n    dockerChan, err := docker.Listen()\n\tif err != nil {\n        log.Fatalf(\"docker:Docker.Listen: %v\", err)\n    } else {\n        log.Printf(\"docker:Docker.Listen...\")\n\t}\n\n\t\/\/ optionally arrange to stop on signal\n\tvar stopChan chan os.Signal\n\n\tif Options.ExitFlush {\n\t\tstopChan = make(chan os.Signal)\n\n\t\tsignal.Notify(stopChan, syscall.SIGINT, syscall.SIGTERM)\n\t}\n\n\t\/\/ mainloop\n\trun(configWriter, dockerChan, stopChan)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nfunc BenchmarkRun(b *testing.B) {\n\topt := &option{}\n\tfor i := 0; i < b.N; i++ {\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := run(buf, []string{\"github.com\/haya14busa\/go-typeconv\"}, opt); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n}\n<commit_msg>cmd: add test for run()<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n\n\tddiff \"github.com\/kylelemons\/godebug\/diff\"\n)\n\nfunc TestRun_package(t *testing.T) {\n\topt := &option{}\n\tbuf := new(bytes.Buffer)\n\tif err := run(buf, []string{\"github.com\/haya14busa\/go-typeconv\"}, opt); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif buf.Len() == 0 {\n\t\tt.Error(\"run: output is empty\")\n\t}\n}\n\nfunc TestRun_testdata(t *testing.T) {\n\topt := &option{}\n\tfiles, err := filepath.Glob(\"..\/..\/testdata\/*.input.go\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor _, fname := range files {\n\t\tinput := fname\n\t\tgolden := strings.Replace(input, \"input.go\", \"golden.go\", 1)\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := run(buf, []string{input}, opt); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tgf, err := os.Open(golden)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%s: %v\", fname, err)\n\t\t}\n\t\tdefer gf.Close()\n\t\tb, err := ioutil.ReadAll(gf)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%s: %v\", fname, err)\n\t\t}\n\n\t\tif d := ddiff.Diff(buf.String(), string(b)); d != \"\" {\n\t\t\tt.Errorf(\"%s: diff: (-got +want):\\n%s\", fname, d)\n\t\t}\n\t}\n}\n\nfunc BenchmarkRun(b *testing.B) {\n\topt := &option{}\n\tfor i := 0; i < b.N; i++ {\n\t\tbuf := new(bytes.Buffer)\n\t\tif err := run(buf, []string{\"github.com\/haya14busa\/go-typeconv\"}, opt); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n Copyright 2020 The GoPlus Authors (goplus.org)\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n\/\/ Package build implements the ``gop build'' command.\npackage build\n\nimport (\n\t\"fmt\"\n\t\"go\/token\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/goplus\/gop\/cl\"\n\t\"github.com\/goplus\/gop\/cmd\/internal\/base\"\n\t\"github.com\/goplus\/gop\/cmd\/internal\/work\"\n\t\"github.com\/goplus\/gop\/exec\/bytecode\"\n\t\"github.com\/qiniu\/x\/log\"\n)\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Cmd - gop build\nvar Cmd = &base.Command{\n\tUsageLine: \"gop build [-v] [-o output] <gopSrcDir|gopSrcFile>\",\n\tShort:     \"Build go+ files and execute go build command\",\n}\n\nvar (\n\tflagBuildOutput string\n\tflagVerbose     bool\n\tflag            = &Cmd.Flag\n)\n\nfunc init() {\n\tflag.StringVar(&flagBuildOutput, \"o\", \"\", \"go build output file\")\n\tflag.BoolVar(&flagVerbose, \"v\", false, \"print the names of packages as they are compiled.\")\n\tCmd.Run = runCmd\n}\n\nfunc runCmd(cmd *base.Command, args []string) {\n\tflag.Parse(args)\n\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to build: %v\", err)\n\t}\n\n\tpaths := flag.Args()\n\tif len(paths) == 0 {\n\t\tpaths = append(paths, dir)\n\t}\n\n\tcl.CallBuiltinOp = bytecode.CallBuiltinOp\n\tlog.SetFlags(log.Ldefault &^ log.LstdFlags)\n\n\tfset := token.NewFileSet()\n\tpkgs, errs := work.LoadPackages(fset, paths)\n\tif len(errs) > 0 {\n\t\tlog.Fatalf(\"load packages error: %v\\n\", errs)\n\t}\n\tif len(pkgs) == 0 {\n\t\tfmt.Println(\"no Go+ files in \", paths)\n\t}\n\tfor _, pkg := range pkgs {\n\t\terr := work.GenGoPkg(fset, pkg.Pkg, pkg.Dir)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"generate go package error: %v\\n\", err)\n\t\t}\n\t\tvar target string\n\t\tif flagBuildOutput != \"\" {\n\t\t\ttarget = filepath.Join(dir, flagBuildOutput)\n\t\t} else {\n\t\t\ttarget = filepath.Join(pkg.Dir, pkg.Target)\n\t\t}\n\t\terr = work.GoBuild(pkg.Dir, target)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"go build error: %v\\n\", err)\n\t\t}\n\t\tif flagVerbose && pkg.Name == \"main\" {\n\t\t\tfmt.Println(target)\n\t\t}\n\t}\n}\n<commit_msg>gop build output abs check<commit_after>\/*\n Copyright 2020 The GoPlus Authors (goplus.org)\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n\/\/ Package build implements the ``gop build'' command.\npackage build\n\nimport (\n\t\"fmt\"\n\t\"go\/token\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/goplus\/gop\/cl\"\n\t\"github.com\/goplus\/gop\/cmd\/internal\/base\"\n\t\"github.com\/goplus\/gop\/cmd\/internal\/work\"\n\t\"github.com\/goplus\/gop\/exec\/bytecode\"\n\t\"github.com\/qiniu\/x\/log\"\n)\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ Cmd - gop build\nvar Cmd = &base.Command{\n\tUsageLine: \"gop build [-v] [-o output] <gopSrcDir|gopSrcFile>\",\n\tShort:     \"Build go+ files and execute go build command\",\n}\n\nvar (\n\tflagBuildOutput string\n\tflagVerbose     bool\n\tflag            = &Cmd.Flag\n)\n\nfunc init() {\n\tflag.StringVar(&flagBuildOutput, \"o\", \"\", \"go build output file\")\n\tflag.BoolVar(&flagVerbose, \"v\", false, \"print the names of packages as they are compiled.\")\n\tCmd.Run = runCmd\n}\n\nfunc runCmd(cmd *base.Command, args []string) {\n\tflag.Parse(args)\n\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalf(\"Fail to build: %v\", err)\n\t}\n\n\tpaths := flag.Args()\n\tif len(paths) == 0 {\n\t\tpaths = append(paths, dir)\n\t}\n\n\tcl.CallBuiltinOp = bytecode.CallBuiltinOp\n\tlog.SetFlags(log.Ldefault &^ log.LstdFlags)\n\n\tfset := token.NewFileSet()\n\tpkgs, errs := work.LoadPackages(fset, paths)\n\tif len(errs) > 0 {\n\t\tlog.Fatalf(\"load packages error: %v\\n\", errs)\n\t}\n\tif len(pkgs) == 0 {\n\t\tfmt.Println(\"no Go+ files in \", paths)\n\t}\n\tfor _, pkg := range pkgs {\n\t\terr := work.GenGoPkg(fset, pkg.Pkg, pkg.Dir)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"generate go package error: %v\\n\", err)\n\t\t}\n\t\ttarget := pkg.Target\n\t\tif flagBuildOutput != \"\" {\n\t\t\ttarget = flagBuildOutput\n\t\t}\n\t\tif !filepath.IsAbs(target) {\n\t\t\ttarget = filepath.Join(dir, target)\n\t\t}\n\t\terr = work.GoBuild(pkg.Dir, target)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"go build error: %v\\n\", err)\n\t\t}\n\t\tif flagVerbose && pkg.Name == \"main\" {\n\t\t\tfmt.Println(target)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package mccli\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/materials-commons\/mcstore\/cmd\/pkg\/mc\"\n)\n\nvar uploadDirCommand = cli.Command{\n\tName:    \"file\",\n\tAliases: []string{\"f\"},\n\tUsage:   \"Upload a file to MaterialsCommons\",\n\tFlags: []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"project, proj, p\",\n\t\t\tUsage: \"The project the file is in\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"recursive, r\",\n\t\t\tUsage: \"Should sub directories also be uploaded\",\n\t\t},\n\t\tcli.IntFlag{\n\t\t\tName:  \"parallel, n\",\n\t\t\tValue: 3,\n\t\t\tUsage: \"Number of simultaneous uploads to perform, defaults to 3\",\n\t\t},\n\t},\n\tAction: uploadDirCLI,\n}\n\nfunc uploadDirCLI(c *cli.Context) {\n\tif len(c.Args()) != 1 {\n\t\tfmt.Println(\"You must specify a directory to upload\")\n\t\tos.Exit(1)\n\t}\n\n\tdirPath := filepath.Clean(c.Args()[0])\n\tif !validateDirectoryPath(dirPath) {\n\t\tos.Exit(1)\n\t}\n\n\tproject := c.String(\"project\")\n\tnumThreads := getNumThreads(c)\n\trecursive := c.Bool(\"recursive\")\n\n\tclient := mc.NewClientAPI()\n\tif err := client.UploadDirectory(project, dirPath, recursive, numThreads); err != nil {\n\t\tfmt.Println(\"Directory upload failed:\", err)\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Println(\"Directory successfully uploaded.\")\n}\n<commit_msg>Cut and paste error. Upload dir had the same command as upload file.<commit_after>package mccli\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/materials-commons\/mcstore\/cmd\/pkg\/mc\"\n)\n\nvar uploadDirCommand = cli.Command{\n\tName:    \"directory\",\n\tAliases: []string{\"dir\", \"d\"},\n\tUsage:   \"Upload a file to MaterialsCommons\",\n\tFlags: []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"project, proj, p\",\n\t\t\tUsage: \"The project the file is in\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"recursive, r\",\n\t\t\tUsage: \"Should sub directories also be uploaded\",\n\t\t},\n\t\tcli.IntFlag{\n\t\t\tName:  \"parallel, n\",\n\t\t\tValue: 3,\n\t\t\tUsage: \"Number of simultaneous uploads to perform, defaults to 3\",\n\t\t},\n\t},\n\tAction: uploadDirCLI,\n}\n\nfunc uploadDirCLI(c *cli.Context) {\n\tif len(c.Args()) != 1 {\n\t\tfmt.Println(\"You must specify a directory to upload\")\n\t\tos.Exit(1)\n\t}\n\n\tdirPath := filepath.Clean(c.Args()[0])\n\tif !validateDirectoryPath(dirPath) {\n\t\tos.Exit(1)\n\t}\n\n\tproject := c.String(\"project\")\n\tnumThreads := getNumThreads(c)\n\trecursive := c.Bool(\"recursive\")\n\n\tclient := mc.NewClientAPI()\n\tif err := client.UploadDirectory(project, dirPath, recursive, numThreads); err != nil {\n\t\tfmt.Println(\"Directory upload failed:\", err)\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Println(\"Directory successfully uploaded.\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package cleanup\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\n\t\"k8s.io\/client-go\/kubernetes\"\n\n\t\"github.com\/flant\/kubedog\/pkg\/kube\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/common\"\n\t\"github.com\/flant\/werf\/pkg\/cleaning\"\n\t\"github.com\/flant\/werf\/pkg\/docker\"\n\t\"github.com\/flant\/werf\/pkg\/docker_registry\"\n\t\"github.com\/flant\/werf\/pkg\/git_repo\"\n\t\"github.com\/flant\/werf\/pkg\/lock\"\n\t\"github.com\/flant\/werf\/pkg\/tmp_manager\"\n\t\"github.com\/flant\/werf\/pkg\/util\"\n\t\"github.com\/flant\/werf\/pkg\/werf\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar CmdData struct {\n\tWithoutKube bool\n}\n\nvar CommonCmdData common.CmdData\n\nfunc NewCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:                   \"cleanup\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort:                 \"Safely cleanup unused project images and stages\",\n\t\tLong: common.GetLongCommandDescription(`Safely cleanup unused project images and stages.\n\nFirst step is 'werf images cleanup' command, which will delete unused images from images repo. Second step is 'werf stages cleanup' command, which will delete unused stages from stages storage to be in sync with the images repo.\n\nIt is safe to run this command periodically (daily is enough) by automated cleanup job in parallel with other werf commands such as build, deploy and host cleanup.`),\n\t\tExample: `  $ werf cleanup --stages-storage :local --images-repo registry.mydomain.com\/myproject`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif err := common.ApplyLogOptions(&CommonCmdData); err != nil {\n\t\t\t\tcmd.Help()\n\t\t\t\tfmt.Println()\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcommon.LogVersion()\n\n\t\t\treturn common.LogRunningTime(func() error {\n\t\t\t\treturn runCleanup()\n\t\t\t})\n\t\t},\n\t}\n\n\tcommon.SetupDir(&CommonCmdData, cmd)\n\tcommon.SetupTmpDir(&CommonCmdData, cmd)\n\tcommon.SetupHomeDir(&CommonCmdData, cmd)\n\n\tcommon.SetupStagesStorage(&CommonCmdData, cmd)\n\tcommon.SetupImagesRepo(&CommonCmdData, cmd)\n\tcommon.SetupDockerConfig(&CommonCmdData, cmd, \"Command needs granted permissions to read, pull and delete images from the specified stages storage and images repo\")\n\tcommon.SetupInsecureRepo(&CommonCmdData, cmd)\n\tcommon.SetupImagesCleanupPolicies(&CommonCmdData, cmd)\n\n\tcommon.SetupKubeConfig(&CommonCmdData, cmd)\n\tcommon.SetupKubeContext(&CommonCmdData, cmd)\n\n\tcommon.SetupDryRun(&CommonCmdData, cmd)\n\n\tcommon.SetupLogOptions(&CommonCmdData, cmd)\n\n\tcmd.Flags().BoolVarP(&CmdData.WithoutKube, \"without-kube\", \"\", false, \"Do not skip deployed kubernetes images\")\n\n\treturn cmd\n}\n\nfunc runCleanup() error {\n\tif err := werf.Init(*CommonCmdData.TmpDir, *CommonCmdData.HomeDir); err != nil {\n\t\treturn fmt.Errorf(\"initialization error: %s\", err)\n\t}\n\n\tif err := lock.Init(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := docker_registry.Init(docker_registry.Options{AllowInsecureRepo: *CommonCmdData.InsecureRepo}); err != nil {\n\t\treturn err\n\t}\n\n\tif err := docker.Init(*CommonCmdData.DockerConfig); err != nil {\n\t\treturn err\n\t}\n\n\tif err := kube.Init(kube.InitOptions{KubeContext: *CommonCmdData.KubeContext, KubeConfig: *CommonCmdData.KubeConfig}); err != nil {\n\t\treturn fmt.Errorf(\"cannot initialize kube: %s\", err)\n\t}\n\n\tprojectDir, err := common.GetProjectDir(&CommonCmdData)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting project dir failed: %s\", err)\n\t}\n\tcommon.LogProjectDir(projectDir)\n\n\tprojectTmpDir, err := tmp_manager.CreateProjectDir()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting project tmp dir failed: %s\", err)\n\t}\n\tdefer tmp_manager.ReleaseProjectDir(projectTmpDir)\n\n\twerfConfig, err := common.GetWerfConfig(projectDir)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"bad config: %s\", err)\n\t}\n\n\tprojectName := werfConfig.Meta.Project\n\n\timagesRepo, err := common.GetImagesRepo(projectName, &CommonCmdData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstagesRepo, err := common.GetStagesRepo(&CommonCmdData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar imagesNames []string\n\tfor _, image := range werfConfig.Images {\n\t\timagesNames = append(imagesNames, image.Name)\n\t}\n\n\tcommonRepoOptions := cleaning.CommonRepoOptions{\n\t\tImagesRepo:    imagesRepo,\n\t\tStagesStorage: stagesRepo,\n\t\tImagesNames:   imagesNames,\n\t\tDryRun:        *CommonCmdData.DryRun,\n\t}\n\n\tvar localGitRepo *git_repo.Local\n\tgitDir := path.Join(projectDir, \".git\")\n\tif exist, err := util.DirExists(gitDir); err != nil {\n\t\treturn err\n\t} else if exist {\n\t\tlocalGitRepo = &git_repo.Local{\n\t\t\tPath:   projectDir,\n\t\t\tGitDir: gitDir,\n\t\t}\n\t}\n\n\tpolicies, err := common.GetImagesCleanupPolicies(&CommonCmdData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcommonProjectOptions := cleaning.CommonProjectOptions{\n\t\tProjectName:   projectName,\n\t\tCommonOptions: cleaning.CommonOptions{DryRun: *CommonCmdData.DryRun},\n\t}\n\n\timagesCleanupOptions := cleaning.ImagesCleanupOptions{\n\t\tCommonRepoOptions: commonRepoOptions,\n\t\tLocalGit:          localGitRepo,\n\t\tKubernetesClients: []kubernetes.Interface{kube.Kubernetes},\n\t\tWithoutKube:       CmdData.WithoutKube,\n\t\tPolicies:          policies,\n\t}\n\n\tstagesCleanupOptions := cleaning.StagesCleanupOptions{\n\t\tCommonRepoOptions:    commonRepoOptions,\n\t\tCommonProjectOptions: commonProjectOptions,\n\t}\n\n\tcleanupOptions := cleaning.CleanupOptions{\n\t\tStagesCleanupOptions: stagesCleanupOptions,\n\t\tImagesCleanupOptions: imagesCleanupOptions,\n\t}\n\n\tif err := cleaning.Cleanup(cleanupOptions); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>HOTFIX 'werf cleanup': Use all contexts from kube-config to found used images<commit_after>package cleanup\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\n\t\"github.com\/flant\/kubedog\/pkg\/kube\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/common\"\n\t\"github.com\/flant\/werf\/pkg\/cleaning\"\n\t\"github.com\/flant\/werf\/pkg\/docker\"\n\t\"github.com\/flant\/werf\/pkg\/docker_registry\"\n\t\"github.com\/flant\/werf\/pkg\/git_repo\"\n\t\"github.com\/flant\/werf\/pkg\/lock\"\n\t\"github.com\/flant\/werf\/pkg\/tmp_manager\"\n\t\"github.com\/flant\/werf\/pkg\/util\"\n\t\"github.com\/flant\/werf\/pkg\/werf\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar CmdData struct {\n\tWithoutKube bool\n}\n\nvar CommonCmdData common.CmdData\n\nfunc NewCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:                   \"cleanup\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort:                 \"Safely cleanup unused project images and stages\",\n\t\tLong: common.GetLongCommandDescription(`Safely cleanup unused project images and stages.\n\nFirst step is 'werf images cleanup' command, which will delete unused images from images repo. Second step is 'werf stages cleanup' command, which will delete unused stages from stages storage to be in sync with the images repo.\n\nIt is safe to run this command periodically (daily is enough) by automated cleanup job in parallel with other werf commands such as build, deploy and host cleanup.`),\n\t\tExample: `  $ werf cleanup --stages-storage :local --images-repo registry.mydomain.com\/myproject`,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif err := common.ApplyLogOptions(&CommonCmdData); err != nil {\n\t\t\t\tcmd.Help()\n\t\t\t\tfmt.Println()\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcommon.LogVersion()\n\n\t\t\treturn common.LogRunningTime(func() error {\n\t\t\t\treturn runCleanup()\n\t\t\t})\n\t\t},\n\t}\n\n\tcommon.SetupDir(&CommonCmdData, cmd)\n\tcommon.SetupTmpDir(&CommonCmdData, cmd)\n\tcommon.SetupHomeDir(&CommonCmdData, cmd)\n\n\tcommon.SetupStagesStorage(&CommonCmdData, cmd)\n\tcommon.SetupImagesRepo(&CommonCmdData, cmd)\n\tcommon.SetupDockerConfig(&CommonCmdData, cmd, \"Command needs granted permissions to read, pull and delete images from the specified stages storage and images repo\")\n\tcommon.SetupInsecureRepo(&CommonCmdData, cmd)\n\tcommon.SetupImagesCleanupPolicies(&CommonCmdData, cmd)\n\n\tcommon.SetupKubeConfig(&CommonCmdData, cmd)\n\tcommon.SetupKubeContext(&CommonCmdData, cmd)\n\n\tcommon.SetupDryRun(&CommonCmdData, cmd)\n\n\tcommon.SetupLogOptions(&CommonCmdData, cmd)\n\n\tcmd.Flags().BoolVarP(&CmdData.WithoutKube, \"without-kube\", \"\", false, \"Do not skip deployed kubernetes images\")\n\n\treturn cmd\n}\n\nfunc runCleanup() error {\n\tif err := werf.Init(*CommonCmdData.TmpDir, *CommonCmdData.HomeDir); err != nil {\n\t\treturn fmt.Errorf(\"initialization error: %s\", err)\n\t}\n\n\tif err := lock.Init(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := docker_registry.Init(docker_registry.Options{AllowInsecureRepo: *CommonCmdData.InsecureRepo}); err != nil {\n\t\treturn err\n\t}\n\n\tif err := docker.Init(*CommonCmdData.DockerConfig); err != nil {\n\t\treturn err\n\t}\n\n\tif err := kube.Init(kube.InitOptions{KubeContext: *CommonCmdData.KubeContext, KubeConfig: *CommonCmdData.KubeConfig}); err != nil {\n\t\treturn fmt.Errorf(\"cannot initialize kube: %s\", err)\n\t}\n\n\tprojectDir, err := common.GetProjectDir(&CommonCmdData)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting project dir failed: %s\", err)\n\t}\n\tcommon.LogProjectDir(projectDir)\n\n\tprojectTmpDir, err := tmp_manager.CreateProjectDir()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"getting project tmp dir failed: %s\", err)\n\t}\n\tdefer tmp_manager.ReleaseProjectDir(projectTmpDir)\n\n\twerfConfig, err := common.GetWerfConfig(projectDir)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"bad config: %s\", err)\n\t}\n\n\tprojectName := werfConfig.Meta.Project\n\n\timagesRepo, err := common.GetImagesRepo(projectName, &CommonCmdData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstagesRepo, err := common.GetStagesRepo(&CommonCmdData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar imagesNames []string\n\tfor _, image := range werfConfig.Images {\n\t\timagesNames = append(imagesNames, image.Name)\n\t}\n\n\tcommonRepoOptions := cleaning.CommonRepoOptions{\n\t\tImagesRepo:    imagesRepo,\n\t\tStagesStorage: stagesRepo,\n\t\tImagesNames:   imagesNames,\n\t\tDryRun:        *CommonCmdData.DryRun,\n\t}\n\n\tvar localGitRepo *git_repo.Local\n\tgitDir := path.Join(projectDir, \".git\")\n\tif exist, err := util.DirExists(gitDir); err != nil {\n\t\treturn err\n\t} else if exist {\n\t\tlocalGitRepo = &git_repo.Local{\n\t\t\tPath:   projectDir,\n\t\t\tGitDir: gitDir,\n\t\t}\n\t}\n\n\tpolicies, err := common.GetImagesCleanupPolicies(&CommonCmdData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkubernetesClients, err := kube.GetAllClients(kube.GetClientsOptions{KubeConfig: *CommonCmdData.KubeConfig})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to get kubernetes clusters connections: %s\", err)\n\t}\n\n\tcommonProjectOptions := cleaning.CommonProjectOptions{\n\t\tProjectName:   projectName,\n\t\tCommonOptions: cleaning.CommonOptions{DryRun: *CommonCmdData.DryRun},\n\t}\n\n\timagesCleanupOptions := cleaning.ImagesCleanupOptions{\n\t\tCommonRepoOptions: commonRepoOptions,\n\t\tLocalGit:          localGitRepo,\n\t\tKubernetesClients: kubernetesClients,\n\t\tWithoutKube:       CmdData.WithoutKube,\n\t\tPolicies:          policies,\n\t}\n\n\tstagesCleanupOptions := cleaning.StagesCleanupOptions{\n\t\tCommonRepoOptions:    commonRepoOptions,\n\t\tCommonProjectOptions: commonProjectOptions,\n\t}\n\n\tcleanupOptions := cleaning.CleanupOptions{\n\t\tStagesCleanupOptions: stagesCleanupOptions,\n\t\tImagesCleanupOptions: imagesCleanupOptions,\n\t}\n\n\tif err := cleaning.Cleanup(cleanupOptions); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package service\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"goa.design\/goa\/v3\/codegen\"\n\t\"goa.design\/goa\/v3\/expr\"\n)\n\ntype (\n\t\/\/ endpointsData contains the data necessary to render the\n\t\/\/ service endpoints struct template.\n\tendpointsData struct {\n\t\t\/\/ Name is the service name.\n\t\tName string\n\t\t\/\/ Description is the service description.\n\t\tDescription string\n\t\t\/\/ VarName is the endpoint struct name.\n\t\tVarName string\n\t\t\/\/ ClientVarName is the client struct name.\n\t\tClientVarName string\n\t\t\/\/ ServiceVarName is the service interface name.\n\t\tServiceVarName string\n\t\t\/\/ Methods lists the endpoint struct methods.\n\t\tMethods []*endpointMethodData\n\t\t\/\/ ClientInitArgs lists the arguments needed to instantiate the client.\n\t\tClientInitArgs string\n\t\t\/\/ Schemes contains the security schemes types used by the\n\t\t\/\/ all the endpoints.\n\t\tSchemes SchemesData\n\t}\n\n\t\/\/ endpointMethodData describes a single endpoint method.\n\tendpointMethodData struct {\n\t\t*MethodData\n\t\t\/\/ ArgName is the name of the argument used to initialize the client\n\t\t\/\/ struct method field.\n\t\tArgName string\n\t\t\/\/ ClientVarName is the corresponding client struct field name.\n\t\tClientVarName string\n\t\t\/\/ ServiceName is the name of the owner service.\n\t\tServiceName string\n\t\t\/\/ ServiceVarName is the name of the owner service Go interface.\n\t\tServiceVarName string\n\t}\n)\n\nconst (\n\t\/\/ endpointsStructName is the name of the generated endpoints data\n\t\/\/ structure.\n\tendpointsStructName = \"Endpoints\"\n\n\t\/\/ serviceInterfaceName is the name of the generated service interface.\n\tserviceInterfaceName = \"Service\"\n)\n\n\/\/ EndpointFile returns the endpoint file for the given service.\nfunc EndpointFile(genpkg string, service *expr.ServiceExpr) *codegen.File {\n\tsvc := Services.Get(service.Name)\n\tsvcName := codegen.SnakeCase(svc.VarName)\n\tpath := filepath.Join(codegen.Gendir, svcName, \"endpoints.go\")\n\tdata := endpointData(service)\n\tvar (\n\t\tsections []*codegen.SectionTemplate\n\t)\n\t{\n\t\theader := codegen.Header(service.Name+\" endpoints\", svc.PkgName,\n\t\t\t[]*codegen.ImportSpec{\n\t\t\t\t{Path: \"context\"},\n\t\t\t\t{Path: \"io\"},\n\t\t\t\t{Path: \"fmt\"},\n\t\t\t\tcodegen.GoaImport(\"\"),\n\t\t\t\tcodegen.GoaImport(\"security\"),\n\t\t\t\t{Path: genpkg + \"\/\" + svcName + \"\/\" + \"views\", Name: svc.ViewsPkg},\n\t\t\t})\n\t\tdef := &codegen.SectionTemplate{\n\t\t\tName:   \"endpoints-struct\",\n\t\t\tSource: serviceEndpointsT,\n\t\t\tData:   data,\n\t\t}\n\t\tsections = []*codegen.SectionTemplate{header, def}\n\t\tfor _, m := range data.Methods {\n\t\t\tif m.ServerStream != nil {\n\t\t\t\tsections = append(sections, &codegen.SectionTemplate{\n\t\t\t\t\tName:   \"endpoint-input-struct\",\n\t\t\t\t\tSource: serviceEndpointStreamStructT,\n\t\t\t\t\tData:   m,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif m.SkipRequestBodyEncodeDecode {\n\t\t\t\tsections = append(sections, &codegen.SectionTemplate{\n\t\t\t\t\tName:   \"request-body-struct\",\n\t\t\t\t\tSource: serviceRequestBodyStructT,\n\t\t\t\t\tData:   m,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif m.SkipResponseBodyEncodeDecode {\n\t\t\t\tsections = append(sections, &codegen.SectionTemplate{\n\t\t\t\t\tName:   \"response-body-struct\",\n\t\t\t\t\tSource: serviceResponseBodyStructT,\n\t\t\t\t\tData:   m,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tsections = append(sections, &codegen.SectionTemplate{\n\t\t\tName:   \"endpoints-init\",\n\t\t\tSource: serviceEndpointsInitT,\n\t\t\tData:   data,\n\t\t})\n\t\tsections = append(sections, &codegen.SectionTemplate{\n\t\t\tName:   \"endpoints-use\",\n\t\t\tSource: serviceEndpointsUseT,\n\t\t\tData:   data,\n\t\t})\n\t\tfor _, m := range data.Methods {\n\t\t\tsections = append(sections, &codegen.SectionTemplate{\n\t\t\t\tName:    \"endpoint-method\",\n\t\t\t\tSource:  serviceEndpointMethodT,\n\t\t\t\tData:    m,\n\t\t\t\tFuncMap: map[string]interface{}{\"payloadVar\": payloadVar},\n\t\t\t})\n\t\t}\n\t}\n\n\treturn &codegen.File{Path: path, SectionTemplates: sections}\n}\n\nfunc endpointData(service *expr.ServiceExpr) *endpointsData {\n\tsvc := Services.Get(service.Name)\n\tmethods := make([]*endpointMethodData, len(svc.Methods))\n\tnames := make([]string, len(svc.Methods))\n\tfor i, m := range svc.Methods {\n\t\tmethods[i] = &endpointMethodData{\n\t\t\tMethodData:     m,\n\t\t\tArgName:        codegen.Goify(m.VarName, false),\n\t\t\tServiceName:    svc.Name,\n\t\t\tServiceVarName: serviceInterfaceName,\n\t\t\tClientVarName:  clientStructName,\n\t\t}\n\t\tnames[i] = codegen.Goify(m.VarName, false)\n\t}\n\tdesc := fmt.Sprintf(\"%s wraps the %q service endpoints.\", endpointsStructName, service.Name)\n\treturn &endpointsData{\n\t\tName:           service.Name,\n\t\tDescription:    desc,\n\t\tVarName:        endpointsStructName,\n\t\tClientVarName:  clientStructName,\n\t\tServiceVarName: serviceInterfaceName,\n\t\tClientInitArgs: strings.Join(names, \", \"),\n\t\tMethods:        methods,\n\t\tSchemes:        svc.Schemes,\n\t}\n}\n\nfunc payloadVar(e *endpointMethodData) string {\n\tif e.ServerStream != nil || e.SkipRequestBodyEncodeDecode {\n\t\treturn \"ep.Payload\"\n\t}\n\treturn \"p\"\n}\n\n\/\/ input: endpointsData\nconst serviceEndpointsT = `{{ comment .Description }}\ntype {{ .VarName }} struct {\n{{- range .Methods}}\n\t{{ .VarName }} goa.Endpoint\n{{- end }}\n}\n`\n\n\/\/ input: endpointsData\nconst serviceEndpointsInitT = `{{ printf \"New%s wraps the methods of the %q service with endpoints.\" .VarName .Name | comment }}\nfunc New{{ .VarName }}(s {{ .ServiceVarName }}) *{{ .VarName }} {\n{{- if .Schemes }}\n\t\/\/ Casting service to Auther interface\n\ta := s.(Auther)\n{{- end }}\n\treturn &{{ .VarName }}{\n{{- range .Methods }}\n\t\t{{ .VarName }}: New{{ .VarName }}Endpoint(s{{ range .Schemes }}, a.{{ .Type }}Auth{{ end }}),\n{{- end }}\n\t}\n}\n`\n\n\/\/ input: endpointMethodData\nconst serviceEndpointStreamStructT = `{{ printf \"%s holds both the payload and the server stream of the %q method.\" .ServerStream.EndpointStruct .Name | comment }}\ntype {{ .ServerStream.EndpointStruct }} struct {\n{{- if .PayloadRef }}\n\t{{ comment \"Payload is the method payload.\" }}\n\tPayload {{ .PayloadRef }}\n{{- end }}\n\t{{ printf \"Stream is the server stream used by the %q method to send data.\" .Name | comment }}\n\tStream {{ .ServerStream.Interface }}\n}\n`\n\n\/\/ input: endpointMethodData\nconst serviceRequestBodyStructT = `{{ printf \"%s holds both the payload and the HTTP request body reader of the %q method.\" .RequestStruct .Name | comment }}\ntype {{ .RequestStruct }} struct {\n{{- if .PayloadRef }}\n\t{{ comment \"Payload is the method payload.\" }}\n\tPayload {{ .PayloadRef }}\n{{- end }}\n\t{{ comment \"Body streams the HTTP request body.\" }}\n\tBody io.ReadCloser\n}\n`\n\n\/\/ input: endpointMethodData\nconst serviceResponseBodyStructT = `{{ printf \"%s holds both the result and the HTTP response body reader of the %q method.\" .ResponseStruct .Name | comment }}\ntype {{ .ResponseStruct }} struct {\n{{- if .ResultRef }}\n\t{{ comment \"Result is the method result.\" }}\n\tResult {{ .ResultRef }}\n{{- end }}\n\t{{ comment \"Body streams the HTTP response body.\" }}\n\tBody io.ReadCloser\n}\n`\n\n\/\/ input: endpointMethodData\nconst serviceEndpointMethodT = `{{ printf \"New%sEndpoint returns an endpoint function that calls the method %q of service %q.\" .VarName .Name .ServiceName | comment }}\nfunc New{{ .VarName }}Endpoint(s {{ .ServiceVarName }}{{ range .Schemes }}, auth{{ .Type }}Fn security.Auth{{ .Type }}Func{{ end }}) goa.Endpoint {\n\treturn func(ctx context.Context, req interface{}) (interface{}, error) {\n{{- if or .ServerStream }}\n\t\tep := req.(*{{ .ServerStream.EndpointStruct }})\n{{- else if .SkipRequestBodyEncodeDecode }}\n\t\tep := req.(*{{ .RequestStruct }})\n{{- else if .PayloadRef }}\n\t\tp := req.({{ .PayloadRef }})\n{{- end }}\n{{- $payload := payloadVar . }}\n{{- if .Requirements }}\n\t\tvar err error\n\t{{- range $ridx, $r := .Requirements }}\n\t\t{{- if ne $ridx 0 }}\n\t\tif err != nil {\n\t\t{{- end }}\n\t\t{{- range $sidx, $s := .Schemes }}\n\t\t\t{{- if ne $sidx 0 }}\n\t\t\tif err == nil {\n\t\t\t{{- end }}\n\t\t\t{{- if eq .Type \"Basic\" }}\n\t\t\t\tsc := security.BasicScheme{\n\t\t\t\t\tName: {{ printf \"%q\" .SchemeName }},\n\t\t\t\t\tScopes: []string{ {{- range .Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t\tRequiredScopes: []string{ {{- range $r.Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t}\n\t\t\t\t{{- if .UsernamePointer }}\n\t\t\t\tvar user string\n\t\t\t\tif {{ $payload }}.{{ .UsernameField }} != nil {\n\t\t\t\t\tuser = *{{ $payload }}.{{ .UsernameField }}\n\t\t\t\t}\n\t\t\t\t{{- end }}\n\t\t\t\t{{- if .PasswordPointer }}\n\t\t\t\tvar pass string\n\t\t\t\tif {{ $payload }}.{{ .PasswordField }} != nil {\n\t\t\t\t\tpass = *{{ $payload }}.{{ .PasswordField }}\n\t\t\t\t}\n\t\t\t\t{{- end }}\n\t\t\t\tctx, err = auth{{ .Type }}Fn(ctx, {{ if .UsernamePointer }}user{{ else }}{{ $payload }}.{{ .UsernameField }}{{ end }},\n\t\t\t\t\t{{- if .PasswordPointer }}pass{{ else }}{{ $payload }}.{{ .PasswordField }}{{ end }}, &sc)\n\n\t\t\t{{- else if eq .Type \"APIKey\" }}\n\t\t\t\tsc := security.APIKeyScheme{\n\t\t\t\t\tName: {{ printf \"%q\" .SchemeName }},\n\t\t\t\t\tScopes: []string{ {{- range .Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t\tRequiredScopes: []string{ {{- range $r.Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t}\n\t\t\t\t{{- if $s.CredPointer }}\n\t\t\t\tvar key string\n\t\t\t\tif {{ $payload }}.{{ $s.CredField }} != nil {\n\t\t\t\t\tkey = *{{ $payload }}.{{ $s.CredField }}\n\t\t\t\t}\n\t\t\t\t{{- end }}\n\t\t\t\tctx, err = auth{{ .Type }}Fn(ctx, {{ if $s.CredPointer }}key{{ else }}{{ $payload }}.{{ $s.CredField }}{{ end }}, &sc)\n\n\t\t\t{{- else if eq .Type \"JWT\" }}\n\t\t\t\tsc := security.JWTScheme{\n\t\t\t\t\tName: {{ printf \"%q\" .SchemeName }},\n\t\t\t\t\tScopes: []string{ {{- range .Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t\tRequiredScopes: []string{ {{- range $r.Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t}\n\t\t\t\t{{- if $s.CredPointer }}\n\t\t\t\tvar token string\n\t\t\t\tif {{ $payload }}.{{ $s.CredField }} != nil {\n\t\t\t\t\ttoken = *{{ $payload }}.{{ $s.CredField }}\n\t\t\t\t}\n\t\t\t\t{{- end }}\n\t\t\t\tctx, err = auth{{ .Type }}Fn(ctx, {{ if $s.CredPointer }}token{{ else }}{{ $payload }}.{{ $s.CredField }}{{ end }}, &sc)\n\n\t\t\t{{- else if eq .Type \"OAuth2\" }}\n\t\t\t\tsc := security.OAuth2Scheme{\n\t\t\t\t\tName: {{ printf \"%q\" .SchemeName }},\n\t\t\t\t\tScopes: []string{ {{- range .Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t\tRequiredScopes: []string{ {{- range $r.Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t\t{{- if .Flows }}\n\t\t\t\t\tFlows: []*security.OAuthFlow{\n\t\t\t\t\t\t{{- range .Flows }}\n\t\t\t\t\t\t&security.OAuthFlow{\n\t\t\t\t\t\t\tType: \"{{ .Type }}\",\n\t\t\t\t\t\t\t{{- if .AuthorizationURL }}\n\t\t\t\t\t\t\tAuthorizationURL: {{ printf \"%q\" .AuthorizationURL }},\n\t\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t\t{{- if .TokenURL }}\n\t\t\t\t\t\t\tTokenURL: {{ printf \"%q\" .TokenURL }},\n\t\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t\t{{- if .RefreshURL }}\n\t\t\t\t\t\t\tRefreshURL: {{ printf \"%q\" .RefreshURL }},\n\t\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t},\n\t\t\t\t\t{{- end }}\n\t\t\t\t}\n\t\t\t\t{{- if $s.CredPointer }}\n\t\t\t\tvar token string\n\t\t\t\tif {{ $payload }}.{{ $s.CredField }} != nil {\n\t\t\t\t\ttoken = *{{ $payload }}.{{ $s.CredField }}\n\t\t\t\t}\n\t\t\t\t{{- end }}\n\t\t\t\tctx, err = auth{{ .Type }}Fn(ctx, {{ if $s.CredPointer }}token{{ else }}{{ $payload }}.{{ $s.CredField }}{{ end }}, &sc)\n\n\t\t\t{{- end }}\n\t\t\t{{- if ne $sidx 0 }}\n\t\t\t\t}\n\t\t\t{{- end }}\n\t\t{{- end }}\n\t\t{{- if ne $ridx 0 }}\n\t\t}\n\t\t{{- end }}\n\t{{- end }}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n{{- end }}\n{{- if .ServerStream }}\n\treturn nil, s.{{ .VarName }}(ctx, {{ if .PayloadRef }}{{ $payload }}, {{ end }}ep.Stream)\n{{- else if .SkipRequestBodyEncodeDecode }}\n\t{{- if .SkipResponseBodyEncodeDecode }}\n\t{{ if .ResultRef }}res, {{ end }}body, err := s.{{ .VarName }}(ctx, {{ if .PayloadRef }}ep.Payload, {{ end }}ep.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &{{ .ResponseStruct }}{ {{ if .ResultRef }}Result: res, {{ end }}Body: body }, nil\n\t{{- else }}\n\treturn {{ if not .ResultRef }}nil, {{ end }}s.{{ .VarName }}(ctx, {{ if .PayloadRef }}ep.Payload, {{ end }}ep.Body)\n\t{{- end }}\n{{- else if .ViewedResult }}\n\t\tres,{{ if not .ViewedResult.ViewName }} view,{{ end }} err := s.{{ .VarName }}(ctx{{ if .PayloadRef }}, {{ $payload }}{{ end }})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvres := {{ $.ViewedResult.Init.Name }}(res, {{ if .ViewedResult.ViewName }}{{ printf \"%q\" .ViewedResult.ViewName }}{{ else }}view{{ end }})\n\t\treturn vres, nil\n{{- else }}\n\t{{- if .SkipResponseBodyEncodeDecode }}\n\t{{ if .ResultRef }}res, {{ end }}body, err := s.{{ .VarName }}(ctx{{ if .PayloadRef }}, {{ $payload}}{{ end }})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &{{ .ResponseStruct }}{ {{ if .ResultRef }}Result: res, {{ end }}Body: body }, nil\n\t{{- else }}\n\treturn {{ if not .ResultRef }}nil, {{ end }}s.{{ .VarName }}(ctx{{ if .PayloadRef }}, {{ $payload }}{{ end }})\n\t{{- end }}\n{{- end }}\n\t}\n}\n`\n\n\/\/ input: endpointMethodData\nconst serviceEndpointsUseT = `{{ printf \"Use applies the given middleware to all the %q service endpoints.\" .Name | comment }}\nfunc (e *{{ .VarName }}) Use(m func(goa.Endpoint) goa.Endpoint) {\n{{- range .Methods }}\n\te.{{ .VarName }} = m(e.{{ .VarName }})\n{{- end }}\n}\n`\n<commit_msg>Properly handle result types with multiple views and SkipRequestBodyDecodeEncode (#2543)<commit_after>package service\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"goa.design\/goa\/v3\/codegen\"\n\t\"goa.design\/goa\/v3\/expr\"\n)\n\ntype (\n\t\/\/ endpointsData contains the data necessary to render the\n\t\/\/ service endpoints struct template.\n\tendpointsData struct {\n\t\t\/\/ Name is the service name.\n\t\tName string\n\t\t\/\/ Description is the service description.\n\t\tDescription string\n\t\t\/\/ VarName is the endpoint struct name.\n\t\tVarName string\n\t\t\/\/ ClientVarName is the client struct name.\n\t\tClientVarName string\n\t\t\/\/ ServiceVarName is the service interface name.\n\t\tServiceVarName string\n\t\t\/\/ Methods lists the endpoint struct methods.\n\t\tMethods []*endpointMethodData\n\t\t\/\/ ClientInitArgs lists the arguments needed to instantiate the client.\n\t\tClientInitArgs string\n\t\t\/\/ Schemes contains the security schemes types used by the\n\t\t\/\/ all the endpoints.\n\t\tSchemes SchemesData\n\t}\n\n\t\/\/ endpointMethodData describes a single endpoint method.\n\tendpointMethodData struct {\n\t\t*MethodData\n\t\t\/\/ ArgName is the name of the argument used to initialize the client\n\t\t\/\/ struct method field.\n\t\tArgName string\n\t\t\/\/ ClientVarName is the corresponding client struct field name.\n\t\tClientVarName string\n\t\t\/\/ ServiceName is the name of the owner service.\n\t\tServiceName string\n\t\t\/\/ ServiceVarName is the name of the owner service Go interface.\n\t\tServiceVarName string\n\t}\n)\n\nconst (\n\t\/\/ endpointsStructName is the name of the generated endpoints data\n\t\/\/ structure.\n\tendpointsStructName = \"Endpoints\"\n\n\t\/\/ serviceInterfaceName is the name of the generated service interface.\n\tserviceInterfaceName = \"Service\"\n)\n\n\/\/ EndpointFile returns the endpoint file for the given service.\nfunc EndpointFile(genpkg string, service *expr.ServiceExpr) *codegen.File {\n\tsvc := Services.Get(service.Name)\n\tsvcName := codegen.SnakeCase(svc.VarName)\n\tpath := filepath.Join(codegen.Gendir, svcName, \"endpoints.go\")\n\tdata := endpointData(service)\n\tvar (\n\t\tsections []*codegen.SectionTemplate\n\t)\n\t{\n\t\theader := codegen.Header(service.Name+\" endpoints\", svc.PkgName,\n\t\t\t[]*codegen.ImportSpec{\n\t\t\t\t{Path: \"context\"},\n\t\t\t\t{Path: \"io\"},\n\t\t\t\t{Path: \"fmt\"},\n\t\t\t\tcodegen.GoaImport(\"\"),\n\t\t\t\tcodegen.GoaImport(\"security\"),\n\t\t\t\t{Path: genpkg + \"\/\" + svcName + \"\/\" + \"views\", Name: svc.ViewsPkg},\n\t\t\t})\n\t\tdef := &codegen.SectionTemplate{\n\t\t\tName:   \"endpoints-struct\",\n\t\t\tSource: serviceEndpointsT,\n\t\t\tData:   data,\n\t\t}\n\t\tsections = []*codegen.SectionTemplate{header, def}\n\t\tfor _, m := range data.Methods {\n\t\t\tif m.ServerStream != nil {\n\t\t\t\tsections = append(sections, &codegen.SectionTemplate{\n\t\t\t\t\tName:   \"endpoint-input-struct\",\n\t\t\t\t\tSource: serviceEndpointStreamStructT,\n\t\t\t\t\tData:   m,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif m.SkipRequestBodyEncodeDecode {\n\t\t\t\tsections = append(sections, &codegen.SectionTemplate{\n\t\t\t\t\tName:   \"request-body-struct\",\n\t\t\t\t\tSource: serviceRequestBodyStructT,\n\t\t\t\t\tData:   m,\n\t\t\t\t})\n\t\t\t}\n\t\t\tif m.SkipResponseBodyEncodeDecode {\n\t\t\t\tsections = append(sections, &codegen.SectionTemplate{\n\t\t\t\t\tName:   \"response-body-struct\",\n\t\t\t\t\tSource: serviceResponseBodyStructT,\n\t\t\t\t\tData:   m,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tsections = append(sections, &codegen.SectionTemplate{\n\t\t\tName:   \"endpoints-init\",\n\t\t\tSource: serviceEndpointsInitT,\n\t\t\tData:   data,\n\t\t})\n\t\tsections = append(sections, &codegen.SectionTemplate{\n\t\t\tName:   \"endpoints-use\",\n\t\t\tSource: serviceEndpointsUseT,\n\t\t\tData:   data,\n\t\t})\n\t\tfor _, m := range data.Methods {\n\t\t\tsections = append(sections, &codegen.SectionTemplate{\n\t\t\t\tName:    \"endpoint-method\",\n\t\t\t\tSource:  serviceEndpointMethodT,\n\t\t\t\tData:    m,\n\t\t\t\tFuncMap: map[string]interface{}{\"payloadVar\": payloadVar},\n\t\t\t})\n\t\t}\n\t}\n\n\treturn &codegen.File{Path: path, SectionTemplates: sections}\n}\n\nfunc endpointData(service *expr.ServiceExpr) *endpointsData {\n\tsvc := Services.Get(service.Name)\n\tmethods := make([]*endpointMethodData, len(svc.Methods))\n\tnames := make([]string, len(svc.Methods))\n\tfor i, m := range svc.Methods {\n\t\tmethods[i] = &endpointMethodData{\n\t\t\tMethodData:     m,\n\t\t\tArgName:        codegen.Goify(m.VarName, false),\n\t\t\tServiceName:    svc.Name,\n\t\t\tServiceVarName: serviceInterfaceName,\n\t\t\tClientVarName:  clientStructName,\n\t\t}\n\t\tnames[i] = codegen.Goify(m.VarName, false)\n\t}\n\tdesc := fmt.Sprintf(\"%s wraps the %q service endpoints.\", endpointsStructName, service.Name)\n\treturn &endpointsData{\n\t\tName:           service.Name,\n\t\tDescription:    desc,\n\t\tVarName:        endpointsStructName,\n\t\tClientVarName:  clientStructName,\n\t\tServiceVarName: serviceInterfaceName,\n\t\tClientInitArgs: strings.Join(names, \", \"),\n\t\tMethods:        methods,\n\t\tSchemes:        svc.Schemes,\n\t}\n}\n\nfunc payloadVar(e *endpointMethodData) string {\n\tif e.ServerStream != nil || e.SkipRequestBodyEncodeDecode {\n\t\treturn \"ep.Payload\"\n\t}\n\treturn \"p\"\n}\n\n\/\/ input: endpointsData\nconst serviceEndpointsT = `{{ comment .Description }}\ntype {{ .VarName }} struct {\n{{- range .Methods}}\n\t{{ .VarName }} goa.Endpoint\n{{- end }}\n}\n`\n\n\/\/ input: endpointsData\nconst serviceEndpointsInitT = `{{ printf \"New%s wraps the methods of the %q service with endpoints.\" .VarName .Name | comment }}\nfunc New{{ .VarName }}(s {{ .ServiceVarName }}) *{{ .VarName }} {\n{{- if .Schemes }}\n\t\/\/ Casting service to Auther interface\n\ta := s.(Auther)\n{{- end }}\n\treturn &{{ .VarName }}{\n{{- range .Methods }}\n\t\t{{ .VarName }}: New{{ .VarName }}Endpoint(s{{ range .Schemes }}, a.{{ .Type }}Auth{{ end }}),\n{{- end }}\n\t}\n}\n`\n\n\/\/ input: endpointMethodData\nconst serviceEndpointStreamStructT = `{{ printf \"%s holds both the payload and the server stream of the %q method.\" .ServerStream.EndpointStruct .Name | comment }}\ntype {{ .ServerStream.EndpointStruct }} struct {\n{{- if .PayloadRef }}\n\t{{ comment \"Payload is the method payload.\" }}\n\tPayload {{ .PayloadRef }}\n{{- end }}\n\t{{ printf \"Stream is the server stream used by the %q method to send data.\" .Name | comment }}\n\tStream {{ .ServerStream.Interface }}\n}\n`\n\n\/\/ input: endpointMethodData\nconst serviceRequestBodyStructT = `{{ printf \"%s holds both the payload and the HTTP request body reader of the %q method.\" .RequestStruct .Name | comment }}\ntype {{ .RequestStruct }} struct {\n{{- if .PayloadRef }}\n\t{{ comment \"Payload is the method payload.\" }}\n\tPayload {{ .PayloadRef }}\n{{- end }}\n\t{{ comment \"Body streams the HTTP request body.\" }}\n\tBody io.ReadCloser\n}\n`\n\n\/\/ input: endpointMethodData\nconst serviceResponseBodyStructT = `{{ printf \"%s holds both the result and the HTTP response body reader of the %q method.\" .ResponseStruct .Name | comment }}\ntype {{ .ResponseStruct }} struct {\n{{- if .ResultRef }}\n\t{{ comment \"Result is the method result.\" }}\n\tResult {{ .ResultRef }}\n{{- end }}\n\t{{ comment \"Body streams the HTTP response body.\" }}\n\tBody io.ReadCloser\n}\n`\n\n\/\/ input: endpointMethodData\nconst serviceEndpointMethodT = `{{ printf \"New%sEndpoint returns an endpoint function that calls the method %q of service %q.\" .VarName .Name .ServiceName | comment }}\nfunc New{{ .VarName }}Endpoint(s {{ .ServiceVarName }}{{ range .Schemes }}, auth{{ .Type }}Fn security.Auth{{ .Type }}Func{{ end }}) goa.Endpoint {\n\treturn func(ctx context.Context, req interface{}) (interface{}, error) {\n{{- if or .ServerStream }}\n\t\tep := req.(*{{ .ServerStream.EndpointStruct }})\n{{- else if .SkipRequestBodyEncodeDecode }}\n\t\tep := req.(*{{ .RequestStruct }})\n{{- else if .PayloadRef }}\n\t\tp := req.({{ .PayloadRef }})\n{{- end }}\n{{- $payload := payloadVar . }}\n{{- if .Requirements }}\n\t\tvar err error\n\t{{- range $ridx, $r := .Requirements }}\n\t\t{{- if ne $ridx 0 }}\n\t\tif err != nil {\n\t\t{{- end }}\n\t\t{{- range $sidx, $s := .Schemes }}\n\t\t\t{{- if ne $sidx 0 }}\n\t\t\tif err == nil {\n\t\t\t{{- end }}\n\t\t\t{{- if eq .Type \"Basic\" }}\n\t\t\t\tsc := security.BasicScheme{\n\t\t\t\t\tName: {{ printf \"%q\" .SchemeName }},\n\t\t\t\t\tScopes: []string{ {{- range .Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t\tRequiredScopes: []string{ {{- range $r.Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t}\n\t\t\t\t{{- if .UsernamePointer }}\n\t\t\t\tvar user string\n\t\t\t\tif {{ $payload }}.{{ .UsernameField }} != nil {\n\t\t\t\t\tuser = *{{ $payload }}.{{ .UsernameField }}\n\t\t\t\t}\n\t\t\t\t{{- end }}\n\t\t\t\t{{- if .PasswordPointer }}\n\t\t\t\tvar pass string\n\t\t\t\tif {{ $payload }}.{{ .PasswordField }} != nil {\n\t\t\t\t\tpass = *{{ $payload }}.{{ .PasswordField }}\n\t\t\t\t}\n\t\t\t\t{{- end }}\n\t\t\t\tctx, err = auth{{ .Type }}Fn(ctx, {{ if .UsernamePointer }}user{{ else }}{{ $payload }}.{{ .UsernameField }}{{ end }},\n\t\t\t\t\t{{- if .PasswordPointer }}pass{{ else }}{{ $payload }}.{{ .PasswordField }}{{ end }}, &sc)\n\n\t\t\t{{- else if eq .Type \"APIKey\" }}\n\t\t\t\tsc := security.APIKeyScheme{\n\t\t\t\t\tName: {{ printf \"%q\" .SchemeName }},\n\t\t\t\t\tScopes: []string{ {{- range .Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t\tRequiredScopes: []string{ {{- range $r.Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t}\n\t\t\t\t{{- if $s.CredPointer }}\n\t\t\t\tvar key string\n\t\t\t\tif {{ $payload }}.{{ $s.CredField }} != nil {\n\t\t\t\t\tkey = *{{ $payload }}.{{ $s.CredField }}\n\t\t\t\t}\n\t\t\t\t{{- end }}\n\t\t\t\tctx, err = auth{{ .Type }}Fn(ctx, {{ if $s.CredPointer }}key{{ else }}{{ $payload }}.{{ $s.CredField }}{{ end }}, &sc)\n\n\t\t\t{{- else if eq .Type \"JWT\" }}\n\t\t\t\tsc := security.JWTScheme{\n\t\t\t\t\tName: {{ printf \"%q\" .SchemeName }},\n\t\t\t\t\tScopes: []string{ {{- range .Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t\tRequiredScopes: []string{ {{- range $r.Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t}\n\t\t\t\t{{- if $s.CredPointer }}\n\t\t\t\tvar token string\n\t\t\t\tif {{ $payload }}.{{ $s.CredField }} != nil {\n\t\t\t\t\ttoken = *{{ $payload }}.{{ $s.CredField }}\n\t\t\t\t}\n\t\t\t\t{{- end }}\n\t\t\t\tctx, err = auth{{ .Type }}Fn(ctx, {{ if $s.CredPointer }}token{{ else }}{{ $payload }}.{{ $s.CredField }}{{ end }}, &sc)\n\n\t\t\t{{- else if eq .Type \"OAuth2\" }}\n\t\t\t\tsc := security.OAuth2Scheme{\n\t\t\t\t\tName: {{ printf \"%q\" .SchemeName }},\n\t\t\t\t\tScopes: []string{ {{- range .Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t\tRequiredScopes: []string{ {{- range $r.Scopes }}{{ printf \"%q\" . }}, {{ end }} },\n\t\t\t\t\t{{- if .Flows }}\n\t\t\t\t\tFlows: []*security.OAuthFlow{\n\t\t\t\t\t\t{{- range .Flows }}\n\t\t\t\t\t\t&security.OAuthFlow{\n\t\t\t\t\t\t\tType: \"{{ .Type }}\",\n\t\t\t\t\t\t\t{{- if .AuthorizationURL }}\n\t\t\t\t\t\t\tAuthorizationURL: {{ printf \"%q\" .AuthorizationURL }},\n\t\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t\t{{- if .TokenURL }}\n\t\t\t\t\t\t\tTokenURL: {{ printf \"%q\" .TokenURL }},\n\t\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t\t{{- if .RefreshURL }}\n\t\t\t\t\t\t\tRefreshURL: {{ printf \"%q\" .RefreshURL }},\n\t\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t},\n\t\t\t\t\t{{- end }}\n\t\t\t\t}\n\t\t\t\t{{- if $s.CredPointer }}\n\t\t\t\tvar token string\n\t\t\t\tif {{ $payload }}.{{ $s.CredField }} != nil {\n\t\t\t\t\ttoken = *{{ $payload }}.{{ $s.CredField }}\n\t\t\t\t}\n\t\t\t\t{{- end }}\n\t\t\t\tctx, err = auth{{ .Type }}Fn(ctx, {{ if $s.CredPointer }}token{{ else }}{{ $payload }}.{{ $s.CredField }}{{ end }}, &sc)\n\n\t\t\t{{- end }}\n\t\t\t{{- if ne $sidx 0 }}\n\t\t\t\t}\n\t\t\t{{- end }}\n\t\t{{- end }}\n\t\t{{- if ne $ridx 0 }}\n\t\t}\n\t\t{{- end }}\n\t{{- end }}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n{{- end }}\n{{- if .ServerStream }}\n\treturn nil, s.{{ .VarName }}(ctx, {{ if .PayloadRef }}{{ $payload }}, {{ end }}ep.Stream)\n{{- else if .SkipRequestBodyEncodeDecode }}\n\t{{- if .SkipResponseBodyEncodeDecode }}\n\t{{ if .ResultRef }}res, {{ end }}body, err := s.{{ .VarName }}(ctx, {{ if .PayloadRef }}ep.Payload, {{ end }}ep.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &{{ .ResponseStruct }}{ {{ if .ResultRef }}Result: res, {{ end }}Body: body }, nil\n\t{{- else if .ViewedResult }}\n\tres, {{ if not .ViewedResult.ViewName }}view, {{ end }}err := s.{{ .VarName }}(ctx, {{ if .PayloadRef }}ep.Payload, {{ end }}ep.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvres := {{ $.ViewedResult.Init.Name }}(res, {{ if .ViewedResult.ViewName }}{{ printf \"%q\" .ViewedResult.ViewName }}{{ else }}view{{ end }})\n\treturn vres, nil\n\t{{- else }}\n\treturn {{ if not .ResultRef }}nil, {{ end }}s.{{ .VarName }}(ctx, {{ if .PayloadRef }}ep.Payload, {{ end }}ep.Body)\n\t{{- end }}\n{{- else if .ViewedResult }}\n\tres, {{ if not .ViewedResult.ViewName }}view, {{ end }}err := s.{{ .VarName }}(ctx{{ if .PayloadRef }}, {{ $payload }}{{ end }})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvres := {{ $.ViewedResult.Init.Name }}(res, {{ if .ViewedResult.ViewName }}{{ printf \"%q\" .ViewedResult.ViewName }}{{ else }}view{{ end }})\n\treturn vres, nil\n{{- else if .SkipResponseBodyEncodeDecode }}\n\t{{ if .ResultRef }}res, {{ end }}body, err := s.{{ .VarName }}(ctx{{ if .PayloadRef }}, {{ $payload}}{{ end }})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &{{ .ResponseStruct }}{ {{ if .ResultRef }}Result: res, {{ end }}Body: body }, nil\n{{- else }}\n\treturn {{ if not .ResultRef }}nil, {{ end }}s.{{ .VarName }}(ctx{{ if .PayloadRef }}, {{ $payload }}{{ end }})\n{{- end }}\n\t}\n}\n`\n\n\/\/ input: endpointMethodData\nconst serviceEndpointsUseT = `{{ printf \"Use applies the given middleware to all the %q service endpoints.\" .Name | comment }}\nfunc (e *{{ .VarName }}) Use(m func(goa.Endpoint) goa.Endpoint) {\n{{- range .Methods }}\n\te.{{ .VarName }} = m(e.{{ .VarName }})\n{{- end }}\n}\n`\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/timeredbull\/commandmocker\"\n\t\"github.com\/timeredbull\/tsuru\/api\/app\"\n\t\"io\/ioutil\"\n\t. \"launchpad.net\/gocheck\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\nfunc getOutput() *output {\n\treturn &output{\n\t\tServices: map[string]Service{\n\t\t\t\"umaappqq\": Service{\n\t\t\t\tUnits: map[string]app.Unit{\n\t\t\t\t\t\"umaappqq\/0\": app.Unit{\n\t\t\t\t\t\tAgentState: \"started\",\n\t\t\t\t\t\tMachine:    1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tMachines: map[int]interface{}{\n\t\t\t0: map[interface{}]interface{}{\n\t\t\t\t\"dns-name\":       \"192.168.0.10\",\n\t\t\t\t\"instance-id\":    \"i-00000zz6\",\n\t\t\t\t\"instance-state\": \"running\",\n\t\t\t\t\"agent-state\":    \"running\",\n\t\t\t},\n\t\t\t1: map[interface{}]interface{}{\n\t\t\t\t\"dns-name\":       \"192.168.0.11\",\n\t\t\t\t\"instance-id\":    \"i-00000zz7\",\n\t\t\t\t\"instance-state\": \"running\",\n\t\t\t\t\"agent-state\":    \"running\",\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc getApp(c *C) *app.App {\n\ta := &app.App{Name: \"umaappqq\", State: \"STOPPED\"}\n\terr := a.Create()\n\tc.Assert(err, IsNil)\n\treturn a\n}\n\nfunc (s *S) TestUpdate(c *C) {\n\ta := getApp(c)\n\tout := getOutput()\n\tupdate(out)\n\n\terr := a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(a.State, Equals, \"started\")\n\tc.Assert(a.Units[0].Ip, Equals, \"192.168.0.11\")\n\tc.Assert(a.Units[0].Machine, Equals, 1)\n\tc.Assert(a.Units[0].InstanceState, Equals, \"running\")\n\tc.Assert(a.Units[0].MachineAgentState, Equals, \"running\")\n\tc.Assert(a.Units[0].AgentState, Equals, \"started\")\n\tc.Assert(a.Units[0].InstanceId, Equals, \"i-00000zz7\")\n\n\ta.Destroy()\n}\n\nfunc (s *S) TestUpdateWithMultipleUnits(c *C) {\n\ta := getApp(c)\n\tout := getOutput()\n\tu := app.Unit{AgentState: \"started\", Machine: 2}\n\tout.Services[\"umaappqq\"].Units[\"umaappqq\/1\"] = u\n\tout.Machines[2] = map[interface{}]interface{}{\n\t\t\"dns-name\":       \"192.168.0.12\",\n\t\t\"instance-id\":    \"i-00000zz8\",\n\t\t\"instance-state\": \"running\",\n\t\t\"agent-state\":    \"running\",\n\t}\n\tupdate(out)\n\terr := a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(len(a.Units), Equals, 2)\n\tfor _, u = range a.Units {\n\t\tif u.Machine == 2 {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.Assert(u.Ip, Equals, \"192.168.0.12\")\n\tc.Assert(u.InstanceState, Equals, \"running\")\n\tc.Assert(u.AgentState, Equals, \"started\")\n\tc.Assert(u.MachineAgentState, Equals, \"running\")\n}\n\nfunc (s *S) TestUpdateWithDownMachine(c *C) {\n\ta := app.App{Name: \"barduscoapp\", State: \"STOPPED\"}\n\terr := a.Create()\n\tc.Assert(err, IsNil)\n\tfile, _ := os.Open(filepath.Join(\"testdata\", \"broken-output.yaml\"))\n\tjujuOutput, _ := ioutil.ReadAll(file)\n\tfile.Close()\n\tout := parse(jujuOutput)\n\tupdate(out)\n\terr = a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(a.State, Equals, \"creating\")\n}\n\nfunc (s *S) TestUpdateTwice(c *C) {\n\ta := getApp(c)\n\tdefer a.Destroy()\n\tout := getOutput()\n\tupdate(out)\n\terr := a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(a.State, Equals, \"started\")\n\tc.Assert(a.Units[0].Ip, Equals, \"192.168.0.11\")\n\tc.Assert(a.Units[0].Machine, Equals, 1)\n\tc.Assert(a.Units[0].InstanceState, Equals, \"running\")\n\tc.Assert(a.Units[0].MachineAgentState, Equals, \"running\")\n\tc.Assert(a.Units[0].AgentState, Equals, \"started\")\n\tupdate(out)\n\terr = a.Get()\n\tc.Assert(len(a.Units), Equals, 1)\n}\n\nfunc (s *S) TestUpdateWithMultipleApps(c *C) {\n\tappDicts := []map[string]string{\n\t\tmap[string]string{\n\t\t\t\"name\": \"andrewzito3\",\n\t\t\t\"ip\":   \"10.10.10.163\",\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"name\": \"flaviapp\",\n\t\t\t\"ip\":   \"10.10.10.208\",\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"name\": \"mysqlapi\",\n\t\t\t\"ip\":   \"10.10.10.131\",\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"name\": \"teste_api_semantica\",\n\t\t\t\"ip\":   \"10.10.10.189\",\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"name\": \"xikin\",\n\t\t\t\"ip\":   \"10.10.10.168\",\n\t\t},\n\t}\n\tapps := make([]app.App, len(appDicts))\n\tfor i, appDict := range appDicts {\n\t\ta := app.App{Name: appDict[\"name\"]}\n\t\terr := a.Create()\n\t\tc.Assert(err, IsNil)\n\t\tapps[i] = a\n\t}\n\tjujuOutput, err := ioutil.ReadFile(filepath.Join(\"testdata\", \"multiple-apps.yaml\"))\n\tc.Assert(err, IsNil)\n\tdata := parse(jujuOutput)\n\tupdate(data)\n\tfor _, appDict := range appDicts {\n\t\ta := app.App{Name: appDict[\"name\"]}\n\t\terr := a.Get()\n\t\tc.Assert(err, IsNil)\n\t\tc.Assert(a.Units[0].Ip, Equals, appDict[\"ip\"])\n\t}\n}\n\nfunc (s *S) TestParser(c *C) {\n\tfile, _ := os.Open(filepath.Join(\"testdata\", \"output.yaml\"))\n\tjujuOutput, _ := ioutil.ReadAll(file)\n\tfile.Close()\n\texpected := getOutput()\n\tc.Assert(parse(jujuOutput), DeepEquals, expected)\n}\n\nfunc (s *S) TestCollect(c *C) {\n\ta := app.App{JujuEnv: \"zeta\"}\n\ttmpdir, err := commandmocker.Add(\"juju\", \"$*\")\n\tc.Assert(err, IsNil)\n\tdefer commandmocker.Remove(tmpdir)\n\tout, err := collect(&a)\n\tc.Assert(err, IsNil)\n\tc.Assert(string(out), Equals, \"status -e zeta\")\n}\n\nfunc (s *S) TestAppStatusMachineAgentPending(c *C) {\n\tu := app.Unit{MachineAgentState: \"pending\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"creating\")\n}\n\nfunc (s *S) TestAppStatusInstanceStatePending(c *C) {\n\tu := app.Unit{InstanceState: \"pending\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"creating\")\n}\n\nfunc (s *S) TestAppStatusInstanceStateError(c *C) {\n\tu := app.Unit{InstanceState: \"error\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"error\")\n}\n\nfunc (s *S) TestAppStatusAgentStatePending(c *C) {\n\tu := app.Unit{AgentState: \"pending\", InstanceState: \"\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"creating\")\n}\n\nfunc (s *S) TestAppStatusAgentAndInstanceRunning(c *C) {\n\tu := app.Unit{AgentState: \"started\", InstanceState: \"running\", MachineAgentState: \"running\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"started\")\n}\n\nfunc (s *S) TestAppStatusMachineAgentRunningAndInstanceAndAgentPending(c *C) {\n\tu := app.Unit{AgentState: \"pending\", InstanceState: \"running\", MachineAgentState: \"running\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"installing\")\n}\n\nfunc (s *S) TestAppStatusInstancePending(c *C) {\n\tu := app.Unit{AgentState: \"not-started\", InstanceState: \"pending\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"creating\")\n}\n\nfunc (s *S) TestAppStatusInstancePendingWhenMachineStateIsRunning(c *C) {\n\tu := app.Unit{AgentState: \"not-started\", MachineAgentState: \"running\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"creating\")\n}\n\nfunc (s *S) TestAppStatePending(c *C) {\n\tu := app.Unit{MachineAgentState: \"some-state\", AgentState: \"some-state\", InstanceState: \"some-other-state\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"pending\")\n}\n<commit_msg>collector: using ioutil.ReadFile instead of os.Open + ioutil.ReadAll<commit_after>package main\n\nimport (\n\t\"github.com\/timeredbull\/commandmocker\"\n\t\"github.com\/timeredbull\/tsuru\/api\/app\"\n\t\"io\/ioutil\"\n\t. \"launchpad.net\/gocheck\"\n\t\"path\/filepath\"\n)\n\nfunc getOutput() *output {\n\treturn &output{\n\t\tServices: map[string]Service{\n\t\t\t\"umaappqq\": Service{\n\t\t\t\tUnits: map[string]app.Unit{\n\t\t\t\t\t\"umaappqq\/0\": app.Unit{\n\t\t\t\t\t\tAgentState: \"started\",\n\t\t\t\t\t\tMachine:    1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tMachines: map[int]interface{}{\n\t\t\t0: map[interface{}]interface{}{\n\t\t\t\t\"dns-name\":       \"192.168.0.10\",\n\t\t\t\t\"instance-id\":    \"i-00000zz6\",\n\t\t\t\t\"instance-state\": \"running\",\n\t\t\t\t\"agent-state\":    \"running\",\n\t\t\t},\n\t\t\t1: map[interface{}]interface{}{\n\t\t\t\t\"dns-name\":       \"192.168.0.11\",\n\t\t\t\t\"instance-id\":    \"i-00000zz7\",\n\t\t\t\t\"instance-state\": \"running\",\n\t\t\t\t\"agent-state\":    \"running\",\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc getApp(c *C) *app.App {\n\ta := &app.App{Name: \"umaappqq\", State: \"STOPPED\"}\n\terr := a.Create()\n\tc.Assert(err, IsNil)\n\treturn a\n}\n\nfunc (s *S) TestUpdate(c *C) {\n\ta := getApp(c)\n\tout := getOutput()\n\tupdate(out)\n\n\terr := a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(a.State, Equals, \"started\")\n\tc.Assert(a.Units[0].Ip, Equals, \"192.168.0.11\")\n\tc.Assert(a.Units[0].Machine, Equals, 1)\n\tc.Assert(a.Units[0].InstanceState, Equals, \"running\")\n\tc.Assert(a.Units[0].MachineAgentState, Equals, \"running\")\n\tc.Assert(a.Units[0].AgentState, Equals, \"started\")\n\tc.Assert(a.Units[0].InstanceId, Equals, \"i-00000zz7\")\n\n\ta.Destroy()\n}\n\nfunc (s *S) TestUpdateWithMultipleUnits(c *C) {\n\ta := getApp(c)\n\tout := getOutput()\n\tu := app.Unit{AgentState: \"started\", Machine: 2}\n\tout.Services[\"umaappqq\"].Units[\"umaappqq\/1\"] = u\n\tout.Machines[2] = map[interface{}]interface{}{\n\t\t\"dns-name\":       \"192.168.0.12\",\n\t\t\"instance-id\":    \"i-00000zz8\",\n\t\t\"instance-state\": \"running\",\n\t\t\"agent-state\":    \"running\",\n\t}\n\tupdate(out)\n\terr := a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(len(a.Units), Equals, 2)\n\tfor _, u = range a.Units {\n\t\tif u.Machine == 2 {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.Assert(u.Ip, Equals, \"192.168.0.12\")\n\tc.Assert(u.InstanceState, Equals, \"running\")\n\tc.Assert(u.AgentState, Equals, \"started\")\n\tc.Assert(u.MachineAgentState, Equals, \"running\")\n}\n\nfunc (s *S) TestUpdateWithDownMachine(c *C) {\n\ta := app.App{Name: \"barduscoapp\", State: \"STOPPED\"}\n\terr := a.Create()\n\tc.Assert(err, IsNil)\n\tjujuOutput, err := ioutil.ReadFile(filepath.Join(\"testdata\", \"broken-output.yaml\"))\n\tc.Assert(err, IsNil)\n\tout := parse(jujuOutput)\n\tupdate(out)\n\terr = a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(a.State, Equals, \"creating\")\n}\n\nfunc (s *S) TestUpdateTwice(c *C) {\n\ta := getApp(c)\n\tdefer a.Destroy()\n\tout := getOutput()\n\tupdate(out)\n\terr := a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(a.State, Equals, \"started\")\n\tc.Assert(a.Units[0].Ip, Equals, \"192.168.0.11\")\n\tc.Assert(a.Units[0].Machine, Equals, 1)\n\tc.Assert(a.Units[0].InstanceState, Equals, \"running\")\n\tc.Assert(a.Units[0].MachineAgentState, Equals, \"running\")\n\tc.Assert(a.Units[0].AgentState, Equals, \"started\")\n\tupdate(out)\n\terr = a.Get()\n\tc.Assert(len(a.Units), Equals, 1)\n}\n\nfunc (s *S) TestUpdateWithMultipleApps(c *C) {\n\tappDicts := []map[string]string{\n\t\tmap[string]string{\n\t\t\t\"name\": \"andrewzito3\",\n\t\t\t\"ip\":   \"10.10.10.163\",\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"name\": \"flaviapp\",\n\t\t\t\"ip\":   \"10.10.10.208\",\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"name\": \"mysqlapi\",\n\t\t\t\"ip\":   \"10.10.10.131\",\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"name\": \"teste_api_semantica\",\n\t\t\t\"ip\":   \"10.10.10.189\",\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"name\": \"xikin\",\n\t\t\t\"ip\":   \"10.10.10.168\",\n\t\t},\n\t}\n\tapps := make([]app.App, len(appDicts))\n\tfor i, appDict := range appDicts {\n\t\ta := app.App{Name: appDict[\"name\"]}\n\t\terr := a.Create()\n\t\tc.Assert(err, IsNil)\n\t\tapps[i] = a\n\t}\n\tjujuOutput, err := ioutil.ReadFile(filepath.Join(\"testdata\", \"multiple-apps.yaml\"))\n\tc.Assert(err, IsNil)\n\tdata := parse(jujuOutput)\n\tupdate(data)\n\tfor _, appDict := range appDicts {\n\t\ta := app.App{Name: appDict[\"name\"]}\n\t\terr := a.Get()\n\t\tc.Assert(err, IsNil)\n\t\tc.Assert(a.Units[0].Ip, Equals, appDict[\"ip\"])\n\t}\n}\n\nfunc (s *S) TestParser(c *C) {\n\tjujuOutput, err := ioutil.ReadFile(filepath.Join(\"testdata\", \"output.yaml\"))\n\tc.Assert(err, IsNil)\n\texpected := getOutput()\n\tc.Assert(parse(jujuOutput), DeepEquals, expected)\n}\n\nfunc (s *S) TestCollect(c *C) {\n\ta := app.App{JujuEnv: \"zeta\"}\n\ttmpdir, err := commandmocker.Add(\"juju\", \"$*\")\n\tc.Assert(err, IsNil)\n\tdefer commandmocker.Remove(tmpdir)\n\tout, err := collect(&a)\n\tc.Assert(err, IsNil)\n\tc.Assert(string(out), Equals, \"status -e zeta\")\n}\n\nfunc (s *S) TestAppStatusMachineAgentPending(c *C) {\n\tu := app.Unit{MachineAgentState: \"pending\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"creating\")\n}\n\nfunc (s *S) TestAppStatusInstanceStatePending(c *C) {\n\tu := app.Unit{InstanceState: \"pending\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"creating\")\n}\n\nfunc (s *S) TestAppStatusInstanceStateError(c *C) {\n\tu := app.Unit{InstanceState: \"error\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"error\")\n}\n\nfunc (s *S) TestAppStatusAgentStatePending(c *C) {\n\tu := app.Unit{AgentState: \"pending\", InstanceState: \"\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"creating\")\n}\n\nfunc (s *S) TestAppStatusAgentAndInstanceRunning(c *C) {\n\tu := app.Unit{AgentState: \"started\", InstanceState: \"running\", MachineAgentState: \"running\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"started\")\n}\n\nfunc (s *S) TestAppStatusMachineAgentRunningAndInstanceAndAgentPending(c *C) {\n\tu := app.Unit{AgentState: \"pending\", InstanceState: \"running\", MachineAgentState: \"running\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"installing\")\n}\n\nfunc (s *S) TestAppStatusInstancePending(c *C) {\n\tu := app.Unit{AgentState: \"not-started\", InstanceState: \"pending\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"creating\")\n}\n\nfunc (s *S) TestAppStatusInstancePendingWhenMachineStateIsRunning(c *C) {\n\tu := app.Unit{AgentState: \"not-started\", MachineAgentState: \"running\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"creating\")\n}\n\nfunc (s *S) TestAppStatePending(c *C) {\n\tu := app.Unit{MachineAgentState: \"some-state\", AgentState: \"some-state\", InstanceState: \"some-other-state\"}\n\tst := appState(&u)\n\tc.Assert(st, Equals, \"pending\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n)\n\nvar (\n\terrLogger = log.New(os.Stderr, \"\", 0)\n)\n\nfunc main() {\n\tflag.Parse()\n\tconfig := loadConfig()\n\n\tcommand := remoteCommand()\n\n\tsessions := openSessions(config)\n\n\tsignals := make(chan os.Signal)\n\tsignal.Notify(signals, syscall.SIGINT)\n\n\tvar wg sync.WaitGroup\n\tdone := make(chan bool)\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-signals:\n\t\t\tbreak loop\n\t\tcase session, ok := <-sessions:\n\t\t\tif ok {\n\t\t\t\tdefer session.Session.Close()\n\t\t\t\thost := session.Host\n\t\t\t\terr := requestPty(session.Session)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrLogger.Print(prependHost(host, err.Error()))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\toutScanner := initScanner(session)\n\t\t\t\twg.Add(1)\n\t\t\t\tgo runRemote(command, session, &wg)\n\t\t\t\tgo output(host, outScanner)\n\t\t\t} else {\n\t\t\t\tgo func() {\n\t\t\t\t\twg.Wait()\n\t\t\t\t\tdone <- true\n\t\t\t\t}()\n\t\t\t\tsessions = nil\n\t\t\t}\n\t\tcase <-done:\n\t\t\tbreak loop\n\t\t}\n\t}\n}\n\nfunc remoteCommand() string {\n\treturn strings.Join(flag.Args()[1:], \" \")\n}\n\nfunc initScanner(session Session) *bufio.Scanner {\n\treader, _ := session.Session.StdoutPipe()\n\tscanner := bufio.NewScanner(reader)\n\treturn scanner\n}\n\nfunc runRemote(command string, session Session, wg *sync.WaitGroup) {\n\terr := session.Session.Run(command)\n\tif err != nil {\n\t\terrLogger.Print(prependHost(session.Host, err.Error()))\n\t}\n\twg.Done()\n}\n\nfunc output(host string, scanner *bufio.Scanner) {\n\tfor scanner.Scan() {\n\t\tfmt.Println(prependHost(host, scanner.Text()))\n\t}\n}\n\nfunc prependHost(host, str string) string {\n\treturn \"[\" + host + \"] \" + str\n}\n<commit_msg>print newline after interrupt is caught<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n)\n\nvar (\n\terrLogger = log.New(os.Stderr, \"\", 0)\n)\n\nfunc main() {\n\tflag.Parse()\n\tconfig := loadConfig()\n\n\tcommand := remoteCommand()\n\n\tsessions := openSessions(config)\n\n\tsignals := make(chan os.Signal)\n\tsignal.Notify(signals, syscall.SIGINT)\n\n\tvar wg sync.WaitGroup\n\tdone := make(chan bool)\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-signals:\n\t\t\tfmt.Println() \/\/ clean up for the next prompt\n\t\t\tbreak loop\n\t\tcase session, ok := <-sessions:\n\t\t\tif ok {\n\t\t\t\tdefer session.Session.Close()\n\t\t\t\thost := session.Host\n\t\t\t\terr := requestPty(session.Session)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrLogger.Print(prependHost(host, err.Error()))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\toutScanner := initScanner(session)\n\t\t\t\twg.Add(1)\n\t\t\t\tgo runRemote(command, session, &wg)\n\t\t\t\tgo output(host, outScanner)\n\t\t\t} else {\n\t\t\t\tgo func() {\n\t\t\t\t\twg.Wait()\n\t\t\t\t\tdone <- true\n\t\t\t\t}()\n\t\t\t\tsessions = nil\n\t\t\t}\n\t\tcase <-done:\n\t\t\tbreak loop\n\t\t}\n\t}\n}\n\nfunc remoteCommand() string {\n\treturn strings.Join(flag.Args()[1:], \" \")\n}\n\nfunc initScanner(session Session) *bufio.Scanner {\n\treader, _ := session.Session.StdoutPipe()\n\tscanner := bufio.NewScanner(reader)\n\treturn scanner\n}\n\nfunc runRemote(command string, session Session, wg *sync.WaitGroup) {\n\terr := session.Session.Run(command)\n\tif err != nil {\n\t\terrLogger.Print(prependHost(session.Host, err.Error()))\n\t}\n\twg.Done()\n}\n\nfunc output(host string, scanner *bufio.Scanner) {\n\tfor scanner.Scan() {\n\t\tfmt.Println(prependHost(host, scanner.Text()))\n\t}\n}\n\nfunc prependHost(host, str string) string {\n\treturn \"[\" + host + \"] \" + str\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011, 2012, 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage charm\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\n\t\"github.com\/juju\/schema\"\n\t\"gopkg.in\/yaml.v1\"\n\n\t\"gopkg.in\/juju\/charm.v4\/hooks\"\n)\n\n\/\/ RelationScope describes the scope of a relation.\ntype RelationScope string\n\n\/\/ Note that schema doesn't support custom string types,\n\/\/ so when we use these values in a schema.Checker,\n\/\/ we must store them as strings, not RelationScopes.\n\nconst (\n\tScopeGlobal    RelationScope = \"global\"\n\tScopeContainer RelationScope = \"container\"\n)\n\n\/\/ RelationRole defines the role of a relation.\ntype RelationRole string\n\nconst (\n\tRoleProvider RelationRole = \"provider\"\n\tRoleRequirer RelationRole = \"requirer\"\n\tRolePeer     RelationRole = \"peer\"\n)\n\n\/\/ Relation represents a single relation defined in the charm\n\/\/ metadata.yaml file.\ntype Relation struct {\n\tName      string\n\tRole      RelationRole\n\tInterface string\n\tOptional  bool\n\tLimit     int\n\tScope     RelationScope\n}\n\n\/\/ ImplementedBy returns whether the relation is implemented by the supplied charm.\nfunc (r Relation) ImplementedBy(ch Charm) bool {\n\tif r.IsImplicit() {\n\t\treturn true\n\t}\n\tvar m map[string]Relation\n\tswitch r.Role {\n\tcase RoleProvider:\n\t\tm = ch.Meta().Provides\n\tcase RoleRequirer:\n\t\tm = ch.Meta().Requires\n\tcase RolePeer:\n\t\tm = ch.Meta().Peers\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown relation role %q\", r.Role))\n\t}\n\trel, found := m[r.Name]\n\tif !found {\n\t\treturn false\n\t}\n\tif rel.Interface == r.Interface {\n\t\tswitch r.Scope {\n\t\tcase ScopeGlobal:\n\t\t\treturn rel.Scope != ScopeContainer\n\t\tcase ScopeContainer:\n\t\t\treturn true\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"unknown relation scope %q\", r.Scope))\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ IsImplicit returns whether the relation is supplied by juju itself,\n\/\/ rather than by a charm.\nfunc (r Relation) IsImplicit() bool {\n\treturn (r.Name == \"juju-info\" &&\n\t\tr.Interface == \"juju-info\" &&\n\t\tr.Role == RoleProvider)\n}\n\n\/\/ Meta represents all the known content that may be defined\n\/\/ within a charm's metadata.yaml file.\ntype Meta struct {\n\tName        string\n\tSummary     string\n\tDescription string\n\tSubordinate bool\n\tProvides    map[string]Relation `bson:\",omitempty\"`\n\tRequires    map[string]Relation `bson:\",omitempty\"`\n\tPeers       map[string]Relation `bson:\",omitempty\"`\n\tFormat      int                 `bson:\",omitempty\"`\n\tOldRevision int                 `bson:\",omitempty\"` \/\/ Obsolete\n\tCategories  []string            `bson:\",omitempty\"`\n\tTags        []string            `bson:\",omitempty\"`\n\tSeries      string              `bson:\",omitempty\"`\n}\n\nfunc generateRelationHooks(relName string, allHooks map[string]bool) {\n\tfor _, hookName := range hooks.RelationHooks() {\n\t\tallHooks[fmt.Sprintf(\"%s-%s\", relName, hookName)] = true\n\t}\n}\n\n\/\/ Hooks returns a map of all possible valid hooks, taking relations\n\/\/ into account. It's a map to enable fast lookups, and the value is\n\/\/ always true.\nfunc (m Meta) Hooks() map[string]bool {\n\tallHooks := make(map[string]bool)\n\t\/\/ Unit hooks\n\tfor _, hookName := range hooks.UnitHooks() {\n\t\tallHooks[string(hookName)] = true\n\t}\n\t\/\/ Relation hooks\n\tfor hookName := range m.Provides {\n\t\tgenerateRelationHooks(hookName, allHooks)\n\t}\n\tfor hookName := range m.Requires {\n\t\tgenerateRelationHooks(hookName, allHooks)\n\t}\n\tfor hookName := range m.Peers {\n\t\tgenerateRelationHooks(hookName, allHooks)\n\t}\n\treturn allHooks\n}\n\nfunc parseCategories(categories interface{}) []string {\n\tif categories == nil {\n\t\treturn nil\n\t}\n\tslice := categories.([]interface{})\n\tresult := make([]string, 0, len(slice))\n\tfor _, cat := range slice {\n\t\tresult = append(result, cat.(string))\n\t}\n\treturn result\n}\n\nfunc parseTags(tags interface{}) []string {\n\tif tags == nil {\n\t\treturn nil\n\t}\n\tslice := tags.([]interface{})\n\tresult := make([]string, 0, len(slice))\n\tfor _, cat := range slice {\n\t\t\/\/ todo : check if tag is whitelisted\n\t\tresult = append(result, cat.(string))\n\t}\n\treturn result\n}\n\n\/\/ Todo : cheks if tags are whitelisted or not.\nfunc checkTags(tags interface{}) error {\n\treturn nil\n}\n\n\/\/ ReadMeta reads the content of a metadata.yaml file and returns\n\/\/ its representation.\nfunc ReadMeta(r io.Reader) (meta *Meta, err error) {\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn\n\t}\n\traw := make(map[interface{}]interface{})\n\terr = yaml.Unmarshal(data, raw)\n\tif err != nil {\n\t\treturn\n\t}\n\tv, err := charmSchema.Coerce(raw, nil)\n\tif err != nil {\n\t\treturn nil, errors.New(\"metadata: \" + err.Error())\n\t}\n\tm := v.(map[string]interface{})\n\tmeta = &Meta{}\n\tmeta.Name = m[\"name\"].(string)\n\t\/\/ Schema decodes as int64, but the int range should be good\n\t\/\/ enough for revisions.\n\tmeta.Summary = m[\"summary\"].(string)\n\tmeta.Description = m[\"description\"].(string)\n\tmeta.Provides = parseRelations(m[\"provides\"], RoleProvider)\n\tmeta.Requires = parseRelations(m[\"requires\"], RoleRequirer)\n\tmeta.Peers = parseRelations(m[\"peers\"], RolePeer)\n\tmeta.Format = int(m[\"format\"].(int64))\n\tmeta.Categories = parseCategories(m[\"categories\"])\n\tmeta.Tags = parseTags(m[\"tags\"])\n\tif subordinate := m[\"subordinate\"]; subordinate != nil {\n\t\tmeta.Subordinate = subordinate.(bool)\n\t}\n\tif rev := m[\"revision\"]; rev != nil {\n\t\t\/\/ Obsolete\n\t\tmeta.OldRevision = int(m[\"revision\"].(int64))\n\t}\n\tif series, ok := m[\"series\"]; ok && series != nil {\n\t\tmeta.Series = series.(string)\n\t}\n\tif err := meta.Check(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn meta, nil\n}\n\n\/\/ Check checks that the metadata is well-formed.\nfunc (meta Meta) Check() error {\n\t\/\/ Check for duplicate or forbidden relation names or interfaces.\n\tnames := map[string]bool{}\n\tcheckRelations := func(src map[string]Relation, role RelationRole) error {\n\t\tfor name, rel := range src {\n\t\t\tif rel.Name != name {\n\t\t\t\treturn fmt.Errorf(\"charm %q has mismatched relation name %q; expected %q\", meta.Name, rel.Name, name)\n\t\t\t}\n\t\t\tif rel.Role != role {\n\t\t\t\treturn fmt.Errorf(\"charm %q has mismatched role %q; expected %q\", meta.Name, rel.Role, role)\n\t\t\t}\n\t\t\t\/\/ Container-scoped require relations on subordinates are allowed\n\t\t\t\/\/ to use the otherwise-reserved juju-* namespace.\n\t\t\tif !meta.Subordinate || role != RoleRequirer || rel.Scope != ScopeContainer {\n\t\t\t\tif reservedName(name) {\n\t\t\t\t\treturn fmt.Errorf(\"charm %q using a reserved relation name: %q\", meta.Name, name)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif role != RoleRequirer {\n\t\t\t\tif reservedName(rel.Interface) {\n\t\t\t\t\treturn fmt.Errorf(\"charm %q relation %q using a reserved interface: %q\", meta.Name, name, rel.Interface)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif names[name] {\n\t\t\t\treturn fmt.Errorf(\"charm %q using a duplicated relation name: %q\", meta.Name, name)\n\t\t\t}\n\t\t\tnames[name] = true\n\t\t}\n\t\treturn nil\n\t}\n\tif err := checkRelations(meta.Provides, RoleProvider); err != nil {\n\t\treturn err\n\t}\n\tif err := checkRelations(meta.Requires, RoleRequirer); err != nil {\n\t\treturn err\n\t}\n\tif err := checkRelations(meta.Peers, RolePeer); err != nil {\n\t\treturn err\n\t}\n\tif err := checkTags(meta.Tags); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Subordinate charms must have at least one relation that\n\t\/\/ has container scope, otherwise they can't relate to the\n\t\/\/ principal.\n\tif meta.Subordinate {\n\t\tvalid := false\n\t\tif meta.Requires != nil {\n\t\t\tfor _, relationData := range meta.Requires {\n\t\t\t\tif relationData.Scope == ScopeContainer {\n\t\t\t\t\tvalid = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !valid {\n\t\t\treturn fmt.Errorf(\"subordinate charm %q lacks \\\"requires\\\" relation with container scope\", meta.Name)\n\t\t}\n\t}\n\n\tif meta.Series != \"\" {\n\t\tif !IsValidSeries(meta.Series) {\n\t\t\treturn fmt.Errorf(\"charm %q declares invalid series: %q\", meta.Name, meta.Series)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc reservedName(name string) bool {\n\treturn name == \"juju\" || strings.HasPrefix(name, \"juju-\")\n}\n\nfunc parseRelations(relations interface{}, role RelationRole) map[string]Relation {\n\tif relations == nil {\n\t\treturn nil\n\t}\n\tresult := make(map[string]Relation)\n\tfor name, rel := range relations.(map[string]interface{}) {\n\t\trelMap := rel.(map[string]interface{})\n\t\trelation := Relation{\n\t\t\tName:      name,\n\t\t\tRole:      role,\n\t\t\tInterface: relMap[\"interface\"].(string),\n\t\t\tOptional:  relMap[\"optional\"].(bool),\n\t\t}\n\t\tif scope := relMap[\"scope\"]; scope != nil {\n\t\t\trelation.Scope = RelationScope(scope.(string))\n\t\t}\n\t\tif relMap[\"limit\"] != nil {\n\t\t\t\/\/ Schema defaults to int64, but we know\n\t\t\t\/\/ the int range should be more than enough.\n\t\t\trelation.Limit = int(relMap[\"limit\"].(int64))\n\t\t}\n\t\tresult[name] = relation\n\t}\n\treturn result\n}\n\n\/\/ Schema coercer that expands the interface shorthand notation.\n\/\/ A consistent format is easier to work with than considering the\n\/\/ potential difference everywhere.\n\/\/\n\/\/ Supports the following variants::\n\/\/\n\/\/   provides:\n\/\/     server: riak\n\/\/     admin: http\n\/\/     foobar:\n\/\/       interface: blah\n\/\/\n\/\/   provides:\n\/\/     server:\n\/\/       interface: mysql\n\/\/       limit:\n\/\/       optional: false\n\/\/\n\/\/ In all input cases, the output is the fully specified interface\n\/\/ representation as seen in the mysql interface description above.\nfunc ifaceExpander(limit interface{}) schema.Checker {\n\treturn ifaceExpC{limit}\n}\n\ntype ifaceExpC struct {\n\tlimit interface{}\n}\n\nvar (\n\tstringC = schema.String()\n\tmapC    = schema.StringMap(schema.Any())\n)\n\nfunc (c ifaceExpC) Coerce(v interface{}, path []string) (newv interface{}, err error) {\n\ts, err := stringC.Coerce(v, path)\n\tif err == nil {\n\t\tnewv = map[string]interface{}{\n\t\t\t\"interface\": s,\n\t\t\t\"limit\":     c.limit,\n\t\t\t\"optional\":  false,\n\t\t\t\"scope\":     string(ScopeGlobal),\n\t\t}\n\t\treturn\n\t}\n\n\tv, err = mapC.Coerce(v, path)\n\tif err != nil {\n\t\treturn\n\t}\n\tm := v.(map[string]interface{})\n\tif _, ok := m[\"limit\"]; !ok {\n\t\tm[\"limit\"] = c.limit\n\t}\n\treturn ifaceSchema.Coerce(m, path)\n}\n\nvar ifaceSchema = schema.FieldMap(\n\tschema.Fields{\n\t\t\"interface\": schema.String(),\n\t\t\"limit\":     schema.OneOf(schema.Const(nil), schema.Int()),\n\t\t\"scope\":     schema.OneOf(schema.Const(string(ScopeGlobal)), schema.Const(string(ScopeContainer))),\n\t\t\"optional\":  schema.Bool(),\n\t},\n\tschema.Defaults{\n\t\t\"scope\":    string(ScopeGlobal),\n\t\t\"optional\": false,\n\t},\n)\n\nvar charmSchema = schema.FieldMap(\n\tschema.Fields{\n\t\t\"name\":        schema.String(),\n\t\t\"summary\":     schema.String(),\n\t\t\"description\": schema.String(),\n\t\t\"peers\":       schema.StringMap(ifaceExpander(int64(1))),\n\t\t\"provides\":    schema.StringMap(ifaceExpander(nil)),\n\t\t\"requires\":    schema.StringMap(ifaceExpander(int64(1))),\n\t\t\"revision\":    schema.Int(), \/\/ Obsolete\n\t\t\"format\":      schema.Int(),\n\t\t\"subordinate\": schema.Bool(),\n\t\t\"categories\":  schema.List(schema.String()),\n\t\t\"tags\":        schema.List(schema.String()),\n\t\t\"series\":      schema.String(),\n\t},\n\tschema.Defaults{\n\t\t\"provides\":    schema.Omit,\n\t\t\"requires\":    schema.Omit,\n\t\t\"peers\":       schema.Omit,\n\t\t\"revision\":    schema.Omit,\n\t\t\"format\":      1,\n\t\t\"subordinate\": schema.Omit,\n\t\t\"categories\":  schema.Omit,\n\t\t\"tags\":        schema.Omit,\n\t\t\"series\":      schema.Omit,\n\t},\n)\n<commit_msg>* removed whitelist checking * common parsing function for categories and tags<commit_after>\/\/ Copyright 2011, 2012, 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage charm\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\n\t\"github.com\/juju\/schema\"\n\t\"gopkg.in\/yaml.v1\"\n\n\t\"gopkg.in\/juju\/charm.v4\/hooks\"\n)\n\n\/\/ RelationScope describes the scope of a relation.\ntype RelationScope string\n\n\/\/ Note that schema doesn't support custom string types,\n\/\/ so when we use these values in a schema.Checker,\n\/\/ we must store them as strings, not RelationScopes.\n\nconst (\n\tScopeGlobal    RelationScope = \"global\"\n\tScopeContainer RelationScope = \"container\"\n)\n\n\/\/ RelationRole defines the role of a relation.\ntype RelationRole string\n\nconst (\n\tRoleProvider RelationRole = \"provider\"\n\tRoleRequirer RelationRole = \"requirer\"\n\tRolePeer     RelationRole = \"peer\"\n)\n\n\/\/ Relation represents a single relation defined in the charm\n\/\/ metadata.yaml file.\ntype Relation struct {\n\tName      string\n\tRole      RelationRole\n\tInterface string\n\tOptional  bool\n\tLimit     int\n\tScope     RelationScope\n}\n\n\/\/ ImplementedBy returns whether the relation is implemented by the supplied charm.\nfunc (r Relation) ImplementedBy(ch Charm) bool {\n\tif r.IsImplicit() {\n\t\treturn true\n\t}\n\tvar m map[string]Relation\n\tswitch r.Role {\n\tcase RoleProvider:\n\t\tm = ch.Meta().Provides\n\tcase RoleRequirer:\n\t\tm = ch.Meta().Requires\n\tcase RolePeer:\n\t\tm = ch.Meta().Peers\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown relation role %q\", r.Role))\n\t}\n\trel, found := m[r.Name]\n\tif !found {\n\t\treturn false\n\t}\n\tif rel.Interface == r.Interface {\n\t\tswitch r.Scope {\n\t\tcase ScopeGlobal:\n\t\t\treturn rel.Scope != ScopeContainer\n\t\tcase ScopeContainer:\n\t\t\treturn true\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"unknown relation scope %q\", r.Scope))\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ IsImplicit returns whether the relation is supplied by juju itself,\n\/\/ rather than by a charm.\nfunc (r Relation) IsImplicit() bool {\n\treturn (r.Name == \"juju-info\" &&\n\t\tr.Interface == \"juju-info\" &&\n\t\tr.Role == RoleProvider)\n}\n\n\/\/ Meta represents all the known content that may be defined\n\/\/ within a charm's metadata.yaml file.\ntype Meta struct {\n\tName        string\n\tSummary     string\n\tDescription string\n\tSubordinate bool\n\tProvides    map[string]Relation `bson:\",omitempty\"`\n\tRequires    map[string]Relation `bson:\",omitempty\"`\n\tPeers       map[string]Relation `bson:\",omitempty\"`\n\tFormat      int                 `bson:\",omitempty\"`\n\tOldRevision int                 `bson:\",omitempty\"` \/\/ Obsolete\n\tCategories  []string            `bson:\",omitempty\"`\n\tTags        []string            `bson:\",omitempty\"`\n\tSeries      string              `bson:\",omitempty\"`\n}\n\nfunc generateRelationHooks(relName string, allHooks map[string]bool) {\n\tfor _, hookName := range hooks.RelationHooks() {\n\t\tallHooks[fmt.Sprintf(\"%s-%s\", relName, hookName)] = true\n\t}\n}\n\n\/\/ Hooks returns a map of all possible valid hooks, taking relations\n\/\/ into account. It's a map to enable fast lookups, and the value is\n\/\/ always true.\nfunc (m Meta) Hooks() map[string]bool {\n\tallHooks := make(map[string]bool)\n\t\/\/ Unit hooks\n\tfor _, hookName := range hooks.UnitHooks() {\n\t\tallHooks[string(hookName)] = true\n\t}\n\t\/\/ Relation hooks\n\tfor hookName := range m.Provides {\n\t\tgenerateRelationHooks(hookName, allHooks)\n\t}\n\tfor hookName := range m.Requires {\n\t\tgenerateRelationHooks(hookName, allHooks)\n\t}\n\tfor hookName := range m.Peers {\n\t\tgenerateRelationHooks(hookName, allHooks)\n\t}\n\treturn allHooks\n}\n\nfunc parseStringList(list interface{}) []string {\n\tif list == nil {\n\t\treturn nil\n\t}\n\tslice := list.([]interface{})\n\tresult := make([]string, 0, len(slice))\n\tfor _, cat := range slice {\n\t\tresult = append(result, cat.(string))\n\t}\n\treturn result\n}\n\nfunc parseCategories(categories interface{}) []string {\n\treturn parseStringList(categories)\n}\n\nfunc parseTags(tags interface{}) []string {\n\treturn parseStringList(tags)\n}\n\n\/\/ ReadMeta reads the content of a metadata.yaml file and returns\n\/\/ its representation.\nfunc ReadMeta(r io.Reader) (meta *Meta, err error) {\n\tdata, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn\n\t}\n\traw := make(map[interface{}]interface{})\n\terr = yaml.Unmarshal(data, raw)\n\tif err != nil {\n\t\treturn\n\t}\n\tv, err := charmSchema.Coerce(raw, nil)\n\tif err != nil {\n\t\treturn nil, errors.New(\"metadata: \" + err.Error())\n\t}\n\tm := v.(map[string]interface{})\n\tmeta = &Meta{}\n\tmeta.Name = m[\"name\"].(string)\n\t\/\/ Schema decodes as int64, but the int range should be good\n\t\/\/ enough for revisions.\n\tmeta.Summary = m[\"summary\"].(string)\n\tmeta.Description = m[\"description\"].(string)\n\tmeta.Provides = parseRelations(m[\"provides\"], RoleProvider)\n\tmeta.Requires = parseRelations(m[\"requires\"], RoleRequirer)\n\tmeta.Peers = parseRelations(m[\"peers\"], RolePeer)\n\tmeta.Format = int(m[\"format\"].(int64))\n\tmeta.Categories = parseCategories(m[\"categories\"])\n\tmeta.Tags = parseTags(m[\"tags\"])\n\tif subordinate := m[\"subordinate\"]; subordinate != nil {\n\t\tmeta.Subordinate = subordinate.(bool)\n\t}\n\tif rev := m[\"revision\"]; rev != nil {\n\t\t\/\/ Obsolete\n\t\tmeta.OldRevision = int(m[\"revision\"].(int64))\n\t}\n\tif series, ok := m[\"series\"]; ok && series != nil {\n\t\tmeta.Series = series.(string)\n\t}\n\tif err := meta.Check(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn meta, nil\n}\n\n\/\/ Check checks that the metadata is well-formed.\nfunc (meta Meta) Check() error {\n\t\/\/ Check for duplicate or forbidden relation names or interfaces.\n\tnames := map[string]bool{}\n\tcheckRelations := func(src map[string]Relation, role RelationRole) error {\n\t\tfor name, rel := range src {\n\t\t\tif rel.Name != name {\n\t\t\t\treturn fmt.Errorf(\"charm %q has mismatched relation name %q; expected %q\", meta.Name, rel.Name, name)\n\t\t\t}\n\t\t\tif rel.Role != role {\n\t\t\t\treturn fmt.Errorf(\"charm %q has mismatched role %q; expected %q\", meta.Name, rel.Role, role)\n\t\t\t}\n\t\t\t\/\/ Container-scoped require relations on subordinates are allowed\n\t\t\t\/\/ to use the otherwise-reserved juju-* namespace.\n\t\t\tif !meta.Subordinate || role != RoleRequirer || rel.Scope != ScopeContainer {\n\t\t\t\tif reservedName(name) {\n\t\t\t\t\treturn fmt.Errorf(\"charm %q using a reserved relation name: %q\", meta.Name, name)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif role != RoleRequirer {\n\t\t\t\tif reservedName(rel.Interface) {\n\t\t\t\t\treturn fmt.Errorf(\"charm %q relation %q using a reserved interface: %q\", meta.Name, name, rel.Interface)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif names[name] {\n\t\t\t\treturn fmt.Errorf(\"charm %q using a duplicated relation name: %q\", meta.Name, name)\n\t\t\t}\n\t\t\tnames[name] = true\n\t\t}\n\t\treturn nil\n\t}\n\tif err := checkRelations(meta.Provides, RoleProvider); err != nil {\n\t\treturn err\n\t}\n\tif err := checkRelations(meta.Requires, RoleRequirer); err != nil {\n\t\treturn err\n\t}\n\tif err := checkRelations(meta.Peers, RolePeer); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Subordinate charms must have at least one relation that\n\t\/\/ has container scope, otherwise they can't relate to the\n\t\/\/ principal.\n\tif meta.Subordinate {\n\t\tvalid := false\n\t\tif meta.Requires != nil {\n\t\t\tfor _, relationData := range meta.Requires {\n\t\t\t\tif relationData.Scope == ScopeContainer {\n\t\t\t\t\tvalid = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif !valid {\n\t\t\treturn fmt.Errorf(\"subordinate charm %q lacks \\\"requires\\\" relation with container scope\", meta.Name)\n\t\t}\n\t}\n\n\tif meta.Series != \"\" {\n\t\tif !IsValidSeries(meta.Series) {\n\t\t\treturn fmt.Errorf(\"charm %q declares invalid series: %q\", meta.Name, meta.Series)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc reservedName(name string) bool {\n\treturn name == \"juju\" || strings.HasPrefix(name, \"juju-\")\n}\n\nfunc parseRelations(relations interface{}, role RelationRole) map[string]Relation {\n\tif relations == nil {\n\t\treturn nil\n\t}\n\tresult := make(map[string]Relation)\n\tfor name, rel := range relations.(map[string]interface{}) {\n\t\trelMap := rel.(map[string]interface{})\n\t\trelation := Relation{\n\t\t\tName:      name,\n\t\t\tRole:      role,\n\t\t\tInterface: relMap[\"interface\"].(string),\n\t\t\tOptional:  relMap[\"optional\"].(bool),\n\t\t}\n\t\tif scope := relMap[\"scope\"]; scope != nil {\n\t\t\trelation.Scope = RelationScope(scope.(string))\n\t\t}\n\t\tif relMap[\"limit\"] != nil {\n\t\t\t\/\/ Schema defaults to int64, but we know\n\t\t\t\/\/ the int range should be more than enough.\n\t\t\trelation.Limit = int(relMap[\"limit\"].(int64))\n\t\t}\n\t\tresult[name] = relation\n\t}\n\treturn result\n}\n\n\/\/ Schema coercer that expands the interface shorthand notation.\n\/\/ A consistent format is easier to work with than considering the\n\/\/ potential difference everywhere.\n\/\/\n\/\/ Supports the following variants::\n\/\/\n\/\/   provides:\n\/\/     server: riak\n\/\/     admin: http\n\/\/     foobar:\n\/\/       interface: blah\n\/\/\n\/\/   provides:\n\/\/     server:\n\/\/       interface: mysql\n\/\/       limit:\n\/\/       optional: false\n\/\/\n\/\/ In all input cases, the output is the fully specified interface\n\/\/ representation as seen in the mysql interface description above.\nfunc ifaceExpander(limit interface{}) schema.Checker {\n\treturn ifaceExpC{limit}\n}\n\ntype ifaceExpC struct {\n\tlimit interface{}\n}\n\nvar (\n\tstringC = schema.String()\n\tmapC    = schema.StringMap(schema.Any())\n)\n\nfunc (c ifaceExpC) Coerce(v interface{}, path []string) (newv interface{}, err error) {\n\ts, err := stringC.Coerce(v, path)\n\tif err == nil {\n\t\tnewv = map[string]interface{}{\n\t\t\t\"interface\": s,\n\t\t\t\"limit\":     c.limit,\n\t\t\t\"optional\":  false,\n\t\t\t\"scope\":     string(ScopeGlobal),\n\t\t}\n\t\treturn\n\t}\n\n\tv, err = mapC.Coerce(v, path)\n\tif err != nil {\n\t\treturn\n\t}\n\tm := v.(map[string]interface{})\n\tif _, ok := m[\"limit\"]; !ok {\n\t\tm[\"limit\"] = c.limit\n\t}\n\treturn ifaceSchema.Coerce(m, path)\n}\n\nvar ifaceSchema = schema.FieldMap(\n\tschema.Fields{\n\t\t\"interface\": schema.String(),\n\t\t\"limit\":     schema.OneOf(schema.Const(nil), schema.Int()),\n\t\t\"scope\":     schema.OneOf(schema.Const(string(ScopeGlobal)), schema.Const(string(ScopeContainer))),\n\t\t\"optional\":  schema.Bool(),\n\t},\n\tschema.Defaults{\n\t\t\"scope\":    string(ScopeGlobal),\n\t\t\"optional\": false,\n\t},\n)\n\nvar charmSchema = schema.FieldMap(\n\tschema.Fields{\n\t\t\"name\":        schema.String(),\n\t\t\"summary\":     schema.String(),\n\t\t\"description\": schema.String(),\n\t\t\"peers\":       schema.StringMap(ifaceExpander(int64(1))),\n\t\t\"provides\":    schema.StringMap(ifaceExpander(nil)),\n\t\t\"requires\":    schema.StringMap(ifaceExpander(int64(1))),\n\t\t\"revision\":    schema.Int(), \/\/ Obsolete\n\t\t\"format\":      schema.Int(),\n\t\t\"subordinate\": schema.Bool(),\n\t\t\"categories\":  schema.List(schema.String()),\n\t\t\"tags\":        schema.List(schema.String()),\n\t\t\"series\":      schema.String(),\n\t},\n\tschema.Defaults{\n\t\t\"provides\":    schema.Omit,\n\t\t\"requires\":    schema.Omit,\n\t\t\"peers\":       schema.Omit,\n\t\t\"revision\":    schema.Omit,\n\t\t\"format\":      1,\n\t\t\"subordinate\": schema.Omit,\n\t\t\"categories\":  schema.Omit,\n\t\t\"tags\":        schema.Omit,\n\t\t\"series\":      schema.Omit,\n\t},\n)\n<|endoftext|>"}
{"text":"<commit_before>package mgos\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strconv\"\n)\n\n\/\/ Getter like url.Values\ntype Getter interface {\n\tGet(string) string\n}\n\n\/\/ FromGetter make strunct from value\nfunc FromGetter(getter Getter, dest interface{}) error {\n\n\tswitch dest.(type) {\n\tdefault:\n\t\treturn fmt.Errorf(\"dest is not struct\")\n\tcase interface{}:\n\t\telem := reflect.ValueOf(dest).Elem()\n\n\t\tfor i := 0; i < elem.NumField(); i++ {\n\t\t\tfield := elem.Field(i)\n\t\t\ttypeField := elem.Type().Field(i)\n\t\t\tname := typeField.Tag.Get(\"mgos\")\n\t\t\tif name == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tuv := getter.Get(name)\n\n\t\t\tswitch field.Kind() {\n\t\t\tcase reflect.Int8, reflect.Int, reflect.Int64:\n\t\t\t\tif i, err := strconv.Atoi(uv); err == nil {\n\t\t\t\t\tfield.SetInt(int64(i))\n\t\t\t\t}\n\t\t\tcase reflect.Uint8, reflect.Uint, reflect.Uint64:\n\t\t\t\tif i, err := strconv.Atoi(uv); err == nil {\n\t\t\t\t\tfield.SetUint(uint64(i))\n\t\t\t\t}\n\t\t\tcase reflect.String:\n\t\t\t\tfield.SetString(uv)\n\t\t\tcase reflect.Bool:\n\t\t\t\tif uv != \"\" && uv != \"0\" {\n\t\t\t\t\tfield.SetBool(true)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Sprintf(\"kind (%s) not supported\", elem.Kind()))\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn nil\n}\n<commit_msg>Add scanner interface.<commit_after>package mgos\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strconv\"\n)\n\n\/\/ Getter like url.Values\ntype Getter interface {\n\tGet(string) string\n}\n\ntype Scanner interface {\n\tScan(interface{}) error\n}\n\n\/\/ FromGetter make strunct from value\nfunc FromGetter(getter Getter, dest interface{}) error {\n\n\tswitch dest.(type) {\n\tdefault:\n\t\treturn fmt.Errorf(\"dest is not struct\")\n\tcase interface{}:\n\t\telem := reflect.ValueOf(dest).Elem()\n\n\t\tfor i := 0; i < elem.NumField(); i++ {\n\t\t\tfield := elem.Field(i)\n\t\t\ttypeField := elem.Type().Field(i)\n\t\t\tname := typeField.Tag.Get(\"mgos\")\n\t\t\tif name == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tuv := getter.Get(name)\n\n\t\t\tswitch field.Kind() {\n\t\t\tcase reflect.Int8, reflect.Int, reflect.Int64:\n\t\t\t\tif i, err := strconv.Atoi(uv); err == nil {\n\t\t\t\t\tfield.SetInt(int64(i))\n\t\t\t\t}\n\t\t\tcase reflect.Uint8, reflect.Uint, reflect.Uint64:\n\t\t\t\tif i, err := strconv.Atoi(uv); err == nil {\n\t\t\t\t\tfield.SetUint(uint64(i))\n\t\t\t\t}\n\t\t\tcase reflect.String:\n\t\t\t\tfield.SetString(uv)\n\t\t\tcase reflect.Bool:\n\t\t\t\tif uv != \"\" && uv != \"0\" {\n\t\t\t\t\tfield.SetBool(true)\n\t\t\t\t}\n\t\t\tcase reflect.Struct:\n\t\t\t\t\/\/ i := field.Interface()\n\t\t\t\t\/\/ scanner, ok := i.(Scanner)\n\t\t\t\t\/\/ if !ok {\n\t\t\t\t\/\/ \treturn fmt.Errorf(\"%s is not Scanner\", )\n\t\t\t\t\/\/ }\n\t\t\tdefault:\n\t\t\t\tpanic(fmt.Sprintf(\"kind (%s) not supported\", elem.Kind()))\n\t\t\t}\n\n\t\t}\n\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as\n\/\/ defined in FIPS 186-3.\n\/\/\n\/\/ This implementation derives the nonce from an AES-CTR CSPRNG keyed by:\n\/\/\n\/\/ SHA2-512(priv.D || entropy || hash)[:32]\n\/\/\n\/\/ The CSPRNG key is indifferentiable from a random oracle as shown in\n\/\/ [Coron], the AES-CTR stream is indifferentiable from a random oracle\n\/\/ under standard cryptographic assumptions (see [Larsson] for examples).\n\/\/\n\/\/ References:\n\/\/   [Coron]\n\/\/     https:\/\/cs.nyu.edu\/~dodis\/ps\/merkle.pdf\n\/\/   [Larsson]\n\/\/     https:\/\/web.archive.org\/web\/20040719170906\/https:\/\/www.nada.kth.se\/kurser\/kth\/2D1441\/semteo03\/lecturenotes\/assump.pdf\npackage ecdsa\n\n\/\/ Further references:\n\/\/   [NSA]: Suite B implementer's guide to FIPS 186-3\n\/\/     https:\/\/apps.nsa.gov\/iaarchive\/library\/ia-guidance\/ia-solutions-for-classified\/algorithm-guidance\/suite-b-implementers-guide-to-fips-186-3-ecdsa.cfm\n\/\/   [SECG]: SECG, SEC1\n\/\/     http:\/\/www.secg.org\/sec1-v2.pdf\n\nimport (\n\t\"crypto\"\n\t\"crypto\/aes\"\n\t\"crypto\/cipher\"\n\t\"crypto\/elliptic\"\n\t\"crypto\/internal\/randutil\"\n\t\"crypto\/sha512\"\n\t\"errors\"\n\t\"io\"\n\t\"math\/big\"\n\n\t\"golang.org\/x\/crypto\/cryptobyte\"\n\t\"golang.org\/x\/crypto\/cryptobyte\/asn1\"\n)\n\n\/\/ A invertible implements fast inverse mod Curve.Params().N\ntype invertible interface {\n\t\/\/ Inverse returns the inverse of k in GF(P)\n\tInverse(k *big.Int) *big.Int\n}\n\n\/\/ combinedMult implements fast multiplication S1*g + S2*p (g - generator, p - arbitrary point)\ntype combinedMult interface {\n\tCombinedMult(bigX, bigY *big.Int, baseScalar, scalar []byte) (x, y *big.Int)\n}\n\nconst (\n\taesIV = \"IV for ECDSA CTR\"\n)\n\n\/\/ PublicKey represents an ECDSA public key.\ntype PublicKey struct {\n\telliptic.Curve\n\tX, Y *big.Int\n}\n\n\/\/ Any methods implemented on PublicKey might need to also be implemented on\n\/\/ PrivateKey, as the latter embeds the former and will expose its methods.\n\n\/\/ Equal reports whether pub and x have the same value.\n\/\/\n\/\/ Two keys are only considered to have the same value if they have the same Curve value.\n\/\/ Note that for example elliptic.P256() and elliptic.P256().Params() are different\n\/\/ values, as the latter is a generic not constant time implementation.\nfunc (pub *PublicKey) Equal(x crypto.PublicKey) bool {\n\txx, ok := x.(*PublicKey)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn pub.X.Cmp(xx.X) == 0 && pub.Y.Cmp(xx.Y) == 0 &&\n\t\t\/\/ Standard library Curve implementations are singletons, so this check\n\t\t\/\/ will work for those. Other Curves might be equivalent even if not\n\t\t\/\/ singletons, but there is no definitive way to check for that, and\n\t\t\/\/ better to err on the side of safety.\n\t\tpub.Curve == xx.Curve\n}\n\n\/\/ PrivateKey represents an ECDSA private key.\ntype PrivateKey struct {\n\tPublicKey\n\tD *big.Int\n}\n\n\/\/ Public returns the public key corresponding to priv.\nfunc (priv *PrivateKey) Public() crypto.PublicKey {\n\treturn &priv.PublicKey\n}\n\n\/\/ Equal reports whether priv and x have the same value.\n\/\/\n\/\/ See PublicKey.Equal for details on how Curve is compared.\nfunc (priv *PrivateKey) Equal(x crypto.PrivateKey) bool {\n\txx, ok := x.(*PrivateKey)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn priv.PublicKey.Equal(&xx.PublicKey) && priv.D.Cmp(xx.D) == 0\n}\n\n\/\/ Sign signs digest with priv, reading randomness from rand. The opts argument\n\/\/ is not currently used but, in keeping with the crypto.Signer interface,\n\/\/ should be the hash function used to digest the message.\n\/\/\n\/\/ This method implements crypto.Signer, which is an interface to support keys\n\/\/ where the private part is kept in, for example, a hardware module. Common\n\/\/ uses should use the Sign function in this package directly.\nfunc (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {\n\tr, s, err := Sign(rand, priv, digest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar b cryptobyte.Builder\n\tb.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {\n\t\tb.AddASN1BigInt(r)\n\t\tb.AddASN1BigInt(s)\n\t})\n\treturn b.Bytes()\n}\n\nvar one = new(big.Int).SetInt64(1)\n\n\/\/ randFieldElement returns a random element of the field underlying the given\n\/\/ curve using the procedure given in [NSA] A.2.1.\nfunc randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) {\n\tparams := c.Params()\n\tb := make([]byte, params.BitSize\/8+8)\n\t_, err = io.ReadFull(rand, b)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tk = new(big.Int).SetBytes(b)\n\tn := new(big.Int).Sub(params.N, one)\n\tk.Mod(k, n)\n\tk.Add(k, one)\n\treturn\n}\n\n\/\/ GenerateKey generates a public and private key pair.\nfunc GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) {\n\tk, err := randFieldElement(c, rand)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpriv := new(PrivateKey)\n\tpriv.PublicKey.Curve = c\n\tpriv.D = k\n\tpriv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())\n\treturn priv, nil\n}\n\n\/\/ hashToInt converts a hash value to an integer. There is some disagreement\n\/\/ about how this is done. [NSA] suggests that this is done in the obvious\n\/\/ manner, but [SECG] truncates the hash to the bit-length of the curve order\n\/\/ first. We follow [SECG] because that's what OpenSSL does. Additionally,\n\/\/ OpenSSL right shifts excess bits from the number if the hash is too large\n\/\/ and we mirror that too.\nfunc hashToInt(hash []byte, c elliptic.Curve) *big.Int {\n\torderBits := c.Params().N.BitLen()\n\torderBytes := (orderBits + 7) \/ 8\n\tif len(hash) > orderBytes {\n\t\thash = hash[:orderBytes]\n\t}\n\n\tret := new(big.Int).SetBytes(hash)\n\texcess := len(hash)*8 - orderBits\n\tif excess > 0 {\n\t\tret.Rsh(ret, uint(excess))\n\t}\n\treturn ret\n}\n\n\/\/ fermatInverse calculates the inverse of k in GF(P) using Fermat's method.\n\/\/ This has better constant-time properties than Euclid's method (implemented\n\/\/ in math\/big.Int.ModInverse) although math\/big itself isn't strictly\n\/\/ constant-time so it's not perfect.\nfunc fermatInverse(k, N *big.Int) *big.Int {\n\ttwo := big.NewInt(2)\n\tnMinus2 := new(big.Int).Sub(N, two)\n\treturn new(big.Int).Exp(k, nMinus2, N)\n}\n\nvar errZeroParam = errors.New(\"zero parameter\")\n\n\/\/ Sign signs a hash (which should be the result of hashing a larger message)\n\/\/ using the private key, priv. If the hash is longer than the bit-length of the\n\/\/ private key's curve order, the hash will be truncated to that length. It\n\/\/ returns the signature as a pair of integers. The security of the private key\n\/\/ depends on the entropy of rand.\nfunc Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {\n\trandutil.MaybeReadByte(rand)\n\n\t\/\/ Get min(log2(q) \/ 2, 256) bits of entropy from rand.\n\tentropylen := (priv.Curve.Params().BitSize + 7) \/ 16\n\tif entropylen > 32 {\n\t\tentropylen = 32\n\t}\n\tentropy := make([]byte, entropylen)\n\t_, err = io.ReadFull(rand, entropy)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Initialize an SHA-512 hash context; digest ...\n\tmd := sha512.New()\n\tmd.Write(priv.D.Bytes()) \/\/ the private key,\n\tmd.Write(entropy)        \/\/ the entropy,\n\tmd.Write(hash)           \/\/ and the input hash;\n\tkey := md.Sum(nil)[:32]  \/\/ and compute ChopMD-256(SHA-512),\n\t\/\/ which is an indifferentiable MAC.\n\n\t\/\/ Create an AES-CTR instance to use as a CSPRNG.\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Create a CSPRNG that xors a stream of zeros with\n\t\/\/ the output of the AES-CTR instance.\n\tcsprng := cipher.StreamReader{\n\t\tR: zeroReader,\n\t\tS: cipher.NewCTR(block, []byte(aesIV)),\n\t}\n\n\t\/\/ See [NSA] 3.4.1\n\tc := priv.PublicKey.Curve\n\treturn sign(priv, &csprng, c, hash)\n}\n\nfunc signGeneric(priv *PrivateKey, csprng *cipher.StreamReader, c elliptic.Curve, hash []byte) (r, s *big.Int, err error) {\n\tN := c.Params().N\n\tif N.Sign() == 0 {\n\t\treturn nil, nil, errZeroParam\n\t}\n\tvar k, kInv *big.Int\n\tfor {\n\t\tfor {\n\t\t\tk, err = randFieldElement(c, *csprng)\n\t\t\tif err != nil {\n\t\t\t\tr = nil\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif in, ok := priv.Curve.(invertible); ok {\n\t\t\t\tkInv = in.Inverse(k)\n\t\t\t} else {\n\t\t\t\tkInv = fermatInverse(k, N) \/\/ N != 0\n\t\t\t}\n\n\t\t\tr, _ = priv.Curve.ScalarBaseMult(k.Bytes())\n\t\t\tr.Mod(r, N)\n\t\t\tif r.Sign() != 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\te := hashToInt(hash, c)\n\t\ts = new(big.Int).Mul(priv.D, r)\n\t\ts.Add(s, e)\n\t\ts.Mul(s, kInv)\n\t\ts.Mod(s, N) \/\/ N != 0\n\t\tif s.Sign() != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ SignASN1 signs a hash (which should be the result of hashing a larger message)\n\/\/ using the private key, priv. If the hash is longer than the bit-length of the\n\/\/ private key's curve order, the hash will be truncated to that length. It\n\/\/ returns the ASN.1 encoded signature. The security of the private key\n\/\/ depends on the entropy of rand.\nfunc SignASN1(rand io.Reader, priv *PrivateKey, hash []byte) ([]byte, error) {\n\treturn priv.Sign(rand, hash, nil)\n}\n\n\/\/ Verify verifies the signature in r, s of hash using the public key, pub. Its\n\/\/ return value records whether the signature is valid.\nfunc Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {\n\t\/\/ See [NSA] 3.4.2\n\tc := pub.Curve\n\tN := c.Params().N\n\n\tif r.Sign() <= 0 || s.Sign() <= 0 {\n\t\treturn false\n\t}\n\tif r.Cmp(N) >= 0 || s.Cmp(N) >= 0 {\n\t\treturn false\n\t}\n\treturn verify(pub, c, hash, r, s)\n}\n\nfunc verifyGeneric(pub *PublicKey, c elliptic.Curve, hash []byte, r, s *big.Int) bool {\n\te := hashToInt(hash, c)\n\tvar w *big.Int\n\tN := c.Params().N\n\tif in, ok := c.(invertible); ok {\n\t\tw = in.Inverse(s)\n\t} else {\n\t\tw = new(big.Int).ModInverse(s, N)\n\t}\n\n\tu1 := e.Mul(e, w)\n\tu1.Mod(u1, N)\n\tu2 := w.Mul(r, w)\n\tu2.Mod(u2, N)\n\n\t\/\/ Check if implements S1*g + S2*p\n\tvar x, y *big.Int\n\tif opt, ok := c.(combinedMult); ok {\n\t\tx, y = opt.CombinedMult(pub.X, pub.Y, u1.Bytes(), u2.Bytes())\n\t} else {\n\t\tx1, y1 := c.ScalarBaseMult(u1.Bytes())\n\t\tx2, y2 := c.ScalarMult(pub.X, pub.Y, u2.Bytes())\n\t\tx, y = c.Add(x1, y1, x2, y2)\n\t}\n\n\tif x.Sign() == 0 && y.Sign() == 0 {\n\t\treturn false\n\t}\n\tx.Mod(x, N)\n\treturn x.Cmp(r) == 0\n}\n\n\/\/ VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the\n\/\/ public key, pub. Its return value records whether the signature is valid.\nfunc VerifyASN1(pub *PublicKey, hash, sig []byte) bool {\n\tvar (\n\t\tr, s  = &big.Int{}, &big.Int{}\n\t\tinner cryptobyte.String\n\t)\n\tinput := cryptobyte.String(sig)\n\tif !input.ReadASN1(&inner, asn1.SEQUENCE) ||\n\t\t!input.Empty() ||\n\t\t!inner.ReadASN1Integer(r) ||\n\t\t!inner.ReadASN1Integer(s) ||\n\t\t!inner.Empty() {\n\t\treturn false\n\t}\n\treturn Verify(pub, hash, r, s)\n}\n\ntype zr struct {\n\tio.Reader\n}\n\n\/\/ Read replaces the contents of dst with zeros.\nfunc (z *zr) Read(dst []byte) (n int, err error) {\n\tfor i := range dst {\n\t\tdst[i] = 0\n\t}\n\treturn len(dst), nil\n}\n\nvar zeroReader = &zr{}\n<commit_msg>crypto\/ecdsa: draw a fixed amount of entropy while signing<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as\n\/\/ defined in FIPS 186-3.\n\/\/\n\/\/ This implementation derives the nonce from an AES-CTR CSPRNG keyed by:\n\/\/\n\/\/ SHA2-512(priv.D || entropy || hash)[:32]\n\/\/\n\/\/ The CSPRNG key is indifferentiable from a random oracle as shown in\n\/\/ [Coron], the AES-CTR stream is indifferentiable from a random oracle\n\/\/ under standard cryptographic assumptions (see [Larsson] for examples).\n\/\/\n\/\/ References:\n\/\/   [Coron]\n\/\/     https:\/\/cs.nyu.edu\/~dodis\/ps\/merkle.pdf\n\/\/   [Larsson]\n\/\/     https:\/\/web.archive.org\/web\/20040719170906\/https:\/\/www.nada.kth.se\/kurser\/kth\/2D1441\/semteo03\/lecturenotes\/assump.pdf\npackage ecdsa\n\n\/\/ Further references:\n\/\/   [NSA]: Suite B implementer's guide to FIPS 186-3\n\/\/     https:\/\/apps.nsa.gov\/iaarchive\/library\/ia-guidance\/ia-solutions-for-classified\/algorithm-guidance\/suite-b-implementers-guide-to-fips-186-3-ecdsa.cfm\n\/\/   [SECG]: SECG, SEC1\n\/\/     http:\/\/www.secg.org\/sec1-v2.pdf\n\nimport (\n\t\"crypto\"\n\t\"crypto\/aes\"\n\t\"crypto\/cipher\"\n\t\"crypto\/elliptic\"\n\t\"crypto\/internal\/randutil\"\n\t\"crypto\/sha512\"\n\t\"errors\"\n\t\"io\"\n\t\"math\/big\"\n\n\t\"golang.org\/x\/crypto\/cryptobyte\"\n\t\"golang.org\/x\/crypto\/cryptobyte\/asn1\"\n)\n\n\/\/ A invertible implements fast inverse mod Curve.Params().N\ntype invertible interface {\n\t\/\/ Inverse returns the inverse of k in GF(P)\n\tInverse(k *big.Int) *big.Int\n}\n\n\/\/ combinedMult implements fast multiplication S1*g + S2*p (g - generator, p - arbitrary point)\ntype combinedMult interface {\n\tCombinedMult(bigX, bigY *big.Int, baseScalar, scalar []byte) (x, y *big.Int)\n}\n\nconst (\n\taesIV = \"IV for ECDSA CTR\"\n)\n\n\/\/ PublicKey represents an ECDSA public key.\ntype PublicKey struct {\n\telliptic.Curve\n\tX, Y *big.Int\n}\n\n\/\/ Any methods implemented on PublicKey might need to also be implemented on\n\/\/ PrivateKey, as the latter embeds the former and will expose its methods.\n\n\/\/ Equal reports whether pub and x have the same value.\n\/\/\n\/\/ Two keys are only considered to have the same value if they have the same Curve value.\n\/\/ Note that for example elliptic.P256() and elliptic.P256().Params() are different\n\/\/ values, as the latter is a generic not constant time implementation.\nfunc (pub *PublicKey) Equal(x crypto.PublicKey) bool {\n\txx, ok := x.(*PublicKey)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn pub.X.Cmp(xx.X) == 0 && pub.Y.Cmp(xx.Y) == 0 &&\n\t\t\/\/ Standard library Curve implementations are singletons, so this check\n\t\t\/\/ will work for those. Other Curves might be equivalent even if not\n\t\t\/\/ singletons, but there is no definitive way to check for that, and\n\t\t\/\/ better to err on the side of safety.\n\t\tpub.Curve == xx.Curve\n}\n\n\/\/ PrivateKey represents an ECDSA private key.\ntype PrivateKey struct {\n\tPublicKey\n\tD *big.Int\n}\n\n\/\/ Public returns the public key corresponding to priv.\nfunc (priv *PrivateKey) Public() crypto.PublicKey {\n\treturn &priv.PublicKey\n}\n\n\/\/ Equal reports whether priv and x have the same value.\n\/\/\n\/\/ See PublicKey.Equal for details on how Curve is compared.\nfunc (priv *PrivateKey) Equal(x crypto.PrivateKey) bool {\n\txx, ok := x.(*PrivateKey)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn priv.PublicKey.Equal(&xx.PublicKey) && priv.D.Cmp(xx.D) == 0\n}\n\n\/\/ Sign signs digest with priv, reading randomness from rand. The opts argument\n\/\/ is not currently used but, in keeping with the crypto.Signer interface,\n\/\/ should be the hash function used to digest the message.\n\/\/\n\/\/ This method implements crypto.Signer, which is an interface to support keys\n\/\/ where the private part is kept in, for example, a hardware module. Common\n\/\/ uses should use the Sign function in this package directly.\nfunc (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {\n\tr, s, err := Sign(rand, priv, digest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar b cryptobyte.Builder\n\tb.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {\n\t\tb.AddASN1BigInt(r)\n\t\tb.AddASN1BigInt(s)\n\t})\n\treturn b.Bytes()\n}\n\nvar one = new(big.Int).SetInt64(1)\n\n\/\/ randFieldElement returns a random element of the field underlying the given\n\/\/ curve using the procedure given in [NSA] A.2.1.\nfunc randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) {\n\tparams := c.Params()\n\tb := make([]byte, params.BitSize\/8+8)\n\t_, err = io.ReadFull(rand, b)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tk = new(big.Int).SetBytes(b)\n\tn := new(big.Int).Sub(params.N, one)\n\tk.Mod(k, n)\n\tk.Add(k, one)\n\treturn\n}\n\n\/\/ GenerateKey generates a public and private key pair.\nfunc GenerateKey(c elliptic.Curve, rand io.Reader) (*PrivateKey, error) {\n\tk, err := randFieldElement(c, rand)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpriv := new(PrivateKey)\n\tpriv.PublicKey.Curve = c\n\tpriv.D = k\n\tpriv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes())\n\treturn priv, nil\n}\n\n\/\/ hashToInt converts a hash value to an integer. There is some disagreement\n\/\/ about how this is done. [NSA] suggests that this is done in the obvious\n\/\/ manner, but [SECG] truncates the hash to the bit-length of the curve order\n\/\/ first. We follow [SECG] because that's what OpenSSL does. Additionally,\n\/\/ OpenSSL right shifts excess bits from the number if the hash is too large\n\/\/ and we mirror that too.\nfunc hashToInt(hash []byte, c elliptic.Curve) *big.Int {\n\torderBits := c.Params().N.BitLen()\n\torderBytes := (orderBits + 7) \/ 8\n\tif len(hash) > orderBytes {\n\t\thash = hash[:orderBytes]\n\t}\n\n\tret := new(big.Int).SetBytes(hash)\n\texcess := len(hash)*8 - orderBits\n\tif excess > 0 {\n\t\tret.Rsh(ret, uint(excess))\n\t}\n\treturn ret\n}\n\n\/\/ fermatInverse calculates the inverse of k in GF(P) using Fermat's method.\n\/\/ This has better constant-time properties than Euclid's method (implemented\n\/\/ in math\/big.Int.ModInverse) although math\/big itself isn't strictly\n\/\/ constant-time so it's not perfect.\nfunc fermatInverse(k, N *big.Int) *big.Int {\n\ttwo := big.NewInt(2)\n\tnMinus2 := new(big.Int).Sub(N, two)\n\treturn new(big.Int).Exp(k, nMinus2, N)\n}\n\nvar errZeroParam = errors.New(\"zero parameter\")\n\n\/\/ Sign signs a hash (which should be the result of hashing a larger message)\n\/\/ using the private key, priv. If the hash is longer than the bit-length of the\n\/\/ private key's curve order, the hash will be truncated to that length. It\n\/\/ returns the signature as a pair of integers. The security of the private key\n\/\/ depends on the entropy of rand.\nfunc Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) {\n\trandutil.MaybeReadByte(rand)\n\n\t\/\/ Get 256 bits of entropy from rand.\n\tentropy := make([]byte, 32)\n\t_, err = io.ReadFull(rand, entropy)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Initialize an SHA-512 hash context; digest ...\n\tmd := sha512.New()\n\tmd.Write(priv.D.Bytes()) \/\/ the private key,\n\tmd.Write(entropy)        \/\/ the entropy,\n\tmd.Write(hash)           \/\/ and the input hash;\n\tkey := md.Sum(nil)[:32]  \/\/ and compute ChopMD-256(SHA-512),\n\t\/\/ which is an indifferentiable MAC.\n\n\t\/\/ Create an AES-CTR instance to use as a CSPRNG.\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Create a CSPRNG that xors a stream of zeros with\n\t\/\/ the output of the AES-CTR instance.\n\tcsprng := cipher.StreamReader{\n\t\tR: zeroReader,\n\t\tS: cipher.NewCTR(block, []byte(aesIV)),\n\t}\n\n\t\/\/ See [NSA] 3.4.1\n\tc := priv.PublicKey.Curve\n\treturn sign(priv, &csprng, c, hash)\n}\n\nfunc signGeneric(priv *PrivateKey, csprng *cipher.StreamReader, c elliptic.Curve, hash []byte) (r, s *big.Int, err error) {\n\tN := c.Params().N\n\tif N.Sign() == 0 {\n\t\treturn nil, nil, errZeroParam\n\t}\n\tvar k, kInv *big.Int\n\tfor {\n\t\tfor {\n\t\t\tk, err = randFieldElement(c, *csprng)\n\t\t\tif err != nil {\n\t\t\t\tr = nil\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif in, ok := priv.Curve.(invertible); ok {\n\t\t\t\tkInv = in.Inverse(k)\n\t\t\t} else {\n\t\t\t\tkInv = fermatInverse(k, N) \/\/ N != 0\n\t\t\t}\n\n\t\t\tr, _ = priv.Curve.ScalarBaseMult(k.Bytes())\n\t\t\tr.Mod(r, N)\n\t\t\tif r.Sign() != 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\te := hashToInt(hash, c)\n\t\ts = new(big.Int).Mul(priv.D, r)\n\t\ts.Add(s, e)\n\t\ts.Mul(s, kInv)\n\t\ts.Mod(s, N) \/\/ N != 0\n\t\tif s.Sign() != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ SignASN1 signs a hash (which should be the result of hashing a larger message)\n\/\/ using the private key, priv. If the hash is longer than the bit-length of the\n\/\/ private key's curve order, the hash will be truncated to that length. It\n\/\/ returns the ASN.1 encoded signature. The security of the private key\n\/\/ depends on the entropy of rand.\nfunc SignASN1(rand io.Reader, priv *PrivateKey, hash []byte) ([]byte, error) {\n\treturn priv.Sign(rand, hash, nil)\n}\n\n\/\/ Verify verifies the signature in r, s of hash using the public key, pub. Its\n\/\/ return value records whether the signature is valid.\nfunc Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool {\n\t\/\/ See [NSA] 3.4.2\n\tc := pub.Curve\n\tN := c.Params().N\n\n\tif r.Sign() <= 0 || s.Sign() <= 0 {\n\t\treturn false\n\t}\n\tif r.Cmp(N) >= 0 || s.Cmp(N) >= 0 {\n\t\treturn false\n\t}\n\treturn verify(pub, c, hash, r, s)\n}\n\nfunc verifyGeneric(pub *PublicKey, c elliptic.Curve, hash []byte, r, s *big.Int) bool {\n\te := hashToInt(hash, c)\n\tvar w *big.Int\n\tN := c.Params().N\n\tif in, ok := c.(invertible); ok {\n\t\tw = in.Inverse(s)\n\t} else {\n\t\tw = new(big.Int).ModInverse(s, N)\n\t}\n\n\tu1 := e.Mul(e, w)\n\tu1.Mod(u1, N)\n\tu2 := w.Mul(r, w)\n\tu2.Mod(u2, N)\n\n\t\/\/ Check if implements S1*g + S2*p\n\tvar x, y *big.Int\n\tif opt, ok := c.(combinedMult); ok {\n\t\tx, y = opt.CombinedMult(pub.X, pub.Y, u1.Bytes(), u2.Bytes())\n\t} else {\n\t\tx1, y1 := c.ScalarBaseMult(u1.Bytes())\n\t\tx2, y2 := c.ScalarMult(pub.X, pub.Y, u2.Bytes())\n\t\tx, y = c.Add(x1, y1, x2, y2)\n\t}\n\n\tif x.Sign() == 0 && y.Sign() == 0 {\n\t\treturn false\n\t}\n\tx.Mod(x, N)\n\treturn x.Cmp(r) == 0\n}\n\n\/\/ VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the\n\/\/ public key, pub. Its return value records whether the signature is valid.\nfunc VerifyASN1(pub *PublicKey, hash, sig []byte) bool {\n\tvar (\n\t\tr, s  = &big.Int{}, &big.Int{}\n\t\tinner cryptobyte.String\n\t)\n\tinput := cryptobyte.String(sig)\n\tif !input.ReadASN1(&inner, asn1.SEQUENCE) ||\n\t\t!input.Empty() ||\n\t\t!inner.ReadASN1Integer(r) ||\n\t\t!inner.ReadASN1Integer(s) ||\n\t\t!inner.Empty() {\n\t\treturn false\n\t}\n\treturn Verify(pub, hash, r, s)\n}\n\ntype zr struct {\n\tio.Reader\n}\n\n\/\/ Read replaces the contents of dst with zeros.\nfunc (z *zr) Read(dst []byte) (n int, err error) {\n\tfor i := range dst {\n\t\tdst[i] = 0\n\t}\n\treturn len(dst), nil\n}\n\nvar zeroReader = &zr{}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"compress\/flate\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"os\"\n)\n\ntype PDFormat struct {\n\tName             [32]byte \/\/start at byte 0\n\tAttributes       uint16   \/\/32\n\tVersion          uint16   \/\/34\n\tCreationDate     uint32   \/\/36\n\tModifyDate       uint32   \/\/40\n\tBackupDate       uint32   \/\/44\n\tModifyNumber     uint32   \/\/48\n\tAppInfoID        uint32   \/\/52\n\tSortInfoID       uint32   \/\/56\n\tType             [4]byte  \/\/60\n\tCreator          [4]byte  \/\/64\n\tUniqueIDSeed     uint32   \/\/68\n\tNextRecordListID uint32   \/\/72\n\tSectionCount     uint16   \/\/76-78\n}\n\ntype PDRecordInfoSection struct {\n\tDataOffset uint32  \/\/starts at byte 0\n\tAttributes byte    \/\/4\n\tUniqueID   [3]byte \/\/5-8\n}\n\ntype PDHeader struct {\n\tCompressionType uint16 \/\/starts at byte 0\n\t_               uint16 \/\/2 (always zero?)\n\tTextLength      uint32 \/\/4\n\tRecordCount     uint16 \/\/8\n\tRecordSize      uint16 \/\/10\n\tCurrentPosition uint32 \/\/12-16\n}\n\ntype Mobi8Header struct {\n\t\/\/note that since the values are being read\n\t\/\/by bytes.Read, we can't use \"_\" as a name,\n\t\/\/or have any unexported fields.\n\t\/\/This is stupid, but whatever.\n\t\/\/We use the name \"SkipX\" instead.\n\tCompressionType     uint16   \/\/start at byte 0\n\tSkip1               uint16   \/\/2 (always zero?)\n\tTextLength          uint32   \/\/4\n\tRecordCount         uint16   \/\/8\n\tRecordSize          uint16   \/\/10\n\tCryptoType          uint16   \/\/12\n\tSkip2               uint16   \/\/14 filler\n\tIdentifier          [4]byte  \/\/16\n\tHeaderLength        uint32   \/\/20\n\tType                uint32   \/\/24\n\tTextEncoding        uint32   \/\/28\n\tUniqueID            uint32   \/\/32\n\tVersion             uint32   \/\/36\n\tOrtographicIndex    uint32   \/\/40\n\tIncflectionIndex    uint32   \/\/44\n\tIndexNames          uint32   \/\/48\n\tIndexKeys           uint32   \/\/52\n\tExtra               [24]byte \/\/56\n\tFirstNontext        uint32   \/\/80\n\tTitleOffset         uint32   \/\/84\n\tTitleLength         uint32   \/\/88\n\tLocale              uint32   \/\/92\n\tInputLanguage       uint32   \/\/96\n\tOutputLanguage      uint32   \/\/100\n\tMinVersion          uint32   \/\/104\n\tFirstImageOffset    uint32   \/\/108\n\tHuffmanRecordOffset uint32   \/\/112\n\tHuffmanRecordCount  uint32   \/\/116\n\tHuffmanTableOffset  uint32   \/\/120\n\tHuffTableLength     uint32   \/\/124\n\tExthFlags           uint32   \/\/128\n\tSkip3               [32]byte \/\/132\n\tUnknown0            uint32   \/\/164\n\tDrmOffset           uint32   \/\/168\n\tDrmCount            uint32   \/\/172\n\tDrmSize             uint32   \/\/176\n\tDrmFlags            uint32   \/\/180\n\tSkip4               [8]byte  \/\/184\n\tFirstContentNumber  uint32   \/\/192\n\tFdstFlowCount       uint32   \/\/196\n\tFcisOffset          uint32   \/\/200\n\tFcisCount           uint32   \/\/204\n\tFlisOffset          uint32   \/\/208\n\tFlisCount           uint32   \/\/212\n\tSkip5               [8]byte  \/\/216\n\tSrcsOffset          uint32   \/\/224\n\tSrcsCount           uint32   \/\/228\n\tSkip6               [8]byte  \/\/232\n\tTrailDataFlags      uint16   \/\/240\n\tNcxIndex            uint32   \/\/242\n\tFragmentIndex       uint32   \/\/246\n\tSkeletonIndex       uint32   \/\/250\n\tDatpOffset          uint32   \/\/254\n\tGuideIndex          uint32   \/\/258-262\n}\n\nfunc GetStruct(file *os.File, hd interface{}, length int, offset int64) (rd int, err error) {\n\tb := make([]byte, length)\n\trd, err = file.ReadAt(b, offset)\n\tif err != nil {\n\t\treturn\n\t}\n\tbuf := bytes.NewBuffer(b)\n\terr = binary.Read(buf, binary.BigEndian, hd)\n\treturn\n}\n\ntype ExthHeader struct {\n\tIdentifier   uint32 \/\/starts at byte 0\n\tHeaderLength uint32 \/\/4\n\tRecordCount  uint32 \/\/8-12\n}\n\ntype ExthRecordInfo struct {\n\tRecordType   uint32 \/\/starts at 0\n\tRecordLength uint32 \/\/4-8\n}\n\ntype ExthRecordData []byte\n\ntype FileHeader struct {\n\tFormat     PDFormat\n\tSections   []PDRecordInfoSection\n\tMobiHeader Mobi8Header\n\tFcis       FcisRecord\n}\n\ntype FcisRecord struct {\n\tIdentifier [4]byte \/\/starts at 0, to 4 \"FCIS\"\n\tSkip1      uint32  \/\/4     20\n\tSkip2      uint32  \/\/8     16\n\tSkip3      uint32  \/\/12    1\n\tSkip4      uint32  \/\/16    0\n\tTextLength uint32  \/\/20    Same as PDHeader\n\tSkip5      uint32  \/\/24    0\n\tSkip6      uint32  \/\/28    32\n\tSkip7      uint32  \/\/32    8\n\tSkip8      uint16  \/\/36    1\n\tSkip9      uint16  \/\/38    1\n\tSkip10     uint32  \/\/40-44 0\n}\n\nfunc main() {\n\thd, err := GetFileHeader(\"file.mobi\")\n\tcheck(err)\n\tfmt.Printf(\"%#v\\n\", hd.Format)\n\tfmt.Printf(\"%#v %#v\\n\", hd.Sections[0], hd.Sections[181])\n\tfmt.Printf(\"%#v\\n\", hd.MobiHeader)\n\tfmt.Printf(\"%#v\\n\", hd.Fcis)\n}\n\n\/\/GetPDRecordInfoSectionList reads `count` items from `file`,\n\/\/starting at byte `offset` and placing the result in in `ris`.\n\/\/Returns the number of records read, and any error.\nfunc GetPDRecordInfoSectionList(file *os.File, ris *[]PDRecordInfoSection, count int, start int) (ii int, err error) {\n\tfor ii = 0; ii < count; ii++ {\n\t\tvar section PDRecordInfoSection\n\t\t_, err = GetStruct(file, &section, 8, int64(start+ii*8))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t*ris = append(*ris, section)\n\t}\n\treturn\n}\n\n\/\/GetFileHeader reads the header information from the file at path `path`.\n\/\/Returns the FileHeader as read, and any error.\nfunc GetFileHeader(path string) (hd FileHeader, err error) {\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tstart := 0\n\tif err != nil {\n\t\treturn\n\t}\n\n\tstart, err = GetStruct(file, &hd.Format, 78, 0)\n\tfmt.Println(start)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trdr := flate.NewReader(file)\n\tdefer rdr.Close()\n\n\ta, err := GetPDRecordInfoSectionList(file, &hd.Sections, int(hd.Format.SectionCount), start)\n\tfmt.Println(a)\n\tif err != nil {\n\t\treturn\n\t}\n\n\ta, err = GetStruct(file, &hd.MobiHeader, 262, int64(hd.Sections[0].DataOffset))\n\tfmt.Println(a, err)\n\n    if hd.MobiHeader.FcisCount > 0 {\n        offset := int64(hd.Sections[hd.MobiHeader.FcisOffset].DataOffset)\n        a, err = GetStruct(file, &hd.Fcis, 44, offset)\n        fmt.Println(\"FCIS\", a, err)\n    }\n\n\treturn\n}\n\n\/\/check panics when there's an error.\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n<commit_msg>added support for flis record<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"compress\/flate\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"os\"\n)\n\ntype PDFormat struct {\n\tName             [32]byte \/\/start at byte 0\n\tAttributes       uint16   \/\/32\n\tVersion          uint16   \/\/34\n\tCreationDate     uint32   \/\/36\n\tModifyDate       uint32   \/\/40\n\tBackupDate       uint32   \/\/44\n\tModifyNumber     uint32   \/\/48\n\tAppInfoID        uint32   \/\/52\n\tSortInfoID       uint32   \/\/56\n\tType             [4]byte  \/\/60\n\tCreator          [4]byte  \/\/64\n\tUniqueIDSeed     uint32   \/\/68\n\tNextRecordListID uint32   \/\/72\n\tSectionCount     uint16   \/\/76-78\n}\n\ntype PDRecordInfoSection struct {\n\tDataOffset uint32  \/\/starts at byte 0\n\tAttributes byte    \/\/4\n\tUniqueID   [3]byte \/\/5-8\n}\n\ntype PDHeader struct {\n\tCompressionType uint16 \/\/starts at byte 0\n\t_               uint16 \/\/2 (always zero?)\n\tTextLength      uint32 \/\/4\n\tRecordCount     uint16 \/\/8\n\tRecordSize      uint16 \/\/10\n\tCurrentPosition uint32 \/\/12-16\n}\n\ntype Mobi8Header struct {\n\t\/\/note that since the values are being read\n\t\/\/by bytes.Read, we can't use \"_\" as a name,\n\t\/\/or have any unexported fields.\n\t\/\/This is stupid, but whatever.\n\t\/\/We use the name \"SkipX\" instead.\n\tCompressionType     uint16   \/\/start at byte 0\n\tSkip1               uint16   \/\/2 (always zero?)\n\tTextLength          uint32   \/\/4\n\tRecordCount         uint16   \/\/8\n\tRecordSize          uint16   \/\/10\n\tCryptoType          uint16   \/\/12\n\tSkip2               uint16   \/\/14 filler\n\tIdentifier          [4]byte  \/\/16\n\tHeaderLength        uint32   \/\/20\n\tType                uint32   \/\/24\n\tTextEncoding        uint32   \/\/28\n\tUniqueID            uint32   \/\/32\n\tVersion             uint32   \/\/36\n\tOrtographicIndex    uint32   \/\/40\n\tIncflectionIndex    uint32   \/\/44\n\tIndexNames          uint32   \/\/48\n\tIndexKeys           uint32   \/\/52\n\tExtra               [24]byte \/\/56\n\tFirstNontext        uint32   \/\/80\n\tTitleOffset         uint32   \/\/84\n\tTitleLength         uint32   \/\/88\n\tLocale              uint32   \/\/92\n\tInputLanguage       uint32   \/\/96\n\tOutputLanguage      uint32   \/\/100\n\tMinVersion          uint32   \/\/104\n\tFirstImageOffset    uint32   \/\/108\n\tHuffmanRecordOffset uint32   \/\/112\n\tHuffmanRecordCount  uint32   \/\/116\n\tHuffmanTableOffset  uint32   \/\/120\n\tHuffTableLength     uint32   \/\/124\n\tExthFlags           uint32   \/\/128\n\tSkip3               [32]byte \/\/132\n\tUnknown0            uint32   \/\/164\n\tDrmOffset           uint32   \/\/168\n\tDrmCount            uint32   \/\/172\n\tDrmSize             uint32   \/\/176\n\tDrmFlags            uint32   \/\/180\n\tSkip4               [8]byte  \/\/184\n\tFirstContentNumber  uint32   \/\/192\n\tFdstFlowCount       uint32   \/\/196\n\tFcisOffset          uint32   \/\/200\n\tFcisCount           uint32   \/\/204\n\tFlisOffset          uint32   \/\/208\n\tFlisCount           uint32   \/\/212\n\tSkip5               [8]byte  \/\/216\n\tSrcsOffset          uint32   \/\/224\n\tSrcsCount           uint32   \/\/228\n\tSkip6               [8]byte  \/\/232\n\tTrailDataFlags      uint16   \/\/240\n\tNcxIndex            uint32   \/\/242\n\tFragmentIndex       uint32   \/\/246\n\tSkeletonIndex       uint32   \/\/250\n\tDatpOffset          uint32   \/\/254\n\tGuideIndex          uint32   \/\/258-262\n}\n\nfunc GetStruct(file *os.File, hd interface{}, length int, offset int64) (rd int, err error) {\n\tb := make([]byte, length)\n\trd, err = file.ReadAt(b, offset)\n\tif err != nil {\n\t\treturn\n\t}\n\tbuf := bytes.NewBuffer(b)\n\terr = binary.Read(buf, binary.BigEndian, hd)\n\treturn\n}\n\ntype ExthHeader struct {\n\tIdentifier   uint32 \/\/starts at byte 0\n\tHeaderLength uint32 \/\/4\n\tRecordCount  uint32 \/\/8-12\n}\n\ntype ExthRecordInfo struct {\n\tRecordType   uint32 \/\/starts at 0\n\tRecordLength uint32 \/\/4-8\n}\n\ntype ExthRecordData []byte\n\ntype FileHeader struct {\n\tFormat     PDFormat\n\tSections   []PDRecordInfoSection\n\tMobiHeader Mobi8Header\n\tFcis       FcisRecord\n\tFlis       FlisRecord\n}\n\ntype FlisRecord struct {\n\tIdentifier [4]byte \/\/starts at 0, \"FLIS\"\n\tSkip1      uint32  \/\/4            8\n\tSkip2      uint16  \/\/8            65\n\tSkip3      uint16  \/\/10           0\n\tSkip4      uint32  \/\/12           0\n\tSkip5      uint32  \/\/16          -1\n\tSkip6      uint16  \/\/20           1\n\tSkip7      uint16  \/\/22           3\n\tSkip8      uint32  \/\/24           3\n\tSkip9      uint32  \/\/28           1\n\tSkip10     uint32  \/\/32-36       -1\n}\n\ntype FcisRecord struct {\n\tIdentifier [4]byte \/\/starts at 0, to 4 \"FCIS\"\n\tSkip1      uint32  \/\/4     20\n\tSkip2      uint32  \/\/8     16\n\tSkip3      uint32  \/\/12    1\n\tSkip4      uint32  \/\/16    0\n\tTextLength uint32  \/\/20    Same as PDHeader\n\tSkip5      uint32  \/\/24    0\n\tSkip6      uint32  \/\/28    32\n\tSkip7      uint32  \/\/32    8\n\tSkip8      uint16  \/\/36    1\n\tSkip9      uint16  \/\/38    1\n\tSkip10     uint32  \/\/40-44 0\n}\n\nfunc main() {\n\thd, err := GetFileHeader(\"file.mobi\")\n\tcheck(err)\n\tfmt.Printf(\"%#v\\n\", hd.Format)\n\tfmt.Printf(\"%#v %#v\\n\", hd.Sections[0], hd.Sections[181])\n\tfmt.Printf(\"%#v\\n\", hd.MobiHeader)\n\tfmt.Printf(\"%#v\\n\", hd.Fcis)\n\tfmt.Printf(\"%#v\\n\", hd.Flis)\n}\n\n\/\/GetPDRecordInfoSectionList reads `count` items from `file`,\n\/\/starting at byte `offset` and placing the result in in `ris`.\n\/\/Returns the number of records read, and any error.\nfunc GetPDRecordInfoSectionList(file *os.File, ris *[]PDRecordInfoSection, count int, start int) (ii int, err error) {\n\tfor ii = 0; ii < count; ii++ {\n\t\tvar section PDRecordInfoSection\n\t\t_, err = GetStruct(file, &section, 8, int64(start+ii*8))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t*ris = append(*ris, section)\n\t}\n\treturn\n}\n\n\/\/GetFileHeader reads the header information from the file at path `path`.\n\/\/Returns the FileHeader as read, and any error.\nfunc GetFileHeader(path string) (hd FileHeader, err error) {\n\tfile, err := os.Open(path)\n\tdefer file.Close()\n\tstart := 0\n\tif err != nil {\n\t\treturn\n\t}\n\n\tstart, err = GetStruct(file, &hd.Format, 78, 0)\n\tfmt.Println(start)\n\tif err != nil {\n\t\treturn\n\t}\n\n\trdr := flate.NewReader(file)\n\tdefer rdr.Close()\n\n\ta, err := GetPDRecordInfoSectionList(file, &hd.Sections, int(hd.Format.SectionCount), start)\n\tfmt.Println(a)\n\tif err != nil {\n\t\treturn\n\t}\n\n\ta, err = GetStruct(file, &hd.MobiHeader, 262, int64(hd.Sections[0].DataOffset))\n\tfmt.Println(a, err)\n\n\tif hd.MobiHeader.FcisCount > 0 {\n\t\toffset := int64(hd.Sections[hd.MobiHeader.FcisOffset].DataOffset)\n\t\ta, err = GetStruct(file, &hd.Fcis, 44, offset)\n\t\tfmt.Println(\"FCIS\", a, err)\n\t}\n\n\tif hd.MobiHeader.FlisCount > 0 {\n\t\toffset := int64(hd.Sections[hd.MobiHeader.FlisOffset].DataOffset)\n\t\ta, err = GetStruct(file, &hd.Flis, 44, offset)\n\t\tfmt.Println(\"FCIS\", a, err)\n\t}\n\n\treturn\n}\n\n\/\/check panics when there's an error.\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Manu Martinez-Almeida.  All rights reserved.\n\/\/ Use of this source code is governed by a MIT style\n\/\/ license that can be found in the LICENSE file.\n\npackage gin\n\nimport (\n\t\"io\"\n\t\"os\"\n\n\t\"github.com\/gin-gonic\/gin\/binding\"\n)\n\nconst ENV_GIN_MODE = \"GIN_MODE\"\n\nconst (\n\tDebugMode   string = \"debug\"\n\tReleaseMode string = \"release\"\n\tTestMode    string = \"test\"\n)\nconst (\n\tdebugCode   = iota\n\treleaseCode \n\ttestCode  \n)\n\n\/\/ DefaultWriter is the default io.Writer used the Gin for debug output and\n\/\/ middleware output like Logger() or Recovery().\n\/\/ Note that both Logger and Recovery provides custom ways to configure their\n\/\/ output io.Writer.\n\/\/ To support coloring in Windows use:\n\/\/ \t\timport \"github.com\/mattn\/go-colorable\"\n\/\/ \t\tgin.DefaultWriter = colorable.NewColorableStdout()\nvar DefaultWriter io.Writer = os.Stdout\nvar DefaultErrorWriter io.Writer = os.Stderr\n\nvar ginMode = debugCode\nvar modeName = DebugMode\n\nfunc init() {\n\tmode := os.Getenv(ENV_GIN_MODE)\n\tif len(mode) == 0 {\n\t\tSetMode(DebugMode)\n\t} else {\n\t\tSetMode(mode)\n\t}\n}\n\nfunc SetMode(value string) {\n\tswitch value {\n\tcase DebugMode:\n\t\tginMode = debugCode\n\tcase ReleaseMode:\n\t\tginMode = releaseCode\n\tcase TestMode:\n\t\tginMode = testCode\n\tdefault:\n\t\tpanic(\"gin mode unknown: \" + value)\n\t}\n\tmodeName = value\n}\n\nfunc DisableBindValidation() {\n\tbinding.Validator = nil\n}\n\nfunc Mode() string {\n\treturn modeName\n}\n<commit_msg>fix: gofmt error. (#833)<commit_after>\/\/ Copyright 2014 Manu Martinez-Almeida.  All rights reserved.\n\/\/ Use of this source code is governed by a MIT style\n\/\/ license that can be found in the LICENSE file.\n\npackage gin\n\nimport (\n\t\"io\"\n\t\"os\"\n\n\t\"github.com\/gin-gonic\/gin\/binding\"\n)\n\nconst ENV_GIN_MODE = \"GIN_MODE\"\n\nconst (\n\tDebugMode   string = \"debug\"\n\tReleaseMode string = \"release\"\n\tTestMode    string = \"test\"\n)\nconst (\n\tdebugCode = iota\n\treleaseCode\n\ttestCode\n)\n\n\/\/ DefaultWriter is the default io.Writer used the Gin for debug output and\n\/\/ middleware output like Logger() or Recovery().\n\/\/ Note that both Logger and Recovery provides custom ways to configure their\n\/\/ output io.Writer.\n\/\/ To support coloring in Windows use:\n\/\/ \t\timport \"github.com\/mattn\/go-colorable\"\n\/\/ \t\tgin.DefaultWriter = colorable.NewColorableStdout()\nvar DefaultWriter io.Writer = os.Stdout\nvar DefaultErrorWriter io.Writer = os.Stderr\n\nvar ginMode = debugCode\nvar modeName = DebugMode\n\nfunc init() {\n\tmode := os.Getenv(ENV_GIN_MODE)\n\tif len(mode) == 0 {\n\t\tSetMode(DebugMode)\n\t} else {\n\t\tSetMode(mode)\n\t}\n}\n\nfunc SetMode(value string) {\n\tswitch value {\n\tcase DebugMode:\n\t\tginMode = debugCode\n\tcase ReleaseMode:\n\t\tginMode = releaseCode\n\tcase TestMode:\n\t\tginMode = testCode\n\tdefault:\n\t\tpanic(\"gin mode unknown: \" + value)\n\t}\n\tmodeName = value\n}\n\nfunc DisableBindValidation() {\n\tbinding.Validator = nil\n}\n\nfunc Mode() string {\n\treturn modeName\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/rand\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"sync\"\n\n\tMQTT \"git.eclipse.org\/gitroot\/paho\/org.eclipse.paho.mqtt.golang.git\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/cli\"\n)\n\nvar MaxClientIdLen = 8\nvar MaxRetryCount = 3\n\ntype MQTTClient struct {\n\tClient     *MQTT.Client\n\tOpts       *MQTT.ClientOptions\n\tRetryCount int\n\tSubscribed map[string]byte\n\n\tlock *sync.Mutex \/\/ use for reconnect\n}\n\n\/\/ Connects connect to the MQTT broker with Options.\nfunc (m *MQTTClient) Connect() (*MQTT.Client, error) {\n\n\tm.Client = MQTT.NewClient(m.Opts)\n\n\tlog.Info(\"connecting...\")\n\n\tif token := m.Client.Connect(); token.Wait() && token.Error() != nil {\n\t\treturn nil, token.Error()\n\t}\n\treturn m.Client, nil\n}\n\nfunc (m *MQTTClient) Publish(topic string, payload []byte, qos int, retain bool, sync bool) error {\n\ttoken := m.Client.Publish(topic, byte(qos), retain, payload)\n\n\tif sync == true {\n\t\ttoken.Wait()\n\t}\n\n\treturn token.Error()\n}\n\nfunc (m *MQTTClient) Disconnect() error {\n\tif m.Client.IsConnected() {\n\t\tm.Client.Disconnect(20)\n\t\tlog.Info(\"client disconnected\")\n\t}\n\treturn nil\n}\n\nfunc (m *MQTTClient) SubscribeOnConnect(client *MQTT.Client) {\n\tlog.Infof(\"client connected\")\n\n\ttoken := client.SubscribeMultiple(m.Subscribed, m.onMessageReceived)\n\ttoken.Wait()\n\tif token.Error() != nil {\n\t\tlog.Error(token.Error())\n\t}\n}\n\nfunc (m *MQTTClient) ConnectionLost(client *MQTT.Client, reason error) {\n\tlog.Errorf(\"client disconnected: %s\", reason)\n}\n\nfunc (m *MQTTClient) onMessageReceived(client *MQTT.Client, message MQTT.Message) {\n\tlog.Infof(\"topic:%s  \/ msg:%s\", message.Topic(), message.Payload())\n\tfmt.Println(string(message.Payload()))\n}\n\nfunc getCertPool(pemPath string) (*x509.CertPool, error) {\n\tcerts := x509.NewCertPool()\n\n\tpemData, err := ioutil.ReadFile(pemPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcerts.AppendCertsFromPEM(pemData)\n\treturn certs, nil\n}\n\n\/\/ getRandomClientId returns randomized ClientId.\nfunc getRandomClientId() string {\n\tconst alphanum = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\tvar bytes = make([]byte, MaxClientIdLen)\n\trand.Read(bytes)\n\tfor i, b := range bytes {\n\t\tbytes[i] = alphanum[b%byte(len(alphanum))]\n\t}\n\treturn \"mqttcli-\" + string(bytes)\n}\n\n\/\/ NewOption returns ClientOptions via parsing command line options.\nfunc NewOption(c *cli.Context) (*MQTT.ClientOptions, error) {\n\topts := MQTT.NewClientOptions()\n\n\thost := c.String(\"host\")\n\tport := c.Int(\"p\")\n\n\tif host == \"\" {\n\t\tgetSettingsFromFile(c.String(\"conf\"), opts)\n\t}\n\n\tclientId := c.String(\"i\")\n\tif clientId == \"\" {\n\t\tclientId = getRandomClientId()\n\t}\n\topts.SetClientID(clientId)\n\n\tTLSConfig := &tls.Config{InsecureSkipVerify: false}\n\tcafile := c.String(\"cafile\")\n\tscheme := \"tcp\"\n\tif cafile != \"\" {\n\t\tscheme = \"ssl\"\n\t\tcertPool, err := getCertPool(cafile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tTLSConfig.RootCAs = certPool\n\t}\n\tinsecure := c.Bool(\"insecure\")\n\tif insecure {\n\t\tTLSConfig.InsecureSkipVerify = true\n\t}\n\topts.SetTLSConfig(TLSConfig)\n\n\tuser := c.String(\"u\")\n\tif user != \"\" {\n\t\topts.SetUsername(user)\n\t}\n\tpassword := c.String(\"P\")\n\tif password != \"\" {\n\t\topts.SetPassword(password)\n\t}\n\n\tif host != \"\" {\n\t\tbrokerUri := fmt.Sprintf(\"%s:\/\/%s:%d\", scheme, host, port)\n\t\tlog.Infof(\"Broker URI: %s\", brokerUri)\n\n\t\topts.AddBroker(brokerUri)\n\t}\n\n\topts.SetAutoReconnect(true)\n\treturn opts, nil\n}\n<commit_msg>not subscribe if publish or subscribe not set.<commit_after>package main\n\nimport (\n\t\"crypto\/rand\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"sync\"\n\n\tMQTT \"git.eclipse.org\/gitroot\/paho\/org.eclipse.paho.mqtt.golang.git\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/cli\"\n)\n\nvar MaxClientIdLen = 8\nvar MaxRetryCount = 3\n\ntype MQTTClient struct {\n\tClient     *MQTT.Client\n\tOpts       *MQTT.ClientOptions\n\tRetryCount int\n\tSubscribed map[string]byte\n\n\tlock *sync.Mutex \/\/ use for reconnect\n}\n\n\/\/ Connects connect to the MQTT broker with Options.\nfunc (m *MQTTClient) Connect() (*MQTT.Client, error) {\n\n\tm.Client = MQTT.NewClient(m.Opts)\n\n\tlog.Info(\"connecting...\")\n\n\tif token := m.Client.Connect(); token.Wait() && token.Error() != nil {\n\t\treturn nil, token.Error()\n\t}\n\treturn m.Client, nil\n}\n\nfunc (m *MQTTClient) Publish(topic string, payload []byte, qos int, retain bool, sync bool) error {\n\ttoken := m.Client.Publish(topic, byte(qos), retain, payload)\n\n\tif sync == true {\n\t\ttoken.Wait()\n\t}\n\n\treturn token.Error()\n}\n\nfunc (m *MQTTClient) Disconnect() error {\n\tif m.Client.IsConnected() {\n\t\tm.Client.Disconnect(20)\n\t\tlog.Info(\"client disconnected\")\n\t}\n\treturn nil\n}\n\nfunc (m *MQTTClient) SubscribeOnConnect(client *MQTT.Client) {\n\tlog.Infof(\"client connected\")\n\n\tif len(m.Subscribed) > 0 {\n\t\ttoken := client.SubscribeMultiple(m.Subscribed, m.onMessageReceived)\n\t\ttoken.Wait()\n\t\tif token.Error() != nil {\n\t\t\tlog.Error(token.Error())\n\t\t}\n\t}\n}\n\nfunc (m *MQTTClient) ConnectionLost(client *MQTT.Client, reason error) {\n\tlog.Errorf(\"client disconnected: %s\", reason)\n}\n\nfunc (m *MQTTClient) onMessageReceived(client *MQTT.Client, message MQTT.Message) {\n\tlog.Infof(\"topic:%s \/ msg:%s\", message.Topic(), message.Payload())\n\tfmt.Println(string(message.Payload()))\n}\n\nfunc getCertPool(pemPath string) (*x509.CertPool, error) {\n\tcerts := x509.NewCertPool()\n\n\tpemData, err := ioutil.ReadFile(pemPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcerts.AppendCertsFromPEM(pemData)\n\treturn certs, nil\n}\n\n\/\/ getRandomClientId returns randomized ClientId.\nfunc getRandomClientId() string {\n\tconst alphanum = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\tvar bytes = make([]byte, MaxClientIdLen)\n\trand.Read(bytes)\n\tfor i, b := range bytes {\n\t\tbytes[i] = alphanum[b%byte(len(alphanum))]\n\t}\n\treturn \"mqttcli-\" + string(bytes)\n}\n\n\/\/ NewOption returns ClientOptions via parsing command line options.\nfunc NewOption(c *cli.Context) (*MQTT.ClientOptions, error) {\n\topts := MQTT.NewClientOptions()\n\n\thost := c.String(\"host\")\n\tport := c.Int(\"p\")\n\n\tif host == \"\" {\n\t\tgetSettingsFromFile(c.String(\"conf\"), opts)\n\t}\n\n\tclientId := c.String(\"i\")\n\tif clientId == \"\" {\n\t\tclientId = getRandomClientId()\n\t}\n\topts.SetClientID(clientId)\n\n\tTLSConfig := &tls.Config{InsecureSkipVerify: false}\n\tcafile := c.String(\"cafile\")\n\tscheme := \"tcp\"\n\tif cafile != \"\" {\n\t\tscheme = \"ssl\"\n\t\tcertPool, err := getCertPool(cafile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tTLSConfig.RootCAs = certPool\n\t}\n\tinsecure := c.Bool(\"insecure\")\n\tif insecure {\n\t\tTLSConfig.InsecureSkipVerify = true\n\t}\n\topts.SetTLSConfig(TLSConfig)\n\n\tuser := c.String(\"u\")\n\tif user != \"\" {\n\t\topts.SetUsername(user)\n\t}\n\tpassword := c.String(\"P\")\n\tif password != \"\" {\n\t\topts.SetPassword(password)\n\t}\n\n\tif host != \"\" {\n\t\tbrokerUri := fmt.Sprintf(\"%s:\/\/%s:%d\", scheme, host, port)\n\t\tlog.Infof(\"Broker URI: %s\", brokerUri)\n\n\t\topts.AddBroker(brokerUri)\n\t}\n\n\topts.SetAutoReconnect(true)\n\treturn opts, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n)\n\nvar (\n\tstatements map[string]string = map[string]string{\n\t\t\"by_email\": \"SELECT * FROM `bucket-1` WHERE email='%s'\",\n\t}\n)\n\ntype queryClient struct {\n\turl, index, consistency string\n}\n\nfunc newQueryClient(config nbConfig) *queryClient {\n\tclient := queryClient{\n\t\turl:         fmt.Sprintf(\"%s\/query\/service\", config.Database.Address.N1QL),\n\t\tindex:       config.Query.Index,\n\t\tconsistency: config.Query.Consistency,\n\t}\n\treturn &client\n}\n\nfunc (c *queryClient) post(statement string) error {\n\tvalues := url.Values{\n\t\t\"statement\":        []string{statement},\n\t\t\"scan_consistency\": []string{c.consistency},\n\t}\n\n\tresp, err := http.PostForm(c.url, values)\n\tdefer resp.Body.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn errors.New(fmt.Sprintf(\"unexpected status code: %d\", resp.StatusCode))\n\t}\n\n\tif _, err = ioutil.ReadAll(resp.Body); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *queryClient) query(value doc) error {\n\tvar statement string\n\n\tswitch c.index {\n\tcase \"by_email\":\n\t\tstatement = fmt.Sprintf(statements[c.index], value.Email)\n\tdefault:\n\t\tfatalf(\"unknown index: %s\\n\", c.index)\n\t}\n\n\treturn c.post(statement)\n}\n<commit_msg>Fix golint issue<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n)\n\nvar (\n\tstatements map[string]string = map[string]string{\n\t\t\"by_email\": \"SELECT * FROM `bucket-1` WHERE email='%s'\",\n\t}\n)\n\ntype queryClient struct {\n\turl, index, consistency string\n}\n\nfunc newQueryClient(config nbConfig) *queryClient {\n\tclient := queryClient{\n\t\turl:         fmt.Sprintf(\"%s\/query\/service\", config.Database.Address.N1QL),\n\t\tindex:       config.Query.Index,\n\t\tconsistency: config.Query.Consistency,\n\t}\n\treturn &client\n}\n\nfunc (c *queryClient) post(statement string) error {\n\tvalues := url.Values{\n\t\t\"statement\":        []string{statement},\n\t\t\"scan_consistency\": []string{c.consistency},\n\t}\n\n\tresp, err := http.PostForm(c.url, values)\n\tdefer resp.Body.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"unexpected status code: %d\", resp.StatusCode)\n\t}\n\n\tif _, err = ioutil.ReadAll(resp.Body); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c *queryClient) query(value doc) error {\n\tvar statement string\n\n\tswitch c.index {\n\tcase \"by_email\":\n\t\tstatement = fmt.Sprintf(statements[c.index], value.Email)\n\tdefault:\n\t\tfatalf(\"unknown index: %s\\n\", c.index)\n\t}\n\n\treturn c.post(statement)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2015 Xuyuan Pang <xuyuanp # gmail dot com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage hador\n\nimport (\n\t\"container\/list\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/Xuyuanp\/hador\/swagger\"\n)\n\nfunc splitSegments(path string) []string {\n\tpath = trimPath(path)\n\tif len(path) == 0 {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(path, \"\/\")\n}\n\nfunc isReg(segment string) bool {\n\tif regSegmentRegexp.MatchString(segment) {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(segment, \"{\") && strings.HasSuffix(segment, \"}\") {\n\t\treturn true\n\t}\n\treturn false\n}\n\nvar regSegmentRegexp = regexp.MustCompile(`\\(\\?P<.+>.+\\)`)\n\ntype dispatcher struct {\n\tnode *Node\n}\n\nfunc (d *dispatcher) Serve(ctx *Context) {\n\tn := d.node\n\n\tsegment := ctx.segment()\n\n\t\/\/ path matches\n\tif len(segment) == 0 {\n\t\tn.doServe(ctx)\n\t\treturn\n\t}\n\n\t\/\/ find next node\n\tnext := n.findNext(segment)\n\tif next != nil {\n\t\tif next.paramReg != nil {\n\t\t\tctx.Params()[next.paramName] = segment\n\t\t}\n\t\tnext.Serve(ctx)\n\t\treturn\n\t}\n\t\/\/ 404 not found\n\tctx.OnError(http.StatusNotFound)\n}\n\n\/\/ Node struct\ntype Node struct {\n\t*FilterChain\n\th           *Hador\n\tparent      *Node\n\tdepth       int\n\tsegment     string\n\tparamName   string\n\tparamReg    *regexp.Regexp\n\trawChildren map[string]*Node\n\tregChildren []*Node\n\tleaves      map[Method]*Leaf\n}\n\n\/\/ NewNode creates new Node instance.\nfunc NewNode(h *Hador, segment string, depth int) *Node {\n\tparamName, paramReg := resolveSegment(segment)\n\tn := &Node{\n\t\th:           h,\n\t\tsegment:     segment,\n\t\tdepth:       depth,\n\t\tparamName:   paramName,\n\t\tparamReg:    paramReg,\n\t\trawChildren: make(map[string]*Node),\n\t\tregChildren: make([]*Node, 0),\n\t\tleaves:      make(map[Method]*Leaf),\n\t}\n\tn.FilterChain = NewFilterChain(&dispatcher{node: n})\n\treturn n\n}\n\nfunc resolveSegment(segment string) (paramName string, paramReg *regexp.Regexp) {\n\tvar splits []string\n\tif strings.HasPrefix(segment, \"{\") && strings.HasSuffix(segment, \"}\") {\n\t\tseg := segment[1 : len(segment)-1]\n\t\tsplits = strings.SplitN(seg, \":\", 2)\n\t\tif len(splits) == 1 {\n\t\t\tsplits = append(splits, \".+\")\n\t\t}\n\t} else if regSegmentRegexp.MatchString(segment) {\n\t\tseg := segment[4 : len(segment)-1]\n\t\tsplits = strings.SplitN(seg, \">\", 2)\n\t}\n\tif splits != nil && len(splits) == 2 {\n\t\tparamName = splits[0]\n\t\tregstr := splits[1]\n\t\tif !strings.HasPrefix(regstr, \"^\") {\n\t\t\tregstr = \"^\" + regstr\n\t\t}\n\t\tif !strings.HasSuffix(regstr, \"$\") {\n\t\t\tregstr = regstr + \"$\"\n\t\t}\n\t\tparamReg = regexp.MustCompile(regstr)\n\t}\n\treturn\n}\n\n\/\/ AddRoute adds a new route with method, pattern and handler\nfunc (n *Node) AddRoute(method Method, pattern string, h interface{}, filters ...Filter) *Leaf {\n\thandler := parseHandler(h)\n\tsegments := splitSegments(pattern)\n\tif _, l, ok := n.add(segments, method, handler, filters...); ok {\n\t\treturn l\n\t}\n\tpanic(fmt.Errorf(\"pattern: %s has been registered\", pattern))\n}\n\nfunc (n *Node) add(segments []string, method Method, handler Handler, filters ...Filter) (*Node, *Leaf, bool) {\n\tif len(segments) == 0 {\n\t\tif method != \"\" && handler != nil {\n\t\t\tl, ok := n.handle(method, handler, filters...)\n\t\t\treturn n, l, ok\n\t\t}\n\t\tn.AddFilters(filters...)\n\t\treturn n, nil, true\n\t}\n\n\tsegment := segments[0]\n\tnext := n.findOrCreateNext(segment)\n\treturn next.add(segments[1:], method, handler, filters...)\n}\n\nfunc (n *Node) handle(method Method, handler Handler, filters ...Filter) (l *Leaf, ok bool) {\n\tif _, ok := n.leaves[method]; ok {\n\t\treturn nil, false\n\t}\n\tl = NewLeaf(n, method, handler)\n\tn.leaves[method] = l\n\tl.AddFilters(filters...)\n\treturn l, true\n}\n\nfunc (n *Node) findOrCreateNext(segment string) (next *Node) {\n\tif !isReg(segment) {\n\t\tif ne, ok := n.rawChildren[segment]; ok {\n\t\t\tnext = ne\n\t\t} else {\n\t\t\tnext = NewNode(n.h, segment, n.depth+1)\n\t\t\tn.rawChildren[segment] = next\n\t\t}\n\t} else {\n\t\tfound := false\n\t\tfor _, next = range n.regChildren {\n\t\t\tif next.segment == segment {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tnext = NewNode(n.h, segment, n.depth+1)\n\t\t\tn.regChildren = append(n.regChildren, next)\n\t\t}\n\t}\n\tnext.parent = n\n\treturn\n}\n\nfunc (n *Node) findNext(segment string) (next *Node) {\n\tif ne, ok := n.rawChildren[segment]; ok {\n\t\tnext = ne\n\t} else {\n\t\tfor _, ne := range n.regChildren {\n\t\t\tif ne.MatchRegexp(segment) {\n\t\t\t\tnext = ne\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (n *Node) doServe(ctx *Context) {\n\t\/\/ 404 not found\n\tif len(n.leaves) == 0 {\n\t\tctx.OnError(http.StatusNotFound)\n\t\treturn\n\t}\n\t\/\/ method matches\n\tif l, ok := n.leaves[Method(ctx.Request.Method)]; ok {\n\t\tl.Serve(ctx)\n\t\treturn\n\t}\n\t\/\/ ANY matches\n\tif l, ok := n.leaves[\"ANY\"]; ok {\n\t\tl.Serve(ctx)\n\t\treturn\n\t}\n\t\/\/ 405 method not allowed\n\tmethods := make([]Method, len(n.leaves))\n\ti := 0\n\tfor m := range n.leaves {\n\t\tmethods[i] = m\n\t\ti++\n\t}\n\tctx.OnError(http.StatusMethodNotAllowed, methods)\n}\n\n\/\/ MatchRegexp checks if the segment match regexp in node\nfunc (n *Node) MatchRegexp(segment string) bool {\n\tif n.paramReg != nil && n.paramReg.MatchString(segment) {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ Setter returns a setter-chain to add a new route.\nfunc (n *Node) Setter() MethodSetter {\n\treturn func(method Method) PathSetter {\n\t\treturn func(path string) HandlerSetter {\n\t\t\treturn func(handler interface{}, filters ...Filter) *swagger.Operation {\n\t\t\t\treturn n.AddRoute(method, path, handler, filters...).SwaggerOperation()\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Path returns the full path from root to the node\nfunc (n *Node) Path() string {\n\tif n.parent == nil {\n\t\treturn \"\/\"\n\t}\n\tppath := n.parent.Path()\n\tif ppath == \"\/\" {\n\t\tppath = \"\"\n\t}\n\tif n.paramName != \"\" {\n\t\treturn ppath + \"\/{\" + n.paramName + \"}\"\n\t}\n\treturn ppath + \"\/\" + n.segment\n}\n\n\/\/ Parent returns the node's parent node\nfunc (n *Node) Parent() *Node {\n\treturn n.parent\n}\n\n\/\/ Depth returns the nodes' depth\nfunc (n *Node) Depth() int {\n\treturn n.depth\n}\n\n\/\/ Segment returns node's segment\nfunc (n *Node) Segment() string {\n\treturn n.segment\n}\n\n\/\/ Leaves returns all of node's leaves\nfunc (n *Node) Leaves() []*Leaf {\n\tleaves := make([]*Leaf, len(n.leaves))\n\ti := 0\n\tfor _, l := range n.leaves {\n\t\tleaves[i] = l\n\t\ti++\n\t}\n\treturn leaves[:i]\n}\n\nfunc (n *Node) travel(llist *list.List) {\n\tfor _, l := range n.leaves {\n\t\tllist.PushBack(l)\n\t}\n\tfor _, child := range n.rawChildren {\n\t\tchild.travel(llist)\n\t}\n\tfor _, child := range n.regChildren {\n\t\tchild.travel(llist)\n\t}\n}\n<commit_msg>Removed dispatcher; Node serves requests by itself.<commit_after>\/*\n * Copyright 2015 Xuyuan Pang <xuyuanp # gmail dot com>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage hador\n\nimport (\n\t\"container\/list\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/Xuyuanp\/hador\/swagger\"\n)\n\nfunc splitSegments(path string) []string {\n\tpath = trimPath(path)\n\tif len(path) == 0 {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(path, \"\/\")\n}\n\nfunc isReg(segment string) bool {\n\tif regSegmentRegexp.MatchString(segment) {\n\t\treturn true\n\t}\n\tif strings.HasPrefix(segment, \"{\") && strings.HasSuffix(segment, \"}\") {\n\t\treturn true\n\t}\n\treturn false\n}\n\nvar regSegmentRegexp = regexp.MustCompile(`\\(\\?P<.+>.+\\)`)\n\n\/\/ Node struct\ntype Node struct {\n\th           *Hador\n\tparent      *Node\n\tdepth       int\n\tsegment     string\n\tparamName   string\n\tparamReg    *regexp.Regexp\n\trawChildren map[string]*Node\n\tregChildren []*Node\n\tleaves      map[Method]*Leaf\n}\n\n\/\/ NewNode creates new Node instance.\nfunc NewNode(h *Hador, segment string, depth int) *Node {\n\tparamName, paramReg := resolveSegment(segment)\n\tn := &Node{\n\t\th:           h,\n\t\tsegment:     segment,\n\t\tdepth:       depth,\n\t\tparamName:   paramName,\n\t\tparamReg:    paramReg,\n\t\trawChildren: make(map[string]*Node),\n\t\tregChildren: make([]*Node, 0),\n\t\tleaves:      make(map[Method]*Leaf),\n\t}\n\treturn n\n}\n\nfunc resolveSegment(segment string) (paramName string, paramReg *regexp.Regexp) {\n\tvar splits []string\n\tif strings.HasPrefix(segment, \"{\") && strings.HasSuffix(segment, \"}\") {\n\t\tseg := segment[1 : len(segment)-1]\n\t\tsplits = strings.SplitN(seg, \":\", 2)\n\t\tif len(splits) == 1 {\n\t\t\tsplits = append(splits, \".+\")\n\t\t}\n\t} else if regSegmentRegexp.MatchString(segment) {\n\t\tseg := segment[4 : len(segment)-1]\n\t\tsplits = strings.SplitN(seg, \">\", 2)\n\t}\n\tif splits != nil && len(splits) == 2 {\n\t\tparamName = splits[0]\n\t\tregstr := splits[1]\n\t\tif !strings.HasPrefix(regstr, \"^\") {\n\t\t\tregstr = \"^\" + regstr\n\t\t}\n\t\tif !strings.HasSuffix(regstr, \"$\") {\n\t\t\tregstr = regstr + \"$\"\n\t\t}\n\t\tparamReg = regexp.MustCompile(regstr)\n\t}\n\treturn\n}\n\n\/\/ AddRoute adds a new route with method, pattern and handler\nfunc (n *Node) AddRoute(method Method, pattern string, h interface{}, filters ...Filter) *Leaf {\n\thandler := parseHandler(h)\n\tsegments := splitSegments(pattern)\n\tif _, l, ok := n.add(segments, method, handler, filters...); ok {\n\t\treturn l\n\t}\n\tpanic(fmt.Errorf(\"pattern: %s has been registered\", pattern))\n}\n\nfunc (n *Node) add(segments []string, method Method, handler Handler, filters ...Filter) (*Node, *Leaf, bool) {\n\tif len(segments) == 0 {\n\t\tif method != \"\" && handler != nil {\n\t\t\tl, ok := n.handle(method, handler, filters...)\n\t\t\treturn n, l, ok\n\t\t}\n\t\treturn n, nil, true\n\t}\n\n\tsegment := segments[0]\n\tnext := n.findOrCreateNext(segment)\n\treturn next.add(segments[1:], method, handler, filters...)\n}\n\nfunc (n *Node) handle(method Method, handler Handler, filters ...Filter) (l *Leaf, ok bool) {\n\tif _, ok := n.leaves[method]; ok {\n\t\treturn nil, false\n\t}\n\tl = NewLeaf(n, method, handler)\n\tn.leaves[method] = l\n\tl.AddFilters(filters...)\n\treturn l, true\n}\n\nfunc (n *Node) findOrCreateNext(segment string) (next *Node) {\n\tif !isReg(segment) {\n\t\tif ne, ok := n.rawChildren[segment]; ok {\n\t\t\tnext = ne\n\t\t} else {\n\t\t\tnext = NewNode(n.h, segment, n.depth+1)\n\t\t\tn.rawChildren[segment] = next\n\t\t}\n\t} else {\n\t\tfound := false\n\t\tfor _, next = range n.regChildren {\n\t\t\tif next.segment == segment {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tnext = NewNode(n.h, segment, n.depth+1)\n\t\t\tn.regChildren = append(n.regChildren, next)\n\t\t}\n\t}\n\tnext.parent = n\n\treturn\n}\n\nfunc (n *Node) findNext(segment string) (next *Node) {\n\tif ne, ok := n.rawChildren[segment]; ok {\n\t\tnext = ne\n\t} else {\n\t\tfor _, ne := range n.regChildren {\n\t\t\tif ne.MatchRegexp(segment) {\n\t\t\t\tnext = ne\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (n *Node) Serve(ctx *Context) {\n\tsegment := ctx.segment()\n\n\t\/\/ path matches\n\tif len(segment) == 0 {\n\t\tn.doServe(ctx)\n\t\treturn\n\t}\n\n\t\/\/ find next node\n\tnext := n.findNext(segment)\n\tif next != nil {\n\t\tif next.paramReg != nil {\n\t\t\tctx.Params()[next.paramName] = segment\n\t\t}\n\t\tnext.Serve(ctx)\n\t\treturn\n\t}\n\t\/\/ 404 not found\n\tctx.OnError(http.StatusNotFound)\n}\n\nfunc (n *Node) doServe(ctx *Context) {\n\t\/\/ 404 not found\n\tif len(n.leaves) == 0 {\n\t\tctx.OnError(http.StatusNotFound)\n\t\treturn\n\t}\n\t\/\/ method matches\n\tif l, ok := n.leaves[Method(ctx.Request.Method)]; ok {\n\t\tl.Serve(ctx)\n\t\treturn\n\t}\n\t\/\/ ANY matches\n\tif l, ok := n.leaves[\"ANY\"]; ok {\n\t\tl.Serve(ctx)\n\t\treturn\n\t}\n\t\/\/ 405 method not allowed\n\tmethods := make([]Method, len(n.leaves))\n\ti := 0\n\tfor m := range n.leaves {\n\t\tmethods[i] = m\n\t\ti++\n\t}\n\tctx.OnError(http.StatusMethodNotAllowed, methods)\n}\n\n\/\/ MatchRegexp checks if the segment match regexp in node\nfunc (n *Node) MatchRegexp(segment string) bool {\n\tif n.paramReg != nil && n.paramReg.MatchString(segment) {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ Setter returns a setter-chain to add a new route.\nfunc (n *Node) Setter() MethodSetter {\n\treturn func(method Method) PathSetter {\n\t\treturn func(path string) HandlerSetter {\n\t\t\treturn func(handler interface{}, filters ...Filter) *swagger.Operation {\n\t\t\t\treturn n.AddRoute(method, path, handler, filters...).SwaggerOperation()\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Path returns the full path from root to the node\nfunc (n *Node) Path() string {\n\tif n.parent == nil {\n\t\treturn \"\/\"\n\t}\n\tppath := n.parent.Path()\n\tif ppath == \"\/\" {\n\t\tppath = \"\"\n\t}\n\tif n.paramName != \"\" {\n\t\treturn ppath + \"\/{\" + n.paramName + \"}\"\n\t}\n\treturn ppath + \"\/\" + n.segment\n}\n\n\/\/ Parent returns the node's parent node\nfunc (n *Node) Parent() *Node {\n\treturn n.parent\n}\n\n\/\/ Depth returns the nodes' depth\nfunc (n *Node) Depth() int {\n\treturn n.depth\n}\n\n\/\/ Segment returns node's segment\nfunc (n *Node) Segment() string {\n\treturn n.segment\n}\n\n\/\/ Leaves returns all of node's leaves\nfunc (n *Node) Leaves() []*Leaf {\n\tleaves := make([]*Leaf, len(n.leaves))\n\ti := 0\n\tfor _, l := range n.leaves {\n\t\tleaves[i] = l\n\t\ti++\n\t}\n\treturn leaves[:i]\n}\n\nfunc (n *Node) travel(llist *list.List) {\n\tfor _, l := range n.leaves {\n\t\tllist.PushBack(l)\n\t}\n\tfor _, child := range n.rawChildren {\n\t\tchild.travel(llist)\n\t}\n\tfor _, child := range n.regChildren {\n\t\tchild.travel(llist)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package jiracmd\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/coryb\/figtree\"\n\t\"github.com\/coryb\/oreo\"\n\t\"github.com\/go-jira\/jira\"\n\t\"github.com\/go-jira\/jira\/jiracli\"\n\t\"github.com\/mgutz\/ansi\"\n\tkingpin \"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\nfunc CmdLoginRegistry() *jiracli.CommandRegistryEntry {\n\topts := jiracli.CommonOptions{}\n\treturn &jiracli.CommandRegistryEntry{\n\t\t\"Attempt to login into jira server\",\n\t\tfunc(fig *figtree.FigTree, cmd *kingpin.CmdClause) error {\n\t\t\tjiracli.LoadConfigs(cmd, fig, &opts)\n\t\t\treturn nil\n\t\t},\n\t\tfunc(o *oreo.Client, globals *jiracli.GlobalOptions) error {\n\t\t\treturn CmdLogin(o, globals, &opts)\n\t\t},\n\t}\n}\n\nfunc authCallback(req *http.Request, resp *http.Response) (*http.Response, error) {\n\tif resp.StatusCode == 403 {\n\t\tdefer resp.Body.Close()\n\t\t\/\/ X-Authentication-Denied-Reason: CAPTCHA_CHALLENGE; login-url=https:\/\/jira\/login.jsp\n\t\tif reason := resp.Header.Get(\"X-Authentication-Denied-Reason\"); reason != \"\" {\n\t\t\treturn resp, fmt.Errorf(\"Authenticaion Failed: \" + reason)\n\t\t}\n\t\treturn resp, fmt.Errorf(\"Authenticaion Failed: Unkown Reason\")\n\t} else if resp.StatusCode == 200 {\n\t\tif reason := resp.Header.Get(\"X-Seraph-Loginreason\"); reason == \"AUTHENTICATION_DENIED\" {\n\t\t\tdefer resp.Body.Close()\n\t\t\treturn resp, fmt.Errorf(\"Authentication Failed: \" + reason)\n\t\t}\n\t}\n\n\treturn resp, nil\n}\n\n\/\/ CmdLogin will attempt to login into jira server\nfunc CmdLogin(o *oreo.Client, globals *jiracli.GlobalOptions, opts *jiracli.CommonOptions) error {\n\tif globals.AuthMethod() == \"api-token\" {\n\t\tlog.Noticef(\"No need to login when using api-token authentication method\")\n\t\treturn nil\n\t}\n\n\tua := o.WithoutRedirect().WithRetries(0).WithoutCallbacks().WithPostCallback(authCallback)\n\tfor {\n\t\tif session, err := jira.GetSession(o, globals.Endpoint.Value); err != nil {\n\t\t\t\/\/ No active session so try to create a new one\n\t\t\t_, err := jira.NewSession(ua, globals.Endpoint.Value, globals)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ reset password on failed session\n\t\t\t\tglobals.SetPass(\"\")\n\t\t\t\tlog.Errorf(\"%s\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !globals.Quiet.Value {\n\t\t\t\tfmt.Println(ansi.Color(\"OK\", \"green\"), \"New session for\", globals.User)\n\t\t\t}\n\t\t\tbreak\n\t\t} else {\n\t\t\tif !globals.Quiet.Value {\n\t\t\t\tfmt.Println(ansi.Color(\"OK\", \"green\"), \"Found session for\", session.Name)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Remove (possible) infinite loop from CmdLogin.<commit_after>package jiracmd\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/coryb\/figtree\"\n\t\"github.com\/coryb\/oreo\"\n\t\"github.com\/go-jira\/jira\"\n\t\"github.com\/go-jira\/jira\/jiracli\"\n\t\"github.com\/mgutz\/ansi\"\n\tkingpin \"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\nfunc CmdLoginRegistry() *jiracli.CommandRegistryEntry {\n\topts := jiracli.CommonOptions{}\n\treturn &jiracli.CommandRegistryEntry{\n\t\t\"Attempt to login into jira server\",\n\t\tfunc(fig *figtree.FigTree, cmd *kingpin.CmdClause) error {\n\t\t\tjiracli.LoadConfigs(cmd, fig, &opts)\n\t\t\treturn nil\n\t\t},\n\t\tfunc(o *oreo.Client, globals *jiracli.GlobalOptions) error {\n\t\t\treturn CmdLogin(o, globals, &opts)\n\t\t},\n\t}\n}\n\nfunc authCallback(req *http.Request, resp *http.Response) (*http.Response, error) {\n\tif resp.StatusCode == 403 {\n\t\tdefer resp.Body.Close()\n\t\t\/\/ X-Authentication-Denied-Reason: CAPTCHA_CHALLENGE; login-url=https:\/\/jira\/login.jsp\n\t\tif reason := resp.Header.Get(\"X-Authentication-Denied-Reason\"); reason != \"\" {\n\t\t\treturn resp, fmt.Errorf(\"Authenticaion Failed: \" + reason)\n\t\t}\n\t\treturn resp, fmt.Errorf(\"Authenticaion Failed: Unkown Reason\")\n\t} else if resp.StatusCode == 200 {\n\t\tif reason := resp.Header.Get(\"X-Seraph-Loginreason\"); reason == \"AUTHENTICATION_DENIED\" {\n\t\t\tdefer resp.Body.Close()\n\t\t\treturn resp, fmt.Errorf(\"Authentication Failed: \" + reason)\n\t\t}\n\t}\n\n\treturn resp, nil\n}\n\n\/\/ CmdLogin will attempt to login into jira server\nfunc CmdLogin(o *oreo.Client, globals *jiracli.GlobalOptions, opts *jiracli.CommonOptions) error {\n\tif globals.AuthMethod() == \"api-token\" {\n\t\tlog.Noticef(\"No need to login when using api-token authentication method\")\n\t\treturn nil\n\t}\n\n\tua := o.WithoutRedirect().WithRetries(0).WithoutCallbacks().WithPostCallback(authCallback)\n\n\tif session, err := jira.GetSession(o, globals.Endpoint.Value); err != nil {\n\t\t\/\/ No active session so try to create a new one\n\t\t_, err := jira.NewSession(ua, globals.Endpoint.Value, globals)\n\t\tif err != nil {\n\t\t\t\/\/ reset password on failed session\n\t\t\tglobals.SetPass(\"\")\n\t\t\tlog.Errorf(\"%s\", err)\n\t\t} else if !globals.Quiet.Value {\n\t\t\tfmt.Println(ansi.Color(\"OK\", \"green\"), \"New session for\", globals.User)\n\t\t}\n\t} else {\n\t\tif !globals.Quiet.Value {\n\t\t\tfmt.Println(ansi.Color(\"OK\", \"green\"), \"Found session for\", session.Name)\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package diff\n\nimport (\n\t\"fmt\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/engine\/apply\/action\/component\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/engine\/apply\/action\/global\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/engine\/resolve\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/event\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/lang\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/lang\/builder\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/util\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"testing\"\n)\n\nfunc TestDiffEmpty(t *testing.T) {\n\tb := makePolicyBuilder()\n\tresolvedPrev := resolvePolicy(t, b)\n\tresolvedNext := resolvePolicy(t, b)\n\n\t\/\/ diff should be empty\n\tdiff := NewPolicyResolutionDiff(resolvedNext, resolvedPrev, 0)\n\tverifyDiff(t, diff, 0, 0, 0, 0, 0, 0, 0)\n}\n\nfunc TestDiffComponentCreationAndAttachDependency(t *testing.T) {\n\tb := makePolicyBuilder()\n\tresolvedPrev := resolvePolicy(t, b)\n\n\t\/\/ add dependency\n\td1 := b.AddDependency(b.AddUser(), b.Policy().GetObjectsByKind(lang.ContractObject.Kind)[0].(*lang.Contract))\n\td1.Labels[\"param\"] = \"value1\"\n\tresolvedNext := resolvePolicy(t, b)\n\n\t\/\/ diff should contain instantiated component\n\tdiff := NewPolicyResolutionDiff(resolvedNext, resolvedPrev, 0)\n\tverifyDiff(t, diff, 2, 0, 0, 2, 0, 2, 1)\n\n\t\/\/ add another dependency\n\td2 := b.AddDependency(b.AddUser(), b.Policy().GetObjectsByKind(lang.ContractObject.Kind)[0].(*lang.Contract))\n\td2.Labels[\"param\"] = \"value1\"\n\tresolvedNextAgain := resolvePolicy(t, b)\n\n\t\/\/ component should not be instantiated again (it's already there), just new dependency should be attached\n\tdiffAgain := NewPolicyResolutionDiff(resolvedNextAgain, resolvedNext, 0)\n\tverifyDiff(t, diffAgain, 0, 0, 0, 2, 0, 2, 1)\n}\n\nfunc TestDiffComponentUpdate(t *testing.T) {\n\tb := makePolicyBuilder()\n\tresolvedPrev := resolvePolicy(t, b)\n\n\t\/\/ add dependency\n\td1 := b.AddDependency(b.AddUser(), b.Policy().GetObjectsByKind(lang.ContractObject.Kind)[0].(*lang.Contract))\n\td1.Labels[\"param\"] = \"value1\"\n\tresolvedNext := resolvePolicy(t, b)\n\n\t\/\/ diff should contain instantiated component\n\tdiff := NewPolicyResolutionDiff(resolvedNext, resolvedPrev, 0)\n\tverifyDiff(t, diff, 2, 0, 0, 2, 0, 2, 1)\n\n\t\/\/ update dependency\n\td1.Labels[\"param\"] = \"value2\"\n\tresolvedNextAgain := resolvePolicy(t, b)\n\n\t\/\/ component should be updated\n\tdiffAgain := NewPolicyResolutionDiff(resolvedNextAgain, resolvedNext, 0)\n\tverifyDiff(t, diffAgain, 0, 0, 2, 0, 0, 1, 1)\n}\n\nfunc TestDiffComponentDelete(t *testing.T) {\n\tb := makePolicyBuilder()\n\tresolvedPrev := resolvePolicy(t, b)\n\n\t\/\/ add dependency\n\td1 := b.AddDependency(b.AddUser(), b.Policy().GetObjectsByKind(lang.ContractObject.Kind)[0].(*lang.Contract))\n\td1.Labels[\"param\"] = \"value1\"\n\tresolvedNext := resolvePolicy(t, b)\n\n\t\/\/ diff should contain instantiated component\n\tdiff := NewPolicyResolutionDiff(resolvedNext, resolvedPrev, 0)\n\tverifyDiff(t, diff, 2, 0, 0, 2, 0, 2, 1)\n\n\t\/\/ resolve empty policy\n\tresolvedEmpty := resolvePolicy(t, builder.NewPolicyBuilder())\n\n\t\/\/ diff should contain destructed component\n\tdiffAgain := NewPolicyResolutionDiff(resolvedEmpty, resolvedNext, 0)\n\tverifyDiff(t, diffAgain, 0, 2, 0, 0, 2, 2, 1)\n}\n\n\/*\n\tHelpers\n*\/\n\nfunc makePolicyBuilder() *builder.PolicyBuilder {\n\tb := builder.NewPolicyBuilder()\n\n\t\/\/ create a service\n\tservice := b.AddService()\n\tb.AddServiceComponent(service,\n\t\tb.CodeComponent(\n\t\t\tutil.NestedParameterMap{\"param\": \"{{ .Labels.param }}\"},\n\t\t\tnil,\n\t\t),\n\t)\n\tb.AddContract(service, b.CriteriaTrue())\n\n\t\/\/ add rules to allow all dependencies\n\tclusterObj := b.AddCluster()\n\tb.AddRule(b.CriteriaTrue(), b.RuleActions(lang.NewLabelOperationsSetSingleLabel(lang.LabelCluster, clusterObj.Name)))\n\n\treturn b\n}\n\nfunc resolvePolicy(t *testing.T, builder *builder.PolicyBuilder) *resolve.PolicyResolution {\n\tt.Helper()\n\tresolver := resolve.NewPolicyResolver(builder.Policy(), builder.External())\n\tresult, eventLog, err := resolver.ResolveAllDependencies()\n\tif !assert.NoError(t, err, \"Policy should be resolved without errors\") {\n\t\thook := &event.HookConsole{}\n\t\teventLog.Save(hook)\n\t\tt.FailNow()\n\t}\n\treturn result\n}\n\nfunc verifyDiff(t *testing.T, diff *PolicyResolutionDiff, componentInstantiate int, componentDestruct int, componentUpdate int, componentAttachDependency int, componentDetachDependency int, componentEndpoints int, clusters int) {\n\tt.Helper()\n\tcnt := struct {\n\t\tcreate    int\n\t\tupdate    int\n\t\tdelete    int\n\t\tattach    int\n\t\tdetach    int\n\t\tendpoints int\n\t\tclusters  int\n\t}{}\n\ts := []string{}\n\tfor _, act := range diff.Actions {\n\t\tswitch act.(type) {\n\t\tcase *component.CreateAction:\n\t\t\tcnt.create++\n\t\tcase *component.DeleteAction:\n\t\t\tcnt.delete++\n\t\tcase *component.UpdateAction:\n\t\t\tcnt.update++\n\t\tcase *component.AttachDependencyAction:\n\t\t\tcnt.attach++\n\t\tcase *component.DetachDependencyAction:\n\t\t\tcnt.detach++\n\t\tcase *component.EndpointsAction:\n\t\t\tcnt.endpoints++\n\t\tcase *global.PostProcessAction:\n\t\t\tcnt.clusters++\n\t\tdefault:\n\t\t\tt.Fatalf(\"Incorrect action type: %T\", act)\n\t\t}\n\t\ts = append(s, fmt.Sprintf(\"%+v\", act))\n\t}\n\n\tok := assert.Equal(t, componentInstantiate, cnt.create, \"Diff: component instantiations\")\n\tok = ok && assert.Equal(t, componentDestruct, cnt.delete, \"Diff: component destructions\")\n\tok = ok && assert.Equal(t, componentUpdate, cnt.update, \"Diff: component updates\")\n\tok = ok && assert.Equal(t, componentAttachDependency, cnt.attach, \"Diff: dependencies attached to components\")\n\tok = ok && assert.Equal(t, componentDetachDependency, cnt.detach, \"Diff: dependencies removed from components\")\n\tok = ok && assert.Equal(t, componentEndpoints, cnt.endpoints, \"Diff: component endpoints\")\n\tok = ok && assert.Equal(t, clusters, cnt.clusters, \"Diff: all clusters post processing\")\n\n\tif !ok {\n\t\tt.Logf(\"Log of diff actions: %s\", s)\n\t\tt.FailNow()\n\t}\n}\n<commit_msg>clusters -> postprocess<commit_after>package diff\n\nimport (\n\t\"fmt\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/engine\/apply\/action\/component\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/engine\/apply\/action\/global\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/engine\/resolve\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/event\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/lang\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/lang\/builder\"\n\t\"github.com\/Aptomi\/aptomi\/pkg\/util\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"testing\"\n)\n\nfunc TestDiffEmpty(t *testing.T) {\n\tb := makePolicyBuilder()\n\tresolvedPrev := resolvePolicy(t, b)\n\tresolvedNext := resolvePolicy(t, b)\n\n\t\/\/ diff should be empty\n\tdiff := NewPolicyResolutionDiff(resolvedNext, resolvedPrev, 0)\n\tverifyDiff(t, diff, 0, 0, 0, 0, 0, 0, 0)\n}\n\nfunc TestDiffComponentCreationAndAttachDependency(t *testing.T) {\n\tb := makePolicyBuilder()\n\tresolvedPrev := resolvePolicy(t, b)\n\n\t\/\/ add dependency\n\td1 := b.AddDependency(b.AddUser(), b.Policy().GetObjectsByKind(lang.ContractObject.Kind)[0].(*lang.Contract))\n\td1.Labels[\"param\"] = \"value1\"\n\tresolvedNext := resolvePolicy(t, b)\n\n\t\/\/ diff should contain instantiated component\n\tdiff := NewPolicyResolutionDiff(resolvedNext, resolvedPrev, 0)\n\tverifyDiff(t, diff, 2, 0, 0, 2, 0, 2, 1)\n\n\t\/\/ add another dependency\n\td2 := b.AddDependency(b.AddUser(), b.Policy().GetObjectsByKind(lang.ContractObject.Kind)[0].(*lang.Contract))\n\td2.Labels[\"param\"] = \"value1\"\n\tresolvedNextAgain := resolvePolicy(t, b)\n\n\t\/\/ component should not be instantiated again (it's already there), just new dependency should be attached\n\tdiffAgain := NewPolicyResolutionDiff(resolvedNextAgain, resolvedNext, 0)\n\tverifyDiff(t, diffAgain, 0, 0, 0, 2, 0, 2, 1)\n}\n\nfunc TestDiffComponentUpdate(t *testing.T) {\n\tb := makePolicyBuilder()\n\tresolvedPrev := resolvePolicy(t, b)\n\n\t\/\/ add dependency\n\td1 := b.AddDependency(b.AddUser(), b.Policy().GetObjectsByKind(lang.ContractObject.Kind)[0].(*lang.Contract))\n\td1.Labels[\"param\"] = \"value1\"\n\tresolvedNext := resolvePolicy(t, b)\n\n\t\/\/ diff should contain instantiated component\n\tdiff := NewPolicyResolutionDiff(resolvedNext, resolvedPrev, 0)\n\tverifyDiff(t, diff, 2, 0, 0, 2, 0, 2, 1)\n\n\t\/\/ update dependency\n\td1.Labels[\"param\"] = \"value2\"\n\tresolvedNextAgain := resolvePolicy(t, b)\n\n\t\/\/ component should be updated\n\tdiffAgain := NewPolicyResolutionDiff(resolvedNextAgain, resolvedNext, 0)\n\tverifyDiff(t, diffAgain, 0, 0, 2, 0, 0, 1, 1)\n}\n\nfunc TestDiffComponentDelete(t *testing.T) {\n\tb := makePolicyBuilder()\n\tresolvedPrev := resolvePolicy(t, b)\n\n\t\/\/ add dependency\n\td1 := b.AddDependency(b.AddUser(), b.Policy().GetObjectsByKind(lang.ContractObject.Kind)[0].(*lang.Contract))\n\td1.Labels[\"param\"] = \"value1\"\n\tresolvedNext := resolvePolicy(t, b)\n\n\t\/\/ diff should contain instantiated component\n\tdiff := NewPolicyResolutionDiff(resolvedNext, resolvedPrev, 0)\n\tverifyDiff(t, diff, 2, 0, 0, 2, 0, 2, 1)\n\n\t\/\/ resolve empty policy\n\tresolvedEmpty := resolvePolicy(t, builder.NewPolicyBuilder())\n\n\t\/\/ diff should contain destructed component\n\tdiffAgain := NewPolicyResolutionDiff(resolvedEmpty, resolvedNext, 0)\n\tverifyDiff(t, diffAgain, 0, 2, 0, 0, 2, 2, 1)\n}\n\n\/*\n\tHelpers\n*\/\n\nfunc makePolicyBuilder() *builder.PolicyBuilder {\n\tb := builder.NewPolicyBuilder()\n\n\t\/\/ create a service\n\tservice := b.AddService()\n\tb.AddServiceComponent(service,\n\t\tb.CodeComponent(\n\t\t\tutil.NestedParameterMap{\"param\": \"{{ .Labels.param }}\"},\n\t\t\tnil,\n\t\t),\n\t)\n\tb.AddContract(service, b.CriteriaTrue())\n\n\t\/\/ add rules to allow all dependencies\n\tclusterObj := b.AddCluster()\n\tb.AddRule(b.CriteriaTrue(), b.RuleActions(lang.NewLabelOperationsSetSingleLabel(lang.LabelCluster, clusterObj.Name)))\n\n\treturn b\n}\n\nfunc resolvePolicy(t *testing.T, builder *builder.PolicyBuilder) *resolve.PolicyResolution {\n\tt.Helper()\n\tresolver := resolve.NewPolicyResolver(builder.Policy(), builder.External())\n\tresult, eventLog, err := resolver.ResolveAllDependencies()\n\tif !assert.NoError(t, err, \"Policy should be resolved without errors\") {\n\t\thook := &event.HookConsole{}\n\t\teventLog.Save(hook)\n\t\tt.FailNow()\n\t}\n\treturn result\n}\n\nfunc verifyDiff(t *testing.T, diff *PolicyResolutionDiff, componentInstantiate int, componentDestruct int, componentUpdate int, componentAttachDependency int, componentDetachDependency int, componentEndpoints int, clusters int) {\n\tt.Helper()\n\tcnt := struct {\n\t\tcreate      int\n\t\tupdate      int\n\t\tdelete      int\n\t\tattach      int\n\t\tdetach      int\n\t\tendpoints   int\n\t\tpostprocess int\n\t}{}\n\ts := []string{}\n\tfor _, act := range diff.Actions {\n\t\tswitch act.(type) {\n\t\tcase *component.CreateAction:\n\t\t\tcnt.create++\n\t\tcase *component.DeleteAction:\n\t\t\tcnt.delete++\n\t\tcase *component.UpdateAction:\n\t\t\tcnt.update++\n\t\tcase *component.AttachDependencyAction:\n\t\t\tcnt.attach++\n\t\tcase *component.DetachDependencyAction:\n\t\t\tcnt.detach++\n\t\tcase *component.EndpointsAction:\n\t\t\tcnt.endpoints++\n\t\tcase *global.PostProcessAction:\n\t\t\tcnt.postprocess++\n\t\tdefault:\n\t\t\tt.Fatalf(\"Incorrect action type: %T\", act)\n\t\t}\n\t\ts = append(s, fmt.Sprintf(\"%+v\", act))\n\t}\n\n\tok := assert.Equal(t, componentInstantiate, cnt.create, \"Diff: component instantiations\")\n\tok = ok && assert.Equal(t, componentDestruct, cnt.delete, \"Diff: component destructions\")\n\tok = ok && assert.Equal(t, componentUpdate, cnt.update, \"Diff: component updates\")\n\tok = ok && assert.Equal(t, componentAttachDependency, cnt.attach, \"Diff: dependencies attached to components\")\n\tok = ok && assert.Equal(t, componentDetachDependency, cnt.detach, \"Diff: dependencies removed from components\")\n\tok = ok && assert.Equal(t, componentEndpoints, cnt.endpoints, \"Diff: component endpoints\")\n\tok = ok && assert.Equal(t, clusters, cnt.postprocess, \"Diff: post processing\")\n\n\tif !ok {\n\t\tt.Logf(\"Log of diff actions: %s\", s)\n\t\tt.FailNow()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gwr\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\/\/ DataSource is the interface implemented by all\n\/\/ data sources.\ntype DataSource interface {\n\t\/\/ NOTE: implementation is self encoding, but may abstract internally\n\tInfo() DataSourceInfo\n\tGet(format string, w io.Writer) error\n\tWatch(format string, w io.Writer) error\n}\n\n\/\/ DataSourceInfo provides a description of each\n\/\/ data source, such as name and supported formats.\ntype DataSourceInfo struct {\n\tName    string                 `json:\"name\"`\n\tFormats []string               `json:\"formats\"`\n\tAttrs   map[string]interface{} `json:\"attrs\"`\n}\n\n\/\/ DataSources is a flat collection of DataSources\n\/\/ with a meta introspection data source.\ntype DataSources struct {\n\tsources   map[string]DataSource\n\tmetaNouns metaNounDataSource\n}\n\n\/\/ NewDataSources creates a DataSources structure\n\/\/ an sets up its \"\/meta\/nouns\" data source.\nfunc NewDataSources() *DataSources {\n\tdss := &DataSources{}\n\tdss.init()\n\treturn dss\n}\n\nfunc (dss *DataSources) init() {\n\tdss.sources = make(map[string]DataSource, 2)\n\tdss.metaNouns.sources = dss\n\tdss.AddMarshaledDataSource(&dss.metaNouns)\n}\n\n\/\/ Info returns a map of all DataSource.Info() data\nfunc (dss *DataSources) Info() map[string]DataSourceInfo {\n\tinfo := make(map[string]DataSourceInfo, len(dss.sources))\n\tfor name, ds := range dss.sources {\n\t\tinfo[name] = ds.Info()\n\t}\n\treturn info\n}\n\n\/\/ AddMarshaledDataSource adds a generically-marshaled data source. It is a\n\/\/ convenience for AddDataSource(NewMarshaledDataSource(gds, nil))\nfunc (dss *DataSources) AddMarshaledDataSource(gds GenericDataSource) error {\n\tmds := NewMarshaledDataSource(gds, nil)\n\t\/\/ TODO: useful to return mds?\n\treturn dss.AddDataSource(mds)\n}\n\n\/\/ AddDataSource adds a DataSource, if none is\n\/\/ already defined for the given name.\nfunc (dss *DataSources) AddDataSource(ds DataSource) error {\n\tinfo := ds.Info()\n\t_, ok := dss.sources[info.Name]\n\tif ok {\n\t\treturn fmt.Errorf(\"data source already defined\")\n\t}\n\tdss.sources[info.Name] = ds\n\tdss.metaNouns.dataSourceAdded(ds)\n\treturn nil\n}\n\n\/\/ TODO: do we really need to support removing data sources?  I can see the\n\/\/ case for intermediaries perhaps, and suspect that is needed... but punting\n\/\/ for now.\n<commit_msg>Add DefaultDataSources<commit_after>package gwr\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\n\/\/ The default data sources registry which data sources are added to by the\n\/\/ module-level Add* functions.\nvar DefaultDataSources DataSources\n\nfunc init() {\n\tDefaultDataSources.init()\n}\n\n\/\/ AddDataSource adds a data source to the default data sources registry.\nfunc AddDataSource(ds DataSource) error {\n\treturn DefaultDataSources.AddDataSource(ds)\n}\n\n\/\/ AddMarshaledDataSource adds a generically marshaled data source to the\n\/\/ default data sources registry.\nfunc AddMarshaledDataSource(gds GenericDataSource) error {\n\treturn DefaultDataSources.AddMarshaledDataSource(gds)\n}\n\n\/\/ DataSource is the interface implemented by all\n\/\/ data sources.\ntype DataSource interface {\n\t\/\/ NOTE: implementation is self encoding, but may abstract internally\n\tInfo() DataSourceInfo\n\tGet(format string, w io.Writer) error\n\tWatch(format string, w io.Writer) error\n}\n\n\/\/ DataSourceInfo provides a description of each\n\/\/ data source, such as name and supported formats.\ntype DataSourceInfo struct {\n\tName    string                 `json:\"name\"`\n\tFormats []string               `json:\"formats\"`\n\tAttrs   map[string]interface{} `json:\"attrs\"`\n}\n\n\/\/ DataSources is a flat collection of DataSources\n\/\/ with a meta introspection data source.\ntype DataSources struct {\n\tsources   map[string]DataSource\n\tmetaNouns metaNounDataSource\n}\n\n\/\/ NewDataSources creates a DataSources structure\n\/\/ an sets up its \"\/meta\/nouns\" data source.\nfunc NewDataSources() *DataSources {\n\tdss := &DataSources{}\n\tdss.init()\n\treturn dss\n}\n\nfunc (dss *DataSources) init() {\n\tdss.sources = make(map[string]DataSource, 2)\n\tdss.metaNouns.sources = dss\n\tdss.AddMarshaledDataSource(&dss.metaNouns)\n}\n\n\/\/ Info returns a map of all DataSource.Info() data\nfunc (dss *DataSources) Info() map[string]DataSourceInfo {\n\tinfo := make(map[string]DataSourceInfo, len(dss.sources))\n\tfor name, ds := range dss.sources {\n\t\tinfo[name] = ds.Info()\n\t}\n\treturn info\n}\n\n\/\/ AddMarshaledDataSource adds a generically-marshaled data source. It is a\n\/\/ convenience for AddDataSource(NewMarshaledDataSource(gds, nil))\nfunc (dss *DataSources) AddMarshaledDataSource(gds GenericDataSource) error {\n\tmds := NewMarshaledDataSource(gds, nil)\n\t\/\/ TODO: useful to return mds?\n\treturn dss.AddDataSource(mds)\n}\n\n\/\/ AddDataSource adds a DataSource, if none is\n\/\/ already defined for the given name.\nfunc (dss *DataSources) AddDataSource(ds DataSource) error {\n\tinfo := ds.Info()\n\t_, ok := dss.sources[info.Name]\n\tif ok {\n\t\treturn fmt.Errorf(\"data source already defined\")\n\t}\n\tdss.sources[info.Name] = ds\n\tdss.metaNouns.dataSourceAdded(ds)\n\treturn nil\n}\n\n\/\/ TODO: do we really need to support removing data sources?  I can see the\n\/\/ case for intermediaries perhaps, and suspect that is needed... but punting\n\/\/ for now.\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *  Copyright 2016 Adobe Systems Incorporated. All rights reserved.\n *  This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License. You may obtain a copy\n *  of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software distributed under\n *  the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n *  OF ANY KIND, either express or implied. See the License for the specific language\n *  governing permissions and limitations under the License.\n *\/\npackage build\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/adobe-platform\/porter\/aws\/cloudformation\"\n\t\"github.com\/adobe-platform\/porter\/aws_session\"\n\t\"github.com\/adobe-platform\/porter\/cfn\"\n\t\"github.com\/adobe-platform\/porter\/conf\"\n\t\"github.com\/adobe-platform\/porter\/constants\"\n\t\"github.com\/adobe-platform\/porter\/hook\"\n\t\"github.com\/adobe-platform\/porter\/logger\"\n\t\"github.com\/adobe-platform\/porter\/provision\"\n\t\"github.com\/adobe-platform\/porter\/provision_output\"\n\t\"github.com\/phylake\/go-cli\"\n)\n\nvar sleepDuration = constants.StackCreationPollInterval()\n\ntype (\n\tProvisionStackCmd struct{}\n)\n\nfunc (recv *ProvisionStackCmd) Name() string {\n\treturn \"provision\"\n}\n\nfunc (recv *ProvisionStackCmd) ShortHelp() string {\n\treturn \"Provision a new stack\"\n}\n\nfunc (recv *ProvisionStackCmd) LongHelp() string {\n\treturn `NAME\n    provision -- Provision a new stack\n\nSYNOPSIS\n    provision -e <environment out of .porter\/config>\n\nDESCRIPTION\n    Provision a new stack for a given environment.\n\n    This command is similar to create-stack but it works with multiple regions\n    and should be run from a build box.`\n}\n\nfunc (recv *ProvisionStackCmd) SubCommands() []cli.Command {\n\treturn nil\n}\n\nfunc (recv *ProvisionStackCmd) Execute(args []string) bool {\n\n\tif len(args) > 0 {\n\t\tvar environment string\n\t\tflagSet := flag.NewFlagSet(\"\", flag.ExitOnError)\n\t\tflagSet.StringVar(&environment, \"e\", \"\", \"\")\n\t\tflagSet.Usage = func() {\n\t\t\tfmt.Println(recv.LongHelp())\n\t\t}\n\t\tflagSet.Parse(args)\n\n\t\tProvisionStack(environment)\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc ProvisionStack(env string) {\n\n\tlog := logger.CLI(\"cmd\", \"build-provision\")\n\n\tprovisionOutput := provision_output.Environment{\n\t\tEnvironment: env,\n\t\tRegions:     make([]provision_output.Region, 0),\n\t}\n\n\tconfig, success := conf.GetAlteredConfig(log)\n\tif !success {\n\t\tos.Exit(1)\n\t}\n\n\tenvironment, err := config.GetEnvironment(env)\n\tif err != nil {\n\t\tlog.Error(\"GetEnvironment\", \"Error\", err)\n\t\tos.Exit(1)\n\t}\n\n\terr = environment.IsWithinBlackoutWindow()\n\tif err != nil {\n\t\tlog.Error(\"Blackout window is active\", \"Error\", err, \"Environment\", environment.Name)\n\t\tos.Exit(1)\n\t}\n\n\t_, err = os.Stat(constants.PayloadPath)\n\tif err != nil {\n\t\tlog.Error(\"Service payload not found\", \"ServicePayloadPath\", constants.PayloadPath, \"Error\", err)\n\t\tos.Exit(1)\n\t}\n\n\tstackArgs := provision.StackArgs{\n\t\tEnvironment: env,\n\t}\n\n\tif !hook.Execute(log, constants.HookPreProvision, env, nil) {\n\t\tos.Exit(1)\n\t}\n\n\tstackOutput, success := provision.CreateStack(log, config, stackArgs)\n\tif !success {\n\t\tos.Exit(1)\n\t}\n\n\tregionCount := len(environment.Regions)\n\toutputChan := make(chan provision_output.Region, regionCount)\n\tfailureChan := make(chan struct{}, regionCount)\n\n\tfor _, regionOutput := range stackOutput.Regions {\n\t\tgo provisionStackPoll(environment, regionOutput, outputChan, failureChan)\n\t}\n\n\tcommandFailed := false\n\tfor i := 0; i < regionCount; i++ {\n\t\tselect {\n\t\tcase regionOutput := <-outputChan:\n\t\t\tprovisionOutput.Regions = append(provisionOutput.Regions, regionOutput)\n\t\tcase _ = <-failureChan:\n\t\t\tcommandFailed = true\n\t\t}\n\t}\n\n\tif commandFailed {\n\n\t\tif len(provisionOutput.Regions) > 0 {\n\t\t\tlog.Warn(\"Some regions failed to create. Deleting the successful ones\")\n\n\t\t\tfor _, pr := range provisionOutput.Regions {\n\t\t\t\troleARN, err := environment.GetRoleARN(pr.AWSRegion)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"GetRoleARN\", \"Error\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\troleSession := aws_session.STS(pr.AWSRegion, roleARN, 0)\n\t\t\t\tcfnClient := cloudformation.New(roleSession)\n\n\t\t\t\tlog.Info(\"DeleteStack\", \"StackId\", pr.StackId)\n\t\t\t\tcloudformation.DeleteStack(cfnClient, pr.StackId)\n\t\t\t}\n\t\t}\n\n\t\tos.Exit(1)\n\t}\n\n\tprovisionBytes, err := json.Marshal(provisionOutput)\n\tif err != nil {\n\t\tlog.Error(\"json.Marshal\", \"Error\", err)\n\t}\n\n\t\/\/ write the stackoutput into porter tmp directory\n\terr = ioutil.WriteFile(constants.ProvisionOutputPath, provisionBytes, 0644)\n\tif err != nil {\n\t\tlog.Error(\"Unable to write provision output\", \"Error\", err)\n\t\tos.Exit(1)\n\t}\n\n\tif !hook.Execute(log, constants.HookPostProvision, env, provisionOutput.Regions) {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc provisionStackPoll(environment *conf.Environment, stackRegionOutput provision.CreateStackRegionOutput, outputChan chan provision_output.Region, failureChan chan struct{}) {\n\tvar (\n\t\tstackProvisioned bool\n\t\telbLogicalId     string\n\t)\n\n\tlog := logger.CLI(\"cmd\", \"build-provision\", \"Region\", stackRegionOutput.Region)\n\n\tregion, err := environment.GetRegion(stackRegionOutput.Region)\n\tif err != nil {\n\t\tlog.Error(\"GetRegion\", \"Error\", err)\n\t\treturn\n\t}\n\n\troleARN, err := environment.GetRoleARN(region.Name)\n\tif err != nil {\n\t\tlog.Error(\"GetRoleARN\", \"Error\", err)\n\t\treturn\n\t}\n\n\troleSession := aws_session.STS(region.Name, roleARN, constants.StackCreationTimeout())\n\tcfnClient := cloudformation.New(roleSession)\n\n\tn := int(constants.StackCreationTimeout().Seconds() \/ sleepDuration.Seconds())\n\nstackEventPoll:\n\tfor i := 0; i < n; i++ {\n\n\t\tstackStatus, err := cloudformation.DescribeStack(cfnClient, stackRegionOutput.StackId)\n\t\tif err != nil {\n\t\t\tlog.Error(\"DescribeStack\", \"Error\", err)\n\t\t\tfailureChan <- struct{}{}\n\t\t\treturn\n\t\t}\n\t\tif stackStatus == nil || len(stackStatus.Stacks) != 1 {\n\t\t\tlog.Error(\"unexpected stack status\")\n\t\t\tfailureChan <- struct{}{}\n\t\t\treturn\n\t\t}\n\n\t\tlog.Info(\"Stack status\", \"StackStatus\", *stackStatus.Stacks[0].StackStatus)\n\n\t\tswitch *stackStatus.Stacks[0].StackStatus {\n\t\tcase \"CREATE_COMPLETE\":\n\t\t\tstackProvisioned = true\n\t\t\tbreak stackEventPoll\n\t\tcase \"CREATE_FAILED\":\n\t\t\tlog.Error(\"Stack creation failed\")\n\t\t\tfailureChan <- struct{}{}\n\t\t\treturn\n\t\tcase \"DELETE_IN_PROGRESS\":\n\t\t\tlog.Error(\"Stack is being deleted\")\n\t\t\tfailureChan <- struct{}{}\n\t\t\treturn\n\t\tcase \"ROLLBACK_IN_PROGRESS\":\n\t\t\tlog.Error(\"Stack is rolling back\")\n\t\t\tfailureChan <- struct{}{}\n\t\t\treturn\n\t\t}\n\n\t\ttime.Sleep(sleepDuration)\n\t}\n\n\tif !stackProvisioned {\n\t\tlog.Error(\"stack provision timeout\")\n\t\tfailureChan <- struct{}{}\n\t\treturn\n\t}\n\n\tcfnTemplateByte, err := ioutil.ReadFile(constants.CloudFormationTemplatePath)\n\tif err != nil {\n\t\tlog.Error(\"CloudFormationTemplate read file error\", \"Error\", err)\n\t}\n\n\tcfnTemplate := cfn.NewTemplate()\n\n\terr = json.Unmarshal(cfnTemplateByte, &cfnTemplate)\n\tif err != nil {\n\t\tlog.Error(\"json unmarshal error on cfn template\", \"Error\", err)\n\t\tfailureChan <- struct{}{}\n\t\treturn\n\t}\n\n\tcfnTemplate.ParseResources()\n\n\telbLogicalId, err = cfnTemplate.GetResourceName(cfn.ElasticLoadBalancing_LoadBalancer)\n\tif err != nil {\n\t\tlog.Error(\"GetResourceName\", \"Error\", err)\n\t\tfailureChan <- struct{}{}\n\t\treturn\n\t}\n\n\t\/\/Once stack provisioned get the provisoned elb\n\tphysicalResourceID, err := cloudformation.DescribeStackResource(cfnClient, stackRegionOutput.StackId, elbLogicalId)\n\n\tif err != nil {\n\t\tlog.Error(\"Error on getting physicalResourceId\", \"Error\", err)\n\t\tfailureChan <- struct{}{}\n\t\treturn\n\t}\n\n\tprovisionDetails := provision_output.Region{\n\t\tAWSRegion:          region.Name,\n\t\tStackId:            stackRegionOutput.StackId,\n\t\tProvisionedELBName: physicalResourceID,\n\t}\n\n\toutputChan <- provisionDetails\n\n}\n<commit_msg>Retry DescribeStackResource calls in provision<commit_after>\/*\n *  Copyright 2016 Adobe Systems Incorporated. All rights reserved.\n *  This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License. You may obtain a copy\n *  of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software distributed under\n *  the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n *  OF ANY KIND, either express or implied. See the License for the specific language\n *  governing permissions and limitations under the License.\n *\/\npackage build\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/adobe-platform\/porter\/aws\/cloudformation\"\n\t\"github.com\/adobe-platform\/porter\/aws_session\"\n\t\"github.com\/adobe-platform\/porter\/cfn\"\n\t\"github.com\/adobe-platform\/porter\/conf\"\n\t\"github.com\/adobe-platform\/porter\/constants\"\n\t\"github.com\/adobe-platform\/porter\/hook\"\n\t\"github.com\/adobe-platform\/porter\/logger\"\n\t\"github.com\/adobe-platform\/porter\/provision\"\n\t\"github.com\/adobe-platform\/porter\/provision_output\"\n\t\"github.com\/adobe-platform\/porter\/util\"\n\t\"github.com\/phylake\/go-cli\"\n)\n\nvar sleepDuration = constants.StackCreationPollInterval()\n\ntype (\n\tProvisionStackCmd struct{}\n)\n\nfunc (recv *ProvisionStackCmd) Name() string {\n\treturn \"provision\"\n}\n\nfunc (recv *ProvisionStackCmd) ShortHelp() string {\n\treturn \"Provision a new stack\"\n}\n\nfunc (recv *ProvisionStackCmd) LongHelp() string {\n\treturn `NAME\n    provision -- Provision a new stack\n\nSYNOPSIS\n    provision -e <environment out of .porter\/config>\n\nDESCRIPTION\n    Provision a new stack for a given environment.\n\n    This command is similar to create-stack but it works with multiple regions\n    and should be run from a build box.`\n}\n\nfunc (recv *ProvisionStackCmd) SubCommands() []cli.Command {\n\treturn nil\n}\n\nfunc (recv *ProvisionStackCmd) Execute(args []string) bool {\n\n\tif len(args) > 0 {\n\t\tvar environment string\n\t\tflagSet := flag.NewFlagSet(\"\", flag.ExitOnError)\n\t\tflagSet.StringVar(&environment, \"e\", \"\", \"\")\n\t\tflagSet.Usage = func() {\n\t\t\tfmt.Println(recv.LongHelp())\n\t\t}\n\t\tflagSet.Parse(args)\n\n\t\tProvisionStack(environment)\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc ProvisionStack(env string) {\n\n\tlog := logger.CLI(\"cmd\", \"build-provision\")\n\n\tprovisionOutput := provision_output.Environment{\n\t\tEnvironment: env,\n\t\tRegions:     make([]provision_output.Region, 0),\n\t}\n\n\tconfig, success := conf.GetAlteredConfig(log)\n\tif !success {\n\t\tos.Exit(1)\n\t}\n\n\tenvironment, err := config.GetEnvironment(env)\n\tif err != nil {\n\t\tlog.Error(\"GetEnvironment\", \"Error\", err)\n\t\tos.Exit(1)\n\t}\n\n\terr = environment.IsWithinBlackoutWindow()\n\tif err != nil {\n\t\tlog.Error(\"Blackout window is active\", \"Error\", err, \"Environment\", environment.Name)\n\t\tos.Exit(1)\n\t}\n\n\t_, err = os.Stat(constants.PayloadPath)\n\tif err != nil {\n\t\tlog.Error(\"Service payload not found\", \"ServicePayloadPath\", constants.PayloadPath, \"Error\", err)\n\t\tos.Exit(1)\n\t}\n\n\tstackArgs := provision.StackArgs{\n\t\tEnvironment: env,\n\t}\n\n\tif !hook.Execute(log, constants.HookPreProvision, env, nil) {\n\t\tos.Exit(1)\n\t}\n\n\tstackOutput, success := provision.CreateStack(log, config, stackArgs)\n\tif !success {\n\t\tos.Exit(1)\n\t}\n\n\tregionCount := len(environment.Regions)\n\toutputChan := make(chan provision_output.Region, regionCount)\n\tfailureChan := make(chan struct{}, regionCount)\n\n\tfor _, regionOutput := range stackOutput.Regions {\n\t\tgo provisionStackPoll(environment, regionOutput, outputChan, failureChan)\n\t}\n\n\tcommandFailed := false\n\tfor i := 0; i < regionCount; i++ {\n\t\tselect {\n\t\tcase regionOutput := <-outputChan:\n\t\t\tprovisionOutput.Regions = append(provisionOutput.Regions, regionOutput)\n\t\tcase _ = <-failureChan:\n\t\t\tcommandFailed = true\n\t\t}\n\t}\n\n\tif commandFailed {\n\n\t\tif len(provisionOutput.Regions) > 0 {\n\t\t\tlog.Warn(\"Some regions failed to create. Deleting the successful ones\")\n\n\t\t\tfor _, pr := range provisionOutput.Regions {\n\t\t\t\troleARN, err := environment.GetRoleARN(pr.AWSRegion)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"GetRoleARN\", \"Error\", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\troleSession := aws_session.STS(pr.AWSRegion, roleARN, 0)\n\t\t\t\tcfnClient := cloudformation.New(roleSession)\n\n\t\t\t\tlog.Info(\"DeleteStack\", \"StackId\", pr.StackId)\n\t\t\t\tcloudformation.DeleteStack(cfnClient, pr.StackId)\n\t\t\t}\n\t\t}\n\n\t\tos.Exit(1)\n\t}\n\n\tprovisionBytes, err := json.Marshal(provisionOutput)\n\tif err != nil {\n\t\tlog.Error(\"json.Marshal\", \"Error\", err)\n\t}\n\n\t\/\/ write the stackoutput into porter tmp directory\n\terr = ioutil.WriteFile(constants.ProvisionOutputPath, provisionBytes, 0644)\n\tif err != nil {\n\t\tlog.Error(\"Unable to write provision output\", \"Error\", err)\n\t\tos.Exit(1)\n\t}\n\n\tif !hook.Execute(log, constants.HookPostProvision, env, provisionOutput.Regions) {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc provisionStackPoll(environment *conf.Environment, stackRegionOutput provision.CreateStackRegionOutput, outputChan chan provision_output.Region, failureChan chan struct{}) {\n\tvar (\n\t\tstackProvisioned   bool\n\t\telbLogicalId       string\n\t\tphysicalResourceID string\n\t)\n\n\tlog := logger.CLI(\"cmd\", \"build-provision\", \"Region\", stackRegionOutput.Region)\n\n\tregion, err := environment.GetRegion(stackRegionOutput.Region)\n\tif err != nil {\n\t\tlog.Error(\"GetRegion\", \"Error\", err)\n\t\treturn\n\t}\n\n\troleARN, err := environment.GetRoleARN(region.Name)\n\tif err != nil {\n\t\tlog.Error(\"GetRoleARN\", \"Error\", err)\n\t\treturn\n\t}\n\n\troleSession := aws_session.STS(region.Name, roleARN, constants.StackCreationTimeout())\n\tcfnClient := cloudformation.New(roleSession)\n\n\tn := int(constants.StackCreationTimeout().Seconds() \/ sleepDuration.Seconds())\n\nstackEventPoll:\n\tfor i := 0; i < n; i++ {\n\n\t\tstackStatus, err := cloudformation.DescribeStack(cfnClient, stackRegionOutput.StackId)\n\t\tif err != nil {\n\t\t\tlog.Error(\"DescribeStack\", \"Error\", err)\n\t\t\tfailureChan <- struct{}{}\n\t\t\treturn\n\t\t}\n\t\tif stackStatus == nil || len(stackStatus.Stacks) != 1 {\n\t\t\tlog.Error(\"unexpected stack status\")\n\t\t\tfailureChan <- struct{}{}\n\t\t\treturn\n\t\t}\n\n\t\tlog.Info(\"Stack status\", \"StackStatus\", *stackStatus.Stacks[0].StackStatus)\n\n\t\tswitch *stackStatus.Stacks[0].StackStatus {\n\t\tcase \"CREATE_COMPLETE\":\n\t\t\tstackProvisioned = true\n\t\t\tbreak stackEventPoll\n\t\tcase \"CREATE_FAILED\":\n\t\t\tlog.Error(\"Stack creation failed\")\n\t\t\tfailureChan <- struct{}{}\n\t\t\treturn\n\t\tcase \"DELETE_IN_PROGRESS\":\n\t\t\tlog.Error(\"Stack is being deleted\")\n\t\t\tfailureChan <- struct{}{}\n\t\t\treturn\n\t\tcase \"ROLLBACK_IN_PROGRESS\":\n\t\t\tlog.Error(\"Stack is rolling back\")\n\t\t\tfailureChan <- struct{}{}\n\t\t\treturn\n\t\t}\n\n\t\ttime.Sleep(sleepDuration)\n\t}\n\n\tif !stackProvisioned {\n\t\tlog.Error(\"stack provision timeout\")\n\t\tfailureChan <- struct{}{}\n\t\treturn\n\t}\n\n\tcfnTemplateByte, err := ioutil.ReadFile(constants.CloudFormationTemplatePath)\n\tif err != nil {\n\t\tlog.Error(\"CloudFormationTemplate read file error\", \"Error\", err)\n\t}\n\n\tcfnTemplate := cfn.NewTemplate()\n\n\terr = json.Unmarshal(cfnTemplateByte, &cfnTemplate)\n\tif err != nil {\n\t\tlog.Error(\"json unmarshal error on cfn template\", \"Error\", err)\n\t\tfailureChan <- struct{}{}\n\t\treturn\n\t}\n\n\tcfnTemplate.ParseResources()\n\n\telbLogicalId, err = cfnTemplate.GetResourceName(cfn.ElasticLoadBalancing_LoadBalancer)\n\tif err != nil {\n\t\tlog.Error(\"GetResourceName\", \"Error\", err)\n\t\tfailureChan <- struct{}{}\n\t\treturn\n\t}\n\n\t\/\/Once stack provisioned get the provisoned elb\n\tretryMsg := func(i int) { log.Warn(\"DescribeStackResource retrying\", \"Count\", i) }\n\tif !util.SuccessRetryer(9, retryMsg, func() bool {\n\t\tphysicalResourceID, err = cloudformation.DescribeStackResource(cfnClient, stackRegionOutput.StackId, elbLogicalId)\n\t\tif err != nil {\n\t\t\tlog.Error(\"Error on getting physicalResourceId\", \"Error\", err)\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}) {\n\t\tfailureChan <- struct{}{}\n\t\treturn\n\t}\n\n\tprovisionDetails := provision_output.Region{\n\t\tAWSRegion:          region.Name,\n\t\tStackId:            stackRegionOutput.StackId,\n\t\tProvisionedELBName: physicalResourceID,\n\t}\n\n\toutputChan <- provisionDetails\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2015,2016 Phil Pennock.\n\/\/ All rights reserved, except as granted under license.\n\/\/ Licensed per file LICENSE.txt\n\npackage version\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/philpennock\/character\/commands\/root\"\n)\n\n\/\/ VersionString is expected to be set by the linker during build.\n\/\/ If make(1) is used for build, this will happen.\nvar VersionString string\n\n\/\/ Library version functions should be defined in other files in this dir,\n\/\/ under appropriate build-tag constraints, and those files should use\n\/\/ the add function below in their init() routines.  Each function should\n\/\/ return a short library name, and any lines of output for versioning.\n\/\/ If the short library name is empty, then the library's name is assumed\n\/\/ to be embedded in the output lines already.\nvar libraryVersionFuncs []func() (string, []string)\n\nfunc addLibraryVersionFunc(f func() (string, []string)) {\n\tlibraryVersionFuncs = append(libraryVersionFuncs, f)\n}\n\nvar versionCmd = &cobra.Command{\n\tUse:   \"version\",\n\tShort: \"show version of character\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tif VersionString == \"\" {\n\t\t\tVersionString = \"<unknown>\"\n\t\t}\n\t\tfmt.Printf(\"%s: version %s\\n\", cmd.Root().Name(), VersionString)\n\t\tfmt.Printf(\"Golang: Runtime: %s\\n\", runtime.Version())\n\t\tfor _, f := range libraryVersionFuncs {\n\t\t\tname, infoLines := f()\n\t\t\tfor _, l := range infoLines {\n\t\t\t\tif name != \"\" {\n\t\t\t\t\tfmt.Printf(\"%s: %s\\n\", name, l)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\"%s\\n\", l)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n}\n\nfunc init() {\n\troot.AddCommand(versionCmd)\n}\n<commit_msg>Source URL as part of version output<commit_after>\/\/ Copyright © 2015,2016 Phil Pennock.\n\/\/ All rights reserved, except as granted under license.\n\/\/ Licensed per file LICENSE.txt\n\npackage version\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/philpennock\/character\/commands\/root\"\n)\n\n\/\/ SourceURL is so that the version command identifies where this came from.\n\/\/ It can be overriden at link time, but is not expected to be.\nvar SourceURL = \"https:\/\/github.com\/philpennock\/character\"\n\n\/\/ VersionString is expected to be set by the linker during build.\n\/\/ If make(1) is used for build, this will happen.\nvar VersionString string\n\n\/\/ Library version functions should be defined in other files in this dir,\n\/\/ under appropriate build-tag constraints, and those files should use\n\/\/ the add function below in their init() routines.  Each function should\n\/\/ return a short library name, and any lines of output for versioning.\n\/\/ If the short library name is empty, then the library's name is assumed\n\/\/ to be embedded in the output lines already.\nvar libraryVersionFuncs []func() (string, []string)\n\nfunc addLibraryVersionFunc(f func() (string, []string)) {\n\tlibraryVersionFuncs = append(libraryVersionFuncs, f)\n}\n\nvar versionCmd = &cobra.Command{\n\tUse:   \"version\",\n\tShort: \"show version of character\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tif VersionString == \"\" {\n\t\t\tVersionString = \"<unknown>\"\n\t\t}\n\t\tfmt.Printf(\"%s: version %s\\n\", cmd.Root().Name(), VersionString)\n\t\tfmt.Printf(\"Golang: Runtime: %s\\n\", runtime.Version())\n\t\tfor _, f := range libraryVersionFuncs {\n\t\t\tname, infoLines := f()\n\t\t\tfor _, l := range infoLines {\n\t\t\t\tif name != \"\" {\n\t\t\t\t\tfmt.Printf(\"%s: %s\\n\", name, l)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\"%s\\n\", l)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"%s: Source URL <%s>\\n\", cmd.Root().Name(), SourceURL)\n\t},\n}\n\nfunc init() {\n\troot.AddCommand(versionCmd)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com>\n\/\/ All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\npackage capability\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\ntype capHeader struct {\n\tversion uint32\n\tpid     int\n}\n\ntype capData struct {\n\teffective   uint32\n\tpermitted   uint32\n\tinheritable uint32\n}\n\nfunc capget(hdr *capHeader, data *capData) (err error) {\n\t_, _, e1 := syscall.Syscall(syscall.SYS_CAPGET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}\n\nfunc capset(hdr *capHeader, data *capData) (err error) {\n\t_, _, e1 := syscall.Syscall(syscall.SYS_CAPSET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}\n\nfunc prctl(option int, arg2, arg3, arg4, arg5 uintptr) (err error) {\n\t_, _, e1 := syscall.Syscall6(syscall.SYS_PRCTL, uintptr(option), arg2, arg3, arg4, arg5, 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}\n\nconst (\n\tvfsXattrName = \"security.capability\"\n\n\tvfsCapVerMask = 0xff000000\n\tvfsCapVer1    = 0x01000000\n\tvfsCapVer2    = 0x02000000\n\n\tvfsCapFlagMask      = ^vfsCapVerMask\n\tvfsCapFlageffective = 0x000001\n\n\tvfscapDataSizeV1 = 4 * (1 + 2*1)\n\tvfscapDataSizeV2 = 4 * (1 + 2*2)\n)\n\ntype vfscapData struct {\n\tmagic uint32\n\tdata  [2]struct {\n\t\tpermitted   uint32\n\t\tinheritable uint32\n\t}\n\teffective [2]uint32\n\tversion   int8\n}\n\nvar (\n\t_vfsXattrName *byte\n)\n\nfunc init() {\n\t_vfsXattrName, _ = syscall.BytePtrFromString(vfsXattrName)\n}\n\nfunc getVfsCap(path string, dest *vfscapData) (err error) {\n\tvar _p0 *byte\n\t_p0, err = syscall.BytePtrFromString(path)\n\tif err != nil {\n\t\treturn\n\t}\n\tr0, _, e1 := syscall.Syscall6(syscall.SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(dest)), vfscapDataSizeV2, 0, 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\tswitch dest.magic & vfsCapVerMask {\n\tcase vfsCapVer1:\n\t\tdest.version = 1\n\t\tif r0 != vfscapDataSizeV1 {\n\t\t\treturn syscall.EINVAL\n\t\t}\n\t\tdest.data[1].permitted = 0\n\t\tdest.data[1].inheritable = 0\n\tcase vfsCapVer2:\n\t\tdest.version = 2\n\t\tif r0 != vfscapDataSizeV2 {\n\t\t\treturn syscall.EINVAL\n\t\t}\n\tdefault:\n\t\treturn syscall.EINVAL\n\t}\n\tif dest.magic&vfsCapFlageffective != 0 {\n\t\tdest.effective[0] = dest.data[0].permitted | dest.data[0].inheritable\n\t\tdest.effective[1] = dest.data[1].permitted | dest.data[1].inheritable\n\t} else {\n\t\tdest.effective[0] = 0\n\t\tdest.effective[1] = 0\n\t}\n\treturn\n}\n\nfunc setVfsCap(path string, data *vfscapData) (err error) {\n\tvar _p0 *byte\n\t_p0, err = syscall.BytePtrFromString(path)\n\tif err != nil {\n\t\treturn\n\t}\n\tvar size uintptr\n\tif data.version == 1 {\n\t\tdata.magic = vfsCapVer1\n\t\tsize = vfscapDataSizeV1\n\t} else if data.version == 2 {\n\t\tdata.magic = vfsCapVer2\n\t\tif data.effective[0] != 0 || data.effective[1] != 0 {\n\t\t\tdata.magic |= vfsCapFlageffective\n\t\t\tdata.data[0].permitted |= data.effective[0]\n\t\t\tdata.data[1].permitted |= data.effective[1]\n\t\t}\n\t\tsize = vfscapDataSizeV2\n\t} else {\n\t\treturn syscall.EINVAL\n\t}\n\t_, _, e1 := syscall.Syscall6(syscall.SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(data)), size, 0, 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}\n<commit_msg>Don't set permitted when effective is specified<commit_after>\/\/ Copyright (c) 2013, Suryandaru Triandana <syndtr@gmail.com>\n\/\/ All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\npackage capability\n\nimport (\n\t\"syscall\"\n\t\"unsafe\"\n)\n\ntype capHeader struct {\n\tversion uint32\n\tpid     int\n}\n\ntype capData struct {\n\teffective   uint32\n\tpermitted   uint32\n\tinheritable uint32\n}\n\nfunc capget(hdr *capHeader, data *capData) (err error) {\n\t_, _, e1 := syscall.Syscall(syscall.SYS_CAPGET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}\n\nfunc capset(hdr *capHeader, data *capData) (err error) {\n\t_, _, e1 := syscall.Syscall(syscall.SYS_CAPSET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}\n\nfunc prctl(option int, arg2, arg3, arg4, arg5 uintptr) (err error) {\n\t_, _, e1 := syscall.Syscall6(syscall.SYS_PRCTL, uintptr(option), arg2, arg3, arg4, arg5, 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}\n\nconst (\n\tvfsXattrName = \"security.capability\"\n\n\tvfsCapVerMask = 0xff000000\n\tvfsCapVer1    = 0x01000000\n\tvfsCapVer2    = 0x02000000\n\n\tvfsCapFlagMask      = ^vfsCapVerMask\n\tvfsCapFlageffective = 0x000001\n\n\tvfscapDataSizeV1 = 4 * (1 + 2*1)\n\tvfscapDataSizeV2 = 4 * (1 + 2*2)\n)\n\ntype vfscapData struct {\n\tmagic uint32\n\tdata  [2]struct {\n\t\tpermitted   uint32\n\t\tinheritable uint32\n\t}\n\teffective [2]uint32\n\tversion   int8\n}\n\nvar (\n\t_vfsXattrName *byte\n)\n\nfunc init() {\n\t_vfsXattrName, _ = syscall.BytePtrFromString(vfsXattrName)\n}\n\nfunc getVfsCap(path string, dest *vfscapData) (err error) {\n\tvar _p0 *byte\n\t_p0, err = syscall.BytePtrFromString(path)\n\tif err != nil {\n\t\treturn\n\t}\n\tr0, _, e1 := syscall.Syscall6(syscall.SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(dest)), vfscapDataSizeV2, 0, 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\tswitch dest.magic & vfsCapVerMask {\n\tcase vfsCapVer1:\n\t\tdest.version = 1\n\t\tif r0 != vfscapDataSizeV1 {\n\t\t\treturn syscall.EINVAL\n\t\t}\n\t\tdest.data[1].permitted = 0\n\t\tdest.data[1].inheritable = 0\n\tcase vfsCapVer2:\n\t\tdest.version = 2\n\t\tif r0 != vfscapDataSizeV2 {\n\t\t\treturn syscall.EINVAL\n\t\t}\n\tdefault:\n\t\treturn syscall.EINVAL\n\t}\n\tif dest.magic&vfsCapFlageffective != 0 {\n\t\tdest.effective[0] = dest.data[0].permitted | dest.data[0].inheritable\n\t\tdest.effective[1] = dest.data[1].permitted | dest.data[1].inheritable\n\t} else {\n\t\tdest.effective[0] = 0\n\t\tdest.effective[1] = 0\n\t}\n\treturn\n}\n\nfunc setVfsCap(path string, data *vfscapData) (err error) {\n\tvar _p0 *byte\n\t_p0, err = syscall.BytePtrFromString(path)\n\tif err != nil {\n\t\treturn\n\t}\n\tvar size uintptr\n\tif data.version == 1 {\n\t\tdata.magic = vfsCapVer1\n\t\tsize = vfscapDataSizeV1\n\t} else if data.version == 2 {\n\t\tdata.magic = vfsCapVer2\n\t\tif data.effective[0] != 0 || data.effective[1] != 0 {\n\t\t\tdata.magic |= vfsCapFlageffective\n\t\t}\n\t\tsize = vfscapDataSizeV2\n\t} else {\n\t\treturn syscall.EINVAL\n\t}\n\t_, _, e1 := syscall.Syscall6(syscall.SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(data)), size, 0, 0)\n\tif e1 != 0 {\n\t\terr = e1\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * A Go package to copy a Dataset\n *\n * Copyright (C) 2017 Lawrence Woodman <lwoodman@vlifesystems.com>\n *\n * Licensed under an MIT licence.  Please see LICENCE.md for details.\n *\/\n\n\/\/ Package dcopy copies a Dataset so that you can work consistently on\n\/\/ the same Dataset.  This is important where a database is likely to be\n\/\/ updated while you are working on it.  The copy of the database is stored\n\/\/ in an sqlite3 database located in a temporary directory.\npackage dcopy\n\nimport (\n\t\"encoding\/csv\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/lawrencewoodman\/ddataset\"\n\t\"github.com\/lawrencewoodman\/ddataset\/dcsv\"\n\t\"github.com\/lawrencewoodman\/ddataset\/internal\"\n)\n\n\/\/ DCopy represents a copy of a Dataset\ntype DCopy struct {\n\tdataset    ddataset.Dataset\n\ttmpDir     string\n\tisReleased bool\n\tnumRecords int64\n}\n\n\/\/ DCopyConn represents a connection to a DCopy Dataset\ntype DCopyConn struct {\n\tconn ddataset.Conn\n\terr  error\n}\n\n\/\/ New creates a new DCopy Dataset which will be a copy of the Dataset\n\/\/ supplied at the time it is run. Please note that this creates a file\n\/\/ on the disk containing a copy of the supplied Dataset.  The copy is\n\/\/ created in a sub-directory of tmpDir.  If tmpDir is the empty string,\n\/\/ then it uses the default system temporary directory.\nfunc New(dataset ddataset.Dataset, tmpDir string) (ddataset.Dataset, error) {\n\ttmpDir, err := ioutil.TempDir(tmpDir, \"dcopy\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcopyFilename := filepath.Join(tmpDir, \"copy.csv\")\n\tf, err := os.Create(copyFilename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tw := csv.NewWriter(f)\n\n\tconn, err := dataset.Open()\n\tif err != nil {\n\t\tos.RemoveAll(tmpDir)\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\n\tstrRecord := make([]string, len(dataset.Fields()))\n\tfor conn.Next() {\n\t\trecord := conn.Read()\n\t\tfor i, f := range dataset.Fields() {\n\t\t\tstrRecord[i] = record[f].String()\n\t\t}\n\t\tif err := w.Write(strRecord); err != nil {\n\t\t\tos.RemoveAll(tmpDir)\n\t\t\treturn nil, fmt.Errorf(\"error writing record to csv copy: %s\", err)\n\t\t}\n\t}\n\n\tif err := conn.Err(); err != nil {\n\t\tos.RemoveAll(tmpDir)\n\t\treturn nil, err\n\t}\n\n\tw.Flush()\n\tif err := w.Error(); err != nil {\n\t\tos.RemoveAll(tmpDir)\n\t\treturn nil, err\n\t}\n\n\treturn &DCopy{\n\t\tdataset:    dcsv.New(copyFilename, false, ',', dataset.Fields()),\n\t\ttmpDir:     tmpDir,\n\t\tisReleased: false,\n\t\tnumRecords: -1,\n\t}, nil\n}\n\n\/\/ Open creates a connection to the Dataset\nfunc (d *DCopy) Open() (ddataset.Conn, error) {\n\tif d.isReleased {\n\t\treturn nil, ddataset.ErrReleased\n\t}\n\tconn, err := d.dataset.Open()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DCopyConn{\n\t\tconn: conn,\n\t\terr:  nil,\n\t}, nil\n}\n\n\/\/ Fields returns the field names used by the Dataset\nfunc (d *DCopy) Fields() []string {\n\tif d.isReleased {\n\t\treturn []string{}\n\t}\n\treturn d.dataset.Fields()\n}\n\n\/\/ NumRecords returns the number of records in the Dataset.  If there is\n\/\/ a problem getting the number of records it returns -1.\nfunc (d *DCopy) NumRecords() int64 {\n\tif d.numRecords != -1 {\n\t\treturn d.numRecords\n\t}\n\td.numRecords = internal.CountNumRecords(d)\n\treturn d.numRecords\n}\n\n\/\/ Release releases any resources associated with the Dataset d,\n\/\/ rendering it unusable in the future.  In this case it deletes\n\/\/ the temporary copy of the Dataset.\nfunc (d *DCopy) Release() error {\n\tif !d.isReleased {\n\t\terr := os.RemoveAll(d.tmpDir)\n\t\tif err == nil {\n\t\t\td.isReleased = true\n\t\t}\n\t\treturn err\n\t}\n\treturn ddataset.ErrReleased\n}\n\n\/\/ Next returns whether there is a Record to be Read\nfunc (c *DCopyConn) Next() bool {\n\treturn c.conn.Next()\n}\n\n\/\/ Err returns any errors from the connection\nfunc (c *DCopyConn) Err() error {\n\treturn c.conn.Err()\n}\n\n\/\/ Read returns the current Record\nfunc (c *DCopyConn) Read() ddataset.Record {\n\treturn c.conn.Read()\n}\n\n\/\/ Close closes the connection and deletes the copy\nfunc (c *DCopyConn) Close() error {\n\treturn c.conn.Close()\n}\n<commit_msg>Update dcopy comment to say copy in CSV not sqlite3<commit_after>\/*\n * A Go package to copy a Dataset\n *\n * Copyright (C) 2017 Lawrence Woodman <lwoodman@vlifesystems.com>\n *\n * Licensed under an MIT licence.  Please see LICENCE.md for details.\n *\/\n\n\/\/ Package dcopy copies a Dataset so that you can work consistently on\n\/\/ the same Dataset.  This is important where a database is likely to be\n\/\/ updated while you are working on it.  The copy of the database is stored\n\/\/ in a CSV file located in a temporary directory.\npackage dcopy\n\nimport (\n\t\"encoding\/csv\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/lawrencewoodman\/ddataset\"\n\t\"github.com\/lawrencewoodman\/ddataset\/dcsv\"\n\t\"github.com\/lawrencewoodman\/ddataset\/internal\"\n)\n\n\/\/ DCopy represents a copy of a Dataset\ntype DCopy struct {\n\tdataset    ddataset.Dataset\n\ttmpDir     string\n\tisReleased bool\n\tnumRecords int64\n}\n\n\/\/ DCopyConn represents a connection to a DCopy Dataset\ntype DCopyConn struct {\n\tconn ddataset.Conn\n\terr  error\n}\n\n\/\/ New creates a new DCopy Dataset which will be a copy of the Dataset\n\/\/ supplied at the time it is run. Please note that this creates a file\n\/\/ on the disk containing a copy of the supplied Dataset.  The copy is\n\/\/ created in a sub-directory of tmpDir.  If tmpDir is the empty string,\n\/\/ then it uses the default system temporary directory.\nfunc New(dataset ddataset.Dataset, tmpDir string) (ddataset.Dataset, error) {\n\ttmpDir, err := ioutil.TempDir(tmpDir, \"dcopy\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcopyFilename := filepath.Join(tmpDir, \"copy.csv\")\n\tf, err := os.Create(copyFilename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tw := csv.NewWriter(f)\n\n\tconn, err := dataset.Open()\n\tif err != nil {\n\t\tos.RemoveAll(tmpDir)\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\n\tstrRecord := make([]string, len(dataset.Fields()))\n\tfor conn.Next() {\n\t\trecord := conn.Read()\n\t\tfor i, f := range dataset.Fields() {\n\t\t\tstrRecord[i] = record[f].String()\n\t\t}\n\t\tif err := w.Write(strRecord); err != nil {\n\t\t\tos.RemoveAll(tmpDir)\n\t\t\treturn nil, fmt.Errorf(\"error writing record to csv copy: %s\", err)\n\t\t}\n\t}\n\n\tif err := conn.Err(); err != nil {\n\t\tos.RemoveAll(tmpDir)\n\t\treturn nil, err\n\t}\n\n\tw.Flush()\n\tif err := w.Error(); err != nil {\n\t\tos.RemoveAll(tmpDir)\n\t\treturn nil, err\n\t}\n\n\treturn &DCopy{\n\t\tdataset:    dcsv.New(copyFilename, false, ',', dataset.Fields()),\n\t\ttmpDir:     tmpDir,\n\t\tisReleased: false,\n\t\tnumRecords: -1,\n\t}, nil\n}\n\n\/\/ Open creates a connection to the Dataset\nfunc (d *DCopy) Open() (ddataset.Conn, error) {\n\tif d.isReleased {\n\t\treturn nil, ddataset.ErrReleased\n\t}\n\tconn, err := d.dataset.Open()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &DCopyConn{\n\t\tconn: conn,\n\t\terr:  nil,\n\t}, nil\n}\n\n\/\/ Fields returns the field names used by the Dataset\nfunc (d *DCopy) Fields() []string {\n\tif d.isReleased {\n\t\treturn []string{}\n\t}\n\treturn d.dataset.Fields()\n}\n\n\/\/ NumRecords returns the number of records in the Dataset.  If there is\n\/\/ a problem getting the number of records it returns -1.\nfunc (d *DCopy) NumRecords() int64 {\n\tif d.numRecords != -1 {\n\t\treturn d.numRecords\n\t}\n\td.numRecords = internal.CountNumRecords(d)\n\treturn d.numRecords\n}\n\n\/\/ Release releases any resources associated with the Dataset d,\n\/\/ rendering it unusable in the future.  In this case it deletes\n\/\/ the temporary copy of the Dataset.\nfunc (d *DCopy) Release() error {\n\tif !d.isReleased {\n\t\terr := os.RemoveAll(d.tmpDir)\n\t\tif err == nil {\n\t\t\td.isReleased = true\n\t\t}\n\t\treturn err\n\t}\n\treturn ddataset.ErrReleased\n}\n\n\/\/ Next returns whether there is a Record to be Read\nfunc (c *DCopyConn) Next() bool {\n\treturn c.conn.Next()\n}\n\n\/\/ Err returns any errors from the connection\nfunc (c *DCopyConn) Err() error {\n\treturn c.conn.Err()\n}\n\n\/\/ Read returns the current Record\nfunc (c *DCopyConn) Read() ddataset.Record {\n\treturn c.conn.Read()\n}\n\n\/\/ Close closes the connection and deletes the copy\nfunc (c *DCopyConn) Close() error {\n\treturn c.conn.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Tests for client.go\n\npackage http_test\n\nimport (\n\t\"fmt\"\n\t. \"http\"\n\t\"http\/httptest\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"url\"\n)\n\nvar robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {\n\tw.Header().Set(\"Last-Modified\", \"sometime\")\n\tfmt.Fprintf(w, \"User-agent: go\\nDisallow: \/something\/\")\n})\n\nfunc TestClient(t *testing.T) {\n\tts := httptest.NewServer(robotsTxtHandler)\n\tdefer ts.Close()\n\n\tr, err := Get(ts.URL)\n\tvar b []byte\n\tif err == nil {\n\t\tb, err = ioutil.ReadAll(r.Body)\n\t\tr.Body.Close()\n\t}\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if s := string(b); !strings.HasPrefix(s, \"User-agent:\") {\n\t\tt.Errorf(\"Incorrect page body (did not begin with User-agent): %q\", s)\n\t}\n}\n\nfunc TestClientHead(t *testing.T) {\n\tts := httptest.NewServer(robotsTxtHandler)\n\tdefer ts.Close()\n\n\tr, err := Head(ts.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif _, ok := r.Header[\"Last-Modified\"]; !ok {\n\t\tt.Error(\"Last-Modified header not found.\")\n\t}\n}\n\ntype recordingTransport struct {\n\treq *Request\n}\n\nfunc (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err os.Error) {\n\tt.req = req\n\treturn nil, os.NewError(\"dummy impl\")\n}\n\nfunc TestGetRequestFormat(t *testing.T) {\n\ttr := &recordingTransport{}\n\tclient := &Client{Transport: tr}\n\turl := \"http:\/\/dummy.faketld\/\"\n\tclient.Get(url) \/\/ Note: doesn't hit network\n\tif tr.req.Method != \"GET\" {\n\t\tt.Errorf(\"expected method %q; got %q\", \"GET\", tr.req.Method)\n\t}\n\tif tr.req.URL.String() != url {\n\t\tt.Errorf(\"expected URL %q; got %q\", url, tr.req.URL.String())\n\t}\n\tif tr.req.Header == nil {\n\t\tt.Errorf(\"expected non-nil request Header\")\n\t}\n}\n\nfunc TestPostRequestFormat(t *testing.T) {\n\ttr := &recordingTransport{}\n\tclient := &Client{Transport: tr}\n\n\turl := \"http:\/\/dummy.faketld\/\"\n\tjson := `{\"key\":\"value\"}`\n\tb := strings.NewReader(json)\n\tclient.Post(url, \"application\/json\", b) \/\/ Note: doesn't hit network\n\n\tif tr.req.Method != \"POST\" {\n\t\tt.Errorf(\"got method %q, want %q\", tr.req.Method, \"POST\")\n\t}\n\tif tr.req.URL.String() != url {\n\t\tt.Errorf(\"got URL %q, want %q\", tr.req.URL.String(), url)\n\t}\n\tif tr.req.Header == nil {\n\t\tt.Fatalf(\"expected non-nil request Header\")\n\t}\n\tif tr.req.Close {\n\t\tt.Error(\"got Close true, want false\")\n\t}\n\tif g, e := tr.req.ContentLength, int64(len(json)); g != e {\n\t\tt.Errorf(\"got ContentLength %d, want %d\", g, e)\n\t}\n}\n\nfunc TestPostFormRequestFormat(t *testing.T) {\n\ttr := &recordingTransport{}\n\tclient := &Client{Transport: tr}\n\n\turlStr := \"http:\/\/dummy.faketld\/\"\n\tform := make(url.Values)\n\tform.Set(\"foo\", \"bar\")\n\tform.Add(\"foo\", \"bar2\")\n\tform.Set(\"bar\", \"baz\")\n\tclient.PostForm(urlStr, form) \/\/ Note: doesn't hit network\n\n\tif tr.req.Method != \"POST\" {\n\t\tt.Errorf(\"got method %q, want %q\", tr.req.Method, \"POST\")\n\t}\n\tif tr.req.URL.String() != urlStr {\n\t\tt.Errorf(\"got URL %q, want %q\", tr.req.URL.String(), urlStr)\n\t}\n\tif tr.req.Header == nil {\n\t\tt.Fatalf(\"expected non-nil request Header\")\n\t}\n\tif g, e := tr.req.Header.Get(\"Content-Type\"), \"application\/x-www-form-urlencoded\"; g != e {\n\t\tt.Errorf(\"got Content-Type %q, want %q\", g, e)\n\t}\n\tif tr.req.Close {\n\t\tt.Error(\"got Close true, want false\")\n\t}\n\texpectedBody := \"foo=bar&foo=bar2&bar=baz\"\n\tif g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {\n\t\tt.Errorf(\"got ContentLength %d, want %d\", g, e)\n\t}\n\tbodyb, err := ioutil.ReadAll(tr.req.Body)\n\tif err != nil {\n\t\tt.Fatalf(\"ReadAll on req.Body: %v\", err)\n\t}\n\tif g := string(bodyb); g != expectedBody {\n\t\tt.Errorf(\"got body %q, want %q\", g, expectedBody)\n\t}\n}\n\nfunc TestRedirects(t *testing.T) {\n\tvar ts *httptest.Server\n\tts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {\n\t\tn, _ := strconv.Atoi(r.FormValue(\"n\"))\n\t\t\/\/ Test Referer header. (7 is arbitrary position to test at)\n\t\tif n == 7 {\n\t\t\tif g, e := r.Referer(), ts.URL+\"\/?n=6\"; e != g {\n\t\t\t\tt.Errorf(\"on request ?n=7, expected referer of %q; got %q\", e, g)\n\t\t\t}\n\t\t}\n\t\tif n < 15 {\n\t\t\tRedirect(w, r, fmt.Sprintf(\"\/?n=%d\", n+1), StatusFound)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprintf(w, \"n=%d\", n)\n\t}))\n\tdefer ts.Close()\n\n\tc := &Client{}\n\t_, err := c.Get(ts.URL)\n\tif e, g := \"Get \/?n=10: stopped after 10 redirects\", fmt.Sprintf(\"%v\", err); e != g {\n\t\tt.Errorf(\"with default client Get, expected error %q, got %q\", e, g)\n\t}\n\n\t\/\/ HEAD request should also have the ability to follow redirects.\n\t_, err = c.Head(ts.URL)\n\tif e, g := \"Head \/?n=10: stopped after 10 redirects\", fmt.Sprintf(\"%v\", err); e != g {\n\t\tt.Errorf(\"with default client Head, expected error %q, got %q\", e, g)\n\t}\n\n\t\/\/ Do should also follow redirects.\n\tgreq, _ := NewRequest(\"GET\", ts.URL, nil)\n\t_, err = c.Do(greq)\n\tif e, g := \"Get \/?n=10: stopped after 10 redirects\", fmt.Sprintf(\"%v\", err); e != g {\n\t\tt.Errorf(\"with default client Do, expected error %q, got %q\", e, g)\n\t}\n\n\tvar checkErr os.Error\n\tvar lastVia []*Request\n\tc = &Client{CheckRedirect: func(_ *Request, via []*Request) os.Error {\n\t\tlastVia = via\n\t\treturn checkErr\n\t}}\n\tres, err := c.Get(ts.URL)\n\tfinalUrl := res.Request.URL.String()\n\tif e, g := \"<nil>\", fmt.Sprintf(\"%v\", err); e != g {\n\t\tt.Errorf(\"with custom client, expected error %q, got %q\", e, g)\n\t}\n\tif !strings.HasSuffix(finalUrl, \"\/?n=15\") {\n\t\tt.Errorf(\"expected final url to end in \/?n=15; got url %q\", finalUrl)\n\t}\n\tif e, g := 15, len(lastVia); e != g {\n\t\tt.Errorf(\"expected lastVia to have contained %d elements; got %d\", e, g)\n\t}\n\n\tcheckErr = os.NewError(\"no redirects allowed\")\n\tres, err = c.Get(ts.URL)\n\tfinalUrl = res.Request.URL.String()\n\tif e, g := \"Get \/?n=1: no redirects allowed\", fmt.Sprintf(\"%v\", err); e != g {\n\t\tt.Errorf(\"with redirects forbidden, expected error %q, got %q\", e, g)\n\t}\n}\n\nfunc TestStreamingGet(t *testing.T) {\n\tsay := make(chan string)\n\tts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {\n\t\tw.(Flusher).Flush()\n\t\tfor str := range say {\n\t\t\tw.Write([]byte(str))\n\t\t\tw.(Flusher).Flush()\n\t\t}\n\t}))\n\tdefer ts.Close()\n\n\tc := &Client{}\n\tres, err := c.Get(ts.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar buf [10]byte\n\tfor _, str := range []string{\"i\", \"am\", \"also\", \"known\", \"as\", \"comet\"} {\n\t\tsay <- str\n\t\tn, err := io.ReadFull(res.Body, buf[0:len(str)])\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"ReadFull on %q: %v\", str, err)\n\t\t}\n\t\tif n != len(str) {\n\t\t\tt.Fatalf(\"Receiving %q, only read %d bytes\", str, n)\n\t\t}\n\t\tgot := string(buf[0:n])\n\t\tif got != str {\n\t\t\tt.Fatalf(\"Expected %q, got %q\", str, got)\n\t\t}\n\t}\n\tclose(say)\n\t_, err = io.ReadFull(res.Body, buf[0:1])\n\tif err != os.EOF {\n\t\tt.Fatalf(\"at end expected EOF, got %v\", err)\n\t}\n}\n\ntype writeCountingConn struct {\n\tnet.Conn\n\tcount *int\n}\n\nfunc (c *writeCountingConn) Write(p []byte) (int, os.Error) {\n\t*c.count++\n\treturn c.Conn.Write(p)\n}\n\n\/\/ TestClientWrites verifies that client requests are buffered and we\n\/\/ don't send a TCP packet per line of the http request + body.\nfunc TestClientWrites(t *testing.T) {\n\tts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {\n\t}))\n\tdefer ts.Close()\n\n\twrites := 0\n\tdialer := func(netz string, addr string) (net.Conn, os.Error) {\n\t\tc, err := net.Dial(netz, addr)\n\t\tif err == nil {\n\t\t\tc = &writeCountingConn{c, &writes}\n\t\t}\n\t\treturn c, err\n\t}\n\tc := &Client{Transport: &Transport{Dial: dialer}}\n\n\t_, err := c.Get(ts.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif writes != 1 {\n\t\tt.Errorf(\"Get request did %d Write calls, want 1\", writes)\n\t}\n\n\twrites = 0\n\t_, err = c.PostForm(ts.URL, url.Values{\"foo\": {\"bar\"}})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif writes != 1 {\n\t\tt.Errorf(\"Post request did %d Write calls, want 1\", writes)\n\t}\n}\n<commit_msg>http: do not depend on map iteration order<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Tests for client.go\n\npackage http_test\n\nimport (\n\t\"fmt\"\n\t. \"http\"\n\t\"http\/httptest\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"url\"\n)\n\nvar robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {\n\tw.Header().Set(\"Last-Modified\", \"sometime\")\n\tfmt.Fprintf(w, \"User-agent: go\\nDisallow: \/something\/\")\n})\n\nfunc TestClient(t *testing.T) {\n\tts := httptest.NewServer(robotsTxtHandler)\n\tdefer ts.Close()\n\n\tr, err := Get(ts.URL)\n\tvar b []byte\n\tif err == nil {\n\t\tb, err = ioutil.ReadAll(r.Body)\n\t\tr.Body.Close()\n\t}\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if s := string(b); !strings.HasPrefix(s, \"User-agent:\") {\n\t\tt.Errorf(\"Incorrect page body (did not begin with User-agent): %q\", s)\n\t}\n}\n\nfunc TestClientHead(t *testing.T) {\n\tts := httptest.NewServer(robotsTxtHandler)\n\tdefer ts.Close()\n\n\tr, err := Head(ts.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif _, ok := r.Header[\"Last-Modified\"]; !ok {\n\t\tt.Error(\"Last-Modified header not found.\")\n\t}\n}\n\ntype recordingTransport struct {\n\treq *Request\n}\n\nfunc (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err os.Error) {\n\tt.req = req\n\treturn nil, os.NewError(\"dummy impl\")\n}\n\nfunc TestGetRequestFormat(t *testing.T) {\n\ttr := &recordingTransport{}\n\tclient := &Client{Transport: tr}\n\turl := \"http:\/\/dummy.faketld\/\"\n\tclient.Get(url) \/\/ Note: doesn't hit network\n\tif tr.req.Method != \"GET\" {\n\t\tt.Errorf(\"expected method %q; got %q\", \"GET\", tr.req.Method)\n\t}\n\tif tr.req.URL.String() != url {\n\t\tt.Errorf(\"expected URL %q; got %q\", url, tr.req.URL.String())\n\t}\n\tif tr.req.Header == nil {\n\t\tt.Errorf(\"expected non-nil request Header\")\n\t}\n}\n\nfunc TestPostRequestFormat(t *testing.T) {\n\ttr := &recordingTransport{}\n\tclient := &Client{Transport: tr}\n\n\turl := \"http:\/\/dummy.faketld\/\"\n\tjson := `{\"key\":\"value\"}`\n\tb := strings.NewReader(json)\n\tclient.Post(url, \"application\/json\", b) \/\/ Note: doesn't hit network\n\n\tif tr.req.Method != \"POST\" {\n\t\tt.Errorf(\"got method %q, want %q\", tr.req.Method, \"POST\")\n\t}\n\tif tr.req.URL.String() != url {\n\t\tt.Errorf(\"got URL %q, want %q\", tr.req.URL.String(), url)\n\t}\n\tif tr.req.Header == nil {\n\t\tt.Fatalf(\"expected non-nil request Header\")\n\t}\n\tif tr.req.Close {\n\t\tt.Error(\"got Close true, want false\")\n\t}\n\tif g, e := tr.req.ContentLength, int64(len(json)); g != e {\n\t\tt.Errorf(\"got ContentLength %d, want %d\", g, e)\n\t}\n}\n\nfunc TestPostFormRequestFormat(t *testing.T) {\n\ttr := &recordingTransport{}\n\tclient := &Client{Transport: tr}\n\n\turlStr := \"http:\/\/dummy.faketld\/\"\n\tform := make(url.Values)\n\tform.Set(\"foo\", \"bar\")\n\tform.Add(\"foo\", \"bar2\")\n\tform.Set(\"bar\", \"baz\")\n\tclient.PostForm(urlStr, form) \/\/ Note: doesn't hit network\n\n\tif tr.req.Method != \"POST\" {\n\t\tt.Errorf(\"got method %q, want %q\", tr.req.Method, \"POST\")\n\t}\n\tif tr.req.URL.String() != urlStr {\n\t\tt.Errorf(\"got URL %q, want %q\", tr.req.URL.String(), urlStr)\n\t}\n\tif tr.req.Header == nil {\n\t\tt.Fatalf(\"expected non-nil request Header\")\n\t}\n\tif g, e := tr.req.Header.Get(\"Content-Type\"), \"application\/x-www-form-urlencoded\"; g != e {\n\t\tt.Errorf(\"got Content-Type %q, want %q\", g, e)\n\t}\n\tif tr.req.Close {\n\t\tt.Error(\"got Close true, want false\")\n\t}\n\t\/\/ Depending on map iteration, body can be either of these.\n\texpectedBody := \"foo=bar&foo=bar2&bar=baz\"\n\texpectedBody1 := \"bar=baz&foo=bar&foo=bar2\"\n\tif g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {\n\t\tt.Errorf(\"got ContentLength %d, want %d\", g, e)\n\t}\n\tbodyb, err := ioutil.ReadAll(tr.req.Body)\n\tif err != nil {\n\t\tt.Fatalf(\"ReadAll on req.Body: %v\", err)\n\t}\n\tif g := string(bodyb); g != expectedBody && g != expectedBody1 {\n\t\tt.Errorf(\"got body %q, want %q or %q\", g, expectedBody, expectedBody1)\n\t}\n}\n\nfunc TestRedirects(t *testing.T) {\n\tvar ts *httptest.Server\n\tts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {\n\t\tn, _ := strconv.Atoi(r.FormValue(\"n\"))\n\t\t\/\/ Test Referer header. (7 is arbitrary position to test at)\n\t\tif n == 7 {\n\t\t\tif g, e := r.Referer(), ts.URL+\"\/?n=6\"; e != g {\n\t\t\t\tt.Errorf(\"on request ?n=7, expected referer of %q; got %q\", e, g)\n\t\t\t}\n\t\t}\n\t\tif n < 15 {\n\t\t\tRedirect(w, r, fmt.Sprintf(\"\/?n=%d\", n+1), StatusFound)\n\t\t\treturn\n\t\t}\n\t\tfmt.Fprintf(w, \"n=%d\", n)\n\t}))\n\tdefer ts.Close()\n\n\tc := &Client{}\n\t_, err := c.Get(ts.URL)\n\tif e, g := \"Get \/?n=10: stopped after 10 redirects\", fmt.Sprintf(\"%v\", err); e != g {\n\t\tt.Errorf(\"with default client Get, expected error %q, got %q\", e, g)\n\t}\n\n\t\/\/ HEAD request should also have the ability to follow redirects.\n\t_, err = c.Head(ts.URL)\n\tif e, g := \"Head \/?n=10: stopped after 10 redirects\", fmt.Sprintf(\"%v\", err); e != g {\n\t\tt.Errorf(\"with default client Head, expected error %q, got %q\", e, g)\n\t}\n\n\t\/\/ Do should also follow redirects.\n\tgreq, _ := NewRequest(\"GET\", ts.URL, nil)\n\t_, err = c.Do(greq)\n\tif e, g := \"Get \/?n=10: stopped after 10 redirects\", fmt.Sprintf(\"%v\", err); e != g {\n\t\tt.Errorf(\"with default client Do, expected error %q, got %q\", e, g)\n\t}\n\n\tvar checkErr os.Error\n\tvar lastVia []*Request\n\tc = &Client{CheckRedirect: func(_ *Request, via []*Request) os.Error {\n\t\tlastVia = via\n\t\treturn checkErr\n\t}}\n\tres, err := c.Get(ts.URL)\n\tfinalUrl := res.Request.URL.String()\n\tif e, g := \"<nil>\", fmt.Sprintf(\"%v\", err); e != g {\n\t\tt.Errorf(\"with custom client, expected error %q, got %q\", e, g)\n\t}\n\tif !strings.HasSuffix(finalUrl, \"\/?n=15\") {\n\t\tt.Errorf(\"expected final url to end in \/?n=15; got url %q\", finalUrl)\n\t}\n\tif e, g := 15, len(lastVia); e != g {\n\t\tt.Errorf(\"expected lastVia to have contained %d elements; got %d\", e, g)\n\t}\n\n\tcheckErr = os.NewError(\"no redirects allowed\")\n\tres, err = c.Get(ts.URL)\n\tfinalUrl = res.Request.URL.String()\n\tif e, g := \"Get \/?n=1: no redirects allowed\", fmt.Sprintf(\"%v\", err); e != g {\n\t\tt.Errorf(\"with redirects forbidden, expected error %q, got %q\", e, g)\n\t}\n}\n\nfunc TestStreamingGet(t *testing.T) {\n\tsay := make(chan string)\n\tts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {\n\t\tw.(Flusher).Flush()\n\t\tfor str := range say {\n\t\t\tw.Write([]byte(str))\n\t\t\tw.(Flusher).Flush()\n\t\t}\n\t}))\n\tdefer ts.Close()\n\n\tc := &Client{}\n\tres, err := c.Get(ts.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar buf [10]byte\n\tfor _, str := range []string{\"i\", \"am\", \"also\", \"known\", \"as\", \"comet\"} {\n\t\tsay <- str\n\t\tn, err := io.ReadFull(res.Body, buf[0:len(str)])\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"ReadFull on %q: %v\", str, err)\n\t\t}\n\t\tif n != len(str) {\n\t\t\tt.Fatalf(\"Receiving %q, only read %d bytes\", str, n)\n\t\t}\n\t\tgot := string(buf[0:n])\n\t\tif got != str {\n\t\t\tt.Fatalf(\"Expected %q, got %q\", str, got)\n\t\t}\n\t}\n\tclose(say)\n\t_, err = io.ReadFull(res.Body, buf[0:1])\n\tif err != os.EOF {\n\t\tt.Fatalf(\"at end expected EOF, got %v\", err)\n\t}\n}\n\ntype writeCountingConn struct {\n\tnet.Conn\n\tcount *int\n}\n\nfunc (c *writeCountingConn) Write(p []byte) (int, os.Error) {\n\t*c.count++\n\treturn c.Conn.Write(p)\n}\n\n\/\/ TestClientWrites verifies that client requests are buffered and we\n\/\/ don't send a TCP packet per line of the http request + body.\nfunc TestClientWrites(t *testing.T) {\n\tts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {\n\t}))\n\tdefer ts.Close()\n\n\twrites := 0\n\tdialer := func(netz string, addr string) (net.Conn, os.Error) {\n\t\tc, err := net.Dial(netz, addr)\n\t\tif err == nil {\n\t\t\tc = &writeCountingConn{c, &writes}\n\t\t}\n\t\treturn c, err\n\t}\n\tc := &Client{Transport: &Transport{Dial: dialer}}\n\n\t_, err := c.Get(ts.URL)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif writes != 1 {\n\t\tt.Errorf(\"Get request did %d Write calls, want 1\", writes)\n\t}\n\n\twrites = 0\n\t_, err = c.PostForm(ts.URL, url.Values{\"foo\": {\"bar\"}})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif writes != 1 {\n\t\tt.Errorf(\"Post request did %d Write calls, want 1\", writes)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build debug\n\npackage debug\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n)\n\nvar opts struct {\n\ttags   map[string]bool\n\tbreaks map[string]bool\n\tm      sync.Mutex\n}\n\nvar debugLogger = initDebugLogger()\n\nfunc initDebugLogger() (lgr *log.Logger) {\n\topts.tags = make(map[string]bool)\n\topts.breaks = make(map[string]bool)\n\n\tfmt.Fprintf(os.Stderr, \"debug enabled\\n\")\n\n\tdebugfile := os.Getenv(\"DEBUG_LOG\")\n\tif debugfile != \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"debug log file %v\\n\", debugfile)\n\n\t\t\/\/ open logfile\n\t\tf, err := os.OpenFile(debugfile, os.O_WRONLY|os.O_APPEND, 0600)\n\n\t\tif err != nil && os.IsNotExist(err) {\n\t\t\t\/\/ create logfile\n\t\t\tf, err = os.OpenFile(debugfile, os.O_WRONLY|os.O_CREATE, 0600)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"unable to open debug log file: %v\\n\", err)\n\t\t\tos.Exit(2)\n\t\t}\n\n\t\t\/\/ seek to the end\n\t\t_, err = f.Seek(2, 0)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"unable to seek to the end of %v: %v\\n\", debugfile, err)\n\t\t\tos.Exit(3)\n\t\t}\n\n\t\t\/\/ open logger\n\t\tlgr = log.New(f, \"\", log.LstdFlags)\n\t}\n\n\t\/\/ defaults\n\topts.tags[\"break\"] = true\n\n\t\/\/ initialize tags\n\tenv := os.Getenv(\"DEBUG_TAGS\")\n\tif len(env) > 0 {\n\t\ttags := []string{}\n\n\t\tfor _, tag := range strings.Split(env, \",\") {\n\t\t\tt := strings.TrimSpace(tag)\n\t\t\tval := true\n\t\t\tif t[0] == '-' {\n\t\t\t\tval = false\n\t\t\t\tt = t[1:]\n\t\t\t} else if t[0] == '+' {\n\t\t\t\tval = true\n\t\t\t\tt = t[1:]\n\t\t\t}\n\n\t\t\t\/\/ test pattern\n\t\t\t_, err := path.Match(t, \"\")\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"error: invalid pattern %q: %v\\n\", t, err)\n\t\t\t\tos.Exit(5)\n\t\t\t}\n\n\t\t\topts.tags[t] = val\n\t\t\ttags = append(tags, tag)\n\t\t}\n\n\t\tfmt.Fprintf(os.Stderr, \"debug log enabled for: %v\\n\", tags)\n\t}\n\n\t\/\/ initialize break tags\n\tenv = os.Getenv(\"DEBUG_BREAK\")\n\tif len(env) > 0 {\n\t\tbreaks := []string{}\n\n\t\tfor _, tag := range strings.Split(env, \",\") {\n\t\t\tt := strings.TrimSpace(tag)\n\t\t\topts.breaks[t] = true\n\t\t\tbreaks = append(breaks, t)\n\t\t}\n\n\t\tfmt.Fprintf(os.Stderr, \"debug breaks enabled for: %v\\n\", breaks)\n\t}\n\n\treturn\n}\n\nfunc Log(tag string, f string, args ...interface{}) {\n\t\/\/ synchronize log writes\n\topts.m.Lock()\n\tdefer opts.m.Unlock()\n\n\tif f[len(f)-1] != '\\n' {\n\t\tf += \"\\n\"\n\t}\n\n\tdbgprint := func() {\n\t\tfmt.Fprintf(os.Stderr, \"DEBUG[\"+tag+\"]: \"+f, args...)\n\t}\n\n\tif debugLogger != nil {\n\t\tdebugLogger.Printf(\"[\"+tag+\"] \"+f, args...)\n\t}\n\n\t\/\/ check if tag is enabled directly\n\tif v, ok := opts.tags[tag]; ok {\n\t\tif v {\n\t\t\tdbgprint()\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ check for globbing\n\tfor k, v := range opts.tags {\n\t\tif m, _ := path.Match(k, tag); m {\n\t\t\tif v {\n\t\t\t\tdbgprint()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ check if tag \"all\" is enabled\n\tif v, ok := opts.tags[\"all\"]; ok && v {\n\t\tdbgprint()\n\t}\n}\n\nfunc Break(tag string) {\n\t\/\/ check if breaking is enabled\n\tif v, ok := opts.breaks[tag]; !ok || !v {\n\t\treturn\n\t}\n\n\t_, file, line, _ := runtime.Caller(1)\n\tLog(\"break\", \"stopping process %d at %s (%v:%v)\\n\", os.Getpid(), tag, file, line)\n\tp, err := os.FindProcess(os.Getpid())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = p.Signal(syscall.SIGSTOP)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n<commit_msg>debug: do not seek after creating log file<commit_after>\/\/ +build debug\n\npackage debug\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n)\n\nvar opts struct {\n\ttags   map[string]bool\n\tbreaks map[string]bool\n\tm      sync.Mutex\n}\n\nvar debugLogger = initDebugLogger()\n\nfunc initDebugLogger() (lgr *log.Logger) {\n\topts.tags = make(map[string]bool)\n\topts.breaks = make(map[string]bool)\n\n\tfmt.Fprintf(os.Stderr, \"debug enabled\\n\")\n\n\tdebugfile := os.Getenv(\"DEBUG_LOG\")\n\tif debugfile != \"\" {\n\t\tfmt.Fprintf(os.Stderr, \"debug log file %v\\n\", debugfile)\n\n\t\t\/\/ open logfile\n\t\tf, err := os.OpenFile(debugfile, os.O_WRONLY|os.O_APPEND, 0600)\n\n\t\tif err == nil {\n\t\t\t\/\/ seek to the end\n\t\t\t_, err = f.Seek(2, 0)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"unable to seek to the end of %v: %v\\n\", debugfile, err)\n\t\t\t\tos.Exit(3)\n\t\t\t}\n\t\t}\n\n\t\tif err != nil && os.IsNotExist(err) {\n\t\t\t\/\/ create logfile\n\t\t\tf, err = os.OpenFile(debugfile, os.O_WRONLY|os.O_CREATE, 0600)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"unable to open debug log file: %v\\n\", err)\n\t\t\tos.Exit(2)\n\t\t}\n\n\t\t\/\/ open logger\n\t\tlgr = log.New(f, \"\", log.LstdFlags)\n\t}\n\n\t\/\/ defaults\n\topts.tags[\"break\"] = true\n\n\t\/\/ initialize tags\n\tenv := os.Getenv(\"DEBUG_TAGS\")\n\tif len(env) > 0 {\n\t\ttags := []string{}\n\n\t\tfor _, tag := range strings.Split(env, \",\") {\n\t\t\tt := strings.TrimSpace(tag)\n\t\t\tval := true\n\t\t\tif t[0] == '-' {\n\t\t\t\tval = false\n\t\t\t\tt = t[1:]\n\t\t\t} else if t[0] == '+' {\n\t\t\t\tval = true\n\t\t\t\tt = t[1:]\n\t\t\t}\n\n\t\t\t\/\/ test pattern\n\t\t\t_, err := path.Match(t, \"\")\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"error: invalid pattern %q: %v\\n\", t, err)\n\t\t\t\tos.Exit(5)\n\t\t\t}\n\n\t\t\topts.tags[t] = val\n\t\t\ttags = append(tags, tag)\n\t\t}\n\n\t\tfmt.Fprintf(os.Stderr, \"debug log enabled for: %v\\n\", tags)\n\t}\n\n\t\/\/ initialize break tags\n\tenv = os.Getenv(\"DEBUG_BREAK\")\n\tif len(env) > 0 {\n\t\tbreaks := []string{}\n\n\t\tfor _, tag := range strings.Split(env, \",\") {\n\t\t\tt := strings.TrimSpace(tag)\n\t\t\topts.breaks[t] = true\n\t\t\tbreaks = append(breaks, t)\n\t\t}\n\n\t\tfmt.Fprintf(os.Stderr, \"debug breaks enabled for: %v\\n\", breaks)\n\t}\n\n\treturn\n}\n\nfunc Log(tag string, f string, args ...interface{}) {\n\t\/\/ synchronize log writes\n\topts.m.Lock()\n\tdefer opts.m.Unlock()\n\n\tif f[len(f)-1] != '\\n' {\n\t\tf += \"\\n\"\n\t}\n\n\tdbgprint := func() {\n\t\tfmt.Fprintf(os.Stderr, \"DEBUG[\"+tag+\"]: \"+f, args...)\n\t}\n\n\tif debugLogger != nil {\n\t\tdebugLogger.Printf(\"[\"+tag+\"] \"+f, args...)\n\t}\n\n\t\/\/ check if tag is enabled directly\n\tif v, ok := opts.tags[tag]; ok {\n\t\tif v {\n\t\t\tdbgprint()\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ check for globbing\n\tfor k, v := range opts.tags {\n\t\tif m, _ := path.Match(k, tag); m {\n\t\t\tif v {\n\t\t\t\tdbgprint()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ check if tag \"all\" is enabled\n\tif v, ok := opts.tags[\"all\"]; ok && v {\n\t\tdbgprint()\n\t}\n}\n\nfunc Break(tag string) {\n\t\/\/ check if breaking is enabled\n\tif v, ok := opts.breaks[tag]; !ok || !v {\n\t\treturn\n\t}\n\n\t_, file, line, _ := runtime.Caller(1)\n\tLog(\"break\", \"stopping process %d at %s (%v:%v)\\n\", os.Getpid(), tag, file, line)\n\tp, err := os.FindProcess(os.Getpid())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = p.Signal(syscall.SIGSTOP)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2010 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage sort\n\nimport \"testing\"\n\n\nfunc f(a []int, x int) func(int) bool {\n\treturn func(i int) bool {\n\t\treturn a[i] <= x\n\t}\n}\n\n\nvar data = []int{0: -10, 1: -5, 2: 0, 3: 1, 4: 2, 5: 3, 6: 5, 7: 7, 8: 11, 9: 100, 10: 100, 11: 100, 12: 1000, 13: 10000}\n\nvar tests = []struct {\n\tname string\n\tn    int\n\tf    func(int) bool\n\ti    int\n}{\n\t{\"empty\", 0, nil, 0},\n\t{\"1 1\", 1, func(i int) bool { return i <= 1 }, 0},\n\t{\"1 true\", 1, func(i int) bool { return false }, 0},\n\t{\"1 false\", 1, func(i int) bool { return true }, 0},\n\t{\"1e9 991\", 1e9, func(i int) bool { return i <= 991 }, 991},\n\t{\"1e9 true\", 1e9, func(i int) bool { return false }, 0},\n\t{\"1e9 false\", 1e9, func(i int) bool { return true }, 1e9 - 1},\n\t{\"data -20\", len(data), f(data, -20), 0},\n\t{\"data -10\", len(data), f(data, -10), 0},\n\t{\"data -9\", len(data), f(data, -9), 0},\n\t{\"data -6\", len(data), f(data, -6), 0},\n\t{\"data -5\", len(data), f(data, -5), 1},\n\t{\"data 3\", len(data), f(data, 3), 5},\n\t{\"data 99\", len(data), f(data, 99), 8},\n\t{\"data 100\", len(data), f(data, 100), 11},\n\t{\"data 101\", len(data), f(data, 101), 11},\n\t{\"data 10000\", len(data), f(data, 10000), 13},\n\t{\"data 10001\", len(data), f(data, 10001), 13},\n\t{\"descending a\", 7, func(i int) bool { return []int{99, 99, 59, 42, 7, 0, -1, -1}[i] >= 7 }, 4},\n\t{\"descending 7\", 1e9, func(i int) bool { return 1e9-i >= 7 }, 1e9 - 7},\n}\n\n\nfunc TestSearch(t *testing.T) {\n\tfor _, e := range tests {\n\t\ti := Search(e.n, e.f)\n\t\tif i != e.i {\n\t\t\tt.Errorf(\"%s: expected index %d; got %d\", e.name, e.i, i)\n\t\t}\n\t}\n}\n\n\n\/\/ Smoke tests for convenience wrappers - not comprehensive.\n\nvar fdata = []float{0: -3.14, 1: 0, 2: 1, 3: 2, 4: 1000.7}\nvar sdata = []string{0: \"f\", 1: \"foo\", 2: \"foobar\", 3: \"x\"}\n\nvar wrappertests = []struct {\n\tname   string\n\tresult int\n\ti      int\n}{\n\t{\"SearchInts\", SearchInts(data, 11), 8},\n\t{\"SearchFloats\", SearchFloats(fdata, 2.1), 3},\n\t{\"SearchStrings\", SearchStrings(sdata, \"\"), 0},\n\t{\"IntArray.Search\", IntArray(data).Search(0), 2},\n\t{\"FloatArray.Search\", FloatArray(fdata).Search(2.0), 3},\n\t{\"StringArray.Search\", StringArray(sdata).Search(\"x\"), 3},\n}\n\n\nfunc TestSearchWrappers(t *testing.T) {\n\tfor _, e := range wrappertests {\n\t\tif e.result != e.i {\n\t\t\tt.Errorf(\"%s: expected index %d; got %d\", e.name, e.i, e.result)\n\t\t}\n\t}\n}\n<commit_msg>sort.Search: more typos<commit_after>\/\/ Copyright 2010 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage sort\n\nimport \"testing\"\n\n\nfunc f(a []int, x int) func(int) bool {\n\treturn func(i int) bool {\n\t\treturn a[i] <= x\n\t}\n}\n\n\nvar data = []int{0: -10, 1: -5, 2: 0, 3: 1, 4: 2, 5: 3, 6: 5, 7: 7, 8: 11, 9: 100, 10: 100, 11: 100, 12: 1000, 13: 10000}\n\nvar tests = []struct {\n\tname string\n\tn    int\n\tf    func(int) bool\n\ti    int\n}{\n\t{\"empty\", 0, nil, 0},\n\t{\"1 1\", 1, func(i int) bool { return i <= 1 }, 0},\n\t{\"1 false\", 1, func(i int) bool { return false }, 0},\n\t{\"1 true\", 1, func(i int) bool { return true }, 0},\n\t{\"1e9 991\", 1e9, func(i int) bool { return i <= 991 }, 991},\n\t{\"1e9 false\", 1e9, func(i int) bool { return false }, 0},\n\t{\"1e9 true\", 1e9, func(i int) bool { return true }, 1e9 - 1},\n\t{\"data -20\", len(data), f(data, -20), 0},\n\t{\"data -10\", len(data), f(data, -10), 0},\n\t{\"data -9\", len(data), f(data, -9), 0},\n\t{\"data -6\", len(data), f(data, -6), 0},\n\t{\"data -5\", len(data), f(data, -5), 1},\n\t{\"data 3\", len(data), f(data, 3), 5},\n\t{\"data 99\", len(data), f(data, 99), 8},\n\t{\"data 100\", len(data), f(data, 100), 11},\n\t{\"data 101\", len(data), f(data, 101), 11},\n\t{\"data 10000\", len(data), f(data, 10000), 13},\n\t{\"data 10001\", len(data), f(data, 10001), 13},\n\t{\"descending a\", 7, func(i int) bool { return []int{99, 99, 59, 42, 7, 0, -1, -1}[i] >= 7 }, 4},\n\t{\"descending 7\", 1e9, func(i int) bool { return 1e9-i >= 7 }, 1e9 - 7},\n}\n\n\nfunc TestSearch(t *testing.T) {\n\tfor _, e := range tests {\n\t\ti := Search(e.n, e.f)\n\t\tif i != e.i {\n\t\t\tt.Errorf(\"%s: expected index %d; got %d\", e.name, e.i, i)\n\t\t}\n\t}\n}\n\n\n\/\/ Smoke tests for convenience wrappers - not comprehensive.\n\nvar fdata = []float{0: -3.14, 1: 0, 2: 1, 3: 2, 4: 1000.7}\nvar sdata = []string{0: \"f\", 1: \"foo\", 2: \"foobar\", 3: \"x\"}\n\nvar wrappertests = []struct {\n\tname   string\n\tresult int\n\ti      int\n}{\n\t{\"SearchInts\", SearchInts(data, 11), 8},\n\t{\"SearchFloats\", SearchFloats(fdata, 2.1), 3},\n\t{\"SearchStrings\", SearchStrings(sdata, \"\"), 0},\n\t{\"IntArray.Search\", IntArray(data).Search(0), 2},\n\t{\"FloatArray.Search\", FloatArray(fdata).Search(2.0), 3},\n\t{\"StringArray.Search\", StringArray(sdata).Search(\"x\"), 3},\n}\n\n\nfunc TestSearchWrappers(t *testing.T) {\n\tfor _, e := range wrappertests {\n\t\tif e.result != e.i {\n\t\t\tt.Errorf(\"%s: expected index %d; got %d\", e.name, e.i, e.result)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package golight\n\nimport (\n\t\"testing\"\n)\n\nfunc TestGetCommandData(t *testing.T) {\n\tdata := getCommandData(command{color: Green})\n\t\n\tif (data == nil) {\n\t\tt.Errorf(\"Error, data was null\")\t\t\n\t}\t\n}<commit_msg>adds proper tests<commit_after>package golight\n\nimport (\n\t\"testing\"\n)\n\nfunc TestGetCommandDataGreenOn(t *testing.T) {\n\tdata := getCommandData(command{color: Green})\n\t\n\tif data == nil {\n\t\tt.Errorf(\"Error, data was null\")\t\t\n\t}\t\n\n\tif len(data) != 8 {\n\t\tt.Errorf(\"Malformed command\")\n\t}\n\n\tif data[0] != 0x65 {\n\t\tt.Errorf(\"Wrong major command\")\n\t}\n\t\n\tif data[1] != 0x0C {\n\t\tt.Errorf(\"Wrong minor command\")\n\t}\n\t\n\tif data[2] != Green {\n\t\tt.Errorf(\"Color in wrong place\")\n\t}\n\t\n\tif data[3] != 0x00 {\n\t\tt.Errorf(\"Color in wrong place\")\n\t}\n\t\n\tif data[4] != 0x00 {\n\t\tt.Errorf(\"Wrong HID1 value\")\n\t}\n\t\n\tif data[5] != 0x00 {\n\t\tt.Errorf(\"Wrong HID2 value\")\n\t}\n\t\n\tif data[6] != 0x00 {\n\t\tt.Errorf(\"Wrong HID3 value\")\n\t}\n\t\n\tif data[7] != 0x00 {\n\t\tt.Errorf(\"Wrong HID4 value\")\n\t}\n}\n\nfunc TestGetCommandDataGreenOff(t *testing.T) {\n\tdata := getCommandData(command{color: Green, shutdown:true})\n\t\n\tif data == nil {\n\t\tt.Errorf(\"Error, data was null\")\t\t\n\t}\t\n\n\tif len(data) != 8 {\n\t\tt.Errorf(\"Malformed command\")\n\t}\n\n\tif data[0] != 0x65 {\n\t\tt.Errorf(\"Wrong major command\")\n\t}\n\t\n\tif data[1] != 0x0C {\n\t\tt.Errorf(\"Wrong minor command\")\n\t}\n\t\n\tif data[2] != 0x00 {\n\t\tt.Errorf(\"Color in wrong place\")\n\t}\n\t\n\tif data[3] != Green {\n\t\tt.Errorf(\"Color in wrong place\")\n\t}\n\t\n\tif data[4] != 0x00 {\n\t\tt.Errorf(\"Wrong HID1 value\")\n\t}\n\t\n\tif data[5] != 0x00 {\n\t\tt.Errorf(\"Wrong HID2 value\")\n\t}\n\t\n\tif data[6] != 0x00 {\n\t\tt.Errorf(\"Wrong HID3 value\")\n\t}\n\t\n\tif data[7] != 0x00 {\n\t\tt.Errorf(\"Wrong HID4 value\")\n\t}\n}\n\nfunc TestGetCommandDataYellowFlash(t *testing.T) {\n\tdata := getCommandData(command{color: Yellow, flash: true})\n\t\n\tif data == nil {\n\t\tt.Errorf(\"Error, data was null\")\t\t\n\t}\t\n\n\tif len(data) != 8 {\n\t\tt.Errorf(\"Malformed command\")\n\t}\n\n\tif data[0] != 0x65 {\n\t\tt.Errorf(\"Wrong major command\")\n\t}\n\t\n\tif data[1] != 0x14 {\n\t\tt.Errorf(\"Wrong minor command\")\n\t}\n\t\n\tif data[2] != 0x00 {\n\t\tt.Errorf(\"Color in wrong place\")\n\t}\n\t\n\tif data[3] != Yellow {\n\t\tt.Errorf(\"Color in wrong place\")\n\t}\n\t\n\tif data[4] != 0x00 {\n\t\tt.Errorf(\"Wrong HID1 value\")\n\t}\n\t\n\tif data[5] != 0x00 {\n\t\tt.Errorf(\"Wrong HID2 value\")\n\t}\n\t\n\tif data[6] != 0x00 {\n\t\tt.Errorf(\"Wrong HID3 value\")\n\t}\n\t\n\tif data[7] != 0x00 {\n\t\tt.Errorf(\"Wrong HID4 value\")\n\t}\n}\n\nfunc TestGetCommandDataRedFlashOff(t *testing.T) {\n\tdata := getCommandData(command{color: Red, flash: true, shutdown: true})\n\t\n\tif data == nil {\n\t\tt.Errorf(\"Error, data was null\")\t\t\n\t}\t\n\n\tif len(data) != 8 {\n\t\tt.Errorf(\"Malformed command\")\n\t}\n\n\tif data[0] != 0x65 {\n\t\tt.Errorf(\"Wrong major command\")\n\t}\n\t\n\tif data[1] != 0x14 {\n\t\tt.Errorf(\"Wrong minor command\")\n\t}\n\t\n\tif data[2] != Red {\n\t\tt.Errorf(\"Color in wrong place\")\n\t}\n\t\n\tif data[3] != 0x00 {\n\t\tt.Errorf(\"Color in wrong place\")\n\t}\n\t\n\tif data[4] != 0x00 {\n\t\tt.Errorf(\"Wrong HID1 value\")\n\t}\n\t\n\tif data[5] != 0x00 {\n\t\tt.Errorf(\"Wrong HID2 value\")\n\t}\n\t\n\tif data[6] != 0x00 {\n\t\tt.Errorf(\"Wrong HID3 value\")\n\t}\n\t\n\tif data[7] != 0x00 {\n\t\tt.Errorf(\"Wrong HID4 value\")\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2020 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage opengl\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/driver\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/shaderir\"\n)\n\ntype Shader struct {\n\tid       driver.ShaderID\n\tgraphics *Graphics\n\n\tir *shaderir.Program\n\tp  program\n}\n\nfunc NewShader(id driver.ShaderID, graphics *Graphics, program *shaderir.Program) (*Shader, error) {\n\ts := &Shader{\n\t\tid:       id,\n\t\tgraphics: graphics,\n\t\tir:       program,\n\t}\n\tif err := s.compile(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn s, nil\n}\n\nfunc (s *Shader) ID() driver.ShaderID {\n\treturn s.id\n}\n\nfunc (s *Shader) Dispose() {\n\ts.graphics.context.deleteProgram(s.p)\n\ts.graphics.removeShader(s)\n}\n\nfunc (s *Shader) compile() error {\n\tvssrc, fssrc := s.ir.Glsl()\n\n\tvs, err := s.graphics.context.newShader(vertexShader, vssrc)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"opengl: vertex shader compile error: %v, source:\\n%s\", vssrc)\n\t}\n\tdefer s.graphics.context.deleteShader(vs)\n\n\tfs, err := s.graphics.context.newShader(fragmentShader, fssrc)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"opengl: fragment shader compile error: %v, source:\\n%s\", fssrc)\n\t}\n\tdefer s.graphics.context.deleteShader(fs)\n\n\tp, err := s.graphics.context.newProgram([]shader{vs, fs}, theArrayBufferLayout.names())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.p = p\n\treturn nil\n}\n<commit_msg>graphicsdriver\/opengl: Bug fix: fmt arguments<commit_after>\/\/ Copyright 2020 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage opengl\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/driver\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/shaderir\"\n)\n\ntype Shader struct {\n\tid       driver.ShaderID\n\tgraphics *Graphics\n\n\tir *shaderir.Program\n\tp  program\n}\n\nfunc NewShader(id driver.ShaderID, graphics *Graphics, program *shaderir.Program) (*Shader, error) {\n\ts := &Shader{\n\t\tid:       id,\n\t\tgraphics: graphics,\n\t\tir:       program,\n\t}\n\tif err := s.compile(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn s, nil\n}\n\nfunc (s *Shader) ID() driver.ShaderID {\n\treturn s.id\n}\n\nfunc (s *Shader) Dispose() {\n\ts.graphics.context.deleteProgram(s.p)\n\ts.graphics.removeShader(s)\n}\n\nfunc (s *Shader) compile() error {\n\tvssrc, fssrc := s.ir.Glsl()\n\n\tvs, err := s.graphics.context.newShader(vertexShader, vssrc)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"opengl: vertex shader compile error: %v, source:\\n%s\", err, vssrc)\n\t}\n\tdefer s.graphics.context.deleteShader(vs)\n\n\tfs, err := s.graphics.context.newShader(fragmentShader, fssrc)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"opengl: fragment shader compile error: %v, source:\\n%s\", err, fssrc)\n\t}\n\tdefer s.graphics.context.deleteShader(fs)\n\n\tp, err := s.graphics.context.newProgram([]shader{vs, fs}, theArrayBufferLayout.names())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.p = p\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package simplify\n\nimport \"math\"\n\ntype PairKey struct {\n\tA, B Vector\n}\n\nfunc MakePairKey(a, b *Vertex) PairKey {\n\tif b.Less(a.Vector) {\n\t\ta, b = b, a\n\t}\n\treturn PairKey{a.Vector, b.Vector}\n}\n\ntype Pair struct {\n\tA, B        *Vertex\n\tIndex       int\n\tRemoved     bool\n\tCachedError float64\n}\n\nfunc NewPair(a, b *Vertex) *Pair {\n\tif b.Less(a.Vector) {\n\t\ta, b = b, a\n\t}\n\treturn &Pair{a, b, -1, false, -1}\n}\n\nfunc (p *Pair) Quadric() Matrix {\n\treturn p.A.Quadric.Add(p.B.Quadric)\n}\n\nfunc (p *Pair) Vector() Vector {\n\tq := p.Quadric()\n\tif math.Abs(q.Determinant()) > 1e-12 {\n\t\treturn q.QuadricVector()\n\t}\n\t\/\/ cannot compute best vector with matrix\n\t\/\/ look for best vector along edge\n\tconst n = 32\n\ta := p.A.Vector\n\tb := p.B.Vector\n\td := b.Sub(a)\n\tbestE := -1.0\n\tbestV := Vector{}\n\tfor i := 0; i <= n; i++ {\n\t\tt := float64(i) \/ n\n\t\tv := a.Add(d.MulScalar(t))\n\t\te := q.QuadricError(v)\n\t\tif bestE < 0 || e < bestE {\n\t\t\tbestE = e\n\t\t\tbestV = v\n\t\t}\n\t}\n\treturn bestV\n}\n\nfunc (p *Pair) Error() float64 {\n\tif p.CachedError < 0 {\n\t\tp.CachedError = p.Quadric().QuadricError(p.Vector())\n\t}\n\treturn p.CachedError\n}\n<commit_msg>better epsilon<commit_after>package simplify\n\nimport \"math\"\n\ntype PairKey struct {\n\tA, B Vector\n}\n\nfunc MakePairKey(a, b *Vertex) PairKey {\n\tif b.Less(a.Vector) {\n\t\ta, b = b, a\n\t}\n\treturn PairKey{a.Vector, b.Vector}\n}\n\ntype Pair struct {\n\tA, B        *Vertex\n\tIndex       int\n\tRemoved     bool\n\tCachedError float64\n}\n\nfunc NewPair(a, b *Vertex) *Pair {\n\tif b.Less(a.Vector) {\n\t\ta, b = b, a\n\t}\n\treturn &Pair{a, b, -1, false, -1}\n}\n\nfunc (p *Pair) Quadric() Matrix {\n\treturn p.A.Quadric.Add(p.B.Quadric)\n}\n\nfunc (p *Pair) Vector() Vector {\n\tq := p.Quadric()\n\tif math.Abs(q.Determinant()) > 1e-3 {\n\t\treturn q.QuadricVector()\n\t}\n\t\/\/ cannot compute best vector with matrix\n\t\/\/ look for best vector along edge\n\tconst n = 32\n\ta := p.A.Vector\n\tb := p.B.Vector\n\td := b.Sub(a)\n\tbestE := -1.0\n\tbestV := Vector{}\n\tfor i := 0; i <= n; i++ {\n\t\tt := float64(i) \/ n\n\t\tv := a.Add(d.MulScalar(t))\n\t\te := q.QuadricError(v)\n\t\tif bestE < 0 || e < bestE {\n\t\t\tbestE = e\n\t\t\tbestV = v\n\t\t}\n\t}\n\treturn bestV\n}\n\nfunc (p *Pair) Error() float64 {\n\tif p.CachedError < 0 {\n\t\tp.CachedError = p.Quadric().QuadricError(p.Vector())\n\t}\n\treturn p.CachedError\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2016 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"github.com\/golang\/glog\"\n\n\t\"github.com\/01org\/ciao\/ciao-controller\/types\"\n\t\"github.com\/01org\/ciao\/payloads\"\n\t\"github.com\/01org\/ciao\/ssntp\/uuid\"\n)\n\nfunc validateVMWorkload(req types.Workload) error {\n\t\/\/ FWType must be either EFI or legacy.\n\tif req.FWType != string(payloads.EFI) && req.FWType != payloads.Legacy {\n\t\treturn types.ErrBadRequest\n\t}\n\n\t\/\/ Must have storage for VMs\n\tif len(req.Storage) == 0 {\n\t\treturn types.ErrBadRequest\n\t}\n\n\treturn nil\n}\n\nfunc validateContainerWorkload(req types.Workload) error {\n\t\/\/ we should reject anything with ImageID set, but\n\t\/\/ we'll just ignore it.\n\tif req.ImageName == \"\" {\n\t\treturn types.ErrBadRequest\n\t}\n\n\treturn nil\n}\n\nfunc validateWorkloadStorage(req types.Workload) error {\n\tbootableCount := 0\n\tfor i := range req.Storage {\n\t\t\/\/ check that a workload type is specified\n\t\tif req.Storage[i].SourceType == \"\" {\n\t\t\treturn types.ErrBadRequest\n\t\t}\n\n\t\t\/\/ you may not request a sized volume unless it's empty.\n\t\tif req.Storage[i].Size > 0 && req.Storage[i].SourceType != types.Empty {\n\t\t\treturn types.ErrBadRequest\n\t\t}\n\n\t\t\/\/ you may not request a bootable empty volume.\n\t\tif req.Storage[i].Bootable && req.Storage[i].SourceType == types.Empty {\n\t\t\treturn types.ErrBadRequest\n\t\t}\n\n\t\tif req.Storage[i].ID != \"\" {\n\t\t\t\/\/ validate that the id is at least valid\n\t\t\t\/\/ uuid4.\n\t\t\t_, err := uuid.Parse(req.Storage[i].ID)\n\t\t\tif err != nil {\n\t\t\t\treturn types.ErrBadRequest\n\t\t\t}\n\n\t\t\t\/\/ If we have an ID we must have a type to get it from\n\t\t\tif req.Storage[i].SourceType != types.Empty {\n\t\t\t\treturn types.ErrBadRequest\n\t\t\t}\n\t\t}\n\n\t\tif req.Storage[i].SourceID == \"\" {\n\t\t\t\/\/ you may only use no source id with empty type\n\t\t\tif req.Storage[i].SourceType != types.Empty {\n\t\t\t\treturn types.ErrBadRequest\n\t\t\t}\n\t\t}\n\n\t\tif req.Storage[i].Bootable {\n\t\t\tbootableCount++\n\t\t}\n\t}\n\n\t\/\/ must be at least one bootable volume\n\tif req.VMType == payloads.QEMU && bootableCount == 0 {\n\t\treturn types.ErrBadRequest\n\t}\n\n\treturn nil\n}\n\n\/\/ this is probably an insufficient amount of checking.\nfunc validateWorkloadRequest(req types.Workload) error {\n\t\/\/ ID must be blank.\n\tif req.ID != \"\" {\n\t\tglog.V(2).Info(\"Invalid workload request: ID is not blank\")\n\t\treturn types.ErrBadRequest\n\t}\n\n\t\/\/ we don't validate the TenantID right now - it is passed\n\t\/\/ in via the ciao api, and it has passed the regex input\n\t\/\/ validation already. there's also a conflict with ssntp's uuid.Parse()\n\t\/\/ function where they assume you are using a uuid4 with '-' as\n\t\/\/ separator, and keystone doesn't use the '-' separator for\n\t\/\/ uuids.\n\n\tif req.VMType == payloads.QEMU {\n\t\terr := validateVMWorkload(req)\n\t\tif err != nil {\n\t\t\tglog.V(2).Info(\"Invalid workload request: invalid VM workload\")\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\terr := validateContainerWorkload(req)\n\t\tif err != nil {\n\t\t\tglog.V(2).Info(\"Invalid workload request: invalid container workload\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif req.ImageID != \"\" {\n\t\t\/\/ validate that the image id is at least valid\n\t\t\/\/ uuid4.\n\t\t_, err := uuid.Parse(req.ImageID)\n\t\tif err != nil {\n\t\t\tglog.V(2).Info(\"Invalid workload request: ImageID is not uuid4\")\n\t\t\treturn types.ErrBadRequest\n\t\t}\n\t}\n\n\tif req.Config == \"\" {\n\t\tglog.V(2).Info(\"Invalid workload request: config is blank\")\n\t\treturn types.ErrBadRequest\n\t}\n\n\tif len(req.Storage) > 0 {\n\t\terr := validateWorkloadStorage(req)\n\t\tif err != nil {\n\t\t\tglog.V(2).Info(\"Invalid workload request: invalid storage\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *controller) CreateWorkload(req types.Workload) (types.Workload, error) {\n\terr := validateWorkloadRequest(req)\n\tif err != nil {\n\t\treturn req, err\n\t}\n\n\t\/\/ check to see if this is a new tenant. If so, we need to add\n\t\/\/ them to the datastore. We do not however want to launch a\n\t\/\/ CNCI yet since this might be a request to upload a CNCI\n\t\/\/ workload. Instead, we'll add the new tenant directly to the\n\t\/\/ datastore. On first launch request, if the tenant doesn't yet\n\t\/\/ have a cnci, it will get launched for them then.\n\ttenant, err := c.ds.GetTenant(req.TenantID)\n\tif err != nil {\n\t\treturn req, err\n\t}\n\n\tif tenant == nil {\n\t\t_, err := c.ds.AddTenant(req.TenantID)\n\t\tif err != nil {\n\t\t\treturn req, err\n\t\t}\n\t}\n\n\t\/\/ create a workload storage resource for this new workload.\n\tif req.ImageID != \"\" {\n\t\t\/\/ validate that the image id is at least valid\n\t\t\/\/ uuid4.\n\t\t_, err = uuid.Parse(req.ImageID)\n\t\tif err != nil {\n\t\t\treturn req, err\n\t\t}\n\n\t\tstorage := types.StorageResource{\n\t\t\tBootable:   true,\n\t\t\tEphemeral:  true,\n\t\t\tSourceType: types.ImageService,\n\t\t\tSourceID:   req.ImageID,\n\t\t}\n\n\t\treq.ImageID = \"\"\n\t\treq.Storage = append(req.Storage, storage)\n\t}\n\n\treq.ID = uuid.Generate().String()\n\n\terr = c.ds.AddWorkload(req)\n\treturn req, err\n}\n\nfunc (c *controller) DeleteWorkload(tenantID string, workloadID string) error {\n\treturn c.ds.DeleteWorkload(tenantID, workloadID)\n}\n\nfunc (c *controller) ShowWorkload(tenantID string, workloadID string) (types.Workload, error) {\n\treturn c.ds.GetWorkload(tenantID, workloadID)\n}\n<commit_msg>ciao-controller: Adjust workload validation to always accept size<commit_after>\/\/ Copyright (c) 2016 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"github.com\/golang\/glog\"\n\n\t\"github.com\/01org\/ciao\/ciao-controller\/types\"\n\t\"github.com\/01org\/ciao\/payloads\"\n\t\"github.com\/01org\/ciao\/ssntp\/uuid\"\n)\n\nfunc validateVMWorkload(req types.Workload) error {\n\t\/\/ FWType must be either EFI or legacy.\n\tif req.FWType != string(payloads.EFI) && req.FWType != payloads.Legacy {\n\t\treturn types.ErrBadRequest\n\t}\n\n\t\/\/ Must have storage for VMs\n\tif len(req.Storage) == 0 {\n\t\treturn types.ErrBadRequest\n\t}\n\n\treturn nil\n}\n\nfunc validateContainerWorkload(req types.Workload) error {\n\t\/\/ we should reject anything with ImageID set, but\n\t\/\/ we'll just ignore it.\n\tif req.ImageName == \"\" {\n\t\treturn types.ErrBadRequest\n\t}\n\n\treturn nil\n}\n\nfunc validateWorkloadStorage(req types.Workload) error {\n\tbootableCount := 0\n\tfor i := range req.Storage {\n\t\t\/\/ check that a workload type is specified\n\t\tif req.Storage[i].SourceType == \"\" {\n\t\t\treturn types.ErrBadRequest\n\t\t}\n\n\t\t\/\/ you may not request a bootable empty volume.\n\t\tif req.Storage[i].Bootable && req.Storage[i].SourceType == types.Empty {\n\t\t\treturn types.ErrBadRequest\n\t\t}\n\n\t\tif req.Storage[i].ID != \"\" {\n\t\t\t\/\/ validate that the id is at least valid\n\t\t\t\/\/ uuid4.\n\t\t\t_, err := uuid.Parse(req.Storage[i].ID)\n\t\t\tif err != nil {\n\t\t\t\treturn types.ErrBadRequest\n\t\t\t}\n\n\t\t\t\/\/ If we have an ID we must have a type to get it from\n\t\t\tif req.Storage[i].SourceType != types.Empty {\n\t\t\t\treturn types.ErrBadRequest\n\t\t\t}\n\t\t}\n\n\t\tif req.Storage[i].SourceID == \"\" {\n\t\t\t\/\/ you may only use no source id with empty type\n\t\t\tif req.Storage[i].SourceType != types.Empty {\n\t\t\t\treturn types.ErrBadRequest\n\t\t\t}\n\t\t}\n\n\t\tif req.Storage[i].Bootable {\n\t\t\tbootableCount++\n\t\t}\n\t}\n\n\t\/\/ must be at least one bootable volume\n\tif req.VMType == payloads.QEMU && bootableCount == 0 {\n\t\treturn types.ErrBadRequest\n\t}\n\n\treturn nil\n}\n\n\/\/ this is probably an insufficient amount of checking.\nfunc validateWorkloadRequest(req types.Workload) error {\n\t\/\/ ID must be blank.\n\tif req.ID != \"\" {\n\t\tglog.V(2).Info(\"Invalid workload request: ID is not blank\")\n\t\treturn types.ErrBadRequest\n\t}\n\n\t\/\/ we don't validate the TenantID right now - it is passed\n\t\/\/ in via the ciao api, and it has passed the regex input\n\t\/\/ validation already. there's also a conflict with ssntp's uuid.Parse()\n\t\/\/ function where they assume you are using a uuid4 with '-' as\n\t\/\/ separator, and keystone doesn't use the '-' separator for\n\t\/\/ uuids.\n\n\tif req.VMType == payloads.QEMU {\n\t\terr := validateVMWorkload(req)\n\t\tif err != nil {\n\t\t\tglog.V(2).Info(\"Invalid workload request: invalid VM workload\")\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\terr := validateContainerWorkload(req)\n\t\tif err != nil {\n\t\t\tglog.V(2).Info(\"Invalid workload request: invalid container workload\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif req.ImageID != \"\" {\n\t\t\/\/ validate that the image id is at least valid\n\t\t\/\/ uuid4.\n\t\t_, err := uuid.Parse(req.ImageID)\n\t\tif err != nil {\n\t\t\tglog.V(2).Info(\"Invalid workload request: ImageID is not uuid4\")\n\t\t\treturn types.ErrBadRequest\n\t\t}\n\t}\n\n\tif req.Config == \"\" {\n\t\tglog.V(2).Info(\"Invalid workload request: config is blank\")\n\t\treturn types.ErrBadRequest\n\t}\n\n\tif len(req.Storage) > 0 {\n\t\terr := validateWorkloadStorage(req)\n\t\tif err != nil {\n\t\t\tglog.V(2).Info(\"Invalid workload request: invalid storage\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *controller) CreateWorkload(req types.Workload) (types.Workload, error) {\n\terr := validateWorkloadRequest(req)\n\tif err != nil {\n\t\treturn req, err\n\t}\n\n\t\/\/ check to see if this is a new tenant. If so, we need to add\n\t\/\/ them to the datastore. We do not however want to launch a\n\t\/\/ CNCI yet since this might be a request to upload a CNCI\n\t\/\/ workload. Instead, we'll add the new tenant directly to the\n\t\/\/ datastore. On first launch request, if the tenant doesn't yet\n\t\/\/ have a cnci, it will get launched for them then.\n\ttenant, err := c.ds.GetTenant(req.TenantID)\n\tif err != nil {\n\t\treturn req, err\n\t}\n\n\tif tenant == nil {\n\t\t_, err := c.ds.AddTenant(req.TenantID)\n\t\tif err != nil {\n\t\t\treturn req, err\n\t\t}\n\t}\n\n\t\/\/ create a workload storage resource for this new workload.\n\tif req.ImageID != \"\" {\n\t\t\/\/ validate that the image id is at least valid\n\t\t\/\/ uuid4.\n\t\t_, err = uuid.Parse(req.ImageID)\n\t\tif err != nil {\n\t\t\treturn req, err\n\t\t}\n\n\t\tstorage := types.StorageResource{\n\t\t\tBootable:   true,\n\t\t\tEphemeral:  true,\n\t\t\tSourceType: types.ImageService,\n\t\t\tSourceID:   req.ImageID,\n\t\t}\n\n\t\treq.ImageID = \"\"\n\t\treq.Storage = append(req.Storage, storage)\n\t}\n\n\treq.ID = uuid.Generate().String()\n\n\terr = c.ds.AddWorkload(req)\n\treturn req, err\n}\n\nfunc (c *controller) DeleteWorkload(tenantID string, workloadID string) error {\n\treturn c.ds.DeleteWorkload(tenantID, workloadID)\n}\n\nfunc (c *controller) ShowWorkload(tenantID string, workloadID string) (types.Workload, error) {\n\treturn c.ds.GetWorkload(tenantID, workloadID)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n* Copyright (c) 2014 Mark Samman <https:\/\/github.com\/marksamman\/gotorrent>\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in\n* all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n* THE SOFTWARE.\n *\/\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n)\n\nconst (\n\tChoke = iota\n\tUnchoke\n\tInterested\n\tNotInterested\n\tHave\n\tBitfield\n\tRequest\n\tPiece\n\tCancel\n\tPort\n)\n\ntype Peer struct {\n\tIP        uint32\n\tPort      uint16\n\ttorrent   *Torrent\n\thandshake []byte\n\n\tpieces     map[string]struct{}\n\tconnection net.Conn\n\tchoked     bool\n\tinterested bool\n}\n\nfunc NewPeer(torrent *Torrent) Peer {\n\tpeer := Peer{}\n\tpeer.torrent = torrent\n\n\tpeer.choked = true\n\tpeer.interested = false\n\treturn peer\n}\n\nfunc (peer *Peer) getStringIP() string {\n\treturn fmt.Sprintf(\"%d.%d.%d.%d\",\n\t\tpeer.IP>>24, (peer.IP>>16)&255, (peer.IP>>8)&255, peer.IP&255)\n}\n\nfunc (peer *Peer) readN(n int) ([]byte, error) {\n\tbuf := make([]byte, n)\n\tfor pos := 0; pos < n; {\n\t\tcount, err := peer.connection.Read(buf[pos:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpos += count\n\t}\n\treturn buf, nil\n}\n\nfunc (peer *Peer) connect(pieceChannel chan FilePiece) {\n\taddr := fmt.Sprintf(\"%s:%d\", peer.getStringIP(), peer.Port)\n\tlog.Println(\"connecting to:\", addr)\n\n\tvar err error\n\tpeer.connection, err = net.Dial(\"tcp4\", addr)\n\tif err != nil {\n\t\tlog.Printf(\"failed to connect to peer: %s\\n\", err)\n\t\treturn\n\t}\n\tdefer peer.connection.Close()\n\n\tlog.Printf(\"connected to peer: %s\\n\", addr)\n\n\t\/\/ Send handshake\n\tif _, err := peer.connection.Write(peer.torrent.Handshake); err != nil {\n\t\tlog.Printf(\"failed to send handshake to peer: %s\\n\", err)\n\t\treturn\n\t}\n\n\t\/\/ Receive handshake\n\tpeer.handshake, err = peer.readN(68)\n\tif err != nil {\n\t\tlog.Printf(\"failed to read handshake from peer: %s\\n\", err)\n\t\treturn\n\t}\n\n\t\/\/ Validate info hash\n\tif !bytes.Equal(peer.handshake[28:48], peer.torrent.InfoHash) {\n\t\tlog.Printf(\"info hash mismatch from peer: %s\", addr)\n\t\treturn\n\t}\n\n\t\/\/ TODO: Validate peer id if provided by tracker\n\n\tlog.Printf(\"successfully exchanged handshake with peer: %s\\n\", addr)\n\tfor {\n\t\terr := peer.processMessage(pieceChannel)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"failed to process message from peer %s: %s\\n\", addr, err)\n\t\t\treturn\n\t\t}\n\n\t\tif !peer.choked {\n\t\t\tfor k, _ := range peer.torrent.getPiecesSHA1() {\n\t\t\t\tpieceLength := int64(peer.torrent.getPieceLength())\n\t\t\t\tvar pos int64\n\t\t\t\tpos = 0\n\t\t\t\tfor pieceLength != 0 {\n\t\t\t\t\treq := pieceLength\n\t\t\t\t\tif req > 16384 {\n\t\t\t\t\t\treq = 16384\n\t\t\t\t\t}\n\n\t\t\t\t\tpeer.sendRequest(uint32(k), 0, uint32(req))\n\t\t\t\t\tpos += req\n\t\t\t\t\tpieceLength -= req\n\t\t\t\t}\n\t\t\t}\n\t\t\tpeer.choked = true\n\t\t}\n\t}\n}\n\nfunc (peer *Peer) processMessage(pieceChannel chan FilePiece) error {\n\tlengthHeader, err := peer.readN(4)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar length uint32\n\tbinary.Read(bytes.NewBuffer(lengthHeader), binary.BigEndian, &length)\n\tif length == 0 {\n\t\t\/\/ keep-alive\n\t\treturn nil\n\t}\n\n\tdata, err := peer.readN(int(length))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"receive message from peer, len: %d, type: %d\\n\", length, data[0])\n\n\tswitch data[0] {\n\tcase Choke:\n\t\tif length != 1 {\n\t\t\treturn errors.New(\"length of choke packet must be 1\")\n\t\t}\n\n\t\tpeer.choked = true\n\tcase Unchoke:\n\t\tif length != 1 {\n\t\t\treturn errors.New(\"length of unchoke packet must be 1\")\n\t\t}\n\n\t\tpeer.choked = false\n\tcase Interested:\n\t\tif length != 1 {\n\t\t\treturn errors.New(\"length of interested packet must be 1\")\n\t\t}\n\n\t\tpeer.interested = true\n\t\t\/\/ TODO: Unchoke peer and send files\n\tcase NotInterested:\n\t\tif length != 1 {\n\t\t\treturn errors.New(\"length of not interested packet must be 1\")\n\t\t}\n\n\t\tpeer.interested = false\n\tcase Have:\n\t\tif length != 5 {\n\t\t\treturn errors.New(\"length of have packet must be 5\")\n\t\t}\n\n\t\tstringPiece := string(data[1:])\n\t\t_, exists := peer.torrent.Pieces[stringPiece]\n\t\tif exists {\n\t\t\tpeer.pieces[stringPiece] = struct{}{}\n\t\t}\n\t\tpeer.sendInterested()\n\tcase Bitfield:\n\t\t\/\/ ignore\n\t\tbreak\n\n\tcase Request:\n\t\tif length != 13 {\n\t\t\treturn errors.New(\"length of request packet must be 13\")\n\t\t}\n\n\t\tbuf := bytes.NewBuffer(data[1:])\n\t\tvar index, begin, length uint32\n\t\tbinary.Read(buf, binary.BigEndian, &index)\n\t\tbinary.Read(buf, binary.BigEndian, &begin)\n\t\tbinary.Read(buf, binary.BigEndian, &length)\n\t\tif length > 32768 {\n\t\t\treturn errors.New(\"peer requested length over 32KB\")\n\t\t}\n\n\tcase Piece:\n\t\tif length < 10 {\n\t\t\treturn errors.New(\"length of piece packet must be at least 10\")\n\t\t}\n\n\t\tbuf := bytes.NewBuffer(data[1:])\n\t\tfilePiece := FilePiece{}\n\t\tbinary.Read(buf, binary.BigEndian, &filePiece.index)\n\t\tbinary.Read(buf, binary.BigEndian, &filePiece.begin)\n\t\tfilePiece.data = data[9:]\n\t\tpieceChannel <- filePiece\n\n\tcase Cancel:\n\t\tif length != 13 {\n\t\t\treturn errors.New(\"length of cancel packet must be 13\")\n\t\t}\n\n\t\tbuf := bytes.NewBuffer(data[1:])\n\t\tvar index, begin, length uint32\n\t\tbinary.Read(buf, binary.BigEndian, &index)\n\t\tbinary.Read(buf, binary.BigEndian, &begin)\n\t\tbinary.Read(buf, binary.BigEndian, &length)\n\n\tcase Port:\n\t\tif length != 3 {\n\t\t\treturn errors.New(\"length of port packet must be 3\")\n\t\t}\n\n\t\tvar port uint16\n\t\tbinary.Read(bytes.NewBuffer(data[1:]), binary.BigEndian, &port)\n\t}\n\treturn nil\n}\n\nfunc (peer *Peer) sendInterested() {\n\tpeer.connection.Write([]byte{0, 0, 0, 1, 2})\n}\n\nfunc (peer *Peer) sendRequest(index, begin, length uint32) {\n\tvar packet bytes.Buffer\n\tpacket.WriteByte(0)\n\tpacket.WriteByte(0)\n\tpacket.WriteByte(0)\n\tpacket.WriteByte(13)\n\tpacket.WriteByte(Request)\n\n\t\/\/ Index\n\tpacket.WriteByte(byte(index >> 24))\n\tpacket.WriteByte(byte(index >> 16))\n\tpacket.WriteByte(byte(index >> 8))\n\tpacket.WriteByte(byte(index))\n\n\t\/\/ Begin\n\tpacket.WriteByte(byte(begin >> 24))\n\tpacket.WriteByte(byte(begin >> 16))\n\tpacket.WriteByte(byte(begin >> 8))\n\tpacket.WriteByte(byte(begin))\n\n\t\/\/ Length\n\tpacket.WriteByte(byte(length >> 24))\n\tpacket.WriteByte(byte(length >> 16))\n\tpacket.WriteByte(byte(length >> 8))\n\tpacket.WriteByte(byte(length))\n\n\tpeer.connection.Write(packet.Bytes())\n}\n<commit_msg>Code cleanup<commit_after>\/*\n* Copyright (c) 2014 Mark Samman <https:\/\/github.com\/marksamman\/gotorrent>\n*\n* Permission is hereby granted, free of charge, to any person obtaining a copy\n* of this software and associated documentation files (the \"Software\"), to deal\n* in the Software without restriction, including without limitation the rights\n* to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n* copies of the Software, and to permit persons to whom the Software is\n* furnished to do so, subject to the following conditions:\n*\n* The above copyright notice and this permission notice shall be included in\n* all copies or substantial portions of the Software.\n*\n* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n* THE SOFTWARE.\n *\/\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n)\n\nconst (\n\tChoke = iota\n\tUnchoke\n\tInterested\n\tNotInterested\n\tHave\n\tBitfield\n\tRequest\n\tPiece\n\tCancel\n\tPort\n)\n\ntype Peer struct {\n\tIP        uint32\n\tPort      uint16\n\ttorrent   *Torrent\n\thandshake []byte\n\n\tpieces     map[string]struct{}\n\tconnection net.Conn\n\tchoked     bool\n\tinterested bool\n}\n\nfunc NewPeer(torrent *Torrent) Peer {\n\tpeer := Peer{}\n\tpeer.torrent = torrent\n\n\tpeer.choked = true\n\tpeer.interested = false\n\treturn peer\n}\n\nfunc (peer *Peer) getStringIP() string {\n\treturn fmt.Sprintf(\"%d.%d.%d.%d\",\n\t\tpeer.IP>>24, (peer.IP>>16)&255, (peer.IP>>8)&255, peer.IP&255)\n}\n\nfunc (peer *Peer) readN(n int) ([]byte, error) {\n\tbuf := make([]byte, n)\n\tfor pos := 0; pos < n; {\n\t\tcount, err := peer.connection.Read(buf[pos:])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpos += count\n\t}\n\treturn buf, nil\n}\n\nfunc (peer *Peer) connect(pieceChannel chan FilePiece) {\n\taddr := fmt.Sprintf(\"%s:%d\", peer.getStringIP(), peer.Port)\n\tlog.Println(\"connecting to:\", addr)\n\n\tvar err error\n\tpeer.connection, err = net.Dial(\"tcp4\", addr)\n\tif err != nil {\n\t\tlog.Printf(\"failed to connect to peer: %s\\n\", err)\n\t\treturn\n\t}\n\tdefer peer.connection.Close()\n\n\tlog.Printf(\"connected to peer: %s\\n\", addr)\n\n\t\/\/ Send handshake\n\tif _, err := peer.connection.Write(peer.torrent.Handshake); err != nil {\n\t\tlog.Printf(\"failed to send handshake to peer: %s\\n\", err)\n\t\treturn\n\t}\n\n\t\/\/ Receive handshake\n\tpeer.handshake, err = peer.readN(68)\n\tif err != nil {\n\t\tlog.Printf(\"failed to read handshake from peer: %s\\n\", err)\n\t\treturn\n\t}\n\n\t\/\/ Validate info hash\n\tif !bytes.Equal(peer.handshake[28:48], peer.torrent.InfoHash) {\n\t\tlog.Printf(\"info hash mismatch from peer: %s\", addr)\n\t\treturn\n\t}\n\n\t\/\/ TODO: Validate peer id if provided by tracker\n\n\tlog.Printf(\"successfully exchanged handshake with peer: %s\\n\", addr)\n\tfor {\n\t\terr := peer.processMessage(pieceChannel)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"failed to process message from peer %s: %s\\n\", addr, err)\n\t\t\treturn\n\t\t}\n\n\t\tif !peer.choked {\n\t\t\tfor k, _ := range peer.torrent.getPiecesSHA1() {\n\t\t\t\tpieceLength := int64(peer.torrent.getPieceLength())\n\t\t\t\tvar pos int64\n\t\t\t\tpos = 0\n\t\t\t\tfor pieceLength != 0 {\n\t\t\t\t\treq := pieceLength\n\t\t\t\t\tif req > 16384 {\n\t\t\t\t\t\treq = 16384\n\t\t\t\t\t}\n\n\t\t\t\t\tpeer.sendRequest(uint32(k), 0, uint32(req))\n\t\t\t\t\tpos += req\n\t\t\t\t\tpieceLength -= req\n\t\t\t\t}\n\t\t\t}\n\t\t\tpeer.choked = true\n\t\t}\n\t}\n}\n\nfunc (peer *Peer) processMessage(pieceChannel chan FilePiece) error {\n\tlengthHeader, err := peer.readN(4)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar length uint32\n\tbinary.Read(bytes.NewBuffer(lengthHeader), binary.BigEndian, &length)\n\tif length == 0 {\n\t\t\/\/ keep-alive\n\t\treturn nil\n\t}\n\n\tdata, err := peer.readN(int(length))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"receive message from peer, len: %d, type: %d\\n\", length, data[0])\n\n\tswitch data[0] {\n\tcase Choke:\n\t\tif length != 1 {\n\t\t\treturn errors.New(\"length of choke packet must be 1\")\n\t\t}\n\n\t\tpeer.choked = true\n\tcase Unchoke:\n\t\tif length != 1 {\n\t\t\treturn errors.New(\"length of unchoke packet must be 1\")\n\t\t}\n\n\t\tpeer.choked = false\n\tcase Interested:\n\t\tif length != 1 {\n\t\t\treturn errors.New(\"length of interested packet must be 1\")\n\t\t}\n\n\t\tpeer.interested = true\n\t\t\/\/ TODO: Unchoke peer and send files\n\tcase NotInterested:\n\t\tif length != 1 {\n\t\t\treturn errors.New(\"length of not interested packet must be 1\")\n\t\t}\n\n\t\tpeer.interested = false\n\tcase Have:\n\t\tif length != 5 {\n\t\t\treturn errors.New(\"length of have packet must be 5\")\n\t\t}\n\n\t\tstringPiece := string(data[1:])\n\t\t_, exists := peer.torrent.Pieces[stringPiece]\n\t\tif exists {\n\t\t\tpeer.pieces[stringPiece] = struct{}{}\n\t\t}\n\t\tpeer.sendInterested()\n\tcase Bitfield:\n\t\t\/\/ ignore\n\t\tbreak\n\n\tcase Request:\n\t\tif length != 13 {\n\t\t\treturn errors.New(\"length of request packet must be 13\")\n\t\t}\n\n\t\tbuf := bytes.NewBuffer(data[1:])\n\t\tvar index, begin, length uint32\n\t\tbinary.Read(buf, binary.BigEndian, &index)\n\t\tbinary.Read(buf, binary.BigEndian, &begin)\n\t\tbinary.Read(buf, binary.BigEndian, &length)\n\t\tif length > 32768 {\n\t\t\treturn errors.New(\"peer requested length over 32KB\")\n\t\t}\n\n\tcase Piece:\n\t\tif length < 10 {\n\t\t\treturn errors.New(\"length of piece packet must be at least 10\")\n\t\t}\n\n\t\tbuf := bytes.NewBuffer(data[1:])\n\t\tfilePiece := FilePiece{}\n\t\tbinary.Read(buf, binary.BigEndian, &filePiece.index)\n\t\tbinary.Read(buf, binary.BigEndian, &filePiece.begin)\n\t\tfilePiece.data = data[9:]\n\t\tpieceChannel <- filePiece\n\n\tcase Cancel:\n\t\tif length != 13 {\n\t\t\treturn errors.New(\"length of cancel packet must be 13\")\n\t\t}\n\n\t\tbuf := bytes.NewBuffer(data[1:])\n\t\tvar index, begin, length uint32\n\t\tbinary.Read(buf, binary.BigEndian, &index)\n\t\tbinary.Read(buf, binary.BigEndian, &begin)\n\t\tbinary.Read(buf, binary.BigEndian, &length)\n\n\tcase Port:\n\t\tif length != 3 {\n\t\t\treturn errors.New(\"length of port packet must be 3\")\n\t\t}\n\n\t\tvar port uint16\n\t\tbinary.Read(bytes.NewBuffer(data[1:]), binary.BigEndian, &port)\n\t}\n\treturn nil\n}\n\nfunc (peer *Peer) sendInterested() {\n\tpeer.connection.Write([]byte{0, 0, 0, 1, 2})\n}\n\nfunc (peer *Peer) sendRequest(index, begin, length uint32) {\n\tvar packet bytes.Buffer\n\tbinary.Write(&packet, binary.BigEndian, uint32(13))\n\tpacket.WriteByte(Request)\n\tbinary.Write(&packet, binary.BigEndian, index)\n\tbinary.Write(&packet, binary.BigEndian, begin)\n\tbinary.Write(&packet, binary.BigEndian, length)\n\tpeer.connection.Write(packet.Bytes())\n}\n<|endoftext|>"}
{"text":"<commit_before>package eventloop\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/dop251\/goja\"\n\t\"github.com\/dop251\/goja_nodejs\/console\"\n\t\"github.com\/dop251\/goja_nodejs\/require\"\n)\n\ntype job struct {\n\tcancelled bool\n\tfn        func()\n}\n\ntype Timer struct {\n\tjob\n\ttimer *time.Timer\n}\n\ntype Interval struct {\n\tjob\n\tticker   *time.Ticker\n\tstopChan chan struct{}\n}\n\ntype EventLoop struct {\n\tvm       *goja.Runtime\n\tjobChan  chan func()\n\tjobCount int32\n\tcanRun   bool\n\n\tauxJobs     []func()\n\tauxJobsLock sync.Mutex\n\twakeup      chan struct{}\n\n\tstopCond *sync.Cond\n\trunning  bool\n\n\tenableConsole bool\n}\n\nfunc NewEventLoop(opts ...Option) *EventLoop {\n\tvm := goja.New()\n\n\tloop := &EventLoop{\n\t\tvm:            vm,\n\t\tjobChan:       make(chan func()),\n\t\twakeup:        make(chan struct{}, 1),\n\t\tstopCond:      sync.NewCond(&sync.Mutex{}),\n\t\tenableConsole: true,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(loop)\n\t}\n\n\tnew(require.Registry).Enable(vm)\n\tif loop.enableConsole {\n\t\tconsole.Enable(vm)\n\t}\n\tvm.Set(\"setTimeout\", loop.setTimeout)\n\tvm.Set(\"setInterval\", loop.setInterval)\n\tvm.Set(\"clearTimeout\", loop.clearTimeout)\n\tvm.Set(\"clearInterval\", loop.clearInterval)\n\n\treturn loop\n}\n\ntype Option func(*EventLoop)\n\n\/\/ EnableConsole controls whether the \"console\" module is loaded into\n\/\/ the runtime used by the loop.  By default, loops are created with\n\/\/ the \"console\" module loaded, pass EnableConsole(false) to\n\/\/ NewEventLoop to disable this behavior.\nfunc EnableConsole(enableConsole bool) Option {\n\treturn func(loop *EventLoop) {\n\t\tloop.enableConsole = enableConsole\n\t}\n}\n\nfunc (loop *EventLoop) schedule(call goja.FunctionCall, repeating bool) goja.Value {\n\tif fn, ok := goja.AssertFunction(call.Argument(0)); ok {\n\t\tdelay := call.Argument(1).ToInteger()\n\t\tvar args []goja.Value\n\t\tif len(call.Arguments) > 2 {\n\t\t\targs = call.Arguments[2:]\n\t\t}\n\t\tf := func() { fn(nil, args...) }\n\t\tloop.jobCount++\n\t\tif repeating {\n\t\t\treturn loop.vm.ToValue(loop.addInterval(f, time.Duration(delay)*time.Millisecond))\n\t\t} else {\n\t\t\treturn loop.vm.ToValue(loop.addTimeout(f, time.Duration(delay)*time.Millisecond))\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (loop *EventLoop) setTimeout(call goja.FunctionCall) goja.Value {\n\treturn loop.schedule(call, false)\n}\n\nfunc (loop *EventLoop) setInterval(call goja.FunctionCall) goja.Value {\n\treturn loop.schedule(call, true)\n}\n\n\/\/ SetTimeout schedules to run the specified function in the context\n\/\/ of the loop as soon as possible after the specified timeout period.\n\/\/ SetTimeout returns a Timer which can be passed to ClearTimeout.\n\/\/ The instance of goja.Runtime that is passed to the function and any Values derived\n\/\/ from it must not be used outside of the function. SetTimeout is\n\/\/ safe to call inside or outside of the loop.\nfunc (loop *EventLoop) SetTimeout(fn func(*goja.Runtime), timeout time.Duration) *Timer {\n\tt := loop.addTimeout(func() { fn(loop.vm) }, timeout)\n\tloop.addAuxJob(func() {\n\t\tloop.jobCount++\n\t})\n\treturn t\n}\n\n\/\/ ClearTimeout cancels a Timer returned by SetTimeout if it has not run yet.\n\/\/ ClearTimeout is safe to call inside or outside of the loop.\nfunc (loop *EventLoop) ClearTimeout(t *Timer) {\n\tloop.addAuxJob(func() {\n\t\tloop.clearTimeout(t)\n\t})\n}\n\n\/\/ SetInterval schedules to repeatedly run the specified function in\n\/\/ the context of the loop as soon as possible after every specified\n\/\/ timeout period.  SetInterval returns an Interval which can be\n\/\/ passed to ClearInterval. The instance of goja.Runtime that is passed to the\n\/\/ function and any Values derived from it must not be used outside of\n\/\/ the function. SetInterval is safe to call inside or outside of the\n\/\/ loop.\nfunc (loop *EventLoop) SetInterval(fn func(*goja.Runtime), timeout time.Duration) *Interval {\n\ti := loop.addInterval(func() { fn(loop.vm) }, timeout)\n\tloop.addAuxJob(func() {\n\t\tloop.jobCount++\n\t})\n\treturn i\n}\n\n\/\/ ClearInterval cancels an Interval returned by SetInterval.\n\/\/ ClearInterval is safe to call inside or outside of the loop.\nfunc (loop *EventLoop) ClearInterval(i *Interval) {\n\tloop.addAuxJob(func() {\n\t\tloop.clearInterval(i)\n\t})\n}\n\nfunc (loop *EventLoop) setRunning() {\n\tloop.stopCond.L.Lock()\n\tif loop.running {\n\t\tpanic(\"Loop is already started\")\n\t}\n\tloop.running = true\n\tloop.stopCond.L.Unlock()\n}\n\n\/\/ Run calls the specified function, starts the event loop and waits until there are no more delayed jobs to run\n\/\/ after which it stops the loop and returns.\n\/\/ The instance of goja.Runtime that is passed to the function and any Values derived from it must not be used outside\n\/\/ of the function.\n\/\/ Do NOT use this function while the loop is already running. Use RunOnLoop() instead.\n\/\/ If the loop is already started it will panic.\nfunc (loop *EventLoop) Run(fn func(*goja.Runtime)) {\n\tloop.setRunning()\n\tfn(loop.vm)\n\tloop.run(false)\n}\n\n\/\/ Start the event loop in the background. The loop continues to run until Stop() is called.\n\/\/ If the loop is already started it will panic.\nfunc (loop *EventLoop) Start() {\n\tloop.setRunning()\n\tgo loop.run(true)\n}\n\n\/\/ Stop the loop that was started with Start(). After this function returns there will be no more jobs executed\n\/\/ by the loop. It is possible to call Start() or Run() again after this to resume the execution.\n\/\/ Note, it does not cancel active timeouts.\n\/\/ It is not allowed to run Start() and Stop() concurrently.\n\/\/ Calling Stop() on an already stopped loop or inside the loop will hang.\nfunc (loop *EventLoop) Stop() {\n\tloop.jobChan <- func() {\n\t\tloop.canRun = false\n\t}\n\n\tloop.stopCond.L.Lock()\n\tfor loop.running {\n\t\tloop.stopCond.Wait()\n\t}\n\tloop.stopCond.L.Unlock()\n}\n\n\/\/ RunOnLoop schedules to run the specified function in the context of the loop as soon as possible.\n\/\/ The order of the runs is preserved (i.e. the functions will be called in the same order as calls to RunOnLoop())\n\/\/ The instance of goja.Runtime that is passed to the function and any Values derived from it must not be used outside\n\/\/ of the function. It is safe to call inside or outside of the loop.\nfunc (loop *EventLoop) RunOnLoop(fn func(*goja.Runtime)) {\n\tloop.addAuxJob(func() { fn(loop.vm) })\n}\n\nfunc (loop *EventLoop) runAux() {\n\tloop.auxJobsLock.Lock()\n\tjobs := loop.auxJobs\n\tloop.auxJobs = nil\n\tloop.auxJobsLock.Unlock()\n\tfor _, job := range jobs {\n\t\tjob()\n\t}\n}\n\nfunc (loop *EventLoop) run(inBackground bool) {\n\tloop.canRun = true\n\tloop.runAux()\n\n\tfor loop.canRun && (inBackground || loop.jobCount > 0) {\n\t\tselect {\n\t\tcase job := <-loop.jobChan:\n\t\t\tjob()\n\t\t\tif loop.canRun {\n\t\t\t\tselect {\n\t\t\t\tcase <-loop.wakeup:\n\t\t\t\t\tloop.runAux()\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-loop.wakeup:\n\t\t\tloop.runAux()\n\t\t}\n\t}\n\tloop.stopCond.L.Lock()\n\tloop.running = false\n\tloop.stopCond.L.Unlock()\n\tloop.stopCond.Broadcast()\n}\n\nfunc (loop *EventLoop) addAuxJob(fn func()) {\n\tloop.auxJobsLock.Lock()\n\tloop.auxJobs = append(loop.auxJobs, fn)\n\tloop.auxJobsLock.Unlock()\n\tselect {\n\tcase loop.wakeup <- struct{}{}:\n\tdefault:\n\t}\n}\n\nfunc (loop *EventLoop) addTimeout(f func(), timeout time.Duration) *Timer {\n\tt := &Timer{\n\t\tjob: job{fn: f},\n\t}\n\tt.timer = time.AfterFunc(timeout, func() {\n\t\tloop.jobChan <- func() {\n\t\t\tloop.doTimeout(t)\n\t\t}\n\t})\n\n\treturn t\n}\n\nfunc (loop *EventLoop) addInterval(f func(), timeout time.Duration) *Interval {\n\t\/\/ https:\/\/nodejs.org\/api\/timers.html#timers_setinterval_callback_delay_args\n\tif timeout <= 0 {\n\t\ttimeout = time.Millisecond\n\t}\n\n\ti := &Interval{\n\t\tjob:      job{fn: f},\n\t\tticker:   time.NewTicker(timeout),\n\t\tstopChan: make(chan struct{}),\n\t}\n\n\tgo i.run(loop)\n\treturn i\n}\n\nfunc (loop *EventLoop) doTimeout(t *Timer) {\n\tif !t.cancelled {\n\t\tt.fn()\n\t\tt.cancelled = true\n\t\tloop.jobCount--\n\t}\n}\n\nfunc (loop *EventLoop) doInterval(i *Interval) {\n\tif !i.cancelled {\n\t\ti.fn()\n\t}\n}\n\nfunc (loop *EventLoop) clearTimeout(t *Timer) {\n\tif t != nil && !t.cancelled {\n\t\tt.timer.Stop()\n\t\tt.cancelled = true\n\t\tloop.jobCount--\n\t}\n}\n\nfunc (loop *EventLoop) clearInterval(i *Interval) {\n\tif i != nil && !i.cancelled {\n\t\ti.cancelled = true\n\t\tclose(i.stopChan)\n\t\tloop.jobCount--\n\t}\n}\n\nfunc (i *Interval) run(loop *EventLoop) {\nL:\n\tfor {\n\t\tselect {\n\t\tcase <-i.stopChan:\n\t\t\ti.ticker.Stop()\n\t\t\tbreak L\n\t\tcase <-i.ticker.C:\n\t\t\tloop.jobChan <- func() {\n\t\t\t\tloop.doInterval(i)\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Exposure registry<commit_after>package eventloop\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/dop251\/goja\"\n\t\"github.com\/dop251\/goja_nodejs\/console\"\n\t\"github.com\/dop251\/goja_nodejs\/require\"\n)\n\ntype job struct {\n\tcancelled bool\n\tfn        func()\n}\n\ntype Timer struct {\n\tjob\n\ttimer *time.Timer\n}\n\ntype Interval struct {\n\tjob\n\tticker   *time.Ticker\n\tstopChan chan struct{}\n}\n\ntype EventLoop struct {\n\tvm       *goja.Runtime\n\tjobChan  chan func()\n\tjobCount int32\n\tcanRun   bool\n\n\tauxJobs     []func()\n\tauxJobsLock sync.Mutex\n\twakeup      chan struct{}\n\n\tstopCond *sync.Cond\n\trunning  bool\n\n\tenableConsole bool\n\tregistry      *require.Registry\n}\n\nfunc NewEventLoop(opts ...Option) *EventLoop {\n\tvm := goja.New()\n\n\tloop := &EventLoop{\n\t\tvm:            vm,\n\t\tjobChan:       make(chan func()),\n\t\twakeup:        make(chan struct{}, 1),\n\t\tstopCond:      sync.NewCond(&sync.Mutex{}),\n\t\tenableConsole: true,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(loop)\n\t}\n\tif loop.registry == nil {\n\t\tloop.registry = new(require.Registry)\n\t}\n\tloop.registry.Enable(vm)\n\tif loop.enableConsole {\n\t\tconsole.Enable(vm)\n\t}\n\tvm.Set(\"setTimeout\", loop.setTimeout)\n\tvm.Set(\"setInterval\", loop.setInterval)\n\tvm.Set(\"clearTimeout\", loop.clearTimeout)\n\tvm.Set(\"clearInterval\", loop.clearInterval)\n\n\treturn loop\n}\n\ntype Option func(*EventLoop)\n\n\/\/ EnableConsole controls whether the \"console\" module is loaded into\n\/\/ the runtime used by the loop.  By default, loops are created with\n\/\/ the \"console\" module loaded, pass EnableConsole(false) to\n\/\/ NewEventLoop to disable this behavior.\nfunc EnableConsole(enableConsole bool) Option {\n\treturn func(loop *EventLoop) {\n\t\tloop.enableConsole = enableConsole\n\t}\n}\n\nfunc WithRegistry(registry *require.Registry) Option {\n\treturn func(loop *EventLoop) {\n\t\tloop.registry = registry\n\t}\n}\n\nfunc (loop *EventLoop) schedule(call goja.FunctionCall, repeating bool) goja.Value {\n\tif fn, ok := goja.AssertFunction(call.Argument(0)); ok {\n\t\tdelay := call.Argument(1).ToInteger()\n\t\tvar args []goja.Value\n\t\tif len(call.Arguments) > 2 {\n\t\t\targs = call.Arguments[2:]\n\t\t}\n\t\tf := func() { fn(nil, args...) }\n\t\tloop.jobCount++\n\t\tif repeating {\n\t\t\treturn loop.vm.ToValue(loop.addInterval(f, time.Duration(delay)*time.Millisecond))\n\t\t} else {\n\t\t\treturn loop.vm.ToValue(loop.addTimeout(f, time.Duration(delay)*time.Millisecond))\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (loop *EventLoop) setTimeout(call goja.FunctionCall) goja.Value {\n\treturn loop.schedule(call, false)\n}\n\nfunc (loop *EventLoop) setInterval(call goja.FunctionCall) goja.Value {\n\treturn loop.schedule(call, true)\n}\n\n\/\/ SetTimeout schedules to run the specified function in the context\n\/\/ of the loop as soon as possible after the specified timeout period.\n\/\/ SetTimeout returns a Timer which can be passed to ClearTimeout.\n\/\/ The instance of goja.Runtime that is passed to the function and any Values derived\n\/\/ from it must not be used outside of the function. SetTimeout is\n\/\/ safe to call inside or outside of the loop.\nfunc (loop *EventLoop) SetTimeout(fn func(*goja.Runtime), timeout time.Duration) *Timer {\n\tt := loop.addTimeout(func() { fn(loop.vm) }, timeout)\n\tloop.addAuxJob(func() {\n\t\tloop.jobCount++\n\t})\n\treturn t\n}\n\n\/\/ ClearTimeout cancels a Timer returned by SetTimeout if it has not run yet.\n\/\/ ClearTimeout is safe to call inside or outside of the loop.\nfunc (loop *EventLoop) ClearTimeout(t *Timer) {\n\tloop.addAuxJob(func() {\n\t\tloop.clearTimeout(t)\n\t})\n}\n\n\/\/ SetInterval schedules to repeatedly run the specified function in\n\/\/ the context of the loop as soon as possible after every specified\n\/\/ timeout period.  SetInterval returns an Interval which can be\n\/\/ passed to ClearInterval. The instance of goja.Runtime that is passed to the\n\/\/ function and any Values derived from it must not be used outside of\n\/\/ the function. SetInterval is safe to call inside or outside of the\n\/\/ loop.\nfunc (loop *EventLoop) SetInterval(fn func(*goja.Runtime), timeout time.Duration) *Interval {\n\ti := loop.addInterval(func() { fn(loop.vm) }, timeout)\n\tloop.addAuxJob(func() {\n\t\tloop.jobCount++\n\t})\n\treturn i\n}\n\n\/\/ ClearInterval cancels an Interval returned by SetInterval.\n\/\/ ClearInterval is safe to call inside or outside of the loop.\nfunc (loop *EventLoop) ClearInterval(i *Interval) {\n\tloop.addAuxJob(func() {\n\t\tloop.clearInterval(i)\n\t})\n}\n\nfunc (loop *EventLoop) setRunning() {\n\tloop.stopCond.L.Lock()\n\tif loop.running {\n\t\tpanic(\"Loop is already started\")\n\t}\n\tloop.running = true\n\tloop.stopCond.L.Unlock()\n}\n\n\/\/ Run calls the specified function, starts the event loop and waits until there are no more delayed jobs to run\n\/\/ after which it stops the loop and returns.\n\/\/ The instance of goja.Runtime that is passed to the function and any Values derived from it must not be used outside\n\/\/ of the function.\n\/\/ Do NOT use this function while the loop is already running. Use RunOnLoop() instead.\n\/\/ If the loop is already started it will panic.\nfunc (loop *EventLoop) Run(fn func(*goja.Runtime)) {\n\tloop.setRunning()\n\tfn(loop.vm)\n\tloop.run(false)\n}\n\n\/\/ Start the event loop in the background. The loop continues to run until Stop() is called.\n\/\/ If the loop is already started it will panic.\nfunc (loop *EventLoop) Start() {\n\tloop.setRunning()\n\tgo loop.run(true)\n}\n\n\/\/ Stop the loop that was started with Start(). After this function returns there will be no more jobs executed\n\/\/ by the loop. It is possible to call Start() or Run() again after this to resume the execution.\n\/\/ Note, it does not cancel active timeouts.\n\/\/ It is not allowed to run Start() and Stop() concurrently.\n\/\/ Calling Stop() on an already stopped loop or inside the loop will hang.\nfunc (loop *EventLoop) Stop() {\n\tloop.jobChan <- func() {\n\t\tloop.canRun = false\n\t}\n\n\tloop.stopCond.L.Lock()\n\tfor loop.running {\n\t\tloop.stopCond.Wait()\n\t}\n\tloop.stopCond.L.Unlock()\n}\n\n\/\/ RunOnLoop schedules to run the specified function in the context of the loop as soon as possible.\n\/\/ The order of the runs is preserved (i.e. the functions will be called in the same order as calls to RunOnLoop())\n\/\/ The instance of goja.Runtime that is passed to the function and any Values derived from it must not be used outside\n\/\/ of the function. It is safe to call inside or outside of the loop.\nfunc (loop *EventLoop) RunOnLoop(fn func(*goja.Runtime)) {\n\tloop.addAuxJob(func() { fn(loop.vm) })\n}\n\nfunc (loop *EventLoop) runAux() {\n\tloop.auxJobsLock.Lock()\n\tjobs := loop.auxJobs\n\tloop.auxJobs = nil\n\tloop.auxJobsLock.Unlock()\n\tfor _, job := range jobs {\n\t\tjob()\n\t}\n}\n\nfunc (loop *EventLoop) run(inBackground bool) {\n\tloop.canRun = true\n\tloop.runAux()\n\n\tfor loop.canRun && (inBackground || loop.jobCount > 0) {\n\t\tselect {\n\t\tcase job := <-loop.jobChan:\n\t\t\tjob()\n\t\t\tif loop.canRun {\n\t\t\t\tselect {\n\t\t\t\tcase <-loop.wakeup:\n\t\t\t\t\tloop.runAux()\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-loop.wakeup:\n\t\t\tloop.runAux()\n\t\t}\n\t}\n\tloop.stopCond.L.Lock()\n\tloop.running = false\n\tloop.stopCond.L.Unlock()\n\tloop.stopCond.Broadcast()\n}\n\nfunc (loop *EventLoop) addAuxJob(fn func()) {\n\tloop.auxJobsLock.Lock()\n\tloop.auxJobs = append(loop.auxJobs, fn)\n\tloop.auxJobsLock.Unlock()\n\tselect {\n\tcase loop.wakeup <- struct{}{}:\n\tdefault:\n\t}\n}\n\nfunc (loop *EventLoop) addTimeout(f func(), timeout time.Duration) *Timer {\n\tt := &Timer{\n\t\tjob: job{fn: f},\n\t}\n\tt.timer = time.AfterFunc(timeout, func() {\n\t\tloop.jobChan <- func() {\n\t\t\tloop.doTimeout(t)\n\t\t}\n\t})\n\n\treturn t\n}\n\nfunc (loop *EventLoop) addInterval(f func(), timeout time.Duration) *Interval {\n\t\/\/ https:\/\/nodejs.org\/api\/timers.html#timers_setinterval_callback_delay_args\n\tif timeout <= 0 {\n\t\ttimeout = time.Millisecond\n\t}\n\n\ti := &Interval{\n\t\tjob:      job{fn: f},\n\t\tticker:   time.NewTicker(timeout),\n\t\tstopChan: make(chan struct{}),\n\t}\n\n\tgo i.run(loop)\n\treturn i\n}\n\nfunc (loop *EventLoop) doTimeout(t *Timer) {\n\tif !t.cancelled {\n\t\tt.fn()\n\t\tt.cancelled = true\n\t\tloop.jobCount--\n\t}\n}\n\nfunc (loop *EventLoop) doInterval(i *Interval) {\n\tif !i.cancelled {\n\t\ti.fn()\n\t}\n}\n\nfunc (loop *EventLoop) clearTimeout(t *Timer) {\n\tif t != nil && !t.cancelled {\n\t\tt.timer.Stop()\n\t\tt.cancelled = true\n\t\tloop.jobCount--\n\t}\n}\n\nfunc (loop *EventLoop) clearInterval(i *Interval) {\n\tif i != nil && !i.cancelled {\n\t\ti.cancelled = true\n\t\tclose(i.stopChan)\n\t\tloop.jobCount--\n\t}\n}\n\nfunc (i *Interval) run(loop *EventLoop) {\nL:\n\tfor {\n\t\tselect {\n\t\tcase <-i.stopChan:\n\t\t\ti.ticker.Stop()\n\t\t\tbreak L\n\t\tcase <-i.ticker.C:\n\t\t\tloop.jobChan <- func() {\n\t\t\t\tloop.doInterval(i)\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019, OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Command jaeger is an example program that creates spans\n\/\/ and uploads to Jaeger.\npackage main\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"go.opentelemetry.io\/otel\/api\/core\"\n\t\"go.opentelemetry.io\/otel\/api\/key\"\n\n\t\"go.opentelemetry.io\/otel\/exporter\/trace\/jaeger\"\n\t\"go.opentelemetry.io\/otel\/global\"\n\tsdktrace \"go.opentelemetry.io\/otel\/sdk\/trace\"\n)\n\n\/\/ initTracer creates a new trace provider instance and registers it as global trace provider.\nfunc initTracer() func() {\n\t\/\/ Create Jaeger Exporter\n\texporter, err := jaeger.NewExporter(\n\t\tjaeger.WithCollectorEndpoint(\"http:\/\/localhost:14268\/api\/traces\"),\n\t\tjaeger.WithProcess(jaeger.Process{\n\t\t\tServiceName: \"trace-demo\",\n\t\t\tTags: []core.KeyValue{\n\t\t\t\tkey.String(\"exporter\", \"jaeger\"),\n\t\t\t\tkey.Float64(\"float\", 312.23),\n\t\t\t},\n\t\t}),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ For demoing purposes, always sample. In a production application, you should\n\t\/\/ configure this to a trace.ProbabilitySampler set at the desired\n\t\/\/ probability.\n\ttp, err := sdktrace.NewProvider(\n\t\tsdktrace.WithConfig(sdktrace.Config{DefaultSampler: sdktrace.AlwaysSample()}),\n\t\tsdktrace.WithSyncer(exporter))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tglobal.SetTraceProvider(tp)\n\treturn func() {\n\t\texporter.Flush()\n\t}\n}\n\nfunc main() {\n\tfn := initTracer()\n\tdefer fn()\n\n\tctx := context.Background()\n\n\ttr := global.TraceProvider().GetTracer(\"component-main\")\n\tctx, span := tr.Start(ctx, \"\/foo\")\n\tbar(ctx)\n\tspan.End()\n}\n\nfunc bar(ctx context.Context) {\n\ttr := global.TraceProvider().GetTracer(\"component-bar\")\n\t_, span := tr.Start(ctx, \"\/bar\")\n\tdefer span.End()\n\n\t\/\/ Do bar...\n}\n<commit_msg>[example\/jaeger] Remove prefix slash in Tracer.Start() (#292)<commit_after>\/\/ Copyright 2019, OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Command jaeger is an example program that creates spans\n\/\/ and uploads to Jaeger.\npackage main\n\nimport (\n\t\"context\"\n\t\"log\"\n\n\t\"go.opentelemetry.io\/otel\/api\/core\"\n\t\"go.opentelemetry.io\/otel\/api\/key\"\n\n\t\"go.opentelemetry.io\/otel\/exporter\/trace\/jaeger\"\n\t\"go.opentelemetry.io\/otel\/global\"\n\tsdktrace \"go.opentelemetry.io\/otel\/sdk\/trace\"\n)\n\n\/\/ initTracer creates a new trace provider instance and registers it as global trace provider.\nfunc initTracer() func() {\n\t\/\/ Create Jaeger Exporter\n\texporter, err := jaeger.NewExporter(\n\t\tjaeger.WithCollectorEndpoint(\"http:\/\/localhost:14268\/api\/traces\"),\n\t\tjaeger.WithProcess(jaeger.Process{\n\t\t\tServiceName: \"trace-demo\",\n\t\t\tTags: []core.KeyValue{\n\t\t\t\tkey.String(\"exporter\", \"jaeger\"),\n\t\t\t\tkey.Float64(\"float\", 312.23),\n\t\t\t},\n\t\t}),\n\t)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ For demoing purposes, always sample. In a production application, you should\n\t\/\/ configure this to a trace.ProbabilitySampler set at the desired\n\t\/\/ probability.\n\ttp, err := sdktrace.NewProvider(\n\t\tsdktrace.WithConfig(sdktrace.Config{DefaultSampler: sdktrace.AlwaysSample()}),\n\t\tsdktrace.WithSyncer(exporter))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tglobal.SetTraceProvider(tp)\n\treturn func() {\n\t\texporter.Flush()\n\t}\n}\n\nfunc main() {\n\tfn := initTracer()\n\tdefer fn()\n\n\tctx := context.Background()\n\n\ttr := global.TraceProvider().GetTracer(\"component-main\")\n\tctx, span := tr.Start(ctx, \"foo\")\n\tbar(ctx)\n\tspan.End()\n}\n\nfunc bar(ctx context.Context) {\n\ttr := global.TraceProvider().GetTracer(\"component-bar\")\n\t_, span := tr.Start(ctx, \"bar\")\n\tdefer span.End()\n\n\t\/\/ Do bar...\n}\n<|endoftext|>"}
{"text":"<commit_before>package gopter_test\n\nimport (\n\t\"github.com\/leanovate\/gopter\"\n\t\"github.com\/leanovate\/gopter\/gen\"\n\t\"github.com\/leanovate\/gopter\/prop\"\n)\n\nfunc spookyCalculation(a, b int) int {\n\tif a < 0 {\n\t\ta = -a\n\t}\n\tif b < 0 {\n\t\tb = -b\n\t}\n\treturn 2*b + 3*(2+(a+1)+b*(b+1))\n}\n\n\/\/ Example_labels demonstrates how labels may help, in case of more complex\n\/\/ conditions.\nfunc Example_labels() {\n\tparameters := gopter.DefaultTestParameters()\n\tparameters.Rng.Seed(1234) \/\/ Just for this example to generate reproducable results\n\tparameters.MinSuccessfulTests = 10000\n\n\tproperties := gopter.NewProperties(parameters)\n\n\tproperties.Property(\"Check spooky\", prop.ForAll(\n\t\tfunc(a, b int) string {\n\t\t\tresult := spookyCalculation(a, b)\n\t\t\tif result < 0 {\n\t\t\t\treturn \"negative result\"\n\t\t\t}\n\t\t\tif result%2 == 0 {\n\t\t\t\treturn \"even result\"\n\t\t\t}\n\t\t\treturn \"\"\n\t\t},\n\t\tgen.Int().WithLabel(\"a\"),\n\t\tgen.Int().WithLabel(\"b\"),\n\t))\n\n\t\/\/ When using testing.T you might just use: properties.TestingRun(t)\n\tproperties.Run(gopter.ConsoleReporter(false))\n\t\/\/ Output:\n\t\/\/ ! Check spooky: Falsified after 0 passed tests.\n\t\/\/ > Labels of failing property: even result\n\t\/\/ a: 3\n\t\/\/ a_ORIGINAL (44 shrinks): 861384713\n\t\/\/ b: 0\n\t\/\/ b_ORIGINAL (1 shrinks): -642623569\n}\n<commit_msg>Workaround for godoc<commit_after>package gopter_test\n\nimport (\n\t\"github.com\/leanovate\/gopter\"\n\t\"github.com\/leanovate\/gopter\/gen\"\n\t\"github.com\/leanovate\/gopter\/prop\"\n)\n\nfunc spookyCalculation(a, b int) int {\n\tif a < 0 {\n\t\ta = -a\n\t}\n\tif b < 0 {\n\t\tb = -b\n\t}\n\treturn 2*b + 3*(2+(a+1)+b*(b+1))\n}\n\n\/\/ Example_labels demonstrates how labels may help, in case of more complex\n\/\/ conditions.\n\/\/ The output will be:\n\/\/  ! Check spooky: Falsified after 0 passed tests.\n\/\/  > Labels of failing property: even result\n\/\/  a: 3\n\/\/  a_ORIGINAL (44 shrinks): 861384713\n\/\/  b: 0\n\/\/  b_ORIGINAL (1 shrinks): -642623569\nfunc Example_labels() {\n\tparameters := gopter.DefaultTestParameters()\n\tparameters.Rng.Seed(1234) \/\/ Just for this example to generate reproducable results\n\tparameters.MinSuccessfulTests = 10000\n\n\tproperties := gopter.NewProperties(parameters)\n\n\tproperties.Property(\"Check spooky\", prop.ForAll(\n\t\tfunc(a, b int) string {\n\t\t\tresult := spookyCalculation(a, b)\n\t\t\tif result < 0 {\n\t\t\t\treturn \"negative result\"\n\t\t\t}\n\t\t\tif result%2 == 0 {\n\t\t\t\treturn \"even result\"\n\t\t\t}\n\t\t\treturn \"\"\n\t\t},\n\t\tgen.Int().WithLabel(\"a\"),\n\t\tgen.Int().WithLabel(\"b\"),\n\t))\n\n\t\/\/ When using testing.T you might just use: properties.TestingRun(t)\n\tproperties.Run(gopter.ConsoleReporter(false))\n\t\/\/ Output:\n\t\/\/ ! Check spooky: Falsified after 0 passed tests.\n\t\/\/ > Labels of failing property: even result\n\t\/\/ a: 3\n\t\/\/ a_ORIGINAL (44 shrinks): 861384713\n\t\/\/ b: 0\n\t\/\/ b_ORIGINAL (1 shrinks): -642623569\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\".\/handlers\"\n\t\"github.com\/SkylakeCoder\/go-web\/web\"\n\t\"log\"\n)\n\nfunc main() {\n\tapp := web.GetApp()\n\tapp.SetViewType(web.VIEW_EGO)\n\tapp.SetViewDir(\".\/views_ego\")\n\tapp.SetStaticDir(\".\/static\")\n\n\tapp.Get(\"\/hello\", &handlers.Hello{})\n\tapp.Get(\"\/json\", &handlers.JSON{})\n\tapp.Get(\"\/view\", &handlers.View{})\n\tapp.Post(\"\/post_form\", &handlers.PostForm{})\n\tapp.Get(\"\/user\/:username\", &handlers.UserColon{})\n\tapp.Get(\"\/count\", &handlers.Count{})\n\tapp.Get(\"\/404\", &handlers.Handler404{})\n\tapp.Post(\"\/404\", &handlers.Handler404{})\n\n\terr := app.Listen(8688)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n<commit_msg>a method name has been changed.<commit_after>package main\n\nimport (\n\t\".\/handlers\"\n\t\"github.com\/SkylakeCoder\/go-web\/web\"\n\t\"log\"\n)\n\nfunc main() {\n\tapp := web.NewApp()\n\tapp.SetViewType(web.VIEW_EGO)\n\tapp.SetViewDir(\".\/views_ego\")\n\tapp.SetStaticDir(\".\/static\")\n\n\tapp.Get(\"\/hello\", &handlers.Hello{})\n\tapp.Get(\"\/json\", &handlers.JSON{})\n\tapp.Get(\"\/view\", &handlers.View{})\n\tapp.Post(\"\/post_form\", &handlers.PostForm{})\n\tapp.Get(\"\/user\/:username\", &handlers.UserColon{})\n\tapp.Get(\"\/count\", &handlers.Count{})\n\tapp.Get(\"\/404\", &handlers.Handler404{})\n\tapp.Post(\"\/404\", &handlers.Handler404{})\n\n\terr := app.Listen(8688)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nPackage pipe provides filters that can be chained together in a manner\nsimilar to Unix pipelines.\n\nEach filter is a function that takes as input a sequence of\nstrings (read from a channel) and produces as output a sequence of\nstrings (written to a channel).\n\nFilters can be chained together (e.g., via the Run function), the\noutput of one filter is fed as input to the next filter.  The empty\ninput is passed to the first filter. The following sequence will\nprint two lines to standard output:\n\n\terr := pipe.Run(\n\t\tpipe.Echo(\"hello\", \"world\"),\n\t\tpipe.Reverse(),\n\t\tpipe.WriteLines(os.Stdout),\n\t)\n\nAn application can implement its own filters easily. For example,\nrepeat(n) returns a filter that repeats every input n times.\n\n\tfunc repeat(n int) Filter {\n\t\treturn func(arg pipe.Arg) {\n\t\t\tfor s := range arg.In {\n\t\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\t\targ.Out <- s\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpipe.Run(\n\t\tpipe.Echo(\"hello\"),\n\t\trepeat(10),\n\t)\n\nNote that repeat is not a Filter since it needs to accept the\nparameter n. Instead, it returns a Filter.  This convention is\nfollowed throughout this library: all filtering functionality is\nprovided by functions that return a Filter.\n\n*\/\npackage pipe\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"sync\"\n)\n\n\/\/ filterErrors records errors accumulated during the execution of a filter.\ntype filterErrors struct {\n\tmu     sync.Mutex\n\terrors []error\n}\n\n\/\/ Arg contains the data passed to a Filter. Arg.In is a channel that\n\/\/ produces the input to the filter, and Arg.Out is a channel that\n\/\/ receives the output from the filter.\ntype Arg struct {\n\tIn     <-chan string\n\tOut    chan<- string\n\terrors *filterErrors\n}\n\n\/\/ ReportError records an error encountered during an execution of a filter.\n\/\/ This error will be reported by whatever facility (e.g., ForEach or Run)\n\/\/ was being used to execute the filters.\n\/\/\n\/\/ A filter should report any errors by calling ReportError.  Even if\n\/\/ the filter has reported an error, it should read all data from\n\/\/ arg.In, if only to disarded immediately.\nfunc (a *Arg) ReportError(err error) {\n\ta.errors.mu.Lock()\n\tdefer a.errors.mu.Unlock()\n\ta.errors.errors = append(a.errors.errors, err)\n}\n\n\/\/ Filter is the type of a function that reads a sequence of strings\n\/\/ from a channel and produces a sequence on another channel.\ntype Filter func(Arg)\n\n\/\/ Sequence returns a filter that is the concatenation of all filter arguments.\n\/\/ The output of a filter is fed as input to the next filter.\nfunc Sequence(filters ...Filter) Filter {\n\treturn func(arg Arg) {\n\t\tin := arg.In\n\t\tfor _, f := range filters {\n\t\t\tc := make(chan string, 10000)\n\t\t\tgo runAndClose(f, Arg{in, c, arg.errors})\n\t\t\tin = c\n\t\t}\n\t\tpassThrough(Arg{in, arg.Out, arg.errors})\n\t}\n}\n\n\/\/ Run executes the sequence of filters and discards all output.\n\/\/ It returns either nil, an error if any filter reported an error.\nfunc Run(filters ...Filter) error {\n\treturn ForEach(Sequence(filters...), func(s string) {})\n}\n\n\/\/ ForEach calls fn(s) for every item s in the output of filter and\n\/\/ returns either nil, or any error reported by the execution of the filter.\nfunc ForEach(filter Filter, fn func(s string)) error {\n\tin := make(chan string, 0)\n\tclose(in)\n\tout := make(chan string, 10000)\n\te := &filterErrors{}\n\tgo runAndClose(filter, Arg{in, out, e})\n\tfor s := range out {\n\t\tfn(s)\n\t}\n\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\tswitch len(e.errors) {\n\tcase 0:\n\t\treturn nil\n\tcase 1:\n\t\treturn e.errors[0]\n\tdefault:\n\t\treturn fmt.Errorf(\"Filter errors: %s\", e.errors)\n\t}\n}\n\nfunc runAndClose(f Filter, arg Arg) {\n\tf(arg)\n\tclose(arg.Out)\n}\n\n\/\/ passThrough copies all items read from in to out.\nfunc passThrough(arg Arg) {\n\tfor s := range arg.In {\n\t\targ.Out <- s\n\t}\n}\n\n\/\/ Echo emits items.\n\/\/ Any input items are copied verbatim to the output before items are emitted.\nfunc Echo(items ...string) Filter {\n\treturn func(arg Arg) {\n\t\tpassThrough(arg)\n\t\tfor _, s := range items {\n\t\t\targ.Out <- s\n\t\t}\n\t}\n}\n\n\/\/ Numbers copies its input and then emits the integers x..y\nfunc Numbers(x, y int) Filter {\n\treturn func(arg Arg) {\n\t\tpassThrough(arg)\n\t\tfor i := x; i <= y; i++ {\n\t\t\targ.Out <- fmt.Sprintf(\"%d\", i)\n\t\t}\n\t}\n}\n\n\/\/ Map calls fn(x) for every item x and yields the outputs of the fn calls.\nfunc Map(fn func(string) string) Filter {\n\treturn func(arg Arg) {\n\t\tfor s := range arg.In {\n\t\t\targ.Out <- fn(s)\n\t\t}\n\t}\n}\n\n\/\/ If emits every input x for which fn(x) is true.\nfunc If(fn func(string) bool) Filter {\n\treturn func(arg Arg) {\n\t\tfor s := range arg.In {\n\t\t\tif fn(s) {\n\t\t\t\targ.Out <- s\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc errorFilter(err error) Filter {\n\treturn func(arg Arg) {\n\t\targ.ReportError(err)\n\t\tfor _ = range arg.In {\n\t\t\t\/\/ Drop the input\n\t\t}\n\t}\n}\n\n\/\/ Grep emits every input x that matches the regular expression r.\nfunc Grep(r string) Filter {\n\tre, err := regexp.Compile(r)\n\tif err != nil {\n\t\treturn errorFilter(err)\n\t}\n\treturn If(re.MatchString)\n}\n\n\/\/ GrepNot emits every input x that does not match the regular expression r.\nfunc GrepNot(r string) Filter {\n\tre, err := regexp.Compile(r)\n\tif err != nil {\n\t\treturn errorFilter(err)\n\t}\n\treturn If(func(s string) bool { return !re.MatchString(s) })\n}\n\n\/\/ Uniq squashes adjacent identical items in arg.In into a single output.\nfunc Uniq() Filter {\n\treturn func(arg Arg) {\n\t\tfirst := true\n\t\tlast := \"\"\n\t\tfor s := range arg.In {\n\t\t\tif first || last != s {\n\t\t\t\targ.Out <- s\n\t\t\t}\n\t\t\tlast = s\n\t\t\tfirst = false\n\t\t}\n\t}\n}\n\n\/\/ UniqWithCount squashes adjacent identical items in arg.In into a single\n\/\/ output prefixed with the count of identical items.\nfunc UniqWithCount() Filter {\n\treturn func(arg Arg) {\n\t\tcurrent := \"\"\n\t\tcount := 0\n\t\tfor s := range arg.In {\n\t\t\tif s != current {\n\t\t\t\tif count > 0 {\n\t\t\t\t\targ.Out <- fmt.Sprintf(\"%d %s\", count, current)\n\t\t\t\t}\n\t\t\t\tcount = 0\n\t\t\t\tcurrent = s\n\t\t\t}\n\t\t\tcount++\n\t\t}\n\t\tif count > 0 {\n\t\t\targ.Out <- fmt.Sprintf(\"%d %s\", count, current)\n\t\t}\n\t}\n}\n\n\/\/ Substitute replaces all occurrences of the regular expression r in\n\/\/ an input item with replacement.  The replacement string can contain\n\/\/ $1, $2, etc. which represent submatches of r.\nfunc Substitute(r, replacement string) Filter {\n\tre, err := regexp.Compile(r)\n\tif err != nil {\n\t\treturn errorFilter(err)\n\t}\n\treturn func(arg Arg) {\n\t\tfor s := range arg.In {\n\t\t\targ.Out <- re.ReplaceAllString(s, replacement)\n\t\t}\n\t}\n}\n\n\/\/ Reverse yields items in the reverse of the order it received them.\nfunc Reverse() Filter {\n\treturn func(arg Arg) {\n\t\tvar data []string\n\t\tfor s := range arg.In {\n\t\t\tdata = append(data, s)\n\t\t}\n\t\tfor i := len(data) - 1; i >= 0; i-- {\n\t\t\targ.Out <- data[i]\n\t\t}\n\t}\n}\n\n\/\/ First yields the first n items that it receives.\nfunc First(n int) Filter {\n\treturn func(arg Arg) {\n\t\temitted := 0\n\t\tfor s := range arg.In {\n\t\t\tif emitted < n {\n\t\t\t\targ.Out <- s\n\t\t\t\temitted++\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ DropFirst yields all items except for the first n items that it receives.\nfunc DropFirst(n int) Filter {\n\treturn func(arg Arg) {\n\t\temitted := 0\n\t\tfor s := range arg.In {\n\t\t\tif emitted >= n {\n\t\t\t\targ.Out <- s\n\t\t\t}\n\t\t\temitted++\n\t\t}\n\t}\n}\n\n\/\/ Last yields the last n items that it receives.\nfunc Last(n int) Filter {\n\treturn func(arg Arg) {\n\t\tvar buf []string\n\t\tfor s := range arg.In {\n\t\t\tbuf = append(buf, s)\n\t\t\tif len(buf) > n {\n\t\t\t\tbuf = buf[1:]\n\t\t\t}\n\t\t}\n\t\tfor _, s := range buf {\n\t\t\targ.Out <- s\n\t\t}\n\t}\n}\n\n\/\/ DropLast yields all items except for the last n items that it receives.\nfunc DropLast(n int) Filter {\n\treturn func(arg Arg) {\n\t\tvar buf []string\n\t\tfor s := range arg.In {\n\t\t\tbuf = append(buf, s)\n\t\t\tif len(buf) > n {\n\t\t\t\targ.Out <- buf[0]\n\t\t\t\tbuf = buf[1:]\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ NumberLines prefixes its item with its index in the input sequence\n\/\/ (starting at 1).\nfunc NumberLines() Filter {\n\treturn func(arg Arg) {\n\t\tline := 1\n\t\tfor s := range arg.In {\n\t\t\targ.Out <- fmt.Sprintf(\"%5d %s\", line, s)\n\t\t\tline++\n\t\t}\n\t}\n}\n\n\/\/ Slice emits s[startOffset:endOffset] for each input item s.  Note\n\/\/ that Slice follows Go conventions, and unlike the \"cut\" utility,\n\/\/ offsets are numbered starting at zero, and the end offset is not\n\/\/ included in the output.\nfunc Slice(startOffset, endOffset int) Filter {\n\treturn func(arg Arg) {\n\t\tfor s := range arg.In {\n\t\t\tif len(s) > endOffset {\n\t\t\t\ts = s[:endOffset]\n\t\t\t}\n\t\t\tif len(s) < startOffset {\n\t\t\t\ts = \"\"\n\t\t\t} else {\n\t\t\t\ts = s[startOffset:]\n\t\t\t}\n\t\t\targ.Out <- s\n\t\t}\n\t}\n}\n\n\/\/ Select splits each item into columns and yields the concatenation\n\/\/ of the columns numbers passed as arguments to Select.  Columns are\n\/\/ numbered starting at 1. A column number of 0 is interpreted as the\n\/\/ full string.\nfunc Select(columns ...int) Filter {\n\treturn func(arg Arg) {\n\t\tfor s := range arg.In {\n\t\t\tresult := \"\"\n\t\t\tfor _, col := range columns {\n\t\t\t\tif _, c := column(s, col); c != \"\" {\n\t\t\t\t\tif result != \"\" {\n\t\t\t\t\t\tresult = result + \" \"\n\t\t\t\t\t}\n\t\t\t\t\tresult = result + c\n\t\t\t\t}\n\t\t\t}\n\t\t\targ.Out <- result\n\t\t}\n\t}\n}\n<commit_msg>fix typo<commit_after>\/*\nPackage pipe provides filters that can be chained together in a manner\nsimilar to Unix pipelines.\n\nEach filter is a function that takes as input a sequence of\nstrings (read from a channel) and produces as output a sequence of\nstrings (written to a channel).\n\nFilters can be chained together (e.g., via the Run function), the\noutput of one filter is fed as input to the next filter.  The empty\ninput is passed to the first filter. The following sequence will\nprint two lines to standard output:\n\n\terr := pipe.Run(\n\t\tpipe.Echo(\"hello\", \"world\"),\n\t\tpipe.Reverse(),\n\t\tpipe.WriteLines(os.Stdout),\n\t)\n\nAn application can implement its own filters easily. For example,\nrepeat(n) returns a filter that repeats every input n times.\n\n\tfunc repeat(n int) Filter {\n\t\treturn func(arg pipe.Arg) {\n\t\t\tfor s := range arg.In {\n\t\t\t\tfor i := 0; i < n; i++ {\n\t\t\t\t\targ.Out <- s\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpipe.Run(\n\t\tpipe.Echo(\"hello\"),\n\t\trepeat(10),\n\t)\n\nNote that repeat is not a Filter since it needs to accept the\nparameter n. Instead, it returns a Filter.  This convention is\nfollowed throughout this library: all filtering functionality is\nprovided by functions that return a Filter.\n\n*\/\npackage pipe\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"sync\"\n)\n\n\/\/ filterErrors records errors accumulated during the execution of a filter.\ntype filterErrors struct {\n\tmu     sync.Mutex\n\terrors []error\n}\n\n\/\/ Arg contains the data passed to a Filter. Arg.In is a channel that\n\/\/ produces the input to the filter, and Arg.Out is a channel that\n\/\/ receives the output from the filter.\ntype Arg struct {\n\tIn     <-chan string\n\tOut    chan<- string\n\terrors *filterErrors\n}\n\n\/\/ ReportError records an error encountered during an execution of a filter.\n\/\/ This error will be reported by whatever facility (e.g., ForEach or Run)\n\/\/ was being used to execute the filters.\n\/\/\n\/\/ A filter should report any errors by calling ReportError.  Even if\n\/\/ the filter has reported an error, it should read all data from\n\/\/ arg.In, if only to disard it immediately.\nfunc (a *Arg) ReportError(err error) {\n\ta.errors.mu.Lock()\n\tdefer a.errors.mu.Unlock()\n\ta.errors.errors = append(a.errors.errors, err)\n}\n\n\/\/ Filter is the type of a function that reads a sequence of strings\n\/\/ from a channel and produces a sequence on another channel.\ntype Filter func(Arg)\n\n\/\/ Sequence returns a filter that is the concatenation of all filter arguments.\n\/\/ The output of a filter is fed as input to the next filter.\nfunc Sequence(filters ...Filter) Filter {\n\treturn func(arg Arg) {\n\t\tin := arg.In\n\t\tfor _, f := range filters {\n\t\t\tc := make(chan string, 10000)\n\t\t\tgo runAndClose(f, Arg{in, c, arg.errors})\n\t\t\tin = c\n\t\t}\n\t\tpassThrough(Arg{in, arg.Out, arg.errors})\n\t}\n}\n\n\/\/ Run executes the sequence of filters and discards all output.\n\/\/ It returns either nil, an error if any filter reported an error.\nfunc Run(filters ...Filter) error {\n\treturn ForEach(Sequence(filters...), func(s string) {})\n}\n\n\/\/ ForEach calls fn(s) for every item s in the output of filter and\n\/\/ returns either nil, or any error reported by the execution of the filter.\nfunc ForEach(filter Filter, fn func(s string)) error {\n\tin := make(chan string, 0)\n\tclose(in)\n\tout := make(chan string, 10000)\n\te := &filterErrors{}\n\tgo runAndClose(filter, Arg{in, out, e})\n\tfor s := range out {\n\t\tfn(s)\n\t}\n\n\te.mu.Lock()\n\tdefer e.mu.Unlock()\n\tswitch len(e.errors) {\n\tcase 0:\n\t\treturn nil\n\tcase 1:\n\t\treturn e.errors[0]\n\tdefault:\n\t\treturn fmt.Errorf(\"Filter errors: %s\", e.errors)\n\t}\n}\n\nfunc runAndClose(f Filter, arg Arg) {\n\tf(arg)\n\tclose(arg.Out)\n}\n\n\/\/ passThrough copies all items read from in to out.\nfunc passThrough(arg Arg) {\n\tfor s := range arg.In {\n\t\targ.Out <- s\n\t}\n}\n\n\/\/ Echo emits items.\n\/\/ Any input items are copied verbatim to the output before items are emitted.\nfunc Echo(items ...string) Filter {\n\treturn func(arg Arg) {\n\t\tpassThrough(arg)\n\t\tfor _, s := range items {\n\t\t\targ.Out <- s\n\t\t}\n\t}\n}\n\n\/\/ Numbers copies its input and then emits the integers x..y\nfunc Numbers(x, y int) Filter {\n\treturn func(arg Arg) {\n\t\tpassThrough(arg)\n\t\tfor i := x; i <= y; i++ {\n\t\t\targ.Out <- fmt.Sprintf(\"%d\", i)\n\t\t}\n\t}\n}\n\n\/\/ Map calls fn(x) for every item x and yields the outputs of the fn calls.\nfunc Map(fn func(string) string) Filter {\n\treturn func(arg Arg) {\n\t\tfor s := range arg.In {\n\t\t\targ.Out <- fn(s)\n\t\t}\n\t}\n}\n\n\/\/ If emits every input x for which fn(x) is true.\nfunc If(fn func(string) bool) Filter {\n\treturn func(arg Arg) {\n\t\tfor s := range arg.In {\n\t\t\tif fn(s) {\n\t\t\t\targ.Out <- s\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc errorFilter(err error) Filter {\n\treturn func(arg Arg) {\n\t\targ.ReportError(err)\n\t\tfor _ = range arg.In {\n\t\t\t\/\/ Drop the input\n\t\t}\n\t}\n}\n\n\/\/ Grep emits every input x that matches the regular expression r.\nfunc Grep(r string) Filter {\n\tre, err := regexp.Compile(r)\n\tif err != nil {\n\t\treturn errorFilter(err)\n\t}\n\treturn If(re.MatchString)\n}\n\n\/\/ GrepNot emits every input x that does not match the regular expression r.\nfunc GrepNot(r string) Filter {\n\tre, err := regexp.Compile(r)\n\tif err != nil {\n\t\treturn errorFilter(err)\n\t}\n\treturn If(func(s string) bool { return !re.MatchString(s) })\n}\n\n\/\/ Uniq squashes adjacent identical items in arg.In into a single output.\nfunc Uniq() Filter {\n\treturn func(arg Arg) {\n\t\tfirst := true\n\t\tlast := \"\"\n\t\tfor s := range arg.In {\n\t\t\tif first || last != s {\n\t\t\t\targ.Out <- s\n\t\t\t}\n\t\t\tlast = s\n\t\t\tfirst = false\n\t\t}\n\t}\n}\n\n\/\/ UniqWithCount squashes adjacent identical items in arg.In into a single\n\/\/ output prefixed with the count of identical items.\nfunc UniqWithCount() Filter {\n\treturn func(arg Arg) {\n\t\tcurrent := \"\"\n\t\tcount := 0\n\t\tfor s := range arg.In {\n\t\t\tif s != current {\n\t\t\t\tif count > 0 {\n\t\t\t\t\targ.Out <- fmt.Sprintf(\"%d %s\", count, current)\n\t\t\t\t}\n\t\t\t\tcount = 0\n\t\t\t\tcurrent = s\n\t\t\t}\n\t\t\tcount++\n\t\t}\n\t\tif count > 0 {\n\t\t\targ.Out <- fmt.Sprintf(\"%d %s\", count, current)\n\t\t}\n\t}\n}\n\n\/\/ Substitute replaces all occurrences of the regular expression r in\n\/\/ an input item with replacement.  The replacement string can contain\n\/\/ $1, $2, etc. which represent submatches of r.\nfunc Substitute(r, replacement string) Filter {\n\tre, err := regexp.Compile(r)\n\tif err != nil {\n\t\treturn errorFilter(err)\n\t}\n\treturn func(arg Arg) {\n\t\tfor s := range arg.In {\n\t\t\targ.Out <- re.ReplaceAllString(s, replacement)\n\t\t}\n\t}\n}\n\n\/\/ Reverse yields items in the reverse of the order it received them.\nfunc Reverse() Filter {\n\treturn func(arg Arg) {\n\t\tvar data []string\n\t\tfor s := range arg.In {\n\t\t\tdata = append(data, s)\n\t\t}\n\t\tfor i := len(data) - 1; i >= 0; i-- {\n\t\t\targ.Out <- data[i]\n\t\t}\n\t}\n}\n\n\/\/ First yields the first n items that it receives.\nfunc First(n int) Filter {\n\treturn func(arg Arg) {\n\t\temitted := 0\n\t\tfor s := range arg.In {\n\t\t\tif emitted < n {\n\t\t\t\targ.Out <- s\n\t\t\t\temitted++\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ DropFirst yields all items except for the first n items that it receives.\nfunc DropFirst(n int) Filter {\n\treturn func(arg Arg) {\n\t\temitted := 0\n\t\tfor s := range arg.In {\n\t\t\tif emitted >= n {\n\t\t\t\targ.Out <- s\n\t\t\t}\n\t\t\temitted++\n\t\t}\n\t}\n}\n\n\/\/ Last yields the last n items that it receives.\nfunc Last(n int) Filter {\n\treturn func(arg Arg) {\n\t\tvar buf []string\n\t\tfor s := range arg.In {\n\t\t\tbuf = append(buf, s)\n\t\t\tif len(buf) > n {\n\t\t\t\tbuf = buf[1:]\n\t\t\t}\n\t\t}\n\t\tfor _, s := range buf {\n\t\t\targ.Out <- s\n\t\t}\n\t}\n}\n\n\/\/ DropLast yields all items except for the last n items that it receives.\nfunc DropLast(n int) Filter {\n\treturn func(arg Arg) {\n\t\tvar buf []string\n\t\tfor s := range arg.In {\n\t\t\tbuf = append(buf, s)\n\t\t\tif len(buf) > n {\n\t\t\t\targ.Out <- buf[0]\n\t\t\t\tbuf = buf[1:]\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ NumberLines prefixes its item with its index in the input sequence\n\/\/ (starting at 1).\nfunc NumberLines() Filter {\n\treturn func(arg Arg) {\n\t\tline := 1\n\t\tfor s := range arg.In {\n\t\t\targ.Out <- fmt.Sprintf(\"%5d %s\", line, s)\n\t\t\tline++\n\t\t}\n\t}\n}\n\n\/\/ Slice emits s[startOffset:endOffset] for each input item s.  Note\n\/\/ that Slice follows Go conventions, and unlike the \"cut\" utility,\n\/\/ offsets are numbered starting at zero, and the end offset is not\n\/\/ included in the output.\nfunc Slice(startOffset, endOffset int) Filter {\n\treturn func(arg Arg) {\n\t\tfor s := range arg.In {\n\t\t\tif len(s) > endOffset {\n\t\t\t\ts = s[:endOffset]\n\t\t\t}\n\t\t\tif len(s) < startOffset {\n\t\t\t\ts = \"\"\n\t\t\t} else {\n\t\t\t\ts = s[startOffset:]\n\t\t\t}\n\t\t\targ.Out <- s\n\t\t}\n\t}\n}\n\n\/\/ Select splits each item into columns and yields the concatenation\n\/\/ of the columns numbers passed as arguments to Select.  Columns are\n\/\/ numbered starting at 1. A column number of 0 is interpreted as the\n\/\/ full string.\nfunc Select(columns ...int) Filter {\n\treturn func(arg Arg) {\n\t\tfor s := range arg.In {\n\t\t\tresult := \"\"\n\t\t\tfor _, col := range columns {\n\t\t\t\tif _, c := column(s, col); c != \"\" {\n\t\t\t\t\tif result != \"\" {\n\t\t\t\t\t\tresult = result + \" \"\n\t\t\t\t\t}\n\t\t\t\t\tresult = result + c\n\t\t\t\t}\n\t\t\t}\n\t\t\targ.Out <- result\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package app\n\nimport (\n\t\"github.com\/toonsevrin\/simplechain\/types\"\n\t\"net\/http\"\n\t\"github.com\/gorilla\/mux\"\n\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"fmt\"\n\t\"strings\"\n\t\"os\"\n)\n\ntype Server struct {\n\tApp App\n}\nfunc (server *Server) Init(){\n\n\trouter := mux.NewRouter().StrictSlash(true)\n\n\trouter.Methods(\"GET\").Path(\"\/blocks\").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\tif isLocalhostOrPeer(*server, *request){\n\t\t\tjson.NewEncoder(writer).Encode(server.App.Blockchain)\n\t\t}else {\n\t\t\tjson.NewEncoder(writer).Encode(Success{false, &string(\"Unauthorized\")})\n\t\t}\n\t})\n\trouter.Methods(\"POST\").Path(\"\/mineBlock\").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\tif isLocalhostOrPeer(*server, *request) {\n\t\t\tbody, err := ioutil.ReadAll(request.Body)\n\t\t\tif err != nil {\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{false, &string(\"An error occurred reading request body\")})\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdata := string(body)\n\t\t\tblock := server.App.createAndAddNextBlock(data)\n\t\t\tjson.NewEncoder(writer).Encode(Success{Success:true})\n\t\t\tserver.App.broadcast(block)\n\t\t}else {\n\t\t\tjson.NewEncoder(writer).Encode(Success{false, &\"Unauthorized\"})\n\t\t}\n\t})\n\trouter.Methods(\"POST\").Path(\"\/addBlock\").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\tif isLocalhostOrPeer(*server, *request){\n\t\t\tblock := types.Block{}\n\t\t\tbody, err := ioutil.ReadAll(request.Body)\n\t\t\tif err != nil {\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{false,&\"An error occurred reading request body\"})\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := json.Unmarshal(body, &block); err != nil {\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{false,&\"An error occurred parsing request body\"})\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif server.App.HasBlock(block){\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{false,&\"Block already exists\"})\n\t\t\t\tfmt.Println(\"Received block that already exists in db.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !block.IsValid() {\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{false,&\"Received invalid block\"})\n\t\t\t\tfmt.Println(\"Received invalid block\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif uint32(len(server.App.Blockchain)) == block.Index {\/\/next block\n\t\t\t\tif block.PreviousHash == server.App.getLatestBlock().Hash {\/\/next block references your chain\n\t\t\t\t\tserver.App.AddBlock(block)\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: true})\n\t\t\t\t\tserver.App.broadcast(block)\n\t\t\t\t}else {\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &\"Invalid hash\"})\n\t\t\t\t}\n\t\t\t}else if uint32(len(server.App.Blockchain)) < block.Index {\/\/block is in the future\n\t\t\t\tRemoteChain := []types.Block{}\n\t\t\t\tresponse, err := http.NewRequest(\"GET\", server.App.Peers[request.RemoteAddr].getUrl() + \"\/blocks\", nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &string(err.Error())})\n\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tbody, err := ioutil.ReadAll(response.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &string(err.Error())})\n\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err := json.Unmarshal(body, &RemoteChain); err != nil {\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &string(err.Error())})\n\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif(server.App.pickLongestChain(RemoteChain)){\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: true})\n\t\t\t\t\tserver.App.broadcast(block)\n\t\t\t\t}else {\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &\"Peer has a longer chain\"})\n\t\t\t\t}\n\t\t\t}\n\t\t}else {\n\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &\"Unauthorized\"})\n\t\t}\n\t})\n\trouter.Methods(\"POST\").Path(\"\/addPeer\").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\tif isLocalhost(*request){\n\t\t\tbody, err := ioutil.ReadAll(request.Body)\n\t\t\tif err != nil {\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &string(err.Error())})\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpeer := Peer{}\n\t\t\tif err := json.Unmarshal(body, &peer); err != nil {\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &string(err.Error())})\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tserver.App.Peers[peer.getUrl()] = &peer\n\t\t\tserver.App.PeerAddresses[peer.Ip] = true\n\t\t\tjson.NewEncoder(writer).Encode(Success{Success: true})\n\t\t}else{\n\t\t\twriter.Write([]byte(\"Only localhost can add peers\"))\n\t\t}\n\t})\n\thttp.ListenAndServe(\":\" + getPort(), router)\n}\nfunc getPort() string{\n\tport := os.Getenv(\"PORT\")\n\tif(port == \"\"){\n\t\treturn \"8080\"\n\t}else {\n\t\treturn port\n\t}\n}\nfunc isLocalhostOrPeer(server Server, request http.Request) bool{\n\t_, isPeer := server.App.PeerAddresses[request.RemoteAddr]\n\treturn isPeer || isLocalhost(request)\n}\nfunc isLocalhost(req http.Request) bool{\n\tfmt.Println(req.RemoteAddr)\n\treturn strings.Contains(req.RemoteAddr, \"127.0.0.1\") || strings.Contains(req.RemoteAddr, \"[::1]\")\/\/::1 is ipv6\n}\n\ntype Success struct {\n\tSuccess bool `json:\"success\"`\n\tError *string `json:\"error\"`\n}<commit_msg>testing pointer string v2<commit_after>package app\n\nimport (\n\t\"github.com\/toonsevrin\/simplechain\/types\"\n\t\"net\/http\"\n\t\"github.com\/gorilla\/mux\"\n\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"fmt\"\n\t\"strings\"\n\t\"os\"\n)\n\ntype Server struct {\n\tApp App\n}\nfunc (server *Server) Init(){\n\n\trouter := mux.NewRouter().StrictSlash(true)\n\n\trouter.Methods(\"GET\").Path(\"\/blocks\").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\tif isLocalhostOrPeer(*server, *request){\n\t\t\tjson.NewEncoder(writer).Encode(server.App.Blockchain)\n\t\t}else {\n\t\t\tjson.NewEncoder(writer).Encode(Success{false, str(\"Unauthorized\")})\n\t\t}\n\t})\n\trouter.Methods(\"POST\").Path(\"\/mineBlock\").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\tif isLocalhostOrPeer(*server, *request) {\n\t\t\tbody, err := ioutil.ReadAll(request.Body)\n\t\t\tif err != nil {\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{false, str(\"An error occurred reading request body\")})\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdata := string(body)\n\t\t\tblock := server.App.createAndAddNextBlock(data)\n\t\t\tjson.NewEncoder(writer).Encode(Success{Success:true})\n\t\t\tserver.App.broadcast(block)\n\t\t}else {\n\t\t\tjson.NewEncoder(writer).Encode(Success{false, &\"Unauthorized\"})\n\t\t}\n\t})\n\trouter.Methods(\"POST\").Path(\"\/addBlock\").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\tif isLocalhostOrPeer(*server, *request){\n\t\t\tblock := types.Block{}\n\t\t\tbody, err := ioutil.ReadAll(request.Body)\n\t\t\tif err != nil {\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{false,&\"An error occurred reading request body\"})\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err := json.Unmarshal(body, &block); err != nil {\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{false,&\"An error occurred parsing request body\"})\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif server.App.HasBlock(block){\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{false,&\"Block already exists\"})\n\t\t\t\tfmt.Println(\"Received block that already exists in db.\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !block.IsValid() {\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{false,&\"Received invalid block\"})\n\t\t\t\tfmt.Println(\"Received invalid block\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif uint32(len(server.App.Blockchain)) == block.Index {\/\/next block\n\t\t\t\tif block.PreviousHash == server.App.getLatestBlock().Hash {\/\/next block references your chain\n\t\t\t\t\tserver.App.AddBlock(block)\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: true})\n\t\t\t\t\tserver.App.broadcast(block)\n\t\t\t\t}else {\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &\"Invalid hash\"})\n\t\t\t\t}\n\t\t\t}else if uint32(len(server.App.Blockchain)) < block.Index {\/\/block is in the future\n\t\t\t\tRemoteChain := []types.Block{}\n\t\t\t\tresponse, err := http.NewRequest(\"GET\", server.App.Peers[request.RemoteAddr].getUrl() + \"\/blocks\", nil)\n\t\t\t\tif err != nil {\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &string(err.Error())})\n\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tbody, err := ioutil.ReadAll(response.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &string(err.Error())})\n\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err := json.Unmarshal(body, &RemoteChain); err != nil {\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &string(err.Error())})\n\t\t\t\t\tfmt.Println(err.Error())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif(server.App.pickLongestChain(RemoteChain)){\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: true})\n\t\t\t\t\tserver.App.broadcast(block)\n\t\t\t\t}else {\n\t\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &\"Peer has a longer chain\"})\n\t\t\t\t}\n\t\t\t}\n\t\t}else {\n\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &\"Unauthorized\"})\n\t\t}\n\t})\n\trouter.Methods(\"POST\").Path(\"\/addPeer\").HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\tif isLocalhost(*request){\n\t\t\tbody, err := ioutil.ReadAll(request.Body)\n\t\t\tif err != nil {\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &string(err.Error())})\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpeer := Peer{}\n\t\t\tif err := json.Unmarshal(body, &peer); err != nil {\n\t\t\t\tjson.NewEncoder(writer).Encode(Success{Success: false, Error: &string(err.Error())})\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tserver.App.Peers[peer.getUrl()] = &peer\n\t\t\tserver.App.PeerAddresses[peer.Ip] = true\n\t\t\tjson.NewEncoder(writer).Encode(Success{Success: true})\n\t\t}else{\n\t\t\twriter.Write([]byte(\"Only localhost can add peers\"))\n\t\t}\n\t})\n\thttp.ListenAndServe(\":\" + getPort(), router)\n}\nfunc getPort() string{\n\tport := os.Getenv(\"PORT\")\n\tif(port == \"\"){\n\t\treturn \"8080\"\n\t}else {\n\t\treturn port\n\t}\n}\nfunc isLocalhostOrPeer(server Server, request http.Request) bool{\n\t_, isPeer := server.App.PeerAddresses[request.RemoteAddr]\n\treturn isPeer || isLocalhost(request)\n}\nfunc isLocalhost(req http.Request) bool{\n\tfmt.Println(req.RemoteAddr)\n\treturn strings.Contains(req.RemoteAddr, \"127.0.0.1\") || strings.Contains(req.RemoteAddr, \"[::1]\")\/\/::1 is ipv6\n}\n\ntype Success struct {\n\tSuccess bool `json:\"success\"`\n\tError *string `json:\"error\"`\n}\n\nfunc str(str string) *string{\n\treturn &str\n}<|endoftext|>"}
{"text":"<commit_before>package containeranalysis\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\tcontaineranalysisapi \"cloud.google.com\/go\/containeranalysis\/apiv1\"\n\tgrafeasv1 \"cloud.google.com\/go\/grafeas\/apiv1\"\n\n\t\"github.com\/docker\/distribution\/reference\"\n\t\"google.golang.org\/api\/iterator\"\n\tgrafeas \"google.golang.org\/genproto\/googleapis\/grafeas\/v1\"\n\n\t\"github.com\/Shopify\/voucher\"\n\t\"github.com\/Shopify\/voucher\/attestation\"\n\t\"github.com\/Shopify\/voucher\/repository\"\n\t\"github.com\/Shopify\/voucher\/signer\"\n)\n\nvar errCannotAttest = errors.New(\"cannot create attestations, keyring is empty\")\n\n\/\/ Client implements voucher.MetadataClient, connecting to containeranalysis Grafeas.\ntype Client struct {\n\tcontaineranalysis *grafeasv1.Client        \/\/ The client reference.\n\tkeyring           signer.AttestationSigner \/\/ The keyring used for signing metadata.\n\tbinauthProject    string                   \/\/ The project that Binauth Notes and Occurrences are written to.\n\timageProject      string                   \/\/ The project that image information is stored.\n}\n\n\/\/ CanAttest returns true if the client can create and sign attestations.\nfunc (g *Client) CanAttest() bool {\n\treturn nil != g.keyring\n}\n\n\/\/ NewPayloadBody returns a payload body appropriate for this MetadataClient.\nfunc (g *Client) NewPayloadBody(reference reference.Canonical) (string, error) {\n\tpayload, err := attestation.NewPayload(reference).ToString()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn payload, err\n}\n\n\/\/ AddAttestationToImage adds a new attestation with the passed Attestation\n\/\/ to the image described by ImageData.\nfunc (g *Client) AddAttestationToImage(ctx context.Context, reference reference.Canonical, attestation voucher.Attestation) (voucher.SignedAttestation, error) {\n\tif !g.CanAttest() {\n\t\treturn voucher.SignedAttestation{}, errCannotAttest\n\t}\n\n\tsignedAttestation, err := voucher.SignAttestation(g.keyring, attestation)\n\tif nil != err {\n\t\treturn voucher.SignedAttestation{}, err\n\t}\n\n\t_, err = g.containeranalysis.CreateOccurrence(\n\t\tctx,\n\t\tnewOccurrenceAttestation(\n\t\t\treference,\n\t\t\tsignedAttestation,\n\t\t\tg.binauthProject,\n\t\t),\n\t)\n\n\tif isAttestionExistsErr(err) {\n\t\terr = nil\n\n\t\tsignedAttestation.Signature = \"\"\n\t}\n\n\treturn signedAttestation, err\n}\n\n\/\/ GetAttestations returns all of the attestations associated with an image.\nfunc (g *Client) GetAttestations(ctx context.Context, reference reference.Canonical) ([]voucher.SignedAttestation, error) {\n\tfilterStr := kindFilterStr(reference, grafeas.NoteKind_ATTESTATION)\n\n\tvar attestations []voucher.SignedAttestation\n\n\tproject := projectPath(g.binauthProject)\n\treq := &grafeas.ListOccurrencesRequest{Parent: project, Filter: filterStr}\n\toccIterator := g.containeranalysis.ListOccurrences(ctx, req)\n\n\tfor {\n\t\tocc, err := occIterator.Next()\n\t\tif nil != err {\n\t\t\tif iterator.Done == err {\n\t\t\t\treturn attestations, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\tnote, err := g.containeranalysis.GetOccurrenceNote(\n\t\t\tctx,\n\t\t\t&grafeas.GetOccurrenceNoteRequest{\n\t\t\t\tName: occ.GetName(),\n\t\t\t},\n\t\t)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tname := getCheckNameFromNoteName(g.binauthProject, note.GetName())\n\n\t\tattestations = append(\n\t\t\tattestations,\n\t\t\tOccurrenceToAttestation(name, occ),\n\t\t)\n\t}\n}\n\n\/\/ GetVulnerabilities returns the detected vulnerabilities for the Image described by voucher.ImageData.\nfunc (g *Client) GetVulnerabilities(ctx context.Context, reference reference.Canonical) (vulnerabilities []voucher.Vulnerability, err error) {\n\tfilterStr := kindFilterStr(reference, grafeas.NoteKind_VULNERABILITY)\n\n\terr = pollForDiscoveries(ctx, g, reference)\n\tif nil != err {\n\t\treturn []voucher.Vulnerability{}, err\n\t}\n\n\tproject := projectPath(g.imageProject)\n\treq := &grafeas.ListOccurrencesRequest{Parent: project, Filter: filterStr}\n\toccIterator := g.containeranalysis.ListOccurrences(ctx, req)\n\n\tfor {\n\t\tvar occ *grafeas.Occurrence\n\n\t\tocc, err = occIterator.Next()\n\t\tif nil != err {\n\t\t\tif iterator.Done == err {\n\t\t\t\terr = nil\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\n\t\tvuln := OccurrenceToVulnerability(occ)\n\t\tvulnerabilities = append(vulnerabilities, vuln)\n\t}\n\n\treturn\n}\n\n\/\/ Close closes the containeranalysis Grafeas client.\nfunc (g *Client) Close() {\n\tg.containeranalysis.Close()\n}\n\n\/\/ GetBuildDetail gets the BuildDetail for the passed image.\nfunc (g *Client) GetBuildDetail(ctx context.Context, reference reference.Canonical) (repository.BuildDetail, error) {\n\tvar err error\n\n\tfilterStr := kindFilterStr(reference, grafeas.NoteKind_BUILD)\n\n\tproject := projectPath(g.imageProject)\n\treq := &grafeas.ListOccurrencesRequest{Parent: project, Filter: filterStr}\n\toccIterator := g.containeranalysis.ListOccurrences(ctx, req)\n\n\tocc, err := occIterator.Next()\n\tif err != nil {\n\t\tif err == iterator.Done {\n\t\t\terr = &voucher.NoMetadataError{\n\t\t\t\tType: voucher.VulnerabilityType,\n\t\t\t\tErr:  errNoOccurrences,\n\t\t\t}\n\t\t}\n\t\treturn repository.BuildDetail{}, err\n\t}\n\n\tif _, err := occIterator.Next(); err != iterator.Done {\n\t\treturn repository.BuildDetail{}, errors.New(\"Found multiple Grafeas occurrences for \" + reference.String())\n\t}\n\n\treturn OccurrenceToBuildDetail(occ), nil\n}\n\n\/\/ NewClient creates a new containeranalysis Grafeas Client.\nfunc NewClient(ctx context.Context, imageProject, binauthProject string, keyring signer.AttestationSigner) (*Client, error) {\n\tvar err error\n\n\tcaClient, err := containeranalysisapi.NewClient(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &Client{\n\t\tcontaineranalysis: caClient.GetGrafeasClient(),\n\t\tkeyring:           keyring,\n\t\tbinauthProject:    binauthProject,\n\t\timageProject:      imageProject,\n\t}\n\n\treturn client, nil\n}\n<commit_msg>close keyring if it's open (#95)<commit_after>package containeranalysis\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\tcontaineranalysisapi \"cloud.google.com\/go\/containeranalysis\/apiv1\"\n\tgrafeasv1 \"cloud.google.com\/go\/grafeas\/apiv1\"\n\n\t\"github.com\/docker\/distribution\/reference\"\n\t\"google.golang.org\/api\/iterator\"\n\tgrafeas \"google.golang.org\/genproto\/googleapis\/grafeas\/v1\"\n\n\t\"github.com\/Shopify\/voucher\"\n\t\"github.com\/Shopify\/voucher\/attestation\"\n\t\"github.com\/Shopify\/voucher\/repository\"\n\t\"github.com\/Shopify\/voucher\/signer\"\n)\n\nvar errCannotAttest = errors.New(\"cannot create attestations, keyring is empty\")\n\n\/\/ Client implements voucher.MetadataClient, connecting to containeranalysis Grafeas.\ntype Client struct {\n\tcontaineranalysis *grafeasv1.Client        \/\/ The client reference.\n\tkeyring           signer.AttestationSigner \/\/ The keyring used for signing metadata.\n\tbinauthProject    string                   \/\/ The project that Binauth Notes and Occurrences are written to.\n\timageProject      string                   \/\/ The project that image information is stored.\n}\n\n\/\/ CanAttest returns true if the client can create and sign attestations.\nfunc (g *Client) CanAttest() bool {\n\treturn nil != g.keyring\n}\n\n\/\/ NewPayloadBody returns a payload body appropriate for this MetadataClient.\nfunc (g *Client) NewPayloadBody(reference reference.Canonical) (string, error) {\n\tpayload, err := attestation.NewPayload(reference).ToString()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn payload, err\n}\n\n\/\/ AddAttestationToImage adds a new attestation with the passed Attestation\n\/\/ to the image described by ImageData.\nfunc (g *Client) AddAttestationToImage(ctx context.Context, reference reference.Canonical, attestation voucher.Attestation) (voucher.SignedAttestation, error) {\n\tif !g.CanAttest() {\n\t\treturn voucher.SignedAttestation{}, errCannotAttest\n\t}\n\n\tsignedAttestation, err := voucher.SignAttestation(g.keyring, attestation)\n\tif nil != err {\n\t\treturn voucher.SignedAttestation{}, err\n\t}\n\n\t_, err = g.containeranalysis.CreateOccurrence(\n\t\tctx,\n\t\tnewOccurrenceAttestation(\n\t\t\treference,\n\t\t\tsignedAttestation,\n\t\t\tg.binauthProject,\n\t\t),\n\t)\n\n\tif isAttestionExistsErr(err) {\n\t\terr = nil\n\n\t\tsignedAttestation.Signature = \"\"\n\t}\n\n\treturn signedAttestation, err\n}\n\n\/\/ GetAttestations returns all of the attestations associated with an image.\nfunc (g *Client) GetAttestations(ctx context.Context, reference reference.Canonical) ([]voucher.SignedAttestation, error) {\n\tfilterStr := kindFilterStr(reference, grafeas.NoteKind_ATTESTATION)\n\n\tvar attestations []voucher.SignedAttestation\n\n\tproject := projectPath(g.binauthProject)\n\treq := &grafeas.ListOccurrencesRequest{Parent: project, Filter: filterStr}\n\toccIterator := g.containeranalysis.ListOccurrences(ctx, req)\n\n\tfor {\n\t\tocc, err := occIterator.Next()\n\t\tif nil != err {\n\t\t\tif iterator.Done == err {\n\t\t\t\treturn attestations, nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\tnote, err := g.containeranalysis.GetOccurrenceNote(\n\t\t\tctx,\n\t\t\t&grafeas.GetOccurrenceNoteRequest{\n\t\t\t\tName: occ.GetName(),\n\t\t\t},\n\t\t)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tname := getCheckNameFromNoteName(g.binauthProject, note.GetName())\n\n\t\tattestations = append(\n\t\t\tattestations,\n\t\t\tOccurrenceToAttestation(name, occ),\n\t\t)\n\t}\n}\n\n\/\/ GetVulnerabilities returns the detected vulnerabilities for the Image described by voucher.ImageData.\nfunc (g *Client) GetVulnerabilities(ctx context.Context, reference reference.Canonical) (vulnerabilities []voucher.Vulnerability, err error) {\n\tfilterStr := kindFilterStr(reference, grafeas.NoteKind_VULNERABILITY)\n\n\terr = pollForDiscoveries(ctx, g, reference)\n\tif nil != err {\n\t\treturn []voucher.Vulnerability{}, err\n\t}\n\n\tproject := projectPath(g.imageProject)\n\treq := &grafeas.ListOccurrencesRequest{Parent: project, Filter: filterStr}\n\toccIterator := g.containeranalysis.ListOccurrences(ctx, req)\n\n\tfor {\n\t\tvar occ *grafeas.Occurrence\n\n\t\tocc, err = occIterator.Next()\n\t\tif nil != err {\n\t\t\tif iterator.Done == err {\n\t\t\t\terr = nil\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\n\t\tvuln := OccurrenceToVulnerability(occ)\n\t\tvulnerabilities = append(vulnerabilities, vuln)\n\t}\n\n\treturn\n}\n\n\/\/ Close closes the containeranalysis Grafeas client.\nfunc (g *Client) Close() {\n\tif nil != g.keyring {\n\t\t_ = g.keyring.Close()\n\t}\n\tg.containeranalysis.Close()\n}\n\n\/\/ GetBuildDetail gets the BuildDetail for the passed image.\nfunc (g *Client) GetBuildDetail(ctx context.Context, reference reference.Canonical) (repository.BuildDetail, error) {\n\tvar err error\n\n\tfilterStr := kindFilterStr(reference, grafeas.NoteKind_BUILD)\n\n\tproject := projectPath(g.imageProject)\n\treq := &grafeas.ListOccurrencesRequest{Parent: project, Filter: filterStr}\n\toccIterator := g.containeranalysis.ListOccurrences(ctx, req)\n\n\tocc, err := occIterator.Next()\n\tif err != nil {\n\t\tif err == iterator.Done {\n\t\t\terr = &voucher.NoMetadataError{\n\t\t\t\tType: voucher.VulnerabilityType,\n\t\t\t\tErr:  errNoOccurrences,\n\t\t\t}\n\t\t}\n\t\treturn repository.BuildDetail{}, err\n\t}\n\n\tif _, err := occIterator.Next(); err != iterator.Done {\n\t\treturn repository.BuildDetail{}, errors.New(\"Found multiple Grafeas occurrences for \" + reference.String())\n\t}\n\n\treturn OccurrenceToBuildDetail(occ), nil\n}\n\n\/\/ NewClient creates a new containeranalysis Grafeas Client.\nfunc NewClient(ctx context.Context, imageProject, binauthProject string, keyring signer.AttestationSigner) (*Client, error) {\n\tvar err error\n\n\tcaClient, err := containeranalysisapi.NewClient(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &Client{\n\t\tcontaineranalysis: caClient.GetGrafeasClient(),\n\t\tkeyring:           keyring,\n\t\tbinauthProject:    binauthProject,\n\t\timageProject:      imageProject,\n\t}\n\n\treturn client, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package pool\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype NextConn func() (net.Conn, error)\n\ntype limitConn struct {\n\tnet.Conn\n\t*sync.Cond\n\tlimit *uint64\n}\n\nfunc (c *limitConn) Close() error {\n\tgo func() {\n\t\tc.Cond.L.Lock()\n\t\tdefer c.Cond.L.Unlock()\n\t\t(*c.limit)++\n\t\tc.Cond.Signal()\n\t}()\n\treturn c.Conn.Close()\n}\n\nfunc PoolLimiter(next NextConn, limit uint64) NextConn {\n\tvar mu sync.Mutex\n\tcond := sync.NewCond(&mu)\n\n\treturn func() (net.Conn, error) {\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\t\tfor limit == 0 {\n\t\t\tcond.Wait()\n\t\t}\n\t\tc, err := next()\n\t\tif err == nil {\n\t\t\tlimit--\n\t\t\tc = &limitConn{\n\t\t\t\tConn:  c,\n\t\t\t\tCond:  cond,\n\t\t\t\tlimit: &limit,\n\t\t\t}\n\t\t}\n\t\treturn c, err\n\t}\n}\n\ntype Pool struct {\n\tnext NextConn\n\treqs *requests\n\tdead chan struct{}\n}\n\nfunc NewPool(next NextConn) *Pool {\n\tp := &Pool{\n\t\tnext: next,\n\t\treqs: newRequests(),\n\t\tdead: make(chan struct{}),\n\t}\n\tgo p.manage()\n\treturn p\n}\n\nvar ErrPoolClosed = errors.New(\"pool closed\")\n\nfunc (p *Pool) Get() (net.Conn, error) {\n\tif c, ok := <-p.reqs.submit(); ok {\n\t\treturn c, nil\n\t}\n\treturn nil, ErrPoolClosed\n}\n\nfunc (p *Pool) manage() {\n\tfor {\n\t\treq, ok := p.reqs.next()\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\tvar c net.Conn\n\t\terr := errors.New(\"temp error\")\n\n\t\tfor err != nil {\n\t\t\tc, err = p.next()\n\t\t\tif err != nil {\n\t\t\t\tselect {\n\t\t\t\tcase <-time.After(5 * time.Second):\n\t\t\t\tcase <-p.dead:\n\t\t\t\t\tclose(req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treq <- c\n\t}\n}\n\nfunc (p *Pool) Close() error {\n\tp.reqs.close()\n\tclose(p.dead)\n\treturn nil\n}\n\ntype requests struct {\n\tmu   sync.Mutex\n\tcond *sync.Cond\n\tdead bool\n\treqs []chan net.Conn\n}\n\nfunc newRequests() *requests {\n\tr := &requests{reqs: make([]chan net.Conn, 0)}\n\tr.cond = sync.NewCond(&r.mu)\n\treturn r\n}\n\nfunc (r *requests) submit() <-chan net.Conn {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\treq := make(chan net.Conn)\n\tif r.dead {\n\t\tclose(req)\n\t} else {\n\t\tr.reqs = append(r.reqs, req)\n\t\tr.cond.Signal()\n\t}\n\treturn req\n}\n\nfunc (r *requests) next() (req chan<- net.Conn, ok bool) {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tfor len(r.reqs) == 0 && !r.dead {\n\t\tr.cond.Wait()\n\t}\n\tif r.dead {\n\t\treturn nil, false\n\t} else {\n\t\treq, r.reqs = r.reqs[0], r.reqs[1:]\n\t\treturn req, true\n\t}\n}\n\nfunc (r *requests) close() {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.dead = true\n\tfor _, req := range r.reqs {\n\t\tclose(req)\n\t}\n\tr.reqs = nil\n\tr.cond.Broadcast()\n}\n<commit_msg>added godoc<commit_after>package pool\n\nimport (\n\t\"errors\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype NextConn func() (net.Conn, error)\n\ntype limitConn struct {\n\tnet.Conn\n\t*sync.Cond\n\tlimit *uint64\n}\n\nfunc (c *limitConn) Close() error {\n\tgo func() {\n\t\tc.Cond.L.Lock()\n\t\tdefer c.Cond.L.Unlock()\n\t\t(*c.limit)++\n\t\tc.Cond.Signal()\n\t}()\n\treturn c.Conn.Close()\n}\n\n\/\/ PoolLimiter limits the number of concurrent connections returned by next to limit\nfunc PoolLimiter(next NextConn, limit uint64) NextConn {\n\tvar mu sync.Mutex\n\tcond := sync.NewCond(&mu)\n\n\treturn func() (net.Conn, error) {\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\t\tfor limit == 0 {\n\t\t\tcond.Wait()\n\t\t}\n\t\tc, err := next()\n\t\tif err == nil {\n\t\t\tlimit--\n\t\t\tc = &limitConn{\n\t\t\t\tConn:  c,\n\t\t\t\tCond:  cond,\n\t\t\t\tlimit: &limit,\n\t\t\t}\n\t\t}\n\t\treturn c, err\n\t}\n}\n\n\/\/ Pool manages connections\ntype Pool struct {\n\tnext NextConn\n\treqs *requests\n\tdead chan struct{}\n}\n\n\/\/ NewPool creates a new Pool object for managing connections\nfunc NewPool(next NextConn) *Pool {\n\tp := &Pool{\n\t\tnext: next,\n\t\treqs: newRequests(),\n\t\tdead: make(chan struct{}),\n\t}\n\tgo p.manage()\n\treturn p\n}\n\nvar ErrPoolClosed = errors.New(\"pool closed\")\n\n\/\/ Get will return a net.Conn, it can be called concurrently\n\/\/ and calls to Get() will be returned in the order they were called.\nfunc (p *Pool) Get() (net.Conn, error) {\n\tif c, ok := <-p.reqs.submit(); ok {\n\t\treturn c, nil\n\t}\n\treturn nil, ErrPoolClosed\n}\n\nfunc (p *Pool) manage() {\n\tfor {\n\t\treq, ok := p.reqs.next()\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\n\t\tvar c net.Conn\n\t\terr := errors.New(\"temp error\")\n\n\t\tfor err != nil {\n\t\t\tc, err = p.next()\n\t\t\tif err != nil {\n\t\t\t\tselect {\n\t\t\t\tcase <-time.After(5 * time.Second):\n\t\t\t\tcase <-p.dead:\n\t\t\t\t\tclose(req)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treq <- c\n\t}\n}\n\n\/\/ Close closes the pool and cancels calls to Get()\nfunc (p *Pool) Close() error {\n\tp.reqs.close()\n\tclose(p.dead)\n\treturn nil\n}\n\ntype requests struct {\n\tmu   sync.Mutex\n\tcond *sync.Cond\n\tdead bool\n\treqs []chan net.Conn\n}\n\nfunc newRequests() *requests {\n\tr := &requests{reqs: make([]chan net.Conn, 0)}\n\tr.cond = sync.NewCond(&r.mu)\n\treturn r\n}\n\nfunc (r *requests) submit() <-chan net.Conn {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\treq := make(chan net.Conn)\n\tif r.dead {\n\t\tclose(req)\n\t} else {\n\t\tr.reqs = append(r.reqs, req)\n\t\tr.cond.Signal()\n\t}\n\treturn req\n}\n\nfunc (r *requests) next() (req chan<- net.Conn, ok bool) {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tfor len(r.reqs) == 0 && !r.dead {\n\t\tr.cond.Wait()\n\t}\n\tif r.dead {\n\t\treturn nil, false\n\t} else {\n\t\treq, r.reqs = r.reqs[0], r.reqs[1:]\n\t\treturn req, true\n\t}\n}\n\nfunc (r *requests) close() {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.dead = true\n\tfor _, req := range r.reqs {\n\t\tclose(req)\n\t}\n\tr.reqs = nil\n\tr.cond.Broadcast()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\/pprof\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/cenkalti\/log\"\n\t\"github.com\/cenkalti\/rain\/client\"\n\t\"github.com\/cenkalti\/rain\/internal\/logger\"\n\t\"github.com\/cenkalti\/rain\/resume\/torrentresume\"\n\t\"github.com\/cenkalti\/rain\/storage\/filestorage\"\n\t\"github.com\/cenkalti\/rain\/torrent\"\n\t\"github.com\/mitchellh\/go-homedir\"\n)\n\nvar (\n\tconfigPath = flag.String(\"config\", \"\", \"config path\")\n\tdest       = flag.String(\"dest\", \".\", \"where to download\")\n\tport       = flag.Int(\"port\", 0, \"listen port\")\n\tdebug      = flag.Bool(\"debug\", false, \"enable debug log\")\n\tversion    = flag.Bool(\"version\", false, \"version\")\n\tseed       = flag.Bool(\"seed\", false, \"continue seeding after dowload finishes\")\n\tcpuprofile = flag.String(\"cpuprofile\", \"\", \"write cpu profile to `file`\")\n)\n\nfunc main() {\n\tflag.Parse()\n\tif *cpuprofile != \"\" {\n\t\tf, err := os.Create(*cpuprofile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"could not create CPU profile: \", err)\n\t\t}\n\t\tif err := pprof.StartCPUProfile(f); err != nil {\n\t\t\tlog.Fatal(\"could not start CPU profile: \", err)\n\t\t}\n\t\tdefer pprof.StopCPUProfile()\n\t}\n\tif *version {\n\t\tfmt.Println(torrent.Version)\n\t\treturn\n\t}\n\targs := flag.Args()\n\tif len(args) == 0 {\n\t\t_, _ = fmt.Fprintln(os.Stderr, \"Give a torrent file as first argument!\")\n\t\tos.Exit(1)\n\t}\n\tif *debug {\n\t\tlogger.SetLogLevel(log.DEBUG)\n\t}\n\tcfg := client.NewConfig()\n\tif *configPath != \"\" {\n\t\tcp, err := homedir.Expand(*configPath)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\terr = cfg.LoadFile(cp)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tsto, err := filestorage.New(*dest)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tres, err := torrentresume.New(\"rain.resume\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar t *torrent.Torrent\n\tif strings.HasPrefix(args[0], \"magnet:\") {\n\t\tt, err = torrent.DownloadMagnet(args[0], *port, sto, res)\n\t} else {\n\t\tf, err2 := os.Open(args[0])\n\t\tif err2 != nil {\n\t\t\tlog.Fatal(err2)\n\t\t}\n\t\tt, err = torrent.DownloadTorrent(f, *port, sto, res)\n\t\t_ = f.Close()\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tsigC := make(chan os.Signal, 1)\n\tsignal.Notify(sigC, syscall.SIGINT, syscall.SIGTERM)\nLOOP:\n\tfor {\n\t\tselect {\n\t\tcase <-sigC:\n\t\t\tbreak LOOP\n\t\tcase <-t.NotifyComplete():\n\t\t\tif !*seed {\n\t\t\t\tbreak LOOP\n\t\t\t}\n\t\tcase err = <-t.NotifyError():\n\t\t\tlog.Error(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\terr = t.Close()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>fix cli<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\/pprof\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/cenkalti\/log\"\n\t\"github.com\/cenkalti\/rain\/client\"\n\t\"github.com\/cenkalti\/rain\/internal\/logger\"\n\trainversion \"github.com\/cenkalti\/rain\/internal\/version\"\n\t\"github.com\/cenkalti\/rain\/resume\/torrentresume\"\n\t\"github.com\/cenkalti\/rain\/storage\/filestorage\"\n\t\"github.com\/cenkalti\/rain\/torrent\"\n\t\"github.com\/mitchellh\/go-homedir\"\n)\n\nvar (\n\tconfigPath = flag.String(\"config\", \"\", \"config path\")\n\tdest       = flag.String(\"dest\", \".\", \"where to download\")\n\tport       = flag.Int(\"port\", 0, \"listen port\")\n\tdebug      = flag.Bool(\"debug\", false, \"enable debug log\")\n\tversion    = flag.Bool(\"version\", false, \"version\")\n\tseed       = flag.Bool(\"seed\", false, \"continue seeding after dowload finishes\")\n\tcpuprofile = flag.String(\"cpuprofile\", \"\", \"write cpu profile to `file`\")\n)\n\nfunc main() {\n\tflag.Parse()\n\tif *cpuprofile != \"\" {\n\t\tf, err := os.Create(*cpuprofile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"could not create CPU profile: \", err)\n\t\t}\n\t\tif err := pprof.StartCPUProfile(f); err != nil {\n\t\t\tlog.Fatal(\"could not start CPU profile: \", err)\n\t\t}\n\t\tdefer pprof.StopCPUProfile()\n\t}\n\tif *version {\n\t\tfmt.Println(rainversion.Version)\n\t\treturn\n\t}\n\targs := flag.Args()\n\tif len(args) == 0 {\n\t\t_, _ = fmt.Fprintln(os.Stderr, \"Give a torrent file as first argument!\")\n\t\tos.Exit(1)\n\t}\n\tif *debug {\n\t\tlogger.SetLogLevel(log.DEBUG)\n\t}\n\tcfg := client.NewConfig()\n\tif *configPath != \"\" {\n\t\tcp, err := homedir.Expand(*configPath)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\terr = cfg.LoadFile(cp)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\tsto, err := filestorage.New(*dest)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tres, err := torrentresume.New(\"rain.resume\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar t *torrent.Torrent\n\tif strings.HasPrefix(args[0], \"magnet:\") {\n\t\tt, err = torrent.DownloadMagnet(args[0], *port, sto, res)\n\t} else {\n\t\tf, err2 := os.Open(args[0])\n\t\tif err2 != nil {\n\t\t\tlog.Fatal(err2)\n\t\t}\n\t\tt, err = torrent.DownloadTorrent(f, *port, sto, res)\n\t\t_ = f.Close()\n\t}\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tsigC := make(chan os.Signal, 1)\n\tsignal.Notify(sigC, syscall.SIGINT, syscall.SIGTERM)\nLOOP:\n\tfor {\n\t\tselect {\n\t\tcase <-sigC:\n\t\t\tbreak LOOP\n\t\tcase <-t.NotifyComplete():\n\t\t\tif !*seed {\n\t\t\t\tbreak LOOP\n\t\t\t}\n\t\tcase err = <-t.NotifyError():\n\t\t\tlog.Error(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n\tt.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>package tchannel\n\nimport (\n\t\"math\/rand\"\n\t\"sync\"\n)\n\n\/\/ lockedSource allows a random number generator to be used by multiple goroutines concurrently.\n\/\/ The code is very similar to math\/rand.lockedSource, which is unfortunately not exposed.\ntype lockedSource struct {\n\tmut sync.Mutex\n\tsrc rand.Source\n}\n\n\/\/ NewRand returns a rand.Rand that is threadsafe.\nfunc NewRand(seed int64) *rand.Rand {\n\treturn rand.New(&lockedSource{src: rand.NewSource(seed)})\n}\n\nfunc (r *lockedSource) Int63() (n int64) {\n\tr.mut.Lock()\n\tn = r.src.Int63()\n\tr.mut.Unlock()\n\treturn\n}\n\nfunc (r *lockedSource) Seed(seed int64) {\n\tr.mut.Lock()\n\tr.src.Seed(seed)\n\tr.mut.Unlock()\n}\n<commit_msg>Add copyright<commit_after>package tchannel\n\n\/\/ Copyright (c) 2015 Uber Technologies, Inc.\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\nimport (\n\t\"math\/rand\"\n\t\"sync\"\n)\n\n\/\/ lockedSource allows a random number generator to be used by multiple goroutines concurrently.\n\/\/ The code is very similar to math\/rand.lockedSource, which is unfortunately not exposed.\ntype lockedSource struct {\n\tmut sync.Mutex\n\tsrc rand.Source\n}\n\n\/\/ NewRand returns a rand.Rand that is threadsafe.\nfunc NewRand(seed int64) *rand.Rand {\n\treturn rand.New(&lockedSource{src: rand.NewSource(seed)})\n}\n\nfunc (r *lockedSource) Int63() (n int64) {\n\tr.mut.Lock()\n\tn = r.src.Int63()\n\tr.mut.Unlock()\n\treturn\n}\n\nfunc (r *lockedSource) Seed(seed int64) {\n\tr.mut.Lock()\n\tr.src.Seed(seed)\n\tr.mut.Unlock()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n  \"github.com\/ricallinson\/forgery\"\n  \"github.com\/spacedock-io\/index\/models\"\n)\n\nfunc CreateRepo(req *f.Request, res *f.Response, next func()) {\n  ns := req.Params[\"namespace\"]\n  repo := req.Params[\"repo\"]\n\n  images := req.Map[\"json\"]\n\n  r := &models.Repo{}\n  ts, err := r.Create(repo, ns, \"1\", req.Map[\"_uid\"].(int64), images.([]interface{}))\n  if err != nil {\n    res.Send(err.Error(), 400)\n  }\n\n  res.Set(\"X-Docker-Token\", ts)\n  res.Set(\"WWW-Authenticate\", \"Token \" + ts)\n  res.Set(\"X-Docker-Endpoints\", \"reg22.spacedock.io, reg41.spacedock.io\")\n\n  res.Send(\"Created\", 200)\n}\n\nfunc DeleteRepo(req *f.Request, res *f.Response, next func()) {\n  res.Send(\"Not implemented yet.\")\n}\n\nfunc GetUserImage(req *f.Request, res *f.Response, next func()) {\n  res.Send(\"Not implemented yet.\")\n}\n\nfunc RepoAuth(req *f.Request, res *f.Response, next func()) {\n  res.Send(200)\n}\n\nfunc UpdateUserImage(req *f.Request, res *f.Response, next func()) {\n  res.Send(\"Not implemented yet.\")\n}\n<commit_msg>GET user repo images now works<commit_after>package main\n\nimport (\n  \"encoding\/json\"\n  \"github.com\/ricallinson\/forgery\"\n  \"github.com\/spacedock-io\/index\/models\"\n)\n\nfunc CreateRepo(req *f.Request, res *f.Response, next func()) {\n  ns := req.Params[\"namespace\"]\n  repo := req.Params[\"repo\"]\n\n  images := req.Map[\"json\"]\n\n  r := &models.Repo{}\n  ts, err := r.Create(repo, ns, \"1\", req.Map[\"_uid\"].(int64), images.([]interface{}))\n  if err != nil {\n    res.Send(err.Error(), 400)\n  }\n\n  res.Set(\"X-Docker-Token\", ts)\n  res.Set(\"WWW-Authenticate\", \"Token \" + ts)\n  res.Set(\"X-Docker-Endpoints\", \"reg22.spacedock.io, reg41.spacedock.io\")\n\n  res.Send(\"Created\", 200)\n}\n\nfunc DeleteRepo(req *f.Request, res *f.Response, next func()) {\n  res.Send(\"Not implemented yet.\")\n}\n\nfunc GetUserImage(req *f.Request, res *f.Response, next func()) {\n  repo := req.Params[\"repo\"]\n  ns := req.Params[\"ns\"]\n\n  r, err := models.GetRepo(ns, repo)\n  if err != nil {\n    res.Send(err.Error(), 400)\n  }\n\n  images, e := r.GetImages()\n  if e != nil {\n    res.Send(e.Error(), 400)\n  }\n\n  j, jsonErr := json.Marshal(images)\n  if jsonErr != nil {\n    res.Send(\"Error returning data\", 400)\n  }\n  res.Send(string(j), 200)\n}\n\nfunc RepoAuth(req *f.Request, res *f.Response, next func()) {\n  res.Send(200)\n}\n\nfunc UpdateUserImage(req *f.Request, res *f.Response, next func()) {\n  res.Send(\"Not implemented yet.\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n  \"encoding\/json\"\n  \"github.com\/ricallinson\/forgery\"\n  \"github.com\/spacedock-io\/index\/models\"\n)\n\nfunc CreateRepo(req *f.Request, res *f.Response, next func()) {\n  images := req.Map[\"json\"]\n  u := req.Map[\"_user\"].(*models.User)\n\n  r := &models.Repo{\n    Namespace: req.Params[\"namespace\"],\n    Name: req.Params[\"repo\"],\n  }\n\n  ts, err := r.Create(\"1\", u, images.([]interface{}))\n  if err != nil {\n    res.Send(err.Error(), 400)\n  }\n\n  res.Set(\"X-Docker-Token\", ts)\n  res.Set(\"WWW-Authenticate\", \"Token \" + ts)\n  res.Set(\"X-Docker-Endpoints\", \"staging.spacedock.io:8081\")\n\n  res.Send(\"\\\"\\\"\", 200)\n}\n\nfunc DeleteRepo(req *f.Request, res *f.Response, next func()) {\n  namespace := req.Params[\"namespace\"]\n  repo := req.Params[\"repo\"]\n\n  r, err := models.GetRepo(namespace, repo)\n  if err != nil {\n    res.Send(err.Error(), 400)\n    return\n  }\n\n  if !r.Deleted {\n    ts, err := r.MarkAsDeleted(req.Map[\"_uid\"].(int64))\n    if err != nil {\n      res.Send(err.Error(), 400)\n      return\n    }\n\n    res.Set(\"X-Docker-Token\", ts)\n    res.Set(\"WWW-Authenticate\", \"Token \" + ts)\n    res.Set(\"X-Docker-Endpoints\", \"staging.spacedock.io:8081\")\n\n    res.Send(202)\n    return\n  }\n\n  err = r.Delete()\n  if err != nil {\n    res.Send(err.Error(), 400)\n    return\n  }\n\n  res.Send(200)\n}\n\nfunc GetUserImage(req *f.Request, res *f.Response, next func()) {\n  repo := req.Params[\"repo\"]\n  ns := req.Params[\"ns\"]\n\n  r, err := models.GetRepo(ns, repo)\n  if err != nil {\n    res.Send(err.Error(), 400)\n  }\n\n  images, e := r.GetImages()\n  if e != nil {\n    res.Send(e.Error(), 400)\n  }\n\n  j, jsonErr := json.Marshal(images)\n  if jsonErr != nil {\n    res.Send(\"Error returning data\", 400)\n  }\n  res.Send(string(j), 200)\n}\n\nfunc RepoAuth(req *f.Request, res *f.Response, next func()) {\n  res.Send(200)\n}\n\nfunc UpdateUserImage(req *f.Request, res *f.Response, next func()) {\n  repo := req.Params[\"repo\"]\n  ns := req.Params[\"namespace\"]\n  json := req.Map[\"json\"].([]interface{})\n\n  r, err := models.GetRepo(ns, repo)\n  if err != nil {\n    res.Send(err.Error(), 400)\n  }\n\n  er := r.UpdateImages(json)\n  if er != nil {\n    res.Send(err.Error(), 400)\n  }\n\n  res.Send(\"\\\"\\\"\", 204)\n}\n<commit_msg>Let's try a mix of 201 and 200<commit_after>package main\n\nimport (\n  \"encoding\/json\"\n  \"github.com\/ricallinson\/forgery\"\n  \"github.com\/spacedock-io\/index\/models\"\n)\n\nfunc CreateRepo(req *f.Request, res *f.Response, next func()) {\n  images := req.Map[\"json\"]\n  u := req.Map[\"_user\"].(*models.User)\n\n  r := &models.Repo{\n    Namespace: req.Params[\"namespace\"],\n    Name: req.Params[\"repo\"],\n  }\n\n  ts, err := r.Create(\"1\", u, images.([]interface{}))\n  if err == models.AlreadyExistsErr {\n    res.Send(\"\\\"\\\"\", 200)\n    return\n  } else if err != nil {\n    res.Send(err.Error(), 400)\n    return\n  }\n\n  res.Set(\"X-Docker-Token\", ts)\n  res.Set(\"WWW-Authenticate\", \"Token \" + ts)\n  res.Set(\"X-Docker-Endpoints\", \"staging.spacedock.io:8081\")\n\n  res.Send(\"\\\"\\\"\", 201)\n}\n\nfunc DeleteRepo(req *f.Request, res *f.Response, next func()) {\n  namespace := req.Params[\"namespace\"]\n  repo := req.Params[\"repo\"]\n\n  r, err := models.GetRepo(namespace, repo)\n  if err != nil {\n    res.Send(err.Error(), 400)\n    return\n  }\n\n  if !r.Deleted {\n    ts, err := r.MarkAsDeleted(req.Map[\"_uid\"].(int64))\n    if err != nil {\n      res.Send(err.Error(), 400)\n      return\n    }\n\n    res.Set(\"X-Docker-Token\", ts)\n    res.Set(\"WWW-Authenticate\", \"Token \" + ts)\n    res.Set(\"X-Docker-Endpoints\", \"staging.spacedock.io:8081\")\n\n    res.Send(202)\n    return\n  }\n\n  err = r.Delete()\n  if err != nil {\n    res.Send(err.Error(), 400)\n    return\n  }\n\n  res.Send(200)\n}\n\nfunc GetUserImage(req *f.Request, res *f.Response, next func()) {\n  repo := req.Params[\"repo\"]\n  ns := req.Params[\"ns\"]\n\n  r, err := models.GetRepo(ns, repo)\n  if err != nil {\n    res.Send(err.Error(), 400)\n  }\n\n  images, e := r.GetImages()\n  if e != nil {\n    res.Send(e.Error(), 400)\n  }\n\n  j, jsonErr := json.Marshal(images)\n  if jsonErr != nil {\n    res.Send(\"Error returning data\", 400)\n  }\n  res.Send(string(j), 200)\n}\n\nfunc RepoAuth(req *f.Request, res *f.Response, next func()) {\n  res.Send(200)\n}\n\nfunc UpdateUserImage(req *f.Request, res *f.Response, next func()) {\n  repo := req.Params[\"repo\"]\n  ns := req.Params[\"namespace\"]\n  json := req.Map[\"json\"].([]interface{})\n\n  r, err := models.GetRepo(ns, repo)\n  if err != nil {\n    res.Send(err.Error(), 400)\n  }\n\n  er := r.UpdateImages(json)\n  if er != nil {\n    res.Send(err.Error(), 400)\n  }\n\n  res.Send(\"\\\"\\\"\", 204)\n}\n<|endoftext|>"}
{"text":"<commit_before>package dnsr\n\nvar root = `\n;       This file holds the information on root name servers needed to \n;       initialize cache of Internet domain name servers\n;       (e.g. reference this file in the \"cache  .  <file>\"\n;       configuration file of BIND domain name servers). \n; \n;       This file is made available by InterNIC \n;       under anonymous FTP as\n;           file                \/domain\/named.cache \n;           on server           FTP.INTERNIC.NET\n;       -OR-                    RS.INTERNIC.NET\n; \n;       last update:     October 23, 2017 \n;       related version of root zone:     2017102301\n; \n; FORMERLY NS.INTERNIC.NET \n;\n.                        3600000      NS    A.ROOT-SERVERS.NET.\nA.ROOT-SERVERS.NET.      3600000      A     198.41.0.4\nA.ROOT-SERVERS.NET.      3600000      AAAA  2001:503:ba3e::2:30\n; \n; FORMERLY NS1.ISI.EDU \n;\n.                        3600000      NS    B.ROOT-SERVERS.NET.\nB.ROOT-SERVERS.NET.      3600000      A     192.228.79.201\nB.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:200::b\n; \n; FORMERLY C.PSI.NET \n;\n.                        3600000      NS    C.ROOT-SERVERS.NET.\nC.ROOT-SERVERS.NET.      3600000      A     192.33.4.12\nC.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:2::c\n; \n; FORMERLY TERP.UMD.EDU \n;\n.                        3600000      NS    D.ROOT-SERVERS.NET.\nD.ROOT-SERVERS.NET.      3600000      A     199.7.91.13\nD.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:2d::d\n; \n; FORMERLY NS.NASA.GOV\n;\n.                        3600000      NS    E.ROOT-SERVERS.NET.\nE.ROOT-SERVERS.NET.      3600000      A     192.203.230.10\nE.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:a8::e\n; \n; FORMERLY NS.ISC.ORG\n;\n.                        3600000      NS    F.ROOT-SERVERS.NET.\nF.ROOT-SERVERS.NET.      3600000      A     192.5.5.241\nF.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:2f::f\n; \n; FORMERLY NS.NIC.DDN.MIL\n;\n.                        3600000      NS    G.ROOT-SERVERS.NET.\nG.ROOT-SERVERS.NET.      3600000      A     192.112.36.4\nG.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:12::d0d\n; \n; FORMERLY AOS.ARL.ARMY.MIL\n;\n.                        3600000      NS    H.ROOT-SERVERS.NET.\nH.ROOT-SERVERS.NET.      3600000      A     198.97.190.53\nH.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:1::53\n; \n; FORMERLY NIC.NORDU.NET\n;\n.                        3600000      NS    I.ROOT-SERVERS.NET.\nI.ROOT-SERVERS.NET.      3600000      A     192.36.148.17\nI.ROOT-SERVERS.NET.      3600000      AAAA  2001:7fe::53\n; \n; OPERATED BY VERISIGN, INC.\n;\n.                        3600000      NS    J.ROOT-SERVERS.NET.\nJ.ROOT-SERVERS.NET.      3600000      A     192.58.128.30\nJ.ROOT-SERVERS.NET.      3600000      AAAA  2001:503:c27::2:30\n; \n; OPERATED BY RIPE NCC\n;\n.                        3600000      NS    K.ROOT-SERVERS.NET.\nK.ROOT-SERVERS.NET.      3600000      A     193.0.14.129\nK.ROOT-SERVERS.NET.      3600000      AAAA  2001:7fd::1\n; \n; OPERATED BY ICANN\n;\n.                        3600000      NS    L.ROOT-SERVERS.NET.\nL.ROOT-SERVERS.NET.      3600000      A     199.7.83.42\nL.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:9f::42\n; \n; OPERATED BY WIDE\n;\n.                        3600000      NS    M.ROOT-SERVERS.NET.\nM.ROOT-SERVERS.NET.      3600000      A     202.12.27.33\nM.ROOT-SERVERS.NET.      3600000      AAAA  2001:dc3::35\n; End of file`\n<commit_msg>autopull: 2017-10-24T23:30:17Z<commit_after>package dnsr\n\nvar root = `\n;       This file holds the information on root name servers needed to \n;       initialize cache of Internet domain name servers\n;       (e.g. reference this file in the \"cache  .  <file>\"\n;       configuration file of BIND domain name servers). \n; \n;       This file is made available by InterNIC \n;       under anonymous FTP as\n;           file                \/domain\/named.cache \n;           on server           FTP.INTERNIC.NET\n;       -OR-                    RS.INTERNIC.NET\n; \n;       last update:     October 24, 2017 \n;       related version of root zone:     2017102400\n; \n; FORMERLY NS.INTERNIC.NET \n;\n.                        3600000      NS    A.ROOT-SERVERS.NET.\nA.ROOT-SERVERS.NET.      3600000      A     198.41.0.4\nA.ROOT-SERVERS.NET.      3600000      AAAA  2001:503:ba3e::2:30\n; \n; FORMERLY NS1.ISI.EDU \n;\n.                        3600000      NS    B.ROOT-SERVERS.NET.\nB.ROOT-SERVERS.NET.      3600000      A     199.9.14.201\nB.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:200::b\n; \n; FORMERLY C.PSI.NET \n;\n.                        3600000      NS    C.ROOT-SERVERS.NET.\nC.ROOT-SERVERS.NET.      3600000      A     192.33.4.12\nC.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:2::c\n; \n; FORMERLY TERP.UMD.EDU \n;\n.                        3600000      NS    D.ROOT-SERVERS.NET.\nD.ROOT-SERVERS.NET.      3600000      A     199.7.91.13\nD.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:2d::d\n; \n; FORMERLY NS.NASA.GOV\n;\n.                        3600000      NS    E.ROOT-SERVERS.NET.\nE.ROOT-SERVERS.NET.      3600000      A     192.203.230.10\nE.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:a8::e\n; \n; FORMERLY NS.ISC.ORG\n;\n.                        3600000      NS    F.ROOT-SERVERS.NET.\nF.ROOT-SERVERS.NET.      3600000      A     192.5.5.241\nF.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:2f::f\n; \n; FORMERLY NS.NIC.DDN.MIL\n;\n.                        3600000      NS    G.ROOT-SERVERS.NET.\nG.ROOT-SERVERS.NET.      3600000      A     192.112.36.4\nG.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:12::d0d\n; \n; FORMERLY AOS.ARL.ARMY.MIL\n;\n.                        3600000      NS    H.ROOT-SERVERS.NET.\nH.ROOT-SERVERS.NET.      3600000      A     198.97.190.53\nH.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:1::53\n; \n; FORMERLY NIC.NORDU.NET\n;\n.                        3600000      NS    I.ROOT-SERVERS.NET.\nI.ROOT-SERVERS.NET.      3600000      A     192.36.148.17\nI.ROOT-SERVERS.NET.      3600000      AAAA  2001:7fe::53\n; \n; OPERATED BY VERISIGN, INC.\n;\n.                        3600000      NS    J.ROOT-SERVERS.NET.\nJ.ROOT-SERVERS.NET.      3600000      A     192.58.128.30\nJ.ROOT-SERVERS.NET.      3600000      AAAA  2001:503:c27::2:30\n; \n; OPERATED BY RIPE NCC\n;\n.                        3600000      NS    K.ROOT-SERVERS.NET.\nK.ROOT-SERVERS.NET.      3600000      A     193.0.14.129\nK.ROOT-SERVERS.NET.      3600000      AAAA  2001:7fd::1\n; \n; OPERATED BY ICANN\n;\n.                        3600000      NS    L.ROOT-SERVERS.NET.\nL.ROOT-SERVERS.NET.      3600000      A     199.7.83.42\nL.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:9f::42\n; \n; OPERATED BY WIDE\n;\n.                        3600000      NS    M.ROOT-SERVERS.NET.\nM.ROOT-SERVERS.NET.      3600000      A     202.12.27.33\nM.ROOT-SERVERS.NET.      3600000      AAAA  2001:dc3::35\n; End of file`\n<|endoftext|>"}
{"text":"<commit_before>package sqlutil\n\nimport (\n\t\"database\/sql\"\n\t\"strings\"\n)\n\n\/\/ Creates a result holder for a query result as an array of raw bytes\nfunc ResultHolder(rows *sql.Rows) []interface{} {\n\tcols, _ := rows.Columns()\n\tl := len(cols)\n\tresult := make([]interface{}, l, l)\n\tfor i, _ := range cols {\n\t\tresult[i] = new(sql.RawBytes)\n\t}\n\treturn result\n}\n\ntype rawResult map[string][]byte\n\n\/\/ Converts a query results row for each row resultt as a map of column to raw bytes\nfunc RawResultMap(rows *sql.Rows) []rawResult {\n\tcols, _ := rows.Columns()\n\tresult := ResultHolder(rows)\n\tresults := make([]rawResult, 0)\n\tc := 0\n\tfor rows.Next() {\n\t\tc++\n\t\tresultMap := make(map[string][]byte)\n\t\trows.Scan(result...)\n\t\tfor i, v := range result {\n\t\t\tf := v.(*sql.RawBytes)\n\t\t\tresultMap[cols[i]] = (*f)[:]\n\t\t}\n\t\tresults = append(results, resultMap)\n\t}\n\n\treturn results\n}\n<commit_msg>removed an unused import<commit_after>package sqlutil\n\nimport (\n\t\"database\/sql\"\n)\n\n\/\/ Creates a result holder for a query result as an array of raw bytes\nfunc ResultHolder(rows *sql.Rows) []interface{} {\n\tcols, _ := rows.Columns()\n\tl := len(cols)\n\tresult := make([]interface{}, l, l)\n\tfor i, _ := range cols {\n\t\tresult[i] = new(sql.RawBytes)\n\t}\n\treturn result\n}\n\ntype rawResult map[string][]byte\n\n\/\/ Converts a query results row for each row resultt as a map of column to raw bytes\nfunc RawResultMap(rows *sql.Rows) []rawResult {\n\tcols, _ := rows.Columns()\n\tresult := ResultHolder(rows)\n\tresults := make([]rawResult, 0)\n\tc := 0\n\tfor rows.Next() {\n\t\tc++\n\t\tresultMap := make(map[string][]byte)\n\t\trows.Scan(result...)\n\t\tfor i, v := range result {\n\t\t\tf := v.(*sql.RawBytes)\n\t\t\tresultMap[cols[i]] = (*f)[:]\n\t\t}\n\t\tresults = append(results, resultMap)\n\t}\n\n\treturn results\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"github.com\/codegangsta\/cli\"\n)\n\nfunc assert(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc stringInSlice(a string, list []string) bool {\n\tfor _, b := range list {\n\t\tif b == a {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ RunCommand runs cmd on file\nfunc RunCommand(cmd string, path string) string {\n\n\tcmdOut, err := exec.Command(cmd, path).Output()\n\tassert(err)\n\n\treturn string(cmdOut)\n}\n\n\/\/ ParseExiftoolOutput convert exiftool output into JSON\nfunc ParseExiftoolOutput(exifout string) []byte {\n\n\tvar ignoreTags = []string{\n\t\t\"Directory\",\n\t\t\"File Name\",\n\t\t\"File Permissions\",\n\t\t\"File Modification Date\/Time\",\n\t}\n\n\texifJSON := make(map[string]map[string]string)\n\tlines := strings.Split(exifout, \"\\n\")\n\tdatas := make(map[string]string, len(lines))\n\n\tfor _, line := range lines {\n\t\tkeyvalue := strings.Split(line, \":\")\n\t\tif len(keyvalue) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif !stringInSlice(strings.TrimSpace(keyvalue[0]), ignoreTags) {\n\t\t\tdatas[strings.TrimSpace(keyvalue[0])] = strings.TrimSpace(keyvalue[1])\n\t\t}\n\t}\n\n\texifJSON[\"exiftool\"] = datas\n\tjsonExif, err := json.Marshal(exifJSON)\n\tassert(err)\n\n\treturn jsonExif\n}\n\n\/\/ ParseSsdeepOutput convert ssdeep output into JSON\nfunc ParseSsdeepOutput(ssdout string) []byte {\n\n\tdatas := make(map[string]string, 1)\n\t\/\/ Break output into lines\n\tlines := strings.Split(ssdout, \"\\n\")\n\t\/\/ Break second line into hash and path\n\thashAndPath := strings.Split(lines[1], \",\")\n\t\/\/ Add hash to map\n\tdatas[\"ssdeep\"] = strings.TrimSpace(hashAndPath[0])\n\n\tjsonSsdeep, err := json.Marshal(datas)\n\tassert(err)\n\n\treturn jsonSsdeep\n}\n\n\/\/ ParseTRiDOutput convert trid output into JSON\nfunc ParseTRiDOutput(tridout string) []byte {\n\tlines := strings.Split(tridout, \"\\n\")\n\tlines = lines[5:]\n\n\t\/\/ fmt.Println(lines)\n\n\tdatas := make(map[string][]string, 1)\n\tj, err := json.Marshal(datas)\n\tassert(err)\n\n\treturn j\n}\n\nfunc main() {\n\t\/\/ argPath := os.Args[1]\n\tapp := cli.NewApp()\n\tapp.Name = \"greet\"\n\tapp.Usage = \"fight the loneliness!\"\n\tapp.Action = func(c *cli.Context) {\n\t\tpath := c.Args().First()\n\t\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\t\tassert(err)\n\t\t}\n\t\tssdeepJSON := ParseSsdeepOutput(RunCommand(\"ssdeep\", path))\n\t\ttridJSON := ParseTRiDOutput(RunCommand(\"trid\", path))\n\t\texiftoolJSON := ParseExiftoolOutput(RunCommand(\"exiftool\", path))\n\t\tfmt.Println(string(ssdeepJSON))\n\t\tfmt.Println(string(tridJSON))\n\t\tfmt.Println(string(exiftoolJSON))\n\t}\n\n\tapp.Run(os.Args)\n}\n<commit_msg>get rid of codegangsta\/cli<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n)\n\nfunc assert(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc stringInSlice(a string, list []string) bool {\n\tfor _, b := range list {\n\t\tif b == a {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ RunCommand runs cmd on file\nfunc RunCommand(cmd string, path string) string {\n\n\tcmdOut, err := exec.Command(cmd, path).Output()\n\tassert(err)\n\n\treturn string(cmdOut)\n}\n\n\/\/ ParseExiftoolOutput convert exiftool output into JSON\nfunc ParseExiftoolOutput(exifout string) []byte {\n\n\tvar ignoreTags = []string{\n\t\t\"Directory\",\n\t\t\"File Name\",\n\t\t\"File Permissions\",\n\t\t\"File Modification Date\/Time\",\n\t}\n\n\texifJSON := make(map[string]map[string]string)\n\tlines := strings.Split(exifout, \"\\n\")\n\tdatas := make(map[string]string, len(lines))\n\n\tfor _, line := range lines {\n\t\tkeyvalue := strings.Split(line, \":\")\n\t\tif len(keyvalue) != 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif !stringInSlice(strings.TrimSpace(keyvalue[0]), ignoreTags) {\n\t\t\tdatas[strings.TrimSpace(keyvalue[0])] = strings.TrimSpace(keyvalue[1])\n\t\t}\n\t}\n\n\texifJSON[\"exiftool\"] = datas\n\tjsonExif, err := json.Marshal(exifJSON)\n\tassert(err)\n\n\treturn jsonExif\n}\n\n\/\/ ParseSsdeepOutput convert ssdeep output into JSON\nfunc ParseSsdeepOutput(ssdout string) []byte {\n\n\tdatas := make(map[string]string, 1)\n\t\/\/ Break output into lines\n\tlines := strings.Split(ssdout, \"\\n\")\n\t\/\/ Break second line into hash and path\n\thashAndPath := strings.Split(lines[1], \",\")\n\t\/\/ Add hash to map\n\tdatas[\"ssdeep\"] = strings.TrimSpace(hashAndPath[0])\n\n\tjsonSsdeep, err := json.Marshal(datas)\n\tassert(err)\n\n\treturn jsonSsdeep\n}\n\n\/\/ ParseTRiDOutput convert trid output into JSON\nfunc ParseTRiDOutput(tridout string) []byte {\n\tlines := strings.Split(tridout, \"\\n\")\n\tlines = lines[5:]\n\n\t\/\/ fmt.Println(lines)\n\n\tdatas := make(map[string][]string, 1)\n\tj, err := json.Marshal(datas)\n\tassert(err)\n\n\treturn j\n}\n\nfunc main() {\n\tpath := os.Args[1]\n\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\tassert(err)\n\t}\n\tssdeepJSON := ParseSsdeepOutput(RunCommand(\"ssdeep\", path))\n\ttridJSON := ParseTRiDOutput(RunCommand(\"trid\", path))\n\texiftoolJSON := ParseExiftoolOutput(RunCommand(\"exiftool\", path))\n\tfmt.Println(string(ssdeepJSON))\n\tfmt.Println(string(tridJSON))\n\tfmt.Println(string(exiftoolJSON))\n}\n<|endoftext|>"}
{"text":"<commit_before>package gomail\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/mail\"\n)\n\n\/\/ Sender is the interface that wraps the Send method.\n\/\/\n\/\/ Send sends an email to the given addresses.\ntype Sender interface {\n\tSend(from string, to []string, msg io.WriterTo) error\n}\n\n\/\/ SendCloser is the interface that groups the Send and Close methods.\ntype SendCloser interface {\n\tSender\n\tClose() error\n}\n\n\/\/ A SendFunc is a function that sends emails to the given adresses.\n\/\/\n\/\/ The SendFunc type is an adapter to allow the use of ordinary functions as\n\/\/ email senders. If f is a function with the appropriate signature, SendFunc(f)\n\/\/ is a Sender object that calls f.\ntype SendFunc func(from string, to []string, msg io.WriterTo) error\n\n\/\/ Send calls f(from, to, msg).\nfunc (f SendFunc) Send(from string, to []string, msg io.WriterTo) error {\n\treturn f(from, to, msg)\n}\n\n\/\/ Send sends emails using the given Sender.\nfunc Send(s Sender, msg ...*Message) error {\n\tfor i, m := range msg {\n\t\tif err := send(s, m); err != nil {\n\t\t\treturn fmt.Errorf(\"gomail: could not send email %d: %v\", i+1, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc send(s Sender, m *Message) error {\n\tfrom, err := m.getFrom()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tto, err := m.getRecipients()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := s.Send(from, to, m); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *Message) getFrom() (string, error) {\n\tfrom := m.header[\"Sender\"]\n\tif len(from) == 0 {\n\t\tfrom = m.header[\"From\"]\n\t\tif len(from) == 0 {\n\t\t\treturn \"\", errors.New(`gomail: invalid message, \"From\" field is absent`)\n\t\t}\n\t}\n\n\treturn parseAddress(from[0])\n}\n\nfunc (m *Message) getRecipients() ([]string, error) {\n\tn := 0\n\tfor _, field := range []string{\"To\", \"Cc\", \"Bcc\"} {\n\t\tif addresses, ok := m.header[field]; ok {\n\t\t\tn += len(addresses)\n\t\t}\n\t}\n\tlist := make([]string, 0, n)\n\n\tfor _, field := range []string{\"To\", \"Cc\", \"Bcc\"} {\n\t\tif addresses, ok := m.header[field]; ok {\n\t\t\tfor _, a := range addresses {\n\t\t\t\taddr, err := parseAddress(a)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tlist = addAddress(list, addr)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn list, nil\n}\n\nfunc addAddress(list []string, addr string) []string {\n\tfor _, a := range list {\n\t\tif addr == a {\n\t\t\treturn list\n\t\t}\n\t}\n\n\treturn append(list, addr)\n}\n\nfunc parseAddress(field string) (string, error) {\n\ta, err := mail.ParseAddress(field)\n\tif a == nil {\n\t\treturn \"\", err\n\t}\n\n\treturn a.Address, err\n}\n<commit_msg>Made the error clearer when an address is invalid<commit_after>package gomail\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/mail\"\n)\n\n\/\/ Sender is the interface that wraps the Send method.\n\/\/\n\/\/ Send sends an email to the given addresses.\ntype Sender interface {\n\tSend(from string, to []string, msg io.WriterTo) error\n}\n\n\/\/ SendCloser is the interface that groups the Send and Close methods.\ntype SendCloser interface {\n\tSender\n\tClose() error\n}\n\n\/\/ A SendFunc is a function that sends emails to the given adresses.\n\/\/\n\/\/ The SendFunc type is an adapter to allow the use of ordinary functions as\n\/\/ email senders. If f is a function with the appropriate signature, SendFunc(f)\n\/\/ is a Sender object that calls f.\ntype SendFunc func(from string, to []string, msg io.WriterTo) error\n\n\/\/ Send calls f(from, to, msg).\nfunc (f SendFunc) Send(from string, to []string, msg io.WriterTo) error {\n\treturn f(from, to, msg)\n}\n\n\/\/ Send sends emails using the given Sender.\nfunc Send(s Sender, msg ...*Message) error {\n\tfor i, m := range msg {\n\t\tif err := send(s, m); err != nil {\n\t\t\treturn fmt.Errorf(\"gomail: could not send email %d: %v\", i+1, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc send(s Sender, m *Message) error {\n\tfrom, err := m.getFrom()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tto, err := m.getRecipients()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := s.Send(from, to, m); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (m *Message) getFrom() (string, error) {\n\tfrom := m.header[\"Sender\"]\n\tif len(from) == 0 {\n\t\tfrom = m.header[\"From\"]\n\t\tif len(from) == 0 {\n\t\t\treturn \"\", errors.New(`gomail: invalid message, \"From\" field is absent`)\n\t\t}\n\t}\n\n\treturn parseAddress(from[0])\n}\n\nfunc (m *Message) getRecipients() ([]string, error) {\n\tn := 0\n\tfor _, field := range []string{\"To\", \"Cc\", \"Bcc\"} {\n\t\tif addresses, ok := m.header[field]; ok {\n\t\t\tn += len(addresses)\n\t\t}\n\t}\n\tlist := make([]string, 0, n)\n\n\tfor _, field := range []string{\"To\", \"Cc\", \"Bcc\"} {\n\t\tif addresses, ok := m.header[field]; ok {\n\t\t\tfor _, a := range addresses {\n\t\t\t\taddr, err := parseAddress(a)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tlist = addAddress(list, addr)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn list, nil\n}\n\nfunc addAddress(list []string, addr string) []string {\n\tfor _, a := range list {\n\t\tif addr == a {\n\t\t\treturn list\n\t\t}\n\t}\n\n\treturn append(list, addr)\n}\n\nfunc parseAddress(field string) (string, error) {\n\taddr, err := mail.ParseAddress(field)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"gomail: invalid address %q: %v\", field, err)\n\t}\n\treturn addr.Address, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t_ \"time\"\n\t\"crypto\/rand\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"github.com\/gorilla\/sessions\"\n\t\"io\"\n\t\"net\/http\"\n\t\"encoding\/json\"\n\t\"database\/sql\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"runtime\"\n\t\"errors\"\n\t\"html\/template\"\n)\n\nvar templates = template.Must(template.ParseFiles(\".\/HackMIT2\/index.html\"))\n\nconst MESSAGE_QUEUE_SIZE = 10\n\nvar authKey = []byte(\"somesecretauth\")\nvar store sessions.Store\nvar pool *Pool\nvar clients map[int64]*Client\n\nvar db *sql.DB\n\/\/ var tv syscall.Timeval\n\ntype Pool struct {\n\tin  chan *Client\n\tout chan *Room\n}\n\ntype Client struct {\n\tid      int64\n\tin      chan string\n\tout     chan string\n\tretChan chan *Room\n}\n\ntype Room struct {\n\tid      int64\n\tclient1 *Client\n\tclient2 *Client\n}\n\nfunc (p *Pool) Pair() {\n\tfor {\n\t\tc1, c2 := <-p.in, <-p.in\n\n\t\tfmt.Println(\"match found for \", c1.id, \" and \", c2.id)\n\n\t\tb := make([]byte, 8)\n\t\tn, err := io.ReadFull(rand.Reader, b)\n\t\tif err != nil || n != 8 {\n\t\t\treturn\n\t\t}\n\t\tcrId, _ := binary.Varint(b)\n\n\t\troom := &Room{crId, c1, c2}\n\n\t\tc1.in, c2.in = c2.out, c1.out\n\n\t\tc1.retChan <- room\n\t\tc2.retChan <- room\n\t}\n}\n\nfunc newPool() *Pool {\n\tpool := &Pool{\n\t\tin:  make(chan *Client),\n\t\tout: make(chan *Room),\n\t}\n\n\tgo pool.Pair()\n\n\treturn pool\n}\n\nfunc UIDFromSession(w http.ResponseWriter, r *http.Request) (int64, error) {\n\tsession, _ := store.Get(r, \"session\")\n\tuserid := session.Values[\"userid\"]\n\n\tfmt.Println(session.Values)\n\tif userid == nil {\n\t\treturn 0, errors.New(\"no cookie set\")\n\t} \n\treturn userid.(int64), nil\n}\n\nfunc main() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\tdb, _ = sql.Open(\"mysql\", \"root:pass@\/suitup\")\n\tdefer db.Close()\n\n\tstore = sessions.NewCookieStore(authKey)\n\n\tpool = newPool()\n\tclients = make(map[int64]*Client)\n\n\thttp.HandleFunc(\"\/\", mainHandle)\n\n\thttp.HandleFunc(\"\/login\", login)\n\n\thttp.HandleFunc(\"\/message\/check\", checkMessage)\n\thttp.HandleFunc(\"\/message\/send\", sendMessage)\n\n\thttp.HandleFunc(\"\/chatroom\/join\", joinChatRoom)\n\thttp.HandleFunc(\"\/chatroom\/leave\", leaveChatRoom)\n\n\thttp.Handle(\"\/assets\/\", http.StripPrefix(\"\/assets\/\", http.FileServer(http.Dir(\"\/home\/suitup\/hackmit\/HackMIT2\/\"))))\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\ntype IdQuery struct {\n    Id            int64      `json:\"id\"`\n\n}\n\nfunc mainHandle(w http.ResponseWriter, r *http.Request) {\n\ttemplates.ExecuteTemplate(w, \".\/HackMIT2\/index.html\", nil)\n}\n\nfunc joinChatRoom(w http.ResponseWriter, r *http.Request) {\n\tuid, err := UIDFromSession(w, r)\n\thandleError(err)\n\n  \tfmt.Println(\"uid: \", uid)\n\tretChan := make(chan *Room)\n\tclient := &Client{\n\t\tid:      uid,\n\t\tin:      nil,\n\t\tout:     make(chan string, MESSAGE_QUEUE_SIZE),\n\t\tretChan: retChan,\n\t}\n\tclients[uid] = client\n\tpool.in <- client\n\n\tfmt.Println(\"added \", uid, \" to queue\")\n\tchatroom := <- retChan\n\n\tfmt.Fprint(w, \"{\\\"status\\\":\\\"success\\\",\\\"crid\\\":\", chatroom.id, \"}\")\n}\n\nfunc leaveChatRoom(w http.ResponseWriter, r *http.Request) {\n\tuid, _ := UIDFromSession(w, r)\n\tfmt.Fprint(w, uid)\n}\n\nfunc sendMessage(w http.ResponseWriter, r *http.Request) {\n\tuid, err := UIDFromSession(w, r)\n\thandleError(err)\n\n\tfmt.Println(uid)\n\n\tmessage := r.FormValue(\"s\")\n\n\t\/\/ message := r.PostFormValue(\"message\")\n\n\tclient := clients[uid]\n\n\tif client != nil {\n\t\tclient.out <- message\n\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"success\\\"}-\", message)\n\t} else {\n\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"failure\\\"}-\", message)\n\t}\t\n}\n\nfunc checkMessage(w http.ResponseWriter, r *http.Request) {\n\tuid, err := UIDFromSession(w, r)\n\thandleError(err)\n\n\tclient := clients[uid]\n\n\tif client != nil {\n\t\tfmt.Println(\"client found\")\n\t\tselect {\n\t\tcase message, ok := <- clients[uid].in:\n\t\t\tfmt.Println(\"message pulled from channel\")\n\t\t\tif ok {\n\t\t\t\tfmt.Fprint(w, message)\n\t\t\t} else {\n\t\t\t\tfmt.Fprint(w, \"\")\n\t\t\t}\n\t\tdefault:\n\t\t\tfmt.Println(\"\")\n\t\t\tfmt.Fprint(w, \"\")\n\t\t}\n\t\n\t} else {\n\t\tfmt.Println(\"client not found\")\n\t\tfmt.Fprint(w, \"\")\n\t}\n}\n\n\n\nfunc login(w http.ResponseWriter, r *http.Request) {\n\tinputToken := r.FormValue(\"access_token\")\n\tif len(inputToken) != 0 {\n\t\tuid := GetMe(inputToken)\n\n\t\t\/\/ row := db.QueryRow(\"SELECT id FROM users\")\n\t\trow := db.QueryRow(\"SELECT id FROM users WHERE facebook_id=?\", string(uid))\n\t\tiq := new(IdQuery)\n\t\terr := row.Scan(&iq.Id)\n\n\t\tif err != nil {\n\t\t\t_, err = db.Exec(\"insert into users (facebook_id, username, email, level, points) values (?, ?, ?, 0, 0)\", uid, \"\", \"\")\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"failure\\\"}\")\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\trow = db.QueryRow(\"SELECT id FROM users WHERE facebook_id=?\", string(uid))\n\t\t\t\terr = row.Scan(&iq.Id)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"failure\\\"}\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tfmt.Println(\"session-id: \", iq.Id)\n\n\t\tsession, _ := store.Get(r, \"session\")\n\t\tsession.Values[\"userid\"] = iq.Id\n\t\tsession.Save(r, w)\n\n\t\tfmt.Println(session.Values)\n\n\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"success\\\"}\")\n\n\n\t\/\/ \tif err == nil {\n\t\/\/ \t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"success\\\",\\\"uid\\\":\", iq.Id, \"}\")\n\t\/\/ \t} else {\n\t\/\/ \t\t_, err = db.Exec(\"insert into users (facebook_id, username, email, level, points) values (?, ?, ?, 0, 0)\", uid, \"\", \"\")\n\t\/\/ \t\tif err == nil {\n\t\/\/ \t\t\trow = db.QueryRow(\"SELECT id FROM users WHERE facebook_id=?\", string(uid))\n\t\/\/ \t\t\terr = row.Scan(&iq.Id)\n\t\/\/ \t\t\tif err == nil {\n\t\/\/ \t\t\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"success\\\"},\\\"uid\\\":\", iq.Id, \"}\")\n\t\/\/ \t\t\t} else {\n\t\/\/ \t\t\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"failure\\\"}\")\n\t\/\/ \t\t\t}\n\t\/\/ \t\t} else {\n\t\/\/ \t\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"failure\\\"}\")\n\t\/\/ \t\t}\n\t\/\/ \t}\n\t\/\/ } else {\n\t\/\/ \tfmt.Fprint(w, \"{\\\"status\\\":\\\"failure\\\"}\")\n\t}\n}\n\t\n\nfunc readHttpBody(response *http.Response) string {\n\tbodyBuffer := make([]byte, 1000)\n\tvar str string\n\n\tcount, err := response.Body.Read(bodyBuffer)\n\n\tfor ; count > 0; count, err = response.Body.Read(bodyBuffer) {\n\n\t\tif err != nil {\n\n\t\t}\n\n\t\tstr += string(bodyBuffer[:count])\n\t}\n\n\treturn str\n\n}\n\nfunc getUncachedResponse(uri string) (*http.Response, error) {\n\trequest, err := http.NewRequest(\"GET\", uri, nil)\n\n\tif err == nil {\n\t\trequest.Header.Add(\"Cache-Control\", \"no-cache\")\n\n\t\tclient := new(http.Client)\n\n\t\treturn client.Do(request)\n\t}\n\n\tif (err != nil) {\n\t}\n\treturn nil, err\n\n}\n\nfunc GetMe(token string) string {\n\tresponse, err := getUncachedResponse(\"https:\/\/graph.facebook.com\/me?access_token=\"+token)\n\n\tif err == nil {\n\n\t\tvar jsonBlob interface{}\n\n\t\tresponseBody := readHttpBody(response)\n\n\t\tif responseBody != \"\" {\n\t\t\terr = json.Unmarshal([]byte(responseBody), &jsonBlob)\n\n\t\t\tif err == nil {\n\t\t\t\tjsonObj := jsonBlob.(map[string]interface{})\n\t\t\t\treturn jsonObj[\"id\"].(string)\n\t\t\t}\n\t\t}\n\t\treturn err.Error()\n\t}\n\n\treturn err.Error()\n}\n\nfunc handleError(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n<commit_msg>index.html<commit_after>package main\n\nimport (\n\t_ \"time\"\n\t\"crypto\/rand\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"github.com\/gorilla\/sessions\"\n\t\"io\"\n\t\"net\/http\"\n\t\"encoding\/json\"\n\t\"database\/sql\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"runtime\"\n\t\"errors\"\n\t\"html\/template\"\n)\n\nvar templates = template.Must(template.ParseFiles(\"index.html\"))\n\nconst MESSAGE_QUEUE_SIZE = 10\n\nvar authKey = []byte(\"somesecretauth\")\nvar store sessions.Store\nvar pool *Pool\nvar clients map[int64]*Client\n\nvar db *sql.DB\n\/\/ var tv syscall.Timeval\n\ntype Pool struct {\n\tin  chan *Client\n\tout chan *Room\n}\n\ntype Client struct {\n\tid      int64\n\tin      chan string\n\tout     chan string\n\tretChan chan *Room\n}\n\ntype Room struct {\n\tid      int64\n\tclient1 *Client\n\tclient2 *Client\n}\n\nfunc (p *Pool) Pair() {\n\tfor {\n\t\tc1, c2 := <-p.in, <-p.in\n\n\t\tfmt.Println(\"match found for \", c1.id, \" and \", c2.id)\n\n\t\tb := make([]byte, 8)\n\t\tn, err := io.ReadFull(rand.Reader, b)\n\t\tif err != nil || n != 8 {\n\t\t\treturn\n\t\t}\n\t\tcrId, _ := binary.Varint(b)\n\n\t\troom := &Room{crId, c1, c2}\n\n\t\tc1.in, c2.in = c2.out, c1.out\n\n\t\tc1.retChan <- room\n\t\tc2.retChan <- room\n\t}\n}\n\nfunc newPool() *Pool {\n\tpool := &Pool{\n\t\tin:  make(chan *Client),\n\t\tout: make(chan *Room),\n\t}\n\n\tgo pool.Pair()\n\n\treturn pool\n}\n\nfunc UIDFromSession(w http.ResponseWriter, r *http.Request) (int64, error) {\n\tsession, _ := store.Get(r, \"session\")\n\tuserid := session.Values[\"userid\"]\n\n\tfmt.Println(session.Values)\n\tif userid == nil {\n\t\treturn 0, errors.New(\"no cookie set\")\n\t} \n\treturn userid.(int64), nil\n}\n\nfunc main() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\tdb, _ = sql.Open(\"mysql\", \"root:pass@\/suitup\")\n\tdefer db.Close()\n\n\tstore = sessions.NewCookieStore(authKey)\n\n\tpool = newPool()\n\tclients = make(map[int64]*Client)\n\n\thttp.HandleFunc(\"\/\", mainHandle)\n\n\thttp.HandleFunc(\"\/login\", login)\n\n\thttp.HandleFunc(\"\/message\/check\", checkMessage)\n\thttp.HandleFunc(\"\/message\/send\", sendMessage)\n\n\thttp.HandleFunc(\"\/chatroom\/join\", joinChatRoom)\n\thttp.HandleFunc(\"\/chatroom\/leave\", leaveChatRoom)\n\n\thttp.Handle(\"\/assets\/\", http.StripPrefix(\"\/assets\/\", http.FileServer(http.Dir(\"\/home\/suitup\/hackmit\/assets\/\"))))\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\ntype IdQuery struct {\n    Id            int64      `json:\"id\"`\n\n}\n\nfunc mainHandle(w http.ResponseWriter, r *http.Request) {\n\ttemplates.ExecuteTemplate(w, \"index.html\", nil)\n}\n\nfunc joinChatRoom(w http.ResponseWriter, r *http.Request) {\n\tuid, err := UIDFromSession(w, r)\n\thandleError(err)\n\n  \tfmt.Println(\"uid: \", uid)\n\tretChan := make(chan *Room)\n\tclient := &Client{\n\t\tid:      uid,\n\t\tin:      nil,\n\t\tout:     make(chan string, MESSAGE_QUEUE_SIZE),\n\t\tretChan: retChan,\n\t}\n\tclients[uid] = client\n\tpool.in <- client\n\n\tfmt.Println(\"added \", uid, \" to queue\")\n\tchatroom := <- retChan\n\n\tfmt.Fprint(w, \"{\\\"status\\\":\\\"success\\\",\\\"crid\\\":\", chatroom.id, \"}\")\n}\n\nfunc leaveChatRoom(w http.ResponseWriter, r *http.Request) {\n\tuid, _ := UIDFromSession(w, r)\n\tfmt.Fprint(w, uid)\n}\n\nfunc sendMessage(w http.ResponseWriter, r *http.Request) {\n\tuid, err := UIDFromSession(w, r)\n\thandleError(err)\n\n\tfmt.Println(uid)\n\n\tmessage := r.FormValue(\"s\")\n\n\t\/\/ message := r.PostFormValue(\"message\")\n\n\tclient := clients[uid]\n\n\tif client != nil {\n\t\tclient.out <- message\n\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"success\\\"}-\", message)\n\t} else {\n\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"failure\\\"}-\", message)\n\t}\t\n}\n\nfunc checkMessage(w http.ResponseWriter, r *http.Request) {\n\tuid, err := UIDFromSession(w, r)\n\thandleError(err)\n\n\tclient := clients[uid]\n\n\tif client != nil {\n\t\tfmt.Println(\"client found\")\n\t\tselect {\n\t\tcase message, ok := <- clients[uid].in:\n\t\t\tfmt.Println(\"message pulled from channel\")\n\t\t\tif ok {\n\t\t\t\tfmt.Fprint(w, message)\n\t\t\t} else {\n\t\t\t\tfmt.Fprint(w, \"\")\n\t\t\t}\n\t\tdefault:\n\t\t\tfmt.Println(\"\")\n\t\t\tfmt.Fprint(w, \"\")\n\t\t}\n\t\n\t} else {\n\t\tfmt.Println(\"client not found\")\n\t\tfmt.Fprint(w, \"\")\n\t}\n}\n\n\n\nfunc login(w http.ResponseWriter, r *http.Request) {\n\tinputToken := r.FormValue(\"access_token\")\n\tif len(inputToken) != 0 {\n\t\tuid := GetMe(inputToken)\n\n\t\t\/\/ row := db.QueryRow(\"SELECT id FROM users\")\n\t\trow := db.QueryRow(\"SELECT id FROM users WHERE facebook_id=?\", string(uid))\n\t\tiq := new(IdQuery)\n\t\terr := row.Scan(&iq.Id)\n\n\t\tif err != nil {\n\t\t\t_, err = db.Exec(\"insert into users (facebook_id, username, email, level, points) values (?, ?, ?, 0, 0)\", uid, \"\", \"\")\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"failure\\\"}\")\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\trow = db.QueryRow(\"SELECT id FROM users WHERE facebook_id=?\", string(uid))\n\t\t\t\terr = row.Scan(&iq.Id)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"failure\\\"}\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tfmt.Println(\"session-id: \", iq.Id)\n\n\t\tsession, _ := store.Get(r, \"session\")\n\t\tsession.Values[\"userid\"] = iq.Id\n\t\tsession.Save(r, w)\n\n\t\tfmt.Println(session.Values)\n\n\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"success\\\"}\")\n\n\n\t\/\/ \tif err == nil {\n\t\/\/ \t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"success\\\",\\\"uid\\\":\", iq.Id, \"}\")\n\t\/\/ \t} else {\n\t\/\/ \t\t_, err = db.Exec(\"insert into users (facebook_id, username, email, level, points) values (?, ?, ?, 0, 0)\", uid, \"\", \"\")\n\t\/\/ \t\tif err == nil {\n\t\/\/ \t\t\trow = db.QueryRow(\"SELECT id FROM users WHERE facebook_id=?\", string(uid))\n\t\/\/ \t\t\terr = row.Scan(&iq.Id)\n\t\/\/ \t\t\tif err == nil {\n\t\/\/ \t\t\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"success\\\"},\\\"uid\\\":\", iq.Id, \"}\")\n\t\/\/ \t\t\t} else {\n\t\/\/ \t\t\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"failure\\\"}\")\n\t\/\/ \t\t\t}\n\t\/\/ \t\t} else {\n\t\/\/ \t\t\tfmt.Fprint(w, \"{\\\"status\\\":\\\"failure\\\"}\")\n\t\/\/ \t\t}\n\t\/\/ \t}\n\t\/\/ } else {\n\t\/\/ \tfmt.Fprint(w, \"{\\\"status\\\":\\\"failure\\\"}\")\n\t}\n}\n\t\n\nfunc readHttpBody(response *http.Response) string {\n\tbodyBuffer := make([]byte, 1000)\n\tvar str string\n\n\tcount, err := response.Body.Read(bodyBuffer)\n\n\tfor ; count > 0; count, err = response.Body.Read(bodyBuffer) {\n\n\t\tif err != nil {\n\n\t\t}\n\n\t\tstr += string(bodyBuffer[:count])\n\t}\n\n\treturn str\n\n}\n\nfunc getUncachedResponse(uri string) (*http.Response, error) {\n\trequest, err := http.NewRequest(\"GET\", uri, nil)\n\n\tif err == nil {\n\t\trequest.Header.Add(\"Cache-Control\", \"no-cache\")\n\n\t\tclient := new(http.Client)\n\n\t\treturn client.Do(request)\n\t}\n\n\tif (err != nil) {\n\t}\n\treturn nil, err\n\n}\n\nfunc GetMe(token string) string {\n\tresponse, err := getUncachedResponse(\"https:\/\/graph.facebook.com\/me?access_token=\"+token)\n\n\tif err == nil {\n\n\t\tvar jsonBlob interface{}\n\n\t\tresponseBody := readHttpBody(response)\n\n\t\tif responseBody != \"\" {\n\t\t\terr = json.Unmarshal([]byte(responseBody), &jsonBlob)\n\n\t\t\tif err == nil {\n\t\t\t\tjsonObj := jsonBlob.(map[string]interface{})\n\t\t\t\treturn jsonObj[\"id\"].(string)\n\t\t\t}\n\t\t}\n\t\treturn err.Error()\n\t}\n\n\treturn err.Error()\n}\n\nfunc handleError(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package kiwi\n\n\/\/ This file consists of Sink related structures and functions.\n\/\/ Outputs accepts incoming log records from Loggers, check them with filters\n\/\/ and write to output streams if checks passed.\n\n\/* Copyright (c) 2016-2019, Alexander I.Grafov <grafov@gmail.com>\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and\/or other materials provided with the distribution.\n\n* Neither the name of kvlog nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nॐ तारे तुत्तारे तुरे स्व *\/\n\nimport (\n\t\"io\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\n\/\/ States of the sink.\nconst (\n\tsinkClosed int32 = iota - 1\n\tsinkStopped\n\tsinkActive\n)\n\n\/\/ Sinks accepts records through the chanels.\n\/\/ Each sink has its own channel.\nvar collector struct {\n\tsync.RWMutex\n\tsinks []*Sink\n\tcount int\n}\n\ntype (\n\t\/\/ Sink used for filtering incoming log records from all logger instances\n\t\/\/ and decides how to filter them. Each output wraps its own io.Writer.\n\t\/\/ Sink methods are safe for concurrent usage.\n\tSink struct {\n\t\tid     uint\n\t\tIn     chan chain\n\t\tclose  chan struct{}\n\t\twriter io.Writer\n\t\tformat Formatter\n\t\tstate  *int32\n\n\t\tsync.RWMutex\n\t\tpositiveFilters map[string]Filter\n\t\tnegativeFilters map[string]Filter\n\t\thiddenKeys      map[string]bool\n\t}\n\tchain struct {\n\t\twg    *sync.WaitGroup\n\t\tpairs []*Pair\n\t}\n)\n\n\/\/ SinkTo creates a new sink for an arbitrary number of loggers.\n\/\/ There are any number of sinks may be created for saving incoming log\n\/\/ records to different places.\n\/\/ The sink requires explicit start with Start() before usage.\n\/\/ That allows firstly setup filters before sink will really accept any records.\nfunc SinkTo(w io.Writer, fn Formatter) *Sink {\n\tcollector.RLock()\n\tfor i, sink := range collector.sinks {\n\t\tif sink.writer == w {\n\t\t\tcollector.sinks[i].format = fn\n\t\t\tcollector.RUnlock()\n\t\t\treturn collector.sinks[i]\n\t\t}\n\t}\n\tcollector.RUnlock()\n\tvar (\n\t\tstate = sinkStopped\n\t\tsink  = &Sink{\n\t\t\tIn:              make(chan chain, 16),\n\t\t\tclose:           make(chan struct{}),\n\t\t\tformat:          fn,\n\t\t\tstate:           &state,\n\t\t\twriter:          w,\n\t\t\tpositiveFilters: make(map[string]Filter),\n\t\t\tnegativeFilters: make(map[string]Filter),\n\t\t\thiddenKeys:      make(map[string]bool),\n\t\t}\n\t)\n\tcollector.Lock()\n\tsink.id = uint(collector.count)\n\tcollector.sinks = append(collector.sinks, sink)\n\tcollector.count++\n\tcollector.Unlock()\n\tgo processSink(sink)\n\treturn sink\n}\n\n\/\/ HasKey sets restriction for records output.\n\/\/ Only the records WITH any of the keys will be passed to output.\nfunc (s *Sink) HasKey(keys ...string) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tfor _, key := range keys {\n\t\t\ts.positiveFilters[key] = &keyFilter{}\n\t\t\tdelete(s.negativeFilters, key)\n\t\t}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ HasNotKey sets restriction for records output.\n\/\/ Only the records WITHOUT any of the keys will be passed to output.\nfunc (s *Sink) HasNotKey(keys ...string) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tfor _, key := range keys {\n\t\t\ts.negativeFilters[key] = &keyFilter{}\n\t\t\tdelete(s.positiveFilters, key)\n\t\t}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ HasValue sets restriction for records output.\n\/\/ A record passed to output if the key equal one of any of the listed values.\nfunc (s *Sink) HasValue(key string, vals ...string) *Sink {\n\tif len(vals) == 0 {\n\t\treturn s.HasKey(key)\n\t}\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\ts.positiveFilters[key] = &valsFilter{Vals: vals}\n\t\tdelete(s.negativeFilters, key)\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ HasNotValue sets restriction for records output.\nfunc (s *Sink) HasNotValue(key string, vals ...string) *Sink {\n\tif len(vals) == 0 {\n\t\treturn s.HasNotKey(key)\n\t}\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\ts.negativeFilters[key] = &valsFilter{Vals: vals}\n\t\tdelete(s.positiveFilters, key)\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Int64Range sets restriction for records output.\nfunc (s *Sink) Int64Range(key string, from, to int64) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.negativeFilters, key)\n\t\ts.positiveFilters[key] = &int64RangeFilter{From: from, To: to}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Int64NotRange sets restriction for records output.\nfunc (s *Sink) Int64NotRange(key string, from, to int64) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.positiveFilters, key)\n\t\ts.negativeFilters[key] = &int64RangeFilter{From: from, To: to}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Float64Range sets restriction for records output.\nfunc (s *Sink) Float64Range(key string, from, to float64) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.negativeFilters, key)\n\t\ts.positiveFilters[key] = &float64RangeFilter{From: from, To: to}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Float64NotRange sets restriction for records output.\nfunc (s *Sink) Float64NotRange(key string, from, to float64) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.positiveFilters, key)\n\t\ts.negativeFilters[key] = &float64RangeFilter{From: from, To: to}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ TimeRange sets restriction for records output.\nfunc (s *Sink) TimeRange(key string, from, to time.Time) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.negativeFilters, key)\n\t\ts.positiveFilters[key] = &timeRangeFilter{From: from, To: to}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ TimeNotRange sets restriction for records output.\nfunc (s *Sink) TimeNotRange(key string, from, to time.Time) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.positiveFilters, key)\n\t\ts.negativeFilters[key] = &timeRangeFilter{From: from, To: to}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ WithFilter setup custom filtering function for values for a specific key.\n\/\/ Custom filter should realize Filter interface. All custom filters treated\n\/\/ as positive filters. So if the filter returns true then it will be passed.\nfunc (s *Sink) WithFilter(key string, customFilter Filter) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.negativeFilters, key)\n\t\ts.positiveFilters[key] = customFilter\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Reset all filters for the keys for the output.\nfunc (s *Sink) Reset(keys ...string) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tfor _, key := range keys {\n\t\t\tdelete(s.positiveFilters, key)\n\t\t\tdelete(s.negativeFilters, key)\n\t\t}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Hide keys from the output. Other keys in record will be displayed\n\/\/ but not hidden keys.\nfunc (s *Sink) Hide(keys ...string) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tfor _, key := range keys {\n\t\t\ts.hiddenKeys[key] = true\n\t\t}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Unhide previously hidden keys. They will be displayed in the output again.\nfunc (s *Sink) Unhide(keys ...string) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tfor _, key := range keys {\n\t\t\tdelete(s.hiddenKeys, key)\n\t\t}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Stop stops writing to the output.\nfunc (s *Sink) Stop() *Sink {\n\tatomic.StoreInt32(s.state, sinkStopped)\n\treturn s\n}\n\n\/\/ Start writing to the output.\n\/\/ After creation of a new sink it will paused and you need explicitly start it.\n\/\/ It allows setup the filters before the sink will accepts any records.\nfunc (s *Sink) Start() *Sink {\n\tatomic.StoreInt32(s.state, sinkActive)\n\treturn s\n}\n\n\/\/ Close closes the sink. It flushes records for the sink before closing.\nfunc (s *Sink) Close() {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\tatomic.StoreInt32(s.state, sinkClosed)\n\t\ts.close <- struct{}{}\n\t\tcollector.Lock()\n\t\tcollector.count--\n\t\tcollector.sinks = append(collector.sinks[0:s.id], collector.sinks[s.id+1:]...)\n\t\tcollector.Unlock()\n\t}\n}\n\nfunc processSink(s *Sink) {\n\tvar (\n\t\trecord chain\n\t\tok     bool\n\t)\n\tfor {\n\t\tselect {\n\t\tcase record, ok = <-s.In:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif atomic.LoadInt32(s.state) < sinkActive {\n\t\t\t\trecord.wg.Done()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts.RLock()\n\t\t\tvar filter Filter\n\t\t\tfor _, pair := range record.pairs {\n\t\t\t\t\/\/ Negative conditions have highest priority\n\t\t\t\tif filter, ok = s.negativeFilters[pair.Key]; ok {\n\t\t\t\t\tif filter.Check(pair.Key, pair.Val) {\n\t\t\t\t\t\tgoto skipRecord\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ At last check for positive conditions\n\t\t\t\tif filter, ok = s.positiveFilters[pair.Key]; ok {\n\t\t\t\t\tif !filter.Check(pair.Key, pair.Val) {\n\t\t\t\t\t\tgoto skipRecord\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\ts.formatRecord(record.pairs)\n\t\tskipRecord:\n\t\t\ts.RUnlock()\n\t\t\trecord.wg.Done()\n\t\tcase <-s.close:\n\t\t\ts.Lock()\n\t\t\ts.positiveFilters = nil\n\t\t\ts.negativeFilters = nil\n\t\t\ts.hiddenKeys = nil\n\t\t\ts.Unlock()\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (s *Sink) formatRecord(record []*Pair) {\n\ts.format.Begin()\n\tfor _, pair := range record {\n\t\tif ok := s.hiddenKeys[pair.Key]; ok {\n\t\t\tcontinue\n\t\t}\n\t\ts.format.Pair(pair.Key, pair.Val, pair.Type)\n\t}\n\ts.writer.Write(s.format.Finish())\n}\n\nconst flushTimeout = 3 * time.Second\n\nfunc sinkRecord(rec []*Pair) {\n\tvar wg sync.WaitGroup\n\tcollector.RLock()\n\tfor _, s := range collector.sinks {\n\t\tif atomic.LoadInt32(s.state) == sinkActive {\n\t\t\twg.Add(1)\n\t\t\ts.In <- chain{&wg, rec}\n\t\t}\n\t}\n\tcollector.RUnlock()\n\tvar c = make(chan struct{})\n\tgo func() {\n\t\tdefer close(c)\n\t\twg.Wait()\n\t}()\n\tselect {\n\tcase <-c:\n\t\treturn\n\tcase <-time.After(flushTimeout):\n\t\treturn\n\t}\n}\n<commit_msg>Fix side effects of sink.Close() refs #4 and #5<commit_after>package kiwi\n\n\/\/ This file consists of Sink related structures and functions.\n\/\/ Outputs accepts incoming log records from Loggers, check them with filters\n\/\/ and write to output streams if checks passed.\n\n\/* Copyright (c) 2016-2019, Alexander I.Grafov <grafov@gmail.com>\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and\/or other materials provided with the distribution.\n\n* Neither the name of kvlog nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nॐ तारे तुत्तारे तुरे स्व *\/\n\nimport (\n\t\"io\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\n\/\/ States of the sink.\nconst (\n\tsinkClosed int32 = iota - 1\n\tsinkStopped\n\tsinkActive\n)\n\n\/\/ Sinks accepts records through the chanels.\n\/\/ Each sink has its own channel.\nvar collector struct {\n\tsync.RWMutex\n\tsinks []*Sink\n}\n\ntype (\n\t\/\/ Sink used for filtering incoming log records from all logger instances\n\t\/\/ and decides how to filter them. Each output wraps its own io.Writer.\n\t\/\/ Sink methods are safe for concurrent usage.\n\tSink struct {\n\t\tIn     chan chain\n\t\tclose  chan struct{}\n\t\twriter io.Writer\n\t\tformat Formatter\n\t\tstate  *int32\n\n\t\tsync.RWMutex\n\t\tpositiveFilters map[string]Filter\n\t\tnegativeFilters map[string]Filter\n\t\thiddenKeys      map[string]bool\n\t}\n\tchain struct {\n\t\twg    *sync.WaitGroup\n\t\tpairs []*Pair\n\t}\n)\n\n\/\/ SinkTo creates a new sink for an arbitrary number of loggers.\n\/\/ There are any number of sinks may be created for saving incoming log\n\/\/ records to different places.\n\/\/ The sink requires explicit start with Start() before usage.\n\/\/ That allows firstly setup filters before sink will really accept any records.\nfunc SinkTo(w io.Writer, fn Formatter) *Sink {\n\tcollector.RLock()\n\tfor i, sink := range collector.sinks {\n\t\tif sink.writer == w {\n\t\t\tcollector.sinks[i].format = fn\n\t\t\tcollector.RUnlock()\n\t\t\treturn collector.sinks[i]\n\t\t}\n\t}\n\tcollector.RUnlock()\n\tvar (\n\t\tstate = sinkStopped\n\t\tsink  = &Sink{\n\t\t\tIn:              make(chan chain, 16),\n\t\t\tclose:           make(chan struct{}),\n\t\t\tformat:          fn,\n\t\t\tstate:           &state,\n\t\t\twriter:          w,\n\t\t\tpositiveFilters: make(map[string]Filter),\n\t\t\tnegativeFilters: make(map[string]Filter),\n\t\t\thiddenKeys:      make(map[string]bool),\n\t\t}\n\t)\n\tcollector.Lock()\n\tcollector.sinks = append(collector.sinks, sink)\n\tcollector.Unlock()\n\tgo processSink(sink)\n\treturn sink\n}\n\n\/\/ HasKey sets restriction for records output.\n\/\/ Only the records WITH any of the keys will be passed to output.\nfunc (s *Sink) HasKey(keys ...string) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tfor _, key := range keys {\n\t\t\ts.positiveFilters[key] = &keyFilter{}\n\t\t\tdelete(s.negativeFilters, key)\n\t\t}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ HasNotKey sets restriction for records output.\n\/\/ Only the records WITHOUT any of the keys will be passed to output.\nfunc (s *Sink) HasNotKey(keys ...string) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tfor _, key := range keys {\n\t\t\ts.negativeFilters[key] = &keyFilter{}\n\t\t\tdelete(s.positiveFilters, key)\n\t\t}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ HasValue sets restriction for records output.\n\/\/ A record passed to output if the key equal one of any of the listed values.\nfunc (s *Sink) HasValue(key string, vals ...string) *Sink {\n\tif len(vals) == 0 {\n\t\treturn s.HasKey(key)\n\t}\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\ts.positiveFilters[key] = &valsFilter{Vals: vals}\n\t\tdelete(s.negativeFilters, key)\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ HasNotValue sets restriction for records output.\nfunc (s *Sink) HasNotValue(key string, vals ...string) *Sink {\n\tif len(vals) == 0 {\n\t\treturn s.HasNotKey(key)\n\t}\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\ts.negativeFilters[key] = &valsFilter{Vals: vals}\n\t\tdelete(s.positiveFilters, key)\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Int64Range sets restriction for records output.\nfunc (s *Sink) Int64Range(key string, from, to int64) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.negativeFilters, key)\n\t\ts.positiveFilters[key] = &int64RangeFilter{From: from, To: to}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Int64NotRange sets restriction for records output.\nfunc (s *Sink) Int64NotRange(key string, from, to int64) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.positiveFilters, key)\n\t\ts.negativeFilters[key] = &int64RangeFilter{From: from, To: to}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Float64Range sets restriction for records output.\nfunc (s *Sink) Float64Range(key string, from, to float64) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.negativeFilters, key)\n\t\ts.positiveFilters[key] = &float64RangeFilter{From: from, To: to}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Float64NotRange sets restriction for records output.\nfunc (s *Sink) Float64NotRange(key string, from, to float64) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.positiveFilters, key)\n\t\ts.negativeFilters[key] = &float64RangeFilter{From: from, To: to}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ TimeRange sets restriction for records output.\nfunc (s *Sink) TimeRange(key string, from, to time.Time) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.negativeFilters, key)\n\t\ts.positiveFilters[key] = &timeRangeFilter{From: from, To: to}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ TimeNotRange sets restriction for records output.\nfunc (s *Sink) TimeNotRange(key string, from, to time.Time) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.positiveFilters, key)\n\t\ts.negativeFilters[key] = &timeRangeFilter{From: from, To: to}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ WithFilter setup custom filtering function for values for a specific key.\n\/\/ Custom filter should realize Filter interface. All custom filters treated\n\/\/ as positive filters. So if the filter returns true then it will be passed.\nfunc (s *Sink) WithFilter(key string, customFilter Filter) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tdelete(s.negativeFilters, key)\n\t\ts.positiveFilters[key] = customFilter\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Reset all filters for the keys for the output.\nfunc (s *Sink) Reset(keys ...string) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tfor _, key := range keys {\n\t\t\tdelete(s.positiveFilters, key)\n\t\t\tdelete(s.negativeFilters, key)\n\t\t}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Hide keys from the output. Other keys in record will be displayed\n\/\/ but not hidden keys.\nfunc (s *Sink) Hide(keys ...string) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tfor _, key := range keys {\n\t\t\ts.hiddenKeys[key] = true\n\t\t}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Unhide previously hidden keys. They will be displayed in the output again.\nfunc (s *Sink) Unhide(keys ...string) *Sink {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\ts.Lock()\n\t\tfor _, key := range keys {\n\t\t\tdelete(s.hiddenKeys, key)\n\t\t}\n\t\ts.Unlock()\n\t}\n\treturn s\n}\n\n\/\/ Stop stops writing to the output.\nfunc (s *Sink) Stop() *Sink {\n\tatomic.StoreInt32(s.state, sinkStopped)\n\treturn s\n}\n\n\/\/ Start writing to the output.\n\/\/ After creation of a new sink it will paused and you need explicitly start it.\n\/\/ It allows setup the filters before the sink will accepts any records.\nfunc (s *Sink) Start() *Sink {\n\tatomic.StoreInt32(s.state, sinkActive)\n\treturn s\n}\n\n\/\/ Close closes the sink. It flushes records for the sink before closing.\nfunc (s *Sink) Close() {\n\tif atomic.LoadInt32(s.state) > sinkClosed {\n\t\tatomic.StoreInt32(s.state, sinkClosed)\n\t\ts.close <- struct{}{}\n\t\tcollector.Lock()\n\t\tfor i, v := range collector.sinks {\n\t\t\tif s == v {\n\t\t\t\tcollector.sinks[i] = collector.sinks[len(collector.sinks)-1]\n\t\t\t\tcollector.sinks[len(collector.sinks)-1] = nil\n\t\t\t\tcollector.sinks = collector.sinks[:len(collector.sinks)-1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tcollector.Unlock()\n\t}\n}\n\nfunc processSink(s *Sink) {\n\tvar (\n\t\trecord chain\n\t\tok     bool\n\t)\n\tfor {\n\t\tselect {\n\t\tcase record, ok = <-s.In:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif atomic.LoadInt32(s.state) < sinkActive {\n\t\t\t\trecord.wg.Done()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ts.RLock()\n\t\t\tvar filter Filter\n\t\t\tfor _, pair := range record.pairs {\n\t\t\t\t\/\/ Negative conditions have highest priority\n\t\t\t\tif filter, ok = s.negativeFilters[pair.Key]; ok {\n\t\t\t\t\tif filter.Check(pair.Key, pair.Val) {\n\t\t\t\t\t\tgoto skipRecord\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ At last check for positive conditions\n\t\t\t\tif filter, ok = s.positiveFilters[pair.Key]; ok {\n\t\t\t\t\tif !filter.Check(pair.Key, pair.Val) {\n\t\t\t\t\t\tgoto skipRecord\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\ts.formatRecord(record.pairs)\n\t\tskipRecord:\n\t\t\ts.RUnlock()\n\t\t\trecord.wg.Done()\n\t\tcase <-s.close:\n\t\t\ts.Lock()\n\t\t\ts.positiveFilters = nil\n\t\t\ts.negativeFilters = nil\n\t\t\ts.hiddenKeys = nil\n\t\t\ts.Unlock()\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (s *Sink) formatRecord(record []*Pair) {\n\ts.format.Begin()\n\tfor _, pair := range record {\n\t\tif ok := s.hiddenKeys[pair.Key]; ok {\n\t\t\tcontinue\n\t\t}\n\t\ts.format.Pair(pair.Key, pair.Val, pair.Type)\n\t}\n\ts.writer.Write(s.format.Finish())\n}\n\nconst flushTimeout = 3 * time.Second\n\nfunc sinkRecord(rec []*Pair) {\n\tvar wg sync.WaitGroup\n\tcollector.RLock()\n\tfor _, s := range collector.sinks {\n\t\tif atomic.LoadInt32(s.state) == sinkActive {\n\t\t\twg.Add(1)\n\t\t\ts.In <- chain{&wg, rec}\n\t\t}\n\t}\n\tcollector.RUnlock()\n\tvar c = make(chan struct{})\n\tgo func() {\n\t\tdefer close(c)\n\t\twg.Wait()\n\t}()\n\tselect {\n\tcase <-c:\n\t\treturn\n\tcase <-time.After(flushTimeout):\n\t\treturn\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package smaz is an implementation of the smaz library\n\/\/ (https:\/\/github.com\/antirez\/smaz) for compressing small strings.\npackage smaz\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\n\t\"github.com\/kjk\/smaz\/trie\"\n)\n\nvar codeStrings = []string{\" \",\n\t\"the\", \"e\", \"t\", \"a\", \"of\", \"o\", \"and\", \"i\", \"n\", \"s\", \"e \", \"r\", \" th\",\n\t\" t\", \"in\", \"he\", \"th\", \"h\", \"he \", \"to\", \"\\r\\n\", \"l\", \"s \", \"d\", \" a\", \"an\",\n\t\"er\", \"c\", \" o\", \"d \", \"on\", \" of\", \"re\", \"of \", \"t \", \", \", \"is\", \"u\", \"at\",\n\t\"   \", \"n \", \"or\", \"which\", \"f\", \"m\", \"as\", \"it\", \"that\", \"\\n\", \"was\", \"en\",\n\t\"  \", \" w\", \"es\", \" an\", \" i\", \"\\r\", \"f \", \"g\", \"p\", \"nd\", \" s\", \"nd \", \"ed \",\n\t\"w\", \"ed\", \"http:\/\/\", \"for\", \"te\", \"ing\", \"y \", \"The\", \" c\", \"ti\", \"r \", \"his\",\n\t\"st\", \" in\", \"ar\", \"nt\", \",\", \" to\", \"y\", \"ng\", \" h\", \"with\", \"le\", \"al\", \"to \",\n\t\"b\", \"ou\", \"be\", \"were\", \" b\", \"se\", \"o \", \"ent\", \"ha\", \"ng \", \"their\", \"\\\"\",\n\t\"hi\", \"from\", \" f\", \"in \", \"de\", \"ion\", \"me\", \"v\", \".\", \"ve\", \"all\", \"re \",\n\t\"ri\", \"ro\", \"is \", \"co\", \"f t\", \"are\", \"ea\", \". \", \"her\", \" m\", \"er \", \" p\",\n\t\"es \", \"by\", \"they\", \"di\", \"ra\", \"ic\", \"not\", \"s, \", \"d t\", \"at \", \"ce\", \"la\",\n\t\"h \", \"ne\", \"as \", \"tio\", \"on \", \"n t\", \"io\", \"we\", \" a \", \"om\", \", a\", \"s o\",\n\t\"ur\", \"li\", \"ll\", \"ch\", \"had\", \"this\", \"e t\", \"g \", \"e\\r\\n\", \" wh\", \"ere\",\n\t\" co\", \"e o\", \"a \", \"us\", \" d\", \"ss\", \"\\n\\r\\n\", \"\\r\\n\\r\", \"=\\\"\", \" be\", \" e\",\n\t\"s a\", \"ma\", \"one\", \"t t\", \"or \", \"but\", \"el\", \"so\", \"l \", \"e s\", \"s,\", \"no\",\n\t\"ter\", \" wa\", \"iv\", \"ho\", \"e a\", \" r\", \"hat\", \"s t\", \"ns\", \"ch \", \"wh\", \"tr\",\n\t\"ut\", \"\/\", \"have\", \"ly \", \"ta\", \" ha\", \" on\", \"tha\", \"-\", \" l\", \"ati\", \"en \",\n\t\"pe\", \" re\", \"there\", \"ass\", \"si\", \" fo\", \"wa\", \"ec\", \"our\", \"who\", \"its\", \"z\",\n\t\"fo\", \"rs\", \">\", \"ot\", \"un\", \"<\", \"im\", \"th \", \"nc\", \"ate\", \"><\", \"ver\", \"ad\",\n\t\" we\", \"ly\", \"ee\", \" n\", \"id\", \" cl\", \"ac\", \"il\", \"<\/\", \"rt\", \" wi\", \"div\",\n\t\"e, \", \" it\", \"whi\", \" ma\", \"ge\", \"x\", \"e c\", \"men\", \".com\",\n}\n\nvar codes = make([][]byte, len(codeStrings))\nvar codeTrie = trie.New()\n\nfunc init() {\n\tfor i, code := range codeStrings {\n\t\tcodes[i] = []byte(code)\n\t\tcodeTrie.Put([]byte(code), i)\n\t}\n}\n\nfunc flushVerb(dst *[]byte, verbBuf *bytes.Buffer) {\n\td := *dst\n\t\/\/ We can write a max of 255 continuous verbatim characters, because the\n\t\/\/ length of the continous verbatim section is represented by a single byte.\n\tfor verbBuf.Len() > 0 {\n\t\tchunk := verbBuf.Next(255)\n\t\tif len(chunk) == 1 {\n\t\t\t\/\/ 254 is code for a single verbatim byte\n\t\t\td = append(d, byte(254))\n\t\t} else {\n\t\t\t\/\/ 255 is code for a verbatim string. It is followed by a byte\n\t\t\t\/\/ containing the length of the string.\n\t\t\td = append(d, byte(255))\n\t\t\td = append(d, byte(len(chunk)))\n\t\t}\n\t\td = append(d, chunk...)\n\t}\n\tverbBuf.Reset()\n\t*dst = d\n}\n\n\/\/ Compress compresses a byte slice and returns the compressed data.\nfunc Compress(dst, input []byte) []byte {\n\tdst = dst[0:0]\n\tvar verbBuf bytes.Buffer\n\troot := codeTrie.Root()\n\n\tfor len(input) > 0 {\n\t\tprefixLen := 0\n\t\tcode := 0\n\t\tnode := root\n\t\tfor i, c := range input {\n\t\t\tnext, ok := node.Walk(c)\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tnode = next\n\t\t\tif node.Terminal() {\n\t\t\t\tprefixLen = i + 1\n\t\t\t\tcode = node.Val()\n\t\t\t}\n\t\t}\n\n\t\tif prefixLen > 0 {\n\t\t\tinput = input[prefixLen:]\n\t\t\tflushVerb(&dst, &verbBuf)\n\t\t\tdst = append(dst, byte(code))\n\t\t} else {\n\t\t\tverbBuf.WriteByte(input[0])\n\t\t\tinput = input[1:]\n\t\t}\n\t}\n\tflushVerb(&dst, &verbBuf)\n\treturn dst\n}\n\n\/\/ ErrDecompression is returned when decompressing invalid smaz-encoded data.\nvar ErrDecompression = errors.New(\"Invalid or corrupted compressed data.\")\n\n\/\/ Decompress decompresses a smaz-compressed byte slice and return a new slice\n\/\/ with the decompressed data. err is nil if and only if decompression fails\n\/\/ for any reason (e.g., corrupted data).\nfunc Decompress(compressed []byte) ([]byte, error) {\n\tdecompressed := make([]byte, 0, len(compressed)) \/\/ Estimate initial size\n\tfor len(compressed) > 0 {\n\t\tn := int(compressed[0])\n\t\tswitch n {\n\t\tcase 254: \/\/ Verbatim byte\n\t\t\tif len(compressed) < 2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tdecompressed = append(decompressed, compressed[1])\n\t\t\tcompressed = compressed[2:]\n\t\tcase 255: \/\/ Verbatim string\n\t\t\tif len(compressed) < 2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tn = int(compressed[1])\n\t\t\tif len(compressed) < n+2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tdecompressed = append(decompressed, compressed[2:n+2]...)\n\t\t\tcompressed = compressed[n+2:]\n\t\tdefault: \/\/ Look up encoded value\n\t\t\td := codes[n]\n\t\t\tdecompressed = append(decompressed, d...)\n\t\t\tcompressed = compressed[1:]\n\t\t}\n\t}\n\n\treturn decompressed, nil\n}\n<commit_msg>speed up compression<commit_after>\/\/ Package smaz is an implementation of the smaz library\n\/\/ (https:\/\/github.com\/antirez\/smaz) for compressing small strings.\npackage smaz\n\nimport (\n\t\"errors\"\n\n\t\"github.com\/kjk\/smaz\/trie\"\n)\n\nvar codeStrings = []string{\" \",\n\t\"the\", \"e\", \"t\", \"a\", \"of\", \"o\", \"and\", \"i\", \"n\", \"s\", \"e \", \"r\", \" th\",\n\t\" t\", \"in\", \"he\", \"th\", \"h\", \"he \", \"to\", \"\\r\\n\", \"l\", \"s \", \"d\", \" a\", \"an\",\n\t\"er\", \"c\", \" o\", \"d \", \"on\", \" of\", \"re\", \"of \", \"t \", \", \", \"is\", \"u\", \"at\",\n\t\"   \", \"n \", \"or\", \"which\", \"f\", \"m\", \"as\", \"it\", \"that\", \"\\n\", \"was\", \"en\",\n\t\"  \", \" w\", \"es\", \" an\", \" i\", \"\\r\", \"f \", \"g\", \"p\", \"nd\", \" s\", \"nd \", \"ed \",\n\t\"w\", \"ed\", \"http:\/\/\", \"for\", \"te\", \"ing\", \"y \", \"The\", \" c\", \"ti\", \"r \", \"his\",\n\t\"st\", \" in\", \"ar\", \"nt\", \",\", \" to\", \"y\", \"ng\", \" h\", \"with\", \"le\", \"al\", \"to \",\n\t\"b\", \"ou\", \"be\", \"were\", \" b\", \"se\", \"o \", \"ent\", \"ha\", \"ng \", \"their\", \"\\\"\",\n\t\"hi\", \"from\", \" f\", \"in \", \"de\", \"ion\", \"me\", \"v\", \".\", \"ve\", \"all\", \"re \",\n\t\"ri\", \"ro\", \"is \", \"co\", \"f t\", \"are\", \"ea\", \". \", \"her\", \" m\", \"er \", \" p\",\n\t\"es \", \"by\", \"they\", \"di\", \"ra\", \"ic\", \"not\", \"s, \", \"d t\", \"at \", \"ce\", \"la\",\n\t\"h \", \"ne\", \"as \", \"tio\", \"on \", \"n t\", \"io\", \"we\", \" a \", \"om\", \", a\", \"s o\",\n\t\"ur\", \"li\", \"ll\", \"ch\", \"had\", \"this\", \"e t\", \"g \", \"e\\r\\n\", \" wh\", \"ere\",\n\t\" co\", \"e o\", \"a \", \"us\", \" d\", \"ss\", \"\\n\\r\\n\", \"\\r\\n\\r\", \"=\\\"\", \" be\", \" e\",\n\t\"s a\", \"ma\", \"one\", \"t t\", \"or \", \"but\", \"el\", \"so\", \"l \", \"e s\", \"s,\", \"no\",\n\t\"ter\", \" wa\", \"iv\", \"ho\", \"e a\", \" r\", \"hat\", \"s t\", \"ns\", \"ch \", \"wh\", \"tr\",\n\t\"ut\", \"\/\", \"have\", \"ly \", \"ta\", \" ha\", \" on\", \"tha\", \"-\", \" l\", \"ati\", \"en \",\n\t\"pe\", \" re\", \"there\", \"ass\", \"si\", \" fo\", \"wa\", \"ec\", \"our\", \"who\", \"its\", \"z\",\n\t\"fo\", \"rs\", \">\", \"ot\", \"un\", \"<\", \"im\", \"th \", \"nc\", \"ate\", \"><\", \"ver\", \"ad\",\n\t\" we\", \"ly\", \"ee\", \" n\", \"id\", \" cl\", \"ac\", \"il\", \"<\/\", \"rt\", \" wi\", \"div\",\n\t\"e, \", \" it\", \"whi\", \" ma\", \"ge\", \"x\", \"e c\", \"men\", \".com\",\n}\n\nvar codes = make([][]byte, len(codeStrings))\nvar codeTrie = trie.New()\n\nfunc init() {\n\tfor i, code := range codeStrings {\n\t\tcodes[i] = []byte(code)\n\t\tcodeTrie.Put([]byte(code), i)\n\t}\n}\n\nfunc next(d []byte, n int) ([]byte, []byte) {\n\tif n >= len(d) {\n\t\treturn d, nil\n\t}\n\treturn d[:n], d[n:]\n}\n\nfunc flushVerb(d, verbBuf []byte) ([]byte, []byte) {\n\tvar chunk []byte\n\t\/\/ We can write a max of 255 continuous verbatim characters, because the\n\t\/\/ length of the continous verbatim section is represented by a single byte.\n\tfor len(verbBuf) > 0 {\n\t\tchunk, verbBuf = next(verbBuf, 255)\n\t\tif len(chunk) == 1 {\n\t\t\t\/\/ 254 is code for a single verbatim byte\n\t\t\td = append(d, byte(254))\n\t\t} else {\n\t\t\t\/\/ 255 is code for a verbatim string. It is followed by a byte\n\t\t\t\/\/ containing the length of the string.\n\t\t\td = append(d, byte(255))\n\t\t\td = append(d, byte(len(chunk)))\n\t\t}\n\t\td = append(d, chunk...)\n\t}\n\treturn d, verbBuf[0:0]\n}\n\n\/\/ Compress compresses a byte slice and returns the compressed data.\nfunc Compress(dst, input []byte) []byte {\n\tdst = dst[0:0]\n\tvar verbBuf []byte\n\troot := codeTrie.Root()\n\n\tfor len(input) > 0 {\n\t\tprefixLen := 0\n\t\tcode := 0\n\t\tnode := root\n\t\tfor i, c := range input {\n\t\t\tnext, ok := node.Walk(c)\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tnode = next\n\t\t\tif node.Terminal() {\n\t\t\t\tprefixLen = i + 1\n\t\t\t\tcode = node.Val()\n\t\t\t}\n\t\t}\n\n\t\tif prefixLen > 0 {\n\t\t\tinput = input[prefixLen:]\n\t\t\tdst, verbBuf = flushVerb(dst, verbBuf)\n\t\t\tdst = append(dst, byte(code))\n\t\t} else {\n\t\t\tverbBuf = append(verbBuf, input[0])\n\t\t\tinput = input[1:]\n\t\t}\n\t}\n\tdst, _ = flushVerb(dst, verbBuf)\n\treturn dst\n}\n\n\/\/ ErrDecompression is returned when decompressing invalid smaz-encoded data.\nvar ErrDecompression = errors.New(\"Invalid or corrupted compressed data.\")\n\n\/\/ Decompress decompresses a smaz-compressed byte slice and return a new slice\n\/\/ with the decompressed data. err is nil if and only if decompression fails\n\/\/ for any reason (e.g., corrupted data).\nfunc Decompress(compressed []byte) ([]byte, error) {\n\tdecompressed := make([]byte, 0, len(compressed)) \/\/ Estimate initial size\n\tfor len(compressed) > 0 {\n\t\tn := int(compressed[0])\n\t\tswitch n {\n\t\tcase 254: \/\/ Verbatim byte\n\t\t\tif len(compressed) < 2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tdecompressed = append(decompressed, compressed[1])\n\t\t\tcompressed = compressed[2:]\n\t\tcase 255: \/\/ Verbatim string\n\t\t\tif len(compressed) < 2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tn = int(compressed[1])\n\t\t\tif len(compressed) < n+2 {\n\t\t\t\treturn nil, ErrDecompression\n\t\t\t}\n\t\t\tdecompressed = append(decompressed, compressed[2:n+2]...)\n\t\t\tcompressed = compressed[n+2:]\n\t\tdefault: \/\/ Look up encoded value\n\t\t\td := codes[n]\n\t\t\tdecompressed = append(decompressed, d...)\n\t\t\tcompressed = compressed[1:]\n\t\t}\n\t}\n\n\treturn decompressed, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package kmath\n\nimport (\n    \"sort\"\n    \"errors\"\n    \"math\"\n)\n\n\/\/ Gini returns the Gini coefficient. It is a measure of inequality in a \n\/\/ frequency distribution. 0 indicates perfect equality, 1 maximum inequality.\n\/\/\n\/\/ See https:\/\/en.wikipedia.org\/wiki\/Gini_coefficient\nfunc Gini(in []float64) float64 {\n\n    var i int\n    N := len(in)  \n    \n\t\/\/ Get the total of the series\n\tc := 0.0\n\tfor i=0;i<N;i++ {\n\t\tc += in[i]\n\t}\n\n\t\/\/ Create a vector Y with what part of the total is each input value. \n\ty := make([]float64, N)\n\n\tfor i=0;i<N;i++ {\n\t\ty[i] = in[i] \/ c\n\t}\n\n    \/\/ sort Y values in ascending order\n\tsort.Float64s(y)\n\n\t\/\/ Normalize the X\n\tx := 1.0 \/ float64(N)\n\n\t\/\/ Calculate areas below the diagonal\n\tgini := 0.0\n\tacc := 0.0\n\tpacc := 0.0\n\t\n\tfor i := 0; i < N; i++ {\n\t\tacc += y[i]\n\t\tpacc += x\n\t\tgini += (pacc - acc) * x\n\t}\n\n    \/\/ Normalize to 0...1 (area of triangle is 0.5 max)\n\treturn 2 * gini\n}\n\n\/\/ Cover\nfunc Cover(v []float64, lev float64) (float64,float64) {\n    var i int\n    N := len(v)  \n\n    Ad := 0.0\n    Au := 0.0\n    \n    for i=0;i<N;i++ {\n        if v[i]>=lev {\n            Au += (v[i]-lev)\n            Ad += lev\n        } else {\n            Ad += v[i]\n        }\n    }\n    \n    n := float64(N)\n    return Ad\/(lev*n), Au\/(lev*n)\n}\n\n\/\/ Pearson returns the Pearson correlation coeficient of two arrays\nfunc Pearson (a, b [] float64) (float64, error) {\n\n    n := len(a)\n    \n    if n!=len(b) {\n        return 0,errors.New(\"lengths differ\")\n    }\n\n    ma := 0.0\n    mb := 0.0\n    \n    for i:=0;i<n;i++ {\n        ma += a[i]\n        mb += b[i]\n    }\n    \n    ma \/= float64(n)\n    mb \/= float64(n)\n    \n    nu := 0.0\n    d1 := 0.0\n    d2 := 0.0\n    \n    var da, db float64\n    \n    for i:=0; i<n; i++ {\n        da = a[i] - ma\n        db = b[i] - mb\n        nu += da*db\n        d1 += da*da\n        d2 += db*db\n    }\n    \n    return nu \/ ( math.Sqrt(d1) * math.Sqrt(d2) ), nil\n}<commit_msg>gini corrected<commit_after>package kmath\n\nimport (\n    \"sort\"\n    \"errors\"\n    \"math\"\n)\n\n\/\/ Gini returns the Gini coefficient. It is a measure of inequality in a \n\/\/ frequency distribution. 0 indicates perfect equality, 1 maximum inequality.\n\/\/\n\/\/ See https:\/\/en.wikipedia.org\/wiki\/Gini_coefficient\nfunc Gini(in []float64) float64 {\n\n    var i int\n    N := len(in)  \n    \n\t\/\/ Get the total of the series\n\tc := 0.0\n\tfor i=0;i<N;i++ {\n\t\tc += in[i]\n\t}\n\n\t\/\/ Create a normalized vector Y\n\ty := make([]float64, N)\n\n\tfor i=0;i<N;i++ {\n\t\ty[i] = in[i] \/ c\n\t}\n\n    \/\/ sort Y values in ascending order\n\tsort.Float64s(y)\n\n\t\/\/ Normalize X\n\tx := 1.0 \/ float64(N)\n\t\n\t\/\/ Accumulate Y\n\tfor i=0; i<N-1; i++ {\n\t    y[i+1] += y[i]\n\t}\n\n\t\/\/ Calculate areas below the diagonal (Brown formula)\n\tgini := 0.0\n\t\n\tfor i := 0; i < N-1; i++ {\n\t\tgini += (y[i+1] + y[i]) * x\n\t}\n\n\treturn 1 - gini\n}\n\n\/\/ Cover\nfunc Cover(v []float64, lev float64) (float64,float64) {\n    var i int\n    N := len(v)  \n\n    Ad := 0.0\n    Au := 0.0\n    \n    for i=0;i<N;i++ {\n        if v[i]>=lev {\n            Au += (v[i]-lev)\n            Ad += lev\n        } else {\n            Ad += v[i]\n        }\n    }\n    \n    n := float64(N)\n    return Ad\/(lev*n), Au\/(lev*n)\n}\n\n\/\/ Pearson returns the Pearson correlation coeficient of two arrays\nfunc Pearson (a, b [] float64) (float64, error) {\n\n    n := len(a)\n    \n    if n!=len(b) {\n        return 0,errors.New(\"lengths differ\")\n    }\n\n    ma := 0.0\n    mb := 0.0\n    \n    for i:=0;i<n;i++ {\n        ma += a[i]\n        mb += b[i]\n    }\n    \n    ma \/= float64(n)\n    mb \/= float64(n)\n    \n    nu := 0.0\n    d1 := 0.0\n    d2 := 0.0\n    \n    var da, db float64\n    \n    for i:=0; i<n; i++ {\n        da = a[i] - ma\n        db = b[i] - mb\n        nu += da*db\n        d1 += da*da\n        d2 += db*db\n    }\n    \n    return nu \/ ( math.Sqrt(d1) * math.Sqrt(d2) ), nil\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/brotherlogic\/godiscogs\"\n\t\"golang.org\/x\/net\/context\"\n\n\tpbd \"github.com\/brotherlogic\/godiscogs\"\n)\n\nimport \"github.com\/golang\/protobuf\/proto\"\n\nimport \"strconv\"\n\nimport \"time\"\n\nimport pb \"github.com\/brotherlogic\/discogssyncer\/server\"\n\n\/\/ GetRelease Gets the release and metadata for the release\nfunc (syncer *Syncer) GetRelease(id int, folder int) (*pbd.Release, *pb.ReleaseMetadata) {\n\treleaseData, err := ioutil.ReadFile(syncer.saveLocation + \"\/\" + strconv.Itoa(folder) + \"\/\" + strconv.Itoa(id) + \".release\")\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\tmetadataData, _ := ioutil.ReadFile(syncer.saveLocation + \"\/static-metadata\/\" + strconv.Itoa(id) + \".metadata\")\n\trelease := &pbd.Release{}\n\tmetadata := &pb.ReleaseMetadata{}\n\n\tproto.Unmarshal(releaseData, release)\n\tproto.Unmarshal(metadataData, metadata)\n\n\treturn release, metadata\n}\n\nfunc (syncer *Syncer) saveMetadata(rel *godiscogs.Release) {\n\tmetadataRoot := syncer.saveLocation + \"\/static-metadata\/\"\n\tmetadataPath := metadataRoot + strconv.Itoa(int(rel.Id)) + \".metadata\"\n\tif _, err := os.Stat(metadataRoot); os.IsNotExist(err) {\n\t\tos.MkdirAll(metadataRoot, 0777)\n\t}\n\n\tmetadata := &pb.ReleaseMetadata{}\n\tif _, err := os.Stat(metadataPath); os.IsNotExist(err) {\n\t\tmetadata.DateAdded = time.Now().Unix()\n\t\tmetadata.DateRefreshed = time.Now().Unix()\n\t} else {\n\t\tdata, _ := ioutil.ReadFile(metadataPath)\n\t\tproto.Unmarshal(data, metadata)\n\t\tmetadata.DateRefreshed = time.Now().Unix()\n\t}\n\tdata, _ := proto.Marshal(metadata)\n\tioutil.WriteFile(metadataPath, data, 0644)\n}\n\nfunc (syncer *Syncer) deleteRelease(rel *godiscogs.Release, folder int) {\n\tos.Remove(syncer.saveLocation + \"\/\" + strconv.Itoa(folder) + \"\/\" + strconv.Itoa(int(rel.Id)) + \".release\")\n}\n\nfunc (syncer *Syncer) saveRelease(rel *godiscogs.Release, folder int) {\n\t\/\/Check that the save folder exists\n\tsavePath := syncer.saveLocation + \"\/\" + strconv.Itoa(folder) + \"\/\"\n\tif _, err := os.Stat(savePath); os.IsNotExist(err) {\n\t\tos.MkdirAll(savePath, 0777)\n\t}\n\n\tdata, _ := proto.Marshal(rel)\n\tioutil.WriteFile(savePath+strconv.Itoa(int(rel.Id))+\".release\", data, 0644)\n\tsyncer.saveMetadata(rel)\n}\n\ntype saver interface {\n\tGetCollection() []godiscogs.Release\n\tGetFolders() []godiscogs.Folder\n\tGetRelease(id int) (godiscogs.Release, error)\n\tMoveToFolder(folderID int, releaseID int, instanceID int, newFolderID int)\n\tAddToFolder(folderID int, releaseID int)\n\tSetRating(folderID int, releaseID int, instanceID int, rating int)\n\tGetWantlist() ([]pbd.Release, error)\n}\n\n\/\/ SaveCollection writes out the full collection to files.\nfunc (syncer *Syncer) SaveCollection(retr saver) {\n\treleases := retr.GetCollection()\n\tfor _, release := range releases {\n\t\tfullRelease, _ := retr.GetRelease(int(release.Id))\n\t\tfullRelease.InstanceId = release.InstanceId\n\t\tfullRelease.FolderId = release.FolderId\n\t\tfullRelease.Rating = release.Rating\n\t\tsyncer.saveRelease(&fullRelease, int(release.FolderId))\n\t}\n\tfolders := retr.GetFolders()\n\tfolderList := pb.FolderList{}\n\tfor i := range folders {\n\t\tfolder := folders[i]\n\t\tfolderList.Folders = append(folderList.Folders, &folder)\n\t}\n\tsyncer.SaveFolders(&folderList)\n}\n\n\/\/ SyncWantlist syncs the wantlist with the server\nfunc (syncer *Syncer) SyncWantlist() {\n\twants, _ := syncer.retr.GetWantlist()\n\n\tfor _, want := range wants {\n\t\tseen := false\n\t\tvar val *pb.Want\n\t\tfor _, swant := range syncer.wants.Want {\n\t\t\tif swant.ReleaseId == want.Id {\n\t\t\t\tseen = true\n\t\t\t\tval = swant\n\t\t\t}\n\t\t}\n\n\t\tif seen {\n\t\t\tval.Wanted = true\n\t\t} else {\n\t\t\tsyncer.wants.Want = append(syncer.wants.Want, &pb.Want{ReleaseId: want.Id, Valued: false, Wanted: true})\n\t\t}\n\t}\n\n\t\/\/ Cache the want list releases\n\tfor _, want := range syncer.wants.Want {\n\t\trelease, _ := syncer.retr.GetRelease(int(want.ReleaseId))\n\t\tsyncer.saveRelease(&release, -5)\n\t}\n\n\tsyncer.saveWantList()\n}\n\nfunc (syncer *Syncer) getFolders() *pb.FolderList {\n\tdata, _ := ioutil.ReadFile(syncer.saveLocation + \"\/metadata\/folders\")\n\tfolderData := &pb.FolderList{}\n\tproto.Unmarshal(data, folderData)\n\treturn folderData\n}\n\n\/\/ GetSingleRelease gets a single release\nfunc (syncer *Syncer) GetSingleRelease(ctx context.Context, in *pbd.Release) (*pbd.Release, error) {\n\tif val, ok := syncer.relMap[in.Id]; ok {\n\t\treturn val, nil\n\t}\n\treturn nil, errors.New(\"Unable to find release\")\n}\n\n\/\/ MoveToFolder moves a release to the specified folder\nfunc (syncer *Syncer) MoveToFolder(ctx context.Context, in *pb.ReleaseMove) (*pb.Empty, error) {\n\tsyncer.retr.MoveToFolder(int(in.Release.FolderId), int(in.Release.Id), int(in.Release.InstanceId), int(in.NewFolderId))\n\toldFolder := int(in.Release.FolderId)\n\tfullRelease, _ := syncer.retr.GetRelease(int(in.Release.Id))\n\tfullRelease.FolderId = int32(in.NewFolderId)\n\tsyncer.relMap[fullRelease.Id] = &fullRelease\n\n\tsyncer.Log(fmt.Sprintf(\"Moving %v from %v to %v\", in.Release.Id, in.Release.FolderId, in.NewFolderId))\n\tsyncer.saveRelease(&fullRelease, int(in.NewFolderId))\n\tsyncer.deleteRelease(&fullRelease, oldFolder)\n\treturn &pb.Empty{}, nil\n}\n\n\/\/ AddToFolder adds a release to the specified folder\nfunc (syncer *Syncer) AddToFolder(ctx context.Context, in *pb.ReleaseMove) (*pb.Empty, error) {\n\tsyncer.retr.AddToFolder(int(in.NewFolderId), int(in.Release.Id))\n\tfullRelease, _ := syncer.retr.GetRelease(int(in.Release.Id))\n\tfullRelease.FolderId = int32(in.NewFolderId)\n\tsyncer.saveRelease(&fullRelease, int(in.NewFolderId))\n\tsyncer.relMap[in.Release.Id] = &fullRelease\n\treturn &pb.Empty{}, nil\n}\n\n\/\/ UpdateRating updates the rating of a release\nfunc (syncer *Syncer) UpdateRating(ctx context.Context, in *pbd.Release) (*pb.Empty, error) {\n\tsyncer.retr.SetRating(int(in.FolderId), int(in.Id), int(in.InstanceId), int(in.Rating))\n\tfullRelease, _ := syncer.GetRelease(int(in.Id), int(in.FolderId))\n\tfullRelease.Rating = int32(in.Rating)\n\tsyncer.relMap[in.Id] = fullRelease\n\tsyncer.saveRelease(fullRelease, int(fullRelease.FolderId))\n\treturn &pb.Empty{}, nil\n}\n\n\/\/ UpdateMetadata updates the metadata of a given record\nfunc (syncer *Syncer) UpdateMetadata(ctx context.Context, in *pb.MetadataUpdate) (*pb.ReleaseMetadata, error) {\n\trelease, metadata := syncer.GetRelease(int(in.Release.Id), int(in.Release.FolderId))\n\tif release == nil {\n\t\treturn nil, errors.New(\"Unable to locate release\")\n\t}\n\tproto.Merge(metadata, in.Update)\n\n\tmetadataRoot := syncer.saveLocation + \"\/static-metadata\/\"\n\tmetadataPath := metadataRoot + strconv.Itoa(int(in.Release.Id)) + \".metadata\"\n\tdata, _ := proto.Marshal(metadata)\n\tioutil.WriteFile(metadataPath, data, 0644)\n\n\treturn metadata, nil\n}\n\n\/\/ GetWantlist gets the wantlist\nfunc (syncer *Syncer) GetWantlist(ctx context.Context, in *pb.Empty) (*pb.Wantlist, error) {\n\treturn &syncer.wants, nil\n}\n\n\/\/ GetMetadata gets the metadata for a given release\nfunc (syncer *Syncer) GetMetadata(ctx context.Context, in *pbd.Release) (*pb.ReleaseMetadata, error) {\n\t_, metadata := syncer.GetRelease(int(in.Id), int(in.FolderId))\n\treturn metadata, nil\n}\n\n\/\/ GetReleasesInFolder serves up the releases in a given folder\nfunc (syncer *Syncer) GetReleasesInFolder(ctx context.Context, in *pb.FolderList) (*pb.ReleaseList, error) {\n\n\treleases := pb.ReleaseList{}\n\tfor _, folderSpec := range in.Folders {\n\t\tfolders := syncer.getFolders()\n\t\tfor _, folder := range folders.Folders {\n\t\t\tif folder.Name == folderSpec.Name || folder.Id == folderSpec.Id {\n\t\t\t\tinnerReleases := syncer.getReleases(int(folder.Id))\n\t\t\t\treleases.Releases = append(releases.Releases, innerReleases.Releases...)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &releases, nil\n}\n\nfunc (syncer *Syncer) getReleases(folderID int) *pb.ReleaseList {\n\treleases := pb.ReleaseList{}\n\tfiles, _ := ioutil.ReadDir(syncer.saveLocation + \"\/\" + strconv.Itoa(folderID) + \"\/\")\n\tfor _, file := range files {\n\t\tif strings.HasSuffix(file.Name(), \".release\") {\n\t\t\tdata, _ := ioutil.ReadFile(syncer.saveLocation + \"\/\" + strconv.Itoa(folderID) + \"\/\" + file.Name())\n\t\t\trelease := &pbd.Release{}\n\t\t\tproto.Unmarshal(data, release)\n\t\t\treleases.Releases = append(releases.Releases, release)\n\t\t}\n\t}\n\treturn &releases\n}\n\nfunc (syncer *Syncer) initWantlist() {\n\twldata, _ := ioutil.ReadFile(syncer.saveLocation + \"\/metadata\/wantlist\")\n\tproto.Unmarshal(wldata, &syncer.wants)\n}\n\nfunc (syncer *Syncer) saveWantList() {\n\tdata, _ := proto.Marshal(&syncer.wants)\n\tsavePath := syncer.saveLocation + \"\/metadata\/\"\n\tif _, err := os.Stat(savePath); os.IsNotExist(err) {\n\t\tos.MkdirAll(savePath, 0777)\n\t}\n\tioutil.WriteFile(savePath+\"wantlist\", data, 0644)\n}\n\n\/\/ SaveFolders saves out the list of folders\nfunc (syncer *Syncer) SaveFolders(list *pb.FolderList) {\n\tsavePath := syncer.saveLocation + \"\/metadata\/\"\n\tif _, err := os.Stat(savePath); os.IsNotExist(err) {\n\t\tos.MkdirAll(savePath, 0777)\n\t}\n\n\tdata, _ := proto.Marshal(list)\n\tioutil.WriteFile(savePath+\"folders\", data, 0644)\n}\n\n\/\/ GetCollection serves up the whole of the collection\nfunc (syncer *Syncer) GetCollection(ctx context.Context, in *pb.Empty) (*pb.ReleaseList, error) {\n\treleases := pb.ReleaseList{}\n\tbfiles, _ := ioutil.ReadDir(syncer.saveLocation)\n\tfor _, bfile := range bfiles {\n\t\tif bfile.IsDir() {\n\t\t\tfolderID, _ := strconv.Atoi(bfile.Name())\n\t\t\tfor _, release := range syncer.getReleases(folderID).Releases {\n\t\t\t\treleases.Releases = append(releases.Releases, release)\n\t\t\t}\n\t\t}\n\t}\n\treturn &releases, nil\n}\n<commit_msg>Added cache of new wants<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/brotherlogic\/godiscogs\"\n\t\"golang.org\/x\/net\/context\"\n\n\tpbd \"github.com\/brotherlogic\/godiscogs\"\n)\n\nimport \"github.com\/golang\/protobuf\/proto\"\n\nimport \"strconv\"\n\nimport \"time\"\n\nimport pb \"github.com\/brotherlogic\/discogssyncer\/server\"\n\n\/\/ GetRelease Gets the release and metadata for the release\nfunc (syncer *Syncer) GetRelease(id int, folder int) (*pbd.Release, *pb.ReleaseMetadata) {\n\treleaseData, err := ioutil.ReadFile(syncer.saveLocation + \"\/\" + strconv.Itoa(folder) + \"\/\" + strconv.Itoa(id) + \".release\")\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\tmetadataData, _ := ioutil.ReadFile(syncer.saveLocation + \"\/static-metadata\/\" + strconv.Itoa(id) + \".metadata\")\n\trelease := &pbd.Release{}\n\tmetadata := &pb.ReleaseMetadata{}\n\n\tproto.Unmarshal(releaseData, release)\n\tproto.Unmarshal(metadataData, metadata)\n\n\treturn release, metadata\n}\n\nfunc (syncer *Syncer) saveMetadata(rel *godiscogs.Release) {\n\tmetadataRoot := syncer.saveLocation + \"\/static-metadata\/\"\n\tmetadataPath := metadataRoot + strconv.Itoa(int(rel.Id)) + \".metadata\"\n\tif _, err := os.Stat(metadataRoot); os.IsNotExist(err) {\n\t\tos.MkdirAll(metadataRoot, 0777)\n\t}\n\n\tmetadata := &pb.ReleaseMetadata{}\n\tif _, err := os.Stat(metadataPath); os.IsNotExist(err) {\n\t\tmetadata.DateAdded = time.Now().Unix()\n\t\tmetadata.DateRefreshed = time.Now().Unix()\n\t} else {\n\t\tdata, _ := ioutil.ReadFile(metadataPath)\n\t\tproto.Unmarshal(data, metadata)\n\t\tmetadata.DateRefreshed = time.Now().Unix()\n\t}\n\tdata, _ := proto.Marshal(metadata)\n\tioutil.WriteFile(metadataPath, data, 0644)\n}\n\nfunc (syncer *Syncer) deleteRelease(rel *godiscogs.Release, folder int) {\n\tos.Remove(syncer.saveLocation + \"\/\" + strconv.Itoa(folder) + \"\/\" + strconv.Itoa(int(rel.Id)) + \".release\")\n}\n\nfunc (syncer *Syncer) saveRelease(rel *godiscogs.Release, folder int) {\n\t\/\/Check that the save folder exists\n\tsavePath := syncer.saveLocation + \"\/\" + strconv.Itoa(folder) + \"\/\"\n\tif _, err := os.Stat(savePath); os.IsNotExist(err) {\n\t\tos.MkdirAll(savePath, 0777)\n\t}\n\n\tdata, _ := proto.Marshal(rel)\n\tioutil.WriteFile(savePath+strconv.Itoa(int(rel.Id))+\".release\", data, 0644)\n\tsyncer.saveMetadata(rel)\n}\n\ntype saver interface {\n\tGetCollection() []godiscogs.Release\n\tGetFolders() []godiscogs.Folder\n\tGetRelease(id int) (godiscogs.Release, error)\n\tMoveToFolder(folderID int, releaseID int, instanceID int, newFolderID int)\n\tAddToFolder(folderID int, releaseID int)\n\tSetRating(folderID int, releaseID int, instanceID int, rating int)\n\tGetWantlist() ([]pbd.Release, error)\n}\n\n\/\/ SaveCollection writes out the full collection to files.\nfunc (syncer *Syncer) SaveCollection(retr saver) {\n\treleases := retr.GetCollection()\n\tfor _, release := range releases {\n\t\tfullRelease, _ := retr.GetRelease(int(release.Id))\n\t\tfullRelease.InstanceId = release.InstanceId\n\t\tfullRelease.FolderId = release.FolderId\n\t\tfullRelease.Rating = release.Rating\n\t\tsyncer.saveRelease(&fullRelease, int(release.FolderId))\n\t}\n\tfolders := retr.GetFolders()\n\tfolderList := pb.FolderList{}\n\tfor i := range folders {\n\t\tfolder := folders[i]\n\t\tfolderList.Folders = append(folderList.Folders, &folder)\n\t}\n\tsyncer.SaveFolders(&folderList)\n}\n\n\/\/ SyncWantlist syncs the wantlist with the server\nfunc (syncer *Syncer) SyncWantlist() {\n\twants, _ := syncer.retr.GetWantlist()\n\n\tfor _, want := range wants {\n\t\tseen := false\n\t\tvar val *pb.Want\n\t\tfor _, swant := range syncer.wants.Want {\n\t\t\tif swant.ReleaseId == want.Id {\n\t\t\t\tseen = true\n\t\t\t\tval = swant\n\t\t\t}\n\t\t}\n\n\t\tif seen {\n\t\t\tval.Wanted = true\n\t\t} else {\n\t\t\tsyncer.wants.Want = append(syncer.wants.Want, &pb.Want{ReleaseId: want.Id, Valued: false, Wanted: true})\n\t\t}\n\t}\n\n\t\/\/ Cache the want list releases\n\tfor _, want := range syncer.wants.Want {\n\t\trelease, _ := syncer.retr.GetRelease(int(want.ReleaseId))\n\t\tsyncer.saveRelease(&release, -5)\n\t}\n\n\tsyncer.saveWantList()\n}\n\nfunc (syncer *Syncer) getFolders() *pb.FolderList {\n\tdata, _ := ioutil.ReadFile(syncer.saveLocation + \"\/metadata\/folders\")\n\tfolderData := &pb.FolderList{}\n\tproto.Unmarshal(data, folderData)\n\treturn folderData\n}\n\n\/\/ GetSingleRelease gets a single release\nfunc (syncer *Syncer) GetSingleRelease(ctx context.Context, in *pbd.Release) (*pbd.Release, error) {\n\tif val, ok := syncer.relMap[in.Id]; ok {\n\t\treturn val, nil\n\t}\n\treturn nil, errors.New(\"Unable to find release\")\n}\n\n\/\/ MoveToFolder moves a release to the specified folder\nfunc (syncer *Syncer) MoveToFolder(ctx context.Context, in *pb.ReleaseMove) (*pb.Empty, error) {\n\tsyncer.retr.MoveToFolder(int(in.Release.FolderId), int(in.Release.Id), int(in.Release.InstanceId), int(in.NewFolderId))\n\toldFolder := int(in.Release.FolderId)\n\tfullRelease, _ := syncer.retr.GetRelease(int(in.Release.Id))\n\tfullRelease.FolderId = int32(in.NewFolderId)\n\tsyncer.relMap[fullRelease.Id] = &fullRelease\n\n\tsyncer.Log(fmt.Sprintf(\"Moving %v from %v to %v\", in.Release.Id, in.Release.FolderId, in.NewFolderId))\n\tsyncer.saveRelease(&fullRelease, int(in.NewFolderId))\n\tsyncer.deleteRelease(&fullRelease, oldFolder)\n\treturn &pb.Empty{}, nil\n}\n\n\/\/ AddToFolder adds a release to the specified folder\nfunc (syncer *Syncer) AddToFolder(ctx context.Context, in *pb.ReleaseMove) (*pb.Empty, error) {\n\tsyncer.retr.AddToFolder(int(in.NewFolderId), int(in.Release.Id))\n\tfullRelease, _ := syncer.retr.GetRelease(int(in.Release.Id))\n\tfullRelease.FolderId = int32(in.NewFolderId)\n\tsyncer.saveRelease(&fullRelease, int(in.NewFolderId))\n\tsyncer.relMap[in.Release.Id] = &fullRelease\n\treturn &pb.Empty{}, nil\n}\n\n\/\/ UpdateRating updates the rating of a release\nfunc (syncer *Syncer) UpdateRating(ctx context.Context, in *pbd.Release) (*pb.Empty, error) {\n\tsyncer.retr.SetRating(int(in.FolderId), int(in.Id), int(in.InstanceId), int(in.Rating))\n\tfullRelease, _ := syncer.GetRelease(int(in.Id), int(in.FolderId))\n\tfullRelease.Rating = int32(in.Rating)\n\tsyncer.relMap[in.Id] = fullRelease\n\tsyncer.saveRelease(fullRelease, int(fullRelease.FolderId))\n\treturn &pb.Empty{}, nil\n}\n\n\/\/ UpdateMetadata updates the metadata of a given record\nfunc (syncer *Syncer) UpdateMetadata(ctx context.Context, in *pb.MetadataUpdate) (*pb.ReleaseMetadata, error) {\n\trelease, metadata := syncer.GetRelease(int(in.Release.Id), int(in.Release.FolderId))\n\tif release == nil {\n\t\treturn nil, errors.New(\"Unable to locate release\")\n\t}\n\tproto.Merge(metadata, in.Update)\n\n\tmetadataRoot := syncer.saveLocation + \"\/static-metadata\/\"\n\tmetadataPath := metadataRoot + strconv.Itoa(int(in.Release.Id)) + \".metadata\"\n\tdata, _ := proto.Marshal(metadata)\n\tioutil.WriteFile(metadataPath, data, 0644)\n\n\treturn metadata, nil\n}\n\n\/\/ GetWantlist gets the wantlist\nfunc (syncer *Syncer) GetWantlist(ctx context.Context, in *pb.Empty) (*pb.Wantlist, error) {\n\treturn &syncer.wants, nil\n}\n\n\/\/ GetMetadata gets the metadata for a given release\nfunc (syncer *Syncer) GetMetadata(ctx context.Context, in *pbd.Release) (*pb.ReleaseMetadata, error) {\n\t_, metadata := syncer.GetRelease(int(in.Id), int(in.FolderId))\n\treturn metadata, nil\n}\n\n\/\/ GetReleasesInFolder serves up the releases in a given folder\nfunc (syncer *Syncer) GetReleasesInFolder(ctx context.Context, in *pb.FolderList) (*pb.ReleaseList, error) {\n\n\treleases := pb.ReleaseList{}\n\tfor _, folderSpec := range in.Folders {\n\t\tfolders := syncer.getFolders()\n\t\tfor _, folder := range folders.Folders {\n\t\t\tif folder.Name == folderSpec.Name || folder.Id == folderSpec.Id {\n\t\t\t\tinnerReleases := syncer.getReleases(int(folder.Id))\n\t\t\t\treleases.Releases = append(releases.Releases, innerReleases.Releases...)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &releases, nil\n}\n\nfunc (syncer *Syncer) getReleases(folderID int) *pb.ReleaseList {\n\treleases := pb.ReleaseList{}\n\tfiles, _ := ioutil.ReadDir(syncer.saveLocation + \"\/\" + strconv.Itoa(folderID) + \"\/\")\n\tfor _, file := range files {\n\t\tif strings.HasSuffix(file.Name(), \".release\") {\n\t\t\tdata, _ := ioutil.ReadFile(syncer.saveLocation + \"\/\" + strconv.Itoa(folderID) + \"\/\" + file.Name())\n\t\t\trelease := &pbd.Release{}\n\t\t\tproto.Unmarshal(data, release)\n\t\t\treleases.Releases = append(releases.Releases, release)\n\t\t}\n\t}\n\treturn &releases\n}\n\nfunc (syncer *Syncer) initWantlist() {\n\twldata, _ := ioutil.ReadFile(syncer.saveLocation + \"\/metadata\/wantlist\")\n\tproto.Unmarshal(wldata, &syncer.wants)\n\n\tfor _, want := range syncer.wants.Want {\n\t\trel, _ := syncer.GetRelease(int(want.ReleaseId), -5)\n\t\tsyncer.relMap[rel.Id] = rel\n\t}\n}\n\nfunc (syncer *Syncer) saveWantList() {\n\tdata, _ := proto.Marshal(&syncer.wants)\n\tsavePath := syncer.saveLocation + \"\/metadata\/\"\n\tif _, err := os.Stat(savePath); os.IsNotExist(err) {\n\t\tos.MkdirAll(savePath, 0777)\n\t}\n\tioutil.WriteFile(savePath+\"wantlist\", data, 0644)\n}\n\n\/\/ SaveFolders saves out the list of folders\nfunc (syncer *Syncer) SaveFolders(list *pb.FolderList) {\n\tsavePath := syncer.saveLocation + \"\/metadata\/\"\n\tif _, err := os.Stat(savePath); os.IsNotExist(err) {\n\t\tos.MkdirAll(savePath, 0777)\n\t}\n\n\tdata, _ := proto.Marshal(list)\n\tioutil.WriteFile(savePath+\"folders\", data, 0644)\n}\n\n\/\/ GetCollection serves up the whole of the collection\nfunc (syncer *Syncer) GetCollection(ctx context.Context, in *pb.Empty) (*pb.ReleaseList, error) {\n\treleases := pb.ReleaseList{}\n\tbfiles, _ := ioutil.ReadDir(syncer.saveLocation)\n\tfor _, bfile := range bfiles {\n\t\tif bfile.IsDir() {\n\t\t\tfolderID, _ := strconv.Atoi(bfile.Name())\n\t\t\tfor _, release := range syncer.getReleases(folderID).Releases {\n\t\t\t\treleases.Releases = append(releases.Releases, release)\n\t\t\t}\n\t\t}\n\t}\n\treturn &releases, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\ntype ReadFn func() (reader io.ReadCloser, err error)\ntype File struct {\n\tUrl      url.URL\n\tMtime    time.Time\n\tFileFunc ReadFn\n}\n\nfunc (f File) ReadAll() (content []byte, err error) {\n\treader, err := f.FileFunc()\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ioutil.ReadAll(reader)\n}\n\nfunc Sync(from, to string, lookup LookupFn) (chan File, chan error) {\n\tfiles := make(chan File)\n\terrs := make(chan error)\n\n\tfromUri, err := url.Parse(from)\n\tif err != nil {\n\t\terrs <- err\n\t\treturn nil, errs\n\t}\n\n\tgo func() {\n\t\ttodos := []File{File{Url: *fromUri}}\n\t\tfor i := 0; i < len(todos); i++ {\n\t\t\ttodo := todos[i]\n\n\t\t\tindexFn, err := lookup(todo)\n\t\t\terrs <- err\n\t\t\tif indexFn == nil {\n\t\t\t\terrs <- errors.New(\"Not Supported: \" + todo.Url.String())\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\thfiles := make(chan File)\n\t\t\tfinish := make(chan bool)\n\t\t\tgo func(f chan bool) {\n\t\t\t\tindexFn(todo, hfiles, errs)\n\t\t\t\tf <- true\n\t\t\t}(finish)\n\n\t\tLOOP:\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-finish:\n\t\t\t\t\tbreak LOOP\n\t\t\t\tcase f := <-hfiles:\n\t\t\t\t\tif f.FileFunc == nil {\n\t\t\t\t\t\ttodos = append(todos, f)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tf.Url.Path = filepath.Join(to, f.Url.Path)\n\t\t\t\t\t\terr = Local(f)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrs <- err\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfiles <- f\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclose(files)\n\t\tclose(errs)\n\t}()\n\treturn files, errs\n}\n\nfunc removeNanoseconds(in time.Time) time.Time {\n\treturn time.Date(\n\t\tin.Year(),\n\t\tin.Month(),\n\t\tin.Day(),\n\t\tin.Hour(),\n\t\tin.Minute(),\n\t\tin.Second(),\n\t\t0, in.Location())\n}\n\nfunc Local(file File) (err error) {\n\tst, err := os.Stat(file.Url.Path)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn\n\t}\n\tif st == nil || file.Mtime.After(st.ModTime()) {\n\t\terr = os.MkdirAll(filepath.Dir(file.Url.Path), os.ModeDir|os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tosfile, err := os.Create(file.Url.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer osfile.Close()\n\t\tr, err := file.FileFunc()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = io.Copy(osfile, r)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tos.Chtimes(file.Url.Path, file.Mtime, file.Mtime)\n\n\t\tosfile.Sync()\n\t}\n\treturn\n}\n<commit_msg>skip nil error values<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\ntype ReadFn func() (reader io.ReadCloser, err error)\ntype File struct {\n\tUrl      url.URL\n\tMtime    time.Time\n\tFileFunc ReadFn\n}\n\nfunc (f File) ReadAll() (content []byte, err error) {\n\treader, err := f.FileFunc()\n\tif err != nil {\n\t\treturn\n\t}\n\treturn ioutil.ReadAll(reader)\n}\n\nfunc Sync(from, to string, lookup LookupFn) (chan File, chan error) {\n\tfiles := make(chan File)\n\terrs := make(chan error)\n\n\tfromUri, err := url.Parse(from)\n\tif err != nil {\n\t\terrs <- err\n\t\treturn nil, errs\n\t}\n\n\tgo func() {\n\t\ttodos := []File{File{Url: *fromUri}}\n\t\tfor i := 0; i < len(todos); i++ {\n\t\t\ttodo := todos[i]\n\n\t\t\tindexFn, err := lookup(todo)\n\t\t\terrs <- err\n\t\t\tif indexFn == nil {\n\t\t\t\terrs <- errors.New(\"Not Supported: \" + todo.Url.String())\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\thfiles := make(chan File)\n\t\t\tfinish := make(chan bool)\n\t\t\tgo func(f chan bool) {\n\t\t\t\tindexFn(todo, hfiles, errs)\n\t\t\t\tf <- true\n\t\t\t}(finish)\n\n\t\tLOOP:\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-finish:\n\t\t\t\t\tbreak LOOP\n\t\t\t\tcase f := <-hfiles:\n\t\t\t\t\tif f.FileFunc == nil {\n\t\t\t\t\t\ttodos = append(todos, f)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tf.Url.Path = filepath.Join(to, f.Url.Path)\n\t\t\t\t\t\terr = Local(f)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\terrs <- err\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfiles <- f\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tclose(files)\n\t\tclose(errs)\n\t}()\n\treturn files, skipNil(errs)\n}\n\nfunc skipNil(in chan error) chan error {\n\tout := make(chan error)\n\tgo func() {\n\t\tfor e := range in {\n\t\t\tif e != nil {\n\t\t\t\tout <- e\n\t\t\t}\n\t\t}\n\t\tclose(out)\n\t}()\n\treturn out\n}\n\nfunc removeNanoseconds(in time.Time) time.Time {\n\treturn time.Date(\n\t\tin.Year(),\n\t\tin.Month(),\n\t\tin.Day(),\n\t\tin.Hour(),\n\t\tin.Minute(),\n\t\tin.Second(),\n\t\t0, in.Location())\n}\n\nfunc Local(file File) (err error) {\n\tst, err := os.Stat(file.Url.Path)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn\n\t}\n\tif st == nil || file.Mtime.After(st.ModTime()) {\n\t\terr = os.MkdirAll(filepath.Dir(file.Url.Path), os.ModeDir|os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tosfile, err := os.Create(file.Url.Path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer osfile.Close()\n\t\tr, err := file.FileFunc()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = io.Copy(osfile, r)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tos.Chtimes(file.Url.Path, file.Mtime, file.Mtime)\n\n\t\tosfile.Sync()\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package tail\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sync\"\n\t\"time\"\n\n\tfsnotify \"github.com\/fsnotify\/fsnotify\"\n)\n\nconst (\n\topenRetryInterval = time.Second\n\ttailOldFileDelay  = 15 * time.Second\n\tlinesCapacity     = 1024\n\terrorsCapacity    = 16\n)\n\n\/\/ Line is a line of the target file.\ntype Line struct {\n\tText string\n\tTime time.Time\n}\n\n\/\/ Tail tails a file.\ntype Tail struct {\n\tLines  <-chan *Line\n\tErrors <-chan error\n\n\topt      Options\n\tlines    chan<- *Line\n\terrors   chan<- error\n\tfilename string\n\twg       sync.WaitGroup\n\tctx      context.Context\n\tcancel   context.CancelFunc\n}\n\n\/\/ Options is options for Tail\ntype Options struct {\n\t\/\/ MaxBytesLine is maximum length of lines in bytes.\n\t\/\/ If it is zero, there is no limit.\n\tMaxBytesLine int64\n}\n\ntype tail struct {\n\tparent *Tail\n\n\tfile    *os.File\n\treader  *bufio.Reader\n\twatcher *fsnotify.Watcher\n\tbuf     bytes.Buffer\n\tctx     context.Context\n\tcancel  context.CancelFunc\n}\n\n\/\/ NewTailFile starts tailing a file with opt options.\nfunc NewTailFileWithOptions(filename string, opts Options) (*Tail, error) {\n\tfilename, err := filepath.Abs(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tlines := make(chan *Line, linesCapacity)\n\terrs := make(chan error, errorsCapacity)\n\tparent := &Tail{\n\t\tLines:    lines,\n\t\tErrors:   errs,\n\t\tlines:    lines,\n\t\terrors:   errs,\n\t\tfilename: filename,\n\t\tctx:      ctx,\n\t\tcancel:   cancel,\n\t}\n\n\tparent.wg.Add(1)\n\tgo func() {\n\t\tdefer parent.wg.Done()\n\t\tparent.runFile(os.SEEK_END)\n\t}()\n\tgo parent.wait()\n\n\treturn parent, nil\n}\n\n\/\/ NewTailFile starts tailing a file with the default configuration.\nfunc NewTailFile(filename string) (*Tail, error) {\n\treturn NewTailFileWithOptions(filename, Options{})\n}\n\n\/\/ NewTailReader starts tailing io.Reader\nfunc NewTailReaderWithOptions(reader io.Reader, opts Options) (*Tail, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tlines := make(chan *Line, linesCapacity)\n\terrs := make(chan error, errorsCapacity)\n\tparent := &Tail{\n\t\tLines:  lines,\n\t\tErrors: errs,\n\t\tlines:  lines,\n\t\terrors: errs,\n\t\tctx:    ctx,\n\t\tcancel: cancel,\n\t}\n\tr := ctxReader{\n\t\tctx: ctx,\n\t\tr:   reader,\n\t}\n\tt := &tail{\n\t\tparent: parent,\n\t\treader: bufio.NewReader(r),\n\t\tctx:    ctx,\n\t\tcancel: cancel,\n\t}\n\n\tparent.wg.Add(1)\n\tgo func() {\n\t\tdefer parent.wg.Done()\n\t\tt.runReader()\n\t}()\n\tgo parent.wait()\n\n\treturn parent, nil\n}\n\n\/\/ NewTailReader starts tailing io.Reader with the default configuration.\nfunc NewTailReader(reader io.Reader) (*Tail, error) {\n\treturn NewTailReaderWithOptions(reader, Options{})\n}\n\n\/\/ Close stops tailing the file.\nfunc (t *Tail) Close() error {\n\tt.cancel()\n\tt.wg.Wait()\n\treturn nil\n}\n\nfunc (t *Tail) wait() {\n\tt.wg.Wait()\n\tclose(t.errors)\n\tclose(t.lines)\n}\n\n\/\/ open opens the target file.\n\/\/ If it does not exist, wait for creating new file.\nfunc (t *Tail) open(seek int) (*tail, error) {\n\tconst defaultBufSize = 4096\n\tbufSize := defaultBufSize\n\tif t.opt.MaxBytesLine != 0 && int64(bufSize) > t.opt.MaxBytesLine {\n\t\tbufSize = int(t.opt.MaxBytesLine)\n\t}\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor {\n\t\tfile, err := os.Open(t.filename)\n\t\tif err == nil {\n\t\t\t\/\/ success, seek and watch the file.\n\t\t\tif _, err := file.Seek(0, seek); err != nil {\n\t\t\t\tfile.Close()\n\t\t\t\twatcher.Close()\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif err := watcher.Add(t.filename); err != nil {\n\t\t\t\tfile.Close()\n\t\t\t\twatcher.Close()\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tctx, cancel := context.WithCancel(t.ctx)\n\t\t\tr := ctxReader{\n\t\t\t\tctx: ctx,\n\t\t\t\tr:   file,\n\t\t\t}\n\n\t\t\treturn &tail{\n\t\t\t\tparent:  t,\n\t\t\t\tfile:    file,\n\t\t\t\treader:  bufio.NewReaderSize(r, bufSize),\n\t\t\t\twatcher: watcher,\n\t\t\t\tctx:     ctx,\n\t\t\t\tcancel:  cancel,\n\t\t\t}, nil\n\t\t}\n\n\t\t\/\/ fail. retry...\n\t\tseek = io.SeekStart\n\t\ttimer := time.NewTimer(openRetryInterval)\n\t\tselect {\n\t\tcase <-t.ctx.Done():\n\t\t\ttimer.Stop()\n\t\t\treturn nil, t.ctx.Err()\n\t\tcase <-timer.C:\n\t\t}\n\t}\n}\n\n\/\/ runFile tails target files\nfunc (t *Tail) runFile(seek int) {\n\tchild, err := t.open(seek)\n\tif err != nil {\n\t\tif !errors.Is(err, context.Canceled) {\n\t\t\tt.errors <- err\n\t\t}\n\t\treturn\n\t}\n\n\tt.wg.Add(1)\n\tgo func() {\n\t\tdefer t.wg.Done()\n\t\tchild.runFile()\n\t}()\n}\n\n\/\/ runFile tails a file\nfunc (t *tail) runFile() {\n\tdefer t.watcher.Close()\n\tdefer t.cancel()\n\n\tcherr := make(chan error, 1)\n\tch := make(chan struct{}, 1)\n\tdefer close(ch)\n\n\tt.parent.wg.Add(1)\n\tgo func() {\n\t\tdefer t.parent.wg.Done()\n\t\tfor {\n\t\t\tif err := t.restrict(); err != nil {\n\t\t\t\tselect {\n\t\t\t\tcase cherr <- err:\n\t\t\t\tcase <-t.ctx.Done():\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr := t.tail()\n\t\t\tif err == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ wait for writing new lines.\n\t\t\tselect {\n\t\t\tcase cherr <- err:\n\t\t\tcase <-t.ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase _, ok := <-ch:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-t.ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar renamed bool\n\tvar waiting bool \/\/ waiting for writing new lines?\n\tfor {\n\t\tselect {\n\t\tcase event := <-t.watcher.Events:\n\t\t\tif event.Op.Has(fsnotify.Remove) {\n\t\t\t\t\/\/ the target file is removed, stop tailing.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif event.Op.Has(fsnotify.Rename) {\n\t\t\t\t\/\/ log rotation is detected.\n\t\t\t\tif !renamed {\n\t\t\t\t\t\/\/ start to watch creating new file.\n\t\t\t\t\tt.parent.wg.Add(1)\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tdefer t.parent.wg.Done()\n\t\t\t\t\t\tt.parent.runFile(io.SeekStart)\n\t\t\t\t\t}()\n\n\t\t\t\t\t\/\/ wait a little, and stop tailing old file.\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\ttimer := time.NewTimer(tailOldFileDelay)\n\t\t\t\t\t\tdefer timer.Stop()\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase <-timer.C:\n\t\t\t\t\t\t\tt.cancel()\n\t\t\t\t\t\tcase <-t.ctx.Done():\n\t\t\t\t\t\t}\n\t\t\t\t\t}()\n\t\t\t\t}\n\t\t\t\tname, err := getFileName(t.file)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.parent.errors <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err := t.watcher.Add(name); err != nil {\n\t\t\t\t\tt.parent.errors <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\trenamed = true\n\t\t\t}\n\n\t\t\t\/\/ notify new lines are wrote.\n\t\t\tif waiting {\n\t\t\t\tch <- struct{}{}\n\t\t\t\twaiting = false\n\t\t\t}\n\t\tcase err := <-cherr:\n\t\t\tif errors.Is(err, io.EOF) {\n\t\t\t\twaiting = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tt.parent.errors <- err\n\t\t\treturn\n\t\tcase err := <-t.watcher.Errors:\n\t\t\tt.parent.errors <- err\n\t\t\treturn\n\t\tcase <-t.ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ runReader tails io.Reader\nfunc (t *tail) runReader() {\n\tdefer t.cancel()\n\terr := t.tail()\n\tif errors.Is(err, io.EOF) || errors.Is(err, io.ErrClosedPipe) {\n\t\treturn\n\t}\n\tif err != nil {\n\t\tif !errors.Is(err, context.Canceled) {\n\t\t\tt.parent.errors <- err\n\t\t}\n\t\treturn\n\t}\n}\n\n\/\/ restrict detects a file that is truncated\nfunc (t *tail) restrict() error {\n\tstat, err := t.file.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\tpos, err := t.file.Seek(0, io.SeekCurrent)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif stat.Size() < pos {\n\t\t\/\/ file is truncated. seek to head of file.\n\t\t_, err := t.file.Seek(0, io.SeekStart)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ tail reads lines until EOF\nfunc (t *tail) tail() error {\n\topts := t.parent.opt\n\tfor {\n\t\tline, err := t.reader.ReadSlice('\\n')\n\t\tt.buf.Write(line)\n\t\tif err == bufio.ErrBufferFull {\n\t\t\t\/\/ the reader cannot find EOL in its buffer.\n\t\t\t\/\/ continue to read a line.\n\t\t\tif opts.MaxBytesLine == 0 || int64(t.buf.Len()) < opts.MaxBytesLine {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tt.parent.lines <- &Line{t.buf.String(), time.Now()}\n\t\tt.buf.Reset()\n\t}\n}\n<commit_msg>fix opts is ignored<commit_after>package tail\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sync\"\n\t\"time\"\n\n\tfsnotify \"github.com\/fsnotify\/fsnotify\"\n)\n\nconst (\n\topenRetryInterval = time.Second\n\ttailOldFileDelay  = 15 * time.Second\n\tlinesCapacity     = 1024\n\terrorsCapacity    = 16\n)\n\n\/\/ Line is a line of the target file.\ntype Line struct {\n\tText string\n\tTime time.Time\n}\n\n\/\/ Tail tails a file.\ntype Tail struct {\n\tLines  <-chan *Line\n\tErrors <-chan error\n\n\topts     Options\n\tlines    chan<- *Line\n\terrors   chan<- error\n\tfilename string\n\twg       sync.WaitGroup\n\tctx      context.Context\n\tcancel   context.CancelFunc\n}\n\n\/\/ Options is options for Tail\ntype Options struct {\n\t\/\/ MaxBytesLine is maximum length of lines in bytes.\n\t\/\/ If it is zero, there is no limit.\n\tMaxBytesLine int64\n}\n\ntype tail struct {\n\tparent *Tail\n\n\tfile    *os.File\n\treader  *bufio.Reader\n\twatcher *fsnotify.Watcher\n\tbuf     bytes.Buffer\n\tctx     context.Context\n\tcancel  context.CancelFunc\n}\n\n\/\/ NewTailFile starts tailing a file with opt options.\nfunc NewTailFileWithOptions(filename string, opts Options) (*Tail, error) {\n\tfilename, err := filepath.Abs(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tlines := make(chan *Line, linesCapacity)\n\terrs := make(chan error, errorsCapacity)\n\tparent := &Tail{\n\t\tLines:    lines,\n\t\tErrors:   errs,\n\t\topts:     opts,\n\t\tlines:    lines,\n\t\terrors:   errs,\n\t\tfilename: filename,\n\t\tctx:      ctx,\n\t\tcancel:   cancel,\n\t}\n\n\tparent.wg.Add(1)\n\tgo func() {\n\t\tdefer parent.wg.Done()\n\t\tparent.runFile(os.SEEK_END)\n\t}()\n\tgo parent.wait()\n\n\treturn parent, nil\n}\n\n\/\/ NewTailFile starts tailing a file with the default configuration.\nfunc NewTailFile(filename string) (*Tail, error) {\n\treturn NewTailFileWithOptions(filename, Options{})\n}\n\n\/\/ NewTailReader starts tailing io.Reader\nfunc NewTailReaderWithOptions(reader io.Reader, opts Options) (*Tail, error) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tlines := make(chan *Line, linesCapacity)\n\terrs := make(chan error, errorsCapacity)\n\tparent := &Tail{\n\t\tLines:  lines,\n\t\tErrors: errs,\n\t\topts:   opts,\n\t\tlines:  lines,\n\t\terrors: errs,\n\t\tctx:    ctx,\n\t\tcancel: cancel,\n\t}\n\tr := ctxReader{\n\t\tctx: ctx,\n\t\tr:   reader,\n\t}\n\tt := &tail{\n\t\tparent: parent,\n\t\treader: bufio.NewReader(r),\n\t\tctx:    ctx,\n\t\tcancel: cancel,\n\t}\n\n\tparent.wg.Add(1)\n\tgo func() {\n\t\tdefer parent.wg.Done()\n\t\tt.runReader()\n\t}()\n\tgo parent.wait()\n\n\treturn parent, nil\n}\n\n\/\/ NewTailReader starts tailing io.Reader with the default configuration.\nfunc NewTailReader(reader io.Reader) (*Tail, error) {\n\treturn NewTailReaderWithOptions(reader, Options{})\n}\n\n\/\/ Close stops tailing the file.\nfunc (t *Tail) Close() error {\n\tt.cancel()\n\tt.wg.Wait()\n\treturn nil\n}\n\nfunc (t *Tail) wait() {\n\tt.wg.Wait()\n\tclose(t.errors)\n\tclose(t.lines)\n}\n\n\/\/ open opens the target file.\n\/\/ If it does not exist, wait for creating new file.\nfunc (t *Tail) open(seek int) (*tail, error) {\n\tconst defaultBufSize = 4096\n\tbufSize := defaultBufSize\n\tif t.opts.MaxBytesLine != 0 && int64(bufSize) > t.opts.MaxBytesLine {\n\t\tbufSize = int(t.opts.MaxBytesLine)\n\t}\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor {\n\t\tfile, err := os.Open(t.filename)\n\t\tif err == nil {\n\t\t\t\/\/ success, seek and watch the file.\n\t\t\tif _, err := file.Seek(0, seek); err != nil {\n\t\t\t\tfile.Close()\n\t\t\t\twatcher.Close()\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tif err := watcher.Add(t.filename); err != nil {\n\t\t\t\tfile.Close()\n\t\t\t\twatcher.Close()\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tctx, cancel := context.WithCancel(t.ctx)\n\t\t\tr := ctxReader{\n\t\t\t\tctx: ctx,\n\t\t\t\tr:   file,\n\t\t\t}\n\n\t\t\treturn &tail{\n\t\t\t\tparent:  t,\n\t\t\t\tfile:    file,\n\t\t\t\treader:  bufio.NewReaderSize(r, bufSize),\n\t\t\t\twatcher: watcher,\n\t\t\t\tctx:     ctx,\n\t\t\t\tcancel:  cancel,\n\t\t\t}, nil\n\t\t}\n\n\t\t\/\/ fail. retry...\n\t\tseek = io.SeekStart\n\t\ttimer := time.NewTimer(openRetryInterval)\n\t\tselect {\n\t\tcase <-t.ctx.Done():\n\t\t\ttimer.Stop()\n\t\t\treturn nil, t.ctx.Err()\n\t\tcase <-timer.C:\n\t\t}\n\t}\n}\n\n\/\/ runFile tails target files\nfunc (t *Tail) runFile(seek int) {\n\tchild, err := t.open(seek)\n\tif err != nil {\n\t\tif !errors.Is(err, context.Canceled) {\n\t\t\tt.errors <- err\n\t\t}\n\t\treturn\n\t}\n\n\tt.wg.Add(1)\n\tgo func() {\n\t\tdefer t.wg.Done()\n\t\tchild.runFile()\n\t}()\n}\n\n\/\/ runFile tails a file\nfunc (t *tail) runFile() {\n\tdefer t.watcher.Close()\n\tdefer t.cancel()\n\n\tcherr := make(chan error, 1)\n\tch := make(chan struct{}, 1)\n\tdefer close(ch)\n\n\tt.parent.wg.Add(1)\n\tgo func() {\n\t\tdefer t.parent.wg.Done()\n\t\tfor {\n\t\t\tif err := t.restrict(); err != nil {\n\t\t\t\tselect {\n\t\t\t\tcase cherr <- err:\n\t\t\t\tcase <-t.ctx.Done():\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr := t.tail()\n\t\t\tif err == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ wait for writing new lines.\n\t\t\tselect {\n\t\t\tcase cherr <- err:\n\t\t\tcase <-t.ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t\tselect {\n\t\t\tcase _, ok := <-ch:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-t.ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\tvar renamed bool\n\tvar waiting bool \/\/ waiting for writing new lines?\n\tfor {\n\t\tselect {\n\t\tcase event := <-t.watcher.Events:\n\t\t\tif event.Op.Has(fsnotify.Remove) {\n\t\t\t\t\/\/ the target file is removed, stop tailing.\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif event.Op.Has(fsnotify.Rename) {\n\t\t\t\t\/\/ log rotation is detected.\n\t\t\t\tif !renamed {\n\t\t\t\t\t\/\/ start to watch creating new file.\n\t\t\t\t\tt.parent.wg.Add(1)\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\tdefer t.parent.wg.Done()\n\t\t\t\t\t\tt.parent.runFile(io.SeekStart)\n\t\t\t\t\t}()\n\n\t\t\t\t\t\/\/ wait a little, and stop tailing old file.\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\ttimer := time.NewTimer(tailOldFileDelay)\n\t\t\t\t\t\tdefer timer.Stop()\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase <-timer.C:\n\t\t\t\t\t\t\tt.cancel()\n\t\t\t\t\t\tcase <-t.ctx.Done():\n\t\t\t\t\t\t}\n\t\t\t\t\t}()\n\t\t\t\t}\n\t\t\t\tname, err := getFileName(t.file)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.parent.errors <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err := t.watcher.Add(name); err != nil {\n\t\t\t\t\tt.parent.errors <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\trenamed = true\n\t\t\t}\n\n\t\t\t\/\/ notify new lines are wrote.\n\t\t\tif waiting {\n\t\t\t\tch <- struct{}{}\n\t\t\t\twaiting = false\n\t\t\t}\n\t\tcase err := <-cherr:\n\t\t\tif errors.Is(err, io.EOF) {\n\t\t\t\twaiting = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tt.parent.errors <- err\n\t\t\treturn\n\t\tcase err := <-t.watcher.Errors:\n\t\t\tt.parent.errors <- err\n\t\t\treturn\n\t\tcase <-t.ctx.Done():\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ runReader tails io.Reader\nfunc (t *tail) runReader() {\n\tdefer t.cancel()\n\terr := t.tail()\n\tif errors.Is(err, io.EOF) || errors.Is(err, io.ErrClosedPipe) {\n\t\treturn\n\t}\n\tif err != nil {\n\t\tif !errors.Is(err, context.Canceled) {\n\t\t\tt.parent.errors <- err\n\t\t}\n\t\treturn\n\t}\n}\n\n\/\/ restrict detects a file that is truncated\nfunc (t *tail) restrict() error {\n\tstat, err := t.file.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\tpos, err := t.file.Seek(0, io.SeekCurrent)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif stat.Size() < pos {\n\t\t\/\/ file is truncated. seek to head of file.\n\t\t_, err := t.file.Seek(0, io.SeekStart)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ tail reads lines until EOF\nfunc (t *tail) tail() error {\n\topts := t.parent.opts\n\tfor {\n\t\tline, err := t.reader.ReadSlice('\\n')\n\t\tt.buf.Write(line)\n\t\tif err == bufio.ErrBufferFull {\n\t\t\t\/\/ the reader cannot find EOL in its buffer.\n\t\t\t\/\/ continue to read a line.\n\t\t\tif opts.MaxBytesLine == 0 || int64(t.buf.Len()) < opts.MaxBytesLine {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tt.parent.lines <- &Line{t.buf.String(), time.Now()}\n\t\tt.buf.Reset()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\n\/\/ All actions under task command\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/url\"\n\t\"strconv\"\n)\n\ntype TaskList struct {\n\tclient *Client\n\tformat Formatter\n}\n\nfunc (t TaskList) Apply(args []string) {\n\tswitch len(args) {\n\tcase 0:\n\t\tt.listAll()\n\tcase 1:\n\t\tt.listById(args[0])\n\tdefault:\n\t\tCheck(false, \"too many arguments\")\n\t}\n}\n\nfunc (t TaskList) listAll() {\n\tpath := \"\/v2\/tasks\"\n\trequest := t.client.GET(path)\n\tresponse, e := t.client.Do(request)\n\tCheck(e == nil, \"failed to get response\", e)\n\tdefer response.Body.Close()\n\tfmt.Println(t.format.Format(response.Body, t.HumanizeAll))\n}\n\nfunc (t TaskList) HumanizeAll(body io.Reader) string {\n\tdec := json.NewDecoder(body)\n\tvar tasks Tasks\n\te := dec.Decode(&tasks)\n\tCheck(e == nil, \"failed to unmarshal response\", e)\n\tvar b bytes.Buffer\n\tfor _, task := range tasks.Tasks {\n\t\tb.WriteString(task.AppID)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(task.Host)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(task.Version)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(task.ID)\n\t\tb.WriteString(\"\\n\")\n\t}\n\ttitle := \"APPID HOST VERSION TASKID\\n\"\n\ttext := title + b.String()\n\treturn Columnize(text)\n}\n\nfunc (t TaskList) listById(id string) {\n\tesc := url.QueryEscape(id)\n\tpath := \"\/v2\/apps\/\" + esc + \"?embed=apps.tasks\"\n\trequest := t.client.GET(path)\n\tresponse, e := t.client.Do(request)\n\tCheck(e == nil, \"failed to get response\", e)\n\tdefer response.Body.Close()\n\tfmt.Println(t.format.Format(response.Body, t.HumanizeById))\n}\n\nfunc (t TaskList) HumanizeById(body io.Reader) string {\n\tdec := json.NewDecoder(body)\n\tvar appbyid AppById\n\te := dec.Decode(&appbyid)\n\tCheck(e == nil, \"failed to unmarshal response\", e)\n\n\tvar b bytes.Buffer\n\tfor _, task := range appbyid.App.Tasks {\n\t\tb.WriteString(task.ID)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(task.Host)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(task.Version)\n\t\t\/\/ ports?\n\t}\n\ttitle := \"ID HOST VERSION\\n\"\n\ttext := title + b.String()\n\treturn Columnize(text)\n}\n\ntype TaskKill struct {\n\tclient *Client\n\tformat Formatter\n}\n\nfunc (t TaskKill) Apply(args []string) {\n\tswitch len(args) {\n\tcase 1:\n\t\tt.killAll(args[0])\n\tcase 2:\n\t\tt.killOnly(args[0], args[1])\n\tdefault:\n\t\tCheck(false, \"task kill takes 1 or 2 arguments\")\n\t}\n}\n\nfunc (t TaskKill) killAll(id string) {\n\tesc := url.QueryEscape(id)\n\tpath := \"\/v2\/apps\/\" + esc + \"\/tasks\"\n\trequest := t.client.DELETE(path)\n\tresponse, e := t.client.Do(request)\n\tCheck(e == nil, \"failed to get response\", e)\n\tdefer response.Body.Close()\n\n\tsc := response.StatusCode\n\tCheck(sc != 404, \"unknown id\")\n\tCheck(sc == 200, \"failed with status code\", sc)\n\tt.format.Format(response.Body, t.Humanize)\n}\n\nfunc (t TaskKill) killOnly(id, taskid string) {\n\tescID := url.QueryEscape(id)\n\tescTaskID := url.QueryEscape(taskid)\n\tpath := \"\/v2\/apps\/\" + escID + \"\/tasks\/\" + escTaskID\n\trequest := t.client.DELETE(path)\n\tresponse, e := t.client.Do(request)\n\tCheck(e == nil, \"failed to get response\", e)\n\tdefer response.Body.Close()\n\tsc := response.StatusCode\n\tCheck(sc != 404, \"unknown appid or taskid\")\n\tCheck(sc == 200, \"failed with status code\", sc)\n\tt.format.Format(response.Body, t.Humanize)\n}\n\nfunc (t TaskKill) Humanize(body io.Reader) string {\n\t\/\/ todo does this actually return a list of killed tasks?\n\treturn \"success\"\n}\n\ntype TaskQueue struct {\n\tclient *Client\n\tformat Formatter\n}\n\nfunc (t TaskQueue) Apply(args []string) {\n\tCheck(len(args) == 0, \"no arguments\")\n\trequest := t.client.GET(\"\/v2\/queue\")\n\tresponse, e := t.client.Do(request)\n\tCheck(e == nil, \"failed to get response\", e)\n\tdefer response.Body.Close()\n\tfmt.Println(t.format.Format(response.Body, t.Humanize))\n}\n\nfunc (t TaskQueue) Humanize(body io.Reader) string {\n\tdec := json.NewDecoder(body)\n\tvar queue Queue\n\te := dec.Decode(&queue)\n\tCheck(e == nil, \"failed to decode response\", e)\n\ttitle := \"APP VERSION OVERDUE\\n\"\n\tvar b bytes.Buffer\n\tfor _, queuedTask := range queue.Queue {\n\t\tb.WriteString(queuedTask.App.ID)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(queuedTask.App.Version)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(strconv.FormatBool(queuedTask.Delay[\"overdue\"]))\n\t\tb.WriteString(\"\\n\")\n\t}\n\ttext := title + b.String()\n\treturn Columnize(text)\n}\n<commit_msg>Fixed formatting for task list<commit_after>package main\n\n\/\/ All actions under task command\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/url\"\n\t\"strconv\"\n)\n\ntype TaskList struct {\n\tclient *Client\n\tformat Formatter\n}\n\nfunc (t TaskList) Apply(args []string) {\n\tswitch len(args) {\n\tcase 0:\n\t\tt.listAll()\n\tcase 1:\n\t\tt.listById(args[0])\n\tdefault:\n\t\tCheck(false, \"too many arguments\")\n\t}\n}\n\nfunc (t TaskList) listAll() {\n\tpath := \"\/v2\/tasks\"\n\trequest := t.client.GET(path)\n\tresponse, e := t.client.Do(request)\n\tCheck(e == nil, \"failed to get response\", e)\n\tdefer response.Body.Close()\n\tfmt.Println(t.format.Format(response.Body, t.HumanizeAll))\n}\n\nfunc (t TaskList) HumanizeAll(body io.Reader) string {\n\tdec := json.NewDecoder(body)\n\tvar tasks Tasks\n\te := dec.Decode(&tasks)\n\tCheck(e == nil, \"failed to unmarshal response\", e)\n\tvar b bytes.Buffer\n\tfor _, task := range tasks.Tasks {\n\t\tb.WriteString(task.AppID)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(task.Host)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(task.Version)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(task.ID)\n\t\tb.WriteString(\"\\n\")\n\t}\n\ttitle := \"APPID HOST VERSION TASKID\\n\"\n\ttext := title + b.String()\n\treturn Columnize(text)\n}\n\nfunc (t TaskList) listById(id string) {\n\tesc := url.QueryEscape(id)\n\tpath := \"\/v2\/apps\/\" + esc + \"?embed=apps.tasks\"\n\trequest := t.client.GET(path)\n\tresponse, e := t.client.Do(request)\n\tCheck(e == nil, \"failed to get response\", e)\n\tdefer response.Body.Close()\n\tfmt.Println(t.format.Format(response.Body, t.HumanizeById))\n}\n\nfunc (t TaskList) HumanizeById(body io.Reader) string {\n\tdec := json.NewDecoder(body)\n\tvar appbyid AppById\n\te := dec.Decode(&appbyid)\n\tCheck(e == nil, \"failed to unmarshal response\", e)\n\n\tvar b bytes.Buffer\n\tfor _, task := range appbyid.App.Tasks {\n\t\tb.WriteString(task.ID)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(task.Host)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(task.Version)\n\t\tb.WriteString(\"\\n\")\n\t\t\/\/ ports?\n\t}\n\ttitle := \"ID HOST VERSION\\n\"\n\ttext := title + b.String()\n\treturn Columnize(text)\n}\n\ntype TaskKill struct {\n\tclient *Client\n\tformat Formatter\n}\n\nfunc (t TaskKill) Apply(args []string) {\n\tswitch len(args) {\n\tcase 1:\n\t\tt.killAll(args[0])\n\tcase 2:\n\t\tt.killOnly(args[0], args[1])\n\tdefault:\n\t\tCheck(false, \"task kill takes 1 or 2 arguments\")\n\t}\n}\n\nfunc (t TaskKill) killAll(id string) {\n\tesc := url.QueryEscape(id)\n\tpath := \"\/v2\/apps\/\" + esc + \"\/tasks\"\n\trequest := t.client.DELETE(path)\n\tresponse, e := t.client.Do(request)\n\tCheck(e == nil, \"failed to get response\", e)\n\tdefer response.Body.Close()\n\n\tsc := response.StatusCode\n\tCheck(sc != 404, \"unknown id\")\n\tCheck(sc == 200, \"failed with status code\", sc)\n\tt.format.Format(response.Body, t.Humanize)\n}\n\nfunc (t TaskKill) killOnly(id, taskid string) {\n\tescID := url.QueryEscape(id)\n\tescTaskID := url.QueryEscape(taskid)\n\tpath := \"\/v2\/apps\/\" + escID + \"\/tasks\/\" + escTaskID\n\trequest := t.client.DELETE(path)\n\tresponse, e := t.client.Do(request)\n\tCheck(e == nil, \"failed to get response\", e)\n\tdefer response.Body.Close()\n\tsc := response.StatusCode\n\tCheck(sc != 404, \"unknown appid or taskid\")\n\tCheck(sc == 200, \"failed with status code\", sc)\n\tt.format.Format(response.Body, t.Humanize)\n}\n\nfunc (t TaskKill) Humanize(body io.Reader) string {\n\t\/\/ todo does this actually return a list of killed tasks?\n\treturn \"success\"\n}\n\ntype TaskQueue struct {\n\tclient *Client\n\tformat Formatter\n}\n\nfunc (t TaskQueue) Apply(args []string) {\n\tCheck(len(args) == 0, \"no arguments\")\n\trequest := t.client.GET(\"\/v2\/queue\")\n\tresponse, e := t.client.Do(request)\n\tCheck(e == nil, \"failed to get response\", e)\n\tdefer response.Body.Close()\n\tfmt.Println(t.format.Format(response.Body, t.Humanize))\n}\n\nfunc (t TaskQueue) Humanize(body io.Reader) string {\n\tdec := json.NewDecoder(body)\n\tvar queue Queue\n\te := dec.Decode(&queue)\n\tCheck(e == nil, \"failed to decode response\", e)\n\ttitle := \"APP VERSION OVERDUE\\n\"\n\tvar b bytes.Buffer\n\tfor _, queuedTask := range queue.Queue {\n\t\tb.WriteString(queuedTask.App.ID)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(queuedTask.App.Version)\n\t\tb.WriteString(\" \")\n\t\tb.WriteString(strconv.FormatBool(queuedTask.Delay[\"overdue\"]))\n\t\tb.WriteString(\"\\n\")\n\t}\n\ttext := title + b.String()\n\treturn Columnize(text)\n}\n<|endoftext|>"}
{"text":"<commit_before>package tmsh\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\/\/ BigIP is a struct for session state\ntype BigIP struct {\n\thost    string\n\tuser    string\n\tsshconn SSH\n}\n\n\/\/ NewKeySession is NewSession plus key handling\nfunc NewKeySession(host, port, user string, key []byte) (*BigIP, error) {\n       return NewSession(host, port, user, \"\", key)\n}\n\n\/\/ NewSession sets up new SSH session to BIG-IP TMSH\nfunc NewSession(host, port, user, password string) (*BigIP, error) {\n\treturn GenSession(host,post,user,password,[]byte{})\n}\n\n\/\/ GenSession handles either Password or SSH Key based..\nfunc GenSession(host, port, user, password string, key []byte) (*BigIP, error) {\n    sshconn, err := newSSHConnection(host+\":\"+port, user, password, key)\n\t\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret, _ := sshconn.Recv(\"# \")\n\tif !strings.Contains(string(ret), \"(tmos)\") {\n\t\t_, err := sshconn.Send(\"tmsh\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tret, err = sshconn.Recv(\"# \")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbigip := &BigIP{\n\t\thost:    host,\n\t\tuser:    user,\n\t\tsshconn: sshconn,\n\t}\n\n\t\/\/ Suppress pager output\n\tif _, err := bigip.ExecuteCommand(\"modify cli preference pager disabled display-threshold 0\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bigip, nil\n}\n\n\/\/ ExecuteCommand is used to execute any TMSH commands\nfunc (bigip *BigIP) ExecuteCommand(cmd string) (string, error) {\n\tpromptSuffix := \"# \"\n\n\t_, err := bigip.sshconn.Send(cmd)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresults, err := bigip.sshconn.Recv(promptSuffix)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresults = removeCarriageReturn(results)\n\treader := bytes.NewReader(results)\n\tscanner := bufio.NewScanner(reader)\n\n\tvar lines []string\n\n\tfor scanner.Scan() {\n\t\ttext := scanner.Text()\n\t\tline := removeSpaceAndBackspace(text)\n\n\t\tif strings.HasPrefix(line, \"Last login:\") ||\n\t\t\tstrings.Contains(line, \"(tmos)\") ||\n\t\t\tstrings.HasPrefix(line, cmd) {\n\t\t\tcontinue\n\t\t}\n\n\t\tlines = append(lines, text)\n\t}\n\n\treturn strings.Join(lines, \"\\n\"), nil\n}\n\n\/\/ Save is used to execute 'save \/sys config' command\nfunc (bigip *BigIP) Save() error {\n\tret, err := bigip.ExecuteCommand(\"save \/sys config current-partition\")\n\tif err != nil {\n\t\tfmt.Errorf(ret)\n\t}\n\n\tif strings.Contains(ret, \"Syntax Error: \\\"current-partition\\\" unknown property\") {\n\t\tret, err = bigip.ExecuteCommand(\"save \/sys config\")\n\t\tif err != nil {\n\t\t\tfmt.Errorf(ret)\n\t\t}\n\t}\n\n\tif strings.Contains(ret, \"Error\") {\n\t\treturn fmt.Errorf(ret)\n\t}\n\n\treturn nil\n}\n\n\/\/ Close is used to close SSH session\nfunc (bigip *BigIP) Close() {\n\tbigip.sshconn.Close()\n}\n<commit_msg>Switch to GenSession<commit_after>package tmsh\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n\/\/ BigIP is a struct for session state\ntype BigIP struct {\n\thost    string\n\tuser    string\n\tsshconn SSH\n}\n\n\/\/ NewKeySession is NewSession plus key handling\nfunc NewKeySession(host, port, user string, key []byte) (*BigIP, error) {\n       return GenSession(host, port, user, \"\", key)\n}\n\n\/\/ NewSession sets up new SSH session to BIG-IP TMSH\nfunc NewSession(host, port, user, password string) (*BigIP, error) {\n\treturn GenSession(host,post,user,password,[]byte{})\n}\n\n\/\/ GenSession handles either Password or SSH Key based..\nfunc GenSession(host, port, user, password string, key []byte) (*BigIP, error) {\n    sshconn, err := newSSHConnection(host+\":\"+port, user, password, key)\n\t\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret, _ := sshconn.Recv(\"# \")\n\tif !strings.Contains(string(ret), \"(tmos)\") {\n\t\t_, err := sshconn.Send(\"tmsh\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tret, err = sshconn.Recv(\"# \")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tbigip := &BigIP{\n\t\thost:    host,\n\t\tuser:    user,\n\t\tsshconn: sshconn,\n\t}\n\n\t\/\/ Suppress pager output\n\tif _, err := bigip.ExecuteCommand(\"modify cli preference pager disabled display-threshold 0\"); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn bigip, nil\n}\n\n\/\/ ExecuteCommand is used to execute any TMSH commands\nfunc (bigip *BigIP) ExecuteCommand(cmd string) (string, error) {\n\tpromptSuffix := \"# \"\n\n\t_, err := bigip.sshconn.Send(cmd)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresults, err := bigip.sshconn.Recv(promptSuffix)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresults = removeCarriageReturn(results)\n\treader := bytes.NewReader(results)\n\tscanner := bufio.NewScanner(reader)\n\n\tvar lines []string\n\n\tfor scanner.Scan() {\n\t\ttext := scanner.Text()\n\t\tline := removeSpaceAndBackspace(text)\n\n\t\tif strings.HasPrefix(line, \"Last login:\") ||\n\t\t\tstrings.Contains(line, \"(tmos)\") ||\n\t\t\tstrings.HasPrefix(line, cmd) {\n\t\t\tcontinue\n\t\t}\n\n\t\tlines = append(lines, text)\n\t}\n\n\treturn strings.Join(lines, \"\\n\"), nil\n}\n\n\/\/ Save is used to execute 'save \/sys config' command\nfunc (bigip *BigIP) Save() error {\n\tret, err := bigip.ExecuteCommand(\"save \/sys config current-partition\")\n\tif err != nil {\n\t\tfmt.Errorf(ret)\n\t}\n\n\tif strings.Contains(ret, \"Syntax Error: \\\"current-partition\\\" unknown property\") {\n\t\tret, err = bigip.ExecuteCommand(\"save \/sys config\")\n\t\tif err != nil {\n\t\t\tfmt.Errorf(ret)\n\t\t}\n\t}\n\n\tif strings.Contains(ret, \"Error\") {\n\t\treturn fmt.Errorf(ret)\n\t}\n\n\treturn nil\n}\n\n\/\/ Close is used to close SSH session\nfunc (bigip *BigIP) Close() {\n\tbigip.sshconn.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014, Mauro Toffanin. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/toffanin\/go-todo\/commands\"\n\t\"github.com\/toffanin\/go-todo\/utils\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\/\/\"github.com\/fatih\/color\"\n)\n\nvar (\n\tappName = \"todo\"\n\n\t\/\/ The text template for the Default help topic\n\tappHelpTemplate = `\nNAME:\n   {{.Name}} - {{.Usage}}\n\nUSAGE:\n   [environment variables] {{.Name}} [global options] command [...]\n\nVERSION:\n   {{.Version}}\n\nCOMMANDS:\n   {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ \"\\t\" }}{{.Usage}}\n   {{end}}\nGLOBAL OPTIONS:\n   {{range .Flags}}{{.}}\n   {{end}}\nENVIRONMENT VARIABLES:\n   TODOTXT_AUTO_ARCHIVE=0,1{{\"\\t\"}}is equivalent to global options -a (0) \/ -A (1)\n   TODOTXT_CFG_FILE=CONFIG_FILE{{\"\\t\"}}is equivalent to global option -d CONFIG_FILE\n   TODOTXT_FORCE=1{{\"\\t\"}}is equivalent to global option -f\n   TODOTXT_PRESERVE_LINE_NUMBERS=0,1{{\"\\t\"}}is equivalent to global options -n (0) \/ -N (1)\n   TODOTXT_PLAIN=0,1{{\"\\t\"}}is equivalent to global options -p (1) \/ -c (0)\n   TODOTXT_DATE_ON_ADD=0,1{{\"\\t\"}}is equivalent to global options -t (1) \/ -T (0)\n   TODOTXT_VERBOSE=1{{ \"\\t\" }}is equivalent to global option -v\n   TODOTXT_DISABLE_FILTER=1{{ \"\\t\" }}is equivalent to global option -x\n   TODOTXT_DEFAULT_ACTION=\"\"{{ \"\\t\" }}run this when called with no arguments\n   TODOTXT_SORT_COMMAND=\"sort ...\"{{ \"\\t\" }}customize list output\n   TODOTXT_FINAL_FILTER=\"sed ...\"{{ \"\\t\" }}customize list after color, P@+ hiding\n   TODOTXT_SOURCEVAR=\\$DONE_FILE{{ \"\\t\" }}use another source for listcon, listproj\n\n`\n\n\t\/\/ The text template for the command help topic.\n\tcommandHelpTemplate = `\nNAME:\n   {{.Name}} - {{.Usage}}\n\nUSAGE:\n   ` + appName + ` {{.Name}} [options] [arguments...]\n\nDESCRIPTION:\n   {{.Description}}\n\nOPTIONS:\n   {{range .Flags}}{{.}}\n   {{end}}\n\n`\n)\n\nfunc main() {\n\n\t\/\/ Load Todo.txt CLI environment variables\n\tutils.LoadConfig()\n\n\t\/\/ Initialize the templates for help sections\n\tcli.AppHelpTemplate = appHelpTemplate\n\tcli.CommandHelpTemplate = commandHelpTemplate\n\n\t\/\/ Initialize the app CLI\n\tapp := cli.NewApp()\n\n\tapp.Name = appName\n\tapp.Usage = \"A simple and extensible utility for managing your todo.txt files\"\n\tapp.Version = \"1.0.1\"\n\tapp.Author = \"Mauro Toffanin\"\n\tapp.Email = \"toffanin.mauro@gmail.com\"\n\tapp.EnableBashCompletion = true\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolFlag{\"t\", \"Prefixes the current date to a task automatically when it's added\"},\n\t\tcli.BoolFlag{\"T\", \"Do not prefix the current date to a task automatically when it's added\"},\n\t\tcli.BoolFlag{\"f\", \"Forces actions without confirmation or interactive input\"},\n\t}\n\tapp.Commands = []cli.Command{\n\t\tcommands.GetEnv(),\n\t\tcommands.GetInit(),\n\t\tcommands.GetShorthelp(),\n\t\tcommands.GetAdd(),\n\t\tcommands.GetAddm(),\n\t\tcommands.GetList(),\n\t\t\/*{\n\t\t\tName:  \"status\",\n\t\t\tUsage: \"Obtain a summary of the todo.txt structure\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\"dest, d\", \"\", \"specifies a different destination path\"},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\/\/fmt.Println(\"status: \", c.Args().First())\n\t\t\t},\n\t\t},*\/\n\t}\n\n\tif err := app.Run(os.Args); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n<commit_msg>Print the name of the app in the command help section to avoid confusion<commit_after>\/\/ Copyright (c) 2014, Mauro Toffanin. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/toffanin\/go-todo\/commands\"\n\t\"github.com\/toffanin\/go-todo\/utils\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\/\/\"github.com\/fatih\/color\"\n)\n\nvar (\n\tappName = \"todo\"\n\n\t\/\/ The text template for the Default help topic\n\tappHelpTemplate = `\nNAME:\n   {{.Name}} - {{.Usage}}\n\nUSAGE:\n   [environment variables] {{.Name}} [global options] command [...]\n\nVERSION:\n   {{.Version}}\n\nCOMMANDS:\n   {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ \"\\t\" }}{{.Usage}}\n   {{end}}\nGLOBAL OPTIONS:\n   {{range .Flags}}{{.}}\n   {{end}}\nENVIRONMENT VARIABLES:\n   TODOTXT_AUTO_ARCHIVE=0,1{{\"\\t\"}}is equivalent to global options -a (0) \/ -A (1)\n   TODOTXT_CFG_FILE=CONFIG_FILE{{\"\\t\"}}is equivalent to global option -d CONFIG_FILE\n   TODOTXT_FORCE=1{{\"\\t\"}}is equivalent to global option -f\n   TODOTXT_PRESERVE_LINE_NUMBERS=0,1{{\"\\t\"}}is equivalent to global options -n (0) \/ -N (1)\n   TODOTXT_PLAIN=0,1{{\"\\t\"}}is equivalent to global options -p (1) \/ -c (0)\n   TODOTXT_DATE_ON_ADD=0,1{{\"\\t\"}}is equivalent to global options -t (1) \/ -T (0)\n   TODOTXT_VERBOSE=1{{ \"\\t\" }}is equivalent to global option -v\n   TODOTXT_DISABLE_FILTER=1{{ \"\\t\" }}is equivalent to global option -x\n   TODOTXT_DEFAULT_ACTION=\"\"{{ \"\\t\" }}run this when called with no arguments\n   TODOTXT_SORT_COMMAND=\"sort ...\"{{ \"\\t\" }}customize list output\n   TODOTXT_FINAL_FILTER=\"sed ...\"{{ \"\\t\" }}customize list after color, P@+ hiding\n   TODOTXT_SOURCEVAR=\\$DONE_FILE{{ \"\\t\" }}use another source for listcon, listproj\n\n`\n\n\t\/\/ The text template for the command help topic.\n\tcommandHelpTemplate = `\nNAME:\n   ` + appName + `\n\nCOMMAND:\n   {{.Name}} - {{.Usage}}\n\nUSAGE:\n   ` + appName + ` {{.Name}} [options] [arguments...]\n\nDESCRIPTION:\n   {{.Description}}\n\nOPTIONS:\n   {{range .Flags}}{{.}}\n   {{end}}\n\n`\n)\n\nfunc main() {\n\n\t\/\/ Load Todo.txt CLI environment variables\n\tutils.LoadConfig()\n\n\t\/\/ Initialize the templates for help sections\n\tcli.AppHelpTemplate = appHelpTemplate\n\tcli.CommandHelpTemplate = commandHelpTemplate\n\n\t\/\/ Initialize the app CLI\n\tapp := cli.NewApp()\n\n\tapp.Name = appName\n\tapp.Usage = \"A simple and extensible utility for managing your todo.txt files\"\n\tapp.Version = \"1.0.1\"\n\tapp.Author = \"Mauro Toffanin\"\n\tapp.Email = \"toffanin.mauro@gmail.com\"\n\tapp.EnableBashCompletion = true\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolFlag{\"t\", \"Prefixes the current date to a task automatically when it's added\"},\n\t\tcli.BoolFlag{\"T\", \"Do not prefix the current date to a task automatically when it's added\"},\n\t\tcli.BoolFlag{\"f\", \"Forces actions without confirmation or interactive input\"},\n\t}\n\tapp.Commands = []cli.Command{\n\t\tcommands.GetEnv(),\n\t\tcommands.GetInit(),\n\t\tcommands.GetShorthelp(),\n\t\tcommands.GetAdd(),\n\t\tcommands.GetAddm(),\n\t\tcommands.GetList(),\n\t\t\/*{\n\t\t\tName:  \"status\",\n\t\t\tUsage: \"Obtain a summary of the todo.txt structure\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\"dest, d\", \"\", \"specifies a different destination path\"},\n\t\t\t},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\/\/fmt.Println(\"status: \", c.Args().First())\n\t\t\t},\n\t\t},*\/\n\t}\n\n\tif err := app.Run(os.Args); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved.\n\/\/ Use of this source code is governed by a LGPLv2.1\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build linux\n\npackage lxc\n\n\/\/ #include <lxc\/lxccontainer.h>\nimport \"C\"\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ Verbosity type\ntype Verbosity int\n\nconst (\n\t\/\/ Quiet makes some API calls not to write anything to stdout\n\tQuiet Verbosity = 1 << iota\n\t\/\/ Verbose makes some API calls write to stdout\n\tVerbose\n)\n\n\/\/ BackendStore type specifies possible backend types.\ntype BackendStore int\n\nconst (\n\t\/\/ Btrfs backendstore type\n\tBtrfs BackendStore = iota + 1\n\t\/\/ Directory backendstore type\n\tDirectory\n\t\/\/ LVM backendstore type\n\tLVM\n\t\/\/ ZFS backendstore type\n\tZFS\n\t\/\/ Aufs backendstore type\n\tAufs\n\t\/\/ Overlayfs backendstore type\n\tOverlayfs\n\t\/\/ Loopback backendstore type\n\tLoopback\n\t\/\/ Best backendstore type\n\tBest\n)\n\n\/\/ BackendStore as string\nfunc (t BackendStore) String() string {\n\tswitch t {\n\tcase Directory:\n\t\treturn \"dir\"\n\tcase ZFS:\n\t\treturn \"zfs\"\n\tcase Btrfs:\n\t\treturn \"btrfs\"\n\tcase LVM:\n\t\treturn \"lvm\"\n\tcase Aufs:\n\t\treturn \"aufs\"\n\tcase Overlayfs:\n\t\treturn \"overlayfs\"\n\tcase Loopback:\n\t\treturn \"loopback\"\n\tcase Best:\n\t\treturn \"best\"\n\t}\n\treturn \"<INVALID>\"\n}\n\n\/\/ State type specifies possible container states.\ntype State int\n\nconst (\n\t\/\/ STOPPED means container is not running\n\tSTOPPED State = iota + 1\n\t\/\/ STARTING means container is starting\n\tSTARTING\n\t\/\/ RUNNING means container is running\n\tRUNNING\n\t\/\/ STOPPING means container is stopping\n\tSTOPPING\n\t\/\/ ABORTING means container is aborting\n\tABORTING\n\t\/\/ FREEZING means container is freezing\n\tFREEZING\n\t\/\/ FROZEN means containe is frozen\n\tFROZEN\n\t\/\/ THAWED means container is thawed\n\tTHAWED\n)\n\nvar stateMap = map[string]State{\n\t\"STOPPED\":  STOPPED,\n\t\"STARTING\": STARTING,\n\t\"RUNNING\":  RUNNING,\n\t\"STOPPING\": STOPPING,\n\t\"ABORTING\": ABORTING,\n\t\"FREEZING\": FREEZING,\n\t\"FROZEN\":   FROZEN,\n\t\"THAWED\":   THAWED,\n}\n\n\/\/ State as string\nfunc (t State) String() string {\n\tswitch t {\n\tcase STOPPED:\n\t\treturn \"STOPPED\"\n\tcase STARTING:\n\t\treturn \"STARTING\"\n\tcase RUNNING:\n\t\treturn \"RUNNING\"\n\tcase STOPPING:\n\t\treturn \"STOPPING\"\n\tcase ABORTING:\n\t\treturn \"ABORTING\"\n\tcase FREEZING:\n\t\treturn \"FREEZING\"\n\tcase FROZEN:\n\t\treturn \"FROZEN\"\n\tcase THAWED:\n\t\treturn \"THAWED\"\n\t}\n\treturn \"<INVALID>\"\n}\n\n\/\/ Taken from http:\/\/golang.org\/doc\/effective_go.html#constants\n\n\/\/ ByteSize type\ntype ByteSize float64\n\nconst (\n\t_ = iota\n\t\/\/ KB - kilobyte\n\tKB ByteSize = 1 << (10 * iota)\n\t\/\/ MB - megabyte\n\tMB\n\t\/\/ GB - gigabyte\n\tGB\n\t\/\/ TB - terabyte\n\tTB\n\t\/\/ PB - petabyte\n\tPB\n\t\/\/ EB - exabyte\n\tEB\n\t\/\/ ZB - zettabyte\n\tZB\n\t\/\/ YB - yottabyte\n\tYB\n)\n\nfunc (b ByteSize) String() string {\n\tswitch {\n\tcase b >= YB:\n\t\treturn fmt.Sprintf(\"%.2fYB\", b\/YB)\n\tcase b >= ZB:\n\t\treturn fmt.Sprintf(\"%.2fZB\", b\/ZB)\n\tcase b >= EB:\n\t\treturn fmt.Sprintf(\"%.2fEB\", b\/EB)\n\tcase b >= PB:\n\t\treturn fmt.Sprintf(\"%.2fPB\", b\/PB)\n\tcase b >= TB:\n\t\treturn fmt.Sprintf(\"%.2fTB\", b\/TB)\n\tcase b >= GB:\n\t\treturn fmt.Sprintf(\"%.2fGB\", b\/GB)\n\tcase b >= MB:\n\t\treturn fmt.Sprintf(\"%.2fMB\", b\/MB)\n\tcase b >= KB:\n\t\treturn fmt.Sprintf(\"%.2fKB\", b\/KB)\n\t}\n\treturn fmt.Sprintf(\"%.2fB\", b)\n}\n\n\/\/ LogLevel type specifies possible log levels.\ntype LogLevel int\n\nconst (\n\t\/\/ TRACE priority\n\tTRACE LogLevel = iota\n\t\/\/ DEBUG priority\n\tDEBUG\n\t\/\/ INFO priority\n\tINFO\n\t\/\/ NOTICE priority\n\tNOTICE\n\t\/\/ WARN priority\n\tWARN\n\t\/\/ ERROR priority\n\tERROR\n\t\/\/ CRIT priority\n\tCRIT\n\t\/\/ ALERT priority\n\tALERT\n\t\/\/ FATAL priority\n\tFATAL\n)\n\nvar logLevelMap = map[string]LogLevel{\n\t\"TRACE\":  TRACE,\n\t\"DEBUG\":  DEBUG,\n\t\"INFO\":   INFO,\n\t\"NOTICE\": NOTICE,\n\t\"WARN\":   WARN,\n\t\"ERROR\":  ERROR,\n\t\"CRIT\":   CRIT,\n\t\"ALERT\":  ALERT,\n\t\"FATAL\":  FATAL,\n}\n\nfunc (l LogLevel) String() string {\n\tswitch l {\n\tcase TRACE:\n\t\treturn \"TRACE\"\n\tcase DEBUG:\n\t\treturn \"DEBUG\"\n\tcase INFO:\n\t\treturn \"INFO\"\n\tcase NOTICE:\n\t\treturn \"NOTICE\"\n\tcase WARN:\n\t\treturn \"WARN\"\n\tcase ERROR:\n\t\treturn \"ERROR\"\n\tcase CRIT:\n\t\treturn \"CRIT\"\n\tcase ALERT:\n\t\treturn \"ALERT\"\n\tcase FATAL:\n\t\treturn \"FATAL\"\n\t}\n\treturn \"NOTSET\"\n}\n\n\/\/ CloneFlags type\ntype CloneFlags int\n\nconst (\n\t\/\/ CloneKeepName means do not edit the rootfs to change the hostname\n\tCloneKeepName CloneFlags = 1 << iota\n\t\/\/ CloneKeepMACAddr means do not change the mac address on network interfaces\n\tCloneKeepMACAddr\n\t\/\/ CloneSnapshot means snapshot the original filesystem(s)\n\tCloneSnapshot\n\t\/\/ CloneKeepBdevType means use the same bdev type\n\tCloneKeepBdevType\n\t\/\/ CloneMaybeSnapshot means snapshot only if bdev supports it, else copy\n\tCloneMaybeSnapshot\n)\n\ntype Personality int64\n\nconst (\n\tX86    = 0x0008\n\tX86_64 = 0x0000\n)\n<commit_msg>use the Personality type<commit_after>\/\/ Copyright © 2013, 2014, The Go-LXC Authors. All rights reserved.\n\/\/ Use of this source code is governed by a LGPLv2.1\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build linux\n\npackage lxc\n\n\/\/ #include <lxc\/lxccontainer.h>\nimport \"C\"\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ Verbosity type\ntype Verbosity int\n\nconst (\n\t\/\/ Quiet makes some API calls not to write anything to stdout\n\tQuiet Verbosity = 1 << iota\n\t\/\/ Verbose makes some API calls write to stdout\n\tVerbose\n)\n\n\/\/ BackendStore type specifies possible backend types.\ntype BackendStore int\n\nconst (\n\t\/\/ Btrfs backendstore type\n\tBtrfs BackendStore = iota + 1\n\t\/\/ Directory backendstore type\n\tDirectory\n\t\/\/ LVM backendstore type\n\tLVM\n\t\/\/ ZFS backendstore type\n\tZFS\n\t\/\/ Aufs backendstore type\n\tAufs\n\t\/\/ Overlayfs backendstore type\n\tOverlayfs\n\t\/\/ Loopback backendstore type\n\tLoopback\n\t\/\/ Best backendstore type\n\tBest\n)\n\n\/\/ BackendStore as string\nfunc (t BackendStore) String() string {\n\tswitch t {\n\tcase Directory:\n\t\treturn \"dir\"\n\tcase ZFS:\n\t\treturn \"zfs\"\n\tcase Btrfs:\n\t\treturn \"btrfs\"\n\tcase LVM:\n\t\treturn \"lvm\"\n\tcase Aufs:\n\t\treturn \"aufs\"\n\tcase Overlayfs:\n\t\treturn \"overlayfs\"\n\tcase Loopback:\n\t\treturn \"loopback\"\n\tcase Best:\n\t\treturn \"best\"\n\t}\n\treturn \"<INVALID>\"\n}\n\n\/\/ State type specifies possible container states.\ntype State int\n\nconst (\n\t\/\/ STOPPED means container is not running\n\tSTOPPED State = iota + 1\n\t\/\/ STARTING means container is starting\n\tSTARTING\n\t\/\/ RUNNING means container is running\n\tRUNNING\n\t\/\/ STOPPING means container is stopping\n\tSTOPPING\n\t\/\/ ABORTING means container is aborting\n\tABORTING\n\t\/\/ FREEZING means container is freezing\n\tFREEZING\n\t\/\/ FROZEN means containe is frozen\n\tFROZEN\n\t\/\/ THAWED means container is thawed\n\tTHAWED\n)\n\nvar stateMap = map[string]State{\n\t\"STOPPED\":  STOPPED,\n\t\"STARTING\": STARTING,\n\t\"RUNNING\":  RUNNING,\n\t\"STOPPING\": STOPPING,\n\t\"ABORTING\": ABORTING,\n\t\"FREEZING\": FREEZING,\n\t\"FROZEN\":   FROZEN,\n\t\"THAWED\":   THAWED,\n}\n\n\/\/ State as string\nfunc (t State) String() string {\n\tswitch t {\n\tcase STOPPED:\n\t\treturn \"STOPPED\"\n\tcase STARTING:\n\t\treturn \"STARTING\"\n\tcase RUNNING:\n\t\treturn \"RUNNING\"\n\tcase STOPPING:\n\t\treturn \"STOPPING\"\n\tcase ABORTING:\n\t\treturn \"ABORTING\"\n\tcase FREEZING:\n\t\treturn \"FREEZING\"\n\tcase FROZEN:\n\t\treturn \"FROZEN\"\n\tcase THAWED:\n\t\treturn \"THAWED\"\n\t}\n\treturn \"<INVALID>\"\n}\n\n\/\/ Taken from http:\/\/golang.org\/doc\/effective_go.html#constants\n\n\/\/ ByteSize type\ntype ByteSize float64\n\nconst (\n\t_ = iota\n\t\/\/ KB - kilobyte\n\tKB ByteSize = 1 << (10 * iota)\n\t\/\/ MB - megabyte\n\tMB\n\t\/\/ GB - gigabyte\n\tGB\n\t\/\/ TB - terabyte\n\tTB\n\t\/\/ PB - petabyte\n\tPB\n\t\/\/ EB - exabyte\n\tEB\n\t\/\/ ZB - zettabyte\n\tZB\n\t\/\/ YB - yottabyte\n\tYB\n)\n\nfunc (b ByteSize) String() string {\n\tswitch {\n\tcase b >= YB:\n\t\treturn fmt.Sprintf(\"%.2fYB\", b\/YB)\n\tcase b >= ZB:\n\t\treturn fmt.Sprintf(\"%.2fZB\", b\/ZB)\n\tcase b >= EB:\n\t\treturn fmt.Sprintf(\"%.2fEB\", b\/EB)\n\tcase b >= PB:\n\t\treturn fmt.Sprintf(\"%.2fPB\", b\/PB)\n\tcase b >= TB:\n\t\treturn fmt.Sprintf(\"%.2fTB\", b\/TB)\n\tcase b >= GB:\n\t\treturn fmt.Sprintf(\"%.2fGB\", b\/GB)\n\tcase b >= MB:\n\t\treturn fmt.Sprintf(\"%.2fMB\", b\/MB)\n\tcase b >= KB:\n\t\treturn fmt.Sprintf(\"%.2fKB\", b\/KB)\n\t}\n\treturn fmt.Sprintf(\"%.2fB\", b)\n}\n\n\/\/ LogLevel type specifies possible log levels.\ntype LogLevel int\n\nconst (\n\t\/\/ TRACE priority\n\tTRACE LogLevel = iota\n\t\/\/ DEBUG priority\n\tDEBUG\n\t\/\/ INFO priority\n\tINFO\n\t\/\/ NOTICE priority\n\tNOTICE\n\t\/\/ WARN priority\n\tWARN\n\t\/\/ ERROR priority\n\tERROR\n\t\/\/ CRIT priority\n\tCRIT\n\t\/\/ ALERT priority\n\tALERT\n\t\/\/ FATAL priority\n\tFATAL\n)\n\nvar logLevelMap = map[string]LogLevel{\n\t\"TRACE\":  TRACE,\n\t\"DEBUG\":  DEBUG,\n\t\"INFO\":   INFO,\n\t\"NOTICE\": NOTICE,\n\t\"WARN\":   WARN,\n\t\"ERROR\":  ERROR,\n\t\"CRIT\":   CRIT,\n\t\"ALERT\":  ALERT,\n\t\"FATAL\":  FATAL,\n}\n\nfunc (l LogLevel) String() string {\n\tswitch l {\n\tcase TRACE:\n\t\treturn \"TRACE\"\n\tcase DEBUG:\n\t\treturn \"DEBUG\"\n\tcase INFO:\n\t\treturn \"INFO\"\n\tcase NOTICE:\n\t\treturn \"NOTICE\"\n\tcase WARN:\n\t\treturn \"WARN\"\n\tcase ERROR:\n\t\treturn \"ERROR\"\n\tcase CRIT:\n\t\treturn \"CRIT\"\n\tcase ALERT:\n\t\treturn \"ALERT\"\n\tcase FATAL:\n\t\treturn \"FATAL\"\n\t}\n\treturn \"NOTSET\"\n}\n\n\/\/ CloneFlags type\ntype CloneFlags int\n\nconst (\n\t\/\/ CloneKeepName means do not edit the rootfs to change the hostname\n\tCloneKeepName CloneFlags = 1 << iota\n\t\/\/ CloneKeepMACAddr means do not change the mac address on network interfaces\n\tCloneKeepMACAddr\n\t\/\/ CloneSnapshot means snapshot the original filesystem(s)\n\tCloneSnapshot\n\t\/\/ CloneKeepBdevType means use the same bdev type\n\tCloneKeepBdevType\n\t\/\/ CloneMaybeSnapshot means snapshot only if bdev supports it, else copy\n\tCloneMaybeSnapshot\n)\n\ntype Personality int64\n\nconst (\n\tX86    Personality = 0x0008\n\tX86_64             = 0x0000\n)\n<|endoftext|>"}
{"text":"<commit_before>package core\n\nimport (\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tPOSTGRES = \"postgres\"\n\tSQLITE   = \"sqlite3\"\n\tMYSQL    = \"mysql\"\n\tMSSQL    = \"mssql\"\n\tORACLE   = \"oracle\"\n)\n\n\/\/ xorm SQL types\ntype SQLType struct {\n\tName           string\n\tDefaultLength  int\n\tDefaultLength2 int\n}\n\nconst (\n\tUNKNOW_TYPE = iota\n\tTEXT_TYPE\n\tBLOB_TYPE\n\tTIME_TYPE\n\tNUMERIC_TYPE\n)\n\nfunc (s *SQLType) IsType(st int) bool {\n\tif t, ok := SqlTypes[s.Name]; ok && t == st {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *SQLType) IsText() bool {\n\treturn s.IsType(TEXT_TYPE)\n}\n\nfunc (s *SQLType) IsBlob() bool {\n\treturn s.IsType(BLOB_TYPE)\n}\n\nfunc (s *SQLType) IsTime() bool {\n\treturn s.IsType(TIME_TYPE)\n}\n\nfunc (s *SQLType) IsNumeric() bool {\n\treturn s.IsType(NUMERIC_TYPE)\n}\n\nfunc (s *SQLType) IsJson() bool {\n\treturn s.Name == Json || s.Name == Jsonb\n}\n\nvar (\n\tBit       = \"BIT\"\n\tTinyInt   = \"TINYINT\"\n\tSmallInt  = \"SMALLINT\"\n\tMediumInt = \"MEDIUMINT\"\n\tInt       = \"INT\"\n\tInteger   = \"INTEGER\"\n\tBigInt    = \"BIGINT\"\n\n\tEnum = \"ENUM\"\n\tSet  = \"SET\"\n\n\tChar       = \"CHAR\"\n\tVarchar    = \"VARCHAR\"\n\tNVarchar   = \"NVARCHAR\"\n\tTinyText   = \"TINYTEXT\"\n\tText       = \"TEXT\"\n\tClob       = \"CLOB\"\n\tMediumText = \"MEDIUMTEXT\"\n\tLongText   = \"LONGTEXT\"\n\tUuid       = \"UUID\"\n\n\tDate       = \"DATE\"\n\tDateTime   = \"DATETIME\"\n\tTime       = \"TIME\"\n\tTimeStamp  = \"TIMESTAMP\"\n\tTimeStampz = \"TIMESTAMPZ\"\n\n\tDecimal = \"DECIMAL\"\n\tNumeric = \"NUMERIC\"\n\n\tReal   = \"REAL\"\n\tFloat  = \"FLOAT\"\n\tDouble = \"DOUBLE\"\n\n\tBinary     = \"BINARY\"\n\tVarBinary  = \"VARBINARY\"\n\tTinyBlob   = \"TINYBLOB\"\n\tBlob       = \"BLOB\"\n\tMediumBlob = \"MEDIUMBLOB\"\n\tLongBlob   = \"LONGBLOB\"\n\tBytea      = \"BYTEA\"\n\n\tBool    = \"BOOL\"\n\tBoolean = \"BOOLEAN\"\n\n\tSerial    = \"SERIAL\"\n\tBigSerial = \"BIGSERIAL\"\n\n\tJson  = \"JSON\"\n\tJsonb = \"JSONB\"\n\n\tSqlTypes = map[string]int{\n\t\tBit:       NUMERIC_TYPE,\n\t\tTinyInt:   NUMERIC_TYPE,\n\t\tSmallInt:  NUMERIC_TYPE,\n\t\tMediumInt: NUMERIC_TYPE,\n\t\tInt:       NUMERIC_TYPE,\n\t\tInteger:   NUMERIC_TYPE,\n\t\tBigInt:    NUMERIC_TYPE,\n\n\t\tEnum:  TEXT_TYPE,\n\t\tSet:   TEXT_TYPE,\n\t\tJson:  TEXT_TYPE,\n\t\tJsonb: TEXT_TYPE,\n\n\t\tChar:       TEXT_TYPE,\n\t\tVarchar:    TEXT_TYPE,\n\t\tNVarchar:   TEXT_TYPE,\n\t\tTinyText:   TEXT_TYPE,\n\t\tText:       TEXT_TYPE,\n\t\tMediumText: TEXT_TYPE,\n\t\tLongText:   TEXT_TYPE,\n\t\tUuid:       TEXT_TYPE,\n\t\tClob:       TEXT_TYPE,\n\n\t\tDate:       TIME_TYPE,\n\t\tDateTime:   TIME_TYPE,\n\t\tTime:       TIME_TYPE,\n\t\tTimeStamp:  TIME_TYPE,\n\t\tTimeStampz: TIME_TYPE,\n\n\t\tDecimal: NUMERIC_TYPE,\n\t\tNumeric: NUMERIC_TYPE,\n\t\tReal:    NUMERIC_TYPE,\n\t\tFloat:   NUMERIC_TYPE,\n\t\tDouble:  NUMERIC_TYPE,\n\n\t\tBinary:    BLOB_TYPE,\n\t\tVarBinary: BLOB_TYPE,\n\n\t\tTinyBlob:   BLOB_TYPE,\n\t\tBlob:       BLOB_TYPE,\n\t\tMediumBlob: BLOB_TYPE,\n\t\tLongBlob:   BLOB_TYPE,\n\t\tBytea:      BLOB_TYPE,\n\n\t\tBool: NUMERIC_TYPE,\n\n\t\tSerial:    NUMERIC_TYPE,\n\t\tBigSerial: NUMERIC_TYPE,\n\t}\n\n\tintTypes  = sort.StringSlice{\"*int\", \"*int16\", \"*int32\", \"*int8\"}\n\tuintTypes = sort.StringSlice{\"*uint\", \"*uint16\", \"*uint32\", \"*uint8\"}\n)\n\n\/\/ !nashtsai! treat following var as interal const values, these are used for reflect.TypeOf comparison\nvar (\n\tc_EMPTY_STRING       string\n\tc_BOOL_DEFAULT       bool\n\tc_BYTE_DEFAULT       byte\n\tc_COMPLEX64_DEFAULT  complex64\n\tc_COMPLEX128_DEFAULT complex128\n\tc_FLOAT32_DEFAULT    float32\n\tc_FLOAT64_DEFAULT    float64\n\tc_INT64_DEFAULT      int64\n\tc_UINT64_DEFAULT     uint64\n\tc_INT32_DEFAULT      int32\n\tc_UINT32_DEFAULT     uint32\n\tc_INT16_DEFAULT      int16\n\tc_UINT16_DEFAULT     uint16\n\tc_INT8_DEFAULT       int8\n\tc_UINT8_DEFAULT      uint8\n\tc_INT_DEFAULT        int\n\tc_UINT_DEFAULT       uint\n\tc_TIME_DEFAULT       time.Time\n)\n\nvar (\n\tIntType   = reflect.TypeOf(c_INT_DEFAULT)\n\tInt8Type  = reflect.TypeOf(c_INT8_DEFAULT)\n\tInt16Type = reflect.TypeOf(c_INT16_DEFAULT)\n\tInt32Type = reflect.TypeOf(c_INT32_DEFAULT)\n\tInt64Type = reflect.TypeOf(c_INT64_DEFAULT)\n\n\tUintType   = reflect.TypeOf(c_UINT_DEFAULT)\n\tUint8Type  = reflect.TypeOf(c_UINT8_DEFAULT)\n\tUint16Type = reflect.TypeOf(c_UINT16_DEFAULT)\n\tUint32Type = reflect.TypeOf(c_UINT32_DEFAULT)\n\tUint64Type = reflect.TypeOf(c_UINT64_DEFAULT)\n\n\tFloat32Type = reflect.TypeOf(c_FLOAT32_DEFAULT)\n\tFloat64Type = reflect.TypeOf(c_FLOAT64_DEFAULT)\n\n\tComplex64Type  = reflect.TypeOf(c_COMPLEX64_DEFAULT)\n\tComplex128Type = reflect.TypeOf(c_COMPLEX128_DEFAULT)\n\n\tStringType = reflect.TypeOf(c_EMPTY_STRING)\n\tBoolType   = reflect.TypeOf(c_BOOL_DEFAULT)\n\tByteType   = reflect.TypeOf(c_BYTE_DEFAULT)\n\tBytesType  = reflect.SliceOf(ByteType)\n\n\tTimeType = reflect.TypeOf(c_TIME_DEFAULT)\n)\n\nvar (\n\tPtrIntType   = reflect.PtrTo(IntType)\n\tPtrInt8Type  = reflect.PtrTo(Int8Type)\n\tPtrInt16Type = reflect.PtrTo(Int16Type)\n\tPtrInt32Type = reflect.PtrTo(Int32Type)\n\tPtrInt64Type = reflect.PtrTo(Int64Type)\n\n\tPtrUintType   = reflect.PtrTo(UintType)\n\tPtrUint8Type  = reflect.PtrTo(Uint8Type)\n\tPtrUint16Type = reflect.PtrTo(Uint16Type)\n\tPtrUint32Type = reflect.PtrTo(Uint32Type)\n\tPtrUint64Type = reflect.PtrTo(Uint64Type)\n\n\tPtrFloat32Type = reflect.PtrTo(Float32Type)\n\tPtrFloat64Type = reflect.PtrTo(Float64Type)\n\n\tPtrComplex64Type  = reflect.PtrTo(Complex64Type)\n\tPtrComplex128Type = reflect.PtrTo(Complex128Type)\n\n\tPtrStringType = reflect.PtrTo(StringType)\n\tPtrBoolType   = reflect.PtrTo(BoolType)\n\tPtrByteType   = reflect.PtrTo(ByteType)\n\n\tPtrTimeType = reflect.PtrTo(TimeType)\n)\n\n\/\/ Type2SQLType generate SQLType acorrding Go's type\nfunc Type2SQLType(t reflect.Type) (st SQLType) {\n\tswitch k := t.Kind(); k {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:\n\t\tst = SQLType{Int, 0, 0}\n\tcase reflect.Int64, reflect.Uint64:\n\t\tst = SQLType{BigInt, 0, 0}\n\tcase reflect.Float32:\n\t\tst = SQLType{Float, 0, 0}\n\tcase reflect.Float64:\n\t\tst = SQLType{Double, 0, 0}\n\tcase reflect.Complex64, reflect.Complex128:\n\t\tst = SQLType{Varchar, 64, 0}\n\tcase reflect.Array, reflect.Slice, reflect.Map:\n\t\tif t.Elem() == reflect.TypeOf(c_BYTE_DEFAULT) {\n\t\t\tst = SQLType{Blob, 0, 0}\n\t\t} else {\n\t\t\tst = SQLType{Text, 0, 0}\n\t\t}\n\tcase reflect.Bool:\n\t\tst = SQLType{Bool, 0, 0}\n\tcase reflect.String:\n\t\tst = SQLType{Varchar, 255, 0}\n\tcase reflect.Struct:\n\t\tif t.ConvertibleTo(TimeType) {\n\t\t\tst = SQLType{DateTime, 0, 0}\n\t\t} else {\n\t\t\t\/\/ TODO need to handle association struct\n\t\t\tst = SQLType{Text, 0, 0}\n\t\t}\n\tcase reflect.Ptr:\n\t\tst = Type2SQLType(t.Elem())\n\tdefault:\n\t\tst = SQLType{Text, 0, 0}\n\t}\n\treturn\n}\n\n\/\/ default sql type change to go types\nfunc SQLType2Type(st SQLType) reflect.Type {\n\tname := strings.ToUpper(st.Name)\n\tswitch name {\n\tcase Bit, TinyInt, SmallInt, MediumInt, Int, Integer, Serial:\n\t\treturn reflect.TypeOf(1)\n\tcase BigInt, BigSerial:\n\t\treturn reflect.TypeOf(int64(1))\n\tcase Float, Real:\n\t\treturn reflect.TypeOf(float32(1))\n\tcase Double:\n\t\treturn reflect.TypeOf(float64(1))\n\tcase Char, Varchar, NVarchar, TinyText, Text, MediumText, LongText, Enum, Set, Uuid, Clob:\n\t\treturn reflect.TypeOf(\"\")\n\tcase TinyBlob, Blob, LongBlob, Bytea, Binary, MediumBlob, VarBinary:\n\t\treturn reflect.TypeOf([]byte{})\n\tcase Bool:\n\t\treturn reflect.TypeOf(true)\n\tcase DateTime, Date, Time, TimeStamp, TimeStampz:\n\t\treturn reflect.TypeOf(c_TIME_DEFAULT)\n\tcase Decimal, Numeric:\n\t\treturn reflect.TypeOf(\"\")\n\tdefault:\n\t\treturn reflect.TypeOf(\"\")\n\t}\n}\n<commit_msg>add UniqueIdentifier type for supporting mssql<commit_after>package core\n\nimport (\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tPOSTGRES = \"postgres\"\n\tSQLITE   = \"sqlite3\"\n\tMYSQL    = \"mysql\"\n\tMSSQL    = \"mssql\"\n\tORACLE   = \"oracle\"\n)\n\n\/\/ xorm SQL types\ntype SQLType struct {\n\tName           string\n\tDefaultLength  int\n\tDefaultLength2 int\n}\n\nconst (\n\tUNKNOW_TYPE = iota\n\tTEXT_TYPE\n\tBLOB_TYPE\n\tTIME_TYPE\n\tNUMERIC_TYPE\n)\n\nfunc (s *SQLType) IsType(st int) bool {\n\tif t, ok := SqlTypes[s.Name]; ok && t == st {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *SQLType) IsText() bool {\n\treturn s.IsType(TEXT_TYPE)\n}\n\nfunc (s *SQLType) IsBlob() bool {\n\treturn s.IsType(BLOB_TYPE)\n}\n\nfunc (s *SQLType) IsTime() bool {\n\treturn s.IsType(TIME_TYPE)\n}\n\nfunc (s *SQLType) IsNumeric() bool {\n\treturn s.IsType(NUMERIC_TYPE)\n}\n\nfunc (s *SQLType) IsJson() bool {\n\treturn s.Name == Json || s.Name == Jsonb\n}\n\nvar (\n\tBit       = \"BIT\"\n\tTinyInt   = \"TINYINT\"\n\tSmallInt  = \"SMALLINT\"\n\tMediumInt = \"MEDIUMINT\"\n\tInt       = \"INT\"\n\tInteger   = \"INTEGER\"\n\tBigInt    = \"BIGINT\"\n\n\tEnum = \"ENUM\"\n\tSet  = \"SET\"\n\n\tChar             = \"CHAR\"\n\tVarchar          = \"VARCHAR\"\n\tNVarchar         = \"NVARCHAR\"\n\tTinyText         = \"TINYTEXT\"\n\tText             = \"TEXT\"\n\tClob             = \"CLOB\"\n\tMediumText       = \"MEDIUMTEXT\"\n\tLongText         = \"LONGTEXT\"\n\tUuid             = \"UUID\"\n\tUniqueIdentifier = \"UNIQUEIDENTIFIER\"\n\n\tDate       = \"DATE\"\n\tDateTime   = \"DATETIME\"\n\tTime       = \"TIME\"\n\tTimeStamp  = \"TIMESTAMP\"\n\tTimeStampz = \"TIMESTAMPZ\"\n\n\tDecimal = \"DECIMAL\"\n\tNumeric = \"NUMERIC\"\n\n\tReal   = \"REAL\"\n\tFloat  = \"FLOAT\"\n\tDouble = \"DOUBLE\"\n\n\tBinary     = \"BINARY\"\n\tVarBinary  = \"VARBINARY\"\n\tTinyBlob   = \"TINYBLOB\"\n\tBlob       = \"BLOB\"\n\tMediumBlob = \"MEDIUMBLOB\"\n\tLongBlob   = \"LONGBLOB\"\n\tBytea      = \"BYTEA\"\n\n\tBool    = \"BOOL\"\n\tBoolean = \"BOOLEAN\"\n\n\tSerial    = \"SERIAL\"\n\tBigSerial = \"BIGSERIAL\"\n\n\tJson  = \"JSON\"\n\tJsonb = \"JSONB\"\n\n\tSqlTypes = map[string]int{\n\t\tBit:       NUMERIC_TYPE,\n\t\tTinyInt:   NUMERIC_TYPE,\n\t\tSmallInt:  NUMERIC_TYPE,\n\t\tMediumInt: NUMERIC_TYPE,\n\t\tInt:       NUMERIC_TYPE,\n\t\tInteger:   NUMERIC_TYPE,\n\t\tBigInt:    NUMERIC_TYPE,\n\n\t\tEnum:  TEXT_TYPE,\n\t\tSet:   TEXT_TYPE,\n\t\tJson:  TEXT_TYPE,\n\t\tJsonb: TEXT_TYPE,\n\n\t\tChar:       TEXT_TYPE,\n\t\tVarchar:    TEXT_TYPE,\n\t\tNVarchar:   TEXT_TYPE,\n\t\tTinyText:   TEXT_TYPE,\n\t\tText:       TEXT_TYPE,\n\t\tMediumText: TEXT_TYPE,\n\t\tLongText:   TEXT_TYPE,\n\t\tUuid:       TEXT_TYPE,\n\t\tClob:       TEXT_TYPE,\n\n\t\tDate:       TIME_TYPE,\n\t\tDateTime:   TIME_TYPE,\n\t\tTime:       TIME_TYPE,\n\t\tTimeStamp:  TIME_TYPE,\n\t\tTimeStampz: TIME_TYPE,\n\n\t\tDecimal: NUMERIC_TYPE,\n\t\tNumeric: NUMERIC_TYPE,\n\t\tReal:    NUMERIC_TYPE,\n\t\tFloat:   NUMERIC_TYPE,\n\t\tDouble:  NUMERIC_TYPE,\n\n\t\tBinary:    BLOB_TYPE,\n\t\tVarBinary: BLOB_TYPE,\n\n\t\tTinyBlob:         BLOB_TYPE,\n\t\tBlob:             BLOB_TYPE,\n\t\tMediumBlob:       BLOB_TYPE,\n\t\tLongBlob:         BLOB_TYPE,\n\t\tBytea:            BLOB_TYPE,\n\t\tUniqueIdentifier: BLOB_TYPE,\n\n\t\tBool: NUMERIC_TYPE,\n\n\t\tSerial:    NUMERIC_TYPE,\n\t\tBigSerial: NUMERIC_TYPE,\n\t}\n\n\tintTypes  = sort.StringSlice{\"*int\", \"*int16\", \"*int32\", \"*int8\"}\n\tuintTypes = sort.StringSlice{\"*uint\", \"*uint16\", \"*uint32\", \"*uint8\"}\n)\n\n\/\/ !nashtsai! treat following var as interal const values, these are used for reflect.TypeOf comparison\nvar (\n\tc_EMPTY_STRING       string\n\tc_BOOL_DEFAULT       bool\n\tc_BYTE_DEFAULT       byte\n\tc_COMPLEX64_DEFAULT  complex64\n\tc_COMPLEX128_DEFAULT complex128\n\tc_FLOAT32_DEFAULT    float32\n\tc_FLOAT64_DEFAULT    float64\n\tc_INT64_DEFAULT      int64\n\tc_UINT64_DEFAULT     uint64\n\tc_INT32_DEFAULT      int32\n\tc_UINT32_DEFAULT     uint32\n\tc_INT16_DEFAULT      int16\n\tc_UINT16_DEFAULT     uint16\n\tc_INT8_DEFAULT       int8\n\tc_UINT8_DEFAULT      uint8\n\tc_INT_DEFAULT        int\n\tc_UINT_DEFAULT       uint\n\tc_TIME_DEFAULT       time.Time\n)\n\nvar (\n\tIntType   = reflect.TypeOf(c_INT_DEFAULT)\n\tInt8Type  = reflect.TypeOf(c_INT8_DEFAULT)\n\tInt16Type = reflect.TypeOf(c_INT16_DEFAULT)\n\tInt32Type = reflect.TypeOf(c_INT32_DEFAULT)\n\tInt64Type = reflect.TypeOf(c_INT64_DEFAULT)\n\n\tUintType   = reflect.TypeOf(c_UINT_DEFAULT)\n\tUint8Type  = reflect.TypeOf(c_UINT8_DEFAULT)\n\tUint16Type = reflect.TypeOf(c_UINT16_DEFAULT)\n\tUint32Type = reflect.TypeOf(c_UINT32_DEFAULT)\n\tUint64Type = reflect.TypeOf(c_UINT64_DEFAULT)\n\n\tFloat32Type = reflect.TypeOf(c_FLOAT32_DEFAULT)\n\tFloat64Type = reflect.TypeOf(c_FLOAT64_DEFAULT)\n\n\tComplex64Type  = reflect.TypeOf(c_COMPLEX64_DEFAULT)\n\tComplex128Type = reflect.TypeOf(c_COMPLEX128_DEFAULT)\n\n\tStringType = reflect.TypeOf(c_EMPTY_STRING)\n\tBoolType   = reflect.TypeOf(c_BOOL_DEFAULT)\n\tByteType   = reflect.TypeOf(c_BYTE_DEFAULT)\n\tBytesType  = reflect.SliceOf(ByteType)\n\n\tTimeType = reflect.TypeOf(c_TIME_DEFAULT)\n)\n\nvar (\n\tPtrIntType   = reflect.PtrTo(IntType)\n\tPtrInt8Type  = reflect.PtrTo(Int8Type)\n\tPtrInt16Type = reflect.PtrTo(Int16Type)\n\tPtrInt32Type = reflect.PtrTo(Int32Type)\n\tPtrInt64Type = reflect.PtrTo(Int64Type)\n\n\tPtrUintType   = reflect.PtrTo(UintType)\n\tPtrUint8Type  = reflect.PtrTo(Uint8Type)\n\tPtrUint16Type = reflect.PtrTo(Uint16Type)\n\tPtrUint32Type = reflect.PtrTo(Uint32Type)\n\tPtrUint64Type = reflect.PtrTo(Uint64Type)\n\n\tPtrFloat32Type = reflect.PtrTo(Float32Type)\n\tPtrFloat64Type = reflect.PtrTo(Float64Type)\n\n\tPtrComplex64Type  = reflect.PtrTo(Complex64Type)\n\tPtrComplex128Type = reflect.PtrTo(Complex128Type)\n\n\tPtrStringType = reflect.PtrTo(StringType)\n\tPtrBoolType   = reflect.PtrTo(BoolType)\n\tPtrByteType   = reflect.PtrTo(ByteType)\n\n\tPtrTimeType = reflect.PtrTo(TimeType)\n)\n\n\/\/ Type2SQLType generate SQLType acorrding Go's type\nfunc Type2SQLType(t reflect.Type) (st SQLType) {\n\tswitch k := t.Kind(); k {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32:\n\t\tst = SQLType{Int, 0, 0}\n\tcase reflect.Int64, reflect.Uint64:\n\t\tst = SQLType{BigInt, 0, 0}\n\tcase reflect.Float32:\n\t\tst = SQLType{Float, 0, 0}\n\tcase reflect.Float64:\n\t\tst = SQLType{Double, 0, 0}\n\tcase reflect.Complex64, reflect.Complex128:\n\t\tst = SQLType{Varchar, 64, 0}\n\tcase reflect.Array, reflect.Slice, reflect.Map:\n\t\tif t.Elem() == reflect.TypeOf(c_BYTE_DEFAULT) {\n\t\t\tst = SQLType{Blob, 0, 0}\n\t\t} else {\n\t\t\tst = SQLType{Text, 0, 0}\n\t\t}\n\tcase reflect.Bool:\n\t\tst = SQLType{Bool, 0, 0}\n\tcase reflect.String:\n\t\tst = SQLType{Varchar, 255, 0}\n\tcase reflect.Struct:\n\t\tif t.ConvertibleTo(TimeType) {\n\t\t\tst = SQLType{DateTime, 0, 0}\n\t\t} else {\n\t\t\t\/\/ TODO need to handle association struct\n\t\t\tst = SQLType{Text, 0, 0}\n\t\t}\n\tcase reflect.Ptr:\n\t\tst = Type2SQLType(t.Elem())\n\tdefault:\n\t\tst = SQLType{Text, 0, 0}\n\t}\n\treturn\n}\n\n\/\/ default sql type change to go types\nfunc SQLType2Type(st SQLType) reflect.Type {\n\tname := strings.ToUpper(st.Name)\n\tswitch name {\n\tcase Bit, TinyInt, SmallInt, MediumInt, Int, Integer, Serial:\n\t\treturn reflect.TypeOf(1)\n\tcase BigInt, BigSerial:\n\t\treturn reflect.TypeOf(int64(1))\n\tcase Float, Real:\n\t\treturn reflect.TypeOf(float32(1))\n\tcase Double:\n\t\treturn reflect.TypeOf(float64(1))\n\tcase Char, Varchar, NVarchar, TinyText, Text, MediumText, LongText, Enum, Set, Uuid, Clob:\n\t\treturn reflect.TypeOf(\"\")\n\tcase TinyBlob, Blob, LongBlob, Bytea, Binary, MediumBlob, VarBinary, UniqueIdentifier:\n\t\treturn reflect.TypeOf([]byte{})\n\tcase Bool:\n\t\treturn reflect.TypeOf(true)\n\tcase DateTime, Date, Time, TimeStamp, TimeStampz:\n\t\treturn reflect.TypeOf(c_TIME_DEFAULT)\n\tcase Decimal, Numeric:\n\t\treturn reflect.TypeOf(\"\")\n\tdefault:\n\t\treturn reflect.TypeOf(\"\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package goio\n\nimport (\n\t\"log\"\n\t\"sync\"\n)\n\ntype User struct {\n\tEvent\n\tId        string\n\tClientIds MapBool\n\tRoomIds   MapBool\n\tlock      sync.RWMutex\n}\n\nfunc (self *User) Receive(message *Message) {\n\tself.lock.Lock()\n\tdefer self.lock.Unlock()\n\n\tfor cltId := range self.ClientIds.Map {\n\t\tclt := GlobalClients().Get(cltId)\n\t\tif clt != nil {\n\t\t\tclt.Receive(message)\n\t\t}\n\t}\n}\n\nfunc (self *User) Delete(id string) {\n\tself.lock.Lock()\n\tdefer self.lock.Unlock()\n\n\tself.ClientIds.Delete(id)\n\tif 0 == self.ClientIds.Count() {\n\t\tlog.Println(\"user client count 0\")\n\t\tself.Destory()\n\t}\n}\n\nfunc (self *User) Destory() {\n\tself.Emit(\"destory\", nil)\n}\n\nfunc (self *User) Add(clt *Client) {\n\tif self.ClientIds.Has(clt.Id) {\n\t\treturn\n\t}\n\n\tclt.On(\"destory\", func(message *Message) {\n\t\tself.Delete(clt.Id)\n\t})\n\n\tclt.UserId = self.Id\n\tself.ClientIds.Add(clt.Id)\n}\n<commit_msg>don't send message to myself<commit_after>package goio\n\nimport (\n\t\"log\"\n\t\"sync\"\n)\n\ntype User struct {\n\tEvent\n\tId        string\n\tClientIds MapBool\n\tRoomIds   MapBool\n\tlock      sync.RWMutex\n}\n\nfunc (self *User) Receive(message *Message) {\n\n\t\/\/ Don't send message to myself\n\tif message != nil && message.CallerId == self.Id {\n\t\treturn\n\t}\n\n\tself.lock.Lock()\n\tdefer self.lock.Unlock()\n\n\tfor cltId := range self.ClientIds.Map {\n\t\tclt := GlobalClients().Get(cltId)\n\t\tif clt != nil {\n\t\t\tclt.Receive(message)\n\t\t}\n\t}\n}\n\nfunc (self *User) Delete(id string) {\n\tself.lock.Lock()\n\tdefer self.lock.Unlock()\n\n\tself.ClientIds.Delete(id)\n\tif 0 == self.ClientIds.Count() {\n\t\tlog.Println(\"user client count 0\")\n\t\tself.Destory()\n\t}\n}\n\nfunc (self *User) Destory() {\n\tself.Emit(\"destory\", nil)\n}\n\nfunc (self *User) Add(clt *Client) {\n\tif self.ClientIds.Has(clt.Id) {\n\t\treturn\n\t}\n\n\tclt.On(\"destory\", func(message *Message) {\n\t\tself.Delete(clt.Id)\n\t})\n\n\tclt.UserId = self.Id\n\tself.ClientIds.Add(clt.Id)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\/exec\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\nfunc CreateUser(etcd *Etcd, username string) error {\n\tif err := etcd.Mkdir(\"\/paus\/users\/\" + username); err != nil {\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"Failed to create user. username: %s\", username))\n\t}\n\n\treturn nil\n}\n\nfunc UserExists(etcd *Etcd, username string) bool {\n\treturn etcd.HasKey(\"\/paus\/users\/\" + username)\n}\n\nfunc UploadPublicKey(username, pubKey string) (string, error) {\n\t\/\/ libcompose does not support `docker-compose run`...\n\tout, err := exec.Command(\"docker-compose\", \"-p\", \"paus\", \"run\", \"--rm\", \"gitreceive-upload-key\", username, pubKey).Output()\n\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, fmt.Sprintf(\"Failed to upload SSH public key. username: %s, pubKey: %s\", username, pubKey))\n\t}\n\n\treturn string(out), nil\n}\n<commit_msg>Create app directory with new user<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\/exec\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\nfunc CreateUser(etcd *Etcd, username string) error {\n\tif err := etcd.Mkdir(\"\/paus\/users\/\" + username); err != nil {\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"Failed to create user. username: %s\", username))\n\t}\n\n\tif err := etcd.Mkdir(\"\/paus\/users\/\" + username + \"\/apps\"); err != nil {\n\t\treturn errors.Wrap(err, fmt.Sprintf(\"Failed to create user app directory. username: %s\", username))\n\t}\n\n\treturn nil\n}\n\nfunc UserExists(etcd *Etcd, username string) bool {\n\treturn etcd.HasKey(\"\/paus\/users\/\" + username)\n}\n\nfunc UploadPublicKey(username, pubKey string) (string, error) {\n\t\/\/ libcompose does not support `docker-compose run`...\n\tout, err := exec.Command(\"docker-compose\", \"-p\", \"paus\", \"run\", \"--rm\", \"gitreceive-upload-key\", username, pubKey).Output()\n\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, fmt.Sprintf(\"Failed to upload SSH public key. username: %s, pubKey: %s\", username, pubKey))\n\t}\n\n\treturn string(out), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package aceproject\n\nimport (\n\t\"net\/http\"\n\n\tsling \"gopkg.in\/dghubble\/sling.v1\"\n)\n\n\/\/ GetUsersParam represents getusers request parameter\ntype GetUsersParam struct {\n\tFilterActive bool `url:\"FilterActive,omitempty\"`\n}\n\n\/\/ UserResponse represents user listing response\ntype UserResponse struct {\n\tStatus  string `json:\"status\"`\n\tResults []User `json:\"results\"`\n}\n\n\/\/ User is representing user in ACEProject\ntype User struct {\n\tID            int64   `json:\"USER_ID\"`\n\tUsername      string  `json:\"USERNAME\"`\n\tEmail         string  `json:\"EMAIL_ALERT\"`\n\tFirstName     string  `json:\"FIRST_NAME\"`\n\tLastName      string  `json:\"LAST_NAME\"`\n\tUserGroupID   int64   `json:\"USER_GROUP_ID\"`\n\tUserGroupName string  `json:\"USER_GROUP_NAME\"`\n\tActive        bool    `json:\"ACTIVE\"`\n\tErrorDesc     *string `json:\"ERRORDESCRIPTION,omitempty\"`\n}\n\n\/\/ UserService provides methods to interact with user specific action\ntype UserService struct {\n\tsling *sling.Sling\n}\n\n\/\/ NewUserService return a new UserService\nfunc NewUserService(httpClient *http.Client, guidInfo *GUIDInfo) *UserService {\n\treturn &UserService{\n\t\tsling: sling.New().Client(httpClient).Base(baseURL).QueryStruct(guidInfo),\n\t}\n}\n\n\/\/ List returns the user list\nfunc (s *UserService) List() ([]User, *http.Response, error) {\n\tresObj := new(UserResponse)\n\tresp, err := s.sling.New().\n\t\tQueryStruct(CreateFunctionParam(\"getusers\")).\n\t\tReceiveSuccess(resObj)\n\tif resObj != nil && len(resObj.Results) > 0 {\n\t\tif resObj.Results[0].ErrorDesc != nil {\n\t\t\treturn nil, resp, Error{*resObj.Results[0].ErrorDesc}\n\t\t}\n\t\treturn *(&resObj.Results), resp, err\n\t}\n\treturn make([]User, 0), resp, err\n}\n\n\/\/ ListWithActiveness returns the list of active \/ non-active users\nfunc (s *UserService) ListWithActiveness(active bool) ([]User, *http.Response, error) {\n\tresObj := new(UserResponse)\n\tresp, err := s.sling.New().\n\t\tQueryStruct(CreateFunctionParam(\"getusers\")).\n\t\tQueryStruct(&GetUsersParam{FilterActive: active}).\n\t\tReceiveSuccess(resObj)\n\tif resObj != nil && len(resObj.Results) > 0 {\n\t\tif resObj.Results[0].ErrorDesc != nil {\n\t\t\treturn nil, resp, Error{*resObj.Results[0].ErrorDesc}\n\t\t}\n\t\treturn *(&resObj.Results), resp, err\n\t}\n\treturn make([]User, 0), resp, err\n}\n<commit_msg>allow query inactive user (#9)<commit_after>package aceproject\n\nimport (\n\t\"net\/http\"\n\n\tsling \"gopkg.in\/dghubble\/sling.v1\"\n)\n\n\/\/ GetUsersParam represents getusers request parameter\ntype GetUsersParam struct {\n\tFilterActive bool `url:\"FilterActive\"`\n}\n\n\/\/ UserResponse represents user listing response\ntype UserResponse struct {\n\tStatus  string `json:\"status\"`\n\tResults []User `json:\"results\"`\n}\n\n\/\/ User is representing user in ACEProject\ntype User struct {\n\tID            int64   `json:\"USER_ID\"`\n\tUsername      string  `json:\"USERNAME\"`\n\tEmail         string  `json:\"EMAIL_ALERT\"`\n\tFirstName     string  `json:\"FIRST_NAME\"`\n\tLastName      string  `json:\"LAST_NAME\"`\n\tUserGroupID   int64   `json:\"USER_GROUP_ID\"`\n\tUserGroupName string  `json:\"USER_GROUP_NAME\"`\n\tActive        bool    `json:\"ACTIVE\"`\n\tErrorDesc     *string `json:\"ERRORDESCRIPTION,omitempty\"`\n}\n\n\/\/ UserService provides methods to interact with user specific action\ntype UserService struct {\n\tsling *sling.Sling\n}\n\n\/\/ NewUserService return a new UserService\nfunc NewUserService(httpClient *http.Client, guidInfo *GUIDInfo) *UserService {\n\treturn &UserService{\n\t\tsling: sling.New().Client(httpClient).Base(baseURL).QueryStruct(guidInfo),\n\t}\n}\n\n\/\/ List returns the user list\nfunc (s *UserService) List() ([]User, *http.Response, error) {\n\tresObj := new(UserResponse)\n\tresp, err := s.sling.New().\n\t\tQueryStruct(CreateFunctionParam(\"getusers\")).\n\t\tReceiveSuccess(resObj)\n\tif resObj != nil && len(resObj.Results) > 0 {\n\t\tif resObj.Results[0].ErrorDesc != nil {\n\t\t\treturn nil, resp, Error{*resObj.Results[0].ErrorDesc}\n\t\t}\n\t\treturn *(&resObj.Results), resp, err\n\t}\n\treturn make([]User, 0), resp, err\n}\n\n\/\/ ListWithActiveness returns the list of active \/ non-active users\nfunc (s *UserService) ListWithActiveness(active bool) ([]User, *http.Response, error) {\n\tresObj := new(UserResponse)\n\tresp, err := s.sling.New().\n\t\tQueryStruct(CreateFunctionParam(\"getusers\")).\n\t\tQueryStruct(&GetUsersParam{FilterActive: active}).\n\t\tReceiveSuccess(resObj)\n\tif resObj != nil && len(resObj.Results) > 0 {\n\t\tif resObj.Results[0].ErrorDesc != nil {\n\t\t\treturn nil, resp, Error{*resObj.Results[0].ErrorDesc}\n\t\t}\n\t\treturn *(&resObj.Results), resp, err\n\t}\n\treturn make([]User, 0), resp, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package cloudflare\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n)\n\n\/*\nInformation about the logged-in user.\n\nAPI reference: https:\/\/api.cloudflare.com\/#user-user-details\n*\/\nfunc (api API) UserDetails() (User, error) {\n\tvar r UserResponse\n\tres, err := api.makeRequest(\"GET\", \"\/user\", nil)\n\tif err != nil {\n\t\treturn User{}, err\n\t}\n\tfmt.Printf(\"%s\\n\", res)\n\terr = json.Unmarshal(res, &r)\n\tif err != nil {\n\t\treturn User{}, err\n\t}\n\treturn r.Result, nil\n}\n\n\/*\nUpdate user properties.\n\nAPI reference: https:\/\/api.cloudflare.com\/#user-update-user\n*\/\nfunc (api API) UpdateUser() (User, error) {\n\t\/\/ api.makeRequest(\"PATCH\", \"\/user\", user)\n\treturn User{}, nil\n}\n<commit_msg>Remove more debug prints<commit_after>package cloudflare\n\nimport \"encoding\/json\"\n\n\/*\nInformation about the logged-in user.\n\nAPI reference: https:\/\/api.cloudflare.com\/#user-user-details\n*\/\nfunc (api API) UserDetails() (User, error) {\n\tvar r UserResponse\n\tres, err := api.makeRequest(\"GET\", \"\/user\", nil)\n\tif err != nil {\n\t\treturn User{}, err\n\t}\n\terr = json.Unmarshal(res, &r)\n\tif err != nil {\n\t\treturn User{}, err\n\t}\n\treturn r.Result, nil\n}\n\n\/*\nUpdate user properties.\n\nAPI reference: https:\/\/api.cloudflare.com\/#user-update-user\n*\/\nfunc (api API) UpdateUser() (User, error) {\n\t\/\/ api.makeRequest(\"PATCH\", \"\/user\", user)\n\treturn User{}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cuckoofilter\n\nimport (\n\t\"encoding\/binary\"\n\n\t\"github.com\/dgryski\/go-metro\"\n)\n\nfunc getAltIndex(fp byte, i uint, numBuckets uint) uint {\n\tbytes := []byte{0, 0, 0, 0, 0, 0, 0, fp}\n\thash := binary.LittleEndian.Uint64(bytes)\n\treturn uint(uint64(i)^(hash*0x5bd1e995)) % numBuckets\n}\n\nfunc getFingerprint(data []byte) byte {\n\tfp := byte(metro.Hash64(data, 1337))\n\tif fp == 0 {\n\t\tfp += 7\n\t}\n\treturn fp\n}\n\n\/\/ getIndicesAndFingerprint returns the 2 bucket indices and fingerprint to be used\nfunc getIndicesAndFingerprint(data []byte, numBuckets uint) (uint, uint, byte) {\n\thash := metro.Hash64(data, 1337)\n\tf := getFingerprint(data)\n\ti1 := uint(hash) % numBuckets\n\ti2 := getAltIndex(f, i1, numBuckets)\n\treturn i1, i2, f\n}\n\nfunc getNextPow2(n uint64) uint {\n\tn--\n\tn |= n >> 1\n\tn |= n >> 2\n\tn |= n >> 4\n\tn |= n >> 8\n\tn |= n >> 16\n\tn |= n >> 32\n\tn++\n\treturn uint(n)\n}\n<commit_msg>use different hashing algorithm for fingerprint<commit_after>package cuckoofilter\n\nimport (\n\t\"github.com\/dgryski\/go-metro\"\n)\n\nfunc getAltIndex(fp byte, i uint, numBuckets uint) uint {\n\thash := uint(metro.Hash64([]byte{fp}, 1337))\n\treturn (i ^ hash) % numBuckets\n}\n\nfunc getFingerprint(data []byte) byte {\n\tfp := byte(metro.Hash64(data, 1335)%255 + 1)\n\treturn fp\n}\n\n\/\/ getIndicesAndFingerprint returns the 2 bucket indices and fingerprint to be used\nfunc getIndicesAndFingerprint(data []byte, numBuckets uint) (uint, uint, byte) {\n\thash := metro.Hash64(data, 1337)\n\tf := getFingerprint(data)\n\ti1 := uint(hash) % numBuckets\n\ti2 := getAltIndex(f, i1, numBuckets)\n\treturn i1, i2, f\n}\n\nfunc getNextPow2(n uint64) uint {\n\tn--\n\tn |= n >> 1\n\tn |= n >> 2\n\tn |= n >> 4\n\tn |= n >> 8\n\tn |= n >> 16\n\tn |= n >> 32\n\tn++\n\treturn uint(n)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n)\n\nfunc ParseLine(line string) (*Example, error) {\n\ttokens := strings.Split(line, \"\\t\")\n\tvar url string\n\tif len(tokens) == 1 {\n\t\turl = tokens[0]\n\t\treturn NewExample(url, UNLABELED), nil\n\t} else if len(tokens) == 2 {\n\t\turl = tokens[0]\n\t\tlabel, _ := strconv.ParseInt(tokens[1], 10, 0)\n\t\tswitch LabelType(label) {\n\t\tcase POSITIVE, NEGATIVE, UNLABELED:\n\t\t\treturn NewExample(url, LabelType(label)), nil\n\t\tdefault:\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Invalid Label type %d in %s\", label, line))\n\t\t}\n\t} else {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Invalid line: %s\", line))\n\t}\n}\n\nfunc ReadExamples(filename string) ([]*Example, error) {\n\tfp, err := os.Open(filename)\n\tdefer fp.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tscanner := bufio.NewScanner(fp)\n\tvar examples Examples\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\te, err := ParseLine(line)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\texamples = append(examples, e)\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn examples, nil\n}\n\nfunc WriteExamples(examples Examples, filename string) error {\n\tfp, err := os.Create(filename)\n\tdefer fp.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twriter := bufio.NewWriter(fp)\n\tfor _, e := range examples {\n\t\tif e.IsNew && e.IsLabeled() {\n\t\t\t_, err := writer.WriteString(e.Url + \"\\t\" + strconv.Itoa(int(e.Label)) + \"\\n\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\twriter.Flush()\n\treturn nil\n}\n\nfunc FilterLabeledExamples(examples Examples) Examples {\n\tvar result Examples\n\tfor _, e := range examples {\n\t\tif e.IsLabeled() {\n\t\t\tresult = append(result, e)\n\t\t}\n\t}\n\treturn result\n}\n\nfunc FilterUnlabeledExamples(examples Examples) Examples {\n\tresult := Examples{}\n\n\talreadyLabeledByURL := make(map[string]bool)\n\talreadyLabeledByTitle := make(map[string]bool)\n\tfor _, e := range FilterLabeledExamples(examples) {\n\t\talreadyLabeledByURL[e.Url] = true\n\t\talreadyLabeledByTitle[e.Title] = true\n\t}\n\n\tfor _, e := range examples {\n\t\tif _, ok := alreadyLabeledByURL[e.Url]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := alreadyLabeledByTitle[e.Title]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tif !e.IsLabeled() {\n\t\t\talreadyLabeledByURL[e.Url] = true\n\t\t\talreadyLabeledByTitle[e.Title] = true\n\t\t\tresult = append(result, e)\n\t\t}\n\t}\n\treturn result\n}\n\nfunc removeDuplicate(args []string) []string {\n\tresults := make([]string, 0)\n\tencountered := map[string]bool{}\n\tfor i := 0; i < len(args); i++ {\n\t\tif !encountered[args[i]] {\n\t\t\tencountered[args[i]] = true\n\t\t\tresults = append(results, args[i])\n\t\t}\n\t}\n\treturn results\n}\n\nfunc AttachMetaData(cache *Cache, examples Examples) {\n\tshuffle(examples)\n\n\twg := &sync.WaitGroup{}\n\tcpus := runtime.NumCPU()\n\truntime.GOMAXPROCS(cpus)\n\tsem := make(chan struct{}, 2000)\n\tfor idx, e := range examples {\n\t\twg.Add(1)\n\t\tsem <- struct{}{}\n\t\tgo func(e *Example, idx int) {\n\t\t\tdefer wg.Done()\n\t\t\tif example, ok := cache.Get(*e); ok {\n\t\t\t\te.Title = example.Title\n\t\t\t\te.FinalUrl = example.FinalUrl\n\t\t\t\te.Description = example.Description\n\t\t\t\te.Body = example.Body\n\t\t\t\te.StatusCode = example.StatusCode\n\t\t\t} else {\n\t\t\t\tarticle := GetArticle(e.Url)\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Fetching(\"+strconv.Itoa(idx)+\"): \"+article.Url)\n\t\t\t\te.Title = article.Title\n\t\t\t\te.FinalUrl = article.Url\n\t\t\t\te.Description = article.Description\n\t\t\t\te.Body = article.Body\n\t\t\t\te.StatusCode = article.StatusCode\n\t\t\t\tcache.Add(*e)\n\t\t\t}\n\t\t\te.Fv = removeDuplicate(ExtractFeatures(*e))\n\t\t\t<-sem\n\t\t}(e, idx)\n\t}\n\twg.Wait()\n}\n\nfunc FilterStatusCodeOkExamples(examples Examples) Examples {\n\tresult := Examples{}\n\n\tfor _, e := range examples {\n\t\tif e.StatusCode == 200 {\n\t\t\tresult = append(result, e)\n\t\t}\n\t}\n\n\treturn result\n}\n<commit_msg>並列数下げる<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n)\n\nfunc ParseLine(line string) (*Example, error) {\n\ttokens := strings.Split(line, \"\\t\")\n\tvar url string\n\tif len(tokens) == 1 {\n\t\turl = tokens[0]\n\t\treturn NewExample(url, UNLABELED), nil\n\t} else if len(tokens) == 2 {\n\t\turl = tokens[0]\n\t\tlabel, _ := strconv.ParseInt(tokens[1], 10, 0)\n\t\tswitch LabelType(label) {\n\t\tcase POSITIVE, NEGATIVE, UNLABELED:\n\t\t\treturn NewExample(url, LabelType(label)), nil\n\t\tdefault:\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Invalid Label type %d in %s\", label, line))\n\t\t}\n\t} else {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Invalid line: %s\", line))\n\t}\n}\n\nfunc ReadExamples(filename string) ([]*Example, error) {\n\tfp, err := os.Open(filename)\n\tdefer fp.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tscanner := bufio.NewScanner(fp)\n\tvar examples Examples\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\te, err := ParseLine(line)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\texamples = append(examples, e)\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn examples, nil\n}\n\nfunc WriteExamples(examples Examples, filename string) error {\n\tfp, err := os.Create(filename)\n\tdefer fp.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twriter := bufio.NewWriter(fp)\n\tfor _, e := range examples {\n\t\tif e.IsNew && e.IsLabeled() {\n\t\t\t_, err := writer.WriteString(e.Url + \"\\t\" + strconv.Itoa(int(e.Label)) + \"\\n\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\twriter.Flush()\n\treturn nil\n}\n\nfunc FilterLabeledExamples(examples Examples) Examples {\n\tvar result Examples\n\tfor _, e := range examples {\n\t\tif e.IsLabeled() {\n\t\t\tresult = append(result, e)\n\t\t}\n\t}\n\treturn result\n}\n\nfunc FilterUnlabeledExamples(examples Examples) Examples {\n\tresult := Examples{}\n\n\talreadyLabeledByURL := make(map[string]bool)\n\talreadyLabeledByTitle := make(map[string]bool)\n\tfor _, e := range FilterLabeledExamples(examples) {\n\t\talreadyLabeledByURL[e.Url] = true\n\t\talreadyLabeledByTitle[e.Title] = true\n\t}\n\n\tfor _, e := range examples {\n\t\tif _, ok := alreadyLabeledByURL[e.Url]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := alreadyLabeledByTitle[e.Title]; ok {\n\t\t\tcontinue\n\t\t}\n\t\tif !e.IsLabeled() {\n\t\t\talreadyLabeledByURL[e.Url] = true\n\t\t\talreadyLabeledByTitle[e.Title] = true\n\t\t\tresult = append(result, e)\n\t\t}\n\t}\n\treturn result\n}\n\nfunc removeDuplicate(args []string) []string {\n\tresults := make([]string, 0)\n\tencountered := map[string]bool{}\n\tfor i := 0; i < len(args); i++ {\n\t\tif !encountered[args[i]] {\n\t\t\tencountered[args[i]] = true\n\t\t\tresults = append(results, args[i])\n\t\t}\n\t}\n\treturn results\n}\n\nfunc AttachMetaData(cache *Cache, examples Examples) {\n\tshuffle(examples)\n\n\twg := &sync.WaitGroup{}\n\tcpus := runtime.NumCPU()\n\truntime.GOMAXPROCS(cpus)\n\tsem := make(chan struct{}, 20)\n\tfor idx, e := range examples {\n\t\twg.Add(1)\n\t\tsem <- struct{}{}\n\t\tgo func(e *Example, idx int) {\n\t\t\tdefer wg.Done()\n\t\t\tif example, ok := cache.Get(*e); ok {\n\t\t\t\te.Title = example.Title\n\t\t\t\te.FinalUrl = example.FinalUrl\n\t\t\t\te.Description = example.Description\n\t\t\t\te.Body = example.Body\n\t\t\t\te.StatusCode = example.StatusCode\n\t\t\t} else {\n\t\t\t\tarticle := GetArticle(e.Url)\n\t\t\t\tfmt.Fprintln(os.Stderr, \"Fetching(\"+strconv.Itoa(idx)+\"): \"+article.Url)\n\t\t\t\te.Title = article.Title\n\t\t\t\te.FinalUrl = article.Url\n\t\t\t\te.Description = article.Description\n\t\t\t\te.Body = article.Body\n\t\t\t\te.StatusCode = article.StatusCode\n\t\t\t\tcache.Add(*e)\n\t\t\t}\n\t\t\te.Fv = removeDuplicate(ExtractFeatures(*e))\n\t\t\t<-sem\n\t\t}(e, idx)\n\t}\n\twg.Wait()\n}\n\nfunc FilterStatusCodeOkExamples(examples Examples) Examples {\n\tresult := Examples{}\n\n\tfor _, e := range examples {\n\t\tif e.StatusCode == 200 {\n\t\t\tresult = append(result, e)\n\t\t}\n\t}\n\n\treturn result\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2016 Jeevanandam M (https:\/\/github.com\/jeevatkm)\n\/\/ resty source code and usage is governed by a MIT style\n\/\/ license that can be found in the LICENSE file.\n\npackage log\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc strIsEmpty(v string) bool {\n\treturn len(strings.TrimSpace(v)) == 0\n}\n\nfunc closeSilently(v interface{}) {\n\tif d, ok := v.(io.Closer); ok {\n\t\t_ = d.Close()\n\t}\n}\n\nfunc lines(fileName string) int {\n\tf, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn 0\n\t}\n\tdefer closeSilently(f)\n\n\tbuf := make([]byte, 8196)\n\tcount := 0\n\tlineSep := []byte{'\\n'}\n\n\tfor {\n\t\tc, err := f.Read(buf)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn count\n\t\t}\n\n\t\tcount += bytes.Count(buf[:c], lineSep)\n\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn count\n}\n\n\/\/ createDir method creates nested directories if not exists\nfunc mkDirAll(path string) error {\n\tif _, err := os.Lstat(path); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif err = os.MkdirAll(path, filePermission); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to create directory '%v': %v\", path, err)\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"unable to create directory '%v': %v\", path, err)\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>godoc update<commit_after>\/\/ Copyright (c) 2016 Jeevanandam M (https:\/\/github.com\/jeevatkm)\n\/\/ resty source code and usage is governed by a MIT style\n\/\/ license that can be found in the LICENSE file.\n\npackage log\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n)\n\nfunc strIsEmpty(v string) bool {\n\treturn len(strings.TrimSpace(v)) == 0\n}\n\nfunc closeSilently(v interface{}) {\n\tif d, ok := v.(io.Closer); ok {\n\t\t_ = d.Close()\n\t}\n}\n\nfunc lines(fileName string) int {\n\tf, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn 0\n\t}\n\tdefer closeSilently(f)\n\n\tbuf := make([]byte, 8196)\n\tcount := 0\n\tlineSep := []byte{'\\n'}\n\n\tfor {\n\t\tc, err := f.Read(buf)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn count\n\t\t}\n\n\t\tcount += bytes.Count(buf[:c], lineSep)\n\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn count\n}\n\n\/\/ mkDirAll method creates nested directories if not exists\nfunc mkDirAll(path string) error {\n\tif _, err := os.Lstat(path); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\tif err = os.MkdirAll(path, filePermission); err != nil {\n\t\t\t\treturn fmt.Errorf(\"unable to create directory '%v': %v\", path, err)\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"unable to create directory '%v': %v\", path, err)\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package docli\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"io\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/digitalocean\/godo\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nvar DefaultClientSource ClientSource = &LiveClientSource{}\n\ntype TokenSource struct {\n\tAccessToken string\n}\n\ntype TestClientSource struct {\n\tClient *godo.Client\n}\n\nfunc (cs *TestClientSource) NewClient(_ string) *godo.Client {\n\treturn cs.Client\n}\n\nfunc (t *TokenSource) Token() (*oauth2.Token, error) {\n\treturn &oauth2.Token{\n\t\tAccessToken: t.AccessToken,\n\t}, nil\n}\n\nfunc LoadOpts(c *cli.Context) *Opts {\n\treturn &Opts{\n\t\tDebug: c.GlobalBool(\"debug\"),\n\t}\n}\n\nfunc WriteJSON(item interface{}, w io.Writer) error {\n\tb, err := json.Marshal(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar out bytes.Buffer\n\tjson.Indent(&out, b, \"\", \"  \")\n\t_, err = out.WriteTo(w)\n\treturn err\n\n}\n\nfunc ToJSON(item interface{}) (string, error) {\n\tb, err := json.MarshalIndent(item, \"\", \"  \")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(b), nil\n}\n\ntype ClientSource interface {\n\tNewClient(token string) *godo.Client\n}\n\ntype LiveClientSource struct{}\n\nfunc (cs *LiveClientSource) NewClient(token string) *godo.Client {\n\ttokenSource := &TokenSource{\n\t\tAccessToken: token,\n\t}\n\n\toauthClient := oauth2.NewClient(oauth2.NoContext, tokenSource)\n\treturn godo.NewClient(oauthClient)\n}\n\nfunc NewClient(c *cli.Context, cs ClientSource) *godo.Client {\n\tif cs == nil {\n\t\tcs = &LiveClientSource{}\n\t}\n\n\tpat := c.GlobalString(\"token\")\n\treturn cs.NewClient(pat)\n}\n\nfunc WithinTest(cs ClientSource, fs *flag.FlagSet, fn func(*cli.Context)) {\n\togSource := DefaultClientSource\n\tDefaultClientSource = cs\n\n\tdefer func() {\n\t\tDefaultClientSource = ogSource\n\t}()\n\n\tvar b bytes.Buffer\n\tapp := cli.NewApp()\n\tapp.Writer = bufio.NewWriter(&b)\n\n\tglobalSet := flag.NewFlagSet(\"global test\", 0)\n\tglobalSet.String(\"token\", \"token\", \"token\")\n\n\tif fs == nil {\n\t\tfs = flag.NewFlagSet(\"local test\", 0)\n\t}\n\n\tc := cli.NewContext(app, fs, globalSet)\n\n\tfn(c)\n}\n<commit_msg>update to use global context<commit_after>package docli\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"io\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/digitalocean\/godo\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nvar DefaultClientSource ClientSource = &LiveClientSource{}\n\ntype TokenSource struct {\n\tAccessToken string\n}\n\ntype TestClientSource struct {\n\tClient *godo.Client\n}\n\nfunc (cs *TestClientSource) NewClient(_ string) *godo.Client {\n\treturn cs.Client\n}\n\nfunc (t *TokenSource) Token() (*oauth2.Token, error) {\n\treturn &oauth2.Token{\n\t\tAccessToken: t.AccessToken,\n\t}, nil\n}\n\nfunc LoadOpts(c *cli.Context) *Opts {\n\treturn &Opts{\n\t\tDebug: c.GlobalBool(\"debug\"),\n\t}\n}\n\nfunc WriteJSON(item interface{}, w io.Writer) error {\n\tb, err := json.Marshal(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar out bytes.Buffer\n\tjson.Indent(&out, b, \"\", \"  \")\n\t_, err = out.WriteTo(w)\n\treturn err\n\n}\n\nfunc ToJSON(item interface{}) (string, error) {\n\tb, err := json.MarshalIndent(item, \"\", \"  \")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(b), nil\n}\n\ntype ClientSource interface {\n\tNewClient(token string) *godo.Client\n}\n\ntype LiveClientSource struct{}\n\nfunc (cs *LiveClientSource) NewClient(token string) *godo.Client {\n\ttokenSource := &TokenSource{\n\t\tAccessToken: token,\n\t}\n\n\toauthClient := oauth2.NewClient(oauth2.NoContext, tokenSource)\n\treturn godo.NewClient(oauthClient)\n}\n\nfunc NewClient(c *cli.Context, cs ClientSource) *godo.Client {\n\tif cs == nil {\n\t\tcs = &LiveClientSource{}\n\t}\n\n\tpat := c.GlobalString(\"token\")\n\treturn cs.NewClient(pat)\n}\n\nfunc WithinTest(cs ClientSource, fs *flag.FlagSet, fn func(*cli.Context)) {\n\togSource := DefaultClientSource\n\tDefaultClientSource = cs\n\n\tdefer func() {\n\t\tDefaultClientSource = ogSource\n\t}()\n\n\tvar b bytes.Buffer\n\tapp := cli.NewApp()\n\tapp.Writer = bufio.NewWriter(&b)\n\n\tglobalSet := flag.NewFlagSet(\"global test\", 0)\n\tglobalSet.String(\"token\", \"token\", \"token\")\n\n\tglobalCtx := cli.NewContext(app, globalSet, nil)\n\n\tif fs == nil {\n\t\tfs = flag.NewFlagSet(\"local test\", 0)\n\t}\n\n\tc := cli.NewContext(app, fs, globalCtx)\n\n\tfn(c)\n}\n<|endoftext|>"}
{"text":"<commit_before>package dpdk\n\n\/*\n#include <rte_config.h>\n#include <rte_malloc.h>\n*\/\nimport \"C\"\nimport \"unsafe\"\n\nfunc GetCArray(n uint) *unsafe.Pointer {\n\tvar p *unsafe.Pointer\n\tarr := C.rte_malloc((*C.char)(nil), C.size_t(n)*C.size_t(unsafe.Sizeof(p)), C.unsigned(0))\n\treturn (*unsafe.Pointer)(arr)\n}\n\nfunc SliceFromCArray(arr *unsafe.Pointer, n uint) []unsafe.Pointer {\n\treturn (*[1 << 30](unsafe.Pointer))(unsafe.Pointer(arr))[:n:n]\n}\n<commit_msg>util: Add rte_errno error string helper<commit_after>package dpdk\n\n\/*\n#include <rte_config.h>\n#include <rte_malloc.h>\n#include <rte_errno.h>\n*\/\nimport \"C\"\nimport \"unsafe\"\n\nfunc GetCArray(n uint) *unsafe.Pointer {\n\tvar p *unsafe.Pointer\n\tarr := C.rte_malloc((*C.char)(nil), C.size_t(n)*C.size_t(unsafe.Sizeof(p)), C.unsigned(0))\n\treturn (*unsafe.Pointer)(arr)\n}\n\nfunc SliceFromCArray(arr *unsafe.Pointer, n uint) []unsafe.Pointer {\n\treturn (*[1 << 30](unsafe.Pointer))(unsafe.Pointer(arr))[:n:n]\n}\n\nfunc StrError(errno int) string {\n    return C.GoString(C.rte_strerror(C.int(errno)))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2011 Dmitry Chestnykh\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n\/\/ UUID package implements UUID (version 4, random) type and methods for the manipulation of it.\npackage uuid\n\nimport (\n\t\"fmt\"\n\t\"crypto\/rand\"\n\t\"encoding\/hex\"\n\t\"os\"\n\t\"strings\"\n)\n\nconst (\n\tUUIDLen = 16\n)\n\ntype UUID [UUIDLen]byte\n\n\/\/ New generates and returns new UUID v4 (generated randomly).\nfunc New() (u UUID) {\n\trand.Read(u[:])\n\tu[6] = u[6]>>4 | 0x40 \/\/ set version number\n\tu[8] &^= 1 << 6       \/\/ set 6th bit to 0\n\tu[8] |= 1 << 7        \/\/ set 7th bit to 1\n\treturn\n}\n\n\/\/ NewShortString converts a short string (hex uuid without dashes) to UUID.\nfunc NewShortString(s string) (u UUID, err os.Error) {\n\tb := []byte(s)\n\tif hex.DecodedLen(len(s)) != UUIDLen {\n\t\terr = os.NewError(\"uuid: wrong string length for decode\")\n\t\treturn\n\t}\n\t_, err = hex.Decode(u[:], b)\n\treturn\n}\n\n\/\/ NewShortString converts a string (hex uuid, can include dashes) to UUID.\nfunc NewString(s string) (UUID, os.Error) {\n\ts = strings.Replace(s, \"-\", \"\", -1)\n\treturn NewShortString(s)\n}\n\n\/\/ String returns string representation of UUID.\n\/\/ Example: b7c016dc-2ba4-a68d-b368-a97da9f43cee\nfunc (u UUID) String() string {\n\treturn fmt.Sprintf(\"%x-%x-%x-%x-%x\", u[:4], u[4:6], u[6:8], u[8:10], u[10:])\n}\n\n\/\/ ShortString returns short string representation (without dashes) of UUID.\n\/\/ Example: b7c016dc2ba4a68db368a97da9f43cee\nfunc (u UUID) ShortString() string {\n\treturn fmt.Sprintf(\"%x\", u[:])\n}\n\n\/\/ Bytes returns a byte slice of UUID.\nfunc (u UUID) Bytes() []byte {\n\treturn u[:]\n}\n\n\/\/ Equal returns a boolean reporting whether UUID equals another one (a).\nfunc (u UUID) Equal(a UUID) bool {\n\tfor i, v := range u {\n\t\tif v != a[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ MarshalJSON encodes UUID pointer into JSON representation.\nfunc (u *UUID) MarshalJSON() ([]byte, os.Error) {\n\treturn []byte(\"\\\"\" + u.ShortString() + \"\\\"\"), nil\n}\n\n\/\/ UnmarshalJSON decodes UUID pointer from JSON representation.\nfunc (u *UUID) UnmarshalJSON(b []byte) os.Error {\n\tif len(b) < 3 {\n\t\treturn os.NewError(\"uuid: JSON value is too short for UUID\")\n\t}\n\tx, err := NewShortString(string(b[1 : len(b)-1]))\n\tcopy((*u)[:], x[:])\n\treturn err\n}\n<commit_msg>Use io.ReadFull to read from random source.<commit_after>\/\/ Copyright (c) 2011 Dmitry Chestnykh\n\/\/ \n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/ \n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/ \n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n\/\/ UUID package implements UUID (version 4, random) type and methods for the manipulation of it.\npackage uuid\n\nimport (\n\t\"fmt\"\n\t\"crypto\/rand\"\n\t\"encoding\/hex\"\n\t\"os\"\n\t\"strings\"\n)\n\nconst (\n\tUUIDLen = 16\n)\n\ntype UUID [UUIDLen]byte\n\n\/\/ New generates and returns new UUID v4 (generated randomly).\nfunc New() (u UUID) {\n\tif _, err := io.ReadFull(rand.Reader, u[:]); err != nil {\n\t\tpanic(\"error reading from random source: \" + err.String())\n\t}\n\tu[6] = u[6]>>4 | 0x40 \/\/ set version number\n\tu[8] &^= 1 << 6       \/\/ set 6th bit to 0\n\tu[8] |= 1 << 7        \/\/ set 7th bit to 1\n\treturn\n}\n\n\/\/ NewShortString converts a short string (hex uuid without dashes) to UUID.\nfunc NewShortString(s string) (u UUID, err os.Error) {\n\tb := []byte(s)\n\tif hex.DecodedLen(len(s)) != UUIDLen {\n\t\terr = os.NewError(\"uuid: wrong string length for decode\")\n\t\treturn\n\t}\n\t_, err = hex.Decode(u[:], b)\n\treturn\n}\n\n\/\/ NewShortString converts a string (hex uuid, can include dashes) to UUID.\nfunc NewString(s string) (UUID, os.Error) {\n\ts = strings.Replace(s, \"-\", \"\", -1)\n\treturn NewShortString(s)\n}\n\n\/\/ String returns string representation of UUID.\n\/\/ Example: b7c016dc-2ba4-a68d-b368-a97da9f43cee\nfunc (u UUID) String() string {\n\treturn fmt.Sprintf(\"%x-%x-%x-%x-%x\", u[:4], u[4:6], u[6:8], u[8:10], u[10:])\n}\n\n\/\/ ShortString returns short string representation (without dashes) of UUID.\n\/\/ Example: b7c016dc2ba4a68db368a97da9f43cee\nfunc (u UUID) ShortString() string {\n\treturn fmt.Sprintf(\"%x\", u[:])\n}\n\n\/\/ Bytes returns a byte slice of UUID.\nfunc (u UUID) Bytes() []byte {\n\treturn u[:]\n}\n\n\/\/ Equal returns a boolean reporting whether UUID equals another one (a).\nfunc (u UUID) Equal(a UUID) bool {\n\tfor i, v := range u {\n\t\tif v != a[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ MarshalJSON encodes UUID pointer into JSON representation.\nfunc (u *UUID) MarshalJSON() ([]byte, os.Error) {\n\treturn []byte(\"\\\"\" + u.ShortString() + \"\\\"\"), nil\n}\n\n\/\/ UnmarshalJSON decodes UUID pointer from JSON representation.\nfunc (u *UUID) UnmarshalJSON(b []byte) os.Error {\n\tif len(b) < 3 {\n\t\treturn os.NewError(\"uuid: JSON value is too short for UUID\")\n\t}\n\tx, err := NewShortString(string(b[1 : len(b)-1]))\n\tcopy((*u)[:], x[:])\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package tql\nimport (\n    \"errors\"\n    \"math\"\n)\n\nconst (\n\tValString = iota\n\tValInt\n\tValFloat\n\tValQuoteString\n\tValBool\n\tValNull\n\tValReference\n\tValList\n)\n\ntype Val struct {\n\tValType int\n\tV     interface{}\n}\n\nvar ErrTypeNotMatch = errors.New(\"type not match\")\n\nfunc (v Val) LT(v1 interface{}) (bool, error) {\n    switch v.ValType {\n        case ValInt:\n            return v.V.(int64) < v1.(int64), nil\n        case ValFloat:\n            return v.V.(float64) < v1.(float64), nil\n    }\n    return false, ErrTypeNotMatch\n}\n\nfunc (v Val) GT(v1 interface{}) (bool, error) {\n    switch v.ValType {\n        case ValInt:\n            return v.V.(int64) > v1.(int64), nil\n        case ValFloat:\n            return v.V.(float64) > v1.(float64), nil\n    }\n    return false, ErrTypeNotMatch\n}\n\nfunc (v Val) EQ(v1 interface{}) (bool, error) {\n    switch v.ValType {\n        case ValInt:\n            return v.V.(int64) == v1.(int64), nil\n        case ValFloat:\n            return math.Abs(v.V.(float64) - v1.(float64)) < 1e-7, nil\n        case ValQuoteString:\n            return v.V.(string) == v1.(string), nil\n    }\n    return false, ErrTypeNotMatch\n}\n\nfunc (v Val) NOTEQ(v1 interface{}) (bool, error) {\n    return true, nil\n}\n\nfunc (v Val) LTE(v1 interface{}) (bool, error) {\n    b, err := v.GT(v1)\n    return !b, err\n}\n\nfunc (v Val) GTE(v1 interface{}) (bool, error) {\n    b, err := v.LT(v1)\n    return !b, err\n}\n\n<commit_msg>implement not eq<commit_after>package tql\nimport (\n    \"errors\"\n    \"math\"\n)\n\nconst (\n\tValString = iota\n\tValInt\n\tValFloat\n\tValQuoteString\n\tValBool\n\tValNull\n\tValReference\n\tValList\n)\n\ntype Val struct {\n\tValType int\n\tV     interface{}\n}\n\nvar ErrTypeNotMatch = errors.New(\"type not match\")\n\nfunc (v Val) LT(v1 interface{}) (bool, error) {\n    switch v.ValType {\n        case ValInt:\n            return v.V.(int64) < v1.(int64), nil\n        case ValFloat:\n            return v.V.(float64) < v1.(float64), nil\n    }\n    return false, ErrTypeNotMatch\n}\n\nfunc (v Val) GT(v1 interface{}) (bool, error) {\n    switch v.ValType {\n        case ValInt:\n            return v.V.(int64) > v1.(int64), nil\n        case ValFloat:\n            return v.V.(float64) > v1.(float64), nil\n    }\n    return false, ErrTypeNotMatch\n}\n\nfunc (v Val) EQ(v1 interface{}) (bool, error) {\n    switch v.ValType {\n        case ValInt:\n            return v.V.(int64) == v1.(int64), nil\n        case ValFloat:\n            return math.Abs(v.V.(float64) - v1.(float64)) < 1e-7, nil\n        case ValQuoteString:\n            return v.V.(string) == v1.(string), nil\n    }\n    return false, ErrTypeNotMatch\n}\n\nfunc (v Val) NOTEQ(v1 interface{}) (bool, error) {\n    b, err := v.EQ(v1)\n    return !b, err\n}\n\nfunc (v Val) LTE(v1 interface{}) (bool, error) {\n    b, err := v.GT(v1)\n    return !b, err\n}\n\nfunc (v Val) GTE(v1 interface{}) (bool, error) {\n    b, err := v.LT(v1)\n    return !b, err\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n\n\t\"github.com\/nsf\/termbox-go\"\n)\n\n\/\/ Colors\nconst backgroundColor = termbox.ColorBlue\nconst boardColor = termbox.ColorBlack\nconst instructionsColor = termbox.ColorYellow\n\nvar pieceColors = []termbox.Attribute{\n\ttermbox.ColorBlack,\n\ttermbox.ColorRed,\n\ttermbox.ColorGreen,\n\ttermbox.ColorYellow,\n\ttermbox.ColorBlue,\n\ttermbox.ColorMagenta,\n\ttermbox.ColorCyan,\n\ttermbox.ColorWhite,\n}\n\n\/\/ Layout\nconst defaultMarginWidth = 2\nconst defaultMarginHeight = 1\nconst titleStartX = defaultMarginWidth\nconst titleStartY = defaultMarginHeight\nconst titleHeight = 1\nconst titleEndY = titleStartY + titleHeight\nconst boardStartX = defaultMarginWidth\nconst boardStartY = titleEndY + defaultMarginHeight\nconst boardWidth = 10\nconst boardHeight = 16\nconst cellWidth = 2\nconst boardEndX = boardStartX + boardWidth*cellWidth\nconst boardEndY = boardStartY + boardHeight\nconst instructionsStartX = boardEndX + defaultMarginWidth\nconst instructionsStartY = boardStartY\n\n\/\/ Text in the UI\nconst title = \"TETRIS WRITTEN IN GO\"\n\nvar instructions = []string{\n\t\"Goal: Fill in 5 lines!\",\n\t\"\",\n\t\"\\u2190      Left\",\n\t\"\\u2192      Right\",\n\t\"\\u2191      Rotate\",\n\t\"\\u2193      Down\",\n\t\"Space  Fall\",\n\t\"s      Start\",\n\t\"p      Pause\",\n\t\"esc    Exit\",\n\t\"\",\n\t\"Level: %v\",\n\t\"Lines: %v\",\n\t\"\",\n\t\"GAME OVER!\",\n}\n\n\/\/ This takes care of rendering everything.\nfunc render(g *Game) {\n\ttermbox.Clear(backgroundColor, backgroundColor)\n\ttbprint(titleStartX, titleStartY, instructionsColor, backgroundColor, title)\n\tfor y := 0; y < boardHeight; y++ {\n\t\tfor x := 0; x < boardWidth; x++ {\n\t\t\tcellValue := g.board[y][x]\n\t\t\tabsCellValue := int(math.Abs(float64(cellValue)))\n\t\t\tcellColor := pieceColors[absCellValue]\n\t\t\tfor i := 0; i < cellWidth; i++ {\n\t\t\t\ttermbox.SetCell(boardStartX+cellWidth*x+i, boardStartY+y, ' ', cellColor, cellColor)\n\t\t\t}\n\t\t}\n\t}\n\tfor y, instruction := range instructions {\n\t\tif strings.HasPrefix(instruction, \"Level:\") {\n\t\t\tinstruction = fmt.Sprintf(instruction, g.level)\n\t\t} else if strings.HasPrefix(instruction, \"Lines:\") {\n\t\t\tinstruction = fmt.Sprintf(instruction, g.numLines)\n\t\t} else if strings.HasPrefix(instruction, \"GAME OVER\") && g.state != gameOver {\n\t\t\tinstruction = \"\"\n\t\t}\n\t\ttbprint(instructionsStartX, instructionsStartY+y, instructionsColor, backgroundColor, instruction)\n\t}\n\ttermbox.Flush()\n}\n\n\/\/ Function tbprint draws a string.\nfunc tbprint(x, y int, fg, bg termbox.Attribute, msg string) {\n\tfor _, c := range msg {\n\t\ttermbox.SetCell(x, y, c, fg, bg)\n\t\tx++\n\t}\n}\n<commit_msg>Don't use unicode arrows--doesn't work well on Windows<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n\n\t\"github.com\/nsf\/termbox-go\"\n)\n\n\/\/ Colors\nconst backgroundColor = termbox.ColorBlue\nconst boardColor = termbox.ColorBlack\nconst instructionsColor = termbox.ColorYellow\n\nvar pieceColors = []termbox.Attribute{\n\ttermbox.ColorBlack,\n\ttermbox.ColorRed,\n\ttermbox.ColorGreen,\n\ttermbox.ColorYellow,\n\ttermbox.ColorBlue,\n\ttermbox.ColorMagenta,\n\ttermbox.ColorCyan,\n\ttermbox.ColorWhite,\n}\n\n\/\/ Layout\nconst defaultMarginWidth = 2\nconst defaultMarginHeight = 1\nconst titleStartX = defaultMarginWidth\nconst titleStartY = defaultMarginHeight\nconst titleHeight = 1\nconst titleEndY = titleStartY + titleHeight\nconst boardStartX = defaultMarginWidth\nconst boardStartY = titleEndY + defaultMarginHeight\nconst boardWidth = 10\nconst boardHeight = 16\nconst cellWidth = 2\nconst boardEndX = boardStartX + boardWidth*cellWidth\nconst boardEndY = boardStartY + boardHeight\nconst instructionsStartX = boardEndX + defaultMarginWidth\nconst instructionsStartY = boardStartY\n\n\/\/ Text in the UI\nconst title = \"TETRIS WRITTEN IN GO\"\n\nvar instructions = []string{\n\t\"Goal: Fill in 5 lines!\",\n\t\"\",\n\t\"left   Left\",\n\t\"right  Right\",\n\t\"up     Rotate\",\n\t\"down   Down\",\n\t\"space  Fall\",\n\t\"s      Start\",\n\t\"p      Pause\",\n\t\"esc    Exit\",\n\t\"\",\n\t\"Level: %v\",\n\t\"Lines: %v\",\n\t\"\",\n\t\"GAME OVER!\",\n}\n\n\/\/ This takes care of rendering everything.\nfunc render(g *Game) {\n\ttermbox.Clear(backgroundColor, backgroundColor)\n\ttbprint(titleStartX, titleStartY, instructionsColor, backgroundColor, title)\n\tfor y := 0; y < boardHeight; y++ {\n\t\tfor x := 0; x < boardWidth; x++ {\n\t\t\tcellValue := g.board[y][x]\n\t\t\tabsCellValue := int(math.Abs(float64(cellValue)))\n\t\t\tcellColor := pieceColors[absCellValue]\n\t\t\tfor i := 0; i < cellWidth; i++ {\n\t\t\t\ttermbox.SetCell(boardStartX+cellWidth*x+i, boardStartY+y, ' ', cellColor, cellColor)\n\t\t\t}\n\t\t}\n\t}\n\tfor y, instruction := range instructions {\n\t\tif strings.HasPrefix(instruction, \"Level:\") {\n\t\t\tinstruction = fmt.Sprintf(instruction, g.level)\n\t\t} else if strings.HasPrefix(instruction, \"Lines:\") {\n\t\t\tinstruction = fmt.Sprintf(instruction, g.numLines)\n\t\t} else if strings.HasPrefix(instruction, \"GAME OVER\") && g.state != gameOver {\n\t\t\tinstruction = \"\"\n\t\t}\n\t\ttbprint(instructionsStartX, instructionsStartY+y, instructionsColor, backgroundColor, instruction)\n\t}\n\ttermbox.Flush()\n}\n\n\/\/ Function tbprint draws a string.\nfunc tbprint(x, y int, fg, bg termbox.Attribute, msg string) {\n\tfor _, c := range msg {\n\t\ttermbox.SetCell(x, y, c, fg, bg)\n\t\tx++\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package couchdb\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/google\/go-querystring\/query\"\n)\n\n\/\/ Execute specified view function from specified design document.\nfunc (v *View) Get(name string, params QueryParameters) (*ViewResponse, error) {\n\tq, err := query.Values(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turi := fmt.Sprintf(\"%s_view\/%s?%s\", v.Url, name, q.Encode())\n\tbody, err := request(\"GET\", uri, nil, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newViewResponse(body)\n}\n\n\/\/ Execute specified view function from specified design document.\n\/\/ Unlike View.Get for accessing views, View.Post supports\n\/\/ the specification of explicit keys to be retrieved from the view results.\nfunc (v *View) Post(name string, keys []string, params QueryParameters) (*ViewResponse, error) {\n\t\/\/ create POST body\n\tres, err := json.Marshal(keys)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ create query string\n\tq, err := query.Values(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turl := fmt.Sprintf(\"%s_view\/%s?%s\", v.Url, name, q.Encode())\n\tdata := bytes.NewReader(res)\n\tbody, err := request(\"GET\", url, data, \"application\/json\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newViewResponse(body)\n}\n\nfunc newViewResponse(body []byte) (*ViewResponse, error) {\n\tvar response *ViewResponse\n\treturn response, json.Unmarshal(body, &response)\n}\n<commit_msg>use double quoted query string for view functions<commit_after>package couchdb\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/google\/go-querystring\/query\"\n)\n\n\/\/ Execute specified view function from specified design document.\nfunc (v *View) Get(name string, params QueryParameters) (*ViewResponse, error) {\n\tq, err := query.Values(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tquoted := quote(q)\n\turi := fmt.Sprintf(\"%s_view\/%s?%s\", v.Url, name, quoted.Encode())\n\tbody, err := request(\"GET\", uri, nil, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newViewResponse(body)\n}\n\n\/\/ Execute specified view function from specified design document.\n\/\/ Unlike View.Get for accessing views, View.Post supports\n\/\/ the specification of explicit keys to be retrieved from the view results.\nfunc (v *View) Post(name string, keys []string, params QueryParameters) (*ViewResponse, error) {\n\t\/\/ create POST body\n\tres, err := json.Marshal(keys)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ create query string\n\tq, err := query.Values(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tquoted := quote(q)\n\turl := fmt.Sprintf(\"%s_view\/%s?%s\", v.Url, name, quoted.Encode())\n\tdata := bytes.NewReader(res)\n\tbody, err := request(\"GET\", url, data, \"application\/json\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newViewResponse(body)\n}\n\nfunc newViewResponse(body []byte) (*ViewResponse, error) {\n\tvar response *ViewResponse\n\treturn response, json.Unmarshal(body, &response)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package vlog add leveled log on std log(golang.org\/pkg\/log\/)\n\/\/ It implements most std log functions(except logger), variables\n\/\/ and add provides V-style logging controlled by the -v flag or SetLogLevel()\n\/\/ If flag.Parse be called before any logging, -v flag(default 0) use automaticlly.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Basic examples:\n\/\/  vlog.SetLogLevel(3)\n\/\/  vlog.GetLogLevel()\n\/\/\n\/\/\tvlog.Println(\"Prepare to repel boarders\")\n\/\/\n\/\/\tvlog.Fatalf(\"Initialization failed: %s\", err)\n\/\/\n\/\/ See the documentation for the V function for an explanation of these examples:\n\/\/\n\/\/\tif vlog.V(2) {\n\/\/\t\tvlog.Print(\"Starting transaction...\")\n\/\/\t}\n\/\/\n\/\/\tvlog.V(2).Println(\"Processed\", nItems, \"elements\")\npackage vlog\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n)\n\n\/\/ These flags define which text to prefix to each log entry generated by the Logger.\nconst (\n\t\/\/ Bits or'ed together to control what's printed.\n\t\/\/ There is no control over the order they appear (the order listed\n\t\/\/ here) or the format they present (as described in the comments).\n\t\/\/ The prefix is followed by a colon only when Llongfile or Lshortfile\n\t\/\/ is specified.\n\t\/\/ For example, flags Ldate | Ltime (or LstdFlags) produce,\n\t\/\/\t2009\/01\/23 01:23:23 message\n\t\/\/ while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,\n\t\/\/\t2009\/01\/23 01:23:23.123123 \/a\/b\/c\/d.go:23: message\n\tLdate         = log.Ldate             \/\/ the date in the local time zone: 2009\/01\/23\n\tLtime         = log.Ltime             \/\/ the time in the local time zone: 01:23:23\n\tLmicroseconds = log.Lmicroseconds     \/\/ microsecond resolution: 01:23:23.123123.  assumes Ltime.\n\tLlongfile     = log.Llongfile         \/\/ full file name and line number: \/a\/b\/c\/d.go:23\n\tLshortfile    = log.Lshortfile        \/\/ final file name element and line number: d.go:23. overrides Llongfile\n\tLUTC          = log.LUTC              \/\/ if Ldate or Ltime is set, use UTC rather than the local time zone\n\tLstdFlags     = log.Ldate | log.Ltime \/\/ initial values for the standard logger\n)\n\nvar (\n\tlevel Level\n\n\tvParsed bool\n\n\tstd = log.New(os.Stderr, \"\", LstdFlags)\n)\n\nfunc init() {\n\tflag.Var(&level, \"v\", \"log level for V logs(default 0)\")\n}\n\ntype Level int32\n\n\/\/ String is part of the flag.Value interface.\nfunc (l *Level) String() string {\n\treturn strconv.FormatInt(int64(*l), 10)\n}\n\n\/\/ Get is part of the flag.Value interface.\nfunc (l *Level) Get() interface{} {\n\treturn int32(*l)\n}\n\n\/\/ Set is part of the flag.Value interface.\nfunc (l *Level) Set(value string) error {\n\tv, err := strconv.ParseInt(value, 0, 32)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*l = Level(v)\n\tvParsed = true\n\treturn nil\n}\n\n\/\/ Set log level, just use at parameter initialize zone.\nfunc SetLogLevel(v Level) {\n\tlevel = v\n}\n\n\/\/ Get log level, just use at parameter initialize zone.\nfunc GetLogLevel() Level {\n\treturn level\n}\n\n\/\/ Get bool, whether be parsed for command line(use or not use -v flag)\nfunc IsLevelParsed() bool {\n\treturn vParsed\n}\n\n\/\/ Verbose is a boolean type that implements Print like function.\n\/\/ See the documentation of V for more information.\ntype Verbose bool\n\n\/\/ Whether an individual call to V generates a log record depends on the setting of level.\nfunc V(v Level) Verbose {\n\tif v <= level {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (vb Verbose) Printf(format string, v ...interface{}) {\n\tif vb {\n\t\tstd.Output(2, fmt.Sprintf(format, v...))\n\t}\n}\n\nfunc (vb Verbose) Println(v ...interface{}) {\n\tif vb {\n\t\tstd.Output(2, fmt.Sprintln(v...))\n\t}\n}\n\nfunc (vb Verbose) Print(v ...interface{}) {\n\tif vb {\n\t\tstd.Output(2, fmt.Sprint(v...))\n\t}\n}\n\n\/\/ SetOutput sets the output destination for the standard logger.\nfunc SetOutput(w io.Writer) {\n\tstd.SetOutput(w)\n}\n\n\/\/ Flags returns the output flags for the standard logger.\nfunc Flags() int {\n\treturn std.Flags()\n}\n\n\/\/ SetFlags sets the output flags for the standard logger.\nfunc SetFlags(flag int) {\n\tstd.SetFlags(flag)\n}\n\n\/\/ Prefix returns the output prefix for the standard logger.\nfunc Prefix() string {\n\treturn std.Prefix()\n}\n\n\/\/ SetPrefix sets the output prefix for the standard logger.\nfunc SetPrefix(prefix string) {\n\tstd.SetPrefix(prefix)\n}\n\n\/\/ These functions write to the standard logger.\n\n\/\/ Print calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Print.\nfunc Print(v ...interface{}) {\n\tstd.Output(2, fmt.Sprint(v...))\n}\n\n\/\/ Printf calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Printf.\nfunc Printf(format string, v ...interface{}) {\n\tstd.Output(2, fmt.Sprintf(format, v...))\n}\n\n\/\/ Println calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Println.\nfunc Println(v ...interface{}) {\n\tstd.Output(2, fmt.Sprintln(v...))\n}\n\n\/\/ Fatal is equivalent to Print() followed by a call to os.Exit(1).\nfunc Fatal(v ...interface{}) {\n\tstd.Output(2, fmt.Sprint(v...))\n\tos.Exit(1)\n}\n\n\/\/ Fatalf is equivalent to Printf() followed by a call to os.Exit(1).\nfunc Fatalf(format string, v ...interface{}) {\n\tstd.Output(2, fmt.Sprintf(format, v...))\n\tos.Exit(1)\n}\n\n\/\/ Fatalln is equivalent to Println() followed by a call to os.Exit(1).\nfunc Fatalln(v ...interface{}) {\n\tstd.Output(2, fmt.Sprintln(v...))\n\tos.Exit(1)\n}\n\n\/\/ Panic is equivalent to Print() followed by a call to panic().\nfunc Panic(v ...interface{}) {\n\ts := fmt.Sprint(v...)\n\tstd.Output(2, s)\n\tpanic(s)\n}\n\n\/\/ Panicf is equivalent to Printf() followed by a call to panic().\nfunc Panicf(format string, v ...interface{}) {\n\ts := fmt.Sprintf(format, v...)\n\tstd.Output(2, s)\n\tpanic(s)\n}\n\n\/\/ Panicln is equivalent to Println() followed by a call to panic().\nfunc Panicln(v ...interface{}) {\n\ts := fmt.Sprintln(v...)\n\tstd.Output(2, s)\n\tpanic(s)\n}\n\n\/\/ Output writes the output for a logging event.  The string s contains\n\/\/ the text to print after the prefix specified by the flags of the\n\/\/ Logger.  A newline is appended if the last character of s is not\n\/\/ already a newline.  Calldepth is the count of the number of\n\/\/ frames to skip when computing the file name and line number\n\/\/ if Llongfile or Lshortfile is set; a value of 1 will print the details\n\/\/ for the caller of Output.\nfunc Output(calldepth int, s string) error {\n\treturn std.Output(calldepth+1, s) \/\/ +1 for this frame.\n}\n<commit_msg>change comment doc<commit_after>\/\/ Package vlog add leveled log on std log(golang.org\/pkg\/log\/)\n\/\/ It implements most std log functions(except logger), variables\n\/\/ and add provides V-style logging controlled by the -v flag or SetLogLevel()\n\/\/ If flag.Parse be called before any logging, -v flag(default 0) use automaticlly.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Basic examples:\n\/\/  vlog.SetLogLevel(3)\n\/\/  vlog.GetLogLevel()\n\/\/\n\/\/\tvlog.Println(\"Prepare to repel boarders\")\n\/\/\n\/\/\tvlog.Fatalf(\"Initialization failed: %s\", err)\n\/\/\n\/\/ See the documentation for the V function for an explanation of these examples:\n\/\/\n\/\/\tif vlog.V(2) {\n\/\/\t\tvlog.Print(\"Starting transaction...\")\n\/\/\t}\n\/\/\n\/\/\tvlog.V(2).Println(\"Processed\", nItems, \"elements\")\npackage vlog\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n)\n\n\/\/ These flags define which text to prefix to each log entry generated by the Logger.\nconst (\n\t\/\/ Bits or'ed together to control what's printed.\n\t\/\/ There is no control over the order they appear (the order listed\n\t\/\/ here) or the format they present (as described in the comments).\n\t\/\/ The prefix is followed by a colon only when Llongfile or Lshortfile\n\t\/\/ is specified.\n\t\/\/ For example, flags Ldate | Ltime (or LstdFlags) produce,\n\t\/\/\t2009\/01\/23 01:23:23 message\n\t\/\/ while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,\n\t\/\/\t2009\/01\/23 01:23:23.123123 \/a\/b\/c\/d.go:23: message\n\tLdate         = log.Ldate             \/\/ the date in the local time zone: 2009\/01\/23\n\tLtime         = log.Ltime             \/\/ the time in the local time zone: 01:23:23\n\tLmicroseconds = log.Lmicroseconds     \/\/ microsecond resolution: 01:23:23.123123.  assumes Ltime.\n\tLlongfile     = log.Llongfile         \/\/ full file name and line number: \/a\/b\/c\/d.go:23\n\tLshortfile    = log.Lshortfile        \/\/ final file name element and line number: d.go:23. overrides Llongfile\n\tLUTC          = log.LUTC              \/\/ if Ldate or Ltime is set, use UTC rather than the local time zone\n\tLstdFlags     = log.Ldate | log.Ltime \/\/ initial values for the standard logger\n)\n\nvar (\n\tlevel Level\n\n\tvParsed bool\n\n\tstd = log.New(os.Stderr, \"\", LstdFlags)\n)\n\nfunc init() {\n\tflag.Var(&level, \"v\", \"log level for V logs(default 0)\")\n}\n\n\/\/ Level log level\ntype Level int32\n\n\/\/ String is part of the flag.Value interface.\nfunc (l *Level) String() string {\n\treturn strconv.FormatInt(int64(*l), 10)\n}\n\n\/\/ Get is part of the flag.Value interface.\nfunc (l *Level) Get() interface{} {\n\treturn int32(*l)\n}\n\n\/\/ Set is part of the flag.Value interface.\nfunc (l *Level) Set(value string) error {\n\tv, err := strconv.ParseInt(value, 0, 32)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*l = Level(v)\n\tvParsed = true\n\treturn nil\n}\n\n\/\/ SetLogLevel set log level, just use at parameter initialize zone.\nfunc SetLogLevel(v Level) {\n\tlevel = v\n}\n\n\/\/ GetLogLevel get log level, just use at parameter initialize zone.\nfunc GetLogLevel() Level {\n\treturn level\n}\n\n\/\/ IsLevelParsed get bool, whether be parsed for command line(use or not use -v flag)\nfunc IsLevelParsed() bool {\n\treturn vParsed\n}\n\n\/\/ Verbose is a boolean type that implements Print like function.\n\/\/ See the documentation of V for more information.\ntype Verbose bool\n\n\/\/ V function return Verbose,\n\/\/ whether an individual call to V generates a log record depends on the setting of level.\nfunc V(v Level) Verbose {\n\tif v <= level {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ Printf calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Printf.\nfunc (vb Verbose) Printf(format string, v ...interface{}) {\n\tif vb {\n\t\tstd.Output(2, fmt.Sprintf(format, v...))\n\t}\n}\n\n\/\/ Println calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Println.\nfunc (vb Verbose) Println(v ...interface{}) {\n\tif vb {\n\t\tstd.Output(2, fmt.Sprintln(v...))\n\t}\n}\n\n\/\/ Print calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Print.\nfunc (vb Verbose) Print(v ...interface{}) {\n\tif vb {\n\t\tstd.Output(2, fmt.Sprint(v...))\n\t}\n}\n\n\/\/ SetOutput sets the output destination for the standard logger.\nfunc SetOutput(w io.Writer) {\n\tstd.SetOutput(w)\n}\n\n\/\/ Flags returns the output flags for the standard logger.\nfunc Flags() int {\n\treturn std.Flags()\n}\n\n\/\/ SetFlags sets the output flags for the standard logger.\nfunc SetFlags(flag int) {\n\tstd.SetFlags(flag)\n}\n\n\/\/ Prefix returns the output prefix for the standard logger.\nfunc Prefix() string {\n\treturn std.Prefix()\n}\n\n\/\/ SetPrefix sets the output prefix for the standard logger.\nfunc SetPrefix(prefix string) {\n\tstd.SetPrefix(prefix)\n}\n\n\/\/ These functions write to the standard logger.\n\n\/\/ Print calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Print.\nfunc Print(v ...interface{}) {\n\tstd.Output(2, fmt.Sprint(v...))\n}\n\n\/\/ Printf calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Printf.\nfunc Printf(format string, v ...interface{}) {\n\tstd.Output(2, fmt.Sprintf(format, v...))\n}\n\n\/\/ Println calls Output to print to the standard logger.\n\/\/ Arguments are handled in the manner of fmt.Println.\nfunc Println(v ...interface{}) {\n\tstd.Output(2, fmt.Sprintln(v...))\n}\n\n\/\/ Fatal is equivalent to Print() followed by a call to os.Exit(1).\nfunc Fatal(v ...interface{}) {\n\tstd.Output(2, fmt.Sprint(v...))\n\tos.Exit(1)\n}\n\n\/\/ Fatalf is equivalent to Printf() followed by a call to os.Exit(1).\nfunc Fatalf(format string, v ...interface{}) {\n\tstd.Output(2, fmt.Sprintf(format, v...))\n\tos.Exit(1)\n}\n\n\/\/ Fatalln is equivalent to Println() followed by a call to os.Exit(1).\nfunc Fatalln(v ...interface{}) {\n\tstd.Output(2, fmt.Sprintln(v...))\n\tos.Exit(1)\n}\n\n\/\/ Panic is equivalent to Print() followed by a call to panic().\nfunc Panic(v ...interface{}) {\n\ts := fmt.Sprint(v...)\n\tstd.Output(2, s)\n\tpanic(s)\n}\n\n\/\/ Panicf is equivalent to Printf() followed by a call to panic().\nfunc Panicf(format string, v ...interface{}) {\n\ts := fmt.Sprintf(format, v...)\n\tstd.Output(2, s)\n\tpanic(s)\n}\n\n\/\/ Panicln is equivalent to Println() followed by a call to panic().\nfunc Panicln(v ...interface{}) {\n\ts := fmt.Sprintln(v...)\n\tstd.Output(2, s)\n\tpanic(s)\n}\n\n\/\/ Output writes the output for a logging event.  The string s contains\n\/\/ the text to print after the prefix specified by the flags of the\n\/\/ Logger.  A newline is appended if the last character of s is not\n\/\/ already a newline.  Calldepth is the count of the number of\n\/\/ frames to skip when computing the file name and line number\n\/\/ if Llongfile or Lshortfile is set; a value of 1 will print the details\n\/\/ for the caller of Output.\nfunc Output(calldepth int, s string) error {\n\treturn std.Output(calldepth+1, s) \/\/ +1 for this frame.\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Packet vlog provides package level verbose logging.\n\/\/ The actual logging is done with the standard log package.\n\/\/\n\/\/ To define a package level logging variable,\n\/\/   var v = vlog.New()\n\/\/\n\/\/ To log a message at INFO level,\n\/\/   v.I(\"a\")\n\/\/\n\/\/ The logging level can be set with either the flag -vlog or\n\/\/ the environment variable GO_VLOG.\n\/\/\n\/\/ The -vlog or GO_VLOG format is,\n\/\/  k=v(,k=v)*\n\/\/  k can be exact match like \"foo\/bar\" or prefix match like \"foo\/*\".\n\/\/  v can be w|i|v1|v2\n\/\/ Default level can be set with prefix match \"*\".\npackage vlog\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\/atomic\"\n)\n\n\/\/go:generate stringer -type=Level\ntype Level int32\n\nconst (\n\tv2 Level = -2 + iota\n\tv1\n\tinfo\n\twarn\n)\n\n\/\/ W logs warning message.\n\/\/ If args[0] is a format string, args is formatted with Printf,\n\/\/ otherwise args is formatted with Println.\nfunc (v *Level) W(args ...interface{}) {\n\tif *v <= warn {\n\t\tlg.Log(Format(args...))\n\t}\n}\n\n\/\/ I logs info message.\nfunc (v *Level) I(args ...interface{}) {\n\tif *v <= info {\n\t\tlg.Log(Format(args...))\n\t}\n}\n\n\/\/ V1 logs verbose level 1 message.\nfunc (v *Level) V1(args ...interface{}) {\n\tif *v <= v1 {\n\t\tlg.Log(Format(args...))\n\t}\n}\n\n\/\/ V2 logs verbose level 2 message.\nfunc (v *Level) V2(args ...interface{}) {\n\tif *v <= v2 {\n\t\tlg.Log(Format(args...))\n\t}\n}\n\n\/\/ Vstack logs the message and the stacktrace of this goroutine.\n\/\/ It is noop when verbose logging is not enabled.\nfunc (v *Level) Vstack(args ...interface{}) {\n\tif *v >= info {\n\t\treturn\n\t}\n\ts := Format(args...)\n\tlg.Log(stackTrace(s))\n}\n\n\/\/ On returns true if the specific verbose level 1-3 is enabled.\nfunc (v *Level) On(l int) bool {\n\tlv := Level(-l)\n\treturn *v <= lv\n}\n\n\/\/ Vset sets the verbose logging level.\nfunc (v *Level) Vset(l int) Level {\n\tlv := Level(-l)\n\tif lv < v2 || lv >= info {\n\t\tlg.Log(Format(\"invalid verbose level=%d\", l))\n\t\treturn *v\n\t}\n\told := *v\n\tatomic.StoreInt32((*int32)(v), int32(lv))\n\treturn old\n}\n\n\/\/ Error returns an error. The message of the error is formatted\n\/\/ from args. If verbose level 1 is enabled, the error messag includes\n\/\/ the caller, and if verbose level 2 is enabled, the error message\n\/\/ includes the call stack.\nfunc (v *Level) Error(args ...interface{}) error {\n\treturn v.newError(Format(args...))\n}\n\n\/\/ newError is necessary to get the correct call stack\nfunc (v *Level) newError(s string) error {\n\tswitch *v {\n\tdefault:\n\t\treturn errors.New(s)\n\n\tcase v1:\n\t\t_, fn, ln, ok := runtime.Caller(3)\n\t\tif !ok {\n\t\t\treturn errors.New(\"???: \" + s)\n\t\t}\n\t\treturn errors.New(\"E[\" + fn + \":\" + strconv.Itoa(ln) + \"]\" + s)\n\n\tcase v2:\n\t\treturn errors.New(stackTrace(s))\n\t}\n}\n\nfunc parseLevel(lvs string) Level {\n\tswitch strings.ToLower(lvs) {\n\tcase \"2\", \"v2\":\n\t\treturn v2\n\tcase \"1\", \"v1\":\n\t\treturn v1\n\tcase \"i\", \"info\":\n\t\treturn info\n\tcase \"w\", \"warn\":\n\t\treturn warn\n\tdefault:\n\t\tlg.Log(Format(\"ignore invalid logging level=%s\", lvs))\n\t\treturn info\n\t}\n}\n\n\/\/ New returns a vlog Level variable.\n\/\/ The name of the Level variable is inferred with these rules,\n\/\/  - file name of the caller must be under \"\/src\/\", to follow go path convention\n\/\/  - if the file is \"...\/src\/<foo_pkg>\/{main,cmd}\/bar.go\", name is \"foo_pkg\/bar\".\n\/\/  - if the file is \"...\/src\/<foo_pkg>\/bar.go\", name is \"foo_pkg\".\n\/\/\n\/\/ New must be called before Parse() is callled.\nfunc New() *Level {\n\t\/\/ Note: 1 to skip New\n\t_, fn, _, ok := runtime.Caller(1)\n\tif !ok {\n\t\tlg.Log(\"fail to get file from runtime.caller\")\n\t\treturn &levelVars[0].Level \/\/ [0] is default\n\t}\n\tname := inferName(fn)\n\treturn newVar(name, fn)\n}\n\nfunc newVar(name, fn string) *Level {\n\tif name == \"\" {\n\t\tlg.Log(Format(\"fail to infer name from file=%s\", fn))\n\t\treturn &levelVars[0].Level \/\/ [0] is default\n\t}\n\tfor _, lv := range levelVars {\n\t\tif lv.Name == name {\n\t\t\tlg.Log(Format(\"dup level name=%s inferred from file=%s\", name, fn))\n\t\t\treturn &lv.Level\n\t\t}\n\t}\n\tlv := &levelVar{\n\t\tName: name,\n\t\tFile: fn,\n\t}\n\tlevelVars = append(levelVars, lv)\n\treturn &lv.Level\n}\n\nfunc inferName(fn string) string {\n\tfn = strings.ToLower(fn)\n\ti := strings.LastIndex(fn, \"\/src\/\")\n\tif i < 0 {\n\t\treturn \"\"\n\t}\n\tdn, fn := path.Split(fn[i+len(\"\/src\/\"):])\n\tif !strings.HasSuffix(fn, \".go\") {\n\t\treturn \"\"\n\t}\n\tfor _, p := range []string{\"\/main\/\", \"\/cmd\/\"} {\n\t\tif strings.HasSuffix(dn, p) {\n\t\t\tdn = dn[:len(dn)-len(p)]\n\t\t\tfn = fn[:len(fn)-len(\".go\")]\n\t\t\treturn path.Join(dn, fn)\n\t\t}\n\t}\n\treturn strings.TrimRight(dn, \"\/\")\n}\n\ntype levelVar struct {\n\tName  string\n\tFile  string\n\tLevel Level\n}\n\nfunc (lv *levelVar) String() string {\n\treturn fmt.Sprintf(\"%s@%s\", lv.Name, lv.File)\n}\n\nvar levelVars = []*levelVar{&levelVar{}} \/\/ default level\n\nfunc Parse() {\n\tflag.Parse()\n\tsetLevels(*vlogFlag)\n\tif *vlogHelp {\n\t\tlg.Log(\"vlog setting:\" + printLevelVars())\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\tif *vlogFile != \"\" {\n\t\tlg = newRotateLogger(*vlogFile)\n\t}\n}\n\nfunc ParseEnv() {\n\tif val := os.Getenv(\"GO_VLOG\"); val != \"\" { \/\/ for testing\n\t\tsetLevels(val)\n\t\tlg.Log(printLevelVars())\n\t}\n}\n\nfunc setLevels(value string) {\n\texact, prefix := parseFlag(value)\n\tif v, ok := prefix[\"\/\"]; ok {\n\t\tlevelVars[0].Level = v \/\/ default level\n\t}\n\tdef := levelVars[0].Level\n\tfor _, lv := range levelVars[1:] {\n\t\tlv.Level = def\n\t}\n\tif len(prefix) > 0 {\n\t\tprefixes := make([]string, 0, len(prefix))\n\t\tfor k := range prefix {\n\t\t\tprefixes = append(prefixes, k)\n\t\t}\n\t\tsort.Strings(prefixes)\n\n\t\tfor _, lv := range levelVars[1:] {\n\t\t\tfor i := len(prefixes) - 1; i >= 0; i-- {\n\t\t\t\tk := prefixes[i]\n\t\t\t\t\/\/ Match \"foo\" with \"foo\/\" and \"foo\/bar\" with \"foo\/\"\n\t\t\t\tif lv.Name == k[:len(k)-1] || strings.HasPrefix(lv.Name, k) {\n\t\t\t\t\tlv.Level = prefix[k]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor _, lv := range levelVars[1:] {\n\t\tif i, ok := exact[lv.Name]; ok {\n\t\t\tlv.Level = i\n\t\t}\n\t}\n}\n\nfunc parseFlag(value string) (exact, prefix map[string]Level) {\n\texact = make(map[string]Level)\n\tprefix = make(map[string]Level)\n\ts := value\n\tfor s != \"\" {\n\t\tk := s\n\t\tif i := strings.Index(s, \",\"); i >= 0 {\n\t\t\tk, s = s[:i], s[i+1:]\n\t\t} else {\n\t\t\ts = \"\"\n\t\t}\n\t\tj := strings.Index(k, \"=\")\n\t\tif j < 0 {\n\t\t\tpanic(Format(\"malformed: no level\", value))\n\t\t}\n\t\tk, v := k[:j], k[j+1:]\n\t\tlv := parseLevel(v)\n\t\tk = strings.ToLower(k)\n\t\tpre := false\n\t\tif k == \"*\" || strings.HasSuffix(k, \"\/*\") {\n\t\t\tk = k[:len(k)-1]\n\t\t\tif strings.Contains(k, \"*\") {\n\t\t\t\tpanic(Format(\"malformed: multiple star\", s))\n\t\t\t}\n\t\t\tpre = true\n\t\t} else if strings.Contains(k, \"*\") {\n\t\t\tpanic(Format(\"malformed: star in middle\", s))\n\t\t}\n\t\tk = strings.TrimRight(k, \"\/\")\n\t\tif pre {\n\t\t\tprefix[k+\"\/\"] = lv\n\t\t} else {\n\t\t\texact[k] = lv\n\t\t}\n\t}\n\treturn exact, prefix\n}\n\nfunc printLevelVars() string {\n\tvar b bytes.Buffer\n\tfmt.Fprintf(&b, \"*=%v\", levelVars[0].Level)\n\tfor _, lv := range levelVars[1:] {\n\t\tfmt.Fprintf(&b, \",%s=%v\", lv.Name, lv.Level)\n\t}\n\treturn b.String()\n}\n\nvar (\n\tvlogFlag = flag.String(\"vlog\", \"\", \"vlog settings, k=v(,k=v)*\")\n\tvlogFile = flag.String(\"vlogfile\", \"\", \"vlog file prefix\")\n\tvlogHelp = flag.Bool(\"vloghelp\", false, \"show vlog setting and flag help\")\n)\n\ntype Logger interface {\n\tLog(s string)\n\tFlush()\n}\n\ntype stderrLogger struct {\n\tlg *log.Logger\n}\n\nfunc (l *stderrLogger) Log(s string) {\n\tl.lg.Output(3, s)\n}\n\nfunc (l *stderrLogger) Flush() {}\n\nconst logPrefix = log.Ldate | log.Lmicroseconds | log.Lshortfile\n\n\/\/ lg should always be available\nvar lg Logger = &stderrLogger{lg: log.New(os.Stderr, \"\", logPrefix)}\n\nvar stackTraceBegin = []byte(\"\/vlog.go:\")\n\nfunc stackTrace(s string) string {\n\tvar buf [4 << 10]byte\n\tm := copy(buf[:], s)\n\tn := runtime.Stack(buf[m:], false)\n\tn += m\n\n\t\/\/ Trim the frames in vlog.go, any line that contains \"\/vlog.go:\"\n\tb := buf[m:n]\n\tj := bytes.LastIndex(b, stackTraceBegin)\n\tif j < 0 {\n\t\treturn string(buf[:n])\n\t}\n\tb = b[j:]\n\tj = bytes.IndexAny(b, \"\\n\")\n\tif j < 0 {\n\t\treturn string(buf[:n])\n\t}\n\tb = b[j+1:]\n\tbuf[m] = '\\n' \/\/ put a newline between s and stack frames\n\tn = copy(buf[m+1:], b)\n\tn += m + 1\n\tif buf[n] != '\\n' {\n\t\tbuf[n] = '\\n' \/\/ always end with newline\n\t}\n\treturn string(buf[:n])\n}\n<commit_msg>fix caller depth; change verbose error format<commit_after>\/\/ Packet vlog provides package level verbose logging.\n\/\/ The actual logging is done with the standard log package.\n\/\/\n\/\/ To define a package level logging variable,\n\/\/   var v = vlog.New()\n\/\/\n\/\/ To log a message at INFO level,\n\/\/   v.I(\"a\")\n\/\/\n\/\/ The logging level can be set with either the flag -vlog or\n\/\/ the environment variable GO_VLOG.\n\/\/\n\/\/ The -vlog or GO_VLOG format is,\n\/\/  k=v(,k=v)*\n\/\/  k can be exact match like \"foo\/bar\" or prefix match like \"foo\/*\".\n\/\/  v can be w|i|v1|v2\n\/\/ Default level can be set with prefix match \"*\".\npackage vlog\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\/atomic\"\n)\n\n\/\/go:generate stringer -type=Level\ntype Level int32\n\nconst (\n\tv2 Level = -2 + iota\n\tv1\n\tinfo\n\twarn\n)\n\n\/\/ W logs warning message.\n\/\/ If args[0] is a format string, args is formatted with Printf,\n\/\/ otherwise args is formatted with Println.\nfunc (v *Level) W(args ...interface{}) {\n\tif *v <= warn {\n\t\tlg.Log(Format(args...))\n\t}\n}\n\n\/\/ I logs info message.\nfunc (v *Level) I(args ...interface{}) {\n\tif *v <= info {\n\t\tlg.Log(Format(args...))\n\t}\n}\n\n\/\/ V1 logs verbose level 1 message.\nfunc (v *Level) V1(args ...interface{}) {\n\tif *v <= v1 {\n\t\tlg.Log(Format(args...))\n\t}\n}\n\n\/\/ V2 logs verbose level 2 message.\nfunc (v *Level) V2(args ...interface{}) {\n\tif *v <= v2 {\n\t\tlg.Log(Format(args...))\n\t}\n}\n\n\/\/ Vstack logs the message and the stacktrace of this goroutine.\n\/\/ It is noop when verbose logging is not enabled.\nfunc (v *Level) Vstack(args ...interface{}) {\n\tif *v >= info {\n\t\treturn\n\t}\n\ts := Format(args...)\n\tlg.Log(stackTrace(s))\n}\n\n\/\/ On returns true if the specific verbose level 1-3 is enabled.\nfunc (v *Level) On(l int) bool {\n\tlv := Level(-l)\n\treturn *v <= lv\n}\n\n\/\/ Vset sets the verbose logging level.\nfunc (v *Level) Vset(l int) Level {\n\tlv := Level(-l)\n\tif lv < v2 || lv >= info {\n\t\tlg.Log(Format(\"invalid verbose level=%d\", l))\n\t\treturn *v\n\t}\n\told := *v\n\tatomic.StoreInt32((*int32)(v), int32(lv))\n\treturn old\n}\n\n\/\/ Error returns an error. The message of the error is formatted\n\/\/ from args. If verbose level 1 is enabled, the error messag includes\n\/\/ the caller, and if verbose level 2 is enabled, the error message\n\/\/ includes the call stack.\nfunc (v *Level) Error(args ...interface{}) error {\n\treturn v.newError(Format(args...))\n}\n\n\/\/ newError is necessary to get the correct call stack\nfunc (v *Level) newError(s string) error {\n\tswitch *v {\n\tdefault:\n\t\treturn errors.New(s)\n\n\tcase v1:\n\t\t_, fn, ln, ok := runtime.Caller(2)\n\t\tif !ok {\n\t\t\treturn errors.New(\"???: \" + s)\n\t\t}\n\t\treturn errors.New(fn + \":\" + strconv.Itoa(ln) + \" \" + s)\n\n\tcase v2:\n\t\treturn errors.New(stackTrace(s))\n\t}\n}\n\nfunc parseLevel(lvs string) Level {\n\tswitch strings.ToLower(lvs) {\n\tcase \"2\", \"v2\":\n\t\treturn v2\n\tcase \"1\", \"v1\":\n\t\treturn v1\n\tcase \"i\", \"info\":\n\t\treturn info\n\tcase \"w\", \"warn\":\n\t\treturn warn\n\tdefault:\n\t\tlg.Log(Format(\"ignore invalid logging level=%s\", lvs))\n\t\treturn info\n\t}\n}\n\n\/\/ New returns a vlog Level variable.\n\/\/ The name of the Level variable is inferred with these rules,\n\/\/  - file name of the caller must be under \"\/src\/\", to follow go path convention\n\/\/  - if the file is \"...\/src\/<foo_pkg>\/{main,cmd}\/bar.go\", name is \"foo_pkg\/bar\".\n\/\/  - if the file is \"...\/src\/<foo_pkg>\/bar.go\", name is \"foo_pkg\".\n\/\/\n\/\/ New must be called before Parse() is callled.\nfunc New() *Level {\n\t\/\/ Note: 1 to skip New\n\t_, fn, _, ok := runtime.Caller(1)\n\tif !ok {\n\t\tlg.Log(\"fail to get file from runtime.caller\")\n\t\treturn &levelVars[0].Level \/\/ [0] is default\n\t}\n\tname := inferName(fn)\n\treturn newVar(name, fn)\n}\n\nfunc newVar(name, fn string) *Level {\n\tif name == \"\" {\n\t\tlg.Log(Format(\"fail to infer name from file=%s\", fn))\n\t\treturn &levelVars[0].Level \/\/ [0] is default\n\t}\n\tfor _, lv := range levelVars {\n\t\tif lv.Name == name {\n\t\t\tlg.Log(Format(\"dup level name=%s inferred from file=%s\", name, fn))\n\t\t\treturn &lv.Level\n\t\t}\n\t}\n\tlv := &levelVar{\n\t\tName: name,\n\t\tFile: fn,\n\t}\n\tlevelVars = append(levelVars, lv)\n\treturn &lv.Level\n}\n\nfunc inferName(fn string) string {\n\tfn = strings.ToLower(fn)\n\ti := strings.LastIndex(fn, \"\/src\/\")\n\tif i < 0 {\n\t\treturn \"\"\n\t}\n\tdn, fn := path.Split(fn[i+len(\"\/src\/\"):])\n\tif !strings.HasSuffix(fn, \".go\") {\n\t\treturn \"\"\n\t}\n\tfor _, p := range []string{\"\/main\/\", \"\/cmd\/\"} {\n\t\tif strings.HasSuffix(dn, p) {\n\t\t\tdn = dn[:len(dn)-len(p)]\n\t\t\tfn = fn[:len(fn)-len(\".go\")]\n\t\t\treturn path.Join(dn, fn)\n\t\t}\n\t}\n\treturn strings.TrimRight(dn, \"\/\")\n}\n\ntype levelVar struct {\n\tName  string\n\tFile  string\n\tLevel Level\n}\n\nfunc (lv *levelVar) String() string {\n\treturn fmt.Sprintf(\"%s@%s\", lv.Name, lv.File)\n}\n\nvar levelVars = []*levelVar{&levelVar{}} \/\/ default level\n\nfunc Parse() {\n\tflag.Parse()\n\tsetLevels(*vlogFlag)\n\tif *vlogHelp {\n\t\tlg.Log(\"vlog setting:\" + printLevelVars())\n\t\tflag.Usage()\n\t\tos.Exit(2)\n\t}\n\tif *vlogFile != \"\" {\n\t\tlg = newRotateLogger(*vlogFile)\n\t}\n}\n\nfunc ParseEnv() {\n\tif val := os.Getenv(\"GO_VLOG\"); val != \"\" { \/\/ for testing\n\t\tsetLevels(val)\n\t\tlg.Log(printLevelVars())\n\t}\n}\n\nfunc setLevels(value string) {\n\texact, prefix := parseFlag(value)\n\tif v, ok := prefix[\"\/\"]; ok {\n\t\tlevelVars[0].Level = v \/\/ default level\n\t}\n\tdef := levelVars[0].Level\n\tfor _, lv := range levelVars[1:] {\n\t\tlv.Level = def\n\t}\n\tif len(prefix) > 0 {\n\t\tprefixes := make([]string, 0, len(prefix))\n\t\tfor k := range prefix {\n\t\t\tprefixes = append(prefixes, k)\n\t\t}\n\t\tsort.Strings(prefixes)\n\n\t\tfor _, lv := range levelVars[1:] {\n\t\t\tfor i := len(prefixes) - 1; i >= 0; i-- {\n\t\t\t\tk := prefixes[i]\n\t\t\t\t\/\/ Match \"foo\" with \"foo\/\" and \"foo\/bar\" with \"foo\/\"\n\t\t\t\tif lv.Name == k[:len(k)-1] || strings.HasPrefix(lv.Name, k) {\n\t\t\t\t\tlv.Level = prefix[k]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor _, lv := range levelVars[1:] {\n\t\tif i, ok := exact[lv.Name]; ok {\n\t\t\tlv.Level = i\n\t\t}\n\t}\n}\n\nfunc parseFlag(value string) (exact, prefix map[string]Level) {\n\texact = make(map[string]Level)\n\tprefix = make(map[string]Level)\n\ts := value\n\tfor s != \"\" {\n\t\tk := s\n\t\tif i := strings.Index(s, \",\"); i >= 0 {\n\t\t\tk, s = s[:i], s[i+1:]\n\t\t} else {\n\t\t\ts = \"\"\n\t\t}\n\t\tj := strings.Index(k, \"=\")\n\t\tif j < 0 {\n\t\t\tpanic(Format(\"malformed: no level\", value))\n\t\t}\n\t\tk, v := k[:j], k[j+1:]\n\t\tlv := parseLevel(v)\n\t\tk = strings.ToLower(k)\n\t\tpre := false\n\t\tif k == \"*\" || strings.HasSuffix(k, \"\/*\") {\n\t\t\tk = k[:len(k)-1]\n\t\t\tif strings.Contains(k, \"*\") {\n\t\t\t\tpanic(Format(\"malformed: multiple star\", s))\n\t\t\t}\n\t\t\tpre = true\n\t\t} else if strings.Contains(k, \"*\") {\n\t\t\tpanic(Format(\"malformed: star in middle\", s))\n\t\t}\n\t\tk = strings.TrimRight(k, \"\/\")\n\t\tif pre {\n\t\t\tprefix[k+\"\/\"] = lv\n\t\t} else {\n\t\t\texact[k] = lv\n\t\t}\n\t}\n\treturn exact, prefix\n}\n\nfunc printLevelVars() string {\n\tvar b bytes.Buffer\n\tfmt.Fprintf(&b, \"*=%v\", levelVars[0].Level)\n\tfor _, lv := range levelVars[1:] {\n\t\tfmt.Fprintf(&b, \",%s=%v\", lv.Name, lv.Level)\n\t}\n\treturn b.String()\n}\n\nvar (\n\tvlogFlag = flag.String(\"vlog\", \"\", \"vlog settings, k=v(,k=v)*\")\n\tvlogFile = flag.String(\"vlogfile\", \"\", \"vlog file prefix\")\n\tvlogHelp = flag.Bool(\"vloghelp\", false, \"show vlog setting and flag help\")\n)\n\ntype Logger interface {\n\tLog(s string)\n\tFlush()\n}\n\ntype stderrLogger struct {\n\tlg *log.Logger\n}\n\nfunc (l *stderrLogger) Log(s string) {\n\tl.lg.Output(3, s)\n}\n\nfunc (l *stderrLogger) Flush() {}\n\nconst logPrefix = log.Ldate | log.Lmicroseconds | log.Lshortfile\n\n\/\/ lg should always be available\nvar lg Logger = &stderrLogger{lg: log.New(os.Stderr, \"\", logPrefix)}\n\nvar stackTraceBegin = []byte(\"\/vlog.go:\")\n\nfunc stackTrace(s string) string {\n\tvar buf [4 << 10]byte\n\tm := copy(buf[:], s)\n\tn := runtime.Stack(buf[m:], false)\n\tn += m\n\n\t\/\/ Trim the frames in vlog.go, any line that contains \"\/vlog.go:\"\n\tb := buf[m:n]\n\tj := bytes.LastIndex(b, stackTraceBegin)\n\tif j < 0 {\n\t\treturn string(buf[:n])\n\t}\n\tb = b[j:]\n\tj = bytes.IndexAny(b, \"\\n\")\n\tif j < 0 {\n\t\treturn string(buf[:n])\n\t}\n\tb = b[j+1:]\n\tbuf[m] = '\\n' \/\/ put a newline between s and stack frames\n\tn = copy(buf[m+1:], b)\n\tn += m + 1\n\tif buf[n] != '\\n' {\n\t\tbuf[n] = '\\n' \/\/ always end with newline\n\t}\n\treturn string(buf[:n])\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 <chaishushan{AT}gmail.com>. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage protorpc\n\nimport (\n\t\"fmt\"\n\t\"hash\/crc32\"\n\t\"io\"\n\n\twire \"github.com\/chai2010\/protorpc\/wire.pb\"\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/golang\/snappy\"\n)\n\nfunc maxUint32(a, b uint32) uint32 {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc writeRequest(w io.Writer, id uint64, method string, request proto.Message) error {\n\t\/\/ marshal request\n\tpbRequest := []byte{}\n\tif request != nil {\n\t\tvar err error\n\t\tpbRequest, err = proto.Marshal(request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ compress serialized proto data\n\tcompressedPbRequest := snappy.Encode(nil, pbRequest)\n\n\t\/\/ generate header\n\theader := &wire.RequestHeader{\n\t\tId:                         id,\n\t\tMethod:                     method,\n\t\tRawRequestLen:              uint32(len(pbRequest)),\n\t\tSnappyCompressedRequestLen: uint32(len(compressedPbRequest)),\n\t\tChecksum:                   crc32.ChecksumIEEE(compressedPbRequest),\n\t}\n\n\t\/\/ check header size\n\tpbHeader, err := proto.Marshal(header)\n\tif err != err {\n\t\treturn err\n\t}\n\tif len(pbHeader) > int(wire.Const_MAX_REQUEST_HEADER_LEN) {\n\t\treturn fmt.Errorf(\"protorpc.writeRequest: header larger than max_header_len: %d.\", len(pbHeader))\n\t}\n\n\t\/\/ send header (more)\n\tif err := sendFrame(w, pbHeader); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ send body (end)\n\tif err := sendFrame(w, compressedPbRequest); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc readRequestHeader(r io.Reader, header *wire.RequestHeader) (err error) {\n\t\/\/ recv header (more)\n\tpbHeader, err := recvFrame(r, int(wire.Const_MAX_REQUEST_HEADER_LEN))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Marshal Header\n\terr = proto.Unmarshal(pbHeader, header)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc readRequestBody(r io.Reader, header *wire.RequestHeader, request proto.Message) error {\n\tmaxBodyLen := maxUint32(header.RawRequestLen, header.SnappyCompressedRequestLen)\n\n\t\/\/ recv body (end)\n\tcompressedPbRequest, err := recvFrame(r, int(maxBodyLen))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ checksum\n\tif crc32.ChecksumIEEE(compressedPbRequest) != header.Checksum {\n\t\treturn fmt.Errorf(\"protorpc.readRequestBody: unexpected checksum.\")\n\t}\n\n\t\/\/ decode the compressed data\n\tpbRequest, err := snappy.Decode(nil, compressedPbRequest)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ check wire header: rawMsgLen\n\tif uint32(len(pbRequest)) != header.RawRequestLen {\n\t\treturn fmt.Errorf(\"protorpc.readRequestBody: Unexcpeted header.RawRequestLen.\")\n\t}\n\n\t\/\/ Unmarshal to proto message\n\tif request != nil {\n\t\terr = proto.Unmarshal(pbRequest, request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc writeResponse(w io.Writer, id uint64, serr string, response proto.Message) (err error) {\n\t\/\/ clean response if error\n\tif serr != \"\" {\n\t\tresponse = nil\n\t}\n\n\t\/\/ marshal response\n\tpbResponse := []byte{}\n\tif response != nil {\n\t\tpbResponse, err = proto.Marshal(response)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ compress serialized proto data\n\tcompressedPbResponse := snappy.Encode(nil, pbResponse)\n\n\t\/\/ generate header\n\theader := &wire.ResponseHeader{\n\t\tId:                          id,\n\t\tError:                       serr,\n\t\tRawResponseLen:              uint32(len(pbResponse)),\n\t\tSnappyCompressedResponseLen: uint32(len(compressedPbResponse)),\n\t\tChecksum:                    crc32.ChecksumIEEE(compressedPbResponse),\n\t}\n\n\t\/\/ check header size\n\tpbHeader, err := proto.Marshal(header)\n\tif err != err {\n\t\treturn\n\t}\n\n\t\/\/ send header (more)\n\tif err = sendFrame(w, pbHeader); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ send body (end)\n\tif err = sendFrame(w, compressedPbResponse); err != nil {\n\t\treturn\n\t}\n\n\treturn nil\n}\n\nfunc readResponseHeader(r io.Reader, header *wire.ResponseHeader) error {\n\t\/\/ recv header (more)\n\tpbHeader, err := recvFrame(r, int(wire.Const_MAX_REQUEST_HEADER_LEN))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Marshal Header\n\terr = proto.Unmarshal(pbHeader, header)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc readResponseBody(r io.Reader, header *wire.ResponseHeader, response proto.Message) error {\n\tmaxBodyLen := int(maxUint32(header.RawResponseLen, header.SnappyCompressedResponseLen))\n\n\t\/\/ recv body (end)\n\tcompressedPbResponse, err := recvFrame(r, maxBodyLen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ checksum\n\tif crc32.ChecksumIEEE(compressedPbResponse) != header.Checksum {\n\t\treturn fmt.Errorf(\"protorpc.readResponseBody: unexpected checksum.\")\n\t}\n\n\t\/\/ decode the compressed data\n\tpbResponse, err := snappy.Decode(nil, compressedPbResponse)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ check wire header: rawMsgLen\n\tif uint32(len(pbResponse)) != header.RawResponseLen {\n\t\treturn fmt.Errorf(\"protorpc.readResponseBody: Unexcpeted header.RawResponseLen.\")\n\t}\n\n\t\/\/ Unmarshal to proto message\n\tif response != nil {\n\t\terr = proto.Unmarshal(pbResponse, response)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>add UseSappy and UseCrc32ChecksumIEEE<commit_after>\/\/ Copyright 2013 <chaishushan{AT}gmail.com>. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage protorpc\n\nimport (\n\t\"fmt\"\n\t\"hash\/crc32\"\n\t\"io\"\n\n\twire \"github.com\/chai2010\/protorpc\/wire.pb\"\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/golang\/snappy\"\n)\n\nvar (\n\tUseSappy             = true\n\tUseCrc32ChecksumIEEE = true\n)\n\nfunc maxUint32(a, b uint32) uint32 {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc writeRequest(w io.Writer, id uint64, method string, request proto.Message) error {\n\t\/\/ marshal request\n\tpbRequest := []byte{}\n\tif request != nil {\n\t\tvar err error\n\t\tpbRequest, err = proto.Marshal(request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ compress serialized proto data\n\tcompressedPbRequest := snappy.Encode(nil, pbRequest)\n\n\t\/\/ generate header\n\theader := &wire.RequestHeader{\n\t\tId:                         id,\n\t\tMethod:                     method,\n\t\tRawRequestLen:              uint32(len(pbRequest)),\n\t\tSnappyCompressedRequestLen: uint32(len(compressedPbRequest)),\n\t\tChecksum:                   crc32.ChecksumIEEE(compressedPbRequest),\n\t}\n\n\tif !UseSappy {\n\t\theader.SnappyCompressedRequestLen = 0\n\t\tcompressedPbRequest = pbRequest\n\t}\n\tif !UseCrc32ChecksumIEEE {\n\t\theader.Checksum = 0\n\t}\n\n\t\/\/ check header size\n\tpbHeader, err := proto.Marshal(header)\n\tif err != err {\n\t\treturn err\n\t}\n\tif len(pbHeader) > int(wire.Const_MAX_REQUEST_HEADER_LEN) {\n\t\treturn fmt.Errorf(\"protorpc.writeRequest: header larger than max_header_len: %d.\", len(pbHeader))\n\t}\n\n\t\/\/ send header (more)\n\tif err := sendFrame(w, pbHeader); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ send body (end)\n\tif err := sendFrame(w, compressedPbRequest); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc readRequestHeader(r io.Reader, header *wire.RequestHeader) (err error) {\n\t\/\/ recv header (more)\n\tpbHeader, err := recvFrame(r, int(wire.Const_MAX_REQUEST_HEADER_LEN))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Marshal Header\n\terr = proto.Unmarshal(pbHeader, header)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc readRequestBody(r io.Reader, header *wire.RequestHeader, request proto.Message) error {\n\tmaxBodyLen := maxUint32(header.RawRequestLen, header.SnappyCompressedRequestLen)\n\n\t\/\/ recv body (end)\n\tcompressedPbRequest, err := recvFrame(r, int(maxBodyLen))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ checksum\n\tif header.Checksum != 0 {\n\t\tif crc32.ChecksumIEEE(compressedPbRequest) != header.Checksum {\n\t\t\treturn fmt.Errorf(\"protorpc.readRequestBody: unexpected checksum.\")\n\t\t}\n\t}\n\n\tvar pbRequest []byte\n\tif header.SnappyCompressedRequestLen != 0 {\n\t\t\/\/ decode the compressed data\n\t\tpbRequest, err = snappy.Decode(nil, compressedPbRequest)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ check wire header: rawMsgLen\n\t\tif uint32(len(pbRequest)) != header.RawRequestLen {\n\t\t\treturn fmt.Errorf(\"protorpc.readRequestBody: Unexcpeted header.RawRequestLen.\")\n\t\t}\n\t} else {\n\t\tpbRequest = compressedPbRequest\n\t}\n\n\t\/\/ Unmarshal to proto message\n\tif request != nil {\n\t\terr = proto.Unmarshal(pbRequest, request)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc writeResponse(w io.Writer, id uint64, serr string, response proto.Message) (err error) {\n\t\/\/ clean response if error\n\tif serr != \"\" {\n\t\tresponse = nil\n\t}\n\n\t\/\/ marshal response\n\tpbResponse := []byte{}\n\tif response != nil {\n\t\tpbResponse, err = proto.Marshal(response)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ compress serialized proto data\n\tcompressedPbResponse := snappy.Encode(nil, pbResponse)\n\n\t\/\/ generate header\n\theader := &wire.ResponseHeader{\n\t\tId:                          id,\n\t\tError:                       serr,\n\t\tRawResponseLen:              uint32(len(pbResponse)),\n\t\tSnappyCompressedResponseLen: uint32(len(compressedPbResponse)),\n\t\tChecksum:                    crc32.ChecksumIEEE(compressedPbResponse),\n\t}\n\n\tif !UseSappy {\n\t\theader.SnappyCompressedResponseLen = 0\n\t\tcompressedPbResponse = pbResponse\n\t}\n\tif !UseCrc32ChecksumIEEE {\n\t\theader.Checksum = 0\n\t}\n\n\t\/\/ check header size\n\tpbHeader, err := proto.Marshal(header)\n\tif err != err {\n\t\treturn\n\t}\n\n\t\/\/ send header (more)\n\tif err = sendFrame(w, pbHeader); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ send body (end)\n\tif err = sendFrame(w, compressedPbResponse); err != nil {\n\t\treturn\n\t}\n\n\treturn nil\n}\n\nfunc readResponseHeader(r io.Reader, header *wire.ResponseHeader) error {\n\t\/\/ recv header (more)\n\tpbHeader, err := recvFrame(r, int(wire.Const_MAX_REQUEST_HEADER_LEN))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Marshal Header\n\terr = proto.Unmarshal(pbHeader, header)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc readResponseBody(r io.Reader, header *wire.ResponseHeader, response proto.Message) error {\n\tmaxBodyLen := int(maxUint32(header.RawResponseLen, header.SnappyCompressedResponseLen))\n\n\t\/\/ recv body (end)\n\tcompressedPbResponse, err := recvFrame(r, maxBodyLen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ checksum\n\tif header.Checksum != 0 {\n\t\tif crc32.ChecksumIEEE(compressedPbResponse) != header.Checksum {\n\t\t\treturn fmt.Errorf(\"protorpc.readResponseBody: unexpected checksum.\")\n\t\t}\n\t}\n\n\tvar pbResponse []byte\n\tif header.SnappyCompressedResponseLen != 0 {\n\t\t\/\/ decode the compressed data\n\t\tpbResponse, err = snappy.Decode(nil, compressedPbResponse)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ check wire header: rawMsgLen\n\t\tif uint32(len(pbResponse)) != header.RawResponseLen {\n\t\t\treturn fmt.Errorf(\"protorpc.readResponseBody: Unexcpeted header.RawResponseLen.\")\n\t\t}\n\t} else {\n\t\tpbResponse = compressedPbResponse\n\t}\n\n\t\/\/ Unmarshal to proto message\n\tif response != nil {\n\t\terr = proto.Unmarshal(pbResponse, response)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Ardan Studios. All rights reserved.\n\/\/ Use of this source code is governed by a MIT\n\/\/ license that can be found in the LICENSE handle.\n\n\/\/ Package work manages a pool of routines to perform work.\npackage work\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\nconst (\n\taddRoutine = 1\n\trmvRoutine = 2\n)\n\n\/\/ ErrorInvalidMinRoutines is the error for the invalid minRoutine parameter.\nvar ErrorInvalidMinRoutines = errors.New(\"Invalid minimum number of routines\")\n\n\/\/ ErrorInvalidIdleTime is the error for the invalid idle time parameter.\nvar ErrorInvalidIdleTime = errors.New(\"Invalid duration for idle time\")\n\n\/\/ ErrorInvalidStatTime is the error for the invalid stat time parameter.\nvar ErrorInvalidStatTime = errors.New(\"Invalid duration for stat time\")\n\n\/\/ Worker must be implemented by types that want to use\n\/\/ this worker processes.\ntype Worker interface {\n\tWork(id int)\n}\n\n\/\/ Work provides a pool of routines that can execute any Worker\n\/\/ tasks that are submitted.\ntype Work struct {\n\tminRoutines int            \/\/ Minumum number of routines always in the pool.\n\tidleTime    time.Duration  \/\/ Time for routines to die on idle.\n\tstatTime    time.Duration  \/\/ Time to display stats.\n\tcounter     int            \/\/ Maintains a running total number of routines ever created.\n\ttasks       chan Worker    \/\/ Unbuffered channel that work is sent into.\n\tcontrol     chan int       \/\/ Unbuffered channel that work for the manager is send into.\n\tkill        chan struct{}  \/\/ Unbuffered channel to signal for a goroutine to die.\n\tshutdown    chan struct{}  \/\/ Closed when the Work pool is being shutdown.\n\twg          sync.WaitGroup \/\/ Manages the number of routines for shutdown.\n\troutines    int64          \/\/ Number of routines\n\tactive      int64          \/\/ Active number of routines in the work pool.\n\tpending     int64          \/\/ Pending number of routines waiting to submit work.\n}\n\n\/\/ manager controls changes to the work pool including stats\n\/\/ and shutting down.\nfunc (w *Work) manager() {\n\tw.wg.Add(1)\n\n\tgo func() {\n\t\tlog.Println(\"Work : manager : Started\")\n\n\t\t\/\/ Create a timer to run stats.\n\t\tvar stats <-chan time.Time\n\t\ttimer := time.NewTimer(w.statTime)\n\t\tstats = timer.C\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-w.shutdown:\n\t\t\t\t\/\/ Capture the current number of routines.\n\t\t\t\troutines := int(atomic.LoadInt64(&w.routines))\n\n\t\t\t\t\/\/ Send a kill to all the existing routines.\n\t\t\t\tfor i := 0; i < routines; i++ {\n\t\t\t\t\tw.kill <- struct{}{}\n\t\t\t\t}\n\n\t\t\t\t\/\/ Decrement the waitgroup and kill the manager.\n\t\t\t\tw.wg.Done()\n\t\t\t\treturn\n\n\t\t\tcase c := <-w.control:\n\t\t\t\tswitch c {\n\t\t\t\tcase addRoutine:\n\t\t\t\t\tlog.Println(\"Work : manager : Info : Add Routine\")\n\n\t\t\t\t\t\/\/ Capture a unique id.\n\t\t\t\t\tw.counter++\n\n\t\t\t\t\t\/\/ Add to the counts.\n\t\t\t\t\tw.wg.Add(1)\n\t\t\t\t\tatomic.AddInt64(&w.routines, 1)\n\n\t\t\t\t\t\/\/ Create the routine.\n\t\t\t\t\tgo w.work(w.counter)\n\n\t\t\t\tcase rmvRoutine:\n\t\t\t\t\tlog.Println(\"Work : manager : Info : Remove Routine\")\n\n\t\t\t\t\t\/\/ Capture the number of routines.\n\t\t\t\t\troutines := int(atomic.LoadInt64(&w.routines))\n\n\t\t\t\t\t\/\/ Are there routines to remove.\n\t\t\t\t\tif routines <= w.minRoutines {\n\t\t\t\t\t\tlog.Println(\"Work : manager : Info : Remove Routine Cancelled\")\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Send a kill signal to remove a routine.\n\t\t\t\t\tw.kill <- struct{}{}\n\t\t\t\t}\n\n\t\t\tcase <-stats:\n\t\t\t\t\/\/ Capture the stats.\n\t\t\t\troutines := atomic.LoadInt64(&w.routines)\n\t\t\t\tpending := atomic.LoadInt64(&w.pending)\n\t\t\t\tactive := atomic.LoadInt64(&w.active)\n\n\t\t\t\t\/\/ Display the stats.\n\t\t\t\tfmt.Printf(\"Work : manager : Stats : G[%d] P[%d] A[%d]\\n\", routines, pending, active)\n\n\t\t\t\t\/\/ Reset the clock.\n\t\t\t\ttimer.Reset(w.statTime)\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\/\/ New creates a new Worker.\nfunc New(minRoutines int, idleTime time.Duration, statTime time.Duration) (*Work, error) {\n\tif minRoutines < 0 {\n\t\treturn nil, ErrorInvalidMinRoutines\n\t}\n\n\tif idleTime < time.Minute {\n\t\treturn nil, ErrorInvalidIdleTime\n\t}\n\n\tif statTime < time.Millisecond {\n\t\treturn nil, ErrorInvalidStatTime\n\t}\n\n\tw := Work{\n\t\tminRoutines: minRoutines,\n\t\tidleTime:    idleTime,\n\t\tstatTime:    statTime,\n\t\ttasks:       make(chan Worker),\n\t\tcontrol:     make(chan int),\n\t\tkill:        make(chan struct{}),\n\t\tshutdown:    make(chan struct{}),\n\t}\n\n\t\/\/ Start the manager.\n\tw.manager()\n\n\t\/\/ Add the routines.\n\tw.Add(minRoutines)\n\n\treturn &w, nil\n}\n\n\/\/ Add creates routines to process work or sets a count for\n\/\/ routines to terminate.\nfunc (w *Work) Add(routines int) {\n\tif routines == 0 {\n\t\treturn\n\t}\n\n\tcmd := addRoutine\n\tif routines < 0 {\n\t\troutines = routines * -1\n\t\tcmd = rmvRoutine\n\t}\n\n\tfor i := 0; i < routines; i++ {\n\t\tw.control <- cmd\n\t}\n}\n\n\/\/ work performs the users work and keeps stats.\nfunc (w *Work) work(id int) {\n\t\/\/ Create a timer to track idle time.\n\tvar idle <-chan time.Time\n\tvar timer *time.Timer\n\n\t\/\/ Set the timer for routines about the min mark.\n\tif id > w.minRoutines {\n\t\ttimer = time.NewTimer(w.idleTime)\n\t\tidle = timer.C\n\t}\n\ndone:\n\tfor {\n\t\tselect {\n\t\tcase t := <-w.tasks:\n\t\t\tatomic.AddInt64(&w.active, 1)\n\t\t\t{\n\t\t\t\t\/\/ Perform the work.\n\t\t\t\tt.Work(id)\n\t\t\t}\n\t\t\tatomic.AddInt64(&w.active, -1)\n\n\t\tcase <-w.kill:\n\t\t\tbreak done\n\n\t\tcase <-idle:\n\t\t\tbreak done\n\t\t}\n\n\t\t\/\/ If this goroutine can die on idle time\n\t\t\/\/ then reset the timer.\n\t\tif timer != nil {\n\t\t\ttimer.Reset(w.idleTime)\n\t\t}\n\t}\n\n\t\/\/ Decrement the counts.\n\tatomic.AddInt64(&w.routines, -1)\n\tw.wg.Done()\n\n\tlog.Println(\"Work : gr : Info : Shutdown\")\n}\n\n\/\/ Run wait for the goroutine pool to take the work\n\/\/ to be executed.\nfunc (w *Work) Run(work Worker) {\n\tatomic.AddInt64(&w.pending, 1)\n\t{\n\t\tw.tasks <- work\n\t}\n\tatomic.AddInt64(&w.pending, -1)\n}\n\n\/\/ Shutdown waits for all the workers to finish.\nfunc (w *Work) Shutdown() {\n\tclose(w.shutdown)\n\tw.wg.Wait()\n}\n<commit_msg>Removed idle time. Goroutines are cheap and this is un-necessary.<commit_after>\/\/ Copyright 2014 Ardan Studios. All rights reserved.\n\/\/ Use of this source code is governed by a MIT\n\/\/ license that can be found in the LICENSE handle.\n\n\/\/ Package work manages a pool of routines to perform work.\npackage work\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\nconst (\n\taddRoutine = 1\n\trmvRoutine = 2\n)\n\n\/\/ ErrorInvalidMinRoutines is the error for the invalid minRoutine parameter.\nvar ErrorInvalidMinRoutines = errors.New(\"Invalid minimum number of routines\")\n\n\/\/ ErrorInvalidStatTime is the error for the invalid stat time parameter.\nvar ErrorInvalidStatTime = errors.New(\"Invalid duration for stat time\")\n\n\/\/ Worker must be implemented by types that want to use\n\/\/ this worker processes.\ntype Worker interface {\n\tWork(id int)\n}\n\n\/\/ Work provides a pool of routines that can execute any Worker\n\/\/ tasks that are submitted.\ntype Work struct {\n\tminRoutines int            \/\/ Minumum number of routines always in the pool.\n\tstatTime    time.Duration  \/\/ Time to display stats.\n\tcounter     int            \/\/ Maintains a running total number of routines ever created.\n\ttasks       chan Worker    \/\/ Unbuffered channel that work is sent into.\n\tcontrol     chan int       \/\/ Unbuffered channel that work for the manager is send into.\n\tkill        chan struct{}  \/\/ Unbuffered channel to signal for a goroutine to die.\n\tshutdown    chan struct{}  \/\/ Closed when the Work pool is being shutdown.\n\twg          sync.WaitGroup \/\/ Manages the number of routines for shutdown.\n\troutines    int64          \/\/ Number of routines\n\tactive      int64          \/\/ Active number of routines in the work pool.\n\tpending     int64          \/\/ Pending number of routines waiting to submit work.\n}\n\n\/\/ New creates a new Worker.\nfunc New(minRoutines int, statTime time.Duration) (*Work, error) {\n\tif minRoutines < 0 {\n\t\treturn nil, ErrorInvalidMinRoutines\n\t}\n\n\tif statTime < time.Millisecond {\n\t\treturn nil, ErrorInvalidStatTime\n\t}\n\n\tw := Work{\n\t\tminRoutines: minRoutines,\n\t\tstatTime:    statTime,\n\t\ttasks:       make(chan Worker),\n\t\tcontrol:     make(chan int),\n\t\tkill:        make(chan struct{}),\n\t\tshutdown:    make(chan struct{}),\n\t}\n\n\t\/\/ Start the manager.\n\tw.manager()\n\n\t\/\/ Add the routines.\n\tw.Add(minRoutines)\n\n\treturn &w, nil\n}\n\n\/\/ Add creates routines to process work or sets a count for\n\/\/ routines to terminate.\nfunc (w *Work) Add(routines int) {\n\tif routines == 0 {\n\t\treturn\n\t}\n\n\tcmd := addRoutine\n\tif routines < 0 {\n\t\troutines = routines * -1\n\t\tcmd = rmvRoutine\n\t}\n\n\tfor i := 0; i < routines; i++ {\n\t\tw.control <- cmd\n\t}\n}\n\n\/\/ work performs the users work and keeps stats.\nfunc (w *Work) work(id int) {\ndone:\n\tfor {\n\t\tselect {\n\t\tcase t := <-w.tasks:\n\t\t\tatomic.AddInt64(&w.active, 1)\n\t\t\t{\n\t\t\t\t\/\/ Perform the work.\n\t\t\t\tt.Work(id)\n\t\t\t}\n\t\t\tatomic.AddInt64(&w.active, -1)\n\n\t\tcase <-w.kill:\n\t\t\tbreak done\n\t\t}\n\t}\n\n\t\/\/ Decrement the counts.\n\tatomic.AddInt64(&w.routines, -1)\n\tw.wg.Done()\n\n\tlog.Println(\"Work : gr : Info : Shutdown\")\n}\n\n\/\/ Run wait for the goroutine pool to take the work\n\/\/ to be executed.\nfunc (w *Work) Run(work Worker) {\n\tatomic.AddInt64(&w.pending, 1)\n\t{\n\t\tw.tasks <- work\n\t}\n\tatomic.AddInt64(&w.pending, -1)\n}\n\n\/\/ Shutdown waits for all the workers to finish.\nfunc (w *Work) Shutdown() {\n\tclose(w.shutdown)\n\tw.wg.Wait()\n}\n\n\/\/ manager controls changes to the work pool including stats\n\/\/ and shutting down.\nfunc (w *Work) manager() {\n\tw.wg.Add(1)\n\n\tgo func() {\n\t\tlog.Println(\"Work : manager : Started\")\n\n\t\t\/\/ Create a timer to run stats.\n\t\ttimer := time.NewTimer(w.statTime)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-w.shutdown:\n\t\t\t\t\/\/ Capture the current number of routines.\n\t\t\t\troutines := int(atomic.LoadInt64(&w.routines))\n\n\t\t\t\t\/\/ Send a kill to all the existing routines.\n\t\t\t\tfor i := 0; i < routines; i++ {\n\t\t\t\t\tw.kill <- struct{}{}\n\t\t\t\t}\n\n\t\t\t\t\/\/ Decrement the waitgroup and kill the manager.\n\t\t\t\tw.wg.Done()\n\t\t\t\treturn\n\n\t\t\tcase c := <-w.control:\n\t\t\t\tswitch c {\n\t\t\t\tcase addRoutine:\n\t\t\t\t\tlog.Println(\"Work : manager : Info : Add Routine\")\n\n\t\t\t\t\t\/\/ Capture a unique id.\n\t\t\t\t\tw.counter++\n\n\t\t\t\t\t\/\/ Add to the counts.\n\t\t\t\t\tw.wg.Add(1)\n\t\t\t\t\tatomic.AddInt64(&w.routines, 1)\n\n\t\t\t\t\t\/\/ Create the routine.\n\t\t\t\t\tgo w.work(w.counter)\n\n\t\t\t\tcase rmvRoutine:\n\t\t\t\t\tlog.Println(\"Work : manager : Info : Remove Routine\")\n\n\t\t\t\t\t\/\/ Capture the number of routines.\n\t\t\t\t\troutines := int(atomic.LoadInt64(&w.routines))\n\n\t\t\t\t\t\/\/ Are there routines to remove.\n\t\t\t\t\tif routines <= w.minRoutines {\n\t\t\t\t\t\tlog.Println(\"Work : manager : Info : Remove Routine Cancelled\")\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Send a kill signal to remove a routine.\n\t\t\t\t\tw.kill <- struct{}{}\n\t\t\t\t}\n\n\t\t\tcase <-timer.C:\n\t\t\t\t\/\/ Capture the stats.\n\t\t\t\troutines := atomic.LoadInt64(&w.routines)\n\t\t\t\tpending := atomic.LoadInt64(&w.pending)\n\t\t\t\tactive := atomic.LoadInt64(&w.active)\n\n\t\t\t\t\/\/ Display the stats.\n\t\t\t\tfmt.Printf(\"Work : manager : Stats : G[%d] P[%d] A[%d]\\n\", routines, pending, active)\n\n\t\t\t\t\/\/ Reset the clock.\n\t\t\t\ttimer.Reset(w.statTime)\n\t\t\t}\n\t\t}\n\t}()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2015 John Ko\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"io\"\n\t\/\/\"mime\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc headHandler(w http.ResponseWriter, r *http.Request) {\n\t\/\/ force close because curl tries to keep open\n\tw.Header().Set(\"Connection\", \"close\")\n\tif allowedHead() {\n\t\tvars := mux.Vars(r)\n\t\thash := vars[\"hash\"]\n\t\t_, _, _, err := storage.Head(hash)\n\t\t\/\/filename, contentLength, _, err := storage.Head(hash)\n\t\t\/\/contentType := mime.TypeByExtension(filepath.Ext(filename))\n\t\tif err != nil {\n\t\t\t\/\/ we only care about the status code\n\t\t\tw.WriteHeader(404)\n\t\t\treturn\n\t\t} else {\n\t\t\t\/\/ you may want the json?\n\t\t\t\/\/fmt.Fprintf(w, \"{\\\"sha512\\\":\\\"%s\\\",\\\"filename\\\":\\\"%s\\\",\\\"length\\\":%d,\\\"content_type\\\":\\\"%s\\\",\\\"stub\\\":true}\", hash, filename, contentLength, strings.Split(contentType, \";\")[0])\n\t\t}\n\t} else {\n\t\t\/\/ we only care about the status code\n\t\tw.WriteHeader(403)\n\t}\n}\n\nfunc SplitHashToPairSlash(token string) string {\n\t\/\/ split hash to pairs because a folder of 400+ items is slow\n\tpairs := regexp.MustCompile(\"[0-9a-f]{2}\").FindAll([]byte(token), -1)\n\t\/\/ join pairs with os.PathSeparator\n\tnewtoken := bytes.Join(pairs, []byte(string(os.PathSeparator)))\n\treturn string(newtoken[:])\n}\n\nfunc NameLengthTime(path string) (filename string, contentLength uint64, modTime time.Time, err error) {\n\t\/\/ content length\n\tvar fi os.FileInfo\n\tif fi, err = os.Lstat(filepath.Join(path, \"data\")); err != nil {\n\t\treturn\n\t}\n\tcontentLength = uint64(fi.Size())\n\tmodTime = fi.ModTime()\n\t\/\/ Use tail to get the last real filename\n\tvar lastname []byte\n\tlastname, _ = exec.Command(cmdTAIL, \"-n\", \"1\", filepath.Join(path, \"filename\")).Output()\n\t\/\/ Assume the first output before space is the mimeType\n\tfilename = strings.TrimSpace(fmt.Sprintf(\"%s\", lastname))\n\treturn\n}\n\nfunc Sha512(str string, word string) (hash string, err error) {\n\t\/\/ FreeBSD specific call \/sbin\/sha512 instead of using the import crypto\/sha512\n\t\/\/ because the import has high memory usage (loads the data in RAM)\n\t\/\/ and Go lang uses garbage collection so the high RAM lingers\n\t\/\/ Assume the output is the hash, need to trim \\n\n\n\t\/\/hash, err := exec.Command(cmdSHA512, \"-q\", \"-s\", word).Output()\n\t\/\/if err != nil {\n\t\/\/      return\n\t\/\/}\n\n\t\/\/ TODO: is shasum more universal on *nix systems?\n\tcmd := exec.Command(cmdSHASUM, \"--algorithm\", \"512\", str)\n\tif word != \"\" {\n\t\tcmd.Stdin = strings.NewReader(word)\n\t}\n\ttmpout, err := cmd.Output()\n\t\/\/ Assume the first output before space is the hash\n\thash = strings.Split(strings.TrimSpace(fmt.Sprintf(\"%s\", tmpout)), \" \")[0]\n\treturn\n}\n\nfunc Sha512Word(word string) (hash string, err error) {\n\thash, err = Sha512(\"-\", word)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (s *LocalStorage) saveFilename(hash string, filename string) {\n\tvar err error\n\tnewpath := filepath.Join(s.basedir, SplitHashToPairSlash(hash))\n\tvar f1 io.WriteCloser\n\tf1, err = os.OpenFile(filepath.Join(newpath, \"filename\"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)\n\tif err == nil {\n\t\tdefer f1.Close()\n\t\tio.Copy(f1, strings.NewReader(fmt.Sprintf(\"%s\\n\", filename)))\n\t}\n}\n\nfunc (s *LocalStorage) HardLinkSha512Path(oldpath string, filename string) (hash string, contentLength uint64, err error) {\n\tvar fi os.FileInfo\n\tif fi, err = os.Lstat(oldpath); err != nil {\n\t\treturn\n\t}\n\tcontentLength = uint64(fi.Size())\n\thash, err = Sha512(oldpath, \"\")\n\tif err != nil {\n\t\treturn\n\t}\n\tnewpath := filepath.Join(s.basedir, SplitHashToPairSlash(hash))\n\t\/\/ mkdir -p\n\tif err = os.MkdirAll(newpath, 0700); err != nil && !os.IsExist(err) {\n\t\treturn\n\t}\n\t\/\/ Link the oldpath to sha512\/data\n\tif err = os.Link(oldpath, filepath.Join(newpath, \"data\")); err != nil {\n\t\tif strings.Index(err.Error(), \"file exists\") >= 0 {\n\t\t\terr = nil\n\t\t}\n\t}\n\tstorage.saveFilename(newpath, filename)\n\tos.Remove(oldpath)\n\treturn\n}\n\nfunc (s *LocalStorage) HardLinkSha512(token string, filename string) (hash string, contentLength uint64, err error) {\n\toldpath := filepath.Join(config.Temp, token, filename)\n\thash, contentLength, err = storage.HardLinkSha512Path(oldpath, filename)\n\treturn\n}\n\nfunc (s *LocalStorage) DeleteFile(token string, filename string) error {\n\toldpath := filepath.Join(config.Temp, token)\n\tos.Remove(filepath.Join(oldpath, filename))\n\tos.Remove(oldpath)\n\treturn nil\n}\n<commit_msg>storage.saveFilename(hash, filename)<commit_after>\/*\nThe MIT License (MIT)\n\nCopyright (c) 2015 John Ko\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/gorilla\/mux\"\n\t\"io\"\n\t\/\/\"mime\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc headHandler(w http.ResponseWriter, r *http.Request) {\n\t\/\/ force close because curl tries to keep open\n\tw.Header().Set(\"Connection\", \"close\")\n\tif allowedHead() {\n\t\tvars := mux.Vars(r)\n\t\thash := vars[\"hash\"]\n\t\t_, _, _, err := storage.Head(hash)\n\t\t\/\/filename, contentLength, _, err := storage.Head(hash)\n\t\t\/\/contentType := mime.TypeByExtension(filepath.Ext(filename))\n\t\tif err != nil {\n\t\t\t\/\/ we only care about the status code\n\t\t\tw.WriteHeader(404)\n\t\t\treturn\n\t\t} else {\n\t\t\t\/\/ you may want the json?\n\t\t\t\/\/fmt.Fprintf(w, \"{\\\"sha512\\\":\\\"%s\\\",\\\"filename\\\":\\\"%s\\\",\\\"length\\\":%d,\\\"content_type\\\":\\\"%s\\\",\\\"stub\\\":true}\", hash, filename, contentLength, strings.Split(contentType, \";\")[0])\n\t\t}\n\t} else {\n\t\t\/\/ we only care about the status code\n\t\tw.WriteHeader(403)\n\t}\n}\n\nfunc SplitHashToPairSlash(token string) string {\n\t\/\/ split hash to pairs because a folder of 400+ items is slow\n\tpairs := regexp.MustCompile(\"[0-9a-f]{2}\").FindAll([]byte(token), -1)\n\t\/\/ join pairs with os.PathSeparator\n\tnewtoken := bytes.Join(pairs, []byte(string(os.PathSeparator)))\n\treturn string(newtoken[:])\n}\n\nfunc NameLengthTime(path string) (filename string, contentLength uint64, modTime time.Time, err error) {\n\t\/\/ content length\n\tvar fi os.FileInfo\n\tif fi, err = os.Lstat(filepath.Join(path, \"data\")); err != nil {\n\t\treturn\n\t}\n\tcontentLength = uint64(fi.Size())\n\tmodTime = fi.ModTime()\n\t\/\/ Use tail to get the last real filename\n\tvar lastname []byte\n\tlastname, _ = exec.Command(cmdTAIL, \"-n\", \"1\", filepath.Join(path, \"filename\")).Output()\n\t\/\/ Assume the first output before space is the mimeType\n\tfilename = strings.TrimSpace(fmt.Sprintf(\"%s\", lastname))\n\treturn\n}\n\nfunc Sha512(str string, word string) (hash string, err error) {\n\t\/\/ FreeBSD specific call \/sbin\/sha512 instead of using the import crypto\/sha512\n\t\/\/ because the import has high memory usage (loads the data in RAM)\n\t\/\/ and Go lang uses garbage collection so the high RAM lingers\n\t\/\/ Assume the output is the hash, need to trim \\n\n\n\t\/\/hash, err := exec.Command(cmdSHA512, \"-q\", \"-s\", word).Output()\n\t\/\/if err != nil {\n\t\/\/      return\n\t\/\/}\n\n\t\/\/ TODO: is shasum more universal on *nix systems?\n\tcmd := exec.Command(cmdSHASUM, \"--algorithm\", \"512\", str)\n\tif word != \"\" {\n\t\tcmd.Stdin = strings.NewReader(word)\n\t}\n\ttmpout, err := cmd.Output()\n\t\/\/ Assume the first output before space is the hash\n\thash = strings.Split(strings.TrimSpace(fmt.Sprintf(\"%s\", tmpout)), \" \")[0]\n\treturn\n}\n\nfunc Sha512Word(word string) (hash string, err error) {\n\thash, err = Sha512(\"-\", word)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (s *LocalStorage) saveFilename(hash string, filename string) {\n\tvar err error\n\tnewpath := filepath.Join(s.basedir, SplitHashToPairSlash(hash))\n\tvar f1 io.WriteCloser\n\tf1, err = os.OpenFile(filepath.Join(newpath, \"filename\"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)\n\tif err == nil {\n\t\tdefer f1.Close()\n\t\tio.Copy(f1, strings.NewReader(fmt.Sprintf(\"%s\\n\", filename)))\n\t}\n}\n\nfunc (s *LocalStorage) HardLinkSha512Path(oldpath string, filename string) (hash string, contentLength uint64, err error) {\n\tvar fi os.FileInfo\n\tif fi, err = os.Lstat(oldpath); err != nil {\n\t\treturn\n\t}\n\tcontentLength = uint64(fi.Size())\n\thash, err = Sha512(oldpath, \"\")\n\tif err != nil {\n\t\treturn\n\t}\n\tnewpath := filepath.Join(s.basedir, SplitHashToPairSlash(hash))\n\t\/\/ mkdir -p\n\tif err = os.MkdirAll(newpath, 0700); err != nil && !os.IsExist(err) {\n\t\treturn\n\t}\n\t\/\/ Link the oldpath to sha512\/data\n\tif err = os.Link(oldpath, filepath.Join(newpath, \"data\")); err != nil {\n\t\tif strings.Index(err.Error(), \"file exists\") >= 0 {\n\t\t\terr = nil\n\t\t}\n\t}\n\tstorage.saveFilename(hash, filename)\n\tos.Remove(oldpath)\n\treturn\n}\n\nfunc (s *LocalStorage) HardLinkSha512(token string, filename string) (hash string, contentLength uint64, err error) {\n\toldpath := filepath.Join(config.Temp, token, filename)\n\thash, contentLength, err = storage.HardLinkSha512Path(oldpath, filename)\n\treturn\n}\n\nfunc (s *LocalStorage) DeleteFile(token string, filename string) error {\n\toldpath := filepath.Join(config.Temp, token)\n\tos.Remove(filepath.Join(oldpath, filename))\n\tos.Remove(oldpath)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package dbsplitter\n\nimport (\n\t\"fmt\"\n\t\"github.com\/go-xorm\/xorm\"\n)\n\ntype DbSplitterXorm struct{}\n\nfunc (d *DbSplitterXorm) GetEngines(dbs []string) (map[string]*xorm.Engine, error) {\n\tengines := map[string]*xorm.Engine{}\n\tfor _, db := range dbs {\n\t\tparams := getConnectionStrings(db)\n\t\tengines[db] = d.getEngine(params)\n\t}\n\treturn engines, nil\n}\n\nfunc (d *DbSplitterXorm) getEngine(params map[string]string) *xorm.Engine {\n\tdsn := d.parseParameter(params)\n\tdb, err := xorm.NewEngine(\"mysql\", dsn)\n\tif err != nil {\n\t\tpanic(\"cannot get engines. params=\" + dsn)\n\t}\n\treturn db\n}\n\nfunc (d *DbSplitterXorm) parseParameter(params map[string]string) string {\n\treturn fmt.Sprintf(\"%s:%s@tcp(%s:%s)\/%s?charset=utf8\", params[\"user\"], params[\"pass\"], params[\"host\"], params[\"port\"], params[\"dbname\"])\n}\n<commit_msg>Change xorm naming mapper to Gonic<commit_after>package dbsplitter\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/go-xorm\/xorm\"\n\t\"github.com\/go-xorm\/core\"\n)\n\ntype DbSplitterXorm struct{}\n\nfunc (d *DbSplitterXorm) GetEngines(dbs []string) (map[string]*xorm.Engine, error) {\n\tengines := map[string]*xorm.Engine{}\n\tfor _, db := range dbs {\n\t\tparams := getConnectionStrings(db)\n\t\tengines[db] = d.getEngine(params)\n\t}\n\treturn engines, nil\n}\n\nfunc (d *DbSplitterXorm) getEngine(params map[string]string) *xorm.Engine {\n\tdsn := d.parseParameter(params)\n\tdb, err := xorm.NewEngine(\"mysql\", dsn)\n\tif err != nil {\n\t\tpanic(\"cannot get engines. params=\" + dsn)\n\t}\n\tdb.SetMapper(core.NewCacheMapper(new(core.GonicMapper)))\n\treturn db\n}\n\nfunc (d *DbSplitterXorm) parseParameter(params map[string]string) string {\n\treturn fmt.Sprintf(\"%s:%s@tcp(%s:%s)\/%s?charset=utf8\", params[\"user\"], params[\"pass\"], params[\"host\"], params[\"port\"], params[\"dbname\"])\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/crooks\/yamn\/config\"\n\t\"github.com\/crooks\/yamn\/idlog\"\n\t\"github.com\/crooks\/yamn\/keymgr\"\n\t\"github.com\/luksen\/maildir\"\n)\n\nconst (\n\tversion        string = \"0.2.5\"\n\tdayLength      int    = 24 * 60 * 60 \/\/ Day in seconds\n\tmaxFragLength         = 17910\n\tmaxCopies             = 5\n\tbase64LineWrap        = 64\n\trfc5322date           = \"Mon, 2 Jan 2006 15:04:05 -0700\"\n\tshortdate             = \"2 Jan 2006\"\n)\n\nvar (\n\t\/\/ flags - Command line flags\n\tflags *config.Flags\n\t\/\/ cfg - Config parameters\n\tcfg *config.Config\n\t\/\/ Trace loglevel\n\tTrace *log.Logger\n\t\/\/ Info loglevel\n\tInfo *log.Logger\n\t\/\/ Warn loglevel\n\tWarn *log.Logger\n\t\/\/ Error loglevel\n\tError *log.Logger\n\t\/\/ Pubring - Public Keyring\n\tPubring *keymgr.Pubring\n\t\/\/ IDDb - Message ID log (replay protection)\n\tIDDb *idlog.IDLog\n\t\/\/ ChunkDb - Chunk database\n\tChunkDb *Chunk\n)\n\nfunc logInit(\n\ttraceHandle io.Writer,\n\tinfoHandle io.Writer,\n\twarnHandle io.Writer,\n\terrorHandle io.Writer) {\n\n\tTrace = log.New(traceHandle,\n\t\t\"Trace: \",\n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n\n\tInfo = log.New(infoHandle,\n\t\t\"Info: \",\n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n\n\tWarn = log.New(warnHandle,\n\t\t\"Warn: \",\n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n\n\tError = log.New(errorHandle,\n\t\t\"Error: \",\n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n}\n\nfunc main() {\n\tvar err error\n\tflags = config.ParseFlags()\n\t\/\/ Some config defaults are derived from flags so ParseConfig is a flags method\n\tcfg, err = flags.ParseConfig()\n\tif err != nil {\n\t\t\/\/ No logging is defined at this point so log the error to stderr\n\t\tfmt.Fprintf(os.Stderr, \"Unable to parse config file: %v\", err)\n\t\tos.Exit(1)\n\t}\n\tif cfg.General.LogToFile {\n\t\tlogfile, err := os.OpenFile(\n\t\t\tcfg.Files.Logfile,\n\t\t\tos.O_RDWR|os.O_CREATE|os.O_APPEND,\n\t\t\t0640,\n\t\t)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(\n\t\t\t\tos.Stderr,\n\t\t\t\t\"Error opening logfile: %s.\\n\",\n\t\t\t\terr,\n\t\t\t)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tswitch strings.ToLower(cfg.General.Loglevel) {\n\t\tcase \"trace\":\n\t\t\tlogInit(logfile,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t)\n\t\tcase \"info\":\n\t\t\tlogInit(ioutil.Discard,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t)\n\t\tcase \"warn\":\n\t\t\tlogInit(ioutil.Discard,\n\t\t\t\tioutil.Discard,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t)\n\t\tcase \"error\":\n\t\t\tlogInit(ioutil.Discard,\n\t\t\t\tioutil.Discard,\n\t\t\t\tioutil.Discard,\n\t\t\t\tlogfile,\n\t\t\t)\n\t\tdefault:\n\t\t\tfmt.Fprintf(\n\t\t\t\tos.Stderr,\n\t\t\t\t\"Unknown loglevel: %s.  Assuming \\\"Info\\\".\\n\",\n\t\t\t\tcfg.General.Loglevel,\n\t\t\t)\n\t\t\tlogInit(ioutil.Discard,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t)\n\t\t}\n\t} else {\n\t\tswitch strings.ToLower(cfg.General.Loglevel) {\n\t\tcase \"trace\":\n\t\t\tlogInit(os.Stdout,\n\t\t\t\tos.Stdout,\n\t\t\t\tos.Stdout,\n\t\t\t\tos.Stderr,\n\t\t\t)\n\t\tcase \"info\":\n\t\t\tlogInit(ioutil.Discard,\n\t\t\t\tos.Stdout,\n\t\t\t\tos.Stdout,\n\t\t\t\tos.Stderr,\n\t\t\t)\n\t\tcase \"warn\":\n\t\t\tlogInit(ioutil.Discard,\n\t\t\t\tioutil.Discard,\n\t\t\t\tos.Stdout,\n\t\t\t\tos.Stderr,\n\t\t\t)\n\t\tcase \"error\":\n\t\t\tlogInit(\n\t\t\t\tioutil.Discard,\n\t\t\t\tioutil.Discard,\n\t\t\t\tioutil.Discard,\n\t\t\t\tos.Stderr,\n\t\t\t)\n\t\tdefault:\n\t\t\tfmt.Fprintf(\n\t\t\t\tos.Stderr,\n\t\t\t\t\"Unknown loglevel: %s.  Assuming \\\"Info\\\".\\n\",\n\t\t\t\tcfg.General.Loglevel,\n\t\t\t)\n\t\t\tlogInit(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)\n\t\t} \/\/ End of stdout\/stderr logging setup\n\t} \/\/ End of logging setup\n\n\t\/\/ Inform the user which (if any) config file was used.\n\tif cfg.Files.Config != \"\" {\n\t\tInfo.Printf(\"Using config file: %s\", cfg.Files.Config)\n\t} else {\n\t\tWarn.Println(\"No config file was found. Resorting to defaults\")\n\t}\n\n\t\/\/ If the debug flag is set, print the config in JSON format and then exit.\n\tif flags.Debug {\n\t\ty, err := cfg.Debug()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Debugging Error: %s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", y)\n\t\tos.Exit(0)\n\t}\n\n\tif flags.Client {\n\t\tmixprep()\n\t} else if flags.Stdin {\n\t\tdir := maildir.Dir(cfg.Files.Maildir)\n\t\tnewmsg, err := dir.NewDelivery()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tstdin, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tnewmsg.Write(stdin)\n\t\tnewmsg.Close()\n\t} else if flags.Remailer {\n\t\terr = loopServer()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else if flags.Dummy {\n\t\tinjectDummy()\n\t} else if flags.Refresh {\n\t\tfmt.Printf(\"Keyring refresh: from=%s, to=%s\\n\", cfg.Urls.Pubring, cfg.Files.Pubring)\n\t\thttpGet(cfg.Urls.Pubring, cfg.Files.Pubring)\n\t\tfmt.Printf(\"Stats refresh: from=%s, to=%s\\n\", cfg.Urls.Mlist2, cfg.Files.Mlist2)\n\t\thttpGet(cfg.Urls.Mlist2, cfg.Files.Mlist2)\n\t}\n\tif flags.Send {\n\t\t\/\/ Flush the outbound pool\n\t\tpoolOutboundSend()\n\t}\n}\n<commit_msg>Do debugging in YAML and fix the version flag<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/crooks\/yamn\/config\"\n\t\"github.com\/crooks\/yamn\/idlog\"\n\t\"github.com\/crooks\/yamn\/keymgr\"\n\t\"github.com\/luksen\/maildir\"\n)\n\nconst (\n\tversion        string = \"0.2.5\"\n\tdayLength      int    = 24 * 60 * 60 \/\/ Day in seconds\n\tmaxFragLength         = 17910\n\tmaxCopies             = 5\n\tbase64LineWrap        = 64\n\trfc5322date           = \"Mon, 2 Jan 2006 15:04:05 -0700\"\n\tshortdate             = \"2 Jan 2006\"\n)\n\nvar (\n\t\/\/ flags - Command line flags\n\tflags *config.Flags\n\t\/\/ cfg - Config parameters\n\tcfg *config.Config\n\t\/\/ Trace loglevel\n\tTrace *log.Logger\n\t\/\/ Info loglevel\n\tInfo *log.Logger\n\t\/\/ Warn loglevel\n\tWarn *log.Logger\n\t\/\/ Error loglevel\n\tError *log.Logger\n\t\/\/ Pubring - Public Keyring\n\tPubring *keymgr.Pubring\n\t\/\/ IDDb - Message ID log (replay protection)\n\tIDDb *idlog.IDLog\n\t\/\/ ChunkDb - Chunk database\n\tChunkDb *Chunk\n)\n\nfunc logInit(\n\ttraceHandle io.Writer,\n\tinfoHandle io.Writer,\n\twarnHandle io.Writer,\n\terrorHandle io.Writer) {\n\n\tTrace = log.New(traceHandle,\n\t\t\"Trace: \",\n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n\n\tInfo = log.New(infoHandle,\n\t\t\"Info: \",\n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n\n\tWarn = log.New(warnHandle,\n\t\t\"Warn: \",\n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n\n\tError = log.New(errorHandle,\n\t\t\"Error: \",\n\t\tlog.Ldate|log.Ltime|log.Lshortfile)\n}\n\nfunc main() {\n\tvar err error\n\tflags = config.ParseFlags()\n\tif flags.Version {\n\t\tfmt.Println(version)\n\t\tos.Exit(0)\n\t}\n\t\/\/ Some config defaults are derived from flags so ParseConfig is a flags method\n\tcfg, err = flags.ParseConfig()\n\tif err != nil {\n\t\t\/\/ No logging is defined at this point so log the error to stderr\n\t\tfmt.Fprintf(os.Stderr, \"Unable to parse config file: %v\", err)\n\t\tos.Exit(1)\n\t}\n\t\/\/ If the debug flag is set, print the config and exit\n\tif flags.Debug {\n\t\ty, err := cfg.Debug()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Debugging Error: %s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", y)\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Set up some logging based on loglevel and LogToFile\n\tif cfg.General.LogToFile {\n\t\tlogfile, err := os.OpenFile(\n\t\t\tcfg.Files.Logfile,\n\t\t\tos.O_RDWR|os.O_CREATE|os.O_APPEND,\n\t\t\t0640,\n\t\t)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(\n\t\t\t\tos.Stderr,\n\t\t\t\t\"Error opening logfile: %s.\\n\",\n\t\t\t\terr,\n\t\t\t)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tswitch strings.ToLower(cfg.General.Loglevel) {\n\t\tcase \"trace\":\n\t\t\tlogInit(logfile,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t)\n\t\tcase \"info\":\n\t\t\tlogInit(ioutil.Discard,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t)\n\t\tcase \"warn\":\n\t\t\tlogInit(ioutil.Discard,\n\t\t\t\tioutil.Discard,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t)\n\t\tcase \"error\":\n\t\t\tlogInit(ioutil.Discard,\n\t\t\t\tioutil.Discard,\n\t\t\t\tioutil.Discard,\n\t\t\t\tlogfile,\n\t\t\t)\n\t\tdefault:\n\t\t\tfmt.Fprintf(\n\t\t\t\tos.Stderr,\n\t\t\t\t\"Unknown loglevel: %s.  Assuming \\\"Info\\\".\\n\",\n\t\t\t\tcfg.General.Loglevel,\n\t\t\t)\n\t\t\tlogInit(ioutil.Discard,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t\tlogfile,\n\t\t\t)\n\t\t}\n\t} else {\n\t\tswitch strings.ToLower(cfg.General.Loglevel) {\n\t\tcase \"trace\":\n\t\t\tlogInit(os.Stdout,\n\t\t\t\tos.Stdout,\n\t\t\t\tos.Stdout,\n\t\t\t\tos.Stderr,\n\t\t\t)\n\t\tcase \"info\":\n\t\t\tlogInit(ioutil.Discard,\n\t\t\t\tos.Stdout,\n\t\t\t\tos.Stdout,\n\t\t\t\tos.Stderr,\n\t\t\t)\n\t\tcase \"warn\":\n\t\t\tlogInit(ioutil.Discard,\n\t\t\t\tioutil.Discard,\n\t\t\t\tos.Stdout,\n\t\t\t\tos.Stderr,\n\t\t\t)\n\t\tcase \"error\":\n\t\t\tlogInit(\n\t\t\t\tioutil.Discard,\n\t\t\t\tioutil.Discard,\n\t\t\t\tioutil.Discard,\n\t\t\t\tos.Stderr,\n\t\t\t)\n\t\tdefault:\n\t\t\tfmt.Fprintf(\n\t\t\t\tos.Stderr,\n\t\t\t\t\"Unknown loglevel: %s.  Assuming \\\"Info\\\".\\n\",\n\t\t\t\tcfg.General.Loglevel,\n\t\t\t)\n\t\t\tlogInit(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr)\n\t\t} \/\/ End of stdout\/stderr logging setup\n\t} \/\/ End of logging setup\n\n\t\/\/ Inform the user which (if any) config file was used.\n\tif cfg.Files.Config != \"\" {\n\t\tInfo.Printf(\"Using config file: %s\", cfg.Files.Config)\n\t} else {\n\t\tWarn.Println(\"No config file was found. Resorting to defaults\")\n\t}\n\n\tif flags.Client {\n\t\tmixprep()\n\t} else if flags.Stdin {\n\t\tdir := maildir.Dir(cfg.Files.Maildir)\n\t\tnewmsg, err := dir.NewDelivery()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tstdin, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tnewmsg.Write(stdin)\n\t\tnewmsg.Close()\n\t} else if flags.Remailer {\n\t\terr = loopServer()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else if flags.Dummy {\n\t\tinjectDummy()\n\t} else if flags.Refresh {\n\t\tfmt.Printf(\"Keyring refresh: from=%s, to=%s\\n\", cfg.Urls.Pubring, cfg.Files.Pubring)\n\t\thttpGet(cfg.Urls.Pubring, cfg.Files.Pubring)\n\t\tfmt.Printf(\"Stats refresh: from=%s, to=%s\\n\", cfg.Urls.Mlist2, cfg.Files.Mlist2)\n\t\thttpGet(cfg.Urls.Mlist2, cfg.Files.Mlist2)\n\t}\n\tif flags.Send {\n\t\t\/\/ Flush the outbound pool\n\t\tpoolOutboundSend()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\tstdlog \"log\"\n\t\"os\"\n\n\t\"github.com\/Masterminds\/log-go\"\n\t\"github.com\/crooks\/jlog\"\n\t\"github.com\/crooks\/yamn\/config\"\n\t\"github.com\/crooks\/yamn\/idlog\"\n\t\"github.com\/crooks\/yamn\/keymgr\"\n\t\"github.com\/luksen\/maildir\"\n)\n\nconst (\n\tversion        string = \"0.2.5\"\n\tdayLength      int    = 24 * 60 * 60 \/\/ Day in seconds\n\tmaxFragLength         = 17910\n\tmaxCopies             = 5\n\tbase64LineWrap        = 64\n\trfc5322date           = \"Mon, 2 Jan 2006 15:04:05 -0700\"\n\tshortdate             = \"2 Jan 2006\"\n)\n\nvar (\n\t\/\/ flags - Command line flags\n\tflag *config.Flags\n\t\/\/ cfg - Config parameters\n\tcfg *config.Config\n\t\/\/ Pubring - Public Keyring\n\tPubring *keymgr.Pubring\n\t\/\/ IDDb - Message ID log (replay protection)\n\tIDDb *idlog.IDLog\n\t\/\/ ChunkDb - Chunk database\n\tChunkDb *Chunk\n)\n\nfunc main() {\n\tvar err error\n\tflag, cfg = config.GetCfg()\n\tif flag.Version {\n\t\tfmt.Println(version)\n\t\tos.Exit(0)\n\t}\n\t\/\/ If the debug flag is set, print the config and exit\n\tif flag.Debug {\n\t\ty, err := cfg.Debug()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Debugging Error: %s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", y)\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Set up logging\n\tloglevel, err := log.Atoi(cfg.General.Loglevel)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%s: Unknown loglevel\", cfg.General.Loglevel)\n\t\tos.Exit(1)\n\t}\n\t\/\/ If we're logging to a file, open the file and redirect output to it\n\tif cfg.General.LogToFile && cfg.General.LogToJournal {\n\t\tfmt.Fprintln(os.Stderr, \"Cannot log to file and journal\")\n\t\tos.Exit(1)\n\t} else if cfg.General.LogToFile {\n\t\tlogfile, err := os.OpenFile(cfg.Files.Logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s: Error opening logfile: %v\", cfg.Files.Logfile, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tstdlog.SetOutput(logfile)\n\t\tlog.Current = log.StdLogger{Level: loglevel}\n\t} else if cfg.General.LogToJournal {\n\t\tlog.Current = jlog.NewJournal(loglevel)\n\t} else {\n\t\tlog.Current = log.StdLogger{Level: loglevel}\n\t}\n\n\t\/\/ Inform the user which (if any) config file was used.\n\tif cfg.Files.Config != \"\" {\n\t\tlog.Infof(\"Using config file: %s\", cfg.Files.Config)\n\t} else {\n\t\tlog.Warn(\"No config file was found. Resorting to defaults\")\n\t}\n\n\t\/\/ Setup complete, time to do some work\n\tif flag.Client {\n\t\tmixprep()\n\t} else if flag.Stdin {\n\t\tdir := maildir.Dir(cfg.Files.Maildir)\n\t\tnewmsg, err := dir.NewDelivery()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tstdin, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tnewmsg.Write(stdin)\n\t\tnewmsg.Close()\n\t} else if flag.Remailer {\n\t\terr = loopServer()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else if flag.Dummy {\n\t\tinjectDummy()\n\t} else if flag.Refresh {\n\t\tfmt.Printf(\"Keyring refresh: from=%s, to=%s\\n\", cfg.Urls.Pubring, cfg.Files.Pubring)\n\t\thttpGet(cfg.Urls.Pubring, cfg.Files.Pubring)\n\t\tfmt.Printf(\"Stats refresh: from=%s, to=%s\\n\", cfg.Urls.Mlist2, cfg.Files.Mlist2)\n\t\thttpGet(cfg.Urls.Mlist2, cfg.Files.Mlist2)\n\t}\n\tif flag.Send {\n\t\t\/\/ Flush the outbound pool\n\t\tpoolOutboundSend()\n\t}\n}\n<commit_msg>Bump version number<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\tstdlog \"log\"\n\t\"os\"\n\n\t\"github.com\/Masterminds\/log-go\"\n\t\"github.com\/crooks\/jlog\"\n\t\"github.com\/crooks\/yamn\/config\"\n\t\"github.com\/crooks\/yamn\/idlog\"\n\t\"github.com\/crooks\/yamn\/keymgr\"\n\t\"github.com\/luksen\/maildir\"\n)\n\nconst (\n\tversion        string = \"0.2.6\"\n\tdayLength      int    = 24 * 60 * 60 \/\/ Day in seconds\n\tmaxFragLength         = 17910\n\tmaxCopies             = 5\n\tbase64LineWrap        = 64\n\trfc5322date           = \"Mon, 2 Jan 2006 15:04:05 -0700\"\n\tshortdate             = \"2 Jan 2006\"\n)\n\nvar (\n\t\/\/ flags - Command line flags\n\tflag *config.Flags\n\t\/\/ cfg - Config parameters\n\tcfg *config.Config\n\t\/\/ Pubring - Public Keyring\n\tPubring *keymgr.Pubring\n\t\/\/ IDDb - Message ID log (replay protection)\n\tIDDb *idlog.IDLog\n\t\/\/ ChunkDb - Chunk database\n\tChunkDb *Chunk\n)\n\nfunc main() {\n\tvar err error\n\tflag, cfg = config.GetCfg()\n\tif flag.Version {\n\t\tfmt.Println(version)\n\t\tos.Exit(0)\n\t}\n\t\/\/ If the debug flag is set, print the config and exit\n\tif flag.Debug {\n\t\ty, err := cfg.Debug()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Debugging Error: %s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tfmt.Printf(\"%s\\n\", y)\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Set up logging\n\tloglevel, err := log.Atoi(cfg.General.Loglevel)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%s: Unknown loglevel\", cfg.General.Loglevel)\n\t\tos.Exit(1)\n\t}\n\t\/\/ If we're logging to a file, open the file and redirect output to it\n\tif cfg.General.LogToFile && cfg.General.LogToJournal {\n\t\tfmt.Fprintln(os.Stderr, \"Cannot log to file and journal\")\n\t\tos.Exit(1)\n\t} else if cfg.General.LogToFile {\n\t\tlogfile, err := os.OpenFile(cfg.Files.Logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s: Error opening logfile: %v\", cfg.Files.Logfile, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tstdlog.SetOutput(logfile)\n\t\tlog.Current = log.StdLogger{Level: loglevel}\n\t} else if cfg.General.LogToJournal {\n\t\tlog.Current = jlog.NewJournal(loglevel)\n\t} else {\n\t\tlog.Current = log.StdLogger{Level: loglevel}\n\t}\n\n\t\/\/ Inform the user which (if any) config file was used.\n\tif cfg.Files.Config != \"\" {\n\t\tlog.Infof(\"Using config file: %s\", cfg.Files.Config)\n\t} else {\n\t\tlog.Warn(\"No config file was found. Resorting to defaults\")\n\t}\n\n\t\/\/ Setup complete, time to do some work\n\tif flag.Client {\n\t\tmixprep()\n\t} else if flag.Stdin {\n\t\tdir := maildir.Dir(cfg.Files.Maildir)\n\t\tnewmsg, err := dir.NewDelivery()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tstdin, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tnewmsg.Write(stdin)\n\t\tnewmsg.Close()\n\t} else if flag.Remailer {\n\t\terr = loopServer()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else if flag.Dummy {\n\t\tinjectDummy()\n\t} else if flag.Refresh {\n\t\tfmt.Printf(\"Keyring refresh: from=%s, to=%s\\n\", cfg.Urls.Pubring, cfg.Files.Pubring)\n\t\thttpGet(cfg.Urls.Pubring, cfg.Files.Pubring)\n\t\tfmt.Printf(\"Stats refresh: from=%s, to=%s\\n\", cfg.Urls.Mlist2, cfg.Files.Mlist2)\n\t\thttpGet(cfg.Urls.Mlist2, cfg.Files.Mlist2)\n\t}\n\tif flag.Send {\n\t\t\/\/ Flush the outbound pool\n\t\tpoolOutboundSend()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/go-telegram-bot-api\/telegram-bot-api\"\n)\n\nvar ssl = flag.Int(\"ssl\", 0, \"0:no ssl, 1:SelfSign, 2:CA-cert\")\nvar webhook = flag.Bool(\"webhook\", false, \"webhook mode\")\nvar debug = flag.Bool(\"debug\", false, \"debug\")\nvar noisy = flag.Bool(\"noisy\", false, \"noisy\")\nvar token = flag.String(\"token\", \"\", \"token\")\nvar pubip = flag.String(\"pubip\", \"\", \"public ip, get with 'curl -s https:\/\/ipinfo.io\/ip'\")\nvar port = flag.Int(\"port\", 8443, \"webhook server port\")\nvar cert = flag.String(\"cert\", \"cert.pem\", \"cert for webhook https server\")\nvar key = flag.String(\"key\", \"key.pem\", \"priv key for webhook https server\")\nvar pathAd = flag.String(\"Ad\", func() string { p, _ := exec.LookPath(\"Ad\"); return p }(), \"path to Ad\")\nvar path7z = flag.String(\"7z\", func() string { p, _ := exec.LookPath(\"7z\"); return p }(), \"path to 7z\")\n\nfunc handleUpdate(bot *tgbotapi.BotAPI, update tgbotapi.Update) {\n\n\tif update.Message == nil {\n\t\treturn\n\t}\n\tNoisy := *noisy\n\tif update.Message.From.UserName == \"sehari24jam\" {\n\t\tNoisy = true\n\t}\n\n\tlog.Printf(\"[%s] %s\", update.Message.From.UserName, update.Message.Text)\n\n\tmsg := tgbotapi.NewMessage(update.Message.Chat.ID, \"Failed\")\n\tmsg.ReplyToMessageID = update.Message.MessageID\n\n\tswitch update.Message.Text {\n\tcase \"\/start\":\n\t\tmsg.Text = fmt.Sprintf(\"Welcome %s (%s %s).\\n\"+\n\t\t\t\"You may send me asciidoc (.adoc) file.\\n\"+\n\t\t\t\"Or you can pack whole *.adoc and its included images + sub-adoc into a single compressed file.\",\n\t\t\tupdate.Message.From.UserName, update.Message.From.FirstName, update.Message.From.LastName)\n\t\tbot.Send(msg)\n\t\treturn\n\tdefault:\n\t\tif update.Message.Document == nil {\n\t\t\tmsg.Text = \"Send me asciidoc file (.adoc). I don't understand: \" + update.Message.Text\n\t\t\tbot.Send(msg)\n\t\t\treturn\n\t\t}\n\t}\n\n\tf, err := bot.GetFile(tgbotapi.FileConfig{FileID: update.Message.Document.FileID})\n\t\/\/log.Printf(\"DocFile: %s\", update.Message.Document.FileName)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tif Noisy {\n\t\t\tmsg.Text = \"Failed to proceed uploaded file\"\n\t\t}\n\t\tbot.Send(msg)\n\t\treturn\n\t}\n\n\text := path.Ext(update.Message.Document.FileName)\n\ttmp := path.Join(os.TempDir(), \"ybot.\"+update.Message.Chat.UserName)\n\tpacked := false\n\tdpacked := false\n\n\tswitch strings.ToLower(ext) {\n\n\tcase \".zip\", \".rar\", \".7z\":\n\t\tpacked = true\n\t\tmsg.Text = \"Looks good, let me work on this compressed file\"\n\n\tcase \".tgz\", \".tbz2\", \".txz\":\n\t\tdpacked = true\n\t\tmsg.Text = \"Looks good, let me work on this compressed file.\"\n\n\tcase \".gz\", \".bz2\", \".xz\":\n\t\tftar := strings.TrimSuffix(update.Message.Document.FileName, ext)\n\t\texttar := path.Ext(ftar)\n\t\tif exttar == \".tar\" {\n\t\t\tdpacked = true\n\t\t\tmsg.Text = \"Looks good, let me work on this compressed file..\"\n\t\t\text = exttar + ext\n\t\t} else {\n\t\t\tmsg.Text = \"Document is not an adoc\"\n\t\t\tbot.Send(msg)\n\t\t\treturn\n\t\t}\n\n\tcase \".adoc\":\n\t\tmsg.Text = \"Looks good, let me work on this file\"\n\n\tdefault:\n\t\tmsg.Text = \"Document is not an adoc\"\n\t\tbot.Send(msg)\n\t\treturn\n\t}\n\n\tif packed || dpacked {\n\t\ttmp, err = ioutil.TempDir(\"\", \"ybot-\")\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t\tif Noisy {\n\t\t\t\tmsg.Text = \"Unable to create temp\"\n\t\t\t}\n\t\t\tbot.Send(msg)\n\t\t\treturn\n\t\t}\n\t}\n\tbot.Send(msg)\n\n\tworkfolder := path.Join(tmp, path.Dir(f.FilePath))\n\t\/\/lfile := path.Join(\"\/tmp\", f.FilePath)\n\tpdffile := path.Join(workfolder, strings.TrimSuffix(update.Message.Document.FileName, ext)+\".pdf\")\n\tworkfile := path.Join(workfolder, update.Message.Document.FileName)\n\n\t\/\/ get WorkFile from TG\n\tresponse, err := http.Get(f.Link(*token))\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tif packed || dpacked {\n\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t}\n\t\tif Noisy {\n\t\t\tmsg.Text = \"Failed to get uploaded file\"\n\t\t}\n\t\tbot.Send(msg)\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\n\t\/\/ create sub folder as necessary\n\tos.MkdirAll(workfolder, os.ModePerm)\n\n\t\/\/ save WorkFile\n\tfile, err := os.Create(workfile)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tif packed || dpacked {\n\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t}\n\t\tif Noisy {\n\t\t\tmsg.Text = \"Unable to create new file\"\n\t\t}\n\t\tbot.Send(msg)\n\t\treturn\n\t}\n\t\/\/ Use io.Copy to just dump the response body to the file. This supports huge files\n\t_, err = io.Copy(file, response.Body)\n\tfile.Close()\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tif packed || dpacked {\n\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t}\n\t\tif Noisy {\n\t\t\tmsg.Text = \"Unable to buffer uploaded file\"\n\t\t}\n\t\tbot.Send(msg)\n\t\treturn\n\t}\n\n\tgo func() {\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ extraction\n\t\tswitch {\n\t\tcase packed:\n\t\t\tcmd := exec.Command(\"7z\", \"x\", workfile)\n\t\t\tcmd.Dir = workfolder\n\t\t\tout, err := cmd.CombinedOutput()\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tif packed {\n\t\t\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t\t\t}\n\t\t\t\tif Noisy {\n\t\t\t\t\tmsg.Text = fmt.Sprintf(\"Failed %v\\n%v\", string(out), err)\n\t\t\t\t}\n\t\t\t\tbot.Send(msg)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tworkfile = \"*.adoc\"\n\t\tcase dpacked:\n\t\t\tvar out bytes.Buffer\n\t\t\txcmd1 := exec.Command(\"7z\", \"x\", workfile, \"-so\")\n\t\t\txcmd1.Dir = workfolder\n\t\t\txcmd2 := exec.Command(\"7z\", \"x\", \"-si\", \"-ttar\", \"-y\")\n\t\t\txcmd2.Dir = workfolder\n\t\t\txcmd2.Stdin, _ = xcmd1.StdoutPipe()\n\t\t\txcmd2.Stdout = &out\n\t\t\t_ = xcmd2.Start()\n\t\t\t_ = xcmd1.Run()\n\t\t\terr := xcmd2.Wait()\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tif packed {\n\t\t\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t\t\t}\n\t\t\t\tif Noisy {\n\t\t\t\t\tmsg.Text = fmt.Sprintf(\"Failed %v\\n%v\", string(out.Bytes()), err)\n\t\t\t\t}\n\t\t\t\tbot.Send(msg)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tworkfile = \"*.adoc\"\n\t\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ conversion\n\t\tcmd := exec.Command(\"Ad\", workfile)\n\t\tcmd.Dir = workfolder\n\t\tout, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\tif packed {\n\t\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t\t}\n\t\t\tif Noisy {\n\t\t\t\tmsg.Text = fmt.Sprintf(\"Failed %v\\n%v\", string(out), err)\n\t\t\t}\n\t\t\tbot.Send(msg)\n\t\t\treturn\n\t\t}\n\n\t\tif packed || dpacked {\n\t\t\tfiles, err := filepath.Glob(path.Join(workfolder, \"*.pdf\"))\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t\t\tif Noisy {\n\t\t\t\t\tmsg.Text = fmt.Sprintf(\"Failed %v..\", err)\n\t\t\t\t}\n\t\t\t\tbot.Send(msg)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, f := range files {\n\t\t\t\tbot.Send(tgbotapi.NewDocumentUpload(msg.ChatID, f))\n\t\t\t}\n\t\t\tif Noisy {\n\t\t\t\tmsg.Text = fmt.Sprintf(\"Success %v..\", string(out))\n\t\t\t} else {\n\t\t\t\tmsg.Text = \"Success..\"\n\t\t\t}\n\t\t\tbot.Send(msg)\n\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t} else {\n\t\t\tif Noisy {\n\t\t\t\tmsg.Text = fmt.Sprintf(\"Success %v\", string(out))\n\t\t\t} else {\n\t\t\t\tmsg.Text = \"Success\"\n\t\t\t}\n\t\t\tbot.Send(msg)\n\t\t\tbot.Send(tgbotapi.NewDocumentUpload(msg.ChatID, pdffile))\n\t\t}\n\n\t}()\n\n}\n\nfunc main() {\n\n\tflag.Parse()\n\n\tif *token == \"\" {\n\t\t*token = os.Getenv(\"YBOTTOKEN\")\n\t}\n\tbot, err := tgbotapi.NewBotAPI(*token)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tbot.Debug = *debug\n\n\tlog.Printf(\"Authorized on account %s\", bot.Self.UserName)\n\n\tif *webhook {\n\n\t\tvar updates tgbotapi.UpdatesChannel\n\t\tswitch *ssl {\n\t\tcase 1:\n\t\t\turl := fmt.Sprintf(\"https:\/\/%s:%d\/%s\", *pubip, *port, bot.Token)\n\t\t\tlog.Print(\"Webhook URL: \" + url)\n\t\t\t_, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert(url, *cert))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tupdates = bot.ListenForWebhook(\"\/\" + bot.Token)\n\t\t\tgo http.ListenAndServeTLS(fmt.Sprintf(\"0.0.0.0:%d\", *port), *cert, *key, nil)\n\n\t\tcase 2:\n\t\t\turl := fmt.Sprintf(\"https:\/\/%s:%d\/%s\", *pubip, *port, bot.Token)\n\t\t\tlog.Print(\"Webhook URL: \" + url)\n\t\t\t_, err = bot.SetWebhook(tgbotapi.NewWebhook(url))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tupdates = bot.ListenForWebhook(\"\/\" + bot.Token)\n\t\t\tgo http.ListenAndServeTLS(fmt.Sprintf(\"0.0.0.0:%d\", *port), *cert, *key, nil)\n\n\t\tdefault:\n\t\t\turl := fmt.Sprintf(\"http:\/\/%s:%d\/%s\", *pubip, *port, bot.Token)\n\t\t\tlog.Print(\"Webhook URL: \" + url)\n\t\t\t_, err = bot.SetWebhook(tgbotapi.NewWebhook(url))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tupdates = bot.ListenForWebhook(\"\/\" + bot.Token)\n\t\t\tgo http.ListenAndServe(fmt.Sprintf(\"0.0.0.0:%d\", *port), nil)\n\t\t}\n\n\t\tlog.Printf(\"Starting Collect Update from WebHook\")\n\t\tfor update := range updates {\n\t\t\thandleUpdate(bot, update)\n\t\t\t\/\/log.Printf(\"%+v\\n\", update)\n\t\t}\n\n\t} else {\n\n\t\tu := tgbotapi.NewUpdate(0)\n\t\tu.Timeout = 60\n\n\t\tupdates, err := bot.GetUpdatesChan(u)\n\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\n\t\tlog.Printf(\"Starting GetUpdate\")\n\t\tfor update := range updates {\n\t\t\thandleUpdate(bot, update)\n\t\t}\n\t}\n\n}\n<commit_msg>minor code move<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/go-telegram-bot-api\/telegram-bot-api\"\n)\n\nvar ssl = flag.Int(\"ssl\", 0, \"0:no ssl, 1:SelfSign, 2:CA-cert\")\nvar webhook = flag.Bool(\"webhook\", false, \"webhook mode\")\nvar debug = flag.Bool(\"debug\", false, \"debug\")\nvar noisy = flag.Bool(\"noisy\", false, \"noisy\")\nvar token = flag.String(\"token\", os.Getenv(\"YBOTTOKEN\"), \"token\")\nvar pubip = flag.String(\"pubip\", \"\", \"public ip, get with 'curl -s https:\/\/ipinfo.io\/ip'\")\nvar port = flag.Int(\"port\", 8443, \"webhook server port\")\nvar cert = flag.String(\"cert\", \"cert.pem\", \"cert for webhook https server\")\nvar key = flag.String(\"key\", \"key.pem\", \"priv key for webhook https server\")\nvar pathAd = flag.String(\"Ad\", func() string { p, _ := exec.LookPath(\"Ad\"); return p }(), \"path to Ad\")\nvar path7z = flag.String(\"7z\", func() string { p, _ := exec.LookPath(\"7z\"); return p }(), \"path to 7z\")\n\nfunc handleUpdate(bot *tgbotapi.BotAPI, update tgbotapi.Update) {\n\n\tif update.Message == nil {\n\t\treturn\n\t}\n\tNoisy := *noisy\n\tif update.Message.From.UserName == \"sehari24jam\" {\n\t\tNoisy = true\n\t}\n\n\tlog.Printf(\"[%s] %s\", update.Message.From.UserName, update.Message.Text)\n\n\tmsg := tgbotapi.NewMessage(update.Message.Chat.ID, \"Failed\")\n\tmsg.ReplyToMessageID = update.Message.MessageID\n\n\tswitch update.Message.Text {\n\tcase \"\/start\":\n\t\tmsg.Text = fmt.Sprintf(\"Welcome %s (%s %s).\\n\"+\n\t\t\t\"You may send me asciidoc (.adoc) file.\\n\"+\n\t\t\t\"Or you can pack whole *.adoc and its included images + sub-adoc into a single compressed file.\",\n\t\t\tupdate.Message.From.UserName, update.Message.From.FirstName, update.Message.From.LastName)\n\t\tbot.Send(msg)\n\t\treturn\n\tdefault:\n\t\tif update.Message.Document == nil {\n\t\t\tmsg.Text = \"Send me asciidoc file (.adoc). I don't understand: \" + update.Message.Text\n\t\t\tbot.Send(msg)\n\t\t\treturn\n\t\t}\n\t}\n\n\tf, err := bot.GetFile(tgbotapi.FileConfig{FileID: update.Message.Document.FileID})\n\t\/\/log.Printf(\"DocFile: %s\", update.Message.Document.FileName)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tif Noisy {\n\t\t\tmsg.Text = \"Failed to proceed uploaded file\"\n\t\t}\n\t\tbot.Send(msg)\n\t\treturn\n\t}\n\n\text := path.Ext(update.Message.Document.FileName)\n\ttmp := path.Join(os.TempDir(), \"ybot.\"+update.Message.Chat.UserName)\n\tpacked := false\n\tdpacked := false\n\n\tswitch strings.ToLower(ext) {\n\n\tcase \".zip\", \".rar\", \".7z\":\n\t\tpacked = true\n\t\tmsg.Text = \"Looks good, let me work on this compressed file\"\n\n\tcase \".tgz\", \".tbz2\", \".txz\":\n\t\tdpacked = true\n\t\tmsg.Text = \"Looks good, let me work on this compressed file.\"\n\n\tcase \".gz\", \".bz2\", \".xz\":\n\t\tftar := strings.TrimSuffix(update.Message.Document.FileName, ext)\n\t\texttar := path.Ext(ftar)\n\t\tif exttar == \".tar\" {\n\t\t\tdpacked = true\n\t\t\tmsg.Text = \"Looks good, let me work on this compressed file..\"\n\t\t\text = exttar + ext\n\t\t} else {\n\t\t\tmsg.Text = \"Document is not an adoc\"\n\t\t\tbot.Send(msg)\n\t\t\treturn\n\t\t}\n\n\tcase \".adoc\":\n\t\tmsg.Text = \"Looks good, let me work on this file\"\n\n\tdefault:\n\t\tmsg.Text = \"Document is not an adoc\"\n\t\tbot.Send(msg)\n\t\treturn\n\t}\n\n\tif packed || dpacked {\n\t\ttmp, err = ioutil.TempDir(\"\", \"ybot-\")\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t\tif Noisy {\n\t\t\t\tmsg.Text = \"Unable to create temp\"\n\t\t\t}\n\t\t\tbot.Send(msg)\n\t\t\treturn\n\t\t}\n\t}\n\tbot.Send(msg)\n\n\tworkfolder := path.Join(tmp, path.Dir(f.FilePath))\n\t\/\/lfile := path.Join(\"\/tmp\", f.FilePath)\n\tpdffile := path.Join(workfolder, strings.TrimSuffix(update.Message.Document.FileName, ext)+\".pdf\")\n\tworkfile := path.Join(workfolder, update.Message.Document.FileName)\n\n\t\/\/ get WorkFile from TG\n\tresponse, err := http.Get(f.Link(*token))\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tif packed || dpacked {\n\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t}\n\t\tif Noisy {\n\t\t\tmsg.Text = \"Failed to get uploaded file\"\n\t\t}\n\t\tbot.Send(msg)\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\n\t\/\/ create sub folder as necessary\n\tos.MkdirAll(workfolder, os.ModePerm)\n\n\t\/\/ save WorkFile\n\tfile, err := os.Create(workfile)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tif packed || dpacked {\n\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t}\n\t\tif Noisy {\n\t\t\tmsg.Text = \"Unable to create new file\"\n\t\t}\n\t\tbot.Send(msg)\n\t\treturn\n\t}\n\t\/\/ Use io.Copy to just dump the response body to the file. This supports huge files\n\t_, err = io.Copy(file, response.Body)\n\tfile.Close()\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tif packed || dpacked {\n\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t}\n\t\tif Noisy {\n\t\t\tmsg.Text = \"Unable to buffer uploaded file\"\n\t\t}\n\t\tbot.Send(msg)\n\t\treturn\n\t}\n\n\tgo func() {\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ extraction\n\t\tswitch {\n\t\tcase packed:\n\t\t\tcmd := exec.Command(\"7z\", \"x\", workfile)\n\t\t\tcmd.Dir = workfolder\n\t\t\tout, err := cmd.CombinedOutput()\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tif packed {\n\t\t\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t\t\t}\n\t\t\t\tif Noisy {\n\t\t\t\t\tmsg.Text = fmt.Sprintf(\"Failed %v\\n%v\", string(out), err)\n\t\t\t\t}\n\t\t\t\tbot.Send(msg)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tworkfile = \"*.adoc\"\n\t\tcase dpacked:\n\t\t\tvar out bytes.Buffer\n\t\t\txcmd1 := exec.Command(\"7z\", \"x\", \"-so\", workfile)\n\t\t\txcmd1.Dir = workfolder\n\t\t\txcmd2 := exec.Command(\"7z\", \"x\", \"-si\", \"-ttar\", \"-y\")\n\t\t\txcmd2.Dir = workfolder\n\t\t\txcmd2.Stdin, _ = xcmd1.StdoutPipe()\n\t\t\txcmd2.Stdout = &out\n\t\t\t_ = xcmd2.Start()\n\t\t\t_ = xcmd1.Run()\n\t\t\terr := xcmd2.Wait()\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tif packed {\n\t\t\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t\t\t}\n\t\t\t\tif Noisy {\n\t\t\t\t\tmsg.Text = fmt.Sprintf(\"Failed %v\\n%v\", string(out.Bytes()), err)\n\t\t\t\t}\n\t\t\t\tbot.Send(msg)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tworkfile = \"*.adoc\"\n\t\t}\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ conversion\n\t\tcmd := exec.Command(\"Ad\", workfile)\n\t\tcmd.Dir = workfolder\n\t\tout, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\tif packed {\n\t\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t\t}\n\t\t\tif Noisy {\n\t\t\t\tmsg.Text = fmt.Sprintf(\"Failed %v\\n%v\", string(out), err)\n\t\t\t}\n\t\t\tbot.Send(msg)\n\t\t\treturn\n\t\t}\n\n\t\tif packed || dpacked {\n\t\t\tfiles, err := filepath.Glob(path.Join(workfolder, \"*.pdf\"))\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t\t\tif Noisy {\n\t\t\t\t\tmsg.Text = fmt.Sprintf(\"Failed %v..\", err)\n\t\t\t\t}\n\t\t\t\tbot.Send(msg)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, f := range files {\n\t\t\t\tbot.Send(tgbotapi.NewDocumentUpload(msg.ChatID, f))\n\t\t\t}\n\t\t\tif Noisy {\n\t\t\t\tmsg.Text = fmt.Sprintf(\"Success %v..\", string(out))\n\t\t\t} else {\n\t\t\t\tmsg.Text = \"Success..\"\n\t\t\t}\n\t\t\tbot.Send(msg)\n\t\t\tlog.Print(os.RemoveAll(tmp))\n\t\t} else {\n\t\t\tif Noisy {\n\t\t\t\tmsg.Text = fmt.Sprintf(\"Success %v\", string(out))\n\t\t\t} else {\n\t\t\t\tmsg.Text = \"Success\"\n\t\t\t}\n\t\t\tbot.Send(msg)\n\t\t\tbot.Send(tgbotapi.NewDocumentUpload(msg.ChatID, pdffile))\n\t\t}\n\n\t}()\n\n}\n\nfunc main() {\n\n\tflag.Parse()\n\n\t\/\/if *token == \"\" {\n\t\/\/\t*token = os.Getenv(\"YBOTTOKEN\")\n\t\/\/}\n\tbot, err := tgbotapi.NewBotAPI(*token)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tbot.Debug = *debug\n\n\tlog.Printf(\"Authorized on account %s\", bot.Self.UserName)\n\n\tif *webhook {\n\n\t\tvar updates tgbotapi.UpdatesChannel\n\t\tswitch *ssl {\n\t\tcase 1:\n\t\t\turl := fmt.Sprintf(\"https:\/\/%s:%d\/%s\", *pubip, *port, bot.Token)\n\t\t\tlog.Print(\"Webhook URL: \" + url)\n\t\t\t_, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert(url, *cert))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tupdates = bot.ListenForWebhook(\"\/\" + bot.Token)\n\t\t\tgo http.ListenAndServeTLS(fmt.Sprintf(\"0.0.0.0:%d\", *port), *cert, *key, nil)\n\n\t\tcase 2:\n\t\t\turl := fmt.Sprintf(\"https:\/\/%s:%d\/%s\", *pubip, *port, bot.Token)\n\t\t\tlog.Print(\"Webhook URL: \" + url)\n\t\t\t_, err = bot.SetWebhook(tgbotapi.NewWebhook(url))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tupdates = bot.ListenForWebhook(\"\/\" + bot.Token)\n\t\t\tgo http.ListenAndServeTLS(fmt.Sprintf(\"0.0.0.0:%d\", *port), *cert, *key, nil)\n\n\t\tdefault:\n\t\t\turl := fmt.Sprintf(\"http:\/\/%s:%d\/%s\", *pubip, *port, bot.Token)\n\t\t\tlog.Print(\"Webhook URL: \" + url)\n\t\t\t_, err = bot.SetWebhook(tgbotapi.NewWebhook(url))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t\tupdates = bot.ListenForWebhook(\"\/\" + bot.Token)\n\t\t\tgo http.ListenAndServe(fmt.Sprintf(\"0.0.0.0:%d\", *port), nil)\n\t\t}\n\n\t\tlog.Printf(\"Starting Collect Update from WebHook\")\n\t\tfor update := range updates {\n\t\t\thandleUpdate(bot, update)\n\t\t\t\/\/log.Printf(\"%+v\\n\", update)\n\t\t}\n\n\t} else {\n\n\t\tu := tgbotapi.NewUpdate(0)\n\t\tu.Timeout = 60\n\n\t\tupdates, err := bot.GetUpdatesChan(u)\n\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\n\t\tlog.Printf(\"Starting GetUpdate\")\n\t\tfor update := range updates {\n\t\t\thandleUpdate(bot, update)\n\t\t}\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2021 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ The seeddb command populates a database with an initial set of modules.\npackage main\n\nimport (\n\t\"context\"\n\t\"database\/sql\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t_ \"github.com\/jackc\/pgx\/v4\/stdlib\" \/\/ for pgx driver\n\t\"golang.org\/x\/pkgsite\/internal\"\n\t\"golang.org\/x\/pkgsite\/internal\/config\"\n\t\"golang.org\/x\/pkgsite\/internal\/config\/dynconfig\"\n\t\"golang.org\/x\/pkgsite\/internal\/database\"\n\t\"golang.org\/x\/pkgsite\/internal\/derrors\"\n\t\"golang.org\/x\/pkgsite\/internal\/experiment\"\n\t\"golang.org\/x\/pkgsite\/internal\/log\"\n\t\"golang.org\/x\/pkgsite\/internal\/postgres\"\n\t\"golang.org\/x\/pkgsite\/internal\/proxy\"\n\t\"golang.org\/x\/pkgsite\/internal\/source\"\n\t\"golang.org\/x\/pkgsite\/internal\/stdlib\"\n\t\"golang.org\/x\/pkgsite\/internal\/worker\"\n\t\"golang.org\/x\/sync\/errgroup\"\n)\n\nvar (\n\tseedfile = flag.String(\"seed\", \"devtools\/cmd\/seeddb\/seed.txt\", \"filename containing modules for seeding the database\")\n\trefetch  = flag.Bool(\"refetch\", false, \"refetch modules in the seedfile even if they already exist\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tctx := context.Background()\n\tcfg, err := config.Init(ctx)\n\tif err != nil {\n\t\tlog.Fatal(ctx, err)\n\t}\n\n\texps, err := fetchExperiments(ctx, cfg)\n\tif err != nil {\n\t\tlog.Fatal(ctx, err)\n\t}\n\tctx = experiment.NewContext(ctx, exps...)\n\n\tdb, err := database.Open(\"pgx\", cfg.DBConnInfo(), \"seeddb\")\n\tif err != nil {\n\t\tlog.Fatalf(ctx, \"database.Open for host %s failed with %v\", cfg.DBHost, err)\n\t}\n\tdefer db.Close()\n\n\tif err := run(ctx, db, cfg.ProxyURL); err != nil {\n\t\tlog.Fatal(ctx, err)\n\t}\n}\n\nfunc run(ctx context.Context, db *database.DB, proxyURL string) error {\n\tstart := time.Now()\n\n\tproxyClient, err := proxy.New(proxyURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsourceClient := source.NewClient(config.SourceTimeout)\n\tseedModules, err := readSeedFile(ctx, *seedfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Expand versions and group by module path.\n\tversionsByPath := map[string][]string{}\n\tfor _, m := range seedModules {\n\t\tvers, err := versions(ctx, proxyClient, m)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tversionsByPath[m.Path] = append(versionsByPath[m.Path], vers...)\n\t}\n\n\tr := results{}\n\tg := new(errgroup.Group)\n\tf := &worker.Fetcher{\n\t\tProxyClient:  proxyClient,\n\t\tSourceClient: sourceClient,\n\t\tDB:           postgres.New(db),\n\t}\n\tfor path, vers := range versionsByPath {\n\t\tpath := path\n\t\tvers := vers\n\t\t\/\/ Process versions of the same module sequentially, to avoid DB contention.\n\t\tg.Go(func() error {\n\t\t\tfor _, v := range vers {\n\t\t\t\tif err := fetch(ctx, db, f, path, v, &r); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err := g.Wait(); err != nil {\n\t\treturn err\n\t}\n\tlog.Infof(ctx, \"Successfully fetched all modules: %v\", time.Since(start))\n\n\t\/\/ Print the time it took to fetch these modules.\n\tvar keys []string\n\tfor k := range r.paths {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\tfor _, k := range keys {\n\t\tlog.Infof(ctx, \"%s | %v\", k, r.paths[k])\n\t}\n\treturn nil\n}\n\nfunc versions(ctx context.Context, proxyClient *proxy.Client, mv internal.Modver) ([]string, error) {\n\tif mv.Version != \"all\" {\n\t\treturn []string{mv.Version}, nil\n\t}\n\tif mv.Path == stdlib.ModulePath {\n\t\tstdVersions, err := stdlib.Versions()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ As an optimization, only fetch release versions for the standard\n\t\t\/\/ library.\n\t\tvar vers []string\n\t\tfor _, v := range stdVersions {\n\t\t\tif strings.HasSuffix(v, \".0\") {\n\t\t\t\tvers = append(vers, v)\n\t\t\t}\n\t\t}\n\t\treturn vers, nil\n\t}\n\treturn proxyClient.Versions(ctx, mv.Path)\n}\n\nfunc fetch(ctx context.Context, db *database.DB, f *worker.Fetcher, m, v string, r *results) error {\n\t\/\/ Record the duration of this fetch request.\n\tstart := time.Now()\n\n\tvar exists bool\n\tdefer func() {\n\t\tr.add(m, v, start, exists)\n\t}()\n\terr := db.QueryRow(ctx, `\n\t\tSELECT 1 FROM modules WHERE module_path = $1 AND version = $2;\n\t`, m, v).Scan(&exists)\n\tif err != nil && !errors.Is(err, sql.ErrNoRows) {\n\t\treturn err\n\t}\n\tif errors.Is(err, sql.ErrNoRows) || *refetch {\n\t\treturn fetchFunc(ctx, f, m, v)\n\t}\n\treturn nil\n}\n\nfunc fetchFunc(ctx context.Context, f *worker.Fetcher, m, v string) (err error) {\n\tdefer derrors.Wrap(&err, \"fetchFunc(ctx, f, %q, %q)\", m, v)\n\n\tlog.Infof(ctx, \"Fetch requested: %q %q\", m, v)\n\tfetchCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)\n\tdefer cancel()\n\n\tcode, _, err := f.FetchAndUpdateState(fetchCtx, m, v, \"\")\n\tif err != nil {\n\t\tif code == http.StatusNotFound {\n\t\t\t\/\/ We expect\n\t\t\t\/\/ github.com\/jackc\/pgx\/pgxpool@v3.6.2+incompatible\n\t\t\t\/\/ to fail from seed.txt, so that it will redirect to\n\t\t\t\/\/ github.com\/jackc\/pgx\/v4\/pgxpool in tests.\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\ntype results struct {\n\tmu    sync.Mutex\n\tpaths map[string]time.Duration\n}\n\nfunc (r *results) add(modPath, version string, start time.Time, exists bool) {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tif r.paths == nil {\n\t\tr.paths = map[string]time.Duration{}\n\t}\n\tkey := fmt.Sprintf(\"%s@%s\", modPath, version)\n\tif exists {\n\t\tkey = fmt.Sprintf(\"%s (exists)\", key)\n\t}\n\tr.paths[key] = time.Since(start)\n}\n\n\/\/ readSeedFile reads a file of module versions that we want to fetch for\n\/\/ seeding the database. Each line of the file should be of the form:\n\/\/     module@version\nfunc readSeedFile(ctx context.Context, seedfile string) (_ []internal.Modver, err error) {\n\tdefer derrors.Wrap(&err, \"readSeedFile %q\", seedfile)\n\tlines, err := internal.ReadFileLines(seedfile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Infof(ctx, \"read %d module versions from %s\", len(lines), seedfile)\n\n\tvar modules []internal.Modver\n\tfor _, l := range lines {\n\t\tmv, err := internal.ParseModver(l)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmodules = append(modules, mv)\n\t}\n\treturn modules, nil\n}\n\nfunc fetchExperiments(ctx context.Context, cfg *config.Config) ([]string, error) {\n\tif cfg.DynamicConfigLocation == \"\" {\n\t\treturn nil, nil\n\t}\n\tdc, err := dynconfig.Read(ctx, cfg.DynamicConfigLocation)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar exps []string\n\tfor _, e := range dc.Experiments {\n\t\tif e.Rollout > 0 {\n\t\t\texps = append(exps, e.Name)\n\t\t}\n\t}\n\treturn exps, nil\n}\n<commit_msg>devtools\/cmd\/seeddb: add -keep_going<commit_after>\/\/ Copyright 2021 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ The seeddb command populates a database with an initial set of modules.\npackage main\n\nimport (\n\t\"context\"\n\t\"database\/sql\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t_ \"github.com\/jackc\/pgx\/v4\/stdlib\" \/\/ for pgx driver\n\t\"golang.org\/x\/pkgsite\/internal\"\n\t\"golang.org\/x\/pkgsite\/internal\/config\"\n\t\"golang.org\/x\/pkgsite\/internal\/config\/dynconfig\"\n\t\"golang.org\/x\/pkgsite\/internal\/database\"\n\t\"golang.org\/x\/pkgsite\/internal\/derrors\"\n\t\"golang.org\/x\/pkgsite\/internal\/experiment\"\n\t\"golang.org\/x\/pkgsite\/internal\/log\"\n\t\"golang.org\/x\/pkgsite\/internal\/postgres\"\n\t\"golang.org\/x\/pkgsite\/internal\/proxy\"\n\t\"golang.org\/x\/pkgsite\/internal\/source\"\n\t\"golang.org\/x\/pkgsite\/internal\/stdlib\"\n\t\"golang.org\/x\/pkgsite\/internal\/worker\"\n\t\"golang.org\/x\/sync\/errgroup\"\n)\n\nvar (\n\tseedfile  = flag.String(\"seed\", \"devtools\/cmd\/seeddb\/seed.txt\", \"filename containing modules for seeding the database\")\n\trefetch   = flag.Bool(\"refetch\", false, \"refetch modules in the seedfile even if they already exist\")\n\tkeepGoing = flag.Bool(\"keep_going\", false, \"continue on errors\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tctx := context.Background()\n\tcfg, err := config.Init(ctx)\n\tif err != nil {\n\t\tlog.Fatal(ctx, err)\n\t}\n\n\texps, err := fetchExperiments(ctx, cfg)\n\tif err != nil {\n\t\tlog.Fatal(ctx, err)\n\t}\n\tctx = experiment.NewContext(ctx, exps...)\n\n\tdb, err := database.Open(\"pgx\", cfg.DBConnInfo(), \"seeddb\")\n\tif err != nil {\n\t\tlog.Fatalf(ctx, \"database.Open for host %s failed with %v\", cfg.DBHost, err)\n\t}\n\tdefer db.Close()\n\n\tif err := run(ctx, db, cfg.ProxyURL); err != nil {\n\t\tlog.Fatal(ctx, err)\n\t}\n}\n\nfunc run(ctx context.Context, db *database.DB, proxyURL string) error {\n\tstart := time.Now()\n\n\tproxyClient, err := proxy.New(proxyURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsourceClient := source.NewClient(config.SourceTimeout)\n\tseedModules, err := readSeedFile(ctx, *seedfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Expand versions and group by module path.\n\tversionsByPath := map[string][]string{}\n\tfor _, m := range seedModules {\n\t\tvers, err := versions(ctx, proxyClient, m)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tversionsByPath[m.Path] = append(versionsByPath[m.Path], vers...)\n\t}\n\n\tr := results{}\n\tg := new(errgroup.Group)\n\tf := &worker.Fetcher{\n\t\tProxyClient:  proxyClient,\n\t\tSourceClient: sourceClient,\n\t\tDB:           postgres.New(db),\n\t}\n\tvar (\n\t\tmu     sync.Mutex\n\t\terrors database.MultiErr\n\t)\n\tfor path, vers := range versionsByPath {\n\t\tpath := path\n\t\tvers := vers\n\t\t\/\/ Process versions of the same module sequentially, to avoid DB contention.\n\t\tg.Go(func() error {\n\t\t\tfor _, v := range vers {\n\t\t\t\tif err := fetch(ctx, db, f, path, v, &r); err != nil {\n\t\t\t\t\tif *keepGoing {\n\t\t\t\t\t\tmu.Lock()\n\t\t\t\t\t\terrors = append(errors, err)\n\t\t\t\t\t\tmu.Unlock()\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t}\n\tif err := g.Wait(); err != nil {\n\t\treturn err\n\t}\n\tif len(errors) > 0 {\n\t\treturn errors\n\t}\n\tlog.Infof(ctx, \"Successfully fetched all modules: %v\", time.Since(start))\n\n\t\/\/ Print the time it took to fetch these modules.\n\tvar keys []string\n\tfor k := range r.paths {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\tfor _, k := range keys {\n\t\tlog.Infof(ctx, \"%s | %v\", k, r.paths[k])\n\t}\n\treturn nil\n}\n\nfunc versions(ctx context.Context, proxyClient *proxy.Client, mv internal.Modver) ([]string, error) {\n\tif mv.Version != \"all\" {\n\t\treturn []string{mv.Version}, nil\n\t}\n\tif mv.Path == stdlib.ModulePath {\n\t\tstdVersions, err := stdlib.Versions()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ As an optimization, only fetch release versions for the standard\n\t\t\/\/ library.\n\t\tvar vers []string\n\t\tfor _, v := range stdVersions {\n\t\t\tif strings.HasSuffix(v, \".0\") {\n\t\t\t\tvers = append(vers, v)\n\t\t\t}\n\t\t}\n\t\treturn vers, nil\n\t}\n\treturn proxyClient.Versions(ctx, mv.Path)\n}\n\nfunc fetch(ctx context.Context, db *database.DB, f *worker.Fetcher, m, v string, r *results) error {\n\t\/\/ Record the duration of this fetch request.\n\tstart := time.Now()\n\n\tvar exists bool\n\tdefer func() {\n\t\tr.add(m, v, start, exists)\n\t}()\n\terr := db.QueryRow(ctx, `\n\t\tSELECT 1 FROM modules WHERE module_path = $1 AND version = $2;\n\t`, m, v).Scan(&exists)\n\tif err != nil && !errors.Is(err, sql.ErrNoRows) {\n\t\treturn err\n\t}\n\tif errors.Is(err, sql.ErrNoRows) || *refetch {\n\t\treturn fetchFunc(ctx, f, m, v)\n\t}\n\treturn nil\n}\n\nfunc fetchFunc(ctx context.Context, f *worker.Fetcher, m, v string) (err error) {\n\tdefer derrors.Wrap(&err, \"fetchFunc(ctx, f, %q, %q)\", m, v)\n\n\tlog.Infof(ctx, \"Fetch requested: %q %q\", m, v)\n\tfetchCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)\n\tdefer cancel()\n\n\tcode, _, err := f.FetchAndUpdateState(fetchCtx, m, v, \"\")\n\tif err != nil {\n\t\tif code == http.StatusNotFound {\n\t\t\t\/\/ We expect\n\t\t\t\/\/ github.com\/jackc\/pgx\/pgxpool@v3.6.2+incompatible\n\t\t\t\/\/ to fail from seed.txt, so that it will redirect to\n\t\t\t\/\/ github.com\/jackc\/pgx\/v4\/pgxpool in tests.\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\ntype results struct {\n\tmu    sync.Mutex\n\tpaths map[string]time.Duration\n}\n\nfunc (r *results) add(modPath, version string, start time.Time, exists bool) {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tif r.paths == nil {\n\t\tr.paths = map[string]time.Duration{}\n\t}\n\tkey := fmt.Sprintf(\"%s@%s\", modPath, version)\n\tif exists {\n\t\tkey = fmt.Sprintf(\"%s (exists)\", key)\n\t}\n\tr.paths[key] = time.Since(start)\n}\n\n\/\/ readSeedFile reads a file of module versions that we want to fetch for\n\/\/ seeding the database. Each line of the file should be of the form:\n\/\/     module@version\nfunc readSeedFile(ctx context.Context, seedfile string) (_ []internal.Modver, err error) {\n\tdefer derrors.Wrap(&err, \"readSeedFile %q\", seedfile)\n\tlines, err := internal.ReadFileLines(seedfile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Infof(ctx, \"read %d module versions from %s\", len(lines), seedfile)\n\n\tvar modules []internal.Modver\n\tfor _, l := range lines {\n\t\tmv, err := internal.ParseModver(l)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmodules = append(modules, mv)\n\t}\n\treturn modules, nil\n}\n\nfunc fetchExperiments(ctx context.Context, cfg *config.Config) ([]string, error) {\n\tif cfg.DynamicConfigLocation == \"\" {\n\t\treturn nil, nil\n\t}\n\tdc, err := dynconfig.Read(ctx, cfg.DynamicConfigLocation)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar exps []string\n\tfor _, e := range dc.Experiments {\n\t\tif e.Rollout > 0 {\n\t\t\texps = append(exps, e.Name)\n\t\t}\n\t}\n\treturn exps, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ web100lib provides Go bindings to some functions in the web100 library.\npackage web100lib\n\n\/\/ Cgo directives must immediately preceed 'import \"C\"' below.\n\/\/ For more information see:\n\/\/  - https:\/\/blog.golang.org\/c-go-cgo\n\/\/  - https:\/\/golang.org\/cmd\/cgo\n\n\/*\n#include <stdio.h>\n#include <stdlib.h>\n#include <web100.h>\n#include <web100-int.h>\n\n#include <arpa\/inet.h>\n*\/\nimport \"C\"\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"unsafe\"\n\n\t\"cloud.google.com\/go\/bigquery\"\n)\n\n\/\/ Discoveries:\n\/\/  - Not all C macros exist in the \"C\" namespace.\n\/\/  - 'NULL' is usually equivalent to 'nil'\n\n\/\/ Web100 maintains state associated with a web100 log file.\ntype Web100 struct {\n\t\/\/ legacyNames maps legacy web100 variable names to their canonical names.\n\tlegacyNames map[string]string\n\n\t\/\/ Do not export unsafe pointers.\n\tlog  unsafe.Pointer\n\tsnap unsafe.Pointer\n}\n\n\/\/ Open prepares a web100 log file for reading. The caller must call Close on\n\/\/ the returned Web100 instance to release resources.\nfunc Open(filename string, legacyNames map[string]string) (*Web100, error) {\n\tc_filename := C.CString(filename)\n\tdefer C.free(unsafe.Pointer(c_filename))\n\n\tlog := C.web100_log_open_read(c_filename)\n\tif log == nil {\n\t\treturn nil, fmt.Errorf(C.GoString(C.web100_strerror(C.web100_errno)))\n\t}\n\n\t\/\/ Pre-allocate a snapshot record.\n\tsnap := C.web100_snapshot_alloc_from_log(log)\n\n\tw := &Web100{\n\t\tlegacyNames: legacyNames,\n\t\tlog:         unsafe.Pointer(log),\n\t\tsnap:        unsafe.Pointer(snap),\n\t}\n\treturn w, nil\n}\n\n\/\/ Next iterates through the web100 log file reading the next snapshot record\n\/\/ until EOF or an error occurs.\nfunc (w *Web100) Next() error {\n\tlog := (*C.web100_log)(w.log)\n\tsnap := (*C.web100_snapshot)(w.snap)\n\n\t\/\/ Read the next web100_snaplog data from underlying file.\n\terr := C.web100_snap_from_log(snap, log)\n\tif err == C.EOF {\n\t\treturn io.EOF\n\t}\n\tif err != C.WEB100_ERR_SUCCESS {\n\t\treturn fmt.Errorf(C.GoString(C.web100_strerror(err)))\n\t}\n\treturn nil\n}\n\nfunc (w *Web100) Values() (map[string]bigquery.Value, error) {\n\tv, err := w.logValues()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tv, err = w.snapValues(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn v, nil\n}\n\n\/\/ logValues returns a map of values from the web100 log. IPv6 address\n\/\/ connection information is not available and must be set based on a snapshot.\nfunc (w *Web100) logValues() (map[string]bigquery.Value, error) {\n\tlog := (*C.web100_log)(w.log)\n\n\tagent := C.web100_get_log_agent(log)\n\n\tresults := make(map[string]bigquery.Value)\n\tresults[\"web100_log_entry.version\"] = C.GoString(C.web100_get_agent_version(agent))\n\n\ttime := C.web100_get_log_time(log)\n\tresults[\"web100_log_entry.log_time\"] = int64(time)\n\n\tconn := C.web100_get_log_connection(log)\n\t\/\/ NOTE: web100_connection_spec_v6 is not filled in by the web100 library.\n\t\/\/ NOTE: addrtype is always WEB100_ADDRTYPE_UNKNOWN.\n\t\/\/ NOTE: legacy values for local_af are: IPv4 = 0, IPv6 = 1.\n\tresults[\"web100_log_entry.connection_spec.local_af\"] = int64(0)\n\n\tvar spec C.struct_web100_connection_spec\n\tC.web100_get_connection_spec(conn, &spec)\n\n\taddr := C.struct_in_addr{C.in_addr_t(spec.src_addr)}\n\tresults[\"web100_log_entry.connection_spec.local_ip\"] = C.GoString(C.inet_ntoa(addr))\n\tresults[\"web100_log_entry.connection_spec.local_port\"] = int64(spec.src_port)\n\n\taddr = C.struct_in_addr{C.in_addr_t(spec.dst_addr)}\n\tresults[\"web100_log_entry.connection_spec.remote_ip\"] = C.GoString(C.inet_ntoa(addr))\n\tresults[\"web100_log_entry.connection_spec.remote_port\"] = int64(spec.dst_port)\n\n\treturn results, nil\n}\n\n\/\/ snapValues converts all variables in the latest snap record into a results map.\nfunc (w *Web100) snapValues(logValues map[string]bigquery.Value) (map[string]bigquery.Value, error) {\n\tlog := (*C.web100_log)(w.log)\n\tsnap := (*C.web100_snapshot)(w.snap)\n\n\tvar_text := C.calloc(2*C.WEB100_VALUE_LEN_MAX, 1) \/\/ Use a better size.\n\tdefer C.free(var_text)\n\n\tvar_data := C.calloc(C.WEB100_VALUE_LEN_MAX, 1)\n\tdefer C.free(var_data)\n\n\t\/\/ Parses variables from most recent web100_snapshot data.\n\tgroup := C.web100_get_log_group(log)\n\tfor v := C.web100_var_head(group); v != nil; v = C.web100_var_next(v) {\n\n\t\tname := C.web100_get_var_name(v)\n\t\tvar_type := C.web100_get_var_type(v)\n\n\t\t\/\/ Read the raw variable data from the snapshot data.\n\t\terrno := C.web100_snap_read(v, snap, var_data)\n\t\tif errno != C.WEB100_ERR_SUCCESS {\n\t\t\treturn nil, fmt.Errorf(C.GoString(C.web100_strerror(errno)))\n\t\t}\n\n\t\t\/\/ Convert raw var_data into a string based on var_type.\n\t\t\/\/ TODO(final): ultimately, we should reimplement web100_value_to_textn to operate on Go types.\n\t\tC.web100_value_to_textn((*C.char)(var_text), C.WEB100_VALUE_LEN_MAX, (C.WEB100_TYPE)(var_type), var_data)\n\n\t\t\/\/ Use the canonical variable name.\n\t\tvar canonicalName string\n\t\tif _, ok := w.legacyNames[canonicalName]; ok {\n\t\t\tcanonicalName = w.legacyNames[canonicalName]\n\t\t} else {\n\t\t\tcanonicalName = C.GoString(name)\n\t\t}\n\n\t\t\/\/ Attempt to convert the current variable to an int64.\n\t\tvalue, err := strconv.ParseInt(C.GoString((*C.char)(var_text)), 10, 64)\n\t\tif err != nil {\n\t\t\t\/\/ Leave variable as a string.\n\t\t\tfmt.Println(\"var_type:\", int(var_type), \"name:\", canonicalName)\n\t\t\tlogValues[fmt.Sprintf(\"web100_log_entry.snap.%s\", canonicalName)] = C.GoString((*C.char)(var_text))\n\t\t} else {\n\t\t\t\/\/\n\t\t\tlogValues[fmt.Sprintf(\"web100_log_entry.snap.%s\", canonicalName)] = value\n\t\t}\n\t}\n\treturn logValues, nil\n}\n\n\/\/ Close releases resources created by Open.\nfunc (w *Web100) Close() error {\n\tsnap := (*C.web100_snapshot)(w.snap)\n\tC.web100_snapshot_free(snap)\n\n\tlog := (*C.web100_log)(w.log)\n\terr := C.web100_log_close_read(log)\n\tif err != C.WEB100_ERR_SUCCESS {\n\t\treturn fmt.Errorf(C.GoString(C.web100_strerror(err)))\n\t}\n\n\t\/\/ Clear pointer after free.\n\tw.log = nil\n\tw.snap = nil\n\treturn nil\n}\n\nfunc LookupError(errnum int) string {\n\treturn C.GoString(C.web100_strerror(C.int(errnum)))\n}\n\nfunc PrettyPrint(results map[string]string) {\n\tb, err := json.MarshalIndent(results, \"\", \"  \")\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\tfmt.Print(string(b))\n}\n<commit_msg>Remove log line.<commit_after>\/\/ web100lib provides Go bindings to some functions in the web100 library.\npackage web100lib\n\n\/\/ Cgo directives must immediately preceed 'import \"C\"' below.\n\/\/ For more information see:\n\/\/  - https:\/\/blog.golang.org\/c-go-cgo\n\/\/  - https:\/\/golang.org\/cmd\/cgo\n\n\/*\n#include <stdio.h>\n#include <stdlib.h>\n#include <web100.h>\n#include <web100-int.h>\n\n#include <arpa\/inet.h>\n*\/\nimport \"C\"\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"unsafe\"\n\n\t\"cloud.google.com\/go\/bigquery\"\n)\n\n\/\/ Discoveries:\n\/\/  - Not all C macros exist in the \"C\" namespace.\n\/\/  - 'NULL' is usually equivalent to 'nil'\n\n\/\/ Web100 maintains state associated with a web100 log file.\ntype Web100 struct {\n\t\/\/ legacyNames maps legacy web100 variable names to their canonical names.\n\tlegacyNames map[string]string\n\n\t\/\/ Do not export unsafe pointers.\n\tlog  unsafe.Pointer\n\tsnap unsafe.Pointer\n}\n\n\/\/ Open prepares a web100 log file for reading. The caller must call Close on\n\/\/ the returned Web100 instance to release resources.\nfunc Open(filename string, legacyNames map[string]string) (*Web100, error) {\n\tc_filename := C.CString(filename)\n\tdefer C.free(unsafe.Pointer(c_filename))\n\n\tlog := C.web100_log_open_read(c_filename)\n\tif log == nil {\n\t\treturn nil, fmt.Errorf(C.GoString(C.web100_strerror(C.web100_errno)))\n\t}\n\n\t\/\/ Pre-allocate a snapshot record.\n\tsnap := C.web100_snapshot_alloc_from_log(log)\n\n\tw := &Web100{\n\t\tlegacyNames: legacyNames,\n\t\tlog:         unsafe.Pointer(log),\n\t\tsnap:        unsafe.Pointer(snap),\n\t}\n\treturn w, nil\n}\n\n\/\/ Next iterates through the web100 log file reading the next snapshot record\n\/\/ until EOF or an error occurs.\nfunc (w *Web100) Next() error {\n\tlog := (*C.web100_log)(w.log)\n\tsnap := (*C.web100_snapshot)(w.snap)\n\n\t\/\/ Read the next web100_snaplog data from underlying file.\n\terr := C.web100_snap_from_log(snap, log)\n\tif err == C.EOF {\n\t\treturn io.EOF\n\t}\n\tif err != C.WEB100_ERR_SUCCESS {\n\t\treturn fmt.Errorf(C.GoString(C.web100_strerror(err)))\n\t}\n\treturn nil\n}\n\nfunc (w *Web100) Values() (map[string]bigquery.Value, error) {\n\tv, err := w.logValues()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tv, err = w.snapValues(v)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn v, nil\n}\n\n\/\/ logValues returns a map of values from the web100 log. IPv6 address\n\/\/ connection information is not available and must be set based on a snapshot.\nfunc (w *Web100) logValues() (map[string]bigquery.Value, error) {\n\tlog := (*C.web100_log)(w.log)\n\n\tagent := C.web100_get_log_agent(log)\n\n\tresults := make(map[string]bigquery.Value)\n\tresults[\"web100_log_entry.version\"] = C.GoString(C.web100_get_agent_version(agent))\n\n\ttime := C.web100_get_log_time(log)\n\tresults[\"web100_log_entry.log_time\"] = int64(time)\n\n\tconn := C.web100_get_log_connection(log)\n\t\/\/ NOTE: web100_connection_spec_v6 is not filled in by the web100 library.\n\t\/\/ NOTE: addrtype is always WEB100_ADDRTYPE_UNKNOWN.\n\t\/\/ NOTE: legacy values for local_af are: IPv4 = 0, IPv6 = 1.\n\tresults[\"web100_log_entry.connection_spec.local_af\"] = int64(0)\n\n\tvar spec C.struct_web100_connection_spec\n\tC.web100_get_connection_spec(conn, &spec)\n\n\taddr := C.struct_in_addr{C.in_addr_t(spec.src_addr)}\n\tresults[\"web100_log_entry.connection_spec.local_ip\"] = C.GoString(C.inet_ntoa(addr))\n\tresults[\"web100_log_entry.connection_spec.local_port\"] = int64(spec.src_port)\n\n\taddr = C.struct_in_addr{C.in_addr_t(spec.dst_addr)}\n\tresults[\"web100_log_entry.connection_spec.remote_ip\"] = C.GoString(C.inet_ntoa(addr))\n\tresults[\"web100_log_entry.connection_spec.remote_port\"] = int64(spec.dst_port)\n\n\treturn results, nil\n}\n\n\/\/ snapValues converts all variables in the latest snap record into a results map.\nfunc (w *Web100) snapValues(logValues map[string]bigquery.Value) (map[string]bigquery.Value, error) {\n\tlog := (*C.web100_log)(w.log)\n\tsnap := (*C.web100_snapshot)(w.snap)\n\n\tvar_text := C.calloc(2*C.WEB100_VALUE_LEN_MAX, 1) \/\/ Use a better size.\n\tdefer C.free(var_text)\n\n\tvar_data := C.calloc(C.WEB100_VALUE_LEN_MAX, 1)\n\tdefer C.free(var_data)\n\n\t\/\/ Parses variables from most recent web100_snapshot data.\n\tgroup := C.web100_get_log_group(log)\n\tfor v := C.web100_var_head(group); v != nil; v = C.web100_var_next(v) {\n\n\t\tname := C.web100_get_var_name(v)\n\t\tvar_type := C.web100_get_var_type(v)\n\n\t\t\/\/ Read the raw variable data from the snapshot data.\n\t\terrno := C.web100_snap_read(v, snap, var_data)\n\t\tif errno != C.WEB100_ERR_SUCCESS {\n\t\t\treturn nil, fmt.Errorf(C.GoString(C.web100_strerror(errno)))\n\t\t}\n\n\t\t\/\/ Convert raw var_data into a string based on var_type.\n\t\t\/\/ TODO(final): ultimately, we should reimplement web100_value_to_textn to operate on Go types.\n\t\tC.web100_value_to_textn((*C.char)(var_text), C.WEB100_VALUE_LEN_MAX, (C.WEB100_TYPE)(var_type), var_data)\n\n\t\t\/\/ Use the canonical variable name.\n\t\tvar canonicalName string\n\t\tif _, ok := w.legacyNames[canonicalName]; ok {\n\t\t\tcanonicalName = w.legacyNames[canonicalName]\n\t\t} else {\n\t\t\tcanonicalName = C.GoString(name)\n\t\t}\n\n\t\t\/\/ Attempt to convert the current variable to an int64.\n\t\tvalue, err := strconv.ParseInt(C.GoString((*C.char)(var_text)), 10, 64)\n\t\tif err != nil {\n\t\t\t\/\/ Leave variable as a string.\n\t\t\tlogValues[fmt.Sprintf(\"web100_log_entry.snap.%s\", canonicalName)] = C.GoString((*C.char)(var_text))\n\t\t} else {\n\t\t\t\/\/\n\t\t\tlogValues[fmt.Sprintf(\"web100_log_entry.snap.%s\", canonicalName)] = value\n\t\t}\n\t}\n\treturn logValues, nil\n}\n\n\/\/ Close releases resources created by Open.\nfunc (w *Web100) Close() error {\n\tsnap := (*C.web100_snapshot)(w.snap)\n\tC.web100_snapshot_free(snap)\n\n\tlog := (*C.web100_log)(w.log)\n\terr := C.web100_log_close_read(log)\n\tif err != C.WEB100_ERR_SUCCESS {\n\t\treturn fmt.Errorf(C.GoString(C.web100_strerror(err)))\n\t}\n\n\t\/\/ Clear pointer after free.\n\tw.log = nil\n\tw.snap = nil\n\treturn nil\n}\n\nfunc LookupError(errnum int) string {\n\treturn C.GoString(C.web100_strerror(C.int(errnum)))\n}\n\nfunc PrettyPrint(results map[string]string) {\n\tb, err := json.MarshalIndent(results, \"\", \"  \")\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t}\n\tfmt.Print(string(b))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\n\/\/ The format tests are white box tests, meaning that the tests are in the\n\/\/ same package as the code, as all the format details are internal to the\n\/\/ package.\n\npackage agent\n\nimport (\n\t\"os\"\n\t\"path\"\n\n\tgc \"launchpad.net\/gocheck\"\n\n\t\"launchpad.net\/juju-core\/testing\"\n\tjc \"launchpad.net\/juju-core\/testing\/checkers\"\n)\n\ntype format112Suite struct {\n\ttesting.LoggingSuite\n\tformatter formatter112\n}\n\nvar _ = gc.Suite(&format112Suite{})\n\nvar agentParams = AgentConfigParams{\n\tTag:            \"omg\",\n\tPassword:       \"sekrit\",\n\tCACert:         []byte(\"ca cert\"),\n\tStateAddresses: []string{\"localhost:1234\"},\n\tAPIAddresses:   []string{\"localhost:1235\"},\n\tNonce:          \"a nonce\",\n}\n\nfunc (s *format112Suite) newConfig(c *gc.C) *configInternal {\n\tparams := agentParams\n\tparams.DataDir = c.MkDir()\n\tconfig, err := newConfig(params)\n\tc.Assert(err, gc.IsNil)\n\treturn config\n}\n\nfunc (s *format112Suite) TestWriteAgentConfig(c *gc.C) {\n\tconfig := s.newConfig(c)\n\terr := s.formatter.write(config)\n\tc.Assert(err, gc.IsNil)\n\n\texpectedLocation := path.Join(config.Dir(), \"agent.conf\")\n\tfileInfo, err := os.Stat(expectedLocation)\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(fileInfo.Mode().IsRegular(), jc.IsTrue)\n\tc.Assert(fileInfo.Mode().Perm(), gc.Equals, os.FileMode(0600))\n\tc.Assert(fileInfo.Size(), jc.GreaterThan, 0)\n}\n\nfunc (s *format112Suite) TestRead(c *gc.C) {\n\tconfig := s.newConfig(c)\n\terr := s.formatter.write(config)\n\tc.Assert(err, gc.IsNil)\n\t\/\/ The readConfig is missing the dataDir initially.\n\treadConfig, err := s.formatter.read(config.Dir())\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(readConfig.dataDir, gc.Equals, \"\")\n\t\/\/ This is put in by the ReadConf method that we are avoiding using\n\t\/\/ becuase it will have side-effects soon around migrating configs.\n\treadConfig.dataDir = config.dataDir\n\tc.Assert(readConfig, gc.DeepEquals, config)\n}\n\nfunc (s *format112Suite) TestWriteCommands(c *gc.C) {\n\tconfig := s.newConfig(c)\n\tcommands, err := s.formatter.writeCommands(config)\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(commands, gc.HasLen, 3)\n\tc.Assert(commands[0], gc.Matches, `mkdir -p '\\S+\/agents\/omg'`)\n\tc.Assert(commands[1], gc.Matches, `install -m 600 \/dev\/null '\\S+\/agents\/omg\/agent.conf'`)\n\tc.Assert(commands[2], gc.Matches, `printf '%s\\\\n' '(.|\\n)*' > '\\S+\/agents\/omg\/agent.conf'`)\n}\n<commit_msg>Test state config.<commit_after>\/\/ Copyright 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\n\/\/ The format tests are white box tests, meaning that the tests are in the\n\/\/ same package as the code, as all the format details are internal to the\n\/\/ package.\n\npackage agent\n\nimport (\n\t\"os\"\n\t\"path\"\n\n\tgc \"launchpad.net\/gocheck\"\n\n\t\"launchpad.net\/juju-core\/testing\"\n\tjc \"launchpad.net\/juju-core\/testing\/checkers\"\n)\n\ntype format112Suite struct {\n\ttesting.LoggingSuite\n\tformatter formatter112\n}\n\nvar _ = gc.Suite(&format112Suite{})\n\nvar agentParams = AgentConfigParams{\n\tTag:            \"omg\",\n\tPassword:       \"sekrit\",\n\tCACert:         []byte(\"ca cert\"),\n\tStateAddresses: []string{\"localhost:1234\"},\n\tAPIAddresses:   []string{\"localhost:1235\"},\n\tNonce:          \"a nonce\",\n}\n\nfunc (s *format112Suite) newConfig(c *gc.C) *configInternal {\n\tparams := agentParams\n\tparams.DataDir = c.MkDir()\n\tconfig, err := newConfig(params)\n\tc.Assert(err, gc.IsNil)\n\treturn config\n}\n\nfunc (s *format112Suite) TestWriteAgentConfig(c *gc.C) {\n\tconfig := s.newConfig(c)\n\terr := s.formatter.write(config)\n\tc.Assert(err, gc.IsNil)\n\n\texpectedLocation := path.Join(config.Dir(), \"agent.conf\")\n\tfileInfo, err := os.Stat(expectedLocation)\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(fileInfo.Mode().IsRegular(), jc.IsTrue)\n\tc.Assert(fileInfo.Mode().Perm(), gc.Equals, os.FileMode(0600))\n\tc.Assert(fileInfo.Size(), jc.GreaterThan, 0)\n}\n\nfunc (s *format112Suite) assertWriteAndRead(c *gc.C, config *configInternal) {\n\terr := s.formatter.write(config)\n\tc.Assert(err, gc.IsNil)\n\t\/\/ The readConfig is missing the dataDir initially.\n\treadConfig, err := s.formatter.read(config.Dir())\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(readConfig.dataDir, gc.Equals, \"\")\n\t\/\/ This is put in by the ReadConf method that we are avoiding using\n\t\/\/ becuase it will have side-effects soon around migrating configs.\n\treadConfig.dataDir = config.dataDir\n\tc.Assert(readConfig, gc.DeepEquals, config)\n}\n\nfunc (s *format112Suite) TestRead(c *gc.C) {\n\tconfig := s.newConfig(c)\n\ts.assertWriteAndRead(c, config)\n}\n\nfunc (s *format112Suite) TestWriteCommands(c *gc.C) {\n\tconfig := s.newConfig(c)\n\tcommands, err := s.formatter.writeCommands(config)\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(commands, gc.HasLen, 3)\n\tc.Assert(commands[0], gc.Matches, `mkdir -p '\\S+\/agents\/omg'`)\n\tc.Assert(commands[1], gc.Matches, `install -m 600 \/dev\/null '\\S+\/agents\/omg\/agent.conf'`)\n\tc.Assert(commands[2], gc.Matches, `printf '%s\\\\n' '(.|\\n)*' > '\\S+\/agents\/omg\/agent.conf'`)\n}\n\nfunc (s *format112Suite) TestReadWriteStateConfig(c *gc.C) {\n\tstateParams := StateMachineConfigParams{\n\t\tAgentConfigParams: agentParams,\n\t\tStateServerCert:   []byte(\"some special cert\"),\n\t\tStateServerKey:    []byte(\"a special key\"),\n\t\tStatePort:         12345,\n\t\tAPIPort:           23456,\n\t}\n\tstateParams.DataDir = c.MkDir()\n\tconfigInterface, err := NewStateMachineConfig(stateParams)\n\tc.Assert(err, gc.IsNil)\n\tconfig, ok := configInterface.(*configInternal)\n\tc.Assert(ok, jc.IsTrue)\n\n\ts.assertWriteAndRead(c, config)\n}\n<|endoftext|>"}
{"text":"<commit_before>package channeldb\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"io\"\n\n\t\"github.com\/coreos\/bbolt\"\n\t\"github.com\/lightningnetwork\/lnd\/lnwire\"\n)\n\nvar (\n\t\/\/ paymentBucket is the name of the bucket within the database that\n\t\/\/ stores all data related to payments.\n\t\/\/\n\t\/\/ Within the payments bucket, each invoice is keyed by its invoice ID\n\t\/\/ which is a monotonically increasing uint64.  BoltDB's sequence\n\t\/\/ feature is used for generating monotonically increasing id.\n\tpaymentBucket = []byte(\"payments\")\n\n\t\/\/ paymentStatusBucket is the name of the bucket within the database that\n\t\/\/ stores the status of a payment indexed by the payment's preimage.\n\tpaymentStatusBucket = []byte(\"payment-status\")\n)\n\n\/\/ PaymentStatus represent current status of payment\ntype PaymentStatus byte\n\nconst (\n\t\/\/ StatusGrounded is status where payment is initiated and received\n\t\/\/ an intermittent failure\n\tStatusGrounded PaymentStatus = 0\n\n\t\/\/ StatusInFlight is status where payment is initiated, but a response\n\t\/\/ has not been received\n\tStatusInFlight PaymentStatus = 1\n\n\t\/\/ StatusCompleted is status where payment is initiated and complete\n\t\/\/ a payment successfully\n\tStatusCompleted PaymentStatus = 2\n)\n\n\/\/ Bytes returns status as slice of bytes\nfunc (ps PaymentStatus) Bytes() []byte {\n\treturn []byte{byte(ps)}\n}\n\n\/\/ FromBytes sets status from slice of bytes\nfunc (ps *PaymentStatus) FromBytes(status []byte) error {\n\tif len(status) != 1 {\n\t\treturn errors.New(\"payment status is empty\")\n\t}\n\n\tswitch PaymentStatus(status[0]) {\n\tcase StatusGrounded, StatusInFlight, StatusCompleted:\n\t\t*ps = PaymentStatus(status[0])\n\tdefault:\n\t\treturn errors.New(\"unknown payment status\")\n\t}\n\n\treturn nil\n}\n\n\/\/ String returns readable representation of payment status\nfunc (ps PaymentStatus) String() string {\n\tswitch ps {\n\tcase StatusGrounded:\n\t\treturn \"Grounded\"\n\tcase StatusInFlight:\n\t\treturn \"In Flight\"\n\tcase StatusCompleted:\n\t\treturn \"Completed\"\n\tdefault:\n\t\treturn \"Unknown\"\n\t}\n}\n\n\/\/ OutgoingPayment represents a successful payment between the daemon and a\n\/\/ remote node. Details such as the total fee paid, and the time of the payment\n\/\/ are stored.\ntype OutgoingPayment struct {\n\tInvoice\n\n\t\/\/ Fee is the total fee paid for the payment in milli-satoshis.\n\tFee lnwire.MilliSatoshi\n\n\t\/\/ TotalTimeLock is the total cumulative time-lock in the HTLC extended\n\t\/\/ from the second-to-last hop to the destination.\n\tTimeLockLength uint32\n\n\t\/\/ Path encodes the path the payment took through the network. The path\n\t\/\/ excludes the outgoing node and consists of the hex-encoded\n\t\/\/ compressed public key of each of the nodes involved in the payment.\n\tPath [][33]byte\n\n\t\/\/ PaymentPreimage is the preImage of a successful payment. This is used\n\t\/\/ to calculate the PaymentHash as well as serve as a proof of payment.\n\tPaymentPreimage [32]byte\n}\n\n\/\/ AddPayment saves a successful payment to the database. It is assumed that\n\/\/ all payment are sent using unique payment hashes.\nfunc (db *DB) AddPayment(payment *OutgoingPayment) error {\n\t\/\/ Validate the field of the inner voice within the outgoing payment,\n\t\/\/ these must also adhere to the same constraints as regular invoices.\n\tif err := validateInvoice(&payment.Invoice); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ We first serialize the payment before starting the database\n\t\/\/ transaction so we can avoid creating a DB payment in the case of a\n\t\/\/ serialization error.\n\tvar b bytes.Buffer\n\tif err := serializeOutgoingPayment(&b, payment); err != nil {\n\t\treturn err\n\t}\n\tpaymentBytes := b.Bytes()\n\n\treturn db.Batch(func(tx *bolt.Tx) error {\n\t\tpayments, err := tx.CreateBucketIfNotExists(paymentBucket)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Obtain the new unique sequence number for this payment.\n\t\tpaymentID, err := payments.NextSequence()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ We use BigEndian for keys as it orders keys in\n\t\t\/\/ ascending order. This allows bucket scans to order payments\n\t\t\/\/ in the order in which they were created.\n\t\tpaymentIDBytes := make([]byte, 8)\n\t\tbinary.BigEndian.PutUint64(paymentIDBytes, paymentID)\n\n\t\treturn payments.Put(paymentIDBytes, paymentBytes)\n\t})\n}\n\n\/\/ FetchAllPayments returns all outgoing payments in DB.\nfunc (db *DB) FetchAllPayments() ([]*OutgoingPayment, error) {\n\tvar payments []*OutgoingPayment\n\n\terr := db.View(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket(paymentBucket)\n\t\tif bucket == nil {\n\t\t\treturn ErrNoPaymentsCreated\n\t\t}\n\n\t\treturn bucket.ForEach(func(k, v []byte) error {\n\t\t\t\/\/ If the value is nil, then we ignore it as it may be\n\t\t\t\/\/ a sub-bucket.\n\t\t\tif v == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tr := bytes.NewReader(v)\n\t\t\tpayment, err := deserializeOutgoingPayment(r)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpayments = append(payments, payment)\n\t\t\treturn nil\n\t\t})\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn payments, nil\n}\n\n\/\/ DeleteAllPayments deletes all payments from DB.\nfunc (db *DB) DeleteAllPayments() error {\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\terr := tx.DeleteBucket(paymentBucket)\n\t\tif err != nil && err != bolt.ErrBucketNotFound {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = tx.CreateBucket(paymentBucket)\n\t\treturn err\n\t})\n}\n\n\/\/ UpdatePaymentStatus sets status for outgoing\/finished payment to store status in\n\/\/ local database.\nfunc (db *DB) UpdatePaymentStatus(paymentHash [32]byte, status PaymentStatus) error {\n\treturn db.Batch(func(tx *bolt.Tx) error {\n\t\tpaymentStatuses, err := tx.CreateBucketIfNotExists(paymentStatusBucket)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn paymentStatuses.Put(paymentHash[:], status.Bytes())\n\t})\n}\n\n\/\/ FetchPaymentStatus returns payment status for outgoing payment\n\/\/ if status of the payment isn't found it set to default status \"StatusGrounded\".\nfunc (db *DB) FetchPaymentStatus(paymentHash [32]byte) (PaymentStatus, error) {\n\t\/\/ default status for all payments that wasn't recorded in database\n\tpaymentStatus := StatusGrounded\n\n\terr := db.View(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket(paymentStatusBucket)\n\t\tif bucket == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tpaymentStatusBytes := bucket.Get(paymentHash[:])\n\t\tif paymentStatusBytes == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn paymentStatus.FromBytes(paymentStatusBytes)\n\t})\n\tif err != nil {\n\t\treturn StatusGrounded, err\n\t}\n\n\treturn paymentStatus, nil\n}\n\nfunc serializeOutgoingPayment(w io.Writer, p *OutgoingPayment) error {\n\tvar scratch [8]byte\n\n\tif err := serializeInvoice(w, &p.Invoice); err != nil {\n\t\treturn err\n\t}\n\n\tbyteOrder.PutUint64(scratch[:], uint64(p.Fee))\n\tif _, err := w.Write(scratch[:]); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ First write out the length of the bytes to prefix the value.\n\tpathLen := uint32(len(p.Path))\n\tbyteOrder.PutUint32(scratch[:4], pathLen)\n\tif _, err := w.Write(scratch[:4]); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Then with the path written, we write out the series of public keys\n\t\/\/ involved in the path.\n\tfor _, hop := range p.Path {\n\t\tif _, err := w.Write(hop[:]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tbyteOrder.PutUint32(scratch[:4], p.TimeLockLength)\n\tif _, err := w.Write(scratch[:4]); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := w.Write(p.PaymentPreimage[:]); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc deserializeOutgoingPayment(r io.Reader) (*OutgoingPayment, error) {\n\tvar scratch [8]byte\n\n\tp := &OutgoingPayment{}\n\n\tinv, err := deserializeInvoice(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.Invoice = inv\n\n\tif _, err := r.Read(scratch[:]); err != nil {\n\t\treturn nil, err\n\t}\n\tp.Fee = lnwire.MilliSatoshi(byteOrder.Uint64(scratch[:]))\n\n\tif _, err = r.Read(scratch[:4]); err != nil {\n\t\treturn nil, err\n\t}\n\tpathLen := byteOrder.Uint32(scratch[:4])\n\n\tpath := make([][33]byte, pathLen)\n\tfor i := uint32(0); i < pathLen; i++ {\n\t\tif _, err := r.Read(path[i][:]); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tp.Path = path\n\n\tif _, err = r.Read(scratch[:4]); err != nil {\n\t\treturn nil, err\n\t}\n\tp.TimeLockLength = byteOrder.Uint32(scratch[:4])\n\n\tif _, err := r.Read(p.PaymentPreimage[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, nil\n}\n<commit_msg>channeldb\/payments: touch up docs<commit_after>package channeldb\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"io\"\n\n\t\"github.com\/coreos\/bbolt\"\n\t\"github.com\/lightningnetwork\/lnd\/lnwire\"\n)\n\nvar (\n\t\/\/ paymentBucket is the name of the bucket within the database that\n\t\/\/ stores all data related to payments.\n\t\/\/\n\t\/\/ Within the payments bucket, each invoice is keyed by its invoice ID\n\t\/\/ which is a monotonically increasing uint64.  BoltDB's sequence\n\t\/\/ feature is used for generating monotonically increasing id.\n\tpaymentBucket = []byte(\"payments\")\n\n\t\/\/ paymentStatusBucket is the name of the bucket within the database that\n\t\/\/ stores the status of a payment indexed by the payment's preimage.\n\tpaymentStatusBucket = []byte(\"payment-status\")\n)\n\n\/\/ PaymentStatus represent current status of payment\ntype PaymentStatus byte\n\nconst (\n\t\/\/ StatusGrounded is the status where a payment has never been\n\t\/\/ initiated, or has been initiated and received an intermittent\n\t\/\/ failure.\n\tStatusGrounded PaymentStatus = 0\n\n\t\/\/ StatusInFlight is the status where a payment has been initiated, but\n\t\/\/ a response has not been received.\n\tStatusInFlight PaymentStatus = 1\n\n\t\/\/ StatusCompleted is the status where a payment has been initiated and\n\t\/\/ the payment was completed successfully.\n\tStatusCompleted PaymentStatus = 2\n)\n\n\/\/ Bytes returns status as slice of bytes.\nfunc (ps PaymentStatus) Bytes() []byte {\n\treturn []byte{byte(ps)}\n}\n\n\/\/ FromBytes sets status from slice of bytes.\nfunc (ps *PaymentStatus) FromBytes(status []byte) error {\n\tif len(status) != 1 {\n\t\treturn errors.New(\"payment status is empty\")\n\t}\n\n\tswitch PaymentStatus(status[0]) {\n\tcase StatusGrounded, StatusInFlight, StatusCompleted:\n\t\t*ps = PaymentStatus(status[0])\n\tdefault:\n\t\treturn errors.New(\"unknown payment status\")\n\t}\n\n\treturn nil\n}\n\n\/\/ String returns readable representation of payment status.\nfunc (ps PaymentStatus) String() string {\n\tswitch ps {\n\tcase StatusGrounded:\n\t\treturn \"Grounded\"\n\tcase StatusInFlight:\n\t\treturn \"In Flight\"\n\tcase StatusCompleted:\n\t\treturn \"Completed\"\n\tdefault:\n\t\treturn \"Unknown\"\n\t}\n}\n\n\/\/ OutgoingPayment represents a successful payment between the daemon and a\n\/\/ remote node. Details such as the total fee paid, and the time of the payment\n\/\/ are stored.\ntype OutgoingPayment struct {\n\tInvoice\n\n\t\/\/ Fee is the total fee paid for the payment in milli-satoshis.\n\tFee lnwire.MilliSatoshi\n\n\t\/\/ TotalTimeLock is the total cumulative time-lock in the HTLC extended\n\t\/\/ from the second-to-last hop to the destination.\n\tTimeLockLength uint32\n\n\t\/\/ Path encodes the path the payment took through the network. The path\n\t\/\/ excludes the outgoing node and consists of the hex-encoded\n\t\/\/ compressed public key of each of the nodes involved in the payment.\n\tPath [][33]byte\n\n\t\/\/ PaymentPreimage is the preImage of a successful payment. This is used\n\t\/\/ to calculate the PaymentHash as well as serve as a proof of payment.\n\tPaymentPreimage [32]byte\n}\n\n\/\/ AddPayment saves a successful payment to the database. It is assumed that\n\/\/ all payment are sent using unique payment hashes.\nfunc (db *DB) AddPayment(payment *OutgoingPayment) error {\n\t\/\/ Validate the field of the inner voice within the outgoing payment,\n\t\/\/ these must also adhere to the same constraints as regular invoices.\n\tif err := validateInvoice(&payment.Invoice); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ We first serialize the payment before starting the database\n\t\/\/ transaction so we can avoid creating a DB payment in the case of a\n\t\/\/ serialization error.\n\tvar b bytes.Buffer\n\tif err := serializeOutgoingPayment(&b, payment); err != nil {\n\t\treturn err\n\t}\n\tpaymentBytes := b.Bytes()\n\n\treturn db.Batch(func(tx *bolt.Tx) error {\n\t\tpayments, err := tx.CreateBucketIfNotExists(paymentBucket)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Obtain the new unique sequence number for this payment.\n\t\tpaymentID, err := payments.NextSequence()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ We use BigEndian for keys as it orders keys in\n\t\t\/\/ ascending order. This allows bucket scans to order payments\n\t\t\/\/ in the order in which they were created.\n\t\tpaymentIDBytes := make([]byte, 8)\n\t\tbinary.BigEndian.PutUint64(paymentIDBytes, paymentID)\n\n\t\treturn payments.Put(paymentIDBytes, paymentBytes)\n\t})\n}\n\n\/\/ FetchAllPayments returns all outgoing payments in DB.\nfunc (db *DB) FetchAllPayments() ([]*OutgoingPayment, error) {\n\tvar payments []*OutgoingPayment\n\n\terr := db.View(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket(paymentBucket)\n\t\tif bucket == nil {\n\t\t\treturn ErrNoPaymentsCreated\n\t\t}\n\n\t\treturn bucket.ForEach(func(k, v []byte) error {\n\t\t\t\/\/ If the value is nil, then we ignore it as it may be\n\t\t\t\/\/ a sub-bucket.\n\t\t\tif v == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tr := bytes.NewReader(v)\n\t\t\tpayment, err := deserializeOutgoingPayment(r)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpayments = append(payments, payment)\n\t\t\treturn nil\n\t\t})\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn payments, nil\n}\n\n\/\/ DeleteAllPayments deletes all payments from DB.\nfunc (db *DB) DeleteAllPayments() error {\n\treturn db.Update(func(tx *bolt.Tx) error {\n\t\terr := tx.DeleteBucket(paymentBucket)\n\t\tif err != nil && err != bolt.ErrBucketNotFound {\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = tx.CreateBucket(paymentBucket)\n\t\treturn err\n\t})\n}\n\n\/\/ UpdatePaymentStatus sets the payment status for outgoing\/finished payments in\n\/\/ local database.\nfunc (db *DB) UpdatePaymentStatus(paymentHash [32]byte, status PaymentStatus) error {\n\treturn db.Batch(func(tx *bolt.Tx) error {\n\t\tpaymentStatuses, err := tx.CreateBucketIfNotExists(paymentStatusBucket)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn paymentStatuses.Put(paymentHash[:], status.Bytes())\n\t})\n}\n\n\/\/ FetchPaymentStatus returns the payment status for outgoing payment.\n\/\/ If status of the payment isn't found, it will default to \"StatusGrounded\".\nfunc (db *DB) FetchPaymentStatus(paymentHash [32]byte) (PaymentStatus, error) {\n\t\/\/ The default status for all payments that aren't recorded in database.\n\tpaymentStatus := StatusGrounded\n\n\terr := db.View(func(tx *bolt.Tx) error {\n\t\tbucket := tx.Bucket(paymentStatusBucket)\n\t\tif bucket == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tpaymentStatusBytes := bucket.Get(paymentHash[:])\n\t\tif paymentStatusBytes == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn paymentStatus.FromBytes(paymentStatusBytes)\n\t})\n\tif err != nil {\n\t\treturn StatusGrounded, err\n\t}\n\n\treturn paymentStatus, nil\n}\n\nfunc serializeOutgoingPayment(w io.Writer, p *OutgoingPayment) error {\n\tvar scratch [8]byte\n\n\tif err := serializeInvoice(w, &p.Invoice); err != nil {\n\t\treturn err\n\t}\n\n\tbyteOrder.PutUint64(scratch[:], uint64(p.Fee))\n\tif _, err := w.Write(scratch[:]); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ First write out the length of the bytes to prefix the value.\n\tpathLen := uint32(len(p.Path))\n\tbyteOrder.PutUint32(scratch[:4], pathLen)\n\tif _, err := w.Write(scratch[:4]); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Then with the path written, we write out the series of public keys\n\t\/\/ involved in the path.\n\tfor _, hop := range p.Path {\n\t\tif _, err := w.Write(hop[:]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tbyteOrder.PutUint32(scratch[:4], p.TimeLockLength)\n\tif _, err := w.Write(scratch[:4]); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := w.Write(p.PaymentPreimage[:]); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc deserializeOutgoingPayment(r io.Reader) (*OutgoingPayment, error) {\n\tvar scratch [8]byte\n\n\tp := &OutgoingPayment{}\n\n\tinv, err := deserializeInvoice(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.Invoice = inv\n\n\tif _, err := r.Read(scratch[:]); err != nil {\n\t\treturn nil, err\n\t}\n\tp.Fee = lnwire.MilliSatoshi(byteOrder.Uint64(scratch[:]))\n\n\tif _, err = r.Read(scratch[:4]); err != nil {\n\t\treturn nil, err\n\t}\n\tpathLen := byteOrder.Uint32(scratch[:4])\n\n\tpath := make([][33]byte, pathLen)\n\tfor i := uint32(0); i < pathLen; i++ {\n\t\tif _, err := r.Read(path[i][:]); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tp.Path = path\n\n\tif _, err = r.Read(scratch[:4]); err != nil {\n\t\treturn nil, err\n\t}\n\tp.TimeLockLength = byteOrder.Uint32(scratch[:4])\n\n\tif _, err := r.Read(p.PaymentPreimage[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package checkers\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestNewGame(t *testing.T) {\n\tgame := NewGame()\n\tboard := game.GetBoard()\n\tif board == nil {\n\t\tt.Error(\"Board wasn't created.\")\n\t}\n}\n\nfunc TestGetAvailableMoves(t *testing.T) {\n\t\/\/ TODO: Fix positions (checkers are placed on white cells!)\n\tcheckers := []*struct {\n\t\tch   Checker\n\t\tX, Y int\n\t}{\n\t\t{newChecker(false), 4, 5},\n\t\t{newChecker(true), 5, 6},\n\t\t{newChecker(false), 3, 6},\n\t\t{newChecker(true), 3, 4},\n\t\t{newChecker(false), 5, 4},\n\t\t{newChecker(true), 6, 7},\n\t\t{newChecker(false), 2, 7},\n\t\t{newChecker(true), 2, 3},\n\t\t{newChecker(false), 6, 3},\n\t}\n\n\texpectedMoves := [][]Move{\n\t\tnil,\n\t\t{Move{Target: Point{X: 4, Y: 7}, BecomeQueen: true}},\n\t\t{Move{Target: Point{X: 2, Y: 5}}},\n\t\t{Move{Target: Point{X: 2, Y: 5}}},\n\t\t{Move{Target: Point{X: 4, Y: 3}}},\n\t\tnil,\n\t\t{Move{Target: Point{X: 1, Y: 6}}},\n\t\t{Move{Target: Point{X: 1, Y: 4}}},\n\t\t{\n\t\t\tMove{Target: Point{X: 5, Y: 2}},\n\t\t\tMove{Target: Point{X: 7, Y: 2}},\n\t\t},\n\t}\n\n\tgame := NewGame()\n\tboard := game.GetBoard()\n\n\tfor _, c := range checkers {\n\t\tmoves := game.getAvailableMoves(&c.ch, false)\n\t\tif len(moves) > 0 {\n\t\t\tt.Error(\"Checker at\", c.ch.Position(), \"is not on board but has moves:\", moves)\n\t\t}\n\t}\n\n\tfor _, c := range checkers {\n\t\tboard.placeChecker(c.X, c.Y, &c.ch)\n\t}\n\n\tfor i, c := range checkers {\n\t\tmoves := game.getAvailableMoves(&c.ch, false)\n\t\t\/\/ we should compare sorted moves (both expected and acquired from game)\n\t\t\/\/ since order can be different. First we have to compare lengths of\n\t\t\/\/ both slices and only the do in-depth compare (i.e. sort and compare\n\t\t\/\/ elements). It's requied to extract comparison code ino separate\n\t\t\/\/ function.\n\t\tif !reflect.DeepEqual(moves, expectedMoves[i]) {\n\t\t\tif expectedMoves[i] == nil {\n\t\t\t\tt.Error(\"Checker at\", c.ch.Position(), \"shouldn't have moves.\")\n\t\t\t} else {\n\t\t\t\tt.Error(\"Checker at\", c.ch.Position(), \"should have at least 1 move.\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif t.Failed() {\n\t\tt.Logf(\"Current board state:\\n%s\", board.DebugString())\n\t}\n}\n<commit_msg>Place checkers on black cells Resolve cl0ne\/go-checkers#2<commit_after>package checkers\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestNewGame(t *testing.T) {\n\tgame := NewGame()\n\tboard := game.GetBoard()\n\tif board == nil {\n\t\tt.Error(\"Board wasn't created.\")\n\t}\n}\n\nfunc TestGetAvailableMoves(t *testing.T) {\n\tcheckers := []*struct {\n\t\tch   Checker\n\t\tX, Y int\n\t}{\n\t\t{newChecker(false), 4, 4},\n\t\t{newChecker(true), 5, 5},\n\t\t{newChecker(false), 3, 5},\n\t\t{newChecker(true), 3, 3},\n\t\t{newChecker(false), 5, 3},\n\t\t{newChecker(true), 6, 6},\n\t\t{newChecker(false), 2, 6},\n\t\t{newChecker(true), 2, 2},\n\t\t{newChecker(false), 6, 2},\n\t}\n\n\texpectedMoves := [][]Move{\n\t\tnil,\n\t\t{Move{Target: Point{X: 4, Y: 6}}},\n\t\t{Move{Target: Point{X: 2, Y: 4}}},\n\t\t{Move{Target: Point{X: 2, Y: 4}}},\n\t\t{Move{Target: Point{X: 4, Y: 2}}},\n\t\t{\n\t\t\tMove{Target: Point{X: 7, Y: 7}, BecomeQueen: true},\n\t\t\tMove{Target: Point{X: 5, Y: 7}, BecomeQueen: true},\n\t\t},\n\t\t{Move{Target: Point{X: 1, Y: 5}}},\n\t\t{Move{Target: Point{X: 1, Y: 3}}},\n\t\t{\n\t\t\tMove{Target: Point{X: 5, Y: 1}},\n\t\t\tMove{Target: Point{X: 7, Y: 1}},\n\t\t},\n\t}\n\n\tgame := NewGame()\n\tboard := game.GetBoard()\n\n\tfor _, c := range checkers {\n\t\tmoves := game.getAvailableMoves(&c.ch, false)\n\t\tif len(moves) > 0 {\n\t\t\tt.Error(\"Checker at\", c.ch.Position(), \"is not on board but has moves:\", moves)\n\t\t}\n\t}\n\n\tfor _, c := range checkers {\n\t\tboard.placeChecker(c.X, c.Y, &c.ch)\n\t}\n\n\tfor i, c := range checkers {\n\t\tmoves := game.getAvailableMoves(&c.ch, false)\n\t\t\/\/ we should compare sorted moves (both expected and acquired from game)\n\t\t\/\/ since order can be different. First we have to compare lengths of\n\t\t\/\/ both slices and only the do in-depth compare (i.e. sort and compare\n\t\t\/\/ elements). It's requied to extract comparison code ino separate\n\t\t\/\/ function.\n\t\tif !reflect.DeepEqual(moves, expectedMoves[i]) {\n\t\t\tif expectedMoves[i] == nil {\n\t\t\t\tt.Error(\"Checker at\", c.ch.Position(), \"shouldn't have moves.\")\n\t\t\t} else {\n\t\t\t\tt.Error(\"Checker at\", c.ch.Position(), \"should have at least 1 move.\")\n\t\t\t}\n\t\t}\n\t}\n\n\tif t.Failed() {\n\t\tt.Logf(\"Current board state:\\n%s\", board.DebugString())\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package jobspec\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/hcl\"\n\thclobj \"github.com\/hashicorp\/hcl\/hcl\"\n\t\"github.com\/hashicorp\/nomad\/nomad\/structs\"\n\t\"github.com\/mitchellh\/mapstructure\"\n)\n\n\/\/ Parse parses the job spec from the given io.Reader.\n\/\/\n\/\/ Due to current internal limitations, the entire contents of the\n\/\/ io.Reader will be copied into memory first before parsing.\nfunc Parse(r io.Reader) (*structs.Job, error) {\n\t\/\/ Copy the reader into an in-memory buffer first since HCL requires it.\n\tvar buf bytes.Buffer\n\tif _, err := io.Copy(&buf, r); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Parse the buffer\n\tobj, err := hcl.Parse(buf.String())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing: %s\", err)\n\t}\n\tbuf.Reset()\n\n\tvar job structs.Job\n\n\t\/\/ Parse the job out\n\tjobO := obj.Get(\"job\", false)\n\tif jobO == nil {\n\t\treturn nil, fmt.Errorf(\"'job' stanza not found\")\n\t}\n\tif err := parseJob(&job, jobO); err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing 'job': %s\", err)\n\t}\n\n\treturn &job, nil\n}\n\n\/\/ ParseFile parses the given path as a job spec.\nfunc ParseFile(path string) (*structs.Job, error) {\n\tpath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\treturn Parse(f)\n}\n\nfunc parseJob(result *structs.Job, obj *hclobj.Object) error {\n\tif obj.Len() > 1 {\n\t\treturn fmt.Errorf(\"only one 'job' block allowed\")\n\t}\n\n\t\/\/ Get our job object\n\tobj = obj.Elem(true)[0]\n\n\t\/\/ Decode the full thing into a map[string]interface for ease\n\tvar m map[string]interface{}\n\tif err := hcl.DecodeObject(&m, obj); err != nil {\n\t\treturn err\n\t}\n\tdelete(m, \"constraint\")\n\tdelete(m, \"meta\")\n\tdelete(m, \"update\")\n\n\t\/\/ Set the ID and name to the object key\n\tresult.ID = obj.Key\n\tresult.Name = obj.Key\n\n\t\/\/ Defaults\n\tresult.Priority = 50\n\tresult.Region = \"global\"\n\tresult.Type = \"service\"\n\n\t\/\/ Decode the rest\n\tif err := mapstructure.WeakDecode(m, result); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Parse constraints\n\tif o := obj.Get(\"constraint\", false); o != nil {\n\t\tif err := parseConstraints(&result.Constraints, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ If we have an update strategy, then parse that\n\tif o := obj.Get(\"update\", false); o != nil {\n\t\tif err := parseUpdate(&result.Update, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Parse out meta fields. These are in HCL as a list so we need\n\t\/\/ to iterate over them and merge them.\n\tif metaO := obj.Get(\"meta\", false); metaO != nil {\n\t\tfor _, o := range metaO.Elem(false) {\n\t\t\tvar m map[string]interface{}\n\t\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := mapstructure.WeakDecode(m, &result.Meta); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ If we have tasks outside, do those\n\tif o := obj.Get(\"task\", false); o != nil {\n\t\tvar tasks []*structs.Task\n\t\tif err := parseTasks(&tasks, o); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tresult.TaskGroups = make([]*structs.TaskGroup, len(tasks), len(tasks)*2)\n\t\tfor i, t := range tasks {\n\t\t\tresult.TaskGroups[i] = &structs.TaskGroup{\n\t\t\t\tName:  t.Name,\n\t\t\t\tCount: 1,\n\t\t\t\tTasks: []*structs.Task{t},\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Parse the task groups\n\tif o := obj.Get(\"group\", false); o != nil {\n\t\tif err := parseGroups(result, o); err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing 'group': %s\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc parseGroups(result *structs.Job, obj *hclobj.Object) error {\n\t\/\/ Get all the maps of keys to the actual object\n\tobjects := make(map[string]*hclobj.Object)\n\tfor _, o1 := range obj.Elem(false) {\n\t\tfor _, o2 := range o1.Elem(true) {\n\t\t\tif _, ok := objects[o2.Key]; ok {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"group '%s' defined more than once\",\n\t\t\t\t\to2.Key)\n\t\t\t}\n\n\t\t\tobjects[o2.Key] = o2\n\t\t}\n\t}\n\n\tif len(objects) == 0 {\n\t\treturn nil\n\t}\n\n\t\/\/ Go through each object and turn it into an actual result.\n\tcollection := make([]*structs.TaskGroup, 0, len(objects))\n\tfor n, o := range objects {\n\t\tvar m map[string]interface{}\n\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdelete(m, \"constraint\")\n\t\tdelete(m, \"meta\")\n\t\tdelete(m, \"task\")\n\n\t\t\/\/ Build the group with the basic decode\n\t\tvar g structs.TaskGroup\n\t\tg.Name = n\n\t\tif err := mapstructure.WeakDecode(m, &g); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Parse constraints\n\t\tif o := o.Get(\"constraint\", false); o != nil {\n\t\t\tif err := parseConstraints(&g.Constraints, o); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Parse out meta fields. These are in HCL as a list so we need\n\t\t\/\/ to iterate over them and merge them.\n\t\tif metaO := o.Get(\"meta\", false); metaO != nil {\n\t\t\tfor _, o := range metaO.Elem(false) {\n\t\t\t\tvar m map[string]interface{}\n\t\t\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := mapstructure.WeakDecode(m, &g.Meta); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Parse tasks\n\t\tif o := o.Get(\"task\", false); o != nil {\n\t\t\tif err := parseTasks(&g.Tasks, o); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tcollection = append(collection, &g)\n\t}\n\n\tresult.TaskGroups = append(result.TaskGroups, collection...)\n\treturn nil\n}\n\nfunc parseConstraints(result *[]*structs.Constraint, obj *hclobj.Object) error {\n\tfor _, o := range obj.Elem(false) {\n\t\tvar m map[string]interface{}\n\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tm[\"LTarget\"] = m[\"attribute\"]\n\t\tm[\"RTarget\"] = m[\"value\"]\n\t\tm[\"Operand\"] = m[\"operator\"]\n\n\t\t\/\/ Default constraint to being hard\n\t\tif _, ok := m[\"hard\"]; !ok {\n\t\t\tm[\"hard\"] = true\n\t\t}\n\n\t\t\/\/ Build the constraint\n\t\tvar c structs.Constraint\n\t\tif err := mapstructure.WeakDecode(m, &c); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif c.Operand == \"\" {\n\t\t\tc.Operand = \"=\"\n\t\t}\n\n\t\t*result = append(*result, &c)\n\t}\n\n\treturn nil\n}\n\nfunc parseTasks(result *[]*structs.Task, obj *hclobj.Object) error {\n\t\/\/ Get all the maps of keys to the actual object\n\tobjects := make([]*hclobj.Object, 0, 5)\n\tset := make(map[string]struct{})\n\tfor _, o1 := range obj.Elem(false) {\n\t\tfor _, o2 := range o1.Elem(true) {\n\t\t\tif _, ok := set[o2.Key]; ok {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"group '%s' defined more than once\",\n\t\t\t\t\to2.Key)\n\t\t\t}\n\n\t\t\tobjects = append(objects, o2)\n\t\t\tset[o2.Key] = struct{}{}\n\t\t}\n\t}\n\n\tif len(objects) == 0 {\n\t\treturn nil\n\t}\n\n\tfor _, o := range objects {\n\t\tvar m map[string]interface{}\n\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdelete(m, \"config\")\n\t\tdelete(m, \"constraint\")\n\t\tdelete(m, \"meta\")\n\t\tdelete(m, \"resources\")\n\n\t\t\/\/ Build the task\n\t\tvar t structs.Task\n\t\tt.Name = o.Key\n\t\tif err := mapstructure.WeakDecode(m, &t); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ If we have config, then parse that\n\t\tif o := o.Get(\"config\", false); o != nil {\n\t\t\tfor _, o := range o.Elem(false) {\n\t\t\t\tvar m map[string]interface{}\n\t\t\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := mapstructure.WeakDecode(m, &t.Config); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Parse constraints\n\t\tif o := o.Get(\"constraint\", false); o != nil {\n\t\t\tif err := parseConstraints(&t.Constraints, o); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Parse out meta fields. These are in HCL as a list so we need\n\t\t\/\/ to iterate over them and merge them.\n\t\tif metaO := o.Get(\"meta\", false); metaO != nil {\n\t\t\tfor _, o := range metaO.Elem(false) {\n\t\t\t\tvar m map[string]interface{}\n\t\t\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := mapstructure.WeakDecode(m, &t.Meta); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If we have resources, then parse that\n\t\tif o := o.Get(\"resources\", false); o != nil {\n\t\t\tvar r structs.Resources\n\t\t\tif err := parseResources(&r, o); err != nil {\n\t\t\t\treturn fmt.Errorf(\"task '%s': %s\", t.Name, err)\n\t\t\t}\n\n\t\t\tt.Resources = &r\n\t\t}\n\n\t\t*result = append(*result, &t)\n\t}\n\n\treturn nil\n}\n\nfunc parseResources(result *structs.Resources, obj *hclobj.Object) error {\n\tif obj.Len() > 1 {\n\t\treturn fmt.Errorf(\"only one 'resource' block allowed per task\")\n\t}\n\n\tfor _, o := range obj.Elem(false) {\n\t\tvar m map[string]interface{}\n\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdelete(m, \"network\")\n\n\t\tif err := mapstructure.WeakDecode(m, result); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Parse the network resources\n\t\tif o := o.Get(\"network\", false); o != nil {\n\t\t\tif o.Len() > 1 {\n\t\t\t\treturn fmt.Errorf(\"only one 'network' resource allowed\")\n\t\t\t}\n\n\t\t\tvar r structs.NetworkResource\n\t\t\tvar m map[string]interface{}\n\t\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := mapstructure.WeakDecode(m, &r); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tresult.Networks = []*structs.NetworkResource{&r}\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc parseUpdate(result *structs.UpdateStrategy, obj *hclobj.Object) error {\n\tif obj.Len() > 1 {\n\t\treturn fmt.Errorf(\"only one 'update' block allowed per job\")\n\t}\n\n\tfor _, o := range obj.Elem(false) {\n\t\tvar m map[string]interface{}\n\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, key := range []string{\"stagger\", \"Stagger\"} {\n\t\t\tif raw, ok := m[key]; ok {\n\t\t\t\tswitch v := raw.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tdur, err := time.ParseDuration(v)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"invalid stagger time '%s'\", raw)\n\t\t\t\t\t}\n\t\t\t\t\tm[key] = dur\n\t\t\t\tcase int:\n\t\t\t\t\tm[key] = time.Duration(v) * time.Second\n\t\t\t\tdefault:\n\t\t\t\t\treturn fmt.Errorf(\"invalid type for stagger time '%s'\",\n\t\t\t\t\t\traw)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err := mapstructure.WeakDecode(m, result); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>jobspec: default count of group to 1 if not specified<commit_after>package jobspec\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/hcl\"\n\thclobj \"github.com\/hashicorp\/hcl\/hcl\"\n\t\"github.com\/hashicorp\/nomad\/nomad\/structs\"\n\t\"github.com\/mitchellh\/mapstructure\"\n)\n\n\/\/ Parse parses the job spec from the given io.Reader.\n\/\/\n\/\/ Due to current internal limitations, the entire contents of the\n\/\/ io.Reader will be copied into memory first before parsing.\nfunc Parse(r io.Reader) (*structs.Job, error) {\n\t\/\/ Copy the reader into an in-memory buffer first since HCL requires it.\n\tvar buf bytes.Buffer\n\tif _, err := io.Copy(&buf, r); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Parse the buffer\n\tobj, err := hcl.Parse(buf.String())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing: %s\", err)\n\t}\n\tbuf.Reset()\n\n\tvar job structs.Job\n\n\t\/\/ Parse the job out\n\tjobO := obj.Get(\"job\", false)\n\tif jobO == nil {\n\t\treturn nil, fmt.Errorf(\"'job' stanza not found\")\n\t}\n\tif err := parseJob(&job, jobO); err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing 'job': %s\", err)\n\t}\n\n\treturn &job, nil\n}\n\n\/\/ ParseFile parses the given path as a job spec.\nfunc ParseFile(path string) (*structs.Job, error) {\n\tpath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\treturn Parse(f)\n}\n\nfunc parseJob(result *structs.Job, obj *hclobj.Object) error {\n\tif obj.Len() > 1 {\n\t\treturn fmt.Errorf(\"only one 'job' block allowed\")\n\t}\n\n\t\/\/ Get our job object\n\tobj = obj.Elem(true)[0]\n\n\t\/\/ Decode the full thing into a map[string]interface for ease\n\tvar m map[string]interface{}\n\tif err := hcl.DecodeObject(&m, obj); err != nil {\n\t\treturn err\n\t}\n\tdelete(m, \"constraint\")\n\tdelete(m, \"meta\")\n\tdelete(m, \"update\")\n\n\t\/\/ Set the ID and name to the object key\n\tresult.ID = obj.Key\n\tresult.Name = obj.Key\n\n\t\/\/ Defaults\n\tresult.Priority = 50\n\tresult.Region = \"global\"\n\tresult.Type = \"service\"\n\n\t\/\/ Decode the rest\n\tif err := mapstructure.WeakDecode(m, result); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Parse constraints\n\tif o := obj.Get(\"constraint\", false); o != nil {\n\t\tif err := parseConstraints(&result.Constraints, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ If we have an update strategy, then parse that\n\tif o := obj.Get(\"update\", false); o != nil {\n\t\tif err := parseUpdate(&result.Update, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Parse out meta fields. These are in HCL as a list so we need\n\t\/\/ to iterate over them and merge them.\n\tif metaO := obj.Get(\"meta\", false); metaO != nil {\n\t\tfor _, o := range metaO.Elem(false) {\n\t\t\tvar m map[string]interface{}\n\t\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := mapstructure.WeakDecode(m, &result.Meta); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ If we have tasks outside, do those\n\tif o := obj.Get(\"task\", false); o != nil {\n\t\tvar tasks []*structs.Task\n\t\tif err := parseTasks(&tasks, o); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tresult.TaskGroups = make([]*structs.TaskGroup, len(tasks), len(tasks)*2)\n\t\tfor i, t := range tasks {\n\t\t\tresult.TaskGroups[i] = &structs.TaskGroup{\n\t\t\t\tName:  t.Name,\n\t\t\t\tCount: 1,\n\t\t\t\tTasks: []*structs.Task{t},\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Parse the task groups\n\tif o := obj.Get(\"group\", false); o != nil {\n\t\tif err := parseGroups(result, o); err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing 'group': %s\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc parseGroups(result *structs.Job, obj *hclobj.Object) error {\n\t\/\/ Get all the maps of keys to the actual object\n\tobjects := make(map[string]*hclobj.Object)\n\tfor _, o1 := range obj.Elem(false) {\n\t\tfor _, o2 := range o1.Elem(true) {\n\t\t\tif _, ok := objects[o2.Key]; ok {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"group '%s' defined more than once\",\n\t\t\t\t\to2.Key)\n\t\t\t}\n\n\t\t\tobjects[o2.Key] = o2\n\t\t}\n\t}\n\n\tif len(objects) == 0 {\n\t\treturn nil\n\t}\n\n\t\/\/ Go through each object and turn it into an actual result.\n\tcollection := make([]*structs.TaskGroup, 0, len(objects))\n\tfor n, o := range objects {\n\t\tvar m map[string]interface{}\n\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdelete(m, \"constraint\")\n\t\tdelete(m, \"meta\")\n\t\tdelete(m, \"task\")\n\n\t\t\/\/ Default count to 1 if not specified\n\t\tif _, ok := m[\"count\"]; !ok {\n\t\t\tm[\"count\"] = 1\n\t\t}\n\n\t\t\/\/ Build the group with the basic decode\n\t\tvar g structs.TaskGroup\n\t\tg.Name = n\n\t\tif err := mapstructure.WeakDecode(m, &g); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Parse constraints\n\t\tif o := o.Get(\"constraint\", false); o != nil {\n\t\t\tif err := parseConstraints(&g.Constraints, o); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Parse out meta fields. These are in HCL as a list so we need\n\t\t\/\/ to iterate over them and merge them.\n\t\tif metaO := o.Get(\"meta\", false); metaO != nil {\n\t\t\tfor _, o := range metaO.Elem(false) {\n\t\t\t\tvar m map[string]interface{}\n\t\t\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := mapstructure.WeakDecode(m, &g.Meta); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Parse tasks\n\t\tif o := o.Get(\"task\", false); o != nil {\n\t\t\tif err := parseTasks(&g.Tasks, o); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tcollection = append(collection, &g)\n\t}\n\n\tresult.TaskGroups = append(result.TaskGroups, collection...)\n\treturn nil\n}\n\nfunc parseConstraints(result *[]*structs.Constraint, obj *hclobj.Object) error {\n\tfor _, o := range obj.Elem(false) {\n\t\tvar m map[string]interface{}\n\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tm[\"LTarget\"] = m[\"attribute\"]\n\t\tm[\"RTarget\"] = m[\"value\"]\n\t\tm[\"Operand\"] = m[\"operator\"]\n\n\t\t\/\/ Default constraint to being hard\n\t\tif _, ok := m[\"hard\"]; !ok {\n\t\t\tm[\"hard\"] = true\n\t\t}\n\n\t\t\/\/ Build the constraint\n\t\tvar c structs.Constraint\n\t\tif err := mapstructure.WeakDecode(m, &c); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif c.Operand == \"\" {\n\t\t\tc.Operand = \"=\"\n\t\t}\n\n\t\t*result = append(*result, &c)\n\t}\n\n\treturn nil\n}\n\nfunc parseTasks(result *[]*structs.Task, obj *hclobj.Object) error {\n\t\/\/ Get all the maps of keys to the actual object\n\tobjects := make([]*hclobj.Object, 0, 5)\n\tset := make(map[string]struct{})\n\tfor _, o1 := range obj.Elem(false) {\n\t\tfor _, o2 := range o1.Elem(true) {\n\t\t\tif _, ok := set[o2.Key]; ok {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"group '%s' defined more than once\",\n\t\t\t\t\to2.Key)\n\t\t\t}\n\n\t\t\tobjects = append(objects, o2)\n\t\t\tset[o2.Key] = struct{}{}\n\t\t}\n\t}\n\n\tif len(objects) == 0 {\n\t\treturn nil\n\t}\n\n\tfor _, o := range objects {\n\t\tvar m map[string]interface{}\n\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdelete(m, \"config\")\n\t\tdelete(m, \"constraint\")\n\t\tdelete(m, \"meta\")\n\t\tdelete(m, \"resources\")\n\n\t\t\/\/ Build the task\n\t\tvar t structs.Task\n\t\tt.Name = o.Key\n\t\tif err := mapstructure.WeakDecode(m, &t); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ If we have config, then parse that\n\t\tif o := o.Get(\"config\", false); o != nil {\n\t\t\tfor _, o := range o.Elem(false) {\n\t\t\t\tvar m map[string]interface{}\n\t\t\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := mapstructure.WeakDecode(m, &t.Config); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Parse constraints\n\t\tif o := o.Get(\"constraint\", false); o != nil {\n\t\t\tif err := parseConstraints(&t.Constraints, o); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Parse out meta fields. These are in HCL as a list so we need\n\t\t\/\/ to iterate over them and merge them.\n\t\tif metaO := o.Get(\"meta\", false); metaO != nil {\n\t\t\tfor _, o := range metaO.Elem(false) {\n\t\t\t\tvar m map[string]interface{}\n\t\t\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := mapstructure.WeakDecode(m, &t.Meta); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If we have resources, then parse that\n\t\tif o := o.Get(\"resources\", false); o != nil {\n\t\t\tvar r structs.Resources\n\t\t\tif err := parseResources(&r, o); err != nil {\n\t\t\t\treturn fmt.Errorf(\"task '%s': %s\", t.Name, err)\n\t\t\t}\n\n\t\t\tt.Resources = &r\n\t\t}\n\n\t\t*result = append(*result, &t)\n\t}\n\n\treturn nil\n}\n\nfunc parseResources(result *structs.Resources, obj *hclobj.Object) error {\n\tif obj.Len() > 1 {\n\t\treturn fmt.Errorf(\"only one 'resource' block allowed per task\")\n\t}\n\n\tfor _, o := range obj.Elem(false) {\n\t\tvar m map[string]interface{}\n\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdelete(m, \"network\")\n\n\t\tif err := mapstructure.WeakDecode(m, result); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Parse the network resources\n\t\tif o := o.Get(\"network\", false); o != nil {\n\t\t\tif o.Len() > 1 {\n\t\t\t\treturn fmt.Errorf(\"only one 'network' resource allowed\")\n\t\t\t}\n\n\t\t\tvar r structs.NetworkResource\n\t\t\tvar m map[string]interface{}\n\t\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := mapstructure.WeakDecode(m, &r); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tresult.Networks = []*structs.NetworkResource{&r}\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc parseUpdate(result *structs.UpdateStrategy, obj *hclobj.Object) error {\n\tif obj.Len() > 1 {\n\t\treturn fmt.Errorf(\"only one 'update' block allowed per job\")\n\t}\n\n\tfor _, o := range obj.Elem(false) {\n\t\tvar m map[string]interface{}\n\t\tif err := hcl.DecodeObject(&m, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, key := range []string{\"stagger\", \"Stagger\"} {\n\t\t\tif raw, ok := m[key]; ok {\n\t\t\t\tswitch v := raw.(type) {\n\t\t\t\tcase string:\n\t\t\t\t\tdur, err := time.ParseDuration(v)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"invalid stagger time '%s'\", raw)\n\t\t\t\t\t}\n\t\t\t\t\tm[key] = dur\n\t\t\t\tcase int:\n\t\t\t\t\tm[key] = time.Duration(v) * time.Second\n\t\t\t\tdefault:\n\t\t\t\t\treturn fmt.Errorf(\"invalid type for stagger time '%s'\",\n\t\t\t\t\t\traw)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err := mapstructure.WeakDecode(m, result); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 CoreOS, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ etcdctl is a command line application that controls etcd.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/coreos\/etcd\/etcdctl\/ctlv2\"\n\t\"github.com\/coreos\/etcd\/etcdctl\/ctlv3\"\n)\n\nconst (\n\tapiEnv = \"ETCDCTL_API\"\n)\n\nfunc main() {\n\tapiv := os.Getenv(apiEnv)\n\t\/\/ unset apiEnv to avoid side-effect for future env and flag parsing.\n\tos.Unsetenv(apiv)\n\tif len(apiv) == 0 || apiv == \"2\" {\n\t\tctlv2.Start()\n\t\treturn\n\t}\n\n\tif apiv == \"3\" {\n\t\tctlv3.Start()\n\t\treturn\n\t}\n\n\tfmt.Fprintln(os.Stderr, \"unsupported API version\", apiv)\n\tos.Exit(1)\n}\n<commit_msg>etcdctl: unset ETCDCTL_API env var properly<commit_after>\/\/ Copyright 2016 CoreOS, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ etcdctl is a command line application that controls etcd.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/coreos\/etcd\/etcdctl\/ctlv2\"\n\t\"github.com\/coreos\/etcd\/etcdctl\/ctlv3\"\n)\n\nconst (\n\tapiEnv = \"ETCDCTL_API\"\n)\n\nfunc main() {\n\tapiv := os.Getenv(apiEnv)\n\t\/\/ unset apiEnv to avoid side-effect for future env and flag parsing.\n\tos.Unsetenv(apiEnv)\n\tif len(apiv) == 0 || apiv == \"2\" {\n\t\tctlv2.Start()\n\t\treturn\n\t}\n\n\tif apiv == \"3\" {\n\t\tctlv3.Start()\n\t\treturn\n\t}\n\n\tfmt.Fprintln(os.Stderr, \"unsupported API version\", apiv)\n\tos.Exit(1)\n}\n<|endoftext|>"}
{"text":"<commit_before>package eval\n\nimport (\n\t\"fmt\"\n)\n\ntype ioType byte\n\nconst (\n\tfileIO ioType = iota \/\/ Default IO type. Corresponds to io.f.\n\tchanIO \/\/ Corresponds to io.ch.\n\tunusedIO\n)\n\ntype builtinFunc func(*Evaluator, []Value, [3]*io) string\n\ntype builtin struct {\n\tfn builtinFunc\n\tioTypes [3]ioType\n}\n\nvar builtins = map[string]builtin {\n\t\"set\": builtin{implSet, [3]ioType{unusedIO, unusedIO}},\n\t\"put\": builtin{implPut, [3]ioType{unusedIO, chanIO}},\n\t\"print\": builtin{implPrint, [3]ioType{unusedIO}},\n\t\"println\": builtin{implPrintln, [3]ioType{unusedIO}},\n\t\"printchan\": builtin{implPrintchan, [3]ioType{chanIO, fileIO}},\n}\n\nfunc implSet(ev *Evaluator, args []Value, ios [3]*io) string {\n\t\/\/ TODO Support setting locals\n\t\/\/ TODO Prevent overriding builtin variables e.g. $pid $env\n\tif len(args) != 3 || args[1].String(ev) != \"=\" {\n\t\treturn \"args error\"\n\t}\n\tev.globals[args[0].String(ev)] = args[2]\n\treturn \"\"\n}\n\nfunc implPut(ev *Evaluator, args []Value, ios [3]*io) string {\n\tout := ios[1].ch\n\tfor _, a := range args {\n\t\tout <- a\n\t}\n\tclose(out)\n\treturn \"\"\n}\n\nfunc implPrint(ev *Evaluator, args []Value, ios [3]*io) string {\n\tout := ios[1].f\n\tfor _, a := range args {\n\t\tfmt.Fprint(out, a.String(ev))\n\t}\n\treturn \"\"\n}\n\nfunc implPrintln(ev *Evaluator, args []Value, ios [3]*io) string {\n\targs = append(args, NewScalar(\"\\n\"))\n\treturn implPrint(ev, args, ios)\n}\n\nfunc implPrintchan(ev *Evaluator, args []Value, ios [3]*io) string {\n\tif len(args) > 0 {\n\t\treturn \"args error\"\n\t}\n\tin := ios[0].ch\n\tout := ios[1].f\n\n\tfor s := range in {\n\t\tfmt.Fprintf(out, \"%q\\n\", s)\n\t}\n\treturn \"\"\n}\n<commit_msg>Add builtin `fn`, for defining function<commit_after>package eval\n\nimport (\n\t\"fmt\"\n)\n\ntype ioType byte\n\nconst (\n\tfileIO ioType = iota \/\/ Default IO type. Corresponds to io.f.\n\tchanIO \/\/ Corresponds to io.ch.\n\tunusedIO\n)\n\ntype builtinFunc func(*Evaluator, []Value, [3]*io) string\n\ntype builtin struct {\n\tfn builtinFunc\n\tioTypes [3]ioType\n}\n\nvar builtins = map[string]builtin {\n\t\"set\": builtin{implSet, [3]ioType{unusedIO, unusedIO}},\n\t\"fn\": builtin{implFn, [3]ioType{unusedIO, unusedIO}},\n\t\"put\": builtin{implPut, [3]ioType{unusedIO, chanIO}},\n\t\"print\": builtin{implPrint, [3]ioType{unusedIO}},\n\t\"println\": builtin{implPrintln, [3]ioType{unusedIO}},\n\t\"printchan\": builtin{implPrintchan, [3]ioType{chanIO, fileIO}},\n}\n\nfunc doSet(ev *Evaluator, name Value, value Value) string {\n\t\/\/ TODO Support setting locals\n\t\/\/ TODO Prevent overriding builtin variables e.g. $pid $env\n\tev.globals[name.String(ev)] = value\n\treturn \"\"\n}\n\nfunc implSet(ev *Evaluator, args []Value, ios [3]*io) string {\n\tif len(args) != 3 || args[1].String(ev) != \"=\" {\n\t\treturn \"args error\"\n\t}\n\treturn doSet(ev, args[0], args[2])\n}\n\nfunc implFn(ev *Evaluator, args []Value, ios [3]*io) string {\n\t\/\/ TODO Support `fn f a b c { cmd }` as sugar for `fn f { | a b c | cmd }`\n\tif len(args) != 2 {\n\t\treturn \"args error\"\n\t}\n\tif _, ok := args[1].(*Closure); !ok {\n\t\treturn \"args error\"\n\t}\n\treturn doSet(ev, args[0], args[1])\n}\n\nfunc implPut(ev *Evaluator, args []Value, ios [3]*io) string {\n\tout := ios[1].ch\n\tfor _, a := range args {\n\t\tout <- a\n\t}\n\tclose(out)\n\treturn \"\"\n}\n\nfunc implPrint(ev *Evaluator, args []Value, ios [3]*io) string {\n\tout := ios[1].f\n\tfor _, a := range args {\n\t\tfmt.Fprint(out, a.String(ev))\n\t}\n\treturn \"\"\n}\n\nfunc implPrintln(ev *Evaluator, args []Value, ios [3]*io) string {\n\targs = append(args, NewScalar(\"\\n\"))\n\treturn implPrint(ev, args, ios)\n}\n\nfunc implPrintchan(ev *Evaluator, args []Value, ios [3]*io) string {\n\tif len(args) > 0 {\n\t\treturn \"args error\"\n\t}\n\tin := ios[0].ch\n\tout := ios[1].f\n\n\tfor s := range in {\n\t\tfmt.Fprintf(out, \"%q\\n\", s)\n\t}\n\treturn \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package eval\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar ErrArityMismatch = errors.New(\"arity mismatch\")\n\nvar unnamedRestArg = \":\"\n\n\/\/ Closure is a closure defined in elvish script.\ntype Closure struct {\n\tArgNames []string\n\t\/\/ The name for the rest argument. If empty, the function has fixed arity.\n\t\/\/ If equal to unnamedRestArg, the rest argument is unnamed but can be\n\t\/\/ accessed via $args.\n\tRestArg  string\n\tOp       Op\n\tCaptured map[string]Variable\n}\n\nfunc (*Closure) Kind() string {\n\treturn \"fn\"\n}\n\nfunc newClosure(a []string, r string, op Op, e map[string]Variable) *Closure {\n\treturn &Closure{a, r, op, e}\n}\n\nfunc (c *Closure) Repr(int) string {\n\treturn fmt.Sprintf(\"<Closure%v>\", *c)\n}\n\n\/\/ Call calls a closure.\nfunc (c *Closure) Call(ec *EvalCtx, args []Value) {\n\t\/\/ TODO Support keyword arguments\n\tif c.RestArg != \"\" {\n\t\tif len(c.ArgNames) > len(args) {\n\t\t\tthrow(ErrArityMismatch)\n\t\t}\n\t} else {\n\t\tif len(c.ArgNames) != len(args) {\n\t\t\tthrow(ErrArityMismatch)\n\t\t}\n\t}\n\n\t\/\/ This evalCtx is dedicated to the current form, so we modify it in place.\n\t\/\/ BUG(xiaq): When evaluating closures, async access to global variables\n\t\/\/ and ports can be problematic.\n\n\t\/\/ Make upvalue namespace and capture variables.\n\tec.up = make(map[string]Variable)\n\tfor name, variable := range c.Captured {\n\t\tec.up[name] = variable\n\t}\n\t\/\/ Make local namespace and pass arguments.\n\tec.local = make(map[string]Variable)\n\tfor i, name := range c.ArgNames {\n\t\tec.local[name] = NewPtrVariable(args[i])\n\t}\n\tif c.RestArg != \"\" && c.RestArg != unnamedRestArg {\n\t\tec.local[c.RestArg] = NewPtrVariable(NewList(args[len(c.ArgNames):]...))\n\t}\n\tLogger.Printf(\"EvalCtx=%p, args=%v\", ec, args)\n\tec.positionals = args\n\tec.local[\"args\"] = NewPtrVariable(List{&args})\n\tec.local[\"kwargs\"] = NewPtrVariable(Map{&map[Value]Value{}})\n\n\t\/\/ TODO(xiaq): Also change ec.name and ec.text since the closure being\n\t\/\/ called can come from another source.\n\n\tc.Op.Exec(ec)\n}\n<commit_msg>Slightly prettier Repr of closure.<commit_after>package eval\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar ErrArityMismatch = errors.New(\"arity mismatch\")\n\nvar unnamedRestArg = \"@\"\n\n\/\/ Closure is a closure defined in elvish script.\ntype Closure struct {\n\tArgNames []string\n\t\/\/ The name for the rest argument. If empty, the function has fixed arity.\n\t\/\/ If equal to unnamedRestArg, the rest argument is unnamed but can be\n\t\/\/ accessed via $args.\n\tRestArg  string\n\tOp       Op\n\tCaptured map[string]Variable\n}\n\nfunc (*Closure) Kind() string {\n\treturn \"fn\"\n}\n\nfunc newClosure(a []string, r string, op Op, e map[string]Variable) *Closure {\n\treturn &Closure{a, r, op, e}\n}\n\nfunc (c *Closure) Repr(int) string {\n\treturn fmt.Sprintf(\"<closure%v>\", *c)\n}\n\n\/\/ Call calls a closure.\nfunc (c *Closure) Call(ec *EvalCtx, args []Value) {\n\t\/\/ TODO Support keyword arguments\n\tif c.RestArg != \"\" {\n\t\tif len(c.ArgNames) > len(args) {\n\t\t\tthrow(ErrArityMismatch)\n\t\t}\n\t} else {\n\t\tif len(c.ArgNames) != len(args) {\n\t\t\tthrow(ErrArityMismatch)\n\t\t}\n\t}\n\n\t\/\/ This evalCtx is dedicated to the current form, so we modify it in place.\n\t\/\/ BUG(xiaq): When evaluating closures, async access to global variables\n\t\/\/ and ports can be problematic.\n\n\t\/\/ Make upvalue namespace and capture variables.\n\tec.up = make(map[string]Variable)\n\tfor name, variable := range c.Captured {\n\t\tec.up[name] = variable\n\t}\n\t\/\/ Make local namespace and pass arguments.\n\tec.local = make(map[string]Variable)\n\tfor i, name := range c.ArgNames {\n\t\tec.local[name] = NewPtrVariable(args[i])\n\t}\n\tif c.RestArg != \"\" && c.RestArg != unnamedRestArg {\n\t\tec.local[c.RestArg] = NewPtrVariable(NewList(args[len(c.ArgNames):]...))\n\t}\n\tLogger.Printf(\"EvalCtx=%p, args=%v\", ec, args)\n\tec.positionals = args\n\tec.local[\"args\"] = NewPtrVariable(List{&args})\n\tec.local[\"kwargs\"] = NewPtrVariable(Map{&map[Value]Value{}})\n\n\t\/\/ TODO(xiaq): Also change ec.name and ec.text since the closure being\n\t\/\/ called can come from another source.\n\n\tc.Op.Exec(ec)\n}\n<|endoftext|>"}
{"text":"<commit_before>package audru\n\nimport (\n\t\"testing\"\n)\n\nfunc TestWriterManager(t *testing.T) {\n\tpiper, err := NewWriterManager(2, \"\")\n\n\tif err != nil {\n\t\tt.FailNow()\n\t}\n\tw, err := piper.NewWriter()\n\tif err != nil {\n\t\tt.FailNow()\n\t}\n\tw.Write([]byte(\"hello\"))\n}\n<commit_msg>Concurrent test added<commit_after>package audru\n\nimport (\n\t\"sync\"\n\t\"testing\"\n)\n\nfunc TestWriterManager(t *testing.T) {\n\tpiper, err := NewWriterManager(2, \"\")\n\n\tif err != nil {\n\t\tt.FailNow()\n\t}\n\n\tvar wg sync.WaitGroup\n\n\tfor i := 0; i < 4; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tw, err := piper.NewWriter()\n\t\t\tif err != nil {\n\t\t\t\tt.FailNow()\n\t\t\t}\n\t\t\tw.Write([]byte(\"hello\"))\n\t\t}()\n\t}\n\twg.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 tsuru-autoscale authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/tsuru\/tsuru-autoscale\/db\"\n\t\"github.com\/tsuru\/tsuru\/log\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\nfunc StartAutoScale() {\n\tgo runAutoScale()\n}\n\n\/\/ Event represents an auto scale event with\n\/\/ the scale metadata.\ntype Event struct {\n\tID         bson.ObjectId `bson:\"_id\"`\n\tStartTime  time.Time\n\tEndTime    time.Time `bson:\",omitempty\"`\n\tConfig     *Config\n\tType       string\n\tSuccessful bool\n\tError      string `bson:\",omitempty\"`\n}\n\nfunc NewEvent(config *Config, scaleType string) (*Event, error) {\n\tevt := Event{\n\t\tID:        bson.NewObjectId(),\n\t\tStartTime: time.Now().UTC(),\n\t\tConfig:    config,\n\t\tType:      scaleType,\n\t}\n\tconn, err := db.Conn()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\treturn &evt, conn.AutoScale().Insert(evt)\n}\n\nfunc (evt *Event) update(err error) error {\n\tif err != nil {\n\t\tevt.Error = err.Error()\n\t}\n\tevt.Successful = err == nil\n\tevt.EndTime = time.Now().UTC()\n\tconn, err := db.Conn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\treturn conn.AutoScale().UpdateId(evt.ID, evt)\n}\n\n\/\/ Action represents an AutoScale action to increase or decrease the\n\/\/ number of the units.\ntype Action struct {\n\tWait       time.Duration `json:\"wait\"`\n\tExpression string        `json:\"expression\"`\n\tUnits      uint          `json:\"units\"`\n}\n\nfunc NewAction(expression string, units uint, wait time.Duration) (*Action, error) {\n\tif expressionIsValid(expression) {\n\t\treturn &Action{Wait: wait, Expression: expression, Units: units}, nil\n\t}\n\treturn nil, errors.New(\"Expression is not valid.\")\n}\n\nvar expressionRegex = regexp.MustCompile(\"{(.*)} ([><=]) ([0-9]+)\")\n\nfunc expressionIsValid(expression string) bool {\n\treturn expressionRegex.MatchString(expression)\n}\n\nfunc (action *Action) metric() string {\n\treturn expressionRegex.FindStringSubmatch(action.Expression)[1]\n}\n\nfunc (action *Action) operator() string {\n\treturn expressionRegex.FindStringSubmatch(action.Expression)[2]\n}\n\nfunc (action *Action) value() (float64, error) {\n\treturn strconv.ParseFloat(expressionRegex.FindStringSubmatch(action.Expression)[3], 64)\n}\n\n\/\/ Config represents the configuration for the auto scale.\ntype Config struct {\n\tName     string `json:\"increase\"`\n\tIncrease Action `json:\"increase\"`\n\tDecrease Action `json:\"decrease\"`\n\tMinUnits uint   `json:\"minUnits\"`\n\tMaxUnits uint   `json:\"maxUnits\"`\n\tEnabled  bool   `json:\"enabled\"`\n}\n\ntype App struct {\n\tName string\n}\n\nfunc (a *App) Units() []string {\n\treturn nil\n}\n\nfunc (a *App) Metric(kind string) (float64, error) {\n\treturn float64(0), nil\n}\n\nfunc (a *App) AddUnits(n uint, writer io.Writer) error {\n\treturn nil\n}\n\nfunc (a *App) RemoveUnits(n uint) error {\n\treturn nil\n}\n\nfunc runAutoScaleOnce() {\n\tconfigs := []Config{}\n\tfor _, config := range configs {\n\t\terr := scaleIfNeeded(&config)\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t}\n\t}\n}\n\nfunc runAutoScale() {\n\tfor {\n\t\trunAutoScaleOnce()\n\t\ttime.Sleep(30 * time.Second)\n\t}\n}\n\nfunc scaleIfNeeded(config *Config) error {\n\tif config == nil {\n\t\treturn errors.New(\"AutoScale is not configured.\")\n\t}\n\t\/*\n\t\tincreaseMetric, _ := app.Metric(config.Increase.metric())\n\t\tvalue, _ := config.Increase.value()\n\t\tif increaseMetric > value {\n\t\t\tcurrentUnits := uint(len(app.Units()))\n\t\t\tmaxUnits := config.MaxUnits\n\t\t\tif maxUnits == 0 {\n\t\t\t\tmaxUnits = 1\n\t\t\t}\n\t\t\tif currentUnits >= maxUnits {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif wait, err := shouldWait(app, config.Increase.Wait); err != nil {\n\t\t\t\treturn err\n\t\t\t} else if wait {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tevt, err := NewEvent(app, \"increase\")\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error trying to insert auto scale event, auto scale aborted: %s\", err.Error())\n\t\t \t}\n\t\t\tinc := config.Increase.Units\n\t\t\tif currentUnits+inc > config.MaxUnits {\n\t\t\t\tinc = config.MaxUnits - currentUnits\n\t\t\t}\n\t\t\taddUnitsErr := app.AddUnits(inc, nil)\n\t\t\terr = evt.update(addUnitsErr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error trying to update auto scale event: %s\", err.Error())\n\t\t\t}\n\t\t\treturn addUnitsErr\n\t\t}\n\t\tdecreaseMetric, _ := app.Metric(config.Decrease.metric())\n\t\tvalue, _ = config.Decrease.value()\n\t\tif decreaseMetric < value {\n\t\t\tcurrentUnits := uint(len(app.Units()))\n\t\t\tminUnits := config.MinUnits\n\t\t\tif minUnits == 0 {\n\t\t\t\tminUnits = 1\n\t\t\t}\n\t\t\tif currentUnits <= minUnits {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif wait, err := shouldWait(app, config.Decrease.Wait); err != nil {\n\t\t\t\treturn err\n\t\t\t} else if wait {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tevt, err := NewEvent(app, \"decrease\")\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error trying to insert auto scale event, auto scale aborted: %s\", err.Error())\n\t\t\t}\n\t\t\tdec := config.Decrease.Units\n\t\t\tif currentUnits-dec < config.MinUnits {\n\t\t\t\tdec = currentUnits - config.MinUnits\n\t\t\t}\n\t\t\tremoveUnitsErr := app.RemoveUnits(dec)\n\t\t\terr = evt.update(removeUnitsErr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error trying to update auto scale event: %s\", err.Error())\n\t\t\t}\n\t\t\treturn removeUnitsErr\n\t\t}\n\t*\/\n\treturn nil\n}\n\nfunc shouldWait(app *App, waitPeriod time.Duration) (bool, error) {\n\tnow := time.Now().UTC()\n\tlastEvent, err := lastScaleEvent(app.Name)\n\tif err != nil && err != mgo.ErrNotFound {\n\t\treturn false, err\n\t}\n\tif err != mgo.ErrNotFound && lastEvent.EndTime.IsZero() {\n\t\treturn true, nil\n\t}\n\tdiff := now.Sub(lastEvent.EndTime)\n\tif diff > waitPeriod {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}\n\nfunc lastScaleEvent(appName string) (Event, error) {\n\tvar event Event\n\tconn, err := db.Conn()\n\tif err != nil {\n\t\treturn event, err\n\t}\n\tdefer conn.Close()\n\terr = conn.AutoScale().Find(bson.M{\"appname\": appName}).Sort(\"-starttime\").One(&event)\n\treturn event, err\n}\n\nfunc ListAutoScaleHistory(appName string) ([]Event, error) {\n\tconn, err := db.Conn()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\tvar history []Event\n\tq := bson.M{}\n\tif appName != \"\" {\n\t\tq[\"appname\"] = appName\n\t}\n\terr = conn.AutoScale().Find(q).Sort(\"-_id\").Limit(200).All(&history)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn history, nil\n}\n\nfunc AutoScaleEnable(config *Config) error {\n\tconfig.Enabled = true\n\treturn nil\n}\n\nfunc AutoScaleDisable(config *Config) error {\n\tconfig.Enabled = false\n\treturn nil\n}\n<commit_msg>remove unused App struct<commit_after>\/\/ Copyright 2015 tsuru-autoscale authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/tsuru\/tsuru-autoscale\/db\"\n\t\"github.com\/tsuru\/tsuru\/log\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\nfunc StartAutoScale() {\n\tgo runAutoScale()\n}\n\n\/\/ Event represents an auto scale event with\n\/\/ the scale metadata.\ntype Event struct {\n\tID         bson.ObjectId `bson:\"_id\"`\n\tStartTime  time.Time\n\tEndTime    time.Time `bson:\",omitempty\"`\n\tConfig     *Config\n\tType       string\n\tSuccessful bool\n\tError      string `bson:\",omitempty\"`\n}\n\nfunc NewEvent(config *Config, scaleType string) (*Event, error) {\n\tevt := Event{\n\t\tID:        bson.NewObjectId(),\n\t\tStartTime: time.Now().UTC(),\n\t\tConfig:    config,\n\t\tType:      scaleType,\n\t}\n\tconn, err := db.Conn()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\treturn &evt, conn.AutoScale().Insert(evt)\n}\n\nfunc (evt *Event) update(err error) error {\n\tif err != nil {\n\t\tevt.Error = err.Error()\n\t}\n\tevt.Successful = err == nil\n\tevt.EndTime = time.Now().UTC()\n\tconn, err := db.Conn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\treturn conn.AutoScale().UpdateId(evt.ID, evt)\n}\n\n\/\/ Action represents an AutoScale action to increase or decrease the\n\/\/ number of the units.\ntype Action struct {\n\tWait       time.Duration `json:\"wait\"`\n\tExpression string        `json:\"expression\"`\n\tUnits      uint          `json:\"units\"`\n}\n\nfunc NewAction(expression string, units uint, wait time.Duration) (*Action, error) {\n\tif expressionIsValid(expression) {\n\t\treturn &Action{Wait: wait, Expression: expression, Units: units}, nil\n\t}\n\treturn nil, errors.New(\"Expression is not valid.\")\n}\n\nvar expressionRegex = regexp.MustCompile(\"{(.*)} ([><=]) ([0-9]+)\")\n\nfunc expressionIsValid(expression string) bool {\n\treturn expressionRegex.MatchString(expression)\n}\n\nfunc (action *Action) metric() string {\n\treturn expressionRegex.FindStringSubmatch(action.Expression)[1]\n}\n\nfunc (action *Action) operator() string {\n\treturn expressionRegex.FindStringSubmatch(action.Expression)[2]\n}\n\nfunc (action *Action) value() (float64, error) {\n\treturn strconv.ParseFloat(expressionRegex.FindStringSubmatch(action.Expression)[3], 64)\n}\n\n\/\/ Config represents the configuration for the auto scale.\ntype Config struct {\n\tName     string `json:\"increase\"`\n\tIncrease Action `json:\"increase\"`\n\tDecrease Action `json:\"decrease\"`\n\tMinUnits uint   `json:\"minUnits\"`\n\tMaxUnits uint   `json:\"maxUnits\"`\n\tEnabled  bool   `json:\"enabled\"`\n}\n\nfunc runAutoScaleOnce() {\n\tconfigs := []Config{}\n\tfor _, config := range configs {\n\t\terr := scaleIfNeeded(&config)\n\t\tif err != nil {\n\t\t\tlog.Error(err.Error())\n\t\t}\n\t}\n}\n\nfunc runAutoScale() {\n\tfor {\n\t\trunAutoScaleOnce()\n\t\ttime.Sleep(30 * time.Second)\n\t}\n}\n\nfunc scaleIfNeeded(config *Config) error {\n\tif config == nil {\n\t\treturn errors.New(\"AutoScale is not configured.\")\n\t}\n\t\/*\n\t\tincreaseMetric, _ := app.Metric(config.Increase.metric())\n\t\tvalue, _ := config.Increase.value()\n\t\tif increaseMetric > value {\n\t\t\tcurrentUnits := uint(len(app.Units()))\n\t\t\tmaxUnits := config.MaxUnits\n\t\t\tif maxUnits == 0 {\n\t\t\t\tmaxUnits = 1\n\t\t\t}\n\t\t\tif currentUnits >= maxUnits {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif wait, err := shouldWait(app, config.Increase.Wait); err != nil {\n\t\t\t\treturn err\n\t\t\t} else if wait {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tevt, err := NewEvent(app, \"increase\")\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error trying to insert auto scale event, auto scale aborted: %s\", err.Error())\n\t\t \t}\n\t\t\tinc := config.Increase.Units\n\t\t\tif currentUnits+inc > config.MaxUnits {\n\t\t\t\tinc = config.MaxUnits - currentUnits\n\t\t\t}\n\t\t\taddUnitsErr := app.AddUnits(inc, nil)\n\t\t\terr = evt.update(addUnitsErr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error trying to update auto scale event: %s\", err.Error())\n\t\t\t}\n\t\t\treturn addUnitsErr\n\t\t}\n\t\tdecreaseMetric, _ := app.Metric(config.Decrease.metric())\n\t\tvalue, _ = config.Decrease.value()\n\t\tif decreaseMetric < value {\n\t\t\tcurrentUnits := uint(len(app.Units()))\n\t\t\tminUnits := config.MinUnits\n\t\t\tif minUnits == 0 {\n\t\t\t\tminUnits = 1\n\t\t\t}\n\t\t\tif currentUnits <= minUnits {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif wait, err := shouldWait(app, config.Decrease.Wait); err != nil {\n\t\t\t\treturn err\n\t\t\t} else if wait {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tevt, err := NewEvent(app, \"decrease\")\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error trying to insert auto scale event, auto scale aborted: %s\", err.Error())\n\t\t\t}\n\t\t\tdec := config.Decrease.Units\n\t\t\tif currentUnits-dec < config.MinUnits {\n\t\t\t\tdec = currentUnits - config.MinUnits\n\t\t\t}\n\t\t\tremoveUnitsErr := app.RemoveUnits(dec)\n\t\t\terr = evt.update(removeUnitsErr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error trying to update auto scale event: %s\", err.Error())\n\t\t\t}\n\t\t\treturn removeUnitsErr\n\t\t}\n\t*\/\n\treturn nil\n}\n\nfunc shouldWait(config *Config, waitPeriod time.Duration) (bool, error) {\n\tnow := time.Now().UTC()\n\tlastEvent, err := lastScaleEvent(config.Name)\n\tif err != nil && err != mgo.ErrNotFound {\n\t\treturn false, err\n\t}\n\tif err != mgo.ErrNotFound && lastEvent.EndTime.IsZero() {\n\t\treturn true, nil\n\t}\n\tdiff := now.Sub(lastEvent.EndTime)\n\tif diff > waitPeriod {\n\t\treturn false, nil\n\t}\n\treturn true, nil\n}\n\nfunc lastScaleEvent(appName string) (Event, error) {\n\tvar event Event\n\tconn, err := db.Conn()\n\tif err != nil {\n\t\treturn event, err\n\t}\n\tdefer conn.Close()\n\terr = conn.AutoScale().Find(bson.M{\"appname\": appName}).Sort(\"-starttime\").One(&event)\n\treturn event, err\n}\n\nfunc ListAutoScaleHistory(appName string) ([]Event, error) {\n\tconn, err := db.Conn()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer conn.Close()\n\tvar history []Event\n\tq := bson.M{}\n\tif appName != \"\" {\n\t\tq[\"appname\"] = appName\n\t}\n\terr = conn.AutoScale().Find(q).Sort(\"-_id\").Limit(200).All(&history)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn history, nil\n}\n\nfunc AutoScaleEnable(config *Config) error {\n\tconfig.Enabled = true\n\treturn nil\n}\n\nfunc AutoScaleDisable(config *Config) error {\n\tconfig.Enabled = false\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"log\"\n\n\t\"github.com\/zserge\/hid\"\n)\n\nfunc main() {\n\thid.UsbWalk(func(device hid.Device) {\n\t\tlog.Printf(\"%+v\\n\", device.Info())\n\t\tif err := device.Open(); err != nil {\n\t\t\tlog.Println(\"Open error: \", err)\n\t\t\treturn\n\t\t}\n\t\tdefer device.Close()\n\n\t\tlog.Println(device.HIDReport())\n\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tlog.Println(device.Read(8, 0))\n\t\t}\n\t})\n}\n<commit_msg>added interactive shell<commit_after>package main\n\nimport (\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/peterh\/liner\"\n\t\"github.com\/zserge\/hid\"\n)\n\nfunc shell(device hid.Device, inputReportSize int) {\n\tif err := device.Open(); err != nil {\n\t\tfmt.Println(\"Open error: \", err)\n\t\treturn\n\t}\n\tdefer device.Close()\n\n\tif report, err := device.HIDReport(); err != nil {\n\t\tfmt.Println(\"HID report error:\", err)\n\t\treturn\n\t} else {\n\t\tfmt.Println(\"HID report\", hex.EncodeToString(report))\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tif buf, err := device.Read(inputReportSize, 1*time.Second); err == nil {\n\t\t\t\tfmt.Println(\"\\rInput report:  \", hex.EncodeToString(buf))\n\t\t\t\tsyscall.Kill(syscall.Getpid(), syscall.SIGWINCH)\n\t\t\t}\n\t\t}\n\t}()\n\n\tcommands := map[string]func([]byte){\n\t\t\"output\": func(b []byte) {\n\t\t\tif len(b) == 0 {\n\t\t\t\tfmt.Println(\"Invalid input: output report data expected\")\n\t\t\t} else if n, err := device.Write(b, 1*time.Second); err != nil {\n\t\t\t\tfmt.Println(\"Output report write failed:\", err)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Output report: written %d bytes\\n\", n)\n\t\t\t}\n\t\t},\n\t\t\"set-feature\": func(b []byte) {\n\t\t\tif len(b) == 0 {\n\t\t\t\tfmt.Println(\"Invalid input: feature report data expected\")\n\t\t\t} else if err := device.SetReport(0, b); err != nil {\n\t\t\t\tfmt.Println(\"Feature report write failed:\", err)\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"Feature report: \" + hex.EncodeToString(b) + \"\\n\")\n\t\t\t}\n\t\t},\n\t\t\"get-feature\": func(b []byte) {\n\t\t\tif b, err := device.GetReport(0); err != nil {\n\t\t\t\tfmt.Println(\"Feature report read failed:\", err)\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Feature report: \" + hex.EncodeToString(b) + \"\\n\")\n\t\t\t}\n\t\t},\n\t}\n\n\tline := liner.NewLiner()\n\tdefer line.Close()\n\tline.SetCtrlCAborts(true)\n\tline.SetCompleter(func(line string) (c []string) {\n\t\tfor cmd, _ := range commands {\n\t\t\tif strings.HasPrefix(cmd, strings.ToLower(line)) {\n\t\t\t\tc = append(c, cmd+\" \")\n\t\t\t}\n\t\t}\n\t\treturn\n\t})\n\nout:\n\tfor {\n\t\tif s, err := line.Prompt(\"$ \"); err == nil {\n\t\t\tif len(s) > 0 {\n\t\t\t\tline.AppendHistory(s)\n\t\t\t\ts = strings.ToLower(s)\n\t\t\t\tfor cmd, f := range commands {\n\t\t\t\t\tif strings.HasPrefix(s, cmd) {\n\t\t\t\t\t\ts = strings.TrimSpace(s[len(cmd):])\n\t\t\t\t\t\traw := []byte{}\n\t\t\t\t\t\tif len(s) > 0 {\n\t\t\t\t\t\t\traw = make([]byte, len(s)\/2, len(s)\/2)\n\t\t\t\t\t\t\tif _, err := hex.Decode(raw, []byte(s)); err != nil {\n\t\t\t\t\t\t\t\tfmt.Println(\"Invalid input:\", err)\n\t\t\t\t\t\t\t\tfmt.Println(\">>\", hex.EncodeToString(raw))\n\t\t\t\t\t\t\t\tcontinue out\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tf(raw)\n\t\t\t\t\t\tcontinue out\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif err != liner.ErrPromptAborted {\n\t\t\t\tfmt.Println(\"Input error:\", err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc main() {\n\n\tif len(os.Args) == 2 && (os.Args[1] == \"-h\" || os.Args[1] == \"--help\") {\n\t\tfmt.Println(\"USAGE:\")\n\t\tfmt.Printf(\"  %s                list USB HID devices\\n\", os.Args[0])\n\t\tfmt.Printf(\"  %s <id> [size]    open USB HID device shell for the given input report size\\n\", os.Args[0])\n\t\tfmt.Printf(\"  %s -h|--help      show this help\\n\", os.Args[0])\n\t\tfmt.Println()\n\t\treturn\n\t}\n\n\t\/\/ Without arguments - enumerate all HID devices\n\tif len(os.Args) == 1 {\n\t\tfound := false\n\t\thid.UsbWalk(func(device hid.Device) {\n\t\t\tinfo := device.Info()\n\t\t\tfmt.Printf(\"%04x:%04x:%04x\\n\", info.Vendor, info.Product, info.Revision)\n\t\t\tfound = true\n\t\t})\n\t\tif !found {\n\t\t\tfmt.Println(\"No USB HID devices found\\n\")\n\t\t}\n\t\treturn\n\t}\n\n\tinputReportSize := 1\n\n\tif len(os.Args) > 2 {\n\t\tif n, err := strconv.Atoi(os.Args[2]); err == nil {\n\t\t\tinputReportSize = n\n\t\t} else {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\thid.UsbWalk(func(device hid.Device) {\n\t\tinfo := device.Info()\n\t\tid := fmt.Sprintf(\"%04x:%04x:%04x\", info.Vendor, info.Product, info.Revision)\n\t\tif id != os.Args[1] {\n\t\t\treturn\n\t\t}\n\n\t\tshell(device, inputReportSize)\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/DataDog\/dd-trace-go\/tracer\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/flachnetz\/dd-zipkin-proxy\"\n\t\"github.com\/openzipkin\/zipkin-go-opentracing\/_thrift\/gen-go\/zipkincore\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc main() {\n\tconverter := DefaultSpanConverter{}\n\tzipkinproxy.Main(converter.Convert)\n}\n\nvar reHash = regexp.MustCompile(\"\\\\b(?:[a-f0-9]{32}|[a-f0-9-]{8}-[a-f0-9-]{4}-[a-f0-9-]{4}-[a-f0-9-]{4}-[a-f0-9-]{12})\\\\b\")\nvar reNumber = regexp.MustCompile(\"\\\\b[0-9]{2,}\\\\b\")\nvar reIwgHash = regexp.MustCompile(\"iwg\\\\.[A-Za-z0-9]{12}\\\\b\")\n\nfunc SimplifyResourceName(value string) string {\n\t\/\/ check if we need to apply the regexp by checking if a match is possible or not\n\tdigitCount := 0\n\thashCharCount := 0\n\tfor _, char := range value {\n\t\tisDigit := char >= '0' && char <= '9'\n\t\tif isDigit {\n\t\t\tdigitCount++\n\t\t}\n\n\t\tif isDigit || char >= 'a' && char <= 'f' {\n\t\t\thashCharCount++\n\t\t}\n\t}\n\n\t\/\/ only search for hash, if we have enough chars for it\n\tif hashCharCount >= 32 {\n\t\tvalue = reHash.ReplaceAllString(value, \"_HASH_\")\n\t}\n\n\t\/\/ only replace numbers, if we have enough digits for a match\n\tif digitCount >= 2 {\n\t\tvalue = reNumber.ReplaceAllString(value, \"_NUMBER_\")\n\t}\n\n\tif strings.HasPrefix(value, \"iwg.\") {\n\t\tvalue = reIwgHash.ReplaceAllString(value, \"iwg._HASH_\")\n\t}\n\n\treturn value\n}\n\ntype DefaultSpanConverter struct {\n\tcurrent  map[uint64]string\n\tprevious map[uint64]string\n}\n\nfunc (converter *DefaultSpanConverter) Convert(span *zipkincore.Span) *tracer.Span {\n\tif span.Name == \"watch-config-key-values\" {\n\t\treturn nil\n\t}\n\n\tname := SimplifyResourceName(span.Name)\n\n\tconverted := &tracer.Span{\n\t\tSpanID:   uint64(span.ID),\n\t\tParentID: uint64(span.GetParentID()),\n\t\tTraceID:  uint64(span.TraceID),\n\t\tName:     name,\n\t\tResource: name,\n\t\tStart:    1000 * span.GetTimestamp(),\n\t\tDuration: 1000 * span.GetDuration(),\n\t\tSampled:  true,\n\t}\n\n\t\/\/ datadog traces use a trace of 0\n\tif converted.ParentID == converted.SpanID {\n\t\tconverted.ParentID = 0\n\t}\n\n\t\/\/ split \"http:\/some\/url\" or \"get:\/some\/url\"\n\tfor _, prefix := range []string{\"http:\/\", \"get:\/\", \"post:\/\"} {\n\t\tif strings.HasPrefix(converted.Name, prefix) {\n\t\t\tconverted.Resource = converted.Name[len(prefix)-1:]\n\t\t\tconverted.Name = prefix[:len(prefix)-2]\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/ convert binary annotations (like tags)\n\tif len(span.BinaryAnnotations) > 0 {\n\t\tconverted.Meta = make(map[string]string, len(span.BinaryAnnotations))\n\t\tfor _, an := range span.BinaryAnnotations {\n\t\t\tif an.AnnotationType == zipkincore.AnnotationType_STRING {\n\t\t\t\tkey := an.Key\n\n\t\t\t\t\/\/ rename keys to better match the datadog one.\n\t\t\t\tswitch key {\n\t\t\t\tcase \"http.status\":\n\t\t\t\t\tkey = \"http.status_code\"\n\n\t\t\t\tcase \"client.url\":\n\t\t\t\t\tkey = \"http.url\"\n\t\t\t\t}\n\n\t\t\t\tconverted.Meta[key] = string(an.Value)\n\t\t\t}\n\n\t\t\tif an.Host != nil && an.Host.ServiceName != \"\" {\n\t\t\t\tconverted.Service = an.Host.ServiceName\n\t\t\t}\n\t\t}\n\n\t\tif url := converted.Meta[\"http.url\"]; url != \"\" {\n\t\t\tconverted.Resource = SimplifyResourceName(url)\n\t\t}\n\n\t\tif status := converted.Meta[\"http.status_code\"]; status != \"\" {\n\t\t\tif len(status) > 0 && '3' <= status[0] && status[0] <= '9' {\n\t\t\t\tif statusValue, err := strconv.Atoi(status); err == nil && statusValue >= 400 {\n\t\t\t\t\tconverted.Error = int32(statusValue)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ try to get the service from the cs\/cr or sr\/ss annotations\n\tvar minTimestamp, maxTimestamp int64\n\tfor _, an := range span.Annotations {\n\t\tif an.Host != nil && an.Host.ServiceName != \"\" {\n\t\t\tif an.Value == \"sr\" {\n\t\t\t\tconverted.Service = an.Host.ServiceName\n\t\t\t}\n\t\t}\n\n\t\tif an.Timestamp < minTimestamp || minTimestamp == 0 {\n\t\t\tminTimestamp = an.Timestamp\n\t\t}\n\n\t\tif an.Timestamp > maxTimestamp {\n\t\t\tmaxTimestamp = an.Timestamp\n\t\t}\n\t}\n\n\tif converted.Start == 0 {\n\t\tconverted.Start = 1000 * minTimestamp\n\t\tconverted.Duration = 1000 * (maxTimestamp - minTimestamp)\n\t}\n\n\t\/\/ simplify some names\n\tif strings.HasPrefix(converted.Name, \"http:\") {\n\t\tconverted.Service = converted.Name[5:]\n\t}\n\n\tif converted.Name == \"transaction\" {\n\t\tconverted.Service = \"oracle\"\n\t}\n\n\tif sql := converted.Meta[\"sql\"]; sql != \"\" {\n\t\tdelete(converted.Meta, \"sql\")\n\t\tconverted.Service = \"sql\"\n\t\tconverted.Resource = sql\n\t}\n\n\tif strings.HasPrefix(converted.Name, \"redis:\") {\n\t\tconverted.Service = \"redis\"\n\n\t\tif key := converted.Meta[\"redis.key\"]; key != \"\" {\n\t\t\tconverted.Resource = SimplifyResourceName(key)\n\n\t\t\t\/\/ the hash is not really important later on. lets not spam datadog with it.\n\t\t\tdelete(converted.Meta, \"redis.key\")\n\t\t}\n\t}\n\n\tif converted.Service == \"core-services\" {\n\t\tif strings.Contains(converted.Meta[\"http.url\"], \":6080\/\") {\n\t\t\tconverted.Service = \"iwg-restrictor\"\n\t\t\tconverted.Name = iwgNameFromResource(converted.Resource, converted.Name)\n\t\t\tconverted.Resource = dropDomainFromUrl(converted.Resource)\n\t\t}\n\n\t\tif strings.Contains(converted.Meta[\"http.url\"], \":2080\/\") {\n\t\t\tconverted.Service = \"instant-win-game\"\n\t\t\tconverted.Name = \"iwg-game\"\n\t\t\tconverted.Resource = dropDomainFromUrl(converted.Resource)\n\t\t}\n\t}\n\n\t\/\/ If we could not get a service, we'll try to get it from the parent span.\n\t\/\/ Try first in the current map, then in the previous one.\n\tif converted.Service == \"\" {\n\t\tparentService := converter.current[converted.ParentID]\n\t\tif parentService != \"\" {\n\t\t\tconverted.Service = parentService\n\t\t} else {\n\t\t\tparentService = converter.previous[converted.ParentID]\n\t\t\tif parentService != \"\" {\n\t\t\t\tconverted.Service = parentService\n\t\t\t}\n\t\t}\n\n\t\t\/\/ if we did not get a service, use a fallback\n\t\tif converted.Service == \"\" {\n\t\t\tlogrus.Warnf(\"Could not get a service for this span: %+v\", span)\n\t\t\tconverted.Service = \"unknown\"\n\t\t}\n\t}\n\n\tif lc := converted.Meta[\"lc\"]; lc != \"\" {\n\t\tdelete(converted.Meta, \"lc\")\n\n\t\tif converted.Name == \"\" {\n\t\t\tconverted.Name = converted.Meta[\"lc\"]\n\t\t}\n\n\t\tif lc == \"consul\" {\n\t\t\tconverted.Service = \"consul\"\n\t\t}\n\t}\n\n\t\/\/ guess a type for the datadog ui.\n\tif converted.Name == \"transaction\" || converted.Service == \"redis\" {\n\t\tconverted.Type = \"db\"\n\t} else {\n\t\tconverted.Type = \"http\"\n\t}\n\n\tif converted.Name == \"hystrix\" {\n\t\tconverted.Resource = converted.Meta[\"thread\"]\n\t}\n\n\tif converted.Name == \"\" {\n\t\tlogrus.Warnf(\"Could not get a name for this span: %+v converted: %+v\", span, converted)\n\t}\n\n\t\/\/ initialize history maps for span -> parent assignment\n\tif len(converter.current) >= 40000 || converter.current == nil {\n\t\tconverter.previous = converter.current\n\t\tconverter.current = make(map[uint64]string, 40000)\n\t}\n\n\t\/\/ remember the service for a short while\n\tconverter.current[converted.SpanID] = converted.Service\n\n\treturn converted\n}\n\nfunc dropDomainFromUrl(url string) string {\n\tswitch {\n\tcase strings.HasPrefix(url, \"http:\/\/\"):\n\t\tindex := strings.IndexRune(url[7:], '\/')\n\t\treturn url[7+index:]\n\n\tcase strings.HasPrefix(url, \"https:\/\/\"):\n\t\tindex := strings.IndexRune(url[8:], '\/')\n\t\treturn url[8+index:]\n\t}\n\n\treturn url\n}\n\nfunc iwgNameFromResource(resource string, fallback string) string {\n\tsplittedUrl := strings.Split(strings.Trim(resource, \"\/\"), \"\/\")\n\tif len(splittedUrl) == 1 && splittedUrl[0] != \"\" {\n\t\treturn splittedUrl[0]\n\t} else if len(splittedUrl) > 1 {\n\t\treturn splittedUrl[len(splittedUrl)-2] + \"\/\" + splittedUrl[len(splittedUrl)-1]\n\t}\n\treturn fallback\n}\n<commit_msg>Use local component as service name.<commit_after>package main\n\nimport (\n\t\"github.com\/DataDog\/dd-trace-go\/tracer\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/flachnetz\/dd-zipkin-proxy\"\n\t\"github.com\/openzipkin\/zipkin-go-opentracing\/_thrift\/gen-go\/zipkincore\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc main() {\n\tconverter := DefaultSpanConverter{}\n\tzipkinproxy.Main(converter.Convert)\n}\n\nvar reHash = regexp.MustCompile(\"\\\\b(?:[a-f0-9]{32}|[a-f0-9-]{8}-[a-f0-9-]{4}-[a-f0-9-]{4}-[a-f0-9-]{4}-[a-f0-9-]{12})\\\\b\")\nvar reNumber = regexp.MustCompile(\"\\\\b[0-9]{2,}\\\\b\")\nvar reIwgHash = regexp.MustCompile(\"iwg\\\\.[A-Za-z0-9]{12}\\\\b\")\n\nfunc SimplifyResourceName(value string) string {\n\t\/\/ check if we need to apply the regexp by checking if a match is possible or not\n\tdigitCount := 0\n\thashCharCount := 0\n\tfor _, char := range value {\n\t\tisDigit := char >= '0' && char <= '9'\n\t\tif isDigit {\n\t\t\tdigitCount++\n\t\t}\n\n\t\tif isDigit || char >= 'a' && char <= 'f' {\n\t\t\thashCharCount++\n\t\t}\n\t}\n\n\t\/\/ only search for hash, if we have enough chars for it\n\tif hashCharCount >= 32 {\n\t\tvalue = reHash.ReplaceAllString(value, \"_HASH_\")\n\t}\n\n\t\/\/ only replace numbers, if we have enough digits for a match\n\tif digitCount >= 2 {\n\t\tvalue = reNumber.ReplaceAllString(value, \"_NUMBER_\")\n\t}\n\n\tif strings.HasPrefix(value, \"iwg.\") {\n\t\tvalue = reIwgHash.ReplaceAllString(value, \"iwg._HASH_\")\n\t}\n\n\treturn value\n}\n\ntype DefaultSpanConverter struct {\n\tcurrent  map[uint64]string\n\tprevious map[uint64]string\n}\n\nfunc (converter *DefaultSpanConverter) Convert(span *zipkincore.Span) *tracer.Span {\n\tif span.Name == \"watch-config-key-values\" {\n\t\treturn nil\n\t}\n\n\tname := SimplifyResourceName(span.Name)\n\n\tconverted := &tracer.Span{\n\t\tSpanID:   uint64(span.ID),\n\t\tParentID: uint64(span.GetParentID()),\n\t\tTraceID:  uint64(span.TraceID),\n\t\tName:     name,\n\t\tResource: name,\n\t\tStart:    1000 * span.GetTimestamp(),\n\t\tDuration: 1000 * span.GetDuration(),\n\t\tSampled:  true,\n\t}\n\n\t\/\/ datadog traces use a trace of 0\n\tif converted.ParentID == converted.SpanID {\n\t\tconverted.ParentID = 0\n\t}\n\n\t\/\/ split \"http:\/some\/url\" or \"get:\/some\/url\"\n\tfor _, prefix := range []string{\"http:\/\", \"get:\/\", \"post:\/\"} {\n\t\tif strings.HasPrefix(converted.Name, prefix) {\n\t\t\tconverted.Resource = converted.Name[len(prefix)-1:]\n\t\t\tconverted.Name = prefix[:len(prefix)-2]\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/ convert binary annotations (like tags)\n\tif len(span.BinaryAnnotations) > 0 {\n\t\tconverted.Meta = make(map[string]string, len(span.BinaryAnnotations))\n\t\tfor _, an := range span.BinaryAnnotations {\n\t\t\tif an.AnnotationType == zipkincore.AnnotationType_STRING {\n\t\t\t\tkey := an.Key\n\n\t\t\t\t\/\/ rename keys to better match the datadog one.\n\t\t\t\tswitch key {\n\t\t\t\tcase \"http.status\":\n\t\t\t\t\tkey = \"http.status_code\"\n\n\t\t\t\tcase \"client.url\":\n\t\t\t\t\tkey = \"http.url\"\n\t\t\t\t}\n\n\t\t\t\tconverted.Meta[key] = string(an.Value)\n\t\t\t}\n\n\t\t\tif an.Host != nil && an.Host.ServiceName != \"\" {\n\t\t\t\tconverted.Service = an.Host.ServiceName\n\t\t\t}\n\t\t}\n\n\t\tif url := converted.Meta[\"http.url\"]; url != \"\" {\n\t\t\tconverted.Resource = SimplifyResourceName(url)\n\t\t}\n\n\t\tif status := converted.Meta[\"http.status_code\"]; status != \"\" {\n\t\t\tif len(status) > 0 && '3' <= status[0] && status[0] <= '9' {\n\t\t\t\tif statusValue, err := strconv.Atoi(status); err == nil && statusValue >= 400 {\n\t\t\t\t\tconverted.Error = int32(statusValue)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ try to get the service from the cs\/cr or sr\/ss annotations\n\tvar minTimestamp, maxTimestamp int64\n\tfor _, an := range span.Annotations {\n\t\tif an.Host != nil && an.Host.ServiceName != \"\" {\n\t\t\tif an.Value == \"sr\" {\n\t\t\t\tconverted.Service = an.Host.ServiceName\n\t\t\t}\n\t\t}\n\n\t\tif an.Timestamp < minTimestamp || minTimestamp == 0 {\n\t\t\tminTimestamp = an.Timestamp\n\t\t}\n\n\t\tif an.Timestamp > maxTimestamp {\n\t\t\tmaxTimestamp = an.Timestamp\n\t\t}\n\t}\n\n\tif converted.Start == 0 {\n\t\tconverted.Start = 1000 * minTimestamp\n\t\tconverted.Duration = 1000 * (maxTimestamp - minTimestamp)\n\t}\n\n\t\/\/ simplify some names\n\tif strings.HasPrefix(converted.Name, \"http:\") {\n\t\tconverted.Service = converted.Name[5:]\n\t}\n\n\tif converted.Name == \"transaction\" {\n\t\tconverted.Service = \"oracle\"\n\t}\n\n\tif sql := converted.Meta[\"sql\"]; sql != \"\" {\n\t\tdelete(converted.Meta, \"sql\")\n\t\tconverted.Service = \"sql\"\n\t\tconverted.Resource = sql\n\t}\n\n\tif strings.HasPrefix(converted.Name, \"redis:\") {\n\t\tconverted.Service = \"redis\"\n\n\t\tif key := converted.Meta[\"redis.key\"]; key != \"\" {\n\t\t\tconverted.Resource = SimplifyResourceName(key)\n\n\t\t\t\/\/ the hash is not really important later on. lets not spam datadog with it.\n\t\t\tdelete(converted.Meta, \"redis.key\")\n\t\t}\n\t}\n\n\tif converted.Service == \"core-services\" {\n\t\tif strings.Contains(converted.Meta[\"http.url\"], \":6080\/\") {\n\t\t\tconverted.Service = \"iwg-restrictor\"\n\t\t\tconverted.Name = iwgNameFromResource(converted.Resource, converted.Name)\n\t\t\tconverted.Resource = dropDomainFromUrl(converted.Resource)\n\t\t}\n\n\t\tif strings.Contains(converted.Meta[\"http.url\"], \":2080\/\") {\n\t\t\tconverted.Service = \"instant-win-game\"\n\t\t\tconverted.Name = \"iwg-game\"\n\t\t\tconverted.Resource = dropDomainFromUrl(converted.Resource)\n\t\t}\n\n\t\tif lc := converted.Meta[\"lc\"]; lc != \"\" {\n\t\t\tconverted.Name = lc\n\t\t\tconverted.Service = lc\n\t\t}\n\t}\n\n\t\/\/ If we could not get a service, we'll try to get it from the parent span.\n\t\/\/ Try first in the current map, then in the previous one.\n\tif converted.Service == \"\" {\n\t\tparentService := converter.current[converted.ParentID]\n\t\tif parentService != \"\" {\n\t\t\tconverted.Service = parentService\n\t\t} else {\n\t\t\tparentService = converter.previous[converted.ParentID]\n\t\t\tif parentService != \"\" {\n\t\t\t\tconverted.Service = parentService\n\t\t\t}\n\t\t}\n\n\t\t\/\/ if we did not get a service, use a fallback\n\t\tif converted.Service == \"\" {\n\t\t\tlogrus.Warnf(\"Could not get a service for this span: %+v\", span)\n\t\t\tconverted.Service = \"unknown\"\n\t\t}\n\t}\n\n\tif lc := converted.Meta[\"lc\"]; lc != \"\" {\n\t\tdelete(converted.Meta, \"lc\")\n\n\t\tif converted.Name == \"\" {\n\t\t\tconverted.Name = converted.Meta[\"lc\"]\n\t\t}\n\n\t\tif lc == \"consul\" {\n\t\t\tconverted.Service = \"consul\"\n\t\t}\n\t}\n\n\t\/\/ guess a type for the datadog ui.\n\tif converted.Name == \"transaction\" || converted.Service == \"redis\" {\n\t\tconverted.Type = \"db\"\n\t} else {\n\t\tconverted.Type = \"http\"\n\t}\n\n\tif converted.Name == \"hystrix\" {\n\t\tconverted.Resource = converted.Meta[\"thread\"]\n\t}\n\n\tif converted.Name == \"\" {\n\t\tlogrus.Warnf(\"Could not get a name for this span: %+v converted: %+v\", span, converted)\n\t}\n\n\t\/\/ initialize history maps for span -> parent assignment\n\tif len(converter.current) >= 40000 || converter.current == nil {\n\t\tconverter.previous = converter.current\n\t\tconverter.current = make(map[uint64]string, 40000)\n\t}\n\n\t\/\/ remember the service for a short while\n\tconverter.current[converted.SpanID] = converted.Service\n\n\treturn converted\n}\n\nfunc dropDomainFromUrl(url string) string {\n\tswitch {\n\tcase strings.HasPrefix(url, \"http:\/\/\"):\n\t\tindex := strings.IndexRune(url[7:], '\/')\n\t\treturn url[7+index:]\n\n\tcase strings.HasPrefix(url, \"https:\/\/\"):\n\t\tindex := strings.IndexRune(url[8:], '\/')\n\t\treturn url[8+index:]\n\t}\n\n\treturn url\n}\n\nfunc iwgNameFromResource(resource string, fallback string) string {\n\tsplittedUrl := strings.Split(strings.Trim(resource, \"\/\"), \"\/\")\n\tif len(splittedUrl) == 1 && splittedUrl[0] != \"\" {\n\t\treturn splittedUrl[0]\n\t} else if len(splittedUrl) > 1 {\n\t\treturn splittedUrl[len(splittedUrl)-2] + \"\/\" + splittedUrl[len(splittedUrl)-1]\n\t}\n\treturn fallback\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"fmt\"\n\nfunc a() error {\n\tfmt.Println(\"this function returns an error\")\n\treturn nil\n}\n\nfunc b() (int, error) {\n\tfmt.Println(\"this function returns an int and an error\")\n\treturn 0, nil\n}\n\nfunc main() {\n\t\/\/ Single error return\n\t_ = a()\n\ta()\n\n\t\/\/ Return another value and an error\n\t_, _ = b()\n\tb()\n\n\t\/\/ Method with a single error return\n\tx := t{}\n\t_ = x.a()\n\tx.a()\n\n\t\/\/ Method call on a struct member\n\ty := u{x}\n\t_ = y.t.a()\n\ty.t.a()\n\n\tm1 := map[string]func() error{\"a\": a}\n\t_ = m1[\"a\"]()\n\tm1[\"a\"]()\n}\n<commit_msg>Add extra test cases for blank identifiers<commit_after>package main\n\nimport \"fmt\"\n\nfunc a() error {\n\tfmt.Println(\"this function returns an error\")\n\treturn nil\n}\n\nfunc b() (int, error) {\n\tfmt.Println(\"this function returns an int and an error\")\n\treturn 0, nil\n}\n\nfunc main() {\n\t\/\/ Single error return\n\t_ = a()\n\ta()\n\n\t\/\/ Return another value and an error\n\t_, _ = b()\n\tb()\n\n\t\/\/ Method with a single error return\n\tx := t{}\n\t_ = x.a()\n\tx.a()\n\n\t\/\/ Method call on a struct member\n\ty := u{x}\n\t_ = y.t.a()\n\ty.t.a()\n\n\tm1 := map[string]func() error{\"a\": a}\n\t_ = m1[\"a\"]()\n\tm1[\"a\"]()\n\n\t\/\/ Additional cases for assigning errors to blank identifier\n\tz, _ := b()\n\t_, w := a(), 5\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\/http\"\n\n\t\"github.com\/bradfitz\/slice\"\n\t\"github.com\/samsarahq\/thunder\/graphql\"\n\t\"github.com\/samsarahq\/thunder\/graphql\/schemabuilder\"\n\t\"github.com\/samsarahq\/thunder\/livesql\"\n\t\"github.com\/samsarahq\/thunder\/sqlgen\"\n)\n\nvar reactionTypes = map[string]bool{\n\t\":)\": true,\n\t\":(\": true,\n}\n\ntype Message struct {\n\tId   int64 `sql:\",primary\" graphql:\",key\"`\n\tText string\n}\n\ntype ReactionInstance struct {\n\tId        int64 `sql:\",primary\"`\n\tMessageId int64\n\tReaction  string\n}\n\ntype Reaction struct {\n\tReaction string `graphql:\",key\"`\n\tCount    int\n}\n\ntype Server struct {\n\tdb *livesql.LiveDB\n}\n\ntype Query struct{}\n\nfunc (s *Server) Query() schemabuilder.Spec {\n\tspec := schemabuilder.Spec{\n\t\tType: Query{},\n\t}\n\tspec.FieldFunc(\"messages\", s.messages)\n\treturn spec\n}\n\nfunc (s *Server) messages(ctx context.Context) ([]*Message, error) {\n\tvar result []*Message\n\tif err := s.db.Query(ctx, &result, nil, nil); err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}\n\ntype Mutation struct{}\n\nfunc (s *Server) Mutation() schemabuilder.Spec {\n\tspec := schemabuilder.Spec{\n\t\tType: Mutation{},\n\t}\n\tspec.FieldFunc(\"addMessage\", func(ctx context.Context, args struct{ Text string }) error {\n\t\t_, err := s.db.InsertRow(ctx, &Message{Text: args.Text})\n\t\treturn err\n\t})\n\tspec.FieldFunc(\"deleteMessage\", func(ctx context.Context, args struct{ Id int64 }) error {\n\t\treturn s.db.DeleteRow(ctx, &Message{Id: args.Id})\n\t})\n\tspec.FieldFunc(\"addReaction\", func(ctx context.Context, args struct {\n\t\tMessageId int64\n\t\tReaction  string\n\t}) error {\n\t\tif _, ok := reactionTypes[args.Reaction]; !ok {\n\t\t\treturn errors.New(\"reaction not allowed\")\n\t\t}\n\n\t\t_, err := s.db.InsertRow(ctx, &ReactionInstance{MessageId: args.MessageId, Reaction: args.Reaction})\n\t\treturn err\n\t})\n\treturn spec\n}\n\nfunc (s *Server) Message() schemabuilder.Spec {\n\tspec := schemabuilder.Spec{\n\t\tType: Message{},\n\t}\n\tspec.FieldFunc(\"reactions\", s.messageReactions)\n\treturn spec\n}\n\nfunc (s *Server) messageReactions(ctx context.Context, m *Message) ([]*Reaction, error) {\n\treactions := make(map[string]*Reaction)\n\tfor reactionType := range reactionTypes {\n\t\treactions[reactionType] = &Reaction{\n\t\t\tReaction: reactionType,\n\t\t}\n\t}\n\n\tvar instances []*ReactionInstance\n\tif err := s.db.Query(ctx, &instances, sqlgen.Filter{\"message_id\": m.Id}, nil); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, instance := range instances {\n\t\treactions[instance.Reaction].Count++\n\t}\n\n\tvar result []*Reaction\n\tfor _, reaction := range reactions {\n\t\tresult = append(result, reaction)\n\t}\n\tslice.Sort(result, func(a, b int) bool { return result[a].Reaction < result[b].Reaction })\n\n\treturn result, nil\n}\n\nfunc main() {\n\tsqlgenSchema := sqlgen.NewSchema()\n\tsqlgenSchema.MustRegisterType(\"messages\", sqlgen.AutoIncrement, Message{})\n\tsqlgenSchema.MustRegisterType(\"reaction_instances\", sqlgen.AutoIncrement, ReactionInstance{})\n\n\tliveDB, err := livesql.Open(\"localhost\", 3307, \"root\", \"\", \"chat\", sqlgenSchema)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tserver := &Server{\n\t\tdb: liveDB,\n\t}\n\tgraphqlSchema := schemabuilder.MustBuildSchema(server)\n\n\thttp.Handle(\"\/graphql\", graphql.Handler(graphqlSchema))\n\tif err := http.ListenAndServe(\":3030\", nil); err != nil {\n\t\tpanic(err)\n\t}\n}\n<commit_msg>example: inline two fields functions<commit_after>package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\/http\"\n\n\t\"github.com\/bradfitz\/slice\"\n\t\"github.com\/samsarahq\/thunder\/graphql\"\n\t\"github.com\/samsarahq\/thunder\/graphql\/schemabuilder\"\n\t\"github.com\/samsarahq\/thunder\/livesql\"\n\t\"github.com\/samsarahq\/thunder\/sqlgen\"\n)\n\nvar reactionTypes = map[string]bool{\n\t\":)\": true,\n\t\":(\": true,\n}\n\ntype Message struct {\n\tId   int64 `sql:\",primary\" graphql:\",key\"`\n\tText string\n}\n\ntype ReactionInstance struct {\n\tId        int64 `sql:\",primary\"`\n\tMessageId int64\n\tReaction  string\n}\n\ntype Reaction struct {\n\tReaction string `graphql:\",key\"`\n\tCount    int\n}\n\ntype Server struct {\n\tdb *livesql.LiveDB\n}\n\ntype Query struct{}\n\nfunc (s *Server) Query() schemabuilder.Spec {\n\tspec := schemabuilder.Spec{\n\t\tType: Query{},\n\t}\n\tspec.FieldFunc(\"messages\", func(ctx context.Context) ([]*Message, error) {\n\t\tvar result []*Message\n\t\tif err := s.db.Query(ctx, &result, nil, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn result, nil\n\t})\n\treturn spec\n}\n\ntype Mutation struct{}\n\nfunc (s *Server) Mutation() schemabuilder.Spec {\n\tspec := schemabuilder.Spec{\n\t\tType: Mutation{},\n\t}\n\tspec.FieldFunc(\"addMessage\", func(ctx context.Context, args struct{ Text string }) error {\n\t\t_, err := s.db.InsertRow(ctx, &Message{Text: args.Text})\n\t\treturn err\n\t})\n\tspec.FieldFunc(\"deleteMessage\", func(ctx context.Context, args struct{ Id int64 }) error {\n\t\treturn s.db.DeleteRow(ctx, &Message{Id: args.Id})\n\t})\n\tspec.FieldFunc(\"addReaction\", func(ctx context.Context, args struct {\n\t\tMessageId int64\n\t\tReaction  string\n\t}) error {\n\t\tif _, ok := reactionTypes[args.Reaction]; !ok {\n\t\t\treturn errors.New(\"reaction not allowed\")\n\t\t}\n\t\t_, err := s.db.InsertRow(ctx, &ReactionInstance{MessageId: args.MessageId, Reaction: args.Reaction})\n\t\treturn err\n\t})\n\treturn spec\n}\n\nfunc (s *Server) Message() schemabuilder.Spec {\n\tspec := schemabuilder.Spec{\n\t\tType: Message{},\n\t}\n\tspec.FieldFunc(\"reactions\", func(ctx context.Context, m *Message) ([]*Reaction, error) {\n\t\treactions := make(map[string]*Reaction)\n\t\tfor reactionType := range reactionTypes {\n\t\t\treactions[reactionType] = &Reaction{\n\t\t\t\tReaction: reactionType,\n\t\t\t}\n\t\t}\n\n\t\tvar instances []*ReactionInstance\n\t\tif err := s.db.Query(ctx, &instances, sqlgen.Filter{\"message_id\": m.Id}, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, instance := range instances {\n\t\t\treactions[instance.Reaction].Count++\n\t\t}\n\n\t\tvar result []*Reaction\n\t\tfor _, reaction := range reactions {\n\t\t\tresult = append(result, reaction)\n\t\t}\n\t\tslice.Sort(result, func(a, b int) bool { return result[a].Reaction < result[b].Reaction })\n\n\t\treturn result, nil\n\t})\n\treturn spec\n}\n\nfunc main() {\n\tsqlgenSchema := sqlgen.NewSchema()\n\tsqlgenSchema.MustRegisterType(\"messages\", sqlgen.AutoIncrement, Message{})\n\tsqlgenSchema.MustRegisterType(\"reaction_instances\", sqlgen.AutoIncrement, ReactionInstance{})\n\n\tliveDB, err := livesql.Open(\"localhost\", 3307, \"root\", \"\", \"chat\", sqlgenSchema)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tserver := &Server{\n\t\tdb: liveDB,\n\t}\n\tgraphqlSchema := schemabuilder.MustBuildSchema(server)\n\n\thttp.Handle(\"\/graphql\", graphql.Handler(graphqlSchema))\n\tif err := http.ListenAndServe(\":3030\", nil); err != nil {\n\t\tpanic(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/md5\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t_ \"net\/http\/pprof\"\n\n\t\"github.com\/lucas-clemente\/quic-go\"\n\t\"github.com\/lucas-clemente\/quic-go\/http3\"\n\t\"github.com\/lucas-clemente\/quic-go\/integrationtests\/tools\/testserver\"\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/testdata\"\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/utils\"\n\t\"github.com\/lucas-clemente\/quic-go\/quictrace\"\n)\n\ntype binds []string\n\nfunc (b binds) String() string {\n\treturn strings.Join(b, \",\")\n}\n\nfunc (b *binds) Set(v string) error {\n\t*b = strings.Split(v, \",\")\n\treturn nil\n}\n\n\/\/ Size is needed by the \/demo\/upload handler to determine the size of the uploaded file\ntype Size interface {\n\tSize() int64\n}\n\nvar tracer quictrace.Tracer\n\nfunc init() {\n\ttracer = quictrace.NewTracer()\n}\n\nfunc exportTraces() error {\n\ttraces := tracer.GetAllTraces()\n\tif len(traces) != 1 {\n\t\treturn errors.New(\"expected exactly one trace\")\n\t}\n\tfor _, trace := range traces {\n\t\tf, err := os.Create(\"trace.qtr\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := f.Write(trace); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tf.Close()\n\t\tfmt.Println(\"Wrote trace to\", f.Name())\n\t}\n\treturn nil\n}\n\ntype tracingHandler struct {\n\thandler http.Handler\n}\n\nvar _ http.Handler = &tracingHandler{}\n\nfunc (h *tracingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\th.handler.ServeHTTP(w, r)\n\tif err := exportTraces(); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc setupHandler(www string, trace bool) http.Handler {\n\tmux := http.NewServeMux()\n\n\tmux.Handle(\"\/\", http.FileServer(http.Dir(www)))\n\tmux.HandleFunc(\"\/demo\/tile\", func(w http.ResponseWriter, r *http.Request) {\n\t\t\/\/ Small 40x40 png\n\t\tw.Write([]byte{\n\t\t\t0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,\n\t\t\t0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x28,\n\t\t\t0x01, 0x03, 0x00, 0x00, 0x00, 0xb6, 0x30, 0x2a, 0x2e, 0x00, 0x00, 0x00,\n\t\t\t0x03, 0x50, 0x4c, 0x54, 0x45, 0x5a, 0xc3, 0x5a, 0xad, 0x38, 0xaa, 0xdb,\n\t\t\t0x00, 0x00, 0x00, 0x0b, 0x49, 0x44, 0x41, 0x54, 0x78, 0x01, 0x63, 0x18,\n\t\t\t0x61, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x01, 0xe2, 0xb8, 0x75, 0x22, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,\n\t\t})\n\t})\n\n\tmux.HandleFunc(\"\/demo\/tiles\", func(w http.ResponseWriter, r *http.Request) {\n\t\tio.WriteString(w, \"<html><head><style>img{width:40px;height:40px;}<\/style><\/head><body>\")\n\t\tfor i := 0; i < 200; i++ {\n\t\t\tfmt.Fprintf(w, `<img src=\"\/demo\/tile?cachebust=%d\">`, i)\n\t\t}\n\t\tio.WriteString(w, \"<\/body><\/html>\")\n\t})\n\n\tmux.HandleFunc(\"\/demo\/echo\", func(w http.ResponseWriter, r *http.Request) {\n\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error reading body while handling \/echo: %s\\n\", err.Error())\n\t\t}\n\t\tw.Write(body)\n\t})\n\n\t\/\/ accept file uploads and return the MD5 of the uploaded file\n\t\/\/ maximum accepted file size is 1 GB\n\tmux.HandleFunc(\"\/demo\/upload\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == http.MethodPost {\n\t\t\terr := r.ParseMultipartForm(1 << 30) \/\/ 1 GB\n\t\t\tif err == nil {\n\t\t\t\tvar file multipart.File\n\t\t\t\tfile, _, err = r.FormFile(\"uploadfile\")\n\t\t\t\tif err == nil {\n\t\t\t\t\tvar size int64\n\t\t\t\t\tif sizeInterface, ok := file.(Size); ok {\n\t\t\t\t\t\tsize = sizeInterface.Size()\n\t\t\t\t\t\tb := make([]byte, size)\n\t\t\t\t\t\tfile.Read(b)\n\t\t\t\t\t\tmd5 := md5.Sum(b)\n\t\t\t\t\t\tfmt.Fprintf(w, \"%x\", md5)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\terr = errors.New(\"couldn't get uploaded file size\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tutils.DefaultLogger.Infof(\"Error receiving upload: %#v\", err)\n\t\t\t}\n\t\t}\n\t\tio.WriteString(w, `<html><body><form action=\"\/demo\/upload\" method=\"post\" enctype=\"multipart\/form-data\">\n\t\t\t\t<input type=\"file\" name=\"uploadfile\"><br>\n\t\t\t\t<input type=\"submit\">\n\t\t\t<\/form><\/body><\/html>`)\n\t})\n\n\tmux.HandleFunc(\"\/dynamic\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tconst maxSize = 1 << 30 \/\/ 1 GB\n\t\tnum, err := strconv.ParseInt(strings.ReplaceAll(r.RequestURI, \"\/dynamic\/\", \"\"), 10, 64)\n\t\tif err != nil || num <= 0 || num > maxSize {\n\t\t\tw.WriteHeader(400)\n\t\t\treturn\n\t\t}\n\t\tw.Write(testserver.GeneratePRData(int(num)))\n\t})\n\n\tif !trace {\n\t\treturn mux\n\t}\n\treturn &tracingHandler{handler: mux}\n}\n\nfunc main() {\n\t\/\/ defer profile.Start().Stop()\n\tgo func() {\n\t\tlog.Println(http.ListenAndServe(\"localhost:6060\", nil))\n\t}()\n\t\/\/ runtime.SetBlockProfileRate(1)\n\n\tverbose := flag.Bool(\"v\", false, \"verbose\")\n\tbs := binds{}\n\tflag.Var(&bs, \"bind\", \"bind to\")\n\twww := flag.String(\"www\", \"\/var\/www\", \"www data\")\n\ttcp := flag.Bool(\"tcp\", false, \"also listen on TCP\")\n\ttrace := flag.Bool(\"trace\", false, \"enable quic-trace\")\n\tflag.Parse()\n\n\tlogger := utils.DefaultLogger\n\n\tif *verbose {\n\t\tlogger.SetLogLevel(utils.LogLevelDebug)\n\t} else {\n\t\tlogger.SetLogLevel(utils.LogLevelInfo)\n\t}\n\tlogger.SetLogTimeFormat(\"\")\n\n\tif len(bs) == 0 {\n\t\tbs = binds{\"localhost:6121\"}\n\t}\n\n\thandler := setupHandler(*www, *trace)\n\tvar quicConf *quic.Config\n\tif *trace {\n\t\tquicConf = &quic.Config{QuicTracer: tracer}\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(bs))\n\tfor _, b := range bs {\n\t\tbCap := b\n\t\tgo func() {\n\t\t\tvar err error\n\t\t\tif *tcp {\n\t\t\t\tcertFile, keyFile := testdata.GetCertificatePaths()\n\t\t\t\terr = http3.ListenAndServe(bCap, certFile, keyFile, nil)\n\t\t\t} else {\n\t\t\t\tserver := http3.Server{\n\t\t\t\t\tServer:     &http.Server{Handler: handler, Addr: bCap},\n\t\t\t\t\tQuicConfig: quicConf,\n\t\t\t\t}\n\t\t\t\terr = server.ListenAndServeTLS(testdata.GetCertificatePaths())\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n}\n<commit_msg>make example server conform with the GET \/xxx format used for interop<commit_after>package main\n\nimport (\n\t\"crypto\/md5\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"mime\/multipart\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t_ \"net\/http\/pprof\"\n\n\t\"github.com\/lucas-clemente\/quic-go\"\n\t\"github.com\/lucas-clemente\/quic-go\/http3\"\n\t\"github.com\/lucas-clemente\/quic-go\/integrationtests\/tools\/testserver\"\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/testdata\"\n\t\"github.com\/lucas-clemente\/quic-go\/internal\/utils\"\n\t\"github.com\/lucas-clemente\/quic-go\/quictrace\"\n)\n\ntype binds []string\n\nfunc (b binds) String() string {\n\treturn strings.Join(b, \",\")\n}\n\nfunc (b *binds) Set(v string) error {\n\t*b = strings.Split(v, \",\")\n\treturn nil\n}\n\n\/\/ Size is needed by the \/demo\/upload handler to determine the size of the uploaded file\ntype Size interface {\n\tSize() int64\n}\n\nvar tracer quictrace.Tracer\n\nfunc init() {\n\ttracer = quictrace.NewTracer()\n}\n\nfunc exportTraces() error {\n\ttraces := tracer.GetAllTraces()\n\tif len(traces) != 1 {\n\t\treturn errors.New(\"expected exactly one trace\")\n\t}\n\tfor _, trace := range traces {\n\t\tf, err := os.Create(\"trace.qtr\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := f.Write(trace); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tf.Close()\n\t\tfmt.Println(\"Wrote trace to\", f.Name())\n\t}\n\treturn nil\n}\n\ntype tracingHandler struct {\n\thandler http.Handler\n}\n\nvar _ http.Handler = &tracingHandler{}\n\nfunc (h *tracingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\th.handler.ServeHTTP(w, r)\n\tif err := exportTraces(); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc setupHandler(www string, trace bool) http.Handler {\n\tmux := http.NewServeMux()\n\n\tif len(www) > 0 {\n\t\tmux.Handle(\"\/\", http.FileServer(http.Dir(www)))\n\t} else {\n\t\tmux.HandleFunc(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\t\tfmt.Printf(\"%#v\\n\", r)\n\t\t\tconst maxSize = 1 << 30 \/\/ 1 GB\n\t\t\tnum, err := strconv.ParseInt(strings.ReplaceAll(r.RequestURI, \"\/\", \"\"), 10, 64)\n\t\t\tif err != nil || num <= 0 || num > maxSize {\n\t\t\t\tw.WriteHeader(400)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.Write(testserver.GeneratePRData(int(num)))\n\t\t})\n\t}\n\n\tmux.HandleFunc(\"\/demo\/tile\", func(w http.ResponseWriter, r *http.Request) {\n\t\t\/\/ Small 40x40 png\n\t\tw.Write([]byte{\n\t\t\t0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,\n\t\t\t0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x28,\n\t\t\t0x01, 0x03, 0x00, 0x00, 0x00, 0xb6, 0x30, 0x2a, 0x2e, 0x00, 0x00, 0x00,\n\t\t\t0x03, 0x50, 0x4c, 0x54, 0x45, 0x5a, 0xc3, 0x5a, 0xad, 0x38, 0xaa, 0xdb,\n\t\t\t0x00, 0x00, 0x00, 0x0b, 0x49, 0x44, 0x41, 0x54, 0x78, 0x01, 0x63, 0x18,\n\t\t\t0x61, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x01, 0xe2, 0xb8, 0x75, 0x22, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,\n\t\t})\n\t})\n\n\tmux.HandleFunc(\"\/demo\/tiles\", func(w http.ResponseWriter, r *http.Request) {\n\t\tio.WriteString(w, \"<html><head><style>img{width:40px;height:40px;}<\/style><\/head><body>\")\n\t\tfor i := 0; i < 200; i++ {\n\t\t\tfmt.Fprintf(w, `<img src=\"\/demo\/tile?cachebust=%d\">`, i)\n\t\t}\n\t\tio.WriteString(w, \"<\/body><\/html>\")\n\t})\n\n\tmux.HandleFunc(\"\/demo\/echo\", func(w http.ResponseWriter, r *http.Request) {\n\t\tbody, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error reading body while handling \/echo: %s\\n\", err.Error())\n\t\t}\n\t\tw.Write(body)\n\t})\n\n\t\/\/ accept file uploads and return the MD5 of the uploaded file\n\t\/\/ maximum accepted file size is 1 GB\n\tmux.HandleFunc(\"\/demo\/upload\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == http.MethodPost {\n\t\t\terr := r.ParseMultipartForm(1 << 30) \/\/ 1 GB\n\t\t\tif err == nil {\n\t\t\t\tvar file multipart.File\n\t\t\t\tfile, _, err = r.FormFile(\"uploadfile\")\n\t\t\t\tif err == nil {\n\t\t\t\t\tvar size int64\n\t\t\t\t\tif sizeInterface, ok := file.(Size); ok {\n\t\t\t\t\t\tsize = sizeInterface.Size()\n\t\t\t\t\t\tb := make([]byte, size)\n\t\t\t\t\t\tfile.Read(b)\n\t\t\t\t\t\tmd5 := md5.Sum(b)\n\t\t\t\t\t\tfmt.Fprintf(w, \"%x\", md5)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\terr = errors.New(\"couldn't get uploaded file size\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tutils.DefaultLogger.Infof(\"Error receiving upload: %#v\", err)\n\t\t\t}\n\t\t}\n\t\tio.WriteString(w, `<html><body><form action=\"\/demo\/upload\" method=\"post\" enctype=\"multipart\/form-data\">\n\t\t\t\t<input type=\"file\" name=\"uploadfile\"><br>\n\t\t\t\t<input type=\"submit\">\n\t\t\t<\/form><\/body><\/html>`)\n\t})\n\n\tif !trace {\n\t\treturn mux\n\t}\n\treturn &tracingHandler{handler: mux}\n}\n\nfunc main() {\n\t\/\/ defer profile.Start().Stop()\n\tgo func() {\n\t\tlog.Println(http.ListenAndServe(\"localhost:6060\", nil))\n\t}()\n\t\/\/ runtime.SetBlockProfileRate(1)\n\n\tverbose := flag.Bool(\"v\", false, \"verbose\")\n\tbs := binds{}\n\tflag.Var(&bs, \"bind\", \"bind to\")\n\twww := flag.String(\"www\", \"\", \"www data\")\n\ttcp := flag.Bool(\"tcp\", false, \"also listen on TCP\")\n\ttrace := flag.Bool(\"trace\", false, \"enable quic-trace\")\n\tflag.Parse()\n\n\tlogger := utils.DefaultLogger\n\n\tif *verbose {\n\t\tlogger.SetLogLevel(utils.LogLevelDebug)\n\t} else {\n\t\tlogger.SetLogLevel(utils.LogLevelInfo)\n\t}\n\tlogger.SetLogTimeFormat(\"\")\n\n\tif len(bs) == 0 {\n\t\tbs = binds{\"localhost:6121\"}\n\t}\n\n\thandler := setupHandler(*www, *trace)\n\tvar quicConf *quic.Config\n\tif *trace {\n\t\tquicConf = &quic.Config{QuicTracer: tracer}\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(bs))\n\tfor _, b := range bs {\n\t\tbCap := b\n\t\tgo func() {\n\t\t\tvar err error\n\t\t\tif *tcp {\n\t\t\t\tcertFile, keyFile := testdata.GetCertificatePaths()\n\t\t\t\terr = http3.ListenAndServe(bCap, certFile, keyFile, nil)\n\t\t\t} else {\n\t\t\t\tserver := http3.Server{\n\t\t\t\t\tServer:     &http.Server{Handler: handler, Addr: bCap},\n\t\t\t\t\tQuicConfig: quicConf,\n\t\t\t\t}\n\t\t\t\terr = server.ListenAndServeTLS(testdata.GetCertificatePaths())\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\twg.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The xridge kubestone contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage sysbench\n\nimport (\n\tbatchv1 \"k8s.io\/api\/batch\/v1\"\n\tcorev1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\n\t\"github.com\/firepear\/qsplit\"\n\tperfv1alpha1 \"github.com\/xridge\/kubestone\/api\/v1alpha1\"\n)\n\n\/\/ NewJob creates a sysbench benchmark job\nfunc NewJob(cr *perfv1alpha1.Sysbench) *batchv1.Job {\n\tlabels := map[string]string{\n\t\t\"app\":               \"sysbench\",\n\t\t\"kubestone-cr-name\": cr.Name,\n\t}\n\tfor key, value := range cr.Spec.PodLabels {\n\t\tlabels[key] = value\n\t}\n\n\tsysbenchCmdLineArgs := []string{}\n\tsysbenchCmdLineArgs = append(sysbenchCmdLineArgs, qsplit.ToStrings([]byte(cr.Spec.Options))...)\n\tsysbenchCmdLineArgs = append(sysbenchCmdLineArgs, cr.Spec.TestName, cr.Spec.Command)\n\n\tbackoffLimit := int32(0)\n\n\tjob := batchv1.Job{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName:      cr.Name,\n\t\t\tNamespace: cr.Namespace,\n\t\t},\n\t\tSpec: batchv1.JobSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:            \"sysbench\",\n\t\t\t\t\t\t\tImage:           cr.Spec.Image.Name,\n\t\t\t\t\t\t\tImagePullPolicy: corev1.PullPolicy(cr.Spec.Image.PullPolicy),\n\t\t\t\t\t\t\tArgs:            sysbenchCmdLineArgs,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tImagePullSecrets: []corev1.LocalObjectReference{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: cr.Spec.Image.PullSecret,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tRestartPolicy: corev1.RestartPolicyNever,\n\t\t\t\t\tAffinity:      &cr.Spec.PodScheduling.Affinity,\n\t\t\t\t\tTolerations:   cr.Spec.PodScheduling.Tolerations,\n\t\t\t\t\tNodeSelector:  cr.Spec.PodScheduling.NodeSelector,\n\t\t\t\t\tNodeName:      cr.Spec.PodScheduling.NodeName,\n\t\t\t\t},\n\t\t\t},\n\t\t\tBackoffLimit: &backoffLimit,\n\t\t},\n\t}\n\n\treturn &job\n}\n<commit_msg>Add TODO item not to forget other pods attributes<commit_after>\/*\nCopyright 2019 The xridge kubestone contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage sysbench\n\nimport (\n\tbatchv1 \"k8s.io\/api\/batch\/v1\"\n\tcorev1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\n\t\"github.com\/firepear\/qsplit\"\n\tperfv1alpha1 \"github.com\/xridge\/kubestone\/api\/v1alpha1\"\n)\n\n\/\/ NewJob creates a sysbench benchmark job\nfunc NewJob(cr *perfv1alpha1.Sysbench) *batchv1.Job {\n\tlabels := map[string]string{\n\t\t\"app\":               \"sysbench\",\n\t\t\"kubestone-cr-name\": cr.Name,\n\t}\n\tfor key, value := range cr.Spec.PodLabels {\n\t\tlabels[key] = value\n\t}\n\n\tsysbenchCmdLineArgs := []string{}\n\tsysbenchCmdLineArgs = append(sysbenchCmdLineArgs, qsplit.ToStrings([]byte(cr.Spec.Options))...)\n\tsysbenchCmdLineArgs = append(sysbenchCmdLineArgs, cr.Spec.TestName, cr.Spec.Command)\n\n\tbackoffLimit := int32(0)\n\n\tjob := batchv1.Job{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName:      cr.Name,\n\t\t\tNamespace: cr.Namespace,\n\t\t},\n\t\tSpec: batchv1.JobSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tLabels: labels,\n\t\t\t\t},\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: []corev1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:            \"sysbench\",\n\t\t\t\t\t\t\tImage:           cr.Spec.Image.Name,\n\t\t\t\t\t\t\tImagePullPolicy: corev1.PullPolicy(cr.Spec.Image.PullPolicy),\n\t\t\t\t\t\t\tArgs:            sysbenchCmdLineArgs,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tImagePullSecrets: []corev1.LocalObjectReference{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: cr.Spec.Image.PullSecret,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\/\/ TODO: add more options here eg. resource requests\/limits\n\t\t\t\t\tRestartPolicy: corev1.RestartPolicyNever,\n\t\t\t\t\tAffinity:      &cr.Spec.PodScheduling.Affinity,\n\t\t\t\t\tTolerations:   cr.Spec.PodScheduling.Tolerations,\n\t\t\t\t\tNodeSelector:  cr.Spec.PodScheduling.NodeSelector,\n\t\t\t\t\tNodeName:      cr.Spec.PodScheduling.NodeName,\n\t\t\t\t},\n\t\t\t},\n\t\t\tBackoffLimit: &backoffLimit,\n\t\t},\n\t}\n\n\treturn &job\n}\n<|endoftext|>"}
{"text":"<commit_before>package v1\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/freeusd\/solebtc\/Godeps\/_workspace\/src\/github.com\/gin-gonic\/gin\"\n\t. \"github.com\/freeusd\/solebtc\/Godeps\/_workspace\/src\/github.com\/smartystreets\/goconvey\/convey\"\n\t\"github.com\/freeusd\/solebtc\/errors\"\n\t\"github.com\/freeusd\/solebtc\/models\"\n)\n\nconst (\n\tvalidBTCAddr   = \"1EFJFaeATfp2442TGcHS5mgadXJjsSSP2T\"\n\tinvalidBTCAddr = \"address\"\n\n\tvalidEmail   = \"valid@email.cc\"\n\tinvalidEmail = \"invalid@.ee.cc\"\n)\n\nfunc TestSignup(t *testing.T) {\n\trequestDataJSON := func(email string) []byte {\n\t\traw, _ := json.Marshal(map[string]interface{}{\n\t\t\t\"email\":      email,\n\t\t\t\"address\":    \"address\",\n\t\t\t\"referer_id\": 2,\n\t\t})\n\t\treturn raw\n\t}\n\n\ttestdata := []struct {\n\t\twhen        string\n\t\trequestData []byte\n\t\tcode        int\n\t\tgetUserByID dependencyGetUserByID\n\t\tcreateUser  dependencyCreateUser\n\t}{\n\t\t{\n\t\t\t\"invalid json data\",\n\t\t\t[]byte(\"huhu\"),\n\t\t\t400,\n\t\t\tnil,\n\t\t\tnil,\n\t\t},\n\t\t{\n\t\t\t\"invalid email\",\n\t\t\trequestDataJSON(invalidEmail),\n\t\t\t400,\n\t\t\tnil,\n\t\t\tnil,\n\t\t},\n\t\t{\n\t\t\t\"duplicate email\",\n\t\t\trequestDataJSON(validEmail),\n\t\t\t409,\n\t\t\tmockGetUserByID(models.User{}, nil),\n\t\t\tmockCreateUser(errors.New(errors.ErrCodeDuplicateEmail)),\n\t\t},\n\t\t{\n\t\t\t\"valid email, but create user unknown error\",\n\t\t\trequestDataJSON(validEmail),\n\t\t\t500,\n\t\t\tmockGetUserByID(models.User{}, nil),\n\t\t\tmockCreateUser(errors.New(errors.ErrCodeUnknown)),\n\t\t},\n\t\t{\n\t\t\t\"valid email\",\n\t\t\trequestDataJSON(validEmail),\n\t\t\t200,\n\t\t\tmockGetUserByID(models.User{}, nil),\n\t\t\tmockCreateUser(nil),\n\t\t},\n\t}\n\n\tfor _, v := range testdata {\n\t\tConvey(\"Given Signup controller\", t, func() {\n\t\t\thandler := Signup(v.createUser, v.getUserByID)\n\n\t\t\tConvey(fmt.Sprintf(\"When request with %s\", v.when), func() {\n\t\t\t\troute := \"\/users\"\n\t\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\t\tr.POST(route, handler)\n\t\t\t\treq, _ := http.NewRequest(\"POST\", route, bytes.NewBuffer(v.requestData))\n\t\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\t\tConvey(fmt.Sprintf(\"Response code should be equal to %d\", v.code), func() {\n\t\t\t\t\tSo(resp.Code, ShouldEqual, v.code)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t}\n}\n\nfunc TestVerifyEmail(t *testing.T) {\n\tConvey(\"Given verify email controller with expired session and errored getSessionByToken dependency\", t, func() {\n\t\tgetSessionByToken := mockGetSessionByToken(models.Session{}, errors.New(errors.ErrCodeUnknown))\n\t\thandler := VerifyEmail(getSessionByToken, nil, nil)\n\n\t\tConvey(\"When verify email\", func() {\n\t\t\troute := \"\/users\/1\/status\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.PUT(route, handler)\n\t\t\treq, _ := http.NewRequest(\"PUT\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 401\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 401)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given verify email controller with expired session and getSessionByToken dependency\", t, func() {\n\t\tgetSessionByToken := mockGetSessionByToken(models.Session{}, nil)\n\t\thandler := VerifyEmail(getSessionByToken, nil, nil)\n\n\t\tConvey(\"When verify email\", func() {\n\t\t\troute := \"\/users\/1\/status\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.PUT(route, handler)\n\t\t\treq, _ := http.NewRequest(\"PUT\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 401\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 401)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given verify email controller with errored getUserByID dependency\", t, func() {\n\t\tgetSessionByToken := mockGetSessionByToken(models.Session{UpdatedAt: time.Now()}, nil)\n\t\tgetUserByID := mockGetUserByID(models.User{}, errors.New(errors.ErrCodeUnknown))\n\t\thandler := VerifyEmail(getSessionByToken, getUserByID, nil)\n\n\t\tConvey(\"When verify email\", func() {\n\t\t\troute := \"\/users\/1\/status\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.PUT(route, handler)\n\t\t\treq, _ := http.NewRequest(\"PUT\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 500\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 500)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given verify email controller with banned user status\", t, func() {\n\t\tgetSessionByToken := mockGetSessionByToken(models.Session{UpdatedAt: time.Now()}, nil)\n\t\tgetUserByID := mockGetUserByID(models.User{Status: models.UserStatusBanned}, nil)\n\t\thandler := VerifyEmail(getSessionByToken, getUserByID, nil)\n\n\t\tConvey(\"When verify email\", func() {\n\t\t\troute := \"\/users\/1\/status\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.PUT(route, handler)\n\t\t\treq, _ := http.NewRequest(\"PUT\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 403\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 403)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given verify email controller with errored updateUser dependency\", t, func() {\n\t\tgetSessionByToken := mockGetSessionByToken(models.Session{UpdatedAt: time.Now()}, nil)\n\t\tgetUserByID := mockGetUserByID(models.User{}, nil)\n\t\tupdateUserStatus := mockUpdateUserStatus(errors.New(errors.ErrCodeUnknown))\n\t\thandler := VerifyEmail(getSessionByToken, getUserByID, updateUserStatus)\n\n\t\tConvey(\"When verify email\", func() {\n\t\t\troute := \"\/users\/1\/status\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.PUT(route, handler)\n\t\t\treq, _ := http.NewRequest(\"PUT\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 500\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 500)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given verify email controller with correct dependencies injected\", t, func() {\n\t\tgetSessionByToken := mockGetSessionByToken(models.Session{UpdatedAt: time.Now()}, nil)\n\t\tgetUserByID := mockGetUserByID(models.User{}, nil)\n\t\tupdateUserStatus := mockUpdateUserStatus(nil)\n\t\thandler := VerifyEmail(getSessionByToken, getUserByID, updateUserStatus)\n\n\t\tConvey(\"When verify email\", func() {\n\t\t\troute := \"\/users\/1\/status\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.PUT(route, handler)\n\t\t\treq, _ := http.NewRequest(\"PUT\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 200\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 200)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestGetUserInfo(t *testing.T) {\n\tConvey(\"Given get user info controller with errored getUserByID dependency\", t, func() {\n\t\tgetUserByID := mockGetUserByID(models.User{}, errors.New(errors.ErrCodeNotFound))\n\t\thandler := UserInfo(getUserByID)\n\n\t\tConvey(\"When get user info\", func() {\n\t\t\troute := \"\/users\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.Use(func(c *gin.Context) {\n\t\t\t\tc.Set(\"auth_token\", models.AuthToken{})\n\t\t\t})\n\t\t\tr.GET(route, handler)\n\t\t\treq, _ := http.NewRequest(\"GET\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 500\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 500)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given get user info controller with correctly dependencies injected\", t, func() {\n\t\tgetUserByID := mockGetUserByID(models.User{}, nil)\n\t\thandler := UserInfo(getUserByID)\n\n\t\tConvey(\"When get user info\", func() {\n\t\t\troute := \"\/users\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.Use(func(c *gin.Context) {\n\t\t\t\tc.Set(\"auth_token\", models.AuthToken{})\n\t\t\t})\n\t\t\tr.GET(route, handler)\n\t\t\treq, _ := http.NewRequest(\"GET\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 200\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 200)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestGetReferees(t *testing.T) {\n\tConvey(\"Given referee list controller\", t, func() {\n\t\thandler := RefereeList(nil, nil)\n\n\t\tConvey(\"When get reward list with invalid limit\", func() {\n\t\t\troute := \"\/users\/referees\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.Use(func(c *gin.Context) {\n\t\t\t\tc.Set(\"auth_token\", models.AuthToken{})\n\t\t\t})\n\t\t\tr.GET(route, handler)\n\t\t\treq, _ := http.NewRequest(\"GET\", route+\"?limit=3i\", nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 400\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 400)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given referee list controller with errored getRefereesSinceID dependency\", t, func() {\n\t\tsince := mockGetRefereesSince(nil, errors.New(errors.ErrCodeUnknown))\n\t\thandler := RefereeList(since, nil)\n\n\t\tConvey(\"When get referee list\", func() {\n\t\t\troute := \"\/users\/referees\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.Use(func(c *gin.Context) {\n\t\t\t\tc.Set(\"auth_token\", models.AuthToken{})\n\t\t\t})\n\t\t\tr.GET(route, handler)\n\t\t\treq, _ := http.NewRequest(\"GET\", route+\"?since=1234567890\", nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 500\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 500)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given referee list controller with correct dependencies injected\", t, func() {\n\t\tuntil := mockGetRefereesUntil(nil, nil)\n\t\thandler := RefereeList(nil, until)\n\n\t\tConvey(\"When get referee list\", func() {\n\t\t\troute := \"\/users\/referees\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.Use(func(c *gin.Context) {\n\t\t\t\tc.Set(\"auth_token\", models.AuthToken{})\n\t\t\t})\n\t\t\tr.GET(route, handler)\n\t\t\treq, _ := http.NewRequest(\"GET\", route+\"?until=1234567890\", nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 200\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 200)\n\t\t\t})\n\t\t})\n\t})\n}\n<commit_msg>Do not convert between currencies, e.g btc <-> usd<commit_after>package v1\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/freeusd\/solebtc\/Godeps\/_workspace\/src\/github.com\/gin-gonic\/gin\"\n\t. \"github.com\/freeusd\/solebtc\/Godeps\/_workspace\/src\/github.com\/smartystreets\/goconvey\/convey\"\n\t\"github.com\/freeusd\/solebtc\/errors\"\n\t\"github.com\/freeusd\/solebtc\/models\"\n)\n\nconst (\n\tvalidEmail   = \"valid@email.cc\"\n\tinvalidEmail = \"invalid@.ee.cc\"\n)\n\nfunc TestSignup(t *testing.T) {\n\trequestDataJSON := func(email string) []byte {\n\t\traw, _ := json.Marshal(map[string]interface{}{\n\t\t\t\"email\":      email,\n\t\t\t\"address\":    \"address\",\n\t\t\t\"referer_id\": 2,\n\t\t})\n\t\treturn raw\n\t}\n\n\ttestdata := []struct {\n\t\twhen        string\n\t\trequestData []byte\n\t\tcode        int\n\t\tgetUserByID dependencyGetUserByID\n\t\tcreateUser  dependencyCreateUser\n\t}{\n\t\t{\n\t\t\t\"invalid json data\",\n\t\t\t[]byte(\"huhu\"),\n\t\t\t400,\n\t\t\tnil,\n\t\t\tnil,\n\t\t},\n\t\t{\n\t\t\t\"invalid email\",\n\t\t\trequestDataJSON(invalidEmail),\n\t\t\t400,\n\t\t\tnil,\n\t\t\tnil,\n\t\t},\n\t\t{\n\t\t\t\"duplicate email\",\n\t\t\trequestDataJSON(validEmail),\n\t\t\t409,\n\t\t\tmockGetUserByID(models.User{}, nil),\n\t\t\tmockCreateUser(errors.New(errors.ErrCodeDuplicateEmail)),\n\t\t},\n\t\t{\n\t\t\t\"valid email, but create user unknown error\",\n\t\t\trequestDataJSON(validEmail),\n\t\t\t500,\n\t\t\tmockGetUserByID(models.User{}, nil),\n\t\t\tmockCreateUser(errors.New(errors.ErrCodeUnknown)),\n\t\t},\n\t\t{\n\t\t\t\"valid email\",\n\t\t\trequestDataJSON(validEmail),\n\t\t\t200,\n\t\t\tmockGetUserByID(models.User{}, nil),\n\t\t\tmockCreateUser(nil),\n\t\t},\n\t}\n\n\tfor _, v := range testdata {\n\t\tConvey(\"Given Signup controller\", t, func() {\n\t\t\thandler := Signup(v.createUser, v.getUserByID)\n\n\t\t\tConvey(fmt.Sprintf(\"When request with %s\", v.when), func() {\n\t\t\t\troute := \"\/users\"\n\t\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\t\tr.POST(route, handler)\n\t\t\t\treq, _ := http.NewRequest(\"POST\", route, bytes.NewBuffer(v.requestData))\n\t\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\t\tConvey(fmt.Sprintf(\"Response code should be equal to %d\", v.code), func() {\n\t\t\t\t\tSo(resp.Code, ShouldEqual, v.code)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t}\n}\n\nfunc TestVerifyEmail(t *testing.T) {\n\tConvey(\"Given verify email controller with expired session and errored getSessionByToken dependency\", t, func() {\n\t\tgetSessionByToken := mockGetSessionByToken(models.Session{}, errors.New(errors.ErrCodeUnknown))\n\t\thandler := VerifyEmail(getSessionByToken, nil, nil)\n\n\t\tConvey(\"When verify email\", func() {\n\t\t\troute := \"\/users\/1\/status\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.PUT(route, handler)\n\t\t\treq, _ := http.NewRequest(\"PUT\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 401\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 401)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given verify email controller with expired session and getSessionByToken dependency\", t, func() {\n\t\tgetSessionByToken := mockGetSessionByToken(models.Session{}, nil)\n\t\thandler := VerifyEmail(getSessionByToken, nil, nil)\n\n\t\tConvey(\"When verify email\", func() {\n\t\t\troute := \"\/users\/1\/status\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.PUT(route, handler)\n\t\t\treq, _ := http.NewRequest(\"PUT\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 401\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 401)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given verify email controller with errored getUserByID dependency\", t, func() {\n\t\tgetSessionByToken := mockGetSessionByToken(models.Session{UpdatedAt: time.Now()}, nil)\n\t\tgetUserByID := mockGetUserByID(models.User{}, errors.New(errors.ErrCodeUnknown))\n\t\thandler := VerifyEmail(getSessionByToken, getUserByID, nil)\n\n\t\tConvey(\"When verify email\", func() {\n\t\t\troute := \"\/users\/1\/status\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.PUT(route, handler)\n\t\t\treq, _ := http.NewRequest(\"PUT\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 500\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 500)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given verify email controller with banned user status\", t, func() {\n\t\tgetSessionByToken := mockGetSessionByToken(models.Session{UpdatedAt: time.Now()}, nil)\n\t\tgetUserByID := mockGetUserByID(models.User{Status: models.UserStatusBanned}, nil)\n\t\thandler := VerifyEmail(getSessionByToken, getUserByID, nil)\n\n\t\tConvey(\"When verify email\", func() {\n\t\t\troute := \"\/users\/1\/status\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.PUT(route, handler)\n\t\t\treq, _ := http.NewRequest(\"PUT\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 403\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 403)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given verify email controller with errored updateUser dependency\", t, func() {\n\t\tgetSessionByToken := mockGetSessionByToken(models.Session{UpdatedAt: time.Now()}, nil)\n\t\tgetUserByID := mockGetUserByID(models.User{}, nil)\n\t\tupdateUserStatus := mockUpdateUserStatus(errors.New(errors.ErrCodeUnknown))\n\t\thandler := VerifyEmail(getSessionByToken, getUserByID, updateUserStatus)\n\n\t\tConvey(\"When verify email\", func() {\n\t\t\troute := \"\/users\/1\/status\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.PUT(route, handler)\n\t\t\treq, _ := http.NewRequest(\"PUT\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 500\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 500)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given verify email controller with correct dependencies injected\", t, func() {\n\t\tgetSessionByToken := mockGetSessionByToken(models.Session{UpdatedAt: time.Now()}, nil)\n\t\tgetUserByID := mockGetUserByID(models.User{}, nil)\n\t\tupdateUserStatus := mockUpdateUserStatus(nil)\n\t\thandler := VerifyEmail(getSessionByToken, getUserByID, updateUserStatus)\n\n\t\tConvey(\"When verify email\", func() {\n\t\t\troute := \"\/users\/1\/status\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.PUT(route, handler)\n\t\t\treq, _ := http.NewRequest(\"PUT\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 200\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 200)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestGetUserInfo(t *testing.T) {\n\tConvey(\"Given get user info controller with errored getUserByID dependency\", t, func() {\n\t\tgetUserByID := mockGetUserByID(models.User{}, errors.New(errors.ErrCodeNotFound))\n\t\thandler := UserInfo(getUserByID)\n\n\t\tConvey(\"When get user info\", func() {\n\t\t\troute := \"\/users\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.Use(func(c *gin.Context) {\n\t\t\t\tc.Set(\"auth_token\", models.AuthToken{})\n\t\t\t})\n\t\t\tr.GET(route, handler)\n\t\t\treq, _ := http.NewRequest(\"GET\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 500\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 500)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given get user info controller with correctly dependencies injected\", t, func() {\n\t\tgetUserByID := mockGetUserByID(models.User{}, nil)\n\t\thandler := UserInfo(getUserByID)\n\n\t\tConvey(\"When get user info\", func() {\n\t\t\troute := \"\/users\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.Use(func(c *gin.Context) {\n\t\t\t\tc.Set(\"auth_token\", models.AuthToken{})\n\t\t\t})\n\t\t\tr.GET(route, handler)\n\t\t\treq, _ := http.NewRequest(\"GET\", route, nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 200\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 200)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestGetReferees(t *testing.T) {\n\tConvey(\"Given referee list controller\", t, func() {\n\t\thandler := RefereeList(nil, nil)\n\n\t\tConvey(\"When get reward list with invalid limit\", func() {\n\t\t\troute := \"\/users\/referees\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.Use(func(c *gin.Context) {\n\t\t\t\tc.Set(\"auth_token\", models.AuthToken{})\n\t\t\t})\n\t\t\tr.GET(route, handler)\n\t\t\treq, _ := http.NewRequest(\"GET\", route+\"?limit=3i\", nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 400\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 400)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given referee list controller with errored getRefereesSinceID dependency\", t, func() {\n\t\tsince := mockGetRefereesSince(nil, errors.New(errors.ErrCodeUnknown))\n\t\thandler := RefereeList(since, nil)\n\n\t\tConvey(\"When get referee list\", func() {\n\t\t\troute := \"\/users\/referees\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.Use(func(c *gin.Context) {\n\t\t\t\tc.Set(\"auth_token\", models.AuthToken{})\n\t\t\t})\n\t\t\tr.GET(route, handler)\n\t\t\treq, _ := http.NewRequest(\"GET\", route+\"?since=1234567890\", nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 500\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 500)\n\t\t\t})\n\t\t})\n\t})\n\n\tConvey(\"Given referee list controller with correct dependencies injected\", t, func() {\n\t\tuntil := mockGetRefereesUntil(nil, nil)\n\t\thandler := RefereeList(nil, until)\n\n\t\tConvey(\"When get referee list\", func() {\n\t\t\troute := \"\/users\/referees\"\n\t\t\t_, resp, r := gin.CreateTestContext()\n\t\t\tr.Use(func(c *gin.Context) {\n\t\t\t\tc.Set(\"auth_token\", models.AuthToken{})\n\t\t\t})\n\t\t\tr.GET(route, handler)\n\t\t\treq, _ := http.NewRequest(\"GET\", route+\"?until=1234567890\", nil)\n\t\t\tr.ServeHTTP(resp, req)\n\n\t\t\tConvey(\"Response code should be 200\", func() {\n\t\t\t\tSo(resp.Code, ShouldEqual, 200)\n\t\t\t})\n\t\t})\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Tomas Machalek <tomas.machalek@gmail.com>\n\/\/ Copyright 2017 Institute of the Czech National Corpus,\n\/\/                Faculty of Arts, Charles University\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage kontext\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/czcorpus\/klogproc\/conversion\"\n)\n\nvar (\n\tdatetimeRegexp = regexp.MustCompile(\"^(\\\\d{4}-\\\\d{2}-\\\\d{2})(\\\\s|T)([012]\\\\d:[0-5]\\\\d:[0-5]\\\\d(\\\\.\\\\d+))\")\n)\n\nfunc importDatetimeString(dateStr string) (string, error) {\n\tsrch := datetimeRegexp.FindStringSubmatch(dateStr)\n\tif len(srch) > 0 {\n\t\treturn fmt.Sprintf(\"%sT%s\", srch[1], srch[3]), nil\n\t}\n\treturn \"\", fmt.Errorf(\"Failed to import datetime \\\"%s\\\"\", dateStr)\n}\n\n\/\/ ImportJSONLog parses original JSON record with some\n\/\/ additional value corrections.\nfunc ImportJSONLog(jsonLine []byte) (*InputRecord, error) {\n\tvar record InputRecord\n\terr := json.Unmarshal(jsonLine, &record)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdt, err := importDatetimeString(record.Date)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trecord.Date = dt\n\treturn &record, nil\n}\n\n\/\/ ------------------------------------------------------------\n\n\/\/ Request is a simple representation of\n\/\/ HTTP request metadata used in KonText logging\ntype Request struct {\n\tHTTPForwardedFor string `json:\"HTTP_X_FORWARDED_FOR\"`\n\tHTTPUserAgent    string `json:\"HTTP_USER_AGENT\"`\n\tHTTPRemoteAddr   string `json:\"HTTP_REMOTE_ADDR\"`\n\tRemoteAddr       string `json:\"REMOTE_ADDR\"`\n}\n\n\/\/ ------------------------------------------------------------\n\n\/\/ ErrorRecord specifies a thrown error along with\n\/\/ optional anchor for easier search within text file\n\/\/ log\ntype ErrorRecord struct {\n\tName   string `json:\"name\"`\n\tAnchor string `json:\"anchor\"`\n}\n\n\/\/ ------------------------------------------------------------\n\n\/\/ InputRecord represents a parsed KonText record\ntype InputRecord struct {\n\tUserID   int                    `json:\"user_id\"`\n\tProcTime float32                `json:\"proc_time\"`\n\tDate     string                 `json:\"date\"`\n\tAction   string                 `json:\"action\"`\n\tRequest  Request                `json:\"request\"`\n\tParams   map[string]interface{} `json:\"params\"`\n\tPID      int                    `json:\"pid\"`\n\tSettings map[string]interface{} `json:\"settings\"`\n\tError    ErrorRecord            `json:\"error\"`\n}\n\n\/\/ GetTime returns record's time as a Golang's Time\n\/\/ instance. Please note that the value is truncated\n\/\/ to seconds.\nfunc (rec *InputRecord) GetTime() time.Time {\n\treturn conversion.ConvertDatetimeString(rec.Date)\n}\n\n\/\/ GetClientIP returns a client IP no matter in which\n\/\/ part of the record it was found\n\/\/ (e.g. REMOTE_ADDR vs. HTTP_REMOTE_ADDR vs. HTTP_FORWARDED_FOR)\nfunc (rec *InputRecord) GetClientIP() net.IP {\n\tif rec.Request.HTTPForwardedFor != \"\" {\n\t\treturn net.ParseIP(rec.Request.HTTPForwardedFor)\n\n\t} else if rec.Request.HTTPRemoteAddr != \"\" {\n\t\treturn net.ParseIP(rec.Request.HTTPRemoteAddr)\n\n\t} else if rec.Request.RemoteAddr != \"\" {\n\t\treturn net.ParseIP(rec.Request.RemoteAddr)\n\t}\n\treturn make([]byte, 0)\n}\n\n\/\/ GetUserAgent returns a raw HTTP user agent info as provided by the client\nfunc (rec *InputRecord) GetUserAgent() string {\n\treturn rec.Request.HTTPUserAgent\n}\n\n\/\/ IsProcessable returns true if there was no error in reading the record\nfunc (rec *InputRecord) IsProcessable() bool {\n\treturn true\n}\n\n\/\/ GetStringParam fetches a string parameter from\n\/\/ a special \"params\" sub-object\nfunc (rec *InputRecord) GetStringParam(name string) string {\n\tswitch v := rec.Params[name].(type) {\n\tcase string:\n\t\treturn v\n\t}\n\treturn \"\"\n}\n\n\/\/ GetIntParam fetches an integer parameter from\n\/\/ a special \"params\" sub-object\nfunc (rec *InputRecord) GetIntParam(name string) int {\n\tswitch v := rec.Params[name].(type) {\n\tcase int:\n\t\treturn v\n\t}\n\treturn -1\n}\n\n\/\/ GetAlignedCorpora fetches aligned corpora names from arguments\n\/\/ found in record's \"Params\" attribute. It isolates\n\/\/ user from miscellaneous idiosyncrasies of KonText\/Bonito\n\/\/ URL parameter handling (= it's not always that straightforward\n\/\/ to detect aligned languages from raw URL).\nfunc (rec *InputRecord) GetAlignedCorpora() []string {\n\ttmp := make(map[string]bool)\n\tfor k := range rec.Params {\n\t\tif strings.HasPrefix(k, \"queryselector_\") {\n\t\t\ttmp[k[len(\"queryselector_\"):]] = true\n\t\t}\n\t\tif strings.HasPrefix(k, \"pcq_pos_neg_\") {\n\t\t\ttmp[k[len(\"pcq_pos_neg_\"):]] = true\n\t\t}\n\t}\n\tans := make([]string, len(tmp))\n\ti := 0\n\tfor k := range tmp {\n\t\tans[i] = k\n\t\ti++\n\t}\n\treturn ans\n}\n<commit_msg>Fix dt parsing<commit_after>\/\/ Copyright 2017 Tomas Machalek <tomas.machalek@gmail.com>\n\/\/ Copyright 2017 Institute of the Czech National Corpus,\n\/\/                Faculty of Arts, Charles University\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage kontext\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/czcorpus\/klogproc\/conversion\"\n)\n\nvar (\n\tdatetimeRegexp = regexp.MustCompile(\"^(\\\\d{4}-\\\\d{2}-\\\\d{2})(\\\\s|T)([012]\\\\d:[0-5]\\\\d:[0-5]\\\\d(\\\\.\\\\d+))\")\n)\n\nfunc importDatetimeString(dateStr string) (string, error) {\n\tsrch := datetimeRegexp.FindStringSubmatch(dateStr)\n\tif len(srch) > 0 {\n\t\treturn fmt.Sprintf(\"%sT%s\", srch[1], srch[3]), nil\n\t}\n\treturn \"\", fmt.Errorf(\"Failed to import datetime \\\"%s\\\"\", dateStr)\n}\n\n\/\/ ImportJSONLog parses original JSON record with some\n\/\/ additional value corrections.\nfunc ImportJSONLog(jsonLine []byte) (*InputRecord, error) {\n\tvar record InputRecord\n\terr := json.Unmarshal(jsonLine, &record)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdt, err := importDatetimeString(record.Date)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trecord.Date = dt\n\treturn &record, nil\n}\n\n\/\/ ------------------------------------------------------------\n\n\/\/ Request is a simple representation of\n\/\/ HTTP request metadata used in KonText logging\ntype Request struct {\n\tHTTPForwardedFor string `json:\"HTTP_X_FORWARDED_FOR\"`\n\tHTTPUserAgent    string `json:\"HTTP_USER_AGENT\"`\n\tHTTPRemoteAddr   string `json:\"HTTP_REMOTE_ADDR\"`\n\tRemoteAddr       string `json:\"REMOTE_ADDR\"`\n}\n\n\/\/ ------------------------------------------------------------\n\n\/\/ ErrorRecord specifies a thrown error along with\n\/\/ optional anchor for easier search within text file\n\/\/ log\ntype ErrorRecord struct {\n\tName   string `json:\"name\"`\n\tAnchor string `json:\"anchor\"`\n}\n\n\/\/ ------------------------------------------------------------\n\n\/\/ InputRecord represents a parsed KonText record\ntype InputRecord struct {\n\tUserID   int                    `json:\"user_id\"`\n\tProcTime float32                `json:\"proc_time\"`\n\tDate     string                 `json:\"date\"`\n\tAction   string                 `json:\"action\"`\n\tRequest  Request                `json:\"request\"`\n\tParams   map[string]interface{} `json:\"params\"`\n\tPID      int                    `json:\"pid\"`\n\tSettings map[string]interface{} `json:\"settings\"`\n\tError    ErrorRecord            `json:\"error\"`\n}\n\n\/\/ GetTime returns record's time as a Golang's Time\n\/\/ instance. Please note that the value is truncated\n\/\/ to seconds.\nfunc (rec *InputRecord) GetTime() time.Time {\n\treturn conversion.ConvertDatetimeStringWithMillisNoTZ(rec.Date)\n}\n\n\/\/ GetClientIP returns a client IP no matter in which\n\/\/ part of the record it was found\n\/\/ (e.g. REMOTE_ADDR vs. HTTP_REMOTE_ADDR vs. HTTP_FORWARDED_FOR)\nfunc (rec *InputRecord) GetClientIP() net.IP {\n\tif rec.Request.HTTPForwardedFor != \"\" {\n\t\treturn net.ParseIP(rec.Request.HTTPForwardedFor)\n\n\t} else if rec.Request.HTTPRemoteAddr != \"\" {\n\t\treturn net.ParseIP(rec.Request.HTTPRemoteAddr)\n\n\t} else if rec.Request.RemoteAddr != \"\" {\n\t\treturn net.ParseIP(rec.Request.RemoteAddr)\n\t}\n\treturn make([]byte, 0)\n}\n\n\/\/ GetUserAgent returns a raw HTTP user agent info as provided by the client\nfunc (rec *InputRecord) GetUserAgent() string {\n\treturn rec.Request.HTTPUserAgent\n}\n\n\/\/ IsProcessable returns true if there was no error in reading the record\nfunc (rec *InputRecord) IsProcessable() bool {\n\treturn true\n}\n\n\/\/ GetStringParam fetches a string parameter from\n\/\/ a special \"params\" sub-object\nfunc (rec *InputRecord) GetStringParam(name string) string {\n\tswitch v := rec.Params[name].(type) {\n\tcase string:\n\t\treturn v\n\t}\n\treturn \"\"\n}\n\n\/\/ GetIntParam fetches an integer parameter from\n\/\/ a special \"params\" sub-object\nfunc (rec *InputRecord) GetIntParam(name string) int {\n\tswitch v := rec.Params[name].(type) {\n\tcase int:\n\t\treturn v\n\t}\n\treturn -1\n}\n\n\/\/ GetAlignedCorpora fetches aligned corpora names from arguments\n\/\/ found in record's \"Params\" attribute. It isolates\n\/\/ user from miscellaneous idiosyncrasies of KonText\/Bonito\n\/\/ URL parameter handling (= it's not always that straightforward\n\/\/ to detect aligned languages from raw URL).\nfunc (rec *InputRecord) GetAlignedCorpora() []string {\n\ttmp := make(map[string]bool)\n\tfor k := range rec.Params {\n\t\tif strings.HasPrefix(k, \"queryselector_\") {\n\t\t\ttmp[k[len(\"queryselector_\"):]] = true\n\t\t}\n\t\tif strings.HasPrefix(k, \"pcq_pos_neg_\") {\n\t\t\ttmp[k[len(\"pcq_pos_neg_\"):]] = true\n\t\t}\n\t}\n\tans := make([]string, len(tmp))\n\ti := 0\n\tfor k := range tmp {\n\t\tans[i] = k\n\t\ti++\n\t}\n\treturn ans\n}\n<|endoftext|>"}
{"text":"<commit_before>package worker\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/funkygao\/fae\/servant\/mysql\"\n\t\"github.com\/funkygao\/gafka\/cmd\/kateway\/job\"\n\tjm \"github.com\/funkygao\/gafka\/cmd\/kateway\/job\/mysql\"\n\t\"github.com\/funkygao\/gafka\/cmd\/kateway\/store\"\n\tlog \"github.com\/funkygao\/log4go\"\n)\n\n\/\/ Worker polls a single JobQueue and handle each Job.\ntype Worker struct {\n\tparentId       string \/\/ controller short id\n\tcluster, topic string\n\tmc             *mysql.MysqlCluster\n\tstopper        <-chan struct{}\n\tdueJobs        chan job.JobItem\n\tauditor        log.Logger\n\n\t\/\/ cached values\n\tappid string\n\taid   int\n\ttable string\n\tident string\n}\n\nfunc New(parentId, cluster, topic string, mc *mysql.MysqlCluster,\n\tstopper <-chan struct{}, auditor log.Logger) *Worker {\n\tthis := &Worker{\n\t\tparentId: parentId,\n\t\tcluster:  cluster,\n\t\ttopic:    topic,\n\t\tmc:       mc,\n\t\tstopper:  stopper,\n\t\tdueJobs:  make(chan job.JobItem, 200),\n\t\tauditor:  auditor,\n\t}\n\n\tthis.appid = topic[:strings.IndexByte(topic, '.')]\n\tthis.aid = jm.App_id(this.appid)\n\tthis.table = jm.JobTable(topic)\n\tthis.ident = fmt.Sprintf(\"worker{cluster:%s app:%s aid:%d topic:%s table:%s}\",\n\t\tthis.cluster, this.appid, this.aid, this.topic, this.table)\n\n\treturn this\n}\n\n\/\/ poll mysql for due jobs and send to kafka.\nfunc (this *Worker) Run() {\n\tlog.Trace(\"starting %s\", this.Ident())\n\n\tvar (\n\t\twg   sync.WaitGroup\n\t\titem job.JobItem\n\t\ttick = time.NewTicker(time.Second)\n\t\tsql  = fmt.Sprintf(\"SELECT job_id,app_id,payload,due_time FROM %s WHERE due_time<=?\", this.table)\n\t)\n\n\t\/\/ handler pool FIXME\n\tfor i := 0; i < 5; i++ {\n\t\twg.Add(1)\n\t\tgo this.handleDueJobs(&wg)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-this.stopper:\n\t\t\tlog.Debug(\"%s stopping\", this.ident)\n\t\t\twg.Wait()\n\t\t\treturn\n\n\t\tcase now := <-tick.C:\n\t\t\trows, err := this.mc.Query(jm.AppPool, this.topic, this.aid, sql, now.Unix())\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"%s: %v\", this.ident, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor rows.Next() {\n\t\t\t\t\/\/ FIXME ctime not handled\n\t\t\t\terr = rows.Scan(&item.JobId, &item.AppId, &item.Payload, &item.DueTime)\n\t\t\t\tif err == nil {\n\t\t\t\t\tthis.dueJobs <- item\n\t\t\t\t\tlog.Debug(\"%s due %s\", this.ident, item)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Error(\"%s: %s\", this.ident, err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif err = rows.Err(); err != nil {\n\t\t\t\tlog.Error(\"%s: %s\", this.ident, err)\n\t\t\t}\n\n\t\t\trows.Close()\n\t\t}\n\t}\n\n}\n\n\/\/ TODO batch DELETE\/INSERT for better performance.\nfunc (this *Worker) handleDueJobs(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tvar (\n\t\tsqlDeleteJob     = fmt.Sprintf(\"DELETE FROM %s WHERE job_id=?\", this.table)\n\t\tsqlInsertArchive = fmt.Sprintf(\"INSERT INTO %s(app_id,job_id,payload,ctime,due_time,invoke_time,actor_id) VALUES(?,?,?,?,?,?,?)\",\n\t\t\tjm.HistoryTable(this.topic))\n\t)\n\tfor {\n\t\tselect {\n\t\tcase <-this.stopper:\n\t\t\treturn\n\n\t\tcase item := <-this.dueJobs:\n\t\t\tlog.Debug(\"%s handling %s\", this.ident, item)\n\t\t\taffectedRows, _, err := this.mc.Exec(jm.AppPool, this.table, this.aid, sqlDeleteJob, item.JobId)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"%s: %s\", this.ident, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif affectedRows == 0 {\n\t\t\t\t\/\/ race fails, client Delete wins\n\t\t\t\tlog.Warn(\"%s: %s race fails\", this.ident, item)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlog.Debug(\"%s deleted from real time table: %s\", this.ident, item)\n\t\t\t_, _, err = store.DefaultPubStore.SyncPub(this.cluster, this.topic, nil, item.Payload)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"%s: %s\", this.ident, err)\n\t\t\t\t\/\/ TODO insert back to job table\n\t\t\t} else {\n\t\t\t\tthis.auditor.Trace(item.String())\n\n\t\t\t\t\/\/ mv job to archive table\n\t\t\t\t_, _, err = this.mc.Exec(jm.AppPool, this.table, this.aid, sqlInsertArchive,\n\t\t\t\t\titem.AppId, item.JobId, item.Payload, item.Ctime, item.DueTime, time.Now().UnixNano(), this.parentId)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"%s: %s\", this.ident, err)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Debug(\"%s archived %s\", this.ident, item)\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n}\n\nfunc (this *Worker) Ident() string {\n\treturn this.ident\n}\n<commit_msg>pool size=1, to guarantee the delivery order<commit_after>package worker\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/funkygao\/fae\/servant\/mysql\"\n\t\"github.com\/funkygao\/gafka\/cmd\/kateway\/job\"\n\tjm \"github.com\/funkygao\/gafka\/cmd\/kateway\/job\/mysql\"\n\t\"github.com\/funkygao\/gafka\/cmd\/kateway\/store\"\n\tlog \"github.com\/funkygao\/log4go\"\n)\n\n\/\/ Worker polls a single JobQueue and handle each Job.\ntype Worker struct {\n\tparentId       string \/\/ controller short id\n\tcluster, topic string\n\tmc             *mysql.MysqlCluster\n\tstopper        <-chan struct{}\n\tdueJobs        chan job.JobItem\n\tauditor        log.Logger\n\n\t\/\/ cached values\n\tappid string\n\taid   int\n\ttable string\n\tident string\n}\n\nfunc New(parentId, cluster, topic string, mc *mysql.MysqlCluster,\n\tstopper <-chan struct{}, auditor log.Logger) *Worker {\n\tthis := &Worker{\n\t\tparentId: parentId,\n\t\tcluster:  cluster,\n\t\ttopic:    topic,\n\t\tmc:       mc,\n\t\tstopper:  stopper,\n\t\tdueJobs:  make(chan job.JobItem, 200),\n\t\tauditor:  auditor,\n\t}\n\n\tthis.appid = topic[:strings.IndexByte(topic, '.')]\n\tthis.aid = jm.App_id(this.appid)\n\tthis.table = jm.JobTable(topic)\n\tthis.ident = fmt.Sprintf(\"worker{cluster:%s app:%s aid:%d topic:%s table:%s}\",\n\t\tthis.cluster, this.appid, this.aid, this.topic, this.table)\n\n\treturn this\n}\n\n\/\/ poll mysql for due jobs and send to kafka.\nfunc (this *Worker) Run() {\n\tlog.Trace(\"starting %s\", this.Ident())\n\n\tvar (\n\t\twg   sync.WaitGroup\n\t\titem job.JobItem\n\t\ttick = time.NewTicker(time.Second)\n\t\tsql  = fmt.Sprintf(\"SELECT job_id,app_id,payload,due_time FROM %s WHERE due_time<=?\", this.table)\n\t)\n\n\t\/\/ handler pool, currently to guarantee the order, we use pool=1\n\tfor i := 0; i < 1; i++ {\n\t\twg.Add(1)\n\t\tgo this.handleDueJobs(&wg)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase <-this.stopper:\n\t\t\tlog.Debug(\"%s stopping\", this.ident)\n\t\t\twg.Wait()\n\t\t\treturn\n\n\t\tcase now := <-tick.C:\n\t\t\trows, err := this.mc.Query(jm.AppPool, this.topic, this.aid, sql, now.Unix())\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"%s: %v\", this.ident, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor rows.Next() {\n\t\t\t\t\/\/ FIXME ctime not handled\n\t\t\t\terr = rows.Scan(&item.JobId, &item.AppId, &item.Payload, &item.DueTime)\n\t\t\t\tif err == nil {\n\t\t\t\t\tthis.dueJobs <- item\n\t\t\t\t\tlog.Debug(\"%s due %s\", this.ident, item)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Error(\"%s: %s\", this.ident, err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif err = rows.Err(); err != nil {\n\t\t\t\tlog.Error(\"%s: %s\", this.ident, err)\n\t\t\t}\n\n\t\t\trows.Close()\n\t\t}\n\t}\n\n}\n\n\/\/ TODO batch DELETE\/INSERT for better performance.\nfunc (this *Worker) handleDueJobs(wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\n\tvar (\n\t\tsqlDeleteJob     = fmt.Sprintf(\"DELETE FROM %s WHERE job_id=?\", this.table)\n\t\tsqlInsertArchive = fmt.Sprintf(\"INSERT INTO %s(app_id,job_id,payload,ctime,due_time,invoke_time,actor_id) VALUES(?,?,?,?,?,?,?)\",\n\t\t\tjm.HistoryTable(this.topic))\n\t)\n\tfor {\n\t\tselect {\n\t\tcase <-this.stopper:\n\t\t\treturn\n\n\t\tcase item := <-this.dueJobs:\n\t\t\tlog.Debug(\"%s handling %s\", this.ident, item)\n\t\t\taffectedRows, _, err := this.mc.Exec(jm.AppPool, this.table, this.aid, sqlDeleteJob, item.JobId)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"%s: %s\", this.ident, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif affectedRows == 0 {\n\t\t\t\t\/\/ race fails, client Delete wins\n\t\t\t\tlog.Warn(\"%s: %s race fails\", this.ident, item)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlog.Debug(\"%s deleted from real time table: %s\", this.ident, item)\n\t\t\t_, _, err = store.DefaultPubStore.SyncPub(this.cluster, this.topic, nil, item.Payload)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"%s: %s\", this.ident, err)\n\t\t\t\t\/\/ TODO insert back to job table\n\t\t\t} else {\n\t\t\t\tthis.auditor.Trace(item.String())\n\n\t\t\t\t\/\/ mv job to archive table\n\t\t\t\t_, _, err = this.mc.Exec(jm.AppPool, this.table, this.aid, sqlInsertArchive,\n\t\t\t\t\titem.AppId, item.JobId, item.Payload, item.Ctime, item.DueTime, time.Now().UnixNano(), this.parentId)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(\"%s: %s\", this.ident, err)\n\t\t\t\t} else {\n\t\t\t\t\tlog.Debug(\"%s archived %s\", this.ident, item)\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n}\n\nfunc (this *Worker) Ident() string {\n\treturn this.ident\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\tgc \"launchpad.net\/gocheck\"\n\n\t\"launchpad.net\/juju-core\/constraints\"\n\t\"launchpad.net\/juju-core\/instance\"\n\tjujutesting \"launchpad.net\/juju-core\/juju\/testing\"\n\t\"launchpad.net\/juju-core\/state\"\n\t\"launchpad.net\/juju-core\/testing\"\n\tjc \"launchpad.net\/juju-core\/testing\/checkers\"\n)\n\ntype AddMachineSuite struct {\n\tjujutesting.RepoSuite\n}\n\nvar _ = gc.Suite(&AddMachineSuite{})\n\nfunc runAddMachine(c *gc.C, args ...string) error {\n\t_, err := testing.RunCommand(c, &AddMachineCommand{}, args)\n\treturn err\n}\n\nfunc (s *AddMachineSuite) TestAddMachine(c *gc.C) {\n\terr := runAddMachine(c)\n\tc.Assert(err, gc.IsNil)\n\tm, err := s.State.Machine(\"0\")\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(m.Life(), gc.Equals, state.Alive)\n\tc.Assert(m.Series(), gc.DeepEquals, \"precise\")\n\tmcons, err := m.Constraints()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(&mcons, jc.Satisfies, constraints.IsEmpty)\n}\n\nfunc (s *AddMachineSuite) TestAddMachineWithSeries(c *gc.C) {\n\terr := runAddMachine(c, \"--series\", \"series\")\n\tc.Assert(err, gc.IsNil)\n\tm, err := s.State.Machine(\"0\")\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(m.Series(), gc.DeepEquals, \"series\")\n}\n\nfunc (s *AddMachineSuite) TestAddMachineWithConstraints(c *gc.C) {\n\terr := runAddMachine(c, \"--constraints\", \"mem=4G\")\n\tc.Assert(err, gc.IsNil)\n\tm, err := s.State.Machine(\"0\")\n\tc.Assert(err, gc.IsNil)\n\tmcons, err := m.Constraints()\n\tc.Assert(err, gc.IsNil)\n\texpectedCons := constraints.MustParse(\"mem=4G\")\n\tc.Assert(mcons, gc.DeepEquals, expectedCons)\n}\n\nfunc (s *AddMachineSuite) _assertAddContainer(c *gc.C, parentId, containerId string, ctype instance.ContainerType) {\n\tm, err := s.State.Machine(parentId)\n\tc.Assert(err, gc.IsNil)\n\tcontainers, err := m.Containers()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(containers, gc.DeepEquals, []string{containerId})\n\tcontainer, err := s.State.Machine(containerId)\n\tc.Assert(err, gc.IsNil)\n\tcontainers, err = container.Containers()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(containers, gc.DeepEquals, []string(nil))\n\tc.Assert(container.ContainerType(), gc.Equals, ctype)\n}\n\nfunc (s *AddMachineSuite) TestAddContainerToNewMachine(c *gc.C) {\n\tfor i, ctype := range instance.SupportedContainerTypes {\n\t\terr := runAddMachine(c, fmt.Sprintf(\"%s\", ctype))\n\t\tc.Assert(err, gc.IsNil)\n\t\ts._assertAddContainer(c, strconv.Itoa(i), fmt.Sprintf(\"%d\/%s\/0\", i, ctype), ctype)\n\t}\n}\n\nfunc (s *AddMachineSuite) TestAddContainerToExistingMachine(c *gc.C) {\n\terr := runAddMachine(c)\n\tc.Assert(err, gc.IsNil)\n\terr = runAddMachine(c)\n\tc.Assert(err, gc.IsNil)\n\tfor i, container := range instance.SupportedContainerTypes {\n\t\terr := runAddMachine(c, fmt.Sprintf(\"%s:1\", container))\n\t\tc.Assert(err, gc.IsNil)\n\t\ts._assertAddContainer(c, \"1\", fmt.Sprintf(\"1\/%s\/%d\", container, i), container)\n\t}\n}\n\nfunc (s *AddMachineSuite) TestAddMachineErrors(c *gc.C) {\n\terr := runAddMachine(c, \":lxc\")\n\tc.Assert(err, gc.ErrorMatches, `malformed container argument \":lxc\"`)\n\terr = runAddMachine(c, \"lxc:\")\n\tc.Assert(err, gc.ErrorMatches, `malformed container argument \"lxc:\"`)\n\terr = runAddMachine(c, \"2\")\n\tc.Assert(err, gc.ErrorMatches, `malformed container argument \"2\"`)\n\terr = runAddMachine(c, \"foo\")\n\tc.Assert(err, gc.ErrorMatches, `malformed container argument \"foo\"`)\n\terr = runAddMachine(c, \"lxc\", \"--constraints\", \"container=lxc\")\n\tc.Assert(err, gc.ErrorMatches, `container constraint \"lxc\" not allowed when adding a machine`)\n}\n<commit_msg>Again, loop happens more than once.<commit_after>\/\/ Copyright 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\tgc \"launchpad.net\/gocheck\"\n\n\t\"launchpad.net\/juju-core\/constraints\"\n\t\"launchpad.net\/juju-core\/instance\"\n\tjujutesting \"launchpad.net\/juju-core\/juju\/testing\"\n\t\"launchpad.net\/juju-core\/state\"\n\t\"launchpad.net\/juju-core\/testing\"\n\tjc \"launchpad.net\/juju-core\/testing\/checkers\"\n)\n\ntype AddMachineSuite struct {\n\tjujutesting.RepoSuite\n}\n\nvar _ = gc.Suite(&AddMachineSuite{})\n\nfunc runAddMachine(c *gc.C, args ...string) error {\n\t_, err := testing.RunCommand(c, &AddMachineCommand{}, args)\n\treturn err\n}\n\nfunc (s *AddMachineSuite) TestAddMachine(c *gc.C) {\n\terr := runAddMachine(c)\n\tc.Assert(err, gc.IsNil)\n\tm, err := s.State.Machine(\"0\")\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(m.Life(), gc.Equals, state.Alive)\n\tc.Assert(m.Series(), gc.DeepEquals, \"precise\")\n\tmcons, err := m.Constraints()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(&mcons, jc.Satisfies, constraints.IsEmpty)\n}\n\nfunc (s *AddMachineSuite) TestAddMachineWithSeries(c *gc.C) {\n\terr := runAddMachine(c, \"--series\", \"series\")\n\tc.Assert(err, gc.IsNil)\n\tm, err := s.State.Machine(\"0\")\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(m.Series(), gc.DeepEquals, \"series\")\n}\n\nfunc (s *AddMachineSuite) TestAddMachineWithConstraints(c *gc.C) {\n\terr := runAddMachine(c, \"--constraints\", \"mem=4G\")\n\tc.Assert(err, gc.IsNil)\n\tm, err := s.State.Machine(\"0\")\n\tc.Assert(err, gc.IsNil)\n\tmcons, err := m.Constraints()\n\tc.Assert(err, gc.IsNil)\n\texpectedCons := constraints.MustParse(\"mem=4G\")\n\tc.Assert(mcons, gc.DeepEquals, expectedCons)\n}\n\nfunc (s *AddMachineSuite) _assertAddContainer(c *gc.C, parentId, containerId string, ctype instance.ContainerType) {\n\tm, err := s.State.Machine(parentId)\n\tc.Assert(err, gc.IsNil)\n\tcontainers, err := m.Containers()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(containers, gc.DeepEquals, []string{containerId})\n\tcontainer, err := s.State.Machine(containerId)\n\tc.Assert(err, gc.IsNil)\n\tcontainers, err = container.Containers()\n\tc.Assert(err, gc.IsNil)\n\tc.Assert(containers, gc.DeepEquals, []string(nil))\n\tc.Assert(container.ContainerType(), gc.Equals, ctype)\n}\n\nfunc (s *AddMachineSuite) TestAddContainerToNewMachine(c *gc.C) {\n\tfor i, ctype := range instance.SupportedContainerTypes {\n\t\terr := runAddMachine(c, fmt.Sprintf(\"%s\", ctype))\n\t\tc.Assert(err, gc.IsNil)\n\t\ts._assertAddContainer(c, strconv.Itoa(i), fmt.Sprintf(\"%d\/%s\/0\", i, ctype), ctype)\n\t}\n}\n\nfunc (s *AddMachineSuite) TestAddContainerToExistingMachine(c *gc.C) {\n\terr := runAddMachine(c)\n\tc.Assert(err, gc.IsNil)\n\tfor i, container := range instance.SupportedContainerTypes {\n\t\tmachineNum := strconv.Itoa(i + 1)\n\t\terr = runAddMachine(c)\n\t\tc.Assert(err, gc.IsNil)\n\t\terr := runAddMachine(c, fmt.Sprintf(\"%s:%s\", container, machineNum))\n\t\tc.Assert(err, gc.IsNil)\n\t\ts._assertAddContainer(c, machineNum, fmt.Sprintf(\"%s\/%s\/0\", machineNum, container), container)\n\t}\n}\n\nfunc (s *AddMachineSuite) TestAddMachineErrors(c *gc.C) {\n\terr := runAddMachine(c, \":lxc\")\n\tc.Assert(err, gc.ErrorMatches, `malformed container argument \":lxc\"`)\n\terr = runAddMachine(c, \"lxc:\")\n\tc.Assert(err, gc.ErrorMatches, `malformed container argument \"lxc:\"`)\n\terr = runAddMachine(c, \"2\")\n\tc.Assert(err, gc.ErrorMatches, `malformed container argument \"2\"`)\n\terr = runAddMachine(c, \"foo\")\n\tc.Assert(err, gc.ErrorMatches, `malformed container argument \"foo\"`)\n\terr = runAddMachine(c, \"lxc\", \"--constraints\", \"container=lxc\")\n\tc.Assert(err, gc.ErrorMatches, `container constraint \"lxc\" not allowed when adding a machine`)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012-2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage service\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\n\t\"github.com\/juju\/cmd\"\n\t\"github.com\/juju\/names\"\n\t\"launchpad.net\/gnuflag\"\n\n\t\"github.com\/juju\/juju\/cmd\/envcmd\"\n\t\"github.com\/juju\/juju\/cmd\/juju\/block\"\n\t\"github.com\/juju\/juju\/environs\/config\"\n\t\"github.com\/juju\/juju\/provider\"\n)\n\n\/\/ UnitCommandBase provides support for commands which deploy units. It handles the parsing\n\/\/ and validation of --to and --num-units arguments.\ntype UnitCommandBase struct {\n\tToMachineSpec string\n\tNumUnits      int\n}\n\nfunc (c *UnitCommandBase) SetFlags(f *gnuflag.FlagSet) {\n\tf.IntVar(&c.NumUnits, \"num-units\", 1, \"\")\n\tf.StringVar(&c.ToMachineSpec, \"to\", \"\", \"the machine or container to deploy the unit in, bypasses constraints\")\n}\n\nfunc (c *UnitCommandBase) Init(args []string) error {\n\tif c.NumUnits < 1 {\n\t\treturn errors.New(\"--num-units must be a positive integer\")\n\t}\n\tif c.ToMachineSpec != \"\" {\n\t\tif c.NumUnits > 1 {\n\t\t\treturn errors.New(\"cannot use --num-units > 1 with --to\")\n\t\t}\n\t\tif !IsMachineOrNewContainer(c.ToMachineSpec) {\n\t\t\treturn fmt.Errorf(\"invalid --to parameter %q\", c.ToMachineSpec)\n\t\t}\n\n\t}\n\treturn nil\n}\n\n\/\/ TODO(anastasiamac) 2014-10-20 Bug#1383116\n\/\/ This exists to provide more context to the user about\n\/\/ why they cannot allocate units to machine 0. Remove\n\/\/ this when the local provider's machine 0 is a container.\n\/\/ TODO(cherylj) Unexport CheckProvider once deploy is moved under service\nfunc (c *UnitCommandBase) CheckProvider(conf *config.Config) error {\n\tif conf.Type() == provider.Local && c.ToMachineSpec == \"0\" {\n\t\treturn errors.New(\"machine 0 is the state server for a local environment and cannot host units\")\n\t}\n\treturn nil\n}\n\n\/\/ TODO(cherylj) Unexport GetClientConfig once deploy is moved under service\nvar GetClientConfig = func(client ServiceAddUnitAPI) (*config.Config, error) {\n\t\/\/ Separated into a variable for easy overrides\n\tattrs, err := client.EnvironmentGet()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn config.New(config.NoDefaults, attrs)\n}\n\n\/\/ AddUnitCommand is responsible adding additional units to a service.\ntype AddUnitCommand struct {\n\tenvcmd.EnvCommandBase\n\tUnitCommandBase\n\tServiceName string\n\tapi         ServiceAddUnitAPI\n}\n\nconst addUnitDoc = `\nAdding units to an existing service is a way to scale out an environment by\ndeploying more instances of a service.  Add-unit must be called on services that\nhave already been deployed via juju deploy.  \n\nBy default, services are deployed to newly provisioned machines.  Alternatively,\nservice units can be added to a specific existing machine using the --to\nargument.\n\nExamples:\n juju add-unit mysql -n 5          (Add 5 mysql units on 5 new machines)\n juju add-unit mysql --to 23       (Add a mysql unit to machine 23)\n juju add-unit mysql --to 24\/lxc\/3 (Add unit to lxc container 3 on host machine 24)\n juju add-unit mysql --to lxc:25   (Add unit to a new lxc container on host machine 25)\n`\n\nfunc (c *AddUnitCommand) Info() *cmd.Info {\n\treturn &cmd.Info{\n\t\tName:    \"add-unit\",\n\t\tArgs:    \"<service name>\",\n\t\tPurpose: \"add one or more units of an already-deployed service\",\n\t\tDoc:     addUnitDoc,\n\t}\n}\n\nfunc (c *AddUnitCommand) SetFlags(f *gnuflag.FlagSet) {\n\tc.UnitCommandBase.SetFlags(f)\n\tf.IntVar(&c.NumUnits, \"n\", 1, \"number of service units to add\")\n}\n\nfunc (c *AddUnitCommand) Init(args []string) error {\n\tswitch len(args) {\n\tcase 1:\n\t\tc.ServiceName = args[0]\n\tcase 0:\n\t\treturn errors.New(\"no service specified\")\n\t}\n\tif err := cmd.CheckEmpty(args[1:]); err != nil {\n\t\treturn err\n\t}\n\treturn c.UnitCommandBase.Init(args)\n}\n\n\/\/ ServiceAddUnitAPI defines the methods on the client API\n\/\/ that the service add-unit command calls.\ntype ServiceAddUnitAPI interface {\n\tClose() error\n\tAddServiceUnits(service string, numUnits int, machineSpec string) ([]string, error)\n\tEnvironmentGet() (map[string]interface{}, error)\n}\n\nfunc (c *AddUnitCommand) getAPI() (ServiceAddUnitAPI, error) {\n\tif c.api != nil {\n\t\treturn c.api, nil\n\t}\n\treturn c.NewAPIClient()\n}\n\n\/\/ Run connects to the environment specified on the command line\n\/\/ and calls AddServiceUnits for the given service.\nfunc (c *AddUnitCommand) Run(_ *cmd.Context) error {\n\tapiclient, err := c.getAPI()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer apiclient.Close()\n\n\tconf, err := GetClientConfig(apiclient)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.CheckProvider(conf); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = apiclient.AddServiceUnits(c.ServiceName, c.NumUnits, c.ToMachineSpec)\n\treturn block.ProcessBlockedError(err, block.BlockChange)\n}\n\nconst (\n\tdeployTarget = \"^(\" + names.ContainerTypeSnippet + \":)?\" + names.MachineSnippet + \"$\"\n)\n\nvar (\n\tvalidMachineOrNewContainer = regexp.MustCompile(deployTarget)\n)\n\n\/\/ IsMachineOrNewContainer returns whether spec is a valid machine id\n\/\/ or new container definition.\nfunc IsMachineOrNewContainer(spec string) bool {\n\treturn validMachineOrNewContainer.MatchString(spec)\n}\n<commit_msg>Address review comments for service add-unit<commit_after>\/\/ Copyright 2012-2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage service\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\n\t\"github.com\/juju\/cmd\"\n\t\"github.com\/juju\/names\"\n\t\"launchpad.net\/gnuflag\"\n\n\t\"github.com\/juju\/juju\/cmd\/envcmd\"\n\t\"github.com\/juju\/juju\/cmd\/juju\/block\"\n\t\"github.com\/juju\/juju\/environs\/config\"\n\t\"github.com\/juju\/juju\/provider\"\n)\n\n\/\/ UnitCommandBase provides support for commands which deploy units. It handles the parsing\n\/\/ and validation of --to and --num-units arguments.\ntype UnitCommandBase struct {\n\tToMachineSpec string\n\tNumUnits      int\n}\n\nfunc (c *UnitCommandBase) SetFlags(f *gnuflag.FlagSet) {\n\tf.IntVar(&c.NumUnits, \"num-units\", 1, \"\")\n\tf.StringVar(&c.ToMachineSpec, \"to\", \"\", \"the machine or container to deploy the unit in, bypasses constraints\")\n}\n\nfunc (c *UnitCommandBase) Init(args []string) error {\n\tif c.NumUnits < 1 {\n\t\treturn errors.New(\"--num-units must be a positive integer\")\n\t}\n\tif c.ToMachineSpec != \"\" {\n\t\tif c.NumUnits > 1 {\n\t\t\treturn errors.New(\"cannot use --num-units > 1 with --to\")\n\t\t}\n\t\tif !IsMachineOrNewContainer(c.ToMachineSpec) {\n\t\t\treturn fmt.Errorf(\"invalid --to parameter %q\", c.ToMachineSpec)\n\t\t}\n\n\t}\n\treturn nil\n}\n\n\/\/ TODO(anastasiamac) 2014-10-20 Bug#1383116\n\/\/ This exists to provide more context to the user about\n\/\/ why they cannot allocate units to machine 0. Remove\n\/\/ this when the local provider's machine 0 is a container.\n\/\/ TODO(cherylj) Unexport CheckProvider once deploy is moved under service\nfunc (c *UnitCommandBase) CheckProvider(conf *config.Config) error {\n\tif conf.Type() == provider.Local && c.ToMachineSpec == \"0\" {\n\t\treturn errors.New(\"machine 0 is the state server for a local environment and cannot host units\")\n\t}\n\treturn nil\n}\n\n\/\/ TODO(cherylj) Unexport GetClientConfig and make it a standard function\n\/\/ once deploy is moved under service\nvar GetClientConfig = func(client ServiceAddUnitAPI) (*config.Config, error) {\n\t\/\/ Separated into a variable for easy overrides\n\tattrs, err := client.EnvironmentGet()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn config.New(config.NoDefaults, attrs)\n}\n\n\/\/ AddUnitCommand is responsible adding additional units to a service.\ntype AddUnitCommand struct {\n\tenvcmd.EnvCommandBase\n\tUnitCommandBase\n\tServiceName string\n\tapi         ServiceAddUnitAPI\n}\n\nconst addUnitDoc = `\nAdding units to an existing service is a way to scale out an environment by\ndeploying more instances of a service.  Add-unit must be called on services that\nhave already been deployed via juju deploy.\n\nBy default, services are deployed to newly provisioned machines.  Alternatively,\nservice units can be added to a specific existing machine using the --to\nargument.\n\nExamples:\n juju add-unit mysql -n 5          (Add 5 mysql units on 5 new machines)\n juju add-unit mysql --to 23       (Add a mysql unit to machine 23)\n juju add-unit mysql --to 24\/lxc\/3 (Add unit to lxc container 3 on host machine 24)\n juju add-unit mysql --to lxc:25   (Add unit to a new lxc container on host machine 25)\n`\n\nfunc (c *AddUnitCommand) Info() *cmd.Info {\n\treturn &cmd.Info{\n\t\tName:    \"add-unit\",\n\t\tArgs:    \"<service name>\",\n\t\tPurpose: \"add one or more units of an already-deployed service\",\n\t\tDoc:     addUnitDoc,\n\t}\n}\n\nfunc (c *AddUnitCommand) SetFlags(f *gnuflag.FlagSet) {\n\tc.UnitCommandBase.SetFlags(f)\n\tf.IntVar(&c.NumUnits, \"n\", 1, \"number of service units to add\")\n}\n\nfunc (c *AddUnitCommand) Init(args []string) error {\n\tswitch len(args) {\n\tcase 1:\n\t\tc.ServiceName = args[0]\n\tcase 0:\n\t\treturn errors.New(\"no service specified\")\n\t}\n\tif err := cmd.CheckEmpty(args[1:]); err != nil {\n\t\treturn err\n\t}\n\treturn c.UnitCommandBase.Init(args)\n}\n\n\/\/ ServiceAddUnitAPI defines the methods on the client API\n\/\/ that the service add-unit command calls.\ntype ServiceAddUnitAPI interface {\n\tClose() error\n\tAddServiceUnits(service string, numUnits int, machineSpec string) ([]string, error)\n\tEnvironmentGet() (map[string]interface{}, error)\n}\n\nfunc (c *AddUnitCommand) getAPI() (ServiceAddUnitAPI, error) {\n\tif c.api != nil {\n\t\treturn c.api, nil\n\t}\n\treturn c.NewAPIClient()\n}\n\n\/\/ Run connects to the environment specified on the command line\n\/\/ and calls AddServiceUnits for the given service.\nfunc (c *AddUnitCommand) Run(_ *cmd.Context) error {\n\tapiclient, err := c.getAPI()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer apiclient.Close()\n\n\tconf, err := GetClientConfig(apiclient)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.CheckProvider(conf); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = apiclient.AddServiceUnits(c.ServiceName, c.NumUnits, c.ToMachineSpec)\n\treturn block.ProcessBlockedError(err, block.BlockChange)\n}\n\n\/\/ deployTarget describes the format a machine or container target must match to be valid.\nconst deployTarget = \"^(\" + names.ContainerTypeSnippet + \":)?\" + names.MachineSnippet + \"$\"\n\nvar validMachineOrNewContainer = regexp.MustCompile(deployTarget)\n\n\/\/ IsMachineOrNewContainer returns whether spec is a valid machine id\n\/\/ or new container definition.\nfunc IsMachineOrNewContainer(spec string) bool {\n\treturn validMachineOrNewContainer.MatchString(spec)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/golang\/glog\"\n\tmultierror \"github.com\/hashicorp\/go-multierror\"\n\t\"github.com\/spf13\/cobra\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\n\tproxyconfig \"istio.io\/api\/proxy\/v1\/config\"\n\t\"istio.io\/pilot\/adapter\/config\/aggregate\"\n\t\"istio.io\/pilot\/adapter\/config\/crd\"\n\t\"istio.io\/pilot\/adapter\/config\/ingress\"\n\t\"istio.io\/pilot\/cmd\"\n\t\"istio.io\/pilot\/model\"\n\t\"istio.io\/pilot\/platform\"\n\t\"istio.io\/pilot\/platform\/consul\"\n\t\"istio.io\/pilot\/platform\/kube\"\n\t\"istio.io\/pilot\/proxy\"\n\t\"istio.io\/pilot\/proxy\/envoy\"\n\t\"istio.io\/pilot\/tools\/version\"\n)\n\n\/\/ ConsulArgs store the args related to Consul configuration\ntype ConsulArgs struct {\n\tconfig    string\n\tserverURL string\n}\n\ntype args struct {\n\tkubeconfig string\n\tmeshconfig string\n\n\t\/\/ ingress sync mode is set to off by default\n\tcontrollerOptions kube.ControllerOptions\n\tdiscoveryOptions  envoy.DiscoveryServiceOptions\n\n\tserviceregistry platform.ServiceRegistry\n\tconsulargs      ConsulArgs\n}\n\nvar (\n\tflags args\n\n\trootCmd = &cobra.Command{\n\t\tUse:   \"pilot\",\n\t\tShort: \"Istio Pilot\",\n\t\tLong:  \"Istio Pilot provides management plane functionality to the Istio service mesh and Istio Mixer.\",\n\t}\n\n\tdiscoveryCmd = &cobra.Command{\n\t\tUse:   \"discovery\",\n\t\tShort: \"Start Istio proxy discovery service\",\n\t\tRunE: func(c *cobra.Command, args []string) error {\n\n\t\t\t\/\/ receive mesh configuration\n\t\t\tmesh, fail := cmd.ReadMeshConfig(flags.meshconfig)\n\t\t\tif fail != nil {\n\t\t\t\tdefaultMesh := proxy.DefaultMeshConfig()\n\t\t\t\tmesh = &defaultMesh\n\t\t\t\tglog.Warningf(\"failed to read mesh configuration, using default: %v\", fail)\n\t\t\t}\n\t\t\tglog.V(2).Infof(\"mesh configuration %s\", spew.Sdump(mesh))\n\t\t\tglog.V(2).Infof(\"version %s\", version.Line())\n\t\t\tglog.V(2).Infof(\"flags %s\", spew.Sdump(flags))\n\n\t\t\tvar serviceController model.Controller\n\t\t\tvar configController model.ConfigStoreCache\n\t\t\tenvironment := proxy.Environment{\n\t\t\t\tMesh: mesh,\n\t\t\t}\n\n\t\t\tstop := make(chan struct{})\n\n\t\t\tconfigClient, err := crd.NewClient(flags.kubeconfig, model.ConfigDescriptor{\n\t\t\t\tmodel.RouteRule,\n\t\t\t\tmodel.EgressRule,\n\t\t\t\tmodel.DestinationPolicy,\n\t\t\t}, flags.controllerOptions.DomainSuffix)\n\t\t\tif err != nil {\n\t\t\t\treturn multierror.Prefix(err, \"failed to open a config client.\")\n\t\t\t}\n\n\t\t\tif err = configClient.RegisterResources(); err != nil {\n\t\t\t\treturn multierror.Prefix(err, \"failed to register custom resources.\")\n\t\t\t}\n\n\t\t\t\/\/ Set up values for input to discovery service in different platforms\n\t\t\tif flags.serviceregistry == platform.KubernetesRegistry || flags.serviceregistry == \"\" {\n\t\t\t\t_, client, kuberr := kube.CreateInterface(flags.kubeconfig)\n\t\t\t\tif kuberr != nil {\n\t\t\t\t\treturn multierror.Prefix(kuberr, \"failed to connect to Kubernetes API.\")\n\t\t\t\t}\n\n\t\t\t\tif flags.controllerOptions.Namespace == \"\" {\n\t\t\t\t\tflags.controllerOptions.Namespace = os.Getenv(\"POD_NAMESPACE\")\n\t\t\t\t}\n\n\t\t\t\tkubeController := kube.NewController(client, mesh, flags.controllerOptions)\n\t\t\t\tif mesh.IngressControllerMode == proxyconfig.ProxyMeshConfig_OFF {\n\t\t\t\t\tconfigController = crd.NewController(configClient, flags.controllerOptions)\n\t\t\t\t} else {\n\t\t\t\t\tconfigController, err = aggregate.MakeCache([]model.ConfigStoreCache{\n\t\t\t\t\t\tcrd.NewController(configClient, flags.controllerOptions),\n\t\t\t\t\t\tingress.NewController(client, mesh, flags.controllerOptions),\n\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tenvironment.ServiceDiscovery = kubeController\n\t\t\t\tenvironment.ServiceAccounts = kubeController\n\t\t\t\tenvironment.IstioConfigStore = model.MakeIstioStore(configController)\n\t\t\t\tserviceController = kubeController\n\t\t\t\tingressSyncer := ingress.NewStatusSyncer(mesh, client, flags.controllerOptions)\n\n\t\t\t\tgo ingressSyncer.Run(stop)\n\t\t\t} else if flags.serviceregistry == platform.ConsulRegistry {\n\t\t\t\tglog.V(2).Infof(\"Consul url: %v\", flags.consulargs.serverURL)\n\n\t\t\t\tconsulController, conerr := consul.NewController(\n\t\t\t\t\tflags.consulargs.serverURL, \"dc1\", 2*time.Second)\n\t\t\t\tif conerr != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to create Consul controller: %v\", conerr)\n\t\t\t\t}\n\n\t\t\t\tconfigController = crd.NewController(configClient, flags.controllerOptions)\n\n\t\t\t\tenvironment.ServiceDiscovery = consulController\n\t\t\t\tenvironment.ServiceAccounts = consulController\n\t\t\t\tenvironment.IstioConfigStore = model.MakeIstioStore(configController)\n\t\t\t\tserviceController = consulController\n\t\t\t}\n\n\t\t\t\/\/ Set up discovery service\n\t\t\tdiscovery, err := envoy.NewDiscoveryService(\n\t\t\t\tserviceController,\n\t\t\t\tconfigController,\n\t\t\t\tenvironment,\n\t\t\t\tflags.discoveryOptions)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to create discovery service: %v\", err)\n\t\t\t}\n\n\t\t\tgo serviceController.Run(stop)\n\t\t\tgo configController.Run(stop)\n\t\t\tgo discovery.Run()\n\t\t\tcmd.WaitSignal(stop)\n\t\t\treturn nil\n\t\t},\n\t}\n)\n\nfunc init() {\n\tdiscoveryCmd.PersistentFlags().StringVar((*string)(&flags.serviceregistry), \"serviceregistry\",\n\t\tstring(platform.KubernetesRegistry),\n\t\tfmt.Sprintf(\"Select the platform for service registry, options are {%s, %s}\",\n\t\t\tstring(platform.KubernetesRegistry), string(platform.ConsulRegistry)))\n\tdiscoveryCmd.PersistentFlags().StringVar(&flags.kubeconfig, \"kubeconfig\", \"\",\n\t\t\"Use a Kubernetes configuration file instead of in-cluster configuration\")\n\tdiscoveryCmd.PersistentFlags().StringVar(&flags.meshconfig, \"meshConfig\", \"\/etc\/istio\/config\/mesh\",\n\t\tfmt.Sprintf(\"File name for Istio mesh configuration\"))\n\tdiscoveryCmd.PersistentFlags().StringVarP(&flags.controllerOptions.Namespace, \"namespace\", \"n\", \"\",\n\t\t\"Select a namespace for the controller loop. If not set, uses ${POD_NAMESPACE} environment variable\")\n\tdiscoveryCmd.PersistentFlags().StringVarP(&flags.controllerOptions.WatchedNamespace, \"app namespace\",\n\t\t\"a\", metav1.NamespaceAll,\n\t\t\"Restrict the applications namespace the controller manages; if not set, controller watches all namespaces\")\n\tdiscoveryCmd.PersistentFlags().DurationVar(&flags.controllerOptions.ResyncPeriod, \"resync\", time.Second,\n\t\t\"Controller resync interval\")\n\tdiscoveryCmd.PersistentFlags().StringVar(&flags.controllerOptions.DomainSuffix, \"domain\", \"cluster.local\",\n\t\t\"DNS domain suffix\")\n\n\tdiscoveryCmd.PersistentFlags().IntVar(&flags.discoveryOptions.Port, \"port\", 8080,\n\t\t\"Discovery service port\")\n\tdiscoveryCmd.PersistentFlags().BoolVar(&flags.discoveryOptions.EnableProfiling, \"profile\", true,\n\t\t\"Enable profiling via web interface host:port\/debug\/pprof\")\n\tdiscoveryCmd.PersistentFlags().BoolVar(&flags.discoveryOptions.EnableCaching, \"discovery_cache\", true,\n\t\t\"Enable caching discovery service responses\")\n\tdiscoveryCmd.PersistentFlags().StringVar(&flags.consulargs.config, \"consulconfig\", \"\",\n\t\t\"Consul Config file for discovery\")\n\tdiscoveryCmd.PersistentFlags().StringVar(&flags.consulargs.serverURL, \"consulserverURL\", \"\",\n\t\t\"URL for the consul server\")\n\n\tcmd.AddFlags(rootCmd)\n\n\trootCmd.AddCommand(discoveryCmd)\n\trootCmd.AddCommand(cmd.VersionCmd)\n}\n\nfunc main() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tglog.Error(err)\n\t\tos.Exit(-1)\n\t}\n}\n<commit_msg>Increase default ResyncPeriod from 1 to 30 seconds (#1195)<commit_after>\/\/ Copyright 2017 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/golang\/glog\"\n\tmultierror \"github.com\/hashicorp\/go-multierror\"\n\t\"github.com\/spf13\/cobra\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\n\tproxyconfig \"istio.io\/api\/proxy\/v1\/config\"\n\t\"istio.io\/pilot\/adapter\/config\/aggregate\"\n\t\"istio.io\/pilot\/adapter\/config\/crd\"\n\t\"istio.io\/pilot\/adapter\/config\/ingress\"\n\t\"istio.io\/pilot\/cmd\"\n\t\"istio.io\/pilot\/model\"\n\t\"istio.io\/pilot\/platform\"\n\t\"istio.io\/pilot\/platform\/consul\"\n\t\"istio.io\/pilot\/platform\/kube\"\n\t\"istio.io\/pilot\/proxy\"\n\t\"istio.io\/pilot\/proxy\/envoy\"\n\t\"istio.io\/pilot\/tools\/version\"\n)\n\n\/\/ ConsulArgs store the args related to Consul configuration\ntype ConsulArgs struct {\n\tconfig    string\n\tserverURL string\n}\n\ntype args struct {\n\tkubeconfig string\n\tmeshconfig string\n\n\t\/\/ ingress sync mode is set to off by default\n\tcontrollerOptions kube.ControllerOptions\n\tdiscoveryOptions  envoy.DiscoveryServiceOptions\n\n\tserviceregistry platform.ServiceRegistry\n\tconsulargs      ConsulArgs\n}\n\nvar (\n\tflags args\n\n\trootCmd = &cobra.Command{\n\t\tUse:   \"pilot\",\n\t\tShort: \"Istio Pilot\",\n\t\tLong:  \"Istio Pilot provides management plane functionality to the Istio service mesh and Istio Mixer.\",\n\t}\n\n\tdiscoveryCmd = &cobra.Command{\n\t\tUse:   \"discovery\",\n\t\tShort: \"Start Istio proxy discovery service\",\n\t\tRunE: func(c *cobra.Command, args []string) error {\n\n\t\t\t\/\/ receive mesh configuration\n\t\t\tmesh, fail := cmd.ReadMeshConfig(flags.meshconfig)\n\t\t\tif fail != nil {\n\t\t\t\tdefaultMesh := proxy.DefaultMeshConfig()\n\t\t\t\tmesh = &defaultMesh\n\t\t\t\tglog.Warningf(\"failed to read mesh configuration, using default: %v\", fail)\n\t\t\t}\n\t\t\tglog.V(2).Infof(\"mesh configuration %s\", spew.Sdump(mesh))\n\t\t\tglog.V(2).Infof(\"version %s\", version.Line())\n\t\t\tglog.V(2).Infof(\"flags %s\", spew.Sdump(flags))\n\n\t\t\tvar serviceController model.Controller\n\t\t\tvar configController model.ConfigStoreCache\n\t\t\tenvironment := proxy.Environment{\n\t\t\t\tMesh: mesh,\n\t\t\t}\n\n\t\t\tstop := make(chan struct{})\n\n\t\t\tconfigClient, err := crd.NewClient(flags.kubeconfig, model.ConfigDescriptor{\n\t\t\t\tmodel.RouteRule,\n\t\t\t\tmodel.EgressRule,\n\t\t\t\tmodel.DestinationPolicy,\n\t\t\t}, flags.controllerOptions.DomainSuffix)\n\t\t\tif err != nil {\n\t\t\t\treturn multierror.Prefix(err, \"failed to open a config client.\")\n\t\t\t}\n\n\t\t\tif err = configClient.RegisterResources(); err != nil {\n\t\t\t\treturn multierror.Prefix(err, \"failed to register custom resources.\")\n\t\t\t}\n\n\t\t\t\/\/ Set up values for input to discovery service in different platforms\n\t\t\tif flags.serviceregistry == platform.KubernetesRegistry || flags.serviceregistry == \"\" {\n\t\t\t\t_, client, kuberr := kube.CreateInterface(flags.kubeconfig)\n\t\t\t\tif kuberr != nil {\n\t\t\t\t\treturn multierror.Prefix(kuberr, \"failed to connect to Kubernetes API.\")\n\t\t\t\t}\n\n\t\t\t\tif flags.controllerOptions.Namespace == \"\" {\n\t\t\t\t\tflags.controllerOptions.Namespace = os.Getenv(\"POD_NAMESPACE\")\n\t\t\t\t}\n\n\t\t\t\tkubeController := kube.NewController(client, mesh, flags.controllerOptions)\n\t\t\t\tif mesh.IngressControllerMode == proxyconfig.ProxyMeshConfig_OFF {\n\t\t\t\t\tconfigController = crd.NewController(configClient, flags.controllerOptions)\n\t\t\t\t} else {\n\t\t\t\t\tconfigController, err = aggregate.MakeCache([]model.ConfigStoreCache{\n\t\t\t\t\t\tcrd.NewController(configClient, flags.controllerOptions),\n\t\t\t\t\t\tingress.NewController(client, mesh, flags.controllerOptions),\n\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tenvironment.ServiceDiscovery = kubeController\n\t\t\t\tenvironment.ServiceAccounts = kubeController\n\t\t\t\tenvironment.IstioConfigStore = model.MakeIstioStore(configController)\n\t\t\t\tserviceController = kubeController\n\t\t\t\tingressSyncer := ingress.NewStatusSyncer(mesh, client, flags.controllerOptions)\n\n\t\t\t\tgo ingressSyncer.Run(stop)\n\t\t\t} else if flags.serviceregistry == platform.ConsulRegistry {\n\t\t\t\tglog.V(2).Infof(\"Consul url: %v\", flags.consulargs.serverURL)\n\n\t\t\t\tconsulController, conerr := consul.NewController(\n\t\t\t\t\tflags.consulargs.serverURL, \"dc1\", 2*time.Second)\n\t\t\t\tif conerr != nil {\n\t\t\t\t\treturn fmt.Errorf(\"failed to create Consul controller: %v\", conerr)\n\t\t\t\t}\n\n\t\t\t\tconfigController = crd.NewController(configClient, flags.controllerOptions)\n\n\t\t\t\tenvironment.ServiceDiscovery = consulController\n\t\t\t\tenvironment.ServiceAccounts = consulController\n\t\t\t\tenvironment.IstioConfigStore = model.MakeIstioStore(configController)\n\t\t\t\tserviceController = consulController\n\t\t\t}\n\n\t\t\t\/\/ Set up discovery service\n\t\t\tdiscovery, err := envoy.NewDiscoveryService(\n\t\t\t\tserviceController,\n\t\t\t\tconfigController,\n\t\t\t\tenvironment,\n\t\t\t\tflags.discoveryOptions)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to create discovery service: %v\", err)\n\t\t\t}\n\n\t\t\tgo serviceController.Run(stop)\n\t\t\tgo configController.Run(stop)\n\t\t\tgo discovery.Run()\n\t\t\tcmd.WaitSignal(stop)\n\t\t\treturn nil\n\t\t},\n\t}\n)\n\nfunc init() {\n\tdiscoveryCmd.PersistentFlags().StringVar((*string)(&flags.serviceregistry), \"serviceregistry\",\n\t\tstring(platform.KubernetesRegistry),\n\t\tfmt.Sprintf(\"Select the platform for service registry, options are {%s, %s}\",\n\t\t\tstring(platform.KubernetesRegistry), string(platform.ConsulRegistry)))\n\tdiscoveryCmd.PersistentFlags().StringVar(&flags.kubeconfig, \"kubeconfig\", \"\",\n\t\t\"Use a Kubernetes configuration file instead of in-cluster configuration\")\n\tdiscoveryCmd.PersistentFlags().StringVar(&flags.meshconfig, \"meshConfig\", \"\/etc\/istio\/config\/mesh\",\n\t\tfmt.Sprintf(\"File name for Istio mesh configuration\"))\n\tdiscoveryCmd.PersistentFlags().StringVarP(&flags.controllerOptions.Namespace, \"namespace\", \"n\", \"\",\n\t\t\"Select a namespace for the controller loop. If not set, uses ${POD_NAMESPACE} environment variable\")\n\tdiscoveryCmd.PersistentFlags().StringVarP(&flags.controllerOptions.WatchedNamespace, \"app namespace\",\n\t\t\"a\", metav1.NamespaceAll,\n\t\t\"Restrict the applications namespace the controller manages; if not set, controller watches all namespaces\")\n\tdiscoveryCmd.PersistentFlags().DurationVar(&flags.controllerOptions.ResyncPeriod, \"resync\", 60*time.Second,\n\t\t\"Controller resync interval\")\n\tdiscoveryCmd.PersistentFlags().StringVar(&flags.controllerOptions.DomainSuffix, \"domain\", \"cluster.local\",\n\t\t\"DNS domain suffix\")\n\n\tdiscoveryCmd.PersistentFlags().IntVar(&flags.discoveryOptions.Port, \"port\", 8080,\n\t\t\"Discovery service port\")\n\tdiscoveryCmd.PersistentFlags().BoolVar(&flags.discoveryOptions.EnableProfiling, \"profile\", true,\n\t\t\"Enable profiling via web interface host:port\/debug\/pprof\")\n\tdiscoveryCmd.PersistentFlags().BoolVar(&flags.discoveryOptions.EnableCaching, \"discovery_cache\", true,\n\t\t\"Enable caching discovery service responses\")\n\tdiscoveryCmd.PersistentFlags().StringVar(&flags.consulargs.config, \"consulconfig\", \"\",\n\t\t\"Consul Config file for discovery\")\n\tdiscoveryCmd.PersistentFlags().StringVar(&flags.consulargs.serverURL, \"consulserverURL\", \"\",\n\t\t\"URL for the consul server\")\n\n\tcmd.AddFlags(rootCmd)\n\n\trootCmd.AddCommand(discoveryCmd)\n\trootCmd.AddCommand(cmd.VersionCmd)\n}\n\nfunc main() {\n\tif err := rootCmd.Execute(); err != nil {\n\t\tglog.Error(err)\n\t\tos.Exit(-1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cmd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/config\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/constants\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/update\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/version\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n)\n\nvar (\n\topts      = &config.SkaffoldOptions{}\n\tv         string\n\toverwrite bool\n\n\tupdateMsg = make(chan string)\n)\n\nvar rootCmd = &cobra.Command{\n\tUse:   \"skaffold\",\n\tShort: \"A tool that facilitates continuous development for Kubernetes applications.\",\n}\n\nfunc NewSkaffoldCommand(out, err io.Writer) *cobra.Command {\n\trootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {\n\t\tif err := SetUpLogs(err, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t\trootCmd.SilenceUsage = true\n\t\tlogrus.Infof(\"Skaffold %+v\", version.Get())\n\t\tgo func() {\n\t\t\tif err := updateCheck(updateMsg); err != nil {\n\t\t\t\tlogrus.Infof(\"update check failed: %s\", err)\n\t\t\t}\n\t\t}()\n\t\treturn nil\n\t}\n\n\trootCmd.PersistentPostRun = func(cmd *cobra.Command, args []string) {\n\t\tselect {\n\t\tcase msg := <-updateMsg:\n\t\t\tfmt.Fprintf(out, \"%s\\n\", msg)\n\t\tdefault:\n\t\t}\n\t}\n\n\trootCmd.SilenceErrors = true\n\trootCmd.AddCommand(NewCmdCompletion(out))\n\trootCmd.AddCommand(NewCmdVersion(out))\n\trootCmd.AddCommand(NewCmdRun(out))\n\trootCmd.AddCommand(NewCmdDev(out))\n\trootCmd.AddCommand(NewCmdBuild(out))\n\trootCmd.AddCommand(NewCmdDeploy(out))\n\trootCmd.AddCommand(NewCmdDelete(out))\n\trootCmd.AddCommand(NewCmdFix(out))\n\trootCmd.AddCommand(NewCmdConfig(out))\n\trootCmd.AddCommand(NewCmdInit(out))\n\n\trootCmd.PersistentFlags().StringVarP(&v, \"verbosity\", \"v\", constants.DefaultLogLevel.String(), \"Log level (debug, info, warn, error, fatal, panic\")\n\n\tsetFlagsFromEnvVariables(rootCmd.Commands())\n\n\treturn rootCmd\n}\n\nfunc updateCheck(ch chan string) error {\n\tif quietFlag {\n\t\tlogrus.Debugf(\"Update check is disabled because of quiet mode\")\n\t\treturn nil\n\t}\n\tif !update.IsUpdateCheckEnabled() {\n\t\tlogrus.Debugf(\"Update check not enabled, skipping.\")\n\t\treturn nil\n\t}\n\tcurrent, err := version.ParseVersion(version.Get().Version)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"parsing current semver, skipping update check\")\n\t}\n\tlatest, err := update.GetLatestVersion(context.Background())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting latest version\")\n\t}\n\tif latest.GT(current) {\n\t\tch <- fmt.Sprintf(\"There is a new version (%s) of skaffold available. Download it at %s\\n\", latest, constants.LatestDownloadURL)\n\t}\n\treturn nil\n}\n\n\/\/ Each flag can also be set with an env variable whose name starts with `SKAFFOLD_`.\nfunc setFlagsFromEnvVariables(commands []*cobra.Command) {\n\tfor _, cmd := range commands {\n\t\tcmd.Flags().VisitAll(func(f *pflag.Flag) {\n\t\t\t\/\/ special case for backward compatibility.\n\t\t\tif f.Name == \"namespace\" {\n\t\t\t\tif val, present := os.LookupEnv(\"SKAFFOLD_DEPLOY_NAMESPACE\"); present {\n\t\t\t\t\tlogrus.Warnln(\"Using SKAFFOLD_DEPLOY_NAMESPACE env variable is deprecated. Please use SKAFFOLD_NAMESPACE instead.\")\n\t\t\t\t\tcmd.Flags().Set(f.Name, val)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tenvVar := fmt.Sprintf(\"SKAFFOLD_%s\", strings.Replace(strings.ToUpper(f.Name), \"-\", \"_\", -1))\n\t\t\tif val, present := os.LookupEnv(envVar); present {\n\t\t\t\tcmd.Flags().Set(f.Name, val)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc AddDevFlags(cmd *cobra.Command) {\n\tcmd.Flags().BoolVar(&opts.Cleanup, \"cleanup\", true, \"Delete deployments after dev mode is interrupted\")\n\tcmd.Flags().StringArrayVarP(&opts.Watch, \"watch-image\", \"w\", nil, \"Choose which artifacts to watch. Artifacts with image names that contain the expression will be watched only. Default is to watch sources for all artifacts.\")\n\tcmd.Flags().IntVarP(&opts.WatchPollInterval, \"watch-poll-interval\", \"i\", 1000, \"Interval (in ms) between two checks for file changes.\")\n\tcmd.Flags().BoolVar(&opts.PortForward, \"port-forward\", true, \"Port-forward exposed container ports within pods\")\n}\n\nfunc AddRunDeployFlags(cmd *cobra.Command) {\n\tcmd.Flags().BoolVar(&opts.Tail, \"tail\", false, \"Stream logs from deployed objects\")\n}\n\nfunc AddRunDevFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&opts.ConfigurationFile, \"filename\", \"f\", \"skaffold.yaml\", \"Filename or URL to the pipeline file\")\n\tcmd.Flags().BoolVar(&opts.Notification, \"toot\", false, \"Emit a terminal beep after the deploy is complete\")\n\tcmd.Flags().StringArrayVarP(&opts.Profiles, \"profile\", \"p\", nil, \"Activate profiles by name\")\n\tcmd.Flags().StringVarP(&opts.Namespace, \"namespace\", \"n\", \"\", \"Run Helm deployments in the specified namespace\")\n}\n\nfunc AddFixFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&opts.ConfigurationFile, \"filename\", \"f\", \"skaffold.yaml\", \"Filename or URL to the pipeline file\")\n\tcmd.Flags().BoolVar(&overwrite, \"overwrite\", false, \"Overwrite original config with fixed config\")\n}\n\nfunc SetUpLogs(out io.Writer, level string) error {\n\tlogrus.SetOutput(out)\n\tlvl, err := logrus.ParseLevel(v)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"parsing log level\")\n\t}\n\tlogrus.SetLevel(lvl)\n\treturn nil\n}\n<commit_msg>Fix missing parenthesis<commit_after>\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cmd\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/config\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/constants\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/update\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/version\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n)\n\nvar (\n\topts      = &config.SkaffoldOptions{}\n\tv         string\n\toverwrite bool\n\n\tupdateMsg = make(chan string)\n)\n\nvar rootCmd = &cobra.Command{\n\tUse:   \"skaffold\",\n\tShort: \"A tool that facilitates continuous development for Kubernetes applications.\",\n}\n\nfunc NewSkaffoldCommand(out, err io.Writer) *cobra.Command {\n\trootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {\n\t\tif err := SetUpLogs(err, v); err != nil {\n\t\t\treturn err\n\t\t}\n\t\trootCmd.SilenceUsage = true\n\t\tlogrus.Infof(\"Skaffold %+v\", version.Get())\n\t\tgo func() {\n\t\t\tif err := updateCheck(updateMsg); err != nil {\n\t\t\t\tlogrus.Infof(\"update check failed: %s\", err)\n\t\t\t}\n\t\t}()\n\t\treturn nil\n\t}\n\n\trootCmd.PersistentPostRun = func(cmd *cobra.Command, args []string) {\n\t\tselect {\n\t\tcase msg := <-updateMsg:\n\t\t\tfmt.Fprintf(out, \"%s\\n\", msg)\n\t\tdefault:\n\t\t}\n\t}\n\n\trootCmd.SilenceErrors = true\n\trootCmd.AddCommand(NewCmdCompletion(out))\n\trootCmd.AddCommand(NewCmdVersion(out))\n\trootCmd.AddCommand(NewCmdRun(out))\n\trootCmd.AddCommand(NewCmdDev(out))\n\trootCmd.AddCommand(NewCmdBuild(out))\n\trootCmd.AddCommand(NewCmdDeploy(out))\n\trootCmd.AddCommand(NewCmdDelete(out))\n\trootCmd.AddCommand(NewCmdFix(out))\n\trootCmd.AddCommand(NewCmdConfig(out))\n\trootCmd.AddCommand(NewCmdInit(out))\n\n\trootCmd.PersistentFlags().StringVarP(&v, \"verbosity\", \"v\", constants.DefaultLogLevel.String(), \"Log level (debug, info, warn, error, fatal, panic)\")\n\n\tsetFlagsFromEnvVariables(rootCmd.Commands())\n\n\treturn rootCmd\n}\n\nfunc updateCheck(ch chan string) error {\n\tif quietFlag {\n\t\tlogrus.Debugf(\"Update check is disabled because of quiet mode\")\n\t\treturn nil\n\t}\n\tif !update.IsUpdateCheckEnabled() {\n\t\tlogrus.Debugf(\"Update check not enabled, skipping.\")\n\t\treturn nil\n\t}\n\tcurrent, err := version.ParseVersion(version.Get().Version)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"parsing current semver, skipping update check\")\n\t}\n\tlatest, err := update.GetLatestVersion(context.Background())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting latest version\")\n\t}\n\tif latest.GT(current) {\n\t\tch <- fmt.Sprintf(\"There is a new version (%s) of skaffold available. Download it at %s\\n\", latest, constants.LatestDownloadURL)\n\t}\n\treturn nil\n}\n\n\/\/ Each flag can also be set with an env variable whose name starts with `SKAFFOLD_`.\nfunc setFlagsFromEnvVariables(commands []*cobra.Command) {\n\tfor _, cmd := range commands {\n\t\tcmd.Flags().VisitAll(func(f *pflag.Flag) {\n\t\t\t\/\/ special case for backward compatibility.\n\t\t\tif f.Name == \"namespace\" {\n\t\t\t\tif val, present := os.LookupEnv(\"SKAFFOLD_DEPLOY_NAMESPACE\"); present {\n\t\t\t\t\tlogrus.Warnln(\"Using SKAFFOLD_DEPLOY_NAMESPACE env variable is deprecated. Please use SKAFFOLD_NAMESPACE instead.\")\n\t\t\t\t\tcmd.Flags().Set(f.Name, val)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tenvVar := fmt.Sprintf(\"SKAFFOLD_%s\", strings.Replace(strings.ToUpper(f.Name), \"-\", \"_\", -1))\n\t\t\tif val, present := os.LookupEnv(envVar); present {\n\t\t\t\tcmd.Flags().Set(f.Name, val)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc AddDevFlags(cmd *cobra.Command) {\n\tcmd.Flags().BoolVar(&opts.Cleanup, \"cleanup\", true, \"Delete deployments after dev mode is interrupted\")\n\tcmd.Flags().StringArrayVarP(&opts.Watch, \"watch-image\", \"w\", nil, \"Choose which artifacts to watch. Artifacts with image names that contain the expression will be watched only. Default is to watch sources for all artifacts.\")\n\tcmd.Flags().IntVarP(&opts.WatchPollInterval, \"watch-poll-interval\", \"i\", 1000, \"Interval (in ms) between two checks for file changes.\")\n\tcmd.Flags().BoolVar(&opts.PortForward, \"port-forward\", true, \"Port-forward exposed container ports within pods\")\n}\n\nfunc AddRunDeployFlags(cmd *cobra.Command) {\n\tcmd.Flags().BoolVar(&opts.Tail, \"tail\", false, \"Stream logs from deployed objects\")\n}\n\nfunc AddRunDevFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&opts.ConfigurationFile, \"filename\", \"f\", \"skaffold.yaml\", \"Filename or URL to the pipeline file\")\n\tcmd.Flags().BoolVar(&opts.Notification, \"toot\", false, \"Emit a terminal beep after the deploy is complete\")\n\tcmd.Flags().StringArrayVarP(&opts.Profiles, \"profile\", \"p\", nil, \"Activate profiles by name\")\n\tcmd.Flags().StringVarP(&opts.Namespace, \"namespace\", \"n\", \"\", \"Run Helm deployments in the specified namespace\")\n}\n\nfunc AddFixFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&opts.ConfigurationFile, \"filename\", \"f\", \"skaffold.yaml\", \"Filename or URL to the pipeline file\")\n\tcmd.Flags().BoolVar(&overwrite, \"overwrite\", false, \"Overwrite original config with fixed config\")\n}\n\nfunc SetUpLogs(out io.Writer, level string) error {\n\tlogrus.SetOutput(out)\n\tlvl, err := logrus.ParseLevel(v)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"parsing log level\")\n\t}\n\tlogrus.SetLevel(lvl)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build windows\n\/\/ This file is compiled only on windows. It contains paths used by the windows\n\/\/ browser bundle.\n\/\/ http:\/\/golang.org\/pkg\/go\/build\/#hdr-Build_Constraints\n\npackage main\n\nconst (\n\tfirefoxPath        string = \"Browser\/firefox.exe\"\n\tfirefoxProfilePath        = \"Data\/Browser\/profile.meek-http-helper\"\n)\n<commit_msg>Remove a useless type.<commit_after>\/\/ +build windows\n\/\/ This file is compiled only on windows. It contains paths used by the windows\n\/\/ browser bundle.\n\/\/ http:\/\/golang.org\/pkg\/go\/build\/#hdr-Build_Constraints\n\npackage main\n\nconst (\n\tfirefoxPath        = \"Browser\/firefox.exe\"\n\tfirefoxProfilePath = \"Data\/Browser\/profile.meek-http-helper\"\n)\n<|endoftext|>"}
{"text":"<commit_before>package lrserver_test\n\nimport (\n\t\"github.com\/jaschaephraim\/lrserver\"\n\t\"golang.org\/x\/exp\/fsnotify\"\n\t\"log\"\n\t\"net\/http\"\n)\n\n\/\/ html includes the client JavaScript\nconst html = `<!doctype html>\n<html>\n<head>\n  <title>Example<\/title>\n<body>\n  <script src=\"http:\/\/localhost:35729\/livereload.js\"><\/script>\n<\/body>\n<\/html>`\n\nfunc Example() {\n\t\/\/ Create file watcher\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer watcher.Close()\n\n\t\/\/ Add dir to watcher\n\terr = watcher.Add(\"\/path\/to\/watched\/dir\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\t\/\/ Start LiveReload server\n\tgo lrserver.ListenAndServe()\n\n\t\/\/ Start goroutine that requests reload upon watcher event\n\tgo func() {\n\t\tfor {\n\t\t\tevent := <-watcher.Events\n\t\t\tlrserver.Reload(event.Name)\n\t\t}\n\t}()\n\n\t\/\/ Start serving html\n\thttp.HandleFunc(\"\/\", func(rw http.ResponseWriter, req *http.Request) {\n\t\trw.Write([]byte(html))\n\t})\n\thttp.ListenAndServe(\":3000\", nil)\n}\n<commit_msg>Update use of fsnotify in example<commit_after>package lrserver_test\n\nimport (\n\t\"github.com\/jaschaephraim\/lrserver\"\n\t\"golang.org\/x\/exp\/fsnotify\"\n\t\"log\"\n\t\"net\/http\"\n)\n\n\/\/ html includes the client JavaScript\nconst html = `<!doctype html>\n<html>\n<head>\n  <title>Example<\/title>\n<\/head>\n<body>\n  <script src=\"http:\/\/localhost:35729\/livereload.js\"><\/script>\n<\/body>\n<\/html>`\n\nfunc Example() {\n\t\/\/ Create file watcher\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer watcher.Close()\n\n\t\/\/ Watch dir\n\terr = watcher.Watch(\"\/path\/to\/watched\/dir\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\t\/\/ Start LiveReload server\n\tgo lrserver.ListenAndServe()\n\n\t\/\/ Start goroutine that requests reload upon watcher event\n\tgo func() {\n\t\tfor {\n\t\t\tevent := <-watcher.Event\n\t\t\tlrserver.Reload(event.Name)\n\t\t}\n\t}()\n\n\t\/\/ Start serving html\n\thttp.HandleFunc(\"\/\", func(rw http.ResponseWriter, req *http.Request) {\n\t\trw.Write([]byte(html))\n\t})\n\thttp.ListenAndServe(\":3000\", nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package rx_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/reactivego\/rx\"\n)\n\nfunc ExampleObservable_ConcatWith() {\n\toa := rx.From(0, 1, 2, 3)\n\tob := rx.From(4, 5)\n\toc := rx.From(6)\n\tod := rx.From(7, 8, 9)\n\toa.ConcatWith(ob, oc).ConcatWith(od).Subscribe(func(next interface{}, err error, done bool) {\n\t\tswitch {\n\t\tcase !done:\n\t\t\tfmt.Printf(\"%d,\", next.(int))\n\t\tcase err != nil:\n\t\t\tfmt.Print(\"err\", err)\n\t\tdefault:\n\t\t\tfmt.Printf(\"complete\")\n\t\t}\n\t}).Wait()\n\n\t\/\/ Output:\n\t\/\/ 0,1,2,3,4,5,6,7,8,9,complete\n}\n\n\nfunc ExampleObservable_Defer() {\n\tcount := 0\n\tsource := rx.Defer(func() rx.Observable {\n\t\treturn rx.From(count)\n\t})\n\tmapped := source.Map(func(next interface{}) interface{} {\n\t\treturn fmt.Sprintf(\"observable %d\", next)\n\t})\n\n\tmapped.Println()\n\tcount = 123\n\tmapped.Println()\n\tcount = 456\n\tmapped.Println()\n\n\t\/\/ Output:\n\t\/\/ observable 0\n\t\/\/ observable 123\n\t\/\/ observable 456\n}\n\nfunc ExampleObservable_Do() {\n\trx.From(1, 2, 3).Do(func(v interface{}) {\n\t\tfmt.Println(v.(int))\n\t}).Wait()\n\n\t\/\/ Output:\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n}\n\nfunc ExampleObservable_Filter() {\n\teven := func(i interface{}) bool {\n\t\treturn i.(int)%2 == 0\n\t}\n\n\trx.From(1, 2, 3, 4, 5, 6, 7, 8).Filter(even).Println()\n\n\t\/\/ Output:\n\t\/\/ 2\n\t\/\/ 4\n\t\/\/ 6\n\t\/\/ 8\n}\n\nfunc ExampleFromChan() {\n\tch := make(chan interface{}, 6)\n\tfor i := 0; i < 5; i++ {\n\t\tch <- i + 1\n\t}\n\tclose(ch)\n\n\trx.FromChan(ch).Println()\n\n\t\/\/ Output:\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n\t\/\/ 4\n\t\/\/ 5\n}\n\nfunc ExampleFrom() {\n\trx.From(1, 2, 3, 4, 5).Println()\n\n\t\/\/ Output:\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n\t\/\/ 4\n\t\/\/ 5\n}\n\nfunc ExampleFromSlice() {\n\trx.From([]interface{}{1, 2, 3, 4, 5}...).Println()\n\n\t\/\/ Output:\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n\t\/\/ 4\n\t\/\/ 5\n}\n\nfunc ExampleObservable_Map() {\n\trx.From(1, 2, 3, 4).Map(func(i interface{}) interface{} {\n\t\treturn fmt.Sprintf(\"%d!\", i.(int))\n\t}).Println()\n\n\t\/\/ Output:\n\t\/\/ 1!\n\t\/\/ 2!\n\t\/\/ 3!\n\t\/\/ 4!\n}\n\nfunc ExampleObservable_MergeMap() {\n\tsource := rx.From(1, 2).\n\t\tMergeMap(func(n interface{}) rx.Observable {\n\t\t\treturn rx.Range(n.(int), 2).AsObservable()\n\t\t})\n\tif err := source.Println(); err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Output:\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 2\n\t\/\/ 3\n}\n\nfunc ExampleObservable_Scan() {\n\tadd := func(acc interface{}, value interface{}) interface{} {\n\t\treturn acc.(int) + value.(int)\n\t}\n\n\trx.From(1, 2, 3, 4, 5).Scan(add, 0).Println()\n\n\t\/\/ Output:\n\t\/\/ 1\n\t\/\/ 3\n\t\/\/ 6\n\t\/\/ 10\n\t\/\/ 15\n}\n\nfunc ExampleObservableObservable_SwitchAll() {\n\t\/\/ intToObs creates a new observable that emits an integer starting after and then repeated every 20 milliseconds\n\t\/\/ in the range starting at 0 and incrementing by 1. It takes only the first 10 emitted values and then uses\n\t\/\/ AsObservable to convert the IntObservable back to an untyped Observable.\n\tintToObs := func(i int) rx.Observable {\n\t\treturn rx.Interval(20 * time.Millisecond).\n\t\t\tTake(10).\n\t\t\tAsObservable()\n\t}\n\n\trx.Interval(100 * time.Millisecond).\n\t\tTake(3).\n\t\tMapObservable(intToObs).\n\t\tSwitchAll().\n\t\tPrintln()\n\n\t\/\/ Output:\n\t\/\/ 0\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n\t\/\/ 0\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n\t\/\/ 0\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n\t\/\/ 4\n\t\/\/ 5\n\t\/\/ 6\n\t\/\/ 7\n\t\/\/ 8\n\t\/\/ 9\n}\n<commit_msg>Fix names of examples for godoc.<commit_after>package rx_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/reactivego\/rx\"\n)\n\nfunc ExampleObservable_ConcatWith() {\n\toa := rx.From(0, 1, 2, 3)\n\tob := rx.From(4, 5)\n\toc := rx.From(6)\n\tod := rx.From(7, 8, 9)\n\toa.ConcatWith(ob, oc).ConcatWith(od).Subscribe(func(next interface{}, err error, done bool) {\n\t\tswitch {\n\t\tcase !done:\n\t\t\tfmt.Printf(\"%d,\", next.(int))\n\t\tcase err != nil:\n\t\t\tfmt.Print(\"err\", err)\n\t\tdefault:\n\t\t\tfmt.Printf(\"complete\")\n\t\t}\n\t}).Wait()\n\n\t\/\/ Output:\n\t\/\/ 0,1,2,3,4,5,6,7,8,9,complete\n}\n\nfunc ExampleDefer() {\n\tcount := 0\n\tsource := rx.Defer(func() rx.Observable {\n\t\treturn rx.From(count)\n\t})\n\tmapped := source.Map(func(next interface{}) interface{} {\n\t\treturn fmt.Sprintf(\"observable %d\", next)\n\t})\n\n\tmapped.Println()\n\tcount = 123\n\tmapped.Println()\n\tcount = 456\n\tmapped.Println()\n\n\t\/\/ Output:\n\t\/\/ observable 0\n\t\/\/ observable 123\n\t\/\/ observable 456\n}\n\nfunc ExampleObservable_Do() {\n\trx.From(1, 2, 3).Do(func(v interface{}) {\n\t\tfmt.Println(v.(int))\n\t}).Wait()\n\n\t\/\/ Output:\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n}\n\nfunc ExampleObservable_Filter() {\n\teven := func(i interface{}) bool {\n\t\treturn i.(int)%2 == 0\n\t}\n\n\trx.From(1, 2, 3, 4, 5, 6, 7, 8).Filter(even).Println()\n\n\t\/\/ Output:\n\t\/\/ 2\n\t\/\/ 4\n\t\/\/ 6\n\t\/\/ 8\n}\n\nfunc ExampleFromChan() {\n\tch := make(chan interface{}, 6)\n\tfor i := 0; i < 5; i++ {\n\t\tch <- i + 1\n\t}\n\tclose(ch)\n\n\trx.FromChan(ch).Println()\n\n\t\/\/ Output:\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n\t\/\/ 4\n\t\/\/ 5\n}\n\nfunc ExampleFrom() {\n\trx.From(1, 2, 3, 4, 5).Println()\n\n\t\/\/ Output:\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n\t\/\/ 4\n\t\/\/ 5\n}\n\nfunc ExampleFrom_slice() {\n\trx.From([]interface{}{1, 2, 3, 4, 5}...).Println()\n\n\t\/\/ Output:\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n\t\/\/ 4\n\t\/\/ 5\n}\n\nfunc ExampleObservable_Map() {\n\trx.From(1, 2, 3, 4).Map(func(i interface{}) interface{} {\n\t\treturn fmt.Sprintf(\"%d!\", i.(int))\n\t}).Println()\n\n\t\/\/ Output:\n\t\/\/ 1!\n\t\/\/ 2!\n\t\/\/ 3!\n\t\/\/ 4!\n}\n\nfunc ExampleObservable_MergeMap() {\n\tsource := rx.From(1, 2).\n\t\tMergeMap(func(n interface{}) rx.Observable {\n\t\t\treturn rx.Range(n.(int), 2).AsObservable()\n\t\t})\n\tif err := source.Println(); err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Output:\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 2\n\t\/\/ 3\n}\n\nfunc ExampleObservable_Scan() {\n\tadd := func(acc interface{}, value interface{}) interface{} {\n\t\treturn acc.(int) + value.(int)\n\t}\n\n\trx.From(1, 2, 3, 4, 5).Scan(add, 0).Println()\n\n\t\/\/ Output:\n\t\/\/ 1\n\t\/\/ 3\n\t\/\/ 6\n\t\/\/ 10\n\t\/\/ 15\n}\n\nfunc ExampleObservableObservable_SwitchAll() {\n\t\/\/ intToObs creates a new observable that emits an integer starting after and then repeated every 20 milliseconds\n\t\/\/ in the range starting at 0 and incrementing by 1. It takes only the first 10 emitted values and then uses\n\t\/\/ AsObservable to convert the IntObservable back to an untyped Observable.\n\tintToObs := func(i int) rx.Observable {\n\t\treturn rx.Interval(20 * time.Millisecond).\n\t\t\tTake(10).\n\t\t\tAsObservable()\n\t}\n\n\trx.Interval(100 * time.Millisecond).\n\t\tTake(3).\n\t\tMapObservable(intToObs).\n\t\tSwitchAll().\n\t\tPrintln()\n\n\t\/\/ Output:\n\t\/\/ 0\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n\t\/\/ 0\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n\t\/\/ 0\n\t\/\/ 1\n\t\/\/ 2\n\t\/\/ 3\n\t\/\/ 4\n\t\/\/ 5\n\t\/\/ 6\n\t\/\/ 7\n\t\/\/ 8\n\t\/\/ 9\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 The Bazel Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage skylark_test\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"unsafe\"\n\n\t\"github.com\/google\/skylark\"\n)\n\n\/\/ ExampleEmbedding demonstrates a simple embedding\n\/\/ of the Skylark interpreter into a Go program.\nfunc ExampleEmbedding() {\n\tconst data = `\nprint(greeting + \", world\")\n\nsquares = [x*x for x in range(10)]\n`\n\n\tthread := &skylark.Thread{\n\t\tPrint: func(_ *skylark.Thread, msg string) { fmt.Println(msg) },\n\t}\n\tglobals := skylark.StringDict{\n\t\t\"greeting\": skylark.String(\"hello\"),\n\t}\n\tif err := skylark.ExecFile(thread, \"apparent\/filename.sky\", data, globals); err != nil {\n\t\tif evalErr, ok := err.(*skylark.EvalError); ok {\n\t\t\tlog.Fatal(evalErr.Backtrace())\n\t\t}\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Print the global environment.\n\tvar names []string\n\tfor name := range globals {\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\tfmt.Println(\"\\nGlobals:\")\n\tfor _, name := range names {\n\t\tv := globals[name]\n\t\tfmt.Printf(\"%s (%s) = %s\\n\", name, v.Type(), v.String())\n\t}\n\n\t\/\/ Output:\n\t\/\/ hello, world\n\t\/\/\n\t\/\/ Globals:\n\t\/\/ greeting (string) = \"hello\"\n\t\/\/ squares (list) = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n}\n\n\/\/ ExampleLoadSequential demonstrates a simple caching\n\/\/ implementation of 'load' that works sequentially.\nfunc ExampleLoadSequential() {\n\tfakeFilesystem := map[string]string{\n\t\t\"c.sky\": `load(\"b.sky\", \"b\"); c = b + \"!\"`,\n\t\t\"b.sky\": `load(\"a.sky\", \"a\"); b = a + \", world\"`,\n\t\t\"a.sky\": `a = \"Hello\"`,\n\t}\n\n\ttype entry struct {\n\t\tglobals skylark.StringDict\n\t\terr     error\n\t}\n\n\tcache := make(map[string]*entry)\n\n\tload := func(thread *skylark.Thread, module string) (skylark.StringDict, error) {\n\t\te, ok := cache[module]\n\t\tif e == nil {\n\t\t\tif ok {\n\t\t\t\t\/\/ request for package whose loading is in progress\n\t\t\t\treturn nil, fmt.Errorf(\"cycle in load graph\")\n\t\t\t}\n\n\t\t\t\/\/ Add a placeholder to indicate \"load in progress\".\n\t\t\tcache[module] = nil\n\n\t\t\t\/\/ Load it.\n\t\t\tdata := fakeFilesystem[module]\n\t\t\tglobals := make(skylark.StringDict)\n\t\t\terr := skylark.ExecFile(thread, module, data, globals)\n\t\t\te = &entry{globals, err}\n\n\t\t\t\/\/ Update the cache.\n\t\t\tcache[module] = e\n\t\t}\n\t\treturn e.globals, e.err\n\t}\n\n\tthread := &skylark.Thread{Load: load}\n\tglobals, err := load(thread, \"c.sky\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(globals[\"c\"])\n\n\t\/\/ Output:\n\t\/\/ \"Hello, world!\"\n}\n\n\/\/ ExampleLoadParallel demonstrates a parallel implementation\n\/\/ of 'load' with caching, duplicate suppression, and cycle detection.\nfunc ExampleLoadParallel() {\n\tcache := &cache{\n\t\tcache: make(map[string]*entry),\n\t\tfakeFilesystem: map[string]string{\n\t\t\t\"c.sky\": `load(\"a.sky\", \"a\"); c = a * 2`,\n\t\t\t\"b.sky\": `load(\"a.sky\", \"a\"); b = a * 3`,\n\t\t\t\"a.sky\": `a = 1; print(\"loaded a\")`,\n\t\t},\n\t}\n\n\t\/\/ We load modules b and c in parallel by concurrent calls to\n\t\/\/ cache.Load.  Both of them load module a, but a is executed\n\t\/\/ only once, as witnessed by the sole output of its print\n\t\/\/ statement.\n\n\tch := make(chan string)\n\tfor _, name := range []string{\"b\", \"c\"} {\n\t\tgo func(name string) {\n\t\t\tglobals, err := cache.Load(name + \".sky\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tch <- fmt.Sprintf(\"%s = %s\", name, globals[name])\n\t\t}(name)\n\t}\n\tgot := []string{<-ch, <-ch}\n\tsort.Strings(got)\n\tfmt.Println(strings.Join(got, \"\\n\"))\n\n\t\/\/ Output:\n\t\/\/ loaded a\n\t\/\/ b = 3\n\t\/\/ c = 2\n}\n\n\/\/ ExampleLoadParallelCycle demonstrates detection\n\/\/ of cycles during parallel loading.\nfunc ExampleLoadParallelCycle() {\n\tcache := &cache{\n\t\tcache: make(map[string]*entry),\n\t\tfakeFilesystem: map[string]string{\n\t\t\t\"c.sky\": `load(\"b.sky\", \"b\"); c = b * 2`,\n\t\t\t\"b.sky\": `load(\"a.sky\", \"a\"); b = a * 3`,\n\t\t\t\"a.sky\": `load(\"c.sky\", \"c\"); a = c * 5; print(\"loaded a\")`,\n\t\t},\n\t}\n\n\tch := make(chan string)\n\tfor _, name := range \"bc\" {\n\t\tname := string(name)\n\t\tgo func() {\n\t\t\t_, err := cache.Load(name + \".sky\")\n\t\t\tif err == nil {\n\t\t\t\tlog.Fatalf(\"Load of %s.sky succeeded unexpectedly\", name)\n\t\t\t}\n\t\t\tch <- err.Error()\n\t\t}()\n\t}\n\tgot := []string{<-ch, <-ch}\n\tsort.Strings(got)\n\tfmt.Println(strings.Join(got, \"\\n\"))\n\n\t\/\/ Output:\n\t\/\/ cannot load a.sky: cannot load c.sky: cycle in load graph\n\t\/\/ cannot load b.sky: cannot load a.sky: cannot load c.sky: cycle in load graph\n}\n\n\/\/ cache is a concurrency-safe, duplicate-suppressing,\n\/\/ non-blocking cache of the doLoad function.\n\/\/ See Section 9.7 of gopl.io for an explanation of this structure.\n\/\/ It also features online deadlock (load cycle) detection.\ntype cache struct {\n\tcacheMu sync.Mutex\n\tcache   map[string]*entry\n\n\tfakeFilesystem map[string]string\n}\n\ntype entry struct {\n\towner   unsafe.Pointer \/\/ a *cycleChecker; see cycleCheck\n\tglobals skylark.StringDict\n\terr     error\n\tready   chan struct{}\n}\n\nfunc (c *cache) Load(module string) (skylark.StringDict, error) {\n\treturn c.get(new(cycleChecker), module)\n}\n\n\/\/ get loads and returns an entry (if not already loaded).\nfunc (c *cache) get(cc *cycleChecker, module string) (skylark.StringDict, error) {\n\tc.cacheMu.Lock()\n\te := c.cache[module]\n\tif e != nil {\n\t\tc.cacheMu.Unlock()\n\t\t\/\/ Some other goroutine is getting this module.\n\t\t\/\/ Wait for it to become ready.\n\n\t\t\/\/ Detect load cycles to avoid deadlocks.\n\t\tif err := cycleCheck(e, cc); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcc.setWaitsFor(e)\n\t\t<-e.ready\n\t\tcc.setWaitsFor(nil)\n\t} else {\n\t\t\/\/ First request for this module.\n\t\te = &entry{ready: make(chan struct{})}\n\t\tc.cache[module] = e\n\t\tc.cacheMu.Unlock()\n\n\t\te.setOwner(cc)\n\t\te.globals, e.err = c.doLoad(cc, module)\n\t\te.setOwner(nil)\n\n\t\t\/\/ Broadcast that the entry is now ready.\n\t\tclose(e.ready)\n\t}\n\treturn e.globals, e.err\n}\n\nfunc (c *cache) doLoad(cc *cycleChecker, module string) (skylark.StringDict, error) {\n\tthread := &skylark.Thread{\n\t\tPrint: func(_ *skylark.Thread, msg string) { fmt.Println(msg) },\n\t\tLoad: func(_ *skylark.Thread, module string) (skylark.StringDict, error) {\n\t\t\t\/\/ Tunnel the cycle-checker state for this \"thread of loading\".\n\t\t\treturn c.get(cc, module)\n\t\t},\n\t}\n\tdata := c.fakeFilesystem[module]\n\tglobals := make(skylark.StringDict)\n\terr := skylark.ExecFile(thread, module, data, globals)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn globals, nil\n}\n\n\/\/ -- concurrent cycle checking --\n\n\/\/ A cycleChecker is used for concurrent deadlock detection.\n\/\/ Each top-level call to Load creates its own cycleChecker,\n\/\/ which is passed to all recursive calls it makes.\n\/\/ It corresponds to a logical thread in the deadlock detection literature.\ntype cycleChecker struct {\n\twaitsFor unsafe.Pointer \/\/ an *entry; see cycleCheck\n}\n\nfunc (cc *cycleChecker) setWaitsFor(e *entry) {\n\tatomic.StorePointer(&cc.waitsFor, unsafe.Pointer(e))\n}\n\nfunc (e *entry) setOwner(cc *cycleChecker) {\n\tatomic.StorePointer(&e.owner, unsafe.Pointer(cc))\n}\n\n\/\/ cycleCheck reports whether there is a path in the waits-for graph\n\/\/ from resource 'e' to thread 'me'.\n\/\/\n\/\/ The waits-for graph (WFG) is a bipartite graph whose nodes are\n\/\/ alternately of type entry and cycleChecker.  Each node has at most\n\/\/ one outgoing edge.  An entry has an \"owner\" edge to a cycleChecker\n\/\/ while it is being readied by that cycleChecker, and a cycleChecker\n\/\/ has a \"waits-for\" edge to an entry while it is waiting for that entry\n\/\/ to become ready.\n\/\/\n\/\/ Before adding a waits-for edge, the cache checks whether the new edge\n\/\/ would form a cycle.  If so, this indicates that the load graph is\n\/\/ cyclic and that the following wait operation would deadlock.\nfunc cycleCheck(e *entry, me *cycleChecker) error {\n\tfor e != nil {\n\t\tcc := (*cycleChecker)(atomic.LoadPointer(&e.owner))\n\t\tif cc == nil {\n\t\t\tbreak\n\t\t}\n\t\tif cc == me {\n\t\t\treturn fmt.Errorf(\"cycle in load graph\")\n\t\t}\n\t\te = (*entry)(atomic.LoadPointer(&cc.waitsFor))\n\t}\n\treturn nil\n}\n<commit_msg>example: initialize loaded module in a new thread<commit_after>\/\/ Copyright 2017 The Bazel Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage skylark_test\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"unsafe\"\n\n\t\"github.com\/google\/skylark\"\n)\n\n\/\/ ExampleEmbedding demonstrates a simple embedding\n\/\/ of the Skylark interpreter into a Go program.\nfunc ExampleEmbedding() {\n\tconst data = `\nprint(greeting + \", world\")\n\nsquares = [x*x for x in range(10)]\n`\n\n\tthread := &skylark.Thread{\n\t\tPrint: func(_ *skylark.Thread, msg string) { fmt.Println(msg) },\n\t}\n\tglobals := skylark.StringDict{\n\t\t\"greeting\": skylark.String(\"hello\"),\n\t}\n\tif err := skylark.ExecFile(thread, \"apparent\/filename.sky\", data, globals); err != nil {\n\t\tif evalErr, ok := err.(*skylark.EvalError); ok {\n\t\t\tlog.Fatal(evalErr.Backtrace())\n\t\t}\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Print the global environment.\n\tvar names []string\n\tfor name := range globals {\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\tfmt.Println(\"\\nGlobals:\")\n\tfor _, name := range names {\n\t\tv := globals[name]\n\t\tfmt.Printf(\"%s (%s) = %s\\n\", name, v.Type(), v.String())\n\t}\n\n\t\/\/ Output:\n\t\/\/ hello, world\n\t\/\/\n\t\/\/ Globals:\n\t\/\/ greeting (string) = \"hello\"\n\t\/\/ squares (list) = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n}\n\n\/\/ ExampleLoadSequential demonstrates a simple caching\n\/\/ implementation of 'load' that works sequentially.\nfunc ExampleLoadSequential() {\n\tfakeFilesystem := map[string]string{\n\t\t\"c.sky\": `load(\"b.sky\", \"b\"); c = b + \"!\"`,\n\t\t\"b.sky\": `load(\"a.sky\", \"a\"); b = a + \", world\"`,\n\t\t\"a.sky\": `a = \"Hello\"`,\n\t}\n\n\ttype entry struct {\n\t\tglobals skylark.StringDict\n\t\terr     error\n\t}\n\n\tcache := make(map[string]*entry)\n\n\tvar load func(_ *skylark.Thread, module string) (skylark.StringDict, error)\n\tload = func(_ *skylark.Thread, module string) (skylark.StringDict, error) {\n\t\te, ok := cache[module]\n\t\tif e == nil {\n\t\t\tif ok {\n\t\t\t\t\/\/ request for package whose loading is in progress\n\t\t\t\treturn nil, fmt.Errorf(\"cycle in load graph\")\n\t\t\t}\n\n\t\t\t\/\/ Add a placeholder to indicate \"load in progress\".\n\t\t\tcache[module] = nil\n\n\t\t\t\/\/ Load and initialize the module in a new thread.\n\t\t\tdata := fakeFilesystem[module]\n\t\t\tthread := &skylark.Thread{Load: load}\n\t\t\tglobals := make(skylark.StringDict)\n\t\t\terr := skylark.ExecFile(thread, module, data, globals)\n\t\t\te = &entry{globals, err}\n\n\t\t\t\/\/ Update the cache.\n\t\t\tcache[module] = e\n\t\t}\n\t\treturn e.globals, e.err\n\t}\n\n\tthread := &skylark.Thread{Load: load}\n\tglobals, err := load(thread, \"c.sky\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(globals[\"c\"])\n\n\t\/\/ Output:\n\t\/\/ \"Hello, world!\"\n}\n\n\/\/ ExampleLoadParallel demonstrates a parallel implementation\n\/\/ of 'load' with caching, duplicate suppression, and cycle detection.\nfunc ExampleLoadParallel() {\n\tcache := &cache{\n\t\tcache: make(map[string]*entry),\n\t\tfakeFilesystem: map[string]string{\n\t\t\t\"c.sky\": `load(\"a.sky\", \"a\"); c = a * 2`,\n\t\t\t\"b.sky\": `load(\"a.sky\", \"a\"); b = a * 3`,\n\t\t\t\"a.sky\": `a = 1; print(\"loaded a\")`,\n\t\t},\n\t}\n\n\t\/\/ We load modules b and c in parallel by concurrent calls to\n\t\/\/ cache.Load.  Both of them load module a, but a is executed\n\t\/\/ only once, as witnessed by the sole output of its print\n\t\/\/ statement.\n\n\tch := make(chan string)\n\tfor _, name := range []string{\"b\", \"c\"} {\n\t\tgo func(name string) {\n\t\t\tglobals, err := cache.Load(name + \".sky\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tch <- fmt.Sprintf(\"%s = %s\", name, globals[name])\n\t\t}(name)\n\t}\n\tgot := []string{<-ch, <-ch}\n\tsort.Strings(got)\n\tfmt.Println(strings.Join(got, \"\\n\"))\n\n\t\/\/ Output:\n\t\/\/ loaded a\n\t\/\/ b = 3\n\t\/\/ c = 2\n}\n\n\/\/ ExampleLoadParallelCycle demonstrates detection\n\/\/ of cycles during parallel loading.\nfunc ExampleLoadParallelCycle() {\n\tcache := &cache{\n\t\tcache: make(map[string]*entry),\n\t\tfakeFilesystem: map[string]string{\n\t\t\t\"c.sky\": `load(\"b.sky\", \"b\"); c = b * 2`,\n\t\t\t\"b.sky\": `load(\"a.sky\", \"a\"); b = a * 3`,\n\t\t\t\"a.sky\": `load(\"c.sky\", \"c\"); a = c * 5; print(\"loaded a\")`,\n\t\t},\n\t}\n\n\tch := make(chan string)\n\tfor _, name := range \"bc\" {\n\t\tname := string(name)\n\t\tgo func() {\n\t\t\t_, err := cache.Load(name + \".sky\")\n\t\t\tif err == nil {\n\t\t\t\tlog.Fatalf(\"Load of %s.sky succeeded unexpectedly\", name)\n\t\t\t}\n\t\t\tch <- err.Error()\n\t\t}()\n\t}\n\tgot := []string{<-ch, <-ch}\n\tsort.Strings(got)\n\tfmt.Println(strings.Join(got, \"\\n\"))\n\n\t\/\/ Output:\n\t\/\/ cannot load a.sky: cannot load c.sky: cycle in load graph\n\t\/\/ cannot load b.sky: cannot load a.sky: cannot load c.sky: cycle in load graph\n}\n\n\/\/ cache is a concurrency-safe, duplicate-suppressing,\n\/\/ non-blocking cache of the doLoad function.\n\/\/ See Section 9.7 of gopl.io for an explanation of this structure.\n\/\/ It also features online deadlock (load cycle) detection.\ntype cache struct {\n\tcacheMu sync.Mutex\n\tcache   map[string]*entry\n\n\tfakeFilesystem map[string]string\n}\n\ntype entry struct {\n\towner   unsafe.Pointer \/\/ a *cycleChecker; see cycleCheck\n\tglobals skylark.StringDict\n\terr     error\n\tready   chan struct{}\n}\n\nfunc (c *cache) Load(module string) (skylark.StringDict, error) {\n\treturn c.get(new(cycleChecker), module)\n}\n\n\/\/ get loads and returns an entry (if not already loaded).\nfunc (c *cache) get(cc *cycleChecker, module string) (skylark.StringDict, error) {\n\tc.cacheMu.Lock()\n\te := c.cache[module]\n\tif e != nil {\n\t\tc.cacheMu.Unlock()\n\t\t\/\/ Some other goroutine is getting this module.\n\t\t\/\/ Wait for it to become ready.\n\n\t\t\/\/ Detect load cycles to avoid deadlocks.\n\t\tif err := cycleCheck(e, cc); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcc.setWaitsFor(e)\n\t\t<-e.ready\n\t\tcc.setWaitsFor(nil)\n\t} else {\n\t\t\/\/ First request for this module.\n\t\te = &entry{ready: make(chan struct{})}\n\t\tc.cache[module] = e\n\t\tc.cacheMu.Unlock()\n\n\t\te.setOwner(cc)\n\t\te.globals, e.err = c.doLoad(cc, module)\n\t\te.setOwner(nil)\n\n\t\t\/\/ Broadcast that the entry is now ready.\n\t\tclose(e.ready)\n\t}\n\treturn e.globals, e.err\n}\n\nfunc (c *cache) doLoad(cc *cycleChecker, module string) (skylark.StringDict, error) {\n\tthread := &skylark.Thread{\n\t\tPrint: func(_ *skylark.Thread, msg string) { fmt.Println(msg) },\n\t\tLoad: func(_ *skylark.Thread, module string) (skylark.StringDict, error) {\n\t\t\t\/\/ Tunnel the cycle-checker state for this \"thread of loading\".\n\t\t\treturn c.get(cc, module)\n\t\t},\n\t}\n\tdata := c.fakeFilesystem[module]\n\tglobals := make(skylark.StringDict)\n\terr := skylark.ExecFile(thread, module, data, globals)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn globals, nil\n}\n\n\/\/ -- concurrent cycle checking --\n\n\/\/ A cycleChecker is used for concurrent deadlock detection.\n\/\/ Each top-level call to Load creates its own cycleChecker,\n\/\/ which is passed to all recursive calls it makes.\n\/\/ It corresponds to a logical thread in the deadlock detection literature.\ntype cycleChecker struct {\n\twaitsFor unsafe.Pointer \/\/ an *entry; see cycleCheck\n}\n\nfunc (cc *cycleChecker) setWaitsFor(e *entry) {\n\tatomic.StorePointer(&cc.waitsFor, unsafe.Pointer(e))\n}\n\nfunc (e *entry) setOwner(cc *cycleChecker) {\n\tatomic.StorePointer(&e.owner, unsafe.Pointer(cc))\n}\n\n\/\/ cycleCheck reports whether there is a path in the waits-for graph\n\/\/ from resource 'e' to thread 'me'.\n\/\/\n\/\/ The waits-for graph (WFG) is a bipartite graph whose nodes are\n\/\/ alternately of type entry and cycleChecker.  Each node has at most\n\/\/ one outgoing edge.  An entry has an \"owner\" edge to a cycleChecker\n\/\/ while it is being readied by that cycleChecker, and a cycleChecker\n\/\/ has a \"waits-for\" edge to an entry while it is waiting for that entry\n\/\/ to become ready.\n\/\/\n\/\/ Before adding a waits-for edge, the cache checks whether the new edge\n\/\/ would form a cycle.  If so, this indicates that the load graph is\n\/\/ cyclic and that the following wait operation would deadlock.\nfunc cycleCheck(e *entry, me *cycleChecker) error {\n\tfor e != nil {\n\t\tcc := (*cycleChecker)(atomic.LoadPointer(&e.owner))\n\t\tif cc == nil {\n\t\t\tbreak\n\t\t}\n\t\tif cc == me {\n\t\t\treturn fmt.Errorf(\"cycle in load graph\")\n\t\t}\n\t\te = (*entry)(atomic.LoadPointer(&cc.waitsFor))\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package jwt_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n)\n\nfunc ExampleParse(myToken string, myLookupKey func(interface{}) (interface{}, error)) {\n\ttoken, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {\n\t\treturn myLookupKey(token.Header[\"kid\"])\n\t})\n\n\tif err == nil && token.Valid {\n\t\tfmt.Println(\"Your token is valid.  I like your style.\")\n\t} else {\n\t\tfmt.Println(\"This token is terrible!  I cannot accept this.\")\n\t}\n}\n\nfunc ExampleNew() {\n\t\/\/ Create the token\n\ttoken := jwt.New(jwt.SigningMethodRS256)\n\n\t\/\/ Set some claims\n\tclaims := token.Claims.(jwt.MapClaim)\n\tclaims[\"foo\"] = \"bar\"\n\tclaims[\"exp\"] = time.Unix(0, 0).Add(time.Hour * 1).Unix()\n\n\tfmt.Printf(\"%v\\n\", token.Claims)\n\t\/\/Output: map[foo:bar exp:3600]\n}\n\nfunc ExampleNewWithClaims(mySigningKey []byte) (string, error) {\n\t\/\/ Create the Claims\n\tclaims := jwt.StandardClaims{\n\t\tExpiresAt: 15000,\n\t\tIssuer:    \"test\",\n\t}\n\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)\n\treturn token.SignedString(mySigningKey)\n}\n\nfunc ExampleParse_errorChecking(myToken string, myLookupKey func(interface{}) (interface{}, error)) {\n\ttoken, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {\n\t\treturn myLookupKey(token.Header[\"kid\"])\n\t})\n\n\tif token.Valid {\n\t\tfmt.Println(\"You look nice today\")\n\t} else if ve, ok := err.(*jwt.ValidationError); ok {\n\t\tif ve.Errors&jwt.ValidationErrorMalformed != 0 {\n\t\t\tfmt.Println(\"That's not even a token\")\n\t\t} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {\n\t\t\t\/\/ Token is either expired or not active yet\n\t\t\tfmt.Println(\"Timing is everything\")\n\t\t} else {\n\t\t\tfmt.Println(\"Couldn't handle this token:\", err)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Couldn't handle this token:\", err)\n\t}\n\n}\n<commit_msg>fixed ordering of map output in example test<commit_after>package jwt_test\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n)\n\nfunc ExampleParse(myToken string, myLookupKey func(interface{}) (interface{}, error)) {\n\ttoken, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {\n\t\treturn myLookupKey(token.Header[\"kid\"])\n\t})\n\n\tif err == nil && token.Valid {\n\t\tfmt.Println(\"Your token is valid.  I like your style.\")\n\t} else {\n\t\tfmt.Println(\"This token is terrible!  I cannot accept this.\")\n\t}\n}\n\nfunc ExampleNew() {\n\t\/\/ Create the token\n\ttoken := jwt.New(jwt.SigningMethodRS256)\n\n\t\/\/ Set some claims\n\tclaims := token.Claims.(jwt.MapClaim)\n\tclaims[\"foo\"] = \"bar\"\n\tclaims[\"exp\"] = time.Unix(0, 0).Add(time.Hour * 1).Unix()\n\n\tfmt.Printf(\"<%T> foo:%v exp:%v\\n\", token.Claims, claims[\"foo\"], claims[\"exp\"])\n\t\/\/Output: <jwt.MapClaim> foo:bar exp:3600\n}\n\nfunc ExampleNewWithClaims(mySigningKey []byte) (string, error) {\n\t\/\/ Create the Claims\n\tclaims := jwt.StandardClaims{\n\t\tExpiresAt: 15000,\n\t\tIssuer:    \"test\",\n\t}\n\n\ttoken := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)\n\treturn token.SignedString(mySigningKey)\n}\n\nfunc ExampleParse_errorChecking(myToken string, myLookupKey func(interface{}) (interface{}, error)) {\n\ttoken, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {\n\t\treturn myLookupKey(token.Header[\"kid\"])\n\t})\n\n\tif token.Valid {\n\t\tfmt.Println(\"You look nice today\")\n\t} else if ve, ok := err.(*jwt.ValidationError); ok {\n\t\tif ve.Errors&jwt.ValidationErrorMalformed != 0 {\n\t\t\tfmt.Println(\"That's not even a token\")\n\t\t} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {\n\t\t\t\/\/ Token is either expired or not active yet\n\t\t\tfmt.Println(\"Timing is everything\")\n\t\t} else {\n\t\t\tfmt.Println(\"Couldn't handle this token:\", err)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Couldn't handle this token:\", err)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"dns\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc q(w dns.RequestWriter, m *dns.Msg) {\n\tw.Send(m)\n\tr, err := w.Receive()\n\tif err != nil {\n\t\tfmt.Printf(\"%s\\n\", err.Error())\n\t}\n\tw.Write(r)\n}\n\nfunc main() {\n\tdnssec := flag.Bool(\"dnssec\", false, \"request DNSSEC records\")\n\tquery := flag.Bool(\"question\", false, \"show question\")\n\tshort := flag.Bool(\"short\", false, \"abbreviate long DNSKEY and RRSIG RRs\")\n        check := flag.Bool(\"check\", false, \"check internal DNSSEC consistency\")\n\tport := flag.Int(\"port\", 53, \"port number to use\")\n\taa := flag.Bool(\"aa\", false, \"set AA flag in query\")\n\tad := flag.Bool(\"ad\", false, \"set AD flag in query\")\n\tcd := flag.Bool(\"cd\", false, \"set CD flag in query\")\n\trd := flag.Bool(\"rd\", true, \"unset RD flag in query\")\n\ttcp := flag.Bool(\"tcp\", false, \"TCP mode\")\n\tnsid := flag.Bool(\"nsid\", false, \"ask for NSID\")\n\tfp := flag.Bool(\"fp\", false, \"enable server detection\")\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s [@server] [qtype] [qclass] [name ...]\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\n\tconf, _ := dns.ClientConfigFromFile(\"\/etc\/resolv.conf\")\n\tnameserver := \"@\" + conf.Servers[0]\n\tqtype := uint16(0)\n\tqclass := uint16(dns.ClassINET) \/\/ Default qclass\n\tvar qname []string\n\n\tflag.Parse()\n\nFlags:\n\tfor i := 0; i < flag.NArg(); i++ {\n\t\t\/\/ If it starts with @ it is a nameserver\n\t\tif flag.Arg(i)[0] == '@' {\n\t\t\tnameserver = flag.Arg(i)\n\t\t\tcontinue Flags\n\t\t}\n\t\t\/\/ First class, then type, to make ANY queries possible\n\t\t\/\/ And if it looks like type, it is a type\n\t\tif k, ok := dns.Str_rr[strings.ToUpper(flag.Arg(i))]; ok {\n\t\t\tqtype = k\n\t\t\tcontinue Flags\n\t\t}\n\t\t\/\/ If it looks like a class, it is a class\n\t\tif k, ok := dns.Str_class[strings.ToUpper(flag.Arg(i))]; ok {\n\t\t\tqclass = k\n\t\t\tcontinue Flags\n\t\t}\n\t\t\/\/ If it starts with TYPExxx it is unknown rr\n\t\tif strings.HasPrefix(flag.Arg(i), \"TYPE\") {\n\t\t\ti, e := strconv.Atoi(string([]byte(flag.Arg(i))[4:]))\n\t\t\tif e == nil {\n\t\t\t\tqtype = uint16(i)\n\t\t\t\tcontinue Flags\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Anything else is a qname\n\t\tqname = append(qname, flag.Arg(i))\n\t}\n\tif len(qname) == 0 {\n\t\tqname = make([]string, 1)\n\t\tqname[0] = \".\"\n\t\tqtype = dns.TypeNS\n\t}\n\tif qtype == 0 {\n\t\tqtype = dns.TypeA\n\t}\n\n\tnameserver = string([]byte(nameserver)[1:]) \/\/ chop off @\n\tnameserver += \":\" + strconv.Itoa(*port)\n\n\t\/\/ ipv6 todo\n\t\/\/ We use the async query handling, just to show how\n\t\/\/ it is to be used.\n\tdns.HandleQueryFunc(\".\", q)\n\tdns.ListenAndQuery(nil, nil)\n\tc := dns.NewClient()\n\tif *tcp {\n\t\tc.Net = \"tcp\"\n\t}\n\n\tm := new(dns.Msg)\n\tm.MsgHdr.Authoritative = *aa\n\tm.MsgHdr.AuthenticatedData = *ad\n\tm.MsgHdr.CheckingDisabled = *cd\n\tm.MsgHdr.RecursionDesired = *rd\n\tm.Question = make([]dns.Question, 1)\n\tif *dnssec || *nsid {\n\t\to := new(dns.RR_OPT)\n\t\to.Hdr.Name = \".\"\n\t\to.Hdr.Rrtype = dns.TypeOPT\n\t\tif *dnssec {\n\t\t\to.SetDo()\n\t\t\to.SetUDPSize(dns.DefaultMsgSize)\n\t\t}\n\t\tif *nsid {\n\t\t\to.SetNsid(\"\")\n\t\t}\n\t\tm.Extra = append(m.Extra, o)\n\t}\n\n\tif *fp {\n\t\tstartParse(nameserver)\n\t\treturn\n\t}\n\tfor _, v := range qname {\n\t\tm.Question[0] = dns.Question{v, qtype, qclass}\n\t\tm.Id = dns.Id()\n\t\tif *query {\n\t\t\tfmt.Printf(\"%s\\n\", msgToFingerprint(m))\n\t\t\tfmt.Printf(\"%s\\n\", m.String())\n\t\t}\n\t\tc.Do(m, nameserver)\n\t}\n\n\ti := 0\nforever:\n\tfor {\n\t\tselect {\n\t\tcase r := <-dns.DefaultReplyChan:\n\t\t\tif r.Reply != nil {\n\t\t\t\tif r.Reply.Rcode == dns.RcodeSuccess {\n\t\t\t\t\tif r.Request.Id != r.Reply.Id {\n\t\t\t\t\t\tfmt.Printf(\"Id mismatch\\n\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif *short {\n\t\t\t\t\tr.Reply = shortMsg(r.Reply)\n\t\t\t\t}\n\n\t\t\t\tfmt.Printf(\"%v\", r.Reply)\n                                if *check {\n                                        println()\n                                        sigCheck(r.Reply, nameserver)\n                                        if err := r.Reply.Nsec3Verify(r.Reply.Question[0]); err == nil {\n                                                fmt.Printf(\";+ Correct authenticated denial of existence (NSEC3)\\n\")\n                                        } else {\n                                                fmt.Printf(\";- Incorrect authenticated denial of existence (NSEC3): %s\\n\",err.Error())\n                                        }\n\n                                }\n\t\t\t}\n\t\t\ti++\n\t\t\tif i == len(qname) {\n\t\t\t\tbreak forever\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Check the sigs in the msg, get the signer's key (additional query), get the \n\/\/ rrset from the message, check the signature(s)\nfunc sigCheck(in *dns.Msg, server string) {\n        for _, rr := range in.Answer {\n                if rr.Header().Rrtype == dns.TypeRRSIG {\n                        rrset := getRRset(in.Answer, rr.Header().Name, rr.(*dns.RR_RRSIG).TypeCovered)\n                        key := getKey(rr.(*dns.RR_RRSIG).SignerName, rr.(*dns.RR_RRSIG).KeyTag, server)\n                        if key == nil {\n                                fmt.Printf(\";? DNSKEY %s\/%d not found\\n\", rr.(*dns.RR_RRSIG).SignerName, rr.(*dns.RR_RRSIG).KeyTag)\n                        }\n                        if err := rr.(*dns.RR_RRSIG).Verify(key, rrset); err != nil {\n                                fmt.Printf(\";- Bogus signature,  %s does not RRSet with DNSKEY %s\/%d\\n\", shortSig(rr.(*dns.RR_RRSIG)), key.Header().Name, key.KeyTag())\n                        } else {\n                                fmt.Printf(\";+ Secure signature, %s validates RRSet with DNSKEY %s\/%d\\n\", shortSig(rr.(*dns.RR_RRSIG)), key.Header().Name, key.KeyTag())\n                        }\n                }\n        }\n        for _, rr := range in.Ns {\n                if rr.Header().Rrtype == dns.TypeRRSIG {\n                        rrset := getRRset(in.Ns, rr.Header().Name, rr.(*dns.RR_RRSIG).TypeCovered)\n                        key := getKey(rr.(*dns.RR_RRSIG).SignerName, rr.(*dns.RR_RRSIG).KeyTag, server)\n                        if key == nil {\n                                fmt.Printf(\";? DNSKEY %s\/%d not found\\n\", rr.(*dns.RR_RRSIG).SignerName, rr.(*dns.RR_RRSIG).KeyTag)\n                        }\n                        if err := rr.(*dns.RR_RRSIG).Verify(key, rrset); err != nil {\n                                fmt.Printf(\";- Bogus signature,  %s does not RRSet with DNSKEY %s\/%d\\n\", shortSig(rr.(*dns.RR_RRSIG)), key.Header().Name, key.KeyTag())\n                        } else {\n                                fmt.Printf(\";+ Secure signature, %s validates RRSet with DNSKEY %s\/%d\\n\", shortSig(rr.(*dns.RR_RRSIG)), key.Header().Name, key.KeyTag())\n                        }\n                }\n        }\n        for _, rr := range in.Extra {\n                if rr.Header().Rrtype == dns.TypeRRSIG {\n                        rrset := getRRset(in.Extra, rr.Header().Name, rr.(*dns.RR_RRSIG).TypeCovered)\n                        key := getKey(rr.(*dns.RR_RRSIG).SignerName, rr.(*dns.RR_RRSIG).KeyTag, server)\n                        if key == nil {\n                                fmt.Printf(\";? DNSKEY %s\/%d not found\\n\", rr.(*dns.RR_RRSIG).SignerName, rr.(*dns.RR_RRSIG).KeyTag)\n                        }\n                        if err := rr.(*dns.RR_RRSIG).Verify(key, rrset); err != nil {\n                                fmt.Printf(\";- Bogus signature,  %s does not RRSet with DNSKEY %s\/%d\\n\", shortSig(rr.(*dns.RR_RRSIG)), key.Header().Name, key.KeyTag())\n                        } else {\n                                fmt.Printf(\";+ Secure signature, %s validates RRSet with DNSKEY %s\/%d\\n\", shortSig(rr.(*dns.RR_RRSIG)), key.Header().Name, key.KeyTag())\n                        }\n                }\n        }\n}\n\n\/\/ Return the RRset belonging to the signature with name and type t\nfunc getRRset(l []dns.RR, name string, t uint16) []dns.RR {\n        l1 := make([]dns.RR, 0)\n        for _, rr := range l {\n                if rr.Header().Name == name && rr.Header().Rrtype == t {\n                        l1 = append(l1, rr)\n                }\n        }\n        return l1\n}\n\n\/\/ Get the key from the DNS (uses the local resolver) and return them.\n\/\/ If nothing is found we return nil\nfunc getKey(name string, keytag uint16, server string) *dns.RR_DNSKEY {\n        c := dns.NewClient()\n        m := new(dns.Msg)\n        m.SetQuestion(name, dns.TypeDNSKEY)\n        r, err := c.Exchange(m, server)\n        if err != nil {\n                return nil\n        }\n        for _, k := range r.Answer {\n                if k1, ok := k.(*dns.RR_DNSKEY); ok {\n                        if k1.KeyTag() == keytag {\n                                return k1\n                        }\n                }\n        }\n        return nil\n}\n\n\/\/ shorten RRSIG to \"miek.nl RRSIG(NS)\"\nfunc shortSig(sig *dns.RR_RRSIG) string {\n        return sig.Header().Name + \" RRSIG(\" + dns.Rr_str[sig.TypeCovered] + \")\"\n}\n\n\/\/ Walk trough message and short Key data and Sig data\nfunc shortMsg(in *dns.Msg) *dns.Msg {\n\tfor i := 0; i < len(in.Answer); i++ {\n\t\tin.Answer[i] = shortRR(in.Answer[i])\n\t}\n\tfor i := 0; i < len(in.Ns); i++ {\n\t\tin.Ns[i] = shortRR(in.Ns[i])\n\t}\n\tfor i := 0; i < len(in.Extra); i++ {\n\t\tin.Extra[i] = shortRR(in.Extra[i])\n\t}\n\treturn in\n}\n\nfunc shortRR(r dns.RR) dns.RR {\n\tswitch t := r.(type) {\n\tcase *dns.RR_DS:\n\t\tt.Digest = \"...\"\n\tcase *dns.RR_DNSKEY:\n\t\tt.PublicKey = \"...\"\n\tcase *dns.RR_RRSIG:\n\t\tt.Signature = \"...\"\n\t\tt.Inception = 0 \/\/ For easy grepping\n\t\tt.Expiration = 0\n\tcase *dns.RR_NSEC3:\n\t\tt.Salt = \"-\" \/\/ Nobody cares\n\t\tif len(t.TypeBitMap) > 5 {\n\t\t\tt.TypeBitMap = t.TypeBitMap[1:5]\n\t\t}\n\t}\n\treturn r\n}\n<commit_msg>Nsec3 needs some tweaking<commit_after>package main\n\nimport (\n\t\"dns\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nfunc q(w dns.RequestWriter, m *dns.Msg) {\n\tw.Send(m)\n\tr, err := w.Receive()\n\tif err != nil {\n\t\tfmt.Printf(\"%s\\n\", err.Error())\n\t}\n\tw.Write(r)\n}\n\nfunc main() {\n\tdnssec := flag.Bool(\"dnssec\", false, \"request DNSSEC records\")\n\tquery := flag.Bool(\"question\", false, \"show question\")\n\tshort := flag.Bool(\"short\", false, \"abbreviate long DNSKEY and RRSIG RRs\")\n        check := flag.Bool(\"check\", false, \"check internal DNSSEC consistency\")\n\tport := flag.Int(\"port\", 53, \"port number to use\")\n\taa := flag.Bool(\"aa\", false, \"set AA flag in query\")\n\tad := flag.Bool(\"ad\", false, \"set AD flag in query\")\n\tcd := flag.Bool(\"cd\", false, \"set CD flag in query\")\n\trd := flag.Bool(\"rd\", true, \"unset RD flag in query\")\n\ttcp := flag.Bool(\"tcp\", false, \"TCP mode\")\n\tnsid := flag.Bool(\"nsid\", false, \"ask for NSID\")\n\tfp := flag.Bool(\"fp\", false, \"enable server detection\")\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage: %s [@server] [qtype] [qclass] [name ...]\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\n\tconf, _ := dns.ClientConfigFromFile(\"\/etc\/resolv.conf\")\n\tnameserver := \"@\" + conf.Servers[0]\n\tqtype := uint16(0)\n\tqclass := uint16(dns.ClassINET) \/\/ Default qclass\n\tvar qname []string\n\n\tflag.Parse()\n\nFlags:\n\tfor i := 0; i < flag.NArg(); i++ {\n\t\t\/\/ If it starts with @ it is a nameserver\n\t\tif flag.Arg(i)[0] == '@' {\n\t\t\tnameserver = flag.Arg(i)\n\t\t\tcontinue Flags\n\t\t}\n\t\t\/\/ First class, then type, to make ANY queries possible\n\t\t\/\/ And if it looks like type, it is a type\n\t\tif k, ok := dns.Str_rr[strings.ToUpper(flag.Arg(i))]; ok {\n\t\t\tqtype = k\n\t\t\tcontinue Flags\n\t\t}\n\t\t\/\/ If it looks like a class, it is a class\n\t\tif k, ok := dns.Str_class[strings.ToUpper(flag.Arg(i))]; ok {\n\t\t\tqclass = k\n\t\t\tcontinue Flags\n\t\t}\n\t\t\/\/ If it starts with TYPExxx it is unknown rr\n\t\tif strings.HasPrefix(flag.Arg(i), \"TYPE\") {\n\t\t\ti, e := strconv.Atoi(string([]byte(flag.Arg(i))[4:]))\n\t\t\tif e == nil {\n\t\t\t\tqtype = uint16(i)\n\t\t\t\tcontinue Flags\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Anything else is a qname\n\t\tqname = append(qname, flag.Arg(i))\n\t}\n\tif len(qname) == 0 {\n\t\tqname = make([]string, 1)\n\t\tqname[0] = \".\"\n\t\tqtype = dns.TypeNS\n\t}\n\tif qtype == 0 {\n\t\tqtype = dns.TypeA\n\t}\n\n\tnameserver = string([]byte(nameserver)[1:]) \/\/ chop off @\n\tnameserver += \":\" + strconv.Itoa(*port)\n\n\t\/\/ ipv6 todo\n\t\/\/ We use the async query handling, just to show how\n\t\/\/ it is to be used.\n\tdns.HandleQueryFunc(\".\", q)\n\tdns.ListenAndQuery(nil, nil)\n\tc := dns.NewClient()\n\tif *tcp {\n\t\tc.Net = \"tcp\"\n\t}\n\n\tm := new(dns.Msg)\n\tm.MsgHdr.Authoritative = *aa\n\tm.MsgHdr.AuthenticatedData = *ad\n\tm.MsgHdr.CheckingDisabled = *cd\n\tm.MsgHdr.RecursionDesired = *rd\n\tm.Question = make([]dns.Question, 1)\n\tif *dnssec || *nsid {\n\t\to := new(dns.RR_OPT)\n\t\to.Hdr.Name = \".\"\n\t\to.Hdr.Rrtype = dns.TypeOPT\n\t\tif *dnssec {\n\t\t\to.SetDo()\n\t\t\to.SetUDPSize(dns.DefaultMsgSize)\n\t\t}\n\t\tif *nsid {\n\t\t\to.SetNsid(\"\")\n\t\t}\n\t\tm.Extra = append(m.Extra, o)\n\t}\n\n\tif *fp {\n\t\tstartParse(nameserver)\n\t\treturn\n\t}\n\tfor _, v := range qname {\n\t\tm.Question[0] = dns.Question{v, qtype, qclass}\n\t\tm.Id = dns.Id()\n\t\tif *query {\n\t\t\tfmt.Printf(\"%s\\n\", msgToFingerprint(m))\n\t\t\tfmt.Printf(\"%s\\n\", m.String())\n\t\t}\n\t\tc.Do(m, nameserver)\n\t}\n\n\ti := 0\nforever:\n\tfor {\n\t\tselect {\n\t\tcase r := <-dns.DefaultReplyChan:\n\t\t\tif r.Reply != nil {\n\t\t\t\tif r.Reply.Rcode == dns.RcodeSuccess {\n\t\t\t\t\tif r.Request.Id != r.Reply.Id {\n\t\t\t\t\t\tfmt.Printf(\"Id mismatch\\n\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif *short {\n\t\t\t\t\tr.Reply = shortMsg(r.Reply)\n\t\t\t\t}\n\n\t\t\t\tfmt.Printf(\"%v\", r.Reply)\n                                if *check {\n                                        println()\n                                        sigCheck(r.Reply, nameserver)\n                                        if err := r.Reply.Nsec3Verify(r.Reply.Question[0]); err == nil {\n                                                fmt.Printf(\";+ Correct authenticated denial of existence (NSEC3)\\n\")\n                                        } else {\n                                                \/\/ Could be: no nsec3 records\n                                        \/\/        fmt.Printf(\";- Incorrect authenticated denial of existence (NSEC3): %s\\n\",err.Error())\n                                        }\n\n                                }\n\t\t\t}\n\t\t\ti++\n\t\t\tif i == len(qname) {\n\t\t\t\tbreak forever\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Check the sigs in the msg, get the signer's key (additional query), get the \n\/\/ rrset from the message, check the signature(s)\nfunc sigCheck(in *dns.Msg, server string) {\n        for _, rr := range in.Answer {\n                if rr.Header().Rrtype == dns.TypeRRSIG {\n                        rrset := getRRset(in.Answer, rr.Header().Name, rr.(*dns.RR_RRSIG).TypeCovered)\n                        key := getKey(rr.(*dns.RR_RRSIG).SignerName, rr.(*dns.RR_RRSIG).KeyTag, server)\n                        if key == nil {\n                                fmt.Printf(\";? DNSKEY %s\/%d not found\\n\", rr.(*dns.RR_RRSIG).SignerName, rr.(*dns.RR_RRSIG).KeyTag)\n                        }\n                        if err := rr.(*dns.RR_RRSIG).Verify(key, rrset); err != nil {\n                                fmt.Printf(\";- Bogus signature,  %s does not RRSet with DNSKEY %s\/%d\\n\", shortSig(rr.(*dns.RR_RRSIG)), key.Header().Name, key.KeyTag())\n                        } else {\n                                fmt.Printf(\";+ Secure signature, %s validates RRSet with DNSKEY %s\/%d\\n\", shortSig(rr.(*dns.RR_RRSIG)), key.Header().Name, key.KeyTag())\n                        }\n                }\n        }\n        for _, rr := range in.Ns {\n                if rr.Header().Rrtype == dns.TypeRRSIG {\n                        rrset := getRRset(in.Ns, rr.Header().Name, rr.(*dns.RR_RRSIG).TypeCovered)\n                        key := getKey(rr.(*dns.RR_RRSIG).SignerName, rr.(*dns.RR_RRSIG).KeyTag, server)\n                        if key == nil {\n                                fmt.Printf(\";? DNSKEY %s\/%d not found\\n\", rr.(*dns.RR_RRSIG).SignerName, rr.(*dns.RR_RRSIG).KeyTag)\n                        }\n                        if err := rr.(*dns.RR_RRSIG).Verify(key, rrset); err != nil {\n                                fmt.Printf(\";- Bogus signature,  %s does not RRSet with DNSKEY %s\/%d\\n\", shortSig(rr.(*dns.RR_RRSIG)), key.Header().Name, key.KeyTag())\n                        } else {\n                                fmt.Printf(\";+ Secure signature, %s validates RRSet with DNSKEY %s\/%d\\n\", shortSig(rr.(*dns.RR_RRSIG)), key.Header().Name, key.KeyTag())\n                        }\n                }\n        }\n        for _, rr := range in.Extra {\n                if rr.Header().Rrtype == dns.TypeRRSIG {\n                        rrset := getRRset(in.Extra, rr.Header().Name, rr.(*dns.RR_RRSIG).TypeCovered)\n                        key := getKey(rr.(*dns.RR_RRSIG).SignerName, rr.(*dns.RR_RRSIG).KeyTag, server)\n                        if key == nil {\n                                fmt.Printf(\";? DNSKEY %s\/%d not found\\n\", rr.(*dns.RR_RRSIG).SignerName, rr.(*dns.RR_RRSIG).KeyTag)\n                        }\n                        if err := rr.(*dns.RR_RRSIG).Verify(key, rrset); err != nil {\n                                fmt.Printf(\";- Bogus signature,  %s does not RRSet with DNSKEY %s\/%d\\n\", shortSig(rr.(*dns.RR_RRSIG)), key.Header().Name, key.KeyTag())\n                        } else {\n                                fmt.Printf(\";+ Secure signature, %s validates RRSet with DNSKEY %s\/%d\\n\", shortSig(rr.(*dns.RR_RRSIG)), key.Header().Name, key.KeyTag())\n                        }\n                }\n        }\n}\n\n\/\/ Return the RRset belonging to the signature with name and type t\nfunc getRRset(l []dns.RR, name string, t uint16) []dns.RR {\n        l1 := make([]dns.RR, 0)\n        for _, rr := range l {\n                if rr.Header().Name == name && rr.Header().Rrtype == t {\n                        l1 = append(l1, rr)\n                }\n        }\n        return l1\n}\n\n\/\/ Get the key from the DNS (uses the local resolver) and return them.\n\/\/ If nothing is found we return nil\nfunc getKey(name string, keytag uint16, server string) *dns.RR_DNSKEY {\n        c := dns.NewClient()\n        m := new(dns.Msg)\n        m.SetQuestion(name, dns.TypeDNSKEY)\n        r, err := c.Exchange(m, server)\n        if err != nil {\n                return nil\n        }\n        for _, k := range r.Answer {\n                if k1, ok := k.(*dns.RR_DNSKEY); ok {\n                        if k1.KeyTag() == keytag {\n                                return k1\n                        }\n                }\n        }\n        return nil\n}\n\n\/\/ shorten RRSIG to \"miek.nl RRSIG(NS)\"\nfunc shortSig(sig *dns.RR_RRSIG) string {\n        return sig.Header().Name + \" RRSIG(\" + dns.Rr_str[sig.TypeCovered] + \")\"\n}\n\n\/\/ Walk trough message and short Key data and Sig data\nfunc shortMsg(in *dns.Msg) *dns.Msg {\n\tfor i := 0; i < len(in.Answer); i++ {\n\t\tin.Answer[i] = shortRR(in.Answer[i])\n\t}\n\tfor i := 0; i < len(in.Ns); i++ {\n\t\tin.Ns[i] = shortRR(in.Ns[i])\n\t}\n\tfor i := 0; i < len(in.Extra); i++ {\n\t\tin.Extra[i] = shortRR(in.Extra[i])\n\t}\n\treturn in\n}\n\nfunc shortRR(r dns.RR) dns.RR {\n\tswitch t := r.(type) {\n\tcase *dns.RR_DS:\n\t\tt.Digest = \"...\"\n\tcase *dns.RR_DNSKEY:\n\t\tt.PublicKey = \"...\"\n\tcase *dns.RR_RRSIG:\n\t\tt.Signature = \"...\"\n\t\tt.Inception = 0 \/\/ For easy grepping\n\t\tt.Expiration = 0\n\tcase *dns.RR_NSEC3:\n\t\tt.Salt = \"-\" \/\/ Nobody cares\n\t\tif len(t.TypeBitMap) > 5 {\n\t\t\tt.TypeBitMap = t.TypeBitMap[1:5]\n\t\t}\n\t}\n\treturn r\n}\n<|endoftext|>"}
{"text":"<commit_before>package httpauth\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha256\"\n\t\"crypto\/subtle\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\ntype basicAuth struct {\n\th    http.Handler\n\topts AuthOptions\n}\n\n\/\/ AuthOptions stores the configuration for HTTP Basic Authentication.\n\/\/\n\/\/ A http.Handler may also be passed to UnauthorizedHandler to override the\n\/\/ default error handler if you wish to serve a custom template\/response.\ntype AuthOptions struct {\n\tRealm               string\n\tUser                string\n\tPassword            string\n\tAuthFunc            func(string, string, *http.Request) bool\n\tUnauthorizedHandler http.Handler\n}\n\n\/\/ Satisfies the http.Handler interface for basicAuth.\nfunc (b basicAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Check if we have a user-provided error handler, else set a default\n\tif b.opts.UnauthorizedHandler == nil {\n\t\tb.opts.UnauthorizedHandler = http.HandlerFunc(defaultUnauthorizedHandler)\n\t}\n\n\t\/\/ Check that the provided details match\n\tif b.authenticate(r) == false {\n\t\tb.requestAuth(w, r)\n\t\treturn\n\t}\n\n\t\/\/ Call the next handler on success.\n\tb.h.ServeHTTP(w, r)\n}\n\n\/\/ authenticate retrieves and then validates the user:password combination provided in\n\/\/ the request header. Returns 'false' if the user has not successfully authenticated.\nfunc (b *basicAuth) authenticate(r *http.Request) bool {\n\tconst basicScheme string = \"Basic \"\n\n\tif r == nil {\n\t\treturn false\n\t}\n\n\t\/\/ In simple mode, prevent authentication with empty credentials if User or\n\t\/\/ Password is not set.\n\tif b.opts.AuthFunc == nil && (b.opts.User == \"\" || b.opts.Password == \"\") {\n\t\treturn false\n\t}\n\n\t\/\/ Confirm the request is sending Basic Authentication credentials.\n\tauth := r.Header.Get(\"Authorization\")\n\tif !strings.HasPrefix(auth, basicScheme) {\n\t\treturn false\n\t}\n\n\t\/\/ Get the plain-text username and password from the request.\n\t\/\/ The first six characters are skipped - e.g. \"Basic \".\n\tstr, err := base64.StdEncoding.DecodeString(auth[len(basicScheme):])\n\tif err != nil {\n\t\treturn false\n\t}\n\n\t\/\/ Split on the first \":\" character only, with any subsequent colons assumed to be part\n\t\/\/ of the password. Note that the RFC2617 standard does not place any limitations on\n\t\/\/ allowable characters in the password.\n\tcreds := bytes.SplitN(str, []byte(\":\"), 2)\n\n\tif len(creds) != 2 {\n\t\treturn false\n\t}\n\n\tgivenUser := string(creds[0])\n\tgivenPass := string(creds[1])\n\n\t\/\/ Default to Simple mode if no AuthFunc is defined.\n\tif b.opts.AuthFunc == nil {\n\t\tb.opts.AuthFunc = b.simpleBasicAuthFunc\n\t}\n\n\treturn b.opts.AuthFunc(givenUser, givenPass, r)\n}\n\n\/\/ simpleBasicAuthFunc authenticates the supplied username and password against\n\/\/ the User and Password set in the Options struct.\nfunc (b *basicAuth) simpleBasicAuthFunc(user, pass string, r *http.Request) bool {\n\t\/\/ Equalize lengths of supplied and required credentials\n\t\/\/ by hashing them\n\tgivenUser := sha256.Sum256([]byte(user))\n\tgivenPass := sha256.Sum256([]byte(pass))\n\trequiredUser := sha256.Sum256([]byte(b.opts.User))\n\trequiredPass := sha256.Sum256([]byte(b.opts.Password))\n\n\t\/\/ Compare the supplied credentials to those set in our options\n\tif subtle.ConstantTimeCompare(givenUser[:], requiredUser[:]) == 1 &&\n\t\tsubtle.ConstantTimeCompare(givenPass[:], requiredPass[:]) == 1 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ Require authentication, and serve our error handler otherwise.\nfunc (b *basicAuth) requestAuth(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"WWW-Authenticate\", fmt.Sprintf(`Basic realm=%q`, b.opts.Realm))\n\tb.opts.UnauthorizedHandler.ServeHTTP(w, r)\n}\n\n\/\/ defaultUnauthorizedHandler provides a default HTTP 401 Unauthorized response.\nfunc defaultUnauthorizedHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)\n}\n\n\/\/ BasicAuth provides HTTP middleware for protecting URIs with HTTP Basic Authentication\n\/\/ as per RFC 2617. The server authenticates a user:password combination provided in the\n\/\/ \"Authorization\" HTTP header.\n\/\/\n\/\/ Example:\n\/\/\n\/\/     package main\n\/\/\n\/\/     import(\n\/\/            \"net\/http\"\n\/\/            \"github.com\/zenazn\/goji\"\n\/\/            \"github.com\/goji\/httpauth\"\n\/\/     )\n\/\/\n\/\/     func main() {\n\/\/          basicOpts := httpauth.AuthOptions{\n\/\/                      Realm: \"Restricted\",\n\/\/                      User: \"Dave\",\n\/\/                      Password: \"ClearText\",\n\/\/                  }\n\/\/\n\/\/          goji.Use(httpauth.BasicAuth(basicOpts), SomeOtherMiddleware)\n\/\/          goji.Get(\"\/thing\", myHandler)\n\/\/  }\n\/\/\n\/\/ Note: HTTP Basic Authentication credentials are sent in plain text, and therefore it does\n\/\/ not make for a wholly secure authentication mechanism. You should serve your content over\n\/\/ HTTPS to mitigate this, noting that \"Basic Authentication\" is meant to be just that: basic!\nfunc BasicAuth(o AuthOptions) func(http.Handler) http.Handler {\n\tfn := func(h http.Handler) http.Handler {\n\t\treturn basicAuth{h, o}\n\t}\n\treturn fn\n}\n\n\/\/ SimpleBasicAuth is a convenience wrapper around BasicAuth. It takes a user and password, and\n\/\/ returns a pre-configured BasicAuth handler using the \"Restricted\" realm and a default 401 handler.\n\/\/\n\/\/ Example:\n\/\/\n\/\/     package main\n\/\/\n\/\/     import(\n\/\/            \"net\/http\"\n\/\/            \"github.com\/zenazn\/goji\/web\/httpauth\"\n\/\/     )\n\/\/\n\/\/     func main() {\n\/\/\n\/\/          goji.Use(httpauth.SimpleBasicAuth(\"dave\", \"somepassword\"), SomeOtherMiddleware)\n\/\/          goji.Get(\"\/thing\", myHandler)\n\/\/      }\n\/\/\nfunc SimpleBasicAuth(user, password string) func(http.Handler) http.Handler {\n\topts := AuthOptions{\n\t\tRealm:    \"Restricted\",\n\t\tUser:     user,\n\t\tPassword: password,\n\t}\n\treturn BasicAuth(opts)\n}\n<commit_msg>[bugfix] Allow empty passwords again. Reverts part of 723e9a2b49655.<commit_after>package httpauth\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha256\"\n\t\"crypto\/subtle\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\ntype basicAuth struct {\n\th    http.Handler\n\topts AuthOptions\n}\n\n\/\/ AuthOptions stores the configuration for HTTP Basic Authentication.\n\/\/\n\/\/ A http.Handler may also be passed to UnauthorizedHandler to override the\n\/\/ default error handler if you wish to serve a custom template\/response.\ntype AuthOptions struct {\n\tRealm               string\n\tUser                string\n\tPassword            string\n\tAuthFunc            func(string, string, *http.Request) bool\n\tUnauthorizedHandler http.Handler\n}\n\n\/\/ Satisfies the http.Handler interface for basicAuth.\nfunc (b basicAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Check if we have a user-provided error handler, else set a default\n\tif b.opts.UnauthorizedHandler == nil {\n\t\tb.opts.UnauthorizedHandler = http.HandlerFunc(defaultUnauthorizedHandler)\n\t}\n\n\t\/\/ Check that the provided details match\n\tif b.authenticate(r) == false {\n\t\tb.requestAuth(w, r)\n\t\treturn\n\t}\n\n\t\/\/ Call the next handler on success.\n\tb.h.ServeHTTP(w, r)\n}\n\n\/\/ authenticate retrieves and then validates the user:password combination provided in\n\/\/ the request header. Returns 'false' if the user has not successfully authenticated.\nfunc (b *basicAuth) authenticate(r *http.Request) bool {\n\tconst basicScheme string = \"Basic \"\n\n\tif r == nil {\n\t\treturn false\n\t}\n\n\t\/\/ In simple mode, prevent authentication with empty credentials if User is\n\t\/\/ not set. Allow empty passwords to support non-password use-cases.\n\tif b.opts.AuthFunc == nil && b.opts.User == \"\" {\n\t\treturn false\n\t}\n\n\t\/\/ Confirm the request is sending Basic Authentication credentials.\n\tauth := r.Header.Get(\"Authorization\")\n\tif !strings.HasPrefix(auth, basicScheme) {\n\t\treturn false\n\t}\n\n\t\/\/ Get the plain-text username and password from the request.\n\t\/\/ The first six characters are skipped - e.g. \"Basic \".\n\tstr, err := base64.StdEncoding.DecodeString(auth[len(basicScheme):])\n\tif err != nil {\n\t\treturn false\n\t}\n\n\t\/\/ Split on the first \":\" character only, with any subsequent colons assumed to be part\n\t\/\/ of the password. Note that the RFC2617 standard does not place any limitations on\n\t\/\/ allowable characters in the password.\n\tcreds := bytes.SplitN(str, []byte(\":\"), 2)\n\n\tif len(creds) != 2 {\n\t\treturn false\n\t}\n\n\tgivenUser := string(creds[0])\n\tgivenPass := string(creds[1])\n\n\t\/\/ Default to Simple mode if no AuthFunc is defined.\n\tif b.opts.AuthFunc == nil {\n\t\tb.opts.AuthFunc = b.simpleBasicAuthFunc\n\t}\n\n\treturn b.opts.AuthFunc(givenUser, givenPass, r)\n}\n\n\/\/ simpleBasicAuthFunc authenticates the supplied username and password against\n\/\/ the User and Password set in the Options struct.\nfunc (b *basicAuth) simpleBasicAuthFunc(user, pass string, r *http.Request) bool {\n\t\/\/ Equalize lengths of supplied and required credentials\n\t\/\/ by hashing them\n\tgivenUser := sha256.Sum256([]byte(user))\n\tgivenPass := sha256.Sum256([]byte(pass))\n\trequiredUser := sha256.Sum256([]byte(b.opts.User))\n\trequiredPass := sha256.Sum256([]byte(b.opts.Password))\n\n\t\/\/ Compare the supplied credentials to those set in our options\n\tif subtle.ConstantTimeCompare(givenUser[:], requiredUser[:]) == 1 &&\n\t\tsubtle.ConstantTimeCompare(givenPass[:], requiredPass[:]) == 1 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ Require authentication, and serve our error handler otherwise.\nfunc (b *basicAuth) requestAuth(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"WWW-Authenticate\", fmt.Sprintf(`Basic realm=%q`, b.opts.Realm))\n\tb.opts.UnauthorizedHandler.ServeHTTP(w, r)\n}\n\n\/\/ defaultUnauthorizedHandler provides a default HTTP 401 Unauthorized response.\nfunc defaultUnauthorizedHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)\n}\n\n\/\/ BasicAuth provides HTTP middleware for protecting URIs with HTTP Basic Authentication\n\/\/ as per RFC 2617. The server authenticates a user:password combination provided in the\n\/\/ \"Authorization\" HTTP header.\n\/\/\n\/\/ Example:\n\/\/\n\/\/     package main\n\/\/\n\/\/     import(\n\/\/            \"net\/http\"\n\/\/            \"github.com\/zenazn\/goji\"\n\/\/            \"github.com\/goji\/httpauth\"\n\/\/     )\n\/\/\n\/\/     func main() {\n\/\/          basicOpts := httpauth.AuthOptions{\n\/\/                      Realm: \"Restricted\",\n\/\/                      User: \"Dave\",\n\/\/                      Password: \"ClearText\",\n\/\/                  }\n\/\/\n\/\/          goji.Use(httpauth.BasicAuth(basicOpts), SomeOtherMiddleware)\n\/\/          goji.Get(\"\/thing\", myHandler)\n\/\/  }\n\/\/\n\/\/ Note: HTTP Basic Authentication credentials are sent in plain text, and therefore it does\n\/\/ not make for a wholly secure authentication mechanism. You should serve your content over\n\/\/ HTTPS to mitigate this, noting that \"Basic Authentication\" is meant to be just that: basic!\nfunc BasicAuth(o AuthOptions) func(http.Handler) http.Handler {\n\tfn := func(h http.Handler) http.Handler {\n\t\treturn basicAuth{h, o}\n\t}\n\treturn fn\n}\n\n\/\/ SimpleBasicAuth is a convenience wrapper around BasicAuth. It takes a user and password, and\n\/\/ returns a pre-configured BasicAuth handler using the \"Restricted\" realm and a default 401 handler.\n\/\/\n\/\/ Example:\n\/\/\n\/\/     package main\n\/\/\n\/\/     import(\n\/\/            \"net\/http\"\n\/\/            \"github.com\/zenazn\/goji\/web\/httpauth\"\n\/\/     )\n\/\/\n\/\/     func main() {\n\/\/\n\/\/          goji.Use(httpauth.SimpleBasicAuth(\"dave\", \"somepassword\"), SomeOtherMiddleware)\n\/\/          goji.Get(\"\/thing\", myHandler)\n\/\/      }\n\/\/\nfunc SimpleBasicAuth(user, password string) func(http.Handler) http.Handler {\n\topts := AuthOptions{\n\t\tRealm:    \"Restricted\",\n\t\tUser:     user,\n\t\tPassword: password,\n\t}\n\treturn BasicAuth(opts)\n}\n<|endoftext|>"}
{"text":"<commit_before>package beanWork\n\nimport (\n\t\"github.com\/kr\/beanstalk\"\n\t\"sync\"\n)\n\ntype(\n\t\/\/ callback function\n\tJobHandler func(*BeanJob)\n\n\t\/\/\n\tBeanWorker struct {\n\t\tNet     string\n\t\tAddress string\n\t}\n\n)\n\n\n\/\/ create number of worker as go routines\nfunc (bw *BeanWorker)Worker(tube string, numberOfWorkers int, fn JobHandler) {\n\tfor i := 0; i < numberOfWorkers; i++ {\n\t\tgo bw.work(tube, fn)\n\t}\n}\n\n\/\/ create new beanstalk connection and return it\n\/\/ panic if got an connection error\nfunc (bw *BeanWorker)getNewConnection() *beanstalk.Conn {\n\tc, err := beanstalk.Dial(bw.Net, bw.Address)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn c\n}\n\n\/\/ create all resource required running an active tube connection\n\/\/ each worker gets its own connection to prevent race conditions\nfunc (bw *BeanWorker)work(tube string, fn JobHandler) {\n\tbeanTube := beanTube{\n\t\ttubeName:tube,\n\t\tconn:bw.getNewConnection(),\n\t\twg:sync.WaitGroup{},\n\t}\n\tbeanTube.tubeSet = beanTube.getTubeSet()\n\tbeanTube.reserveTubeJobs(fn)\n}\n\n\/\/ run waits for incoming chan messages\nfunc (bw *BeanWorker)Run() {\n\tfor {\n\t\tselect {\n\t\t}\n\t}\n}<commit_msg>defer close connection<commit_after>package beanWork\n\nimport (\n\t\"github.com\/kr\/beanstalk\"\n\t\"sync\"\n)\n\ntype(\n\t\/\/ callback function\n\tJobHandler func(*BeanJob)\n\n\t\/\/\n\tBeanWorker struct {\n\t\tNet     string\n\t\tAddress string\n\t}\n\n)\n\n\n\/\/ create number of worker as go routines\nfunc (bw *BeanWorker)Worker(tube string, numberOfWorkers int, fn JobHandler) {\n\tfor i := 0; i < numberOfWorkers; i++ {\n\t\tgo bw.work(tube, fn)\n\t}\n}\n\n\/\/ create new beanstalk connection and return it\n\/\/ panic if got an connection error\nfunc (bw *BeanWorker)getNewConnection() *beanstalk.Conn {\n\tc, err := beanstalk.Dial(bw.Net, bw.Address)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn c\n}\n\n\/\/ create all resource required running an active tube connection\n\/\/ each worker gets its own connection to prevent race conditions\nfunc (bw *BeanWorker)work(tube string, fn JobHandler) {\n\tbeanTube := beanTube{\n\t\ttubeName:tube,\n\t\tconn:bw.getNewConnection(),\n\t\twg:sync.WaitGroup{},\n\t}\n\tdefer beanTube.conn.Close()\n\tbeanTube.tubeSet = beanTube.getTubeSet()\n\tbeanTube.reserveTubeJobs(fn)\n}\n\n\/\/ run waits for incoming chan messages\nfunc (bw *BeanWorker)Run() {\n\tfor {\n\t\tselect {\n\t\t}\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 by caixw, All rights reserved.\n\/\/ Use of this source code is governed by a MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage orm_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/issue9\/assert\"\n\t\"github.com\/issue9\/orm\/v2\/sqlbuilder\"\n)\n\n\n\n\/\/ mysql: BenchmarkDB_Insert-4     \t    5000\t    280546 ns\/op\nfunc BenchmarkDB_Insert(b *testing.B) {\n\ta := assert.New(b)\n\n\tm := &Group{\n\t\tName:    \"name\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tdb := newDB(a)\n\tdefer func() {\n\t\tdb.Drop(&Group{})\n\t\tcloseDB(a)\n\t}()\n\n\ta.NotError(db.Create(&Group{}))\n\n\tfor i := 0; i < b.N; i++ {\n\t\ta.NotError(db.Insert(m))\n\t}\n}\n\n\/\/ mysql: BenchmarkDB_Update-4     \t    5000\t    369461 ns\/op\nfunc BenchmarkDB_Update(b *testing.B) {\n\ta := assert.New(b)\n\n\tm := &Group{\n\t\tName:    \"name\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tdb := newDB(a)\n\tdefer func() {\n\t\tdb.Drop(&Group{})\n\t\tcloseDB(a)\n\t}()\n\n\t\/\/ 构造数据\n\ta.NotError(db.Create(&Group{}))\n\ta.NotError(db.Insert(m))\n\n\tm.ID = 1 \/\/ 自增，从 1 开始\n\tfor i := 0; i < b.N; i++ {\n\t\ta.NotError(db.Update(m))\n\t}\n}\n\n\/\/ mysql: BenchmarkDB_Select-4     \t   10000\t    218232 ns\/op\nfunc BenchmarkDB_Select(b *testing.B) {\n\ta := assert.New(b)\n\n\tm := &Group{\n\t\tName:    \"name\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tdb := newDB(a)\n\tdefer func() {\n\t\tdb.Drop(&Group{})\n\t\tcloseDB(a)\n\t}()\n\n\ta.NotError(db.Create(&Group{}))\n\ta.NotError(db.Insert(m))\n\n\tm.ID = 1\n\tfor i := 0; i < b.N; i++ {\n\t\ta.NotError(db.Select(m))\n\t}\n}\n\n\/\/ mysql: BenchmarkDB_WhereUpdate-4\t   10000\t    163209 ns\/op\nfunc BenchmarkDB_WhereUpdate(b *testing.B) {\n\ta := assert.New(b)\n\n\tm := &Group{\n\t\tName:    \"name\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tdb := newDB(a)\n\tdefer func() {\n\t\tdb.Drop(&Group{})\n\t\tcloseDB(a)\n\t}()\n\n\t\/\/ 构造数据\n\ta.NotError(db.Create(&Group{}))\n\ta.NotError(db.Insert(m))\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, err := sqlbuilder.\n\t\t\tUpdate(db).Table(\"{#groups}\").\n\t\t\tSet(\"name\", \"n1\").\n\t\t\tIncrease(\"created\", 1).\n\t\t\tWhere(\"{id}=?\", i+1).\n\t\t\tExec()\n\t\ta.NotError(err)\n\t}\n}\n\n\/\/ mysql: BenchmarkDB_Count-4      \t   10000\t    186920 ns\/op\nfunc BenchmarkDB_Count(b *testing.B) {\n\ta := assert.New(b)\n\n\tm := &Group{\n\t\tName:    \"name\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tdb := newDB(a)\n\tdefer func() {\n\t\tdb.Drop(&Group{})\n\t\tcloseDB(a)\n\t}()\n\n\t\/\/ 构造数据\n\ta.NotError(db.Create(&Group{}))\n\ta.NotError(db.Insert(m))\n\n\tbe := &Group{Name: \"name\"}\n\tfor i := 0; i < b.N; i++ {\n\t\tcount, _ := db.Count(be)\n\t\tif count < 1 {\n\t\t\tb.Error(\"count:\", count)\n\t\t}\n\t}\n}\n<commit_msg>gofmt<commit_after>\/\/ Copyright 2015 by caixw, All rights reserved.\n\/\/ Use of this source code is governed by a MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage orm_test\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/issue9\/assert\"\n\t\"github.com\/issue9\/orm\/v2\/sqlbuilder\"\n)\n\n\/\/ mysql: BenchmarkDB_Insert-4     \t    5000\t    280546 ns\/op\nfunc BenchmarkDB_Insert(b *testing.B) {\n\ta := assert.New(b)\n\n\tm := &Group{\n\t\tName:    \"name\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tdb := newDB(a)\n\tdefer func() {\n\t\tdb.Drop(&Group{})\n\t\tcloseDB(a)\n\t}()\n\n\ta.NotError(db.Create(&Group{}))\n\n\tfor i := 0; i < b.N; i++ {\n\t\ta.NotError(db.Insert(m))\n\t}\n}\n\n\/\/ mysql: BenchmarkDB_Update-4     \t    5000\t    369461 ns\/op\nfunc BenchmarkDB_Update(b *testing.B) {\n\ta := assert.New(b)\n\n\tm := &Group{\n\t\tName:    \"name\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tdb := newDB(a)\n\tdefer func() {\n\t\tdb.Drop(&Group{})\n\t\tcloseDB(a)\n\t}()\n\n\t\/\/ 构造数据\n\ta.NotError(db.Create(&Group{}))\n\ta.NotError(db.Insert(m))\n\n\tm.ID = 1 \/\/ 自增，从 1 开始\n\tfor i := 0; i < b.N; i++ {\n\t\ta.NotError(db.Update(m))\n\t}\n}\n\n\/\/ mysql: BenchmarkDB_Select-4     \t   10000\t    218232 ns\/op\nfunc BenchmarkDB_Select(b *testing.B) {\n\ta := assert.New(b)\n\n\tm := &Group{\n\t\tName:    \"name\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tdb := newDB(a)\n\tdefer func() {\n\t\tdb.Drop(&Group{})\n\t\tcloseDB(a)\n\t}()\n\n\ta.NotError(db.Create(&Group{}))\n\ta.NotError(db.Insert(m))\n\n\tm.ID = 1\n\tfor i := 0; i < b.N; i++ {\n\t\ta.NotError(db.Select(m))\n\t}\n}\n\n\/\/ mysql: BenchmarkDB_WhereUpdate-4\t   10000\t    163209 ns\/op\nfunc BenchmarkDB_WhereUpdate(b *testing.B) {\n\ta := assert.New(b)\n\n\tm := &Group{\n\t\tName:    \"name\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tdb := newDB(a)\n\tdefer func() {\n\t\tdb.Drop(&Group{})\n\t\tcloseDB(a)\n\t}()\n\n\t\/\/ 构造数据\n\ta.NotError(db.Create(&Group{}))\n\ta.NotError(db.Insert(m))\n\n\tfor i := 0; i < b.N; i++ {\n\t\t_, err := sqlbuilder.\n\t\t\tUpdate(db).Table(\"{#groups}\").\n\t\t\tSet(\"name\", \"n1\").\n\t\t\tIncrease(\"created\", 1).\n\t\t\tWhere(\"{id}=?\", i+1).\n\t\t\tExec()\n\t\ta.NotError(err)\n\t}\n}\n\n\/\/ mysql: BenchmarkDB_Count-4      \t   10000\t    186920 ns\/op\nfunc BenchmarkDB_Count(b *testing.B) {\n\ta := assert.New(b)\n\n\tm := &Group{\n\t\tName:    \"name\",\n\t\tCreated: time.Now().Unix(),\n\t}\n\n\tdb := newDB(a)\n\tdefer func() {\n\t\tdb.Drop(&Group{})\n\t\tcloseDB(a)\n\t}()\n\n\t\/\/ 构造数据\n\ta.NotError(db.Create(&Group{}))\n\ta.NotError(db.Insert(m))\n\n\tbe := &Group{Name: \"name\"}\n\tfor i := 0; i < b.N; i++ {\n\t\tcount, _ := db.Count(be)\n\t\tif count < 1 {\n\t\t\tb.Error(\"count:\", count)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 tsuru authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"github.com\/globocom\/commandmocker\"\n\t\"github.com\/globocom\/tsuru\/app\"\n\t\"github.com\/globocom\/tsuru\/db\"\n\t\"io\/ioutil\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\t. \"launchpad.net\/gocheck\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\nfunc getOutput() *output {\n\treturn &output{\n\t\tServices: map[string]Service{\n\t\t\t\"umaappqq\": {\n\t\t\t\tUnits: map[string]app.Unit{\n\t\t\t\t\t\"umaappqq\/0\": {\n\t\t\t\t\t\tAgentState: \"started\",\n\t\t\t\t\t\tMachine:    1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tMachines: map[int]interface{}{\n\t\t\t0: map[interface{}]interface{}{\n\t\t\t\t\"dns-name\":       \"192.168.0.10\",\n\t\t\t\t\"instance-id\":    \"i-00000zz6\",\n\t\t\t\t\"instance-state\": \"running\",\n\t\t\t\t\"agent-state\":    \"running\",\n\t\t\t},\n\t\t\t1: map[interface{}]interface{}{\n\t\t\t\t\"dns-name\":       \"192.168.0.11\",\n\t\t\t\t\"instance-id\":    \"i-00000zz7\",\n\t\t\t\t\"instance-state\": \"running\",\n\t\t\t\t\"agent-state\":    \"running\",\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc getApp(c *C) *app.App {\n\ta := &app.App{Name: \"umaappqq\", State: \"STOPPED\"}\n\terr := db.Session.Apps().Insert(&a)\n\tc.Assert(err, IsNil)\n\treturn a\n}\n\nfunc (s *S) TestUpdate(c *C) {\n\ta := getApp(c)\n\tdefer db.Session.Apps().Remove(bson.M{\"name\": a.Name})\n\tout := getOutput()\n\tupdate(out)\n\terr := a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(a.State, Equals, \"started\")\n\tc.Assert(a.Units[0].Ip, Equals, \"192.168.0.11\")\n\tc.Assert(a.Units[0].Machine, Equals, 1)\n\tc.Assert(a.Units[0].InstanceState, Equals, \"running\")\n\tc.Assert(a.Units[0].MachineAgentState, Equals, \"running\")\n\tc.Assert(a.Units[0].AgentState, Equals, \"started\")\n\tc.Assert(a.Units[0].InstanceId, Equals, \"i-00000zz7\")\n}\n\nfunc (s *S) TestUpdateWithMultipleUnits(c *C) {\n\ta := getApp(c)\n\tout := getOutput()\n\tu := app.Unit{AgentState: \"started\", Machine: 2}\n\tout.Services[\"umaappqq\"].Units[\"umaappqq\/1\"] = u\n\tout.Machines[2] = map[interface{}]interface{}{\n\t\t\"dns-name\":       \"192.168.0.12\",\n\t\t\"instance-id\":    \"i-00000zz8\",\n\t\t\"instance-state\": \"running\",\n\t\t\"agent-state\":    \"running\",\n\t}\n\tupdate(out)\n\terr := a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(len(a.Units), Equals, 2)\n\tfor _, u = range a.Units {\n\t\tif u.Machine == 2 {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.Assert(u.Ip, Equals, \"192.168.0.12\")\n\tc.Assert(u.InstanceState, Equals, \"running\")\n\tc.Assert(u.AgentState, Equals, \"started\")\n\tc.Assert(u.MachineAgentState, Equals, \"running\")\n}\n\nfunc (s *S) TestUpdateWithDownMachine(c *C) {\n\ta := app.App{Name: \"barduscoapp\", State: \"STOPPED\"}\n\terr := db.Session.Apps().Insert(&a)\n\tc.Assert(err, IsNil)\n\tjujuOutput, err := ioutil.ReadFile(filepath.Join(\"testdata\", \"broken-output.yaml\"))\n\tc.Assert(err, IsNil)\n\tout := parse(jujuOutput)\n\tupdate(out)\n\terr = a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(a.State, Equals, \"creating\")\n}\n\nfunc (s *S) TestUpdateTwice(c *C) {\n\ta := getApp(c)\n\tdefer db.Session.Apps().Remove(bson.M{\"name\": a.Name})\n\tout := getOutput()\n\tupdate(out)\n\terr := a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(a.State, Equals, \"started\")\n\tc.Assert(a.Units[0].Ip, Equals, \"192.168.0.11\")\n\tc.Assert(a.Units[0].Machine, Equals, 1)\n\tc.Assert(a.Units[0].InstanceState, Equals, \"running\")\n\tc.Assert(a.Units[0].MachineAgentState, Equals, \"running\")\n\tc.Assert(a.Units[0].AgentState, Equals, \"started\")\n\tupdate(out)\n\terr = a.Get()\n\tc.Assert(len(a.Units), Equals, 1)\n}\n\nfunc (s *S) TestUpdateWithMultipleApps(c *C) {\n\tappDicts := []map[string]string{\n\t\t{\n\t\t\t\"name\": \"andrewzito3\",\n\t\t\t\"ip\":   \"10.10.10.163\",\n\t\t},\n\t\t{\n\t\t\t\"name\": \"flaviapp\",\n\t\t\t\"ip\":   \"10.10.10.208\",\n\t\t},\n\t\t{\n\t\t\t\"name\": \"mysqlapi\",\n\t\t\t\"ip\":   \"10.10.10.131\",\n\t\t},\n\t\t{\n\t\t\t\"name\": \"teste_api_semantica\",\n\t\t\t\"ip\":   \"10.10.10.189\",\n\t\t},\n\t\t{\n\t\t\t\"name\": \"xikin\",\n\t\t\t\"ip\":   \"10.10.10.168\",\n\t\t},\n\t}\n\tapps := make([]app.App, len(appDicts))\n\tfor i, appDict := range appDicts {\n\t\ta := app.App{Name: appDict[\"name\"]}\n\t\terr := db.Session.Apps().Insert(&a)\n\t\tc.Assert(err, IsNil)\n\t\tapps[i] = a\n\t}\n\tjujuOutput, err := ioutil.ReadFile(filepath.Join(\"testdata\", \"multiple-apps.yaml\"))\n\tc.Assert(err, IsNil)\n\tdata := parse(jujuOutput)\n\tupdate(data)\n\tfor _, appDict := range appDicts {\n\t\ta := app.App{Name: appDict[\"name\"]}\n\t\terr := a.Get()\n\t\tc.Assert(err, IsNil)\n\t\tc.Assert(a.Units[0].Ip, Equals, appDict[\"ip\"])\n\t}\n}\n\nfunc (s *S) TestParser(c *C) {\n\tjujuOutput, err := ioutil.ReadFile(filepath.Join(\"testdata\", \"output.yaml\"))\n\tc.Assert(err, IsNil)\n\texpected := getOutput()\n\tc.Assert(parse(jujuOutput), DeepEquals, expected)\n}\n\nfunc (s *S) TestExecWithTimeout(c *C) {\n\tvar data = []struct {\n\t\tcmd     []string\n\t\ttimeout time.Duration\n\t\tout     string\n\t\terr     error\n\t}{\n\t\t{\n\t\t\tcmd:     []string{\"sleep\", \"2\"},\n\t\t\ttimeout: 1e6,\n\t\t\tout:     \"\",\n\t\t\terr:     errors.New(`\"sleep 2\" ran for more than 1ms.`),\n\t\t},\n\t\t{\n\t\t\tcmd:     []string{\"python\", \"-c\", \"import time; time.sleep(1); print 'hello world!'\"},\n\t\t\ttimeout: 2e9,\n\t\t\tout:     \"hello world!\\n\",\n\t\t\terr:     nil,\n\t\t},\n\t}\n\tfor _, d := range data {\n\t\tout, err := execWithTimeout(d.timeout, d.cmd[0], d.cmd[1:]...)\n\t\tif string(out) != d.out {\n\t\t\tc.Errorf(\"Output. Want %q. Got %q.\", d.out, out)\n\t\t}\n\t\tif d.err == nil && err != nil {\n\t\t\tc.Errorf(\"Error. Want %v. Got %v.\", d.err, err)\n\t\t} else if d.err != nil && err.Error() != d.err.Error() {\n\t\t\tc.Errorf(\"Error message. Want %q. Got %q.\", d.err.Error(), err.Error())\n\t\t}\n\t}\n}\n\nfunc (s *S) TestCollect(c *C) {\n\ttmpdir, err := commandmocker.Add(\"juju\", \"$*\")\n\tc.Assert(err, IsNil)\n\tdefer commandmocker.Remove(tmpdir)\n\tout, err := collect()\n\tc.Assert(err, IsNil)\n\tc.Assert(string(out), Equals, \"status\")\n}\n<commit_msg>collector: raise timeout on test<commit_after>\/\/ Copyright 2012 tsuru authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"github.com\/globocom\/commandmocker\"\n\t\"github.com\/globocom\/tsuru\/app\"\n\t\"github.com\/globocom\/tsuru\/db\"\n\t\"io\/ioutil\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\t. \"launchpad.net\/gocheck\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\nfunc getOutput() *output {\n\treturn &output{\n\t\tServices: map[string]Service{\n\t\t\t\"umaappqq\": {\n\t\t\t\tUnits: map[string]app.Unit{\n\t\t\t\t\t\"umaappqq\/0\": {\n\t\t\t\t\t\tAgentState: \"started\",\n\t\t\t\t\t\tMachine:    1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tMachines: map[int]interface{}{\n\t\t\t0: map[interface{}]interface{}{\n\t\t\t\t\"dns-name\":       \"192.168.0.10\",\n\t\t\t\t\"instance-id\":    \"i-00000zz6\",\n\t\t\t\t\"instance-state\": \"running\",\n\t\t\t\t\"agent-state\":    \"running\",\n\t\t\t},\n\t\t\t1: map[interface{}]interface{}{\n\t\t\t\t\"dns-name\":       \"192.168.0.11\",\n\t\t\t\t\"instance-id\":    \"i-00000zz7\",\n\t\t\t\t\"instance-state\": \"running\",\n\t\t\t\t\"agent-state\":    \"running\",\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc getApp(c *C) *app.App {\n\ta := &app.App{Name: \"umaappqq\", State: \"STOPPED\"}\n\terr := db.Session.Apps().Insert(&a)\n\tc.Assert(err, IsNil)\n\treturn a\n}\n\nfunc (s *S) TestUpdate(c *C) {\n\ta := getApp(c)\n\tdefer db.Session.Apps().Remove(bson.M{\"name\": a.Name})\n\tout := getOutput()\n\tupdate(out)\n\terr := a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(a.State, Equals, \"started\")\n\tc.Assert(a.Units[0].Ip, Equals, \"192.168.0.11\")\n\tc.Assert(a.Units[0].Machine, Equals, 1)\n\tc.Assert(a.Units[0].InstanceState, Equals, \"running\")\n\tc.Assert(a.Units[0].MachineAgentState, Equals, \"running\")\n\tc.Assert(a.Units[0].AgentState, Equals, \"started\")\n\tc.Assert(a.Units[0].InstanceId, Equals, \"i-00000zz7\")\n}\n\nfunc (s *S) TestUpdateWithMultipleUnits(c *C) {\n\ta := getApp(c)\n\tout := getOutput()\n\tu := app.Unit{AgentState: \"started\", Machine: 2}\n\tout.Services[\"umaappqq\"].Units[\"umaappqq\/1\"] = u\n\tout.Machines[2] = map[interface{}]interface{}{\n\t\t\"dns-name\":       \"192.168.0.12\",\n\t\t\"instance-id\":    \"i-00000zz8\",\n\t\t\"instance-state\": \"running\",\n\t\t\"agent-state\":    \"running\",\n\t}\n\tupdate(out)\n\terr := a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(len(a.Units), Equals, 2)\n\tfor _, u = range a.Units {\n\t\tif u.Machine == 2 {\n\t\t\tbreak\n\t\t}\n\t}\n\tc.Assert(u.Ip, Equals, \"192.168.0.12\")\n\tc.Assert(u.InstanceState, Equals, \"running\")\n\tc.Assert(u.AgentState, Equals, \"started\")\n\tc.Assert(u.MachineAgentState, Equals, \"running\")\n}\n\nfunc (s *S) TestUpdateWithDownMachine(c *C) {\n\ta := app.App{Name: \"barduscoapp\", State: \"STOPPED\"}\n\terr := db.Session.Apps().Insert(&a)\n\tc.Assert(err, IsNil)\n\tjujuOutput, err := ioutil.ReadFile(filepath.Join(\"testdata\", \"broken-output.yaml\"))\n\tc.Assert(err, IsNil)\n\tout := parse(jujuOutput)\n\tupdate(out)\n\terr = a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(a.State, Equals, \"creating\")\n}\n\nfunc (s *S) TestUpdateTwice(c *C) {\n\ta := getApp(c)\n\tdefer db.Session.Apps().Remove(bson.M{\"name\": a.Name})\n\tout := getOutput()\n\tupdate(out)\n\terr := a.Get()\n\tc.Assert(err, IsNil)\n\tc.Assert(a.State, Equals, \"started\")\n\tc.Assert(a.Units[0].Ip, Equals, \"192.168.0.11\")\n\tc.Assert(a.Units[0].Machine, Equals, 1)\n\tc.Assert(a.Units[0].InstanceState, Equals, \"running\")\n\tc.Assert(a.Units[0].MachineAgentState, Equals, \"running\")\n\tc.Assert(a.Units[0].AgentState, Equals, \"started\")\n\tupdate(out)\n\terr = a.Get()\n\tc.Assert(len(a.Units), Equals, 1)\n}\n\nfunc (s *S) TestUpdateWithMultipleApps(c *C) {\n\tappDicts := []map[string]string{\n\t\t{\n\t\t\t\"name\": \"andrewzito3\",\n\t\t\t\"ip\":   \"10.10.10.163\",\n\t\t},\n\t\t{\n\t\t\t\"name\": \"flaviapp\",\n\t\t\t\"ip\":   \"10.10.10.208\",\n\t\t},\n\t\t{\n\t\t\t\"name\": \"mysqlapi\",\n\t\t\t\"ip\":   \"10.10.10.131\",\n\t\t},\n\t\t{\n\t\t\t\"name\": \"teste_api_semantica\",\n\t\t\t\"ip\":   \"10.10.10.189\",\n\t\t},\n\t\t{\n\t\t\t\"name\": \"xikin\",\n\t\t\t\"ip\":   \"10.10.10.168\",\n\t\t},\n\t}\n\tapps := make([]app.App, len(appDicts))\n\tfor i, appDict := range appDicts {\n\t\ta := app.App{Name: appDict[\"name\"]}\n\t\terr := db.Session.Apps().Insert(&a)\n\t\tc.Assert(err, IsNil)\n\t\tapps[i] = a\n\t}\n\tjujuOutput, err := ioutil.ReadFile(filepath.Join(\"testdata\", \"multiple-apps.yaml\"))\n\tc.Assert(err, IsNil)\n\tdata := parse(jujuOutput)\n\tupdate(data)\n\tfor _, appDict := range appDicts {\n\t\ta := app.App{Name: appDict[\"name\"]}\n\t\terr := a.Get()\n\t\tc.Assert(err, IsNil)\n\t\tc.Assert(a.Units[0].Ip, Equals, appDict[\"ip\"])\n\t}\n}\n\nfunc (s *S) TestParser(c *C) {\n\tjujuOutput, err := ioutil.ReadFile(filepath.Join(\"testdata\", \"output.yaml\"))\n\tc.Assert(err, IsNil)\n\texpected := getOutput()\n\tc.Assert(parse(jujuOutput), DeepEquals, expected)\n}\n\nfunc (s *S) TestExecWithTimeout(c *C) {\n\tvar data = []struct {\n\t\tcmd     []string\n\t\ttimeout time.Duration\n\t\tout     string\n\t\terr     error\n\t}{\n\t\t{\n\t\t\tcmd:     []string{\"sleep\", \"2\"},\n\t\t\ttimeout: 1e6,\n\t\t\tout:     \"\",\n\t\t\terr:     errors.New(`\"sleep 2\" ran for more than 1ms.`),\n\t\t},\n\t\t{\n\t\t\tcmd:     []string{\"python\", \"-c\", \"import time; time.sleep(1); print 'hello world!'\"},\n\t\t\ttimeout: 5e9,\n\t\t\tout:     \"hello world!\\n\",\n\t\t\terr:     nil,\n\t\t},\n\t}\n\tfor _, d := range data {\n\t\tout, err := execWithTimeout(d.timeout, d.cmd[0], d.cmd[1:]...)\n\t\tif string(out) != d.out {\n\t\t\tc.Errorf(\"Output. Want %q. Got %q.\", d.out, out)\n\t\t}\n\t\tif d.err == nil && err != nil {\n\t\t\tc.Errorf(\"Error. Want %v. Got %v.\", d.err, err)\n\t\t} else if d.err != nil && err.Error() != d.err.Error() {\n\t\t\tc.Errorf(\"Error message. Want %q. Got %q.\", d.err.Error(), err.Error())\n\t\t}\n\t}\n}\n\nfunc (s *S) TestCollect(c *C) {\n\ttmpdir, err := commandmocker.Add(\"juju\", \"$*\")\n\tc.Assert(err, IsNil)\n\tdefer commandmocker.Remove(tmpdir)\n\tout, err := collect()\n\tc.Assert(err, IsNil)\n\tc.Assert(string(out), Equals, \"status\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go9p Authors.  All rights reserved.\n\/\/ Copyright 2013 Adin Scannell.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the licenses\/go9p file.\npackage plan9\n\nimport (\n    \"log\"\n    \"sync\"\n    \"syscall\"\n)\n\ntype Fs struct {\n\n    \/\/ The read mappings.\n    Read map[string][]string `json:\"read\"`\n\n    \/\/ The write mappings.\n    Write map[string]string `json:\"write\"`\n\n    \/\/ are we speaking 9P2000.u?\n    Dotu bool `json:\"dotu\"`\n\n    \/\/ open FiDs.\n    Fidpool map[uint32]*Fid `json:\"fidpool\"`\n\n    \/\/ requests outstanding.\n    Reqs map[uint16]bool `json:\"reqs\"`\n\n    \/\/ Lock protecting the above.\n    fidLock sync.RWMutex\n    fidCond *sync.Cond\n\n    \/\/ Our open files.\n    files map[string]*File\n\n    \/\/ Lock protecting the above.\n    filesLock sync.RWMutex\n\n    \/\/ Our file map priority queue,\n    \/\/ used for closing unused file descriptors.\n    lru []*File\n\n    \/\/ Lock protecting the above.\n    lruLock sync.Mutex\n\n    \/\/ Our file root.\n    root *File\n\n    \/\/ Our next fileid.\n    Fileid uint64 `json:\"fileid\"`\n\n    \/\/ Our file descriptor limits.\n    Fdlimit uint `json:\"fdlimit\"`\n}\n\nfunc (fs *Fs) error(buf Buffer, tag uint16, err error) error {\n\n    \/\/ Was there an error?\n    \/\/ If so, encode it properly.\n    int_err, ok := err.(*Error)\n    if ok {\n        \/\/ We have a specific error code.\n        return PackRerror(buf, tag, int_err.Err, int_err.Errornum, fs.Dotu)\n    }\n\n    \/\/ This is a generic error.\n    return PackRerror(buf, tag, err.Error(), uint32(syscall.EIO), fs.Dotu)\n}\n\nfunc (fs *Fs) wait(tag uint16) {\n    fs.fidLock.RLock()\n    for fs.Reqs[tag] {\n        fs.fidCond.Wait()\n    }\n    fs.fidLock.RUnlock()\n}\n\nfunc (fs *Fs) clear(tag uint16) {\n    fs.fidLock.Lock()\n    delete(fs.Reqs, tag)\n    fs.fidCond.Broadcast()\n    fs.fidLock.Unlock()\n}\n\nfunc (fs *Fs) Handle(req Buffer, resp Buffer, debug bool) error {\n\n    var fid *Fid\n    var afid *Fid\n\n    \/\/ Unpack our message.\n    fcall, err := Unpack(req, fs.Dotu)\n    if err != nil {\n        log.Printf(\"9pfs serialization error?\")\n        err = fs.error(resp, NOTAG, err)\n        goto done\n    }\n\n    if debug {\n        log.Printf(\"req: Fcall -> %s\", fcall.String())\n    }\n\n    \/\/ Save our tag.\n    if fcall.Tag != NOTAG {\n        fs.fidLock.Lock()\n        _, ok := fs.Reqs[fcall.Tag]\n        if ok {\n            fs.fidLock.Unlock()\n            err = fs.error(resp, fcall.Tag, Einuse)\n            goto done\n        }\n        fs.Reqs[fcall.Tag] = true\n        defer fs.clear(fcall.Tag)\n        fs.fidLock.Unlock()\n    }\n\n    \/\/ Is there an fid here?\n    if fcall.Fid != NOFID &&\n        fcall.Type != Tattach &&\n        fcall.Type != Tauth &&\n        fcall.Type != Tversion {\n\n        fid = fs.GetFid(fcall.Fid)\n        if fid == nil {\n            err = fs.error(resp, fcall.Tag, Eunknownfid)\n            goto done\n        }\n        defer fid.DecRef(fs)\n    }\n    if fcall.Afid != NOFID &&\n        fcall.Type == Tattach {\n\n        afid = fs.GetFid(fcall.Afid)\n        if afid == nil {\n            err = fs.error(resp, fcall.Tag, Eunknownfid)\n            goto done\n        }\n        defer afid.DecRef(fs)\n    }\n\n    switch fcall.Type {\n    case Tversion:\n        var msize uint32\n        var dotu bool\n        var version string\n        msize, dotu, version, err = fs.version(fcall.Msize, fcall.Version)\n        if err == nil {\n            err = PackRversion(resp, fcall.Tag, msize, version)\n        }\n        if err == nil {\n            fs.versionPost(msize, dotu)\n        }\n\n    case Tauth:\n        var qid *Qid\n        qid, err = fs.auth(fcall.Afid, fcall.Uname, fcall.Aname, fcall.Unamenum)\n        if err == nil {\n            err = PackRauth(resp, fcall.Tag, qid)\n        }\n\n    case Tattach:\n        var qid *Qid\n        qid, err = fs.attach(fcall.Fid, afid, fcall.Uname, fcall.Aname, fcall.Unamenum)\n        if err == nil {\n            err = PackRattach(resp, fcall.Tag, qid)\n        }\n\n    case Tflush:\n        fs.wait(fcall.Oldtag)\n        err = PackRflush(resp, fcall.Tag)\n\n    case Twalk:\n        var wqids []Qid\n        wqids, err = fs.walk(fid, fcall.Newfid, fcall.Wname)\n        if err == nil {\n            err = PackRwalk(resp, fcall.Tag, wqids)\n        }\n\n    case Topen:\n        var qid *Qid\n        var iounit uint32\n        qid, iounit, err = fs.open(fid, fcall.Mode)\n        if err == nil {\n            err = PackRopen(resp, fcall.Tag, qid, iounit)\n        }\n        if err == nil {\n            fs.openPost(fid, fcall.Mode)\n        }\n\n    case Tcreate:\n        var file *File\n        var qid *Qid\n        var iounit uint32\n        file, qid, iounit, err = fs.create(fid, fcall.Name, fcall.Perm, fcall.Mode, fcall.Ext)\n        if err == nil {\n            err = PackRcreate(resp, fcall.Tag, qid, iounit)\n        }\n        if err == nil {\n            fs.createPost(fid, file, fcall.Name, fcall.Mode)\n        } else {\n            fs.createFail(fid, file, fcall.Name, fcall.Mode)\n        }\n\n    case Tread:\n        \/\/ NOTE: This is a somewhat ugly special case.\n        \/\/ Because of the way the interface is designed here,\n        \/\/ we have to specially check for directory reads.\n        if fid == nil {\n            err = Eunknownfid\n\n        } else if fid.file.Qid.Type&QTDIR != 0 {\n\n            var children []*Dir\n            var count int\n            var written int\n\n            children, err = fs.readDir(fid, int64(fcall.Offset), int(fcall.Count))\n            if err == nil {\n                \/\/ Pack with no count.\n                err = PackRread(resp, fcall.Tag, 0)\n            }\n            if err == nil {\n                \/\/ Pack the given entries.\n                for count < len(children) {\n                    if debug {\n                        log.Printf(\n                            \"fid %d child[%d] -> %s\",\n                            fcall.Fid,\n                            count,\n                            children[count].Name)\n                    }\n                    packed := pstat(resp, children[count], fs.Dotu)\n                    if resp.WriteLeft() >= 0 &&\n                        written+packed < int(fcall.Count) {\n                        count += 1\n                        written += packed\n                    } else {\n                        \/\/ This one didn't count.\n                        \/\/ We weren't able to fit the entire\n                        \/\/ directory encoded here, so do it next time.\n                        break\n                    }\n                }\n                \/\/ Repack with the appropriate count.\n                err = PackRread(resp, fcall.Tag, uint32(written))\n            }\n            if err == nil {\n                fs.readDirPost(fid, uint32(written), count)\n            }\n\n        } else {\n\n            var fd int\n            var length int\n\n            fd, err = fs.readFile(fid, int64(fcall.Offset), int(fcall.Count))\n            if err == nil {\n                \/\/ Pack with no count.\n                err = PackRread(resp, fcall.Tag, 0)\n            }\n            if err == nil {\n                \/\/ Perform the actual read.\n                length, err = resp.ReadFromFd(fd, int64(fcall.Offset), int(fcall.Count))\n                if err == nil {\n                    \/\/ Repack with the appropriate count.\n                    err = PackRread(resp, fcall.Tag, uint32(length))\n                }\n            }\n            if err == nil {\n                fs.readFilePost(fid, uint32(length))\n            } else {\n                fs.readFileFail(fid, uint32(length))\n            }\n        }\n\n    case Twrite:\n        \/\/ NOTE: Ugly as per above.\n        \/\/ No writes should happen on directories.\n\n        if fid == nil {\n            err = Eunknownfid\n\n        } else if fid.file.Qid.Type&QTDIR != 0 {\n            err = Ebaduse\n\n        } else {\n\n            var fd int\n            var length int\n\n            fd, err = fs.writeFile(fid, int64(fcall.Offset), int(fcall.Count))\n            if err == nil {\n                err = PackRwrite(resp, fcall.Tag, 0)\n            }\n            if err == nil {\n                \/\/ Perform the actual write.\n                length, err = req.WriteToFd(fd, int64(fcall.Offset), int(fcall.Count))\n                if err == nil {\n                    \/\/ Repack with the appropriate count.\n                    err = PackRwrite(resp, fcall.Tag, uint32(length))\n                }\n            }\n            if err == nil {\n                fs.writeFilePost(fid, uint32(length))\n            } else {\n                fs.writeFileFail(fid, uint32(length))\n            }\n        }\n\n    case Tclunk:\n        err = fs.clunk(fid)\n        if err == nil {\n            err = PackRclunk(resp, fcall.Tag)\n        }\n        if err == nil {\n            fs.clunkPost(fid)\n        }\n\n    case Tremove:\n        err = fs.remove(fid)\n        if err == nil {\n            err = PackRremove(resp, fcall.Tag)\n        }\n        if err == nil {\n            err = fs.removePost(fid)\n        }\n\n    case Tstat:\n        var dir *Dir\n        dir, err = fs.stat(fid)\n        if err == nil {\n            err = PackRstat(resp, fcall.Tag, dir, fs.Dotu)\n        }\n\n    case Twstat:\n        err = fs.wstat(fid, &fcall.Dir)\n        if err == nil {\n            err = PackRwstat(resp, fcall.Tag)\n        }\n\n    default:\n        err = InvalidMessage\n    }\n\n    if err != nil {\n        \/\/ An error? Re-encode.\n        err = fs.error(resp, fcall.Tag, err)\n        goto done\n    }\n\ndone:\n    if debug {\n        resp.ReadRewind()\n        rcall, err := Unpack(resp, fs.Dotu)\n        if err != nil {\n            log.Printf(\"9pfs response error? req: Fcall -> %s\", fcall.String())\n            return err\n        }\n\n        \/\/ Print our result.\n        log.Printf(\"resp: Fcall <- %s\", rcall.String())\n    }\n\n    if debug {\n        fs.fidLock.Lock()\n        fs.filesLock.Lock()\n        for fidno, fid := range fs.Fidpool {\n            log.Printf(\n                \"  fidno %x: %d refs (%s)\",\n                fidno, fid.Refs, fid.file)\n        }\n        for path, file := range fs.files {\n            log.Printf(\n                \"  file %x: %s => %d refs\",\n                file.Qid.Path, path, file.refs)\n        }\n        fs.fidLock.Unlock()\n        fs.filesLock.Unlock()\n    }\n\n    \/\/ All good.\n    return nil\n}\n\nfunc (fs *Fs) Init() error {\n    fs.Read = make(map[string][]string)\n    fs.Write = make(map[string]string)\n    fs.Dotu = true\n    fs.Fidpool = make(map[uint32]*Fid)\n    fs.Reqs = make(map[uint16]bool)\n    fs.fidCond = sync.NewCond(&fs.fidLock)\n    fs.files = make(map[string]*File)\n    fs.lru = make([]*File, 0, 0)\n\n    if fs.Fdlimit == 0 {\n        \/\/ Figure out our active limit (1\/2 open limit).\n        \/\/ We use 1\/2 because control connections, tap devices,\n        \/\/ disks, etc. all need file descriptors. Note that we\n        \/\/ also explicitly handle running out of file descriptors,\n        \/\/ but this gives us an open bound to leave room for the\n        \/\/ rest of the system (because pieces don't always handle\n        \/\/ an EMFILE or ENFILE appropriately).\n        var rlim syscall.Rlimit\n        err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlim)\n        if err != nil {\n            return err\n        }\n        fs.Fdlimit = uint(rlim.Cur) \/ 2\n    }\n\n    return nil\n}\n\nfunc (fs *Fs) Attach() error {\n\n    fs.fidLock.Lock()\n    defer fs.fidLock.Unlock()\n\n    \/\/ Load the root.\n    var err error\n    fs.root, err = fs.lookup(\"\/\")\n    if err != nil {\n        return err\n    }\n\n    \/\/ Restore all our Fids.\n    for _, fid := range fs.Fidpool {\n        fid.file, err = fs.lookup(fid.Path)\n        if err != nil {\n            return err\n        }\n    }\n\n    return nil\n}\n<commit_msg>Probe rlimit on attach(), not on init().<commit_after>\/\/ Copyright 2009 The Go9p Authors.  All rights reserved.\n\/\/ Copyright 2013 Adin Scannell.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the licenses\/go9p file.\npackage plan9\n\nimport (\n    \"log\"\n    \"sync\"\n    \"syscall\"\n)\n\ntype Fs struct {\n\n    \/\/ The read mappings.\n    Read map[string][]string `json:\"read\"`\n\n    \/\/ The write mappings.\n    Write map[string]string `json:\"write\"`\n\n    \/\/ are we speaking 9P2000.u?\n    Dotu bool `json:\"dotu\"`\n\n    \/\/ open FiDs.\n    Fidpool map[uint32]*Fid `json:\"fidpool\"`\n\n    \/\/ requests outstanding.\n    Reqs map[uint16]bool `json:\"reqs\"`\n\n    \/\/ Lock protecting the above.\n    fidLock sync.RWMutex\n    fidCond *sync.Cond\n\n    \/\/ Our open files.\n    files map[string]*File\n\n    \/\/ Lock protecting the above.\n    filesLock sync.RWMutex\n\n    \/\/ Our file map priority queue,\n    \/\/ used for closing unused file descriptors.\n    lru []*File\n\n    \/\/ Lock protecting the above.\n    lruLock sync.Mutex\n\n    \/\/ Our file root.\n    root *File\n\n    \/\/ Our next fileid.\n    Fileid uint64 `json:\"fileid\"`\n\n    \/\/ Our file descriptor limits.\n    Fdlimit uint `json:\"fdlimit\"`\n}\n\nfunc (fs *Fs) error(buf Buffer, tag uint16, err error) error {\n\n    \/\/ Was there an error?\n    \/\/ If so, encode it properly.\n    int_err, ok := err.(*Error)\n    if ok {\n        \/\/ We have a specific error code.\n        return PackRerror(buf, tag, int_err.Err, int_err.Errornum, fs.Dotu)\n    }\n\n    \/\/ This is a generic error.\n    return PackRerror(buf, tag, err.Error(), uint32(syscall.EIO), fs.Dotu)\n}\n\nfunc (fs *Fs) wait(tag uint16) {\n    fs.fidLock.RLock()\n    for fs.Reqs[tag] {\n        fs.fidCond.Wait()\n    }\n    fs.fidLock.RUnlock()\n}\n\nfunc (fs *Fs) clear(tag uint16) {\n    fs.fidLock.Lock()\n    delete(fs.Reqs, tag)\n    fs.fidCond.Broadcast()\n    fs.fidLock.Unlock()\n}\n\nfunc (fs *Fs) Handle(req Buffer, resp Buffer, debug bool) error {\n\n    var fid *Fid\n    var afid *Fid\n\n    \/\/ Unpack our message.\n    fcall, err := Unpack(req, fs.Dotu)\n    if err != nil {\n        log.Printf(\"9pfs serialization error?\")\n        err = fs.error(resp, NOTAG, err)\n        goto done\n    }\n\n    if debug {\n        log.Printf(\"req: Fcall -> %s\", fcall.String())\n    }\n\n    \/\/ Save our tag.\n    if fcall.Tag != NOTAG {\n        fs.fidLock.Lock()\n        _, ok := fs.Reqs[fcall.Tag]\n        if ok {\n            fs.fidLock.Unlock()\n            err = fs.error(resp, fcall.Tag, Einuse)\n            goto done\n        }\n        fs.Reqs[fcall.Tag] = true\n        defer fs.clear(fcall.Tag)\n        fs.fidLock.Unlock()\n    }\n\n    \/\/ Is there an fid here?\n    if fcall.Fid != NOFID &&\n        fcall.Type != Tattach &&\n        fcall.Type != Tauth &&\n        fcall.Type != Tversion {\n\n        fid = fs.GetFid(fcall.Fid)\n        if fid == nil {\n            err = fs.error(resp, fcall.Tag, Eunknownfid)\n            goto done\n        }\n        defer fid.DecRef(fs)\n    }\n    if fcall.Afid != NOFID &&\n        fcall.Type == Tattach {\n\n        afid = fs.GetFid(fcall.Afid)\n        if afid == nil {\n            err = fs.error(resp, fcall.Tag, Eunknownfid)\n            goto done\n        }\n        defer afid.DecRef(fs)\n    }\n\n    switch fcall.Type {\n    case Tversion:\n        var msize uint32\n        var dotu bool\n        var version string\n        msize, dotu, version, err = fs.version(fcall.Msize, fcall.Version)\n        if err == nil {\n            err = PackRversion(resp, fcall.Tag, msize, version)\n        }\n        if err == nil {\n            fs.versionPost(msize, dotu)\n        }\n\n    case Tauth:\n        var qid *Qid\n        qid, err = fs.auth(fcall.Afid, fcall.Uname, fcall.Aname, fcall.Unamenum)\n        if err == nil {\n            err = PackRauth(resp, fcall.Tag, qid)\n        }\n\n    case Tattach:\n        var qid *Qid\n        qid, err = fs.attach(fcall.Fid, afid, fcall.Uname, fcall.Aname, fcall.Unamenum)\n        if err == nil {\n            err = PackRattach(resp, fcall.Tag, qid)\n        }\n\n    case Tflush:\n        fs.wait(fcall.Oldtag)\n        err = PackRflush(resp, fcall.Tag)\n\n    case Twalk:\n        var wqids []Qid\n        wqids, err = fs.walk(fid, fcall.Newfid, fcall.Wname)\n        if err == nil {\n            err = PackRwalk(resp, fcall.Tag, wqids)\n        }\n\n    case Topen:\n        var qid *Qid\n        var iounit uint32\n        qid, iounit, err = fs.open(fid, fcall.Mode)\n        if err == nil {\n            err = PackRopen(resp, fcall.Tag, qid, iounit)\n        }\n        if err == nil {\n            fs.openPost(fid, fcall.Mode)\n        }\n\n    case Tcreate:\n        var file *File\n        var qid *Qid\n        var iounit uint32\n        file, qid, iounit, err = fs.create(fid, fcall.Name, fcall.Perm, fcall.Mode, fcall.Ext)\n        if err == nil {\n            err = PackRcreate(resp, fcall.Tag, qid, iounit)\n        }\n        if err == nil {\n            fs.createPost(fid, file, fcall.Name, fcall.Mode)\n        } else {\n            fs.createFail(fid, file, fcall.Name, fcall.Mode)\n        }\n\n    case Tread:\n        \/\/ NOTE: This is a somewhat ugly special case.\n        \/\/ Because of the way the interface is designed here,\n        \/\/ we have to specially check for directory reads.\n        if fid == nil {\n            err = Eunknownfid\n\n        } else if fid.file.Qid.Type&QTDIR != 0 {\n\n            var children []*Dir\n            var count int\n            var written int\n\n            children, err = fs.readDir(fid, int64(fcall.Offset), int(fcall.Count))\n            if err == nil {\n                \/\/ Pack with no count.\n                err = PackRread(resp, fcall.Tag, 0)\n            }\n            if err == nil {\n                \/\/ Pack the given entries.\n                for count < len(children) {\n                    if debug {\n                        log.Printf(\n                            \"fid %d child[%d] -> %s\",\n                            fcall.Fid,\n                            count,\n                            children[count].Name)\n                    }\n                    packed := pstat(resp, children[count], fs.Dotu)\n                    if resp.WriteLeft() >= 0 &&\n                        written+packed < int(fcall.Count) {\n                        count += 1\n                        written += packed\n                    } else {\n                        \/\/ This one didn't count.\n                        \/\/ We weren't able to fit the entire\n                        \/\/ directory encoded here, so do it next time.\n                        break\n                    }\n                }\n                \/\/ Repack with the appropriate count.\n                err = PackRread(resp, fcall.Tag, uint32(written))\n            }\n            if err == nil {\n                fs.readDirPost(fid, uint32(written), count)\n            }\n\n        } else {\n\n            var fd int\n            var length int\n\n            fd, err = fs.readFile(fid, int64(fcall.Offset), int(fcall.Count))\n            if err == nil {\n                \/\/ Pack with no count.\n                err = PackRread(resp, fcall.Tag, 0)\n            }\n            if err == nil {\n                \/\/ Perform the actual read.\n                length, err = resp.ReadFromFd(fd, int64(fcall.Offset), int(fcall.Count))\n                if err == nil {\n                    \/\/ Repack with the appropriate count.\n                    err = PackRread(resp, fcall.Tag, uint32(length))\n                }\n            }\n            if err == nil {\n                fs.readFilePost(fid, uint32(length))\n            } else {\n                fs.readFileFail(fid, uint32(length))\n            }\n        }\n\n    case Twrite:\n        \/\/ NOTE: Ugly as per above.\n        \/\/ No writes should happen on directories.\n\n        if fid == nil {\n            err = Eunknownfid\n\n        } else if fid.file.Qid.Type&QTDIR != 0 {\n            err = Ebaduse\n\n        } else {\n\n            var fd int\n            var length int\n\n            fd, err = fs.writeFile(fid, int64(fcall.Offset), int(fcall.Count))\n            if err == nil {\n                err = PackRwrite(resp, fcall.Tag, 0)\n            }\n            if err == nil {\n                \/\/ Perform the actual write.\n                length, err = req.WriteToFd(fd, int64(fcall.Offset), int(fcall.Count))\n                if err == nil {\n                    \/\/ Repack with the appropriate count.\n                    err = PackRwrite(resp, fcall.Tag, uint32(length))\n                }\n            }\n            if err == nil {\n                fs.writeFilePost(fid, uint32(length))\n            } else {\n                fs.writeFileFail(fid, uint32(length))\n            }\n        }\n\n    case Tclunk:\n        err = fs.clunk(fid)\n        if err == nil {\n            err = PackRclunk(resp, fcall.Tag)\n        }\n        if err == nil {\n            fs.clunkPost(fid)\n        }\n\n    case Tremove:\n        err = fs.remove(fid)\n        if err == nil {\n            err = PackRremove(resp, fcall.Tag)\n        }\n        if err == nil {\n            err = fs.removePost(fid)\n        }\n\n    case Tstat:\n        var dir *Dir\n        dir, err = fs.stat(fid)\n        if err == nil {\n            err = PackRstat(resp, fcall.Tag, dir, fs.Dotu)\n        }\n\n    case Twstat:\n        err = fs.wstat(fid, &fcall.Dir)\n        if err == nil {\n            err = PackRwstat(resp, fcall.Tag)\n        }\n\n    default:\n        err = InvalidMessage\n    }\n\n    if err != nil {\n        \/\/ An error? Re-encode.\n        err = fs.error(resp, fcall.Tag, err)\n        goto done\n    }\n\ndone:\n    if debug {\n        resp.ReadRewind()\n        rcall, err := Unpack(resp, fs.Dotu)\n        if err != nil {\n            log.Printf(\"9pfs response error? req: Fcall -> %s\", fcall.String())\n            return err\n        }\n\n        \/\/ Print our result.\n        log.Printf(\"resp: Fcall <- %s\", rcall.String())\n    }\n\n    if debug {\n        fs.fidLock.Lock()\n        fs.filesLock.Lock()\n        for fidno, fid := range fs.Fidpool {\n            log.Printf(\n                \"  fidno %x: %d refs (%s)\",\n                fidno, fid.Refs, fid.file)\n        }\n        for path, file := range fs.files {\n            log.Printf(\n                \"  file %x: %s => %d refs\",\n                file.Qid.Path, path, file.refs)\n        }\n        fs.fidLock.Unlock()\n        fs.filesLock.Unlock()\n    }\n\n    \/\/ All good.\n    return nil\n}\n\nfunc (fs *Fs) Init() error {\n    fs.Read = make(map[string][]string)\n    fs.Write = make(map[string]string)\n    fs.Dotu = true\n    fs.Fidpool = make(map[uint32]*Fid)\n    fs.Reqs = make(map[uint16]bool)\n    fs.fidCond = sync.NewCond(&fs.fidLock)\n    fs.files = make(map[string]*File)\n    fs.lru = make([]*File, 0, 0)\n\n    return nil\n}\n\nfunc (fs *Fs) Attach() error {\n\n    fs.fidLock.Lock()\n    defer fs.fidLock.Unlock()\n\n    \/\/ Load the root.\n    var err error\n    fs.root, err = fs.lookup(\"\/\")\n    if err != nil {\n        return err\n    }\n\n    \/\/ Restore all our Fids.\n    for _, fid := range fs.Fidpool {\n        fid.file, err = fs.lookup(fid.Path)\n        if err != nil {\n            return err\n        }\n    }\n\n    if fs.Fdlimit == 0 {\n        \/\/ Figure out our active limit (1\/2 open limit).\n        \/\/ We use 1\/2 because control connections, tap devices,\n        \/\/ disks, etc. all need file descriptors. Note that we\n        \/\/ also explicitly handle running out of file descriptors,\n        \/\/ but this gives us an open bound to leave room for the\n        \/\/ rest of the system (because pieces don't always handle\n        \/\/ an EMFILE or ENFILE appropriately).\n        var rlim syscall.Rlimit\n        err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlim)\n        if err != nil {\n            return err\n        }\n        fs.Fdlimit = uint(rlim.Cur) \/ 2\n    }\n\n    return nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package scheduler\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ Job defines a nomad job specification\ntype Job struct {\n\tRegion      string\n\tID          string\n\tName        string\n\tType        string\n\tPriority    int\n\tAllAtOnce   bool\n\tDatacenters []string\n\tConstraints []Constraint\n\tTaskGroups  []TaskGroup\n\tUpdate      Update\n}\n\n\/\/ Constraint defines a job\/task contraint\ntype Constraint struct {\n\tLTarget string\n\tRTarget string\n\tOperand string\n}\n\n\/\/ Update defines the update stanza\ntype Update struct {\n\tStagger     int64\n\tMaxParallel int\n}\n\n\/\/ TaskGroups defines the task_group stanza\ntype TaskGroup struct {\n\tName          string\n\tCount         int\n\tConstraints   []string\n\tTasks         []Task\n\tResources     Resources\n\tRestartPolicy RestartPolicy\n\tMeta          map[string]string\n}\n\n\/\/ Task defines a job task\ntype Task struct {\n\tName            string\n\tDriver          string\n\tConfig          Config\n\tEnv             map[string]string\n\tServices        []NomadService\n\tMeta            map[string]string\n\tLogConfig       LogConfig\n\tTemplates       []Template\n\tArtifacts       []Artifact\n\tResources       Resources\n\tDispatchPayload DispatchPayload\n}\n\n\/\/ DispatchPayload configures tast to have access to dispatch payload\ntype DispatchPayload struct {\n\tFile string\n}\n\n\/\/ Resources defines the resources to allocate to a task\ntype Resources struct {\n\tCPU      int\n\tMemoryMB int\n\tIOPS     int\n\tNetworks []Network\n}\n\n\/\/ Network defines network allocation\ntype Network struct {\n\tMBits        int\n\tDynamicPorts []DynamicPort\n}\n\n\/\/ RestartPolicy defines restart policy\ntype RestartPolicy struct {\n\tInterval int64\n\tAttempts int\n\tDelay    int64\n\tMode     string\n}\n\n\/\/ DynamicPort defines a dynamic port allocation\ntype DynamicPort struct {\n\tLabel string\n}\n\n\/\/ Artifact defines an artifact to be downloaded\ntype Artifact struct {\n\tGetterSource  string\n\tRelativeDest  string\n\tGetterOptions map[string]string\n}\n\n\/\/ Template defines template objects to render for the task\ntype Template struct {\n\tSourcePath   string\n\tDestPath     string\n\tEmbeddedTmpl string\n\tChangeMode   string\n\tChangeSignal string\n\tSplay        int64\n}\n\n\/\/ LogConfig defines log configurations\ntype LogConfig struct {\n\tMaxFiles      int\n\tMaxFileSizeMB int\n}\n\n\/\/ NomadService defines a service\ntype NomadService struct {\n\tName      string\n\tTags      []string\n\tPortLabel string\n\tChecks    []Check\n}\n\n\/\/ Check defines a service check\ntype Check struct {\n\tID       string `json:\"Id\"`\n\tName     string\n\tType     string\n\tPath     string\n\tPort     string\n\tTimeout  int64\n\tInterval int64\n\tProtocol string\n}\n\n\/\/ Config defines a driver\/task configuration\ntype Config struct {\n\tCommand string   `json:\"command\"`\n\tArgs    []string `json:\"args\"`\n}\n\n\/\/ NomadJob represents a nomad job\ntype NomadJob struct {\n\tJob *Job\n}\n\n\/\/ NewJob creates a new job with some default values.\nfunc NewJob(connectorVersion, id string, count int) *NomadJob {\n\treturn &NomadJob{\n\t\tJob: &Job{\n\t\t\tRegion:      \"\",\n\t\t\tID:          id,\n\t\t\tName:        id,\n\t\t\tType:        \"service\",\n\t\t\tPriority:    50,\n\t\t\tAllAtOnce:   false,\n\t\t\tDatacenters: []string{},\n\t\t\tConstraints: []Constraint{\n\t\t\t\tConstraint{\n\t\t\t\t\tLTarget: \"${attr.kernel.name}\",\n\t\t\t\t\tRTarget: \"linux\",\n\t\t\t\t\tOperand: \"=\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tTaskGroups: []TaskGroup{\n\t\t\t\tTaskGroup{\n\t\t\t\t\tName:  fmt.Sprintf(\"tskgrp-%s\", id),\n\t\t\t\t\tCount: count,\n\t\t\t\t\tTasks: []Task{\n\t\t\t\t\t\tTask{\n\t\t\t\t\t\t\tName:   fmt.Sprintf(\"task-%s\", id),\n\t\t\t\t\t\t\tDriver: \"raw_exec\",\n\t\t\t\t\t\t\tConfig: Config{\n\t\t\t\t\t\t\t\tCommand: \"bash\",\n\t\t\t\t\t\t\t\tArgs:    []string{\"runner.sh\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tEnv: map[string]string{\n\t\t\t\t\t\t\t\t\"CONNECTOR_VERSION\":   connectorVersion,\n\t\t\t\t\t\t\t\t\"COCOON_ID\":           id,\n\t\t\t\t\t\t\t\t\"CONTAINER_ID\":        id,\n\t\t\t\t\t\t\t\t\"COCOON_CODE_URL\":     \"\",\n\t\t\t\t\t\t\t\t\"COCOON_CODE_TAG\":     \"\",\n\t\t\t\t\t\t\t\t\"COCOON_CODE_LANG\":    \"\",\n\t\t\t\t\t\t\t\t\"COCOON_BUILD_PARAMS\": \"\",\n\t\t\t\t\t\t\t\t\"COCOON_DISK_LIMIT\":   \"\",\n\t\t\t\t\t\t\t\t\/\/ The name of the connector runner script and a link to the script.\n\t\t\t\t\t\t\t\t\/\/ The runner script will fetch and run whatever is found in this environment vars.\n\t\t\t\t\t\t\t\t\"RUN_SCRIPT_NAME\": \"run-connector.sh\",\n\t\t\t\t\t\t\t\t\"RUN_SCRIPT_URL\":  \"https:\/\/rawgit.com\/ncodes\/cocoon\/master\/scripts\/run-connector.sh\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tServices: []NomadService{\n\t\t\t\t\t\t\t\tNomadService{\n\t\t\t\t\t\t\t\t\tName:      fmt.Sprintf(\"cocoons-%s\", id),\n\t\t\t\t\t\t\t\t\tTags:      []string{id},\n\t\t\t\t\t\t\t\t\tPortLabel: \"CONNECTOR_RPC\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tMeta: map[string]string{},\n\t\t\t\t\t\t\tLogConfig: LogConfig{\n\t\t\t\t\t\t\t\tMaxFiles:      10,\n\t\t\t\t\t\t\t\tMaxFileSizeMB: 10,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tTemplates: []Template{},\n\t\t\t\t\t\t\tArtifacts: []Artifact{\n\t\t\t\t\t\t\t\tArtifact{\n\t\t\t\t\t\t\t\t\tGetterSource: \"https:\/\/rawgit.com\/ncodes\/cocoon\/master\/scripts\/runner.sh\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tResources: Resources{\n\t\t\t\t\t\t\t\tCPU:      0,\n\t\t\t\t\t\t\t\tMemoryMB: 0,\n\t\t\t\t\t\t\t\tIOPS:     0,\n\t\t\t\t\t\t\t\tNetworks: []Network{\n\t\t\t\t\t\t\t\t\tNetwork{\n\t\t\t\t\t\t\t\t\t\tMBits: 1,\n\t\t\t\t\t\t\t\t\t\tDynamicPorts: []DynamicPort{\n\t\t\t\t\t\t\t\t\t\t\tDynamicPort{Label: \"CONNECTOR_RPC\"},\n\t\t\t\t\t\t\t\t\t\t\tDynamicPort{Label: \"COCOON_RPC\"},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tDispatchPayload: DispatchPayload{},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tResources: Resources{\n\t\t\t\t\t\tCPU:      0,\n\t\t\t\t\t\tMemoryMB: 0,\n\t\t\t\t\t\tIOPS:     0,\n\t\t\t\t\t\tNetworks: []Network{},\n\t\t\t\t\t},\n\t\t\t\t\tRestartPolicy: RestartPolicy{\n\t\t\t\t\t\tInterval: 300000000000,\n\t\t\t\t\t\tAttempts: 10,\n\t\t\t\t\t\tDelay:    25000000000,\n\t\t\t\t\t\tMode:     \"delay\",\n\t\t\t\t\t},\n\t\t\t\t\tMeta: map[string]string{},\n\t\t\t\t},\n\t\t\t},\n\t\t\tUpdate: Update{\n\t\t\t\tStagger:     10000000000,\n\t\t\t\tMaxParallel: 1,\n\t\t\t},\n\t\t},\n\t}\n}\n\n\/\/ GetSpec returns the job's specification\nfunc (j *NomadJob) GetSpec() *Job {\n\treturn j.Job\n}\n<commit_msg>set bare minimum default<commit_after>package scheduler\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ Job defines a nomad job specification\ntype Job struct {\n\tRegion      string\n\tID          string\n\tName        string\n\tType        string\n\tPriority    int\n\tAllAtOnce   bool\n\tDatacenters []string\n\tConstraints []Constraint\n\tTaskGroups  []TaskGroup\n\tUpdate      Update\n}\n\n\/\/ Constraint defines a job\/task contraint\ntype Constraint struct {\n\tLTarget string\n\tRTarget string\n\tOperand string\n}\n\n\/\/ Update defines the update stanza\ntype Update struct {\n\tStagger     int64\n\tMaxParallel int\n}\n\n\/\/ TaskGroups defines the task_group stanza\ntype TaskGroup struct {\n\tName          string\n\tCount         int\n\tConstraints   []string\n\tTasks         []Task\n\tResources     Resources\n\tRestartPolicy RestartPolicy\n\tMeta          map[string]string\n}\n\n\/\/ Task defines a job task\ntype Task struct {\n\tName            string\n\tDriver          string\n\tConfig          Config\n\tEnv             map[string]string\n\tServices        []NomadService\n\tMeta            map[string]string\n\tLogConfig       LogConfig\n\tTemplates       []Template\n\tArtifacts       []Artifact\n\tResources       Resources\n\tDispatchPayload DispatchPayload\n}\n\n\/\/ DispatchPayload configures tast to have access to dispatch payload\ntype DispatchPayload struct {\n\tFile string\n}\n\n\/\/ Resources defines the resources to allocate to a task\ntype Resources struct {\n\tCPU      int\n\tMemoryMB int\n\tIOPS     int\n\tNetworks []Network\n}\n\n\/\/ Network defines network allocation\ntype Network struct {\n\tMBits        int\n\tDynamicPorts []DynamicPort\n}\n\n\/\/ RestartPolicy defines restart policy\ntype RestartPolicy struct {\n\tInterval int64\n\tAttempts int\n\tDelay    int64\n\tMode     string\n}\n\n\/\/ DynamicPort defines a dynamic port allocation\ntype DynamicPort struct {\n\tLabel string\n}\n\n\/\/ Artifact defines an artifact to be downloaded\ntype Artifact struct {\n\tGetterSource  string\n\tRelativeDest  string\n\tGetterOptions map[string]string\n}\n\n\/\/ Template defines template objects to render for the task\ntype Template struct {\n\tSourcePath   string\n\tDestPath     string\n\tEmbeddedTmpl string\n\tChangeMode   string\n\tChangeSignal string\n\tSplay        int64\n}\n\n\/\/ LogConfig defines log configurations\ntype LogConfig struct {\n\tMaxFiles      int\n\tMaxFileSizeMB int\n}\n\n\/\/ NomadService defines a service\ntype NomadService struct {\n\tName      string\n\tTags      []string\n\tPortLabel string\n\tChecks    []Check\n}\n\n\/\/ Check defines a service check\ntype Check struct {\n\tID       string `json:\"Id\"`\n\tName     string\n\tType     string\n\tPath     string\n\tPort     string\n\tTimeout  int64\n\tInterval int64\n\tProtocol string\n}\n\n\/\/ Config defines a driver\/task configuration\ntype Config struct {\n\tCommand string   `json:\"command\"`\n\tArgs    []string `json:\"args\"`\n}\n\n\/\/ NomadJob represents a nomad job\ntype NomadJob struct {\n\tJob *Job\n}\n\n\/\/ NewJob creates a new job with some default values.\nfunc NewJob(connectorVersion, id string, count int) *NomadJob {\n\treturn &NomadJob{\n\t\tJob: &Job{\n\t\t\tRegion:      \"\",\n\t\t\tID:          id,\n\t\t\tName:        id,\n\t\t\tType:        \"service\",\n\t\t\tPriority:    50,\n\t\t\tAllAtOnce:   false,\n\t\t\tDatacenters: []string{},\n\t\t\tConstraints: []Constraint{\n\t\t\t\tConstraint{\n\t\t\t\t\tLTarget: \"${attr.kernel.name}\",\n\t\t\t\t\tRTarget: \"linux\",\n\t\t\t\t\tOperand: \"=\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tTaskGroups: []TaskGroup{\n\t\t\t\tTaskGroup{\n\t\t\t\t\tName:  fmt.Sprintf(\"tskgrp-%s\", id),\n\t\t\t\t\tCount: count,\n\t\t\t\t\tTasks: []Task{\n\t\t\t\t\t\tTask{\n\t\t\t\t\t\t\tName:   fmt.Sprintf(\"task-%s\", id),\n\t\t\t\t\t\t\tDriver: \"raw_exec\",\n\t\t\t\t\t\t\tConfig: Config{\n\t\t\t\t\t\t\t\tCommand: \"bash\",\n\t\t\t\t\t\t\t\tArgs:    []string{\"runner.sh\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tEnv: map[string]string{\n\t\t\t\t\t\t\t\t\"CONNECTOR_VERSION\":   connectorVersion,\n\t\t\t\t\t\t\t\t\"COCOON_ID\":           id,\n\t\t\t\t\t\t\t\t\"CONTAINER_ID\":        id,\n\t\t\t\t\t\t\t\t\"COCOON_CODE_URL\":     \"\",\n\t\t\t\t\t\t\t\t\"COCOON_CODE_TAG\":     \"\",\n\t\t\t\t\t\t\t\t\"COCOON_CODE_LANG\":    \"\",\n\t\t\t\t\t\t\t\t\"COCOON_BUILD_PARAMS\": \"\",\n\t\t\t\t\t\t\t\t\"COCOON_DISK_LIMIT\":   \"\",\n\t\t\t\t\t\t\t\t\/\/ The name of the connector runner script and a link to the script.\n\t\t\t\t\t\t\t\t\/\/ The runner script will fetch and run whatever is found in this environment vars.\n\t\t\t\t\t\t\t\t\"RUN_SCRIPT_NAME\": \"run-connector.sh\",\n\t\t\t\t\t\t\t\t\"RUN_SCRIPT_URL\":  \"https:\/\/rawgit.com\/ncodes\/cocoon\/master\/scripts\/run-connector.sh\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tServices: []NomadService{\n\t\t\t\t\t\t\t\tNomadService{\n\t\t\t\t\t\t\t\t\tName:      fmt.Sprintf(\"cocoons-%s\", id),\n\t\t\t\t\t\t\t\t\tTags:      []string{id},\n\t\t\t\t\t\t\t\t\tPortLabel: \"CONNECTOR_RPC\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tMeta: map[string]string{},\n\t\t\t\t\t\t\tLogConfig: LogConfig{\n\t\t\t\t\t\t\t\tMaxFiles:      10,\n\t\t\t\t\t\t\t\tMaxFileSizeMB: 10,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tTemplates: []Template{},\n\t\t\t\t\t\t\tArtifacts: []Artifact{\n\t\t\t\t\t\t\t\tArtifact{\n\t\t\t\t\t\t\t\t\tGetterSource: \"https:\/\/rawgit.com\/ncodes\/cocoon\/master\/scripts\/runner.sh\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tResources: Resources{\n\t\t\t\t\t\t\t\tCPU:      20,\n\t\t\t\t\t\t\t\tMemoryMB: 10,\n\t\t\t\t\t\t\t\tIOPS:     0,\n\t\t\t\t\t\t\t\tNetworks: []Network{\n\t\t\t\t\t\t\t\t\tNetwork{\n\t\t\t\t\t\t\t\t\t\tMBits: 1,\n\t\t\t\t\t\t\t\t\t\tDynamicPorts: []DynamicPort{\n\t\t\t\t\t\t\t\t\t\t\tDynamicPort{Label: \"CONNECTOR_RPC\"},\n\t\t\t\t\t\t\t\t\t\t\tDynamicPort{Label: \"COCOON_RPC\"},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tDispatchPayload: DispatchPayload{},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tResources: Resources{\n\t\t\t\t\t\tCPU:      20,\n\t\t\t\t\t\tMemoryMB: 10,\n\t\t\t\t\t\tIOPS:     0,\n\t\t\t\t\t\tNetworks: []Network{},\n\t\t\t\t\t},\n\t\t\t\t\tRestartPolicy: RestartPolicy{\n\t\t\t\t\t\tInterval: 300000000000,\n\t\t\t\t\t\tAttempts: 10,\n\t\t\t\t\t\tDelay:    25000000000,\n\t\t\t\t\t\tMode:     \"delay\",\n\t\t\t\t\t},\n\t\t\t\t\tMeta: map[string]string{},\n\t\t\t\t},\n\t\t\t},\n\t\t\tUpdate: Update{\n\t\t\t\tStagger:     10000000000,\n\t\t\t\tMaxParallel: 1,\n\t\t\t},\n\t\t},\n\t}\n}\n\n\/\/ GetSpec returns the job's specification\nfunc (j *NomadJob) GetSpec() *Job {\n\treturn j.Job\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport( \n\t\"fmt\"\n\t\"Golly\/parser\"\n\t\"strconv\"\n)\n\ntype baseType int\nconst(\n\tInt baseType = iota\n\tFloat\n\tChar\n\tSymbol\n\tList\n\tFuncDef\n\tVarDef\n)\n\ntype FuncParem struct{\n\tName string\n\tTypeID int64\n}\n\ntype FunctionDef struct{\n\tNumParems int16\n\tParems []FuncParem\n\tReturnVals []FuncParem\n}\n\ntype TypeDef struct{\n\tName string\n\tOrder int32\n}\n\ntype Union struct{\n\tCurType int16 \n\tTypes []string \n}\n\ntype EnvBinding struct{\n\tName string\n\tBinding interface{}\n}\n\ntype Environment []EnvBinding\n\nfunc (env Environment) findBinding(name string, recur bool) *EnvBinding{\n\tfor i, _ := range env{\n\t\tif env[i].Name == name{\n\t\t\treturn &env[i]\n\t\t}\n\t}\n\tif recur{\n\t\tif len(env) == 0{\n\t\t\tpanic(\"Error: root environment is empty!\\n\")\n\t\t}\n\t\tif parentEnv, ok := env[0].Binding.(Environment); ok {\n\t\t\treturn parentEnv.findBinding(name, true)\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (env *Environment) addBinding(recur bool) *EnvBinding{\n\tif recur{\n\t\tif parentEnv, ok := (*env)[0].Binding.(Environment); ok {\n\t\t\treturn parentEnv.addBinding(true)\n\t\t} else {\n\t\t\t*env = append(*env, EnvBinding{})\n\t\t\treturn &((*env)[len(*env)])\n\t\t}\n\t}else{\n\t\t*env = append(*env, EnvBinding{})\n\t\treturn &((*env)[len(*env)])\n\t}\n}\n\ntype ListCell struct{\n\tTypeName string\n\tValue interface{}\n\tMutable bool\n}\n\ntype CellList struct{\n\tCells []ListCell\n\tEnvironment []EnvBinding\n}\n\nfunc defGlobal(environ *[]EnvBinding) *EnvBinding{\n\tif parentEnv, ok := (*environ)[0].Binding.([]EnvBinding); ok {\n\t\treturn defGlobal(&parentEnv)\n\t} else {\n\t\t*environ = append(*environ, EnvBinding{})\n\t\treturn &((*environ)[len(*environ)])\n\t}\n}\n\nfunc evalNumToken(num *Parser.Token, lineNum int, caller string)(ListCell){\n\tnewValue := ListCell{}\n\t\t\tif (*num).LitType == Parser.FixNum{\n\t\t\t\tfloatval, err := strconv.ParseFloat((*num).Value, 32)\n\t\t\t\tif err != nil{\n\t\t\t\t\terrMsg := fmt.Sprintf(\"Error: cannot parse string %v to float in %v at line %v.\\n\", (*num).Value, caller, lineNum) \n\t\t\t\t\tpanic(errMsg)\n\t\t\t\t}else{\n\t\t\t\t\tnewValue.Value = floatval\n\t\t\t\t\tnewValue.TypeName = \"float\"\n\t\t\t\t}\n\t\t\t}else if (*num).LitType == Parser.FixNum{\n\t\t\t\tintval, err := strconv.Atoi((*num).Value)\n\t\t\t\tif err != nil{\n\t\t\t\t\terrMsg := fmt.Sprintf(\"Error: cannot parse string %v to int in %v at line %v.\\n\", (*num).Value, caller, lineNum) \n\t\t\t\t\tpanic(errMsg)\n\t\t\t\t}else{\n\t\t\t\t\tnewValue.Value = intval\n\t\t\t\t\tnewValue.TypeName = \"int\"\n\t\t\t\t}\n\t\t\t}\n\treturn newValue\n}\n\nfunc evalIdToken(identifierName *Parser.Token, env *Environment, lineNum int, caller string)(interface{}){\n\tvar newValue interface{}\n\tvalueReferenced := env.findBinding((*identifierName).Value, true)\n\t\t\tif valueReferenced == nil{\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to evalute var %v in %v at line %v, but that var is unbound.\\n\", (*identifierName).Value, caller, lineNum) \n\t\t\t\tpanic(errMsg)\n\t\t\t}else{\n\t\t\t\tnewValue = valueReferenced.Binding\n\t\t\t}\n\treturn newValue\n}\nfunc bindVars(list *Parser.Token, env Environment, lineNum int, global, mut bool, caller string)Environment{\n\tfor i := 0; i < len(list.ListVals); i++{\n\t\tval := &list.ListVals[i]\n\t\tif val.Type != Parser.IdToken{\n\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to assign to a non-identifier in %v at line %v.\\n\", caller, lineNum) \n\t\t\tpanic(errMsg)\t\t\t\t\n\t\t}\n\t\tprevBinding := env.findBinding(val.Value, global)\n\t\tvar newBinding *EnvBinding\n\t\tif prevBinding != nil{\n\t\t\tif boundVal, ok := (*prevBinding).Binding.(ListCell); ok {\n\t\t\t\tif !boundVal.Mutable{\n\t\t\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to assign to an immutable identifier in %v at line %v.\\n\", caller, lineNum) \n\t\t\t\t\tpanic(errMsg)\t\t\t\t\n\t\t\t\t}else{\n\t\t\t\t\tnewBinding = prevBinding\n\t\t\t\t}\n\t\t\t} else {\t\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: malformed environment binding encountered in binding for %v in %v at line %v.\\n\", val.Value, caller, lineNum) \n\t\t\t\tpanic(errMsg)\t\t\t\t\n\t\t\t}\n\t\t}else{\n\t\t\tnewBinding = env.addBinding(global)\n\t\t}\n\t\tif i >= len(list.ListVals){\n\t\t\terrMsg := fmt.Sprintf(\"Error: nothing to assign to %v in %v at line %v.\\n\", val.Value, caller, lineNum) \n\t\t\tpanic(errMsg)\n\t\t}\n\t\tnextVal := &list.ListVals[i+1]\n\t\tnewBinding.Name = val.Value\n\t\tnewValue := ListCell{TypeName: \"undecided\", Mutable: mut}\n\t\ttypeNameAnnotated := \"\"\n\t\tswitch (*nextVal).Type {\n\t\tcase Parser.LiteralToken:\n\t\t\tnewValue = evalNumToken(nextVal,lineNum,caller)\n\t\tcase Parser.DefToken:\n\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to assign reserved name %v to %v in %v at line %v.\\n\", (*nextVal).Value, val.Value, caller, lineNum) \n\t\t\tpanic(errMsg)\n\t\tcase Parser.ListToken:\n\t\t\tnewValue.Value = evalListToken(nextVal)\n\t\tcase Parser.TypeAnnToken:\n\t\t\tif i >= len(list.ListVals)+1{\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: no type provided in assignment to %v in %v at line %v.\\n\", val.Value, caller, lineNum) \n\t\t\t\tpanic(errMsg)\n\t\t\t}\n\t\t\tnextValType := &list.ListVals[i+2]\n\t\t\tnewValueType := ListCell{}\n\t\t\tnewNameFound := false\n\t\t\tswitch (*nextValType).Type {\n\t\t\tcase Parser.LiteralToken:\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: attempting use a numeric literal as the type for %v in %v at line %v.\\n\", val.Value, caller, lineNum) \n\t\t\t\tpanic(errMsg)\n\t\t\tcase Parser.DefToken:\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: attempting use a reserved name as the type for %v in %v at line %v.\\n\", val.Value, caller, lineNum) \n\t\t\t\tpanic(errMsg)\n\t\t\tcase Parser.ListToken:\n\t\t\t\tnewValueType = evalListToken(nextVal)\n\t\t\t\tif newValueType.TypeName != \"type\"{\n\t\t\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to assign something that is not a type, but a %v, to %v in %v at line %v.\\n\", newValueType.TypeName, val.Value, caller, lineNum)\n\t\t\t\t\tpanic(errMsg)\n\t\t\t\t}\n\t\t\t\tnewNameFound = true\n\t\t\tcase Parser.TypeAnnToken:\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: misplaced type annotation marker in %v at line %v.\\n\", val.Value, caller, lineNum) \n\t\t\t\tpanic(errMsg)\n\t\t\t}\n\t\t\ttypeName := nextValType.Value\n\t\t\tif newNameFound{\n\t\t\t\tif foundTypeActual, ok := newValueType.Value.(TypeDef); ok {\n\t\t\t\t\ttypeName = foundTypeActual.Name\n\t\t\t\t}else{\n\t\t\t\t\terrMsg := fmt.Sprintf(\"Error: cell claiming to be a type actually contains something else, in %v at line %v.\\n\", caller, lineNum) \n\t\t\t\t\tpanic(errMsg)\n\t\t\t\t}\n\t\t\t}\n\t\t\tnamesBinding := env.findBinding(typeName, true)\n\t\t\tif _, ok := namesBinding.Binding.(TypeDef); ok{\n\t\t\t\ttypeNameAnnotated = typeName\t\n\t\t\t}else{\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to assign type %v to %v in %v at line %v, but that type is not bound.\\n\", typeName, val.Value, caller, lineNum) \n\t\t\t\tpanic(errMsg)\n\t\t\t}\n\t\t}\n\t\tif newValue.TypeName != \"undecided\" && newValue.TypeName != typeNameAnnotated{\n\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to assign type %v to %v in %v at line %v, but it is already of type %v.\\n\", typeNameAnnotated, val.Value, caller, lineNum, newValue.TypeName) \n\t\t\tpanic(errMsg)\n\t\t}else if typeNameAnnotated != \"\"{\n\t\t\tnewValue.TypeName = typeNameAnnotated\n\t\t}\n\t\tnewBinding.Binding = newValue\n\t}\n\treturn env\n}\n\nfunc evalListToken(list *Parser.Token)(ListCell){\n\tfirstVal := &list.ListVals[0]\n\/\/\tinitCellList := CellList{}\n\tinitEnvironment := Environment{}\n\tswitch firstVal.Type{\n\tcase Parser.LiteralToken: \n\t\terrMsg := fmt.Sprintf(\"Error: attempting to evaluate a literal, %v, at line %v.\\n\", firstVal.Value, firstVal.LineNum) \n\t\tpanic(errMsg)\n\tcase Parser.DefToken:\n\t\tdefKind := &firstVal.Value\n\t\tif len(list.ListVals) < 3{\n\t\t\terrMsg := fmt.Sprintf(\"Error: too few arguments to %v at line %v.\\n\", defKind, firstVal.LineNum) \n\t\t\tpanic(errMsg)\t\t\t\t\n\t\t}else if list.ListVals[1].Type != Parser.ListToken{\n\t\t\terrMsg := fmt.Sprintf(\"Error: first argument (%v) to %v at line %v is not a list.\\n\",list.ListVals[1].Value, defKind, firstVal.LineNum) \n\t\t\tpanic(errMsg)\t\t\t\t\n\t\t}else if list.ListVals[2].Type != Parser.ListToken{\n\t\t\terrMsg := fmt.Sprintf(\"Error: second argument (%v) to %v  at line %v is not a list.\\n\",list.ListVals[2].Value, defKind, firstVal.LineNum) \n\t\t\tpanic(errMsg)\t\t\t\t\n\t\t}else if len(list.ListVals) > 3{\n\t\t\terrMsg := fmt.Sprintf(\"Error: too many arguments to %v at line %v.\\n\",defKind, firstVal.LineNum) \n\t\t\tpanic(errMsg)\t\t\t\t\n\t\t}\n\t\tinitEnvironment = bindVars(&list.ListVals[1], initEnvironment, firstVal.LineNum, true, true, \"let\")\n\t\n\t\t\t\n\t}\n\treturn ListCell{} \n}\n\nfunc main(){\n\t\/\/types := []string{\"Int\", \"Float\", \"Char\", \"Symbol\", \"List\"}\n\tinput := `(let (a 1) (b 2))`\n\tres := Parser.Lex(&input)\n\ttokens := Parser.ParseList(res, 0)\n\tfor _, tok := range tokens.ListVals{\n\t\tfmt.Println(tok)\n\t}\n\tevalListToken(&tokens.ListVals[0])\n}\n<commit_msg>Improved type handling.<commit_after>package main\n\nimport( \n\t\"fmt\"\n\t\"Golly\/parser\"\n\t\"strconv\"\n)\n\ntype baseType int\nconst(\n\tInt baseType = iota\n\tFloat\n\tChar\n\tSymbol\n\tList\n\tFuncDef\n\tVarDef\n)\n\ntype FuncParem struct{\n\tName string\n\tTypeID int64\n}\n\ntype FunctionDef struct{\n\tNumParems int16\n\tParems []FuncParem\n\tReturnVals []FuncParem\n}\n\ntype singleType struct{\n\tInputs []string\n\tOutputs []string\n\tOrder int8 \n}\n\ntype TypeDef struct{\n\tName string\n\tTypes []singleType\n}\n\ntype Union struct{\n\tCurType int16 \n\tTypes []string \n}\n\ntype EnvBinding struct{\n\tName string\n\tBinding ListCell\n}\n\ntype Environment []EnvBinding\n\nfunc (env Environment) findBinding(name string, recur bool) *EnvBinding{\n\tfor i, _ := range env{\n\t\tif env[i].Name == name{\n\t\t\treturn &env[i]\n\t\t}\n\t}\n\tif recur{\n\t\tif len(env) == 0{\n\t\t\tpanic(\"Error: root environment is empty!\\n\")\n\t\t}\n\t\tif env[0].Binding.TypeName == \"environment\"{\n\t\t\tif parentEnv, ok := env[0].Binding.Value.(Environment); ok {\t\n\t\t\t\treturn parentEnv.findBinding(name, true)\n\t\t\t}else{\n\t\t\t\tpanic(\"Error: encountered an environment-typed cell that contained no environment! This shouldn't happen; report it as a bug.\\n\")\n\t\t\t}\n\t\t}else{\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (env *Environment) addBinding(recur bool) *EnvBinding{\n\tif recur{\n\t\tif (*env)[0].Binding.TypeName == \"environment\"{\n\t\t\tif parentEnv, ok := (*env)[0].Binding.Value.(Environment); ok {\n\t\t\t\treturn parentEnv.addBinding(true)\n\t\t\t}else{\n\t\t\t\tpanic(\"Error: encountered an environment-typed cell that contained no environment! This shouldn't happen; report it as a bug.\\n\")\n\t\t\t}\t\t\n\t\t}else {\n\t\t\t*env = append(*env, EnvBinding{})\n\t\t\treturn &((*env)[len(*env)])\n\t\t}\n\t}else{\n\t\t*env = append(*env, EnvBinding{})\n\t\treturn &((*env)[len(*env)])\n\t}\n}\n\ntype ListCell struct{\n\tTypeName string\n\tValue interface{}\n\tMutable bool\n}\n\ntype CellList struct{\n\tCells []ListCell\n\tEnvironment []EnvBinding\n}\n\nfunc evalNumToken(num *Parser.Token, lineNum int, caller string)(ListCell){\n\tnewValue := ListCell{}\n\t\t\tif (*num).LitType == Parser.FixNum{\n\t\t\t\tfloatval, err := strconv.ParseFloat((*num).Value, 32)\n\t\t\t\tif err != nil{\n\t\t\t\t\terrMsg := fmt.Sprintf(\"Error: cannot parse string %v to float in %v at line %v.\\n\", (*num).Value, caller, lineNum) \n\t\t\t\t\tpanic(errMsg)\n\t\t\t\t}else{\n\t\t\t\t\tnewValue.Value = floatval\n\t\t\t\t\tnewValue.TypeName = \"float\"\n\t\t\t\t}\n\t\t\t}else if (*num).LitType == Parser.FixNum{\n\t\t\t\tintval, err := strconv.Atoi((*num).Value)\n\t\t\t\tif err != nil{\n\t\t\t\t\terrMsg := fmt.Sprintf(\"Error: cannot parse string %v to int in %v at line %v.\\n\", (*num).Value, caller, lineNum) \n\t\t\t\t\tpanic(errMsg)\n\t\t\t\t}else{\n\t\t\t\t\tnewValue.Value = intval\n\t\t\t\t\tnewValue.TypeName = \"int\"\n\t\t\t\t}\n\t\t\t}\n\treturn newValue\n}\n\nfunc evalIdToken(identifierName *Parser.Token, env *Environment, lineNum int, caller string)(interface{}){\n\tvar newValue interface{}\n\tvalueReferenced := env.findBinding((*identifierName).Value, true)\n\t\t\tif valueReferenced == nil{\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to evalute var %v in %v at line %v, but that var is unbound.\\n\", (*identifierName).Value, caller, lineNum) \n\t\t\t\tpanic(errMsg)\n\t\t\t}else{\n\t\t\t\tnewValue = valueReferenced.Binding\n\t\t\t}\n\treturn newValue\n}\nfunc bindVars(list *Parser.Token, env Environment, lineNum int, global, mut bool, caller string)Environment{\n\tfor i := 0; i < len(list.ListVals); i++{\n\t\tval := &list.ListVals[i]\n\t\tif val.Type != Parser.IdToken{\n\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to assign to a non-identifier in %v at line %v.\\n\", caller, lineNum) \n\t\t\tpanic(errMsg)\t\t\t\t\n\t\t}\n\t\tprevBinding := env.findBinding(val.Value, global)\n\t\tvar newBinding *EnvBinding\n\t\tif prevBinding != nil{\n\t\t\tif !(*prevBinding).Binding.Mutable{\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to assign to an immutable identifier in %v at line %v.\\n\", caller, lineNum) \n\t\t\t\tpanic(errMsg)\t\t\t\t\n\t\t\t}else{\n\t\t\t\tnewBinding = prevBinding\n\t\t\t}\n\t\t}else{\n\t\t\tnewBinding = env.addBinding(global)\n\t\t}\n\t\tif i >= len(list.ListVals){\n\t\t\terrMsg := fmt.Sprintf(\"Error: nothing to assign to %v in %v at line %v.\\n\", val.Value, caller, lineNum) \n\t\t\tpanic(errMsg)\n\t\t}\n\t\tnextVal := &list.ListVals[i+1]\n\t\tnewBinding.Name = val.Value\n\t\tnewValue := ListCell{TypeName: \"undecided\", Mutable: mut}\n\t\ttypeNameAnnotated := \"\"\n\t\tswitch (*nextVal).Type {\n\t\tcase Parser.LiteralToken:\n\t\t\tnewValue = evalNumToken(nextVal,lineNum,caller)\n\t\tcase Parser.DefToken:\n\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to assign reserved name %v to %v in %v at line %v.\\n\", (*nextVal).Value, val.Value, caller, lineNum) \n\t\t\tpanic(errMsg)\n\t\tcase Parser.ListToken:\n\t\t\tnewValue.Value = evalListToken(nextVal)\n\t\tcase Parser.TypeAnnToken:\n\t\t\tif i >= len(list.ListVals)+1{\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: no type provided in assignment to %v in %v at line %v.\\n\", val.Value, caller, lineNum) \n\t\t\t\tpanic(errMsg)\n\t\t\t}\n\t\t\tnextValType := &list.ListVals[i+2]\n\t\t\tnewValueType := ListCell{}\n\t\t\tnewNameFound := false\n\t\t\tswitch (*nextValType).Type {\n\t\t\tcase Parser.LiteralToken:\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: attempting use a numeric literal as the type for %v in %v at line %v.\\n\", val.Value, caller, lineNum) \n\t\t\t\tpanic(errMsg)\n\t\t\tcase Parser.DefToken:\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: attempting use a reserved name as the type for %v in %v at line %v.\\n\", val.Value, caller, lineNum) \n\t\t\t\tpanic(errMsg)\n\t\t\tcase Parser.ListToken:\n\t\t\t\tnewValueType = evalListToken(nextVal)\n\t\t\t\tif newValueType.TypeName != \"type\"{\n\t\t\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to assign something that is not a type, but a %v, to %v in %v at line %v.\\n\", newValueType.TypeName, val.Value, caller, lineNum)\n\t\t\t\t\tpanic(errMsg)\n\t\t\t\t}\n\t\t\t\tnewNameFound = true\n\t\t\tcase Parser.TypeAnnToken:\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: misplaced type annotation marker in %v at line %v.\\n\", val.Value, caller, lineNum) \n\t\t\t\tpanic(errMsg)\n\t\t\t}\n\t\t\ttypeName := nextValType.Value\n\t\t\tif newNameFound{\n\t\t\t\tif foundTypeActual, ok := newValueType.Value.(TypeDef); ok {\n\t\t\t\t\ttypeName = foundTypeActual.Name\n\t\t\t\t}else{\n\t\t\t\t\terrMsg := fmt.Sprintf(\"Error: cell claiming to be a type actually contains something else, in %v at line %v.\\n\", caller, lineNum) \n\t\t\t\t\tpanic(errMsg)\n\t\t\t\t}\n\t\t\t}\n\t\t\tnamesBinding := env.findBinding(typeName, true)\n\t\t\tif namesBinding.Binding.TypeName == \"type\"{\n\t\t\t\ttypeNameAnnotated = typeName\t\n\t\t\t}else{\n\t\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to assign type %v to %v in %v at line %v, but that type is not bound.\\n\", typeName, val.Value, caller, lineNum) \n\t\t\t\tpanic(errMsg)\n\t\t\t}\n\t\t}\n\t\tif newValue.TypeName != \"undecided\" && newValue.TypeName != typeNameAnnotated{\n\t\t\terrMsg := fmt.Sprintf(\"Error: attempting to assign type %v to %v in %v at line %v, but it is already of type %v.\\n\", typeNameAnnotated, val.Value, caller, lineNum, newValue.TypeName) \n\t\t\tpanic(errMsg)\n\t\t}else if typeNameAnnotated != \"\"{\n\t\t\tnewValue.TypeName = typeNameAnnotated\n\t\t}\n\t\tnewBinding.Binding = newValue\n\t}\n\treturn env\n}\n\nfunc evalListToken(list *Parser.Token)(ListCell){\n\tfirstVal := &list.ListVals[0]\n\/\/\tinitCellList := CellList{}\n\tinitEnvironment := Environment{}\n\tswitch firstVal.Type{\n\tcase Parser.LiteralToken: \n\t\terrMsg := fmt.Sprintf(\"Error: attempting to evaluate a literal, %v, at line %v.\\n\", firstVal.Value, firstVal.LineNum) \n\t\tpanic(errMsg)\n\tcase Parser.DefToken:\n\t\tdefKind := &firstVal.Value\n\t\tif len(list.ListVals) < 3{\n\t\t\terrMsg := fmt.Sprintf(\"Error: too few arguments to %v at line %v.\\n\", defKind, firstVal.LineNum) \n\t\t\tpanic(errMsg)\t\t\t\t\n\t\t}else if list.ListVals[1].Type != Parser.ListToken{\n\t\t\terrMsg := fmt.Sprintf(\"Error: first argument (%v) to %v at line %v is not a list.\\n\",list.ListVals[1].Value, defKind, firstVal.LineNum) \n\t\t\tpanic(errMsg)\t\t\t\t\n\t\t}else if list.ListVals[2].Type != Parser.ListToken{\n\t\t\terrMsg := fmt.Sprintf(\"Error: second argument (%v) to %v  at line %v is not a list.\\n\",list.ListVals[2].Value, defKind, firstVal.LineNum) \n\t\t\tpanic(errMsg)\t\t\t\t\n\t\t}else if len(list.ListVals) > 3{\n\t\t\terrMsg := fmt.Sprintf(\"Error: too many arguments to %v at line %v.\\n\",defKind, firstVal.LineNum) \n\t\t\tpanic(errMsg)\t\t\t\t\n\t\t}\n\t\tinitEnvironment = bindVars(&list.ListVals[1], initEnvironment, firstVal.LineNum, true, true, \"let\")\n\t\n\t\t\t\n\t}\n\treturn ListCell{} \n}\n\nfunc main(){\n\t\/\/types := []string{\"Int\", \"Float\", \"Char\", \"Symbol\", \"List\"}\n\tinput := `(let (a 1) (b 2))`\n\tres := Parser.Lex(&input)\n\ttokens := Parser.ParseList(res, 0)\n\tfor _, tok := range tokens.ListVals{\n\t\tfmt.Println(tok)\n\t}\n\tevalListToken(&tokens.ListVals[0])\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"$GO_BOOTSTRAP_REPO_NAME\/$GO_BOOTSTRAP_REPO_USER\/$GO_BOOTSTRAP_PROJECT_NAME\/dal\"\n\t\"$GO_BOOTSTRAP_REPO_NAME\/$GO_BOOTSTRAP_REPO_USER\/$GO_BOOTSTRAP_PROJECT_NAME\/handlers\"\n\t\"$GO_BOOTSTRAP_REPO_NAME\/$GO_BOOTSTRAP_REPO_USER\/$GO_BOOTSTRAP_PROJECT_NAME\/libenv\"\n\t\"$GO_BOOTSTRAP_REPO_NAME\/$GO_BOOTSTRAP_REPO_USER\/$GO_BOOTSTRAP_PROJECT_NAME\/libunix\"\n\t\"$GO_BOOTSTRAP_REPO_NAME\/$GO_BOOTSTRAP_REPO_USER\/$GO_BOOTSTRAP_PROJECT_NAME\/middlewares\"\n\t\"github.com\/carbocation\/interpose\"\n\tgorilla_mux \"github.com\/gorilla\/mux\"\n\t\"github.com\/gorilla\/sessions\"\n\t\"github.com\/jmoiron\/sqlx\"\n\t_ \"github.com\/lib\/pq\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/tylerb\/graceful\"\n\t\"net\/http\"\n\t\"time\"\n)\n\nfunc init() {\n\tgob.Register(&dal.UserRow{})\n}\n\n\/\/ NewApplication is the constructor for Application struct.\nfunc NewApplication() (*Application, error) {\n\tu, err := libunix.CurrentUser()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdsn := libenv.EnvWithDefault(\"DSN\", fmt.Sprintf(\"postgres:\/\/%v@localhost:5432\/$GO_BOOTSTRAP_PROJECT_NAME?sslmode=disable\", u))\n\n\tdb, err := sqlx.Connect(\"postgres\", dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcookieStoreSecret := libenv.EnvWithDefault(\"COOKIE_SECRET\", \"$GO_BOOTSTRAP_COOKIE_SECRET\")\n\n\trm := &Application{}\n\trm.dsn = dsn\n\trm.db = db\n\trm.cookieStore = sessions.NewCookieStore([]byte(cookieStoreSecret))\n\n\treturn rm, err\n}\n\n\/\/ Application is the application object that runs HTTP server.\ntype Application struct {\n\tdsn         string\n\tdb          *sqlx.DB\n\tcookieStore *sessions.CookieStore\n}\n\nfunc (rm *Application) middlewareStruct() (*interpose.Middleware, error) {\n\tmiddle := interpose.New()\n\tmiddle.Use(middlewares.SetDB(rm.db))\n\tmiddle.Use(middlewares.SetCookieStore(rm.cookieStore))\n\n\tmiddle.UseHandler(rm.mux())\n\n\treturn middle, nil\n}\n\nfunc (rm *Application) mux() *gorilla_mux.Router {\n\tMustLogin := middlewares.MustLogin\n\n\trouter := gorilla_mux.NewRouter()\n\n\trouter.Handle(\"\/\", MustLogin(http.HandlerFunc(handlers.GetHome))).Methods(\"GET\")\n\n\trouter.HandleFunc(\"\/signup\", handlers.GetSignup).Methods(\"GET\")\n\trouter.HandleFunc(\"\/signup\", handlers.PostSignup).Methods(\"POST\")\n\trouter.HandleFunc(\"\/login\", handlers.GetLogin).Methods(\"GET\")\n\trouter.HandleFunc(\"\/login\", handlers.PostLogin).Methods(\"POST\")\n\trouter.HandleFunc(\"\/logout\", handlers.GetLogout).Methods(\"GET\")\n\n\trouter.Handle(\"\/users\/{id:[0-9]+}\", MustLogin(http.HandlerFunc(handlers.PostPutDeleteUsersID))).Methods(\"POST\", \"PUT\", \"DELETE\")\n\n\t\/\/ Path of static files must be last!\n\trouter.PathPrefix(\"\/\").Handler(http.FileServer(http.Dir(\"static\")))\n\n\treturn router\n}\n\nfunc main() {\n\tapp, err := NewApplication()\n\tif err != nil {\n\t\tlogrus.Fatal(err.Error())\n\t}\n\n\tmiddle, err := app.middlewareStruct()\n\tif err != nil {\n\t\tlogrus.Fatal(err.Error())\n\t}\n\n\tserverAddress := libenv.EnvWithDefault(\"HTTP_ADDR\", \":8888\")\n\tcertFile := libenv.EnvWithDefault(\"HTTP_CERT_FILE\", \"\")\n\tkeyFile := libenv.EnvWithDefault(\"HTTP_KEY_FILE\", \"\")\n\tdrainIntervalString := libenv.EnvWithDefault(\"HTTP_DRAIN_INTERVAL\", \"1s\")\n\n\tdrainInterval, err := time.ParseDuration(drainIntervalString)\n\tif err != nil {\n\t\tlogrus.Fatal(err.Error())\n\t}\n\n\tsrv := &graceful.Server{\n\t\tTimeout: drainInterval,\n\t\tServer:  &http.Server{Addr: serverAddress, Handler: middle},\n\t}\n\n\tlogrus.Infoln(\"Running HTTP server on \"+ serverAddress)\n\tif certFile != \"\" && keyFile != \"\" {\n\t\tsrv.ListenAndServeTLS(certFile, keyFile)\n\t} else {\n\t\tsrv.ListenAndServe()\n\t}\n}\n<commit_msg>cleanup self pointer on main.go<commit_after>package main\n\nimport (\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"$GO_BOOTSTRAP_REPO_NAME\/$GO_BOOTSTRAP_REPO_USER\/$GO_BOOTSTRAP_PROJECT_NAME\/dal\"\n\t\"$GO_BOOTSTRAP_REPO_NAME\/$GO_BOOTSTRAP_REPO_USER\/$GO_BOOTSTRAP_PROJECT_NAME\/handlers\"\n\t\"$GO_BOOTSTRAP_REPO_NAME\/$GO_BOOTSTRAP_REPO_USER\/$GO_BOOTSTRAP_PROJECT_NAME\/libenv\"\n\t\"$GO_BOOTSTRAP_REPO_NAME\/$GO_BOOTSTRAP_REPO_USER\/$GO_BOOTSTRAP_PROJECT_NAME\/libunix\"\n\t\"$GO_BOOTSTRAP_REPO_NAME\/$GO_BOOTSTRAP_REPO_USER\/$GO_BOOTSTRAP_PROJECT_NAME\/middlewares\"\n\t\"github.com\/carbocation\/interpose\"\n\tgorilla_mux \"github.com\/gorilla\/mux\"\n\t\"github.com\/gorilla\/sessions\"\n\t\"github.com\/jmoiron\/sqlx\"\n\t_ \"github.com\/lib\/pq\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/tylerb\/graceful\"\n\t\"net\/http\"\n\t\"time\"\n)\n\nfunc init() {\n\tgob.Register(&dal.UserRow{})\n}\n\n\/\/ NewApplication is the constructor for Application struct.\nfunc NewApplication() (*Application, error) {\n\tu, err := libunix.CurrentUser()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdsn := libenv.EnvWithDefault(\"DSN\", fmt.Sprintf(\"postgres:\/\/%v@localhost:5432\/$GO_BOOTSTRAP_PROJECT_NAME?sslmode=disable\", u))\n\n\tdb, err := sqlx.Connect(\"postgres\", dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcookieStoreSecret := libenv.EnvWithDefault(\"COOKIE_SECRET\", \"$GO_BOOTSTRAP_COOKIE_SECRET\")\n\n\tapp := &Application{}\n\tapp.dsn = dsn\n\tapp.db = db\n\tapp.cookieStore = sessions.NewCookieStore([]byte(cookieStoreSecret))\n\n\treturn app, err\n}\n\n\/\/ Application is the application object that runs HTTP server.\ntype Application struct {\n\tdsn         string\n\tdb          *sqlx.DB\n\tcookieStore *sessions.CookieStore\n}\n\nfunc (app *Application) middlewareStruct() (*interpose.Middleware, error) {\n\tmiddle := interpose.New()\n\tmiddle.Use(middlewares.SetDB(app.db))\n\tmiddle.Use(middlewares.SetCookieStore(app.cookieStore))\n\n\tmiddle.UseHandler(app.mux())\n\n\treturn middle, nil\n}\n\nfunc (app *Application) mux() *gorilla_mux.Router {\n\tMustLogin := middlewares.MustLogin\n\n\trouter := gorilla_mux.NewRouter()\n\n\trouter.Handle(\"\/\", MustLogin(http.HandlerFunc(handlers.GetHome))).Methods(\"GET\")\n\n\trouter.HandleFunc(\"\/signup\", handlers.GetSignup).Methods(\"GET\")\n\trouter.HandleFunc(\"\/signup\", handlers.PostSignup).Methods(\"POST\")\n\trouter.HandleFunc(\"\/login\", handlers.GetLogin).Methods(\"GET\")\n\trouter.HandleFunc(\"\/login\", handlers.PostLogin).Methods(\"POST\")\n\trouter.HandleFunc(\"\/logout\", handlers.GetLogout).Methods(\"GET\")\n\n\trouter.Handle(\"\/users\/{id:[0-9]+}\", MustLogin(http.HandlerFunc(handlers.PostPutDeleteUsersID))).Methods(\"POST\", \"PUT\", \"DELETE\")\n\n\t\/\/ Path of static files must be last!\n\trouter.PathPrefix(\"\/\").Handler(http.FileServer(http.Dir(\"static\")))\n\n\treturn router\n}\n\nfunc main() {\n\tapp, err := NewApplication()\n\tif err != nil {\n\t\tlogrus.Fatal(err.Error())\n\t}\n\n\tmiddle, err := app.middlewareStruct()\n\tif err != nil {\n\t\tlogrus.Fatal(err.Error())\n\t}\n\n\tserverAddress := libenv.EnvWithDefault(\"HTTP_ADDR\", \":8888\")\n\tcertFile := libenv.EnvWithDefault(\"HTTP_CERT_FILE\", \"\")\n\tkeyFile := libenv.EnvWithDefault(\"HTTP_KEY_FILE\", \"\")\n\tdrainIntervalString := libenv.EnvWithDefault(\"HTTP_DRAIN_INTERVAL\", \"1s\")\n\n\tdrainInterval, err := time.ParseDuration(drainIntervalString)\n\tif err != nil {\n\t\tlogrus.Fatal(err.Error())\n\t}\n\n\tsrv := &graceful.Server{\n\t\tTimeout: drainInterval,\n\t\tServer:  &http.Server{Addr: serverAddress, Handler: middle},\n\t}\n\n\tlogrus.Infoln(\"Running HTTP server on \"+ serverAddress)\n\tif certFile != \"\" && keyFile != \"\" {\n\t\tsrv.ListenAndServeTLS(certFile, keyFile)\n\t} else {\n\t\tsrv.ListenAndServe()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* vim: set sw=4 sts=4 et foldmethod=syntax : *\/\n\n\/*\n * Copyright (c) 2011 Alexander Færøy <ahf@0x90.dk>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n *   list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n *   this list of conditions and the following disclaimer in the documentation\n *   and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\npackage main\n\nimport (\n    \"strings\"\n)\n\ntype Channel struct {\n    ircd *Ircd \/\/ Pointer to the IRCd instance.\n\n    name string \/\/ The name of the channel.\n    topic string \/\/ The topic of the channel.\n\n    joining chan *Client \/\/ Channel of Joining Members.\n    parting chan *Client \/\/ Channel of Members whom are leaving.\n    read_topic chan chan string \/\/ Channel for synchronous read of the topic.\n    private_messages chan *PrivateMessage \/\/ Channel of private messages.\n\n    clients *ClientSet \/\/ Client Members.\n}\n\nfunc NewChannel(ircd *Ircd, name string) *Channel {\n    channel := new(Channel)\n\n    \/\/ Channel Name.\n    channel.name = name\n\n    \/\/ Default to Empty Topic.\n    channel.topic = \"\"\n\n    \/\/ The IRCd.\n    channel.ircd = ircd\n\n    \/\/ Clients.\n    channel.clients = NewClientSet()\n\n    \/\/ Channels.\n    channel.joining = make(chan *Client)\n    channel.parting = make(chan *Client)\n    channel.read_topic = make(chan chan string)\n    channel.private_messages = make(chan *PrivateMessage)\n\n    \/\/ Message Handler.\n    go channel.Handler()\n\n    return channel\n}\n\nfunc (this *Channel) Handler() {\n    this.Printf(\"Starting Channel Handler\")\n    defer this.Printf(\"Leaving Channel Handler\")\n\n    \/\/ The IRCd.\n    ircd := this.ircd\n\n    for {\n        select {\n            case joining_client := <-this.joining:\n                this.Printf(\"Client '%s' joined.\", joining_client)\n\n                \/\/ This is true, if our joining client is the creator of the channel.\n                \/\/   creator := this.clients.Len() == 0\n\n                \/\/ Insert our new client.\n                this.clients.Insert(joining_client)\n\n                \/\/ Send JOIN message to all clients.\n                this.clients.ForEach(func (client *Client) {\n                    client.ChannelJoin(joining_client, this)\n                })\n\n                \/\/ Client Names.\n                names := this.clients.Names()\n\n                \/\/ NOTE: See RB codebase for information about the \"=\" here.\n                joining_client.SendNumeric(RPL_NAMREPLY, ircd.Me(), joining_client.Nickname(), \"=\", this.name, strings.Join(names, \" \"))\n\n                \/\/ FIXME: This could become a long message for large channels.\n                joining_client.SendNumeric(RPL_ENDOFNAMES, ircd.Me(), joining_client.Nickname(), this.name)\n\n\n            case parting_client := <-this.parting:\n                this.Printf(\"Client '%s' left.\", parting_client)\n\n                \/\/ Send PART message to all clients, including ourself.\n                this.clients.ForEach(func (client *Client) {\n                    client.ChannelPart(parting_client, this)\n                })\n\n                \/\/ Remove our client.\n                this.clients.Delete(parting_client)\n\n                \/\/ Last member left?\n                if this.clients.Len() == 0 {\n                    \/\/ Unregister.\n                    this.Unregister()\n\n                    \/\/ Shutdown.\n                    return\n                }\n\n            case topic_reader := <-this.read_topic:\n                \/\/ Send topic.\n                topic_reader<-this.topic\n\n            case message := <-this.private_messages:\n                \/\/ Source Client.\n                source := message.Source()\n\n                \/\/ Broadcast to each client, except the source.\n                this.clients.ForEach(func (client *Client) {\n                    \/\/ FIXME: Should we compare source.Nickname() with\n                    \/\/ client.Nickname() here?\n                    if source == client {\n                        \/\/ Don't send message to ourself.\n                        return\n                    }\n\n                    \/\/ Send message.\n                    client.PrivateMessage(message)\n                })\n        }\n    }\n}\n\nfunc (this *Channel) Join(client *Client) {\n    this.joining<-client\n}\n\nfunc (this *Channel) Part(client *Client) {\n    this.parting<-client\n}\n\nfunc (this *Channel) Topic() string {\n    c := make(chan string)\n    this.read_topic<-c\n    return <-c\n}\n\nfunc (this *Channel) PrivateMessage(message *PrivateMessage) {\n    this.private_messages<-message\n}\n\nfunc (this *Channel) Unregister() {\n    this.ircd.UnregisterChannel(this)\n}\n\nfunc (this *Channel) Name() string {\n    return this.name\n}\n\nfunc (this *Channel) String() string {\n    return this.name\n}\n\nfunc (this *Channel) Printf(format string, a...interface{}) {\n    this.ircd.Printf(this.String() + \": \" + format, a...)\n}\n<commit_msg>Add ClientCount() to the Channel type.<commit_after>\/* vim: set sw=4 sts=4 et foldmethod=syntax : *\/\n\n\/*\n * Copyright (c) 2011 Alexander Færøy <ahf@0x90.dk>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n *   list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n *   this list of conditions and the following disclaimer in the documentation\n *   and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\npackage main\n\nimport (\n    \"strings\"\n)\n\ntype Channel struct {\n    ircd *Ircd \/\/ Pointer to the IRCd instance.\n\n    name string \/\/ The name of the channel.\n    topic string \/\/ The topic of the channel.\n\n    joining chan *Client \/\/ Channel of Joining Members.\n    parting chan *Client \/\/ Channel of Members whom are leaving.\n    read_topic chan chan string \/\/ Channel for synchronous read of the topic.\n    read_client_count chan chan int \/\/ Channel for reading the client count of the channel.\n    private_messages chan *PrivateMessage \/\/ Channel of private messages.\n\n    clients *ClientSet \/\/ Client Members.\n}\n\nfunc NewChannel(ircd *Ircd, name string) *Channel {\n    channel := new(Channel)\n\n    \/\/ Channel Name.\n    channel.name = name\n\n    \/\/ Default to Empty Topic.\n    channel.topic = \"\"\n\n    \/\/ The IRCd.\n    channel.ircd = ircd\n\n    \/\/ Clients.\n    channel.clients = NewClientSet()\n\n    \/\/ Channels.\n    channel.joining = make(chan *Client)\n    channel.parting = make(chan *Client)\n    channel.read_topic = make(chan chan string)\n    channel.private_messages = make(chan *PrivateMessage)\n    channel.read_client_count = make(chan chan int)\n\n    \/\/ Message Handler.\n    go channel.Handler()\n\n    return channel\n}\n\nfunc (this *Channel) Handler() {\n    this.Printf(\"Starting Channel Handler\")\n    defer this.Printf(\"Leaving Channel Handler\")\n\n    \/\/ The IRCd.\n    ircd := this.ircd\n\n    for {\n        select {\n            case joining_client := <-this.joining:\n                this.Printf(\"Client '%s' joined.\", joining_client)\n\n                \/\/ This is true, if our joining client is the creator of the channel.\n                \/\/   creator := this.clients.Len() == 0\n\n                \/\/ Insert our new client.\n                this.clients.Insert(joining_client)\n\n                \/\/ Send JOIN message to all clients.\n                this.clients.ForEach(func (client *Client) {\n                    client.ChannelJoin(joining_client, this)\n                })\n\n                \/\/ Client Names.\n                names := this.clients.Names()\n\n                \/\/ NOTE: See RB codebase for information about the \"=\" here.\n                joining_client.SendNumeric(RPL_NAMREPLY, ircd.Me(), joining_client.Nickname(), \"=\", this.name, strings.Join(names, \" \"))\n\n                \/\/ FIXME: This could become a long message for large channels.\n                joining_client.SendNumeric(RPL_ENDOFNAMES, ircd.Me(), joining_client.Nickname(), this.name)\n\n\n            case parting_client := <-this.parting:\n                this.Printf(\"Client '%s' left.\", parting_client)\n\n                \/\/ Send PART message to all clients, including ourself.\n                this.clients.ForEach(func (client *Client) {\n                    client.ChannelPart(parting_client, this)\n                })\n\n                \/\/ Remove our client.\n                this.clients.Delete(parting_client)\n\n                \/\/ Last member left?\n                if this.clients.Len() == 0 {\n                    \/\/ Unregister.\n                    this.Unregister()\n\n                    \/\/ Shutdown.\n                    return\n                }\n\n            case topic_reader := <-this.read_topic:\n                \/\/ Send topic.\n                topic_reader<-this.topic\n\n            case client_count_reader := <-this.read_client_count:\n                \/\/ Send the client count.\n                client_count_reader<-this.clients.Len()\n\n            case message := <-this.private_messages:\n                \/\/ Source Client.\n                source := message.Source()\n\n                \/\/ Broadcast to each client, except the source.\n                this.clients.ForEach(func (client *Client) {\n                    \/\/ FIXME: Should we compare source.Nickname() with\n                    \/\/ client.Nickname() here?\n                    if source == client {\n                        \/\/ Don't send message to ourself.\n                        return\n                    }\n\n                    \/\/ Send message.\n                    client.PrivateMessage(message)\n                })\n        }\n    }\n}\n\nfunc (this *Channel) Join(client *Client) {\n    this.joining<-client\n}\n\nfunc (this *Channel) Part(client *Client) {\n    this.parting<-client\n}\n\nfunc (this *Channel) Topic() string {\n    c := make(chan string)\n    this.read_topic<-c\n    return <-c\n}\n\nfunc (this *Channel) ClientCount() chan int {\n    c := make(chan int)\n    this.read_client_count<-c\n    return c\n}\n\nfunc (this *Channel) PrivateMessage(message *PrivateMessage) {\n    this.private_messages<-message\n}\n\nfunc (this *Channel) Unregister() {\n    this.ircd.UnregisterChannel(this)\n}\n\nfunc (this *Channel) Name() string {\n    return this.name\n}\n\nfunc (this *Channel) String() string {\n    return this.name\n}\n\nfunc (this *Channel) Printf(format string, a...interface{}) {\n    this.ircd.Printf(this.String() + \": \" + format, a...)\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\thumanize \"github.com\/dustin\/go-humanize\"\n\t\"github.com\/schollz\/croc\/src\/croc\"\n\t\"github.com\/schollz\/croc\/src\/utils\"\n\t\"github.com\/skratchdot\/open-golang\/open\"\n\t\"github.com\/urfave\/cli\"\n)\n\nvar Version string\nvar codePhrase string\nvar cr *croc.Croc\n\nfunc Run() {\n\tapp := cli.NewApp()\n\tapp.Name = \"croc\"\n\tif Version == \"\" {\n\t\tVersion = \"dev\"\n\t}\n\n\tapp.Version = Version\n\tapp.Compiled = time.Now()\n\tapp.Usage = \"easily and securely transfer stuff from one computer to another\"\n\tapp.UsageText = \"croc allows any two computers to directly and securely transfer files\"\n\t\/\/ app.ArgsUsage = \"[args and such]\"\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:        \"send\",\n\t\t\tUsage:       \"send a file\",\n\t\t\tDescription: \"send a file over the relay\",\n\t\t\tArgsUsage:   \"[filename]\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.BoolFlag{Name: \"no-compress, o\", Usage: \"disable compression\"},\n\t\t\t\tcli.BoolFlag{Name: \"no-encrypt, e\", Usage: \"disable encryption\"},\n\t\t\t\tcli.StringFlag{Name: \"code, c\", Usage: \"codephrase used to connect to relay\"},\n\t\t\t},\n\t\t\tHelpName: \"croc send\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn send(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:        \"relay\",\n\t\t\tUsage:       \"start a croc relay\",\n\t\t\tDescription: \"the croc relay will handle websocket and TCP connections\",\n\t\t\tFlags:       []cli.Flag{},\n\t\t\tHelpName:    \"croc relay\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn relay(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:        \"config\",\n\t\t\tUsage:       \"generates a config file\",\n\t\t\tDescription: \"the croc config can be used to set static parameters\",\n\t\t\tFlags:       []cli.Flag{},\n\t\t\tHelpName:    \"croc config\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn saveDefaultConfig(c)\n\t\t\t},\n\t\t},\n\t}\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{Name: \"addr\", Value: \"croc4.schollz.com\", Usage: \"address of the public relay\"},\n\t\tcli.StringFlag{Name: \"addr-ws\", Value: \"8153\", Usage: \"port of the public relay websocket server to connect\"},\n\t\tcli.StringFlag{Name: \"addr-tcp\", Value: \"8154,8155,8156,8157,8158,8159,8160,8161\", Usage: \"tcp ports of the public relay server to connect\"},\n\t\tcli.BoolFlag{Name: \"no-local\", Usage: \"disable local mode\"},\n\t\tcli.BoolFlag{Name: \"local\", Usage: \"use only local mode\"},\n\t\tcli.BoolFlag{Name: \"debug\", Usage: \"increase verbosity (a lot)\"},\n\t\tcli.BoolFlag{Name: \"yes\", Usage: \"automatically agree to all prompts\"},\n\t\tcli.BoolFlag{Name: \"stdout\", Usage: \"redirect file to stdout\"},\n\t\tcli.BoolFlag{Name: \"force-tcp\", Usage: \"force TCP\"},\n\t\tcli.BoolFlag{Name: \"force-web\", Usage: \"force websockets\"},\n\t\tcli.StringFlag{Name: \"port\", Value: \"8153\", Usage: \"port that the websocket listens on\"},\n\t\tcli.StringFlag{Name: \"tcp-port\", Value: \"8154,8155,8156,8157,8158,8159,8160,8161\", Usage: \"ports that the tcp server listens on\"},\n\t\tcli.StringFlag{Name: \"curve\", Value: \"siec\", Usage: \"specify elliptic curve to use for PAKE (p256, p384, p521, siec)\"},\n\t}\n\tapp.EnableBashCompletion = true\n\tapp.HideHelp = false\n\tapp.HideVersion = false\n\tapp.BashComplete = func(c *cli.Context) {\n\t\tfmt.Fprintf(c.App.Writer, \"send\\nreceive\\relay\")\n\t}\n\tapp.Action = func(c *cli.Context) error {\n\t\treturn receive(c)\n\t}\n\tapp.Before = func(c *cli.Context) error {\n\t\tcr = croc.Init(c.GlobalBool(\"debug\"))\n\t\tcr.Version = Version\n\t\tcr.AllowLocalDiscovery = true\n\t\tcr.Address = c.GlobalString(\"addr\")\n\t\tcr.AddressTCPPorts = strings.Split(c.GlobalString(\"addr-tcp\"), \",\")\n\t\tcr.AddressWebsocketPort = c.GlobalString(\"addr-ws\")\n\t\tcr.NoRecipientPrompt = c.GlobalBool(\"yes\")\n\t\tcr.Stdout = c.GlobalBool(\"stdout\")\n\t\tcr.LocalOnly = c.GlobalBool(\"local\")\n\t\tcr.NoLocal = c.GlobalBool(\"no-local\")\n\t\tcr.ShowText = true\n\t\tcr.RelayWebsocketPort = c.String(\"port\")\n\t\tcr.RelayTCPPorts = strings.Split(c.String(\"tcp-port\"), \",\")\n\t\tcr.CurveType = c.String(\"curve\")\n\t\tif c.GlobalBool(\"force-tcp\") {\n\t\t\tcr.ForceSend = 2\n\t\t}\n\t\tif c.GlobalBool(\"force-web\") {\n\t\t\tcr.ForceSend = 1\n\t\t}\n\t\treturn nil\n\t}\n\n\terr := app.Run(os.Args)\n\tif err != nil {\n\t\tfmt.Printf(\"\\nerror: %s\", err.Error())\n\t}\n}\n\nfunc saveDefaultConfig(c *cli.Context) error {\n\treturn croc.SaveDefaultConfig()\n}\n\nfunc send(c *cli.Context) error {\n\tstat, _ := os.Stdin.Stat()\n\tvar fname string\n\tif (stat.Mode() & os.ModeCharDevice) == 0 {\n\t\tf, err := ioutil.TempFile(\".\", \"croc-stdin-\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = io.Copy(f, os.Stdin)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = f.Close()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfname = f.Name()\n\t\tdefer func() {\n\t\t\terr = os.Remove(fname)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}()\n\t} else {\n\t\tfname = c.Args().First()\n\t}\n\tif fname == \"\" {\n\t\treturn errors.New(\"must specify file: croc send [filename]\")\n\t}\n\tcr.UseCompression = !c.Bool(\"no-compress\")\n\tcr.UseEncryption = !c.Bool(\"no-encrypt\")\n\tif c.String(\"code\") != \"\" {\n\t\tcr.Codephrase = c.String(\"code\")\n\t}\n\tcr.LoadConfig()\n\tif len(cr.Codephrase) == 0 {\n\t\t\/\/ generate code phrase\n\t\tcr.Codephrase = utils.GetRandomName()\n\t}\n\n\t\/\/ print the text\n\tfinfo, err := os.Stat(fname)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfname, _ = filepath.Abs(fname)\n\tfname = filepath.Clean(fname)\n\t_, filename := filepath.Split(fname)\n\tfileOrFolder := \"file\"\n\tfsize := finfo.Size()\n\tif finfo.IsDir() {\n\t\tfileOrFolder = \"folder\"\n\t\tfsize, err = dirSize(fname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfmt.Fprintf(os.Stderr,\n\t\t\"Sending %s %s named '%s'\\nCode is: %s\\nOn the other computer, please run:\\n\\ncroc %s\\n\\n\",\n\t\thumanize.Bytes(uint64(fsize)),\n\t\tfileOrFolder,\n\t\tfilename,\n\t\tcr.Codephrase,\n\t\tcr.Codephrase,\n\t)\n\treturn cr.Send(fname, cr.Codephrase)\n}\n\nfunc receive(c *cli.Context) error {\n\tif c.GlobalString(\"code\") != \"\" {\n\t\tcodePhrase = c.GlobalString(\"code\")\n\t}\n\tif c.Args().First() != \"\" {\n\t\tcodePhrase = c.Args().First()\n\t}\n\topenFolder := false\n\tif len(os.Args) == 1 {\n\t\t\/\/ open folder since they didn't give any arguments\n\t\topenFolder = true\n\t}\n\tif codePhrase == \"\" {\n\t\tcodePhrase = utils.GetInput(\"Enter receive code: \")\n\t}\n\terr := cr.Receive(codePhrase)\n\tif err == nil && openFolder {\n\t\tcwd, _ := os.Getwd()\n\t\topen.Run(cwd)\n\t}\n\treturn err\n}\n\nfunc relay(c *cli.Context) error {\n\treturn cr.Relay()\n}\n\nfunc dirSize(path string) (int64, error) {\n\tvar size int64\n\terr := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {\n\t\tif !info.IsDir() {\n\t\t\tsize += info.Size()\n\t\t}\n\t\treturn err\n\t})\n\treturn size, err\n}\n<commit_msg>recipient also uses codephrase<commit_after>package cli\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\thumanize \"github.com\/dustin\/go-humanize\"\n\t\"github.com\/schollz\/croc\/src\/croc\"\n\t\"github.com\/schollz\/croc\/src\/utils\"\n\t\"github.com\/skratchdot\/open-golang\/open\"\n\t\"github.com\/urfave\/cli\"\n)\n\nvar Version string\nvar cr *croc.Croc\n\nfunc Run() {\n\tapp := cli.NewApp()\n\tapp.Name = \"croc\"\n\tif Version == \"\" {\n\t\tVersion = \"dev\"\n\t}\n\n\tapp.Version = Version\n\tapp.Compiled = time.Now()\n\tapp.Usage = \"easily and securely transfer stuff from one computer to another\"\n\tapp.UsageText = \"croc allows any two computers to directly and securely transfer files\"\n\t\/\/ app.ArgsUsage = \"[args and such]\"\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName:        \"send\",\n\t\t\tUsage:       \"send a file\",\n\t\t\tDescription: \"send a file over the relay\",\n\t\t\tArgsUsage:   \"[filename]\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.BoolFlag{Name: \"no-compress, o\", Usage: \"disable compression\"},\n\t\t\t\tcli.BoolFlag{Name: \"no-encrypt, e\", Usage: \"disable encryption\"},\n\t\t\t\tcli.StringFlag{Name: \"code, c\", Usage: \"codephrase used to connect to relay\"},\n\t\t\t},\n\t\t\tHelpName: \"croc send\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn send(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:        \"relay\",\n\t\t\tUsage:       \"start a croc relay\",\n\t\t\tDescription: \"the croc relay will handle websocket and TCP connections\",\n\t\t\tFlags:       []cli.Flag{},\n\t\t\tHelpName:    \"croc relay\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn relay(c)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName:        \"config\",\n\t\t\tUsage:       \"generates a config file\",\n\t\t\tDescription: \"the croc config can be used to set static parameters\",\n\t\t\tFlags:       []cli.Flag{},\n\t\t\tHelpName:    \"croc config\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\treturn saveDefaultConfig(c)\n\t\t\t},\n\t\t},\n\t}\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{Name: \"addr\", Value: \"croc4.schollz.com\", Usage: \"address of the public relay\"},\n\t\tcli.StringFlag{Name: \"addr-ws\", Value: \"8153\", Usage: \"port of the public relay websocket server to connect\"},\n\t\tcli.StringFlag{Name: \"addr-tcp\", Value: \"8154,8155,8156,8157,8158,8159,8160,8161\", Usage: \"tcp ports of the public relay server to connect\"},\n\t\tcli.BoolFlag{Name: \"no-local\", Usage: \"disable local mode\"},\n\t\tcli.BoolFlag{Name: \"local\", Usage: \"use only local mode\"},\n\t\tcli.BoolFlag{Name: \"debug\", Usage: \"increase verbosity (a lot)\"},\n\t\tcli.BoolFlag{Name: \"yes\", Usage: \"automatically agree to all prompts\"},\n\t\tcli.BoolFlag{Name: \"stdout\", Usage: \"redirect file to stdout\"},\n\t\tcli.BoolFlag{Name: \"force-tcp\", Usage: \"force TCP\"},\n\t\tcli.BoolFlag{Name: \"force-web\", Usage: \"force websockets\"},\n\t\tcli.StringFlag{Name: \"port\", Value: \"8153\", Usage: \"port that the websocket listens on\"},\n\t\tcli.StringFlag{Name: \"tcp-port\", Value: \"8154,8155,8156,8157,8158,8159,8160,8161\", Usage: \"ports that the tcp server listens on\"},\n\t\tcli.StringFlag{Name: \"curve\", Value: \"siec\", Usage: \"specify elliptic curve to use for PAKE (p256, p384, p521, siec)\"},\n\t}\n\tapp.EnableBashCompletion = true\n\tapp.HideHelp = false\n\tapp.HideVersion = false\n\tapp.BashComplete = func(c *cli.Context) {\n\t\tfmt.Fprintf(c.App.Writer, \"send\\nreceive\\relay\")\n\t}\n\tapp.Action = func(c *cli.Context) error {\n\t\treturn receive(c)\n\t}\n\tapp.Before = func(c *cli.Context) error {\n\t\tcr = croc.Init(c.GlobalBool(\"debug\"))\n\t\tcr.Version = Version\n\t\tcr.AllowLocalDiscovery = true\n\t\tcr.Address = c.GlobalString(\"addr\")\n\t\tcr.AddressTCPPorts = strings.Split(c.GlobalString(\"addr-tcp\"), \",\")\n\t\tcr.AddressWebsocketPort = c.GlobalString(\"addr-ws\")\n\t\tcr.NoRecipientPrompt = c.GlobalBool(\"yes\")\n\t\tcr.Stdout = c.GlobalBool(\"stdout\")\n\t\tcr.LocalOnly = c.GlobalBool(\"local\")\n\t\tcr.NoLocal = c.GlobalBool(\"no-local\")\n\t\tcr.ShowText = true\n\t\tcr.RelayWebsocketPort = c.String(\"port\")\n\t\tcr.RelayTCPPorts = strings.Split(c.String(\"tcp-port\"), \",\")\n\t\tcr.CurveType = c.String(\"curve\")\n\t\tif c.GlobalBool(\"force-tcp\") {\n\t\t\tcr.ForceSend = 2\n\t\t}\n\t\tif c.GlobalBool(\"force-web\") {\n\t\t\tcr.ForceSend = 1\n\t\t}\n\t\treturn nil\n\t}\n\n\terr := app.Run(os.Args)\n\tif err != nil {\n\t\tfmt.Printf(\"\\nerror: %s\", err.Error())\n\t}\n}\n\nfunc saveDefaultConfig(c *cli.Context) error {\n\treturn croc.SaveDefaultConfig()\n}\n\nfunc send(c *cli.Context) error {\n\tstat, _ := os.Stdin.Stat()\n\tvar fname string\n\tif (stat.Mode() & os.ModeCharDevice) == 0 {\n\t\tf, err := ioutil.TempFile(\".\", \"croc-stdin-\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = io.Copy(f, os.Stdin)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = f.Close()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfname = f.Name()\n\t\tdefer func() {\n\t\t\terr = os.Remove(fname)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}()\n\t} else {\n\t\tfname = c.Args().First()\n\t}\n\tif fname == \"\" {\n\t\treturn errors.New(\"must specify file: croc send [filename]\")\n\t}\n\tcr.UseCompression = !c.Bool(\"no-compress\")\n\tcr.UseEncryption = !c.Bool(\"no-encrypt\")\n\tif c.String(\"code\") != \"\" {\n\t\tcr.Codephrase = c.String(\"code\")\n\t}\n\tcr.LoadConfig()\n\tif len(cr.Codephrase) == 0 {\n\t\t\/\/ generate code phrase\n\t\tcr.Codephrase = utils.GetRandomName()\n\t}\n\n\t\/\/ print the text\n\tfinfo, err := os.Stat(fname)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfname, _ = filepath.Abs(fname)\n\tfname = filepath.Clean(fname)\n\t_, filename := filepath.Split(fname)\n\tfileOrFolder := \"file\"\n\tfsize := finfo.Size()\n\tif finfo.IsDir() {\n\t\tfileOrFolder = \"folder\"\n\t\tfsize, err = dirSize(fname)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfmt.Fprintf(os.Stderr,\n\t\t\"Sending %s %s named '%s'\\nCode is: %s\\nOn the other computer, please run:\\n\\ncroc %s\\n\\n\",\n\t\thumanize.Bytes(uint64(fsize)),\n\t\tfileOrFolder,\n\t\tfilename,\n\t\tcr.Codephrase,\n\t\tcr.Codephrase,\n\t)\n\treturn cr.Send(fname, cr.Codephrase)\n}\n\nfunc receive(c *cli.Context) error {\n\tif c.GlobalString(\"code\") != \"\" {\n\t\tcr.Codephrase = c.GlobalString(\"code\")\n\t}\n\tif c.Args().First() != \"\" {\n\t\tcr.Codephrase = c.Args().First()\n\t}\n\tcr.LoadConfig()\n\topenFolder := false\n\tif len(os.Args) == 1 {\n\t\t\/\/ open folder since they didn't give any arguments\n\t\topenFolder = true\n\t}\n\tif cr.Codephrase == \"\" {\n\t\tcr.Codephrase = utils.GetInput(\"Enter receive code: \")\n\t}\n\terr := cr.Receive(cr.Codephrase)\n\tif err == nil && openFolder {\n\t\tcwd, _ := os.Getwd()\n\t\topen.Run(cwd)\n\t}\n\treturn err\n}\n\nfunc relay(c *cli.Context) error {\n\treturn cr.Relay()\n}\n\nfunc dirSize(path string) (int64, error) {\n\tvar size int64\n\terr := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {\n\t\tif !info.IsDir() {\n\t\t\tsize += info.Size()\n\t\t}\n\t\treturn err\n\t})\n\treturn size, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright IBM Corp. 2016 All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\t\t http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\n\/\/WARNING - this chaincode's ID is hard-coded in chaincode_example04 to illustrate one way of\n\/\/calling chaincode from a chaincode. If this example is modified, chaincode_example04.go has\n\/\/to be modified as well with the new ID of chaincode_example02.\n\/\/chaincode_example05 show's how chaincode ID can be passed in as a parameter instead of\n\/\/hard-coding.\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com\/hyperledger\/fabric\/core\/chaincode\/shim\"\n)\n\n\/\/ SimpleChaincode example simple Chaincode implementation\ntype SimpleChaincode struct {\n}\n\nfunc (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tvar A, B string    \/\/ Entities\n\tvar Aval, Bval int \/\/ Asset holdings\n\tvar err error\n\n\tif len(args) != 4 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 4\")\n\t}\n\n\t\/\/ Initialize the chaincode\n\tA = args[0]\n\tAval, err = strconv.Atoi(args[1])\n\tif err != nil {\n\t\treturn nil, errors.New(\"Expecting integer value for asset holding\")\n\t}\n\tB = args[2]\n\tBval, err = strconv.Atoi(args[3])\n\tif err != nil {\n\t\treturn nil, errors.New(\"Expecting integer value for asset holding\")\n\t}\n\tfmt.Printf(\"Aval = %d, Bval = %d\\n\", Aval, Bval)\n\n\t\/\/ Write the state to the ledger\n\terr = stub.PutState(A, []byte(strconv.Itoa(Aval)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = stub.PutState(B, []byte(strconv.Itoa(Bval)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n\n\/\/ Transaction makes payment of X units from A to B\nfunc (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tif function == \"delete\" {\n\t\t\/\/ Deletes an entity from its state\n\t\treturn t.delete(stub, args)\n\t}\n\n\tvar A, B string    \/\/ Entities\n\tvar Aval, Bval int \/\/ Asset holdings\n\tvar X int          \/\/ Transaction value\n\tvar err error\n\n\tif len(args) != 3 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 3\")\n\t}\n\n\tA = args[0]\n\tB = args[1]\n\n\t\/\/ Get the state from the ledger\n\t\/\/ TODO: will be nice to have a GetAllState call to ledger\n\tAvalbytes, err := stub.GetState(A)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to get state\")\n\t}\n\tif Avalbytes == nil {\n\t\treturn nil, errors.New(\"Entity not found\")\n\t}\n\tAval, _ = strconv.Atoi(string(Avalbytes))\n\n\tBvalbytes, err := stub.GetState(B)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to get state\")\n\t}\n\tif Bvalbytes == nil {\n\t\treturn nil, errors.New(\"Entity not found\")\n\t}\n\tBval, _ = strconv.Atoi(string(Bvalbytes))\n\n\t\/\/ Perform the execution\n\tX, err = strconv.Atoi(args[2])\n\tif err != nil {\n\t\treturn nil, errors.New(\"Invalid transaction amount, expecting a integer value\")\n\t}\n\tAval = Aval - X\n\tBval = Bval + X\n\tfmt.Printf(\"Aval = %d, Bval = %d\\n\", Aval, Bval)\n\n\t\/\/ Write the state back to the ledger\n\terr = stub.PutState(A, []byte(strconv.Itoa(Aval)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = stub.PutState(B, []byte(strconv.Itoa(Bval)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n\n\/\/ Deletes an entity from state\nfunc (t *SimpleChaincode) delete(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\tA := args[0]\n\n\t\/\/ Delete the key from the state in ledger\n\terr := stub.DelState(A)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to delete state\")\n\t}\n\n\treturn nil, nil\n}\n\n\/\/ Query callback representing the query of a chaincode\nfunc (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tif function != \"query\" {\n\t\treturn nil, errors.New(\"Invalid query function name. Expecting \\\"query\\\"\")\n\t}\n\tvar A string \/\/ Entities\n\tvar err error\n\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting name of the person to query\")\n\t}\n\n\tA = args[0]\n\n\t\/\/ Get the state from the ledger\n\tAvalbytes, err := stub.GetState(A)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to get state for \" + A + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tif Avalbytes == nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Nil amount for \" + A + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tjsonResp := \"{\\\"Name\\\":\\\"\" + A + \"\\\",\\\"Amount\\\":\\\"\" + string(Avalbytes) + \"\\\"}\"\n\tfmt.Printf(\"Query Response:%s\\n\", jsonResp)\n\treturn Avalbytes, nil\n}\n\nfunc main() {\n\terr := shim.Start(new(SimpleChaincode))\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting Simple chaincode: %s\", err)\n\t}\n}\n<commit_msg>Update chaincode_example02.go<commit_after>\/*\nCopyright IBM Corp. 2016 All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\t\t http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\n\/\/WARNING - this chaincode's ID is hard-coded in chaincode_example04 to illustrate one way of\n\/\/calling chaincode from a chaincode. If this example is modified, chaincode_example04.go has\n\/\/to be modified as well with the new ID of chaincode_example02.\n\/\/chaincode_example05 show's how chaincode ID can be passed in as a parameter instead of\n\/\/hard-coding.\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com\/hyperledger\/fabric\/core\/chaincode\/shim\"\n)\n\n\/\/ SimpleChaincode example simple Chaincode implementation\ntype SimpleChaincode struct {\n}\n\nfunc (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n\tvar A, B string    \/\/ Entities\n\tvar Aval, Bval int \/\/ Asset holdings\n\tvar err error\n\n\tif len(args) != 4 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 4\")\n\t}\n\n\t\/\/ Initialize the chaincode\n\tA = args[0]\n\tAval, err = strconv.Atoi(args[1])\n\tif err != nil {\n\t\treturn nil, errors.New(\"Expecting integer value for asset holding\")\n\t}\n\tB = args[2]\n\tBval, err = strconv.Atoi(args[3])\n\tif err != nil {\n\t\treturn nil, errors.New(\"Expecting integer value for asset holding\")\n\t}\n\tfmt.Printf(\"Aval = %d, Bval = %d\\n\", Aval, Bval)\n\n\t\/\/ Write the state to the ledger\n\terr = stub.PutState(A, []byte(strconv.Itoa(Aval)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = stub.PutState(B, []byte(strconv.Itoa(Bval)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n\n\/\/ Transaction makes payment of X units from A to B\nfunc (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n\tif function == \"delete\" {\n\t\t\/\/ Deletes an entity from its state\n\t\treturn t.delete(stub, args)\n\t}\n\n\tvar A, B string    \/\/ Entities\n\tvar Aval, Bval int \/\/ Asset holdings\n\tvar X int          \/\/ Transaction value\n\tvar err error\n\n\tif len(args) != 3 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 3\")\n\t}\n\n\tA = args[0]\n\tB = args[1]\n\n\t\/\/ Get the state from the ledger\n\t\/\/ TODO: will be nice to have a GetAllState call to ledger\n\tAvalbytes, err := stub.GetState(A)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to get state\")\n\t}\n\tif Avalbytes == nil {\n\t\treturn nil, errors.New(\"Entity not found\")\n\t}\n\tAval, _ = strconv.Atoi(string(Avalbytes))\n\n\tBvalbytes, err := stub.GetState(B)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to get state\")\n\t}\n\tif Bvalbytes == nil {\n\t\treturn nil, errors.New(\"Entity not found\")\n\t}\n\tBval, _ = strconv.Atoi(string(Bvalbytes))\n\n\t\/\/ Perform the execution\n\tX, err = strconv.Atoi(args[2])\n\tif err != nil {\n\t\treturn nil, errors.New(\"Invalid transaction amount, expecting a integer value\")\n\t}\n\tAval = Aval - X\n\tBval = Bval + X\n\tfmt.Printf(\"Aval = %d, Bval = %d\\n\", Aval, Bval)\n\n\t\/\/ Write the state back to the ledger\n\terr = stub.PutState(A, []byte(strconv.Itoa(Aval)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = stub.PutState(B, []byte(strconv.Itoa(Bval)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n\n\/\/ Deletes an entity from state\nfunc (t *SimpleChaincode) delete(stub *shim.ChaincodeStub, args []string) ([]byte, error) {\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 1\")\n\t}\n\n\tA := args[0]\n\n\t\/\/ Delete the key from the state in ledger\n\terr := stub.DelState(A)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Failed to delete state\")\n\t}\n\n\treturn nil, nil\n}\n\n\/\/ Query callback representing the query of a chaincode\nfunc (t *SimpleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n\tif function != \"query\" {\n\t\treturn nil, errors.New(\"Invalid query function name. Expecting \\\"query\\\"\")\n\t}\n\tvar A string \/\/ Entities\n\tvar err error\n\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting name of the person to query\")\n\t}\n\n\tA = args[0]\n\n\t\/\/ Get the state from the ledger\n\tAvalbytes, err := stub.GetState(A)\n\tif err != nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Failed to get state for \" + A + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tif Avalbytes == nil {\n\t\tjsonResp := \"{\\\"Error\\\":\\\"Nil amount for \" + A + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\tjsonResp := \"{\\\"Name\\\":\\\"\" + A + \"\\\",\\\"Amount\\\":\\\"\" + string(Avalbytes) + \"\\\"}\"\n\tfmt.Printf(\"Query Response:%s\\n\", jsonResp)\n\treturn Avalbytes, nil\n}\n\nfunc main() {\n\terr := shim.Start(new(SimpleChaincode))\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting Simple chaincode: %s\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2014-2015 Conformal Systems LLC <info@conformal.com>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/btcsuite\/btcd\/btcjson\/v2\/btcjson\"\n\t\"github.com\/btcsuite\/btcd\/wire\"\n\trpc \"github.com\/btcsuite\/btcrpcclient\"\n\t\"github.com\/btcsuite\/btcutil\"\n)\n\n\/\/ minFee is the minimum tx fee that can be paid\nconst minFee btcutil.Amount = 1e4 \/\/ 0.0001 BTC\n\n\/\/ utxoQueue is the queue of utxos belonging to a actor\n\/\/ utxos are queued after a block is received and are dispatched\n\/\/ to their respective owner from com.poolUtxos\n\/\/ they are dequeued from simulateTx and splitUtxos\ntype utxoQueue struct {\n\tutxos   []*TxOut\n\tenqueue chan *TxOut\n\tdequeue chan *TxOut\n}\n\n\/\/ Actor describes an actor on the simulation network.  Each actor runs\n\/\/ independantly without external input to decide it's behavior.\ntype Actor struct {\n\t*Node\n\tquit             chan struct{}\n\twg               sync.WaitGroup\n\townedAddresses   []btcutil.Address\n\tutxoQueue        *utxoQueue\n\tminingAddr       chan btcutil.Address\n\twalletPassphrase string\n}\n\n\/\/ TxOut is a valid tx output that can be used to generate transactions\ntype TxOut struct {\n\tOutPoint *wire.OutPoint\n\tAmount   btcutil.Amount\n}\n\n\/\/ NewActor creates a new actor which runs its own wallet process connecting\n\/\/ to the btcd node server specified by node, and listening for simulator\n\/\/ websocket connections on the specified port.\nfunc NewActor(node *Node, port uint16) (*Actor, error) {\n\t\/\/ Please don't run this as root.\n\tif port < 1024 {\n\t\treturn nil, errors.New(\"invalid actor port\")\n\t}\n\n\t\/\/ Set btcwallet node args\n\targs, err := newBtcwalletArgs(port, node.Args.(*btcdArgs))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogFile, err := getLogFile(args.prefix)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot get log file, logging disabled: %v\", err)\n\t}\n\tbtcwallet, err := NewNodeFromArgs(args, nil, logFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ta := Actor{\n\t\tNode:             btcwallet,\n\t\tquit:             make(chan struct{}),\n\t\townedAddresses:   make([]btcutil.Address, *maxAddresses),\n\t\tminingAddr:       make(chan btcutil.Address),\n\t\twalletPassphrase: \"password\",\n\t\tutxoQueue: &utxoQueue{\n\t\t\tenqueue: make(chan *TxOut),\n\t\t\tdequeue: make(chan *TxOut),\n\t\t},\n\t}\n\treturn &a, nil\n}\n\n\/\/ Start creates the command to execute a wallet process and starts the\n\/\/ command in the background, attaching the command's stderr and stdout\n\/\/ to the passed writers. Nil writers may be used to discard output.\n\/\/\n\/\/ In addition to starting the wallet process, this runs goroutines to\n\/\/ handle wallet notifications and requests the wallet process to create\n\/\/ an intial encrypted wallet, so that it can actually send and receive BTC.\n\/\/\n\/\/ If the RPC client connection cannot be established or wallet cannot\n\/\/ be created, the wallet process is killed and the actor directory\n\/\/ removed.\nfunc (a *Actor) Start(stderr, stdout io.Writer, com *Communication) error {\n\tconnected := make(chan struct{})\n\tconst timeoutSecs int64 = 3600 * 24\n\n\tif err := a.Node.Start(); err != nil {\n\t\ta.Shutdown()\n\t\tcom.errChan <- struct{}{}\n\t\treturn err\n\t}\n\n\tntfnHandlers := &rpc.NotificationHandlers{\n\t\tOnClientConnected: func() {\n\t\t\tconnected <- struct{}{}\n\t\t},\n\t}\n\ta.handlers = ntfnHandlers\n\n\tif err := a.Connect(); err != nil {\n\t\ta.Shutdown()\n\t\tcom.errChan <- struct{}{}\n\t\treturn err\n\t}\n\n\t\/\/ Wait for btcd to connect\n\t<-connected\n\n\t\/\/ Wait for wallet sync\n\tfor i := 0; i < *maxConnRetries; i++ {\n\t\tif _, err := a.client.GetBalance(\"\"); err != nil {\n\t\t\ttime.Sleep(time.Duration(i) * 50 * time.Millisecond)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\t\/\/ Create wallet addresses and unlock wallet.\n\tlog.Printf(\"%s: Creating wallet addresses...\", a)\n\tfor i := range a.ownedAddresses {\n\t\tfmt.Printf(\"\\r%d\/%d\", i+1, len(a.ownedAddresses))\n\t\taddr, err := a.client.GetNewAddress()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%s: Cannot create address #%d\", a, i+1)\n\t\t\tcom.errChan <- struct{}{}\n\t\t\treturn err\n\t\t}\n\t\ta.ownedAddresses[i] = addr\n\t}\n\tfmt.Printf(\"\\n\")\n\n\tif err := a.client.WalletPassphrase(a.walletPassphrase, timeoutSecs); err != nil {\n\t\tlog.Printf(\"%s: Cannot unlock wallet: %v\", a, err)\n\t\tcom.errChan <- struct{}{}\n\t\treturn err\n\t}\n\n\t\/\/ Send a random address that will be used by the cpu miner.\n\ta.miningAddr <- a.ownedAddresses[rand.Int()%len(a.ownedAddresses)]\n\n\t\/\/ Start a goroutine that queues up a set of utxos belonging to this\n\t\/\/ actor. The utxos are sent from com.poolUtxos which in turn receives\n\t\/\/ block notifications from sim.go\n\ta.wg.Add(1)\n\tgo a.queueUtxos()\n\n\t\/\/ Start a goroutine to simulate transactions.\n\ta.wg.Add(1)\n\tgo a.simulateTx(com.downstream, com.txpool)\n\n\t\/\/ Start a goroutine to split utxos\n\ta.wg.Add(1)\n\tgo a.splitUtxos(com.split, com.txpool)\n\n\treturn nil\n}\n\n\/\/ simulateTx runs as a goroutine and simulates transactions between actors\n\/\/\n\/\/ It receives a random address downstream, dequeues a utxo, sends a raw\n\/\/ transaction to the address using the utxo as input\nfunc (a *Actor) simulateTx(downstream <-chan btcutil.Address, txpool chan<- struct{}) {\n\tdefer a.wg.Done()\n\n\tfor {\n\t\tselect {\n\t\tcase utxo := <-a.utxoQueue.dequeue:\n\t\t\tselect {\n\t\t\tcase addr := <-downstream:\n\t\t\t\t\/\/ Create a raw transaction\n\t\t\t\tinputs := []btcjson.TransactionInput{{\n\t\t\t\t\tTxid: utxo.OutPoint.Hash.String(),\n\t\t\t\t\tVout: utxo.OutPoint.Index,\n\t\t\t\t}}\n\n\t\t\t\t\/\/ Provide a fees of minFee to ensure the tx gets mined\n\t\t\t\t\/\/ the utxo amount is guaranteed to be > maxSplit*minFee\n\t\t\t\tamt := utxo.Amount - minFee\n\t\t\t\tamounts := map[btcutil.Address]btcutil.Amount{\n\t\t\t\t\taddr: amt,\n\t\t\t\t}\n\n\t\t\t\terr := a.sendRawTransaction(inputs, amounts)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"%s: Error sending raw transaction: %v\", a, err)\n\t\t\t\t\tselect {\n\t\t\t\t\tcase txpool <- struct{}{}:\n\t\t\t\t\tcase <-a.quit:\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\tcase <-a.quit:\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-a.quit:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ splitUtxos runs as a goroutine and builds up a large set of utxos that\n\/\/ can be used to simulate large tx\/block ratios\n\/\/\n\/\/ It receives a 'split' which is int that indicates the number of resultant utxos\n\/\/ the tx is sent to addresses from the same actor since we're only interested in\n\/\/ building up the utxo set\nfunc (a *Actor) splitUtxos(split <-chan int, txpool chan<- struct{}) {\n\tdefer a.wg.Done()\n\n\tfor {\n\t\tselect {\n\t\tcase utxo := <-a.utxoQueue.dequeue:\n\t\t\tselect {\n\t\t\tcase split := <-split:\n\t\t\t\t\/\/ Create a raw transaction\n\t\t\t\tinputs := []btcjson.TransactionInput{{\n\t\t\t\t\tTxid: utxo.OutPoint.Hash.String(),\n\t\t\t\t\tVout: utxo.OutPoint.Index,\n\t\t\t\t}}\n\n\t\t\t\t\/\/ Provide a fees of minFee to ensure the tx gets mined\n\t\t\t\t\/\/ the utxo amount is guaranteed to be > maxSplit*minFee\n\t\t\t\tamt := utxo.Amount - minFee\n\t\t\t\tamounts := map[btcutil.Address]btcutil.Amount{}\n\n\t\t\t\t\/\/ Create a output of random amount and sent it\n\t\t\t\t\/\/ to a random address from the address space\n\t\t\t\t\/\/ total number of outputs is split+1, taking into\n\t\t\t\t\/\/ account this utxo which is consumed in the process\n\n\t\t\t\t\/\/ set a rand start index for getting different random addrs\n\t\t\t\trandomIndex := rand.Int() % len(a.ownedAddresses)\n\t\t\t\tfor i := 0; i <= split; i++ {\n\t\t\t\t\tvar to btcutil.Address\n\t\t\t\t\tvar change btcutil.Amount\n\t\t\t\t\t\/\/ pick a random address\n\t\t\t\t\tif randomIndex+i < len(a.ownedAddresses) {\n\t\t\t\t\t\tto = a.ownedAddresses[randomIndex+i]\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ wrap around incase of an overflow\n\t\t\t\t\t\tto = a.ownedAddresses[randomIndex+i-len(a.ownedAddresses)]\n\t\t\t\t\t}\n\t\t\t\t\tif i == split {\n\t\t\t\t\t\t\/\/ last split, so just set the change\n\t\t\t\t\t\tchange = amt\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ pick a random change amount which is less than amt\n\t\t\t\t\t\t\/\/ but have a lower bound at minFee\n\t\t\t\t\t\tchange = btcutil.Amount(rand.Int63n(int64(amt) \/ 2))\n\t\t\t\t\t\tif change < minFee {\n\t\t\t\t\t\t\tchange = minFee\n\t\t\t\t\t\t}\n\t\t\t\t\t\tamt -= change\n\t\t\t\t\t}\n\t\t\t\t\tamounts[to] = change\n\t\t\t\t}\n\n\t\t\t\terr := a.sendRawTransaction(inputs, amounts)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"%s: Error sending raw transaction: %v\", a, err)\n\t\t\t\t\tselect {\n\t\t\t\t\tcase txpool <- struct{}{}:\n\t\t\t\t\tcase <-a.quit:\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\tcase <-a.quit:\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-a.quit:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ sendRawTransaction creates a raw transaction, signs it and sends it\nfunc (a *Actor) sendRawTransaction(inputs []btcjson.TransactionInput, amounts map[btcutil.Address]btcutil.Amount) error {\n\tmsgTx, err := a.client.CreateRawTransaction(inputs, amounts)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ sign it\n\tmsgTx, ok, err := a.client.SignRawTransaction(msgTx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !ok {\n\t\treturn err\n\t}\n\t\/\/ and finally send it.\n\tif _, err := a.client.SendRawTransaction(msgTx, false); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ queueUtxos receives utxos belonging to this actor and queues them up\nfunc (a *Actor) queueUtxos() {\n\tdefer a.wg.Done()\n\n\tenqueue := a.utxoQueue.enqueue\n\tvar dequeue chan *TxOut\n\tvar next *TxOut\nout:\n\tfor {\n\t\tselect {\n\t\tcase n, ok := <-enqueue:\n\t\t\tif !ok {\n\t\t\t\t\/\/ If no utxos are queued for handling,\n\t\t\t\t\/\/ the queue is finished.\n\t\t\t\tif len(a.utxoQueue.utxos) == 0 {\n\t\t\t\t\tbreak out\n\t\t\t\t}\n\t\t\t\t\/\/ nil channel so no more reads can occur.\n\t\t\t\tenqueue = nil\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(a.utxoQueue.utxos) == 0 {\n\t\t\t\tnext = n\n\t\t\t\tdequeue = a.utxoQueue.dequeue\n\t\t\t}\n\t\t\ta.utxoQueue.utxos = append(a.utxoQueue.utxos, n)\n\t\tcase dequeue <- next:\n\t\t\ta.utxoQueue.utxos[0] = nil\n\t\t\ta.utxoQueue.utxos = a.utxoQueue.utxos[1:]\n\t\t\tif len(a.utxoQueue.utxos) != 0 {\n\t\t\t\tnext = a.utxoQueue.utxos[0]\n\t\t\t} else {\n\t\t\t\t\/\/ If no more utxos can be enqueued, the\n\t\t\t\t\/\/ queue is finished.\n\t\t\t\tif enqueue == nil {\n\t\t\t\t\tbreak out\n\t\t\t\t}\n\t\t\t\tdequeue = nil\n\t\t\t}\n\t\tcase <-a.quit:\n\t\t\tbreak out\n\t\t}\n\t}\n\tclose(a.utxoQueue.dequeue)\n}\n\n\/\/ Shutdown performs a shutdown down the actor by first signalling\n\/\/ all goroutines to stop, waiting for them to stop and them cleaning up\nfunc (a *Actor) Shutdown() {\n\tselect {\n\tcase <-a.quit:\n\tdefault:\n\t\tclose(a.quit)\n\t\ta.WaitForShutdown()\n\t\ta.Node.Shutdown()\n\t}\n}\n\n\/\/ WaitForShutdown waits until every actor goroutine has returned\nfunc (a *Actor) WaitForShutdown() {\n\ta.wg.Wait()\n}\n<commit_msg>Update btcjson path import paths to new location.<commit_after>\/*\n * Copyright (c) 2014-2015 Conformal Systems LLC <info@conformal.com>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/btcsuite\/btcd\/btcjson\"\n\t\"github.com\/btcsuite\/btcd\/wire\"\n\trpc \"github.com\/btcsuite\/btcrpcclient\"\n\t\"github.com\/btcsuite\/btcutil\"\n)\n\n\/\/ minFee is the minimum tx fee that can be paid\nconst minFee btcutil.Amount = 1e4 \/\/ 0.0001 BTC\n\n\/\/ utxoQueue is the queue of utxos belonging to a actor\n\/\/ utxos are queued after a block is received and are dispatched\n\/\/ to their respective owner from com.poolUtxos\n\/\/ they are dequeued from simulateTx and splitUtxos\ntype utxoQueue struct {\n\tutxos   []*TxOut\n\tenqueue chan *TxOut\n\tdequeue chan *TxOut\n}\n\n\/\/ Actor describes an actor on the simulation network.  Each actor runs\n\/\/ independantly without external input to decide it's behavior.\ntype Actor struct {\n\t*Node\n\tquit             chan struct{}\n\twg               sync.WaitGroup\n\townedAddresses   []btcutil.Address\n\tutxoQueue        *utxoQueue\n\tminingAddr       chan btcutil.Address\n\twalletPassphrase string\n}\n\n\/\/ TxOut is a valid tx output that can be used to generate transactions\ntype TxOut struct {\n\tOutPoint *wire.OutPoint\n\tAmount   btcutil.Amount\n}\n\n\/\/ NewActor creates a new actor which runs its own wallet process connecting\n\/\/ to the btcd node server specified by node, and listening for simulator\n\/\/ websocket connections on the specified port.\nfunc NewActor(node *Node, port uint16) (*Actor, error) {\n\t\/\/ Please don't run this as root.\n\tif port < 1024 {\n\t\treturn nil, errors.New(\"invalid actor port\")\n\t}\n\n\t\/\/ Set btcwallet node args\n\targs, err := newBtcwalletArgs(port, node.Args.(*btcdArgs))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogFile, err := getLogFile(args.prefix)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot get log file, logging disabled: %v\", err)\n\t}\n\tbtcwallet, err := NewNodeFromArgs(args, nil, logFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ta := Actor{\n\t\tNode:             btcwallet,\n\t\tquit:             make(chan struct{}),\n\t\townedAddresses:   make([]btcutil.Address, *maxAddresses),\n\t\tminingAddr:       make(chan btcutil.Address),\n\t\twalletPassphrase: \"password\",\n\t\tutxoQueue: &utxoQueue{\n\t\t\tenqueue: make(chan *TxOut),\n\t\t\tdequeue: make(chan *TxOut),\n\t\t},\n\t}\n\treturn &a, nil\n}\n\n\/\/ Start creates the command to execute a wallet process and starts the\n\/\/ command in the background, attaching the command's stderr and stdout\n\/\/ to the passed writers. Nil writers may be used to discard output.\n\/\/\n\/\/ In addition to starting the wallet process, this runs goroutines to\n\/\/ handle wallet notifications and requests the wallet process to create\n\/\/ an intial encrypted wallet, so that it can actually send and receive BTC.\n\/\/\n\/\/ If the RPC client connection cannot be established or wallet cannot\n\/\/ be created, the wallet process is killed and the actor directory\n\/\/ removed.\nfunc (a *Actor) Start(stderr, stdout io.Writer, com *Communication) error {\n\tconnected := make(chan struct{})\n\tconst timeoutSecs int64 = 3600 * 24\n\n\tif err := a.Node.Start(); err != nil {\n\t\ta.Shutdown()\n\t\tcom.errChan <- struct{}{}\n\t\treturn err\n\t}\n\n\tntfnHandlers := &rpc.NotificationHandlers{\n\t\tOnClientConnected: func() {\n\t\t\tconnected <- struct{}{}\n\t\t},\n\t}\n\ta.handlers = ntfnHandlers\n\n\tif err := a.Connect(); err != nil {\n\t\ta.Shutdown()\n\t\tcom.errChan <- struct{}{}\n\t\treturn err\n\t}\n\n\t\/\/ Wait for btcd to connect\n\t<-connected\n\n\t\/\/ Wait for wallet sync\n\tfor i := 0; i < *maxConnRetries; i++ {\n\t\tif _, err := a.client.GetBalance(\"\"); err != nil {\n\t\t\ttime.Sleep(time.Duration(i) * 50 * time.Millisecond)\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\n\t\/\/ Create wallet addresses and unlock wallet.\n\tlog.Printf(\"%s: Creating wallet addresses...\", a)\n\tfor i := range a.ownedAddresses {\n\t\tfmt.Printf(\"\\r%d\/%d\", i+1, len(a.ownedAddresses))\n\t\taddr, err := a.client.GetNewAddress()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"%s: Cannot create address #%d\", a, i+1)\n\t\t\tcom.errChan <- struct{}{}\n\t\t\treturn err\n\t\t}\n\t\ta.ownedAddresses[i] = addr\n\t}\n\tfmt.Printf(\"\\n\")\n\n\tif err := a.client.WalletPassphrase(a.walletPassphrase, timeoutSecs); err != nil {\n\t\tlog.Printf(\"%s: Cannot unlock wallet: %v\", a, err)\n\t\tcom.errChan <- struct{}{}\n\t\treturn err\n\t}\n\n\t\/\/ Send a random address that will be used by the cpu miner.\n\ta.miningAddr <- a.ownedAddresses[rand.Int()%len(a.ownedAddresses)]\n\n\t\/\/ Start a goroutine that queues up a set of utxos belonging to this\n\t\/\/ actor. The utxos are sent from com.poolUtxos which in turn receives\n\t\/\/ block notifications from sim.go\n\ta.wg.Add(1)\n\tgo a.queueUtxos()\n\n\t\/\/ Start a goroutine to simulate transactions.\n\ta.wg.Add(1)\n\tgo a.simulateTx(com.downstream, com.txpool)\n\n\t\/\/ Start a goroutine to split utxos\n\ta.wg.Add(1)\n\tgo a.splitUtxos(com.split, com.txpool)\n\n\treturn nil\n}\n\n\/\/ simulateTx runs as a goroutine and simulates transactions between actors\n\/\/\n\/\/ It receives a random address downstream, dequeues a utxo, sends a raw\n\/\/ transaction to the address using the utxo as input\nfunc (a *Actor) simulateTx(downstream <-chan btcutil.Address, txpool chan<- struct{}) {\n\tdefer a.wg.Done()\n\n\tfor {\n\t\tselect {\n\t\tcase utxo := <-a.utxoQueue.dequeue:\n\t\t\tselect {\n\t\t\tcase addr := <-downstream:\n\t\t\t\t\/\/ Create a raw transaction\n\t\t\t\tinputs := []btcjson.TransactionInput{{\n\t\t\t\t\tTxid: utxo.OutPoint.Hash.String(),\n\t\t\t\t\tVout: utxo.OutPoint.Index,\n\t\t\t\t}}\n\n\t\t\t\t\/\/ Provide a fees of minFee to ensure the tx gets mined\n\t\t\t\t\/\/ the utxo amount is guaranteed to be > maxSplit*minFee\n\t\t\t\tamt := utxo.Amount - minFee\n\t\t\t\tamounts := map[btcutil.Address]btcutil.Amount{\n\t\t\t\t\taddr: amt,\n\t\t\t\t}\n\n\t\t\t\terr := a.sendRawTransaction(inputs, amounts)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"%s: Error sending raw transaction: %v\", a, err)\n\t\t\t\t\tselect {\n\t\t\t\t\tcase txpool <- struct{}{}:\n\t\t\t\t\tcase <-a.quit:\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\tcase <-a.quit:\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-a.quit:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ splitUtxos runs as a goroutine and builds up a large set of utxos that\n\/\/ can be used to simulate large tx\/block ratios\n\/\/\n\/\/ It receives a 'split' which is int that indicates the number of resultant utxos\n\/\/ the tx is sent to addresses from the same actor since we're only interested in\n\/\/ building up the utxo set\nfunc (a *Actor) splitUtxos(split <-chan int, txpool chan<- struct{}) {\n\tdefer a.wg.Done()\n\n\tfor {\n\t\tselect {\n\t\tcase utxo := <-a.utxoQueue.dequeue:\n\t\t\tselect {\n\t\t\tcase split := <-split:\n\t\t\t\t\/\/ Create a raw transaction\n\t\t\t\tinputs := []btcjson.TransactionInput{{\n\t\t\t\t\tTxid: utxo.OutPoint.Hash.String(),\n\t\t\t\t\tVout: utxo.OutPoint.Index,\n\t\t\t\t}}\n\n\t\t\t\t\/\/ Provide a fees of minFee to ensure the tx gets mined\n\t\t\t\t\/\/ the utxo amount is guaranteed to be > maxSplit*minFee\n\t\t\t\tamt := utxo.Amount - minFee\n\t\t\t\tamounts := map[btcutil.Address]btcutil.Amount{}\n\n\t\t\t\t\/\/ Create a output of random amount and sent it\n\t\t\t\t\/\/ to a random address from the address space\n\t\t\t\t\/\/ total number of outputs is split+1, taking into\n\t\t\t\t\/\/ account this utxo which is consumed in the process\n\n\t\t\t\t\/\/ set a rand start index for getting different random addrs\n\t\t\t\trandomIndex := rand.Int() % len(a.ownedAddresses)\n\t\t\t\tfor i := 0; i <= split; i++ {\n\t\t\t\t\tvar to btcutil.Address\n\t\t\t\t\tvar change btcutil.Amount\n\t\t\t\t\t\/\/ pick a random address\n\t\t\t\t\tif randomIndex+i < len(a.ownedAddresses) {\n\t\t\t\t\t\tto = a.ownedAddresses[randomIndex+i]\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ wrap around incase of an overflow\n\t\t\t\t\t\tto = a.ownedAddresses[randomIndex+i-len(a.ownedAddresses)]\n\t\t\t\t\t}\n\t\t\t\t\tif i == split {\n\t\t\t\t\t\t\/\/ last split, so just set the change\n\t\t\t\t\t\tchange = amt\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/\/ pick a random change amount which is less than amt\n\t\t\t\t\t\t\/\/ but have a lower bound at minFee\n\t\t\t\t\t\tchange = btcutil.Amount(rand.Int63n(int64(amt) \/ 2))\n\t\t\t\t\t\tif change < minFee {\n\t\t\t\t\t\t\tchange = minFee\n\t\t\t\t\t\t}\n\t\t\t\t\t\tamt -= change\n\t\t\t\t\t}\n\t\t\t\t\tamounts[to] = change\n\t\t\t\t}\n\n\t\t\t\terr := a.sendRawTransaction(inputs, amounts)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"%s: Error sending raw transaction: %v\", a, err)\n\t\t\t\t\tselect {\n\t\t\t\t\tcase txpool <- struct{}{}:\n\t\t\t\t\tcase <-a.quit:\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\tcase <-a.quit:\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-a.quit:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ sendRawTransaction creates a raw transaction, signs it and sends it\nfunc (a *Actor) sendRawTransaction(inputs []btcjson.TransactionInput, amounts map[btcutil.Address]btcutil.Amount) error {\n\tmsgTx, err := a.client.CreateRawTransaction(inputs, amounts)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ sign it\n\tmsgTx, ok, err := a.client.SignRawTransaction(msgTx)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !ok {\n\t\treturn err\n\t}\n\t\/\/ and finally send it.\n\tif _, err := a.client.SendRawTransaction(msgTx, false); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ queueUtxos receives utxos belonging to this actor and queues them up\nfunc (a *Actor) queueUtxos() {\n\tdefer a.wg.Done()\n\n\tenqueue := a.utxoQueue.enqueue\n\tvar dequeue chan *TxOut\n\tvar next *TxOut\nout:\n\tfor {\n\t\tselect {\n\t\tcase n, ok := <-enqueue:\n\t\t\tif !ok {\n\t\t\t\t\/\/ If no utxos are queued for handling,\n\t\t\t\t\/\/ the queue is finished.\n\t\t\t\tif len(a.utxoQueue.utxos) == 0 {\n\t\t\t\t\tbreak out\n\t\t\t\t}\n\t\t\t\t\/\/ nil channel so no more reads can occur.\n\t\t\t\tenqueue = nil\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(a.utxoQueue.utxos) == 0 {\n\t\t\t\tnext = n\n\t\t\t\tdequeue = a.utxoQueue.dequeue\n\t\t\t}\n\t\t\ta.utxoQueue.utxos = append(a.utxoQueue.utxos, n)\n\t\tcase dequeue <- next:\n\t\t\ta.utxoQueue.utxos[0] = nil\n\t\t\ta.utxoQueue.utxos = a.utxoQueue.utxos[1:]\n\t\t\tif len(a.utxoQueue.utxos) != 0 {\n\t\t\t\tnext = a.utxoQueue.utxos[0]\n\t\t\t} else {\n\t\t\t\t\/\/ If no more utxos can be enqueued, the\n\t\t\t\t\/\/ queue is finished.\n\t\t\t\tif enqueue == nil {\n\t\t\t\t\tbreak out\n\t\t\t\t}\n\t\t\t\tdequeue = nil\n\t\t\t}\n\t\tcase <-a.quit:\n\t\t\tbreak out\n\t\t}\n\t}\n\tclose(a.utxoQueue.dequeue)\n}\n\n\/\/ Shutdown performs a shutdown down the actor by first signalling\n\/\/ all goroutines to stop, waiting for them to stop and them cleaning up\nfunc (a *Actor) Shutdown() {\n\tselect {\n\tcase <-a.quit:\n\tdefault:\n\t\tclose(a.quit)\n\t\ta.WaitForShutdown()\n\t\ta.Node.Shutdown()\n\t}\n}\n\n\/\/ WaitForShutdown waits until every actor goroutine has returned\nfunc (a *Actor) WaitForShutdown() {\n\ta.wg.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>package adodb\n\nimport (\n\t\"errors\"\n\t\"database\/sql\"\n\t\"database\/sql\/driver\"\n\t\"fmt\"\n\t\"github.com\/mattn\/go-ole\"\n\t\"github.com\/mattn\/go-ole\/oleutil\"\n\t\"math\/big\"\n\t\"time\"\n\t\"unsafe\"\n)\n\nfunc init() {\n\tole.CoInitialize(0)\n\tsql.Register(\"adodb\", &AdodbDriver{})\n}\n\ntype AdodbDriver struct {\n\n}\n\ntype AdodbConn struct {\n\tdb *ole.IDispatch\n}\n\ntype AdodbTx struct {\n\tc *AdodbConn\n}\n\nfunc (tx *AdodbTx) Commit() error {\n\t_, err := oleutil.CallMethod(tx.c.db, \"CommitTrans\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (tx *AdodbTx) Rollback() error {\n\t_, err := oleutil.CallMethod(tx.c.db, \"Rollback\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *AdodbConn) exec(cmd string) error {\n\t_, err := oleutil.CallMethod(c.db, \"Execute\", cmd)\n\treturn err\n}\n\nfunc (c *AdodbConn) Begin() (driver.Tx, error) {\n\t_, err := oleutil.CallMethod(c.db, \"BeginTrans\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AdodbTx{c}, nil\n}\n\nfunc (d *AdodbDriver) Open(dsn string) (driver.Conn, error) {\n\tunknown, err := oleutil.CreateObject(\"ADODB.Connection\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdb, err := unknown.QueryInterface(ole.IID_IDispatch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = oleutil.CallMethod(db, \"Open\", dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AdodbConn{db}, nil\n}\n\nfunc (c *AdodbConn) Close() error {\n\t_, err := oleutil.CallMethod(c.db, \"Close\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.db = nil\n\treturn nil\n}\n\ntype AdodbStmt struct {\n\tc  *AdodbConn\n\ts  *ole.IDispatch\n\tps *ole.IDispatch\n\tb  []string\n}\n\nfunc (c *AdodbConn) Prepare(query string) (driver.Stmt, error) {\n\tunknown, err := oleutil.CreateObject(\"ADODB.Command\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts, err := unknown.QueryInterface(ole.IID_IDispatch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = oleutil.PutProperty(s, \"ActiveConnection\", c.db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = oleutil.PutProperty(s, \"CommandText\", query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = oleutil.PutProperty(s, \"CommandType\", 1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = oleutil.PutProperty(s, \"Prepared\", true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tval, err := oleutil.GetProperty(s, \"Parameters\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AdodbStmt{c, s, val.ToIDispatch(), nil}, nil\n}\n\nfunc (s *AdodbStmt) Bind(bind []string) error {\n\ts.b = bind\n\treturn nil\n}\n\nfunc (s *AdodbStmt) Close() error {\n\ts.s.Release()\n\treturn nil\n}\n\nfunc (s *AdodbStmt) NumInput() int {\n\tif s.b != nil {\n\t\treturn len(s.b)\n\t}\n\t_, err := oleutil.CallMethod(s.ps, \"Refresh\")\n\tif err != nil {\n\t\treturn -1\n\t}\n\tval, err := oleutil.GetProperty(s.ps, \"Count\")\n\tif err != nil {\n\t\treturn -1\n\t}\n\tc := int(val.Val)\n\treturn c\n}\n\nfunc (s *AdodbStmt) bind(args []driver.Value) error {\n\tif s.b != nil {\n\t\tfor i, v := range args {\n\t\t\tvar b string = \"?\"\n\t\t\tif len(s.b) < i {\n\t\t\t\tb = s.b[i]\n\t\t\t}\n\t\t\tunknown, err := oleutil.CallMethod(s.s, \"CreateParameter\", b, 12, 1)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tparam := unknown.ToIDispatch()\n\t\t\tdefer param.Release()\n\t\t\t_, err = oleutil.PutProperty(param, \"Value\", v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = oleutil.CallMethod(s.ps, \"Append\", param)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor i, v := range args {\n\t\t\tvar varval ole.VARIANT\n\t\t\tvarval.VT = ole.VT_I4\n\t\t\tvarval.Val = int64(i)\n\t\t\tval, err := oleutil.CallMethod(s.ps, \"Item\", &varval)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\titem := val.ToIDispatch()\n\t\t\tdefer item.Release()\n\t\t\t_, err = oleutil.PutProperty(item, \"Value\", v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *AdodbStmt) Query(args []driver.Value) (driver.Rows, error) {\n\tif err := s.bind(args); err != nil {\n\t\treturn nil, err\n\t}\n\trc, err := oleutil.CallMethod(s.s, \"Execute\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AdodbRows{s, rc.ToIDispatch(), -1, nil}, nil\n}\n\nfunc (s *AdodbStmt) Exec(args []driver.Value) (driver.Result, error) {\n\tif err := s.bind(args); err != nil {\n\t\treturn nil, err\n\t}\n\t_, err := oleutil.CallMethod(s.s, \"Execute\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn driver.ResultNoRows, nil\n}\n\ntype AdodbRows struct {\n\ts    *AdodbStmt\n\trc   *ole.IDispatch\n\tnc   int\n\tcols []string\n}\n\nfunc (rc *AdodbRows) Close() error {\n\t_, err := oleutil.CallMethod(rc.rc, \"Close\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (rc *AdodbRows) Columns() []string {\n\tif rc.nc != len(rc.cols) {\n\t\tunknown, err := oleutil.GetProperty(rc.rc, \"Fields\")\n\t\tif err != nil {\n\t\t\treturn []string{}\n\t\t}\n\t\tfields := unknown.ToIDispatch()\n\t\tdefer fields.Release()\n\t\tval, err := oleutil.GetProperty(fields, \"Count\")\n\t\tif err != nil {\n\t\t\treturn []string{}\n\t\t}\n\t\trc.nc = int(val.Val)\n\t\trc.cols = make([]string, rc.nc)\n\t\tfor i := 0; i < rc.nc; i++ {\n\t\t\tvar varval ole.VARIANT\n\t\t\tvarval.VT = ole.VT_I4\n\t\t\tvarval.Val = int64(i)\n\t\t\tval, err := oleutil.CallMethod(fields, \"Item\", &varval)\n\t\t\tif err != nil {\n\t\t\t\treturn []string{}\n\t\t\t}\n\t\t\titem := val.ToIDispatch()\n\t\t\tif err != nil {\n\t\t\t\treturn []string{}\n\t\t\t}\n\t\t\tname, err := oleutil.GetProperty(item, \"Name\")\n\t\t\tif err != nil {\n\t\t\t\treturn []string{}\n\t\t\t}\n\t\t\trc.cols[i] = name.ToString()\n\t\t\titem.Release()\n\t\t}\n\t}\n\treturn rc.cols\n}\n\nfunc (rc *AdodbRows) Next(dest []driver.Value) error {\n\t_, err := oleutil.CallMethod(rc.rc, \"MoveNext\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tunknown, err := oleutil.GetProperty(rc.rc, \"EOF\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif unknown.Val != 0 {\n\t\treturn errors.New(\"EOF\")\n\t}\n\tunknown, err = oleutil.GetProperty(rc.rc, \"Fields\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tfields := unknown.ToIDispatch()\n\tdefer fields.Release()\n\tfor i := range dest {\n\t\tvar varval ole.VARIANT\n\t\tvarval.VT = ole.VT_I4\n\t\tvarval.Val = int64(i)\n\t\tval, err := oleutil.CallMethod(fields, \"Item\", &varval)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfield := val.ToIDispatch()\n\t\tdefer field.Release()\n\t\ttyp, err := oleutil.GetProperty(field, \"Type\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tval, err = oleutil.GetProperty(field, \"Value\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfield.Release()\n\t\tswitch typ.Val {\n\t\tcase 0: \/\/ ADEMPTY\n\t\t\t\/\/ TODO\n\t\tcase 2: \/\/ ADSMALLINT\n\t\t\tdest[i] = int16(val.Val)\n\t\tcase 3: \/\/ ADINTEGER\n\t\t\tdest[i] = int32(val.Val)\n\t\tcase 4: \/\/ ADSINGLE\n\t\t\tdest[i] = float32(val.Val)\n\t\tcase 5: \/\/ ADDOUBLE\n\t\t\tdest[i] = val.Val\n\t\tcase 6: \/\/ ADCURRENCY\n\t\t\t\/\/ TODO\n\t\tcase 7: \/\/ ADDATE\n\t\t\t\/\/ TODO\n\t\tcase 8: \/\/ ADBSTR\n\t\t\tdest[i] = val.ToString()\n\t\tcase 9: \/\/ ADIDISPATCH\n\t\t\tdest[i] = val.ToIDispatch()\n\t\tcase 10: \/\/ ADERROR\n\t\t\t\/\/ TODO\n\t\tcase 11: \/\/ ADBOOLEAN\n\t\t\tif val.Val != 0 {\n\t\t\t\tdest[i] = true\n\t\t\t} else {\n\t\t\t\tdest[i] = false\n\t\t\t}\n\t\tcase 12: \/\/ ADVARIANT\n\t\t\tdest[i] = val\n\t\tcase 13: \/\/ ADIUNKNOWN\n\t\t\tdest[i] = val.ToIUnknown()\n\t\tcase 14: \/\/ ADDECIMAL\n\t\t\t\/\/ TODO\n\t\tcase 16: \/\/ ADTINYINT\n\t\t\tdest[i] = int8(val.Val)\n\t\tcase 17: \/\/ ADUNSIGNEDTINYINT\n\t\t\tdest[i] = uint8(val.Val)\n\t\tcase 18: \/\/ ADUNSIGNEDSMALLINT\n\t\t\tdest[i] = uint16(val.Val)\n\t\tcase 19: \/\/ ADUNSIGNEDINT\n\t\t\tdest[i] = uint32(val.Val)\n\t\tcase 20: \/\/ ADBIGINT\n\t\t\tdest[i] = big.NewInt(val.Val)\n\t\tcase 21: \/\/ ADUNSIGNEDBIGINT\n\t\t\t\/\/ TODO\n\t\tcase 72: \/\/ ADGUID\n\t\t\t\/\/ TODO\n\t\tcase 128: \/\/ ADBINARY\n\t\t\tsa := *(**ole.SAFEARRAY)(unsafe.Pointer(&val.Val))\n\t\t\tdest[i] = (*[1 << 30]byte)(unsafe.Pointer(uintptr(sa.PvData)))[0:sa.CbElements]\n\t\tcase 129: \/\/ ADCHAR\n\t\t\tdest[i] = uint8(val.Val)\n\t\tcase 130: \/\/ ADWCHAR\n\t\t\tdest[i] = uint16(val.Val)\n\t\tcase 131: \/\/ ADNUMERIC\n\t\t\tdest[i] = val.Val\n\t\tcase 132: \/\/ ADUSERDEFINED\n\t\t\tdest[i] = uintptr(val.Val)\n\t\tcase 133: \/\/ ADDBDATE\n\t\t\tdest[i] = time.Unix(0, val.Val).UTC()\n\t\tcase 134: \/\/ ADDBTIME\n\t\t\tdest[i] = time.Unix(0, val.Val).UTC()\n\t\tcase 135: \/\/ ADDBTIMESTAMP\n\t\t\tdest[i] = time.Unix(0, val.Val).UTC()\n\t\tcase 136: \/\/ ADCHAPTER\n\t\t\tdest[i] = val.ToString()\n\t\tcase 200: \/\/ ADVARCHAR\n\t\t\tdest[i] = val.ToString()\n\t\tcase 201: \/\/ ADLONGVARCHAR\n\t\t\tdest[i] = val.ToString()\n\t\tcase 202: \/\/ ADVARWCHAR\n\t\t\tdest[i] = val.ToString()\n\t\tcase 203: \/\/ ADLONGVARWCHAR\n\t\t\tdest[i] = val.ToString()\n\t\tcase 204: \/\/ ADVARBINARY\n\t\t\t\/\/ TODO\n\t\tcase 205: \/\/ ADLONGVARBINARY\n\t\t\t\/\/ TODO\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>check EOF first. close #1<commit_after>package adodb\n\nimport (\n\t\"errors\"\n\t\"database\/sql\"\n\t\"database\/sql\/driver\"\n\t\"fmt\"\n\t\"github.com\/mattn\/go-ole\"\n\t\"github.com\/mattn\/go-ole\/oleutil\"\n\t\"math\/big\"\n\t\"time\"\n\t\"unsafe\"\n)\n\nfunc init() {\n\tole.CoInitialize(0)\n\tsql.Register(\"adodb\", &AdodbDriver{})\n}\n\ntype AdodbDriver struct {\n\n}\n\ntype AdodbConn struct {\n\tdb *ole.IDispatch\n}\n\ntype AdodbTx struct {\n\tc *AdodbConn\n}\n\nfunc (tx *AdodbTx) Commit() error {\n\t_, err := oleutil.CallMethod(tx.c.db, \"CommitTrans\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (tx *AdodbTx) Rollback() error {\n\t_, err := oleutil.CallMethod(tx.c.db, \"Rollback\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *AdodbConn) exec(cmd string) error {\n\t_, err := oleutil.CallMethod(c.db, \"Execute\", cmd)\n\treturn err\n}\n\nfunc (c *AdodbConn) Begin() (driver.Tx, error) {\n\t_, err := oleutil.CallMethod(c.db, \"BeginTrans\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AdodbTx{c}, nil\n}\n\nfunc (d *AdodbDriver) Open(dsn string) (driver.Conn, error) {\n\tunknown, err := oleutil.CreateObject(\"ADODB.Connection\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdb, err := unknown.QueryInterface(ole.IID_IDispatch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = oleutil.CallMethod(db, \"Open\", dsn)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AdodbConn{db}, nil\n}\n\nfunc (c *AdodbConn) Close() error {\n\t_, err := oleutil.CallMethod(c.db, \"Close\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.db = nil\n\treturn nil\n}\n\ntype AdodbStmt struct {\n\tc  *AdodbConn\n\ts  *ole.IDispatch\n\tps *ole.IDispatch\n\tb  []string\n}\n\nfunc (c *AdodbConn) Prepare(query string) (driver.Stmt, error) {\n\tunknown, err := oleutil.CreateObject(\"ADODB.Command\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts, err := unknown.QueryInterface(ole.IID_IDispatch)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = oleutil.PutProperty(s, \"ActiveConnection\", c.db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = oleutil.PutProperty(s, \"CommandText\", query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = oleutil.PutProperty(s, \"CommandType\", 1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err = oleutil.PutProperty(s, \"Prepared\", true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tval, err := oleutil.GetProperty(s, \"Parameters\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AdodbStmt{c, s, val.ToIDispatch(), nil}, nil\n}\n\nfunc (s *AdodbStmt) Bind(bind []string) error {\n\ts.b = bind\n\treturn nil\n}\n\nfunc (s *AdodbStmt) Close() error {\n\ts.s.Release()\n\treturn nil\n}\n\nfunc (s *AdodbStmt) NumInput() int {\n\tif s.b != nil {\n\t\treturn len(s.b)\n\t}\n\t_, err := oleutil.CallMethod(s.ps, \"Refresh\")\n\tif err != nil {\n\t\treturn -1\n\t}\n\tval, err := oleutil.GetProperty(s.ps, \"Count\")\n\tif err != nil {\n\t\treturn -1\n\t}\n\tc := int(val.Val)\n\treturn c\n}\n\nfunc (s *AdodbStmt) bind(args []driver.Value) error {\n\tif s.b != nil {\n\t\tfor i, v := range args {\n\t\t\tvar b string = \"?\"\n\t\t\tif len(s.b) < i {\n\t\t\t\tb = s.b[i]\n\t\t\t}\n\t\t\tunknown, err := oleutil.CallMethod(s.s, \"CreateParameter\", b, 12, 1)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tparam := unknown.ToIDispatch()\n\t\t\tdefer param.Release()\n\t\t\t_, err = oleutil.PutProperty(param, \"Value\", v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\t_, err = oleutil.CallMethod(s.ps, \"Append\", param)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tfor i, v := range args {\n\t\t\tvar varval ole.VARIANT\n\t\t\tvarval.VT = ole.VT_I4\n\t\t\tvarval.Val = int64(i)\n\t\t\tval, err := oleutil.CallMethod(s.ps, \"Item\", &varval)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\titem := val.ToIDispatch()\n\t\t\tdefer item.Release()\n\t\t\t_, err = oleutil.PutProperty(item, \"Value\", v)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (s *AdodbStmt) Query(args []driver.Value) (driver.Rows, error) {\n\tif err := s.bind(args); err != nil {\n\t\treturn nil, err\n\t}\n\trc, err := oleutil.CallMethod(s.s, \"Execute\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &AdodbRows{s, rc.ToIDispatch(), -1, nil}, nil\n}\n\nfunc (s *AdodbStmt) Exec(args []driver.Value) (driver.Result, error) {\n\tif err := s.bind(args); err != nil {\n\t\treturn nil, err\n\t}\n\t_, err := oleutil.CallMethod(s.s, \"Execute\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn driver.ResultNoRows, nil\n}\n\ntype AdodbRows struct {\n\ts    *AdodbStmt\n\trc   *ole.IDispatch\n\tnc   int\n\tcols []string\n}\n\nfunc (rc *AdodbRows) Close() error {\n\t_, err := oleutil.CallMethod(rc.rc, \"Close\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (rc *AdodbRows) Columns() []string {\n\tif rc.nc != len(rc.cols) {\n\t\tunknown, err := oleutil.GetProperty(rc.rc, \"Fields\")\n\t\tif err != nil {\n\t\t\treturn []string{}\n\t\t}\n\t\tfields := unknown.ToIDispatch()\n\t\tdefer fields.Release()\n\t\tval, err := oleutil.GetProperty(fields, \"Count\")\n\t\tif err != nil {\n\t\t\treturn []string{}\n\t\t}\n\t\trc.nc = int(val.Val)\n\t\trc.cols = make([]string, rc.nc)\n\t\tfor i := 0; i < rc.nc; i++ {\n\t\t\tvar varval ole.VARIANT\n\t\t\tvarval.VT = ole.VT_I4\n\t\t\tvarval.Val = int64(i)\n\t\t\tval, err := oleutil.CallMethod(fields, \"Item\", &varval)\n\t\t\tif err != nil {\n\t\t\t\treturn []string{}\n\t\t\t}\n\t\t\titem := val.ToIDispatch()\n\t\t\tif err != nil {\n\t\t\t\treturn []string{}\n\t\t\t}\n\t\t\tname, err := oleutil.GetProperty(item, \"Name\")\n\t\t\tif err != nil {\n\t\t\t\treturn []string{}\n\t\t\t}\n\t\t\trc.cols[i] = name.ToString()\n\t\t\titem.Release()\n\t\t}\n\t}\n\treturn rc.cols\n}\n\nfunc (rc *AdodbRows) Next(dest []driver.Value) error {\n\tunknown, err := oleutil.GetProperty(rc.rc, \"EOF\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif unknown.Val != 0 {\n\t\treturn errors.New(\"EOF\")\n\t}\n\t_, err = oleutil.CallMethod(rc.rc, \"MoveNext\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn err\n\t}\n\tunknown, err = oleutil.GetProperty(rc.rc, \"Fields\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tfields := unknown.ToIDispatch()\n\tdefer fields.Release()\n\tfor i := range dest {\n\t\tvar varval ole.VARIANT\n\t\tvarval.VT = ole.VT_I4\n\t\tvarval.Val = int64(i)\n\t\tval, err := oleutil.CallMethod(fields, \"Item\", &varval)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfield := val.ToIDispatch()\n\t\tdefer field.Release()\n\t\ttyp, err := oleutil.GetProperty(field, \"Type\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tval, err = oleutil.GetProperty(field, \"Value\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfield.Release()\n\t\tswitch typ.Val {\n\t\tcase 0: \/\/ ADEMPTY\n\t\t\t\/\/ TODO\n\t\tcase 2: \/\/ ADSMALLINT\n\t\t\tdest[i] = int16(val.Val)\n\t\tcase 3: \/\/ ADINTEGER\n\t\t\tdest[i] = int32(val.Val)\n\t\tcase 4: \/\/ ADSINGLE\n\t\t\tdest[i] = float32(val.Val)\n\t\tcase 5: \/\/ ADDOUBLE\n\t\t\tdest[i] = val.Val\n\t\tcase 6: \/\/ ADCURRENCY\n\t\t\t\/\/ TODO\n\t\tcase 7: \/\/ ADDATE\n\t\t\t\/\/ TODO\n\t\tcase 8: \/\/ ADBSTR\n\t\t\tdest[i] = val.ToString()\n\t\tcase 9: \/\/ ADIDISPATCH\n\t\t\tdest[i] = val.ToIDispatch()\n\t\tcase 10: \/\/ ADERROR\n\t\t\t\/\/ TODO\n\t\tcase 11: \/\/ ADBOOLEAN\n\t\t\tif val.Val != 0 {\n\t\t\t\tdest[i] = true\n\t\t\t} else {\n\t\t\t\tdest[i] = false\n\t\t\t}\n\t\tcase 12: \/\/ ADVARIANT\n\t\t\tdest[i] = val\n\t\tcase 13: \/\/ ADIUNKNOWN\n\t\t\tdest[i] = val.ToIUnknown()\n\t\tcase 14: \/\/ ADDECIMAL\n\t\t\t\/\/ TODO\n\t\tcase 16: \/\/ ADTINYINT\n\t\t\tdest[i] = int8(val.Val)\n\t\tcase 17: \/\/ ADUNSIGNEDTINYINT\n\t\t\tdest[i] = uint8(val.Val)\n\t\tcase 18: \/\/ ADUNSIGNEDSMALLINT\n\t\t\tdest[i] = uint16(val.Val)\n\t\tcase 19: \/\/ ADUNSIGNEDINT\n\t\t\tdest[i] = uint32(val.Val)\n\t\tcase 20: \/\/ ADBIGINT\n\t\t\tdest[i] = big.NewInt(val.Val)\n\t\tcase 21: \/\/ ADUNSIGNEDBIGINT\n\t\t\t\/\/ TODO\n\t\tcase 72: \/\/ ADGUID\n\t\t\t\/\/ TODO\n\t\tcase 128: \/\/ ADBINARY\n\t\t\tsa := *(**ole.SAFEARRAY)(unsafe.Pointer(&val.Val))\n\t\t\tdest[i] = (*[1 << 30]byte)(unsafe.Pointer(uintptr(sa.PvData)))[0:sa.CbElements]\n\t\tcase 129: \/\/ ADCHAR\n\t\t\tdest[i] = uint8(val.Val)\n\t\tcase 130: \/\/ ADWCHAR\n\t\t\tdest[i] = uint16(val.Val)\n\t\tcase 131: \/\/ ADNUMERIC\n\t\t\tdest[i] = val.Val\n\t\tcase 132: \/\/ ADUSERDEFINED\n\t\t\tdest[i] = uintptr(val.Val)\n\t\tcase 133: \/\/ ADDBDATE\n\t\t\tdest[i] = time.Unix(0, val.Val).UTC()\n\t\tcase 134: \/\/ ADDBTIME\n\t\t\tdest[i] = time.Unix(0, val.Val).UTC()\n\t\tcase 135: \/\/ ADDBTIMESTAMP\n\t\t\tdest[i] = time.Unix(0, val.Val).UTC()\n\t\tcase 136: \/\/ ADCHAPTER\n\t\t\tdest[i] = val.ToString()\n\t\tcase 200: \/\/ ADVARCHAR\n\t\t\tdest[i] = val.ToString()\n\t\tcase 201: \/\/ ADLONGVARCHAR\n\t\t\tdest[i] = val.ToString()\n\t\tcase 202: \/\/ ADVARWCHAR\n\t\t\tdest[i] = val.ToString()\n\t\tcase 203: \/\/ ADLONGVARWCHAR\n\t\t\tdest[i] = val.ToString()\n\t\tcase 204: \/\/ ADVARBINARY\n\t\t\t\/\/ TODO\n\t\tcase 205: \/\/ ADLONGVARBINARY\n\t\t\t\/\/ TODO\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) nano Author. All Rights Reserved.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\npackage nano\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/lonnng\/nano\/internal\/codec\"\n\t\"github.com\/lonnng\/nano\/internal\/message\"\n\t\"github.com\/lonnng\/nano\/internal\/packet\"\n\t\"github.com\/lonnng\/nano\/session\"\n)\n\nconst agentWriteBacklog = 16\n\nvar (\n\tErrBrokenPipe   = errors.New(\"broken low-level pipe\")\n\tErrBufferExceed = errors.New(\"session send buffer exceed\")\n)\n\n\/\/ Agent corresponding a user, used for store raw conn information\ntype (\n\tagent struct {\n\t\tsession *session.Session    \/\/ session\n\t\tconn    net.Conn            \/\/ low-level conn fd\n\t\tstate   int32               \/\/ current agent state\n\t\tchDie   chan struct{}       \/\/ wait for close\n\t\tchSend  chan pendingMessage \/\/ push message queue\n\t\tlastAt  int64               \/\/ last heartbeat unix time stamp\n\t\tdecoder *codec.Decoder      \/\/ binary decoder\n\t}\n\n\tpendingMessage struct {\n\t\ttyp     message.MessageType \/\/ message type\n\t\troute   string              \/\/ message route(push)\n\t\tmid     uint                \/\/ response message id(response)\n\t\tpayload interface{}         \/\/ payload\n\t}\n)\n\n\/\/ Create new agent instance\nfunc newAgent(conn net.Conn) *agent {\n\ta := &agent{\n\t\tconn:    conn,\n\t\tstate:   statusStart,\n\t\tchDie:   make(chan struct{}),\n\t\tlastAt:  time.Now().Unix(),\n\t\tchSend:  make(chan pendingMessage, agentWriteBacklog),\n\t\tdecoder: codec.NewDecoder(),\n\t}\n\n\t\/\/ binding session\n\ts := session.New(a)\n\ta.session = s\n\n\treturn a\n}\n\n\/\/ Push, implementation for session.NetworkEntity interface\nfunc (a *agent) Push(route string, v interface{}) error {\n\tif a.status() == statusClosed {\n\t\treturn ErrBrokenPipe\n\t}\n\n\tif len(a.chSend) >= agentWriteBacklog {\n\t\treturn ErrBufferExceed\n\t}\n\n\tif env.debug {\n\t\tlog.Println(fmt.Sprintf(\"Type=Push, UID=%d, Route=%s, Data=%+v\", a.session.Uid(), route, v))\n\t}\n\n\ta.chSend <- pendingMessage{typ: message.Push, route: route, payload: v}\n\treturn nil\n}\n\n\/\/ Response, implementation for session.NetworkEntity interface\n\/\/ Response message to session\nfunc (a *agent) Response(v interface{}) error {\n\tif a.status() == statusClosed {\n\t\treturn ErrBrokenPipe\n\t}\n\n\tmid := a.session.LastRID\n\tif mid <= 0 {\n\t\treturn ErrSessionOnNotify\n\t}\n\n\tif len(a.chSend) >= agentWriteBacklog {\n\t\treturn ErrBufferExceed\n\t}\n\n\tif env.debug {\n\t\tlog.Println(fmt.Sprintf(\"Type=Response, UID=%d, MID=%d, Data=%+v\", a.session.Uid(), mid, v))\n\t}\n\n\ta.chSend <- pendingMessage{typ: message.Response, mid: mid, payload: v}\n\treturn nil\n}\n\n\/\/ Close, implementation for session.NetworkEntity interface\n\/\/ Close closes the agent, clean inner state and close low-level connection.\n\/\/ Any blocked Read or Write operations will be unblocked and return errors.\nfunc (a *agent) Close() error {\n\tif a.status() == statusClosed {\n\t\treturn ErrClosedSession\n\t}\n\ta.setStatus(statusClosed)\n\n\tif env.debug {\n\t\tlog.Println(fmt.Sprintf(\"Session closed, Id=%d, IP=%s\", a.session.ID(), a.conn.RemoteAddr()))\n\t}\n\n\t\/\/ close all channel\n\tclose(a.chDie)\n\treturn a.conn.Close()\n}\n\n\/\/ RemoteAddr, implementation for session.NetworkEntity interface\n\/\/ returns the remote network address.\nfunc (a *agent) RemoteAddr() net.Addr {\n\treturn a.conn.RemoteAddr()\n}\n\n\/\/ String, implementation for Stringer interface\nfunc (a *agent) String() string {\n\treturn fmt.Sprintf(\"Remote=%s, LastTime=%d\", a.conn.RemoteAddr().String(), a.lastAt)\n}\n\nfunc (a *agent) status() int32 {\n\treturn atomic.LoadInt32(&a.state)\n}\n\nfunc (a *agent) setStatus(state int32) {\n\tatomic.StoreInt32(&a.state, state)\n}\n\nfunc (a *agent) write() {\n\tticker := time.NewTicker(env.heartbeat)\n\tchWrite := make(chan []byte, agentWriteBacklog)\n\t\/\/ clean func\n\tdefer func() {\n\t\tticker.Stop()\n\t\tclose(a.chSend)\n\t\tclose(chWrite)\n\t\ta.Close()\n\t\tif env.debug {\n\t\t\tlog.Println(fmt.Sprintf(\"Session write goroutine exit, SessionID=%d, UID=%d\", a.session.ID(), a.session.Uid()))\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tdeadline := time.Now().Add(-2 * env.heartbeat).Unix()\n\t\t\tif a.lastAt < deadline {\n\t\t\t\tlog.Println(fmt.Sprintf(\"Session heartbeat timeout, LastTime=%d, Deadline=%d\", a.lastAt, deadline))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tchWrite <- hbd\n\n\t\tcase data := <-chWrite:\n\t\t\t\/\/ close agent while low-level conn broken\n\t\t\tif _, err := a.conn.Write(data); err != nil {\n\t\t\t\tlog.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase data := <-a.chSend:\n\t\t\tpayload, err := serializeOrRaw(data.payload)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err.Error())\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ construct message and encode\n\t\t\tm := &message.Message{\n\t\t\t\tType:  data.typ,\n\t\t\t\tData:  payload,\n\t\t\t\tRoute: data.route,\n\t\t\t\tID:    data.mid,\n\t\t\t}\n\t\t\tem, err := m.Encode()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err.Error())\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ packet encode\n\t\t\tp, err := codec.Encode(packet.Data, em)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tchWrite <- p\n\n\t\tcase <-a.chDie: \/\/ agent closed signal\n\t\t\treturn\n\n\t\tcase <-env.die: \/\/ application quit\n\t\t\treturn\n\t\t}\n\t}\n}\n<commit_msg>fixed: handle session closed event<commit_after>\/\/ Copyright (c) nano Author. All Rights Reserved.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\npackage nano\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/lonnng\/nano\/internal\/codec\"\n\t\"github.com\/lonnng\/nano\/internal\/message\"\n\t\"github.com\/lonnng\/nano\/internal\/packet\"\n\t\"github.com\/lonnng\/nano\/session\"\n)\n\nconst agentWriteBacklog = 16\n\nvar (\n\tErrBrokenPipe   = errors.New(\"broken low-level pipe\")\n\tErrBufferExceed = errors.New(\"session send buffer exceed\")\n)\n\n\/\/ Agent corresponding a user, used for store raw conn information\ntype (\n\tagent struct {\n\t\tsession *session.Session    \/\/ session\n\t\tconn    net.Conn            \/\/ low-level conn fd\n\t\tstate   int32               \/\/ current agent state\n\t\tchDie   chan struct{}       \/\/ wait for close\n\t\tchSend  chan pendingMessage \/\/ push message queue\n\t\tlastAt  int64               \/\/ last heartbeat unix time stamp\n\t\tdecoder *codec.Decoder      \/\/ binary decoder\n\t}\n\n\tpendingMessage struct {\n\t\ttyp     message.MessageType \/\/ message type\n\t\troute   string              \/\/ message route(push)\n\t\tmid     uint                \/\/ response message id(response)\n\t\tpayload interface{}         \/\/ payload\n\t}\n)\n\n\/\/ Create new agent instance\nfunc newAgent(conn net.Conn) *agent {\n\ta := &agent{\n\t\tconn:    conn,\n\t\tstate:   statusStart,\n\t\tchDie:   make(chan struct{}),\n\t\tlastAt:  time.Now().Unix(),\n\t\tchSend:  make(chan pendingMessage, agentWriteBacklog),\n\t\tdecoder: codec.NewDecoder(),\n\t}\n\n\t\/\/ binding session\n\ts := session.New(a)\n\ta.session = s\n\n\treturn a\n}\n\n\/\/ Push, implementation for session.NetworkEntity interface\nfunc (a *agent) Push(route string, v interface{}) error {\n\tif a.status() == statusClosed {\n\t\treturn ErrBrokenPipe\n\t}\n\n\tif len(a.chSend) >= agentWriteBacklog {\n\t\treturn ErrBufferExceed\n\t}\n\n\tif env.debug {\n\t\tlog.Println(fmt.Sprintf(\"Type=Push, UID=%d, Route=%s, Data=%+v\", a.session.Uid(), route, v))\n\t}\n\n\ta.chSend <- pendingMessage{typ: message.Push, route: route, payload: v}\n\treturn nil\n}\n\n\/\/ Response, implementation for session.NetworkEntity interface\n\/\/ Response message to session\nfunc (a *agent) Response(v interface{}) error {\n\tif a.status() == statusClosed {\n\t\treturn ErrBrokenPipe\n\t}\n\n\tmid := a.session.LastRID\n\tif mid <= 0 {\n\t\treturn ErrSessionOnNotify\n\t}\n\n\tif len(a.chSend) >= agentWriteBacklog {\n\t\treturn ErrBufferExceed\n\t}\n\n\tif env.debug {\n\t\tlog.Println(fmt.Sprintf(\"Type=Response, UID=%d, MID=%d, Data=%+v\", a.session.Uid(), mid, v))\n\t}\n\n\ta.chSend <- pendingMessage{typ: message.Response, mid: mid, payload: v}\n\treturn nil\n}\n\n\/\/ Close, implementation for session.NetworkEntity interface\n\/\/ Close closes the agent, clean inner state and close low-level connection.\n\/\/ Any blocked Read or Write operations will be unblocked and return errors.\nfunc (a *agent) Close() error {\n\tif a.status() == statusClosed {\n\t\treturn ErrClosedSession\n\t}\n\ta.setStatus(statusClosed)\n\n\tif env.debug {\n\t\tlog.Println(fmt.Sprintf(\"Session closed, Id=%d, IP=%s\", a.session.ID(), a.conn.RemoteAddr()))\n\t}\n\n\t\/\/ close all channel\n\tclose(a.chDie)\n\thandler.chCloseSession <- a.session\n\n\treturn a.conn.Close()\n}\n\n\/\/ RemoteAddr, implementation for session.NetworkEntity interface\n\/\/ returns the remote network address.\nfunc (a *agent) RemoteAddr() net.Addr {\n\treturn a.conn.RemoteAddr()\n}\n\n\/\/ String, implementation for Stringer interface\nfunc (a *agent) String() string {\n\treturn fmt.Sprintf(\"Remote=%s, LastTime=%d\", a.conn.RemoteAddr().String(), a.lastAt)\n}\n\nfunc (a *agent) status() int32 {\n\treturn atomic.LoadInt32(&a.state)\n}\n\nfunc (a *agent) setStatus(state int32) {\n\tatomic.StoreInt32(&a.state, state)\n}\n\nfunc (a *agent) write() {\n\tticker := time.NewTicker(env.heartbeat)\n\tchWrite := make(chan []byte, agentWriteBacklog)\n\t\/\/ clean func\n\tdefer func() {\n\t\tticker.Stop()\n\t\tclose(a.chSend)\n\t\tclose(chWrite)\n\t\ta.Close()\n\t\tif env.debug {\n\t\t\tlog.Println(fmt.Sprintf(\"Session write goroutine exit, SessionID=%d, UID=%d\", a.session.ID(), a.session.Uid()))\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tdeadline := time.Now().Add(-2 * env.heartbeat).Unix()\n\t\t\tif a.lastAt < deadline {\n\t\t\t\tlog.Println(fmt.Sprintf(\"Session heartbeat timeout, LastTime=%d, Deadline=%d\", a.lastAt, deadline))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tchWrite <- hbd\n\n\t\tcase data := <-chWrite:\n\t\t\t\/\/ close agent while low-level conn broken\n\t\t\tif _, err := a.conn.Write(data); err != nil {\n\t\t\t\tlog.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase data := <-a.chSend:\n\t\t\tpayload, err := serializeOrRaw(data.payload)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err.Error())\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ construct message and encode\n\t\t\tm := &message.Message{\n\t\t\t\tType:  data.typ,\n\t\t\t\tData:  payload,\n\t\t\t\tRoute: data.route,\n\t\t\t\tID:    data.mid,\n\t\t\t}\n\t\t\tem, err := m.Encode()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err.Error())\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ packet encode\n\t\t\tp, err := codec.Encode(packet.Data, em)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tchWrite <- p\n\n\t\tcase <-a.chDie: \/\/ agent closed signal\n\t\t\treturn\n\n\t\tcase <-env.die: \/\/ application quit\n\t\t\treturn\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package telegraf\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/influxdb\/telegraf\/outputs\"\n\t\"github.com\/influxdb\/telegraf\/plugins\"\n)\n\ntype runningOutput struct {\n\tname   string\n\toutput outputs.Output\n}\n\ntype runningPlugin struct {\n\tname   string\n\tplugin plugins.Plugin\n\tconfig *ConfiguredPlugin\n}\n\n\/\/ Agent runs telegraf and collects data based on the given config\ntype Agent struct {\n\n\t\/\/ Interval at which to gather information\n\tInterval Duration\n\n\t\/\/ Run in debug mode?\n\tDebug    bool\n\tHostname string\n\n\tConfig *Config\n\n\toutputs []*runningOutput\n\tplugins []*runningPlugin\n}\n\n\/\/ NewAgent returns an Agent struct based off the given Config\nfunc NewAgent(config *Config) (*Agent, error) {\n\tagent := &Agent{Config: config, Interval: Duration{10 * time.Second}}\n\n\terr := config.ApplyAgent(agent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif agent.Hostname == \"\" {\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tagent.Hostname = hostname\n\t}\n\n\tif config.Tags == nil {\n\t\tconfig.Tags = map[string]string{}\n\t}\n\n\tconfig.Tags[\"host\"] = agent.Hostname\n\n\treturn agent, nil\n}\n\n\/\/ Connect connects to all configured outputs\nfunc (a *Agent) Connect() error {\n\tfor _, o := range a.outputs {\n\t\terr := o.output.Connect()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Close closes the connection to all configured outputs\nfunc (a *Agent) Close() error {\n\tvar err error\n\tfor _, o := range a.outputs {\n\t\terr = o.output.Close()\n\t}\n\treturn err\n}\n\n\/\/ LoadOutputs loads the agent's outputs\nfunc (a *Agent) LoadOutputs() ([]string, error) {\n\tvar names []string\n\n\tfor _, name := range a.Config.OutputsDeclared() {\n\t\tcreator, ok := outputs.Outputs[name]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Undefined but requested output: %s\", name)\n\t\t}\n\n\t\toutput := creator()\n\n\t\terr := a.Config.ApplyOutput(name, output)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ta.outputs = append(a.outputs, &runningOutput{name, output})\n\t\tnames = append(names, name)\n\t}\n\n\tsort.Strings(names)\n\n\treturn names, nil\n}\n\n\/\/ LoadPlugins loads the agent's plugins\nfunc (a *Agent) LoadPlugins(pluginsFilter string) ([]string, error) {\n\tvar names []string\n\tvar filters []string\n\n\tpluginsFilter = strings.TrimSpace(pluginsFilter)\n\tif pluginsFilter != \"\" {\n\t\tfilters = strings.Split(\":\"+pluginsFilter+\":\", \":\")\n\t}\n\n\tfor _, name := range a.Config.PluginsDeclared() {\n\t\tcreator, ok := plugins.Plugins[name]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Undefined but requested plugin: %s\", name)\n\t\t}\n\n\t\tisPluginEnabled := false\n\t\tif len(filters) > 0 {\n\t\t\tfor _, runeValue := range filters {\n\t\t\t\tif runeValue != \"\" && strings.ToLower(runeValue) == strings.ToLower(name) {\n\t\t\t\t\tfmt.Printf(\"plugin [%s] is enabled (filter options)\\n\", name)\n\t\t\t\t\tisPluginEnabled = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ if no filter, we ALWAYS accept the plugin\n\t\t\tisPluginEnabled = true\n\t\t}\n\n\t\tif isPluginEnabled {\n\t\t\tplugin := creator()\n\t\t\tconfig, err := a.Config.ApplyPlugin(name, plugin)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\ta.plugins = append(a.plugins, &runningPlugin{name, plugin, config})\n\t\t\tnames = append(names, name)\n\t\t}\n\t}\n\n\tsort.Strings(names)\n\n\treturn names, nil\n}\n\nfunc (a *Agent) crankParallel() error {\n\tpoints := make(chan *BatchPoints, len(a.plugins))\n\n\tvar wg sync.WaitGroup\n\n\tfor _, plugin := range a.plugins {\n\t\tif plugin.config.Interval != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func(plugin *runningPlugin) {\n\t\t\tdefer wg.Done()\n\n\t\t\tvar acc BatchPoints\n\t\t\tacc.Debug = a.Debug\n\t\t\tacc.Prefix = plugin.name + \"_\"\n\t\t\tacc.Config = plugin.config\n\n\t\t\tplugin.plugin.Gather(&acc)\n\n\t\t\tpoints <- &acc\n\t\t}(plugin)\n\t}\n\n\twg.Wait()\n\n\tclose(points)\n\n\tvar bp BatchPoints\n\tbp.Time = time.Now()\n\tbp.Tags = a.Config.Tags\n\n\tfor sub := range points {\n\t\tbp.Points = append(bp.Points, sub.Points...)\n\t}\n\n\treturn a.flush(&bp)\n}\n\nfunc (a *Agent) crank() error {\n\tvar bp BatchPoints\n\n\tbp.Debug = a.Debug\n\n\tfor _, plugin := range a.plugins {\n\t\tbp.Prefix = plugin.name + \"_\"\n\t\tbp.Config = plugin.config\n\t\terr := plugin.plugin.Gather(&bp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tbp.Time = time.Now()\n\tbp.Tags = a.Config.Tags\n\n\treturn a.flush(&bp)\n}\n\nfunc (a *Agent) crankSeparate(shutdown chan struct{}, plugin *runningPlugin) error {\n\tticker := time.NewTicker(plugin.config.Interval)\n\n\tfor {\n\t\tvar bp BatchPoints\n\n\t\tbp.Debug = a.Debug\n\n\t\tbp.Prefix = plugin.name + \"_\"\n\t\tbp.Config = plugin.config\n\t\terr := plugin.plugin.Gather(&bp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbp.Tags = a.Config.Tags\n\t\tbp.Time = time.Now()\n\n\t\terr = a.flush(&bp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tselect {\n\t\tcase <-shutdown:\n\t\t\treturn nil\n\t\tcase <-ticker.C:\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\nfunc (a *Agent) flush(bp *BatchPoints) error {\n\tvar wg sync.WaitGroup\n\tvar outerr error\n\tfor _, o := range a.outputs {\n\t\twg.Add(1)\n\t\tgo func(ro *runningOutput) {\n\t\t\tdefer wg.Done()\n\t\t\touterr = ro.output.Write(bp.BatchPoints)\n\t\t}(o)\n\t}\n\n\twg.Wait()\n\n\treturn outerr\n}\n\n\/\/ TestAllPlugins verifies that we can 'Gather' from all plugins with the\n\/\/ default configuration\nfunc (a *Agent) TestAllPlugins() error {\n\tvar names []string\n\n\tfor name := range plugins.Plugins {\n\t\tnames = append(names, name)\n\t}\n\n\tsort.Strings(names)\n\n\tvar acc BatchPoints\n\tacc.Debug = true\n\n\tfmt.Printf(\"* Testing all plugins with default configuration\\n\")\n\n\tfor _, name := range names {\n\t\tplugin := plugins.Plugins[name]()\n\n\t\tfmt.Printf(\"* Plugin: %s\\n\", name)\n\n\t\tacc.Prefix = name + \"_\"\n\t\terr := plugin.Gather(&acc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Test verifies that we can 'Gather' from all plugins with their configured\n\/\/ Config struct\nfunc (a *Agent) Test() error {\n\tvar acc BatchPoints\n\n\tacc.Debug = true\n\n\tfor _, plugin := range a.plugins {\n\t\tacc.Prefix = plugin.name + \"_\"\n\t\tacc.Config = plugin.config\n\n\t\tfmt.Printf(\"* Plugin: %s\\n\", plugin.name)\n\t\tif plugin.config.Interval != 0 {\n\t\t\tfmt.Printf(\"* Internal: %s\\n\", plugin.config.Interval)\n\t\t}\n\n\t\terr := plugin.plugin.Gather(&acc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Run runs the agent daemon, gathering every Interval\nfunc (a *Agent) Run(shutdown chan struct{}) error {\n\tvar wg sync.WaitGroup\n\n\tfor _, plugin := range a.plugins {\n\t\tif plugin.config.Interval != 0 {\n\t\t\twg.Add(1)\n\t\t\tgo func(plugin *runningPlugin) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\ta.crankSeparate(shutdown, plugin)\n\t\t\t}(plugin)\n\t\t}\n\t}\n\n\tdefer wg.Wait()\n\n\tticker := time.NewTicker(a.Interval.Duration)\n\n\tfor {\n\t\terr := a.crankParallel()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error in plugins: %s\", err)\n\t\t}\n\n\t\tselect {\n\t\tcase <-shutdown:\n\t\t\treturn nil\n\t\tcase <-ticker.C:\n\t\t\tcontinue\n\t\t}\n\t}\n}\n<commit_msg>Log plugin errors in crankParallel and crankSeparate cases. Previously errors weren't logged in these cases.<commit_after>package telegraf\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/influxdb\/telegraf\/outputs\"\n\t\"github.com\/influxdb\/telegraf\/plugins\"\n)\n\ntype runningOutput struct {\n\tname   string\n\toutput outputs.Output\n}\n\ntype runningPlugin struct {\n\tname   string\n\tplugin plugins.Plugin\n\tconfig *ConfiguredPlugin\n}\n\n\/\/ Agent runs telegraf and collects data based on the given config\ntype Agent struct {\n\n\t\/\/ Interval at which to gather information\n\tInterval Duration\n\n\t\/\/ Run in debug mode?\n\tDebug    bool\n\tHostname string\n\n\tConfig *Config\n\n\toutputs []*runningOutput\n\tplugins []*runningPlugin\n}\n\n\/\/ NewAgent returns an Agent struct based off the given Config\nfunc NewAgent(config *Config) (*Agent, error) {\n\tagent := &Agent{Config: config, Interval: Duration{10 * time.Second}}\n\n\terr := config.ApplyAgent(agent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif agent.Hostname == \"\" {\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tagent.Hostname = hostname\n\t}\n\n\tif config.Tags == nil {\n\t\tconfig.Tags = map[string]string{}\n\t}\n\n\tconfig.Tags[\"host\"] = agent.Hostname\n\n\treturn agent, nil\n}\n\n\/\/ Connect connects to all configured outputs\nfunc (a *Agent) Connect() error {\n\tfor _, o := range a.outputs {\n\t\terr := o.output.Connect()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Close closes the connection to all configured outputs\nfunc (a *Agent) Close() error {\n\tvar err error\n\tfor _, o := range a.outputs {\n\t\terr = o.output.Close()\n\t}\n\treturn err\n}\n\n\/\/ LoadOutputs loads the agent's outputs\nfunc (a *Agent) LoadOutputs() ([]string, error) {\n\tvar names []string\n\n\tfor _, name := range a.Config.OutputsDeclared() {\n\t\tcreator, ok := outputs.Outputs[name]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Undefined but requested output: %s\", name)\n\t\t}\n\n\t\toutput := creator()\n\n\t\terr := a.Config.ApplyOutput(name, output)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ta.outputs = append(a.outputs, &runningOutput{name, output})\n\t\tnames = append(names, name)\n\t}\n\n\tsort.Strings(names)\n\n\treturn names, nil\n}\n\n\/\/ LoadPlugins loads the agent's plugins\nfunc (a *Agent) LoadPlugins(pluginsFilter string) ([]string, error) {\n\tvar names []string\n\tvar filters []string\n\n\tpluginsFilter = strings.TrimSpace(pluginsFilter)\n\tif pluginsFilter != \"\" {\n\t\tfilters = strings.Split(\":\"+pluginsFilter+\":\", \":\")\n\t}\n\n\tfor _, name := range a.Config.PluginsDeclared() {\n\t\tcreator, ok := plugins.Plugins[name]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"Undefined but requested plugin: %s\", name)\n\t\t}\n\n\t\tisPluginEnabled := false\n\t\tif len(filters) > 0 {\n\t\t\tfor _, runeValue := range filters {\n\t\t\t\tif runeValue != \"\" && strings.ToLower(runeValue) == strings.ToLower(name) {\n\t\t\t\t\tfmt.Printf(\"plugin [%s] is enabled (filter options)\\n\", name)\n\t\t\t\t\tisPluginEnabled = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ if no filter, we ALWAYS accept the plugin\n\t\t\tisPluginEnabled = true\n\t\t}\n\n\t\tif isPluginEnabled {\n\t\t\tplugin := creator()\n\t\t\tconfig, err := a.Config.ApplyPlugin(name, plugin)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\ta.plugins = append(a.plugins, &runningPlugin{name, plugin, config})\n\t\t\tnames = append(names, name)\n\t\t}\n\t}\n\n\tsort.Strings(names)\n\n\treturn names, nil\n}\n\nfunc (a *Agent) crankParallel() error {\n\tpoints := make(chan *BatchPoints, len(a.plugins))\n\n\tvar wg sync.WaitGroup\n\n\tfor _, plugin := range a.plugins {\n\t\tif plugin.config.Interval != 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func(plugin *runningPlugin) {\n\t\t\tdefer wg.Done()\n\n\t\t\tvar acc BatchPoints\n\t\t\tacc.Debug = a.Debug\n\t\t\tacc.Prefix = plugin.name + \"_\"\n\t\t\tacc.Config = plugin.config\n\n\t\t\terr := plugin.plugin.Gather(&acc)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error in plugins: %s\", err)\n\t\t\t}\n\n\n\t\t\tpoints <- &acc\n\t\t}(plugin)\n\t}\n\n\twg.Wait()\n\n\tclose(points)\n\n\tvar bp BatchPoints\n\tbp.Time = time.Now()\n\tbp.Tags = a.Config.Tags\n\n\tfor sub := range points {\n\t\tbp.Points = append(bp.Points, sub.Points...)\n\t}\n\n\treturn a.flush(&bp)\n}\n\nfunc (a *Agent) crank() error {\n\tvar bp BatchPoints\n\n\tbp.Debug = a.Debug\n\n\tfor _, plugin := range a.plugins {\n\t\tbp.Prefix = plugin.name + \"_\"\n\t\tbp.Config = plugin.config\n\t\terr := plugin.plugin.Gather(&bp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tbp.Time = time.Now()\n\tbp.Tags = a.Config.Tags\n\n\treturn a.flush(&bp)\n}\n\nfunc (a *Agent) crankSeparate(shutdown chan struct{}, plugin *runningPlugin) error {\n\tticker := time.NewTicker(plugin.config.Interval)\n\n\tfor {\n\t\tvar bp BatchPoints\n\n\t\tbp.Debug = a.Debug\n\n\t\tbp.Prefix = plugin.name + \"_\"\n\t\tbp.Config = plugin.config\n\t\terr := plugin.plugin.Gather(&bp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbp.Tags = a.Config.Tags\n\t\tbp.Time = time.Now()\n\n\t\terr = a.flush(&bp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tselect {\n\t\tcase <-shutdown:\n\t\t\treturn nil\n\t\tcase <-ticker.C:\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\nfunc (a *Agent) flush(bp *BatchPoints) error {\n\tvar wg sync.WaitGroup\n\tvar outerr error\n\tfor _, o := range a.outputs {\n\t\twg.Add(1)\n\t\tgo func(ro *runningOutput) {\n\t\t\tdefer wg.Done()\n\t\t\touterr = ro.output.Write(bp.BatchPoints)\n\t\t}(o)\n\t}\n\n\twg.Wait()\n\n\treturn outerr\n}\n\n\/\/ TestAllPlugins verifies that we can 'Gather' from all plugins with the\n\/\/ default configuration\nfunc (a *Agent) TestAllPlugins() error {\n\tvar names []string\n\n\tfor name := range plugins.Plugins {\n\t\tnames = append(names, name)\n\t}\n\n\tsort.Strings(names)\n\n\tvar acc BatchPoints\n\tacc.Debug = true\n\n\tfmt.Printf(\"* Testing all plugins with default configuration\\n\")\n\n\tfor _, name := range names {\n\t\tplugin := plugins.Plugins[name]()\n\n\t\tfmt.Printf(\"* Plugin: %s\\n\", name)\n\n\t\tacc.Prefix = name + \"_\"\n\t\terr := plugin.Gather(&acc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Test verifies that we can 'Gather' from all plugins with their configured\n\/\/ Config struct\nfunc (a *Agent) Test() error {\n\tvar acc BatchPoints\n\n\tacc.Debug = true\n\n\tfor _, plugin := range a.plugins {\n\t\tacc.Prefix = plugin.name + \"_\"\n\t\tacc.Config = plugin.config\n\n\t\tfmt.Printf(\"* Plugin: %s\\n\", plugin.name)\n\t\tif plugin.config.Interval != 0 {\n\t\t\tfmt.Printf(\"* Internal: %s\\n\", plugin.config.Interval)\n\t\t}\n\n\t\terr := plugin.plugin.Gather(&acc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Run runs the agent daemon, gathering every Interval\nfunc (a *Agent) Run(shutdown chan struct{}) error {\n\tvar wg sync.WaitGroup\n\n\tfor _, plugin := range a.plugins {\n\t\tif plugin.config.Interval != 0 {\n\t\t\twg.Add(1)\n\t\t\tgo func(plugin *runningPlugin) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\terr := a.crankSeparate(shutdown, plugin)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Error in plugins: %s\", err)\n\t\t\t\t}\n\t\t\t}(plugin)\n\t\t}\n\t}\n\n\tdefer wg.Wait()\n\n\tticker := time.NewTicker(a.Interval.Duration)\n\n\tfor {\n\t\terr := a.crankParallel()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error in plugins: %s\", err)\n\t\t}\n\n\t\tselect {\n\t\tcase <-shutdown:\n\t\t\treturn nil\n\t\tcase <-ticker.C:\n\t\t\tcontinue\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gosnmp\n\ntype Agent struct {\n\tsnmpContext\n}\n\nfunc NewAgent(name string, maxTargets int, logger Logger) *Agent {\n\treturn NewAgentWithPort(name, maxTargets, 161, logger)\n}\n\nfunc NewAgentWithPort(name string, maxTargets int, port int, logger Logger) *Agent {\n\tagent := new(Agent)\n\tagent.snmpContext = *newContext(name, maxTargets, false, port, logger)\n\treturn agent\n}\n\nfunc (ctxt *snmpContext) processIncomingRequest(req SnmpRequest) {\n\n}\n<commit_msg>Add BasicOidHandler interface<commit_after>package gosnmp\n\ntype Agent struct {\n\tsnmpContext\n}\n\nfunc NewAgent(name string, maxTargets int, logger Logger) *Agent {\n\treturn NewAgentWithPort(name, maxTargets, 161, logger)\n}\n\nfunc NewAgentWithPort(name string, maxTargets int, port int, logger Logger) *Agent {\n\tagent := new(Agent)\n\tagent.snmpContext = *newContext(name, maxTargets, false, port, logger)\n\treturn agent\n}\n\nfunc (ctxt *snmpContext) processIncomingRequest(req SnmpRequest) {\n\n}\n\ntype BasicOidHandler interface {\n\tGet(Varbind) error\n\tSet(Varbind) error\n}\n\nfunc (agent *Agent) register<|endoftext|>"}
{"text":"<commit_before>package fzf\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"sort\"\n\t\"time\"\n)\n\ntype MatchRequest struct {\n\tchunks  []*Chunk\n\tpattern *Pattern\n}\n\ntype Matcher struct {\n\tpatternBuilder func([]rune) *Pattern\n\tsort           bool\n\teventBox       *EventBox\n\treqBox         *EventBox\n\tpartitions     int\n\tqueryCache     QueryCache\n}\n\nconst (\n\tREQ_RETRY EventType = iota\n\tREQ_RESET\n)\n\nconst (\n\tSTAT_CANCELLED int = iota\n\tSTAT_QCH\n\tSTAT_CHUNKS\n)\n\nconst (\n\tPROGRESS_MIN_DURATION = 200 * time.Millisecond\n)\n\nfunc NewMatcher(patternBuilder func([]rune) *Pattern,\n\tsort bool, eventBox *EventBox) *Matcher {\n\treturn &Matcher{\n\t\tpatternBuilder: patternBuilder,\n\t\tsort:           sort,\n\t\teventBox:       eventBox,\n\t\treqBox:         NewEventBox(),\n\t\tpartitions:     runtime.NumCPU(),\n\t\tqueryCache:     make(QueryCache)}\n}\n\nfunc (m *Matcher) Loop() {\n\tprevCount := 0\n\n\tfor {\n\t\tvar request MatchRequest\n\n\t\tm.reqBox.Wait(func(events *Events) {\n\t\t\tfor _, val := range *events {\n\t\t\t\tswitch val := val.(type) {\n\t\t\t\tcase MatchRequest:\n\t\t\t\t\trequest = val\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(fmt.Sprintf(\"Unexpected type: %T\", val))\n\t\t\t\t}\n\t\t\t}\n\t\t\tevents.Clear()\n\t\t})\n\n\t\t\/\/ Restart search\n\t\tpatternString := request.pattern.AsString()\n\t\tallMatches := []*Item{}\n\t\tcancelled := false\n\t\tcount := CountItems(request.chunks)\n\n\t\tfoundCache := false\n\t\tif count == prevCount {\n\t\t\t\/\/ Look up queryCache\n\t\t\tif cached, found := m.queryCache[patternString]; found {\n\t\t\t\tfoundCache = true\n\t\t\t\tallMatches = cached\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Invalidate queryCache\n\t\t\tprevCount = count\n\t\t\tm.queryCache = make(QueryCache)\n\t\t}\n\n\t\tif !foundCache {\n\t\t\tallMatches, cancelled = m.scan(request, 0)\n\t\t}\n\n\t\tif !cancelled {\n\t\t\tm.queryCache[patternString] = allMatches\n\t\t\tm.eventBox.Set(EVT_SEARCH_FIN, allMatches)\n\t\t}\n\t}\n}\n\nfunc (m *Matcher) sliceChunks(chunks []*Chunk) [][]*Chunk {\n\tperSlice := len(chunks) \/ m.partitions\n\n\t\/\/ No need to parallelize\n\tif perSlice == 0 {\n\t\treturn [][]*Chunk{chunks}\n\t}\n\n\tslices := make([][]*Chunk, m.partitions)\n\tfor i := 0; i < m.partitions; i++ {\n\t\tstart := i * perSlice\n\t\tend := start + perSlice\n\t\tif i == m.partitions-1 {\n\t\t\tend = len(chunks)\n\t\t}\n\t\tslices[i] = chunks[start:end]\n\t}\n\treturn slices\n}\n\ntype partialResult struct {\n\tindex   int\n\tmatches []*Item\n}\n\nfunc (m *Matcher) scan(request MatchRequest, limit int) ([]*Item, bool) {\n\tstartedAt := time.Now()\n\n\tnumChunks := len(request.chunks)\n\tif numChunks == 0 {\n\t\treturn []*Item{}, false\n\t}\n\tpattern := request.pattern\n\tempty := pattern.IsEmpty()\n\tcancelled := NewAtomicBool(false)\n\n\tslices := m.sliceChunks(request.chunks)\n\tnumSlices := len(slices)\n\tresultChan := make(chan partialResult, numSlices)\n\tcountChan := make(chan int, numSlices)\n\n\tfor idx, chunks := range slices {\n\t\tgo func(idx int, chunks []*Chunk) {\n\t\t\tsliceMatches := []*Item{}\n\t\t\tfor _, chunk := range chunks {\n\t\t\t\tvar matches []*Item\n\t\t\t\tif empty {\n\t\t\t\t\tmatches = *chunk\n\t\t\t\t} else {\n\t\t\t\t\tmatches = request.pattern.Match(chunk)\n\t\t\t\t}\n\t\t\t\tsliceMatches = append(sliceMatches, matches...)\n\t\t\t\tif cancelled.Get() {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcountChan <- len(sliceMatches)\n\t\t\t}\n\t\t\tif !empty && m.sort {\n\t\t\t\tsort.Sort(ByRelevance(sliceMatches))\n\t\t\t}\n\t\t\tresultChan <- partialResult{idx, sliceMatches}\n\t\t}(idx, chunks)\n\t}\n\n\tcount := 0\n\tmatchCount := 0\n\tfor matchesInChunk := range countChan {\n\t\tcount += 1\n\t\tmatchCount += matchesInChunk\n\n\t\tif limit > 0 && matchCount > limit {\n\t\t\treturn nil, true \/\/ For --select-1 and --exit-0\n\t\t}\n\n\t\tif count == numChunks {\n\t\t\tbreak\n\t\t}\n\n\t\tif !empty && m.reqBox.Peak(REQ_RESET) {\n\t\t\tcancelled.Set(true)\n\t\t\treturn nil, true\n\t\t}\n\n\t\tif time.Now().Sub(startedAt) > PROGRESS_MIN_DURATION {\n\t\t\tm.eventBox.Set(EVT_SEARCH_PROGRESS, float32(count)\/float32(numChunks))\n\t\t}\n\t}\n\n\tpartialResults := make([][]*Item, numSlices)\n\tfor range slices {\n\t\tpartialResult := <-resultChan\n\t\tpartialResults[partialResult.index] = partialResult.matches\n\t}\n\n\tvar allMatches []*Item\n\tif empty || !m.sort {\n\t\tallMatches = []*Item{}\n\t\tfor _, matches := range partialResults {\n\t\t\tallMatches = append(allMatches, matches...)\n\t\t}\n\t} else {\n\t\tallMatches = SortMerge(partialResults)\n\t}\n\n\treturn allMatches, false\n}\n\nfunc (m *Matcher) Reset(chunks []*Chunk, patternRunes []rune, cancel bool) {\n\tpattern := m.patternBuilder(patternRunes)\n\n\tvar event EventType\n\tif cancel {\n\t\tevent = REQ_RESET\n\t} else {\n\t\tevent = REQ_RETRY\n\t}\n\tm.reqBox.Set(event, MatchRequest{chunks, pattern})\n}\n<commit_msg>Fix scan limit for --select-1 and --exit-0 options<commit_after>package fzf\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"sort\"\n\t\"time\"\n)\n\ntype MatchRequest struct {\n\tchunks  []*Chunk\n\tpattern *Pattern\n}\n\ntype Matcher struct {\n\tpatternBuilder func([]rune) *Pattern\n\tsort           bool\n\teventBox       *EventBox\n\treqBox         *EventBox\n\tpartitions     int\n\tqueryCache     QueryCache\n}\n\nconst (\n\tREQ_RETRY EventType = iota\n\tREQ_RESET\n)\n\nconst (\n\tSTAT_CANCELLED int = iota\n\tSTAT_QCH\n\tSTAT_CHUNKS\n)\n\nconst (\n\tPROGRESS_MIN_DURATION = 200 * time.Millisecond\n)\n\nfunc NewMatcher(patternBuilder func([]rune) *Pattern,\n\tsort bool, eventBox *EventBox) *Matcher {\n\treturn &Matcher{\n\t\tpatternBuilder: patternBuilder,\n\t\tsort:           sort,\n\t\teventBox:       eventBox,\n\t\treqBox:         NewEventBox(),\n\t\tpartitions:     runtime.NumCPU(),\n\t\tqueryCache:     make(QueryCache)}\n}\n\nfunc (m *Matcher) Loop() {\n\tprevCount := 0\n\n\tfor {\n\t\tvar request MatchRequest\n\n\t\tm.reqBox.Wait(func(events *Events) {\n\t\t\tfor _, val := range *events {\n\t\t\t\tswitch val := val.(type) {\n\t\t\t\tcase MatchRequest:\n\t\t\t\t\trequest = val\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(fmt.Sprintf(\"Unexpected type: %T\", val))\n\t\t\t\t}\n\t\t\t}\n\t\t\tevents.Clear()\n\t\t})\n\n\t\t\/\/ Restart search\n\t\tpatternString := request.pattern.AsString()\n\t\tallMatches := []*Item{}\n\t\tcancelled := false\n\t\tcount := CountItems(request.chunks)\n\n\t\tfoundCache := false\n\t\tif count == prevCount {\n\t\t\t\/\/ Look up queryCache\n\t\t\tif cached, found := m.queryCache[patternString]; found {\n\t\t\t\tfoundCache = true\n\t\t\t\tallMatches = cached\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Invalidate queryCache\n\t\t\tprevCount = count\n\t\t\tm.queryCache = make(QueryCache)\n\t\t}\n\n\t\tif !foundCache {\n\t\t\tallMatches, cancelled = m.scan(request, 0)\n\t\t}\n\n\t\tif !cancelled {\n\t\t\tm.queryCache[patternString] = allMatches\n\t\t\tm.eventBox.Set(EVT_SEARCH_FIN, allMatches)\n\t\t}\n\t}\n}\n\nfunc (m *Matcher) sliceChunks(chunks []*Chunk) [][]*Chunk {\n\tperSlice := len(chunks) \/ m.partitions\n\n\t\/\/ No need to parallelize\n\tif perSlice == 0 {\n\t\treturn [][]*Chunk{chunks}\n\t}\n\n\tslices := make([][]*Chunk, m.partitions)\n\tfor i := 0; i < m.partitions; i++ {\n\t\tstart := i * perSlice\n\t\tend := start + perSlice\n\t\tif i == m.partitions-1 {\n\t\t\tend = len(chunks)\n\t\t}\n\t\tslices[i] = chunks[start:end]\n\t}\n\treturn slices\n}\n\ntype partialResult struct {\n\tindex   int\n\tmatches []*Item\n}\n\nfunc (m *Matcher) scan(request MatchRequest, limit int) ([]*Item, bool) {\n\tstartedAt := time.Now()\n\n\tnumChunks := len(request.chunks)\n\tif numChunks == 0 {\n\t\treturn []*Item{}, false\n\t}\n\tpattern := request.pattern\n\tempty := pattern.IsEmpty()\n\tcancelled := NewAtomicBool(false)\n\n\tslices := m.sliceChunks(request.chunks)\n\tnumSlices := len(slices)\n\tresultChan := make(chan partialResult, numSlices)\n\tcountChan := make(chan int, numSlices)\n\n\tfor idx, chunks := range slices {\n\t\tgo func(idx int, chunks []*Chunk) {\n\t\t\tsliceMatches := []*Item{}\n\t\t\tfor _, chunk := range chunks {\n\t\t\t\tvar matches []*Item\n\t\t\t\tif empty {\n\t\t\t\t\tmatches = *chunk\n\t\t\t\t} else {\n\t\t\t\t\tmatches = request.pattern.Match(chunk)\n\t\t\t\t}\n\t\t\t\tsliceMatches = append(sliceMatches, matches...)\n\t\t\t\tif cancelled.Get() {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcountChan <- len(matches)\n\t\t\t}\n\t\t\tif !empty && m.sort {\n\t\t\t\tsort.Sort(ByRelevance(sliceMatches))\n\t\t\t}\n\t\t\tresultChan <- partialResult{idx, sliceMatches}\n\t\t}(idx, chunks)\n\t}\n\n\tcount := 0\n\tmatchCount := 0\n\tfor matchesInChunk := range countChan {\n\t\tcount += 1\n\t\tmatchCount += matchesInChunk\n\n\t\tif limit > 0 && matchCount > limit {\n\t\t\treturn nil, true \/\/ For --select-1 and --exit-0\n\t\t}\n\n\t\tif count == numChunks {\n\t\t\tbreak\n\t\t}\n\n\t\tif !empty && m.reqBox.Peak(REQ_RESET) {\n\t\t\tcancelled.Set(true)\n\t\t\treturn nil, true\n\t\t}\n\n\t\tif time.Now().Sub(startedAt) > PROGRESS_MIN_DURATION {\n\t\t\tm.eventBox.Set(EVT_SEARCH_PROGRESS, float32(count)\/float32(numChunks))\n\t\t}\n\t}\n\n\tpartialResults := make([][]*Item, numSlices)\n\tfor range slices {\n\t\tpartialResult := <-resultChan\n\t\tpartialResults[partialResult.index] = partialResult.matches\n\t}\n\n\tvar allMatches []*Item\n\tif empty || !m.sort {\n\t\tallMatches = []*Item{}\n\t\tfor _, matches := range partialResults {\n\t\t\tallMatches = append(allMatches, matches...)\n\t\t}\n\t} else {\n\t\tallMatches = SortMerge(partialResults)\n\t}\n\n\treturn allMatches, false\n}\n\nfunc (m *Matcher) Reset(chunks []*Chunk, patternRunes []rune, cancel bool) {\n\tpattern := m.patternBuilder(patternRunes)\n\n\tvar event EventType\n\tif cancel {\n\t\tevent = REQ_RESET\n\t} else {\n\t\tevent = REQ_RETRY\n\t}\n\tm.reqBox.Set(event, MatchRequest{chunks, pattern})\n}\n<|endoftext|>"}
{"text":"<commit_before>package local\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com\/docker\/docker\/api\/types\/plugins\/logdriver\"\n\t\"github.com\/docker\/docker\/daemon\/logger\"\n\t\"github.com\/docker\/docker\/daemon\/logger\/loggerutils\"\n\t\"github.com\/docker\/docker\/errdefs\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ maxMsgLen is the maximum size of the logger.Message after serialization.\n\/\/ logger.defaultBufSize caps the size of Line field.\nconst maxMsgLen int = 1e6 \/\/ 1MB.\n\nfunc (d *driver) ReadLogs(config logger.ReadConfig) *logger.LogWatcher {\n\treturn d.logfile.ReadLogs(config)\n}\n\nfunc getTailReader(ctx context.Context, r loggerutils.SizeReaderAt, req int) (io.Reader, int, error) {\n\tsize := r.Size()\n\tif req < 0 {\n\t\treturn nil, 0, errdefs.InvalidParameter(errors.Errorf(\"invalid number of lines to tail: %d\", req))\n\t}\n\n\tif size < (encodeBinaryLen*2)+1 {\n\t\treturn bytes.NewReader(nil), 0, nil\n\t}\n\n\tconst encodeBinaryLen64 = int64(encodeBinaryLen)\n\tvar found int\n\n\tbuf := make([]byte, encodeBinaryLen)\n\n\toffset := size\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, 0, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\tn, err := r.ReadAt(buf, offset-encodeBinaryLen64)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, 0, errors.Wrap(err, \"error reading log message footer\")\n\t\t}\n\n\t\tif n != encodeBinaryLen {\n\t\t\treturn nil, 0, errdefs.DataLoss(errors.New(\"unexpected number of bytes read from log message footer\"))\n\t\t}\n\n\t\tmsgLen := binary.BigEndian.Uint32(buf)\n\n\t\tn, err = r.ReadAt(buf, offset-encodeBinaryLen64-encodeBinaryLen64-int64(msgLen))\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, 0, errors.Wrap(err, \"error reading log message header\")\n\t\t}\n\n\t\tif n != encodeBinaryLen {\n\t\t\treturn nil, 0, errdefs.DataLoss(errors.New(\"unexpected number of bytes read from log message header\"))\n\t\t}\n\n\t\tif msgLen != binary.BigEndian.Uint32(buf) {\n\t\t\treturn nil, 0, errdefs.DataLoss(errors.Wrap(err, \"log message header and footer indicate different message sizes\"))\n\t\t}\n\n\t\tfound++\n\t\toffset -= int64(msgLen)\n\t\toffset -= encodeBinaryLen64 * 2\n\t\tif found == req {\n\t\t\tbreak\n\t\t}\n\t\tif offset <= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn io.NewSectionReader(r, offset, size), found, nil\n}\n\ntype decoder struct {\n\trdr   io.Reader\n\tproto *logdriver.LogEntry\n\t\/\/ buf keeps bytes from rdr.\n\tbuf []byte\n\t\/\/ offset is the position in buf.\n\t\/\/ If offset > 0, buf[offset:] has bytes which are read but haven't used.\n\toffset int\n\t\/\/ nextMsgLen is the length of the next log message.\n\t\/\/ If nextMsgLen = 0, a new value must be read from rdr.\n\tnextMsgLen int\n}\n\nfunc (d *decoder) readRecord(size int) error {\n\tvar err error\n\tfor i := 0; i < maxDecodeRetry; i++ {\n\t\tvar n int\n\t\tn, err = io.ReadFull(d.rdr, d.buf[d.offset:size])\n\t\td.offset += n\n\t\tif err != nil {\n\t\t\tif err != io.ErrUnexpectedEOF {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\td.offset = 0\n\treturn nil\n}\n\nfunc (d *decoder) Decode() (*logger.Message, error) {\n\tif d.proto == nil {\n\t\td.proto = &logdriver.LogEntry{}\n\t} else {\n\t\tresetProto(d.proto)\n\t}\n\tif d.buf == nil {\n\t\td.buf = make([]byte, initialBufSize)\n\t}\n\n\tif d.nextMsgLen == 0 {\n\t\tmsgLen, err := d.decodeSizeHeader()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif msgLen > maxMsgLen {\n\t\t\treturn nil, fmt.Errorf(\"log message is too large (%d > %d)\", msgLen, maxMsgLen)\n\t\t}\n\n\t\tif len(d.buf) < msgLen+encodeBinaryLen {\n\t\t\td.buf = make([]byte, msgLen+encodeBinaryLen)\n\t\t} else if msgLen <= initialBufSize {\n\t\t\td.buf = d.buf[:initialBufSize]\n\t\t} else {\n\t\t\td.buf = d.buf[:msgLen+encodeBinaryLen]\n\t\t}\n\n\t\td.nextMsgLen = msgLen\n\t}\n\treturn d.decodeLogEntry()\n}\n\nfunc (d *decoder) Reset(rdr io.Reader) {\n\tif d.rdr == rdr {\n\t\treturn\n\t}\n\n\td.rdr = rdr\n\tif d.proto != nil {\n\t\tresetProto(d.proto)\n\t}\n\tif d.buf != nil {\n\t\td.buf = d.buf[:initialBufSize]\n\t}\n\td.offset = 0\n\td.nextMsgLen = 0\n}\n\nfunc (d *decoder) Close() {\n\td.buf = d.buf[:0]\n\td.buf = nil\n\tif d.proto != nil {\n\t\tresetProto(d.proto)\n\t}\n\td.rdr = nil\n}\n\nfunc decodeFunc(rdr io.Reader) loggerutils.Decoder {\n\treturn &decoder{rdr: rdr}\n}\n\nfunc (d *decoder) decodeSizeHeader() (int, error) {\n\terr := d.readRecord(encodeBinaryLen)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"could not read a size header\")\n\t}\n\n\tmsgLen := int(binary.BigEndian.Uint32(d.buf[:encodeBinaryLen]))\n\treturn msgLen, nil\n}\n\nfunc (d *decoder) decodeLogEntry() (*logger.Message, error) {\n\tmsgLen := d.nextMsgLen\n\terr := d.readRecord(msgLen + encodeBinaryLen)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not read a log entry (size=%d+%d)\", msgLen, encodeBinaryLen)\n\t}\n\td.nextMsgLen = 0\n\n\tif err := d.proto.Unmarshal(d.buf[:msgLen]); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error unmarshalling log entry (size=%d)\", msgLen)\n\t}\n\n\tmsg := protoToMessage(d.proto)\n\tif msg.PLogMetaData == nil {\n\t\tmsg.Line = append(msg.Line, '\\n')\n\t}\n\n\treturn msg, nil\n}\n<commit_msg>daemon\/logger\/local: fix appending newlines<commit_after>package local\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com\/docker\/docker\/api\/types\/plugins\/logdriver\"\n\t\"github.com\/docker\/docker\/daemon\/logger\"\n\t\"github.com\/docker\/docker\/daemon\/logger\/loggerutils\"\n\t\"github.com\/docker\/docker\/errdefs\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ maxMsgLen is the maximum size of the logger.Message after serialization.\n\/\/ logger.defaultBufSize caps the size of Line field.\nconst maxMsgLen int = 1e6 \/\/ 1MB.\n\nfunc (d *driver) ReadLogs(config logger.ReadConfig) *logger.LogWatcher {\n\treturn d.logfile.ReadLogs(config)\n}\n\nfunc getTailReader(ctx context.Context, r loggerutils.SizeReaderAt, req int) (io.Reader, int, error) {\n\tsize := r.Size()\n\tif req < 0 {\n\t\treturn nil, 0, errdefs.InvalidParameter(errors.Errorf(\"invalid number of lines to tail: %d\", req))\n\t}\n\n\tif size < (encodeBinaryLen*2)+1 {\n\t\treturn bytes.NewReader(nil), 0, nil\n\t}\n\n\tconst encodeBinaryLen64 = int64(encodeBinaryLen)\n\tvar found int\n\n\tbuf := make([]byte, encodeBinaryLen)\n\n\toffset := size\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil, 0, ctx.Err()\n\t\tdefault:\n\t\t}\n\n\t\tn, err := r.ReadAt(buf, offset-encodeBinaryLen64)\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, 0, errors.Wrap(err, \"error reading log message footer\")\n\t\t}\n\n\t\tif n != encodeBinaryLen {\n\t\t\treturn nil, 0, errdefs.DataLoss(errors.New(\"unexpected number of bytes read from log message footer\"))\n\t\t}\n\n\t\tmsgLen := binary.BigEndian.Uint32(buf)\n\n\t\tn, err = r.ReadAt(buf, offset-encodeBinaryLen64-encodeBinaryLen64-int64(msgLen))\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn nil, 0, errors.Wrap(err, \"error reading log message header\")\n\t\t}\n\n\t\tif n != encodeBinaryLen {\n\t\t\treturn nil, 0, errdefs.DataLoss(errors.New(\"unexpected number of bytes read from log message header\"))\n\t\t}\n\n\t\tif msgLen != binary.BigEndian.Uint32(buf) {\n\t\t\treturn nil, 0, errdefs.DataLoss(errors.Wrap(err, \"log message header and footer indicate different message sizes\"))\n\t\t}\n\n\t\tfound++\n\t\toffset -= int64(msgLen)\n\t\toffset -= encodeBinaryLen64 * 2\n\t\tif found == req {\n\t\t\tbreak\n\t\t}\n\t\tif offset <= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn io.NewSectionReader(r, offset, size), found, nil\n}\n\ntype decoder struct {\n\trdr   io.Reader\n\tproto *logdriver.LogEntry\n\t\/\/ buf keeps bytes from rdr.\n\tbuf []byte\n\t\/\/ offset is the position in buf.\n\t\/\/ If offset > 0, buf[offset:] has bytes which are read but haven't used.\n\toffset int\n\t\/\/ nextMsgLen is the length of the next log message.\n\t\/\/ If nextMsgLen = 0, a new value must be read from rdr.\n\tnextMsgLen int\n}\n\nfunc (d *decoder) readRecord(size int) error {\n\tvar err error\n\tfor i := 0; i < maxDecodeRetry; i++ {\n\t\tvar n int\n\t\tn, err = io.ReadFull(d.rdr, d.buf[d.offset:size])\n\t\td.offset += n\n\t\tif err != nil {\n\t\t\tif err != io.ErrUnexpectedEOF {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\td.offset = 0\n\treturn nil\n}\n\nfunc (d *decoder) Decode() (*logger.Message, error) {\n\tif d.proto == nil {\n\t\td.proto = &logdriver.LogEntry{}\n\t} else {\n\t\tresetProto(d.proto)\n\t}\n\tif d.buf == nil {\n\t\td.buf = make([]byte, initialBufSize)\n\t}\n\n\tif d.nextMsgLen == 0 {\n\t\tmsgLen, err := d.decodeSizeHeader()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif msgLen > maxMsgLen {\n\t\t\treturn nil, fmt.Errorf(\"log message is too large (%d > %d)\", msgLen, maxMsgLen)\n\t\t}\n\n\t\tif len(d.buf) < msgLen+encodeBinaryLen {\n\t\t\td.buf = make([]byte, msgLen+encodeBinaryLen)\n\t\t} else if msgLen <= initialBufSize {\n\t\t\td.buf = d.buf[:initialBufSize]\n\t\t} else {\n\t\t\td.buf = d.buf[:msgLen+encodeBinaryLen]\n\t\t}\n\n\t\td.nextMsgLen = msgLen\n\t}\n\treturn d.decodeLogEntry()\n}\n\nfunc (d *decoder) Reset(rdr io.Reader) {\n\tif d.rdr == rdr {\n\t\treturn\n\t}\n\n\td.rdr = rdr\n\tif d.proto != nil {\n\t\tresetProto(d.proto)\n\t}\n\tif d.buf != nil {\n\t\td.buf = d.buf[:initialBufSize]\n\t}\n\td.offset = 0\n\td.nextMsgLen = 0\n}\n\nfunc (d *decoder) Close() {\n\td.buf = d.buf[:0]\n\td.buf = nil\n\tif d.proto != nil {\n\t\tresetProto(d.proto)\n\t}\n\td.rdr = nil\n}\n\nfunc decodeFunc(rdr io.Reader) loggerutils.Decoder {\n\treturn &decoder{rdr: rdr}\n}\n\nfunc (d *decoder) decodeSizeHeader() (int, error) {\n\terr := d.readRecord(encodeBinaryLen)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"could not read a size header\")\n\t}\n\n\tmsgLen := int(binary.BigEndian.Uint32(d.buf[:encodeBinaryLen]))\n\treturn msgLen, nil\n}\n\nfunc (d *decoder) decodeLogEntry() (*logger.Message, error) {\n\tmsgLen := d.nextMsgLen\n\terr := d.readRecord(msgLen + encodeBinaryLen)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not read a log entry (size=%d+%d)\", msgLen, encodeBinaryLen)\n\t}\n\td.nextMsgLen = 0\n\n\tif err := d.proto.Unmarshal(d.buf[:msgLen]); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"error unmarshalling log entry (size=%d)\", msgLen)\n\t}\n\n\tmsg := protoToMessage(d.proto)\n\tif msg.PLogMetaData == nil || msg.PLogMetaData.Last {\n\t\tmsg.Line = append(msg.Line, '\\n')\n\t}\n\n\treturn msg, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com>\n\/\/ All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ +build darwin freebsd linux netbsd openbsd\n\npackage storage\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\ntype unixFileLock struct {\n\tf *os.File\n}\n\nfunc (fl *unixFileLock) release() error {\n\tif err := setFileLock(fl.f, false); err != nil {\n\t\treturn err\n\t}\n\treturn fl.f.Close()\n}\n\nfunc newFileLock(path string) (fl fileLock, err error) {\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0644)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = setFileLock(f, true)\n\tif err != nil {\n\t\tf.Close()\n\t\treturn\n\t}\n\tfl = &unixFileLock{f: f}\n\treturn\n}\n\nfunc setFileLock(f *os.File, lock bool) error {\n\thow := syscall.LOCK_UN\n\tif lock {\n\t\thow = syscall.LOCK_EX\n\t}\n\treturn syscall.Flock(int(f.Fd()), how|syscall.LOCK_NB)\n}\n\nfunc rename(oldpath, newpath string) error {\n\treturn os.Rename(oldpath, newpath)\n}\n\nfunc syncDir(name string) error {\n\tf, err := os.Open(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tif err := f.Sync(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>storage: Add support for dragonfly #59<commit_after>\/\/ Copyright (c) 2012, Suryandaru Triandana <syndtr@gmail.com>\n\/\/ All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ +build darwin dragonfly freebsd linux netbsd openbsd\n\npackage storage\n\nimport (\n\t\"os\"\n\t\"syscall\"\n)\n\ntype unixFileLock struct {\n\tf *os.File\n}\n\nfunc (fl *unixFileLock) release() error {\n\tif err := setFileLock(fl.f, false); err != nil {\n\t\treturn err\n\t}\n\treturn fl.f.Close()\n}\n\nfunc newFileLock(path string) (fl fileLock, err error) {\n\tf, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0644)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = setFileLock(f, true)\n\tif err != nil {\n\t\tf.Close()\n\t\treturn\n\t}\n\tfl = &unixFileLock{f: f}\n\treturn\n}\n\nfunc setFileLock(f *os.File, lock bool) error {\n\thow := syscall.LOCK_UN\n\tif lock {\n\t\thow = syscall.LOCK_EX\n\t}\n\treturn syscall.Flock(int(f.Fd()), how|syscall.LOCK_NB)\n}\n\nfunc rename(oldpath, newpath string) error {\n\treturn os.Rename(oldpath, newpath)\n}\n\nfunc syncDir(name string) error {\n\tf, err := os.Open(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tif err := f.Sync(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/hyperledger\/fabric\/core\/chaincode\/shim\"\n)\n\ntype SimpleChaincode struct {\n}\n\nfunc main() {\n\n\terr := shim.Start(new(SimpleChaincode))\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting Simple chaincode: %s\", err)\n\t}\n}\n\nfunc (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"incorrect number of args\")\n\t}\n\n\terr := stub.PutState(\"hello_world\", []byte(args[0]))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n\nfunc (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"invoke is running\" + function)\n\n\tif function == \"init\" {\n\t\treturn t.Init(stub, \"init\", args)\n\t} else if function == \"write\" {\n\t\treturn t.write(stub, args)\n\t}\n\tfmt.Println(\"invoke did not find func:\" + function)\n\n\treturn nil, errors.New(\"received unknow function\" + function)\n}\n\nfunc (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"query is running \" + function) \/\/log\n\tswitch function {\n\tcase \"read\":\n\t\treturn t.read(stub, args)\n\tcase \"read2\":\n\t\treturn t.read2(stub, args)\n\tcase \"helloworld\":\n\t\treturn t.helloworld()\n\tdefault:\n\t\tfmt.Println(\"query did not find func: \" + function)\n\t} \/\/根据输入的string类型参数function, 来决定使用哪个子函数。\n\n\treturn nil, errors.New(\"received unknow function: \" + function) \/\/如果没有的话，则返回失败\n}\n\nfunc (t *SimpleChaincode) read2(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tkey := args[0]\n\tresult := []byte(\"helloworld\" + key)\n\tvar err error\n\treturn result, err\n}\n\nfunc (t *SimpleChaincode) read3(stub shim.ChaincodeStubInterface) ([]byte, error) {\n\tresult := []byte(stub.GetTxID())\n\treturn result, nil\n}\n\nfunc (t *SimpleChaincode) helloworld() ([]byte, error) {\n\tresult := []byte(\"hello world\")\n\treturn result, nil\n}\n\nfunc (t *SimpleChaincode) write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tvar key, value string\n\tvar err error\n\tfmt.Println(\"running write()\")\n\n\tif len(args) != 2 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tkey = args[0]\n\tvalue = args[1]\n\n\terr = stub.PutState(key, []byte(value))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n\nfunc (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tvar key, jsonResp string\n\tvar err error\n\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"incorrect number of arguments. expecting 1\")\n\t}\n\n\tkey = args[0]\n\tvalAsbytes, err := stub.GetState(key)\n\n\tif err != nil {\n\t\tjsonResp = \"{\\\"Error\\\":\\\"Failed to get state for \" + key + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\treturn valAsbytes, nil\n}\n<commit_msg>fix bugs<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/hyperledger\/fabric\/core\/chaincode\/shim\"\n)\n\ntype SimpleChaincode struct {\n}\n\nfunc main() {\n\n\terr := shim.Start(new(SimpleChaincode))\n\tif err != nil {\n\t\tfmt.Printf(\"Error starting Simple chaincode: %s\", err)\n\t}\n}\n\nfunc (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"incorrect number of args\")\n\t}\n\n\terr := stub.PutState(\"hello_world\", []byte(args[0]))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n\nfunc (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"invoke is running\" + function)\n\n\tif function == \"init\" {\n\t\treturn t.Init(stub, \"init\", args)\n\t} else if function == \"write\" {\n\t\treturn t.write(stub, args)\n\t}\n\tfmt.Println(\"invoke did not find func:\" + function)\n\n\treturn nil, errors.New(\"received unknow function\" + function)\n}\n\nfunc (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"query is running \" + function) \/\/log\n\tswitch function {\n\tcase \"read\":\n\t\treturn t.read(stub, args)\n\tcase \"read2\":\n\t\treturn t.read2(stub, args)\n\tcase \"read3\":\n\t\treturn t.read3(stub)\n\tcase \"helloworld\":\n\t\treturn t.helloworld()\n\tdefault:\n\t\tfmt.Println(\"query did not find func: \" + function)\n\t} \/\/根据输入的string类型参数function, 来决定使用哪个子函数。\n\n\treturn nil, errors.New(\"received unknow function: \" + function) \/\/如果没有的话，则返回失败\n}\n\nfunc (t *SimpleChaincode) read2(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tkey := args[0]\n\tresult := []byte(\"helloworld\" + key)\n\tvar err error\n\treturn result, err\n}\n\nfunc (t *SimpleChaincode) read3(stub shim.ChaincodeStubInterface) ([]byte, error) {\n\tresult := []byte(stub.GetTxID())\n\treturn result, nil\n}\n\nfunc (t *SimpleChaincode) helloworld() ([]byte, error) {\n\tresult := []byte(\"hello world\")\n\treturn result, nil\n}\n\nfunc (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tvar key, jsonResp string\n\tvar err error\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"incorrect number of arguments. expecting 1\")\n\t}\n\tkey = args[0]\n\tvalAsbytes, err := stub.GetState(key)\n\n\tif err != nil {\n\t\tjsonResp = \"{\\\"Error\\\":\\\"Failed to get state for \" + key + \"\\\"}\"\n\t\treturn nil, errors.New(jsonResp)\n\t}\n\n\treturn valAsbytes, nil\n}\n\nfunc (t *SimpleChaincode) write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {\n\tvar key, value string\n\tvar err error\n\tfmt.Println(\"running write()\")\n\n\tif len(args) != 2 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting 2\")\n\t}\n\n\tkey = args[0]\n\tvalue = args[1]\n\n\terr = stub.PutState(key, []byte(value))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package v1alpha1\n\nimport (\n\tcrdutils \"github.com\/appscode\/kutil\/apiextensions\/v1beta1\"\n\tapiextensions \"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\/v1beta1\"\n)\n\nfunc (d DormantDatabase) OffshootName() string {\n\treturn d.Name\n}\n\nfunc (d DormantDatabase) ResourceShortCode() string {\n\treturn ResourceCodeDormantDatabase\n}\n\nfunc (d DormantDatabase) ResourceKind() string {\n\treturn ResourceKindDormantDatabase\n}\n\nfunc (d DormantDatabase) ResourceSingular() string {\n\treturn ResourceSingularDormantDatabase\n}\n\nfunc (d DormantDatabase) ResourcePlural() string {\n\treturn ResourcePluralDormantDatabase\n}\n\nfunc (d DormantDatabase) CustomResourceDefinition() *apiextensions.CustomResourceDefinition {\n\treturn crdutils.NewCustomResourceDefinition(crdutils.Config{\n\t\tGroup:         SchemeGroupVersion.Group,\n\t\tPlural:        ResourcePluralDormantDatabase,\n\t\tSingular:      ResourceSingularDormantDatabase,\n\t\tKind:          ResourceKindDormantDatabase,\n\t\tShortNames:    []string{ResourceCodeDormantDatabase},\n\t\tCategories:    []string{\"datastore\", \"kubedb\", \"appscode\", \"all\"},\n\t\tResourceScope: string(apiextensions.NamespaceScoped),\n\t\tVersions: []apiextensions.CustomResourceDefinitionVersion{\n\t\t\t{\n\t\t\t\tName:    SchemeGroupVersion.Version,\n\t\t\t\tServed:  true,\n\t\t\t\tStorage: true,\n\t\t\t},\n\t\t},\n\t\tLabels: crdutils.Labels{\n\t\t\tLabelsMap: map[string]string{\"app\": \"kubedb\"},\n\t\t},\n\t\tSpecDefinitionName:      \"github.com\/kubedb\/apimachinery\/apis\/kubedb\/v1alpha1.DormantDatabase\",\n\t\tEnableValidation:        false,\n\t\tGetOpenAPIDefinitions:   GetOpenAPIDefinitions,\n\t\tEnableStatusSubresource: EnableStatusSubresource,\n\t\tAdditionalPrinterColumns: []apiextensions.CustomResourceColumnDefinition{\n\t\t\t{\n\t\t\t\tName:     \"Status\",\n\t\t\t\tType:     \"string\",\n\t\t\t\tJSONPath: \".status.phase\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tName:     \"Age\",\n\t\t\t\tType:     \"date\",\n\t\t\t\tJSONPath: \".metadata.creationTimestamp\",\n\t\t\t},\n\t\t},\n\t}, setNameSchema)\n}\n\nfunc (d *DormantDatabase) Migrate() {\n\tif d == nil {\n\t\treturn\n\t}\n\td.Spec.Origin.Spec.Elasticsearch.Migrate()\n\td.Spec.Origin.Spec.Postgres.Migrate()\n\td.Spec.Origin.Spec.MySQL.Migrate()\n\td.Spec.Origin.Spec.MongoDB.Migrate()\n\td.Spec.Origin.Spec.Redis.Migrate()\n\td.Spec.Origin.Spec.Memcached.Migrate()\n\td.Spec.Origin.Spec.Etcd.Migrate()\n}\n<commit_msg>Add OffshootSelectors to DormantDatabase (#294)<commit_after>package v1alpha1\n\nimport (\n\tcrdutils \"github.com\/appscode\/kutil\/apiextensions\/v1beta1\"\n\tmeta_util \"github.com\/appscode\/kutil\/meta\"\n\tapiextensions \"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\/v1beta1\"\n)\n\nfunc (d DormantDatabase) OffshootSelectors() map[string]string {\n\tselector := map[string]string{\n\t\tLabelDatabaseName: d.Name,\n\t}\n\tswitch {\n\tcase d.Spec.Origin.Spec.Etcd != nil:\n\t\tselector[LabelDatabaseKind] = ResourceKindEtcd\n\tcase d.Spec.Origin.Spec.Elasticsearch != nil:\n\t\tselector[LabelDatabaseKind] = ResourceKindElasticsearch\n\tcase d.Spec.Origin.Spec.Memcached != nil:\n\t\tselector[LabelDatabaseKind] = ResourceKindMemcached\n\tcase d.Spec.Origin.Spec.MongoDB != nil:\n\t\tselector[LabelDatabaseKind] = ResourceKindMongoDB\n\tcase d.Spec.Origin.Spec.MySQL != nil:\n\t\tselector[LabelDatabaseKind] = ResourceKindMySQL\n\tcase d.Spec.Origin.Spec.Postgres != nil:\n\t\tselector[LabelDatabaseKind] = ResourceKindPostgres\n\tcase d.Spec.Origin.Spec.Redis != nil:\n\t\tselector[LabelDatabaseKind] = ResourceKindRedis\n\t}\n\treturn selector\n}\n\nfunc (d DormantDatabase) OffshootLabels() map[string]string {\n\treturn meta_util.FilterKeys(GenericKey, d.OffshootSelectors(), d.Spec.Origin.Labels)\n}\n\nfunc (d DormantDatabase) OffshootName() string {\n\treturn d.Name\n}\n\nfunc (d DormantDatabase) ResourceShortCode() string {\n\treturn ResourceCodeDormantDatabase\n}\n\nfunc (d DormantDatabase) ResourceKind() string {\n\treturn ResourceKindDormantDatabase\n}\n\nfunc (d DormantDatabase) ResourceSingular() string {\n\treturn ResourceSingularDormantDatabase\n}\n\nfunc (d DormantDatabase) ResourcePlural() string {\n\treturn ResourcePluralDormantDatabase\n}\n\nfunc (d DormantDatabase) CustomResourceDefinition() *apiextensions.CustomResourceDefinition {\n\treturn crdutils.NewCustomResourceDefinition(crdutils.Config{\n\t\tGroup:         SchemeGroupVersion.Group,\n\t\tPlural:        ResourcePluralDormantDatabase,\n\t\tSingular:      ResourceSingularDormantDatabase,\n\t\tKind:          ResourceKindDormantDatabase,\n\t\tShortNames:    []string{ResourceCodeDormantDatabase},\n\t\tCategories:    []string{\"datastore\", \"kubedb\", \"appscode\", \"all\"},\n\t\tResourceScope: string(apiextensions.NamespaceScoped),\n\t\tVersions: []apiextensions.CustomResourceDefinitionVersion{\n\t\t\t{\n\t\t\t\tName:    SchemeGroupVersion.Version,\n\t\t\t\tServed:  true,\n\t\t\t\tStorage: true,\n\t\t\t},\n\t\t},\n\t\tLabels: crdutils.Labels{\n\t\t\tLabelsMap: map[string]string{\"app\": \"kubedb\"},\n\t\t},\n\t\tSpecDefinitionName:      \"github.com\/kubedb\/apimachinery\/apis\/kubedb\/v1alpha1.DormantDatabase\",\n\t\tEnableValidation:        false,\n\t\tGetOpenAPIDefinitions:   GetOpenAPIDefinitions,\n\t\tEnableStatusSubresource: EnableStatusSubresource,\n\t\tAdditionalPrinterColumns: []apiextensions.CustomResourceColumnDefinition{\n\t\t\t{\n\t\t\t\tName:     \"Status\",\n\t\t\t\tType:     \"string\",\n\t\t\t\tJSONPath: \".status.phase\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tName:     \"Age\",\n\t\t\t\tType:     \"date\",\n\t\t\t\tJSONPath: \".metadata.creationTimestamp\",\n\t\t\t},\n\t\t},\n\t}, setNameSchema)\n}\n\nfunc (d *DormantDatabase) Migrate() {\n\tif d == nil {\n\t\treturn\n\t}\n\td.Spec.Origin.Spec.Elasticsearch.Migrate()\n\td.Spec.Origin.Spec.Postgres.Migrate()\n\td.Spec.Origin.Spec.MySQL.Migrate()\n\td.Spec.Origin.Spec.MongoDB.Migrate()\n\td.Spec.Origin.Spec.Redis.Migrate()\n\td.Spec.Origin.Spec.Memcached.Migrate()\n\td.Spec.Origin.Spec.Etcd.Migrate()\n}\n<|endoftext|>"}
{"text":"<commit_before>package reservation\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/garyburd\/redigo\/redis\"\n)\n\n\/\/ Reservation is a type that represents a lock on a resource. At most one reservation\n\/\/ can exist for an individual resource at any time.\ntype Reservation struct {\n\tstopped     bool\n\tkey, source string\n\tgetConn     func() redis.Conn\n\tttl         time.Duration\n}\n\n\/\/ Manager is responsible for creating and extending reservations. When a Reservation\n\/\/ is created using Manager, the manager will automatically extend that Reservation\n\/\/ every `Manager.Heartbeat` time units by setting the Reservation to expire\n\/\/ after `Manager.TTL` time elapses.\ntype Manager struct {\n\towner          string\n\tpool           *redis.Pool\n\tHeartbeat, TTL time.Duration\n}\n\n\/\/ NewManager returns a new Manager, or an error if a connection to the supplied\n\/\/ Redis server cannot be made.\nfunc NewManager(redisURL, owner string) (*Manager, error) {\n\t\/\/ Open redis pool\n\tredisPool := redis.NewPool(func() (redis.Conn, error) {\n\t\treturn redis.DialTimeout(\"tcp\", redisURL, 15*time.Second, 10*time.Second, 10*time.Second)\n\t}, 5)\n\n\t\/\/ Get a conn and ping so we fail immediately if the URL is wrong\n\tconn := redisPool.Get()\n\tdefer conn.Close()\n\tif _, err := conn.Do(\"PING\"); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error connecting to redis: %s\", err)\n\t}\n\n\treturn &Manager{\n\t\tHeartbeat: 15 * time.Minute,\n\t\tTTL:       4 * time.Hour,\n\t\towner:     owner,\n\t\tpool:      redisPool,\n\t}, nil\n}\n\n\/\/ Lock creates a Reservation for `resource`, or returns an error if there already exists a\n\/\/ Reservation for that resource.\nfunc (manager *Manager) Lock(resource string) (*Reservation, error) {\n\t\/\/ Get hostname\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey := fmt.Sprintf(\"reservation-%s\", resource)\n\tval := fmt.Sprintf(\"%s-%s-%d\", hostname, manager.owner, os.Getpid())\n\n\t\/\/ Get connection\n\tconn := manager.pool.Get()\n\tdefer conn.Close()\n\n\t\/\/ Try to set the reservation\n\tsuccess, err := conn.Do(\n\t\t\"SET\", key, val,\n\t\t\"EX\", manager.TTL.Seconds(),\n\t\t\"NX\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error with SET command: %s\", err.Error())\n\t}\n\tif success == nil {\n\t\treturn nil, fmt.Errorf(\"Reservation already exists for resource %s\", resource)\n\t}\n\n\t\/\/ Make new reservation\n\tres := &Reservation{\n\t\tkey:     key,\n\t\tsource:  val,\n\t\tgetConn: manager.pool.Get,\n\t\tttl:     manager.TTL,\n\t}\n\n\t\/\/ Set up heartbeat in background\n\tgo func() {\n\t\tfor _ = range time.Tick(manager.Heartbeat) {\n\t\t\tif res.stopped {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t\/\/ Panic if err; no way to handle the error gracefully when this runs in the background\n\t\t\tif _, err := res.heartbeat(); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn res, nil\n}\n\n\/\/ Release ends a lock on a resource. Release returns `nil` if release was successful or\n\/\/ an `error` if not. In the event of an error, the reservation will be removed from Redis after\n\/\/ `Reservation.ttl` expires.\nfunc (res *Reservation) Release() error {\n\tconn := res.getConn()\n\tdefer conn.Close()\n\n\t_, err := redis.Int(conn.Do(\"DEL\", res.key))\n\t\/\/ Always release lock so reservation will expire after TTL if delete fails\n\tres.stopped = true\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting reservation key for %s: %s\", res.key, err.Error())\n\t}\n\treturn nil\n}\n\nfunc (res *Reservation) heartbeat() (int, error) {\n\t\/\/ Get connection\n\tconn := res.getConn()\n\tdefer conn.Close()\n\n\t\/\/ Check that the reservation still exists and error if we don't have it\n\tsource, err := redis.String(conn.Do(\"GET\", res.key))\n\tif err != nil {\n\t\treturn -1, fmt.Errorf(\"Could not fetch owner of reservation %s: ERR %s\", res.key, err.Error())\n\t}\n\tif source != res.source {\n\t\treturn -1, fmt.Errorf(\"Reservation for %s has unknown owner %s\", res.key, source)\n\t}\n\n\t\/\/ Extend reservation\n\tsuccess, err := redis.Int(conn.Do(\"EXPIRE\", res.key, res.ttl.Seconds()))\n\tif err != nil || success != 1 {\n\t\treturn -1, fmt.Errorf(\"Could not extend reservation %s: ERR %s\", res.key, err.Error())\n\t}\n\treturn success, nil\n}\n<commit_msg>handle redis errors safely<commit_after>package reservation\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/garyburd\/redigo\/redis\"\n)\n\n\/\/ Reservation is a type that represents a lock on a resource. At most one reservation\n\/\/ can exist for an individual resource at any time.\ntype Reservation struct {\n\tstopped     bool\n\tkey, source string\n\tgetConn     func() redis.Conn\n\tttl         time.Duration\n}\n\n\/\/ Manager is responsible for creating and extending reservations. When a Reservation\n\/\/ is created using Manager, the manager will automatically extend that Reservation\n\/\/ every `Manager.Heartbeat` time units by setting the Reservation to expire\n\/\/ after `Manager.TTL` time elapses.\ntype Manager struct {\n\towner          string\n\tpool           *redis.Pool\n\tHeartbeat, TTL time.Duration\n}\n\n\/\/ NewManager returns a new Manager, or an error if a connection to the supplied\n\/\/ Redis server cannot be made.\nfunc NewManager(redisURL, owner string) (*Manager, error) {\n\t\/\/ Open redis pool\n\tredisPool := redis.NewPool(func() (redis.Conn, error) {\n\t\treturn redis.DialTimeout(\"tcp\", redisURL, 15*time.Second, 10*time.Second, 10*time.Second)\n\t}, 5)\n\n\t\/\/ Get a conn and ping so we fail immediately if the URL is wrong\n\tconn := redisPool.Get()\n\tdefer conn.Close()\n\tif _, err := conn.Do(\"PING\"); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error connecting to redis: %s\", err)\n\t}\n\n\treturn &Manager{\n\t\tHeartbeat: 15 * time.Minute,\n\t\tTTL:       4 * time.Hour,\n\t\towner:     owner,\n\t\tpool:      redisPool,\n\t}, nil\n}\n\n\/\/ Lock creates a Reservation for `resource`, or returns an error if there already exists a\n\/\/ Reservation for that resource.\nfunc (manager *Manager) Lock(resource string) (*Reservation, error) {\n\t\/\/ Get hostname\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey := fmt.Sprintf(\"reservation-%s\", resource)\n\tval := fmt.Sprintf(\"%s-%s-%d\", hostname, manager.owner, os.Getpid())\n\n\t\/\/ Get connection\n\tconn := manager.pool.Get()\n\tdefer conn.Close()\n\n\t\/\/ Try to set the reservation\n\tsuccess, err := conn.Do(\n\t\t\"SET\", key, val,\n\t\t\"EX\", manager.TTL.Seconds(),\n\t\t\"NX\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error with SET command: %s\", err.Error())\n\t}\n\tif success == nil {\n\t\treturn nil, fmt.Errorf(\"Reservation already exists for resource %s\", resource)\n\t}\n\n\t\/\/ Make new reservation\n\tres := &Reservation{\n\t\tkey:     key,\n\t\tsource:  val,\n\t\tgetConn: manager.pool.Get,\n\t\tttl:     manager.TTL,\n\t}\n\n\t\/\/ Set up heartbeat in background\n\tgo func() {\n\t\tfor _ = range time.Tick(manager.Heartbeat) {\n\t\t\tif res.stopped {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t\/\/ Panic if err; no way to handle the error gracefully when this runs in the background\n\t\t\tsuccess, err := res.heartbeat()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tif success != 1 {\n\t\t\t\tpanic(fmt.Errorf(\"Got code %d when attempting to extend reservation\", success))\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn res, nil\n}\n\n\/\/ Release ends a lock on a resource. Release returns `nil` if release was successful or\n\/\/ an `error` if not. In the event of an error, the reservation will be removed from Redis after\n\/\/ `Reservation.ttl` expires.\nfunc (res *Reservation) Release() error {\n\tconn := res.getConn()\n\tdefer conn.Close()\n\n\t_, err := redis.Int(conn.Do(\"DEL\", res.key))\n\t\/\/ Always release lock so reservation will expire after TTL if delete fails\n\tres.stopped = true\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting reservation key for %s: %s\", res.key, err.Error())\n\t}\n\treturn nil\n}\n\nfunc (res *Reservation) heartbeat() (int, error) {\n\t\/\/ Get connection\n\tconn := res.getConn()\n\tdefer conn.Close()\n\n\t\/\/ Check that the reservation still exists and error if we don't have it\n\tsource, err := redis.String(conn.Do(\"GET\", res.key))\n\tif err != nil {\n\t\treturn -1, fmt.Errorf(\"Could not fetch owner of reservation %s: ERR %s\", res.key, err.Error())\n\t}\n\tif source != res.source {\n\t\treturn -1, fmt.Errorf(\"Reservation for %s has unknown owner %s\", res.key, source)\n\t}\n\n\t\/\/ Extend reservation\n\tsuccess, err := redis.Int(conn.Do(\"EXPIRE\", res.key, res.ttl.Seconds()))\n\tif err != nil {\n\t\treturn -1, fmt.Errorf(\"Could not extend reservation %s: ERR %s\", res.key, err.Error())\n\t}\n\treturn success, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/cloudtrail\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n)\n\nfunc resourceAwsCloudTrail() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsCloudTrailCreate,\n\t\tRead:   resourceAwsCloudTrailRead,\n\t\tUpdate: resourceAwsCloudTrailUpdate,\n\t\tDelete: resourceAwsCloudTrailDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"name\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"s3_bucket_name\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t\"s3_key_prefix\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"cloud_watch_logs_role_arn\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"cloud_watch_logs_group_arn\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"include_global_service_events\": &schema.Schema{\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault:  true,\n\t\t\t},\n\t\t\t\"sns_topic_name\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceAwsCloudTrailCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).cloudtrailconn\n\n\tinput := cloudtrail.CreateTrailInput{\n\t\tName:         aws.String(d.Get(\"name\").(string)),\n\t\tS3BucketName: aws.String(d.Get(\"s3_bucket_name\").(string)),\n\t}\n\n\tif v, ok := d.GetOk(\"cloud_watch_logs_group_arn\"); ok {\n\t\tinput.CloudWatchLogsLogGroupArn = aws.String(v.(string))\n\t}\n\tif v, ok := d.GetOk(\"cloud_watch_logs_role_arn\"); ok {\n\t\tinput.CloudWatchLogsRoleArn = aws.String(v.(string))\n\t}\n\tif v, ok := d.GetOk(\"include_global_service_events\"); ok {\n\t\tinput.IncludeGlobalServiceEvents = aws.Bool(v.(bool))\n\t}\n\tif v, ok := d.GetOk(\"s3_key_prefix\"); ok {\n\t\tinput.S3KeyPrefix = aws.String(v.(string))\n\t}\n\tif v, ok := d.GetOk(\"sns_topic_name\"); ok {\n\t\tinput.SnsTopicName = aws.String(v.(string))\n\t}\n\n\tt, err := conn.CreateTrail(&input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[DEBUG] CloudTrail created: %s\", t)\n\n\td.SetId(*t.Name)\n\n\treturn resourceAwsCloudTrailRead(d, meta)\n}\n\nfunc resourceAwsCloudTrailRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).cloudtrailconn\n\n\tname := d.Get(\"name\").(string)\n\tinput := cloudtrail.DescribeTrailsInput{\n\t\tTrailNameList: []*string{\n\t\t\taws.String(name),\n\t\t},\n\t}\n\tresp, err := conn.DescribeTrails(&input)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(resp.TrailList) == 0 {\n\t\treturn fmt.Errorf(\"No CloudTrail found, using name %q\", name)\n\t}\n\n\ttrail := resp.TrailList[0]\n\tlog.Printf(\"[DEBUG] CloudTrail received: %s\", trail)\n\n\td.Set(\"name\", trail.Name)\n\td.Set(\"s3_bucket_name\", trail.S3BucketName)\n\td.Set(\"s3_key_prefix\", trail.S3KeyPrefix)\n\td.Set(\"cloud_watch_logs_role_arn\", trail.CloudWatchLogsRoleArn)\n\td.Set(\"cloud_watch_logs_group_arn\", trail.CloudWatchLogsLogGroupArn)\n\td.Set(\"include_global_service_events\", trail.IncludeGlobalServiceEvents)\n\td.Set(\"sns_topic_name\", trail.SnsTopicName)\n\n\treturn nil\n}\n\nfunc resourceAwsCloudTrailUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).cloudtrailconn\n\n\tinput := cloudtrail.UpdateTrailInput{\n\t\tName: aws.String(d.Get(\"name\").(string)),\n\t}\n\n\tif d.HasChange(\"s3_bucket_name\") {\n\t\tinput.S3BucketName = aws.String(d.Get(\"s3_bucket_name\").(string))\n\t}\n\tif d.HasChange(\"s3_key_prefix\") {\n\t\tinput.S3KeyPrefix = aws.String(d.Get(\"s3_key_prefix\").(string))\n\t}\n\tif d.HasChange(\"cloud_watch_logs_role_arn\") {\n\t\tinput.CloudWatchLogsRoleArn = aws.String(d.Get(\"cloud_watch_logs_role_arn\").(string))\n\t}\n\tif d.HasChange(\"cloud_watch_logs_group_arn\") {\n\t\tinput.CloudWatchLogsLogGroupArn = aws.String(d.Get(\"cloud_watch_logs_group_arn\").(string))\n\t}\n\tif d.HasChange(\"include_global_service_events\") {\n\t\tinput.IncludeGlobalServiceEvents = aws.Bool(d.Get(\"include_global_service_events\").(bool))\n\t}\n\tif d.HasChange(\"sns_topic_name\") {\n\t\tinput.SnsTopicName = aws.String(d.Get(\"sns_topic_name\").(string))\n\t}\n\n\tlog.Printf(\"[DEBUG] Updating CloudTrail: %s\", input)\n\tt, err := conn.UpdateTrail(&input)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[DEBUG] CloudTrail updated: %s\", t)\n\n\treturn resourceAwsCloudTrailRead(d, meta)\n}\n\nfunc resourceAwsCloudTrailDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).cloudtrailconn\n\tname := d.Get(\"name\").(string)\n\n\tlog.Printf(\"[DEBUG] Deleting CloudTrail: %q\", name)\n\t_, err := conn.DeleteTrail(&cloudtrail.DeleteTrailInput{\n\t\tName: aws.String(name),\n\t})\n\n\treturn err\n}\n<commit_msg>Add enable_logging to AWS CloudTrail<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/cloudtrail\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n)\n\nfunc resourceAwsCloudTrail() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsCloudTrailCreate,\n\t\tRead:   resourceAwsCloudTrailRead,\n\t\tUpdate: resourceAwsCloudTrailUpdate,\n\t\tDelete: resourceAwsCloudTrailDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"name\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"enable_logging\": &schema.Schema{\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault:  false,\n\t\t\t},\n\t\t\t\"s3_bucket_name\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t},\n\t\t\t\"s3_key_prefix\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"cloud_watch_logs_role_arn\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"cloud_watch_logs_group_arn\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"include_global_service_events\": &schema.Schema{\n\t\t\t\tType:     schema.TypeBool,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault:  true,\n\t\t\t},\n\t\t\t\"sns_topic_name\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceAwsCloudTrailCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).cloudtrailconn\n\n\tinput := cloudtrail.CreateTrailInput{\n\t\tName:         aws.String(d.Get(\"name\").(string)),\n\t\tS3BucketName: aws.String(d.Get(\"s3_bucket_name\").(string)),\n\t}\n\n\tif v, ok := d.GetOk(\"cloud_watch_logs_group_arn\"); ok {\n\t\tinput.CloudWatchLogsLogGroupArn = aws.String(v.(string))\n\t}\n\tif v, ok := d.GetOk(\"cloud_watch_logs_role_arn\"); ok {\n\t\tinput.CloudWatchLogsRoleArn = aws.String(v.(string))\n\t}\n\tif v, ok := d.GetOk(\"include_global_service_events\"); ok {\n\t\tinput.IncludeGlobalServiceEvents = aws.Bool(v.(bool))\n\t}\n\tif v, ok := d.GetOk(\"s3_key_prefix\"); ok {\n\t\tinput.S3KeyPrefix = aws.String(v.(string))\n\t}\n\tif v, ok := d.GetOk(\"sns_topic_name\"); ok {\n\t\tinput.SnsTopicName = aws.String(v.(string))\n\t}\n\n\tt, err := conn.CreateTrail(&input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[DEBUG] CloudTrail created: %s\", t)\n\n\td.SetId(*t.Name)\n\n\t\/\/ AWS CloudTrail sets newly-created trails to false.\n\tif v, ok := d.GetOk(\"enable_logging\"); ok && v.(bool) {\n\t\tcloudTrailSetLogging(conn, v.(bool), d.Id())\n\t}\n\n\treturn resourceAwsCloudTrailRead(d, meta)\n}\n\nfunc resourceAwsCloudTrailRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).cloudtrailconn\n\n\tname := d.Get(\"name\").(string)\n\tinput := cloudtrail.DescribeTrailsInput{\n\t\tTrailNameList: []*string{\n\t\t\taws.String(name),\n\t\t},\n\t}\n\tresp, err := conn.DescribeTrails(&input)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(resp.TrailList) == 0 {\n\t\treturn fmt.Errorf(\"No CloudTrail found, using name %q\", name)\n\t}\n\n\ttrail := resp.TrailList[0]\n\tlog.Printf(\"[DEBUG] CloudTrail received: %s\", trail)\n\n\td.Set(\"name\", trail.Name)\n\td.Set(\"s3_bucket_name\", trail.S3BucketName)\n\td.Set(\"s3_key_prefix\", trail.S3KeyPrefix)\n\td.Set(\"cloud_watch_logs_role_arn\", trail.CloudWatchLogsRoleArn)\n\td.Set(\"cloud_watch_logs_group_arn\", trail.CloudWatchLogsLogGroupArn)\n\td.Set(\"include_global_service_events\", trail.IncludeGlobalServiceEvents)\n\td.Set(\"sns_topic_name\", trail.SnsTopicName)\n\n\tlogstatus, err := cloudTrailGetLoggingStatus(conn, *trail.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.Set(\"enable_logging\", logstatus)\n\n\treturn nil\n}\n\nfunc resourceAwsCloudTrailUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).cloudtrailconn\n\n\tinput := cloudtrail.UpdateTrailInput{\n\t\tName: aws.String(d.Get(\"name\").(string)),\n\t}\n\n\tif d.HasChange(\"s3_bucket_name\") {\n\t\tinput.S3BucketName = aws.String(d.Get(\"s3_bucket_name\").(string))\n\t}\n\tif d.HasChange(\"s3_key_prefix\") {\n\t\tinput.S3KeyPrefix = aws.String(d.Get(\"s3_key_prefix\").(string))\n\t}\n\tif d.HasChange(\"cloud_watch_logs_role_arn\") {\n\t\tinput.CloudWatchLogsRoleArn = aws.String(d.Get(\"cloud_watch_logs_role_arn\").(string))\n\t}\n\tif d.HasChange(\"cloud_watch_logs_group_arn\") {\n\t\tinput.CloudWatchLogsLogGroupArn = aws.String(d.Get(\"cloud_watch_logs_group_arn\").(string))\n\t}\n\tif d.HasChange(\"include_global_service_events\") {\n\t\tinput.IncludeGlobalServiceEvents = aws.Bool(d.Get(\"include_global_service_events\").(bool))\n\t}\n\tif d.HasChange(\"sns_topic_name\") {\n\t\tinput.SnsTopicName = aws.String(d.Get(\"sns_topic_name\").(string))\n\t}\n\n\tlog.Printf(\"[DEBUG] Updating CloudTrail: %s\", input)\n\tt, err := conn.UpdateTrail(&input)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif d.HasChange(\"enable_logging\") {\n\t\tlog.Printf(\"[DEBUG] Updating logging on CloudTrail: %s\", input)\n\t\terr := cloudTrailSetLogging(conn, d.Get(\"enable_logging\").(bool), *input.Name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.Printf(\"[DEBUG] CloudTrail updated: %s\", t)\n\n\treturn resourceAwsCloudTrailRead(d, meta)\n}\n\nfunc resourceAwsCloudTrailDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).cloudtrailconn\n\tname := d.Get(\"name\").(string)\n\n\tlog.Printf(\"[DEBUG] Deleting CloudTrail: %q\", name)\n\t_, err := conn.DeleteTrail(&cloudtrail.DeleteTrailInput{\n\t\tName: aws.String(name),\n\t})\n\n\treturn err\n}\n\nfunc cloudTrailGetLoggingStatus(conn *cloudtrail.CloudTrail, id string) (bool, error) {\n\tGetTrailStatusOpts := &cloudtrail.GetTrailStatusInput{\n\t\tName: aws.String(id),\n\t}\n\tresp, err := conn.GetTrailStatus(GetTrailStatusOpts)\n\n\treturn *resp.IsLogging, err\n}\n\nfunc cloudTrailSetLogging(conn *cloudtrail.CloudTrail, enabled bool, id string) error {\n\tif enabled {\n\t\tlog.Printf(\n\t\t\t\"[DEBUG] Starting logging on CloudTrail (%s)\",\n\t\t\tid)\n\t\tStartLoggingOpts := &cloudtrail.StartLoggingInput{\n\t\t\tName: aws.String(id),\n\t\t}\n\t\tif _, err := conn.StartLogging(StartLoggingOpts); err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"Error starting logging on CloudTrail (%s): %s\",\n\t\t\t\tid, err)\n\t\t}\n\t} else {\n\t\tlog.Printf(\n\t\t\t\"[DEBUG] Stopping logging on CloudTrail (%s)\",\n\t\t\tid)\n\t\tStopLoggingOpts := &cloudtrail.StopLoggingInput{\n\t\t\tName: aws.String(id),\n\t\t}\n\t\tif _, err := conn.StopLogging(StopLoggingOpts); err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"Error stopping logging on CloudTrail (%s): %s\",\n\t\t\t\tid, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n)\n\nfunc main() {\n\tfmt.Println(\"Initializing Octave CPU...\")\n\tcpu := &CPU{running: true, sp: 65535}\n\n\tfile, err := os.Open(os.Args[1])\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer file.Close()\n\n\tcpu.memory, err = ioutil.ReadAll(file)\n\n\tcpu.devices[0] = stack{cpu}\n\tcpu.devices[1] = tty{bufio.NewReader(os.Stdin)}\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor cpu.running {\n\t\tinst_byte := fetch(cpu)\n\t\tinst_func := decode(inst_byte)\n\t\tinst_func(inst_byte, cpu)\n\t}\n}\n\ntype CPU struct {\n\tmemory    []uint8\n\tregisters [4]uint8\n\tpc        uint16\n\tsp        uint16\n\trunning   bool\n\tresult    uint8\n\tdevices   [8]Device\n}\n\ntype instruction func(uint8, *CPU)\n\ntype Device interface {\n\tread() uint8\n\twrite(uint8)\n}\n\ntype tty struct {\n\treader *bufio.Reader\n}\n\nfunc (t tty) read() uint8 {\n\tb, _ := t.reader.ReadByte()\n\treturn b\n}\n\nfunc (t tty) write(char uint8) {\n\tfmt.Printf(\"%c\", char)\n}\n\ntype stack struct {\n\tcpu *CPU\n}\n\nfunc (s stack) read() uint8 {\n\tvalue := s.cpu.memory[s.cpu.sp]\n\ts.cpu.sp++\n\treturn value\n}\n\nfunc (s stack) write(char uint8) {\n\ts.cpu.memory[s.cpu.sp] = char\n\ts.cpu.sp--\n}\n\nfunc fetch(cpu *CPU) uint8 {\n\tinst := cpu.memory[cpu.pc]\n\tcpu.pc = cpu.pc + 1\n\treturn inst\n}\n\nfunc decode(i uint8) instruction {\n\tinst := illegal\n\n\tswitch i >> 5 {\n\tcase 0:\n\t\tfmt.Fprint(os.Stderr, \"jmp\\n\")\n\t\tinst = jmp\n\tcase 1:\n\t\tfmt.Fprint(os.Stderr, \"loadi\\n\")\n\t\tinst = loadi\n\tcase 2:\n\t\tfmt.Fprint(os.Stderr, \"math\\n\")\n\t\tinst = math\n\tcase 3:\n\t\tfmt.Fprint(os.Stderr, \"logic\\n\")\n\t\tinst = logic\n\tcase 4:\n\t\tfmt.Fprint(os.Stderr, \"mem\\n\")\n\t\tinst = mem\n\tcase 5:\n\t\tfmt.Fprint(os.Stderr, \"stack\\n\")\n\t\tinst = stacki\n\tcase 6:\n\t\tfmt.Fprint(os.Stderr, \"in\\n\")\n\t\tinst = in\n\tcase 7:\n\t\tfmt.Fprint(os.Stderr, \"out\\n\")\n\t\tinst = out\n\t}\n\n\treturn inst\n}\n\nfunc jmp(i uint8, cpu *CPU) {\n\tif i == 0 {\n\t\tcpu.running = false\n\t}\n\n\tregister := i << 3 >> 6\n\tn := i << 5 >> 7\n\tz := i << 6 >> 7\n\tp := i << 7 >> 7\n\n\tif (n == 1 && cpu.result < 0) || (z == 1 && cpu.result == 0) || (p == 1 && cpu.result > 0) {\n\t\toffset := int8(cpu.registers[register])\n\t\tfmt.Fprintf(os.Stderr, \"Taking jump to %v\\n\", offset)\n\t\tcpu.pc = uint16(int32(cpu.pc) + int32(offset))\n\t}\n}\n\nfunc loadi(i uint8, cpu *CPU) {\n\tlocation := i << 3 >> 7\n\n\tif location == 0 {\n\t\tcpu.registers[0] = (i << 4) | (cpu.registers[0] << 4 >> 4)\n\t} else {\n\t\tcpu.registers[0] = (i << 4 >> 4) | (cpu.registers[0] >> 4 << 4)\n\t}\n}\n\nfunc math(i uint8, cpu *CPU) {\n\toperation := i << 3 >> 7\n\tdestination := i << 4 >> 6\n\tsource := i << 6 >> 6\n\n\tif operation == 0 {\n\t\tcpu.registers[destination] = cpu.registers[destination] + cpu.registers[source]\n\t} else {\n\t\tcpu.registers[destination] = cpu.registers[destination] \/ cpu.registers[source]\n\t}\n\n\tcpu.result = cpu.registers[destination]\n}\n\nfunc logic(i uint8, cpu *CPU) {\n\toperation := i << 3 >> 7\n\tdestination := i << 4 >> 6\n\tsource := i << 6 >> 6\n\n\tif operation == 0 {\n\t\tcpu.registers[destination] = cpu.registers[destination] & cpu.registers[source]\n\t} else {\n\t\tcpu.registers[destination] = cpu.registers[destination] ^ cpu.registers[source]\n\t}\n\n\tcpu.result = cpu.registers[destination]\n}\n\nfunc mem(i uint8, cpu *CPU) {\n\toperation := i << 3 >> 7\n\taddress_high := i << 4 >> 6\n\taddress_low := i << 6 >> 6\n\taddress := uint16(cpu.registers[address_high])<<8 + uint16(cpu.registers[address_low])\n\n\tif operation == 0 {\n\t\t\/\/ LOAD\n\t\tfmt.Fprintf(os.Stderr, \"Loading %v\\n to R0\", address)\n\t\tcpu.registers[0] = cpu.memory[address]\n\t} else {\n\t\t\/\/ STORE\n\t\tfmt.Fprintf(os.Stderr, \"Storing R0 to %v\\n\", address)\n\t\tcpu.memory[address] = cpu.registers[0]\n\t}\n}\n\nfunc stacki(i uint8, cpu *CPU) {\n\tstacki := i << 3 >> 3\n\n\tswitch stacki {\n\tcase 0:\n\t\t\/\/ add16\n\tcase 1:\n\t\t\/\/ sub16\n\tcase 2:\n\t\t\/\/ mul16\n\tcase 3:\n\t\t\/\/ div16\n\tcase 4:\n\t\t\/\/ mod16\n\tcase 5:\n\t\t\/\/ neg16\n\tcase 6:\n\t\t\/\/ and16\n\tcase 7:\n\t\t\/\/ or16\n\tcase 8:\n\t\t\/\/ xor16\n\tcase 9:\n\t\t\/\/ not16\n\tcase 10:\n\t\t\/\/ add32\n\tcase 11:\n\t\t\/\/ sub32\n\tcase 12:\n\t\t\/\/ mul32\n\tcase 13:\n\t\t\/\/ div32\n\tcase 14:\n\t\t\/\/ mod32\n\tcase 15:\n\t\t\/\/ neg32\n\tcase 16:\n\t\t\/\/ and32\n\tcase 17:\n\t\t\/\/ or32\n\tcase 18:\n\t\t\/\/ xor32\n\tcase 19:\n\t\t\/\/ not32\n\tcase 20:\n\t\t\/\/ Get jump address off the stack\n\t\tnew_pc_high := cpu.devices[0].read()\n\t\tnew_pc_low := cpu.devices[0].read()\n\t\tnew_pc := uint16(new_pc_high)<<8 + uint16(new_pc_low)\n\n\t\t\/\/ Push next address to the stack\n\t\tpc_high := cpu.pc >> 8\n\t\tpc_low := cpu.pc << 8 >> 8\n\t\tcpu.devices[0].write(uint8(pc_high))\n\t\tcpu.devices[0].write(uint8(pc_low))\n\n\t\t\/\/ Jump\n\t\tcpu.pc = new_pc\n\tcase 21:\n\t\t\/\/ trap\n\tcase 22:\n\t\t\/\/ Get return address off the stack\n\t\tpc_high := cpu.devices[0].read()\n\t\tpc_low := cpu.devices[0].read()\n\t\tpc := uint16(pc_high)<<8 + uint16(pc_low)\n\n\t\t\/\/ Jump\n\t\tcpu.pc = pc\n\tcase 23:\n\t\t\/\/ iret\n\tdefault:\n\t\t\/\/ device := stacki - 24\n\t\t\/\/ TODO: enable device\n\t}\n}\n\nfunc in(i uint8, cpu *CPU) {\n\tdevice := i << 5 >> 5\n\tdestination := i << 3 >> 6\n\tcpu.registers[destination] = cpu.devices[device].read()\n}\n\nfunc out(i uint8, cpu *CPU) {\n\tdevice := i << 3 >> 5\n\tsource := i << 6 >> 6\n\tcpu.devices[device].write(cpu.registers[source])\n}\n\nfunc illegal(i uint8, cpu *CPU) {\n}\n<commit_msg>Call stack order<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n)\n\nfunc main() {\n\tfmt.Println(\"Initializing Octave CPU...\")\n\tcpu := &CPU{running: true, sp: 65535}\n\n\tfile, err := os.Open(os.Args[1])\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer file.Close()\n\n\tcpu.memory, err = ioutil.ReadAll(file)\n\n\tcpu.devices[0] = stack{cpu}\n\tcpu.devices[1] = tty{bufio.NewReader(os.Stdin)}\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor cpu.running {\n\t\tinst_byte := fetch(cpu)\n\t\tinst_func := decode(inst_byte)\n\t\tinst_func(inst_byte, cpu)\n\t}\n}\n\ntype CPU struct {\n\tmemory    []uint8\n\tregisters [4]uint8\n\tpc        uint16\n\tsp        uint16\n\trunning   bool\n\tresult    uint8\n\tdevices   [8]Device\n}\n\ntype instruction func(uint8, *CPU)\n\ntype Device interface {\n\tread() uint8\n\twrite(uint8)\n}\n\ntype tty struct {\n\treader *bufio.Reader\n}\n\nfunc (t tty) read() uint8 {\n\tb, _ := t.reader.ReadByte()\n\treturn b\n}\n\nfunc (t tty) write(char uint8) {\n\tfmt.Printf(\"%c\", char)\n}\n\ntype stack struct {\n\tcpu *CPU\n}\n\nfunc (s stack) read() uint8 {\n\tvalue := s.cpu.memory[s.cpu.sp]\n\ts.cpu.sp++\n\treturn value\n}\n\nfunc (s stack) write(char uint8) {\n\ts.cpu.memory[s.cpu.sp] = char\n\ts.cpu.sp--\n}\n\nfunc fetch(cpu *CPU) uint8 {\n\tinst := cpu.memory[cpu.pc]\n\tcpu.pc = cpu.pc + 1\n\treturn inst\n}\n\nfunc decode(i uint8) instruction {\n\tinst := illegal\n\n\tswitch i >> 5 {\n\tcase 0:\n\t\tfmt.Fprint(os.Stderr, \"jmp\\n\")\n\t\tinst = jmp\n\tcase 1:\n\t\tfmt.Fprint(os.Stderr, \"loadi\\n\")\n\t\tinst = loadi\n\tcase 2:\n\t\tfmt.Fprint(os.Stderr, \"math\\n\")\n\t\tinst = math\n\tcase 3:\n\t\tfmt.Fprint(os.Stderr, \"logic\\n\")\n\t\tinst = logic\n\tcase 4:\n\t\tfmt.Fprint(os.Stderr, \"mem\\n\")\n\t\tinst = mem\n\tcase 5:\n\t\tfmt.Fprint(os.Stderr, \"stack\\n\")\n\t\tinst = stacki\n\tcase 6:\n\t\tfmt.Fprint(os.Stderr, \"in\\n\")\n\t\tinst = in\n\tcase 7:\n\t\tfmt.Fprint(os.Stderr, \"out\\n\")\n\t\tinst = out\n\t}\n\n\treturn inst\n}\n\nfunc jmp(i uint8, cpu *CPU) {\n\tif i == 0 {\n\t\tcpu.running = false\n\t}\n\n\tregister := i << 3 >> 6\n\tn := i << 5 >> 7\n\tz := i << 6 >> 7\n\tp := i << 7 >> 7\n\n\tif (n == 1 && cpu.result < 0) || (z == 1 && cpu.result == 0) || (p == 1 && cpu.result > 0) {\n\t\toffset := int8(cpu.registers[register])\n\t\tfmt.Fprintf(os.Stderr, \"Taking jump to %v\\n\", offset)\n\t\tcpu.pc = uint16(int32(cpu.pc) + int32(offset))\n\t}\n}\n\nfunc loadi(i uint8, cpu *CPU) {\n\tlocation := i << 3 >> 7\n\n\tif location == 0 {\n\t\tcpu.registers[0] = (i << 4) | (cpu.registers[0] << 4 >> 4)\n\t} else {\n\t\tcpu.registers[0] = (i << 4 >> 4) | (cpu.registers[0] >> 4 << 4)\n\t}\n}\n\nfunc math(i uint8, cpu *CPU) {\n\toperation := i << 3 >> 7\n\tdestination := i << 4 >> 6\n\tsource := i << 6 >> 6\n\n\tif operation == 0 {\n\t\tcpu.registers[destination] = cpu.registers[destination] + cpu.registers[source]\n\t} else {\n\t\tcpu.registers[destination] = cpu.registers[destination] \/ cpu.registers[source]\n\t}\n\n\tcpu.result = cpu.registers[destination]\n}\n\nfunc logic(i uint8, cpu *CPU) {\n\toperation := i << 3 >> 7\n\tdestination := i << 4 >> 6\n\tsource := i << 6 >> 6\n\n\tif operation == 0 {\n\t\tcpu.registers[destination] = cpu.registers[destination] & cpu.registers[source]\n\t} else {\n\t\tcpu.registers[destination] = cpu.registers[destination] ^ cpu.registers[source]\n\t}\n\n\tcpu.result = cpu.registers[destination]\n}\n\nfunc mem(i uint8, cpu *CPU) {\n\toperation := i << 3 >> 7\n\taddress_high := i << 4 >> 6\n\taddress_low := i << 6 >> 6\n\taddress := uint16(cpu.registers[address_high])<<8 + uint16(cpu.registers[address_low])\n\n\tif operation == 0 {\n\t\t\/\/ LOAD\n\t\tfmt.Fprintf(os.Stderr, \"Loading %v\\n to R0\", address)\n\t\tcpu.registers[0] = cpu.memory[address]\n\t} else {\n\t\t\/\/ STORE\n\t\tfmt.Fprintf(os.Stderr, \"Storing R0 to %v\\n\", address)\n\t\tcpu.memory[address] = cpu.registers[0]\n\t}\n}\n\nfunc stacki(i uint8, cpu *CPU) {\n\tstacki := i << 3 >> 3\n\n\tswitch stacki {\n\tcase 0:\n\t\t\/\/ add16\n\tcase 1:\n\t\t\/\/ sub16\n\tcase 2:\n\t\t\/\/ mul16\n\tcase 3:\n\t\t\/\/ div16\n\tcase 4:\n\t\t\/\/ mod16\n\tcase 5:\n\t\t\/\/ neg16\n\tcase 6:\n\t\t\/\/ and16\n\tcase 7:\n\t\t\/\/ or16\n\tcase 8:\n\t\t\/\/ xor16\n\tcase 9:\n\t\t\/\/ not16\n\tcase 10:\n\t\t\/\/ add32\n\tcase 11:\n\t\t\/\/ sub32\n\tcase 12:\n\t\t\/\/ mul32\n\tcase 13:\n\t\t\/\/ div32\n\tcase 14:\n\t\t\/\/ mod32\n\tcase 15:\n\t\t\/\/ neg32\n\tcase 16:\n\t\t\/\/ and32\n\tcase 17:\n\t\t\/\/ or32\n\tcase 18:\n\t\t\/\/ xor32\n\tcase 19:\n\t\t\/\/ not32\n\tcase 20:\n\t\t\/\/ Get jump address off the stack\n\t\tnew_pc_high := cpu.devices[0].read()\n\t\tnew_pc_low := cpu.devices[0].read()\n\t\tnew_pc := uint16(new_pc_high)<<8 + uint16(new_pc_low)\n\n\t\t\/\/ Push next address to the stack\n\t\tpc_high := cpu.pc >> 8\n\t\tpc_low := cpu.pc << 8 >> 8\n\t\tcpu.devices[0].write(uint8(pc_low))\n\t\tcpu.devices[0].write(uint8(pc_high))\n\n\t\t\/\/ Jump\n\t\tcpu.pc = new_pc\n\tcase 21:\n\t\t\/\/ trap\n\tcase 22:\n\t\t\/\/ Get return address off the stack\n\t\tpc_high := cpu.devices[0].read()\n\t\tpc_low := cpu.devices[0].read()\n\t\tpc := uint16(pc_high)<<8 + uint16(pc_low)\n\n\t\t\/\/ Jump\n\t\tcpu.pc = pc\n\tcase 23:\n\t\t\/\/ iret\n\tdefault:\n\t\t\/\/ device := stacki - 24\n\t\t\/\/ TODO: enable device\n\t}\n}\n\nfunc in(i uint8, cpu *CPU) {\n\tdevice := i << 5 >> 5\n\tdestination := i << 3 >> 6\n\tcpu.registers[destination] = cpu.devices[device].read()\n}\n\nfunc out(i uint8, cpu *CPU) {\n\tdevice := i << 3 >> 5\n\tsource := i << 6 >> 6\n\tcpu.devices[device].write(cpu.registers[source])\n}\n\nfunc illegal(i uint8, cpu *CPU) {\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/ethereum\/eth-go\"\n\t\"github.com\/ethereum\/ethchain-go\"\n\t\"github.com\/ethereum\/ethdb-go\"\n\t\"github.com\/ethereum\/ethutil-go\"\n\t\"github.com\/ethereum\/ethwire-go\"\n\t_ \"math\/big\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype Console struct {\n\tdb       *ethdb.MemDatabase\n\ttrie     *ethutil.Trie\n\tethereum *eth.Ethereum\n}\n\nfunc NewConsole(s *eth.Ethereum) *Console {\n\tdb, _ := ethdb.NewMemDatabase()\n\ttrie := ethutil.NewTrie(db, \"\")\n\n\treturn &Console{db: db, trie: trie, ethereum: s}\n}\n\nfunc (i *Console) ValidateInput(action string, argumentLength int) error {\n\terr := false\n\tvar expArgCount int\n\n\tswitch {\n\tcase action == \"update\" && argumentLength != 2:\n\t\terr = true\n\t\texpArgCount = 2\n\tcase action == \"get\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"dag\" && argumentLength != 2:\n\t\terr = true\n\t\texpArgCount = 2\n\tcase action == \"decode\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"encode\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"gettx\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"tx\" && argumentLength != 2:\n\t\terr = true\n\t\texpArgCount = 2\n\tcase action == \"getaddr\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"contract\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"say\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"addp\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\t}\n\n\tif err {\n\t\treturn errors.New(fmt.Sprintf(\"'%s' requires %d args, got %d\", action, expArgCount, argumentLength))\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc (i *Console) PrintRoot() {\n\troot := ethutil.Conv(i.trie.Root)\n\tif len(root.AsBytes()) != 0 {\n\t\tfmt.Println(hex.EncodeToString(root.AsBytes()))\n\t} else {\n\t\tfmt.Println(i.trie.Root)\n\t}\n}\n\nfunc (i *Console) ParseInput(input string) bool {\n\tscanner := bufio.NewScanner(strings.NewReader(input))\n\tscanner.Split(bufio.ScanWords)\n\n\tcount := 0\n\tvar tokens []string\n\tfor scanner.Scan() {\n\t\tcount++\n\t\ttokens = append(tokens, scanner.Text())\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"reading input:\", err)\n\t}\n\n\tif len(tokens) == 0 {\n\t\treturn true\n\t}\n\n\terr := i.ValidateInput(tokens[0], count-1)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t} else {\n\t\tswitch tokens[0] {\n\t\tcase \"update\":\n\t\t\ti.trie.Update(tokens[1], tokens[2])\n\n\t\t\ti.PrintRoot()\n\t\tcase \"get\":\n\t\t\tfmt.Println(i.trie.Get(tokens[1]))\n\t\tcase \"root\":\n\t\t\ti.PrintRoot()\n\t\tcase \"rawroot\":\n\t\t\tfmt.Println(i.trie.Root)\n\t\tcase \"print\":\n\t\t\ti.db.Print()\n\t\tcase \"dag\":\n\t\t\tfmt.Println(ethchain.DaggerVerify(ethutil.Big(tokens[1]), \/\/ hash\n\t\t\t\tethutil.BigPow(2, 36),   \/\/ diff\n\t\t\t\tethutil.Big(tokens[2]))) \/\/ nonce\n\t\tcase \"decode\":\n\t\t\tvalue := ethutil.NewRlpValueFromBytes([]byte(tokens[1]))\n\t\t\tfmt.Println(value)\n\t\tcase \"getaddr\":\n\t\t\tencoded, _ := hex.DecodeString(tokens[1])\n\t\t\td := i.ethereum.BlockManager.BlockChain().CurrentBlock.State().Get(string(encoded))\n\t\t\tif d != \"\" {\n\t\t\t\tdecoder := ethutil.NewRlpValueFromBytes([]byte(d))\n\t\t\t\tfmt.Println(decoder)\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"getaddr: address unknown\")\n\t\t\t}\n\t\tcase \"say\":\n\t\t\ti.ethereum.Broadcast(ethwire.MsgTalkTy, []interface{}{tokens[1]})\n\t\tcase \"addp\":\n\t\t\ti.ethereum.ConnectToPeer(tokens[1])\n\t\tcase \"pcount\":\n\t\t\tfmt.Println(\"peers:\", i.ethereum.Peers().Len())\n\t\tcase \"encode\":\n\t\t\tfmt.Printf(\"%q\\n\", ethutil.Encode(tokens[1]))\n\t\tcase \"tx\":\n\t\t\trecipient, err := hex.DecodeString(tokens[1])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"recipient err:\", err)\n\t\t\t} else {\n\t\t\t\ttx := ethchain.NewTransaction(recipient, ethutil.Big(tokens[2]), []string{\"\"})\n\t\t\t\tdata, _ := ethutil.Config.Db.Get([]byte(\"KeyRing\"))\n\t\t\t\tkeyRing := ethutil.NewValueFromBytes(data)\n\t\t\t\ttx.Sign(keyRing.Get(0).Bytes())\n\t\t\t\tfmt.Printf(\"%x\\n\", tx.Hash())\n\t\t\t\ti.ethereum.TxPool.QueueTransaction(tx)\n\t\t\t}\n\n\t\tcase \"gettx\":\n\t\t\taddr, _ := hex.DecodeString(tokens[1])\n\t\t\tdata, _ := ethutil.Config.Db.Get(addr)\n\t\t\tif len(data) != 0 {\n\t\t\t\tdecoder := ethutil.NewRlpValueFromBytes(data)\n\t\t\t\tfmt.Println(decoder)\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"gettx: tx not found\")\n\t\t\t}\n\t\tcase \"contract\":\n\t\t\tcontract := ethchain.NewTransaction([]byte{}, ethutil.Big(tokens[1]), []string{\"PUSH\", \"1234\"})\n\t\t\tfmt.Printf(\"%x\\n\", contract.Hash())\n\n\t\t\ti.ethereum.TxPool.QueueTransaction(contract)\n\t\tcase \"exit\", \"quit\", \"q\":\n\t\t\treturn false\n\t\tcase \"help\":\n\t\t\tfmt.Printf(\"COMMANDS:\\n\" +\n\t\t\t\t\"\\033[1m= DB =\\033[0m\\n\" +\n\t\t\t\t\"update KEY VALUE - Updates\/Creates a new value for the given key\\n\" +\n\t\t\t\t\"get KEY - Retrieves the given key\\n\" +\n\t\t\t\t\"root - Prints the hex encoded merkle root\\n\" +\n\t\t\t\t\"rawroot - Prints the raw merkle root\\n\" +\n\t\t\t\t\"\\033[1m= Dagger =\\033[0m\\n\" +\n\t\t\t\t\"dag HASH NONCE - Verifies a nonce with the given hash with dagger\\n\" +\n\t\t\t\t\"\\033[1m= Encoding =\\033[0m\\n\" +\n\t\t\t\t\"decode STR\\n\" +\n\t\t\t\t\"encode STR\\n\" +\n\t\t\t\t\"\\033[1m= Other =\\033[0m\\n\" +\n\t\t\t\t\"addp HOST:PORT\\n\" +\n\t\t\t\t\"tx TO AMOUNT\\n\" +\n\t\t\t\t\"contract AMOUNT\\n\")\n\n\t\tdefault:\n\t\t\tfmt.Println(\"Unknown command:\", tokens[0])\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (i *Console) Start() {\n\tfmt.Printf(\"Eth Console. Type (help) for help\\n\")\n\treader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tfmt.Printf(\"eth >>> \")\n\t\tstr, _, err := reader.ReadLine()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error reading input\", err)\n\t\t} else {\n\t\t\tif !i.ParseInput(string(str)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Added block retrieval<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/ethereum\/eth-go\"\n\t\"github.com\/ethereum\/ethchain-go\"\n\t\"github.com\/ethereum\/ethdb-go\"\n\t\"github.com\/ethereum\/ethutil-go\"\n\t\"github.com\/ethereum\/ethwire-go\"\n\t_ \"math\/big\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype Console struct {\n\tdb       *ethdb.MemDatabase\n\ttrie     *ethutil.Trie\n\tethereum *eth.Ethereum\n}\n\nfunc NewConsole(s *eth.Ethereum) *Console {\n\tdb, _ := ethdb.NewMemDatabase()\n\ttrie := ethutil.NewTrie(db, \"\")\n\n\treturn &Console{db: db, trie: trie, ethereum: s}\n}\n\nfunc (i *Console) ValidateInput(action string, argumentLength int) error {\n\terr := false\n\tvar expArgCount int\n\n\tswitch {\n\tcase action == \"update\" && argumentLength != 2:\n\t\terr = true\n\t\texpArgCount = 2\n\tcase action == \"get\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"dag\" && argumentLength != 2:\n\t\terr = true\n\t\texpArgCount = 2\n\tcase action == \"decode\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"encode\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"gettx\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"tx\" && argumentLength != 2:\n\t\terr = true\n\t\texpArgCount = 2\n\tcase action == \"getaddr\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"contract\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"say\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"addp\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\tcase action == \"block\" && argumentLength != 1:\n\t\terr = true\n\t\texpArgCount = 1\n\t}\n\n\tif err {\n\t\treturn errors.New(fmt.Sprintf(\"'%s' requires %d args, got %d\", action, expArgCount, argumentLength))\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc (i *Console) PrintRoot() {\n\troot := ethutil.Conv(i.trie.Root)\n\tif len(root.AsBytes()) != 0 {\n\t\tfmt.Println(hex.EncodeToString(root.AsBytes()))\n\t} else {\n\t\tfmt.Println(i.trie.Root)\n\t}\n}\n\nfunc (i *Console) ParseInput(input string) bool {\n\tscanner := bufio.NewScanner(strings.NewReader(input))\n\tscanner.Split(bufio.ScanWords)\n\n\tcount := 0\n\tvar tokens []string\n\tfor scanner.Scan() {\n\t\tcount++\n\t\ttokens = append(tokens, scanner.Text())\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"reading input:\", err)\n\t}\n\n\tif len(tokens) == 0 {\n\t\treturn true\n\t}\n\n\terr := i.ValidateInput(tokens[0], count-1)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t} else {\n\t\tswitch tokens[0] {\n\t\tcase \"update\":\n\t\t\ti.trie.Update(tokens[1], tokens[2])\n\n\t\t\ti.PrintRoot()\n\t\tcase \"get\":\n\t\t\tfmt.Println(i.trie.Get(tokens[1]))\n\t\tcase \"root\":\n\t\t\ti.PrintRoot()\n\t\tcase \"rawroot\":\n\t\t\tfmt.Println(i.trie.Root)\n\t\tcase \"print\":\n\t\t\ti.db.Print()\n\t\tcase \"dag\":\n\t\t\tfmt.Println(ethchain.DaggerVerify(ethutil.Big(tokens[1]), \/\/ hash\n\t\t\t\tethutil.BigPow(2, 36),   \/\/ diff\n\t\t\t\tethutil.Big(tokens[2]))) \/\/ nonce\n\t\tcase \"decode\":\n\t\t\tvalue := ethutil.NewRlpValueFromBytes([]byte(tokens[1]))\n\t\t\tfmt.Println(value)\n\t\tcase \"getaddr\":\n\t\t\tencoded, _ := hex.DecodeString(tokens[1])\n\t\t\taddr := i.ethereum.BlockManager.BlockChain().CurrentBlock.GetAddr(encoded)\n\t\t\tfmt.Println(\"addr:\", addr)\n\t\tcase \"block\":\n\t\t\tencoded, _ := hex.DecodeString(tokens[1])\n\t\t\tblock := i.ethereum.BlockManager.BlockChain().GetBlock(encoded)\n\t\t\tfmt.Println(block)\n\t\tcase \"say\":\n\t\t\ti.ethereum.Broadcast(ethwire.MsgTalkTy, []interface{}{tokens[1]})\n\t\tcase \"addp\":\n\t\t\ti.ethereum.ConnectToPeer(tokens[1])\n\t\tcase \"pcount\":\n\t\t\tfmt.Println(\"peers:\", i.ethereum.Peers().Len())\n\t\tcase \"encode\":\n\t\t\tfmt.Printf(\"%q\\n\", ethutil.Encode(tokens[1]))\n\t\tcase \"tx\":\n\t\t\trecipient, err := hex.DecodeString(tokens[1])\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"recipient err:\", err)\n\t\t\t} else {\n\t\t\t\ttx := ethchain.NewTransaction(recipient, ethutil.Big(tokens[2]), []string{\"\"})\n\t\t\t\tdata, _ := ethutil.Config.Db.Get([]byte(\"KeyRing\"))\n\t\t\t\tkeyRing := ethutil.NewValueFromBytes(data)\n\t\t\t\ttx.Sign(keyRing.Get(0).Bytes())\n\t\t\t\tfmt.Printf(\"%x\\n\", tx.Hash())\n\t\t\t\ti.ethereum.TxPool.QueueTransaction(tx)\n\t\t\t}\n\n\t\tcase \"gettx\":\n\t\t\taddr, _ := hex.DecodeString(tokens[1])\n\t\t\tdata, _ := ethutil.Config.Db.Get(addr)\n\t\t\tif len(data) != 0 {\n\t\t\t\tdecoder := ethutil.NewRlpValueFromBytes(data)\n\t\t\t\tfmt.Println(decoder)\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"gettx: tx not found\")\n\t\t\t}\n\t\tcase \"contract\":\n\t\t\tcontract := ethchain.NewTransaction([]byte{}, ethutil.Big(tokens[1]), []string{\"PUSH\", \"1234\"})\n\t\t\tfmt.Printf(\"%x\\n\", contract.Hash())\n\n\t\t\ti.ethereum.TxPool.QueueTransaction(contract)\n\t\tcase \"exit\", \"quit\", \"q\":\n\t\t\treturn false\n\t\tcase \"help\":\n\t\t\tfmt.Printf(\"COMMANDS:\\n\" +\n\t\t\t\t\"\\033[1m= DB =\\033[0m\\n\" +\n\t\t\t\t\"update KEY VALUE - Updates\/Creates a new value for the given key\\n\" +\n\t\t\t\t\"get KEY - Retrieves the given key\\n\" +\n\t\t\t\t\"root - Prints the hex encoded merkle root\\n\" +\n\t\t\t\t\"rawroot - Prints the raw merkle root\\n\" +\n\t\t\t\t\"block HASH - Prints the block\\n\" +\n\t\t\t\t\"getaddr ADDR - Prints the account associated with the address\\n\" +\n\t\t\t\t\"\\033[1m= Dagger =\\033[0m\\n\" +\n\t\t\t\t\"dag HASH NONCE - Verifies a nonce with the given hash with dagger\\n\" +\n\t\t\t\t\"\\033[1m= Encoding =\\033[0m\\n\" +\n\t\t\t\t\"decode STR\\n\" +\n\t\t\t\t\"encode STR\\n\" +\n\t\t\t\t\"\\033[1m= Other =\\033[0m\\n\" +\n\t\t\t\t\"addp HOST:PORT\\n\" +\n\t\t\t\t\"tx TO AMOUNT\\n\" +\n\t\t\t\t\"contract AMOUNT\\n\")\n\n\t\tdefault:\n\t\t\tfmt.Println(\"Unknown command:\", tokens[0])\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (i *Console) Start() {\n\tfmt.Printf(\"Eth Console. Type (help) for help\\n\")\n\treader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tfmt.Printf(\"eth >>> \")\n\t\tstr, _, err := reader.ReadLine()\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error reading input\", err)\n\t\t} else {\n\t\t\tif !i.ParseInput(string(str)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n)\n\nfunc cmdMail(args []string) {\n\tvar (\n\t\tdiff   = flags.Bool(\"diff\", false, \"show change commit diff and don't upload or mail\")\n\t\tforce  = flags.Bool(\"f\", false, \"mail even if there are staged changes\")\n\t\ttopic  = flags.String(\"topic\", \"\", \"set Gerrit topic\")\n\t\trList  = new(stringList) \/\/ installed below\n\t\tccList = new(stringList) \/\/ installed below\n\t)\n\tflags.Var(rList, \"r\", \"comma-separated list of reviewers\")\n\tflags.Var(ccList, \"cc\", \"comma-separated list of people to CC:\")\n\n\tflags.Usage = func() {\n\t\tfmt.Fprintf(stderr(), \"Usage: %s mail %s [-r reviewer,...] [-cc mail,...] [-topic topic] [commit-hash]\\n\", os.Args[0], globalFlags)\n\t}\n\tflags.Parse(args)\n\tif len(flags.Args()) > 1 {\n\t\tflags.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tb := CurrentBranch()\n\n\tvar c *Commit\n\tif len(flags.Args()) == 1 {\n\t\tc = b.CommitByHash(\"mail\", flags.Arg(0))\n\t} else {\n\t\tc = b.DefaultCommit(\"mail\")\n\t}\n\n\tif *diff {\n\t\trun(\"git\", \"diff\", b.Branchpoint()[:7]+\"..\"+c.ShortHash, \"--\")\n\t\treturn\n\t}\n\n\tif !*force && HasStagedChanges() {\n\t\tdief(\"there are staged changes; aborting.\\n\"+\n\t\t\t\"Use '%s change' to include them or '%s mail -f' to force it.\", os.Args[0], os.Args[0])\n\t}\n\n\t\/\/ for side effect of dying with a good message if origin is GitHub\n\tloadGerritOrigin()\n\n\trefSpec := b.PushSpec(c)\n\tstart := \"%\"\n\tif *rList != \"\" {\n\t\trefSpec += mailList(start, \"r\", string(*rList))\n\t\tstart = \",\"\n\t}\n\tif *ccList != \"\" {\n\t\trefSpec += mailList(start, \"cc\", string(*ccList))\n\t\tstart = \",\"\n\t}\n\tif *topic != \"\" {\n\t\t\/\/ There's no way to escape the topic, but the only\n\t\t\/\/ ambiguous character is ',' (though other characters\n\t\t\/\/ like ' ' will be rejected outright by git).\n\t\tif strings.Contains(*topic, \",\") {\n\t\t\tdief(\"topic may not contain a comma\")\n\t\t}\n\t\trefSpec += start + \"topic=\" + *topic\n\t}\n\trun(\"git\", \"push\", \"-q\", \"origin\", refSpec)\n\n\t\/\/ Create local tag for mailed change.\n\t\/\/ If in the 'work' branch, this creates or updates work.mailed.\n\t\/\/ Older mailings are in the reflog, so work.mailed is newest,\n\t\/\/ work.mailed@{1} is the one before that, work.mailed@{2} before that,\n\t\/\/ and so on.\n\t\/\/ Git doesn't actually have a concept of a local tag,\n\t\/\/ but Gerrit won't let people push tags to it, so the tag\n\t\/\/ can't propagate out of the local client into the official repo.\n\t\/\/ There is no conflict with the branch names people are using\n\t\/\/ for work, because git change rejects any name containing a dot.\n\t\/\/ The space of names with dots is ours (the Go team's) to define.\n\trun(\"git\", \"tag\", \"-f\", b.Name+\".mailed\")\n}\n\n\/\/ PushSpec returns the spec for a Gerrit push command to publish the change c in b.\n\/\/ If c is nil, PushSpec returns a spec for pushing all changes in b.\nfunc (b *Branch) PushSpec(c *Commit) string {\n\tlocal := \"HEAD\"\n\tif c != nil && (len(b.Pending()) == 0 || b.Pending()[0].Hash != c.Hash) {\n\t\tlocal = c.ShortHash\n\t}\n\treturn local + \":refs\/for\/\" + strings.TrimPrefix(b.OriginBranch(), \"origin\/\")\n}\n\n\/\/ mailAddressRE matches the mail addresses we admit. It's restrictive but admits\n\/\/ all the addresses in the Go CONTRIBUTORS file at time of writing (tested separately).\nvar mailAddressRE = regexp.MustCompile(`^([a-zA-Z0-9][-_.a-zA-Z0-9]*)(@[-_.a-zA-Z0-9]+)?$`)\n\n\/\/ mailList turns the list of mail addresses from the flag value into the format\n\/\/ expected by gerrit. The start argument is a % or , depending on where we\n\/\/ are in the processing sequence.\nfunc mailList(start, tag string, flagList string) string {\n\terrors := false\n\tspec := start\n\tshort := \"\"\n\tlong := \"\"\n\tfor i, addr := range strings.Split(flagList, \",\") {\n\t\tm := mailAddressRE.FindStringSubmatch(addr)\n\t\tif m == nil {\n\t\t\tprintf(\"invalid reviewer mail address: %s\", addr)\n\t\t\terrors = true\n\t\t\tcontinue\n\t\t}\n\t\tif m[2] == \"\" {\n\t\t\temail := mailLookup(addr)\n\t\t\tif email == \"\" {\n\t\t\t\tprintf(\"unknown reviewer: %s\", addr)\n\t\t\t\terrors = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tshort += \",\" + addr\n\t\t\tlong += \",\" + email\n\t\t\taddr = email\n\t\t}\n\t\tif i > 0 {\n\t\t\tspec += \",\"\n\t\t}\n\t\tspec += tag + \"=\" + addr\n\t}\n\tif short != \"\" {\n\t\tverbosef(\"expanded %s to %s\", short[1:], long[1:])\n\t}\n\tif errors {\n\t\tdie()\n\t}\n\treturn spec\n}\n\n\/\/ reviewers is the list of reviewers for the current repository,\n\/\/ sorted by how many reviews each has done.\nvar reviewers []reviewer\n\ntype reviewer struct {\n\taddr  string\n\tcount int\n}\n\n\/\/ mailLookup translates the short name (like adg) into a full\n\/\/ email address (like adg@golang.org).\n\/\/ It returns \"\" if no translation is found.\n\/\/ The algorithm for expanding short user names is as follows:\n\/\/ Look at the git commit log for the current repository,\n\/\/ extracting all the email addresses in Reviewed-By lines\n\/\/ and sorting by how many times each address appears.\n\/\/ For each short user name, walk the list, most common\n\/\/ address first, and use the first address found that has\n\/\/ the short user name on the left side of the @.\nfunc mailLookup(short string) string {\n\tloadReviewers()\n\n\tshort += \"@\"\n\tfor _, r := range reviewers {\n\t\tif strings.HasPrefix(r.addr, short) {\n\t\t\treturn r.addr\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\/\/ loadReviewers reads the reviewer list from the current git repo\n\/\/ and leaves it in the global variable reviewers.\n\/\/ See the comment on mailLookup for a description of how the\n\/\/ list is generated and used.\nfunc loadReviewers() {\n\tif reviewers != nil {\n\t\treturn\n\t}\n\tcountByAddr := map[string]int{}\n\tfor _, line := range nonBlankLines(cmdOutput(\"git\", \"log\", \"--format=format:%B\")) {\n\t\tif strings.HasPrefix(line, \"Reviewed-by:\") {\n\t\t\tf := strings.Fields(line)\n\t\t\taddr := f[len(f)-1]\n\t\t\tif strings.HasPrefix(addr, \"<\") && strings.Contains(addr, \"@\") && strings.HasSuffix(addr, \">\") {\n\t\t\t\tcountByAddr[addr[1:len(addr)-1]]++\n\t\t\t}\n\t\t}\n\t}\n\n\treviewers = []reviewer{}\n\tfor addr, count := range countByAddr {\n\t\treviewers = append(reviewers, reviewer{addr, count})\n\t}\n\tsort.Sort(reviewersByCount(reviewers))\n}\n\ntype reviewersByCount []reviewer\n\nfunc (x reviewersByCount) Len() int      { return len(x) }\nfunc (x reviewersByCount) Swap(i, j int) { x[i], x[j] = x[j], x[i] }\nfunc (x reviewersByCount) Less(i, j int) bool {\n\tif x[i].count != x[j].count {\n\t\treturn x[i].count > x[j].count\n\t}\n\treturn x[i].addr < x[j].addr\n}\n\n\/\/ stringList is a flag.Value that is like flag.String, but if repeated\n\/\/ keeps appending to the old value, inserting commas as separators.\n\/\/ This allows people to write -r rsc,adg (like the old hg command)\n\/\/ but also -r rsc -r adg (like standard git commands).\n\/\/ This does change the meaning of -r rsc -r adg (it used to mean just adg).\ntype stringList string\n\nfunc (x *stringList) String() string {\n\treturn string(*x)\n}\n\nfunc (x *stringList) Set(s string) error {\n\tif *x != \"\" && s != \"\" {\n\t\t*x += \",\"\n\t}\n\t*x += stringList(s)\n\treturn nil\n}\n<commit_msg>git-codereview: set x.mailed tag to mailed commit instead of HEAD<commit_after>\/\/ Copyright 2014 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n)\n\nfunc cmdMail(args []string) {\n\tvar (\n\t\tdiff   = flags.Bool(\"diff\", false, \"show change commit diff and don't upload or mail\")\n\t\tforce  = flags.Bool(\"f\", false, \"mail even if there are staged changes\")\n\t\ttopic  = flags.String(\"topic\", \"\", \"set Gerrit topic\")\n\t\trList  = new(stringList) \/\/ installed below\n\t\tccList = new(stringList) \/\/ installed below\n\t)\n\tflags.Var(rList, \"r\", \"comma-separated list of reviewers\")\n\tflags.Var(ccList, \"cc\", \"comma-separated list of people to CC:\")\n\n\tflags.Usage = func() {\n\t\tfmt.Fprintf(stderr(), \"Usage: %s mail %s [-r reviewer,...] [-cc mail,...] [-topic topic] [commit-hash]\\n\", os.Args[0], globalFlags)\n\t}\n\tflags.Parse(args)\n\tif len(flags.Args()) > 1 {\n\t\tflags.Usage()\n\t\tos.Exit(2)\n\t}\n\n\tb := CurrentBranch()\n\n\tvar c *Commit\n\tif len(flags.Args()) == 1 {\n\t\tc = b.CommitByHash(\"mail\", flags.Arg(0))\n\t} else {\n\t\tc = b.DefaultCommit(\"mail\")\n\t}\n\n\tif *diff {\n\t\trun(\"git\", \"diff\", b.Branchpoint()[:7]+\"..\"+c.ShortHash, \"--\")\n\t\treturn\n\t}\n\n\tif !*force && HasStagedChanges() {\n\t\tdief(\"there are staged changes; aborting.\\n\"+\n\t\t\t\"Use '%s change' to include them or '%s mail -f' to force it.\", os.Args[0], os.Args[0])\n\t}\n\n\t\/\/ for side effect of dying with a good message if origin is GitHub\n\tloadGerritOrigin()\n\n\trefSpec := b.PushSpec(c)\n\tstart := \"%\"\n\tif *rList != \"\" {\n\t\trefSpec += mailList(start, \"r\", string(*rList))\n\t\tstart = \",\"\n\t}\n\tif *ccList != \"\" {\n\t\trefSpec += mailList(start, \"cc\", string(*ccList))\n\t\tstart = \",\"\n\t}\n\tif *topic != \"\" {\n\t\t\/\/ There's no way to escape the topic, but the only\n\t\t\/\/ ambiguous character is ',' (though other characters\n\t\t\/\/ like ' ' will be rejected outright by git).\n\t\tif strings.Contains(*topic, \",\") {\n\t\t\tdief(\"topic may not contain a comma\")\n\t\t}\n\t\trefSpec += start + \"topic=\" + *topic\n\t}\n\trun(\"git\", \"push\", \"-q\", \"origin\", refSpec)\n\n\t\/\/ Create local tag for mailed change.\n\t\/\/ If in the 'work' branch, this creates or updates work.mailed.\n\t\/\/ Older mailings are in the reflog, so work.mailed is newest,\n\t\/\/ work.mailed@{1} is the one before that, work.mailed@{2} before that,\n\t\/\/ and so on.\n\t\/\/ Git doesn't actually have a concept of a local tag,\n\t\/\/ but Gerrit won't let people push tags to it, so the tag\n\t\/\/ can't propagate out of the local client into the official repo.\n\t\/\/ There is no conflict with the branch names people are using\n\t\/\/ for work, because git change rejects any name containing a dot.\n\t\/\/ The space of names with dots is ours (the Go team's) to define.\n\trun(\"git\", \"tag\", \"-f\", b.Name+\".mailed\", c.ShortHash)\n}\n\n\/\/ PushSpec returns the spec for a Gerrit push command to publish the change c in b.\n\/\/ If c is nil, PushSpec returns a spec for pushing all changes in b.\nfunc (b *Branch) PushSpec(c *Commit) string {\n\tlocal := \"HEAD\"\n\tif c != nil && (len(b.Pending()) == 0 || b.Pending()[0].Hash != c.Hash) {\n\t\tlocal = c.ShortHash\n\t}\n\treturn local + \":refs\/for\/\" + strings.TrimPrefix(b.OriginBranch(), \"origin\/\")\n}\n\n\/\/ mailAddressRE matches the mail addresses we admit. It's restrictive but admits\n\/\/ all the addresses in the Go CONTRIBUTORS file at time of writing (tested separately).\nvar mailAddressRE = regexp.MustCompile(`^([a-zA-Z0-9][-_.a-zA-Z0-9]*)(@[-_.a-zA-Z0-9]+)?$`)\n\n\/\/ mailList turns the list of mail addresses from the flag value into the format\n\/\/ expected by gerrit. The start argument is a % or , depending on where we\n\/\/ are in the processing sequence.\nfunc mailList(start, tag string, flagList string) string {\n\terrors := false\n\tspec := start\n\tshort := \"\"\n\tlong := \"\"\n\tfor i, addr := range strings.Split(flagList, \",\") {\n\t\tm := mailAddressRE.FindStringSubmatch(addr)\n\t\tif m == nil {\n\t\t\tprintf(\"invalid reviewer mail address: %s\", addr)\n\t\t\terrors = true\n\t\t\tcontinue\n\t\t}\n\t\tif m[2] == \"\" {\n\t\t\temail := mailLookup(addr)\n\t\t\tif email == \"\" {\n\t\t\t\tprintf(\"unknown reviewer: %s\", addr)\n\t\t\t\terrors = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tshort += \",\" + addr\n\t\t\tlong += \",\" + email\n\t\t\taddr = email\n\t\t}\n\t\tif i > 0 {\n\t\t\tspec += \",\"\n\t\t}\n\t\tspec += tag + \"=\" + addr\n\t}\n\tif short != \"\" {\n\t\tverbosef(\"expanded %s to %s\", short[1:], long[1:])\n\t}\n\tif errors {\n\t\tdie()\n\t}\n\treturn spec\n}\n\n\/\/ reviewers is the list of reviewers for the current repository,\n\/\/ sorted by how many reviews each has done.\nvar reviewers []reviewer\n\ntype reviewer struct {\n\taddr  string\n\tcount int\n}\n\n\/\/ mailLookup translates the short name (like adg) into a full\n\/\/ email address (like adg@golang.org).\n\/\/ It returns \"\" if no translation is found.\n\/\/ The algorithm for expanding short user names is as follows:\n\/\/ Look at the git commit log for the current repository,\n\/\/ extracting all the email addresses in Reviewed-By lines\n\/\/ and sorting by how many times each address appears.\n\/\/ For each short user name, walk the list, most common\n\/\/ address first, and use the first address found that has\n\/\/ the short user name on the left side of the @.\nfunc mailLookup(short string) string {\n\tloadReviewers()\n\n\tshort += \"@\"\n\tfor _, r := range reviewers {\n\t\tif strings.HasPrefix(r.addr, short) {\n\t\t\treturn r.addr\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\/\/ loadReviewers reads the reviewer list from the current git repo\n\/\/ and leaves it in the global variable reviewers.\n\/\/ See the comment on mailLookup for a description of how the\n\/\/ list is generated and used.\nfunc loadReviewers() {\n\tif reviewers != nil {\n\t\treturn\n\t}\n\tcountByAddr := map[string]int{}\n\tfor _, line := range nonBlankLines(cmdOutput(\"git\", \"log\", \"--format=format:%B\")) {\n\t\tif strings.HasPrefix(line, \"Reviewed-by:\") {\n\t\t\tf := strings.Fields(line)\n\t\t\taddr := f[len(f)-1]\n\t\t\tif strings.HasPrefix(addr, \"<\") && strings.Contains(addr, \"@\") && strings.HasSuffix(addr, \">\") {\n\t\t\t\tcountByAddr[addr[1:len(addr)-1]]++\n\t\t\t}\n\t\t}\n\t}\n\n\treviewers = []reviewer{}\n\tfor addr, count := range countByAddr {\n\t\treviewers = append(reviewers, reviewer{addr, count})\n\t}\n\tsort.Sort(reviewersByCount(reviewers))\n}\n\ntype reviewersByCount []reviewer\n\nfunc (x reviewersByCount) Len() int      { return len(x) }\nfunc (x reviewersByCount) Swap(i, j int) { x[i], x[j] = x[j], x[i] }\nfunc (x reviewersByCount) Less(i, j int) bool {\n\tif x[i].count != x[j].count {\n\t\treturn x[i].count > x[j].count\n\t}\n\treturn x[i].addr < x[j].addr\n}\n\n\/\/ stringList is a flag.Value that is like flag.String, but if repeated\n\/\/ keeps appending to the old value, inserting commas as separators.\n\/\/ This allows people to write -r rsc,adg (like the old hg command)\n\/\/ but also -r rsc -r adg (like standard git commands).\n\/\/ This does change the meaning of -r rsc -r adg (it used to mean just adg).\ntype stringList string\n\nfunc (x *stringList) String() string {\n\treturn string(*x)\n}\n\nfunc (x *stringList) Set(s string) error {\n\tif *x != \"\" && s != \"\" {\n\t\t*x += \",\"\n\t}\n\t*x += stringList(s)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package github\n\nimport (\n\t\"github.com\/bmizerany\/assert\"\n\t\"testing\"\n)\n\nfunc TestWebURL(t *testing.T) {\n\tproject := Project{\"foo\", \"bar\"}\n\turl := project.WebURL(\"\", \"\", \"baz\")\n\tassert.Equal(t, \"https:\/\/github.com\/bar\/foo\/baz\", url)\n\n\turl = project.WebURL(\"1\", \"2\", \"\")\n\tassert.Equal(t, \"https:\/\/github.com\/2\/1\", url)\n}\n\nfunc TestParseNameAndOwner(t *testing.T) {\n\towner, name := parseOwnerAndName()\n\tassert.Equal(t, \"gh\", name)\n\n\townerNotEmpty := len(owner) != 0\n\tassert.Equal(t, ownerNotEmpty, true)\n}\n\nfunc TestMustMatchGitHubURL(t *testing.T) {\n\turl, _ := mustMatchGitHubURL(\"git:\/\/github.com\/jingweno\/gh.git\")\n\tassert.Equal(t, \"git:\/\/github.com\/jingweno\/gh.git\", url[0])\n\n\turl, _ = mustMatchGitHubURL(\"git@github.com:jingweno\/gh.git\")\n\tassert.Equal(t, \"git@github.com:jingweno\/gh.git\", url[0])\n\n\turl, _ = mustMatchGitHubURL(\"https:\/\/github.com\/jingweno\/gh.git\")\n\tassert.Equal(t, \"https:\/\/github.com\/jingweno\/gh.git\", url[0])\n}\n<commit_msg>Clean up TestParseNameAndOwner<commit_after>package github\n\nimport (\n\t\"github.com\/bmizerany\/assert\"\n\t\"testing\"\n)\n\nfunc TestWebURL(t *testing.T) {\n\tproject := Project{\"foo\", \"bar\"}\n\turl := project.WebURL(\"\", \"\", \"baz\")\n\tassert.Equal(t, \"https:\/\/github.com\/bar\/foo\/baz\", url)\n\n\turl = project.WebURL(\"1\", \"2\", \"\")\n\tassert.Equal(t, \"https:\/\/github.com\/2\/1\", url)\n}\n\nfunc TestParseNameAndOwner(t *testing.T) {\n\towner, name := parseOwnerAndName()\n\n\tassert.Equal(t, \"gh\", name)\n\tassert.T(t, len(owner) > 0)\n}\n\nfunc TestMustMatchGitHubURL(t *testing.T) {\n\turl, _ := mustMatchGitHubURL(\"git:\/\/github.com\/jingweno\/gh.git\")\n\tassert.Equal(t, \"git:\/\/github.com\/jingweno\/gh.git\", url[0])\n\n\turl, _ = mustMatchGitHubURL(\"git@github.com:jingweno\/gh.git\")\n\tassert.Equal(t, \"git@github.com:jingweno\/gh.git\", url[0])\n\n\turl, _ = mustMatchGitHubURL(\"https:\/\/github.com\/jingweno\/gh.git\")\n\tassert.Equal(t, \"https:\/\/github.com\/jingweno\/gh.git\", url[0])\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015-present Oursky Ltd.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage migration\n\n\nimport (\n\t\"fmt\"\n\n  \"github.com\/jmoiron\/sqlx\"\n)\n\ntype ReservedColumnExistedError struct {\n\ttable  string\n\tcolumn string\n}\n\nfunc (e *ReservedColumnExistedError) Error() string {\n\t\/\/ TODO: put a link of guide here for those who failed to migrate\n\treturn fmt.Sprintf(`Reserved column %s.%s has already been existed`, e.table, e.column)\n}\n\ntype revision_f0c53134d25d struct {\n}\n\nfunc (r *revision_f0c53134d25d) Version() string {\n\treturn \"f0c53134d25d\"\n}\n\nfunc (r *revision_f0c53134d25d) IsTableExisted(tx *sqlx.Tx, table string) (bool, error) {\n\tvar exists bool\n\terr := tx.QueryRowx(`\nSELECT EXISTS (\n\tSELECT 1\n\tFROM information_schema.tables\n\tWHERE\n\t\ttable_schema = current_schema() AND\n\t\ttable_name = $1\n);\n\t\t`, table).Scan(&exists)\n\treturn exists, err\n}\n\nfunc (r *revision_f0c53134d25d) IsColumnExisted(tx *sqlx.Tx, table string, column string) (bool, error) {\n\tvar exists bool\n\terr := tx.QueryRowx(`\nSELECT EXISTS (\n\tSELECT 1\n\tFROM information_schema.columns\n\tWHERE\n\t\ttable_schema = current_schema() AND\n\t\ttable_name = $1 AND\n\t\tcolumn_name = $2\n);\n\t\t`, table, column).Scan(&exists)\n\treturn exists, err\n}\n\nfunc (r *revision_f0c53134d25d) EnsureReservedColumnsNotExisted(tx *sqlx.Tx) error {\n\ttable := `user`\n\tcolumns := [2]string{`username`, `email`}\n\n\tfor _, column := range columns {\n\t\tisExisted, err := r.IsColumnExisted(tx, table, column)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif isExisted {\n\t\t\treturn &ReservedColumnExistedError{table: table, column: column}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (r *revision_f0c53134d25d) Up(tx *sqlx.Tx) error {\n\tmigrateSkygearUserStmt := `\n-- Migrate _user to _auth\nALTER TABLE _user_role DROP CONSTRAINT _user_role_user_id_fkey;\nALTER TABLE _device DROP CONSTRAINT _device_user_id_fkey;\nALTER TABLE _friend DROP CONSTRAINT _friend_right_id_fkey;\nALTER TABLE _follow DROP CONSTRAINT _follow_right_id_fkey;\n\nALTER TABLE _user_role RENAME TO _auth_role;\n\nALTER TABLE _user RENAME TO _auth;\n\nALTER TABLE _auth_role RENAME user_id TO auth_id;\nALTER TABLE _device RENAME user_id TO auth_id;\nALTER TABLE _subscription RENAME user_id TO auth_id;\n\nALTER TABLE _auth_role\n\tADD CONSTRAINT _auth_role_auth_id_fkey FOREIGN KEY (auth_id) REFERENCES _auth (id);\nALTER TABLE _device\n\tADD CONSTRAINT _device_auth_id_fkey FOREIGN KEY (auth_id) REFERENCES _auth (id);\nALTER TABLE _friend\n\tADD CONSTRAINT _friend_right_id_fkey FOREIGN KEY (right_id) REFERENCES _auth (id);\nALTER TABLE _follow\n\tADD CONSTRAINT _follow_right_id_fkey FOREIGN KEY (right_id) REFERENCES _auth (id);\n\nCREATE VIEW _user AS\nSELECT * FROM _auth;\n\nALTER TABLE _auth RENAME auth to provider_info;\n\t `\n\t_, err := tx.Exec(migrateSkygearUserStmt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = r.EnsureReservedColumnsNotExisted(tx); err != nil {\n\t\treturn err\n\t}\n\n\tvar userTableExists bool\n\tuserTableExists, err = r.IsTableExisted(tx, `user`)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar migrateUserStmt string\n\tif userTableExists {\n\t\tmigrateUserStmt = `\n-- Migrate username and email to user table\nALTER TABLE user ADD COLUMN username citext UNIQUE;\nALTER TABLE user ADD COLUMN email citext UNIQUE;\n\nUPDATE user\nSET\n\tusername = a.username,\n\temail = a.email\nFROM _auth as a;\n\nALTER TABLE _auth DROP COLUMN username citext UNIQUE;\nALTER TABLE _auth DROP COLUMN email citext UNIQUE;\n\t\t`\n\t} else {\n\t\tmigrateUserStmt = `\n-- Create user table if not existed\nCREATE TABLE user (\n    _id text,\n    _database_id text,\n    _owner_id text,\n    _access jsonb,\n    _created_at timestamp without time zone NOT NULL,\n    _created_by text,\n    _updated_at timestamp without time zone NOT NULL,\n    _updated_by text,\n    username citext,\n    email citext,\n    PRIMARY KEY(_id, _database_id, _owner_id),\n    UNIQUE (_id),\n    UNIQUE (username),\n    UNIQUE (email)\n);\n\t\t`\n\t}\n\n\t_, err = tx.Exec(migrateUserStmt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (r *revision_f0c53134d25d) Down(tx *sqlx.Tx) error {\n\tmigrateUserStmt := `\n-- Migrate username and email to user table (backward)\nALTER TABLE _auth ADD COLUMN username citext UNIQUE;\nALTER TABLE _auth ADD COLUMN email citext UNIQUE;\n\nUPDATE _auth\nSET\n\tusername = u.username,\n\temail = u.email\nFROM user as u;\n\nALTER TABLE user DROP COLUMN username citext UNIQUE;\nALTER TABLE user DROP COLUMN email citext UNIQUE;\n\t\t`\n\t_, err := tx.Exec(migrateUserStmt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmigrateSkygearUserStmt := `\n-- Migrate _user to _auth (backward)\nALTER TABLE _auth RENAME provider_info to auth;\n\nDROP VIEW _user;\n\nALTER TABLE _auth_role DROP CONSTRAINT _auth_role_auth_id_fkey;\nALTER TABLE _device DROP CONSTRAINT _device_auth_id_fkey;\nALTER TABLE _friend DROP CONSTRAINT _friend_right_id_fkey;\nALTER TABLE _follow DROP CONSTRAINT _follow_right_id_fkey;\n\nALTER TABLE _auth_role RENAME auth_id TO user_id;\nALTER TABLE _device RENAME auth_id TO user_id;\nALTER TABLE _subscription RENAME auth_id TO user_id;\n\nALTER TABLE _auth RENAME TO _user;\n\nALTER TABLE _auth_role RENAME TO _user_role;\n\nALTER TABLE _user_role\n\tADD CONSTRAINT _user_role_user_id_fkey FOREIGN KEY (user_id) REFERENCES _user (id);\nALTER TABLE _device\n\tADD CONSTRAINT _device_user_id_fkey FOREIGN KEY (user_id) REFERENCES _user (id);\nALTER TABLE _friend\n\tADD CONSTRAINT _friend_right_id_fkey FOREIGN KEY (right_id) REFERENCES _user (id);\nALTER TABLE _follow\n\tADD CONSTRAINT _follow_right_id_fkey FOREIGN KEY (right_id) REFERENCES _user (id);\n\t`\n\n\t_, err = tx.Exec(migrateSkygearUserStmt)\n\treturn err\n}\n<commit_msg>Fix sql syntax error<commit_after>\/\/ Copyright 2015-present Oursky Ltd.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage migration\n\n\nimport (\n\t\"fmt\"\n\n  \"github.com\/jmoiron\/sqlx\"\n)\n\ntype ReservedColumnExistedError struct {\n\ttable  string\n\tcolumn string\n}\n\nfunc (e *ReservedColumnExistedError) Error() string {\n\t\/\/ TODO: put a link of guide here for those who failed to migrate\n\treturn fmt.Sprintf(`Reserved column %s.%s has already been existed`, e.table, e.column)\n}\n\ntype revision_f0c53134d25d struct {\n}\n\nfunc (r *revision_f0c53134d25d) Version() string {\n\treturn \"f0c53134d25d\"\n}\n\nfunc (r *revision_f0c53134d25d) IsTableExisted(tx *sqlx.Tx, table string) (bool, error) {\n\tvar exists bool\n\terr := tx.QueryRowx(`\nSELECT EXISTS (\n\tSELECT 1\n\tFROM information_schema.tables\n\tWHERE\n\t\ttable_schema = current_schema() AND\n\t\ttable_name = $1\n);\n\t\t`, table).Scan(&exists)\n\treturn exists, err\n}\n\nfunc (r *revision_f0c53134d25d) IsColumnExisted(tx *sqlx.Tx, table string, column string) (bool, error) {\n\tvar exists bool\n\terr := tx.QueryRowx(`\nSELECT EXISTS (\n\tSELECT 1\n\tFROM information_schema.columns\n\tWHERE\n\t\ttable_schema = current_schema() AND\n\t\ttable_name = $1 AND\n\t\tcolumn_name = $2\n);\n\t\t`, table, column).Scan(&exists)\n\treturn exists, err\n}\n\nfunc (r *revision_f0c53134d25d) EnsureReservedColumnsNotExisted(tx *sqlx.Tx) error {\n\ttable := `user`\n\tcolumns := [2]string{`username`, `email`}\n\n\tfor _, column := range columns {\n\t\tisExisted, err := r.IsColumnExisted(tx, table, column)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif isExisted {\n\t\t\treturn &ReservedColumnExistedError{table: table, column: column}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (r *revision_f0c53134d25d) Up(tx *sqlx.Tx) error {\n\tmigrateSkygearUserStmt := `\n-- Migrate _user to _auth\nALTER TABLE _user_role DROP CONSTRAINT _user_role_user_id_fkey;\nALTER TABLE _device DROP CONSTRAINT _device_user_id_fkey;\nALTER TABLE _friend DROP CONSTRAINT _friend_right_id_fkey;\nALTER TABLE _follow DROP CONSTRAINT _follow_right_id_fkey;\n\nALTER TABLE _user_role RENAME TO _auth_role;\n\nALTER TABLE _user RENAME TO _auth;\n\nALTER TABLE _auth_role RENAME user_id TO auth_id;\nALTER TABLE _device RENAME user_id TO auth_id;\nALTER TABLE _subscription RENAME user_id TO auth_id;\n\nALTER TABLE _auth_role\n\tADD CONSTRAINT _auth_role_auth_id_fkey FOREIGN KEY (auth_id) REFERENCES _auth (id);\nALTER TABLE _device\n\tADD CONSTRAINT _device_auth_id_fkey FOREIGN KEY (auth_id) REFERENCES _auth (id);\nALTER TABLE _friend\n\tADD CONSTRAINT _friend_right_id_fkey FOREIGN KEY (right_id) REFERENCES _auth (id);\nALTER TABLE _follow\n\tADD CONSTRAINT _follow_right_id_fkey FOREIGN KEY (right_id) REFERENCES _auth (id);\n\nCREATE VIEW _user AS\nSELECT * FROM _auth;\n\nALTER TABLE _auth RENAME auth to provider_info;\n\t `\n\t_, err := tx.Exec(migrateSkygearUserStmt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = r.EnsureReservedColumnsNotExisted(tx); err != nil {\n\t\treturn err\n\t}\n\n\tvar userTableExists bool\n\tuserTableExists, err = r.IsTableExisted(tx, `user`)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar migrateUserStmt string\n\tif userTableExists {\n\t\tmigrateUserStmt = `\n-- Migrate username and email to user table\nALTER TABLE \"user\" ADD COLUMN username citext UNIQUE;\nALTER TABLE \"user\" ADD COLUMN email citext UNIQUE;\n\nUPDATE \"user\"\nSET\n\tusername = a.username,\n\temail = a.email\nFROM _auth as a\nWHERE a.id = \"user\"._id;\n\nALTER TABLE _auth DROP COLUMN username;\nALTER TABLE _auth DROP COLUMN email;\n\t\t`\n\t} else {\n\t\tmigrateUserStmt = `\n-- Create user table if not existed\nCREATE TABLE \"user\" (\n    _id text,\n    _database_id text,\n    _owner_id text,\n    _access jsonb,\n    _created_at timestamp without time zone NOT NULL,\n    _created_by text,\n    _updated_at timestamp without time zone NOT NULL,\n    _updated_by text,\n    username citext,\n    email citext,\n    PRIMARY KEY(_id, _database_id, _owner_id),\n    UNIQUE (_id),\n    UNIQUE (username),\n    UNIQUE (email)\n);\n\t\t`\n\t}\n\n\t_, err = tx.Exec(migrateUserStmt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (r *revision_f0c53134d25d) Down(tx *sqlx.Tx) error {\n\tmigrateUserStmt := `\n-- Migrate username and email to user table (backward)\nALTER TABLE _auth ADD COLUMN username citext UNIQUE;\nALTER TABLE _auth ADD COLUMN email citext UNIQUE;\n\nUPDATE _auth\nSET\n\tusername = u.username,\n\temail = u.email\nFROM \"user\" as u\nWHERE _auth.id = u._id;\n\nALTER TABLE \"user\" DROP COLUMN username;\nALTER TABLE \"user\" DROP COLUMN email;\n\t\t`\n\t_, err := tx.Exec(migrateUserStmt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmigrateSkygearUserStmt := `\n-- Migrate _user to _auth (backward)\nALTER TABLE _auth RENAME provider_info to auth;\n\nDROP VIEW _user;\n\nALTER TABLE _auth_role DROP CONSTRAINT _auth_role_auth_id_fkey;\nALTER TABLE _device DROP CONSTRAINT _device_auth_id_fkey;\nALTER TABLE _friend DROP CONSTRAINT _friend_right_id_fkey;\nALTER TABLE _follow DROP CONSTRAINT _follow_right_id_fkey;\n\nALTER TABLE _auth_role RENAME auth_id TO user_id;\nALTER TABLE _device RENAME auth_id TO user_id;\nALTER TABLE _subscription RENAME auth_id TO user_id;\n\nALTER TABLE _auth RENAME TO _user;\n\nALTER TABLE _auth_role RENAME TO _user_role;\n\nALTER TABLE _user_role\n\tADD CONSTRAINT _user_role_user_id_fkey FOREIGN KEY (user_id) REFERENCES _user (id);\nALTER TABLE _device\n\tADD CONSTRAINT _device_user_id_fkey FOREIGN KEY (user_id) REFERENCES _user (id);\nALTER TABLE _friend\n\tADD CONSTRAINT _friend_right_id_fkey FOREIGN KEY (right_id) REFERENCES _user (id);\nALTER TABLE _follow\n\tADD CONSTRAINT _follow_right_id_fkey FOREIGN KEY (right_id) REFERENCES _user (id);\n\t`\n\n\t_, err = tx.Exec(migrateSkygearUserStmt)\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package stardb\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"time\"\n\n\t\"gopkg.in\/mgo.v2\"\n\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\ntype Farm struct {\n\n\t\/\/ Fields with  `json:\"-\"` are ommited for web display\n\n\tInternalID bson.ObjectId `bson:\"_id,omitempty\" json:\"-\"`\n\tID         string        \/\/ Like InternalID, but in hex format. This can be exposed on the web.\n\tUniqueID   int           `json:\"-\"`\n\tName       string\n\tFarmer     string\n\tLikes      int\n\tLastUpdate time.Time\n\tThumbnail  string\n}\n\nfunc (f *Farm) ScreenshotPath() string {\n\treturn fmt.Sprintf(\"\/screenshot\/%v\/%d.png\", f.InternalID.Hex(), f.LastUpdate.Unix())\n}\n\nfunc (f *Farm) saveGamePath() string {\n\treturn SaveGamePath(f.InternalID.Hex(), f.LastUpdate)\n}\n\nfunc SaveGamePath(id string, ts time.Time) string {\n\treturn fmt.Sprintf(\"\/saveGames\/%v\/%d.xml\", id, ts.Unix())\n}\n\nfunc FarmsJSON() ([]byte, error) {\n\tvar farms []*Farm\n\n\tif err := FarmCollection.Find(nil).Sort(\"-lastupdate\").Limit(20).All(&farms); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, farm := range farms {\n\t\tfarm.Thumbnail = farm.ScreenshotPath()\n\t\tfarm.ID = farm.InternalID.Hex()\n\t}\n\treturn json.Marshal(farms)\n}\n\nfunc FarmJSON(id string) ([]byte, error) {\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn nil, fmt.Errorf(\"invalid farm id\")\n\t}\n\tvar farm *Farm\n\tif err := FarmCollection.Find(bson.M{\"_id\": bson.ObjectIdHex(id)}).One(&farm); err != nil {\n\t\treturn nil, err\n\t}\n\tfarm.Thumbnail = farm.ScreenshotPath()\n\tfarm.ID = farm.InternalID.Hex()\n\n\treturn json.Marshal(farm)\n}\n\nfunc LegacyMap(farmer string) (*Farm, error) {\n\tvar farm *Farm\n\tif err := FarmCollection.Find(bson.M{\"farmer\": farmer}).One(&farm); err != nil {\n\t\treturn nil, fmt.Errorf(\"error finding farm: %v\", err)\n\t}\n\tfarm.ID = farm.InternalID.Hex()\n\treturn farm, nil\n}\n\nfunc SearchFarmsJSON(query string) ([]byte, error) {\n\tvar farms []*Farm\n\tre := bson.RegEx{query, \"i\"}\n\tif err := FarmCollection.Find(\n\t\tbson.M{\"$or\": []interface{}{\n\t\t\tbson.M{\"name\": bson.M{\"$regex\": re}},\n\t\t\tbson.M{\"farmer\": bson.M{\"$regex\": re}},\n\t\t}}).Sort(\"-lastupdate\").Limit(20).All(&farms); err != nil {\n\t\treturn nil, err\n\n\t}\n\tfor _, farm := range farms {\n\t\tfarm.Thumbnail = farm.ScreenshotPath()\n\t\tfarm.ID = farm.InternalID.Hex()\n\t}\n\treturn json.Marshal(farms)\n}\n\nfunc UpdateFarmTime(id bson.ObjectId, ts time.Time) error {\n\treturn FarmCollection.Update(bson.M{\"_id\": id}, bson.M{\"$set\": bson.M{\"lastupdate\": ts}})\n}\n\nfunc FindFarm(c *mgo.Collection, uniqueIDForThisGame int, playerName, farmName string) (ret *Farm, existing bool, err error) {\n\tret = &Farm{}\n\tq := c.Find(bson.M{\n\t\t\"name\":     farmName,\n\t\t\"farmer\":   playerName,\n\t\t\"uniqueid\": uniqueIDForThisGame,\n\t})\n\tif err := q.One(&ret); err != nil {\n\t\tlog.Println(\"not found\", err)\n\n\t\tfarm := &Farm{\n\t\t\tName:       farmName,\n\t\t\tFarmer:     playerName,\n\t\t\tUniqueID:   uniqueIDForThisGame,\n\t\t\tInternalID: bson.NewObjectId(),\n\t\t\tLastUpdate: time.Now(),\n\t\t}\n\t\tif err := c.Insert(farm); err != nil {\n\t\t\tlog.Println(\"could not insert\", err)\n\t\t\treturn nil, false, err\n\t\t}\n\t\tlog.Println(\"insert ok\", farm.InternalID.String())\n\t\treturn farm, false, nil\n\t}\n\tlog.Printf(\"found ok %v, %v, %v\", ret.Name, ret.Farmer, ret.LastUpdate)\n\n\treturn ret, true, nil\n}\n\nfunc WriteSaveFile(farm *Farm, body []byte, ts time.Time) error {\n\tfarm.LastUpdate = ts\n\tsaveFile := farm.saveGamePath()\n\tg, err := GFS.Create(saveFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error opening grid saveGames %v: %v\", saveFile, err)\n\n\t}\n\tg.SetUploadDate(ts)\n\tdefer g.Close()\n\tif _, err := g.Write(body); err != nil {\n\t\treturn fmt.Errorf(\"Failed to write grid save file at %v: %v\", saveFile, err)\n\t}\n\n\tlog.Printf(\"Wrote grid saveGame file %v\", saveFile)\n\treturn nil\n}\n\n\/\/ NewScreenshotWriter saves a screenshot in GFS at screenshots\/<hexid>.png\nfunc NewScreenshotWriter(farm *Farm, ts time.Time) (io.WriteCloser, error) {\n\tif farm.LastUpdate.IsZero() {\n\t\treturn nil, fmt.Errorf(\"error writing screenshot: unexpected zero save time\")\n\t}\n\tg, err := GFS.Create(farm.ScreenshotPath())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tg.SetUploadDate(ts)\n\treturn g, nil\n}\n<commit_msg>dont show LastUpdate on JSON for now<commit_after>package stardb\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"time\"\n\n\t\"gopkg.in\/mgo.v2\"\n\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\ntype Farm struct {\n\n\t\/\/ Fields with  `json:\"-\"` are ommited for web display\n\n\tInternalID bson.ObjectId `bson:\"_id,omitempty\" json:\"-\"`\n\tID         string        \/\/ Like InternalID, but in hex format. This can be exposed on the web.\n\tUniqueID   int           `json:\"-\"`\n\tName       string\n\tFarmer     string\n\tLikes      int\n\t\/\/ TODO: stop omitting this once the web client understands it.\n\tLastUpdate time.Time `json:\"-\"`\n\tThumbnail  string\n}\n\nfunc (f *Farm) ScreenshotPath() string {\n\treturn fmt.Sprintf(\"\/screenshot\/%v\/%d.png\", f.InternalID.Hex(), f.LastUpdate.Unix())\n}\n\nfunc (f *Farm) saveGamePath() string {\n\treturn SaveGamePath(f.InternalID.Hex(), f.LastUpdate)\n}\n\nfunc SaveGamePath(id string, ts time.Time) string {\n\treturn fmt.Sprintf(\"\/saveGames\/%v\/%d.xml\", id, ts.Unix())\n}\n\nfunc FarmsJSON() ([]byte, error) {\n\tvar farms []*Farm\n\n\tif err := FarmCollection.Find(nil).Sort(\"-lastupdate\").Limit(20).All(&farms); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, farm := range farms {\n\t\tfarm.Thumbnail = farm.ScreenshotPath()\n\t\tfarm.ID = farm.InternalID.Hex()\n\t}\n\treturn json.Marshal(farms)\n}\n\nfunc FarmJSON(id string) ([]byte, error) {\n\tif !bson.IsObjectIdHex(id) {\n\t\treturn nil, fmt.Errorf(\"invalid farm id\")\n\t}\n\tvar farm *Farm\n\tif err := FarmCollection.Find(bson.M{\"_id\": bson.ObjectIdHex(id)}).One(&farm); err != nil {\n\t\treturn nil, err\n\t}\n\tfarm.Thumbnail = farm.ScreenshotPath()\n\tfarm.ID = farm.InternalID.Hex()\n\n\treturn json.Marshal(farm)\n}\n\nfunc LegacyMap(farmer string) (*Farm, error) {\n\tvar farm *Farm\n\tif err := FarmCollection.Find(bson.M{\"farmer\": farmer}).One(&farm); err != nil {\n\t\treturn nil, fmt.Errorf(\"error finding farm: %v\", err)\n\t}\n\tfarm.ID = farm.InternalID.Hex()\n\treturn farm, nil\n}\n\nfunc SearchFarmsJSON(query string) ([]byte, error) {\n\tvar farms []*Farm\n\tre := bson.RegEx{query, \"i\"}\n\tif err := FarmCollection.Find(\n\t\tbson.M{\"$or\": []interface{}{\n\t\t\tbson.M{\"name\": bson.M{\"$regex\": re}},\n\t\t\tbson.M{\"farmer\": bson.M{\"$regex\": re}},\n\t\t}}).Sort(\"-lastupdate\").Limit(20).All(&farms); err != nil {\n\t\treturn nil, err\n\n\t}\n\tfor _, farm := range farms {\n\t\tfarm.Thumbnail = farm.ScreenshotPath()\n\t\tfarm.ID = farm.InternalID.Hex()\n\t}\n\treturn json.Marshal(farms)\n}\n\nfunc UpdateFarmTime(id bson.ObjectId, ts time.Time) error {\n\treturn FarmCollection.Update(bson.M{\"_id\": id}, bson.M{\"$set\": bson.M{\"lastupdate\": ts}})\n}\n\nfunc FindFarm(c *mgo.Collection, uniqueIDForThisGame int, playerName, farmName string) (ret *Farm, existing bool, err error) {\n\tret = &Farm{}\n\tq := c.Find(bson.M{\n\t\t\"name\":     farmName,\n\t\t\"farmer\":   playerName,\n\t\t\"uniqueid\": uniqueIDForThisGame,\n\t})\n\tif err := q.One(&ret); err != nil {\n\t\tlog.Println(\"not found\", err)\n\n\t\tfarm := &Farm{\n\t\t\tName:       farmName,\n\t\t\tFarmer:     playerName,\n\t\t\tUniqueID:   uniqueIDForThisGame,\n\t\t\tInternalID: bson.NewObjectId(),\n\t\t\tLastUpdate: time.Now(),\n\t\t}\n\t\tif err := c.Insert(farm); err != nil {\n\t\t\tlog.Println(\"could not insert\", err)\n\t\t\treturn nil, false, err\n\t\t}\n\t\tlog.Println(\"insert ok\", farm.InternalID.String())\n\t\treturn farm, false, nil\n\t}\n\tlog.Printf(\"found ok %v, %v, %v\", ret.Name, ret.Farmer, ret.LastUpdate)\n\n\treturn ret, true, nil\n}\n\nfunc WriteSaveFile(farm *Farm, body []byte, ts time.Time) error {\n\tfarm.LastUpdate = ts\n\tsaveFile := farm.saveGamePath()\n\tg, err := GFS.Create(saveFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error opening grid saveGames %v: %v\", saveFile, err)\n\n\t}\n\tg.SetUploadDate(ts)\n\tdefer g.Close()\n\tif _, err := g.Write(body); err != nil {\n\t\treturn fmt.Errorf(\"Failed to write grid save file at %v: %v\", saveFile, err)\n\t}\n\n\tlog.Printf(\"Wrote grid saveGame file %v\", saveFile)\n\treturn nil\n}\n\n\/\/ NewScreenshotWriter saves a screenshot in GFS at screenshots\/<hexid>.png\nfunc NewScreenshotWriter(farm *Farm, ts time.Time) (io.WriteCloser, error) {\n\tif farm.LastUpdate.IsZero() {\n\t\treturn nil, fmt.Errorf(\"error writing screenshot: unexpected zero save time\")\n\t}\n\tg, err := GFS.Create(farm.ScreenshotPath())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tg.SetUploadDate(ts)\n\treturn g, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package account\n\nimport (\n\t\"bytes\"\n\tcryptorand \"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/cozy\/cozy-stack\/pkg\/config\/config\"\n\t\"github.com\/cozy\/cozy-stack\/pkg\/crypto\"\n\t\"github.com\/cozy\/cozy-stack\/pkg\/utils\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestEncryptDecrytCredentials(t *testing.T) {\n\tencryptedCreds1, err := EncryptCredentials(\"me@mycozy.cloud\", \"fzEE6HFWsSp8jP\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tencryptedCreds2, err := EncryptCredentials(\"me@mycozy.cloud\", \"fzEE6HFWsSp8jP\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tencryptedCreds3, err := EncryptCredentials(\"\", \"fzEE6HFWsSp8jP\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tassert.NotEqual(t, encryptedCreds1, encryptedCreds2)\n\n\t{\n\t\tlogin, password, err := DecryptCredentials(encryptedCreds1)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\t\tassert.Equal(t, \"me@mycozy.cloud\", login)\n\t\tassert.Equal(t, \"fzEE6HFWsSp8jP\", password)\n\t}\n\t{\n\t\tlogin, password, err := DecryptCredentials(encryptedCreds2)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\t\tassert.Equal(t, \"me@mycozy.cloud\", login)\n\t\tassert.Equal(t, \"fzEE6HFWsSp8jP\", password)\n\t}\n\t{\n\t\tlogin, password, err := DecryptCredentials(encryptedCreds3)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\t\tassert.Equal(t, \"\", login)\n\t\tassert.Equal(t, \"fzEE6HFWsSp8jP\", password)\n\t}\n}\n\nfunc TestEncryptDecrytUTF8Credentials(t *testing.T) {\n\trng := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := 0; i < 1024; i++ {\n\t\tlogin := string(crypto.GenerateRandomBytes(rng.Intn(256)))\n\t\tpassword := string(crypto.GenerateRandomBytes(rng.Intn(256)))\n\n\t\tencryptedCreds, err := EncryptCredentials(login, password)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\n\t\tloginDec, passwordDec, err := DecryptCredentials(encryptedCreds)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\n\t\tassert.Equal(t, loginDec, login)\n\t\tassert.Equal(t, passwordDec, password)\n\t}\n\n\tfor i := 0; i < 1024; i++ {\n\t\tlogin := utils.RandomString(rng.Intn(256))\n\t\tpassword := utils.RandomString(rng.Intn(256))\n\n\t\tencryptedCreds, err := EncryptCredentials(login, password)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\n\t\tloginDec, passwordDec, err := DecryptCredentials(encryptedCreds)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\n\t\tassert.Equal(t, loginDec, login)\n\t\tassert.Equal(t, passwordDec, password)\n\t}\n}\n\nfunc TestDecryptCredentialsRandom(t *testing.T) {\n\trng := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := 0; i < 1024; i++ {\n\t\tencrypted := base64.StdEncoding.EncodeToString(crypto.GenerateRandomBytes(rng.Intn(256)))\n\t\t_, _, err := DecryptCredentials(encrypted)\n\t\tassert.Error(t, err)\n\t}\n\tfor i := 0; i < 1024; i++ {\n\t\tencrypted := crypto.GenerateRandomBytes(rng.Intn(256))\n\t\tencryptedWithHeader := make([]byte, len(cipherHeader)+len(encrypted))\n\t\tcopy(encryptedWithHeader[0:], cipherHeader)\n\t\tcopy(encryptedWithHeader[len(cipherHeader):], encrypted)\n\t\t_, _, err := DecryptCredentials(base64.StdEncoding.EncodeToString(encryptedWithHeader))\n\t\tassert.Error(t, err)\n\t}\n}\n\nfunc TestRandomBitFlipsCredentials(t *testing.T) {\n\toriginal, err := EncryptCredentials(\"toto@titi.com\", \"X3hVYLJLRiUyCs\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\toriginalBuffer, err := base64.StdEncoding.DecodeString(original)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\n\tflipped := make([]byte, len(originalBuffer))\n\tcopy(flipped, originalBuffer)\n\tlogin, passwd, err := DecryptCredentials(base64.StdEncoding.EncodeToString(flipped))\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tassert.Equal(t, \"toto@titi.com\", login)\n\tassert.Equal(t, \"X3hVYLJLRiUyCs\", passwd)\n\n\trng := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := 0; i < 100000; i++ {\n\t\tcopy(flipped, originalBuffer)\n\t\tflipsLen := rng.Intn(30) + 1\n\t\tflipsSet := make([]int, 0, flipsLen)\n\t\tfor len(flipsSet) < flipsLen {\n\t\t\tflipValue := rng.Intn(len(originalBuffer) * 8)\n\t\t\tflipFound := false\n\t\t\tfor j := 0; j < len(flipsSet); j++ {\n\t\t\t\tif flipsSet[j] == flipValue {\n\t\t\t\t\tflipFound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !flipFound {\n\t\t\t\tflipsSet = append(flipsSet, flipValue)\n\t\t\t}\n\t\t}\n\t\tfor _, flipValue := range flipsSet {\n\t\t\tmask := byte(0x1 << uint(flipValue%8))\n\t\t\tflipped[flipValue\/8] ^= mask\n\t\t}\n\t\t_, _, err := DecryptCredentials(base64.StdEncoding.EncodeToString(flipped))\n\t\tif !assert.Error(t, err) {\n\t\t\tt.Fatalf(\"Failed with flips %v\", flipsSet)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc TestEncryptDecryptData(t *testing.T) {\n\tvar data interface{}\n\terr := json.Unmarshal([]byte(`{\"foo\":\"bar\",\"baz\":{\"quz\": \"quuz\"}}`), &data)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tencBuffer, err := EncryptCredentialsData(data)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tdecData, err := DecryptCredentialsData(encBuffer)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tassert.EqualValues(t, data, decData)\n}\n\nfunc TestRandomBitFlipsBuffer(t *testing.T) {\n\tplainBuffer := make([]byte, 256)\n\t_, err := io.ReadFull(cryptorand.Reader, plainBuffer)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\n\toriginal, err := EncryptBufferWithKey(config.GetVault().CredentialsEncryptorKey(), plainBuffer)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\n\tflipped := make([]byte, len(original))\n\tcopy(flipped, original)\n\ttestBuffer, err := DecryptBufferWithKey(config.GetVault().CredentialsDecryptorKey(), flipped)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tassert.True(t, bytes.Equal(plainBuffer, testBuffer))\n\n\trng := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := 0; i < 100000; i++ {\n\t\tcopy(flipped, original)\n\t\tflipsLen := rng.Intn(30) + 1\n\t\tflipsSet := make([]int, 0, flipsLen)\n\t\tfor len(flipsSet) < flipsLen {\n\t\t\tflipValue := rng.Intn(len(original) * 8)\n\t\t\tflipFound := false\n\t\t\tfor j := 0; j < len(flipsSet); j++ {\n\t\t\t\tif flipsSet[j] == flipValue {\n\t\t\t\t\tflipFound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !flipFound {\n\t\t\t\tflipsSet = append(flipsSet, flipValue)\n\t\t\t}\n\t\t}\n\t\tfor _, flipValue := range flipsSet {\n\t\t\tmask := byte(0x1 << uint(flipValue%8))\n\t\t\tflipped[flipValue\/8] ^= mask\n\t\t}\n\t\t_, err := DecryptBufferWithKey(config.GetVault().CredentialsDecryptorKey(), flipped)\n\t\tif !assert.Error(t, err) {\n\t\t\tt.Fatalf(\"Failed with flips %v\", flipsSet)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc TestMain(m *testing.M) {\n\tconfig.UseTestFile()\n\tos.Exit(m.Run())\n}\n<commit_msg>Make model\/account tests faster<commit_after>package account\n\nimport (\n\t\"bytes\"\n\tcryptorand \"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/cozy\/cozy-stack\/pkg\/config\/config\"\n\t\"github.com\/cozy\/cozy-stack\/pkg\/crypto\"\n\t\"github.com\/cozy\/cozy-stack\/pkg\/utils\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestEncryptDecrytCredentials(t *testing.T) {\n\tencryptedCreds1, err := EncryptCredentials(\"me@mycozy.cloud\", \"fzEE6HFWsSp8jP\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tencryptedCreds2, err := EncryptCredentials(\"me@mycozy.cloud\", \"fzEE6HFWsSp8jP\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tencryptedCreds3, err := EncryptCredentials(\"\", \"fzEE6HFWsSp8jP\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tassert.NotEqual(t, encryptedCreds1, encryptedCreds2)\n\n\t{\n\t\tlogin, password, err := DecryptCredentials(encryptedCreds1)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\t\tassert.Equal(t, \"me@mycozy.cloud\", login)\n\t\tassert.Equal(t, \"fzEE6HFWsSp8jP\", password)\n\t}\n\t{\n\t\tlogin, password, err := DecryptCredentials(encryptedCreds2)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\t\tassert.Equal(t, \"me@mycozy.cloud\", login)\n\t\tassert.Equal(t, \"fzEE6HFWsSp8jP\", password)\n\t}\n\t{\n\t\tlogin, password, err := DecryptCredentials(encryptedCreds3)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\t\tassert.Equal(t, \"\", login)\n\t\tassert.Equal(t, \"fzEE6HFWsSp8jP\", password)\n\t}\n}\n\nfunc TestEncryptDecrytUTF8Credentials(t *testing.T) {\n\trng := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := 0; i < 1024; i++ {\n\t\tlogin := string(crypto.GenerateRandomBytes(rng.Intn(256)))\n\t\tpassword := string(crypto.GenerateRandomBytes(rng.Intn(256)))\n\n\t\tencryptedCreds, err := EncryptCredentials(login, password)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\n\t\tloginDec, passwordDec, err := DecryptCredentials(encryptedCreds)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\n\t\tassert.Equal(t, loginDec, login)\n\t\tassert.Equal(t, passwordDec, password)\n\t}\n\n\tfor i := 0; i < 1024; i++ {\n\t\tlogin := utils.RandomString(rng.Intn(256))\n\t\tpassword := utils.RandomString(rng.Intn(256))\n\n\t\tencryptedCreds, err := EncryptCredentials(login, password)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\n\t\tloginDec, passwordDec, err := DecryptCredentials(encryptedCreds)\n\t\tif !assert.NoError(t, err) {\n\t\t\treturn\n\t\t}\n\n\t\tassert.Equal(t, loginDec, login)\n\t\tassert.Equal(t, passwordDec, password)\n\t}\n}\n\nfunc TestDecryptCredentialsRandom(t *testing.T) {\n\trng := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := 0; i < 1024; i++ {\n\t\tencrypted := base64.StdEncoding.EncodeToString(crypto.GenerateRandomBytes(rng.Intn(256)))\n\t\t_, _, err := DecryptCredentials(encrypted)\n\t\tassert.Error(t, err)\n\t}\n\tfor i := 0; i < 1024; i++ {\n\t\tencrypted := crypto.GenerateRandomBytes(rng.Intn(256))\n\t\tencryptedWithHeader := make([]byte, len(cipherHeader)+len(encrypted))\n\t\tcopy(encryptedWithHeader[0:], cipherHeader)\n\t\tcopy(encryptedWithHeader[len(cipherHeader):], encrypted)\n\t\t_, _, err := DecryptCredentials(base64.StdEncoding.EncodeToString(encryptedWithHeader))\n\t\tassert.Error(t, err)\n\t}\n}\n\nfunc TestRandomBitFlipsCredentials(t *testing.T) {\n\toriginal, err := EncryptCredentials(\"toto@titi.com\", \"X3hVYLJLRiUyCs\")\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\toriginalBuffer, err := base64.StdEncoding.DecodeString(original)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\n\tflipped := make([]byte, len(originalBuffer))\n\tcopy(flipped, originalBuffer)\n\tlogin, passwd, err := DecryptCredentials(base64.StdEncoding.EncodeToString(flipped))\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tassert.Equal(t, \"toto@titi.com\", login)\n\tassert.Equal(t, \"X3hVYLJLRiUyCs\", passwd)\n\n\trng := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := 0; i < 1000; i++ {\n\t\tcopy(flipped, originalBuffer)\n\t\tflipsLen := rng.Intn(30) + 1\n\t\tflipsSet := make([]int, 0, flipsLen)\n\t\tfor len(flipsSet) < flipsLen {\n\t\t\tflipValue := rng.Intn(len(originalBuffer) * 8)\n\t\t\tflipFound := false\n\t\t\tfor j := 0; j < len(flipsSet); j++ {\n\t\t\t\tif flipsSet[j] == flipValue {\n\t\t\t\t\tflipFound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !flipFound {\n\t\t\t\tflipsSet = append(flipsSet, flipValue)\n\t\t\t}\n\t\t}\n\t\tfor _, flipValue := range flipsSet {\n\t\t\tmask := byte(0x1 << uint(flipValue%8))\n\t\t\tflipped[flipValue\/8] ^= mask\n\t\t}\n\t\t_, _, err := DecryptCredentials(base64.StdEncoding.EncodeToString(flipped))\n\t\tif !assert.Error(t, err) {\n\t\t\tt.Fatalf(\"Failed with flips %v\", flipsSet)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc TestEncryptDecryptData(t *testing.T) {\n\tvar data interface{}\n\terr := json.Unmarshal([]byte(`{\"foo\":\"bar\",\"baz\":{\"quz\": \"quuz\"}}`), &data)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tencBuffer, err := EncryptCredentialsData(data)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tdecData, err := DecryptCredentialsData(encBuffer)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tassert.EqualValues(t, data, decData)\n}\n\nfunc TestRandomBitFlipsBuffer(t *testing.T) {\n\tplainBuffer := make([]byte, 256)\n\t_, err := io.ReadFull(cryptorand.Reader, plainBuffer)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\n\toriginal, err := EncryptBufferWithKey(config.GetVault().CredentialsEncryptorKey(), plainBuffer)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\n\tflipped := make([]byte, len(original))\n\tcopy(flipped, original)\n\ttestBuffer, err := DecryptBufferWithKey(config.GetVault().CredentialsDecryptorKey(), flipped)\n\tif !assert.NoError(t, err) {\n\t\treturn\n\t}\n\tassert.True(t, bytes.Equal(plainBuffer, testBuffer))\n\n\trng := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tfor i := 0; i < 1000; i++ {\n\t\tcopy(flipped, original)\n\t\tflipsLen := rng.Intn(30) + 1\n\t\tflipsSet := make([]int, 0, flipsLen)\n\t\tfor len(flipsSet) < flipsLen {\n\t\t\tflipValue := rng.Intn(len(original) * 8)\n\t\t\tflipFound := false\n\t\t\tfor j := 0; j < len(flipsSet); j++ {\n\t\t\t\tif flipsSet[j] == flipValue {\n\t\t\t\t\tflipFound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !flipFound {\n\t\t\t\tflipsSet = append(flipsSet, flipValue)\n\t\t\t}\n\t\t}\n\t\tfor _, flipValue := range flipsSet {\n\t\t\tmask := byte(0x1 << uint(flipValue%8))\n\t\t\tflipped[flipValue\/8] ^= mask\n\t\t}\n\t\t_, err := DecryptBufferWithKey(config.GetVault().CredentialsDecryptorKey(), flipped)\n\t\tif !assert.Error(t, err) {\n\t\t\tt.Fatalf(\"Failed with flips %v\", flipsSet)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc TestMain(m *testing.M) {\n\tconfig.UseTestFile()\n\tos.Exit(m.Run())\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/   Copyright 2009 Joubin Houshyar\n\/\/ \n\/\/   Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/   you may not use this file except in compliance with the License.\n\/\/   You may obtain a copy of the License at\n\/\/    \n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/    \n\/\/   Unless required by applicable law or agreed to in writing, software\n\/\/   distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/   See the License for the specific language governing permissions and\n\/\/   limitations under the License.\n\/\/\npackage redis\n\nimport (\n\t\"time\";\n)\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ synchronization utilities.\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ Timer\n\/\/\n\/\/ start a new time that will signal on the returned\n\/\/ channel when the specified ns (timeout in nanoseconds)\n\/\/ have passsed.  If ns < 0, function returns immediately\n\/\/ with nil.  Otherwise, the call can select on the channel\n\/\/ and will recieve an item after timeout.  If the timer\n\/\/ itself was interrupted during sleep, the value in channel\n\/\/ will be 0-time-elapsed.  Otherwise, for normal operation,\n\/\/ it will return time elapsed in ns (which hopefully is very\n\/\/ close to the specified ns.\n\/\/\n\nfunc NewTimer (ns int64) (signal <-chan int64) {\n    if ns <= 0 {\n        return nil\n    }\n    c := make(chan int64);\n    go func() {\n    \tt := time.Nanoseconds();\n    \te := time.Sleep(ns);\n    \tif e != nil { \n    \t\tt = 0 - (time.Nanoseconds() - t);\n    \t}\n    \tt = time.Nanoseconds() - t;\n    \tc<- t;\n    }();\n    return c;\n}\n<commit_msg>usage example in sync doc.<commit_after>\/\/   Copyright 2009 Joubin Houshyar\n\/\/ \n\/\/   Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/   you may not use this file except in compliance with the License.\n\/\/   You may obtain a copy of the License at\n\/\/    \n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/    \n\/\/   Unless required by applicable law or agreed to in writing, software\n\/\/   distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/   See the License for the specific language governing permissions and\n\/\/   limitations under the License.\n\/\/\npackage redis\n\nimport (\n\t\"time\";\n)\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ synchronization utilities.\n\/\/ ----------------------------------------------------------------------------\n\n\/\/ Timer\n\/\/\n\/\/ start a new timer that will signal on the returned\n\/\/ channel when the specified ns (timeout in nanoseconds)\n\/\/ have passsed.  If ns < 0, function returns immediately\n\/\/ with nil.  Otherwise, the caller can select on the channel\n\/\/ and will recieve an item after timeout.  If the timer\n\/\/ itself was interrupted during sleep, the value in channel\n\/\/ will be 0-time-elapsed.  Otherwise, for normal operation,\n\/\/ it will return time elapsed in ns (which hopefully is very\n\/\/ close to the specified ns.\n\/\/\n\nfunc NewTimer (ns int64) (signal <-chan int64) {\n    if ns <= 0 {\n        return nil\n    }\n    c := make(chan int64);\n    go func() {\n    \tt := time.Nanoseconds();\n    \te := time.Sleep(ns);\n    \tif e != nil { \n    \t\tt = 0 - (time.Nanoseconds() - t);\n    \t}\n    \tt = time.Nanoseconds() - t;\n    \tc<- t;\n    }();\n    return c;\n}\n<|endoftext|>"}
{"text":"<commit_before>package astutil\n\nimport (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/token\"\n\t\"reflect\"\n\t\"strings\"\n)\n\nfunc IsIdent(expr ast.Expr, ident string) bool {\n\tid, ok := expr.(*ast.Ident)\n\treturn ok && id.Name == ident\n}\n\n\/\/ isBlank returns whether id is the blank identifier \"_\".\n\/\/ If id == nil, the answer is false.\nfunc IsBlank(id ast.Expr) bool {\n\tident, _ := id.(*ast.Ident)\n\treturn ident != nil && ident.Name == \"_\"\n}\n\n\/\/ Deprecated: use code.IsIntegerLiteral instead.\nfunc IsIntLiteral(expr ast.Expr, literal string) bool {\n\tlit, ok := expr.(*ast.BasicLit)\n\treturn ok && lit.Kind == token.INT && lit.Value == literal\n}\n\n\/\/ Deprecated: use IsIntLiteral instead\nfunc IsZero(expr ast.Expr) bool {\n\treturn IsIntLiteral(expr, \"0\")\n}\n\nfunc Preamble(f *ast.File) string {\n\tcutoff := f.Package\n\tif f.Doc != nil {\n\t\tcutoff = f.Doc.Pos()\n\t}\n\tvar out []string\n\tfor _, cmt := range f.Comments {\n\t\tif cmt.Pos() >= cutoff {\n\t\t\tbreak\n\t\t}\n\t\tout = append(out, cmt.Text())\n\t}\n\treturn strings.Join(out, \"\\n\")\n}\n\nfunc GroupSpecs(fset *token.FileSet, specs []ast.Spec) [][]ast.Spec {\n\tif len(specs) == 0 {\n\t\treturn nil\n\t}\n\tgroups := make([][]ast.Spec, 1)\n\tgroups[0] = append(groups[0], specs[0])\n\n\tfor _, spec := range specs[1:] {\n\t\tg := groups[len(groups)-1]\n\t\tif fset.PositionFor(spec.Pos(), false).Line-1 !=\n\t\t\tfset.PositionFor(g[len(g)-1].End(), false).Line {\n\n\t\t\tgroups = append(groups, nil)\n\t\t}\n\n\t\tgroups[len(groups)-1] = append(groups[len(groups)-1], spec)\n\t}\n\n\treturn groups\n}\n\n\/\/ Unparen returns e with any enclosing parentheses stripped.\nfunc Unparen(e ast.Expr) ast.Expr {\n\tfor {\n\t\tp, ok := e.(*ast.ParenExpr)\n\t\tif !ok {\n\t\t\treturn e\n\t\t}\n\t\te = p.X\n\t}\n}\n\n\/\/ CopyExpr creates a deep copy of an expression.\n\/\/ It doesn't support copying FuncLits and returns ok == false when encountering one.\nfunc CopyExpr(node ast.Expr) (ast.Expr, bool) {\n\tswitch node := node.(type) {\n\tcase *ast.BasicLit:\n\t\tcp := *node\n\t\treturn &cp, true\n\tcase *ast.BinaryExpr:\n\t\tcp := *node\n\t\tvar ok1, ok2 bool\n\t\tcp.X, ok1 = CopyExpr(cp.X)\n\t\tcp.Y, ok2 = CopyExpr(cp.Y)\n\t\treturn &cp, ok1 && ok2\n\tcase *ast.CallExpr:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.Fun, ok = CopyExpr(cp.Fun)\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t\tcp.Args = make([]ast.Expr, len(node.Args))\n\t\tfor i, v := range node.Args {\n\t\t\tcp.Args[i], ok = CopyExpr(v)\n\t\t\tif !ok {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t}\n\t\treturn &cp, true\n\tcase *ast.CompositeLit:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.Type, ok = CopyExpr(cp.Type)\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t\tcp.Elts = make([]ast.Expr, len(node.Elts))\n\t\tfor i, v := range node.Elts {\n\t\t\tcp.Elts[i], ok = CopyExpr(v)\n\t\t\tif !ok {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t}\n\t\treturn &cp, true\n\tcase *ast.Ident:\n\t\tcp := *node\n\t\treturn &cp, true\n\tcase *ast.IndexExpr:\n\t\tvar ok1, ok2 bool\n\t\tcp := *node\n\t\tcp.X, ok1 = CopyExpr(cp.X)\n\t\tcp.Index, ok2 = CopyExpr(cp.Index)\n\t\treturn &cp, ok1 && ok2\n\tcase *ast.IndexListExpr:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.X, ok = CopyExpr(cp.X)\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t\tfor i, v := range node.Indices {\n\t\t\tcp.Indices[i], ok = CopyExpr(v)\n\t\t\tif !ok {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t}\n\t\treturn &cp, true\n\tcase *ast.KeyValueExpr:\n\t\tvar ok1, ok2 bool\n\t\tcp := *node\n\t\tcp.Key, ok1 = CopyExpr(cp.Key)\n\t\tcp.Value, ok2 = CopyExpr(cp.Value)\n\t\treturn &cp, ok1 && ok2\n\tcase *ast.ParenExpr:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.X, ok = CopyExpr(cp.X)\n\t\treturn &cp, ok\n\tcase *ast.SelectorExpr:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.X, ok = CopyExpr(cp.X)\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t\tsel, ok := CopyExpr(cp.Sel)\n\t\tif !ok {\n\t\t\t\/\/ this is impossible\n\t\t\treturn nil, false\n\t\t}\n\t\tcp.Sel = sel.(*ast.Ident)\n\t\treturn &cp, true\n\tcase *ast.SliceExpr:\n\t\tvar ok1, ok2, ok3, ok4 bool\n\t\tcp := *node\n\t\tcp.X, ok1 = CopyExpr(cp.X)\n\t\tcp.Low, ok2 = CopyExpr(cp.Low)\n\t\tcp.High, ok3 = CopyExpr(cp.High)\n\t\tcp.Max, ok4 = CopyExpr(cp.Max)\n\t\treturn &cp, ok1 && ok2 && ok3 && ok4\n\tcase *ast.StarExpr:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.X, ok = CopyExpr(cp.X)\n\t\treturn &cp, ok\n\tcase *ast.TypeAssertExpr:\n\t\tvar ok1, ok2 bool\n\t\tcp := *node\n\t\tcp.X, ok1 = CopyExpr(cp.X)\n\t\tcp.Type, ok2 = CopyExpr(cp.Type)\n\t\treturn &cp, ok1 && ok2\n\tcase *ast.UnaryExpr:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.X, ok = CopyExpr(cp.X)\n\t\treturn &cp, ok\n\tcase *ast.MapType:\n\t\tvar ok1, ok2 bool\n\t\tcp := *node\n\t\tcp.Key, ok1 = CopyExpr(cp.Key)\n\t\tcp.Value, ok2 = CopyExpr(cp.Value)\n\t\treturn &cp, ok1 && ok2\n\tcase *ast.ArrayType:\n\t\tvar ok1, ok2 bool\n\t\tcp := *node\n\t\tcp.Len, ok1 = CopyExpr(cp.Len)\n\t\tcp.Elt, ok2 = CopyExpr(cp.Elt)\n\t\treturn &cp, ok1 && ok2\n\tcase *ast.Ellipsis:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.Elt, ok = CopyExpr(cp.Elt)\n\t\treturn &cp, ok\n\tcase *ast.InterfaceType:\n\t\tcp := *node\n\t\treturn &cp, true\n\tcase *ast.StructType:\n\t\tcp := *node\n\t\treturn &cp, true\n\tcase *ast.FuncLit:\n\t\t\/\/ TODO(dh): implement copying of function literals.\n\t\treturn nil, false\n\tcase *ast.ChanType:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.Value, ok = CopyExpr(cp.Value)\n\t\treturn &cp, ok\n\tcase nil:\n\t\treturn nil, true\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unreachable: %T\", node))\n\t}\n}\n\nfunc Equal(a, b ast.Node) bool {\n\tif a == b {\n\t\treturn true\n\t}\n\tif a == nil || b == nil {\n\t\treturn false\n\t}\n\tif reflect.TypeOf(a) != reflect.TypeOf(b) {\n\t\treturn false\n\t}\n\n\tswitch a := a.(type) {\n\tcase *ast.BasicLit:\n\t\tb := b.(*ast.BasicLit)\n\t\treturn a.Kind == b.Kind && a.Value == b.Value\n\tcase *ast.BinaryExpr:\n\t\tb := b.(*ast.BinaryExpr)\n\t\treturn Equal(a.X, b.X) && a.Op == b.Op && Equal(a.Y, b.Y)\n\tcase *ast.CallExpr:\n\t\tb := b.(*ast.CallExpr)\n\t\tif len(a.Args) != len(b.Args) {\n\t\t\treturn false\n\t\t}\n\t\tfor i, arg := range a.Args {\n\t\t\tif !Equal(arg, b.Args[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn Equal(a.Fun, b.Fun) &&\n\t\t\t(a.Ellipsis == token.NoPos && b.Ellipsis == token.NoPos || a.Ellipsis != token.NoPos && b.Ellipsis != token.NoPos)\n\tcase *ast.CompositeLit:\n\t\tb := b.(*ast.CompositeLit)\n\t\tif len(a.Elts) != len(b.Elts) {\n\t\t\treturn false\n\t\t}\n\t\tfor i, elt := range b.Elts {\n\t\t\tif !Equal(elt, b.Elts[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn Equal(a.Type, b.Type) && a.Incomplete == b.Incomplete\n\tcase *ast.Ident:\n\t\tb := b.(*ast.Ident)\n\t\treturn a.Name == b.Name\n\tcase *ast.IndexExpr:\n\t\tb := b.(*ast.IndexExpr)\n\t\treturn Equal(a.X, b.X) && Equal(a.Index, b.Index)\n\tcase *ast.IndexListExpr:\n\t\tb := b.(*ast.IndexListExpr)\n\t\tif len(a.Indices) != len(b.Indices) {\n\t\t\treturn false\n\t\t}\n\t\tfor i, v := range a.Indices {\n\t\t\tif !Equal(v, b.Indices[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn Equal(a.X, b.X)\n\tcase *ast.KeyValueExpr:\n\t\tb := b.(*ast.KeyValueExpr)\n\t\treturn Equal(a.Key, b.Key) && Equal(a.Value, b.Value)\n\tcase *ast.ParenExpr:\n\t\tb := b.(*ast.ParenExpr)\n\t\treturn Equal(a.X, b.X)\n\tcase *ast.SelectorExpr:\n\t\tb := b.(*ast.SelectorExpr)\n\t\treturn Equal(a.X, b.X) && Equal(a.Sel, b.Sel)\n\tcase *ast.SliceExpr:\n\t\tb := b.(*ast.SliceExpr)\n\t\treturn Equal(a.X, b.X) && Equal(a.Low, b.Low) && Equal(a.High, b.High) && Equal(a.Max, b.Max) && a.Slice3 == b.Slice3\n\tcase *ast.StarExpr:\n\t\tb := b.(*ast.StarExpr)\n\t\treturn Equal(a.X, b.X)\n\tcase *ast.TypeAssertExpr:\n\t\tb := b.(*ast.TypeAssertExpr)\n\t\treturn Equal(a.X, b.X) && Equal(a.Type, b.Type)\n\tcase *ast.UnaryExpr:\n\t\tb := b.(*ast.UnaryExpr)\n\t\treturn a.Op == b.Op && Equal(a.X, b.X)\n\tcase *ast.MapType:\n\t\tb := b.(*ast.MapType)\n\t\treturn Equal(a.Key, b.Key) && Equal(a.Value, b.Value)\n\tcase *ast.ArrayType:\n\t\tb := b.(*ast.ArrayType)\n\t\treturn Equal(a.Len, b.Len) && Equal(a.Elt, b.Elt)\n\tcase *ast.Ellipsis:\n\t\tb := b.(*ast.Ellipsis)\n\t\treturn Equal(a.Elt, b.Elt)\n\tcase *ast.InterfaceType:\n\t\tb := b.(*ast.InterfaceType)\n\t\treturn a.Incomplete == b.Incomplete && Equal(a.Methods, b.Methods)\n\tcase *ast.StructType:\n\t\tb := b.(*ast.StructType)\n\t\treturn a.Incomplete == b.Incomplete && Equal(a.Fields, b.Fields)\n\tcase *ast.FuncLit:\n\t\t\/\/ TODO(dh): support function literals\n\t\treturn false\n\tcase *ast.ChanType:\n\t\tb := b.(*ast.ChanType)\n\t\treturn a.Dir == b.Dir && (a.Arrow == token.NoPos && b.Arrow == token.NoPos || a.Arrow != token.NoPos && b.Arrow != token.NoPos)\n\tcase *ast.FieldList:\n\t\tb := b.(*ast.FieldList)\n\t\tif len(a.List) != len(b.List) {\n\t\t\treturn false\n\t\t}\n\t\tfor i, fieldA := range a.List {\n\t\t\tif !Equal(fieldA, b.List[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\tcase *ast.Field:\n\t\tb := b.(*ast.Field)\n\t\tif len(a.Names) != len(b.Names) {\n\t\t\treturn false\n\t\t}\n\t\tfor j, name := range a.Names {\n\t\t\tif !Equal(name, b.Names[j]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tif !Equal(a.Type, b.Type) || !Equal(a.Tag, b.Tag) {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unreachable: %T\", a))\n\t}\n}\n<commit_msg>go\/ast\/astutil: restore compatibility with Go 1.17<commit_after>package astutil\n\nimport (\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/token\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"golang.org\/x\/exp\/typeparams\"\n)\n\nfunc IsIdent(expr ast.Expr, ident string) bool {\n\tid, ok := expr.(*ast.Ident)\n\treturn ok && id.Name == ident\n}\n\n\/\/ isBlank returns whether id is the blank identifier \"_\".\n\/\/ If id == nil, the answer is false.\nfunc IsBlank(id ast.Expr) bool {\n\tident, _ := id.(*ast.Ident)\n\treturn ident != nil && ident.Name == \"_\"\n}\n\n\/\/ Deprecated: use code.IsIntegerLiteral instead.\nfunc IsIntLiteral(expr ast.Expr, literal string) bool {\n\tlit, ok := expr.(*ast.BasicLit)\n\treturn ok && lit.Kind == token.INT && lit.Value == literal\n}\n\n\/\/ Deprecated: use IsIntLiteral instead\nfunc IsZero(expr ast.Expr) bool {\n\treturn IsIntLiteral(expr, \"0\")\n}\n\nfunc Preamble(f *ast.File) string {\n\tcutoff := f.Package\n\tif f.Doc != nil {\n\t\tcutoff = f.Doc.Pos()\n\t}\n\tvar out []string\n\tfor _, cmt := range f.Comments {\n\t\tif cmt.Pos() >= cutoff {\n\t\t\tbreak\n\t\t}\n\t\tout = append(out, cmt.Text())\n\t}\n\treturn strings.Join(out, \"\\n\")\n}\n\nfunc GroupSpecs(fset *token.FileSet, specs []ast.Spec) [][]ast.Spec {\n\tif len(specs) == 0 {\n\t\treturn nil\n\t}\n\tgroups := make([][]ast.Spec, 1)\n\tgroups[0] = append(groups[0], specs[0])\n\n\tfor _, spec := range specs[1:] {\n\t\tg := groups[len(groups)-1]\n\t\tif fset.PositionFor(spec.Pos(), false).Line-1 !=\n\t\t\tfset.PositionFor(g[len(g)-1].End(), false).Line {\n\n\t\t\tgroups = append(groups, nil)\n\t\t}\n\n\t\tgroups[len(groups)-1] = append(groups[len(groups)-1], spec)\n\t}\n\n\treturn groups\n}\n\n\/\/ Unparen returns e with any enclosing parentheses stripped.\nfunc Unparen(e ast.Expr) ast.Expr {\n\tfor {\n\t\tp, ok := e.(*ast.ParenExpr)\n\t\tif !ok {\n\t\t\treturn e\n\t\t}\n\t\te = p.X\n\t}\n}\n\n\/\/ CopyExpr creates a deep copy of an expression.\n\/\/ It doesn't support copying FuncLits and returns ok == false when encountering one.\nfunc CopyExpr(node ast.Expr) (ast.Expr, bool) {\n\tswitch node := node.(type) {\n\tcase *ast.BasicLit:\n\t\tcp := *node\n\t\treturn &cp, true\n\tcase *ast.BinaryExpr:\n\t\tcp := *node\n\t\tvar ok1, ok2 bool\n\t\tcp.X, ok1 = CopyExpr(cp.X)\n\t\tcp.Y, ok2 = CopyExpr(cp.Y)\n\t\treturn &cp, ok1 && ok2\n\tcase *ast.CallExpr:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.Fun, ok = CopyExpr(cp.Fun)\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t\tcp.Args = make([]ast.Expr, len(node.Args))\n\t\tfor i, v := range node.Args {\n\t\t\tcp.Args[i], ok = CopyExpr(v)\n\t\t\tif !ok {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t}\n\t\treturn &cp, true\n\tcase *ast.CompositeLit:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.Type, ok = CopyExpr(cp.Type)\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t\tcp.Elts = make([]ast.Expr, len(node.Elts))\n\t\tfor i, v := range node.Elts {\n\t\t\tcp.Elts[i], ok = CopyExpr(v)\n\t\t\tif !ok {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t}\n\t\treturn &cp, true\n\tcase *ast.Ident:\n\t\tcp := *node\n\t\treturn &cp, true\n\tcase *ast.IndexExpr:\n\t\tvar ok1, ok2 bool\n\t\tcp := *node\n\t\tcp.X, ok1 = CopyExpr(cp.X)\n\t\tcp.Index, ok2 = CopyExpr(cp.Index)\n\t\treturn &cp, ok1 && ok2\n\tcase *typeparams.IndexListExpr:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.X, ok = CopyExpr(cp.X)\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t\tfor i, v := range node.Indices {\n\t\t\tcp.Indices[i], ok = CopyExpr(v)\n\t\t\tif !ok {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t}\n\t\treturn &cp, true\n\tcase *ast.KeyValueExpr:\n\t\tvar ok1, ok2 bool\n\t\tcp := *node\n\t\tcp.Key, ok1 = CopyExpr(cp.Key)\n\t\tcp.Value, ok2 = CopyExpr(cp.Value)\n\t\treturn &cp, ok1 && ok2\n\tcase *ast.ParenExpr:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.X, ok = CopyExpr(cp.X)\n\t\treturn &cp, ok\n\tcase *ast.SelectorExpr:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.X, ok = CopyExpr(cp.X)\n\t\tif !ok {\n\t\t\treturn nil, false\n\t\t}\n\t\tsel, ok := CopyExpr(cp.Sel)\n\t\tif !ok {\n\t\t\t\/\/ this is impossible\n\t\t\treturn nil, false\n\t\t}\n\t\tcp.Sel = sel.(*ast.Ident)\n\t\treturn &cp, true\n\tcase *ast.SliceExpr:\n\t\tvar ok1, ok2, ok3, ok4 bool\n\t\tcp := *node\n\t\tcp.X, ok1 = CopyExpr(cp.X)\n\t\tcp.Low, ok2 = CopyExpr(cp.Low)\n\t\tcp.High, ok3 = CopyExpr(cp.High)\n\t\tcp.Max, ok4 = CopyExpr(cp.Max)\n\t\treturn &cp, ok1 && ok2 && ok3 && ok4\n\tcase *ast.StarExpr:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.X, ok = CopyExpr(cp.X)\n\t\treturn &cp, ok\n\tcase *ast.TypeAssertExpr:\n\t\tvar ok1, ok2 bool\n\t\tcp := *node\n\t\tcp.X, ok1 = CopyExpr(cp.X)\n\t\tcp.Type, ok2 = CopyExpr(cp.Type)\n\t\treturn &cp, ok1 && ok2\n\tcase *ast.UnaryExpr:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.X, ok = CopyExpr(cp.X)\n\t\treturn &cp, ok\n\tcase *ast.MapType:\n\t\tvar ok1, ok2 bool\n\t\tcp := *node\n\t\tcp.Key, ok1 = CopyExpr(cp.Key)\n\t\tcp.Value, ok2 = CopyExpr(cp.Value)\n\t\treturn &cp, ok1 && ok2\n\tcase *ast.ArrayType:\n\t\tvar ok1, ok2 bool\n\t\tcp := *node\n\t\tcp.Len, ok1 = CopyExpr(cp.Len)\n\t\tcp.Elt, ok2 = CopyExpr(cp.Elt)\n\t\treturn &cp, ok1 && ok2\n\tcase *ast.Ellipsis:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.Elt, ok = CopyExpr(cp.Elt)\n\t\treturn &cp, ok\n\tcase *ast.InterfaceType:\n\t\tcp := *node\n\t\treturn &cp, true\n\tcase *ast.StructType:\n\t\tcp := *node\n\t\treturn &cp, true\n\tcase *ast.FuncLit:\n\t\t\/\/ TODO(dh): implement copying of function literals.\n\t\treturn nil, false\n\tcase *ast.ChanType:\n\t\tvar ok bool\n\t\tcp := *node\n\t\tcp.Value, ok = CopyExpr(cp.Value)\n\t\treturn &cp, ok\n\tcase nil:\n\t\treturn nil, true\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unreachable: %T\", node))\n\t}\n}\n\nfunc Equal(a, b ast.Node) bool {\n\tif a == b {\n\t\treturn true\n\t}\n\tif a == nil || b == nil {\n\t\treturn false\n\t}\n\tif reflect.TypeOf(a) != reflect.TypeOf(b) {\n\t\treturn false\n\t}\n\n\tswitch a := a.(type) {\n\tcase *ast.BasicLit:\n\t\tb := b.(*ast.BasicLit)\n\t\treturn a.Kind == b.Kind && a.Value == b.Value\n\tcase *ast.BinaryExpr:\n\t\tb := b.(*ast.BinaryExpr)\n\t\treturn Equal(a.X, b.X) && a.Op == b.Op && Equal(a.Y, b.Y)\n\tcase *ast.CallExpr:\n\t\tb := b.(*ast.CallExpr)\n\t\tif len(a.Args) != len(b.Args) {\n\t\t\treturn false\n\t\t}\n\t\tfor i, arg := range a.Args {\n\t\t\tif !Equal(arg, b.Args[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn Equal(a.Fun, b.Fun) &&\n\t\t\t(a.Ellipsis == token.NoPos && b.Ellipsis == token.NoPos || a.Ellipsis != token.NoPos && b.Ellipsis != token.NoPos)\n\tcase *ast.CompositeLit:\n\t\tb := b.(*ast.CompositeLit)\n\t\tif len(a.Elts) != len(b.Elts) {\n\t\t\treturn false\n\t\t}\n\t\tfor i, elt := range b.Elts {\n\t\t\tif !Equal(elt, b.Elts[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn Equal(a.Type, b.Type) && a.Incomplete == b.Incomplete\n\tcase *ast.Ident:\n\t\tb := b.(*ast.Ident)\n\t\treturn a.Name == b.Name\n\tcase *ast.IndexExpr:\n\t\tb := b.(*ast.IndexExpr)\n\t\treturn Equal(a.X, b.X) && Equal(a.Index, b.Index)\n\tcase *typeparams.IndexListExpr:\n\t\tb := b.(*typeparams.IndexListExpr)\n\t\tif len(a.Indices) != len(b.Indices) {\n\t\t\treturn false\n\t\t}\n\t\tfor i, v := range a.Indices {\n\t\t\tif !Equal(v, b.Indices[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn Equal(a.X, b.X)\n\tcase *ast.KeyValueExpr:\n\t\tb := b.(*ast.KeyValueExpr)\n\t\treturn Equal(a.Key, b.Key) && Equal(a.Value, b.Value)\n\tcase *ast.ParenExpr:\n\t\tb := b.(*ast.ParenExpr)\n\t\treturn Equal(a.X, b.X)\n\tcase *ast.SelectorExpr:\n\t\tb := b.(*ast.SelectorExpr)\n\t\treturn Equal(a.X, b.X) && Equal(a.Sel, b.Sel)\n\tcase *ast.SliceExpr:\n\t\tb := b.(*ast.SliceExpr)\n\t\treturn Equal(a.X, b.X) && Equal(a.Low, b.Low) && Equal(a.High, b.High) && Equal(a.Max, b.Max) && a.Slice3 == b.Slice3\n\tcase *ast.StarExpr:\n\t\tb := b.(*ast.StarExpr)\n\t\treturn Equal(a.X, b.X)\n\tcase *ast.TypeAssertExpr:\n\t\tb := b.(*ast.TypeAssertExpr)\n\t\treturn Equal(a.X, b.X) && Equal(a.Type, b.Type)\n\tcase *ast.UnaryExpr:\n\t\tb := b.(*ast.UnaryExpr)\n\t\treturn a.Op == b.Op && Equal(a.X, b.X)\n\tcase *ast.MapType:\n\t\tb := b.(*ast.MapType)\n\t\treturn Equal(a.Key, b.Key) && Equal(a.Value, b.Value)\n\tcase *ast.ArrayType:\n\t\tb := b.(*ast.ArrayType)\n\t\treturn Equal(a.Len, b.Len) && Equal(a.Elt, b.Elt)\n\tcase *ast.Ellipsis:\n\t\tb := b.(*ast.Ellipsis)\n\t\treturn Equal(a.Elt, b.Elt)\n\tcase *ast.InterfaceType:\n\t\tb := b.(*ast.InterfaceType)\n\t\treturn a.Incomplete == b.Incomplete && Equal(a.Methods, b.Methods)\n\tcase *ast.StructType:\n\t\tb := b.(*ast.StructType)\n\t\treturn a.Incomplete == b.Incomplete && Equal(a.Fields, b.Fields)\n\tcase *ast.FuncLit:\n\t\t\/\/ TODO(dh): support function literals\n\t\treturn false\n\tcase *ast.ChanType:\n\t\tb := b.(*ast.ChanType)\n\t\treturn a.Dir == b.Dir && (a.Arrow == token.NoPos && b.Arrow == token.NoPos || a.Arrow != token.NoPos && b.Arrow != token.NoPos)\n\tcase *ast.FieldList:\n\t\tb := b.(*ast.FieldList)\n\t\tif len(a.List) != len(b.List) {\n\t\t\treturn false\n\t\t}\n\t\tfor i, fieldA := range a.List {\n\t\t\tif !Equal(fieldA, b.List[i]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\tcase *ast.Field:\n\t\tb := b.(*ast.Field)\n\t\tif len(a.Names) != len(b.Names) {\n\t\t\treturn false\n\t\t}\n\t\tfor j, name := range a.Names {\n\t\t\tif !Equal(name, b.Names[j]) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tif !Equal(a.Type, b.Type) || !Equal(a.Tag, b.Tag) {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"unreachable: %T\", a))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package dnsimple\/webhook provides the support for reading and parsing the events\n\/\/ sent from DNSimple via webhook.\npackage webhook\n\nimport (\n\t\"encoding\/json\"\n)\n\n\/\/ Actor represents the entity that triggered the event. It can be either an user,\n\/\/ a DNSimple support representative or the DNSimple system.\ntype Actor struct {\n\tID     int    `json:\"id\"`\n\tEntity string `json:\"entity\"`\n\tPretty string `json:\"pretty\"`\n}\n\n\/\/ Event is an event generated in the DNSimple application.\ntype Event interface {\n\tEventName() string\n\tEventHeader() *Event_Header\n\tPayload() []byte\n\tparse([]byte) error\n}\n\ntype Event_Header struct {\n\tAPIVersion string `json:\"api_version\"`\n\tRequestID  string `json:\"request_identifier\"`\n\tActor      *Actor `json:\"actor\"`\n\tName       string `json:\"name\"`\n\tpayload    []byte\n}\n\ntype eventName struct {\n\tName string `json:\"name\"`\n}\n\n\/\/ Event returns the event name as defined in the name field of the payload.\nfunc (e *Event_Header) EventHeader() *Event_Header {\n\treturn e\n}\n\n\/\/ EventName returns the event name as defined in the name field of the payload.\nfunc (e *Event_Header) EventName() string {\n\treturn e.Name\n}\n\n\/\/ Payload returns the binary payload the event was deserialized from.\nfunc (e *Event_Header) Payload() []byte {\n\treturn e.payload\n}\n\nfunc (e *Event_Header) parse(payload []byte) error {\n\te.payload = payload\n\treturn unmashalEvent(payload, e)\n}\n\n\/\/ Parse takes a payload and attempts to deserialize the payload into an event type\n\/\/ that matches the event action in the payload. If no direct match is found, then a DefaultEvent is returned.\n\/\/\n\/\/ Parse returns type is an Event interface. Therefore, you must perform typecasting\n\/\/ to access any event-specific field.\nfunc Parse(payload []byte) (Event, error) {\n\taction, err := ParseName(payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn switchEvent(action, payload)\n}\n\nfunc ParseName(data []byte) (string, error) {\n\teventName := &eventName{}\n\terr := json.Unmarshal(data, eventName)\n\treturn eventName.Name, err\n}\n\nfunc unmashalEvent(data []byte, v interface{}) error {\n\treturn json.Unmarshal(data, v)\n}\n<commit_msg>Fixed warning: package comment should be of the form \"Package webhook ...\"<commit_after>\/\/ Package webhook provides the support for reading and parsing the events\n\/\/ sent from DNSimple via webhook.\npackage webhook\n\nimport (\n\t\"encoding\/json\"\n)\n\n\/\/ Actor represents the entity that triggered the event. It can be either an user,\n\/\/ a DNSimple support representative or the DNSimple system.\ntype Actor struct {\n\tID     int    `json:\"id\"`\n\tEntity string `json:\"entity\"`\n\tPretty string `json:\"pretty\"`\n}\n\n\/\/ Event is an event generated in the DNSimple application.\ntype Event interface {\n\tEventName() string\n\tEventHeader() *Event_Header\n\tPayload() []byte\n\tparse([]byte) error\n}\n\ntype Event_Header struct {\n\tAPIVersion string `json:\"api_version\"`\n\tRequestID  string `json:\"request_identifier\"`\n\tActor      *Actor `json:\"actor\"`\n\tName       string `json:\"name\"`\n\tpayload    []byte\n}\n\ntype eventName struct {\n\tName string `json:\"name\"`\n}\n\n\/\/ Event returns the event name as defined in the name field of the payload.\nfunc (e *Event_Header) EventHeader() *Event_Header {\n\treturn e\n}\n\n\/\/ EventName returns the event name as defined in the name field of the payload.\nfunc (e *Event_Header) EventName() string {\n\treturn e.Name\n}\n\n\/\/ Payload returns the binary payload the event was deserialized from.\nfunc (e *Event_Header) Payload() []byte {\n\treturn e.payload\n}\n\nfunc (e *Event_Header) parse(payload []byte) error {\n\te.payload = payload\n\treturn unmashalEvent(payload, e)\n}\n\n\/\/ Parse takes a payload and attempts to deserialize the payload into an event type\n\/\/ that matches the event action in the payload. If no direct match is found, then a DefaultEvent is returned.\n\/\/\n\/\/ Parse returns type is an Event interface. Therefore, you must perform typecasting\n\/\/ to access any event-specific field.\nfunc Parse(payload []byte) (Event, error) {\n\taction, err := ParseName(payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn switchEvent(action, payload)\n}\n\nfunc ParseName(data []byte) (string, error) {\n\teventName := &eventName{}\n\terr := json.Unmarshal(data, eventName)\n\treturn eventName.Name, err\n}\n\nfunc unmashalEvent(data []byte, v interface{}) error {\n\treturn json.Unmarshal(data, v)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This is the main package for the `packer` application.\npackage main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/mitchellh\/packer\/packer\"\n\t\"github.com\/mitchellh\/packer\/packer\/plugin\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n)\n\nfunc main() {\n\tif os.Getenv(\"PACKER_LOG\") == \"\" {\n\t\t\/\/ If we don't have logging explicitly enabled, then disable it\n\t\tlog.SetOutput(ioutil.Discard)\n\t} else {\n\t\t\/\/ Logging is enabled, make sure it goes to stderr\n\t\tlog.SetOutput(os.Stderr)\n\t}\n\n\t\/\/ If there is no explicit number of Go threads to use, then set it\n\tif os.Getenv(\"GOMAXPROCS\") == \"\" {\n\t\truntime.GOMAXPROCS(runtime.NumCPU())\n\t}\n\n\tconfig, err := loadConfig()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error loading configuration: \\n\\n%s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlog.Printf(\"Packer config: %+v\", config)\n\n\tdefer plugin.CleanupClients()\n\n\tvar cache packer.Cache\n\tif cacheDir := os.Getenv(\"PACKER_CACHE_DIR\"); cacheDir != \"\" {\n\t\tif err := os.MkdirAll(cacheDir, 0755); err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"Error preparing cache directory: \\n\\n%s\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tlog.Printf(\"Setting cache directory: %s\", cacheDir)\n\t\tcache = &packer.FileCache{CacheDir: cacheDir}\n\t}\n\n\tenvConfig := packer.DefaultEnvironmentConfig()\n\tenvConfig.Cache = cache\n\tenvConfig.Commands = config.CommandNames()\n\tenvConfig.Components.Builder = config.LoadBuilder\n\tenvConfig.Components.Command = config.LoadCommand\n\tenvConfig.Components.Hook = config.LoadHook\n\tenvConfig.Components.PostProcessor = config.LoadPostProcessor\n\tenvConfig.Components.Provisioner = config.LoadProvisioner\n\n\tenv, err := packer.NewEnvironment(envConfig)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Packer initialization error: \\n\\n%s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tsetupSignalHandlers(env)\n\n\texitCode, err := env.Cli(os.Args[1:])\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error executing CLI: %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tplugin.CleanupClients()\n\tos.Exit(exitCode)\n}\n\nfunc loadConfig() (*config, error) {\n\tvar config config\n\tif err := decodeConfig(bytes.NewBufferString(defaultConfig), &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmustExist := true\n\tconfigFilePath := os.Getenv(\"PACKER_CONFIG\")\n\tif configFilePath == \"\" {\n\t\tvar err error\n\t\tconfigFilePath, err = configFile()\n\t\tmustExist = false\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error detecing default config file path: %s\", err)\n\t\t}\n\t}\n\n\tif configFilePath == \"\" {\n\t\treturn &config, nil\n\t}\n\n\tlog.Printf(\"Attempting to open config file: %s\", configFilePath)\n\tf, err := os.Open(configFilePath)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif mustExist {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlog.Println(\"File doesn't exist, but doesn't need to. Ignoring.\")\n\t\treturn &config, nil\n\t}\n\tdefer f.Close()\n\n\tif err := decodeConfig(f, &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}\n<commit_msg>Default cache to \"packer_cache\" in CWD<commit_after>\/\/ This is the main package for the `packer` application.\npackage main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/mitchellh\/packer\/packer\"\n\t\"github.com\/mitchellh\/packer\/packer\/plugin\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n)\n\nfunc main() {\n\tif os.Getenv(\"PACKER_LOG\") == \"\" {\n\t\t\/\/ If we don't have logging explicitly enabled, then disable it\n\t\tlog.SetOutput(ioutil.Discard)\n\t} else {\n\t\t\/\/ Logging is enabled, make sure it goes to stderr\n\t\tlog.SetOutput(os.Stderr)\n\t}\n\n\t\/\/ If there is no explicit number of Go threads to use, then set it\n\tif os.Getenv(\"GOMAXPROCS\") == \"\" {\n\t\truntime.GOMAXPROCS(runtime.NumCPU())\n\t}\n\n\tconfig, err := loadConfig()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error loading configuration: \\n\\n%s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlog.Printf(\"Packer config: %+v\", config)\n\n\tdefer plugin.CleanupClients()\n\n\tcacheDir := os.Getenv(\"PACKER_CACHE_DIR\")\n\tif cacheDir == \"\" {\n\t\tcacheDir = \"packer_cache\"\n\t}\n\n\tif err := os.MkdirAll(cacheDir, 0755); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error preparing cache directory: \\n\\n%s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tlog.Printf(\"Setting cache directory: %s\", cacheDir)\n\tcache := &packer.FileCache{CacheDir: cacheDir}\n\n\tenvConfig := packer.DefaultEnvironmentConfig()\n\tenvConfig.Cache = cache\n\tenvConfig.Commands = config.CommandNames()\n\tenvConfig.Components.Builder = config.LoadBuilder\n\tenvConfig.Components.Command = config.LoadCommand\n\tenvConfig.Components.Hook = config.LoadHook\n\tenvConfig.Components.PostProcessor = config.LoadPostProcessor\n\tenvConfig.Components.Provisioner = config.LoadProvisioner\n\n\tenv, err := packer.NewEnvironment(envConfig)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Packer initialization error: \\n\\n%s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tsetupSignalHandlers(env)\n\n\texitCode, err := env.Cli(os.Args[1:])\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Error executing CLI: %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tplugin.CleanupClients()\n\tos.Exit(exitCode)\n}\n\nfunc loadConfig() (*config, error) {\n\tvar config config\n\tif err := decodeConfig(bytes.NewBufferString(defaultConfig), &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmustExist := true\n\tconfigFilePath := os.Getenv(\"PACKER_CONFIG\")\n\tif configFilePath == \"\" {\n\t\tvar err error\n\t\tconfigFilePath, err = configFile()\n\t\tmustExist = false\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error detecing default config file path: %s\", err)\n\t\t}\n\t}\n\n\tif configFilePath == \"\" {\n\t\treturn &config, nil\n\t}\n\n\tlog.Printf(\"Attempting to open config file: %s\", configFilePath)\n\tf, err := os.Open(configFilePath)\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif mustExist {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tlog.Println(\"File doesn't exist, but doesn't need to. Ignoring.\")\n\t\treturn &config, nil\n\t}\n\tdefer f.Close()\n\n\tif err := decodeConfig(f, &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package gocd\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\n\/\/ APIClientRequest helper struct to reduce amount of code.\ntype APIClientRequest struct {\n\tMethod       string\n\tPath         string\n\tAPIVersion   string\n\tRequestBody  interface{}\n\tResponseType string\n\tResponseBody interface{}\n\tHeaders      map[string]string\n}\n\n\/\/ Handles any call to HEAD by returning whether or not we got a 2xx code.\nfunc (c *Client) genericHeadAction(ctx context.Context, path string, apiversion string) (bool, *APIResponse, error) {\n\t_, resp, err := c.httpAction(ctx, &APIClientRequest{\n\t\tMethod:       \"HEAD\",\n\t\tPath:         path,\n\t\tAPIVersion:   apiversion,\n\t\tResponseType: responseTypeJSON,\n\t})\n\n\texists := resp.HTTP.StatusCode >= 300 || resp.HTTP.StatusCode < 200\n\n\treturn exists, resp, err\n\n}\n\nfunc (c *Client) patchAction(ctx context.Context, r *APIClientRequest) (interface{}, *APIResponse, error) {\n\tr.Method = \"PATCH\"\n\treturn c.httpAction(ctx, r)\n}\n\nfunc (c *Client) getAction(ctx context.Context, r *APIClientRequest) (interface{}, *APIResponse, error) {\n\tr.Method = \"GET\"\n\treturn c.httpAction(ctx, r)\n}\n\nfunc (c *Client) postAction(ctx context.Context, r *APIClientRequest) (interface{}, *APIResponse, error) {\n\tr.Method = \"POST\"\n\treturn c.httpAction(ctx, r)\n}\n\nfunc (c *Client) putAction(ctx context.Context, r *APIClientRequest) (interface{}, *APIResponse, error) {\n\tr.Method = \"PUT\"\n\treturn c.httpAction(ctx, r)\n}\n\n\/\/ Returns a message from the DELETE action on the provided HTTP resource.\nfunc (c *Client) deleteAction(ctx context.Context, path string, apiversion string) (string, *APIResponse, error) {\n\ta := StringResponse{}\n\t_, resp, err := c.httpAction(ctx, &APIClientRequest{\n\t\tMethod:       \"DELETE\",\n\t\tPath:         path,\n\t\tAPIVersion:   apiversion,\n\t\tResponseType: responseTypeJSON,\n\t\tResponseBody: &a,\n\t})\n\n\treturn a.Message, resp, err\n}\n\nfunc (c *Client) httpAction(ctx context.Context, r *APIClientRequest) (interface{}, *APIResponse, error) {\n\n\tlog.Debugf(\"HTTP Request\")\n\tlog.Debugf(\"%s %s\", r.Method, r.Path)\n\n\tif r.ResponseType == \"\" {\n\t\tr.ResponseType = responseTypeJSON\n\t}\n\n\tvar isVersioned bool\n\tvar ver Versioned\n\tif ver, isVersioned = (r.RequestBody).(Versioned); isVersioned {\n\t\tif r.Headers == nil {\n\t\t\tr.Headers = map[string]string{}\n\t\t}\n\t\tr.Headers[\"If-Match\"] = fmt.Sprintf(\"\\\"%s\\\"\", ver.GetVersion())\n\t}\n\n\t\/\/ Build the request\n\tvar reqBody interface{}\n\tif r.RequestBody != nil {\n\t\treqBody = r.RequestBody\n\t} else {\n\t\treqBody = nil\n\t}\n\n\treq, err := c.NewRequest(r.Method, r.Path, reqBody, r.APIVersion)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\n\tif len(r.Headers) > 0 {\n\t\tfor key, value := range r.Headers {\n\t\t\treq.HTTP.Header.Set(key, value)\n\t\t}\n\t}\n\n\tfor header, values := range req.HTTP.Header {\n\t\tfor _, value := range values {\n\t\t\tlog.Debugf(\"%s: %s\", header, value)\n\t\t}\n\t}\n\tif r.RequestBody != nil {\n\t\tlog.Debug()\n\t\tlog.Debug(r.RequestBody)\n\t\tlog.Debug()\n\t\tlog.Debug()\n\t}\n\n\tresp, err := c.Do(ctx, req, r.ResponseBody, r.ResponseType)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn r.ResponseBody, resp, err\n\t}\n\n\tif ver, isVersioned = (r.ResponseBody).(Versioned); isVersioned {\n\t\tparseVersions(resp.HTTP, ver)\n\t}\n\n\tif r.ResponseType == responseTypeJSON {\n\t\tlog.Debug()\n\t\tlog.Debug(\"Response\")\n\t\tlog.Debugf(\"%s %s\", resp.HTTP.Proto, resp.HTTP.Status)\n\t\tfor header, values := range resp.HTTP.Header {\n\t\t\tfor _, value := range values {\n\t\t\t\tlog.Debugf(\"%s: %s\", header, value)\n\t\t\t}\n\t\t}\n\t\tlog.Debug()\n\t\tb, _ := json.Marshal(r.ResponseBody)\n\t\tlog.Debugf(\"%s\", b)\n\t}\n\n\treturn r.ResponseBody, resp, err\n}\n\nfunc parseVersions(response *http.Response, versioned Versioned) {\n\tetag := response.Header.Get(\"Etag\")\n\tversioned.SetVersion(\n\t\tstrings.Replace(etag, \"\\\"\", \"\", -1),\n\t)\n}\n<commit_msg>Removed extra debug statements<commit_after>package gocd\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\n\/\/ APIClientRequest helper struct to reduce amount of code.\ntype APIClientRequest struct {\n\tMethod       string\n\tPath         string\n\tAPIVersion   string\n\tRequestBody  interface{}\n\tResponseType string\n\tResponseBody interface{}\n\tHeaders      map[string]string\n}\n\n\/\/ Handles any call to HEAD by returning whether or not we got a 2xx code.\nfunc (c *Client) genericHeadAction(ctx context.Context, path string, apiversion string) (bool, *APIResponse, error) {\n\t_, resp, err := c.httpAction(ctx, &APIClientRequest{\n\t\tMethod:       \"HEAD\",\n\t\tPath:         path,\n\t\tAPIVersion:   apiversion,\n\t\tResponseType: responseTypeJSON,\n\t})\n\n\texists := resp.HTTP.StatusCode >= 300 || resp.HTTP.StatusCode < 200\n\n\treturn exists, resp, err\n\n}\n\nfunc (c *Client) patchAction(ctx context.Context, r *APIClientRequest) (interface{}, *APIResponse, error) {\n\tr.Method = \"PATCH\"\n\treturn c.httpAction(ctx, r)\n}\n\nfunc (c *Client) getAction(ctx context.Context, r *APIClientRequest) (interface{}, *APIResponse, error) {\n\tr.Method = \"GET\"\n\treturn c.httpAction(ctx, r)\n}\n\nfunc (c *Client) postAction(ctx context.Context, r *APIClientRequest) (interface{}, *APIResponse, error) {\n\tr.Method = \"POST\"\n\treturn c.httpAction(ctx, r)\n}\n\nfunc (c *Client) putAction(ctx context.Context, r *APIClientRequest) (interface{}, *APIResponse, error) {\n\tr.Method = \"PUT\"\n\treturn c.httpAction(ctx, r)\n}\n\n\/\/ Returns a message from the DELETE action on the provided HTTP resource.\nfunc (c *Client) deleteAction(ctx context.Context, path string, apiversion string) (string, *APIResponse, error) {\n\ta := StringResponse{}\n\t_, resp, err := c.httpAction(ctx, &APIClientRequest{\n\t\tMethod:       \"DELETE\",\n\t\tPath:         path,\n\t\tAPIVersion:   apiversion,\n\t\tResponseType: responseTypeJSON,\n\t\tResponseBody: &a,\n\t})\n\n\treturn a.Message, resp, err\n}\n\nfunc (c *Client) httpAction(ctx context.Context, r *APIClientRequest) (interface{}, *APIResponse, error) {\n\n\tlog.Debugf(\"HTTP Request\")\n\tlog.Debugf(\"%s %s\", r.Method, r.Path)\n\n\tif r.ResponseType == \"\" {\n\t\tr.ResponseType = responseTypeJSON\n\t}\n\n\tif ver, isVersioned := (r.RequestBody).(Versioned); isVersioned {\n\t\tif r.Headers == nil {\n\t\t\tr.Headers = map[string]string{}\n\t\t}\n\t\tr.Headers[\"If-Match\"] = fmt.Sprintf(\"\\\"%s\\\"\", ver.GetVersion())\n\t}\n\n\t\/\/ Build the request\n\treq, err := c.NewRequest(r.Method, r.Path, r.RequestBody, r.APIVersion)\n\tif err != nil {\n\t\treturn false, nil, err\n\t}\n\n\tif len(r.Headers) > 0 {\n\t\tfor key, value := range r.Headers {\n\t\t\treq.HTTP.Header.Set(key, value)\n\t\t}\n\t}\n\n\tfor header, values := range req.HTTP.Header {\n\t\tfor _, value := range values {\n\t\t\tlog.Debugf(\"%s: %s\", header, value)\n\t\t}\n\t}\n\tif r.RequestBody != nil {\n\t\tlog.Debugf(\"\\n%s\\n\\n\", r.RequestBody)\n\t}\n\n\tresp, err := c.Do(ctx, req, r.ResponseBody, r.ResponseType)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn r.ResponseBody, resp, err\n\t}\n\n\tif ver, isVersioned := (r.ResponseBody).(Versioned); isVersioned {\n\t\tparseVersions(resp.HTTP, ver)\n\t}\n\n\tif r.ResponseType == responseTypeJSON {\n\t\tlog.Debugf(\"\\nResponse\\n%s %s\\n\", resp.HTTP.Proto, resp.HTTP.Status)\n\t\tfor header, values := range resp.HTTP.Header {\n\t\t\tfor _, value := range values {\n\t\t\t\tlog.Debugf(\"%s: %s\", header, value)\n\t\t\t}\n\t\t}\n\t\tb, _ := json.Marshal(r.ResponseBody)\n\t\tlog.Debugf(\"\\n%s\", b)\n\t}\n\n\treturn r.ResponseBody, resp, err\n}\n\nfunc parseVersions(response *http.Response, versioned Versioned) {\n\tetag := response.Header.Get(\"Etag\")\n\tversioned.SetVersion(\n\t\tstrings.Replace(etag, \"\\\"\", \"\", -1),\n\t)\n}\n<|endoftext|>"}
{"text":"<commit_before>package gofetcher\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/cocaine\/cocaine-framework-go\/cocaine\"\n\t\"github.com\/ugorji\/go\/codec\"\n)\n\nconst (\n\tDefaultTimeout         = 5000\n\tDefaultFollowRedirects = true\n\tKeepAliveTimeout       = 30\n)\n\n\/\/ took from httputil\/reverseproxy.go\n\/\/ Hop-by-hop headers. These are removed when sent to the backend.\n\/\/ http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec13.html\nvar hopHeaders = []string{\n\t\"Connection\",\n\t\"Keep-Alive\",\n\t\"Proxy-Authenticate\",\n\t\"Proxy-Authorization\",\n\t\"Te\", \/\/ canonicalized version of \"TE\"\n\t\"Trailers\",\n\t\"Transfer-Encoding\",\n\t\"Upgrade\",\n}\n\ntype WarnError struct {\n\terr error\n}\n\nfunc (s *WarnError) Error() string { return s.err.Error() }\n\nfunc NewWarn(err error) *WarnError {\n\treturn &WarnError{err: err}\n}\n\ntype Gofetcher struct {\n\tLogger    *cocaine.Logger\n\tTransport http.RoundTripper\n\n\tUserAgent string\n}\n\ntype Cookies map[string]string\n\ntype Request struct {\n\tMethod          string\n\tURL             string\n\tBody            io.Reader\n\tTimeout         int64\n\tCookies         Cookies\n\tHeaders         http.Header\n\tFollowRedirects bool\n}\n\ntype responseAndError struct {\n\tres *http.Response\n\terr error\n}\n\ntype Response struct {\n\thttpResponse *http.Response\n\tbody         []byte\n\theader       http.Header\n\truntime      time.Duration\n}\n\nfunc NewGofetcher() *Gofetcher {\n\tlogger, err := cocaine.NewLogger()\n\tif err != nil {\n\t\tfmt.Printf(\"Could not initialize logger due to error: %v\", err)\n\t\treturn nil\n\t}\n\ttransport := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout:   30 * time.Second,\n\t\t\tKeepAlive: KeepAliveTimeout * time.Second,\n\t\t\tDualStack: true,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t}\n\tgofetcher := Gofetcher{logger, transport, \"\"}\n\treturn &gofetcher\n}\n\nfunc (gofetcher *Gofetcher) SetUserAgent(userAgent string) {\n\tgofetcher.UserAgent = userAgent\n}\n\nfunc noRedirect(_ *http.Request, via []*http.Request) error {\n\tif len(via) > 0 {\n\t\treturn errors.New(\"stopped after first redirect\")\n\t}\n\treturn nil\n}\n\nfunc (gofetcher *Gofetcher) PrepareRequest(request *Request) (*http.Request, *http.Client, error) {\n\tvar (\n\t\terr            error\n\t\thttpRequest    *http.Request\n\t\trequestTimeout time.Duration = time.Duration(request.Timeout) * time.Millisecond\n\t)\n\n\thttpClient := &http.Client{\n\t\tTransport: gofetcher.Transport,\n\t\tTimeout:   requestTimeout,\n\t}\n\tif request.FollowRedirects == false {\n\t\thttpClient.CheckRedirect = noRedirect\n\t}\n\n\thttpRequest, err = http.NewRequest(request.Method, request.URL, request.Body)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfor name, value := range request.Cookies {\n\t\thttpRequest.AddCookie(&http.Cookie{Name: name, Value: value})\n\t}\n\thttpRequest.Header = request.Headers\n\n\t\/\/ Remove hop-by-hop headers to the backend.  Especially\n\t\/\/ important is \"Connection\" because we want a persistent\n\t\/\/ connection, regardless of what the client sent to us.  This\n\t\/\/ is modifying the same underlying map from req (shallow\n\t\/\/ copied above) so we only copy it if necessary.\n\tfor _, h := range hopHeaders {\n\t\thttpRequest.Header.Del(h)\n\t}\n\thttpRequest.Header.Add(\"Connection\", \"keep-alive\")\n\thttpRequest.Header.Add(\"Keep-Alive\", fmt.Sprintf(\"%d\", KeepAliveTimeout))\n\n\tif gofetcher.UserAgent != \"\" && len(httpRequest.Header[\"User-Agent\"]) == 0 {\n\t\thttpRequest.Header.Set(\"User-Agent\", gofetcher.UserAgent)\n\t}\n\n\treturn httpRequest, httpClient, nil\n}\n\nfunc (gofetcher *Gofetcher) ExecuteRequest(req *http.Request, client *http.Client, attempt int) (*http.Response, error) {\n\tvar (\n\t\thttpResponse *http.Response\n\t\terr          error\n\t)\n\n\tgofetcher.Logger.Infof(\"Requested url: %s, method: %s, timeout: %d, headers: %v, attempt: %d\",\n\t\treq.URL.String(), req.Method, client.Timeout, req.Header, attempt)\n\n\tresultChan := make(chan responseAndError)\n\tstarted := time.Now()\n\tgo func() {\n\t\tres, err := client.Do(req)\n\t\tresultChan <- responseAndError{res, err}\n\t}()\n\t\/\/ http connection stay active after timeout exceeded in go <1.3, cause we can't close it using current client api.\n\t\/\/ Read more about timeouts: https:\/\/code.google.com\/p\/go\/issues\/detail?id=3362\n\t\/\/\n\tselect {\n\tcase result := <-resultChan:\n\t\thttpResponse, err = result.res, result.err\n\tcase <-time.After(client.Timeout):\n\t\terr = errors.New(fmt.Sprintf(\"Request timeout[%s] exceeded\", client.Timeout.String()))\n\t\tgo func() {\n\t\t\t\/\/ close httpResponse when it ready\n\t\t\tresult := <-resultChan\n\t\t\tif result.res != nil {\n\t\t\t\tresult.res.Body.Close()\n\t\t\t}\n\t\t}()\n\t}\n\tif err != nil {\n\t\t\/\/ special case for redirect failure (returns both response and error)\n\t\t\/\/ read more https:\/\/code.google.com\/p\/go\/issues\/detail?id=3795\n\t\tif httpResponse == nil {\n\t\t\tif urlError, ok := err.(*url.Error); ok {\n\t\t\t\t\/\/ golang bug: golang.org\/issue\/3514\n\t\t\t\tif urlError.Err == io.EOF {\n\t\t\t\t\tgofetcher.Logger.Infof(\"Got EOF error while loading %s, attempt(%d)\", req.URL.String(), attempt)\n\t\t\t\t\tif attempt == 1 {\n\t\t\t\t\t\treturn gofetcher.ExecuteRequest(req, client, attempt+1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, NewWarn(err)\n\t\t}\n\t}\n\n\tfor _, h := range hopHeaders {\n\t\thttpResponse.Header.Del(h)\n\t}\n\n\truntime := time.Since(started)\n\tgofetcher.Logger.Info(fmt.Sprintf(\"Response code: %d, url: %s, runtime: %v\",\n\t\thttpResponse.StatusCode, req.URL.String(), runtime))\n\treturn httpResponse, nil\n\n}\n\n\/\/ Normal methods\n\nfunc parseHeaders(rawHeaders map[string]interface{}) http.Header {\n\theaders := make(http.Header)\n\tfor name, values := range rawHeaders {\n\t\tfor _, value := range values.([]interface{}) {\n\t\t\theaders.Add(name, string(value.([]uint8))) \/\/ to transform in canonical form\n\t\t}\n\t}\n\treturn headers\n}\n\nfunc parseCookies(rawCookie map[string]interface{}) Cookies {\n\tcookies := Cookies{}\n\tfor key, value := range rawCookie {\n\t\tcookies[key] = string(value.([]uint8))\n\t}\n\treturn cookies\n}\n\nfunc parseTimeout(rawTimeout interface{}) (timeout int64) {\n\t\/\/ is it possible to got timeout in int64 instead of uint64?\n\tswitch rawTimeout.(type) {\n\tcase uint64:\n\t\ttimeout = int64(rawTimeout.(uint64))\n\tcase int64:\n\t\ttimeout = rawTimeout.(int64)\n\t}\n\treturn timeout\n}\n\nfunc (gofetcher *Gofetcher) ParseRequest(method string, requestBody []byte) (request *Request) {\n\tvar (\n\t\tmh              codec.MsgpackHandle\n\t\th                     = &mh\n\t\ttimeout         int64 = DefaultTimeout\n\t\tcookies         Cookies\n\t\theaders              = make(http.Header)\n\t\tfollowRedirects bool = DefaultFollowRedirects\n\t\tbody            *bytes.Buffer\n\t)\n\tmh.MapType = reflect.TypeOf(map[string]interface{}(nil))\n\tvar res []interface{}\n\tcodec.NewDecoderBytes(requestBody, h).Decode(&res)\n\turl := string(res[0].([]uint8))\n\tswitch {\n\tcase method == \"GET\" || method == \"HEAD\" || method == \"DELETE\":\n\t\tif len(res) > 1 {\n\t\t\ttimeout = parseTimeout(res[1])\n\t\t}\n\t\tif len(res) > 2 {\n\t\t\tcookies = parseCookies(res[2].(map[string]interface{}))\n\t\t}\n\t\tif len(res) > 3 {\n\t\t\theaders = parseHeaders(res[3].(map[string]interface{}))\n\t\t}\n\t\tif len(res) > 4 {\n\t\t\tfollowRedirects = res[4].(bool)\n\t\t}\n\tcase method == \"POST\" || method == \"PUT\" || method == \"PATCH\":\n\t\tif len(res) > 1 {\n\t\t\tbody = bytes.NewBuffer(res[1].([]byte))\n\t\t}\n\t\tif len(res) > 2 {\n\t\t\ttimeout = parseTimeout(res[2])\n\t\t}\n\t\tif len(res) > 3 {\n\t\t\tcookies = parseCookies(res[3].(map[string]interface{}))\n\t\t}\n\t\tif len(res) > 4 {\n\t\t\theaders = parseHeaders(res[4].(map[string]interface{}))\n\t\t}\n\t\tif len(res) > 5 {\n\t\t\tfollowRedirects = res[5].(bool)\n\t\t}\n\t}\n\n\trequest = &Request{Method: method, URL: url, Timeout: timeout,\n\t\tFollowRedirects: followRedirects,\n\t\tCookies:         cookies, Headers: headers}\n\tif body != nil {\n\t\trequest.Body = body\n\t}\n\treturn request\n}\n\nfunc (gofetcher *Gofetcher) WriteError(response *cocaine.Response, request *Request, err error) {\n\tif _, casted := err.(*WarnError); casted {\n\t\tgofetcher.Logger.Warnf(\"Error occured: %v, while downloading %s\",\n\t\t\terr.Error(), request.URL)\n\t} else {\n\t\tgofetcher.Logger.Errf(\"Error occured: %v, while downloading %s\",\n\t\t\terr.Error(), request.URL)\n\t}\n\tresponse.Write([]interface{}{false, err.Error(), 0, http.Header{}})\n}\n\nfunc (gofetcher *Gofetcher) WriteResponse(response *cocaine.Response, request *Request, resp *http.Response, body []byte) {\n\tresponse.Write([]interface{}{true, body, resp.StatusCode, resp.Header})\n}\n\nfunc (gofetcher *Gofetcher) handler(method string, request *cocaine.Request, response *cocaine.Response) {\n\tdefer response.Close()\n\n\trequestBody := <-request.Read()\n\thttpRequest := gofetcher.ParseRequest(method, requestBody)\n\n\treq, client, err := gofetcher.PrepareRequest(httpRequest)\n\tif err != nil {\n\t\tgofetcher.WriteError(response, httpRequest, err)\n\t\treturn\n\t}\n\n\tresp, err := gofetcher.ExecuteRequest(req, client, 1)\n\tif err != nil {\n\t\tgofetcher.WriteError(response, httpRequest, err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tgofetcher.WriteError(response, httpRequest, err)\n\t\treturn\n\t}\n\n\tgofetcher.WriteResponse(response, httpRequest, resp, body)\n}\n\nfunc (gofetcher *Gofetcher) GetHandler(method string) func(request *cocaine.Request, response *cocaine.Response) {\n\treturn func(request *cocaine.Request, response *cocaine.Response) {\n\t\tgofetcher.handler(method, request, response)\n\t}\n}\n\n\/\/ Http methods\n\nfunc (gofetcher *Gofetcher) HttpProxy(res http.ResponseWriter, req *http.Request) {\n\tvar (\n\t\ttimeout int64 = DefaultTimeout\n\t\tresp    *http.Response\n\t)\n\turl := req.FormValue(\"url\")\n\ttimeoutArg := req.FormValue(\"timeout\")\n\tif timeoutArg != \"\" {\n\t\ttout, _ := strconv.Atoi(timeoutArg)\n\t\ttimeout = int64(tout)\n\t}\n\thttpRequest := &Request{Method: req.Method, URL: url, Timeout: timeout,\n\t\tFollowRedirects: DefaultFollowRedirects, Headers: req.Header, Body: req.Body}\n\tprepReq, prepClient, err := gofetcher.PrepareRequest(httpRequest)\n\tif err == nil {\n\t\tresp, err = gofetcher.ExecuteRequest(prepReq, prepClient, 1)\n\t}\n\n\tif err != nil {\n\t\tres.Header().Set(\"Content-Type\", \"text\/html\")\n\t\tres.WriteHeader(500)\n\t\tres.Write([]byte(err.Error()))\n\t\tif _, casted := err.(*WarnError); casted {\n\t\t\tgofetcher.Logger.Warnf(\"Gofetcher error: %v\", err)\n\t\t} else {\n\t\t\tgofetcher.Logger.Errf(\"Gofetcher error: %v\", err)\n\t\t}\n\n\t} else {\n\t\tfor key, values := range resp.Header {\n\t\t\tfor _, value := range values {\n\t\t\t\tres.Header().Add(key, value)\n\t\t\t}\n\t\t}\n\t\tres.WriteHeader(200)\n\t\tif _, err := io.Copy(res, resp.Body); err != nil {\n\t\t\tgofetcher.Logger.Errf(\"Error: %v\", err)\n\t\t}\n\t}\n}\n\nfunc (gofetcher *Gofetcher) HttpEcho(res http.ResponseWriter, req *http.Request) {\n\tgofetcher.Logger.Info(\"Http echo handler requested\")\n\ttext := req.FormValue(\"text\")\n\tres.Header().Set(\"Content-Type\", \"text\/html\")\n\tres.WriteHeader(200)\n\tres.Write([]byte(text))\n}\n<commit_msg>not deliberately failed redirects are errors now<commit_after>package gofetcher\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/cocaine\/cocaine-framework-go\/cocaine\"\n\t\"github.com\/ugorji\/go\/codec\"\n)\n\nconst (\n\tDefaultTimeout         = 5000\n\tDefaultFollowRedirects = true\n\tKeepAliveTimeout       = 30\n)\n\n\/\/ took from httputil\/reverseproxy.go\n\/\/ Hop-by-hop headers. These are removed when sent to the backend.\n\/\/ http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec13.html\nvar hopHeaders = []string{\n\t\"Connection\",\n\t\"Keep-Alive\",\n\t\"Proxy-Authenticate\",\n\t\"Proxy-Authorization\",\n\t\"Te\", \/\/ canonicalized version of \"TE\"\n\t\"Trailers\",\n\t\"Transfer-Encoding\",\n\t\"Upgrade\",\n}\n\ntype WarnError struct {\n\terr error\n}\n\nfunc (s *WarnError) Error() string { return s.err.Error() }\n\nfunc NewWarn(err error) *WarnError {\n\treturn &WarnError{err: err}\n}\n\ntype Gofetcher struct {\n\tLogger    *cocaine.Logger\n\tTransport http.RoundTripper\n\n\tUserAgent string\n}\n\ntype Cookies map[string]string\n\ntype Request struct {\n\tMethod          string\n\tURL             string\n\tBody            io.Reader\n\tTimeout         int64\n\tCookies         Cookies\n\tHeaders         http.Header\n\tFollowRedirects bool\n}\n\ntype responseAndError struct {\n\tres *http.Response\n\terr error\n}\n\ntype Response struct {\n\thttpResponse *http.Response\n\tbody         []byte\n\theader       http.Header\n\truntime      time.Duration\n}\n\nfunc NewGofetcher() *Gofetcher {\n\tlogger, err := cocaine.NewLogger()\n\tif err != nil {\n\t\tfmt.Printf(\"Could not initialize logger due to error: %v\", err)\n\t\treturn nil\n\t}\n\ttransport := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout:   30 * time.Second,\n\t\t\tKeepAlive: KeepAliveTimeout * time.Second,\n\t\t\tDualStack: true,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t}\n\tgofetcher := Gofetcher{logger, transport, \"\"}\n\treturn &gofetcher\n}\n\nfunc (gofetcher *Gofetcher) SetUserAgent(userAgent string) {\n\tgofetcher.UserAgent = userAgent\n}\n\ntype noRedirectError struct{}\n\nfunc (nr noRedirectError) Error() string {\n\treturn \"stopped after first redirect\"\n}\n\nfunc noRedirect(_ *http.Request, via []*http.Request) error {\n\tif len(via) > 0 {\n\t\treturn noRedirectError{}\n\t}\n\treturn nil\n}\n\nfunc (gofetcher *Gofetcher) PrepareRequest(request *Request) (*http.Request, *http.Client, error) {\n\tvar (\n\t\terr            error\n\t\thttpRequest    *http.Request\n\t\trequestTimeout time.Duration = time.Duration(request.Timeout) * time.Millisecond\n\t)\n\n\thttpClient := &http.Client{\n\t\tTransport: gofetcher.Transport,\n\t\tTimeout:   requestTimeout,\n\t}\n\tif request.FollowRedirects == false {\n\t\thttpClient.CheckRedirect = noRedirect\n\t}\n\n\thttpRequest, err = http.NewRequest(request.Method, request.URL, request.Body)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfor name, value := range request.Cookies {\n\t\thttpRequest.AddCookie(&http.Cookie{Name: name, Value: value})\n\t}\n\thttpRequest.Header = request.Headers\n\n\t\/\/ Remove hop-by-hop headers to the backend.  Especially\n\t\/\/ important is \"Connection\" because we want a persistent\n\t\/\/ connection, regardless of what the client sent to us.  This\n\t\/\/ is modifying the same underlying map from req (shallow\n\t\/\/ copied above) so we only copy it if necessary.\n\tfor _, h := range hopHeaders {\n\t\thttpRequest.Header.Del(h)\n\t}\n\thttpRequest.Header.Add(\"Connection\", \"keep-alive\")\n\thttpRequest.Header.Add(\"Keep-Alive\", fmt.Sprintf(\"%d\", KeepAliveTimeout))\n\n\tif gofetcher.UserAgent != \"\" && len(httpRequest.Header[\"User-Agent\"]) == 0 {\n\t\thttpRequest.Header.Set(\"User-Agent\", gofetcher.UserAgent)\n\t}\n\n\treturn httpRequest, httpClient, nil\n}\n\nfunc (gofetcher *Gofetcher) ExecuteRequest(req *http.Request, client *http.Client, attempt int) (*http.Response, error) {\n\tvar (\n\t\thttpResponse *http.Response\n\t\terr          error\n\t)\n\n\tgofetcher.Logger.Infof(\"Requested url: %s, method: %s, timeout: %d, headers: %v, attempt: %d\",\n\t\treq.URL.String(), req.Method, client.Timeout, req.Header, attempt)\n\n\tresultChan := make(chan responseAndError)\n\tstarted := time.Now()\n\tgo func() {\n\t\tres, err := client.Do(req)\n\t\tresultChan <- responseAndError{res, err}\n\t}()\n\t\/\/ http connection stay active after timeout exceeded in go <1.3, cause we can't close it using current client api.\n\t\/\/ Read more about timeouts: https:\/\/code.google.com\/p\/go\/issues\/detail?id=3362\n\t\/\/\n\tselect {\n\tcase result := <-resultChan:\n\t\thttpResponse, err = result.res, result.err\n\tcase <-time.After(client.Timeout):\n\t\terr = errors.New(fmt.Sprintf(\"Request timeout[%s] exceeded\", client.Timeout.String()))\n\t\tgo func() {\n\t\t\t\/\/ close httpResponse when it ready\n\t\t\tresult := <-resultChan\n\t\t\tif result.res != nil {\n\t\t\t\tresult.res.Body.Close()\n\t\t\t}\n\t\t}()\n\t}\n\tif err != nil {\n\t\t\/\/ special case for redirect failure (returns both response and error)\n\t\t\/\/ read more https:\/\/code.google.com\/p\/go\/issues\/detail?id=3795\n\t\tif httpResponse == nil {\n\t\t\tif urlError, ok := err.(*url.Error); ok {\n\t\t\t\t\/\/ golang bug: golang.org\/issue\/3514\n\t\t\t\tif urlError.Err == io.EOF {\n\t\t\t\t\tgofetcher.Logger.Infof(\"Got EOF error while loading %s, attempt(%d)\", req.URL.String(), attempt)\n\t\t\t\t\tif attempt == 1 {\n\t\t\t\t\t\treturn gofetcher.ExecuteRequest(req, client, attempt+1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil, NewWarn(err)\n\t\t}\n\n\t\tif _, ok := err.(noRedirectError); !ok {\n\t\t\t\/\/ http client failed to redirect and this is not because we requested it to\n\t\t\t\/\/ usually it means that server sent response with redirect status code but omitted \"Location\" header\n\t\t\treturn nil, NewWarn(err)\n\t\t}\n\t}\n\n\tfor _, h := range hopHeaders {\n\t\thttpResponse.Header.Del(h)\n\t}\n\n\truntime := time.Since(started)\n\tgofetcher.Logger.Info(fmt.Sprintf(\"Response code: %d, url: %s, runtime: %v\",\n\t\thttpResponse.StatusCode, req.URL.String(), runtime))\n\treturn httpResponse, nil\n\n}\n\n\/\/ Normal methods\n\nfunc parseHeaders(rawHeaders map[string]interface{}) http.Header {\n\theaders := make(http.Header)\n\tfor name, values := range rawHeaders {\n\t\tfor _, value := range values.([]interface{}) {\n\t\t\theaders.Add(name, string(value.([]uint8))) \/\/ to transform in canonical form\n\t\t}\n\t}\n\treturn headers\n}\n\nfunc parseCookies(rawCookie map[string]interface{}) Cookies {\n\tcookies := Cookies{}\n\tfor key, value := range rawCookie {\n\t\tcookies[key] = string(value.([]uint8))\n\t}\n\treturn cookies\n}\n\nfunc parseTimeout(rawTimeout interface{}) (timeout int64) {\n\t\/\/ is it possible to got timeout in int64 instead of uint64?\n\tswitch rawTimeout.(type) {\n\tcase uint64:\n\t\ttimeout = int64(rawTimeout.(uint64))\n\tcase int64:\n\t\ttimeout = rawTimeout.(int64)\n\t}\n\treturn timeout\n}\n\nfunc (gofetcher *Gofetcher) ParseRequest(method string, requestBody []byte) (request *Request) {\n\tvar (\n\t\tmh              codec.MsgpackHandle\n\t\th                     = &mh\n\t\ttimeout         int64 = DefaultTimeout\n\t\tcookies         Cookies\n\t\theaders              = make(http.Header)\n\t\tfollowRedirects bool = DefaultFollowRedirects\n\t\tbody            *bytes.Buffer\n\t)\n\tmh.MapType = reflect.TypeOf(map[string]interface{}(nil))\n\tvar res []interface{}\n\tcodec.NewDecoderBytes(requestBody, h).Decode(&res)\n\turl := string(res[0].([]uint8))\n\tswitch {\n\tcase method == \"GET\" || method == \"HEAD\" || method == \"DELETE\":\n\t\tif len(res) > 1 {\n\t\t\ttimeout = parseTimeout(res[1])\n\t\t}\n\t\tif len(res) > 2 {\n\t\t\tcookies = parseCookies(res[2].(map[string]interface{}))\n\t\t}\n\t\tif len(res) > 3 {\n\t\t\theaders = parseHeaders(res[3].(map[string]interface{}))\n\t\t}\n\t\tif len(res) > 4 {\n\t\t\tfollowRedirects = res[4].(bool)\n\t\t}\n\tcase method == \"POST\" || method == \"PUT\" || method == \"PATCH\":\n\t\tif len(res) > 1 {\n\t\t\tbody = bytes.NewBuffer(res[1].([]byte))\n\t\t}\n\t\tif len(res) > 2 {\n\t\t\ttimeout = parseTimeout(res[2])\n\t\t}\n\t\tif len(res) > 3 {\n\t\t\tcookies = parseCookies(res[3].(map[string]interface{}))\n\t\t}\n\t\tif len(res) > 4 {\n\t\t\theaders = parseHeaders(res[4].(map[string]interface{}))\n\t\t}\n\t\tif len(res) > 5 {\n\t\t\tfollowRedirects = res[5].(bool)\n\t\t}\n\t}\n\n\trequest = &Request{Method: method, URL: url, Timeout: timeout,\n\t\tFollowRedirects: followRedirects,\n\t\tCookies:         cookies, Headers: headers}\n\tif body != nil {\n\t\trequest.Body = body\n\t}\n\treturn request\n}\n\nfunc (gofetcher *Gofetcher) WriteError(response *cocaine.Response, request *Request, err error) {\n\tif _, casted := err.(*WarnError); casted {\n\t\tgofetcher.Logger.Warnf(\"Error occured: %v, while downloading %s\",\n\t\t\terr.Error(), request.URL)\n\t} else {\n\t\tgofetcher.Logger.Errf(\"Error occured: %v, while downloading %s\",\n\t\t\terr.Error(), request.URL)\n\t}\n\tresponse.Write([]interface{}{false, err.Error(), 0, http.Header{}})\n}\n\nfunc (gofetcher *Gofetcher) WriteResponse(response *cocaine.Response, request *Request, resp *http.Response, body []byte) {\n\tresponse.Write([]interface{}{true, body, resp.StatusCode, resp.Header})\n}\n\nfunc (gofetcher *Gofetcher) handler(method string, request *cocaine.Request, response *cocaine.Response) {\n\tdefer response.Close()\n\n\trequestBody := <-request.Read()\n\thttpRequest := gofetcher.ParseRequest(method, requestBody)\n\n\treq, client, err := gofetcher.PrepareRequest(httpRequest)\n\tif err != nil {\n\t\tgofetcher.WriteError(response, httpRequest, err)\n\t\treturn\n\t}\n\n\tresp, err := gofetcher.ExecuteRequest(req, client, 1)\n\tif err != nil {\n\t\tgofetcher.WriteError(response, httpRequest, err)\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\tgofetcher.WriteError(response, httpRequest, err)\n\t\treturn\n\t}\n\n\tgofetcher.WriteResponse(response, httpRequest, resp, body)\n}\n\nfunc (gofetcher *Gofetcher) GetHandler(method string) func(request *cocaine.Request, response *cocaine.Response) {\n\treturn func(request *cocaine.Request, response *cocaine.Response) {\n\t\tgofetcher.handler(method, request, response)\n\t}\n}\n\n\/\/ Http methods\n\nfunc (gofetcher *Gofetcher) HttpProxy(res http.ResponseWriter, req *http.Request) {\n\tvar (\n\t\ttimeout int64 = DefaultTimeout\n\t\tresp    *http.Response\n\t)\n\turl := req.FormValue(\"url\")\n\ttimeoutArg := req.FormValue(\"timeout\")\n\tif timeoutArg != \"\" {\n\t\ttout, _ := strconv.Atoi(timeoutArg)\n\t\ttimeout = int64(tout)\n\t}\n\thttpRequest := &Request{Method: req.Method, URL: url, Timeout: timeout,\n\t\tFollowRedirects: DefaultFollowRedirects, Headers: req.Header, Body: req.Body}\n\tprepReq, prepClient, err := gofetcher.PrepareRequest(httpRequest)\n\tif err == nil {\n\t\tresp, err = gofetcher.ExecuteRequest(prepReq, prepClient, 1)\n\t}\n\n\tif err != nil {\n\t\tres.Header().Set(\"Content-Type\", \"text\/html\")\n\t\tres.WriteHeader(500)\n\t\tres.Write([]byte(err.Error()))\n\t\tif _, casted := err.(*WarnError); casted {\n\t\t\tgofetcher.Logger.Warnf(\"Gofetcher error: %v\", err)\n\t\t} else {\n\t\t\tgofetcher.Logger.Errf(\"Gofetcher error: %v\", err)\n\t\t}\n\n\t} else {\n\t\tfor key, values := range resp.Header {\n\t\t\tfor _, value := range values {\n\t\t\t\tres.Header().Add(key, value)\n\t\t\t}\n\t\t}\n\t\tres.WriteHeader(200)\n\t\tif _, err := io.Copy(res, resp.Body); err != nil {\n\t\t\tgofetcher.Logger.Errf(\"Error: %v\", err)\n\t\t}\n\t}\n}\n\nfunc (gofetcher *Gofetcher) HttpEcho(res http.ResponseWriter, req *http.Request) {\n\tgofetcher.Logger.Info(\"Http echo handler requested\")\n\ttext := req.FormValue(\"text\")\n\tres.Header().Set(\"Content-Type\", \"text\/html\")\n\tres.WriteHeader(200)\n\tres.Write([]byte(text))\n}\n<|endoftext|>"}
{"text":"<commit_before>package stats\n\nimport(\n\t\"github.com\/trendrr\/goshire\/dynmap\"\n\t\"github.com\/trendrr\/goshire\/timeamount\"\n\t\"time\"\n\t\"log\"\n\n)\n\n\/\/ A simple stats collector\n\ntype Stats struct {\n\titemChan chan statsItem\n\tgetChan chan getRequest\n\tPersister StatsPersister\n\titems map[timeamount.TimeAmount]*StatsSave\n\n}\n\ntype StatsPersister interface {\n\tPersist(t timeamount.TimeAmount, val dynmap.DynMap )\n\n}\n\ntype statsItemType int\nconst (\n\tSET statsItemType = 0\n\tINC                = 1\n)\n\ntype getRequest struct {\n\tresultChan chan map[timeamount.TimeAmount]*StatsSave\n}\n\ntype statsItem struct {\n\tKey string\n\tVal int64\n\ttyp statsItemType\n}\n\ntype StatsSave struct {\n\tEpoch int64\n\tTimeAmount timeamount.TimeAmount\n\tValues *dynmap.DynMap\n}\n\n\/\/ Creates a new Stats tracker. caller must still envoke the Start function\n\/\/ timeamounts should be in the form \"{num} {timeframe}\" \n\/\/ example \n\/\/ NewStats(\"1 minute\", \"30 minute\", \"1 day\")\nfunc New(timeamounts ...string) (*Stats, error) {\n\ts := &Stats{\n\t\titemChan : make(chan statsItem, 500),\n\t\titems : make(map[timeamount.TimeAmount]*StatsSave),\n\t}\n\tfor _,ta := range(timeamounts) {\n\t\tt, err := timeamount.Parse(ta)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.items[t] = &StatsSave{\n\t\t\t\tEpoch : t.ToTrendrrEpoch(time.Now()),\n\t\t\t\tTimeAmount : t,\n\t\t\t\tValues : dynmap.New(),\n\t\t}\n\t}\n\treturn s, nil\n}\n\n\/\/ Sets the given key with the given value.\nfunc (this *Stats) Set(key string, val int64) {\n\tselect {\n\tcase this.itemChan <- statsItem{Key : key, Val : int64(val), typ : SET} :\n\tdefault :\n\t\tlog.Printf( \"Could not Inc Key: %s Val: %d\", key, val)\n\t}\n}\n\nfunc (this *Stats) Inc(key string, val int) {\n\tselect {\n\tcase this.itemChan <- statsItem{Key : key, Val : int64(val), typ : INC} :\n\tdefault :\n\t\tlog.Printf( \"Could not Inc Key: %s Val: %d\", key, val)\n\t}\n}\n\nfunc (this *Stats) Get() map[timeamount.TimeAmount]*StatsSave {\n\tgreq := getRequest{\n\t\tresultChan : make(chan map[timeamount.TimeAmount]*StatsSave),\n\t}\n\tthis.getChan <- greq\n\treturn <- greq.resultChan\n}\n\n\/\/starts the event loop.\n\/\/this is necessary for it to do anything!\nfunc (this *Stats) Start() {\n\tgo this.eventLoop()\n}\n\nfunc (this *Stats) Close() error {\n\t\/\/TODO: cleanly exit\n\treturn nil\n}\n\nfunc (this *Stats) eventLoop() {\n\t\/\/TODO: add kill chan\n\tfor {\n\t\tselect {\n\t\tcase item := <- this.itemChan:\n\t\t\tthis.add(item)\n\t\tcase greq := <- this.getChan:\n\t\t\tgreq.resultChan <- this.get()\n\n\t\t}\n\t}\n}\n\n\/\/ Gets a clone of the current state\nfunc (this *Stats) get() map[timeamount.TimeAmount]*StatsSave{\n\tmp := make(map[timeamount.TimeAmount]*StatsSave)\n\tfor ta,ss := range(this.items) {\n\t\tres := &StatsSave{\n\t\t\tValues : ss.Values.Clone(),\n\t\t\tTimeAmount: ss.TimeAmount,\n\t\t\tEpoch : ss.Epoch,\n\t\t}\n\t\tmp[ta] = res\n\t}\n\treturn mp\n}\n\nfunc (this *Stats) add(item statsItem) {\n\tfor ta, sts := range(this.items) {\n\t\tepoch := ta.ToTrendrrEpoch(time.Now())\n\n\t\tif epoch != sts.Epoch {\n\t\t\t\/\/ need to persist this.. \n\t\t\tthis.persist(sts)\n\t\t\tsts = &StatsSave{\n\t\t\t\tEpoch : epoch,\n\t\t\t\tTimeAmount : ta,\n\t\t\t\tValues : dynmap.New(),\n\t\t\t}\n\t\t\tthis.items[ta] = sts\n\t\t}\n\t\t\n\t\tif item.typ == INC {\n\t\t\tval := sts.Values.MustInt64(item.Key, int64(0))\n\t\t\tsts.Values.PutWithDot(item.Key, int64(val+item.Val))\t\n\t\t} else if item.typ == SET {\n\t\t\tsts.Values.PutWithDot(item.Key, int64(item.Val))\n\t\t}\n\n\t\t\n\t}\n}\n\nfunc (this *Stats) persist(item *StatsSave) {\n\t\/\/Do something \n\tjson, _ := item.Values.MarshalJSON()\n\n\tlog.Printf(\"TODO PERSISTING %s %s\", item.TimeAmount.String(), string(json))\n}<commit_msg>more on stats<commit_after>package stats\n\nimport(\n\t\"github.com\/trendrr\/goshire\/dynmap\"\n\t\"github.com\/trendrr\/goshire\/timeamount\"\n\t\"time\"\n\t\"log\"\n\n)\n\n\/\/ A simple stats collector\n\ntype Stats struct {\n\titemChan chan statsItem\n\tgetChan chan getRequest\n\tPersister StatsPersister\n\titems map[timeamount.TimeAmount]*StatsSave\n\n}\n\ntype StatsPersister interface {\n\tPersist(t timeamount.TimeAmount, val dynmap.DynMap )\n\n}\n\ntype statsItemType int\nconst (\n\tSET statsItemType = 0\n\tINC                = 1\n)\n\ntype getRequest struct {\n\tresultChan chan map[timeamount.TimeAmount]*StatsSave\n}\n\ntype statsItem struct {\n\tKey string\n\tVal int64\n\ttyp statsItemType\n}\n\ntype StatsSave struct {\n\tEpoch int64\n\tTimeAmount timeamount.TimeAmount\n\tValues *dynmap.DynMap\n}\n\n\/\/ Creates a new Stats tracker. caller must still envoke the Start function\n\/\/ timeamounts should be in the form \"{num} {timeframe}\" \n\/\/ example \n\/\/ NewStats(\"1 minute\", \"30 minute\", \"1 day\")\nfunc New(timeamounts ...string) (*Stats, error) {\n\ts := &Stats{\n\t\titemChan : make(chan statsItem, 5),\n\t\tgetChan : make(chan getRequest, 10),\n\t\titems : make(map[timeamount.TimeAmount]*StatsSave),\n\t}\n\tfor _,ta := range(timeamounts) {\n\t\tt, err := timeamount.Parse(ta)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.items[t] = &StatsSave{\n\t\t\t\tEpoch : t.ToTrendrrEpoch(time.Now()),\n\t\t\t\tTimeAmount : t,\n\t\t\t\tValues : dynmap.New(),\n\t\t}\n\t}\n\treturn s, nil\n}\n\n\/\/ Sets the given key with the given value.\nfunc (this *Stats) Set(key string, val int64) {\n\tselect {\n\tcase this.itemChan <- statsItem{Key : key, Val : int64(val), typ : SET} :\n\tdefault :\n\t\tlog.Printf( \"Could not Inc Key: %s Val: %d\", key, val)\n\t}\n}\n\nfunc (this *Stats) Inc(key string, val int) {\n\tselect {\n\tcase this.itemChan <- statsItem{Key : key, Val : int64(val), typ : INC} :\n\tdefault :\n\t\tlog.Printf( \"Could not Inc Key: %s Val: %d\", key, val)\n\t}\n\n}\n\nfunc (this *Stats) Get() map[timeamount.TimeAmount]*StatsSave {\n\tgreq := getRequest{\n\t\tresultChan : make(chan map[timeamount.TimeAmount]*StatsSave),\n\t}\n\tthis.getChan <- greq\n\treturn <- greq.resultChan\n}\n\n\/\/starts the event loop.\n\/\/this is necessary for it to do anything!\nfunc (this *Stats) Start() {\n\tgo this.eventLoop()\n}\n\nfunc (this *Stats) Close() error {\n\t\/\/TODO: cleanly exit\n\treturn nil\n}\n\nfunc (this *Stats) eventLoop() {\n\t\/\/TODO: add kill chan\n\tfor {\n\t\tselect {\n\t\tcase item := <- this.itemChan:\n\t\t\tthis.add(item)\n\t\tcase greq := <- this.getChan:\n\t\t\tgreq.resultChan <- this.get()\n\n\t\t}\n\t}\n}\n\n\/\/ Gets a clone of the current state\nfunc (this *Stats) get() map[timeamount.TimeAmount]*StatsSave{\n\tmp := make(map[timeamount.TimeAmount]*StatsSave)\n\tfor ta,ss := range(this.items) {\n\t\tres := &StatsSave{\n\t\t\tValues : ss.Values.Clone(),\n\t\t\tTimeAmount: ss.TimeAmount,\n\t\t\tEpoch : ss.Epoch,\n\t\t}\n\t\tmp[ta] = res\n\t}\n\treturn mp\n}\n\nfunc (this *Stats) add(item statsItem) {\n\tfor ta, sts := range(this.items) {\n\t\tepoch := ta.ToTrendrrEpoch(time.Now())\n\n\t\tif epoch != sts.Epoch {\n\t\t\t\/\/ need to persist this.. \n\t\t\tthis.persist(sts)\n\t\t\tsts = &StatsSave{\n\t\t\t\tEpoch : epoch,\n\t\t\t\tTimeAmount : ta,\n\t\t\t\tValues : dynmap.New(),\n\t\t\t}\n\t\t\tthis.items[ta] = sts\n\t\t}\n\t\t\n\t\tif item.typ == INC {\n\t\t\tval := sts.Values.MustInt64(item.Key, int64(0))\n\t\t\tsts.Values.PutWithDot(item.Key, int64(val+item.Val))\n\t\t} else if item.typ == SET {\n\t\t\tsts.Values.PutWithDot(item.Key, int64(item.Val))\n\t\t}\n\n\t\t\n\t}\n}\n\nfunc (this *Stats) persist(item *StatsSave) {\n\t\/\/Do something \n\tjson, _ := item.Values.MarshalJSON()\n\n\tlog.Printf(\"TODO PERSISTING %s %s\", item.TimeAmount.String(), string(json))\n}<|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"code.google.com\/p\/go.crypto\/curve25519\"\n\t\"crypto\/hmac\"\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\/\/\"github.com\/agl\/ed25519\"\n\t\"github.com\/andres-erbsen\/dename\/client\"\n\t\/\/\"github.com\/andres-erbsen\/dename\/protocol\"\n\t\"bytes\"\n\t\"code.google.com\/p\/go.crypto\/nacl\/box\"\n\tprotobuf \"code.google.com\/p\/gogoprotobuf\/proto\"\n\t\"crypto\/subtle\"\n\t\"errors\"\n\t\"github.com\/andres-erbsen\/chatterbox\/proto\"\n\t\"github.com\/andres-erbsen\/chatterbox\/ratchet\"\n\ttestutil2 \"github.com\/andres-erbsen\/dename\/server\/testutil\" \/\/TODO: Move MakeToken to TestUtil\n\t\"github.com\/andres-erbsen\/dename\/testutil\"\n\t\/\/\"io\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst PROFILE_FIELD_ID = 1984\n\nfunc TestAliceTalksToBob(t *testing.T) {\n\tdir, err := ioutil.TempDir(\"\", \"testdb\")\n\thandleError(err, t)\n\n\tdefer os.RemoveAll(dir)\n\tdb, err := leveldb.OpenFile(dir, nil)\n\thandleError(err, t)\n\n\tdefer db.Close()\n\n\tserver, pks := setUpServerTest(db, t)\n\n\tconnA, inBufA, outBufA, pkpA := setUpClientTest(server, t)\n\tconnB, inBufB, outBufB, pkpB := setUpClientTest(server, t)\n\n\tconfig, f := testutil.SingleServer(t)\n\tdefer f()\n\ttime.Sleep(100)\n\n\t\/\/func createNewUser(name []byte, t *testing.T, config *client.Config, serverAddr string, pkTransport *[32]byte, idServer *[32]byte, signingKey *[32]byte, authKey *[32]byte) (*[32]byte, *client.Client) {\n\tpkTransportA, skTransportA, err := box.GenerateKey(rand.Reader)\n\thandleError(err)\n\n\tpkTransportB, skTransportA, err := box.GenerateKey(rand.Reader)\n\thandleError(err)\n\n\tska, dnmca := createNewUser([]byte(\"Alice\"), t, config, server.listener.Addr().String(), pkTransportA, pks)\n\tskb, dnmcb := createNewUser([]byte(\"Bob\"), t, config)\n\n\tprofileA\n\tprofileB\n\n\tmsg = []byte{\"Envelope1\"}\n\tratch, err := encryptAuthFirst(msg, []byte(\"Bob\"), ska, config)\n\thandleError(err)\n\n\tclientA := StartClient([]byte(\"Alice\"))\n\tclientB := StartClient([]byte(\"Bob\"), server.listener.Addr().String(), skb, connB, config)\n\n\t\/\/clientB.decryptAuthFirst(\n\n\t\/\/clientB := StartClient([]byte(\"Bob),\n}\n\nfunc setUpClientTest(server *Server, t *testing.T) (*transport.Conn, []byte, []byte, *[32]byte) {\n\toldConn, err := net.Dial(\"tcp\", server.listener.Addr().String())\n\thandleError(err, t)\n\n\tpkp, skp, err := box.GenerateKey(rand.Reader)\n\thandleError(err, t)\n\n\tconn, _, err := transport.Handshake(oldConn, pkp, skp, nil, MAX_MESSAGE_SIZE)\n\thandleError(err, t)\n\n\tinBuf := make([]byte, MAX_MESSAGE_SIZE)\n\toutBuf := make([]byte, MAX_MESSAGE_SIZE)\n\n\treturn conn, inBuf, outBuf, pkp\n}\n\nfunc setUpServerTest(db *leveldb.DB, t *testing.T) (*Server, *[32]byte) {\n\tshutdown := make(chan struct{})\n\n\tpks, sks, err := box.GenerateKey(rand.Reader)\n\thandleError(err, t)\n\n\tserver, err := StartServer(db, shutdown, pks, sks)\n\thandleError(err, t)\n\n\treturn server, nil\n}\n\nfunc handleError(err error, t *testing.T) {\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestMessageEncryptionAuthentication(t *testing.T) {\n\tconfig, f := testutil.SingleServer(t)\n\tdefer f()\n\ttime.Sleep(100)\n\n\tska, dnmca := createNewUser([]byte(\"Alice\"), t, config)\n\tskb, dnmcb := createNewUser([]byte(\"Bob\"), t, config)\n\n\tratchA := &ratchet.Ratchet{\n\t\tFillAuth:  FillAuthWith(ska),\n\t\tCheckAuth: CheckAuthWith(dnmca),\n\t\tRand:      nil,\n\t\tNow:       nil,\n\t}\n\tratchB := &ratchet.Ratchet{\n\t\tFillAuth:  FillAuthWith(skb),\n\t\tCheckAuth: CheckAuthWith(dnmcb),\n\t\tRand:      nil,\n\t\tNow:       nil,\n\t}\n\n\t\/\/pka0, ska0, err := box.GenerateKey(rand.Reader)\n\t\/\/handleError(err, t)\n\tpkb0, skb0, err := box.GenerateKey(rand.Reader)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tmsg, err := protobuf.Marshal(&proto.Message{\n\t\tSubject:  nil,\n\t\tContents: []byte(\"Message\"),\n\t\tDename:   []byte(\"Alice\"),\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tout := append([]byte{}, (*pkb0)[:]...)\n\n\tout = ratchA.EncryptFirst(out, msg, pkb0)\n\tmsg2, err := ratchB.DecryptFirst(out[32:], skb0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif !bytes.Equal(msg, msg2) {\n\t\tt.Error(\"Original and decrypted message not the same.\")\n\t}\n}\n\nfunc createNewUser(name []byte, t *testing.T, config *client.Config, serverAddr string, pkTransport *[32]byte, idServer *[32]byte, signingKey *[32]byte, authKey *[32]byte) (*[32]byte, *client.Client) {\n\tnewClient, err := client.NewClient(config, nil, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/TODO: All these names are horrible, please change them\n\tpkAuth, skAuth, err := box.GenerateKey(rand.Reader)\n\n\tchatProfile := &proto.Profile{\n\t\tServerAddressTCP:  []byte(serverAddr),\n\t\tServerTransportPK: (proto.Byte32)(pkTransport),\n\t\tUserIDAtServer:    (proto.Byte32)(idServer),\n\t\tKeySigningKey:     (proto.Byte32)(signingKey),\n\t\tMessageAuthKey:    (proto.Byte32)(authKey),\n\t}\n\n\tchatProfileBytes, err := protobuf.Marshal(chatProfile)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tprofile, sk, err := client.NewProfile(nil, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tclient.SetProfileField(profile, PROFILE_FIELD_ID, chatProfileBytes)\n\n\terr = newClient.Register(sk, name, profile, testutil2.MakeToken())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/Remove this outside of the test\n\tprofile2, err := newClient.Lookup(name)\n\tif !profile.Equal(profile2) {\n\t\tt.Errorf(\"Correct profile not added to server:\\nprofile: %v\\nprofile2 %v\\n\", profile, profile2)\n\t}\n\n\treturn skAuth, newClient\n}\n\n\/\/func FillAuthWith(ourAuthPrivate *[32]byte) func([]byte, []byte, *[32]byte) {\n\/\/return func(tag, data []byte, theirAuthPublic *[32]byte) {\n\/\/var sharedAuthKey [32]byte\n\/\/curve25519.ScalarMult(&sharedAuthKey, ourAuthPrivate, theirAuthPublic)\n\/\/h := hmac.New(sha256.New, sharedAuthKey[:])\n\/\/h.Write(data)\n\/\/h.Sum(nil)\n\/\/copy(tag, h.Sum(nil))\n\/\/}\n\/\/}\n\n\/\/func CheckAuthWith(dnmc *client.Client) func([]byte, []byte, []byte, *[32]byte) error {\n\/\/return func(tag, data, msg []byte, ourAuthPrivate *[32]byte) error {\n\/\/var sharedAuthKey [32]byte\n\/\/message := new(proto.Message)\n\/\/if err := message.Unmarshal(msg); err != nil {\n\/\/return err\n\/\/}\n\/\/profile, err := dnmc.Lookup(message.Dename)\n\/\/if err != nil {\n\/\/return err\n\/\/}\n\n\/\/chatProfileBytes, err := client.GetProfileField(profile, PROFILE_FIELD_ID)\n\/\/if err != nil {\n\/\/return err\n\/\/}\n\n\/\/chatProfile := new(proto.Profile)\n\/\/if err := chatProfile.Unmarshal(chatProfileBytes); err != nil {\n\/\/return err\n\/\/}\n\n\/\/theirAuthPublic := (*[32]byte)(&chatProfile.MessageAuthKey)\n\n\/\/curve25519.ScalarMult(&sharedAuthKey, ourAuthPrivate, theirAuthPublic)\n\/\/h := hmac.New(sha256.New, sharedAuthKey[:])\n\/\/h.Write(data)\n\/\/if subtle.ConstantTimeCompare(tag, h.Sum(nil)[:len(tag)]) == 0 {\n\n\/\/return errors.New(\"Authentication failed: failed to reproduce envelope auth tag using the current auth pubkey from dename\")\n\/\/}\n\/\/return nil\n\/\/}\n\/\/}\n<commit_msg>Nothing is broken<commit_after>package client\n\nimport (\n\t\"bytes\"\n\t\"code.google.com\/p\/go.crypto\/nacl\/box\"\n\tprotobuf \"code.google.com\/p\/gogoprotobuf\/proto\"\n\t\"crypto\/rand\"\n\t\"fmt\"\n\t\"github.com\/andres-erbsen\/chatterbox\/proto\"\n\t\"github.com\/andres-erbsen\/chatterbox\/ratchet\"\n\t\"github.com\/andres-erbsen\/dename\/client\"\n\ttestutil2 \"github.com\/andres-erbsen\/dename\/server\/testutil\" \/\/TODO: Move MakeToken to TestUtil\n\t\"github.com\/andres-erbsen\/dename\/testutil\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc handleError(err error, t *testing.T) {\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc TestMessageEncryptionAuthentication(t *testing.T) {\n\tconfig, f := testutil.SingleServer(t)\n\tdefer f()\n\ttime.Sleep(100)\n\n\tska, dnmca := createNewUser([]byte(\"Alice\"), t, config)\n\tskb, dnmcb := createNewUser([]byte(\"Bob\"), t, config)\n\n\tratchA := &ratchet.Ratchet{\n\t\tFillAuth:  FillAuthWith(ska),\n\t\tCheckAuth: CheckAuthWith(dnmca),\n\t\tRand:      nil,\n\t\tNow:       nil,\n\t}\n\tratchB := &ratchet.Ratchet{\n\t\tFillAuth:  FillAuthWith(skb),\n\t\tCheckAuth: CheckAuthWith(dnmcb),\n\t\tRand:      nil,\n\t\tNow:       nil,\n\t}\n\n\t\/\/pka0, ska0, err := box.GenerateKey(rand.Reader)\n\t\/\/handleError(err, t)\n\tpkb0, skb0, err := box.GenerateKey(rand.Reader)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tmsg, err := protobuf.Marshal(&proto.Message{\n\t\tSubject:  nil,\n\t\tContents: []byte(\"Message\"),\n\t\tDename:   []byte(\"Alice\"),\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tout := append([]byte{}, (*pkb0)[:]...)\n\n\tout = ratchA.EncryptFirst(out, msg, pkb0)\n\tmsg2, err := ratchB.DecryptFirst(out[32:], skb0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif !bytes.Equal(msg, msg2) {\n\t\tt.Error(\"Original and decrypted message not the same.\")\n\t}\n}\n\nfunc createNewUser(name []byte, t *testing.T, config *client.Config) (*[32]byte, *client.Client) {\n\tnewClient, err := client.NewClient(config, nil, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/TODO: All these names are horrible, please change them\n\tpkAuth, skAuth, err := box.GenerateKey(rand.Reader)\n\n\tchatProfile := &proto.Profile{\n\t\tServerAddressTCP:  \"\",\n\t\tServerTransportPK: (proto.Byte32)([32]byte{}),\n\t\tUserIDAtServer:    (proto.Byte32)([32]byte{}),\n\t\tKeySigningKey:     (proto.Byte32)([32]byte{}),\n\t\tMessageAuthKey:    (proto.Byte32)(*pkAuth),\n\t}\n\n\tchatProfileBytes, err := protobuf.Marshal(chatProfile)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tprofile, sk, err := client.NewProfile(nil, nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tclient.SetProfileField(profile, PROFILE_FIELD_ID, chatProfileBytes)\n\n\terr = newClient.Register(sk, name, profile, testutil2.MakeToken())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/Remove this outside of the test\n\tprofile2, err := newClient.Lookup(name)\n\tif !profile.Equal(profile2) {\n\t\tt.Error(\"Correct profile not added to server.\")\n\t\tfmt.Printf(\"profile: %v\\n\", profile)\n\t\tfmt.Printf(\"profile2: %v\\n\", profile2)\n\t}\n\n\treturn skAuth, newClient\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"github.com\/nsf\/termbox-go\"\nimport \"time\"\nimport \"flag\"\n\nfunc main() {\n\tloops := flag.Int(\"loops\", 0, \"number of times to loop (default: infinite)\")\n\tdelay := flag.Int(\"delay\", 75, \"frame delay in ms\")\n\torientation := flag.String(\"orientation\", \"regular\", \"regular or aussie\")\n\tflag.Parse()\n\n\terr := termbox.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer termbox.Close()\n\n\tevent_queue := make(chan termbox.Event)\n\tgo func() {\n\t\tfor {\n\t\t\tevent_queue <- termbox.PollEvent()\n\t\t}\n\t}()\n\n\ttermbox.SetOutputMode(termbox.Output256)\n\n\tloop_index := 0\n\tdraw(*orientation)\n\nloop:\n\tfor {\n\t\tselect {\n\t\tcase ev := <-event_queue:\n\t\t\tif ev.Type == termbox.EventKey && (ev.Key == termbox.KeyEsc || ev.Key == termbox.KeyCtrlC) {\n\t\t\t\tbreak loop\n\t\t\t}\n\t\tdefault:\n\t\t\tloop_index++\n\t\t\tif *loops > 0 && (loop_index\/9) >= *loops {\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t\tdraw(*orientation)\n\t\t\ttime.Sleep(time.Duration(*delay) * time.Millisecond)\n\t\t}\n\t}\n}\n<commit_msg>Exit on EventInterrupt rather on hardcoded Ctrl+C<commit_after>package main\n\nimport \"github.com\/nsf\/termbox-go\"\nimport \"time\"\nimport \"flag\"\n\nfunc main() {\n\tloops := flag.Int(\"loops\", 0, \"number of times to loop (default: infinite)\")\n\tdelay := flag.Int(\"delay\", 75, \"frame delay in ms\")\n\torientation := flag.String(\"orientation\", \"regular\", \"regular or aussie\")\n\tflag.Parse()\n\n\terr := termbox.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer termbox.Close()\n\n\tevent_queue := make(chan termbox.Event)\n\tgo func() {\n\t\tfor {\n\t\t\tevent_queue <- termbox.PollEvent()\n\t\t}\n\t}()\n\n\ttermbox.SetOutputMode(termbox.Output256)\n\n\tloop_index := 0\n\tdraw(*orientation)\n\nloop:\n\tfor {\n\t\tselect {\n\t\tcase ev := <-event_queue:\n\t\t\tif (ev.Type == termbox.EventKey && ev.Key == termbox.KeyEsc) || ev.Type == termbox.EventInterrupt {\n\t\t\t\tbreak loop\n\t\t\t}\n\t\tdefault:\n\t\t\tloop_index++\n\t\t\tif *loops > 0 && (loop_index\/9) >= *loops {\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t\tdraw(*orientation)\n\t\t\ttime.Sleep(time.Duration(*delay) * time.Millisecond)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Parser struct {\n\n\tdebug bool\n\n\tScanner Scanner\n\toutput string\n\n\t\/\/ node heirarchy stack\n\tstack []*Node\n\n\t\/\/ edge in stack\n\tnode *Node\n\n\t\/\/ states as the Parser object figures out how to output the tokens\n\n\t\/\/ new line has started\n\tisNewLine bool\n\n\tisIndent bool\n\tisDedent bool\n\n\t\/\/ flag indicates we are still checking for attribute assignments\n\tisAttr bool\n\n\tisStringFlag bool\n\n\t\/\/ attrName and attrValue are buffers to determine if TokWord for a tag are \n\t\/\/ potentially for an attribute, or if they are just normal text\n\tattrName string\n\tattrValue string\n\tattrAssigned bool\n\n}\n\nfunc (p *Parser) Output() string {\n\tvar tokens []rune\n\tvar text string\n\n\tp.node = p.newNode()\n\tp.node.Type = NodeRoot\n\tp.stack = make([]*Node, 0)\n\tp.stack = append(p.stack, p.node)\n\n\tp.output = \"\"\n\tp.isNewLine = true\n\tp.isIndent = false\n\tp.isDedent = false\n\tp.isAttr = false\n\tp.attrName = \"\"\n\tp.attrValue = \"\"\n\tp.attrAssigned = false\n\n\tfor {\n\t\ttokens = p.Scanner.Scan()\n\t\tfor _, token := range tokens {\n\t\t\ttext = p.Scanner.TokenText()\n\t\t\tif p.debug {\n\t\t\t\tfmt.Printf(\"[debug] token: [%s]\\n\", TokenString(token))\n\t\t\t\tfmt.Printf(\"[debug] text:  [%s]\\n\", text)\n\t\t\t}\n\t\t\tp.processToken(token, text)\n\t\t\tif p.debug {\n\t\t\t\tfmt.Printf(\"[debug] node:  [%s]\\n\\n\", p.node.Debug())\n\t\t\t}\n\t\t}\n\t\tif tokens[0] == TokEOF {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn p.output\n}\n\nfunc (p *Parser) trimOutput() {\n\tp.output = strings.TrimSpace(p.output)\n}\n\nfunc (p *Parser) newNode() *Node {\n\tn := new(Node)\n\tn.attrs = make(map[string]string)\n\treturn n\n}\n\nfunc (p *Parser) lastNode() *Node {\n\tif len(p.stack) > 0 {\n\t\treturn p.stack[len(p.stack) - 1]\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc (p *Parser) popNode() *Node {\n\tn := p.lastNode()\n\tif n != nil {\n\t\tp.stack = p.stack[0:len(p.stack)-1]\n\t}\n\treturn n\n}\n\nfunc (p *Parser) pushNode(n *Node) {\n\tp.stack = append(p.stack, n)\n}\n\nfunc (p *Parser) dedentFromStack() {\n\tn := p.lastNode()\n\tif n != nil && n.Type != NodeRoot {\n\t\tp.output += n.OpenString()\n\t\tp.trimOutput()\n\t\tp.output += n.CloseString()\n\t\tp.popNode()\n\t}\n}\n\nfunc (p *Parser) processToken(tok rune, text string) {\n\t\/\/ indent\/dedent\/nodent is the first place to look to see if new nodes need\n\t\/\/ to be made. checks are for parent node being certain types like NodeText\n\t\/\/ or NodeComment\n\tswitch tok {\n\tcase TokIndent:\n\t\tp.isIndent = true\n\t\tp.isDedent = false\n\t\tif p.node.Type != NodeText {\n\t\t\tp.output += p.node.OpenString()\n\t\t\tp.node = p.newNode()\n\t\t\tp.pushNode(p.node)\n\t\t}\n\tcase TokDedent:\n\t\tp.isIndent = false\n\t\tp.isDedent = true\n\t\tp.dedentFromStack()\n\t\tif p.node.Type != NodeText {\n\t\t\tp.dedentFromStack()\n\t\t}\n\t\tp.node = p.newNode()\n\t\tp.pushNode(p.node)\n\tcase TokNodent:\n\t\tp.isIndent = false\n\t\tp.isDedent = false\n\t\tswitch p.node.Type {\n\t\tcase NodeRoot:\n\t\t\tp.node = p.newNode()\n\t\t\tp.pushNode(p.node)\n\t\tcase NodeText:\n\t\tdefault:\n\t\t\t\/\/ replace top of stack with new node (pop then push)\n\t\t\tn := p.popNode()\n\t\t\tp.output += n.OpenString()\n\t\t\tp.trimOutput()\n\t\t\tp.output += n.CloseString()\n\t\t\tp.node = p.newNode()\n\t\t\tp.pushNode(p.node)\n\t\t}\n\t}\n\n\tif p.node.Type == NodeText && tok != TokDedent {\n\t\tif tok != TokIndent {\n\t\t\tif tok == TokNewLine {\n\t\t\t\tp.node.text += \" \"\n\t\t\t} else if tok != TokWhitespace || p.node.text != \"\" {\n\t\t\t\tp.node.text += text\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\tswitch tok {\n\tcase TokWord, TokComma:\n\t\tswitch p.node.Type {\n\t\tcase NodeNil:\n\t\t\tp.node.Type = NodeTag\n\t\t\tp.node.tag = text\n\t\t\t\/\/ found the tag, now check for attributes\n\t\t\tp.isAttr = true\n\t\t\tp.attrAssigned = false\n\t\tcase NodeTag:\n\t\t\tif p.isAttr {\n\t\t\t\tif p.attrAssigned {\n\t\t\t\t\tif _, found := p.node.attrs[p.attrName]; found {\n\t\t\t\t\t\tp.node.attrs[p.attrName] += \" \"\n\t\t\t\t\t\tp.node.attrs[p.attrName] += text\n\t\t\t\t\t} else {\n\t\t\t\t\t\tp.node.attrs[p.attrName] = text\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ reset to look for a new attribute assignment\n\t\t\t\t\tp.attrName = \"\"\n\t\t\t\t\tp.attrValue = \"\"\n\t\t\t\t\tp.attrAssigned = false\n\t\t\t\t\tp.node.attrString = \"\"\n\t\t\t\t} else if p.attrName == \"\" {\n\t\t\t\t\tp.node.attrString += text\n\t\t\t\t\tp.attrName = text\n\t\t\t\t} else {\n\t\t\t\t\tp.node.text += p.node.attrString\n\t\t\t\t\tp.node.text += text\n\t\t\t\t\tp.node.attrString = \"\"\n\t\t\t\t\tp.isAttr = false\n\t\t\t\t\tp.attrAssigned = false\n\t\t\t\t\tp.attrName = \"\"\n\t\t\t\t\tp.attrValue = \"\"\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tp.node.text += text\n\t\t\t}\n\t\t}\n\tcase TokString:\n\t\tswitch p.node.Type {\n\t\tcase NodeTag:\n\t\t\tif p.isAttr {\n\t\t\t\tif p.attrAssigned {\n\t\t\t\t\tif _, found := p.node.attrs[p.attrName]; found {\n\t\t\t\t\t\tp.node.attrs[p.attrName] += \" \"\n\t\t\t\t\t\tp.node.attrs[p.attrName] += text[1:len(text)-1]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tp.node.attrs[p.attrName] = text[1:len(text)-1]\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ reset to look for a new attribute assignment\n\t\t\t\t\tp.attrName = \"\"\n\t\t\t\t\tp.attrValue = \"\"\n\t\t\t\t\tp.attrAssigned = false\n\t\t\t\t\tp.node.attrString = \"\"\n\t\t\t\t} else if p.attrName != \"\" {\n\t\t\t\t\t\/\/ TODO using string in attrName shouldn't be allowed\n\t\t\t\t\tp.node.text += p.node.attrString\n\t\t\t\t\tp.node.text += text[1:len(text)-1]\n\t\t\t\t\tp.node.attrString = \"\"\n\t\t\t\t\tp.isAttr = false\n\t\t\t\t\tp.attrName = \"\"\n\t\t\t\t\tp.attrValue = \"\"\n\t\t\t\t\tp.attrAssigned = false\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tp.node.text += text\n\t\t\t}\n\t\tcase NodeText:\n\t\t\tp.node.text += text\n\t\t}\n\tcase TokAssign:\n\t\tswitch p.node.Type {\n\t\tcase NodeTag:\n\t\t\tif p.isAttr {\n\t\t\t\tif p.attrName != \"\" && p.attrValue == \"\" {\n\t\t\t\t\tp.attrAssigned = true\n\t\t\t\t\tp.node.attrString += text\n\t\t\t\t}\n\t\t\t\tif p.attrName == \"\" || p.attrValue != \"\" {\n\t\t\t\t\tp.attrAssigned = false\n\t\t\t\t\tp.isAttr = false\n\t\t\t\t\tp.node.text += p.node.attrString\n\t\t\t\t\tp.node.attrString = \"\"\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tp.node.text += text\n\t\t\t}\n\t\tcase NodeText:\n\t\t\tp.node.text += text\n\t\t}\n\tcase TokWhitespace:\n\t\tswitch p.node.Type {\n\t\tcase NodeTag:\n\t\t\tif p.isAttr && p.node.attrString != \"\" {\n\t\t\t\tp.node.attrString += text\n\n\t\t\t\/\/ skip initial whitespace for text\n\t\t\t} else if p.node.text != \"\" {\n\t\t\t\tp.node.text += text\n\t\t\t}\n\t\t}\n\tcase TokStringFlag:\n\t\tswitch p.node.Type {\n\t\tcase NodeNil:\n\t\t\t\/\/ new node, but indent indicates continue with text of previous node\n\t\t\tp.node.Type = NodeText\n\t\tcase NodeTag:\n\t\t\tif p.isAttr {\n\t\t\t\tp.node.text += p.node.attrString\n\t\t\t\tp.node.attrString = \"\"\n\t\t\t} else {\n\t\t\t\tp.node.text += text\n\t\t\t}\n\t\t\tp.isAttr = false\n\t\t}\n\tcase TokNewLine:\n\t\t\/\/ reset\n\t\tp.isIndent = false\n\t\tp.isDedent = false\n\t\tp.isAttr = false\n\t\tp.attrName = \"\"\n\t\tp.attrValue = \"\"\n\t\tp.attrAssigned = false\n\tcase TokEOF:\n\t\t\/\/ close the remaining nodes in the stack \n\t\tfor len(p.stack) > 0 {\n\t\t\tlastNode := p.popNode()\n\t\t\tp.trimOutput()\n\t\t\tp.output += lastNode.CloseString()\n\t\t}\n\t\/\/ nop\n\tcase TokIndent, TokDedent, TokNodent:\n\tdefault:\n\t\tif !p.isAttr {\n\t\t\tp.node.text += text\n\t\t}\n\t}\n}\n\n<commit_msg>dedenting from Node stack adds a space if it is a NodeText<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Parser struct {\n\n\tdebug bool\n\n\tScanner Scanner\n\toutput string\n\n\t\/\/ node heirarchy stack\n\tstack []*Node\n\n\t\/\/ edge in stack\n\tnode *Node\n\n\t\/\/ states as the Parser object figures out how to output the tokens\n\n\t\/\/ new line has started\n\tisNewLine bool\n\n\tisIndent bool\n\tisDedent bool\n\n\t\/\/ flag indicates we are still checking for attribute assignments\n\tisAttr bool\n\n\tisStringFlag bool\n\n\t\/\/ attrName and attrValue are buffers to determine if TokWord for a tag are \n\t\/\/ potentially for an attribute, or if they are just normal text\n\tattrName string\n\tattrValue string\n\tattrAssigned bool\n\n}\n\nfunc (p *Parser) Output() string {\n\tvar tokens []rune\n\tvar text string\n\n\tp.node = p.newNode()\n\tp.node.Type = NodeRoot\n\tp.stack = make([]*Node, 0)\n\tp.stack = append(p.stack, p.node)\n\n\tp.output = \"\"\n\tp.isNewLine = true\n\tp.isIndent = false\n\tp.isDedent = false\n\tp.isAttr = false\n\tp.attrName = \"\"\n\tp.attrValue = \"\"\n\tp.attrAssigned = false\n\n\tfor {\n\t\ttokens = p.Scanner.Scan()\n\t\tfor _, token := range tokens {\n\t\t\ttext = p.Scanner.TokenText()\n\t\t\tif p.debug {\n\t\t\t\tfmt.Printf(\"[debug] token: [%s]\\n\", TokenString(token))\n\t\t\t\tfmt.Printf(\"[debug] text:  [%s]\\n\", text)\n\t\t\t}\n\t\t\tp.processToken(token, text)\n\t\t\tif p.debug {\n\t\t\t\tfmt.Printf(\"[debug] node:  [%s]\\n\\n\", p.node.Debug())\n\t\t\t}\n\t\t}\n\t\tif tokens[0] == TokEOF {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn p.output\n}\n\nfunc (p *Parser) trimOutput() {\n\tp.output = strings.TrimSpace(p.output)\n}\n\nfunc (p *Parser) newNode() *Node {\n\tn := new(Node)\n\tn.attrs = make(map[string]string)\n\treturn n\n}\n\nfunc (p *Parser) lastNode() *Node {\n\tif len(p.stack) > 0 {\n\t\treturn p.stack[len(p.stack) - 1]\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc (p *Parser) popNode() *Node {\n\tn := p.lastNode()\n\tif n != nil {\n\t\tp.stack = p.stack[0:len(p.stack)-1]\n\t}\n\treturn n\n}\n\nfunc (p *Parser) pushNode(n *Node) {\n\tp.stack = append(p.stack, n)\n}\n\nfunc (p *Parser) dedentFromStack() {\n\tn := p.lastNode()\n\tif n != nil && n.Type != NodeRoot {\n\t\tp.output += n.OpenString()\n\t\tp.trimOutput()\n\t\t\/\/ newlines in NodeText have spaces. Adding one here for consistency\n\t\tif n.Type == NodeText {\n\t\t\tp.output += \" \"\n\t\t}\n\t\tp.output += n.CloseString()\n\t\tp.popNode()\n\t}\n}\n\nfunc (p *Parser) processToken(tok rune, text string) {\n\t\/\/ indent\/dedent\/nodent is the first place to look to see if new nodes need\n\t\/\/ to be made. checks are for parent node being certain types like NodeText\n\t\/\/ or NodeComment\n\tswitch tok {\n\tcase TokIndent:\n\t\tp.isIndent = true\n\t\tp.isDedent = false\n\t\tif p.node.Type != NodeText {\n\t\t\tp.output += p.node.OpenString()\n\t\t\tp.node = p.newNode()\n\t\t\tp.pushNode(p.node)\n\t\t}\n\tcase TokDedent:\n\t\tp.isIndent = false\n\t\tp.isDedent = true\n\t\tp.dedentFromStack()\n\t\tif p.node.Type != NodeText {\n\t\t\tp.dedentFromStack()\n\t\t}\n\t\tp.node = p.newNode()\n\t\tp.pushNode(p.node)\n\tcase TokNodent:\n\t\tp.isIndent = false\n\t\tp.isDedent = false\n\t\tswitch p.node.Type {\n\t\tcase NodeRoot:\n\t\t\tp.node = p.newNode()\n\t\t\tp.pushNode(p.node)\n\t\tcase NodeText:\n\t\tdefault:\n\t\t\t\/\/ replace top of stack with new node (pop then push)\n\t\t\tn := p.popNode()\n\t\t\tp.output += n.OpenString()\n\t\t\tp.trimOutput()\n\t\t\tp.output += n.CloseString()\n\t\t\tp.node = p.newNode()\n\t\t\tp.pushNode(p.node)\n\t\t}\n\t}\n\n\tif p.node.Type == NodeText && tok != TokDedent {\n\t\tif tok != TokIndent {\n\t\t\tif tok == TokNewLine {\n\t\t\t\tp.node.text += \" \"\n\t\t\t} else if tok != TokWhitespace || p.node.text != \"\" {\n\t\t\t\tp.node.text += text\n\t\t\t}\n\t\t}\n\t\treturn\n\t}\n\n\tswitch tok {\n\tcase TokWord, TokComma:\n\t\tswitch p.node.Type {\n\t\tcase NodeNil:\n\t\t\tp.node.Type = NodeTag\n\t\t\tp.node.tag = text\n\t\t\t\/\/ found the tag, now check for attributes\n\t\t\tp.isAttr = true\n\t\t\tp.attrAssigned = false\n\t\tcase NodeTag:\n\t\t\tif p.isAttr {\n\t\t\t\tif p.attrAssigned {\n\t\t\t\t\tif _, found := p.node.attrs[p.attrName]; found {\n\t\t\t\t\t\tp.node.attrs[p.attrName] += \" \"\n\t\t\t\t\t\tp.node.attrs[p.attrName] += text\n\t\t\t\t\t} else {\n\t\t\t\t\t\tp.node.attrs[p.attrName] = text\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ reset to look for a new attribute assignment\n\t\t\t\t\tp.attrName = \"\"\n\t\t\t\t\tp.attrValue = \"\"\n\t\t\t\t\tp.attrAssigned = false\n\t\t\t\t\tp.node.attrString = \"\"\n\t\t\t\t} else if p.attrName == \"\" {\n\t\t\t\t\tp.node.attrString += text\n\t\t\t\t\tp.attrName = text\n\t\t\t\t} else {\n\t\t\t\t\tp.node.text += p.node.attrString\n\t\t\t\t\tp.node.text += text\n\t\t\t\t\tp.node.attrString = \"\"\n\t\t\t\t\tp.isAttr = false\n\t\t\t\t\tp.attrAssigned = false\n\t\t\t\t\tp.attrName = \"\"\n\t\t\t\t\tp.attrValue = \"\"\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tp.node.text += text\n\t\t\t}\n\t\t}\n\tcase TokString:\n\t\tswitch p.node.Type {\n\t\tcase NodeTag:\n\t\t\tif p.isAttr {\n\t\t\t\tif p.attrAssigned {\n\t\t\t\t\tif _, found := p.node.attrs[p.attrName]; found {\n\t\t\t\t\t\tp.node.attrs[p.attrName] += \" \"\n\t\t\t\t\t\tp.node.attrs[p.attrName] += text[1:len(text)-1]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tp.node.attrs[p.attrName] = text[1:len(text)-1]\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ reset to look for a new attribute assignment\n\t\t\t\t\tp.attrName = \"\"\n\t\t\t\t\tp.attrValue = \"\"\n\t\t\t\t\tp.attrAssigned = false\n\t\t\t\t\tp.node.attrString = \"\"\n\t\t\t\t} else if p.attrName != \"\" {\n\t\t\t\t\t\/\/ TODO using string in attrName shouldn't be allowed\n\t\t\t\t\tp.node.text += p.node.attrString\n\t\t\t\t\tp.node.text += text[1:len(text)-1]\n\t\t\t\t\tp.node.attrString = \"\"\n\t\t\t\t\tp.isAttr = false\n\t\t\t\t\tp.attrName = \"\"\n\t\t\t\t\tp.attrValue = \"\"\n\t\t\t\t\tp.attrAssigned = false\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tp.node.text += text\n\t\t\t}\n\t\tcase NodeText:\n\t\t\tp.node.text += text\n\t\t}\n\tcase TokAssign:\n\t\tswitch p.node.Type {\n\t\tcase NodeTag:\n\t\t\tif p.isAttr {\n\t\t\t\tif p.attrName != \"\" && p.attrValue == \"\" {\n\t\t\t\t\tp.attrAssigned = true\n\t\t\t\t\tp.node.attrString += text\n\t\t\t\t}\n\t\t\t\tif p.attrName == \"\" || p.attrValue != \"\" {\n\t\t\t\t\tp.attrAssigned = false\n\t\t\t\t\tp.isAttr = false\n\t\t\t\t\tp.node.text += p.node.attrString\n\t\t\t\t\tp.node.attrString = \"\"\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tp.node.text += text\n\t\t\t}\n\t\tcase NodeText:\n\t\t\tp.node.text += text\n\t\t}\n\tcase TokWhitespace:\n\t\tswitch p.node.Type {\n\t\tcase NodeTag:\n\t\t\tif p.isAttr && p.node.attrString != \"\" {\n\t\t\t\tp.node.attrString += text\n\n\t\t\t\/\/ skip initial whitespace for text\n\t\t\t} else if p.node.text != \"\" {\n\t\t\t\tp.node.text += text\n\t\t\t}\n\t\t}\n\tcase TokStringFlag:\n\t\tswitch p.node.Type {\n\t\tcase NodeNil:\n\t\t\t\/\/ new node, but indent indicates continue with text of previous node\n\t\t\tp.node.Type = NodeText\n\t\tcase NodeTag:\n\t\t\tif p.isAttr {\n\t\t\t\tp.node.text += p.node.attrString\n\t\t\t\tp.node.attrString = \"\"\n\t\t\t} else {\n\t\t\t\tp.node.text += text\n\t\t\t}\n\t\t\tp.isAttr = false\n\t\t}\n\tcase TokNewLine:\n\t\t\/\/ reset\n\t\tp.isIndent = false\n\t\tp.isDedent = false\n\t\tp.isAttr = false\n\t\tp.attrName = \"\"\n\t\tp.attrValue = \"\"\n\t\tp.attrAssigned = false\n\tcase TokEOF:\n\t\t\/\/ close the remaining nodes in the stack \n\t\tfor len(p.stack) > 0 {\n\t\t\tlastNode := p.popNode()\n\t\t\tp.trimOutput()\n\t\t\tp.output += lastNode.CloseString()\n\t\t}\n\t\/\/ nop\n\tcase TokIndent, TokDedent, TokNodent:\n\tdefault:\n\t\tif !p.isAttr {\n\t\t\tp.node.text += text\n\t\t}\n\t}\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype clippingHandler func(*rawClipping)\n\ntype parser struct {\n\thandler clippingHandler\n}\n\nfunc (p *parser) parseClippingFile(clippingFile string) {\n\tf, err := os.Open(clippingFile)\n\tif err != nil {\n\t\tlog.Fatalln(\"Cannot open file\", err.Error())\n\t}\n\tdefer f.Close()\n\n\tp.parse(f)\n}\n\ntype clippingType int\n\nconst (\n\tundefined clippingType = iota\n\thighlight\n\tnote\n\tbookmark\n)\n\ntype rawClipping struct {\n\tbaseClipping\n\tcType clippingType\n}\n\nfunc (i *parser) parse(r io.Reader) {\n\tc := new(rawClipping)\n\n\tlineNo := 0\n\n\tscanner := bufio.NewScanner(r)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tlineNo++\n\n\t\tif line == \"==========\" {\n\t\t\tlineNo = 0\n\t\t\tif c != nil {\n\t\t\t\ti.handler(c)\n\t\t\t}\n\t\t\tc = new(rawClipping)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch lineNo {\n\t\tcase 1:\n\t\t\ti.extractBook(line, c)\n\t\tcase 2:\n\t\t\ti.extractLocationAndDate(line, c)\n\t\tcase 3:\n\t\t\tcontinue\n\t\tdefault:\n\t\t\tif c.Content != \"\" {\n\t\t\t\tc.Content += \"\\n\"\n\t\t\t}\n\t\t\tc.Content += line\n\t\t}\n\n\t}\n}\n\nfunc (i *parser) extractBook(str string, c *rawClipping) {\n\tix := strings.LastIndex(str, \" (\")\n\tif ix < 0 {\n\t\tc.Book.Title = str\n\t} else {\n\t\tc.Book.Title = str[:ix]\n\t\tc.Book.Authors = str[ix+2 : len(str)-1]\n\t}\n}\n\nfunc (i *parser) extractLocationAndDate(str string, c *rawClipping) {\n\tix := strings.LastIndex(str, \" | \")\n\n\ti.extractLocation(str[:ix], c)\n\ti.extractAddDate(str[ix+3:], c)\n\tc.cType = extractType(str)\n}\n\nfunc extractType(str string) clippingType {\n\tif strings.Contains(str, \"Your Highlight\") {\n\t\treturn highlight\n\t} else if strings.Contains(str, \"Your Note\") {\n\t\treturn note\n\t} else if strings.Contains(str, \"Your Bookmark\") {\n\t\treturn bookmark\n\t} else {\n\t\tlog.Fatalln(\"Cannot deternime clipping type:\", str)\n\t\treturn undefined\n\t}\n}\n\nfunc (i *parser) extractAddDate(str string, c *rawClipping) {\n\tix := strings.Index(str, \",\")\n\tdateStr := str[ix+2:]\n\tt, err := time.Parse(\"January 2, 2006 3:04:05 PM\", dateStr)\n\tif err != nil {\n\t\tlog.Fatalln(\"Cannot parse date:\", dateStr)\n\t}\n\tc.CreationTime = t.Unix()\n}\n\nfunc (i *parser) extractLocation(str string, c *rawClipping) {\n\tix := strings.LastIndex(str, \" \")\n\tpageStr := strings.Split(str[ix+1:], \"-\")\n\tii, err := strconv.Atoi(pageStr[0])\n\tif err != nil {\n\t\tlog.Fatalln(\"Cannot parse start page\", pageStr[0], \"in\", str)\n\t}\n\tc.Loc.Start = ii\n\n\tif len(pageStr) == 2 {\n\t\tii, err = strconv.Atoi(pageStr[1])\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Cannot pares end page\", pageStr[1], \"in\", str)\n\t\t}\n\t\tc.Loc.End = ii\n\t} else {\n\t\tc.Loc.End = ii\n\t}\n}\n<commit_msg>Remove BOM from book titles<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype clippingHandler func(*rawClipping)\n\ntype parser struct {\n\thandler clippingHandler\n}\n\nvar bom = []byte{0xef, 0xbb, 0xbf}\n\nfunc (p *parser) parseClippingFile(clippingFile string) {\n\tf, err := os.Open(clippingFile)\n\tif err != nil {\n\t\tlog.Fatalln(\"Cannot open file\", err.Error())\n\t}\n\tdefer f.Close()\n\n\tp.parse(f)\n}\n\ntype clippingType int\n\nconst (\n\tundefined clippingType = iota\n\thighlight\n\tnote\n\tbookmark\n)\n\ntype rawClipping struct {\n\tbaseClipping\n\tcType clippingType\n}\n\nfunc (i *parser) parse(r io.Reader) {\n\tc := new(rawClipping)\n\n\tlineNo := 0\n\n\tscanner := bufio.NewScanner(r)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tlineNo++\n\n\t\tif line == \"==========\" {\n\t\t\tlineNo = 0\n\t\t\tif c != nil {\n\t\t\t\ti.handler(c)\n\t\t\t}\n\t\t\tc = new(rawClipping)\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch lineNo {\n\t\tcase 1:\n\t\t\ti.extractBook(line, c)\n\t\tcase 2:\n\t\t\ti.extractLocationAndDate(line, c)\n\t\tcase 3:\n\t\t\tcontinue\n\t\tdefault:\n\t\t\tif c.Content != \"\" {\n\t\t\t\tc.Content += \"\\n\"\n\t\t\t}\n\t\t\tc.Content += line\n\t\t}\n\n\t}\n}\n\nfunc (i *parser) extractBook(str string, c *rawClipping) {\n\tif bytes.HasPrefix([]byte(str), bom) {\n\t\tstr = str[3:]\n\t}\n\tix := strings.LastIndex(str, \" (\")\n\tif ix < 0 {\n\t\tc.Book.Title = str\n\t} else {\n\t\tc.Book.Title = str[:ix]\n\t\tc.Book.Authors = str[ix+2 : len(str)-1]\n\t}\n}\n\nfunc (i *parser) extractLocationAndDate(str string, c *rawClipping) {\n\tix := strings.LastIndex(str, \" | \")\n\n\ti.extractLocation(str[:ix], c)\n\ti.extractAddDate(str[ix+3:], c)\n\tc.cType = extractType(str)\n}\n\nfunc extractType(str string) clippingType {\n\tif strings.Contains(str, \"Your Highlight\") {\n\t\treturn highlight\n\t} else if strings.Contains(str, \"Your Note\") {\n\t\treturn note\n\t} else if strings.Contains(str, \"Your Bookmark\") {\n\t\treturn bookmark\n\t} else {\n\t\tlog.Fatalln(\"Cannot deternime clipping type:\", str)\n\t\treturn undefined\n\t}\n}\n\nfunc (i *parser) extractAddDate(str string, c *rawClipping) {\n\tix := strings.Index(str, \",\")\n\tdateStr := str[ix+2:]\n\tt, err := time.Parse(\"January 2, 2006 3:04:05 PM\", dateStr)\n\tif err != nil {\n\t\tlog.Fatalln(\"Cannot parse date:\", dateStr)\n\t}\n\tc.CreationTime = t.Unix()\n}\n\nfunc (i *parser) extractLocation(str string, c *rawClipping) {\n\tix := strings.LastIndex(str, \" \")\n\tpageStr := strings.Split(str[ix+1:], \"-\")\n\tii, err := strconv.Atoi(pageStr[0])\n\tif err != nil {\n\t\tlog.Fatalln(\"Cannot parse start page\", pageStr[0], \"in\", str)\n\t}\n\tc.Loc.Start = ii\n\n\tif len(pageStr) == 2 {\n\t\tii, err = strconv.Atoi(pageStr[1])\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Cannot pares end page\", pageStr[1], \"in\", str)\n\t\t}\n\t\tc.Loc.End = ii\n\t} else {\n\t\tc.Loc.End = ii\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package tql\n\n\/*\n  Tql, Simple SQL-Like query language\n\n  BNF:\n  select <property> [, <property> ...] | *]\n    [from <from>]\n    [where <condition> [and <condition> ...]] [limit <num> offset <num> | limit <num>, <num>]\n\n  <condition> := <property> {< | <= | > | >= | = | != | in} <value>\n*\/\n\nimport (\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar tokenize_regex = `(?:\"[^\"\\n\\r]*\")+|(?:'[^'\\n\\r]*')+|<=|>=|!=|=|<|>|,|\\*|-?\\d+(?:\\.\\d+)?|\\w+(?:\\.\\w+)*|(?:\"[^\"\\s]+\")+|\\(|\\)|\\S+`\n\ntype Tql struct {\n\ttokens  []string\n\tquery   string\n\tpos     int\n\tprops   []string\n\tfrom    string\n\tconds   []Cond\n\tlimit   int64\n\toffset  int64\n\torderBy string \/\/ TODO\n\torder   int \/\/ TODO\n}\n\nconst (\n\tValString = iota\n\tValInt\n\tValFloat\n\tValQuoteString\n\tValBool\n\tValNull\n\tValReference\n\tValList\n)\n\ntype Val struct {\n\tvalType int\n\tval     interface{}\n}\n\ntype Cond struct {\n\tidentifier string\n\top         string\n\tval        Val\n}\n\nfunc NewTql(query string) *Tql {\n\tt := new(Tql)\n\tt.pos = 0\n\tt.query = strings.ToLower(query)\n\tt.limit = -1\n\tt.offset = -1\n    t.order = -1\n\tif re, err := regexp.Compile(tokenize_regex); err != nil {\n\t\treturn nil\n\t} else {\n\t\tt.tokens = re.FindAllString(t.query, -1)\n\t\tif len(t.tokens) <= 0 {\n\t\t\treturn nil\n\t\t}\n\t}\n\tt.__Select()\n\treturn t\n}\n\nfunc (t *Tql) __Expect(expect string) {\n\tif t.__Consume(expect) == false {\n\t\tpanic(\"token error\")\n\t}\n}\n\nfunc (t *Tql) __Consume(expect string) bool {\n\tif t.pos < len(t.tokens) {\n\t\tif t.tokens[t.pos] == expect {\n\t\t\tt.pos += 1\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (t *Tql) __ConsumeRegexp(regex string) (bool, string) {\n\tif t.pos < len(t.tokens) {\n\t\ttoken := t.tokens[t.pos]\n\t\tre, _ := regexp.Compile(regex)\n\t\tif re.MatchString(token) {\n\t\t\tt.pos += 1\n\t\t\treturn true, token\n\t\t}\n\t}\n\treturn false, \"\"\n}\n\n\/\/ consume a identifier an return\nvar identifier_regex = `(\\w+(?:\\.\\w+)*)$`\n\nfunc (t *Tql) __Identifier() (bool, string) {\n\tif b, ident := t.__ConsumeRegexp(identifier_regex); b {\n\t\treturn true, ident\n\t}\n\treturn false, \"\"\n}\n\nfunc (t *Tql) __ExpectIdentifier() string {\n\tif b, ident := t.__Identifier(); b {\n\t\treturn ident\n\t}\n\tpanic(\"identifier error\")\n}\n\nfunc (t *Tql) __Select() bool {\n\tt.__Expect(\"select\")\n\tif !t.__Consume(\"*\") {\n\t\tt.props = append(t.props, t.__ExpectIdentifier())\n\t\tfor t.__Consume(\",\") {\n\t\t\tt.props = append(t.props, t.__ExpectIdentifier())\n\t\t}\n\t} else {\n\t\tt.props = append(t.props, \"*\")\n\t}\n\treturn t.__From()\n}\n\nfunc (t *Tql) __From() bool {\n\tif t.__Consume(\"from\") {\n\t\tt.from = t.__ExpectIdentifier()\n\t} else {\n\t\treturn false\n\t}\n\treturn t.__Where()\n}\n\nfunc (t *Tql) __Where() bool {\n\tif t.__Consume(\"where\") {\n\t\treturn t.__ParseFilterList()\n\t}\n\treturn t.__orderBy()\n}\n\nvar num_regex = `(\\d+)$`\n\nfunc (t *Tql) __Limit() bool {\n\tif t.__Consume(\"limit\") {\n\t\t_, limit := t.__ConsumeRegexp(num_regex)\n\t\tn, err := strconv.ParseInt(limit, 10, 64)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tif t.__Consume(\",\") {\n\t\t\tt.offset = n\n\t\t\t_, limit := t.__ConsumeRegexp(num_regex)\n\t\t\tn, err = strconv.ParseInt(limit, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tt.limit = n\n\t}\n\treturn t.__Offset()\n}\n\nfunc (t *Tql) __Offset() bool {\n\tif t.__Consume(\"offset\") {\n\t\tb, offset := t.__ConsumeRegexp(num_regex)\n\t\tif !b {\n\t\t\treturn false\n\t\t}\n\t\tn, err := strconv.ParseInt(offset, 10, 64)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tt.offset = n\n\t\treturn true\n\t}\n\treturn true\n}\n\nvar quoted_string_regex = `((?:\\'[^\\'\\n\\r]*\\')+)|((?:\"[^\"\\n\\r]*\")+)`\n\nfunc (t *Tql) __Value() (bool, Val) {\n\tif t.pos < len(t.tokens) {\n\t\ttoken := t.tokens[t.pos]\n\t\t\/\/ try int\n\t\ti, err := strconv.ParseInt(token, 10, 64)\n\t\tif err == nil {\n\t\t\tt.pos += 1\n\t\t\treturn true, Val{ValInt, i}\n\t\t}\n\t\t\/\/ try float\n\t\tf, err := strconv.ParseFloat(token, 64)\n\t\tif err == nil {\n\t\t\tt.pos += 1\n\t\t\treturn true, Val{ValFloat, f}\n\t\t}\n\t\t\/\/ try quote string\n\t\tb, val := t.__ConsumeRegexp(quoted_string_regex)\n\t\tif b {\n\t\t\tif t.tokens[t.pos-1][0] == '\\'' {\n\t\t\t\tval = strings.Replace(val, \"''\", \"'\", -1)\n\t\t\t} else {\n\t\t\t\tval = strings.Replace(val, `\"\"`, `\"`, -1)\n\t\t\t}\n\t\t\treturn true, Val{ValQuoteString, val}\n\t\t}\n\t\t\/\/ try bool\n\t\tb = t.__Consume(\"true\")\n\t\tif b {\n\t\t\treturn true, Val{ValBool, true}\n\t\t}\n\t\tb = t.__Consume(\"false\")\n\t\tif b {\n\t\t\treturn true, Val{ValBool, false}\n\t\t}\n\t\t\/\/ try null\n\t\tb = t.__Consume(\"null\")\n\t\tif b {\n\t\t\treturn true, Val{ValNull, nil}\n\t\t}\n\t}\n\treturn false, Val{}\n}\n\nfunc (t *Tql) __ValueList() (bool, Val) {\n\tvar vals []Val\n\tt.__Expect(\"(\")\n\tfor {\n\t\tif b, val := t.__Value(); b {\n\t\t\tvals = append(vals, val)\n\t\t} else {\n\t\t\treturn false, Val{}\n\t\t}\n\t\tif !t.__Consume(\",\") {\n\t\t\tbreak\n\t\t}\n\t}\n\tt.__Expect(\")\")\n\treturn true, Val{ValList, vals}\n}\n\nfunc (t *Tql) __orderBy() bool {\n    if t.__Consume(\"order\") {\n        if t.__Consume(\"by\") {\n            t.orderBy = t.__ExpectIdentifier()\n            if t.__Consume(\"asc\") {\n                t.order = 1\n            } else if t.__Consume(\"desc\") {\n                t.order = -1\n            }\n        } else {\n            panic(\"parsing order error\")\n        }\n    }\n    return t.__Limit()\n}\n\nvar condition_regex = `(<=|>=|!=|=|<|>|in)$`\n\nfunc (t *Tql) __ParseFilterList() bool {\n\tb, ident := t.__Identifier()\n\tif !b {\n\t\treturn b\n\t}\n\tb, op := t.__ConsumeRegexp(condition_regex)\n\tif !b {\n\t\treturn b\n\t}\n\tb, val := t.__Value()\n\tif !b && op == \"in\" {\n\t\tb, val = t.__ValueList()\n\t}\n\tif !b {\n\t\treturn b\n\t}\n\tt.conds = append(t.conds, Cond{ident, op, val})\n\tif t.__Consume(\"and\") {\n\t\treturn t.__ParseFilterList()\n\t}\n\treturn t.__orderBy()\n}\n<commit_msg>modify doc<commit_after>package tql\n\n\/*\n  Tql, Simple SQL-Like query language\n\n  BNF:\n  select <property> [, <property> ...] | *]\n    [from <from>]\n    [where <condition> [and <condition> ...]]\n    [order by <property> [asc|desc]]\n    [limit <num> offset <num> | limit <num>, <num>]\n\n  <condition> := <property> {< | <= | > | >= | = | != | in} <value>\n*\/\n\nimport (\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar tokenize_regex = `(?:\"[^\"\\n\\r]*\")+|(?:'[^'\\n\\r]*')+|<=|>=|!=|=|<|>|,|\\*|-?\\d+(?:\\.\\d+)?|\\w+(?:\\.\\w+)*|(?:\"[^\"\\s]+\")+|\\(|\\)|\\S+`\n\ntype Tql struct {\n\ttokens  []string\n\tquery   string\n\tpos     int\n\tprops   []string\n\tfrom    string\n\tconds   []Cond\n\tlimit   int64\n\toffset  int64\n\torderBy string\n\torder   int\n}\n\nconst (\n\tValString = iota\n\tValInt\n\tValFloat\n\tValQuoteString\n\tValBool\n\tValNull\n\tValReference\n\tValList\n)\n\ntype Val struct {\n\tvalType int\n\tval     interface{}\n}\n\ntype Cond struct {\n\tidentifier string\n\top         string\n\tval        Val\n}\n\nfunc NewTql(query string) *Tql {\n\tt := new(Tql)\n\tt.pos = 0\n\tt.query = strings.ToLower(query)\n\tt.limit = -1\n\tt.offset = -1\n    t.order = -1\n\tif re, err := regexp.Compile(tokenize_regex); err != nil {\n\t\treturn nil\n\t} else {\n\t\tt.tokens = re.FindAllString(t.query, -1)\n\t\tif len(t.tokens) <= 0 {\n\t\t\treturn nil\n\t\t}\n\t}\n\tt.__Select()\n\treturn t\n}\n\nfunc (t *Tql) __Expect(expect string) {\n\tif t.__Consume(expect) == false {\n\t\tpanic(\"token error\")\n\t}\n}\n\nfunc (t *Tql) __Consume(expect string) bool {\n\tif t.pos < len(t.tokens) {\n\t\tif t.tokens[t.pos] == expect {\n\t\t\tt.pos += 1\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (t *Tql) __ConsumeRegexp(regex string) (bool, string) {\n\tif t.pos < len(t.tokens) {\n\t\ttoken := t.tokens[t.pos]\n\t\tre, _ := regexp.Compile(regex)\n\t\tif re.MatchString(token) {\n\t\t\tt.pos += 1\n\t\t\treturn true, token\n\t\t}\n\t}\n\treturn false, \"\"\n}\n\n\/\/ consume a identifier an return\nvar identifier_regex = `(\\w+(?:\\.\\w+)*)$`\n\nfunc (t *Tql) __Identifier() (bool, string) {\n\tif b, ident := t.__ConsumeRegexp(identifier_regex); b {\n\t\treturn true, ident\n\t}\n\treturn false, \"\"\n}\n\nfunc (t *Tql) __ExpectIdentifier() string {\n\tif b, ident := t.__Identifier(); b {\n\t\treturn ident\n\t}\n\tpanic(\"identifier error\")\n}\n\nfunc (t *Tql) __Select() bool {\n\tt.__Expect(\"select\")\n\tif !t.__Consume(\"*\") {\n\t\tt.props = append(t.props, t.__ExpectIdentifier())\n\t\tfor t.__Consume(\",\") {\n\t\t\tt.props = append(t.props, t.__ExpectIdentifier())\n\t\t}\n\t} else {\n\t\tt.props = append(t.props, \"*\")\n\t}\n\treturn t.__From()\n}\n\nfunc (t *Tql) __From() bool {\n\tif t.__Consume(\"from\") {\n\t\tt.from = t.__ExpectIdentifier()\n\t} else {\n\t\treturn false\n\t}\n\treturn t.__Where()\n}\n\nfunc (t *Tql) __Where() bool {\n\tif t.__Consume(\"where\") {\n\t\treturn t.__ParseFilterList()\n\t}\n\treturn t.__orderBy()\n}\n\nvar num_regex = `(\\d+)$`\n\nfunc (t *Tql) __Limit() bool {\n\tif t.__Consume(\"limit\") {\n\t\t_, limit := t.__ConsumeRegexp(num_regex)\n\t\tn, err := strconv.ParseInt(limit, 10, 64)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tif t.__Consume(\",\") {\n\t\t\tt.offset = n\n\t\t\t_, limit := t.__ConsumeRegexp(num_regex)\n\t\t\tn, err = strconv.ParseInt(limit, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tt.limit = n\n\t}\n\treturn t.__Offset()\n}\n\nfunc (t *Tql) __Offset() bool {\n\tif t.__Consume(\"offset\") {\n\t\tb, offset := t.__ConsumeRegexp(num_regex)\n\t\tif !b {\n\t\t\treturn false\n\t\t}\n\t\tn, err := strconv.ParseInt(offset, 10, 64)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tt.offset = n\n\t\treturn true\n\t}\n\treturn true\n}\n\nvar quoted_string_regex = `((?:\\'[^\\'\\n\\r]*\\')+)|((?:\"[^\"\\n\\r]*\")+)`\n\nfunc (t *Tql) __Value() (bool, Val) {\n\tif t.pos < len(t.tokens) {\n\t\ttoken := t.tokens[t.pos]\n\t\t\/\/ try int\n\t\ti, err := strconv.ParseInt(token, 10, 64)\n\t\tif err == nil {\n\t\t\tt.pos += 1\n\t\t\treturn true, Val{ValInt, i}\n\t\t}\n\t\t\/\/ try float\n\t\tf, err := strconv.ParseFloat(token, 64)\n\t\tif err == nil {\n\t\t\tt.pos += 1\n\t\t\treturn true, Val{ValFloat, f}\n\t\t}\n\t\t\/\/ try quote string\n\t\tb, val := t.__ConsumeRegexp(quoted_string_regex)\n\t\tif b {\n\t\t\tif t.tokens[t.pos-1][0] == '\\'' {\n\t\t\t\tval = strings.Replace(val, \"''\", \"'\", -1)\n\t\t\t} else {\n\t\t\t\tval = strings.Replace(val, `\"\"`, `\"`, -1)\n\t\t\t}\n\t\t\treturn true, Val{ValQuoteString, val}\n\t\t}\n\t\t\/\/ try bool\n\t\tb = t.__Consume(\"true\")\n\t\tif b {\n\t\t\treturn true, Val{ValBool, true}\n\t\t}\n\t\tb = t.__Consume(\"false\")\n\t\tif b {\n\t\t\treturn true, Val{ValBool, false}\n\t\t}\n\t\t\/\/ try null\n\t\tb = t.__Consume(\"null\")\n\t\tif b {\n\t\t\treturn true, Val{ValNull, nil}\n\t\t}\n\t}\n\treturn false, Val{}\n}\n\nfunc (t *Tql) __ValueList() (bool, Val) {\n\tvar vals []Val\n\tt.__Expect(\"(\")\n\tfor {\n\t\tif b, val := t.__Value(); b {\n\t\t\tvals = append(vals, val)\n\t\t} else {\n\t\t\treturn false, Val{}\n\t\t}\n\t\tif !t.__Consume(\",\") {\n\t\t\tbreak\n\t\t}\n\t}\n\tt.__Expect(\")\")\n\treturn true, Val{ValList, vals}\n}\n\nfunc (t *Tql) __orderBy() bool {\n    if t.__Consume(\"order\") {\n        if t.__Consume(\"by\") {\n            t.orderBy = t.__ExpectIdentifier()\n            if t.__Consume(\"asc\") {\n                t.order = 1\n            } else if t.__Consume(\"desc\") {\n                t.order = -1\n            }\n        } else {\n            panic(\"parsing order error\")\n        }\n    }\n    return t.__Limit()\n}\n\nvar condition_regex = `(<=|>=|!=|=|<|>|in)$`\n\nfunc (t *Tql) __ParseFilterList() bool {\n\tb, ident := t.__Identifier()\n\tif !b {\n\t\treturn b\n\t}\n\tb, op := t.__ConsumeRegexp(condition_regex)\n\tif !b {\n\t\treturn b\n\t}\n\tb, val := t.__Value()\n\tif !b && op == \"in\" {\n\t\tb, val = t.__ValueList()\n\t}\n\tif !b {\n\t\treturn b\n\t}\n\tt.conds = append(t.conds, Cond{ident, op, val})\n\tif t.__Consume(\"and\") {\n\t\treturn t.__ParseFilterList()\n\t}\n\treturn t.__orderBy()\n}\n<|endoftext|>"}
{"text":"<commit_before>package store\n\nimport (\n\t\"crypto\/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com\/adamdecaf\/cert-manage\/tools\/file\"\n\t\"github.com\/adamdecaf\/cert-manage\/whitelist\"\n)\n\nvar (\n\tErrNoBackupMade = errors.New(\"unable to make backup of store\")\n\n\t\/\/ internal options\n\tdebug = len(os.Getenv(\"TRAVIS_OS_NAME\")) > 0 ||\n\t\tlen(os.Getenv(\"DEBUG\")) > 0 ||\n\t\tstrings.Contains(os.Getenv(\"GODEBUG\"), \"x509roots=1\")\n\n\tbackupDirPerms os.FileMode = 0744\n\n\t\/\/ Define a mapping between -app and the Store instance\n\tappStores = map[string]Store{\n\t\t\"chrome\":  ChromeStore(),\n\t\t\"firefox\": FirefoxStore(),\n\t\t\"java\":    JavaStore(),\n\t}\n)\n\n\/\/ Store represents a certificate store (often called 'pool') and has\n\/\/ operations on it which mutate the underlying state (e.g. a file or\n\/\/ directory).\ntype Store interface {\n\t\/\/ Backup will attempt to save a backup of the certificate store\n\t\/\/ on the local system\n\tBackup() error\n\n\t\/\/ List returns the currently trusted X509 certificates contained\n\t\/\/ within the cert store\n\tList() ([]*x509.Certificate, error)\n\n\t\/\/ Remove will distrust the certificate in the store\n\t\/\/\n\t\/\/ Note: This may not actually delete the certificate, but modify\n\t\/\/ the store such that the certificate is no longer trusted.\n\t\/\/ This is done when possible to limit the actual deletions to\n\t\/\/ preserve restore capabilities\n\tRemove(whitelist.Whitelist) error\n\n\t\/\/ Restore will bring the system back to it's previous state\n\t\/\/ if a backup exists, otherwise it will attempt to bring the\n\t\/\/ cert trust status to the system's default state\n\t\/\/\n\t\/\/ Optionally, this can take a specific filepath to use as the\n\t\/\/ restore point. This may not be supported on all stores.\n\t\/\/\n\t\/\/ Note: It is strongly advised that any additional certs installed\n\t\/\/ be verified are still properly installed and working after\n\t\/\/ Restore() is called.\n\tRestore(where string) error\n}\n\n\/\/ Platform returns a new instance of Store for the running os\/platform\nfunc Platform() Store {\n\treturn platform()\n}\n\n\/\/ ForApp returns a `Store` instance for the given app\nfunc ForApp(app string) (Store, error) {\n\ts, ok := appStores[strings.ToLower(app)]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"application '%s' not found\", app)\n\t}\n\treturn s, nil\n}\n\n\/\/ getCertManageDir returns the fs location (always creating first) where a specific\n\/\/ store can save files into. This path is recommended for backups\n\/\/\n\/\/ If `name` is an absolute fs reference then just ensure that directory is created\n\/\/ and has permissions setup properly.\nfunc getCertManageDir(name string) (string, error) {\n\tparent := getCertManageParentDir()\n\terr := os.MkdirAll(parent, os.ModeDir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\terr = os.Chmod(parent, backupDirPerms)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdir := filepath.Join(parent, name)\n\t\/\/ If `name` is actually an absolute fs reference then just ensure\n\t\/\/ it's created and owned properly, otherwise append whatever was\n\t\/\/ provided onto the parent dir.\n\tif filepath.IsAbs(name) {\n\t\ts, err := os.Stat(name)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif !s.IsDir() {\n\t\t\treturn \"\", fmt.Errorf(\"since %s exists and cannot be a file, should be a dir\", name)\n\t\t}\n\t\tdir = name\n\t}\n\n\t\/\/ Create the dir and set ownership\n\terr = os.MkdirAll(dir, os.ModeDir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\terr = os.Chmod(dir, backupDirPerms)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn dir, nil\n}\n\nfunc getCertManageParentDir() string {\n\tuhome := file.HomeDir()\n\tif uhome != \"\" {\n\t\t\/\/ Setup parent dir\n\t\tif runtime.GOOS == \"darwin\" {\n\t\t\treturn filepath.Join(uhome, \"\/Library\/cert-manage\")\n\t\t}\n\t\tif runtime.GOOS == \"linux\" || runtime.GOOS == \"windows\" {\n\t\t\treturn filepath.Join(uhome, \".cert-manage\")\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\/\/ getLatestBackup returns the \"biggest\" file or dir at a given path\n\/\/\n\/\/ This sorting is done by assuming filenames follow a pattern like\n\/\/ file-%d.ext where %d is a sortable timestamp and the filename follows\n\/\/ lexigraphical sorting. Results are sorted in descending order and the\n\/\/ first element (if exists) is returned\nfunc getLatestBackup(dir string) (string, error) {\n\tfis, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(fis) == 0 {\n\t\treturn \"\", nil\n\t}\n\n\t\/\/ get largest\n\tfile.SortFileInfos(fis)\n\tlatest := fis[len(fis)-1]\n\treturn filepath.Join(dir, latest.Name()), nil\n}\n<commit_msg>store: allow getCertManageDir to create child dirs<commit_after>package store\n\nimport (\n\t\"crypto\/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com\/adamdecaf\/cert-manage\/tools\/file\"\n\t\"github.com\/adamdecaf\/cert-manage\/whitelist\"\n)\n\nvar (\n\tErrNoBackupMade = errors.New(\"unable to make backup of store\")\n\n\t\/\/ internal options\n\tdebug = len(os.Getenv(\"TRAVIS_OS_NAME\")) > 0 ||\n\t\tlen(os.Getenv(\"DEBUG\")) > 0 ||\n\t\tstrings.Contains(os.Getenv(\"GODEBUG\"), \"x509roots=1\")\n\n\tbackupDirPerms os.FileMode = 0744\n\n\t\/\/ Define a mapping between -app and the Store instance\n\tappStores = map[string]Store{\n\t\t\"chrome\":  ChromeStore(),\n\t\t\"firefox\": FirefoxStore(),\n\t\t\"java\":    JavaStore(),\n\t}\n)\n\n\/\/ Store represents a certificate store (often called 'pool') and has\n\/\/ operations on it which mutate the underlying state (e.g. a file or\n\/\/ directory).\ntype Store interface {\n\t\/\/ Backup will attempt to save a backup of the certificate store\n\t\/\/ on the local system\n\tBackup() error\n\n\t\/\/ List returns the currently trusted X509 certificates contained\n\t\/\/ within the cert store\n\tList() ([]*x509.Certificate, error)\n\n\t\/\/ Remove will distrust the certificate in the store\n\t\/\/\n\t\/\/ Note: This may not actually delete the certificate, but modify\n\t\/\/ the store such that the certificate is no longer trusted.\n\t\/\/ This is done when possible to limit the actual deletions to\n\t\/\/ preserve restore capabilities\n\tRemove(whitelist.Whitelist) error\n\n\t\/\/ Restore will bring the system back to it's previous state\n\t\/\/ if a backup exists, otherwise it will attempt to bring the\n\t\/\/ cert trust status to the system's default state\n\t\/\/\n\t\/\/ Optionally, this can take a specific filepath to use as the\n\t\/\/ restore point. This may not be supported on all stores.\n\t\/\/\n\t\/\/ Note: It is strongly advised that any additional certs installed\n\t\/\/ be verified are still properly installed and working after\n\t\/\/ Restore() is called.\n\tRestore(where string) error\n}\n\n\/\/ Platform returns a new instance of Store for the running os\/platform\nfunc Platform() Store {\n\treturn platform()\n}\n\n\/\/ ForApp returns a `Store` instance for the given app\nfunc ForApp(app string) (Store, error) {\n\ts, ok := appStores[strings.ToLower(app)]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"application '%s' not found\", app)\n\t}\n\treturn s, nil\n}\n\n\/\/ getCertManageDir returns the fs location (always creating first) where a specific\n\/\/ store can save files into. This path is recommended for backups\n\/\/\n\/\/ If `name` is an absolute fs reference then just ensure that directory is created\n\/\/ and has permissions setup properly.\nfunc getCertManageDir(name string) (string, error) {\n\tparent := getCertManageParentDir()\n\terr := os.MkdirAll(parent, os.ModeDir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\terr = os.Chmod(parent, backupDirPerms)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tdir := filepath.Join(parent, name)\n\t\/\/ If `name` is actually an absolute fs reference then just ensure\n\t\/\/ it's created and owned properly, otherwise append whatever was\n\t\/\/ provided onto the parent dir.\n\tif filepath.IsAbs(name) {\n\t\ts, err := os.Stat(name)\n\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif s != nil && !s.IsDir() {\n\t\t\treturn \"\", fmt.Errorf(\"since %s exists and cannot be a file, should be a dir\", name)\n\t\t}\n\t\tdir = name\n\t}\n\n\t\/\/ Create the dir and set ownership\n\terr = os.MkdirAll(dir, os.ModeDir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\terr = os.Chmod(dir, backupDirPerms)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn dir, nil\n}\n\nfunc getCertManageParentDir() string {\n\tuhome := file.HomeDir()\n\tif uhome != \"\" {\n\t\t\/\/ Setup parent dir\n\t\tif runtime.GOOS == \"darwin\" {\n\t\t\treturn filepath.Join(uhome, \"\/Library\/cert-manage\")\n\t\t}\n\t\tif runtime.GOOS == \"linux\" || runtime.GOOS == \"windows\" {\n\t\t\treturn filepath.Join(uhome, \".cert-manage\")\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\/\/ getLatestBackup returns the \"biggest\" file or dir at a given path\n\/\/\n\/\/ This sorting is done by assuming filenames follow a pattern like\n\/\/ file-%d.ext where %d is a sortable timestamp and the filename follows\n\/\/ lexigraphical sorting. Results are sorted in descending order and the\n\/\/ first element (if exists) is returned\nfunc getLatestBackup(dir string) (string, error) {\n\tfis, err := ioutil.ReadDir(dir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(fis) == 0 {\n\t\treturn \"\", nil\n\t}\n\n\t\/\/ get largest\n\tfile.SortFileInfos(fis)\n\tlatest := fis[len(fis)-1]\n\treturn filepath.Join(dir, latest.Name()), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package store provides a distributed SQLite instance.\n\/\/\n\/\/ Distributed consensus is provided via the Raft algorithm.\npackage store\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/raft\"\n\t\"github.com\/hashicorp\/raft-boltdb\"\n\tsql \"github.com\/otoolep\/rqlite\/db\"\n)\n\nconst (\n\tretainSnapshotCount = 2\n\traftTimeout         = 10 * time.Second\n)\n\ntype command struct {\n\tTx      bool     `json:\"tx,omitempty\"`\n\tQueries []string `json:\"queries,omitempty\"`\n}\n\n\/\/ Store is a SQLite database, where all changes are made via Raft consensus.\ntype Store struct {\n\traftDir  string\n\traftBind string\n\n\tmu sync.Mutex\n\n\traft *raft.Raft \/\/ The consensus mechanism\n\tdb   *sql.DB    \/\/ The underlying SQLite store\n\n\tlogger *log.Logger\n\n\tSQLiteDB string\n}\n\n\/\/ New returns a new Store.\nfunc New(db *sql.DB, dir, bind string) *Store {\n\treturn &Store{\n\t\traftDir:  dir,\n\t\traftBind: bind,\n\t\tdb:       db,\n\t\tlogger:   log.New(os.Stderr, \"[store] \", log.LstdFlags),\n\t}\n}\n\n\/\/ Open opens the store. If enableSingle is set, and there are no existing peers,\n\/\/ then this node becomesthe first node, and therefore leader, of the cluster.\nfunc (s *Store) Open(enableSingle bool) error {\n\t\/\/ Setup Raft configuration.\n\tconfig := raft.DefaultConfig()\n\n\t\/\/ Check for any existing peers.\n\tpeers, err := readPeersJSON(filepath.Join(s.raftDir, \"peers.json\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Allow the node to entry single-mode, potentially electing itself, if\n\t\/\/ explicitly enabled and there is only 1 node in the cluster already.\n\tif enableSingle && len(peers) <= 1 {\n\t\ts.logger.Println(\"enabling single-node mode\")\n\t\tconfig.EnableSingleNode = true\n\t\tconfig.DisableBootstrapAfterElect = false\n\t}\n\n\t\/\/ Setup Raft communication.\n\taddr, err := net.ResolveTCPAddr(\"tcp\", s.raftBind)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttransport, err := raft.NewTCPTransport(s.raftBind, addr, 3, 10*time.Second, os.Stderr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Create peer storage.\n\tpeerStore := raft.NewJSONPeers(s.raftDir, transport)\n\n\t\/\/ Create the snapshot store. This allows the Raft to truncate the log.\n\tsnapshots, err := raft.NewFileSnapshotStore(s.raftDir, retainSnapshotCount, os.Stderr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"file snapshot store: %s\", err)\n\t}\n\n\t\/\/ Create the log store and stable store.\n\tlogStore, err := raftboltdb.NewBoltStore(filepath.Join(s.raftDir, \"raft.db\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"new bolt store: %s\", err)\n\t}\n\n\t\/\/ Instantiate the Raft systems.\n\tra, err := raft.NewRaft(config, (*fsm)(s), logStore, logStore, snapshots, peerStore, transport)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"new raft: %s\", err)\n\t}\n\ts.raft = ra\n\n\treturn nil\n}\n\nfunc (s *Store) Execute(queries []string, tx bool) ([]*sql.Result, error) {\n\tif s.raft.State() != raft.Leader {\n\t\treturn nil, fmt.Errorf(\"not leader\")\n\t}\n\n\tc := &command{\n\t\tTx:      tx,\n\t\tQueries: queries,\n\t}\n\tb, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf := s.raft.Apply(b, raftTimeout)\n\tif err, ok := f.(error); ok {\n\t\treturn nil, err\n\t}\n\n\treturn nil, nil\n}\n\nfunc (s *Store) Query(queries []string, tx bool) ([]*sql.Rows, error) {\n\t\/\/ Go straight to the local database. Optionally check if leader. Hard way?\n\treturn nil, nil\n}\n\n\/\/ Join joins a node, located at addr, to this store. The node must be ready to\n\/\/ respond to Raft communications at that address.\nfunc (s *Store) Join(addr string) error {\n\ts.logger.Printf(\"received join request for remote node as %s\", addr)\n\n\tf := s.raft.AddPeer(addr)\n\tif f.Error() != nil {\n\t\treturn f.Error()\n\t}\n\ts.logger.Printf(\"node at %s joined successfully\", addr)\n\treturn nil\n}\n\ntype fsm Store\n\n\/\/ Apply applies a Raft log entry to the database.\nfunc (f *fsm) Apply(l *raft.Log) interface{} {\n\tvar c command\n\tif err := json.Unmarshal(l.Data, &c); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to unmarshal command: %s\", err.Error()))\n\t}\n\n\tr, err := f.db.Execute(c.Queries, c.Tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn r\n}\n\n\/\/ Snapshot returns a snapshot of the database.\nfunc (f *fsm) Snapshot() (raft.FSMSnapshot, error) {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\treturn nil, nil\n}\n\n\/\/ Restore restores the database to a previous state.\nfunc (f *fsm) Restore(rc io.ReadCloser) error {\n\treturn nil\n}\n\ntype fsmSnapshot struct {\n}\n\nfunc (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error {\n\treturn nil\n}\n\nfunc (f *fsmSnapshot) Release() {}\n\nfunc readPeersJSON(path string) ([]string, error) {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\tif len(b) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tvar peers []string\n\tdec := json.NewDecoder(bytes.NewReader(b))\n\tif err := dec.Decode(&peers); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn peers, nil\n}\n<commit_msg>Start threading ApplyFuture for Execute response<commit_after>\/\/ Package store provides a distributed SQLite instance.\n\/\/\n\/\/ Distributed consensus is provided via the Raft algorithm.\npackage store\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/raft\"\n\t\"github.com\/hashicorp\/raft-boltdb\"\n\tsql \"github.com\/otoolep\/rqlite\/db\"\n)\n\nconst (\n\tretainSnapshotCount = 2\n\traftTimeout         = 10 * time.Second\n)\n\ntype command struct {\n\tTx      bool     `json:\"tx,omitempty\"`\n\tQueries []string `json:\"queries,omitempty\"`\n}\n\n\/\/ Store is a SQLite database, where all changes are made via Raft consensus.\ntype Store struct {\n\traftDir  string\n\traftBind string\n\n\tmu sync.Mutex\n\n\traft *raft.Raft \/\/ The consensus mechanism\n\tdb   *sql.DB    \/\/ The underlying SQLite store\n\n\tlogger *log.Logger\n\n\tSQLiteDB string\n}\n\n\/\/ New returns a new Store.\nfunc New(db *sql.DB, dir, bind string) *Store {\n\treturn &Store{\n\t\traftDir:  dir,\n\t\traftBind: bind,\n\t\tdb:       db,\n\t\tlogger:   log.New(os.Stderr, \"[store] \", log.LstdFlags),\n\t}\n}\n\n\/\/ Open opens the store. If enableSingle is set, and there are no existing peers,\n\/\/ then this node becomesthe first node, and therefore leader, of the cluster.\nfunc (s *Store) Open(enableSingle bool) error {\n\t\/\/ Setup Raft configuration.\n\tconfig := raft.DefaultConfig()\n\n\t\/\/ Check for any existing peers.\n\tpeers, err := readPeersJSON(filepath.Join(s.raftDir, \"peers.json\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Allow the node to entry single-mode, potentially electing itself, if\n\t\/\/ explicitly enabled and there is only 1 node in the cluster already.\n\tif enableSingle && len(peers) <= 1 {\n\t\ts.logger.Println(\"enabling single-node mode\")\n\t\tconfig.EnableSingleNode = true\n\t\tconfig.DisableBootstrapAfterElect = false\n\t}\n\n\t\/\/ Setup Raft communication.\n\taddr, err := net.ResolveTCPAddr(\"tcp\", s.raftBind)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttransport, err := raft.NewTCPTransport(s.raftBind, addr, 3, 10*time.Second, os.Stderr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Create peer storage.\n\tpeerStore := raft.NewJSONPeers(s.raftDir, transport)\n\n\t\/\/ Create the snapshot store. This allows the Raft to truncate the log.\n\tsnapshots, err := raft.NewFileSnapshotStore(s.raftDir, retainSnapshotCount, os.Stderr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"file snapshot store: %s\", err)\n\t}\n\n\t\/\/ Create the log store and stable store.\n\tlogStore, err := raftboltdb.NewBoltStore(filepath.Join(s.raftDir, \"raft.db\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"new bolt store: %s\", err)\n\t}\n\n\t\/\/ Instantiate the Raft systems.\n\tra, err := raft.NewRaft(config, (*fsm)(s), logStore, logStore, snapshots, peerStore, transport)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"new raft: %s\", err)\n\t}\n\ts.raft = ra\n\n\treturn nil\n}\n\nfunc (s *Store) Execute(queries []string, tx bool) ([]*sql.Result, error) {\n\tif s.raft.State() != raft.Leader {\n\t\treturn nil, fmt.Errorf(\"not leader\")\n\t}\n\n\tc := &command{\n\t\tTx:      tx,\n\t\tQueries: queries,\n\t}\n\tb, err := json.Marshal(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr := s.raft.Apply(b, raftTimeout).(*fsmResponse)\n\treturn r.Response().([]*sql.Result), r.Error()\n}\n\nfunc (s *Store) Query(queries []string, tx bool) ([]*sql.Rows, error) {\n\t\/\/ Go straight to the local database. Optionally check if leader. Hard way?\n\treturn nil, nil\n}\n\n\/\/ Join joins a node, located at addr, to this store. The node must be ready to\n\/\/ respond to Raft communications at that address.\nfunc (s *Store) Join(addr string) error {\n\ts.logger.Printf(\"received join request for remote node as %s\", addr)\n\n\tf := s.raft.AddPeer(addr)\n\tif f.Error() != nil {\n\t\treturn f.Error()\n\t}\n\ts.logger.Printf(\"node at %s joined successfully\", addr)\n\treturn nil\n}\n\ntype fsm Store\n\ntype fsmResponse struct {\n\tresults []*sql.Result\n\terror error\n\tindex uint64\n}\n\nfunc (f *fsmResponse) Response() interface{} {\n\treturn f.results\n}\n\nfunc (f *fsmResponse) Index() uint64 {\n\treturn f.index\n}\n\nfunc (f *fsmResponse) Error() error {\n\treturn f.error\n}\n\n\/\/ Apply applies a Raft log entry to the database.\nfunc (f *fsm) Apply(l *raft.Log) interface{} {\n\tvar c command\n\tif err := json.Unmarshal(l.Data, &c); err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to unmarshal command: %s\", err.Error()))\n\t}\n\n\tr, err := f.db.Execute(c.Queries, c.Tx)\n\treturn &fsmResponse{\n\t\tresults: r,\n\t\terror: err,\n\t\tindex: 1,\n\t}\n}\n\n\/\/ Snapshot returns a snapshot of the database.\nfunc (f *fsm) Snapshot() (raft.FSMSnapshot, error) {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\n\treturn nil, nil\n}\n\n\/\/ Restore restores the database to a previous state.\nfunc (f *fsm) Restore(rc io.ReadCloser) error {\n\treturn nil\n}\n\ntype fsmSnapshot struct {\n}\n\nfunc (f *fsmSnapshot) Persist(sink raft.SnapshotSink) error {\n\treturn nil\n}\n\nfunc (f *fsmSnapshot) Release() {}\n\nfunc readPeersJSON(path string) ([]string, error) {\n\tb, err := ioutil.ReadFile(path)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\tif len(b) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tvar peers []string\n\tdec := json.NewDecoder(bytes.NewReader(b))\n\tif err := dec.Decode(&peers); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn peers, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package store\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"path\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\tetcdErr \"github.com\/coreos\/etcd\/error\"\n)\n\ntype Store struct {\n\tRoot       *Node\n\tWatcherHub *watcherHub\n\tIndex      uint64\n\tTerm       uint64\n\tStats      *Stats\n\tworldLock  sync.RWMutex \/\/ stop the world lock. Used to do snapshot\n}\n\nfunc New() *Store {\n\ts := new(Store)\n\ts.Root = newDir(\"\/\", 0, 0, nil, \"\", Permanent)\n\ts.Stats = newStats()\n\ts.WatcherHub = newWatchHub(1000)\n\n\treturn s\n}\n\nfunc (s *Store) Get(nodePath string, recursive, sorted bool, index uint64, term uint64) (*Event, error) {\n\ts.worldLock.RLock()\n\tdefer s.worldLock.RUnlock()\n\n\tnodePath = path.Clean(path.Join(\"\/\", nodePath))\n\n\tn, err := s.internalGet(nodePath, index, term)\n\n\tif err != nil {\n\t\ts.Stats.Inc(GetFail)\n\t\treturn nil, err\n\t}\n\n\te := newEvent(Get, nodePath, index, term)\n\n\tif n.IsDir() { \/\/ node is dir\n\t\te.Dir = true\n\n\t\tchildren, _ := n.List()\n\t\te.KVPairs = make([]KeyValuePair, len(children))\n\n\t\t\/\/ we do not use the index in the children slice directly\n\t\t\/\/ we need to skip the hidden one\n\t\ti := 0\n\n\t\tfor _, child := range children {\n\n\t\t\tif child.IsHidden() { \/\/ get will not list hidden node\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\te.KVPairs[i] = child.Pair(recursive, sorted)\n\n\t\t\ti++\n\t\t}\n\n\t\t\/\/ eliminate hidden nodes\n\t\te.KVPairs = e.KVPairs[:i]\n\n\t\trootPairs := KeyValuePair{\n\t\t\tKVPairs: e.KVPairs,\n\t\t}\n\n\t\tif sorted {\n\t\t\tsort.Sort(rootPairs)\n\t\t}\n\n\t} else { \/\/ node is file\n\t\te.Value = n.Value\n\t}\n\n\tif n.ExpireTime.Sub(Permanent) != 0 {\n\t\te.Expiration = &n.ExpireTime\n\t\te.TTL = int64(n.ExpireTime.Sub(time.Now())\/time.Second) + 1\n\t}\n\n\ts.Stats.Inc(GetSuccess)\n\n\treturn e, nil\n}\n\n\/\/ Create function creates the Node at nodePath. Create will help to create intermediate directories with no ttl.\n\/\/ If the node has already existed, create will fail.\n\/\/ If any node on the path is a file, create will fail.\nfunc (s *Store) Create(nodePath string, value string, expireTime time.Time, index uint64, term uint64) (*Event, error) {\n\ts.worldLock.RLock()\n\tdefer s.worldLock.RUnlock()\n\n\tnodePath = path.Clean(path.Join(\"\/\", nodePath))\n\n\t\/\/ make sure we can create the node\n\t_, err := s.internalGet(nodePath, index, term)\n\n\tif err == nil { \/\/ key already exists\n\t\ts.Stats.Inc(SetFail)\n\t\treturn nil, etcdErr.NewError(etcdErr.EcodeNodeExist, nodePath)\n\t}\n\n\tetcdError, _ := err.(etcdErr.Error)\n\n\tif etcdError.ErrorCode == 104 { \/\/ we cannot create the key due to meet a file while walking\n\t\ts.Stats.Inc(SetFail)\n\t\treturn nil, err\n\t}\n\n\tdir, _ := path.Split(nodePath)\n\n\t\/\/ walk through the nodePath, create dirs and get the last directory node\n\td, err := s.walk(dir, s.checkDir)\n\n\tif err != nil {\n\t\ts.Stats.Inc(SetFail)\n\t\treturn nil, err\n\t}\n\n\te := newEvent(Create, nodePath, s.Index, s.Term)\n\n\tvar n *Node\n\n\tif len(value) != 0 { \/\/ create file\n\t\te.Value = value\n\n\t\tn = newFile(nodePath, value, s.Index, s.Term, d, \"\", expireTime)\n\n\t} else { \/\/ create directory\n\t\te.Dir = true\n\n\t\tn = newDir(nodePath, s.Index, s.Term, d, \"\", expireTime)\n\n\t}\n\n\terr = d.Add(n)\n\n\tif err != nil {\n\t\ts.Stats.Inc(SetFail)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Node with TTL\n\tif expireTime.Sub(Permanent) != 0 {\n\t\tn.Expire()\n\t\te.Expiration = &n.ExpireTime\n\t\te.TTL = int64(expireTime.Sub(time.Now())\/time.Second) + 1\n\t}\n\n\ts.WatcherHub.notify(e)\n\ts.Stats.Inc(SetSuccess)\n\treturn e, nil\n}\n\n\/\/ Update function updates the value\/ttl of the node.\n\/\/ If the node is a file, the value and the ttl can be updated.\n\/\/ If the node is a directory, only the ttl can be updated.\nfunc (s *Store) Update(nodePath string, value string, expireTime time.Time, index uint64, term uint64) (*Event, error) {\n\ts.worldLock.RLock()\n\tdefer s.worldLock.RUnlock()\n\n\tn, err := s.internalGet(nodePath, index, term)\n\n\tif err != nil { \/\/ if the node does not exist, return error\n\t\ts.Stats.Inc(UpdateFail)\n\t\treturn nil, err\n\t}\n\n\te := newEvent(Update, nodePath, s.Index, s.Term)\n\n\tif n.IsDir() { \/\/ if the node is a directory, we can only update ttl\n\n\t\tif len(value) != 0 {\n\t\t\ts.Stats.Inc(UpdateFail)\n\t\t\treturn nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath)\n\t\t}\n\n\t} else { \/\/ if the node is a file, we can update value and ttl\n\t\te.PrevValue = n.Value\n\n\t\tif len(value) != 0 {\n\t\t\te.Value = value\n\t\t}\n\n\t\tn.Write(value, index, term)\n\t}\n\n\t\/\/ update ttl\n\tif !n.IsPermanent() {\n\t\tn.stopExpire <- true\n\t}\n\n\tif expireTime.Sub(Permanent) != 0 {\n\t\tn.ExpireTime = expireTime\n\t\tn.Expire()\n\t\te.Expiration = &n.ExpireTime\n\t\te.TTL = int64(expireTime.Sub(time.Now())\/time.Second) + 1\n\t}\n\n\ts.WatcherHub.notify(e)\n\ts.Stats.Inc(UpdateSuccess)\n\treturn e, nil\n}\n\nfunc (s *Store) TestAndSet(nodePath string, prevValue string, prevIndex uint64,\n\tvalue string, expireTime time.Time, index uint64, term uint64) (*Event, error) {\n\n\ts.worldLock.RLock()\n\tdefer s.worldLock.RUnlock()\n\n\tf, err := s.internalGet(nodePath, index, term)\n\n\tif err != nil {\n\t\ts.Stats.Inc(TestAndSetFail)\n\t\treturn nil, err\n\t}\n\n\tif f.IsDir() { \/\/ can only test and set file\n\t\ts.Stats.Inc(TestAndSetFail)\n\t\treturn nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath)\n\t}\n\n\tif f.Value == prevValue || f.ModifiedIndex == prevIndex {\n\t\t\/\/ if test succeed, write the value\n\t\te := newEvent(TestAndSet, nodePath, index, term)\n\t\te.PrevValue = f.Value\n\t\te.Value = value\n\t\tf.Write(value, index, term)\n\n\t\ts.WatcherHub.notify(e)\n\t\ts.Stats.Inc(TestAndSetSuccess)\n\t\treturn e, nil\n\t}\n\n\tcause := fmt.Sprintf(\"[%v != %v] [%v != %v]\", prevValue, f.Value, prevIndex, f.ModifiedIndex)\n\ts.Stats.Inc(TestAndSetFail)\n\treturn nil, etcdErr.NewError(etcdErr.EcodeTestFailed, cause)\n}\n\n\/\/ Delete function deletes the node at the given path.\n\/\/ If the node is a directory, recursive must be true to delete it.\nfunc (s *Store) Delete(nodePath string, recursive bool, index uint64, term uint64) (*Event, error) {\n\ts.worldLock.RLock()\n\tdefer s.worldLock.RUnlock()\n\n\tn, err := s.internalGet(nodePath, index, term)\n\n\tif err != nil { \/\/ if the node does not exist, return error\n\t\ts.Stats.Inc(DeleteFail)\n\t\treturn nil, err\n\t}\n\n\te := newEvent(Delete, nodePath, index, term)\n\n\tif n.IsDir() {\n\t\te.Dir = true\n\t} else {\n\t\te.PrevValue = n.Value\n\t}\n\n\tcallback := func(path string) { \/\/ notify function\n\t\ts.WatcherHub.notifyWithPath(e, path, true)\n\t}\n\n\terr = n.Remove(recursive, callback)\n\n\tif err != nil {\n\t\ts.Stats.Inc(DeleteFail)\n\t\treturn nil, err\n\t}\n\n\ts.WatcherHub.notify(e)\n\ts.Stats.Inc(DeleteSuccess)\n\n\treturn e, nil\n}\n\nfunc (s *Store) Watch(prefix string, recursive bool, sinceIndex uint64, index uint64, term uint64) (<-chan *Event, error) {\n\ts.worldLock.RLock()\n\tdefer s.worldLock.RUnlock()\n\n\ts.Index, s.Term = index, term\n\n\tif sinceIndex == 0 {\n\t\treturn s.WatcherHub.watch(prefix, recursive, index+1)\n\t}\n\n\treturn s.WatcherHub.watch(prefix, recursive, sinceIndex)\n}\n\n\/\/ walk function walks all the nodePath and apply the walkFunc on each directory\nfunc (s *Store) walk(nodePath string, walkFunc func(prev *Node, component string) (*Node, error)) (*Node, error) {\n\tcomponents := strings.Split(nodePath, \"\/\")\n\n\tcurr := s.Root\n\n\tvar err error\n\tfor i := 1; i < len(components); i++ {\n\t\tif len(components[i]) == 0 { \/\/ ignore empty string\n\t\t\treturn curr, nil\n\t\t}\n\n\t\tcurr, err = walkFunc(curr, components[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\n\treturn curr, nil\n}\n\n\/\/ InternalGet function get the node of the given nodePath.\nfunc (s *Store) internalGet(nodePath string, index uint64, term uint64) (*Node, error) {\n\tnodePath = path.Clean(path.Join(\"\/\", nodePath))\n\n\t\/\/ update file system known index and term\n\ts.Index, s.Term = index, term\n\n\twalkFunc := func(parent *Node, name string) (*Node, error) {\n\n\t\tif !parent.IsDir() {\n\t\t\treturn nil, etcdErr.NewError(etcdErr.EcodeNotDir, parent.Path)\n\t\t}\n\n\t\tchild, ok := parent.Children[name]\n\t\tif ok {\n\t\t\treturn child, nil\n\t\t}\n\n\t\treturn nil, etcdErr.NewError(etcdErr.EcodeKeyNotFound, path.Join(parent.Path, name))\n\t}\n\n\tf, err := s.walk(nodePath, walkFunc)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f, nil\n}\n\n\/\/ checkDir function will check whether the component is a directory under parent node.\n\/\/ If it is a directory, this function will return the pointer to that node.\n\/\/ If it does not exist, this function will create a new directory and return the pointer to that node.\n\/\/ If it is a file, this function will return error.\nfunc (s *Store) checkDir(parent *Node, dirName string) (*Node, error) {\n\tsubDir, ok := parent.Children[dirName]\n\n\tif ok {\n\t\treturn subDir, nil\n\t}\n\n\tn := newDir(path.Join(parent.Path, dirName), s.Index, s.Term, parent, parent.ACL, Permanent)\n\n\tparent.Children[dirName] = n\n\n\treturn n, nil\n}\n\n\/\/ Save function saves the static state of the store system.\n\/\/ Save function will not be able to save the state of watchers.\n\/\/ Save function will not save the parent field of the node. Or there will\n\/\/ be cyclic dependencies issue for the json package.\nfunc (s *Store) Save() ([]byte, error) {\n\ts.worldLock.Lock()\n\n\tclonedStore := New()\n\tclonedStore.Root = s.Root.Clone()\n\tclonedStore.WatcherHub = s.WatcherHub.clone()\n\tclonedStore.Index = s.Index\n\tclonedStore.Term = s.Term\n\tclonedStore.Stats = s.Stats.clone()\n\n\ts.worldLock.Unlock()\n\n\tb, err := json.Marshal(clonedStore)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}\n\n\/\/ recovery function recovery the store system from a static state.\n\/\/ It needs to recovery the parent field of the nodes.\n\/\/ It needs to delete the expired nodes since the saved time and also\n\/\/ need to create monitor go routines.\nfunc (s *Store) Recovery(state []byte) error {\n\ts.worldLock.Lock()\n\tdefer s.worldLock.Unlock()\n\terr := json.Unmarshal(state, s)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.Root.recoverAndclean()\n\treturn nil\n}\n\nfunc (s *Store) JsonStats() []byte {\n\ts.Stats.Watchers = uint64(s.WatcherHub.count)\n\treturn s.Stats.toJson()\n}\n<commit_msg>minor clean up<commit_after>package store\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"path\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\tetcdErr \"github.com\/coreos\/etcd\/error\"\n)\n\ntype Store struct {\n\tRoot       *Node\n\tWatcherHub *watcherHub\n\tIndex      uint64\n\tTerm       uint64\n\tStats      *Stats\n\tworldLock  sync.RWMutex \/\/ stop the world lock. Used to do snapshot\n}\n\nfunc New() *Store {\n\ts := new(Store)\n\ts.Root = newDir(\"\/\", 0, 0, nil, \"\", Permanent)\n\ts.Stats = newStats()\n\ts.WatcherHub = newWatchHub(1000)\n\n\treturn s\n}\n\nfunc (s *Store) Get(nodePath string, recursive, sorted bool, index uint64, term uint64) (*Event, error) {\n\ts.worldLock.RLock()\n\tdefer s.worldLock.RUnlock()\n\n\tnodePath = path.Clean(path.Join(\"\/\", nodePath))\n\n\tn, err := s.internalGet(nodePath, index, term)\n\n\tif err != nil {\n\t\ts.Stats.Inc(GetFail)\n\t\treturn nil, err\n\t}\n\n\te := newEvent(Get, nodePath, index, term)\n\n\tif n.IsDir() { \/\/ node is dir\n\t\te.Dir = true\n\n\t\tchildren, _ := n.List()\n\t\te.KVPairs = make([]KeyValuePair, len(children))\n\n\t\t\/\/ we do not use the index in the children slice directly\n\t\t\/\/ we need to skip the hidden one\n\t\ti := 0\n\n\t\tfor _, child := range children {\n\n\t\t\tif child.IsHidden() { \/\/ get will not list hidden node\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\te.KVPairs[i] = child.Pair(recursive, sorted)\n\n\t\t\ti++\n\t\t}\n\n\t\t\/\/ eliminate hidden nodes\n\t\te.KVPairs = e.KVPairs[:i]\n\n\t\trootPairs := KeyValuePair{\n\t\t\tKVPairs: e.KVPairs,\n\t\t}\n\n\t\tif sorted {\n\t\t\tsort.Sort(rootPairs)\n\t\t}\n\n\t} else { \/\/ node is file\n\t\te.Value = n.Value\n\t}\n\n\tif n.ExpireTime.Sub(Permanent) != 0 {\n\t\te.Expiration = &n.ExpireTime\n\t\te.TTL = int64(n.ExpireTime.Sub(time.Now())\/time.Second) + 1\n\t}\n\n\ts.Stats.Inc(GetSuccess)\n\n\treturn e, nil\n}\n\n\/\/ Create function creates the Node at nodePath. Create will help to create intermediate directories with no ttl.\n\/\/ If the node has already existed, create will fail.\n\/\/ If any node on the path is a file, create will fail.\nfunc (s *Store) Create(nodePath string, value string, expireTime time.Time, index uint64, term uint64) (*Event, error) {\n\ts.worldLock.RLock()\n\tdefer s.worldLock.RUnlock()\n\n\tnodePath = path.Clean(path.Join(\"\/\", nodePath))\n\n\t\/\/ make sure we can create the node\n\t_, err := s.internalGet(nodePath, index, term)\n\n\tif err == nil { \/\/ key already exists\n\t\ts.Stats.Inc(SetFail)\n\t\treturn nil, etcdErr.NewError(etcdErr.EcodeNodeExist, nodePath)\n\t}\n\n\tetcdError, _ := err.(etcdErr.Error)\n\n\tif etcdError.ErrorCode == 104 { \/\/ we cannot create the key due to meet a file while walking\n\t\ts.Stats.Inc(SetFail)\n\t\treturn nil, err\n\t}\n\n\tdir, _ := path.Split(nodePath)\n\n\t\/\/ walk through the nodePath, create dirs and get the last directory node\n\td, err := s.walk(dir, s.checkDir)\n\n\tif err != nil {\n\t\ts.Stats.Inc(SetFail)\n\t\treturn nil, err\n\t}\n\n\te := newEvent(Create, nodePath, s.Index, s.Term)\n\n\tvar n *Node\n\n\tif len(value) != 0 { \/\/ create file\n\t\te.Value = value\n\n\t\tn = newFile(nodePath, value, s.Index, s.Term, d, \"\", expireTime)\n\n\t} else { \/\/ create directory\n\t\te.Dir = true\n\n\t\tn = newDir(nodePath, s.Index, s.Term, d, \"\", expireTime)\n\n\t}\n\n\terr = d.Add(n)\n\n\tif err != nil {\n\t\ts.Stats.Inc(SetFail)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Node with TTL\n\tif expireTime.Sub(Permanent) != 0 {\n\t\tn.Expire()\n\t\te.Expiration = &n.ExpireTime\n\t\te.TTL = int64(expireTime.Sub(time.Now())\/time.Second) + 1\n\t}\n\n\ts.WatcherHub.notify(e)\n\ts.Stats.Inc(SetSuccess)\n\treturn e, nil\n}\n\n\/\/ Update function updates the value\/ttl of the node.\n\/\/ If the node is a file, the value and the ttl can be updated.\n\/\/ If the node is a directory, only the ttl can be updated.\nfunc (s *Store) Update(nodePath string, value string, expireTime time.Time, index uint64, term uint64) (*Event, error) {\n\ts.worldLock.RLock()\n\tdefer s.worldLock.RUnlock()\n\n\tn, err := s.internalGet(nodePath, index, term)\n\n\tif err != nil { \/\/ if the node does not exist, return error\n\t\ts.Stats.Inc(UpdateFail)\n\t\treturn nil, err\n\t}\n\n\te := newEvent(Update, nodePath, s.Index, s.Term)\n\n\tif n.IsDir() { \/\/ if the node is a directory, we can only update ttl\n\n\t\tif len(value) != 0 {\n\t\t\ts.Stats.Inc(UpdateFail)\n\t\t\treturn nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath)\n\t\t}\n\n\t} else { \/\/ if the node is a file, we can update value and ttl\n\t\te.PrevValue = n.Value\n\n\t\tif len(value) != 0 {\n\t\t\te.Value = value\n\t\t}\n\n\t\tn.Write(value, index, term)\n\t}\n\n\t\/\/ update ttl\n\tif !n.IsPermanent() {\n\t\tn.stopExpire <- true\n\t}\n\n\tif expireTime.Sub(Permanent) != 0 {\n\t\tn.ExpireTime = expireTime\n\t\tn.Expire()\n\t\te.Expiration = &n.ExpireTime\n\t\te.TTL = int64(expireTime.Sub(time.Now())\/time.Second) + 1\n\t}\n\n\ts.WatcherHub.notify(e)\n\ts.Stats.Inc(UpdateSuccess)\n\treturn e, nil\n}\n\nfunc (s *Store) TestAndSet(nodePath string, prevValue string, prevIndex uint64,\n\tvalue string, expireTime time.Time, index uint64, term uint64) (*Event, error) {\n\n\ts.worldLock.RLock()\n\tdefer s.worldLock.RUnlock()\n\n\tf, err := s.internalGet(nodePath, index, term)\n\n\tif err != nil {\n\t\ts.Stats.Inc(TestAndSetFail)\n\t\treturn nil, err\n\t}\n\n\tif f.IsDir() { \/\/ can only test and set file\n\t\ts.Stats.Inc(TestAndSetFail)\n\t\treturn nil, etcdErr.NewError(etcdErr.EcodeNotFile, nodePath)\n\t}\n\n\tif f.Value == prevValue || f.ModifiedIndex == prevIndex {\n\t\t\/\/ if test succeed, write the value\n\t\te := newEvent(TestAndSet, nodePath, index, term)\n\t\te.PrevValue = f.Value\n\t\te.Value = value\n\t\tf.Write(value, index, term)\n\n\t\ts.WatcherHub.notify(e)\n\t\ts.Stats.Inc(TestAndSetSuccess)\n\t\treturn e, nil\n\t}\n\n\tcause := fmt.Sprintf(\"[%v != %v] [%v != %v]\", prevValue, f.Value, prevIndex, f.ModifiedIndex)\n\ts.Stats.Inc(TestAndSetFail)\n\treturn nil, etcdErr.NewError(etcdErr.EcodeTestFailed, cause)\n}\n\n\/\/ Delete function deletes the node at the given path.\n\/\/ If the node is a directory, recursive must be true to delete it.\nfunc (s *Store) Delete(nodePath string, recursive bool, index uint64, term uint64) (*Event, error) {\n\ts.worldLock.RLock()\n\tdefer s.worldLock.RUnlock()\n\n\tn, err := s.internalGet(nodePath, index, term)\n\n\tif err != nil { \/\/ if the node does not exist, return error\n\t\ts.Stats.Inc(DeleteFail)\n\t\treturn nil, err\n\t}\n\n\te := newEvent(Delete, nodePath, index, term)\n\n\tif n.IsDir() {\n\t\te.Dir = true\n\t} else {\n\t\te.PrevValue = n.Value\n\t}\n\n\tcallback := func(path string) { \/\/ notify function\n\t\ts.WatcherHub.notifyWithPath(e, path, true)\n\t}\n\n\terr = n.Remove(recursive, callback)\n\n\tif err != nil {\n\t\ts.Stats.Inc(DeleteFail)\n\t\treturn nil, err\n\t}\n\n\ts.WatcherHub.notify(e)\n\ts.Stats.Inc(DeleteSuccess)\n\n\treturn e, nil\n}\n\nfunc (s *Store) Watch(prefix string, recursive bool, sinceIndex uint64, index uint64, term uint64) (<-chan *Event, error) {\n\ts.worldLock.RLock()\n\tdefer s.worldLock.RUnlock()\n\n\ts.Index, s.Term = index, term\n\n\tif sinceIndex == 0 {\n\t\treturn s.WatcherHub.watch(prefix, recursive, index+1)\n\t}\n\n\treturn s.WatcherHub.watch(prefix, recursive, sinceIndex)\n}\n\n\/\/ walk function walks all the nodePath and apply the walkFunc on each directory\nfunc (s *Store) walk(nodePath string, walkFunc func(prev *Node, component string) (*Node, error)) (*Node, error) {\n\tcomponents := strings.Split(nodePath, \"\/\")\n\n\tcurr := s.Root\n\n\tvar err error\n\tfor i := 1; i < len(components); i++ {\n\t\tif len(components[i]) == 0 { \/\/ ignore empty string\n\t\t\treturn curr, nil\n\t\t}\n\n\t\tcurr, err = walkFunc(curr, components[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t}\n\n\treturn curr, nil\n}\n\n\/\/ InternalGet function get the node of the given nodePath.\nfunc (s *Store) internalGet(nodePath string, index uint64, term uint64) (*Node, error) {\n\tnodePath = path.Clean(path.Join(\"\/\", nodePath))\n\n\t\/\/ update file system known index and term\n\ts.Index, s.Term = index, term\n\n\twalkFunc := func(parent *Node, name string) (*Node, error) {\n\n\t\tif !parent.IsDir() {\n\t\t\treturn nil, etcdErr.NewError(etcdErr.EcodeNotDir, parent.Path)\n\t\t}\n\n\t\tchild, ok := parent.Children[name]\n\t\tif ok {\n\t\t\treturn child, nil\n\t\t}\n\n\t\treturn nil, etcdErr.NewError(etcdErr.EcodeKeyNotFound, path.Join(parent.Path, name))\n\t}\n\n\tf, err := s.walk(nodePath, walkFunc)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f, nil\n}\n\n\/\/ checkDir function will check whether the component is a directory under parent node.\n\/\/ If it is a directory, this function will return the pointer to that node.\n\/\/ If it does not exist, this function will create a new directory and return the pointer to that node.\n\/\/ If it is a file, this function will return error.\nfunc (s *Store) checkDir(parent *Node, dirName string) (*Node, error) {\n\tsubDir, ok := parent.Children[dirName]\n\n\tif ok {\n\t\treturn subDir, nil\n\t}\n\n\tn := newDir(path.Join(parent.Path, dirName), s.Index, s.Term, parent, parent.ACL, Permanent)\n\n\tparent.Children[dirName] = n\n\n\treturn n, nil\n}\n\n\/\/ Save function saves the static state of the store system.\n\/\/ Save function will not be able to save the state of watchers.\n\/\/ Save function will not save the parent field of the node. Or there will\n\/\/ be cyclic dependencies issue for the json package.\nfunc (s *Store) Save() ([]byte, error) {\n\ts.worldLock.Lock()\n\n\tclonedStore := New()\n\tclonedStore.Index = s.Index\n\tclonedStore.Term = s.Term\n\tclonedStore.Root = s.Root.Clone()\n\tclonedStore.WatcherHub = s.WatcherHub.clone()\n\tclonedStore.Stats = s.Stats.clone()\n\n\ts.worldLock.Unlock()\n\n\tb, err := json.Marshal(clonedStore)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b, nil\n}\n\n\/\/ recovery function recovery the store system from a static state.\n\/\/ It needs to recovery the parent field of the nodes.\n\/\/ It needs to delete the expired nodes since the saved time and also\n\/\/ need to create monitor go routines.\nfunc (s *Store) Recovery(state []byte) error {\n\ts.worldLock.Lock()\n\tdefer s.worldLock.Unlock()\n\terr := json.Unmarshal(state, s)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.Root.recoverAndclean()\n\treturn nil\n}\n\nfunc (s *Store) JsonStats() []byte {\n\ts.Stats.Watchers = uint64(s.WatcherHub.count)\n\treturn s.Stats.toJson()\n}\n<|endoftext|>"}
{"text":"<commit_before>package store\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"path\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/ Typedefs\n\/\/\n\/\/------------------------------------------------------------------------------\n\n\/\/ The main struct of the Key-Value store\ntype Store struct {\n\n\t\/\/ key-value store structure\n\tTree *tree\n\n\t\/\/ WatcherHub is where we register all the clients\n\t\/\/ who issue a watch request\n\twatcher *WatcherHub\n\n\t\/\/ The string channel to send messages to the outside world\n\t\/\/ Now we use it to send changes to the hub of the web service\n\tmessager *chan string\n\n\t\/\/ A map to keep the recent response to the clients\n\tResponseMap map[string]Response\n\n\t\/\/ The max number of the recent responses we can record\n\tResponseMaxSize int\n\n\t\/\/ The current number of the recent responses we have recorded\n\tResponseCurrSize uint\n\n\t\/\/ The index of the first recent responses we have\n\tResponseStartIndex uint64\n\n\t\/\/ Current index of the raft machine\n\tIndex uint64\n\n\t\/\/ Basic statistics information of etcd storage\n\tBasicStats EtcdStats\n}\n\n\/\/ A Node represents a Value in the Key-Value pair in the store\n\/\/ It has its value, expire time and a channel used to update the\n\/\/ expire time (since we do countdown in a go routine, we need to\n\/\/ communicate with it via channel)\ntype Node struct {\n\t\/\/ The string value of the node\n\tValue string `json:\"value\"`\n\n\t\/\/ If the node is a permanent one the ExprieTime will be Unix(0,0)\n\t\/\/ Otherwise after the expireTime, the node will be deleted\n\tExpireTime time.Time `json:\"expireTime\"`\n\n\t\/\/ A channel to update the expireTime of the node\n\tupdate chan time.Time `json:\"-\"`\n}\n\n\/\/ The response from the store to the user who issue a command\ntype Response struct {\n\tAction    string `json:\"action\"`\n\tKey       string `json:\"key\"`\n\tDir       bool   `json:\"dir,omitempty\"`\n\tPrevValue string `json:\"prevValue,omitempty\"`\n\tValue     string `json:\"value,omitempty\"`\n\n\t\/\/ If the key did not exist before the action,\n\t\/\/ this field should be set to true\n\tNewKey bool `json:\"newKey,omitempty\"`\n\n\tExpiration *time.Time `json:\"expiration,omitempty\"`\n\n\t\/\/ Time to live in second\n\tTTL int64 `json:\"ttl,omitempty\"`\n\n\t\/\/ The command index of the raft machine when the command is executed\n\tIndex uint64 `json:\"index\"`\n}\n\n\/\/ A listNode represent the simplest Key-Value pair with its type\n\/\/ It is only used when do list opeartion\n\/\/ We want to have a file system like store, thus we distingush \"file\"\n\/\/ and \"directory\"\ntype ListNode struct {\n\tKey   string\n\tValue string\n\tType  string\n}\n\nvar PERMANENT = time.Unix(0, 0)\n\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/ Methods\n\/\/\n\/\/------------------------------------------------------------------------------\n\n\/\/ Create a new stroe\n\/\/ Arguement max is the max number of response we want to record\nfunc CreateStore(max int) *Store {\n\ts := new(Store)\n\n\ts.messager = nil\n\n\ts.ResponseMap = make(map[string]Response)\n\ts.ResponseStartIndex = 0\n\ts.ResponseMaxSize = max\n\ts.ResponseCurrSize = 0\n\n\ts.Tree = &tree{\n\t\t&treeNode{\n\t\t\tNode{\n\t\t\t\t\"\/\",\n\t\t\t\ttime.Unix(0, 0),\n\t\t\t\tnil,\n\t\t\t},\n\t\t\ttrue,\n\t\t\tmake(map[string]*treeNode),\n\t\t},\n\t}\n\n\ts.watcher = createWatcherHub()\n\n\treturn s\n}\n\n\/\/ Set the messager of the store\nfunc (s *Store) SetMessager(messager *chan string) {\n\ts.messager = messager\n}\n\n\/\/ Set the key to value with expiration time\nfunc (s *Store) Set(key string, value string, expireTime time.Time, index uint64) ([]byte, error) {\n\n\t\/\/Update index\n\ts.Index = index\n\n\t\/\/Update stats\n\ts.BasicStats.Sets++\n\n\tkey = path.Clean(\"\/\" + key)\n\n\tisExpire := !expireTime.Equal(PERMANENT)\n\n\t\/\/ base response\n\tresp := Response{\n\t\tAction: \"SET\",\n\t\tKey:    key,\n\t\tValue:  value,\n\t\tIndex:  index,\n\t}\n\n\t\/\/ When the slow follower receive the set command\n\t\/\/ the key may be expired, we should not add the node\n\t\/\/ also if the node exist, we need to delete the node\n\tif isExpire && expireTime.Sub(time.Now()) < 0 {\n\t\treturn s.Delete(key, index)\n\t}\n\n\tvar TTL int64\n\n\t\/\/ Update ttl\n\tif isExpire {\n\t\tTTL = int64(expireTime.Sub(time.Now()) \/ time.Second)\n\t\tresp.Expiration = &expireTime\n\t\tresp.TTL = TTL\n\t}\n\n\t\/\/ Get the node\n\tnode, ok := s.Tree.get(key)\n\n\tif ok {\n\t\t\/\/ Update when node exists\n\n\t\t\/\/ Node is not permanent\n\t\tif !node.ExpireTime.Equal(PERMANENT) {\n\n\t\t\t\/\/ If node is not permanent\n\t\t\t\/\/ Update its expireTime\n\t\t\tnode.update <- expireTime\n\n\t\t} else {\n\n\t\t\t\/\/ If we want the permanent node to have expire time\n\t\t\t\/\/ We need to create create a go routine with a channel\n\t\t\tif isExpire {\n\t\t\t\tnode.update = make(chan time.Time)\n\t\t\t\tgo s.monitorExpiration(key, node.update, expireTime)\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/ Update the information of the node\n\t\ts.Tree.set(key, Node{value, expireTime, node.update})\n\n\t\tresp.PrevValue = node.Value\n\n\t\ts.watcher.notify(resp)\n\n\t\tmsg, err := json.Marshal(resp)\n\n\t\t\/\/ Send to the messager\n\t\tif s.messager != nil && err == nil {\n\n\t\t\t*s.messager <- string(msg)\n\t\t}\n\n\t\ts.addToResponseMap(index, &resp)\n\n\t\treturn msg, err\n\n\t\t\/\/ Add new node\n\t} else {\n\n\t\tupdate := make(chan time.Time)\n\n\t\tok := s.Tree.set(key, Node{value, expireTime, update})\n\n\t\tif !ok {\n\t\t\terr := NotFile(key)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif isExpire {\n\t\t\tgo s.monitorExpiration(key, update, expireTime)\n\t\t}\n\n\t\tresp.NewKey = true\n\n\t\tmsg, err := json.Marshal(resp)\n\n\t\t\/\/ Nofity the watcher\n\t\ts.watcher.notify(resp)\n\n\t\t\/\/ Send to the messager\n\t\tif s.messager != nil && err == nil {\n\n\t\t\t*s.messager <- string(msg)\n\t\t}\n\n\t\ts.addToResponseMap(index, &resp)\n\t\treturn msg, err\n\t}\n\n}\n\n\/\/ Get the value of the key and return the raw response\nfunc (s *Store) internalGet(key string) *Response {\n\n\tkey = path.Clean(\"\/\" + key)\n\n\tnode, ok := s.Tree.get(key)\n\n\tif ok {\n\t\tvar TTL int64\n\t\tvar isExpire bool = false\n\n\t\tisExpire = !node.ExpireTime.Equal(PERMANENT)\n\n\t\tresp := &Response{\n\t\t\tAction: \"GET\",\n\t\t\tKey:    key,\n\t\t\tValue:  node.Value,\n\t\t\tIndex:  s.Index,\n\t\t}\n\n\t\t\/\/ Update ttl\n\t\tif isExpire {\n\t\t\tTTL = int64(node.ExpireTime.Sub(time.Now()) \/ time.Second)\n\t\t\tresp.Expiration = &node.ExpireTime\n\t\t\tresp.TTL = TTL\n\t\t}\n\n\t\treturn resp\n\n\t} else {\n\t\t\/\/ we do not found the key\n\t\treturn nil\n\t}\n}\n\n\/\/ Get all the items under key\n\/\/ If key is a file return the file\n\/\/ If key is a directory reuturn an array of files\nfunc (s *Store) Get(key string) ([]byte, error) {\n\tresps, err := s.RawGet(key)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(resps) == 1 {\n\t\treturn json.Marshal(resps[0])\n\t}\n\n\treturn json.Marshal(resps)\n}\n\nfunc (s *Store) RawGet(key string) ([]*Response, error) {\n\t\/\/Update stats\n\ts.BasicStats.Gets++\n\n\tkey = path.Clean(\"\/\" + key)\n\n\tnodes, keys, dirs, ok := s.Tree.list(key)\n\n\tif ok {\n\t\tresps := make([]*Response, len(nodes))\n\t\tfor i := 0; i < len(nodes); i++ {\n\n\t\t\tvar TTL int64\n\t\t\tvar isExpire bool = false\n\n\t\t\tisExpire = !nodes[i].ExpireTime.Equal(PERMANENT)\n\n\t\t\tresps[i] = &Response{\n\t\t\t\tAction: \"GET\",\n\t\t\t\tIndex:  s.Index,\n\t\t\t\tKey:    path.Join(key, keys[i]),\n\t\t\t}\n\n\t\t\tif !dirs[i] {\n\t\t\t\tresps[i].Value = nodes[i].Value\n\t\t\t} else {\n\t\t\t\tresps[i].Dir = true\n\t\t\t}\n\n\t\t\t\/\/ Update ttl\n\t\t\tif isExpire {\n\t\t\t\tTTL = int64(nodes[i].ExpireTime.Sub(time.Now()) \/ time.Second)\n\t\t\t\tresps[i].Expiration = &nodes[i].ExpireTime\n\t\t\t\tresps[i].TTL = TTL\n\t\t\t}\n\n\t\t}\n\n\t\treturn resps, nil\n\t}\n\n\terr := NotFoundError(key)\n\treturn nil, err\n}\n\n\/\/ Delete the key\nfunc (s *Store) Delete(key string, index uint64) ([]byte, error) {\n\n\t\/\/Update stats\n\ts.BasicStats.Deletes++\n\n\tkey = path.Clean(\"\/\" + key)\n\n\t\/\/Update index\n\ts.Index = index\n\n\tnode, ok := s.Tree.get(key)\n\n\tif ok {\n\n\t\tresp := Response{\n\t\t\tAction:    \"DELETE\",\n\t\t\tKey:       key,\n\t\t\tPrevValue: node.Value,\n\t\t\tIndex:     index,\n\t\t}\n\n\t\tif node.ExpireTime.Equal(PERMANENT) {\n\n\t\t\ts.Tree.delete(key)\n\n\t\t} else {\n\t\t\tresp.Expiration = &node.ExpireTime\n\t\t\t\/\/ Kill the expire go routine\n\t\t\tnode.update <- PERMANENT\n\t\t\ts.Tree.delete(key)\n\n\t\t}\n\n\t\tmsg, err := json.Marshal(resp)\n\n\t\ts.watcher.notify(resp)\n\n\t\t\/\/ notify the messager\n\t\tif s.messager != nil && err == nil {\n\n\t\t\t*s.messager <- string(msg)\n\t\t}\n\n\t\ts.addToResponseMap(index, &resp)\n\n\t\treturn msg, err\n\n\t} else {\n\t\terr := NotFoundError(key)\n\t\treturn nil, err\n\t}\n}\n\n\/\/ Set the value of the key to the value if the given prevValue is equal to the value of the key\nfunc (s *Store) TestAndSet(key string, prevValue string, value string, expireTime time.Time, index uint64) ([]byte, error) {\n\t\/\/Update stats\n\ts.BasicStats.TestAndSets++\n\n\tresp := s.internalGet(key)\n\n\tif resp == nil {\n\t\terr := NotFoundError(key)\n\t\treturn nil, err\n\t}\n\n\tif resp.Value == prevValue {\n\n\t\t\/\/ If test success, do set\n\t\treturn s.Set(key, value, expireTime, index)\n\t} else {\n\n\t\t\/\/ If fails, return err\n\t\terr := TestFail(fmt.Sprintf(\"TestAndSet: %s!=%s\", resp.Value, prevValue))\n\t\treturn nil, err\n\t}\n\n}\n\n\/\/ Add a channel to the watchHub.\n\/\/ The watchHub will send response to the channel when any key under the prefix\n\/\/ changes [since the sinceIndex if given]\nfunc (s *Store) AddWatcher(prefix string, watcher *Watcher, sinceIndex uint64) error {\n\treturn s.watcher.addWatcher(prefix, watcher, sinceIndex, s.ResponseStartIndex, s.Index, &s.ResponseMap)\n}\n\n\/\/ This function should be created as a go routine to delete the key-value pair\n\/\/ when it reaches expiration time\n\nfunc (s *Store) monitorExpiration(key string, update chan time.Time, expireTime time.Time) {\n\n\tduration := expireTime.Sub(time.Now())\n\n\tfor {\n\t\tselect {\n\n\t\t\/\/ Timeout delete the node\n\t\tcase <-time.After(duration):\n\t\t\tnode, ok := s.Tree.get(key)\n\n\t\t\tif !ok {\n\t\t\t\treturn\n\n\t\t\t} else {\n\n\t\t\t\ts.Tree.delete(key)\n\n\t\t\t\tresp := Response{\n\t\t\t\t\tAction:     \"DELETE\",\n\t\t\t\t\tKey:        key,\n\t\t\t\t\tPrevValue:  node.Value,\n\t\t\t\t\tExpiration: &node.ExpireTime,\n\t\t\t\t\tIndex:      s.Index,\n\t\t\t\t}\n\n\t\t\t\tmsg, err := json.Marshal(resp)\n\n\t\t\t\ts.watcher.notify(resp)\n\n\t\t\t\t\/\/ notify the messager\n\t\t\t\tif s.messager != nil && err == nil {\n\n\t\t\t\t\t*s.messager <- string(msg)\n\t\t\t\t}\n\n\t\t\t\treturn\n\n\t\t\t}\n\n\t\tcase updateTime := <-update:\n\t\t\t\/\/ Update duration\n\t\t\t\/\/ If the node become a permanent one, the go routine is\n\t\t\t\/\/ not needed\n\t\t\tif updateTime.Equal(PERMANENT) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ Update duration\n\t\t\tduration = updateTime.Sub(time.Now())\n\t\t}\n\t}\n}\n\n\/\/ When we receive a command that will change the state of the key-value store\n\/\/ We will add the result of it to the ResponseMap for the use of watch command\n\/\/ Also we may remove the oldest response when we add new one\nfunc (s *Store) addToResponseMap(index uint64, resp *Response) {\n\n\t\/\/ zero case\n\tif s.ResponseMaxSize == 0 {\n\t\treturn\n\t}\n\n\tstrIndex := strconv.FormatUint(index, 10)\n\ts.ResponseMap[strIndex] = *resp\n\n\t\/\/ unlimited\n\tif s.ResponseMaxSize < 0 {\n\t\ts.ResponseCurrSize++\n\t\treturn\n\t}\n\n\t\/\/ if we reach the max point, we need to delete the most latest\n\t\/\/ response and update the startIndex\n\tif s.ResponseCurrSize == uint(s.ResponseMaxSize) {\n\t\ts.ResponseStartIndex++\n\t\tdelete(s.ResponseMap, strconv.FormatUint(s.ResponseStartIndex, 10))\n\t} else {\n\t\ts.ResponseCurrSize++\n\t}\n}\n\n\/\/ Save the current state of the storage system\nfunc (s *Store) Save() ([]byte, error) {\n\tb, err := json.Marshal(s)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}\n\n\/\/ Recovery the state of the stroage system from a previous state\nfunc (s *Store) Recovery(state []byte) error {\n\terr := json.Unmarshal(state, s)\n\n\t\/\/ The only thing need to change after the recovery is the\n\t\/\/ node with expiration time, we need to delete all the node\n\t\/\/ that have been expired and setup go routines to monitor the\n\t\/\/ other ones\n\ts.checkExpiration()\n\n\treturn err\n}\n\n\/\/ Clean the expired nodes\n\/\/ Set up go routines to mon\nfunc (s *Store) checkExpiration() {\n\ts.Tree.traverse(s.checkNode, false)\n}\n\n\/\/ Check each node\nfunc (s *Store) checkNode(key string, node *Node) {\n\n\tif node.ExpireTime.Equal(PERMANENT) {\n\t\treturn\n\t} else {\n\t\tif node.ExpireTime.Sub(time.Now()) >= time.Second {\n\n\t\t\tnode.update = make(chan time.Time)\n\t\t\tgo s.monitorExpiration(key, node.update, node.ExpireTime)\n\n\t\t} else {\n\t\t\t\/\/ we should delete this node\n\t\t\ts.Tree.delete(key)\n\t\t}\n\t}\n}\n<commit_msg>add space in comments<commit_after>package store\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"path\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/ Typedefs\n\/\/\n\/\/------------------------------------------------------------------------------\n\n\/\/ The main struct of the Key-Value store\ntype Store struct {\n\n\t\/\/ key-value store structure\n\tTree *tree\n\n\t\/\/ WatcherHub is where we register all the clients\n\t\/\/ who issue a watch request\n\twatcher *WatcherHub\n\n\t\/\/ The string channel to send messages to the outside world\n\t\/\/ Now we use it to send changes to the hub of the web service\n\tmessager *chan string\n\n\t\/\/ A map to keep the recent response to the clients\n\tResponseMap map[string]Response\n\n\t\/\/ The max number of the recent responses we can record\n\tResponseMaxSize int\n\n\t\/\/ The current number of the recent responses we have recorded\n\tResponseCurrSize uint\n\n\t\/\/ The index of the first recent responses we have\n\tResponseStartIndex uint64\n\n\t\/\/ Current index of the raft machine\n\tIndex uint64\n\n\t\/\/ Basic statistics information of etcd storage\n\tBasicStats EtcdStats\n}\n\n\/\/ A Node represents a Value in the Key-Value pair in the store\n\/\/ It has its value, expire time and a channel used to update the\n\/\/ expire time (since we do countdown in a go routine, we need to\n\/\/ communicate with it via channel)\ntype Node struct {\n\t\/\/ The string value of the node\n\tValue string `json:\"value\"`\n\n\t\/\/ If the node is a permanent one the ExprieTime will be Unix(0,0)\n\t\/\/ Otherwise after the expireTime, the node will be deleted\n\tExpireTime time.Time `json:\"expireTime\"`\n\n\t\/\/ A channel to update the expireTime of the node\n\tupdate chan time.Time `json:\"-\"`\n}\n\n\/\/ The response from the store to the user who issue a command\ntype Response struct {\n\tAction    string `json:\"action\"`\n\tKey       string `json:\"key\"`\n\tDir       bool   `json:\"dir,omitempty\"`\n\tPrevValue string `json:\"prevValue,omitempty\"`\n\tValue     string `json:\"value,omitempty\"`\n\n\t\/\/ If the key did not exist before the action,\n\t\/\/ this field should be set to true\n\tNewKey bool `json:\"newKey,omitempty\"`\n\n\tExpiration *time.Time `json:\"expiration,omitempty\"`\n\n\t\/\/ Time to live in second\n\tTTL int64 `json:\"ttl,omitempty\"`\n\n\t\/\/ The command index of the raft machine when the command is executed\n\tIndex uint64 `json:\"index\"`\n}\n\n\/\/ A listNode represent the simplest Key-Value pair with its type\n\/\/ It is only used when do list opeartion\n\/\/ We want to have a file system like store, thus we distingush \"file\"\n\/\/ and \"directory\"\ntype ListNode struct {\n\tKey   string\n\tValue string\n\tType  string\n}\n\nvar PERMANENT = time.Unix(0, 0)\n\n\/\/------------------------------------------------------------------------------\n\/\/\n\/\/ Methods\n\/\/\n\/\/------------------------------------------------------------------------------\n\n\/\/ Create a new stroe\n\/\/ Arguement max is the max number of response we want to record\nfunc CreateStore(max int) *Store {\n\ts := new(Store)\n\n\ts.messager = nil\n\n\ts.ResponseMap = make(map[string]Response)\n\ts.ResponseStartIndex = 0\n\ts.ResponseMaxSize = max\n\ts.ResponseCurrSize = 0\n\n\ts.Tree = &tree{\n\t\t&treeNode{\n\t\t\tNode{\n\t\t\t\t\"\/\",\n\t\t\t\ttime.Unix(0, 0),\n\t\t\t\tnil,\n\t\t\t},\n\t\t\ttrue,\n\t\t\tmake(map[string]*treeNode),\n\t\t},\n\t}\n\n\ts.watcher = createWatcherHub()\n\n\treturn s\n}\n\n\/\/ Set the messager of the store\nfunc (s *Store) SetMessager(messager *chan string) {\n\ts.messager = messager\n}\n\n\/\/ Set the key to value with expiration time\nfunc (s *Store) Set(key string, value string, expireTime time.Time, index uint64) ([]byte, error) {\n\n\t\/\/Update index\n\ts.Index = index\n\n\t\/\/Update stats\n\ts.BasicStats.Sets++\n\n\tkey = path.Clean(\"\/\" + key)\n\n\tisExpire := !expireTime.Equal(PERMANENT)\n\n\t\/\/ base response\n\tresp := Response{\n\t\tAction: \"SET\",\n\t\tKey:    key,\n\t\tValue:  value,\n\t\tIndex:  index,\n\t}\n\n\t\/\/ When the slow follower receive the set command\n\t\/\/ the key may be expired, we should not add the node\n\t\/\/ also if the node exist, we need to delete the node\n\tif isExpire && expireTime.Sub(time.Now()) < 0 {\n\t\treturn s.Delete(key, index)\n\t}\n\n\tvar TTL int64\n\n\t\/\/ Update ttl\n\tif isExpire {\n\t\tTTL = int64(expireTime.Sub(time.Now()) \/ time.Second)\n\t\tresp.Expiration = &expireTime\n\t\tresp.TTL = TTL\n\t}\n\n\t\/\/ Get the node\n\tnode, ok := s.Tree.get(key)\n\n\tif ok {\n\t\t\/\/ Update when node exists\n\n\t\t\/\/ Node is not permanent\n\t\tif !node.ExpireTime.Equal(PERMANENT) {\n\n\t\t\t\/\/ If node is not permanent\n\t\t\t\/\/ Update its expireTime\n\t\t\tnode.update <- expireTime\n\n\t\t} else {\n\n\t\t\t\/\/ If we want the permanent node to have expire time\n\t\t\t\/\/ We need to create create a go routine with a channel\n\t\t\tif isExpire {\n\t\t\t\tnode.update = make(chan time.Time)\n\t\t\t\tgo s.monitorExpiration(key, node.update, expireTime)\n\t\t\t}\n\n\t\t}\n\n\t\t\/\/ Update the information of the node\n\t\ts.Tree.set(key, Node{value, expireTime, node.update})\n\n\t\tresp.PrevValue = node.Value\n\n\t\ts.watcher.notify(resp)\n\n\t\tmsg, err := json.Marshal(resp)\n\n\t\t\/\/ Send to the messager\n\t\tif s.messager != nil && err == nil {\n\n\t\t\t*s.messager <- string(msg)\n\t\t}\n\n\t\ts.addToResponseMap(index, &resp)\n\n\t\treturn msg, err\n\n\t\t\/\/ Add new node\n\t} else {\n\n\t\tupdate := make(chan time.Time)\n\n\t\tok := s.Tree.set(key, Node{value, expireTime, update})\n\n\t\tif !ok {\n\t\t\terr := NotFile(key)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif isExpire {\n\t\t\tgo s.monitorExpiration(key, update, expireTime)\n\t\t}\n\n\t\tresp.NewKey = true\n\n\t\tmsg, err := json.Marshal(resp)\n\n\t\t\/\/ Nofity the watcher\n\t\ts.watcher.notify(resp)\n\n\t\t\/\/ Send to the messager\n\t\tif s.messager != nil && err == nil {\n\n\t\t\t*s.messager <- string(msg)\n\t\t}\n\n\t\ts.addToResponseMap(index, &resp)\n\t\treturn msg, err\n\t}\n\n}\n\n\/\/ Get the value of the key and return the raw response\nfunc (s *Store) internalGet(key string) *Response {\n\n\tkey = path.Clean(\"\/\" + key)\n\n\tnode, ok := s.Tree.get(key)\n\n\tif ok {\n\t\tvar TTL int64\n\t\tvar isExpire bool = false\n\n\t\tisExpire = !node.ExpireTime.Equal(PERMANENT)\n\n\t\tresp := &Response{\n\t\t\tAction: \"GET\",\n\t\t\tKey:    key,\n\t\t\tValue:  node.Value,\n\t\t\tIndex:  s.Index,\n\t\t}\n\n\t\t\/\/ Update ttl\n\t\tif isExpire {\n\t\t\tTTL = int64(node.ExpireTime.Sub(time.Now()) \/ time.Second)\n\t\t\tresp.Expiration = &node.ExpireTime\n\t\t\tresp.TTL = TTL\n\t\t}\n\n\t\treturn resp\n\n\t} else {\n\t\t\/\/ we do not found the key\n\t\treturn nil\n\t}\n}\n\n\/\/ Get all the items under key\n\/\/ If key is a file return the file\n\/\/ If key is a directory reuturn an array of files\nfunc (s *Store) Get(key string) ([]byte, error) {\n\tresps, err := s.RawGet(key)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(resps) == 1 {\n\t\treturn json.Marshal(resps[0])\n\t}\n\n\treturn json.Marshal(resps)\n}\n\nfunc (s *Store) RawGet(key string) ([]*Response, error) {\n\t\/\/ Update stats\n\ts.BasicStats.Gets++\n\n\tkey = path.Clean(\"\/\" + key)\n\n\tnodes, keys, dirs, ok := s.Tree.list(key)\n\n\tif ok {\n\t\tresps := make([]*Response, len(nodes))\n\t\tfor i := 0; i < len(nodes); i++ {\n\n\t\t\tvar TTL int64\n\t\t\tvar isExpire bool = false\n\n\t\t\tisExpire = !nodes[i].ExpireTime.Equal(PERMANENT)\n\n\t\t\tresps[i] = &Response{\n\t\t\t\tAction: \"GET\",\n\t\t\t\tIndex:  s.Index,\n\t\t\t\tKey:    path.Join(key, keys[i]),\n\t\t\t}\n\n\t\t\tif !dirs[i] {\n\t\t\t\tresps[i].Value = nodes[i].Value\n\t\t\t} else {\n\t\t\t\tresps[i].Dir = true\n\t\t\t}\n\n\t\t\t\/\/ Update ttl\n\t\t\tif isExpire {\n\t\t\t\tTTL = int64(nodes[i].ExpireTime.Sub(time.Now()) \/ time.Second)\n\t\t\t\tresps[i].Expiration = &nodes[i].ExpireTime\n\t\t\t\tresps[i].TTL = TTL\n\t\t\t}\n\n\t\t}\n\n\t\treturn resps, nil\n\t}\n\n\terr := NotFoundError(key)\n\treturn nil, err\n}\n\n\/\/ Delete the key\nfunc (s *Store) Delete(key string, index uint64) ([]byte, error) {\n\n\t\/\/ Update stats\n\ts.BasicStats.Deletes++\n\n\tkey = path.Clean(\"\/\" + key)\n\n\t\/\/ Update index\n\ts.Index = index\n\n\tnode, ok := s.Tree.get(key)\n\n\tif ok {\n\n\t\tresp := Response{\n\t\t\tAction:    \"DELETE\",\n\t\t\tKey:       key,\n\t\t\tPrevValue: node.Value,\n\t\t\tIndex:     index,\n\t\t}\n\n\t\tif node.ExpireTime.Equal(PERMANENT) {\n\n\t\t\ts.Tree.delete(key)\n\n\t\t} else {\n\t\t\tresp.Expiration = &node.ExpireTime\n\t\t\t\/\/ Kill the expire go routine\n\t\t\tnode.update <- PERMANENT\n\t\t\ts.Tree.delete(key)\n\n\t\t}\n\n\t\tmsg, err := json.Marshal(resp)\n\n\t\ts.watcher.notify(resp)\n\n\t\t\/\/ notify the messager\n\t\tif s.messager != nil && err == nil {\n\n\t\t\t*s.messager <- string(msg)\n\t\t}\n\n\t\ts.addToResponseMap(index, &resp)\n\n\t\treturn msg, err\n\n\t} else {\n\t\terr := NotFoundError(key)\n\t\treturn nil, err\n\t}\n}\n\n\/\/ Set the value of the key to the value if the given prevValue is equal to the value of the key\nfunc (s *Store) TestAndSet(key string, prevValue string, value string, expireTime time.Time, index uint64) ([]byte, error) {\n\t\/\/ Update stats\n\ts.BasicStats.TestAndSets++\n\n\tresp := s.internalGet(key)\n\n\tif resp == nil {\n\t\terr := NotFoundError(key)\n\t\treturn nil, err\n\t}\n\n\tif resp.Value == prevValue {\n\n\t\t\/\/ If test success, do set\n\t\treturn s.Set(key, value, expireTime, index)\n\t} else {\n\n\t\t\/\/ If fails, return err\n\t\terr := TestFail(fmt.Sprintf(\"TestAndSet: %s!=%s\", resp.Value, prevValue))\n\t\treturn nil, err\n\t}\n\n}\n\n\/\/ Add a channel to the watchHub.\n\/\/ The watchHub will send response to the channel when any key under the prefix\n\/\/ changes [since the sinceIndex if given]\nfunc (s *Store) AddWatcher(prefix string, watcher *Watcher, sinceIndex uint64) error {\n\treturn s.watcher.addWatcher(prefix, watcher, sinceIndex, s.ResponseStartIndex, s.Index, &s.ResponseMap)\n}\n\n\/\/ This function should be created as a go routine to delete the key-value pair\n\/\/ when it reaches expiration time\n\nfunc (s *Store) monitorExpiration(key string, update chan time.Time, expireTime time.Time) {\n\n\tduration := expireTime.Sub(time.Now())\n\n\tfor {\n\t\tselect {\n\n\t\t\/\/ Timeout delete the node\n\t\tcase <-time.After(duration):\n\t\t\tnode, ok := s.Tree.get(key)\n\n\t\t\tif !ok {\n\t\t\t\treturn\n\n\t\t\t} else {\n\n\t\t\t\ts.Tree.delete(key)\n\n\t\t\t\tresp := Response{\n\t\t\t\t\tAction:     \"DELETE\",\n\t\t\t\t\tKey:        key,\n\t\t\t\t\tPrevValue:  node.Value,\n\t\t\t\t\tExpiration: &node.ExpireTime,\n\t\t\t\t\tIndex:      s.Index,\n\t\t\t\t}\n\n\t\t\t\tmsg, err := json.Marshal(resp)\n\n\t\t\t\ts.watcher.notify(resp)\n\n\t\t\t\t\/\/ notify the messager\n\t\t\t\tif s.messager != nil && err == nil {\n\n\t\t\t\t\t*s.messager <- string(msg)\n\t\t\t\t}\n\n\t\t\t\treturn\n\n\t\t\t}\n\n\t\tcase updateTime := <-update:\n\t\t\t\/\/ Update duration\n\t\t\t\/\/ If the node become a permanent one, the go routine is\n\t\t\t\/\/ not needed\n\t\t\tif updateTime.Equal(PERMANENT) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ Update duration\n\t\t\tduration = updateTime.Sub(time.Now())\n\t\t}\n\t}\n}\n\n\/\/ When we receive a command that will change the state of the key-value store\n\/\/ We will add the result of it to the ResponseMap for the use of watch command\n\/\/ Also we may remove the oldest response when we add new one\nfunc (s *Store) addToResponseMap(index uint64, resp *Response) {\n\n\t\/\/ zero case\n\tif s.ResponseMaxSize == 0 {\n\t\treturn\n\t}\n\n\tstrIndex := strconv.FormatUint(index, 10)\n\ts.ResponseMap[strIndex] = *resp\n\n\t\/\/ unlimited\n\tif s.ResponseMaxSize < 0 {\n\t\ts.ResponseCurrSize++\n\t\treturn\n\t}\n\n\t\/\/ if we reach the max point, we need to delete the most latest\n\t\/\/ response and update the startIndex\n\tif s.ResponseCurrSize == uint(s.ResponseMaxSize) {\n\t\ts.ResponseStartIndex++\n\t\tdelete(s.ResponseMap, strconv.FormatUint(s.ResponseStartIndex, 10))\n\t} else {\n\t\ts.ResponseCurrSize++\n\t}\n}\n\n\/\/ Save the current state of the storage system\nfunc (s *Store) Save() ([]byte, error) {\n\tb, err := json.Marshal(s)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}\n\n\/\/ Recovery the state of the stroage system from a previous state\nfunc (s *Store) Recovery(state []byte) error {\n\terr := json.Unmarshal(state, s)\n\n\t\/\/ The only thing need to change after the recovery is the\n\t\/\/ node with expiration time, we need to delete all the node\n\t\/\/ that have been expired and setup go routines to monitor the\n\t\/\/ other ones\n\ts.checkExpiration()\n\n\treturn err\n}\n\n\/\/ Clean the expired nodes\n\/\/ Set up go routines to mon\nfunc (s *Store) checkExpiration() {\n\ts.Tree.traverse(s.checkNode, false)\n}\n\n\/\/ Check each node\nfunc (s *Store) checkNode(key string, node *Node) {\n\n\tif node.ExpireTime.Equal(PERMANENT) {\n\t\treturn\n\t} else {\n\t\tif node.ExpireTime.Sub(time.Now()) >= time.Second {\n\n\t\t\tnode.update = make(chan time.Time)\n\t\t\tgo s.monitorExpiration(key, node.update, node.ExpireTime)\n\n\t\t} else {\n\t\t\t\/\/ we should delete this node\n\t\t\ts.Tree.delete(key)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"github.com\/kardianos\/osext\"\n\t_ \"github.com\/mattn\/go-sqlite3\"\n\t\"github.com\/spf13\/viper\"\n\t\"html\/template\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype DbContext struct {\n\tDb     *sql.DB\n\tInsert *sql.Stmt\n}\n\nfunc (c *DbContext) Close() {\n\tif c.Insert != nil {\n\t\tc.Insert.Close()\n\t}\n\tif c.Db != nil {\n\t\tc.Db.Close()\n\t}\n}\n\nfunc loadConfig() {\n\tviper.SetConfigName(\"pbxlog\")\n\tviper.SetConfigType(\"yaml\")\n\n\tviper.AddConfigPath(\"$HOME\")\n\tviper.AddConfigPath(\"$HOME\/.pbxlog\")\n\tviper.AddConfigPath(\".\")\n\n\tviper.SetDefault(\"pabx\", \"\")\n\tviper.SetDefault(\"webui\", \"\")\n\tviper.SetDefault(\"dump-file\", \"\")\n\tviper.SetDefault(\"error-file\", \"\")\n\tviper.SetDefault(\"calls-db\", \"\")\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Fatal error config file: %s \\n\", err))\n\t}\n\n\tfmt.Printf(\"Using pabx = %s\\n\", viper.GetString(\"pabx\"))\n\tfmt.Printf(\"Using webui = %s\\n\", viper.GetString(\"webui\"))\n\tfmt.Printf(\"Using dump-file = %s\\n\", viper.GetString(\"dump-file\"))\n\tfmt.Printf(\"Using error-file = %s\\n\", viper.GetString(\"error-file\"))\n\tfmt.Printf(\"Using calls-db = %s\\n\", viper.GetString(\"calls-db\"))\n\n\tif viper.GetString(\"pabx\") == \"\" || viper.GetString(\"calls-db\") == \"\" {\n\t\tpanic(\"pabx and calls-db configuration values required\")\n\t}\n}\n\nfunc connectToPABX() net.Conn {\n\tconn, err := net.Dial(\"tcp\", viper.GetString(\"pabx\"))\n\tpanicErr(err)\n\treturn conn\n}\n\nfunc openDumpFile(configItem string) *os.File {\n\tfilename := viper.GetString(configItem)\n\tif filename == \"\" {\n\t\treturn nil\n\t}\n\n\tdumpfile, err := os.OpenFile(filename,\n\t\tos.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)\n\tpanicErr(err)\n\n\treturn dumpfile\n}\n\ntype CDR struct {\n\tCallid    int\n\tExtension int\n\tExtName   string\n\tAuth      string\n\tAuthName  string\n\tCalltime  string\n\tDuration  string\n\tCode      string\n\tDialed    string\n\tAccount   string\n\tCost      string\n\tClid      string\n\tClidname  string\n\tGpno      string\n\tRingtime  string\n}\n\nfunc openCallsDatabase() *DbContext {\n\tctx := new(DbContext)\n\n\tvar err error\n\tctx.Db, err = sql.Open(\"sqlite3\", viper.GetString(\"calls-db\"))\n\tpanicErr(err)\n\n\t_, err = ctx.Db.Exec(\"CREATE TABLE IF NOT EXISTS calls (\" +\n\t\t\"callid INTEGER, extension INTEGER, auth TEXT, calltime TEXT, duration TEXT, \" +\n\t\t\"code TEXT, dialed TEXT, account TEXT, cost REAL, clid TEXT, \" +\n\t\t\"clidname TEXT, gpno TEXT, ringtime TEXT);\")\n\tpanicErr(err)\n\n\t_, err = ctx.Db.Exec(\"CREATE TABLE IF NOT EXISTS extensions (num INTEGER, name TEXT);\")\n\tpanicErr(err)\n\n\tctx.Insert, err = ctx.Db.Prepare(\"INSERT INTO calls(callid, extension, auth, calltime, \" +\n\t\t\"duration, code, dialed, account, cost, clid, clidname, gpno, ringtime) \" +\n\t\t\"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\")\n\tpanicErr(err)\n\n\treturn ctx\n}\n\nfunc insertCDR(ctx *DbContext, cdr *CDR) {\n\t_, err := ctx.Insert.Exec(cdr.Callid, cdr.Extension, cdr.Auth,\n\t\tcdr.Calltime, cdr.Duration, cdr.Code, cdr.Dialed, cdr.Account,\n\t\tcdr.Cost, cdr.Clid, cdr.Clidname, cdr.Gpno, cdr.Ringtime)\n\tpanicErr(err)\n}\n\nfunc splitData(str string) *CDR {\n\tn := len(str)\n\tif n != 154 && n != 122 {\n\t\treturn nil\n\t}\n\tt := time.Now()\n\n\tvar cdr CDR\n\tcdr.Callid, _ = strconv.Atoi(strings.TrimSpace(str[2:8]))\n\tcdr.Extension, _ = strconv.Atoi(strings.TrimSpace(str[9:15]))\n\tcdr.Auth = strings.TrimSpace(str[16:25])\n\tcdr.Calltime = strings.TrimSpace(fmt.Sprintf(\"%d-%s-%s\", t.Year(), str[26:28], str[29:40]))\n\tcdr.Duration = strings.TrimSpace(str[41:49])\n\tcdr.Code = strings.TrimSpace(str[50:52])\n\tcdr.Dialed = strings.TrimSpace(str[53:71])\n\tcdr.Account = strings.TrimSpace(str[72:89])\n\tcdr.Cost = strings.TrimSpace(str[90:100])\n\tcdr.Clid = strings.TrimSpace(str[101:117])\n\tif n == 154 {\n\t\tcdr.Clidname = strings.TrimSpace(str[118:136])\n\t\tcdr.Gpno = strings.TrimSpace(str[137:143])\n\t\tcdr.Ringtime = strings.TrimSpace(str[143:151])\n\t} else {\n\t\tcdr.Clidname = \"\"\n\t\tcdr.Gpno = \"\"\n\t\tcdr.Ringtime = \"\"\n\t}\n\n\treturn &cdr\n}\n\nfunc skipHeader(line string) string {\n\tconst tag = \"====\"\n\tif line[0] == 0x0C {\n\t\tn := strings.LastIndex(line, tag)\n\t\tif n >= 0 {\n\t\t\tfmt.Print(\" HDR \")\n\t\t\treturn line[n+len(tag)+2:]\n\t\t}\n\t}\n\treturn line\n}\n\nfunc main() {\n\tif time.Now().Year() < 2018 {\n\t\tpanic(\"System date incorrect\")\n\t}\n\n\tloadConfig()\n\n\tpabxConn := connectToPABX()\n\tdefer pabxConn.Close()\n\tpabx := bufio.NewReader(pabxConn)\n\n\tctx := openCallsDatabase()\n\tdefer ctx.Close()\n\n\tstartWebServer(ctx)\n\n\tdumpfile := openDumpFile(\"dump-file\")\n\tif dumpfile != nil {\n\t\tdefer dumpfile.Close()\n\t}\n\n\tfor {\n\t\t\/\/ every call record ends with a nul character\n\t\tstr, err := pabx.ReadString('\\000')\n\t\tpanicErr(err)\n\t\tif dumpfile != nil {\n\t\t\tdumpfile.Write([]byte(str))\n\t\t\tdumpfile.Sync()\n\t\t}\n\t\tfmt.Print(\".\")\n\n\t\t\/\/ every now and then the PABX will preface the call\n\t\t\/\/ record with a human readable header. Skip it.\n\t\tstr = skipHeader(str)\n\n\t\t\/\/ process this single call record\n\t\tcdr := splitData(str)\n\t\tif cdr == nil {\n\t\t\tdumpError(str)\n\t\t} else {\n\t\t\tinsertCDR(ctx, cdr)\n\t\t}\n\t}\n}\n\nfunc dumpError(str string) {\n\tfmt.Print(\" INVALID \")\n\terrorfile := openDumpFile(\"error-file\")\n\tif errorfile != nil {\n\t\tdefer errorfile.Close()\n\t\tmsg := fmt.Sprintf(\"\\nError: len = %d\\n--\\n%s\\n--\\n\", len(str), str)\n\t\terrorfile.Write([]byte(msg))\n\t\terrorfile.Sync()\n\t}\n}\n\nfunc panicErr(err error, args ...string) {\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error: %q: %s\\n\", err, args))\n\t}\n}\n\n\/* ----- WEBUI ----- *\/\n\nfunc startWebServer(ctx *DbContext) {\n\twebui := viper.GetString(\"webui\")\n\tif webui == \"\" {\n\t\treturn\n\t}\n\n\thttp.HandleFunc(\"\/\",\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\thandler(ctx, w, r)\n\t\t})\n\n\tlistener, err := net.Listen(\"tcp\", webui)\n\tpanicErr(err)\n\n\tgo http.Serve(listener, nil)\n}\n\ntype Row struct {\n\tCDR\n\tGroup int\n}\ntype Page struct {\n\tList []Row\n\tPrev int\n\tNext int\n}\n\nfunc handler(ctx *DbContext, w http.ResponseWriter, r *http.Request) {\n\tfolder, err := osext.ExecutableFolder()\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"osext = %v\", err)\n\t\treturn\n\t}\n\ttemplateFile := path.Join(folder, \"pbxlog.html\")\n\n\tt := template.New(\"pbxlog.html\")\n\tt, err = t.ParseFiles(templateFile)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"ParseFiles = %v\", err)\n\t\treturn\n\t}\n\n\tcount, err := strconv.Atoi(r.FormValue(\"count\"))\n\tif err != nil || count < 1 {\n\t\tcount = 200\n\t}\n\n\tpage, err := strconv.Atoi(r.FormValue(\"page\"))\n\tif err != nil || page < 1 {\n\t\tpage = 1\n\t}\n\n\t\/* not using limit\/offset for pagination, see below *\/\n\trows, err := ctx.Db.Query(\"\"+\n\t\t\"SELECT callid, extension, COALESCE(x.name, '') AS extname, \"+\n\t\t\"auth, COALESCE(a.name, '') AS authname, calltime, duration, \"+\n\t\t\"code, dialed, account, cost, clid, clidname, \"+\n\t\t\"gpno, ringtime \"+\n\t\t\"FROM calls c \"+\n\t\t\"LEFT JOIN extensions x ON c.extension = x.num \"+\n\t\t\"LEFT JOIN extensions a ON c.auth = a.num \"+\n\t\t\"ORDER BY calltime DESC, callid DESC \")\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Query = %v\", err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tvar p Page\n\tvar cdr Row\n\tvar grp map[int]int\n\tvar next int\n\tvar ok bool\n\n\t\/* handle pagination manually as sqlite3 limit\/offset seems to skip\n\t   records for some reason. Since most people will not be looking too\n\t   far back in the database manually, although inefficient, this is \n\t   plenty fast enough *\/\n\tskip := (page - 1) * count;\n\tfor i := 0; i < skip; i++ {\n\t\trows.Next()\n\t}\n\n\tgrp = make(map[int]int)\n\tfor i := 0; i < count; i++ {\n\t\tif !rows.Next() {\n\t\t\tbreak\n\t\t}\n\n\t\terr = rows.Scan(&cdr.Callid, &cdr.Extension, &cdr.ExtName, &cdr.Auth, &cdr.AuthName,\n\t\t\t&cdr.Calltime, &cdr.Duration, &cdr.Code, &cdr.Dialed, &cdr.Account, &cdr.Cost,\n\t\t\t&cdr.Clid, &cdr.Clidname, &cdr.Gpno, &cdr.Ringtime)\n\t\tcdr.Group, ok = grp[cdr.Callid]\n\t\tif !ok {\n\t\t\tnext = (next % 5) + 1\n\t\t\tcdr.Group = next\n\t\t\tgrp[cdr.Callid] = cdr.Group\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(w, \"rows.Scan() = %v\", err)\n\t\t}\n\t\tp.List = append(p.List, cdr)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"rows.Err() = %v\", err)\n\t}\n\n        p.Prev = page - 1\n        if p.Prev < 1 {\n \t\tp.Prev = 1\n\t}\n\tp.Next = page + 1\n\n\terr = t.Execute(w, p)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"%v\", err)\n\t\treturn\n\t}\n}\n<commit_msg>go formatting of the code<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"github.com\/kardianos\/osext\"\n\t_ \"github.com\/mattn\/go-sqlite3\"\n\t\"github.com\/spf13\/viper\"\n\t\"html\/template\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype DbContext struct {\n\tDb     *sql.DB\n\tInsert *sql.Stmt\n}\n\nfunc (c *DbContext) Close() {\n\tif c.Insert != nil {\n\t\tc.Insert.Close()\n\t}\n\tif c.Db != nil {\n\t\tc.Db.Close()\n\t}\n}\n\nfunc loadConfig() {\n\tviper.SetConfigName(\"pbxlog\")\n\tviper.SetConfigType(\"yaml\")\n\n\tviper.AddConfigPath(\"$HOME\")\n\tviper.AddConfigPath(\"$HOME\/.pbxlog\")\n\tviper.AddConfigPath(\".\")\n\n\tviper.SetDefault(\"pabx\", \"\")\n\tviper.SetDefault(\"webui\", \"\")\n\tviper.SetDefault(\"dump-file\", \"\")\n\tviper.SetDefault(\"error-file\", \"\")\n\tviper.SetDefault(\"calls-db\", \"\")\n\n\terr := viper.ReadInConfig()\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Fatal error config file: %s \\n\", err))\n\t}\n\n\tfmt.Printf(\"Using pabx = %s\\n\", viper.GetString(\"pabx\"))\n\tfmt.Printf(\"Using webui = %s\\n\", viper.GetString(\"webui\"))\n\tfmt.Printf(\"Using dump-file = %s\\n\", viper.GetString(\"dump-file\"))\n\tfmt.Printf(\"Using error-file = %s\\n\", viper.GetString(\"error-file\"))\n\tfmt.Printf(\"Using calls-db = %s\\n\", viper.GetString(\"calls-db\"))\n\n\tif viper.GetString(\"pabx\") == \"\" || viper.GetString(\"calls-db\") == \"\" {\n\t\tpanic(\"pabx and calls-db configuration values required\")\n\t}\n}\n\nfunc connectToPABX() net.Conn {\n\tconn, err := net.Dial(\"tcp\", viper.GetString(\"pabx\"))\n\tpanicErr(err)\n\treturn conn\n}\n\nfunc openDumpFile(configItem string) *os.File {\n\tfilename := viper.GetString(configItem)\n\tif filename == \"\" {\n\t\treturn nil\n\t}\n\n\tdumpfile, err := os.OpenFile(filename,\n\t\tos.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)\n\tpanicErr(err)\n\n\treturn dumpfile\n}\n\ntype CDR struct {\n\tCallid    int\n\tExtension int\n\tExtName   string\n\tAuth      string\n\tAuthName  string\n\tCalltime  string\n\tDuration  string\n\tCode      string\n\tDialed    string\n\tAccount   string\n\tCost      string\n\tClid      string\n\tClidname  string\n\tGpno      string\n\tRingtime  string\n}\n\nfunc openCallsDatabase() *DbContext {\n\tctx := new(DbContext)\n\n\tvar err error\n\tctx.Db, err = sql.Open(\"sqlite3\", viper.GetString(\"calls-db\"))\n\tpanicErr(err)\n\n\t_, err = ctx.Db.Exec(\"CREATE TABLE IF NOT EXISTS calls (\" +\n\t\t\"callid INTEGER, extension INTEGER, auth TEXT, calltime TEXT, duration TEXT, \" +\n\t\t\"code TEXT, dialed TEXT, account TEXT, cost REAL, clid TEXT, \" +\n\t\t\"clidname TEXT, gpno TEXT, ringtime TEXT);\")\n\tpanicErr(err)\n\n\t_, err = ctx.Db.Exec(\"CREATE TABLE IF NOT EXISTS extensions (num INTEGER, name TEXT);\")\n\tpanicErr(err)\n\n\tctx.Insert, err = ctx.Db.Prepare(\"INSERT INTO calls(callid, extension, auth, calltime, \" +\n\t\t\"duration, code, dialed, account, cost, clid, clidname, gpno, ringtime) \" +\n\t\t\"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\")\n\tpanicErr(err)\n\n\treturn ctx\n}\n\nfunc insertCDR(ctx *DbContext, cdr *CDR) {\n\t_, err := ctx.Insert.Exec(cdr.Callid, cdr.Extension, cdr.Auth,\n\t\tcdr.Calltime, cdr.Duration, cdr.Code, cdr.Dialed, cdr.Account,\n\t\tcdr.Cost, cdr.Clid, cdr.Clidname, cdr.Gpno, cdr.Ringtime)\n\tpanicErr(err)\n}\n\nfunc splitData(str string) *CDR {\n\tn := len(str)\n\tif n != 154 && n != 122 {\n\t\treturn nil\n\t}\n\tt := time.Now()\n\n\tvar cdr CDR\n\tcdr.Callid, _ = strconv.Atoi(strings.TrimSpace(str[2:8]))\n\tcdr.Extension, _ = strconv.Atoi(strings.TrimSpace(str[9:15]))\n\tcdr.Auth = strings.TrimSpace(str[16:25])\n\tcdr.Calltime = strings.TrimSpace(fmt.Sprintf(\"%d-%s-%s\", t.Year(), str[26:28], str[29:40]))\n\tcdr.Duration = strings.TrimSpace(str[41:49])\n\tcdr.Code = strings.TrimSpace(str[50:52])\n\tcdr.Dialed = strings.TrimSpace(str[53:71])\n\tcdr.Account = strings.TrimSpace(str[72:89])\n\tcdr.Cost = strings.TrimSpace(str[90:100])\n\tcdr.Clid = strings.TrimSpace(str[101:117])\n\tif n == 154 {\n\t\tcdr.Clidname = strings.TrimSpace(str[118:136])\n\t\tcdr.Gpno = strings.TrimSpace(str[137:143])\n\t\tcdr.Ringtime = strings.TrimSpace(str[143:151])\n\t} else {\n\t\tcdr.Clidname = \"\"\n\t\tcdr.Gpno = \"\"\n\t\tcdr.Ringtime = \"\"\n\t}\n\n\treturn &cdr\n}\n\nfunc skipHeader(line string) string {\n\tconst tag = \"====\"\n\tif line[0] == 0x0C {\n\t\tn := strings.LastIndex(line, tag)\n\t\tif n >= 0 {\n\t\t\tfmt.Print(\" HDR \")\n\t\t\treturn line[n+len(tag)+2:]\n\t\t}\n\t}\n\treturn line\n}\n\nfunc main() {\n\tif time.Now().Year() < 2018 {\n\t\tpanic(\"System date incorrect\")\n\t}\n\n\tloadConfig()\n\n\tpabxConn := connectToPABX()\n\tdefer pabxConn.Close()\n\tpabx := bufio.NewReader(pabxConn)\n\n\tctx := openCallsDatabase()\n\tdefer ctx.Close()\n\n\tstartWebServer(ctx)\n\n\tdumpfile := openDumpFile(\"dump-file\")\n\tif dumpfile != nil {\n\t\tdefer dumpfile.Close()\n\t}\n\n\tfor {\n\t\t\/\/ every call record ends with a nul character\n\t\tstr, err := pabx.ReadString('\\000')\n\t\tpanicErr(err)\n\t\tif dumpfile != nil {\n\t\t\tdumpfile.Write([]byte(str))\n\t\t\tdumpfile.Sync()\n\t\t}\n\t\tfmt.Print(\".\")\n\n\t\t\/\/ every now and then the PABX will preface the call\n\t\t\/\/ record with a human readable header. Skip it.\n\t\tstr = skipHeader(str)\n\n\t\t\/\/ process this single call record\n\t\tcdr := splitData(str)\n\t\tif cdr == nil {\n\t\t\tdumpError(str)\n\t\t} else {\n\t\t\tinsertCDR(ctx, cdr)\n\t\t}\n\t}\n}\n\nfunc dumpError(str string) {\n\tfmt.Print(\" INVALID \")\n\terrorfile := openDumpFile(\"error-file\")\n\tif errorfile != nil {\n\t\tdefer errorfile.Close()\n\t\tmsg := fmt.Sprintf(\"\\nError: len = %d\\n--\\n%s\\n--\\n\", len(str), str)\n\t\terrorfile.Write([]byte(msg))\n\t\terrorfile.Sync()\n\t}\n}\n\nfunc panicErr(err error, args ...string) {\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"Error: %q: %s\\n\", err, args))\n\t}\n}\n\n\/* ----- WEBUI ----- *\/\n\nfunc startWebServer(ctx *DbContext) {\n\twebui := viper.GetString(\"webui\")\n\tif webui == \"\" {\n\t\treturn\n\t}\n\n\thttp.HandleFunc(\"\/\",\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\thandler(ctx, w, r)\n\t\t})\n\n\tlistener, err := net.Listen(\"tcp\", webui)\n\tpanicErr(err)\n\n\tgo http.Serve(listener, nil)\n}\n\ntype Row struct {\n\tCDR\n\tGroup int\n}\ntype Page struct {\n\tList []Row\n\tPrev int\n\tNext int\n}\n\nfunc handler(ctx *DbContext, w http.ResponseWriter, r *http.Request) {\n\tfolder, err := osext.ExecutableFolder()\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"osext = %v\", err)\n\t\treturn\n\t}\n\ttemplateFile := path.Join(folder, \"pbxlog.html\")\n\n\tt := template.New(\"pbxlog.html\")\n\tt, err = t.ParseFiles(templateFile)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"ParseFiles = %v\", err)\n\t\treturn\n\t}\n\n\tcount, err := strconv.Atoi(r.FormValue(\"count\"))\n\tif err != nil || count < 1 {\n\t\tcount = 200\n\t}\n\n\tpage, err := strconv.Atoi(r.FormValue(\"page\"))\n\tif err != nil || page < 1 {\n\t\tpage = 1\n\t}\n\n\t\/* not using limit\/offset for pagination, see below *\/\n\trows, err := ctx.Db.Query(\"\" +\n\t\t\"SELECT callid, extension, COALESCE(x.name, '') AS extname, \" +\n\t\t\"auth, COALESCE(a.name, '') AS authname, calltime, duration, \" +\n\t\t\"code, dialed, account, cost, clid, clidname, \" +\n\t\t\"gpno, ringtime \" +\n\t\t\"FROM calls c \" +\n\t\t\"LEFT JOIN extensions x ON c.extension = x.num \" +\n\t\t\"LEFT JOIN extensions a ON c.auth = a.num \" +\n\t\t\"ORDER BY calltime DESC, callid DESC \")\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"Query = %v\", err)\n\t\treturn\n\t}\n\tdefer rows.Close()\n\n\tvar p Page\n\tvar cdr Row\n\tvar grp map[int]int\n\tvar next int\n\tvar ok bool\n\n\t\/* handle pagination manually as sqlite3 limit\/offset seems to skip\n\t   records for some reason. Since most people will not be looking too\n\t   far back in the database manually, although inefficient, this is\n\t   plenty fast enough *\/\n\tskip := (page - 1) * count\n\tfor i := 0; i < skip; i++ {\n\t\trows.Next()\n\t}\n\n\tgrp = make(map[int]int)\n\tfor i := 0; i < count; i++ {\n\t\tif !rows.Next() {\n\t\t\tbreak\n\t\t}\n\n\t\terr = rows.Scan(&cdr.Callid, &cdr.Extension, &cdr.ExtName, &cdr.Auth, &cdr.AuthName,\n\t\t\t&cdr.Calltime, &cdr.Duration, &cdr.Code, &cdr.Dialed, &cdr.Account, &cdr.Cost,\n\t\t\t&cdr.Clid, &cdr.Clidname, &cdr.Gpno, &cdr.Ringtime)\n\t\tcdr.Group, ok = grp[cdr.Callid]\n\t\tif !ok {\n\t\t\tnext = (next % 5) + 1\n\t\t\tcdr.Group = next\n\t\t\tgrp[cdr.Callid] = cdr.Group\n\t\t}\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(w, \"rows.Scan() = %v\", err)\n\t\t}\n\t\tp.List = append(p.List, cdr)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"rows.Err() = %v\", err)\n\t}\n\n\tp.Prev = page - 1\n\tif p.Prev < 1 {\n\t\tp.Prev = 1\n\t}\n\tp.Next = page + 1\n\n\terr = t.Execute(w, p)\n\tif err != nil {\n\t\tfmt.Fprintf(w, \"%v\", err)\n\t\treturn\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package cloudtest\n\nimport (\n\t\"github.com\/aws\/aws-sdk-go\/service\/lambda\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ stackLambdaLiteralSelector returns a lambda function\ntype stackLambdaLiteralSelector struct {\n\tliteralName string\n}\n\nfunc (slls *stackLambdaLiteralSelector) Select(t CloudTest) (*lambda.GetFunctionOutput, error) {\n\toutput := cache.getFunction(t, slls.literalName)\n\tif output == nil {\n\t\treturn nil, errors.Errorf(\"Failed to find named function: %s\", slls.literalName)\n\t}\n\treturn output, nil\n}\n\n\/\/ NewLambdaLiteralSelector returns a new LambdaSelector that just uses\n\/\/ the hardcoded name\nfunc NewLambdaLiteralSelector(functionName string) LambdaSelector {\n\treturn &stackLambdaLiteralSelector{\n\t\tliteralName: functionName,\n\t}\n}\n\n\/\/ stackLambdasSelector returns a lambda function\ntype stackLambdasSelector struct {\n\tstackName    string\n\tjmesSelector string\n}\n\nfunc (sls *stackLambdasSelector) Select(t CloudTest) (*lambda.GetFunctionOutput, error) {\n\n\tfunctionOutput := cache.getStackFunction(t, sls.stackName, sls.jmesSelector)\n\tif functionOutput == nil {\n\t\treturn nil, errors.Errorf(\"Failed to find AWS Laambda in stack %s for selector: %s\",\n\t\t\tsls.stackName,\n\t\t\tsls.jmesSelector)\n\t}\n\treturn functionOutput, nil\n}\n\n\/\/ NewStackLambdaSelector returns a new LambdaSelector using the jmesSelector\n\/\/ expression against all GetFunctionOutputs for that lambda function\nfunc NewStackLambdaSelector(stackName string, jmesSelector string) LambdaSelector {\n\treturn &stackLambdasSelector{\n\t\tstackName:    stackName,\n\t\tjmesSelector: jmesSelector,\n\t}\n}\n<commit_msg>Correct typo<commit_after>package cloudtest\n\nimport (\n\t\"github.com\/aws\/aws-sdk-go\/service\/lambda\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ stackLambdaLiteralSelector returns a lambda function\ntype stackLambdaLiteralSelector struct {\n\tliteralName string\n}\n\nfunc (slls *stackLambdaLiteralSelector) Select(t CloudTest) (*lambda.GetFunctionOutput, error) {\n\toutput := cache.getFunction(t, slls.literalName)\n\tif output == nil {\n\t\treturn nil, errors.Errorf(\"Failed to find named function: %s\", slls.literalName)\n\t}\n\treturn output, nil\n}\n\n\/\/ NewLambdaLiteralSelector returns a new LambdaSelector that just uses\n\/\/ the hardcoded name\nfunc NewLambdaLiteralSelector(functionName string) LambdaSelector {\n\treturn &stackLambdaLiteralSelector{\n\t\tliteralName: functionName,\n\t}\n}\n\n\/\/ stackLambdasSelector returns a lambda function\ntype stackLambdasSelector struct {\n\tstackName    string\n\tjmesSelector string\n}\n\nfunc (sls *stackLambdasSelector) Select(t CloudTest) (*lambda.GetFunctionOutput, error) {\n\n\tfunctionOutput := cache.getStackFunction(t, sls.stackName, sls.jmesSelector)\n\tif functionOutput == nil {\n\t\treturn nil, errors.Errorf(\"Failed to find AWS Lambda in stack %s for selector: %s\",\n\t\t\tsls.stackName,\n\t\t\tsls.jmesSelector)\n\t}\n\treturn functionOutput, nil\n}\n\n\/\/ NewStackLambdaSelector returns a new LambdaSelector using the jmesSelector\n\/\/ expression against all GetFunctionOutputs for that lambda function\nfunc NewStackLambdaSelector(stackName string, jmesSelector string) LambdaSelector {\n\treturn &stackLambdasSelector{\n\t\tstackName:    stackName,\n\t\tjmesSelector: jmesSelector,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gstruct_test\n\nimport (\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gstruct\"\n)\n\nvar _ = Describe(\"Struct\", func() {\n\tallFields := struct{ A, B string }{\"a\", \"b\"}\n\tmissingFields := struct{ A string }{\"a\"}\n\textraFields := struct{ A, B, C string }{\"a\", \"b\", \"c\"}\n\temptyFields := struct{ A, B string }{}\n\n\tIt(\"should strictly match all fields\", func() {\n\t\tm := MatchAllFields(Fields{\n\t\t\t\"B\": Equal(\"b\"),\n\t\t\t\"A\": Equal(\"a\"),\n\t\t})\n\t\tExpect(allFields).Should(m, \"should match all fields\")\n\t\tExpect(missingFields).ShouldNot(m, \"should fail with missing fields\")\n\t\tExpect(extraFields).ShouldNot(m, \"should fail with extra fields\")\n\t\tExpect(emptyFields).ShouldNot(m, \"should fail with empty fields\")\n\n\t\tm = MatchAllFields(Fields{\n\t\t\t\"A\": Equal(\"a\"),\n\t\t\t\"B\": Equal(\"fail\"),\n\t\t})\n\t\tExpect(allFields).ShouldNot(m, \"should run nested matchers\")\n\t})\n\n\tIt(\"should handle empty structs\", func() {\n\t\tm := MatchAllFields(Fields{})\n\t\tExpect(struct{}{}).Should(m, \"should handle empty structs\")\n\t\tExpect(allFields).ShouldNot(m, \"should fail with extra fields\")\n\t})\n\n\tIt(\"should ignore missing fields\", func() {\n\t\tm := MatchFields(IgnoreMissing, Fields{\n\t\t\t\"B\": Equal(\"b\"),\n\t\t\t\"A\": Equal(\"a\"),\n\t\t})\n\t\tExpect(allFields).Should(m, \"should match all fields\")\n\t\tExpect(missingFields).Should(m, \"should ignore missing fields\")\n\t\tExpect(extraFields).ShouldNot(m, \"should fail with extra fields\")\n\t\tExpect(emptyFields).ShouldNot(m, \"should fail with empty fields\")\n\t})\n\n\tIt(\"should ignore extra fields\", func() {\n\t\tm := MatchFields(IgnoreExtras, Fields{\n\t\t\t\"B\": Equal(\"b\"),\n\t\t\t\"A\": Equal(\"a\"),\n\t\t})\n\t\tExpect(allFields).Should(m, \"should match all fields\")\n\t\tExpect(missingFields).ShouldNot(m, \"should fail with missing fields\")\n\t\tExpect(extraFields).Should(m, \"should ignore extra fields\")\n\t\tExpect(emptyFields).ShouldNot(m, \"should fail with empty fields\")\n\t})\n\n\tIt(\"should ignore missing and extra fields\", func() {\n\t\tm := MatchFields(IgnoreMissing|IgnoreExtras, Fields{\n\t\t\t\"B\": Equal(\"b\"),\n\t\t\t\"A\": Equal(\"a\"),\n\t\t})\n\t\tExpect(allFields).Should(m, \"should match all fields\")\n\t\tExpect(missingFields).Should(m, \"should ignore missing fields\")\n\t\tExpect(extraFields).Should(m, \"should ignore extra fields\")\n\t\tExpect(emptyFields).ShouldNot(m, \"should fail with empty fields\")\n\n\t\tm = MatchFields(IgnoreMissing|IgnoreExtras, Fields{\n\t\t\t\"A\": Equal(\"a\"),\n\t\t\t\"B\": Equal(\"fail\"),\n\t\t})\n\t\tExpect(allFields).ShouldNot(m, \"should run nested matchers\")\n\t})\n})\n<commit_msg>add analogous tests to fields_test.go<commit_after>package gstruct_test\n\nimport (\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gstruct\"\n)\n\nvar _ = Describe(\"Struct\", func() {\n\tallFields := struct{ A, B string }{\"a\", \"b\"}\n\tmissingFields := struct{ A string }{\"a\"}\n\textraFields := struct{ A, B, C string }{\"a\", \"b\", \"c\"}\n\temptyFields := struct{ A, B string }{}\n\n\tIt(\"should strictly match all fields\", func() {\n\t\tm := MatchAllFields(Fields{\n\t\t\t\"B\": Equal(\"b\"),\n\t\t\t\"A\": Equal(\"a\"),\n\t\t})\n\t\tExpect(allFields).Should(m, \"should match all fields\")\n\t\tExpect(missingFields).ShouldNot(m, \"should fail with missing fields\")\n\t\tExpect(extraFields).ShouldNot(m, \"should fail with extra fields\")\n\t\tExpect(emptyFields).ShouldNot(m, \"should fail with empty fields\")\n\n\t\tm = MatchAllFields(Fields{\n\t\t\t\"A\": Equal(\"a\"),\n\t\t\t\"B\": Equal(\"fail\"),\n\t\t})\n\t\tExpect(allFields).ShouldNot(m, \"should run nested matchers\")\n\t})\n\n\tIt(\"should handle empty structs\", func() {\n\t\tm := MatchAllFields(Fields{})\n\t\tExpect(struct{}{}).Should(m, \"should handle empty structs\")\n\t\tExpect(allFields).ShouldNot(m, \"should fail with extra fields\")\n\t})\n\n\tIt(\"should ignore missing fields\", func() {\n\t\tm := MatchFields(IgnoreMissing, Fields{\n\t\t\t\"B\": Equal(\"b\"),\n\t\t\t\"A\": Equal(\"a\"),\n\t\t})\n\t\tExpect(allFields).Should(m, \"should match all fields\")\n\t\tExpect(missingFields).Should(m, \"should ignore missing fields\")\n\t\tExpect(extraFields).ShouldNot(m, \"should fail with extra fields\")\n\t\tExpect(emptyFields).ShouldNot(m, \"should fail with empty fields\")\n\t})\n\n\tIt(\"should ignore extra fields\", func() {\n\t\tm := MatchFields(IgnoreExtras, Fields{\n\t\t\t\"B\": Equal(\"b\"),\n\t\t\t\"A\": Equal(\"a\"),\n\t\t})\n\t\tExpect(allFields).Should(m, \"should match all fields\")\n\t\tExpect(missingFields).ShouldNot(m, \"should fail with missing fields\")\n\t\tExpect(extraFields).Should(m, \"should ignore extra fields\")\n\t\tExpect(emptyFields).ShouldNot(m, \"should fail with empty fields\")\n\t})\n\n\tIt(\"should ignore missing and extra fields\", func() {\n\t\tm := MatchFields(IgnoreMissing|IgnoreExtras, Fields{\n\t\t\t\"B\": Equal(\"b\"),\n\t\t\t\"A\": Equal(\"a\"),\n\t\t})\n\t\tExpect(allFields).Should(m, \"should match all fields\")\n\t\tExpect(missingFields).Should(m, \"should ignore missing fields\")\n\t\tExpect(extraFields).Should(m, \"should ignore extra fields\")\n\t\tExpect(emptyFields).ShouldNot(m, \"should fail with empty fields\")\n\n\t\tm = MatchFields(IgnoreMissing|IgnoreExtras, Fields{\n\t\t\t\"A\": Equal(\"a\"),\n\t\t\t\"B\": Equal(\"fail\"),\n\t\t})\n\t\tExpect(allFields).ShouldNot(m, \"should run nested matchers\")\n\t})\n\n\tIt(\"should produce sensible error messages\", func() {\n\t\tm := MatchAllFields(Fields{\n\t\t\t\"B\": Equal(\"b\"),\n\t\t\t\"A\": Equal(\"a\"),\n\t\t})\n\n\t\tactual := struct{ A, C string }{A: \"b\", C: \"c\"}\n\n\t\t\/\/Because the order of the constituent errors can't be guaranteed,\n\t\t\/\/we do a number of checks to make sure everything's included\n\t\tm.Match(actual)\n\t\tExpect(m.FailureMessage(actual)).Should(HavePrefix(\n\t\t\t\"Expected\\n    <string>: \\nto match fields: {\\n\",\n\t\t))\n\t\tExpect(m.FailureMessage(actual)).Should(ContainSubstring(\n\t\t\t\".A:\\n\tExpected\\n\t    <string>: b\\n\tto equal\\n\t    <string>: a\\n\",\n\t\t))\n\t\tExpect(m.FailureMessage(actual)).Should(ContainSubstring(\n\t\t\t\"missing expected field B\\n\",\n\t\t))\n\t\tExpect(m.FailureMessage(actual)).Should(ContainSubstring(\n\t\t\t\".C:\\n\tunexpected field C: {A:b C:c}\",\n\t\t))\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/jkomoros\/sudoku\"\n)\n\ntype model struct {\n\tgrid *sudoku.Grid\n}\n\n\/\/TODO: rename Mutator to command\ntype command interface {\n\tApply(m *model)\n\tUndo(m *model)\n}\n\ntype markCommand struct {\n\trow, col    int\n\tmarksToggle map[int]bool\n}\n\ntype numberCommand struct {\n\trow, col int\n\tnumber   int\n\t\/\/Necessary so we can undo.\n\toldNumber int\n}\n\nfunc (m *model) SetGrid(grid *sudoku.Grid) {\n\tm.grid = grid\n}\n\nfunc (m *model) SetMarks(row, col int, marksToggle map[int]bool) {\n\tcommand := m.newMarkCommand(row, col, marksToggle)\n\tcommand.Apply(m)\n}\n\nfunc (m *model) newMarkCommand(row, col int, marksToggle map[int]bool) *markCommand {\n\t\/\/Only keep marks in the toggle that won't be a no-op\n\tnewMarksToggle := make(map[int]bool)\n\n\tcell := m.grid.Cell(row, col)\n\n\tif cell == nil {\n\t\treturn nil\n\t}\n\tfor key, value := range marksToggle {\n\t\tif cell.Mark(key) != value {\n\t\t\t\/\/Good, keep it\n\t\t\tnewMarksToggle[key] = value\n\t\t}\n\t}\n\n\tif len(newMarksToggle) == 0 {\n\t\t\/\/The command would be a no op!\n\t\treturn nil\n\t}\n\n\treturn &markCommand{row, col, newMarksToggle}\n}\n\nfunc (m *model) SetNumber(row, col int, num int) {\n\t\/\/TODO: this should also only add an action if the specified cell is not already num.\n\tcell := m.grid.Cell(row, col)\n\tif cell == nil {\n\t\treturn\n\t}\n\tmutator := &numberCommand{row, col, num, cell.Number()}\n\tmutator.Apply(m)\n}\n\n\/\/TODO: implement model.new{Mark|Number}Mutator, which only return a\n\/\/modelMutator if it wouldn't be a no-op. Then, test that they return nil if\n\/\/it would be a no op, including omitting marks that would be a no op.\n\nfunc (m *markCommand) Apply(model *model) {\n\tcell := model.grid.Cell(m.row, m.col)\n\tif cell == nil {\n\t\treturn\n\t}\n\tfor key, value := range m.marksToggle {\n\t\tcell.SetMark(key, value)\n\t}\n}\n\nfunc (m *markCommand) Undo(model *model) {\n\tcell := model.grid.Cell(m.row, m.col)\n\tif cell == nil {\n\t\treturn\n\t}\n\tfor key, value := range m.marksToggle {\n\t\t\/\/Set the opposite since we're undoing.\n\t\tcell.SetMark(key, !value)\n\t}\n}\n\nfunc (n *numberCommand) Apply(model *model) {\n\tcell := model.grid.Cell(n.row, n.col)\n\tif cell == nil {\n\t\treturn\n\t}\n\tcell.SetNumber(n.number)\n}\n\nfunc (n *numberCommand) Undo(model *model) {\n\tcell := model.grid.Cell(n.row, n.col)\n\tif cell == nil {\n\t\treturn\n\t}\n\tcell.SetNumber(n.oldNumber)\n}\n<commit_msg>Fixed potentil nil method error<commit_after>package main\n\nimport (\n\t\"github.com\/jkomoros\/sudoku\"\n)\n\ntype model struct {\n\tgrid *sudoku.Grid\n}\n\n\/\/TODO: rename Mutator to command\ntype command interface {\n\tApply(m *model)\n\tUndo(m *model)\n}\n\ntype markCommand struct {\n\trow, col    int\n\tmarksToggle map[int]bool\n}\n\ntype numberCommand struct {\n\trow, col int\n\tnumber   int\n\t\/\/Necessary so we can undo.\n\toldNumber int\n}\n\nfunc (m *model) SetGrid(grid *sudoku.Grid) {\n\tm.grid = grid\n}\n\nfunc (m *model) SetMarks(row, col int, marksToggle map[int]bool) {\n\tcommand := m.newMarkCommand(row, col, marksToggle)\n\tif command == nil {\n\t\treturn\n\t}\n\tcommand.Apply(m)\n}\n\nfunc (m *model) newMarkCommand(row, col int, marksToggle map[int]bool) *markCommand {\n\t\/\/Only keep marks in the toggle that won't be a no-op\n\tnewMarksToggle := make(map[int]bool)\n\n\tcell := m.grid.Cell(row, col)\n\n\tif cell == nil {\n\t\treturn nil\n\t}\n\tfor key, value := range marksToggle {\n\t\tif cell.Mark(key) != value {\n\t\t\t\/\/Good, keep it\n\t\t\tnewMarksToggle[key] = value\n\t\t}\n\t}\n\n\tif len(newMarksToggle) == 0 {\n\t\t\/\/The command would be a no op!\n\t\treturn nil\n\t}\n\n\treturn &markCommand{row, col, newMarksToggle}\n}\n\nfunc (m *model) SetNumber(row, col int, num int) {\n\t\/\/TODO: this should also only add an action if the specified cell is not already num.\n\tcell := m.grid.Cell(row, col)\n\tif cell == nil {\n\t\treturn\n\t}\n\tmutator := &numberCommand{row, col, num, cell.Number()}\n\tmutator.Apply(m)\n}\n\n\/\/TODO: implement model.new{Mark|Number}Mutator, which only return a\n\/\/modelMutator if it wouldn't be a no-op. Then, test that they return nil if\n\/\/it would be a no op, including omitting marks that would be a no op.\n\nfunc (m *markCommand) Apply(model *model) {\n\tcell := model.grid.Cell(m.row, m.col)\n\tif cell == nil {\n\t\treturn\n\t}\n\tfor key, value := range m.marksToggle {\n\t\tcell.SetMark(key, value)\n\t}\n}\n\nfunc (m *markCommand) Undo(model *model) {\n\tcell := model.grid.Cell(m.row, m.col)\n\tif cell == nil {\n\t\treturn\n\t}\n\tfor key, value := range m.marksToggle {\n\t\t\/\/Set the opposite since we're undoing.\n\t\tcell.SetMark(key, !value)\n\t}\n}\n\nfunc (n *numberCommand) Apply(model *model) {\n\tcell := model.grid.Cell(n.row, n.col)\n\tif cell == nil {\n\t\treturn\n\t}\n\tcell.SetNumber(n.number)\n}\n\nfunc (n *numberCommand) Undo(model *model) {\n\tcell := model.grid.Cell(n.row, n.col)\n\tif cell == nil {\n\t\treturn\n\t}\n\tcell.SetNumber(n.oldNumber)\n}\n<|endoftext|>"}
{"text":"<commit_before>package photon\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/as27\/govuegui\"\n\t\"github.com\/as27\/govuegui\/gui\/photon\/src\/pkg\/photoncss\"\n\t\"github.com\/as27\/govuegui\/gui\/photon\/src\/pkg\/photonwoff\"\n)\n\nvar Template = govuegui.GuiTemplate{\n\tCSSHandler: photoncss.Handler,\n\tCustomCSS: `#govuegui{\n        max-width:1200px;\n        margin: auto;\n    }`,\n\tFiles: map[string]func(w http.ResponseWriter, r *http.Request){\n\t\t\"photon-entypo.woff\": photonwoff.Handler,\n\t},\n\tBody: `<body> \n        <div id=\"govuegui\" class=\"window\">\n\t    <header class=\"toolbar toolbar-header\">\n\t\t<h1 class=\"title\">{{appTitle}}<\/h1>\n\n        <div class=\"toolbar-actions\">\n            <div class=\"btn-group\">\n                <router-link\n                    v-for=\"form in data.Forms\"\n                    active-class=\"active\"\n                    class=\"btn btn-default\"\n                    tag=\"button\"\n                    :to=\"{name: 'gvgform', params: { formid: form.id}}\">\n                    <span class=\"icon icon-menu icon-text\"><\/span>\n                    {{form.id}}<\/router-link>\n            <\/div>\n        <\/div>\n\n\t\t<\/header>\t\n            <router-view :data=data :forms=forms ><\/router-view>\n        <footer class=\"toolbar toolbar-footer\">\n\t\t<h1 class=\"title\">\n        <strong>govuigui<\/strong> \n        by <a href=\"https:\/\/as27.github.io\/\" target=\"_blank\">Andreas Schr&ouml;pfer<\/a>\n      | <a href=\"https:\/\/github.com\/as27\/govuegui\" target=\"_blank\">govuigui github page<\/a>\n\t\t<\/h1><\/footer>\n        <\/div>\n    <\/body>\n`,\n\tGvgForms: `\n    <div class=\"window-content\">\n    <div class=\"pane-group\">\n      <div class=\"pane-sm sidebar\">\n        <nav class=\"nav-group\">\n            <h5 class=\"nav-group-title\">Forms<\/h5>\n            <router-link\n                v-for=\"form in data.Forms\"\n                active-class=\"active\"\n                class=\"nav-group-item\"\n                :to=\"{name: 'gvgform', params: { formid: form.id}}\">\n                <span class=\"icon icon-home\"><\/span>\n                {{form.id}}<\/router-link>\n        <\/nav>\n        \n      <\/div>\n      <div class=\"pane\">\n            <router-view :data=data :form=forms[formid] :formid=formid><\/router-view>\n      <\/div>\n    <\/div>\n  <\/div>\n  `,\n\n\tGvgForm: `<div><div class=\"tab-group\">\n    <router-link v-for=\"box in form.Boxes\"\n        active-class=\"active\"\n        class=\"tab-item\"\n        tag=\"div\"\n        :to=\"{ name: 'gvgbox', params: { boxid: box.id}}\">\n        {{box.id}}\n    <\/router-link>\n<\/div>\n    <gvgbox :box=myBox :data=data><\/gvgbox>\n    <button class=\"btn btn-large btn-primary\" @click=\"saveData\">Submit<\/button>\n    <\/div>`,\n\n\tGvgBox: `<form class=\"padded-more\">\n    <h2>{{box.id}}<\/h2>\n            <gvgelement \n                v-for=\"element in box.elements\"\n                :element=element \n                :data=data><\/gvgelement>\n    <\/form>\n   `,\n\n\tGvgElement: `\n    <div class=\"form-group\">\n        <label v-if=\"renderLabel\" class=\"label\">{{element.label}}<\/label>\n        <component :is=element.type :element=element :data=data v-model=\"data.Data.data[element.id]\"><\/component>\n    <\/div>`,\n\tGvgButton: `<div><br><button class=\"btn btn-large btn-primary\" @click=\"callAction\">{{element.label}}<\/button><br><\/div>`,\n\n\tGvgList: `<div class=\"text\">\n   <ul>\n   <li v-for=\"litem in data.Data.data[element.id]\">{{litem}}<\/li>\n   <\/ul> \n    <\/div>`,\n\tGvgDropdown: `<div>\n    <select v-model=\"data.Data.data[element.id]\" class=\"form-control\">\n    <option v-for=\"oitem in element.options\" v-bind:value=\"oitem.Option\">{{oitem.Values[0]}}<\/option>\n    <\/select>\n    <\/div>`,\n\n\tGvgTable: `<div class=\"text\">\n    <table class=\"table is-narrow\">\n    <thead>\n    <tr><th v-for=\"cell in data.Data.data[element.id][0]\">{{cell}}<\/th><\/tr>\n    <\/thead>\n    <tr v-for=\"(row,index) in data.Data.data[element.id]\" v-if=\"index > 0\">\n    <td v-for=\"cell in row\">{{cell}}<\/td>\n    <\/tr>\n    <\/table>\n    <\/div>`,\n\tGvgText: `<div class=\"text\" v-html=\"data.Data.data[element.id]\"><\/div>`,\n\n\tGvgTextarea: `<textarea class=\"form-control\" v-model=\"data.Data.data[element.id]\"><\/textarea>`,\n\n\tGvgInput: `<input class=\"form-control\" type=\"text\" v-model=\"data.Data.data[element.id]\">`,\n}\n<commit_msg>photon template changed<commit_after>package photon\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/as27\/govuegui\"\n\t\"github.com\/as27\/govuegui\/gui\/photon\/src\/pkg\/photoncss\"\n\t\"github.com\/as27\/govuegui\/gui\/photon\/src\/pkg\/photonwoff\"\n)\n\nvar Template = govuegui.GuiTemplate{\n\tCSSHandler: photoncss.Handler,\n\tCustomCSS: `#govuegui{\n        max-width:1200px;\n        margin: auto;\n    }`,\n\tFiles: map[string]func(w http.ResponseWriter, r *http.Request){\n\t\t\"photon-entypo.woff\": photonwoff.Handler,\n\t},\n\tBody: `<body> \n        <div id=\"govuegui\" class=\"window\">\n\t    <header class=\"toolbar toolbar-header\">\n\t\t<h1 class=\"title\">{{appTitle}}<\/h1>\n\n        <div class=\"toolbar-actions\">\n            <div class=\"btn-group\">\n                <router-link\n                    v-for=\"form in data.Forms\"\n                    active-class=\"active\"\n                    class=\"btn btn-default\"\n                    tag=\"button\"\n                    :to=\"{name: 'gvgform', params: { formid: form.id}}\">\n                    <span class=\"icon icon-menu icon-text\"><\/span>\n                    {{form.id}}<\/router-link>\n            <\/div>\n        <\/div>\n\n\t\t<\/header>\t\n            <router-view :data=data :forms=forms ><\/router-view>\n        <footer class=\"toolbar toolbar-footer\">\n\t\t<h1 class=\"title\">\n        <strong>govuigui<\/strong> \n        by <a href=\"https:\/\/as27.github.io\/\" target=\"_blank\">Andreas Schr&ouml;pfer<\/a>\n      | <a href=\"https:\/\/github.com\/as27\/govuegui\" target=\"_blank\">govuigui github page<\/a>\n\t\t<\/h1><\/footer>\n        <\/div>\n    <\/body>\n`,\n\tGvgForms: `\n    <div class=\"window-content\">\n            <router-view :data=data :form=forms[formid] :formid=formid><\/router-view>\n     <\/div>\n  `,\n\n\tGvgForm: `\n     <div class=\"pane-group\">\n      <div class=\"pane-sm sidebar\">\n        <nav class=\"nav-group\">\n            <h5 class=\"nav-group-title\">Boxes<\/h5>\n            <router-link\n                v-for=\"box in form.Boxes\"\n                active-class=\"active\"\n                class=\"nav-group-item\"\n                :to=\"{ name: 'gvgbox', params: { boxid: box.id}}\">\n                <span class=\"icon icon-home\"><\/span>\n                {{box.id}}<\/router-link>\n        <\/nav>\n      <\/div>\n      <div class=\"pane\">\n        <gvgbox :box=myBox :data=data><\/gvgbox>\n        <button class=\"btn btn-large btn-primary\" @click=\"saveData\">Submit<\/button>\n      <\/div>\n    <\/div>\n    `,\n\n\tGvgBox: `<form class=\"padded-more\">\n    <h2>{{box.id}}<\/h2>\n            <gvgelement \n                v-for=\"element in box.elements\"\n                :element=element \n                :data=data><\/gvgelement>\n    <\/form>\n   `,\n\n\tGvgElement: `\n    <div class=\"form-group\">\n        <label v-if=\"renderLabel\" class=\"label\">{{element.label}}<\/label>\n        <component :is=element.type :element=element :data=data v-model=\"data.Data.data[element.id]\"><\/component>\n    <\/div>`,\n\tGvgButton: `<div><br><button class=\"btn btn-large btn-primary\" @click=\"callAction\">{{element.label}}<\/button><br><\/div>`,\n\n\tGvgList: `<div class=\"text\">\n   <ul>\n   <li v-for=\"litem in data.Data.data[element.id]\">{{litem}}<\/li>\n   <\/ul> \n    <\/div>`,\n\tGvgDropdown: `<div>\n    <select v-model=\"data.Data.data[element.id]\" class=\"form-control\">\n    <option v-for=\"oitem in element.options\" v-bind:value=\"oitem.Option\">{{oitem.Values[0]}}<\/option>\n    <\/select>\n    <\/div>`,\n\n\tGvgTable: `<div class=\"text\">\n    <table class=\"table is-narrow\">\n    <thead>\n    <tr><th v-for=\"cell in data.Data.data[element.id][0]\">{{cell}}<\/th><\/tr>\n    <\/thead>\n    <tr v-for=\"(row,index) in data.Data.data[element.id]\" v-if=\"index > 0\">\n    <td v-for=\"cell in row\">{{cell}}<\/td>\n    <\/tr>\n    <\/table>\n    <\/div>`,\n\tGvgText: `<div class=\"text\" v-html=\"data.Data.data[element.id]\"><\/div>`,\n\n\tGvgTextarea: `<textarea class=\"form-control\" v-model=\"data.Data.data[element.id]\"><\/textarea>`,\n\n\tGvgInput: `<input class=\"form-control\" type=\"text\" v-model=\"data.Data.data[element.id]\">`,\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/raintreeinc\/knowledgebase\/kbserver\/pgdb\"\n\n\t_ \"github.com\/lib\/pq\"\n)\n\nvar (\n\tdatabase = flag.String(\"database\", \"user=root dbname=knowledgebase sslmode=disable\", \"database `params`\")\n)\n\nfunc main() {\n\tflag.Parse()\n\tif os.Getenv(\"DATABASE\") != \"\" {\n\t\t*database = os.Getenv(\"DATABASE\")\n\t}\n\n\tditamap := os.Getenv(\"DITAMAP\")\n\n\t\/\/ Load database\n\tdb, err := pgdb.New(*database)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tusers, err := db.Users().List()\n\tlog.Println(err)\n\tfor _, user := range users {\n\t\tlog.Printf(\"%+v\\n\", user)\n\t}\n\n\t\/\/user, err := db.Users().ByID(\"usernaem\")\n}\n<commit_msg>Remove unneeded var.<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/raintreeinc\/knowledgebase\/kbserver\/pgdb\"\n\n\t_ \"github.com\/lib\/pq\"\n)\n\nvar (\n\tdatabase = flag.String(\"database\", \"user=root dbname=knowledgebase sslmode=disable\", \"database `params`\")\n)\n\nfunc main() {\n\tflag.Parse()\n\tif os.Getenv(\"DATABASE\") != \"\" {\n\t\t*database = os.Getenv(\"DATABASE\")\n\t}\n\n\t\/\/ Load database\n\tdb, err := pgdb.New(*database)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tusers, err := db.Users().List()\n\tlog.Println(err)\n\tfor _, user := range users {\n\t\tlog.Printf(\"%+v\\n\", user)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCommand lmdb_stat is a clone of mdb_stat that displays the status an LMDB\nenvironment.\n\nCommand line flags mirror the flags for the original program.  For information\nabout, run lmdb_stat with the -h flag.\n\n\tlmdb_stat -h\n*\/\npackage main\n\nimport \"C\"\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n\n\t\"github.com\/bmatsuo\/lmdb-go\/exp\/lmdbscan\"\n\t\"github.com\/bmatsuo\/lmdb-go\/internal\/lmdbcmd\"\n\t\"github.com\/bmatsuo\/lmdb-go\/lmdb\"\n)\n\nfunc main() {\n\topt := &Options{}\n\tflag.BoolVar(&opt.PrintInfo, \"e\", false, \"Display information about the database environment\")\n\tflag.BoolVar(&opt.PrintFree, \"f\", false, \"Display freelist information\")\n\tflag.BoolVar(&opt.PrintFreeSummary, \"ff\", false, \"Display freelist information\")\n\tflag.BoolVar(&opt.PrintFreeFull, \"fff\", false, \"Display freelist information\")\n\tflag.BoolVar(&opt.PrintReaders, \"r\", false, strings.Join([]string{\n\t\t\"Display information about the environment reader table.\",\n\t\t\"Shows the process ID, thread ID, and transaction ID for each active reader slot.\",\n\t}, \"  \"))\n\tflag.BoolVar(&opt.PrintReadersCheck, \"rr\", false, strings.Join([]string{\n\t\t\"Implies -r.\",\n\t\t\"Check for stale entries in the reader table and clear them.\",\n\t\t\"The reader table is printed again after the check is performed.\",\n\t}, \"  \"))\n\tflag.BoolVar(&opt.PrintStatAll, \"a\", false, \"Display the status of all databases in the environment\")\n\tflag.StringVar(&opt.PrintStatSub, \"s\", \"\", \"Display the status of a specific subdatabase.\")\n\tflag.BoolVar(&opt.Debug, \"D\", false, \"print debug information\")\n\tflag.Parse()\n\n\tlmdbcmd.PrintVersion()\n\n\tif opt.PrintStatAll && opt.PrintStatSub != \"\" {\n\t\tlog.Fatal(\"only one of -a and -s may be provided\")\n\t}\n\n\tif flag.NArg() > 1 {\n\t\tlog.Fatalf(\"too many argument provided\")\n\t}\n\tif flag.NArg() == 0 {\n\t\tlog.Fatalf(\"missing argument\")\n\t}\n\topt.Path = flag.Arg(0)\n\n\tvar failed bool\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tif opt.Debug {\n\t\t\t\tpanic(e)\n\t\t\t}\n\t\t\tlog.Print(e)\n\t\t\tfailed = true\n\t\t}\n\t\tif failed {\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\terr := doMain(opt)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tfailed = true\n\t}\n}\n\n\/\/ Options contains all the configuration for an lmdb_stat command including\n\/\/ command line arguments.\ntype Options struct {\n\tPath string\n\n\tPrintInfo         bool\n\tPrintReaders      bool\n\tPrintReadersCheck bool\n\tPrintFree         bool\n\tPrintFreeSummary  bool\n\tPrintFreeFull     bool\n\tPrintStatAll      bool\n\tPrintStatSub      string\n\n\tDebug bool\n}\n\nfunc doMain(opt *Options) error {\n\tenv, err := lmdb.NewEnv()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif opt.PrintStatAll || opt.PrintStatSub != \"\" {\n\t\terr = env.SetMaxDBs(1)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr = env.Open(opt.Path, lmdbcmd.OpenFlag(), 0644)\n\tdefer env.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif opt.PrintInfo {\n\t\terr = doPrintInfo(env, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif opt.PrintReaders || opt.PrintReadersCheck {\n\t\terr = doPrintReaders(env, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif opt.PrintFree || opt.PrintFreeSummary || opt.PrintFreeFull {\n\t\terr = doPrintFree(env, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = doPrintStatRoot(env, opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif opt.PrintStatAll {\n\t\terr = doPrintStatAll(env, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if opt.PrintStatSub != \"\" {\n\t\terr = doPrintStatDB(env, opt.PrintStatSub, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc doPrintInfo(env *lmdb.Env, opt *Options) error {\n\tinfo, err := env.Info()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpagesize := os.Getpagesize()\n\n\tfmt.Println(\"Environment Info\")\n\tfmt.Println(\"  Map address:\", nil)\n\tfmt.Println(\"  Map size:\", info.MapSize)\n\tfmt.Println(\"  Page size:\", pagesize)\n\tfmt.Println(\"  Max pages:\", info.MapSize\/int64(pagesize))\n\tfmt.Println(\"  Number of pages used:\", info.LastPNO+1)\n\tfmt.Println(\"  Last transaction ID:\", info.LastTxnID)\n\tfmt.Println(\"  Max readers:\", info.MaxReaders)\n\tfmt.Println(\"  Number of readers used:\", info.NumReaders)\n\n\treturn nil\n}\n\nfunc doPrintReaders(env *lmdb.Env, opt *Options) error {\n\tfmt.Println(\"Reader Table Status\")\n\tw := bufio.NewWriter(os.Stdout)\n\terr := printReaders(env, w, opt)\n\tif err == nil {\n\t\terr = w.Flush()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif opt.PrintReadersCheck {\n\t\tnumstale, err := env.ReaderCheck()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"  %d stale readers cleared.\\n\", numstale)\n\t\terr = printReaders(env, w, opt)\n\t\tif err == nil {\n\t\t\terr = w.Flush()\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc printReaders(env *lmdb.Env, w io.Writer, opt *Options) error {\n\treturn env.ReaderList(func(msg string) error {\n\t\t_, err := fmt.Fprint(w, msg)\n\t\treturn err\n\t})\n}\n\nfunc doPrintFree(env *lmdb.Env, opt *Options) error {\n\treturn env.View(func(txn *lmdb.Txn) (err error) {\n\t\ttxn.RawRead = true\n\n\t\tfmt.Println(\"Freelist status\")\n\n\t\tstat, err := txn.Stat(0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprintStat(stat, opt)\n\n\t\tvar numpages int64\n\t\ts := lmdbscan.New(txn, 0)\n\t\tdefer s.Close()\n\t\tfor s.Scan() {\n\t\t\tkey := s.Key()\n\t\t\tdata := s.Val()\n\t\t\ttxid := *(*C.size_t)(unsafe.Pointer(&key[0]))\n\t\t\tipages := int64(*(*C.size_t)(unsafe.Pointer(&data[0])))\n\t\t\tnumpages += ipages\n\t\t\tif opt.PrintFreeSummary || opt.PrintFreeFull {\n\t\t\t\tbad := \"\"\n\t\t\t\thdr := reflect.SliceHeader{\n\t\t\t\t\tData: uintptr(unsafe.Pointer(&data[0])),\n\t\t\t\t\tLen:  int(ipages) + 1,\n\t\t\t\t\tCap:  int(ipages) + 1,\n\t\t\t\t}\n\t\t\t\tpages := *(*[]C.size_t)(unsafe.Pointer(&hdr))\n\t\t\t\tpages = pages[1:]\n\t\t\t\tvar span C.size_t\n\t\t\t\tprev := C.size_t(1)\n\t\t\t\tfor i := ipages - 1; i >= 0; i-- {\n\t\t\t\t\tpg := pages[i]\n\t\t\t\t\tif pg < prev {\n\t\t\t\t\t\tbad = \" [bad sequence]\"\n\t\t\t\t\t}\n\t\t\t\t\tprev = pg\n\t\t\t\t\tpg += span\n\t\t\t\t\tfor i >= int64(span) && pages[i-int64(span)] == pg {\n\t\t\t\t\t\tspan++\n\t\t\t\t\t\tpg++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"    Transaction %x, %d pages, maxspan %d%s\\n\", txid, ipages, span, bad)\n\n\t\t\t\tif opt.PrintFreeFull {\n\t\t\t\t\tfor j := ipages - 1; j >= 0; {\n\t\t\t\t\t\tpg := pages[j]\n\t\t\t\t\t\tj--\n\t\t\t\t\t\tspan := C.size_t(1)\n\t\t\t\t\t\tfor j >= 0 && pages[j] == pg+span {\n\t\t\t\t\t\t\tj--\n\t\t\t\t\t\t\tspan++\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif span > 1 {\n\t\t\t\t\t\t\tfmt.Printf(\"     %9x[%d]\\n\", pg, span)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfmt.Printf(\"     %9x\\n\", pg)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\terr = s.Err()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Println(\"  Free pages:\", numpages)\n\n\t\treturn nil\n\t})\n}\n\nfunc doPrintStatRoot(env *lmdb.Env, opt *Options) error {\n\tstat, err := env.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Status of Main DB\")\n\tfmt.Println(\"  Tree depth:\", stat.Depth)\n\tfmt.Println(\"  Branch pages:\", stat.BranchPages)\n\tfmt.Println(\"  Lead pages:\", stat.LeafPages)\n\tfmt.Println(\"  Overflow pages:\", stat.OverflowPages)\n\tfmt.Println(\"  Entries:\", stat.Entries)\n\n\treturn nil\n}\n\nfunc doPrintStatDB(env *lmdb.Env, db string, opt *Options) error {\n\terr := env.View(func(txn *lmdb.Txn) (err error) {\n\t\treturn printStatDB(env, txn, db, opt)\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%v (%s)\", err, db)\n\t}\n\treturn nil\n}\n\nfunc printStatDB(env *lmdb.Env, txn *lmdb.Txn, db string, opt *Options) error {\n\tdbi, err := txn.OpenDBI(db, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer env.CloseDBI(dbi)\n\n\tstat, err := txn.Stat(dbi)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Status of\", db)\n\tprintStat(stat, opt)\n\n\treturn err\n}\n\nfunc printStat(stat *lmdb.Stat, opt *Options) error {\n\tfmt.Println(\"  Tree depth:\", stat.Depth)\n\tfmt.Println(\"  Branch pages:\", stat.BranchPages)\n\tfmt.Println(\"  Lead pages:\", stat.LeafPages)\n\tfmt.Println(\"  Overflow pages:\", stat.OverflowPages)\n\tfmt.Println(\"  Entries:\", stat.Entries)\n\n\treturn nil\n}\n\nfunc doPrintStatAll(env *lmdb.Env, opt *Options) error {\n\treturn env.View(func(txn *lmdb.Txn) (err error) {\n\t\tdbi, err := txn.OpenRoot(0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer env.CloseDBI(dbi)\n\n\t\ts := lmdbscan.New(txn, dbi)\n\t\tdefer s.Close()\n\t\tfor s.Scan() {\n\t\t\terr = printStatDB(env, txn, string(s.Key()), opt)\n\t\t\tif e, ok := err.(*lmdb.OpError); ok {\n\t\t\t\tif e.Op == \"mdb_dbi_open\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%v (%s)\", err, s.Key())\n\t\t\t}\n\t\t}\n\t\treturn s.Err()\n\t})\n}\n<commit_msg>cmd\/lmdb_stat: Fix typos and format flags to be 1:1 with mdb_stat<commit_after>\/*\nCommand lmdb_stat is a clone of mdb_stat that displays the status an LMDB\nenvironment.\n\nCommand line flags mirror the flags for the original program.  For information\nabout, run lmdb_stat with the -h flag.\n\n\tlmdb_stat -h\n*\/\npackage main\n\nimport \"C\"\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"unsafe\"\n\n\t\"github.com\/bmatsuo\/lmdb-go\/exp\/lmdbscan\"\n\t\"github.com\/bmatsuo\/lmdb-go\/internal\/lmdbcmd\"\n\t\"github.com\/bmatsuo\/lmdb-go\/lmdb\"\n)\n\nfunc main() {\n\topt := &Options{}\n\tflag.BoolVar(&opt.PrintInfo, \"e\", false, \"Display information about the database environment\")\n\tflag.BoolVar(&opt.PrintFree, \"f\", false, \"Display freelist information\")\n\tflag.BoolVar(&opt.PrintFreeSummary, \"ff\", false, \"Display freelist information\")\n\tflag.BoolVar(&opt.PrintFreeFull, \"fff\", false, \"Display freelist information\")\n\tflag.BoolVar(&opt.PrintReaders, \"r\", false, strings.Join([]string{\n\t\t\"Display information about the environment reader table.\",\n\t\t\"Shows the process ID, thread ID, and transaction ID for each active reader slot.\",\n\t}, \"  \"))\n\tflag.BoolVar(&opt.PrintReadersCheck, \"rr\", false, strings.Join([]string{\n\t\t\"Implies -r.\",\n\t\t\"Check for stale entries in the reader table and clear them.\",\n\t\t\"The reader table is printed again after the check is performed.\",\n\t}, \"  \"))\n\tflag.BoolVar(&opt.PrintStatAll, \"a\", false, \"Display the status of all databases in the environment\")\n\tflag.StringVar(&opt.PrintStatSub, \"s\", \"\", \"Display the status of a specific subdatabase.\")\n\tflag.BoolVar(&opt.Debug, \"D\", false, \"print debug information\")\n\tflag.Parse()\n\n\tlmdbcmd.PrintVersion()\n\n\tif opt.PrintStatAll && opt.PrintStatSub != \"\" {\n\t\tlog.Fatal(\"only one of -a and -s may be provided\")\n\t}\n\n\tif flag.NArg() > 1 {\n\t\tlog.Fatalf(\"too many argument provided\")\n\t}\n\tif flag.NArg() == 0 {\n\t\tlog.Fatalf(\"missing argument\")\n\t}\n\topt.Path = flag.Arg(0)\n\n\tvar failed bool\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\tif opt.Debug {\n\t\t\t\tpanic(e)\n\t\t\t}\n\t\t\tlog.Print(e)\n\t\t\tfailed = true\n\t\t}\n\t\tif failed {\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\terr := doMain(opt)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\tfailed = true\n\t}\n}\n\n\/\/ Options contains all the configuration for an lmdb_stat command including\n\/\/ command line arguments.\ntype Options struct {\n\tPath string\n\n\tPrintInfo         bool\n\tPrintReaders      bool\n\tPrintReadersCheck bool\n\tPrintFree         bool\n\tPrintFreeSummary  bool\n\tPrintFreeFull     bool\n\tPrintStatAll      bool\n\tPrintStatSub      string\n\n\tDebug bool\n}\n\nfunc doMain(opt *Options) error {\n\tenv, err := lmdb.NewEnv()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif opt.PrintStatAll || opt.PrintStatSub != \"\" {\n\t\terr = env.SetMaxDBs(1)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr = env.Open(opt.Path, lmdbcmd.OpenFlag(), 0644)\n\tdefer env.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif opt.PrintInfo {\n\t\terr = doPrintInfo(env, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif opt.PrintReaders || opt.PrintReadersCheck {\n\t\terr = doPrintReaders(env, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif opt.PrintFree || opt.PrintFreeSummary || opt.PrintFreeFull {\n\t\terr = doPrintFree(env, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = doPrintStatRoot(env, opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif opt.PrintStatAll {\n\t\terr = doPrintStatAll(env, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else if opt.PrintStatSub != \"\" {\n\t\terr = doPrintStatDB(env, opt.PrintStatSub, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc doPrintInfo(env *lmdb.Env, opt *Options) error {\n\tinfo, err := env.Info()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpagesize := os.Getpagesize()\n\n\tfmt.Println(\"Environment Info\")\n\tfmt.Println(\"  Map address:\", nil)\n\tfmt.Println(\"  Map size:\", info.MapSize)\n\tfmt.Println(\"  Page size:\", pagesize)\n\tfmt.Println(\"  Max pages:\", info.MapSize\/int64(pagesize))\n\tfmt.Println(\"  Number of pages used:\", info.LastPNO+1)\n\tfmt.Println(\"  Last transaction ID:\", info.LastTxnID)\n\tfmt.Println(\"  Max readers:\", info.MaxReaders)\n\tfmt.Println(\"  Number of readers used:\", info.NumReaders)\n\n\treturn nil\n}\n\nfunc doPrintReaders(env *lmdb.Env, opt *Options) error {\n\tfmt.Println(\"Reader Table Status\")\n\tw := bufio.NewWriter(os.Stdout)\n\terr := printReaders(env, w, opt)\n\tif err == nil {\n\t\terr = w.Flush()\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif opt.PrintReadersCheck {\n\t\tnumstale, err := env.ReaderCheck()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"  %d stale readers cleared.\\n\", numstale)\n\t\terr = printReaders(env, w, opt)\n\t\tif err == nil {\n\t\t\terr = w.Flush()\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc printReaders(env *lmdb.Env, w io.Writer, opt *Options) error {\n\treturn env.ReaderList(func(msg string) error {\n\t\t_, err := fmt.Fprint(w, msg)\n\t\treturn err\n\t})\n}\n\nfunc doPrintFree(env *lmdb.Env, opt *Options) error {\n\treturn env.View(func(txn *lmdb.Txn) (err error) {\n\t\ttxn.RawRead = true\n\n\t\tfmt.Println(\"Freelist Status\")\n\n\t\tstat, err := txn.Stat(0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprintStat(stat, opt)\n\n\t\tvar numpages int64\n\t\ts := lmdbscan.New(txn, 0)\n\t\tdefer s.Close()\n\t\tfor s.Scan() {\n\t\t\tkey := s.Key()\n\t\t\tdata := s.Val()\n\t\t\ttxid := *(*C.size_t)(unsafe.Pointer(&key[0]))\n\t\t\tipages := int64(*(*C.size_t)(unsafe.Pointer(&data[0])))\n\t\t\tnumpages += ipages\n\t\t\tif opt.PrintFreeSummary || opt.PrintFreeFull {\n\t\t\t\tbad := \"\"\n\t\t\t\thdr := reflect.SliceHeader{\n\t\t\t\t\tData: uintptr(unsafe.Pointer(&data[0])),\n\t\t\t\t\tLen:  int(ipages) + 1,\n\t\t\t\t\tCap:  int(ipages) + 1,\n\t\t\t\t}\n\t\t\t\tpages := *(*[]C.size_t)(unsafe.Pointer(&hdr))\n\t\t\t\tpages = pages[1:]\n\t\t\t\tvar span C.size_t\n\t\t\t\tprev := C.size_t(1)\n\t\t\t\tfor i := ipages - 1; i >= 0; i-- {\n\t\t\t\t\tpg := pages[i]\n\t\t\t\t\tif pg < prev {\n\t\t\t\t\t\tbad = \" [bad sequence]\"\n\t\t\t\t\t}\n\t\t\t\t\tprev = pg\n\t\t\t\t\tpg += span\n\t\t\t\t\tfor i >= int64(span) && pages[i-int64(span)] == pg {\n\t\t\t\t\t\tspan++\n\t\t\t\t\t\tpg++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"    Transaction %d, %d pages, maxspan %d%s\\n\", txid, ipages, span, bad)\n\n\t\t\t\tif opt.PrintFreeFull {\n\t\t\t\t\tfor j := ipages - 1; j >= 0; {\n\t\t\t\t\t\tpg := pages[j]\n\t\t\t\t\t\tj--\n\t\t\t\t\t\tspan := C.size_t(1)\n\t\t\t\t\t\tfor j >= 0 && pages[j] == pg+span {\n\t\t\t\t\t\t\tj--\n\t\t\t\t\t\t\tspan++\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif span > 1 {\n\t\t\t\t\t\t\tfmt.Printf(\"     %9d[%d]\\n\", pg, span)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfmt.Printf(\"     %9d\\n\", pg)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\terr = s.Err()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Println(\"  Free pages:\", numpages)\n\n\t\treturn nil\n\t})\n}\n\nfunc doPrintStatRoot(env *lmdb.Env, opt *Options) error {\n\tstat, err := env.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Status of Main DB\")\n\tfmt.Println(\"  Tree depth:\", stat.Depth)\n\tfmt.Println(\"  Branch pages:\", stat.BranchPages)\n\tfmt.Println(\"  Leaf pages:\", stat.LeafPages)\n\tfmt.Println(\"  Overflow pages:\", stat.OverflowPages)\n\tfmt.Println(\"  Entries:\", stat.Entries)\n\n\treturn nil\n}\n\nfunc doPrintStatDB(env *lmdb.Env, db string, opt *Options) error {\n\terr := env.View(func(txn *lmdb.Txn) (err error) {\n\t\treturn printStatDB(env, txn, db, opt)\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%v (%s)\", err, db)\n\t}\n\treturn nil\n}\n\nfunc printStatDB(env *lmdb.Env, txn *lmdb.Txn, db string, opt *Options) error {\n\tdbi, err := txn.OpenDBI(db, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer env.CloseDBI(dbi)\n\n\tstat, err := txn.Stat(dbi)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Status of\", db)\n\tprintStat(stat, opt)\n\n\treturn err\n}\n\nfunc printStat(stat *lmdb.Stat, opt *Options) error {\n\tfmt.Println(\"  Tree depth:\", stat.Depth)\n\tfmt.Println(\"  Branch pages:\", stat.BranchPages)\n\tfmt.Println(\"  Leaf pages:\", stat.LeafPages)\n\tfmt.Println(\"  Overflow pages:\", stat.OverflowPages)\n\tfmt.Println(\"  Entries:\", stat.Entries)\n\n\treturn nil\n}\n\nfunc doPrintStatAll(env *lmdb.Env, opt *Options) error {\n\treturn env.View(func(txn *lmdb.Txn) (err error) {\n\t\tdbi, err := txn.OpenRoot(0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer env.CloseDBI(dbi)\n\n\t\ts := lmdbscan.New(txn, dbi)\n\t\tdefer s.Close()\n\t\tfor s.Scan() {\n\t\t\terr = printStatDB(env, txn, string(s.Key()), opt)\n\t\t\tif e, ok := err.(*lmdb.OpError); ok {\n\t\t\t\tif e.Op == \"mdb_dbi_open\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"%v (%s)\", err, s.Key())\n\t\t\t}\n\t\t}\n\t\treturn s.Err()\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"golang.org\/x\/oauth2\"\n)\n\n\/\/ Github represents a control version repository to\n\/\/ interact with github.com\ntype Github struct {\n\tclient *github.Client\n\towner  string\n\trepo   string\n\turl    string\n}\n\nconst (\n\ttimeoutShortRequest = 10 * time.Second\n\ttimeoutLongRequest  = 20 * time.Second\n)\n\n\/\/ newGithub returns an object of type Github\nfunc newGithub(url, token string) (CVR, error) {\n\turl = strings.TrimSpace(url)\n\n\townerRepo := strings.SplitAfter(url, \"\/\"+githubDomain+\"\/\")\n\n\t\/\/ at least we need two tokens\n\tif len(ownerRepo) < 2 {\n\t\treturn nil, fmt.Errorf(\"missing owner and repo %s\", url)\n\t}\n\n\townerRepo = strings.Split(ownerRepo[1], \"\/\")\n\n\t\/\/ at least we need two tokens: owner and repo\n\tif len(ownerRepo) < 2 {\n\t\treturn nil, fmt.Errorf(\"failed to get owner and repo %s\", url)\n\t}\n\n\tif len(ownerRepo[0]) == 0 {\n\t\treturn nil, fmt.Errorf(\"missing owner in url %s\", url)\n\t}\n\n\tif len(ownerRepo[1]) == 0 {\n\t\treturn nil, fmt.Errorf(\"missing repository in url %s\", url)\n\t}\n\n\t\/\/ create a new http client using the token\n\tvar client *http.Client\n\tif token != \"\" {\n\t\tts := oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: token},\n\t\t)\n\t\tclient = oauth2.NewClient(context.Background(), ts)\n\t}\n\n\treturn &Github{\n\t\tclient: github.NewClient(client),\n\t\towner:  ownerRepo[0],\n\t\trepo:   ownerRepo[1],\n\t\turl:    url,\n\t}, nil\n}\n\n\/\/ getDomain returns the domain name\nfunc (g *Github) getDomain() string {\n\treturn githubDomain\n}\n\n\/\/ getOwner returns the owner of the repo\nfunc (g *Github) getOwner() string {\n\treturn g.owner\n}\n\n\/\/ getRepo returns the repository name\nfunc (g *Github) getRepo() string {\n\treturn g.repo\n}\n\n\/\/ getOpenPullRequests returns the open pull requests\nfunc (g *Github) getOpenPullRequests() (map[string]*PullRequest, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), timeoutShortRequest)\n\tdefer cancel()\n\n\tpullRequests, _, err := g.client.PullRequests.List(ctx, g.owner, g.repo, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list pull requests %s\", err)\n\t}\n\n\tprs := make(map[string]*PullRequest)\n\n\tfor _, pr := range pullRequests {\n\t\tif pr == nil || pr.Number == nil {\n\t\t\tcontinue\n\t\t}\n\t\tnumber := *pr.Number\n\n\t\tpullRequest, err := g.getPullRequest(number)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tprs[strconv.Itoa(number)] = pullRequest\n\t}\n\n\treturn prs, nil\n}\n\n\/\/ getPullRequest returns a specific pull request\nfunc (g *Github) getPullRequest(pr int) (*PullRequest, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), timeoutShortRequest)\n\tdefer cancel()\n\n\t\/\/ get all commits of the pull request\n\tlistCommits, _, err := g.client.PullRequests.ListCommits(ctx, g.owner, g.repo, pr, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar commits []PullRequestCommit\n\tfor _, c := range listCommits {\n\t\tif c == nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get all commits of the pull request %d\", pr)\n\t\t}\n\n\t\tif c.SHA == nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get commit SHA of the pull request %d\", pr)\n\t\t}\n\t\tsha := *c.SHA\n\n\t\tif c.Commit == nil || c.Commit.Committer == nil || c.Commit.Committer.Date == nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get commit time of the pull request %d\", pr)\n\t\t}\n\t\ttime := *c.Commit.Committer.Date\n\n\t\tcommits = append(commits,\n\t\t\tPullRequestCommit{\n\t\t\t\tSha:  sha,\n\t\t\t\tTime: time,\n\t\t\t},\n\t\t)\n\t}\n\n\tpullRequest, _, err := g.client.PullRequests.Get(ctx, g.owner, g.repo, pr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ check the integrity of the pullRuest object before use it\n\tif pullRequest == nil {\n\t\treturn nil, fmt.Errorf(\"failed to get pull request %d\", pr)\n\t}\n\n\tif pullRequest.User == nil || pullRequest.User.Login == nil {\n\t\treturn nil, fmt.Errorf(\"failed to get the author of the pull request %d\", pr)\n\t}\n\n\tauthor := *pullRequest.User.Login\n\n\tif pullRequest.Mergeable == nil {\n\t\treturn nil, fmt.Errorf(\"Unable to know if the pull request %d is mergeable\", pr)\n\t}\n\n\tmergeable := *pullRequest.Mergeable\n\n\tif pullRequest.Head == nil || pullRequest.Head.Ref == nil {\n\t\treturn nil, fmt.Errorf(\"failed to get the branch name of the pull request %d\", pr)\n\t}\n\n\tbranchName := *pullRequest.Head.Ref\n\n\treturn &PullRequest{\n\t\tNumber:     pr,\n\t\tCommits:    commits,\n\t\tAuthor:     author,\n\t\tMergeable:  mergeable,\n\t\tBranchName: branchName,\n\t}, nil\n}\n\n\/\/ getLatestPullRequestComment returns the latest comment of a specific\n\/\/ user in the specific pr. If comment.User is an empty string then any user\n\/\/ could be the author of the latest pull request. If comment.Comment is an empty\n\/\/ string an error is returned.\nfunc (g *Github) getLatestPullRequestComment(pr int, comment PullRequestComment) (*PullRequestComment, error) {\n\tif len(comment.Comment) == 0 {\n\t\treturn nil, fmt.Errorf(\"comment cannot be an empty string\")\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), timeoutLongRequest)\n\tdefer cancel()\n\n\tcomments, _, err := g.client.Issues.ListComments(ctx, g.owner, g.repo, pr, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i := len(comments) - 1; i >= 0; i-- {\n\t\tc := comments[i]\n\t\tif len(comment.User) != 0 {\n\t\t\tif strings.Compare(*c.User.Login, comment.User) != 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif strings.Compare(*c.Body, comment.Comment) == 0 {\n\t\t\treturn &PullRequestComment{\n\t\t\t\tUser:    comment.User,\n\t\t\t\tComment: comment.Comment,\n\t\t\t\ttime:    *c.CreatedAt,\n\t\t\t}, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"comment '%+v' not found\", comment)\n}\n\nfunc (g *Github) downloadPullRequest(pr PullRequest, workingDirectory string) (string, error) {\n\tprojectDirectory, err := filepath.Abs(workingDirectory)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tprojectDirectory = filepath.Join(projectDirectory, g.repo)\n\tif err := os.MkdirAll(projectDirectory, 0755); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create project directory %s\", err)\n\t}\n\n\tvar stderr bytes.Buffer\n\n\t\/\/ clone the project\n\tcmd := exec.Command(\"git\", \"clone\", g.url, \".\")\n\tcmd.Dir = projectDirectory\n\tcmd.Stderr = &stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to run git clone %s %s\", stderr.String(), err)\n\t}\n\n\t\/\/ fetch the branch\n\tstderr.Reset()\n\tcmd = exec.Command(\"git\", \"fetch\", \"origin\", fmt.Sprintf(\"pull\/%d\/head:%s\", pr.Number, pr.BranchName))\n\tcmd.Dir = projectDirectory\n\tcmd.Stderr = &stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to run git fetch %s %s\", stderr.String(), err)\n\t}\n\n\t\/\/ checkout the branch\n\tstderr.Reset()\n\tcmd = exec.Command(\"git\", \"checkout\", pr.BranchName)\n\tcmd.Dir = projectDirectory\n\tcmd.Stderr = &stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to run git checkout %s %s\", stderr.String(), err)\n\t}\n\n\treturn projectDirectory, nil\n}\n\n\/\/ createComment creates a comment in the specific pr\nfunc (g *Github) createComment(pr int, comment string) error {\n\tctx, cancel := context.WithTimeout(context.Background(), timeoutLongRequest)\n\tdefer cancel()\n\n\tc := &github.IssueComment{Body: &comment}\n\n\t_, _, err := g.client.Issues.CreateComment(ctx, g.owner, g.repo, pr, c)\n\n\treturn err\n}\n\n\/\/ isMember returns true if the user is member of the organization, else false\nfunc (g *Github) isMember(user string) (bool, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), timeoutShortRequest)\n\tdefer cancel()\n\n\tret, _, err := g.client.Organizations.IsMember(ctx, g.owner, user)\n\n\treturn ret, err\n}\n<commit_msg>localCI: do not fail if we don't know if the pr is mergeable<commit_after>\/\/ Copyright (c) 2017 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"golang.org\/x\/oauth2\"\n)\n\n\/\/ Github represents a control version repository to\n\/\/ interact with github.com\ntype Github struct {\n\tclient *github.Client\n\towner  string\n\trepo   string\n\turl    string\n}\n\nconst (\n\ttimeoutShortRequest = 10 * time.Second\n\ttimeoutLongRequest  = 20 * time.Second\n)\n\n\/\/ newGithub returns an object of type Github\nfunc newGithub(url, token string) (CVR, error) {\n\turl = strings.TrimSpace(url)\n\n\townerRepo := strings.SplitAfter(url, \"\/\"+githubDomain+\"\/\")\n\n\t\/\/ at least we need two tokens\n\tif len(ownerRepo) < 2 {\n\t\treturn nil, fmt.Errorf(\"missing owner and repo %s\", url)\n\t}\n\n\townerRepo = strings.Split(ownerRepo[1], \"\/\")\n\n\t\/\/ at least we need two tokens: owner and repo\n\tif len(ownerRepo) < 2 {\n\t\treturn nil, fmt.Errorf(\"failed to get owner and repo %s\", url)\n\t}\n\n\tif len(ownerRepo[0]) == 0 {\n\t\treturn nil, fmt.Errorf(\"missing owner in url %s\", url)\n\t}\n\n\tif len(ownerRepo[1]) == 0 {\n\t\treturn nil, fmt.Errorf(\"missing repository in url %s\", url)\n\t}\n\n\t\/\/ create a new http client using the token\n\tvar client *http.Client\n\tif token != \"\" {\n\t\tts := oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: token},\n\t\t)\n\t\tclient = oauth2.NewClient(context.Background(), ts)\n\t}\n\n\treturn &Github{\n\t\tclient: github.NewClient(client),\n\t\towner:  ownerRepo[0],\n\t\trepo:   ownerRepo[1],\n\t\turl:    url,\n\t}, nil\n}\n\n\/\/ getDomain returns the domain name\nfunc (g *Github) getDomain() string {\n\treturn githubDomain\n}\n\n\/\/ getOwner returns the owner of the repo\nfunc (g *Github) getOwner() string {\n\treturn g.owner\n}\n\n\/\/ getRepo returns the repository name\nfunc (g *Github) getRepo() string {\n\treturn g.repo\n}\n\n\/\/ getOpenPullRequests returns the open pull requests\nfunc (g *Github) getOpenPullRequests() (map[string]*PullRequest, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), timeoutShortRequest)\n\tdefer cancel()\n\n\tpullRequests, _, err := g.client.PullRequests.List(ctx, g.owner, g.repo, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to list pull requests %s\", err)\n\t}\n\n\tprs := make(map[string]*PullRequest)\n\n\tfor _, pr := range pullRequests {\n\t\tif pr == nil || pr.Number == nil {\n\t\t\tcontinue\n\t\t}\n\t\tnumber := *pr.Number\n\n\t\tpullRequest, err := g.getPullRequest(number)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tprs[strconv.Itoa(number)] = pullRequest\n\t}\n\n\treturn prs, nil\n}\n\n\/\/ getPullRequest returns a specific pull request\nfunc (g *Github) getPullRequest(pr int) (*PullRequest, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), timeoutShortRequest)\n\tdefer cancel()\n\n\t\/\/ get all commits of the pull request\n\tlistCommits, _, err := g.client.PullRequests.ListCommits(ctx, g.owner, g.repo, pr, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar commits []PullRequestCommit\n\tfor _, c := range listCommits {\n\t\tif c == nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get all commits of the pull request %d\", pr)\n\t\t}\n\n\t\tif c.SHA == nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get commit SHA of the pull request %d\", pr)\n\t\t}\n\t\tsha := *c.SHA\n\n\t\tif c.Commit == nil || c.Commit.Committer == nil || c.Commit.Committer.Date == nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get commit time of the pull request %d\", pr)\n\t\t}\n\t\ttime := *c.Commit.Committer.Date\n\n\t\tcommits = append(commits,\n\t\t\tPullRequestCommit{\n\t\t\t\tSha:  sha,\n\t\t\t\tTime: time,\n\t\t\t},\n\t\t)\n\t}\n\n\tpullRequest, _, err := g.client.PullRequests.Get(ctx, g.owner, g.repo, pr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ check the integrity of the pullRuest object before use it\n\tif pullRequest == nil {\n\t\treturn nil, fmt.Errorf(\"failed to get pull request %d\", pr)\n\t}\n\n\tif pullRequest.User == nil || pullRequest.User.Login == nil {\n\t\treturn nil, fmt.Errorf(\"failed to get the author of the pull request %d\", pr)\n\t}\n\n\tauthor := *pullRequest.User.Login\n\n\t\/\/ do not fail if we don't know if the pull request is\n\t\/\/ mergeable, just test it\n\tmergeable := true\n\tif pullRequest.Mergeable != nil {\n\t\tmergeable = *pullRequest.Mergeable\n\t}\n\n\tif pullRequest.Head == nil || pullRequest.Head.Ref == nil {\n\t\treturn nil, fmt.Errorf(\"failed to get the branch name of the pull request %d\", pr)\n\t}\n\n\tbranchName := *pullRequest.Head.Ref\n\n\treturn &PullRequest{\n\t\tNumber:     pr,\n\t\tCommits:    commits,\n\t\tAuthor:     author,\n\t\tMergeable:  mergeable,\n\t\tBranchName: branchName,\n\t}, nil\n}\n\n\/\/ getLatestPullRequestComment returns the latest comment of a specific\n\/\/ user in the specific pr. If comment.User is an empty string then any user\n\/\/ could be the author of the latest pull request. If comment.Comment is an empty\n\/\/ string an error is returned.\nfunc (g *Github) getLatestPullRequestComment(pr int, comment PullRequestComment) (*PullRequestComment, error) {\n\tif len(comment.Comment) == 0 {\n\t\treturn nil, fmt.Errorf(\"comment cannot be an empty string\")\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), timeoutLongRequest)\n\tdefer cancel()\n\n\tcomments, _, err := g.client.Issues.ListComments(ctx, g.owner, g.repo, pr, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i := len(comments) - 1; i >= 0; i-- {\n\t\tc := comments[i]\n\t\tif len(comment.User) != 0 {\n\t\t\tif strings.Compare(*c.User.Login, comment.User) != 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif strings.Compare(*c.Body, comment.Comment) == 0 {\n\t\t\treturn &PullRequestComment{\n\t\t\t\tUser:    comment.User,\n\t\t\t\tComment: comment.Comment,\n\t\t\t\ttime:    *c.CreatedAt,\n\t\t\t}, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"comment '%+v' not found\", comment)\n}\n\nfunc (g *Github) downloadPullRequest(pr PullRequest, workingDirectory string) (string, error) {\n\tprojectDirectory, err := filepath.Abs(workingDirectory)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tprojectDirectory = filepath.Join(projectDirectory, g.repo)\n\tif err := os.MkdirAll(projectDirectory, 0755); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to create project directory %s\", err)\n\t}\n\n\tvar stderr bytes.Buffer\n\n\t\/\/ clone the project\n\tcmd := exec.Command(\"git\", \"clone\", g.url, \".\")\n\tcmd.Dir = projectDirectory\n\tcmd.Stderr = &stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to run git clone %s %s\", stderr.String(), err)\n\t}\n\n\t\/\/ fetch the branch\n\tstderr.Reset()\n\tcmd = exec.Command(\"git\", \"fetch\", \"origin\", fmt.Sprintf(\"pull\/%d\/head:%s\", pr.Number, pr.BranchName))\n\tcmd.Dir = projectDirectory\n\tcmd.Stderr = &stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to run git fetch %s %s\", stderr.String(), err)\n\t}\n\n\t\/\/ checkout the branch\n\tstderr.Reset()\n\tcmd = exec.Command(\"git\", \"checkout\", pr.BranchName)\n\tcmd.Dir = projectDirectory\n\tcmd.Stderr = &stderr\n\tif err := cmd.Run(); err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to run git checkout %s %s\", stderr.String(), err)\n\t}\n\n\treturn projectDirectory, nil\n}\n\n\/\/ createComment creates a comment in the specific pr\nfunc (g *Github) createComment(pr int, comment string) error {\n\tctx, cancel := context.WithTimeout(context.Background(), timeoutLongRequest)\n\tdefer cancel()\n\n\tc := &github.IssueComment{Body: &comment}\n\n\t_, _, err := g.client.Issues.CreateComment(ctx, g.owner, g.repo, pr, c)\n\n\treturn err\n}\n\n\/\/ isMember returns true if the user is member of the organization, else false\nfunc (g *Github) isMember(user string) (bool, error) {\n\tctx, cancel := context.WithTimeout(context.Background(), timeoutShortRequest)\n\tdefer cancel()\n\n\tret, _, err := g.client.Organizations.IsMember(ctx, g.owner, user)\n\n\treturn ret, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"go\/format\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"text\/template\"\n)\n\ntype generateType struct {\n\tName    string\n\tInitial string\n\tFields  []generateField\n}\n\ntype generateField struct {\n\tName     string\n\tInitial  string\n\tTypeName string\n\tJSONName string\n\tView     string\n}\n\n\/\/ following the type, an optional third param could designate the editor.Input-like\n\/\/ func to call which would output different text based on the element returned\n\/\/ blog title:string Author:string PostCategory:string content:string:richtext some_thing:int\n\n\/\/ blog title:string Author:string PostCategory:string content:string some_thing:int\nfunc parseType(args []string) (generateType, error) {\n\tt := generateType{\n\t\tName: fieldName(args[0]),\n\t}\n\tt.Initial = strings.ToLower(string(t.Name[0]))\n\n\tfields := args[1:]\n\tfor _, field := range fields {\n\t\tf, err := parseField(field, t)\n\t\tif err != nil {\n\t\t\treturn generateType{}, err\n\t\t}\n\t\t\/\/ NEW\n\t\t\/\/ set initial (1st character of the type's name) on field so we don't need\n\t\t\/\/ to set the template variable like was done in prior version\n\t\tf.Initial = t.Initial\n\n\t\tt.Fields = append(t.Fields, f)\n\t}\n\n\treturn t, nil\n}\n\nfunc parseField(raw string, gt generateType) (generateField, error) {\n\t\/\/ contents:string or \/\/ contents:string:richtext\n\tif !strings.Contains(raw, \":\") {\n\t\treturn generateField{}, fmt.Errorf(\"Invalid generate argument. [%s]\", raw)\n\t}\n\n\tdata := strings.Split(raw, \":\")\n\n\tfield := generateField{\n\t\tName:     fieldName(data[0]),\n\t\tInitial:  gt.Initial,\n\t\tTypeName: strings.ToLower(data[1]),\n\t\tJSONName: fieldJSONName(data[0]),\n\t}\n\n\tfieldType := \"input\"\n\tif len(data) == 3 {\n\t\tfieldType = data[2]\n\t}\n\n\terr := setFieldView(&field, fieldType)\n\tif err != nil {\n\t\treturn generateField{}, err\n\t}\n\n\treturn field, nil\n}\n\n\/\/ get the initial field name passed and check it for all possible cases\n\/\/ MyTitle:string myTitle:string my_title:string -> MyTitle\n\/\/ error-message:string -> ErrorMessage\nfunc fieldName(name string) string {\n\t\/\/ remove _ or - if first character\n\tif name[0] == '-' || name[0] == '_' {\n\t\tname = name[1:]\n\t}\n\n\t\/\/ remove _ or - if last character\n\tif name[len(name)-1] == '-' || name[len(name)-1] == '_' {\n\t\tname = name[:len(name)-1]\n\t}\n\n\t\/\/ upcase the first character\n\tname = strings.ToUpper(string(name[0])) + name[1:]\n\n\t\/\/ remove _ or - character, and upcase the character immediately following\n\tfor i := 0; i < len(name); i++ {\n\t\tr := rune(name[i])\n\t\tif isUnderscore(r) || isHyphen(r) {\n\t\t\tup := strings.ToUpper(string(name[i+1]))\n\t\t\tname = name[:i] + up + name[i+2:]\n\t\t}\n\t}\n\n\treturn name\n}\n\n\/\/ get the initial field name passed and convert to json-like name\n\/\/ MyTitle:string myTitle:string my_title:string -> my_title\n\/\/ error-message:string -> error-message\nfunc fieldJSONName(name string) string {\n\t\/\/ remove _ or - if first character\n\tif name[0] == '-' || name[0] == '_' {\n\t\tname = name[1:]\n\t}\n\n\t\/\/ downcase the first character\n\tname = strings.ToLower(string(name[0])) + name[1:]\n\n\t\/\/ check for uppercase character, downcase and insert _ before it if i-1\n\t\/\/ isn't already _ or -\n\tfor i := 0; i < len(name); i++ {\n\t\tr := rune(name[i])\n\t\tif isUpper(r) {\n\t\t\tlow := strings.ToLower(string(r))\n\t\t\tif name[i-1] == '_' || name[i-1] == '-' {\n\t\t\t\tname = name[:i] + low + name[i+1:]\n\t\t\t} else {\n\t\t\t\tname = name[:i] + \"_\" + low + name[i+1:]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn name\n}\n\n\/\/ set the specified view inside the editor field for a generated field for a type\nfunc setFieldView(field *generateField, viewType string) error {\n\tvar err error\n\tvar tmpl *template.Template\n\tbuf := &bytes.Buffer{}\n\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmplDir := filepath.Join(pwd, \"cmd\", \"ponzu\", \"templates\")\n\ttmplFrom := func(filename string) (*template.Template, error) {\n\t\treturn template.ParseFiles(filepath.Join(tmplDir, filename))\n\t}\n\n\tviewType = strings.ToLower(viewType)\n\tswitch viewType {\n\tcase \"checkbox\":\n\t\ttmpl, err = tmplFrom(\"gen-checkbox.tmpl\")\n\tcase \"custom\":\n\t\ttmpl, err = tmplFrom(\"gen-custom.tmpl\")\n\tcase \"file\":\n\t\ttmpl, err = tmplFrom(\"gen-file.tmpl\")\n\tcase \"hidden\":\n\t\ttmpl, err = tmplFrom(\"gen-hidden.tmpl\")\n\tcase \"input\", \"text\":\n\t\ttmpl, err = tmplFrom(\"gen-input.tmpl\")\n\tcase \"richtext\":\n\t\ttmpl, err = tmplFrom(\"gen-richtext.tmpl\")\n\tcase \"select\":\n\t\ttmpl, err = tmplFrom(\"gen-select.tmpl\")\n\tcase \"textarea\":\n\t\ttmpl, err = tmplFrom(\"gen-textarea.tmpl\")\n\tcase \"tags\":\n\t\ttmpl, err = tmplFrom(\"gen-tags.tmpl\")\n\tdefault:\n\t\tmsg := fmt.Sprintf(\"'%s' is not a recognized view type. Using 'input' instead.\", viewType)\n\t\tfmt.Println(msg)\n\t\ttmpl, err = tmplFrom(\"gen-input.tmpl\")\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = tmpl.Execute(buf, field)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfield.View = buf.String()\n\n\treturn nil\n}\n\nfunc isUpper(char rune) bool {\n\tif char >= 'A' && char <= 'Z' {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc isUnderscore(char rune) bool {\n\treturn char == '_'\n}\n\nfunc isHyphen(char rune) bool {\n\treturn char == '-'\n}\n\nfunc generateContentType(args []string) error {\n\tname := args[0]\n\tfileName := strings.ToLower(name) + \".go\"\n\n\t\/\/ open file in .\/content\/ dir\n\t\/\/ if exists, alert user of conflict\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontentDir := filepath.Join(pwd, \"content\")\n\tfilePath := filepath.Join(contentDir, fileName)\n\n\tif _, err := os.Stat(filePath); !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"Please remove '%s' before executing this command.\", fileName)\n\t}\n\n\t\/\/ no file exists.. ok to write new one\n\tfile, err := os.Create(filePath)\n\tdefer file.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ parse type info from args\n\tgt, err := parseType(args)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to parse type args: %s\", err.Error())\n\t}\n\n\ttmplPath := filepath.Join(pwd, \"cmd\", \"ponzu\", \"templates\", \"gen-content.tmpl\")\n\ttmpl, err := template.ParseFiles(tmplPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to parse template: %s\", err.Error())\n\t}\n\n\tbuf := &bytes.Buffer{}\n\terr = tmpl.Execute(buf, gt)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to execute template: %s\", err.Error())\n\t}\n\n\tfmtBuf, err := format.Source(buf.Bytes())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to format template: %s\", err.Error())\n\t}\n\n\t_, err = file.Write(fmtBuf)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to write generated file buffer: %s\", err.Error())\n\t}\n\n\treturn nil\n}\n<commit_msg>remove old comment\/reminder<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"go\/format\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"text\/template\"\n)\n\ntype generateType struct {\n\tName    string\n\tInitial string\n\tFields  []generateField\n}\n\ntype generateField struct {\n\tName     string\n\tInitial  string\n\tTypeName string\n\tJSONName string\n\tView     string\n}\n\n\/\/ blog title:string Author:string PostCategory:string content:string some_thing:int\nfunc parseType(args []string) (generateType, error) {\n\tt := generateType{\n\t\tName: fieldName(args[0]),\n\t}\n\tt.Initial = strings.ToLower(string(t.Name[0]))\n\n\tfields := args[1:]\n\tfor _, field := range fields {\n\t\tf, err := parseField(field, t)\n\t\tif err != nil {\n\t\t\treturn generateType{}, err\n\t\t}\n\t\t\/\/ NEW\n\t\t\/\/ set initial (1st character of the type's name) on field so we don't need\n\t\t\/\/ to set the template variable like was done in prior version\n\t\tf.Initial = t.Initial\n\n\t\tt.Fields = append(t.Fields, f)\n\t}\n\n\treturn t, nil\n}\n\nfunc parseField(raw string, gt generateType) (generateField, error) {\n\t\/\/ contents:string or \/\/ contents:string:richtext\n\tif !strings.Contains(raw, \":\") {\n\t\treturn generateField{}, fmt.Errorf(\"Invalid generate argument. [%s]\", raw)\n\t}\n\n\tdata := strings.Split(raw, \":\")\n\n\tfield := generateField{\n\t\tName:     fieldName(data[0]),\n\t\tInitial:  gt.Initial,\n\t\tTypeName: strings.ToLower(data[1]),\n\t\tJSONName: fieldJSONName(data[0]),\n\t}\n\n\tfieldType := \"input\"\n\tif len(data) == 3 {\n\t\tfieldType = data[2]\n\t}\n\n\terr := setFieldView(&field, fieldType)\n\tif err != nil {\n\t\treturn generateField{}, err\n\t}\n\n\treturn field, nil\n}\n\n\/\/ get the initial field name passed and check it for all possible cases\n\/\/ MyTitle:string myTitle:string my_title:string -> MyTitle\n\/\/ error-message:string -> ErrorMessage\nfunc fieldName(name string) string {\n\t\/\/ remove _ or - if first character\n\tif name[0] == '-' || name[0] == '_' {\n\t\tname = name[1:]\n\t}\n\n\t\/\/ remove _ or - if last character\n\tif name[len(name)-1] == '-' || name[len(name)-1] == '_' {\n\t\tname = name[:len(name)-1]\n\t}\n\n\t\/\/ upcase the first character\n\tname = strings.ToUpper(string(name[0])) + name[1:]\n\n\t\/\/ remove _ or - character, and upcase the character immediately following\n\tfor i := 0; i < len(name); i++ {\n\t\tr := rune(name[i])\n\t\tif isUnderscore(r) || isHyphen(r) {\n\t\t\tup := strings.ToUpper(string(name[i+1]))\n\t\t\tname = name[:i] + up + name[i+2:]\n\t\t}\n\t}\n\n\treturn name\n}\n\n\/\/ get the initial field name passed and convert to json-like name\n\/\/ MyTitle:string myTitle:string my_title:string -> my_title\n\/\/ error-message:string -> error-message\nfunc fieldJSONName(name string) string {\n\t\/\/ remove _ or - if first character\n\tif name[0] == '-' || name[0] == '_' {\n\t\tname = name[1:]\n\t}\n\n\t\/\/ downcase the first character\n\tname = strings.ToLower(string(name[0])) + name[1:]\n\n\t\/\/ check for uppercase character, downcase and insert _ before it if i-1\n\t\/\/ isn't already _ or -\n\tfor i := 0; i < len(name); i++ {\n\t\tr := rune(name[i])\n\t\tif isUpper(r) {\n\t\t\tlow := strings.ToLower(string(r))\n\t\t\tif name[i-1] == '_' || name[i-1] == '-' {\n\t\t\t\tname = name[:i] + low + name[i+1:]\n\t\t\t} else {\n\t\t\t\tname = name[:i] + \"_\" + low + name[i+1:]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn name\n}\n\n\/\/ set the specified view inside the editor field for a generated field for a type\nfunc setFieldView(field *generateField, viewType string) error {\n\tvar err error\n\tvar tmpl *template.Template\n\tbuf := &bytes.Buffer{}\n\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmplDir := filepath.Join(pwd, \"cmd\", \"ponzu\", \"templates\")\n\ttmplFrom := func(filename string) (*template.Template, error) {\n\t\treturn template.ParseFiles(filepath.Join(tmplDir, filename))\n\t}\n\n\tviewType = strings.ToLower(viewType)\n\tswitch viewType {\n\tcase \"checkbox\":\n\t\ttmpl, err = tmplFrom(\"gen-checkbox.tmpl\")\n\tcase \"custom\":\n\t\ttmpl, err = tmplFrom(\"gen-custom.tmpl\")\n\tcase \"file\":\n\t\ttmpl, err = tmplFrom(\"gen-file.tmpl\")\n\tcase \"hidden\":\n\t\ttmpl, err = tmplFrom(\"gen-hidden.tmpl\")\n\tcase \"input\", \"text\":\n\t\ttmpl, err = tmplFrom(\"gen-input.tmpl\")\n\tcase \"richtext\":\n\t\ttmpl, err = tmplFrom(\"gen-richtext.tmpl\")\n\tcase \"select\":\n\t\ttmpl, err = tmplFrom(\"gen-select.tmpl\")\n\tcase \"textarea\":\n\t\ttmpl, err = tmplFrom(\"gen-textarea.tmpl\")\n\tcase \"tags\":\n\t\ttmpl, err = tmplFrom(\"gen-tags.tmpl\")\n\tdefault:\n\t\tmsg := fmt.Sprintf(\"'%s' is not a recognized view type. Using 'input' instead.\", viewType)\n\t\tfmt.Println(msg)\n\t\ttmpl, err = tmplFrom(\"gen-input.tmpl\")\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = tmpl.Execute(buf, field)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfield.View = buf.String()\n\n\treturn nil\n}\n\nfunc isUpper(char rune) bool {\n\tif char >= 'A' && char <= 'Z' {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc isUnderscore(char rune) bool {\n\treturn char == '_'\n}\n\nfunc isHyphen(char rune) bool {\n\treturn char == '-'\n}\n\nfunc generateContentType(args []string) error {\n\tname := args[0]\n\tfileName := strings.ToLower(name) + \".go\"\n\n\t\/\/ open file in .\/content\/ dir\n\t\/\/ if exists, alert user of conflict\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontentDir := filepath.Join(pwd, \"content\")\n\tfilePath := filepath.Join(contentDir, fileName)\n\n\tif _, err := os.Stat(filePath); !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"Please remove '%s' before executing this command.\", fileName)\n\t}\n\n\t\/\/ no file exists.. ok to write new one\n\tfile, err := os.Create(filePath)\n\tdefer file.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ parse type info from args\n\tgt, err := parseType(args)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to parse type args: %s\", err.Error())\n\t}\n\n\ttmplPath := filepath.Join(pwd, \"cmd\", \"ponzu\", \"templates\", \"gen-content.tmpl\")\n\ttmpl, err := template.ParseFiles(tmplPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to parse template: %s\", err.Error())\n\t}\n\n\tbuf := &bytes.Buffer{}\n\terr = tmpl.Execute(buf, gt)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to execute template: %s\", err.Error())\n\t}\n\n\tfmtBuf, err := format.Source(buf.Bytes())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to format template: %s\", err.Error())\n\t}\n\n\t_, err = file.Write(fmtBuf)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to write generated file buffer: %s\", err.Error())\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"image\/png\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/DexterLB\/traytor\"\n\t\"github.com\/DexterLB\/traytor\/rpc\"\n\t\"github.com\/valyala\/gorpc\"\n)\n\ntype SampleCounter struct {\n\tsync.Mutex\n\tCounter int\n}\n\nfunc NewSampleCounter(value int) *SampleCounter {\n\treturn &SampleCounter{Counter: value}\n}\n\nfunc (sc *SampleCounter) Dec() bool {\n\tsc.Lock()\n\tdefer sc.Unlock()\n\n\tif sc.Counter > 0 {\n\t\tsc.Counter--\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc RenderLoop(\n\tsampleCounter *SampleCounter,\n\tclient *gorpc.DispatcherClient,\n\trenderedImages chan<- *traytor.Image,\n\twidth int,\n\theight int,\n) {\n\tfor {\n\t\tif !sampleCounter.Dec() {\n\t\t\treturn\n\t\t}\n\t\timage, err := client.CallTimeout(\"Sample\", [2]int{width, height}, 10*time.Minute)\n\t\tif err == nil {\n\t\t\trenderedImages <- image.(*traytor.Image)\n\t\t\tlog.Printf(\"Rendered sample :)\\n\")\n\t\t} else {\n\t\t\tlog.Printf(\"No sample :( %s\\n\", err)\n\t\t}\n\t}\n}\n\nfunc JoinSamples(\n\trenderedImages <-chan *traytor.Image,\n\twidth int,\n\theight int,\n) *traytor.Image {\n\taverageImage := traytor.NewImage(width, height)\n\taverageImage.Divisor = 0\n\tfor image := range renderedImages {\n\t\taverageImage.Add(image)\n\t\taverageImage.Divisor += image.Divisor\n\t}\n\treturn averageImage\n}\n\nfunc runClient(c *cli.Context) error {\n\tscene, image := getArguments(c)\n\tworkers := c.StringSlice(\"worker\")\n\tif len(workers) == 0 {\n\t\tshowError(c, \"can't render on zero workers :(\")\n\t}\n\n\tfmt.Printf(\n\t\t\"will render %s to %s of size %dx%d with %d threads on those workers: %s\\n\",\n\t\tscene, image,\n\t\tc.Int(\"width\"), c.Int(\"height\"),\n\t\tc.GlobalInt(\"max-jobs\"),\n\t\tstrings.Join(workers, \", \"),\n\t)\n\trr := rpc.NewRemoteRaytracer(time.Now().Unix())\n\n\twidth, height := c.Int(\"width\"), c.Int(\"height\")\n\tsampleCounter := NewSampleCounter(30)\n\trenderedImages := make(chan *traytor.Image, 30)\n\tclients := make([]*gorpc.Client, len(workers))\n\n\tdata, err := ioutil.ReadFile(scene)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error when loading scene: %s\", err)\n\t}\n\n\tfinishRender := &sync.WaitGroup{}\n\tfinishRender.Add(len(workers))\n\n\tfor i := range workers {\n\t\tclients[i] = &gorpc.Client{Addr: workers[i]}\n\t\tclients[i].Start()\n\t\tdispatcher := rr.Dispatcher.NewFuncClient(clients[i])\n\t\t_, err = dispatcher.CallTimeout(\"LoadScene\", data, 10*time.Minute)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Can't load scene: %s\", err)\n\t\t}\n\t\tgo func() {\n\t\t\tRenderLoop(sampleCounter, dispatcher, renderedImages, width, height)\n\t\t\tfinishRender.Done()\n\t\t}()\n\t}\n\n\tgo func() {\n\t\tfinishRender.Wait()\n\t\tclose(renderedImages)\n\t}()\n\n\taverageImage := JoinSamples(renderedImages, width, height)\n\tfile, err := os.Create(image)\n\tdefer file.Close()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error when saving image: %s\", err)\n\t}\n\tpng.Encode(file, averageImage)\n\treturn nil\n}\n<commit_msg>Try remote render with 4 workers<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"image\/png\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/DexterLB\/traytor\"\n\t\"github.com\/DexterLB\/traytor\/rpc\"\n\t\"github.com\/valyala\/gorpc\"\n)\n\ntype SampleCounter struct {\n\tsync.Mutex\n\tCounter int\n}\n\nfunc NewSampleCounter(value int) *SampleCounter {\n\treturn &SampleCounter{Counter: value}\n}\n\nfunc (sc *SampleCounter) Dec() bool {\n\tsc.Lock()\n\tdefer sc.Unlock()\n\n\tif sc.Counter > 0 {\n\t\tsc.Counter--\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc RenderLoop(\n\tsampleCounter *SampleCounter,\n\tclient *gorpc.DispatcherClient,\n\trenderedImages chan<- *traytor.Image,\n\twidth int,\n\theight int,\n) {\n\tfor {\n\t\tif !sampleCounter.Dec() {\n\t\t\treturn\n\t\t}\n\t\timage, err := client.CallTimeout(\"Sample\", [2]int{width, height}, 10*time.Minute)\n\t\tif err == nil {\n\t\t\trenderedImages <- image.(*traytor.Image)\n\t\t\tlog.Printf(\"Rendered sample :)\\n\")\n\t\t} else {\n\t\t\tlog.Printf(\"No sample :( %s\\n\", err)\n\t\t}\n\t}\n}\n\nfunc JoinSamples(\n\trenderedImages <-chan *traytor.Image,\n\twidth int,\n\theight int,\n) *traytor.Image {\n\taverageImage := traytor.NewImage(width, height)\n\taverageImage.Divisor = 0\n\tfor image := range renderedImages {\n\t\taverageImage.Add(image)\n\t\taverageImage.Divisor += image.Divisor\n\t}\n\treturn averageImage\n}\n\nfunc runClient(c *cli.Context) error {\n\tscene, image := getArguments(c)\n\tworkers := c.StringSlice(\"worker\")\n\tif len(workers) == 0 {\n\t\tshowError(c, \"can't render on zero workers :(\")\n\t}\n\n\tfmt.Printf(\n\t\t\"will render %s to %s of size %dx%d with %d threads on those workers: %s\\n\",\n\t\tscene, image,\n\t\tc.Int(\"width\"), c.Int(\"height\"),\n\t\tc.GlobalInt(\"max-jobs\"),\n\t\tstrings.Join(workers, \", \"),\n\t)\n\trr := rpc.NewRemoteRaytracer(time.Now().Unix())\n\n\twidth, height := c.Int(\"width\"), c.Int(\"height\")\n\tsampleCounter := NewSampleCounter(50)\n\trenderedImages := make(chan *traytor.Image, 50)\n\tclients := make([]*gorpc.Client, len(workers))\n\n\tdata, err := ioutil.ReadFile(scene)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error when loading scene: %s\", err)\n\t}\n\n\tfinishRender := &sync.WaitGroup{}\n\tfinishRender.Add(len(workers))\n\n\tfor i := range workers {\n\t\tclients[i] = &gorpc.Client{Addr: workers[i]}\n\t\tclients[i].Start()\n\t\tdispatcher := rr.Dispatcher.NewFuncClient(clients[i])\n\t\t_, err = dispatcher.CallTimeout(\"LoadScene\", data, 10*time.Minute)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Can't load scene: %s\", err)\n\t\t}\n\t\tgo func() {\n\t\t\tRenderLoop(sampleCounter, dispatcher, renderedImages, width, height)\n\t\t\tfinishRender.Done()\n\t\t}()\n\t}\n\n\tgo func() {\n\t\tfinishRender.Wait()\n\t\tclose(renderedImages)\n\t}()\n\n\taverageImage := JoinSamples(renderedImages, width, height)\n\tfile, err := os.Create(image)\n\tdefer file.Close()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error when saving image: %s\", err)\n\t}\n\tpng.Encode(file, averageImage)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The astrogo Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"image\"\n\t\"image\/color\"\n\t\"image\/draw\"\n\t\"image\/png\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/astrogo\/fitsio\"\n\n\t\"golang.org\/x\/exp\/shiny\/driver\"\n\t\"golang.org\/x\/exp\/shiny\/screen\"\n\t\"golang.org\/x\/mobile\/event\/key\"\n\t\"golang.org\/x\/mobile\/event\/lifecycle\"\n\t\"golang.org\/x\/mobile\/event\/paint\"\n\t\"golang.org\/x\/mobile\/event\/size\"\n)\n\ntype fileInfo struct {\n\tName   string\n\tImages []image.Image\n}\n\nfunc main() {\n\n\thelp := flag.Bool(\"help\", false, \"show help\")\n\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, `view-fits - a FITS image viewer.\n\nUsage of view-fits:\n$ view-fits [file1 [file2 [...]]]\n\nExamples:\n$ view-fits astrogo\/fitsio\/testdata\/file-img2-bitpix+08.fits\n$ view-fits astrogo\/fitsio\/testdata\/file-img2-bitpix*.fits\n$ view-fits http:\/\/data.astropy.org\/tutorials\/FITS-images\/HorseHead.fits\n$ view-fits file:\/\/\/some\/file.fits\n\nControls:\n- left\/right arrows: switch to previous\/next file\n- up\/down arrows:    switch to previous\/next image in the current file\n- r:                 reload\/redisplay current image\n- z:                 resize window to fit current image\n- p:                 print current image to 'output.png'\n- ?:                 show help\n- q\/ESC:             quit\n`)\n\t}\n\n\tflag.Parse()\n\n\tif *help || len(os.Args) < 2 {\n\t\tflag.Usage()\n\t\tos.Exit(0)\n\t}\n\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"[view-fits] \")\n\n\tinfos := processFiles()\n\tif len(infos) == 0 {\n\t\tlog.Fatal(\"No image among given FITS files.\")\n\t}\n\n\ttype cursor struct {\n\t\tfile int\n\t\timg  int\n\t}\n\n\tdriver.Main(func(s screen.Screen) {\n\n\t\t\/\/ Number of files.\n\t\tnbFiles := len(infos)\n\n\t\t\/\/ Current displayed file and image in file.\n\t\tcur := cursor{file: 0, img: 0}\n\n\t\t\/\/ Building the main window.\n\t\tw, err := s.NewWindow(&screen.NewWindowOptions{\n\t\t\tWidth:  500,\n\t\t\tHeight: 500,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer w.Release()\n\n\t\t\/\/ Building the screen buffer.\n\t\tb, err := s.NewBuffer(image.Point{500, 500})\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer release(b)\n\n\t\tw.Fill(b.Bounds(), color.Black, draw.Src)\n\t\tw.Publish()\n\n\t\trepaint := true\n\t\tvar (\n\t\t\tsz size.Event\n\t\t\t\/\/bkg = color.Black\n\t\t\tbkg = color.RGBA{0xe0, 0xe0, 0xe0, 0xff} \/\/ Material Design \"Grey 300\"\n\t\t)\n\n\t\tfor {\n\t\t\tswitch e := w.NextEvent().(type) {\n\t\t\tdefault:\n\t\t\t\t\/\/ ignore\n\n\t\t\tcase lifecycle.Event:\n\t\t\t\tswitch {\n\t\t\t\tcase e.From == lifecycle.StageVisible && e.To == lifecycle.StageFocused:\n\t\t\t\t\trepaint = true\n\t\t\t\tdefault:\n\t\t\t\t\trepaint = false\n\t\t\t\t}\n\t\t\t\tif repaint {\n\t\t\t\t\tw.Send(paint.Event{})\n\t\t\t\t}\n\n\t\t\tcase key.Event:\n\t\t\t\tswitch e.Code {\n\t\t\t\tcase key.CodeEscape, key.CodeQ:\n\t\t\t\t\treturn\n\n\t\t\t\tcase key.CodeSlash:\n\t\t\t\t\tif e.Direction == key.DirPress && e.Modifiers&key.ModShift != 0 {\n\t\t\t\t\t\tflag.Usage()\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeRightArrow:\n\t\t\t\t\tif e.Direction == key.DirPress {\n\t\t\t\t\t\trepaint = true\n\t\t\t\t\t\tif cur.file < nbFiles-1 {\n\t\t\t\t\t\t\tcur.file++\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcur.file = 0\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcur.img = 0\n\t\t\t\t\t\tlog.Printf(\"file:   %v\\n\", infos[cur.file].Name)\n\t\t\t\t\t\tlog.Printf(\"images: %d\\n\", len(infos[cur.file].Images))\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeLeftArrow:\n\t\t\t\t\tif e.Direction == key.DirPress {\n\t\t\t\t\t\trepaint = true\n\t\t\t\t\t\tif cur.file == 0 {\n\t\t\t\t\t\t\tcur.file = nbFiles - 1\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcur.file--\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcur.img = 0\n\t\t\t\t\t\tlog.Printf(\"file:   %v\\n\", infos[cur.file].Name)\n\t\t\t\t\t\tlog.Printf(\"images: %d\\n\", len(infos[cur.file].Images))\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeDownArrow:\n\t\t\t\t\tif e.Direction == key.DirPress {\n\t\t\t\t\t\trepaint = true\n\t\t\t\t\t\tnbImg := len(infos[cur.file].Images)\n\t\t\t\t\t\tif cur.img < nbImg-1 {\n\t\t\t\t\t\t\tcur.img++\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcur.img = 0\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeUpArrow:\n\t\t\t\t\tif e.Direction == key.DirPress {\n\t\t\t\t\t\trepaint = true\n\t\t\t\t\t\tnbImg := len(infos[cur.file].Images)\n\t\t\t\t\t\tif cur.img == 0 {\n\t\t\t\t\t\t\tcur.img = nbImg - 1\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcur.img--\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeR:\n\t\t\t\t\tif e.Direction == key.DirPress {\n\t\t\t\t\t\trepaint = true\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeZ:\n\t\t\t\t\tif e.Direction == key.DirPress {\n\t\t\t\t\t\t\/\/ resize to current image\n\t\t\t\t\t\t\/\/ TODO(sbinet)\n\t\t\t\t\t\trepaint = true\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeP:\n\t\t\t\t\tif e.Direction != key.DirPress {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tout, err := os.Create(\"output.png\")\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatalf(\"error printing image: %v\\n\", err)\n\t\t\t\t\t}\n\t\t\t\t\tdefer out.Close()\n\t\t\t\t\terr = png.Encode(out, infos[cur.file].Images[cur.img])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatalf(\"error printing image: %v\\n\", err)\n\t\t\t\t\t}\n\t\t\t\t\terr = out.Close()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatalf(\"error printing image: %v\\n\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Printf(\"printed current image to [%s]\\n\", out.Name())\n\t\t\t\t}\n\n\t\t\t\tif repaint {\n\t\t\t\t\tw.Send(paint.Event{})\n\t\t\t\t}\n\n\t\t\tcase size.Event:\n\t\t\t\tsz = e\n\n\t\t\tcase paint.Event:\n\t\t\t\tif !repaint {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trepaint = false\n\t\t\t\timg := infos[cur.file].Images[cur.img]\n\n\t\t\t\trelease(b)\n\t\t\t\tb, err = s.NewBuffer(img.Bounds().Size())\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\tdefer release(b)\n\n\t\t\t\tdraw.Draw(b.RGBA(), b.Bounds(), img, image.Point{}, draw.Src)\n\n\t\t\t\tw.Fill(sz.Bounds(), bkg, draw.Src)\n\t\t\t\tw.Upload(image.Point{}, b, img.Bounds())\n\t\t\t\tw.Publish()\n\t\t\t}\n\n\t\t}\n\n\t})\n}\n\nfunc processFiles() []fileInfo {\n\tinfos := make([]fileInfo, 0, len(flag.Args()))\n\t\/\/ Parsing input files.\n\tfor _, fname := range flag.Args() {\n\n\t\tfinfo := fileInfo{Name: fname}\n\n\t\tr, err := openStream(fname)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Can not open the input file: %v\", err)\n\t\t}\n\t\tdefer r.Close()\n\n\t\t\/\/ Opening the FITS file.\n\t\tf, err := fitsio.Open(r)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Can not open the FITS input file: %v\", err)\n\t\t}\n\t\tdefer f.Close()\n\n\t\t\/\/ Getting the file HDUs.\n\t\thdus := f.HDUs()\n\t\tfor _, hdu := range hdus {\n\t\t\t\/\/ Getting the header informations.\n\t\t\theader := hdu.Header()\n\t\t\taxes := header.Axes()\n\n\t\t\t\/\/ Discarding HDU with no axes.\n\t\t\tif len(axes) != 0 {\n\t\t\t\tif hdu, ok := hdu.(fitsio.Image); ok {\n\t\t\t\t\timg := hdu.Image()\n\t\t\t\t\tif img != nil {\n\t\t\t\t\t\tfinfo.Images = append(finfo.Images, img)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(finfo.Images) > 0 {\n\t\t\tinfos = append(infos, finfo)\n\t\t}\n\t}\n\n\treturn infos\n}\n\nfunc openStream(name string) (io.ReadCloser, error) {\n\tswitch {\n\tcase strings.HasPrefix(name, \"http:\/\/\") || strings.HasPrefix(name, \"https:\/\/\"):\n\t\tresp, err := http.Get(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tf, err := ioutil.TempFile(\"\", \"view-fits-\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t_, err = io.Copy(f, resp.Body)\n\t\tif err != nil {\n\t\t\tf.Close()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ make sure we have at least a full FITS block\n\t\tf.Seek(0, 2880)\n\t\tf.Seek(0, 0)\n\n\t\treturn f, nil\n\n\tcase strings.HasPrefix(name, \"file:\/\/\"):\n\t\tname = name[len(\"file:\/\/\"):]\n\t\treturn os.Open(name)\n\tdefault:\n\t\treturn os.Open(name)\n\t}\n}\n\ntype releaser interface {\n\tRelease()\n}\n\nfunc release(r releaser) {\n\tif r != nil {\n\t\tr.Release()\n\t}\n}\n<commit_msg>cmd\/view-fits: add godoc doc-string<commit_after>\/\/ Copyright 2016 The astrogo Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ view-fits is a simple program to display images in a FITS file.\n\/\/\n\/\/ Usage of view-fits:\n\/\/ $ view-fits [file1 [file2 [...]]]\n\/\/\n\/\/ Examples:\n\/\/  $ view-fits astrogo\/fitsio\/testdata\/file-img2-bitpix+08.fits\n\/\/  $ view-fits astrogo\/fitsio\/testdata\/file-img2-bitpix*.fits\n\/\/  $ view-fits http:\/\/data.astropy.org\/tutorials\/FITS-images\/HorseHead.fits\n\/\/  $ view-fits file:\/\/\/some\/file.fits\n\/\/\n\/\/ Controls:\n\/\/  - left\/right arrows: switch to previous\/next file\n\/\/  - up\/down arrows:    switch to previous\/next image in the current file\n\/\/  - r:                 reload\/redisplay current image\n\/\/  - z:                 resize window to fit current image\n\/\/  - p:                 print current image to 'output.png'\n\/\/  - ?:                 show help\n\/\/  - q\/ESC:             quit\n\/\/\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"image\"\n\t\"image\/color\"\n\t\"image\/draw\"\n\t\"image\/png\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/astrogo\/fitsio\"\n\n\t\"golang.org\/x\/exp\/shiny\/driver\"\n\t\"golang.org\/x\/exp\/shiny\/screen\"\n\t\"golang.org\/x\/mobile\/event\/key\"\n\t\"golang.org\/x\/mobile\/event\/lifecycle\"\n\t\"golang.org\/x\/mobile\/event\/paint\"\n\t\"golang.org\/x\/mobile\/event\/size\"\n)\n\ntype fileInfo struct {\n\tName   string\n\tImages []image.Image\n}\n\nfunc main() {\n\n\thelp := flag.Bool(\"help\", false, \"show help\")\n\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, `view-fits - a FITS image viewer.\n\nUsage of view-fits:\n$ view-fits [file1 [file2 [...]]]\n\nExamples:\n$ view-fits astrogo\/fitsio\/testdata\/file-img2-bitpix+08.fits\n$ view-fits astrogo\/fitsio\/testdata\/file-img2-bitpix*.fits\n$ view-fits http:\/\/data.astropy.org\/tutorials\/FITS-images\/HorseHead.fits\n$ view-fits file:\/\/\/some\/file.fits\n\nControls:\n- left\/right arrows: switch to previous\/next file\n- up\/down arrows:    switch to previous\/next image in the current file\n- r:                 reload\/redisplay current image\n- z:                 resize window to fit current image\n- p:                 print current image to 'output.png'\n- ?:                 show help\n- q\/ESC:             quit\n`)\n\t}\n\n\tflag.Parse()\n\n\tif *help || len(os.Args) < 2 {\n\t\tflag.Usage()\n\t\tos.Exit(0)\n\t}\n\n\tlog.SetFlags(0)\n\tlog.SetPrefix(\"[view-fits] \")\n\n\tinfos := processFiles()\n\tif len(infos) == 0 {\n\t\tlog.Fatal(\"No image among given FITS files.\")\n\t}\n\n\ttype cursor struct {\n\t\tfile int\n\t\timg  int\n\t}\n\n\tdriver.Main(func(s screen.Screen) {\n\n\t\t\/\/ Number of files.\n\t\tnbFiles := len(infos)\n\n\t\t\/\/ Current displayed file and image in file.\n\t\tcur := cursor{file: 0, img: 0}\n\n\t\t\/\/ Building the main window.\n\t\tw, err := s.NewWindow(&screen.NewWindowOptions{\n\t\t\tWidth:  500,\n\t\t\tHeight: 500,\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer w.Release()\n\n\t\t\/\/ Building the screen buffer.\n\t\tb, err := s.NewBuffer(image.Point{500, 500})\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer release(b)\n\n\t\tw.Fill(b.Bounds(), color.Black, draw.Src)\n\t\tw.Publish()\n\n\t\trepaint := true\n\t\tvar (\n\t\t\tsz size.Event\n\t\t\t\/\/bkg = color.Black\n\t\t\tbkg = color.RGBA{0xe0, 0xe0, 0xe0, 0xff} \/\/ Material Design \"Grey 300\"\n\t\t)\n\n\t\tfor {\n\t\t\tswitch e := w.NextEvent().(type) {\n\t\t\tdefault:\n\t\t\t\t\/\/ ignore\n\n\t\t\tcase lifecycle.Event:\n\t\t\t\tswitch {\n\t\t\t\tcase e.From == lifecycle.StageVisible && e.To == lifecycle.StageFocused:\n\t\t\t\t\trepaint = true\n\t\t\t\tdefault:\n\t\t\t\t\trepaint = false\n\t\t\t\t}\n\t\t\t\tif repaint {\n\t\t\t\t\tw.Send(paint.Event{})\n\t\t\t\t}\n\n\t\t\tcase key.Event:\n\t\t\t\tswitch e.Code {\n\t\t\t\tcase key.CodeEscape, key.CodeQ:\n\t\t\t\t\treturn\n\n\t\t\t\tcase key.CodeSlash:\n\t\t\t\t\tif e.Direction == key.DirPress && e.Modifiers&key.ModShift != 0 {\n\t\t\t\t\t\tflag.Usage()\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeRightArrow:\n\t\t\t\t\tif e.Direction == key.DirPress {\n\t\t\t\t\t\trepaint = true\n\t\t\t\t\t\tif cur.file < nbFiles-1 {\n\t\t\t\t\t\t\tcur.file++\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcur.file = 0\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcur.img = 0\n\t\t\t\t\t\tlog.Printf(\"file:   %v\\n\", infos[cur.file].Name)\n\t\t\t\t\t\tlog.Printf(\"images: %d\\n\", len(infos[cur.file].Images))\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeLeftArrow:\n\t\t\t\t\tif e.Direction == key.DirPress {\n\t\t\t\t\t\trepaint = true\n\t\t\t\t\t\tif cur.file == 0 {\n\t\t\t\t\t\t\tcur.file = nbFiles - 1\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcur.file--\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcur.img = 0\n\t\t\t\t\t\tlog.Printf(\"file:   %v\\n\", infos[cur.file].Name)\n\t\t\t\t\t\tlog.Printf(\"images: %d\\n\", len(infos[cur.file].Images))\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeDownArrow:\n\t\t\t\t\tif e.Direction == key.DirPress {\n\t\t\t\t\t\trepaint = true\n\t\t\t\t\t\tnbImg := len(infos[cur.file].Images)\n\t\t\t\t\t\tif cur.img < nbImg-1 {\n\t\t\t\t\t\t\tcur.img++\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcur.img = 0\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeUpArrow:\n\t\t\t\t\tif e.Direction == key.DirPress {\n\t\t\t\t\t\trepaint = true\n\t\t\t\t\t\tnbImg := len(infos[cur.file].Images)\n\t\t\t\t\t\tif cur.img == 0 {\n\t\t\t\t\t\t\tcur.img = nbImg - 1\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcur.img--\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeR:\n\t\t\t\t\tif e.Direction == key.DirPress {\n\t\t\t\t\t\trepaint = true\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeZ:\n\t\t\t\t\tif e.Direction == key.DirPress {\n\t\t\t\t\t\t\/\/ resize to current image\n\t\t\t\t\t\t\/\/ TODO(sbinet)\n\t\t\t\t\t\trepaint = true\n\t\t\t\t\t}\n\n\t\t\t\tcase key.CodeP:\n\t\t\t\t\tif e.Direction != key.DirPress {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tout, err := os.Create(\"output.png\")\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatalf(\"error printing image: %v\\n\", err)\n\t\t\t\t\t}\n\t\t\t\t\tdefer out.Close()\n\t\t\t\t\terr = png.Encode(out, infos[cur.file].Images[cur.img])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatalf(\"error printing image: %v\\n\", err)\n\t\t\t\t\t}\n\t\t\t\t\terr = out.Close()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatalf(\"error printing image: %v\\n\", err)\n\t\t\t\t\t}\n\t\t\t\t\tlog.Printf(\"printed current image to [%s]\\n\", out.Name())\n\t\t\t\t}\n\n\t\t\t\tif repaint {\n\t\t\t\t\tw.Send(paint.Event{})\n\t\t\t\t}\n\n\t\t\tcase size.Event:\n\t\t\t\tsz = e\n\n\t\t\tcase paint.Event:\n\t\t\t\tif !repaint {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trepaint = false\n\t\t\t\timg := infos[cur.file].Images[cur.img]\n\n\t\t\t\trelease(b)\n\t\t\t\tb, err = s.NewBuffer(img.Bounds().Size())\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\tdefer release(b)\n\n\t\t\t\tdraw.Draw(b.RGBA(), b.Bounds(), img, image.Point{}, draw.Src)\n\n\t\t\t\tw.Fill(sz.Bounds(), bkg, draw.Src)\n\t\t\t\tw.Upload(image.Point{}, b, img.Bounds())\n\t\t\t\tw.Publish()\n\t\t\t}\n\n\t\t}\n\n\t})\n}\n\nfunc processFiles() []fileInfo {\n\tinfos := make([]fileInfo, 0, len(flag.Args()))\n\t\/\/ Parsing input files.\n\tfor _, fname := range flag.Args() {\n\n\t\tfinfo := fileInfo{Name: fname}\n\n\t\tr, err := openStream(fname)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Can not open the input file: %v\", err)\n\t\t}\n\t\tdefer r.Close()\n\n\t\t\/\/ Opening the FITS file.\n\t\tf, err := fitsio.Open(r)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Can not open the FITS input file: %v\", err)\n\t\t}\n\t\tdefer f.Close()\n\n\t\t\/\/ Getting the file HDUs.\n\t\thdus := f.HDUs()\n\t\tfor _, hdu := range hdus {\n\t\t\t\/\/ Getting the header informations.\n\t\t\theader := hdu.Header()\n\t\t\taxes := header.Axes()\n\n\t\t\t\/\/ Discarding HDU with no axes.\n\t\t\tif len(axes) != 0 {\n\t\t\t\tif hdu, ok := hdu.(fitsio.Image); ok {\n\t\t\t\t\timg := hdu.Image()\n\t\t\t\t\tif img != nil {\n\t\t\t\t\t\tfinfo.Images = append(finfo.Images, img)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(finfo.Images) > 0 {\n\t\t\tinfos = append(infos, finfo)\n\t\t}\n\t}\n\n\treturn infos\n}\n\nfunc openStream(name string) (io.ReadCloser, error) {\n\tswitch {\n\tcase strings.HasPrefix(name, \"http:\/\/\") || strings.HasPrefix(name, \"https:\/\/\"):\n\t\tresp, err := http.Get(name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tf, err := ioutil.TempFile(\"\", \"view-fits-\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t_, err = io.Copy(f, resp.Body)\n\t\tif err != nil {\n\t\t\tf.Close()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ make sure we have at least a full FITS block\n\t\tf.Seek(0, 2880)\n\t\tf.Seek(0, 0)\n\n\t\treturn f, nil\n\n\tcase strings.HasPrefix(name, \"file:\/\/\"):\n\t\tname = name[len(\"file:\/\/\"):]\n\t\treturn os.Open(name)\n\tdefault:\n\t\treturn os.Open(name)\n\t}\n}\n\ntype releaser interface {\n\tRelease()\n}\n\nfunc release(r releaser) {\n\tif r != nil {\n\t\tr.Release()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\tlog \"github.com\/whosonfirst\/go-whosonfirst-log\"\n\tpip \"github.com\/whosonfirst\/go-whosonfirst-pip\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\n\nfunc main() {\n\n\tvar host = flag.String(\"host\", \"localhost\", \"The hostname to listen for requests on\")\n\tvar port = flag.Int(\"port\", 8080, \"The port number to listen for requests on\")\n\tvar data = flag.String(\"data\", \"\", \"The data directory where WOF data lives, required\")\n\tvar cache_all = flag.Bool(\"cache_all\", false, \"Just cache everything, regardless of size\")\n\tvar cache_size = flag.Int(\"cache_size\", 1024, \"The number of WOF records with large geometries to cache\")\n\tvar cache_trigger = flag.Int(\"cache_trigger\", 2000, \"The minimum number of coordinates in a WOF record that will trigger caching\")\n\tvar strict = flag.Bool(\"strict\", false, \"Enable strict placetype checking\")\n\tvar loglevel = flag.String(\"loglevel\", \"info\", \"Log level for reporting\")\n\tvar logs = flag.String(\"logs\", \"\", \"Where to write logs to disk\")\n\tvar metrics = flag.String(\"metrics\", \"\", \"Where to write (@rcrowley go-metrics style) metrics to disk\")\n\tvar format = flag.String(\"metrics-as\", \"plain\", \"Format metrics as... ? Valid options are \\\"json\\\" and \\\"plain\\\"\")\n\tvar cors = flag.Bool(\"cors\", false, \"Enable CORS headers\")\n\n\tflag.Parse()\n\targs := flag.Args()\n\n\tif *data == \"\" {\n\t\tpanic(\"missing data\")\n\t}\n\n\t_, err := os.Stat(*data)\n\n\tif os.IsNotExist(err) {\n\t\tpanic(\"data does not exist\")\n\t}\n\n\tvar l_writer io.Writer\n\tvar m_writer io.Writer\n\n\tl_writer = io.MultiWriter(os.Stdout)\n\n\tif *logs != \"\" {\n\n\t\tl_file, l_err := os.OpenFile(*logs, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)\n\n\t\tif l_err != nil {\n\t\t\tpanic(l_err)\n\t\t}\n\n\t\tl_writer = io.MultiWriter(os.Stdout, l_file)\n\t}\n\n\tlogger := log.NewWOFLogger(\"[wof-pip-server] \")\n\tlogger.AddLogger(l_writer, *loglevel)\n\n\tif *cache_all {\n\n\t\t*cache_size = 0\n\t\t*cache_trigger = 1\n\n\t\tmu := new(sync.Mutex)\n\t\twg := new(sync.WaitGroup)\n\n\t\tfor _, path := range args {\n\n\t\t\twg.Add(1)\n\n\t\t\tgo func(path string) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tcount := 0\n\n\t\t\t\tfh, err := os.Open(path)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(\"failed to open %s for reading, because %v\", path, err)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\tscanner := bufio.NewScanner(fh)\n\n\t\t\t\tfor scanner.Scan() {\n\t\t\t\t\tcount += 1\n\t\t\t\t}\n\n\t\t\t\tmu.Lock()\n\t\t\t\t*cache_size += count\n\t\t\t\tmu.Unlock()\n\n\t\t\t}(path)\n\t\t}\n\n\t\twg.Wait()\n\n\t\tlogger.Status(\"set cache_size to %d and cache_trigger to %d\", *cache_size, *cache_trigger)\n\t}\n\n\tp, p_err := pip.NewPointInPolygon(*data, *cache_size, *cache_trigger, logger)\n\n\tif p_err != nil {\n\t\tpanic(p_err)\n\t}\n\n\tif *metrics != \"\" {\n\n\t\tm_file, m_err := os.OpenFile(*metrics, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)\n\n\t\tif m_err != nil {\n\t\t\tpanic(m_err)\n\t\t}\n\n\t\tm_writer = io.MultiWriter(m_file)\n\t\t_ = p.SendMetricsTo(m_writer, 60e9, *format)\n\t}\n\n\tt1 := time.Now()\n\n\tfor _, path := range args {\n\t\tp.IndexMetaFile(path)\n\t}\n\n\tt2 := float64(time.Since(t1)) \/ 1e9\n\n\tp.Logger.Status(\"indexed %d records in %.3f seconds\", p.Rtree.Size(), t2)\n\n\tfor pt, count := range p.Placetypes {\n\t\tp.Logger.Status(\"indexed %s: %d\", pt, count)\n\t}\n\n\thandler := func(rsp http.ResponseWriter, req *http.Request) {\n\n\t\tquery := req.URL.Query()\n\n\t\tstr_lat := query.Get(\"latitude\")\n\t\tstr_lon := query.Get(\"longitude\")\n\t\tplacetype := query.Get(\"placetype\")\n\n\t\tif str_lat == \"\" {\n\t\t\thttp.Error(rsp, \"Missing latitude parameter\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif str_lon == \"\" {\n\t\t\thttp.Error(rsp, \"Missing longitude parameter\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tlat, lat_err := strconv.ParseFloat(str_lat, 64)\n\t\tlon, lon_err := strconv.ParseFloat(str_lon, 64)\n\n\t\tif lat_err != nil {\n\t\t\thttp.Error(rsp, \"Invalid latitude parameter\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif lon_err != nil {\n\t\t\thttp.Error(rsp, \"Invalid longitude parameter\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif lat > 90.0 || lat < -90.0 {\n\t\t\thttp.Error(rsp, \"E_IMPOSSIBLE_LATITUDE\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif lon > 180.0 || lon < -180.0 {\n\t\t\thttp.Error(rsp, \"E_IMPOSSIBLE_LONGITUDE\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif placetype != \"\" {\n\n\t\t\tif *strict && !p.IsKnownPlacetype(placetype) {\n\t\t\t\thttp.Error(rsp, \"Unknown placetype\", http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tresults, timings := p.GetByLatLonForPlacetype(lat, lon, placetype)\n\n\t\tcount := len(results)\n\t\tttp := 0.0\n\n\t\tfor _, t := range timings {\n\t\t\tttp += t.Duration\n\t\t}\n\n\t\tif placetype != \"\" {\n\t\t\tp.Logger.Debug(\"time to reverse geocode %f, %f @%s: %d results in %f seconds \", lat, lon, placetype, count, ttp)\n\t\t} else {\n\t\t\tp.Logger.Debug(\"time to reverse geocode %f, %f: %d results in %f seconds \", lat, lon, count, ttp)\n\t\t}\n\n\t\tjs, err := json.Marshal(results)\n\n\t\tif err != nil {\n\t\t\thttp.Error(rsp, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ maybe this although it seems like it adds functionality for a lot of\n\t\t\/\/ features this server does not need - https:\/\/github.com\/rs\/cors\n\t\t\/\/ (20151022\/thisisaaronland)\n\n\t\tif *cors {\n\t\t\trsp.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\t}\n\n\t\trsp.Header().Set(\"Content-Type\", \"application\/json\")\n\t\trsp.Write(js)\n\t}\n\n\tendpoint := fmt.Sprintf(\"%s:%d\", *host, *port)\n\n\thttp.HandleFunc(\"\/\", handler)\n\thttp.ListenAndServe(endpoint, nil)\n}\n<commit_msg>add proper error checking when starting pip-server (thanks @dphiffer!)<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\tlog \"github.com\/whosonfirst\/go-whosonfirst-log\"\n\tpip \"github.com\/whosonfirst\/go-whosonfirst-pip\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\n\nfunc main() {\n\n\tvar host = flag.String(\"host\", \"localhost\", \"The hostname to listen for requests on\")\n\tvar port = flag.Int(\"port\", 8080, \"The port number to listen for requests on\")\n\tvar data = flag.String(\"data\", \"\", \"The data directory where WOF data lives, required\")\n\tvar cache_all = flag.Bool(\"cache_all\", false, \"Just cache everything, regardless of size\")\n\tvar cache_size = flag.Int(\"cache_size\", 1024, \"The number of WOF records with large geometries to cache\")\n\tvar cache_trigger = flag.Int(\"cache_trigger\", 2000, \"The minimum number of coordinates in a WOF record that will trigger caching\")\n\tvar strict = flag.Bool(\"strict\", false, \"Enable strict placetype checking\")\n\tvar loglevel = flag.String(\"loglevel\", \"info\", \"Log level for reporting\")\n\tvar logs = flag.String(\"logs\", \"\", \"Where to write logs to disk\")\n\tvar metrics = flag.String(\"metrics\", \"\", \"Where to write (@rcrowley go-metrics style) metrics to disk\")\n\tvar format = flag.String(\"metrics-as\", \"plain\", \"Format metrics as... ? Valid options are \\\"json\\\" and \\\"plain\\\"\")\n\tvar cors = flag.Bool(\"cors\", false, \"Enable CORS headers\")\n\n\tflag.Parse()\n\targs := flag.Args()\n\n\tif *data == \"\" {\n\t\tpanic(\"missing data\")\n\t}\n\n\t_, err := os.Stat(*data)\n\n\tif os.IsNotExist(err) {\n\t\tpanic(\"data does not exist\")\n\t}\n\n\tvar l_writer io.Writer\n\tvar m_writer io.Writer\n\n\tl_writer = io.MultiWriter(os.Stdout)\n\n\tif *logs != \"\" {\n\n\t\tl_file, l_err := os.OpenFile(*logs, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)\n\n\t\tif l_err != nil {\n\t\t\tpanic(l_err)\n\t\t}\n\n\t\tl_writer = io.MultiWriter(os.Stdout, l_file)\n\t}\n\n\tlogger := log.NewWOFLogger(\"[wof-pip-server] \")\n\tlogger.AddLogger(l_writer, *loglevel)\n\n\tif *cache_all {\n\n\t\t*cache_size = 0\n\t\t*cache_trigger = 1\n\n\t\tmu := new(sync.Mutex)\n\t\twg := new(sync.WaitGroup)\n\n\t\tfor _, path := range args {\n\n\t\t\twg.Add(1)\n\n\t\t\tgo func(path string) {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tcount := 0\n\n\t\t\t\tfh, err := os.Open(path)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(\"failed to open %s for reading, because %v\", path, err)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\n\t\t\t\tscanner := bufio.NewScanner(fh)\n\n\t\t\t\tfor scanner.Scan() {\n\t\t\t\t\tcount += 1\n\t\t\t\t}\n\n\t\t\t\tmu.Lock()\n\t\t\t\t*cache_size += count\n\t\t\t\tmu.Unlock()\n\n\t\t\t}(path)\n\t\t}\n\n\t\twg.Wait()\n\n\t\tlogger.Status(\"set cache_size to %d and cache_trigger to %d\", *cache_size, *cache_trigger)\n\t}\n\n\tp, p_err := pip.NewPointInPolygon(*data, *cache_size, *cache_trigger, logger)\n\n\tif p_err != nil {\n\t\tpanic(p_err)\n\t}\n\n\tif *metrics != \"\" {\n\n\t\tm_file, m_err := os.OpenFile(*metrics, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)\n\n\t\tif m_err != nil {\n\t\t\tpanic(m_err)\n\t\t}\n\n\t\tm_writer = io.MultiWriter(m_file)\n\t\t_ = p.SendMetricsTo(m_writer, 60e9, *format)\n\t}\n\n\tt1 := time.Now()\n\n\tfor _, path := range args {\n\t\tp.IndexMetaFile(path)\n\t}\n\n\tt2 := float64(time.Since(t1)) \/ 1e9\n\n\tp.Logger.Status(\"indexed %d records in %.3f seconds\", p.Rtree.Size(), t2)\n\n\tfor pt, count := range p.Placetypes {\n\t\tp.Logger.Status(\"indexed %s: %d\", pt, count)\n\t}\n\n\thandler := func(rsp http.ResponseWriter, req *http.Request) {\n\n\t\tquery := req.URL.Query()\n\n\t\tstr_lat := query.Get(\"latitude\")\n\t\tstr_lon := query.Get(\"longitude\")\n\t\tplacetype := query.Get(\"placetype\")\n\n\t\tif str_lat == \"\" {\n\t\t\thttp.Error(rsp, \"Missing latitude parameter\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif str_lon == \"\" {\n\t\t\thttp.Error(rsp, \"Missing longitude parameter\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tlat, lat_err := strconv.ParseFloat(str_lat, 64)\n\t\tlon, lon_err := strconv.ParseFloat(str_lon, 64)\n\n\t\tif lat_err != nil {\n\t\t\thttp.Error(rsp, \"Invalid latitude parameter\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif lon_err != nil {\n\t\t\thttp.Error(rsp, \"Invalid longitude parameter\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif lat > 90.0 || lat < -90.0 {\n\t\t\thttp.Error(rsp, \"E_IMPOSSIBLE_LATITUDE\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif lon > 180.0 || lon < -180.0 {\n\t\t\thttp.Error(rsp, \"E_IMPOSSIBLE_LONGITUDE\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tif placetype != \"\" {\n\n\t\t\tif *strict && !p.IsKnownPlacetype(placetype) {\n\t\t\t\thttp.Error(rsp, \"Unknown placetype\", http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tresults, timings := p.GetByLatLonForPlacetype(lat, lon, placetype)\n\n\t\tcount := len(results)\n\t\tttp := 0.0\n\n\t\tfor _, t := range timings {\n\t\t\tttp += t.Duration\n\t\t}\n\n\t\tif placetype != \"\" {\n\t\t\tp.Logger.Debug(\"time to reverse geocode %f, %f @%s: %d results in %f seconds \", lat, lon, placetype, count, ttp)\n\t\t} else {\n\t\t\tp.Logger.Debug(\"time to reverse geocode %f, %f: %d results in %f seconds \", lat, lon, count, ttp)\n\t\t}\n\n\t\tjs, err := json.Marshal(results)\n\n\t\tif err != nil {\n\t\t\thttp.Error(rsp, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ maybe this although it seems like it adds functionality for a lot of\n\t\t\/\/ features this server does not need - https:\/\/github.com\/rs\/cors\n\t\t\/\/ (20151022\/thisisaaronland)\n\n\t\tif *cors {\n\t\t\trsp.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\t}\n\n\t\trsp.Header().Set(\"Content-Type\", \"application\/json\")\n\t\trsp.Write(js)\n\t}\n\n\tendpoint := fmt.Sprintf(\"%s:%d\", *host, *port)\n\n\thttp.HandleFunc(\"\/\", handler)\n\terr = http.ListenAndServe(endpoint, nil)\n\n\tif err != nil {\n\t       logger.Error(\"failed to start server, because %v\", err)\n\t       os.Exit(1)\n\t}\n\n\tos.Exit(0)\n}\n<|endoftext|>"}
{"text":"<commit_before>package handlers\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/kisielk\/sqlstruct\"\n\t\"github.com\/nelsonleduc\/calmanbot\/service\"\n)\n\ntype Cached struct {\n\tID     int    `sql:\"id\"`\n\tQuery  string `sql:\"query\"`\n\tResult string `sql:\"result\"`\n}\n\ntype SmartCache struct {\n\tmonitor service.Monitor\n}\n\nfunc NewSmartCache(monitor service.Monitor) SmartCache {\n\treturn SmartCache{monitor}\n}\n\nfunc (s SmartCache) CachedResponse(message string) *string {\n\n\tcached, _ := cacheFetch(\"WHERE query = $1\", []interface{}{message})\n\n\tfirst := cached[0]\n\ts.monitor.ValueFor(first.ID)\n\n\treturn nil\n}\n\nfunc (s SmartCache) CacheQuery(query, result string) int {\n\tqueryStr := \"INSERT INTO cached(query, result) VALUES($1, $2) RETURNING id\"\n\trow := currentDB.QueryRow(queryStr, query, result)\n\n\tvar id int\n\trow.Scan(&id)\n\n\treturn id\n}\n\n\/\/Temp DB\nvar currentDB *sql.DB\n\nfunc init() {\n\tcurrentDB = connect()\n}\n\nfunc connect() *sql.DB {\n\tdbUrl := os.Getenv(\"DATABASE_URL\")\n\tdatabase, err := sql.Open(\"postgres\", dbUrl)\n\tif err != nil {\n\t\tlog.Fatalf(\"[x] Could not open the connection to the database. Reason: %s\", err.Error())\n\t}\n\treturn database\n}\n\nfunc cacheFetch(whereStr string, values []interface{}) ([]Cached, error) {\n\n\tqueryStr := fmt.Sprintf(\"SELECT %s FROM cached\", sqlstruct.Columns(Cached{}))\n\n\tfmt.Println(queryStr)\n\n\trows, err := currentDB.Query(queryStr+\" \"+whereStr, values...)\n\tif err != nil {\n\t\treturn []Cached{}, err\n\t}\n\tdefer rows.Close()\n\n\tactions := []Cached{}\n\tfor rows.Next() {\n\t\tvar act Cached\n\t\terr := sqlstruct.Scan(&act, rows)\n\t\tif err == nil {\n\t\t\tactions = append(actions, act)\n\t\t}\n\t}\n\n\treturn actions, nil\n}\n<commit_msg>Minor safety<commit_after>package handlers\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/kisielk\/sqlstruct\"\n\t\"github.com\/nelsonleduc\/calmanbot\/service\"\n)\n\ntype Cached struct {\n\tID     int    `sql:\"id\"`\n\tQuery  string `sql:\"query\"`\n\tResult string `sql:\"result\"`\n}\n\ntype SmartCache struct {\n\tmonitor service.Monitor\n}\n\nfunc NewSmartCache(monitor service.Monitor) SmartCache {\n\treturn SmartCache{monitor}\n}\n\nfunc (s SmartCache) CachedResponse(message string) *string {\n\n\tcached, _ := cacheFetch(\"WHERE query = $1\", []interface{}{message})\n\n\tif len(cached) == 0 {\n\t\treturn nil\n\t}\n\n\tfirst := cached[0]\n\ts.monitor.ValueFor(first.ID)\n\n\treturn nil\n}\n\nfunc (s SmartCache) CacheQuery(query, result string) int {\n\tqueryStr := \"INSERT INTO cached(query, result) VALUES($1, $2) RETURNING id\"\n\trow := currentDB.QueryRow(queryStr, query, result)\n\n\tvar id int\n\trow.Scan(&id)\n\n\treturn id\n}\n\n\/\/Temp DB\nvar currentDB *sql.DB\n\nfunc init() {\n\tcurrentDB = connect()\n}\n\nfunc connect() *sql.DB {\n\tdbUrl := os.Getenv(\"DATABASE_URL\")\n\tdatabase, err := sql.Open(\"postgres\", dbUrl)\n\tif err != nil {\n\t\tlog.Fatalf(\"[x] Could not open the connection to the database. Reason: %s\", err.Error())\n\t}\n\treturn database\n}\n\nfunc cacheFetch(whereStr string, values []interface{}) ([]Cached, error) {\n\n\tqueryStr := fmt.Sprintf(\"SELECT %s FROM cached\", sqlstruct.Columns(Cached{}))\n\n\tfmt.Println(queryStr)\n\n\trows, err := currentDB.Query(queryStr+\" \"+whereStr, values...)\n\tif err != nil {\n\t\treturn []Cached{}, err\n\t}\n\tdefer rows.Close()\n\n\tactions := []Cached{}\n\tfor rows.Next() {\n\t\tvar act Cached\n\t\terr := sqlstruct.Scan(&act, rows)\n\t\tif err == nil {\n\t\t\tactions = append(actions, act)\n\t\t}\n\t}\n\n\treturn actions, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\/\/ Contributor:\n\/\/ - Aaron Meihm ameihm@mozilla.com\n\npackage main\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\tslib \"servicelib\"\n\t\"strconv\"\n)\n\nfunc getRRA(op opContext, rraid string) (slib.RRAService, error) {\n\tvar rr slib.RRAService\n\n\terr := op.QueryRow(`SELECT rraid, service,\n\t\tari, api, afi, cri, cpi, cfi,\n\t\tiri, ipi, ifi,\n\t\tarp, app, afp, crp, cpp, cfp,\n\t\tirp, ipp, ifp, datadefault, raw\n\t\tFROM rra WHERE rraid = $1`, rraid).Scan(&rr.ID,\n\t\t&rr.Name, &rr.AvailRepImpact, &rr.AvailPrdImpact,\n\t\t&rr.AvailFinImpact, &rr.ConfiRepImpact, &rr.ConfiPrdImpact, &rr.ConfiFinImpact,\n\t\t&rr.IntegRepImpact, &rr.IntegPrdImpact, &rr.IntegFinImpact,\n\t\t&rr.AvailRepProb, &rr.AvailPrdProb, &rr.AvailFinProb,\n\t\t&rr.ConfiRepProb, &rr.ConfiPrdProb, &rr.ConfiFinProb,\n\t\t&rr.IntegRepProb, &rr.IntegPrdProb, &rr.IntegFinProb,\n\t\t&rr.DefData, &rr.RawRRA)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn rr, nil\n\t\t} else {\n\t\t\treturn rr, err\n\t\t}\n\t}\n\terr = rraResolveSupportGroups(op, &rr)\n\tif err != nil {\n\t\treturn rr, err\n\t}\n\n\treturn rr, nil\n}\n\nfunc rraResolveSupportGroups(op opContext, r *slib.RRAService) error {\n\tr.SupportGrps = make([]slib.SystemGroup, 0)\n\trows, err := op.Query(`SELECT sysgroupid FROM\n\t\trra_sysgroup WHERE rraid = $1`,\n\t\tr.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor rows.Next() {\n\t\tvar sgid string\n\t\terr = rows.Scan(&sgid)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\treturn err\n\t\t}\n\t\tsg, err := getSysGroup(op, sgid)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\treturn err\n\t\t}\n\t\tif sg.Name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tr.SupportGrps = append(r.SupportGrps, sg)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Return a risk document that includes all RRAs\nfunc serviceRisks(rw http.ResponseWriter, req *http.Request) {\n\top := opContext{}\n\top.newContext(dbconn, false, req.RemoteAddr)\n\n\trows, err := op.Query(`SELECT rraid FROM rra`)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\tresp := slib.RisksResponse{}\n\tfor rows.Next() {\n\t\tvar rraid int\n\t\terr = rows.Scan(&rraid)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\top.logf(err.Error())\n\t\t\thttp.Error(rw, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\t\trs, err := riskForRRA(op, true, rraid)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\top.logf(err.Error())\n\t\t\thttp.Error(rw, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\t\tresp.Risks = append(resp.Risks, rs)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\n\tbuf, err := json.Marshal(&resp)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\tfmt.Fprintf(rw, string(buf))\n}\n\n\/\/ Calculate the risk for the requested RRA\nfunc serviceGetRRARisk(rw http.ResponseWriter, req *http.Request) {\n\treq.ParseForm()\n\n\top := opContext{}\n\top.newContext(dbconn, false, req.RemoteAddr)\n\n\trraid := req.FormValue(\"id\")\n\tif rraid == \"\" {\n\t\terr := fmt.Errorf(\"no rra id specified\")\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 400)\n\t\treturn\n\t}\n\tr, err := strconv.Atoi(rraid)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\trs, err := riskForRRA(op, true, r)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\n\tbuf, err := json.Marshal(&rs)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\tfmt.Fprintf(rw, string(buf))\n}\n\n\/\/ Read incoming RRA and update database as required. This can result in a\n\/\/ new RRA being added, or an existing RRA being updated.\nfunc serviceUpdateRRA(rw http.ResponseWriter, req *http.Request) {\n\treq.ParseMultipartForm(10000000)\n\n\trawrra := req.FormValue(\"rra\")\n\tif rawrra == \"\" {\n\t\tlogf(\"no rra parameter in update request\")\n\t\thttp.Error(rw, \"no rra parameter in update request\", 500)\n\t\treturn\n\t}\n\n\top := opContext{}\n\top.newContext(dbconn, false, req.RemoteAddr)\n\n\t\/\/ XXX Use the same import function we use in the RRA importer for now.\n\t\/\/ This can be cleaned up once the RRA importer is removed and the POST\n\t\/\/ functionality for RRAs is being used exclusively.\n\tvar (\n\t\tnrra    rraESData\n\t\trraList []rraESData\n\t)\n\terr := json.Unmarshal([]byte(rawrra), &nrra.rra)\n\tif err != nil {\n\t\tlogf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\terr = json.Unmarshal([]byte(rawrra), &nrra.raw)\n\tif err != nil {\n\t\tlogf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\terr = nrra.rra.validate()\n\tif err != nil {\n\t\tlogf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\trraList = append(rraList, nrra)\n\n\terr = dbUpdateRRAs(rraList)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\n\tur := slib.RRAUpdateResponse{OK: true}\n\tbuf, err := json.Marshal(&ur)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\tfmt.Fprintf(rw, string(buf))\n}\n\n\/\/ API entry point to retrieve specific RRA details\nfunc serviceGetRRA(rw http.ResponseWriter, req *http.Request) {\n\treq.ParseForm()\n\n\trraid := req.FormValue(\"id\")\n\n\top := opContext{}\n\top.newContext(dbconn, false, req.RemoteAddr)\n\n\tr, err := getRRA(op, rraid)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\n\tbuf, err := json.Marshal(&r)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\tfmt.Fprintf(rw, string(buf))\n}\n\n\/\/ API entry point to retrieve all RRAs\nfunc serviceRRAs(rw http.ResponseWriter, req *http.Request) {\n\top := opContext{}\n\top.newContext(dbconn, false, req.RemoteAddr)\n\n\trows, err := op.Query(`SELECT rraid, service, datadefault\n\t\tFROM rra x WHERE lastmodified = (\n\t\t\tSELECT MAX(lastmodified) FROM rra y WHERE\n\t\t\tx.service = y.service\n\t\t)`)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\tsrr := slib.RRAsResponse{}\n\tsrr.Results = make([]slib.RRAService, 0)\n\tfor rows.Next() {\n\t\tvar s slib.RRAService\n\t\terr = rows.Scan(&s.ID, &s.Name, &s.DefData)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\top.logf(err.Error())\n\t\t\thttp.Error(rw, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\t\tsrr.Results = append(srr.Results, s)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\n\tbuf, err := json.Marshal(&srr)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\n\tfmt.Fprint(rw, string(buf))\n}\n<commit_msg>when retrieving all risks, only include latest rra per service<commit_after>\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\/\/ Contributor:\n\/\/ - Aaron Meihm ameihm@mozilla.com\n\npackage main\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\tslib \"servicelib\"\n\t\"strconv\"\n)\n\nfunc getRRA(op opContext, rraid string) (slib.RRAService, error) {\n\tvar rr slib.RRAService\n\n\terr := op.QueryRow(`SELECT rraid, service,\n\t\tari, api, afi, cri, cpi, cfi,\n\t\tiri, ipi, ifi,\n\t\tarp, app, afp, crp, cpp, cfp,\n\t\tirp, ipp, ifp, datadefault, raw\n\t\tFROM rra WHERE rraid = $1`, rraid).Scan(&rr.ID,\n\t\t&rr.Name, &rr.AvailRepImpact, &rr.AvailPrdImpact,\n\t\t&rr.AvailFinImpact, &rr.ConfiRepImpact, &rr.ConfiPrdImpact, &rr.ConfiFinImpact,\n\t\t&rr.IntegRepImpact, &rr.IntegPrdImpact, &rr.IntegFinImpact,\n\t\t&rr.AvailRepProb, &rr.AvailPrdProb, &rr.AvailFinProb,\n\t\t&rr.ConfiRepProb, &rr.ConfiPrdProb, &rr.ConfiFinProb,\n\t\t&rr.IntegRepProb, &rr.IntegPrdProb, &rr.IntegFinProb,\n\t\t&rr.DefData, &rr.RawRRA)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn rr, nil\n\t\t} else {\n\t\t\treturn rr, err\n\t\t}\n\t}\n\terr = rraResolveSupportGroups(op, &rr)\n\tif err != nil {\n\t\treturn rr, err\n\t}\n\n\treturn rr, nil\n}\n\nfunc rraResolveSupportGroups(op opContext, r *slib.RRAService) error {\n\tr.SupportGrps = make([]slib.SystemGroup, 0)\n\trows, err := op.Query(`SELECT sysgroupid FROM\n\t\trra_sysgroup WHERE rraid = $1`,\n\t\tr.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor rows.Next() {\n\t\tvar sgid string\n\t\terr = rows.Scan(&sgid)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\treturn err\n\t\t}\n\t\tsg, err := getSysGroup(op, sgid)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\treturn err\n\t\t}\n\t\tif sg.Name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tr.SupportGrps = append(r.SupportGrps, sg)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ Return a risk document that includes all RRAs\nfunc serviceRisks(rw http.ResponseWriter, req *http.Request) {\n\top := opContext{}\n\top.newContext(dbconn, false, req.RemoteAddr)\n\n\trows, err := op.Query(`SELECT rraid FROM rra x\n\t\tWHERE lastmodified = (\n\t\t\tSELECT MAX(lastmodified) FROM rra y\n\t\t\tWHERE x.service = y.service\n\t\t)`)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\tresp := slib.RisksResponse{}\n\tfor rows.Next() {\n\t\tvar rraid int\n\t\terr = rows.Scan(&rraid)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\top.logf(err.Error())\n\t\t\thttp.Error(rw, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\t\trs, err := riskForRRA(op, true, rraid)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\top.logf(err.Error())\n\t\t\thttp.Error(rw, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\t\tresp.Risks = append(resp.Risks, rs)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\n\tbuf, err := json.Marshal(&resp)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\tfmt.Fprintf(rw, string(buf))\n}\n\n\/\/ Calculate the risk for the requested RRA\nfunc serviceGetRRARisk(rw http.ResponseWriter, req *http.Request) {\n\treq.ParseForm()\n\n\top := opContext{}\n\top.newContext(dbconn, false, req.RemoteAddr)\n\n\trraid := req.FormValue(\"id\")\n\tif rraid == \"\" {\n\t\terr := fmt.Errorf(\"no rra id specified\")\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 400)\n\t\treturn\n\t}\n\tr, err := strconv.Atoi(rraid)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\trs, err := riskForRRA(op, true, r)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\n\tbuf, err := json.Marshal(&rs)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\tfmt.Fprintf(rw, string(buf))\n}\n\n\/\/ Read incoming RRA and update database as required. This can result in a\n\/\/ new RRA being added, or an existing RRA being updated.\nfunc serviceUpdateRRA(rw http.ResponseWriter, req *http.Request) {\n\treq.ParseMultipartForm(10000000)\n\n\trawrra := req.FormValue(\"rra\")\n\tif rawrra == \"\" {\n\t\tlogf(\"no rra parameter in update request\")\n\t\thttp.Error(rw, \"no rra parameter in update request\", 500)\n\t\treturn\n\t}\n\n\top := opContext{}\n\top.newContext(dbconn, false, req.RemoteAddr)\n\n\t\/\/ XXX Use the same import function we use in the RRA importer for now.\n\t\/\/ This can be cleaned up once the RRA importer is removed and the POST\n\t\/\/ functionality for RRAs is being used exclusively.\n\tvar (\n\t\tnrra    rraESData\n\t\trraList []rraESData\n\t)\n\terr := json.Unmarshal([]byte(rawrra), &nrra.rra)\n\tif err != nil {\n\t\tlogf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\terr = json.Unmarshal([]byte(rawrra), &nrra.raw)\n\tif err != nil {\n\t\tlogf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\terr = nrra.rra.validate()\n\tif err != nil {\n\t\tlogf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\trraList = append(rraList, nrra)\n\n\terr = dbUpdateRRAs(rraList)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\n\tur := slib.RRAUpdateResponse{OK: true}\n\tbuf, err := json.Marshal(&ur)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\tfmt.Fprintf(rw, string(buf))\n}\n\n\/\/ API entry point to retrieve specific RRA details\nfunc serviceGetRRA(rw http.ResponseWriter, req *http.Request) {\n\treq.ParseForm()\n\n\trraid := req.FormValue(\"id\")\n\n\top := opContext{}\n\top.newContext(dbconn, false, req.RemoteAddr)\n\n\tr, err := getRRA(op, rraid)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\n\tbuf, err := json.Marshal(&r)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\tfmt.Fprintf(rw, string(buf))\n}\n\n\/\/ API entry point to retrieve all RRAs\nfunc serviceRRAs(rw http.ResponseWriter, req *http.Request) {\n\top := opContext{}\n\top.newContext(dbconn, false, req.RemoteAddr)\n\n\trows, err := op.Query(`SELECT rraid, service, datadefault\n\t\tFROM rra x WHERE lastmodified = (\n\t\t\tSELECT MAX(lastmodified) FROM rra y WHERE\n\t\t\tx.service = y.service\n\t\t)`)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\tsrr := slib.RRAsResponse{}\n\tsrr.Results = make([]slib.RRAService, 0)\n\tfor rows.Next() {\n\t\tvar s slib.RRAService\n\t\terr = rows.Scan(&s.ID, &s.Name, &s.DefData)\n\t\tif err != nil {\n\t\t\trows.Close()\n\t\t\top.logf(err.Error())\n\t\t\thttp.Error(rw, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\t\tsrr.Results = append(srr.Results, s)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\n\tbuf, err := json.Marshal(&srr)\n\tif err != nil {\n\t\top.logf(err.Error())\n\t\thttp.Error(rw, err.Error(), 500)\n\t\treturn\n\t}\n\n\tfmt.Fprint(rw, string(buf))\n}\n<|endoftext|>"}
{"text":"<commit_before>package remote\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/hashicorp\/terraform\/state\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\n\/\/ testClient is a generic function to test any client.\nfunc testClient(t *testing.T, c Client) {\n\tvar buf bytes.Buffer\n\ts := state.TestStateInitial()\n\tif err := terraform.WriteState(s, &buf); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\tdata := buf.Bytes()\n\n\tif err := c.Put(data); err != nil {\n\t\tt.Fatalf(\"put: %s\", err)\n\t}\n\n\tp, err := c.Get()\n\tif err != nil {\n\t\tt.Fatalf(\"get: %s\", err)\n\t}\n\tif !bytes.Equal(p.Data, data) {\n\t\tt.Fatalf(\"bad: %#v\", p)\n\t}\n\n\tif err := c.Delete(); err != nil {\n\t\tt.Fatalf(\"delete: %s\", err)\n\t}\n\n\tp, err = c.Get()\n\tif err != nil {\n\t\tt.Fatalf(\"get: %s\", err)\n\t}\n\tif p != nil {\n\t\tt.Fatalf(\"bad: %#v\", p)\n\t}\n}\n\nfunc TestRemoteClient_noPayload(t *testing.T) {\n\ts := &State{\n\t\tClient: nilClient{},\n\t}\n\tif err := s.RefreshState(); err != nil {\n\t\tt.Fatal(\"error refreshing empty remote state\")\n\t}\n}\n\n\/\/ nilClient returns nil for everything\ntype nilClient struct{}\n\nfunc (nilClient) Get() (*Payload, error) { return nil, nil }\n\nfunc (c nilClient) Put([]byte) error { return nil }\n\nfunc (c nilClient) Delete() error { return nil }\n\n\/\/ ensure that remote state can be properly initialized\nfunc TestRemoteClient_stateInit(t *testing.T) {\n\tlocalStateFile, err := ioutil.TempFile(\"\", \"tf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ we need to remove the temp files so we recognize there's no local or\n\t\/\/ remote state.\n\tlocalStateFile.Close()\n\tos.Remove(localStateFile.Name())\n\t\/\/defer os.Remove(localStateFile.Name())\n\tfmt.Println(\"LOCAL:\", localStateFile.Name())\n\n\tlocal := &state.LocalState{\n\t\tPath: localStateFile.Name(),\n\t}\n\tif err := local.RefreshState(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tlocalState := local.State()\n\n\tfmt.Println(\"localState.Empty():\", localState.Empty())\n\n\tremoteStateFile, err := ioutil.TempFile(\"\", \"tf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tremoteStateFile.Close()\n\tos.Remove(remoteStateFile.Name())\n\t\/\/defer os.Remove(remoteStateFile.Name()\n\tfmt.Println(\"LOCAL:\", localStateFile.Name())\n\tfmt.Println(\"REMOTE:\", remoteStateFile.Name())\n\n\tremoteClient := &FileClient{\n\t\tPath: remoteStateFile.Name(),\n\t}\n\n\tdurable := &State{\n\t\tClient: remoteClient,\n\t}\n\n\tcache := &state.CacheState{\n\t\tCache:   local,\n\t\tDurable: durable,\n\t}\n\n\tif err := cache.RefreshState(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tswitch cache.RefreshResult() {\n\n\t\/\/ we should be \"refreshing\" the remote state to initialize it\n\tcase state.CacheRefreshLocalNewer:\n\t\t\/\/ Write our local state out to the durable storage to start.\n\t\tif err := cache.WriteState(localState); err != nil {\n\t\t\tt.Fatal(\"Error preparing remote state:\", err)\n\t\t}\n\t\tif err := cache.PersistState(); err != nil {\n\t\t\tt.Fatal(\"Error preparing remote state:\", err)\n\t\t}\n\tdefault:\n\n\t\tt.Fatal(\"unexpected refresh result:\", cache.RefreshResult())\n\t}\n\n}\n<commit_msg>Add remote state init test<commit_after>package remote\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/hashicorp\/terraform\/state\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\n\/\/ testClient is a generic function to test any client.\nfunc testClient(t *testing.T, c Client) {\n\tvar buf bytes.Buffer\n\ts := state.TestStateInitial()\n\tif err := terraform.WriteState(s, &buf); err != nil {\n\t\tt.Fatalf(\"err: %s\", err)\n\t}\n\tdata := buf.Bytes()\n\n\tif err := c.Put(data); err != nil {\n\t\tt.Fatalf(\"put: %s\", err)\n\t}\n\n\tp, err := c.Get()\n\tif err != nil {\n\t\tt.Fatalf(\"get: %s\", err)\n\t}\n\tif !bytes.Equal(p.Data, data) {\n\t\tt.Fatalf(\"bad: %#v\", p)\n\t}\n\n\tif err := c.Delete(); err != nil {\n\t\tt.Fatalf(\"delete: %s\", err)\n\t}\n\n\tp, err = c.Get()\n\tif err != nil {\n\t\tt.Fatalf(\"get: %s\", err)\n\t}\n\tif p != nil {\n\t\tt.Fatalf(\"bad: %#v\", p)\n\t}\n}\n\nfunc TestRemoteClient_noPayload(t *testing.T) {\n\ts := &State{\n\t\tClient: nilClient{},\n\t}\n\tif err := s.RefreshState(); err != nil {\n\t\tt.Fatal(\"error refreshing empty remote state\")\n\t}\n}\n\n\/\/ nilClient returns nil for everything\ntype nilClient struct{}\n\nfunc (nilClient) Get() (*Payload, error) { return nil, nil }\n\nfunc (c nilClient) Put([]byte) error { return nil }\n\nfunc (c nilClient) Delete() error { return nil }\n\n\/\/ ensure that remote state can be properly initialized\nfunc TestRemoteClient_stateInit(t *testing.T) {\n\tlocalStateFile, err := ioutil.TempFile(\"\", \"tf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ we need to remove the temp files so we recognize there's no local or\n\t\/\/ remote state.\n\tlocalStateFile.Close()\n\tos.Remove(localStateFile.Name())\n\tdefer os.Remove(localStateFile.Name())\n\n\tremoteStateFile, err := ioutil.TempFile(\"\", \"tf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tremoteStateFile.Close()\n\tos.Remove(remoteStateFile.Name())\n\tdefer os.Remove(remoteStateFile.Name())\n\n\t\/\/ Now we need an empty state to initialize the state files.\n\tnewState := terraform.NewState()\n\tnewState.Remote = &terraform.RemoteState{\n\t\tType:   \"_local\",\n\t\tConfig: map[string]string{\"path\": remoteStateFile.Name()},\n\t}\n\n\tremoteClient := &FileClient{\n\t\tPath: remoteStateFile.Name(),\n\t}\n\n\tcache := &state.CacheState{\n\t\tCache: &state.LocalState{\n\t\t\tPath: localStateFile.Name(),\n\t\t},\n\t\tDurable: &State{\n\t\t\tClient: remoteClient,\n\t\t},\n\t}\n\n\t\/\/ This will write the local state file, and set the state field in the CacheState\n\terr = cache.WriteState(newState)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ This will persist the local state we just wrote to the remote state file\n\terr = cache.PersistState()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ now compare the two state files just to be sure\n\tlocalData, err := ioutil.ReadFile(localStateFile.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tremoteData, err := ioutil.ReadFile(remoteStateFile.Name())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif !bytes.Equal(localData, remoteData) {\n\t\tt.Log(\"state files don't match\")\n\t\tt.Log(\"Local:\\n\", string(localData))\n\t\tt.Log(\"Remote:\\n\", string(remoteData))\n\t\tt.Fatal(\"failed to initialize remote state\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package helpers\n\nimport (\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/vito\/cmdtest\/matchers\"\n\n\t\"github.com\/pivotal-cf-experimental\/cf-test-helpers\/cf\"\n)\n\nvar AdminUserContext cf.UserContext\nvar RegularUserContext cf.UserContext\n\ntype SuiteContext interface {\n\tSetup()\n\tTeardown()\n\n\tAdminUserContext() cf.UserContext\n\tRegularUserContext() cf.UserContext\n}\n\nfunc SetupEnvironment(context SuiteContext) {\n\tvar originalCfHomeDir, currentCfHomeDir string\n\n\tBeforeEach(func() {\n\t\tAdminUserContext = context.AdminUserContext()\n\t\tRegularUserContext = context.RegularUserContext()\n\n\t\tcontext.Setup()\n\n\t\tcf.AsUser(AdminUserContext, func() {\n\t\t\tSetUpSpaceWithUserAccess(RegularUserContext, RegularUserContext.Space)\n\t\t})\n\n\t\toriginalCfHomeDir, currentCfHomeDir = cf.InitiateUserContext(RegularUserContext)\n\t\tcf.TargetSpace(RegularUserContext)\n\t})\n\n\tAfterEach(func() {\n\t\tcf.RestoreUserContext(RegularUserContext, originalCfHomeDir, currentCfHomeDir)\n\n\t\tcontext.Teardown()\n\t})\n}\n\nfunc SetUpSpaceWithUserAccess(uc cf.UserContext, sname string) {\n\tExpect(cf.Cf(\"create-space\", \"-o\", uc.Org, sname)).To(ExitWith(0))\n\tExpect(cf.Cf(\"set-space-role\", uc.Username, uc.Org, sname, \"SpaceManager\")).To(ExitWith(0))\n\tExpect(cf.Cf(\"set-space-role\", uc.Username, uc.Org, sname, \"SpaceDeveloper\")).To(ExitWith(0))\n\tExpect(cf.Cf(\"set-space-role\", uc.Username, uc.Org, sname, \"SpaceAuditor\")).To(ExitWith(0))\n}\n<commit_msg>Remove explicit space argument from space setup helper function<commit_after>package helpers\n\nimport (\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/vito\/cmdtest\/matchers\"\n\n\t\"github.com\/pivotal-cf-experimental\/cf-test-helpers\/cf\"\n)\n\nvar AdminUserContext cf.UserContext\nvar RegularUserContext cf.UserContext\n\ntype SuiteContext interface {\n\tSetup()\n\tTeardown()\n\n\tAdminUserContext() cf.UserContext\n\tRegularUserContext() cf.UserContext\n}\n\nfunc SetupEnvironment(context SuiteContext) {\n\tvar originalCfHomeDir, currentCfHomeDir string\n\n\tBeforeEach(func() {\n\t\tAdminUserContext = context.AdminUserContext()\n\t\tRegularUserContext = context.RegularUserContext()\n\n\t\tcontext.Setup()\n\n\t\tcf.AsUser(AdminUserContext, func() {\n\t\t\tsetUpSpaceWithUserAccess(RegularUserContext)\n\t\t})\n\n\t\toriginalCfHomeDir, currentCfHomeDir = cf.InitiateUserContext(RegularUserContext)\n\t\tcf.TargetSpace(RegularUserContext)\n\t})\n\n\tAfterEach(func() {\n\t\tcf.RestoreUserContext(RegularUserContext, originalCfHomeDir, currentCfHomeDir)\n\n\t\tcontext.Teardown()\n\t})\n}\n\nfunc setUpSpaceWithUserAccess(uc cf.UserContext) {\n\tExpect(cf.Cf(\"create-space\", \"-o\", uc.Org, uc.Space)).To(ExitWith(0))\n\tExpect(cf.Cf(\"set-space-role\", uc.Username, uc.Org, uc.Space, \"SpaceManager\")).To(ExitWith(0))\n\tExpect(cf.Cf(\"set-space-role\", uc.Username, uc.Org, uc.Space, \"SpaceDeveloper\")).To(ExitWith(0))\n\tExpect(cf.Cf(\"set-space-role\", uc.Username, uc.Org, uc.Space, \"SpaceAuditor\")).To(ExitWith(0))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage commands\n\nimport (\n\t\"github.com\/GoogleContainerTools\/kpt\/internal\/docs\/generated\/cfgdocs\"\n\t\"github.com\/spf13\/cobra\"\n\t\"sigs.k8s.io\/kustomize\/cmd\/config\/configcobra\"\n)\n\nfunc GetConfigCommand(name string) *cobra.Command {\n\tcfgCmd := &cobra.Command{\n\t\tUse:     \"cfg\",\n\t\tShort:   cfgdocs.READMEShort,\n\t\tLong:    cfgdocs.READMEShort + \"\\n\" + cfgdocs.READMELong,\n\t\tExample: cfgdocs.READMEExamples,\n\t\tAliases: []string{\"config\"},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\th, err := cmd.Flags().GetBool(\"help\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif h {\n\t\t\t\treturn cmd.Help()\n\t\t\t}\n\t\t\treturn cmd.Usage()\n\t\t},\n\t}\n\n\tan := configcobra.Annotate(name)\n\tan.Short = cfgdocs.AnnotateShort\n\tan.Long = cfgdocs.AnnotateShort + \"\\n\" + cfgdocs.AnnotateLong\n\tan.Example = cfgdocs.AnnotateExamples\n\n\tcat := configcobra.Cat(name)\n\tcat.Short = cfgdocs.CatShort\n\tcat.Long = cfgdocs.CatShort + \"\\n\" + cfgdocs.CatLong\n\tcat.Example = cfgdocs.CatExamples\n\n\tcount := configcobra.Count(name)\n\tcount.Short = cfgdocs.CountShort\n\tcount.Long = cfgdocs.CountShort + \"\\n\" + cfgdocs.CountLong\n\tcount.Example = cfgdocs.CountExamples\n\n\tcreateSetter := configcobra.CreateSetter(name)\n\tcreateSetter.Short = cfgdocs.CreateSetterShort\n\tcreateSetter.Long = cfgdocs.CreateSetterShort + \"\\n\" + cfgdocs.CreateSetterLong\n\tcreateSetter.Example = cfgdocs.CreateSetterExamples\n\n\tfmt := configcobra.Fmt(name)\n\tfmt.Short = cfgdocs.FmtShort\n\tfmt.Long = cfgdocs.FmtShort + \"\\n\" + cfgdocs.FmtLong\n\tfmt.Example = cfgdocs.FmtExamples\n\n\tgrep := configcobra.Grep(name)\n\tgrep.Short = cfgdocs.GrepShort\n\tgrep.Long = cfgdocs.GrepShort + \"\\n\" + cfgdocs.GrepLong\n\tgrep.Example = cfgdocs.GrepExamples\n\n\tlistSetters := configcobra.ListSetters(name)\n\tlistSetters.Short = cfgdocs.ListSettersShort\n\tlistSetters.Long = cfgdocs.ListSettersShort + \"\\n\" + cfgdocs.ListSettersLong\n\tlistSetters.Example = cfgdocs.ListSettersExamples\n\n\tset := configcobra.Set(name)\n\tset.Short = cfgdocs.SetShort\n\tset.Long = cfgdocs.SetShort + \"\\n\" + cfgdocs.SetLong\n\tset.Example = cfgdocs.SetExamples\n\n\ttree := configcobra.Tree(name)\n\ttree.Short = cfgdocs.TreeShort\n\ttree.Long = cfgdocs.TreeShort + \"\\n\" + cfgdocs.TreeLong\n\ttree.Example = cfgdocs.TreeExamples\n\n\tcfgCmd.AddCommand(an, cat, count, createSetter, fmt,\n\t\tgrep, listSetters, set, tree)\n\treturn cfgCmd\n}\n<commit_msg>wrap cfg set to add implicit project number set<commit_after>\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage commands\n\nimport (\n\t\"github.com\/GoogleContainerTools\/kpt\/internal\/docs\/generated\/cfgdocs\"\n\t\"github.com\/GoogleContainerTools\/kpt\/internal\/util\/setters\"\n\t\"github.com\/spf13\/cobra\"\n\t\"sigs.k8s.io\/kustomize\/cmd\/config\/configcobra\"\n)\n\nfunc GetConfigCommand(name string) *cobra.Command {\n\tcfgCmd := &cobra.Command{\n\t\tUse:     \"cfg\",\n\t\tShort:   cfgdocs.READMEShort,\n\t\tLong:    cfgdocs.READMEShort + \"\\n\" + cfgdocs.READMELong,\n\t\tExample: cfgdocs.READMEExamples,\n\t\tAliases: []string{\"config\"},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\th, err := cmd.Flags().GetBool(\"help\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif h {\n\t\t\t\treturn cmd.Help()\n\t\t\t}\n\t\t\treturn cmd.Usage()\n\t\t},\n\t}\n\n\tan := configcobra.Annotate(name)\n\tan.Short = cfgdocs.AnnotateShort\n\tan.Long = cfgdocs.AnnotateShort + \"\\n\" + cfgdocs.AnnotateLong\n\tan.Example = cfgdocs.AnnotateExamples\n\n\tcat := configcobra.Cat(name)\n\tcat.Short = cfgdocs.CatShort\n\tcat.Long = cfgdocs.CatShort + \"\\n\" + cfgdocs.CatLong\n\tcat.Example = cfgdocs.CatExamples\n\n\tcount := configcobra.Count(name)\n\tcount.Short = cfgdocs.CountShort\n\tcount.Long = cfgdocs.CountShort + \"\\n\" + cfgdocs.CountLong\n\tcount.Example = cfgdocs.CountExamples\n\n\tcreateSetter := configcobra.CreateSetter(name)\n\tcreateSetter.Short = cfgdocs.CreateSetterShort\n\tcreateSetter.Long = cfgdocs.CreateSetterShort + \"\\n\" + cfgdocs.CreateSetterLong\n\tcreateSetter.Example = cfgdocs.CreateSetterExamples\n\n\tfmt := configcobra.Fmt(name)\n\tfmt.Short = cfgdocs.FmtShort\n\tfmt.Long = cfgdocs.FmtShort + \"\\n\" + cfgdocs.FmtLong\n\tfmt.Example = cfgdocs.FmtExamples\n\n\tgrep := configcobra.Grep(name)\n\tgrep.Short = cfgdocs.GrepShort\n\tgrep.Long = cfgdocs.GrepShort + \"\\n\" + cfgdocs.GrepLong\n\tgrep.Example = cfgdocs.GrepExamples\n\n\tlistSetters := configcobra.ListSetters(name)\n\tlistSetters.Short = cfgdocs.ListSettersShort\n\tlistSetters.Long = cfgdocs.ListSettersShort + \"\\n\" + cfgdocs.ListSettersLong\n\tlistSetters.Example = cfgdocs.ListSettersExamples\n\n\tset := SetCommand(name)\n\tset.Short = cfgdocs.SetShort\n\tset.Long = cfgdocs.SetShort + \"\\n\" + cfgdocs.SetLong\n\tset.Example = cfgdocs.SetExamples\n\n\ttree := configcobra.Tree(name)\n\ttree.Short = cfgdocs.TreeShort\n\ttree.Long = cfgdocs.TreeShort + \"\\n\" + cfgdocs.TreeLong\n\ttree.Example = cfgdocs.TreeExamples\n\n\tcfgCmd.AddCommand(an, cat, count, createSetter, fmt,\n\t\tgrep, listSetters, set, tree)\n\treturn cfgCmd\n}\n\n\/\/ SetCommand wraps the kustomize set command in order to automatically update\n\/\/ a project number if a project id is set.\nfunc SetCommand(parent string) *cobra.Command {\n\tkustomizeCmd := configcobra.Set(parent)\n\tsetCmd := *kustomizeCmd\n\tsetCmd.RunE = func(c *cobra.Command, args []string) error {\n\t\tkustomizeCmd.SetArgs(args)\n\t\tif err := kustomizeCmd.Execute(); err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tif len(args) != 3 || args[1] != \"gcloud.core.project\" {\n\t\t\treturn nil\n\t\t}\n\t\tprojectNumber, err := setters.GetProjectNumberFromProjectID(args[2])\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tkustomizeCmd.SetArgs([]string{args[0], \"gcloud.project.projectNumber\", projectNumber})\n\t\treturn kustomizeCmd.Execute()\n\t}\n\treturn &setCmd\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Doctl Authors All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage commands\n\nimport (\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/apache\/openwhisk-client-go\/whisk\"\n\t\"github.com\/digitalocean\/doctl\"\n\t\"github.com\/digitalocean\/doctl\/commands\/displayers\"\n\t\"github.com\/digitalocean\/doctl\/do\"\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ Functions generates the serverless 'functions' subtree for addition to the doctl command\nfunc Functions() *Command {\n\tcmd := &Command{\n\t\tCommand: &cobra.Command{\n\t\t\tUse:   \"functions\",\n\t\t\tShort: \"Work with the functions in your namespace\",\n\t\t\tLong: `The subcommands of ` + \"`\" + `doctl serverless functions` + \"`\" + ` operate on your functions namespace.\nYou are able to inspect and list these functions to know what is deployed.  You can also invoke functions to test them.`,\n\t\t\tAliases: []string{\"fn\"},\n\t\t},\n\t}\n\n\tget := CmdBuilder(cmd, RunFunctionsGet, \"get <functionName>\", \"Retrieves the deployed copy of a function (code or metadata)\",\n\t\t`Use `+\"`\"+`doctl serverless functions get`+\"`\"+` to obtain the code or metadata of a deployed function.\nThis allows you to inspect the deployed copy and ascertain whether it corresponds to what\nis in your functions project in the local file system.`,\n\t\tWriter)\n\tAddBoolFlag(get, \"url\", \"r\", false, \"get function url\")\n\tAddBoolFlag(get, \"code\", \"\", false, \"show function code (only works if code is not a zip file)\")\n\tAddStringFlag(get, \"save-env\", \"E\", \"\", \"save environment variables to FILE as key-value pairs\")\n\tAddStringFlag(get, \"save-env-json\", \"J\", \"\", \"save environment variables to FILE as JSON\")\n\tAddBoolFlag(get, \"save\", \"\", false, \"save function code to file corresponding to the function name\")\n\tAddStringFlag(get, \"save-as\", \"\", \"\", \"file to save function code to\")\n\n\tinvoke := CmdBuilder(cmd, RunFunctionsInvoke, \"invoke <functionName>\", \"Invokes a function\",\n\t\t`Use `+\"`\"+`doctl serverless functions invoke`+\"`\"+` to invoke a function in your functions namespace.\nYou can provide inputs and inspect outputs.`,\n\t\tWriter)\n\tAddBoolFlag(invoke, \"web\", \"\", false, \"Invoke as a web function, show result as web page\")\n\tAddStringSliceFlag(invoke, \"param\", \"p\", []string{}, \"parameter values in KEY:VALUE format, list allowed\")\n\tAddStringFlag(invoke, \"param-file\", \"P\", \"\", \"FILE containing parameter values in JSON format\")\n\tAddBoolFlag(invoke, \"full\", \"f\", false, \"wait for full activation record\")\n\tAddBoolFlag(invoke, \"no-wait\", \"n\", false, \"fire and forget (asynchronous invoke, does not wait for the result)\")\n\n\tlist := CmdBuilder(cmd, RunFunctionsList, \"list [<packageName>]\", \"Lists the functions in your functions namespace\",\n\t\t`Use `+\"`\"+`doctl serverless functions list`+\"`\"+` to list the functions in your functions namespace.`,\n\t\tWriter, aliasOpt(\"ls\"), displayerType(&displayers.Functions{}))\n\tAddStringFlag(list, \"limit\", \"l\", \"\", \"only return LIMIT number of functions (default 30, max 200)\")\n\tAddStringFlag(list, \"skip\", \"s\", \"\", \"exclude the first SKIP number of functions from the result\")\n\tAddBoolFlag(list, \"count\", \"\", false, \"show only the total number of functions\")\n\tAddBoolFlag(list, \"name-sort\", \"\", false, \"sort results by name\")\n\tAddBoolFlag(list, \"name\", \"n\", false, \"sort results by name\")\n\n\treturn cmd\n}\n\n\/\/ RunFunctionsGet supports the 'serverless functions get' command\nfunc RunFunctionsGet(c *CmdConfig) error {\n\terr := ensureOneArg(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\turlFlag, _ := c.Doit.GetBool(c.NS, flagURL)\n\tcodeFlag, _ := c.Doit.GetBool(c.NS, flagCode)\n\tsaveFlag, _ := c.Doit.GetBool(c.NS, flagSave)\n\tsaveAsFlag, _ := c.Doit.GetString(c.NS, flagSaveAs)\n\tsaveEnvFlag, _ := c.Doit.GetString(c.NS, flagSaveEnv)\n\tsaveEnvJSONFlag, _ := c.Doit.GetString(c.NS, flagSaveEnvJSON)\n\tfetchCode := codeFlag || saveFlag || saveAsFlag != \"\"\n\n\tsls := c.Serverless()\n\taction, parms, err := sls.GetFunction(c.Args[0], fetchCode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif urlFlag {\n\t\thost, err := sls.GetConnectedAPIHost()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = fmt.Fprintln(c.Out, computeURL(action, host))\n\t\treturn err\n\t}\n\n\tif saveFlag || saveAsFlag != \"\" {\n\t\treturn doSaveFunctionCode(action, saveFlag, saveAsFlag)\n\t}\n\n\tif saveEnvFlag != \"\" || saveEnvJSONFlag != \"\" {\n\t\treturn doSaveFunctionEnvironment(saveEnvFlag, saveEnvJSONFlag, parms)\n\t}\n\n\tif codeFlag {\n\t\tif !*action.Exec.Binary {\n\t\t\t_, err = fmt.Fprintln(c.Out, *action.Exec.Code)\n\t\t\treturn err\n\t\t}\n\t\treturn errors.New(\"Binary code cannot be displayed on the console\")\n\t}\n\n\toutput := do.ServerlessOutput{Entity: action}\n\treturn c.PrintServerlessTextOutput(output)\n}\n\n\/\/ doSaveFunctionCode performs the save operations for code\nfunc doSaveFunctionCode(action whisk.Action, save bool, saveAs string) error {\n\tvar extension string \/\/ used only when save and !saveAs\n\tvar data []byte\n\tif *action.Exec.Binary {\n\t\textension = \".zip\"\n\t\tdecoded, err := base64.StdEncoding.DecodeString(*action.Exec.Code)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdata = decoded\n\t} else {\n\t\textension = fileExtensionForKind(action.Exec.Kind) \/\/ find equivalent\n\t\tdata = []byte(*action.Exec.Code)\n\t}\n\tif save && saveAs == \"\" {\n\t\tsaveAs = action.Name + extension\n\t}\n\tif saveAs != \"\" {\n\t\terr := os.WriteFile(saveAs, data, 0666)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ doSaveFunctionEnvironment saves the environment variables for a function to file,\n\/\/ either as key-value pairs or JSON.  Could do both if both are specified.\nfunc doSaveFunctionEnvironment(saveEnv string, saveEnvJSON string, parms []do.FunctionParameter) error {\n\tkeyVals := []string{}\n\tenvMap := map[string]string{}\n\tfor _, parm := range parms {\n\t\tif parm.Init {\n\t\t\tkeyVal := parm.Key + \"=\" + parm.Value\n\t\t\tkeyVals = append(keyVals, keyVal)\n\t\t\tenvMap[parm.Key] = parm.Value\n\t\t}\n\t}\n\n\tif saveEnv != \"\" {\n\t\tdata := []byte(strings.Join(keyVals, \"\\n\"))\n\t\terr := os.WriteFile(saveEnv, data, 0666)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif saveEnvJSON != \"\" {\n\t\tdata, err := json.MarshalIndent(&envMap, \"\", \"  \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = os.WriteFile(saveEnvJSON, data, 0666)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ fileExtensionforKind finds the right file extension for a given runtime 'kind'.\n\/\/ This code will require modification when the repertoire of runtimes is extended.\nfunc fileExtensionForKind(kind string) string {\n\tlang := strings.Split(kind, \":\")[0]\n\tswitch strings.ToLower(lang) {\n\tcase \"go\":\n\t\treturn \".go\"\n\tcase \"nodejs\":\n\t\treturn \".js\"\n\tcase \"php\":\n\t\treturn \".php\"\n\tcase \"python\":\n\t\treturn \".py\"\n\t}\n\treturn \"\"\n}\n\n\/\/ computeURL determines the URL string based on the action get output.\n\/\/ Based on code in aio-cli-plugin-runtime, src\/commands\/runtime\/action\/get.js\nfunc computeURL(action whisk.Action, host string) string {\n\tnameParts := strings.Split(action.Namespace, \"\/\")\n\tnamespace := nameParts[0]\n\tvar packageName string\n\tif len(nameParts) > 1 {\n\t\tpackageName = nameParts[1]\n\t}\n\tif action.WebAction() {\n\t\tif packageName == \"\" {\n\t\t\tpackageName = \"default\"\n\t\t}\n\t\treturn fmt.Sprintf(\"%s\/api\/v1\/web\/%s\/%s\/%s\", host, namespace, packageName, action.Name)\n\t}\n\tif packageName != \"\" {\n\t\tpackageName += \"\/\"\n\t}\n\treturn fmt.Sprintf(\"%s\/api\/v1\/namespaces\/%s\/actions\/%s%s\", host, namespace, packageName, action.Name)\n}\n\n\/\/ RunFunctionsInvoke supports the 'serverless functions invoke' command\nfunc RunFunctionsInvoke(c *CmdConfig) error {\n\terr := ensureOneArg(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparamFile, _ := c.Doit.GetString(c.NS, flagParamFile)\n\tparamFlags, _ := c.Doit.GetStringSlice(c.NS, flagParam)\n\tparams, err := consolidateParams(paramFile, paramFlags)\n\tif err != nil {\n\t\treturn err\n\t}\n\tweb, _ := c.Doit.GetBool(c.NS, flagWeb)\n\tif web {\n\t\tvar mapParams map[string]interface{} = nil\n\t\tif params != nil {\n\t\t\tp, ok := params.(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"cannot invoke via web: parameters do not form a dictionary\")\n\t\t\t}\n\t\t\tmapParams = p\n\t\t}\n\t\treturn c.Serverless().InvokeFunctionViaWeb(c.Args[0], mapParams)\n\t}\n\tfull, _ := c.Doit.GetBool(c.NS, flagFull)\n\tnoWait, _ := c.Doit.GetBool(c.NS, flagNoWait)\n\tblocking := !noWait\n\tresult := blocking && !full\n\tresponse, err := c.Serverless().InvokeFunction(c.Args[0], params, blocking, result)\n\tif err != nil {\n\t\treturn err\n\t}\n\toutput := do.ServerlessOutput{Entity: response}\n\treturn c.PrintServerlessTextOutput(output)\n}\n\n\/\/ RunFunctionsList supports the 'serverless functions list' command\nfunc RunFunctionsList(c *CmdConfig) error {\n\targCount := len(c.Args)\n\tif argCount > 1 {\n\t\treturn doctl.NewTooManyArgsErr(c.NS)\n\t}\n\tvar pkg string\n\tif argCount == 1 {\n\t\tpkg = c.Args[0]\n\t}\n\t\/\/ Determine if '--count' is requested since we will use simple text output in that case.\n\t\/\/ Count is mutually exclusive with the global format flag.\n\tcount, _ := c.Doit.GetBool(c.NS, flagCount)\n\tif count && c.Doit.IsSet(\"format\") {\n\t\treturn errors.New(\"the --count and --format flags are mutually exclusive\")\n\t}\n\t\/\/ Retrieve other flags\n\tskip, _ := c.Doit.GetInt(c.NS, flagSkip)\n\tlimit, _ := c.Doit.GetInt(c.NS, flagLimit)\n\tnameSort, _ := c.Doit.GetBool(c.NS, flagNameSort)\n\tnameName, _ := c.Doit.GetBool(c.NS, flagNameName)\n\t\/\/ Get information from backend\n\tlist, err := c.Serverless().ListFunctions(pkg, skip, limit)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif count {\n\t\tplural := \"s\"\n\t\tare := \"are\"\n\t\tif len(list) == 1 {\n\t\t\tplural = \"\"\n\t\t\tare = \"is\"\n\t\t}\n\t\tfmt.Fprintf(c.Out, \"There %s %d function%s in this namespace.\\n\", are, len(list), plural)\n\t\treturn nil\n\t}\n\tif nameSort || nameName {\n\t\tsortFunctionList(list)\n\t}\n\treturn c.Display(&displayers.Functions{Info: list})\n}\n\n\/\/ sortFunctionList performs a sort of a function list (by name)\nfunc sortFunctionList(list []whisk.Action) {\n\tisLess := func(i, j int) bool {\n\t\treturn list[i].Name < list[j].Name\n\t}\n\tsort.Slice(list, isLess)\n}\n\n\/\/ consolidateParams accepts parameters from a file, the command line, or both, and consolidates all\n\/\/ such parameters into a simple dictionary.\nfunc consolidateParams(paramFile string, params []string) (interface{}, error) {\n\tconsolidated := map[string]interface{}{}\n\tif len(paramFile) > 0 {\n\t\tcontents, err := os.ReadFile(paramFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = json.Unmarshal(contents, &consolidated)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tfor _, param := range params {\n\t\tparts := strings.Split(param, \":\")\n\t\tif len(parts) < 2 {\n\t\t\treturn nil, fmt.Errorf(\"values for --params must have KEY:VALUE form\")\n\t\t}\n\t\tparts1 := strings.Join(parts[1:], \":\")\n\t\tconsolidated[parts[0]] = parts1\n\t}\n\tif len(consolidated) > 0 {\n\t\treturn consolidated, nil\n\t}\n\treturn nil, nil\n}\n<commit_msg>Adds a more descriptive output of what happens when long running functions are invoked synchronously (#1298)<commit_after>\/*\nCopyright 2018 The Doctl Authors All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage commands\n\nimport (\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/apache\/openwhisk-client-go\/whisk\"\n\t\"github.com\/digitalocean\/doctl\"\n\t\"github.com\/digitalocean\/doctl\/commands\/charm\/template\"\n\t\"github.com\/digitalocean\/doctl\/commands\/displayers\"\n\t\"github.com\/digitalocean\/doctl\/do\"\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ Functions generates the serverless 'functions' subtree for addition to the doctl command\nfunc Functions() *Command {\n\tcmd := &Command{\n\t\tCommand: &cobra.Command{\n\t\t\tUse:   \"functions\",\n\t\t\tShort: \"Work with the functions in your namespace\",\n\t\t\tLong: `The subcommands of ` + \"`\" + `doctl serverless functions` + \"`\" + ` operate on your functions namespace.\nYou are able to inspect and list these functions to know what is deployed.  You can also invoke functions to test them.`,\n\t\t\tAliases: []string{\"fn\"},\n\t\t},\n\t}\n\n\tget := CmdBuilder(cmd, RunFunctionsGet, \"get <functionName>\", \"Retrieves the deployed copy of a function (code or metadata)\",\n\t\t`Use `+\"`\"+`doctl serverless functions get`+\"`\"+` to obtain the code or metadata of a deployed function.\nThis allows you to inspect the deployed copy and ascertain whether it corresponds to what\nis in your functions project in the local file system.`,\n\t\tWriter)\n\tAddBoolFlag(get, \"url\", \"r\", false, \"get function url\")\n\tAddBoolFlag(get, \"code\", \"\", false, \"show function code (only works if code is not a zip file)\")\n\tAddStringFlag(get, \"save-env\", \"E\", \"\", \"save environment variables to FILE as key-value pairs\")\n\tAddStringFlag(get, \"save-env-json\", \"J\", \"\", \"save environment variables to FILE as JSON\")\n\tAddBoolFlag(get, \"save\", \"\", false, \"save function code to file corresponding to the function name\")\n\tAddStringFlag(get, \"save-as\", \"\", \"\", \"file to save function code to\")\n\n\tinvoke := CmdBuilder(cmd, RunFunctionsInvoke, \"invoke <functionName>\", \"Invokes a function\",\n\t\t`Use `+\"`\"+`doctl serverless functions invoke`+\"`\"+` to invoke a function in your functions namespace.\nYou can provide inputs and inspect outputs.`,\n\t\tWriter)\n\tAddBoolFlag(invoke, \"web\", \"\", false, \"Invoke as a web function, show result as web page\")\n\tAddStringSliceFlag(invoke, \"param\", \"p\", []string{}, \"parameter values in KEY:VALUE format, list allowed\")\n\tAddStringFlag(invoke, \"param-file\", \"P\", \"\", \"FILE containing parameter values in JSON format\")\n\tAddBoolFlag(invoke, \"full\", \"f\", false, \"wait for full activation record\")\n\tAddBoolFlag(invoke, \"no-wait\", \"n\", false, \"fire and forget (asynchronous invoke, does not wait for the result)\")\n\n\tlist := CmdBuilder(cmd, RunFunctionsList, \"list [<packageName>]\", \"Lists the functions in your functions namespace\",\n\t\t`Use `+\"`\"+`doctl serverless functions list`+\"`\"+` to list the functions in your functions namespace.`,\n\t\tWriter, aliasOpt(\"ls\"), displayerType(&displayers.Functions{}))\n\tAddStringFlag(list, \"limit\", \"l\", \"\", \"only return LIMIT number of functions (default 30, max 200)\")\n\tAddStringFlag(list, \"skip\", \"s\", \"\", \"exclude the first SKIP number of functions from the result\")\n\tAddBoolFlag(list, \"count\", \"\", false, \"show only the total number of functions\")\n\tAddBoolFlag(list, \"name-sort\", \"\", false, \"sort results by name\")\n\tAddBoolFlag(list, \"name\", \"n\", false, \"sort results by name\")\n\n\treturn cmd\n}\n\n\/\/ RunFunctionsGet supports the 'serverless functions get' command\nfunc RunFunctionsGet(c *CmdConfig) error {\n\terr := ensureOneArg(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\turlFlag, _ := c.Doit.GetBool(c.NS, flagURL)\n\tcodeFlag, _ := c.Doit.GetBool(c.NS, flagCode)\n\tsaveFlag, _ := c.Doit.GetBool(c.NS, flagSave)\n\tsaveAsFlag, _ := c.Doit.GetString(c.NS, flagSaveAs)\n\tsaveEnvFlag, _ := c.Doit.GetString(c.NS, flagSaveEnv)\n\tsaveEnvJSONFlag, _ := c.Doit.GetString(c.NS, flagSaveEnvJSON)\n\tfetchCode := codeFlag || saveFlag || saveAsFlag != \"\"\n\n\tsls := c.Serverless()\n\taction, parms, err := sls.GetFunction(c.Args[0], fetchCode)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif urlFlag {\n\t\thost, err := sls.GetConnectedAPIHost()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = fmt.Fprintln(c.Out, computeURL(action, host))\n\t\treturn err\n\t}\n\n\tif saveFlag || saveAsFlag != \"\" {\n\t\treturn doSaveFunctionCode(action, saveFlag, saveAsFlag)\n\t}\n\n\tif saveEnvFlag != \"\" || saveEnvJSONFlag != \"\" {\n\t\treturn doSaveFunctionEnvironment(saveEnvFlag, saveEnvJSONFlag, parms)\n\t}\n\n\tif codeFlag {\n\t\tif !*action.Exec.Binary {\n\t\t\t_, err = fmt.Fprintln(c.Out, *action.Exec.Code)\n\t\t\treturn err\n\t\t}\n\t\treturn errors.New(\"Binary code cannot be displayed on the console\")\n\t}\n\n\toutput := do.ServerlessOutput{Entity: action}\n\treturn c.PrintServerlessTextOutput(output)\n}\n\n\/\/ doSaveFunctionCode performs the save operations for code\nfunc doSaveFunctionCode(action whisk.Action, save bool, saveAs string) error {\n\tvar extension string \/\/ used only when save and !saveAs\n\tvar data []byte\n\tif *action.Exec.Binary {\n\t\textension = \".zip\"\n\t\tdecoded, err := base64.StdEncoding.DecodeString(*action.Exec.Code)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdata = decoded\n\t} else {\n\t\textension = fileExtensionForKind(action.Exec.Kind) \/\/ find equivalent\n\t\tdata = []byte(*action.Exec.Code)\n\t}\n\tif save && saveAs == \"\" {\n\t\tsaveAs = action.Name + extension\n\t}\n\tif saveAs != \"\" {\n\t\terr := os.WriteFile(saveAs, data, 0666)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ doSaveFunctionEnvironment saves the environment variables for a function to file,\n\/\/ either as key-value pairs or JSON.  Could do both if both are specified.\nfunc doSaveFunctionEnvironment(saveEnv string, saveEnvJSON string, parms []do.FunctionParameter) error {\n\tkeyVals := []string{}\n\tenvMap := map[string]string{}\n\tfor _, parm := range parms {\n\t\tif parm.Init {\n\t\t\tkeyVal := parm.Key + \"=\" + parm.Value\n\t\t\tkeyVals = append(keyVals, keyVal)\n\t\t\tenvMap[parm.Key] = parm.Value\n\t\t}\n\t}\n\n\tif saveEnv != \"\" {\n\t\tdata := []byte(strings.Join(keyVals, \"\\n\"))\n\t\terr := os.WriteFile(saveEnv, data, 0666)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif saveEnvJSON != \"\" {\n\t\tdata, err := json.MarshalIndent(&envMap, \"\", \"  \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = os.WriteFile(saveEnvJSON, data, 0666)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ fileExtensionforKind finds the right file extension for a given runtime 'kind'.\n\/\/ This code will require modification when the repertoire of runtimes is extended.\nfunc fileExtensionForKind(kind string) string {\n\tlang := strings.Split(kind, \":\")[0]\n\tswitch strings.ToLower(lang) {\n\tcase \"go\":\n\t\treturn \".go\"\n\tcase \"nodejs\":\n\t\treturn \".js\"\n\tcase \"php\":\n\t\treturn \".php\"\n\tcase \"python\":\n\t\treturn \".py\"\n\t}\n\treturn \"\"\n}\n\n\/\/ computeURL determines the URL string based on the action get output.\n\/\/ Based on code in aio-cli-plugin-runtime, src\/commands\/runtime\/action\/get.js\nfunc computeURL(action whisk.Action, host string) string {\n\tnameParts := strings.Split(action.Namespace, \"\/\")\n\tnamespace := nameParts[0]\n\tvar packageName string\n\tif len(nameParts) > 1 {\n\t\tpackageName = nameParts[1]\n\t}\n\tif action.WebAction() {\n\t\tif packageName == \"\" {\n\t\t\tpackageName = \"default\"\n\t\t}\n\t\treturn fmt.Sprintf(\"%s\/api\/v1\/web\/%s\/%s\/%s\", host, namespace, packageName, action.Name)\n\t}\n\tif packageName != \"\" {\n\t\tpackageName += \"\/\"\n\t}\n\treturn fmt.Sprintf(\"%s\/api\/v1\/namespaces\/%s\/actions\/%s%s\", host, namespace, packageName, action.Name)\n}\n\n\/\/ RunFunctionsInvoke supports the 'serverless functions invoke' command\nfunc RunFunctionsInvoke(c *CmdConfig) error {\n\terr := ensureOneArg(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tparamFile, _ := c.Doit.GetString(c.NS, flagParamFile)\n\tparamFlags, _ := c.Doit.GetStringSlice(c.NS, flagParam)\n\tparams, err := consolidateParams(paramFile, paramFlags)\n\tif err != nil {\n\t\treturn err\n\t}\n\tweb, _ := c.Doit.GetBool(c.NS, flagWeb)\n\tif web {\n\t\tvar mapParams map[string]interface{} = nil\n\t\tif params != nil {\n\t\t\tp, ok := params.(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"cannot invoke via web: parameters do not form a dictionary\")\n\t\t\t}\n\t\t\tmapParams = p\n\t\t}\n\t\treturn c.Serverless().InvokeFunctionViaWeb(c.Args[0], mapParams)\n\t}\n\tfull, _ := c.Doit.GetBool(c.NS, flagFull)\n\tnoWait, _ := c.Doit.GetBool(c.NS, flagNoWait)\n\tblocking := !noWait\n\tresult := blocking && !full\n\tresponse, err := c.Serverless().InvokeFunction(c.Args[0], params, blocking, result)\n\n\tif err != nil {\n\t\tif response != nil {\n\t\t\tactivationResponse := response.(map[string]interface{})\n\t\t\ttemplate.Print(`Request accepted, but processing not completed yet. {{nl}}All functions invocation >= 30s will get demoted to an asynchronous invocation. Use {{highlight \"--no-wait\"}} flag to immediately return the activation id. {{nl}}\nUse this command to view the results.\n{{bold \"doctl sls activations result\" }} {{bold .}} {{nl 2}}`, activationResponse[\"activationId\"])\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\toutput := do.ServerlessOutput{Entity: response}\n\treturn c.PrintServerlessTextOutput(output)\n}\n\n\/\/ RunFunctionsList supports the 'serverless functions list' command\nfunc RunFunctionsList(c *CmdConfig) error {\n\targCount := len(c.Args)\n\tif argCount > 1 {\n\t\treturn doctl.NewTooManyArgsErr(c.NS)\n\t}\n\tvar pkg string\n\tif argCount == 1 {\n\t\tpkg = c.Args[0]\n\t}\n\t\/\/ Determine if '--count' is requested since we will use simple text output in that case.\n\t\/\/ Count is mutually exclusive with the global format flag.\n\tcount, _ := c.Doit.GetBool(c.NS, flagCount)\n\tif count && c.Doit.IsSet(\"format\") {\n\t\treturn errors.New(\"the --count and --format flags are mutually exclusive\")\n\t}\n\t\/\/ Retrieve other flags\n\tskip, _ := c.Doit.GetInt(c.NS, flagSkip)\n\tlimit, _ := c.Doit.GetInt(c.NS, flagLimit)\n\tnameSort, _ := c.Doit.GetBool(c.NS, flagNameSort)\n\tnameName, _ := c.Doit.GetBool(c.NS, flagNameName)\n\t\/\/ Get information from backend\n\tlist, err := c.Serverless().ListFunctions(pkg, skip, limit)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif count {\n\t\tplural := \"s\"\n\t\tare := \"are\"\n\t\tif len(list) == 1 {\n\t\t\tplural = \"\"\n\t\t\tare = \"is\"\n\t\t}\n\t\tfmt.Fprintf(c.Out, \"There %s %d function%s in this namespace.\\n\", are, len(list), plural)\n\t\treturn nil\n\t}\n\tif nameSort || nameName {\n\t\tsortFunctionList(list)\n\t}\n\treturn c.Display(&displayers.Functions{Info: list})\n}\n\n\/\/ sortFunctionList performs a sort of a function list (by name)\nfunc sortFunctionList(list []whisk.Action) {\n\tisLess := func(i, j int) bool {\n\t\treturn list[i].Name < list[j].Name\n\t}\n\tsort.Slice(list, isLess)\n}\n\n\/\/ consolidateParams accepts parameters from a file, the command line, or both, and consolidates all\n\/\/ such parameters into a simple dictionary.\nfunc consolidateParams(paramFile string, params []string) (interface{}, error) {\n\tconsolidated := map[string]interface{}{}\n\tif len(paramFile) > 0 {\n\t\tcontents, err := os.ReadFile(paramFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = json.Unmarshal(contents, &consolidated)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tfor _, param := range params {\n\t\tparts := strings.Split(param, \":\")\n\t\tif len(parts) < 2 {\n\t\t\treturn nil, fmt.Errorf(\"values for --params must have KEY:VALUE form\")\n\t\t}\n\t\tparts1 := strings.Join(parts[1:], \":\")\n\t\tconsolidated[parts[0]] = parts1\n\t}\n\tif len(consolidated) > 0 {\n\t\treturn consolidated, nil\n\t}\n\treturn nil, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package crypto\n\nimport (\n\t\"crypto\/cipher\"\n\t\"io\"\n\n\t\"v2ray.com\/core\/common\"\n\t\"v2ray.com\/core\/common\/buf\"\n\t\"v2ray.com\/core\/common\/protocol\"\n)\n\ntype BytesGenerator interface {\n\tNext() []byte\n}\n\ntype NoOpBytesGenerator struct {\n\tbuffer [1]byte\n}\n\nfunc (v NoOpBytesGenerator) Next() []byte {\n\treturn v.buffer[:0]\n}\n\ntype StaticBytesGenerator struct {\n\tContent []byte\n}\n\nfunc (v StaticBytesGenerator) Next() []byte {\n\treturn v.Content\n}\n\ntype Authenticator interface {\n\tNonceSize() int\n\tOverhead() int\n\tOpen(dst, cipherText []byte) ([]byte, error)\n\tSeal(dst, plainText []byte) ([]byte, error)\n}\n\ntype AEADAuthenticator struct {\n\tcipher.AEAD\n\tNonceGenerator          BytesGenerator\n\tAdditionalDataGenerator BytesGenerator\n}\n\nfunc (v *AEADAuthenticator) Open(dst, cipherText []byte) ([]byte, error) {\n\tiv := v.NonceGenerator.Next()\n\tif len(iv) != v.AEAD.NonceSize() {\n\t\treturn nil, newError(\"invalid AEAD nonce size: \", len(iv))\n\t}\n\n\tadditionalData := v.AdditionalDataGenerator.Next()\n\treturn v.AEAD.Open(dst, iv, cipherText, additionalData)\n}\n\nfunc (v *AEADAuthenticator) Seal(dst, plainText []byte) ([]byte, error) {\n\tiv := v.NonceGenerator.Next()\n\tif len(iv) != v.AEAD.NonceSize() {\n\t\treturn nil, newError(\"invalid AEAD nonce size: \", len(iv))\n\t}\n\n\tadditionalData := v.AdditionalDataGenerator.Next()\n\treturn v.AEAD.Seal(dst, iv, plainText, additionalData), nil\n}\n\ntype AuthenticationReader struct {\n\tauth         Authenticator\n\tbuffer       *buf.Buffer\n\treader       io.Reader\n\tsizeParser   ChunkSizeDecoder\n\tsize         int\n\ttransferType protocol.TransferType\n}\n\nconst (\n\treaderBufferSize = 32 * 1024\n)\n\nfunc NewAuthenticationReader(auth Authenticator, sizeParser ChunkSizeDecoder, reader io.Reader, transferType protocol.TransferType) *AuthenticationReader {\n\treturn &AuthenticationReader{\n\t\tauth:         auth,\n\t\tbuffer:       buf.NewLocal(readerBufferSize),\n\t\treader:       reader,\n\t\tsizeParser:   sizeParser,\n\t\tsize:         -1,\n\t\ttransferType: transferType,\n\t}\n}\n\nfunc (r *AuthenticationReader) readSize() error {\n\tif r.size >= 0 {\n\t\treturn nil\n\t}\n\n\tsizeBytes := r.sizeParser.SizeBytes()\n\tif r.buffer.Len() < sizeBytes {\n\t\tif r.buffer.IsEmpty() {\n\t\t\tr.buffer.Clear()\n\t\t} else {\n\t\t\tcommon.Must(r.buffer.Reset(buf.ReadFrom(r.buffer)))\n\t\t}\n\n\t\tdelta := sizeBytes - r.buffer.Len()\n\t\tif err := r.buffer.AppendSupplier(buf.ReadAtLeastFrom(r.reader, delta)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tsize, err := r.sizeParser.Decode(r.buffer.BytesTo(sizeBytes))\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.size = int(size)\n\tr.buffer.SliceFrom(sizeBytes)\n\treturn nil\n}\n\nfunc (r *AuthenticationReader) readChunk(waitForData bool) ([]byte, error) {\n\tif err := r.readSize(); err != nil {\n\t\treturn nil, err\n\t}\n\tif r.size > readerBufferSize-r.sizeParser.SizeBytes() {\n\t\treturn nil, newError(\"size too large \", r.size).AtWarning()\n\t}\n\n\tif r.size == r.auth.Overhead() {\n\t\treturn nil, io.EOF\n\t}\n\n\tif r.buffer.Len() < r.size {\n\t\tif !waitForData {\n\t\t\treturn nil, io.ErrNoProgress\n\t\t}\n\n\t\tif r.buffer.IsEmpty() {\n\t\t\tr.buffer.Clear()\n\t\t} else {\n\t\t\tcommon.Must(r.buffer.Reset(buf.ReadFrom(r.buffer)))\n\t\t}\n\n\t\tdelta := r.size - r.buffer.Len()\n\t\tif err := r.buffer.AppendSupplier(buf.ReadAtLeastFrom(r.reader, delta)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tb, err := r.auth.Open(r.buffer.BytesTo(0), r.buffer.BytesTo(r.size))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr.buffer.SliceFrom(r.size)\n\tr.size = -1\n\treturn b, nil\n}\n\nfunc (r *AuthenticationReader) ReadMultiBuffer() (buf.MultiBuffer, error) {\n\tb, err := r.readChunk(true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar mb buf.MultiBuffer\n\tif r.transferType == protocol.TransferTypeStream {\n\t\tmb.Write(b)\n\t} else {\n\t\tvar bb *buf.Buffer\n\t\tif len(b) < buf.Size {\n\t\t\tbb = buf.New()\n\t\t} else {\n\t\t\tbb = buf.NewLocal(len(b))\n\t\t}\n\t\tbb.Append(b)\n\t\tmb.Append(bb)\n\t}\n\n\tfor r.buffer.Len() >= r.sizeParser.SizeBytes() {\n\t\tb, err := r.readChunk(false)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif r.transferType == protocol.TransferTypeStream {\n\t\t\tmb.Write(b)\n\t\t} else {\n\t\t\tvar bb *buf.Buffer\n\t\t\tif len(b) < buf.Size {\n\t\t\t\tbb = buf.New()\n\t\t\t} else {\n\t\t\t\tbb = buf.NewLocal(len(b))\n\t\t\t}\n\t\t\tbb.Append(b)\n\t\t\tmb.Append(bb)\n\t\t}\n\t}\n\n\treturn mb, nil\n}\n\nconst (\n\tWriteSize = 1024\n)\n\ntype AuthenticationWriter struct {\n\tauth         Authenticator\n\twriter       buf.Writer\n\tsizeParser   ChunkSizeEncoder\n\ttransferType protocol.TransferType\n}\n\nfunc NewAuthenticationWriter(auth Authenticator, sizeParser ChunkSizeEncoder, writer io.Writer, transferType protocol.TransferType) *AuthenticationWriter {\n\treturn &AuthenticationWriter{\n\t\tauth:         auth,\n\t\twriter:       buf.NewWriter(writer),\n\t\tsizeParser:   sizeParser,\n\t\ttransferType: transferType,\n\t}\n}\n\nfunc (w *AuthenticationWriter) seal(b *buf.Buffer) (*buf.Buffer, error) {\n\tencryptedSize := b.Len() + w.auth.Overhead()\n\n\teb := buf.New()\n\tcommon.Must(eb.Reset(func(bb []byte) (int, error) {\n\t\tw.sizeParser.Encode(uint16(encryptedSize), bb[:0])\n\t\treturn w.sizeParser.SizeBytes(), nil\n\t}))\n\tif err := eb.AppendSupplier(func(bb []byte) (int, error) {\n\t\t_, err := w.auth.Seal(bb[:0], b.Bytes())\n\t\treturn encryptedSize, err\n\t}); err != nil {\n\t\teb.Release()\n\t\treturn nil, err\n\t}\n\n\treturn eb, nil\n}\n\nfunc (w *AuthenticationWriter) writeStream(mb buf.MultiBuffer) error {\n\tdefer mb.Release()\n\n\tmb2Write := buf.NewMultiBufferCap(len(mb) + 10)\n\n\tfor {\n\t\tb := buf.New()\n\t\tcommon.Must(b.Reset(func(bb []byte) (int, error) {\n\t\t\treturn mb.Read(bb[:WriteSize])\n\t\t}))\n\t\teb, err := w.seal(b)\n\t\tb.Release()\n\n\t\tif err != nil {\n\t\t\tmb2Write.Release()\n\t\t\treturn err\n\t\t}\n\t\tmb2Write.Append(eb)\n\t\tif mb.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn w.writer.WriteMultiBuffer(mb2Write)\n}\n\nfunc (w *AuthenticationWriter) writePacket(mb buf.MultiBuffer) error {\n\tdefer mb.Release()\n\n\tmb2Write := buf.NewMultiBufferCap(len(mb) * 2)\n\n\tfor {\n\t\tb := mb.SplitFirst()\n\t\tif b == nil {\n\t\t\tb = buf.New()\n\t\t}\n\t\teb, err := w.seal(b)\n\t\tb.Release()\n\t\tif err != nil {\n\t\t\tmb2Write.Release()\n\t\t\treturn err\n\t\t}\n\t\tmb2Write.Append(eb)\n\t\tif mb.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn w.writer.WriteMultiBuffer(mb2Write)\n}\n\nfunc (w *AuthenticationWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {\n\tif w.transferType == protocol.TransferTypeStream {\n\t\treturn w.writeStream(mb)\n\t}\n\n\treturn w.writePacket(mb)\n}\n<commit_msg>fix length check in auth reader<commit_after>package crypto\n\nimport (\n\t\"crypto\/cipher\"\n\t\"io\"\n\n\t\"v2ray.com\/core\/common\"\n\t\"v2ray.com\/core\/common\/buf\"\n\t\"v2ray.com\/core\/common\/protocol\"\n)\n\ntype BytesGenerator interface {\n\tNext() []byte\n}\n\ntype NoOpBytesGenerator struct {\n\tbuffer [1]byte\n}\n\nfunc (v NoOpBytesGenerator) Next() []byte {\n\treturn v.buffer[:0]\n}\n\ntype StaticBytesGenerator struct {\n\tContent []byte\n}\n\nfunc (v StaticBytesGenerator) Next() []byte {\n\treturn v.Content\n}\n\ntype Authenticator interface {\n\tNonceSize() int\n\tOverhead() int\n\tOpen(dst, cipherText []byte) ([]byte, error)\n\tSeal(dst, plainText []byte) ([]byte, error)\n}\n\ntype AEADAuthenticator struct {\n\tcipher.AEAD\n\tNonceGenerator          BytesGenerator\n\tAdditionalDataGenerator BytesGenerator\n}\n\nfunc (v *AEADAuthenticator) Open(dst, cipherText []byte) ([]byte, error) {\n\tiv := v.NonceGenerator.Next()\n\tif len(iv) != v.AEAD.NonceSize() {\n\t\treturn nil, newError(\"invalid AEAD nonce size: \", len(iv))\n\t}\n\n\tadditionalData := v.AdditionalDataGenerator.Next()\n\treturn v.AEAD.Open(dst, iv, cipherText, additionalData)\n}\n\nfunc (v *AEADAuthenticator) Seal(dst, plainText []byte) ([]byte, error) {\n\tiv := v.NonceGenerator.Next()\n\tif len(iv) != v.AEAD.NonceSize() {\n\t\treturn nil, newError(\"invalid AEAD nonce size: \", len(iv))\n\t}\n\n\tadditionalData := v.AdditionalDataGenerator.Next()\n\treturn v.AEAD.Seal(dst, iv, plainText, additionalData), nil\n}\n\ntype AuthenticationReader struct {\n\tauth         Authenticator\n\tbuffer       *buf.Buffer\n\treader       io.Reader\n\tsizeParser   ChunkSizeDecoder\n\tsize         int\n\ttransferType protocol.TransferType\n}\n\nconst (\n\treaderBufferSize = 32 * 1024\n)\n\nfunc NewAuthenticationReader(auth Authenticator, sizeParser ChunkSizeDecoder, reader io.Reader, transferType protocol.TransferType) *AuthenticationReader {\n\treturn &AuthenticationReader{\n\t\tauth:         auth,\n\t\tbuffer:       buf.NewLocal(readerBufferSize),\n\t\treader:       reader,\n\t\tsizeParser:   sizeParser,\n\t\tsize:         -1,\n\t\ttransferType: transferType,\n\t}\n}\n\nfunc (r *AuthenticationReader) readSize() error {\n\tif r.size >= 0 {\n\t\treturn nil\n\t}\n\n\tsizeBytes := r.sizeParser.SizeBytes()\n\tif r.buffer.Len() < sizeBytes {\n\t\tif r.buffer.IsEmpty() {\n\t\t\tr.buffer.Clear()\n\t\t} else {\n\t\t\tcommon.Must(r.buffer.Reset(buf.ReadFrom(r.buffer)))\n\t\t}\n\n\t\tdelta := sizeBytes - r.buffer.Len()\n\t\tif err := r.buffer.AppendSupplier(buf.ReadAtLeastFrom(r.reader, delta)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tsize, err := r.sizeParser.Decode(r.buffer.BytesTo(sizeBytes))\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.size = int(size)\n\tr.buffer.SliceFrom(sizeBytes)\n\treturn nil\n}\n\nfunc (r *AuthenticationReader) readChunk(waitForData bool) ([]byte, error) {\n\tif err := r.readSize(); err != nil {\n\t\treturn nil, err\n\t}\n\tif r.size > readerBufferSize-r.sizeParser.SizeBytes() {\n\t\treturn nil, newError(\"size too large \", r.size).AtWarning()\n\t}\n\n\tif r.size == r.auth.Overhead() {\n\t\treturn nil, io.EOF\n\t}\n\n\tif r.buffer.Len() < r.size {\n\t\tif !waitForData {\n\t\t\treturn nil, io.ErrNoProgress\n\t\t}\n\n\t\tif r.buffer.IsEmpty() {\n\t\t\tr.buffer.Clear()\n\t\t} else {\n\t\t\tcommon.Must(r.buffer.Reset(buf.ReadFrom(r.buffer)))\n\t\t}\n\n\t\tdelta := r.size - r.buffer.Len()\n\t\tif err := r.buffer.AppendSupplier(buf.ReadAtLeastFrom(r.reader, delta)); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tb, err := r.auth.Open(r.buffer.BytesTo(0), r.buffer.BytesTo(r.size))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr.buffer.SliceFrom(r.size)\n\tr.size = -1\n\treturn b, nil\n}\n\nfunc (r *AuthenticationReader) ReadMultiBuffer() (buf.MultiBuffer, error) {\n\tb, err := r.readChunk(true)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar mb buf.MultiBuffer\n\tif r.transferType == protocol.TransferTypeStream {\n\t\tmb.Write(b)\n\t} else {\n\t\tvar bb *buf.Buffer\n\t\tif len(b) <= buf.Size {\n\t\t\tbb = buf.New()\n\t\t} else {\n\t\t\tbb = buf.NewLocal(len(b))\n\t\t}\n\t\tbb.Append(b)\n\t\tmb.Append(bb)\n\t}\n\n\tfor r.buffer.Len() >= r.sizeParser.SizeBytes() {\n\t\tb, err := r.readChunk(false)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif r.transferType == protocol.TransferTypeStream {\n\t\t\tmb.Write(b)\n\t\t} else {\n\t\t\tvar bb *buf.Buffer\n\t\t\tif len(b) <= buf.Size {\n\t\t\t\tbb = buf.New()\n\t\t\t} else {\n\t\t\t\tbb = buf.NewLocal(len(b))\n\t\t\t}\n\t\t\tbb.Append(b)\n\t\t\tmb.Append(bb)\n\t\t}\n\t}\n\n\treturn mb, nil\n}\n\nconst (\n\tWriteSize = 1024\n)\n\ntype AuthenticationWriter struct {\n\tauth         Authenticator\n\twriter       buf.Writer\n\tsizeParser   ChunkSizeEncoder\n\ttransferType protocol.TransferType\n}\n\nfunc NewAuthenticationWriter(auth Authenticator, sizeParser ChunkSizeEncoder, writer io.Writer, transferType protocol.TransferType) *AuthenticationWriter {\n\treturn &AuthenticationWriter{\n\t\tauth:         auth,\n\t\twriter:       buf.NewWriter(writer),\n\t\tsizeParser:   sizeParser,\n\t\ttransferType: transferType,\n\t}\n}\n\nfunc (w *AuthenticationWriter) seal(b *buf.Buffer) (*buf.Buffer, error) {\n\tencryptedSize := b.Len() + w.auth.Overhead()\n\n\teb := buf.New()\n\tcommon.Must(eb.Reset(func(bb []byte) (int, error) {\n\t\tw.sizeParser.Encode(uint16(encryptedSize), bb[:0])\n\t\treturn w.sizeParser.SizeBytes(), nil\n\t}))\n\tif err := eb.AppendSupplier(func(bb []byte) (int, error) {\n\t\t_, err := w.auth.Seal(bb[:0], b.Bytes())\n\t\treturn encryptedSize, err\n\t}); err != nil {\n\t\teb.Release()\n\t\treturn nil, err\n\t}\n\n\treturn eb, nil\n}\n\nfunc (w *AuthenticationWriter) writeStream(mb buf.MultiBuffer) error {\n\tdefer mb.Release()\n\n\tmb2Write := buf.NewMultiBufferCap(len(mb) + 10)\n\n\tfor {\n\t\tb := buf.New()\n\t\tcommon.Must(b.Reset(func(bb []byte) (int, error) {\n\t\t\treturn mb.Read(bb[:WriteSize])\n\t\t}))\n\t\teb, err := w.seal(b)\n\t\tb.Release()\n\n\t\tif err != nil {\n\t\t\tmb2Write.Release()\n\t\t\treturn err\n\t\t}\n\t\tmb2Write.Append(eb)\n\t\tif mb.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn w.writer.WriteMultiBuffer(mb2Write)\n}\n\nfunc (w *AuthenticationWriter) writePacket(mb buf.MultiBuffer) error {\n\tdefer mb.Release()\n\n\tmb2Write := buf.NewMultiBufferCap(len(mb) * 2)\n\n\tfor {\n\t\tb := mb.SplitFirst()\n\t\tif b == nil {\n\t\t\tb = buf.New()\n\t\t}\n\t\teb, err := w.seal(b)\n\t\tb.Release()\n\t\tif err != nil {\n\t\t\tmb2Write.Release()\n\t\t\treturn err\n\t\t}\n\t\tmb2Write.Append(eb)\n\t\tif mb.IsEmpty() {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn w.writer.WriteMultiBuffer(mb2Write)\n}\n\nfunc (w *AuthenticationWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {\n\tif w.transferType == protocol.TransferTypeStream {\n\t\treturn w.writeStream(mb)\n\t}\n\n\treturn w.writePacket(mb)\n}\n<|endoftext|>"}
{"text":"<commit_before>package gonavitia\n\nimport (\n\t\"fmt\"\n\t\"github.com\/aabizri\/gonavitia\/types\"\n\t\"net\/url\"\n)\n\n\/\/ PlacesResults doesn't have pagination\ntype PlacesResults struct {\n\tPlaces []types.Place\n\n\tLogging\n\tsession *Session\n}\n\nfunc (res PlacesResults) String() string {\n\tvar msg string\n\tfor i, place := range res.Places {\n\t\tmsg += fmt.Sprintf(\"Place #%d (%s): %v\\n\", i, place.PlaceType(), place) \/\/TODO: When types implements a String() method on its Place type, use it\n\t}\n\treturn msg\n}\n\ntype PlacesRequest struct {\n\tQuery string \/\/ The search item\n\n\t\/\/ Types are the type of objects to query\n\t\/\/ It can either be a stop_area, an address, a poi or an administrative_region\n\tTypes []string\n\n\tAdminURI []string \/\/ If given it will filter the search by specific admin uris\n\n\tDisableGeoJson bool\n\n\tAround types.Coordinates \/\/ If given, it will prioritize objects around these coordinates\n}\n\n\/\/ toURL formats a Places request to url\nfunc (req PlacesRequest) toURL() (url.Values, error) {\n\tparams := url.Values{\n\t\t\"q\": []string{req.Query},\n\t}\n\n\tif len(req.Types) != 0 {\n\t\tparams[\"type[]\"] = req.Types\n\t}\n\n\tif len(req.AdminURI) != 0 {\n\t\tparams[\"admin_uri[]\"] = req.AdminURI\n\t}\n\n\tif req.DisableGeoJson {\n\t\tparams[\"disable_geojson\"] = []string{\"true\"}\n\t}\n\n\treturn params, nil\n}\n\n\/\/ places is the internal function used by Places functions\nfunc (s *Session) places(url string, params PlacesRequest) (*PlacesResults, error) {\n\tvar results = &PlacesResults{session: s}\n\terr := s.request(url, params, results)\n\treturn results, err\n}\n\nconst placesEndpoint = \"places\"\n\n\/\/ Places search in all geographical objects using their names, returning a list of corresponding places.\nfunc (s *Session) Places(params PlacesRequest) (*PlacesResults, error) {\n\t\/\/ Create the URL\n\turl := s.APIURL + \"\/\" + placesEndpoint\n\n\t\/\/ Call\n\treturn s.places(url, params)\n}\n\n\/\/ Places search in all geographical objects within a given region using their names, returning a list of places.\nfunc (s *Session) PlacesR(params PlacesRequest, regionID string) (*PlacesResults, error) {\n\t\/\/ Create the URL\n\turl := s.APIURL + \"\/coverage\/\" + regionID + \"\/\" + placesEndpoint\n\n\t\/\/ Call\n\treturn s.places(url, params)\n}\n<commit_msg>Add Count to PlacesRequest<commit_after>package gonavitia\n\nimport (\n\t\"fmt\"\n\t\"github.com\/aabizri\/gonavitia\/types\"\n\t\"net\/url\"\n\t\"strconv\"\n)\n\n\/\/ PlacesResults doesn't have pagination\ntype PlacesResults struct {\n\tPlaces []types.Place\n\n\tLogging\n\tsession *Session\n}\n\nfunc (res PlacesResults) String() string {\n\tvar msg string\n\tfor i, place := range res.Places {\n\t\tmsg += fmt.Sprintf(\"Place #%d (%s): %s\\n\", i, place.PlaceType(), place.String())\n\t}\n\treturn msg\n}\n\ntype PlacesRequest struct {\n\tQuery string \/\/ The search item\n\n\t\/\/ Types are the type of objects to query\n\t\/\/ It can either be a stop_area, an address, a poi or an administrative_region\n\tTypes []string\n\n\tAdminURI []string \/\/ If given it will filter the search by specific admin uris\n\n\tDisableGeoJson bool\n\n\tAround types.Coordinates \/\/ If given, it will prioritize objects around these coordinates\n\n\t\/\/ Maximum amount of results\n\tCount uint\n}\n\n\/\/ toURL formats a Places request to url\nfunc (req PlacesRequest) toURL() (url.Values, error) {\n\tparams := url.Values{\n\t\t\"q\": []string{req.Query},\n\t}\n\n\tif len(req.Types) != 0 {\n\t\tparams[\"type[]\"] = req.Types\n\t}\n\n\tif len(req.AdminURI) != 0 {\n\t\tparams[\"admin_uri[]\"] = req.AdminURI\n\t}\n\n\tif req.DisableGeoJson {\n\t\tparams[\"disable_geojson\"] = []string{\"true\"}\n\t}\n\n\tif req.Count != 0 {\n\t\tcountStr := strconv.FormatUint(uint64(req.Count), 10)\n\t\tparams[\"count\"] = []string{countStr}\n\t}\n\treturn params, nil\n}\n\n\/\/ places is the internal function used by Places functions\nfunc (s *Session) places(url string, params PlacesRequest) (*PlacesResults, error) {\n\tvar results = &PlacesResults{session: s}\n\terr := s.request(url, params, results)\n\treturn results, err\n}\n\nconst placesEndpoint = \"places\"\n\n\/\/ Places search in all geographical objects using their names, returning a list of corresponding places.\nfunc (s *Session) Places(params PlacesRequest) (*PlacesResults, error) {\n\t\/\/ Create the URL\n\turl := s.APIURL + \"\/\" + placesEndpoint\n\n\t\/\/ Call\n\treturn s.places(url, params)\n}\n\n\/\/ Places search in all geographical objects within a given region using their names, returning a list of places.\nfunc (s *Session) PlacesR(params PlacesRequest, regionID string) (*PlacesResults, error) {\n\t\/\/ Create the URL\n\turl := s.APIURL + \"\/coverage\/\" + regionID + \"\/\" + placesEndpoint\n\n\t\/\/ Call\n\treturn s.places(url, params)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Jesper Brodersen. All rights reserved.\n\/\/ This code is BSD-licensed, see LICENSE file.\n\n\/\/ pm-get is a package manger written in Go Language\n\/\/ this is the user application for running daily tasks on packages,\n\/\/ like browsing, installing, uninstalling and updating\npackage main\n\nimport (\n\t\"github.com\/broeman\/gopack\/cmd\" \/\/ using CLI command args\n\t\"github.com\/codegangsta\/cli\"\n\t\"os\"\n\t\"runtime\"\n)\n\nconst APP_VER = \"0.1 Alpha\"\n\nfunc init() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n}\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"pm-get\"\n\tapp.Usage = \"Package Manager in Go\"\n\tapp.Version = APP_VER\n\tapp.Commands = []cli.Command{\n\t\tcmd.Install,   \/\/ install a package\n\t\tcmd.UnInstall, \/\/ uninstall a package\n\t\tcmd.Show,      \/\/ show package\n\t\tcmd.Installed, \/\/ shows current installed packages, placeholder\n\t\t\/\/cmd.Update,\t\/\/ update packages\n\t\tcmd.Init, \/\/ placeholder initialization\n\t}\n\tapp.Run(os.Args)\n\n}\n<commit_msg>linked to local cmd, as library doesn't provide any longer<commit_after>\/\/ Copyright 2014 Jesper Brodersen. All rights reserved.\n\/\/ This code is BSD-licensed, see LICENSE file.\n\n\/\/ pm-get is a package manger written in Go Language\n\/\/ this is the user application for running daily tasks on packages,\n\/\/ like browsing, installing, uninstalling and updating\npackage main\n\nimport (\n\t\"github.com\/broeman\/pm-get\/cmd\" \/\/ using CLI command args\n\t\"github.com\/codegangsta\/cli\"\n\t\"os\"\n\t\"runtime\"\n)\n\nconst APP_VER = \"0.1 Alpha\"\n\nfunc init() {\n\truntime.GOMAXPROCS(runtime.NumCPU())\n}\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"pm-get\"\n\tapp.Usage = \"Package Manager in Go\"\n\tapp.Version = APP_VER\n\tapp.Commands = []cli.Command{\n\t\tcmd.Install,   \/\/ install a package\n\t\tcmd.UnInstall, \/\/ uninstall a package\n\t\tcmd.Show,      \/\/ show package\n\t\tcmd.Installed, \/\/ shows current installed packages, placeholder\n\t\t\/\/cmd.Update,\t\/\/ update packages\n\t\tcmd.Init, \/\/ placeholder initialization\n\t}\n\tapp.Run(os.Args)\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/ Author: jacobsa@google.com (Aaron Jacobs)\n\npackage syncutil\n\nimport (\n\t\"flag\"\n\t\"sync\"\n)\n\nvar fCheckInvariants = flag.Bool(\"syncutil.check_invariants\", false, \"Crash when registered invariants are violated.\")\n\n\/\/ A reader\/writer mutex like sync.RWMutex that additionally runs a check for\n\/\/ registered invariants at times when invariants should hold, when enabled.\n\/\/ This can aid debugging subtle code by crashing early as soon as something\n\/\/ unexpected happens.\n\/\/\n\/\/ Must be created with NewInvariantMutex. See that function for more details.\n\/\/\n\/\/ A typical use looks like this:\n\/\/\n\/\/     type myStruct struct {\n\/\/       mu InvariantMutex\n\/\/\n\/\/       \/\/ INVARIANT: nextGeneration == currentGeneration + 1\n\/\/       currentGeneration int  \/\/ GUARDED_BY(mu)\n\/\/       nextGeneration    int  \/\/ GUARDED_BY(mu)\n\/\/     }\n\/\/\n\/\/     \/\/ The constructor function for myStruct sets up the mutex to\n\/\/     \/\/ call the checkInvariants method.\n\/\/     func newMyStruct() *myStruct {\n\/\/       s := &myStruct{\n\/\/         currentGeneration: 1,\n\/\/         nextGeneration:    2,\n\/\/       }\n\/\/\n\/\/       s.mu = NewInvariantMutex(func() { s.checkInvariants() })\n\/\/       return s\n\/\/     }\n\/\/\n\/\/     type (s *myStruct) checkInvariants() {\n\/\/       if s.nextGeneration != s.currentGeneration + 1 {\n\/\/         panic(\n\/\/           fmt.Sprintf(\"%v != %v + 1\", s.nextGeneration, s.currentGeneration))\n\/\/       }\n\/\/     }\n\/\/\n\/\/     \/\/ When the flag is set, invariants will be checked at entry to and exit\n\/\/     \/\/ from this function.\n\/\/     func (s *myStruct) setGeneration(n int) {\n\/\/       s.mu.Lock()\n\/\/       defer s.mu.Unlock()\n\/\/\n\/\/       currentGeneration = n\n\/\/       nextGeneration = n + 1\n\/\/     }\n\/\/\ntype InvariantMutex struct {\n\tmu    sync.RWMutex\n\tcheck func()\n}\n\nfunc (i *InvariantMutex) Lock() {\n\ti.mu.Lock()\n\ti.checkIfEnabled()\n}\n\nfunc (i *InvariantMutex) Unlock() {\n\ti.checkIfEnabled()\n\ti.mu.Unlock()\n}\n\nfunc (i *InvariantMutex) RLock() {\n\ti.mu.RLock()\n\ti.checkIfEnabled()\n}\n\nfunc (i *InvariantMutex) RUnlock() {\n\ti.checkIfEnabled()\n\ti.mu.RUnlock()\n}\n\nfunc (i *InvariantMutex) checkIfEnabled() {\n\tif *fCheckInvariants {\n\t\ti.check()\n\t}\n}\n\n\/\/ Create a reader\/writer mutex which, when the flag -syncutil.check_invariants\n\/\/ is set, will call the supplied function at moments when invariants protected\n\/\/ by the mutex should hold (e.g. just after acquiring the lock). The function\n\/\/ should crash if an invariant is violated. It should not have side effects,\n\/\/ as there are no guarantees that it will run.\nfunc NewInvariantMutex(check func()) InvariantMutex {\n\tif check == nil {\n\t\tpanic(\"check must be non-nil.\")\n\t}\n\n\treturn InvariantMutex{\n\t\tcheck: check,\n\t}\n}\n<commit_msg>Fixed errors in the example.<commit_after>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/ Author: jacobsa@google.com (Aaron Jacobs)\n\npackage syncutil\n\nimport (\n\t\"flag\"\n\t\"sync\"\n)\n\nvar fCheckInvariants = flag.Bool(\"syncutil.check_invariants\", false, \"Crash when registered invariants are violated.\")\n\n\/\/ A reader\/writer mutex like sync.RWMutex that additionally runs a check for\n\/\/ registered invariants at times when invariants should hold, when enabled.\n\/\/ This can aid debugging subtle code by crashing early as soon as something\n\/\/ unexpected happens.\n\/\/\n\/\/ Must be created with NewInvariantMutex. See that function for more details.\n\/\/\n\/\/ A typical use looks like this:\n\/\/\n\/\/     type myStruct struct {\n\/\/       mu syncutil.InvariantMutex\n\/\/\n\/\/       \/\/ INVARIANT: nextGeneration == currentGeneration + 1\n\/\/       currentGeneration int \/\/ GUARDED_BY(mu)\n\/\/       nextGeneration    int \/\/ GUARDED_BY(mu)\n\/\/     }\n\/\/\n\/\/     \/\/ The constructor function for myStruct sets up the mutex to\n\/\/     \/\/ call the checkInvariants method.\n\/\/     func newMyStruct() *myStruct {\n\/\/       s := &myStruct{\n\/\/         currentGeneration: 1,\n\/\/         nextGeneration:    2,\n\/\/       }\n\/\/\n\/\/       s.mu = syncutil.NewInvariantMutex(func() { s.checkInvariants() })\n\/\/       return s\n\/\/     }\n\/\/\n\/\/     func (s *myStruct) checkInvariants() {\n\/\/       if s.nextGeneration != s.currentGeneration+1 {\n\/\/         panic(\n\/\/           fmt.Sprintf(\"%v != %v + 1\", s.nextGeneration, s.currentGeneration))\n\/\/       }\n\/\/     }\n\/\/\n\/\/     \/\/ When the flag is set, invariants will be checked at entry to and exit\n\/\/     \/\/ from this function.\n\/\/     func (s *myStruct) setGeneration(n int) {\n\/\/       s.mu.Lock()\n\/\/       defer s.mu.Unlock()\n\/\/\n\/\/       s.currentGeneration = n\n\/\/       s.nextGeneration = n + 1\n\/\/     }\n\/\/\ntype InvariantMutex struct {\n\tmu    sync.RWMutex\n\tcheck func()\n}\n\nfunc (i *InvariantMutex) Lock() {\n\ti.mu.Lock()\n\ti.checkIfEnabled()\n}\n\nfunc (i *InvariantMutex) Unlock() {\n\ti.checkIfEnabled()\n\ti.mu.Unlock()\n}\n\nfunc (i *InvariantMutex) RLock() {\n\ti.mu.RLock()\n\ti.checkIfEnabled()\n}\n\nfunc (i *InvariantMutex) RUnlock() {\n\ti.checkIfEnabled()\n\ti.mu.RUnlock()\n}\n\nfunc (i *InvariantMutex) checkIfEnabled() {\n\tif *fCheckInvariants {\n\t\ti.check()\n\t}\n}\n\n\/\/ Create a reader\/writer mutex which, when the flag -syncutil.check_invariants\n\/\/ is set, will call the supplied function at moments when invariants protected\n\/\/ by the mutex should hold (e.g. just after acquiring the lock). The function\n\/\/ should crash if an invariant is violated. It should not have side effects,\n\/\/ as there are no guarantees that it will run.\nfunc NewInvariantMutex(check func()) InvariantMutex {\n\tif check == nil {\n\t\tpanic(\"check must be non-nil.\")\n\t}\n\n\treturn InvariantMutex{\n\t\tcheck: check,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package s3gof3r\n\nimport (\n\t\"bytes\"\n\t\"crypto\/md5\"\n\t\"encoding\/base64\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"hash\"\n\t\"io\"\n\t\"math\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\/\/ defined by amazon\nconst (\n\tminPartSize = 5 * mb\n\tmaxPartSize = 5 * gb\n\tmaxObjSize  = 5 * tb\n\tmaxNPart    = 10000\n\tmd5Header   = \"content-md5\"\n)\n\ntype part struct {\n\tr   io.ReadSeeker\n\tlen int64\n\tb   []byte\n\n\t\/\/ read by xml encoder\n\tPartNumber int\n\tETag       string\n\n\t\/\/ Used for checksum of checksums on completion\n\tcontentMd5 string\n}\n\ntype putter struct {\n\turl url.URL\n\tb   *Bucket\n\tc   *Config\n\n\tbufsz      int64\n\tbuf        []byte\n\tbufbytes   int \/\/ bytes written to current buffer\n\tch         chan *part\n\tpart       int\n\tclosed     bool\n\terr        error\n\twg         sync.WaitGroup\n\tmd5OfParts hash.Hash\n\tmd5        hash.Hash\n\tETag       string\n\n\tsp *bp\n\n\tmakes    int\n\tUploadId string \/\/ casing matches s3 xml\n\txml      struct {\n\t\tXMLName string `xml:\"CompleteMultipartUpload\"`\n\t\tPart    []*part\n\t}\n\tputsz int64\n}\n\n\/\/ Sends an S3 multipart upload initiation request.\n\/\/ See http:\/\/docs.amazonwebservices.com\/AmazonS3\/latest\/dev\/mpuoverview.html.\n\/\/ The initial request returns an UploadId that we use to identify\n\/\/ subsequent PUT requests.\nfunc newPutter(url url.URL, h http.Header, c *Config, b *Bucket) (p *putter, err error) {\n\tp = new(putter)\n\tp.url = url\n\tp.b = b\n\tp.c = c\n\tp.c.Concurrency = max(c.Concurrency, 1)\n\tp.c.NTry = max(c.NTry, 1)\n\tp.bufsz = max64(minPartSize, c.PartSize)\n\tresp, err := p.retryRequest(\"POST\", url.String()+\"?uploads\", nil, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer checkClose(resp.Body, &err)\n\tif resp.StatusCode != 200 {\n\t\treturn nil, newRespError(resp)\n\t}\n\terr = xml.NewDecoder(resp.Body).Decode(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.ch = make(chan *part)\n\tfor i := 0; i < p.c.Concurrency; i++ {\n\t\tgo p.worker()\n\t}\n\tp.md5OfParts = md5.New()\n\tp.md5 = md5.New()\n\n\tp.sp = bufferPool(p.bufsz)\n\n\treturn p, nil\n}\n\nfunc (p *putter) Write(b []byte) (int, error) {\n\tif p.closed {\n\t\tp.abort()\n\t\treturn 0, syscall.EINVAL\n\t}\n\tif p.err != nil {\n\t\tp.abort()\n\t\treturn 0, p.err\n\t}\n\tnw := 0\n\tfor nw < len(b) {\n\t\tif p.buf == nil {\n\t\t\tp.buf = <-p.sp.get\n\t\t\tif int64(cap(p.buf)) < p.bufsz {\n\t\t\t\tp.buf = make([]byte, p.bufsz)\n\t\t\t\truntime.GC()\n\t\t\t}\n\t\t}\n\t\tn := copy(p.buf[p.bufbytes:], b[nw:])\n\t\tp.bufbytes += n\n\t\tnw += n\n\n\t\tif len(p.buf) == p.bufbytes {\n\t\t\tp.flush()\n\t\t}\n\t}\n\treturn nw, nil\n}\n\nfunc (p *putter) flush() {\n\tp.wg.Add(1)\n\tp.part++\n\tp.putsz += int64(p.bufbytes)\n\tpart := &part{bytes.NewReader(p.buf[:p.bufbytes]), int64(p.bufbytes), p.buf, p.part, \"\", \"\"}\n\tvar err error\n\tpart.contentMd5, part.ETag, err = p.md5Content(part.r)\n\tif err != nil {\n\t\tp.err = err\n\t}\n\n\tp.xml.Part = append(p.xml.Part, part)\n\tp.ch <- part\n\tp.buf, p.bufbytes = nil, 0\n\n\t\/\/ if necessary, double buffer size every 2000 parts due to the 10000-part AWS limit\n\t\/\/ to reach the 5 Terabyte max object size, initial part size must be ~85 MB\n\tif p.part%2000 == 0 && p.part < maxNPart && growPartSize(p.part, p.bufsz, p.putsz) {\n\t\tp.bufsz = min64(p.bufsz*2, maxPartSize)\n\t\tp.sp.sizech <- p.bufsz \/\/ update pool buffer size\n\t\tlogger.debugPrintf(\"part size doubled to %d\", p.bufsz)\n\t}\n}\n\nfunc (p *putter) worker() {\n\tfor part := range p.ch {\n\t\tp.retryPutPart(part)\n\t}\n}\n\n\/\/ Calls putPart up to nTry times to recover from transient errors.\nfunc (p *putter) retryPutPart(part *part) {\n\tdefer p.wg.Done()\n\tvar err error\n\tfor i := 0; i < p.c.NTry; i++ {\n\t\ttime.Sleep(time.Duration(math.Exp2(float64(i))) * 100 * time.Millisecond) \/\/ exponential back-off\n\t\terr = p.putPart(part)\n\t\tif err == nil {\n\t\t\tp.sp.give <- part.b\n\t\t\tpart.b = nil\n\t\t\treturn\n\t\t}\n\t\tlogger.debugPrintf(\"Error on attempt %d: Retrying part: %d, Error: %s\", i, part.PartNumber, err)\n\t}\n\tp.err = err\n}\n\n\/\/ uploads a part, checking the etag against the calculated value\nfunc (p *putter) putPart(part *part) error {\n\tv := url.Values{}\n\tv.Set(\"partNumber\", strconv.Itoa(part.PartNumber))\n\tv.Set(\"uploadId\", p.UploadId)\n\tif _, err := part.r.Seek(0, 0); err != nil { \/\/ move back to beginning, if retrying\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"PUT\", p.url.String()+\"?\"+v.Encode(), part.r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.ContentLength = part.len\n\treq.Header.Set(md5Header, part.contentMd5)\n\tp.b.Sign(req)\n\tresp, err := p.c.Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer checkClose(resp.Body, &err)\n\tif resp.StatusCode != 200 {\n\t\treturn newRespError(resp)\n\t}\n\ts := resp.Header.Get(\"etag\")\n\ts = s[1 : len(s)-1] \/\/ includes quote chars for some reason\n\tif part.ETag != s {\n\t\treturn fmt.Errorf(\"Response etag does not match. Remote:%s Calculated:%s\", s, p.ETag)\n\t}\n\treturn nil\n}\n\nfunc (p *putter) Close() (err error) {\n\tif p.closed {\n\t\tp.abort()\n\t\treturn syscall.EINVAL\n\t}\n\tif p.err != nil {\n\t\tp.abort()\n\t\treturn p.err\n\t}\n\tif p.bufbytes > 0 || \/\/ partial part\n\t\tp.part == 0 { \/\/ 0 length file\n\t\tp.flush()\n\t}\n\tp.wg.Wait()\n\tclose(p.ch)\n\tp.closed = true\n\tclose(p.sp.quit)\n\n\t\/\/ check p.err before completing\n\tif p.err != nil {\n\t\tp.abort()\n\t\treturn p.err\n\t}\n\t\/\/ Complete Multipart upload\n\tbody, err := xml.Marshal(p.xml)\n\tif err != nil {\n\t\tp.abort()\n\t\treturn\n\t}\n\tb := bytes.NewReader(body)\n\tv := url.Values{}\n\tv.Set(\"uploadId\", p.UploadId)\n\tresp, err := p.retryRequest(\"POST\", p.url.String()+\"?\"+v.Encode(), b, nil)\n\tif err != nil {\n\t\tp.abort()\n\t\treturn\n\t}\n\tdefer checkClose(resp.Body, &err)\n\tif resp.StatusCode != 200 {\n\t\tp.abort()\n\t\treturn newRespError(resp)\n\t}\n\t\/\/ Check md5 hash of concatenated part md5 hashes against ETag\n\t\/\/ more info: https:\/\/forums.aws.amazon.com\/thread.jspa?messageID=456442&#456442\n\tcalculatedMd5ofParts := fmt.Sprintf(\"%x\", p.md5OfParts.Sum(nil))\n\t\/\/ Parse etag from body of response\n\terr = xml.NewDecoder(resp.Body).Decode(p)\n\tif err != nil {\n\t\treturn\n\t}\n\t\/\/ strip part count from end and '\"' from front.\n\tremoteMd5ofParts := strings.Split(p.ETag, \"-\")[0]\n\tremoteMd5ofParts = remoteMd5ofParts[1:len(remoteMd5ofParts)]\n\tif calculatedMd5ofParts != remoteMd5ofParts {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn fmt.Errorf(\"MD5 hash of part hashes comparison failed. Hash from multipart complete header: %s.\"+\n\t\t\t\" Calculated multipart hash: %s.\", remoteMd5ofParts, calculatedMd5ofParts)\n\t}\n\tif p.c.Md5Check {\n\t\tfor i := 0; i < p.c.NTry; i++ {\n\t\t\tif err = p.putMd5(); err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ Try to abort multipart upload. Do not error on failure.\nfunc (p *putter) abort() {\n\tv := url.Values{}\n\tv.Set(\"uploadId\", p.UploadId)\n\ts := p.url.String() + \"?\" + v.Encode()\n\tresp, err := p.retryRequest(\"DELETE\", s, nil, nil)\n\tif err != nil {\n\t\tlogger.Printf(\"Error aborting multipart upload: %v\\n\", err)\n\t\treturn\n\t}\n\tdefer checkClose(resp.Body, &err)\n\tif resp.StatusCode != 204 {\n\t\tlogger.Printf(\"Error aborting multipart upload: %v\", newRespError(resp))\n\t}\n\treturn\n}\n\n\/\/ Md5 functions\nfunc (p *putter) md5Content(r io.ReadSeeker) (string, string, error) {\n\th := md5.New()\n\tmw := io.MultiWriter(h, p.md5)\n\tif _, err := io.Copy(mw, r); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tsum := h.Sum(nil)\n\thexSum := fmt.Sprintf(\"%x\", sum)\n\t\/\/ add to checksum of all parts for verification on upload completion\n\tif _, err := p.md5OfParts.Write(sum); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\treturn base64.StdEncoding.EncodeToString(sum), hexSum, nil\n}\n\n\/\/ Put md5 file in .md5 subdirectory of bucket  where the file is stored\n\/\/ e.g. the md5 for https:\/\/mybucket.s3.amazonaws.com\/gof3r will be stored in\n\/\/ https:\/\/mybucket.s3.amazonaws.com\/.md5\/gof3r.md5\nfunc (p *putter) putMd5() (err error) {\n\tcalcMd5 := fmt.Sprintf(\"%x\", p.md5.Sum(nil))\n\tmd5Reader := strings.NewReader(calcMd5)\n\tmd5Path := fmt.Sprint(\".md5\", p.url.Path, \".md5\")\n\tmd5Url, err := p.b.url(md5Path, p.c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.debugPrintln(\"md5: \", calcMd5)\n\tlogger.debugPrintln(\"md5Path: \", md5Path)\n\tr, err := http.NewRequest(\"PUT\", md5Url.String(), md5Reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tp.b.Sign(r)\n\tresp, err := p.c.Client.Do(r)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer checkClose(resp.Body, &err)\n\tif resp.StatusCode != 200 {\n\t\treturn newRespError(resp)\n\t}\n\treturn\n}\n\nfunc (p *putter) retryRequest(method, urlStr string, body io.ReadSeeker, h http.Header) (resp *http.Response, err error) {\n\tfor i := 0; i < p.c.NTry; i++ {\n\t\tvar req *http.Request\n\t\treq, err = http.NewRequest(method, urlStr, body)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tfor k := range h {\n\t\t\tfor _, v := range h[k] {\n\t\t\t\treq.Header.Add(k, v)\n\t\t\t}\n\t\t}\n\n\t\tp.b.Sign(req)\n\t\tresp, err = p.c.Client.Do(req)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t\tlogger.debugPrintln(err)\n\t\tif body != nil {\n\t\t\tif _, err = body.Seek(0, 0); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ returns true unless partSize is large enough\n\/\/ to achieve maxObjSize with remaining parts\nfunc growPartSize(partIndex int, partSize, putsz int64) bool {\n\treturn (maxObjSize-putsz)\/(maxNPart-int64(partIndex)) > partSize\n}\n<commit_msg>Handle cases where etag is missing gracefully.<commit_after>package s3gof3r\n\nimport (\n\t\"bytes\"\n\t\"crypto\/md5\"\n\t\"encoding\/base64\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"hash\"\n\t\"io\"\n\t\"math\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\n\/\/ defined by amazon\nconst (\n\tminPartSize = 5 * mb\n\tmaxPartSize = 5 * gb\n\tmaxObjSize  = 5 * tb\n\tmaxNPart    = 10000\n\tmd5Header   = \"content-md5\"\n)\n\ntype part struct {\n\tr   io.ReadSeeker\n\tlen int64\n\tb   []byte\n\n\t\/\/ read by xml encoder\n\tPartNumber int\n\tETag       string\n\n\t\/\/ Used for checksum of checksums on completion\n\tcontentMd5 string\n}\n\ntype putter struct {\n\turl url.URL\n\tb   *Bucket\n\tc   *Config\n\n\tbufsz      int64\n\tbuf        []byte\n\tbufbytes   int \/\/ bytes written to current buffer\n\tch         chan *part\n\tpart       int\n\tclosed     bool\n\terr        error\n\twg         sync.WaitGroup\n\tmd5OfParts hash.Hash\n\tmd5        hash.Hash\n\tETag       string\n\n\tsp *bp\n\n\tmakes    int\n\tUploadId string \/\/ casing matches s3 xml\n\txml      struct {\n\t\tXMLName string `xml:\"CompleteMultipartUpload\"`\n\t\tPart    []*part\n\t}\n\tputsz int64\n}\n\n\/\/ Sends an S3 multipart upload initiation request.\n\/\/ See http:\/\/docs.amazonwebservices.com\/AmazonS3\/latest\/dev\/mpuoverview.html.\n\/\/ The initial request returns an UploadId that we use to identify\n\/\/ subsequent PUT requests.\nfunc newPutter(url url.URL, h http.Header, c *Config, b *Bucket) (p *putter, err error) {\n\tp = new(putter)\n\tp.url = url\n\tp.b = b\n\tp.c = c\n\tp.c.Concurrency = max(c.Concurrency, 1)\n\tp.c.NTry = max(c.NTry, 1)\n\tp.bufsz = max64(minPartSize, c.PartSize)\n\tresp, err := p.retryRequest(\"POST\", url.String()+\"?uploads\", nil, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer checkClose(resp.Body, &err)\n\tif resp.StatusCode != 200 {\n\t\treturn nil, newRespError(resp)\n\t}\n\terr = xml.NewDecoder(resp.Body).Decode(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp.ch = make(chan *part)\n\tfor i := 0; i < p.c.Concurrency; i++ {\n\t\tgo p.worker()\n\t}\n\tp.md5OfParts = md5.New()\n\tp.md5 = md5.New()\n\n\tp.sp = bufferPool(p.bufsz)\n\n\treturn p, nil\n}\n\nfunc (p *putter) Write(b []byte) (int, error) {\n\tif p.closed {\n\t\tp.abort()\n\t\treturn 0, syscall.EINVAL\n\t}\n\tif p.err != nil {\n\t\tp.abort()\n\t\treturn 0, p.err\n\t}\n\tnw := 0\n\tfor nw < len(b) {\n\t\tif p.buf == nil {\n\t\t\tp.buf = <-p.sp.get\n\t\t\tif int64(cap(p.buf)) < p.bufsz {\n\t\t\t\tp.buf = make([]byte, p.bufsz)\n\t\t\t\truntime.GC()\n\t\t\t}\n\t\t}\n\t\tn := copy(p.buf[p.bufbytes:], b[nw:])\n\t\tp.bufbytes += n\n\t\tnw += n\n\n\t\tif len(p.buf) == p.bufbytes {\n\t\t\tp.flush()\n\t\t}\n\t}\n\treturn nw, nil\n}\n\nfunc (p *putter) flush() {\n\tp.wg.Add(1)\n\tp.part++\n\tp.putsz += int64(p.bufbytes)\n\tpart := &part{bytes.NewReader(p.buf[:p.bufbytes]), int64(p.bufbytes), p.buf, p.part, \"\", \"\"}\n\tvar err error\n\tpart.contentMd5, part.ETag, err = p.md5Content(part.r)\n\tif err != nil {\n\t\tp.err = err\n\t}\n\n\tp.xml.Part = append(p.xml.Part, part)\n\tp.ch <- part\n\tp.buf, p.bufbytes = nil, 0\n\n\t\/\/ if necessary, double buffer size every 2000 parts due to the 10000-part AWS limit\n\t\/\/ to reach the 5 Terabyte max object size, initial part size must be ~85 MB\n\tif p.part%2000 == 0 && p.part < maxNPart && growPartSize(p.part, p.bufsz, p.putsz) {\n\t\tp.bufsz = min64(p.bufsz*2, maxPartSize)\n\t\tp.sp.sizech <- p.bufsz \/\/ update pool buffer size\n\t\tlogger.debugPrintf(\"part size doubled to %d\", p.bufsz)\n\t}\n}\n\nfunc (p *putter) worker() {\n\tfor part := range p.ch {\n\t\tp.retryPutPart(part)\n\t}\n}\n\n\/\/ Calls putPart up to nTry times to recover from transient errors.\nfunc (p *putter) retryPutPart(part *part) {\n\tdefer p.wg.Done()\n\tvar err error\n\tfor i := 0; i < p.c.NTry; i++ {\n\t\ttime.Sleep(time.Duration(math.Exp2(float64(i))) * 100 * time.Millisecond) \/\/ exponential back-off\n\t\terr = p.putPart(part)\n\t\tif err == nil {\n\t\t\tp.sp.give <- part.b\n\t\t\tpart.b = nil\n\t\t\treturn\n\t\t}\n\t\tlogger.debugPrintf(\"Error on attempt %d: Retrying part: %d, Error: %s\", i, part.PartNumber, err)\n\t}\n\tp.err = err\n}\n\n\/\/ uploads a part, checking the etag against the calculated value\nfunc (p *putter) putPart(part *part) error {\n\tv := url.Values{}\n\tv.Set(\"partNumber\", strconv.Itoa(part.PartNumber))\n\tv.Set(\"uploadId\", p.UploadId)\n\tif _, err := part.r.Seek(0, 0); err != nil { \/\/ move back to beginning, if retrying\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"PUT\", p.url.String()+\"?\"+v.Encode(), part.r)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.ContentLength = part.len\n\treq.Header.Set(md5Header, part.contentMd5)\n\tp.b.Sign(req)\n\tresp, err := p.c.Client.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer checkClose(resp.Body, &err)\n\tif resp.StatusCode != 200 {\n\t\treturn newRespError(resp)\n\t}\n\ts := resp.Header.Get(\"etag\")\n\tif len(s) < 2 {\n\t\treturn fmt.Errorf(\"Got Bad etag:%s\", s)\n\t}\n\ts = s[1 : len(s)-1] \/\/ includes quote chars for some reason\n\tif part.ETag != s {\n\t\treturn fmt.Errorf(\"Response etag does not match. Remote:%s Calculated:%s\", s, p.ETag)\n\t}\n\treturn nil\n}\n\nfunc (p *putter) Close() (err error) {\n\tif p.closed {\n\t\tp.abort()\n\t\treturn syscall.EINVAL\n\t}\n\tif p.err != nil {\n\t\tp.abort()\n\t\treturn p.err\n\t}\n\tif p.bufbytes > 0 || \/\/ partial part\n\t\tp.part == 0 { \/\/ 0 length file\n\t\tp.flush()\n\t}\n\tp.wg.Wait()\n\tclose(p.ch)\n\tp.closed = true\n\tclose(p.sp.quit)\n\n\t\/\/ check p.err before completing\n\tif p.err != nil {\n\t\tp.abort()\n\t\treturn p.err\n\t}\n\t\/\/ Complete Multipart upload\n\tbody, err := xml.Marshal(p.xml)\n\tif err != nil {\n\t\tp.abort()\n\t\treturn\n\t}\n\tb := bytes.NewReader(body)\n\tv := url.Values{}\n\tv.Set(\"uploadId\", p.UploadId)\n\tresp, err := p.retryRequest(\"POST\", p.url.String()+\"?\"+v.Encode(), b, nil)\n\tif err != nil {\n\t\tp.abort()\n\t\treturn\n\t}\n\tdefer checkClose(resp.Body, &err)\n\tif resp.StatusCode != 200 {\n\t\tp.abort()\n\t\treturn newRespError(resp)\n\t}\n\t\/\/ Check md5 hash of concatenated part md5 hashes against ETag\n\t\/\/ more info: https:\/\/forums.aws.amazon.com\/thread.jspa?messageID=456442&#456442\n\tcalculatedMd5ofParts := fmt.Sprintf(\"%x\", p.md5OfParts.Sum(nil))\n\t\/\/ Parse etag from body of response\n\terr = xml.NewDecoder(resp.Body).Decode(p)\n\tif err != nil {\n\t\treturn\n\t}\n\t\/\/ strip part count from end and '\"' from front.\n\tremoteMd5ofParts := strings.Split(p.ETag, \"-\")[0]\n\tif len(remoteMd5ofParts) == 0 {\n\t\treturn fmt.Errorf(\"Nil ETag\")\n\t}\n\tremoteMd5ofParts = remoteMd5ofParts[1:len(remoteMd5ofParts)]\n\tif calculatedMd5ofParts != remoteMd5ofParts {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn fmt.Errorf(\"MD5 hash of part hashes comparison failed. Hash from multipart complete header: %s.\"+\n\t\t\t\" Calculated multipart hash: %s.\", remoteMd5ofParts, calculatedMd5ofParts)\n\t}\n\tif p.c.Md5Check {\n\t\tfor i := 0; i < p.c.NTry; i++ {\n\t\t\tif err = p.putMd5(); err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ Try to abort multipart upload. Do not error on failure.\nfunc (p *putter) abort() {\n\tv := url.Values{}\n\tv.Set(\"uploadId\", p.UploadId)\n\ts := p.url.String() + \"?\" + v.Encode()\n\tresp, err := p.retryRequest(\"DELETE\", s, nil, nil)\n\tif err != nil {\n\t\tlogger.Printf(\"Error aborting multipart upload: %v\\n\", err)\n\t\treturn\n\t}\n\tdefer checkClose(resp.Body, &err)\n\tif resp.StatusCode != 204 {\n\t\tlogger.Printf(\"Error aborting multipart upload: %v\", newRespError(resp))\n\t}\n\treturn\n}\n\n\/\/ Md5 functions\nfunc (p *putter) md5Content(r io.ReadSeeker) (string, string, error) {\n\th := md5.New()\n\tmw := io.MultiWriter(h, p.md5)\n\tif _, err := io.Copy(mw, r); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tsum := h.Sum(nil)\n\thexSum := fmt.Sprintf(\"%x\", sum)\n\t\/\/ add to checksum of all parts for verification on upload completion\n\tif _, err := p.md5OfParts.Write(sum); err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\treturn base64.StdEncoding.EncodeToString(sum), hexSum, nil\n}\n\n\/\/ Put md5 file in .md5 subdirectory of bucket  where the file is stored\n\/\/ e.g. the md5 for https:\/\/mybucket.s3.amazonaws.com\/gof3r will be stored in\n\/\/ https:\/\/mybucket.s3.amazonaws.com\/.md5\/gof3r.md5\nfunc (p *putter) putMd5() (err error) {\n\tcalcMd5 := fmt.Sprintf(\"%x\", p.md5.Sum(nil))\n\tmd5Reader := strings.NewReader(calcMd5)\n\tmd5Path := fmt.Sprint(\".md5\", p.url.Path, \".md5\")\n\tmd5Url, err := p.b.url(md5Path, p.c)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.debugPrintln(\"md5: \", calcMd5)\n\tlogger.debugPrintln(\"md5Path: \", md5Path)\n\tr, err := http.NewRequest(\"PUT\", md5Url.String(), md5Reader)\n\tif err != nil {\n\t\treturn\n\t}\n\tp.b.Sign(r)\n\tresp, err := p.c.Client.Do(r)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer checkClose(resp.Body, &err)\n\tif resp.StatusCode != 200 {\n\t\treturn newRespError(resp)\n\t}\n\treturn\n}\n\nfunc (p *putter) retryRequest(method, urlStr string, body io.ReadSeeker, h http.Header) (resp *http.Response, err error) {\n\tfor i := 0; i < p.c.NTry; i++ {\n\t\tvar req *http.Request\n\t\treq, err = http.NewRequest(method, urlStr, body)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tfor k := range h {\n\t\t\tfor _, v := range h[k] {\n\t\t\t\treq.Header.Add(k, v)\n\t\t\t}\n\t\t}\n\n\t\tp.b.Sign(req)\n\t\tresp, err = p.c.Client.Do(req)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t\tlogger.debugPrintln(err)\n\t\tif body != nil {\n\t\t\tif _, err = body.Seek(0, 0); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ returns true unless partSize is large enough\n\/\/ to achieve maxObjSize with remaining parts\nfunc growPartSize(partIndex int, partSize, putsz int64) bool {\n\treturn (maxObjSize-putsz)\/(maxNPart-int64(partIndex)) > partSize\n}\n<|endoftext|>"}
{"text":"<commit_before>package integration_test\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/ginkgo\/extensions\/table\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"Garden External Networker errors\", func() {\n\tvar (\n\t\tcommand            *exec.Cmd\n\t\tfakeConfigFilePath string\n\t\tdefaultConfig      map[string]interface{}\n\t)\n\n\tvar writeConfig = func(configHash map[string]interface{}) {\n\t\tconfigBytes, err := json.Marshal(configHash)\n\t\tExpect(err).NotTo(HaveOccurred())\n\t\terr = ioutil.WriteFile(fakeConfigFilePath, configBytes, 0600)\n\t\tExpect(err).NotTo(HaveOccurred())\n\t}\n\n\tBeforeEach(func() {\n\t\tvar err error\n\t\tconfigFile, err := ioutil.TempFile(\"\", \"adapter-config-\")\n\t\tExpect(err).NotTo(HaveOccurred())\n\t\tExpect(configFile.Close()).To(Succeed())\n\n\t\tdir, err := ioutil.TempDir(\"\", \"fake-cni-dir\")\n\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\tstateFilePath, err := ioutil.TempFile(\"\", \"external-networker-state.json\")\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\tfakeConfigFilePath = configFile.Name()\n\t\tdefaultConfig = map[string]interface{}{\n\t\t\t\"cni_plugin_dir\": dir,\n\t\t\t\"cni_config_dir\": dir,\n\t\t\t\"bind_mount_dir\": dir,\n\t\t\t\"state_file\":     stateFilePath.Name(),\n\t\t\t\"start_port\":     1234,\n\t\t\t\"total_ports\":    56,\n\t\t}\n\t\twriteConfig(defaultConfig)\n\n\t\tcommand = exec.Command(paths.PathToAdapter)\n\t\tcommand.Args = []string{paths.PathToAdapter,\n\t\t\t\"--action=up\",\n\t\t\t\"--handle=some-container-handle\",\n\t\t\t\"--configFile=\" + fakeConfigFilePath,\n\t\t}\n\t\tcommand.Env = []string{\"PATH=\/sbin\"}\n\n\t\tcommand.Stdin = strings.NewReader(fmt.Sprintf(`{ \"pid\": %d }`, GinkgoParallelNode()))\n\t})\n\n\tContext(\"when inputs are invalid\", func() {\n\t\tContext(\"when there's a generic error in main\", func() {\n\t\t\tIt(\"prints the error to stderr with the lager logger\", func() {\n\t\t\t\tcommand.Args = []string{\n\t\t\t\t\tpaths.PathToAdapter,\n\t\t\t\t\t\"invalidArg\",\n\t\t\t\t}\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(\"error: parse args: unexpected extra args: [invalidArg]\"))\n\t\t\t})\n\t\t})\n\t\tContext(\"when stdin is not valid JSON\", func() {\n\t\t\tIt(\"should exit status 1 and print an error to stderr\", func() {\n\t\t\t\tcommand.Stdin = strings.NewReader(\"{{{bad\")\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\tBy(\"checking that the error was logged to stderr\")\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(\"invalid character\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the stdin JSON is missing a pid field\", func() {\n\t\t\tIt(\"should exit status 1 and print an error to stderr\", func() {\n\t\t\t\tcommand.Stdin = strings.NewReader(`{ \"something\": 12 }`)\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session, \"2s\").Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(\"missing pid\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the provided pid is not an integer\", func() {\n\t\t\tIt(\"should exit status 1 and print an error to stderr\", func() {\n\t\t\t\tcommand.Stdin = strings.NewReader(`{ \"pid\": \"not-a-number\"  }`)\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(`cannot unmarshal string into Go value of type int`))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the action is incorrect\", func() {\n\t\t\tIt(\"should return an error\", func() {\n\t\t\t\tcommand.Args[1] = \"--action=some-invalid-action\"\n\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(`unrecognized action: some-invalid-action`))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when an unknown flag is provided\", func() {\n\t\t\tIt(\"should return an error\", func() {\n\t\t\t\tcommand.Args = append(command.Args, \"--banana\")\n\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(`flag provided but not defined: -banana`))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when an unknown positional arg is provided\", func() {\n\t\t\tIt(\"should return an error\", func() {\n\t\t\t\tcommand.Args = append(command.Args, \"something-else\")\n\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(`unexpected extra args: [something-else]`))\n\t\t\t})\n\t\t})\n\n\t\tvar removeArrayElement = func(src []string, elementToRemove string) []string {\n\t\t\treduced := []string{}\n\t\t\tfor _, element := range src {\n\t\t\t\tif !strings.HasPrefix(element, elementToRemove) {\n\t\t\t\t\treduced = append(reduced, element)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn reduced\n\t\t}\n\n\t\tDescribeTable(\"missing required arguments\",\n\t\t\tfunc(missingFlag string) {\n\t\t\t\tcommand.Args = removeArrayElement(command.Args, \"--\"+missingFlag)\n\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tBy(\"checking that process exits with an err\")\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\n\t\t\t\tBy(\"checking that the error was logged to stderr\")\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\texpectedErrorString := fmt.Sprintf(\"missing required flag '%s'\", missingFlag)\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(expectedErrorString))\n\t\t\t},\n\t\t\tEntry(\"action\", \"action\"),\n\t\t\tEntry(\"handle\", \"handle\"),\n\t\t\tEntry(\"configFile\", \"configFile\"),\n\t\t)\n\n\t\tDescribeTable(\"missing required config\",\n\t\t\tfunc(missingKey string) {\n\t\t\t\tdelete(defaultConfig, missingKey)\n\t\t\t\twriteConfig(defaultConfig)\n\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tBy(\"checking that process exits with an err\")\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\n\t\t\t\tBy(\"checking that the error was logged to stderr\")\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\texpectedErrorString := fmt.Sprintf(\"missing required config '%s'\", missingKey)\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(expectedErrorString))\n\t\t\t},\n\t\t\tEntry(\"cni_plugin_dir\", \"cni_plugin_dir\"),\n\t\t\tEntry(\"cni_config_dir\", \"cni_config_dir\"),\n\t\t\tEntry(\"bind_mount_dir\", \"bind_mount_dir\"),\n\t\t)\n\n\t\tContext(\"when the user doesn't know what to do\", func() {\n\t\t\tDescribeTable(\"arguments that indicate ignorance\",\n\t\t\t\tfunc(args []string) {\n\t\t\t\t\tcommand.Args = args\n\t\t\t\t\tcommand.Stdin = strings.NewReader(\"invalid json\")\n\n\t\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(`this is a plugin for Garden-runC.  Don't run it directly.`))\n\t\t\t\t},\n\t\t\t\tEntry(\"no args\", []string{paths.PathToAdapter}),\n\t\t\t\tEntry(\"short help\", []string{paths.PathToAdapter, \"-h\"}),\n\t\t\t\tEntry(\"long help\", []string{paths.PathToAdapter, \"--help\"}),\n\t\t\t)\n\t\t})\n\t})\n})\n<commit_msg>Relax assertion on error string<commit_after>package integration_test\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/ginkgo\/extensions\/table\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"Garden External Networker errors\", func() {\n\tvar (\n\t\tcommand            *exec.Cmd\n\t\tfakeConfigFilePath string\n\t\tdefaultConfig      map[string]interface{}\n\t)\n\n\tvar writeConfig = func(configHash map[string]interface{}) {\n\t\tconfigBytes, err := json.Marshal(configHash)\n\t\tExpect(err).NotTo(HaveOccurred())\n\t\terr = ioutil.WriteFile(fakeConfigFilePath, configBytes, 0600)\n\t\tExpect(err).NotTo(HaveOccurred())\n\t}\n\n\tBeforeEach(func() {\n\t\tvar err error\n\t\tconfigFile, err := ioutil.TempFile(\"\", \"adapter-config-\")\n\t\tExpect(err).NotTo(HaveOccurred())\n\t\tExpect(configFile.Close()).To(Succeed())\n\n\t\tdir, err := ioutil.TempDir(\"\", \"fake-cni-dir\")\n\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\tstateFilePath, err := ioutil.TempFile(\"\", \"external-networker-state.json\")\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\tfakeConfigFilePath = configFile.Name()\n\t\tdefaultConfig = map[string]interface{}{\n\t\t\t\"cni_plugin_dir\": dir,\n\t\t\t\"cni_config_dir\": dir,\n\t\t\t\"bind_mount_dir\": dir,\n\t\t\t\"state_file\":     stateFilePath.Name(),\n\t\t\t\"start_port\":     1234,\n\t\t\t\"total_ports\":    56,\n\t\t}\n\t\twriteConfig(defaultConfig)\n\n\t\tcommand = exec.Command(paths.PathToAdapter)\n\t\tcommand.Args = []string{paths.PathToAdapter,\n\t\t\t\"--action=up\",\n\t\t\t\"--handle=some-container-handle\",\n\t\t\t\"--configFile=\" + fakeConfigFilePath,\n\t\t}\n\t\tcommand.Env = []string{\"PATH=\/sbin\"}\n\n\t\tcommand.Stdin = strings.NewReader(fmt.Sprintf(`{ \"pid\": %d }`, GinkgoParallelNode()))\n\t})\n\n\tContext(\"when inputs are invalid\", func() {\n\t\tContext(\"when there's a generic error in main\", func() {\n\t\t\tIt(\"prints the error to stderr with the lager logger\", func() {\n\t\t\t\tcommand.Args = []string{\n\t\t\t\t\tpaths.PathToAdapter,\n\t\t\t\t\t\"invalidArg\",\n\t\t\t\t}\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(\"error: parse args: unexpected extra args: [invalidArg]\"))\n\t\t\t})\n\t\t})\n\t\tContext(\"when stdin is not valid JSON\", func() {\n\t\t\tIt(\"should exit status 1 and print an error to stderr\", func() {\n\t\t\t\tcommand.Stdin = strings.NewReader(\"{{{bad\")\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\tBy(\"checking that the error was logged to stderr\")\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(\"invalid character\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the stdin JSON is missing a pid field\", func() {\n\t\t\tIt(\"should exit status 1 and print an error to stderr\", func() {\n\t\t\t\tcommand.Stdin = strings.NewReader(`{ \"something\": 12 }`)\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session, \"2s\").Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(\"missing pid\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the provided pid is not an integer\", func() {\n\t\t\tIt(\"should exit status 1 and print an error to stderr\", func() {\n\t\t\t\tcommand.Stdin = strings.NewReader(`{ \"pid\": \"not-a-number\"  }`)\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\tExpect(session.Err.Contents()).To(MatchRegexp(`cannot unmarshal string into Go.*type int`))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the action is incorrect\", func() {\n\t\t\tIt(\"should return an error\", func() {\n\t\t\t\tcommand.Args[1] = \"--action=some-invalid-action\"\n\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(`unrecognized action: some-invalid-action`))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when an unknown flag is provided\", func() {\n\t\t\tIt(\"should return an error\", func() {\n\t\t\t\tcommand.Args = append(command.Args, \"--banana\")\n\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(`flag provided but not defined: -banana`))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when an unknown positional arg is provided\", func() {\n\t\t\tIt(\"should return an error\", func() {\n\t\t\t\tcommand.Args = append(command.Args, \"something-else\")\n\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(`unexpected extra args: [something-else]`))\n\t\t\t})\n\t\t})\n\n\t\tvar removeArrayElement = func(src []string, elementToRemove string) []string {\n\t\t\treduced := []string{}\n\t\t\tfor _, element := range src {\n\t\t\t\tif !strings.HasPrefix(element, elementToRemove) {\n\t\t\t\t\treduced = append(reduced, element)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn reduced\n\t\t}\n\n\t\tDescribeTable(\"missing required arguments\",\n\t\t\tfunc(missingFlag string) {\n\t\t\t\tcommand.Args = removeArrayElement(command.Args, \"--\"+missingFlag)\n\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tBy(\"checking that process exits with an err\")\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\n\t\t\t\tBy(\"checking that the error was logged to stderr\")\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\texpectedErrorString := fmt.Sprintf(\"missing required flag '%s'\", missingFlag)\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(expectedErrorString))\n\t\t\t},\n\t\t\tEntry(\"action\", \"action\"),\n\t\t\tEntry(\"handle\", \"handle\"),\n\t\t\tEntry(\"configFile\", \"configFile\"),\n\t\t)\n\n\t\tDescribeTable(\"missing required config\",\n\t\t\tfunc(missingKey string) {\n\t\t\t\tdelete(defaultConfig, missingKey)\n\t\t\t\twriteConfig(defaultConfig)\n\n\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tBy(\"checking that process exits with an err\")\n\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\n\t\t\t\tBy(\"checking that the error was logged to stderr\")\n\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\texpectedErrorString := fmt.Sprintf(\"missing required config '%s'\", missingKey)\n\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(expectedErrorString))\n\t\t\t},\n\t\t\tEntry(\"cni_plugin_dir\", \"cni_plugin_dir\"),\n\t\t\tEntry(\"cni_config_dir\", \"cni_config_dir\"),\n\t\t\tEntry(\"bind_mount_dir\", \"bind_mount_dir\"),\n\t\t)\n\n\t\tContext(\"when the user doesn't know what to do\", func() {\n\t\t\tDescribeTable(\"arguments that indicate ignorance\",\n\t\t\t\tfunc(args []string) {\n\t\t\t\t\tcommand.Args = args\n\t\t\t\t\tcommand.Stdin = strings.NewReader(\"invalid json\")\n\n\t\t\t\t\tsession, err := gexec.Start(command, GinkgoWriter, GinkgoWriter)\n\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\tEventually(session).Should(gexec.Exit(1))\n\t\t\t\t\tExpect(session.Out.Contents()).To(BeEmpty())\n\t\t\t\t\tExpect(session.Err.Contents()).To(ContainSubstring(`this is a plugin for Garden-runC.  Don't run it directly.`))\n\t\t\t\t},\n\t\t\t\tEntry(\"no args\", []string{paths.PathToAdapter}),\n\t\t\t\tEntry(\"short help\", []string{paths.PathToAdapter, \"-h\"}),\n\t\t\t\tEntry(\"long help\", []string{paths.PathToAdapter, \"--help\"}),\n\t\t\t)\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package matching\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/SpectoLabs\/hoverfly\/core\/util\"\n)\n\nfunc JsonMatch(matchingString string, toMatch string) bool {\n\tminifiedMatchingString, err := util.MinifyJson(matchingString)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tminifiedToMatch, err := util.MinifyJson(toMatch)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tvar matchingJson, toMatchJson map[string]interface{}\n\n\terr = json.Unmarshal([]byte(minifiedMatchingString), &matchingJson)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\terr = json.Unmarshal([]byte(minifiedToMatch), &toMatchJson)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tfmt.Println(matchingJson)\n\tfmt.Println(toMatchJson)\n\treturn reflect.DeepEqual(matchingJson, toMatchJson)\n}\n<commit_msg>Removing fmt calls<commit_after>package matching\n\nimport (\n\t\"encoding\/json\"\n\t\"reflect\"\n\n\t\"github.com\/SpectoLabs\/hoverfly\/core\/util\"\n)\n\nfunc JsonMatch(matchingString string, toMatch string) bool {\n\tminifiedMatchingString, err := util.MinifyJson(matchingString)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tminifiedToMatch, err := util.MinifyJson(toMatch)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tvar matchingJson, toMatchJson map[string]interface{}\n\n\terr = json.Unmarshal([]byte(minifiedMatchingString), &matchingJson)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\terr = json.Unmarshal([]byte(minifiedToMatch), &toMatchJson)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\treturn reflect.DeepEqual(matchingJson, toMatchJson)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ syncwatcher.go\npackage main\n\nimport (\n\t\"code.google.com\/p\/go.exp\/fsnotify\"\n\t\"os\"\n\t\"bufio\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"log\"\n\t\"fmt\"\n\t\"time\"\n\t\"flag\"\n\t\"runtime\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sort\"\n)\n\n\ntype Configuration struct {\n\tVersion\t\t\tint\n\tRepositories\t[]RepositoryConfiguration\n}\n\ntype RepositoryConfiguration struct {\n\tID\t\t\t\t\tstring\n\tDirectory\t\t\tstring\n\tReadOnly\t\t\tbool\n\tRescanIntervalS\t\tint\n}\n\n\n\/\/ HTTP Authentication\nvar (\n\ttarget\t\tstring\n\tauthUser\tstring\n\tauthPass\tstring\n\tcsrfToken\tstring\n\tcsrfFile\tstring\n\tapiKey\t\tstring\n)\n\n\/\/ HTTP Debounce\nvar (\n\tdebounceTimeout = 300*time.Millisecond\n\tdirVsFiles = 10\n)\n\n\/\/ Main\nvar (\n\tstop = make(chan int)\n)\n\nfunc init() {\n\tflag.StringVar(&target, \"target\", \"localhost:8080\", \"Target\")\n\tflag.StringVar(&authUser, \"user\", \"\", \"Username\")\n\tflag.StringVar(&authPass, \"pass\", \"\", \"Password\")\n\tflag.StringVar(&csrfFile, \"csrf\", \"\", \"CSRF token file\")\n\tflag.StringVar(&apiKey, \"api\", \"\", \"API key\")\n\tflag.Parse()\n\tif !strings.Contains(target, \":\/\/\") { target = \"http:\/\/\" + target }\t\n\tif len(csrfFile) > 0 {\n\t\tfd, err := os.Open(csrfFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\ts := bufio.NewScanner(fd)\n\t\tfor s.Scan() {\n\t\t\tcsrfToken = s.Text()\n\t\t}\n\t\tfd.Close()\n\t}\n}\n\nfunc main() {\n\n\ttestWebGuiPost()\n\n\trepos := getRepos()\n\tfor i := range repos {\n\t\trepo := repos[i]\n\t\trepodir := repo.Directory\n\t\trepodir = expandTilde(repo.Directory)\n\t\tgo watchRepo(repo.ID, repodir)\n\t}\n\n\tcode := <-stop\n\tprintln(\"Exiting\")\n\tos.Exit(code)\n\n}\n\nfunc getRepos() []RepositoryConfiguration {\n\tr, err := http.NewRequest(\"GET\", target+\"\/rest\/config\", nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif len(csrfToken) > 0 {\n\t\tr.Header.Set(\"X-CSRF-Token\", csrfToken)\n\t}\n\tif len(authUser) > 0 {\n\t\tr.SetBasicAuth(authUser, authPass)\n\t}\n\tif len(apiKey) > 0 {\n\t\tr.Header.Set(\"X-API-Key\", apiKey)\n\t}\n\ttr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify : true} }\n\tclient := &http.Client{Transport: tr, Timeout: 5*time.Second}\n\tres, err := client.Do(r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != 200 {\n\t\tlog.Fatalf(\"Status %d != 200 for GET\", res.StatusCode)\n\t}\n\tbs, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar cfg Configuration\n\terr = json.Unmarshal(bs, &cfg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn cfg.Repositories\n}\n\nfunc watchRepo(repo string, directory string) {\n\texpandedDirectory := expandTilde(directory)\n\tsw, err := NewSyncWatcher()\n\tif sw == nil || err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer sw.Close()\n\terr = sw.Watch(expandedDirectory)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tinformChangeDebounced := informChangeDebounce(debounceTimeout, repo, directory, dirVsFiles, informChange)\n\tlog.Println(\"Watching \" + repo + \": \" + directory)\n\tfor {\n\t\tev := waitForEvent(sw)\n\t\tif ev == nil {\n\t\t\tlog.Println(\"Error: fsnotify event is nil\")\n\t\t\tcontinue\n\t\t}\n\t\tlog.Println(\"Change detected in \" + ev.Name)\n\t\tinformChangeDebounced(ev.Name)\n\t}\n}\n\nfunc waitForEvent(sw *SyncWatcher) (ev *fsnotify.FileEvent) {\n\tvar ok bool\n\tselect {\n\t\tcase ev, ok = <-sw.Event:\n\t\t\tif !ok {\n\t\t\t\tlog.Println(\"Error: channel closed\")\n\t\t\t}\n\t\tcase err, eok := <-sw.Error:\n\t\t\tlog.Println(err, eok)\n\t}\n\treturn\n}\n\nfunc testWebGuiPost() {\n\tr, err := http.NewRequest(\"POST\", target+\"\/rest\/404\", nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif len(csrfToken) > 0 {\n\t\tr.Header.Set(\"X-CSRF-Token\", csrfToken)\n\t}\n\tif len(authUser) > 0 {\n\t\tr.SetBasicAuth(authUser, authPass)\n\t}\n\tif len(apiKey) > 0 {\n\t\tr.Header.Set(\"X-API-Key\", apiKey)\n\t}\n\ttr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify : true} }\n\tclient := &http.Client{Transport: tr, Timeout: 5*time.Second}\n\tres, err := client.Do(r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != 404 {\n\t\tlog.Fatalf(\"Status %d != 404 for POST\\n\", res.StatusCode)\n\t}\n}\n\nfunc informChange(repo string, sub string) {\n\tdata := url.Values {}\n\tdata.Set(\"repo\", repo)\n\tdata.Set(\"sub\", sub)\n\tr, err := http.NewRequest(\"POST\", target+\"\/rest\/scan?\"+data.Encode(), nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tif len(csrfToken) > 0 {\n\t\tr.Header.Set(\"X-CSRF-Token\", csrfToken)\n\t}\n\tif len(authUser) > 0 {\n\t\tr.SetBasicAuth(authUser, authPass)\n\t}\n\tif len(apiKey) > 0 {\n\t\tr.Header.Set(\"X-API-Key\", apiKey)\n\t}\n\ttr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify : true} }\n\tclient := &http.Client{Transport: tr, Timeout: 5*time.Second}\n\tres, err := client.Do(r)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tif res.StatusCode != 200 {\n\t\tlog.Printf(\"Error: Status %d != 200 for POST.\\n\" + repo + \": \" + sub, res.StatusCode)\n\t\treturn\n\t} else {\n\t\tlog.Println(\"Syncthing is indexing change in \" + repo + \": \" + sub)\n\t}\n}\n\n\nfunc informChangeDebounce(interval time.Duration, repo string, repoDirectory string, dirVsFiles int, callback func(repo string, sub string)) func(string) {\n\tdebounce := func(f func(paths []string)) func(string) {\n\t\ttimer := &time.Timer{}\n\t\tsubs := make([]string, 0)\n\t\treturn func(sub string) {\n\t\t\ttimer.Stop()\n\t\t\tsubs = append(subs, sub)\n\t\t\ttimer = time.AfterFunc(interval, func() {\n\t\t\t\tf(subs)\n\t\t\t\tsubs = make([]string, 0)\n\t\t\t})\n\t\t}\n\t}\n\t\n\treturn debounce(func(paths []string) {\n\t\t\/\/ Do not inform Syncthing immediately but wait for debounce\n\t\t\/\/ Therefore, we need to keep track of the paths that were changed\n\t\t\/\/ This function optimises tracking in two ways:\n\t\t\/\/\t- If there are more than `dirVsFiles` changes in a directory, we inform Syncthing to scan the entire directory\n\t\t\/\/\t- Directories with parent directory changes are aggregated. If A\/B has 3 changes and A\/C has 8, A will have 11 changes and if this is bigger than dirVsFiles we will scan A.\n\t\tif (len(paths) == 0) { return }\n\t\ttrackedPaths := make(map[string]int) \/\/ Map directories to scores; if score == -1 the path is a filename\n\t\tsort.Strings(paths) \/\/ Make sure parent paths are processed first\n\t\tfor i := range paths {\n\t\t\tpath := paths[i]\n\t\t\tdir := filepath.Dir(path)\n\t\t\tscore := 1 \/\/ File change counts for 1 per directory\n\t\t\tif dir == filepath.Clean(path) {\n\t\t\t\tscore = dirVsFiles \/\/ Is directory itself, should definitely inform\n\t\t\t}\n\t\t\t\/\/ Search for existing parent directory relations in the map\n\t\t\tfor trackedPath, _ := range trackedPaths {\n\t\t\t\tif strings.Contains(dir, trackedPath) {\n\t\t\t\t\t\/\/ Increment score of tracked current\/parent directory\n\t\t\t\t\ttrackedPaths[trackedPath] += score\n\t\t\t\t}\n\t\t\t}\n\t\t\t_, exists := trackedPaths[dir]\n\t\t\tif !exists {\n\t\t\t\ttrackedPaths[dir] = score\n\t\t\t}\n\t\t\ttrackedPaths[path] = -1\n\t\t}\n\t\tvar keys []string\n\t\tfor k := range trackedPaths {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Strings(keys) \/\/ Sort directories before their own files\n\t\tpreviousDone, previousPath := false, \"\"\n\t\tfor i := range keys {\n\t\t\ttrackedPath := keys[i]\n\t\t\ttrackedPathScore, _ := trackedPaths[trackedPath]\n\t\t\tif previousDone && strings.Contains(trackedPath, previousPath) { continue } \/\/ Already informed parent directory change\n\t\t\tif trackedPathScore < dirVsFiles && trackedPathScore != -1 { continue } \/\/ Not enough files for this directory or it is a file\n\t\t\tpreviousDone = trackedPathScore != -1\n\t\t\tpreviousPath = trackedPath\n\t\t\tsub := strings.TrimPrefix(trackedPath, repoDirectory)\n\t\t\tsub = strings.TrimPrefix(sub, string(os.PathSeparator))\n\t\t\tcallback(repo, sub)\n\t\t}\n\t})\n}\n\nfunc getHomeDir() string {\n\tvar home string\n\tswitch runtime.GOOS {\n\t\tcase \"windows\":\n\t\thome = filepath.Join(os.Getenv(\"HomeDrive\"), os.Getenv(\"HomePath\"))\n\t\tif home == \"\" {\n\t\t\thome = os.Getenv(\"UserProfile\")\n\t\t}\n\t\tdefault:\n\t\t\thome = os.Getenv(\"HOME\")\n\t}\n\tif home == \"\" {\n\t\tlog.Fatal(\"No home directory found - set $HOME (or the platform equivalent).\")\n\t}\n\treturn home\n}\n\nfunc expandTilde(p string) string {\n\tif p == \"~\" {\n\t\treturn getHomeDir()\n\t}\n\tp = filepath.FromSlash(p)\n\tif !strings.HasPrefix(p, fmt.Sprintf(\"~%c\", os.PathSeparator)) {\n\t\treturn p\n\t}\n\treturn filepath.Join(getHomeDir(), p[2:])\n}\n<commit_msg>Update compatibility with Syncthing wrt Repo vs Folder naming<commit_after>\/\/ syncwatcher.go\npackage main\n\nimport (\n\t\"code.google.com\/p\/go.exp\/fsnotify\"\n\t\"os\"\n\t\"bufio\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"log\"\n\t\"fmt\"\n\t\"time\"\n\t\"flag\"\n\t\"runtime\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sort\"\n)\n\n\ntype Configuration struct {\n\tVersion\t\t\tint\n\tFolders\t\t\t[]FolderConfiguration\n}\n\ntype FolderConfiguration struct {\n\tID\t\t\tstring\n\tPath\t\t\tstring\n\tReadOnly\t\tbool\n\tRescanIntervalS\t\tint\n}\n\n\n\/\/ HTTP Authentication\nvar (\n\ttarget\t\tstring\n\tauthUser\tstring\n\tauthPass\tstring\n\tcsrfToken\tstring\n\tcsrfFile\tstring\n\tapiKey\t\tstring\n)\n\n\/\/ HTTP Debounce\nvar (\n\tdebounceTimeout = 300*time.Millisecond\n\tdirVsFiles = 10\n)\n\n\/\/ Main\nvar (\n\tstop = make(chan int)\n)\n\nfunc init() {\n\tflag.StringVar(&target, \"target\", \"localhost:8080\", \"Target\")\n\tflag.StringVar(&authUser, \"user\", \"\", \"Username\")\n\tflag.StringVar(&authPass, \"pass\", \"\", \"Password\")\n\tflag.StringVar(&csrfFile, \"csrf\", \"\", \"CSRF token file\")\n\tflag.StringVar(&apiKey, \"api\", \"\", \"API key\")\n\tflag.Parse()\n\tif !strings.Contains(target, \":\/\/\") { target = \"http:\/\/\" + target }\t\n\tif len(csrfFile) > 0 {\n\t\tfd, err := os.Open(csrfFile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\ts := bufio.NewScanner(fd)\n\t\tfor s.Scan() {\n\t\t\tcsrfToken = s.Text()\n\t\t}\n\t\tfd.Close()\n\t}\n}\n\nfunc main() {\n\n\ttestWebGuiPost()\n\n\tfolders := getFolders()\n\tfor i := range folders {\n\t\tfolder := folders[i]\n\t\tfolderdir := folder.Path\n\t\tfolderdir = expandTilde(folder.Path)\n\t\tgo watchRepo(folder.ID, folderdir)\n\t}\n\n\tcode := <-stop\n\tprintln(\"Exiting\")\n\tos.Exit(code)\n\n}\n\nfunc getFolders() []FolderConfiguration {\n\tr, err := http.NewRequest(\"GET\", target+\"\/rest\/config\", nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif len(csrfToken) > 0 {\n\t\tr.Header.Set(\"X-CSRF-Token\", csrfToken)\n\t}\n\tif len(authUser) > 0 {\n\t\tr.SetBasicAuth(authUser, authPass)\n\t}\n\tif len(apiKey) > 0 {\n\t\tr.Header.Set(\"X-API-Key\", apiKey)\n\t}\n\ttr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify : true} }\n\tclient := &http.Client{Transport: tr, Timeout: 5*time.Second}\n\tres, err := client.Do(r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != 200 {\n\t\tlog.Fatalf(\"Status %d != 200 for GET\", res.StatusCode)\n\t}\n\tbs, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tvar cfg Configuration\n\terr = json.Unmarshal(bs, &cfg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn cfg.Folders\n}\n\nfunc watchRepo(folder string, path string) {\n\texpandedPath := expandTilde(path)\n\tsw, err := NewSyncWatcher()\n\tif sw == nil || err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer sw.Close()\n\terr = sw.Watch(expandedPath)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tinformChangeDebounced := informChangeDebounce(debounceTimeout, folder, path, dirVsFiles, informChange)\n\tlog.Println(\"Watching \" + folder + \": \" + path)\n\tfor {\n\t\tev := waitForEvent(sw)\n\t\tif ev == nil {\n\t\t\tlog.Println(\"Error: fsnotify event is nil\")\n\t\t\tcontinue\n\t\t}\n\t\tlog.Println(\"Change detected in \" + ev.Name)\n\t\tinformChangeDebounced(ev.Name)\n\t}\n}\n\nfunc waitForEvent(sw *SyncWatcher) (ev *fsnotify.FileEvent) {\n\tvar ok bool\n\tselect {\n\t\tcase ev, ok = <-sw.Event:\n\t\t\tif !ok {\n\t\t\t\tlog.Println(\"Error: channel closed\")\n\t\t\t}\n\t\tcase err, eok := <-sw.Error:\n\t\t\tlog.Println(err, eok)\n\t}\n\treturn\n}\n\nfunc testWebGuiPost() {\n\tr, err := http.NewRequest(\"POST\", target+\"\/rest\/404\", nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif len(csrfToken) > 0 {\n\t\tr.Header.Set(\"X-CSRF-Token\", csrfToken)\n\t}\n\tif len(authUser) > 0 {\n\t\tr.SetBasicAuth(authUser, authPass)\n\t}\n\tif len(apiKey) > 0 {\n\t\tr.Header.Set(\"X-API-Key\", apiKey)\n\t}\n\ttr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify : true} }\n\tclient := &http.Client{Transport: tr, Timeout: 5*time.Second}\n\tres, err := client.Do(r)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != 404 {\n\t\tlog.Fatalf(\"Status %d != 404 for POST\\n\", res.StatusCode)\n\t}\n}\n\nfunc informChange(folder string, sub string) {\n\tdata := url.Values {}\n\tdata.Set(\"folder\", folder)\n\tdata.Set(\"sub\", sub)\n\tr, err := http.NewRequest(\"POST\", target+\"\/rest\/scan?\"+data.Encode(), nil)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tif len(csrfToken) > 0 {\n\t\tr.Header.Set(\"X-CSRF-Token\", csrfToken)\n\t}\n\tif len(authUser) > 0 {\n\t\tr.SetBasicAuth(authUser, authPass)\n\t}\n\tif len(apiKey) > 0 {\n\t\tr.Header.Set(\"X-API-Key\", apiKey)\n\t}\n\ttr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify : true} }\n\tclient := &http.Client{Transport: tr, Timeout: 5*time.Second}\n\tres, err := client.Do(r)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tif res.StatusCode != 200 {\n\t\tlog.Printf(\"Error: Status %d != 200 for POST.\\n\" + folder + \": \" + sub, res.StatusCode)\n\t\treturn\n\t} else {\n\t\tlog.Println(\"Syncthing is indexing change in \" + folder + \": \" + sub)\n\t}\n}\n\n\nfunc informChangeDebounce(interval time.Duration, folder string, folderPath string, dirVsFiles int, callback func(folder string, sub string)) func(string) {\n\tdebounce := func(f func(paths []string)) func(string) {\n\t\ttimer := &time.Timer{}\n\t\tsubs := make([]string, 0)\n\t\treturn func(sub string) {\n\t\t\ttimer.Stop()\n\t\t\tsubs = append(subs, sub)\n\t\t\ttimer = time.AfterFunc(interval, func() {\n\t\t\t\tf(subs)\n\t\t\t\tsubs = make([]string, 0)\n\t\t\t})\n\t\t}\n\t}\n\t\n\treturn debounce(func(paths []string) {\n\t\t\/\/ Do not inform Syncthing immediately but wait for debounce\n\t\t\/\/ Therefore, we need to keep track of the paths that were changed\n\t\t\/\/ This function optimises tracking in two ways:\n\t\t\/\/\t- If there are more than `dirVsFiles` changes in a directory, we inform Syncthing to scan the entire directory\n\t\t\/\/\t- Directories with parent directory changes are aggregated. If A\/B has 3 changes and A\/C has 8, A will have 11 changes and if this is bigger than dirVsFiles we will scan A.\n\t\tif (len(paths) == 0) { return }\n\t\ttrackedPaths := make(map[string]int) \/\/ Map directories to scores; if score == -1 the path is a filename\n\t\tsort.Strings(paths) \/\/ Make sure parent paths are processed first\n\t\tfor i := range paths {\n\t\t\tpath := paths[i]\n\t\t\tdir := filepath.Dir(path)\n\t\t\tscore := 1 \/\/ File change counts for 1 per directory\n\t\t\tif dir == filepath.Clean(path) {\n\t\t\t\tscore = dirVsFiles \/\/ Is directory itself, should definitely inform\n\t\t\t}\n\t\t\t\/\/ Search for existing parent directory relations in the map\n\t\t\tfor trackedPath, _ := range trackedPaths {\n\t\t\t\tif strings.Contains(dir, trackedPath) {\n\t\t\t\t\t\/\/ Increment score of tracked current\/parent directory\n\t\t\t\t\ttrackedPaths[trackedPath] += score\n\t\t\t\t}\n\t\t\t}\n\t\t\t_, exists := trackedPaths[dir]\n\t\t\tif !exists {\n\t\t\t\ttrackedPaths[dir] = score\n\t\t\t}\n\t\t\ttrackedPaths[path] = -1\n\t\t}\n\t\tvar keys []string\n\t\tfor k := range trackedPaths {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Strings(keys) \/\/ Sort directories before their own files\n\t\tpreviousDone, previousPath := false, \"\"\n\t\tfor i := range keys {\n\t\t\ttrackedPath := keys[i]\n\t\t\ttrackedPathScore, _ := trackedPaths[trackedPath]\n\t\t\tif previousDone && strings.Contains(trackedPath, previousPath) { continue } \/\/ Already informed parent directory change\n\t\t\tif trackedPathScore < dirVsFiles && trackedPathScore != -1 { continue } \/\/ Not enough files for this directory or it is a file\n\t\t\tpreviousDone = trackedPathScore != -1\n\t\t\tpreviousPath = trackedPath\n\t\t\tsub := strings.TrimPrefix(trackedPath, folderPath)\n\t\t\tsub = strings.TrimPrefix(sub, string(os.PathSeparator))\n\t\t\tcallback(folder, sub)\n\t\t}\n\t})\n}\n\nfunc getHomeDir() string {\n\tvar home string\n\tswitch runtime.GOOS {\n\t\tcase \"windows\":\n\t\thome = filepath.Join(os.Getenv(\"HomeDrive\"), os.Getenv(\"HomePath\"))\n\t\tif home == \"\" {\n\t\t\thome = os.Getenv(\"UserProfile\")\n\t\t}\n\t\tdefault:\n\t\t\thome = os.Getenv(\"HOME\")\n\t}\n\tif home == \"\" {\n\t\tlog.Fatal(\"No home path found - set $HOME (or the platform equivalent).\")\n\t}\n\treturn home\n}\n\nfunc expandTilde(p string) string {\n\tif p == \"~\" {\n\t\treturn getHomeDir()\n\t}\n\tp = filepath.FromSlash(p)\n\tif !strings.HasPrefix(p, fmt.Sprintf(\"~%c\", os.PathSeparator)) {\n\t\treturn p\n\t}\n\treturn filepath.Join(getHomeDir(), p[2:])\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"crypto\/md5\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nconst version = \"0.1.0+Go\"\n\ntype ansiColorer func(color int) string\n\ntype options struct {\n\tforeground ansiColorer\n\tbackground ansiColorer\n\tpattern    string\n}\n\ntype colorMode int\n\nconst (\n\tmode16Color colorMode = iota\n\tmode256color\n)\n\nfunc main() {\n\tinteractLinewise(colorLineMaker(parseArgs(os.Args[1:])))\n}\n\nfunc parseArgs(args []string) options {\n\tcolorForeground, colorBackground := true, false\n\tregexps := make([]string, 0)\n\tcolorDepth := mode256color\n\n\tacceptingFlags := true\n\tfor _, arg := range args {\n\t\tif !acceptingFlags {\n\t\t\tregexps = append(regexps, arg)\n\t\t\tcontinue\n\t\t}\n\n\t\tif arg == \"-h\" || arg == \"--help\" {\n\t\t\tprintUsage()\n\t\t\tos.Exit(0)\n\t\t} else if arg == \"-v\" || arg == \"--version\" {\n\t\t\tfmt.Printf(\"Synesthesia version %v\\n\", version)\n\t\t\tos.Exit(0)\n\t\t} else if arg == \"-f\" || arg == \"--foreground\" {\n\t\t\tcolorForeground = true\n\t\t} else if arg == \"--no-foreground\" {\n\t\t\tcolorForeground = false\n\t\t} else if arg == \"-b\" || arg == \"--background\" {\n\t\t\tcolorBackground = true\n\t\t} else if arg == \"--no-background\" {\n\t\t\tcolorBackground = false\n\t\t} else if arg == \"--16\" {\n\t\t\tcolorDepth = mode16Color\n\t\t} else if arg == \"--256\" {\n\t\t\tcolorDepth = mode256color\n\t\t} else if arg == \"--\" {\n\t\t\tacceptingFlags = false\n\t\t} else if strings.HasPrefix(arg, \"-\") {\n\t\t\tfmt.Printf(\"Unrecognized flag: %s\\n\", arg)\n\t\t\tprintUsage()\n\t\t\tos.Exit(1)\n\t\t} else {\n\t\t\tregexps = append(regexps, arg)\n\t\t}\n\t}\n\n\tforegroundColorer, backgroundColorer := colorNoop, colorNoop\n\tif colorDepth == mode16Color {\n\t\tif colorForeground {\n\t\t\tforegroundColorer = colorAnsi16Foreground\n\t\t}\n\t\tif colorBackground {\n\t\t\tbackgroundColorer = colorAnsi16Background\n\t\t}\n\t} else if colorDepth == mode256color {\n\t\tif colorForeground {\n\t\t\tforegroundColorer = colorAnsi256Foreground\n\t\t}\n\t\tif colorBackground {\n\t\t\tbackgroundColorer = colorAnsi256Background\n\t\t}\n\t}\n\n\tvalidateRegexps(regexps)\n\tfor i, pattern := range regexps {\n\t\tregexps[i] = fmt.Sprintf(\"(?:%v)\", pattern)\n\t}\n\n\treturn options{foregroundColorer, backgroundColorer, strings.Join(regexps, \"|\")}\n}\n\nfunc printUsage() {\n\tfmt.Fprintf(os.Stderr, `Usage: %v ([flags]|[patterns])... [-- [patterns]...]\nColor standard input based on the values matched by the provided regular\nexpressions.\nBefore --, any parameters starting with a dash will be interpreted as flags.\nAfter it, all parameters are interpreted as patterns.\nA pattern is any valid Go regular expression.\nMultiples of flags controlling the same option are allowed; the last flag\nspecified will take precedence over the ones that come before it.\nFlags:\n-b --background     Turn on or off background colorization. (default off)\n   --no-background\n-f --foreground     Turn on or off foreground colorization. (default on)\n   --no-foreground\n-h --help           Print usage information.\n`, os.Args[0])\n}\n\nfunc validateRegexps(regexps []string) {\n\tvalid := true\n\tfor _, pattern := range regexps {\n\t\tif _, err := regexp.Compile(pattern); err != nil {\n\t\t\tvalid = false\n\t\t\tfmt.Fprintf(os.Stderr, \"Invalid regex: %v\\n\", pattern)\n\t\t}\n\t}\n\tif !valid {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc interactLinewise(transform func([]byte) []byte) {\n\tinput := bufio.NewReader(os.Stdin)\n\tline, err := input.ReadBytes('\\n')\n\tfor err == nil {\n\t\tfmt.Print(string(transform(line)))\n\t\tline, err = input.ReadBytes('\\n')\n\t}\n\tfmt.Print(string(transform(line)))\n}\n\nfunc colorLineMaker(options options) func([]byte) []byte {\n\tpattern := regexp.MustCompile(options.pattern)\n\treturn func(line []byte) []byte {\n\t\treturn colorPatternInString(pattern, line, options.foreground, options.background)\n\t}\n}\n\nfunc colorPatternInString(pattern *regexp.Regexp, buf []byte, foreground, background ansiColorer) []byte {\n\treturn pattern.ReplaceAllFunc(buf, colorMatchMaker(foreground, background))\n}\n\nfunc colorMatchMaker(foreground, background ansiColorer) func([]byte) []byte {\n\treturn func(match []byte) []byte {\n\t\treturn color(match, foreground, background)\n\t}\n}\n\nfunc color(buf []byte, foreground, background ansiColorer) []byte {\n\tsum := md5.Sum(buf)\n\tcolor := int(sum[md5.Size-3])<<16 | int(sum[md5.Size-2])<<8 | int(sum[md5.Size-1])\n\treturn []byte(fmt.Sprintf(\"%v%v%v\\033[m\", foreground(color), background(color), string(buf)))\n}\n\nfunc colorNoop(color int) string {\n\treturn \"\"\n}\n\nfunc colorAnsi16Foreground(color int) string {\n\tcolor = color % 16\n\tindex := color%8 + 30\n\tif color < 8 {\n\t\treturn fmt.Sprintf(\"\\033[%vm\", index)\n\t}\n\treturn fmt.Sprintf(\"\\033[%v;1m\", index)\n}\n\nfunc colorAnsi16Background(color int) string {\n\tcolor = color % 16\n\tindex := color%8 + 40\n\tif color < 8 {\n\t\treturn fmt.Sprintf(\"\\033[%vm\", index)\n\t}\n\treturn fmt.Sprintf(\"\\033[%v;1m\", index)\n}\n\nfunc colorAnsi256Foreground(color int) string {\n\tr, g, b := color>>(16+3), color>>(8+3)&0x1F, color>>3&0x1F\n\treturn fmt.Sprintf(\"\\033[38;5;%vm\", rgbTo216Color(r, g, b)+16)\n}\n\nfunc colorAnsi256Background(color int) string {\n\tr, g, b := color>>(16+3), color>>(8+3)&0x1F, color>>3&0x1F\n\treturn fmt.Sprintf(\"\\033[48;5;%vm\", rgbTo216Color(r, g, b)+16)\n}\n\nfunc rgbFrom216Color(color int) (int, int, int) {\n\treturn color \/ 36, color \/ 6 % 6, color % 6\n}\n\nfunc rgbTo216Color(r, g, b int) int {\n\treturn r*36 + g*6 + b\n}\n<commit_msg>Invert background colors<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"crypto\/md5\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n)\n\nconst version = \"0.1.0+Go\"\n\ntype ansiColorer func(color int) string\n\ntype options struct {\n\tforeground ansiColorer\n\tbackground ansiColorer\n\tpattern    string\n}\n\ntype colorMode int\n\nconst (\n\tmode16Color colorMode = iota\n\tmode256color\n)\n\nfunc main() {\n\tinteractLinewise(colorLineMaker(parseArgs(os.Args[1:])))\n}\n\nfunc parseArgs(args []string) options {\n\tcolorForeground, colorBackground := true, false\n\tregexps := make([]string, 0)\n\tcolorDepth := mode256color\n\n\tacceptingFlags := true\n\tfor _, arg := range args {\n\t\tif !acceptingFlags {\n\t\t\tregexps = append(regexps, arg)\n\t\t\tcontinue\n\t\t}\n\n\t\tif arg == \"-h\" || arg == \"--help\" {\n\t\t\tprintUsage()\n\t\t\tos.Exit(0)\n\t\t} else if arg == \"-v\" || arg == \"--version\" {\n\t\t\tfmt.Printf(\"Synesthesia version %v\\n\", version)\n\t\t\tos.Exit(0)\n\t\t} else if arg == \"-f\" || arg == \"--foreground\" {\n\t\t\tcolorForeground = true\n\t\t} else if arg == \"--no-foreground\" {\n\t\t\tcolorForeground = false\n\t\t} else if arg == \"-b\" || arg == \"--background\" {\n\t\t\tcolorBackground = true\n\t\t} else if arg == \"--no-background\" {\n\t\t\tcolorBackground = false\n\t\t} else if arg == \"--16\" {\n\t\t\tcolorDepth = mode16Color\n\t\t} else if arg == \"--256\" {\n\t\t\tcolorDepth = mode256color\n\t\t} else if arg == \"--\" {\n\t\t\tacceptingFlags = false\n\t\t} else if strings.HasPrefix(arg, \"-\") {\n\t\t\tfmt.Printf(\"Unrecognized flag: %s\\n\", arg)\n\t\t\tprintUsage()\n\t\t\tos.Exit(1)\n\t\t} else {\n\t\t\tregexps = append(regexps, arg)\n\t\t}\n\t}\n\n\tforegroundColorer, backgroundColorer := colorNoop, colorNoop\n\tif colorDepth == mode16Color {\n\t\tif colorForeground {\n\t\t\tforegroundColorer = colorAnsi16Foreground\n\t\t}\n\t\tif colorBackground {\n\t\t\tbackgroundColorer = colorAnsi16Background\n\t\t}\n\t} else if colorDepth == mode256color {\n\t\tif colorForeground {\n\t\t\tforegroundColorer = colorAnsi256Foreground\n\t\t}\n\t\tif colorBackground {\n\t\t\tbackgroundColorer = colorAnsi256Background\n\t\t}\n\t}\n\n\tvalidateRegexps(regexps)\n\tfor i, pattern := range regexps {\n\t\tregexps[i] = fmt.Sprintf(\"(?:%v)\", pattern)\n\t}\n\n\treturn options{foregroundColorer, backgroundColorer, strings.Join(regexps, \"|\")}\n}\n\nfunc printUsage() {\n\tfmt.Fprintf(os.Stderr, `Usage: %v ([flags]|[patterns])... [-- [patterns]...]\nColor standard input based on the values matched by the provided regular\nexpressions.\nBefore --, any parameters starting with a dash will be interpreted as flags.\nAfter it, all parameters are interpreted as patterns.\nA pattern is any valid Go regular expression.\nMultiples of flags controlling the same option are allowed; the last flag\nspecified will take precedence over the ones that come before it.\nFlags:\n-b --background     Turn on or off background colorization. (default off)\n   --no-background\n-f --foreground     Turn on or off foreground colorization. (default on)\n   --no-foreground\n-h --help           Print usage information.\n`, os.Args[0])\n}\n\nfunc validateRegexps(regexps []string) {\n\tvalid := true\n\tfor _, pattern := range regexps {\n\t\tif _, err := regexp.Compile(pattern); err != nil {\n\t\t\tvalid = false\n\t\t\tfmt.Fprintf(os.Stderr, \"Invalid regex: %v\\n\", pattern)\n\t\t}\n\t}\n\tif !valid {\n\t\tos.Exit(1)\n\t}\n}\n\nfunc interactLinewise(transform func([]byte) []byte) {\n\tinput := bufio.NewReader(os.Stdin)\n\tline, err := input.ReadBytes('\\n')\n\tfor err == nil {\n\t\tfmt.Print(string(transform(line)))\n\t\tline, err = input.ReadBytes('\\n')\n\t}\n\tfmt.Print(string(transform(line)))\n}\n\nfunc colorLineMaker(options options) func([]byte) []byte {\n\tpattern := regexp.MustCompile(options.pattern)\n\treturn func(line []byte) []byte {\n\t\treturn colorPatternInString(pattern, line, options.foreground, options.background)\n\t}\n}\n\nfunc colorPatternInString(pattern *regexp.Regexp, buf []byte, foreground, background ansiColorer) []byte {\n\treturn pattern.ReplaceAllFunc(buf, colorMatchMaker(foreground, background))\n}\n\nfunc colorMatchMaker(foreground, background ansiColorer) func([]byte) []byte {\n\treturn func(match []byte) []byte {\n\t\treturn color(match, foreground, background)\n\t}\n}\n\nfunc color(buf []byte, foreground, background ansiColorer) []byte {\n\tsum := md5.Sum(buf)\n\tcolor := int(sum[md5.Size-3])<<16 | int(sum[md5.Size-2])<<8 | int(sum[md5.Size-1])\n\treturn []byte(fmt.Sprintf(\"%v%v%v\\033[m\", foreground(color), background(0xFFFFFF-color), string(buf)))\n}\n\nfunc colorNoop(color int) string {\n\treturn \"\"\n}\n\nfunc colorAnsi16Foreground(color int) string {\n\tcolor = color % 16\n\tindex := color%8 + 30\n\tif color < 8 {\n\t\treturn fmt.Sprintf(\"\\033[%vm\", index)\n\t}\n\treturn fmt.Sprintf(\"\\033[%v;1m\", index)\n}\n\nfunc colorAnsi16Background(color int) string {\n\tcolor = color % 16\n\tindex := color%8 + 40\n\tif color < 8 {\n\t\treturn fmt.Sprintf(\"\\033[%vm\", index)\n\t}\n\treturn fmt.Sprintf(\"\\033[%v;1m\", index)\n}\n\nfunc colorAnsi256Foreground(color int) string {\n\tr, g, b := color>>(16+3), color>>(8+3)&0x1F, color>>3&0x1F\n\treturn fmt.Sprintf(\"\\033[38;5;%vm\", rgbTo216Color(r, g, b)+16)\n}\n\nfunc colorAnsi256Background(color int) string {\n\tr, g, b := color>>(16+3), color>>(8+3)&0x1F, color>>3&0x1F\n\treturn fmt.Sprintf(\"\\033[48;5;%vm\", rgbTo216Color(r, g, b)+16)\n}\n\nfunc rgbFrom216Color(color int) (int, int, int) {\n\treturn color \/ 36, color \/ 6 % 6, color % 6\n}\n\nfunc rgbTo216Color(r, g, b int) int {\n\treturn r*36 + g*6 + b\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build windows\n\npackage overseer\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nvar (\n\tsupported = true\n\tuid       = syscall.Getuid()\n\tgid       = syscall.Getgid()\n\tSIGUSR1   = syscall.SIGTERM\n\tSIGUSR2   = syscall.SIGTERM\n\tSIGTERM   = syscall.SIGTERM\n)\n\nfunc move(dst, src string) error {\n\tos.MkdirAll(filepath.Dir(dst), 0755)\n\tif err := os.Rename(src, dst); err == nil {\n\t\treturn nil\n\t}\n\t\/\/HACK: we're shelling out to move because windows\n\t\/\/throws errors when crossing device boundaryes.\n\t\/\/ https:\/\/www.microsoft.com\/resources\/documentation\/windows\/xp\/all\/proddocs\/en-us\/move.mspx?mfr=true\n\tcmd := exec.Command(\"cmd\", \"\/c\", `move \/y \"`+src+`\" \"`+dst+`\"`)\n\tif b, err := cmd.CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"%v: %q: %v\", cmd.Args, bytes.TrimSpace(b), err)\n\t}\n\treturn nil\n}\n\nfunc chmod(f *os.File, perms os.FileMode) error {\n\tif err := f.Chmod(perms); err != nil && !strings.Contains(err.Error(), \"not supported\") {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc chown(f *os.File, uid, gid int) error {\n\tif err := f.Chown(uid, gid); err != nil && !strings.Contains(err.Error(), \"not supported\") {\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>windows: escape cmd args properly<commit_after>\/\/ +build windows\n\npackage overseer\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"syscall\"\n)\n\nvar (\n\tsupported = true\n\tuid       = syscall.Getuid()\n\tgid       = syscall.Getgid()\n\tSIGUSR1   = syscall.SIGTERM\n\tSIGUSR2   = syscall.SIGTERM\n\tSIGTERM   = syscall.SIGTERM\n)\n\nfunc move(dst, src string) error {\n\tos.MkdirAll(filepath.Dir(dst), 0755)\n\tif err := os.Rename(src, dst); err == nil {\n\t\treturn nil\n\t}\n\t\/\/HACK: we're shelling out to move because windows\n\t\/\/throws errors when crossing device boundaryes.\n\t\/\/ https:\/\/www.microsoft.com\/resources\/documentation\/windows\/xp\/all\/proddocs\/en-us\/move.mspx?mfr=true\n\n\t\/\/ https:\/\/blogs.msdn.microsoft.com\/twistylittlepassagesallalike\/2011\/04\/23\/everyone-quotes-command-line-arguments-the-wrong-way\/\n\tR := func(s string) string { return replShellMeta.Replace(syscall.EscapeArg(s)) }\n\tcmd := exec.Command(\"cmd\", \"\/c\", `move \/y `+R(src)+` `+R(dst))\n\tif b, err := cmd.CombinedOutput(); err != nil {\n\t\treturn fmt.Errorf(\"%v: %q: %v\", cmd.Args, bytes.TrimSpace(b), err)\n\t}\n\treturn nil\n}\n\nfunc chmod(f *os.File, perms os.FileMode) error {\n\tif err := f.Chmod(perms); err != nil && !strings.Contains(err.Error(), \"not supported\") {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc chown(f *os.File, uid, gid int) error {\n\tif err := f.Chown(uid, gid); err != nil && !strings.Contains(err.Error(), \"not supported\") {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ https:\/\/blogs.msdn.microsoft.com\/twistylittlepassagesallalike\/2011\/04\/23\/everyone-quotes-command-line-arguments-the-wrong-way\/\nvar replShellMeta = strings.NewReplacer(\n\t`(`, `^(`,\n\t`)`, `^)`,\n\t`%`, `^%`,\n\t`!`, `^!`,\n\t`^`, `^^`,\n\t`\"`, `^\"`,\n\t`<`, `^<`,\n\t`>`, `^>`,\n\t`&`, `^&`,\n\t`|`, `^|`,\n)\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright (C) 2014 Sebastian 'tokkee' Harl <sh@tokkee.org>\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/    notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/    notice, this list of conditions and the following disclaimer in the\n\/\/    documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n\/\/ TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n\/\/ OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n\/\/ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n\/\/ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n\/\/ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\npackage sysdb\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\/\/ The SysDB JSON time format.\nconst jsonTime = `\"2006-01-02 15:04:05 -0700\"`\n\n\/\/ A Duration represents the elapsed time between two instants as a\n\/\/ nanoseconds count.\n\/\/\n\/\/ It supports marshaling to and unmarshaling from the SysDB JSON format (a\n\/\/ sequence of decimal numbers with a unit suffix).\ntype Duration time.Duration\n\n\/\/ Common durations. All values greater than or equal to a day are not exact\n\/\/ values but subject to daylight savings time changes, leap years, etc. They\n\/\/ are available mostly for providing human readable display formats.\nconst (\n\tSecond = Duration(1000000000)\n\tMinute = 60 * Second\n\tHour   = 60 * Minute\n\tDay    = 24 * Hour\n\tMonth  = Duration(30436875 * 24 * 60 * 60 * 1000)\n\tYear   = Duration(3652425 * 24 * 60 * 60 * 100000)\n)\n\n\/\/ MarshalJSON implements the json.Marshaler interface. The duration is a\n\/\/ quoted string in the SysDB JSON format.\nfunc (d Duration) MarshalJSON() ([]byte, error) {\n\tif d == 0 {\n\t\treturn []byte(`\"0s\"`), nil\n\t}\n\n\ts := `\"`\n\tsecs := false\n\tfor _, spec := range []struct {\n\t\tinterval Duration\n\t\tsuffix   string\n\t}{{Year, \"Y\"}, {Month, \"M\"}, {Day, \"D\"}, {Hour, \"h\"}, {Minute, \"m\"}, {Second, \"\"}} {\n\t\tif d >= spec.interval {\n\t\t\ts += fmt.Sprintf(\"%d%s\", d\/spec.interval, spec.suffix)\n\t\t\td %= spec.interval\n\t\t\tif spec.interval == Second {\n\t\t\t\tsecs = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif d > 0 {\n\t\ts += fmt.Sprintf(\".%09d\", d)\n\t\tfor i := len(s) - 1; i > 0; i-- {\n\t\t\tif s[i] != '0' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ts = s[:i]\n\t\t}\n\t\tsecs = true\n\t}\n\tif secs {\n\t\ts += \"s\"\n\t}\n\ts += `\"`\n\treturn []byte(s), nil\n}\n\n\/\/ UnmarshalJSON implements the json.Unmarshaler interface. The duration is\n\/\/ expected to be a quoted string in the SysDB JSON format.\nfunc (d *Duration) UnmarshalJSON(data []byte) error {\n\tm := map[string]Duration{\n\t\t\"Y\": Year,\n\t\t\"M\": Month,\n\t\t\"D\": Day,\n\t\t\"h\": Hour,\n\t\t\"m\": Minute,\n\t\t\"s\": Second,\n\t}\n\n\tif data[0] != '\"' || data[len(data)-1] != '\"' {\n\t\treturn fmt.Errorf(\"unquoted duration %q\", string(data))\n\t}\n\tdata = data[1 : len(data)-1]\n\n\torig := string(data)\n\tvar res Duration\n\tfor len(data) != 0 {\n\t\t\/\/ consume digits\n\t\tn := 0\n\t\tdec := 0\n\t\tfrac := false\n\t\tfor n < len(data) && '0' <= data[n] && data[n] <= '9' {\n\t\t\tdec = dec*10 + int(data[n]-'0')\n\t\t\tn++\n\t\t}\n\t\tif n < len(data) && data[n] == '.' {\n\t\t\tfrac = true\n\t\t\tn++\n\n\t\t\t\/\/ consume fraction\n\t\t\tm := 1000000000\n\t\t\tfor n < len(data) && '0' <= data[n] && data[n] <= '9' {\n\t\t\t\tif m > 1 { \/\/ cut of to nanoseconds\n\t\t\t\t\tdec = dec*10 + int(data[n]-'0')\n\t\t\t\t\tm \/= 10\n\t\t\t\t}\n\t\t\t\tn++\n\t\t\t}\n\t\t\tdec *= m\n\t\t}\n\t\tif n >= len(data) {\n\t\t\treturn fmt.Errorf(\"missing unit in duration %q\", orig)\n\t\t}\n\t\tif n == 0 {\n\t\t\t\/\/ we found something which is not a number\n\t\t\treturn fmt.Errorf(\"invalid duration %q\", orig)\n\t\t}\n\n\t\t\/\/ consume unit\n\t\tu := n\n\t\tfor u < len(data) && data[u] != '.' && (data[u] < '0' || '9' < data[u]) {\n\t\t\tu++\n\t\t}\n\n\t\tunit := string(data[n:u])\n\t\tdata = data[u:]\n\n\t\t\/\/ convert to Duration\n\t\td, ok := m[unit]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"invalid unit %q in duration %q\", unit, orig)\n\t\t}\n\n\t\tif d == Second {\n\t\t\tif frac {\n\t\t\t\td = 1\n\t\t\t}\n\t\t} else if frac {\n\t\t\treturn fmt.Errorf(\"invalid fraction %q%s in duration %q\", dec, unit, orig)\n\t\t}\n\n\t\tres += Duration(dec) * d\n\t}\n\t*d = res\n\treturn nil\n}\n\n\/\/ String returns the duration formatted using a predefined format string.\nfunc (d Duration) String() string { return time.Duration(d).String() }\n\n\/\/ A Time represents an instant in time with nanosecond precision.\n\/\/\n\/\/ It supports marshaling to and unmarshaling from the SysDB JSON format\n\/\/ (YYYY-MM-DD hh:mm:ss +-zzzz).\ntype Time time.Time\n\n\/\/ MarshalJSON implements the json.Marshaler interface. The time is a quoted\n\/\/ string in the SysDB JSON format.\nfunc (t Time) MarshalJSON() ([]byte, error) {\n\treturn []byte(time.Time(t).Format(jsonTime)), nil\n}\n\n\/\/ UnmarshalJSON implements the json.Unmarshaler interface. The time is\n\/\/ expected to be a quoted string in the SysDB JSON format.\nfunc (t *Time) UnmarshalJSON(data []byte) error {\n\tparsed, err := time.Parse(jsonTime, string(data))\n\tif err == nil {\n\t\t*t = Time(parsed)\n\t}\n\treturn err\n}\n\n\/\/ Equal reports whether t and u represent the same time instant.\nfunc (t Time) Equal(u Time) bool {\n\treturn time.Time(t).Equal(time.Time(u))\n}\n\n\/\/ String returns the time formatted using a predefined format string.\nfunc (t Time) String() string { return time.Time(t).String() }\n\n\/\/ An Attribute describes a host, metric, or service attribute.\ntype Attribute struct {\n\tName           string   `json:\"name\"`\n\tValue          string   `json:\"value\"`\n\tLastUpdate     Time     `json:\"last_update\"`\n\tUpdateInterval Duration `json:\"update_interval\"`\n\tBackends       []string `json:\"backends\"`\n}\n\n\/\/ A Metric describes a metric known to SysDB.\ntype Metric struct {\n\tName           string      `json:\"name\"`\n\tLastUpdate     Time        `json:\"last_update\"`\n\tUpdateInterval Duration    `json:\"update_interval\"`\n\tBackends       []string    `json:\"backends\"`\n\tAttributes     []Attribute `json:\"attributes\"`\n}\n\n\/\/ A Service describes a service object stored in the SysDB store.\ntype Service struct {\n\tName           string      `json:\"name\"`\n\tLastUpdate     Time        `json:\"last_update\"`\n\tUpdateInterval Duration    `json:\"update_interval\"`\n\tBackends       []string    `json:\"backends\"`\n\tAttributes     []Attribute `json:\"attributes\"`\n}\n\n\/\/ A Host describes a host object stored in the SysDB store.\ntype Host struct {\n\tName           string      `json:\"name\"`\n\tLastUpdate     Time        `json:\"last_update\"`\n\tUpdateInterval Duration    `json:\"update_interval\"`\n\tBackends       []string    `json:\"backends\"`\n\tAttributes     []Attribute `json:\"attributes\"`\n\tMetrics        []Metric    `json:\"metrics\"`\n\tServices       []Service   `json:\"services\"`\n}\n\n\/\/ A DataPoint describes a datum at a certain point of time.\ntype DataPoint struct {\n\tTimestamp Time    `json:\"timestamp\"`\n\tValue     float64 `json:\"value,string\"`\n}\n\n\/\/ A Timeseries describes a sequence of data-points.\ntype Timeseries struct {\n\tStart Time                   `json:\"start\"`\n\tEnd   Time                   `json:\"end\"`\n\tData  map[string][]DataPoint `json:\"data\"`\n}\n\n\/\/ vim: set tw=78 sw=4 sw=4 noexpandtab :\n<commit_msg>Parse a metric's \"timeseries\" field.<commit_after>\/\/\n\/\/ Copyright (C) 2014 Sebastian 'tokkee' Harl <sh@tokkee.org>\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/ 1. Redistributions of source code must retain the above copyright\n\/\/    notice, this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright\n\/\/    notice, this list of conditions and the following disclaimer in the\n\/\/    documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n\/\/ TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n\/\/ OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n\/\/ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n\/\/ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n\/\/ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\npackage sysdb\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\n\/\/ The SysDB JSON time format.\nconst jsonTime = `\"2006-01-02 15:04:05 -0700\"`\n\n\/\/ A Duration represents the elapsed time between two instants as a\n\/\/ nanoseconds count.\n\/\/\n\/\/ It supports marshaling to and unmarshaling from the SysDB JSON format (a\n\/\/ sequence of decimal numbers with a unit suffix).\ntype Duration time.Duration\n\n\/\/ Common durations. All values greater than or equal to a day are not exact\n\/\/ values but subject to daylight savings time changes, leap years, etc. They\n\/\/ are available mostly for providing human readable display formats.\nconst (\n\tSecond = Duration(1000000000)\n\tMinute = 60 * Second\n\tHour   = 60 * Minute\n\tDay    = 24 * Hour\n\tMonth  = Duration(30436875 * 24 * 60 * 60 * 1000)\n\tYear   = Duration(3652425 * 24 * 60 * 60 * 100000)\n)\n\n\/\/ MarshalJSON implements the json.Marshaler interface. The duration is a\n\/\/ quoted string in the SysDB JSON format.\nfunc (d Duration) MarshalJSON() ([]byte, error) {\n\tif d == 0 {\n\t\treturn []byte(`\"0s\"`), nil\n\t}\n\n\ts := `\"`\n\tsecs := false\n\tfor _, spec := range []struct {\n\t\tinterval Duration\n\t\tsuffix   string\n\t}{{Year, \"Y\"}, {Month, \"M\"}, {Day, \"D\"}, {Hour, \"h\"}, {Minute, \"m\"}, {Second, \"\"}} {\n\t\tif d >= spec.interval {\n\t\t\ts += fmt.Sprintf(\"%d%s\", d\/spec.interval, spec.suffix)\n\t\t\td %= spec.interval\n\t\t\tif spec.interval == Second {\n\t\t\t\tsecs = true\n\t\t\t}\n\t\t}\n\t}\n\n\tif d > 0 {\n\t\ts += fmt.Sprintf(\".%09d\", d)\n\t\tfor i := len(s) - 1; i > 0; i-- {\n\t\t\tif s[i] != '0' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ts = s[:i]\n\t\t}\n\t\tsecs = true\n\t}\n\tif secs {\n\t\ts += \"s\"\n\t}\n\ts += `\"`\n\treturn []byte(s), nil\n}\n\n\/\/ UnmarshalJSON implements the json.Unmarshaler interface. The duration is\n\/\/ expected to be a quoted string in the SysDB JSON format.\nfunc (d *Duration) UnmarshalJSON(data []byte) error {\n\tm := map[string]Duration{\n\t\t\"Y\": Year,\n\t\t\"M\": Month,\n\t\t\"D\": Day,\n\t\t\"h\": Hour,\n\t\t\"m\": Minute,\n\t\t\"s\": Second,\n\t}\n\n\tif data[0] != '\"' || data[len(data)-1] != '\"' {\n\t\treturn fmt.Errorf(\"unquoted duration %q\", string(data))\n\t}\n\tdata = data[1 : len(data)-1]\n\n\torig := string(data)\n\tvar res Duration\n\tfor len(data) != 0 {\n\t\t\/\/ consume digits\n\t\tn := 0\n\t\tdec := 0\n\t\tfrac := false\n\t\tfor n < len(data) && '0' <= data[n] && data[n] <= '9' {\n\t\t\tdec = dec*10 + int(data[n]-'0')\n\t\t\tn++\n\t\t}\n\t\tif n < len(data) && data[n] == '.' {\n\t\t\tfrac = true\n\t\t\tn++\n\n\t\t\t\/\/ consume fraction\n\t\t\tm := 1000000000\n\t\t\tfor n < len(data) && '0' <= data[n] && data[n] <= '9' {\n\t\t\t\tif m > 1 { \/\/ cut of to nanoseconds\n\t\t\t\t\tdec = dec*10 + int(data[n]-'0')\n\t\t\t\t\tm \/= 10\n\t\t\t\t}\n\t\t\t\tn++\n\t\t\t}\n\t\t\tdec *= m\n\t\t}\n\t\tif n >= len(data) {\n\t\t\treturn fmt.Errorf(\"missing unit in duration %q\", orig)\n\t\t}\n\t\tif n == 0 {\n\t\t\t\/\/ we found something which is not a number\n\t\t\treturn fmt.Errorf(\"invalid duration %q\", orig)\n\t\t}\n\n\t\t\/\/ consume unit\n\t\tu := n\n\t\tfor u < len(data) && data[u] != '.' && (data[u] < '0' || '9' < data[u]) {\n\t\t\tu++\n\t\t}\n\n\t\tunit := string(data[n:u])\n\t\tdata = data[u:]\n\n\t\t\/\/ convert to Duration\n\t\td, ok := m[unit]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"invalid unit %q in duration %q\", unit, orig)\n\t\t}\n\n\t\tif d == Second {\n\t\t\tif frac {\n\t\t\t\td = 1\n\t\t\t}\n\t\t} else if frac {\n\t\t\treturn fmt.Errorf(\"invalid fraction %q%s in duration %q\", dec, unit, orig)\n\t\t}\n\n\t\tres += Duration(dec) * d\n\t}\n\t*d = res\n\treturn nil\n}\n\n\/\/ String returns the duration formatted using a predefined format string.\nfunc (d Duration) String() string { return time.Duration(d).String() }\n\n\/\/ A Time represents an instant in time with nanosecond precision.\n\/\/\n\/\/ It supports marshaling to and unmarshaling from the SysDB JSON format\n\/\/ (YYYY-MM-DD hh:mm:ss +-zzzz).\ntype Time time.Time\n\n\/\/ MarshalJSON implements the json.Marshaler interface. The time is a quoted\n\/\/ string in the SysDB JSON format.\nfunc (t Time) MarshalJSON() ([]byte, error) {\n\treturn []byte(time.Time(t).Format(jsonTime)), nil\n}\n\n\/\/ UnmarshalJSON implements the json.Unmarshaler interface. The time is\n\/\/ expected to be a quoted string in the SysDB JSON format.\nfunc (t *Time) UnmarshalJSON(data []byte) error {\n\tparsed, err := time.Parse(jsonTime, string(data))\n\tif err == nil {\n\t\t*t = Time(parsed)\n\t}\n\treturn err\n}\n\n\/\/ Equal reports whether t and u represent the same time instant.\nfunc (t Time) Equal(u Time) bool {\n\treturn time.Time(t).Equal(time.Time(u))\n}\n\n\/\/ String returns the time formatted using a predefined format string.\nfunc (t Time) String() string { return time.Time(t).String() }\n\n\/\/ An Attribute describes a host, metric, or service attribute.\ntype Attribute struct {\n\tName           string   `json:\"name\"`\n\tValue          string   `json:\"value\"`\n\tLastUpdate     Time     `json:\"last_update\"`\n\tUpdateInterval Duration `json:\"update_interval\"`\n\tBackends       []string `json:\"backends\"`\n}\n\n\/\/ A Metric describes a metric known to SysDB.\ntype Metric struct {\n\tName           string      `json:\"name\"`\n\tTimeseries     bool        `json:\"timeseries\"`\n\tLastUpdate     Time        `json:\"last_update\"`\n\tUpdateInterval Duration    `json:\"update_interval\"`\n\tBackends       []string    `json:\"backends\"`\n\tAttributes     []Attribute `json:\"attributes\"`\n}\n\n\/\/ A Service describes a service object stored in the SysDB store.\ntype Service struct {\n\tName           string      `json:\"name\"`\n\tLastUpdate     Time        `json:\"last_update\"`\n\tUpdateInterval Duration    `json:\"update_interval\"`\n\tBackends       []string    `json:\"backends\"`\n\tAttributes     []Attribute `json:\"attributes\"`\n}\n\n\/\/ A Host describes a host object stored in the SysDB store.\ntype Host struct {\n\tName           string      `json:\"name\"`\n\tLastUpdate     Time        `json:\"last_update\"`\n\tUpdateInterval Duration    `json:\"update_interval\"`\n\tBackends       []string    `json:\"backends\"`\n\tAttributes     []Attribute `json:\"attributes\"`\n\tMetrics        []Metric    `json:\"metrics\"`\n\tServices       []Service   `json:\"services\"`\n}\n\n\/\/ A DataPoint describes a datum at a certain point of time.\ntype DataPoint struct {\n\tTimestamp Time    `json:\"timestamp\"`\n\tValue     float64 `json:\"value,string\"`\n}\n\n\/\/ A Timeseries describes a sequence of data-points.\ntype Timeseries struct {\n\tStart Time                   `json:\"start\"`\n\tEnd   Time                   `json:\"end\"`\n\tData  map[string][]DataPoint `json:\"data\"`\n}\n\n\/\/ vim: set tw=78 sw=4 sw=4 noexpandtab :\n<|endoftext|>"}
{"text":"<commit_before>package system\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/ready-steady\/format\/tgff\"\n)\n\nfunc loadTGFF(path string) (*Platform, *Application, error) {\n\tresult, err := tgff.ParseFile(path)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tplatform, err := loadPlatform(result.Tables)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tapplication, err := loadApplication(result.Graphs)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn platform, application, nil\n}\n\nfunc loadPlatform(tables []tgff.Table) (*Platform, error) {\n\tsize := uint(len(tables))\n\n\tif size == 0 {\n\t\treturn nil, errors.New(\"need at least one table\")\n\t}\n\n\tplatform := &Platform{\n\t\tCores: make([]Core, size),\n\t}\n\n\tvar err error\n\n\tfor _, table := range tables {\n\t\ti := table.ID\n\n\t\tif i >= size {\n\t\t\treturn nil, errors.New(\"encountered an unknown table indexing scheme\")\n\t\t}\n\n\t\tplatform.Cores[i], err = loadCore(table)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\trows := len(platform.Cores[0].Time)\n\n\tfor i := uint(1); i < size; i++ {\n\t\tif rows != len(platform.Cores[i].Time) {\n\t\t\treturn nil, errors.New(\"the table data are inconsistent\")\n\t\t}\n\t}\n\n\treturn platform, nil\n}\n\nfunc loadApplication(graphs []tgff.Graph) (*Application, error) {\n\tif len(graphs) != 1 {\n\t\treturn nil, errors.New(\"need exactly one task graph\")\n\t}\n\n\tsize := uint(len(graphs[0].Tasks))\n\n\tapplication := &Application{\n\t\tTasks: make([]Task, size),\n\t}\n\n\tfor _, task := range graphs[0].Tasks {\n\t\ti, err := extractTaskID(task.Name, size)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tapplication.Tasks[i].ID = i\n\t\tapplication.Tasks[i].Type = task.Type\n\t}\n\n\tfor _, arc := range graphs[0].Arcs {\n\t\ti, err := extractTaskID(arc.From, size)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tj, err := extractTaskID(arc.To, size)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tapplication.Tasks[i].Children = append(application.Tasks[i].Children, j)\n\t\tapplication.Tasks[j].Parents = append(application.Tasks[j].Parents, i)\n\t}\n\n\treturn application, nil\n}\n\nfunc loadCore(table tgff.Table) (Core, error) {\n\tcore := Core{\n\t\tID: table.ID,\n\t}\n\n\tvar tycol, tmcol, pwcol *tgff.Column\n\n\tfor i := range table.Columns {\n\t\tcol := &table.Columns[i]\n\n\t\tname := strings.ToLower(col.Name)\n\n\t\tif strings.Index(name, \"type\") >= 0 {\n\t\t\ttycol = col\n\t\t} else if strings.Index(name, \"time\") >= 0 {\n\t\t\ttmcol = col\n\t\t} else if strings.Index(name, \"power\") >= 0 {\n\t\t\tpwcol = col\n\t\t}\n\n\t\tif tycol != nil && tmcol != nil && pwcol != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif tycol == nil || tmcol == nil || pwcol == nil {\n\t\treturn core, errors.New(\"need columns named type, time, and power\")\n\t}\n\n\tsize := len(tycol.Data)\n\n\tfor i := 0; i < size; i++ {\n\t\tif int(tycol.Data[i]) != i {\n\t\t\treturn core, errors.New(\"data should be sorted by type\")\n\t\t}\n\t}\n\n\tcore.Time = make([]float64, size)\n\tcopy(core.Time, tmcol.Data)\n\n\tcore.Power = make([]float64, size)\n\tcopy(core.Power, pwcol.Data)\n\n\treturn core, nil\n}\n\nfunc extractTaskID(name string, total uint) (uint, error) {\n\tif !strings.HasPrefix(name, \"t0_\") {\n\t\treturn 0, errors.New(\"encountered an unknown task naming scheme\")\n\t}\n\n\tid, err := strconv.ParseUint(name[3:], 10, 0)\n\tif err != nil || id < 0 || uint(id) >= total {\n\t\treturn 0, errors.New(\"encountered an unknown task indexing scheme\")\n\t}\n\n\treturn uint(id), nil\n}\n<commit_msg>system: fix the path to tgff<commit_after>package system\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/ready-steady\/tgff\"\n)\n\nfunc loadTGFF(path string) (*Platform, *Application, error) {\n\tresult, err := tgff.ParseFile(path)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tplatform, err := loadPlatform(result.Tables)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tapplication, err := loadApplication(result.Graphs)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treturn platform, application, nil\n}\n\nfunc loadPlatform(tables []tgff.Table) (*Platform, error) {\n\tsize := uint(len(tables))\n\n\tif size == 0 {\n\t\treturn nil, errors.New(\"need at least one table\")\n\t}\n\n\tplatform := &Platform{\n\t\tCores: make([]Core, size),\n\t}\n\n\tvar err error\n\n\tfor _, table := range tables {\n\t\ti := table.ID\n\n\t\tif i >= size {\n\t\t\treturn nil, errors.New(\"encountered an unknown table indexing scheme\")\n\t\t}\n\n\t\tplatform.Cores[i], err = loadCore(table)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\trows := len(platform.Cores[0].Time)\n\n\tfor i := uint(1); i < size; i++ {\n\t\tif rows != len(platform.Cores[i].Time) {\n\t\t\treturn nil, errors.New(\"the table data are inconsistent\")\n\t\t}\n\t}\n\n\treturn platform, nil\n}\n\nfunc loadApplication(graphs []tgff.Graph) (*Application, error) {\n\tif len(graphs) != 1 {\n\t\treturn nil, errors.New(\"need exactly one task graph\")\n\t}\n\n\tsize := uint(len(graphs[0].Tasks))\n\n\tapplication := &Application{\n\t\tTasks: make([]Task, size),\n\t}\n\n\tfor _, task := range graphs[0].Tasks {\n\t\ti, err := extractTaskID(task.Name, size)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tapplication.Tasks[i].ID = i\n\t\tapplication.Tasks[i].Type = task.Type\n\t}\n\n\tfor _, arc := range graphs[0].Arcs {\n\t\ti, err := extractTaskID(arc.From, size)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tj, err := extractTaskID(arc.To, size)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tapplication.Tasks[i].Children = append(application.Tasks[i].Children, j)\n\t\tapplication.Tasks[j].Parents = append(application.Tasks[j].Parents, i)\n\t}\n\n\treturn application, nil\n}\n\nfunc loadCore(table tgff.Table) (Core, error) {\n\tcore := Core{\n\t\tID: table.ID,\n\t}\n\n\tvar tycol, tmcol, pwcol *tgff.Column\n\n\tfor i := range table.Columns {\n\t\tcol := &table.Columns[i]\n\n\t\tname := strings.ToLower(col.Name)\n\n\t\tif strings.Index(name, \"type\") >= 0 {\n\t\t\ttycol = col\n\t\t} else if strings.Index(name, \"time\") >= 0 {\n\t\t\ttmcol = col\n\t\t} else if strings.Index(name, \"power\") >= 0 {\n\t\t\tpwcol = col\n\t\t}\n\n\t\tif tycol != nil && tmcol != nil && pwcol != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif tycol == nil || tmcol == nil || pwcol == nil {\n\t\treturn core, errors.New(\"need columns named type, time, and power\")\n\t}\n\n\tsize := len(tycol.Data)\n\n\tfor i := 0; i < size; i++ {\n\t\tif int(tycol.Data[i]) != i {\n\t\t\treturn core, errors.New(\"data should be sorted by type\")\n\t\t}\n\t}\n\n\tcore.Time = make([]float64, size)\n\tcopy(core.Time, tmcol.Data)\n\n\tcore.Power = make([]float64, size)\n\tcopy(core.Power, pwcol.Data)\n\n\treturn core, nil\n}\n\nfunc extractTaskID(name string, total uint) (uint, error) {\n\tif !strings.HasPrefix(name, \"t0_\") {\n\t\treturn 0, errors.New(\"encountered an unknown task naming scheme\")\n\t}\n\n\tid, err := strconv.ParseUint(name[3:], 10, 0)\n\tif err != nil || id < 0 || uint(id) >= total {\n\t\treturn 0, errors.New(\"encountered an unknown task indexing scheme\")\n\t}\n\n\treturn uint(id), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package taipei\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst MAX_OUR_REQUESTS = 2\nconst MAX_PEER_REQUESTS = 10\nconst STANDARD_BLOCK_LENGTH = 16 * 1024\n\ntype peerMessage struct {\n\tpeer    *peerState\n\tmessage []byte \/\/ nil means an error occurred\n}\n\ntype peerState struct {\n\taddress         string\n\tid              string\n\twriteChan       chan []byte\n\twriteChan2      chan []byte\n\tlastWriteTime   time.Time\n\tlastReadTime    time.Time\n\thave            *Bitset \/\/ What the peer has told us it has\n\tconn            net.Conn\n\tam_choking      bool \/\/ this client is choking the peer\n\tam_interested   bool \/\/ this client is interested in the peer\n\tpeer_choking    bool \/\/ peer is choking this client\n\tpeer_interested bool \/\/ peer is interested in this client\n\tpeer_requests   map[uint64]bool\n\tour_requests    map[uint64]time.Time \/\/ What we requested, when we requested it\n\tend             sync.Once\n}\n\nfunc queueingWriter(in, out chan []byte) {\n\tqueue := make(map[int][]byte)\n\thead, tail := 0, 0\nL:\n\tfor {\n\t\tif head == tail {\n\t\t\tselect {\n\t\t\tcase m, ok := <-in:\n\t\t\t\tif !ok {\n\t\t\t\t\tbreak L\n\t\t\t\t}\n\t\t\t\tqueue[head] = m\n\t\t\t\thead++\n\t\t\t}\n\t\t} else {\n\t\t\tselect {\n\t\t\tcase m, ok := <-in:\n\t\t\t\tif !ok {\n\t\t\t\t\tbreak L\n\t\t\t\t}\n\t\t\t\tqueue[head] = m\n\t\t\t\thead++\n\t\t\tcase out <- queue[tail]:\n\t\t\t\tdelete(queue, tail)\n\t\t\t\ttail++\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ We throw away any messages waiting to be sent, including the\n\t\/\/ nil message that is automatically sent when the in channel is closed\n\tclose(out)\n}\n\nfunc NewPeerState(conn net.Conn) *peerState {\n\twriteChan := make(chan []byte)\n\twriteChan2 := make(chan []byte)\n\tgo queueingWriter(writeChan, writeChan2)\n\treturn &peerState{writeChan: writeChan, writeChan2: writeChan2, conn: conn,\n\t\tam_choking: true, peer_choking: true,\n\t\tpeer_requests: make(map[uint64]bool, MAX_PEER_REQUESTS),\n\t\tour_requests:  make(map[uint64]time.Time, MAX_OUR_REQUESTS)}\n}\n\nfunc (p *peerState) Close() {\n\tp.end.Do(func() {\n\t\tp.conn.Close()\n\t\tclose(p.writeChan)\n\t})\n}\n\nfunc (p *peerState) AddRequest(index, begin, length uint32) {\n\tif !p.am_choking && len(p.peer_requests) < MAX_PEER_REQUESTS {\n\t\toffset := (uint64(index) << 32) | uint64(begin)\n\t\tp.peer_requests[offset] = true\n\t}\n}\n\nfunc (p *peerState) CancelRequest(index, begin, length uint32) {\n\toffset := (uint64(index) << 32) | uint64(begin)\n\tif _, ok := p.peer_requests[offset]; ok {\n\t\tdelete(p.peer_requests, offset)\n\t}\n}\n\nfunc (p *peerState) RemoveRequest() (index, begin, length uint32, ok bool) {\n\tfor k, _ := range p.peer_requests {\n\t\tindex, begin = uint32(k>>32), uint32(k)\n\t\tlength = STANDARD_BLOCK_LENGTH\n\t\tok = true\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (p *peerState) SetChoke(choke bool) {\n\tif choke != p.am_choking {\n\t\tp.am_choking = choke\n\t\tb := byte(1)\n\t\tif choke {\n\t\t\tb = 0\n\t\t\tp.peer_requests = make(map[uint64]bool, MAX_PEER_REQUESTS)\n\t\t}\n\t\tp.sendOneCharMessage(b)\n\t}\n}\n\nfunc (p *peerState) SetInterested(interested bool) {\n\tif interested != p.am_interested {\n\t\t\/\/ log.Println(\"SetInterested\", interested, p.address)\n\t\tp.am_interested = interested\n\t\tb := byte(3)\n\t\tif interested {\n\t\t\tb = 2\n\t\t}\n\t\tp.sendOneCharMessage(b)\n\t}\n}\n\nfunc (p *peerState) sendOneCharMessage(b byte) {\n\t\/\/ log.Println(\"ocm\", b, p.address)\n\tp.sendMessage([]byte{b})\n}\n\nfunc (p *peerState) sendMessage(b []byte) {\n\tp.writeChan <- b\n\tp.lastWriteTime = time.Now()\n}\n\nfunc (p *peerState) keepAlive(now time.Time) {\n\tif now.Sub(p.lastWriteTime) >= 2*time.Minute {\n\t\t\/\/ log.Stderr(\"Sending keep alive\", p)\n\t\tp.sendMessage([]byte{})\n\t}\n}\n\n\/\/ There's two goroutines per peer, one to read data from the peer, the other to\n\/\/ send data to the peer.\n\nfunc uint32ToBytes(buf []byte, n uint32) {\n\tbuf[0] = byte(n >> 24)\n\tbuf[1] = byte(n >> 16)\n\tbuf[2] = byte(n >> 8)\n\tbuf[3] = byte(n)\n}\n\nfunc writeNBOUint32(conn net.Conn, n uint32) (err error) {\n\tvar buf []byte = make([]byte, 4)\n\tuint32ToBytes(buf, n)\n\t_, err = conn.Write(buf[0:])\n\treturn\n}\n\nfunc bytesToUint32(buf []byte) uint32 {\n\treturn (uint32(buf[0]) << 24) |\n\t\t(uint32(buf[1]) << 16) |\n\t\t(uint32(buf[2]) << 8) | uint32(buf[3])\n}\n\nfunc readNBOUint32(conn net.Conn) (n uint32, err error) {\n\tvar buf [4]byte\n\t_, err = conn.Read(buf[0:])\n\tif err != nil {\n\t\treturn\n\t}\n\tn = bytesToUint32(buf[0:])\n\treturn\n}\n\n\/\/ This func is designed to be run as a goroutine. It\n\/\/ listens for messages on a channel and sends them to a peer.\n\nfunc (p *peerState) peerWriter(errorChan chan peerMessage, header []byte) {\n\t\/\/ log.Println(\"Writing header.\")\n\t_, err := p.conn.Write(header)\n\tif err != nil {\n\t\tgoto exit\n\t}\n\t\/\/ log.Println(\"Writing messages\")\n\tfor msg := range p.writeChan2 {\n\t\t\/\/ log.Println(\"Writing\", len(msg), conn.RemoteAddr())\n\t\terr = writeNBOUint32(p.conn, uint32(len(msg)))\n\t\tif err != nil {\n\t\t\tgoto exit\n\t\t}\n\t\t_, err = p.conn.Write(msg)\n\t\tif err != nil {\n\t\t\t\/\/ log.Println(\"Failed to write a message\", p.address, len(msg), msg, err)\n\t\t\tgoto exit\n\t\t}\n\t}\nexit:\n\t\/\/ log.Println(\"peerWriter exiting\")\n\terrorChan <- peerMessage{p, nil}\n}\n\n\/\/ This func is designed to be run as a goroutine. It\n\/\/ listens for messages from the peer and forwards them to a channel.\n\nfunc (p *peerState) peerReader(msgChan chan peerMessage) {\n\t\/\/ log.Println(\"Reading header.\")\n\tvar header [68]byte\n\t_, err := p.conn.Read(header[0:1])\n\tif err != nil {\n\t\tgoto exit\n\t}\n\tif header[0] != 19 {\n\t\tgoto exit\n\t}\n\t_, err = p.conn.Read(header[1:20])\n\tif err != nil {\n\t\tgoto exit\n\t}\n\tif string(header[1:20]) != \"BitTorrent protocol\" {\n\t\tgoto exit\n\t}\n\t\/\/ Read rest of header\n\t_, err = p.conn.Read(header[20:])\n\tif err != nil {\n\t\tgoto exit\n\t}\n\tmsgChan <- peerMessage{p, header[20:]}\n\t\/\/ log.Println(\"Reading messages\")\n\tfor {\n\t\tvar n uint32\n\t\tn, err = readNBOUint32(p.conn)\n\t\tif err != nil {\n\t\t\tgoto exit\n\t\t}\n\t\tif n > 130*1024 {\n\t\t\t\/\/ log.Println(\"Message size too large: \", n)\n\t\t\tgoto exit\n\t\t}\n\t\tbuf := make([]byte, n)\n\t\t_, err = io.ReadFull(p.conn, buf)\n\t\tif err != nil {\n\t\t\tgoto exit\n\t\t}\n\t\tmsgChan <- peerMessage{p, buf}\n\t}\n\nexit:\n\tmsgChan <- peerMessage{p, nil}\n\t\/\/ log.Println(\"peerReader exiting\")\n}\n<commit_msg>dont close channels. Just throw away any messages that cames after a peer connection is closed<commit_after>package taipei\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"time\"\n)\n\nconst MAX_OUR_REQUESTS = 2\nconst MAX_PEER_REQUESTS = 10\nconst STANDARD_BLOCK_LENGTH = 16 * 1024\n\ntype peerMessage struct {\n\tpeer    *peerState\n\tmessage []byte \/\/ nil means an error occurred\n}\n\ntype peerState struct {\n\taddress         string\n\tid              string\n\twriteChan       chan []byte\n\twriteChan2      chan []byte\n\tlastWriteTime   time.Time\n\tlastReadTime    time.Time\n\thave            *Bitset \/\/ What the peer has told us it has\n\tconn            net.Conn\n\tam_choking      bool \/\/ this client is choking the peer\n\tam_interested   bool \/\/ this client is interested in the peer\n\tpeer_choking    bool \/\/ peer is choking this client\n\tpeer_interested bool \/\/ peer is interested in this client\n\tpeer_requests   map[uint64]bool\n\tour_requests    map[uint64]time.Time \/\/ What we requested, when we requested it\n}\n\nfunc queueingWriter(in, out chan []byte) {\n\tqueue := make(map[int][]byte)\n\thead, tail := 0, 0\nL:\n\tfor {\n\t\tif head == tail {\n\t\t\tselect {\n\t\t\tcase m, ok := <-in:\n\t\t\t\tif !ok {\n\t\t\t\t\tbreak L\n\t\t\t\t}\n\t\t\t\tqueue[head] = m\n\t\t\t\thead++\n\t\t\t}\n\t\t} else {\n\t\t\tselect {\n\t\t\tcase m, ok := <-in:\n\t\t\t\tif !ok {\n\t\t\t\t\tbreak L\n\t\t\t\t}\n\t\t\t\tqueue[head] = m\n\t\t\t\thead++\n\t\t\tcase out <- queue[tail]:\n\t\t\t\tdelete(queue, tail)\n\t\t\t\ttail++\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ We throw away any messages waiting to be sent, including the\n\t\/\/ nil message that is automatically sent when the in channel is closed\n\t\/\/ close(out) \/\/ No need to close channel.\n}\n\nfunc NewPeerState(conn net.Conn) *peerState {\n\twriteChan := make(chan []byte)\n\twriteChan2 := make(chan []byte)\n\tgo queueingWriter(writeChan, writeChan2)\n\treturn &peerState{writeChan: writeChan, writeChan2: writeChan2, conn: conn,\n\t\tam_choking: true, peer_choking: true,\n\t\tpeer_requests: make(map[uint64]bool, MAX_PEER_REQUESTS),\n\t\tour_requests:  make(map[uint64]time.Time, MAX_OUR_REQUESTS)}\n}\n\nfunc (p *peerState) Close() {\n\tp.conn.Close()\n\t\/\/ No need to close p.writeChan. Further writes to p.conn will just fail.\n}\n\nfunc (p *peerState) AddRequest(index, begin, length uint32) {\n\tif !p.am_choking && len(p.peer_requests) < MAX_PEER_REQUESTS {\n\t\toffset := (uint64(index) << 32) | uint64(begin)\n\t\tp.peer_requests[offset] = true\n\t}\n}\n\nfunc (p *peerState) CancelRequest(index, begin, length uint32) {\n\toffset := (uint64(index) << 32) | uint64(begin)\n\tif _, ok := p.peer_requests[offset]; ok {\n\t\tdelete(p.peer_requests, offset)\n\t}\n}\n\nfunc (p *peerState) RemoveRequest() (index, begin, length uint32, ok bool) {\n\tfor k, _ := range p.peer_requests {\n\t\tindex, begin = uint32(k>>32), uint32(k)\n\t\tlength = STANDARD_BLOCK_LENGTH\n\t\tok = true\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (p *peerState) SetChoke(choke bool) {\n\tif choke != p.am_choking {\n\t\tp.am_choking = choke\n\t\tb := byte(1)\n\t\tif choke {\n\t\t\tb = 0\n\t\t\tp.peer_requests = make(map[uint64]bool, MAX_PEER_REQUESTS)\n\t\t}\n\t\tp.sendOneCharMessage(b)\n\t}\n}\n\nfunc (p *peerState) SetInterested(interested bool) {\n\tif interested != p.am_interested {\n\t\t\/\/ log.Println(\"SetInterested\", interested, p.address)\n\t\tp.am_interested = interested\n\t\tb := byte(3)\n\t\tif interested {\n\t\t\tb = 2\n\t\t}\n\t\tp.sendOneCharMessage(b)\n\t}\n}\n\nfunc (p *peerState) sendOneCharMessage(b byte) {\n\t\/\/ log.Println(\"ocm\", b, p.address)\n\tp.sendMessage([]byte{b})\n}\n\nfunc (p *peerState) sendMessage(b []byte) {\n\tp.writeChan <- b\n\tp.lastWriteTime = time.Now()\n}\n\nfunc (p *peerState) keepAlive(now time.Time) {\n\tif now.Sub(p.lastWriteTime) >= 2*time.Minute {\n\t\t\/\/ log.Stderr(\"Sending keep alive\", p)\n\t\tp.sendMessage([]byte{})\n\t}\n}\n\n\/\/ There's two goroutines per peer, one to read data from the peer, the other to\n\/\/ send data to the peer.\n\nfunc uint32ToBytes(buf []byte, n uint32) {\n\tbuf[0] = byte(n >> 24)\n\tbuf[1] = byte(n >> 16)\n\tbuf[2] = byte(n >> 8)\n\tbuf[3] = byte(n)\n}\n\nfunc writeNBOUint32(conn net.Conn, n uint32) (err error) {\n\tvar buf []byte = make([]byte, 4)\n\tuint32ToBytes(buf, n)\n\t_, err = conn.Write(buf[0:])\n\treturn\n}\n\nfunc bytesToUint32(buf []byte) uint32 {\n\treturn (uint32(buf[0]) << 24) |\n\t\t(uint32(buf[1]) << 16) |\n\t\t(uint32(buf[2]) << 8) | uint32(buf[3])\n}\n\nfunc readNBOUint32(conn net.Conn) (n uint32, err error) {\n\tvar buf [4]byte\n\t_, err = conn.Read(buf[0:])\n\tif err != nil {\n\t\treturn\n\t}\n\tn = bytesToUint32(buf[0:])\n\treturn\n}\n\n\/\/ This func is designed to be run as a goroutine. It\n\/\/ listens for messages on a channel and sends them to a peer.\n\nfunc (p *peerState) peerWriter(errorChan chan peerMessage, header []byte) {\n\t\/\/ log.Println(\"Writing header.\")\n\t_, err := p.conn.Write(header)\n\tif err != nil {\n\t\tgoto exit\n\t}\n\t\/\/ log.Println(\"Writing messages\")\n\tfor msg := range p.writeChan2 {\n\t\t\/\/ log.Println(\"Writing\", len(msg), conn.RemoteAddr())\n\t\terr = writeNBOUint32(p.conn, uint32(len(msg)))\n\t\tif err != nil {\n\t\t\tgoto exit\n\t\t}\n\t\t_, err = p.conn.Write(msg)\n\t\tif err != nil {\n\t\t\t\/\/ log.Println(\"Failed to write a message\", p.address, len(msg), msg, err)\n\t\t\tgoto exit\n\t\t}\n\t}\nexit:\n\t\/\/ log.Println(\"peerWriter exiting\")\n\terrorChan <- peerMessage{p, nil}\n}\n\n\/\/ This func is designed to be run as a goroutine. It\n\/\/ listens for messages from the peer and forwards them to a channel.\n\nfunc (p *peerState) peerReader(msgChan chan peerMessage) {\n\t\/\/ log.Println(\"Reading header.\")\n\tvar header [68]byte\n\t_, err := p.conn.Read(header[0:1])\n\tif err != nil {\n\t\tgoto exit\n\t}\n\tif header[0] != 19 {\n\t\tgoto exit\n\t}\n\t_, err = p.conn.Read(header[1:20])\n\tif err != nil {\n\t\tgoto exit\n\t}\n\tif string(header[1:20]) != \"BitTorrent protocol\" {\n\t\tgoto exit\n\t}\n\t\/\/ Read rest of header\n\t_, err = p.conn.Read(header[20:])\n\tif err != nil {\n\t\tgoto exit\n\t}\n\tmsgChan <- peerMessage{p, header[20:]}\n\t\/\/ log.Println(\"Reading messages\")\n\tfor {\n\t\tvar n uint32\n\t\tn, err = readNBOUint32(p.conn)\n\t\tif err != nil {\n\t\t\tgoto exit\n\t\t}\n\t\tif n > 130*1024 {\n\t\t\t\/\/ log.Println(\"Message size too large: \", n)\n\t\t\tgoto exit\n\t\t}\n\t\tbuf := make([]byte, n)\n\t\t_, err = io.ReadFull(p.conn, buf)\n\t\tif err != nil {\n\t\t\tgoto exit\n\t\t}\n\t\tmsgChan <- peerMessage{p, buf}\n\t}\n\nexit:\n\tmsgChan <- peerMessage{p, nil}\n\t\/\/ log.Println(\"peerReader exiting\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package rehttp implements an HTTP transport that handles retries.\n\/\/\n\/\/ An HTTP Client can be created with a *rehttp.Transport as RoundTripper\n\/\/ and it will apply the retry strategy to its requests, e.g.:\n\/\/\n\/\/     tr, err := rehttp.NewTransport(\n\/\/         nil,                            \/\/ will use http.DefaultTransport\n\/\/         rehttp.RetryTemporaryErr(3),    \/\/ max 3 retries for Temporary errors\n\/\/         rehttp.ConstDelay(time.Second), \/\/ wait 1s between retries\n\/\/     )\n\/\/     if err != nil {\n\/\/         \/\/ handle err\n\/\/     }\n\/\/     client := &http.Client{\n\/\/         Transport: tr,\n\/\/         Timeout: 30 * time.Second, \/\/ timeout applies to all retries as a whole\n\/\/     }\n\/\/\n\/\/ The retry strategy is provided by the Transport, which holds\n\/\/ a function that returns whether or not the request should be retried,\n\/\/ and if so, what delay to apply before retrying, based on the ShouldRetryFn\n\/\/ and DelayFn functions passed to NewTransport.\n\/\/\n\/\/ The package offers common delay strategies as ready-made functions that\n\/\/ return a DelayFn:\n\/\/     - ConstDelay(delay time.Duration) DelayFn\n\/\/     - ExponentialDelay(base, max time.Duration) DelayFn\n\/\/\n\/\/ It also provides common retry predicates that return a ShouldRetryFn:\n\/\/     - RetryTemporaryErr(maxRetries int) ShouldRetryFn\n\/\/     - RetryStatus500(maxRetries int) ShouldRetryFn\n\/\/     - RetryHTTPMethods(maxRetries int, methods ...string) ShouldRetryFn\n\/\/\n\/\/ Those can be combined with RetryAny or RetryAll as needed. RetryAny\n\/\/ enables retries if any of the ShouldRetryFn return true, while RetryAll\n\/\/ enables retries if all ShouldRetryFn return true.\n\/\/\n\/\/ The Transport will buffer the request's body in order to be able to\n\/\/ retry the request, as a request attempt will consume and close the\n\/\/ existing body. Sometimes this is not desirable, so it can be prevented\n\/\/ by setting PreventRetryWithBody to true on the Transport. Doing so\n\/\/ will disable retries when a request has a non-nil body.\n\/\/\npackage rehttp\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ PRNG is the *math.Rand value to use to add jitter to the backoff\n\/\/ algorithm used in ExponentialDelay. By default it uses a *math.Rand\n\/\/ initialized with a source based on the current time in nanoseconds.\nvar PRNG = rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\/\/ terribly named interface to detect errors that support Temporary.\ntype temporaryer interface {\n\tTemporary() bool\n}\n\n\/\/ CancelRoundTripper is a RoundTripper that supports CancelRequest.\n\/\/ The *http.Transport type implements this interface.\ntype CancelRoundTripper interface {\n\thttp.RoundTripper\n\tCancelRequest(*http.Request)\n}\n\n\/\/ Attempt holds the data for a RoundTrip attempt.\ntype Attempt struct {\n\t\/\/ Index is the attempt index starting at 0.\n\tIndex int\n\n\t\/\/ Request is the request for this attempt. If a non-nil Response\n\t\/\/ is present, this is the same as Response.Request, but since a\n\t\/\/ Response may not be available, it is guaranteed to be set on this\n\t\/\/ field.\n\tRequest *http.Request\n\n\t\/\/ Response is the response for this attempt. It may be nil if an\n\t\/\/ error occurred an no response was received.\n\tResponse *http.Response\n\n\t\/\/ Error is the error returned by the attempt, if any.\n\tError error\n}\n\n\/\/ retryFn is the signature for functions that implement retry strategies.\ntype retryFn func(attempt Attempt) (bool, time.Duration)\n\n\/\/ DelayFn is the signature for functions that return the delay to apply\n\/\/ before the next retry.\ntype DelayFn func(attempt Attempt) time.Duration\n\n\/\/ ShouldRetryFn is the signature for functions that return whether a\n\/\/ retry should be done for the request.\ntype ShouldRetryFn func(attempt Attempt) bool\n\n\/\/ NewTransport creates a Transport with a retry strategy based on\n\/\/ shouldRetry and delay to control the retry logic. It uses the provided\n\/\/ CancelRoundTripper to execute the requests. If rt is nil,\n\/\/ http.DefaultTransport is used. An error is returned if http.DefaultTransport\n\/\/ is not a CancelRoundTripper (which it is by default).\nfunc NewTransport(rt CancelRoundTripper, shouldRetry ShouldRetryFn, delay DelayFn) (*Transport, error) {\n\tif rt == nil {\n\t\tvar ok bool\n\t\trt, ok = http.DefaultTransport.(CancelRoundTripper)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"http.DefaultTransport is not a CancelRoundTripper\")\n\t\t}\n\t}\n\treturn &Transport{\n\t\tCancelRoundTripper: rt,\n\t\tretry:              toRetryFn(shouldRetry, delay),\n\t}, nil\n}\n\n\/\/ toRetryFn combines shouldRetry and delay into a retryFn.\nfunc toRetryFn(shouldRetry ShouldRetryFn, delay DelayFn) retryFn {\n\treturn func(attempt Attempt) (bool, time.Duration) {\n\t\tretry := shouldRetry(attempt)\n\t\tif !retry {\n\t\t\treturn false, 0\n\t\t}\n\t\treturn true, delay(attempt)\n\t}\n}\n\n\/\/ RetryAny returns a ShouldRetryFn that allows a retry as long as one of\n\/\/ the retryFns returns true. If retryFns is empty, it always returns false.\nfunc RetryAny(retryFns ...ShouldRetryFn) ShouldRetryFn {\n\treturn func(attempt Attempt) bool {\n\t\tfor _, fn := range retryFns {\n\t\t\tif fn(attempt) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n}\n\n\/\/ RetryAll returns a ShouldRetryFn that allows a retry if all retryFns\n\/\/ return true. If retryFns is empty, it always returns true.\nfunc RetryAll(retryFns ...ShouldRetryFn) ShouldRetryFn {\n\treturn func(attempt Attempt) bool {\n\t\tfor _, fn := range retryFns {\n\t\t\tif !fn(attempt) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}\n\n\/\/ RetryTemporaryErr returns a ShouldRetryFn that retries up to maxRetries\n\/\/ times for a temporary error. A temporary error is one that implements\n\/\/ the Temporary() bool method. Most errors from the net package implement\n\/\/ this.\nfunc RetryTemporaryErr(maxRetries int) ShouldRetryFn {\n\treturn func(attempt Attempt) bool {\n\t\tif attempt.Index >= maxRetries {\n\t\t\treturn false\n\t\t}\n\t\tif terr, ok := attempt.Error.(temporaryer); ok {\n\t\t\treturn terr.Temporary()\n\t\t}\n\t\treturn false\n\t}\n}\n\n\/\/ RetryStatus500 returns a ShouldRetryFn that retries up to maxRetries times\n\/\/ for a status code 5xx.\nfunc RetryStatus500(maxRetries int) ShouldRetryFn {\n\treturn func(attempt Attempt) bool {\n\t\tif attempt.Index >= maxRetries {\n\t\t\treturn false\n\t\t}\n\t\treturn attempt.Response != nil &&\n\t\t\tattempt.Response.StatusCode >= 500 &&\n\t\t\tattempt.Response.StatusCode < 600 \/\/ who knows\n\t}\n}\n\n\/\/ RetryHTTPMethods returns a ShouldRetryFn that retries up to maxRetries\n\/\/ times if the request's HTTP method is one of the provided methods.\n\/\/ It is meant to be used in conjunction with another ShouldRetryFn such\n\/\/ as RetryTemporaryErr combined using RetryAll, otherwise this function\n\/\/ will retry any successful request made with one of the provided methods.\nfunc RetryHTTPMethods(maxRetries int, methods ...string) ShouldRetryFn {\n\tfor i, m := range methods {\n\t\tmethods[i] = strings.ToUpper(m)\n\t}\n\n\treturn func(attempt Attempt) bool {\n\t\tif attempt.Index >= maxRetries {\n\t\t\treturn false\n\t\t}\n\t\tcurMeth := strings.ToUpper(attempt.Request.Method)\n\t\tfor _, m := range methods {\n\t\t\tif curMeth == m {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n}\n\n\/\/ ConstDelay returns a DelayFn that always returns the same delay.\nfunc ConstDelay(delay time.Duration) DelayFn {\n\treturn func(attempt Attempt) time.Duration {\n\t\treturn delay\n\t}\n}\n\n\/\/ ExponentialDelay returns a DelayFn that returns a delay between 0 and\n\/\/ base * 2^attempt, capped at max.\n\/\/\n\/\/ See the full jitter algorithm in:\n\/\/ http:\/\/www.awsarchitectureblog.com\/2015\/03\/backoff.html\nfunc ExponentialDelay(base, max time.Duration) DelayFn {\n\treturn func(attempt Attempt) time.Duration {\n\t\texp := math.Pow(2, float64(attempt.Index))\n\t\ttop := float64(base) * exp\n\t\treturn time.Duration(\n\t\t\tPRNG.Int63n(int64(math.Min(float64(max), top))),\n\t\t)\n\t}\n}\n\n\/\/ Transport wraps a CancelRoundTripper such as *http.Transport and adds\n\/\/ retry logic.\ntype Transport struct {\n\tCancelRoundTripper\n\n\t\/\/ PreventRetryWithBody prevents retrying if the request has a body. Since\n\t\/\/ the body is consumed on a request attempt, in order to retry a request\n\t\/\/ with a body, the body has to be buffered in memory. Setting this\n\t\/\/ to true avoids this buffering: the retry logic is bypassed if a body\n\t\/\/ is present.\n\tPreventRetryWithBody bool\n\n\t\/\/ retry is a function that determines if the request should be retried.\n\t\/\/ Unless a retry is prevented based on PreventRetryWithBody, all requests\n\t\/\/ go through that function, even those that are typically considered\n\t\/\/ successful.\n\t\/\/\n\t\/\/ If it returns false, no retry is attempted, otherwise a retry is\n\t\/\/ attempted after the specified duration.\n\tretry retryFn\n\n\tmu    sync.Mutex\n\treqCh map[*http.Request]chan struct{}\n}\n\n\/\/ RoundTrip implements http.RoundTripper for the Transport type.\n\/\/ It calls its underlying RoundTripper to execute the request, and\n\/\/ adds retry logic as per its configuration.\nfunc (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {\n\tvar attempt int\n\tpreventRetry := req.Body != nil && t.PreventRetryWithBody\n\n\tch := make(chan struct{})\n\tt.mu.Lock()\n\tif t.reqCh == nil {\n\t\tt.reqCh = make(map[*http.Request]chan struct{})\n\t}\n\tt.reqCh[req] = ch\n\tt.mu.Unlock()\n\n\tdefer func() {\n\t\tt.mu.Lock()\n\t\tdelete(t.reqCh, req)\n\t\tt.mu.Unlock()\n\t}()\n\n\t\/\/ buffer the body if needed\n\tvar br *bytes.Reader\n\tif req.Body != nil && !preventRetry {\n\t\tvar buf bytes.Buffer\n\t\tif _, err := io.Copy(&buf, req.Body); err != nil {\n\t\t\t\/\/ cannot even try the first attempt, body has been consumed\n\t\t\treq.Body.Close()\n\t\t\treturn nil, err\n\t\t}\n\t\treq.Body.Close()\n\n\t\tbr = bytes.NewReader(buf.Bytes())\n\t\treq.Body = ioutil.NopCloser(br)\n\t}\n\n\tfor {\n\t\tres, err := t.CancelRoundTripper.RoundTrip(req)\n\t\tif preventRetry {\n\t\t\treturn res, err\n\t\t}\n\n\t\tretry, delay := t.retry(Attempt{\n\t\t\tRequest:  req,\n\t\t\tResponse: res,\n\t\t\tIndex:    attempt,\n\t\t\tError:    err,\n\t\t})\n\t\tif !retry {\n\t\t\treturn res, err\n\t\t}\n\n\t\tif br != nil {\n\t\t\t\/\/ Per Go's doc: \"RoundTrip should not modify the request,\n\t\t\t\/\/ except for consuming and closing the Body\", so the only thing\n\t\t\t\/\/ to reset on the request is the body, if any.\n\t\t\tif _, serr := br.Seek(0, 0); serr != nil {\n\t\t\t\t\/\/ failed to retry, return the results\n\t\t\t\treturn res, err\n\t\t\t}\n\t\t\treq.Body = ioutil.NopCloser(br)\n\t\t}\n\t\t\/\/ close the disposed response's body, if any\n\t\tif res != nil {\n\t\t\tres.Body.Close()\n\t\t}\n\n\t\tselect {\n\t\tcase <-time.After(delay):\n\t\t\tattempt++\n\t\tcase <-req.Cancel:\n\t\t\t\/\/ request canceled by caller, don't retry\n\t\t\treturn nil, errors.New(\"net\/http: request canceled\")\n\t\tcase <-ch:\n\t\t\t\/\/ request canceled by call to CancelRequest, don't retry\n\t\t\treturn nil, errors.New(\"net\/http: request canceled\")\n\t\t}\n\t}\n}\n\n\/\/ CancelRequest cancels the specified request, preventing any pending\n\/\/ retry.\nfunc (t *Transport) CancelRequest(req *http.Request) {\n\tvar ch chan struct{}\n\tt.mu.Lock()\n\tif t.reqCh != nil {\n\t\tch = t.reqCh[req]\n\t\tdelete(t.reqCh, req)\n\t}\n\tt.mu.Unlock()\n\n\tif ch != nil {\n\t\tclose(ch)\n\t}\n\n\tt.CancelRoundTripper.CancelRequest(req)\n}\n<commit_msg>jsonreq,rehttp: drain response body before closing<commit_after>\/\/ Package rehttp implements an HTTP transport that handles retries.\n\/\/\n\/\/ An HTTP Client can be created with a *rehttp.Transport as RoundTripper\n\/\/ and it will apply the retry strategy to its requests, e.g.:\n\/\/\n\/\/     tr, err := rehttp.NewTransport(\n\/\/         nil,                            \/\/ will use http.DefaultTransport\n\/\/         rehttp.RetryTemporaryErr(3),    \/\/ max 3 retries for Temporary errors\n\/\/         rehttp.ConstDelay(time.Second), \/\/ wait 1s between retries\n\/\/     )\n\/\/     if err != nil {\n\/\/         \/\/ handle err\n\/\/     }\n\/\/     client := &http.Client{\n\/\/         Transport: tr,\n\/\/         Timeout: 30 * time.Second, \/\/ timeout applies to all retries as a whole\n\/\/     }\n\/\/\n\/\/ The retry strategy is provided by the Transport, which holds\n\/\/ a function that returns whether or not the request should be retried,\n\/\/ and if so, what delay to apply before retrying, based on the ShouldRetryFn\n\/\/ and DelayFn functions passed to NewTransport.\n\/\/\n\/\/ The package offers common delay strategies as ready-made functions that\n\/\/ return a DelayFn:\n\/\/     - ConstDelay(delay time.Duration) DelayFn\n\/\/     - ExponentialDelay(base, max time.Duration) DelayFn\n\/\/\n\/\/ It also provides common retry predicates that return a ShouldRetryFn:\n\/\/     - RetryTemporaryErr(maxRetries int) ShouldRetryFn\n\/\/     - RetryStatus500(maxRetries int) ShouldRetryFn\n\/\/     - RetryHTTPMethods(maxRetries int, methods ...string) ShouldRetryFn\n\/\/\n\/\/ Those can be combined with RetryAny or RetryAll as needed. RetryAny\n\/\/ enables retries if any of the ShouldRetryFn return true, while RetryAll\n\/\/ enables retries if all ShouldRetryFn return true.\n\/\/\n\/\/ The Transport will buffer the request's body in order to be able to\n\/\/ retry the request, as a request attempt will consume and close the\n\/\/ existing body. Sometimes this is not desirable, so it can be prevented\n\/\/ by setting PreventRetryWithBody to true on the Transport. Doing so\n\/\/ will disable retries when a request has a non-nil body.\n\/\/\npackage rehttp\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ PRNG is the *math.Rand value to use to add jitter to the backoff\n\/\/ algorithm used in ExponentialDelay. By default it uses a *math.Rand\n\/\/ initialized with a source based on the current time in nanoseconds.\nvar PRNG = rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\/\/ terribly named interface to detect errors that support Temporary.\ntype temporaryer interface {\n\tTemporary() bool\n}\n\n\/\/ CancelRoundTripper is a RoundTripper that supports CancelRequest.\n\/\/ The *http.Transport type implements this interface.\ntype CancelRoundTripper interface {\n\thttp.RoundTripper\n\tCancelRequest(*http.Request)\n}\n\n\/\/ Attempt holds the data for a RoundTrip attempt.\ntype Attempt struct {\n\t\/\/ Index is the attempt index starting at 0.\n\tIndex int\n\n\t\/\/ Request is the request for this attempt. If a non-nil Response\n\t\/\/ is present, this is the same as Response.Request, but since a\n\t\/\/ Response may not be available, it is guaranteed to be set on this\n\t\/\/ field.\n\tRequest *http.Request\n\n\t\/\/ Response is the response for this attempt. It may be nil if an\n\t\/\/ error occurred an no response was received.\n\tResponse *http.Response\n\n\t\/\/ Error is the error returned by the attempt, if any.\n\tError error\n}\n\n\/\/ retryFn is the signature for functions that implement retry strategies.\ntype retryFn func(attempt Attempt) (bool, time.Duration)\n\n\/\/ DelayFn is the signature for functions that return the delay to apply\n\/\/ before the next retry.\ntype DelayFn func(attempt Attempt) time.Duration\n\n\/\/ ShouldRetryFn is the signature for functions that return whether a\n\/\/ retry should be done for the request.\ntype ShouldRetryFn func(attempt Attempt) bool\n\n\/\/ NewTransport creates a Transport with a retry strategy based on\n\/\/ shouldRetry and delay to control the retry logic. It uses the provided\n\/\/ CancelRoundTripper to execute the requests. If rt is nil,\n\/\/ http.DefaultTransport is used. An error is returned if http.DefaultTransport\n\/\/ is not a CancelRoundTripper (which it is by default).\nfunc NewTransport(rt CancelRoundTripper, shouldRetry ShouldRetryFn, delay DelayFn) (*Transport, error) {\n\tif rt == nil {\n\t\tvar ok bool\n\t\trt, ok = http.DefaultTransport.(CancelRoundTripper)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"http.DefaultTransport is not a CancelRoundTripper\")\n\t\t}\n\t}\n\treturn &Transport{\n\t\tCancelRoundTripper: rt,\n\t\tretry:              toRetryFn(shouldRetry, delay),\n\t}, nil\n}\n\n\/\/ toRetryFn combines shouldRetry and delay into a retryFn.\nfunc toRetryFn(shouldRetry ShouldRetryFn, delay DelayFn) retryFn {\n\treturn func(attempt Attempt) (bool, time.Duration) {\n\t\tretry := shouldRetry(attempt)\n\t\tif !retry {\n\t\t\treturn false, 0\n\t\t}\n\t\treturn true, delay(attempt)\n\t}\n}\n\n\/\/ RetryAny returns a ShouldRetryFn that allows a retry as long as one of\n\/\/ the retryFns returns true. If retryFns is empty, it always returns false.\nfunc RetryAny(retryFns ...ShouldRetryFn) ShouldRetryFn {\n\treturn func(attempt Attempt) bool {\n\t\tfor _, fn := range retryFns {\n\t\t\tif fn(attempt) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n}\n\n\/\/ RetryAll returns a ShouldRetryFn that allows a retry if all retryFns\n\/\/ return true. If retryFns is empty, it always returns true.\nfunc RetryAll(retryFns ...ShouldRetryFn) ShouldRetryFn {\n\treturn func(attempt Attempt) bool {\n\t\tfor _, fn := range retryFns {\n\t\t\tif !fn(attempt) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n}\n\n\/\/ RetryTemporaryErr returns a ShouldRetryFn that retries up to maxRetries\n\/\/ times for a temporary error. A temporary error is one that implements\n\/\/ the Temporary() bool method. Most errors from the net package implement\n\/\/ this.\nfunc RetryTemporaryErr(maxRetries int) ShouldRetryFn {\n\treturn func(attempt Attempt) bool {\n\t\tif attempt.Index >= maxRetries {\n\t\t\treturn false\n\t\t}\n\t\tif terr, ok := attempt.Error.(temporaryer); ok {\n\t\t\treturn terr.Temporary()\n\t\t}\n\t\treturn false\n\t}\n}\n\n\/\/ RetryStatus500 returns a ShouldRetryFn that retries up to maxRetries times\n\/\/ for a status code 5xx.\nfunc RetryStatus500(maxRetries int) ShouldRetryFn {\n\treturn func(attempt Attempt) bool {\n\t\tif attempt.Index >= maxRetries {\n\t\t\treturn false\n\t\t}\n\t\treturn attempt.Response != nil &&\n\t\t\tattempt.Response.StatusCode >= 500 &&\n\t\t\tattempt.Response.StatusCode < 600 \/\/ who knows\n\t}\n}\n\n\/\/ RetryHTTPMethods returns a ShouldRetryFn that retries up to maxRetries\n\/\/ times if the request's HTTP method is one of the provided methods.\n\/\/ It is meant to be used in conjunction with another ShouldRetryFn such\n\/\/ as RetryTemporaryErr combined using RetryAll, otherwise this function\n\/\/ will retry any successful request made with one of the provided methods.\nfunc RetryHTTPMethods(maxRetries int, methods ...string) ShouldRetryFn {\n\tfor i, m := range methods {\n\t\tmethods[i] = strings.ToUpper(m)\n\t}\n\n\treturn func(attempt Attempt) bool {\n\t\tif attempt.Index >= maxRetries {\n\t\t\treturn false\n\t\t}\n\t\tcurMeth := strings.ToUpper(attempt.Request.Method)\n\t\tfor _, m := range methods {\n\t\t\tif curMeth == m {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n}\n\n\/\/ ConstDelay returns a DelayFn that always returns the same delay.\nfunc ConstDelay(delay time.Duration) DelayFn {\n\treturn func(attempt Attempt) time.Duration {\n\t\treturn delay\n\t}\n}\n\n\/\/ ExponentialDelay returns a DelayFn that returns a delay between 0 and\n\/\/ base * 2^attempt, capped at max.\n\/\/\n\/\/ See the full jitter algorithm in:\n\/\/ http:\/\/www.awsarchitectureblog.com\/2015\/03\/backoff.html\nfunc ExponentialDelay(base, max time.Duration) DelayFn {\n\treturn func(attempt Attempt) time.Duration {\n\t\texp := math.Pow(2, float64(attempt.Index))\n\t\ttop := float64(base) * exp\n\t\treturn time.Duration(\n\t\t\tPRNG.Int63n(int64(math.Min(float64(max), top))),\n\t\t)\n\t}\n}\n\n\/\/ Transport wraps a CancelRoundTripper such as *http.Transport and adds\n\/\/ retry logic.\ntype Transport struct {\n\tCancelRoundTripper\n\n\t\/\/ PreventRetryWithBody prevents retrying if the request has a body. Since\n\t\/\/ the body is consumed on a request attempt, in order to retry a request\n\t\/\/ with a body, the body has to be buffered in memory. Setting this\n\t\/\/ to true avoids this buffering: the retry logic is bypassed if a body\n\t\/\/ is present.\n\tPreventRetryWithBody bool\n\n\t\/\/ retry is a function that determines if the request should be retried.\n\t\/\/ Unless a retry is prevented based on PreventRetryWithBody, all requests\n\t\/\/ go through that function, even those that are typically considered\n\t\/\/ successful.\n\t\/\/\n\t\/\/ If it returns false, no retry is attempted, otherwise a retry is\n\t\/\/ attempted after the specified duration.\n\tretry retryFn\n\n\tmu    sync.Mutex\n\treqCh map[*http.Request]chan struct{}\n}\n\n\/\/ RoundTrip implements http.RoundTripper for the Transport type.\n\/\/ It calls its underlying RoundTripper to execute the request, and\n\/\/ adds retry logic as per its configuration.\nfunc (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {\n\tvar attempt int\n\tpreventRetry := req.Body != nil && t.PreventRetryWithBody\n\n\tch := make(chan struct{})\n\tt.mu.Lock()\n\tif t.reqCh == nil {\n\t\tt.reqCh = make(map[*http.Request]chan struct{})\n\t}\n\tt.reqCh[req] = ch\n\tt.mu.Unlock()\n\n\tdefer func() {\n\t\tt.mu.Lock()\n\t\tdelete(t.reqCh, req)\n\t\tt.mu.Unlock()\n\t}()\n\n\t\/\/ buffer the body if needed\n\tvar br *bytes.Reader\n\tif req.Body != nil && !preventRetry {\n\t\tvar buf bytes.Buffer\n\t\tif _, err := io.Copy(&buf, req.Body); err != nil {\n\t\t\t\/\/ cannot even try the first attempt, body has been consumed\n\t\t\treq.Body.Close()\n\t\t\treturn nil, err\n\t\t}\n\t\treq.Body.Close()\n\n\t\tbr = bytes.NewReader(buf.Bytes())\n\t\treq.Body = ioutil.NopCloser(br)\n\t}\n\n\tfor {\n\t\tres, err := t.CancelRoundTripper.RoundTrip(req)\n\t\tif preventRetry {\n\t\t\treturn res, err\n\t\t}\n\n\t\tretry, delay := t.retry(Attempt{\n\t\t\tRequest:  req,\n\t\t\tResponse: res,\n\t\t\tIndex:    attempt,\n\t\t\tError:    err,\n\t\t})\n\t\tif !retry {\n\t\t\treturn res, err\n\t\t}\n\n\t\tif br != nil {\n\t\t\t\/\/ Per Go's doc: \"RoundTrip should not modify the request,\n\t\t\t\/\/ except for consuming and closing the Body\", so the only thing\n\t\t\t\/\/ to reset on the request is the body, if any.\n\t\t\tif _, serr := br.Seek(0, 0); serr != nil {\n\t\t\t\t\/\/ failed to retry, return the results\n\t\t\t\treturn res, err\n\t\t\t}\n\t\t\treq.Body = ioutil.NopCloser(br)\n\t\t}\n\t\t\/\/ close the disposed response's body, if any\n\t\tif res != nil {\n\t\t\tio.Copy(ioutil.Discard, res.Body)\n\t\t\tres.Body.Close()\n\t\t}\n\n\t\tselect {\n\t\tcase <-time.After(delay):\n\t\t\tattempt++\n\t\tcase <-req.Cancel:\n\t\t\t\/\/ request canceled by caller, don't retry\n\t\t\treturn nil, errors.New(\"net\/http: request canceled\")\n\t\tcase <-ch:\n\t\t\t\/\/ request canceled by call to CancelRequest, don't retry\n\t\t\treturn nil, errors.New(\"net\/http: request canceled\")\n\t\t}\n\t}\n}\n\n\/\/ CancelRequest cancels the specified request, preventing any pending\n\/\/ retry.\nfunc (t *Transport) CancelRequest(req *http.Request) {\n\tvar ch chan struct{}\n\tt.mu.Lock()\n\tif t.reqCh != nil {\n\t\tch = t.reqCh[req]\n\t\tdelete(t.reqCh, req)\n\t}\n\tt.mu.Unlock()\n\n\tif ch != nil {\n\t\tclose(ch)\n\t}\n\n\tt.CancelRoundTripper.CancelRequest(req)\n}\n<|endoftext|>"}
{"text":"<commit_before>package vsolver\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/\/ A remoteRepo represents a potential remote repository resource.\n\/\/\n\/\/ RemoteRepos are based purely on lexical analysis; successfully constructing\n\/\/ one is not a guarantee that the resource it identifies actually exists or is\n\/\/ accessible.\ntype remoteRepo struct {\n\tBase     string\n\tRelPkg   string\n\tCloneURL *url.URL\n\tSchemes  []string\n\tVCS      []string\n}\n\n\/\/type remoteResult struct {\n\/\/r   remoteRepo\n\/\/err error\n\/\/}\n\n\/\/ TODO sync access to this map\n\/\/var remoteCache = make(map[string]remoteResult)\n\n\/\/ Regexes for the different known import path flavors\nvar (\n\tghRegex      = regexp.MustCompile(`^(?P<root>github\\.com\/([A-Za-z0-9_.\\-]+\/[A-Za-z0-9_.\\-]+))(\/[A-Za-z0-9_.\\-]+)*$`)\n\tgpinNewRegex = regexp.MustCompile(`^(?P<root>gopkg\\.in\/(?:([a-zA-Z0-9][-a-zA-Z0-9]+)\/)?([a-zA-Z][-.a-zA-Z0-9]*)\\.((?:v0|v[1-9][0-9]*)(?:\\.0|\\.[1-9][0-9]*){0,2}(-unstable)?)(?:\\.git))?((?:\/[a-zA-Z0-9][-.a-zA-Z0-9]*)*)$`)\n\t\/\/gpinOldRegex = regexp.MustCompile(`^(?P<root>gopkg\\.in\/(?:([a-z0-9][-a-z0-9]+)\/)?((?:v0|v[1-9][0-9]*)(?:\\.0|\\.[1-9][0-9]*){0,2}(-unstable)?))\/([a-zA-Z][-a-zA-Z0-9]*)(?:\\.git)?((?:\/[a-zA-Z][-a-zA-Z0-9]*)*)$`)\n\tbbRegex = regexp.MustCompile(`^(?P<root>bitbucket\\.org\/(?P<bitname>[A-Za-z0-9_.\\-]+\/[A-Za-z0-9_.\\-]+))(\/[A-Za-z0-9_.\\-]+)*$`)\n\tlpRegex = regexp.MustCompile(`^(?P<root>launchpad.net\/([A-Za-z0-9-._]+)(\/[A-Za-z0-9-._]+)?)(\/.+)?`)\n\t\/\/glpRegex = regexp.MustCompile(`^(?P<root>git\\.launchpad\\.net\/(([A-Za-z0-9_.\\-]+)|~[A-Za-z0-9_.\\-]+\/(\\+git|[A-Za-z0-9_.\\-]+)\/[A-Za-z0-9_.\\-]+))$`)\n\t\/\/gcRegex      = regexp.MustCompile(`^(?P<root>code\\.google\\.com\/[pr]\/(?P<project>[a-z0-9\\-]+)(\\.(?P<subrepo>[a-z0-9\\-]+))?)(\/[A-Za-z0-9_.\\-]+)*$`)\n\tjazzRegex    = regexp.MustCompile(`^(?P<root>hub\\.jazz\\.net\/git\/[a-z0-9]+\/[A-Za-z0-9_.\\-]+)(\/[A-Za-z0-9_.\\-]+)*$`)\n\tgenericRegex = regexp.MustCompile(`^(?P<root>(?P<repo>([a-z0-9.\\-]+\\.)+[a-z0-9.\\-]+(:[0-9]+)?\/[A-Za-z0-9_.\\-\/~]*?)\\.(?P<vcs>bzr|git|hg|svn))([\/A-Za-z0-9_.\\-]+)*$`)\n)\n\n\/\/ Other helper regexes\nvar (\n\tscpSyntaxRe = regexp.MustCompile(`^([a-zA-Z0-9_]+)@([a-zA-Z0-9._-]+):(.*)$`)\n\tpathvld     = regexp.MustCompile(`^([A-Za-z0-9-]+)(\\.[A-Za-z0-9-]+)+(\/[A-Za-z0-9-_.~]+)*$`)\n)\n\n\/\/ deduceRemoteRepo takes a potential import path and returns a RemoteRepo\n\/\/ representing the remote location of the source of an import path. Remote\n\/\/ repositories can be bare import paths, or urls including a checkout scheme.\nfunc deduceRemoteRepo(path string) (rr remoteRepo, err error) {\n\tif m := scpSyntaxRe.FindStringSubmatch(path); m != nil {\n\t\t\/\/ Match SCP-like syntax and convert it to a URL.\n\t\t\/\/ Eg, \"git@github.com:user\/repo\" becomes\n\t\t\/\/ \"ssh:\/\/git@github.com\/user\/repo\".\n\t\trr.CloneURL = &url.URL{\n\t\t\tScheme:  \"ssh\",\n\t\t\tUser:    url.User(m[1]),\n\t\t\tHost:    m[2],\n\t\t\tRawPath: m[3],\n\t\t}\n\t} else {\n\t\trr.CloneURL, err = url.Parse(path)\n\t\tif err != nil {\n\t\t\treturn remoteRepo{}, fmt.Errorf(\"%q is not a valid import path\", path)\n\t\t}\n\t}\n\n\tpath = rr.CloneURL.Host + rr.CloneURL.Path\n\tif !pathvld.MatchString(path) {\n\t\treturn remoteRepo{}, fmt.Errorf(\"%q is not a valid import path\", path)\n\t}\n\n\tif rr.CloneURL.Scheme != \"\" {\n\t\trr.Schemes = []string{rr.CloneURL.Scheme}\n\t}\n\n\tswitch {\n\tcase ghRegex.MatchString(path):\n\t\tv := ghRegex.FindStringSubmatch(path)\n\n\t\trr.CloneURL.Host = \"github.com\"\n\t\trr.CloneURL.Path = v[2]\n\t\trr.Base = v[1]\n\t\trr.RelPkg = strings.TrimPrefix(v[3], \"\/\")\n\t\trr.VCS = []string{\"git\"}\n\n\t\treturn\n\n\tcase gpinNewRegex.MatchString(path):\n\t\tv := gpinNewRegex.FindStringSubmatch(path)\n\n\t\t\/\/ Duplicate some logic from the gopkg.in server in order to validate\n\t\t\/\/ the import path string without having to hit the server\n\t\tif strings.Contains(v[4], \".\") {\n\t\t\treturn remoteRepo{}, fmt.Errorf(\"%q is not a valid import path; gopkg.in only allows major versions (%q instead of %q)\",\n\t\t\t\tpath, v[4][:strings.Index(v[4], \".\")], v[4])\n\t\t}\n\n\t\t\/\/ If the third position is empty, it's the shortened form that expands\n\t\t\/\/ to the go-pkg github user\n\t\tif v[3] != \"\" {\n\t\t\trr.CloneURL.Path = \"go-pkg\/\" + v[4]\n\t\t} else {\n\t\t\trr.CloneURL.Path = v[2] + v[4]\n\t\t}\n\t\trr.CloneURL.Host = \"github.com\"\n\t\trr.Base = v[1]\n\t\trr.RelPkg = strings.TrimPrefix(v[6], \"\/\")\n\t\trr.VCS = []string{\"git\"}\n\n\t\treturn\n\t\/\/case gpinOldRegex.MatchString(path):\n\n\tcase bbRegex.MatchString(path):\n\t\tv := bbRegex.FindStringSubmatch(path)\n\n\t\trr.CloneURL.Host = \"bitbucket.org\"\n\t\trr.CloneURL.Path = v[2]\n\t\trr.Base = v[1]\n\t\trr.RelPkg = strings.TrimPrefix(v[5], \"\/\")\n\t\trr.VCS = []string{\"git\", \"hg\"}\n\n\t\treturn\n\n\t\/\/case gcRegex.MatchString(path):\n\t\/\/v := gcRegex.FindStringSubmatch(path)\n\n\t\/\/rr.CloneURL.Host = \"code.google.com\"\n\t\/\/rr.CloneURL.Path = \"p\/\" + v[2]\n\t\/\/rr.Base = v[1]\n\t\/\/rr.RelPkg = strings.TrimPrefix(v[5], \"\/\")\n\t\/\/rr.VCS = []string{\"hg\", \"git\"}\n\n\t\/\/return\n\n\tcase lpRegex.MatchString(path):\n\t\tv := lpRegex.FindStringSubmatch(path)\n\t\tv = append(v, \"\", \"\")\n\n\t\trr.CloneURL.Host = \"launchpad.net\"\n\t\trr.Base = v[1]\n\t\trr.RelPkg = strings.TrimPrefix(v[4], \"\/\")\n\t\trr.VCS = []string{\"bzr\"}\n\n\t\tif v[3] == \"\" {\n\t\t\t\/\/ launchpad.net\/project\"\n\t\t\trr.Base = fmt.Sprintf(\"https:\/\/launchpad.net\/%v\", v[2])\n\t\t} else {\n\t\t\t\/\/ launchpad.net\/project\/series\"\n\t\t\trr.Base = fmt.Sprintf(\"https:\/\/launchpad.net\/%s\/%s\", v[2], v[3])\n\t\t}\n\t\treturn\n\n\t\/\/case glpRegex.MatchString(path):\n\t\/\/\/\/ TODO too many rules for this, commenting out for now\n\t\/\/v := lpRegex.FindStringSubmatch(path)\n\n\t\/\/rr.CloneURL.Host = \"launchpad.net\"\n\t\/\/rr.RelPkg = strings.TrimPrefix(v[3], \"\/\")\n\t\/\/rr.VCS = []string{\"git\"}\n\n\t\/\/v = append(v, \"\", \"\")\n\t\/\/if v[2] == \"\" {\n\t\/\/\/\/ launchpad.net\/project\"\n\t\/\/rr.Base = fmt.Sprintf(\"https:\/\/launchpad.net\/%v\", v[1])\n\t\/\/} else {\n\t\/\/\/\/ launchpad.net\/project\/series\"\n\t\/\/rr.Base = fmt.Sprintf(\"https:\/\/launchpad.net\/%s\/%s\", v[1], v[2])\n\t\/\/}\n\t\/\/return\n\n\t\/\/ try the general syntax\n\tcase genericRegex.MatchString(path):\n\t\tv := genericRegex.FindStringSubmatch(path)\n\t\tswitch v[5] {\n\t\tcase \"git\", \"hg\", \"bzr\":\n\t\t\tx := strings.SplitN(v[1], \"\/\", 2)\n\t\t\t\/\/ TODO is this actually correct for bzr?\n\t\t\trr.CloneURL.Host = x[0]\n\t\t\trr.CloneURL.Path = x[1]\n\t\t\trr.VCS = []string{v[5]}\n\t\t\trr.Base = v[1]\n\t\t\trr.RelPkg = strings.TrimPrefix(v[6], \"\/\")\n\t\t\treturn\n\t\tdefault:\n\t\t\treturn remoteRepo{}, fmt.Errorf(\"unknown repository type: %q\", v[5])\n\t\t}\n\t}\n\n\t\/\/ TODO use HTTP metadata to resolve vanity imports\n\treturn remoteRepo{}, fmt.Errorf(\"unable to deduct repository and source type for: %q\", path)\n}\n<commit_msg>Can't forget jazz! (and apache)<commit_after>package vsolver\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/\/ A remoteRepo represents a potential remote repository resource.\n\/\/\n\/\/ RemoteRepos are based purely on lexical analysis; successfully constructing\n\/\/ one is not a guarantee that the resource it identifies actually exists or is\n\/\/ accessible.\ntype remoteRepo struct {\n\tBase     string\n\tRelPkg   string\n\tCloneURL *url.URL\n\tSchemes  []string\n\tVCS      []string\n}\n\n\/\/type remoteResult struct {\n\/\/r   remoteRepo\n\/\/err error\n\/\/}\n\n\/\/ TODO sync access to this map\n\/\/var remoteCache = make(map[string]remoteResult)\n\n\/\/ Regexes for the different known import path flavors\nvar (\n\tghRegex      = regexp.MustCompile(`^(?P<root>github\\.com\/([A-Za-z0-9_.\\-]+\/[A-Za-z0-9_.\\-]+))(\/[A-Za-z0-9_.\\-]+)*$`)\n\tgpinNewRegex = regexp.MustCompile(`^(?P<root>gopkg\\.in\/(?:([a-zA-Z0-9][-a-zA-Z0-9]+)\/)?([a-zA-Z][-.a-zA-Z0-9]*)\\.((?:v0|v[1-9][0-9]*)(?:\\.0|\\.[1-9][0-9]*){0,2}(-unstable)?)(?:\\.git))?((?:\/[a-zA-Z0-9][-.a-zA-Z0-9]*)*)$`)\n\t\/\/gpinOldRegex = regexp.MustCompile(`^(?P<root>gopkg\\.in\/(?:([a-z0-9][-a-z0-9]+)\/)?((?:v0|v[1-9][0-9]*)(?:\\.0|\\.[1-9][0-9]*){0,2}(-unstable)?))\/([a-zA-Z][-a-zA-Z0-9]*)(?:\\.git)?((?:\/[a-zA-Z][-a-zA-Z0-9]*)*)$`)\n\tbbRegex = regexp.MustCompile(`^(?P<root>bitbucket\\.org\/(?P<bitname>[A-Za-z0-9_.\\-]+\/[A-Za-z0-9_.\\-]+))(\/[A-Za-z0-9_.\\-]+)*$`)\n\tlpRegex = regexp.MustCompile(`^(?P<root>launchpad.net\/([A-Za-z0-9-._]+)(\/[A-Za-z0-9-._]+)?)(\/.+)?`)\n\t\/\/glpRegex = regexp.MustCompile(`^(?P<root>git\\.launchpad\\.net\/(([A-Za-z0-9_.\\-]+)|~[A-Za-z0-9_.\\-]+\/(\\+git|[A-Za-z0-9_.\\-]+)\/[A-Za-z0-9_.\\-]+))$`)\n\t\/\/gcRegex      = regexp.MustCompile(`^(?P<root>code\\.google\\.com\/[pr]\/(?P<project>[a-z0-9\\-]+)(\\.(?P<subrepo>[a-z0-9\\-]+))?)(\/[A-Za-z0-9_.\\-]+)*$`)\n\tjazzRegex    = regexp.MustCompile(`^(?P<root>hub\\.jazz\\.net\/git\/[a-z0-9]+\/[A-Za-z0-9_.\\-]+)(\/[A-Za-z0-9_.\\-]+)*$`)\n\tapacheRegex  = regexp.MustCompile(`^(?P<root>git.apache.org\/[a-z0-9_.\\-]+\\.git)(\/[A-Za-z0-9_.\\-]+)*$`)\n\tgenericRegex = regexp.MustCompile(`^(?P<root>(?P<repo>([a-z0-9.\\-]+\\.)+[a-z0-9.\\-]+(:[0-9]+)?\/[A-Za-z0-9_.\\-\/~]*?)\\.(?P<vcs>bzr|git|hg|svn))([\/A-Za-z0-9_.\\-]+)*$`)\n)\n\n\/\/ Other helper regexes\nvar (\n\tscpSyntaxRe = regexp.MustCompile(`^([a-zA-Z0-9_]+)@([a-zA-Z0-9._-]+):(.*)$`)\n\tpathvld     = regexp.MustCompile(`^([A-Za-z0-9-]+)(\\.[A-Za-z0-9-]+)+(\/[A-Za-z0-9-_.~]+)*$`)\n)\n\n\/\/ deduceRemoteRepo takes a potential import path and returns a RemoteRepo\n\/\/ representing the remote location of the source of an import path. Remote\n\/\/ repositories can be bare import paths, or urls including a checkout scheme.\nfunc deduceRemoteRepo(path string) (rr remoteRepo, err error) {\n\tif m := scpSyntaxRe.FindStringSubmatch(path); m != nil {\n\t\t\/\/ Match SCP-like syntax and convert it to a URL.\n\t\t\/\/ Eg, \"git@github.com:user\/repo\" becomes\n\t\t\/\/ \"ssh:\/\/git@github.com\/user\/repo\".\n\t\trr.CloneURL = &url.URL{\n\t\t\tScheme:  \"ssh\",\n\t\t\tUser:    url.User(m[1]),\n\t\t\tHost:    m[2],\n\t\t\tRawPath: m[3],\n\t\t}\n\t} else {\n\t\trr.CloneURL, err = url.Parse(path)\n\t\tif err != nil {\n\t\t\treturn remoteRepo{}, fmt.Errorf(\"%q is not a valid import path\", path)\n\t\t}\n\t}\n\n\tpath = rr.CloneURL.Host + rr.CloneURL.Path\n\tif !pathvld.MatchString(path) {\n\t\treturn remoteRepo{}, fmt.Errorf(\"%q is not a valid import path\", path)\n\t}\n\n\tif rr.CloneURL.Scheme != \"\" {\n\t\trr.Schemes = []string{rr.CloneURL.Scheme}\n\t}\n\n\tswitch {\n\tcase ghRegex.MatchString(path):\n\t\tv := ghRegex.FindStringSubmatch(path)\n\n\t\trr.CloneURL.Host = \"github.com\"\n\t\trr.CloneURL.Path = v[2]\n\t\trr.Base = v[1]\n\t\trr.RelPkg = strings.TrimPrefix(v[3], \"\/\")\n\t\trr.VCS = []string{\"git\"}\n\n\t\treturn\n\n\tcase gpinNewRegex.MatchString(path):\n\t\tv := gpinNewRegex.FindStringSubmatch(path)\n\n\t\t\/\/ Duplicate some logic from the gopkg.in server in order to validate\n\t\t\/\/ the import path string without having to hit the server\n\t\tif strings.Contains(v[4], \".\") {\n\t\t\treturn remoteRepo{}, fmt.Errorf(\"%q is not a valid import path; gopkg.in only allows major versions (%q instead of %q)\",\n\t\t\t\tpath, v[4][:strings.Index(v[4], \".\")], v[4])\n\t\t}\n\n\t\t\/\/ If the third position is empty, it's the shortened form that expands\n\t\t\/\/ to the go-pkg github user\n\t\tif v[3] != \"\" {\n\t\t\trr.CloneURL.Path = \"go-pkg\/\" + v[4]\n\t\t} else {\n\t\t\trr.CloneURL.Path = v[2] + v[4]\n\t\t}\n\t\trr.CloneURL.Host = \"github.com\"\n\t\trr.Base = v[1]\n\t\trr.RelPkg = strings.TrimPrefix(v[6], \"\/\")\n\t\trr.VCS = []string{\"git\"}\n\n\t\treturn\n\t\/\/case gpinOldRegex.MatchString(path):\n\n\tcase bbRegex.MatchString(path):\n\t\tv := bbRegex.FindStringSubmatch(path)\n\n\t\trr.CloneURL.Host = \"bitbucket.org\"\n\t\trr.CloneURL.Path = v[2]\n\t\trr.Base = v[1]\n\t\trr.RelPkg = strings.TrimPrefix(v[5], \"\/\")\n\t\trr.VCS = []string{\"git\", \"hg\"}\n\n\t\treturn\n\n\t\/\/case gcRegex.MatchString(path):\n\t\/\/v := gcRegex.FindStringSubmatch(path)\n\n\t\/\/rr.CloneURL.Host = \"code.google.com\"\n\t\/\/rr.CloneURL.Path = \"p\/\" + v[2]\n\t\/\/rr.Base = v[1]\n\t\/\/rr.RelPkg = strings.TrimPrefix(v[5], \"\/\")\n\t\/\/rr.VCS = []string{\"hg\", \"git\"}\n\n\t\/\/return\n\n\tcase lpRegex.MatchString(path):\n\t\tv := lpRegex.FindStringSubmatch(path)\n\t\tv = append(v, \"\", \"\")\n\n\t\trr.CloneURL.Host = \"launchpad.net\"\n\t\trr.Base = v[1]\n\t\trr.RelPkg = strings.TrimPrefix(v[4], \"\/\")\n\t\trr.VCS = []string{\"bzr\"}\n\n\t\tif v[3] == \"\" {\n\t\t\t\/\/ launchpad.net\/project\"\n\t\t\trr.Base = fmt.Sprintf(\"https:\/\/launchpad.net\/%v\", v[2])\n\t\t} else {\n\t\t\t\/\/ launchpad.net\/project\/series\"\n\t\t\trr.Base = fmt.Sprintf(\"https:\/\/launchpad.net\/%s\/%s\", v[2], v[3])\n\t\t}\n\t\treturn\n\n\tcase jazzRegex.MatchString(path):\n\t\tv := jazzRegex.FindStringSubmatch(path)\n\n\t\trr.CloneURL.Host = \"hub.jazz.net\"\n\t\trr.CloneURL.Path = \"git\" + v[2]\n\t\trr.Base = v[1]\n\t\trr.RelPkg = strings.TrimPrefix(v[2], \"\/\")\n\t\trr.VCS = []string{\"git\"}\n\n\t\treturn\n\n\tcase apacheRegex.MatchString(path):\n\t\tv := apacheRegex.FindStringSubmatch(path)\n\n\t\trr.CloneURL.Host = \"git.apache.org\"\n\t\trr.Base = v[1]\n\t\trr.RelPkg = strings.TrimPrefix(v[2], \"\/\")\n\t\trr.VCS = []string{\"git\"}\n\n\t\treturn\n\n\t\/\/case glpRegex.MatchString(path):\n\t\/\/\/\/ TODO too many rules for this, commenting out for now\n\t\/\/v := lpRegex.FindStringSubmatch(path)\n\n\t\/\/rr.CloneURL.Host = \"launchpad.net\"\n\t\/\/rr.RelPkg = strings.TrimPrefix(v[3], \"\/\")\n\t\/\/rr.VCS = []string{\"git\"}\n\n\t\/\/v = append(v, \"\", \"\")\n\t\/\/if v[2] == \"\" {\n\t\/\/\/\/ launchpad.net\/project\"\n\t\/\/rr.Base = fmt.Sprintf(\"https:\/\/launchpad.net\/%v\", v[1])\n\t\/\/} else {\n\t\/\/\/\/ launchpad.net\/project\/series\"\n\t\/\/rr.Base = fmt.Sprintf(\"https:\/\/launchpad.net\/%s\/%s\", v[1], v[2])\n\t\/\/}\n\t\/\/return\n\n\t\/\/ try the general syntax\n\tcase genericRegex.MatchString(path):\n\t\tv := genericRegex.FindStringSubmatch(path)\n\t\tswitch v[5] {\n\t\tcase \"git\", \"hg\", \"bzr\":\n\t\t\tx := strings.SplitN(v[1], \"\/\", 2)\n\t\t\t\/\/ TODO is this actually correct for bzr?\n\t\t\trr.CloneURL.Host = x[0]\n\t\t\trr.CloneURL.Path = x[1]\n\t\t\trr.VCS = []string{v[5]}\n\t\t\trr.Base = v[1]\n\t\t\trr.RelPkg = strings.TrimPrefix(v[6], \"\/\")\n\t\t\treturn\n\t\tdefault:\n\t\t\treturn remoteRepo{}, fmt.Errorf(\"unknown repository type: %q\", v[5])\n\t\t}\n\t}\n\n\t\/\/ TODO use HTTP metadata to resolve vanity imports\n\treturn remoteRepo{}, fmt.Errorf(\"unable to deduct repository and source type for: %q\", path)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package rndrec is used to randomly select records from a pool based on their\n\/\/ relative weight. For example, if the relative weight of one record is 50, on\n\/\/ average it will be selected five times more often than a record with a\n\/\/ relative weight of 10. This is useful for generating plausible data sets for\n\/\/ testing purposes, for example names based on frequency or regions based on\n\/\/ population.\npackage rndrec\n\nimport (\n\t\"bytes\"\n\t\"encoding\/csv\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"\n)\n\nvar reIntDelimiter = regexp.MustCompile(\"[,_]\")\n\ntype recType struct {\n\t\/\/ cumulative frequency\n\tcf float64\n\t\/\/ list of record fields\n\tfields []string\n}\n\n\/\/ SrcType is used to generate plausible random records based on a list of\n\/\/ weighted records.\ntype SrcType struct {\n\t\/\/ list of records with ascending cumulative frequency\n\tlist []recType\n\t\/\/ maximum cumulative frequency\n\tcfMax float64\n\t\/\/ random number generator\n\trand *rand.Rand\n}\n\n\/\/ String implements the fmt.Stringer interface\nfunc (r SrcType) String() string {\n\tvar b bytes.Buffer\n\tfmt.Fprintf(&b, \"Cumulative frequency maximum: %.2f\\n\", r.cfMax)\n\tfor j, rec := range r.list {\n\t\tfmt.Fprintf(&b, \"%2d: [%10.2f] %v\\n\", j, rec.cf, rec.fields)\n\t}\n\treturn b.String()\n}\n\n\/\/ NewRandomRecordSource processes a list of multi-field records in which each\n\/\/ field is a string. With one exception, one column must be an integer weight.\n\/\/ In this column, specified by weightColPos, each occurrence of an underscore,\n\/\/ comma or period is removed and the remaining string is parsed as an integer.\n\/\/ The values in this column are relative weights; that is, a record that has a\n\/\/ weight twice that of some other record will be selected by Record() on\n\/\/ average twice as often. The sum of these weights does not have to be any\n\/\/ special value. The exception to the requirement that one field be a weight\n\/\/ is when all records are weighted equally. In this case, weightColPos can be\n\/\/ set to -1 and records do not need to have a weight column. Records returned\n\/\/ by the Record() method depend on a local pseudo-random number generator;\n\/\/ seed is used to seed this generator. If any value in the column specified by\n\/\/ weightColPos can not be parsed as an integer, or the cumulative value of\n\/\/ weights is zero, or the number of records is zero, an error is returned.\n\/\/ Otherwise, err is nil and src may be used to retrieve records that are\n\/\/ distributed according to their relative weights.\nfunc NewRandomRecordSource(recs [][]string, weightColPos int, seed int64) (src *SrcType, err error) {\n\tvar rec recType\n\tvar weight string\n\tsrc = new(SrcType)\n\tfor _, fields := range recs {\n\t\tif err == nil {\n\t\t\tif weightColPos == -1 {\n\t\t\t\trec.cf = 1\n\t\t\t} else if weightColPos >= 0 && weightColPos < len(fields) {\n\t\t\t\tweight = fields[weightColPos]\n\t\t\t\trec.cf, err = strconv.ParseFloat(reIntDelimiter.ReplaceAllString(weight, \"\"), 64)\n\t\t\t\t\/\/ rec.cf, err = strconv.ParseInt(reIntDelimiter.ReplaceAllString(weight, \"\"), 10, 64)\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"specified weight column (%d) is out of range\", weightColPos)\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\trec.fields = fields\n\t\t\t\tsrc.list = append(src.list, rec)\n\t\t\t}\n\t\t}\n\t}\n\tif err == nil {\n\t\tif len(src.list) > 0 {\n\t\t\tfor j, rec := range src.list {\n\t\t\t\tsrc.cfMax += rec.cf\n\t\t\t\tsrc.list[j].cf = src.cfMax\n\t\t\t}\n\t\t\tif src.cfMax > 0 {\n\t\t\t\tsrc.rand = rand.New(rand.NewSource(seed))\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"cumulative frequency must be greater than zero\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"number of records must be greater than zero\")\n\t\t}\n\t}\n\tif err != nil {\n\t\tsrc = nil\n\t}\n\treturn\n}\n\n\/\/ NewRandomRecordSourceFromReader processes a list of multi-field records in\n\/\/ the form of a comma-separated-value buffer that can be read with the\n\/\/ io.Reader r. Each record must be separated by a newline. Each field is\n\/\/ separated by the value specified by fieldSep. For more information on the\n\/\/ return value and the other arguments, see NewRandomRecordSource().\nfunc NewRandomRecordSourceFromReader(r io.Reader, weightColPos int, fieldSep rune, seed int64) (src *SrcType, err error) {\n\tvar rdr *csv.Reader\n\tvar recs [][]string\n\trdr = csv.NewReader(r)\n\trdr.Comma = fieldSep\n\trecs, err = rdr.ReadAll()\n\tif err == nil {\n\t\tsrc, err = NewRandomRecordSource(recs, weightColPos, seed)\n\t}\n\treturn\n}\n\n\/\/ NewRandomRecordSourceFromFile processes a list of multi-field records in the\n\/\/ form of a comma-separated-value file with the filename specified by fileStr.\n\/\/ Each record must be separated by a newline. Each field is separated by the\n\/\/ value specified by fieldSep. For more information on the return value and\n\/\/ the other arguments, see NewRandomRecordSource().\nfunc NewRandomRecordSourceFromFile(fileStr string, weightColPos int, fieldSep rune, seed int64) (src *SrcType, err error) {\n\tvar f *os.File\n\tf, err = os.Open(fileStr)\n\tif err == nil {\n\t\tsrc, err = NewRandomRecordSourceFromReader(f, weightColPos, fieldSep, seed)\n\t\tf.Close()\n\t}\n\treturn\n}\n\n\/\/ Record returns a random record based on its relative weight. For example, a\n\/\/ record with a relative weight of 40 will be returned, on average, four times\n\/\/ as often as a record with the relative weight of 10. The returned record\n\/\/ will be in the form of a slice of strings taken directly from the original\n\/\/ list used to initialize the SrcType instance.\nfunc (r *SrcType) Record() []string {\n\tvar cf float64\n\tvar pos int\n\tcf = r.rand.Float64() * r.cfMax \/\/ 0 <= cf < r.cfMax\n\tpos = sort.Search(len(r.list), func(j int) bool {\n\t\treturn r.list[j].cf > cf\n\t})\n\treturn r.list[pos].fields\n}\n<commit_msg>Correct documentation regarding ignored characters in weight value<commit_after>\/\/ Package rndrec is used to randomly select records from a pool based on their\n\/\/ relative weight. For example, if the relative weight of one record is 50, on\n\/\/ average it will be selected five times more often than a record with a\n\/\/ relative weight of 10. This is useful for generating plausible data sets for\n\/\/ testing purposes, for example names based on frequency or regions based on\n\/\/ population.\npackage rndrec\n\nimport (\n\t\"bytes\"\n\t\"encoding\/csv\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"\n)\n\nvar reIntDelimiter = regexp.MustCompile(\"[,_]\")\n\ntype recType struct {\n\t\/\/ cumulative frequency\n\tcf float64\n\t\/\/ list of record fields\n\tfields []string\n}\n\n\/\/ SrcType is used to generate plausible random records based on a list of\n\/\/ weighted records.\ntype SrcType struct {\n\t\/\/ list of records with ascending cumulative frequency\n\tlist []recType\n\t\/\/ maximum cumulative frequency\n\tcfMax float64\n\t\/\/ random number generator\n\trand *rand.Rand\n}\n\n\/\/ String implements the fmt.Stringer interface\nfunc (r SrcType) String() string {\n\tvar b bytes.Buffer\n\tfmt.Fprintf(&b, \"Cumulative frequency maximum: %.2f\\n\", r.cfMax)\n\tfor j, rec := range r.list {\n\t\tfmt.Fprintf(&b, \"%2d: [%10.2f] %v\\n\", j, rec.cf, rec.fields)\n\t}\n\treturn b.String()\n}\n\n\/\/ NewRandomRecordSource processes a list of multi-field records in which each\n\/\/ field is a string. With one exception, one column must be an integer weight.\n\/\/ In this column, specified by weightColPos, each occurrence of an underscore\n\/\/ or comma is removed and the remaining string is parsed as an integer. The\n\/\/ values in this column are relative weights; that is, a record that has a\n\/\/ weight twice that of some other record will be selected by Record() on\n\/\/ average twice as often. The sum of these weights does not have to be any\n\/\/ special value. The exception to the requirement that one field be a weight\n\/\/ is when all records are weighted equally. In this case, weightColPos can be\n\/\/ set to -1 and records do not need to have a weight column. Records returned\n\/\/ by the Record() method depend on a local pseudo-random number generator;\n\/\/ seed is used to seed this generator. If any value in the column specified by\n\/\/ weightColPos can not be parsed as an integer, or the cumulative value of\n\/\/ weights is zero, or the number of records is zero, an error is returned.\n\/\/ Otherwise, err is nil and src may be used to retrieve records that are\n\/\/ distributed according to their relative weights.\nfunc NewRandomRecordSource(recs [][]string, weightColPos int, seed int64) (src *SrcType, err error) {\n\tvar rec recType\n\tvar weight string\n\tsrc = new(SrcType)\n\tfor _, fields := range recs {\n\t\tif err == nil {\n\t\t\tif weightColPos == -1 {\n\t\t\t\trec.cf = 1\n\t\t\t} else if weightColPos >= 0 && weightColPos < len(fields) {\n\t\t\t\tweight = fields[weightColPos]\n\t\t\t\trec.cf, err = strconv.ParseFloat(reIntDelimiter.ReplaceAllString(weight, \"\"), 64)\n\t\t\t\t\/\/ rec.cf, err = strconv.ParseInt(reIntDelimiter.ReplaceAllString(weight, \"\"), 10, 64)\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"specified weight column (%d) is out of range\", weightColPos)\n\t\t\t}\n\t\t\tif err == nil {\n\t\t\t\trec.fields = fields\n\t\t\t\tsrc.list = append(src.list, rec)\n\t\t\t}\n\t\t}\n\t}\n\tif err == nil {\n\t\tif len(src.list) > 0 {\n\t\t\tfor j, rec := range src.list {\n\t\t\t\tsrc.cfMax += rec.cf\n\t\t\t\tsrc.list[j].cf = src.cfMax\n\t\t\t}\n\t\t\tif src.cfMax > 0 {\n\t\t\t\tsrc.rand = rand.New(rand.NewSource(seed))\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"cumulative frequency must be greater than zero\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = fmt.Errorf(\"number of records must be greater than zero\")\n\t\t}\n\t}\n\tif err != nil {\n\t\tsrc = nil\n\t}\n\treturn\n}\n\n\/\/ NewRandomRecordSourceFromReader processes a list of multi-field records in\n\/\/ the form of a comma-separated-value buffer that can be read with the\n\/\/ io.Reader r. Each record must be separated by a newline. Each field is\n\/\/ separated by the value specified by fieldSep. For more information on the\n\/\/ return value and the other arguments, see NewRandomRecordSource().\nfunc NewRandomRecordSourceFromReader(r io.Reader, weightColPos int, fieldSep rune, seed int64) (src *SrcType, err error) {\n\tvar rdr *csv.Reader\n\tvar recs [][]string\n\trdr = csv.NewReader(r)\n\trdr.Comma = fieldSep\n\trecs, err = rdr.ReadAll()\n\tif err == nil {\n\t\tsrc, err = NewRandomRecordSource(recs, weightColPos, seed)\n\t}\n\treturn\n}\n\n\/\/ NewRandomRecordSourceFromFile processes a list of multi-field records in the\n\/\/ form of a comma-separated-value file with the filename specified by fileStr.\n\/\/ Each record must be separated by a newline. Each field is separated by the\n\/\/ value specified by fieldSep. For more information on the return value and\n\/\/ the other arguments, see NewRandomRecordSource().\nfunc NewRandomRecordSourceFromFile(fileStr string, weightColPos int, fieldSep rune, seed int64) (src *SrcType, err error) {\n\tvar f *os.File\n\tf, err = os.Open(fileStr)\n\tif err == nil {\n\t\tsrc, err = NewRandomRecordSourceFromReader(f, weightColPos, fieldSep, seed)\n\t\tf.Close()\n\t}\n\treturn\n}\n\n\/\/ Record returns a random record based on its relative weight. For example, a\n\/\/ record with a relative weight of 40 will be returned, on average, four times\n\/\/ as often as a record with the relative weight of 10. The returned record\n\/\/ will be in the form of a slice of strings taken directly from the original\n\/\/ list used to initialize the SrcType instance.\nfunc (r *SrcType) Record() []string {\n\tvar cf float64\n\tvar pos int\n\tcf = r.rand.Float64() * r.cfMax \/\/ 0 <= cf < r.cfMax\n\tpos = sort.Search(len(r.list), func(j int) bool {\n\t\treturn r.list[j].cf > cf\n\t})\n\treturn r.list[pos].fields\n}\n<|endoftext|>"}
{"text":"<commit_before>package gocli\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype Router struct {\n\tActions   map[string]*Action\n\tSeparator string\n\tWriter    io.Writer\n}\n\nfunc NewRouter(mapping map[string]*Action) *Router {\n\trouter := &Router{}\n\tfor path, action := range mapping {\n\t\trouter.Register(path, action)\n\t}\n\treturn router\n}\n\nfunc (cli *Router) Register(path string, action *Action) {\n\tif cli.Actions == nil {\n\t\tcli.Actions = make(map[string]*Action)\n\t}\n\tcli.Actions[path] = action\n}\n\nfunc (router *Router) matchKey(patterns []string, key string) bool {\n\tkeyParts := strings.Split(key, \"\/\")\n\tfor i, pattern := range patterns {\n\t\tif i > (len(keyParts) - 1) {\n\t\t\treturn false\n\t\t}\n\t\tif !strings.HasPrefix(keyParts[i], pattern) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (router *Router) Search(patterns []string) map[string]*Action {\n\tactions := make(map[string]*Action)\n\tfor key, action := range router.Actions {\n\t\tif router.matchKey(patterns, key) {\n\t\t\tactions[key] = action\n\t\t}\n\t}\n\treturn actions\n}\n\nfunc (cli *Router) Usage() string {\n\tkeys := []string{}\n\tfor key := range cli.Actions {\n\t\tkeys = append(keys, key)\n\t}\n\treturn cli.UsageForKeys(keys, \"\")\n}\n\nfunc (cli *Router) UsageForKeys(keys []string, pattern string) string {\n\tsort.Strings(keys)\n\ttable := NewTable()\n\tif cli.Separator != \"\" {\n\t\ttable.Separator = cli.Separator\n\t}\n\tmaxParts := 0\n\tselected := []string{}\n\tfor _, key := range keys {\n\t\tpartsCount := len(strings.Split(key, \"\/\"))\n\t\tif partsCount > maxParts {\n\t\t\tmaxParts = partsCount\n\t\t}\n\t\tselected = append(selected, key)\n\t}\n\tfor _, key := range selected {\n\t\tparts := strings.Split(key, \"\/\")\n\t\taction := cli.Actions[key]\n\n\t\t\/\/ fill up parts\n\t\tfor i := (maxParts - len(parts)); i > 0; i-- {\n\t\t\tparts = append(parts, \"\")\n\t\t}\n\n\t\tparts = append(parts, action.Usage, action.Description)\n\t\ttable.AddStrings(parts)\n\t\tif action.Args != nil {\n\t\t\tusage := action.Args.Usage()\n\t\t\tif usage != \"\" {\n\t\t\t\tlines := strings.Split(usage, \"\\n\")\n\t\t\t\tfor _, line := range lines {\n\t\t\t\t\tusageParts := []string{}\n\t\t\t\t\tfor j := 0; j < 3; j++ {\n\t\t\t\t\t\tusageParts = append(usageParts, \"\")\n\t\t\t\t\t}\n\t\t\t\t\tcurrent := append(usageParts, line)\n\t\t\t\t\ttable.AddStrings(current)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tout := []string{\"USAGE\"}\n\tout = append(out, table.String())\n\treturn strings.Join(out, \"\\n\")\n}\n\nfunc AddActionUsage(parts []string, table *Table, action *Action) {\n\tparts = append(parts, action.Usage, action.Description)\n\ttable.AddStrings(parts)\n\tif action.Args != nil {\n\t\tusage := action.Args.Usage()\n\t\tif usage != \"\" {\n\t\t\tlines := strings.Split(usage, \"\\n\")\n\t\t\tfor _, line := range lines {\n\t\t\t\tusageParts := []string{}\n\t\t\t\tfor j := 0; j < 3; j++ {\n\t\t\t\t\tusageParts = append(usageParts, \"\")\n\t\t\t\t}\n\t\t\t\tcurrent := append(usageParts, line)\n\t\t\t\ttable.AddStrings(current)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (router *Router) printActionUsage(parts []string, action *Action, message interface{}) {\n\ttable := NewTable()\n\tfmt.Println(\"ERROR:\", message)\n\tAddActionUsage(parts, table, action)\n\trouter.Println(table.String())\n\tos.Exit(1)\n}\n\nfunc (router *Router) Println(a ...interface{}) {\n\twriter := router.Writer\n\tif writer == nil {\n\t\twriter = os.Stdout\n\t}\n\tfmt.Fprintln(writer, a...)\n}\n\nfunc (cli *Router) Handle(raw []string) error {\n\tfor i := len(raw); i > 0; i-- {\n\t\tparts := raw[1:i]\n\t\tactions := cli.Search(parts)\n\t\tswitch len(actions) {\n\t\tcase 0:\n\t\t\tcontinue\n\t\tcase 1:\n\t\t\tvar action *Action\n\t\t\tfor k, a := range actions {\n\t\t\t\tparts = strings.Split(k, \"\/\")\n\t\t\t\taction = a\n\t\t\t}\n\t\t\tdefer func(parts []string, action *Action) {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tcli.printActionUsage(parts, action, r)\n\t\t\t\t}\n\t\t\t}(parts, action)\n\t\t\targs := action.Args\n\t\t\tif args == nil {\n\t\t\t\targs = &Args{}\n\t\t\t}\n\t\t\te := args.Parse(raw[i:])\n\t\t\tif e == nil {\n\t\t\t\te = action.Handler(args)\n\t\t\t}\n\t\t\tif e != nil {\n\t\t\t\tcli.printActionUsage(parts, action, e.Error())\n\t\t\t}\n\t\t\treturn nil\n\t\tdefault:\n\t\t\t\/\/ multiple actions count => print help for them\n\t\t\tkeys := []string{}\n\t\t\tfor key, _ := range actions {\n\t\t\t\tkeys = append(keys, key)\n\t\t\t}\n\t\t\tcli.Println(cli.UsageForKeys(keys, \"\"))\n\t\t\treturn nil\n\n\t\t}\n\t}\n\tcli.Println(cli.Usage())\n\treturn nil\n}\n<commit_msg>don't panic when DEBUG is true<commit_after>package gocli\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype Router struct {\n\tActions   map[string]*Action\n\tSeparator string\n\tWriter    io.Writer\n}\n\nfunc NewRouter(mapping map[string]*Action) *Router {\n\trouter := &Router{}\n\tfor path, action := range mapping {\n\t\trouter.Register(path, action)\n\t}\n\treturn router\n}\n\nfunc (cli *Router) Register(path string, action *Action) {\n\tif cli.Actions == nil {\n\t\tcli.Actions = make(map[string]*Action)\n\t}\n\tcli.Actions[path] = action\n}\n\nfunc (router *Router) matchKey(patterns []string, key string) bool {\n\tkeyParts := strings.Split(key, \"\/\")\n\tfor i, pattern := range patterns {\n\t\tif i > (len(keyParts) - 1) {\n\t\t\treturn false\n\t\t}\n\t\tif !strings.HasPrefix(keyParts[i], pattern) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (router *Router) Search(patterns []string) map[string]*Action {\n\tactions := make(map[string]*Action)\n\tfor key, action := range router.Actions {\n\t\tif router.matchKey(patterns, key) {\n\t\t\tactions[key] = action\n\t\t}\n\t}\n\treturn actions\n}\n\nfunc (cli *Router) Usage() string {\n\tkeys := []string{}\n\tfor key := range cli.Actions {\n\t\tkeys = append(keys, key)\n\t}\n\treturn cli.UsageForKeys(keys, \"\")\n}\n\nfunc (cli *Router) UsageForKeys(keys []string, pattern string) string {\n\tsort.Strings(keys)\n\ttable := NewTable()\n\tif cli.Separator != \"\" {\n\t\ttable.Separator = cli.Separator\n\t}\n\tmaxParts := 0\n\tselected := []string{}\n\tfor _, key := range keys {\n\t\tpartsCount := len(strings.Split(key, \"\/\"))\n\t\tif partsCount > maxParts {\n\t\t\tmaxParts = partsCount\n\t\t}\n\t\tselected = append(selected, key)\n\t}\n\tfor _, key := range selected {\n\t\tparts := strings.Split(key, \"\/\")\n\t\taction := cli.Actions[key]\n\n\t\t\/\/ fill up parts\n\t\tfor i := (maxParts - len(parts)); i > 0; i-- {\n\t\t\tparts = append(parts, \"\")\n\t\t}\n\n\t\tparts = append(parts, action.Usage, action.Description)\n\t\ttable.AddStrings(parts)\n\t\tif action.Args != nil {\n\t\t\tusage := action.Args.Usage()\n\t\t\tif usage != \"\" {\n\t\t\t\tlines := strings.Split(usage, \"\\n\")\n\t\t\t\tfor _, line := range lines {\n\t\t\t\t\tusageParts := []string{}\n\t\t\t\t\tfor j := 0; j < 3; j++ {\n\t\t\t\t\t\tusageParts = append(usageParts, \"\")\n\t\t\t\t\t}\n\t\t\t\t\tcurrent := append(usageParts, line)\n\t\t\t\t\ttable.AddStrings(current)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tout := []string{\"USAGE\"}\n\tout = append(out, table.String())\n\treturn strings.Join(out, \"\\n\")\n}\n\nfunc AddActionUsage(parts []string, table *Table, action *Action) {\n\tparts = append(parts, action.Usage, action.Description)\n\ttable.AddStrings(parts)\n\tif action.Args != nil {\n\t\tusage := action.Args.Usage()\n\t\tif usage != \"\" {\n\t\t\tlines := strings.Split(usage, \"\\n\")\n\t\t\tfor _, line := range lines {\n\t\t\t\tusageParts := []string{}\n\t\t\t\tfor j := 0; j < 3; j++ {\n\t\t\t\t\tusageParts = append(usageParts, \"\")\n\t\t\t\t}\n\t\t\t\tcurrent := append(usageParts, line)\n\t\t\t\ttable.AddStrings(current)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (router *Router) printActionUsage(parts []string, action *Action, message interface{}) {\n\ttable := NewTable()\n\tfmt.Println(\"ERROR:\", message)\n\tAddActionUsage(parts, table, action)\n\trouter.Println(table.String())\n\tos.Exit(1)\n}\n\nfunc (router *Router) Println(a ...interface{}) {\n\twriter := router.Writer\n\tif writer == nil {\n\t\twriter = os.Stdout\n\t}\n\tfmt.Fprintln(writer, a...)\n}\n\nfunc (cli *Router) Handle(raw []string) error {\n\tfor i := len(raw); i > 0; i-- {\n\t\tparts := raw[1:i]\n\t\tactions := cli.Search(parts)\n\t\tswitch len(actions) {\n\t\tcase 0:\n\t\t\tcontinue\n\t\tcase 1:\n\t\t\tvar action *Action\n\t\t\tfor k, a := range actions {\n\t\t\t\tparts = strings.Split(k, \"\/\")\n\t\t\t\taction = a\n\t\t\t}\n\t\t\tif os.Getenv(\"DEBUG\") != \"true\" {\n\t\t\t\tdefer func(parts []string, action *Action) {\n\t\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\t\tcli.printActionUsage(parts, action, r)\n\t\t\t\t\t}\n\t\t\t\t}(parts, action)\n\t\t\t}\n\t\t\targs := action.Args\n\t\t\tif args == nil {\n\t\t\t\targs = &Args{}\n\t\t\t}\n\t\t\te := args.Parse(raw[i:])\n\t\t\tif e == nil {\n\t\t\t\te = action.Handler(args)\n\t\t\t}\n\t\t\tif e != nil {\n\t\t\t\tcli.printActionUsage(parts, action, e.Error())\n\t\t\t}\n\t\t\treturn nil\n\t\tdefault:\n\t\t\t\/\/ multiple actions count => print help for them\n\t\t\tkeys := []string{}\n\t\t\tfor key, _ := range actions {\n\t\t\t\tkeys = append(keys, key)\n\t\t\t}\n\t\t\tcli.Println(cli.UsageForKeys(keys, \"\"))\n\t\t\treturn nil\n\n\t\t}\n\t}\n\tcli.Println(cli.Usage())\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package router\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\/\/ Params map path keys to values.  For example, if your route has the path pattern:\n\/\/  \/person\/:person_id\/pets\/:pet_type\n\/\/ Then a correct Params map would lool like:\n\/\/  router.Params{\n\/\/    \"person_id\": \"123\",\n\/\/    \"pet_type\": \"cats\",\n\/\/  }\ntype Params map[string]string\n\n\/\/ A Route defines properites of an HTTP endpoint.  At runtime, the router will\n\/\/ associate each Route with a http.Handler object, and use the Route properites\n\/\/ to determine which Handler should be invoked.\n\/\/\n\/\/ Currently, properies used in match are such as Method and Path.\n\/\/\n\/\/ Method is one of the following:\n\/\/  GET PUT POST DELETE\n\/\/\n\/\/ Path conforms to Pat-style pattern matching. The following docs are taken from\n\/\/ http:\/\/godoc.org\/github.com\/bmizerany\/pat#PatternServeMux\n\/\/\n\/\/ Path Patterns may contain literals or captures. Capture names start with a colon\n\/\/ and consist of letters A-Z, a-z, _, and 0-9. The rest of the pattern\n\/\/ matches literally. The portion of the URL matching each name ends with an\n\/\/ occurrence of the character in the pattern immediately following the name,\n\/\/ or a \/, whichever comes first. It is possible for a name to match the empty\n\/\/ string.\n\/\/\n\/\/ Example pattern with one capture:\n\/\/   \/hello\/:name\n\/\/ Will match:\n\/\/   \/hello\/blake\n\/\/   \/hello\/keith\n\/\/ Will not match:\n\/\/   \/hello\/blake\/\n\/\/   \/hello\/blake\/foo\n\/\/   \/foo\n\/\/   \/foo\/bar\n\/\/\n\/\/ Example 2:\n\/\/    \/hello\/:name\/\n\/\/ Will match:\n\/\/   \/hello\/blake\/\n\/\/   \/hello\/keith\/foo\n\/\/   \/hello\/blake\n\/\/   \/hello\/keith\n\/\/ Will not match:\n\/\/   \/foo\n\/\/   \/foo\/bar\ntype Route struct {\n\t\/\/ Handler is a key specifying which HTTP handler the router\n\t\/\/ should associate with the endpoint at runtime.\n\tHandler string\n\t\/\/ Method is one of the following: GET,PUT,POST,DELETE\n\tMethod string\n\t\/\/ Path contains a path pattern\n\tPath string\n}\n\n\/\/ PathWithParams combines the route's path pattern with a Params map\n\/\/ to produce a valid path.\nfunc (r Route) PathWithParams(params Params) (string, error) {\n\tcomponents := strings.Split(r.Path, \"\/\")\n\tfor i, c := range components {\n\t\tif len(c) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif c[0] == ':' {\n\t\t\tval, ok := params[c[1:]]\n\t\t\tif !ok {\n\t\t\t\treturn \"\", fmt.Errorf(\"missing param %s\", c)\n\t\t\t}\n\t\t\tcomponents[i] = val\n\t\t}\n\t}\n\n\tu, err := url.Parse(strings.Join(components, \"\/\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn u.String(), nil\n}\n\n\/\/ Routes is a Route collection.\ntype Routes []Route\n\n\/\/ RouteForHandler looks up a Route by it's Handler key.\nfunc (r Routes) RouteForHandler(handler string) (Route, bool) {\n\tfor _, route := range r {\n\t\tif route.Handler == handler {\n\t\t\treturn route, true\n\t\t}\n\t}\n\treturn Route{}, false\n}\n\n\/\/ PathForHandler looks up a Route by it's Handler key and computes it's path\n\/\/ with a given Params map.\nfunc (r Routes) PathForHandler(handler string, params Params) (string, error) {\n\troute, ok := r.RouteForHandler(handler)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"No route exists for handler %\", handler)\n\t}\n\treturn route.PathWithParams(params)\n}\n\n\/\/ Router is deprecated, please use router.NewRouter() instead\nfunc (r Routes) Router(handlers Handlers) (http.Handler, error) {\n\t_, file, line, _ := runtime.Caller(1)\n\tfmt.Printf(\"\\n\\033[0;35m%s\\033[0m%s:%d:%s\\n\", \"WARNING:\", file, line, \" Routes.Router() is deprecated, please use router.NewRouter() instead\")\n\treturn NewRouter(r, handlers)\n}\n<commit_msg>RequestForHandler creates an http Request for a given Route and Params<commit_after>package router\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"runtime\"\n\t\"strings\"\n\t\"io\"\n)\n\n\/\/ Params map path keys to values.  For example, if your route has the path pattern:\n\/\/  \/person\/:person_id\/pets\/:pet_type\n\/\/ Then a correct Params map would lool like:\n\/\/  router.Params{\n\/\/    \"person_id\": \"123\",\n\/\/    \"pet_type\": \"cats\",\n\/\/  }\ntype Params map[string]string\n\n\/\/ A Route defines properites of an HTTP endpoint.  At runtime, the router will\n\/\/ associate each Route with a http.Handler object, and use the Route properites\n\/\/ to determine which Handler should be invoked.\n\/\/\n\/\/ Currently, properies used in match are such as Method and Path.\n\/\/\n\/\/ Method is one of the following:\n\/\/  GET PUT POST DELETE\n\/\/\n\/\/ Path conforms to Pat-style pattern matching. The following docs are taken from\n\/\/ http:\/\/godoc.org\/github.com\/bmizerany\/pat#PatternServeMux\n\/\/\n\/\/ Path Patterns may contain literals or captures. Capture names start with a colon\n\/\/ and consist of letters A-Z, a-z, _, and 0-9. The rest of the pattern\n\/\/ matches literally. The portion of the URL matching each name ends with an\n\/\/ occurrence of the character in the pattern immediately following the name,\n\/\/ or a \/, whichever comes first. It is possible for a name to match the empty\n\/\/ string.\n\/\/\n\/\/ Example pattern with one capture:\n\/\/   \/hello\/:name\n\/\/ Will match:\n\/\/   \/hello\/blake\n\/\/   \/hello\/keith\n\/\/ Will not match:\n\/\/   \/hello\/blake\/\n\/\/   \/hello\/blake\/foo\n\/\/   \/foo\n\/\/   \/foo\/bar\n\/\/\n\/\/ Example 2:\n\/\/    \/hello\/:name\/\n\/\/ Will match:\n\/\/   \/hello\/blake\/\n\/\/   \/hello\/keith\/foo\n\/\/   \/hello\/blake\n\/\/   \/hello\/keith\n\/\/ Will not match:\n\/\/   \/foo\n\/\/   \/foo\/bar\ntype Route struct {\n\t\/\/ Handler is a key specifying which HTTP handler the router\n\t\/\/ should associate with the endpoint at runtime.\n\tHandler string\n\t\/\/ Method is one of the following: GET,PUT,POST,DELETE\n\tMethod string\n\t\/\/ Path contains a path pattern\n\tPath string\n}\n\n\/\/ PathWithParams combines the route's path pattern with a Params map\n\/\/ to produce a valid path.\nfunc (r Route) PathWithParams(params Params) (string, error) {\n\tcomponents := strings.Split(r.Path, \"\/\")\n\tfor i, c := range components {\n\t\tif len(c) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif c[0] == ':' {\n\t\t\tval, ok := params[c[1:]]\n\t\t\tif !ok {\n\t\t\t\treturn \"\", fmt.Errorf(\"missing param %s\", c)\n\t\t\t}\n\t\t\tcomponents[i] = val\n\t\t}\n\t}\n\n\tu, err := url.Parse(strings.Join(components, \"\/\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn u.String(), nil\n}\n\n\/\/ Routes is a Route collection.\ntype Routes []Route\n\n\/\/ RouteForHandler looks up a Route by it's Handler key.\nfunc (r Routes) RouteForHandler(handler string) (Route, bool) {\n\tfor _, route := range r {\n\t\tif route.Handler == handler {\n\t\t\treturn route, true\n\t\t}\n\t}\n\treturn Route{}, false\n}\n\n\/\/ PathForHandler looks up a Route by it's Handler key and computes it's path\n\/\/ with a given Params map.\nfunc (r Routes) PathForHandler(handler string, params Params) (string, error) {\n\troute, ok := r.RouteForHandler(handler)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"No route exists for handler %\", handler)\n\t}\n\treturn route.PathWithParams(params)\n}\n\n\/\/ RequestForHandler creates an http Request for a given Route and Params\nfunc (r Routes) RequestForHandler(handler string, params Params, body io.Reader) (*http.Request, error) {\n\troute, ok := r.RouteForHandler(handler)\n\tif !ok {\n\t\treturn &http.Request{}, fmt.Errorf(\"No route exists for handler %\", handler)\n\t}\n\tpath, err := route.PathWithParams(params)\n\tif err != nil {\n\t\treturn &http.Request{},err\n\t}\n\treturn  http.NewRequest(route.Method,path,body)\n}\n\n\/\/ Router is deprecated, please use router.NewRouter() instead\nfunc (r Routes) Router(handlers Handlers) (http.Handler, error) {\n\t_, file, line, _ := runtime.Caller(1)\n\tfmt.Printf(\"\\n\\033[0;35m%s\\033[0m%s:%d:%s\\n\", \"WARNING:\", file, line, \" Routes.Router() is deprecated, please use router.NewRouter() instead\")\n\treturn NewRouter(r, handlers)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"database\/sql\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"syscall\"\n\t\"text\/template\"\n\t\"time\"\n\n\tda \"github.com\/flynn\/discoverd\/agent\"\n\t\"github.com\/flynn\/go-discoverd\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nvar dataDir = flag.String(\"data\", \"\/data\", \"postgresql data directory\")\nvar serviceName = flag.String(\"service\", \"pg\", \"discoverd service name\")\nvar pgbin = flag.String(\"pgbin\", \"\/usr\/lib\/postgresql\/9.3\/bin\/\", \"postgres binary directory\")\nvar addr = \":\" + os.Getenv(\"PORT\")\n\nfunc main() {\n\tflag.Parse()\n\n\tset, err := discoverd.RegisterWithSet(*serviceName, addr, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar username, password string\n\tvar follower *follower\n\tvar leader *exec.Cmd\n\tvar done <-chan struct{}\n\tfor l := range set.Leaders() {\n\t\tif l.Attrs[\"username\"] != \"\" && l.Attrs[\"password\"] != \"\" {\n\t\t\tusername, password = l.Attrs[\"username\"], l.Attrs[\"password\"]\n\t\t}\n\t\tif l.Addr == set.SelfAddr() {\n\t\t\tif follower == nil {\n\t\t\t\tleader, done = startLeader()\n\t\t\t} else {\n\t\t\t\tleader, done = promoteToLeader(follower, username, password)\n\t\t\t}\n\t\t\tgoto wait\n\t\t} else {\n\t\t\tif follower == nil {\n\t\t\t\tfollower = startFollower(l, set)\n\t\t\t} else {\n\t\t\t\tfollower = switchLeader(l, set, follower)\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ TODO: handle service discovery disconnection\n\nwait:\n\tset.Close()\n\t<-done\n\tprocExit(leader)\n}\n\nfunc startLeader() (*exec.Cmd, <-chan struct{}) {\n\tlog.Println(\"Starting as leader...\")\n\tif err := dirIsEmpty(*dataDir); err == nil {\n\t\tlog.Println(\"Running initdb...\")\n\t\trunCmd(exec.Command(\n\t\t\tfilepath.Join(*pgbin, \"initdb\"),\n\t\t\t\"-D\", *dataDir,\n\t\t\t\"--encoding=UTF-8\",\n\t\t\t\"--locale=en_US.UTF-8\", \/\/ TODO: make this configurable?\n\t\t))\n\t} else if err != ErrNotEmpty {\n\t\tlog.Fatal(err)\n\t}\n\n\tcmd, err := startPostgres(*dataDir)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdb := waitForPostgres(time.Minute)\n\tpassword := createSuperuser(db)\n\tdb.Close()\n\tregister(map[string]string{\"username\": \"flynn\", \"password\": password, \"up\": \"true\"})\n\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tcmd.Wait()\n\t\tclose(done)\n\t}()\n\n\treturn cmd, done\n}\n\nfunc register(attrs map[string]string) {\n\terr := discoverd.RegisterWithAttributes(*serviceName, addr, attrs)\n\tif err != nil {\n\t\tlog.Fatalln(\"discoverd registration error:\", err)\n\t}\n}\n\nfunc procExit(cmd *exec.Cmd) {\n\tdiscoverd.UnregisterAll()\n\tvar status int\n\tif ws, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok {\n\t\tstatus = ws.ExitStatus()\n\t}\n\tos.Exit(status)\n}\n\nfunc createSuperuser(db *sql.DB) (password string) {\n\tlog.Println(\"Creating superuser...\")\n\tpassword = generatePassword()\n\n\t_, err := db.Exec(\"DROP USER IF EXISTS flynn\")\n\tif err != nil {\n\t\tlog.Fatalln(\"Error dropping user:\", err)\n\t}\n\t_, err = db.Exec(\"CREATE USER flynn WITH SUPERUSER CREATEDB CREATEROLE REPLICATION PASSWORD '\" + password + \"'\")\n\tif err != nil {\n\t\tlog.Fatalln(\"Error creating user:\", err)\n\t}\n\tlog.Println(\"Superuser created.\")\n\n\treturn\n}\n\nfunc generatePassword() string {\n\tb := make([]byte, 16)\n\tenc := make([]byte, 24)\n\t_, err := io.ReadFull(rand.Reader, b)\n\tif err != nil {\n\t\tpanic(err) \/\/ This shouldn't ever happen, right?\n\t}\n\tbase64.URLEncoding.Encode(enc, b)\n\treturn string(bytes.TrimRight(enc, \"=\"))\n}\n\nvar pgstr = \"user=postgres host=\/var\/run\/postgresql sslmode=disable port=\" + os.Getenv(\"PORT\")\n\nfunc waitForPostgres(maxWait time.Duration) *sql.DB {\n\tlog.Println(\"Waiting for postgres to boot...\")\n\tstart := time.Now()\n\tfor {\n\t\tvar ping string\n\t\tdb, err := sql.Open(\"postgres\", pgstr)\n\t\tif err != nil {\n\t\t\tgoto fail\n\t\t}\n\t\terr = db.QueryRow(\"SELECT 'ping'\").Scan(&ping)\n\t\tif ping == \"ping\" {\n\t\t\tlog.Println(\"Postgres is up.\")\n\t\t\treturn db\n\t\t}\n\t\tdb.Close()\n\n\tfail:\n\t\tif time.Now().Sub(start) >= maxWait {\n\t\t\tlog.Fatalf(\"Unable to connect to postgres after %s, last error: %q\", maxWait, err)\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n}\n\nfunc waitForPromotion() {\n\tlog.Println(\"Waiting for promotion...\")\n\tdb, err := sql.Open(\"postgres\", pgstr)\n\tif err != nil {\n\t\tlog.Fatalln(\"Error connecting to postgres:\", err)\n\t}\n\tdefer db.Close()\n\tfor {\n\t\tvar recovery bool\n\t\terr := db.QueryRow(\"SELECT pg_is_in_recovery()\").Scan(&recovery)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Error checking recovery status:\", err)\n\t\t}\n\t\tif !recovery {\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n}\n\nfunc promoteToLeader(follower *follower, username, password string) (*exec.Cmd, <-chan struct{}) {\n\tlog.Println(\"Promoting follower to leader...\")\n\tregister(map[string]string{\"up\": \"false\"})\n\tf, err := os.Create(filepath.Join(*dataDir, \"promote.trigger\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tf.Close()\n\n\twaitForPromotion()\n\n\tif username == \"\" || password == \"\" {\n\t\t\/\/ TODO: create superuser\n\t}\n\n\tregister(map[string]string{\"up\": \"true\", \"username\": username, \"password\": password})\n\tlog.Println(\"Follower promoted to leader.\")\n\treturn follower.Cancel()\n}\n\nfunc runCmd(cmd *exec.Cmd) {\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\tif exitErr, ok := err.(*exec.ExitError); ok {\n\t\t\tif status, ok := exitErr.Sys().(syscall.WaitStatus); ok {\n\t\t\t\tos.Exit(status.ExitStatus())\n\t\t\t}\n\t\t}\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc pullBaseBackup(s *discoverd.Service) {\n\tlog.Println(\"Running pg_basebackup...\")\n\trunCmd(exec.Command(\n\t\t\"pg_basebackup\",\n\t\t\"-D\", *dataDir,\n\t\t\"-d\", fmt.Sprintf(\"host=%s port=%s user=%s password=%s\", s.Host, s.Port, s.Attrs[\"username\"], s.Attrs[\"password\"]),\n\t\t\"--xlog-method=stream\",\n\t\t\"--progress\",\n\t\t\"--verbose\",\n\t))\n\tlog.Println(\"pg_basebackup complete.\")\n}\n\nvar recoveryTempl = template.Must(template.New(\"recovery\").Parse(`\nstandby_mode = 'on'\nprimary_conninfo = 'host={{.Host}} port={{.Port}} user={{.Username}} password={{.Password}}'\ntrigger_file = '{{.Trigger}}'\n`))\n\ntype recoveryConfig struct {\n\tHost     string\n\tPort     string\n\tUsername string\n\tPassword string\n\tTrigger  string\n}\n\nfunc writeRecoveryConf(dir string, leader *discoverd.Service) {\n\tf, err := os.Create(filepath.Join(dir, \"recovery.conf\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"Error creating recovery.conf:\", err)\n\t}\n\tdefer f.Close()\n\n\terr = recoveryTempl.Execute(f, &recoveryConfig{\n\t\tHost:     leader.Host,\n\t\tPort:     leader.Port,\n\t\tUsername: leader.Attrs[\"username\"],\n\t\tPassword: leader.Attrs[\"password\"],\n\t\tTrigger:  filepath.Join(dir, \"promote.trigger\"),\n\t})\n\tif err != nil {\n\t\tlog.Fatalln(\"Error writing recovery.conf:\", err)\n\t}\n}\n\nfunc updateToService(u *da.ServiceUpdate) *discoverd.Service {\n\thost, port, _ := net.SplitHostPort(u.Addr)\n\treturn &discoverd.Service{\n\t\tCreated: u.Created,\n\t\tName:    u.Name,\n\t\tAddr:    u.Addr,\n\t\tAttrs:   u.Attrs,\n\t\tHost:    host,\n\t\tPort:    port,\n\t}\n}\n\nfunc waitForLeaderUp(leader *discoverd.Service, set discoverd.ServiceSet) *discoverd.Service {\n\tif leader.Attrs[\"up\"] == \"true\" {\n\t\treturn leader\n\t}\n\tlog.Println(\"Waiting for leader to come up...\")\n\twatch := set.Watch(true, false)\n\tdefer set.Unwatch(watch)\n\tfor update := range watch {\n\t\tif update.Addr == set.Leader().Addr && update.Attrs[\"up\"] == \"true\" {\n\t\t\treturn updateToService(update)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc startFollower(leader *discoverd.Service, set discoverd.ServiceSet) *follower {\n\tlog.Println(\"Starting as follower...\")\n\tleader = waitForLeaderUp(leader, set)\n\tif err := dirIsEmpty(*dataDir); err == nil {\n\t\tpullBaseBackup(leader)\n\t} else if err != ErrNotEmpty {\n\t\tlog.Fatal(err)\n\t}\n\n\twriteRecoveryConf(*dataDir, leader)\n\tcmd, err := startPostgres(*dataDir)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\twaitForPostgres(time.Minute).Close()\n\tregister(map[string]string{\"up\": \"true\"})\n\tlog.Println(\"Follower started.\")\n\n\t\/\/ TODO: if data and insufficient WAL, pg_basebackup\n\treturn newFollower(cmd)\n}\n\nfunc switchLeader(leader *discoverd.Service, set discoverd.ServiceSet, follower *follower) *follower {\n\tlog.Println(\"Switching leaders...\")\n\tleader = waitForLeaderUp(leader, set)\n\tregister(map[string]string{\"up\": \"false\"})\n\twriteRecoveryConf(*dataDir, leader)\n\tfollower.Stop()\n\n\tcmd, err := startPostgres(*dataDir)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\twaitForPostgres(time.Minute).Close()\n\t\/\/ TODO: check for insufficient WAL, then pg_basebackup\n\tregister(map[string]string{\"up\": \"true\"})\n\tlog.Println(\"Leader switch complete.\")\n\treturn newFollower(cmd)\n}\n\nfunc newFollower(cmd *exec.Cmd) *follower {\n\tf := &follower{\n\t\tcmd:  cmd,\n\t\tstop: make(chan struct{}),\n\t\tdone: make(chan struct{}),\n\t}\n\tgo f.wait()\n\treturn f\n}\n\ntype follower struct {\n\tcmd  *exec.Cmd\n\tstop chan struct{}\n\tdone chan struct{}\n}\n\nfunc (f *follower) wait() {\n\tgo func() {\n\t\tf.cmd.Wait()\n\t\tclose(f.done)\n\t}()\n\n\tselect {\n\tcase <-f.done:\n\t\tprocExit(f.cmd)\n\tcase <-f.stop:\n\t}\n}\n\nfunc (f *follower) Cancel() (*exec.Cmd, <-chan struct{}) {\n\tclose(f.stop)\n\treturn f.cmd, f.done\n}\n\nfunc (f *follower) Stop() error {\n\tclose(f.stop)\n\tif err := f.cmd.Process.Signal(syscall.SIGTERM); err != nil {\n\t\treturn err\n\t}\n\t\/\/ TODO: escalate to kill?\n\t<-f.done\n\treturn nil\n}\n\nfunc writeConfig(dataDir string) {\n\terr := copyFile(\"\/etc\/postgresql\/9.3\/main\/postgresql.conf\", filepath.Join(dataDir, \"postgresql.conf\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"Error creating postgresql.conf\", err)\n\t}\n\n\terr = copyFile(\"\/etc\/postgresql\/9.3\/main\/pg_hba.conf\", filepath.Join(dataDir, \"pg_hba.conf\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"Error creating pg_hba.conf\", err)\n\t}\n}\n\nfunc copyFile(src, dest string) error {\n\tsf, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer sf.Close()\n\tdf, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer df.Close()\n\n\t_, err = io.Copy(df, sf)\n\treturn err\n}\n\nfunc startPostgres(dataDir string) (*exec.Cmd, error) {\n\twriteConfig(dataDir)\n\n\tlog.Println(\"Starting postgres...\")\n\tcmd := exec.Command(\n\t\tfilepath.Join(*pgbin, \"postgres\"),\n\t\t\"-D\", dataDir,\n\t\t\"-p\", os.Getenv(\"PORT\"),\n\t\t\"-h\", \"*\",\n\t)\n\tlog.Println(\"exec\", strings.Join(cmd.Args, \" \"))\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo handleSignals(cmd)\n\treturn cmd, nil\n}\n\nfunc handleSignals(cmd *exec.Cmd) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)\n\n\tsig := <-c\n\tdiscoverd.UnregisterAll()\n\tcmd.Process.Signal(sig)\n}\n\nvar ErrNotEmpty = errors.New(\"directory is not empty\")\n\nfunc dirIsEmpty(dir string) error {\n\td, err := os.Open(dir)\n\tif err != nil {\n\t\tif errno, ok := err.(syscall.Errno); ok && errno == syscall.ENOENT {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tdefer d.Close()\n\n\tfor {\n\t\tfs, err := d.Readdir(10)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tfor _, f := range fs {\n\t\t\tif !strings.HasPrefix(f.Name(), \".\") {\n\t\t\t\treturn ErrNotEmpty\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>Fix retrieval of password for follower<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"database\/sql\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"syscall\"\n\t\"text\/template\"\n\t\"time\"\n\n\tda \"github.com\/flynn\/discoverd\/agent\"\n\t\"github.com\/flynn\/go-discoverd\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nvar dataDir = flag.String(\"data\", \"\/data\", \"postgresql data directory\")\nvar serviceName = flag.String(\"service\", \"pg\", \"discoverd service name\")\nvar pgbin = flag.String(\"pgbin\", \"\/usr\/lib\/postgresql\/9.3\/bin\/\", \"postgres binary directory\")\nvar addr = \":\" + os.Getenv(\"PORT\")\n\nfunc main() {\n\tflag.Parse()\n\n\tset, err := discoverd.RegisterWithSet(*serviceName, addr, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar username, password string\n\tvar follower *follower\n\tvar leaderProc *exec.Cmd\n\tvar done <-chan struct{}\n\tvar leader *discoverd.Service\n\n\tif l := set.Leader(); l.Addr == set.SelfAddr() {\n\t\tleaderProc, done = startLeader()\n\t\tgoto wait\n\t}\n\n\tfor u := range set.Watch(true, false) {\n\t\tl := set.Leader()\n\t\tif u.Online && u.Addr == l.Addr && u.Attrs[\"username\"] != \"\" && u.Attrs[\"password\"] != \"\" {\n\t\t\tusername, password = u.Attrs[\"username\"], u.Attrs[\"password\"]\n\t\t}\n\t\tif leader != nil && l.Addr == leader.Addr {\n\t\t\tcontinue\n\t\t}\n\t\tleader = l\n\t\tif leader.Addr == set.SelfAddr() {\n\t\t\tleaderProc, done = promoteToLeader(follower, username, password)\n\t\t\tgoto wait\n\t\t} else {\n\t\t\tif follower == nil {\n\t\t\t\tfollower = startFollower(leader, set)\n\t\t\t} else {\n\t\t\t\tfollower = switchLeader(leader, set, follower)\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ TODO: handle service discovery disconnection\n\nwait:\n\tset.Close()\n\t<-done\n\tprocExit(leaderProc)\n}\n\nfunc startLeader() (*exec.Cmd, <-chan struct{}) {\n\tlog.Println(\"Starting as leader...\")\n\tif err := dirIsEmpty(*dataDir); err == nil {\n\t\tlog.Println(\"Running initdb...\")\n\t\trunCmd(exec.Command(\n\t\t\tfilepath.Join(*pgbin, \"initdb\"),\n\t\t\t\"-D\", *dataDir,\n\t\t\t\"--encoding=UTF-8\",\n\t\t\t\"--locale=en_US.UTF-8\", \/\/ TODO: make this configurable?\n\t\t))\n\t} else if err != ErrNotEmpty {\n\t\tlog.Fatal(err)\n\t}\n\n\tcmd, err := startPostgres(*dataDir)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tdb := waitForPostgres(time.Minute)\n\tpassword := createSuperuser(db)\n\tdb.Close()\n\tregister(map[string]string{\"username\": \"flynn\", \"password\": password, \"up\": \"true\"})\n\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tcmd.Wait()\n\t\tclose(done)\n\t}()\n\n\treturn cmd, done\n}\n\nfunc register(attrs map[string]string) {\n\terr := discoverd.RegisterWithAttributes(*serviceName, addr, attrs)\n\tif err != nil {\n\t\tlog.Fatalln(\"discoverd registration error:\", err)\n\t}\n}\n\nfunc procExit(cmd *exec.Cmd) {\n\tdiscoverd.UnregisterAll()\n\tvar status int\n\tif ws, ok := cmd.ProcessState.Sys().(syscall.WaitStatus); ok {\n\t\tstatus = ws.ExitStatus()\n\t}\n\tos.Exit(status)\n}\n\nfunc createSuperuser(db *sql.DB) (password string) {\n\tlog.Println(\"Creating superuser...\")\n\tpassword = generatePassword()\n\n\t_, err := db.Exec(\"DROP USER IF EXISTS flynn\")\n\tif err != nil {\n\t\tlog.Fatalln(\"Error dropping user:\", err)\n\t}\n\t_, err = db.Exec(\"CREATE USER flynn WITH SUPERUSER CREATEDB CREATEROLE REPLICATION PASSWORD '\" + password + \"'\")\n\tif err != nil {\n\t\tlog.Fatalln(\"Error creating user:\", err)\n\t}\n\tlog.Println(\"Superuser created.\")\n\n\treturn\n}\n\nfunc generatePassword() string {\n\tb := make([]byte, 16)\n\tenc := make([]byte, 24)\n\t_, err := io.ReadFull(rand.Reader, b)\n\tif err != nil {\n\t\tpanic(err) \/\/ This shouldn't ever happen, right?\n\t}\n\tbase64.URLEncoding.Encode(enc, b)\n\treturn string(bytes.TrimRight(enc, \"=\"))\n}\n\nvar pgstr = \"user=postgres host=\/var\/run\/postgresql sslmode=disable port=\" + os.Getenv(\"PORT\")\n\nfunc waitForPostgres(maxWait time.Duration) *sql.DB {\n\tlog.Println(\"Waiting for postgres to boot...\")\n\tstart := time.Now()\n\tfor {\n\t\tvar ping string\n\t\tdb, err := sql.Open(\"postgres\", pgstr)\n\t\tif err != nil {\n\t\t\tgoto fail\n\t\t}\n\t\terr = db.QueryRow(\"SELECT 'ping'\").Scan(&ping)\n\t\tif ping == \"ping\" {\n\t\t\tlog.Println(\"Postgres is up.\")\n\t\t\treturn db\n\t\t}\n\t\tdb.Close()\n\n\tfail:\n\t\tif time.Now().Sub(start) >= maxWait {\n\t\t\tlog.Fatalf(\"Unable to connect to postgres after %s, last error: %q\", maxWait, err)\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n}\n\nfunc waitForPromotion() {\n\tlog.Println(\"Waiting for promotion...\")\n\tdb, err := sql.Open(\"postgres\", pgstr)\n\tif err != nil {\n\t\tlog.Fatalln(\"Error connecting to postgres:\", err)\n\t}\n\tdefer db.Close()\n\tfor {\n\t\tvar recovery bool\n\t\terr := db.QueryRow(\"SELECT pg_is_in_recovery()\").Scan(&recovery)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Error checking recovery status:\", err)\n\t\t}\n\t\tif !recovery {\n\t\t\treturn\n\t\t}\n\t\ttime.Sleep(time.Second)\n\t}\n}\n\nfunc promoteToLeader(follower *follower, username, password string) (*exec.Cmd, <-chan struct{}) {\n\tlog.Println(\"Promoting follower to leader...\")\n\tregister(map[string]string{\"up\": \"false\"})\n\tf, err := os.Create(filepath.Join(*dataDir, \"promote.trigger\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tf.Close()\n\n\twaitForPromotion()\n\n\tif username == \"\" || password == \"\" {\n\t\t\/\/ TODO: create superuser\n\t}\n\n\tregister(map[string]string{\"up\": \"true\", \"username\": username, \"password\": password})\n\tlog.Println(\"Follower promoted to leader.\")\n\treturn follower.Cancel()\n}\n\nfunc runCmd(cmd *exec.Cmd) {\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\tif exitErr, ok := err.(*exec.ExitError); ok {\n\t\t\tif status, ok := exitErr.Sys().(syscall.WaitStatus); ok {\n\t\t\t\tos.Exit(status.ExitStatus())\n\t\t\t}\n\t\t}\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc pullBaseBackup(s *discoverd.Service) {\n\tlog.Println(\"Running pg_basebackup...\")\n\trunCmd(exec.Command(\n\t\t\"pg_basebackup\",\n\t\t\"-D\", *dataDir,\n\t\t\"-d\", fmt.Sprintf(\"host=%s port=%s user=%s password=%s\", s.Host, s.Port, s.Attrs[\"username\"], s.Attrs[\"password\"]),\n\t\t\"--xlog-method=stream\",\n\t\t\"--progress\",\n\t\t\"--verbose\",\n\t))\n\tlog.Println(\"pg_basebackup complete.\")\n}\n\nvar recoveryTempl = template.Must(template.New(\"recovery\").Parse(`\nstandby_mode = 'on'\nprimary_conninfo = 'host={{.Host}} port={{.Port}} user={{.Username}} password={{.Password}}'\ntrigger_file = '{{.Trigger}}'\n`))\n\ntype recoveryConfig struct {\n\tHost     string\n\tPort     string\n\tUsername string\n\tPassword string\n\tTrigger  string\n}\n\nfunc writeRecoveryConf(dir string, leader *discoverd.Service) {\n\tf, err := os.Create(filepath.Join(dir, \"recovery.conf\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"Error creating recovery.conf:\", err)\n\t}\n\tdefer f.Close()\n\n\terr = recoveryTempl.Execute(f, &recoveryConfig{\n\t\tHost:     leader.Host,\n\t\tPort:     leader.Port,\n\t\tUsername: leader.Attrs[\"username\"],\n\t\tPassword: leader.Attrs[\"password\"],\n\t\tTrigger:  filepath.Join(dir, \"promote.trigger\"),\n\t})\n\tif err != nil {\n\t\tlog.Fatalln(\"Error writing recovery.conf:\", err)\n\t}\n}\n\nfunc updateToService(u *da.ServiceUpdate) *discoverd.Service {\n\thost, port, _ := net.SplitHostPort(u.Addr)\n\treturn &discoverd.Service{\n\t\tCreated: u.Created,\n\t\tName:    u.Name,\n\t\tAddr:    u.Addr,\n\t\tAttrs:   u.Attrs,\n\t\tHost:    host,\n\t\tPort:    port,\n\t}\n}\n\nfunc waitForLeaderUp(leader *discoverd.Service, set discoverd.ServiceSet) *discoverd.Service {\n\tif leader.Attrs[\"up\"] == \"true\" {\n\t\treturn leader\n\t}\n\tlog.Println(\"Waiting for leader to come up...\")\n\twatch := set.Watch(true, false)\n\tdefer set.Unwatch(watch)\n\tfor update := range watch {\n\t\tif update.Addr == set.Leader().Addr && update.Attrs[\"up\"] == \"true\" && update.Attrs[\"username\"] != \"\" && update.Attrs[\"password\"] != \"\" {\n\t\t\treturn updateToService(update)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc startFollower(leader *discoverd.Service, set discoverd.ServiceSet) *follower {\n\tlog.Println(\"Starting as follower...\")\n\tleader = waitForLeaderUp(leader, set)\n\tif err := dirIsEmpty(*dataDir); err == nil {\n\t\tpullBaseBackup(leader)\n\t} else if err != ErrNotEmpty {\n\t\tlog.Fatal(err)\n\t}\n\n\twriteRecoveryConf(*dataDir, leader)\n\tcmd, err := startPostgres(*dataDir)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\twaitForPostgres(time.Minute).Close()\n\tregister(map[string]string{\"up\": \"true\"})\n\tlog.Println(\"Follower started.\")\n\n\t\/\/ TODO: if data and insufficient WAL, pg_basebackup\n\treturn newFollower(cmd)\n}\n\nfunc switchLeader(leader *discoverd.Service, set discoverd.ServiceSet, follower *follower) *follower {\n\tlog.Println(\"Switching leaders...\")\n\tleader = waitForLeaderUp(leader, set)\n\tregister(map[string]string{\"up\": \"false\"})\n\twriteRecoveryConf(*dataDir, leader)\n\tfollower.Stop()\n\n\tcmd, err := startPostgres(*dataDir)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\twaitForPostgres(time.Minute).Close()\n\t\/\/ TODO: check for insufficient WAL, then pg_basebackup\n\tregister(map[string]string{\"up\": \"true\"})\n\tlog.Println(\"Leader switch complete.\")\n\treturn newFollower(cmd)\n}\n\nfunc newFollower(cmd *exec.Cmd) *follower {\n\tf := &follower{\n\t\tcmd:  cmd,\n\t\tstop: make(chan struct{}),\n\t\tdone: make(chan struct{}),\n\t}\n\tgo f.wait()\n\treturn f\n}\n\ntype follower struct {\n\tcmd  *exec.Cmd\n\tstop chan struct{}\n\tdone chan struct{}\n}\n\nfunc (f *follower) wait() {\n\tgo func() {\n\t\tf.cmd.Wait()\n\t\tclose(f.done)\n\t}()\n\n\tselect {\n\tcase <-f.done:\n\t\tprocExit(f.cmd)\n\tcase <-f.stop:\n\t}\n}\n\nfunc (f *follower) Cancel() (*exec.Cmd, <-chan struct{}) {\n\tclose(f.stop)\n\treturn f.cmd, f.done\n}\n\nfunc (f *follower) Stop() error {\n\tclose(f.stop)\n\tif err := f.cmd.Process.Signal(syscall.SIGTERM); err != nil {\n\t\treturn err\n\t}\n\t\/\/ TODO: escalate to kill?\n\t<-f.done\n\treturn nil\n}\n\nfunc writeConfig(dataDir string) {\n\terr := copyFile(\"\/etc\/postgresql\/9.3\/main\/postgresql.conf\", filepath.Join(dataDir, \"postgresql.conf\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"Error creating postgresql.conf\", err)\n\t}\n\n\terr = copyFile(\"\/etc\/postgresql\/9.3\/main\/pg_hba.conf\", filepath.Join(dataDir, \"pg_hba.conf\"))\n\tif err != nil {\n\t\tlog.Fatalln(\"Error creating pg_hba.conf\", err)\n\t}\n}\n\nfunc copyFile(src, dest string) error {\n\tsf, err := os.Open(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer sf.Close()\n\tdf, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer df.Close()\n\n\t_, err = io.Copy(df, sf)\n\treturn err\n}\n\nfunc startPostgres(dataDir string) (*exec.Cmd, error) {\n\twriteConfig(dataDir)\n\n\tlog.Println(\"Starting postgres...\")\n\tcmd := exec.Command(\n\t\tfilepath.Join(*pgbin, \"postgres\"),\n\t\t\"-D\", dataDir,\n\t\t\"-p\", os.Getenv(\"PORT\"),\n\t\t\"-h\", \"*\",\n\t)\n\tlog.Println(\"exec\", strings.Join(cmd.Args, \" \"))\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Start(); err != nil {\n\t\treturn nil, err\n\t}\n\tgo handleSignals(cmd)\n\treturn cmd, nil\n}\n\nfunc handleSignals(cmd *exec.Cmd) {\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)\n\n\tsig := <-c\n\tdiscoverd.UnregisterAll()\n\tcmd.Process.Signal(sig)\n}\n\nvar ErrNotEmpty = errors.New(\"directory is not empty\")\n\nfunc dirIsEmpty(dir string) error {\n\td, err := os.Open(dir)\n\tif err != nil {\n\t\tif errno, ok := err.(syscall.Errno); ok && errno == syscall.ENOENT {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\tdefer d.Close()\n\n\tfor {\n\t\tfs, err := d.Readdir(10)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tfor _, f := range fs {\n\t\t\tif !strings.HasPrefix(f.Name(), \".\") {\n\t\t\t\treturn ErrNotEmpty\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n- Copyright 2014 Yua Shizuki. All rights reserved.\n- Licensed under the Apache License, Version 2.0 (the \"License\");\n- you may not use this file except in compliance with the License.\n- You may obtain a copy of the License at\n-\n- http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n-\n- Unless required by applicable law or agreed to in writing, software\n- distributed under the License is distributed on an \"AS IS\" BASIS,\n- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n- See the License for the specific language governing permissions and\n- limitations under the License.\n-*\/\n\npackage main\nimport \"fmt\"\nimport \"github.com\/howeyc\/fsnotify\"\nimport \"io\/ioutil\"\nimport \"path\/filepath\"\nimport \"os\/exec\"\nimport \"os\"\nimport \"net\"\nimport \"strings\"\nimport \"regexp\"\nimport \"txtserve\"\nimport \"time\"\n\nvar controllerListener net.Listener\nvar controllerConn net.Conn\n\nfunc runner() {\n    err := run()\n    if err != nil {\n        errExit(err, \"\")\n    }\n    done := make(chan bool)\n    <-done\n}\n\nfunc run() error {\n    err := build(false)\n    if err != nil {\n        return err\n    }\n    pwd,_ := os.Getwd()\n    exe := filepath.Base(pwd)\n    port, err := controller()\n    if err != nil {\n        return err\n    }\n    cmd := exec.Command(\"sudo\", \".\/\"+exe, \"gokcontroller=\"+port)\n    cmd.Stdin = os.Stdin\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    go cmd.Run()\n    return nil\n}\n\n\/*- http server (child process) controller -*\/\nfunc controller() (string, error) {\n    var err error\n    controllerListener, err = net.Listen(\"tcp\", \"127.0.0.1:0\")\n    if err != nil {\n        return \"\", err\n    }\n    port := strings.Split(controllerListener.Addr().String(), \":\")[1]\n    go controllerStart()\n    return port, nil\n}\n\nfunc switchOffController() {\n    if controllerListener != nil {\n        controllerListener.Close()\n        controllerListener = nil\n    }\n    if controllerConn != nil {\n        controllerConn.Close()\n        controllerConn = nil\n    }\n}\n\nfunc controllerStart() {\n    var err error\n    controllerConn, err = controllerListener.Accept()\n    if err != nil {\n        return\n    }\n    go startNotifier(\".\", make(chan bool))\n    ioutil.ReadAll(controllerConn)\n    switchOffController()\n}\n\/*- End -*\/\n\n\nfunc startNotifier(dir string, end chan bool) {\n    lastUpdate := time.Now()\n    goorgok,_ := regexp.Compile(\"^([^.]*\\\\.go|[^.]*\\\\.gok)$\")\n    watch, err := fsnotify.NewWatcher()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    dirNotifiers := make([](chan bool),0,10)\n    files, err := ioutil.ReadDir(dir)\n    if err != nil {\n        errExit(err, \"\")\n    }\n    for _, f := range files {\n        if f.IsDir() {\n            lenD := len(dirNotifiers)\n            dirNotifiers = append(dirNotifiers, make(chan bool))\n            startNotifier(dir+\"\/\"+f.Name(), dirNotifiers[lenD])\n        }\n    }\n    watch.Watch(dir)\n    for ;; {\n        select {\n            case event := <-watch.Event:\n                if goorgok.Match([]byte(event.Name)) || isDirectory(event.Name) {\n                    if time.Since(lastUpdate) < (1000 * time.Millisecond) {\n                        continue\n                    }\n                    lastUpdate = time.Now()\n                    fmt.Printf(\"%v: src code update => \", lastUpdate)\n                    txtserve.StopServer()\n                    switchOffController()\n                    time.Sleep(200 * time.Millisecond)\n                    err = run()\n                    if err != nil {\n                        fmt.Printf(\"error building server binary\\n\")\n                        txtserve.StartServer(err.Error())\n                    } else {\n                        fmt.Printf(\"server binary build successful\\n\")\n                        watch.Close()\n                        for _, c := range dirNotifiers {\n                            c <- true\n                            close(c)\n                        }\n                        return\n                    }\n                }\n            case shouldEnd := <-end:\n                if shouldEnd {\n                    watch.Close()\n                    for _, c := range dirNotifiers {\n                            c <- true\n                            close(c)\n                    }\n                    return\n                }\n        }\n    }\n}\n\n<commit_msg>standard<commit_after>\/*\n- Copyright 2014 Yua Shizuki. All rights reserved.\n- Licensed under the Apache License, Version 2.0 (the \"License\");\n- you may not use this file except in compliance with the License.\n- You may obtain a copy of the License at\n-\n- http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n-\n- Unless required by applicable law or agreed to in writing, software\n- distributed under the License is distributed on an \"AS IS\" BASIS,\n- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n- See the License for the specific language governing permissions and\n- limitations under the License.\n-*\/\n\npackage main\nimport \"fmt\"\nimport \"github.com\/howeyc\/fsnotify\"\nimport \"io\/ioutil\"\nimport \"path\/filepath\"\nimport \"os\/exec\"\nimport \"os\"\nimport \"net\"\nimport \"strings\"\nimport \"regexp\"\nimport \"github.com\/YuaShizuki\/gok\/txtserve\"\nimport \"time\"\n\nvar controllerListener net.Listener\nvar controllerConn net.Conn\n\nfunc runner() {\n    err := run()\n    if err != nil {\n        errExit(err, \"\")\n    }\n    done := make(chan bool)\n    <-done\n}\n\nfunc run() error {\n    err := build(false)\n    if err != nil {\n        return err\n    }\n    pwd,_ := os.Getwd()\n    exe := filepath.Base(pwd)\n    port, err := controller()\n    if err != nil {\n        return err\n    }\n    cmd := exec.Command(\"sudo\", \".\/\"+exe, \"gokcontroller=\"+port)\n    cmd.Stdin = os.Stdin\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    go cmd.Run()\n    return nil\n}\n\n\/*- http server (child process) controller -*\/\nfunc controller() (string, error) {\n    var err error\n    controllerListener, err = net.Listen(\"tcp\", \"127.0.0.1:0\")\n    if err != nil {\n        return \"\", err\n    }\n    port := strings.Split(controllerListener.Addr().String(), \":\")[1]\n    go controllerStart()\n    return port, nil\n}\n\nfunc switchOffController() {\n    if controllerListener != nil {\n        controllerListener.Close()\n        controllerListener = nil\n    }\n    if controllerConn != nil {\n        controllerConn.Close()\n        controllerConn = nil\n    }\n}\n\nfunc controllerStart() {\n    var err error\n    controllerConn, err = controllerListener.Accept()\n    if err != nil {\n        return\n    }\n    go startNotifier(\".\", make(chan bool))\n    ioutil.ReadAll(controllerConn)\n    switchOffController()\n}\n\/*- End -*\/\n\n\nfunc startNotifier(dir string, end chan bool) {\n    lastUpdate := time.Now()\n    goorgok,_ := regexp.Compile(\"^([^.]*\\\\.go|[^.]*\\\\.gok)$\")\n    watch, err := fsnotify.NewWatcher()\n    if err != nil {\n        fmt.Println(err)\n        os.Exit(1)\n    }\n    dirNotifiers := make([](chan bool),0,10)\n    files, err := ioutil.ReadDir(dir)\n    if err != nil {\n        errExit(err, \"\")\n    }\n    for _, f := range files {\n        if f.IsDir() {\n            lenD := len(dirNotifiers)\n            dirNotifiers = append(dirNotifiers, make(chan bool))\n            startNotifier(dir+\"\/\"+f.Name(), dirNotifiers[lenD])\n        }\n    }\n    watch.Watch(dir)\n    for ;; {\n        select {\n            case event := <-watch.Event:\n                if goorgok.Match([]byte(event.Name)) || isDirectory(event.Name) {\n                    if time.Since(lastUpdate) < (1000 * time.Millisecond) {\n                        continue\n                    }\n                    lastUpdate = time.Now()\n                    fmt.Printf(\"%v: src code update => \", lastUpdate)\n                    txtserve.StopServer()\n                    switchOffController()\n                    time.Sleep(200 * time.Millisecond)\n                    err = run()\n                    if err != nil {\n                        fmt.Printf(\"error building server binary\\n\")\n                        txtserve.StartServer(err.Error())\n                    } else {\n                        fmt.Printf(\"server binary build successful\\n\")\n                        watch.Close()\n                        for _, c := range dirNotifiers {\n                            c <- true\n                            close(c)\n                        }\n                        return\n                    }\n                }\n            case shouldEnd := <-end:\n                if shouldEnd {\n                    watch.Close()\n                    for _, c := range dirNotifiers {\n                            c <- true\n                            close(c)\n                    }\n                    return\n                }\n        }\n    }\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package whatlanggo\n\nimport \"unicode\"\n\ntype scriptCounter struct {\n\tcheckFunc func(r rune) bool\n\tscript    *unicode.RangeTable\n\tcount     *int\n}\n\n\/\/ Scripts is the set of Unicode script tables.\nvar Scripts = map[*unicode.RangeTable]string{\n\tunicode.Arabic:     \"Arabic\",\n\tunicode.Bengali:    \"Bengali\",\n\tunicode.Cyrillic:   \"Cyrillic\",\n\tunicode.Ethiopic:   \"Ethiopic\",\n\tunicode.Devanagari: \"Devanagari\",\n\tunicode.Han:        \"Han\",\n\tunicode.Georgian:   \"Georgian\",\n\tunicode.Greek:      \"Greek\",\n\tunicode.Gujarati:   \"Gujarati\",\n\tunicode.Gurmukhi:   \"Gurmukhi\",\n\tunicode.Hangul:     \"Hangul\",\n\tunicode.Hebrew:     \"Hebrew\",\n\tunicode.Hiragana:   \"Hiragana\",\n\tunicode.Kannada:    \"Kannada\",\n\tunicode.Katakana:   \"Katakana\",\n\tunicode.Khmer:      \"Khmer\",\n\tunicode.Latin:      \"Latin\",\n\tunicode.Malayalam:  \"Malayalam\",\n\tunicode.Myanmar:    \"Myanmar\",\n\tunicode.Oriya:      \"Oriya\",\n\tunicode.Sinhala:    \"Sinhala\",\n\tunicode.Tamil:      \"Tamil\",\n\tunicode.Telugu:     \"Telugu\",\n\tunicode.Thai:       \"Thai\",\n}\n\n\/\/ DetectScript returns only the script of the given text.\nfunc DetectScript(text string) *unicode.RangeTable {\n\thalfLen := len(text) \/ 2\n\n\tscriptCounter := []scriptCounter{\n\t\t{isLatin, unicode.Latin, new(int)},\n\t\t{isCyrillic, unicode.Cyrillic, new(int)},\n\t\t{isArabic, unicode.Arabic, new(int)},\n\t\t{isDevanagari, unicode.Devanagari, new(int)},\n\t\t{isHiraganaKatakana, _HiraganaKatakana, new(int)},\n\t\t{isEthiopic, unicode.Ethiopic, new(int)},\n\t\t{isHebrew, unicode.Hebrew, new(int)},\n\t\t{isBengali, unicode.Bengali, new(int)},\n\t\t{isGeorgian, unicode.Georgian, new(int)},\n\t\t{isHan, unicode.Han, new(int)},\n\t\t{isHangul, unicode.Hangul, new(int)},\n\t\t{isGreek, unicode.Greek, new(int)},\n\t\t{isKannada, unicode.Kannada, new(int)},\n\t\t{isTamil, unicode.Tamil, new(int)},\n\t\t{isThai, unicode.Thai, new(int)},\n\t\t{isGujarati, unicode.Gujarati, new(int)},\n\t\t{isGurmukhi, unicode.Gurmukhi, new(int)},\n\t\t{isTelugu, unicode.Telugu, new(int)},\n\t\t{isMalayalam, unicode.Malayalam, new(int)},\n\t\t{isOriya, unicode.Oriya, new(int)},\n\t\t{isMyanmar, unicode.Myanmar, new(int)},\n\t\t{isSinhala, unicode.Sinhala, new(int)},\n\t\t{isKhmer, unicode.Khmer, new(int)},\n\t}\n\n\tfor _, ch := range text {\n\t\tif isStopChar(ch) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor i, sc := range scriptCounter {\n\t\t\tif sc.checkFunc(ch) {\n\t\t\t\t*sc.count++\n\t\t\t\tif *sc.count > halfLen {\n\t\t\t\t\treturn sc.script\n\t\t\t\t}\n\n\t\t\t\t\/\/if script is found, move it closer to the front so that it be checked first.\n\t\t\t\tif i > 0 {\n\t\t\t\t\tscriptCounter[i], scriptCounter[i-1] = scriptCounter[i-1], scriptCounter[i]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/find the script that occurs the most in the text and return it.\n\tjpCount := 0\n\tmax := 0\n\tmaxScript := &unicode.RangeTable{}\n\tfor _, script := range scriptCounter {\n\t\tif *script.count > max {\n\t\t\tmax = *script.count\n\t\t\tmaxScript = script.script\n\t\t\tif script.script == _HiraganaKatakana {\n\t\t\t\tjpCount = max\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch {\n\tcase max == 0:\n\t\t\/\/if no valid script is detected, return nil.\n\t\treturn nil\n\tcase max != 0 && (maxScript == unicode.Han && jpCount > 0):\n\t\t\/\/ If Hiragana or Katakana is included, even if judged as Mandarin,\n\t\t\/\/ it is regarded as Japanese. Japanese uses Kanji (unicode.Han)\n\t\t\/\/ in addition to Hiragana and Katakana.\n\t\treturn _HiraganaKatakana\n\tdefault:\n\t\treturn maxScript\n\t}\n}\n\nvar isCyrillic = func(r rune) bool {\n\treturn unicode.Is(unicode.Cyrillic, r)\n}\n\nvar isLatin = func(r rune) bool {\n\treturn unicode.Is(unicode.Latin, r)\n}\n\nvar isArabic = func(r rune) bool {\n\treturn unicode.Is(unicode.Arabic, r)\n}\n\nvar isDevanagari = func(r rune) bool {\n\treturn unicode.Is(unicode.Devanagari, r)\n}\n\nvar isEthiopic = func(r rune) bool {\n\treturn unicode.Is(unicode.Ethiopic, r)\n}\n\nvar isHebrew = func(r rune) bool {\n\treturn unicode.Is(unicode.Hebrew, r)\n}\n\nvar isHan = func(r rune) bool {\n\treturn unicode.Is(unicode.Han, r)\n}\n\nvar isBengali = func(r rune) bool {\n\treturn unicode.Is(unicode.Bengali, r)\n}\n\nvar isHiraganaKatakana = func(r rune) bool {\n\treturn unicode.Is(_HiraganaKatakana, r)\n}\n\nvar isHangul = func(r rune) bool {\n\treturn unicode.Is(unicode.Hangul, r)\n}\n\nvar isGreek = func(r rune) bool {\n\treturn unicode.Is(unicode.Greek, r)\n}\n\nvar isKannada = func(r rune) bool {\n\treturn unicode.Is(unicode.Kannada, r)\n}\n\nvar isTamil = func(r rune) bool {\n\treturn unicode.Is(unicode.Tamil, r)\n}\n\nvar isThai = func(r rune) bool {\n\treturn unicode.Is(unicode.Thai, r)\n}\n\nvar isGujarati = func(r rune) bool {\n\treturn unicode.Is(unicode.Gujarati, r)\n}\n\nvar isGurmukhi = func(r rune) bool {\n\treturn unicode.Is(unicode.Gurmukhi, r)\n}\n\nvar isTelugu = func(r rune) bool {\n\treturn unicode.Is(unicode.Telugu, r)\n}\n\nvar isMalayalam = func(r rune) bool {\n\treturn unicode.Is(unicode.Malayalam, r)\n}\n\nvar isOriya = func(r rune) bool {\n\treturn unicode.Is(unicode.Oriya, r)\n}\n\nvar isMyanmar = func(r rune) bool {\n\treturn unicode.Is(unicode.Myanmar, r)\n}\n\nvar isSinhala = func(r rune) bool {\n\treturn unicode.Is(unicode.Sinhala, r)\n}\n\nvar isKhmer = func(r rune) bool {\n\treturn unicode.Is(unicode.Khmer, r)\n}\n\nvar isGeorgian = func(r rune) bool {\n\treturn unicode.Is(unicode.Georgian, r)\n}\n<commit_msg>Lower memory allocator pressure in DetectScript (#16)<commit_after>package whatlanggo\n\nimport \"unicode\"\n\ntype scriptCounter struct {\n\tcheckFunc func(r rune) bool\n\tscript    *unicode.RangeTable\n\tcount     int\n}\n\n\/\/ Scripts is the set of Unicode script tables.\nvar Scripts = map[*unicode.RangeTable]string{\n\tunicode.Arabic:     \"Arabic\",\n\tunicode.Bengali:    \"Bengali\",\n\tunicode.Cyrillic:   \"Cyrillic\",\n\tunicode.Ethiopic:   \"Ethiopic\",\n\tunicode.Devanagari: \"Devanagari\",\n\tunicode.Han:        \"Han\",\n\tunicode.Georgian:   \"Georgian\",\n\tunicode.Greek:      \"Greek\",\n\tunicode.Gujarati:   \"Gujarati\",\n\tunicode.Gurmukhi:   \"Gurmukhi\",\n\tunicode.Hangul:     \"Hangul\",\n\tunicode.Hebrew:     \"Hebrew\",\n\tunicode.Hiragana:   \"Hiragana\",\n\tunicode.Kannada:    \"Kannada\",\n\tunicode.Katakana:   \"Katakana\",\n\tunicode.Khmer:      \"Khmer\",\n\tunicode.Latin:      \"Latin\",\n\tunicode.Malayalam:  \"Malayalam\",\n\tunicode.Myanmar:    \"Myanmar\",\n\tunicode.Oriya:      \"Oriya\",\n\tunicode.Sinhala:    \"Sinhala\",\n\tunicode.Tamil:      \"Tamil\",\n\tunicode.Telugu:     \"Telugu\",\n\tunicode.Thai:       \"Thai\",\n}\n\n\/\/ DetectScript returns only the script of the given text.\nfunc DetectScript(text string) *unicode.RangeTable {\n\thalfLen := len(text) \/ 2\n\n\tscriptCounter := []scriptCounter{\n\t\t{isLatin, unicode.Latin, 0},\n\t\t{isCyrillic, unicode.Cyrillic, 0},\n\t\t{isArabic, unicode.Arabic, 0},\n\t\t{isDevanagari, unicode.Devanagari, 0},\n\t\t{isHiraganaKatakana, _HiraganaKatakana, 0},\n\t\t{isEthiopic, unicode.Ethiopic, 0},\n\t\t{isHebrew, unicode.Hebrew, 0},\n\t\t{isBengali, unicode.Bengali, 0},\n\t\t{isGeorgian, unicode.Georgian, 0},\n\t\t{isHan, unicode.Han, 0},\n\t\t{isHangul, unicode.Hangul, 0},\n\t\t{isGreek, unicode.Greek, 0},\n\t\t{isKannada, unicode.Kannada, 0},\n\t\t{isTamil, unicode.Tamil, 0},\n\t\t{isThai, unicode.Thai, 0},\n\t\t{isGujarati, unicode.Gujarati, 0},\n\t\t{isGurmukhi, unicode.Gurmukhi, 0},\n\t\t{isTelugu, unicode.Telugu, 0},\n\t\t{isMalayalam, unicode.Malayalam, 0},\n\t\t{isOriya, unicode.Oriya, 0},\n\t\t{isMyanmar, unicode.Myanmar, 0},\n\t\t{isSinhala, unicode.Sinhala, 0},\n\t\t{isKhmer, unicode.Khmer, 0},\n\t}\n\n\tfor _, ch := range text {\n\t\tif isStopChar(ch) {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor i, sc := range scriptCounter {\n\t\t\tif sc.checkFunc(ch) {\n\t\t\t\tscriptCounter[i].count++\n\t\t\t\tif scriptCounter[i].count > halfLen {\n\t\t\t\t\treturn sc.script\n\t\t\t\t}\n\n\t\t\t\t\/\/if script is found, move it closer to the front so that it be checked first.\n\t\t\t\tif i > 0 {\n\t\t\t\t\tscriptCounter[i], scriptCounter[i-1] = scriptCounter[i-1], scriptCounter[i]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/find the script that occurs the most in the text and return it.\n\tjpCount := 0\n\tmax := 0\n\tmaxScript := &unicode.RangeTable{}\n\tfor _, script := range scriptCounter {\n\t\tif script.count > max {\n\t\t\tmax = script.count\n\t\t\tmaxScript = script.script\n\t\t\tif script.script == _HiraganaKatakana {\n\t\t\t\tjpCount = max\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch {\n\tcase max == 0:\n\t\t\/\/if no valid script is detected, return nil.\n\t\treturn nil\n\tcase max != 0 && (maxScript == unicode.Han && jpCount > 0):\n\t\t\/\/ If Hiragana or Katakana is included, even if judged as Mandarin,\n\t\t\/\/ it is regarded as Japanese. Japanese uses Kanji (unicode.Han)\n\t\t\/\/ in addition to Hiragana and Katakana.\n\t\treturn _HiraganaKatakana\n\tdefault:\n\t\treturn maxScript\n\t}\n}\n\nvar isCyrillic = func(r rune) bool {\n\treturn unicode.Is(unicode.Cyrillic, r)\n}\n\nvar isLatin = func(r rune) bool {\n\treturn unicode.Is(unicode.Latin, r)\n}\n\nvar isArabic = func(r rune) bool {\n\treturn unicode.Is(unicode.Arabic, r)\n}\n\nvar isDevanagari = func(r rune) bool {\n\treturn unicode.Is(unicode.Devanagari, r)\n}\n\nvar isEthiopic = func(r rune) bool {\n\treturn unicode.Is(unicode.Ethiopic, r)\n}\n\nvar isHebrew = func(r rune) bool {\n\treturn unicode.Is(unicode.Hebrew, r)\n}\n\nvar isHan = func(r rune) bool {\n\treturn unicode.Is(unicode.Han, r)\n}\n\nvar isBengali = func(r rune) bool {\n\treturn unicode.Is(unicode.Bengali, r)\n}\n\nvar isHiraganaKatakana = func(r rune) bool {\n\treturn unicode.Is(_HiraganaKatakana, r)\n}\n\nvar isHangul = func(r rune) bool {\n\treturn unicode.Is(unicode.Hangul, r)\n}\n\nvar isGreek = func(r rune) bool {\n\treturn unicode.Is(unicode.Greek, r)\n}\n\nvar isKannada = func(r rune) bool {\n\treturn unicode.Is(unicode.Kannada, r)\n}\n\nvar isTamil = func(r rune) bool {\n\treturn unicode.Is(unicode.Tamil, r)\n}\n\nvar isThai = func(r rune) bool {\n\treturn unicode.Is(unicode.Thai, r)\n}\n\nvar isGujarati = func(r rune) bool {\n\treturn unicode.Is(unicode.Gujarati, r)\n}\n\nvar isGurmukhi = func(r rune) bool {\n\treturn unicode.Is(unicode.Gurmukhi, r)\n}\n\nvar isTelugu = func(r rune) bool {\n\treturn unicode.Is(unicode.Telugu, r)\n}\n\nvar isMalayalam = func(r rune) bool {\n\treturn unicode.Is(unicode.Malayalam, r)\n}\n\nvar isOriya = func(r rune) bool {\n\treturn unicode.Is(unicode.Oriya, r)\n}\n\nvar isMyanmar = func(r rune) bool {\n\treturn unicode.Is(unicode.Myanmar, r)\n}\n\nvar isSinhala = func(r rune) bool {\n\treturn unicode.Is(unicode.Sinhala, r)\n}\n\nvar isKhmer = func(r rune) bool {\n\treturn unicode.Is(unicode.Khmer, r)\n}\n\nvar isGeorgian = func(r rune) bool {\n\treturn unicode.Is(unicode.Georgian, r)\n}\n<|endoftext|>"}
{"text":"<commit_before>package goinsta\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Search struct {\n\tinst *Instagram\n}\n\ntype SearchResult struct {\n\tHasMore    bool   `json:\"has_more\"`\n\tRankToken  string `json:\"rank_token\"`\n\tStatus     string `json:\"status\"`\n\tNumResults int    `json:\"num_results\"`\n\n\t\/\/ User search results\n\tUsers []User `json:\"users\"`\n\n\t\/\/ Tag search results\n\tTags []struct {\n\t\tID               int64       `json:\"id\"`\n\t\tName             string      `json:\"name\"`\n\t\tMediaCount       int         `json:\"media_count\"`\n\t\tFollowStatus     interface{} `json:\"follow_status\"`\n\t\tFollowing        interface{} `json:\"following\"`\n\t\tAllowFollowing   interface{} `json:\"allow_following\"`\n\t\tAllowMutingStory interface{} `json:\"allow_muting_story\"`\n\t\tProfilePicURL    interface{} `json:\"profile_pic_url\"`\n\t\tNonViolating     interface{} `json:\"non_violating\"`\n\t\tRelatedTags      interface{} `json:\"related_tags\"`\n\t\tDebugInfo        interface{} `json:\"debug_info\"`\n\t} `json:\"results\"`\n\n\t\/\/ Location search result\n\tRequestID string `json:\"request_id\"`\n\tVenues    []struct {\n\t\tExternalIDSource string  `json:\"external_id_source\"`\n\t\tExternalID       string  `json:\"external_id\"`\n\t\tLat              float64 `json:\"lat\"`\n\t\tLng              float64 `json:\"lng\"`\n\t\tAddress          string  `json:\"address\"`\n\t\tName             string  `json:\"name\"`\n\t} `json:\"venues\"`\n\n\t\/\/ Facebook\n\t\/\/ TODO\n}\n\n\/\/ newSearch creates new Search structure\nfunc newSearch(inst *Instagram) *Search {\n\tsearch := &Search{\n\t\tinst: inst,\n\t}\n\treturn search\n}\n\n\/\/ User search by username\nfunc (search *Search) User(user string) (*SearchResult, error) {\n\tinsta := search.inst\n\tbody, err := insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: urlSearchUser,\n\t\t\tQuery: map[string]string{\n\t\t\t\t\"ig_sig_key_version\": goInstaSigKeyVersion,\n\t\t\t\t\"is_typeahead\":       \"true\",\n\t\t\t\t\"query\":              user,\n\t\t\t\t\"rank_token\":         insta.rankToken,\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := &SearchResult{}\n\terr = json.Unmarshal(body, res)\n\treturn res, err\n}\n\n\/\/ Tags search by tag\nfunc (search *Search) Tags(tag string) (*SearchResult, error) {\n\tinsta := search.inst\n\tbody, err := insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: urlSearchTag,\n\t\t\tQuery: map[string]string{\n\t\t\t\t\"is_typeahead\": \"true\",\n\t\t\t\t\"rank_token\":   insta.rankToken,\n\t\t\t\t\"q\":            tag,\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := &SearchResult{}\n\terr = json.Unmarshal(body, res)\n\treturn res, err\n}\n\n\/\/ Location search by location.\n\/\/ DEPRECATED - Instagram does not allow Location search method.\n\/\/ Lat and Lng (Latitude & Longitude) cannot be \"\"\nfunc (search *Search) Location(lat, lng, location string) (*SearchResult, error) {\n\tinsta := search.inst\n\tq := map[string]string{\n\t\t\"rank_token\":     insta.rankToken,\n\t\t\"latitude\":       lat,\n\t\t\"longitude\":      lng,\n\t\t\"ranked_content\": \"true\",\n\t}\n\n\tif location != \"\" {\n\t\tq[\"search_query\"] = location\n\t} else {\n\t\tq[\"timestamp\"] = strconv.FormatInt(time.Now().Unix(), 10)\n\t}\n\n\tbody, err := insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: urlSearchLocation,\n\t\t\tQuery:    q,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := &SearchResult{}\n\terr = json.Unmarshal(body, res)\n\treturn res, err\n}\n\nfunc (search *Search) Facebook(user string) (*SearchResult, error) {\n\t\/\/ TODO\n\treturn nil, nil\n}\n<commit_msg>Search functions finished<commit_after>package goinsta\n\nimport (\n\t\"encoding\/json\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Search struct {\n\tinst *Instagram\n}\n\ntype SearchResult struct {\n\tHasMore    bool   `json:\"has_more\"`\n\tRankToken  string `json:\"rank_token\"`\n\tStatus     string `json:\"status\"`\n\tNumResults int    `json:\"num_results\"`\n\n\t\/\/ User search results\n\tUsers []User `json:\"users\"`\n\n\t\/\/ Tag search results\n\tTags []struct {\n\t\tID               int64       `json:\"id\"`\n\t\tName             string      `json:\"name\"`\n\t\tMediaCount       int         `json:\"media_count\"`\n\t\tFollowStatus     interface{} `json:\"follow_status\"`\n\t\tFollowing        interface{} `json:\"following\"`\n\t\tAllowFollowing   interface{} `json:\"allow_following\"`\n\t\tAllowMutingStory interface{} `json:\"allow_muting_story\"`\n\t\tProfilePicURL    interface{} `json:\"profile_pic_url\"`\n\t\tNonViolating     interface{} `json:\"non_violating\"`\n\t\tRelatedTags      interface{} `json:\"related_tags\"`\n\t\tDebugInfo        interface{} `json:\"debug_info\"`\n\t} `json:\"results\"`\n\n\t\/\/ Location search result\n\tRequestID string `json:\"request_id\"`\n\tVenues    []struct {\n\t\tExternalIDSource string  `json:\"external_id_source\"`\n\t\tExternalID       string  `json:\"external_id\"`\n\t\tLat              float64 `json:\"lat\"`\n\t\tLng              float64 `json:\"lng\"`\n\t\tAddress          string  `json:\"address\"`\n\t\tName             string  `json:\"name\"`\n\t} `json:\"venues\"`\n\n\t\/\/ Facebook\n\t\/\/ Facebook also uses `Users`\n\tPlaces   []interface{} `json:\"places\"`\n\tHashtags []struct {\n\t\tPosition int `json:\"position\"`\n\t\tHashtag  struct {\n\t\t\tName       string `json:\"name\"`\n\t\t\tID         int64  `json:\"id\"`\n\t\t\tMediaCount int    `json:\"media_count\"`\n\t\t} `json:\"hashtag\"`\n\t} `json:\"hashtags\"`\n\tClearClientCache bool `json:\"clear_client_cache\"`\n}\n\n\/\/ newSearch creates new Search structure\nfunc newSearch(inst *Instagram) *Search {\n\tsearch := &Search{\n\t\tinst: inst,\n\t}\n\treturn search\n}\n\n\/\/ User search by username\nfunc (search *Search) User(user string) (*SearchResult, error) {\n\tinsta := search.inst\n\tbody, err := insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: urlSearchUser,\n\t\t\tQuery: map[string]string{\n\t\t\t\t\"ig_sig_key_version\": goInstaSigKeyVersion,\n\t\t\t\t\"is_typeahead\":       \"true\",\n\t\t\t\t\"query\":              user,\n\t\t\t\t\"rank_token\":         insta.rankToken,\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := &SearchResult{}\n\terr = json.Unmarshal(body, res)\n\treturn res, err\n}\n\n\/\/ Tags search by tag\nfunc (search *Search) Tags(tag string) (*SearchResult, error) {\n\tinsta := search.inst\n\tbody, err := insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: urlSearchTag,\n\t\t\tQuery: map[string]string{\n\t\t\t\t\"is_typeahead\": \"true\",\n\t\t\t\t\"rank_token\":   insta.rankToken,\n\t\t\t\t\"q\":            tag,\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := &SearchResult{}\n\terr = json.Unmarshal(body, res)\n\treturn res, err\n}\n\n\/\/ Location search by location.\n\/\/ DEPRECATED - Instagram does not allow Location search method.\n\/\/ Lat and Lng (Latitude & Longitude) cannot be \"\"\nfunc (search *Search) Location(lat, lng, location string) (*SearchResult, error) {\n\tinsta := search.inst\n\tq := map[string]string{\n\t\t\"rank_token\":     insta.rankToken,\n\t\t\"latitude\":       lat,\n\t\t\"longitude\":      lng,\n\t\t\"ranked_content\": \"true\",\n\t}\n\n\tif location != \"\" {\n\t\tq[\"search_query\"] = location\n\t} else {\n\t\tq[\"timestamp\"] = strconv.FormatInt(time.Now().Unix(), 10)\n\t}\n\n\tbody, err := insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: urlSearchLocation,\n\t\t\tQuery:    q,\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := &SearchResult{}\n\terr = json.Unmarshal(body, res)\n\treturn res, err\n}\n\nfunc (search *Search) Facebook(user string) (*SearchResult, error) {\n\tinsta := search.inst\n\tbody, err := insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: \"fbsearch\/topsearch\/\",\n\t\t\tQuery: map[string]string{\n\t\t\t\t\"query\":      user,\n\t\t\t\t\"rank_token\": insta.rankToken,\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres := &SearchResult{}\n\terr = json.Unmarshal(body, res)\n\treturn res, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/btcsuite\/btcd\/wire\"\n)\n\nconst (\n\n\t\/\/ Twister Magic number to make it incompatible with the Bitcoin network\n\tTWISTNET = 0xd2bbdaf0\n\t\/\/ nounce is used to check if we connect to ourselves\n\t\/\/ as we don't listen we can use a fixed value\n\tNOUNCE  = 0x0539a019ca550825\n\tPVER    = 70003\n\tMINPORT = 0\n\tMAXPORT = 65535\n\n\tTWSTDPORT = 28333 \/\/ standard port twister listens on\n\n\tMAXFAILS = 58 \/\/ max number of connect fails before we delete a twistee. Just over 24 hours(checked every 33 minutes)\n\n\tMAXTO = 250 \/\/ max seconds (4min 10 sec) for all comms to twistee to complete before we timeout\n\n\t\/\/ DNS Type. Is this twistee using v4\/v6 and standard or non standard ports\n\tDNSV4STD = 1\n\tDNSV4NON = 2\n\tDNSV6STD = 3\n\tDNSV6NON = 4\n\n\t\/\/ twistee status\n\tstatusRG = 1 \/\/ reported good status. A remote twistee has reported this ip but we have not connected\n\tstatusCG = 2 \/\/ confirmed good. We have connected to the twistee and received addresses\n\tstatusWG = 3 \/\/ was good. Twistee was confirmed good but now having problems\n\tstatusNG = 4 \/\/ no good. Will be removed from theList after 24 hours to redure bouncing ip addresses\n\n)\n\ntype Seeder struct {\n\tuptime  time.Time\n\ttheList map[string]*Twistee\n\tmtx     sync.RWMutex\n}\n\n\/\/ initCrawlers needs to be run before the startCrawlers so it can get\n\/\/ a list of current ip addresses from the other seeders and therefore\n\/\/ start the crawl process\nfunc initCrawlers() {\n\n\tseeders := []string{\"seed2.twister.net.co\", \"seed3.twister.net.co\", \"seed.twister.net.co\"}\n\n\tfor _, seeder := range seeders {\n\t\tc := 0\n\n\t\tnewRRs, err := net.LookupHost(seeder)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"status - unable to do initial lookup to seeder %s %v\\n\", seeder, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, ip := range newRRs {\n\t\t\tif newIP := net.ParseIP(ip); newIP != nil {\n\t\t\t\t\/\/ 1 at the end is the services flag\n\t\t\t\tif x := config.seeder.addNa(wire.NewNetAddressIPPort(newIP, 28333, 1)); x == true {\n\t\t\t\t\tc++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif config.verbose {\n\t\t\tlog.Printf(\"status - completed import of %v addresses from %s\\n\", c, seeder)\n\t\t}\n\t}\n}\n\n\/\/ startCrawlers is called on a time basis to start maxcrawlers new\n\/\/ goroutines if there are spare goroutine slots available\nfunc (s *Seeder) startCrawlers() {\n\n\ttcount := len(s.theList)\n\tif tcount == 0 {\n\t\tif config.debug {\n\t\t\tlog.Printf(\"debug - startCrawlers fail: no twistees available\\n\")\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ struct to hold config options for each status\n\tvar crawlers = []struct {\n\t\tdesc       string\n\t\tstatus     uint32\n\t\tmaxCount   uint32 \/\/ max goroutines to start for this status type\n\t\ttotalCount uint32 \/\/ stats count of this type\n\t\tstarted    uint32 \/\/ count of goroutines started for this type\n\t\tdelay      int64  \/\/ number of second since last try\n\t}{\n\t\t{\"statusRG\", statusRG, 10, 0, 0, 184},\n\t\t{\"statusCG\", statusCG, 10, 0, 0, 325},\n\t\t{\"statusWG\", statusWG, 10, 0, 0, 237},\n\t\t{\"statusNG\", statusNG, 20, 0, 0, 1876},\n\t}\n\n\ts.mtx.RLock()\n\tdefer s.mtx.RUnlock()\n\n\tfor _, c := range crawlers {\n\n\t\t\/\/ range on a map will not return items in the same order each time\n\t\t\/\/ not the best method to randomly pick twistees to crawl. FIXME\n\t\tfor _, tw := range s.theList {\n\n\t\t\tif tw.status != c.status {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ stats count\n\t\t\tc.totalCount++\n\n\t\t\tif tw.crawlActive == true {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif c.started >= c.maxCount {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (time.Now().Unix() - c.delay) <= tw.lastTry.Unix() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ all looks go so start a go routine to crawl the remote twistee\n\t\t\tgo crawlTwistee(tw)\n\t\t\tc.started++\n\t\t}\n\n\t\tlog.Printf(\"stats - started crawler: %s total: %v started: %v\\n\", c.desc, c.totalCount, c.started)\n\t}\n\n\tlog.Printf(\"stats - crawlers started. total twistees: %d\\n\", tcount)\n\n\t\/\/ returns and read lock released\n}\n\n\/\/ isDup will return true or false depending if the ip exists in theList\nfunc (s *Seeder) isDup(ipport string) bool {\n\ts.mtx.RLock()\n\t_, dup := s.theList[ipport]\n\ts.mtx.RUnlock()\n\treturn dup\n}\n\n\/\/ isNaDup returns true if this wire.NetAddress is already known to us\nfunc (s *Seeder) isNaDup(na *wire.NetAddress) bool {\n\treturn s.isDup(net.JoinHostPort(na.IP.String(), strconv.Itoa(int(na.Port))))\n}\n\n\/\/ addNa validates and adds a network address to theList\nfunc (s *Seeder) addNa(nNa *wire.NetAddress) bool {\n\n\tif dup := s.isNaDup(nNa); dup == true {\n\t\treturn false\n\t}\n\tif nNa.Port <= MINPORT || nNa.Port >= MAXPORT {\n\t\treturn false\n\t}\n\n\t\/\/ if the reported timestamp suggests the netaddress has not been seen in the last 24 hours\n\t\/\/ then ignore this netaddress\n\tif (time.Now().Add(-(time.Hour * 24))).After(nNa.Timestamp) {\n\t\treturn false\n\t}\n\n\tnt := Twistee{\n\t\tna:          nNa,\n\t\tlastConnect: time.Now(),\n\t\tversion:     0,\n\t\tstatus:      statusRG,\n\t\tstatusTime:  time.Now(),\n\t\tdnsType:     DNSV4STD,\n\t}\n\n\t\/\/ select the dns type based on the remote address type and port\n\tif x := nt.na.IP.To4(); x == nil {\n\t\t\/\/ not ipv4\n\t\tif nNa.Port != TWSTDPORT {\n\t\t\tnt.dnsType = DNSV6NON\n\n\t\t\t\/\/ produce the nonstdIP\n\t\t\tnt.nonstdIP = getNonStdIP(nt.na.IP, nt.na.Port)\n\n\t\t} else {\n\t\t\tnt.dnsType = DNSV6STD\n\t\t}\n\t} else {\n\t\t\/\/ ipv4\n\t\tif nNa.Port != TWSTDPORT {\n\t\t\tnt.dnsType = DNSV4NON\n\n\t\t\t\/\/ force ipv4 address into a 4 byte buffer\n\t\t\tnt.na.IP = nt.na.IP.To4()\n\n\t\t\t\/\/ produce the nonstdIP\n\t\t\tnt.nonstdIP = getNonStdIP(nt.na.IP, nt.na.Port)\n\t\t}\n\t}\n\n\t\/\/ generate the key and add to theList\n\tk := net.JoinHostPort(nNa.IP.String(), strconv.Itoa(int(nNa.Port)))\n\ts.mtx.Lock()\n\t\/\/ final check to make sure another twistee & goroutine has not already added this twistee\n\t\/\/ FIXME migrate to use channels\n\tif _, dup := s.theList[k]; dup == false {\n\t\ts.theList[k] = &nt\n\t}\n\ts.mtx.Unlock()\n\n\treturn true\n}\n\n\/\/ getNonStdIP is given an IP address and a port and returns a fake IP address\n\/\/ that is encoded with the original IP and port number. Remote clients can match\n\/\/ the two and work out the real IP and port from the two IP addresses.\nfunc getNonStdIP(rip net.IP, port uint16) net.IP {\n\n\tb := []byte{0x0, 0x0, 0x0, 0x0}\n\tcrcAddr := crc16(rip)\n\tb[0] = byte(crcAddr >> 8)\n\tb[1] = byte((crcAddr & 0xff))\n\tb[2] = byte(port >> 8)\n\tb[3] = byte(port & 0xff)\n\n\tencip := net.IPv4(b[0], b[1], b[2], b[3])\n\tif config.debug {\n\t\tlog.Printf(\"debug - encode nonstd - realip: %s port: %v encip: %s crc: %x\\n\", rip.String(), port, encip.String(), crcAddr)\n\t}\n\n\treturn encip\n}\n\n\/\/ crc16 produces a crc16 from a byte slice\nfunc crc16(bs []byte) uint16 {\n\tvar x, crc uint16\n\tcrc = 0xffff\n\n\tfor _, v := range bs {\n\t\tx = crc>>8 ^ uint16(v)\n\t\tx ^= x >> 4\n\t\tcrc = (crc << 8) ^ (x << 12) ^ (x << 5) ^ x\n\t}\n\treturn crc\n}\n\nfunc (s *Seeder) auditTwistees() {\n\n\tc := 0\n\tlog.Printf(\"status - Audit start. System Uptime: %s\\n\", time.Since(s.uptime).String())\n\n\ts.mtx.Lock()\n\tdefer s.mtx.Unlock()\n\n\tfor k, tw := range s.theList {\n\n\t\tif tw.crawlActive == true {\n\t\t\tif time.Now().Unix()-tw.crawlStart.Unix() >= 300 {\n\t\t\t\tlog.Printf(\"warning - long running crawl > 5 minutes ====\\n- %s status:rating:fails %v:%v:%v crawl start: %s last status: %s\\n====\\n\",\n\t\t\t\t\tk,\n\t\t\t\t\ttw.status,\n\t\t\t\t\ttw.rating,\n\t\t\t\t\ttw.connectFails,\n\t\t\t\t\ttw.crawlStart.String(),\n\t\t\t\t\ttw.statusStr)\n\t\t\t}\n\t\t}\n\t\tif tw.status == statusRG || tw.status == statusWG {\n\t\t\tif time.Now().Unix()-tw.statusTime.Unix() >= 900 {\n\t\t\t\tlog.Printf(\"warning - unchanged status > 15 minutes ====\\n- %s status:rating:fails %v:%v:%v last status change: %s last status: %s\\n====\\n\",\n\t\t\t\t\tk,\n\t\t\t\t\ttw.status,\n\t\t\t\t\ttw.rating,\n\t\t\t\t\ttw.connectFails,\n\t\t\t\t\ttw.statusTime.String(),\n\t\t\t\t\ttw.statusStr)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ last audit task is to remove twistees that we can not connect to\n\t\tif tw.status == statusNG && tw.connectFails > MAXFAILS {\n\t\t\tif config.verbose {\n\t\t\t\tlog.Printf(\"status - purging twistee %s after %v failed connections\\n\", k, tw.connectFails)\n\t\t\t}\n\n\t\t\tc++\n\t\t\t\/\/ remove the map entry and mark the old twistee as\n\t\t\t\/\/ nil so garbage collector will remove it\n\t\t\ts.theList[k] = nil\n\t\t\tdelete(s.theList, k)\n\t\t}\n\n\t}\n\tif config.verbose {\n\t\tlog.Printf(\"status - Audit complete. %v twistees purged\\n\", c)\n\t}\n\n}\n\n\/\/ teatload loads the dns records with time based test data\nfunc (s *Seeder) loadDNS() {\n\n\tupdateDNS(s)\n}\n\n\/*\n\n *\/\n<commit_msg>Update version to stop reset by peer errors<commit_after>package main\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/btcsuite\/btcd\/wire\"\n)\n\nconst (\n\n\t\/\/ Twister Magic number to make it incompatible with the Bitcoin network\n\tTWISTNET = 0xd2bbdaf0\n\t\/\/ nounce is used to check if we connect to ourselves\n\t\/\/ as we don't listen we can use a fixed value\n\tNOUNCE  = 0x0539a019ca550825\n\tPVER    = 60000\n\tMINPORT = 0\n\tMAXPORT = 65535\n\n\tTWSTDPORT = 28333 \/\/ standard port twister listens on\n\n\tMAXFAILS = 58 \/\/ max number of connect fails before we delete a twistee. Just over 24 hours(checked every 33 minutes)\n\n\tMAXTO = 250 \/\/ max seconds (4min 10 sec) for all comms to twistee to complete before we timeout\n\n\t\/\/ DNS Type. Is this twistee using v4\/v6 and standard or non standard ports\n\tDNSV4STD = 1\n\tDNSV4NON = 2\n\tDNSV6STD = 3\n\tDNSV6NON = 4\n\n\t\/\/ twistee status\n\tstatusRG = 1 \/\/ reported good status. A remote twistee has reported this ip but we have not connected\n\tstatusCG = 2 \/\/ confirmed good. We have connected to the twistee and received addresses\n\tstatusWG = 3 \/\/ was good. Twistee was confirmed good but now having problems\n\tstatusNG = 4 \/\/ no good. Will be removed from theList after 24 hours to redure bouncing ip addresses\n\n)\n\ntype Seeder struct {\n\tuptime  time.Time\n\ttheList map[string]*Twistee\n\tmtx     sync.RWMutex\n}\n\n\/\/ initCrawlers needs to be run before the startCrawlers so it can get\n\/\/ a list of current ip addresses from the other seeders and therefore\n\/\/ start the crawl process\nfunc initCrawlers() {\n\n\tseeders := []string{\"seed2.twister.net.co\", \"seed3.twister.net.co\", \"seed.twister.net.co\"}\n\n\tfor _, seeder := range seeders {\n\t\tc := 0\n\n\t\tnewRRs, err := net.LookupHost(seeder)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"status - unable to do initial lookup to seeder %s %v\\n\", seeder, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, ip := range newRRs {\n\t\t\tif newIP := net.ParseIP(ip); newIP != nil {\n\t\t\t\t\/\/ 1 at the end is the services flag\n\t\t\t\tif x := config.seeder.addNa(wire.NewNetAddressIPPort(newIP, 28333, 1)); x == true {\n\t\t\t\t\tc++\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif config.verbose {\n\t\t\tlog.Printf(\"status - completed import of %v addresses from %s\\n\", c, seeder)\n\t\t}\n\t}\n}\n\n\/\/ startCrawlers is called on a time basis to start maxcrawlers new\n\/\/ goroutines if there are spare goroutine slots available\nfunc (s *Seeder) startCrawlers() {\n\n\ttcount := len(s.theList)\n\tif tcount == 0 {\n\t\tif config.debug {\n\t\t\tlog.Printf(\"debug - startCrawlers fail: no twistees available\\n\")\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ struct to hold config options for each status\n\tvar crawlers = []struct {\n\t\tdesc       string\n\t\tstatus     uint32\n\t\tmaxCount   uint32 \/\/ max goroutines to start for this status type\n\t\ttotalCount uint32 \/\/ stats count of this type\n\t\tstarted    uint32 \/\/ count of goroutines started for this type\n\t\tdelay      int64  \/\/ number of second since last try\n\t}{\n\t\t{\"statusRG\", statusRG, 10, 0, 0, 184},\n\t\t{\"statusCG\", statusCG, 10, 0, 0, 325},\n\t\t{\"statusWG\", statusWG, 10, 0, 0, 237},\n\t\t{\"statusNG\", statusNG, 20, 0, 0, 1876},\n\t}\n\n\ts.mtx.RLock()\n\tdefer s.mtx.RUnlock()\n\n\tfor _, c := range crawlers {\n\n\t\t\/\/ range on a map will not return items in the same order each time\n\t\t\/\/ not the best method to randomly pick twistees to crawl. FIXME\n\t\tfor _, tw := range s.theList {\n\n\t\t\tif tw.status != c.status {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ stats count\n\t\t\tc.totalCount++\n\n\t\t\tif tw.crawlActive == true {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif c.started >= c.maxCount {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif (time.Now().Unix() - c.delay) <= tw.lastTry.Unix() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ all looks go so start a go routine to crawl the remote twistee\n\t\t\tgo crawlTwistee(tw)\n\t\t\tc.started++\n\t\t}\n\n\t\tlog.Printf(\"stats - started crawler: %s total: %v started: %v\\n\", c.desc, c.totalCount, c.started)\n\t}\n\n\tlog.Printf(\"stats - crawlers started. total twistees: %d\\n\", tcount)\n\n\t\/\/ returns and read lock released\n}\n\n\/\/ isDup will return true or false depending if the ip exists in theList\nfunc (s *Seeder) isDup(ipport string) bool {\n\ts.mtx.RLock()\n\t_, dup := s.theList[ipport]\n\ts.mtx.RUnlock()\n\treturn dup\n}\n\n\/\/ isNaDup returns true if this wire.NetAddress is already known to us\nfunc (s *Seeder) isNaDup(na *wire.NetAddress) bool {\n\treturn s.isDup(net.JoinHostPort(na.IP.String(), strconv.Itoa(int(na.Port))))\n}\n\n\/\/ addNa validates and adds a network address to theList\nfunc (s *Seeder) addNa(nNa *wire.NetAddress) bool {\n\n\tif dup := s.isNaDup(nNa); dup == true {\n\t\treturn false\n\t}\n\tif nNa.Port <= MINPORT || nNa.Port >= MAXPORT {\n\t\treturn false\n\t}\n\n\t\/\/ if the reported timestamp suggests the netaddress has not been seen in the last 24 hours\n\t\/\/ then ignore this netaddress\n\tif (time.Now().Add(-(time.Hour * 24))).After(nNa.Timestamp) {\n\t\treturn false\n\t}\n\n\tnt := Twistee{\n\t\tna:          nNa,\n\t\tlastConnect: time.Now(),\n\t\tversion:     0,\n\t\tstatus:      statusRG,\n\t\tstatusTime:  time.Now(),\n\t\tdnsType:     DNSV4STD,\n\t}\n\n\t\/\/ select the dns type based on the remote address type and port\n\tif x := nt.na.IP.To4(); x == nil {\n\t\t\/\/ not ipv4\n\t\tif nNa.Port != TWSTDPORT {\n\t\t\tnt.dnsType = DNSV6NON\n\n\t\t\t\/\/ produce the nonstdIP\n\t\t\tnt.nonstdIP = getNonStdIP(nt.na.IP, nt.na.Port)\n\n\t\t} else {\n\t\t\tnt.dnsType = DNSV6STD\n\t\t}\n\t} else {\n\t\t\/\/ ipv4\n\t\tif nNa.Port != TWSTDPORT {\n\t\t\tnt.dnsType = DNSV4NON\n\n\t\t\t\/\/ force ipv4 address into a 4 byte buffer\n\t\t\tnt.na.IP = nt.na.IP.To4()\n\n\t\t\t\/\/ produce the nonstdIP\n\t\t\tnt.nonstdIP = getNonStdIP(nt.na.IP, nt.na.Port)\n\t\t}\n\t}\n\n\t\/\/ generate the key and add to theList\n\tk := net.JoinHostPort(nNa.IP.String(), strconv.Itoa(int(nNa.Port)))\n\ts.mtx.Lock()\n\t\/\/ final check to make sure another twistee & goroutine has not already added this twistee\n\t\/\/ FIXME migrate to use channels\n\tif _, dup := s.theList[k]; dup == false {\n\t\ts.theList[k] = &nt\n\t}\n\ts.mtx.Unlock()\n\n\treturn true\n}\n\n\/\/ getNonStdIP is given an IP address and a port and returns a fake IP address\n\/\/ that is encoded with the original IP and port number. Remote clients can match\n\/\/ the two and work out the real IP and port from the two IP addresses.\nfunc getNonStdIP(rip net.IP, port uint16) net.IP {\n\n\tb := []byte{0x0, 0x0, 0x0, 0x0}\n\tcrcAddr := crc16(rip)\n\tb[0] = byte(crcAddr >> 8)\n\tb[1] = byte((crcAddr & 0xff))\n\tb[2] = byte(port >> 8)\n\tb[3] = byte(port & 0xff)\n\n\tencip := net.IPv4(b[0], b[1], b[2], b[3])\n\tif config.debug {\n\t\tlog.Printf(\"debug - encode nonstd - realip: %s port: %v encip: %s crc: %x\\n\", rip.String(), port, encip.String(), crcAddr)\n\t}\n\n\treturn encip\n}\n\n\/\/ crc16 produces a crc16 from a byte slice\nfunc crc16(bs []byte) uint16 {\n\tvar x, crc uint16\n\tcrc = 0xffff\n\n\tfor _, v := range bs {\n\t\tx = crc>>8 ^ uint16(v)\n\t\tx ^= x >> 4\n\t\tcrc = (crc << 8) ^ (x << 12) ^ (x << 5) ^ x\n\t}\n\treturn crc\n}\n\nfunc (s *Seeder) auditTwistees() {\n\n\tc := 0\n\tlog.Printf(\"status - Audit start. System Uptime: %s\\n\", time.Since(s.uptime).String())\n\n\ts.mtx.Lock()\n\tdefer s.mtx.Unlock()\n\n\tfor k, tw := range s.theList {\n\n\t\tif tw.crawlActive == true {\n\t\t\tif time.Now().Unix()-tw.crawlStart.Unix() >= 300 {\n\t\t\t\tlog.Printf(\"warning - long running crawl > 5 minutes ====\\n- %s status:rating:fails %v:%v:%v crawl start: %s last status: %s\\n====\\n\",\n\t\t\t\t\tk,\n\t\t\t\t\ttw.status,\n\t\t\t\t\ttw.rating,\n\t\t\t\t\ttw.connectFails,\n\t\t\t\t\ttw.crawlStart.String(),\n\t\t\t\t\ttw.statusStr)\n\t\t\t}\n\t\t}\n\t\tif tw.status == statusRG || tw.status == statusWG {\n\t\t\tif time.Now().Unix()-tw.statusTime.Unix() >= 900 {\n\t\t\t\tlog.Printf(\"warning - unchanged status > 15 minutes ====\\n- %s status:rating:fails %v:%v:%v last status change: %s last status: %s\\n====\\n\",\n\t\t\t\t\tk,\n\t\t\t\t\ttw.status,\n\t\t\t\t\ttw.rating,\n\t\t\t\t\ttw.connectFails,\n\t\t\t\t\ttw.statusTime.String(),\n\t\t\t\t\ttw.statusStr)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ last audit task is to remove twistees that we can not connect to\n\t\tif tw.status == statusNG && tw.connectFails > MAXFAILS {\n\t\t\tif config.verbose {\n\t\t\t\tlog.Printf(\"status - purging twistee %s after %v failed connections\\n\", k, tw.connectFails)\n\t\t\t}\n\n\t\t\tc++\n\t\t\t\/\/ remove the map entry and mark the old twistee as\n\t\t\t\/\/ nil so garbage collector will remove it\n\t\t\ts.theList[k] = nil\n\t\t\tdelete(s.theList, k)\n\t\t}\n\n\t}\n\tif config.verbose {\n\t\tlog.Printf(\"status - Audit complete. %v twistees purged\\n\", c)\n\t}\n\n}\n\n\/\/ teatload loads the dns records with time based test data\nfunc (s *Seeder) loadDNS() {\n\n\tupdateDNS(s)\n}\n\n\/*\n\n *\/\n<|endoftext|>"}
{"text":"<commit_before>package logrus_sentry\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/getsentry\/raven-go\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nvar (\n\tseverityMap = map[logrus.Level]raven.Severity{\n\t\tlogrus.TraceLevel: raven.DEBUG,\n\t\tlogrus.DebugLevel: raven.DEBUG,\n\t\tlogrus.InfoLevel:  raven.INFO,\n\t\tlogrus.WarnLevel:  raven.WARNING,\n\t\tlogrus.ErrorLevel: raven.ERROR,\n\t\tlogrus.FatalLevel: raven.FATAL,\n\t\tlogrus.PanicLevel: raven.FATAL,\n\t}\n)\n\n\/\/ SentryHook delivers logs to a sentry server.\ntype SentryHook struct {\n\t\/\/ Timeout sets the time to wait for a delivery error from the sentry server.\n\t\/\/ If this is set to zero the server will not wait for any response and will\n\t\/\/ consider the message correctly sent.\n\t\/\/\n\t\/\/ This is ignored for asynchronous hooks. If you want to set a timeout when\n\t\/\/ using an async hook (to bound the length of time that hook.Flush can take),\n\t\/\/ you probably want to create your own raven.Client and set\n\t\/\/ ravenClient.Transport.(*raven.HTTPTransport).Client.Timeout to set a\n\t\/\/ timeout on the underlying HTTP request instead.\n\tTimeout                 time.Duration\n\tStacktraceConfiguration StackTraceConfiguration\n\n\tclient *raven.Client\n\tlevels []logrus.Level\n\n\tserverName   string\n\tignoreFields map[string]struct{}\n\textraFilters map[string]func(interface{}) interface{}\n\n\tasynchronous bool\n\n\tmu sync.RWMutex\n\twg sync.WaitGroup\n}\n\n\/\/ The Stacktracer interface allows an error type to return a raven.Stacktrace.\ntype Stacktracer interface {\n\tGetStacktrace() *raven.Stacktrace\n}\n\ntype causer interface {\n\tCause() error\n}\n\ntype pkgErrorStackTracer interface {\n\tStackTrace() errors.StackTrace\n}\n\n\/\/ StackTraceConfiguration allows for configuring stacktraces\ntype StackTraceConfiguration struct {\n\t\/\/ whether stacktraces should be enabled\n\tEnable bool\n\t\/\/ the level at which to start capturing stacktraces\n\tLevel logrus.Level\n\t\/\/ how many stack frames to skip before stacktrace starts recording\n\tSkip int\n\t\/\/ the number of lines to include around a stack frame for context\n\tContext int\n\t\/\/ the prefixes that will be matched against the stack frame.\n\t\/\/ if the stack frame's package matches one of these prefixes\n\t\/\/ sentry will identify the stack frame as \"in_app\"\n\tInAppPrefixes []string\n\t\/\/ whether sending exception type should be enabled.\n\tSendExceptionType bool\n\t\/\/ whether the exception type and message should be switched.\n\tSwitchExceptionTypeAndMessage bool\n}\n\n\/\/ NewSentryHook creates a hook to be added to an instance of logger\n\/\/ and initializes the raven client.\n\/\/ This method sets the timeout to 100 milliseconds.\nfunc NewSentryHook(DSN string, levels []logrus.Level) (*SentryHook, error) {\n\tclient, err := raven.New(DSN)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewWithClientSentryHook(client, levels)\n}\n\n\/\/ NewWithTagsSentryHook creates a hook with tags to be added to an instance\n\/\/ of logger and initializes the raven client. This method sets the timeout to\n\/\/ 100 milliseconds.\nfunc NewWithTagsSentryHook(DSN string, tags map[string]string, levels []logrus.Level) (*SentryHook, error) {\n\tclient, err := raven.NewWithTags(DSN, tags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewWithClientSentryHook(client, levels)\n}\n\n\/\/ NewWithClientSentryHook creates a hook using an initialized raven client.\n\/\/ This method sets the timeout to 100 milliseconds.\nfunc NewWithClientSentryHook(client *raven.Client, levels []logrus.Level) (*SentryHook, error) {\n\treturn &SentryHook{\n\t\tTimeout: 100 * time.Millisecond,\n\t\tStacktraceConfiguration: StackTraceConfiguration{\n\t\t\tEnable:            false,\n\t\t\tLevel:             logrus.ErrorLevel,\n\t\t\tSkip:              5,\n\t\t\tContext:           0,\n\t\t\tInAppPrefixes:     nil,\n\t\t\tSendExceptionType: true,\n\t\t},\n\t\tclient:       client,\n\t\tlevels:       levels,\n\t\tignoreFields: make(map[string]struct{}),\n\t\textraFilters: make(map[string]func(interface{}) interface{}),\n\t}, nil\n}\n\n\/\/ NewAsyncSentryHook creates a hook same as NewSentryHook, but in asynchronous\n\/\/ mode.\nfunc NewAsyncSentryHook(DSN string, levels []logrus.Level) (*SentryHook, error) {\n\thook, err := NewSentryHook(DSN, levels)\n\treturn setAsync(hook), err\n}\n\n\/\/ NewAsyncWithTagsSentryHook creates a hook same as NewWithTagsSentryHook, but\n\/\/ in asynchronous mode.\nfunc NewAsyncWithTagsSentryHook(DSN string, tags map[string]string, levels []logrus.Level) (*SentryHook, error) {\n\thook, err := NewWithTagsSentryHook(DSN, tags, levels)\n\treturn setAsync(hook), err\n}\n\n\/\/ NewAsyncWithClientSentryHook creates a hook same as NewWithClientSentryHook,\n\/\/ but in asynchronous mode.\nfunc NewAsyncWithClientSentryHook(client *raven.Client, levels []logrus.Level) (*SentryHook, error) {\n\thook, err := NewWithClientSentryHook(client, levels)\n\treturn setAsync(hook), err\n}\n\nfunc setAsync(hook *SentryHook) *SentryHook {\n\tif hook == nil {\n\t\treturn nil\n\t}\n\thook.asynchronous = true\n\treturn hook\n}\n\n\/\/ Fire is called when an event should be sent to sentry\n\/\/ Special fields that sentry uses to give more information to the server\n\/\/ are extracted from entry.Data (if they are found)\n\/\/ These fields are: error, logger, server_name, http_request, tags\nfunc (hook *SentryHook) Fire(entry *logrus.Entry) error {\n\thook.mu.RLock() \/\/ Allow multiple go routines to log simultaneously\n\tdefer hook.mu.RUnlock()\n\tpacket := raven.NewPacket(entry.Message)\n\tpacket.Timestamp = raven.Timestamp(entry.Time)\n\tpacket.Level = severityMap[entry.Level]\n\tpacket.Platform = \"go\"\n\n\tdf := newDataField(entry.Data)\n\n\t\/\/ set special fields\n\tif hook.serverName != \"\" {\n\t\tpacket.ServerName = hook.serverName\n\t}\n\tif logger, ok := df.getLogger(); ok {\n\t\tpacket.Logger = logger\n\t}\n\tif serverName, ok := df.getServerName(); ok {\n\t\tpacket.ServerName = serverName\n\t}\n\tif eventID, ok := df.getEventID(); ok {\n\t\tpacket.EventID = eventID\n\t}\n\tif tags, ok := df.getTags(); ok {\n\t\tpacket.Tags = tags\n\t}\n\tif fingerprint, ok := df.getFingerprint(); ok {\n\t\tpacket.Fingerprint = fingerprint\n\t}\n\tif req, ok := df.getHTTPRequest(); ok {\n\t\tpacket.Interfaces = append(packet.Interfaces, req)\n\t}\n\tif user, ok := df.getUser(); ok {\n\t\tpacket.Interfaces = append(packet.Interfaces, user)\n\t}\n\n\t\/\/ set stacktrace data\n\tstConfig := &hook.StacktraceConfiguration\n\tif stConfig.Enable && entry.Level <= stConfig.Level {\n\t\tif err, ok := df.getError(); ok {\n\t\t\tvar currentStacktrace *raven.Stacktrace\n\t\t\tcurrentStacktrace = hook.findStacktrace(err)\n\t\t\tif currentStacktrace == nil {\n\t\t\t\tcurrentStacktrace = raven.NewStacktrace(stConfig.Skip, stConfig.Context, stConfig.InAppPrefixes)\n\t\t\t}\n\t\t\tcause := errors.Cause(err)\n\t\t\tif cause == nil {\n\t\t\t\tcause = err\n\t\t\t}\n\t\t\texc := raven.NewException(cause, currentStacktrace)\n\t\t\tif !stConfig.SendExceptionType {\n\t\t\t\texc.Type = \"\"\n\t\t\t}\n\t\t\tif stConfig.SwitchExceptionTypeAndMessage {\n\t\t\t\tpacket.Interfaces = append(packet.Interfaces, currentStacktrace)\n\t\t\t\tpacket.Culprit = exc.Type + \": \" + currentStacktrace.Culprit()\n\t\t\t} else {\n\t\t\t\tpacket.Interfaces = append(packet.Interfaces, exc)\n\t\t\t\tpacket.Culprit = err.Error()\n\t\t\t}\n\t\t} else {\n\t\t\tcurrentStacktrace := raven.NewStacktrace(stConfig.Skip, stConfig.Context, stConfig.InAppPrefixes)\n\t\t\tif currentStacktrace != nil {\n\t\t\t\tpacket.Interfaces = append(packet.Interfaces, currentStacktrace)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\/\/ set the culprit even when the stack trace is disabled, as long as we have an error\n\t\tif err, ok := df.getError(); ok {\n\t\t\tpacket.Culprit = err.Error()\n\t\t}\n\t}\n\n\t\/\/ set other fields\n\tdataExtra := hook.formatExtraData(df)\n\tif packet.Extra == nil {\n\t\tpacket.Extra = dataExtra\n\t} else {\n\t\tfor k, v := range dataExtra {\n\t\t\tpacket.Extra[k] = v\n\t\t}\n\t}\n\n\t_, errCh := hook.client.Capture(packet, nil)\n\n\tif hook.asynchronous {\n\t\t\/\/ Our use of hook.mu guarantees that we are following the WaitGroup rule of\n\t\t\/\/ not calling Add in parallel with Wait.\n\t\thook.wg.Add(1)\n\t\tgo func() {\n\t\t\tif err := <-errCh; err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\thook.wg.Done()\n\t\t}()\n\t\treturn nil\n\t} else if timeout := hook.Timeout; timeout == 0 {\n\t\treturn nil\n\t} else {\n\t\ttimeoutCh := time.After(timeout)\n\t\tselect {\n\t\tcase err := <-errCh:\n\t\t\treturn err\n\t\tcase <-timeoutCh:\n\t\t\treturn fmt.Errorf(\"no response from sentry server in %s\", timeout)\n\t\t}\n\t}\n}\n\n\/\/ Flush waits for the log queue to empty. This function only does anything in\n\/\/ asynchronous mode.\nfunc (hook *SentryHook) Flush() {\n\tif !hook.asynchronous {\n\t\treturn\n\t}\n\thook.mu.Lock() \/\/ Claim exclusive access; any logging goroutines will block until the flush completes\n\tdefer hook.mu.Unlock()\n\n\thook.wg.Wait()\n}\n\nfunc (hook *SentryHook) findStacktrace(err error) *raven.Stacktrace {\n\tvar stacktrace *raven.Stacktrace\n\tvar stackErr errors.StackTrace\n\tfor err != nil {\n\t\t\/\/ Find the earliest *raven.Stacktrace, or error.StackTrace\n\t\tif tracer, ok := err.(Stacktracer); ok {\n\t\t\tstacktrace = tracer.GetStacktrace()\n\t\t\tstackErr = nil\n\t\t} else if tracer, ok := err.(pkgErrorStackTracer); ok {\n\t\t\tstacktrace = nil\n\t\t\tstackErr = tracer.StackTrace()\n\t\t}\n\t\tif cause, ok := err.(causer); ok {\n\t\t\terr = cause.Cause()\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tif stackErr != nil {\n\t\tstacktrace = hook.convertStackTrace(stackErr)\n\t}\n\treturn stacktrace\n}\n\n\/\/ convertStackTrace converts an errors.StackTrace into a natively consumable\n\/\/ *raven.Stacktrace\nfunc (hook *SentryHook) convertStackTrace(st errors.StackTrace) *raven.Stacktrace {\n\tstConfig := &hook.StacktraceConfiguration\n\tstFrames := []errors.Frame(st)\n\tframes := make([]*raven.StacktraceFrame, 0, len(stFrames))\n\tfor i := range stFrames {\n\t\tpc := uintptr(stFrames[i])\n\t\tfn := runtime.FuncForPC(pc)\n\t\tfile, line := fn.FileLine(pc)\n\t\tframe := raven.NewStacktraceFrame(pc, fn.Name(), file, line, stConfig.Context, stConfig.InAppPrefixes)\n\t\tif frame != nil {\n\t\t\tframes = append(frames, frame)\n\t\t}\n\t}\n\n\t\/\/ Sentry wants the frames with the oldest first, so reverse them\n\tfor i, j := 0, len(frames)-1; i < j; i, j = i+1, j-1 {\n\t\tframes[i], frames[j] = frames[j], frames[i]\n\t}\n\treturn &raven.Stacktrace{Frames: frames}\n}\n\n\/\/ Levels returns the available logging levels.\nfunc (hook *SentryHook) Levels() []logrus.Level {\n\treturn hook.levels\n}\n\n\/\/ AddIgnore adds field name to ignore.\nfunc (hook *SentryHook) AddIgnore(name string) {\n\thook.ignoreFields[name] = struct{}{}\n}\n\n\/\/ AddExtraFilter adds a custom filter function.\nfunc (hook *SentryHook) AddExtraFilter(name string, fn func(interface{}) interface{}) {\n\thook.extraFilters[name] = fn\n}\n\nfunc (hook *SentryHook) formatExtraData(df *dataField) (result map[string]interface{}) {\n\t\/\/ create a map for passing to Sentry's extra data\n\tresult = make(map[string]interface{}, df.len())\n\tfor k, v := range df.data {\n\t\tif df.isOmit(k) {\n\t\t\tcontinue \/\/ skip already used special fields\n\t\t}\n\t\tif _, ok := hook.ignoreFields[k]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif fn, ok := hook.extraFilters[k]; ok {\n\t\t\tv = fn(v) \/\/ apply custom filter\n\t\t} else {\n\t\t\tv = formatData(v) \/\/ use default formatter\n\t\t}\n\t\tresult[k] = v\n\t}\n\treturn result\n}\n\n\/\/ formatData returns value as a suitable format.\nfunc formatData(value interface{}) (formatted interface{}) {\n\tswitch value := value.(type) {\n\tcase json.Marshaler:\n\t\treturn value\n\tcase error:\n\t\treturn value.Error()\n\tcase fmt.Stringer:\n\t\treturn value.String()\n\tdefault:\n\t\treturn value\n\t}\n}\n<commit_msg>use runtime.Frame instead of program counters after braking change to github.com\/pkg\/errors (#75)<commit_after>package logrus_sentry\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/getsentry\/raven-go\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nvar (\n\tseverityMap = map[logrus.Level]raven.Severity{\n\t\tlogrus.TraceLevel: raven.DEBUG,\n\t\tlogrus.DebugLevel: raven.DEBUG,\n\t\tlogrus.InfoLevel:  raven.INFO,\n\t\tlogrus.WarnLevel:  raven.WARNING,\n\t\tlogrus.ErrorLevel: raven.ERROR,\n\t\tlogrus.FatalLevel: raven.FATAL,\n\t\tlogrus.PanicLevel: raven.FATAL,\n\t}\n)\n\n\/\/ SentryHook delivers logs to a sentry server.\ntype SentryHook struct {\n\t\/\/ Timeout sets the time to wait for a delivery error from the sentry server.\n\t\/\/ If this is set to zero the server will not wait for any response and will\n\t\/\/ consider the message correctly sent.\n\t\/\/\n\t\/\/ This is ignored for asynchronous hooks. If you want to set a timeout when\n\t\/\/ using an async hook (to bound the length of time that hook.Flush can take),\n\t\/\/ you probably want to create your own raven.Client and set\n\t\/\/ ravenClient.Transport.(*raven.HTTPTransport).Client.Timeout to set a\n\t\/\/ timeout on the underlying HTTP request instead.\n\tTimeout                 time.Duration\n\tStacktraceConfiguration StackTraceConfiguration\n\n\tclient *raven.Client\n\tlevels []logrus.Level\n\n\tserverName   string\n\tignoreFields map[string]struct{}\n\textraFilters map[string]func(interface{}) interface{}\n\n\tasynchronous bool\n\n\tmu sync.RWMutex\n\twg sync.WaitGroup\n}\n\n\/\/ The Stacktracer interface allows an error type to return a raven.Stacktrace.\ntype Stacktracer interface {\n\tGetStacktrace() *raven.Stacktrace\n}\n\ntype causer interface {\n\tCause() error\n}\n\ntype pkgErrorStackTracer interface {\n\tStackTrace() errors.StackTrace\n}\n\n\/\/ StackTraceConfiguration allows for configuring stacktraces\ntype StackTraceConfiguration struct {\n\t\/\/ whether stacktraces should be enabled\n\tEnable bool\n\t\/\/ the level at which to start capturing stacktraces\n\tLevel logrus.Level\n\t\/\/ how many stack frames to skip before stacktrace starts recording\n\tSkip int\n\t\/\/ the number of lines to include around a stack frame for context\n\tContext int\n\t\/\/ the prefixes that will be matched against the stack frame.\n\t\/\/ if the stack frame's package matches one of these prefixes\n\t\/\/ sentry will identify the stack frame as \"in_app\"\n\tInAppPrefixes []string\n\t\/\/ whether sending exception type should be enabled.\n\tSendExceptionType bool\n\t\/\/ whether the exception type and message should be switched.\n\tSwitchExceptionTypeAndMessage bool\n}\n\n\/\/ NewSentryHook creates a hook to be added to an instance of logger\n\/\/ and initializes the raven client.\n\/\/ This method sets the timeout to 100 milliseconds.\nfunc NewSentryHook(DSN string, levels []logrus.Level) (*SentryHook, error) {\n\tclient, err := raven.New(DSN)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewWithClientSentryHook(client, levels)\n}\n\n\/\/ NewWithTagsSentryHook creates a hook with tags to be added to an instance\n\/\/ of logger and initializes the raven client. This method sets the timeout to\n\/\/ 100 milliseconds.\nfunc NewWithTagsSentryHook(DSN string, tags map[string]string, levels []logrus.Level) (*SentryHook, error) {\n\tclient, err := raven.NewWithTags(DSN, tags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewWithClientSentryHook(client, levels)\n}\n\n\/\/ NewWithClientSentryHook creates a hook using an initialized raven client.\n\/\/ This method sets the timeout to 100 milliseconds.\nfunc NewWithClientSentryHook(client *raven.Client, levels []logrus.Level) (*SentryHook, error) {\n\treturn &SentryHook{\n\t\tTimeout: 100 * time.Millisecond,\n\t\tStacktraceConfiguration: StackTraceConfiguration{\n\t\t\tEnable:            false,\n\t\t\tLevel:             logrus.ErrorLevel,\n\t\t\tSkip:              6,\n\t\t\tContext:           0,\n\t\t\tInAppPrefixes:     nil,\n\t\t\tSendExceptionType: true,\n\t\t},\n\t\tclient:       client,\n\t\tlevels:       levels,\n\t\tignoreFields: make(map[string]struct{}),\n\t\textraFilters: make(map[string]func(interface{}) interface{}),\n\t}, nil\n}\n\n\/\/ NewAsyncSentryHook creates a hook same as NewSentryHook, but in asynchronous\n\/\/ mode.\nfunc NewAsyncSentryHook(DSN string, levels []logrus.Level) (*SentryHook, error) {\n\thook, err := NewSentryHook(DSN, levels)\n\treturn setAsync(hook), err\n}\n\n\/\/ NewAsyncWithTagsSentryHook creates a hook same as NewWithTagsSentryHook, but\n\/\/ in asynchronous mode.\nfunc NewAsyncWithTagsSentryHook(DSN string, tags map[string]string, levels []logrus.Level) (*SentryHook, error) {\n\thook, err := NewWithTagsSentryHook(DSN, tags, levels)\n\treturn setAsync(hook), err\n}\n\n\/\/ NewAsyncWithClientSentryHook creates a hook same as NewWithClientSentryHook,\n\/\/ but in asynchronous mode.\nfunc NewAsyncWithClientSentryHook(client *raven.Client, levels []logrus.Level) (*SentryHook, error) {\n\thook, err := NewWithClientSentryHook(client, levels)\n\treturn setAsync(hook), err\n}\n\nfunc setAsync(hook *SentryHook) *SentryHook {\n\tif hook == nil {\n\t\treturn nil\n\t}\n\thook.asynchronous = true\n\treturn hook\n}\n\n\/\/ Fire is called when an event should be sent to sentry\n\/\/ Special fields that sentry uses to give more information to the server\n\/\/ are extracted from entry.Data (if they are found)\n\/\/ These fields are: error, logger, server_name, http_request, tags\nfunc (hook *SentryHook) Fire(entry *logrus.Entry) error {\n\thook.mu.RLock() \/\/ Allow multiple go routines to log simultaneously\n\tdefer hook.mu.RUnlock()\n\tpacket := raven.NewPacket(entry.Message)\n\tpacket.Timestamp = raven.Timestamp(entry.Time)\n\tpacket.Level = severityMap[entry.Level]\n\tpacket.Platform = \"go\"\n\n\tdf := newDataField(entry.Data)\n\n\t\/\/ set special fields\n\tif hook.serverName != \"\" {\n\t\tpacket.ServerName = hook.serverName\n\t}\n\tif logger, ok := df.getLogger(); ok {\n\t\tpacket.Logger = logger\n\t}\n\tif serverName, ok := df.getServerName(); ok {\n\t\tpacket.ServerName = serverName\n\t}\n\tif eventID, ok := df.getEventID(); ok {\n\t\tpacket.EventID = eventID\n\t}\n\tif tags, ok := df.getTags(); ok {\n\t\tpacket.Tags = tags\n\t}\n\tif fingerprint, ok := df.getFingerprint(); ok {\n\t\tpacket.Fingerprint = fingerprint\n\t}\n\tif req, ok := df.getHTTPRequest(); ok {\n\t\tpacket.Interfaces = append(packet.Interfaces, req)\n\t}\n\tif user, ok := df.getUser(); ok {\n\t\tpacket.Interfaces = append(packet.Interfaces, user)\n\t}\n\n\t\/\/ set stacktrace data\n\tstConfig := &hook.StacktraceConfiguration\n\tif stConfig.Enable && entry.Level <= stConfig.Level {\n\t\tif err, ok := df.getError(); ok {\n\t\t\tvar currentStacktrace *raven.Stacktrace\n\t\t\tcurrentStacktrace = hook.findStacktrace(err)\n\t\t\tif currentStacktrace == nil {\n\t\t\t\tcurrentStacktrace = raven.NewStacktrace(stConfig.Skip, stConfig.Context, stConfig.InAppPrefixes)\n\t\t\t}\n\t\t\tcause := errors.Cause(err)\n\t\t\tif cause == nil {\n\t\t\t\tcause = err\n\t\t\t}\n\t\t\texc := raven.NewException(cause, currentStacktrace)\n\t\t\tif !stConfig.SendExceptionType {\n\t\t\t\texc.Type = \"\"\n\t\t\t}\n\t\t\tif stConfig.SwitchExceptionTypeAndMessage {\n\t\t\t\tpacket.Interfaces = append(packet.Interfaces, currentStacktrace)\n\t\t\t\tpacket.Culprit = exc.Type + \": \" + currentStacktrace.Culprit()\n\t\t\t} else {\n\t\t\t\tpacket.Interfaces = append(packet.Interfaces, exc)\n\t\t\t\tpacket.Culprit = err.Error()\n\t\t\t}\n\t\t} else {\n\t\t\tcurrentStacktrace := raven.NewStacktrace(stConfig.Skip, stConfig.Context, stConfig.InAppPrefixes)\n\t\t\tif currentStacktrace != nil {\n\t\t\t\tpacket.Interfaces = append(packet.Interfaces, currentStacktrace)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\/\/ set the culprit even when the stack trace is disabled, as long as we have an error\n\t\tif err, ok := df.getError(); ok {\n\t\t\tpacket.Culprit = err.Error()\n\t\t}\n\t}\n\n\t\/\/ set other fields\n\tdataExtra := hook.formatExtraData(df)\n\tif packet.Extra == nil {\n\t\tpacket.Extra = dataExtra\n\t} else {\n\t\tfor k, v := range dataExtra {\n\t\t\tpacket.Extra[k] = v\n\t\t}\n\t}\n\n\t_, errCh := hook.client.Capture(packet, nil)\n\n\tif hook.asynchronous {\n\t\t\/\/ Our use of hook.mu guarantees that we are following the WaitGroup rule of\n\t\t\/\/ not calling Add in parallel with Wait.\n\t\thook.wg.Add(1)\n\t\tgo func() {\n\t\t\tif err := <-errCh; err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t\thook.wg.Done()\n\t\t}()\n\t\treturn nil\n\t} else if timeout := hook.Timeout; timeout == 0 {\n\t\treturn nil\n\t} else {\n\t\ttimeoutCh := time.After(timeout)\n\t\tselect {\n\t\tcase err := <-errCh:\n\t\t\treturn err\n\t\tcase <-timeoutCh:\n\t\t\treturn fmt.Errorf(\"no response from sentry server in %s\", timeout)\n\t\t}\n\t}\n}\n\n\/\/ Flush waits for the log queue to empty. This function only does anything in\n\/\/ asynchronous mode.\nfunc (hook *SentryHook) Flush() {\n\tif !hook.asynchronous {\n\t\treturn\n\t}\n\thook.mu.Lock() \/\/ Claim exclusive access; any logging goroutines will block until the flush completes\n\tdefer hook.mu.Unlock()\n\n\thook.wg.Wait()\n}\n\nfunc (hook *SentryHook) findStacktrace(err error) *raven.Stacktrace {\n\tvar stacktrace *raven.Stacktrace\n\tvar stackErr errors.StackTrace\n\tfor err != nil {\n\t\t\/\/ Find the earliest *raven.Stacktrace, or error.StackTrace\n\t\tif tracer, ok := err.(Stacktracer); ok {\n\t\t\tstacktrace = tracer.GetStacktrace()\n\t\t\tstackErr = nil\n\t\t} else if tracer, ok := err.(pkgErrorStackTracer); ok {\n\t\t\tstacktrace = nil\n\t\t\tstackErr = tracer.StackTrace()\n\t\t}\n\t\tif cause, ok := err.(causer); ok {\n\t\t\terr = cause.Cause()\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\tif stackErr != nil {\n\t\tstacktrace = hook.convertStackTrace(stackErr)\n\t}\n\treturn stacktrace\n}\n\n\/\/ convertStackTrace converts an errors.StackTrace into a natively consumable\n\/\/ *raven.Stacktrace\nfunc (hook *SentryHook) convertStackTrace(st errors.StackTrace) *raven.Stacktrace {\n\tstConfig := &hook.StacktraceConfiguration\n\tstFrames := []errors.Frame(st)\n\tframes := make([]*raven.StacktraceFrame, 0, len(stFrames))\n\tfor _, stFrame := range stFrames {\n\t\tframe := raven.NewStacktraceFrame(stFrame.PC, stFrame.Func.Name(), stFrame.File, stFrame.Line,\n\t\t\tstConfig.Context, stConfig.InAppPrefixes)\n\t\tif frame != nil {\n\t\t\tframes = append(frames, frame)\n\t\t}\n\t}\n\n\t\/\/ Sentry wants the frames with the oldest first, so reverse them\n\tfor i, j := 0, len(frames)-1; i < j; i, j = i+1, j-1 {\n\t\tframes[i], frames[j] = frames[j], frames[i]\n\t}\n\treturn &raven.Stacktrace{Frames: frames}\n}\n\n\/\/ Levels returns the available logging levels.\nfunc (hook *SentryHook) Levels() []logrus.Level {\n\treturn hook.levels\n}\n\n\/\/ AddIgnore adds field name to ignore.\nfunc (hook *SentryHook) AddIgnore(name string) {\n\thook.ignoreFields[name] = struct{}{}\n}\n\n\/\/ AddExtraFilter adds a custom filter function.\nfunc (hook *SentryHook) AddExtraFilter(name string, fn func(interface{}) interface{}) {\n\thook.extraFilters[name] = fn\n}\n\nfunc (hook *SentryHook) formatExtraData(df *dataField) (result map[string]interface{}) {\n\t\/\/ create a map for passing to Sentry's extra data\n\tresult = make(map[string]interface{}, df.len())\n\tfor k, v := range df.data {\n\t\tif df.isOmit(k) {\n\t\t\tcontinue \/\/ skip already used special fields\n\t\t}\n\t\tif _, ok := hook.ignoreFields[k]; ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tif fn, ok := hook.extraFilters[k]; ok {\n\t\t\tv = fn(v) \/\/ apply custom filter\n\t\t} else {\n\t\t\tv = formatData(v) \/\/ use default formatter\n\t\t}\n\t\tresult[k] = v\n\t}\n\treturn result\n}\n\n\/\/ formatData returns value as a suitable format.\nfunc formatData(value interface{}) (formatted interface{}) {\n\tswitch value := value.(type) {\n\tcase json.Marshaler:\n\t\treturn value\n\tcase error:\n\t\treturn value.Error()\n\tcase fmt.Stringer:\n\t\treturn value.String()\n\tdefault:\n\t\treturn value\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/fhs\/gompd\/mpd\"\n\t\"net\/http\"\n\t\"time\"\n)\n\ntype m map[string]interface{}\n\nfunc writeJSONAttrList(w http.ResponseWriter, d []mpd.Attrs, l time.Time, err error) {\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.Header().Add(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tv := m{\"errors\": err, \"data\": d}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc writeJSONAttr(w http.ResponseWriter, d mpd.Attrs, l time.Time, err error) {\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tv := m{\"errors\": err, \"data\": d}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc writeJSONStatus(w http.ResponseWriter, d PlayerStatus, l time.Time, err error) {\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tv := m{\"errors\": err, \"data\": d}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc writeJSON(w http.ResponseWriter, err error) {\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tv := m{\"errors\": err}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc notModified(w http.ResponseWriter, l time.Time) {\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.WriteHeader(304)\n\treturn\n}\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Hello, World\")\n}\n\ntype apiHandler struct {\n\tplayer Music\n}\n\ntype sortAction struct {\n\tAction string   `json:\"action\"`\n\tKeys   []string `json:\"keys\"`\n\tURI    string   `json:\"uri\"`\n}\n\nfunc (h *apiHandler) playlist(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\td, l := h.player.Playlist()\n\t\tif modified(r, l) {\n\t\t\twriteJSONAttrList(w, d, l, nil)\n\t\t} else {\n\t\t\tnotModified(w, l)\n\t\t}\n\tcase \"POST\":\n\t\tdecoder := json.NewDecoder(r.Body)\n\t\tvar s sortAction\n\t\terr := decoder.Decode(&s)\n\t\tif err == nil {\n\t\t\th.player.SortPlaylist(s.Keys, s.URI)\n\t\t}\n\t\twriteJSON(w, err)\n\t}\n}\n\nfunc (h *apiHandler) library(w http.ResponseWriter, r *http.Request) {\n\td, l := h.player.Library()\n\tif modified(r, l) {\n\t\twriteJSONAttrList(w, d, l, nil)\n\t} else {\n\t\tnotModified(w, l)\n\t}\n}\n\nfunc (h *apiHandler) current(w http.ResponseWriter, r *http.Request) {\n\td, l := h.player.Current()\n\tif modified(r, l) {\n\t\twriteJSONAttr(w, d, l, nil)\n\t} else {\n\t\tnotModified(w, l)\n\t}\n}\n\nfunc (h *apiHandler) control(w http.ResponseWriter, r *http.Request) {\n\tmethod := r.FormValue(\"action\")\n\tif method == \"prev\" {\n\t\twriteJSON(w, h.player.Prev())\n\t} else if method == \"play\" {\n\t\twriteJSON(w, h.player.Play())\n\t} else if method == \"pause\" {\n\t\twriteJSON(w, h.player.Pause())\n\t} else if method == \"next\" {\n\t\twriteJSON(w, h.player.Next())\n\t} else {\n\t\td, l := h.player.Status()\n\t\tif modified(r, l) {\n\t\t\twriteJSONStatus(w, d, l, nil)\n\t\t} else {\n\t\t\tnotModified(w, l)\n\t\t}\n\t}\n}\n\nfunc modified(r *http.Request, l time.Time) bool {\n\treturn r.Header.Get(\"If-Modified-Since\") != l.Format(http.TimeFormat)\n}\n\n\/\/ App serves http request.\nfunc App(p Music, config ServerConfig) {\n\tvar api = new(apiHandler)\n\tapi.player = p\n\thttp.HandleFunc(\"\/api\/library\", api.library)\n\thttp.HandleFunc(\"\/api\/songs\", api.playlist)\n\thttp.HandleFunc(\"\/api\/songs\/current\", api.current)\n\thttp.HandleFunc(\"\/api\/control\", api.control)\n\thttp.HandleFunc(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"app.html\")\n\t})\n\thttp.HandleFunc(\"\/app.css\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"app.css\")\n\t})\n\thttp.HandleFunc(\"\/app.js\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"app.js\")\n\t})\n\thttp.HandleFunc(\"\/jquery-3.1.1.js\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"jquery-3.1.1.js\")\n\t})\n\thttp.ListenAndServe(fmt.Sprintf(\":%s\", config.Port), nil)\n}\n\n\/\/ Music Represents music player.\ntype Music interface {\n\tPlay() error\n\tPause() error\n\tNext() error\n\tPrev() error\n\tPlaylist() ([]mpd.Attrs, time.Time)\n\tLibrary() ([]mpd.Attrs, time.Time)\n\tComments() (mpd.Attrs, time.Time)\n\tCurrent() (mpd.Attrs, time.Time)\n\tStatus() (PlayerStatus, time.Time)\n\tSortPlaylist([]string, string) error\n}\n<commit_msg>remove helloworld<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/fhs\/gompd\/mpd\"\n\t\"net\/http\"\n\t\"time\"\n)\n\ntype m map[string]interface{}\n\nfunc writeJSONAttrList(w http.ResponseWriter, d []mpd.Attrs, l time.Time, err error) {\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.Header().Add(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tv := m{\"errors\": err, \"data\": d}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc writeJSONAttr(w http.ResponseWriter, d mpd.Attrs, l time.Time, err error) {\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tv := m{\"errors\": err, \"data\": d}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc writeJSONStatus(w http.ResponseWriter, d PlayerStatus, l time.Time, err error) {\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tv := m{\"errors\": err, \"data\": d}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc writeJSON(w http.ResponseWriter, err error) {\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tv := m{\"errors\": err}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc notModified(w http.ResponseWriter, l time.Time) {\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.WriteHeader(304)\n\treturn\n}\n\ntype apiHandler struct {\n\tplayer Music\n}\n\ntype sortAction struct {\n\tAction string   `json:\"action\"`\n\tKeys   []string `json:\"keys\"`\n\tURI    string   `json:\"uri\"`\n}\n\nfunc (h *apiHandler) playlist(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\td, l := h.player.Playlist()\n\t\tif modified(r, l) {\n\t\t\twriteJSONAttrList(w, d, l, nil)\n\t\t} else {\n\t\t\tnotModified(w, l)\n\t\t}\n\tcase \"POST\":\n\t\tdecoder := json.NewDecoder(r.Body)\n\t\tvar s sortAction\n\t\terr := decoder.Decode(&s)\n\t\tif err == nil {\n\t\t\th.player.SortPlaylist(s.Keys, s.URI)\n\t\t}\n\t\twriteJSON(w, err)\n\t}\n}\n\nfunc (h *apiHandler) library(w http.ResponseWriter, r *http.Request) {\n\td, l := h.player.Library()\n\tif modified(r, l) {\n\t\twriteJSONAttrList(w, d, l, nil)\n\t} else {\n\t\tnotModified(w, l)\n\t}\n}\n\nfunc (h *apiHandler) current(w http.ResponseWriter, r *http.Request) {\n\td, l := h.player.Current()\n\tif modified(r, l) {\n\t\twriteJSONAttr(w, d, l, nil)\n\t} else {\n\t\tnotModified(w, l)\n\t}\n}\n\nfunc (h *apiHandler) control(w http.ResponseWriter, r *http.Request) {\n\tmethod := r.FormValue(\"action\")\n\tif method == \"prev\" {\n\t\twriteJSON(w, h.player.Prev())\n\t} else if method == \"play\" {\n\t\twriteJSON(w, h.player.Play())\n\t} else if method == \"pause\" {\n\t\twriteJSON(w, h.player.Pause())\n\t} else if method == \"next\" {\n\t\twriteJSON(w, h.player.Next())\n\t} else {\n\t\td, l := h.player.Status()\n\t\tif modified(r, l) {\n\t\t\twriteJSONStatus(w, d, l, nil)\n\t\t} else {\n\t\t\tnotModified(w, l)\n\t\t}\n\t}\n}\n\nfunc modified(r *http.Request, l time.Time) bool {\n\treturn r.Header.Get(\"If-Modified-Since\") != l.Format(http.TimeFormat)\n}\n\n\/\/ App serves http request.\nfunc App(p Music, config ServerConfig) {\n\tvar api = new(apiHandler)\n\tapi.player = p\n\thttp.HandleFunc(\"\/api\/library\", api.library)\n\thttp.HandleFunc(\"\/api\/songs\", api.playlist)\n\thttp.HandleFunc(\"\/api\/songs\/current\", api.current)\n\thttp.HandleFunc(\"\/api\/control\", api.control)\n\thttp.HandleFunc(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"app.html\")\n\t})\n\thttp.HandleFunc(\"\/app.css\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"app.css\")\n\t})\n\thttp.HandleFunc(\"\/app.js\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"app.js\")\n\t})\n\thttp.HandleFunc(\"\/jquery-3.1.1.js\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"jquery-3.1.1.js\")\n\t})\n\thttp.ListenAndServe(fmt.Sprintf(\":%s\", config.Port), nil)\n}\n\n\/\/ Music Represents music player.\ntype Music interface {\n\tPlay() error\n\tPause() error\n\tNext() error\n\tPrev() error\n\tPlaylist() ([]mpd.Attrs, time.Time)\n\tLibrary() ([]mpd.Attrs, time.Time)\n\tComments() (mpd.Attrs, time.Time)\n\tCurrent() (mpd.Attrs, time.Time)\n\tStatus() (PlayerStatus, time.Time)\n\tSortPlaylist([]string, string) error\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/gophergala\/ImgurGo\/imageprocessor\"\n\t\"github.com\/gophergala\/ImgurGo\/uploadedfile\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n)\n\ntype Server struct {\n\tConfig     *Configuration\n\tHTTPClient *http.Client\n}\n\nfunc CreateServer(c *Configuration) *Server {\n\thttpclient := &http.Client{}\n\treturn &Server{c, httpclient}\n}\n\nfunc (s *Server) _uploadFile(uploadFile io.ReadCloser, w http.ResponseWriter) {\n\tdefer uploadFile.Close()\n\n\ttmpFile, err := ioutil.TempFile(os.TempDir(), \"image\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tErrorResponse(w, \"Unable to write to \/tmp\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tdefer tmpFile.Close()\n\n\t_, err = io.Copy(tmpFile, uploadFile)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tErrorResponse(w, \"Unable to copy image to disk!\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tupload := uploadedfile.NewUploadedFile(\"testfile.jpg\", os.TempDir()+tmpFile.Name(), \"image\/jpeg\")\n\tprocessor, err := imageprocessor.Factory(s.Config.MaxFileSize, upload)\n\tif err != nil {\n\t\tErrorResponse(w, \"Unable to process image!\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\terr = processor.Run(upload)\n\tif err != nil {\n\t\tErrorResponse(w, \"Unable to process image!\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tresp := make(map[string]interface{})\n\n\t\/\/ TODO: Build JSON respons\n\n\tResponse(w, resp)\n}\n\nfunc (s *Server) initServer() {\n\tfileHandler := func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\n\t\tuploadFile, _, err := r.FormFile(\"image\")\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tErrorResponse(w, \"Error processing file!\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\ts._uploadFile(uploadFile, w)\n\t}\n\n\turlHandler := func(w http.ResponseWriter, r *http.Request) {\n\t\tuploadFile, err := s.download(r.FormValue(\"image\"))\n\n\t\tif err != nil {\n\t\t\tErrorResponse(w, \"Error dowloading URL!\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\ts._uploadFile(uploadFile, w)\n\t}\n\n\thttp.HandleFunc(\"\/file\", fileHandler)\n\thttp.HandleFunc(\"\/url\", urlHandler)\n\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc (s *Server) download(url string) (io.ReadCloser, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"User-Agent\", s.Config.UserAgent)\n\n\tresp, err := s.HTTPClient.Do(req)\n\n\tif err != nil {\n\t\t\/\/ \"HTTP protocol error\" - maybe the server sent an invalid response or timed out\n\t\treturn nil, err\n\t}\n\n\tif 200 != resp.StatusCode {\n\t\treturn nil, errors.New(\"Non-200 status code received\")\n\t}\n\n\tcontentLength := resp.ContentLength\n\n\tif contentLength == 0 {\n\t\treturn nil, errors.New(\"Empty file received\")\n\t}\n\n\treturn resp.Body, nil\n}\n<commit_msg>Fix double-adding os tmp directorY<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/gophergala\/ImgurGo\/imageprocessor\"\n\t\"github.com\/gophergala\/ImgurGo\/uploadedfile\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n)\n\ntype Server struct {\n\tConfig     *Configuration\n\tHTTPClient *http.Client\n}\n\nfunc CreateServer(c *Configuration) *Server {\n\thttpclient := &http.Client{}\n\treturn &Server{c, httpclient}\n}\n\nfunc (s *Server) _uploadFile(uploadFile io.ReadCloser, w http.ResponseWriter) {\n\tdefer uploadFile.Close()\n\n\ttmpFile, err := ioutil.TempFile(os.TempDir(), \"image\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tErrorResponse(w, \"Unable to write to \/tmp\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tdefer tmpFile.Close()\n\n\t_, err = io.Copy(tmpFile, uploadFile)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tErrorResponse(w, \"Unable to copy image to disk!\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tupload := uploadedfile.NewUploadedFile(\"testfile.jpg\", tmpFile.Name(), \"image\/jpeg\")\n\tprocessor, err := imageprocessor.Factory(s.Config.MaxFileSize, upload)\n\tif err != nil {\n\t\tErrorResponse(w, \"Unable to process image!\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\terr = processor.Run(upload)\n\tif err != nil {\n\t\tErrorResponse(w, \"Unable to process image!\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tresp := make(map[string]interface{})\n\n\t\/\/ TODO: Build JSON respons\n\n\tResponse(w, resp)\n}\n\nfunc (s *Server) initServer() {\n\tfileHandler := func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\n\t\tuploadFile, _, err := r.FormFile(\"image\")\n\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tErrorResponse(w, \"Error processing file!\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\ts._uploadFile(uploadFile, w)\n\t}\n\n\turlHandler := func(w http.ResponseWriter, r *http.Request) {\n\t\tuploadFile, err := s.download(r.FormValue(\"image\"))\n\n\t\tif err != nil {\n\t\t\tErrorResponse(w, \"Error dowloading URL!\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\ts._uploadFile(uploadFile, w)\n\t}\n\n\thttp.HandleFunc(\"\/file\", fileHandler)\n\thttp.HandleFunc(\"\/url\", urlHandler)\n\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc (s *Server) download(url string) (io.ReadCloser, error) {\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"User-Agent\", s.Config.UserAgent)\n\n\tresp, err := s.HTTPClient.Do(req)\n\n\tif err != nil {\n\t\t\/\/ \"HTTP protocol error\" - maybe the server sent an invalid response or timed out\n\t\treturn nil, err\n\t}\n\n\tif 200 != resp.StatusCode {\n\t\treturn nil, errors.New(\"Non-200 status code received\")\n\t}\n\n\tcontentLength := resp.ContentLength\n\n\tif contentLength == 0 {\n\t\treturn nil, errors.New(\"Empty file received\")\n\t}\n\n\treturn resp.Body, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"database\/sql\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com\/cloudfoundry-incubator\/galera-healthcheck\/healthcheck\"\n\t. \"github.com\/cloudfoundry-incubator\/galera-healthcheck\/logger\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\nvar host = flag.String(\n    \"host\",\n    \"0.0.0.0\",\n    \"Specifies the host of the healthcheck server\",\n)\n\nvar port = flag.Int(\n\t\"port\",\n\t8080,\n\t\"Specifies the port of the healthcheck server\",\n)\n\nvar dbHost = flag.String(\n    \"dbHost\",\n    \"127.0.0.1\",\n    \"Specifies the MySQL host to connect to\",\n)\n\nvar dbPort = flag.Int(\n    \"dbPort\",\n    3306,\n    \"Specifies the MySQL port to connect to\",\n)\n\nvar dbUser = flag.String(\n\t\"dbUser\",\n\t\"root\",\n\t\"Specifies the MySQL user to connect with\",\n)\n\nvar dbPassword = flag.String(\n\t\"dbPassword\",\n\t\"\",\n\t\"Specifies the MySQL password to connect with\",\n)\n\nvar availableWhenDonor = flag.Bool(\n\t\"availWhenDonor\",\n\ttrue,\n\t\"Specifies if the healthcheck allows availability when in donor state\",\n)\n\nvar availableWhenReadOnly = flag.Bool(\n\t\"availWhenReadOnly\",\n\tfalse,\n\t\"Specifies if the healthcheck allows availability when in read only mode\",\n)\n\nvar pidfile = flag.String(\n\t\"pidfile\",\n\t\"\",\n\t\"Location for the pidfile\",\n)\n\nvar connectionCutterPath = flag.String(\n\t\"connectionCutterPath\",\n\t\"\",\n\t\"Location for the script which cuts mysql connections\",\n)\n\nvar healthchecker *healthcheck.Healthchecker\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tresult, msg := healthchecker.Check()\n\tif result {\n\t\tw.WriteHeader(http.StatusOK)\n\t} else {\n\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t}\n\n\tfmt.Fprintf(w, \"Galera Cluster Node status: %s\", msg)\n\tLogWithTimestamp(msg)\n}\n\nfunc main() {\n\tflag.Parse()\n\n\terr := ioutil.WriteFile(*pidfile, []byte(strconv.Itoa(os.Getpid())), 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdb, _ := sql.Open(\"mysql\", fmt.Sprintf(\"%s:%s@tcp(%s:%d)\/\", *dbUser, *dbPassword, *dbHost, *dbPort))\n\tconfig := healthcheck.HealthcheckerConfig{\n\t\t*availableWhenDonor,\n\t\t*availableWhenReadOnly,\n\t}\n\n\thealthchecker = healthcheck.New(db, config)\n\n\thttp.HandleFunc(\"\/\", handler)\n\thttp.ListenAndServe(fmt.Sprintf(\"%s:%d\", *host, *port), nil)\n}\n<commit_msg>Removed unused cli flag<commit_after>package main\n\nimport (\n\t\"database\/sql\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com\/cloudfoundry-incubator\/galera-healthcheck\/healthcheck\"\n\t. \"github.com\/cloudfoundry-incubator\/galera-healthcheck\/logger\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\nvar host = flag.String(\n    \"host\",\n    \"0.0.0.0\",\n    \"Specifies the host of the healthcheck server\",\n)\n\nvar port = flag.Int(\n\t\"port\",\n\t8080,\n\t\"Specifies the port of the healthcheck server\",\n)\n\nvar dbHost = flag.String(\n    \"dbHost\",\n    \"127.0.0.1\",\n    \"Specifies the MySQL host to connect to\",\n)\n\nvar dbPort = flag.Int(\n    \"dbPort\",\n    3306,\n    \"Specifies the MySQL port to connect to\",\n)\n\nvar dbUser = flag.String(\n\t\"dbUser\",\n\t\"root\",\n\t\"Specifies the MySQL user to connect with\",\n)\n\nvar dbPassword = flag.String(\n\t\"dbPassword\",\n\t\"\",\n\t\"Specifies the MySQL password to connect with\",\n)\n\nvar availableWhenDonor = flag.Bool(\n\t\"availWhenDonor\",\n\ttrue,\n\t\"Specifies if the healthcheck allows availability when in donor state\",\n)\n\nvar availableWhenReadOnly = flag.Bool(\n\t\"availWhenReadOnly\",\n\tfalse,\n\t\"Specifies if the healthcheck allows availability when in read only mode\",\n)\n\nvar pidfile = flag.String(\n\t\"pidfile\",\n\t\"\",\n\t\"Location for the pidfile\",\n)\n\nvar healthchecker *healthcheck.Healthchecker\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tresult, msg := healthchecker.Check()\n\tif result {\n\t\tw.WriteHeader(http.StatusOK)\n\t} else {\n\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t}\n\n\tfmt.Fprintf(w, \"Galera Cluster Node status: %s\", msg)\n\tLogWithTimestamp(msg)\n}\n\nfunc main() {\n\tflag.Parse()\n\n\terr := ioutil.WriteFile(*pidfile, []byte(strconv.Itoa(os.Getpid())), 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdb, _ := sql.Open(\"mysql\", fmt.Sprintf(\"%s:%s@tcp(%s:%d)\/\", *dbUser, *dbPassword, *dbHost, *dbPort))\n\tconfig := healthcheck.HealthcheckerConfig{\n\t\t*availableWhenDonor,\n\t\t*availableWhenReadOnly,\n\t}\n\n\thealthchecker = healthcheck.New(db, config)\n\n\thttp.HandleFunc(\"\/\", handler)\n\thttp.ListenAndServe(fmt.Sprintf(\"%s:%d\", *host, *port), nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package benchserve provides a simple line-oriented benchmark server.\n\/\/\n\/\/ It is designed to allow an external program to drive the benchmarks\n\/\/ found in a compiled test binary.\n\/\/\n\/\/ The protocol is still under development and may change.\n\/\/\n\/\/ To enable benchserve with a package, add this somewhere to your\n\/\/ package's tests:\n\/\/\n\/\/ \timport \"github.com\/josharian\/benchserve\"\n\/\/\n\/\/ \tfunc TestMain(m *testing.M) {\n\/\/ \t\tbenchserve.Main(m)\n\/\/ \t}\n\/\/\n\/\/ Your existing tests and benchmarks should operate unchanged.\n\/\/ To use benchserve, compile the tests with 'go test -c',\n\/\/ and then execute with the -test.benchserve flag,\n\/\/ e.g. '.\/foo.test -test.benchserve'.\n\/\/ This will bypass all tests and benchmarks, and ignore all other\n\/\/ flags, including the usual benchmarking and profiling flags,\n\/\/ and instead start a benchmark server.\n\/\/ The benchmark server accepts commands in stdin, prints output\n\/\/ on stdout, and prints errors on stderr.\n\/\/\n\/\/ It is designed to be invoked and driven by another program,\n\/\/ but you can take a quick tour by hand.\n\/\/ Type 'help' to see a list of commands.\n\/\/ Type 'list' to see a list of available benchmarks, one per line,\n\/\/ with a trailing blank line to indicate that the list is complete.\n\/\/ Type 'run BenchmarkName 50' to run BenchmarkName for 50 iterations.\n\/\/ Type 'run BenchmarkName-3 50' to run BenchmarkName for 50 iterations with GOMAXPROCS=3.\n\/\/ Type 'set benchmem true' to turn on memory benchmarking.\n\/\/\n\/\/ The decision to use a simple, line-oriented server using pipes is intentional.\n\/\/ This enables benchserve to rely only on the same set of packages that\n\/\/ the testing package does, which means that it is usable with any package\n\/\/ without introducing circular imports. Using (say) net\/http or net\/rpc or\n\/\/ even just net would cause benchserve to be unsuitable for use with\n\/\/ many packages in the standard library.\n\/\/\n\/\/ Benchserve relies on unexported details of the testing package, which may\n\/\/ change at any time. A request to officially support this functionality\n\/\/ is https:\/\/golang.org\/issue\/10930.\npackage benchserve\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\t\"unsafe\"\n)\n\nfunc Main(m *testing.M) {\n\tbenchserve := flag.Bool(\"test.benchserve\", false, \"run an interactive benchmark server\")\n\tflag.Parse()\n\tif !*benchserve {\n\t\tos.Exit(m.Run())\n\t}\n\n\ts := server{benchmarks: extractBenchmarks(m)}\n\ts.serve()\n}\n\nfunc extractBenchmarks(m *testing.M) []testing.InternalBenchmark {\n\tv := reflect.ValueOf(m).Elem().FieldByName(\"benchmarks\")\n\treturn *(*[]testing.InternalBenchmark)(unsafe.Pointer(v.UnsafeAddr())) \/\/ :(((\n}\n\ntype server struct {\n\tbenchmarks []testing.InternalBenchmark\n\tbenchmem   bool\n}\n\nfunc (s *server) serve() {\n\tcmds := map[string]func([]string){\n\t\t\"help\": s.cmdHelp,\n\t\t\"quit\": s.cmdQuit,\n\t\t\"exit\": s.cmdQuit,\n\t\t\"list\": s.cmdList,\n\t\t\"run\":  s.cmdRun,\n\t\t\"set\":  s.cmdSet,\n\t}\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfor scanner.Scan() {\n\t\tfields := strings.Fields(scanner.Text())\n\t\tif len(fields) == 0 {\n\t\t\ts.cmdHelp(nil)\n\t\t\tcontinue\n\t\t}\n\t\tcmd := cmds[fields[0]]\n\t\tif cmd == nil {\n\t\t\ts.cmdHelp(nil)\n\t\t\tcontinue\n\t\t}\n\t\tcmd(fields[1:])\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(2)\n\t}\n}\n\nfunc (s *server) cmdHelp([]string) {\n\tfmt.Fprintln(os.Stderr, \"commands: help, list, run, set, quit, exit\")\n}\n\nfunc (s *server) cmdQuit([]string) {\n\tos.Exit(0)\n}\n\nfunc (s *server) cmdList([]string) {\n\tfor _, b := range s.benchmarks {\n\t\tfmt.Println(b.Name)\n\t}\n\tfmt.Println()\n}\n\nfunc (s *server) cmdSet(args []string) {\n\t\/\/ TODO: What else is worth setting?\n\tif len(args) < 2 || args[0] != \"benchmem\" {\n\t\tfmt.Fprintln(os.Stderr, \"set benchmem <bool>\")\n\t\treturn\n\t}\n\tb, err := strconv.ParseBool(args[1])\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"bad benchmem value:\", err)\n\t\treturn\n\t}\n\ts.benchmem = b\n}\n\nfunc (s *server) cmdRun(args []string) {\n\tif len(args) < 2 {\n\t\tfmt.Fprintln(os.Stderr, \"run <name>[-cpu] <iterations>\")\n\t\treturn\n\t}\n\n\tname := args[0]\n\tprocs := 1\n\tif i := strings.IndexByte(name, '-'); i != -1 {\n\t\tvar err error\n\t\tprocs, err = strconv.Atoi(name[i+1:])\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, \"bad cpu value:\", err)\n\t\t\treturn\n\t\t}\n\t\tname = name[:i]\n\t}\n\n\tvar bench testing.InternalBenchmark\n\tfor _, x := range s.benchmarks {\n\t\tif x.Name == name {\n\t\t\tbench = x\n\t\t\t\/\/ It is possible to define a benchmark with the same name\n\t\t\t\/\/ twice in a single test binary, by defining it once\n\t\t\t\/\/ in a regular test package and once in an external test package.\n\t\t\t\/\/ If you do that, you probably deserve what happens to you now,\n\t\t\t\/\/ namely that we run one of the two, but no guarantees which.\n\t\t\t\/\/ If someday we combine multiple packages into a single\n\t\t\t\/\/ test binary, then we'll probably need to invoke benchmarks\n\t\t\t\/\/ by index rather than by name.\n\t\t\tbreak\n\t\t}\n\t}\n\tif bench.Name == \"\" {\n\t\tfmt.Fprintln(os.Stderr, \"benchmark not found:\", name)\n\t\treturn\n\t}\n\n\titers, err := strconv.Atoi(args[1])\n\tif err != nil || iters <= 0 {\n\t\tfmt.Fprintf(os.Stderr, \"iterations must be positive, got %v\\n\", iters)\n\t\treturn\n\t}\n\n\tbenchName := benchmarkName(bench.Name, procs)\n\tfmt.Print(benchName, \"\\t\")\n\n\truntime.GOMAXPROCS(procs)\n\tr := runBenchmark(bench, iters)\n\n\tif r.Failed {\n\t\tfmt.Fprintln(os.Stderr, \"--- FAIL:\", benchName)\n\t\treturn\n\t}\n\tfmt.Print(r.BenchmarkResult)\n\tif s.benchmem || r.ShowAllocResult {\n\t\tfmt.Print(\"\\t\", r.MemString())\n\t}\n\tfmt.Println()\n\tif p := runtime.GOMAXPROCS(-1); p != procs {\n\t\tfmt.Fprintf(os.Stderr, \"testing: %s left GOMAXPROCS set to %d\\n\", benchName, p)\n\t}\n}\n\n\/\/ benchmarkName returns full name of benchmark including procs suffix.\nfunc benchmarkName(name string, n int) string {\n\tif n != 1 {\n\t\treturn fmt.Sprintf(\"%s-%d\", name, n)\n\t}\n\treturn name\n}\n\ntype Result struct {\n\ttesting.BenchmarkResult\n\tFailed          bool\n\tShowAllocResult bool\n}\n\n\/\/ runBenchmark runs b for the specified number of iterations.\nfunc runBenchmark(b testing.InternalBenchmark, n int) Result {\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\ttb := testing.B{N: n}\n\ttb.SetParallelism(1)\n\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\t\/\/ Try to get a comparable environment for each run\n\t\t\/\/ by clearing garbage from previous runs.\n\t\truntime.GC()\n\t\ttb.ResetTimer()\n\t\ttb.StartTimer()\n\t\tb.F(&tb)\n\t\ttb.StopTimer()\n\t}()\n\twg.Wait()\n\n\tv := reflect.ValueOf(tb)\n\tvar r Result\n\tr.N = n\n\tr.T = time.Duration(v.FieldByName(\"duration\").Int())\n\tr.Bytes = v.FieldByName(\"bytes\").Int()\n\tr.MemAllocs = v.FieldByName(\"netAllocs\").Uint()\n\tr.MemBytes = v.FieldByName(\"netBytes\").Uint()\n\tr.Failed = v.FieldByName(\"failed\").Bool()\n\tr.ShowAllocResult = v.FieldByName(\"showAllocResult\").Bool()\n\treturn r\n}\n<commit_msg>Replace unreadable docs with sample session<commit_after>\/\/ Package benchserve provides a simple line-oriented benchmark server.\n\/\/\n\/\/ It is designed to allow an external program to drive the benchmarks\n\/\/ found in a compiled test binary.\n\/\/\n\/\/ The protocol is still under development and may change.\n\/\/\n\/\/ To enable benchserve with a package, add this somewhere to your\n\/\/ package's tests:\n\/\/\n\/\/ \timport \"github.com\/josharian\/benchserve\"\n\/\/\n\/\/ \tfunc TestMain(m *testing.M) {\n\/\/ \t\tbenchserve.Main(m)\n\/\/ \t}\n\/\/\n\/\/ Your existing tests and benchmarks should operate unchanged.\n\/\/ To use benchserve, compile the tests with 'go test -c',\n\/\/ and then execute with the -test.benchserve flag,\n\/\/ e.g. '.\/foo.test -test.benchserve'.\n\/\/ This will bypass all tests and benchmarks, and ignore all other\n\/\/ flags, including the usual benchmarking and profiling flags,\n\/\/ and instead start a benchmark server.\n\/\/ The benchmark server accepts commands in stdin, prints output\n\/\/ on stdout, and prints errors on stderr.\n\/\/\n\/\/ It is designed to be invoked and driven by another program,\n\/\/ but you can take a quick tour by hand. Here is a sample session:\n\/\/\n\/\/ \t$ cd $GOROOT\/src\/encoding\/json\n\/\/ \t$ go test -c\n\/\/ \t$ .\/json.test -test.benchserve\n\/\/ \thelp\n\/\/ \tcommands: help, list, run, set, quit, exit\n\/\/ \tlist\n\/\/ \tBenchmarkCodeEncoder\n\/\/ \tBenchmarkCodeMarshal\n\/\/ \tBenchmarkCodeDecoder\n\/\/ \tBenchmarkCodeUnmarshal\n\/\/ \tBenchmarkCodeUnmarshalReuse\n\/\/ \tBenchmarkUnmarshalString\n\/\/ \tBenchmarkUnmarshalFloat64\n\/\/ \tBenchmarkUnmarshalInt64\n\/\/ \tBenchmarkSkipValue\n\/\/ \tBenchmarkEncoderEncode\n\/\/\n\/\/ \trun BenchmarkCodeEncoder 100\n\/\/ \tBenchmarkCodeEncoder\t     100\t  17719109 ns\/op\t 109.51 MB\/s\n\/\/ \tset benchmem true\n\/\/ \trun BenchmarkCodeEncoder 100\n\/\/ \tBenchmarkCodeEncoder\t     100\t  17974625 ns\/op\t 107.96 MB\/s\t   45953 B\/op\t       1 allocs\/op\n\/\/ \trun BenchmarkCodeEncoder-4 100\n\/\/ \tBenchmarkCodeEncoder-4\t     100\t  18031952 ns\/op\t 107.61 MB\/s\t   45979 B\/op\t       1 allocs\/op\n\/\/ \texit\n\/\/ \t$\n\/\/\n\/\/ The decision to use a simple, line-oriented server using pipes is intentional.\n\/\/ This enables benchserve to rely only on the same set of packages that\n\/\/ the testing package does, which means that it is usable with any package\n\/\/ without introducing circular imports. Using (say) net\/http or net\/rpc or\n\/\/ even just net would cause benchserve to be unsuitable for use with\n\/\/ many packages in the standard library.\n\/\/\n\/\/ Benchserve relies on unexported details of the testing package, which may\n\/\/ change at any time. A request to officially support this functionality\n\/\/ is https:\/\/golang.org\/issue\/10930.\npackage benchserve\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\t\"unsafe\"\n)\n\nfunc Main(m *testing.M) {\n\tbenchserve := flag.Bool(\"test.benchserve\", false, \"run an interactive benchmark server\")\n\tflag.Parse()\n\tif !*benchserve {\n\t\tos.Exit(m.Run())\n\t}\n\n\ts := server{benchmarks: extractBenchmarks(m)}\n\ts.serve()\n}\n\nfunc extractBenchmarks(m *testing.M) []testing.InternalBenchmark {\n\tv := reflect.ValueOf(m).Elem().FieldByName(\"benchmarks\")\n\treturn *(*[]testing.InternalBenchmark)(unsafe.Pointer(v.UnsafeAddr())) \/\/ :(((\n}\n\ntype server struct {\n\tbenchmarks []testing.InternalBenchmark\n\tbenchmem   bool\n}\n\nfunc (s *server) serve() {\n\tcmds := map[string]func([]string){\n\t\t\"help\": s.cmdHelp,\n\t\t\"quit\": s.cmdQuit,\n\t\t\"exit\": s.cmdQuit,\n\t\t\"list\": s.cmdList,\n\t\t\"run\":  s.cmdRun,\n\t\t\"set\":  s.cmdSet,\n\t}\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfor scanner.Scan() {\n\t\tfields := strings.Fields(scanner.Text())\n\t\tif len(fields) == 0 {\n\t\t\ts.cmdHelp(nil)\n\t\t\tcontinue\n\t\t}\n\t\tcmd := cmds[fields[0]]\n\t\tif cmd == nil {\n\t\t\ts.cmdHelp(nil)\n\t\t\tcontinue\n\t\t}\n\t\tcmd(fields[1:])\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(2)\n\t}\n}\n\nfunc (s *server) cmdHelp([]string) {\n\tfmt.Fprintln(os.Stderr, \"commands: help, list, run, set, quit, exit\")\n}\n\nfunc (s *server) cmdQuit([]string) {\n\tos.Exit(0)\n}\n\nfunc (s *server) cmdList([]string) {\n\tfor _, b := range s.benchmarks {\n\t\tfmt.Println(b.Name)\n\t}\n\tfmt.Println()\n}\n\nfunc (s *server) cmdSet(args []string) {\n\t\/\/ TODO: What else is worth setting?\n\tif len(args) < 2 || args[0] != \"benchmem\" {\n\t\tfmt.Fprintln(os.Stderr, \"set benchmem <bool>\")\n\t\treturn\n\t}\n\tb, err := strconv.ParseBool(args[1])\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"bad benchmem value:\", err)\n\t\treturn\n\t}\n\ts.benchmem = b\n}\n\nfunc (s *server) cmdRun(args []string) {\n\tif len(args) < 2 {\n\t\tfmt.Fprintln(os.Stderr, \"run <name>[-cpu] <iterations>\")\n\t\treturn\n\t}\n\n\tname := args[0]\n\tprocs := 1\n\tif i := strings.IndexByte(name, '-'); i != -1 {\n\t\tvar err error\n\t\tprocs, err = strconv.Atoi(name[i+1:])\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, \"bad cpu value:\", err)\n\t\t\treturn\n\t\t}\n\t\tname = name[:i]\n\t}\n\n\tvar bench testing.InternalBenchmark\n\tfor _, x := range s.benchmarks {\n\t\tif x.Name == name {\n\t\t\tbench = x\n\t\t\t\/\/ It is possible to define a benchmark with the same name\n\t\t\t\/\/ twice in a single test binary, by defining it once\n\t\t\t\/\/ in a regular test package and once in an external test package.\n\t\t\t\/\/ If you do that, you probably deserve what happens to you now,\n\t\t\t\/\/ namely that we run one of the two, but no guarantees which.\n\t\t\t\/\/ If someday we combine multiple packages into a single\n\t\t\t\/\/ test binary, then we'll probably need to invoke benchmarks\n\t\t\t\/\/ by index rather than by name.\n\t\t\tbreak\n\t\t}\n\t}\n\tif bench.Name == \"\" {\n\t\tfmt.Fprintln(os.Stderr, \"benchmark not found:\", name)\n\t\treturn\n\t}\n\n\titers, err := strconv.Atoi(args[1])\n\tif err != nil || iters <= 0 {\n\t\tfmt.Fprintf(os.Stderr, \"iterations must be positive, got %v\\n\", iters)\n\t\treturn\n\t}\n\n\tbenchName := benchmarkName(bench.Name, procs)\n\tfmt.Print(benchName, \"\\t\")\n\n\truntime.GOMAXPROCS(procs)\n\tr := runBenchmark(bench, iters)\n\n\tif r.Failed {\n\t\tfmt.Fprintln(os.Stderr, \"--- FAIL:\", benchName)\n\t\treturn\n\t}\n\tfmt.Print(r.BenchmarkResult)\n\tif s.benchmem || r.ShowAllocResult {\n\t\tfmt.Print(\"\\t\", r.MemString())\n\t}\n\tfmt.Println()\n\tif p := runtime.GOMAXPROCS(-1); p != procs {\n\t\tfmt.Fprintf(os.Stderr, \"testing: %s left GOMAXPROCS set to %d\\n\", benchName, p)\n\t}\n}\n\n\/\/ benchmarkName returns full name of benchmark including procs suffix.\nfunc benchmarkName(name string, n int) string {\n\tif n != 1 {\n\t\treturn fmt.Sprintf(\"%s-%d\", name, n)\n\t}\n\treturn name\n}\n\ntype Result struct {\n\ttesting.BenchmarkResult\n\tFailed          bool\n\tShowAllocResult bool\n}\n\n\/\/ runBenchmark runs b for the specified number of iterations.\nfunc runBenchmark(b testing.InternalBenchmark, n int) Result {\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\ttb := testing.B{N: n}\n\ttb.SetParallelism(1)\n\n\tgo func() {\n\t\tdefer wg.Done()\n\n\t\t\/\/ Try to get a comparable environment for each run\n\t\t\/\/ by clearing garbage from previous runs.\n\t\truntime.GC()\n\t\ttb.ResetTimer()\n\t\ttb.StartTimer()\n\t\tb.F(&tb)\n\t\ttb.StopTimer()\n\t}()\n\twg.Wait()\n\n\tv := reflect.ValueOf(tb)\n\tvar r Result\n\tr.N = n\n\tr.T = time.Duration(v.FieldByName(\"duration\").Int())\n\tr.Bytes = v.FieldByName(\"bytes\").Int()\n\tr.MemAllocs = v.FieldByName(\"netAllocs\").Uint()\n\tr.MemBytes = v.FieldByName(\"netBytes\").Uint()\n\tr.Failed = v.FieldByName(\"failed\").Bool()\n\tr.ShowAllocResult = v.FieldByName(\"showAllocResult\").Bool()\n\treturn r\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* {{{ Copyright (c) Paul R. Tagliamonte <paultag@debian.org>, 2015\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE. }}} *\/\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"regexp\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/paultag\/sniff\/parser\"\n\n\tcorev1 \"k8s.io\/client-go\/1.4\/kubernetes\/typed\/core\/v1\"\n\ttypedv1beta1 \"k8s.io\/client-go\/1.4\/kubernetes\/typed\/extensions\/v1beta1\"\n\t\"k8s.io\/client-go\/1.4\/pkg\/api\"\n\t_ \"k8s.io\/client-go\/1.4\/pkg\/api\/install\"\n\tapiv1 \"k8s.io\/client-go\/1.4\/pkg\/api\/v1\"\n\t_ \"k8s.io\/client-go\/1.4\/pkg\/apis\/extensions\/install\"\n\textapiv1beta1 \"k8s.io\/client-go\/1.4\/pkg\/apis\/extensions\/v1beta1\"\n\t\"k8s.io\/client-go\/1.4\/pkg\/fields\"\n\t\"k8s.io\/client-go\/1.4\/pkg\/util\/intstr\"\n\t\"k8s.io\/client-go\/1.4\/pkg\/watch\"\n\t\"k8s.io\/client-go\/1.4\/tools\/cache\"\n\t\"k8s.io\/client-go\/1.4\/tools\/clientcmd\"\n)\n\nconst (\n\t\/\/ ingressClassKey picks a specific \"class\" for the Ingress. The controller\n\t\/\/ only processes Ingresses with this annotation either unset, or set\n\t\/\/ to either nginxIngressClass or the empty string.\n\tingressClassKey = \"kubernetes.io\/ingress.class\"\n)\n\ntype ServerAndRegexp struct {\n\tServer *Server\n\tRegexp *regexp.Regexp\n}\n\ntype Proxy struct {\n\tLock       sync.RWMutex\n\tServerList []ServerAndRegexp\n\tDefault    *Server\n}\n\nfunc (c *Proxy) Get(host string) *Server {\n\tc.Lock.RLock()\n\tdefer c.Lock.RUnlock()\n\n\tfor _, tuple := range c.ServerList {\n\t\tif tuple.Regexp.MatchString(host) {\n\t\t\treturn tuple.Server\n\t\t}\n\t}\n\treturn c.Default\n}\n\nfunc (p *Proxy) Update(c *Config) error {\n\tservers := []ServerAndRegexp{}\n\tfor i, server := range c.Servers {\n\t\tfor _, hostname := range server.Names {\n\t\t\tvar host_regexp *regexp.Regexp\n\t\t\tvar err error\n\t\t\tif server.Regexp {\n\t\t\t\thost_regexp, err = regexp.Compile(hostname)\n\t\t\t} else {\n\t\t\t\thost_regexp, err = regexp.Compile(\"^\" + regexp.QuoteMeta(hostname) + \"$\")\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"cannot update proxy due to invalid regex: %v\", err)\n\t\t\t}\n\t\t\ttuple := ServerAndRegexp{&c.Servers[i], host_regexp}\n\t\t\tservers = append(servers, tuple)\n\t\t}\n\t}\n\tvar def *Server\n\tfor i, server := range c.Servers {\n\t\tif server.Default {\n\t\t\tdef = &c.Servers[i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\tp.Lock.Lock()\n\tdefer p.Lock.Unlock()\n\tp.ServerList = servers\n\tp.Default = def\n\n\treturn nil\n}\n\nfunc (c *Config) Serve() error {\n\tglog.V(1).Infof(\"Listening on %s:%d\", c.Bind.Host, c.Bind.Port)\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\n\t\t\"%s:%d\", c.Bind.Host, c.Bind.Port,\n\t))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tproxy := Proxy{}\n\terr = proxy.Update(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.Kubernetes != nil {\n\t\trules := clientcmd.NewDefaultClientConfigLoadingRules()\n\t\tif c.Kubernetes.Kubeconfig != \"\" {\n\t\t\trules.ExplicitPath = c.Kubernetes.Kubeconfig\n\t\t}\n\t\tcmdcfg, err := rules.Load()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tccfg := clientcmd.NewDefaultClientConfig(*cmdcfg, &clientcmd.ConfigOverrides{})\n\t\trcfg, err := ccfg.ClientConfig()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\textclient := typedv1beta1.NewForConfigOrDie(rcfg)\n\t\tclient := corev1.NewForConfigOrDie(rcfg)\n\n\t\t\/\/ trigger to update the proxy\n\t\tupdateTrigger := make(chan struct{}, 1)\n\n\t\t\/\/ watch services\n\t\tservices := NotifyingStore{\n\t\t\tStore: cache.NewStore(cache.MetaNamespaceKeyFunc),\n\t\t\tNotifyFunc: func () {\n\t\t\t\tselect {\n\t\t\t\tcase updateTrigger <- struct{}{}:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t\tlw := cache.NewListWatchFromClient(client, \"services\", \"\", fields.Everything())\n\t\trefl := cache.NewReflector(lw, &apiv1.Service{}, &services, time.Minute)\n\t\trefl.Run()\n\n\t\t\/\/ wait until services are ready\n\t\tglog.V(1).Infof(\"Waiting for service store to be ready\")\n\t\tfor {\n\t\t\tif refl.LastSyncResourceVersion() != \"\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(time.Millisecond * 200)\n\t\t}\n\n\t\t\/\/ watch ingresses\n\t\tingresses := map[string]*extapiv1beta1.Ingress{}\n\t\tlock := sync.Mutex{}\n\t\tclass := c.Kubernetes.IngressClass\n\t\tif class == \"\" {\n\t\t\tclass = \"sniff\"\n\t\t}\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tw, err := extclient.Ingresses(\"\").Watch(api.ListOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\tglog.Errorf(\"Ingress watch error: %v\", err)\n\t\t\t\t\t\/\/ TODO: add backoff logic\n\t\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tevs := w.ResultChan()\n\n\t\t\tEventLoop:\n\t\t\t\tfor ev := range evs {\n\t\t\t\t\ti := ev.Object.(*extapiv1beta1.Ingress)\n\t\t\t\t\tif i != nil && i.Annotations[ingressClassKey] != class {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tswitch ev.Type {\n\t\t\t\t\tcase watch.Added, watch.Modified:\n\t\t\t\t\t\tglog.V(5).Infof(\"event %s for %s\/%s\", ev.Type, i.Namespace, i.Name)\n\t\t\t\t\t\tlock.Lock()\n\t\t\t\t\t\tingresses[i.Namespace+\"\/\"+i.Name] = i\n\t\t\t\t\t\tlock.Unlock()\n\t\t\t\t\tcase watch.Deleted:\n\t\t\t\t\t\tglog.V(5).Infof(\"event %s for %s\/%s\", ev.Type, i.Namespace, i.Name)\n\t\t\t\t\t\tlock.Lock()\n\t\t\t\t\t\tdelete(ingresses, i.Namespace+\"\/\"+i.Name)\n\t\t\t\t\t\tlock.Unlock()\n\t\t\t\t\tcase watch.Error:\n\t\t\t\t\t\tif i != nil {\n\t\t\t\t\t\t\tglog.V(5).Infof(\"event %s for %s\/%s\", ev.Type, i.Namespace, i.Name)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tw.Stop()\n\t\t\t\t\t\tbreak EventLoop\n\t\t\t\t\t}\n\t\t\t\t\tselect {\n\t\t\t\t\tcase updateTrigger <- struct{}{}:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ TODO: add backoff logic\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t}\n\t\t}()\n\n\t\tgo func() {\n\t\t\tfor range updateTrigger {\n\t\t\t\tlock.Lock()\n\n\t\t\t\tserverForBackend := func(ing *extapiv1beta1.Ingress, backend *extapiv1beta1.IngressBackend) (*Server, error) {\n\t\t\t\t\tobj, found, err := services.GetByKey(fmt.Sprintf(\"%s\/%s\", ing.Namespace, backend.ServiceName))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tif !found {\n\t\t\t\t\t\treturn nil, fmt.Errorf(\"service %s\/%s not found\", ing.Namespace, backend.ServiceName)\n\t\t\t\t\t}\n\t\t\t\t\tsvc := obj.(*apiv1.Service)\n\t\t\t\t\tvar port int\n\t\t\t\t\tif backend.ServicePort.Type == intstr.String {\n\t\t\t\t\t\tfor _, p := range svc.Spec.Ports {\n\t\t\t\t\t\t\tif p.Name == backend.ServicePort.StrVal {\n\t\t\t\t\t\t\t\tport = int(p.Port)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif port == 0 {\n\t\t\t\t\t\t\treturn nil, fmt.Errorf(\"port %q of service %s\/%s not found\", backend.ServicePort.StrVal, svc.Namespace, svc.Name)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tport = int(backend.ServicePort.IntVal)\n\t\t\t\t\t}\n\t\t\t\t\treturn &Server{\n\t\t\t\t\t\tHost: svc.Spec.ClusterIP,\n\t\t\t\t\t\t\/\/ TODO: support string values:\n\t\t\t\t\t\tPort: port,\n\t\t\t\t\t}, nil\n\t\t\t\t}\n\n\t\t\t\tfor _, i := range ingresses {\n\t\t\t\t\tc.Servers = []Server{}\n\t\t\t\t\tif i.Spec.Backend != nil {\n\t\t\t\t\t\ts, err := serverForBackend(i, i.Spec.Backend)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tglog.Errorf(\"Ingress %s\/%s error with default backend, skipping: %v\", i.Namespace, i.Name, err)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ts.Default = true\n\t\t\t\t\t\t\tglog.V(4).Infof(\"Adding default backend -> %s:%d\", s.Host, s.Port)\n\t\t\t\t\t\t\tc.Servers = append(c.Servers, *s)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor _, r := range i.Spec.Rules {\n\t\t\t\t\t\tif r.HTTP == nil {\n\t\t\t\t\t\t\tglog.Errorf(\"Ingress %s\/%s error with rule, skipping: http must be set\", i.Namespace, i.Name)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor _, p := range r.HTTP.Paths {\n\t\t\t\t\t\t\tif p.Path != \"\" && p.Path != \"\/\" {\n\t\t\t\t\t\t\t\tglog.Errorf(\"Ingress %s\/%s error with rule, skipping: %v\", i.Namespace, i.Name, err)\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ts, err := serverForBackend(i, &p.Backend)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tglog.Errorf(\"Ingress %s\/%s error with rule %q path %q, skipping: %v\", i.Namespace, i.Name, r.Host, p.Path, err)\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ts.Names = []string{r.Host}\n\t\t\t\t\t\t\tglog.V(4).Infof(\"Adding backend %q -> %s:%d\", r.Host, s.Host, s.Port)\n\t\t\t\t\t\t\tc.Servers = append(c.Servers, *s)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlock.Unlock()\n\n\t\t\t\tglog.V(2).Infof(\"Updating proxy configuration\")\n\t\t\t\terr := proxy.Update(c)\n\t\t\t\tif err != nil {\n\t\t\t\t\tglog.Errorf(\"Error updating proxy: %v\", err)\n\t\t\t\t\t\/\/ TODO: add backoff logic\n\t\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\t} else {\n\t\t\t\t\tglog.V(2).Infof(\"Proxy configuration update done\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tglog.V(3).Infof(\n\t\t\t\"%s -> %s\",\n\t\t\tconn.RemoteAddr(),\n\t\t\tconn.LocalAddr(),\n\t\t)\n\t\tgo proxy.Handle(conn)\n\t}\n}\n\nfunc (s *Proxy) Handle(conn net.Conn) {\n\tdefer conn.Close()\n\tdata := make([]byte, 4096)\n\n\tlength, err := conn.Read(data)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error reading the first 4k of the connection: %s\", err)\n\t\treturn\n\t}\n\n\tvar proxy *Server\n\thostname, hostname_err := parser.GetHostname(data[:])\n\tif hostname_err == nil {\n\t\tglog.V(6).Infof(\"Parsed hostname: %s\", hostname)\n\n\t\tproxy = s.Get(hostname)\n\t\tif proxy == nil {\n\t\t\tglog.V(4).Infof(\"No proxy matched %s\", hostname)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tglog.V(6).Info(\"Parsed request without hostname\")\n\n\t\tproxy = s.Default\n\t\tif proxy == nil {\n\t\t\tglog.V(4).Info(\"No default proxy\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tclientConn, err := net.Dial(\"tcp\", fmt.Sprintf(\n\t\t\"%s:%d\", proxy.Host, proxy.Port,\n\t))\n\tif err != nil {\n\t\tglog.Warningf(\"Error connecting to backend: %s\", err)\n\t\treturn\n\t}\n\tdefer clientConn.Close()\n\tn, err := clientConn.Write(data[:length])\n\tglog.V(7).Infof(\"Wrote %d bytes\", n)\n\tif err != nil {\n\t\tglog.V(7).Infof(\"Error sending data to backend: %s\", err)\n\t\tclientConn.Close()\n\t}\n\tCopycat(clientConn, conn)\n}\n\nfunc Copycat(client, server net.Conn) {\n\tglog.V(6).Info(\"Entering copy routine\")\n\n\tdoCopy := func(s, c net.Conn, cancel chan<- bool) {\n\t\tio.Copy(s, c)\n\t\tcancel <- true\n\t}\n\n\tcancel := make(chan bool, 2)\n\n\tgo doCopy(server, client, cancel)\n\tgo doCopy(client, server, cancel)\n\n\tselect {\n\tcase <-cancel:\n\t\tglog.V(6).Info(\"Disconnected\")\n\t\treturn\n\t}\n\n}\n\n\/\/ vim: foldmethod=marker\n<commit_msg>Use deferred client config loading, for service accounts<commit_after>\/* {{{ Copyright (c) Paul R. Tagliamonte <paultag@debian.org>, 2015\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE. }}} *\/\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"regexp\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/paultag\/sniff\/parser\"\n\n\tcorev1 \"k8s.io\/client-go\/1.4\/kubernetes\/typed\/core\/v1\"\n\ttypedv1beta1 \"k8s.io\/client-go\/1.4\/kubernetes\/typed\/extensions\/v1beta1\"\n\t\"k8s.io\/client-go\/1.4\/pkg\/api\"\n\t_ \"k8s.io\/client-go\/1.4\/pkg\/api\/install\"\n\tapiv1 \"k8s.io\/client-go\/1.4\/pkg\/api\/v1\"\n\t_ \"k8s.io\/client-go\/1.4\/pkg\/apis\/extensions\/install\"\n\textapiv1beta1 \"k8s.io\/client-go\/1.4\/pkg\/apis\/extensions\/v1beta1\"\n\t\"k8s.io\/client-go\/1.4\/pkg\/fields\"\n\t\"k8s.io\/client-go\/1.4\/pkg\/util\/intstr\"\n\t\"k8s.io\/client-go\/1.4\/pkg\/watch\"\n\t\"k8s.io\/client-go\/1.4\/tools\/cache\"\n\t\"k8s.io\/client-go\/1.4\/tools\/clientcmd\"\n)\n\nconst (\n\t\/\/ ingressClassKey picks a specific \"class\" for the Ingress. The controller\n\t\/\/ only processes Ingresses with this annotation either unset, or set\n\t\/\/ to either nginxIngressClass or the empty string.\n\tingressClassKey = \"kubernetes.io\/ingress.class\"\n)\n\ntype ServerAndRegexp struct {\n\tServer *Server\n\tRegexp *regexp.Regexp\n}\n\ntype Proxy struct {\n\tLock       sync.RWMutex\n\tServerList []ServerAndRegexp\n\tDefault    *Server\n}\n\nfunc (c *Proxy) Get(host string) *Server {\n\tc.Lock.RLock()\n\tdefer c.Lock.RUnlock()\n\n\tfor _, tuple := range c.ServerList {\n\t\tif tuple.Regexp.MatchString(host) {\n\t\t\treturn tuple.Server\n\t\t}\n\t}\n\treturn c.Default\n}\n\nfunc (p *Proxy) Update(c *Config) error {\n\tservers := []ServerAndRegexp{}\n\tfor i, server := range c.Servers {\n\t\tfor _, hostname := range server.Names {\n\t\t\tvar host_regexp *regexp.Regexp\n\t\t\tvar err error\n\t\t\tif server.Regexp {\n\t\t\t\thost_regexp, err = regexp.Compile(hostname)\n\t\t\t} else {\n\t\t\t\thost_regexp, err = regexp.Compile(\"^\" + regexp.QuoteMeta(hostname) + \"$\")\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"cannot update proxy due to invalid regex: %v\", err)\n\t\t\t}\n\t\t\ttuple := ServerAndRegexp{&c.Servers[i], host_regexp}\n\t\t\tservers = append(servers, tuple)\n\t\t}\n\t}\n\tvar def *Server\n\tfor i, server := range c.Servers {\n\t\tif server.Default {\n\t\t\tdef = &c.Servers[i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\tp.Lock.Lock()\n\tdefer p.Lock.Unlock()\n\tp.ServerList = servers\n\tp.Default = def\n\n\treturn nil\n}\n\nfunc (c *Config) Serve() error {\n\tglog.V(1).Infof(\"Listening on %s:%d\", c.Bind.Host, c.Bind.Port)\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\n\t\t\"%s:%d\", c.Bind.Host, c.Bind.Port,\n\t))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tproxy := Proxy{}\n\terr = proxy.Update(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.Kubernetes != nil {\n\t\trules := clientcmd.NewDefaultClientConfigLoadingRules()\n\t\tif c.Kubernetes.Kubeconfig != \"\" {\n\t\t\trules.ExplicitPath = c.Kubernetes.Kubeconfig\n\t\t}\n\t\tccfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, &clientcmd.ConfigOverrides{})\n\t\trcfg, err := ccfg.ClientConfig()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\textclient := typedv1beta1.NewForConfigOrDie(rcfg)\n\t\tclient := corev1.NewForConfigOrDie(rcfg)\n\n\t\t\/\/ trigger to update the proxy\n\t\tupdateTrigger := make(chan struct{}, 1)\n\n\t\t\/\/ watch services\n\t\tservices := NotifyingStore{\n\t\t\tStore: cache.NewStore(cache.MetaNamespaceKeyFunc),\n\t\t\tNotifyFunc: func () {\n\t\t\t\tselect {\n\t\t\t\tcase updateTrigger <- struct{}{}:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\t\tlw := cache.NewListWatchFromClient(client, \"services\", \"\", fields.Everything())\n\t\trefl := cache.NewReflector(lw, &apiv1.Service{}, &services, time.Minute)\n\t\trefl.Run()\n\n\t\t\/\/ wait until services are ready\n\t\tglog.V(1).Infof(\"Waiting for service store to be ready\")\n\t\tfor {\n\t\t\tif refl.LastSyncResourceVersion() != \"\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(time.Millisecond * 200)\n\t\t}\n\n\t\t\/\/ watch ingresses\n\t\tingresses := map[string]*extapiv1beta1.Ingress{}\n\t\tlock := sync.Mutex{}\n\t\tclass := c.Kubernetes.IngressClass\n\t\tif class == \"\" {\n\t\t\tclass = \"sniff\"\n\t\t}\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tw, err := extclient.Ingresses(\"\").Watch(api.ListOptions{})\n\t\t\t\tif err != nil {\n\t\t\t\t\tglog.Errorf(\"Ingress watch error: %v\", err)\n\t\t\t\t\t\/\/ TODO: add backoff logic\n\t\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tevs := w.ResultChan()\n\n\t\t\tEventLoop:\n\t\t\t\tfor ev := range evs {\n\t\t\t\t\ti := ev.Object.(*extapiv1beta1.Ingress)\n\t\t\t\t\tif i != nil && i.Annotations[ingressClassKey] != class {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tswitch ev.Type {\n\t\t\t\t\tcase watch.Added, watch.Modified:\n\t\t\t\t\t\tglog.V(5).Infof(\"event %s for %s\/%s\", ev.Type, i.Namespace, i.Name)\n\t\t\t\t\t\tlock.Lock()\n\t\t\t\t\t\tingresses[i.Namespace+\"\/\"+i.Name] = i\n\t\t\t\t\t\tlock.Unlock()\n\t\t\t\t\tcase watch.Deleted:\n\t\t\t\t\t\tglog.V(5).Infof(\"event %s for %s\/%s\", ev.Type, i.Namespace, i.Name)\n\t\t\t\t\t\tlock.Lock()\n\t\t\t\t\t\tdelete(ingresses, i.Namespace+\"\/\"+i.Name)\n\t\t\t\t\t\tlock.Unlock()\n\t\t\t\t\tcase watch.Error:\n\t\t\t\t\t\tif i != nil {\n\t\t\t\t\t\t\tglog.V(5).Infof(\"event %s for %s\/%s\", ev.Type, i.Namespace, i.Name)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tw.Stop()\n\t\t\t\t\t\tbreak EventLoop\n\t\t\t\t\t}\n\t\t\t\t\tselect {\n\t\t\t\t\tcase updateTrigger <- struct{}{}:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/ TODO: add backoff logic\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t}\n\t\t}()\n\n\t\tgo func() {\n\t\t\tfor range updateTrigger {\n\t\t\t\tlock.Lock()\n\n\t\t\t\tserverForBackend := func(ing *extapiv1beta1.Ingress, backend *extapiv1beta1.IngressBackend) (*Server, error) {\n\t\t\t\t\tobj, found, err := services.GetByKey(fmt.Sprintf(\"%s\/%s\", ing.Namespace, backend.ServiceName))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tif !found {\n\t\t\t\t\t\treturn nil, fmt.Errorf(\"service %s\/%s not found\", ing.Namespace, backend.ServiceName)\n\t\t\t\t\t}\n\t\t\t\t\tsvc := obj.(*apiv1.Service)\n\t\t\t\t\tvar port int\n\t\t\t\t\tif backend.ServicePort.Type == intstr.String {\n\t\t\t\t\t\tfor _, p := range svc.Spec.Ports {\n\t\t\t\t\t\t\tif p.Name == backend.ServicePort.StrVal {\n\t\t\t\t\t\t\t\tport = int(p.Port)\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif port == 0 {\n\t\t\t\t\t\t\treturn nil, fmt.Errorf(\"port %q of service %s\/%s not found\", backend.ServicePort.StrVal, svc.Namespace, svc.Name)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tport = int(backend.ServicePort.IntVal)\n\t\t\t\t\t}\n\t\t\t\t\treturn &Server{\n\t\t\t\t\t\tHost: svc.Spec.ClusterIP,\n\t\t\t\t\t\t\/\/ TODO: support string values:\n\t\t\t\t\t\tPort: port,\n\t\t\t\t\t}, nil\n\t\t\t\t}\n\n\t\t\t\tfor _, i := range ingresses {\n\t\t\t\t\tc.Servers = []Server{}\n\t\t\t\t\tif i.Spec.Backend != nil {\n\t\t\t\t\t\ts, err := serverForBackend(i, i.Spec.Backend)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tglog.Errorf(\"Ingress %s\/%s error with default backend, skipping: %v\", i.Namespace, i.Name, err)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\ts.Default = true\n\t\t\t\t\t\t\tglog.V(4).Infof(\"Adding default backend -> %s:%d\", s.Host, s.Port)\n\t\t\t\t\t\t\tc.Servers = append(c.Servers, *s)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfor _, r := range i.Spec.Rules {\n\t\t\t\t\t\tif r.HTTP == nil {\n\t\t\t\t\t\t\tglog.Errorf(\"Ingress %s\/%s error with rule, skipping: http must be set\", i.Namespace, i.Name)\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor _, p := range r.HTTP.Paths {\n\t\t\t\t\t\t\tif p.Path != \"\" && p.Path != \"\/\" {\n\t\t\t\t\t\t\t\tglog.Errorf(\"Ingress %s\/%s error with rule, skipping: %v\", i.Namespace, i.Name, err)\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ts, err := serverForBackend(i, &p.Backend)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tglog.Errorf(\"Ingress %s\/%s error with rule %q path %q, skipping: %v\", i.Namespace, i.Name, r.Host, p.Path, err)\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ts.Names = []string{r.Host}\n\t\t\t\t\t\t\tglog.V(4).Infof(\"Adding backend %q -> %s:%d\", r.Host, s.Host, s.Port)\n\t\t\t\t\t\t\tc.Servers = append(c.Servers, *s)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlock.Unlock()\n\n\t\t\t\tglog.V(2).Infof(\"Updating proxy configuration\")\n\t\t\t\terr := proxy.Update(c)\n\t\t\t\tif err != nil {\n\t\t\t\t\tglog.Errorf(\"Error updating proxy: %v\", err)\n\t\t\t\t\t\/\/ TODO: add backoff logic\n\t\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\t} else {\n\t\t\t\t\tglog.V(2).Infof(\"Proxy configuration update done\")\n\t\t\t\t}\n\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor {\n\t\tconn, err := listener.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tglog.V(3).Infof(\n\t\t\t\"%s -> %s\",\n\t\t\tconn.RemoteAddr(),\n\t\t\tconn.LocalAddr(),\n\t\t)\n\t\tgo proxy.Handle(conn)\n\t}\n}\n\nfunc (s *Proxy) Handle(conn net.Conn) {\n\tdefer conn.Close()\n\tdata := make([]byte, 4096)\n\n\tlength, err := conn.Read(data)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Error reading the first 4k of the connection: %s\", err)\n\t\treturn\n\t}\n\n\tvar proxy *Server\n\thostname, hostname_err := parser.GetHostname(data[:])\n\tif hostname_err == nil {\n\t\tglog.V(6).Infof(\"Parsed hostname: %s\", hostname)\n\n\t\tproxy = s.Get(hostname)\n\t\tif proxy == nil {\n\t\t\tglog.V(4).Infof(\"No proxy matched %s\", hostname)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tglog.V(6).Info(\"Parsed request without hostname\")\n\n\t\tproxy = s.Default\n\t\tif proxy == nil {\n\t\t\tglog.V(4).Info(\"No default proxy\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tclientConn, err := net.Dial(\"tcp\", fmt.Sprintf(\n\t\t\"%s:%d\", proxy.Host, proxy.Port,\n\t))\n\tif err != nil {\n\t\tglog.Warningf(\"Error connecting to backend: %s\", err)\n\t\treturn\n\t}\n\tdefer clientConn.Close()\n\tn, err := clientConn.Write(data[:length])\n\tglog.V(7).Infof(\"Wrote %d bytes\", n)\n\tif err != nil {\n\t\tglog.V(7).Infof(\"Error sending data to backend: %s\", err)\n\t\tclientConn.Close()\n\t}\n\tCopycat(clientConn, conn)\n}\n\nfunc Copycat(client, server net.Conn) {\n\tglog.V(6).Info(\"Entering copy routine\")\n\n\tdoCopy := func(s, c net.Conn, cancel chan<- bool) {\n\t\tio.Copy(s, c)\n\t\tcancel <- true\n\t}\n\n\tcancel := make(chan bool, 2)\n\n\tgo doCopy(server, client, cancel)\n\tgo doCopy(client, server, cancel)\n\n\tselect {\n\tcase <-cancel:\n\t\tglog.V(6).Info(\"Disconnected\")\n\t\treturn\n\t}\n\n}\n\n\/\/ vim: foldmethod=marker\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"log\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"net\/http\"\n\t\"io\/ioutil\"\n\t\"github.com\/gosimple\/conf\"\n\t\"github.com\/noahm\/rss-proxy\/rss\"\n)\n\nvar client *http.Client\nvar config *conf.Config\nvar pathPrefix string\n\nconst FILTER_INCLUDE = 1\nconst FILTER_EXCLUDE = 2\n\ntype Filter struct {\n\tFieldName string\n\tType int\n\tPattern *regexp.Regexp\n}\n\ntype Feed struct {\n\tName string\n\turl string\n\tusername string\n\tpassword string\n\tagent string\n\tfilter *Filter\n}\n\nfunc NewFeed(name, url, username, password, agent string) *Feed {\n\tf := &Feed{\n\t\tName: name,\n\t\turl: url,\n\t\tusername: username,\n\t\tpassword: password,\n\t\tagent: agent,\n\t\tfilter: nil,\n\t}\n\techo(\"Registering handler for \"+pathPrefix+name)\n\thttp.Handle(pathPrefix+name, f)\n\treturn f\n}\n\nfunc (f *Feed)AddFilter(t int, field string, pattern string) {\n\tf.filter = &Filter{\n\t\tFieldName: field,\n\t\tType: t,\n\t\tPattern: regexp.MustCompile(pattern),\n\t}\n}\n\nfunc (f *Feed)ServeHTTP(respWriter http.ResponseWriter, req *http.Request) {\n\techo(\"Proxying \"+f.Name)\n\n\t\/\/ request feed from remote\n\tfeedReq, _ := http.NewRequest(\"GET\", f.url, nil)\n\tfeedReq.SetBasicAuth(f.username, f.password)\n\tif (f.agent != \"\") {\n\t\tfeedReq.Header.Set(\"User-Agent\", f.agent)\n\t}\n\tfeedResp, _ := client.Do(feedReq)\n\tdefer feedResp.Body.Close()\n\t\/\/ copy headers\n\tfor field, values := range feedResp.Header {\n\t\tif (strings.ToLower(field) != \"content-length\") {\n\t\t\tfor _, value := range values {\n\t\t\t\trespWriter.Header().Add(field, value)\n\t\t\t}\n\t\t}\n\t}\n\n\trespWriter.WriteHeader(feedResp.StatusCode)\n\tif (feedResp.StatusCode != 200 || f.filter == nil) {\n\t\t\/\/ copy feed content without parsing\n\t\tbuf, _ := ioutil.ReadAll(feedResp.Body)\n\t\trespWriter.Write(buf)\n\t} else {\n\t\t\/\/ parse and filter feed content\n\t\tfeed, _ := rss.ParseFromReader(feedResp.Body)\n\t\tselectedItems := []rss.Item{}\n\t\tfor _, item := range feed.Channel.Items {\n\t\t\tmatch := f.filter.Pattern.MatchString(item.GetField(f.filter.FieldName))\n\t\t\tif ( match && f.filter.Type == FILTER_INCLUDE) ||\n\t\t\t   (!match && f.filter.Type == FILTER_EXCLUDE) {\n\t\t\t\tselectedItems = append(selectedItems, item)\n\t\t\t}\n\t\t}\n\t\tfeed.Channel.Items = selectedItems\n\t\tbuf, _ := feed.ToBytes()\n\t\trespWriter.Write(buf)\n\t}\n}\n\nfunc unknownFeed(respWriter http.ResponseWriter, req *http.Request) {\n\techo(\"Unknown feed requested\")\n\trespWriter.WriteHeader(404)\n}\n\nfunc echo(s string) {\n\tfmt.Println(s)\n}\n\nfunc main() {\n\tclient = &http.Client{}\n\tconfig, _ := conf.ReadFile(\"server.conf\")\n\n\t\/\/ handle 404s for unknown feeds\n\tpath, _ := config.String(\"\", \"path-prefix\")\n\tpathPrefix = path+\"\/\"\n\techo(\"Handling unknown feeds with path \"+pathPrefix)\n\thttp.HandleFunc(pathPrefix, unknownFeed)\n\n\t\/\/ read in configured feeds\n\tfeeds := make([]*Feed, 0)\n\tvar newFeed *Feed\n\tvar filterType int\n\tvar filterPattern string\n\tfor _, section := range config.Sections() {\n\t\tif section == \"default\" {\n\t\t\tcontinue\n\t\t}\n\t\tfeed, _ := config.String(section, \"feed\")\n\t\tusername, _ := config.String(section, \"username\")\n\t\tpassword, _ := config.String(section, \"password\")\n\t\tagent, err := config.String(section, \"user-agent\")\n\t\tif (err != nil) {\n\t\t\tagent, _ = config.String(\"\", \"user-agent\")\n\t\t}\n\t\tnewFeed = NewFeed(\n\t\t\tsection,\n\t\t\tfeed,\n\t\t\tusername,\n\t\t\tpassword,\n\t\t\tagent,\n\t\t)\n\t\tfilterField, _ := config.String(section, \"filter-field\")\n\t\tif filterField != \"\" {\n\t\t\tfilterPattern, _ = config.String(section, \"filter-include\")\n\t\t\tif filterPattern == \"\" {\n\t\t\t\tfilterPattern, _ = config.String(section, \"filter-exclude\")\n\t\t\t\tif filterPattern == \"\" {\n\t\t\t\t\tpanic(\"No filter-include or filter-exclude patterns include with filter-field directive in section: \"+section)\n\t\t\t\t}\n\t\t\t\tfilterType = FILTER_EXCLUDE\n\t\t\t} else {\n\t\t\t\tfilterType = FILTER_INCLUDE\n\t\t\t}\n\t\t\tnewFeed.AddFilter(filterType, filterField, filterPattern)\n\t\t}\n\t\tfeeds = append(feeds, newFeed)\n\t}\n\n\t\/\/ start server\n\tuseSsl, _ := config.Bool(\"\", \"use-ssl\")\n\taddress, _ := config.String(\"\", \"serve-address\")\n\tif (useSsl) {\n\t\tcert, _ := config.String(\"\", \"ssl-cert\")\n\t\tkey, _ := config.String(\"\", \"ssl-key\")\n\t\tlog.Fatal(http.ListenAndServeTLS(address, cert, key, nil))\n\t} else {\n\t\tlog.Fatal(http.ListenAndServe(address, nil))\n\t}\n}\n<commit_msg>Only send http basic auth, if username is given<commit_after>package main\n\nimport (\n\t\"log\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"net\/http\"\n\t\"io\/ioutil\"\n\t\"github.com\/gosimple\/conf\"\n\t\"github.com\/noahm\/rss-proxy\/rss\"\n)\n\nvar client *http.Client\nvar config *conf.Config\nvar pathPrefix string\n\nconst FILTER_INCLUDE = 1\nconst FILTER_EXCLUDE = 2\n\ntype Filter struct {\n\tFieldName string\n\tType int\n\tPattern *regexp.Regexp\n}\n\ntype Feed struct {\n\tName string\n\turl string\n\tusername string\n\tpassword string\n\tagent string\n\tfilter *Filter\n}\n\nfunc NewFeed(name, url, username, password, agent string) *Feed {\n\tf := &Feed{\n\t\tName: name,\n\t\turl: url,\n\t\tusername: username,\n\t\tpassword: password,\n\t\tagent: agent,\n\t\tfilter: nil,\n\t}\n\techo(\"Registering handler for \"+pathPrefix+name)\n\thttp.Handle(pathPrefix+name, f)\n\treturn f\n}\n\nfunc (f *Feed)AddFilter(t int, field string, pattern string) {\n\tf.filter = &Filter{\n\t\tFieldName: field,\n\t\tType: t,\n\t\tPattern: regexp.MustCompile(pattern),\n\t}\n}\n\nfunc (f *Feed)ServeHTTP(respWriter http.ResponseWriter, req *http.Request) {\n\techo(\"Proxying \"+f.Name)\n\n\t\/\/ request feed from remote\n\tfeedReq, _ := http.NewRequest(\"GET\", f.url, nil)\n\tif (f.username != \"\") {\n\t\tfeedReq.SetBasicAuth(f.username, f.password)\n\t}\n\tif (f.agent != \"\") {\n\t\tfeedReq.Header.Set(\"User-Agent\", f.agent)\n\t}\n\tfeedResp, _ := client.Do(feedReq)\n\tdefer feedResp.Body.Close()\n\t\/\/ copy headers\n\tfor field, values := range feedResp.Header {\n\t\tif (strings.ToLower(field) != \"content-length\") {\n\t\t\tfor _, value := range values {\n\t\t\t\trespWriter.Header().Add(field, value)\n\t\t\t}\n\t\t}\n\t}\n\n\trespWriter.WriteHeader(feedResp.StatusCode)\n\tif (feedResp.StatusCode != 200 || f.filter == nil) {\n\t\t\/\/ copy feed content without parsing\n\t\tbuf, _ := ioutil.ReadAll(feedResp.Body)\n\t\trespWriter.Write(buf)\n\t} else {\n\t\t\/\/ parse and filter feed content\n\t\tfeed, _ := rss.ParseFromReader(feedResp.Body)\n\t\tselectedItems := []rss.Item{}\n\t\tfor _, item := range feed.Channel.Items {\n\t\t\tmatch := f.filter.Pattern.MatchString(item.GetField(f.filter.FieldName))\n\t\t\tif ( match && f.filter.Type == FILTER_INCLUDE) ||\n\t\t\t   (!match && f.filter.Type == FILTER_EXCLUDE) {\n\t\t\t\tselectedItems = append(selectedItems, item)\n\t\t\t}\n\t\t}\n\t\tfeed.Channel.Items = selectedItems\n\t\tbuf, _ := feed.ToBytes()\n\t\trespWriter.Write(buf)\n\t}\n}\n\nfunc unknownFeed(respWriter http.ResponseWriter, req *http.Request) {\n\techo(\"Unknown feed requested\")\n\trespWriter.WriteHeader(404)\n}\n\nfunc echo(s string) {\n\tfmt.Println(s)\n}\n\nfunc main() {\n\tclient = &http.Client{}\n\tconfig, _ := conf.ReadFile(\"server.conf\")\n\n\t\/\/ handle 404s for unknown feeds\n\tpath, _ := config.String(\"\", \"path-prefix\")\n\tpathPrefix = path+\"\/\"\n\techo(\"Handling unknown feeds with path \"+pathPrefix)\n\thttp.HandleFunc(pathPrefix, unknownFeed)\n\n\t\/\/ read in configured feeds\n\tfeeds := make([]*Feed, 0)\n\tvar newFeed *Feed\n\tvar filterType int\n\tvar filterPattern string\n\tfor _, section := range config.Sections() {\n\t\tif section == \"default\" {\n\t\t\tcontinue\n\t\t}\n\t\tfeed, _ := config.String(section, \"feed\")\n\t\tusername, _ := config.String(section, \"username\")\n\t\tpassword, _ := config.String(section, \"password\")\n\t\tagent, err := config.String(section, \"user-agent\")\n\t\tif (err != nil) {\n\t\t\tagent, _ = config.String(\"\", \"user-agent\")\n\t\t}\n\t\tnewFeed = NewFeed(\n\t\t\tsection,\n\t\t\tfeed,\n\t\t\tusername,\n\t\t\tpassword,\n\t\t\tagent,\n\t\t)\n\t\tfilterField, _ := config.String(section, \"filter-field\")\n\t\tif filterField != \"\" {\n\t\t\tfilterPattern, _ = config.String(section, \"filter-include\")\n\t\t\tif filterPattern == \"\" {\n\t\t\t\tfilterPattern, _ = config.String(section, \"filter-exclude\")\n\t\t\t\tif filterPattern == \"\" {\n\t\t\t\t\tpanic(\"No filter-include or filter-exclude patterns include with filter-field directive in section: \"+section)\n\t\t\t\t}\n\t\t\t\tfilterType = FILTER_EXCLUDE\n\t\t\t} else {\n\t\t\t\tfilterType = FILTER_INCLUDE\n\t\t\t}\n\t\t\tnewFeed.AddFilter(filterType, filterField, filterPattern)\n\t\t}\n\t\tfeeds = append(feeds, newFeed)\n\t}\n\n\t\/\/ start server\n\tuseSsl, _ := config.Bool(\"\", \"use-ssl\")\n\taddress, _ := config.String(\"\", \"serve-address\")\n\tif (useSsl) {\n\t\tcert, _ := config.String(\"\", \"ssl-cert\")\n\t\tkey, _ := config.String(\"\", \"ssl-key\")\n\t\tlog.Fatal(http.ListenAndServeTLS(address, cert, key, nil))\n\t} else {\n\t\tlog.Fatal(http.ListenAndServe(address, nil))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package revel\n\nimport (\n\t\"code.google.com\/p\/go.net\/websocket\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n)\n\nvar (\n\tMainRouter         *Router\n\tMainTemplateLoader *TemplateLoader\n\tMainWatcher        *Watcher\n\tServer             *http.Server\n)\n\n\/\/ This method handles all requests.  It dispatches to handleInternal after\n\/\/ handling \/ adapting websocket connections.\nfunc handle(w http.ResponseWriter, r *http.Request) {\n\tupgrade := r.Header.Get(\"Upgrade\")\n\tif upgrade == \"websocket\" || upgrade == \"Websocket\" {\n\t\twebsocket.Handler(func(ws *websocket.Conn) {\n\t\t\tr.Method = \"WS\"\n\t\t\thandleInternal(w, r, ws)\n\t\t}).ServeHTTP(w, r)\n\t} else {\n\t\thandleInternal(w, r, nil)\n\t}\n}\n\nfunc handleInternal(w http.ResponseWriter, r *http.Request, ws *websocket.Conn) {\n\tvar (\n\t\treq  = NewRequest(r)\n\t\tresp = NewResponse(w)\n\t\tc    = NewController(req, resp)\n\t)\n\treq.Websocket = ws\n\n\tFilters[0](c, Filters[1:])\n\tif c.Result != nil {\n\t\tc.Result.Apply(req, resp)\n\t}\n}\n\n\/\/ Run the server.\n\/\/ This is called from the generated main file.\n\/\/ If port is non-zero, use that.  Else, read the port from app.conf.\nfunc Run(port int) {\n\taddress := HttpAddr\n\tif port == 0 {\n\t\tport = HttpPort\n\t}\n\t\/\/ If the port equals zero, it means do not append port to the address.\n\t\/\/ It can use unix socket or something else.\n\tif port != 0 {\n\t\taddress = fmt.Sprintf(\"%s:%d\", address, port)\n\t}\n\n\tMainTemplateLoader = NewTemplateLoader(TemplatePaths)\n\n\t\/\/ The \"watch\" config variable can turn on and off all watching.\n\t\/\/ (As a convenient way to control it all together.)\n\tif Config.BoolDefault(\"watch\", true) {\n\t\tMainWatcher = NewWatcher()\n\t\tFilters = append([]Filter{WatchFilter}, Filters...)\n\t}\n\n\t\/\/ If desired (or by default), create a watcher for templates and routes.\n\t\/\/ The watcher calls Refresh() on things on the first request.\n\tif MainWatcher != nil && Config.BoolDefault(\"watch.templates\", true) {\n\t\tMainWatcher.Listen(MainTemplateLoader, MainTemplateLoader.paths...)\n\t} else {\n\t\tMainTemplateLoader.Refresh()\n\t}\n\n\tServer = &http.Server{\n\t\tAddr:    address,\n\t\tHandler: http.HandlerFunc(handle),\n\t}\n\n\trunStartupHooks()\n\n\tgo func() {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tfmt.Printf(\"Listening on port %d...\\n\", port)\n\t}()\n\n\tif HttpSsl {\n\t\tERROR.Fatalln(\"Failed to listen:\",\n\t\t\tServer.ListenAndServeTLS(HttpSslCert, HttpSslKey))\n\t} else {\n\t\tERROR.Fatalln(\"Failed to listen:\", Server.ListenAndServe())\n\t}\n}\n\nfunc runStartupHooks() {\n\tfor _, hook := range startupHooks {\n\t\thook()\n\t}\n}\n\nvar startupHooks []func()\n\nfunc OnAppStart(f func()) {\n\tstartupHooks = append(startupHooks, f)\n}\n<commit_msg>Support arbitrary network types<commit_after>package revel\n\nimport (\n\t\"code.google.com\/p\/go.net\/websocket\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar (\n\tMainRouter         *Router\n\tMainTemplateLoader *TemplateLoader\n\tMainWatcher        *Watcher\n\tServer             *http.Server\n)\n\n\/\/ This method handles all requests.  It dispatches to handleInternal after\n\/\/ handling \/ adapting websocket connections.\nfunc handle(w http.ResponseWriter, r *http.Request) {\n\tupgrade := r.Header.Get(\"Upgrade\")\n\tif upgrade == \"websocket\" || upgrade == \"Websocket\" {\n\t\twebsocket.Handler(func(ws *websocket.Conn) {\n\t\t\tr.Method = \"WS\"\n\t\t\thandleInternal(w, r, ws)\n\t\t}).ServeHTTP(w, r)\n\t} else {\n\t\thandleInternal(w, r, nil)\n\t}\n}\n\nfunc handleInternal(w http.ResponseWriter, r *http.Request, ws *websocket.Conn) {\n\tvar (\n\t\treq  = NewRequest(r)\n\t\tresp = NewResponse(w)\n\t\tc    = NewController(req, resp)\n\t)\n\treq.Websocket = ws\n\n\tFilters[0](c, Filters[1:])\n\tif c.Result != nil {\n\t\tc.Result.Apply(req, resp)\n\t}\n}\n\n\/\/ Run the server.\n\/\/ This is called from the generated main file.\n\/\/ If port is non-zero, use that.  Else, read the port from app.conf.\nfunc Run(port int) {\n\taddress := HttpAddr\n\tif port == 0 {\n\t\tport = HttpPort\n\t}\n\n\tvar network = \"tcp\"\n\tvar localAddress string\n\n\t\/\/ If the port is zero, treat the address as a fully qualified local address.\n\t\/\/ This address must be prefixed with the network type followed by a colon,\n\t\/\/ e.g. unix:\/tmp\/app.socket or tcp6:::1 (equivalent to tcp6:0:0:0:0:0:0:0:1)\n\tif port == 0 {\n\t\tparts := strings.SplitN(address, \":\", 2)\n\t\tnetwork = parts[0]\n\t\tlocalAddress = parts[1]\n\t} else {\n\t\tlocalAddress = address + \":\" + strconv.Itoa(port)\n\t}\n\n\tMainTemplateLoader = NewTemplateLoader(TemplatePaths)\n\n\t\/\/ The \"watch\" config variable can turn on and off all watching.\n\t\/\/ (As a convenient way to control it all together.)\n\tif Config.BoolDefault(\"watch\", true) {\n\t\tMainWatcher = NewWatcher()\n\t\tFilters = append([]Filter{WatchFilter}, Filters...)\n\t}\n\n\t\/\/ If desired (or by default), create a watcher for templates and routes.\n\t\/\/ The watcher calls Refresh() on things on the first request.\n\tif MainWatcher != nil && Config.BoolDefault(\"watch.templates\", true) {\n\t\tMainWatcher.Listen(MainTemplateLoader, MainTemplateLoader.paths...)\n\t} else {\n\t\tMainTemplateLoader.Refresh()\n\t}\n\n\tServer = &http.Server{\n\t\tAddr:    localAddress,\n\t\tHandler: http.HandlerFunc(handle),\n\t}\n\n\trunStartupHooks()\n\n\tgo func() {\n\t\ttime.Sleep(100 * time.Millisecond)\n\t\tfmt.Printf(\"Listening on %s...\\n\", address)\n\t}()\n\n\tif HttpSsl {\n\t\tif network != \"tcp\" {\n\t\t\t\/\/ This limitation is just to reduce complexity, since it is standard\n\t\t\t\/\/ to terminate SSL upstream when using unix domain sockets.\n\t\t\tERROR.Fatalln(\"SSL is only supported for TCP sockets. Specify a port to listen on.\")\n\t\t}\n\t\tERROR.Fatalln(\"Failed to listen:\",\n\t\t\tServer.ListenAndServeTLS(HttpSslCert, HttpSslKey))\n\t} else {\n\t\tlistener, err := net.Listen(network, localAddress)\n\t\tif err != nil {\n\t\t\tERROR.Fatalln(\"Failed to listen:\", err)\n\t\t}\n\t\tERROR.Fatalln(\"Failed to serve:\", Server.Serve(listener))\n\t}\n}\n\nfunc runStartupHooks() {\n\tfor _, hook := range startupHooks {\n\t\thook()\n\t}\n}\n\nvar startupHooks []func()\n\nfunc OnAppStart(f func()) {\n\tstartupHooks = append(startupHooks, f)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst maxSize = 5242880\n\nvar blockNetworks = [][]byte{\n\t\/\/ IPv4 Link-local\n\t{169, 254},\n\t\/\/ IPv4 Private\n\t{10},\n\t{172, 16},\n\t{192, 168},\n\t\/\/ TODO: add IPv6\n}\n\nvar httpClient = &http.Client{CheckRedirect: checkRedirect}\n\nfunc checkRedirect(req *http.Request, via []*http.Request) error {\n\tif len(via) >= 4 {\n\t\treturn errors.New(\"Stopped after 10 redirects\")\n\t}\n\tif req.Host != \"\" && !hostAllowed(req.Host) {\n\t\treturn errors.New(\"Invalid host\")\n\t}\n\treturn nil\n}\n\nfunc hostAllowed(host string) bool {\n\tips, err := net.LookupIP(host)\n\tif err != nil || len(ips) == 0 {\n\t\treturn false\n\t}\n\tfor _, ip := range ips {\n\tnetworks:\n\t\tfor _, net := range blockNetworks {\n\t\t\tfor i, b := range net {\n\t\t\t\t\/\/ check each octet of the ip\n\t\t\t\tif ip[i] != b {\n\t\t\t\t\t\/\/ octet doesn't match, move on\n\t\t\t\t\tcontinue networks\n\t\t\t\t}\n\t\t\t\t\/\/ all prefix octets match, this network is blocked\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc proxyRequest(w http.ResponseWriter, r *http.Request) {\n\tif strings.Index(r.Header.Get(\"Via\"), \"assetproxy\") != -1 {\n\t\thttp.Error(w, \"Requesting from self\", http.StatusBadRequest)\n\t}\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, \"Only GET is allowed\", http.StatusMethodNotAllowed)\n\t}\n\n\tdestURL := r.URL.Query().Get(\"url\")\n\tif destURL == \"\" {\n\t\tdestURLBytes, err := hex.DecodeString(r.URL.Path[1:])\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Invalid URL encoding\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tdestURL = string(destURLBytes)\n\t}\n\n\tdest, err := url.Parse(destURL)\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid URL\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif dest.Scheme != \"http\" && dest.Scheme != \"https\" {\n\t\thttp.Error(w, \"Invalid URL scheme, expected http\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif dest.Host == \"\" {\n\t\thttp.Error(w, \"Missing URL host\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif !hostAllowed(dest.Host) {\n\t\thttp.Error(w, \"Invalid host\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\tacceptHeader := r.Header.Get(\"Accept\")\n\tif acceptHeader == \"\" {\n\t\tacceptHeader = \"image\/*\"\n\t}\n\n\treq, _ := http.NewRequest(\"GET\", destURL, nil)\n\treq.Header.Set(\"User-Agent\", r.Header.Get(\"User-Agent\"))\n\treq.Header.Set(\"X-Content-Type-Options\", \"nosniff\")\n\treq.Header.Set(\"Accept\", acceptHeader)\n\treq.Header.Set(\"Accept-Encoding\", r.Header.Get(\"Accept-Encoding\"))\n\n\tvia := r.Header.Get(\"Via\")\n\tif via != \"\" {\n\t\tvia += \", \"\n\t}\n\tvia += \"1.1 assetproxy\"\n\treq.Header.Set(\"Via\", via)\n\n\tifModifiedSince := r.Header.Get(\"If-Modified-Since\")\n\tif ifModifiedSince != \"\" {\n\t\treq.Header.Set(\"If-Modified-Since\", ifModifiedSince)\n\t}\n\n\tifNoneMatch := r.Header.Get(\"If-None-Match\")\n\tif ifNoneMatch != \"\" {\n\t\treq.Header.Set(\"If-None-Match\", ifNoneMatch)\n\t}\n\n\tres, err := httpClient.Do(req)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusNotFound)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK && res.StatusCode != http.StatusNotModified {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tcontentType := res.Header.Get(\"Content-Type\")\n\tif res.StatusCode == http.StatusOK && (len(contentType) < 5 || contentType[:5] != \"image\") {\n\t\thttp.Error(w, \"Received invalid Content-Type\", http.StatusNotFound)\n\t\treturn\n\t}\n\tif contentType != \"\" {\n\t\tw.Header().Set(\"Content-Type\", contentType)\n\t}\n\n\tetag := res.Header.Get(\"ETag\")\n\tif etag != \"\" {\n\t\tw.Header().Set(\"ETag\", etag)\n\t}\n\n\tcontentEncoding := res.Header.Get(\"Content-Encoding\")\n\tif contentEncoding != \"\" {\n\t\tw.Header().Set(\"Content-Encoding\", contentEncoding)\n\t}\n\n\tcontentLength := res.Header.Get(\"Content-Length\")\n\tparsedContentLength, _ := strconv.Atoi(contentLength)\n\tif parsedContentLength > maxSize {\n\t\thttp.Error(w, \"Response is too large\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif contentLength != \"\" {\n\t\tw.Header().Set(\"Content-Length\", contentLength)\n\t}\n\n\tcacheControl := res.Header.Get(\"Cache-Control\")\n\tif cacheControl == \"\" {\n\t\tcacheControl = \"public, max-age=3600\"\n\t}\n\tw.Header().Set(\"Cache-Control\", cacheControl)\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\n\tio.Copy(w, io.LimitReader(res.Body, maxSize))\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", proxyRequest)\n\tport := os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\tport = \"8081\"\n\t}\n\tlog.Fatal(http.ListenAndServe(\":\"+port, nil))\n}\n<commit_msg>Fix up not modified behavior<commit_after>package main\n\nimport (\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst maxSize = 5242880\n\nvar blockNetworks = [][]byte{\n\t\/\/ IPv4 Link-local\n\t{169, 254},\n\t\/\/ IPv4 Private\n\t{10},\n\t{172, 16},\n\t{192, 168},\n\t\/\/ TODO: add IPv6\n}\n\nvar httpClient = &http.Client{CheckRedirect: checkRedirect}\n\nfunc checkRedirect(req *http.Request, via []*http.Request) error {\n\tif len(via) >= 4 {\n\t\treturn errors.New(\"Stopped after 10 redirects\")\n\t}\n\tif req.Host != \"\" && !hostAllowed(req.Host) {\n\t\treturn errors.New(\"Invalid host\")\n\t}\n\treturn nil\n}\n\nfunc hostAllowed(host string) bool {\n\tips, err := net.LookupIP(host)\n\tif err != nil || len(ips) == 0 {\n\t\treturn false\n\t}\n\tfor _, ip := range ips {\n\tnetworks:\n\t\tfor _, net := range blockNetworks {\n\t\t\tfor i, b := range net {\n\t\t\t\t\/\/ check each octet of the ip\n\t\t\t\tif ip[i] != b {\n\t\t\t\t\t\/\/ octet doesn't match, move on\n\t\t\t\t\tcontinue networks\n\t\t\t\t}\n\t\t\t\t\/\/ all prefix octets match, this network is blocked\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc proxyRequest(w http.ResponseWriter, r *http.Request) {\n\tif strings.Index(r.Header.Get(\"Via\"), \"assetproxy\") != -1 {\n\t\thttp.Error(w, \"Requesting from self\", http.StatusBadRequest)\n\t}\n\tif r.Method != \"GET\" {\n\t\thttp.Error(w, \"Only GET is allowed\", http.StatusMethodNotAllowed)\n\t}\n\n\tdestURL := r.URL.Query().Get(\"url\")\n\tif destURL == \"\" {\n\t\tdestURLBytes, err := hex.DecodeString(r.URL.Path[1:])\n\t\tif err != nil {\n\t\t\thttp.Error(w, \"Invalid URL encoding\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tdestURL = string(destURLBytes)\n\t}\n\n\tdest, err := url.Parse(destURL)\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid URL\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif dest.Scheme != \"http\" && dest.Scheme != \"https\" {\n\t\thttp.Error(w, \"Invalid URL scheme, expected http\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif dest.Host == \"\" {\n\t\thttp.Error(w, \"Missing URL host\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif !hostAllowed(dest.Host) {\n\t\thttp.Error(w, \"Invalid host\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\tacceptHeader := r.Header.Get(\"Accept\")\n\tif acceptHeader == \"\" {\n\t\tacceptHeader = \"image\/*\"\n\t}\n\n\treq, _ := http.NewRequest(\"GET\", destURL, nil)\n\treq.Header.Set(\"User-Agent\", r.Header.Get(\"User-Agent\"))\n\treq.Header.Set(\"X-Content-Type-Options\", \"nosniff\")\n\treq.Header.Set(\"Accept\", acceptHeader)\n\treq.Header.Set(\"Accept-Encoding\", r.Header.Get(\"Accept-Encoding\"))\n\n\tvia := r.Header.Get(\"Via\")\n\tif via != \"\" {\n\t\tvia += \", \"\n\t}\n\tvia += \"1.1 assetproxy\"\n\treq.Header.Set(\"Via\", via)\n\n\tifModifiedSince := r.Header.Get(\"If-Modified-Since\")\n\tif ifModifiedSince != \"\" {\n\t\treq.Header.Set(\"If-Modified-Since\", ifModifiedSince)\n\t}\n\n\tifNoneMatch := r.Header.Get(\"If-None-Match\")\n\tif ifNoneMatch != \"\" {\n\t\treq.Header.Set(\"If-None-Match\", ifNoneMatch)\n\t}\n\n\tres, err := httpClient.Do(req)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusNotFound)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode != http.StatusOK && res.StatusCode != http.StatusNotModified {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\tcontentType := res.Header.Get(\"Content-Type\")\n\tif res.StatusCode == http.StatusOK && (len(contentType) < 5 || contentType[:5] != \"image\") {\n\t\thttp.Error(w, \"Received invalid Content-Type\", http.StatusNotFound)\n\t\treturn\n\t}\n\tif contentType != \"\" {\n\t\tw.Header().Set(\"Content-Type\", contentType)\n\t}\n\n\tetag := res.Header.Get(\"ETag\")\n\tif etag != \"\" {\n\t\tw.Header().Set(\"ETag\", etag)\n\t}\n\n\tlastModified := res.Header.Get(\"Last-Modified\")\n\tif lastModified != \"\" {\n\t\tw.Header().Set(\"Last-Modified\", lastModified)\n\t}\n\n\tdate := res.Header.Get(\"Date\")\n\tif date != \"\" {\n\t\tw.Header().Set(\"Date\", date)\n\t}\n\n\tcontentEncoding := res.Header.Get(\"Content-Encoding\")\n\tif contentEncoding != \"\" {\n\t\tw.Header().Set(\"Content-Encoding\", contentEncoding)\n\t}\n\n\tcontentLength := res.Header.Get(\"Content-Length\")\n\tparsedContentLength, _ := strconv.Atoi(contentLength)\n\tif parsedContentLength > maxSize {\n\t\thttp.Error(w, \"Response is too large\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif contentLength != \"\" {\n\t\tw.Header().Set(\"Content-Length\", contentLength)\n\t}\n\n\tcacheControl := res.Header.Get(\"Cache-Control\")\n\tif cacheControl == \"\" {\n\t\tcacheControl = \"public, max-age=3600\"\n\t}\n\tw.Header().Set(\"Cache-Control\", cacheControl)\n\tw.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n\n\tif res.StatusCode == http.StatusNotModified {\n\t\tw.WriteHeader(http.StatusNotModified)\n\t} else {\n\t\tio.Copy(w, io.LimitReader(res.Body, maxSize))\n\t}\n}\n\nfunc main() {\n\thttp.HandleFunc(\"\/\", proxyRequest)\n\tport := os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\tport = \"8081\"\n\t}\n\tlog.Fatal(http.ListenAndServe(\":\"+port, nil))\n}\n<|endoftext|>"}
{"text":"<commit_before>package g9p\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n\n\t\"github.com\/joushou\/g9p\/protocol\"\n)\n\n\/\/ Server serves a ReadWriter with a given handler.\ntype Server struct {\n\tHandler   Handler\n\tRW        io.ReadWriter\n\twriteLock sync.Mutex\n}\n\nfunc (s *Server) handleResponse(tag protocol.Tag, d protocol.Message, e error) {\n\tif e == ErrFlushed {\n\t\treturn\n\t}\n\n\tif e != nil {\n\t\td = &protocol.ErrorResponse{Tag: tag, Error: e.Error()}\n\t}\n\n\ts.writeLock.Lock()\n\tdefer s.writeLock.Unlock()\n\n\tprotocol.Encode(s.RW, d)\n}\n\n\/\/ Start starts the server loop\nfunc (s *Server) Start() error {\n\tfor {\n\t\tvar (\n\t\t\tsize uint32\n\t\t\tmt   protocol.MessageType\n\t\t\terr  error\n\t\t)\n\n\t\tif size, mt, err = protocol.DecodeHdr(s.RW); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ This LimitedReader is not a necessity, but simply a sanity check.\n\t\tlimiter := &io.LimitedReader{R: s.RW, N: int64(size) - protocol.HeaderSize}\n\n\t\tswitch mt {\n\t\tcase protocol.Tversion:\n\t\t\tr := &protocol.VersionRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tgo func(r *protocol.VersionRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Version(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tauth:\n\t\t\tr := &protocol.AuthRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tgo func(r *protocol.AuthRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Auth(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tattach:\n\t\t\tr := &protocol.AttachRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.AttachRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Attach(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tflush:\n\t\t\tr := &protocol.FlushRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.FlushRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Flush(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Twalk:\n\t\t\tr := &protocol.WalkRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.WalkRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Walk(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Topen:\n\t\t\tr := &protocol.OpenRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.OpenRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Open(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tcreate:\n\t\t\tr := &protocol.CreateRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.CreateRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Create(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tread:\n\t\t\tr := &protocol.ReadRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.ReadRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Read(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Twrite:\n\t\t\tr := &protocol.WriteRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.WriteRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Write(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tclunk:\n\t\t\tr := &protocol.ClunkRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.ClunkRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Clunk(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tremove:\n\t\t\tr := &protocol.RemoveRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.RemoveRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Remove(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tstat:\n\t\t\tr := &protocol.StatRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.StatRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Stat(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Twstat:\n\t\t\tr := &protocol.WriteStatRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.WriteStatRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.WriteStat(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tdefault:\n\t\t\treturn protocol.ErrUnknownMessageType\n\t\t}\n\t}\n}\n\n\/\/ Serve serves a ReadWriter with the given handler. Serve does not return\n\/\/ unless an I\/O error occurs.\nfunc Serve(rw io.ReadWriter, handler Handler) error {\n\ts := Server{\n\t\tHandler: handler,\n\t\tRW:      rw,\n\t}\n\n\terr := s.Start()\n\tif c, ok := s.RW.(io.Closer); ok {\n\t\tc.Close()\n\t}\n\treturn err\n}\n\n\/\/ ServeListener accepts connections, calls the provided function to retrieve a\n\/\/ new handler, calling Serve with the connection and handler.\nfunc ServeListener(l net.Listener, handler func() Handler) error {\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo Serve(conn, handler())\n\t}\n}\n<commit_msg>Make FlushResponses sequential from the server<commit_after>package g9p\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n\n\t\"github.com\/joushou\/g9p\/protocol\"\n)\n\n\/\/ Server serves a ReadWriter with a given handler.\ntype Server struct {\n\tHandler   Handler\n\tRW        io.ReadWriter\n\twriteLock sync.Mutex\n}\n\nfunc (s *Server) handleResponse(tag protocol.Tag, d protocol.Message, e error) {\n\tif e == ErrFlushed {\n\t\treturn\n\t}\n\n\tif e != nil {\n\t\td = &protocol.ErrorResponse{Tag: tag, Error: e.Error()}\n\t}\n\n\ts.writeLock.Lock()\n\tdefer s.writeLock.Unlock()\n\n\tprotocol.Encode(s.RW, d)\n}\n\n\/\/ Start starts the server loop\nfunc (s *Server) Start() error {\n\tfor {\n\t\tvar (\n\t\t\tsize uint32\n\t\t\tmt   protocol.MessageType\n\t\t\terr  error\n\t\t)\n\n\t\tif size, mt, err = protocol.DecodeHdr(s.RW); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ This LimitedReader is not a necessity, but simply a sanity check.\n\t\tlimiter := &io.LimitedReader{R: s.RW, N: int64(size) - protocol.HeaderSize}\n\n\t\tswitch mt {\n\t\tcase protocol.Tversion:\n\t\t\tr := &protocol.VersionRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tgo func(r *protocol.VersionRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Version(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tauth:\n\t\t\tr := &protocol.AuthRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tgo func(r *protocol.AuthRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Auth(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tattach:\n\t\t\tr := &protocol.AttachRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.AttachRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Attach(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tflush:\n\t\t\tr := &protocol.FlushRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ FlushRequest is not handled concurrently to ensure the sequential\n\t\t\t\/\/ behaviour the spec demands\n\t\t\t\/\/go func(r *protocol.FlushRequest) {\n\t\t\ttag := r.Tag\n\t\t\tres, err := s.Handler.Flush(r)\n\t\t\tif res != nil {\n\t\t\t\tres.Tag = tag\n\t\t\t}\n\t\t\ts.handleResponse(tag, res, err)\n\t\t\t\/\/}(r)\n\t\tcase protocol.Twalk:\n\t\t\tr := &protocol.WalkRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.WalkRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Walk(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Topen:\n\t\t\tr := &protocol.OpenRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.OpenRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Open(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tcreate:\n\t\t\tr := &protocol.CreateRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.CreateRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Create(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tread:\n\t\t\tr := &protocol.ReadRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.ReadRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Read(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Twrite:\n\t\t\tr := &protocol.WriteRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.WriteRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Write(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tclunk:\n\t\t\tr := &protocol.ClunkRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.ClunkRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Clunk(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tremove:\n\t\t\tr := &protocol.RemoveRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.RemoveRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Remove(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Tstat:\n\t\t\tr := &protocol.StatRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.StatRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.Stat(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tcase protocol.Twstat:\n\t\t\tr := &protocol.WriteStatRequest{}\n\t\t\tif err = r.Decode(limiter); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tgo func(r *protocol.WriteStatRequest) {\n\t\t\t\ttag := r.Tag\n\t\t\t\tres, err := s.Handler.WriteStat(r)\n\t\t\t\tif res != nil {\n\t\t\t\t\tres.Tag = tag\n\t\t\t\t}\n\t\t\t\ts.handleResponse(tag, res, err)\n\t\t\t}(r)\n\t\tdefault:\n\t\t\treturn protocol.ErrUnknownMessageType\n\t\t}\n\t}\n}\n\n\/\/ Serve serves a ReadWriter with the given handler. Serve does not return\n\/\/ unless an I\/O error occurs.\nfunc Serve(rw io.ReadWriter, handler Handler) error {\n\ts := Server{\n\t\tHandler: handler,\n\t\tRW:      rw,\n\t}\n\n\terr := s.Start()\n\tif c, ok := s.RW.(io.Closer); ok {\n\t\tc.Close()\n\t}\n\treturn err\n}\n\n\/\/ ServeListener accepts connections, calls the provided function to retrieve a\n\/\/ new handler, calling Serve with the connection and handler.\nfunc ServeListener(l net.Listener, handler func() Handler) error {\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo Serve(conn, handler())\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"net\/http\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/goware\/jwtauth\"\n\t\"github.com\/go-chi\/chi\"\n\t\"github.com\/go-chi\/chi\/middleware\"\n\t\"github.com\/go-chi\/render\"\n)\n\nfunc initServer(host string, useLog bool) {\n\ttokenAuth = jwtauth.New(\"HS256\", sKey, nil)\n\n\tr := chi.NewRouter()\n\n\tif useLog {\n\t\tr.Use(middleware.Logger)\n\t}\n\tr.Use(middleware.RequestID)\n\tr.Use(middleware.Recoverer)\n\t\/\/ r.Use(middleware.Compress())\n\tr.Use(middleware.Timeout(60 * time.Second))\n\tr.Use(corsHandler)\n\n\t\/\/ Frontend\n\tr.Get(\"\/\", indexHandler)\n\tr.Get(\"\/favicon.ico\", serveFileHandler)\n\tFileServer(r, \"\/static\", http.Dir(filepath.Join(\"public\", \"static\")))\n\tr.NotFound(indexHandler)\n\n\t\/\/ Auth\n\tr.Group(func(r chi.Router) {\n\t\tr.Post(\"\/login\", login)\n\t})\n\n\t\/\/ REST API\n\tr.Group(func(r chi.Router) {\n\t\tr.Use(tokenAuth.Verifier)\n\t\tr.Use(jwtauth.Authenticator)\n\n\t\tr.Use(render.SetContentType(render.ContentTypeJSON))\n\n\t\tr.Route(\"\/api\/v1\/contacts\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listContacts)\n\t\t\tr.Post(\"\/\", createContact)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getContact)\n\t\t\t\tr.Put(\"\/\", updateContact)\n\t\t\t\tr.Delete(\"\/\", deleteContact)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/companies\", func(r chi.Router) {\n\t\t\t\/\/ r.With(paginate).Get(\"\/\", listCompanies)\n\t\t\tr.Get(\"\/\", listCompanies)\n\t\t\tr.Post(\"\/\", createCompany)\n\t\t\t\/\/ r.Get(\"\/search\", SearchArticles)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getCompany)\n\t\t\t\tr.Put(\"\/\", updateCompany)\n\t\t\t\tr.Delete(\"\/\", deleteCompany)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/scopes\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listScopes)\n\t\t\tr.Post(\"\/\", createScope)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getScope)\n\t\t\t\tr.Put(\"\/\", updateScope)\n\t\t\t\tr.Delete(\"\/\", deleteScope)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/educations\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listEducations)\n\t\t\tr.Get(\"\/near\", listEducationsNear)\n\t\t\tr.Post(\"\/\", createEducation)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getEducation)\n\t\t\t\tr.Put(\"\/\", updateEducation)\n\t\t\t\tr.Delete(\"\/\", deleteEducation)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/practices\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listPractices)\n\t\t\tr.Get(\"\/near\", listPracticesNear)\n\t\t\tr.Post(\"\/\", createPractice)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getPractice)\n\t\t\t\tr.Put(\"\/\", updatePractice)\n\t\t\t\tr.Delete(\"\/\", deletePractice)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/kinds\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listKinds)\n\t\t\tr.Post(\"\/\", createKind)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getKind)\n\t\t\t\tr.Put(\"\/\", updateKind)\n\t\t\t\tr.Delete(\"\/\", deleteKind)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/posts\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listPosts)\n\t\t\tr.Post(\"\/\", createPost)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getPost)\n\t\t\t\tr.Put(\"\/\", updatePost)\n\t\t\t\tr.Delete(\"\/\", deletePost)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/ranks\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listRanks)\n\t\t\tr.Post(\"\/\", createRank)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getRank)\n\t\t\t\tr.Put(\"\/\", updateRank)\n\t\t\t\tr.Delete(\"\/\", deleteRank)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/departments\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listDepartments)\n\t\t\tr.Post(\"\/\", createDepartment)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getDepartment)\n\t\t\t\tr.Put(\"\/\", updateDepartment)\n\t\t\t\tr.Delete(\"\/\", deleteDepartment)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/sirens\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listSiren)\n\t\t\tr.Post(\"\/\", createSiren)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getSiren)\n\t\t\t\tr.Put(\"\/\", updateSiren)\n\t\t\t\tr.Delete(\"\/\", deleteSiren)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/sirentypes\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listSirenTypes)\n\t\t\tr.Post(\"\/\", createSirenType)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getSirenType)\n\t\t\t\tr.Put(\"\/\", updateSirenType)\n\t\t\t\tr.Delete(\"\/\", deleteSirenType)\n\t\t\t})\n\t\t})\n\t})\n\n\terr := http.ListenAndServe(host, r)\n\terrmsg(\"ListenAndServe\", err)\n}\n<commit_msg>Move Verifier method to pkg-level func to accept *jwtauth.JwtAuth<commit_after>package main\n\nimport (\n\t\"net\/http\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/go-chi\/chi\"\n\t\"github.com\/go-chi\/chi\/middleware\"\n\t\"github.com\/go-chi\/render\"\n\t\"github.com\/goware\/jwtauth\"\n)\n\nfunc initServer(host string, useLog bool) {\n\ttokenAuth = jwtauth.New(\"HS256\", sKey, nil)\n\n\tr := chi.NewRouter()\n\n\tif useLog {\n\t\tr.Use(middleware.Logger)\n\t}\n\tr.Use(middleware.RequestID)\n\tr.Use(middleware.Recoverer)\n\t\/\/ r.Use(middleware.Compress())\n\tr.Use(middleware.Timeout(60 * time.Second))\n\tr.Use(corsHandler)\n\n\t\/\/ Frontend\n\tr.Get(\"\/\", indexHandler)\n\tr.Get(\"\/favicon.ico\", serveFileHandler)\n\tFileServer(r, \"\/static\", http.Dir(filepath.Join(\"public\", \"static\")))\n\tr.NotFound(indexHandler)\n\n\t\/\/ Auth\n\tr.Group(func(r chi.Router) {\n\t\tr.Post(\"\/login\", login)\n\t})\n\n\t\/\/ REST API\n\tr.Group(func(r chi.Router) {\n\t\tr.Use(jwtauth.Verifier(tokenAuth))\n\t\tr.Use(jwtauth.Authenticator)\n\n\t\tr.Use(render.SetContentType(render.ContentTypeJSON))\n\n\t\tr.Route(\"\/api\/v1\/contacts\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listContacts)\n\t\t\tr.Post(\"\/\", createContact)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getContact)\n\t\t\t\tr.Put(\"\/\", updateContact)\n\t\t\t\tr.Delete(\"\/\", deleteContact)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/companies\", func(r chi.Router) {\n\t\t\t\/\/ r.With(paginate).Get(\"\/\", listCompanies)\n\t\t\tr.Get(\"\/\", listCompanies)\n\t\t\tr.Post(\"\/\", createCompany)\n\t\t\t\/\/ r.Get(\"\/search\", SearchArticles)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getCompany)\n\t\t\t\tr.Put(\"\/\", updateCompany)\n\t\t\t\tr.Delete(\"\/\", deleteCompany)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/scopes\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listScopes)\n\t\t\tr.Post(\"\/\", createScope)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getScope)\n\t\t\t\tr.Put(\"\/\", updateScope)\n\t\t\t\tr.Delete(\"\/\", deleteScope)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/educations\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listEducations)\n\t\t\tr.Get(\"\/near\", listEducationsNear)\n\t\t\tr.Post(\"\/\", createEducation)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getEducation)\n\t\t\t\tr.Put(\"\/\", updateEducation)\n\t\t\t\tr.Delete(\"\/\", deleteEducation)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/practices\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listPractices)\n\t\t\tr.Get(\"\/near\", listPracticesNear)\n\t\t\tr.Post(\"\/\", createPractice)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getPractice)\n\t\t\t\tr.Put(\"\/\", updatePractice)\n\t\t\t\tr.Delete(\"\/\", deletePractice)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/kinds\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listKinds)\n\t\t\tr.Post(\"\/\", createKind)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getKind)\n\t\t\t\tr.Put(\"\/\", updateKind)\n\t\t\t\tr.Delete(\"\/\", deleteKind)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/posts\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listPosts)\n\t\t\tr.Post(\"\/\", createPost)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getPost)\n\t\t\t\tr.Put(\"\/\", updatePost)\n\t\t\t\tr.Delete(\"\/\", deletePost)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/ranks\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listRanks)\n\t\t\tr.Post(\"\/\", createRank)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getRank)\n\t\t\t\tr.Put(\"\/\", updateRank)\n\t\t\t\tr.Delete(\"\/\", deleteRank)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/departments\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listDepartments)\n\t\t\tr.Post(\"\/\", createDepartment)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getDepartment)\n\t\t\t\tr.Put(\"\/\", updateDepartment)\n\t\t\t\tr.Delete(\"\/\", deleteDepartment)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/sirens\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listSiren)\n\t\t\tr.Post(\"\/\", createSiren)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getSiren)\n\t\t\t\tr.Put(\"\/\", updateSiren)\n\t\t\t\tr.Delete(\"\/\", deleteSiren)\n\t\t\t})\n\t\t})\n\n\t\tr.Route(\"\/api\/v1\/sirentypes\", func(r chi.Router) {\n\t\t\tr.Get(\"\/\", listSirenTypes)\n\t\t\tr.Post(\"\/\", createSirenType)\n\t\t\tr.Route(\"\/{id}\", func(r chi.Router) {\n\t\t\t\tr.Get(\"\/\", getSirenType)\n\t\t\t\tr.Put(\"\/\", updateSirenType)\n\t\t\t\tr.Delete(\"\/\", deleteSirenType)\n\t\t\t})\n\t\t})\n\t})\n\n\terr := http.ListenAndServe(host, r)\n\terrmsg(\"ListenAndServe\", err)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"net\/http\"\n\nfunc main() {\n\tm := http.NewServeMux()\n\n\t\/\/list available data sets\n\tm.HandleFunc(\"\/list\", handleList)\n\n\t\/\/session\n\t\/\/get (with auth) - returns values\n\t\/\/post - returns key and value for session\n\tm.HandleFunc(\"\/session\", handleSession)\n\n\n\n}\n<commit_msg>api front completed \t\/list \t\t- list available data sets \t\t\t- a data set is a countinuous time series (ie. a single the prices of a single day for a single symbol\/ticker) \t\/session \t\t- post request with dataset information, creates session and responds with session id \t\/session\/{session id} \t\t- get request, reponds with data for that day, as well as session information<commit_after>package main\n\nimport (\n\t\"net\/http\"\n\t\"time\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"crypto\/rand\"\n\tmrand \"math\/rand\"\n\t\"encoding\/base64\"\n\t\"io\/ioutil\"\n)\n\n\/\/dummy funcion\nfunc getSets() []dataset {\n\tarr := []dataset{\n\t\t{\n\t\t\tTicker: \"AAPL\",\n\t\t\tStart: time.Now(),\n\t\t\tEnd: time.Now().Add(time.Second),\n\t\t}, {\n\t\t\tTicker: \"AAPL\",\n\t\t\tStart: time.Now().Add(20 * time.Hour),\n\t\t\tEnd: time.Now().Add(25 * time.Hour),\n\t\t},\n\t}\n\n\treturn arr\n}\n\nfunc getMoment(t time.Time, p time.Duration) float32 {\n\treturn mrand.Float32()\n}\n\n\n\/\/data sets are continuous on the specified time interval. the moment table has an interval of 1 minute\ntype dataset struct {\n\tTicker string `json:\"ticker\"`\n\tInterval time.Duration `json:\"interval\"`\n\tStart time.Time `json:\"start\"`\n\tEnd time.Time `json:\"end\"`\n}\n\n\/\/this represents a practice\/training session\ntype session struct {\n\tsessStart time.Time\n\tCurrentTime time.Time `json:\"current_time\"`\n\tInterval time.Duration `json:\"interval\"`\n\tTicker string `json:\"ticker\"`\n\tBidPrice float32 `json:\"bid_price\"`\n}\n\nfunc (s *session) next() session {\n\ts.BidPrice = getMoment(s.CurrentTime, s.Interval)\n\n\ts.CurrentTime = s.CurrentTime.Add(s.Interval)\n\n\treturn *s\n}\n\nvar SESSIONS map[string]*session = map[string]*session{}\n\nfunc handleList(w http.ResponseWriter, r *http.Request) {\n\tarr := getSets()\n\n\tbyt, err := json.Marshal(arr)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tw.Write([]byte(\"Error getting data sets\"))\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(byt)\n}\n\nfunc sessionFromDataset(req dataset) (string, error) {\n\ttoken := make([]byte, 10)\n\t_, err := rand.Read(token)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttokenStr := base64.StdEncoding.EncodeToString(token)\n\n\n\tfor SESSIONS[tokenStr] != nil {\n\t\t_, err = rand.Read(token)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\ttokenStr = base64.StdEncoding.EncodeToString(token)\n\t}\n\n\tSESSIONS[tokenStr] = &session{\n\t\tsessStart: time.Now(),\n\t\tInterval: req.Interval,\n\t\tCurrentTime: req.Start,\n\t\tTicker: req.Ticker,\n\t}\n\n\treturn tokenStr, nil\n}\n\nfunc handleSessionCreate(w http.ResponseWriter, r *http.Request) {\n\t\/\/post request creates session\n\tif r.Method != http.MethodPost {\n\t\thttp.Error(w, \"send a POST request with dataset from \/list or get request to \/session\/{token}\", http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tbyt, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, \"could not read body\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\treq := dataset{}\n\terr = json.Unmarshal(byt, &req)\n\tif err != nil {\n\t\thttp.Error(w, \"could not parse body\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstr, err := sessionFromDataset(req)\n\tif err != nil {\n\t\thttp.Error(w, \"session could not be created\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tv := struct {\n\t\tToken string `json:\"token\"`\n\t}{\n\t\tToken: str,\n\t}\n\n\tfmt.Println(str)\n\n\tretByt, err := json.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, \"could not marshal response\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(retByt)\n\n}\n\nfunc handleSession(w http.ResponseWriter, r *http.Request)  {\n\n\tif r.Method != http.MethodGet {\n\t\thttp.Error(w, \"must be get request\", http.StatusMethodNotAllowed)\n\t}\n\n\ttoken := r.URL.Path[len(\"\/session\/\"):]\n\n\tif SESSIONS[token] == (&session{}) {\n\t\thttp.Error(w, \"session \" + token +\" doesn't exist\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\tret := SESSIONS[token].next()\n\n\tbyt, err := json.Marshal(ret)\n\tif err != nil {\n\t\thttp.Error(w, \"could not marshal response\", http.StatusInternalServerError)\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(byt)\n\n}\n\nfunc main() {\n\tfmt.Println(\"starting\")\n\n\tm := http.NewServeMux()\n\n\t\/\/list available data sets\n\tm.HandleFunc(\"\/list\", handleList)\n\n\t\/\/session\n\t\/\/get (with auth) - returns values\n\t\/\/post - returns key and value for session\n\tm.HandleFunc(\"\/session\", handleSessionCreate)\n\tm.HandleFunc(\"\/session\/\", handleSession)\n\n\n\thttp.ListenAndServe(\":8080\", m)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"encoding\/gob\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/flynn\/go-discover\/discover\"\n\tlornec \"github.com\/flynn\/lorne\/client\"\n\t\"github.com\/flynn\/lorne\/types\"\n\tsampic \"github.com\/flynn\/sampi\/client\"\n\t\"github.com\/flynn\/sampi\/types\"\n\t\"github.com\/titanous\/go-dockerclient\"\n\t\"github.com\/titanous\/go-tigertonic\"\n)\n\nfunc main() {\n\tvar err error\n\tscheduler, err = sampic.New()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdisc, err = discover.NewClient()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tmux := tigertonic.NewTrieServeMux()\n\tmux.Handle(\"POST\", \"\/apps\/{app_id}\/formation\/{formation_id}\", tigertonic.Marshaled(changeFormation))\n\tmux.Handle(\"GET\", \"\/apps\/{app_id}\/jobs\", tigertonic.Marshaled(getJobs))\n\tmux.HandleFunc(\"GET\", \"\/apps\/{app_id}\/jobs\/{job_id}\/logs\", getJobLog)\n\tmux.HandleFunc(\"POST\", \"\/apps\/{app_id}\/jobs\", runJob)\n\thttp.ListenAndServe(\"127.0.0.1:1200\", tigertonic.Logged(mux, nil))\n}\n\nvar scheduler *sampic.Client\nvar disc *discover.Client\n\ntype Job struct {\n\tID   string `json:\"id\"`\n\tType string `json:\"type\"`\n}\n\n\/\/ GET \/apps\/{app_id}\/jobs\nfunc getJobs(u *url.URL, h http.Header) (int, http.Header, []Job, error) {\n\tstate, err := scheduler.State()\n\tif err != nil {\n\t\treturn 500, nil, nil, err\n\t}\n\n\tq := u.Query()\n\tprefix := q.Get(\"app_id\") + \"-\"\n\tjobs := make([]Job, 0)\n\tfor _, host := range state {\n\t\tfor _, job := range host.Jobs {\n\t\t\tif strings.HasPrefix(job.ID, prefix) {\n\t\t\t\ttyp := strings.Split(job.ID[len(prefix):], \".\")[0]\n\t\t\t\tjobs = append(jobs, Job{ID: job.ID, Type: typ})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 200, nil, jobs, nil\n}\n\ntype Formation struct {\n\tQuantity int    `json:\"quantity\"`\n\tType     string `json:\"type\"`\n}\n\n\/\/ POST \/apps\/{app_id}\/formation\/{formation_id}\nfunc changeFormation(u *url.URL, h http.Header, req *Formation) (int, http.Header, *Formation, error) {\n\tstate, err := scheduler.State()\n\tif err != nil {\n\t\tlog.Println(\"scheduler state error\", err)\n\t\treturn 500, nil, nil, err\n\t}\n\n\tq := u.Query()\n\treq.Type = q.Get(\"formation_id\")\n\tprefix := q.Get(\"app_id\") + \"-\" + req.Type + \".\"\n\tvar jobs []*sampi.Job\n\tfor _, host := range state {\n\t\tfor _, job := range host.Jobs {\n\t\t\tif strings.HasPrefix(job.ID, prefix) {\n\t\t\t\tif job.Attributes == nil {\n\t\t\t\t\tjob.Attributes = make(map[string]string)\n\t\t\t\t}\n\t\t\t\tjob.Attributes[\"host_id\"] = host.ID\n\t\t\t\tjobs = append(jobs, job)\n\t\t\t}\n\t\t}\n\t}\n\n\tif req.Quantity < 0 {\n\t\treq.Quantity = 0\n\t}\n\tdiff := req.Quantity - len(jobs)\n\tlog.Printf(\"have %d %s, diff %d\", len(jobs), req.Type, diff)\n\tif diff > 0 {\n\t\tconfig := &docker.Config{\n\t\t\tImage:        \"ubuntu\",\n\t\t\tCmd:          []string{\"bash\", \"-c\", \"while true; do sleep 1; date; done;\"},\n\t\t\tAttachStdout: true,\n\t\t\tAttachStderr: true,\n\t\t}\n\t\tschedReq := &sampi.ScheduleReq{\n\t\t\tHostJobs: make(map[string][]*sampi.Job),\n\t\t}\n\touter:\n\t\tfor {\n\t\t\tfor host := range state {\n\t\t\t\tschedReq.HostJobs[host] = append(schedReq.HostJobs[host], &sampi.Job{ID: prefix + randomID(), Config: config})\n\t\t\t\tdiff--\n\t\t\t\tif diff == 0 {\n\t\t\t\t\tbreak outer\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tres, err := scheduler.Schedule(schedReq)\n\t\tif err != nil || !res.Success {\n\t\t\tlog.Println(\"schedule error\", err)\n\t\t\treturn 500, nil, nil, err\n\t\t}\n\t} else if diff < 0 {\n\t\tfor _, job := range jobs[:-diff] {\n\t\t\thost, err := lornec.New(job.Attributes[\"host_id\"])\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"error connecting to\", job.Attributes[\"host_id\"], err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := host.StopJob(job.ID); err != nil {\n\t\t\t\tlog.Println(\"error stopping\", job.ID, \"on\", job.Attributes[\"host_id\"], err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 200, nil, req, nil\n}\n\n\/\/ GET \/apps\/{app_id}\/jobs\/{job_id}\/logs\nfunc getJobLog(w http.ResponseWriter, req *http.Request) {\n\tstate, err := scheduler.State()\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tq := req.URL.Query()\n\tjobID := q.Get(\"job_id\")\n\tif prefix := q.Get(\"app_id\") + \"-\"; !strings.HasPrefix(jobID, prefix) {\n\t\tjobID = prefix + jobID\n\t}\n\tvar job *sampi.Job\n\tvar host sampi.Host\nouter:\n\tfor _, host = range state {\n\t\tfor _, job = range host.Jobs {\n\t\t\tif job.ID == jobID {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t}\n\t\tjob = nil\n\t}\n\tif job == nil {\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\tattachReq := &lorne.AttachReq{\n\t\tJobID: job.ID,\n\t\tFlags: lorne.AttachFlagStdout | lorne.AttachFlagStderr | lorne.AttachFlagLogs,\n\t}\n\terr, errChan := lorneAttach(host.ID, attachReq, w, nil)\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tlog.Println(\"attach error\", err)\n\t\treturn\n\t}\n\tif err := <-errChan; err != nil {\n\t\tlog.Println(\"attach failed\", err)\n\t}\n}\n\ntype NewJob struct {\n\tCmd     []string          `json:\"cmd\"`\n\tEnv     map[string]string `json:\"env\"`\n\tAttach  bool              `json:\"attach\"`\n\tTTY     bool              `json:\"tty\"`\n\tColumns int               `json:\"tty_columns\"`\n\tLines   int               `json:\"tty_lines\"`\n}\n\n\/\/ POST \/apps\/{app_id}\/jobs\nfunc runJob(w http.ResponseWriter, req *http.Request) {\n\tvar jobReq NewJob\n\tif err := json.NewDecoder(req.Body).Decode(&jobReq); err != nil {\n\t\tw.WriteHeader(500)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tstate, err := scheduler.State()\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\t\/\/ pick a random host\n\tvar hostID string\n\tfor hostID = range state {\n\t\tbreak\n\t}\n\tif hostID == \"\" {\n\t\tw.WriteHeader(500)\n\t\tlog.Println(\"no hosts found\")\n\t\treturn\n\t}\n\n\tenv := make([]string, 0, len(jobReq.Env))\n\tfor k, v := range jobReq.Env {\n\t\tenv = append(env, k+\"=\"+v)\n\t}\n\n\tq := req.URL.Query()\n\tjob := &sampi.Job{\n\t\tID: q.Get(\"app_id\") + \"-run.\" + randomID(),\n\t\tConfig: &docker.Config{\n\t\t\tImage:        \"ubuntu\",\n\t\t\tCmd:          jobReq.Cmd,\n\t\t\tAttachStdin:  true,\n\t\t\tAttachStdout: true,\n\t\t\tAttachStderr: true,\n\t\t\tStdinOnce:    true,\n\t\t\tEnv:          env,\n\t\t},\n\t}\n\tif jobReq.TTY {\n\t\tjob.Config.Tty = true\n\t}\n\tif jobReq.Attach {\n\t\tjob.Config.AttachStdin = true\n\t\tjob.Config.StdinOnce = true\n\t\tjob.Config.OpenStdin = true\n\t}\n\n\toutR, outW := io.Pipe()\n\tinR, inW := io.Pipe()\n\tdefer outR.Close()\n\tdefer inW.Close()\n\tvar errChan <-chan error\n\tif jobReq.Attach {\n\t\tattachReq := &lorne.AttachReq{\n\t\t\tJobID:  job.ID,\n\t\t\tFlags:  lorne.AttachFlagStdout | lorne.AttachFlagStderr | lorne.AttachFlagStdin | lorne.AttachFlagStream,\n\t\t\tHeight: jobReq.Lines,\n\t\t\tWidth:  jobReq.Columns,\n\t\t}\n\t\terr, errChan = lorneAttach(hostID, attachReq, outW, inR)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(500)\n\t\t\tlog.Println(\"attach failed\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tres, err := scheduler.Schedule(&sampi.ScheduleReq{HostJobs: map[string][]*sampi.Job{hostID: {job}}})\n\tif err != nil || !res.Success {\n\t\tw.WriteHeader(500)\n\t\tlog.Println(\"schedule failed\", err)\n\t\treturn\n\t}\n\n\tif jobReq.Attach {\n\t\tw.Header().Set(\"Content-Type\", \"application\/vnd.flynn.hijack\")\n\t\tw.Header().Set(\"Content-Length\", \"0\")\n\t\tw.WriteHeader(200)\n\t\tconn, bufrw, err := w.(http.Hijacker).Hijack()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tbufrw.Flush()\n\t\tgo func() {\n\t\t\tbuf := make([]byte, bufrw.Reader.Buffered())\n\t\t\tbufrw.Read(buf)\n\t\t\tinW.Write(buf)\n\t\t\tio.Copy(inW, conn)\n\t\t\tinW.Close()\n\t\t}()\n\t\tgo io.Copy(conn, outR)\n\t\t<-errChan\n\t\tconn.Close()\n\t\treturn\n\t}\n\tw.WriteHeader(200)\n}\n\nfunc lorneAttach(host string, req *lorne.AttachReq, out io.Writer, in io.Reader) (error, <-chan error) {\n\tservices, err := disc.Services(\"flynn-lorne-attach.\" + host)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\taddrs := services.OnlineAddrs()\n\tif len(addrs) == 0 {\n\t\treturn err, nil\n\t}\n\tconn, err := net.Dial(\"tcp\", addrs[0])\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\terr = gob.NewEncoder(conn).Encode(req)\n\tif err != nil {\n\t\tconn.Close()\n\t\treturn err, nil\n\t}\n\n\terrChan := make(chan error)\n\n\tattach := func() {\n\t\tdefer conn.Close()\n\t\tinErr := make(chan error, 1)\n\t\tif in != nil {\n\t\t\tgo func() {\n\t\t\t\tio.Copy(conn, in)\n\t\t\t}()\n\t\t} else {\n\t\t\tclose(inErr)\n\t\t}\n\t\t_, outErr := io.Copy(out, conn)\n\t\tif outErr != nil {\n\t\t\terrChan <- outErr\n\t\t\treturn\n\t\t}\n\t\terrChan <- <-inErr\n\t}\n\n\tattachState := make([]byte, 1)\n\tif _, err := conn.Read(attachState); err != nil {\n\t\tconn.Close()\n\t\treturn err, nil\n\t}\n\tswitch attachState[0] {\n\tcase lorne.AttachError:\n\t\terrBytes, err := ioutil.ReadAll(conn)\n\t\tconn.Close()\n\t\tif err != nil {\n\t\t\treturn err, nil\n\t\t}\n\t\treturn errors.New(string(errBytes)), nil\n\tcase lorne.AttachWaiting:\n\t\tgo func() {\n\t\t\tif _, err := conn.Read(attachState); err != nil {\n\t\t\t\tconn.Close()\n\t\t\t\terrChan <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif attachState[0] == lorne.AttachError {\n\t\t\t\terrBytes, err := ioutil.ReadAll(conn)\n\t\t\t\tconn.Close()\n\t\t\t\tif err != nil {\n\t\t\t\t\terrChan <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\terrChan <- errors.New(string(errBytes))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tattach()\n\t\t}()\n\t\treturn nil, errChan\n\tdefault:\n\t\tgo attach()\n\t\treturn nil, errChan\n\t}\n}\n\nfunc randomID() string {\n\tb := make([]byte, 16)\n\tenc := make([]byte, 24)\n\t_, err := io.ReadFull(rand.Reader, b)\n\tif err != nil {\n\t\tpanic(err) \/\/ This shouldn't ever happen, right?\n\t}\n\tbase64.URLEncoding.Encode(enc, b)\n\treturn string(bytes.TrimRight(enc, \"=\"))\n}\n<commit_msg>controller: Hack in slugrunner<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"encoding\/gob\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/flynn\/go-discover\/discover\"\n\tlornec \"github.com\/flynn\/lorne\/client\"\n\t\"github.com\/flynn\/lorne\/types\"\n\tsampic \"github.com\/flynn\/sampi\/client\"\n\t\"github.com\/flynn\/sampi\/types\"\n\t\"github.com\/titanous\/go-dockerclient\"\n\t\"github.com\/titanous\/go-tigertonic\"\n)\n\nfunc main() {\n\tvar err error\n\tscheduler, err = sampic.New()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdisc, err = discover.NewClient()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tmux := tigertonic.NewTrieServeMux()\n\tmux.Handle(\"POST\", \"\/apps\/{app_id}\/formation\/{formation_id}\", tigertonic.Marshaled(changeFormation))\n\tmux.Handle(\"GET\", \"\/apps\/{app_id}\/jobs\", tigertonic.Marshaled(getJobs))\n\tmux.HandleFunc(\"GET\", \"\/apps\/{app_id}\/jobs\/{job_id}\/logs\", getJobLog)\n\tmux.HandleFunc(\"POST\", \"\/apps\/{app_id}\/jobs\", runJob)\n\thttp.ListenAndServe(\"127.0.0.1:1200\", tigertonic.Logged(mux, nil))\n}\n\nvar scheduler *sampic.Client\nvar disc *discover.Client\n\ntype Job struct {\n\tID   string `json:\"id\"`\n\tType string `json:\"type\"`\n}\n\n\/\/ GET \/apps\/{app_id}\/jobs\nfunc getJobs(u *url.URL, h http.Header) (int, http.Header, []Job, error) {\n\tstate, err := scheduler.State()\n\tif err != nil {\n\t\treturn 500, nil, nil, err\n\t}\n\n\tq := u.Query()\n\tprefix := q.Get(\"app_id\") + \"-\"\n\tjobs := make([]Job, 0)\n\tfor _, host := range state {\n\t\tfor _, job := range host.Jobs {\n\t\t\tif strings.HasPrefix(job.ID, prefix) {\n\t\t\t\ttyp := strings.Split(job.ID[len(prefix):], \".\")[0]\n\t\t\t\tjobs = append(jobs, Job{ID: job.ID, Type: typ})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 200, nil, jobs, nil\n}\n\ntype Formation struct {\n\tQuantity int    `json:\"quantity\"`\n\tType     string `json:\"type\"`\n}\n\nfunc shelfURL() string {\n\tset, _ := disc.Services(\"shelf\")\n\taddrs := set.OnlineAddrs()\n\tif len(addrs) < 1 {\n\t\tpanic(\"Shelf is not discoverable\")\n\t}\n\treturn addrs[0]\n}\n\n\/\/ POST \/apps\/{app_id}\/formation\/{formation_id}\nfunc changeFormation(u *url.URL, h http.Header, req *Formation) (int, http.Header, *Formation, error) {\n\tstate, err := scheduler.State()\n\tif err != nil {\n\t\tlog.Println(\"scheduler state error\", err)\n\t\treturn 500, nil, nil, err\n\t}\n\n\tq := u.Query()\n\treq.Type = q.Get(\"formation_id\")\n\tprefix := q.Get(\"app_id\") + \"-\" + req.Type + \".\"\n\tvar jobs []*sampi.Job\n\tfor _, host := range state {\n\t\tfor _, job := range host.Jobs {\n\t\t\tif strings.HasPrefix(job.ID, prefix) {\n\t\t\t\tif job.Attributes == nil {\n\t\t\t\t\tjob.Attributes = make(map[string]string)\n\t\t\t\t}\n\t\t\t\tjob.Attributes[\"host_id\"] = host.ID\n\t\t\t\tjobs = append(jobs, job)\n\t\t\t}\n\t\t}\n\t}\n\n\tif req.Quantity < 0 {\n\t\treq.Quantity = 0\n\t}\n\tdiff := req.Quantity - len(jobs)\n\tlog.Printf(\"have %d %s, diff %d\", len(jobs), req.Type, diff)\n\tif diff > 0 {\n\t\tconfig := &docker.Config{\n\t\t\tImage:        \"flynn\/slugrunner\",\n\t\t\tCmd:          []string{\"start\", req.Type},\n\t\t\tAttachStdout: true,\n\t\t\tAttachStderr: true,\n\t\t\tEnv:          []string{\"SLUG_URL=http:\/\/\" + shelfURL() + \"\/\" + q.Get(\"app_id\") + \".tgz\"},\n\t\t}\n\t\tschedReq := &sampi.ScheduleReq{\n\t\t\tHostJobs: make(map[string][]*sampi.Job),\n\t\t}\n\touter:\n\t\tfor {\n\t\t\tfor host := range state {\n\t\t\t\tschedReq.HostJobs[host] = append(schedReq.HostJobs[host], &sampi.Job{ID: prefix + randomID(), Config: config})\n\t\t\t\tdiff--\n\t\t\t\tif diff == 0 {\n\t\t\t\t\tbreak outer\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tres, err := scheduler.Schedule(schedReq)\n\t\tif err != nil || !res.Success {\n\t\t\tlog.Println(\"schedule error\", err)\n\t\t\treturn 500, nil, nil, err\n\t\t}\n\t} else if diff < 0 {\n\t\tfor _, job := range jobs[:-diff] {\n\t\t\thost, err := lornec.New(job.Attributes[\"host_id\"])\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"error connecting to\", job.Attributes[\"host_id\"], err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := host.StopJob(job.ID); err != nil {\n\t\t\t\tlog.Println(\"error stopping\", job.ID, \"on\", job.Attributes[\"host_id\"], err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn 200, nil, req, nil\n}\n\n\/\/ GET \/apps\/{app_id}\/jobs\/{job_id}\/logs\nfunc getJobLog(w http.ResponseWriter, req *http.Request) {\n\tstate, err := scheduler.State()\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tq := req.URL.Query()\n\tjobID := q.Get(\"job_id\")\n\tif prefix := q.Get(\"app_id\") + \"-\"; !strings.HasPrefix(jobID, prefix) {\n\t\tjobID = prefix + jobID\n\t}\n\tvar job *sampi.Job\n\tvar host sampi.Host\nouter:\n\tfor _, host = range state {\n\t\tfor _, job = range host.Jobs {\n\t\t\tif job.ID == jobID {\n\t\t\t\tbreak outer\n\t\t\t}\n\t\t}\n\t\tjob = nil\n\t}\n\tif job == nil {\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\tattachReq := &lorne.AttachReq{\n\t\tJobID: job.ID,\n\t\tFlags: lorne.AttachFlagStdout | lorne.AttachFlagStderr | lorne.AttachFlagLogs,\n\t}\n\terr, errChan := lorneAttach(host.ID, attachReq, w, nil)\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tlog.Println(\"attach error\", err)\n\t\treturn\n\t}\n\tif err := <-errChan; err != nil {\n\t\tlog.Println(\"attach failed\", err)\n\t}\n}\n\ntype NewJob struct {\n\tCmd     []string          `json:\"cmd\"`\n\tEnv     map[string]string `json:\"env\"`\n\tAttach  bool              `json:\"attach\"`\n\tTTY     bool              `json:\"tty\"`\n\tColumns int               `json:\"tty_columns\"`\n\tLines   int               `json:\"tty_lines\"`\n}\n\n\/\/ POST \/apps\/{app_id}\/jobs\nfunc runJob(w http.ResponseWriter, req *http.Request) {\n\tvar jobReq NewJob\n\tif err := json.NewDecoder(req.Body).Decode(&jobReq); err != nil {\n\t\tw.WriteHeader(500)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tstate, err := scheduler.State()\n\tif err != nil {\n\t\tw.WriteHeader(500)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\t\/\/ pick a random host\n\tvar hostID string\n\tfor hostID = range state {\n\t\tbreak\n\t}\n\tif hostID == \"\" {\n\t\tw.WriteHeader(500)\n\t\tlog.Println(\"no hosts found\")\n\t\treturn\n\t}\n\n\tenv := make([]string, 0, len(jobReq.Env))\n\tfor k, v := range jobReq.Env {\n\t\tenv = append(env, k+\"=\"+v)\n\t}\n\n\tq := req.URL.Query()\n\tjob := &sampi.Job{\n\t\tID: q.Get(\"app_id\") + \"-run.\" + randomID(),\n\t\tConfig: &docker.Config{\n\t\t\tImage:        \"ubuntu\",\n\t\t\tCmd:          jobReq.Cmd,\n\t\t\tAttachStdin:  true,\n\t\t\tAttachStdout: true,\n\t\t\tAttachStderr: true,\n\t\t\tStdinOnce:    true,\n\t\t\tEnv:          env,\n\t\t},\n\t}\n\tif jobReq.TTY {\n\t\tjob.Config.Tty = true\n\t}\n\tif jobReq.Attach {\n\t\tjob.Config.AttachStdin = true\n\t\tjob.Config.StdinOnce = true\n\t\tjob.Config.OpenStdin = true\n\t}\n\n\toutR, outW := io.Pipe()\n\tinR, inW := io.Pipe()\n\tdefer outR.Close()\n\tdefer inW.Close()\n\tvar errChan <-chan error\n\tif jobReq.Attach {\n\t\tattachReq := &lorne.AttachReq{\n\t\t\tJobID:  job.ID,\n\t\t\tFlags:  lorne.AttachFlagStdout | lorne.AttachFlagStderr | lorne.AttachFlagStdin | lorne.AttachFlagStream,\n\t\t\tHeight: jobReq.Lines,\n\t\t\tWidth:  jobReq.Columns,\n\t\t}\n\t\terr, errChan = lorneAttach(hostID, attachReq, outW, inR)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(500)\n\t\t\tlog.Println(\"attach failed\", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\tres, err := scheduler.Schedule(&sampi.ScheduleReq{HostJobs: map[string][]*sampi.Job{hostID: {job}}})\n\tif err != nil || !res.Success {\n\t\tw.WriteHeader(500)\n\t\tlog.Println(\"schedule failed\", err)\n\t\treturn\n\t}\n\n\tif jobReq.Attach {\n\t\tw.Header().Set(\"Content-Type\", \"application\/vnd.flynn.hijack\")\n\t\tw.Header().Set(\"Content-Length\", \"0\")\n\t\tw.WriteHeader(200)\n\t\tconn, bufrw, err := w.(http.Hijacker).Hijack()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tbufrw.Flush()\n\t\tgo func() {\n\t\t\tbuf := make([]byte, bufrw.Reader.Buffered())\n\t\t\tbufrw.Read(buf)\n\t\t\tinW.Write(buf)\n\t\t\tio.Copy(inW, conn)\n\t\t\tinW.Close()\n\t\t}()\n\t\tgo io.Copy(conn, outR)\n\t\t<-errChan\n\t\tconn.Close()\n\t\treturn\n\t}\n\tw.WriteHeader(200)\n}\n\nfunc lorneAttach(host string, req *lorne.AttachReq, out io.Writer, in io.Reader) (error, <-chan error) {\n\tservices, err := disc.Services(\"flynn-lorne-attach.\" + host)\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\taddrs := services.OnlineAddrs()\n\tif len(addrs) == 0 {\n\t\treturn err, nil\n\t}\n\tconn, err := net.Dial(\"tcp\", addrs[0])\n\tif err != nil {\n\t\treturn err, nil\n\t}\n\terr = gob.NewEncoder(conn).Encode(req)\n\tif err != nil {\n\t\tconn.Close()\n\t\treturn err, nil\n\t}\n\n\terrChan := make(chan error)\n\n\tattach := func() {\n\t\tdefer conn.Close()\n\t\tinErr := make(chan error, 1)\n\t\tif in != nil {\n\t\t\tgo func() {\n\t\t\t\tio.Copy(conn, in)\n\t\t\t}()\n\t\t} else {\n\t\t\tclose(inErr)\n\t\t}\n\t\t_, outErr := io.Copy(out, conn)\n\t\tif outErr != nil {\n\t\t\terrChan <- outErr\n\t\t\treturn\n\t\t}\n\t\terrChan <- <-inErr\n\t}\n\n\tattachState := make([]byte, 1)\n\tif _, err := conn.Read(attachState); err != nil {\n\t\tconn.Close()\n\t\treturn err, nil\n\t}\n\tswitch attachState[0] {\n\tcase lorne.AttachError:\n\t\terrBytes, err := ioutil.ReadAll(conn)\n\t\tconn.Close()\n\t\tif err != nil {\n\t\t\treturn err, nil\n\t\t}\n\t\treturn errors.New(string(errBytes)), nil\n\tcase lorne.AttachWaiting:\n\t\tgo func() {\n\t\t\tif _, err := conn.Read(attachState); err != nil {\n\t\t\t\tconn.Close()\n\t\t\t\terrChan <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif attachState[0] == lorne.AttachError {\n\t\t\t\terrBytes, err := ioutil.ReadAll(conn)\n\t\t\t\tconn.Close()\n\t\t\t\tif err != nil {\n\t\t\t\t\terrChan <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\terrChan <- errors.New(string(errBytes))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tattach()\n\t\t}()\n\t\treturn nil, errChan\n\tdefault:\n\t\tgo attach()\n\t\treturn nil, errChan\n\t}\n}\n\nfunc randomID() string {\n\tb := make([]byte, 16)\n\tenc := make([]byte, 24)\n\t_, err := io.ReadFull(rand.Reader, b)\n\tif err != nil {\n\t\tpanic(err) \/\/ This shouldn't ever happen, right?\n\t}\n\tbase64.URLEncoding.Encode(enc, b)\n\treturn string(bytes.TrimRight(enc, \"=\"))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"encoding\/binary\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/marcelki\/tftp\/netascii\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"syscall\"\n\t\"time\"\n)\n\nconst (\n\tTRIES = 3\n)\n\nvar (\n\tport = flag.String(\"port\", \":69\", \"The port to listen on\")\n\tdir  = flag.String(\"dir\", \"\", \"The directory to serve\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tlog.Fatalln(ListenAndServe(*port))\n}\n\ntype session struct {\n\taddr net.Addr\n\treq  *request\n}\n\nfunc ListenAndServe(port string) error {\n\tpconn, err := net.ListenPacket(\"udp\", port)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsession := &session{}\n\treturn session.Serve(pconn)\n}\n\nfunc (s *session) Serve(pconn net.PacketConn) error {\n\tdefer pconn.Close()\n\tbuf := make([]byte, 516)\n\tfor {\n\t\tn, addr, err := pconn.ReadFrom(buf)\n\t\tif err != nil {\n\t\t\tif nErr, ok := err.(net.Error); ok && nErr.Temporary() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\trequest, err := parseRequest(buf[:n])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Request is not valid: %v.\", err)\n\t\t\tcontinue\n\t\t}\n\t\ts.req = request\n\t\ts.addr = addr\n\n\t\tif *dir != \"\" {\n\t\t\tdirInfo, err := os.Stat(*dir)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ TODO: error\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !dirInfo.IsDir() {\n\t\t\t\tlog.Fatalf(\"Given directory parameter: %s is not valid\", *dir)\n\t\t\t}\n\t\t\ts.req.filename = *dir + \"\/\" + s.req.filename\n\t\t}\n\t\tswitch s.req.opcode {\n\t\tcase RRQ:\n\t\t\tgo s.ReadRequest()\n\t\tcase WRQ:\n\t\t\tgo s.WriteRequest()\n\t\tdefault:\n\t\t\t\/\/ TODO: received packet is incorrect\n\t\t}\n\t}\n}\n\nfunc (s *session) ReadRequest() {\n\taddr := s.addr\n\tconn, err := net.Dial(\"udp\", addr.String())\n\tif err != nil {\n\t\tlog.Printf(\"RRQ: Could not connect to %s: %s\\n\", addr.String(), err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tif exists := fileExists(s.req.filename); !exists {\n\t\terr := s.sendError(conn, uint16(1), \"File not found\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"RRQ: Error sending error packet to %v.\\n\", addr)\n\t\t}\n\t\tlog.Printf(\"RRQ: Requested file %v does not exist\\n\", s.req.filename)\n\t\treturn\n\t}\n\tfd, err := os.Open(s.req.filename)\n\tif err != nil {\n\t\terr = s.sendError(conn, uint16(0), \"Not defined error: Could not open the file descriptor\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"RRQ: Error sending error packet to %v.\\n\", addr)\n\t\t}\n\t\tlog.Printf(\"RRQ: Could not open the %s file descriptor for reading: %s \\n\", s.req.filename, err)\n\t\treturn\n\n\t}\n\t\/\/ initial ack id\n\tid := uint16(1)\n\t\/\/ check if we get a performance gain, when not reusing the slice\/array\n\tdata := make([]byte, 512)\n\tfor {\n\t\tn, err := io.ReadFull(fd, data)\n\t\tif err != nil && err != io.ErrUnexpectedEOF {\n\t\t\treturn\n\t\t}\n\t\terr = s.sendData(conn, id, data[:n])\n\t\tif err != nil {\n\t\t\t\/\/ TOOD: logging\n\t\t\treturn\n\t\t}\n\t\tid++\n\t}\n}\n\nfunc (s *session) WriteRequest() {\n\taddr := s.addr\n\tconn, err := net.Dial(\"udp\", addr.String())\n\tif err != nil {\n\t\tlog.Printf(\"WRQ: Could not connect to %s: %s\\n\", addr.String(), err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tif exists := fileExists(s.req.filename); exists {\n\t\terr := s.sendError(conn, uint16(6), \"File already exists.\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"WRQ: Error sending error packet to %v.\\n\", addr)\n\t\t}\n\t\tlog.Printf(\"WRQ: File %v does already exist\\n\", s.req.filename)\n\t\treturn\n\t}\n\n\t\/\/ TODO: use different permission for the file\n\tfd, err := os.OpenFile(s.req.filename, os.O_CREATE|os.O_WRONLY, 0777)\n\tif err != nil {\n\t\tif e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOSPC {\n\t\t\terr = s.sendError(conn, uint16(3), \"Disk full or allocation exceeded\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"WRQ: Error sending error packet to %v.\\n\", addr)\n\t\t\t}\n\t\t\tlog.Printf(\"WRQ: Not enough space to open the %s file descriptor\\n\", s.req.filename)\n\t\t\treturn\n\t\t}\n\t\terr = s.sendError(conn, uint16(0), \"Not defined error: Could not open the file descriptor\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"WRQ: Error sending error packet to %v.\\n\", addr)\n\t\t}\n\t\tlog.Printf(\"WRQ: Could not open the %s file descriptor: %s \\n\", s.req.filename, err)\n\t\treturn\n\t}\n\tdefer fd.Close()\n\n\tbw := bufio.NewWriter(fd)\n\tid := uint16(0)\n\tfor {\n\t\t\/\/ TODO: what happens when the client sends an error\n\t\t\/\/ we will never flush the writer ?!\n\t\tdata, err := s.sendAck(conn, id, false)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"WRQ: Error sending ack packet to %v.\\n\", addr)\n\t\t\treturn\n\t\t}\n\t\tid++\n\t\tif s.req.mode == \"octet\" {\n\t\t\t_, err = bw.Write(data)\n\t\t} else if s.req.mode == \"netascii\" {\n\t\t\t_, err = netascii.WriteTo(data, bw)\n\t\t} else {\n\t\t\t\/\/ TODO: logging\n\t\t\tfmt.Println(\"Mode not implemented yet!\")\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Printf(\"WRQ: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tif len(data) < 512 {\n\t\t\ts.sendAck(conn, id, true)\n\t\t\tbw.Flush()\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ sendAck sends a ack packet and returns the next data packet\n\/\/ TODO: write a new routine to handle the write request, it works for now, but it isnt simple and elegant\nfunc (s *session) sendAck(conn net.Conn, id uint16, last bool) (data []byte, err error) {\n\tp := ackPacket(id)\nTx:\n\tfor try := 0; try < TRIES; try++ {\n\t\tconn.Write(p)\n\t\tconn.SetReadDeadline(time.Now().Add(time.Second))\n\n\t\t\/\/ TODO: search for a better alternative handling the last packet \/ termination of the session\n\t\tif last {\n\t\t\treturn nil, err\n\t\t}\n\n\t\trecv := make([]byte, 516)\n\t\tfor {\n\t\t\tn, err := conn.Read(recv)\n\t\t\tif err != nil {\n\t\t\t\tif nErr, ok := err.(net.Error); ok && nErr.Timeout() {\n\t\t\t\t\tcontinue Tx\n\t\t\t\t}\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\topcode, remaining, ok := parsePacket(recv[:n])\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/blockid := remaining[:2]\n\t\t\tdata = remaining[2:]\n\t\t\tswitch opcode {\n\t\t\tcase DATA:\n\t\t\t\treturn data, nil\n\t\t\tcase ERR:\n\t\t\t\t\/\/ TOOD: do something when error send\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"timed outw waiting for the next data packet\\n\")\n}\n\nfunc (s *session) sendData(conn net.Conn, id uint16, data []byte) error {\n\tp := dataPacket(id, data)\nTx:\n\tfor try := 0; try < TRIES; try++ {\n\t\tconn.Write(p)\n\t\tconn.SetReadDeadline(time.Now().Add(time.Second))\n\n\t\t\/\/ TODO: consider another slice length?!\n\t\trecv := make([]byte, 516)\n\t\tfor {\n\t\t\tn, err := conn.Read(recv)\n\t\t\tif err != nil {\n\t\t\t\tif nErr, ok := err.(net.Error); ok && nErr.Timeout() {\n\t\t\t\t\tcontinue Tx\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\topcode, remaining, ok := parsePacket(recv[:n])\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch opcode {\n\t\t\tcase ACK:\n\t\t\t\trecvid := binary.BigEndian.Uint16(remaining)\n\t\t\t\tif recvid == id {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\t\/\/ TODO: what should we do, if the client sends a wrong id?\n\t\t\t\tlog.Printf(\"RRQ: Received wrong block id (%v) for packet\", recvid)\n\t\t\tcase ERR:\n\t\t\t\t\/\/ TODO: client aborted the session\n\t\t\t}\n\t\t}\n\t}\n\treturn fmt.Errorf(\"timed out waiting for ack\")\n}\n\nfunc (s *session) sendError(conn net.Conn, errCode uint16, errMsg string) error {\n\tp := errorPacket(errCode, errMsg)\n\t_, err := conn.Write(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc fileExists(fname string) bool {\n\tif _, err := os.Stat(fname); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc Debug(msg string, v ...interface{}) {\n\tfmt.Printf(\"DEBUG: %v\\nValues: %v\\n\", msg, v)\n}\n<commit_msg>Improved reading from file when performing a read request.<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/marcelki\/tftp\/netascii\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"syscall\"\n\t\"time\"\n)\n\nconst (\n\tTRIES = 3\n)\n\nvar (\n\tport = flag.String(\"port\", \":69\", \"The port to listen on\")\n\tdir  = flag.String(\"dir\", \"\", \"The directory to serve\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tlog.Fatalln(ListenAndServe(*port))\n}\n\ntype session struct {\n\taddr net.Addr\n\treq  *request\n}\n\nfunc ListenAndServe(port string) error {\n\tpconn, err := net.ListenPacket(\"udp\", port)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsession := &session{}\n\treturn session.Serve(pconn)\n}\n\nfunc (s *session) Serve(pconn net.PacketConn) error {\n\tdefer pconn.Close()\n\tbuf := make([]byte, 516)\n\tfor {\n\t\tn, addr, err := pconn.ReadFrom(buf)\n\t\tif err != nil {\n\t\t\tif nErr, ok := err.(net.Error); ok && nErr.Temporary() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\trequest, err := parseRequest(buf[:n])\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Request is not valid: %v.\", err)\n\t\t\tcontinue\n\t\t}\n\t\ts.req = request\n\t\ts.addr = addr\n\n\t\tif *dir != \"\" {\n\t\t\tdirInfo, err := os.Stat(*dir)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ TODO: error\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !dirInfo.IsDir() {\n\t\t\t\tlog.Fatalf(\"Given directory parameter: %s is not valid\", *dir)\n\t\t\t}\n\t\t\ts.req.filename = *dir + \"\/\" + s.req.filename\n\t\t}\n\t\tswitch s.req.opcode {\n\t\tcase RRQ:\n\t\t\tgo s.ReadRequest()\n\t\tcase WRQ:\n\t\t\tgo s.WriteRequest()\n\t\tdefault:\n\t\t\t\/\/ TODO: received packet is incorrect\n\t\t}\n\t}\n}\n\nfunc (s *session) ReadRequest() {\n\taddr := s.addr\n\tconn, err := net.Dial(\"udp\", addr.String())\n\tif err != nil {\n\t\tlog.Printf(\"RRQ: Could not connect to %s: %s\\n\", addr.String(), err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tif exists := fileExists(s.req.filename); !exists {\n\t\terr := s.sendError(conn, uint16(1), \"File not found\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"RRQ: Error sending error packet to %v.\\n\", addr)\n\t\t}\n\t\tlog.Printf(\"RRQ: Requested file %v does not exist\\n\", s.req.filename)\n\t\treturn\n\t}\n\tbuf, err := ioutil.ReadFile(s.req.filename)\n\tif err != nil {\n\t\terr = s.sendError(conn, uint16(0), \"Not defined error: couldn't open the file\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"RRQ: Error sending error packet to %v.\\n\", addr)\n\t\t}\n\t\tlog.Printf(\"RRQ: Couldn't open the %s file descriptor for file: %s\\n\", s.req.filename, err)\n\t\treturn\n\t}\n\tid := uint16(1)\n\tdata := make([]byte, 512)\n\trd := bytes.NewReader(buf)\n\tfor {\n\t\tn, err := rd.Read(data)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\terr = s.sendError(conn, uint16(0), \"Not defined error: couldn't read from file\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"RRQ: Error sending error packet to %v.\\n\", addr)\n\t\t\t}\n\t\t\tlog.Printf(\"RRQ: Could not read from reader: %s\\n\", s.req.filename)\n\t\t\treturn\n\t\t}\n\t\terr = s.sendData(conn, id, data[:n])\n\t\tif err != nil {\n\t\t\t\/\/ TOOD: logging\n\t\t\treturn\n\t\t}\n\t\tid++\n\t}\n}\n\nfunc (s *session) WriteRequest() {\n\taddr := s.addr\n\tconn, err := net.Dial(\"udp\", addr.String())\n\tif err != nil {\n\t\tlog.Printf(\"WRQ: Could not connect to %s: %s\\n\", addr.String(), err)\n\t\treturn\n\t}\n\tdefer conn.Close()\n\n\tif exists := fileExists(s.req.filename); exists {\n\t\terr := s.sendError(conn, uint16(6), \"File already exists.\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"WRQ: Error sending error packet to %v.\\n\", addr)\n\t\t}\n\t\tlog.Printf(\"WRQ: File %v does already exist\\n\", s.req.filename)\n\t\treturn\n\t}\n\n\t\/\/ TODO: use different permission for the file\n\tfd, err := os.OpenFile(s.req.filename, os.O_CREATE|os.O_WRONLY, 0777)\n\tif err != nil {\n\t\tif e, ok := err.(*os.PathError); ok && e.Err == syscall.ENOSPC {\n\t\t\terr = s.sendError(conn, uint16(3), \"Disk full or allocation exceeded\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"WRQ: Error sending error packet to %v.\\n\", addr)\n\t\t\t}\n\t\t\tlog.Printf(\"WRQ: Not enough space to open the %s file descriptor\\n\", s.req.filename)\n\t\t\treturn\n\t\t}\n\t\terr = s.sendError(conn, uint16(0), \"Not defined error: Could not open the file descriptor\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"WRQ: Error sending error packet to %v.\\n\", addr)\n\t\t}\n\t\tlog.Printf(\"WRQ: Could not open the %s file descriptor: %s \\n\", s.req.filename, err)\n\t\treturn\n\t}\n\tdefer fd.Close()\n\n\tbw := bufio.NewWriter(fd)\n\tid := uint16(0)\n\tfor {\n\t\t\/\/ TODO: what happens when the client sends an error\n\t\t\/\/ we will never flush the writer ?!\n\t\tdata, err := s.sendAck(conn, id, false)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"WRQ: Error sending ack packet to %v.\\n\", addr)\n\t\t\treturn\n\t\t}\n\t\tid++\n\t\tif s.req.mode == \"octet\" {\n\t\t\t_, err = bw.Write(data)\n\t\t} else if s.req.mode == \"netascii\" {\n\t\t\t_, err = netascii.WriteTo(data, bw)\n\t\t} else {\n\t\t\t\/\/ TODO: logging\n\t\t\tfmt.Println(\"Mode not implemented yet!\")\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Printf(\"WRQ: %v\", err)\n\t\t\treturn\n\t\t}\n\t\tif len(data) < 512 {\n\t\t\ts.sendAck(conn, id, true)\n\t\t\tbw.Flush()\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ sendAck sends a ack packet and returns the next data packet\n\/\/ TODO: write a new routine to handle the write request, it works for now, but it isnt simple and elegant\nfunc (s *session) sendAck(conn net.Conn, id uint16, last bool) (data []byte, err error) {\n\tp := ackPacket(id)\nTx:\n\tfor try := 0; try < TRIES; try++ {\n\t\tconn.Write(p)\n\t\tconn.SetReadDeadline(time.Now().Add(time.Second))\n\n\t\t\/\/ TODO: search for a better alternative handling the last packet \/ termination of the session\n\t\tif last {\n\t\t\treturn nil, err\n\t\t}\n\n\t\trecv := make([]byte, 516)\n\t\tfor {\n\t\t\tn, err := conn.Read(recv)\n\t\t\tif err != nil {\n\t\t\t\tif nErr, ok := err.(net.Error); ok && nErr.Timeout() {\n\t\t\t\t\tcontinue Tx\n\t\t\t\t}\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\topcode, remaining, ok := parsePacket(recv[:n])\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/blockid := remaining[:2]\n\t\t\tdata = remaining[2:]\n\t\t\tswitch opcode {\n\t\t\tcase DATA:\n\t\t\t\treturn data, nil\n\t\t\tcase ERR:\n\t\t\t\t\/\/ TOOD: do something when error send\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, fmt.Errorf(\"timed outw waiting for the next data packet\\n\")\n}\n\nfunc (s *session) sendData(conn net.Conn, id uint16, data []byte) error {\n\tp := dataPacket(id, data)\nTx:\n\tfor try := 0; try < TRIES; try++ {\n\t\tconn.Write(p)\n\t\tconn.SetReadDeadline(time.Now().Add(time.Second))\n\n\t\t\/\/ TODO: consider another slice length?!\n\t\trecv := make([]byte, 516)\n\t\tfor {\n\t\t\tn, err := conn.Read(recv)\n\t\t\tif err != nil {\n\t\t\t\tif nErr, ok := err.(net.Error); ok && nErr.Timeout() {\n\t\t\t\t\tcontinue Tx\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\t\topcode, remaining, ok := parsePacket(recv[:n])\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tswitch opcode {\n\t\t\tcase ACK:\n\t\t\t\trecvid := binary.BigEndian.Uint16(remaining)\n\t\t\t\tif recvid == id {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\t\/\/ TODO: what should we do, if the client sends a wrong id?\n\t\t\t\tlog.Printf(\"RRQ: Received wrong block id (%v) for packet\", recvid)\n\t\t\tcase ERR:\n\t\t\t\t\/\/ TODO: client aborted the session\n\t\t\t}\n\t\t}\n\t}\n\treturn fmt.Errorf(\"timed out waiting for ack\")\n}\n\nfunc (s *session) sendError(conn net.Conn, errCode uint16, errMsg string) error {\n\tp := errorPacket(errCode, errMsg)\n\t_, err := conn.Write(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc fileExists(fname string) bool {\n\tif _, err := os.Stat(fname); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc Debug(msg string, v ...interface{}) {\n\tfmt.Printf(\"DEBUG: %v\\nValues: %v\\n\", msg, v)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"encoding\/gob\"\n\t\"github.com\/Unknwon\/goconfig\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"sync\"\n)\n\nconst (\n\tversion = \"0.1.6\"\n)\n\nfunc main() {\n\t\/\/log.SetFlags(log.Lshortfile)\/\/debug时开启\n\n\tcfg, err := goconfig.LoadConfigFile(\"server.ini\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tvar (\n\t\tkey  = cfg.MustValue(\"client\", \"key\", \"EbzHvwg8BVYz9Rv3\")\n\t\tport = cfg.MustValue(\"server\", \"port\", \"8081\")\n\t)\n\n\tlog.Println(\"|>>>>>>>>>>>>>>>|<<<<<<<<<<<<<<<|\")\n\tlog.Println(\"程序版本：\" + version)\n\tlog.Println(\"监听端口：\" + port)\n\tlog.Println(\"Key：\" + key)\n\tlog.Println(\"|>>>>>>>>>>>>>>>|<<<<<<<<<<<<<<<|\")\n\n\tcer, err := tls.LoadX509KeyPair(\"cert.pem\", \"key.pem\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tconfig := &tls.Config{Certificates: []tls.Certificate{cer}}\n\tln, err := tls.Listen(\"tcp\", \":\"+port, config)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer ln.Close()\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tgo handleConnection(conn, key)\n\t}\n}\n\nfunc handleConnection(conn net.Conn, key string) {\n\tdefer conn.Close()\n\n\tlog.Println(\"[+]\", conn.RemoteAddr())\n\n\tvar handshake Handshake\n\n\t\/\/读取客户端发送的key\n\tbuf := make([]byte, 100)\n\tn, err := conn.Read(buf)\n\tif err != nil {\n\t\tlog.Println(n, err)\n\t\treturn\n\t}\n\n\t\/\/验证key\n\tif string(buf[:n]) == key {\n\t\t_, err = conn.Write([]byte{0})\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tlog.Println(conn.RemoteAddr(), \"验证失败，对方所使用的key：\", string(buf[:n]))\n\t\t_, err = conn.Write([]byte{1})\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/读取客户端发送数据\n\tbuf = make([]byte, 100)\n\tn, err = conn.Read(buf)\n\tif err != nil {\n\t\tlog.Println(n, err)\n\t\treturn\n\t}\n\n\t\/\/对数据解码\n\terr = decode(buf[:n], &handshake)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tlog.Println(conn.RemoteAddr(), \"==\"+handshake.Reqtype+\"=>\", handshake.Url)\n\n\t\/\/connect\n\tpconn, err := net.Dial(handshake.Reqtype, handshake.Url)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer pconn.Close()\n\n\tvar wg sync.WaitGroup\n\n\twg.Add(1)\n\tgo func(wg sync.WaitGroup, in net.Conn, out net.Conn, host, reqtype string) {\n\t\tdefer wg.Done()\n\t\tio.Copy(in, out)\n\t\tlog.Println(in.RemoteAddr(), \"==\"+reqtype+\"=>\", host, \"[√]\")\n\t}(wg, conn, pconn, handshake.Url, handshake.Reqtype)\n\n\tfunc(wg sync.WaitGroup, in net.Conn, out net.Conn, host, reqtype string) {\n\t\tdefer wg.Done()\n\t\tio.Copy(in, out)\n\t\tlog.Println(out.RemoteAddr(), \"<=\"+reqtype+\"==\", host, \"[√]\")\n\t}(wg, pconn, conn, handshake.Url, handshake.Reqtype)\n\twg.Wait()\n}\n\nfunc decode(data []byte, to interface{}) error {\n\tbuf := bytes.NewBuffer(data)\n\tdec := gob.NewDecoder(buf)\n\treturn dec.Decode(to)\n}\n\ntype Handshake struct {\n\tUrl     string\n\tReqtype string\n}\n<commit_msg>修改错误处理<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"encoding\/gob\"\n\t\"github.com\/Unknwon\/goconfig\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"sync\"\n)\n\nconst (\n\tversion = \"0.1.6\"\n)\n\nfunc main() {\n\t\/\/log.SetFlags(log.Lshortfile)\/\/debug时开启\n\n\tcfg, err := goconfig.LoadConfigFile(\"server.ini\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tvar (\n\t\tkey  = cfg.MustValue(\"client\", \"key\", \"EbzHvwg8BVYz9Rv3\")\n\t\tport = cfg.MustValue(\"server\", \"port\", \"8081\")\n\t)\n\n\tlog.Println(\"|>>>>>>>>>>>>>>>|<<<<<<<<<<<<<<<|\")\n\tlog.Println(\"程序版本：\" + version)\n\tlog.Println(\"监听端口：\" + port)\n\tlog.Println(\"Key：\" + key)\n\tlog.Println(\"|>>>>>>>>>>>>>>>|<<<<<<<<<<<<<<<|\")\n\n\tcer, err := tls.LoadX509KeyPair(\"cert.pem\", \"key.pem\")\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tconfig := &tls.Config{Certificates: []tls.Certificate{cer}}\n\tln, err := tls.Listen(\"tcp\", \":\"+port, config)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer ln.Close()\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\tgo handleConnection(conn, key)\n\t}\n}\n\nfunc handleConnection(conn net.Conn, key string) {\n\tdefer conn.Close()\n\n\tlog.Println(\"[+]\", conn.RemoteAddr())\n\n\tvar handshake Handshake\n\n\t\/\/读取客户端发送的key\n\tbuf := make([]byte, 100)\n\tn, err := conn.Read(buf)\n\tif err != nil {\n\t\tlog.Println(n, err)\n\t\treturn\n\t}\n\n\t\/\/验证key\n\tif string(buf[:n]) == key {\n\t\t_, err = conn.Write([]byte{0})\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tlog.Println(conn.RemoteAddr(), \"验证失败，对方所使用的key：\", string(buf[:n]))\n\t\t_, err = conn.Write([]byte{1})\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/读取客户端发送数据\n\tbuf = make([]byte, 100)\n\tn, err = conn.Read(buf)\n\tif err != nil {\n\t\tlog.Println(n, err)\n\t\treturn\n\t}\n\n\t\/\/对数据解码\n\terr = decode(buf[:n], &handshake)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\n\tlog.Println(conn.RemoteAddr(), \"==\"+handshake.Reqtype+\"=>\", handshake.Url)\n\n\t\/\/connect\n\tpconn, err := net.Dial(handshake.Reqtype, handshake.Url)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tdefer pconn.Close()\n\n\tvar wg sync.WaitGroup\n\n\twg.Add(1)\n\tgo func(wg sync.WaitGroup, in net.Conn, out net.Conn, host, reqtype string) {\n\t\tdefer wg.Done()\n\t\tio.Copy(in, out)\n\t\tlog.Println(in.RemoteAddr(), \"==\"+reqtype+\"=>\", host, \"[√]\")\n\t}(wg, conn, pconn, handshake.Url, handshake.Reqtype)\n\n\tfunc(wg sync.WaitGroup, in net.Conn, out net.Conn, host, reqtype string) {\n\t\tdefer wg.Done()\n\t\tio.Copy(in, out)\n\t\tlog.Println(out.RemoteAddr(), \"<=\"+reqtype+\"==\", host, \"[√]\")\n\t}(wg, pconn, conn, handshake.Url, handshake.Reqtype)\n\twg.Wait()\n}\n\nfunc decode(data []byte, to interface{}) error {\n\tbuf := bytes.NewBuffer(data)\n\tdec := gob.NewDecoder(buf)\n\treturn dec.Decode(to)\n}\n\ntype Handshake struct {\n\tUrl     string\n\tReqtype string\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Jacob Taylor jacob.taylor@gmail.com\n\/\/ License: Apache2\npackage main\n\nimport (\n    \"fmt\"\n    \"net\"\n    \".\/utils\"\n    \"bufio\"\n    \"encoding\/binary\"\n    \"time\"\n    \"os\"\n    \"bytes\"\n    \"io\"\n    \"io\/ioutil\"\n    \"log\"\n)\n\nconst nbd_folder = \"\/sample_disks\/\"\n\nfunc send_export_list_item(output *bufio.Writer, export_name string) {\n    data := make([]byte, 1024)\n    length := len(export_name)\n    offset := 0\n\n    \/\/ length of export name\n    binary.BigEndian.PutUint32(data[offset:], uint32(length))  \/\/ length of string\n    offset += 4\n\n    \/\/ export name\n    copy(data[offset:], export_name)\n    offset += length\n\n    reply_type := uint32(2)     \/\/ reply_type: NBD_REP_SERVER\n    send_message(output, reply_type, uint32(offset), data)\n}\n\nfunc send_ack(output *bufio.Writer) {\n    send_message(output, utils.NBD_COMMAND_ACK, 0, nil)\n}\n\nfunc export_name(output *bufio.Writer, conn net.Conn, payload_size int, payload []byte) {\n    fmt.Printf(\"have request to bind to: %s\\n\", string(payload[:payload_size]))\n\n    defer conn.Close()\n\n    var filename bytes.Buffer\n    current_directory, err := os.Getwd()\n    utils.ErrorCheck(err)\n    filename.WriteString(current_directory)\n    filename.WriteString(nbd_folder)\n    filename.Write(payload[:payload_size])\n\n    fmt.Printf(\"Opening file: %s\\n\", filename.String())\n\n    \/\/ attempt to open the file read only\n    file, err := os.OpenFile(filename.String(), os.O_RDWR, 0644)\n    utils.ErrorCheck(err)\n\n    buffer := make([]byte, 256)\n    offset := 0\n\n    fs, err := file.Stat()\n    file_size := uint64(fs.Size())\n\n    binary.BigEndian.PutUint64(buffer[offset:], file_size)  \/\/ size\n    offset += 8\n\n    binary.BigEndian.PutUint16(buffer[offset:], 1)  \/\/ flags\n    offset += 2\n\n    data_out, err := output.Write(buffer[:offset])\n    output.Flush()\n    utils.ErrorCheck(err)\n    fmt.Printf(\"Wrote %d chars: %v\\n\", data_out, buffer[:offset])\n\n    \/\/ Check the options to see if we need to pad with Zeros\n\n\n\n    buffer = make([]byte, 512*1024)\n    conn_reader := bufio.NewReader(conn)\n    abort := false\n    for {\n        offset := 0\n        waiting_for := 28       \/\/ wait for at least the minimum payload size\n\n\/\/ Duplicate\n        for offset < waiting_for {\n            length, err := conn_reader.Read(buffer[offset:waiting_for])\n            offset += length\n            utils.ErrorCheck(err)\n            if err == io.EOF {\n                abort = true\n                break\n            }\n            utils.LogData(\"Reading instruction\\n\", offset, buffer)\n            if offset < waiting_for {\n                time.Sleep(5 * time.Millisecond)\n            }\n        }\n\/\/ Duplicate\n        if abort {\n            fmt.Printf(\"Abort detected, escaping processing loop\\n\")\n            break\n        }\n\n        fmt.Printf(\"We read the buffer %v\\n\", buffer[:waiting_for])\n\n        \/\/magic := binary.BigEndian.Uint32(buffer)\n        command := binary.BigEndian.Uint32(buffer[4:8])\n        handle := binary.BigEndian.Uint64(buffer[8:16])\n        from := binary.BigEndian.Uint64(buffer[16:24])\n        length := binary.BigEndian.Uint32(buffer[24:28])\n\n        switch command {\n        case utils.NBD_COMMAND_READ:\n            fmt.Printf(\"We have a request to read. handle: %v, from: %v, length: %v\\n\", handle, from, length)\n            fmt.Printf(\"Read Resquest    Offset:%x length: %v     Handle %X\\n\", from, length, handle)\n\n            data_out, err = file.ReadAt(buffer[16:16+length], int64(from))\n            utils.ErrorCheck(err)\n\n            binary.BigEndian.PutUint32(buffer[:4], utils.NBD_REPLY_MAGIC)\n            binary.BigEndian.PutUint32(buffer[4:8], 0)                      \/\/ error bits\n\n            utils.LogData(\"About to reply with\", int(16+length), buffer)\n\n            conn.Write(buffer[:16+length])\n\n            continue\n        case utils.NBD_COMMAND_WRITE:\n            fmt.Printf(\"We have a request to write. handle: %v, from: %v, length: %v\\n\", handle, from, length)\n\n            waiting_for += int(length)                   \/\/ wait for the additional payload\n\n\/\/ Duplicate\n            for offset < waiting_for {\n                length, err := conn_reader.Read(buffer[offset:waiting_for])\n                offset += length\n                utils.ErrorCheck(err)\n                if err == io.EOF {\n                    abort = true\n                    break\n                }\n                utils.LogData(\"Reading write data\\n\", offset, buffer)\n                if offset < waiting_for {\n                    time.Sleep(5 * time.Millisecond)\n                }\n            }\n\/\/ Duplicate\n\n            data_out, err = file.WriteAt(buffer[28:28+length], int64(from))\n            utils.ErrorCheck(err)\n\n            file.Sync()\n\n            \/\/ let them know we are done\n            binary.BigEndian.PutUint32(buffer[:4], utils.NBD_REPLY_MAGIC)\n            binary.BigEndian.PutUint32(buffer[4:8], 0)                      \/\/ error bits\n\n            utils.LogData(\"About to reply with\", int(16), buffer)\n            conn.Write(buffer[:16])\n\n            continue\n\n        case utils.NBD_COMMAND_DISCONNECT:\n            fmt.Printf(\"We have received a request to disconnect\\n\")\n            \/\/ close the file and return\n\n            file.Sync()\n            return\n        }\n    }\n}\n\nfunc send_export_list(output *bufio.Writer) {\n    current_directory, err := os.Getwd()\n    files, err := ioutil.ReadDir(current_directory + nbd_folder)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, file := range files {\n        send_export_list_item(output, file.Name())\n    }\n\n    send_ack(output)\n}\n\nfunc send_message(output *bufio.Writer, reply_type uint32, length uint32, data []byte ) {\n    endian := binary.BigEndian\n    buffer := make([]byte, 1024)\n    offset := 0\n\n    endian.PutUint64(buffer[offset:], utils.NBD_SERVER_SEND_REPLY_MAGIC)\n    offset += 8\n\n    endian.PutUint32(buffer[offset:], uint32(3))  \/\/ Flags (3 = supports list)\n    offset += 4\n\n    endian.PutUint32(buffer[offset:], reply_type)  \/\/ reply_type: NBD_REP_SERVER\n    offset += 4\n\n    endian.PutUint32(buffer[offset:], length)  \/\/ length of package\n    offset += 4\n\n    if data != nil {\n        copy(buffer[offset:], data[0:length])\n        offset += int(length)\n    }\n\n    data_to_send := buffer[:offset]\n    output.Write(data_to_send)\n    output.Flush()\n\n    utils.LogData(\"Just sent:\", offset, data_to_send)\n}\n\nfunc main() {\n\n    if len(os.Args) <  3 {\n        panic(\"missing arguments:  (ipaddress) (portnumber)\")\n        return\n    }\n\n    listener, err := net.Listen(\"tcp\", os.Args[1] + \":\" + os.Args[2])\n    utils.ErrorCheck(err)\n\n    fmt.Printf(\"Hello World, we have %v\\n\", listener)\n    reply_magic := make([]byte, 4)\n    binary.BigEndian.PutUint32(reply_magic, utils.NBD_REPLY_MAGIC)\n\n    for {\n        conn, err := listener.Accept()\n        utils.ErrorCheck(err)\n\n        fmt.Printf(\"We have a new connection from: %s\\n\", conn.RemoteAddr())\n        output := bufio.NewWriter(conn)\n\n        output.WriteString(\"NBDMAGIC\")      \/\/ init password\n        output.WriteString(\"IHAVEOPT\")      \/\/ Magic\n        output.Write([]byte{0, 3})          \/\/ Flags (3 = supports list)\n        output.Flush()\n\n        \/\/ Fetch the data until we get the initial options\n        data := make([]byte, 1024)\n        offset := 0\n        waiting_for := 16       \/\/ wait for at least the minimum payload size\n\n        for offset < waiting_for {\n            length, err := conn.Read(data[offset:])\n            offset += length\n            utils.ErrorCheck(err)\n            \/\/utils.LogData(\"Reading instruction\", offset, data)\n            if offset < waiting_for {\n                time.Sleep(5 * time.Millisecond)\n            }\n        }\n\n        utils.LogData(\"Received from client\", offset, data)\n        \/\/ Skip the first 8 characters (options)\n        command := binary.BigEndian.Uint32(data[12:])\n        payload_size := int(binary.BigEndian.Uint32(data[16:]))\n\n        fmt.Sprintf(\"command is: %d\\npayload_size is: %d\\n\", command, payload_size)\n        waiting_for += int(payload_size)\n        for offset < waiting_for {\n            length, err := conn.Read(data[offset:])\n            offset += length\n            utils.ErrorCheck(err)\n            utils.LogData(\"Reading instruction\", offset, data)\n            if offset < waiting_for {\n                time.Sleep(5 * time.Millisecond)\n            }\n        }\n        payload := make([]byte, payload_size)\n\n        if payload_size > 0{\n            copy(payload, data[20:])\n        }\n\n        utils.LogData(\"Payload is:\", payload_size, payload)\n        fmt.Printf(\"command is: %v\\n\", command)\n\n        \/\/ At this point, we have the command, payload size, and payload.\n        switch command {\n        case utils.NBD_COMMAND_LIST:\n            send_export_list(output)\n            conn.Close()\n            break\n        case utils.NBD_COMMAND_EXPORT_NAME:\n            go export_name(output, conn, payload_size, payload)\n            break\n        }\n    }\n\n}\n<commit_msg>adding packet tracking log statements<commit_after>\/\/ Copyright 2016 Jacob Taylor jacob.taylor@gmail.com\n\/\/ License: Apache2\npackage main\n\nimport (\n    \"fmt\"\n    \"net\"\n    \".\/utils\"\n    \"bufio\"\n    \"encoding\/binary\"\n    \"time\"\n    \"os\"\n    \"bytes\"\n    \"io\"\n    \"io\/ioutil\"\n    \"log\"\n)\n\nconst nbd_folder = \"\/sample_disks\/\"\n\nfunc send_export_list_item(output *bufio.Writer, export_name string) {\n    data := make([]byte, 1024)\n    length := len(export_name)\n    offset := 0\n\n    \/\/ length of export name\n    binary.BigEndian.PutUint32(data[offset:], uint32(length))  \/\/ length of string\n    offset += 4\n\n    \/\/ export name\n    copy(data[offset:], export_name)\n    offset += length\n\n    reply_type := uint32(2)     \/\/ reply_type: NBD_REP_SERVER\n    send_message(output, reply_type, uint32(offset), data)\n}\n\nfunc send_ack(output *bufio.Writer) {\n    send_message(output, utils.NBD_COMMAND_ACK, 0, nil)\n}\n\nfunc export_name(output *bufio.Writer, conn net.Conn, payload_size int, payload []byte) {\n    fmt.Printf(\"have request to bind to: %s\\n\", string(payload[:payload_size]))\n\n    defer conn.Close()\n\n    var filename bytes.Buffer\n    current_directory, err := os.Getwd()\n    utils.ErrorCheck(err)\n    filename.WriteString(current_directory)\n    filename.WriteString(nbd_folder)\n    filename.Write(payload[:payload_size])\n\n    fmt.Printf(\"Opening file: %s\\n\", filename.String())\n\n    \/\/ attempt to open the file read only\n    file, err := os.OpenFile(filename.String(), os.O_RDWR, 0644)\n    utils.ErrorCheck(err)\n\n    buffer := make([]byte, 256)\n    offset := 0\n\n    fs, err := file.Stat()\n    file_size := uint64(fs.Size())\n\n    binary.BigEndian.PutUint64(buffer[offset:], file_size)  \/\/ size\n    offset += 8\n\n    binary.BigEndian.PutUint16(buffer[offset:], 1)  \/\/ flags\n    offset += 2\n\n    data_out, err := output.Write(buffer[:offset])\n    output.Flush()\n    utils.ErrorCheck(err)\n    fmt.Printf(\"Wrote %d chars: %v\\n\", data_out, buffer[:offset])\n\n    \/\/ Check the options to see if we need to pad with Zeros\n\n\n\n    buffer = make([]byte, 512*1024)\n    conn_reader := bufio.NewReader(conn)\n    abort := false\n    for {\n        offset := 0\n        waiting_for := 28       \/\/ wait for at least the minimum payload size\n\n\/\/ Duplicate\n        for offset < waiting_for {\n            length, err := conn_reader.Read(buffer[offset:waiting_for])\n            offset += length\n            utils.ErrorCheck(err)\n            if err == io.EOF {\n                abort = true\n                break\n            }\n            utils.LogData(\"Reading instruction\\n\", offset, buffer)\n            if offset < waiting_for {\n                time.Sleep(5 * time.Millisecond)\n            }\n        }\n\/\/ Duplicate\n        if abort {\n            fmt.Printf(\"Abort detected, escaping processing loop\\n\")\n            break\n        }\n\n        fmt.Printf(\"We read the buffer %v\\n\", buffer[:waiting_for])\n\n        \/\/magic := binary.BigEndian.Uint32(buffer)\n        command := binary.BigEndian.Uint32(buffer[4:8])\n        handle := binary.BigEndian.Uint64(buffer[8:16])\n        from := binary.BigEndian.Uint64(buffer[16:24])\n        length := binary.BigEndian.Uint32(buffer[24:28])\n\n        switch command {\n        case utils.NBD_COMMAND_READ:\n            fmt.Printf(\"We have a request to read. handle: %v, from: %v, length: %v\\n\", handle, from, length)\n            fmt.Printf(\"Read Resquest    Offset:%x length: %v     Handle %X\\n\", from, length, handle)\n\n            data_out, err = file.ReadAt(buffer[16:16+length], int64(from))\n            utils.ErrorCheck(err)\n\n            binary.BigEndian.PutUint32(buffer[:4], utils.NBD_REPLY_MAGIC)\n            binary.BigEndian.PutUint32(buffer[4:8], 0)                      \/\/ error bits\n\n            utils.LogData(\"About to reply with\", int(16+length), buffer)\n\n            conn.Write(buffer[:16+length])\n\n            continue\n        case utils.NBD_COMMAND_WRITE:\n            fmt.Printf(\"We have a request to write. handle: %v, from: %v, length: %v\\n\", handle, from, length)\n\n            waiting_for += int(length)                   \/\/ wait for the additional payload\n\n\/\/ Duplicate\n            for offset < waiting_for {\n                length, err := conn_reader.Read(buffer[offset:waiting_for])\n                offset += length\n                utils.ErrorCheck(err)\n                if err == io.EOF {\n                    abort = true\n                    break\n                }\n                utils.LogData(\"Reading write data\\n\", offset, buffer)\n                if offset < waiting_for {\n                    time.Sleep(5 * time.Millisecond)\n                }\n            }\n\/\/ Duplicate\n\n            data_out, err = file.WriteAt(buffer[28:28+length], int64(from))\n            utils.ErrorCheck(err)\n\n            file.Sync()\n\n            \/\/ let them know we are done\n            binary.BigEndian.PutUint32(buffer[:4], utils.NBD_REPLY_MAGIC)\n            binary.BigEndian.PutUint32(buffer[4:8], 0)                      \/\/ error bits\n\n            utils.LogData(\"About to reply with\", int(16), buffer)\n            conn.Write(buffer[:16])\n\n            continue\n\n        case utils.NBD_COMMAND_DISCONNECT:\n            fmt.Printf(\"We have received a request to disconnect\\n\")\n            \/\/ close the file and return\n\n            file.Sync()\n            return\n        }\n    }\n}\n\nfunc send_export_list(output *bufio.Writer) {\n    current_directory, err := os.Getwd()\n    files, err := ioutil.ReadDir(current_directory + nbd_folder)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for _, file := range files {\n        send_export_list_item(output, file.Name())\n    }\n\n    send_ack(output)\n}\n\nfunc send_message(output *bufio.Writer, reply_type uint32, length uint32, data []byte ) {\n    endian := binary.BigEndian\n    buffer := make([]byte, 1024)\n    offset := 0\n\n    endian.PutUint64(buffer[offset:], utils.NBD_SERVER_SEND_REPLY_MAGIC)\n    offset += 8\n\n    endian.PutUint32(buffer[offset:], uint32(3))  \/\/ Flags (3 = supports list)\n    offset += 4\n\n    endian.PutUint32(buffer[offset:], reply_type)  \/\/ reply_type: NBD_REP_SERVER\n    offset += 4\n\n    endian.PutUint32(buffer[offset:], length)  \/\/ length of package\n    offset += 4\n\n    if data != nil {\n        copy(buffer[offset:], data[0:length])\n        offset += int(length)\n    }\n\n    data_to_send := buffer[:offset]\n    output.Write(data_to_send)\n    output.Flush()\n\n    utils.LogData(\"Just sent:\", offset, data_to_send)\n}\n\nfunc main() {\n\n    if len(os.Args) <  3 {\n        panic(\"missing arguments:  (ipaddress) (portnumber)\")\n        return\n    }\n\n    listener, err := net.Listen(\"tcp\", os.Args[1] + \":\" + os.Args[2])\n    utils.ErrorCheck(err)\n\n    fmt.Printf(\"Hello World, we have %v\\n\", listener)\n    reply_magic := make([]byte, 4)\n    binary.BigEndian.PutUint32(reply_magic, utils.NBD_REPLY_MAGIC)\n\n    for {\n        conn, err := listener.Accept()\n        utils.ErrorCheck(err)\n\n        fmt.Printf(\"We have a new connection from: %s\\n\", conn.RemoteAddr())\n        output := bufio.NewWriter(conn)\n\n        output.WriteString(\"NBDMAGIC\")      \/\/ init password\n        output.WriteString(\"IHAVEOPT\")      \/\/ Magic\n        output.Write([]byte{0, 3})          \/\/ Flags (3 = supports list)\n        output.Flush()\n\n        \/\/ Fetch the data until we get the initial options\n        data := make([]byte, 1024)\n        offset := 0\n        waiting_for := 16       \/\/ wait for at least the minimum payload size\n\n        packet_count := 0\n        for offset < waiting_for {\n            length, err := conn.Read(data[offset:])\n            if length > 0 {\n                packet_count += 1\n            }\n            offset += length\n            utils.ErrorCheck(err)\n            \/\/utils.LogData(\"Reading instruction\", offset, data)\n            if offset < waiting_for {\n                time.Sleep(5 * time.Millisecond)\n            }\n        }\n\n        fmt.Printf(\"%d packets processed to get %d bytes\", packet_count, offset)\n        utils.LogData(\"Received from client\", offset, data)\n        \/\/ Skip the first 8 characters (options)\n        command := binary.BigEndian.Uint32(data[12:])\n        payload_size := int(binary.BigEndian.Uint32(data[16:]))\n\n        fmt.Sprintf(\"command is: %d\\npayload_size is: %d\\n\", command, payload_size)\n        waiting_for += int(payload_size)\n        for offset < waiting_for {\n            length, err := conn.Read(data[offset:])\n            offset += length\n            utils.ErrorCheck(err)\n            utils.LogData(\"Reading instruction\", offset, data)\n            if offset < waiting_for {\n                time.Sleep(5 * time.Millisecond)\n            }\n        }\n        payload := make([]byte, payload_size)\n\n        if payload_size > 0{\n            copy(payload, data[20:])\n        }\n\n        utils.LogData(\"Payload is:\", payload_size, payload)\n        fmt.Printf(\"command is: %v\\n\", command)\n\n        \/\/ At this point, we have the command, payload size, and payload.\n        switch command {\n        case utils.NBD_COMMAND_LIST:\n            send_export_list(output)\n            conn.Close()\n            break\n        case utils.NBD_COMMAND_EXPORT_NAME:\n            go export_name(output, conn, payload_size, payload)\n            break\n        }\n    }\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Igor Dolzhikov. All rights reserved.\n\/\/ Use of this source code is governed by a license\n\/\/ that can be found in the LICENSE file.\n\npackage spawn\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com\/takama\/router\"\n)\n\nconst (\n\n\t\/\/ VERSION - current version of the service\n\tVERSION = \"0.1.7\"\n\n\t\/\/ DATE - revision date of the service\n\tDATE = \"2015-03-29T11:30:17Z\"\n\n\t\/\/ MaxSignals - maximum count of update signals\n\tMaxSignals = 1000\n\n\t\/\/ MaxJobs - maximum count of update jobs for every bundle\n\tMaxJobs = 100000\n\n\t\/\/ DefaultTimeout is a timeout for the worker's response\n\tDefaultTimeout time.Duration = 10\n\n\t\/\/ HTTP methods, which should be queued\n\tprotocolHTTP = \"http\"\n\tmethodPOST   = \"POST\"\n\tmethodPUT    = \"PUT\"\n\tmethodDELETE = \"DELETE\"\n\n\t\/\/ Job signals\n\tresponseSignal = iota\n\tnodeJobSignal\n)\n\n\/\/ simplest logger, which initialized during starts of the application\nvar (\n\tstdlog = log.New(os.Stdout, \"\", log.Ldate|log.Ltime)\n\terrlog = log.New(os.Stderr, \"\", log.Ldate|log.Ltime|log.Lshortfile)\n)\n\n\/\/ Server Record\ntype Server struct {\n\n\t\/\/ Server name\/description\n\tName string\n\n\t\/\/ Node Bundle contains the Node records\n\tNodes *NodeBundle\n\t\/\/ contains filtered or unexported fields\n\n\t\/\/ Embeded router\n\t*router.Router\n\n\t\/\/ Response signal channel\n\tresponse chan struct{}\n\n\t\/\/ responseTimeout is a timeout for worker's response\n\tresponseTimeout time.Duration\n\n\t\/\/ job signal channel\n\tjob chan int\n\n\t\/\/ quit signal channel\n\tquit chan struct{}\n\n\t\/\/ round robin mode\n\troundRobin bool\n\n\t\/\/ nodes will queried according to priority\n\tbyPriority bool\n\n\t\/\/ nodes health check\n\tcheck HealthCheck\n\n\t\/\/ Queue Bundle contains the queue records\n\tqueues *queueBundle\n}\n\n\/\/ HealthCheck contains parameters which used for checking node\ntype HealthCheck struct {\n\n\t\/\/ health check time of the node in seconds\n\tSeconds time.Duration `json:\"seconds\"`\n\n\t\/\/ url which will be checked\n\tURL string `json:\"url\"`\n\n\t\/\/ regexp pattern for extended check analyze\n\tPattern string `json:\"regexp\"`\n}\n\n\/\/ NewServer creates a new server which contains the nodes\/queues\nfunc NewServer(name string) (*Server, error) {\n\n\t\/\/ Init the router\n\tr := router.New()\n\tr.PanicHandler = panicHandler\n\tr.NotFound = notFound\n\tr.Logger = logger\n\tr.CustomHandler = baseHandler\n\n\t\/\/ Init the Server\n\tserver := &Server{\n\t\tName:            name,\n\t\tRouter:          r,\n\t\tresponseTimeout: DefaultTimeout,\n\t\tresponse:        make(chan struct{}),\n\t\tjob:             make(chan int, MaxSignals),\n\t\tquit:            make(chan struct{}),\n\t}\n\n\t\/\/ Create and init nodes bundle\n\tserver.Nodes = &NodeBundle{\n\t\tServer:  server,\n\t\trecords: make(map[string]map[uint64]Node),\n\t}\n\n\t\/\/ Create and init queues bundle\n\tserver.queues = &queueBundle{records: make(map[string]*queue)}\n\n\treturn server, nil\n}\n\n\/\/ Run the server, init the handlers, init the specified modes\n\/\/ If handler RequestHandler is not defined used default handler\n\/\/ with standard handling of the requests\/responses\nfunc (server *Server) Run(\n\thostPort, apiHostPort string,\n\thandler RequestHandler,\n\tnodes []Node,\n\troundRobin, byPriority bool,\n\tcheck HealthCheck,\n) (status string, err error) {\n\n\t\/\/ if used round-robin mode\n\tif roundRobin {\n\t\tstdlog.Println(server.Name, \"will used 'round-robin' mode\")\n\t\tserver.roundRobin = roundRobin\n\t}\n\n\t\/\/ if used by-priority mode\n\tif byPriority {\n\t\tstdlog.Println(\"Nodes will queried according to priority\")\n\t\tserver.byPriority = byPriority\n\t}\n\n\t\/\/ Init the Nodes update channel\n\tserver.Nodes.update = make(chan nodeJob, MaxJobs)\n\n\t\/\/ Starts the worker which manage server's jobs\n\tgo server.manage()\n\n\t\/\/ Init the Nodes settings\n\tif !server.Nodes.SetAll(nodes) {\n\t\tstatus = server.Name + \" is not loaded\"\n\t\terr = errors.New(\"The nodes settings in config have incorrect values\")\n\t\treturn\n\t}\n\n\t\/\/ Init a health check settings\n\tserver.check = check\n\n\t\/\/ The info handler returns a system status of the application\n\tserver.GET(\"\/info\", infoHandler)\n\n\t\/\/ Lists methods, which display how to use API\n\tserver.GET(\"\/list\", displayAllMethods)\n\tserver.GET(\"\/list\/nodes\", displayAllNodeMethods)\n\tserver.GET(\"\/list\/nodes\/get\", displayGetNodeMethods)\n\tserver.GET(\"\/list\/nodes\/set\", displaySetNodeMethods)\n\tserver.GET(\"\/list\/nodes\/delete\", displayDeleteNodeMethods)\n\n\t\/\/ Init API methods for the Nodes\n\tserver.GET(\"\/nodes\/:host\/:port\", server.Nodes.getRecord)\n\tserver.GET(\"\/nodes\/:host\", server.Nodes.getAllRecordsByHost)\n\tserver.GET(\"\/nodes\", server.Nodes.getAllRecords)\n\tserver.PUT(\"\/nodes\/:host\/:port\", server.Nodes.putRecord)\n\tserver.PUT(\"\/nodes\", server.Nodes.putAllRecords)\n\tserver.DELETE(\"\/nodes\/:host\/:port\", server.Nodes.deleteRecord)\n\tserver.DELETE(\"\/nodes\/:host\", server.Nodes.deleteAllRecordsByHost)\n\tserver.DELETE(\"\/nodes\", server.Nodes.deleteAllRecords)\n\n\tgo server.Listen(apiHostPort)\n\tgo func() {\n\t\tp := new(proxy)\n\t\tif handler != nil {\n\t\t\tp.handler = handler\n\t\t} else {\n\t\t\tp.handler = server.proxyHandler\n\t\t}\n\t\tif err := http.ListenAndServe(hostPort, p); err != nil {\n\t\t\terrlog.Fatal(err)\n\t\t}\n\t}()\n\n\tstatus = server.Name + \" loaded successfully\"\n\n\treturn\n}\n\n\/\/ Shutdown closes the server graceful\nfunc (server *Server) Shutdown() (status string, err error) {\n\n\t\/\/ Set timer to wait one minute\n\ttimeout := time.NewTimer(time.Second * 30)\n\n\t\/\/ a unwanted response sweeps if exist\n\tfor {\n\t\tselect {\n\t\tcase <-server.response:\n\t\t\tcontinue\n\t\tdefault:\n\t\t}\n\t\tbreak\n\t}\n\n\t\/\/ sends a 'quit' signal\n\tserver.quit <- struct{}{}\n\n\tstatus = server.Name + \" connections closed\"\n\tselect {\n\n\t\/\/ Exit by timeout if jobs did not done\n\tcase <-timeout.C:\n\t\terr = errors.New(\"timeout\")\n\t\treturn\n\t\/\/ Exit after all jobs done\n\tcase <-server.response:\n\t\treturn\n\t}\n}\n\n\/\/ Manage routine which manage all jobs\nfunc (server *Server) manage() {\n\tdefer func() {\n\t\tif recovery := recover(); recovery != nil {\n\t\t\terrlog.Println(\"Recovered in Manage routine\", recovery)\n\t\t\t\/\/ Recover routine\n\t\t\tgo server.manage()\n\t\t} else {\n\t\t\tstdlog.Println(\"Manage routine stoped\")\n\t\t\tserver.response <- struct{}{}\n\t\t}\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase job := <-server.job:\n\t\t\tserver.doJob(job)\n\t\t\tcontinue\n\t\tdefault:\n\t\t}\n\t\tselect {\n\t\tcase job := <-server.job:\n\t\t\tserver.doJob(job)\n\t\t\tcontinue\n\t\tcase <-server.quit:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ Do updates depended by the signal\nfunc (server *Server) doJob(signal int) {\n\tdefer func() {\n\t\tif recovery := recover(); recovery != nil {\n\t\t\terrlog.Println(\"Recovered in do job routine\", recovery)\n\t\t}\n\t}()\n\tswitch signal {\n\tcase responseSignal:\n\t\tserver.response <- struct{}{}\n\tcase nodeJobSignal:\n\t\tserver.Nodes.updateRecords()\n\t\tserver.Nodes.InitRing()\n\t}\n}\n\n\/\/ proxyHandler manages all requests\/responses\nfunc (server *Server) proxyHandler(request *http.Request) *http.Response {\n\n\t\/\/ Add \"X-Forwarded-For\" to repost remote host IP\n\tif remoteHost, _, err := net.SplitHostPort(request.RemoteAddr); err == nil {\n\t\trequest.Header.Add(\"X-Forwarded-For\", remoteHost)\n\t}\n\t\/\/ Use HTTP scheme\n\trequest.URL.Scheme = protocolHTTP\n\n\t\/\/ If requests should not be queued, get result immediately\n\tif request.Method != methodPOST &&\n\t\trequest.Method != methodPUT &&\n\t\trequest.Method != methodDELETE {\n\n\t\treturn server.processGET(request)\n\t}\n\n\treturn server.processUpdate(request)\n}\n\n\/\/ call 'GET' request to the node using defined mode\nfunc (server *Server) processGET(request *http.Request) *http.Response {\n\tif server.roundRobin {\n\n\t\t\/\/ Use round robin to get data from the host\n\t\tfor count := 0; count < server.Nodes.ring.Len(); count++ {\n\t\t\tif node, ok := server.Nodes.CurrentFromRing(); ok &&\n\t\t\t\tnode.Active && !node.Maintenance {\n\n\t\t\t\t\/\/ The host is active and is not in maintenance\n\t\t\t\trequest.URL.Host = fmt.Sprintf(\"%s:%d\", node.Host, node.Port)\n\n\t\t\t\t\/\/ Prepare next host\n\t\t\t\tserver.Nodes.TwistRing()\n\n\t\t\t\tif server.checkNode(request.URL.Host) {\n\t\t\t\t\tresponse, err := http.DefaultTransport.RoundTrip(request)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\/\/ If response is sucess, return\n\t\t\t\t\t\treturn response\n\t\t\t\t\t}\n\t\t\t\t\terrlog.Println(err)\n\t\t\t\t}\n\t\t\t} else {\n\n\t\t\t\t\/\/ Use next host if not active or maintenance mode\n\t\t\t\tserver.Nodes.TwistRing()\n\t\t\t}\n\t\t}\n\t} else {\n\n\t\t\/\/ If is not round robin mode, use first registered host\n\t\tif nodes, total := server.Nodes.GetAll(); total > 0 {\n\t\t\tif server.byPriority {\n\t\t\t\tsort.Sort(byPriority(nodes))\n\t\t\t}\n\t\t\tfor _, node := range nodes {\n\t\t\t\tif node.Active && !node.Maintenance {\n\n\t\t\t\t\t\/\/ The host is active and is not in maintenance\n\t\t\t\t\trequest.URL.Host = fmt.Sprintf(\"%s:%d\", node.Host, node.Port)\n\t\t\t\t\tif server.checkNode(request.URL.Host) {\n\t\t\t\t\t\tresponse, err := http.DefaultTransport.RoundTrip(request)\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t\/\/ If response is sucess, return\n\t\t\t\t\t\t\treturn response\n\t\t\t\t\t\t}\n\t\t\t\t\t\terrlog.Println(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstdlog.Println(\"Warning: no one of the nodes is active\")\n\n\treturn nil\n}\n\n\/\/ call 'PUT', 'POST', 'DELETE' request to the node\nfunc (server *Server) processUpdate(request *http.Request) *http.Response {\n\t\/\/ grab update request\n\tproxyRequestData, err := httputil.DumpRequest(request, true)\n\tif err != nil {\n\n\t\t\/\/ if unsuccessful, return nil response\n\t\terrlog.Println(err)\n\t\treturn nil\n\t}\n\tvar host string\n\tvar response *http.Response\n\tif nodes, total := server.Nodes.GetAll(); total > 0 {\n\t\tanswer := make(chan *http.Response, total)\n\t\tfor _, node := range nodes {\n\t\t\tif node.Active {\n\n\t\t\t\thost = fmt.Sprintf(\"%s:%d\", node.Host, node.Port)\n\n\t\t\t\t\/\/ create new queue job\n\t\t\t\tjob := &queueJob{\n\t\t\t\t\tquery:  make(chan []byte, 1),\n\t\t\t\t\tanswer: answer,\n\t\t\t\t}\n\t\t\t\tjob.query <- proxyRequestData\n\n\t\t\t\tqueue, _ := server.queues.check(host)\n\t\t\t\tqueue.jobs <- job\n\t\t\t\tqueue.task <- doJobTask\n\t\t\t}\n\t\t}\n\t\ttimeout := time.NewTimer(time.Second * server.responseTimeout)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase response = <-answer:\n\t\t\t\treturn response\n\t\t\tcase <-timeout.C:\n\t\t\t\treturn response\n\t\t\t}\n\t\t}\n\t}\n\treturn response\n}\n\n\/\/ worker receive a data from the queue and send it to the node\nfunc (server *Server) worker(q *queue) {\n\tdefer func() {\n\t\tif recovery := recover(); recovery != nil {\n\t\t\terrlog.Println(\"Recovered in worker routine\", recovery)\n\t\t\t\/\/ the worker recovers again\n\t\t\tgo server.worker(q)\n\t\t} else {\n\t\t\tq.response <- struct{}{}\n\t\t\tstdlog.Println(\"Worker closed for\", q.id)\n\t\t}\n\t}()\n\tstdlog.Println(\"Worker started for\", q.id)\n\tfor {\n\t\tselect {\n\t\tcase task := <-q.task:\n\t\t\tswitch task {\n\t\t\tcase doJobTask:\n\t\t\t\tserver.doUpdate(q)\n\t\t\t}\n\t\t\tcontinue\n\t\tdefault:\n\t\t}\n\t\tselect {\n\t\tcase task := <-q.task:\n\t\t\tswitch task {\n\t\t\tcase doJobTask:\n\t\t\t\tserver.doUpdate(q)\n\t\t\t}\n\t\t\tcontinue\n\t\tcase <-q.quit:\n\t\t\treturn\n\t\tcase <-q.ask:\n\t\t\tq.response <- struct{}{}\n\t\t}\n\t}\n}\n\nfunc (server *Server) doUpdate(q *queue) {\n\t\/\/ check the node\n\tfor {\n\t\tif server.checkNode(q.id) {\n\t\t\tbreak\n\t\t}\n\t\tstdlog.Println(\"Node\", q.id, \"does not ready for updates\")\n\t\tstdlog.Println(\"try again in\", server.check.Seconds, \"seconds\")\n\t\ttimeout := time.NewTimer(time.Second * server.check.Seconds)\n\t\tselect {\n\t\t\/\/  Repeat by timeout\n\t\tcase <-timeout.C:\n\t\t\tcontinue\n\t\tcase <-q.quit:\n\t\t\tq.task <- doJobTask\n\t\t\treturn\n\t\tcase <-q.ask:\n\t\t\tq.response <- struct{}{}\n\t\t}\n\t}\n\t\/\/ if the node is alive, post data\n\tjob := <-q.jobs\n\tdata := <-job.query\n\tif response, err := dispatchRequest(q.id, data); err != nil {\n\n\t\t\/\/ Job does not done\n\t\terrlog.Println(err)\n\n\t} else {\n\n\t\t\/\/ job done\n\t\tjob.answer <- response\n\t\tjob.done = true\n\t}\n}\n\n\/\/ check the node\nfunc (server *Server) checkNode(host string) bool {\n\tresponse, err := http.Get(protocolHTTP + \":\/\/\" + host + server.check.URL)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tdefer response.Body.Close()\n\t\/\/ if pattern does not exist, should be true\n\tif server.check.Pattern == \"\" {\n\t\treturn true\n\t}\n\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn false\n\t}\n\t\/\/ check of regexp pattern\n\tvalid := regexp.MustCompile(server.check.Pattern)\n\treturn valid.MatchString(string(data))\n}\n\n\/\/ Reproduce request to specified node and capture response\nfunc dispatchRequest(host string, data []byte) (*http.Response, error) {\n\treader := bufio.NewReader(bytes.NewBuffer(data))\n\trequest, err := http.ReadRequest(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trequest.Body = ioutil.NopCloser(reader)\n\trequest.URL.Scheme = protocolHTTP\n\trequest.URL.Host = host\n\n\tresponse, err := http.DefaultTransport.RoundTrip(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn response, nil\n}\n<commit_msg>Added error log write<commit_after>\/\/ Copyright 2015 Igor Dolzhikov. All rights reserved.\n\/\/ Use of this source code is governed by a license\n\/\/ that can be found in the LICENSE file.\n\npackage spawn\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com\/takama\/router\"\n)\n\nconst (\n\n\t\/\/ VERSION - current version of the service\n\tVERSION = \"0.1.7\"\n\n\t\/\/ DATE - revision date of the service\n\tDATE = \"2015-03-29T11:30:17Z\"\n\n\t\/\/ MaxSignals - maximum count of update signals\n\tMaxSignals = 1000\n\n\t\/\/ MaxJobs - maximum count of update jobs for every bundle\n\tMaxJobs = 100000\n\n\t\/\/ DefaultTimeout is a timeout for the worker's response\n\tDefaultTimeout time.Duration = 10\n\n\t\/\/ HTTP methods, which should be queued\n\tprotocolHTTP = \"http\"\n\tmethodPOST   = \"POST\"\n\tmethodPUT    = \"PUT\"\n\tmethodDELETE = \"DELETE\"\n\n\t\/\/ Job signals\n\tresponseSignal = iota\n\tnodeJobSignal\n)\n\n\/\/ simplest logger, which initialized during starts of the application\nvar (\n\tstdlog = log.New(os.Stdout, \"\", log.Ldate|log.Ltime)\n\terrlog = log.New(os.Stderr, \"\", log.Ldate|log.Ltime|log.Lshortfile)\n)\n\n\/\/ Server Record\ntype Server struct {\n\n\t\/\/ Server name\/description\n\tName string\n\n\t\/\/ Node Bundle contains the Node records\n\tNodes *NodeBundle\n\t\/\/ contains filtered or unexported fields\n\n\t\/\/ Embeded router\n\t*router.Router\n\n\t\/\/ Response signal channel\n\tresponse chan struct{}\n\n\t\/\/ responseTimeout is a timeout for worker's response\n\tresponseTimeout time.Duration\n\n\t\/\/ job signal channel\n\tjob chan int\n\n\t\/\/ quit signal channel\n\tquit chan struct{}\n\n\t\/\/ round robin mode\n\troundRobin bool\n\n\t\/\/ nodes will queried according to priority\n\tbyPriority bool\n\n\t\/\/ nodes health check\n\tcheck HealthCheck\n\n\t\/\/ Queue Bundle contains the queue records\n\tqueues *queueBundle\n}\n\n\/\/ HealthCheck contains parameters which used for checking node\ntype HealthCheck struct {\n\n\t\/\/ health check time of the node in seconds\n\tSeconds time.Duration `json:\"seconds\"`\n\n\t\/\/ url which will be checked\n\tURL string `json:\"url\"`\n\n\t\/\/ regexp pattern for extended check analyze\n\tPattern string `json:\"regexp\"`\n}\n\n\/\/ NewServer creates a new server which contains the nodes\/queues\nfunc NewServer(name string) (*Server, error) {\n\n\t\/\/ Init the router\n\tr := router.New()\n\tr.PanicHandler = panicHandler\n\tr.NotFound = notFound\n\tr.Logger = logger\n\tr.CustomHandler = baseHandler\n\n\t\/\/ Init the Server\n\tserver := &Server{\n\t\tName:            name,\n\t\tRouter:          r,\n\t\tresponseTimeout: DefaultTimeout,\n\t\tresponse:        make(chan struct{}),\n\t\tjob:             make(chan int, MaxSignals),\n\t\tquit:            make(chan struct{}),\n\t}\n\n\t\/\/ Create and init nodes bundle\n\tserver.Nodes = &NodeBundle{\n\t\tServer:  server,\n\t\trecords: make(map[string]map[uint64]Node),\n\t}\n\n\t\/\/ Create and init queues bundle\n\tserver.queues = &queueBundle{records: make(map[string]*queue)}\n\n\treturn server, nil\n}\n\n\/\/ Run the server, init the handlers, init the specified modes\n\/\/ If handler RequestHandler is not defined used default handler\n\/\/ with standard handling of the requests\/responses\nfunc (server *Server) Run(\n\thostPort, apiHostPort string,\n\thandler RequestHandler,\n\tnodes []Node,\n\troundRobin, byPriority bool,\n\tcheck HealthCheck,\n) (status string, err error) {\n\n\t\/\/ if used round-robin mode\n\tif roundRobin {\n\t\tstdlog.Println(server.Name, \"will used 'round-robin' mode\")\n\t\tserver.roundRobin = roundRobin\n\t}\n\n\t\/\/ if used by-priority mode\n\tif byPriority {\n\t\tstdlog.Println(\"Nodes will queried according to priority\")\n\t\tserver.byPriority = byPriority\n\t}\n\n\t\/\/ Init the Nodes update channel\n\tserver.Nodes.update = make(chan nodeJob, MaxJobs)\n\n\t\/\/ Starts the worker which manage server's jobs\n\tgo server.manage()\n\n\t\/\/ Init the Nodes settings\n\tif !server.Nodes.SetAll(nodes) {\n\t\tstatus = server.Name + \" is not loaded\"\n\t\terr = errors.New(\"The nodes settings in config have incorrect values\")\n\t\treturn\n\t}\n\n\t\/\/ Init a health check settings\n\tserver.check = check\n\n\t\/\/ The info handler returns a system status of the application\n\tserver.GET(\"\/info\", infoHandler)\n\n\t\/\/ Lists methods, which display how to use API\n\tserver.GET(\"\/list\", displayAllMethods)\n\tserver.GET(\"\/list\/nodes\", displayAllNodeMethods)\n\tserver.GET(\"\/list\/nodes\/get\", displayGetNodeMethods)\n\tserver.GET(\"\/list\/nodes\/set\", displaySetNodeMethods)\n\tserver.GET(\"\/list\/nodes\/delete\", displayDeleteNodeMethods)\n\n\t\/\/ Init API methods for the Nodes\n\tserver.GET(\"\/nodes\/:host\/:port\", server.Nodes.getRecord)\n\tserver.GET(\"\/nodes\/:host\", server.Nodes.getAllRecordsByHost)\n\tserver.GET(\"\/nodes\", server.Nodes.getAllRecords)\n\tserver.PUT(\"\/nodes\/:host\/:port\", server.Nodes.putRecord)\n\tserver.PUT(\"\/nodes\", server.Nodes.putAllRecords)\n\tserver.DELETE(\"\/nodes\/:host\/:port\", server.Nodes.deleteRecord)\n\tserver.DELETE(\"\/nodes\/:host\", server.Nodes.deleteAllRecordsByHost)\n\tserver.DELETE(\"\/nodes\", server.Nodes.deleteAllRecords)\n\n\tgo server.Listen(apiHostPort)\n\tgo func() {\n\t\tp := new(proxy)\n\t\tif handler != nil {\n\t\t\tp.handler = handler\n\t\t} else {\n\t\t\tp.handler = server.proxyHandler\n\t\t}\n\t\tif err := http.ListenAndServe(hostPort, p); err != nil {\n\t\t\terrlog.Fatal(err)\n\t\t}\n\t}()\n\n\tstatus = server.Name + \" loaded successfully\"\n\n\treturn\n}\n\n\/\/ Shutdown closes the server graceful\nfunc (server *Server) Shutdown() (status string, err error) {\n\n\t\/\/ Set timer to wait one minute\n\ttimeout := time.NewTimer(time.Second * 30)\n\n\t\/\/ a unwanted response sweeps if exist\n\tfor {\n\t\tselect {\n\t\tcase <-server.response:\n\t\t\tcontinue\n\t\tdefault:\n\t\t}\n\t\tbreak\n\t}\n\n\t\/\/ sends a 'quit' signal\n\tserver.quit <- struct{}{}\n\n\tstatus = server.Name + \" connections closed\"\n\tselect {\n\n\t\/\/ Exit by timeout if jobs did not done\n\tcase <-timeout.C:\n\t\terr = errors.New(\"timeout\")\n\t\treturn\n\t\/\/ Exit after all jobs done\n\tcase <-server.response:\n\t\treturn\n\t}\n}\n\n\/\/ Manage routine which manage all jobs\nfunc (server *Server) manage() {\n\tdefer func() {\n\t\tif recovery := recover(); recovery != nil {\n\t\t\terrlog.Println(\"Recovered in Manage routine\", recovery)\n\t\t\t\/\/ Recover routine\n\t\t\tgo server.manage()\n\t\t} else {\n\t\t\tstdlog.Println(\"Manage routine stoped\")\n\t\t\tserver.response <- struct{}{}\n\t\t}\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase job := <-server.job:\n\t\t\tserver.doJob(job)\n\t\t\tcontinue\n\t\tdefault:\n\t\t}\n\t\tselect {\n\t\tcase job := <-server.job:\n\t\t\tserver.doJob(job)\n\t\t\tcontinue\n\t\tcase <-server.quit:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ Do updates depended by the signal\nfunc (server *Server) doJob(signal int) {\n\tdefer func() {\n\t\tif recovery := recover(); recovery != nil {\n\t\t\terrlog.Println(\"Recovered in do job routine\", recovery)\n\t\t}\n\t}()\n\tswitch signal {\n\tcase responseSignal:\n\t\tserver.response <- struct{}{}\n\tcase nodeJobSignal:\n\t\tserver.Nodes.updateRecords()\n\t\tserver.Nodes.InitRing()\n\t}\n}\n\n\/\/ proxyHandler manages all requests\/responses\nfunc (server *Server) proxyHandler(request *http.Request) *http.Response {\n\n\t\/\/ Add \"X-Forwarded-For\" to repost remote host IP\n\tif remoteHost, _, err := net.SplitHostPort(request.RemoteAddr); err == nil {\n\t\trequest.Header.Add(\"X-Forwarded-For\", remoteHost)\n\t}\n\t\/\/ Use HTTP scheme\n\trequest.URL.Scheme = protocolHTTP\n\n\t\/\/ If requests should not be queued, get result immediately\n\tif request.Method != methodPOST &&\n\t\trequest.Method != methodPUT &&\n\t\trequest.Method != methodDELETE {\n\n\t\treturn server.processGET(request)\n\t}\n\n\treturn server.processUpdate(request)\n}\n\n\/\/ call 'GET' request to the node using defined mode\nfunc (server *Server) processGET(request *http.Request) *http.Response {\n\tif server.roundRobin {\n\n\t\t\/\/ Use round robin to get data from the host\n\t\tfor count := 0; count < server.Nodes.ring.Len(); count++ {\n\t\t\tif node, ok := server.Nodes.CurrentFromRing(); ok &&\n\t\t\t\tnode.Active && !node.Maintenance {\n\n\t\t\t\t\/\/ The host is active and is not in maintenance\n\t\t\t\trequest.URL.Host = fmt.Sprintf(\"%s:%d\", node.Host, node.Port)\n\n\t\t\t\t\/\/ Prepare next host\n\t\t\t\tserver.Nodes.TwistRing()\n\n\t\t\t\tif server.checkNode(request.URL.Host) {\n\t\t\t\t\tresponse, err := http.DefaultTransport.RoundTrip(request)\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\/\/ If response is sucess, return\n\t\t\t\t\t\treturn response\n\t\t\t\t\t}\n\t\t\t\t\terrlog.Println(err)\n\t\t\t\t}\n\t\t\t} else {\n\n\t\t\t\t\/\/ Use next host if not active or maintenance mode\n\t\t\t\tserver.Nodes.TwistRing()\n\t\t\t}\n\t\t}\n\t} else {\n\n\t\t\/\/ If is not round robin mode, use first registered host\n\t\tif nodes, total := server.Nodes.GetAll(); total > 0 {\n\t\t\tif server.byPriority {\n\t\t\t\tsort.Sort(byPriority(nodes))\n\t\t\t}\n\t\t\tfor _, node := range nodes {\n\t\t\t\tif node.Active && !node.Maintenance {\n\n\t\t\t\t\t\/\/ The host is active and is not in maintenance\n\t\t\t\t\trequest.URL.Host = fmt.Sprintf(\"%s:%d\", node.Host, node.Port)\n\t\t\t\t\tif server.checkNode(request.URL.Host) {\n\t\t\t\t\t\tresponse, err := http.DefaultTransport.RoundTrip(request)\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t\/\/ If response is sucess, return\n\t\t\t\t\t\t\treturn response\n\t\t\t\t\t\t}\n\t\t\t\t\t\terrlog.Println(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tstdlog.Println(\"Warning: no one of the nodes is active\")\n\n\treturn nil\n}\n\n\/\/ call 'PUT', 'POST', 'DELETE' request to the node\nfunc (server *Server) processUpdate(request *http.Request) *http.Response {\n\t\/\/ grab update request\n\tproxyRequestData, err := httputil.DumpRequest(request, true)\n\tif err != nil {\n\n\t\t\/\/ if unsuccessful, return nil response\n\t\terrlog.Println(err)\n\t\treturn nil\n\t}\n\tvar host string\n\tvar response *http.Response\n\tif nodes, total := server.Nodes.GetAll(); total > 0 {\n\t\tanswer := make(chan *http.Response, total)\n\t\tfor _, node := range nodes {\n\t\t\tif node.Active {\n\n\t\t\t\thost = fmt.Sprintf(\"%s:%d\", node.Host, node.Port)\n\n\t\t\t\t\/\/ create new queue job\n\t\t\t\tjob := &queueJob{\n\t\t\t\t\tquery:  make(chan []byte, 1),\n\t\t\t\t\tanswer: answer,\n\t\t\t\t}\n\t\t\t\tjob.query <- proxyRequestData\n\n\t\t\t\tqueue, _ := server.queues.check(host)\n\t\t\t\tqueue.jobs <- job\n\t\t\t\tqueue.task <- doJobTask\n\t\t\t}\n\t\t}\n\t\ttimeout := time.NewTimer(time.Second * server.responseTimeout)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase response = <-answer:\n\t\t\t\treturn response\n\t\t\tcase <-timeout.C:\n\t\t\t\treturn response\n\t\t\t}\n\t\t}\n\t}\n\treturn response\n}\n\n\/\/ worker receive a data from the queue and send it to the node\nfunc (server *Server) worker(q *queue) {\n\tdefer func() {\n\t\tif recovery := recover(); recovery != nil {\n\t\t\terrlog.Println(\"Recovered in worker routine\", recovery)\n\t\t\t\/\/ the worker recovers again\n\t\t\tgo server.worker(q)\n\t\t} else {\n\t\t\tq.response <- struct{}{}\n\t\t\tstdlog.Println(\"Worker closed for\", q.id)\n\t\t}\n\t}()\n\tstdlog.Println(\"Worker started for\", q.id)\n\tfor {\n\t\tselect {\n\t\tcase task := <-q.task:\n\t\t\tswitch task {\n\t\t\tcase doJobTask:\n\t\t\t\tserver.doUpdate(q)\n\t\t\t}\n\t\t\tcontinue\n\t\tdefault:\n\t\t}\n\t\tselect {\n\t\tcase task := <-q.task:\n\t\t\tswitch task {\n\t\t\tcase doJobTask:\n\t\t\t\tserver.doUpdate(q)\n\t\t\t}\n\t\t\tcontinue\n\t\tcase <-q.quit:\n\t\t\treturn\n\t\tcase <-q.ask:\n\t\t\tq.response <- struct{}{}\n\t\t}\n\t}\n}\n\nfunc (server *Server) doUpdate(q *queue) {\n\t\/\/ check the node\n\tfor {\n\t\tif server.checkNode(q.id) {\n\t\t\tbreak\n\t\t}\n\t\tstdlog.Println(\"Node\", q.id, \"does not ready for updates\")\n\t\tstdlog.Println(\"try again in\", server.check.Seconds, \"seconds\")\n\t\ttimeout := time.NewTimer(time.Second * server.check.Seconds)\n\t\tselect {\n\t\t\/\/  Repeat by timeout\n\t\tcase <-timeout.C:\n\t\t\tcontinue\n\t\tcase <-q.quit:\n\t\t\tq.task <- doJobTask\n\t\t\treturn\n\t\tcase <-q.ask:\n\t\t\tq.response <- struct{}{}\n\t\t}\n\t}\n\t\/\/ if the node is alive, post data\n\tjob := <-q.jobs\n\tdata := <-job.query\n\tif response, err := dispatchRequest(q.id, data); err != nil {\n\n\t\t\/\/ Job does not done\n\t\terrlog.Println(err)\n\n\t} else {\n\n\t\t\/\/ job done\n\t\tjob.answer <- response\n\t\tjob.done = true\n\t}\n}\n\n\/\/ check the node\nfunc (server *Server) checkNode(host string) bool {\n\tresponse, err := http.Get(protocolHTTP + \":\/\/\" + host + server.check.URL)\n\tif err != nil {\n\t\tstdlog.Println(host, err)\n\t\treturn false\n\t}\n\n\tdefer response.Body.Close()\n\t\/\/ if pattern does not exist, should be true\n\tif server.check.Pattern == \"\" {\n\t\treturn true\n\t}\n\n\tdata, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tstdlog.Println(host, err)\n\t\treturn false\n\t}\n\t\/\/ check of regexp pattern\n\tvalid := regexp.MustCompile(server.check.Pattern)\n\treturn valid.MatchString(string(data))\n}\n\n\/\/ Reproduce request to specified node and capture response\nfunc dispatchRequest(host string, data []byte) (*http.Response, error) {\n\treader := bufio.NewReader(bytes.NewBuffer(data))\n\trequest, err := http.ReadRequest(reader)\n\tif err != nil {\n\t\tstdlog.Println(host, err)\n\t\treturn nil, err\n\t}\n\trequest.Body = ioutil.NopCloser(reader)\n\trequest.URL.Scheme = protocolHTTP\n\trequest.URL.Host = host\n\n\tresponse, err := http.DefaultTransport.RoundTrip(request)\n\tif err != nil {\n\t\tstdlog.Println(host, err)\n\t\treturn nil, err\n\t}\n\treturn response, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Pilosa Corp.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage pilosa\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/CAFxX\/gcnotifier\"\n\t\"github.com\/gogo\/protobuf\/proto\"\n\t\"github.com\/pilosa\/pilosa\/internal\"\n)\n\n\/\/ Default server settings.\nconst (\n\tDefaultAntiEntropyInterval = 10 * time.Minute\n\tDefaultPollingInterval     = 60 * time.Second\n)\n\n\/\/ Server represents a holder wrapped by a running HTTP server.\ntype Server struct {\n\tln net.Listener\n\n\t\/\/ Close management.\n\twg      sync.WaitGroup\n\tclosing chan struct{}\n\n\t\/\/ Data storage and HTTP interface.\n\tHolder            *Holder\n\tHandler           *Handler\n\tBroadcaster       Broadcaster\n\tBroadcastReceiver BroadcastReceiver\n\n\t\/\/ Cluster configuration.\n\t\/\/ Host is replaced with actual host after opening if port is \":0\".\n\tHost    string\n\tCluster *Cluster\n\n\t\/\/ Background monitoring intervals.\n\tAntiEntropyInterval time.Duration\n\tPollingInterval     time.Duration\n\tMetricInterval      time.Duration\n\n\t\/\/ Misc options.\n\tMaxWritesPerRequest int\n\n\tLogOutput io.Writer\n}\n\n\/\/ NewServer returns a new instance of Server.\nfunc NewServer() *Server {\n\ts := &Server{\n\t\tclosing: make(chan struct{}),\n\n\t\tHolder:            NewHolder(),\n\t\tHandler:           NewHandler(),\n\t\tBroadcaster:       NopBroadcaster,\n\t\tBroadcastReceiver: NopBroadcastReceiver,\n\n\t\tAntiEntropyInterval: DefaultAntiEntropyInterval,\n\t\tPollingInterval:     DefaultPollingInterval,\n\t\tMetricInterval:      0,\n\n\t\tLogOutput: os.Stderr,\n\t}\n\n\ts.Handler.Holder = s.Holder\n\n\treturn s\n}\n\n\/\/ Open opens and initializes the server.\nfunc (s *Server) Open() error {\n\t\/\/ Require a port in the hostname.\n\thost, port, err := net.SplitHostPort(s.Host)\n\tif err != nil {\n\t\treturn err\n\t} else if port == \"\" {\n\t\tport = DefaultPort\n\t}\n\n\t\/\/ Open HTTP listener to determine port (if specified as :0).\n\tln, err := net.Listen(\"tcp\", \":\"+port)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"net.Listen: %v\", err)\n\t}\n\ts.ln = ln\n\n\t\/\/ Determine hostname based on listening port.\n\ts.Host = net.JoinHostPort(host, strconv.Itoa(s.ln.Addr().(*net.TCPAddr).Port))\n\n\t\/\/ Create local node if no cluster is specified.\n\tif len(s.Cluster.Nodes) == 0 {\n\t\ts.Cluster.Nodes = []*Node{{Host: s.Host}}\n\t}\n\n\tfor i, n := range s.Cluster.Nodes {\n\t\tif s.Cluster.NodeByHost(n.Host) != nil {\n\t\t\ts.Holder.Stats = s.Holder.Stats.WithTags(fmt.Sprintf(\"NodeID:%d\", i))\n\t\t}\n\t}\n\n\t\/\/ Open holder.\n\tif err := s.Holder.Open(); err != nil {\n\t\treturn fmt.Errorf(\"opening Holder: %v\", err)\n\t}\n\n\tif err := s.BroadcastReceiver.Start(s); err != nil {\n\t\treturn fmt.Errorf(\"starting BroadcastReceiver: %v\", err)\n\t}\n\n\t\/\/ Open NodeSet communication\n\tif err := s.Cluster.NodeSet.Open(); err != nil {\n\t\treturn fmt.Errorf(\"opening NodeSet: %v\", err)\n\t}\n\n\t\/\/ Create executor for executing queries.\n\te := NewExecutor()\n\te.Holder = s.Holder\n\te.Host = s.Host\n\te.Cluster = s.Cluster\n\te.MaxWritesPerRequest = s.MaxWritesPerRequest\n\n\t\/\/ Initialize HTTP handler.\n\ts.Handler.Broadcaster = s.Broadcaster\n\ts.Handler.StatusHandler = s\n\ts.Handler.Host = s.Host\n\ts.Handler.Cluster = s.Cluster\n\ts.Handler.Executor = e\n\ts.Handler.LogOutput = s.LogOutput\n\n\t\/\/ Initialize Holder.\n\ts.Holder.Broadcaster = s.Broadcaster\n\ts.Holder.LogOutput = s.LogOutput\n\n\t\/\/ Serve HTTP.\n\tgo func() { http.Serve(ln, s.Handler) }()\n\n\t\/\/ Start background monitoring.\n\ts.wg.Add(3)\n\tgo func() { defer s.wg.Done(); s.monitorAntiEntropy() }()\n\tgo func() { defer s.wg.Done(); s.monitorMaxSlices() }()\n\tgo func() { defer s.wg.Done(); s.monitorRuntime() }()\n\n\treturn nil\n}\n\n\/\/ Close closes the server and waits for it to shutdown.\nfunc (s *Server) Close() error {\n\t\/\/ Notify goroutines to stop.\n\tclose(s.closing)\n\ts.wg.Wait()\n\n\tif s.ln != nil {\n\t\ts.ln.Close()\n\t}\n\tif s.Holder != nil {\n\t\ts.Holder.Close()\n\t}\n\n\treturn nil\n}\n\n\/\/ Addr returns the address of the listener.\nfunc (s *Server) Addr() net.Addr {\n\tif s.ln == nil {\n\t\treturn nil\n\t}\n\treturn s.ln.Addr()\n}\n\nfunc (s *Server) logger() *log.Logger { return log.New(s.LogOutput, \"\", log.LstdFlags) }\n\nfunc (s *Server) monitorAntiEntropy() {\n\tt := time.Now()\n\tticker := time.NewTicker(s.AntiEntropyInterval)\n\tdefer ticker.Stop()\n\n\ts.logger().Printf(\"holder sync monitor initializing (%s interval)\", s.AntiEntropyInterval)\n\n\tfor {\n\t\t\/\/ Wait for tick or a close.\n\t\tselect {\n\t\tcase <-s.closing:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\ts.Holder.Stats.Count(\"AntiEntropy\", 1, 1.0)\n\t\t}\n\n\t\ts.logger().Printf(\"holder sync beginning\")\n\n\t\t\/\/ Initialize syncer with local holder and remote client.\n\t\tvar syncer HolderSyncer\n\t\tsyncer.Holder = s.Holder\n\t\tsyncer.Host = s.Host\n\t\tsyncer.Cluster = s.Cluster\n\t\tsyncer.Closing = s.closing\n\n\t\t\/\/ Sync holders.\n\t\tif err := syncer.SyncHolder(); err != nil {\n\t\t\ts.logger().Printf(\"holder sync error: err=%s\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Record successful sync in log.\n\t\ts.logger().Printf(\"holder sync complete\")\n\t}\n\tdif := time.Since(t)\n\ts.Holder.Stats.Histogram(\"AntiEntropyDuration\", float64(dif), 1.0)\n}\n\n\/\/ monitorMaxSlices periodically pulls the highest slice from each node in the cluster.\nfunc (s *Server) monitorMaxSlices() {\n\t\/\/ Ignore if only one node in the cluster.\n\tif len(s.Cluster.Nodes) <= 1 {\n\t\treturn\n\t}\n\n\tticker := time.NewTicker(s.PollingInterval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-s.closing:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t}\n\n\t\toldmaxslices := s.Holder.MaxSlices()\n\t\tfor _, node := range s.Cluster.Nodes {\n\t\t\tif s.Host != node.Host {\n\t\t\t\tmaxSlices, _ := checkMaxSlices(node.Host)\n\t\t\t\tfor index, newmax := range maxSlices {\n\t\t\t\t\t\/\/ if we don't know about an index locally, log an error because\n\t\t\t\t\t\/\/ indexes should be created and synced prior to slice creation\n\t\t\t\t\tif localIndex := s.Holder.Index(index); localIndex != nil {\n\t\t\t\t\t\tif newmax > oldmaxslices[index] {\n\t\t\t\t\t\t\toldmaxslices[index] = newmax\n\t\t\t\t\t\t\tlocalIndex.SetRemoteMaxSlice(newmax)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ts.logger().Printf(\"Local Index not found: %s\", index)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ ReceiveMessage represents an implementation of BroadcastHandler.\nfunc (s *Server) ReceiveMessage(pb proto.Message) error {\n\tswitch obj := pb.(type) {\n\tcase *internal.CreateSliceMessage:\n\t\tidx := s.Holder.Index(obj.Index)\n\t\tif idx == nil {\n\t\t\treturn fmt.Errorf(\"Local Index not found: %s\", obj.Index)\n\t\t}\n\t\tif obj.IsInverse {\n\t\t\tidx.SetRemoteMaxInverseSlice(obj.Slice)\n\t\t} else {\n\t\t\tidx.SetRemoteMaxSlice(obj.Slice)\n\t\t}\n\tcase *internal.CreateIndexMessage:\n\t\topt := IndexOptions{\n\t\t\tColumnLabel: obj.Meta.ColumnLabel,\n\t\t\tTimeQuantum: TimeQuantum(obj.Meta.TimeQuantum),\n\t\t}\n\t\t_, err := s.Holder.CreateIndex(obj.Index, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase *internal.DeleteIndexMessage:\n\t\tif err := s.Holder.DeleteIndex(obj.Index); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase *internal.CreateFrameMessage:\n\t\tindex := s.Holder.Index(obj.Index)\n\t\topt := FrameOptions{\n\t\t\tRowLabel:       obj.Meta.RowLabel,\n\t\t\tInverseEnabled: obj.Meta.InverseEnabled,\n\t\t\tCacheType:      obj.Meta.CacheType,\n\t\t\tCacheSize:      obj.Meta.CacheSize,\n\t\t\tTimeQuantum:    TimeQuantum(obj.Meta.TimeQuantum),\n\t\t}\n\t\t_, err := index.CreateFrame(obj.Frame, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase *internal.DeleteFrameMessage:\n\t\tindex := s.Holder.Index(obj.Index)\n\t\tif err := index.DeleteFrame(obj.Frame); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ LocalStatus returns the state of the local node as well as the\n\/\/ holder (indexes\/frames) according to the local node.\n\/\/ In a gossip implementation, memberlist.Delegate.LocalState() uses this.\n\/\/ Server implements StatusHandler.\nfunc (s *Server) LocalStatus() (proto.Message, error) {\n\tif s.Holder == nil {\n\t\treturn nil, errors.New(\"Server.Holder is nil\")\n\t}\n\n\tns := internal.NodeStatus{\n\t\tHost:    s.Host,\n\t\tState:   NodeStateUp,\n\t\tIndexes: EncodeIndexes(s.Holder.Indexes()),\n\t}\n\n\t\/\/ Append Slice list per this Node's indexes\n\tfor _, index := range ns.Indexes {\n\t\tindex.Slices = s.Cluster.OwnsSlices(index.Name, index.MaxSlice, s.Host)\n\t}\n\n\treturn &ns, nil\n}\n\n\/\/ ClusterStatus returns the NodeState for all nodes in the cluster.\nfunc (s *Server) ClusterStatus() (proto.Message, error) {\n\t\/\/ Update local Node.state.\n\tns, err := s.LocalStatus()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnode := s.Cluster.NodeByHost(s.Host)\n\tnode.SetStatus(ns.(*internal.NodeStatus))\n\n\t\/\/ Update NodeState for all nodes.\n\tfor host, nodeState := range s.Cluster.NodeStates() {\n\t\t\/\/ In a default configuration (or single-node) where a StaticNodeSet is used\n\t\t\/\/ then all nodes are marked as DOWN. At the very least, we should consider\n\t\t\/\/ the local node as UP.\n\t\t\/\/ TODO: we should be able to remove this check if\/when cluster.Nodes and\n\t\t\/\/ cluster.NodeSet are unified.\n\t\tif host == s.Host {\n\t\t\tnodeState = NodeStateUp\n\t\t}\n\t\tnode := s.Cluster.NodeByHost(host)\n\t\tnode.SetState(nodeState)\n\t}\n\n\treturn s.Cluster.Status(), nil\n}\n\n\/\/ HandleRemoteStatus receives incoming NodeState from remote nodes.\nfunc (s *Server) HandleRemoteStatus(pb proto.Message) error {\n\treturn s.mergeRemoteStatus(pb.(*internal.NodeStatus))\n}\n\nfunc (s *Server) mergeRemoteStatus(ns *internal.NodeStatus) error {\n\t\/\/ Update Node.state.\n\tnode := s.Cluster.NodeByHost(ns.Host)\n\tnode.SetStatus(ns)\n\n\t\/\/ Create indexes that don't exist.\n\tfor _, index := range ns.Indexes {\n\t\topt := IndexOptions{\n\t\t\tColumnLabel: index.Meta.ColumnLabel,\n\t\t\tTimeQuantum: TimeQuantum(index.Meta.TimeQuantum),\n\t\t}\n\t\tidx, err := s.Holder.CreateIndexIfNotExists(index.Name, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Create frames that don't exist.\n\t\tfor _, f := range index.Frames {\n\t\t\topt := FrameOptions{\n\t\t\t\tRowLabel:    f.Meta.RowLabel,\n\t\t\t\tTimeQuantum: TimeQuantum(f.Meta.TimeQuantum),\n\t\t\t\tCacheSize:   f.Meta.CacheSize,\n\t\t\t}\n\t\t\t_, err := idx.CreateFrameIfNotExists(f.Name, opt)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc checkMaxSlices(hostport string) (map[string]uint64, error) {\n\t\/\/ Create HTTP request.\n\treq, err := http.NewRequest(\"GET\", (&url.URL{\n\t\tScheme: \"http\",\n\t\tHost:   hostport,\n\t\tPath:   \"\/slices\/max\",\n\t}).String(), nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Require protobuf encoding.\n\treq.Header.Set(\"Accept\", \"application\/x-protobuf\")\n\treq.Header.Set(\"Content-Type\", \"application\/x-protobuf\")\n\treq.Header.Set(\"User-Agent\", \"pilosa\/\"+Version)\n\n\t\/\/ Send request to remote node.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\t\/\/ Read response into buffer.\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Check status code.\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"invalid status checkMaxSlices: code=%d, err=%s, req=%v\", resp.StatusCode, body, req)\n\t}\n\n\t\/\/ Decode response object.\n\tpb := internal.MaxSlicesResponse{}\n\n\tif err = proto.Unmarshal(body, &pb); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn pb.MaxSlices, nil\n}\n\n\/\/ monitorRuntime periodically polls the Go runtime metrics.\nfunc (s *Server) monitorRuntime() {\n\t\/\/ Disable metrics when poll interval is zero\n\tif s.MetricInterval <= 0 {\n\t\treturn\n\t}\n\n\tticker := time.NewTicker(s.MetricInterval)\n\tdefer ticker.Stop()\n\n\tgcn := gcnotifier.New()\n\tdefer gcn.Close()\n\n\ts.logger().Printf(\"runtime stats initializing (%s interval)\", s.MetricInterval)\n\n\tfor {\n\t\t\/\/ Wait for tick or a close.\n\t\tselect {\n\t\tcase <-s.closing:\n\t\t\treturn\n\t\tcase <-gcn.AfterGC():\n\t\t\t\/\/ GC just ran\n\t\t\ts.Holder.Stats.Count(\"garbage_collection\", 1, 1.0)\n\t\tcase <-ticker.C:\n\t\t}\n\n\t\t\/\/ Record the number of go routines\n\t\ts.Holder.Stats.Gauge(\"goroutines\", float64(runtime.NumGoroutine()), 1.0)\n\t}\n}\n\n\/\/ StatusHandler specifies two methods which an object must implement to share\n\/\/ state in the cluster. These are used by the GossipNodeSet to implement the\n\/\/ LocalState and MergeRemoteState methods of memberlist.Delegate\ntype StatusHandler interface {\n\tLocalStatus() (proto.Message, error)\n\tClusterStatus() (proto.Message, error)\n\tHandleRemoteStatus(proto.Message) error\n}\n<commit_msg>return an error if the BroadcastHandler CreateFrameMessage encounters an Index that does not exist<commit_after>\/\/ Copyright 2017 Pilosa Corp.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage pilosa\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/CAFxX\/gcnotifier\"\n\t\"github.com\/gogo\/protobuf\/proto\"\n\t\"github.com\/pilosa\/pilosa\/internal\"\n)\n\n\/\/ Default server settings.\nconst (\n\tDefaultAntiEntropyInterval = 10 * time.Minute\n\tDefaultPollingInterval     = 60 * time.Second\n)\n\n\/\/ Server represents a holder wrapped by a running HTTP server.\ntype Server struct {\n\tln net.Listener\n\n\t\/\/ Close management.\n\twg      sync.WaitGroup\n\tclosing chan struct{}\n\n\t\/\/ Data storage and HTTP interface.\n\tHolder            *Holder\n\tHandler           *Handler\n\tBroadcaster       Broadcaster\n\tBroadcastReceiver BroadcastReceiver\n\n\t\/\/ Cluster configuration.\n\t\/\/ Host is replaced with actual host after opening if port is \":0\".\n\tHost    string\n\tCluster *Cluster\n\n\t\/\/ Background monitoring intervals.\n\tAntiEntropyInterval time.Duration\n\tPollingInterval     time.Duration\n\tMetricInterval      time.Duration\n\n\t\/\/ Misc options.\n\tMaxWritesPerRequest int\n\n\tLogOutput io.Writer\n}\n\n\/\/ NewServer returns a new instance of Server.\nfunc NewServer() *Server {\n\ts := &Server{\n\t\tclosing: make(chan struct{}),\n\n\t\tHolder:            NewHolder(),\n\t\tHandler:           NewHandler(),\n\t\tBroadcaster:       NopBroadcaster,\n\t\tBroadcastReceiver: NopBroadcastReceiver,\n\n\t\tAntiEntropyInterval: DefaultAntiEntropyInterval,\n\t\tPollingInterval:     DefaultPollingInterval,\n\t\tMetricInterval:      0,\n\n\t\tLogOutput: os.Stderr,\n\t}\n\n\ts.Handler.Holder = s.Holder\n\n\treturn s\n}\n\n\/\/ Open opens and initializes the server.\nfunc (s *Server) Open() error {\n\t\/\/ Require a port in the hostname.\n\thost, port, err := net.SplitHostPort(s.Host)\n\tif err != nil {\n\t\treturn err\n\t} else if port == \"\" {\n\t\tport = DefaultPort\n\t}\n\n\t\/\/ Open HTTP listener to determine port (if specified as :0).\n\tln, err := net.Listen(\"tcp\", \":\"+port)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"net.Listen: %v\", err)\n\t}\n\ts.ln = ln\n\n\t\/\/ Determine hostname based on listening port.\n\ts.Host = net.JoinHostPort(host, strconv.Itoa(s.ln.Addr().(*net.TCPAddr).Port))\n\n\t\/\/ Create local node if no cluster is specified.\n\tif len(s.Cluster.Nodes) == 0 {\n\t\ts.Cluster.Nodes = []*Node{{Host: s.Host}}\n\t}\n\n\tfor i, n := range s.Cluster.Nodes {\n\t\tif s.Cluster.NodeByHost(n.Host) != nil {\n\t\t\ts.Holder.Stats = s.Holder.Stats.WithTags(fmt.Sprintf(\"NodeID:%d\", i))\n\t\t}\n\t}\n\n\t\/\/ Open holder.\n\tif err := s.Holder.Open(); err != nil {\n\t\treturn fmt.Errorf(\"opening Holder: %v\", err)\n\t}\n\n\tif err := s.BroadcastReceiver.Start(s); err != nil {\n\t\treturn fmt.Errorf(\"starting BroadcastReceiver: %v\", err)\n\t}\n\n\t\/\/ Open NodeSet communication\n\tif err := s.Cluster.NodeSet.Open(); err != nil {\n\t\treturn fmt.Errorf(\"opening NodeSet: %v\", err)\n\t}\n\n\t\/\/ Create executor for executing queries.\n\te := NewExecutor()\n\te.Holder = s.Holder\n\te.Host = s.Host\n\te.Cluster = s.Cluster\n\te.MaxWritesPerRequest = s.MaxWritesPerRequest\n\n\t\/\/ Initialize HTTP handler.\n\ts.Handler.Broadcaster = s.Broadcaster\n\ts.Handler.StatusHandler = s\n\ts.Handler.Host = s.Host\n\ts.Handler.Cluster = s.Cluster\n\ts.Handler.Executor = e\n\ts.Handler.LogOutput = s.LogOutput\n\n\t\/\/ Initialize Holder.\n\ts.Holder.Broadcaster = s.Broadcaster\n\ts.Holder.LogOutput = s.LogOutput\n\n\t\/\/ Serve HTTP.\n\tgo func() { http.Serve(ln, s.Handler) }()\n\n\t\/\/ Start background monitoring.\n\ts.wg.Add(3)\n\tgo func() { defer s.wg.Done(); s.monitorAntiEntropy() }()\n\tgo func() { defer s.wg.Done(); s.monitorMaxSlices() }()\n\tgo func() { defer s.wg.Done(); s.monitorRuntime() }()\n\n\treturn nil\n}\n\n\/\/ Close closes the server and waits for it to shutdown.\nfunc (s *Server) Close() error {\n\t\/\/ Notify goroutines to stop.\n\tclose(s.closing)\n\ts.wg.Wait()\n\n\tif s.ln != nil {\n\t\ts.ln.Close()\n\t}\n\tif s.Holder != nil {\n\t\ts.Holder.Close()\n\t}\n\n\treturn nil\n}\n\n\/\/ Addr returns the address of the listener.\nfunc (s *Server) Addr() net.Addr {\n\tif s.ln == nil {\n\t\treturn nil\n\t}\n\treturn s.ln.Addr()\n}\n\nfunc (s *Server) logger() *log.Logger { return log.New(s.LogOutput, \"\", log.LstdFlags) }\n\nfunc (s *Server) monitorAntiEntropy() {\n\tt := time.Now()\n\tticker := time.NewTicker(s.AntiEntropyInterval)\n\tdefer ticker.Stop()\n\n\ts.logger().Printf(\"holder sync monitor initializing (%s interval)\", s.AntiEntropyInterval)\n\n\tfor {\n\t\t\/\/ Wait for tick or a close.\n\t\tselect {\n\t\tcase <-s.closing:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\ts.Holder.Stats.Count(\"AntiEntropy\", 1, 1.0)\n\t\t}\n\n\t\ts.logger().Printf(\"holder sync beginning\")\n\n\t\t\/\/ Initialize syncer with local holder and remote client.\n\t\tvar syncer HolderSyncer\n\t\tsyncer.Holder = s.Holder\n\t\tsyncer.Host = s.Host\n\t\tsyncer.Cluster = s.Cluster\n\t\tsyncer.Closing = s.closing\n\n\t\t\/\/ Sync holders.\n\t\tif err := syncer.SyncHolder(); err != nil {\n\t\t\ts.logger().Printf(\"holder sync error: err=%s\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Record successful sync in log.\n\t\ts.logger().Printf(\"holder sync complete\")\n\t}\n\tdif := time.Since(t)\n\ts.Holder.Stats.Histogram(\"AntiEntropyDuration\", float64(dif), 1.0)\n}\n\n\/\/ monitorMaxSlices periodically pulls the highest slice from each node in the cluster.\nfunc (s *Server) monitorMaxSlices() {\n\t\/\/ Ignore if only one node in the cluster.\n\tif len(s.Cluster.Nodes) <= 1 {\n\t\treturn\n\t}\n\n\tticker := time.NewTicker(s.PollingInterval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-s.closing:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t}\n\n\t\toldmaxslices := s.Holder.MaxSlices()\n\t\tfor _, node := range s.Cluster.Nodes {\n\t\t\tif s.Host != node.Host {\n\t\t\t\tmaxSlices, _ := checkMaxSlices(node.Host)\n\t\t\t\tfor index, newmax := range maxSlices {\n\t\t\t\t\t\/\/ if we don't know about an index locally, log an error because\n\t\t\t\t\t\/\/ indexes should be created and synced prior to slice creation\n\t\t\t\t\tif localIndex := s.Holder.Index(index); localIndex != nil {\n\t\t\t\t\t\tif newmax > oldmaxslices[index] {\n\t\t\t\t\t\t\toldmaxslices[index] = newmax\n\t\t\t\t\t\t\tlocalIndex.SetRemoteMaxSlice(newmax)\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\ts.logger().Printf(\"Local Index not found: %s\", index)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ ReceiveMessage represents an implementation of BroadcastHandler.\nfunc (s *Server) ReceiveMessage(pb proto.Message) error {\n\tswitch obj := pb.(type) {\n\tcase *internal.CreateSliceMessage:\n\t\tidx := s.Holder.Index(obj.Index)\n\t\tif idx == nil {\n\t\t\treturn fmt.Errorf(\"Local Index not found: %s\", obj.Index)\n\t\t}\n\t\tif obj.IsInverse {\n\t\t\tidx.SetRemoteMaxInverseSlice(obj.Slice)\n\t\t} else {\n\t\t\tidx.SetRemoteMaxSlice(obj.Slice)\n\t\t}\n\tcase *internal.CreateIndexMessage:\n\t\topt := IndexOptions{\n\t\t\tColumnLabel: obj.Meta.ColumnLabel,\n\t\t\tTimeQuantum: TimeQuantum(obj.Meta.TimeQuantum),\n\t\t}\n\t\t_, err := s.Holder.CreateIndex(obj.Index, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase *internal.DeleteIndexMessage:\n\t\tif err := s.Holder.DeleteIndex(obj.Index); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase *internal.CreateFrameMessage:\n\t\tidx := s.Holder.Index(obj.Index)\n\t\tif idx == nil {\n\t\t\treturn fmt.Errorf(\"Local Index not found: %s\", obj.Index)\n\t\t}\n\t\topt := FrameOptions{\n\t\t\tRowLabel:       obj.Meta.RowLabel,\n\t\t\tInverseEnabled: obj.Meta.InverseEnabled,\n\t\t\tCacheType:      obj.Meta.CacheType,\n\t\t\tCacheSize:      obj.Meta.CacheSize,\n\t\t\tTimeQuantum:    TimeQuantum(obj.Meta.TimeQuantum),\n\t\t}\n\t\t_, err := idx.CreateFrame(obj.Frame, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase *internal.DeleteFrameMessage:\n\t\tidx := s.Holder.Index(obj.Index)\n\t\tif err := idx.DeleteFrame(obj.Frame); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ LocalStatus returns the state of the local node as well as the\n\/\/ holder (indexes\/frames) according to the local node.\n\/\/ In a gossip implementation, memberlist.Delegate.LocalState() uses this.\n\/\/ Server implements StatusHandler.\nfunc (s *Server) LocalStatus() (proto.Message, error) {\n\tif s.Holder == nil {\n\t\treturn nil, errors.New(\"Server.Holder is nil\")\n\t}\n\n\tns := internal.NodeStatus{\n\t\tHost:    s.Host,\n\t\tState:   NodeStateUp,\n\t\tIndexes: EncodeIndexes(s.Holder.Indexes()),\n\t}\n\n\t\/\/ Append Slice list per this Node's indexes\n\tfor _, index := range ns.Indexes {\n\t\tindex.Slices = s.Cluster.OwnsSlices(index.Name, index.MaxSlice, s.Host)\n\t}\n\n\treturn &ns, nil\n}\n\n\/\/ ClusterStatus returns the NodeState for all nodes in the cluster.\nfunc (s *Server) ClusterStatus() (proto.Message, error) {\n\t\/\/ Update local Node.state.\n\tns, err := s.LocalStatus()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnode := s.Cluster.NodeByHost(s.Host)\n\tnode.SetStatus(ns.(*internal.NodeStatus))\n\n\t\/\/ Update NodeState for all nodes.\n\tfor host, nodeState := range s.Cluster.NodeStates() {\n\t\t\/\/ In a default configuration (or single-node) where a StaticNodeSet is used\n\t\t\/\/ then all nodes are marked as DOWN. At the very least, we should consider\n\t\t\/\/ the local node as UP.\n\t\t\/\/ TODO: we should be able to remove this check if\/when cluster.Nodes and\n\t\t\/\/ cluster.NodeSet are unified.\n\t\tif host == s.Host {\n\t\t\tnodeState = NodeStateUp\n\t\t}\n\t\tnode := s.Cluster.NodeByHost(host)\n\t\tnode.SetState(nodeState)\n\t}\n\n\treturn s.Cluster.Status(), nil\n}\n\n\/\/ HandleRemoteStatus receives incoming NodeState from remote nodes.\nfunc (s *Server) HandleRemoteStatus(pb proto.Message) error {\n\treturn s.mergeRemoteStatus(pb.(*internal.NodeStatus))\n}\n\nfunc (s *Server) mergeRemoteStatus(ns *internal.NodeStatus) error {\n\t\/\/ Update Node.state.\n\tnode := s.Cluster.NodeByHost(ns.Host)\n\tnode.SetStatus(ns)\n\n\t\/\/ Create indexes that don't exist.\n\tfor _, index := range ns.Indexes {\n\t\topt := IndexOptions{\n\t\t\tColumnLabel: index.Meta.ColumnLabel,\n\t\t\tTimeQuantum: TimeQuantum(index.Meta.TimeQuantum),\n\t\t}\n\t\tidx, err := s.Holder.CreateIndexIfNotExists(index.Name, opt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Create frames that don't exist.\n\t\tfor _, f := range index.Frames {\n\t\t\topt := FrameOptions{\n\t\t\t\tRowLabel:    f.Meta.RowLabel,\n\t\t\t\tTimeQuantum: TimeQuantum(f.Meta.TimeQuantum),\n\t\t\t\tCacheSize:   f.Meta.CacheSize,\n\t\t\t}\n\t\t\t_, err := idx.CreateFrameIfNotExists(f.Name, opt)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc checkMaxSlices(hostport string) (map[string]uint64, error) {\n\t\/\/ Create HTTP request.\n\treq, err := http.NewRequest(\"GET\", (&url.URL{\n\t\tScheme: \"http\",\n\t\tHost:   hostport,\n\t\tPath:   \"\/slices\/max\",\n\t}).String(), nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Require protobuf encoding.\n\treq.Header.Set(\"Accept\", \"application\/x-protobuf\")\n\treq.Header.Set(\"Content-Type\", \"application\/x-protobuf\")\n\treq.Header.Set(\"User-Agent\", \"pilosa\/\"+Version)\n\n\t\/\/ Send request to remote node.\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\t\/\/ Read response into buffer.\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Check status code.\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"invalid status checkMaxSlices: code=%d, err=%s, req=%v\", resp.StatusCode, body, req)\n\t}\n\n\t\/\/ Decode response object.\n\tpb := internal.MaxSlicesResponse{}\n\n\tif err = proto.Unmarshal(body, &pb); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn pb.MaxSlices, nil\n}\n\n\/\/ monitorRuntime periodically polls the Go runtime metrics.\nfunc (s *Server) monitorRuntime() {\n\t\/\/ Disable metrics when poll interval is zero\n\tif s.MetricInterval <= 0 {\n\t\treturn\n\t}\n\n\tticker := time.NewTicker(s.MetricInterval)\n\tdefer ticker.Stop()\n\n\tgcn := gcnotifier.New()\n\tdefer gcn.Close()\n\n\ts.logger().Printf(\"runtime stats initializing (%s interval)\", s.MetricInterval)\n\n\tfor {\n\t\t\/\/ Wait for tick or a close.\n\t\tselect {\n\t\tcase <-s.closing:\n\t\t\treturn\n\t\tcase <-gcn.AfterGC():\n\t\t\t\/\/ GC just ran\n\t\t\ts.Holder.Stats.Count(\"garbage_collection\", 1, 1.0)\n\t\tcase <-ticker.C:\n\t\t}\n\n\t\t\/\/ Record the number of go routines\n\t\ts.Holder.Stats.Gauge(\"goroutines\", float64(runtime.NumGoroutine()), 1.0)\n\t}\n}\n\n\/\/ StatusHandler specifies two methods which an object must implement to share\n\/\/ state in the cluster. These are used by the GossipNodeSet to implement the\n\/\/ LocalState and MergeRemoteState methods of memberlist.Delegate\ntype StatusHandler interface {\n\tLocalStatus() (proto.Message, error)\n\tClusterStatus() (proto.Message, error)\n\tHandleRemoteStatus(proto.Message) error\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/fhs\/gompd\/mpd\"\n\t\"mime\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype m map[string]interface{}\ntype jsonParseError struct {\n\tkey string\n}\n\nfunc (j jsonParseError) Error() string {\n\treturn fmt.Sprintf(\"unexpected json type for %s\", j.key)\n}\n\nfunc writeJSONAttrList(w http.ResponseWriter, d []mpd.Attrs, l time.Time, err error) {\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.Header().Add(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tv := m{\"errors\": err, \"data\": d}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc writeJSONAttr(w http.ResponseWriter, d mpd.Attrs, l time.Time, err error) {\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tv := m{\"errors\": err, \"data\": d}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc writeJSONStatus(w http.ResponseWriter, d PlayerStatus, l time.Time, err error) {\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tv := m{\"errors\": err, \"data\": d}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc writeJSON(w http.ResponseWriter, err error) {\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tv := m{\"errors\": err}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc notModified(w http.ResponseWriter, l time.Time) {\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.WriteHeader(304)\n\treturn\n}\n\ntype apiHandler struct {\n\tplayer Music\n}\n\ntype sortAction struct {\n\tAction string   `json:\"action\"`\n\tKeys   []string `json:\"keys\"`\n\tURI    string   `json:\"uri\"`\n}\n\nfunc (h *apiHandler) playlist(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\td, l := h.player.Playlist()\n\t\tif modified(r, l) {\n\t\t\twriteJSONAttrList(w, d, l, nil)\n\t\t} else {\n\t\t\tnotModified(w, l)\n\t\t}\n\tcase \"POST\":\n\t\tdecoder := json.NewDecoder(r.Body)\n\t\tvar s sortAction\n\t\terr := decoder.Decode(&s)\n\t\tif err == nil {\n\t\t\th.player.SortPlaylist(s.Keys, s.URI)\n\t\t}\n\t\twriteJSON(w, err)\n\t}\n}\n\nfunc (h *apiHandler) library(w http.ResponseWriter, r *http.Request) {\n\td, l := h.player.Library()\n\tif modified(r, l) {\n\t\twriteJSONAttrList(w, d, l, nil)\n\t} else {\n\t\tnotModified(w, l)\n\t}\n}\n\nfunc (h *apiHandler) current(w http.ResponseWriter, r *http.Request) {\n\td, l := h.player.Current()\n\tif modified(r, l) {\n\t\twriteJSONAttr(w, d, l, nil)\n\t} else {\n\t\tnotModified(w, l)\n\t}\n}\n\nfunc (h *apiHandler) control(w http.ResponseWriter, r *http.Request) {\n\tif r.Method == \"POST\" {\n\t\tdecoder := json.NewDecoder(r.Body)\n\t\tvar s map[string]interface{}\n\t\terr := decoder.Decode(&s)\n\t\tif v, exist := s[\"volume\"]; exist {\n\t\t\tswitch v.(type) {\n\t\t\tcase float64:\n\t\t\t\terr = h.player.Volume(int(v.(float64)))\n\t\t\t\t\/\/ TODO: write type error\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\twriteJSON(w, err)\n\t\t\treturn\n\t\t}\n\t\tif v, exist := s[\"repeat\"]; exist {\n\t\t\tswitch v.(type) {\n\t\t\tcase bool:\n\t\t\t\terr = h.player.Repeat(v.(bool))\n\t\t\t\t\/\/ TODO: write type error\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\twriteJSON(w, err)\n\t\t\treturn\n\t\t}\n\t\tif v, exist := s[\"random\"]; exist {\n\t\t\tswitch v.(type) {\n\t\t\tcase bool:\n\t\t\t\terr = h.player.Random(v.(bool))\n\t\t\t\t\/\/ TODO: write type error\n\t\t\t}\n\t\t}\n\t\twriteJSON(w, err)\n\t\treturn\n\t}\n\n\t\/\/ TODO: post action\n\tmethod := r.FormValue(\"action\")\n\tif method == \"prev\" {\n\t\twriteJSON(w, h.player.Prev())\n\t\treturn\n\t} else if method == \"play\" {\n\t\twriteJSON(w, h.player.Play())\n\t\treturn\n\t} else if method == \"pause\" {\n\t\twriteJSON(w, h.player.Pause())\n\t\treturn\n\t} else if method == \"next\" {\n\t\twriteJSON(w, h.player.Next())\n\t\treturn\n\t} else {\n\t\td, l := h.player.Status()\n\t\tif modified(r, l) {\n\t\t\twriteJSONStatus(w, d, l, nil)\n\t\t} else {\n\t\t\tnotModified(w, l)\n\t\t}\n\t}\n}\n\nfunc (h *apiHandler) outputs(w http.ResponseWriter, r *http.Request) {\n\td, l := h.player.Outputs()\n\tif r.Method == \"POST\" {\n\t\tid, err := strconv.Atoi(\n\t\t\tstrings.Replace(r.URL.Path, \"\/api\/outputs\/\", \"\", -1),\n\t\t)\n\t\tif err != nil {\n\t\t\twriteJSON(w, err)\n\t\t\treturn\n\t\t}\n\t\tdecoder := json.NewDecoder(r.Body)\n\t\tvar s = struct {\n\t\t\tOutputEnabled bool `json:\"outputenabled\"`\n\t\t}{}\n\t\terr = decoder.Decode(&s)\n\t\tif err != nil {\n\t\t\twriteJSON(w, err)\n\t\t\treturn\n\t\t}\n\t\twriteJSON(w, h.player.Output(id, s.OutputEnabled))\n\t\treturn\n\t}\n\tif modified(r, l) {\n\t\twriteJSONAttrList(w, d, l, nil)\n\t} else {\n\t\tnotModified(w, l)\n\t}\n}\n\nfunc modified(r *http.Request, l time.Time) bool {\n\treturn r.Header.Get(\"If-Modified-Since\") != l.Format(http.TimeFormat)\n}\n\nfunc makeHandleAssets(f string, data []byte) func(http.ResponseWriter, *http.Request) {\n\tn := time.Now()\n\tm := mime.TypeByExtension(path.Ext(f))\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\/\/ w.Header().Add(\"Content-Length\", strconv.Itoa(len(data)))\n\t\tw.Header().Add(\"Last-Modified\", n.Format(http.TimeFormat))\n\t\tif m != \"\" {\n\t\t\tw.Header().Add(\"Content-Type\", m)\n\t\t}\n\t\tw.Write(data)\n\t}\n}\n\nfunc setHandle(p Music) {\n\tvar api = new(apiHandler)\n\tapi.player = p\n\thttp.HandleFunc(\"\/api\/library\", api.library)\n\thttp.HandleFunc(\"\/api\/songs\", api.playlist)\n\thttp.HandleFunc(\"\/api\/songs\/current\", api.current)\n\thttp.HandleFunc(\"\/api\/control\", api.control)\n\thttp.HandleFunc(\"\/api\/outputs\", api.outputs)\n\thttp.HandleFunc(\"\/api\/outputs\/\", api.outputs)\n\tfor _, f := range AssetNames() {\n\t\tp := \"\/\" + f\n\t\tif f == \"assets\/app.html\" {\n\t\t\tp = \"\/\"\n\t\t}\n\t\t_, err := os.Stat(f)\n\t\tif !os.IsNotExist(err) {\n\t\t\tfunc(path, rpath string) {\n\t\t\t\thttp.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\t\thttp.ServeFile(w, r, rpath)\n\t\t\t\t})\n\t\t\t}(p, f)\n\t\t} else {\n\t\t\tdata, _ := Asset(f)\n\t\t\thttp.HandleFunc(p, makeHandleAssets(f, data))\n\t\t}\n\t}\n}\n\n\/\/ App serves http request.\nfunc App(p Music, config ServerConfig) {\n\tsetHandle(p)\n\thttp.ListenAndServe(fmt.Sprintf(\":%s\", config.Port), nil)\n}\n\n\/\/ Music Represents music player.\ntype Music interface {\n\tPlay() error\n\tPause() error\n\tNext() error\n\tPrev() error\n\tVolume(int) error\n\tRepeat(bool) error\n\tRandom(bool) error\n\tPlaylist() ([]mpd.Attrs, time.Time)\n\tLibrary() ([]mpd.Attrs, time.Time)\n\tCurrent() (mpd.Attrs, time.Time)\n\tStatus() (PlayerStatus, time.Time)\n\tOutput(int, bool) error\n\tOutputs() ([]mpd.Attrs, time.Time)\n\tSortPlaylist([]string, string) error\n}\n<commit_msg>cleanup json encode\/decode<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/fhs\/gompd\/mpd\"\n\t\"io\"\n\t\"mime\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype jsonMap map[string]interface{}\n\nfunc parseSimpleJSON(b io.Reader) (jsonMap, error) {\n\tdecoder := json.NewDecoder(b)\n\ts := jsonMap{}\n\treturn s, decoder.Decode(&s)\n}\nfunc (j *jsonMap) execIfInt(key string, f func(int) error) error {\n\td := *j\n\tif v, exist := d[key]; exist {\n\t\tswitch v.(type) {\n\t\tcase float64:\n\t\t\treturn f(int(v.(float64)))\n\t\tdefault:\n\t\t\treturn errors.New(\"unexpected type for \" + key)\n\t\t}\n\t}\n\treturn nil\n}\nfunc (j *jsonMap) execIfBool(key string, f func(bool) error) error {\n\td := *j\n\tif v, exist := d[key]; exist {\n\t\tswitch v.(type) {\n\t\tcase bool:\n\t\t\treturn f(v.(bool))\n\t\tdefault:\n\t\t\treturn errors.New(\"unexpected type for \" + key)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc writeJSONInterface(w http.ResponseWriter, d interface{}, l time.Time, err error) {\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.Header().Add(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tv := jsonMap{\"errors\": err, \"data\": d}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc writeJSON(w http.ResponseWriter, err error) {\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tv := jsonMap{\"errors\": err}\n\tb, jsonerr := json.Marshal(v)\n\tif jsonerr != nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(w, string(b))\n\treturn\n}\n\nfunc notModified(w http.ResponseWriter, l time.Time) {\n\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\tw.Header().Add(\"Last-Modified\", l.Format(http.TimeFormat))\n\tw.WriteHeader(304)\n\treturn\n}\n\ntype apiHandler struct {\n\tplayer Music\n}\n\nfunc (h *apiHandler) playlist(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"GET\":\n\t\td, l := h.player.Playlist()\n\t\tif modified(r, l) {\n\t\t\twriteJSONInterface(w, d, l, nil)\n\t\t} else {\n\t\t\tnotModified(w, l)\n\t\t}\n\tcase \"POST\":\n\t\tdecoder := json.NewDecoder(r.Body)\n\t\tvar s struct {\n\t\t\tAction string   `json:\"action\"`\n\t\t\tKeys   []string `json:\"keys\"`\n\t\t\tURI    string   `json:\"uri\"`\n\t\t}\n\t\terr := decoder.Decode(&s)\n\t\tif err == nil {\n\t\t\th.player.SortPlaylist(s.Keys, s.URI)\n\t\t}\n\t\twriteJSON(w, err)\n\t}\n}\n\nfunc (h *apiHandler) library(w http.ResponseWriter, r *http.Request) {\n\td, l := h.player.Library()\n\tif modified(r, l) {\n\t\twriteJSONInterface(w, d, l, nil)\n\t} else {\n\t\tnotModified(w, l)\n\t}\n}\n\nfunc (h *apiHandler) current(w http.ResponseWriter, r *http.Request) {\n\td, l := h.player.Current()\n\tif modified(r, l) {\n\t\twriteJSONInterface(w, d, l, nil)\n\t} else {\n\t\tnotModified(w, l)\n\t}\n}\n\nfunc (h *apiHandler) control(w http.ResponseWriter, r *http.Request) {\n\tswitch r.Method {\n\tcase \"POST\":\n\t\tj, err := parseSimpleJSON(r.Body)\n\t\tif err != nil {\n\t\t\twriteJSON(w, err)\n\t\t\treturn\n\t\t}\n\t\tfuncs := []func() error{\n\t\t\tfunc() error {\n\t\t\t\treturn j.execIfInt(\"volume\", func(i int) error {\n\t\t\t\t\treturn h.player.Volume(i)\n\t\t\t\t})\n\t\t\t},\n\t\t\tfunc() error {\n\t\t\t\treturn j.execIfBool(\"repeat\", func(b bool) error {\n\t\t\t\t\treturn h.player.Repeat(b)\n\t\t\t\t})\n\t\t\t},\n\t\t\tfunc() error {\n\t\t\t\treturn j.execIfBool(\"random\", func(b bool) error {\n\t\t\t\t\treturn h.player.Random(b)\n\t\t\t\t})\n\t\t\t},\n\t\t}\n\t\tfor i := range funcs {\n\t\t\terr = funcs[i]()\n\t\t\tif err != nil {\n\t\t\t\twriteJSON(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\twriteJSON(w, err)\n\t\treturn\n\tcase \"GET\":\n\t\t\/\/ TODO: post action\n\t\tmethod := r.FormValue(\"action\")\n\t\tif method == \"prev\" {\n\t\t\twriteJSON(w, h.player.Prev())\n\t\t\treturn\n\t\t} else if method == \"play\" {\n\t\t\twriteJSON(w, h.player.Play())\n\t\t\treturn\n\t\t} else if method == \"pause\" {\n\t\t\twriteJSON(w, h.player.Pause())\n\t\t\treturn\n\t\t} else if method == \"next\" {\n\t\t\twriteJSON(w, h.player.Next())\n\t\t\treturn\n\t\t} else {\n\t\t\td, l := h.player.Status()\n\t\t\tif modified(r, l) {\n\t\t\t\twriteJSONInterface(w, d, l, nil)\n\t\t\t} else {\n\t\t\t\tnotModified(w, l)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (h *apiHandler) outputs(w http.ResponseWriter, r *http.Request) {\n\td, l := h.player.Outputs()\n\tif r.Method == \"POST\" {\n\t\tid, err := strconv.Atoi(\n\t\t\tstrings.Replace(r.URL.Path, \"\/api\/outputs\/\", \"\", -1),\n\t\t)\n\t\tif err != nil {\n\t\t\twriteJSON(w, err)\n\t\t\treturn\n\t\t}\n\t\tdecoder := json.NewDecoder(r.Body)\n\t\tvar s = struct {\n\t\t\tOutputEnabled bool `json:\"outputenabled\"`\n\t\t}{}\n\t\terr = decoder.Decode(&s)\n\t\tif err != nil {\n\t\t\twriteJSON(w, err)\n\t\t\treturn\n\t\t}\n\t\twriteJSON(w, h.player.Output(id, s.OutputEnabled))\n\t\treturn\n\t}\n\tif modified(r, l) {\n\t\twriteJSONInterface(w, d, l, nil)\n\t} else {\n\t\tnotModified(w, l)\n\t}\n}\n\nfunc modified(r *http.Request, l time.Time) bool {\n\treturn r.Header.Get(\"If-Modified-Since\") != l.Format(http.TimeFormat)\n}\n\nfunc makeHandleAssets(f string, data []byte) func(http.ResponseWriter, *http.Request) {\n\tn := time.Now()\n\tm := mime.TypeByExtension(path.Ext(f))\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\/\/ w.Header().Add(\"Content-Length\", strconv.Itoa(len(data)))\n\t\tw.Header().Add(\"Last-Modified\", n.Format(http.TimeFormat))\n\t\tif m != \"\" {\n\t\t\tw.Header().Add(\"Content-Type\", m)\n\t\t}\n\t\tw.Write(data)\n\t}\n}\n\nfunc setHandle(p Music) {\n\tvar api = new(apiHandler)\n\tapi.player = p\n\thttp.HandleFunc(\"\/api\/library\", api.library)\n\thttp.HandleFunc(\"\/api\/songs\", api.playlist)\n\thttp.HandleFunc(\"\/api\/songs\/current\", api.current)\n\thttp.HandleFunc(\"\/api\/control\", api.control)\n\thttp.HandleFunc(\"\/api\/outputs\", api.outputs)\n\thttp.HandleFunc(\"\/api\/outputs\/\", api.outputs)\n\tfor _, f := range AssetNames() {\n\t\tp := \"\/\" + f\n\t\tif f == \"assets\/app.html\" {\n\t\t\tp = \"\/\"\n\t\t}\n\t\t_, err := os.Stat(f)\n\t\tif !os.IsNotExist(err) {\n\t\t\tfunc(path, rpath string) {\n\t\t\t\thttp.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\t\thttp.ServeFile(w, r, rpath)\n\t\t\t\t})\n\t\t\t}(p, f)\n\t\t} else {\n\t\t\tdata, _ := Asset(f)\n\t\t\thttp.HandleFunc(p, makeHandleAssets(f, data))\n\t\t}\n\t}\n}\n\n\/\/ App serves http request.\nfunc App(p Music, config ServerConfig) {\n\tsetHandle(p)\n\thttp.ListenAndServe(fmt.Sprintf(\":%s\", config.Port), nil)\n}\n\n\/\/ Music Represents music player.\ntype Music interface {\n\tPlay() error\n\tPause() error\n\tNext() error\n\tPrev() error\n\tVolume(int) error\n\tRepeat(bool) error\n\tRandom(bool) error\n\tPlaylist() ([]mpd.Attrs, time.Time)\n\tLibrary() ([]mpd.Attrs, time.Time)\n\tCurrent() (mpd.Attrs, time.Time)\n\tStatus() (PlayerStatus, time.Time)\n\tOutput(int, bool) error\n\tOutputs() ([]mpd.Attrs, time.Time)\n\tSortPlaylist([]string, string) error\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/labstack\/echo\/engine\/fasthttp\"\n\t\"github.com\/labstack\/echo\/middleware\"\n\n\t\"github.com\/shamsher31\/stay-motivated-server\/db\"\n\t\"github.com\/shamsher31\/stay-motivated-server\/utils\"\n\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\n\/\/ Quote defines structure of quote\ntype Quote struct {\n\tID        bson.ObjectId `json:\"-\" bson:\"_id,omitempty\"`\n\tTitle     string        `json:\"title\" bson:\"title\"`\n\tAuthor    string        `json:\"author\" bson:\"author,omitempty\"`\n\tTimestamp time.Time     `json:\"timestamp\" bson:\"timestamp\"`\n}\n\n\/\/ type Server struct {\n\/\/ \tdb *mgo.Session\n\/\/ }\n\nfunc main() {\n\n\t\/\/ db, err := mgo.Dial(os.Getenv(\"DB_URL\"))\n\t\/\/ utils.CheckError(err)\n\t\/\/ defer db.Close()\n\n\t\/\/ server := &Server{db: db}\n\n\te := echo.New()\n\n\t\/\/ Middleware\n\te.Use(middleware.Logger())\n\te.Use(middleware.Recover())\n\n\te.POST(\"\/qoutes\", createQoute)\n\te.GET(\"\/qoutes\/\", getAllQoutes)\n\te.GET(\"\/qoutes\/:id\", getQoute)\n\t\/\/ e.PUT(\"\/qoutes\/:id\", updateQoute)\n\t\/\/ e.DELETE(\"\/qoutes\/:id\", deleteQoute)\n\n\te.Run(fasthttp.New(os.Getenv(\"PORT\")))\n\n}\n\nfunc createQoute(c echo.Context) error {\n\n\ttitle := c.FormValue(\"title\")\n\tauthor := c.FormValue(\"author\")\n\n\tsession, err := db.GetSession()\n\tutils.CheckError(err)\n\tdefer session.Close()\n\n\tqoutes := db.GetCollection(session, \"qoutes\")\n\tid := db.GenerateID()\n\terr = qoutes.Insert(&Quote{id, title, author, time.Now()})\n\n\tutils.CheckError(err)\n\n\treturn c.JSON(http.StatusOK, qoutes)\n}\n\nfunc getAllQoutes(c echo.Context) error {\n\n\tvar results []Quote\n\n\tsession, err := mgo.Dial(os.Getenv(\"DB_URL\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tqoutes := session.DB(db.DBName).C(\"qoutes\")\n\terr = qoutes.Find(bson.M{\"author\": \"Sam\"}).One(&results)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\treturn c.JSON(http.StatusOK, results)\n}\n\nfunc getQoute(c echo.Context) error {\n\n\tsession, err := db.GetSession()\n\tutils.CheckError(err)\n\tdefer session.Close()\n\n\tqoutes := db.GetCollection(session, \"qoutes\")\n\n\tresult := Quote{}\n\terr = qoutes.Find(bson.M{\"name\": \"Sam\"}).One(&result)\n\n\tutils.CheckError(err)\n\n\treturn c.JSON(http.StatusOK, result)\n}\n<commit_msg>Add status and tag field<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/labstack\/echo\/engine\/fasthttp\"\n\t\"github.com\/labstack\/echo\/middleware\"\n\n\t\"github.com\/shamsher31\/stay-motivated-server\/db\"\n\t\"github.com\/shamsher31\/stay-motivated-server\/utils\"\n\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\ntype Status int\n\nconst (\n\tPENDING Status = iota\n\tAPPROVED\n\tCANCELED\n)\n\n\/\/ Quote defines structure of quote\ntype Quote struct {\n\tID        bson.ObjectId `json:\"-\" bson:\"_id,omitempty\"`\n\tTitle     string        `json:\"title\" bson:\"title\"`\n\tAuthor    string        `json:\"author\" bson:\"author,omitempty\"`\n\tStatus    string        `json:\"status\" bson:\"status\"`\n\tTag       []string      `json:\"tag\" bson:\"tag\"`\n\tTimestamp time.Time     `json:\"timestamp\" bson:\"timestamp\"`\n}\n\n\/\/ type Server struct {\n\/\/ \tdb *mgo.Session\n\/\/ }\n\nfunc main() {\n\n\t\/\/ db, err := mgo.Dial(os.Getenv(\"DB_URL\"))\n\t\/\/ utils.CheckError(err)\n\t\/\/ defer db.Close()\n\n\t\/\/ server := &Server{db: db}\n\n\te := echo.New()\n\n\t\/\/ Middleware\n\te.Use(middleware.Logger())\n\te.Use(middleware.Recover())\n\n\te.POST(\"\/qoutes\", createQoute)\n\te.GET(\"\/qoutes\/\", getAllQoutes)\n\te.GET(\"\/qoutes\/:id\", getQoute)\n\t\/\/ e.PUT(\"\/qoutes\/:id\", updateQoute)\n\t\/\/ e.DELETE(\"\/qoutes\/:id\", deleteQoute)\n\n\te.Run(fasthttp.New(os.Getenv(\"PORT\")))\n\n}\n\nfunc createQoute(c echo.Context) error {\n\n\ttitle := c.FormValue(\"title\")\n\tauthor := c.FormValue(\"author\")\n\n\tsession, err := db.GetSession()\n\tutils.CheckError(err)\n\tdefer session.Close()\n\n\tqoutes := db.GetCollection(session, \"qoutes\")\n\tid := db.GenerateID()\n\terr = qoutes.Insert(&Quote{id, title, author, time.Now()})\n\n\tutils.CheckError(err)\n\n\treturn c.JSON(http.StatusOK, qoutes)\n}\n\nfunc getAllQoutes(c echo.Context) error {\n\n\tvar results []Quote\n\n\tsession, err := mgo.Dial(os.Getenv(\"DB_URL\"))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tqoutes := session.DB(db.DBName).C(\"qoutes\")\n\terr = qoutes.Find(bson.M{\"author\": \"Sam\"}).One(&results)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\treturn c.JSON(http.StatusOK, results)\n}\n\nfunc getQoute(c echo.Context) error {\n\n\tsession, err := db.GetSession()\n\tutils.CheckError(err)\n\tdefer session.Close()\n\n\tqoutes := db.GetCollection(session, \"qoutes\")\n\n\tresult := Quote{}\n\terr = qoutes.Find(bson.M{\"name\": \"Sam\"}).One(&result)\n\n\tutils.CheckError(err)\n\n\treturn c.JSON(http.StatusOK, result)\n}\n<|endoftext|>"}
{"text":"<commit_before>package bay\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"github.com\/acmacalister\/helm\"\n\t\"github.com\/fsouza\/go-dockerclient\"\n)\n\n\/\/ Build is type for implementing callback functions set in your config.\ntype Build interface {\n\tPreBuild(buildDir, lang string, err error)                     \/\/ PreBuild gets called before the docker image is built.\n\tPostBuild(container *docker.Container, lang string, err error) \/\/ PostBuild is called after the docker image is built.\n}\n\n\/\/ Config is a type for configuring the properties of bay.\ntype Config struct {\n\tCPU            int64  \/\/ Cpu is the number of CPUs allowed by each container.\n\tMemory         int64  \/\/ Memory is the amount of memory allowed by each container.\n\tDockerUrl      string \/\/ DockerUrl is the url to your docker instance. Generally your swarm url.\n\tCert           string \/\/ Cert is your TLS certificate for connecting to your docker instance.\n\tKey            string \/\/ Key is your TLS key for connecting to your docker instance.\n\tCa             string \/\/ Ca is your TLS ca for connecting to your docker instance.\n\tBuildInterface Build  \/\/ BuildInterface is the Build Interface.\n}\n\n\/\/ server is a internal struct used by http handlers.\ntype server struct {\n\tconfig       *Config\n\tdockerClient *docker.Client \/\/ the actual init'ed and connected docker client.\n}\n\n\/\/ response is a simple struct for writing back json messages.\ntype response struct {\n\tResponse string `json:\"response\"`\n}\n\n\/\/ Start get this API party started. It is just the http listener to start handling routes.\nfunc Start(address string, c *Config) error {\n\tclient, err := docker.NewClient(c.DockerUrl)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts := server{config: c, dockerClient: client}\n\tr := helm.New(fallThrough)\n\tr.POST(\"\/github_webhook\", s.githubWebhookHandler)\n\tr.POST(\"\/upload\", s.uploadHandler)\n\tr.POST(\"\/git_url\", s.gitHandler)\n\tr.Run(address)\n\treturn nil \/\/ should never get here.\n}\n\n\/\/ fallThrough is an http catch all for routes that aren't handled by the API.\nfunc fallThrough(w http.ResponseWriter, r *http.Request, params url.Values) {\n\thelm.RespondWithJSON(w, response{\"Are you lost?\"}, http.StatusNotFound)\n}\n\n\/\/ githubWebhookHandler is the http handler for github wehbook post.\nfunc (s *server) githubWebhookHandler(w http.ResponseWriter, r *http.Request, params url.Values) {\n\n\tvar wh webhook\n\tjsonDecoder := json.NewDecoder(r.Body)\n\tif err := jsonDecoder.Decode(&wh); err != nil {\n\t\thelm.RespondWithJSON(w, response{\"Failed to decode Github payload\"}, http.StatusInternalServerError)\n\t}\n\n\tgo s.buildWithGit(wh.Repository.URL, \"\")\n\n\thelm.RespondWithJSON(w, response{\"ok\"}, http.StatusOK)\n}\n\n\/\/ uploadHandler is the http handler for file uploads.\nfunc (s *server) uploadHandler(w http.ResponseWriter, r *http.Request, params url.Values) {\n\tfile, header, err := r.FormFile(\"file\")\n\tif err != nil {\n\t\thelm.RespondWithJSON(w, response{\"failed to get file from form\"}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlang, ok := params[\"language\"]\n\tif !ok {\n\t\thelm.RespondWithJSON(w, response{\"Please specific a language parameter to build with.\"}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tgo s.buildWithFiles(file, header.Filename, lang[0], header.Header.Get(\"Content-Type\")) \/\/ need lang from API\n\n\thelm.RespondWithJSON(w, response{fmt.Sprintf(\"%s uploaded successfully\", header.Filename)}, http.StatusOK)\n}\n\n\/\/ gitHandler is the http handler for bare git urls.\nfunc (s *server) gitHandler(w http.ResponseWriter, r *http.Request, params url.Values) {\n\tlang, ok := params[\"language\"]\n\tif !ok {\n\t\thelm.RespondWithJSON(w, response{\"Please specific a language parameter to build with.\"}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tgitUrl, ok := params[\"git_url\"]\n\tif !ok {\n\t\thelm.RespondWithJSON(w, response{\"Please specific a git_url parameter to clone with.\"}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tgo s.buildWithGit(gitUrl[0], lang[0])\n\n\thelm.RespondWithJSON(w, response{\"ok\"}, http.StatusOK)\n}\n<commit_msg>add info handler<commit_after>package bay\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"github.com\/acmacalister\/helm\"\n\tlinuxproc \"github.com\/c9s\/goprocinfo\/linux\"\n\t\"github.com\/fsouza\/go-dockerclient\"\n)\n\nconst (\n\tsize = 1024 \/\/for figuring out byte sizes.\n)\n\n\/\/ Build is type for implementing callback functions set in your config.\ntype Build interface {\n\tPreBuild(buildDir, lang string, err error)                     \/\/ PreBuild gets called before the docker image is built.\n\tPostBuild(container *docker.Container, lang string, err error) \/\/ PostBuild is called after the docker image is built.\n}\n\n\/\/ Config is a type for configuring the properties of bay.\ntype Config struct {\n\tCPU            int64  \/\/ Cpu is the number of CPUs allowed by each container.\n\tMemory         int64  \/\/ Memory is the amount of memory allowed by each container.\n\tDockerUrl      string \/\/ DockerUrl is the url to your docker instance. Generally your swarm url.\n\tCert           string \/\/ Cert is your TLS certificate for connecting to your docker instance.\n\tKey            string \/\/ Key is your TLS key for connecting to your docker instance.\n\tCa             string \/\/ Ca is your TLS ca for connecting to your docker instance.\n\tBuildInterface Build  \/\/ BuildInterface is the Build Interface.\n}\n\n\/\/ server is a internal struct used by http handlers.\ntype server struct {\n\tconfig       *Config\n\tdockerClient *docker.Client \/\/ the actual init'ed and connected docker client.\n}\n\n\/\/ response is a simple struct for writing back json messages.\ntype response struct {\n\tResponse string `json:\"response\"`\n}\n\n\/\/ proc is a struct for the memory and disk info.\ntype proc struct {\n\tTotal uint64 `json:\"total\"`\n\tUsed  uint64 `json:\"used\"`\n\tFree  uint64 `json:\"free\"`\n}\n\n\/\/ procInfo is a struct for the info handler.\ntype procInfo struct {\n\tMemory proc    `json:\"memory\"`\n\tDisk   proc    `json:\"disk\"`\n\tCPU    float64 `json:\"cpu\"`\n}\n\n\/\/ Start get this API party started. It is just the http listener to start handling routes.\nfunc Start(address string, c *Config) error {\n\tclient, err := docker.NewClient(c.DockerUrl)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts := server{config: c, dockerClient: client}\n\tr := helm.New(fallThrough)\n\tr.POST(\"\/github_webhook\", s.githubWebhookHandler)\n\tr.POST(\"\/upload\", s.uploadHandler)\n\tr.POST(\"\/git_url\", s.gitHandler)\n\tr.GET(\"\/info\", infoHandler)\n\tr.Run(address)\n\treturn nil \/\/ should never get here.\n}\n\n\/\/ fallThrough is an http catch all for routes that aren't handled by the API.\nfunc fallThrough(w http.ResponseWriter, r *http.Request, params url.Values) {\n\thelm.RespondWithJSON(w, response{\"Are you lost?\"}, http.StatusNotFound)\n}\n\n\/\/ githubWebhookHandler is the http handler for github wehbook post.\nfunc (s *server) githubWebhookHandler(w http.ResponseWriter, r *http.Request, params url.Values) {\n\n\tvar wh webhook\n\tjsonDecoder := json.NewDecoder(r.Body)\n\tif err := jsonDecoder.Decode(&wh); err != nil {\n\t\thelm.RespondWithJSON(w, response{\"Failed to decode Github payload\"}, http.StatusInternalServerError)\n\t}\n\n\tgo s.buildWithGit(wh.Repository.URL, \"\")\n\n\thelm.RespondWithJSON(w, response{\"ok\"}, http.StatusOK)\n}\n\n\/\/ uploadHandler is the http handler for file uploads.\nfunc (s *server) uploadHandler(w http.ResponseWriter, r *http.Request, params url.Values) {\n\tfile, header, err := r.FormFile(\"file\")\n\tif err != nil {\n\t\thelm.RespondWithJSON(w, response{\"failed to get file from form\"}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlang, ok := params[\"language\"]\n\tif !ok {\n\t\thelm.RespondWithJSON(w, response{\"Please specific a language parameter to build with.\"}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tgo s.buildWithFiles(file, header.Filename, lang[0], header.Header.Get(\"Content-Type\")) \/\/ need lang from API\n\n\thelm.RespondWithJSON(w, response{fmt.Sprintf(\"%s uploaded successfully\", header.Filename)}, http.StatusOK)\n}\n\n\/\/ gitHandler is the http handler for bare git urls.\nfunc (s *server) gitHandler(w http.ResponseWriter, r *http.Request, params url.Values) {\n\tlang, ok := params[\"language\"]\n\tif !ok {\n\t\thelm.RespondWithJSON(w, response{\"Please specific a language parameter to build with.\"}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tgitUrl, ok := params[\"git_url\"]\n\tif !ok {\n\t\thelm.RespondWithJSON(w, response{\"Please specific a git_url parameter to clone with.\"}, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tgo s.buildWithGit(gitUrl[0], lang[0])\n\n\thelm.RespondWithJSON(w, response{\"ok\"}, http.StatusOK)\n}\n\n\/\/ infoHandler is an http handler for responding with the host memory\/disk\/cpu usage.\nfunc infoHandler(w http.ResponseWriter, r *http.Request, params url.Values) {\n\tmem, err := linuxproc.ReadMemInfo(\"\/proc\/meminfo\")\n\tif err != nil {\n\t\thelm.RespondWithJSON(w, response{\"Failed to get memory info.\"}, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tdisk, err := linuxproc.ReadDisk(\"\/\")\n\tif err != nil {\n\t\thelm.RespondWithJSON(w, response{\"Failed to get disk info.\"}, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tcpu, err := linuxproc.ReadStat(\"\/proc\/stat\")\n\tif err != nil {\n\t\thelm.RespondWithJSON(w, response{\"Failed to get cpu info.\"}, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tidle := float64(cpu.CPUStatAll.Idle)\n\ttotal := float64(cpu.CPUStatAll.User+cpu.CPUStatAll.Nice+cpu.CPUStatAll.System) + idle\n\tusage := 100 * (total - idle) \/ total\n\tm := proc{Total: (mem.MemTotal \/ size), Used: ((mem.MemTotal - mem.MemFree) \/ size), Free: (mem.MemFree \/ size)}\n\td := proc{Total: (disk.All \/ size \/ size \/ size), Used: (disk.Used \/ size \/ size \/ size), Free: (disk.Free \/ size \/ size \/ size)}\n\tinfo := procInfo{Memory: m, Disk: d, CPU: usage}\n\thelm.RespondWithJSON(w, info, http.StatusOK)\n}\n<|endoftext|>"}
{"text":"<commit_before>package polynomial\n\nimport \"math\/big\"\n\n\/\/ Generates a polynomial and n points\n\/\/ This polynomial will be solved with k points\nfunc GenRandomShares(n, k int, q *big.Int) (ps Points, p Poly) {\n\tif q.ProbablyPrime(100) == false {\n\t\tps = nil\n\t\tp = nil\n\t\treturn\n\t}\n\tsize := q.BitLen()\/8 + 1\n\tp = make([]*big.Int, k)\n\tfor i := 0; i < k; i++ {\n\t\tcoeff := RandomBigInt(size)\n\t\tcoeff.Mod(coeff, q)\n\t\tp[i] = coeff\n\t}\n\tps = make([]Point, n)\n\tfor i := 0; i < n; i++ {\n\t\tr := RandomBigInt(size)\n\t\tr.Mod(r, q)\n\t\tvar t Point\n\t\tt.x = r\n\t\tt.y = p.Eval(r, q)\n\t\tps[i] = t\n\t}\n\treturn\n}\n<commit_msg>polished a comment<commit_after>package polynomial\n\nimport \"math\/big\"\n\n\/\/ GenRandomShares generates a polynomial and n points\n\/\/ The polynomial can be solved with k points\nfunc GenRandomShares(n, k int, q *big.Int) (ps Points, p Poly) {\n\tif q.ProbablyPrime(100) == false {\n\t\tps = nil\n\t\tp = nil\n\t\treturn\n\t}\n\tsize := q.BitLen()\/8 + 1\n\tp = make([]*big.Int, k)\n\tfor i := 0; i < k; i++ {\n\t\tcoeff := RandomBigInt(size)\n\t\tcoeff.Mod(coeff, q)\n\t\tp[i] = coeff\n\t}\n\tps = make([]Point, n)\n\tfor i := 0; i < n; i++ {\n\t\tr := RandomBigInt(size)\n\t\tr.Mod(r, q)\n\t\tvar t Point\n\t\tt.x = r\n\t\tt.y = p.Eval(r, q)\n\t\tps[i] = t\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\n   \"fmt\"\n\t\"io\/ioutil\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"golang.org\/x\/oauth2\/google\"\n\t\"gopkg.in\/Iwark\/spreadsheet.v2\"\n)\n\ntype Board struct {\n\tpresident, vpe, vppr, secretary, treasurer, saa string\n}\ntype AgendaRoles struct {\n\ttoastmaster, ge, timer, ahCounter, grammarian, eval1, speaker1, eval2, speaker2, eval3, speaker3, eval4, speaker4, tableTopicsMaster string\n\tboardMembers Board\n}\n\nfunc getSheet() (*spreadsheet.Sheet, *spreadsheet.Sheet) {\n\tdata, err := ioutil.ReadFile(\"client_secret.json\")\n\tif err != nil {\n\t\tpanic(\"cannot read client_secret.json\")\n\t}\n\n\tconf, err := google.JWTConfigFromJSON(data, spreadsheet.Scope)\n\tif err != nil {\n\t\tpanic(\"problem with google.JWTConfigFromJSON(data, spreadsheet.Scope)\")\n\t}\n\n\tclient := conf.Client(context.TODO())\n\n\tservice := spreadsheet.NewServiceWithClient(client)\n\tspreadsheet, err := service.FetchSpreadsheet(\"1_P9K2asfsITSGEAh7PrPLxncSemNnjXHg3_O3q7OW0k\/\")\n\tif err != nil {\n\t\tpanic(\"cannot fetch spread sheet: \")\n\t}\n\n\troles, err := spreadsheet.SheetByIndex(0)\n\tif err != nil {\n\t\tpanic(\"Cannot read spreadsheet by index 0\")\n\t}\n\n\tboard, err := spreadsheet.SheetByIndex(1)\n\tif err != nil {\n\t\tpanic(\"Cannot read spreadsheet by index 1\")\n\t}\n\n\treturn roles, board\n}\n\nfunc getBoard(sheet *spreadsheet.Sheet) Board {\n\tboard := Board{}\n\tboard.president = sheet.Columns[1][0].Value\n\tboard.vpe = sheet.Columns[1][1].Value\n\tboard.vppr = sheet.Columns[1][2].Value\n\tboard.secretary = sheet.Columns[1][3].Value\n\tboard.treasurer = sheet.Columns[1][4].Value\n\tboard.saa = sheet.Columns[1][5].Value\t\n\n\treturn board\n}\n\nfunc GetRoles(agendaDate string) AgendaRoles {\n\tsheet, roles := getSheet()\n\tboardMembers := getBoard(roles)\n\n\tagendaRoles := AgendaRoles{}\n\tagendaRoles.boardMembers = boardMembers\n\n\tfor i := range sheet.Columns {\n\t\tif sheet.Columns[i][0].Value == agendaDate {\n\t\t\tagendaRoles.toastmaster = sheet.Columns[i][1].Value\n\t\t\tagendaRoles.ge = sheet.Columns[i][2].Value\n\t\t\tagendaRoles.timer = sheet.Columns[i][3].Value\n\t\t\tagendaRoles.ahCounter = sheet.Columns[i][4].Value\n\t\t\tagendaRoles.grammarian = sheet.Columns[i][5].Value\n\n\t\t\tagendaRoles.speaker1 = sheet.Columns[i][7].Value\n\t\t\tagendaRoles.eval1 = sheet.Columns[i][8].Value\n\n\t\t\tagendaRoles.speaker2 = sheet.Columns[i][9].Value\n\t\t\tagendaRoles.eval2 = sheet.Columns[i][10].Value\n\n\t\t\tagendaRoles.speaker3 = sheet.Columns[i][11].Value\n\t\t\tagendaRoles.eval3 = sheet.Columns[i][12].Value\n\n\t\t\tagendaRoles.speaker4 = sheet.Columns[i][13].Value\n\t\t\tagendaRoles.eval4 = sheet.Columns[i][14].Value\n\n\t\t\tagendaRoles.tableTopicsMaster = sheet.Columns[i][18].Value\n\t\t\tbreak\n\t\t}\n\t}\n\treturn agendaRoles\n}\n<commit_msg>Update sheets.go<commit_after>package main\n\nimport (\n\n   \"fmt\"\n\t\"io\/ioutil\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"golang.org\/x\/oauth2\/google\"\n\t\"gopkg.in\/Iwark\/spreadsheet.v2\"\n)\n\ntype Board struct {\n\tpresident, vpe, vppr, secretary, treasurer, saa string\n}\ntype AgendaRoles struct {\n\ttoastmaster, ge, timer, ahCounter, grammarian, eval1, speaker1, eval2, speaker2, eval3, speaker3, eval4, speaker4, tableTopicsMaster string\n\tboardMembers Board\n}\n\nfunc getSheet() (*spreadsheet.Sheet, *spreadsheet.Sheet) {\n\tdata, err := ioutil.ReadFile(\"client_secret.json\")\n\tif err != nil {\n\t\tpanic(\"cannot read client_secret.json\")\n\t}\n\n\tconf, err := google.JWTConfigFromJSON(data, spreadsheet.Scope)\n\tif err != nil {\n\t\tpanic(\"problem with google.JWTConfigFromJSON(data, spreadsheet.Scope)\")\n\t}\n\n\tclient := conf.Client(context.TODO())\n\n\tservice := spreadsheet.NewServiceWithClient(client)\n\tspreadsheet, err := service.FetchSpreadsheet(\"1_1CBlORqCzL6YvyAUZTk8jezvhyuDzjjumghwGKk5VIK8)\n\tif err != nil {y\n\t\tpanic(\"cannot fetch spread sheet: \")\n\t}\n\n\troles, err := spreadsheet.SheetByIndex(0)\n\tif err != nil {\n\t\tpanic(\"Cannot read spreadsheet by index 0\")\n\t}\n\n\tboard, err := spreadsheet.SheetByIndex(1)\n\tif err != nil {\n\t\tpanic(\"Cannot read spreadsheet by index 1\")\n\t}\n\n\treturn roles, board\n}\n\nfunc getBoard(sheet *spreadsheet.Sheet) Board {\n\tboard := Board{}\n\tboard.president = sheet.Columns[1][0].Value\n\tboard.vpe = sheet.Columns[1][1].Value\n\tboard.vppr = sheet.Columns[1][2].Value\n\tboard.secretary = sheet.Columns[1][3].Value\n\tboard.treasurer = sheet.Columns[1][4].Value\n\tboard.saa = sheet.Columns[1][5].Value\t\n\n\treturn board\n}\n\nfunc GetRoles(agendaDate string) AgendaRoles {\n\tsheet, roles := getSheet()\n\tboardMembers := getBoard(roles)\n\n\tagendaRoles := AgendaRoles{}\n\tagendaRoles.boardMembers = boardMembers\n\n\tfor i := range sheet.Columns {\n\t\tif sheet.Columns[i][0].Value == agendaDate {\n\t\t\tagendaRoles.toastmaster = sheet.Columns[i][1].Value\n\t\t\tagendaRoles.ge = sheet.Columns[i][2].Value\n\t\t\tagendaRoles.timer = sheet.Columns[i][3].Value\n\t\t\tagendaRoles.ahCounter = sheet.Columns[i][4].Value\n\t\t\tagendaRoles.grammarian = sheet.Columns[i][5].Value\n\n\t\t\tagendaRoles.speaker1 = sheet.Columns[i][7].Value\n\t\t\tagendaRoles.eval1 = sheet.Columns[i][8].Value\n\n\t\t\tagendaRoles.speaker2 = sheet.Columns[i][9].Value\n\t\t\tagendaRoles.eval2 = sheet.Columns[i][10].Value\n\n\t\t\tagendaRoles.speaker3 = sheet.Columns[i][11].Value\n\t\t\tagendaRoles.eval3 = sheet.Columns[i][12].Value\n\n\t\t\tagendaRoles.speaker4 = sheet.Columns[i][13].Value\n\t\t\tagendaRoles.eval4 = sheet.Columns[i][14].Value\n\n\t\t\tagendaRoles.tableTopicsMaster = sheet.Columns[i][18].Value\n\t\t\tbreak\n\t\t}\n\t}\n\treturn agendaRoles\n}\n<|endoftext|>"}
{"text":"<commit_before>package goproxy\n\nimport (\n\t\"crypto\"\n\t\"crypto\/ecdsa\"\n\t\"crypto\/elliptic\"\n\t\"crypto\/rsa\"\n\t\"crypto\/sha1\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"crypto\/x509\/pkix\"\n\t\"fmt\"\n\t\"math\/big\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"runtime\"\n\t\"sort\"\n\t\"time\"\n)\n\nfunc hashSorted(lst []string) []byte {\n\tc := make([]string, len(lst))\n\tcopy(c, lst)\n\tsort.Strings(c)\n\th := sha1.New()\n\tfor _, s := range c {\n\t\th.Write([]byte(s + \",\"))\n\t}\n\treturn h.Sum(nil)\n}\n\nfunc hashSortedBigInt(lst []string) *big.Int {\n\trv := new(big.Int)\n\trv.SetBytes(hashSorted(lst))\n\treturn rv\n}\n\nvar goproxySignerVersion = \":goroxy1\"\n\nfunc signHost(ca tls.Certificate, hosts []string) (cert *tls.Certificate, err error) {\n\tvar x509ca *x509.Certificate\n\n\t\/\/ Use the provided ca and not the global GoproxyCa for certificate generation.\n\tif x509ca, err = x509.ParseCertificate(ca.Certificate[0]); err != nil {\n\t\treturn\n\t}\n\tstart := time.Unix(0, 0)\n\tend, err := time.Parse(\"2006-01-02\", \"2049-12-31\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tserial := big.NewInt(rand.Int63())\n\ttemplate := x509.Certificate{\n\t\t\/\/ TODO(elazar): instead of this ugly hack, just encode the certificate and hash the binary form.\n\t\tSerialNumber: serial,\n\t\tIssuer:       x509ca.Subject,\n\t\tSubject: pkix.Name{\n\t\t\tOrganization: []string{\"GoProxy untrusted MITM proxy Inc\"},\n\t\t},\n\t\tNotBefore: start,\n\t\tNotAfter:  end,\n\n\t\tKeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,\n\t\tExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},\n\t\tBasicConstraintsValid: true,\n\t}\n\tfor _, h := range hosts {\n\t\tif ip := net.ParseIP(h); ip != nil {\n\t\t\ttemplate.IPAddresses = append(template.IPAddresses, ip)\n\t\t} else {\n\t\t\ttemplate.DNSNames = append(template.DNSNames, h)\n\t\t\ttemplate.Subject.CommonName = h\n\t\t}\n\t}\n\n\thash := hashSorted(append(hosts, goproxySignerVersion, \":\"+runtime.Version()))\n\tvar csprng CounterEncryptorRand\n\tif csprng, err = NewCounterEncryptorRandFromKey(ca.PrivateKey, hash); err != nil {\n\t\treturn\n\t}\n\n\tvar certpriv crypto.Signer\n\tswitch ca.PrivateKey.(type) {\n\tcase *rsa.PrivateKey:\n\t\tif certpriv, err = rsa.GenerateKey(&csprng, 2048); err != nil {\n\t\t\treturn\n\t\t}\n\tcase *ecdsa.PrivateKey:\n\t\tif certpriv, err = ecdsa.GenerateKey(elliptic.P256(), &csprng); err != nil {\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\terr = fmt.Errorf(\"unsupported key type %T\", ca.PrivateKey)\n\t}\n\n\tvar derBytes []byte\n\tif derBytes, err = x509.CreateCertificate(&csprng, &template, x509ca, certpriv.Public(), ca.PrivateKey); err != nil {\n\t\treturn\n\t}\n\treturn &tls.Certificate{\n\t\tCertificate: [][]byte{derBytes, ca.Certificate[0]},\n\t\tPrivateKey:  certpriv,\n\t}, nil\n}\n\nfunc init() {\n\t\/\/ Avoid deterministic random numbers\n\trand.Seed(time.Now().UnixNano())\n}\n<commit_msg>fix issue: #431 (ERR_CERT_VALIDITY_TOO_LONG)<commit_after>package goproxy\n\nimport (\n\t\"crypto\"\n\t\"crypto\/ecdsa\"\n\t\"crypto\/elliptic\"\n\t\"crypto\/rsa\"\n\t\"crypto\/sha1\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"crypto\/x509\/pkix\"\n\t\"fmt\"\n\t\"math\/big\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"runtime\"\n\t\"sort\"\n\t\"time\"\n)\n\nfunc hashSorted(lst []string) []byte {\n\tc := make([]string, len(lst))\n\tcopy(c, lst)\n\tsort.Strings(c)\n\th := sha1.New()\n\tfor _, s := range c {\n\t\th.Write([]byte(s + \",\"))\n\t}\n\treturn h.Sum(nil)\n}\n\nfunc hashSortedBigInt(lst []string) *big.Int {\n\trv := new(big.Int)\n\trv.SetBytes(hashSorted(lst))\n\treturn rv\n}\n\nvar goproxySignerVersion = \":goroxy1\"\n\nfunc signHost(ca tls.Certificate, hosts []string) (cert *tls.Certificate, err error) {\n\tvar x509ca *x509.Certificate\n\n\t\/\/ Use the provided ca and not the global GoproxyCa for certificate generation.\n\tif x509ca, err = x509.ParseCertificate(ca.Certificate[0]); err != nil {\n\t\treturn\n\t}\n\n\tstart := time.Unix(time.Now().Unix()-2592000, 0) \/\/ 2592000  = 30 day\n\tend := time.Unix(time.Now().Unix()+31536000, 0)  \/\/ 31536000 = 365 day\n\n\tserial := big.NewInt(rand.Int63())\n\ttemplate := x509.Certificate{\n\t\t\/\/ TODO(elazar): instead of this ugly hack, just encode the certificate and hash the binary form.\n\t\tSerialNumber: serial,\n\t\tIssuer:       x509ca.Subject,\n\t\tSubject: pkix.Name{\n\t\t\tOrganization: []string{\"GoProxy untrusted MITM proxy Inc\"},\n\t\t},\n\t\tNotBefore: start,\n\t\tNotAfter:  end,\n\n\t\tKeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,\n\t\tExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},\n\t\tBasicConstraintsValid: true,\n\t}\n\tfor _, h := range hosts {\n\t\tif ip := net.ParseIP(h); ip != nil {\n\t\t\ttemplate.IPAddresses = append(template.IPAddresses, ip)\n\t\t} else {\n\t\t\ttemplate.DNSNames = append(template.DNSNames, h)\n\t\t\ttemplate.Subject.CommonName = h\n\t\t}\n\t}\n\n\thash := hashSorted(append(hosts, goproxySignerVersion, \":\"+runtime.Version()))\n\tvar csprng CounterEncryptorRand\n\tif csprng, err = NewCounterEncryptorRandFromKey(ca.PrivateKey, hash); err != nil {\n\t\treturn\n\t}\n\n\tvar certpriv crypto.Signer\n\tswitch ca.PrivateKey.(type) {\n\tcase *rsa.PrivateKey:\n\t\tif certpriv, err = rsa.GenerateKey(&csprng, 2048); err != nil {\n\t\t\treturn\n\t\t}\n\tcase *ecdsa.PrivateKey:\n\t\tif certpriv, err = ecdsa.GenerateKey(elliptic.P256(), &csprng); err != nil {\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\terr = fmt.Errorf(\"unsupported key type %T\", ca.PrivateKey)\n\t}\n\n\tvar derBytes []byte\n\tif derBytes, err = x509.CreateCertificate(&csprng, &template, x509ca, certpriv.Public(), ca.PrivateKey); err != nil {\n\t\treturn\n\t}\n\treturn &tls.Certificate{\n\t\tCertificate: [][]byte{derBytes, ca.Certificate[0]},\n\t\tPrivateKey:  certpriv,\n\t}, nil\n}\n\nfunc init() {\n\t\/\/ Avoid deterministic random numbers\n\trand.Seed(time.Now().UnixNano())\n}\n<|endoftext|>"}
{"text":"<commit_before>package utp\n\n\/*\n#include \"utp.h\"\n*\/\nimport \"C\"\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/anacrolix\/missinggo\/inproc\"\n)\n\ntype Socket struct {\n\tpc            net.PacketConn\n\tctx           *C.utp_context\n\tbacklog       chan *Conn\n\tclosed        bool\n\tconns         map[*C.utp_socket]*Conn\n\tnonUtpReads   chan packet\n\twriteDeadline time.Time\n\treadDeadline  time.Time\n}\n\nvar (\n\t_ net.PacketConn = (*Socket)(nil)\n)\n\ntype packet struct {\n\tb    []byte\n\tfrom net.Addr\n}\n\nfunc listenPacket(network, addr string) (pc net.PacketConn, err error) {\n\tif network == \"inproc\" {\n\t\treturn inproc.ListenPacket(network, addr)\n\t}\n\treturn net.ListenPacket(network, addr)\n}\n\nfunc NewSocket(network, addr string) (*Socket, error) {\n\tpc, err := listenPacket(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tctx := C.utp_init(2)\n\tif ctx == nil {\n\t\tpanic(ctx)\n\t}\n\tctx.setCallbacks()\n\tif utpLogging {\n\t\tctx.setOption(C.UTP_LOG_NORMAL, 1)\n\t\tctx.setOption(C.UTP_LOG_MTU, 1)\n\t\tctx.setOption(C.UTP_LOG_DEBUG, 1)\n\t}\n\ts := &Socket{\n\t\tpc:          pc,\n\t\tctx:         ctx,\n\t\tbacklog:     make(chan *Conn, 5),\n\t\tconns:       make(map[*C.utp_socket]*Conn),\n\t\tnonUtpReads: make(chan packet, 100),\n\t}\n\tlibContextToSocket[ctx] = s\n\tgo s.timeoutChecker()\n\tgo s.packetReader()\n\treturn s, nil\n}\n\nfunc (s *Socket) onLibSocketDestroyed(ls *C.utp_socket) {\n\tdelete(s.conns, ls)\n}\n\nfunc (s *Socket) newConn(us *C.utp_socket) *Conn {\n\tc := &Conn{\n\t\ts: us,\n\t}\n\tc.cond.L = &mu\n\ts.conns[us] = c\n\tc.writeDeadlineTimer = time.AfterFunc(-1, c.cond.Broadcast)\n\tc.readDeadlineTimer = time.AfterFunc(-1, c.cond.Broadcast)\n\treturn c\n}\n\nvar reads int64\n\nfunc (s *Socket) packetReader() {\n\tvar b [0x1000]byte\n\tfor {\n\t\t\/\/ In C, all the reads are processed and when it threatens to block,\n\t\t\/\/ only then do we call utp_issue_deferred_acks. I don't know how we\n\t\t\/\/ can do this in Go.\n\t\tn, addr, err := s.pc.ReadFrom(b[:])\n\t\tif err != nil {\n\t\t\tmu.Lock()\n\t\t\tclosed := s.closed\n\t\t\tmu.Unlock()\n\t\t\tif closed {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tpanic(err)\n\t\t}\n\t\tsa, sal := netAddrToLibSockaddr(addr)\n\t\tatomic.AddInt64(&reads, 1)\n\t\t\/\/ log.Printf(\"received %d bytes, %d packets\", n, reads)\n\t\tfunc() {\n\t\t\tmu.Lock()\n\t\t\tdefer mu.Unlock()\n\t\t\tif s.closed {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tret := C.utp_process_udp(s.ctx, (*C.byte)(&b[0]), C.size_t(n), sa, sal)\n\t\t\tswitch ret {\n\t\t\tcase 1:\n\t\t\t\tsocketUtpPacketsReceived.Add(1)\n\t\t\t\tC.utp_issue_deferred_acks(s.ctx)\n\t\t\t\tC.utp_check_timeouts(s.ctx)\n\t\t\tcase 0:\n\t\t\t\ts.onReadNonUtp(b[:n], addr)\n\t\t\tdefault:\n\t\t\t\tpanic(ret)\n\t\t\t}\n\t\t}()\n\t}\n}\n\nfunc (s *Socket) timeoutChecker() {\n\tfor {\n\t\tmu.Lock()\n\t\tif s.closed {\n\t\t\tmu.Unlock()\n\t\t\treturn\n\t\t}\n\t\t\/\/ C.utp_issue_deferred_acks(s.ctx)\n\t\tC.utp_check_timeouts(s.ctx)\n\t\tmu.Unlock()\n\t\ttime.Sleep(500 * time.Millisecond)\n\t}\n}\n\nfunc (me *Socket) Close() error {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tif me.closed {\n\t\treturn nil\n\t}\n\t\/\/ Calling this deletes the pointer. It must not be referred to after\n\t\/\/ this.\n\tC.utp_destroy(me.ctx)\n\tme.ctx = nil\n\tme.pc.Close()\n\tclose(me.backlog)\n\tclose(me.nonUtpReads)\n\tme.closed = true\n\treturn nil\n}\n\nfunc (me *Socket) Addr() net.Addr {\n\treturn me.pc.LocalAddr()\n}\n\nfunc (me *Socket) LocalAddr() net.Addr {\n\treturn me.pc.LocalAddr()\n}\n\nfunc (s *Socket) Accept() (net.Conn, error) {\n\tnc, ok := <-s.backlog\n\tif !ok {\n\t\treturn nil, errors.New(\"closed\")\n\t}\n\treturn nc, nil\n}\n\nfunc (s *Socket) Dial(addr string) (net.Conn, error) {\n\treturn s.DialTimeout(addr, 0)\n}\n\nfunc (s *Socket) DialTimeout(addr string, timeout time.Duration) (net.Conn, error) {\n\tctx := context.Background()\n\tif timeout != 0 {\n\t\tvar cancel context.CancelFunc\n\t\tctx, cancel = context.WithTimeout(ctx, timeout)\n\t\tdefer cancel()\n\t}\n\treturn s.DialContext(ctx, addr)\n}\n\nfunc (s *Socket) resolveAddr(addr string) (net.Addr, error) {\n\tn := s.Addr().Network()\n\tswitch n {\n\tcase \"inproc\":\n\t\treturn inproc.ResolveAddr(n, addr)\n\tdefault:\n\t\treturn net.ResolveUDPAddr(n, addr)\n\t}\n}\n\nfunc (s *Socket) DialContext(ctx context.Context, addr string) (net.Conn, error) {\n\tua, err := s.resolveAddr(addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsa, sl := netAddrToLibSockaddr(ua)\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tif s.closed {\n\t\treturn nil, errors.New(\"socket closed\")\n\t}\n\tc := s.newConn(C.utp_create_socket(s.ctx))\n\tC.utp_connect(c.s, sa, sl)\n\terr = c.waitForConnect(ctx)\n\tif err != nil {\n\t\tc.close()\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}\n\nfunc (s *Socket) pushBacklog(c *Conn) {\n\tselect {\n\tcase s.backlog <- c:\n\tdefault:\n\t\tc.close()\n\t}\n}\n\nfunc (s *Socket) ReadFrom(b []byte) (n int, addr net.Addr, err error) {\n\tp, ok := <-s.nonUtpReads\n\tif !ok {\n\t\terr = errors.New(\"closed\")\n\t\treturn\n\t}\n\tn = copy(b, p.b)\n\taddr = p.from\n\treturn\n}\n\nfunc (s *Socket) onReadNonUtp(b []byte, from net.Addr) {\n\tsocketNonUtpPacketsReceived.Add(1)\n\tselect {\n\tcase s.nonUtpReads <- packet{append([]byte(nil), b...), from}:\n\tdefault:\n\t\t\/\/ log.Printf(\"dropped non utp packet: no room in buffer\")\n\t\tnonUtpPacketsDropped.Add(1)\n\t}\n}\n\nfunc (s *Socket) SetReadDeadline(t time.Time) error {\n\tpanic(\"not implemented\")\n}\n\nfunc (s *Socket) SetWriteDeadline(t time.Time) error {\n\tpanic(\"not implemented\")\n}\n\nfunc (s *Socket) SetDeadline(t time.Time) error {\n\tpanic(\"not implemented\")\n}\n\nfunc (s *Socket) WriteTo(b []byte, addr net.Addr) (int, error) {\n\treturn s.pc.WriteTo(b, addr)\n}\n\nfunc (s *Socket) ReadBufferLen() int {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\treturn int(C.utp_context_get_option(s.ctx, C.UTP_RCVBUF))\n}\n\nfunc (s *Socket) WriteBufferLen() int {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\treturn int(C.utp_context_get_option(s.ctx, C.UTP_SNDBUF))\n}\n\nfunc (s *Socket) SetWriteBufferLen(len int) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\ti := C.utp_context_set_option(s.ctx, C.UTP_SNDBUF, C.int(len))\n\tif i != 0 {\n\t\tpanic(i)\n\t}\n}\n<commit_msg>Add workaround for https:\/\/github.com\/anacrolix\/torrent\/issues\/83<commit_after>package utp\n\n\/*\n#include \"utp.h\"\n*\/\nimport \"C\"\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"log\"\n\t\"net\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/anacrolix\/missinggo\/inproc\"\n)\n\ntype Socket struct {\n\tpc            net.PacketConn\n\tctx           *C.utp_context\n\tbacklog       chan *Conn\n\tclosed        bool\n\tconns         map[*C.utp_socket]*Conn\n\tnonUtpReads   chan packet\n\twriteDeadline time.Time\n\treadDeadline  time.Time\n}\n\nvar (\n\t_ net.PacketConn = (*Socket)(nil)\n)\n\ntype packet struct {\n\tb    []byte\n\tfrom net.Addr\n}\n\nfunc listenPacket(network, addr string) (pc net.PacketConn, err error) {\n\tif network == \"inproc\" {\n\t\treturn inproc.ListenPacket(network, addr)\n\t}\n\treturn net.ListenPacket(network, addr)\n}\n\nfunc NewSocket(network, addr string) (*Socket, error) {\n\tpc, err := listenPacket(network, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tctx := C.utp_init(2)\n\tif ctx == nil {\n\t\tpanic(ctx)\n\t}\n\tctx.setCallbacks()\n\tif utpLogging {\n\t\tctx.setOption(C.UTP_LOG_NORMAL, 1)\n\t\tctx.setOption(C.UTP_LOG_MTU, 1)\n\t\tctx.setOption(C.UTP_LOG_DEBUG, 1)\n\t}\n\ts := &Socket{\n\t\tpc:          pc,\n\t\tctx:         ctx,\n\t\tbacklog:     make(chan *Conn, 5),\n\t\tconns:       make(map[*C.utp_socket]*Conn),\n\t\tnonUtpReads: make(chan packet, 100),\n\t}\n\tlibContextToSocket[ctx] = s\n\tgo s.timeoutChecker()\n\tgo s.packetReader()\n\treturn s, nil\n}\n\nfunc (s *Socket) onLibSocketDestroyed(ls *C.utp_socket) {\n\tdelete(s.conns, ls)\n}\n\nfunc (s *Socket) newConn(us *C.utp_socket) *Conn {\n\tc := &Conn{\n\t\ts: us,\n\t}\n\tc.cond.L = &mu\n\ts.conns[us] = c\n\tc.writeDeadlineTimer = time.AfterFunc(-1, c.cond.Broadcast)\n\tc.readDeadlineTimer = time.AfterFunc(-1, c.cond.Broadcast)\n\treturn c\n}\n\nvar reads int64\n\nfunc (s *Socket) packetReader() {\n\tvar b [0x1000]byte\n\tfor {\n\t\t\/\/ In C, all the reads are processed and when it threatens to block,\n\t\t\/\/ only then do we call utp_issue_deferred_acks. I don't know how we\n\t\t\/\/ can do this in Go.\n\t\tn, addr, err := s.pc.ReadFrom(b[:])\n\t\tif err != nil {\n\t\t\tmu.Lock()\n\t\t\tclosed := s.closed\n\t\t\tmu.Unlock()\n\t\t\tif closed {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ See https:\/\/github.com\/anacrolix\/torrent\/issues\/83. If we get\n\t\t\t\/\/ an endless stream of errors (such as the PacketConn being\n\t\t\t\/\/ Closed outside of our control, this work around may need to be\n\t\t\t\/\/ reconsidered.\n\t\t\tlog.Print(err)\n\t\t\tcontinue\n\t\t}\n\t\tsa, sal := netAddrToLibSockaddr(addr)\n\t\tatomic.AddInt64(&reads, 1)\n\t\t\/\/ log.Printf(\"received %d bytes, %d packets\", n, reads)\n\t\tfunc() {\n\t\t\tmu.Lock()\n\t\t\tdefer mu.Unlock()\n\t\t\tif s.closed {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tret := C.utp_process_udp(s.ctx, (*C.byte)(&b[0]), C.size_t(n), sa, sal)\n\t\t\tswitch ret {\n\t\t\tcase 1:\n\t\t\t\tsocketUtpPacketsReceived.Add(1)\n\t\t\t\tC.utp_issue_deferred_acks(s.ctx)\n\t\t\t\tC.utp_check_timeouts(s.ctx)\n\t\t\tcase 0:\n\t\t\t\ts.onReadNonUtp(b[:n], addr)\n\t\t\tdefault:\n\t\t\t\tpanic(ret)\n\t\t\t}\n\t\t}()\n\t}\n}\n\nfunc (s *Socket) timeoutChecker() {\n\tfor {\n\t\tmu.Lock()\n\t\tif s.closed {\n\t\t\tmu.Unlock()\n\t\t\treturn\n\t\t}\n\t\t\/\/ C.utp_issue_deferred_acks(s.ctx)\n\t\tC.utp_check_timeouts(s.ctx)\n\t\tmu.Unlock()\n\t\ttime.Sleep(500 * time.Millisecond)\n\t}\n}\n\nfunc (me *Socket) Close() error {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tif me.closed {\n\t\treturn nil\n\t}\n\t\/\/ Calling this deletes the pointer. It must not be referred to after\n\t\/\/ this.\n\tC.utp_destroy(me.ctx)\n\tme.ctx = nil\n\tme.pc.Close()\n\tclose(me.backlog)\n\tclose(me.nonUtpReads)\n\tme.closed = true\n\treturn nil\n}\n\nfunc (me *Socket) Addr() net.Addr {\n\treturn me.pc.LocalAddr()\n}\n\nfunc (me *Socket) LocalAddr() net.Addr {\n\treturn me.pc.LocalAddr()\n}\n\nfunc (s *Socket) Accept() (net.Conn, error) {\n\tnc, ok := <-s.backlog\n\tif !ok {\n\t\treturn nil, errors.New(\"closed\")\n\t}\n\treturn nc, nil\n}\n\nfunc (s *Socket) Dial(addr string) (net.Conn, error) {\n\treturn s.DialTimeout(addr, 0)\n}\n\nfunc (s *Socket) DialTimeout(addr string, timeout time.Duration) (net.Conn, error) {\n\tctx := context.Background()\n\tif timeout != 0 {\n\t\tvar cancel context.CancelFunc\n\t\tctx, cancel = context.WithTimeout(ctx, timeout)\n\t\tdefer cancel()\n\t}\n\treturn s.DialContext(ctx, addr)\n}\n\nfunc (s *Socket) resolveAddr(addr string) (net.Addr, error) {\n\tn := s.Addr().Network()\n\tswitch n {\n\tcase \"inproc\":\n\t\treturn inproc.ResolveAddr(n, addr)\n\tdefault:\n\t\treturn net.ResolveUDPAddr(n, addr)\n\t}\n}\n\nfunc (s *Socket) DialContext(ctx context.Context, addr string) (net.Conn, error) {\n\tua, err := s.resolveAddr(addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsa, sl := netAddrToLibSockaddr(ua)\n\tmu.Lock()\n\tdefer mu.Unlock()\n\tif s.closed {\n\t\treturn nil, errors.New(\"socket closed\")\n\t}\n\tc := s.newConn(C.utp_create_socket(s.ctx))\n\tC.utp_connect(c.s, sa, sl)\n\terr = c.waitForConnect(ctx)\n\tif err != nil {\n\t\tc.close()\n\t\treturn nil, err\n\t}\n\treturn c, nil\n}\n\nfunc (s *Socket) pushBacklog(c *Conn) {\n\tselect {\n\tcase s.backlog <- c:\n\tdefault:\n\t\tc.close()\n\t}\n}\n\nfunc (s *Socket) ReadFrom(b []byte) (n int, addr net.Addr, err error) {\n\tp, ok := <-s.nonUtpReads\n\tif !ok {\n\t\terr = errors.New(\"closed\")\n\t\treturn\n\t}\n\tn = copy(b, p.b)\n\taddr = p.from\n\treturn\n}\n\nfunc (s *Socket) onReadNonUtp(b []byte, from net.Addr) {\n\tsocketNonUtpPacketsReceived.Add(1)\n\tselect {\n\tcase s.nonUtpReads <- packet{append([]byte(nil), b...), from}:\n\tdefault:\n\t\t\/\/ log.Printf(\"dropped non utp packet: no room in buffer\")\n\t\tnonUtpPacketsDropped.Add(1)\n\t}\n}\n\nfunc (s *Socket) SetReadDeadline(t time.Time) error {\n\tpanic(\"not implemented\")\n}\n\nfunc (s *Socket) SetWriteDeadline(t time.Time) error {\n\tpanic(\"not implemented\")\n}\n\nfunc (s *Socket) SetDeadline(t time.Time) error {\n\tpanic(\"not implemented\")\n}\n\nfunc (s *Socket) WriteTo(b []byte, addr net.Addr) (int, error) {\n\treturn s.pc.WriteTo(b, addr)\n}\n\nfunc (s *Socket) ReadBufferLen() int {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\treturn int(C.utp_context_get_option(s.ctx, C.UTP_RCVBUF))\n}\n\nfunc (s *Socket) WriteBufferLen() int {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\treturn int(C.utp_context_get_option(s.ctx, C.UTP_SNDBUF))\n}\n\nfunc (s *Socket) SetWriteBufferLen(len int) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\ti := C.utp_context_set_option(s.ctx, C.UTP_SNDBUF, C.int(len))\n\tif i != 0 {\n\t\tpanic(i)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package peco\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/lestrrat\/go-pdebug\"\n\t\"github.com\/peco\/peco\/internal\/util\"\n\t\"github.com\/peco\/peco\/pipeline\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ Creates a new Source. Does not start processing the input until you\n\/\/ call Setup()\nfunc NewSource(in io.Reader, idgen lineIDGenerator, capacity int, enableSep bool) *Source {\n\ts := &Source{\n\t\tin:            in, \/\/ Note that this may be closed, so do not rely on it\n\t\tcapacity:      capacity,\n\t\tenableSep:     enableSep,\n\t\tidgen:         idgen,\n\t\tready:         make(chan struct{}),\n\t\tsetupDone:     make(chan struct{}),\n\t\tsetupOnce:     sync.Once{},\n\t\tOutputChannel: pipeline.OutputChannel(make(chan interface{})),\n\t}\n\ts.Reset()\n\treturn s\n}\n\n\/\/ Setup reads from the input os.File.\nfunc (s *Source) Setup(ctx context.Context, state *Peco) {\n\ts.setupOnce.Do(func() {\n\t\tdone := make(chan struct{})\n\t\trefresh := make(chan struct{}, 1)\n\t\tdefer close(done)\n\t\tdefer close(refresh)\n\t\t\/\/ And also, close the done channel so we can tell the consumers\n\t\t\/\/ we have finished reading everything\n\t\tdefer close(s.setupDone)\n\n\t\tdraw := func(state *Peco) {\n\t\t\tstate.Hub().SendDraw(nil)\n\t\t}\n\n\t\tgo func() {\n\t\t\tticker := time.NewTicker(100 * time.Millisecond)\n\t\t\tdefer ticker.Stop()\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-done:\n\t\t\t\t\tdraw(state)\n\t\t\t\t\treturn\n\t\t\t\tcase <-ticker.C:\n\t\t\t\t\tdraw(state)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t\/\/ This sync.Once var is used to receive the notification\n\t\t\/\/ that there was at least 1 line read from the source\n\t\t\/\/ This is wrapped in a sync.Notify so we can safely call\n\t\t\/\/ it in multiple places\n\t\tvar notify sync.Once\n\t\tnotifycb := func() {\n\t\t\t\/\/ close the ready channel so others can be notified\n\t\t\t\/\/ that there's at least 1 line in the buffer\n\t\t\tstate.Hub().SendStatusMsg(\"\")\n\t\t\tclose(s.ready)\n\t\t}\n\n\t\t\/\/ Register this to be called in a defer, just in case we could bailed\n\t\t\/\/ out without reading a single line.\n\t\t\/\/ Note: this will be a no-op if notify.Do has been called before\n\t\tdefer notify.Do(notifycb)\n\n\t\tscanner := bufio.NewScanner(s.in)\n\t\tdefer func() {\n\t\t\tif util.IsTty(s.in) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif closer, ok := s.in.(io.Closer); ok {\n\t\t\t\tcloser.Close()\n\t\t\t}\n\t\t}()\n\n\t\tlines := make(chan string)\n\t\tgo func() {\n\t\t\tdefer close(lines)\n\t\t\tfor scanner.Scan() {\n\t\t\t\tlines <- scanner.Text()\n\t\t\t}\n\t\t}()\n\n\t\tstate.Hub().SendStatusMsg(\"Waiting for input...\")\n\n\t\treadCount := 0\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tif pdebug.Enabled {\n\t\t\t\t\tpdebug.Printf(\"Bailing out of source setup, because ctx was canceled\")\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase l, ok := <-lines:\n\t\t\t\tif !ok {\n\t\t\t\t\tif pdebug.Enabled {\n\t\t\t\t\t\tpdebug.Printf(\"No more lines to read...\")\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\treadCount++\n\t\t\t\ts.Append(NewRawLine(s.idgen.next(), l, s.enableSep))\n\t\t\t\tnotify.Do(notifycb)\n\t\t\t}\n\t\t}\n\n\t\tif pdebug.Enabled {\n\t\t\tpdebug.Printf(\"Read all %d lines from source\", readCount)\n\t\t}\n\t})\n}\n\n\/\/ Start starts\nfunc (s *Source) Start(ctx context.Context, out pipeline.OutputChannel) {\n\t\/\/ I should be the only one running this method until I bail out\n\tif pdebug.Enabled {\n\t\tg := pdebug.Marker(\"Source.Start\")\n\t\tdefer g.End()\n\t\tdefer pdebug.Printf(\"Source sent %d lines\", len(s.lines))\n\t}\n\n\tfor _, l := range s.lines {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tif pdebug.Enabled {\n\t\t\t\tpdebug.Printf(\"Source: context.Done detected\")\n\t\t\t}\n\t\t\treturn\n\t\tdefault:\n\t\t\tout.Send(l)\n\t\t}\n\t}\n\tout.SendEndMark(\"end of input\")\n}\n\n\/\/ Reset resets the state of the source object so that it\n\/\/ is ready to feed the filters\nfunc (s *Source) Reset() {\n\tif pdebug.Enabled {\n\t\tg := pdebug.Marker(\"Source.Reset\")\n\t\tdefer g.End()\n\t}\n\ts.OutputChannel = pipeline.OutputChannel(make(chan interface{}))\n}\n\n\/\/ Ready returns the \"input ready\" channel. It will be closed as soon as\n\/\/ the first line of input is processed via Setup()\nfunc (s *Source) Ready() <-chan struct{} {\n\treturn s.ready\n}\n\n\/\/ SetupDone returns the \"read all lines\" channel. It will be closed as soon as\n\/\/ the all input has been read\nfunc (s *Source) SetupDone() <-chan struct{} {\n\treturn s.setupDone\n}\n\nfunc (s *Source) LineAt(n int) (Line, error) {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\treturn bufferLineAt(s.lines, n)\n}\n\nfunc (s *Source) Size() int {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\treturn bufferSize(s.lines)\n}\n\nfunc (s *Source) Append(l Line) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tbufferAppend(&s.lines, l)\n\tif s.capacity > 0 && len(s.lines) > s.capacity {\n\t\tdiff := len(s.lines) - s.capacity\n\n\t\t\/\/ Golang's version of array realloc\n\t\ts.lines = s.lines[diff:s.capacity:s.capacity]\n\t}\n}\n<commit_msg>seems like we failed to bail out of the for<commit_after>package peco\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/lestrrat\/go-pdebug\"\n\t\"github.com\/peco\/peco\/internal\/util\"\n\t\"github.com\/peco\/peco\/pipeline\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ Creates a new Source. Does not start processing the input until you\n\/\/ call Setup()\nfunc NewSource(in io.Reader, idgen lineIDGenerator, capacity int, enableSep bool) *Source {\n\ts := &Source{\n\t\tin:            in, \/\/ Note that this may be closed, so do not rely on it\n\t\tcapacity:      capacity,\n\t\tenableSep:     enableSep,\n\t\tidgen:         idgen,\n\t\tready:         make(chan struct{}),\n\t\tsetupDone:     make(chan struct{}),\n\t\tsetupOnce:     sync.Once{},\n\t\tOutputChannel: pipeline.OutputChannel(make(chan interface{})),\n\t}\n\ts.Reset()\n\treturn s\n}\n\n\/\/ Setup reads from the input os.File.\nfunc (s *Source) Setup(ctx context.Context, state *Peco) {\n\ts.setupOnce.Do(func() {\n\t\tdone := make(chan struct{})\n\t\trefresh := make(chan struct{}, 1)\n\t\tdefer close(done)\n\t\tdefer close(refresh)\n\t\t\/\/ And also, close the done channel so we can tell the consumers\n\t\t\/\/ we have finished reading everything\n\t\tdefer close(s.setupDone)\n\n\t\tdraw := func(state *Peco) {\n\t\t\tstate.Hub().SendDraw(nil)\n\t\t}\n\n\t\tgo func() {\n\t\t\tticker := time.NewTicker(100 * time.Millisecond)\n\t\t\tdefer ticker.Stop()\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-done:\n\t\t\t\t\tdraw(state)\n\t\t\t\t\treturn\n\t\t\t\tcase <-ticker.C:\n\t\t\t\t\tdraw(state)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t\/\/ This sync.Once var is used to receive the notification\n\t\t\/\/ that there was at least 1 line read from the source\n\t\t\/\/ This is wrapped in a sync.Notify so we can safely call\n\t\t\/\/ it in multiple places\n\t\tvar notify sync.Once\n\t\tnotifycb := func() {\n\t\t\t\/\/ close the ready channel so others can be notified\n\t\t\t\/\/ that there's at least 1 line in the buffer\n\t\t\tstate.Hub().SendStatusMsg(\"\")\n\t\t\tclose(s.ready)\n\t\t}\n\n\t\t\/\/ Register this to be called in a defer, just in case we could bailed\n\t\t\/\/ out without reading a single line.\n\t\t\/\/ Note: this will be a no-op if notify.Do has been called before\n\t\tdefer notify.Do(notifycb)\n\n\t\tscanner := bufio.NewScanner(s.in)\n\t\tdefer func() {\n\t\t\tif util.IsTty(s.in) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif closer, ok := s.in.(io.Closer); ok {\n\t\t\t\tcloser.Close()\n\t\t\t}\n\t\t}()\n\n\t\tlines := make(chan string)\n\t\tgo func() {\n\t\t\tdefer close(lines)\n\t\t\tfor scanner.Scan() {\n\t\t\t\tlines <- scanner.Text()\n\t\t\t}\n\t\t}()\n\n\t\tstate.Hub().SendStatusMsg(\"Waiting for input...\")\n\n\t\treadCount := 0\n\t\tfor loop := true; loop; {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tif pdebug.Enabled {\n\t\t\t\t\tpdebug.Printf(\"Bailing out of source setup, because ctx was canceled\")\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase l, ok := <-lines:\n\t\t\t\tif !ok {\n\t\t\t\t\tif pdebug.Enabled {\n\t\t\t\t\t\tpdebug.Printf(\"No more lines to read...\")\n\t\t\t\t\t}\n\t\t\t\t\tloop = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\treadCount++\n\t\t\t\ts.Append(NewRawLine(s.idgen.next(), l, s.enableSep))\n\t\t\t\tnotify.Do(notifycb)\n\t\t\t}\n\t\t}\n\n\t\tif pdebug.Enabled {\n\t\t\tpdebug.Printf(\"Read all %d lines from source\", readCount)\n\t\t}\n\t})\n}\n\n\/\/ Start starts\nfunc (s *Source) Start(ctx context.Context, out pipeline.OutputChannel) {\n\t\/\/ I should be the only one running this method until I bail out\n\tif pdebug.Enabled {\n\t\tg := pdebug.Marker(\"Source.Start\")\n\t\tdefer g.End()\n\t\tdefer pdebug.Printf(\"Source sent %d lines\", len(s.lines))\n\t}\n\n\tfor _, l := range s.lines {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tif pdebug.Enabled {\n\t\t\t\tpdebug.Printf(\"Source: context.Done detected\")\n\t\t\t}\n\t\t\treturn\n\t\tdefault:\n\t\t\tout.Send(l)\n\t\t}\n\t}\n\tout.SendEndMark(\"end of input\")\n}\n\n\/\/ Reset resets the state of the source object so that it\n\/\/ is ready to feed the filters\nfunc (s *Source) Reset() {\n\tif pdebug.Enabled {\n\t\tg := pdebug.Marker(\"Source.Reset\")\n\t\tdefer g.End()\n\t}\n\ts.OutputChannel = pipeline.OutputChannel(make(chan interface{}))\n}\n\n\/\/ Ready returns the \"input ready\" channel. It will be closed as soon as\n\/\/ the first line of input is processed via Setup()\nfunc (s *Source) Ready() <-chan struct{} {\n\treturn s.ready\n}\n\n\/\/ SetupDone returns the \"read all lines\" channel. It will be closed as soon as\n\/\/ the all input has been read\nfunc (s *Source) SetupDone() <-chan struct{} {\n\treturn s.setupDone\n}\n\nfunc (s *Source) LineAt(n int) (Line, error) {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\treturn bufferLineAt(s.lines, n)\n}\n\nfunc (s *Source) Size() int {\n\ts.mutex.RLock()\n\tdefer s.mutex.RUnlock()\n\treturn bufferSize(s.lines)\n}\n\nfunc (s *Source) Append(l Line) {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\n\tbufferAppend(&s.lines, l)\n\tif s.capacity > 0 && len(s.lines) > s.capacity {\n\t\tdiff := len(s.lines) - s.capacity\n\n\t\t\/\/ Golang's version of array realloc\n\t\ts.lines = s.lines[diff:s.capacity:s.capacity]\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package platform\n\nimport (\n\t\"context\"\n\t\"fmt\"\n)\n\ntype Error string\n\nfunc (e Error) Error() string {\n\treturn string(e)\n}\n\nconst (\n\tErrSourceNotFound = Error(\"source not found\")\n)\n\n\/\/ SourceType is a string for types of sources.\ntype SourceType string\n\nconst (\n\tV2SourceType   = \"v2\"\n\tV1SourceType   = \"v1\"\n\tSelfSourceType = \"self\"\n)\n\n\/\/ Source is an external Influx with time series data.\n\/\/ TODO(desa): do we still need default?\n\/\/ TODO(desa): do sources belong\ntype Source struct {\n\tID                 ID         `json:\"id,string\"`                    \/\/ ID is the unique ID of the source\n\tOrganizationID     ID         `json:\"organizationID\"`               \/\/ OrganizationID is the organization ID that resource belongs to\n\tDefault            bool       `json:\"default\"`                      \/\/ Default specifies the default source for the application\n\tName               string     `json:\"name\"`                         \/\/ Name is the user-defined name for the source\n\tType               SourceType `json:\"type,omitempty\"`               \/\/ Type specifies which kinds of source (enterprise vs oss vs 2.0)\n\tURL                string     `json:\"url\"`                          \/\/ URL are the connections to the source\n\tInsecureSkipVerify bool       `json:\"insecureSkipVerify,omitempty\"` \/\/ InsecureSkipVerify as true means any certificate presented by the source is accepted\n\tTelegraf           string     `json:\"telegraf\"`                     \/\/ Telegraf is the db telegraf is written to.  By default it is \"telegraf\"\n\tSourceFields\n\tV1SourceFields\n\n\tBucketService BucketService `json:\"-\"`\n\t\/\/ TODO(desa): is this a good idea?\n\tSourceQuerier SourceQuerier `json:\"-\"`\n}\n\n\/\/ V1SourceFields are the fields for connecting to a 1.0 source (oss or enterprise)\ntype V1SourceFields struct {\n\tUsername     string `json:\"username,omitempty\"`     \/\/ Username is the username to connect to the source\n\tPassword     string `json:\"password,omitempty\"`     \/\/ Password is in CLEARTEXT\n\tSharedSecret string `json:\"sharedSecret,omitempty\"` \/\/ ShareSecret is the optional signing secret for Influx JWT authorization\n\tMetaURL      string `json:\"metaUrl,omitempty\"`      \/\/ MetaURL is the url for the meta node\n\tDefaultRP    string `json:\"defaultRP\"`              \/\/ DefaultRP is the default retention policy used in database queries to this source\n\tFluxURL      string `json:\"fluxURL,omitempty\"`      \/\/ FluxURL is the url for a flux connected to a 1x source\n}\n\n\/\/ SourceFields\ntype SourceFields struct {\n\tToken string `json:\"token\"` \/\/ Token is the 2.0 authorization token associated with a source\n}\n\n\/\/ SourceService is a service for managing sources.\ntype SourceService interface {\n\t\/\/ DefaultSource retrieves the default source.\n\tDefaultSource(ctx context.Context) (*Source, error)\n\t\/\/ FindSourceByID retrieves a source by its ID.\n\tFindSourceByID(ctx context.Context, id ID) (*Source, error)\n\t\/\/ FindSources returns a list of all sources.\n\tFindSources(ctx context.Context, opts FindOptions) ([]*Source, int, error)\n\t\/\/ CreateSource sets the sources ID and stores it.\n\tCreateSource(ctx context.Context, s *Source) error\n\t\/\/ UpdateSource updates the source.\n\tUpdateSource(ctx context.Context, id ID, upd SourceUpdate) (*Source, error)\n\t\/\/ DeleteSource removes the source.\n\tDeleteSource(ctx context.Context, id ID) error\n}\n\n\/\/ SourceUpdate represents updates to a source.\ntype SourceUpdate struct {\n\tName               *string     `json:\"name\"`\n\tType               *SourceType `json:\"type,omitempty\"`\n\tToken              *string     `json:\"token\"`\n\tURL                *string     `json:\"url\"`\n\tInsecureSkipVerify *bool       `json:\"insecureSkipVerify,omitempty\"`\n\tTelegraf           *string     `json:\"telegraf\"`\n\tUsername           *string     `json:\"username,omitempty\"`\n\tPassword           *string     `json:\"password,omitempty\"`\n\tSharedSecret       *string     `json:\"sharedSecret,omitempty\"`\n\tMetaURL            *string     `json:\"metaURL,omitempty\"`\n\tFluxURL            *string     `json:\"fluxURL,omitempty\"`\n\tRole               *string     `json:\"role,omitempty\"`\n\tDefaultRP          *string     `json:\"defaultRP\"`\n}\n\n\/\/ Apply applies an update to a source.\nfunc (u SourceUpdate) Apply(s *Source) error {\n\tif u.Name != nil {\n\t\ts.Name = *u.Name\n\t}\n\tif u.Type != nil {\n\t\ts.Type = *u.Type\n\t}\n\tif u.Token != nil {\n\t\ts.Token = *u.Token\n\t}\n\tif u.URL != nil {\n\t\ts.URL = *u.URL\n\t}\n\tif u.InsecureSkipVerify != nil {\n\t\ts.InsecureSkipVerify = *u.InsecureSkipVerify\n\t}\n\tif u.Telegraf != nil {\n\t\ts.Telegraf = *u.Telegraf\n\t}\n\tif u.Username != nil {\n\t\ts.Username = *u.Username\n\t}\n\tif u.Password != nil {\n\t\ts.Password = *u.Password\n\t}\n\tif u.SharedSecret != nil {\n\t\ts.SharedSecret = *u.SharedSecret\n\t}\n\tif u.MetaURL != nil {\n\t\ts.MetaURL = *u.MetaURL\n\t}\n\tif u.FluxURL != nil {\n\t\ts.FluxURL = *u.FluxURL\n\t}\n\tif u.DefaultRP != nil {\n\t\ts.DefaultRP = *u.DefaultRP\n\t}\n\n\treturn nil\n}\nfunc (s *Source) FindBucketByID(ctx context.Context, id ID) (*Bucket, error) {\n\tif s.BucketService == nil {\n\t\treturn nil, fmt.Errorf(\"not supported\")\n\t}\n\treturn s.BucketService.FindBucketByID(ctx, id)\n}\n\nfunc (s *Source) FindBucket(ctx context.Context, filter BucketFilter) (*Bucket, error) {\n\tif s.BucketService == nil {\n\t\treturn nil, fmt.Errorf(\"not supported\")\n\t}\n\treturn s.BucketService.FindBucket(ctx, filter)\n}\n\nfunc (s *Source) FindBuckets(ctx context.Context, filter BucketFilter, opt ...FindOptions) ([]*Bucket, int, error) {\n\tif s.BucketService == nil {\n\t\treturn nil, 0, fmt.Errorf(\"not supported\")\n\t}\n\treturn s.BucketService.FindBuckets(ctx, filter, opt...)\n}\n\nfunc (s *Source) CreateBucket(ctx context.Context, b *Bucket) error {\n\tif s.BucketService == nil {\n\t\treturn fmt.Errorf(\"not supported\")\n\t}\n\treturn s.BucketService.CreateBucket(ctx, b)\n}\n\nfunc (s *Source) UpdateBucket(ctx context.Context, id ID, upd BucketUpdate) (*Bucket, error) {\n\tif s.BucketService == nil {\n\t\treturn nil, fmt.Errorf(\"not supported\")\n\t}\n\treturn s.BucketService.UpdateBucket(ctx, id, upd)\n}\n\nfunc (s *Source) DeleteBucket(ctx context.Context, id ID) error {\n\tif s.BucketService == nil {\n\t\treturn fmt.Errorf(\"not supported\")\n\t}\n\treturn s.BucketService.DeleteBucket(ctx, id)\n}\n<commit_msg>feat(platform): ensure that Source implements query interface<commit_after>package platform\n\nimport (\n\t\"context\"\n\t\"fmt\"\n)\n\ntype Error string\n\nfunc (e Error) Error() string {\n\treturn string(e)\n}\n\nconst (\n\tErrSourceNotFound = Error(\"source not found\")\n)\n\n\/\/ SourceType is a string for types of sources.\ntype SourceType string\n\nconst (\n\tV2SourceType   = \"v2\"\n\tV1SourceType   = \"v1\"\n\tSelfSourceType = \"self\"\n)\n\n\/\/ Source is an external Influx with time series data.\n\/\/ TODO(desa): do we still need default?\n\/\/ TODO(desa): do sources belong\ntype Source struct {\n\tID                 ID         `json:\"id,string\"`                    \/\/ ID is the unique ID of the source\n\tOrganizationID     ID         `json:\"organizationID\"`               \/\/ OrganizationID is the organization ID that resource belongs to\n\tDefault            bool       `json:\"default\"`                      \/\/ Default specifies the default source for the application\n\tName               string     `json:\"name\"`                         \/\/ Name is the user-defined name for the source\n\tType               SourceType `json:\"type,omitempty\"`               \/\/ Type specifies which kinds of source (enterprise vs oss vs 2.0)\n\tURL                string     `json:\"url\"`                          \/\/ URL are the connections to the source\n\tInsecureSkipVerify bool       `json:\"insecureSkipVerify,omitempty\"` \/\/ InsecureSkipVerify as true means any certificate presented by the source is accepted\n\tTelegraf           string     `json:\"telegraf\"`                     \/\/ Telegraf is the db telegraf is written to.  By default it is \"telegraf\"\n\tSourceFields\n\tV1SourceFields\n\n\tBucketService BucketService `json:\"-\"`\n\t\/\/ TODO(desa): is this a good idea?\n\tSourceQuerier SourceQuerier `json:\"-\"`\n}\n\n\/\/ V1SourceFields are the fields for connecting to a 1.0 source (oss or enterprise)\ntype V1SourceFields struct {\n\tUsername     string `json:\"username,omitempty\"`     \/\/ Username is the username to connect to the source\n\tPassword     string `json:\"password,omitempty\"`     \/\/ Password is in CLEARTEXT\n\tSharedSecret string `json:\"sharedSecret,omitempty\"` \/\/ ShareSecret is the optional signing secret for Influx JWT authorization\n\tMetaURL      string `json:\"metaUrl,omitempty\"`      \/\/ MetaURL is the url for the meta node\n\tDefaultRP    string `json:\"defaultRP\"`              \/\/ DefaultRP is the default retention policy used in database queries to this source\n\tFluxURL      string `json:\"fluxURL,omitempty\"`      \/\/ FluxURL is the url for a flux connected to a 1x source\n}\n\n\/\/ SourceFields\ntype SourceFields struct {\n\tToken string `json:\"token\"` \/\/ Token is the 2.0 authorization token associated with a source\n}\n\n\/\/ SourceService is a service for managing sources.\ntype SourceService interface {\n\t\/\/ DefaultSource retrieves the default source.\n\tDefaultSource(ctx context.Context) (*Source, error)\n\t\/\/ FindSourceByID retrieves a source by its ID.\n\tFindSourceByID(ctx context.Context, id ID) (*Source, error)\n\t\/\/ FindSources returns a list of all sources.\n\tFindSources(ctx context.Context, opts FindOptions) ([]*Source, int, error)\n\t\/\/ CreateSource sets the sources ID and stores it.\n\tCreateSource(ctx context.Context, s *Source) error\n\t\/\/ UpdateSource updates the source.\n\tUpdateSource(ctx context.Context, id ID, upd SourceUpdate) (*Source, error)\n\t\/\/ DeleteSource removes the source.\n\tDeleteSource(ctx context.Context, id ID) error\n}\n\n\/\/ SourceUpdate represents updates to a source.\ntype SourceUpdate struct {\n\tName               *string     `json:\"name\"`\n\tType               *SourceType `json:\"type,omitempty\"`\n\tToken              *string     `json:\"token\"`\n\tURL                *string     `json:\"url\"`\n\tInsecureSkipVerify *bool       `json:\"insecureSkipVerify,omitempty\"`\n\tTelegraf           *string     `json:\"telegraf\"`\n\tUsername           *string     `json:\"username,omitempty\"`\n\tPassword           *string     `json:\"password,omitempty\"`\n\tSharedSecret       *string     `json:\"sharedSecret,omitempty\"`\n\tMetaURL            *string     `json:\"metaURL,omitempty\"`\n\tFluxURL            *string     `json:\"fluxURL,omitempty\"`\n\tRole               *string     `json:\"role,omitempty\"`\n\tDefaultRP          *string     `json:\"defaultRP\"`\n}\n\n\/\/ Apply applies an update to a source.\nfunc (u SourceUpdate) Apply(s *Source) error {\n\tif u.Name != nil {\n\t\ts.Name = *u.Name\n\t}\n\tif u.Type != nil {\n\t\ts.Type = *u.Type\n\t}\n\tif u.Token != nil {\n\t\ts.Token = *u.Token\n\t}\n\tif u.URL != nil {\n\t\ts.URL = *u.URL\n\t}\n\tif u.InsecureSkipVerify != nil {\n\t\ts.InsecureSkipVerify = *u.InsecureSkipVerify\n\t}\n\tif u.Telegraf != nil {\n\t\ts.Telegraf = *u.Telegraf\n\t}\n\tif u.Username != nil {\n\t\ts.Username = *u.Username\n\t}\n\tif u.Password != nil {\n\t\ts.Password = *u.Password\n\t}\n\tif u.SharedSecret != nil {\n\t\ts.SharedSecret = *u.SharedSecret\n\t}\n\tif u.MetaURL != nil {\n\t\ts.MetaURL = *u.MetaURL\n\t}\n\tif u.FluxURL != nil {\n\t\ts.FluxURL = *u.FluxURL\n\t}\n\tif u.DefaultRP != nil {\n\t\ts.DefaultRP = *u.DefaultRP\n\t}\n\n\treturn nil\n}\nfunc (s *Source) FindBucketByID(ctx context.Context, id ID) (*Bucket, error) {\n\tif s.BucketService == nil {\n\t\treturn nil, fmt.Errorf(\"not supported\")\n\t}\n\treturn s.BucketService.FindBucketByID(ctx, id)\n}\n\nfunc (s *Source) FindBucket(ctx context.Context, filter BucketFilter) (*Bucket, error) {\n\tif s.BucketService == nil {\n\t\treturn nil, fmt.Errorf(\"not supported\")\n\t}\n\treturn s.BucketService.FindBucket(ctx, filter)\n}\n\nfunc (s *Source) FindBuckets(ctx context.Context, filter BucketFilter, opt ...FindOptions) ([]*Bucket, int, error) {\n\tif s.BucketService == nil {\n\t\treturn nil, 0, fmt.Errorf(\"not supported\")\n\t}\n\treturn s.BucketService.FindBuckets(ctx, filter, opt...)\n}\n\nfunc (s *Source) CreateBucket(ctx context.Context, b *Bucket) error {\n\tif s.BucketService == nil {\n\t\treturn fmt.Errorf(\"not supported\")\n\t}\n\treturn s.BucketService.CreateBucket(ctx, b)\n}\n\nfunc (s *Source) UpdateBucket(ctx context.Context, id ID, upd BucketUpdate) (*Bucket, error) {\n\tif s.BucketService == nil {\n\t\treturn nil, fmt.Errorf(\"not supported\")\n\t}\n\treturn s.BucketService.UpdateBucket(ctx, id, upd)\n}\n\nfunc (s *Source) DeleteBucket(ctx context.Context, id ID) error {\n\tif s.BucketService == nil {\n\t\treturn fmt.Errorf(\"not supported\")\n\t}\n\treturn s.BucketService.DeleteBucket(ctx, id)\n}\n\nfunc (s *Source) Query(ctx context.Context, q *SourceQuery) (*SourceQueryResult, error) {\n\tif s.SourceQuerier == nil {\n\t\treturn nil, fmt.Errorf(\"not supported\")\n\t}\n\treturn s.SourceQuerier.Query(ctx, q)\n}\n<|endoftext|>"}
{"text":"<commit_before>package raft\n\n\/\/ StableStore is used to provide stable storage\n\/\/ of key configurations to ensure safety.\ntype StableStore interface {\n\t\/\/ Returns the current term\n\tCurrentTerm() (uint64, error)\n\n\t\/\/ Returns the candidate we voted for this term\n\tVotedFor() (string, error)\n\n\t\/\/ Sets the current term. Clears the current vote.\n\tSetCurrentTerm(uint64) error\n\n\t\/\/ Sets a candidate vote for the current term\n\tSetVote(string) error\n\n\t\/\/ Returns our candidate ID. This should be unique\n\t\/\/ and constant across runs\n\tCandidateID() (string, error)\n}\n<commit_msg>simplify the stable storage interface, push to higher level<commit_after>package raft\n\n\/\/ StableStore is used to provide stable storage\n\/\/ of key configurations to ensure safety.\ntype StableStore interface {\n\tSet(key []byte, val []byte) error\n\tGet(key []byte) ([]byte, error)\n\n\tSetUint64(key []byte, val uint64) error\n\tGetUint64(key []byte) (uint64, error)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2013-2014, Jeremy Bingham (<jbingham@gmail.com>)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage main\n\nimport (\n\t\"github.com\/ctdk\/goiardi\/actor\"\n\t\"github.com\/ctdk\/goiardi\/node\"\n\t\"net\/http\"\n\t\"encoding\/json\"\n)\n\nfunc statusHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\topUser, oerr := actor.GetReqUser(r.Header.Get(\"X-OPS-USERID\"))\n\tif oerr != nil {\n\t\tjsonErrorReport(w, r, oerr.Error(), oerr.Status())\n\t\treturn\n\t}\n\tif !opUser.IsAdmin() {\n\t\tjsonErrorReport(w, r, \"You must be an admin to do that\", http.StatusForbidden)\n\t\treturn\n\t}\n\tpathArray := splitPath(r.URL.Path)\n\n\tif len(pathArray) < 3 {\n\t\tjsonErrorReport(w, r, \"Bad request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar statusResponse interface{}\n\n\tswitch r.Method {\n\tcase \"GET\":\n\t\t\/* pathArray[1] will tell us what operation we're doing *\/\n\t\tswitch pathArray[1] {\n\t\t\tcase \"all\":\n\n\t\t\tcase \"node\":\n\t\t\t\tif len(pathArray) != 4 {\n\t\t\t\t\tjsonErrorReport(w, r, \"Bad request\", http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tnodeName := pathArray[2]\n\t\t\t\top := pathArray[3]\n\t\t\t\tn, gerr := node.Get(nodeName)\n\t\t\t\tif gerr != nil {\n\t\t\t\t\tjsonErrorReport(w, r, gerr.Error(), gerr.Status())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tswitch op {\n\t\t\t\tcase \"latest\":\n\t\t\t\t\tns, err := n.LatestStatus()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tjsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tstatusResponse = ns.ToJSON()\n\t\t\t\tcase \"all\":\n\t\t\t\t\tns, err := n.AllStatuses()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tjsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tsr := make([]map[string]string, len(ns))\n\t\t\t\t\tfor i, v := range ns {\n\t\t\t\t\t\tsr[i] = v.ToJSON()\n\t\t\t\t\t}\n\t\t\t\t\tstatusResponse = sr\n\t\t\t\tdefault:\n\t\t\t\t\tjsonErrorReport(w, r, \"Bad request\", http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tjsonErrorReport(w, r, \"Bad request\", http.StatusBadRequest)\n\t\t\t\treturn\n\t\t}\n\tdefault:\n\t\tjsonErrorReport(w, r, \"Method not allowed\", http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\tenc := json.NewEncoder(w)\n\tif err := enc.Encode(&statusResponse); err != nil {\n\t\tjsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t}\n}\n<commit_msg>node status available over http<commit_after>\/*\n * Copyright (c) 2013-2014, Jeremy Bingham (<jbingham@gmail.com>)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage main\n\nimport (\n\t\"github.com\/ctdk\/goiardi\/actor\"\n\t\"github.com\/ctdk\/goiardi\/node\"\n\t\"github.com\/ctdk\/goiardi\/util\"\n\t\"net\/http\"\n\t\"encoding\/json\"\n\t\"fmt\"\n)\n\nfunc statusHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\topUser, oerr := actor.GetReqUser(r.Header.Get(\"X-OPS-USERID\"))\n\tif oerr != nil {\n\t\tjsonErrorReport(w, r, oerr.Error(), oerr.Status())\n\t\treturn\n\t}\n\tif !opUser.IsAdmin() {\n\t\tjsonErrorReport(w, r, \"You must be an admin to do that\", http.StatusForbidden)\n\t\treturn\n\t}\n\tpathArray := splitPath(r.URL.Path)\n\n\tif len(pathArray) < 3 {\n\t\tjsonErrorReport(w, r, \"Bad request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar statusResponse interface{}\n\n\tswitch r.Method {\n\tcase \"GET\":\n\t\t\/* pathArray[1] will tell us what operation we're doing *\/\n\t\tswitch pathArray[1] {\n\t\t\t\/\/ \/status\/all\/nodes\n\t\t\tcase \"all\":\n\t\t\t\tif len(pathArray) != 3 {\n\t\t\t\t\tjsonErrorReport(w, r, \"Bad request\", http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif pathArray[2] != \"nodes\" {\n\t\t\t\t\tjsonErrorReport(w, r, \"Invalid object to get status for\", http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tnodes := node.AllNodes()\n\t\t\t\tsr := make([]map[string]string, len(nodes))\n\t\t\t\tfor i, n := range nodes {\n\t\t\t\t\tns, err := n.LatestStatus()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tnsbad := make(map[string]string)\n\t\t\t\t\t\tnsbad[\"node_name\"] = n.Name\n\t\t\t\t\t\tnsbad[\"status\"] = \"no record\"\n\t\t\t\t\t\tsr[i] = nsbad\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tsr[i] = ns.ToJSON()\n\t\t\t\t\tnsurl := fmt.Sprintf(\"\/status\/node\/%s\/latest\", n.Name)\n\t\t\t\t\tsr[i][\"url\"] = util.CustomURL(nsurl)\n\t\t\t\t}\n\t\t\t\tstatusResponse = sr\n\t\t\t\/\/ \/status\/node\/<nodeName>\/(all|latest)\n\t\t\tcase \"node\":\n\t\t\t\tif len(pathArray) != 4 {\n\t\t\t\t\tjsonErrorReport(w, r, \"Bad request\", http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tnodeName := pathArray[2]\n\t\t\t\top := pathArray[3]\n\t\t\t\tn, gerr := node.Get(nodeName)\n\t\t\t\tif gerr != nil {\n\t\t\t\t\tjsonErrorReport(w, r, gerr.Error(), gerr.Status())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tswitch op {\n\t\t\t\tcase \"latest\":\n\t\t\t\t\tns, err := n.LatestStatus()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tjsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tstatusResponse = ns.ToJSON()\n\t\t\t\tcase \"all\":\n\t\t\t\t\tns, err := n.AllStatuses()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tjsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\tsr := make([]map[string]string, len(ns))\n\t\t\t\t\tfor i, v := range ns {\n\t\t\t\t\t\tsr[i] = v.ToJSON()\n\t\t\t\t\t}\n\t\t\t\t\tstatusResponse = sr\n\t\t\t\tdefault:\n\t\t\t\t\tjsonErrorReport(w, r, \"Bad request\", http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tjsonErrorReport(w, r, \"Bad request\", http.StatusBadRequest)\n\t\t\t\treturn\n\t\t}\n\tdefault:\n\t\tjsonErrorReport(w, r, \"Method not allowed\", http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\tenc := json.NewEncoder(w)\n\tif err := enc.Encode(&statusResponse); err != nil {\n\t\tjsonErrorReport(w, r, err.Error(), http.StatusInternalServerError)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/gin-gonic\/gin\"\n)\n\ntype Target struct {\n\turl           string\n\tmethod        string\n\ttotal         int\n\tfail          int\n\tlastError     string\n\tlastIsSuccess bool\n\tlastTime      time.Time\n}\n\nfunc main() {\n\tgin.SetMode(gin.ReleaseMode)\n\tnow := time.Now()\n\ttargets := []Target{\n\t\tTarget{\"https:\/\/yorkyao.xyz\/api\/version\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"https:\/\/yorkyao.xyz\/\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"https:\/\/doc.yorkyao.xyz\/\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"https:\/\/news.yorkyao.xyz\/items\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"https:\/\/robot.yorkyao.xyz\/\", \"POST\", 0, 0, \"\", true, now},\n\t\tTarget{\"https:\/\/upload.yorkyao.xyz\/api\/temperary\", \"POST\", 0, 0, \"\", true, now},\n\t}\n\n\tticker := time.NewTicker(time.Second * 60)\n\n\tgo func() {\n\t\tfor t := range ticker.C {\n\t\t\tfmt.Println(t)\n\t\t\tfmt.Println(targets)\n\t\t\tfor i := 0; i < len(targets); i++ {\n\t\t\t\tvar resp *http.Response\n\t\t\t\tvar err error\n\t\t\t\tif targets[i].method == \"GET\" {\n\t\t\t\t\tresp, err = http.Get(targets[i].url)\n\t\t\t\t} else {\n\t\t\t\t\tresp, err = http.Post(targets[i].url, \"application\/x-www-form-urlencoded\", nil)\n\t\t\t\t}\n\t\t\t\ttargets[i].total++\n\t\t\t\ttargets[i].lastTime = time.Now()\n\t\t\t\tif err == nil && resp.StatusCode < 500 {\n\t\t\t\t\ttargets[i].lastIsSuccess = true\n\t\t\t\t} else {\n\t\t\t\t\ttargets[i].fail++\n\t\t\t\t\ttargets[i].lastError = err.Error()\n\t\t\t\t\ttargets[i].lastIsSuccess = false\n\t\t\t\t\tdefer resp.Body.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tr := gin.Default()\n\tr.GET(\"\/\", func(c *gin.Context) {\n\t\tresult := \"\"\n\t\tfor i := 0; i < len(targets); i++ {\n\t\t\ttarget := targets[i]\n\t\t\tif target.lastIsSuccess == false {\n\t\t\t\tresult += target.url + \": fail\\n\"\n\t\t\t} else {\n\t\t\t\tresult += target.url + \": success\\n\"\n\t\t\t}\n\t\t}\n\t\tc.String(200, result)\n\t})\n\taddress := \"localhost:9992\"\n\tfmt.Println(\"listening: \" + address)\n\tr.Run(address)\n}\n<commit_msg>OK, got the trick of json marshal<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/gin-gonic\/gin\"\n)\n\ntype Target struct {\n\tURL           string    `json:\"url\"`\n\tMethod        string    `json:\"method\"`\n\tTotal         int       `json:\"total\"`\n\tFail          int       `json:\"fail\"`\n\tLastError     string    `json:\"lastError\"`\n\tLastIsSuccess bool      `json:\"lastIsSuccess\"`\n\tLastTime      time.Time `json:\"lastTime\"`\n}\n\nfunc main() {\n\tgin.SetMode(gin.ReleaseMode)\n\tnow := time.Now()\n\ttargets := []Target{\n\t\tTarget{\"https:\/\/yorkyao.xyz\/api\/version\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"https:\/\/yorkyao.xyz\/\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"https:\/\/doc.yorkyao.xyz\/\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"https:\/\/news.yorkyao.xyz\/items\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"https:\/\/robot.yorkyao.xyz\/\", \"POST\", 0, 0, \"\", true, now},\n\t\tTarget{\"https:\/\/upload.yorkyao.xyz\/api\/temperary\", \"POST\", 0, 0, \"\", true, now},\n\t}\n\n\tticker := time.NewTicker(time.Second * 60)\n\n\tgo func() {\n\t\tfor t := range ticker.C {\n\t\t\tfmt.Println(t)\n\t\t\tfmt.Println(targets)\n\t\t\tfor i := 0; i < len(targets); i++ {\n\t\t\t\tvar resp *http.Response\n\t\t\t\tvar err error\n\t\t\t\tif targets[i].Method == \"GET\" {\n\t\t\t\t\tresp, err = http.Get(targets[i].URL)\n\t\t\t\t} else {\n\t\t\t\t\tresp, err = http.Post(targets[i].URL, \"application\/x-www-form-urlencoded\", nil)\n\t\t\t\t}\n\t\t\t\ttargets[i].Total++\n\t\t\t\ttargets[i].LastTime = time.Now()\n\t\t\t\tif err == nil && resp.StatusCode < 500 {\n\t\t\t\t\ttargets[i].LastIsSuccess = true\n\t\t\t\t} else {\n\t\t\t\t\ttargets[i].Fail++\n\t\t\t\t\ttargets[i].LastError = err.Error()\n\t\t\t\t\ttargets[i].LastIsSuccess = false\n\t\t\t\t\tdefer resp.Body.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tr := gin.Default()\n\tr.GET(\"\/\", func(c *gin.Context) {\n\t\tc.JSON(200, targets)\n\t})\n\taddress := \"localhost:9992\"\n\tfmt.Println(\"listening: \" + address)\n\tr.Run(address)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/gin-gonic\/gin\"\n)\n\ntype Target struct {\n\tName          string    `json:\"name\"`\n\tURL           string    `json:\"url\"`\n\tMethod        string    `json:\"method\"`\n\tTotal         int       `json:\"total\"`\n\tFail          int       `json:\"fail\"`\n\tLastError     string    `json:\"lastError\"`\n\tLastIsSuccess bool      `json:\"lastIsSuccess\"`\n\tLastTime      time.Time `json:\"lastTime\"`\n}\n\nfunc main() {\n\tgin.SetMode(gin.ReleaseMode)\n\tnow := time.Now()\n\ttargets := []Target{\n\t\tTarget{\"subsnoti backend\", \"https:\/\/yorkyao.xyz\/api\/version\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"subsnoti frontend\", \"https:\/\/yorkyao.xyz\/\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"subsnoti doc\", \"https:\/\/doc.yorkyao.xyz\/\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"news fetcher\", \"https:\/\/news.yorkyao.xyz\/items\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"deploy robot\", \"https:\/\/robot.yorkyao.xyz\/\", \"POST\", 0, 0, \"\", true, now},\n\t\tTarget{\"subsnoti upload\", \"https:\/\/upload.yorkyao.xyz\/api\/temperary\", \"POST\", 0, 0, \"\", true, now},\n\t}\n\n\tticker := time.NewTicker(time.Second * 60)\n\n\tgo func() {\n\t\tfor t := range ticker.C {\n\t\t\tfmt.Println(t)\n\t\t\tfmt.Println(targets)\n\t\t\tfor i := 0; i < len(targets); i++ {\n\t\t\t\tvar resp *http.Response\n\t\t\t\tvar err error\n\t\t\t\tif targets[i].Method == \"GET\" {\n\t\t\t\t\tresp, err = http.Get(targets[i].URL)\n\t\t\t\t} else {\n\t\t\t\t\tresp, err = http.Post(targets[i].URL, \"application\/x-www-form-urlencoded\", nil)\n\t\t\t\t}\n\t\t\t\ttargets[i].Total++\n\t\t\t\ttargets[i].LastTime = time.Now()\n\t\t\t\tif err == nil && resp.StatusCode < 500 {\n\t\t\t\t\ttargets[i].LastIsSuccess = true\n\t\t\t\t} else {\n\t\t\t\t\ttargets[i].Fail++\n\t\t\t\t\ttargets[i].LastError = err.Error()\n\t\t\t\t\ttargets[i].LastIsSuccess = false\n\t\t\t\t\tdefer resp.Body.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tr := gin.Default()\n\tr.GET(\"\/api\/status\", func(c *gin.Context) {\n\t\tc.JSON(200, targets)\n\t})\n\taddress := \"localhost:9992\"\n\tfmt.Println(\"listening: \" + address)\n\tr.Run(address)\n}\n<commit_msg>fix bug of invalid memory address or nil pointer dereference<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/gin-gonic\/gin\"\n)\n\ntype Target struct {\n\tName          string    `json:\"name\"`\n\tURL           string    `json:\"url\"`\n\tMethod        string    `json:\"method\"`\n\tTotal         int       `json:\"total\"`\n\tFail          int       `json:\"fail\"`\n\tLastError     string    `json:\"lastError\"`\n\tLastIsSuccess bool      `json:\"lastIsSuccess\"`\n\tLastTime      time.Time `json:\"lastTime\"`\n}\n\nfunc main() {\n\tgin.SetMode(gin.ReleaseMode)\n\tnow := time.Now()\n\ttargets := []Target{\n\t\tTarget{\"subsnoti backend\", \"https:\/\/yorkyao.xyz\/api\/version\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"subsnoti frontend\", \"https:\/\/yorkyao.xyz\/\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"subsnoti doc\", \"https:\/\/doc.yorkyao.xyz\/\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"news fetcher\", \"https:\/\/news.yorkyao.xyz\/items\", \"GET\", 0, 0, \"\", true, now},\n\t\tTarget{\"deploy robot\", \"https:\/\/robot.yorkyao.xyz\/\", \"POST\", 0, 0, \"\", true, now},\n\t\tTarget{\"subsnoti upload\", \"https:\/\/upload.yorkyao.xyz\/api\/temperary\", \"POST\", 0, 0, \"\", true, now},\n\t}\n\n\tticker := time.NewTicker(time.Second * 60)\n\n\tgo func() {\n\t\tfor t := range ticker.C {\n\t\t\tfmt.Println(t)\n\t\t\tfmt.Println(targets)\n\t\t\tfor i := 0; i < len(targets); i++ {\n\t\t\t\tvar resp *http.Response\n\t\t\t\tvar err error\n\t\t\t\tif targets[i].Method == \"GET\" {\n\t\t\t\t\tresp, err = http.Get(targets[i].URL)\n\t\t\t\t} else {\n\t\t\t\t\tresp, err = http.Post(targets[i].URL, \"application\/x-www-form-urlencoded\", nil)\n\t\t\t\t}\n\t\t\t\ttargets[i].Total++\n\t\t\t\ttargets[i].LastTime = time.Now()\n\t\t\t\tif err != nil {\n\t\t\t\t\ttargets[i].Fail++\n\t\t\t\t\ttargets[i].LastError = err.Error()\n\t\t\t\t\ttargets[i].LastIsSuccess = false\n\t\t\t\t} else if resp != nil && resp.StatusCode >= 500 {\n\t\t\t\t\ttargets[i].Fail++\n\t\t\t\t\ttargets[i].LastError = strconv.Itoa(resp.StatusCode)\n\t\t\t\t\ttargets[i].LastIsSuccess = false\n\t\t\t\t} else {\n\t\t\t\t\ttargets[i].LastIsSuccess = true\n\t\t\t\t}\n\t\t\t\tif resp != nil {\n\t\t\t\t\tdefer resp.Body.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\n\tr := gin.Default()\n\tr.GET(\"\/api\/status\", func(c *gin.Context) {\n\t\tc.JSON(200, targets)\n\t})\n\taddress := \"localhost:9992\"\n\tfmt.Println(\"listening: \" + address)\n\tr.Run(address)\n}\n<|endoftext|>"}
{"text":"<commit_before>package httpie\n\nimport (\n    \"net\/http\"\n    \"bufio\"\n    \"fmt\"\n    \"errors\"\n)\n\nfunc NewStream(endpoint Endpoint, auth Authorizer, consumer Consumer) *Stream {\n    return &Stream{\n        endpoint:   endpoint,\n        authorizer: auth,\n        consumer:   consumer,\n        data:       make(chan []byte, 50),\n    }\n}\n\ntype Stream struct {\n    data        chan []byte\n    endpoint    Endpoint\n    authorizer  Authorizer\n    consumer    Consumer\n}\n\nfunc (s *Stream) Start() {\n    resp, err := s.connect()\n    if err != nil {\n        return\n    }\n\n    s.consume(resp)\n}\n\nfunc (s *Stream) Data() (chan []byte) {\n    return s.data\n}\n\nfunc (s *Stream) connect() (*http.Response, error) {\n    client := &http.Client{}\n    req    := &http.Request{Header: http.Header{}}\n\n    s.endpoint.ApplyTo(req)\n    if s.authorizer != nil {\n        s.authorizer.Authorize(req)\n    }\n\n    resp, err := client.Do(req)\n\n    if err != nil {\n        return nil, err\n    }\n\n    if resp.StatusCode != 200 {\n        return nil, errors.New(fmt.Sprintf(\"Status code received: %s\", resp.StatusCode))\n    }\n\n    return resp, nil\n}\n\nfunc (s *Stream) consume(resp *http.Response) {\n    reader := bufio.NewReader(resp.Body)\n\n    var (\n        b []byte\n        err error\n    )\n\n    for {\n        b, err = s.consumer.Consume(reader)\n\n        if err != nil {\n            resp.Body.Close()\n\n            if resp, err = s.connect(); err != nil {\n                continue\n            }\n\n            reader = bufio.NewReader(resp.Body)\n        }\n\n        s.data <- b\n    }\n}\n<commit_msg>Name this Connect instead of Start<commit_after>package httpie\n\nimport (\n    \"net\/http\"\n    \"bufio\"\n    \"fmt\"\n    \"errors\"\n)\n\nfunc NewStream(endpoint Endpoint, auth Authorizer, consumer Consumer) *Stream {\n    return &Stream{\n        endpoint:   endpoint,\n        authorizer: auth,\n        consumer:   consumer,\n        data:       make(chan []byte, 50),\n    }\n}\n\ntype Stream struct {\n    data        chan []byte\n    endpoint    Endpoint\n    authorizer  Authorizer\n    consumer    Consumer\n}\n\nfunc (s *Stream) Connect() {\n    resp, err := s.connect()\n    if err != nil {\n        return\n    }\n\n    s.consume(resp)\n}\n\nfunc (s *Stream) Data() (chan []byte) {\n    return s.data\n}\n\nfunc (s *Stream) connect() (*http.Response, error) {\n    client := &http.Client{}\n    req    := &http.Request{Header: http.Header{}}\n\n    s.endpoint.ApplyTo(req)\n    if s.authorizer != nil {\n        s.authorizer.Authorize(req)\n    }\n\n    resp, err := client.Do(req)\n\n    if err != nil {\n        return nil, err\n    }\n\n    if resp.StatusCode != 200 {\n        return nil, errors.New(fmt.Sprintf(\"Status code received: %s\", resp.StatusCode))\n    }\n\n    return resp, nil\n}\n\nfunc (s *Stream) consume(resp *http.Response) {\n    reader := bufio.NewReader(resp.Body)\n\n    var (\n        b []byte\n        err error\n    )\n\n    for {\n        b, err = s.consumer.Consume(reader)\n\n        if err != nil {\n            resp.Body.Close()\n\n            if resp, err = s.connect(); err != nil {\n                continue\n            }\n\n            reader = bufio.NewReader(resp.Body)\n        }\n\n        s.data <- b\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>package twitter\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"time\"\n)\n\n\/\/ StreamFilterParams represents the filter parameters used in a stream.\n\/\/ https:\/\/dev.twitter.com\/streaming\/overview\/request-parameters\ntype StreamFilterParams struct {\n\tFilterLevel   string\n\tFollow        []string\n\tLanguage      []string\n\tLocations     []string\n\tStallWarnings bool\n\tTrack         []string\n}\n\n\/\/ StreamMessage represents a message received from a Twitter stream. Fields\n\/\/ should be checked for existence before being used.\ntype StreamMessage struct {\n\t*Tweet\n\tDelete         *DeleteMessage         `json:\"delete\"`\n\tScrubGeo       *ScrubGeoMessage       `json:\"scrub_geo\"`\n\tLimit          *LimitMessage          `json:\"limit\"`\n\tStatusWithheld *StatusWithheldMessage `json:\"status_withheld\"`\n\tUserWithheld   *UserWithheldMessage   `json:\"user_withheld\"`\n\tDisconnect     *DisconnectMessage     `json:\"disconnect_message\"`\n}\n\n\/\/ DeleteMessage represents a stream message that a given Tweet has been\n\/\/ deleted.\ntype DeleteMessage struct {\n\tStatus struct {\n\t\tID        int64  `json:\"id\"`\n\t\tIDStr     string `json:\"id_str\"`\n\t\tUserID    int64  `json:\"user_id\"`\n\t\tUserIDStr string `json:\"user_id_str\"`\n\t} `json:\"status\"`\n}\n\n\/\/ ScrubGeoMessage represents a stream message that geolocated data must be\n\/\/ stripped from a range of Tweets.\ntype ScrubGeoMessage struct {\n\tUserID          int64  `json:\"user_id\"`\n\tUserIDStr       string `json:\"user_id_str\"`\n\tUpToStatusID    int64  `json:\"up_to_status_id\"`\n\tUpToStatusIDStr string `json:\"up_to_status_id_str\"`\n}\n\n\/\/ LimitMessage represents a stream message that a filtered stream has matched\n\/\/ more tweets than its current rate limit allows to be delivered.\ntype LimitMessage struct {\n\tTrack int `json:\"track\"`\n}\n\n\/\/ StatusWithheldMessage represents a stream message that the indicated tweet\n\/\/ has been withheld.\ntype StatusWithheldMessage struct {\n\tID                  int64    `json:\"id\"`\n\tUserID              int64    `json:\"user_id\"`\n\tWithheldInCountries []string `json:\"withheld_in_countries\"`\n}\n\n\/\/ UserWithheldMessage represents a steram message that tweets from the\n\/\/ indicated user have been withheld.\ntype UserWithheldMessage struct {\n\tID                  int64    `json:\"id\"`\n\tWithheldInCountries []string `json:\"withheld_in_countries\"`\n}\n\n\/\/ DisconnectMessage represents a stream message that the stream will disconnect\n\/\/ with the provided code and reason.\n\/\/ https:\/\/dev.twitter.com\/streaming\/overview\/messages-types#disconnect_messages\ntype DisconnectMessage struct {\n\tCode       int    `json:\"code\"`\n\tStreamName string `json:\"stream_name\"`\n\tReason     string `json:\"reason\"`\n}\n\n\/\/ StreamErrFn represents a function that is called when an error is encountered\n\/\/ in a stream and the connection will be retried. If the StreamErrFn returns\n\/\/ a non-nil error, the stream will be immediately closed with the error.\ntype StreamErrFn func(Backoff, error) error\n\n\/\/ Stream represents a Twitter stream connection. Messages from the stream can\n\/\/ be read off the channel returned by Messages. At any point, the stream can be\n\/\/ manually closed by calling the Close method. When the stream exits, the\n\/\/ channel returned from the Done method will be closed.\ntype Stream struct {\n\tctx    context.Context\n\tcancel context.CancelFunc\n\n\tclient   OAuthClient\n\tvalues   url.Values\n\tendpoint string\n\n\tchMessage chan StreamMessage\n\tchDone    chan struct{}\n\tcloseErr  error\n\terrFn     StreamErrFn\n}\n\nfunc newFilterStream(ctx context.Context, client OAuthClient, params StreamFilterParams, errFn StreamErrFn) *Stream {\n\ts := Stream{\n\t\tclient:    client,\n\t\tvalues:    parseFilterParams(params),\n\t\tendpoint:  \"https:\/\/stream.twitter.com\/1.1\/statuses\/filter.json\",\n\t\tchMessage: make(chan StreamMessage),\n\t\tchDone:    make(chan struct{}),\n\t\terrFn:     errFn,\n\t}\n\ts.ctx, s.cancel = context.WithCancel(ctx)\n\tgo s.start()\n\treturn &s\n}\n\n\/\/ Close immediately closes the stream and waits for the stream to completely\n\/\/ close before returning the stream's shutdown error.\nfunc (s *Stream) Close() error {\n\ts.cancel()\n\t<-s.chDone\n\treturn s.Err()\n}\n\n\/\/ Done returns a channel that is closed when the stream has completely\n\/\/ shutdown.\nfunc (s *Stream) Done() <-chan struct{} {\n\treturn s.chDone\n}\n\n\/\/ Err returns the stream's shutdown error after it has been closed. This should\n\/\/ only be called after the the channel returned from Done has been closed.\nfunc (s *Stream) Err() error {\n\treturn s.closeErr\n}\n\n\/\/ Messages returns a read-only channel that messages are sent to as they are\n\/\/ read off of the stream. Messages should be regualrly waiting on this channel,\n\/\/ otherwise the stream's queue (on Twitter's end) will fill up and cause the\n\/\/ stream to close.\nfunc (s *Stream) Messages() <-chan StreamMessage {\n\treturn s.chMessage\n}\n\nfunc (s *Stream) notifyError(boff Backoff, err error) error {\n\tif s.errFn == nil {\n\t\treturn nil\n\t}\n\treturn s.errFn(boff, err)\n}\n\nfunc (s *Stream) start() {\n\tvar err error\n\tdefer func() {\n\t\ts.cancel()\n\t\ts.closeErr = err\n\t\tclose(s.chDone)\n\t}()\n\n\tboff := &backoff{}\n\tfor {\n\t\terr = s.makeRequest(boff)\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\terr = s.ctx.Err()\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif d := boff.wait(); d > 0 {\n\t\t\tselect {\n\t\t\tcase <-s.ctx.Done():\n\t\t\t\terr = s.ctx.Err()\n\t\t\t\treturn\n\t\t\tcase <-time.After(d):\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (s *Stream) makeRequest(boff *backoff) error {\n\t\/\/ Create a child context for this specific request.\n\tctx, cancel := context.WithCancel(s.ctx)\n\tdefer cancel()\n\n\t\/\/ Make HTTP request to open stream.\n\tresp, err := s.client.Do(ctx, \"POST\", nil, s.endpoint, s.values)\n\tif err != nil {\n\t\tboff.incNetDelay()\n\t\treturn s.notifyError(boff, err)\n\t}\n\tdefer resp.Body.Close()\n\n\t\/\/ Handle HTTP response.\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\terr = s.readMessages(cancel, resp.Body)\n\t\tboff.reset()\n\t\treturn s.notifyError(boff, err)\n\tcase 401, 403, 404, 406, 413, 416:\n\t\terr = fmt.Errorf(\"%d: %s\", resp.StatusCode, http.StatusText(resp.StatusCode))\n\t\treturn err\n\tcase 420:\n\t\terr = errors.New(\"420: Rate Limited\")\n\t\tboff.incHTTPDelay(true)\n\t\treturn s.notifyError(boff, err)\n\tdefault:\n\t\terr = fmt.Errorf(\"%d: %s\", resp.StatusCode, http.StatusText(resp.StatusCode))\n\t\tboff.incHTTPDelay(false)\n\t\treturn s.notifyError(boff, err)\n\t}\n}\n\nfunc (s *Stream) readMessages(cancel context.CancelFunc, r io.Reader) error {\n\tscanner := bufio.NewScanner(r)\n\tscanner.Split(scanLines)\n\tfor {\n\t\tif err := s.readMessage(cancel, scanner); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc (s *Stream) readMessage(cancel context.CancelFunc, scanner *bufio.Scanner) error {\n\t\/\/ Set 90 second timeout on receiving a message.\n\t\/\/ https:\/\/dev.twitter.com\/streaming\/overview\/connecting\n\tt := time.AfterFunc(90*time.Second, func() { cancel() })\n\t\/\/ Scan next token.\n\tok := scanner.Scan()\n\tt.Stop()\n\tif !ok {\n\t\treturn scanner.Err()\n\t}\n\tb := scanner.Bytes()\n\tif len(b) == 0 || (len(b) == 1 && b[0] == '\\n') {\n\t\t\/\/ Keep-alive.\n\t\tlog.Println(\"Keep-alive\")\n\t\treturn nil\n\t}\n\t\/\/ Parse StreamMessage JSON.\n\tvar sm StreamMessage\n\terr := json.Unmarshal(b, &sm)\n\tif err != nil {\n\t\treturn err\n\t}\n\tselect {\n\tcase <-s.ctx.Done():\n\t\treturn s.ctx.Err()\n\tcase s.chMessage <- sm:\n\t\treturn nil\n\t}\n}\n\nvar newMsgBytes = []byte(\"\\r\\n\")\n\nfunc scanLines(data []byte, atEOF bool) (int, []byte, error) {\n\tif atEOF && len(data) == 0 {\n\t\treturn 0, nil, nil\n\t}\n\tif i := bytes.Index(data, newMsgBytes); i >= 0 {\n\t\treturn i + 2, data[0:i], nil\n\t}\n\tif atEOF {\n\t\treturn len(data), data, nil\n\t}\n\treturn 0, nil, nil\n}\n\nfunc parseFilterParams(params StreamFilterParams) url.Values {\n\tvalues := url.Values{}\n\t\/\/ Write possible settings.\n\tif params.FilterLevel != \"\" {\n\t\tvalues.Set(\"filter_level\", params.FilterLevel)\n\t}\n\tif params.StallWarnings {\n\t\tvalues.Set(\"stall_warnings\", \"true\")\n\t}\n\t\/\/ Write possible filters.\n\tvar buf bytes.Buffer\n\tif len(params.Follow) > 0 {\n\t\tvalues.Set(\"follow\", commaSeparated(&buf, params.Follow))\n\t}\n\tif len(params.Language) > 0 {\n\t\tvalues.Set(\"language\", commaSeparated(&buf, params.Language))\n\t}\n\tif len(params.Locations) > 0 {\n\t\tvalues.Set(\"locations\", commaSeparated(&buf, params.Locations))\n\t}\n\tif len(params.Track) > 0 {\n\t\tvalues.Set(\"track\", commaSeparated(&buf, params.Track))\n\t}\n\treturn values\n}\n\nfunc commaSeparated(buf *bytes.Buffer, ss []string) string {\n\tbuf.Reset()\n\tfor i, s := range ss {\n\t\tif i > 0 {\n\t\t\tbuf.WriteByte(',')\n\t\t}\n\t\tbuf.WriteString(s)\n\t}\n\treturn buf.String()\n}\n<commit_msg>Move StartFilterStream to stream.go<commit_after>package twitter\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"time\"\n)\n\n\/\/ StartFilterStream starts and returns a new Stream using the provided context,\n\/\/ stream filter parameters, and optional stream error callback.\nfunc (c *Client) StartFilterStream(ctx context.Context, params StreamFilterParams, errFn StreamErrFn) *Stream {\n\treturn newFilterStream(ctx, c, params, errFn)\n}\n\n\/\/ StreamFilterParams represents the filter parameters used in a stream.\n\/\/ https:\/\/dev.twitter.com\/streaming\/overview\/request-parameters\ntype StreamFilterParams struct {\n\tFilterLevel   string\n\tFollow        []string\n\tLanguage      []string\n\tLocations     []string\n\tStallWarnings bool\n\tTrack         []string\n}\n\n\/\/ StreamMessage represents a message received from a Twitter stream. Fields\n\/\/ should be checked for existence before being used.\ntype StreamMessage struct {\n\t*Tweet\n\tDelete         *DeleteMessage         `json:\"delete\"`\n\tScrubGeo       *ScrubGeoMessage       `json:\"scrub_geo\"`\n\tLimit          *LimitMessage          `json:\"limit\"`\n\tStatusWithheld *StatusWithheldMessage `json:\"status_withheld\"`\n\tUserWithheld   *UserWithheldMessage   `json:\"user_withheld\"`\n\tDisconnect     *DisconnectMessage     `json:\"disconnect_message\"`\n}\n\n\/\/ DeleteMessage represents a stream message that a given Tweet has been\n\/\/ deleted.\ntype DeleteMessage struct {\n\tStatus struct {\n\t\tID        int64  `json:\"id\"`\n\t\tIDStr     string `json:\"id_str\"`\n\t\tUserID    int64  `json:\"user_id\"`\n\t\tUserIDStr string `json:\"user_id_str\"`\n\t} `json:\"status\"`\n}\n\n\/\/ ScrubGeoMessage represents a stream message that geolocated data must be\n\/\/ stripped from a range of Tweets.\ntype ScrubGeoMessage struct {\n\tUserID          int64  `json:\"user_id\"`\n\tUserIDStr       string `json:\"user_id_str\"`\n\tUpToStatusID    int64  `json:\"up_to_status_id\"`\n\tUpToStatusIDStr string `json:\"up_to_status_id_str\"`\n}\n\n\/\/ LimitMessage represents a stream message that a filtered stream has matched\n\/\/ more tweets than its current rate limit allows to be delivered.\ntype LimitMessage struct {\n\tTrack int `json:\"track\"`\n}\n\n\/\/ StatusWithheldMessage represents a stream message that the indicated tweet\n\/\/ has been withheld.\ntype StatusWithheldMessage struct {\n\tID                  int64    `json:\"id\"`\n\tUserID              int64    `json:\"user_id\"`\n\tWithheldInCountries []string `json:\"withheld_in_countries\"`\n}\n\n\/\/ UserWithheldMessage represents a steram message that tweets from the\n\/\/ indicated user have been withheld.\ntype UserWithheldMessage struct {\n\tID                  int64    `json:\"id\"`\n\tWithheldInCountries []string `json:\"withheld_in_countries\"`\n}\n\n\/\/ DisconnectMessage represents a stream message that the stream will disconnect\n\/\/ with the provided code and reason.\n\/\/ https:\/\/dev.twitter.com\/streaming\/overview\/messages-types#disconnect_messages\ntype DisconnectMessage struct {\n\tCode       int    `json:\"code\"`\n\tStreamName string `json:\"stream_name\"`\n\tReason     string `json:\"reason\"`\n}\n\n\/\/ StreamErrFn represents a function that is called when an error is encountered\n\/\/ in a stream and the connection will be retried. If the StreamErrFn returns\n\/\/ a non-nil error, the stream will be immediately closed with the error.\ntype StreamErrFn func(Backoff, error) error\n\n\/\/ Stream represents a Twitter stream connection. Messages from the stream can\n\/\/ be read off the channel returned by Messages. At any point, the stream can be\n\/\/ manually closed by calling the Close method. When the stream exits, the\n\/\/ channel returned from the Done method will be closed.\ntype Stream struct {\n\tctx    context.Context\n\tcancel context.CancelFunc\n\n\tclient   oauthClient\n\tvalues   url.Values\n\tendpoint string\n\n\tchMessage chan StreamMessage\n\tchDone    chan struct{}\n\tcloseErr  error\n\terrFn     StreamErrFn\n}\n\nfunc newFilterStream(ctx context.Context, client oauthClient, params StreamFilterParams, errFn StreamErrFn) *Stream {\n\ts := Stream{\n\t\tclient:    client,\n\t\tvalues:    parseFilterParams(params),\n\t\tendpoint:  \"https:\/\/stream.twitter.com\/1.1\/statuses\/filter.json\",\n\t\tchMessage: make(chan StreamMessage),\n\t\tchDone:    make(chan struct{}),\n\t\terrFn:     errFn,\n\t}\n\ts.ctx, s.cancel = context.WithCancel(ctx)\n\tgo s.start()\n\treturn &s\n}\n\n\/\/ Close immediately closes the stream and waits for the stream to completely\n\/\/ close before returning the stream's shutdown error.\nfunc (s *Stream) Close() error {\n\ts.cancel()\n\t<-s.chDone\n\treturn s.Err()\n}\n\n\/\/ Done returns a channel that is closed when the stream has completely\n\/\/ shutdown.\nfunc (s *Stream) Done() <-chan struct{} {\n\treturn s.chDone\n}\n\n\/\/ Err returns the stream's shutdown error after it has been closed. This should\n\/\/ only be called after the the channel returned from Done has been closed.\nfunc (s *Stream) Err() error {\n\treturn s.closeErr\n}\n\n\/\/ Messages returns a read-only channel that messages are sent to as they are\n\/\/ read off of the stream. Messages should be regualrly waiting on this channel,\n\/\/ otherwise the stream's queue (on Twitter's end) will fill up and cause the\n\/\/ stream to close.\nfunc (s *Stream) Messages() <-chan StreamMessage {\n\treturn s.chMessage\n}\n\nfunc (s *Stream) notifyError(boff Backoff, err error) error {\n\tif s.errFn == nil {\n\t\treturn nil\n\t}\n\treturn s.errFn(boff, err)\n}\n\nfunc (s *Stream) start() {\n\tdefer func() {\n\t\ts.cancel()\n\t\tclose(s.chDone)\n\t}()\n\n\tboff := &backoff{}\n\tfor {\n\t\ts.closeErr = s.makeRequest(boff)\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\ts.closeErr = s.ctx.Err()\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\t\tif s.closeErr != nil {\n\t\t\treturn\n\t\t}\n\t\tif d := boff.wait(); d > 0 {\n\t\t\tselect {\n\t\t\tcase <-s.ctx.Done():\n\t\t\t\ts.closeErr = s.ctx.Err()\n\t\t\t\treturn\n\t\t\tcase <-time.After(d):\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (s *Stream) makeRequest(boff *backoff) error {\n\t\/\/ Create a child context for this specific request.\n\tctx, cancel := context.WithCancel(s.ctx)\n\tdefer cancel()\n\n\t\/\/ Make HTTP request to open stream.\n\tresp, err := s.client.do(ctx, \"POST\", s.endpoint, s.values)\n\tif err != nil {\n\t\tboff.incNetDelay()\n\t\treturn s.notifyError(boff, err)\n\t}\n\tdefer resp.Body.Close()\n\n\t\/\/ Handle HTTP response.\n\tswitch resp.StatusCode {\n\tcase 200:\n\t\terr = s.readMessages(cancel, resp.Body)\n\t\tboff.reset()\n\t\treturn s.notifyError(boff, err)\n\tcase 401, 403, 404, 406, 413, 416:\n\t\terr = fmt.Errorf(\"%d: %s\", resp.StatusCode, http.StatusText(resp.StatusCode))\n\t\treturn err\n\tcase 420:\n\t\terr = errors.New(\"420: Rate Limited\")\n\t\tboff.incHTTPDelay(true)\n\t\treturn s.notifyError(boff, err)\n\tdefault:\n\t\terr = fmt.Errorf(\"%d: %s\", resp.StatusCode, http.StatusText(resp.StatusCode))\n\t\tboff.incHTTPDelay(false)\n\t\treturn s.notifyError(boff, err)\n\t}\n}\n\nfunc (s *Stream) readMessages(cancel context.CancelFunc, r io.Reader) error {\n\tscanner := bufio.NewScanner(r)\n\tscanner.Split(scanLines)\n\tfor {\n\t\tif err := s.readMessage(cancel, scanner); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc (s *Stream) readMessage(cancel context.CancelFunc, scanner *bufio.Scanner) error {\n\t\/\/ Set 90 second timeout on receiving a message.\n\t\/\/ https:\/\/dev.twitter.com\/streaming\/overview\/connecting\n\tt := time.AfterFunc(90*time.Second, func() { cancel() })\n\tok := scanner.Scan()\n\tt.Stop()\n\tif !ok {\n\t\treturn scanner.Err()\n\t}\n\tb := scanner.Bytes()\n\tif len(b) == 0 || (len(b) == 1 && b[0] == '\\n') {\n\t\t\/\/ Keep-alive.\n\t\tlog.Println(\"Keep-alive\")\n\t\treturn nil\n\t}\n\t\/\/ Parse StreamMessage JSON.\n\tvar sm StreamMessage\n\terr := json.Unmarshal(b, &sm)\n\tif err != nil {\n\t\treturn err\n\t}\n\tselect {\n\tcase <-s.ctx.Done():\n\t\treturn s.ctx.Err()\n\tcase s.chMessage <- sm:\n\t\treturn nil\n\t}\n}\n\nvar newMsgBytes = []byte(\"\\r\\n\")\n\nfunc scanLines(data []byte, atEOF bool) (int, []byte, error) {\n\tif atEOF && len(data) == 0 {\n\t\treturn 0, nil, nil\n\t}\n\tif i := bytes.Index(data, newMsgBytes); i >= 0 {\n\t\treturn i + 2, data[0:i], nil\n\t}\n\tif atEOF {\n\t\treturn len(data), data, nil\n\t}\n\treturn 0, nil, nil\n}\n\nfunc parseFilterParams(params StreamFilterParams) url.Values {\n\tvalues := url.Values{}\n\t\/\/ Write possible settings.\n\tif params.FilterLevel != \"\" {\n\t\tvalues.Set(\"filter_level\", params.FilterLevel)\n\t}\n\tif params.StallWarnings {\n\t\tvalues.Set(\"stall_warnings\", \"true\")\n\t}\n\t\/\/ Write possible filters.\n\tvar buf bytes.Buffer\n\tif len(params.Follow) > 0 {\n\t\tvalues.Set(\"follow\", commaSeparated(&buf, params.Follow))\n\t}\n\tif len(params.Language) > 0 {\n\t\tvalues.Set(\"language\", commaSeparated(&buf, params.Language))\n\t}\n\tif len(params.Locations) > 0 {\n\t\tvalues.Set(\"locations\", commaSeparated(&buf, params.Locations))\n\t}\n\tif len(params.Track) > 0 {\n\t\tvalues.Set(\"track\", commaSeparated(&buf, params.Track))\n\t}\n\treturn values\n}\n\nfunc commaSeparated(buf *bytes.Buffer, ss []string) string {\n\tbuf.Reset()\n\tfor i, s := range ss {\n\t\tif i > 0 {\n\t\t\tbuf.WriteByte(',')\n\t\t}\n\t\tbuf.WriteString(s)\n\t}\n\treturn buf.String()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package stripe provides the binding for Stripe REST APIs.\npackage stripe\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ defaultUrl is the public Stripe URL for APIs.\nconst defaultUrl = \"https:\/\/api.stripe.com\/v1\"\n\n\/\/ apiversion is the currently supported API version\nconst apiversion = \"2014-08-20\"\n\n\/\/ clientversion is the binding version\nconst clientversion = \"1.0\"\n\n\/\/ Backend is an interface for making calls against a Stripe service.\n\/\/ This interface exists to enable mocking for during testing if needed.\ntype Backend interface {\n\tCall(method, path, token string, body *url.Values, v interface{}) error\n}\n\n\/\/ InternalBackend is the internal implementation for making HTTP calls to Stripe.\ntype InternalBackend struct {\n\turl        string\n\thttpClient *http.Client\n}\n\n\/\/ NewInternalBackend returns a customized backend used for making calls in this binding.\n\/\/ This method should be called in one of two scenarios:\n\/\/\t1. You're running in a Google AppEngine environment where the http.DefaultClient is not available.\n\/\/  2. You're doing internal development at Stripe.\nfunc NewInternalBackend(httpClient *http.Client, url string) *InternalBackend {\n\tif len(url) == 0 {\n\t\turl = defaultUrl\n\t}\n\n\treturn &InternalBackend{\n\t\turl:        url,\n\t\thttpClient: httpClient,\n\t}\n}\n\n\/\/ Key is the Stripe API key used globally in the binding.\nvar Key string\n\nvar debug bool\nvar backend Backend\n\n\/\/ SetDebug enables additional tracing globally.\n\/\/ The method is designed for used during testing.\nfunc SetDebug(value bool) {\n\tdebug = value\n}\n\n\/\/ GetBackend returns the currently used backend in the binding.\nfunc GetBackend() Backend {\n\tif backend == nil {\n\t\tbackend = NewInternalBackend(http.DefaultClient, \"\")\n\t}\n\n\treturn backend\n}\n\n\/\/ SetBackend sets the backend used in the binding.\nfunc SetBackend(b Backend) {\n\tbackend = b\n}\n\n\/\/ Call is the Backend.Call implementation for invoking Stripe APIs.\nfunc (s *InternalBackend) Call(method, path, token string, body *url.Values, v interface{}) error {\n\tif !strings.HasPrefix(path, \"\/\") {\n\t\tpath = \"\/\" + path\n\t}\n\n\tpath = s.url + path\n\n\tif body != nil && len(*body) > 0 {\n\t\tpath += \"?\" + body.Encode()\n\t}\n\n\treq, err := http.NewRequest(method, path, nil)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot create Stripe request: %v\\n\", err)\n\t\treturn err\n\t}\n\n\treq.SetBasicAuth(token, \"\")\n\treq.Header.Add(\"Stripe-Version\", apiversion)\n\treq.Header.Add(\"X-Stripe-Client-User-Agent\", \"Stripe.Go-\"+clientversion)\n\n\tlog.Printf(\"Requesting %v %q\\n\", method, path)\n\tstart := time.Now()\n\n\tres, err := s.httpClient.Do(req)\n\n\tif debug {\n\t\tlog.Printf(\"Completed in %v\\n\", time.Since(start))\n\t}\n\n\tif err != nil {\n\t\tlog.Printf(\"Request to Stripe failed: %v\\n\", err)\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tresBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot parse Stripe response: %v\\n\", err)\n\t\treturn err\n\t}\n\n\tif res.StatusCode >= 400 {\n\t\t\/\/ for some odd reason, the Erro structure doesn't unmarshal\n\t\t\/\/ initially I thought it was because it's a struct inside of a struct\n\t\t\/\/ but even after trying that, it still didn't work\n\t\t\/\/ so unmarshalling to a map for now and parsing the results manually\n\t\t\/\/ but should investigate later\n\t\tvar errMap map[string]interface{}\n\t\tjson.Unmarshal(resBody, &errMap)\n\n\t\tif e, found := errMap[\"error\"]; !found {\n\t\t\terr := errors.New(string(resBody))\n\t\t\tlog.Printf(\"Unparsable error returned from Stripe: %v\\n\", err)\n\t\t\treturn err\n\t\t} else {\n\t\t\troot := e.(map[string]interface{})\n\t\t\terr := &Error{\n\t\t\t\tType:           ErrorType(root[\"type\"].(string)),\n\t\t\t\tMsg:            root[\"message\"].(string),\n\t\t\t\tHttpStatusCode: res.StatusCode,\n\t\t\t}\n\n\t\t\tif code, found := root[\"code\"]; found {\n\t\t\t\terr.Code = ErrorCode(code.(string))\n\t\t\t}\n\n\t\t\tif param, found := root[\"param\"]; found {\n\t\t\t\terr.Param = param.(string)\n\t\t\t}\n\n\t\t\tlog.Printf(\"Error encountered from Stripe: %v\\n\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif debug {\n\t\tlog.Printf(\"Stripe Response: %q\\n\", resBody)\n\t}\n\n\tif v != nil {\n\t\treturn json.Unmarshal(resBody, v)\n\t}\n\n\treturn nil\n}\n<commit_msg>use the proper header for user agent<commit_after>\/\/ Package stripe provides the binding for Stripe REST APIs.\npackage stripe\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ defaultUrl is the public Stripe URL for APIs.\nconst defaultUrl = \"https:\/\/api.stripe.com\/v1\"\n\n\/\/ apiversion is the currently supported API version\nconst apiversion = \"2014-08-20\"\n\n\/\/ clientversion is the binding version\nconst clientversion = \"1.0\"\n\n\/\/ Backend is an interface for making calls against a Stripe service.\n\/\/ This interface exists to enable mocking for during testing if needed.\ntype Backend interface {\n\tCall(method, path, token string, body *url.Values, v interface{}) error\n}\n\n\/\/ InternalBackend is the internal implementation for making HTTP calls to Stripe.\ntype InternalBackend struct {\n\turl        string\n\thttpClient *http.Client\n}\n\n\/\/ NewInternalBackend returns a customized backend used for making calls in this binding.\n\/\/ This method should be called in one of two scenarios:\n\/\/\t1. You're running in a Google AppEngine environment where the http.DefaultClient is not available.\n\/\/  2. You're doing internal development at Stripe.\nfunc NewInternalBackend(httpClient *http.Client, url string) *InternalBackend {\n\tif len(url) == 0 {\n\t\turl = defaultUrl\n\t}\n\n\treturn &InternalBackend{\n\t\turl:        url,\n\t\thttpClient: httpClient,\n\t}\n}\n\n\/\/ Key is the Stripe API key used globally in the binding.\nvar Key string\n\nvar debug bool\nvar backend Backend\n\n\/\/ SetDebug enables additional tracing globally.\n\/\/ The method is designed for used during testing.\nfunc SetDebug(value bool) {\n\tdebug = value\n}\n\n\/\/ GetBackend returns the currently used backend in the binding.\nfunc GetBackend() Backend {\n\tif backend == nil {\n\t\tbackend = NewInternalBackend(http.DefaultClient, \"\")\n\t}\n\n\treturn backend\n}\n\n\/\/ SetBackend sets the backend used in the binding.\nfunc SetBackend(b Backend) {\n\tbackend = b\n}\n\n\/\/ Call is the Backend.Call implementation for invoking Stripe APIs.\nfunc (s *InternalBackend) Call(method, path, token string, body *url.Values, v interface{}) error {\n\tif !strings.HasPrefix(path, \"\/\") {\n\t\tpath = \"\/\" + path\n\t}\n\n\tpath = s.url + path\n\n\tif body != nil && len(*body) > 0 {\n\t\tpath += \"?\" + body.Encode()\n\t}\n\n\treq, err := http.NewRequest(method, path, nil)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot create Stripe request: %v\\n\", err)\n\t\treturn err\n\t}\n\n\treq.SetBasicAuth(token, \"\")\n\treq.Header.Add(\"Stripe-Version\", apiversion)\n\treq.Header.Add(\"User-Agent\", \"Stripe.Go-\"+clientversion)\n\n\tlog.Printf(\"Requesting %v %q\\n\", method, path)\n\tstart := time.Now()\n\n\tres, err := s.httpClient.Do(req)\n\n\tif debug {\n\t\tlog.Printf(\"Completed in %v\\n\", time.Since(start))\n\t}\n\n\tif err != nil {\n\t\tlog.Printf(\"Request to Stripe failed: %v\\n\", err)\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\n\tresBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Cannot parse Stripe response: %v\\n\", err)\n\t\treturn err\n\t}\n\n\tif res.StatusCode >= 400 {\n\t\t\/\/ for some odd reason, the Erro structure doesn't unmarshal\n\t\t\/\/ initially I thought it was because it's a struct inside of a struct\n\t\t\/\/ but even after trying that, it still didn't work\n\t\t\/\/ so unmarshalling to a map for now and parsing the results manually\n\t\t\/\/ but should investigate later\n\t\tvar errMap map[string]interface{}\n\t\tjson.Unmarshal(resBody, &errMap)\n\n\t\tif e, found := errMap[\"error\"]; !found {\n\t\t\terr := errors.New(string(resBody))\n\t\t\tlog.Printf(\"Unparsable error returned from Stripe: %v\\n\", err)\n\t\t\treturn err\n\t\t} else {\n\t\t\troot := e.(map[string]interface{})\n\t\t\terr := &Error{\n\t\t\t\tType:           ErrorType(root[\"type\"].(string)),\n\t\t\t\tMsg:            root[\"message\"].(string),\n\t\t\t\tHttpStatusCode: res.StatusCode,\n\t\t\t}\n\n\t\t\tif code, found := root[\"code\"]; found {\n\t\t\t\terr.Code = ErrorCode(code.(string))\n\t\t\t}\n\n\t\t\tif param, found := root[\"param\"]; found {\n\t\t\t\terr.Param = param.(string)\n\t\t\t}\n\n\t\t\tlog.Printf(\"Error encountered from Stripe: %v\\n\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif debug {\n\t\tlog.Printf(\"Stripe Response: %q\\n\", resBody)\n\t}\n\n\tif v != nil {\n\t\treturn json.Unmarshal(resBody, v)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package triplestore\n\nimport (\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"reflect\"\n\t\"time\"\n)\n\nconst (\n\tpredTag = \"predicate\"\n\tsubTag  = \"subject\"\n)\n\nvar random = rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\/\/ Convert a Struct or ptr to Struct into triples\n\/\/ using field tags.\n\/\/ For each struct's field a triple is created:\n\/\/ - Subject: function first argument\n\/\/ - Predicate: tag value\n\/\/ - Literal: actual field value according to field's type\n\/\/ Unsupported types are ignored\nfunc TriplesFromStruct(sub string, i interface{}) (out []Triple) {\n\tval := reflect.ValueOf(i)\n\n\tvar ok bool\n\tval, ok = getStructOrPtrToStruct(val)\n\tif !ok {\n\t\treturn\n\t}\n\n\tst := val.Type()\n\n\tfor i := 0; i < st.NumField(); i++ {\n\t\tfield, fVal := st.Field(i), val.Field(i)\n\t\tif !fVal.CanInterface() {\n\t\t\tcontinue\n\t\t}\n\n\t\tintValue := reflect.ValueOf(fVal.Interface())\n\t\tif intValue.Kind() == reflect.Ptr && intValue.IsNil() {\n\t\t\tcontinue\n\t\t}\n\n\t\tpred := field.Tag.Get(predTag)\n\t\tif tri, ok := buildTripleFromVal(sub, pred, fVal); ok {\n\t\t\tout = append(out, tri)\n\t\t}\n\n\t\ttag, embedded := field.Tag.Lookup(subTag)\n\t\tfVal, ok := getStructOrPtrToStruct(fVal)\n\t\tif ok && embedded {\n\t\t\tembedSub := tag\n\t\t\tif tag == \"rand\" {\n\t\t\t\tembedSub = fmt.Sprintf(\"%x\", random.Uint32())\n\t\t\t}\n\t\t\ttris := TriplesFromStruct(embedSub, fVal.Interface())\n\t\t\tout = append(out, tris...)\n\t\t\tif embedPred, hasPred := field.Tag.Lookup(predTag); hasPred {\n\t\t\t\tout = append(out, SubjPred(sub, embedPred).Resource(embedSub))\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch fVal.Kind() {\n\t\tcase reflect.Slice:\n\t\t\tlength := fVal.Len()\n\t\t\tfor i := 0; i < length; i++ {\n\t\t\t\tsliceVal := fVal.Index(i)\n\t\t\t\tif tri, ok := buildTripleFromVal(sub, pred, sliceVal); ok {\n\t\t\t\t\tout = append(out, tri)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn\n}\n\nfunc buildTripleFromVal(sub, pred string, v reflect.Value) (Triple, bool) {\n\tif !v.CanInterface() {\n\t\treturn nil, false\n\t}\n\tif pred == \"\" {\n\t\treturn nil, false\n\t}\n\tobjLit, err := ObjectLiteral(v.Interface())\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\n\treturn SubjPred(sub, pred).Object(objLit), true\n}\n\nfunc getStructOrPtrToStruct(v reflect.Value) (reflect.Value, bool) {\n\tswitch v.Kind() {\n\tcase reflect.Struct:\n\t\treturn v, true\n\tcase reflect.Ptr:\n\t\tif v.Elem().Kind() == reflect.Struct {\n\t\t\treturn v.Elem(), true\n\t\t}\n\t}\n\n\treturn v, false\n}\n<commit_msg>Seed random ID generator safe for concurrent use<commit_after>package triplestore\n\nimport (\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"reflect\"\n\t\"time\"\n)\n\nconst (\n\tpredTag = \"predicate\"\n\tsubTag  = \"subject\"\n)\n\nfunc init() {\n\trand.Seed(time.Now().UnixNano())\n}\n\n\/\/ Convert a Struct or ptr to Struct into triples\n\/\/ using field tags.\n\/\/ For each struct's field a triple is created:\n\/\/ - Subject: function first argument\n\/\/ - Predicate: tag value\n\/\/ - Literal: actual field value according to field's type\n\/\/ Unsupported types are ignored\nfunc TriplesFromStruct(sub string, i interface{}) (out []Triple) {\n\tval := reflect.ValueOf(i)\n\n\tvar ok bool\n\tval, ok = getStructOrPtrToStruct(val)\n\tif !ok {\n\t\treturn\n\t}\n\n\tst := val.Type()\n\n\tfor i := 0; i < st.NumField(); i++ {\n\t\tfield, fVal := st.Field(i), val.Field(i)\n\t\tif !fVal.CanInterface() {\n\t\t\tcontinue\n\t\t}\n\n\t\tintValue := reflect.ValueOf(fVal.Interface())\n\t\tif intValue.Kind() == reflect.Ptr && intValue.IsNil() {\n\t\t\tcontinue\n\t\t}\n\n\t\tpred := field.Tag.Get(predTag)\n\t\tif tri, ok := buildTripleFromVal(sub, pred, fVal); ok {\n\t\t\tout = append(out, tri)\n\t\t}\n\n\t\ttag, embedded := field.Tag.Lookup(subTag)\n\t\tfVal, ok := getStructOrPtrToStruct(fVal)\n\t\tif ok && embedded {\n\t\t\tembedSub := tag\n\t\t\tif tag == \"rand\" {\n\t\t\t\tembedSub = fmt.Sprintf(\"%x\", rand.Uint32())\n\t\t\t}\n\t\t\ttris := TriplesFromStruct(embedSub, fVal.Interface())\n\t\t\tout = append(out, tris...)\n\t\t\tif embedPred, hasPred := field.Tag.Lookup(predTag); hasPred {\n\t\t\t\tout = append(out, SubjPred(sub, embedPred).Resource(embedSub))\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch fVal.Kind() {\n\t\tcase reflect.Slice:\n\t\t\tlength := fVal.Len()\n\t\t\tfor i := 0; i < length; i++ {\n\t\t\t\tsliceVal := fVal.Index(i)\n\t\t\t\tif tri, ok := buildTripleFromVal(sub, pred, sliceVal); ok {\n\t\t\t\t\tout = append(out, tri)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn\n}\n\nfunc buildTripleFromVal(sub, pred string, v reflect.Value) (Triple, bool) {\n\tif !v.CanInterface() {\n\t\treturn nil, false\n\t}\n\tif pred == \"\" {\n\t\treturn nil, false\n\t}\n\tobjLit, err := ObjectLiteral(v.Interface())\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\n\treturn SubjPred(sub, pred).Object(objLit), true\n}\n\nfunc getStructOrPtrToStruct(v reflect.Value) (reflect.Value, bool) {\n\tswitch v.Kind() {\n\tcase reflect.Struct:\n\t\treturn v, true\n\tcase reflect.Ptr:\n\t\tif v.Elem().Kind() == reflect.Struct {\n\t\t\treturn v.Elem(), true\n\t\t}\n\t}\n\n\treturn v, false\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\t\"net\/url\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/philips\/go-mailgun\"\n)\n\ntype config struct {\n\tSubscribegun struct {\n\t\tHostname string\n\t\tLists    []string\n\t}\n\tMailgun struct {\n\t\tKey string\n\t}\n}\n\nvar mg *mailgun.Client\nvar cfg config\n\ntype mail struct {\n\tfrom      string\n\tto        []string\n\tcc        []string\n\tbcc       []string\n\tsubject   string\n\thtml      string\n\ttext      string\n\theaders   map[string]string\n\toptions   map[string]string\n\tvariables map[string]string\n}\n\nfunc (m *mail) From() string                 { return m.from }\nfunc (m *mail) To() []string                 { return m.to }\nfunc (m *mail) Cc() []string                 { return m.cc }\nfunc (m *mail) Bcc() []string                { return m.bcc }\nfunc (m *mail) Subject() string              { return m.subject }\nfunc (m *mail) Html() string                 { return m.html }\nfunc (m *mail) Text() string                 { return m.text }\nfunc (m *mail) Headers() map[string]string   { return m.headers }\nfunc (m *mail) Options() map[string]string   { return m.options }\nfunc (m *mail) Variables() map[string]string { return m.variables }\n\nfunc randomString(l int) string {\n\tbytes := make([]byte, l)\n\tfor i := 0; i < l; i++ {\n\t\tbytes[i] = byte(randInt(65, 90))\n\t}\n\treturn string(bytes)\n}\n\nfunc randInt(min int, max int) int {\n\treturn min + rand.Intn(max-min)\n}\n\n\/\/ listAllowed checks to ensure that the list is in the configuration file as\n\/\/ a publicly subscribable list.\nfunc listAllowed(list string) bool {\n\tfor _, l := range cfg.Subscribegun.Lists {\n\t\tif l == list {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ confirmationHandler handles a confirmation link and changes the persons\n\/\/ subscription state to \"subscribed\" or \"unsubscribed\" if the token matches.\nfunc confirmationHandler(w http.ResponseWriter, r *http.Request) {\n\tmuxVars := mux.Vars(r)\n\n\tlistName := muxVars[\"list\"]\n\tif len(listName) == 0 {\n\t\thttp.Error(w, \"No list specified!\", 404)\n\t\treturn\n\t}\n\n\temail := muxVars[\"email\"]\n\tif len(email) == 0 {\n\t\thttp.Error(w, \"No email address!\", 400)\n\t\treturn\n\t}\n\n\ttoken := muxVars[\"token\"]\n\tif len(token) == 0 {\n\t\thttp.Error(w, \"No token!\", 400)\n\t\treturn\n\t}\n\n\tmember, err := mg.GetListMember(listName, email)\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error\", 500)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\taction := muxVars[\"action\"]\n\tif token != member.Vars[strings.Title(action) + \"Token\"] {\n\t\thttp.Error(w, \"Bad confirmation token\", 400)\n\t\treturn\n\t}\n\n\tif action == \"subscribe\" {\n\t\tmember.Subscribed = true\n\t\tfmt.Fprintf(w, \"Success! You are now subscribed to %s\", listName)\n\t} else if action == \"unsubscribe\" {\n\t\tmember.Subscribed = false\n\t\tfmt.Fprintf(w, \"Success! You are now unsubscribed from %s\", listName)\n\t} else {\n\t\thttp.Error(w, fmt.Sprintf(\"Unknown action %s\", action), 500);\n\t\treturn\n\t}\n\n\t_, err = mg.UpdateListMember(listName, member)\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error\", 500)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/ initialHandler subscribes or unsubscribes the requested email from the list\n\/\/ and sends a confirmation email with a token to ensure the email owner actually\n\/\/ requested the action.\nfunc initialHandler(w http.ResponseWriter, r *http.Request) {\n\tmuxVars := mux.Vars(r)\n\n\t\/\/ Deal with CORS stuff\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Add(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\tw.Header().Add(\"Access-Control-Allow-Headers\", \"Origin\")\n\tif w.Header().Get(\"access-control-request-headers\") != \"\" {\n\t\treturn\n\t}\n\n\tlistName := muxVars[\"list\"]\n\tif len(listName) == 0 {\n\t\thttp.Error(w, \"No list specified!\", 404)\n\t\treturn\n\t}\n\n\tif listAllowed(listName) == false {\n\t\thttp.Error(w, \"Unknown list.\", 403)\n\t\treturn\n\t}\n\n\temail := r.FormValue(\"email\")\n\n\taction := muxVars[\"action\"];\n\n\tswitch action {\n\tcase \"subscribe\": handleSubscribe(w, listName, email);\n\tcase \"unsubscribe\": handleUnsubscribe(w, listName, email);\n\tdefault: http.Error(w, fmt.Sprintf(\"Unknown action %s\", action), 500);\n\t}\n}\n\n\/\/ confirmURL generates a url.URL for a confirmation link that the user will\n\/\/ get via and must click to confirm a request.\nfunc confirmURL(action string, listName string, email string, key string) url.URL {\n\tu := url.URL{}\n\tu.Scheme = \"http\"\n\tu.Host = cfg.Subscribegun.Hostname\n\tu.Path = path.Join(\"\/\", action, listName, \"confirm\", email, key)\n\treturn u\n}\n\nfunc addListMember(listName string, email string) (string, error) {\n\t\/\/ Generate the tokens for the user\n\tvars := map[string]string{\n\t\t\"UnsubscribeToken\": randomString(16),\n\t\t\"SubscribeToken\":   randomString(16),\n\t}\n\tmember := mailgun.ListMember{email, false, vars, \"\", \"\"}\n\tkey := vars[\"SubscribeToken\"]\n\n\t_, err := mg.AddListMember(listName, member)\n\treturn key, err\n}\n\n\/\/ handleSubscribe handles a subscribe request.\nfunc handleSubscribe(w http.ResponseWriter, listName string, email string) {\n\tvar key string\n\n\tmember, err := mg.GetListMember(listName, email)\n\t\/\/ Try to add the member if it doesn't exist\n\tif err != nil {\n\t\tkey, err = addListMember(listName, email)\n\t} else {\n\t\tkey = member.Vars[\"SubscribeToken\"]\n\t}\n\t\n\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error\", 500)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tu := confirmURL(\"subscribe\", listName, email, key)\n\tconfirmMail := mail{\n\t\tfrom:    \"no-reply@lists.coreos.com\",\n\t\tto:      []string{email},\n\t\tsubject: \"confirm subscription to \" + listName,\n\t\ttext:    \"click here to confirm your subscription request to \" + listName + \":\\n\" + u.String(),\n\t}\n\t_, err = mg.Send(&confirmMail)\n\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error\", 500)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}\n\n\/\/ handleUnsubscribe handles an unsubscribe request.\nfunc handleUnsubscribe(w http.ResponseWriter, listName string, email string) {\n\tmember, err := mg.GetListMember(listName, email)\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error\", 500)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tkey := member.Vars[\"UnsubscribeToken\"]\n\n\tu := confirmURL(\"unsubscribe\", listName, email, key)\n\tconfirmMail := mail{\n\t\tfrom:    \"no-reply@lists.coreos.com\",\n\t\tto:      []string{email},\n\t\tsubject: \"confirm unsubscribe to \" + listName,\n\t\ttext:    \"click here to confirm your unsubscribe request to \" + listName + \":\\n\" + u.String(),\n\t}\n\t_, err = mg.Send(&confirmMail)\n\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error\", 500)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}\n\nfunc main() {\n\tconfigBytes, err := ioutil.ReadFile(os.Args[1])\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(configBytes, &cfg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tmg = mailgun.New(cfg.Mailgun.Key)\n\n\t\/\/ TODO: add a secret seed in here\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tr := mux.NewRouter()\n\n\tr.HandleFunc(\"\/{action}\/{list}\", initialHandler)\n\tr.HandleFunc(\"\/{action}\/{list}\/confirm\/{email}\/{token}\", confirmationHandler)\n\n\thttp.ListenAndServe(\":8080\", r)\n}\n<commit_msg>chore(subgun): go fmt<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/philips\/go-mailgun\"\n)\n\ntype config struct {\n\tSubscribegun struct {\n\t\tHostname string\n\t\tLists    []string\n\t}\n\tMailgun struct {\n\t\tKey string\n\t}\n}\n\nvar mg *mailgun.Client\nvar cfg config\n\ntype mail struct {\n\tfrom      string\n\tto        []string\n\tcc        []string\n\tbcc       []string\n\tsubject   string\n\thtml      string\n\ttext      string\n\theaders   map[string]string\n\toptions   map[string]string\n\tvariables map[string]string\n}\n\nfunc (m *mail) From() string                 { return m.from }\nfunc (m *mail) To() []string                 { return m.to }\nfunc (m *mail) Cc() []string                 { return m.cc }\nfunc (m *mail) Bcc() []string                { return m.bcc }\nfunc (m *mail) Subject() string              { return m.subject }\nfunc (m *mail) Html() string                 { return m.html }\nfunc (m *mail) Text() string                 { return m.text }\nfunc (m *mail) Headers() map[string]string   { return m.headers }\nfunc (m *mail) Options() map[string]string   { return m.options }\nfunc (m *mail) Variables() map[string]string { return m.variables }\n\nfunc randomString(l int) string {\n\tbytes := make([]byte, l)\n\tfor i := 0; i < l; i++ {\n\t\tbytes[i] = byte(randInt(65, 90))\n\t}\n\treturn string(bytes)\n}\n\nfunc randInt(min int, max int) int {\n\treturn min + rand.Intn(max-min)\n}\n\n\/\/ listAllowed checks to ensure that the list is in the configuration file as\n\/\/ a publicly subscribable list.\nfunc listAllowed(list string) bool {\n\tfor _, l := range cfg.Subscribegun.Lists {\n\t\tif l == list {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ confirmationHandler handles a confirmation link and changes the persons\n\/\/ subscription state to \"subscribed\" or \"unsubscribed\" if the token matches.\nfunc confirmationHandler(w http.ResponseWriter, r *http.Request) {\n\tmuxVars := mux.Vars(r)\n\n\tlistName := muxVars[\"list\"]\n\tif len(listName) == 0 {\n\t\thttp.Error(w, \"No list specified!\", 404)\n\t\treturn\n\t}\n\n\temail := muxVars[\"email\"]\n\tif len(email) == 0 {\n\t\thttp.Error(w, \"No email address!\", 400)\n\t\treturn\n\t}\n\n\ttoken := muxVars[\"token\"]\n\tif len(token) == 0 {\n\t\thttp.Error(w, \"No token!\", 400)\n\t\treturn\n\t}\n\n\tmember, err := mg.GetListMember(listName, email)\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error\", 500)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\taction := muxVars[\"action\"]\n\tif token != member.Vars[strings.Title(action)+\"Token\"] {\n\t\thttp.Error(w, \"Bad confirmation token\", 400)\n\t\treturn\n\t}\n\n\tif action == \"subscribe\" {\n\t\tmember.Subscribed = true\n\t\tfmt.Fprintf(w, \"Success! You are now subscribed to %s\", listName)\n\t} else if action == \"unsubscribe\" {\n\t\tmember.Subscribed = false\n\t\tfmt.Fprintf(w, \"Success! You are now unsubscribed from %s\", listName)\n\t} else {\n\t\thttp.Error(w, fmt.Sprintf(\"Unknown action %s\", action), 500)\n\t\treturn\n\t}\n\n\t_, err = mg.UpdateListMember(listName, member)\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error\", 500)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/ initialHandler subscribes or unsubscribes the requested email from the list\n\/\/ and sends a confirmation email with a token to ensure the email owner actually\n\/\/ requested the action.\nfunc initialHandler(w http.ResponseWriter, r *http.Request) {\n\tmuxVars := mux.Vars(r)\n\n\t\/\/ Deal with CORS stuff\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Add(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\tw.Header().Add(\"Access-Control-Allow-Headers\", \"Origin\")\n\tif w.Header().Get(\"access-control-request-headers\") != \"\" {\n\t\treturn\n\t}\n\n\tlistName := muxVars[\"list\"]\n\tif len(listName) == 0 {\n\t\thttp.Error(w, \"No list specified!\", 404)\n\t\treturn\n\t}\n\n\tif listAllowed(listName) == false {\n\t\thttp.Error(w, \"Unknown list.\", 403)\n\t\treturn\n\t}\n\n\temail := r.FormValue(\"email\")\n\n\taction := muxVars[\"action\"]\n\n\tswitch action {\n\tcase \"subscribe\":\n\t\thandleSubscribe(w, listName, email)\n\tcase \"unsubscribe\":\n\t\thandleUnsubscribe(w, listName, email)\n\tdefault:\n\t\thttp.Error(w, fmt.Sprintf(\"Unknown action %s\", action), 500)\n\t}\n}\n\n\/\/ confirmURL generates a url.URL for a confirmation link that the user will\n\/\/ get via and must click to confirm a request.\nfunc confirmURL(action string, listName string, email string, key string) url.URL {\n\tu := url.URL{}\n\tu.Scheme = \"http\"\n\tu.Host = cfg.Subscribegun.Hostname\n\tu.Path = path.Join(\"\/\", action, listName, \"confirm\", email, key)\n\treturn u\n}\n\nfunc addListMember(listName string, email string) (string, error) {\n\t\/\/ Generate the tokens for the user\n\tvars := map[string]string{\n\t\t\"UnsubscribeToken\": randomString(16),\n\t\t\"SubscribeToken\":   randomString(16),\n\t}\n\tmember := mailgun.ListMember{email, false, vars, \"\", \"\"}\n\tkey := vars[\"SubscribeToken\"]\n\n\t_, err := mg.AddListMember(listName, member)\n\treturn key, err\n}\n\n\/\/ handleSubscribe handles a subscribe request.\nfunc handleSubscribe(w http.ResponseWriter, listName string, email string) {\n\tvar key string\n\n\tmember, err := mg.GetListMember(listName, email)\n\t\/\/ Try to add the member if it doesn't exist\n\tif err != nil {\n\t\tkey, err = addListMember(listName, email)\n\t} else {\n\t\tkey = member.Vars[\"SubscribeToken\"]\n\t}\n\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error\", 500)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tu := confirmURL(\"subscribe\", listName, email, key)\n\tconfirmMail := mail{\n\t\tfrom:    \"no-reply@lists.coreos.com\",\n\t\tto:      []string{email},\n\t\tsubject: \"confirm subscription to \" + listName,\n\t\ttext:    \"click here to confirm your subscription request to \" + listName + \":\\n\" + u.String(),\n\t}\n\t_, err = mg.Send(&confirmMail)\n\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error\", 500)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}\n\n\/\/ handleUnsubscribe handles an unsubscribe request.\nfunc handleUnsubscribe(w http.ResponseWriter, listName string, email string) {\n\tmember, err := mg.GetListMember(listName, email)\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error\", 500)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tkey := member.Vars[\"UnsubscribeToken\"]\n\n\tu := confirmURL(\"unsubscribe\", listName, email, key)\n\tconfirmMail := mail{\n\t\tfrom:    \"no-reply@lists.coreos.com\",\n\t\tto:      []string{email},\n\t\tsubject: \"confirm unsubscribe to \" + listName,\n\t\ttext:    \"click here to confirm your unsubscribe request to \" + listName + \":\\n\" + u.String(),\n\t}\n\t_, err = mg.Send(&confirmMail)\n\n\tif err != nil {\n\t\thttp.Error(w, \"Internal error\", 500)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}\n\nfunc main() {\n\tconfigBytes, err := ioutil.ReadFile(os.Args[1])\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = json.Unmarshal(configBytes, &cfg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tmg = mailgun.New(cfg.Mailgun.Key)\n\n\t\/\/ TODO: add a secret seed in here\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tr := mux.NewRouter()\n\n\tr.HandleFunc(\"\/{action}\/{list}\", initialHandler)\n\tr.HandleFunc(\"\/{action}\/{list}\/confirm\/{email}\/{token}\", confirmationHandler)\n\n\thttp.ListenAndServe(\":8080\", r)\n}\n<|endoftext|>"}
{"text":"<commit_before>package survey\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/AlecAivazis\/survey\/v2\/core\"\n\t\"github.com\/AlecAivazis\/survey\/v2\/terminal\"\n)\n\n\/\/ DefaultAskOptions is the default options on ask, using the OS stdio.\nfunc defaultAskOptions() *AskOptions {\n\treturn &AskOptions{\n\t\tStdio: terminal.Stdio{\n\t\t\tIn:  os.Stdin,\n\t\t\tOut: os.Stdout,\n\t\t\tErr: os.Stderr,\n\t\t},\n\t\tPromptConfig: PromptConfig{\n\t\t\tPageSize:  7,\n\t\t\tHelpInput: \"?\",\n\t\t\tIcons: IconSet{\n\t\t\t\tError: Icon{\n\t\t\t\t\tText:   \"X\",\n\t\t\t\t\tFormat: \"red\",\n\t\t\t\t},\n\t\t\t\tHelp: Icon{\n\t\t\t\t\tText:   \"?\",\n\t\t\t\t\tFormat: \"cyan\",\n\t\t\t\t},\n\t\t\t\tQuestion: Icon{\n\t\t\t\t\tText:   \"?\",\n\t\t\t\t\tFormat: \"green+hb\",\n\t\t\t\t},\n\t\t\t\tMarkedOption: Icon{\n\t\t\t\t\tText:   \"[x]\",\n\t\t\t\t\tFormat: \"green\",\n\t\t\t\t},\n\t\t\t\tUnmarkedOption: Icon{\n\t\t\t\t\tText:   \"[ ]\",\n\t\t\t\t\tFormat: \"default+hb\",\n\t\t\t\t},\n\t\t\t\tSelectFocus: Icon{\n\t\t\t\t\tText:   \">\",\n\t\t\t\t\tFormat: \"cyan+b\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tFilter: func(filter string, value string, index int) (include bool) {\n\t\t\t\tfilter = strings.ToLower(filter)\n\n\t\t\t\t\/\/ include this option if it matches\n\t\t\t\treturn strings.Contains(strings.ToLower(value), filter)\n\t\t\t},\n\t\t},\n\t}\n}\nfunc defaultPromptConfig() *PromptConfig {\n\treturn &defaultAskOptions().PromptConfig\n}\n\nfunc defaultIcons() *IconSet {\n\treturn &defaultPromptConfig().Icons\n}\n\n\/\/ OptionAnswer is an ergonomic alias for core.OptionAnswer\ntype OptionAnswer = core.OptionAnswer\n\n\/\/ Icon holds the text and format to show for a particular icon\ntype Icon struct {\n\tText   string\n\tFormat string\n}\n\n\/\/ IconSet holds the icons to use for various prompts\ntype IconSet struct {\n\tHelpInput      Icon\n\tError          Icon\n\tHelp           Icon\n\tQuestion       Icon\n\tMarkedOption   Icon\n\tUnmarkedOption Icon\n\tSelectFocus    Icon\n}\n\n\/\/ Validator is a function passed to a Question after a user has provided a response.\n\/\/ If the function returns an error, then the user will be prompted again for another\n\/\/ response.\ntype Validator func(ans interface{}) error\n\n\/\/ Transformer is a function passed to a Question after a user has provided a response.\n\/\/ The function can be used to implement a custom logic that will result to return\n\/\/ a different representation of the given answer.\n\/\/\n\/\/ Look `TransformString`, `ToLower` `Title` and `ComposeTransformers` for more.\ntype Transformer func(ans interface{}) (newAns interface{})\n\n\/\/ Question is the core data structure for a survey questionnaire.\ntype Question struct {\n\tName      string\n\tPrompt    Prompt\n\tValidate  Validator\n\tTransform Transformer\n}\n\n\/\/ PromptConfig holds the global configuration for a prompt\ntype PromptConfig struct {\n\tPageSize  int\n\tIcons     IconSet\n\tHelpInput string\n\tFilter    func(filter string, option string, index int) bool\n}\n\n\/\/ Prompt is the primary interface for the objects that can take user input\n\/\/ and return a response.\ntype Prompt interface {\n\tPrompt(config *PromptConfig) (interface{}, error)\n\tCleanup(*PromptConfig, interface{}) error\n\tError(*PromptConfig, error) error\n}\n\n\/\/ PromptAgainer Interface for Prompts that support prompting again after invalid input\ntype PromptAgainer interface {\n\tPromptAgain(config *PromptConfig, invalid interface{}, err error) (interface{}, error)\n}\n\n\/\/ AskOpt allows setting optional ask options.\ntype AskOpt func(options *AskOptions) error\n\n\/\/ AskOptions provides additional options on ask.\ntype AskOptions struct {\n\tStdio        terminal.Stdio\n\tValidators   []Validator\n\tPromptConfig PromptConfig\n}\n\n\/\/ WithStdio specifies the standard input, output and error files survey\n\/\/ interacts with. By default, these are os.Stdin, os.Stdout, and os.Stderr.\nfunc WithStdio(in terminal.FileReader, out terminal.FileWriter, err io.Writer) AskOpt {\n\treturn func(options *AskOptions) error {\n\t\toptions.Stdio.In = in\n\t\toptions.Stdio.Out = out\n\t\toptions.Stdio.Err = err\n\t\treturn nil\n\t}\n}\n\n\/\/ WithFilter specifies the default filter to use when asking questions.\nfunc WithFilter(filter func(filter string, value string, index int) (include bool)) AskOpt {\n\treturn func(options *AskOptions) error {\n\t\t\/\/ save the filter internally\n\t\toptions.PromptConfig.Filter = filter\n\n\t\treturn nil\n\t}\n}\n\n\/\/ WithValidator specifies a validator to use while prompting the user\nfunc WithValidator(v Validator) AskOpt {\n\treturn func(options *AskOptions) error {\n\t\t\/\/ add the provided validator to the list\n\t\toptions.Validators = append(options.Validators, v)\n\n\t\t\/\/ nothing went wrong\n\t\treturn nil\n\t}\n}\n\ntype wantsStdio interface {\n\tWithStdio(terminal.Stdio)\n}\n\n\/\/ WithPageSize sets the default page size used by prompts\nfunc WithPageSize(pageSize int) AskOpt {\n\treturn func(options *AskOptions) error {\n\t\t\/\/ set the page size\n\t\toptions.PromptConfig.PageSize = pageSize\n\n\t\t\/\/ nothing went wrong\n\t\treturn nil\n\t}\n}\n\n\/\/ WithHelpInput changes the character that prompts look for to give the user helpful information.\nfunc WithHelpInput(r rune) AskOpt {\n\treturn func(options *AskOptions) error {\n\t\t\/\/ set the input character\n\t\toptions.PromptConfig.HelpInput = string(r)\n\n\t\t\/\/ nothing went wrong\n\t\treturn nil\n\t}\n}\n\n\/\/ WithIcons sets the icons that will be used when prompting the user\nfunc WithIcons(setIcons func(*IconSet)) AskOpt {\n\treturn func(options *AskOptions) error {\n\t\t\/\/ update the default icons with whatever the user says\n\t\tsetIcons(&options.PromptConfig.Icons)\n\n\t\t\/\/ nothing went wrong\n\t\treturn nil\n\t}\n}\n\n\/*\nAskOne performs the prompt for a single prompt and asks for validation if required.\nResponse types should be something that can be casted from the response type designated\nin the documentation. For example:\n\n\tname := \"\"\n\tprompt := &survey.Input{\n\t\tMessage: \"name\",\n\t}\n\n\tsurvey.AskOne(prompt, &name)\n\n*\/\nfunc AskOne(p Prompt, response interface{}, opts ...AskOpt) error {\n\terr := Ask([]*Question{{Prompt: p}}, response, opts...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/*\nAsk performs the prompt loop, asking for validation when appropriate. The response\ntype can be one of two options. If a struct is passed, the answer will be written to\nthe field whose name matches the Name field on the corresponding question. Field types\nshould be something that can be casted from the response type designated in the\ndocumentation. Note, a survey tag can also be used to identify a Otherwise, a\nmap[string]interface{} can be passed, responses will be written to the key with the\nmatching name. For example:\n\n\tqs := []*survey.Question{\n\t\t{\n\t\t\tName:     \"name\",\n\t\t\tPrompt:   &survey.Input{Message: \"What is your name?\"},\n\t\t\tValidate: survey.Required,\n\t\t\tTransform: survey.Title,\n\t\t},\n\t}\n\n\tanswers := struct{ Name string }{}\n\n\n\terr := survey.Ask(qs, &answers)\n*\/\nfunc Ask(qs []*Question, response interface{}, opts ...AskOpt) error {\n\t\/\/ build up the configuration options\n\toptions := defaultAskOptions()\n\tfor _, opt := range opts {\n\t\tif err := opt(options); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ if we weren't passed a place to record the answers\n\tif response == nil {\n\t\t\/\/ we can't go any further\n\t\treturn errors.New(\"cannot call Ask() with a nil reference to record the answers\")\n\t}\n\n\t\/\/ go over every question\n\tfor _, q := range qs {\n\t\t\/\/ If Prompt implements controllable stdio, pass in specified stdio.\n\t\tif p, ok := q.Prompt.(wantsStdio); ok {\n\t\t\tp.WithStdio(options.Stdio)\n\t\t}\n\n\t\t\/\/ grab the user input and save it\n\t\tans, err := q.Prompt.Prompt(&options.PromptConfig)\n\t\t\/\/ if there was a problem\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ build up a list of validators that we have to apply to this question\n\t\tvalidators := []Validator{}\n\n\t\t\/\/ make sure to include the question specific one\n\t\tif q.Validate != nil {\n\t\t\tvalidators = append(validators, q.Validate)\n\t\t}\n\t\t\/\/ add any \"global\" validators\n\t\tfor _, validator := range options.Validators {\n\t\t\tvalidators = append(validators, validator)\n\t\t}\n\n\t\t\/\/ apply every validator to thte response\n\t\tfor _, validator := range validators {\n\t\t\t\/\/ wait for a valid response\n\t\t\tfor invalid := validator(ans); invalid != nil; invalid = validator(ans) {\n\t\t\t\terr := q.Prompt.Error(&options.PromptConfig, invalid)\n\t\t\t\t\/\/ if there was a problem\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t\/\/ ask for more input\n\t\t\t\tif promptAgainer, ok := q.Prompt.(PromptAgainer); ok {\n\t\t\t\t\tans, err = promptAgainer.PromptAgain(&options.PromptConfig, ans, invalid)\n\t\t\t\t} else {\n\t\t\t\t\tans, err = q.Prompt.Prompt(&options.PromptConfig)\n\t\t\t\t}\n\t\t\t\t\/\/ if there was a problem\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif q.Transform != nil {\n\t\t\t\/\/ check if we have a transformer available, if so\n\t\t\t\/\/ then try to acquire the new representation of the\n\t\t\t\/\/ answer, if the resulting answer is not nil.\n\t\t\tif newAns := q.Transform(ans); newAns != nil {\n\t\t\t\tans = newAns\n\t\t\t}\n\t\t}\n\n\t\t\/\/ tell the prompt to cleanup with the validated value\n\t\tq.Prompt.Cleanup(&options.PromptConfig, ans)\n\n\t\t\/\/ if something went wrong\n\t\tif err != nil {\n\t\t\t\/\/ stop listening\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ add it to the map\n\t\terr = core.WriteAnswer(response, q.Name, ans)\n\t\t\/\/ if something went wrong\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\t\/\/ return the response\n\treturn nil\n}\n\n\/\/ paginate returns a single page of choices given the page size, the total list of\n\/\/ possible choices, and the current selected index in the total list.\nfunc paginate(pageSize int, choices []core.OptionAnswer, sel int) ([]core.OptionAnswer, int) {\n\tvar start, end, cursor int\n\n\tif len(choices) < pageSize {\n\t\t\/\/ if we dont have enough options to fill a page\n\t\tstart = 0\n\t\tend = len(choices)\n\t\tcursor = sel\n\n\t} else if sel < pageSize\/2 {\n\t\t\/\/ if we are in the first half page\n\t\tstart = 0\n\t\tend = pageSize\n\t\tcursor = sel\n\n\t} else if len(choices)-sel-1 < pageSize\/2 {\n\t\t\/\/ if we are in the last half page\n\t\tstart = len(choices) - pageSize\n\t\tend = len(choices)\n\t\tcursor = sel - start\n\n\t} else {\n\t\t\/\/ somewhere in the middle\n\t\tabove := pageSize \/ 2\n\t\tbelow := pageSize - above\n\n\t\tcursor = pageSize \/ 2\n\t\tstart = sel - above\n\t\tend = sel + below\n\t}\n\n\t\/\/ return the subset we care about and the index\n\treturn choices[start:end], cursor\n}\n<commit_msg>survey: prevent panic on nil AskOpt (#243)<commit_after>package survey\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/AlecAivazis\/survey\/v2\/core\"\n\t\"github.com\/AlecAivazis\/survey\/v2\/terminal\"\n)\n\n\/\/ DefaultAskOptions is the default options on ask, using the OS stdio.\nfunc defaultAskOptions() *AskOptions {\n\treturn &AskOptions{\n\t\tStdio: terminal.Stdio{\n\t\t\tIn:  os.Stdin,\n\t\t\tOut: os.Stdout,\n\t\t\tErr: os.Stderr,\n\t\t},\n\t\tPromptConfig: PromptConfig{\n\t\t\tPageSize:  7,\n\t\t\tHelpInput: \"?\",\n\t\t\tIcons: IconSet{\n\t\t\t\tError: Icon{\n\t\t\t\t\tText:   \"X\",\n\t\t\t\t\tFormat: \"red\",\n\t\t\t\t},\n\t\t\t\tHelp: Icon{\n\t\t\t\t\tText:   \"?\",\n\t\t\t\t\tFormat: \"cyan\",\n\t\t\t\t},\n\t\t\t\tQuestion: Icon{\n\t\t\t\t\tText:   \"?\",\n\t\t\t\t\tFormat: \"green+hb\",\n\t\t\t\t},\n\t\t\t\tMarkedOption: Icon{\n\t\t\t\t\tText:   \"[x]\",\n\t\t\t\t\tFormat: \"green\",\n\t\t\t\t},\n\t\t\t\tUnmarkedOption: Icon{\n\t\t\t\t\tText:   \"[ ]\",\n\t\t\t\t\tFormat: \"default+hb\",\n\t\t\t\t},\n\t\t\t\tSelectFocus: Icon{\n\t\t\t\t\tText:   \">\",\n\t\t\t\t\tFormat: \"cyan+b\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tFilter: func(filter string, value string, index int) (include bool) {\n\t\t\t\tfilter = strings.ToLower(filter)\n\n\t\t\t\t\/\/ include this option if it matches\n\t\t\t\treturn strings.Contains(strings.ToLower(value), filter)\n\t\t\t},\n\t\t},\n\t}\n}\nfunc defaultPromptConfig() *PromptConfig {\n\treturn &defaultAskOptions().PromptConfig\n}\n\nfunc defaultIcons() *IconSet {\n\treturn &defaultPromptConfig().Icons\n}\n\n\/\/ OptionAnswer is an ergonomic alias for core.OptionAnswer\ntype OptionAnswer = core.OptionAnswer\n\n\/\/ Icon holds the text and format to show for a particular icon\ntype Icon struct {\n\tText   string\n\tFormat string\n}\n\n\/\/ IconSet holds the icons to use for various prompts\ntype IconSet struct {\n\tHelpInput      Icon\n\tError          Icon\n\tHelp           Icon\n\tQuestion       Icon\n\tMarkedOption   Icon\n\tUnmarkedOption Icon\n\tSelectFocus    Icon\n}\n\n\/\/ Validator is a function passed to a Question after a user has provided a response.\n\/\/ If the function returns an error, then the user will be prompted again for another\n\/\/ response.\ntype Validator func(ans interface{}) error\n\n\/\/ Transformer is a function passed to a Question after a user has provided a response.\n\/\/ The function can be used to implement a custom logic that will result to return\n\/\/ a different representation of the given answer.\n\/\/\n\/\/ Look `TransformString`, `ToLower` `Title` and `ComposeTransformers` for more.\ntype Transformer func(ans interface{}) (newAns interface{})\n\n\/\/ Question is the core data structure for a survey questionnaire.\ntype Question struct {\n\tName      string\n\tPrompt    Prompt\n\tValidate  Validator\n\tTransform Transformer\n}\n\n\/\/ PromptConfig holds the global configuration for a prompt\ntype PromptConfig struct {\n\tPageSize  int\n\tIcons     IconSet\n\tHelpInput string\n\tFilter    func(filter string, option string, index int) bool\n}\n\n\/\/ Prompt is the primary interface for the objects that can take user input\n\/\/ and return a response.\ntype Prompt interface {\n\tPrompt(config *PromptConfig) (interface{}, error)\n\tCleanup(*PromptConfig, interface{}) error\n\tError(*PromptConfig, error) error\n}\n\n\/\/ PromptAgainer Interface for Prompts that support prompting again after invalid input\ntype PromptAgainer interface {\n\tPromptAgain(config *PromptConfig, invalid interface{}, err error) (interface{}, error)\n}\n\n\/\/ AskOpt allows setting optional ask options.\ntype AskOpt func(options *AskOptions) error\n\n\/\/ AskOptions provides additional options on ask.\ntype AskOptions struct {\n\tStdio        terminal.Stdio\n\tValidators   []Validator\n\tPromptConfig PromptConfig\n}\n\n\/\/ WithStdio specifies the standard input, output and error files survey\n\/\/ interacts with. By default, these are os.Stdin, os.Stdout, and os.Stderr.\nfunc WithStdio(in terminal.FileReader, out terminal.FileWriter, err io.Writer) AskOpt {\n\treturn func(options *AskOptions) error {\n\t\toptions.Stdio.In = in\n\t\toptions.Stdio.Out = out\n\t\toptions.Stdio.Err = err\n\t\treturn nil\n\t}\n}\n\n\/\/ WithFilter specifies the default filter to use when asking questions.\nfunc WithFilter(filter func(filter string, value string, index int) (include bool)) AskOpt {\n\treturn func(options *AskOptions) error {\n\t\t\/\/ save the filter internally\n\t\toptions.PromptConfig.Filter = filter\n\n\t\treturn nil\n\t}\n}\n\n\/\/ WithValidator specifies a validator to use while prompting the user\nfunc WithValidator(v Validator) AskOpt {\n\treturn func(options *AskOptions) error {\n\t\t\/\/ add the provided validator to the list\n\t\toptions.Validators = append(options.Validators, v)\n\n\t\t\/\/ nothing went wrong\n\t\treturn nil\n\t}\n}\n\ntype wantsStdio interface {\n\tWithStdio(terminal.Stdio)\n}\n\n\/\/ WithPageSize sets the default page size used by prompts\nfunc WithPageSize(pageSize int) AskOpt {\n\treturn func(options *AskOptions) error {\n\t\t\/\/ set the page size\n\t\toptions.PromptConfig.PageSize = pageSize\n\n\t\t\/\/ nothing went wrong\n\t\treturn nil\n\t}\n}\n\n\/\/ WithHelpInput changes the character that prompts look for to give the user helpful information.\nfunc WithHelpInput(r rune) AskOpt {\n\treturn func(options *AskOptions) error {\n\t\t\/\/ set the input character\n\t\toptions.PromptConfig.HelpInput = string(r)\n\n\t\t\/\/ nothing went wrong\n\t\treturn nil\n\t}\n}\n\n\/\/ WithIcons sets the icons that will be used when prompting the user\nfunc WithIcons(setIcons func(*IconSet)) AskOpt {\n\treturn func(options *AskOptions) error {\n\t\t\/\/ update the default icons with whatever the user says\n\t\tsetIcons(&options.PromptConfig.Icons)\n\n\t\t\/\/ nothing went wrong\n\t\treturn nil\n\t}\n}\n\n\/*\nAskOne performs the prompt for a single prompt and asks for validation if required.\nResponse types should be something that can be casted from the response type designated\nin the documentation. For example:\n\n\tname := \"\"\n\tprompt := &survey.Input{\n\t\tMessage: \"name\",\n\t}\n\n\tsurvey.AskOne(prompt, &name)\n\n*\/\nfunc AskOne(p Prompt, response interface{}, opts ...AskOpt) error {\n\terr := Ask([]*Question{{Prompt: p}}, response, opts...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/*\nAsk performs the prompt loop, asking for validation when appropriate. The response\ntype can be one of two options. If a struct is passed, the answer will be written to\nthe field whose name matches the Name field on the corresponding question. Field types\nshould be something that can be casted from the response type designated in the\ndocumentation. Note, a survey tag can also be used to identify a Otherwise, a\nmap[string]interface{} can be passed, responses will be written to the key with the\nmatching name. For example:\n\n\tqs := []*survey.Question{\n\t\t{\n\t\t\tName:     \"name\",\n\t\t\tPrompt:   &survey.Input{Message: \"What is your name?\"},\n\t\t\tValidate: survey.Required,\n\t\t\tTransform: survey.Title,\n\t\t},\n\t}\n\n\tanswers := struct{ Name string }{}\n\n\n\terr := survey.Ask(qs, &answers)\n*\/\nfunc Ask(qs []*Question, response interface{}, opts ...AskOpt) error {\n\t\/\/ build up the configuration options\n\toptions := defaultAskOptions()\n\tfor _, opt := range opts {\n\t\tif opt == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := opt(options); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ if we weren't passed a place to record the answers\n\tif response == nil {\n\t\t\/\/ we can't go any further\n\t\treturn errors.New(\"cannot call Ask() with a nil reference to record the answers\")\n\t}\n\n\t\/\/ go over every question\n\tfor _, q := range qs {\n\t\t\/\/ If Prompt implements controllable stdio, pass in specified stdio.\n\t\tif p, ok := q.Prompt.(wantsStdio); ok {\n\t\t\tp.WithStdio(options.Stdio)\n\t\t}\n\n\t\t\/\/ grab the user input and save it\n\t\tans, err := q.Prompt.Prompt(&options.PromptConfig)\n\t\t\/\/ if there was a problem\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ build up a list of validators that we have to apply to this question\n\t\tvalidators := []Validator{}\n\n\t\t\/\/ make sure to include the question specific one\n\t\tif q.Validate != nil {\n\t\t\tvalidators = append(validators, q.Validate)\n\t\t}\n\t\t\/\/ add any \"global\" validators\n\t\tfor _, validator := range options.Validators {\n\t\t\tvalidators = append(validators, validator)\n\t\t}\n\n\t\t\/\/ apply every validator to thte response\n\t\tfor _, validator := range validators {\n\t\t\t\/\/ wait for a valid response\n\t\t\tfor invalid := validator(ans); invalid != nil; invalid = validator(ans) {\n\t\t\t\terr := q.Prompt.Error(&options.PromptConfig, invalid)\n\t\t\t\t\/\/ if there was a problem\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\t\/\/ ask for more input\n\t\t\t\tif promptAgainer, ok := q.Prompt.(PromptAgainer); ok {\n\t\t\t\t\tans, err = promptAgainer.PromptAgain(&options.PromptConfig, ans, invalid)\n\t\t\t\t} else {\n\t\t\t\t\tans, err = q.Prompt.Prompt(&options.PromptConfig)\n\t\t\t\t}\n\t\t\t\t\/\/ if there was a problem\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif q.Transform != nil {\n\t\t\t\/\/ check if we have a transformer available, if so\n\t\t\t\/\/ then try to acquire the new representation of the\n\t\t\t\/\/ answer, if the resulting answer is not nil.\n\t\t\tif newAns := q.Transform(ans); newAns != nil {\n\t\t\t\tans = newAns\n\t\t\t}\n\t\t}\n\n\t\t\/\/ tell the prompt to cleanup with the validated value\n\t\tq.Prompt.Cleanup(&options.PromptConfig, ans)\n\n\t\t\/\/ if something went wrong\n\t\tif err != nil {\n\t\t\t\/\/ stop listening\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ add it to the map\n\t\terr = core.WriteAnswer(response, q.Name, ans)\n\t\t\/\/ if something went wrong\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\t\/\/ return the response\n\treturn nil\n}\n\n\/\/ paginate returns a single page of choices given the page size, the total list of\n\/\/ possible choices, and the current selected index in the total list.\nfunc paginate(pageSize int, choices []core.OptionAnswer, sel int) ([]core.OptionAnswer, int) {\n\tvar start, end, cursor int\n\n\tif len(choices) < pageSize {\n\t\t\/\/ if we dont have enough options to fill a page\n\t\tstart = 0\n\t\tend = len(choices)\n\t\tcursor = sel\n\n\t} else if sel < pageSize\/2 {\n\t\t\/\/ if we are in the first half page\n\t\tstart = 0\n\t\tend = pageSize\n\t\tcursor = sel\n\n\t} else if len(choices)-sel-1 < pageSize\/2 {\n\t\t\/\/ if we are in the last half page\n\t\tstart = len(choices) - pageSize\n\t\tend = len(choices)\n\t\tcursor = sel - start\n\n\t} else {\n\t\t\/\/ somewhere in the middle\n\t\tabove := pageSize \/ 2\n\t\tbelow := pageSize - above\n\n\t\tcursor = pageSize \/ 2\n\t\tstart = sel - above\n\t\tend = sel + below\n\t}\n\n\t\/\/ return the subset we care about and the index\n\treturn choices[start:end], cursor\n}\n<|endoftext|>"}
{"text":"<commit_before>package controllers\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"encoding\/json\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/nuveo\/prest\/adapters\/postgres\"\n\t\"github.com\/nuveo\/prest\/api\"\n\t\"github.com\/nuveo\/prest\/statements\"\n)\n\n\/\/ GetTables list all (or filter) tables\nfunc GetTables(w http.ResponseWriter, r *http.Request) {\n\trequestWhere, values, err := postgres.WhereByRequest(r, 1)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tsqlTables := statements.Tables\n\tif requestWhere != \"\" {\n\t\tsqlTables = fmt.Sprint(\n\t\t\tstatements.TablesSelect,\n\t\t\tstatements.TablesWhere,\n\t\t\t\" AND \",\n\t\t\trequestWhere,\n\t\t\tstatements.TablesOrderBy)\n\t}\n\n\tobject, err := postgres.Query(sqlTables, values...)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(object)\n}\n\n\/\/ GetTablesByDatabaseAndSchema list all (or filter) tables based on database and schema\nfunc GetTablesByDatabaseAndSchema(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tdatabase, ok := vars[\"database\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse database in URI\")\n\t\thttp.Error(w, \"Unable to parse database in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tschema, ok := vars[\"schema\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse schema in URI\")\n\t\thttp.Error(w, \"Unable to parse schema in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\trequestWhere, values, err := postgres.WhereByRequest(r, 3)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tsqlSchemaTables := statements.SchemaTables\n\tif requestWhere != \"\" {\n\t\tsqlSchemaTables = fmt.Sprint(\n\t\t\tstatements.SchemaTablesSelect,\n\t\t\tstatements.SchemaTablesWhere,\n\t\t\t\" AND \",\n\t\t\trequestWhere,\n\t\t\tstatements.SchemaTablesOrderBy)\n\t}\n\n\tpage, err := postgres.PaginateIfPossible(r)\n\tif err != nil {\n\t\thttp.Error(w, \"Paging error\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tsqlSchemaTables = fmt.Sprint(sqlSchemaTables, \" \", page)\n\n\tvaluesAux := make([]interface{}, 0)\n\tvaluesAux = append(valuesAux, database)\n\tvaluesAux = append(valuesAux, schema)\n\tvaluesAux = append(valuesAux, values...)\n\n\tobject, err := postgres.Query(sqlSchemaTables, valuesAux...)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(object)\n}\n\n\/\/ SelectFromTables perform select in database\nfunc SelectFromTables(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tdatabase, ok := vars[\"database\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse database in URI\")\n\t\thttp.Error(w, \"Unable to parse database in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tschema, ok := vars[\"schema\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse schema in URI\")\n\t\thttp.Error(w, \"Unable to parse schema in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttable, ok := vars[\"table\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse table in URI\")\n\t\thttp.Error(w, \"Unable to parse table in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tquery := fmt.Sprintf(\"%s %s.%s.%s\", statements.SelectInTable, database, schema, table)\n\n\tjoinValues, err := postgres.JoinByRequest(r)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tfor _, j := range joinValues {\n\t\tquery = fmt.Sprint(query, j)\n\t}\n\n\trequestWhere, values, err := postgres.WhereByRequest(r, 1)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tsqlSelect := query\n\tif requestWhere != \"\" {\n\t\tsqlSelect = fmt.Sprint(\n\t\t\tquery,\n\t\t\t\" WHERE \",\n\t\t\trequestWhere)\n\t}\n\n\tpage, err := postgres.PaginateIfPossible(r)\n\tif err != nil {\n\t\thttp.Error(w, \"Paging error\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tsqlSelect = fmt.Sprint(sqlSelect, \" \", page)\n\n\tobject, err := postgres.Query(sqlSelect, values...)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(object)\n}\n\n\/\/ InsertInTables perform insert in specific table\nfunc InsertInTables(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tdatabase, ok := vars[\"database\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse database in URI\")\n\t\thttp.Error(w, \"Unable to parse database in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tschema, ok := vars[\"schema\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse schema in URI\")\n\t\thttp.Error(w, \"Unable to parse schema in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttable, ok := vars[\"table\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse table in URI\")\n\t\thttp.Error(w, \"Unable to parse table in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\treq := api.Request{}\n\terr := json.NewDecoder(r.Body).Decode(&req)\n\tif err != nil {\n\t\tlog.Println(\"InsertInTables:\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tobject, err := postgres.Insert(database, schema, table, req)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(object)\n}\n\n\/\/ DeleteFromTable perform delete sql\nfunc DeleteFromTable(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tdatabase, ok := vars[\"database\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse database in URI\")\n\t\thttp.Error(w, \"Unable to parse database in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tschema, ok := vars[\"schema\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse schema in URI\")\n\t\thttp.Error(w, \"Unable to parse schema in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttable, ok := vars[\"table\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse table in URI\")\n\t\thttp.Error(w, \"Unable to parse table in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\twhere, values, err := postgres.WhereByRequest(r, 1)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tobject, err := postgres.Delete(database, schema, table, where, values)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(object)\n}\n\n\/\/ UpdateTable perform update table\nfunc UpdateTable(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tdatabase, ok := vars[\"database\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse database in URI\")\n\t\thttp.Error(w, \"Unable to parse database in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tschema, ok := vars[\"schema\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse schema in URI\")\n\t\thttp.Error(w, \"Unable to parse schema in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttable, ok := vars[\"table\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse table in URI\")\n\t\thttp.Error(w, \"Unable to parse table in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\treq := api.Request{}\n\terr := json.NewDecoder(r.Body).Decode(&req)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\twhere, values, err := postgres.WhereByRequest(r, 1)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tobject, err := postgres.Update(database, schema, table, where, values, req)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(object)\n}\n<commit_msg>created order by<commit_after>package controllers\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"encoding\/json\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/nuveo\/prest\/adapters\/postgres\"\n\t\"github.com\/nuveo\/prest\/api\"\n\t\"github.com\/nuveo\/prest\/statements\"\n)\n\n\/\/ GetTables list all (or filter) tables\nfunc GetTables(w http.ResponseWriter, r *http.Request) {\n\trequestWhere, values, err := postgres.WhereByRequest(r, 1)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tsqlTables := statements.Tables\n\tif requestWhere != \"\" {\n\t\tsqlTables = fmt.Sprint(\n\t\t\tstatements.TablesSelect,\n\t\t\tstatements.TablesWhere,\n\t\t\t\" AND \",\n\t\t\trequestWhere,\n\t\t\tstatements.TablesOrderBy)\n\t}\n\n\tobject, err := postgres.Query(sqlTables, values...)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(object)\n}\n\n\/\/ GetTablesByDatabaseAndSchema list all (or filter) tables based on database and schema\nfunc GetTablesByDatabaseAndSchema(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tdatabase, ok := vars[\"database\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse database in URI\")\n\t\thttp.Error(w, \"Unable to parse database in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tschema, ok := vars[\"schema\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse schema in URI\")\n\t\thttp.Error(w, \"Unable to parse schema in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\trequestWhere, values, err := postgres.WhereByRequest(r, 3)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tsqlSchemaTables := statements.SchemaTables\n\tif requestWhere != \"\" {\n\t\tsqlSchemaTables = fmt.Sprint(\n\t\t\tstatements.SchemaTablesSelect,\n\t\t\tstatements.SchemaTablesWhere,\n\t\t\t\" AND \",\n\t\t\trequestWhere,\n\t\t\tstatements.SchemaTablesOrderBy)\n\t}\n\n\tpage, err := postgres.PaginateIfPossible(r)\n\tif err != nil {\n\t\thttp.Error(w, \"Paging error\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tsqlSchemaTables = fmt.Sprint(sqlSchemaTables, \" \", page)\n\n\tvaluesAux := make([]interface{}, 0)\n\tvaluesAux = append(valuesAux, database)\n\tvaluesAux = append(valuesAux, schema)\n\tvaluesAux = append(valuesAux, values...)\n\n\tobject, err := postgres.Query(sqlSchemaTables, valuesAux...)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(object)\n}\n\n\/\/ SelectFromTables perform select in database\nfunc SelectFromTables(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tdatabase, ok := vars[\"database\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse database in URI\")\n\t\thttp.Error(w, \"Unable to parse database in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tschema, ok := vars[\"schema\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse schema in URI\")\n\t\thttp.Error(w, \"Unable to parse schema in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttable, ok := vars[\"table\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse table in URI\")\n\t\thttp.Error(w, \"Unable to parse table in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tquery := fmt.Sprintf(\"%s %s.%s.%s\", statements.SelectInTable, database, schema, table)\n\n\tjoinValues, err := postgres.JoinByRequest(r)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tfor _, j := range joinValues {\n\t\tquery = fmt.Sprint(query, j)\n\t}\n\n\trequestWhere, values, err := postgres.WhereByRequest(r, 1)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tsqlSelect := query\n\tif requestWhere != \"\" {\n\t\tsqlSelect = fmt.Sprint(\n\t\t\tquery,\n\t\t\t\" WHERE \",\n\t\t\trequestWhere)\n\t}\n\n\torder, err := postgres.OrderByRequest(r)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tif len(order) > 0 {\n\t\tsqlSelect = fmt.Sprintf(\"%s %s\", sqlSelect, order)\n\t}\n\n\tpage, err := postgres.PaginateIfPossible(r)\n\tif err != nil {\n\t\thttp.Error(w, \"Paging error\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tsqlSelect = fmt.Sprint(sqlSelect, \" \", page)\n\n\tobject, err := postgres.Query(sqlSelect, values...)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(object)\n}\n\n\/\/ InsertInTables perform insert in specific table\nfunc InsertInTables(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tdatabase, ok := vars[\"database\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse database in URI\")\n\t\thttp.Error(w, \"Unable to parse database in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tschema, ok := vars[\"schema\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse schema in URI\")\n\t\thttp.Error(w, \"Unable to parse schema in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttable, ok := vars[\"table\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse table in URI\")\n\t\thttp.Error(w, \"Unable to parse table in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\treq := api.Request{}\n\terr := json.NewDecoder(r.Body).Decode(&req)\n\tif err != nil {\n\t\tlog.Println(\"InsertInTables:\", err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tobject, err := postgres.Insert(database, schema, table, req)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(object)\n}\n\n\/\/ DeleteFromTable perform delete sql\nfunc DeleteFromTable(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tdatabase, ok := vars[\"database\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse database in URI\")\n\t\thttp.Error(w, \"Unable to parse database in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tschema, ok := vars[\"schema\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse schema in URI\")\n\t\thttp.Error(w, \"Unable to parse schema in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttable, ok := vars[\"table\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse table in URI\")\n\t\thttp.Error(w, \"Unable to parse table in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\twhere, values, err := postgres.WhereByRequest(r, 1)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tobject, err := postgres.Delete(database, schema, table, where, values)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(object)\n}\n\n\/\/ UpdateTable perform update table\nfunc UpdateTable(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tdatabase, ok := vars[\"database\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse database in URI\")\n\t\thttp.Error(w, \"Unable to parse database in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\tschema, ok := vars[\"schema\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse schema in URI\")\n\t\thttp.Error(w, \"Unable to parse schema in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\ttable, ok := vars[\"table\"]\n\tif !ok {\n\t\tlog.Println(\"Unable to parse table in URI\")\n\t\thttp.Error(w, \"Unable to parse table in URI\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\treq := api.Request{}\n\terr := json.NewDecoder(r.Body).Decode(&req)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\twhere, values, err := postgres.WhereByRequest(r, 1)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tobject, err := postgres.Update(database, schema, table, where, values, req)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(object)\n}\n<|endoftext|>"}
{"text":"<commit_before>package iptables_test\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\/exec\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/guardian\/kawasaki\/iptables\"\n\tfakes \"code.cloudfoundry.org\/guardian\/kawasaki\/iptables\/iptablesfakes\"\n\t\"code.cloudfoundry.org\/guardian\/pkg\/locksmith\"\n\t\"github.com\/cloudfoundry\/gunk\/command_runner\/fake_command_runner\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"IPTables controller\", func() {\n\tvar (\n\t\tnetnsName          string\n\t\tprefix             string\n\t\tiptablesController iptables.IPTables\n\t\tfakeLocksmith      *FakeLocksmith\n\t\tfakeRunner         *fake_command_runner.FakeCommandRunner\n\t)\n\n\tBeforeEach(func() {\n\t\tSetDefaultEventuallyTimeout(3 * time.Second)\n\t\tnetnsName = fmt.Sprintf(\"ginkgo-netns-%d\", GinkgoParallelNode())\n\t\tmakeNamespace(netnsName)\n\n\t\tfakeRunner = fake_command_runner.New()\n\t\tfakeRunner.WhenRunning(fake_command_runner.CommandSpec{},\n\t\t\tfunc(cmd *exec.Cmd) error {\n\t\t\t\tif len(cmd.Args) >= 4 && cmd.Args[3] == \"panic\" {\n\t\t\t\t\tpanic(\"ops\")\n\t\t\t\t}\n\t\t\t\treturn wrapCmdInNs(netnsName, cmd).Run()\n\t\t\t},\n\t\t)\n\n\t\tfakeLocksmith = NewFakeLocksmith()\n\n\t\tprefix = fmt.Sprintf(\"g-%d\", GinkgoParallelNode())\n\t\tiptablesController = iptables.New(\"\/sbin\/iptables\", \"\/sbin\/iptables-restore\", fakeRunner, fakeLocksmith, prefix)\n\t})\n\n\tAfterEach(func() {\n\t\tdeleteNamespace(netnsName)\n\t})\n\n\tDescribe(\"CreateChain\", func() {\n\t\tIt(\"creates the chain\", func() {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t})\n\n\t\tContext(\"when the table is nat\", func() {\n\t\t\tIt(\"creates the nat chain\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).To(Succeed())\n\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", \"nat\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the chain already exists\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).To(Succeed())\n\t\t\t})\n\n\t\t\tIt(\"returns an error\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).NotTo(Succeed())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"PrependRule\", func() {\n\t\tIt(\"prepends the rule\", func() {\n\t\t\tfakeTCPRule := new(fakes.FakeRule)\n\t\t\tfakeTCPRule.FlagsReturns([]string{\"--protocol\", \"tcp\"})\n\t\t\tfakeUDPRule := new(fakes.FakeRule)\n\t\t\tfakeUDPRule.FlagsReturns([]string{\"--protocol\", \"udp\"})\n\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\n\t\t\tExpect(iptablesController.PrependRule(\"test-chain\", fakeTCPRule)).To(Succeed())\n\t\t\tExpect(iptablesController.PrependRule(\"test-chain\", fakeUDPRule)).To(Succeed())\n\n\t\t\tbuff := gbytes.NewBuffer()\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\tExpect(buff).To(gbytes.Say(\"-A test-chain -p udp\\n-A test-chain -p tcp\"))\n\t\t})\n\n\t\tIt(\"returns an error when the chain does not exist\", func() {\n\t\t\tfakeRule := new(fakes.FakeRule)\n\t\t\tfakeRule.FlagsReturns([]string{})\n\n\t\t\tExpect(iptablesController.PrependRule(\"test-chain\", fakeRule)).NotTo(Succeed())\n\t\t})\n\t})\n\n\tDescribe(\"BulkPrependRules\", func() {\n\t\tIt(\"appends the rules\", func() {\n\t\t\tfakeTCPRule := new(fakes.FakeRule)\n\t\t\tfakeTCPRule.FlagsReturns([]string{\"--protocol\", \"tcp\"})\n\t\t\tfakeUDPRule := new(fakes.FakeRule)\n\t\t\tfakeUDPRule.FlagsReturns([]string{\"--protocol\", \"udp\"})\n\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\t\t\tExpect(iptablesController.BulkPrependRules(\"test-chain\", []iptables.Rule{\n\t\t\t\tfakeTCPRule,\n\t\t\t\tfakeUDPRule,\n\t\t\t})).To(Succeed())\n\n\t\t\tbuff := gbytes.NewBuffer()\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\tExpect(buff).To(gbytes.Say(\"-A test-chain -p udp\\n-A test-chain -p tcp\"))\n\t\t})\n\n\t\tIt(\"returns an error when the chain does not exist\", func() {\n\t\t\tfakeRule := new(fakes.FakeRule)\n\t\t\tfakeRule.FlagsReturns([]string{\"--protocol\", \"tcp\"})\n\n\t\t\tExpect(iptablesController.BulkPrependRules(\"test-chain\", []iptables.Rule{fakeRule})).NotTo(Succeed())\n\t\t})\n\n\t\tContext(\"when there are no rules passed\", func() {\n\t\t\tIt(\"does nothing\", func() {\n\t\t\t\tExpect(iptablesController.BulkPrependRules(\"test-chain\", []iptables.Rule{})).To(Succeed())\n\t\t\t\tExpect(fakeRunner.ExecutedCommands()).To(BeZero())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"DeleteChain\", func() {\n\t\tBeforeEach(func() {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\t\t})\n\n\t\tIt(\"deletes the chain\", func() {\n\t\t\tExpect(iptablesController.DeleteChain(\"filter\", \"test-chain\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(1))\n\t\t})\n\n\t\tContext(\"when the table is nat\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).To(Succeed())\n\t\t\t})\n\n\t\t\tIt(\"deletes the nat chain\", func() {\n\t\t\t\tExpect(iptablesController.DeleteChain(\"nat\", \"test-chain\")).To(Succeed())\n\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", \"nat\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tEventually(sess).Should(gexec.Exit(1))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the chain does not exist\", func() {\n\t\t\tIt(\"does not return an error\", func() {\n\t\t\t\tExpect(iptablesController.DeleteChain(\"filter\", \"test-non-existing-chain\")).To(Succeed())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"FlushChain\", func() {\n\t\tvar table string\n\n\t\tBeforeEach(func() {\n\t\t\ttable = \"filter\"\n\t\t})\n\n\t\tJustBeforeEach(func() {\n\t\t\tExpect(iptablesController.CreateChain(table, \"test-chain\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-A\", \"test-chain\", \"-j\", \"ACCEPT\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t})\n\n\t\tIt(\"flushes the chain\", func() {\n\t\t\tExpect(iptablesController.FlushChain(table, \"test-chain\")).To(Succeed())\n\n\t\t\tbuff := gbytes.NewBuffer()\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\tConsistently(buff).ShouldNot(gbytes.Say(\"-A test-chain\"))\n\t\t})\n\n\t\tContext(\"when the table is nat\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\ttable = \"nat\"\n\t\t\t})\n\n\t\t\tIt(\"flushes the nat chain\", func() {\n\t\t\t\tExpect(iptablesController.FlushChain(table, \"test-chain\")).To(Succeed())\n\n\t\t\t\tbuff := gbytes.NewBuffer()\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\t\tConsistently(buff).ShouldNot(gbytes.Say(\"-A test-chain\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the chain does not exist\", func() {\n\t\t\tIt(\"does not return an error\", func() {\n\t\t\t\tExpect(iptablesController.FlushChain(\"filter\", \"test-non-existing-chain\")).To(Succeed())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"DeleteChainReferences\", func() {\n\t\tvar table string\n\n\t\tBeforeEach(func() {\n\t\t\ttable = \"filter\"\n\t\t})\n\n\t\tJustBeforeEach(func() {\n\t\t\tExpect(iptablesController.CreateChain(table, \"test-chain-1\")).To(Succeed())\n\t\t\tExpect(iptablesController.CreateChain(table, \"test-chain-2\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-A\", \"test-chain-1\", \"-j\", \"test-chain-2\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t})\n\n\t\tIt(\"deletes the references\", func() {\n\t\t\tExpect(iptablesController.DeleteChainReferences(table, \"test-chain-1\", \"test-chain-2\")).To(Succeed())\n\n\t\t\tEventually(func() string {\n\t\t\t\tbuff := gbytes.NewBuffer()\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-S\", \"test-chain-1\")), buff, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(sess).Should(gexec.Exit(0))\n\n\t\t\t\treturn string(buff.Contents())\n\t\t\t}).ShouldNot(ContainSubstring(\"test-chain-2\"))\n\t\t})\n\t})\n\n\tDescribe(\"Locking Behaviour\", func() {\n\t\tContext(\"when something is holding the lock\", func() {\n\t\t\tvar fakeUnlocker locksmith.Unlocker\n\t\t\tBeforeEach(func() {\n\t\t\t\tvar err error\n\t\t\t\tfakeUnlocker, err = fakeLocksmith.Lock(\"\/foo\/bar\")\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"blocks on any iptables operations until the lock is freed\", func() {\n\t\t\t\tdone := make(chan struct{})\n\t\t\t\tgo func() {\n\t\t\t\t\tdefer GinkgoRecover()\n\t\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\t\t\t\t\tclose(done)\n\t\t\t\t}()\n\n\t\t\t\tConsistently(done).ShouldNot(BeClosed())\n\t\t\t\tfakeUnlocker.Unlock()\n\t\t\t\tEventually(done).Should(BeClosed())\n\t\t\t})\n\t\t})\n\n\t\tIt(\"should unlock, ensuring future commands can get the lock\", func(done Done) {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-1\")).To(Succeed())\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-2\")).To(Succeed())\n\t\t\tclose(done)\n\t\t}, 2.0)\n\n\t\tIt(\"should lock to correct key\", func() {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-1\")).To(Succeed())\n\t\t\tExpect(fakeLocksmith.KeyForLastLock()).To(Equal(iptables.LockKey))\n\t\t})\n\n\t\tContext(\"when locking fails\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tfakeLocksmith.LockReturns(nil, errors.New(\"failed to lock\"))\n\t\t\t})\n\n\t\t\tIt(\"returns the error\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(MatchError(\"failed to lock\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when running an iptables command fails\", func() {\n\t\t\tIt(\"still unlocks\", func(done Done) {\n\t\t\t\t\/\/ this is going to fail, because the chain does not exist\n\t\t\t\tExpect(iptablesController.PrependRule(\"non-existent-chain\", iptables.SingleFilterRule{})).NotTo(Succeed())\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-2\")).To(Succeed())\n\t\t\t\tclose(done)\n\t\t\t}, 2.0)\n\t\t})\n\n\t\tContext(\"when running an iptables command panics\", func() {\n\t\t\tIt(\"still unlocks\", func(done Done) {\n\t\t\t\tExpect(func() { iptablesController.PrependRule(\"panic\", iptables.SingleFilterRule{}) }).To(Panic())\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-2\")).To(Succeed())\n\t\t\t\tclose(done)\n\t\t\t}, 2.0)\n\t\t})\n\n\t\tContext(\"when unlocking fails\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tfakeLocksmith.UnlockReturns(errors.New(\"failed to unlock\"))\n\t\t\t})\n\n\t\t\tIt(\"returns the error\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(MatchError(\"failed to unlock\"))\n\t\t\t})\n\t\t})\n\t})\n})\n\nfunc makeNamespace(nsName string) {\n\tsess, err := gexec.Start(exec.Command(\"ip\", \"netns\", \"add\", nsName), GinkgoWriter, GinkgoWriter)\n\tExpect(err).NotTo(HaveOccurred())\n\tEventually(sess).Should(gexec.Exit(0))\n}\n\nfunc deleteNamespace(nsName string) {\n\tsess, err := gexec.Start(exec.Command(\"ip\", \"netns\", \"delete\", nsName), GinkgoWriter, GinkgoWriter)\n\tExpect(err).NotTo(HaveOccurred())\n\tEventually(sess).Should(gexec.Exit(0))\n}\n\nfunc wrapCmdInNs(nsName string, cmd *exec.Cmd) *exec.Cmd {\n\t\/\/ We wrap iptables with strace to check whether slowness in #145258087\n\t\/\/ is due to iptables being slow or exiting netns being slow.\n\twrappedCmd := exec.Command(\"strace\", \"-ttT\", \"ip\", \"netns\", \"exec\", nsName)\n\twrappedCmd.Args = append(wrappedCmd.Args, cmd.Args...)\n\twrappedCmd.Stdin = cmd.Stdin\n\twrappedCmd.Stdout = cmd.Stdout\n\twrappedCmd.Stderr = cmd.Stderr\n\treturn wrappedCmd\n}\n<commit_msg>Increase the eventually timeout<commit_after>package iptables_test\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\/exec\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/guardian\/kawasaki\/iptables\"\n\tfakes \"code.cloudfoundry.org\/guardian\/kawasaki\/iptables\/iptablesfakes\"\n\t\"code.cloudfoundry.org\/guardian\/pkg\/locksmith\"\n\t\"github.com\/cloudfoundry\/gunk\/command_runner\/fake_command_runner\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"IPTables controller\", func() {\n\tvar (\n\t\tnetnsName          string\n\t\tprefix             string\n\t\tiptablesController iptables.IPTables\n\t\tfakeLocksmith      *FakeLocksmith\n\t\tfakeRunner         *fake_command_runner.FakeCommandRunner\n\t)\n\n\tBeforeEach(func() {\n\t\tSetDefaultEventuallyTimeout(8 * time.Second)\n\t\tnetnsName = fmt.Sprintf(\"ginkgo-netns-%d\", GinkgoParallelNode())\n\t\tmakeNamespace(netnsName)\n\n\t\tfakeRunner = fake_command_runner.New()\n\t\tfakeRunner.WhenRunning(fake_command_runner.CommandSpec{},\n\t\t\tfunc(cmd *exec.Cmd) error {\n\t\t\t\tif len(cmd.Args) >= 4 && cmd.Args[3] == \"panic\" {\n\t\t\t\t\tpanic(\"ops\")\n\t\t\t\t}\n\t\t\t\treturn wrapCmdInNs(netnsName, cmd).Run()\n\t\t\t},\n\t\t)\n\n\t\tfakeLocksmith = NewFakeLocksmith()\n\n\t\tprefix = fmt.Sprintf(\"g-%d\", GinkgoParallelNode())\n\t\tiptablesController = iptables.New(\"\/sbin\/iptables\", \"\/sbin\/iptables-restore\", fakeRunner, fakeLocksmith, prefix)\n\t})\n\n\tAfterEach(func() {\n\t\tdeleteNamespace(netnsName)\n\t})\n\n\tDescribe(\"CreateChain\", func() {\n\t\tIt(\"creates the chain\", func() {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t})\n\n\t\tContext(\"when the table is nat\", func() {\n\t\t\tIt(\"creates the nat chain\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).To(Succeed())\n\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", \"nat\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the chain already exists\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).To(Succeed())\n\t\t\t})\n\n\t\t\tIt(\"returns an error\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).NotTo(Succeed())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"PrependRule\", func() {\n\t\tIt(\"prepends the rule\", func() {\n\t\t\tfakeTCPRule := new(fakes.FakeRule)\n\t\t\tfakeTCPRule.FlagsReturns([]string{\"--protocol\", \"tcp\"})\n\t\t\tfakeUDPRule := new(fakes.FakeRule)\n\t\t\tfakeUDPRule.FlagsReturns([]string{\"--protocol\", \"udp\"})\n\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\n\t\t\tExpect(iptablesController.PrependRule(\"test-chain\", fakeTCPRule)).To(Succeed())\n\t\t\tExpect(iptablesController.PrependRule(\"test-chain\", fakeUDPRule)).To(Succeed())\n\n\t\t\tbuff := gbytes.NewBuffer()\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\tExpect(buff).To(gbytes.Say(\"-A test-chain -p udp\\n-A test-chain -p tcp\"))\n\t\t})\n\n\t\tIt(\"returns an error when the chain does not exist\", func() {\n\t\t\tfakeRule := new(fakes.FakeRule)\n\t\t\tfakeRule.FlagsReturns([]string{})\n\n\t\t\tExpect(iptablesController.PrependRule(\"test-chain\", fakeRule)).NotTo(Succeed())\n\t\t})\n\t})\n\n\tDescribe(\"BulkPrependRules\", func() {\n\t\tIt(\"appends the rules\", func() {\n\t\t\tfakeTCPRule := new(fakes.FakeRule)\n\t\t\tfakeTCPRule.FlagsReturns([]string{\"--protocol\", \"tcp\"})\n\t\t\tfakeUDPRule := new(fakes.FakeRule)\n\t\t\tfakeUDPRule.FlagsReturns([]string{\"--protocol\", \"udp\"})\n\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\t\t\tExpect(iptablesController.BulkPrependRules(\"test-chain\", []iptables.Rule{\n\t\t\t\tfakeTCPRule,\n\t\t\t\tfakeUDPRule,\n\t\t\t})).To(Succeed())\n\n\t\t\tbuff := gbytes.NewBuffer()\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\tExpect(buff).To(gbytes.Say(\"-A test-chain -p udp\\n-A test-chain -p tcp\"))\n\t\t})\n\n\t\tIt(\"returns an error when the chain does not exist\", func() {\n\t\t\tfakeRule := new(fakes.FakeRule)\n\t\t\tfakeRule.FlagsReturns([]string{\"--protocol\", \"tcp\"})\n\n\t\t\tExpect(iptablesController.BulkPrependRules(\"test-chain\", []iptables.Rule{fakeRule})).NotTo(Succeed())\n\t\t})\n\n\t\tContext(\"when there are no rules passed\", func() {\n\t\t\tIt(\"does nothing\", func() {\n\t\t\t\tExpect(iptablesController.BulkPrependRules(\"test-chain\", []iptables.Rule{})).To(Succeed())\n\t\t\t\tExpect(fakeRunner.ExecutedCommands()).To(BeZero())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"DeleteChain\", func() {\n\t\tBeforeEach(func() {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\t\t})\n\n\t\tIt(\"deletes the chain\", func() {\n\t\t\tExpect(iptablesController.DeleteChain(\"filter\", \"test-chain\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(1))\n\t\t})\n\n\t\tContext(\"when the table is nat\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).To(Succeed())\n\t\t\t})\n\n\t\t\tIt(\"deletes the nat chain\", func() {\n\t\t\t\tExpect(iptablesController.DeleteChain(\"nat\", \"test-chain\")).To(Succeed())\n\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", \"nat\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tEventually(sess).Should(gexec.Exit(1))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the chain does not exist\", func() {\n\t\t\tIt(\"does not return an error\", func() {\n\t\t\t\tExpect(iptablesController.DeleteChain(\"filter\", \"test-non-existing-chain\")).To(Succeed())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"FlushChain\", func() {\n\t\tvar table string\n\n\t\tBeforeEach(func() {\n\t\t\ttable = \"filter\"\n\t\t})\n\n\t\tJustBeforeEach(func() {\n\t\t\tExpect(iptablesController.CreateChain(table, \"test-chain\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-A\", \"test-chain\", \"-j\", \"ACCEPT\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t})\n\n\t\tIt(\"flushes the chain\", func() {\n\t\t\tExpect(iptablesController.FlushChain(table, \"test-chain\")).To(Succeed())\n\n\t\t\tbuff := gbytes.NewBuffer()\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\tConsistently(buff).ShouldNot(gbytes.Say(\"-A test-chain\"))\n\t\t})\n\n\t\tContext(\"when the table is nat\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\ttable = \"nat\"\n\t\t\t})\n\n\t\t\tIt(\"flushes the nat chain\", func() {\n\t\t\t\tExpect(iptablesController.FlushChain(table, \"test-chain\")).To(Succeed())\n\n\t\t\t\tbuff := gbytes.NewBuffer()\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\t\tConsistently(buff).ShouldNot(gbytes.Say(\"-A test-chain\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the chain does not exist\", func() {\n\t\t\tIt(\"does not return an error\", func() {\n\t\t\t\tExpect(iptablesController.FlushChain(\"filter\", \"test-non-existing-chain\")).To(Succeed())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"DeleteChainReferences\", func() {\n\t\tvar table string\n\n\t\tBeforeEach(func() {\n\t\t\ttable = \"filter\"\n\t\t})\n\n\t\tJustBeforeEach(func() {\n\t\t\tExpect(iptablesController.CreateChain(table, \"test-chain-1\")).To(Succeed())\n\t\t\tExpect(iptablesController.CreateChain(table, \"test-chain-2\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-A\", \"test-chain-1\", \"-j\", \"test-chain-2\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t})\n\n\t\tIt(\"deletes the references\", func() {\n\t\t\tExpect(iptablesController.DeleteChainReferences(table, \"test-chain-1\", \"test-chain-2\")).To(Succeed())\n\n\t\t\tEventually(func() string {\n\t\t\t\tbuff := gbytes.NewBuffer()\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-S\", \"test-chain-1\")), buff, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(sess).Should(gexec.Exit(0))\n\n\t\t\t\treturn string(buff.Contents())\n\t\t\t}).ShouldNot(ContainSubstring(\"test-chain-2\"))\n\t\t})\n\t})\n\n\tDescribe(\"Locking Behaviour\", func() {\n\t\tContext(\"when something is holding the lock\", func() {\n\t\t\tvar fakeUnlocker locksmith.Unlocker\n\t\t\tBeforeEach(func() {\n\t\t\t\tvar err error\n\t\t\t\tfakeUnlocker, err = fakeLocksmith.Lock(\"\/foo\/bar\")\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"blocks on any iptables operations until the lock is freed\", func() {\n\t\t\t\tdone := make(chan struct{})\n\t\t\t\tgo func() {\n\t\t\t\t\tdefer GinkgoRecover()\n\t\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\t\t\t\t\tclose(done)\n\t\t\t\t}()\n\n\t\t\t\tConsistently(done).ShouldNot(BeClosed())\n\t\t\t\tfakeUnlocker.Unlock()\n\t\t\t\tEventually(done).Should(BeClosed())\n\t\t\t})\n\t\t})\n\n\t\tIt(\"should unlock, ensuring future commands can get the lock\", func(done Done) {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-1\")).To(Succeed())\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-2\")).To(Succeed())\n\t\t\tclose(done)\n\t\t}, 2.0)\n\n\t\tIt(\"should lock to correct key\", func() {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-1\")).To(Succeed())\n\t\t\tExpect(fakeLocksmith.KeyForLastLock()).To(Equal(iptables.LockKey))\n\t\t})\n\n\t\tContext(\"when locking fails\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tfakeLocksmith.LockReturns(nil, errors.New(\"failed to lock\"))\n\t\t\t})\n\n\t\t\tIt(\"returns the error\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(MatchError(\"failed to lock\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when running an iptables command fails\", func() {\n\t\t\tIt(\"still unlocks\", func(done Done) {\n\t\t\t\t\/\/ this is going to fail, because the chain does not exist\n\t\t\t\tExpect(iptablesController.PrependRule(\"non-existent-chain\", iptables.SingleFilterRule{})).NotTo(Succeed())\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-2\")).To(Succeed())\n\t\t\t\tclose(done)\n\t\t\t}, 2.0)\n\t\t})\n\n\t\tContext(\"when running an iptables command panics\", func() {\n\t\t\tIt(\"still unlocks\", func(done Done) {\n\t\t\t\tExpect(func() { iptablesController.PrependRule(\"panic\", iptables.SingleFilterRule{}) }).To(Panic())\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-2\")).To(Succeed())\n\t\t\t\tclose(done)\n\t\t\t}, 2.0)\n\t\t})\n\n\t\tContext(\"when unlocking fails\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tfakeLocksmith.UnlockReturns(errors.New(\"failed to unlock\"))\n\t\t\t})\n\n\t\t\tIt(\"returns the error\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(MatchError(\"failed to unlock\"))\n\t\t\t})\n\t\t})\n\t})\n})\n\nfunc makeNamespace(nsName string) {\n\tsess, err := gexec.Start(exec.Command(\"ip\", \"netns\", \"add\", nsName), GinkgoWriter, GinkgoWriter)\n\tExpect(err).NotTo(HaveOccurred())\n\tEventually(sess).Should(gexec.Exit(0))\n}\n\nfunc deleteNamespace(nsName string) {\n\tsess, err := gexec.Start(exec.Command(\"ip\", \"netns\", \"delete\", nsName), GinkgoWriter, GinkgoWriter)\n\tExpect(err).NotTo(HaveOccurred())\n\tEventually(sess).Should(gexec.Exit(0))\n}\n\nfunc wrapCmdInNs(nsName string, cmd *exec.Cmd) *exec.Cmd {\n\twrappedCmd := exec.Command(\"strace\", \"-ttT\", \"ip\", \"netns\", \"exec\", nsName)\n\twrappedCmd.Args = append(wrappedCmd.Args, cmd.Args...)\n\twrappedCmd.Stdin = cmd.Stdin\n\twrappedCmd.Stdout = cmd.Stdout\n\twrappedCmd.Stderr = cmd.Stderr\n\treturn wrappedCmd\n}\n<|endoftext|>"}
{"text":"<commit_before>package iptables_test\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\/exec\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/guardian\/kawasaki\/iptables\"\n\tfakes \"code.cloudfoundry.org\/guardian\/kawasaki\/iptables\/iptablesfakes\"\n\t\"code.cloudfoundry.org\/guardian\/pkg\/locksmith\"\n\t\"github.com\/cloudfoundry\/gunk\/command_runner\/fake_command_runner\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"IPTables controller\", func() {\n\tvar (\n\t\tnetnsName          string\n\t\tprefix             string\n\t\tiptablesController iptables.IPTables\n\t\tfakeLocksmith      *FakeLocksmith\n\t\tfakeRunner         *fake_command_runner.FakeCommandRunner\n\t)\n\n\tBeforeEach(func() {\n\t\tSetDefaultEventuallyTimeout(3 * time.Second)\n\t\tnetnsName = fmt.Sprintf(\"ginkgo-netns-%d\", GinkgoParallelNode())\n\t\tmakeNamespace(netnsName)\n\n\t\tfakeRunner = fake_command_runner.New()\n\t\tfakeRunner.WhenRunning(fake_command_runner.CommandSpec{},\n\t\t\tfunc(cmd *exec.Cmd) error {\n\t\t\t\tif len(cmd.Args) >= 4 && cmd.Args[3] == \"panic\" {\n\t\t\t\t\tpanic(\"ops\")\n\t\t\t\t}\n\t\t\t\treturn wrapCmdInNs(netnsName, cmd).Run()\n\t\t\t},\n\t\t)\n\n\t\tfakeLocksmith = NewFakeLocksmith()\n\n\t\tprefix = fmt.Sprintf(\"g-%d\", GinkgoParallelNode())\n\t\tiptablesController = iptables.New(\"\/sbin\/iptables\", \"\/sbin\/iptables-restore\", fakeRunner, fakeLocksmith, prefix)\n\t})\n\n\tAfterEach(func() {\n\t\tdeleteNamespace(netnsName)\n\t})\n\n\tDescribe(\"CreateChain\", func() {\n\t\tIt(\"creates the chain\", func() {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t})\n\n\t\tContext(\"when the table is nat\", func() {\n\t\t\tIt(\"creates the nat chain\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).To(Succeed())\n\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", \"nat\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the chain already exists\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).To(Succeed())\n\t\t\t})\n\n\t\t\tIt(\"returns an error\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).NotTo(Succeed())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"PrependRule\", func() {\n\t\tIt(\"prepends the rule\", func() {\n\t\t\tfakeTCPRule := new(fakes.FakeRule)\n\t\t\tfakeTCPRule.FlagsReturns([]string{\"--protocol\", \"tcp\"})\n\t\t\tfakeUDPRule := new(fakes.FakeRule)\n\t\t\tfakeUDPRule.FlagsReturns([]string{\"--protocol\", \"udp\"})\n\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\n\t\t\tExpect(iptablesController.PrependRule(\"test-chain\", fakeTCPRule)).To(Succeed())\n\t\t\tExpect(iptablesController.PrependRule(\"test-chain\", fakeUDPRule)).To(Succeed())\n\n\t\t\tbuff := gbytes.NewBuffer()\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\tExpect(buff).To(gbytes.Say(\"-A test-chain -p udp\\n-A test-chain -p tcp\"))\n\t\t})\n\n\t\tIt(\"returns an error when the chain does not exist\", func() {\n\t\t\tfakeRule := new(fakes.FakeRule)\n\t\t\tfakeRule.FlagsReturns([]string{})\n\n\t\t\tExpect(iptablesController.PrependRule(\"test-chain\", fakeRule)).NotTo(Succeed())\n\t\t})\n\t})\n\n\tDescribe(\"BulkPrependRules\", func() {\n\t\tIt(\"appends the rules\", func() {\n\t\t\tfakeTCPRule := new(fakes.FakeRule)\n\t\t\tfakeTCPRule.FlagsReturns([]string{\"--protocol\", \"tcp\"})\n\t\t\tfakeUDPRule := new(fakes.FakeRule)\n\t\t\tfakeUDPRule.FlagsReturns([]string{\"--protocol\", \"udp\"})\n\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\t\t\tExpect(iptablesController.BulkPrependRules(\"test-chain\", []iptables.Rule{\n\t\t\t\tfakeTCPRule,\n\t\t\t\tfakeUDPRule,\n\t\t\t})).To(Succeed())\n\n\t\t\tbuff := gbytes.NewBuffer()\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\tExpect(buff).To(gbytes.Say(\"-A test-chain -p udp\\n-A test-chain -p tcp\"))\n\t\t})\n\n\t\tIt(\"returns an error when the chain does not exist\", func() {\n\t\t\tfakeRule := new(fakes.FakeRule)\n\t\t\tfakeRule.FlagsReturns([]string{\"--protocol\", \"tcp\"})\n\n\t\t\tExpect(iptablesController.BulkPrependRules(\"test-chain\", []iptables.Rule{fakeRule})).NotTo(Succeed())\n\t\t})\n\n\t\tContext(\"when there are no rules passed\", func() {\n\t\t\tIt(\"does nothing\", func() {\n\t\t\t\tExpect(iptablesController.BulkPrependRules(\"test-chain\", []iptables.Rule{})).To(Succeed())\n\t\t\t\tExpect(fakeRunner.ExecutedCommands()).To(BeZero())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"DeleteChain\", func() {\n\t\tBeforeEach(func() {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\t\t})\n\n\t\tIt(\"deletes the chain\", func() {\n\t\t\tExpect(iptablesController.DeleteChain(\"filter\", \"test-chain\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(1))\n\t\t})\n\n\t\tContext(\"when the table is nat\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).To(Succeed())\n\t\t\t})\n\n\t\t\tIt(\"deletes the nat chain\", func() {\n\t\t\t\tExpect(iptablesController.DeleteChain(\"nat\", \"test-chain\")).To(Succeed())\n\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", \"nat\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tEventually(sess).Should(gexec.Exit(1))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the chain does not exist\", func() {\n\t\t\tIt(\"does not return an error\", func() {\n\t\t\t\tExpect(iptablesController.DeleteChain(\"filter\", \"test-non-existing-chain\")).To(Succeed())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"FlushChain\", func() {\n\t\tvar table string\n\n\t\tBeforeEach(func() {\n\t\t\ttable = \"filter\"\n\t\t})\n\n\t\tJustBeforeEach(func() {\n\t\t\tExpect(iptablesController.CreateChain(table, \"test-chain\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-A\", \"test-chain\", \"-j\", \"ACCEPT\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t})\n\n\t\tIt(\"flushes the chain\", func() {\n\t\t\tExpect(iptablesController.FlushChain(table, \"test-chain\")).To(Succeed())\n\n\t\t\tbuff := gbytes.NewBuffer()\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\tConsistently(buff).ShouldNot(gbytes.Say(\"-A test-chain\"))\n\t\t})\n\n\t\tContext(\"when the table is nat\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\ttable = \"nat\"\n\t\t\t})\n\n\t\t\tIt(\"flushes the nat chain\", func() {\n\t\t\t\tExpect(iptablesController.FlushChain(table, \"test-chain\")).To(Succeed())\n\n\t\t\t\tbuff := gbytes.NewBuffer()\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\t\tConsistently(buff).ShouldNot(gbytes.Say(\"-A test-chain\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the chain does not exist\", func() {\n\t\t\tIt(\"does not return an error\", func() {\n\t\t\t\tExpect(iptablesController.FlushChain(\"filter\", \"test-non-existing-chain\")).To(Succeed())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"DeleteChainReferences\", func() {\n\t\tvar table string\n\n\t\tBeforeEach(func() {\n\t\t\ttable = \"filter\"\n\t\t})\n\n\t\tJustBeforeEach(func() {\n\t\t\tExpect(iptablesController.CreateChain(table, \"test-chain-1\")).To(Succeed())\n\t\t\tExpect(iptablesController.CreateChain(table, \"test-chain-2\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-A\", \"test-chain-1\", \"-j\", \"test-chain-2\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t})\n\n\t\tIt(\"deletes the references\", func() {\n\t\t\tExpect(iptablesController.DeleteChainReferences(table, \"test-chain-1\", \"test-chain-2\")).To(Succeed())\n\n\t\t\tEventually(func() string {\n\t\t\t\tbuff := gbytes.NewBuffer()\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-S\", \"test-chain-1\")), buff, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(sess).Should(gexec.Exit(0))\n\n\t\t\t\treturn string(buff.Contents())\n\t\t\t}).ShouldNot(ContainSubstring(\"test-chain-2\"))\n\t\t})\n\t})\n\n\tDescribe(\"Locking Behaviour\", func() {\n\t\tContext(\"when something is holding the lock\", func() {\n\t\t\tvar fakeUnlocker locksmith.Unlocker\n\t\t\tBeforeEach(func() {\n\t\t\t\tvar err error\n\t\t\t\tfakeUnlocker, err = fakeLocksmith.Lock(\"\/foo\/bar\")\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"blocks on any iptables operations until the lock is freed\", func() {\n\t\t\t\tdone := make(chan struct{})\n\t\t\t\tgo func() {\n\t\t\t\t\tdefer GinkgoRecover()\n\t\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\t\t\t\t\tclose(done)\n\t\t\t\t}()\n\n\t\t\t\tConsistently(done).ShouldNot(BeClosed())\n\t\t\t\tfakeUnlocker.Unlock()\n\t\t\t\tEventually(done).Should(BeClosed())\n\t\t\t})\n\t\t})\n\n\t\tIt(\"should unlock, ensuring future commands can get the lock\", func(done Done) {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-1\")).To(Succeed())\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-2\")).To(Succeed())\n\t\t\tclose(done)\n\t\t}, 2.0)\n\n\t\tIt(\"should lock to correct key\", func() {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-1\")).To(Succeed())\n\t\t\tExpect(fakeLocksmith.KeyForLastLock()).To(Equal(iptables.LockKey))\n\t\t})\n\n\t\tContext(\"when locking fails\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tfakeLocksmith.LockReturns(nil, errors.New(\"failed to lock\"))\n\t\t\t})\n\n\t\t\tIt(\"returns the error\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(MatchError(\"failed to lock\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when running an iptables command fails\", func() {\n\t\t\tIt(\"still unlocks\", func(done Done) {\n\t\t\t\t\/\/ this is going to fail, because the chain does not exist\n\t\t\t\tExpect(iptablesController.PrependRule(\"non-existent-chain\", iptables.SingleFilterRule{})).NotTo(Succeed())\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-2\")).To(Succeed())\n\t\t\t\tclose(done)\n\t\t\t}, 2.0)\n\t\t})\n\n\t\tContext(\"when running an iptables command panics\", func() {\n\t\t\tIt(\"still unlocks\", func(done Done) {\n\t\t\t\tExpect(func() { iptablesController.PrependRule(\"panic\", iptables.SingleFilterRule{}) }).To(Panic())\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-2\")).To(Succeed())\n\t\t\t\tclose(done)\n\t\t\t}, 2.0)\n\t\t})\n\n\t\tContext(\"when unlocking fails\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tfakeLocksmith.UnlockReturns(errors.New(\"failed to unlock\"))\n\t\t\t})\n\n\t\t\tIt(\"returns the error\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(MatchError(\"failed to unlock\"))\n\t\t\t})\n\t\t})\n\t})\n})\n\nfunc makeNamespace(nsName string) {\n\tsess, err := gexec.Start(exec.Command(\"ip\", \"netns\", \"add\", nsName), GinkgoWriter, GinkgoWriter)\n\tExpect(err).NotTo(HaveOccurred())\n\tEventually(sess).Should(gexec.Exit(0))\n}\n\nfunc deleteNamespace(nsName string) {\n\tsess, err := gexec.Start(exec.Command(\"ip\", \"netns\", \"delete\", nsName), GinkgoWriter, GinkgoWriter)\n\tExpect(err).NotTo(HaveOccurred())\n\tEventually(sess).Should(gexec.Exit(0))\n}\n\nfunc wrapCmdInNs(nsName string, cmd *exec.Cmd) *exec.Cmd {\n\twrappedCmd := exec.Command(\"ip\", \"netns\", \"exec\", nsName)\n\twrappedCmd.Args = append(wrappedCmd.Args, cmd.Args...)\n\twrappedCmd.Stdin = cmd.Stdin\n\twrappedCmd.Stdout = cmd.Stdout\n\twrappedCmd.Stderr = cmd.Stderr\n\treturn wrappedCmd\n}\n<commit_msg>Wrap iptables command with strace<commit_after>package iptables_test\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\/exec\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/guardian\/kawasaki\/iptables\"\n\tfakes \"code.cloudfoundry.org\/guardian\/kawasaki\/iptables\/iptablesfakes\"\n\t\"code.cloudfoundry.org\/guardian\/pkg\/locksmith\"\n\t\"github.com\/cloudfoundry\/gunk\/command_runner\/fake_command_runner\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"IPTables controller\", func() {\n\tvar (\n\t\tnetnsName          string\n\t\tprefix             string\n\t\tiptablesController iptables.IPTables\n\t\tfakeLocksmith      *FakeLocksmith\n\t\tfakeRunner         *fake_command_runner.FakeCommandRunner\n\t)\n\n\tBeforeEach(func() {\n\t\tSetDefaultEventuallyTimeout(3 * time.Second)\n\t\tnetnsName = fmt.Sprintf(\"ginkgo-netns-%d\", GinkgoParallelNode())\n\t\tmakeNamespace(netnsName)\n\n\t\tfakeRunner = fake_command_runner.New()\n\t\tfakeRunner.WhenRunning(fake_command_runner.CommandSpec{},\n\t\t\tfunc(cmd *exec.Cmd) error {\n\t\t\t\tif len(cmd.Args) >= 4 && cmd.Args[3] == \"panic\" {\n\t\t\t\t\tpanic(\"ops\")\n\t\t\t\t}\n\t\t\t\treturn wrapCmdInNs(netnsName, cmd).Run()\n\t\t\t},\n\t\t)\n\n\t\tfakeLocksmith = NewFakeLocksmith()\n\n\t\tprefix = fmt.Sprintf(\"g-%d\", GinkgoParallelNode())\n\t\tiptablesController = iptables.New(\"\/sbin\/iptables\", \"\/sbin\/iptables-restore\", fakeRunner, fakeLocksmith, prefix)\n\t})\n\n\tAfterEach(func() {\n\t\tdeleteNamespace(netnsName)\n\t})\n\n\tDescribe(\"CreateChain\", func() {\n\t\tIt(\"creates the chain\", func() {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t})\n\n\t\tContext(\"when the table is nat\", func() {\n\t\t\tIt(\"creates the nat chain\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).To(Succeed())\n\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", \"nat\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the chain already exists\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).To(Succeed())\n\t\t\t})\n\n\t\t\tIt(\"returns an error\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).NotTo(Succeed())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"PrependRule\", func() {\n\t\tIt(\"prepends the rule\", func() {\n\t\t\tfakeTCPRule := new(fakes.FakeRule)\n\t\t\tfakeTCPRule.FlagsReturns([]string{\"--protocol\", \"tcp\"})\n\t\t\tfakeUDPRule := new(fakes.FakeRule)\n\t\t\tfakeUDPRule.FlagsReturns([]string{\"--protocol\", \"udp\"})\n\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\n\t\t\tExpect(iptablesController.PrependRule(\"test-chain\", fakeTCPRule)).To(Succeed())\n\t\t\tExpect(iptablesController.PrependRule(\"test-chain\", fakeUDPRule)).To(Succeed())\n\n\t\t\tbuff := gbytes.NewBuffer()\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\tExpect(buff).To(gbytes.Say(\"-A test-chain -p udp\\n-A test-chain -p tcp\"))\n\t\t})\n\n\t\tIt(\"returns an error when the chain does not exist\", func() {\n\t\t\tfakeRule := new(fakes.FakeRule)\n\t\t\tfakeRule.FlagsReturns([]string{})\n\n\t\t\tExpect(iptablesController.PrependRule(\"test-chain\", fakeRule)).NotTo(Succeed())\n\t\t})\n\t})\n\n\tDescribe(\"BulkPrependRules\", func() {\n\t\tIt(\"appends the rules\", func() {\n\t\t\tfakeTCPRule := new(fakes.FakeRule)\n\t\t\tfakeTCPRule.FlagsReturns([]string{\"--protocol\", \"tcp\"})\n\t\t\tfakeUDPRule := new(fakes.FakeRule)\n\t\t\tfakeUDPRule.FlagsReturns([]string{\"--protocol\", \"udp\"})\n\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\t\t\tExpect(iptablesController.BulkPrependRules(\"test-chain\", []iptables.Rule{\n\t\t\t\tfakeTCPRule,\n\t\t\t\tfakeUDPRule,\n\t\t\t})).To(Succeed())\n\n\t\t\tbuff := gbytes.NewBuffer()\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\tExpect(buff).To(gbytes.Say(\"-A test-chain -p udp\\n-A test-chain -p tcp\"))\n\t\t})\n\n\t\tIt(\"returns an error when the chain does not exist\", func() {\n\t\t\tfakeRule := new(fakes.FakeRule)\n\t\t\tfakeRule.FlagsReturns([]string{\"--protocol\", \"tcp\"})\n\n\t\t\tExpect(iptablesController.BulkPrependRules(\"test-chain\", []iptables.Rule{fakeRule})).NotTo(Succeed())\n\t\t})\n\n\t\tContext(\"when there are no rules passed\", func() {\n\t\t\tIt(\"does nothing\", func() {\n\t\t\t\tExpect(iptablesController.BulkPrependRules(\"test-chain\", []iptables.Rule{})).To(Succeed())\n\t\t\t\tExpect(fakeRunner.ExecutedCommands()).To(BeZero())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"DeleteChain\", func() {\n\t\tBeforeEach(func() {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\t\t})\n\n\t\tIt(\"deletes the chain\", func() {\n\t\t\tExpect(iptablesController.DeleteChain(\"filter\", \"test-chain\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(1))\n\t\t})\n\n\t\tContext(\"when the table is nat\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"nat\", \"test-chain\")).To(Succeed())\n\t\t\t})\n\n\t\t\tIt(\"deletes the nat chain\", func() {\n\t\t\t\tExpect(iptablesController.DeleteChain(\"nat\", \"test-chain\")).To(Succeed())\n\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", \"nat\", \"-L\", \"test-chain\")), GinkgoWriter, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tEventually(sess).Should(gexec.Exit(1))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the chain does not exist\", func() {\n\t\t\tIt(\"does not return an error\", func() {\n\t\t\t\tExpect(iptablesController.DeleteChain(\"filter\", \"test-non-existing-chain\")).To(Succeed())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"FlushChain\", func() {\n\t\tvar table string\n\n\t\tBeforeEach(func() {\n\t\t\ttable = \"filter\"\n\t\t})\n\n\t\tJustBeforeEach(func() {\n\t\t\tExpect(iptablesController.CreateChain(table, \"test-chain\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-A\", \"test-chain\", \"-j\", \"ACCEPT\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t})\n\n\t\tIt(\"flushes the chain\", func() {\n\t\t\tExpect(iptablesController.FlushChain(table, \"test-chain\")).To(Succeed())\n\n\t\t\tbuff := gbytes.NewBuffer()\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\tConsistently(buff).ShouldNot(gbytes.Say(\"-A test-chain\"))\n\t\t})\n\n\t\tContext(\"when the table is nat\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\ttable = \"nat\"\n\t\t\t})\n\n\t\t\tIt(\"flushes the nat chain\", func() {\n\t\t\t\tExpect(iptablesController.FlushChain(table, \"test-chain\")).To(Succeed())\n\n\t\t\t\tbuff := gbytes.NewBuffer()\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-S\", \"test-chain\")), buff, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t\t\tConsistently(buff).ShouldNot(gbytes.Say(\"-A test-chain\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the chain does not exist\", func() {\n\t\t\tIt(\"does not return an error\", func() {\n\t\t\t\tExpect(iptablesController.FlushChain(\"filter\", \"test-non-existing-chain\")).To(Succeed())\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"DeleteChainReferences\", func() {\n\t\tvar table string\n\n\t\tBeforeEach(func() {\n\t\t\ttable = \"filter\"\n\t\t})\n\n\t\tJustBeforeEach(func() {\n\t\t\tExpect(iptablesController.CreateChain(table, \"test-chain-1\")).To(Succeed())\n\t\t\tExpect(iptablesController.CreateChain(table, \"test-chain-2\")).To(Succeed())\n\n\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-A\", \"test-chain-1\", \"-j\", \"test-chain-2\")), GinkgoWriter, GinkgoWriter)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tEventually(sess).Should(gexec.Exit(0))\n\t\t})\n\n\t\tIt(\"deletes the references\", func() {\n\t\t\tExpect(iptablesController.DeleteChainReferences(table, \"test-chain-1\", \"test-chain-2\")).To(Succeed())\n\n\t\t\tEventually(func() string {\n\t\t\t\tbuff := gbytes.NewBuffer()\n\t\t\t\tsess, err := gexec.Start(wrapCmdInNs(netnsName, exec.Command(\"iptables\", \"-t\", table, \"-S\", \"test-chain-1\")), buff, GinkgoWriter)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tEventually(sess).Should(gexec.Exit(0))\n\n\t\t\t\treturn string(buff.Contents())\n\t\t\t}).ShouldNot(ContainSubstring(\"test-chain-2\"))\n\t\t})\n\t})\n\n\tDescribe(\"Locking Behaviour\", func() {\n\t\tContext(\"when something is holding the lock\", func() {\n\t\t\tvar fakeUnlocker locksmith.Unlocker\n\t\t\tBeforeEach(func() {\n\t\t\t\tvar err error\n\t\t\t\tfakeUnlocker, err = fakeLocksmith.Lock(\"\/foo\/bar\")\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"blocks on any iptables operations until the lock is freed\", func() {\n\t\t\t\tdone := make(chan struct{})\n\t\t\t\tgo func() {\n\t\t\t\t\tdefer GinkgoRecover()\n\t\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(Succeed())\n\t\t\t\t\tclose(done)\n\t\t\t\t}()\n\n\t\t\t\tConsistently(done).ShouldNot(BeClosed())\n\t\t\t\tfakeUnlocker.Unlock()\n\t\t\t\tEventually(done).Should(BeClosed())\n\t\t\t})\n\t\t})\n\n\t\tIt(\"should unlock, ensuring future commands can get the lock\", func(done Done) {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-1\")).To(Succeed())\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-2\")).To(Succeed())\n\t\t\tclose(done)\n\t\t}, 2.0)\n\n\t\tIt(\"should lock to correct key\", func() {\n\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-1\")).To(Succeed())\n\t\t\tExpect(fakeLocksmith.KeyForLastLock()).To(Equal(iptables.LockKey))\n\t\t})\n\n\t\tContext(\"when locking fails\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tfakeLocksmith.LockReturns(nil, errors.New(\"failed to lock\"))\n\t\t\t})\n\n\t\t\tIt(\"returns the error\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(MatchError(\"failed to lock\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when running an iptables command fails\", func() {\n\t\t\tIt(\"still unlocks\", func(done Done) {\n\t\t\t\t\/\/ this is going to fail, because the chain does not exist\n\t\t\t\tExpect(iptablesController.PrependRule(\"non-existent-chain\", iptables.SingleFilterRule{})).NotTo(Succeed())\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-2\")).To(Succeed())\n\t\t\t\tclose(done)\n\t\t\t}, 2.0)\n\t\t})\n\n\t\tContext(\"when running an iptables command panics\", func() {\n\t\t\tIt(\"still unlocks\", func(done Done) {\n\t\t\t\tExpect(func() { iptablesController.PrependRule(\"panic\", iptables.SingleFilterRule{}) }).To(Panic())\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain-2\")).To(Succeed())\n\t\t\t\tclose(done)\n\t\t\t}, 2.0)\n\t\t})\n\n\t\tContext(\"when unlocking fails\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tfakeLocksmith.UnlockReturns(errors.New(\"failed to unlock\"))\n\t\t\t})\n\n\t\t\tIt(\"returns the error\", func() {\n\t\t\t\tExpect(iptablesController.CreateChain(\"filter\", \"test-chain\")).To(MatchError(\"failed to unlock\"))\n\t\t\t})\n\t\t})\n\t})\n})\n\nfunc makeNamespace(nsName string) {\n\tsess, err := gexec.Start(exec.Command(\"ip\", \"netns\", \"add\", nsName), GinkgoWriter, GinkgoWriter)\n\tExpect(err).NotTo(HaveOccurred())\n\tEventually(sess).Should(gexec.Exit(0))\n}\n\nfunc deleteNamespace(nsName string) {\n\tsess, err := gexec.Start(exec.Command(\"ip\", \"netns\", \"delete\", nsName), GinkgoWriter, GinkgoWriter)\n\tExpect(err).NotTo(HaveOccurred())\n\tEventually(sess).Should(gexec.Exit(0))\n}\n\nfunc wrapCmdInNs(nsName string, cmd *exec.Cmd) *exec.Cmd {\n\t\/\/ We wrap iptables with strace to check whether slowness in #145258087\n\t\/\/ is due to iptables being slow or exiting netns being slow.\n\twrappedCmd := exec.Command(\"strace\", \"ip\", \"netns\", \"exec\", nsName)\n\twrappedCmd.Args = append(wrappedCmd.Args, cmd.Args...)\n\twrappedCmd.Stdin = cmd.Stdin\n\twrappedCmd.Stdout = cmd.Stdout\n\twrappedCmd.Stderr = cmd.Stderr\n\treturn wrappedCmd\n}\n<|endoftext|>"}
{"text":"<commit_before>package push\n\nimport (\n\t\"code.cloudfoundry.org\/cli\/api\/cloudcontroller\/ccversion\"\n\t\"code.cloudfoundry.org\/cli\/integration\/helpers\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n)\n\nvar _ = Describe(\"push with symlink path\", func() {\n\tvar (\n\t\tappName       string\n\t\trunningDir    string\n\t\tsymlinkedPath string\n\t)\n\n\tBeforeEach(func() {\n\t\thelpers.SkipIfVersionLessThan(ccversion.MinVersionSymlinkedFilesV2)\n\t\tappName = helpers.NewAppName()\n\n\t\tvar err error\n\t\trunningDir, err = ioutil.TempDir(\"\", \"push-with-symlink\")\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tsymlinkedPath = filepath.Join(runningDir, \"symlink-dir\")\n\t})\n\n\tAfterEach(func() {\n\t\tExpect(os.RemoveAll(runningDir)).ToNot(HaveOccurred())\n\t})\n\n\tContext(\"push with flag options\", func() {\n\t\tWhen(\"pushing from a symlinked current directory\", func() {\n\t\t\tIt(\"should push with the absolute path of the app\", func() {\n\t\t\t\thelpers.WithHelloWorldApp(func(dir string) {\n\t\t\t\t\tExpect(os.Symlink(dir, symlinkedPath)).ToNot(HaveOccurred())\n\n\t\t\t\t\tsession := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: symlinkedPath}, PushCommandName, appName)\n\t\t\t\t\t\/\/ Eventually(session).Should(helpers.SayPath(`path:\\s+%s`, dir))\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tWhen(\"pushing a symlinked path with the '-p' flag\", func() {\n\t\t\tIt(\"should push with the absolute path of the app\", func() {\n\t\t\t\thelpers.WithHelloWorldApp(func(dir string) {\n\t\t\t\t\tExpect(os.Symlink(dir, symlinkedPath)).ToNot(HaveOccurred())\n\n\t\t\t\t\tsession := helpers.CF(PushCommandName, appName, \"-p\", symlinkedPath)\n\t\t\t\t\t\/\/ Eventually(session).Should(helpers.SayPath(`path:\\s+%s`, dir))\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tWhen(\"pushing an symlinked archive with the '-p' flag\", func() {\n\t\t\tvar archive string\n\n\t\t\tBeforeEach(func() {\n\t\t\t\thelpers.WithHelloWorldApp(func(appDir string) {\n\t\t\t\t\ttmpfile, err := ioutil.TempFile(\"\", \"push-archive-integration\")\n\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\tarchive = tmpfile.Name()\n\t\t\t\t\tExpect(tmpfile.Close()).ToNot(HaveOccurred())\n\n\t\t\t\t\terr = helpers.Zipit(appDir, archive, \"\")\n\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tAfterEach(func() {\n\t\t\t\tExpect(os.RemoveAll(archive)).ToNot(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"should push with the absolute path of the archive\", func() {\n\t\t\t\tExpect(os.Symlink(archive, symlinkedPath)).ToNot(HaveOccurred())\n\n\t\t\t\tsession := helpers.CF(PushCommandName, appName, \"-p\", symlinkedPath)\n\t\t\t\t\/\/ Eventually(session).Should(helpers.SayPath(`path:\\s+%s`, archive))\n\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"push with a single app manifest\", func() {\n\t\t\tWhen(\"the path property is a symlinked path\", func() {\n\t\t\t\tIt(\"should push with the absolute path of the app\", func() {\n\t\t\t\t\tSkip(\"pending what ado about manifest\")\n\t\t\t\t\thelpers.WithHelloWorldApp(func(dir string) {\n\t\t\t\t\t\tExpect(os.Symlink(dir, symlinkedPath)).ToNot(HaveOccurred())\n\n\t\t\t\t\t\thelpers.WriteManifest(filepath.Join(runningDir, \"manifest.yml\"), map[string]interface{}{\n\t\t\t\t\t\t\t\"applications\": []map[string]string{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\"name\": appName,\n\t\t\t\t\t\t\t\t\t\"path\": symlinkedPath,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})\n\n\t\t\t\t\t\tsession := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: runningDir}, PushCommandName)\n\t\t\t\t\t\tEventually(session).Should(helpers.SayPath(`path:\\s+%s`, dir))\n\t\t\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n})\n<commit_msg>goimports integration\/v7\/push\/symlink_test.go<commit_after>package push\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"code.cloudfoundry.org\/cli\/api\/cloudcontroller\/ccversion\"\n\t\"code.cloudfoundry.org\/cli\/integration\/helpers\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/onsi\/gomega\/gexec\"\n)\n\nvar _ = Describe(\"push with symlink path\", func() {\n\tvar (\n\t\tappName       string\n\t\trunningDir    string\n\t\tsymlinkedPath string\n\t)\n\n\tBeforeEach(func() {\n\t\thelpers.SkipIfVersionLessThan(ccversion.MinVersionSymlinkedFilesV2)\n\t\tappName = helpers.NewAppName()\n\n\t\tvar err error\n\t\trunningDir, err = ioutil.TempDir(\"\", \"push-with-symlink\")\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tsymlinkedPath = filepath.Join(runningDir, \"symlink-dir\")\n\t})\n\n\tAfterEach(func() {\n\t\tExpect(os.RemoveAll(runningDir)).ToNot(HaveOccurred())\n\t})\n\n\tContext(\"push with flag options\", func() {\n\t\tWhen(\"pushing from a symlinked current directory\", func() {\n\t\t\tIt(\"should push with the absolute path of the app\", func() {\n\t\t\t\thelpers.WithHelloWorldApp(func(dir string) {\n\t\t\t\t\tExpect(os.Symlink(dir, symlinkedPath)).ToNot(HaveOccurred())\n\n\t\t\t\t\tsession := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: symlinkedPath}, PushCommandName, appName)\n\t\t\t\t\t\/\/ Eventually(session).Should(helpers.SayPath(`path:\\s+%s`, dir))\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tWhen(\"pushing a symlinked path with the '-p' flag\", func() {\n\t\t\tIt(\"should push with the absolute path of the app\", func() {\n\t\t\t\thelpers.WithHelloWorldApp(func(dir string) {\n\t\t\t\t\tExpect(os.Symlink(dir, symlinkedPath)).ToNot(HaveOccurred())\n\n\t\t\t\t\tsession := helpers.CF(PushCommandName, appName, \"-p\", symlinkedPath)\n\t\t\t\t\t\/\/ Eventually(session).Should(helpers.SayPath(`path:\\s+%s`, dir))\n\t\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tWhen(\"pushing an symlinked archive with the '-p' flag\", func() {\n\t\t\tvar archive string\n\n\t\t\tBeforeEach(func() {\n\t\t\t\thelpers.WithHelloWorldApp(func(appDir string) {\n\t\t\t\t\ttmpfile, err := ioutil.TempFile(\"\", \"push-archive-integration\")\n\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\tarchive = tmpfile.Name()\n\t\t\t\t\tExpect(tmpfile.Close()).ToNot(HaveOccurred())\n\n\t\t\t\t\terr = helpers.Zipit(appDir, archive, \"\")\n\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tAfterEach(func() {\n\t\t\t\tExpect(os.RemoveAll(archive)).ToNot(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"should push with the absolute path of the archive\", func() {\n\t\t\t\tExpect(os.Symlink(archive, symlinkedPath)).ToNot(HaveOccurred())\n\n\t\t\t\tsession := helpers.CF(PushCommandName, appName, \"-p\", symlinkedPath)\n\t\t\t\t\/\/ Eventually(session).Should(helpers.SayPath(`path:\\s+%s`, archive))\n\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"push with a single app manifest\", func() {\n\t\t\tWhen(\"the path property is a symlinked path\", func() {\n\t\t\t\tIt(\"should push with the absolute path of the app\", func() {\n\t\t\t\t\tSkip(\"pending what ado about manifest\")\n\t\t\t\t\thelpers.WithHelloWorldApp(func(dir string) {\n\t\t\t\t\t\tExpect(os.Symlink(dir, symlinkedPath)).ToNot(HaveOccurred())\n\n\t\t\t\t\t\thelpers.WriteManifest(filepath.Join(runningDir, \"manifest.yml\"), map[string]interface{}{\n\t\t\t\t\t\t\t\"applications\": []map[string]string{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\"name\": appName,\n\t\t\t\t\t\t\t\t\t\"path\": symlinkedPath,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})\n\n\t\t\t\t\t\tsession := helpers.CustomCF(helpers.CFEnv{WorkingDirectory: runningDir}, PushCommandName)\n\t\t\t\t\t\tEventually(session).Should(helpers.SayPath(`path:\\s+%s`, dir))\n\t\t\t\t\t\tEventually(session).Should(Exit(0))\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package build\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/davecheney\/gogo\"\n)\n\nfunc Test(pkg *gogo.Package) gogo.Future {\n\t\/\/ commands are built as packages for testing.\n\treturn testPackage(pkg)\n}\n\nfunc testPackage(pkg *gogo.Package) gogo.Future {\n\t\/\/ build dependencies\n\tvar deps []gogo.Future\n\tfor _, dep := range pkg.Imports {\n\t\tdeps = append(deps, Build(dep))\n\t}\n\tcompile := compile(pkg, deps, true)\n\tbuildtest := buildTest(pkg, compile)\n\truntest := runTest(pkg, buildtest)\n\treturn runtest\n}\n\ntype buildTestTarget struct {\n\tfuture\n\tdeps []gogo.Future\n\t*gogo.Package\n}\n\nfunc (t *buildTestTarget) execute() {\n\tfor _, dep := range t.deps {\n\t\tif err := dep.Result(); err != nil {\n\t\t\tt.future.err <- err\n\t\t\treturn\n\t\t}\n\t}\n\tt.future.err <- t.build()\n}\n\nfunc (t *buildTestTarget) build() error {\n\tobjdir := t.Objdir()\n\tif err := t.buildTestMain(objdir); err != nil {\n\t\treturn err\n\t}\n\tif err := t.Gc(objdir, objdir, t.Package.Name()+\".6\", []string{\"_testmain.go\"}); err != nil {\n\t\treturn err\n\t}\n\treturn t.Ld(filepath.Join(objdir, t.Package.Name()+\".test\"), filepath.Join(objdir, t.Package.Name()+\".6\"))\n}\n\nfunc (t *buildTestTarget) buildTestMain(objdir string) error {\n\treturn writeTestmain(filepath.Join(t.Objdir(), \"_testmain.go\"), t.Package)\n}\n\nfunc buildTest(pkg *gogo.Package, deps ...gogo.Future) gogo.Future {\n\tt := &buildTestTarget{\n\t\tfuture: future{\n\t\t\terr: make(chan error, 1),\n\t\t},\n\t\tdeps:    deps,\n\t\tPackage: pkg,\n\t}\n\tgo t.execute()\n\treturn &t.future\n}\n\ntype runTestTarget struct {\n\tfuture\n\tdeps []gogo.Future\n\t*gogo.Package\n}\n\nfunc (t *runTestTarget) execute() {\n\tfor _, dep := range t.deps {\n\t\tif err := dep.Result(); err != nil {\n\t\t\tt.future.err <- err\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Printf(\"test %q\", t.Package.ImportPath())\n\tt.future.err <- t.build()\n}\n\nfunc (t *runTestTarget) build() error {\n\tcmd := exec.Command(filepath.Join(t.Objdir(), t.Package.Name()+\".test\"))\n\tcmd.Dir = t.Package.Srcdir()\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tlog.Printf(\"cd %s; %s\", cmd.Dir, strings.Join(cmd.Args, \" \"))\n\treturn cmd.Run()\n}\n\nfunc runTest(pkg *gogo.Package, deps ...gogo.Future) gogo.Future {\n\tt := &runTestTarget{\n\t\tfuture: future{\n\t\t\terr: make(chan error, 1),\n\t\t},\n\t\tdeps:    deps,\n\t\tPackage: pkg,\n\t}\n\tgo t.execute()\n\treturn &t.future\n}\n<commit_msg>added more documentation<commit_after>package build\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/davecheney\/gogo\"\n)\n\n\/\/ Test returns a Future representing the result of compiling the\n\/\/ package pkg, and its dependencies, and linking it with the \n\/\/ test runner.\nfunc Test(pkg *gogo.Package) gogo.Future {\n\t\/\/ commands are built as packages for testing.\n\treturn testPackage(pkg)\n}\n\nfunc testPackage(pkg *gogo.Package) gogo.Future {\n\t\/\/ build dependencies\n\tvar deps []gogo.Future\n\tfor _, dep := range pkg.Imports {\n\t\tdeps = append(deps, Build(dep))\n\t}\n\tcompile := compile(pkg, deps, true)\n\tbuildtest := buildTest(pkg, compile)\n\truntest := runTest(pkg, buildtest)\n\treturn runtest\n}\n\ntype buildTestTarget struct {\n\tfuture\n\tdeps []gogo.Future\n\t*gogo.Package\n}\n\nfunc (t *buildTestTarget) execute() {\n\tfor _, dep := range t.deps {\n\t\tif err := dep.Result(); err != nil {\n\t\t\tt.future.err <- err\n\t\t\treturn\n\t\t}\n\t}\n\tt.future.err <- t.build()\n}\n\nfunc (t *buildTestTarget) build() error {\n\tobjdir := t.Objdir()\n\tif err := t.buildTestMain(objdir); err != nil {\n\t\treturn err\n\t}\n\tif err := t.Gc(objdir, objdir, t.Package.Name()+\".6\", []string{\"_testmain.go\"}); err != nil {\n\t\treturn err\n\t}\n\treturn t.Ld(filepath.Join(objdir, t.Package.Name()+\".test\"), filepath.Join(objdir, t.Package.Name()+\".6\"))\n}\n\nfunc (t *buildTestTarget) buildTestMain(objdir string) error {\n\treturn writeTestmain(filepath.Join(t.Objdir(), \"_testmain.go\"), t.Package)\n}\n\nfunc buildTest(pkg *gogo.Package, deps ...gogo.Future) gogo.Future {\n\tt := &buildTestTarget{\n\t\tfuture: future{\n\t\t\terr: make(chan error, 1),\n\t\t},\n\t\tdeps:    deps,\n\t\tPackage: pkg,\n\t}\n\tgo t.execute()\n\treturn &t.future\n}\n\ntype runTestTarget struct {\n\tfuture\n\tdeps []gogo.Future\n\t*gogo.Package\n}\n\nfunc (t *runTestTarget) execute() {\n\tfor _, dep := range t.deps {\n\t\tif err := dep.Result(); err != nil {\n\t\t\tt.future.err <- err\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Printf(\"test %q\", t.Package.ImportPath())\n\tt.future.err <- t.build()\n}\n\nfunc (t *runTestTarget) build() error {\n\tcmd := exec.Command(filepath.Join(t.Objdir(), t.Package.Name()+\".test\"))\n\tcmd.Dir = t.Package.Srcdir()\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tlog.Printf(\"cd %s; %s\", cmd.Dir, strings.Join(cmd.Args, \" \"))\n\treturn cmd.Run()\n}\n\nfunc runTest(pkg *gogo.Package, deps ...gogo.Future) gogo.Future {\n\tt := &runTestTarget{\n\t\tfuture: future{\n\t\t\terr: make(chan error, 1),\n\t\t},\n\t\tdeps:    deps,\n\t\tPackage: pkg,\n\t}\n\tgo t.execute()\n\treturn &t.future\n}\n<|endoftext|>"}
{"text":"<commit_before>package util\n\nconst (\n\tVERSION = \"0.90\"\n)\n<commit_msg>start 0.91 beta<commit_after>package util\n\nconst (\n\tVERSION = \"0.91 beta\"\n)\n<|endoftext|>"}
{"text":"<commit_before>package kafkaadmin\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\tkafka \"github.com\/packetloop\/go-kafkaesque\"\n)\n\nfunc resourceKafkaTopic() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceKafkaTopicCreate,\n\t\tRead:   resourceKafkaTopicRead,\n\t\tExists: resourceKafkaTopicExists,\n\t\tUpdate: resourceKafkaTopicUpdate,\n\t\tDelete: resourceKafkaTopicDelete,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"name\": &schema.Schema{\n\t\t\t\tType:        schema.TypeString,\n\t\t\t\tRequired:    true,\n\t\t\t\tForceNew:    true,\n\t\t\t\tDescription: \"Kafka topic name\",\n\t\t\t},\n\t\t\t\"partitions\": &schema.Schema{\n\t\t\t\tType:         schema.TypeInt,\n\t\t\t\tOptional:     true,\n\t\t\t\tDescription:  \"number of partitions for the topic. Must be > 0\",\n\t\t\t\tDefault:      1,\n\t\t\t\tValidateFunc: validateGreaterThanZero,\n\t\t\t},\n\t\t\t\"replication_factor\": &schema.Schema{\n\t\t\t\tType:         schema.TypeInt,\n\t\t\t\tOptional:     true,\n\t\t\t\tForceNew:     true,\n\t\t\t\tDescription:  \"the replication factor for the topic. Must be > 0\",\n\t\t\t\tDefault:      1,\n\t\t\t\tValidateFunc: validateGreaterThanZero,\n\t\t\t},\n\t\t\t\"retention_ms\": &schema.Schema{\n\t\t\t\tType:        schema.TypeInt,\n\t\t\t\tOptional:    true,\n\t\t\t\tDescription: \"the retention period in milliseconds for the topic. If set to -1, no time limit is applied\",\n\t\t\t\tDefault:     -1,\n\t\t\t},\n\t\t\t\"cleanup_policy\": &schema.Schema{\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tOptional:     true,\n\t\t\t\tDescription:  \"the clean up policy for the topic. Either delete or compact\",\n\t\t\t\tDefault:      \"compact\",\n\t\t\t\tValidateFunc: validateCleanupPolicy,\n\t\t\t},\n\t\t\t\"segment_bytes\": &schema.Schema{\n\t\t\t\tType:         schema.TypeInt,\n\t\t\t\tOptional:     true,\n\t\t\t\tDescription:  \"the segment file size for the log\",\n\t\t\t\tDefault:      1073741824,\n\t\t\t\tValidateFunc: validateSegmentBytes,\n\t\t\t},\n\t\t\t\"min_insync_replicas\": &schema.Schema{\n\t\t\t\tType:         schema.TypeInt,\n\t\t\t\tOptional:     true,\n\t\t\t\tDescription:  \"the minimum number of insync replicas. Must be > 0\",\n\t\t\t\tDefault:      1,\n\t\t\t\tValidateFunc: validateGreaterThanZero,\n\t\t\t},\n\t\t\t\"segment_ms\": &schema.Schema{\n\t\t\t\tType:         schema.TypeInt,\n\t\t\t\tOptional:     true,\n\t\t\t\tDescription:  \"the time after which Kafka will force the log to roll. Must be > 0\",\n\t\t\t\tDefault:      604800000,\n\t\t\t\tValidateFunc: validateGreaterThanZero,\n\t\t\t},\n\t\t\t\"retention_bytes\": &schema.Schema{\n\t\t\t\tType:        schema.TypeInt,\n\t\t\t\tOptional:    true,\n\t\t\t\tDescription: \"the retention bytes for the topic\",\n\t\t\t\tDefault:     -1,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceKafkaTopicCreate(d *schema.ResourceData, m interface{}) error {\n\n\tid := strings.ToLower(d.Get(\"name\").(string))\n\td.SetId(id)\n\treturn createRequest(d, m)\n}\n\nfunc resourceKafkaTopicExists(d *schema.ResourceData, m interface{}) (b bool, e error) {\n\t\/\/ Exists - This is called to verify a resource still exists. It is called prior to Read,\n\t\/\/ and lowers the burden of Read to be able to assume the resource exists.\n\tclient := clientConn(m)\n\t_, err := client.GetTopic(d.Id())\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"TOPIC '%v' DOES NOT EXIST: %v\", d.Id(), err)\n\t}\n\treturn true, nil\n\n}\n\nfunc createRequest(d *schema.ResourceData, m interface{}) error {\n\tid := strings.ToLower(d.Get(\"name\").(string))\n\tpartitions := strconv.Itoa(d.Get(\"partitions\").(int))\n\treplicationFactor := strconv.Itoa(d.Get(\"replication_factor\").(int))\n\tretentionMs := strconv.Itoa(d.Get(\"retention_ms\").(int))\n\tcleanupPolicy := d.Get(\"cleanup_policy\").(string)\n\tsegmentBytes := strconv.Itoa(d.Get(\"segment_bytes\").(int))\n\tretentionBytes := strconv.Itoa(d.Get(\"retention_bytes\").(int))\n\tsegmentMs := strconv.Itoa(d.Get(\"segment_ms\").(int))\n\tminInsyncReplicas := strconv.Itoa(d.Get(\"min_insync_replicas\").(int))\n\n\tlog.Printf(\"[TRACE] creating kafka topic '%s'...\", id)\n\tclient := clientConn(m)\n\tt := kafka.NewTopic(id).\n\t\tSetReplicationFactor(replicationFactor).\n\t\tSetPartitions(partitions).\n\t\tBuildTopic()\n\tt.Config = &kafka.Config{\n\t\tRetentionMs:       retentionMs,\n\t\tSegmentBytes:      segmentBytes,\n\t\tCleanupPolicy:     cleanupPolicy,\n\t\tMinInsyncReplicas: minInsyncReplicas,\n\t\tRetentionBytes:    retentionBytes,\n\t\tSegmentMs:         segmentMs,\n\t}\n\tresp, err := client.CreateTopic(t)\n\tif err != nil {\n\t\tlog.Printf(\"[DEBUG] Error Response %v\", err)\n\t}\n\n\treturn checkResponse(d, m, resp, err)\n}\n\nfunc checkResponse(d *schema.ResourceData, m interface{}, r kafka.Response, err error) error {\n\tlog.Printf(\"[TRACE] Create Topic %v\", r)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"CREATE TOPIC '%s' ERROR: %v\", d.Id(), err)\n\t}\n\treturn resourceKafkaTopicRead(d, m)\n}\n\n\/\/ resourceKafkaTopicRead is called to resync the local state with the remote state.\n\/\/ Terraform guarantees that an existing ID will be set. This ID should be used\n\/\/ to look up the resource. Any remote data should be updated into the local data.\n\/\/ No changes to the remote resource are to be made.\nfunc resourceKafkaTopicRead(d *schema.ResourceData, m interface{}) error {\n\tclient := clientConn(m)\n\n\tr, err := client.GetTopic(d.Id())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"GET TOPIC '%s' ERROR: %v\", d.Id(), err)\n\t}\n\n\t\/\/ Unfortunately get topics does not return name of topic, only its config params.\n\td.Set(\"name\", strings.ToLower(d.Id()))\n\td.Set(\"partitions\", r.GetPartitions())\n\td.Set(\"replication_factor\", r.GetReplicationFactor())\n\td.Set(\"retention_ms\", r.GetRetentionMs())\n\td.Set(\"cleanup_policy\", r.GetCleanupPolicy())\n\td.Set(\"segment_bytes\", r.GetSegmentBytes())\n\td.Set(\"min_insync_replicas\", r.GetMinInSyncReplicas())\n\td.Set(\"retention_bytes\", r.GetRetentionBytes())\n\td.Set(\"segment_ms\", r.GetSegmentMs())\n\treturn nil\n\n}\n\nfunc resourceKafkaTopicUpdate(d *schema.ResourceData, m interface{}) error {\n\td.Partial(true)\n\n\tif d.HasChange(\"name\") ||\n\t\td.HasChange(\"replication_factor\") ||\n\t\td.HasChange(\"partitions\") ||\n\t\td.HasChange(\"retention_ms\") ||\n\t\td.HasChange(\"cleanup_policy\") ||\n\t\td.HasChange(\"segment_bytes\") ||\n\t\td.HasChange(\"segment_ms\") ||\n\t\td.HasChange(\"min_insync_replicas\") ||\n\t\td.HasChange(\"retention_bytes\") {\n\t\tlog.Printf(\"[TRACE] UPDATE TOPIC '%s' success\", d.Id())\n\t\td.Partial(false)\n\n\t\treturn updateRequest(d, m)\n\t}\n\treturn nil\n}\n\nfunc updateRequest(d *schema.ResourceData, m interface{}) error {\n\tid := strings.ToLower(d.Get(\"name\").(string))\n\tpartitions := strconv.Itoa(d.Get(\"partitions\").(int))\n\treplicationFactor := strconv.Itoa(d.Get(\"replication_factor\").(int))\n\tretentionMs := strconv.Itoa(d.Get(\"retention_ms\").(int))\n\tcleanupPolicy := d.Get(\"cleanup_policy\").(string)\n\tsegmentBytes := strconv.Itoa(d.Get(\"segment_bytes\").(int))\n\tretentionBytes := strconv.Itoa(d.Get(\"retention_bytes\").(int))\n\tsegmentMs := strconv.Itoa(d.Get(\"segment_ms\").(int))\n\tminInsyncReplicas := strconv.Itoa(d.Get(\"min_insync_replicas\").(int))\n\n\tlog.Printf(\"[TRACE] UPDATE KAFKA TOPIC '%s'...\", id)\n\n\tclient := clientConn(m)\n\n\tt := kafka.NewTopic(id).\n\t\tSetReplicationFactor(replicationFactor).\n\t\tSetPartitions(partitions).\n\t\tBuildTopic()\n\tt.Config = &kafka.Config{\n\t\tRetentionMs:       retentionMs,\n\t\tSegmentBytes:      segmentBytes,\n\t\tCleanupPolicy:     cleanupPolicy,\n\t\tMinInsyncReplicas: minInsyncReplicas,\n\t\tRetentionBytes:    retentionBytes,\n\t\tSegmentMs:         segmentMs,\n\t}\n\n\tresp, err := client.UpdateTopic(t)\n\tif err != nil {\n\t\tlog.Printf(\"[DEBUG] Error Response %v\", err)\n\t}\n\n\treturn checkResponse(d, m, resp, err)\n}\n\nfunc resourceKafkaTopicDelete(d *schema.ResourceData, m interface{}) error {\n\ta := deleteRequest(d.Id())\n\treturn a(d, m)\n}\n\nfunc deleteRequest(id string) (f func(d *schema.ResourceData, m interface{}) error) {\n\treturn func(d *schema.ResourceData, m interface{}) error {\n\t\tclient := clientConn(m)\n\t\t\/\/ Return 'Ok' when successful. Otherwise, this throws an error. Hence,\n\t\t\/\/ we can safely ignore this.\n\t\t_, err := client.DeleteTopic(id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n}\n<commit_msg>MAYH-10089 fix-typo-default value<commit_after>package kafkaadmin\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\tkafka \"github.com\/packetloop\/go-kafkaesque\"\n)\n\nfunc resourceKafkaTopic() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceKafkaTopicCreate,\n\t\tRead:   resourceKafkaTopicRead,\n\t\tExists: resourceKafkaTopicExists,\n\t\tUpdate: resourceKafkaTopicUpdate,\n\t\tDelete: resourceKafkaTopicDelete,\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"name\": &schema.Schema{\n\t\t\t\tType:        schema.TypeString,\n\t\t\t\tRequired:    true,\n\t\t\t\tForceNew:    true,\n\t\t\t\tDescription: \"Kafka topic name\",\n\t\t\t},\n\t\t\t\"partitions\": &schema.Schema{\n\t\t\t\tType:         schema.TypeInt,\n\t\t\t\tOptional:     true,\n\t\t\t\tDescription:  \"number of partitions for the topic. Must be > 0\",\n\t\t\t\tDefault:      1,\n\t\t\t\tValidateFunc: validateGreaterThanZero,\n\t\t\t},\n\t\t\t\"replication_factor\": &schema.Schema{\n\t\t\t\tType:         schema.TypeInt,\n\t\t\t\tOptional:     true,\n\t\t\t\tForceNew:     true,\n\t\t\t\tDescription:  \"the replication factor for the topic. Must be > 0\",\n\t\t\t\tDefault:      1,\n\t\t\t\tValidateFunc: validateGreaterThanZero,\n\t\t\t},\n\t\t\t\"retention_ms\": &schema.Schema{\n\t\t\t\tType:        schema.TypeInt,\n\t\t\t\tOptional:    true,\n\t\t\t\tDescription: \"the retention period in milliseconds for the topic. If set to -1, no time limit is applied\",\n\t\t\t\tDefault:     -1,\n\t\t\t},\n\t\t\t\"cleanup_policy\": &schema.Schema{\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tOptional:     true,\n\t\t\t\tDescription:  \"the clean up policy for the topic. Either delete or compact\",\n\t\t\t\tDefault:      \"delete\",\n\t\t\t\tValidateFunc: validateCleanupPolicy,\n\t\t\t},\n\t\t\t\"segment_bytes\": &schema.Schema{\n\t\t\t\tType:         schema.TypeInt,\n\t\t\t\tOptional:     true,\n\t\t\t\tDescription:  \"the segment file size for the log\",\n\t\t\t\tDefault:      1073741824,\n\t\t\t\tValidateFunc: validateSegmentBytes,\n\t\t\t},\n\t\t\t\"min_insync_replicas\": &schema.Schema{\n\t\t\t\tType:         schema.TypeInt,\n\t\t\t\tOptional:     true,\n\t\t\t\tDescription:  \"the minimum number of insync replicas. Must be > 0\",\n\t\t\t\tDefault:      1,\n\t\t\t\tValidateFunc: validateGreaterThanZero,\n\t\t\t},\n\t\t\t\"segment_ms\": &schema.Schema{\n\t\t\t\tType:         schema.TypeInt,\n\t\t\t\tOptional:     true,\n\t\t\t\tDescription:  \"the time after which Kafka will force the log to roll. Must be > 0\",\n\t\t\t\tDefault:      604800000,\n\t\t\t\tValidateFunc: validateGreaterThanZero,\n\t\t\t},\n\t\t\t\"retention_bytes\": &schema.Schema{\n\t\t\t\tType:        schema.TypeInt,\n\t\t\t\tOptional:    true,\n\t\t\t\tDescription: \"the retention bytes for the topic\",\n\t\t\t\tDefault:     -1,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceKafkaTopicCreate(d *schema.ResourceData, m interface{}) error {\n\n\tid := strings.ToLower(d.Get(\"name\").(string))\n\td.SetId(id)\n\treturn createRequest(d, m)\n}\n\nfunc resourceKafkaTopicExists(d *schema.ResourceData, m interface{}) (b bool, e error) {\n\t\/\/ Exists - This is called to verify a resource still exists. It is called prior to Read,\n\t\/\/ and lowers the burden of Read to be able to assume the resource exists.\n\tclient := clientConn(m)\n\t_, err := client.GetTopic(d.Id())\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"TOPIC '%v' DOES NOT EXIST: %v\", d.Id(), err)\n\t}\n\treturn true, nil\n\n}\n\nfunc createRequest(d *schema.ResourceData, m interface{}) error {\n\tid := strings.ToLower(d.Get(\"name\").(string))\n\tpartitions := strconv.Itoa(d.Get(\"partitions\").(int))\n\treplicationFactor := strconv.Itoa(d.Get(\"replication_factor\").(int))\n\tretentionMs := strconv.Itoa(d.Get(\"retention_ms\").(int))\n\tcleanupPolicy := d.Get(\"cleanup_policy\").(string)\n\tsegmentBytes := strconv.Itoa(d.Get(\"segment_bytes\").(int))\n\tretentionBytes := strconv.Itoa(d.Get(\"retention_bytes\").(int))\n\tsegmentMs := strconv.Itoa(d.Get(\"segment_ms\").(int))\n\tminInsyncReplicas := strconv.Itoa(d.Get(\"min_insync_replicas\").(int))\n\n\tlog.Printf(\"[TRACE] creating kafka topic '%s'...\", id)\n\tclient := clientConn(m)\n\tt := kafka.NewTopic(id).\n\t\tSetReplicationFactor(replicationFactor).\n\t\tSetPartitions(partitions).\n\t\tBuildTopic()\n\tt.Config = &kafka.Config{\n\t\tRetentionMs:       retentionMs,\n\t\tSegmentBytes:      segmentBytes,\n\t\tCleanupPolicy:     cleanupPolicy,\n\t\tMinInsyncReplicas: minInsyncReplicas,\n\t\tRetentionBytes:    retentionBytes,\n\t\tSegmentMs:         segmentMs,\n\t}\n\tresp, err := client.CreateTopic(t)\n\tif err != nil {\n\t\tlog.Printf(\"[DEBUG] Error Response %v\", err)\n\t}\n\n\treturn checkResponse(d, m, resp, err)\n}\n\nfunc checkResponse(d *schema.ResourceData, m interface{}, r kafka.Response, err error) error {\n\tlog.Printf(\"[TRACE] Create Topic %v\", r)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"CREATE TOPIC '%s' ERROR: %v\", d.Id(), err)\n\t}\n\treturn resourceKafkaTopicRead(d, m)\n}\n\n\/\/ resourceKafkaTopicRead is called to resync the local state with the remote state.\n\/\/ Terraform guarantees that an existing ID will be set. This ID should be used\n\/\/ to look up the resource. Any remote data should be updated into the local data.\n\/\/ No changes to the remote resource are to be made.\nfunc resourceKafkaTopicRead(d *schema.ResourceData, m interface{}) error {\n\tclient := clientConn(m)\n\n\tr, err := client.GetTopic(d.Id())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"GET TOPIC '%s' ERROR: %v\", d.Id(), err)\n\t}\n\n\t\/\/ Unfortunately get topics does not return name of topic, only its config params.\n\td.Set(\"name\", strings.ToLower(d.Id()))\n\td.Set(\"partitions\", r.GetPartitions())\n\td.Set(\"replication_factor\", r.GetReplicationFactor())\n\td.Set(\"retention_ms\", r.GetRetentionMs())\n\td.Set(\"cleanup_policy\", r.GetCleanupPolicy())\n\td.Set(\"segment_bytes\", r.GetSegmentBytes())\n\td.Set(\"min_insync_replicas\", r.GetMinInSyncReplicas())\n\td.Set(\"retention_bytes\", r.GetRetentionBytes())\n\td.Set(\"segment_ms\", r.GetSegmentMs())\n\treturn nil\n\n}\n\nfunc resourceKafkaTopicUpdate(d *schema.ResourceData, m interface{}) error {\n\td.Partial(true)\n\n\tif d.HasChange(\"name\") ||\n\t\td.HasChange(\"replication_factor\") ||\n\t\td.HasChange(\"partitions\") ||\n\t\td.HasChange(\"retention_ms\") ||\n\t\td.HasChange(\"cleanup_policy\") ||\n\t\td.HasChange(\"segment_bytes\") ||\n\t\td.HasChange(\"segment_ms\") ||\n\t\td.HasChange(\"min_insync_replicas\") ||\n\t\td.HasChange(\"retention_bytes\") {\n\t\tlog.Printf(\"[TRACE] UPDATE TOPIC '%s' success\", d.Id())\n\t\td.Partial(false)\n\n\t\treturn updateRequest(d, m)\n\t}\n\treturn nil\n}\n\nfunc updateRequest(d *schema.ResourceData, m interface{}) error {\n\tid := strings.ToLower(d.Get(\"name\").(string))\n\tpartitions := strconv.Itoa(d.Get(\"partitions\").(int))\n\treplicationFactor := strconv.Itoa(d.Get(\"replication_factor\").(int))\n\tretentionMs := strconv.Itoa(d.Get(\"retention_ms\").(int))\n\tcleanupPolicy := d.Get(\"cleanup_policy\").(string)\n\tsegmentBytes := strconv.Itoa(d.Get(\"segment_bytes\").(int))\n\tretentionBytes := strconv.Itoa(d.Get(\"retention_bytes\").(int))\n\tsegmentMs := strconv.Itoa(d.Get(\"segment_ms\").(int))\n\tminInsyncReplicas := strconv.Itoa(d.Get(\"min_insync_replicas\").(int))\n\n\tlog.Printf(\"[TRACE] UPDATE KAFKA TOPIC '%s'...\", id)\n\n\tclient := clientConn(m)\n\n\tt := kafka.NewTopic(id).\n\t\tSetReplicationFactor(replicationFactor).\n\t\tSetPartitions(partitions).\n\t\tBuildTopic()\n\tt.Config = &kafka.Config{\n\t\tRetentionMs:       retentionMs,\n\t\tSegmentBytes:      segmentBytes,\n\t\tCleanupPolicy:     cleanupPolicy,\n\t\tMinInsyncReplicas: minInsyncReplicas,\n\t\tRetentionBytes:    retentionBytes,\n\t\tSegmentMs:         segmentMs,\n\t}\n\n\tresp, err := client.UpdateTopic(t)\n\tif err != nil {\n\t\tlog.Printf(\"[DEBUG] Error Response %v\", err)\n\t}\n\n\treturn checkResponse(d, m, resp, err)\n}\n\nfunc resourceKafkaTopicDelete(d *schema.ResourceData, m interface{}) error {\n\ta := deleteRequest(d.Id())\n\treturn a(d, m)\n}\n\nfunc deleteRequest(id string) (f func(d *schema.ResourceData, m interface{}) error) {\n\treturn func(d *schema.ResourceData, m interface{}) error {\n\t\tclient := clientConn(m)\n\t\t\/\/ Return 'Ok' when successful. Otherwise, this throws an error. Hence,\n\t\t\/\/ we can safely ignore this.\n\t\t_, err := client.DeleteTopic(id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Simple caching library with expiration capabilities\n *     Copyright (c) 2013, Christian Muehlhaeuser <muesli@gmail.com>\n *\n *   For license see LICENSE.txt\n *\/\n\npackage cache2go\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ Structure of a table with items in the cache.\ntype CacheTable struct {\n\tsync.RWMutex\n\n\t\/\/ The table's name.\n\tname string\n\t\/\/ All cached items.\n\titems map[interface{}]*CacheItem\n\n\t\/\/ Timer responsible for triggering cleanup.\n\tcleanupTimer *time.Timer\n\t\/\/ Current timer duration.\n\tcleanupInterval time.Duration\n\n\t\/\/ The logger used for this table.\n\tlogger *log.Logger\n\n\t\/\/ Callback method triggered when trying to load a non-existing key.\n\tloadData func(interface{}) *CacheItem\n\t\/\/ Callback method triggered when adding a new item to the cache.\n\taddedItem func(*CacheItem)\n\t\/\/ Callback method triggered before deleting an item from the cache.\n\taboutToDeleteItem func(*CacheItem)\n}\n\n\/\/ Returns how many items are currently stored in the cache.\nfunc (table *CacheTable) Count() int {\n\ttable.RLock()\n\tdefer table.RUnlock()\n\treturn len(table.items)\n}\n\n\/\/ Configures a data-loader callback, which will be called when trying\n\/\/ to use access a non-existing key.\nfunc (table *CacheTable) SetDataLoader(f func(interface{}) *CacheItem) {\n\ttable.Lock()\n\tdefer table.Unlock()\n\ttable.loadData = f\n}\n\n\/\/ Configures a callback, which will be called every time a new item\n\/\/ is added to the cache.\nfunc (table *CacheTable) SetAddedItemCallback(f func(*CacheItem)) {\n\ttable.Lock()\n\tdefer table.Unlock()\n\ttable.addedItem = f\n}\n\n\/\/ Configures a callback, which will be called every time an item\n\/\/ is about to be removed from the cache.\nfunc (table *CacheTable) SetAboutToDeleteItemCallback(f func(*CacheItem)) {\n\ttable.Lock()\n\tdefer table.Unlock()\n\ttable.aboutToDeleteItem = f\n}\n\n\/\/ Sets the logger to be used by this cache table.\nfunc (table *CacheTable) SetLogger(logger *log.Logger) {\n\ttable.Lock()\n\tdefer table.Unlock()\n\ttable.logger = logger\n}\n\n\/\/ Expiration check loop, triggered by a self-adjusting timer.\nfunc (table *CacheTable) expirationCheck() {\n\ttable.Lock()\n\tif table.cleanupTimer != nil {\n\t\ttable.cleanupTimer.Stop()\n\t}\n\tif table.cleanupInterval > 0 {\n\t\ttable.log(\"Expiration check triggered after\", table.cleanupInterval, \"for table\", table.name)\n\t} else {\n\t\ttable.log(\"Expiration check installed for table\", table.name)\n\t}\n\n\t\/\/ Cache value so we don't keep blocking the mutex.\n\titems := table.items\n\ttable.Unlock()\n\n\t\/\/ To be more accurate with timers, we would need to update 'now' on every\n\t\/\/ loop iteration. Not sure it's really efficient though.\n\tnow := time.Now()\n\tsmallestDuration := 0 * time.Second\n\tfor key, item := range items {\n\t\t\/\/ Cache values so we don't keep blocking the mutex.\n\t\titem.RLock()\n\t\tlifeSpan := item.lifeSpan\n\t\taccessedOn := item.accessedOn\n\t\titem.RUnlock()\n\n\t\tif lifeSpan == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif now.Sub(accessedOn) >= lifeSpan {\n\t\t\t\/\/ Item has excessed its lifespan.\n\t\t\ttable.Delete(key)\n\t\t} else {\n\t\t\t\/\/ Find the item chronologically closest to its end-of-lifespan.\n\t\t\tif smallestDuration == 0 || lifeSpan < smallestDuration {\n\t\t\t\tsmallestDuration = lifeSpan - now.Sub(accessedOn)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Setup the interval for the next cleanup run.\n\ttable.Lock()\n\ttable.cleanupInterval = smallestDuration\n\tif smallestDuration > 0 {\n\t\ttable.cleanupTimer = time.AfterFunc(smallestDuration, func() {\n\t\t\tgo table.expirationCheck()\n\t\t})\n\t}\n\ttable.Unlock()\n}\n\n\/\/ Adds a key\/value pair to the cache.\n\/\/ Parameter key is the item's cache-key.\n\/\/ Parameter lifeSpan determines after which time period without an access the item\n\/\/ will get removed from the cache.\n\/\/ Parameter data is the item's value.\nfunc (table *CacheTable) Cache(key interface{}, lifeSpan time.Duration, data interface{}) *CacheItem {\n\titem := CreateCacheItem(key, lifeSpan, data)\n\n\t\/\/ Add item to cache.\n\ttable.Lock()\n\ttable.log(\"Adding item with key\", key, \"and lifespan of\", lifeSpan, \"to table\", table.name)\n\ttable.items[key] = &item\n\n\t\/\/ Cache values so we don't keep blocking the mutex.\n\texpDur := table.cleanupInterval\n\taddedItem := table.addedItem\n\ttable.Unlock()\n\n\t\/\/ Trigger callback after adding an item to cache.\n\tif addedItem != nil {\n\t\taddedItem(&item)\n\t}\n\n\t\/\/ If we haven't set up any expiration check timer or found a more imminent item.\n\tif lifeSpan > 0 && (expDur == 0 || lifeSpan < expDur) {\n\t\ttable.expirationCheck()\n\t}\n\n\treturn &item\n}\n\n\/\/ Delete an item from the cache.\nfunc (table *CacheTable) Delete(key interface{}) (*CacheItem, error) {\n\ttable.RLock()\n\tr, ok := table.items[key]\n\tif !ok {\n\t\ttable.RUnlock()\n\t\treturn nil, ErrKeyNotFound\n\t}\n\n\t\/\/ Cache value so we don't keep blocking the mutex.\n\taboutToDeleteItem := table.aboutToDeleteItem\n\ttable.RUnlock()\n\n\t\/\/ Trigger callbacks before deleting an item from cache.\n\tif aboutToDeleteItem != nil {\n\t\taboutToDeleteItem(r)\n\t}\n\n\tr.RLock()\n\tdefer r.RUnlock()\n\tif r.aboutToExpire != nil {\n\t\tr.aboutToExpire(key)\n\t}\n\n\ttable.Lock()\n\tdefer table.Unlock()\n\ttable.log(\"Deleting item with key\", key, \"created on\", r.createdOn, \"and hit\", r.accessCount, \"times from table\", table.name)\n\tdelete(table.items, key)\n\n\treturn r, nil\n}\n\n\/\/ Test whether an item exists in the cache. Unlike the Value method\n\/\/ Exists neither tries to fetch data via the loadData callback nor\n\/\/ does it keep the item alive in the cache.\nfunc (table *CacheTable) Exists(key interface{}) bool {\n\ttable.RLock()\n\tdefer table.RUnlock()\n\t_, ok := table.items[key]\n\n\treturn ok\n}\n\n\/\/ Get an item from the cache and mark it to be kept alive.\nfunc (table *CacheTable) Value(key interface{}) (*CacheItem, error) {\n\ttable.RLock()\n\tr, ok := table.items[key]\n\tloadData := table.loadData\n\ttable.RUnlock()\n\n\tif ok {\n\t\t\/\/ Update access counter and timestamp.\n\t\tr.KeepAlive()\n\t\treturn r, nil\n\t}\n\n\t\/\/ Item doesn't exist in cache. Try and fetch it with a data-loader.\n\tif loadData != nil {\n\t\titem := loadData(key)\n\t\tif item != nil {\n\t\t\ttable.Cache(key, item.lifeSpan, item.data)\n\t\t\treturn item, nil\n\t\t}\n\n\t\treturn nil, ErrKeyNotFoundOrLoadable\n\t}\n\n\treturn nil, ErrKeyNotFound\n}\n\n\/\/ Delete all items from cache.\nfunc (table *CacheTable) Flush() {\n\ttable.Lock()\n\tdefer table.Unlock()\n\n\ttable.log(\"Flushing table\", table.name)\n\n\ttable.items = make(map[interface{}]*CacheItem)\n\ttable.cleanupInterval = 0\n\tif table.cleanupTimer != nil {\n\t\ttable.cleanupTimer.Stop()\n\t}\n}\n\n\/\/ Internal logging method for convenience.\nfunc (table *CacheTable) log(v ...interface{}) {\n\tif table.logger == nil {\n\t\treturn\n\t}\n\n\ttable.logger.Println(v)\n}\n<commit_msg>cleaned imports<commit_after>\/*\n * Simple caching library with expiration capabilities\n *     Copyright (c) 2013, Christian Muehlhaeuser <muesli@gmail.com>\n *\n *   For license see LICENSE.txt\n *\/\n\npackage cache2go\n\nimport (\n\t\"log\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ Structure of a table with items in the cache.\ntype CacheTable struct {\n\tsync.RWMutex\n\n\t\/\/ The table's name.\n\tname string\n\t\/\/ All cached items.\n\titems map[interface{}]*CacheItem\n\n\t\/\/ Timer responsible for triggering cleanup.\n\tcleanupTimer *time.Timer\n\t\/\/ Current timer duration.\n\tcleanupInterval time.Duration\n\n\t\/\/ The logger used for this table.\n\tlogger *log.Logger\n\n\t\/\/ Callback method triggered when trying to load a non-existing key.\n\tloadData func(interface{}) *CacheItem\n\t\/\/ Callback method triggered when adding a new item to the cache.\n\taddedItem func(*CacheItem)\n\t\/\/ Callback method triggered before deleting an item from the cache.\n\taboutToDeleteItem func(*CacheItem)\n}\n\n\/\/ Returns how many items are currently stored in the cache.\nfunc (table *CacheTable) Count() int {\n\ttable.RLock()\n\tdefer table.RUnlock()\n\treturn len(table.items)\n}\n\n\/\/ Configures a data-loader callback, which will be called when trying\n\/\/ to use access a non-existing key.\nfunc (table *CacheTable) SetDataLoader(f func(interface{}) *CacheItem) {\n\ttable.Lock()\n\tdefer table.Unlock()\n\ttable.loadData = f\n}\n\n\/\/ Configures a callback, which will be called every time a new item\n\/\/ is added to the cache.\nfunc (table *CacheTable) SetAddedItemCallback(f func(*CacheItem)) {\n\ttable.Lock()\n\tdefer table.Unlock()\n\ttable.addedItem = f\n}\n\n\/\/ Configures a callback, which will be called every time an item\n\/\/ is about to be removed from the cache.\nfunc (table *CacheTable) SetAboutToDeleteItemCallback(f func(*CacheItem)) {\n\ttable.Lock()\n\tdefer table.Unlock()\n\ttable.aboutToDeleteItem = f\n}\n\n\/\/ Sets the logger to be used by this cache table.\nfunc (table *CacheTable) SetLogger(logger *log.Logger) {\n\ttable.Lock()\n\tdefer table.Unlock()\n\ttable.logger = logger\n}\n\n\/\/ Expiration check loop, triggered by a self-adjusting timer.\nfunc (table *CacheTable) expirationCheck() {\n\ttable.Lock()\n\tif table.cleanupTimer != nil {\n\t\ttable.cleanupTimer.Stop()\n\t}\n\tif table.cleanupInterval > 0 {\n\t\ttable.log(\"Expiration check triggered after\", table.cleanupInterval, \"for table\", table.name)\n\t} else {\n\t\ttable.log(\"Expiration check installed for table\", table.name)\n\t}\n\n\t\/\/ Cache value so we don't keep blocking the mutex.\n\titems := table.items\n\ttable.Unlock()\n\n\t\/\/ To be more accurate with timers, we would need to update 'now' on every\n\t\/\/ loop iteration. Not sure it's really efficient though.\n\tnow := time.Now()\n\tsmallestDuration := 0 * time.Second\n\tfor key, item := range items {\n\t\t\/\/ Cache values so we don't keep blocking the mutex.\n\t\titem.RLock()\n\t\tlifeSpan := item.lifeSpan\n\t\taccessedOn := item.accessedOn\n\t\titem.RUnlock()\n\n\t\tif lifeSpan == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif now.Sub(accessedOn) >= lifeSpan {\n\t\t\t\/\/ Item has excessed its lifespan.\n\t\t\ttable.Delete(key)\n\t\t} else {\n\t\t\t\/\/ Find the item chronologically closest to its end-of-lifespan.\n\t\t\tif smallestDuration == 0 || lifeSpan < smallestDuration {\n\t\t\t\tsmallestDuration = lifeSpan - now.Sub(accessedOn)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Setup the interval for the next cleanup run.\n\ttable.Lock()\n\ttable.cleanupInterval = smallestDuration\n\tif smallestDuration > 0 {\n\t\ttable.cleanupTimer = time.AfterFunc(smallestDuration, func() {\n\t\t\tgo table.expirationCheck()\n\t\t})\n\t}\n\ttable.Unlock()\n}\n\n\/\/ Adds a key\/value pair to the cache.\n\/\/ Parameter key is the item's cache-key.\n\/\/ Parameter lifeSpan determines after which time period without an access the item\n\/\/ will get removed from the cache.\n\/\/ Parameter data is the item's value.\nfunc (table *CacheTable) Cache(key interface{}, lifeSpan time.Duration, data interface{}) *CacheItem {\n\titem := CreateCacheItem(key, lifeSpan, data)\n\n\t\/\/ Add item to cache.\n\ttable.Lock()\n\ttable.log(\"Adding item with key\", key, \"and lifespan of\", lifeSpan, \"to table\", table.name)\n\ttable.items[key] = &item\n\n\t\/\/ Cache values so we don't keep blocking the mutex.\n\texpDur := table.cleanupInterval\n\taddedItem := table.addedItem\n\ttable.Unlock()\n\n\t\/\/ Trigger callback after adding an item to cache.\n\tif addedItem != nil {\n\t\taddedItem(&item)\n\t}\n\n\t\/\/ If we haven't set up any expiration check timer or found a more imminent item.\n\tif lifeSpan > 0 && (expDur == 0 || lifeSpan < expDur) {\n\t\ttable.expirationCheck()\n\t}\n\n\treturn &item\n}\n\n\/\/ Delete an item from the cache.\nfunc (table *CacheTable) Delete(key interface{}) (*CacheItem, error) {\n\ttable.RLock()\n\tr, ok := table.items[key]\n\tif !ok {\n\t\ttable.RUnlock()\n\t\treturn nil, ErrKeyNotFound\n\t}\n\n\t\/\/ Cache value so we don't keep blocking the mutex.\n\taboutToDeleteItem := table.aboutToDeleteItem\n\ttable.RUnlock()\n\n\t\/\/ Trigger callbacks before deleting an item from cache.\n\tif aboutToDeleteItem != nil {\n\t\taboutToDeleteItem(r)\n\t}\n\n\tr.RLock()\n\tdefer r.RUnlock()\n\tif r.aboutToExpire != nil {\n\t\tr.aboutToExpire(key)\n\t}\n\n\ttable.Lock()\n\tdefer table.Unlock()\n\ttable.log(\"Deleting item with key\", key, \"created on\", r.createdOn, \"and hit\", r.accessCount, \"times from table\", table.name)\n\tdelete(table.items, key)\n\n\treturn r, nil\n}\n\n\/\/ Test whether an item exists in the cache. Unlike the Value method\n\/\/ Exists neither tries to fetch data via the loadData callback nor\n\/\/ does it keep the item alive in the cache.\nfunc (table *CacheTable) Exists(key interface{}) bool {\n\ttable.RLock()\n\tdefer table.RUnlock()\n\t_, ok := table.items[key]\n\n\treturn ok\n}\n\n\/\/ Get an item from the cache and mark it to be kept alive.\nfunc (table *CacheTable) Value(key interface{}) (*CacheItem, error) {\n\ttable.RLock()\n\tr, ok := table.items[key]\n\tloadData := table.loadData\n\ttable.RUnlock()\n\n\tif ok {\n\t\t\/\/ Update access counter and timestamp.\n\t\tr.KeepAlive()\n\t\treturn r, nil\n\t}\n\n\t\/\/ Item doesn't exist in cache. Try and fetch it with a data-loader.\n\tif loadData != nil {\n\t\titem := loadData(key)\n\t\tif item != nil {\n\t\t\ttable.Cache(key, item.lifeSpan, item.data)\n\t\t\treturn item, nil\n\t\t}\n\n\t\treturn nil, ErrKeyNotFoundOrLoadable\n\t}\n\n\treturn nil, ErrKeyNotFound\n}\n\n\/\/ Delete all items from cache.\nfunc (table *CacheTable) Flush() {\n\ttable.Lock()\n\tdefer table.Unlock()\n\n\ttable.log(\"Flushing table\", table.name)\n\n\ttable.items = make(map[interface{}]*CacheItem)\n\ttable.cleanupInterval = 0\n\tif table.cleanupTimer != nil {\n\t\ttable.cleanupTimer.Stop()\n\t}\n}\n\n\/\/ Internal logging method for convenience.\nfunc (table *CacheTable) log(v ...interface{}) {\n\tif table.logger == nil {\n\t\treturn\n\t}\n\n\ttable.logger.Println(v)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This package provides all the input fields logic and customization methods.\npackage fields\n\nimport (\n\t\"github.com\/kirves\/go-form-it\/widgets\"\n\t\"html\/template\"\n)\n\n\/\/ Field is a generic type containing all data associated to an input field.\ntype Field struct {\n\tfieldType  string\n\tWidget     widgets.WidgetInterface \/\/ Public Widget field for widget customization\n\tname       string\n\tclass      []string\n\tid         string\n\tparams     map[string]string\n\tcss        map[string]string\n\ttext       string\n\tlabel      string\n\tchoices    map[string][]InputChoice\n\tlabelClass []string\n\ttag        []string\n\tvalue      string\n}\n\n\/\/ FieldInterface defines the interface an object must implement to be used in a form. Every method returns a FieldInterface object\n\/\/ to allow methods chaining.\ntype FieldInterface interface {\n\tName() string\n\tRender() template.HTML\n\tAddClass(class string) FieldInterface\n\tRemoveClass(class string) FieldInterface\n\tAddTag(class string) FieldInterface\n\tRemoveTag(class string) FieldInterface\n\tSetId(id string) FieldInterface\n\tSetParam(key, value string) FieldInterface\n\tDeleteParam(key string) FieldInterface\n\tAddCss(key, value string) FieldInterface\n\tRemoveCss(key string) FieldInterface\n\tSetStyle(style string) FieldInterface\n\tSetText(text string) FieldInterface\n\tSetLabel(label string) FieldInterface\n\tAddLabelClass(class string) FieldInterface\n\tRemoveLabelClass(class string) FieldInterface\n\tSetChoices(choices map[string][]InputChoice) FieldInterface\n\tSetValue(value string) FieldInterface\n\tDisabled() FieldInterface\n\tEnabled() FieldInterface\n}\n\n\/\/ FieldWithType creates an empty field of the given type and identified by name.\nfunc FieldWithType(name, t string) Field {\n\treturn Field{\n\t\tt,\n\t\tnil,\n\t\tname,\n\t\t[]string{},\n\t\t\"\",\n\t\tmap[string]string{},\n\t\tmap[string]string{},\n\t\t\"\",\n\t\t\"\",\n\t\tmap[string][]InputChoice{},\n\t\t[]string{},\n\t\t[]string{},\n\t\t\"\",\n\t}\n}\n\n\/\/ SetStyle sets the style (e.g.: BASE, BOOTSTRAP) of the field, correctly populating the Widget field.\nfunc (f *Field) SetStyle(style string) FieldInterface {\n\tf.Widget = widgets.BaseWidget(style, f.fieldType)\n\treturn f\n}\n\n\/\/ Name returns the name of the field.\nfunc (f *Field) Name() string {\n\treturn f.name\n}\n\n\/\/ Render packs all data and executes widget render method.\nfunc (f *Field) Render() template.HTML {\n\tif f.Widget != nil {\n\t\tdata := map[string]interface{}{\n\t\t\t\"classes\":      f.class,\n\t\t\t\"id\":           f.id,\n\t\t\t\"name\":         f.name,\n\t\t\t\"params\":       f.params,\n\t\t\t\"css\":          f.css,\n\t\t\t\"text\":         f.text,\n\t\t\t\"type\":         f.fieldType,\n\t\t\t\"label\":        f.label,\n\t\t\t\"choices\":      f.choices,\n\t\t\t\"labelClasses\": f.labelClass,\n\t\t\t\"tags\":         f.tag,\n\t\t\t\"value\":        f.value,\n\t\t}\n\t\treturn template.HTML(f.Widget.Render(data))\n\t}\n\treturn template.HTML(\"\")\n}\n\n\/\/ AddClass adds a class to the field.\nfunc (f *Field) AddClass(class string) FieldInterface {\n\tf.class = append(f.class, class)\n\treturn f\n}\n\n\/\/ RemoveClass removes a class from the field, if it was present.\nfunc (f *Field) RemoveClass(class string) FieldInterface {\n\tind := -1\n\tfor i, v := range f.class {\n\t\tif v == class {\n\t\t\tind = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif ind != -1 {\n\t\tf.class = append(f.class[:ind], f.class[ind+1:]...)\n\t}\n\treturn f\n}\n\n\/\/ SetId associates the given id to the field, overwriting any previous id.\nfunc (f *Field) SetId(id string) FieldInterface {\n\tf.id = id\n\treturn f\n}\n\n\/\/ SetText saves the provided text as content of the field, usually a TextAreaField.\nfunc (f *Field) SetText(text string) FieldInterface {\n\tf.text = text\n\treturn f\n}\n\n\/\/ SetLabel saves the label to be rendered along with the field.\nfunc (f *Field) SetLabel(label string) FieldInterface {\n\tf.label = label\n\treturn f\n}\n\n\/\/ SetLablClass allows to define custom classes for the label.\nfunc (f *Field) AddLabelClass(class string) FieldInterface {\n\tf.labelClass = append(f.labelClass, class)\n\treturn f\n}\n\n\/\/ RemoveLabelClass removes the given class from the field label.\nfunc (f *Field) RemoveLabelClass(class string) FieldInterface {\n\tind := -1\n\tfor i, v := range f.labelClass {\n\t\tif v == class {\n\t\t\tind = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif ind != -1 {\n\t\tf.labelClass = append(f.labelClass[:ind], f.labelClass[ind+1:]...)\n\t}\n\treturn f\n}\n\n\/\/ SetChoices takes as input a dictionary whose key-value entries are defined as follows: key is the group name (the empty string\n\/\/ is the default group that is not explicitly rendered) and value is the list of choices belonging to that group.\n\/\/ Grouping is only useful for Select fields, while groups are ignored in Radio fields.\nfunc (f *Field) SetChoices(choices map[string][]InputChoice) FieldInterface {\n\tf.choices = choices\n\treturn f\n}\n\n\/\/ SetParam adds a parameter (defined as key-value pair) in the field.\nfunc (f *Field) SetParam(key, value string) FieldInterface {\n\tf.params[key] = value\n\treturn f\n}\n\n\/\/ DeleteParam removes a parameter identified by key from the field.\nfunc (f *Field) DeleteParam(key string) FieldInterface {\n\tdelete(f.params, key)\n\treturn f\n}\n\n\/\/ AddCss adds a custom CSS style the field.\nfunc (f *Field) AddCss(key, value string) FieldInterface {\n\tf.css[key] = value\n\treturn f\n}\n\n\/\/ RemoveCss removes CSS options identified by key from the field.\nfunc (f *Field) RemoveCss(key string) FieldInterface {\n\tdelete(f.css, key)\n\treturn f\n}\n\n\/\/ Disabled add the \"disabled\" tag to the field, making it unresponsive in some environments (e.g. Bootstrap).\nfunc (f *Field) Disabled() FieldInterface {\n\tf.AddTag(\"disabled\")\n\treturn f\n}\n\n\/\/ Enabled removes the \"disabled\" tag from the field, making it responsive.\nfunc (f *Field) Enabled() FieldInterface {\n\tf.RemoveTag(\"disabled\")\n\treturn f\n}\n\n\/\/ AddTag adds a no-value parameter (e.g.: checked, disabled) to the field.\nfunc (f *Field) AddTag(tag string) FieldInterface {\n\tf.tag = append(f.tag, tag)\n\treturn f\n}\n\n\/\/ RemoveTag removes a no-value parameter from the field.\nfunc (f *Field) RemoveTag(tag string) FieldInterface {\n\tind := -1\n\tfor i, v := range f.tag {\n\t\tif v == tag {\n\t\t\tind = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif ind != -1 {\n\t\tf.tag = append(f.tag[:ind], f.tag[ind+1:]...)\n\t}\n\treturn f\n}\n\n\/\/ SetValue sets the value parameter for the field.\nfunc (f *Field) SetValue(value string) FieldInterface {\n\tf.value = value\n\treturn f\n}\n<commit_msg>Added helptext and errors support<commit_after>\/\/ This package provides all the input fields logic and customization methods.\npackage fields\n\nimport (\n\t\"github.com\/kirves\/go-form-it\/widgets\"\n\t\"html\/template\"\n)\n\n\/\/ Field is a generic type containing all data associated to an input field.\ntype Field struct {\n\tfieldType  string\n\tWidget     widgets.WidgetInterface \/\/ Public Widget field for widget customization\n\tname       string\n\tclass      []string\n\tid         string\n\tparams     map[string]string\n\tcss        map[string]string\n\ttext       string\n\tlabel      string\n\tchoices    map[string][]InputChoice\n\tlabelClass []string\n\ttag        []string\n\tvalue      string\n\thelptext   string\n\terrors     []string\n}\n\n\/\/ FieldInterface defines the interface an object must implement to be used in a form. Every method returns a FieldInterface object\n\/\/ to allow methods chaining.\ntype FieldInterface interface {\n\tName() string\n\tRender() template.HTML\n\tAddClass(class string) FieldInterface\n\tRemoveClass(class string) FieldInterface\n\tAddTag(class string) FieldInterface\n\tRemoveTag(class string) FieldInterface\n\tSetId(id string) FieldInterface\n\tSetParam(key, value string) FieldInterface\n\tDeleteParam(key string) FieldInterface\n\tAddCss(key, value string) FieldInterface\n\tRemoveCss(key string) FieldInterface\n\tSetStyle(style string) FieldInterface\n\tSetText(text string) FieldInterface\n\tSetLabel(label string) FieldInterface\n\tAddLabelClass(class string) FieldInterface\n\tRemoveLabelClass(class string) FieldInterface\n\tSetChoices(choices map[string][]InputChoice) FieldInterface\n\tSetValue(value string) FieldInterface\n\tDisabled() FieldInterface\n\tEnabled() FieldInterface\n\tSetHelptext(text string) FieldInterface\n\tAddError(err string) FieldInterface\n}\n\n\/\/ FieldWithType creates an empty field of the given type and identified by name.\nfunc FieldWithType(name, t string) Field {\n\treturn Field{\n\t\tt,\n\t\tnil,\n\t\tname,\n\t\t[]string{},\n\t\t\"\",\n\t\tmap[string]string{},\n\t\tmap[string]string{},\n\t\t\"\",\n\t\t\"\",\n\t\tmap[string][]InputChoice{},\n\t\t[]string{},\n\t\t[]string{},\n\t\t\"\",\n\t\t\"\",\n\t\t[]string{},\n\t}\n}\n\n\/\/ SetStyle sets the style (e.g.: BASE, BOOTSTRAP) of the field, correctly populating the Widget field.\nfunc (f *Field) SetStyle(style string) FieldInterface {\n\tf.Widget = widgets.BaseWidget(style, f.fieldType)\n\treturn f\n}\n\n\/\/ Name returns the name of the field.\nfunc (f *Field) Name() string {\n\treturn f.name\n}\n\n\/\/ Render packs all data and executes widget render method.\nfunc (f *Field) Render() template.HTML {\n\tif f.Widget != nil {\n\t\tdata := map[string]interface{}{\n\t\t\t\"classes\":      f.class,\n\t\t\t\"id\":           f.id,\n\t\t\t\"name\":         f.name,\n\t\t\t\"params\":       f.params,\n\t\t\t\"css\":          f.css,\n\t\t\t\"text\":         f.text,\n\t\t\t\"type\":         f.fieldType,\n\t\t\t\"label\":        f.label,\n\t\t\t\"choices\":      f.choices,\n\t\t\t\"labelClasses\": f.labelClass,\n\t\t\t\"tags\":         f.tag,\n\t\t\t\"value\":        f.value,\n\t\t\t\"helptext\":     f.helptext,\n\t\t\t\"errors\":       f.errors,\n\t\t}\n\t\treturn template.HTML(f.Widget.Render(data))\n\t}\n\treturn template.HTML(\"\")\n}\n\n\/\/ AddClass adds a class to the field.\nfunc (f *Field) AddClass(class string) FieldInterface {\n\tf.class = append(f.class, class)\n\treturn f\n}\n\n\/\/ RemoveClass removes a class from the field, if it was present.\nfunc (f *Field) RemoveClass(class string) FieldInterface {\n\tind := -1\n\tfor i, v := range f.class {\n\t\tif v == class {\n\t\t\tind = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif ind != -1 {\n\t\tf.class = append(f.class[:ind], f.class[ind+1:]...)\n\t}\n\treturn f\n}\n\n\/\/ SetId associates the given id to the field, overwriting any previous id.\nfunc (f *Field) SetId(id string) FieldInterface {\n\tf.id = id\n\treturn f\n}\n\n\/\/ SetText saves the provided text as content of the field, usually a TextAreaField.\nfunc (f *Field) SetText(text string) FieldInterface {\n\tf.text = text\n\treturn f\n}\n\n\/\/ SetLabel saves the label to be rendered along with the field.\nfunc (f *Field) SetLabel(label string) FieldInterface {\n\tf.label = label\n\treturn f\n}\n\n\/\/ SetLablClass allows to define custom classes for the label.\nfunc (f *Field) AddLabelClass(class string) FieldInterface {\n\tf.labelClass = append(f.labelClass, class)\n\treturn f\n}\n\n\/\/ RemoveLabelClass removes the given class from the field label.\nfunc (f *Field) RemoveLabelClass(class string) FieldInterface {\n\tind := -1\n\tfor i, v := range f.labelClass {\n\t\tif v == class {\n\t\t\tind = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif ind != -1 {\n\t\tf.labelClass = append(f.labelClass[:ind], f.labelClass[ind+1:]...)\n\t}\n\treturn f\n}\n\n\/\/ SetChoices takes as input a dictionary whose key-value entries are defined as follows: key is the group name (the empty string\n\/\/ is the default group that is not explicitly rendered) and value is the list of choices belonging to that group.\n\/\/ Grouping is only useful for Select fields, while groups are ignored in Radio fields.\nfunc (f *Field) SetChoices(choices map[string][]InputChoice) FieldInterface {\n\tf.choices = choices\n\treturn f\n}\n\n\/\/ SetParam adds a parameter (defined as key-value pair) in the field.\nfunc (f *Field) SetParam(key, value string) FieldInterface {\n\tf.params[key] = value\n\treturn f\n}\n\n\/\/ DeleteParam removes a parameter identified by key from the field.\nfunc (f *Field) DeleteParam(key string) FieldInterface {\n\tdelete(f.params, key)\n\treturn f\n}\n\n\/\/ AddCss adds a custom CSS style the field.\nfunc (f *Field) AddCss(key, value string) FieldInterface {\n\tf.css[key] = value\n\treturn f\n}\n\n\/\/ RemoveCss removes CSS options identified by key from the field.\nfunc (f *Field) RemoveCss(key string) FieldInterface {\n\tdelete(f.css, key)\n\treturn f\n}\n\n\/\/ Disabled add the \"disabled\" tag to the field, making it unresponsive in some environments (e.g. Bootstrap).\nfunc (f *Field) Disabled() FieldInterface {\n\tf.AddTag(\"disabled\")\n\treturn f\n}\n\n\/\/ Enabled removes the \"disabled\" tag from the field, making it responsive.\nfunc (f *Field) Enabled() FieldInterface {\n\tf.RemoveTag(\"disabled\")\n\treturn f\n}\n\n\/\/ AddTag adds a no-value parameter (e.g.: checked, disabled) to the field.\nfunc (f *Field) AddTag(tag string) FieldInterface {\n\tf.tag = append(f.tag, tag)\n\treturn f\n}\n\n\/\/ RemoveTag removes a no-value parameter from the field.\nfunc (f *Field) RemoveTag(tag string) FieldInterface {\n\tind := -1\n\tfor i, v := range f.tag {\n\t\tif v == tag {\n\t\t\tind = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif ind != -1 {\n\t\tf.tag = append(f.tag[:ind], f.tag[ind+1:]...)\n\t}\n\treturn f\n}\n\n\/\/ SetValue sets the value parameter for the field.\nfunc (f *Field) SetValue(value string) FieldInterface {\n\tf.value = value\n\treturn f\n}\n\n\/\/ SetHelptext saves the field helptext.\nfunc (f *Field) SetHelptext(text string) FieldInterface {\n\tf.helptext = text\n\treturn f\n}\n\n\/\/ AddError adds an error string to the field. It's valid only for Bootstrap forms.\nfunc (f *Field) AddError(err string) FieldInterface {\n\tf.errors = append(f.errors, err)\n\treturn f\n}\n<|endoftext|>"}
{"text":"<commit_before>package jobsupervisor\n\nimport (\n\tboshalert \"bosh\/agent\/alert\"\n)\n\ntype JobFailureHandler func(boshalert.MonitAlert) error\n\ntype JobSupervisor interface {\n\tReload() error\n\n\t\/\/ Actions taken on all services\n\tStart() error\n\tStop() error\n\tUnmonitor() error\n\n\tStatus() string\n\n\tAddJob(jobName string, jobIndex int, configPath string) error\n\n\tMonitorJobFailures(handler JobFailureHandler) error\n}\n<commit_msg>note that Start\/Stop command should still work after Unmonitor command is executed<commit_after>package jobsupervisor\n\nimport (\n\tboshalert \"bosh\/agent\/alert\"\n)\n\ntype JobFailureHandler func(boshalert.MonitAlert) error\n\ntype JobSupervisor interface {\n\tReload() error\n\n\t\/\/ Actions taken on all services\n\tStart() error\n\tStop() error\n\n\t\/\/ Start and Stop should still function after Unmonitor.\n\t\/\/ Calling Start after Unmonitor should re-monitor all jobs.\n\t\/\/ Calling Stop after Unmonitor should not re-monitor all jobs.\n\t\/\/ (Monit complies to above requirements.)\n\tUnmonitor() error\n\n\tStatus() string\n\n\tAddJob(jobName string, jobIndex int, configPath string) error\n\n\tMonitorJobFailures(handler JobFailureHandler) error\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ POST \/stream\/<name> or PUT \/stream\/<name>\n\/\/     Broadcast a WebM video\/audio file.\n\/\/\n\/\/     Accepted input: valid WebM split into arbitrarily many requests in absolutely\n\/\/     any way. Multiple files can be concatenated into a single stream as long as they\n\/\/     contain exactly the same tracks (i.e. their number, codecs, and dimensions.\n\/\/     Otherwise any connected decoders will error and have to restart. Changing,\n\/\/     for example, bitrate or tags is fine.)\n\/\/\n\/\/ GET \/stream\/<name>\n\/\/     Receive a published WebM stream. Note that the server makes no attempt\n\/\/     at buffering; if the stream is being broadcast faster than its native framerate,\n\/\/     the client will have to buffer and\/or drop frames.\n\/\/\n\/\/ GET \/stream\/<name> [Upgrade: websocket]\n\/\/     Connect to a JSON-RPC v2.0 node.\n\/\/\n\/\/     Methods of `Chat`:\n\/\/\n\/\/        * `SetName(string)`: assign a (unique) name to this client. This is required to...\n\/\/        * `SendMessage(string)`: broadcast a simple text message to all viewers.\n\/\/        * `RequestHistory()`: ask the server to emit notifications containing the last\n\/\/          few broadcasted text messages.\n\/\/\n\/\/     TODO Methods of `Stream`.\n\/\/\n\/\/     Notifications:\n\/\/\n\/\/        * `Chat.AcquiredName(user string)`: upon a successful `SetName`.\n\/\/          May be emitted automatically at the start of a connection if already logged in.\n\/\/        * `Chat.Message(user string, text string)`: a broadcasted text message.\n\/\/\npackage main\n\nimport (\n\t\"golang.org\/x\/net\/websocket\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype RetransmissionHandler struct {\n\tBroadcastSet\n\tchatLock sync.Mutex\n\tchats    map[string]*Chat\n\t*Context\n}\n\nfunc NewRetransmissionHandler(c *Context) *RetransmissionHandler {\n\tctx := &RetransmissionHandler{chats: make(map[string]*Chat), Context: c}\n\tctx.Timeout = c.StreamKeepAlive\n\tctx.OnStreamClose = func(id string) {\n\t\tctx.chatLock.Lock()\n\t\tif chat, ok := ctx.chats[id]; ok {\n\t\t\tchat.Close()\n\t\t\tdelete(ctx.chats, id)\n\t\t}\n\t\tctx.chatLock.Unlock()\n\t\tif err := ctx.StopStream(id); err != nil {\n\t\t\tlog.Println(\"Error stopping the stream: \", err)\n\t\t}\n\t}\n\tctx.OnStreamTrackInfo = func(id string, info *StreamTrackInfo) {\n\t\tif err := ctx.SetStreamTrackInfo(id, info); err != nil {\n\t\t\tlog.Println(\"Error setting stream metadata: \", err)\n\t\t}\n\t}\n\treturn ctx\n}\n\nfunc (ctx *RetransmissionHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) error {\n\tswitch {\n\tcase r.URL.Path == \"\/stream\/\" || strings.ContainsRune(r.URL.Path[8:], '\/'):\n\t\treturn RenderError(w, http.StatusNotFound, \"\")\n\tcase r.Method == \"GET\":\n\t\treturn ctx.watch(w, r, r.URL.Path[8:])\n\tcase r.Method == \"POST\" || r.Method == \"PUT\":\n\t\treturn ctx.stream(w, r, r.URL.Path[8:])\n\tdefault:\n\t\treturn RenderInvalidMethod(w, \"GET, PUT, POST\")\n\t}\n}\n\nfunc wantsWebsocket(r *http.Request) bool {\n\tif upgrade, ok := r.Header[\"Upgrade\"]; ok {\n\t\tfor i := range upgrade {\n\t\t\tif strings.ToLower(upgrade[i]) == \"websocket\" {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (ctx *RetransmissionHandler) watch(w http.ResponseWriter, r *http.Request, id string) error {\n\tstream, ok := ctx.Readable(id)\n\tif !ok {\n\t\tswitch server, err := ctx.GetStreamServer(id); err {\n\t\tcase ErrStreamNotHere:\n\t\t\tif wantsWebsocket(r) {\n\t\t\t\t\/\/ simply redirecting won't do -- browsers will throw an error.\n\t\t\t\twebsocket.Handler(func(ws *websocket.Conn) {\n\t\t\t\t\tRPCPushEvent(ws, \"RPC.Redirect\", \"\/\/\"+server+r.URL.Path)\n\t\t\t\t}).ServeHTTP(w, r)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\thttp.Redirect(w, r, \"\/\/\"+server+r.URL.Path, http.StatusTemporaryRedirect)\n\t\t\treturn nil\n\t\tcase ErrStreamOffline, nil:\n\t\t\treturn RenderError(w, http.StatusNotFound, \"Stream offline.\")\n\t\tcase ErrStreamNotExist:\n\t\t\treturn RenderError(w, http.StatusNotFound, \"Invalid stream name.\")\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif wantsWebsocket(r) {\n\t\tauth, err := ctx.GetAuthInfo(r)\n\t\tif err != nil && err != ErrUserNotExist {\n\t\t\treturn err\n\t\t}\n\t\twebsocket.Handler(func(ws *websocket.Conn) {\n\t\t\tctx.chatLock.Lock()\n\t\t\tchat, ok := ctx.chats[id]\n\t\t\tif !ok {\n\t\t\t\tchat = NewChat(20)\n\t\t\t\tctx.chats[id] = chat\n\t\t\t}\n\t\t\tctx.chatLock.Unlock()\n\t\t\tchat.RunRPC(ws, auth)\n\t\t}).ServeHTTP(w, r)\n\t\treturn nil\n\t}\n\n\theader := w.Header()\n\theader.Set(\"Access-Control-Allow-Origin\", \"*\")\n\theader.Set(\"Cache-Control\", \"no-cache\")\n\theader.Set(\"Content-Type\", \"video\/webm\")\n\tw.WriteHeader(http.StatusOK)\n\n\tch := make(chan []byte, 60)\n\tdefer close(ch)\n\n\tstream.Connect(ch, false)\n\tdefer stream.Disconnect(ch)\n\n\tfor chunk := range ch {\n\t\tif _, err := w.Write(chunk); err != nil || stream.Closed {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (ctx *RetransmissionHandler) stream(w http.ResponseWriter, r *http.Request, id string) error {\n\tswitch err := ctx.StartStream(id, r.URL.RawQuery); err {\n\tcase ErrInvalidToken:\n\t\treturn RenderError(w, http.StatusForbidden, \"Invalid token.\")\n\tcase ErrStreamNotExist:\n\t\treturn RenderError(w, http.StatusNotFound, \"Invalid stream ID.\")\n\tcase ErrStreamNotHere:\n\t\treturn RenderError(w, http.StatusBadRequest, \"Wrong server.\")\n\tdefault:\n\t\treturn err\n\tcase nil:\n\t}\n\n\tstream, ok := ctx.Writable(id)\n\tif !ok {\n\t\treturn RenderError(w, http.StatusForbidden, \"Stream ID already taken.\")\n\t}\n\tdefer stream.Close()\n\n\tbuffer := [16384]byte{}\n\tfor {\n\t\tn, err := r.Body.Read(buffer[:])\n\t\tif n != 0 {\n\t\t\tif _, err := stream.Write(buffer[:n]); err != nil {\n\t\t\t\tstream.Reset()\n\t\t\t\treturn RenderError(w, http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusNoContent)\n\t\t\treturn nil\n\t\t}\n\t}\n}\n<commit_msg>Display an error when trying to follow the \"publish\" link.<commit_after>\/\/ POST \/stream\/<name> or PUT \/stream\/<name>\n\/\/     Broadcast a WebM video\/audio file.\n\/\/\n\/\/     Accepted input: valid WebM split into arbitrarily many requests in absolutely\n\/\/     any way. Multiple files can be concatenated into a single stream as long as they\n\/\/     contain exactly the same tracks (i.e. their number, codecs, and dimensions.\n\/\/     Otherwise any connected decoders will error and have to restart. Changing,\n\/\/     for example, bitrate or tags is fine.)\n\/\/\n\/\/ GET \/stream\/<name>\n\/\/     Receive a published WebM stream. Note that the server makes no attempt\n\/\/     at buffering; if the stream is being broadcast faster than its native framerate,\n\/\/     the client will have to buffer and\/or drop frames.\n\/\/\n\/\/ GET \/stream\/<name> [Upgrade: websocket]\n\/\/     Connect to a JSON-RPC v2.0 node.\n\/\/\n\/\/     Methods of `Chat`:\n\/\/\n\/\/        * `SetName(string)`: assign a (unique) name to this client. This is required to...\n\/\/        * `SendMessage(string)`: broadcast a simple text message to all viewers.\n\/\/        * `RequestHistory()`: ask the server to emit notifications containing the last\n\/\/          few broadcasted text messages.\n\/\/\n\/\/     TODO Methods of `Stream`.\n\/\/\n\/\/     Notifications:\n\/\/\n\/\/        * `Chat.AcquiredName(user string)`: upon a successful `SetName`.\n\/\/          May be emitted automatically at the start of a connection if already logged in.\n\/\/        * `Chat.Message(user string, text string)`: a broadcasted text message.\n\/\/\npackage main\n\nimport (\n\t\"golang.org\/x\/net\/websocket\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype RetransmissionHandler struct {\n\tBroadcastSet\n\tchatLock sync.Mutex\n\tchats    map[string]*Chat\n\t*Context\n}\n\nfunc NewRetransmissionHandler(c *Context) *RetransmissionHandler {\n\tctx := &RetransmissionHandler{chats: make(map[string]*Chat), Context: c}\n\tctx.Timeout = c.StreamKeepAlive\n\tctx.OnStreamClose = func(id string) {\n\t\tctx.chatLock.Lock()\n\t\tif chat, ok := ctx.chats[id]; ok {\n\t\t\tchat.Close()\n\t\t\tdelete(ctx.chats, id)\n\t\t}\n\t\tctx.chatLock.Unlock()\n\t\tif err := ctx.StopStream(id); err != nil {\n\t\t\tlog.Println(\"Error stopping the stream: \", err)\n\t\t}\n\t}\n\tctx.OnStreamTrackInfo = func(id string, info *StreamTrackInfo) {\n\t\tif err := ctx.SetStreamTrackInfo(id, info); err != nil {\n\t\t\tlog.Println(\"Error setting stream metadata: \", err)\n\t\t}\n\t}\n\treturn ctx\n}\n\nfunc (ctx *RetransmissionHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) error {\n\tswitch {\n\tcase r.URL.Path == \"\/stream\/\" || strings.ContainsRune(r.URL.Path[8:], '\/'):\n\t\treturn RenderError(w, http.StatusNotFound, \"\")\n\tcase r.Method == \"GET\":\n\t\treturn ctx.watch(w, r, r.URL.Path[8:])\n\tcase r.Method == \"POST\" || r.Method == \"PUT\":\n\t\treturn ctx.stream(w, r, r.URL.Path[8:])\n\tdefault:\n\t\treturn RenderInvalidMethod(w, \"GET, PUT, POST\")\n\t}\n}\n\nfunc wantsWebsocket(r *http.Request) bool {\n\tif upgrade, ok := r.Header[\"Upgrade\"]; ok {\n\t\tfor i := range upgrade {\n\t\t\tif strings.ToLower(upgrade[i]) == \"websocket\" {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (ctx *RetransmissionHandler) watch(w http.ResponseWriter, r *http.Request, id string) error {\n\tif r.URL.RawQuery != \"\" {\n\t\treturn RenderError(w, http.StatusBadRequest, \"Send WebMs here, watch using the other links.\")\n\t}\n\n\tstream, ok := ctx.Readable(id)\n\tif !ok {\n\t\tswitch server, err := ctx.GetStreamServer(id); err {\n\t\tcase ErrStreamNotHere:\n\t\t\tif wantsWebsocket(r) {\n\t\t\t\t\/\/ simply redirecting won't do -- browsers will throw an error.\n\t\t\t\twebsocket.Handler(func(ws *websocket.Conn) {\n\t\t\t\t\tRPCPushEvent(ws, \"RPC.Redirect\", \"\/\/\"+server+r.URL.Path)\n\t\t\t\t}).ServeHTTP(w, r)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\thttp.Redirect(w, r, \"\/\/\"+server+r.URL.Path, http.StatusTemporaryRedirect)\n\t\t\treturn nil\n\t\tcase ErrStreamOffline, nil:\n\t\t\treturn RenderError(w, http.StatusNotFound, \"Stream offline.\")\n\t\tcase ErrStreamNotExist:\n\t\t\treturn RenderError(w, http.StatusNotFound, \"Invalid stream name.\")\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif wantsWebsocket(r) {\n\t\tauth, err := ctx.GetAuthInfo(r)\n\t\tif err != nil && err != ErrUserNotExist {\n\t\t\treturn err\n\t\t}\n\t\twebsocket.Handler(func(ws *websocket.Conn) {\n\t\t\tctx.chatLock.Lock()\n\t\t\tchat, ok := ctx.chats[id]\n\t\t\tif !ok {\n\t\t\t\tchat = NewChat(20)\n\t\t\t\tctx.chats[id] = chat\n\t\t\t}\n\t\t\tctx.chatLock.Unlock()\n\t\t\tchat.RunRPC(ws, auth)\n\t\t}).ServeHTTP(w, r)\n\t\treturn nil\n\t}\n\n\theader := w.Header()\n\theader.Set(\"Access-Control-Allow-Origin\", \"*\")\n\theader.Set(\"Cache-Control\", \"no-cache\")\n\theader.Set(\"Content-Type\", \"video\/webm\")\n\tw.WriteHeader(http.StatusOK)\n\n\tch := make(chan []byte, 60)\n\tdefer close(ch)\n\n\tstream.Connect(ch, false)\n\tdefer stream.Disconnect(ch)\n\n\tfor chunk := range ch {\n\t\tif _, err := w.Write(chunk); err != nil || stream.Closed {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (ctx *RetransmissionHandler) stream(w http.ResponseWriter, r *http.Request, id string) error {\n\tswitch err := ctx.StartStream(id, r.URL.RawQuery); err {\n\tcase ErrInvalidToken:\n\t\treturn RenderError(w, http.StatusForbidden, \"Invalid token.\")\n\tcase ErrStreamNotExist:\n\t\treturn RenderError(w, http.StatusNotFound, \"Invalid stream ID.\")\n\tcase ErrStreamNotHere:\n\t\treturn RenderError(w, http.StatusBadRequest, \"Wrong server.\")\n\tdefault:\n\t\treturn err\n\tcase nil:\n\t}\n\n\tstream, ok := ctx.Writable(id)\n\tif !ok {\n\t\treturn RenderError(w, http.StatusForbidden, \"Stream ID already taken.\")\n\t}\n\tdefer stream.Close()\n\n\tbuffer := [16384]byte{}\n\tfor {\n\t\tn, err := r.Body.Read(buffer[:])\n\t\tif n != 0 {\n\t\t\tif _, err := stream.Write(buffer[:n]); err != nil {\n\t\t\t\tstream.Reset()\n\t\t\t\treturn RenderError(w, http.StatusBadRequest, err.Error())\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusNoContent)\n\t\t\treturn nil\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>fix package name<commit_after><|endoftext|>"}
{"text":"<commit_before>package wikidump\n\nimport (\n\t\"bytes\"\n\t\"golang.org\/x\/text\/unicode\/norm\"\n\t\"html\"\n\t\"regexp\"\n\t\"strings\"\n\t\"unicode\"\n\t\"unicode\/utf8\"\n)\n\nvar (\n\tspecial  = regexp.MustCompile(`{{|{\\||\\|}|}}|<[a-z][a-z0-9 \"=]*\/?>|<\/[a-z]+>`)\n\tstarttag = regexp.MustCompile(`<[a-z].*>`)\n\tendtag   = regexp.MustCompile(`<\/[a-z]+>`)\n)\n\n\/\/ Get rid of tables, template calls, quasi-XML. Throws away their content.\n\/\/\n\/\/ Assumes tables, templates and tags are properly nested, except for spurious\n\/\/ end-of-{table,template,element} tags, which are ignored.\nfunc Cleanup(s string) string {\n\tvar depth int\n\toutput := bytes.NewBuffer(make([]byte, 0, len(s)))\n\n\tfor {\n\t\tnext := special.FindStringIndex(s)\n\t\tif next == nil {\n\t\t\tif depth == 0 {\n\t\t\t\toutput.WriteString(s)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\ti, j := next[0], next[1]\n\n\t\tif depth == 0 {\n\t\t\toutput.WriteString(s[:i])\n\t\t}\n\n\t\ttag := s[i:j]\n\t\tswitch {\n\t\tcase tag == \"{{\":\n\t\t\tdepth++\n\t\tcase tag == \"{|\":\n\t\t\tdepth++\n\t\tcase starttag.MatchString(tag):\n\t\t\tdepth++\n\t\tcase tag == \"}}\":\n\t\t\tfallthrough\n\t\tcase tag == \"|}\":\n\t\t\tfallthrough\n\t\tcase endtag.MatchString(tag):\n\t\t\tif depth > 0 {\n\t\t\t\tdepth--\n\t\t\t}\n\t\t}\n\n\t\ts = s[j:]\n\t}\n\treturn norm.NFC.String(html.UnescapeString(output.String()))\n}\n\ntype Link struct {\n\tAnchor, Target string\n}\n\nvar (\n\tlinkRE     = regexp.MustCompile(`(\\w*)\\[\\[([^]]+)\\]\\](\\w*)`)\n\twhitespace = regexp.MustCompile(`[\\s_]+`)\n)\n\nfunc normSpace(s string) string {\n\ts = whitespace.ReplaceAllString(s, \" \")\n\treturn strings.TrimSpace(s)\n}\n\n\/\/ Extract all the wikilinks from s. Returns a frequency table.\nfunc ExtractLinks(s string) map[Link]int {\n\tfreq := make(map[Link]int)\n\n\tfor _, candidate := range linkRE.FindAllStringSubmatch(s, -1) {\n\t\tbefore, l, after := candidate[1], candidate[2], candidate[3]\n\n\t\tvar target, anchor string\n\t\tif pipe := strings.IndexByte(l, '|'); pipe != -1 {\n\t\t\ttarget, anchor = l[:pipe], l[pipe+1:]\n\t\t} else {\n\t\t\ttarget = l\n\t\t\tanchor = l\n\t\t}\n\n\t\t\/\/ If the anchor contains a colon, assume it's a file or category link.\n\t\t\/\/ XXX Maybe skip matches for `:\\s`? Proper solution would parse the\n\t\t\/\/ dump to find non-main namespace prefixes.\n\t\tif strings.IndexByte(target, ':') != -1 {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Remove section links.\n\t\tif hash := strings.IndexByte(target, '#'); hash == 0 {\n\t\t\tcontinue\n\t\t} else if hash != -1 {\n\t\t\ttarget = target[:hash]\n\t\t}\n\n\t\t\/\/ Normalize to the format used in <redirect> elements:\n\t\t\/\/ uppercase first character, spaces instead of underscores.\n\t\ttarget = normSpace(target)\n\t\tfirst, size := utf8.DecodeRuneInString(target)\n\t\t\/\/ XXX Upper case or title case? Should look up the difference...\n\t\tif !unicode.IsUpper(first) {\n\t\t\ttarget = string(unicode.ToUpper(first)) + target[size:]\n\t\t}\n\n\t\tanchor = before + anchor + after\n\t\tfreq[Link{anchor, target}]++\n\t}\n\treturn freq\n}\n<commit_msg>tiny micro-optimizations<commit_after>package wikidump\n\nimport (\n\t\"bytes\"\n\t\"golang.org\/x\/text\/unicode\/norm\"\n\t\"html\"\n\t\"regexp\"\n\t\"strings\"\n\t\"unicode\"\n\t\"unicode\/utf8\"\n)\n\nvar (\n\tspecial  = regexp.MustCompile(`{{|{\\||\\|}|}}|<[a-z][a-z0-9 \"=]*\/?>|<\/[a-z]+>`)\n\tstarttag = regexp.MustCompile(`<[a-z].*>`)\n\tendtag   = regexp.MustCompile(`<\/[a-z]+>`)\n)\n\n\/\/ Get rid of tables, template calls, quasi-XML. Throws away their content.\n\/\/\n\/\/ Assumes tables, templates and tags are properly nested, except for spurious\n\/\/ end-of-{table,template,element} tags, which are ignored.\nfunc Cleanup(s string) string {\n\tvar depth int\n\toutput := bytes.NewBuffer(make([]byte, 0, len(s)))\n\n\tfor {\n\t\tnext := special.FindStringIndex(s)\n\t\tif next == nil {\n\t\t\tif depth == 0 {\n\t\t\t\toutput.WriteString(s)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\ti, j := next[0], next[1]\n\n\t\tif depth == 0 {\n\t\t\toutput.WriteString(s[:i])\n\t\t}\n\n\t\ttag := s[i:j]\n\t\tswitch {\n\t\tcase tag == \"{{\":\n\t\t\tdepth++\n\t\tcase tag == \"{|\":\n\t\t\tdepth++\n\t\tcase starttag.MatchString(tag):\n\t\t\tdepth++\n\t\tcase tag == \"}}\":\n\t\t\tfallthrough\n\t\tcase tag == \"|}\":\n\t\t\tfallthrough\n\t\tcase endtag.MatchString(tag):\n\t\t\tif depth > 0 {\n\t\t\t\tdepth--\n\t\t\t}\n\t\t}\n\n\t\ts = s[j:]\n\t}\n\treturn norm.NFC.String(html.UnescapeString(output.String()))\n}\n\ntype Link struct {\n\tAnchor, Target string\n}\n\nvar (\n\tlinkRE     = regexp.MustCompile(`(\\w*)\\[\\[([^]]+)\\]\\](\\w*)`)\n\twhitespace = regexp.MustCompile(`[\\s_]+`)\n)\n\nfunc normSpace(s string) string {\n\ts = whitespace.ReplaceAllLiteralString(s, \" \")\n\treturn strings.TrimSpace(s)\n}\n\n\/\/ Extract all the wikilinks from s. Returns a frequency table.\nfunc ExtractLinks(s string) map[Link]int {\n\tfreq := make(map[Link]int)\n\n\tfor _, candidate := range linkRE.FindAllStringSubmatch(s, -1) {\n\t\tbefore, l, after := candidate[1], candidate[2], candidate[3]\n\n\t\tvar target, anchor string\n\t\tif pipe := strings.IndexByte(l, '|'); pipe != -1 {\n\t\t\ttarget, anchor = l[:pipe], l[pipe+1:]\n\t\t} else {\n\t\t\ttarget = l\n\t\t\tanchor = l\n\t\t}\n\n\t\t\/\/ If the anchor contains a colon, assume it's a file or category link.\n\t\t\/\/ XXX Maybe skip matches for `:\\s`? Proper solution would parse the\n\t\t\/\/ dump to find non-main namespace prefixes.\n\t\tif strings.IndexByte(target, ':') != -1 {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Remove section links.\n\t\tif hash := strings.IndexByte(target, '#'); hash == 0 {\n\t\t\tcontinue\n\t\t} else if hash != -1 {\n\t\t\ttarget = target[:hash]\n\t\t}\n\n\t\t\/\/ Normalize to the format used in <redirect> elements:\n\t\t\/\/ uppercase first character, spaces instead of underscores.\n\t\ttarget = normSpace(target)\n\t\tfirst, size := utf8.DecodeRuneInString(target)\n\t\t\/\/ XXX Upper case or title case? Should look up the difference...\n\t\tif unicode.IsLower(first) {\n\t\t\ttarget = string(unicode.ToUpper(first)) + target[size:]\n\t\t}\n\n\t\tanchor = before + anchor + after\n\t\tfreq[Link{anchor, target}]++\n\t}\n\treturn freq\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage lease\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"sync\"\n)\n\n\/\/ Create a ReadLease that never expires, unless voluntarily revoked or\n\/\/ upgraded.\n\/\/\n\/\/ The supplied function will be used to obtain the read lease contents, the\n\/\/ first time and whenever the supplied file leaser decides to expire the\n\/\/ temporary copy thus obtained. It must return the same contents every time,\n\/\/ and the contents must be of the given size.\n\/\/\n\/\/ This magic is not preserved after the lease is upgraded.\nfunc NewAutoRefreshingReadLease(\n\tfl FileLeaser,\n\tsize int64,\n\tf func() (io.ReadCloser, error)) (rl ReadLease) {\n\trl = &autoRefreshingReadLease{\n\t\tleaser: fl,\n\t\tsize:   size,\n\t\tf:      f,\n\t}\n\n\treturn\n}\n\ntype autoRefreshingReadLease struct {\n\tmu sync.Mutex\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Constant data\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tsize int64\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Dependencies\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tleaser FileLeaser\n\tf      func() (io.ReadCloser, error)\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Mutable state\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ The current wrapped lease, or nil if one has never been issued.\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\twrapped ReadLease\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Attempt to clean up after the supplied read\/write lease.\nfunc destroyReadWriteLease(rwl ReadWriteLease) {\n\tvar err error\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error destroying read\/write lease: %v\", err)\n\t\t}\n\t}()\n\n\t\/\/ Downgrade to a read lease.\n\trl, err := rwl.Downgrade()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Downgrade: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Revoke the read lease.\n\trl.Revoke()\n}\n\n\/\/ Set up a read\/write lease and fill in our contents.\n\/\/\n\/\/ REQUIRES: The caller has observed that rl.lease has expired.\n\/\/\n\/\/ LOCKS_REQUIRED(rl.mu)\nfunc (rl *autoRefreshingReadLease) getContents() (\n\trwl ReadWriteLease, err error) {\n\t\/\/ Obtain some space to write the contents.\n\trwl, err = rl.leaser.NewFile()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"NewFile: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Attempt to clean up if we exit early.\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tdestroyReadWriteLease(rwl)\n\t\t}\n\t}()\n\n\t\/\/ Obtain the reader for our contents.\n\trc, err := rl.f()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"User function: %v\", err)\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\tcloseErr := rc.Close()\n\t\tif closeErr != nil && err == nil {\n\t\t\terr = fmt.Errorf(\"Close: %v\", closeErr)\n\t\t}\n\t}()\n\n\t\/\/ Copy into the read\/write lease.\n\tcopied, err := io.Copy(rwl, rc)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Copy: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Did the user lie about the size?\n\tif copied != rl.Size() {\n\t\terr = fmt.Errorf(\"Copied %v bytes; expected %v\", copied, rl.Size())\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ Downgrade and save the supplied read\/write lease obtained with getContents\n\/\/ for later use.\n\/\/\n\/\/ LOCKS_REQUIRED(rl.mu)\nfunc (rl *autoRefreshingReadLease) saveContents(rwl ReadWriteLease) {\n\tdowngraded, err := rwl.Downgrade()\n\tif err != nil {\n\t\tlog.Printf(\"Failed to downgrade write lease (%q); abandoning.\", err.Error())\n\t\treturn\n\t}\n\n\trl.wrapped = downgraded\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Public interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (rl *autoRefreshingReadLease) Read(p []byte) (n int, err error) {\n\trl.mu.Lock()\n\tdefer rl.mu.Unlock()\n\n\t\/\/ Common case: is the existing lease still valid?\n\tif rl.wrapped != nil {\n\t\tpanic(\"TODO\")\n\t}\n\n\t\/\/ Get hold of a read\/write lease containing our contents.\n\trwl, err := rl.getContents()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"getContents: %v\", err)\n\t\treturn\n\t}\n\n\tdefer rl.saveContents(rwl)\n\n\t\/\/ Serve from the read\/write lease.\n\tn, err = rwl.Read(p)\n\n\treturn\n}\n\nfunc (rl *autoRefreshingReadLease) Seek(\n\toffset int64,\n\twhence int) (off int64, err error) {\n\tpanic(\"TODO\")\n}\n\nfunc (rl *autoRefreshingReadLease) ReadAt(p []byte, off int64) (n int, err error) {\n\tpanic(\"TODO\")\n}\n\nfunc (rl *autoRefreshingReadLease) Size() (size int64) {\n\tsize = rl.size\n\treturn\n}\n\nfunc (rl *autoRefreshingReadLease) Revoked() (revoked bool) {\n\tpanic(\"TODO\")\n}\n\nfunc (rl *autoRefreshingReadLease) Upgrade() (rwl ReadWriteLease, err error) {\n\tpanic(\"TODO\")\n}\n\nfunc (rl *autoRefreshingReadLease) Revoke() {\n\tpanic(\"TODO\")\n}\n<commit_msg>autoRefreshingReadLease.ReadAt<commit_after>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage lease\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"sync\"\n)\n\n\/\/ Create a ReadLease that never expires, unless voluntarily revoked or\n\/\/ upgraded.\n\/\/\n\/\/ The supplied function will be used to obtain the read lease contents, the\n\/\/ first time and whenever the supplied file leaser decides to expire the\n\/\/ temporary copy thus obtained. It must return the same contents every time,\n\/\/ and the contents must be of the given size.\n\/\/\n\/\/ This magic is not preserved after the lease is upgraded.\nfunc NewAutoRefreshingReadLease(\n\tfl FileLeaser,\n\tsize int64,\n\tf func() (io.ReadCloser, error)) (rl ReadLease) {\n\trl = &autoRefreshingReadLease{\n\t\tleaser: fl,\n\t\tsize:   size,\n\t\tf:      f,\n\t}\n\n\treturn\n}\n\ntype autoRefreshingReadLease struct {\n\tmu sync.Mutex\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Constant data\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tsize int64\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Dependencies\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tleaser FileLeaser\n\tf      func() (io.ReadCloser, error)\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Mutable state\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ The current wrapped lease, or nil if one has never been issued.\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\twrapped ReadLease\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Attempt to clean up after the supplied read\/write lease.\nfunc destroyReadWriteLease(rwl ReadWriteLease) {\n\tvar err error\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error destroying read\/write lease: %v\", err)\n\t\t}\n\t}()\n\n\t\/\/ Downgrade to a read lease.\n\trl, err := rwl.Downgrade()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Downgrade: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Revoke the read lease.\n\trl.Revoke()\n}\n\n\/\/ Set up a read\/write lease and fill in our contents.\n\/\/\n\/\/ REQUIRES: The caller has observed that rl.lease has expired.\n\/\/\n\/\/ LOCKS_REQUIRED(rl.mu)\nfunc (rl *autoRefreshingReadLease) getContents() (\n\trwl ReadWriteLease, err error) {\n\t\/\/ Obtain some space to write the contents.\n\trwl, err = rl.leaser.NewFile()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"NewFile: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Attempt to clean up if we exit early.\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tdestroyReadWriteLease(rwl)\n\t\t}\n\t}()\n\n\t\/\/ Obtain the reader for our contents.\n\trc, err := rl.f()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"User function: %v\", err)\n\t\treturn\n\t}\n\n\tdefer func() {\n\t\tcloseErr := rc.Close()\n\t\tif closeErr != nil && err == nil {\n\t\t\terr = fmt.Errorf(\"Close: %v\", closeErr)\n\t\t}\n\t}()\n\n\t\/\/ Copy into the read\/write lease.\n\tcopied, err := io.Copy(rwl, rc)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Copy: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ Did the user lie about the size?\n\tif copied != rl.Size() {\n\t\terr = fmt.Errorf(\"Copied %v bytes; expected %v\", copied, rl.Size())\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ Downgrade and save the supplied read\/write lease obtained with getContents\n\/\/ for later use.\n\/\/\n\/\/ LOCKS_REQUIRED(rl.mu)\nfunc (rl *autoRefreshingReadLease) saveContents(rwl ReadWriteLease) {\n\tdowngraded, err := rwl.Downgrade()\n\tif err != nil {\n\t\tlog.Printf(\"Failed to downgrade write lease (%q); abandoning.\", err.Error())\n\t\treturn\n\t}\n\n\trl.wrapped = downgraded\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Public interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (rl *autoRefreshingReadLease) Read(p []byte) (n int, err error) {\n\trl.mu.Lock()\n\tdefer rl.mu.Unlock()\n\n\t\/\/ Common case: is the existing lease still valid?\n\tif rl.wrapped != nil {\n\t\tpanic(\"TODO\")\n\t}\n\n\t\/\/ Get hold of a read\/write lease containing our contents.\n\trwl, err := rl.getContents()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"getContents: %v\", err)\n\t\treturn\n\t}\n\n\tdefer rl.saveContents(rwl)\n\n\t\/\/ Serve from the read\/write lease.\n\tn, err = rwl.Read(p)\n\n\treturn\n}\n\nfunc (rl *autoRefreshingReadLease) Seek(\n\toffset int64,\n\twhence int) (off int64, err error) {\n\tpanic(\"TODO\")\n}\n\nfunc (rl *autoRefreshingReadLease) ReadAt(\n\tp []byte,\n\toff int64) (n int, err error) {\n\trl.mu.Lock()\n\tdefer rl.mu.Unlock()\n\n\t\/\/ Common case: is the existing lease still valid?\n\tif rl.wrapped != nil {\n\t\tpanic(\"TODO\")\n\t}\n\n\t\/\/ Get hold of a read\/write lease containing our contents.\n\trwl, err := rl.getContents()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"getContents: %v\", err)\n\t\treturn\n\t}\n\n\tdefer rl.saveContents(rwl)\n\n\t\/\/ Serve from the read\/write lease.\n\tn, err = rwl.ReadAt(p, off)\n\n\treturn\n}\n\nfunc (rl *autoRefreshingReadLease) Size() (size int64) {\n\tsize = rl.size\n\treturn\n}\n\nfunc (rl *autoRefreshingReadLease) Revoked() (revoked bool) {\n\tpanic(\"TODO\")\n}\n\nfunc (rl *autoRefreshingReadLease) Upgrade() (rwl ReadWriteLease, err error) {\n\tpanic(\"TODO\")\n}\n\nfunc (rl *autoRefreshingReadLease) Revoke() {\n\tpanic(\"TODO\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"encoding\/gob\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\n\t\"github.com\/dotcloud\/docker\/term\"\n\t\"github.com\/flynn\/go-discover\/discover\"\n\t\"github.com\/flynn\/lorne\/types\"\n\t\"github.com\/flynn\/sampi\/client\"\n\t\"github.com\/flynn\/sampi\/types\"\n\t\"github.com\/titanous\/go-dockerclient\"\n)\n\nfunc main() {\n\tdisc, err := discover.NewClient()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tscheduler, err := client.New()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tstate, err := scheduler.State()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar firstHost string\n\tfor k := range state {\n\t\tfirstHost = k\n\t\tbreak\n\t}\n\tif firstHost == \"\" {\n\t\tlog.Fatal(\"no hosts\")\n\t}\n\n\tid := randomID()\n\n\tservices := disc.Services(\"flynn-lorne-attach.\" + firstHost)\n\tconn, err := net.Dial(\"tcp\", services.OnlineAddrs()[0])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tws, _ := term.GetWinsize(os.Stdin.Fd())\n\terr = gob.NewEncoder(conn).Encode(&lorne.AttachReq{\n\t\tJobID:  id,\n\t\tFlags:  lorne.AttachFlagStdout | lorne.AttachFlagStderr | lorne.AttachFlagStdin | lorne.AttachFlagStream,\n\t\tHeight: int(ws.Height),\n\t\tWidth:  int(ws.Width),\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tattachState := make([]byte, 1)\n\tif _, err := conn.Read(attachState); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tswitch attachState[0] {\n\tcase lorne.AttachWaiting:\n\t\tlog.Print(\"attach waiting\")\n\tcase lorne.AttachError:\n\t\tlog.Fatal(\"attach error\")\n\t}\n\n\tschedReq := &sampi.ScheduleReq{\n\t\tIncremental: true,\n\t\tHostJobs: map[string][]*sampi.Job{firstHost: {{ID: id, Config: &docker.Config{\n\t\t\tImage:        \"titanous\/redis\",\n\t\t\tCmd:          []string{\"\/redis\/src\/redis-cli\", \"-h\", \"10.0.2.15\"},\n\t\t\tTty:          true,\n\t\t\tAttachStdin:  true,\n\t\t\tAttachStdout: true,\n\t\t\tAttachStderr: true,\n\t\t\tOpenStdin:    true,\n\t\t\tStdinOnce:    true,\n\t\t}}}},\n\t}\n\tif _, err := scheduler.Schedule(schedReq); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif _, err := conn.Read(attachState); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\toldState, err := term.SetRawTerminal(os.Stdin.Fd())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tgo io.Copy(conn, os.Stdin)\n\tif _, err := io.Copy(os.Stdout, conn); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tterm.RestoreTerminal(os.Stdin.Fd(), oldState)\n}\n\nfunc randomID() string {\n\tb := make([]byte, 16)\n\tenc := make([]byte, 24)\n\t_, err := io.ReadFull(rand.Reader, b)\n\tif err != nil {\n\t\tpanic(err) \/\/ This shouldn't ever happen, right?\n\t}\n\tbase64.URLEncoding.Encode(enc, b)\n\treturn string(bytes.TrimRight(enc, \"=\"))\n}\n<commit_msg>sampi: example: Run bash instead of redis-cli<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"encoding\/gob\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com\/dotcloud\/docker\/term\"\n\t\"github.com\/flynn\/go-discover\/discover\"\n\t\"github.com\/flynn\/lorne\/types\"\n\t\"github.com\/flynn\/sampi\/client\"\n\t\"github.com\/flynn\/sampi\/types\"\n\t\"github.com\/titanous\/go-dockerclient\"\n)\n\nfunc main() {\n\tdisc, err := discover.NewClient()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tscheduler, err := client.New()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tstate, err := scheduler.State()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar firstHost string\n\tfor k := range state {\n\t\tfirstHost = k\n\t\tbreak\n\t}\n\tif firstHost == \"\" {\n\t\tlog.Fatal(\"no hosts\")\n\t}\n\n\tid := randomID()\n\n\tservices := disc.Services(\"flynn-lorne-attach.\" + firstHost)\n\tconn, err := net.Dial(\"tcp\", services.OnlineAddrs()[0])\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tws, _ := term.GetWinsize(os.Stdin.Fd())\n\terr = gob.NewEncoder(conn).Encode(&lorne.AttachReq{\n\t\tJobID:  id,\n\t\tFlags:  lorne.AttachFlagStdout | lorne.AttachFlagStderr | lorne.AttachFlagStdin | lorne.AttachFlagStream,\n\t\tHeight: int(ws.Height),\n\t\tWidth:  int(ws.Width),\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tattachState := make([]byte, 1)\n\tif _, err := conn.Read(attachState); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tswitch attachState[0] {\n\tcase lorne.AttachError:\n\t\tlog.Fatal(\"attach error\")\n\t}\n\n\tschedReq := &sampi.ScheduleReq{\n\t\tIncremental: true,\n\t\tHostJobs: map[string][]*sampi.Job{firstHost: {{ID: id, Config: &docker.Config{\n\t\t\tImage:        \"titanous\/redis\",\n\t\t\tCmd:          []string{\"\/bin\/bash\", \"-i\"},\n\t\t\tTty:          true,\n\t\t\tAttachStdin:  true,\n\t\t\tAttachStdout: true,\n\t\t\tAttachStderr: true,\n\t\t\tOpenStdin:    true,\n\t\t\tStdinOnce:    true,\n\t\t\tEnv: []string{\n\t\t\t\t\"COLUMNS=\" + strconv.Itoa(int(ws.Width)),\n\t\t\t\t\"LINES=\" + strconv.Itoa(int(ws.Height)),\n\t\t\t\t\"TERM=\" + os.Getenv(\"TERM\"),\n\t\t\t},\n\t\t}}}},\n\t}\n\tif _, err := scheduler.Schedule(schedReq); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif _, err := conn.Read(attachState); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\toldState, err := term.SetRawTerminal(os.Stdin.Fd())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tgo io.Copy(conn, os.Stdin)\n\tif _, err := io.Copy(os.Stdout, conn); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tterm.RestoreTerminal(os.Stdin.Fd(), oldState)\n}\n\nfunc randomID() string {\n\tb := make([]byte, 16)\n\tenc := make([]byte, 24)\n\t_, err := io.ReadFull(rand.Reader, b)\n\tif err != nil {\n\t\tpanic(err) \/\/ This shouldn't ever happen, right?\n\t}\n\tbase64.URLEncoding.Encode(enc, b)\n\treturn string(bytes.TrimRight(enc, \"=\"))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage build\n\nimport (\n\t\"crypto\/hmac\"\n\t\"fmt\"\n\t\"http\"\n\t\"json\"\n\t\"os\"\n\n\t\"appengine\"\n\t\"appengine\/datastore\"\n\t\"cache\"\n)\n\nconst commitsPerPage = 30\n\n\/\/ defaultPackages specifies the Package records to be created by initHandler.\nvar defaultPackages = []*Package{\n\t&Package{Name: \"Go\"},\n}\n\n\/\/ commitHandler retrieves commit data or records a new commit.\n\/\/\n\/\/ For GET requests it returns a Commit value for the specified\n\/\/ packagePath and hash.\n\/\/\n\/\/ For POST requests it reads a JSON-encoded Commit value from the request\n\/\/ body and creates a new Commit entity. It also updates the \"tip\" Tag for\n\/\/ each new commit at tip.\n\/\/\n\/\/ This handler is used by a gobuilder process in -commit mode.\nfunc commitHandler(r *http.Request) (interface{}, os.Error) {\n\tc := appengine.NewContext(r)\n\tcom := new(Commit)\n\n\tif r.Method == \"GET\" {\n\t\tcom.PackagePath = r.FormValue(\"packagePath\")\n\t\tcom.Hash = r.FormValue(\"hash\")\n\t\tif err := datastore.Get(c, com.Key(c), com); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"getting Commit: %v\", err)\n\t\t}\n\t\treturn com, nil\n\t}\n\tif r.Method != \"POST\" {\n\t\treturn nil, errBadMethod(r.Method)\n\t}\n\n\t\/\/ POST request\n\tdefer r.Body.Close()\n\tif err := json.NewDecoder(r.Body).Decode(com); err != nil {\n\t\treturn nil, fmt.Errorf(\"decoding Body: %v\", err)\n\t}\n\tif len(com.Desc) > maxDatastoreStringLen {\n\t\tcom.Desc = com.Desc[:maxDatastoreStringLen]\n\t}\n\tif err := com.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"validating Commit: %v\", err)\n\t}\n\tdefer cache.Tick(c)\n\ttx := func(c appengine.Context) os.Error {\n\t\treturn addCommit(c, com)\n\t}\n\treturn nil, datastore.RunInTransaction(c, tx, nil)\n}\n\n\/\/ addCommit adds the Commit entity to the datastore and updates the tip Tag.\n\/\/ It must be run inside a datastore transaction.\nfunc addCommit(c appengine.Context, com *Commit) os.Error {\n\tvar tc Commit \/\/ temp value so we don't clobber com\n\terr := datastore.Get(c, com.Key(c), &tc)\n\tif err != datastore.ErrNoSuchEntity {\n\t\t\/\/ if this commit is already in the datastore, do nothing\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"getting Commit: %v\", err)\n\t}\n\t\/\/ get the next commit number\n\tp, err := GetPackage(c, com.PackagePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"GetPackage: %v\", err)\n\t}\n\tcom.Num = p.NextNum\n\tp.NextNum++\n\tif _, err := datastore.Put(c, p.Key(c), p); err != nil {\n\t\treturn fmt.Errorf(\"putting Package: %v\", err)\n\t}\n\t\/\/ if this isn't the first Commit test the parent commit exists\n\tif com.Num > 0 {\n\t\tn, err := datastore.NewQuery(\"Commit\").\n\t\t\tFilter(\"Hash =\", com.ParentHash).\n\t\t\tAncestor(p.Key(c)).\n\t\t\tCount(c)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"testing for parent Commit: %v\", err)\n\t\t}\n\t\tif n == 0 {\n\t\t\treturn os.NewError(\"parent commit not found\")\n\t\t}\n\t}\n\t\/\/ update the tip Tag if this is the Go repo\n\tif p.Path == \"\" {\n\t\tt := &Tag{Kind: \"tip\", Hash: com.Hash}\n\t\tif _, err = datastore.Put(c, t.Key(c), t); err != nil {\n\t\t\treturn fmt.Errorf(\"putting Tag: %v\", err)\n\t\t}\n\t}\n\t\/\/ put the Commit\n\tif _, err = datastore.Put(c, com.Key(c), com); err != nil {\n\t\treturn fmt.Errorf(\"putting Commit: %v\", err)\n\t}\n\treturn nil\n}\n\n\/\/ tagHandler records a new tag. It reads a JSON-encoded Tag value from the\n\/\/ request body and updates the Tag entity for the Kind of tag provided.\n\/\/\n\/\/ This handler is used by a gobuilder process in -commit mode.\nfunc tagHandler(r *http.Request) (interface{}, os.Error) {\n\tif r.Method != \"POST\" {\n\t\treturn nil, errBadMethod(r.Method)\n\t}\n\n\tt := new(Tag)\n\tdefer r.Body.Close()\n\tif err := json.NewDecoder(r.Body).Decode(t); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := t.Valid(); err != nil {\n\t\treturn nil, err\n\t}\n\tc := appengine.NewContext(r)\n\tdefer cache.Tick(c)\n\t_, err := datastore.Put(c, t.Key(c), t)\n\treturn nil, err\n}\n\n\/\/ Todo is a todoHandler response.\ntype Todo struct {\n\tKind string \/\/ \"build-go-commit\" or \"build-package\"\n\tData interface{}\n}\n\n\/\/ todoHandler returns the next action to be performed by a builder.\n\/\/ It expects \"builder\" and \"kind\" query parameters and returns a *Todo value.\n\/\/ Multiple \"kind\" parameters may be specified.\nfunc todoHandler(r *http.Request) (interface{}, os.Error) {\n\tc := appengine.NewContext(r)\n\tnow := cache.Now(c)\n\tkey := \"build-todo-\" + r.Form.Encode()\n\tcachedTodo := new(Todo)\n\tif cache.Get(r, now, key, cachedTodo) {\n\t\treturn cachedTodo, nil\n\t}\n\tvar todo *Todo\n\tvar err os.Error\n\tbuilder := r.FormValue(\"builder\")\n\tfor _, kind := range r.Form[\"kind\"] {\n\t\tvar data interface{}\n\t\tswitch kind {\n\t\tcase \"build-go-commit\":\n\t\t\tdata, err = buildTodo(c, builder, \"\", \"\")\n\t\tcase \"build-package\":\n\t\t\tpackagePath := r.FormValue(\"packagePath\")\n\t\t\tgoHash := r.FormValue(\"goHash\")\n\t\t\tdata, err = buildTodo(c, builder, packagePath, goHash)\n\t\t}\n\t\tif data != nil || err != nil {\n\t\t\ttodo = &Todo{Kind: kind, Data: data}\n\t\t\tbreak\n\t\t}\n\t}\n\tif err == nil {\n\t\tcache.Set(r, now, key, todo)\n\t}\n\treturn todo, err\n}\n\n\/\/ buildTodo returns the next Commit to be built (or nil if none available).\n\/\/\n\/\/ If packagePath and goHash are empty, it scans the first 20 Go Commits in\n\/\/ Num-descending order and returns the first one it finds that doesn't have a\n\/\/ Result for this builder.\n\/\/\n\/\/ If provided with non-empty packagePath and goHash args, it scans the first\n\/\/ 20 Commits in Num-descending order for the specified packagePath and\n\/\/ returns the first that doesn't have a Result for this builder and goHash.\nfunc buildTodo(c appengine.Context, builder, packagePath, goHash string) (interface{}, os.Error) {\n\tp, err := GetPackage(c, packagePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt := datastore.NewQuery(\"Commit\").\n\t\tAncestor(p.Key(c)).\n\t\tLimit(commitsPerPage).\n\t\tOrder(\"-Num\").\n\t\tRun(c)\n\tfor {\n\t\tcom := new(Commit)\n\t\tif _, err := t.Next(com); err != nil {\n\t\t\tif err == datastore.Done {\n\t\t\t\terr = nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tif com.Result(builder, goHash) == nil {\n\t\t\treturn com, nil\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}\n\n\/\/ packagesHandler returns a list of the non-Go Packages monitored\n\/\/ by the dashboard.\nfunc packagesHandler(r *http.Request) (interface{}, os.Error) {\n\tc := appengine.NewContext(r)\n\tnow := cache.Now(c)\n\tconst key = \"build-packages\"\n\tvar p []*Package\n\tif cache.Get(r, now, key, &p) {\n\t\treturn p, nil\n\t}\n\tp, err := Packages(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcache.Set(r, now, key, p)\n\treturn p, nil\n}\n\n\/\/ resultHandler records a build result.\n\/\/ It reads a JSON-encoded Result value from the request body,\n\/\/ creates a new Result entity, and updates the relevant Commit entity.\n\/\/ If the Log field is not empty, resultHandler creates a new Log entity\n\/\/ and updates the LogHash field before putting the Commit entity.\nfunc resultHandler(r *http.Request) (interface{}, os.Error) {\n\tif r.Method != \"POST\" {\n\t\treturn nil, errBadMethod(r.Method)\n\t}\n\n\tc := appengine.NewContext(r)\n\tres := new(Result)\n\tdefer r.Body.Close()\n\tif err := json.NewDecoder(r.Body).Decode(res); err != nil {\n\t\treturn nil, fmt.Errorf(\"decoding Body: %v\", err)\n\t}\n\tif err := res.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"validating Result: %v\", err)\n\t}\n\tdefer cache.Tick(c)\n\t\/\/ store the Log text if supplied\n\tif len(res.Log) > 0 {\n\t\thash, err := PutLog(c, res.Log)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"putting Log: %v\", err)\n\t\t}\n\t\tres.LogHash = hash\n\t}\n\ttx := func(c appengine.Context) os.Error {\n\t\t\/\/ check Package exists\n\t\tif _, err := GetPackage(c, res.PackagePath); err != nil {\n\t\t\treturn fmt.Errorf(\"GetPackage: %v\", err)\n\t\t}\n\t\t\/\/ put Result\n\t\tif _, err := datastore.Put(c, res.Key(c), res); err != nil {\n\t\t\treturn fmt.Errorf(\"putting Result: %v\", err)\n\t\t}\n\t\t\/\/ add Result to Commit\n\t\tcom := &Commit{PackagePath: res.PackagePath, Hash: res.Hash}\n\t\tif err := com.AddResult(c, res); err != nil {\n\t\t\treturn fmt.Errorf(\"AddResult: %v\", err)\n\t\t}\n\t\t\/\/ Send build failure notifications, if necessary.\n\t\t\/\/ Note this must run after the call AddResult, which\n\t\t\/\/ populates the Commit's ResultData field.\n\t\treturn notifyOnFailure(c, com, res.Builder)\n\t}\n\treturn nil, datastore.RunInTransaction(c, tx, nil)\n}\n\n\/\/ logHandler displays log text for a given hash.\n\/\/ It handles paths like \"\/log\/hash\".\nfunc logHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-type\", \"text\/plain\")\n\tc := appengine.NewContext(r)\n\thash := r.URL.Path[len(\"\/log\/\"):]\n\tkey := datastore.NewKey(c, \"Log\", hash, 0, nil)\n\tl := new(Log)\n\tif err := datastore.Get(c, key, l); err != nil {\n\t\tlogErr(w, r, err)\n\t\treturn\n\t}\n\tb, err := l.Text()\n\tif err != nil {\n\t\tlogErr(w, r, err)\n\t\treturn\n\t}\n\tw.Write(b)\n}\n\ntype dashHandler func(*http.Request) (interface{}, os.Error)\n\ntype dashResponse struct {\n\tResponse interface{}\n\tError    string\n}\n\n\/\/ errBadMethod is returned by a dashHandler when\n\/\/ the request has an unsuitable method.\ntype errBadMethod string\n\nfunc (e errBadMethod) String() string {\n\treturn \"bad method: \" + string(e)\n}\n\n\/\/ AuthHandler wraps a http.HandlerFunc with a handler that validates the\n\/\/ supplied key and builder query parameters.\nfunc AuthHandler(h dashHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tc := appengine.NewContext(r)\n\n\t\t\/\/ Put the URL Query values into r.Form to avoid parsing the\n\t\t\/\/ request body when calling r.FormValue.\n\t\tr.Form = r.URL.Query()\n\n\t\tvar err os.Error\n\t\tvar resp interface{}\n\n\t\t\/\/ Validate key query parameter for POST requests only.\n\t\tkey := r.FormValue(\"key\")\n\t\tbuilder := r.FormValue(\"builder\")\n\t\tif r.Method == \"POST\" && !validKey(c, key, builder) {\n\t\t\terr = os.NewError(\"invalid key: \" + key)\n\t\t}\n\n\t\t\/\/ Call the original HandlerFunc and return the response.\n\t\tif err == nil {\n\t\t\tresp, err = h(r)\n\t\t}\n\n\t\t\/\/ Write JSON response.\n\t\tdashResp := &dashResponse{Response: resp}\n\t\tif err != nil {\n\t\t\tc.Errorf(\"%v\", err)\n\t\t\tdashResp.Error = err.String()\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tif err = json.NewEncoder(w).Encode(dashResp); err != nil {\n\t\t\tc.Criticalf(\"encoding response: %v\", err)\n\t\t}\n\t}\n}\n\nfunc initHandler(w http.ResponseWriter, r *http.Request) {\n\t\/\/ TODO(adg): devise a better way of bootstrapping new packages\n\tc := appengine.NewContext(r)\n\tdefer cache.Tick(c)\n\tfor _, p := range defaultPackages {\n\t\tif err := datastore.Get(c, p.Key(c), new(Package)); err == nil {\n\t\t\tcontinue\n\t\t} else if err != datastore.ErrNoSuchEntity {\n\t\t\tlogErr(w, r, err)\n\t\t\treturn\n\t\t}\n\t\tif _, err := datastore.Put(c, p.Key(c), p); err != nil {\n\t\t\tlogErr(w, r, err)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Fprint(w, \"OK\")\n}\n\nfunc keyHandler(w http.ResponseWriter, r *http.Request) {\n\tbuilder := r.FormValue(\"builder\")\n\tif builder == \"\" {\n\t\tlogErr(w, r, os.NewError(\"must supply builder in query string\"))\n\t\treturn\n\t}\n\tc := appengine.NewContext(r)\n\tfmt.Fprint(w, builderKey(c, builder))\n}\n\nfunc init() {\n\t\/\/ admin handlers\n\thttp.HandleFunc(\"\/init\", initHandler)\n\thttp.HandleFunc(\"\/key\", keyHandler)\n\n\t\/\/ authenticated handlers\n\thttp.HandleFunc(\"\/commit\", AuthHandler(commitHandler))\n\thttp.HandleFunc(\"\/packages\", AuthHandler(packagesHandler))\n\thttp.HandleFunc(\"\/result\", AuthHandler(resultHandler))\n\thttp.HandleFunc(\"\/tag\", AuthHandler(tagHandler))\n\thttp.HandleFunc(\"\/todo\", AuthHandler(todoHandler))\n\n\t\/\/ public handlers\n\thttp.HandleFunc(\"\/log\/\", logHandler)\n}\n\nfunc validHash(hash string) bool {\n\t\/\/ TODO(adg): correctly validate a hash\n\treturn hash != \"\"\n}\n\nfunc validKey(c appengine.Context, key, builder string) bool {\n\tif appengine.IsDevAppServer() {\n\t\treturn true\n\t}\n\tif key == secretKey(c) {\n\t\treturn true\n\t}\n\treturn key == builderKey(c, builder)\n}\n\nfunc builderKey(c appengine.Context, builder string) string {\n\th := hmac.NewMD5([]byte(secretKey(c)))\n\th.Write([]byte(builder))\n\treturn fmt.Sprintf(\"%x\", h.Sum())\n}\n\nfunc logErr(w http.ResponseWriter, r *http.Request, err os.Error) {\n\tappengine.NewContext(r).Errorf(\"Error: %v\", err)\n\tw.WriteHeader(http.StatusInternalServerError)\n\tfmt.Fprint(w, \"Error: \", err)\n}\n<commit_msg>dashboard: fix todo caching nil<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage build\n\nimport (\n\t\"crypto\/hmac\"\n\t\"fmt\"\n\t\"http\"\n\t\"json\"\n\t\"os\"\n\n\t\"appengine\"\n\t\"appengine\/datastore\"\n\t\"cache\"\n)\n\nconst commitsPerPage = 30\n\n\/\/ defaultPackages specifies the Package records to be created by initHandler.\nvar defaultPackages = []*Package{\n\t&Package{Name: \"Go\"},\n}\n\n\/\/ commitHandler retrieves commit data or records a new commit.\n\/\/\n\/\/ For GET requests it returns a Commit value for the specified\n\/\/ packagePath and hash.\n\/\/\n\/\/ For POST requests it reads a JSON-encoded Commit value from the request\n\/\/ body and creates a new Commit entity. It also updates the \"tip\" Tag for\n\/\/ each new commit at tip.\n\/\/\n\/\/ This handler is used by a gobuilder process in -commit mode.\nfunc commitHandler(r *http.Request) (interface{}, os.Error) {\n\tc := appengine.NewContext(r)\n\tcom := new(Commit)\n\n\tif r.Method == \"GET\" {\n\t\tcom.PackagePath = r.FormValue(\"packagePath\")\n\t\tcom.Hash = r.FormValue(\"hash\")\n\t\tif err := datastore.Get(c, com.Key(c), com); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"getting Commit: %v\", err)\n\t\t}\n\t\treturn com, nil\n\t}\n\tif r.Method != \"POST\" {\n\t\treturn nil, errBadMethod(r.Method)\n\t}\n\n\t\/\/ POST request\n\tdefer r.Body.Close()\n\tif err := json.NewDecoder(r.Body).Decode(com); err != nil {\n\t\treturn nil, fmt.Errorf(\"decoding Body: %v\", err)\n\t}\n\tif len(com.Desc) > maxDatastoreStringLen {\n\t\tcom.Desc = com.Desc[:maxDatastoreStringLen]\n\t}\n\tif err := com.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"validating Commit: %v\", err)\n\t}\n\tdefer cache.Tick(c)\n\ttx := func(c appengine.Context) os.Error {\n\t\treturn addCommit(c, com)\n\t}\n\treturn nil, datastore.RunInTransaction(c, tx, nil)\n}\n\n\/\/ addCommit adds the Commit entity to the datastore and updates the tip Tag.\n\/\/ It must be run inside a datastore transaction.\nfunc addCommit(c appengine.Context, com *Commit) os.Error {\n\tvar tc Commit \/\/ temp value so we don't clobber com\n\terr := datastore.Get(c, com.Key(c), &tc)\n\tif err != datastore.ErrNoSuchEntity {\n\t\t\/\/ if this commit is already in the datastore, do nothing\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"getting Commit: %v\", err)\n\t}\n\t\/\/ get the next commit number\n\tp, err := GetPackage(c, com.PackagePath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"GetPackage: %v\", err)\n\t}\n\tcom.Num = p.NextNum\n\tp.NextNum++\n\tif _, err := datastore.Put(c, p.Key(c), p); err != nil {\n\t\treturn fmt.Errorf(\"putting Package: %v\", err)\n\t}\n\t\/\/ if this isn't the first Commit test the parent commit exists\n\tif com.Num > 0 {\n\t\tn, err := datastore.NewQuery(\"Commit\").\n\t\t\tFilter(\"Hash =\", com.ParentHash).\n\t\t\tAncestor(p.Key(c)).\n\t\t\tCount(c)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"testing for parent Commit: %v\", err)\n\t\t}\n\t\tif n == 0 {\n\t\t\treturn os.NewError(\"parent commit not found\")\n\t\t}\n\t}\n\t\/\/ update the tip Tag if this is the Go repo\n\tif p.Path == \"\" {\n\t\tt := &Tag{Kind: \"tip\", Hash: com.Hash}\n\t\tif _, err = datastore.Put(c, t.Key(c), t); err != nil {\n\t\t\treturn fmt.Errorf(\"putting Tag: %v\", err)\n\t\t}\n\t}\n\t\/\/ put the Commit\n\tif _, err = datastore.Put(c, com.Key(c), com); err != nil {\n\t\treturn fmt.Errorf(\"putting Commit: %v\", err)\n\t}\n\treturn nil\n}\n\n\/\/ tagHandler records a new tag. It reads a JSON-encoded Tag value from the\n\/\/ request body and updates the Tag entity for the Kind of tag provided.\n\/\/\n\/\/ This handler is used by a gobuilder process in -commit mode.\nfunc tagHandler(r *http.Request) (interface{}, os.Error) {\n\tif r.Method != \"POST\" {\n\t\treturn nil, errBadMethod(r.Method)\n\t}\n\n\tt := new(Tag)\n\tdefer r.Body.Close()\n\tif err := json.NewDecoder(r.Body).Decode(t); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := t.Valid(); err != nil {\n\t\treturn nil, err\n\t}\n\tc := appengine.NewContext(r)\n\tdefer cache.Tick(c)\n\t_, err := datastore.Put(c, t.Key(c), t)\n\treturn nil, err\n}\n\n\/\/ Todo is a todoHandler response.\ntype Todo struct {\n\tKind string \/\/ \"build-go-commit\" or \"build-package\"\n\tData interface{}\n}\n\n\/\/ todoHandler returns the next action to be performed by a builder.\n\/\/ It expects \"builder\" and \"kind\" query parameters and returns a *Todo value.\n\/\/ Multiple \"kind\" parameters may be specified.\nfunc todoHandler(r *http.Request) (interface{}, os.Error) {\n\tc := appengine.NewContext(r)\n\tnow := cache.Now(c)\n\tkey := \"build-todo-\" + r.Form.Encode()\n\tvar todo *Todo\n\tif cache.Get(r, now, key, &todo) {\n\t\treturn todo, nil\n\t}\n\tvar err os.Error\n\tbuilder := r.FormValue(\"builder\")\n\tfor _, kind := range r.Form[\"kind\"] {\n\t\tvar data interface{}\n\t\tswitch kind {\n\t\tcase \"build-go-commit\":\n\t\t\tdata, err = buildTodo(c, builder, \"\", \"\")\n\t\tcase \"build-package\":\n\t\t\tpackagePath := r.FormValue(\"packagePath\")\n\t\t\tgoHash := r.FormValue(\"goHash\")\n\t\t\tdata, err = buildTodo(c, builder, packagePath, goHash)\n\t\t}\n\t\tif data != nil || err != nil {\n\t\t\ttodo = &Todo{Kind: kind, Data: data}\n\t\t\tbreak\n\t\t}\n\t}\n\tif err == nil {\n\t\tcache.Set(r, now, key, todo)\n\t}\n\treturn todo, err\n}\n\n\/\/ buildTodo returns the next Commit to be built (or nil if none available).\n\/\/\n\/\/ If packagePath and goHash are empty, it scans the first 20 Go Commits in\n\/\/ Num-descending order and returns the first one it finds that doesn't have a\n\/\/ Result for this builder.\n\/\/\n\/\/ If provided with non-empty packagePath and goHash args, it scans the first\n\/\/ 20 Commits in Num-descending order for the specified packagePath and\n\/\/ returns the first that doesn't have a Result for this builder and goHash.\nfunc buildTodo(c appengine.Context, builder, packagePath, goHash string) (interface{}, os.Error) {\n\tp, err := GetPackage(c, packagePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt := datastore.NewQuery(\"Commit\").\n\t\tAncestor(p.Key(c)).\n\t\tLimit(commitsPerPage).\n\t\tOrder(\"-Num\").\n\t\tRun(c)\n\tfor {\n\t\tcom := new(Commit)\n\t\tif _, err := t.Next(com); err != nil {\n\t\t\tif err == datastore.Done {\n\t\t\t\terr = nil\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\t\tif com.Result(builder, goHash) == nil {\n\t\t\treturn com, nil\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}\n\n\/\/ packagesHandler returns a list of the non-Go Packages monitored\n\/\/ by the dashboard.\nfunc packagesHandler(r *http.Request) (interface{}, os.Error) {\n\tc := appengine.NewContext(r)\n\tnow := cache.Now(c)\n\tconst key = \"build-packages\"\n\tvar p []*Package\n\tif cache.Get(r, now, key, &p) {\n\t\treturn p, nil\n\t}\n\tp, err := Packages(c)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcache.Set(r, now, key, p)\n\treturn p, nil\n}\n\n\/\/ resultHandler records a build result.\n\/\/ It reads a JSON-encoded Result value from the request body,\n\/\/ creates a new Result entity, and updates the relevant Commit entity.\n\/\/ If the Log field is not empty, resultHandler creates a new Log entity\n\/\/ and updates the LogHash field before putting the Commit entity.\nfunc resultHandler(r *http.Request) (interface{}, os.Error) {\n\tif r.Method != \"POST\" {\n\t\treturn nil, errBadMethod(r.Method)\n\t}\n\n\tc := appengine.NewContext(r)\n\tres := new(Result)\n\tdefer r.Body.Close()\n\tif err := json.NewDecoder(r.Body).Decode(res); err != nil {\n\t\treturn nil, fmt.Errorf(\"decoding Body: %v\", err)\n\t}\n\tif err := res.Valid(); err != nil {\n\t\treturn nil, fmt.Errorf(\"validating Result: %v\", err)\n\t}\n\tdefer cache.Tick(c)\n\t\/\/ store the Log text if supplied\n\tif len(res.Log) > 0 {\n\t\thash, err := PutLog(c, res.Log)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"putting Log: %v\", err)\n\t\t}\n\t\tres.LogHash = hash\n\t}\n\ttx := func(c appengine.Context) os.Error {\n\t\t\/\/ check Package exists\n\t\tif _, err := GetPackage(c, res.PackagePath); err != nil {\n\t\t\treturn fmt.Errorf(\"GetPackage: %v\", err)\n\t\t}\n\t\t\/\/ put Result\n\t\tif _, err := datastore.Put(c, res.Key(c), res); err != nil {\n\t\t\treturn fmt.Errorf(\"putting Result: %v\", err)\n\t\t}\n\t\t\/\/ add Result to Commit\n\t\tcom := &Commit{PackagePath: res.PackagePath, Hash: res.Hash}\n\t\tif err := com.AddResult(c, res); err != nil {\n\t\t\treturn fmt.Errorf(\"AddResult: %v\", err)\n\t\t}\n\t\t\/\/ Send build failure notifications, if necessary.\n\t\t\/\/ Note this must run after the call AddResult, which\n\t\t\/\/ populates the Commit's ResultData field.\n\t\treturn notifyOnFailure(c, com, res.Builder)\n\t}\n\treturn nil, datastore.RunInTransaction(c, tx, nil)\n}\n\n\/\/ logHandler displays log text for a given hash.\n\/\/ It handles paths like \"\/log\/hash\".\nfunc logHandler(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-type\", \"text\/plain\")\n\tc := appengine.NewContext(r)\n\thash := r.URL.Path[len(\"\/log\/\"):]\n\tkey := datastore.NewKey(c, \"Log\", hash, 0, nil)\n\tl := new(Log)\n\tif err := datastore.Get(c, key, l); err != nil {\n\t\tlogErr(w, r, err)\n\t\treturn\n\t}\n\tb, err := l.Text()\n\tif err != nil {\n\t\tlogErr(w, r, err)\n\t\treturn\n\t}\n\tw.Write(b)\n}\n\ntype dashHandler func(*http.Request) (interface{}, os.Error)\n\ntype dashResponse struct {\n\tResponse interface{}\n\tError    string\n}\n\n\/\/ errBadMethod is returned by a dashHandler when\n\/\/ the request has an unsuitable method.\ntype errBadMethod string\n\nfunc (e errBadMethod) String() string {\n\treturn \"bad method: \" + string(e)\n}\n\n\/\/ AuthHandler wraps a http.HandlerFunc with a handler that validates the\n\/\/ supplied key and builder query parameters.\nfunc AuthHandler(h dashHandler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tc := appengine.NewContext(r)\n\n\t\t\/\/ Put the URL Query values into r.Form to avoid parsing the\n\t\t\/\/ request body when calling r.FormValue.\n\t\tr.Form = r.URL.Query()\n\n\t\tvar err os.Error\n\t\tvar resp interface{}\n\n\t\t\/\/ Validate key query parameter for POST requests only.\n\t\tkey := r.FormValue(\"key\")\n\t\tbuilder := r.FormValue(\"builder\")\n\t\tif r.Method == \"POST\" && !validKey(c, key, builder) {\n\t\t\terr = os.NewError(\"invalid key: \" + key)\n\t\t}\n\n\t\t\/\/ Call the original HandlerFunc and return the response.\n\t\tif err == nil {\n\t\t\tresp, err = h(r)\n\t\t}\n\n\t\t\/\/ Write JSON response.\n\t\tdashResp := &dashResponse{Response: resp}\n\t\tif err != nil {\n\t\t\tc.Errorf(\"%v\", err)\n\t\t\tdashResp.Error = err.String()\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tif err = json.NewEncoder(w).Encode(dashResp); err != nil {\n\t\t\tc.Criticalf(\"encoding response: %v\", err)\n\t\t}\n\t}\n}\n\nfunc initHandler(w http.ResponseWriter, r *http.Request) {\n\t\/\/ TODO(adg): devise a better way of bootstrapping new packages\n\tc := appengine.NewContext(r)\n\tdefer cache.Tick(c)\n\tfor _, p := range defaultPackages {\n\t\tif err := datastore.Get(c, p.Key(c), new(Package)); err == nil {\n\t\t\tcontinue\n\t\t} else if err != datastore.ErrNoSuchEntity {\n\t\t\tlogErr(w, r, err)\n\t\t\treturn\n\t\t}\n\t\tif _, err := datastore.Put(c, p.Key(c), p); err != nil {\n\t\t\tlogErr(w, r, err)\n\t\t\treturn\n\t\t}\n\t}\n\tfmt.Fprint(w, \"OK\")\n}\n\nfunc keyHandler(w http.ResponseWriter, r *http.Request) {\n\tbuilder := r.FormValue(\"builder\")\n\tif builder == \"\" {\n\t\tlogErr(w, r, os.NewError(\"must supply builder in query string\"))\n\t\treturn\n\t}\n\tc := appengine.NewContext(r)\n\tfmt.Fprint(w, builderKey(c, builder))\n}\n\nfunc init() {\n\t\/\/ admin handlers\n\thttp.HandleFunc(\"\/init\", initHandler)\n\thttp.HandleFunc(\"\/key\", keyHandler)\n\n\t\/\/ authenticated handlers\n\thttp.HandleFunc(\"\/commit\", AuthHandler(commitHandler))\n\thttp.HandleFunc(\"\/packages\", AuthHandler(packagesHandler))\n\thttp.HandleFunc(\"\/result\", AuthHandler(resultHandler))\n\thttp.HandleFunc(\"\/tag\", AuthHandler(tagHandler))\n\thttp.HandleFunc(\"\/todo\", AuthHandler(todoHandler))\n\n\t\/\/ public handlers\n\thttp.HandleFunc(\"\/log\/\", logHandler)\n}\n\nfunc validHash(hash string) bool {\n\t\/\/ TODO(adg): correctly validate a hash\n\treturn hash != \"\"\n}\n\nfunc validKey(c appengine.Context, key, builder string) bool {\n\tif appengine.IsDevAppServer() {\n\t\treturn true\n\t}\n\tif key == secretKey(c) {\n\t\treturn true\n\t}\n\treturn key == builderKey(c, builder)\n}\n\nfunc builderKey(c appengine.Context, builder string) string {\n\th := hmac.NewMD5([]byte(secretKey(c)))\n\th.Write([]byte(builder))\n\treturn fmt.Sprintf(\"%x\", h.Sum())\n}\n\nfunc logErr(w http.ResponseWriter, r *http.Request, err os.Error) {\n\tappengine.NewContext(r).Errorf(\"Error: %v\", err)\n\tw.WriteHeader(http.StatusInternalServerError)\n\tfmt.Fprint(w, \"Error: \", err)\n}\n<|endoftext|>"}
{"text":"<commit_before>package stripper\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"io\"\n\t\"unicode\"\n)\n\ntype LeadingWhitespaceStripper struct {\n\t\/\/ it's on like\n\tdonkeyKong bool\n\n\tr   *bufio.Reader\n\tbuf bytes.Buffer\n}\n\nfunc NewLeadingWhitespaceStripper(r io.Reader) *LeadingWhitespaceStripper {\n\treturn &LeadingWhitespaceStripper{\n\t\tdonkeyKong: true,\n\n\t\tr: bufio.NewReader(r),\n\t}\n}\n\nfunc (r *LeadingWhitespaceStripper) Read(p []byte) (int, error) {\n\tif r.donkeyKong {\n\t\tfor {\n\t\t\tchar, _, err := r.r.ReadRune()\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\tif !unicode.IsSpace(char) {\n\t\t\t\tr.donkeyKong = false\n\t\t\t\terr = r.r.UnreadRune()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn 0, err\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn r.r.Read(p)\n}\n<commit_msg>Remove unneeded \"LeadingWhitespaceStripper\"<commit_after><|endoftext|>"}
{"text":"<commit_before>package geodata\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/golang\/geo\/s2\"\n\t\"github.com\/golang\/protobuf\/ptypes\/struct\"\n\tspb \"github.com\/golang\/protobuf\/ptypes\/struct\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/twpayne\/go-geom\"\n\t\"github.com\/twpayne\/go-geom\/encoding\/geojson\"\n)\n\n\/\/ GeomToGeoData update gd with geo data gathered from g\nfunc GeomToGeoData(g geom.T, gd *GeoData) error {\n\tgeo := &Geometry{}\n\n\tswitch g := g.(type) {\n\tcase *geom.Point:\n\t\tgeo.Coordinates = g.Coords()\n\t\tgeo.Type = Geometry_POINT\n\t\t\/\/case *geom.MultiPolygon:\n\t\t\/\/\tgeo.Type = geodata.Geometry_MULTIPOLYGON\n\n\tcase *geom.Polygon:\n\t\t\/\/ only supports outer ring\n\t\tgeo.Type = Geometry_POLYGON\n\t\tgeo.Coordinates = g.FlatCoords()\n\n\tdefault:\n\t\treturn errors.Errorf(\"unsupported geo type %T\", g)\n\t}\n\n\tgd.Geometry = geo\n\treturn nil\n}\n\n\/\/ GeoDataToGeom\nfunc GeoDataToGeom(gd *GeoData) (geom.T, error) {\n\tswitch gd.Geometry.Type {\n\tcase Geometry_POINT:\n\t\treturn geom.NewPointFlat(geom.XY, gd.Geometry.Coordinates), nil\n\tcase Geometry_POLYGON:\n\t\treturn geom.NewPolygonFlat(geom.XY, gd.Geometry.Coordinates, []int{len(gd.Geometry.Coordinates)}), nil\n\tdefault:\n\t\treturn nil, errors.Errorf(\"unsupported geodata type\")\n\t}\n}\n\n\/\/ GeoJSONFeatureToGeoData fill gd with the GeoJSON data f\nfunc GeoJSONFeatureToGeoData(f *geojson.Feature, gd *GeoData) error {\n\terr := PropertiesToGeoData(f, gd)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"while converting feature properties to GeoData\")\n\t}\n\n\terr = GeomToGeoData(f.Geometry, gd)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"while converting feature to GeoData\")\n\t}\n\n\treturn nil\n}\n\n\/\/ PropertiesToGeoData update gd.Properties with the properties found in f\nfunc PropertiesToGeoData(f *geojson.Feature, gd *GeoData) error {\n\tfor k, vi := range f.Properties {\n\t\tswitch tv := vi.(type) {\n\t\tcase bool:\n\t\t\tgd.Properties[k] = &structpb.Value{Kind: &structpb.Value_BoolValue{BoolValue: tv}}\n\t\tcase int:\n\t\t\tgd.Properties[k] = &structpb.Value{Kind: &structpb.Value_NumberValue{NumberValue: float64(tv)}}\n\t\tcase string:\n\t\t\tgd.Properties[k] = &structpb.Value{Kind: &structpb.Value_StringValue{StringValue: tv}}\n\t\tcase float64:\n\t\t\tgd.Properties[k] = &structpb.Value{Kind: &structpb.Value_NumberValue{NumberValue: tv}}\n\t\tcase nil:\n\t\t\t\/\/ pass\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"GeoJSON property %s unsupported type %T\", k, tv)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ GeoDataToFlatCellUnion generate an s2 cover for GeoData gd\nfunc GeoDataToFlatCellUnion(gd *GeoData, coverer *s2.RegionCoverer) (s2.CellUnion, error) {\n\tvar cu s2.CellUnion\n\tswitch gd.Geometry.Type {\n\tcase Geometry_POINT:\n\t\tc := s2.CellIDFromLatLng(s2.LatLngFromDegrees(gd.Geometry.Coordinates[1], gd.Geometry.Coordinates[0]))\n\t\tcu = append(cu, c.Parent(coverer.MinLevel))\n\n\tcase Geometry_POLYGON:\n\t\tcup, err := coverPolygon(gd.Geometry.Coordinates, coverer)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"can't cover polygon\")\n\t\t}\n\t\tcu = append(cu, cup...)\n\n\tcase Geometry_MULTIPOLYGON:\n\t\tfor _, g := range gd.Geometry.Geometries {\n\t\t\tcup, err := coverPolygon(g.Coordinates, coverer)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"can't cover multipolygon\")\n\t\t\t}\n\n\t\t\tcu = append(cu, cup...)\n\t\t}\n\n\tcase Geometry_LINESTRING:\n\t\tif len(gd.Geometry.Coordinates)%2 != 0 {\n\t\t\treturn nil, errors.New(\"invalid coordinates count for line\")\n\t\t}\n\n\t\t\/\/ the s2 cover returns bogus results\n\t\t\/\/ pl := make(s2.Polyline, len(gd.Geometry.Coordinates))\n\t\t\/\/ for i := 0; i <= len(gd.Geometry.Coordinates)\/2+2; i += 2 {\n\t\t\/\/ \tll := s2.LatLngFromDegrees(gd.Geometry.Coordinates[i+1], gd.Geometry.Coordinates[i])\n\t\t\/\/ \tpl[i\/2] = s2.PointFromLatLng(ll)\n\t\t\/\/ }\n\n\t\t\/\/ cupl := coverer.Covering(&pl)\n\t\t\/\/ cu = append(cu, cupl...)\n\n\t\t\/\/ uncomplete tempory solution\n\t\t\/\/ for each points add the cell, it is invalid because 2 distant points could be in more than 2 different cells\n\t\tm := make(map[s2.CellID]struct{})\n\t\tfor i := 0; i <= len(gd.Geometry.Coordinates)\/2+2; i += 2 {\n\t\t\tll := s2.LatLngFromDegrees(gd.Geometry.Coordinates[i+1], gd.Geometry.Coordinates[i])\n\t\t\tc := s2.CellIDFromLatLng(ll).Parent(coverer.MinLevel)\n\t\t\tm[c] = struct{}{}\n\t\t}\n\t\tfor c := range m {\n\t\t\tcu = append(cu, c)\n\t\t}\n\tdefault:\n\t\treturn nil, errors.New(\"unsupported data type\")\n\t}\n\n\treturn cu, nil\n}\n\n\/\/ returns an s2 cover from a list of lng, lat forming a closed polygon\nfunc coverPolygon(c []float64, coverer *s2.RegionCoverer) (s2.CellUnion, error) {\n\tif len(c) < 6 {\n\t\treturn nil, errors.New(\"invalid polygons not enough coordinates for a closed polygon\")\n\t}\n\tif len(c)%2 != 0 {\n\t\treturn nil, errors.New(\"invalid polygons odd coordinates number\")\n\t}\n\tl := LoopFromCoordinates(c)\n\tif l.IsEmpty() || l.IsFull() || l.ContainsOrigin() {\n\t\treturn nil, errors.New(\"invalid polygons\")\n\t}\n\n\treturn coverer.Covering(l), nil\n}\n\n\/\/ ToGeoJSONFeatureCollection converts a list of GeoData to a GeoJSON Feature Collection\nfunc ToGeoJSONFeatureCollection(geos []*GeoData) ([]byte, error) {\n\tfc := geojson.FeatureCollection{}\n\tfor _, g := range geos {\n\t\tf := &geojson.Feature{}\n\t\tswitch g.Geometry.Type {\n\t\tcase Geometry_POINT:\n\t\t\tng := geom.NewPointFlat(geom.XY, g.Geometry.Coordinates)\n\t\t\tf.Geometry = ng\n\t\tcase Geometry_POLYGON:\n\t\t\tng := geom.NewPolygonFlat(geom.XY, g.Geometry.Coordinates, []int{len(g.Geometry.Coordinates)})\n\t\t\tf.Geometry = ng\n\t\tcase Geometry_MULTIPOLYGON:\n\t\t\tmp := geom.NewMultiPolygon(geom.XY)\n\t\t\tfor _, poly := range g.Geometry.Geometries {\n\t\t\t\tng := geom.NewPolygonFlat(geom.XY, poly.Coordinates, []int{len(poly.Coordinates)})\n\t\t\t\tmp.Push(ng)\n\t\t\t}\n\t\t\tf.Geometry = mp\n\t\t}\n\t\tf.Properties = PropertiesToJSONMap(g.Properties)\n\t\tfc.Features = append(fc.Features, f)\n\t}\n\n\treturn fc.MarshalJSON()\n}\n\n\/\/ PointsToGeoJSONPolyLines converts a list of GeoDatato containing points to a polylines GeoJSON\nfunc PointsToGeoJSONPolyLines(geos []*GeoData) ([]byte, error) {\n\tf := geojson.Feature{}\n\tvar flatCoords []float64\n\n\tif len(geos) == 0 {\n\t\treturn f.MarshalJSON()\n\t}\n\n\tfor _, g := range geos {\n\t\tswitch g.Geometry.Type {\n\t\tcase Geometry_POINT:\n\t\t\tflatCoords = append(flatCoords, g.Geometry.Coordinates...)\n\t\tdefault:\n\t\t\treturn nil, errors.Errorf(\"unsupported geometry\")\n\n\t\t}\n\n\t}\n\tf.Properties = PropertiesToJSONMap(geos[0].Properties)\n\tg := geom.NewLineStringFlat(geom.XY, flatCoords)\n\tf.Geometry = g\n\n\treturn f.MarshalJSON()\n}\n\n\/\/ PropertiesToJSONMap converts a protobuf map to it's JSON serializable map equivalent\nfunc PropertiesToJSONMap(src map[string]*spb.Value) map[string]interface{} {\n\tres := make(map[string]interface{})\n\n\tfor k, v := range src {\n\t\tswitch x := v.Kind.(type) {\n\t\tcase *spb.Value_NumberValue:\n\t\t\tres[k] = x.NumberValue\n\t\tcase *spb.Value_StringValue:\n\t\t\tres[k] = x.StringValue\n\t\tcase *spb.Value_BoolValue:\n\t\t\tres[k] = x.BoolValue\n\t\t}\n\t}\n\treturn res\n}\n<commit_msg>update tools for line<commit_after>package geodata\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/golang\/geo\/s2\"\n\t\"github.com\/golang\/protobuf\/ptypes\/struct\"\n\tspb \"github.com\/golang\/protobuf\/ptypes\/struct\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/twpayne\/go-geom\"\n\t\"github.com\/twpayne\/go-geom\/encoding\/geojson\"\n)\n\n\/\/ GeomToGeoData update gd with geo data gathered from g\nfunc GeomToGeoData(g geom.T, gd *GeoData) error {\n\tgeo := &Geometry{}\n\n\tswitch g := g.(type) {\n\tcase *geom.Point:\n\t\tgeo.Coordinates = g.Coords()\n\t\tgeo.Type = Geometry_POINT\n\t\t\/\/case *geom.MultiPolygon:\n\t\t\/\/\tgeo.Type = geodata.Geometry_MULTIPOLYGON\n\n\tcase *geom.Polygon:\n\t\t\/\/ only supports outer ring\n\t\tgeo.Type = Geometry_POLYGON\n\t\tgeo.Coordinates = g.FlatCoords()\n\n\tcase *geom.LineString:\n\t\tgeo.Type = Geometry_LINESTRING\n\t\tgeo.Coordinates = g.FlatCoords()\n\n\tdefault:\n\t\treturn errors.Errorf(\"unsupported geo type %T\", g)\n\t}\n\n\tgd.Geometry = geo\n\treturn nil\n}\n\n\/\/ GeoDataToGeom\nfunc GeoDataToGeom(gd *GeoData) (geom.T, error) {\n\tswitch gd.Geometry.Type {\n\tcase Geometry_POINT:\n\t\treturn geom.NewPointFlat(geom.XY, gd.Geometry.Coordinates), nil\n\tcase Geometry_POLYGON:\n\t\treturn geom.NewPolygonFlat(geom.XY, gd.Geometry.Coordinates, []int{len(gd.Geometry.Coordinates)}), nil\n\tcase Geometry_LINESTRING:\n\t\treturn geom.NewLineStringFlat(geo, XY, gd.Geometry.Coordinates)\n\tdefault:\n\t\treturn nil, errors.Errorf(\"unsupported geodata type\")\n\t}\n}\n\n\/\/ GeoJSONFeatureToGeoData fill gd with the GeoJSON data f\nfunc GeoJSONFeatureToGeoData(f *geojson.Feature, gd *GeoData) error {\n\terr := PropertiesToGeoData(f, gd)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"while converting feature properties to GeoData\")\n\t}\n\n\terr = GeomToGeoData(f.Geometry, gd)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"while converting feature to GeoData\")\n\t}\n\n\treturn nil\n}\n\n\/\/ PropertiesToGeoData update gd.Properties with the properties found in f\nfunc PropertiesToGeoData(f *geojson.Feature, gd *GeoData) error {\n\tfor k, vi := range f.Properties {\n\t\tswitch tv := vi.(type) {\n\t\tcase bool:\n\t\t\tgd.Properties[k] = &structpb.Value{Kind: &structpb.Value_BoolValue{BoolValue: tv}}\n\t\tcase int:\n\t\t\tgd.Properties[k] = &structpb.Value{Kind: &structpb.Value_NumberValue{NumberValue: float64(tv)}}\n\t\tcase string:\n\t\t\tgd.Properties[k] = &structpb.Value{Kind: &structpb.Value_StringValue{StringValue: tv}}\n\t\tcase float64:\n\t\t\tgd.Properties[k] = &structpb.Value{Kind: &structpb.Value_NumberValue{NumberValue: tv}}\n\t\tcase nil:\n\t\t\t\/\/ pass\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"GeoJSON property %s unsupported type %T\", k, tv)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ GeoDataToFlatCellUnion generate an s2 cover for GeoData gd\nfunc GeoDataToFlatCellUnion(gd *GeoData, coverer *s2.RegionCoverer) (s2.CellUnion, error) {\n\tvar cu s2.CellUnion\n\tswitch gd.Geometry.Type {\n\tcase Geometry_POINT:\n\t\tc := s2.CellIDFromLatLng(s2.LatLngFromDegrees(gd.Geometry.Coordinates[1], gd.Geometry.Coordinates[0]))\n\t\tcu = append(cu, c.Parent(coverer.MinLevel))\n\n\tcase Geometry_POLYGON:\n\t\tcup, err := coverPolygon(gd.Geometry.Coordinates, coverer)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"can't cover polygon\")\n\t\t}\n\t\tcu = append(cu, cup...)\n\n\tcase Geometry_MULTIPOLYGON:\n\t\tfor _, g := range gd.Geometry.Geometries {\n\t\t\tcup, err := coverPolygon(g.Coordinates, coverer)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"can't cover multipolygon\")\n\t\t\t}\n\n\t\t\tcu = append(cu, cup...)\n\t\t}\n\n\tcase Geometry_LINESTRING:\n\t\tif len(gd.Geometry.Coordinates)%2 != 0 {\n\t\t\treturn nil, errors.New(\"invalid coordinates count for line\")\n\t\t}\n\n\t\t\/\/ the s2 cover returns bogus results\n\t\t\/\/ pl := make(s2.Polyline, len(gd.Geometry.Coordinates))\n\t\t\/\/ for i := 0; i <= len(gd.Geometry.Coordinates)\/2+2; i += 2 {\n\t\t\/\/ \tll := s2.LatLngFromDegrees(gd.Geometry.Coordinates[i+1], gd.Geometry.Coordinates[i])\n\t\t\/\/ \tpl[i\/2] = s2.PointFromLatLng(ll)\n\t\t\/\/ }\n\n\t\t\/\/ cupl := coverer.Covering(&pl)\n\t\t\/\/ cu = append(cu, cupl...)\n\n\t\t\/\/ uncomplete tempory solution\n\t\t\/\/ for each points add the cell, it is invalid because 2 distant points could be in more than 2 different cells\n\t\tm := make(map[s2.CellID]struct{})\n\t\tfor i := 0; i <= len(gd.Geometry.Coordinates)\/2+2; i += 2 {\n\t\t\tll := s2.LatLngFromDegrees(gd.Geometry.Coordinates[i+1], gd.Geometry.Coordinates[i])\n\t\t\tc := s2.CellIDFromLatLng(ll).Parent(coverer.MinLevel)\n\t\t\tm[c] = struct{}{}\n\t\t}\n\t\tfor c := range m {\n\t\t\tcu = append(cu, c)\n\t\t}\n\tdefault:\n\t\treturn nil, errors.New(\"unsupported data type\")\n\t}\n\n\treturn cu, nil\n}\n\n\/\/ returns an s2 cover from a list of lng, lat forming a closed polygon\nfunc coverPolygon(c []float64, coverer *s2.RegionCoverer) (s2.CellUnion, error) {\n\tif len(c) < 6 {\n\t\treturn nil, errors.New(\"invalid polygons not enough coordinates for a closed polygon\")\n\t}\n\tif len(c)%2 != 0 {\n\t\treturn nil, errors.New(\"invalid polygons odd coordinates number\")\n\t}\n\tl := LoopFromCoordinates(c)\n\tif l.IsEmpty() || l.IsFull() || l.ContainsOrigin() {\n\t\treturn nil, errors.New(\"invalid polygons\")\n\t}\n\n\treturn coverer.Covering(l), nil\n}\n\n\/\/ ToGeoJSONFeatureCollection converts a list of GeoData to a GeoJSON Feature Collection\nfunc ToGeoJSONFeatureCollection(geos []*GeoData) ([]byte, error) {\n\tfc := geojson.FeatureCollection{}\n\tfor _, g := range geos {\n\t\tf := &geojson.Feature{}\n\t\tswitch g.Geometry.Type {\n\t\tcase Geometry_POINT:\n\t\t\tng := geom.NewPointFlat(geom.XY, g.Geometry.Coordinates)\n\t\t\tf.Geometry = ng\n\t\tcase Geometry_POLYGON:\n\t\t\tng := geom.NewPolygonFlat(geom.XY, g.Geometry.Coordinates, []int{len(g.Geometry.Coordinates)})\n\t\t\tf.Geometry = ng\n\t\tcase Geometry_MULTIPOLYGON:\n\t\t\tmp := geom.NewMultiPolygon(geom.XY)\n\t\t\tfor _, poly := range g.Geometry.Geometries {\n\t\t\t\tng := geom.NewPolygonFlat(geom.XY, poly.Coordinates, []int{len(poly.Coordinates)})\n\t\t\t\tmp.Push(ng)\n\t\t\t}\n\t\t\tf.Geometry = mp\n\t\tcase Geometry_LINESTRING:\n\t\t\tls := geom.NewLineStringFlat(geom.XY, g.Geometry.Coordinates)\n\t\t\tf.Geometry = ls\n\t\t}\n\t\tf.Properties = PropertiesToJSONMap(g.Properties)\n\t\tfc.Features = append(fc.Features, f)\n\t}\n\n\treturn fc.MarshalJSON()\n}\n\n\/\/ PointsToGeoJSONPolyLines converts a list of GeoData containing points to a polylines GeoJSON\nfunc PointsToGeoJSONPolyLines(geos []*GeoData) ([]byte, error) {\n\tf := geojson.Feature{}\n\tvar flatCoords []float64\n\n\tif len(geos) == 0 {\n\t\treturn f.MarshalJSON()\n\t}\n\n\tfor _, g := range geos {\n\t\tswitch g.Geometry.Type {\n\t\tcase Geometry_POINT:\n\t\t\tflatCoords = append(flatCoords, g.Geometry.Coordinates...)\n\t\tdefault:\n\t\t\treturn nil, errors.Errorf(\"unsupported geometry\")\n\t\t}\n\n\t}\n\tf.Properties = PropertiesToJSONMap(geos[0].Properties)\n\tg := geom.NewLineStringFlat(geom.XY, flatCoords)\n\tf.Geometry = g\n\n\treturn f.MarshalJSON()\n}\n\n\/\/ PropertiesToJSONMap converts a protobuf map to it's JSON serializable map equivalent\nfunc PropertiesToJSONMap(src map[string]*spb.Value) map[string]interface{} {\n\tres := make(map[string]interface{})\n\n\tfor k, v := range src {\n\t\tswitch x := v.Kind.(type) {\n\t\tcase *spb.Value_NumberValue:\n\t\t\tres[k] = x.NumberValue\n\t\tcase *spb.Value_StringValue:\n\t\t\tres[k] = x.StringValue\n\t\tcase *spb.Value_BoolValue:\n\t\t\tres[k] = x.BoolValue\n\t\t}\n\t}\n\treturn res\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/sloonz\/cfeedparser\"\n\t\"github.com\/sloonz\/go-maildir\"\n\t\"github.com\/sloonz\/go-mime-message\"\n\t\"github.com\/sloonz\/go-qprintable\"\n\t\"io\/ioutil\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Cache struct {\n\tdata map[string]bool\n\tpath string\n}\n\nfunc (c *Cache) load() error {\n\tcacheFile, err := os.Open(c.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := ioutil.ReadAll(cacheFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(data, &c.data)\n}\n\nfunc (c *Cache) dump() error {\n\tcacheFile, err := os.Create(c.path + \".new\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cacheFile.Close()\n\n\tenc := json.NewEncoder(cacheFile)\n\tif err = enc.Encode(c.data); err != nil {\n\t\treturn err\n\t}\n\n\treturn os.Rename(c.path+\".new\", c.path)\n}\n\nvar cache Cache\n\nfunc firstNonEmpty(s ...string) string {\n\tvar val string\n\tfor _, val = range s {\n\t\tif val != \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn val\n}\n\nfunc getRFC822Date(e *feedparser.Entry) string {\n\temptyTime := time.Time{}\n\tif e.PublicationDateParsed != emptyTime {\n\t\treturn e.PublicationDateParsed.Format(time.RFC1123Z)\n\t}\n\tif e.ModificationDateParsed != emptyTime {\n\t\treturn e.ModificationDateParsed.Format(time.RFC1123Z)\n\t}\n\tif e.PublicationDate != \"\" {\n\t\treturn e.PublicationDate\n\t}\n\tif e.ModificationDate != \"\" {\n\t\treturn e.ModificationDate\n\t}\n\treturn time.Now().UTC().Format(time.RFC1123Z)\n}\n\nfunc getFrom(e *feedparser.Entry) string {\n\tname := strings.TrimSpace(message.EncodeWord(firstNonEmpty(e.Author.Name, e.Author.Uri, e.Author.Text)))\n\tif e.Author.Email != \"\" {\n\t\tname += \" <\" + strings.TrimSpace(e.Author.Email) + \">\"\n\t}\n\treturn name\n}\n\nvar convertEOLReg = regexp.MustCompile(\"\\r\\n?\")\n\nfunc convertEOL(s string) string {\n\treturn convertEOLReg.ReplaceAllString(s, \"\\n\")\n}\n\nfunc process(rawUrl string) error {\n\turl_, err := url.Parse(rawUrl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmd, err := maildir.New(\".\", false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfeed, err := feedparser.ParseURL(url_)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"[%s]\\n\", feed.Title)\n\tfor _, entry := range feed.Entries {\n\t\tpostId := firstNonEmpty(entry.Id, entry.Link, entry.PublicationDate+\":\"+entry.Title)\n\t\tif _, hasId := cache.data[postId]; hasId {\n\t\t\tcontinue\n\t\t}\n\n\t\tbody := convertEOL(firstNonEmpty(entry.Content, entry.Summary))\n\t\tbody += \"\\n<p><small><a href=\\\"\" + entry.Link + \"\\\">View post<\/a><\/small><\/p>\\n\"\n\n\t\ttitle := strings.TrimSpace(entry.Title)\n\t\tmsg := message.NewTextMessage(qprintable.UnixTextEncoding, bytes.NewBufferString(body))\n\t\tmsg.SetHeader(\"Date\", getRFC822Date(&entry))\n\t\tmsg.SetHeader(\"From\", getFrom(&entry))\n\t\tmsg.SetHeader(\"To\", \"Feeds <feeds@localhost>\")\n\t\tmsg.SetHeader(\"Subject\", message.EncodeWord(title))\n\t\tmsg.SetHeader(\"Content-Type\", \"text\/html; charset=\\\"UTF-8\\\"\")\n\n\t\t_, err = md.CreateMail(msg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Printf(\"  %s\\n\", title)\n\t\tcache.data[postId] = true\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\turl_ := os.Args[1]\n\n\tcache.path = path.Join(os.Getenv(\"HOME\"), \".cache\", \"rss2maildir\", strings.Replace(url_, \"\/\", \"_\", -1))\n\tcache.data = make(map[string]bool)\n\n\terr := cache.load()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Warning: can't read cache: %s\\n\", err.Error())\n\t}\n\n\terr = process(url_)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Can't process feed: %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\terr = cache.dump()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Can't write cache: %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n}\n<commit_msg>Alway add an adress email in the From header<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/sloonz\/cfeedparser\"\n\t\"github.com\/sloonz\/go-maildir\"\n\t\"github.com\/sloonz\/go-mime-message\"\n\t\"github.com\/sloonz\/go-qprintable\"\n\t\"io\/ioutil\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Cache struct {\n\tdata map[string]bool\n\tpath string\n}\n\nfunc (c *Cache) load() error {\n\tcacheFile, err := os.Open(c.path)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := ioutil.ReadAll(cacheFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn json.Unmarshal(data, &c.data)\n}\n\nfunc (c *Cache) dump() error {\n\tcacheFile, err := os.Create(c.path + \".new\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cacheFile.Close()\n\n\tenc := json.NewEncoder(cacheFile)\n\tif err = enc.Encode(c.data); err != nil {\n\t\treturn err\n\t}\n\n\treturn os.Rename(c.path+\".new\", c.path)\n}\n\nvar cache Cache\n\nfunc firstNonEmpty(s ...string) string {\n\tvar val string\n\tfor _, val = range s {\n\t\tif val != \"\" {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn val\n}\n\nfunc getRFC822Date(e *feedparser.Entry) string {\n\temptyTime := time.Time{}\n\tif e.PublicationDateParsed != emptyTime {\n\t\treturn e.PublicationDateParsed.Format(time.RFC1123Z)\n\t}\n\tif e.ModificationDateParsed != emptyTime {\n\t\treturn e.ModificationDateParsed.Format(time.RFC1123Z)\n\t}\n\tif e.PublicationDate != \"\" {\n\t\treturn e.PublicationDate\n\t}\n\tif e.ModificationDate != \"\" {\n\t\treturn e.ModificationDate\n\t}\n\treturn time.Now().UTC().Format(time.RFC1123Z)\n}\n\nfunc getFrom(e *feedparser.Entry) string {\n\tname := strings.TrimSpace(message.EncodeWord(firstNonEmpty(e.Author.Name, e.Author.Uri, e.Author.Text)))\n\tif e.Author.Email != \"\" {\n\t\tname += \" <\" + strings.TrimSpace(e.Author.Email) + \">\"\n\t} else {\n\t\tname += \" <noreply@localhost>\"\n\t}\n\treturn name\n}\n\nvar convertEOLReg = regexp.MustCompile(\"\\r\\n?\")\n\nfunc convertEOL(s string) string {\n\treturn convertEOLReg.ReplaceAllString(s, \"\\n\")\n}\n\nfunc process(rawUrl string) error {\n\turl_, err := url.Parse(rawUrl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmd, err := maildir.New(\".\", false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfeed, err := feedparser.ParseURL(url_)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"[%s]\\n\", feed.Title)\n\tfor _, entry := range feed.Entries {\n\t\tpostId := firstNonEmpty(entry.Id, entry.Link, entry.PublicationDate+\":\"+entry.Title)\n\t\tif _, hasId := cache.data[postId]; hasId {\n\t\t\tcontinue\n\t\t}\n\n\t\tbody := convertEOL(firstNonEmpty(entry.Content, entry.Summary))\n\t\tbody += \"\\n<p><small><a href=\\\"\" + entry.Link + \"\\\">View post<\/a><\/small><\/p>\\n\"\n\n\t\ttitle := strings.TrimSpace(entry.Title)\n\t\tmsg := message.NewTextMessage(qprintable.UnixTextEncoding, bytes.NewBufferString(body))\n\t\tmsg.SetHeader(\"Date\", getRFC822Date(&entry))\n\t\tmsg.SetHeader(\"From\", getFrom(&entry))\n\t\tmsg.SetHeader(\"To\", \"Feeds <feeds@localhost>\")\n\t\tmsg.SetHeader(\"Subject\", message.EncodeWord(title))\n\t\tmsg.SetHeader(\"Content-Type\", \"text\/html; charset=\\\"UTF-8\\\"\")\n\n\t\t_, err = md.CreateMail(msg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Printf(\"  %s\\n\", title)\n\t\tcache.data[postId] = true\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\turl_ := os.Args[1]\n\n\tcache.path = path.Join(os.Getenv(\"HOME\"), \".cache\", \"rss2maildir\", strings.Replace(url_, \"\/\", \"_\", -1))\n\tcache.data = make(map[string]bool)\n\n\terr := cache.load()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Warning: can't read cache: %s\\n\", err.Error())\n\t}\n\n\terr = process(url_)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Can't process feed: %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\terr = cache.dump()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Can't write cache: %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package tunnel\n\nimport (\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com\/micro\/go-micro\/transport\"\n)\n\n\/\/ testAccept will accept connections on the transport, create a new link and tunnel on top\nfunc testAccept(t *testing.T, tun Tunnel, wg *sync.WaitGroup) {\n\t\/\/ listen on some virtual address\n\ttl, err := tun.Listen(\"test-tunnel\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ accept a connection\n\tc, err := tl.Accept()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ get a message\n\tfor {\n\t\tm := new(transport.Message)\n\t\tif err := c.Recv(m); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\twg.Done()\n\t\treturn\n\t}\n}\n\n\/\/ testSend will create a new link to an address and then a tunnel on top\nfunc testSend(t *testing.T, tun Tunnel) {\n\t\/\/ dial a new session\n\tc, err := tun.Dial(\"test-tunnel\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tm := transport.Message{\n\t\tHeader: map[string]string{\n\t\t\t\"test\": \"header\",\n\t\t},\n\t}\n\n\tif err := c.Send(&m); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestTunnel(t *testing.T) {\n\t\/\/ create a new listener\n\ttun := NewTunnel(Nodes(\":9096\"))\n\terr := tun.Connect()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer tun.Close()\n\n\tvar wg sync.WaitGroup\n\n\t\/\/ start accepting connections\n\twg.Add(1)\n\tgo testAccept(t, tun, &wg)\n\n\t\/\/ send a message\n\ttestSend(t, tun)\n\n\t\/\/ wait until message is received\n\twg.Wait()\n}\n\nfunc TestTwoTunnel(t *testing.T) {\n\t\/\/ create a new tunnel client\n\ttunA := NewTunnel(\n\t\tAddress(\":9096\"),\n\t\tNodes(\":9097\"),\n\t)\n\n\t\/\/ create a new tunnel server\n\ttunB := NewTunnel(\n\t\tAddress(\":9097\"),\n\t)\n\n\t\/\/ start tunB\n\terr := tunB.Connect()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer tunB.Close()\n\n\t\/\/ start tunA\n\terr = tunA.Connect()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer tunA.Close()\n\n\tvar wg sync.WaitGroup\n\n\t\/\/ start accepting connections\n\twg.Add(1)\n\tgo testAccept(t, tunB, &wg)\n\n\t\/\/ send a message\n\ttestSend(t, tunA)\n\n\t\/\/ wait until done\n\twg.Wait()\n}\n<commit_msg>Fix travis test?<commit_after>package tunnel\n\nimport (\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com\/micro\/go-micro\/transport\"\n)\n\n\/\/ testAccept will accept connections on the transport, create a new link and tunnel on top\nfunc testAccept(t *testing.T, tun Tunnel, wg *sync.WaitGroup) {\n\t\/\/ listen on some virtual address\n\ttl, err := tun.Listen(\"test-tunnel\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ accept a connection\n\tc, err := tl.Accept()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ get a message\n\tfor {\n\t\tm := new(transport.Message)\n\t\tif err := c.Recv(m); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\twg.Done()\n\t\treturn\n\t}\n}\n\n\/\/ testSend will create a new link to an address and then a tunnel on top\nfunc testSend(t *testing.T, tun Tunnel) {\n\t\/\/ dial a new session\n\tc, err := tun.Dial(\"test-tunnel\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tm := transport.Message{\n\t\tHeader: map[string]string{\n\t\t\t\"test\": \"header\",\n\t\t},\n\t}\n\n\tif err := c.Send(&m); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestTunnel(t *testing.T) {\n\t\/\/ create a new listener\n\ttun := NewTunnel(Nodes(\"127.0.0.1:9096\"))\n\terr := tun.Connect()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer tun.Close()\n\n\tvar wg sync.WaitGroup\n\n\t\/\/ start accepting connections\n\twg.Add(1)\n\tgo testAccept(t, tun, &wg)\n\n\t\/\/ send a message\n\ttestSend(t, tun)\n\n\t\/\/ wait until message is received\n\twg.Wait()\n}\n\nfunc TestTwoTunnel(t *testing.T) {\n\t\/\/ create a new tunnel client\n\ttunA := NewTunnel(\n\t\tAddress(\"127.0.0.1:9096\"),\n\t\tNodes(\"127.0.0.1:9097\"),\n\t)\n\n\t\/\/ create a new tunnel server\n\ttunB := NewTunnel(\n\t\tAddress(\"127.0.0.1:9097\"),\n\t)\n\n\t\/\/ start tunB\n\terr := tunB.Connect()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer tunB.Close()\n\n\t\/\/ start tunA\n\terr = tunA.Connect()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer tunA.Close()\n\n\tvar wg sync.WaitGroup\n\n\t\/\/ start accepting connections\n\twg.Add(1)\n\tgo testAccept(t, tunB, &wg)\n\n\t\/\/ send a message\n\ttestSend(t, tunA)\n\n\t\/\/ wait until done\n\twg.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017-2018 Tigera, Inc. All rights reserved.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage clientv3\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/projectcalico\/libcalico-go\/lib\/apiconfig\"\n\tapiv3 \"github.com\/projectcalico\/libcalico-go\/lib\/apis\/v3\"\n\t\"github.com\/projectcalico\/libcalico-go\/lib\/options\"\n\tvalidator \"github.com\/projectcalico\/libcalico-go\/lib\/validator\/v3\"\n\t\"github.com\/projectcalico\/libcalico-go\/lib\/watch\"\n)\n\n\/\/ GlobalNetworkPolicyInterface has methods to work with GlobalNetworkPolicy resources.\ntype GlobalNetworkPolicyInterface interface {\n\tCreate(ctx context.Context, res *apiv3.GlobalNetworkPolicy, opts options.SetOptions) (*apiv3.GlobalNetworkPolicy, error)\n\tUpdate(ctx context.Context, res *apiv3.GlobalNetworkPolicy, opts options.SetOptions) (*apiv3.GlobalNetworkPolicy, error)\n\tDelete(ctx context.Context, name string, opts options.DeleteOptions) (*apiv3.GlobalNetworkPolicy, error)\n\tGet(ctx context.Context, name string, opts options.GetOptions) (*apiv3.GlobalNetworkPolicy, error)\n\tList(ctx context.Context, opts options.ListOptions) (*apiv3.GlobalNetworkPolicyList, error)\n\tWatch(ctx context.Context, opts options.ListOptions) (watch.Interface, error)\n}\n\n\/\/ globalNetworkPolicies implements GlobalNetworkPolicyInterface\ntype globalNetworkPolicies struct {\n\tclient client\n}\n\n\/\/ Create takes the representation of a GlobalNetworkPolicy and creates it.  Returns the stored\n\/\/ representation of the GlobalNetworkPolicy, and an error, if there is any.\nfunc (r globalNetworkPolicies) Create(ctx context.Context, res *apiv3.GlobalNetworkPolicy, opts options.SetOptions) (*apiv3.GlobalNetworkPolicy, error) {\n\tif res != nil {\n\t\t\/\/ Since we're about to default some fields, take a (shallow) copy of the input data\n\t\t\/\/ before we do so.\n\t\tresCopy := *res\n\t\tres = &resCopy\n\t}\n\tdefaultPolicyTypesField(res.Spec.Ingress, res.Spec.Egress, &res.Spec.Types)\n\n\tif err := validator.Validate(res); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Check if it is permitted to create the network policy with the specific alpha feature support.\n\tif err := r.validateAlphaFeatures(res); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Properly prefix the name\n\tres.GetObjectMeta().SetName(convertPolicyNameForStorage(res.GetObjectMeta().GetName()))\n\tout, err := r.client.resources.Create(ctx, opts, apiv3.KindGlobalNetworkPolicy, res)\n\tif out != nil {\n\t\t\/\/ Remove the prefix out of the returned policy name.\n\t\tout.GetObjectMeta().SetName(convertPolicyNameFromStorage(out.GetObjectMeta().GetName()))\n\t\treturn out.(*apiv3.GlobalNetworkPolicy), err\n\t}\n\n\t\/\/ Remove the prefix out of the returned policy name.\n\tres.GetObjectMeta().SetName(convertPolicyNameFromStorage(res.GetObjectMeta().GetName()))\n\treturn nil, err\n}\n\n\/\/ Update takes the representation of a GlobalNetworkPolicy and updates it. Returns the stored\n\/\/ representation of the GlobalNetworkPolicy, and an error, if there is any.\nfunc (r globalNetworkPolicies) Update(ctx context.Context, res *apiv3.GlobalNetworkPolicy, opts options.SetOptions) (*apiv3.GlobalNetworkPolicy, error) {\n\tif res != nil {\n\t\t\/\/ Since we're about to default some fields, take a (shallow) copy of the input data\n\t\t\/\/ before we do so.\n\t\tresCopy := *res\n\t\tres = &resCopy\n\t}\n\tdefaultPolicyTypesField(res.Spec.Ingress, res.Spec.Egress, &res.Spec.Types)\n\n\tif err := validator.Validate(res); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Check if it is permitted to create the network policy with the specific alpha feature support.\n\tif err := r.validateAlphaFeatures(res); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Properly prefix the name\n\tres.GetObjectMeta().SetName(convertPolicyNameForStorage(res.GetObjectMeta().GetName()))\n\tout, err := r.client.resources.Update(ctx, opts, apiv3.KindGlobalNetworkPolicy, res)\n\tif out != nil {\n\t\t\/\/ Remove the prefix out of the returned policy name.\n\t\tout.GetObjectMeta().SetName(convertPolicyNameFromStorage(out.GetObjectMeta().GetName()))\n\t\treturn out.(*apiv3.GlobalNetworkPolicy), err\n\t}\n\n\t\/\/ Remove the prefix out of the returned policy name.\n\tres.GetObjectMeta().SetName(convertPolicyNameFromStorage(res.GetObjectMeta().GetName()))\n\treturn nil, err\n}\n\n\/\/ Delete takes name of the GlobalNetworkPolicy and deletes it. Returns an error if one occurs.\nfunc (r globalNetworkPolicies) Delete(ctx context.Context, name string, opts options.DeleteOptions) (*apiv3.GlobalNetworkPolicy, error) {\n\tout, err := r.client.resources.Delete(ctx, opts, apiv3.KindGlobalNetworkPolicy, noNamespace, convertPolicyNameForStorage(name))\n\tif out != nil {\n\t\t\/\/ Remove the prefix out of the returned policy name.\n\t\tout.GetObjectMeta().SetName(convertPolicyNameFromStorage(out.GetObjectMeta().GetName()))\n\t\treturn out.(*apiv3.GlobalNetworkPolicy), err\n\t}\n\treturn nil, err\n}\n\n\/\/ Get takes name of the GlobalNetworkPolicy, and returns the corresponding GlobalNetworkPolicy object,\n\/\/ and an error if there is any.\nfunc (r globalNetworkPolicies) Get(ctx context.Context, name string, opts options.GetOptions) (*apiv3.GlobalNetworkPolicy, error) {\n\tout, err := r.client.resources.Get(ctx, opts, apiv3.KindGlobalNetworkPolicy, noNamespace, convertPolicyNameForStorage(name))\n\tif out != nil {\n\t\t\/\/ Remove the prefix out of the returned policy name.\n\t\tout.GetObjectMeta().SetName(convertPolicyNameFromStorage(out.GetObjectMeta().GetName()))\n\t\treturn out.(*apiv3.GlobalNetworkPolicy), err\n\t}\n\treturn nil, err\n}\n\n\/\/ List returns the list of GlobalNetworkPolicy objects that match the supplied options.\nfunc (r globalNetworkPolicies) List(ctx context.Context, opts options.ListOptions) (*apiv3.GlobalNetworkPolicyList, error) {\n\tres := &apiv3.GlobalNetworkPolicyList{}\n\t\/\/ Add the name prefix if name is provided\n\tif opts.Name != \"\" {\n\t\topts.Name = convertPolicyNameForStorage(opts.Name)\n\t}\n\n\tif err := r.client.resources.List(ctx, opts, apiv3.KindGlobalNetworkPolicy, apiv3.KindGlobalNetworkPolicyList, res); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Remove the prefix off of each policy name\n\tfor i, _ := range res.Items {\n\t\tname := res.Items[i].GetObjectMeta().GetName()\n\t\tres.Items[i].GetObjectMeta().SetName(convertPolicyNameFromStorage(name))\n\t}\n\n\treturn res, nil\n}\n\n\/\/ Watch returns a watch.Interface that watches the globalNetworkPolicies that match the\n\/\/ supplied options.\nfunc (r globalNetworkPolicies) Watch(ctx context.Context, opts options.ListOptions) (watch.Interface, error) {\n\t\/\/ Add the name prefix if name is provided\n\tif opts.Name != \"\" {\n\t\topts.Name = convertPolicyNameForStorage(opts.Name)\n\t}\n\n\treturn r.client.resources.Watch(ctx, opts, apiv3.KindGlobalNetworkPolicy, &policyConverter{})\n}\n\nfunc (r globalNetworkPolicies) validateAlphaFeatures(res *apiv3.GlobalNetworkPolicy) error {\n\tif apiconfig.IsAlphaFeatureSet(r.client.config.Spec.AlphaFeatures, apiconfig.AlphaFeatureSA) == false {\n\t\terr := validator.ValidateNoServiceAccountRules(res.Spec.Ingress, res.Spec.Egress)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Global NP %s: %s\", res.GetObjectMeta().GetName(), err.Error())\n\t\t}\n\t}\n\n\tif apiconfig.IsAlphaFeatureSet(r.client.config.Spec.AlphaFeatures, apiconfig.AlphaFeatureHTTP) == false {\n\t\terr := validator.ValidateNoHTTPRules(res.Spec.Ingress, res.Spec.Egress)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Global NP %s: %s\", res.GetObjectMeta().GetName(), err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc defaultPolicyTypesField(ingressRules, egressRules []apiv3.Rule, types *[]apiv3.PolicyType) {\n\tif len(*types) == 0 {\n\t\t\/\/ Default the Types field according to what inbound and outbound rules are present\n\t\t\/\/ in the policy.\n\t\tif len(egressRules) == 0 {\n\t\t\t\/\/ Policy has no egress rules, so apply this policy to ingress only.  (Note:\n\t\t\t\/\/ intentionally including the case where the policy also has no ingress\n\t\t\t\/\/ rules.)\n\t\t\t*types = []apiv3.PolicyType{apiv3.PolicyTypeIngress}\n\t\t} else if len(ingressRules) == 0 {\n\t\t\t\/\/ Policy has egress rules but no ingress rules, so apply this policy to\n\t\t\t\/\/ egress only.\n\t\t\t*types = []apiv3.PolicyType{apiv3.PolicyTypeEgress}\n\t\t} else {\n\t\t\t\/\/ Policy has both ingress and egress rules, so apply this policy to both\n\t\t\t\/\/ ingress and egress.\n\t\t\t*types = []apiv3.PolicyType{apiv3.PolicyTypeIngress, apiv3.PolicyTypeEgress}\n\t\t}\n\t}\n}\n\nfunc convertPolicyNameForStorage(name string) string {\n\t\/\/ Do nothing on names prefixed with \"knp.\"\n\tif strings.HasPrefix(name, \"knp.\") {\n\t\treturn name\n\t}\n\treturn \"default.\" + name\n}\n\nfunc convertPolicyNameFromStorage(name string) string {\n\t\/\/ Do nothing on names prefixed with \"knp.\"\n\tif strings.HasPrefix(name, \"knp.\") {\n\t\treturn name\n\t}\n\tparts := strings.SplitN(name, \".\", 2)\n\treturn parts[len(parts)-1]\n}\n\ntype policyConverter struct{}\n\nfunc (pc *policyConverter) Convert(r resource) resource {\n\tr.GetObjectMeta().SetName(convertPolicyNameFromStorage(r.GetObjectMeta().GetName()))\n\treturn r\n}\n<commit_msg>Don't add\/remove 'ossg.default.' NP prefix when to\/from storage<commit_after>\/\/ Copyright (c) 2017-2018 Tigera, Inc. All rights reserved.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage clientv3\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/projectcalico\/libcalico-go\/lib\/apiconfig\"\n\tapiv3 \"github.com\/projectcalico\/libcalico-go\/lib\/apis\/v3\"\n\t\"github.com\/projectcalico\/libcalico-go\/lib\/options\"\n\tvalidator \"github.com\/projectcalico\/libcalico-go\/lib\/validator\/v3\"\n\t\"github.com\/projectcalico\/libcalico-go\/lib\/watch\"\n)\n\n\/\/ GlobalNetworkPolicyInterface has methods to work with GlobalNetworkPolicy resources.\ntype GlobalNetworkPolicyInterface interface {\n\tCreate(ctx context.Context, res *apiv3.GlobalNetworkPolicy, opts options.SetOptions) (*apiv3.GlobalNetworkPolicy, error)\n\tUpdate(ctx context.Context, res *apiv3.GlobalNetworkPolicy, opts options.SetOptions) (*apiv3.GlobalNetworkPolicy, error)\n\tDelete(ctx context.Context, name string, opts options.DeleteOptions) (*apiv3.GlobalNetworkPolicy, error)\n\tGet(ctx context.Context, name string, opts options.GetOptions) (*apiv3.GlobalNetworkPolicy, error)\n\tList(ctx context.Context, opts options.ListOptions) (*apiv3.GlobalNetworkPolicyList, error)\n\tWatch(ctx context.Context, opts options.ListOptions) (watch.Interface, error)\n}\n\n\/\/ globalNetworkPolicies implements GlobalNetworkPolicyInterface\ntype globalNetworkPolicies struct {\n\tclient client\n}\n\n\/\/ Create takes the representation of a GlobalNetworkPolicy and creates it.  Returns the stored\n\/\/ representation of the GlobalNetworkPolicy, and an error, if there is any.\nfunc (r globalNetworkPolicies) Create(ctx context.Context, res *apiv3.GlobalNetworkPolicy, opts options.SetOptions) (*apiv3.GlobalNetworkPolicy, error) {\n\tif res != nil {\n\t\t\/\/ Since we're about to default some fields, take a (shallow) copy of the input data\n\t\t\/\/ before we do so.\n\t\tresCopy := *res\n\t\tres = &resCopy\n\t}\n\tdefaultPolicyTypesField(res.Spec.Ingress, res.Spec.Egress, &res.Spec.Types)\n\n\tif err := validator.Validate(res); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Check if it is permitted to create the network policy with the specific alpha feature support.\n\tif err := r.validateAlphaFeatures(res); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Properly prefix the name\n\tres.GetObjectMeta().SetName(convertPolicyNameForStorage(res.GetObjectMeta().GetName()))\n\tout, err := r.client.resources.Create(ctx, opts, apiv3.KindGlobalNetworkPolicy, res)\n\tif out != nil {\n\t\t\/\/ Remove the prefix out of the returned policy name.\n\t\tout.GetObjectMeta().SetName(convertPolicyNameFromStorage(out.GetObjectMeta().GetName()))\n\t\treturn out.(*apiv3.GlobalNetworkPolicy), err\n\t}\n\n\t\/\/ Remove the prefix out of the returned policy name.\n\tres.GetObjectMeta().SetName(convertPolicyNameFromStorage(res.GetObjectMeta().GetName()))\n\treturn nil, err\n}\n\n\/\/ Update takes the representation of a GlobalNetworkPolicy and updates it. Returns the stored\n\/\/ representation of the GlobalNetworkPolicy, and an error, if there is any.\nfunc (r globalNetworkPolicies) Update(ctx context.Context, res *apiv3.GlobalNetworkPolicy, opts options.SetOptions) (*apiv3.GlobalNetworkPolicy, error) {\n\tif res != nil {\n\t\t\/\/ Since we're about to default some fields, take a (shallow) copy of the input data\n\t\t\/\/ before we do so.\n\t\tresCopy := *res\n\t\tres = &resCopy\n\t}\n\tdefaultPolicyTypesField(res.Spec.Ingress, res.Spec.Egress, &res.Spec.Types)\n\n\tif err := validator.Validate(res); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Check if it is permitted to create the network policy with the specific alpha feature support.\n\tif err := r.validateAlphaFeatures(res); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Properly prefix the name\n\tres.GetObjectMeta().SetName(convertPolicyNameForStorage(res.GetObjectMeta().GetName()))\n\tout, err := r.client.resources.Update(ctx, opts, apiv3.KindGlobalNetworkPolicy, res)\n\tif out != nil {\n\t\t\/\/ Remove the prefix out of the returned policy name.\n\t\tout.GetObjectMeta().SetName(convertPolicyNameFromStorage(out.GetObjectMeta().GetName()))\n\t\treturn out.(*apiv3.GlobalNetworkPolicy), err\n\t}\n\n\t\/\/ Remove the prefix out of the returned policy name.\n\tres.GetObjectMeta().SetName(convertPolicyNameFromStorage(res.GetObjectMeta().GetName()))\n\treturn nil, err\n}\n\n\/\/ Delete takes name of the GlobalNetworkPolicy and deletes it. Returns an error if one occurs.\nfunc (r globalNetworkPolicies) Delete(ctx context.Context, name string, opts options.DeleteOptions) (*apiv3.GlobalNetworkPolicy, error) {\n\tout, err := r.client.resources.Delete(ctx, opts, apiv3.KindGlobalNetworkPolicy, noNamespace, convertPolicyNameForStorage(name))\n\tif out != nil {\n\t\t\/\/ Remove the prefix out of the returned policy name.\n\t\tout.GetObjectMeta().SetName(convertPolicyNameFromStorage(out.GetObjectMeta().GetName()))\n\t\treturn out.(*apiv3.GlobalNetworkPolicy), err\n\t}\n\treturn nil, err\n}\n\n\/\/ Get takes name of the GlobalNetworkPolicy, and returns the corresponding GlobalNetworkPolicy object,\n\/\/ and an error if there is any.\nfunc (r globalNetworkPolicies) Get(ctx context.Context, name string, opts options.GetOptions) (*apiv3.GlobalNetworkPolicy, error) {\n\tout, err := r.client.resources.Get(ctx, opts, apiv3.KindGlobalNetworkPolicy, noNamespace, convertPolicyNameForStorage(name))\n\tif out != nil {\n\t\t\/\/ Remove the prefix out of the returned policy name.\n\t\tout.GetObjectMeta().SetName(convertPolicyNameFromStorage(out.GetObjectMeta().GetName()))\n\t\treturn out.(*apiv3.GlobalNetworkPolicy), err\n\t}\n\treturn nil, err\n}\n\n\/\/ List returns the list of GlobalNetworkPolicy objects that match the supplied options.\nfunc (r globalNetworkPolicies) List(ctx context.Context, opts options.ListOptions) (*apiv3.GlobalNetworkPolicyList, error) {\n\tres := &apiv3.GlobalNetworkPolicyList{}\n\t\/\/ Add the name prefix if name is provided\n\tif opts.Name != \"\" {\n\t\topts.Name = convertPolicyNameForStorage(opts.Name)\n\t}\n\n\tif err := r.client.resources.List(ctx, opts, apiv3.KindGlobalNetworkPolicy, apiv3.KindGlobalNetworkPolicyList, res); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Remove the prefix off of each policy name\n\tfor i, _ := range res.Items {\n\t\tname := res.Items[i].GetObjectMeta().GetName()\n\t\tres.Items[i].GetObjectMeta().SetName(convertPolicyNameFromStorage(name))\n\t}\n\n\treturn res, nil\n}\n\n\/\/ Watch returns a watch.Interface that watches the globalNetworkPolicies that match the\n\/\/ supplied options.\nfunc (r globalNetworkPolicies) Watch(ctx context.Context, opts options.ListOptions) (watch.Interface, error) {\n\t\/\/ Add the name prefix if name is provided\n\tif opts.Name != \"\" {\n\t\topts.Name = convertPolicyNameForStorage(opts.Name)\n\t}\n\n\treturn r.client.resources.Watch(ctx, opts, apiv3.KindGlobalNetworkPolicy, &policyConverter{})\n}\n\nfunc (r globalNetworkPolicies) validateAlphaFeatures(res *apiv3.GlobalNetworkPolicy) error {\n\tif apiconfig.IsAlphaFeatureSet(r.client.config.Spec.AlphaFeatures, apiconfig.AlphaFeatureSA) == false {\n\t\terr := validator.ValidateNoServiceAccountRules(res.Spec.Ingress, res.Spec.Egress)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Global NP %s: %s\", res.GetObjectMeta().GetName(), err.Error())\n\t\t}\n\t}\n\n\tif apiconfig.IsAlphaFeatureSet(r.client.config.Spec.AlphaFeatures, apiconfig.AlphaFeatureHTTP) == false {\n\t\terr := validator.ValidateNoHTTPRules(res.Spec.Ingress, res.Spec.Egress)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Global NP %s: %s\", res.GetObjectMeta().GetName(), err.Error())\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc defaultPolicyTypesField(ingressRules, egressRules []apiv3.Rule, types *[]apiv3.PolicyType) {\n\tif len(*types) == 0 {\n\t\t\/\/ Default the Types field according to what inbound and outbound rules are present\n\t\t\/\/ in the policy.\n\t\tif len(egressRules) == 0 {\n\t\t\t\/\/ Policy has no egress rules, so apply this policy to ingress only.  (Note:\n\t\t\t\/\/ intentionally including the case where the policy also has no ingress\n\t\t\t\/\/ rules.)\n\t\t\t*types = []apiv3.PolicyType{apiv3.PolicyTypeIngress}\n\t\t} else if len(ingressRules) == 0 {\n\t\t\t\/\/ Policy has egress rules but no ingress rules, so apply this policy to\n\t\t\t\/\/ egress only.\n\t\t\t*types = []apiv3.PolicyType{apiv3.PolicyTypeEgress}\n\t\t} else {\n\t\t\t\/\/ Policy has both ingress and egress rules, so apply this policy to both\n\t\t\t\/\/ ingress and egress.\n\t\t\t*types = []apiv3.PolicyType{apiv3.PolicyTypeIngress, apiv3.PolicyTypeEgress}\n\t\t}\n\t}\n}\n\nfunc convertPolicyNameForStorage(name string) string {\n\t\/\/ Do nothing on names prefixed with \"knp.\"\n\tif strings.HasPrefix(name, \"knp.\") {\n\t\treturn name\n\t}\n\t\/\/ Similarly for \"ossg.\"\n\tif strings.HasPrefix(name, \"ossg.\") {\n\t\treturn name\n\t}\n\treturn \"default.\" + name\n}\n\nfunc convertPolicyNameFromStorage(name string) string {\n\t\/\/ Do nothing on names prefixed with \"knp.\"\n\tif strings.HasPrefix(name, \"knp.\") {\n\t\treturn name\n\t}\n\t\/\/ Similarly for \"ossg.\"\n\tif strings.HasPrefix(name, \"ossg.\") {\n\t\treturn name\n\t}\n\tparts := strings.SplitN(name, \".\", 2)\n\treturn parts[len(parts)-1]\n}\n\ntype policyConverter struct{}\n\nfunc (pc *policyConverter) Convert(r resource) resource {\n\tr.GetObjectMeta().SetName(convertPolicyNameFromStorage(r.GetObjectMeta().GetName()))\n\treturn r\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"net\/url\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\/\/ start when there is no config should report that fact right away\nfunc TestStartWithoutConfig(t *testing.T) {\n\tdone := start(\"\/not\/notaconfig.conf\")\n\tmessage := <- done\n\tif message != \"Could not read file at \/not\/notaconfig.conf\" {\n\t\tt.Errorf(\"did not report the file that was missing\")\n\t}\n}\n\n\/\/ start when there is a bad config should report that fact right away\nfunc TestStartWithBadConfig(t *testing.T) {\n\tdone := start(\".\/test_bad.conf\")\n\tmessage := <- done\n\tif message != \"Could not decode config\" {\n\t\tt.Errorf(\"incorrect bad config mesage\\n\\\"%s\\\"\", message)\n\t}\n}\n\n\/\/ start with a valid file should not be done right away\nfunc TestStartWithGoodConfig(t *testing.T) {\n\tdone := start(\".\/test_good.conf\")\n\tselect {\n\tcase message := <-done:\n\t\tt.Errorf(\"done with message\\n \\\"%s\\\"\", message)\n\tcase <-time.After(time.Millisecond * 50):\n\t\tfmt.Print(\"Stayed up with good config\\n\")\n\t}\n}\n\n\/\/ Stabilizer.ServeHTTP should return the first good response\nfunc TestStabilizerReturnsFirstResponse(t *testing.T) {\n\t\/\/ mock handler that first errors, then takes a long time then returns a\n\t\/\/ a good response\n\treqCount := 0\n\tmockHandler := func(w http.ResponseWriter, r *http.Request) {\n\t\treqCount++\n\t\tif reqCount % 3 == 1 {\n\t\t\thttp.Error(w, \"test error\", 1234567890)\n\t\t}\n\t\tif reqCount % 3 == 2 {\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\tfmt.Fprintf(w, \"slow response\")\n\t\t}\n\t\tif reqCount % 3 == 0 {\n\t\t\tfmt.Fprintf(w, \"fast response\")\n\t\t}\n\t}\n\n\tmockUnstableBackend := httptest.NewServer(http.HandlerFunc(mockHandler))\n\tdefer mockUnstableBackend.Close()\n\tu, err := url.Parse(mockUnstableBackend.URL)\n\tif err != nil { t.Errorf(\"error parsing backend url test broken\") }\n\ttestStabilizer := &Stabilizer{u, 4}\n\ttestStableServer := httptest.NewServer(\n\t\thttp.TimeoutHandler(testStabilizer, 5 * time.Second, \"timeout\"),\n\t)\n\tdefer testStableServer.Close()\n\n\t\/\/ make many requests and make sure they are all the fast response\n\tfor i := 0; i < 50; i++ {\n\t\tres, err := http.Get(testStableServer.URL)\n\t\tif err != nil { t.Errorf(\"error response from stable server\") }\n\n\t\tmessage, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil { t.Errorf(\"error reading response body from stable server\") }\n\t\tres.Body.Close()\n\n\t\t\/\/ ensure that all responses are the fast response\n\t\tif string(message) != \"fast response\" {\n\t\t\tt.Errorf(string(message))\n\t\t}\n\t}\n}\n\n\/\/ TestCanPass proves that tests are running\nfunc TestCanPass(t *testing.T) {\n\tif true != true {\n\t\tt.Errorf(\"true is not true,\\ncheck your premises,\\n consider clojure?\")\n\t}\n}\n<commit_msg>pause slightly before each set of requests so the pipes can clear<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"net\/url\"\n\t\"testing\"\n\t\"time\"\n)\n\n\n\/\/ start when there is no config should report that fact right away\nfunc TestStartWithoutConfig(t *testing.T) {\n\tdone := start(\"\/not\/notaconfig.conf\")\n\tmessage := <- done\n\tif message != \"Could not read file at \/not\/notaconfig.conf\" {\n\t\tt.Errorf(\"did not report the file that was missing\")\n\t}\n}\n\n\/\/ start when there is a bad config should report that fact right away\nfunc TestStartWithBadConfig(t *testing.T) {\n\tdone := start(\".\/test_bad.conf\")\n\tmessage := <- done\n\tif message != \"Could not decode config\" {\n\t\tt.Errorf(\"incorrect bad config mesage\\n\\\"%s\\\"\", message)\n\t}\n}\n\n\/\/ start with a valid file should not be done right away\nfunc TestStartWithGoodConfig(t *testing.T) {\n\tdone := start(\".\/test_good.conf\")\n\tselect {\n\tcase message := <-done:\n\t\tt.Errorf(\"done with message\\n \\\"%s\\\"\", message)\n\tcase <-time.After(time.Millisecond * 50):\n\t\tfmt.Print(\"Stayed up with good config\\n\")\n\t}\n}\n\n\/\/ Stabilizer.ServeHTTP should return the first good response\nfunc TestStabilizerReturnsFirstResponse(t *testing.T) {\n\t\/\/ mock handler that first errors, then takes a long time then returns a\n\t\/\/ a good response\n\treqCount := 0\n\tmockHandler := func(w http.ResponseWriter, r *http.Request) {\n\t\treqCount++\n\t\tif reqCount % 3 == 1 {\n\t\t\thttp.Error(w, \"test error\", 1234567890)\n\t\t}\n\t\tif reqCount % 3 == 2 {\n\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\tfmt.Fprintf(w, \"slow response\")\n\t\t}\n\t\tif reqCount % 3 == 0 {\n\t\t\tfmt.Fprintf(w, \"fast response\")\n\t\t}\n\t}\n\n\tmockUnstableBackend := httptest.NewServer(http.HandlerFunc(mockHandler))\n\tdefer mockUnstableBackend.Close()\n\tu, err := url.Parse(mockUnstableBackend.URL)\n\tif err != nil { t.Errorf(\"error parsing backend url test broken\") }\n\ttestStabilizer := &Stabilizer{u, 4}\n\ttestStableServer := httptest.NewServer(\n\t\thttp.TimeoutHandler(testStabilizer, 5 * time.Second, \"timeout\"),\n\t)\n\tdefer testStableServer.Close()\n\n\t\/\/ make many requests and make sure they are all the fast response\n\tfor i := 0; i < 100; i++ {\n\t\tres, err := http.Get(testStableServer.URL)\n\t\tif err != nil { t.Errorf(\"error response from stable server\") }\n\n\t\tmessage, err := ioutil.ReadAll(res.Body)\n\t\tif err != nil { t.Errorf(\"error reading response body from stable server\") }\n\t\tres.Body.Close()\n\n\t\t\/\/ ensure that all responses are the fast response\n\t\tif string(message) != \"fast response\" {\n\t\t\tt.Errorf(string(message))\n\t\t}\n\n\t\ttime.Sleep(10)\n\t}\n}\n\n\/\/ TestCanPass proves that tests are running\nfunc TestCanPass(t *testing.T) {\n\tif true != true {\n\t\tt.Errorf(\"true is not true,\\ncheck your premises,\\n consider clojure?\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package download\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"golang.org\/x\/sync\/errgroup\"\n\t\"github.com\/pivotal-cf\/go-pivnet\/logger\"\n\t\"syscall\"\n)\n\n\/\/go:generate counterfeiter -o .\/fakes\/ranger.go --fake-name Ranger . ranger\ntype ranger interface {\n\tBuildRange(contentLength int64) ([]Range, error)\n}\n\n\/\/go:generate counterfeiter -o .\/fakes\/http_client.go --fake-name HTTPClient . httpClient\ntype httpClient interface {\n\tDo(*http.Request) (*http.Response, error)\n}\n\ntype downloadLinkFetcher interface {\n\tNewDownloadLink() (string, error)\n}\n\n\/\/go:generate counterfeiter -o .\/fakes\/bar.go --fake-name Bar . bar\ntype bar interface {\n\tSetTotal(contentLength int64)\n\tSetOutput(output io.Writer)\n\tAdd(totalWritten int) int\n\tKickoff()\n\tFinish()\n\tNewProxyReader(reader io.Reader) io.Reader\n}\n\ntype Client struct {\n\tHTTPClient httpClient\n\tRanger     ranger\n\tBar        bar\n\tLogger     logger.Logger\n}\n\nfunc (c Client) Get(\n\tlocation *os.File,\n\tdownloadLinkFetcher downloadLinkFetcher,\n\tprogressWriter io.Writer,\n) error {\n\tcontentURL, err := downloadLinkFetcher.NewDownloadLink()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := http.NewRequest(\"HEAD\", contentURL, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to construct HEAD request: %s\", err)\n\t}\n\n\tresp, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to make HEAD request: %s\", err)\n\t}\n\n\tcontentURL = resp.Request.URL.String()\n\n\tranges, err := c.Ranger.BuildRange(resp.ContentLength)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to construct range: %s\", err)\n\t}\n\n\tc.Bar.SetOutput(progressWriter)\n\tc.Bar.SetTotal(resp.ContentLength)\n\tc.Bar.Kickoff()\n\n\tdefer c.Bar.Finish()\n\tfileInfo, err := location.Stat()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read information from output file: %s\", err)\n\t}\n\n\tvar g errgroup.Group\n\tfor _, r := range ranges {\n\t\tbyteRange := r\n\n\t\tfileWriter, err := os.OpenFile(location.Name(), os.O_RDWR, fileInfo.Mode())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to open file for writing: %s\", err)\n\t\t}\n\n\t\tg.Go(func() error {\n\t\t\terr := c.retryableRequest(contentURL, byteRange.HTTPHeader, fileWriter, byteRange.Lower, downloadLinkFetcher)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed during retryable request: %s\", err)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\n\tif err := g.Wait(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c Client) retryableRequest(contentURL string, rangeHeader http.Header, fileWriter *os.File, startingByte int64, downloadLinkFetcher downloadLinkFetcher) (error) {\n\tcurrentURL := contentURL\n\tdefer fileWriter.Close()\n\n\tvar err error\nRetry:\n\t_, err = fileWriter.Seek(startingByte, 0)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to seek to correct byte of output file: %s\", err)\n\t}\n\n\treq, err := http.NewRequest(\"GET\", currentURL, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header = rangeHeader\n\n\tresp, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\tif netErr, ok := err.(net.Error); ok {\n\t\t\tif netErr.Temporary() {\n\t\t\t\tgoto Retry\n\t\t\t}\n\t\t}\n\n\t\treturn fmt.Errorf(\"download request failed: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode == http.StatusForbidden {\n\t\tc.Logger.Debug(\"received unsuccessful status code: %d\", logger.Data{\"statusCode\": resp.StatusCode})\n\t\tcurrentURL, err = downloadLinkFetcher.NewDownloadLink()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.Logger.Debug(\"fetched new download url: %d\", logger.Data{\"url\": currentURL})\n\n\t\tgoto Retry\n\t}\n\n\tif resp.StatusCode != http.StatusPartialContent {\n\t\treturn fmt.Errorf(\"during GET unexpected status code was returned: %d\", resp.StatusCode)\n\t}\n\n\tvar proxyReader io.Reader\n\tproxyReader = c.Bar.NewProxyReader(resp.Body)\n\n\tbytesWritten, err := io.Copy(fileWriter, proxyReader)\n\tif err != nil {\n\t\tif err == io.ErrUnexpectedEOF {\n\t\t\tc.Bar.Add(int(-1 * bytesWritten))\n\t\t\tgoto Retry\n\t\t}\n\t\toperr, _ := err.(*net.OpError)\n\t\tif operr.Err.Error() == syscall.ECONNRESET.Error() {\n\t\t\tc.Bar.Add(int(-1 * bytesWritten))\n\t\t\tgoto Retry\n\t\t}\n\t\treturn fmt.Errorf(\"failed to write file during io.Copy: %s\", err)\n\t}\n\n\treturn nil\n}\n<commit_msg>Temporarily add debugging to cloudfront requests<commit_after>package download\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"golang.org\/x\/sync\/errgroup\"\n\t\"github.com\/pivotal-cf\/go-pivnet\/logger\"\n\t\"syscall\"\n)\n\n\/\/go:generate counterfeiter -o .\/fakes\/ranger.go --fake-name Ranger . ranger\ntype ranger interface {\n\tBuildRange(contentLength int64) ([]Range, error)\n}\n\n\/\/go:generate counterfeiter -o .\/fakes\/http_client.go --fake-name HTTPClient . httpClient\ntype httpClient interface {\n\tDo(*http.Request) (*http.Response, error)\n}\n\ntype downloadLinkFetcher interface {\n\tNewDownloadLink() (string, error)\n}\n\n\/\/go:generate counterfeiter -o .\/fakes\/bar.go --fake-name Bar . bar\ntype bar interface {\n\tSetTotal(contentLength int64)\n\tSetOutput(output io.Writer)\n\tAdd(totalWritten int) int\n\tKickoff()\n\tFinish()\n\tNewProxyReader(reader io.Reader) io.Reader\n}\n\ntype Client struct {\n\tHTTPClient httpClient\n\tRanger     ranger\n\tBar        bar\n\tLogger     logger.Logger\n}\n\nfunc (c Client) Get(\n\tlocation *os.File,\n\tdownloadLinkFetcher downloadLinkFetcher,\n\tprogressWriter io.Writer,\n) error {\n\tcontentURL, err := downloadLinkFetcher.NewDownloadLink()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := http.NewRequest(\"HEAD\", contentURL, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to construct HEAD request: %s\", err)\n\t}\n\n\tresp, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to make HEAD request: %s\", err)\n\t}\n\n\tcontentURL = resp.Request.URL.String()\n\n\tranges, err := c.Ranger.BuildRange(resp.ContentLength)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to construct range: %s\", resp)\n\t}\n\n\tc.Bar.SetOutput(progressWriter)\n\tc.Bar.SetTotal(resp.ContentLength)\n\tc.Bar.Kickoff()\n\n\tdefer c.Bar.Finish()\n\tfileInfo, err := location.Stat()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to read information from output file: %s\", err)\n\t}\n\n\tvar g errgroup.Group\n\tfor _, r := range ranges {\n\t\tbyteRange := r\n\n\t\tfileWriter, err := os.OpenFile(location.Name(), os.O_RDWR, fileInfo.Mode())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to open file for writing: %s\", err)\n\t\t}\n\n\t\tg.Go(func() error {\n\t\t\terr := c.retryableRequest(contentURL, byteRange.HTTPHeader, fileWriter, byteRange.Lower, downloadLinkFetcher)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed during retryable request: %s\", err)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\n\tif err := g.Wait(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (c Client) retryableRequest(contentURL string, rangeHeader http.Header, fileWriter *os.File, startingByte int64, downloadLinkFetcher downloadLinkFetcher) (error) {\n\tcurrentURL := contentURL\n\tdefer fileWriter.Close()\n\n\tvar err error\nRetry:\n\t_, err = fileWriter.Seek(startingByte, 0)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to seek to correct byte of output file: %s\", err)\n\t}\n\n\treq, err := http.NewRequest(\"GET\", currentURL, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq.Header = rangeHeader\n\n\tresp, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\tif netErr, ok := err.(net.Error); ok {\n\t\t\tif netErr.Temporary() {\n\t\t\t\tgoto Retry\n\t\t\t}\n\t\t}\n\n\t\treturn fmt.Errorf(\"download request failed: %s\", err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode == http.StatusForbidden {\n\t\tc.Logger.Debug(\"received unsuccessful status code: %d\", logger.Data{\"statusCode\": resp.StatusCode})\n\t\tcurrentURL, err = downloadLinkFetcher.NewDownloadLink()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc.Logger.Debug(\"fetched new download url: %d\", logger.Data{\"url\": currentURL})\n\n\t\tgoto Retry\n\t}\n\n\tif resp.StatusCode != http.StatusPartialContent {\n\t\treturn fmt.Errorf(\"during GET unexpected status code was returned: %d\", resp.StatusCode)\n\t}\n\n\tvar proxyReader io.Reader\n\tproxyReader = c.Bar.NewProxyReader(resp.Body)\n\n\tbytesWritten, err := io.Copy(fileWriter, proxyReader)\n\tif err != nil {\n\t\tif err == io.ErrUnexpectedEOF {\n\t\t\tc.Bar.Add(int(-1 * bytesWritten))\n\t\t\tgoto Retry\n\t\t}\n\t\toperr, _ := err.(*net.OpError)\n\t\tif operr.Err.Error() == syscall.ECONNRESET.Error() {\n\t\t\tc.Bar.Add(int(-1 * bytesWritten))\n\t\t\tgoto Retry\n\t\t}\n\t\treturn fmt.Errorf(\"failed to write file during io.Copy: %s\", err)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/sets\"\n\t\"k8s.io\/test-infra\/prow\/config\"\n\t\"k8s.io\/test-infra\/prow\/config\/org\"\n\t\"k8s.io\/test-infra\/prow\/github\"\n\n\t\"github.com\/ghodss\/yaml\"\n)\n\ntype owners struct {\n\tReviewers []string `json:\"reviewers,omitempty\"`\n\tApprovers []string `json:\"approvers\"`\n}\n\nfunc readInto(path string, i interface{}) error {\n\tbuf, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"read: %v\", err)\n\t}\n\tif err := yaml.Unmarshal(buf, i); err != nil {\n\t\treturn fmt.Errorf(\"unmarshal: %v\", err)\n\t}\n\treturn nil\n}\n\nfunc loadOwners(dir string) (*owners, error) {\n\tvar own owners\n\tif err := readInto(dir+\"\/OWNERS\", &own); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &own, nil\n}\n\nfunc loadOrg(dir string) (*org.Config, error) {\n\tvar cfg org.Config\n\tif err := readInto(dir+\"\/org.yaml\", &cfg); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cfg, nil\n}\n\nfunc testDuplicates(list sets.String) error {\n\tfound := sets.String{}\n\tdups := sets.String{}\n\tall := list.List()\n\tfor _, i := range all {\n\t\tif found.Has(i) {\n\t\t\tdups.Insert(i)\n\t\t}\n\t\tfound.Insert(i)\n\t}\n\tif n := len(dups); n > 0 {\n\t\treturn fmt.Errorf(\"%d duplicate names: %s\", n, strings.Join(dups.List(), \", \"))\n\t}\n\treturn nil\n}\n\nfunc isSorted(list []string) bool {\n\titems := make([]string, len(list))\n\tfor _, l := range list {\n\t\titems = append(items, strings.ToLower(l))\n\t}\n\n\treturn sort.StringsAreSorted(items)\n}\n\nfunc normalize(s sets.String) sets.String {\n\tout := sets.String{}\n\tfor i := range s {\n\t\tout.Insert(github.NormLogin(i))\n\t}\n\treturn out\n}\n\n\/\/ testTeamMembers ensures that a user is not a maintainer and member at the same time,\n\/\/ there are no duplicate names in the list and all users are org members.\nfunc testTeamMembers(teams map[string]org.Team, admins sets.String, orgMembers sets.String, orgName string) []error {\n\tvar errs []error\n\tfor teamName, team := range teams {\n\t\tteamMaintainers := sets.NewString(team.Maintainers...)\n\t\tteamMembers := sets.NewString(team.Members...)\n\n\t\tteamMaintainers = normalize(teamMaintainers)\n\t\tteamMembers = normalize(teamMembers)\n\n\t\t\/\/ check for users in both maintainers and members\n\t\tif both := teamMaintainers.Intersection(teamMembers); len(both) > 0 {\n\t\t\terrs = append(errs, fmt.Errorf(\"The team %s in org %s has users in both maintainer admin and member roles: %s\", teamName, orgName, strings.Join(both.List(), \", \")))\n\t\t}\n\n\t\t\/\/ check for duplicates\n\t\tif err := testDuplicates(teamMaintainers); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"The team %s in org %s has duplicate maintainers: %v\", teamName, orgName, err))\n\t\t}\n\t\tif err := testDuplicates(teamMembers); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"The team %s in org %s has duplicate members: %v\", teamMembers, orgName, err))\n\t\t}\n\n\t\t\/\/ check if all are org members\n\t\tif missing := teamMaintainers.Difference(orgMembers); len(missing) > 0 {\n\t\t\terrs = append(errs, fmt.Errorf(\"The following maintainers of team %s are not %s org members: %s\", teamName, orgName, strings.Join(missing.List(), \", \")))\n\t\t}\n\t\tif missing := teamMembers.Difference(orgMembers); len(missing) > 0 {\n\t\t\terrs = append(errs, fmt.Errorf(\"The following members of team %s are not %s org members: %s\", teamName, orgName, strings.Join(missing.List(), \", \")))\n\t\t}\n\n\t\t\/\/ check if admins are a regular member of team\n\t\tif adminTeamMembers := teamMembers.Intersection(admins); len(adminTeamMembers) > 0 {\n\t\t\terrs = append(errs, fmt.Errorf(\"The team %s in org %s has org admins listed as members; these users should be in the maintainers list instead, and cannot be on the members list: %s\", teamName, orgName, strings.Join(adminTeamMembers.List(), \", \")))\n\t\t}\n\n\t\t\/\/ check if lists are sorted\n\t\tif !isSorted(team.Maintainers) {\n\t\t\terrs = append(errs, fmt.Errorf(\"The team %s in org %s has an unsorted list of maintainers\", teamName, orgName))\n\t\t}\n\t\tif !isSorted(team.Members) {\n\t\t\terrs = append(errs, fmt.Errorf(\"The team %s in org %s has an unsorted list of members\", teamName, orgName))\n\t\t}\n\n\t\tif team.Children != nil {\n\t\t\terrs = append(errs, testTeamMembers(team.Children, admins, orgMembers, orgName)...)\n\t\t}\n\t}\n\treturn errs\n}\n\nfunc testOrg(targetDir string, t *testing.T) {\n\tcfg, err := loadOrg(targetDir)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to load org.yaml: %v\", err)\n\t}\n\town, err := loadOwners(targetDir)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to load OWNERS: %v\", err)\n\t}\n\n\tmembers := normalize(sets.NewString(cfg.Members...))\n\tadmins := normalize(sets.NewString(cfg.Admins...))\n\tallOrgMembers := members.Union(admins)\n\n\treviewers := normalize(sets.NewString(own.Reviewers...))\n\tapprovers := normalize(sets.NewString(own.Approvers...))\n\n\tif n := len(approvers); n < 5 {\n\t\tt.Errorf(\"Require at least 5 approvers, found %d: %s\", n, strings.Join(approvers.List(), \", \"))\n\t}\n\n\tif missing := reviewers.Difference(allOrgMembers); len(missing) > 0 {\n\t\tt.Errorf(\"The following reviewers must be members: %s\", strings.Join(missing.List(), \", \"))\n\t}\n\tif missing := approvers.Difference(allOrgMembers); len(missing) > 0 {\n\t\tt.Errorf(\"The following approvers must be members: %s\", strings.Join(missing.List(), \", \"))\n\t}\n\tif err := testDuplicates(reviewers); err != nil {\n\t\tt.Errorf(\"duplicate reviewers: %v\", err)\n\t}\n\tif err := testDuplicates(approvers); err != nil {\n\t\tt.Errorf(\"duplicate approvers: %v\", err)\n\t}\n}\n\nfunc TestAllOrgs(t *testing.T) {\n\tcfg, err := config.Load(\"config.yaml\", \"\")\n\tif err != nil {\n\t\tt.Fatalf(\"cannot read config.yaml from \/\/config:gen-config.yaml: %v\", err)\n\t}\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tt.Fatalf(\"cannot read config: %v\", err)\n\t}\n\tinfos, err := f.Readdir(0)\n\tif err != nil {\n\t\tt.Fatalf(\"cannot read subdirs: %v\", err)\n\t}\n\tfor _, i := range infos {\n\t\tif !i.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\tn := i.Name()\n\t\tif strings.HasPrefix(n, \"linux_\") || strings.HasPrefix(n, \"darwin_\") {\n\t\t\tcontinue\n\t\t}\n\t\tt.Run(n, func(t *testing.T) {\n\t\t\tif _, ok := cfg.Orgs[n]; !ok {\n\t\t\t\tt.Errorf(\"%s missing from generated config.yaml\", n)\n\t\t\t}\n\t\t\ttestOrg(n, t)\n\t\t})\n\t}\n\n\tfor _, org := range cfg.Orgs {\n\t\tmembers := normalize(sets.NewString(org.Members...))\n\t\tadmins := normalize(sets.NewString(org.Admins...))\n\t\tallOrgMembers := members.Union(admins)\n\n\t\tif both := admins.Intersection(members); len(both) > 0 {\n\t\t\tt.Errorf(\"users in both org admin and member roles: %s\", strings.Join(both.List(), \", \"))\n\t\t}\n\n\t\tif !admins.Has(\"k8s-ci-robot\") {\n\t\t\tt.Errorf(\"k8s-ci-robot must be an admin\")\n\t\t}\n\n\t\tif org.BillingEmail != nil {\n\t\t\tt.Errorf(\"billing_email must be unset\")\n\t\t}\n\n\t\tif err := testDuplicates(admins); err != nil {\n\t\t\tt.Errorf(\"duplicate admins: %v\", err)\n\t\t}\n\t\tif err := testDuplicates(allOrgMembers); err != nil {\n\t\t\tt.Errorf(\"duplicate members: %v\", err)\n\t\t}\n\t\tif !isSorted(org.Admins) {\n\t\t\tt.Errorf(\"admins for %s org are unsorted\", *org.Name)\n\t\t}\n\t\tif !isSorted(org.Members) {\n\t\t\tt.Errorf(\"members for %s org are unsorted\", *org.Name)\n\t\t}\n\n\t\tif errs := testTeamMembers(org.Teams, admins, allOrgMembers, *org.Name); errs != nil {\n\t\t\tfor _, err := range errs {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\n\t}\n}\n<commit_msg>Readd test to enforce non-admins shouldn't be maintainers<commit_after>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/sets\"\n\t\"k8s.io\/test-infra\/prow\/config\"\n\t\"k8s.io\/test-infra\/prow\/config\/org\"\n\t\"k8s.io\/test-infra\/prow\/github\"\n\n\t\"github.com\/ghodss\/yaml\"\n)\n\ntype owners struct {\n\tReviewers []string `json:\"reviewers,omitempty\"`\n\tApprovers []string `json:\"approvers\"`\n}\n\nfunc readInto(path string, i interface{}) error {\n\tbuf, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"read: %v\", err)\n\t}\n\tif err := yaml.Unmarshal(buf, i); err != nil {\n\t\treturn fmt.Errorf(\"unmarshal: %v\", err)\n\t}\n\treturn nil\n}\n\nfunc loadOwners(dir string) (*owners, error) {\n\tvar own owners\n\tif err := readInto(dir+\"\/OWNERS\", &own); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &own, nil\n}\n\nfunc loadOrg(dir string) (*org.Config, error) {\n\tvar cfg org.Config\n\tif err := readInto(dir+\"\/org.yaml\", &cfg); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &cfg, nil\n}\n\nfunc testDuplicates(list sets.String) error {\n\tfound := sets.String{}\n\tdups := sets.String{}\n\tall := list.List()\n\tfor _, i := range all {\n\t\tif found.Has(i) {\n\t\t\tdups.Insert(i)\n\t\t}\n\t\tfound.Insert(i)\n\t}\n\tif n := len(dups); n > 0 {\n\t\treturn fmt.Errorf(\"%d duplicate names: %s\", n, strings.Join(dups.List(), \", \"))\n\t}\n\treturn nil\n}\n\nfunc isSorted(list []string) bool {\n\titems := make([]string, len(list))\n\tfor _, l := range list {\n\t\titems = append(items, strings.ToLower(l))\n\t}\n\n\treturn sort.StringsAreSorted(items)\n}\n\nfunc normalize(s sets.String) sets.String {\n\tout := sets.String{}\n\tfor i := range s {\n\t\tout.Insert(github.NormLogin(i))\n\t}\n\treturn out\n}\n\n\/\/ testTeamMembers ensures that a user is not a maintainer and member at the same time,\n\/\/ there are no duplicate names in the list and all users are org members.\nfunc testTeamMembers(teams map[string]org.Team, admins sets.String, orgMembers sets.String, orgName string) []error {\n\tvar errs []error\n\tfor teamName, team := range teams {\n\t\tteamMaintainers := sets.NewString(team.Maintainers...)\n\t\tteamMembers := sets.NewString(team.Members...)\n\n\t\tteamMaintainers = normalize(teamMaintainers)\n\t\tteamMembers = normalize(teamMembers)\n\n\t\t\/\/ check for non-admins in maintainers list\n\t\tif nonAdminMaintainers := teamMaintainers.Difference(admins); len(nonAdminMaintainers) > 0 {\n\t\t\terrs = append(errs, fmt.Errorf(\"The team %s in org %s has non-admins listed as maintainers; these users should be in the members list instead: %s\", teamName, orgName, strings.Join(nonAdminMaintainers.List(), \",\")))\n\t\t}\n\n\t\t\/\/ check for users in both maintainers and members\n\t\tif both := teamMaintainers.Intersection(teamMembers); len(both) > 0 {\n\t\t\terrs = append(errs, fmt.Errorf(\"The team %s in org %s has users in both maintainer admin and member roles: %s\", teamName, orgName, strings.Join(both.List(), \", \")))\n\t\t}\n\n\t\t\/\/ check for duplicates\n\t\tif err := testDuplicates(teamMaintainers); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"The team %s in org %s has duplicate maintainers: %v\", teamName, orgName, err))\n\t\t}\n\t\tif err := testDuplicates(teamMembers); err != nil {\n\t\t\terrs = append(errs, fmt.Errorf(\"The team %s in org %s has duplicate members: %v\", teamMembers, orgName, err))\n\t\t}\n\n\t\t\/\/ check if all are org members\n\t\tif missing := teamMembers.Difference(orgMembers); len(missing) > 0 {\n\t\t\terrs = append(errs, fmt.Errorf(\"The following members of team %s are not %s org members: %s\", teamName, orgName, strings.Join(missing.List(), \", \")))\n\t\t}\n\n\t\t\/\/ check if admins are a regular member of team\n\t\tif adminTeamMembers := teamMembers.Intersection(admins); len(adminTeamMembers) > 0 {\n\t\t\terrs = append(errs, fmt.Errorf(\"The team %s in org %s has org admins listed as members; these users should be in the maintainers list instead, and cannot be on the members list: %s\", teamName, orgName, strings.Join(adminTeamMembers.List(), \", \")))\n\t\t}\n\n\t\t\/\/ check if lists are sorted\n\t\tif !isSorted(team.Maintainers) {\n\t\t\terrs = append(errs, fmt.Errorf(\"The team %s in org %s has an unsorted list of maintainers\", teamName, orgName))\n\t\t}\n\t\tif !isSorted(team.Members) {\n\t\t\terrs = append(errs, fmt.Errorf(\"The team %s in org %s has an unsorted list of members\", teamName, orgName))\n\t\t}\n\n\t\tif team.Children != nil {\n\t\t\terrs = append(errs, testTeamMembers(team.Children, admins, orgMembers, orgName)...)\n\t\t}\n\t}\n\treturn errs\n}\n\nfunc testOrg(targetDir string, t *testing.T) {\n\tcfg, err := loadOrg(targetDir)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to load org.yaml: %v\", err)\n\t}\n\town, err := loadOwners(targetDir)\n\tif err != nil {\n\t\tt.Fatalf(\"failed to load OWNERS: %v\", err)\n\t}\n\n\tmembers := normalize(sets.NewString(cfg.Members...))\n\tadmins := normalize(sets.NewString(cfg.Admins...))\n\tallOrgMembers := members.Union(admins)\n\n\treviewers := normalize(sets.NewString(own.Reviewers...))\n\tapprovers := normalize(sets.NewString(own.Approvers...))\n\n\tif n := len(approvers); n < 5 {\n\t\tt.Errorf(\"Require at least 5 approvers, found %d: %s\", n, strings.Join(approvers.List(), \", \"))\n\t}\n\n\tif missing := reviewers.Difference(allOrgMembers); len(missing) > 0 {\n\t\tt.Errorf(\"The following reviewers must be members: %s\", strings.Join(missing.List(), \", \"))\n\t}\n\tif missing := approvers.Difference(allOrgMembers); len(missing) > 0 {\n\t\tt.Errorf(\"The following approvers must be members: %s\", strings.Join(missing.List(), \", \"))\n\t}\n\tif err := testDuplicates(reviewers); err != nil {\n\t\tt.Errorf(\"duplicate reviewers: %v\", err)\n\t}\n\tif err := testDuplicates(approvers); err != nil {\n\t\tt.Errorf(\"duplicate approvers: %v\", err)\n\t}\n}\n\nfunc TestAllOrgs(t *testing.T) {\n\tcfg, err := config.Load(\"config.yaml\", \"\")\n\tif err != nil {\n\t\tt.Fatalf(\"cannot read config.yaml from \/\/config:gen-config.yaml: %v\", err)\n\t}\n\tf, err := os.Open(\".\")\n\tif err != nil {\n\t\tt.Fatalf(\"cannot read config: %v\", err)\n\t}\n\tinfos, err := f.Readdir(0)\n\tif err != nil {\n\t\tt.Fatalf(\"cannot read subdirs: %v\", err)\n\t}\n\tfor _, i := range infos {\n\t\tif !i.IsDir() {\n\t\t\tcontinue\n\t\t}\n\t\tn := i.Name()\n\t\tif strings.HasPrefix(n, \"linux_\") || strings.HasPrefix(n, \"darwin_\") {\n\t\t\tcontinue\n\t\t}\n\t\tt.Run(n, func(t *testing.T) {\n\t\t\tif _, ok := cfg.Orgs[n]; !ok {\n\t\t\t\tt.Errorf(\"%s missing from generated config.yaml\", n)\n\t\t\t}\n\t\t\ttestOrg(n, t)\n\t\t})\n\t}\n\n\tfor _, org := range cfg.Orgs {\n\t\tmembers := normalize(sets.NewString(org.Members...))\n\t\tadmins := normalize(sets.NewString(org.Admins...))\n\t\tallOrgMembers := members.Union(admins)\n\n\t\tif both := admins.Intersection(members); len(both) > 0 {\n\t\t\tt.Errorf(\"users in both org admin and member roles: %s\", strings.Join(both.List(), \", \"))\n\t\t}\n\n\t\tif !admins.Has(\"k8s-ci-robot\") {\n\t\t\tt.Errorf(\"k8s-ci-robot must be an admin\")\n\t\t}\n\n\t\tif org.BillingEmail != nil {\n\t\t\tt.Errorf(\"billing_email must be unset\")\n\t\t}\n\n\t\tif err := testDuplicates(admins); err != nil {\n\t\t\tt.Errorf(\"duplicate admins: %v\", err)\n\t\t}\n\t\tif err := testDuplicates(allOrgMembers); err != nil {\n\t\t\tt.Errorf(\"duplicate members: %v\", err)\n\t\t}\n\t\tif !isSorted(org.Admins) {\n\t\t\tt.Errorf(\"admins for %s org are unsorted\", *org.Name)\n\t\t}\n\t\tif !isSorted(org.Members) {\n\t\t\tt.Errorf(\"members for %s org are unsorted\", *org.Name)\n\t\t}\n\n\t\tif errs := testTeamMembers(org.Teams, admins, allOrgMembers, *org.Name); errs != nil {\n\t\t\tfor _, err := range errs {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t}\n\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n)\n\n\/\/ EnvFetcher is an implementation of the Fetcher type for communicating with\n\/\/ the system's environment.\n\/\/\n\/\/ It is safe to use across multiple goroutines.\ntype EnvFetcher struct {\n\t\/\/ vmu guards read\/write access to vals\n\tvmu sync.Mutex\n\t\/\/ vals maintains a local cache of the system's enviornment variables\n\t\/\/ for fast repeat lookups of a given key.\n\tvals map[string]string\n}\n\n\/\/ NewEnvFetcher returns a new *EnvFetcher.\nfunc NewEnvFetcher() *EnvFetcher {\n\treturn &EnvFetcher{\n\t\tvals: make(map[string]string),\n\t}\n}\n\n\/\/ Get returns the value associated with the given key as stored in the local\n\/\/ cache, or in the operating system's environment variables.\n\/\/\n\/\/ If there was a cache-hit, the value will be returned from the cache, skipping\n\/\/ a check against os.Getenv. Otherwise, the value will be fetched from the\n\/\/ system, stored in the cache, and then returned. If no value was present in\n\/\/ the cache or in the system, an empty string will be returned.\n\/\/\n\/\/ Get is safe to call across multiple goroutines.\nfunc (e *EnvFetcher) Get(key string) (val string) {\n\te.vmu.Lock()\n\tdefer e.vmu.Unlock()\n\n\tif i, ok := e.vals[key]; ok {\n\t\treturn i\n\t}\n\n\tv := os.Getenv(key)\n\te.vals[key] = v\n\n\treturn v\n}\n\n\/\/ Bool\treturns the boolean state assosicated with a given key, or the value\n\/\/ \"def\", if no value was assosicated.\n\/\/\n\/\/ The \"boolean state assosicated with a given key\" is defined as the\n\/\/ case-insensitive string comparsion with the following:\n\/\/\n\/\/ 1) true if...\n\/\/   \"true\", \"1\", \"on\", \"yes\", or \"t\"\n\/\/ 2) false if...\n\/\/   \"false\", \"0\", \"off\", \"no\", \"f\", or otherwise.\nfunc (e *EnvFetcher) Bool(key string, def bool) (val bool) {\n\ts := e.String(key)\n\tif len(s) == 0 {\n\t\treturn def\n\t}\n\n\tswitch strings.ToLower(s) {\n\tcase \"true\", \"1\", \"on\", \"yes\", \"t\":\n\t\treturn true\n\tcase \"false\", \"0\", \"off\", \"no\", \"f\":\n\t\treturn false\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\/\/ Set replaces a given key-value pair in the cache (if previously present in\n\/\/ the cache) and in the system's environment variables. It returns an error if\n\/\/ one was encountered in setting the environment variable, or `nil` if\n\/\/ successful.\n\/\/\n\/\/ Note: this method is a temporary measure while some of the old tests still\n\/\/ rely on this mutable behavior.\nfunc (e *EnvFetcher) Set(key, val string) error {\n\te.vmu.Lock()\n\tdefer e.vmu.Unlock()\n\n\tif _, ok := e.vals[key]; ok {\n\t\te.vals[key] = val\n\t}\n\n\treturn os.Setenv(key, val)\n}\n\n\/\/ SetAll replaces all key-value pairs with the given set, but does not modify\n\/\/ the system's environment.\n\/\/\n\/\/ Note: this method is a temporary measure while some of the old tests still\n\/\/ rely on this mutable behavior.\nfunc (e *EnvFetcher) SetAll(env map[string]string) {\n\te.vmu.Lock()\n\tdefer e.vmu.Unlock()\n\n\te.vals = make(map[string]string)\n\tfor k, v := range env {\n\t\te.vals[k] = v\n\t}\n}\n<commit_msg>config\/env: fix outdated reference to EnvFetcher.String<commit_after>package config\n\nimport (\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n)\n\n\/\/ EnvFetcher is an implementation of the Fetcher type for communicating with\n\/\/ the system's environment.\n\/\/\n\/\/ It is safe to use across multiple goroutines.\ntype EnvFetcher struct {\n\t\/\/ vmu guards read\/write access to vals\n\tvmu sync.Mutex\n\t\/\/ vals maintains a local cache of the system's enviornment variables\n\t\/\/ for fast repeat lookups of a given key.\n\tvals map[string]string\n}\n\n\/\/ NewEnvFetcher returns a new *EnvFetcher.\nfunc NewEnvFetcher() *EnvFetcher {\n\treturn &EnvFetcher{\n\t\tvals: make(map[string]string),\n\t}\n}\n\n\/\/ Get returns the value associated with the given key as stored in the local\n\/\/ cache, or in the operating system's environment variables.\n\/\/\n\/\/ If there was a cache-hit, the value will be returned from the cache, skipping\n\/\/ a check against os.Getenv. Otherwise, the value will be fetched from the\n\/\/ system, stored in the cache, and then returned. If no value was present in\n\/\/ the cache or in the system, an empty string will be returned.\n\/\/\n\/\/ Get is safe to call across multiple goroutines.\nfunc (e *EnvFetcher) Get(key string) (val string) {\n\te.vmu.Lock()\n\tdefer e.vmu.Unlock()\n\n\tif i, ok := e.vals[key]; ok {\n\t\treturn i\n\t}\n\n\tv := os.Getenv(key)\n\te.vals[key] = v\n\n\treturn v\n}\n\n\/\/ Bool\treturns the boolean state assosicated with a given key, or the value\n\/\/ \"def\", if no value was assosicated.\n\/\/\n\/\/ The \"boolean state assosicated with a given key\" is defined as the\n\/\/ case-insensitive string comparsion with the following:\n\/\/\n\/\/ 1) true if...\n\/\/   \"true\", \"1\", \"on\", \"yes\", or \"t\"\n\/\/ 2) false if...\n\/\/   \"false\", \"0\", \"off\", \"no\", \"f\", or otherwise.\nfunc (e *EnvFetcher) Bool(key string, def bool) (val bool) {\n\ts := e.Get(key)\n\tif len(s) == 0 {\n\t\treturn def\n\t}\n\n\tswitch strings.ToLower(s) {\n\tcase \"true\", \"1\", \"on\", \"yes\", \"t\":\n\t\treturn true\n\tcase \"false\", \"0\", \"off\", \"no\", \"f\":\n\t\treturn false\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\/\/ Set replaces a given key-value pair in the cache (if previously present in\n\/\/ the cache) and in the system's environment variables. It returns an error if\n\/\/ one was encountered in setting the environment variable, or `nil` if\n\/\/ successful.\n\/\/\n\/\/ Note: this method is a temporary measure while some of the old tests still\n\/\/ rely on this mutable behavior.\nfunc (e *EnvFetcher) Set(key, val string) error {\n\te.vmu.Lock()\n\tdefer e.vmu.Unlock()\n\n\tif _, ok := e.vals[key]; ok {\n\t\te.vals[key] = val\n\t}\n\n\treturn os.Setenv(key, val)\n}\n\n\/\/ SetAll replaces all key-value pairs with the given set, but does not modify\n\/\/ the system's environment.\n\/\/\n\/\/ Note: this method is a temporary measure while some of the old tests still\n\/\/ rely on this mutable behavior.\nfunc (e *EnvFetcher) SetAll(env map[string]string) {\n\te.vmu.Lock()\n\tdefer e.vmu.Unlock()\n\n\te.vals = make(map[string]string)\n\tfor k, v := range env {\n\t\te.vals[k] = v\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 Keybase Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD\n\/\/ license that can be found in the LICENSE file.\n\npackage libhttpserver\n\nimport (\n\t\"net\/http\"\n\t\"strings\"\n)\n\ntype contentTypeOverridingResponseWriter struct {\n\toriginal http.ResponseWriter\n}\n\nvar _ http.ResponseWriter = (*contentTypeOverridingResponseWriter)(nil)\n\nfunc newContentTypeOverridingResponseWriter(\n\toriginal http.ResponseWriter) *contentTypeOverridingResponseWriter {\n\treturn &contentTypeOverridingResponseWriter{\n\t\toriginal: original,\n\t}\n}\n\nfunc (w *contentTypeOverridingResponseWriter) calculateOverride(\n\tmimeType string) (newMimeType, disposition string) {\n\t\/\/ Send text\/plain for all HTML and JS files to avoid them being executed\n\t\/\/ by the frontend WebView.\n\tty := strings.ToLower(mimeType)\n\tswitch {\n\t\/\/ First anything textual as text\/plain, also javascript.\n\tcase strings.HasPrefix(ty, \"text\/\") ||\n\t\tty == \"application\/javascript\":\n\t\treturn \"text\/plain\", \"inline\"\n\t\/\/ Rest of html, xml. (note that the type may be e.g. application\/xhtml+xml)\n\tcase strings.Contains(ty, \"xml\") ||\n\t\tstrings.Contains(ty, \"html\"):\n\t\treturn \"text\/plain\", \"attachment\"\n\t\/\/ Pass multimedia types through, and pdf too.\n\tcase strings.HasPrefix(ty, \"audio\/\") ||\n\t\tstrings.HasPrefix(ty, \"image\/\") ||\n\t\tstrings.HasPrefix(ty, \"video\/\") ||\n\t\tty == \"application\/pdf\":\n\t\treturn ty, \"inline\"\n\t\/\/ Otherwise default to text + attachment.\n\tdefault:\n\t\treturn \"text\/plain\", \"attachment\"\n\t}\n}\n\nfunc (w *contentTypeOverridingResponseWriter) override() {\n\tt := w.original.Header().Get(\"Content-Type\")\n\tif len(t) > 0 {\n\t\tct, disp := w.calculateOverride(t)\n\t\tw.original.Header().Set(\"Content-Type\", ct)\n\t\tw.original.Header().Set(\"Content-Disposition\", disp)\n\t}\n\tw.original.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n}\n\nfunc (w *contentTypeOverridingResponseWriter) Header() http.Header {\n\treturn w.original.Header()\n}\n\nfunc (w *contentTypeOverridingResponseWriter) WriteHeader(statusCode int) {\n\tw.override()\n\tw.original.WriteHeader(statusCode)\n}\n\nfunc (w *contentTypeOverridingResponseWriter) Write(data []byte) (int, error) {\n\tw.override()\n\treturn w.original.Write(data)\n}\n\nvar additionalMimeTypes = map[string]string{\n\t\".go\":    \"text\/plain\",\n\t\".py\":    \"text\/plain\",\n\t\".zsh\":   \"text\/plain\",\n\t\".fish\":  \"text\/plain\",\n\t\".cs\":    \"text\/plain\",\n\t\".rb\":    \"text\/plain\",\n\t\".m\":     \"text\/plain\",\n\t\".mm\":    \"text\/plain\",\n\t\".swift\": \"text\/plain\",\n\t\".flow\":  \"text\/plain\",\n\t\".php\":   \"text\/plain\",\n\t\".pl\":    \"text\/plain\",\n\t\".sh\":    \"text\/plain\",\n\t\".js\":    \"text\/plain\",\n\t\".json\":  \"text\/plain\",\n\t\".sql\":   \"text\/plain\",\n\t\".rs\":    \"text\/plain\",\n\t\".xml\":   \"text\/plain\",\n\t\".tex\":   \"text\/plain\",\n\t\".pub\":   \"text\/plain\",\n}\n<commit_msg>libhttpserver: Get mime types right for even more filetypes<commit_after>\/\/ Copyright 2018 Keybase Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD\n\/\/ license that can be found in the LICENSE file.\n\npackage libhttpserver\n\nimport (\n\t\"net\/http\"\n\t\"strings\"\n)\n\ntype contentTypeOverridingResponseWriter struct {\n\toriginal http.ResponseWriter\n}\n\nvar _ http.ResponseWriter = (*contentTypeOverridingResponseWriter)(nil)\n\nfunc newContentTypeOverridingResponseWriter(\n\toriginal http.ResponseWriter) *contentTypeOverridingResponseWriter {\n\treturn &contentTypeOverridingResponseWriter{\n\t\toriginal: original,\n\t}\n}\n\n\/\/ supportedContentTypes has exceptions to the libmime stuff because some types\n\/\/ need special handling or are unsupported by frontend. The boolean value\n\/\/ decides on whether this will be shown inline or as an attachment.\n\/\/ We don't want to render SVG unless that has been audited, even if\n\/\/ the file lacks a .svg extension.\nvar supportedContentTypes = map[string]bool{\n\t\/\/ Media\n\t\"image\/tiff\":         false,\n\t\"image\/x-jng\":        false,\n\t\"image\/vnd.wap.wbmp\": false,\n\t\"image\/svg+xml\":      false,\n}\n\n\/\/ displayInlineDefault decides on the Content-Disposition value (inline vs attachment) for\n\/\/ the given mimeType by consulting the supportedContentTypes map and using the defaultValue\n\/\/ parameter.\nfunc displayInlineDefault(defaultValue bool, mimeType string) string {\n\tres, found := supportedContentTypes[mimeType]\n\tif (found && res) || (!found && defaultValue) {\n\t\treturn \"inline\"\n\t}\n\treturn \"attachment\"\n}\n\nfunc (w *contentTypeOverridingResponseWriter) calculateOverride(\n\tmimeType string) (newMimeType, disposition string) {\n\t\/\/ Send text\/plain for all HTML and JS files to avoid them being executed\n\t\/\/ by the frontend WebView.\n\tty := strings.ToLower(mimeType)\n\tswitch {\n\t\/\/ First anything textual as text\/plain.\n\t\/\/ Javascript is set to plain text by additionalMimeTypes map.\n\t\/\/ If text\/something-dangerous would get here, we set it to plaintext.\n\t\/\/ If application\/javascript somehow gets here it would be handled safely\n\t\/\/ by the default handler below.\n\tcase strings.HasPrefix(ty, \"text\/\"):\n\t\treturn \"text\/plain\", \"inline\"\n\t\/\/ Pass multimedia types through, and pdf too.\n\t\/\/ Some types get special handling here and are not shown inline (e.g. SVG).\n\tcase strings.HasPrefix(ty, \"audio\/\") ||\n\t\tstrings.HasPrefix(ty, \"image\/\") ||\n\t\tstrings.HasPrefix(ty, \"video\/\") ||\n\t\tty == \"application\/pdf\":\n\t\treturn ty, displayInlineDefault(true, ty)\n\t\/\/ Otherwise default to text + attachment.\n\t\/\/ This is safe for all files.\n\tdefault:\n\t\treturn \"text\/plain\", \"attachment\"\n\t}\n}\n\nfunc (w *contentTypeOverridingResponseWriter) override() {\n\tt := w.original.Header().Get(\"Content-Type\")\n\tif len(t) > 0 {\n\t\tct, disp := w.calculateOverride(t)\n\t\tw.original.Header().Set(\"Content-Type\", ct)\n\t\tw.original.Header().Set(\"Content-Disposition\", disp)\n\t}\n\tw.original.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n}\n\nfunc (w *contentTypeOverridingResponseWriter) Header() http.Header {\n\treturn w.original.Header()\n}\n\nfunc (w *contentTypeOverridingResponseWriter) WriteHeader(statusCode int) {\n\tw.override()\n\tw.original.WriteHeader(statusCode)\n}\n\nfunc (w *contentTypeOverridingResponseWriter) Write(data []byte) (int, error) {\n\tw.override()\n\treturn w.original.Write(data)\n}\n\nvar additionalMimeTypes = map[string]string{\n\t\".go\":    \"text\/plain\",\n\t\".py\":    \"text\/plain\",\n\t\".zsh\":   \"text\/plain\",\n\t\".fish\":  \"text\/plain\",\n\t\".cs\":    \"text\/plain\",\n\t\".rb\":    \"text\/plain\",\n\t\".m\":     \"text\/plain\",\n\t\".mm\":    \"text\/plain\",\n\t\".swift\": \"text\/plain\",\n\t\".flow\":  \"text\/plain\",\n\t\".php\":   \"text\/plain\",\n\t\".pl\":    \"text\/plain\",\n\t\".pm\":    \"text\/plain\",\n\t\".sh\":    \"text\/plain\",\n\t\".js\":    \"text\/plain\",\n\t\".json\":  \"text\/plain\",\n\t\".sql\":   \"text\/plain\",\n\t\".rs\":    \"text\/plain\",\n\t\".xml\":   \"text\/plain\",\n\t\".tex\":   \"text\/plain\",\n\t\".pub\":   \"text\/plain\",\n\t\".atom\":  \"text\/plain\",\n\t\".xhtml\": \"text\/plain\",\n\t\".rss\":   \"text\/plain\",\n\t\".tcl\":   \"text\/plain\",\n\t\".tk\":    \"text\/plain\",\n}\n<|endoftext|>"}
{"text":"<commit_before>package node\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/mosaicnetworks\/babble\/src\/common\"\n\t\"github.com\/mosaicnetworks\/babble\/src\/crypto\"\n\t\"github.com\/mosaicnetworks\/babble\/src\/peers\"\n)\n\nfunc TestMonologue(t *testing.T) {\n\tlogger := common.NewTestLogger(t)\n\tkeys, peers := initPeers(1)\n\tnodes := initNodes(keys, peers, 100000, 1000, \"inmem\", 5*time.Millisecond, logger, t)\n\t\/\/defer drawGraphs(nodes, t)\n\n\ttarget := 50\n\terr := gossip(nodes, target, true, 3*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcheckGossip(nodes, 0, t)\n}\n\nfunc TestJoinRequest(t *testing.T) {\n\tlogger := common.NewTestLogger(t)\n\tkeys, peerSet := initPeers(4)\n\tnodes := initNodes(keys, peerSet, 1000000, 1000, \"inmem\", 5*time.Millisecond, logger, t)\n\tdefer shutdownNodes(nodes)\n\t\/\/defer drawGraphs(nodes, t)\n\n\ttarget := 30\n\terr := gossip(nodes, target, false, 3*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckGossip(nodes, 0, t)\n\n\tkey, _ := crypto.GenerateECDSAKey()\n\tpeer := peers.NewPeer(\n\t\tfmt.Sprintf(\"0x%X\", crypto.FromECDSAPub(&key.PublicKey)),\n\t\tfmt.Sprint(\"127.0.0.1:4242\"),\n\t\t\"monika\",\n\t)\n\tnewNode := newNode(peer, key, \"new node\", peerSet, 1000, 1000, \"inmem\", 5*time.Millisecond, logger, t)\n\tdefer newNode.Shutdown()\n\n\terr = newNode.join()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/Gossip some more\n\tsecondTarget := target + 30\n\terr = bombardAndWait(nodes, secondTarget, 6*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckGossip(nodes, 0, t)\n\tcheckPeerSets(nodes, t)\n}\n\nfunc TestLeaveRequest(t *testing.T) {\n\tn := 1\n\tf := func() {\n\t\tlogger := common.NewTestLogger(t)\n\t\tkeys, peerSet := initPeers(n)\n\t\tnodes := initNodes(keys, peerSet, 1000000, 1000, \"inmem\", 5*time.Millisecond, logger, t)\n\t\tdefer shutdownNodes(nodes)\n\t\t\/\/defer drawGraphs(nodes, t)\n\n\t\ttarget := 30\n\t\terr := gossip(nodes, target, false, 3*time.Second)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tcheckGossip(nodes, 0, t)\n\n\t\tleavingNode := nodes[n-1]\n\n\t\terr = leavingNode.Leave()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif n == 1 {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/Gossip some more\n\t\tsecondTarget := target + 50\n\t\terr = bombardAndWait(nodes[0:n-1], secondTarget, 6*time.Second)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tcheckGossip(nodes[0:n-1], 0, t)\n\t\tcheckPeerSets(nodes[0:n-1], t)\n\t}\n\n\tfor n <= 4 {\n\t\tf()\n\t\tn++\n\t}\n}\n\nfunc TestSuccessiveJoinRequest(t *testing.T) {\n\tlogger := common.NewTestLogger(t)\n\tkeys, peerSet := initPeers(1)\n\n\tnode0 := newNode(peerSet.Peers[0], keys[0], \"new node\", peerSet, 1000000, 400, \"inmem\", 10*time.Millisecond, logger, t)\n\tdefer node0.Shutdown()\n\tnode0.RunAsync(true)\n\n\tnodes := []*Node{node0}\n\t\/\/defer drawGraphs(nodes, t)\n\n\ttarget := 20\n\tfor i := 1; i <= 3; i++ {\n\t\tpeerSet := peers.NewPeerSet(node0.GetPeers())\n\n\t\tkey, _ := crypto.GenerateECDSAKey()\n\t\tpeer := peers.NewPeer(\n\t\t\tfmt.Sprintf(\"0x%X\", crypto.FromECDSAPub(&key.PublicKey)),\n\t\t\tfmt.Sprintf(\"127.0.0.1:%d\", 4240+i),\n\t\t\t\"monika\",\n\t\t)\n\t\tnewNode := newNode(peer, key, \"new node\", peerSet, 1000000, 400, \"inmem\", 10*time.Millisecond, logger, t)\n\n\t\tlogger.Debugf(\"starting new node %d, %d\", i, newNode.ID())\n\t\tdefer newNode.Shutdown()\n\t\tnewNode.RunAsync(true)\n\n\t\tnodes = append(nodes, newNode)\n\n\t\t\/\/Gossip some more\n\t\terr := bombardAndWait(nodes, target, 10*time.Second)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tstart := newNode.core.hg.FirstConsensusRound\n\t\tcheckGossip(nodes, *start, t)\n\n\t\ttarget = target + 40\n\t}\n}\n\nfunc TestSuccessiveLeaveRequest(t *testing.T) {\n\tn := 4\n\n\tlogger := common.NewTestLogger(t)\n\tkeys, peerSet := initPeers(n)\n\tnodes := initNodes(keys, peerSet, 1000000, 1000, \"inmem\", 5*time.Millisecond, logger, t)\n\tdefer shutdownNodes(nodes)\n\n\ttarget := 0\n\n\tf := func() {\n\t\t\/\/defer drawGraphs(nodes, t)\n\t\ttarget += 30\n\t\terr := gossip(nodes, target, false, 3*time.Second)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tcheckGossip(nodes, 0, t)\n\n\t\tleavingNode := nodes[n-1]\n\n\t\terr = leavingNode.Leave()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif n == 1 {\n\t\t\treturn\n\t\t}\n\n\t\tnodes = nodes[0 : n-1]\n\n\t\t\/\/Gossip some more\n\t\ttarget += 50\n\t\terr = bombardAndWait(nodes, target, 6*time.Second)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tcheckGossip(nodes, 0, t)\n\t\tcheckPeerSets(nodes, t)\n\t}\n\n\tfor n > 0 {\n\t\tf()\n\t\tn--\n\t}\n}\n\nfunc TestSimultaneusLeaveRequest(t *testing.T) {\n\tlogger := common.NewTestLogger(t)\n\tkeys, peerSet := initPeers(4)\n\tnodes := initNodes(keys, peerSet, 1000000, 1000, \"inmem\", 5*time.Millisecond, logger, t)\n\tdefer shutdownNodes(nodes)\n\t\/\/defer drawGraphs(nodes, t)\n\n\ttarget := 30\n\terr := gossip(nodes, target, false, 3*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckGossip(nodes, 0, t)\n\n\tleavingNode := nodes[3]\n\tleavingNode2 := nodes[2]\n\n\terr = leavingNode.Leave()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = leavingNode2.Leave()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/Gossip some more\n\tsecondTarget := target + 50\n\terr = bombardAndWait(nodes[0:2], secondTarget, 6*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckGossip(nodes[0:2], 0, t)\n\tcheckPeerSets(nodes[0:2], t)\n}\n\nfunc TestJoinLeaveRequest(t *testing.T) {\n\tlogger := common.NewTestLogger(t)\n\tkeys, peerSet := initPeers(4)\n\tnodes := initNodes(keys, peerSet, 1000000, 1000, \"inmem\", 5*time.Millisecond, logger, t)\n\tdefer shutdownNodes(nodes)\n\t\/\/defer drawGraphs(nodes, t)\n\n\ttarget := 30\n\terr := gossip(nodes, target, false, 3*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckGossip(nodes, 0, t)\n\n\tleavingNode := nodes[3]\n\n\terr = leavingNode.Leave()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tkey, _ := crypto.GenerateECDSAKey()\n\tpeer := peers.NewPeer(\n\t\tfmt.Sprintf(\"0x%X\", crypto.FromECDSAPub(&key.PublicKey)),\n\t\tfmt.Sprint(\"127.0.0.1:4242\"),\n\t\t\"new node\",\n\t)\n\tnewNode := newNode(peer, key, peer.Moniker, peerSet, 1000000, 400, \"inmem\", 10*time.Millisecond, logger, t)\n\tdefer newNode.Shutdown()\n\n\t\/\/ Run parallel routine to check newNode eventually reaches CatchingUp state.\n\ttimeout := time.After(6 * time.Second)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-timeout:\n\t\t\t\tt.Fatalf(\"Timeout waiting for newNode to enter CatchingUp state\")\n\t\t\tdefault:\n\t\t\t}\n\t\t\tif newNode.getState() == CatchingUp {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\tnewNode.RunAsync(true)\n\n\t\/\/ remove leaving node\n\tnodes = nodes[0:3]\n\n\t\/\/ add new node\n\t\/\/ nodes = append(nodes, newNode)\n\n\t\/\/Gossip some more\n\tsecondTarget := target + 50\n\terr = bombardAndWait(nodes, secondTarget, 6*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckGossip(nodes, 0, t)\n\tcheckPeerSets(nodes, t)\n\n\tpeerSet2 := nodes[0].GetPeers()\n\n\tif len(peerSet2) != 4 {\n\t\tt.Fatalf(\"Invalid peerSet size\")\n\t}\n}\n\nfunc TestJoinFull(t *testing.T) {\n\tlogger := common.NewTestLogger(t)\n\tkeys, peerSet := initPeers(4)\n\tinitialNodes := initNodes(keys, peerSet, 1000000, 400, \"inmem\", 10*time.Millisecond, logger, t)\n\tdefer shutdownNodes(initialNodes)\n\n\ttarget := 30\n\terr := gossip(initialNodes, target, false, 6*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckGossip(initialNodes, 0, t)\n\n\tkey, _ := crypto.GenerateECDSAKey()\n\tpeer := peers.NewPeer(\n\t\tfmt.Sprintf(\"0x%X\", crypto.FromECDSAPub(&key.PublicKey)),\n\t\tfmt.Sprint(\"127.0.0.1:4242\"),\n\t\t\"monika\",\n\t)\n\tnewNode := newNode(peer, key, \"new node\", peerSet, 1000000, 400, \"inmem\", 10*time.Millisecond, logger, t)\n\tdefer newNode.Shutdown()\n\n\t\/\/Run parallel routine to check newNode eventually reaches CatchingUp state.\n\ttimeout := time.After(6 * time.Second)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-timeout:\n\t\t\t\tt.Fatalf(\"Timeout waiting for newNode to enter CatchingUp state\")\n\t\t\tdefault:\n\t\t\t}\n\t\t\tif newNode.getState() == CatchingUp {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\tnewNode.RunAsync(true)\n\n\tnodes := append(initialNodes, newNode)\n\n\t\/\/defer drawGraphs(nodes, t)\n\n\t\/\/Gossip some more\n\tsecondTarget := target + 50\n\terr = bombardAndWait(nodes, secondTarget, 10*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tstart := newNode.core.hg.FirstConsensusRound\n\tcheckGossip(nodes, *start, t)\n\tcheckPeerSets(nodes, t)\n}\n\nfunc checkPeerSets(nodes []*Node, t *testing.T) {\n\tnode0FP, err := nodes[0].core.hg.Store.GetAllPeerSets()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor i := range nodes[1:] {\n\t\tnodeiFP, err := nodes[i].core.hg.Store.GetAllPeerSets()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif !reflect.DeepEqual(node0FP, nodeiFP) {\n\t\t\tt.Logf(\"Node 0 PeerSets: %v\", node0FP)\n\t\t\tt.Logf(\"Node %d PeerSets: %v\", i, nodeiFP)\n\t\t\tt.Fatalf(\"PeerSets defer\")\n\t\t}\n\t}\n}\n<commit_msg>Remove JoinLeave test<commit_after>package node\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/mosaicnetworks\/babble\/src\/common\"\n\t\"github.com\/mosaicnetworks\/babble\/src\/crypto\"\n\t\"github.com\/mosaicnetworks\/babble\/src\/peers\"\n)\n\nfunc TestMonologue(t *testing.T) {\n\tlogger := common.NewTestLogger(t)\n\tkeys, peers := initPeers(1)\n\tnodes := initNodes(keys, peers, 100000, 1000, \"inmem\", 5*time.Millisecond, logger, t)\n\t\/\/defer drawGraphs(nodes, t)\n\n\ttarget := 50\n\terr := gossip(nodes, target, true, 3*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tcheckGossip(nodes, 0, t)\n}\n\nfunc TestJoinRequest(t *testing.T) {\n\tlogger := common.NewTestLogger(t)\n\tkeys, peerSet := initPeers(4)\n\tnodes := initNodes(keys, peerSet, 1000000, 1000, \"inmem\", 5*time.Millisecond, logger, t)\n\tdefer shutdownNodes(nodes)\n\t\/\/defer drawGraphs(nodes, t)\n\n\ttarget := 30\n\terr := gossip(nodes, target, false, 3*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckGossip(nodes, 0, t)\n\n\tkey, _ := crypto.GenerateECDSAKey()\n\tpeer := peers.NewPeer(\n\t\tfmt.Sprintf(\"0x%X\", crypto.FromECDSAPub(&key.PublicKey)),\n\t\tfmt.Sprint(\"127.0.0.1:4242\"),\n\t\t\"monika\",\n\t)\n\tnewNode := newNode(peer, key, \"new node\", peerSet, 1000, 1000, \"inmem\", 5*time.Millisecond, logger, t)\n\tdefer newNode.Shutdown()\n\n\terr = newNode.join()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/Gossip some more\n\tsecondTarget := target + 30\n\terr = bombardAndWait(nodes, secondTarget, 6*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckGossip(nodes, 0, t)\n\tcheckPeerSets(nodes, t)\n}\n\nfunc TestLeaveRequest(t *testing.T) {\n\tn := 1\n\tf := func() {\n\t\tlogger := common.NewTestLogger(t)\n\t\tkeys, peerSet := initPeers(n)\n\t\tnodes := initNodes(keys, peerSet, 1000000, 1000, \"inmem\", 5*time.Millisecond, logger, t)\n\t\tdefer shutdownNodes(nodes)\n\t\t\/\/defer drawGraphs(nodes, t)\n\n\t\ttarget := 30\n\t\terr := gossip(nodes, target, false, 3*time.Second)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tcheckGossip(nodes, 0, t)\n\n\t\tleavingNode := nodes[n-1]\n\n\t\terr = leavingNode.Leave()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif n == 1 {\n\t\t\treturn\n\t\t}\n\n\t\t\/\/Gossip some more\n\t\tsecondTarget := target + 50\n\t\terr = bombardAndWait(nodes[0:n-1], secondTarget, 6*time.Second)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tcheckGossip(nodes[0:n-1], 0, t)\n\t\tcheckPeerSets(nodes[0:n-1], t)\n\t}\n\n\tfor n <= 4 {\n\t\tf()\n\t\tn++\n\t}\n}\n\nfunc TestSuccessiveJoinRequest(t *testing.T) {\n\tlogger := common.NewTestLogger(t)\n\tkeys, peerSet := initPeers(1)\n\n\tnode0 := newNode(peerSet.Peers[0], keys[0], \"new node\", peerSet, 1000000, 400, \"inmem\", 10*time.Millisecond, logger, t)\n\tdefer node0.Shutdown()\n\tnode0.RunAsync(true)\n\n\tnodes := []*Node{node0}\n\t\/\/defer drawGraphs(nodes, t)\n\n\ttarget := 20\n\tfor i := 1; i <= 3; i++ {\n\t\tpeerSet := peers.NewPeerSet(node0.GetPeers())\n\n\t\tkey, _ := crypto.GenerateECDSAKey()\n\t\tpeer := peers.NewPeer(\n\t\t\tfmt.Sprintf(\"0x%X\", crypto.FromECDSAPub(&key.PublicKey)),\n\t\t\tfmt.Sprintf(\"127.0.0.1:%d\", 4240+i),\n\t\t\t\"monika\",\n\t\t)\n\t\tnewNode := newNode(peer, key, \"new node\", peerSet, 1000000, 400, \"inmem\", 10*time.Millisecond, logger, t)\n\n\t\tlogger.Debugf(\"starting new node %d, %d\", i, newNode.ID())\n\t\tdefer newNode.Shutdown()\n\t\tnewNode.RunAsync(true)\n\n\t\tnodes = append(nodes, newNode)\n\n\t\t\/\/Gossip some more\n\t\terr := bombardAndWait(nodes, target, 10*time.Second)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tstart := newNode.core.hg.FirstConsensusRound\n\t\tcheckGossip(nodes, *start, t)\n\n\t\ttarget = target + 40\n\t}\n}\n\nfunc TestSuccessiveLeaveRequest(t *testing.T) {\n\tn := 4\n\n\tlogger := common.NewTestLogger(t)\n\tkeys, peerSet := initPeers(n)\n\tnodes := initNodes(keys, peerSet, 1000000, 1000, \"inmem\", 5*time.Millisecond, logger, t)\n\tdefer shutdownNodes(nodes)\n\n\ttarget := 0\n\n\tf := func() {\n\t\t\/\/defer drawGraphs(nodes, t)\n\t\ttarget += 30\n\t\terr := gossip(nodes, target, false, 3*time.Second)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tcheckGossip(nodes, 0, t)\n\n\t\tleavingNode := nodes[n-1]\n\n\t\terr = leavingNode.Leave()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif n == 1 {\n\t\t\treturn\n\t\t}\n\n\t\tnodes = nodes[0 : n-1]\n\n\t\t\/\/Gossip some more\n\t\ttarget += 50\n\t\terr = bombardAndWait(nodes, target, 6*time.Second)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tcheckGossip(nodes, 0, t)\n\t\tcheckPeerSets(nodes, t)\n\t}\n\n\tfor n > 0 {\n\t\tf()\n\t\tn--\n\t}\n}\n\nfunc TestSimultaneusLeaveRequest(t *testing.T) {\n\tlogger := common.NewTestLogger(t)\n\tkeys, peerSet := initPeers(4)\n\tnodes := initNodes(keys, peerSet, 1000000, 1000, \"inmem\", 5*time.Millisecond, logger, t)\n\tdefer shutdownNodes(nodes)\n\t\/\/defer drawGraphs(nodes, t)\n\n\ttarget := 30\n\terr := gossip(nodes, target, false, 3*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckGossip(nodes, 0, t)\n\n\tleavingNode := nodes[3]\n\tleavingNode2 := nodes[2]\n\n\terr = leavingNode.Leave()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = leavingNode2.Leave()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/Gossip some more\n\tsecondTarget := target + 50\n\terr = bombardAndWait(nodes[0:2], secondTarget, 6*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckGossip(nodes[0:2], 0, t)\n\tcheckPeerSets(nodes[0:2], t)\n}\n\nfunc TestJoinFull(t *testing.T) {\n\tlogger := common.NewTestLogger(t)\n\tkeys, peerSet := initPeers(4)\n\tinitialNodes := initNodes(keys, peerSet, 1000000, 400, \"inmem\", 10*time.Millisecond, logger, t)\n\tdefer shutdownNodes(initialNodes)\n\n\ttarget := 30\n\terr := gossip(initialNodes, target, false, 6*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcheckGossip(initialNodes, 0, t)\n\n\tkey, _ := crypto.GenerateECDSAKey()\n\tpeer := peers.NewPeer(\n\t\tfmt.Sprintf(\"0x%X\", crypto.FromECDSAPub(&key.PublicKey)),\n\t\tfmt.Sprint(\"127.0.0.1:4242\"),\n\t\t\"monika\",\n\t)\n\tnewNode := newNode(peer, key, \"new node\", peerSet, 1000000, 400, \"inmem\", 10*time.Millisecond, logger, t)\n\tdefer newNode.Shutdown()\n\n\t\/\/Run parallel routine to check newNode eventually reaches CatchingUp state.\n\ttimeout := time.After(6 * time.Second)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-timeout:\n\t\t\t\tt.Fatalf(\"Timeout waiting for newNode to enter CatchingUp state\")\n\t\t\tdefault:\n\t\t\t}\n\t\t\tif newNode.getState() == CatchingUp {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n\n\tnewNode.RunAsync(true)\n\n\tnodes := append(initialNodes, newNode)\n\n\t\/\/defer drawGraphs(nodes, t)\n\n\t\/\/Gossip some more\n\tsecondTarget := target + 50\n\terr = bombardAndWait(nodes, secondTarget, 10*time.Second)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tstart := newNode.core.hg.FirstConsensusRound\n\tcheckGossip(nodes, *start, t)\n\tcheckPeerSets(nodes, t)\n}\n\nfunc checkPeerSets(nodes []*Node, t *testing.T) {\n\tnode0FP, err := nodes[0].core.hg.Store.GetAllPeerSets()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor i := range nodes[1:] {\n\t\tnodeiFP, err := nodes[i].core.hg.Store.GetAllPeerSets()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif !reflect.DeepEqual(node0FP, nodeiFP) {\n\t\t\tt.Logf(\"Node 0 PeerSets: %v\", node0FP)\n\t\t\tt.Logf(\"Node %d PeerSets: %v\", i, nodeiFP)\n\t\t\tt.Fatalf(\"PeerSets defer\")\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage os\n\n\/*\n#cgo CFLAGS: -x objective-c\n#cgo LDFLAGS: -framework CoreFoundation -framework Foundation\n\n#include <sys\/param.h>\n#include <CoreFoundation\/CFString.h>\n#include <Foundation\/NSPathUtilities.h>\n\nchar tmpdir[MAXPATHLEN];\n\nchar* loadtmpdir() {\n\ttmpdir[0] = 0;\n\tCFStringRef path = (CFStringRef)NSTemporaryDirectory();\n\tCFStringGetCString(path, tmpdir, sizeof(tmpdir), kCFStringEncodingUTF8);\n\treturn tmpdir;\n}\n*\/\nimport \"C\"\n\nfunc init() {\n\tif Getenv(\"TEMPDIR\") != \"\" {\n\t\treturn\n\t}\n\tdir := C.GoString(C.loadtmpdir())\n\tif len(dir) == 0 {\n\t\treturn\n\t}\n\tif dir[len(dir)-1] == '\/' {\n\t\tdir = dir[:len(dir)-1]\n\t}\n\tSetenv(\"TMPDIR\", dir)\n}\n<commit_msg>Revert \"os: set TMPDIR on darwin\/arm\"<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Godoc comment extraction and comment -> HTML formatting.\n\npackage doc\n\nimport (\n\t\"go\/ast\"\n\t\"http\" \/\/ for URLEscape\n\t\"io\"\n\t\"regexp\"\n\t\"strings\"\n\t\"template\" \/\/ for htmlEscape\n)\n\n\nfunc isWhitespace(ch byte) bool { return ch == ' ' || ch == '\\t' || ch == '\\n' || ch == '\\r' }\n\n\nfunc stripTrailingWhitespace(s string) string {\n\ti := len(s)\n\tfor i > 0 && isWhitespace(s[i-1]) {\n\t\ti--\n\t}\n\treturn s[0:i]\n}\n\n\n\/\/ CommentText returns the text of comment,\n\/\/ with the comment markers - \/\/, \/*, and *\/ - removed.\nfunc CommentText(comment *ast.CommentGroup) string {\n\tif comment == nil {\n\t\treturn \"\"\n\t}\n\tcomments := make([]string, len(comment.List))\n\tfor i, c := range comment.List {\n\t\tcomments[i] = string(c.Text)\n\t}\n\n\tlines := make([]string, 0, 10) \/\/ most comments are less than 10 lines\n\tfor _, c := range comments {\n\t\t\/\/ Remove comment markers.\n\t\t\/\/ The parser has given us exactly the comment text.\n\t\tswitch c[1] {\n\t\tcase '\/':\n\t\t\t\/\/-style comment\n\t\t\tc = c[2:]\n\t\t\t\/\/ Remove leading space after \/\/, if there is one.\n\t\t\t\/\/ TODO(gri) This appears to be necessary in isolated\n\t\t\t\/\/           cases (bignum.RatFromString) - why?\n\t\t\tif len(c) > 0 && c[0] == ' ' {\n\t\t\t\tc = c[1:]\n\t\t\t}\n\t\tcase '*':\n\t\t\t\/*-style comment *\/\n\t\t\tc = c[2 : len(c)-2]\n\t\t}\n\n\t\t\/\/ Split on newlines.\n\t\tcl := strings.Split(c, \"\\n\", -1)\n\n\t\t\/\/ Walk lines, stripping trailing white space and adding to list.\n\t\tfor _, l := range cl {\n\t\t\tl = stripTrailingWhitespace(l)\n\t\t\t\/\/ Add to list.\n\t\t\tn := len(lines)\n\t\t\tif n+1 >= cap(lines) {\n\t\t\t\tnewlines := make([]string, n, 2*cap(lines))\n\t\t\t\tcopy(newlines, lines)\n\t\t\t\tlines = newlines\n\t\t\t}\n\t\t\tlines = lines[0 : n+1]\n\t\t\tlines[n] = l\n\t\t}\n\t}\n\n\t\/\/ Remove leading blank lines; convert runs of\n\t\/\/ interior blank lines to a single blank line.\n\tn := 0\n\tfor _, line := range lines {\n\t\tif line != \"\" || n > 0 && lines[n-1] != \"\" {\n\t\t\tlines[n] = line\n\t\t\tn++\n\t\t}\n\t}\n\tlines = lines[0:n]\n\n\t\/\/ Add final \"\" entry to get trailing newline from Join.\n\t\/\/ The original loop always leaves room for one more.\n\tif n > 0 && lines[n-1] != \"\" {\n\t\tlines = lines[0 : n+1]\n\t\tlines[n] = \"\"\n\t}\n\n\treturn strings.Join(lines, \"\\n\")\n}\n\n\n\/\/ Split bytes into lines.\nfunc split(text []byte) [][]byte {\n\t\/\/ count lines\n\tn := 0\n\tlast := 0\n\tfor i, c := range text {\n\t\tif c == '\\n' {\n\t\t\tlast = i + 1\n\t\t\tn++\n\t\t}\n\t}\n\tif last < len(text) {\n\t\tn++\n\t}\n\n\t\/\/ split\n\tout := make([][]byte, n)\n\tlast = 0\n\tn = 0\n\tfor i, c := range text {\n\t\tif c == '\\n' {\n\t\t\tout[n] = text[last : i+1]\n\t\t\tlast = i + 1\n\t\t\tn++\n\t\t}\n\t}\n\tif last < len(text) {\n\t\tout[n] = text[last:]\n\t}\n\n\treturn out\n}\n\n\nvar (\n\tldquo = []byte(\"&ldquo;\")\n\trdquo = []byte(\"&rdquo;\")\n)\n\n\/\/ Escape comment text for HTML. If nice is set,\n\/\/ also turn `` into &ldquo; and '' into &rdquo;.\nfunc commentEscape(w io.Writer, s []byte, nice bool) {\n\tlast := 0\n\tif nice {\n\t\tfor i := 0; i < len(s)-1; i++ {\n\t\t\tch := s[i]\n\t\t\tif ch == s[i+1] && (ch == '`' || ch == '\\'') {\n\t\t\t\ttemplate.HTMLEscape(w, s[last:i])\n\t\t\t\tlast = i + 2\n\t\t\t\tswitch ch {\n\t\t\t\tcase '`':\n\t\t\t\t\tw.Write(ldquo)\n\t\t\t\tcase '\\'':\n\t\t\t\t\tw.Write(rdquo)\n\t\t\t\t}\n\t\t\t\ti++ \/\/ loop will add one more\n\t\t\t}\n\t\t}\n\t}\n\ttemplate.HTMLEscape(w, s[last:])\n}\n\n\nconst (\n\t\/\/ Regexp for Go identifiers\n\tidentRx = `[a-zA-Z_][a-zA-Z_0-9]*` \/\/ TODO(gri) ASCII only for now - fix this\n\n\t\/\/ Regexp for URLs\n\tprotocol = `(https?|ftp|file|gopher|mailto|news|nntp|telnet|wais|prospero):`\n\thostPart = `[a-zA-Z0-9_@\\-]+`\n\tfilePart = `[a-zA-Z0-9_?%#~&\/\\-+=]+`\n\turlRx    = protocol + `\/\/` + \/\/ http:\/\/\n\t\thostPart + `([.:]` + hostPart + `)*\/?` + \/\/ \/\/www.google.com:8080\/\n\t\tfilePart + `([:.,]` + filePart + `)*`\n)\n\nvar matchRx = regexp.MustCompile(`(` + identRx + `)|(` + urlRx + `)`)\n\nvar (\n\thtml_a      = []byte(`<a href=\"`)\n\thtml_aq     = []byte(`\">`)\n\thtml_enda   = []byte(\"<\/a>\")\n\thtml_i      = []byte(\"<i>\")\n\thtml_endi   = []byte(\"<\/i>\")\n\thtml_p      = []byte(\"<p>\\n\")\n\thtml_endp   = []byte(\"<\/p>\\n\")\n\thtml_pre    = []byte(\"<pre>\")\n\thtml_endpre = []byte(\"<\/pre>\\n\")\n)\n\n\n\/\/ Emphasize and escape a line of text for HTML. URLs are converted into links;\n\/\/ if the URL also appears in the words map, the link is taken from the map (if\n\/\/ the corresponding map value is the empty string, the URL is not converted\n\/\/ into a link). Go identifiers that appear in the words map are italicized; if\n\/\/ the corresponding map value is not the empty string, it is considered a URL\n\/\/ and the word is converted into a link. If nice is set, the remaining text's\n\/\/ appearance is improved where is makes sense (e.g., `` is turned into &ldquo;\n\/\/ and '' into &rdquo;).\nfunc emphasize(w io.Writer, line []byte, words map[string]string, nice bool) {\n\tfor {\n\t\tm := matchRx.FindSubmatchIndex(line)\n\t\tif m == nil {\n\t\t\tbreak\n\t\t}\n\t\t\/\/ m >= 6 (two parenthesized sub-regexps in matchRx, 1st one is identRx)\n\n\t\t\/\/ write text before match\n\t\tcommentEscape(w, line[0:m[0]], nice)\n\n\t\t\/\/ analyze match\n\t\tmatch := line[m[0]:m[1]]\n\t\turl := \"\"\n\t\titalics := false\n\t\tif words != nil {\n\t\t\turl, italics = words[string(match)]\n\t\t}\n\t\tif m[2] < 0 {\n\t\t\t\/\/ didn't match against first parenthesized sub-regexp; must be match against urlRx\n\t\t\tif !italics {\n\t\t\t\t\/\/ no alternative URL in words list, use match instead\n\t\t\t\turl = string(match)\n\t\t\t}\n\t\t\titalics = false \/\/ don't italicize URLs\n\t\t}\n\n\t\t\/\/ write match\n\t\tif len(url) > 0 {\n\t\t\tw.Write(html_a)\n\t\t\tw.Write([]byte(http.URLEscape(url)))\n\t\t\tw.Write(html_aq)\n\t\t}\n\t\tif italics {\n\t\t\tw.Write(html_i)\n\t\t}\n\t\tcommentEscape(w, match, nice)\n\t\tif italics {\n\t\t\tw.Write(html_endi)\n\t\t}\n\t\tif len(url) > 0 {\n\t\t\tw.Write(html_enda)\n\t\t}\n\n\t\t\/\/ advance\n\t\tline = line[m[1]:]\n\t}\n\tcommentEscape(w, line, nice)\n}\n\n\nfunc indentLen(s []byte) int {\n\ti := 0\n\tfor i < len(s) && (s[i] == ' ' || s[i] == '\\t') {\n\t\ti++\n\t}\n\treturn i\n}\n\n\nfunc isBlank(s []byte) bool { return len(s) == 0 || (len(s) == 1 && s[0] == '\\n') }\n\n\nfunc commonPrefix(a, b []byte) []byte {\n\ti := 0\n\tfor i < len(a) && i < len(b) && a[i] == b[i] {\n\t\ti++\n\t}\n\treturn a[0:i]\n}\n\n\nfunc unindent(block [][]byte) {\n\tif len(block) == 0 {\n\t\treturn\n\t}\n\n\t\/\/ compute maximum common white prefix\n\tprefix := block[0][0:indentLen(block[0])]\n\tfor _, line := range block {\n\t\tif !isBlank(line) {\n\t\t\tprefix = commonPrefix(prefix, line[0:indentLen(line)])\n\t\t}\n\t}\n\tn := len(prefix)\n\n\t\/\/ remove\n\tfor i, line := range block {\n\t\tif !isBlank(line) {\n\t\t\tblock[i] = line[n:]\n\t\t}\n\t}\n}\n\n\n\/\/ Convert comment text to formatted HTML.\n\/\/ The comment was prepared by DocReader,\n\/\/ so it is known not to have leading, trailing blank lines\n\/\/ nor to have trailing spaces at the end of lines.\n\/\/ The comment markers have already been removed.\n\/\/\n\/\/ Turn each run of multiple \\n into <\/p><p>\n\/\/ Turn each run of indented lines into a <pre> block without indent.\n\/\/\n\/\/ URLs in the comment text are converted into links; if the URL also appears\n\/\/ in the words map, the link is taken from the map (if the corresponding map\n\/\/ value is the empty string, the URL is not converted into a link).\n\/\/\n\/\/ Go identifiers that appear in the words map are italicized; if the corresponding\n\/\/ map value is not the empty string, it is considered a URL and the word is converted\n\/\/ into a link.\nfunc ToHTML(w io.Writer, s []byte, words map[string]string) {\n\tinpara := false\n\n\tclose := func() {\n\t\tif inpara {\n\t\t\tw.Write(html_endp)\n\t\t\tinpara = false\n\t\t}\n\t}\n\topen := func() {\n\t\tif !inpara {\n\t\t\tw.Write(html_p)\n\t\t\tinpara = true\n\t\t}\n\t}\n\n\tlines := split(s)\n\tunindent(lines)\n\tfor i := 0; i < len(lines); {\n\t\tline := lines[i]\n\t\tif isBlank(line) {\n\t\t\t\/\/ close paragraph\n\t\t\tclose()\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\t\tif indentLen(line) > 0 {\n\t\t\t\/\/ close paragraph\n\t\t\tclose()\n\n\t\t\t\/\/ count indented or blank lines\n\t\t\tj := i + 1\n\t\t\tfor j < len(lines) && (isBlank(lines[j]) || indentLen(lines[j]) > 0) {\n\t\t\t\tj++\n\t\t\t}\n\t\t\t\/\/ but not trailing blank lines\n\t\t\tfor j > i && isBlank(lines[j-1]) {\n\t\t\t\tj--\n\t\t\t}\n\t\t\tblock := lines[i:j]\n\t\t\ti = j\n\n\t\t\tunindent(block)\n\n\t\t\t\/\/ put those lines in a pre block\n\t\t\tw.Write(html_pre)\n\t\t\tfor _, line := range block {\n\t\t\t\temphasize(w, line, nil, false) \/\/ no nice text formatting\n\t\t\t}\n\t\t\tw.Write(html_endpre)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ open paragraph\n\t\topen()\n\t\temphasize(w, lines[i], words, true) \/\/ nice text formatting\n\t\ti++\n\t}\n\tclose()\n}\n<commit_msg>go\/doc: use correct escaper for URL<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Godoc comment extraction and comment -> HTML formatting.\n\npackage doc\n\nimport (\n\t\"go\/ast\"\n\t\"io\"\n\t\"regexp\"\n\t\"strings\"\n\t\"template\" \/\/ for htmlEscape\n)\n\n\nfunc isWhitespace(ch byte) bool { return ch == ' ' || ch == '\\t' || ch == '\\n' || ch == '\\r' }\n\n\nfunc stripTrailingWhitespace(s string) string {\n\ti := len(s)\n\tfor i > 0 && isWhitespace(s[i-1]) {\n\t\ti--\n\t}\n\treturn s[0:i]\n}\n\n\n\/\/ CommentText returns the text of comment,\n\/\/ with the comment markers - \/\/, \/*, and *\/ - removed.\nfunc CommentText(comment *ast.CommentGroup) string {\n\tif comment == nil {\n\t\treturn \"\"\n\t}\n\tcomments := make([]string, len(comment.List))\n\tfor i, c := range comment.List {\n\t\tcomments[i] = string(c.Text)\n\t}\n\n\tlines := make([]string, 0, 10) \/\/ most comments are less than 10 lines\n\tfor _, c := range comments {\n\t\t\/\/ Remove comment markers.\n\t\t\/\/ The parser has given us exactly the comment text.\n\t\tswitch c[1] {\n\t\tcase '\/':\n\t\t\t\/\/-style comment\n\t\t\tc = c[2:]\n\t\t\t\/\/ Remove leading space after \/\/, if there is one.\n\t\t\t\/\/ TODO(gri) This appears to be necessary in isolated\n\t\t\t\/\/           cases (bignum.RatFromString) - why?\n\t\t\tif len(c) > 0 && c[0] == ' ' {\n\t\t\t\tc = c[1:]\n\t\t\t}\n\t\tcase '*':\n\t\t\t\/*-style comment *\/\n\t\t\tc = c[2 : len(c)-2]\n\t\t}\n\n\t\t\/\/ Split on newlines.\n\t\tcl := strings.Split(c, \"\\n\", -1)\n\n\t\t\/\/ Walk lines, stripping trailing white space and adding to list.\n\t\tfor _, l := range cl {\n\t\t\tl = stripTrailingWhitespace(l)\n\t\t\t\/\/ Add to list.\n\t\t\tn := len(lines)\n\t\t\tif n+1 >= cap(lines) {\n\t\t\t\tnewlines := make([]string, n, 2*cap(lines))\n\t\t\t\tcopy(newlines, lines)\n\t\t\t\tlines = newlines\n\t\t\t}\n\t\t\tlines = lines[0 : n+1]\n\t\t\tlines[n] = l\n\t\t}\n\t}\n\n\t\/\/ Remove leading blank lines; convert runs of\n\t\/\/ interior blank lines to a single blank line.\n\tn := 0\n\tfor _, line := range lines {\n\t\tif line != \"\" || n > 0 && lines[n-1] != \"\" {\n\t\t\tlines[n] = line\n\t\t\tn++\n\t\t}\n\t}\n\tlines = lines[0:n]\n\n\t\/\/ Add final \"\" entry to get trailing newline from Join.\n\t\/\/ The original loop always leaves room for one more.\n\tif n > 0 && lines[n-1] != \"\" {\n\t\tlines = lines[0 : n+1]\n\t\tlines[n] = \"\"\n\t}\n\n\treturn strings.Join(lines, \"\\n\")\n}\n\n\n\/\/ Split bytes into lines.\nfunc split(text []byte) [][]byte {\n\t\/\/ count lines\n\tn := 0\n\tlast := 0\n\tfor i, c := range text {\n\t\tif c == '\\n' {\n\t\t\tlast = i + 1\n\t\t\tn++\n\t\t}\n\t}\n\tif last < len(text) {\n\t\tn++\n\t}\n\n\t\/\/ split\n\tout := make([][]byte, n)\n\tlast = 0\n\tn = 0\n\tfor i, c := range text {\n\t\tif c == '\\n' {\n\t\t\tout[n] = text[last : i+1]\n\t\t\tlast = i + 1\n\t\t\tn++\n\t\t}\n\t}\n\tif last < len(text) {\n\t\tout[n] = text[last:]\n\t}\n\n\treturn out\n}\n\n\nvar (\n\tldquo = []byte(\"&ldquo;\")\n\trdquo = []byte(\"&rdquo;\")\n)\n\n\/\/ Escape comment text for HTML. If nice is set,\n\/\/ also turn `` into &ldquo; and '' into &rdquo;.\nfunc commentEscape(w io.Writer, s []byte, nice bool) {\n\tlast := 0\n\tif nice {\n\t\tfor i := 0; i < len(s)-1; i++ {\n\t\t\tch := s[i]\n\t\t\tif ch == s[i+1] && (ch == '`' || ch == '\\'') {\n\t\t\t\ttemplate.HTMLEscape(w, s[last:i])\n\t\t\t\tlast = i + 2\n\t\t\t\tswitch ch {\n\t\t\t\tcase '`':\n\t\t\t\t\tw.Write(ldquo)\n\t\t\t\tcase '\\'':\n\t\t\t\t\tw.Write(rdquo)\n\t\t\t\t}\n\t\t\t\ti++ \/\/ loop will add one more\n\t\t\t}\n\t\t}\n\t}\n\ttemplate.HTMLEscape(w, s[last:])\n}\n\n\nconst (\n\t\/\/ Regexp for Go identifiers\n\tidentRx = `[a-zA-Z_][a-zA-Z_0-9]*` \/\/ TODO(gri) ASCII only for now - fix this\n\n\t\/\/ Regexp for URLs\n\tprotocol = `(https?|ftp|file|gopher|mailto|news|nntp|telnet|wais|prospero):`\n\thostPart = `[a-zA-Z0-9_@\\-]+`\n\tfilePart = `[a-zA-Z0-9_?%#~&\/\\-+=]+`\n\turlRx    = protocol + `\/\/` + \/\/ http:\/\/\n\t\thostPart + `([.:]` + hostPart + `)*\/?` + \/\/ \/\/www.google.com:8080\/\n\t\tfilePart + `([:.,]` + filePart + `)*`\n)\n\nvar matchRx = regexp.MustCompile(`(` + identRx + `)|(` + urlRx + `)`)\n\nvar (\n\thtml_a      = []byte(`<a href=\"`)\n\thtml_aq     = []byte(`\">`)\n\thtml_enda   = []byte(\"<\/a>\")\n\thtml_i      = []byte(\"<i>\")\n\thtml_endi   = []byte(\"<\/i>\")\n\thtml_p      = []byte(\"<p>\\n\")\n\thtml_endp   = []byte(\"<\/p>\\n\")\n\thtml_pre    = []byte(\"<pre>\")\n\thtml_endpre = []byte(\"<\/pre>\\n\")\n)\n\n\n\/\/ Emphasize and escape a line of text for HTML. URLs are converted into links;\n\/\/ if the URL also appears in the words map, the link is taken from the map (if\n\/\/ the corresponding map value is the empty string, the URL is not converted\n\/\/ into a link). Go identifiers that appear in the words map are italicized; if\n\/\/ the corresponding map value is not the empty string, it is considered a URL\n\/\/ and the word is converted into a link. If nice is set, the remaining text's\n\/\/ appearance is improved where is makes sense (e.g., `` is turned into &ldquo;\n\/\/ and '' into &rdquo;).\nfunc emphasize(w io.Writer, line []byte, words map[string]string, nice bool) {\n\tfor {\n\t\tm := matchRx.FindSubmatchIndex(line)\n\t\tif m == nil {\n\t\t\tbreak\n\t\t}\n\t\t\/\/ m >= 6 (two parenthesized sub-regexps in matchRx, 1st one is identRx)\n\n\t\t\/\/ write text before match\n\t\tcommentEscape(w, line[0:m[0]], nice)\n\n\t\t\/\/ analyze match\n\t\tmatch := line[m[0]:m[1]]\n\t\turl := \"\"\n\t\titalics := false\n\t\tif words != nil {\n\t\t\turl, italics = words[string(match)]\n\t\t}\n\t\tif m[2] < 0 {\n\t\t\t\/\/ didn't match against first parenthesized sub-regexp; must be match against urlRx\n\t\t\tif !italics {\n\t\t\t\t\/\/ no alternative URL in words list, use match instead\n\t\t\t\turl = string(match)\n\t\t\t}\n\t\t\titalics = false \/\/ don't italicize URLs\n\t\t}\n\n\t\t\/\/ write match\n\t\tif len(url) > 0 {\n\t\t\tw.Write(html_a)\n\t\t\ttemplate.HTMLEscape(w, []byte(url))\n\t\t\tw.Write(html_aq)\n\t\t}\n\t\tif italics {\n\t\t\tw.Write(html_i)\n\t\t}\n\t\tcommentEscape(w, match, nice)\n\t\tif italics {\n\t\t\tw.Write(html_endi)\n\t\t}\n\t\tif len(url) > 0 {\n\t\t\tw.Write(html_enda)\n\t\t}\n\n\t\t\/\/ advance\n\t\tline = line[m[1]:]\n\t}\n\tcommentEscape(w, line, nice)\n}\n\n\nfunc indentLen(s []byte) int {\n\ti := 0\n\tfor i < len(s) && (s[i] == ' ' || s[i] == '\\t') {\n\t\ti++\n\t}\n\treturn i\n}\n\n\nfunc isBlank(s []byte) bool { return len(s) == 0 || (len(s) == 1 && s[0] == '\\n') }\n\n\nfunc commonPrefix(a, b []byte) []byte {\n\ti := 0\n\tfor i < len(a) && i < len(b) && a[i] == b[i] {\n\t\ti++\n\t}\n\treturn a[0:i]\n}\n\n\nfunc unindent(block [][]byte) {\n\tif len(block) == 0 {\n\t\treturn\n\t}\n\n\t\/\/ compute maximum common white prefix\n\tprefix := block[0][0:indentLen(block[0])]\n\tfor _, line := range block {\n\t\tif !isBlank(line) {\n\t\t\tprefix = commonPrefix(prefix, line[0:indentLen(line)])\n\t\t}\n\t}\n\tn := len(prefix)\n\n\t\/\/ remove\n\tfor i, line := range block {\n\t\tif !isBlank(line) {\n\t\t\tblock[i] = line[n:]\n\t\t}\n\t}\n}\n\n\n\/\/ Convert comment text to formatted HTML.\n\/\/ The comment was prepared by DocReader,\n\/\/ so it is known not to have leading, trailing blank lines\n\/\/ nor to have trailing spaces at the end of lines.\n\/\/ The comment markers have already been removed.\n\/\/\n\/\/ Turn each run of multiple \\n into <\/p><p>\n\/\/ Turn each run of indented lines into a <pre> block without indent.\n\/\/\n\/\/ URLs in the comment text are converted into links; if the URL also appears\n\/\/ in the words map, the link is taken from the map (if the corresponding map\n\/\/ value is the empty string, the URL is not converted into a link).\n\/\/\n\/\/ Go identifiers that appear in the words map are italicized; if the corresponding\n\/\/ map value is not the empty string, it is considered a URL and the word is converted\n\/\/ into a link.\nfunc ToHTML(w io.Writer, s []byte, words map[string]string) {\n\tinpara := false\n\n\tclose := func() {\n\t\tif inpara {\n\t\t\tw.Write(html_endp)\n\t\t\tinpara = false\n\t\t}\n\t}\n\topen := func() {\n\t\tif !inpara {\n\t\t\tw.Write(html_p)\n\t\t\tinpara = true\n\t\t}\n\t}\n\n\tlines := split(s)\n\tunindent(lines)\n\tfor i := 0; i < len(lines); {\n\t\tline := lines[i]\n\t\tif isBlank(line) {\n\t\t\t\/\/ close paragraph\n\t\t\tclose()\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\t\tif indentLen(line) > 0 {\n\t\t\t\/\/ close paragraph\n\t\t\tclose()\n\n\t\t\t\/\/ count indented or blank lines\n\t\t\tj := i + 1\n\t\t\tfor j < len(lines) && (isBlank(lines[j]) || indentLen(lines[j]) > 0) {\n\t\t\t\tj++\n\t\t\t}\n\t\t\t\/\/ but not trailing blank lines\n\t\t\tfor j > i && isBlank(lines[j-1]) {\n\t\t\t\tj--\n\t\t\t}\n\t\t\tblock := lines[i:j]\n\t\t\ti = j\n\n\t\t\tunindent(block)\n\n\t\t\t\/\/ put those lines in a pre block\n\t\t\tw.Write(html_pre)\n\t\t\tfor _, line := range block {\n\t\t\t\temphasize(w, line, nil, false) \/\/ no nice text formatting\n\t\t\t}\n\t\t\tw.Write(html_endpre)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ open paragraph\n\t\topen()\n\t\temphasize(w, lines[i], words, true) \/\/ nice text formatting\n\t\ti++\n\t}\n\tclose()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2010 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage netchan\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"reflect\"\n\t\"sync\"\n)\n\n\/\/ Import\n\n\/\/ impLog is a logging convenience function.  The first argument must be a string.\nfunc impLog(args ...interface{}) {\n\targs[0] = \"netchan import: \" + args[0].(string)\n\tlog.Stderr(args)\n}\n\n\/\/ An Importer allows a set of channels to be imported from a single\n\/\/ remote machine\/network port.  A machine may have multiple\n\/\/ importers, even from the same machine\/network port.\ntype Importer struct {\n\t*encDec\n\tconn     net.Conn\n\tchanLock sync.Mutex \/\/ protects access to channel map\n\tchans    map[string]*chanDir\n\terrors   chan os.Error\n}\n\n\/\/ NewImporter creates a new Importer object to import channels\n\/\/ from an Exporter at the network and remote address as defined in net.Dial.\n\/\/ The Exporter must be available and serving when the Importer is\n\/\/ created.\nfunc NewImporter(network, remoteaddr string) (*Importer, os.Error) {\n\tconn, err := net.Dial(network, \"\", remoteaddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\timp := new(Importer)\n\timp.encDec = newEncDec(conn)\n\timp.conn = conn\n\timp.chans = make(map[string]*chanDir)\n\timp.errors = make(chan os.Error, 10)\n\tgo imp.run()\n\treturn imp, nil\n}\n\n\/\/ shutdown closes all channels for which we are receiving data from the remote side.\nfunc (imp *Importer) shutdown() {\n\timp.chanLock.Lock()\n\tfor _, ich := range imp.chans {\n\t\tif ich.dir == Recv {\n\t\t\tich.ch.Close()\n\t\t}\n\t}\n\timp.chanLock.Unlock()\n}\n\n\/\/ Handle the data from a single imported data stream, which will\n\/\/ have the form\n\/\/\t(response, data)*\n\/\/ The response identifies by name which channel is transmitting data.\nfunc (imp *Importer) run() {\n\t\/\/ Loop on responses; requests are sent by ImportNValues()\n\thdr := new(header)\n\thdrValue := reflect.NewValue(hdr)\n\tackHdr := new(header)\n\terr := new(error)\n\terrValue := reflect.NewValue(err)\n\tfor {\n\t\t*hdr = header{}\n\t\tif e := imp.decode(hdrValue); e != nil {\n\t\t\timpLog(\"header:\", e)\n\t\t\timp.shutdown()\n\t\t\treturn\n\t\t}\n\t\tswitch hdr.payloadType {\n\t\tcase payData:\n\t\t\t\/\/ done lower in loop\n\t\tcase payError:\n\t\t\tif e := imp.decode(errValue); e != nil {\n\t\t\t\timpLog(\"error:\", e)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err.error != \"\" {\n\t\t\t\timpLog(\"response error:\", err.error)\n\t\t\t\tif sent := imp.errors <- os.ErrorString(err.error); !sent {\n\t\t\t\t\timp.shutdown()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontinue \/\/ errors are not acknowledged.\n\t\t\t}\n\t\tcase payClosed:\n\t\t\tich := imp.getChan(hdr.name)\n\t\t\tif ich != nil {\n\t\t\t\tich.ch.Close()\n\t\t\t}\n\t\t\tcontinue \/\/ closes are not acknowledged.\n\t\tdefault:\n\t\t\timpLog(\"unexpected payload type:\", hdr.payloadType)\n\t\t\treturn\n\t\t}\n\t\tich := imp.getChan(hdr.name)\n\t\tif ich == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif ich.dir != Recv {\n\t\t\timpLog(\"cannot happen: receive from non-Recv channel\")\n\t\t\treturn\n\t\t}\n\t\t\/\/ Acknowledge receipt\n\t\tackHdr.name = hdr.name\n\t\tackHdr.seqNum = hdr.seqNum\n\t\timp.encode(ackHdr, payAck, nil)\n\t\t\/\/ Create a new value for each received item.\n\t\tvalue := reflect.MakeZero(ich.ch.Type().(*reflect.ChanType).Elem())\n\t\tif e := imp.decode(value); e != nil {\n\t\t\timpLog(\"importer value decode:\", e)\n\t\t\treturn\n\t\t}\n\t\tich.ch.Send(value)\n\t}\n}\n\nfunc (imp *Importer) getChan(name string) *chanDir {\n\timp.chanLock.Lock()\n\tich := imp.chans[name]\n\timp.chanLock.Unlock()\n\tif ich == nil {\n\t\timpLog(\"unknown name in netchan request:\", name)\n\t\treturn nil\n\t}\n\treturn ich\n}\n\n\/\/ Errors returns a channel from which transmission and protocol errors\n\/\/ can be read. Clients of the importer are not required to read the error\n\/\/ channel for correct execution. However, if too many errors occur\n\/\/ without being read from the error channel, the importer will shut down.\nfunc (imp *Importer) Errors() chan os.Error {\n\treturn imp.errors\n}\n\n\/\/ Import imports a channel of the given type and specified direction.\n\/\/ It is equivalent to ImportNValues with a count of -1, meaning unbounded.\nfunc (imp *Importer) Import(name string, chT interface{}, dir Dir) os.Error {\n\treturn imp.ImportNValues(name, chT, dir, -1)\n}\n\n\/\/ ImportNValues imports a channel of the given type and specified direction\n\/\/ and then receives or transmits up to n values on that channel.  A value of\n\/\/ n==-1 implies an unbounded number of values.  The channel to be bound to\n\/\/ the remote site's channel is provided in the call and may be of arbitrary\n\/\/ channel type.\n\/\/ Despite the literal signature, the effective signature is\n\/\/\tImportNValues(name string, chT chan T, dir Dir, n int) os.Error\n\/\/ Example usage:\n\/\/\timp, err := NewImporter(\"tcp\", \"netchanserver.mydomain.com:1234\")\n\/\/\tif err != nil { log.Exit(err) }\n\/\/\tch := make(chan myType)\n\/\/\terr := imp.ImportNValues(\"name\", ch, Recv, 1)\n\/\/\tif err != nil { log.Exit(err) }\n\/\/\tfmt.Printf(\"%+v\\n\", <-ch)\nfunc (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, n int) os.Error {\n\tch, err := checkChan(chT, dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\timp.chanLock.Lock()\n\tdefer imp.chanLock.Unlock()\n\t_, present := imp.chans[name]\n\tif present {\n\t\treturn os.ErrorString(\"channel name already being imported:\" + name)\n\t}\n\timp.chans[name] = &chanDir{ch, dir}\n\t\/\/ Tell the other side about this channel.\n\thdr := &header{name: name}\n\treq := &request{count: int64(n), dir: dir}\n\tif err = imp.encode(hdr, payRequest, req); err != nil {\n\t\timpLog(\"request encode:\", err)\n\t\treturn err\n\t}\n\tif dir == Send {\n\t\tgo func() {\n\t\t\tfor i := 0; n == -1 || i < n; i++ {\n\t\t\t\tval := ch.Recv()\n\t\t\t\tif ch.Closed() {\n\t\t\t\t\tif err = imp.encode(hdr, payClosed, nil); err != nil {\n\t\t\t\t\t\timpLog(\"error encoding client closed message:\", err)\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err = imp.encode(hdr, payData, val.Interface()); err != nil {\n\t\t\t\t\timpLog(\"error encoding client send:\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\treturn nil\n}\n<commit_msg>netchan: fix comment typo.<commit_after>\/\/ Copyright 2010 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage netchan\n\nimport (\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"reflect\"\n\t\"sync\"\n)\n\n\/\/ Import\n\n\/\/ impLog is a logging convenience function.  The first argument must be a string.\nfunc impLog(args ...interface{}) {\n\targs[0] = \"netchan import: \" + args[0].(string)\n\tlog.Stderr(args)\n}\n\n\/\/ An Importer allows a set of channels to be imported from a single\n\/\/ remote machine\/network port.  A machine may have multiple\n\/\/ importers, even from the same machine\/network port.\ntype Importer struct {\n\t*encDec\n\tconn     net.Conn\n\tchanLock sync.Mutex \/\/ protects access to channel map\n\tchans    map[string]*chanDir\n\terrors   chan os.Error\n}\n\n\/\/ NewImporter creates a new Importer object to import channels\n\/\/ from an Exporter at the network and remote address as defined in net.Dial.\n\/\/ The Exporter must be available and serving when the Importer is\n\/\/ created.\nfunc NewImporter(network, remoteaddr string) (*Importer, os.Error) {\n\tconn, err := net.Dial(network, \"\", remoteaddr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\timp := new(Importer)\n\timp.encDec = newEncDec(conn)\n\timp.conn = conn\n\timp.chans = make(map[string]*chanDir)\n\timp.errors = make(chan os.Error, 10)\n\tgo imp.run()\n\treturn imp, nil\n}\n\n\/\/ shutdown closes all channels for which we are receiving data from the remote side.\nfunc (imp *Importer) shutdown() {\n\timp.chanLock.Lock()\n\tfor _, ich := range imp.chans {\n\t\tif ich.dir == Recv {\n\t\t\tich.ch.Close()\n\t\t}\n\t}\n\timp.chanLock.Unlock()\n}\n\n\/\/ Handle the data from a single imported data stream, which will\n\/\/ have the form\n\/\/\t(response, data)*\n\/\/ The response identifies by name which channel is transmitting data.\nfunc (imp *Importer) run() {\n\t\/\/ Loop on responses; requests are sent by ImportNValues()\n\thdr := new(header)\n\thdrValue := reflect.NewValue(hdr)\n\tackHdr := new(header)\n\terr := new(error)\n\terrValue := reflect.NewValue(err)\n\tfor {\n\t\t*hdr = header{}\n\t\tif e := imp.decode(hdrValue); e != nil {\n\t\t\timpLog(\"header:\", e)\n\t\t\timp.shutdown()\n\t\t\treturn\n\t\t}\n\t\tswitch hdr.payloadType {\n\t\tcase payData:\n\t\t\t\/\/ done lower in loop\n\t\tcase payError:\n\t\t\tif e := imp.decode(errValue); e != nil {\n\t\t\t\timpLog(\"error:\", e)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err.error != \"\" {\n\t\t\t\timpLog(\"response error:\", err.error)\n\t\t\t\tif sent := imp.errors <- os.ErrorString(err.error); !sent {\n\t\t\t\t\timp.shutdown()\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontinue \/\/ errors are not acknowledged.\n\t\t\t}\n\t\tcase payClosed:\n\t\t\tich := imp.getChan(hdr.name)\n\t\t\tif ich != nil {\n\t\t\t\tich.ch.Close()\n\t\t\t}\n\t\t\tcontinue \/\/ closes are not acknowledged.\n\t\tdefault:\n\t\t\timpLog(\"unexpected payload type:\", hdr.payloadType)\n\t\t\treturn\n\t\t}\n\t\tich := imp.getChan(hdr.name)\n\t\tif ich == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif ich.dir != Recv {\n\t\t\timpLog(\"cannot happen: receive from non-Recv channel\")\n\t\t\treturn\n\t\t}\n\t\t\/\/ Acknowledge receipt\n\t\tackHdr.name = hdr.name\n\t\tackHdr.seqNum = hdr.seqNum\n\t\timp.encode(ackHdr, payAck, nil)\n\t\t\/\/ Create a new value for each received item.\n\t\tvalue := reflect.MakeZero(ich.ch.Type().(*reflect.ChanType).Elem())\n\t\tif e := imp.decode(value); e != nil {\n\t\t\timpLog(\"importer value decode:\", e)\n\t\t\treturn\n\t\t}\n\t\tich.ch.Send(value)\n\t}\n}\n\nfunc (imp *Importer) getChan(name string) *chanDir {\n\timp.chanLock.Lock()\n\tich := imp.chans[name]\n\timp.chanLock.Unlock()\n\tif ich == nil {\n\t\timpLog(\"unknown name in netchan request:\", name)\n\t\treturn nil\n\t}\n\treturn ich\n}\n\n\/\/ Errors returns a channel from which transmission and protocol errors\n\/\/ can be read. Clients of the importer are not required to read the error\n\/\/ channel for correct execution. However, if too many errors occur\n\/\/ without being read from the error channel, the importer will shut down.\nfunc (imp *Importer) Errors() chan os.Error {\n\treturn imp.errors\n}\n\n\/\/ Import imports a channel of the given type and specified direction.\n\/\/ It is equivalent to ImportNValues with a count of -1, meaning unbounded.\nfunc (imp *Importer) Import(name string, chT interface{}, dir Dir) os.Error {\n\treturn imp.ImportNValues(name, chT, dir, -1)\n}\n\n\/\/ ImportNValues imports a channel of the given type and specified direction\n\/\/ and then receives or transmits up to n values on that channel.  A value of\n\/\/ n==-1 implies an unbounded number of values.  The channel to be bound to\n\/\/ the remote site's channel is provided in the call and may be of arbitrary\n\/\/ channel type.\n\/\/ Despite the literal signature, the effective signature is\n\/\/\tImportNValues(name string, chT chan T, dir Dir, n int) os.Error\n\/\/ Example usage:\n\/\/\timp, err := NewImporter(\"tcp\", \"netchanserver.mydomain.com:1234\")\n\/\/\tif err != nil { log.Exit(err) }\n\/\/\tch := make(chan myType)\n\/\/\terr = imp.ImportNValues(\"name\", ch, Recv, 1)\n\/\/\tif err != nil { log.Exit(err) }\n\/\/\tfmt.Printf(\"%+v\\n\", <-ch)\nfunc (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, n int) os.Error {\n\tch, err := checkChan(chT, dir)\n\tif err != nil {\n\t\treturn err\n\t}\n\timp.chanLock.Lock()\n\tdefer imp.chanLock.Unlock()\n\t_, present := imp.chans[name]\n\tif present {\n\t\treturn os.ErrorString(\"channel name already being imported:\" + name)\n\t}\n\timp.chans[name] = &chanDir{ch, dir}\n\t\/\/ Tell the other side about this channel.\n\thdr := &header{name: name}\n\treq := &request{count: int64(n), dir: dir}\n\tif err = imp.encode(hdr, payRequest, req); err != nil {\n\t\timpLog(\"request encode:\", err)\n\t\treturn err\n\t}\n\tif dir == Send {\n\t\tgo func() {\n\t\t\tfor i := 0; n == -1 || i < n; i++ {\n\t\t\t\tval := ch.Recv()\n\t\t\t\tif ch.Closed() {\n\t\t\t\t\tif err = imp.encode(hdr, payClosed, nil); err != nil {\n\t\t\t\t\t\timpLog(\"error encoding client closed message:\", err)\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif err = imp.encode(hdr, payData, val.Interface()); err != nil {\n\t\t\t\t\timpLog(\"error encoding client send:\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/----------------------------------------\n\/\/\n\/\/ Copyright © ying32. All Rights Reserved.\n\/\/\n\/\/ Licensed under Apache License 2.0\n\/\/\n\/\/----------------------------------------\n\n\/\/ +build !windows\n\/\/ +build cgo\n\npackage vcl\n\n\/\/ #cgo darwin CFLAGS: -mmacosx-version-min=10.5 -DMACOSX_DEPLOYMENT_TARGET=10.5\n\/\/\n\/\/ extern void* doEventCallbackProc(void* f, void* args, long argcount);\n\/\/ static void* doGetEventCallbackAddr() {\n\/\/    return &doEventCallbackProc;\n\/\/ }\n\/\/\n\/\/ extern void* doMessageCallbackProc(void* f, void* msg);\n\/\/ static void* doGetMessageCallbackAddr() {\n\/\/    return &doMessageCallbackProc;\n\/\/ }\n\/\/\n\/\/ extern void* doThreadSyncCallbackProc();\n\/\/ static void* doGetThreadSyncCallbackAddr() {\n\/\/    return &doThreadSyncCallbackProc;\n\/\/ }\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\n\/\/export doEventCallbackProc\nfunc doEventCallbackProc(f unsafe.Pointer, args unsafe.Pointer, argcount C.long) unsafe.Pointer {\n\teventCallbackProc(uintptr(f), uintptr(args), int(argcount))\n\treturn nullptr\n}\n\n\/\/export doMessageCallbackProc\nfunc doMessageCallbackProc(f unsafe.Pointer, msg unsafe.Pointer) unsafe.Pointer {\n\tmessageCallbackProc(uintptr(f), uintptr(msg))\n\treturn nullptr\n}\n\n\/\/export doThreadSyncCallbackProc\nfunc doThreadSyncCallbackProc() unsafe.Pointer {\n\tthreadSyncCallbackProc()\n\treturn nullptr\n}\n\nvar (\n\teventCallback      = uintptr(C.doGetEventCallbackAddr())\n\tmessageCallback    = uintptr(C.doGetMessageCallbackAddr())\n\tthreadSyncCallback = uintptr(C.doGetThreadSyncCallbackAddr())\n)\n<commit_msg>add LDFLAGS<commit_after>\/\/----------------------------------------\n\/\/\n\/\/ Copyright © ying32. All Rights Reserved.\n\/\/\n\/\/ Licensed under Apache License 2.0\n\/\/\n\/\/----------------------------------------\n\n\/\/ +build !windows\n\/\/ +build cgo\n\npackage vcl\n\n\/\/ #cgo darwin CFLAGS: -mmacosx-version-min=10.5 -DMACOSX_DEPLOYMENT_TARGET=10.5\n\/\/ #cgo darwin LDFLAGS: -mmacosx-version-min=10.7\n\/\/\n\/\/ extern void* doEventCallbackProc(void* f, void* args, long argcount);\n\/\/ static void* doGetEventCallbackAddr() {\n\/\/    return &doEventCallbackProc;\n\/\/ }\n\/\/\n\/\/ extern void* doMessageCallbackProc(void* f, void* msg);\n\/\/ static void* doGetMessageCallbackAddr() {\n\/\/    return &doMessageCallbackProc;\n\/\/ }\n\/\/\n\/\/ extern void* doThreadSyncCallbackProc();\n\/\/ static void* doGetThreadSyncCallbackAddr() {\n\/\/    return &doThreadSyncCallbackProc;\n\/\/ }\nimport \"C\"\n\nimport (\n\t\"unsafe\"\n)\n\n\/\/export doEventCallbackProc\nfunc doEventCallbackProc(f unsafe.Pointer, args unsafe.Pointer, argcount C.long) unsafe.Pointer {\n\teventCallbackProc(uintptr(f), uintptr(args), int(argcount))\n\treturn nullptr\n}\n\n\/\/export doMessageCallbackProc\nfunc doMessageCallbackProc(f unsafe.Pointer, msg unsafe.Pointer) unsafe.Pointer {\n\tmessageCallbackProc(uintptr(f), uintptr(msg))\n\treturn nullptr\n}\n\n\/\/export doThreadSyncCallbackProc\nfunc doThreadSyncCallbackProc() unsafe.Pointer {\n\tthreadSyncCallbackProc()\n\treturn nullptr\n}\n\nvar (\n\teventCallback      = uintptr(C.doGetEventCallbackAddr())\n\tmessageCallback    = uintptr(C.doGetMessageCallbackAddr())\n\tthreadSyncCallback = uintptr(C.doGetThreadSyncCallbackAddr())\n)\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage metrics\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\n\t\"k8s.io\/apiserver\/pkg\/admission\"\n)\n\nconst (\n\tnamespace = \"apiserver\"\n\tsubsystem = \"admission\"\n)\n\nvar (\n\t\/\/ Use buckets ranging from 25 ms to ~2.5 seconds.\n\tlatencyBuckets       = prometheus.ExponentialBuckets(25000, 2.5, 5)\n\tlatencySummaryMaxAge = 5 * time.Hour\n\n\t\/\/ Metrics provides access to all admission metrics.\n\tMetrics = newAdmissionMetrics()\n)\n\n\/\/ ObserverFunc is a func that emits metrics.\ntype ObserverFunc func(elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string)\n\nconst (\n\tstepValidate = \"validate\"\n\tstepAdmit    = \"admit\"\n)\n\n\/\/ WithControllerMetrics is a decorator for named admission handlers.\nfunc WithControllerMetrics(i admission.Interface, name string) admission.Interface {\n\treturn WithMetrics(i, Metrics.ObserveAdmissionController, name)\n}\n\n\/\/ WithStepMetrics is a decorator for a whole admission phase, i.e. admit or validation.admission step.\nfunc WithStepMetrics(i admission.Interface) admission.Interface {\n\treturn WithMetrics(i, Metrics.ObserveAdmissionStep)\n}\n\n\/\/ WithMetrics is a decorator for admission handlers with a generic observer func.\nfunc WithMetrics(i admission.Interface, observer ObserverFunc, extraLabels ...string) admission.Interface {\n\treturn &pluginHandlerWithMetrics{\n\t\tInterface:   i,\n\t\tobserver:    observer,\n\t\textraLabels: extraLabels,\n\t}\n}\n\n\/\/ pluginHandlerWithMetrics decorates a admission handler with metrics.\ntype pluginHandlerWithMetrics struct {\n\tadmission.Interface\n\tobserver    ObserverFunc\n\textraLabels []string\n}\n\n\/\/ Admit performs a mutating admission control check and emit metrics.\nfunc (p pluginHandlerWithMetrics) Admit(a admission.Attributes) error {\n\tmutatingHandler, ok := p.Interface.(admission.MutationInterface)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tstart := time.Now()\n\terr := mutatingHandler.Admit(a)\n\tp.observer(time.Since(start), err != nil, a, stepAdmit, p.extraLabels...)\n\treturn err\n}\n\n\/\/ Validate performs a non-mutating admission control check and emits metrics.\nfunc (p pluginHandlerWithMetrics) Validate(a admission.Attributes) error {\n\tvalidatingHandler, ok := p.Interface.(admission.ValidationInterface)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tstart := time.Now()\n\terr := validatingHandler.Validate(a)\n\tp.observer(time.Since(start), err != nil, a, stepValidate, p.extraLabels...)\n\treturn err\n}\n\n\/\/ AdmissionMetrics instruments admission with prometheus metrics.\ntype AdmissionMetrics struct {\n\tstep       *metricSet\n\tcontroller *metricSet\n\twebhook    *metricSet\n}\n\n\/\/ newAdmissionMetrics create a new AdmissionMetrics, configured with default metric names.\nfunc newAdmissionMetrics() *AdmissionMetrics {\n\t\/\/ Admission metrics for a step of the admission flow. The entire admission flow is broken down into a series of steps\n\t\/\/ Each step is identified by a distinct type label value.\n\tstep := newMetricSet(\"step\",\n\t\t[]string{\"type\", \"operation\", \"rejected\"},\n\t\t\"Admission sub-step %s, broken out for each operation and API resource and step type (validate or admit).\", true)\n\n\t\/\/ Built-in admission controller metrics. Each admission controller is identified by name.\n\tcontroller := newMetricSet(\"controller\",\n\t\t[]string{\"name\", \"type\", \"operation\", \"rejected\"},\n\t\t\"Admission controller %s, identified by name and broken out for each operation and API resource and type (validate or admit).\", false)\n\n\t\/\/ Admission webhook metrics. Each webhook is identified by name.\n\twebhook := newMetricSet(\"webhook\",\n\t\t[]string{\"name\", \"type\", \"operation\", \"rejected\"},\n\t\t\"Admission webhook %s, identified by name and broken out for each operation and API resource and type (validate or admit).\", false)\n\n\tstep.mustRegister()\n\tcontroller.mustRegister()\n\twebhook.mustRegister()\n\treturn &AdmissionMetrics{step: step, controller: controller, webhook: webhook}\n}\n\nfunc (m *AdmissionMetrics) reset() {\n\tm.step.reset()\n\tm.controller.reset()\n\tm.webhook.reset()\n}\n\n\/\/ ObserveAdmissionStep records admission related metrics for a admission step, identified by step type.\nfunc (m *AdmissionMetrics) ObserveAdmissionStep(elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string) {\n\tm.step.observe(elapsed, append(extraLabels, stepType, string(attr.GetOperation()), strconv.FormatBool(rejected))...)\n}\n\n\/\/ ObserveAdmissionController records admission related metrics for a built-in admission controller, identified by it's plugin handler name.\nfunc (m *AdmissionMetrics) ObserveAdmissionController(elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string) {\n\tm.controller.observe(elapsed, append(extraLabels, stepType, string(attr.GetOperation()), strconv.FormatBool(rejected))...)\n}\n\n\/\/ ObserveWebhook records admission related metrics for a admission webhook.\nfunc (m *AdmissionMetrics) ObserveWebhook(elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string) {\n\tm.webhook.observe(elapsed, append(extraLabels, stepType, string(attr.GetOperation()), strconv.FormatBool(rejected))...)\n}\n\ntype metricSet struct {\n\tlatencies        *prometheus.HistogramVec\n\tlatenciesSummary *prometheus.SummaryVec\n}\n\nfunc newMetricSet(name string, labels []string, helpTemplate string, hasSummary bool) *metricSet {\n\tvar summary *prometheus.SummaryVec\n\tif hasSummary {\n\t\tsummary = prometheus.NewSummaryVec(\n\t\t\tprometheus.SummaryOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName:      fmt.Sprintf(\"%s_admission_latencies_seconds_summary\", name),\n\t\t\t\tHelp:      fmt.Sprintf(helpTemplate, \"latency summary\"),\n\t\t\t\tMaxAge:    latencySummaryMaxAge,\n\t\t\t},\n\t\t\tlabels,\n\t\t)\n\t}\n\n\treturn &metricSet{\n\t\tlatencies: prometheus.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName:      fmt.Sprintf(\"%s_admission_latencies_seconds\", name),\n\t\t\t\tHelp:      fmt.Sprintf(helpTemplate, \"latency histogram\"),\n\t\t\t\tBuckets:   latencyBuckets,\n\t\t\t},\n\t\t\tlabels,\n\t\t),\n\n\t\tlatenciesSummary: summary,\n\t}\n}\n\n\/\/ MustRegister registers all the prometheus metrics in the metricSet.\nfunc (m *metricSet) mustRegister() {\n\tprometheus.MustRegister(m.latencies)\n\tif m.latenciesSummary != nil {\n\t\tprometheus.MustRegister(m.latenciesSummary)\n\t}\n}\n\n\/\/ Reset resets all the prometheus metrics in the metricSet.\nfunc (m *metricSet) reset() {\n\tm.latencies.Reset()\n\tif m.latenciesSummary != nil {\n\t\tm.latenciesSummary.Reset()\n\t}\n}\n\n\/\/ Observe records an observed admission event to all metrics in the metricSet.\nfunc (m *metricSet) observe(elapsed time.Duration, labels ...string) {\n\telapsedSeconds := elapsed.Seconds()\n\tm.latencies.WithLabelValues(labels...).Observe(elapsedSeconds)\n\tif m.latenciesSummary != nil {\n\t\tm.latenciesSummary.WithLabelValues(labels...).Observe(elapsedSeconds)\n\t}\n}\n<commit_msg>Add admission_latencies_milliseconds metrics for backward compatible<commit_after>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage metrics\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\n\t\"k8s.io\/apiserver\/pkg\/admission\"\n)\n\nconst (\n\tnamespace = \"apiserver\"\n\tsubsystem = \"admission\"\n)\n\nvar (\n\t\/\/ Use buckets ranging from 25 ms to ~2.5 seconds.\n\tlatencyBuckets       = prometheus.ExponentialBuckets(25000, 2.5, 5)\n\tlatencySummaryMaxAge = 5 * time.Hour\n\n\t\/\/ Metrics provides access to all admission metrics.\n\tMetrics = newAdmissionMetrics()\n)\n\n\/\/ ObserverFunc is a func that emits metrics.\ntype ObserverFunc func(elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string)\n\nconst (\n\tstepValidate = \"validate\"\n\tstepAdmit    = \"admit\"\n)\n\n\/\/ WithControllerMetrics is a decorator for named admission handlers.\nfunc WithControllerMetrics(i admission.Interface, name string) admission.Interface {\n\treturn WithMetrics(i, Metrics.ObserveAdmissionController, name)\n}\n\n\/\/ WithStepMetrics is a decorator for a whole admission phase, i.e. admit or validation.admission step.\nfunc WithStepMetrics(i admission.Interface) admission.Interface {\n\treturn WithMetrics(i, Metrics.ObserveAdmissionStep)\n}\n\n\/\/ WithMetrics is a decorator for admission handlers with a generic observer func.\nfunc WithMetrics(i admission.Interface, observer ObserverFunc, extraLabels ...string) admission.Interface {\n\treturn &pluginHandlerWithMetrics{\n\t\tInterface:   i,\n\t\tobserver:    observer,\n\t\textraLabels: extraLabels,\n\t}\n}\n\n\/\/ pluginHandlerWithMetrics decorates a admission handler with metrics.\ntype pluginHandlerWithMetrics struct {\n\tadmission.Interface\n\tobserver    ObserverFunc\n\textraLabels []string\n}\n\n\/\/ Admit performs a mutating admission control check and emit metrics.\nfunc (p pluginHandlerWithMetrics) Admit(a admission.Attributes) error {\n\tmutatingHandler, ok := p.Interface.(admission.MutationInterface)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tstart := time.Now()\n\terr := mutatingHandler.Admit(a)\n\tp.observer(time.Since(start), err != nil, a, stepAdmit, p.extraLabels...)\n\treturn err\n}\n\n\/\/ Validate performs a non-mutating admission control check and emits metrics.\nfunc (p pluginHandlerWithMetrics) Validate(a admission.Attributes) error {\n\tvalidatingHandler, ok := p.Interface.(admission.ValidationInterface)\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tstart := time.Now()\n\terr := validatingHandler.Validate(a)\n\tp.observer(time.Since(start), err != nil, a, stepValidate, p.extraLabels...)\n\treturn err\n}\n\n\/\/ AdmissionMetrics instruments admission with prometheus metrics.\ntype AdmissionMetrics struct {\n\tstep       *metricSet\n\tcontroller *metricSet\n\twebhook    *metricSet\n}\n\n\/\/ newAdmissionMetrics create a new AdmissionMetrics, configured with default metric names.\nfunc newAdmissionMetrics() *AdmissionMetrics {\n\t\/\/ Admission metrics for a step of the admission flow. The entire admission flow is broken down into a series of steps\n\t\/\/ Each step is identified by a distinct type label value.\n\tstep := newMetricSet(\"step\",\n\t\t[]string{\"type\", \"operation\", \"rejected\"},\n\t\t\"Admission sub-step %s, broken out for each operation and API resource and step type (validate or admit).\", true)\n\n\t\/\/ Built-in admission controller metrics. Each admission controller is identified by name.\n\tcontroller := newMetricSet(\"controller\",\n\t\t[]string{\"name\", \"type\", \"operation\", \"rejected\"},\n\t\t\"Admission controller %s, identified by name and broken out for each operation and API resource and type (validate or admit).\", false)\n\n\t\/\/ Admission webhook metrics. Each webhook is identified by name.\n\twebhook := newMetricSet(\"webhook\",\n\t\t[]string{\"name\", \"type\", \"operation\", \"rejected\"},\n\t\t\"Admission webhook %s, identified by name and broken out for each operation and API resource and type (validate or admit).\", false)\n\n\tstep.mustRegister()\n\tcontroller.mustRegister()\n\twebhook.mustRegister()\n\treturn &AdmissionMetrics{step: step, controller: controller, webhook: webhook}\n}\n\nfunc (m *AdmissionMetrics) reset() {\n\tm.step.reset()\n\tm.controller.reset()\n\tm.webhook.reset()\n}\n\n\/\/ ObserveAdmissionStep records admission related metrics for a admission step, identified by step type.\nfunc (m *AdmissionMetrics) ObserveAdmissionStep(elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string) {\n\tm.step.observe(elapsed, append(extraLabels, stepType, string(attr.GetOperation()), strconv.FormatBool(rejected))...)\n}\n\n\/\/ ObserveAdmissionController records admission related metrics for a built-in admission controller, identified by it's plugin handler name.\nfunc (m *AdmissionMetrics) ObserveAdmissionController(elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string) {\n\tm.controller.observe(elapsed, append(extraLabels, stepType, string(attr.GetOperation()), strconv.FormatBool(rejected))...)\n}\n\n\/\/ ObserveWebhook records admission related metrics for a admission webhook.\nfunc (m *AdmissionMetrics) ObserveWebhook(elapsed time.Duration, rejected bool, attr admission.Attributes, stepType string, extraLabels ...string) {\n\tm.webhook.observe(elapsed, append(extraLabels, stepType, string(attr.GetOperation()), strconv.FormatBool(rejected))...)\n}\n\ntype metricSet struct {\n\tlatencies                  *prometheus.HistogramVec\n\tdeprecatedLatencies        *prometheus.HistogramVec\n\tlatenciesSummary           *prometheus.SummaryVec\n\tdeprecatedLatenciesSummary *prometheus.SummaryVec\n}\n\nfunc newMetricSet(name string, labels []string, helpTemplate string, hasSummary bool) *metricSet {\n\tvar summary, deprecatedSummary *prometheus.SummaryVec\n\tif hasSummary {\n\t\tsummary = prometheus.NewSummaryVec(\n\t\t\tprometheus.SummaryOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName:      fmt.Sprintf(\"%s_admission_latencies_seconds_summary\", name),\n\t\t\t\tHelp:      fmt.Sprintf(helpTemplate, \"latency summary in seconds\"),\n\t\t\t\tMaxAge:    latencySummaryMaxAge,\n\t\t\t},\n\t\t\tlabels,\n\t\t)\n\t\tdeprecatedSummary = prometheus.NewSummaryVec(\n\t\t\tprometheus.SummaryOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName:      fmt.Sprintf(\"%s_admission_latencies_milliseconds_summary\", name),\n\t\t\t\tHelp:      fmt.Sprintf(\"(Deprecated) \"+helpTemplate, \"latency summary in milliseconds\"),\n\t\t\t\tMaxAge:    latencySummaryMaxAge,\n\t\t\t},\n\t\t\tlabels,\n\t\t)\n\t}\n\n\treturn &metricSet{\n\t\tlatencies: prometheus.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName:      fmt.Sprintf(\"%s_admission_latencies_seconds\", name),\n\t\t\t\tHelp:      fmt.Sprintf(helpTemplate, \"latency histogram in seconds\"),\n\t\t\t\tBuckets:   latencyBuckets,\n\t\t\t},\n\t\t\tlabels,\n\t\t),\n\t\tdeprecatedLatencies: prometheus.NewHistogramVec(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tNamespace: namespace,\n\t\t\t\tSubsystem: subsystem,\n\t\t\t\tName:      fmt.Sprintf(\"%s_admission_latencies_milliseconds\", name),\n\t\t\t\tHelp:      fmt.Sprintf(\"(Deprecated) \"+helpTemplate, \"latency histogram in milliseconds\"),\n\t\t\t\tBuckets:   latencyBuckets,\n\t\t\t},\n\t\t\tlabels,\n\t\t),\n\n\t\tlatenciesSummary:           summary,\n\t\tdeprecatedLatenciesSummary: deprecatedSummary,\n\t}\n}\n\n\/\/ MustRegister registers all the prometheus metrics in the metricSet.\nfunc (m *metricSet) mustRegister() {\n\tprometheus.MustRegister(m.latencies)\n\tprometheus.MustRegister(m.deprecatedLatencies)\n\tif m.latenciesSummary != nil {\n\t\tprometheus.MustRegister(m.latenciesSummary)\n\t}\n\tif m.deprecatedLatenciesSummary != nil {\n\t\tprometheus.MustRegister(m.deprecatedLatenciesSummary)\n\t}\n}\n\n\/\/ Reset resets all the prometheus metrics in the metricSet.\nfunc (m *metricSet) reset() {\n\tm.latencies.Reset()\n\tm.deprecatedLatencies.Reset()\n\tif m.latenciesSummary != nil {\n\t\tm.latenciesSummary.Reset()\n\t}\n\tif m.deprecatedLatenciesSummary != nil {\n\t\tm.deprecatedLatenciesSummary.Reset()\n\t}\n}\n\n\/\/ Observe records an observed admission event to all metrics in the metricSet.\nfunc (m *metricSet) observe(elapsed time.Duration, labels ...string) {\n\telapsedSeconds := elapsed.Seconds()\n\telapsedMicroseconds := float64(elapsed \/ time.Microsecond)\n\tm.latencies.WithLabelValues(labels...).Observe(elapsedSeconds)\n\tm.deprecatedLatencies.WithLabelValues(labels...).Observe(elapsedMicroseconds)\n\tif m.latenciesSummary != nil {\n\t\tm.latenciesSummary.WithLabelValues(labels...).Observe(elapsedSeconds)\n\t}\n\tif m.deprecatedLatenciesSummary != nil {\n\t\tm.deprecatedLatenciesSummary.WithLabelValues(labels...).Observe(elapsedMicroseconds)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package quibit\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestAcceptance(t *testing.T) {\n\tlog := make(chan string, 100)\n\trecvChan := make(chan Frame, 10)\n\tsendChan := make(chan Frame, 10)\n\tpeerChan := make(chan Peer)\n\tport := uint16(4444)\n\n\t\/\/ Initialize Quibit\n\terr := Initialize(log, recvChan, sendChan, peerChan, port)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR INITIALIZING! \", err)\n\t\tt.FailNow()\n\t}\n\n\t\/\/ Test 1: Manual Connection, look for receive\n\tconn, err := net.Dial(\"tcp\", \"127.0.0.1:4444\")\n\tif err != nil {\n\t\tfmt.Println(\"Error connecting: \", err)\n\t\tt.FailNow()\n\t}\n\n\ttime.Sleep(time.Millisecond)\n\tif len(peerList) == 0 {\n\t\tfmt.Println(\"Not in peer list!\")\n\t\tt.FailNow()\n\t}\n\n\tdata := []byte{'a', 'b', 'c', 'd'}\n\tframe := new(Frame)\n\tframe.Configure(data, 1, 1)\n\n\tbuf, _ := frame.Header.ToBytes()\n\t_, err = conn.Write(buf)\n\tif err != nil {\n\t\tfmt.Println(\"Error writing header: \", err)\n\t\tt.FailNow()\n\t}\n\n\t_, err = conn.Write(frame.Payload)\n\tif err != nil {\n\t\tfmt.Println(\"Error writing payload: \", err)\n\t\tt.FailNow()\n\t}\n\n\tframe2 := <-recvChan\n\tif string(frame2.Payload) != string(data) {\n\t\tfmt.Println(\"Bad frame! \", frame2)\n\t\tt.FailNow()\n\t}\n\n\tif frame2.Peer != conn.LocalAddr().String() {\n\t\tfmt.Println(\"Peer doesn't match! \", frame2.Peer, conn.LocalAddr().String())\n\t\tt.FailNow()\n\t}\n\n\t\/\/ Test 2: Send, look for manual receive\n\tsendChan <- frame2\n\ttime.Sleep(time.Millisecond)\n\n\t\/\/ So now we have a connection.  Let's shake hands.\n\theader3 := recvHeader(conn, log)\n\tframe3, err := recvPayload(conn, header3)\n\n\tif err != nil {\n\t\tfmt.Println(\"Error Receiving Frame 3... \", err)\n\t\tt.FailNow()\n\t}\n\n\tif string(frame3.Payload) != string(data) {\n\t\tfmt.Println(\"Bad frame! \", frame3)\n\t\tt.FailNow()\n\t}\n\n\tconn.Close()\n\tCleanup()\n}\n<commit_msg>Fixed test suite<commit_after>package quibit\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestAcceptance(t *testing.T) {\n\tlog := make(chan string, 100)\n\trecvChan := make(chan Frame, 10)\n\tsendChan := make(chan Frame, 10)\n\tpeerChan := make(chan Peer)\n\tport := uint16(4444)\n\n\t\/\/ Initialize Quibit\n\terr := Initialize(log, recvChan, sendChan, peerChan, port)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR INITIALIZING! \", err)\n\t\tt.FailNow()\n\t}\n\n\t\/\/ Test 1: Manual Connection, look for receive\n\tconn, err := net.Dial(\"tcp\", \"127.0.0.1:4444\")\n\tif err != nil {\n\t\tfmt.Println(\"Error connecting: \", err)\n\t\tt.FailNow()\n\t}\n\n\ttime.Sleep(time.Millisecond)\n\tif len(peerList) == 0 {\n\t\tfmt.Println(\"Not in peer list!\")\n\t\tt.FailNow()\n\t}\n\n\tdata := []byte{'a', 'b', 'c', 'd'}\n\tframe := new(Frame)\n\tframe.Configure(data, 1, 1)\n\n\tbuf, _ := frame.Header.ToBytes()\n\t_, err = conn.Write(buf)\n\tif err != nil {\n\t\tfmt.Println(\"Error writing header: \", err)\n\t\tt.FailNow()\n\t}\n\n\t_, err = conn.Write(frame.Payload)\n\tif err != nil {\n\t\tfmt.Println(\"Error writing payload: \", err)\n\t\tt.FailNow()\n\t}\n\n\tframe2 := <-recvChan\n\tif string(frame2.Payload) != string(data) {\n\t\tfmt.Println(\"Bad frame! \", frame2)\n\t\tt.FailNow()\n\t}\n\n\tif frame2.Peer != conn.LocalAddr().String() {\n\t\tfmt.Println(\"Peer doesn't match! \", frame2.Peer, conn.LocalAddr().String())\n\t\tt.FailNow()\n\t}\n\n\t\/\/ Test 2: Send, look for manual receive\n\tsendChan <- frame2\n\ttime.Sleep(time.Millisecond)\n\n\t\/\/ So now we have a connection.  Let's shake hands.\n\theader3, _ := recvHeader(conn, log)\n\tframe3, err := recvPayload(conn, header3)\n\n\tif err != nil {\n\t\tfmt.Println(\"Error Receiving Frame 3... \", err)\n\t\tt.FailNow()\n\t}\n\n\tif string(frame3.Payload) != string(data) {\n\t\tfmt.Println(\"Bad frame! \", frame3)\n\t\tt.FailNow()\n\t}\n\n\tconn.Close()\n\tCleanup()\n}\n<|endoftext|>"}
{"text":"<commit_before>package storage\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"scal\"\n\t\"scal\/settings\"\n\t\"time\"\n\n\t\"gopkg.in\/mgo.v2\"\n)\n\ntype hasHex interface {\n\tHex() string\n}\n\nfunc Hex(id interface{}) string {\n\tif id == nil {\n\t\treturn \"\"\n\t}\n\tid2, ok := id.(hasHex)\n\tif !ok {\n\t\tlog.Print(\"storage.Hex: can not convert to hex: \", id)\n\t\treturn \"\"\n\t}\n\treturn id2.Hex()\n}\n\ntype MongoDatabase struct {\n\tmgo.Database\n}\n\nfunc (db *MongoDatabase) IsNotFound(err error) bool {\n\treturn err == mgo.ErrNotFound\n}\nfunc (db *MongoDatabase) Insert(model hasCollection) error {\n\treturn db.C(model.Collection()).Insert(model)\n}\nfunc (db *MongoDatabase) Update(model hasCollectionUniqueM) error {\n\treturn db.C(model.Collection()).Update(\n\t\tmodel.UniqueM(),\n\t\tmodel,\n\t)\n}\nfunc (db *MongoDatabase) Upsert(model hasCollectionUniqueM) error {\n\t_, err := db.C(model.Collection()).Upsert(\n\t\tmodel.UniqueM(),\n\t\tmodel,\n\t)\n\treturn err\n}\nfunc (db *MongoDatabase) Remove(model hasCollectionUniqueM) error {\n\treturn db.C(model.Collection()).Remove(\n\t\tmodel.UniqueM(),\n\t)\n}\n\n\/\/func (db *MongoDatabase) Find(interface{})\nfunc (db *MongoDatabase) Get(model hasCollectionUniqueM) error {\n\treturn db.C(model.Collection()).Find(\n\t\tmodel.UniqueM(),\n\t).One(model)\n}\nfunc (db *MongoDatabase) First(\n\tcond scal.M,\n\tsortBy string,\n\tmodel hasCollection,\n) error {\n\treturn db.C(model.Collection()).Find(cond).Sort(sortBy).One(model)\n}\nfunc (db *MongoDatabase) FindCount(colName string, cond scal.M) (int, error) {\n\treturn db.C(colName).Find(cond).Count()\n}\n\nfunc (db *MongoDatabase) FindAll(\n\tcolName string,\n\tcond scal.M,\n\tresult interface{},\n) error {\n\treturn db.C(colName).Find(cond).All(result)\n}\nfunc (db *MongoDatabase) PipeAll(\n\tcolName string,\n\tpipeline *[]scal.M,\n\tresult interface{},\n) error {\n\treturn db.C(colName).Pipe(pipeline).All(result)\n}\n\nfunc (db *MongoDatabase) PipeIter(\n\tcolName string,\n\tpipeline *[]scal.M,\n) <-chan scal.MErr {\n\tch := make(chan scal.MErr)\n\titer := db.C(colName).Pipe(pipeline).Iter()\n\tgo func() {\n\t\tdefer iter.Close()\n\t\tdefer close(ch)\n\t\tresM := scal.M{}\n\t\tfor iter.Next(&resM) {\n\t\t\tch <- scal.MErr{M: resM}\n\t\t\tresM = scal.M{}\n\t\t}\n\t\tif err := iter.Err(); err != nil {\n\t\t\tch <- scal.MErr{Err: err}\n\t\t}\n\t\tif iter.Timeout() {\n\t\t\tch <- scal.MErr{Err: errors.New(\"timeout\")}\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc GetDB() (Database, error) {\n\tmongoDBDialInfo := &mgo.DialInfo{\n\t\tAddrs:    []string{settings.MONGO_HOST},\n\t\tTimeout:  2 * time.Second,\n\t\tDatabase: settings.MONGO_DB_NAME,\n\t\tUsername: settings.MONGO_USERNAME,\n\t\tPassword: settings.MONGO_PASSWORD,\n\t}\n\n\t\/\/ Create a session which maintains a pool of socket connections\n\t\/\/ to our MongoDB.\n\tmongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Reads may not be entirely up-to-date, but they will always see the\n\t\/\/ history of changes moving forward, the data read will be consistent\n\t\/\/ across sequential queries in the same session, and modifications made\n\t\/\/ within the session will be observed in following queries (read-your-writes).\n\t\/\/ http:\/\/godoc.org\/labix.org\/v2\/mgo#Session.SetMode\n\tmongoSession.SetMode(mgo.Monotonic, true)\n\n\treturn &MongoDatabase{\n\t\t*mongoSession.DB(settings.MONGO_DB_NAME),\n\t}, nil\n}\n<commit_msg>don't create a mongodb session \/ connection for each request<commit_after>package storage\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"scal\"\n\t\"scal\/settings\"\n\t\"time\"\n\n\t\"gopkg.in\/mgo.v2\"\n)\n\ntype hasHex interface {\n\tHex() string\n}\n\nfunc Hex(id interface{}) string {\n\tif id == nil {\n\t\treturn \"\"\n\t}\n\tid2, ok := id.(hasHex)\n\tif !ok {\n\t\tlog.Print(\"storage.Hex: can not convert to hex: \", id)\n\t\treturn \"\"\n\t}\n\treturn id2.Hex()\n}\n\nvar db *MongoDatabase\n\ntype MongoDatabase struct {\n\tmgo.Database\n}\n\nfunc (db *MongoDatabase) IsNotFound(err error) bool {\n\treturn err == mgo.ErrNotFound\n}\nfunc (db *MongoDatabase) Insert(model hasCollection) error {\n\treturn db.C(model.Collection()).Insert(model)\n}\nfunc (db *MongoDatabase) Update(model hasCollectionUniqueM) error {\n\treturn db.C(model.Collection()).Update(\n\t\tmodel.UniqueM(),\n\t\tmodel,\n\t)\n}\nfunc (db *MongoDatabase) Upsert(model hasCollectionUniqueM) error {\n\t_, err := db.C(model.Collection()).Upsert(\n\t\tmodel.UniqueM(),\n\t\tmodel,\n\t)\n\treturn err\n}\nfunc (db *MongoDatabase) Remove(model hasCollectionUniqueM) error {\n\treturn db.C(model.Collection()).Remove(\n\t\tmodel.UniqueM(),\n\t)\n}\n\n\/\/func (db *MongoDatabase) Find(interface{})\nfunc (db *MongoDatabase) Get(model hasCollectionUniqueM) error {\n\treturn db.C(model.Collection()).Find(\n\t\tmodel.UniqueM(),\n\t).One(model)\n}\nfunc (db *MongoDatabase) First(\n\tcond scal.M,\n\tsortBy string,\n\tmodel hasCollection,\n) error {\n\treturn db.C(model.Collection()).Find(cond).Sort(sortBy).One(model)\n}\nfunc (db *MongoDatabase) FindCount(colName string, cond scal.M) (int, error) {\n\treturn db.C(colName).Find(cond).Count()\n}\n\nfunc (db *MongoDatabase) FindAll(\n\tcolName string,\n\tcond scal.M,\n\tresult interface{},\n) error {\n\treturn db.C(colName).Find(cond).All(result)\n}\nfunc (db *MongoDatabase) PipeAll(\n\tcolName string,\n\tpipeline *[]scal.M,\n\tresult interface{},\n) error {\n\treturn db.C(colName).Pipe(pipeline).All(result)\n}\n\nfunc (db *MongoDatabase) PipeIter(\n\tcolName string,\n\tpipeline *[]scal.M,\n) <-chan scal.MErr {\n\tch := make(chan scal.MErr)\n\titer := db.C(colName).Pipe(pipeline).Iter()\n\tgo func() {\n\t\tdefer iter.Close()\n\t\tdefer close(ch)\n\t\tresM := scal.M{}\n\t\tfor iter.Next(&resM) {\n\t\t\tch <- scal.MErr{M: resM}\n\t\t\tresM = scal.M{}\n\t\t}\n\t\tif err := iter.Err(); err != nil {\n\t\t\tch <- scal.MErr{Err: err}\n\t\t}\n\t\tif iter.Timeout() {\n\t\t\tch <- scal.MErr{Err: errors.New(\"timeout\")}\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc GetDB() (Database, error) {\n\tif db != nil {\n\t\treturn db, nil\n\t}\n\tmongoDBDialInfo := &mgo.DialInfo{\n\t\tAddrs:    []string{settings.MONGO_HOST},\n\t\tTimeout:  2 * time.Second,\n\t\tDatabase: settings.MONGO_DB_NAME,\n\t\tUsername: settings.MONGO_USERNAME,\n\t\tPassword: settings.MONGO_PASSWORD,\n\t}\n\n\t\/\/ Create a session which maintains a pool of socket connections\n\t\/\/ to our MongoDB.\n\tmongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Reads may not be entirely up-to-date, but they will always see the\n\t\/\/ history of changes moving forward, the data read will be consistent\n\t\/\/ across sequential queries in the same session, and modifications made\n\t\/\/ within the session will be observed in following queries (read-your-writes).\n\t\/\/ http:\/\/godoc.org\/labix.org\/v2\/mgo#Session.SetMode\n\tmongoSession.SetMode(mgo.Monotonic, true)\n\n\tdb = &MongoDatabase{\n\t\t*mongoSession.DB(settings.MONGO_DB_NAME),\n\t}\n\treturn db, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage metrics\n\nimport (\n\t\"context\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\tcompbasemetrics \"k8s.io\/component-base\/metrics\"\n\t\"k8s.io\/component-base\/metrics\/legacyregistry\"\n\tbasemetricstestutil \"k8s.io\/component-base\/metrics\/testutil\"\n\t\"k8s.io\/utils\/clock\"\n)\n\nconst (\n\tnamespace = \"apiserver\"\n\tsubsystem = \"flowcontrol\"\n)\n\nconst (\n\trequestKind   = \"request_kind\"\n\tpriorityLevel = \"priority_level\"\n\tflowSchema    = \"flow_schema\"\n\tphase         = \"phase\"\n\tmark          = \"mark\"\n)\n\nvar (\n\tqueueLengthBuckets            = []float64{0, 10, 25, 50, 100, 250, 500, 1000}\n\trequestDurationSecondsBuckets = []float64{0, 0.005, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30}\n)\n\nvar registerMetrics sync.Once\n\n\/\/ Register all metrics.\nfunc Register() {\n\tregisterMetrics.Do(func() {\n\t\tfor _, metric := range metrics {\n\t\t\tlegacyregistry.MustRegister(metric)\n\t\t}\n\t})\n}\n\ntype resettable interface {\n\tReset()\n}\n\n\/\/ Reset all metrics to zero\nfunc Reset() {\n\tfor _, metric := range metrics {\n\t\trm := metric.(resettable)\n\t\trm.Reset()\n\t}\n}\n\n\/\/ GatherAndCompare the given metrics with the given Prometheus syntax expected value\nfunc GatherAndCompare(expected string, metricNames ...string) error {\n\treturn basemetricstestutil.GatherAndCompare(legacyregistry.DefaultGatherer, strings.NewReader(expected), metricNames...)\n}\n\n\/\/ Registerables is a slice of Registerable\ntype Registerables []compbasemetrics.Registerable\n\n\/\/ Append adds more\nfunc (rs Registerables) Append(more ...compbasemetrics.Registerable) Registerables {\n\treturn append(rs, more...)\n}\n\nvar (\n\tapiserverRejectedRequestsTotal = compbasemetrics.NewCounterVec(\n\t\t&compbasemetrics.CounterOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"rejected_requests_total\",\n\t\t\tHelp:           \"Number of requests rejected by API Priority and Fairness system\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema, \"reason\"},\n\t)\n\tapiserverDispatchedRequestsTotal = compbasemetrics.NewCounterVec(\n\t\t&compbasemetrics.CounterOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"dispatched_requests_total\",\n\t\t\tHelp:           \"Number of requests released by API Priority and Fairness system for service\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema},\n\t)\n\n\t\/\/ PriorityLevelConcurrencyObserverPairGenerator creates pairs that observe concurrency for priority levels\n\tPriorityLevelConcurrencyObserverPairGenerator = NewSampleAndWaterMarkHistogramsPairGenerator(clock.RealClock{}, time.Millisecond,\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"priority_level_request_count_samples\",\n\t\t\tHelp:           \"Periodic observations of the number of requests\",\n\t\t\tBuckets:        []float64{0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1},\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"priority_level_request_count_watermarks\",\n\t\t\tHelp:           \"Watermarks of the number of requests\",\n\t\t\tBuckets:        []float64{0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1},\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel})\n\n\t\/\/ ReadWriteConcurrencyObserverPairGenerator creates pairs that observe concurrency broken down by mutating vs readonly\n\tReadWriteConcurrencyObserverPairGenerator = NewSampleAndWaterMarkHistogramsPairGenerator(clock.RealClock{}, time.Millisecond,\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"read_vs_write_request_count_samples\",\n\t\t\tHelp:           \"Periodic observations of the number of requests\",\n\t\t\tBuckets:        []float64{0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1},\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"read_vs_write_request_count_watermarks\",\n\t\t\tHelp:           \"Watermarks of the number of requests\",\n\t\t\tBuckets:        []float64{0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1},\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{requestKind})\n\n\tapiserverCurrentR = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"current_r\",\n\t\t\tHelp:           \"R(time of last change)\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel},\n\t)\n\n\tapiserverDispatchR = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"dispatch_r\",\n\t\t\tHelp:           \"R(time of last dispatch)\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel},\n\t)\n\n\tapiserverLatestS = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"latest_s\",\n\t\t\tHelp:           \"S(most recently dispatched request)\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel},\n\t)\n\n\tapiserverNextSBounds = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"next_s_bounds\",\n\t\t\tHelp:           \"min and max, over queues, of S(oldest waiting request in queue)\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, \"bound\"},\n\t)\n\n\tapiserverNextDiscountedSBounds = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"next_discounted_s_bounds\",\n\t\t\tHelp:           \"min and max, over queues, of S(oldest waiting request in queue) - estimated work in progress\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, \"bound\"},\n\t)\n\n\tapiserverCurrentInqueueRequests = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"current_inqueue_requests\",\n\t\t\tHelp:           \"Number of requests currently pending in queues of the API Priority and Fairness system\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema},\n\t)\n\tapiserverRequestQueueLength = compbasemetrics.NewHistogramVec(\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"request_queue_length_after_enqueue\",\n\t\t\tHelp:           \"Length of queue in the API Priority and Fairness system, as seen by each request after it is enqueued\",\n\t\t\tBuckets:        queueLengthBuckets,\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema},\n\t)\n\tapiserverRequestConcurrencyLimit = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"request_concurrency_limit\",\n\t\t\tHelp:           \"Shared concurrency limit in the API Priority and Fairness system\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel},\n\t)\n\tapiserverCurrentExecutingRequests = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"current_executing_requests\",\n\t\t\tHelp:           \"Number of requests currently executing in the API Priority and Fairness system\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema},\n\t)\n\tapiserverRequestConcurrencyInUse = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"request_concurrency_in_use\",\n\t\t\tHelp:           \"Concurrency (number of seats) occupided by the currently executing requests in the API Priority and Fairness system\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema},\n\t)\n\tapiserverRequestWaitingSeconds = compbasemetrics.NewHistogramVec(\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"request_wait_duration_seconds\",\n\t\t\tHelp:           \"Length of time a request spent waiting in its queue\",\n\t\t\tBuckets:        requestDurationSecondsBuckets,\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema, \"execute\"},\n\t)\n\tapiserverRequestExecutionSeconds = compbasemetrics.NewHistogramVec(\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"request_execution_seconds\",\n\t\t\tHelp:           \"Duration of request execution in the API Priority and Fairness system\",\n\t\t\tBuckets:        requestDurationSecondsBuckets,\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema},\n\t)\n\tmetrics = Registerables{\n\t\tapiserverRejectedRequestsTotal,\n\t\tapiserverDispatchedRequestsTotal,\n\t\tapiserverCurrentR,\n\t\tapiserverDispatchR,\n\t\tapiserverLatestS,\n\t\tapiserverNextSBounds,\n\t\tapiserverNextDiscountedSBounds,\n\t\tapiserverCurrentInqueueRequests,\n\t\tapiserverRequestQueueLength,\n\t\tapiserverRequestConcurrencyLimit,\n\t\tapiserverRequestConcurrencyInUse,\n\t\tapiserverCurrentExecutingRequests,\n\t\tapiserverRequestWaitingSeconds,\n\t\tapiserverRequestExecutionSeconds,\n\t}.\n\t\tAppend(PriorityLevelConcurrencyObserverPairGenerator.metrics()...).\n\t\tAppend(ReadWriteConcurrencyObserverPairGenerator.metrics()...)\n)\n\n\/\/ AddRequestsInQueues adds the given delta to the gauge of the # of requests in the queues of the specified flowSchema and priorityLevel\nfunc AddRequestsInQueues(ctx context.Context, priorityLevel, flowSchema string, delta int) {\n\tapiserverCurrentInqueueRequests.WithLabelValues(priorityLevel, flowSchema).Add(float64(delta))\n}\n\n\/\/ AddRequestsExecuting adds the given delta to the gauge of executing requests of the given flowSchema and priorityLevel\nfunc AddRequestsExecuting(ctx context.Context, priorityLevel, flowSchema string, delta int) {\n\tapiserverCurrentExecutingRequests.WithLabelValues(priorityLevel, flowSchema).Add(float64(delta))\n}\n\n\/\/ SetCurrentR sets the current-R (virtualTime) gauge for the given priority level\nfunc SetCurrentR(priorityLevel string, r float64) {\n\tapiserverCurrentR.WithLabelValues(priorityLevel).Set(r)\n}\n\n\/\/ SetLatestS sets the latest-S (virtual time of dispatched request) gauge for the given priority level\nfunc SetDispatchMetrics(priorityLevel string, r, s, sMin, sMax, discountedSMin, discountedSMax float64) {\n\tapiserverDispatchR.WithLabelValues(priorityLevel).Set(r)\n\tapiserverLatestS.WithLabelValues(priorityLevel).Set(s)\n\tapiserverNextSBounds.WithLabelValues(priorityLevel, \"min\").Set(sMin)\n\tapiserverNextSBounds.WithLabelValues(priorityLevel, \"max\").Set(sMax)\n\tapiserverNextDiscountedSBounds.WithLabelValues(priorityLevel, \"min\").Set(discountedSMin)\n\tapiserverNextDiscountedSBounds.WithLabelValues(priorityLevel, \"max\").Set(discountedSMax)\n}\n\n\/\/ AddRequestConcurrencyInUse adds the given delta to the gauge of concurrency in use by\n\/\/ the currently executing requests of the given flowSchema and priorityLevel\nfunc AddRequestConcurrencyInUse(priorityLevel, flowSchema string, delta int) {\n\tapiserverRequestConcurrencyInUse.WithLabelValues(priorityLevel, flowSchema).Add(float64(delta))\n}\n\n\/\/ UpdateSharedConcurrencyLimit updates the value for the concurrency limit in flow control\nfunc UpdateSharedConcurrencyLimit(priorityLevel string, limit int) {\n\tapiserverRequestConcurrencyLimit.WithLabelValues(priorityLevel).Set(float64(limit))\n}\n\n\/\/ AddReject increments the # of rejected requests for flow control\nfunc AddReject(ctx context.Context, priorityLevel, flowSchema, reason string) {\n\tapiserverRejectedRequestsTotal.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema, reason).Add(1)\n}\n\n\/\/ AddDispatch increments the # of dispatched requests for flow control\nfunc AddDispatch(ctx context.Context, priorityLevel, flowSchema string) {\n\tapiserverDispatchedRequestsTotal.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema).Add(1)\n}\n\n\/\/ ObserveQueueLength observes the queue length for flow control\nfunc ObserveQueueLength(ctx context.Context, priorityLevel, flowSchema string, length int) {\n\tapiserverRequestQueueLength.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema).Observe(float64(length))\n}\n\n\/\/ ObserveWaitingDuration observes the queue length for flow control\nfunc ObserveWaitingDuration(ctx context.Context, priorityLevel, flowSchema, execute string, waitTime time.Duration) {\n\tapiserverRequestWaitingSeconds.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema, execute).Observe(waitTime.Seconds())\n}\n\n\/\/ ObserveExecutionDuration observes the execution duration for flow control\nfunc ObserveExecutionDuration(ctx context.Context, priorityLevel, flowSchema string, executionTime time.Duration) {\n\tapiserverRequestExecutionSeconds.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema).Observe(executionTime.Seconds())\n}\n<commit_msg>apf: add new label for request_execution_seconds metric<commit_after>\/*\nCopyright 2019 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage metrics\n\nimport (\n\t\"context\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\tapirequest \"k8s.io\/apiserver\/pkg\/endpoints\/request\"\n\tcompbasemetrics \"k8s.io\/component-base\/metrics\"\n\t\"k8s.io\/component-base\/metrics\/legacyregistry\"\n\tbasemetricstestutil \"k8s.io\/component-base\/metrics\/testutil\"\n\t\"k8s.io\/utils\/clock\"\n)\n\nconst (\n\tnamespace = \"apiserver\"\n\tsubsystem = \"flowcontrol\"\n)\n\nconst (\n\trequestKind   = \"request_kind\"\n\tpriorityLevel = \"priority_level\"\n\tflowSchema    = \"flow_schema\"\n\tphase         = \"phase\"\n\tmark          = \"mark\"\n)\n\nvar (\n\tqueueLengthBuckets            = []float64{0, 10, 25, 50, 100, 250, 500, 1000}\n\trequestDurationSecondsBuckets = []float64{0, 0.005, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30}\n)\n\nvar registerMetrics sync.Once\n\n\/\/ Register all metrics.\nfunc Register() {\n\tregisterMetrics.Do(func() {\n\t\tfor _, metric := range metrics {\n\t\t\tlegacyregistry.MustRegister(metric)\n\t\t}\n\t})\n}\n\ntype resettable interface {\n\tReset()\n}\n\n\/\/ Reset all metrics to zero\nfunc Reset() {\n\tfor _, metric := range metrics {\n\t\trm := metric.(resettable)\n\t\trm.Reset()\n\t}\n}\n\n\/\/ GatherAndCompare the given metrics with the given Prometheus syntax expected value\nfunc GatherAndCompare(expected string, metricNames ...string) error {\n\treturn basemetricstestutil.GatherAndCompare(legacyregistry.DefaultGatherer, strings.NewReader(expected), metricNames...)\n}\n\n\/\/ Registerables is a slice of Registerable\ntype Registerables []compbasemetrics.Registerable\n\n\/\/ Append adds more\nfunc (rs Registerables) Append(more ...compbasemetrics.Registerable) Registerables {\n\treturn append(rs, more...)\n}\n\nvar (\n\tapiserverRejectedRequestsTotal = compbasemetrics.NewCounterVec(\n\t\t&compbasemetrics.CounterOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"rejected_requests_total\",\n\t\t\tHelp:           \"Number of requests rejected by API Priority and Fairness system\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema, \"reason\"},\n\t)\n\tapiserverDispatchedRequestsTotal = compbasemetrics.NewCounterVec(\n\t\t&compbasemetrics.CounterOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"dispatched_requests_total\",\n\t\t\tHelp:           \"Number of requests released by API Priority and Fairness system for service\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema},\n\t)\n\n\t\/\/ PriorityLevelConcurrencyObserverPairGenerator creates pairs that observe concurrency for priority levels\n\tPriorityLevelConcurrencyObserverPairGenerator = NewSampleAndWaterMarkHistogramsPairGenerator(clock.RealClock{}, time.Millisecond,\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"priority_level_request_count_samples\",\n\t\t\tHelp:           \"Periodic observations of the number of requests\",\n\t\t\tBuckets:        []float64{0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1},\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"priority_level_request_count_watermarks\",\n\t\t\tHelp:           \"Watermarks of the number of requests\",\n\t\t\tBuckets:        []float64{0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1},\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel})\n\n\t\/\/ ReadWriteConcurrencyObserverPairGenerator creates pairs that observe concurrency broken down by mutating vs readonly\n\tReadWriteConcurrencyObserverPairGenerator = NewSampleAndWaterMarkHistogramsPairGenerator(clock.RealClock{}, time.Millisecond,\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"read_vs_write_request_count_samples\",\n\t\t\tHelp:           \"Periodic observations of the number of requests\",\n\t\t\tBuckets:        []float64{0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1},\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"read_vs_write_request_count_watermarks\",\n\t\t\tHelp:           \"Watermarks of the number of requests\",\n\t\t\tBuckets:        []float64{0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1},\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{requestKind})\n\n\tapiserverCurrentR = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"current_r\",\n\t\t\tHelp:           \"R(time of last change)\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel},\n\t)\n\n\tapiserverDispatchR = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"dispatch_r\",\n\t\t\tHelp:           \"R(time of last dispatch)\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel},\n\t)\n\n\tapiserverLatestS = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"latest_s\",\n\t\t\tHelp:           \"S(most recently dispatched request)\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel},\n\t)\n\n\tapiserverNextSBounds = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"next_s_bounds\",\n\t\t\tHelp:           \"min and max, over queues, of S(oldest waiting request in queue)\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, \"bound\"},\n\t)\n\n\tapiserverNextDiscountedSBounds = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"next_discounted_s_bounds\",\n\t\t\tHelp:           \"min and max, over queues, of S(oldest waiting request in queue) - estimated work in progress\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, \"bound\"},\n\t)\n\n\tapiserverCurrentInqueueRequests = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"current_inqueue_requests\",\n\t\t\tHelp:           \"Number of requests currently pending in queues of the API Priority and Fairness system\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema},\n\t)\n\tapiserverRequestQueueLength = compbasemetrics.NewHistogramVec(\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"request_queue_length_after_enqueue\",\n\t\t\tHelp:           \"Length of queue in the API Priority and Fairness system, as seen by each request after it is enqueued\",\n\t\t\tBuckets:        queueLengthBuckets,\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema},\n\t)\n\tapiserverRequestConcurrencyLimit = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"request_concurrency_limit\",\n\t\t\tHelp:           \"Shared concurrency limit in the API Priority and Fairness system\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel},\n\t)\n\tapiserverCurrentExecutingRequests = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"current_executing_requests\",\n\t\t\tHelp:           \"Number of requests currently executing in the API Priority and Fairness system\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema},\n\t)\n\tapiserverRequestConcurrencyInUse = compbasemetrics.NewGaugeVec(\n\t\t&compbasemetrics.GaugeOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"request_concurrency_in_use\",\n\t\t\tHelp:           \"Concurrency (number of seats) occupided by the currently executing requests in the API Priority and Fairness system\",\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema},\n\t)\n\tapiserverRequestWaitingSeconds = compbasemetrics.NewHistogramVec(\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"request_wait_duration_seconds\",\n\t\t\tHelp:           \"Length of time a request spent waiting in its queue\",\n\t\t\tBuckets:        requestDurationSecondsBuckets,\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema, \"execute\"},\n\t)\n\tapiserverRequestExecutionSeconds = compbasemetrics.NewHistogramVec(\n\t\t&compbasemetrics.HistogramOpts{\n\t\t\tNamespace:      namespace,\n\t\t\tSubsystem:      subsystem,\n\t\t\tName:           \"request_execution_seconds\",\n\t\t\tHelp:           \"Duration of request execution in the API Priority and Fairness system\",\n\t\t\tBuckets:        requestDurationSecondsBuckets,\n\t\t\tStabilityLevel: compbasemetrics.ALPHA,\n\t\t},\n\t\t[]string{priorityLevel, flowSchema, \"type\"},\n\t)\n\tmetrics = Registerables{\n\t\tapiserverRejectedRequestsTotal,\n\t\tapiserverDispatchedRequestsTotal,\n\t\tapiserverCurrentR,\n\t\tapiserverDispatchR,\n\t\tapiserverLatestS,\n\t\tapiserverNextSBounds,\n\t\tapiserverNextDiscountedSBounds,\n\t\tapiserverCurrentInqueueRequests,\n\t\tapiserverRequestQueueLength,\n\t\tapiserverRequestConcurrencyLimit,\n\t\tapiserverRequestConcurrencyInUse,\n\t\tapiserverCurrentExecutingRequests,\n\t\tapiserverRequestWaitingSeconds,\n\t\tapiserverRequestExecutionSeconds,\n\t}.\n\t\tAppend(PriorityLevelConcurrencyObserverPairGenerator.metrics()...).\n\t\tAppend(ReadWriteConcurrencyObserverPairGenerator.metrics()...)\n)\n\n\/\/ AddRequestsInQueues adds the given delta to the gauge of the # of requests in the queues of the specified flowSchema and priorityLevel\nfunc AddRequestsInQueues(ctx context.Context, priorityLevel, flowSchema string, delta int) {\n\tapiserverCurrentInqueueRequests.WithLabelValues(priorityLevel, flowSchema).Add(float64(delta))\n}\n\n\/\/ AddRequestsExecuting adds the given delta to the gauge of executing requests of the given flowSchema and priorityLevel\nfunc AddRequestsExecuting(ctx context.Context, priorityLevel, flowSchema string, delta int) {\n\tapiserverCurrentExecutingRequests.WithLabelValues(priorityLevel, flowSchema).Add(float64(delta))\n}\n\n\/\/ SetCurrentR sets the current-R (virtualTime) gauge for the given priority level\nfunc SetCurrentR(priorityLevel string, r float64) {\n\tapiserverCurrentR.WithLabelValues(priorityLevel).Set(r)\n}\n\n\/\/ SetLatestS sets the latest-S (virtual time of dispatched request) gauge for the given priority level\nfunc SetDispatchMetrics(priorityLevel string, r, s, sMin, sMax, discountedSMin, discountedSMax float64) {\n\tapiserverDispatchR.WithLabelValues(priorityLevel).Set(r)\n\tapiserverLatestS.WithLabelValues(priorityLevel).Set(s)\n\tapiserverNextSBounds.WithLabelValues(priorityLevel, \"min\").Set(sMin)\n\tapiserverNextSBounds.WithLabelValues(priorityLevel, \"max\").Set(sMax)\n\tapiserverNextDiscountedSBounds.WithLabelValues(priorityLevel, \"min\").Set(discountedSMin)\n\tapiserverNextDiscountedSBounds.WithLabelValues(priorityLevel, \"max\").Set(discountedSMax)\n}\n\n\/\/ AddRequestConcurrencyInUse adds the given delta to the gauge of concurrency in use by\n\/\/ the currently executing requests of the given flowSchema and priorityLevel\nfunc AddRequestConcurrencyInUse(priorityLevel, flowSchema string, delta int) {\n\tapiserverRequestConcurrencyInUse.WithLabelValues(priorityLevel, flowSchema).Add(float64(delta))\n}\n\n\/\/ UpdateSharedConcurrencyLimit updates the value for the concurrency limit in flow control\nfunc UpdateSharedConcurrencyLimit(priorityLevel string, limit int) {\n\tapiserverRequestConcurrencyLimit.WithLabelValues(priorityLevel).Set(float64(limit))\n}\n\n\/\/ AddReject increments the # of rejected requests for flow control\nfunc AddReject(ctx context.Context, priorityLevel, flowSchema, reason string) {\n\tapiserverRejectedRequestsTotal.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema, reason).Add(1)\n}\n\n\/\/ AddDispatch increments the # of dispatched requests for flow control\nfunc AddDispatch(ctx context.Context, priorityLevel, flowSchema string) {\n\tapiserverDispatchedRequestsTotal.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema).Add(1)\n}\n\n\/\/ ObserveQueueLength observes the queue length for flow control\nfunc ObserveQueueLength(ctx context.Context, priorityLevel, flowSchema string, length int) {\n\tapiserverRequestQueueLength.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema).Observe(float64(length))\n}\n\n\/\/ ObserveWaitingDuration observes the queue length for flow control\nfunc ObserveWaitingDuration(ctx context.Context, priorityLevel, flowSchema, execute string, waitTime time.Duration) {\n\tapiserverRequestWaitingSeconds.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema, execute).Observe(waitTime.Seconds())\n}\n\n\/\/ ObserveExecutionDuration observes the execution duration for flow control\nfunc ObserveExecutionDuration(ctx context.Context, priorityLevel, flowSchema string, executionTime time.Duration) {\n\treqType := \"regular\"\n\tif requestInfo, ok := apirequest.RequestInfoFrom(ctx); ok && requestInfo.Verb == \"watch\" {\n\t\treqType = requestInfo.Verb\n\t}\n\tapiserverRequestExecutionSeconds.WithContext(ctx).WithLabelValues(priorityLevel, flowSchema, reqType).Observe(executionTime.Seconds())\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 gf Author(https:\/\/github.com\/gogf\/gf). All Rights Reserved.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the MIT License.\n\/\/ If a copy of the MIT was not distributed with this file,\n\/\/ You can obtain one at https:\/\/github.com\/gogf\/gf.\n\/\/\n\/\/ Note:\n\/\/ 1. It needs manually import: _ \"github.com\/mattn\/go-sqlite3\"\n\/\/ 2. It does not support Save\/Replace features.\n\npackage gdb\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"github.com\/gogf\/gf\/internal\/intlog\"\n\t\"github.com\/gogf\/gf\/text\/gstr\"\n\t\"strings\"\n)\n\n\/\/ DriverSqlite is the driver for sqlite database.\ntype DriverSqlite struct {\n\t*Core\n}\n\n\/\/ New creates and returns a database object for sqlite.\n\/\/ It implements the interface of gdb.Driver for extra database driver installation.\nfunc (d *DriverSqlite) New(core *Core, node *ConfigNode) (DB, error) {\n\treturn &DriverSqlite{\n\t\tCore: core,\n\t}, nil\n}\n\n\/\/ Open creates and returns a underlying sql.DB object for sqlite.\nfunc (d *DriverSqlite) Open(config *ConfigNode) (*sql.DB, error) {\n\tvar source string\n\tif config.LinkInfo != \"\" {\n\t\tsource = config.LinkInfo\n\t} else {\n\t\tsource = config.Name\n\t}\n\tintlog.Printf(\"Open: %s\", source)\n\tif db, err := sql.Open(\"sqlite3\", source); err == nil {\n\t\treturn db, nil\n\t} else {\n\t\treturn nil, err\n\t}\n}\n\n\/\/ GetChars returns the security char for this type of database.\nfunc (d *DriverSqlite) GetChars() (charLeft string, charRight string) {\n\treturn \"`\", \"`\"\n}\n\n\/\/ HandleSqlBeforeCommit deals with the sql string before commits it to underlying sql driver.\n\/\/ @todo 需要增加对Save方法的支持，可使用正则来实现替换，\n\/\/ @todo 将ON DUPLICATE KEY UPDATE触发器修改为两条SQL语句(INSERT OR IGNORE & UPDATE)\nfunc (d *DriverSqlite) HandleSqlBeforeCommit(link Link, sql string, args []interface{}) (string, []interface{}) {\n\treturn sql, args\n}\n\n\/\/ Tables retrieves and returns the tables of current schema.\n\/\/ It's mainly used in cli tool chain for automatically generating the models.\nfunc (d *DriverSqlite) Tables(schema ...string) (tables []string, err error) {\n\tvar result Result\n\n\tresult, err = d.DB.DoGetAll(nil, `SELECT NAME FROM SQLITE_MASTER WHERE TYPE='table' ORDER BY NAME`)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, m := range result {\n\t\tfor _, v := range m {\n\t\t\ttables = append(tables, v.String())\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ TableFields retrieves and returns the fields information of specified table of current schema.\nfunc (d *DriverSqlite) TableFields(table string, schema ...string) (fields map[string]*TableField, err error) {\n\ttable = gstr.Trim(table)\n\tif gstr.Contains(table, \" \") {\n\t\tpanic(\"function TableFields supports only single table operations\")\n\t}\n\n\tcheckSchema := d.DB.GetSchema()\n\tif len(schema) > 0 && schema[0] != \"\" {\n\t\tcheckSchema = schema[0]\n\t}\n\tv := d.DB.GetCache().GetOrSetFunc(\n\t\tfmt.Sprintf(`sqlite_table_fields_%s_%s`, table, checkSchema), func() interface{} {\n\t\t\tvar result Result\n\n\t\t\tresult, err = d.DB.DoGetAll(nil, fmt.Sprintf(`PRAGMA TABLE_INFO(%s)`, table))\n\t\t\tif err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfields = make(map[string]*TableField)\n\t\t\tfor i, m := range result {\n\t\t\t\tfields[strings.ToLower(m[\"name\"].String())] = &TableField{\n\t\t\t\t\tIndex: i,\n\t\t\t\t\tName:  strings.ToLower(m[\"name\"].String()),\n\t\t\t\t\tType:  strings.ToLower(m[\"type\"].String()),\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn fields\n\t\t}, 0)\n\tif err == nil {\n\t\tfields = v.(map[string]*TableField)\n\t}\n\treturn\n}\n<commit_msg>add Tables and TableFields method for sqlite<commit_after>\/\/ Copyright 2017 gf Author(https:\/\/github.com\/gogf\/gf). All Rights Reserved.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the MIT License.\n\/\/ If a copy of the MIT was not distributed with this file,\n\/\/ You can obtain one at https:\/\/github.com\/gogf\/gf.\n\/\/\n\/\/ Note:\n\/\/ 1. It needs manually import: _ \"github.com\/mattn\/go-sqlite3\"\n\/\/ 2. It does not support Save\/Replace features.\n\npackage gdb\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"github.com\/gogf\/gf\/internal\/intlog\"\n\t\"github.com\/gogf\/gf\/text\/gstr\"\n\t\"strings\"\n)\n\n\/\/ DriverSqlite is the driver for sqlite database.\ntype DriverSqlite struct {\n\t*Core\n}\n\n\/\/ New creates and returns a database object for sqlite.\n\/\/ It implements the interface of gdb.Driver for extra database driver installation.\nfunc (d *DriverSqlite) New(core *Core, node *ConfigNode) (DB, error) {\n\treturn &DriverSqlite{\n\t\tCore: core,\n\t}, nil\n}\n\n\/\/ Open creates and returns a underlying sql.DB object for sqlite.\nfunc (d *DriverSqlite) Open(config *ConfigNode) (*sql.DB, error) {\n\tvar source string\n\tif config.LinkInfo != \"\" {\n\t\tsource = config.LinkInfo\n\t} else {\n\t\tsource = config.Name\n\t}\n\tintlog.Printf(\"Open: %s\", source)\n\tif db, err := sql.Open(\"sqlite3\", source); err == nil {\n\t\treturn db, nil\n\t} else {\n\t\treturn nil, err\n\t}\n}\n\n\/\/ GetChars returns the security char for this type of database.\nfunc (d *DriverSqlite) GetChars() (charLeft string, charRight string) {\n\treturn \"`\", \"`\"\n}\n\n\/\/ HandleSqlBeforeCommit deals with the sql string before commits it to underlying sql driver.\n\/\/ @todo 需要增加对Save方法的支持，可使用正则来实现替换，\n\/\/ @todo 将ON DUPLICATE KEY UPDATE触发器修改为两条SQL语句(INSERT OR IGNORE & UPDATE)\nfunc (d *DriverSqlite) HandleSqlBeforeCommit(link Link, sql string, args []interface{}) (string, []interface{}) {\n\treturn sql, args\n}\n\n\/\/ Tables retrieves and returns the tables of current schema.\n\/\/ It's mainly used in cli tool chain for automatically generating the models.\nfunc (d *DriverSqlite) Tables(schema ...string) (tables []string, err error) {\n\tvar result Result\n\tlink, err := d.DB.GetSlave(schema...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult, err = d.DB.DoGetAll(link, `SELECT NAME FROM SQLITE_MASTER WHERE TYPE='table' ORDER BY NAME`)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, m := range result {\n\t\tfor _, v := range m {\n\t\t\ttables = append(tables, v.String())\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ TableFields retrieves and returns the fields information of specified table of current schema.\nfunc (d *DriverSqlite) TableFields(table string, schema ...string) (fields map[string]*TableField, err error) {\n\ttable = gstr.Trim(table)\n\tif gstr.Contains(table, \" \") {\n\t\tpanic(\"function TableFields supports only single table operations\")\n\t}\n\n\tcheckSchema := d.DB.GetSchema()\n\tif len(schema) > 0 && schema[0] != \"\" {\n\t\tcheckSchema = schema[0]\n\t}\n\tv := d.DB.GetCache().GetOrSetFunc(\n\t\tfmt.Sprintf(`sqlite_table_fields_%s_%s`, table, checkSchema), func() interface{} {\n\t\t\tvar result Result\n\t\t\tvar link *sql.DB\n\t\t\tlink, err = d.DB.GetSlave(checkSchema)\n\t\t\tif err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tresult, err = d.DB.DoGetAll(link, fmt.Sprintf(`PRAGMA TABLE_INFO(%s)`, table))\n\t\t\tif err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfields = make(map[string]*TableField)\n\t\t\tfor i, m := range result {\n\t\t\t\tfields[strings.ToLower(m[\"name\"].String())] = &TableField{\n\t\t\t\t\tIndex: i,\n\t\t\t\t\tName:  strings.ToLower(m[\"name\"].String()),\n\t\t\t\t\tType:  strings.ToLower(m[\"type\"].String()),\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn fields\n\t\t}, 0)\n\tif err == nil {\n\t\tfields = v.(map[string]*TableField)\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"fmt\"\nimport \"os\"\nimport \"net\/http\"\nimport \"io\/ioutil\"\nimport \"log\"\n\nimport \"github.com\/moovweb\/gokogiri\"\nimport \"github.com\/moovweb\/gokogiri\/xml\"\nimport \"github.com\/moovweb\/gokogiri\/xpath\"\nimport \"github.com\/codegangsta\/cli\"\n\nfunc load(url string, fromFile bool) *xml.XmlDocument{\n\tvar data []byte\n\tif fromFile{\n\t\tfile, _ := os.Open(url)\n\t\tdata, _ = ioutil.ReadAll(file)\n\t} else {\n\t\tresp, err := http.Get(url)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdata, _ = ioutil.ReadAll(resp.Body)\n\t}\n\tdoc, _ := gokogiri.ParseXml(data)\n\treturn(doc)\n}\n\nfunc multiple(vrouter string, vrf_name string, count bool) {\n\turl := \"http:\/\/\" + vrouter + \":8085\" + \"\/Snh_PageReq?x=begin:-1,end:-1,table:\" + vrf_name + \".uc.route.0,\"\n\t\n\tvar doc = load(url, false)\n\tdefer doc.Free()\n\txps := xpath.Compile(\"\/\/route_list\/list\/RouteUcSandeshData\/path_list\/list\/PathSandeshData\/nh\/NhSandeshData\/mc_list\/..\/..\/..\/..\/..\/..\/src_ip\/text()\")\n\tss, _ := doc.Root().Search(xps)\n\tif count {\n\t\tfmt.Printf(\"%d\\n\", len(ss))\n\t} else {\n\t\tfor _, s := range ss {\n\t\t\tfmt.Printf(\"%s\\n\", s)\n\t\t}\n\t}\n}\n\ntype Page struct {\n\tVrouterUrl string;\n\tTable string;\n}\n\ntype File struct {\n\tPath string;\n}\n\ntype LoadAble interface {\n\tLoad(descCol DescCol) Collection;\n}\n\n\/\/ Parse data to XML\nfunc fromDataToCollection(data []byte, descCol DescCol) Collection {\n\tdoc, _ := gokogiri.ParseXml(data)\n\tss, _ := doc.Search(descCol.BaseXpath)\n\tif len(ss) < 1 {\n\t\tlog.Fatal(fmt.Sprintf(\"%d Failed to search xpath '%s'\", len(ss), descCol.BaseXpath))\n\t}\n\tcol := Collection{node: ss[0], descCol: descCol}\n\tcol.Init()\n\treturn col\n}\n\nfunc (file File) Load(descCol DescCol) Collection {\n\tf, _ := os.Open(file.Path)\n\tdata, _ := ioutil.ReadAll(f)\n\treturn fromDataToCollection(data, descCol)\n}\n\nfunc (page Page) Load(descCol DescCol) Collection {\n\turl := \"http:\/\/\" + page.VrouterUrl + \":8085\/Snh_PageReq?x=begin:-1,end:-1,table:\" + page.Table + \",\"\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdata, _ := ioutil.ReadAll(resp.Body)\n\treturn fromDataToCollection(data, descCol)\n}\n\ntype Collection struct {\n\tdescCol DescCol;\n\tdoc *xml.XmlDocument;\n\tnode xml.Node;\n\telements []Element;\n}\n\ntype DescCol struct {\n\tPageArgs []string;\n\tPageBuilder (func([]string) LoadAble);\n\tBaseXpath string;\n\tDescElt DescElement;\n\tSearchXpath (func(string) string);\n}\n\ntype DescElement struct {\n\tShortDetailXpath string;\n\tLongDetail LongAble;\n}\n\ntype Element struct {\n\tnode xml.Node;\n\tdesc DescElement;\n}\n\nfunc (col *Collection) Init() {\n\tss, _ := col.node.Search(\"*\")\n\tcol.elements = make([]Element, len(ss))\n\tfor i, s := range ss {\n\t\tcol.elements[i] = Element{node: s, desc: col.descCol.DescElt}\n\t}\n}\n\nfunc (col *Collection) Search(pattern string) Elements{\n\tss, _ := col.node.Search(col.descCol.SearchXpath(pattern))\n\tvar elements []Element = make([]Element, len(ss))\n\tfor i, s := range ss {\n\t\telements[i] = Element{node: s, desc: col.descCol.DescElt}\n\t}\n\treturn Elements(elements)\n}\n\ntype Show interface {\n\tLong()\n\tShort()\n\tXml()\n}\n\ntype Elements []Element\n\nfunc (e Element) Xml() {\n\tfmt.Printf(\"%s\", e.node)\n}\nfunc (elts Elements) Xml() {\n\tfor _, e := range elts {\n\t\te.Xml()\n\t}\n}\nfunc (c Collection) Xml() {\n\tfmt.Printf(\"%s\", c.node)\n}\n\n\nfunc (e Element) Short() {\n\ts, _ := e.node.Search(e.desc.ShortDetailXpath)\n\tif len(s) != 1 {\n\t\tlog.Fatal(\"Xpath '\" + e.desc.ShortDetailXpath + \"' is not valid\")\n\t}\n\tfmt.Printf(\"%s\\n\", s[0])\n}\nfunc (col Collection) Short() {\n\tElements(col.elements).Short()\n}\nfunc (elts Elements) Short() {\n\tfor _, e := range elts {\n\t\te.Short()\n\t}\n}\nfunc (e Element) Long() {\n\te.desc.LongDetail.Long(e)\n}\nfunc (col Collection) Long() {\n\tElements(col.elements).Long()\n}\nfunc (elts Elements) Long() {\n\tfor _, e := range elts {\n\t\te.Long()\n\t\tfmt.Printf(\"\\n\")\n\t}\n}\n\nfunc DescItf() DescCol {\n\treturn DescCol{\n\t\tBaseXpath: \"__ItfResp_list\/ItfResp\/itf_list\/list\",\n\t\tDescElt: DescElement {\n\t\t\tShortDetailXpath: \"name\/text()\",\n\t\t\tLongDetail: LongXpaths([]string{\"uuid\/text()\", \"name\/text()\"}),\n\t\t},\n\t\tPageArgs: []string{\"vrouter\"},\n\t\tPageBuilder: func(args []string) LoadAble{\n\t\t\treturn Page{Table: \"db.interface.0\", VrouterUrl: args[0]}\n\t\t},\n\t}\n}\nfunc DescRoute() DescCol {\n\treturn DescCol{\n\t\tPageArgs: []string{\"vrouter\", \"vrf_name\"},\n\t\tPageBuilder: func(args []string) LoadAble{\n\t\t\treturn Page{VrouterUrl: args[0], Table: args[1] + \".uc.route.0,\"}\n\t\t},\n\t\tBaseXpath: \"__Inet4UcRouteResp_list\/Inet4UcRouteResp\/route_list\/list\",\n\t\tDescElt: DescElement {\n\t\t\tShortDetailXpath: \"src_ip\/text()\",\n\t\t\tLongDetail: LongFunc(routeDetail)},\n\t\tSearchXpath: func(pattern string) string {\n\t\t\treturn \"RouteUcSandeshData\/src_ip[contains(text(),'\" + pattern + \"')]\/..\"\n\t\t},\n\t}\n}\nfunc DescVrf() DescCol {\n\treturn DescCol{\n\t\tPageArgs: []string{\"vrouter\"},\n\t\tPageBuilder: func(args []string) LoadAble{\n\t\t\treturn Page{Table: \"db.vrf.0\", VrouterUrl: args[0]}\n\t\t},\n\t\tBaseXpath: \"__VrfListResp_list\/VrfListResp\/vrf_list\/list\",\n\t\tDescElt: DescElement {\n\t\t\tShortDetailXpath: \"name\/text()\",\n\t\t\tLongDetail: LongXpaths([]string{\"name\/text()\"}),\n\t\t},\n\t}\n}\n\ntype LongFunc (func (Element))\ntype LongXpaths []string\n\ntype LongAble interface {\n\tLong(e Element);\n}\nfunc (lf LongFunc) Long(e Element) {\n\tlf(e)\n}\nfunc (xpaths LongXpaths) Long(e Element) {\n\tfor _, xpath := range xpaths {\n\t\ts, _ := e.node.Search(xpath)\n\t\tfmt.Printf(\"%s \", s[0])\n\t}\n}\n\nfunc routeDetail(e Element) {\n\tsrcIp, _ := e.node.Search(\"src_ip\/text()\")\n\tfmt.Printf(\"%s\\n\", srcIp[0])\n\tpaths, _ := e.node.Search(\"path_list\/list\/PathSandeshData\")\n\tfmt.Printf(\"  Dest_ip ; Peers ; Label ; Itfs\\n\")\n\tfor _, path := range paths {\n\t\tnhs, _ := path.Search(\"nh\/NhSandeshData\/\/dip\/text()\")\n\t\tpeers, _ := path.Search(\"peer\/text()\")\n\t\tlabel, _ := path.Search(\"label\/text()\")\n\t\titf, _ := path.Search(\"nh\/NhSandeshData\/itf\/text()\")\n\t\tfmt.Printf(\"  %s %s %s %s\\n\", nhs, peers, label, itf)\n\t}\n}\n\nfunc GenCommand(descCol DescCol, name string, usage string) cli.Command {\n\treturn cli.Command{\n\t\tName: name,\n\t\tAliases: []string{\"a\"},\n\t\tUsage: usage,\n\t\tArgsUsage: fmt.Sprintf(\"%s\\n\", descCol.PageArgs),\n\t\tFlags: []cli.Flag{\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"long, l\",\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"xml, x\",\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"from-file\",\n\t\t\t\tUsage: \"Use a file instead of loading data from URL\",\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"search, s\",\n\t\t\t\tUsage: \"Search string\",\n\t\t\t\tValue: \"\",\n\t\t\t},\n\t\t},\n\t\tAction: func(c *cli.Context) {\n\t\t\tvar page LoadAble;\n\t\t\tif c.IsSet(\"from-file\") {\n\t\t\t\tpage = File{Path: c.Args()[0]}\n\t\t\t} else {\n\t\t\t\tif c.NArg() < len(descCol.PageArgs) {\n\t\t\t\t\tlog.Fatal(\"Wrong argument number!\")\n\t\t\t\t}\n\t\t\t\tpage = descCol.PageBuilder(c.Args())\n\t\t\t}\n\t\t\tcol := page.Load(descCol)\n\t\t\tvar list Show;\n\n\t\t\tif c.String(\"s\") != \"\" {\n\t\t\t\tlist = col.Search(c.String(\"s\"))\n\t\t\t} else {\n\t\t\t\tlist = col\n\t\t\t}\n\n\t\t\tif c.IsSet(\"xml\") {\n\t\t\t\tlist.Xml()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif c.IsSet(\"long\") {\n\t\t\t\tlist.Long()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlist.Short()\n\t\t},\n\t}\n}\n\nfunc main() {\n\tvar showAsXml bool;\n\tvar count bool;\n\n\tapp := cli.NewApp()\n\tapp.Name = \"contrail-introspect-cli\"\n\tapp.Usage = \"CLI on contrail introspects\"\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName: \"format-xml\",\n\t\t\tDestination: &showAsXml,\n\t\t},\n\t}\n\tapp.Commands = []cli.Command{\n\t\tGenCommand(DescRoute(), \"route\", \"Get route information\"),\n\t\tGenCommand(DescItf(), \"itf\", \"Get interface information\"),\n\t\tGenCommand(DescVrf(), \"vrf\", \"Get vrf information\"),\n\t\t{\n\t\t\tName:      \"multiple\",\n\t\t\tUsage:     \"vrouter vrf_name\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.BoolFlag{\n\t\t\t\t\tName: \"count\",\n\t\t\t\t\tDestination: &count,\n\t\t\t\t}},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tif c.NArg() != 2 {\n\t\t\t\t\tlog.Fatal(\"Wrong argument number!\")\n\t\t\t\t}\n\t\t\t\tvrouter := c.Args()[0]\n\t\t\t\tvrf_name := c.Args()[1]\n\t\t\t\tmultiple(vrouter, vrf_name, count)\n\t\t\t},\n\t\t},\n\t}\n\tapp.Run(os.Args)\n}\n<commit_msg>Improve UI<commit_after>package main\n\nimport \"fmt\"\nimport \"os\"\nimport \"net\/http\"\nimport \"io\/ioutil\"\nimport \"log\"\nimport \"strings\"\n\nimport \"github.com\/moovweb\/gokogiri\"\nimport \"github.com\/moovweb\/gokogiri\/xml\"\nimport \"github.com\/moovweb\/gokogiri\/xpath\"\nimport \"github.com\/codegangsta\/cli\"\n\nfunc load(url string, fromFile bool) *xml.XmlDocument{\n\tvar data []byte\n\tif fromFile{\n\t\tfile, _ := os.Open(url)\n\t\tdata, _ = ioutil.ReadAll(file)\n\t} else {\n\t\tresp, err := http.Get(url)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdata, _ = ioutil.ReadAll(resp.Body)\n\t}\n\tdoc, _ := gokogiri.ParseXml(data)\n\treturn(doc)\n}\n\nfunc multiple(vrouter string, vrf_name string, count bool) {\n\turl := \"http:\/\/\" + vrouter + \":8085\" + \"\/Snh_PageReq?x=begin:-1,end:-1,table:\" + vrf_name + \".uc.route.0,\"\n\t\n\tvar doc = load(url, false)\n\tdefer doc.Free()\n\txps := xpath.Compile(\"\/\/route_list\/list\/RouteUcSandeshData\/path_list\/list\/PathSandeshData\/nh\/NhSandeshData\/mc_list\/..\/..\/..\/..\/..\/..\/src_ip\/text()\")\n\tss, _ := doc.Root().Search(xps)\n\tif count {\n\t\tfmt.Printf(\"%d\\n\", len(ss))\n\t} else {\n\t\tfor _, s := range ss {\n\t\t\tfmt.Printf(\"%s\\n\", s)\n\t\t}\n\t}\n}\n\ntype Page struct {\n\tVrouterUrl string;\n\tTable string;\n}\n\ntype File struct {\n\tPath string;\n}\n\ntype LoadAble interface {\n\tLoad(descCol DescCol) Collection;\n}\n\n\/\/ Parse data to XML\nfunc fromDataToCollection(data []byte, descCol DescCol) Collection {\n\tdoc, _ := gokogiri.ParseXml(data)\n\tss, _ := doc.Search(descCol.BaseXpath)\n\tif len(ss) < 1 {\n\t\tlog.Fatal(fmt.Sprintf(\"%d Failed to search xpath '%s'\", len(ss), descCol.BaseXpath))\n\t}\n\tcol := Collection{node: ss[0], descCol: descCol}\n\tcol.Init()\n\treturn col\n}\n\nfunc (file File) Load(descCol DescCol) Collection {\n\tf, _ := os.Open(file.Path)\n\tdata, _ := ioutil.ReadAll(f)\n\treturn fromDataToCollection(data, descCol)\n}\n\nfunc (page Page) Load(descCol DescCol) Collection {\n\turl := \"http:\/\/\" + page.VrouterUrl + \":8085\/Snh_PageReq?x=begin:-1,end:-1,table:\" + page.Table + \",\"\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdata, _ := ioutil.ReadAll(resp.Body)\n\treturn fromDataToCollection(data, descCol)\n}\n\ntype Collection struct {\n\tdescCol DescCol;\n\tdoc *xml.XmlDocument;\n\tnode xml.Node;\n\telements []Element;\n}\n\ntype DescCol struct {\n\tPageArgs []string;\n\tPageBuilder (func([]string) LoadAble);\n\tBaseXpath string;\n\tDescElt DescElement;\n\tSearchXpath (func(string) string);\n}\n\ntype DescElement struct {\n\tShortDetailXpath string;\n\tLongDetail LongAble;\n}\n\ntype Element struct {\n\tnode xml.Node;\n\tdesc DescElement;\n}\n\nfunc (col *Collection) Init() {\n\tss, _ := col.node.Search(\"*\")\n\tcol.elements = make([]Element, len(ss))\n\tfor i, s := range ss {\n\t\tcol.elements[i] = Element{node: s, desc: col.descCol.DescElt}\n\t}\n}\n\nfunc (col *Collection) Search(pattern string) Elements{\n\tss, _ := col.node.Search(col.descCol.SearchXpath(pattern))\n\tvar elements []Element = make([]Element, len(ss))\n\tfor i, s := range ss {\n\t\telements[i] = Element{node: s, desc: col.descCol.DescElt}\n\t}\n\treturn Elements(elements)\n}\n\ntype Show interface {\n\tLong()\n\tShort()\n\tXml()\n}\n\ntype Elements []Element\n\nfunc (e Element) Xml() {\n\tfmt.Printf(\"%s\", e.node)\n}\nfunc (elts Elements) Xml() {\n\tfor _, e := range elts {\n\t\te.Xml()\n\t}\n}\nfunc (c Collection) Xml() {\n\tfmt.Printf(\"%s\", c.node)\n}\n\n\nfunc (e Element) Short() {\n\ts, _ := e.node.Search(e.desc.ShortDetailXpath)\n\tif len(s) != 1 {\n\t\tlog.Fatal(\"Xpath '\" + e.desc.ShortDetailXpath + \"' is not valid\")\n\t}\n\tfmt.Printf(\"%s\\n\", s[0])\n}\nfunc (col Collection) Short() {\n\tElements(col.elements).Short()\n}\nfunc (elts Elements) Short() {\n\tfor _, e := range elts {\n\t\te.Short()\n\t}\n}\nfunc (e Element) Long() {\n\te.desc.LongDetail.Long(e)\n}\nfunc (col Collection) Long() {\n\tElements(col.elements).Long()\n}\nfunc (elts Elements) Long() {\n\tfor _, e := range elts {\n\t\te.Long()\n\t\tfmt.Printf(\"\\n\")\n\t}\n}\n\nfunc DescItf() DescCol {\n\treturn DescCol{\n\t\tBaseXpath: \"__ItfResp_list\/ItfResp\/itf_list\/list\",\n\t\tDescElt: DescElement {\n\t\t\tShortDetailXpath: \"name\/text()\",\n\t\t\tLongDetail: LongXpaths([]string{\"uuid\/text()\", \"name\/text()\"}),\n\t\t},\n\t\tPageArgs: []string{\"vrouter-fqdn\"},\n\t\tPageBuilder: func(args []string) LoadAble{\n\t\t\treturn Page{Table: \"db.interface.0\", VrouterUrl: args[0]}\n\t\t},\n\t}\n}\nfunc DescRoute() DescCol {\n\treturn DescCol{\n\t\tPageArgs: []string{\"vrouter-fqdn\", \"vrf-name\"},\n\t\tPageBuilder: func(args []string) LoadAble{\n\t\t\treturn Page{VrouterUrl: args[0], Table: args[1] + \".uc.route.0,\"}\n\t\t},\n\t\tBaseXpath: \"__Inet4UcRouteResp_list\/Inet4UcRouteResp\/route_list\/list\",\n\t\tDescElt: DescElement {\n\t\t\tShortDetailXpath: \"src_ip\/text()\",\n\t\t\tLongDetail: LongFunc(routeDetail)},\n\t\tSearchXpath: func(pattern string) string {\n\t\t\treturn \"RouteUcSandeshData\/src_ip[contains(text(),'\" + pattern + \"')]\/..\"\n\t\t},\n\t}\n}\nfunc DescVrf() DescCol {\n\treturn DescCol{\n\t\tPageArgs: []string{\"vrouter-fqdn\"},\n\t\tPageBuilder: func(args []string) LoadAble{\n\t\t\treturn Page{Table: \"db.vrf.0\", VrouterUrl: args[0]}\n\t\t},\n\t\tBaseXpath: \"__VrfListResp_list\/VrfListResp\/vrf_list\/list\",\n\t\tDescElt: DescElement {\n\t\t\tShortDetailXpath: \"name\/text()\",\n\t\t\tLongDetail: LongXpaths([]string{\"name\/text()\"}),\n\t\t},\n\t}\n}\n\ntype LongFunc (func (Element))\ntype LongXpaths []string\n\ntype LongAble interface {\n\tLong(e Element);\n}\nfunc (lf LongFunc) Long(e Element) {\n\tlf(e)\n}\nfunc (xpaths LongXpaths) Long(e Element) {\n\tfor _, xpath := range xpaths {\n\t\ts, _ := e.node.Search(xpath)\n\t\tfmt.Printf(\"%s \", s[0])\n\t}\n}\n\nfunc routeDetail(e Element) {\n\tsrcIp, _ := e.node.Search(\"src_ip\/text()\")\n\tfmt.Printf(\"%s\\n\", srcIp[0])\n\tpaths, _ := e.node.Search(\"path_list\/list\/PathSandeshData\")\n\tfmt.Printf(\"  Dest_ip ; Peers ; Label ; Itfs\\n\")\n\tfor _, path := range paths {\n\t\tnhs, _ := path.Search(\"nh\/NhSandeshData\/\/dip\/text()\")\n\t\tpeers, _ := path.Search(\"peer\/text()\")\n\t\tlabel, _ := path.Search(\"label\/text()\")\n\t\titf, _ := path.Search(\"nh\/NhSandeshData\/itf\/text()\")\n\t\tfmt.Printf(\"  %s %s %s %s\\n\", nhs, peers, label, itf)\n\t}\n}\n\nfunc GenCommand(descCol DescCol, name string, usage string) cli.Command {\n\treturn cli.Command{\n\t\tName: name,\n\t\tAliases: []string{\"a\"},\n\t\tUsage: usage,\n\t\tArgsUsage: fmt.Sprintf(\"%s\\n\", strings.Join(descCol.PageArgs, \" \")),\n\t\tFlags: []cli.Flag{\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"long, l\",\n\t\t\t\tUsage: \"Long version format\",\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"xml, x\",\n\t\t\t\tUsage: \"XML output format\",\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"from-file\",\n\t\t\t\tUsage: \"Load file instead URL (for debugging)\",\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"search, s\",\n\t\t\t\tUsage: \"Search pattern\",\n\t\t\t\tValue: \"\",\n\t\t\t},\n\t\t},\n\t\tAction: func(c *cli.Context) {\n\t\t\tvar page LoadAble;\n\t\t\tif c.IsSet(\"from-file\") {\n\t\t\t\tpage = File{Path: c.Args()[0]}\n\t\t\t} else {\n\t\t\t\tif c.NArg() < len(descCol.PageArgs) {\n\t\t\t\t\tcli.ShowSubcommandHelp(c)\n\t\t\t\t\tos.Exit(1)\n\t\t\t\t}\n\t\t\t\tpage = descCol.PageBuilder(c.Args())\n\t\t\t}\n\t\t\tcol := page.Load(descCol)\n\t\t\tvar list Show;\n\n\t\t\tif c.String(\"s\") != \"\" {\n\t\t\t\tlist = col.Search(c.String(\"s\"))\n\t\t\t} else {\n\t\t\t\tlist = col\n\t\t\t}\n\n\t\t\tif c.IsSet(\"xml\") {\n\t\t\t\tlist.Xml()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif c.IsSet(\"long\") {\n\t\t\t\tlist.Long()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlist.Short()\n\t\t},\n\t}\n}\n\nfunc main() {\n\tvar count bool;\n\n\tapp := cli.NewApp()\n\tapp.Name = \"contrail-introspect-cli\"\n\tapp.Usage = \"CLI on ContraiL Introspects\"\n\tapp.Version= \"0.0.1\"\n\tapp.Commands = []cli.Command{\n\t\tGenCommand(DescRoute(), \"route\", \"Show routes\"),\n\t\tGenCommand(DescItf(), \"itf\", \"Show interfaces\"),\n\t\tGenCommand(DescVrf(), \"vrf\", \"Show vrfs\"),\n\t\t{\n\t\t\tName:      \"multiple\",\n\t\t\tUsage:     \"List routes with multiple nexthops\",\n\t\t\tArgsUsage: \"vrouter vrf_name\",\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.BoolFlag{\n\t\t\t\t\tName: \"count\",\n\t\t\t\t\tDestination: &count,\n\t\t\t\t}},\n\t\t\tAction: func(c *cli.Context) {\n\t\t\t\tif c.NArg() != 2 {\n\t\t\t\t\tlog.Fatal(\"Wrong argument number!\")\n\t\t\t\t}\n\t\t\t\tvrouter := c.Args()[0]\n\t\t\t\tvrf_name := c.Args()[1]\n\t\t\t\tmultiple(vrouter, vrf_name, count)\n\t\t\t},\n\t\t},\n\t}\n\tapp.Run(os.Args)\n}\n<|endoftext|>"}
{"text":"<commit_before>package cache\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\n\t\"core\"\n)\n\nfunc TestStore(t *testing.T) {\n\tmCache, aCache := makeCaches()\n\ttarget := makeTarget(\"\/\/pkg1:test_store\")\n\taCache.Store(target, nil)\n\taCache.Shutdown()\n\tassert.False(t, mCache.inFlight[target])\n\tassert.True(t, mCache.completed[target])\n}\n\nfunc TestStoreExtra(t *testing.T) {\n\tmCache, aCache := makeCaches()\n\ttarget := makeTarget(\"\/\/pkg1:test_store_extra\")\n\taCache.StoreExtra(target, nil, \"some_other_file\")\n\taCache.Shutdown()\n\tassert.False(t, mCache.inFlight[target])\n\tassert.True(t, mCache.completed[target])\n}\n\nfunc TestRetrieve(t *testing.T) {\n\tmCache, aCache := makeCaches()\n\ttarget := makeTarget(\"\/\/pkg1:test_retrieve\")\n\taCache.Retrieve(target, nil)\n\taCache.Shutdown()\n\tassert.False(t, mCache.inFlight[target])\n\tassert.True(t, mCache.completed[target])\n}\n\nfunc TestRetrieveExtra(t *testing.T) {\n\tmCache, aCache := makeCaches()\n\ttarget := makeTarget(\"\/\/pkg1:test_retrieve_extra\")\n\taCache.RetrieveExtra(target, nil, \"some_other_file\")\n\taCache.Shutdown()\n\tassert.False(t, mCache.inFlight[target])\n\tassert.True(t, mCache.completed[target])\n}\n\nfunc TestClean(t *testing.T) {\n\tmCache, aCache := makeCaches()\n\ttarget := makeTarget(\"\/\/pkg1:test_clean\")\n\taCache.Clean(target)\n\taCache.Shutdown()\n\tassert.False(t, mCache.inFlight[target])\n\tassert.True(t, mCache.completed[target])\n}\n\nfunc TestConcurrentStores(t *testing.T) {\n\t\/\/ The cache shouldn't run multiple concurrent stores for the same target.\n\t\/\/ Our mock cache will panic if it detects that, so here we just throw enough\n\t\/\/ concurrent requests at it to try to make sure that we're likely to exercise that.\n\t\/\/ It's pretty hard to really guarantee that it does happen though.\n\tmCache, aCache := makeCaches()\n\ttarget := makeTarget(\"\/\/pkg1:test_concurrent\")\n\texpected := []string{}\n\tfor i := 0; i < 20; i++ {\n\t\ts := fmt.Sprintf(\"file%02d\", i)\n\t\taCache.StoreExtra(target, nil, s)\n\t\texpected = append(expected, s)\n\t}\n\taCache.Shutdown()\n\tassert.False(t, mCache.inFlight[target])\n\tassert.True(t, mCache.completed[target])\n\tstored := mCache.stored[target]\n\tsort.Strings(stored)\n\tassert.Equal(t, expected, stored)\n}\n\n\/\/ Fake cache implementation to ensure our async cache behaves itself.\ntype mockCache struct {\n\tsync.Mutex\n\tinFlight  map[*core.BuildTarget]bool\n\tcompleted map[*core.BuildTarget]bool\n\tstored    map[*core.BuildTarget][]string\n}\n\nfunc (c *mockCache) Store(target *core.BuildTarget, key []byte) {\n\tc.StoreExtra(target, key, \"\")\n}\n\nfunc (c *mockCache) StoreExtra(target *core.BuildTarget, key []byte, file string) {\n\tc.Lock()\n\tif c.inFlight[target] {\n\t\tpanic(\"Concurrent store on \" + target.Label.String())\n\t}\n\tc.inFlight[target] = true\n\tc.Unlock()\n\ttime.Sleep(10 * time.Millisecond) \/\/ Fake a small delay to mimic the real thing\n\tc.Lock()\n\tc.inFlight[target] = false\n\tc.completed[target] = true\n\tc.stored[target] = append(c.stored[target], file)\n\tc.Unlock()\n}\n\nfunc (c *mockCache) Retrieve(target *core.BuildTarget, key []byte) bool {\n\tc.Lock()\n\tc.completed[target] = true\n\tc.Unlock()\n\treturn false\n}\n\nfunc (c *mockCache) RetrieveExtra(target *core.BuildTarget, key []byte, file string) bool {\n\treturn c.Retrieve(target, key)\n}\n\nfunc (c *mockCache) Clean(target *core.BuildTarget) {\n\tc.Retrieve(target, nil)\n}\n\nfunc (*mockCache) Shutdown() {}\n\nfunc makeTarget(label string) *core.BuildTarget {\n\treturn core.NewBuildTarget(core.ParseBuildLabel(label, \"\"))\n}\n\nfunc makeCaches() (mockCache, core.Cache) {\n\tmCache := mockCache{\n\t\tinFlight:  make(map[*core.BuildTarget]bool),\n\t\tcompleted: make(map[*core.BuildTarget]bool),\n\t\tstored:    make(map[*core.BuildTarget][]string),\n\t}\n\tconfig := core.DefaultConfiguration()\n\tconfig.Cache.Workers = 10\n\treturn mCache, newAsyncCache(&mCache, config)\n}\n<commit_msg>Add a test on async cache<commit_after>package cache\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\n\t\"core\"\n)\n\nfunc TestStore(t *testing.T) {\n\tmCache, aCache := makeCaches()\n\ttarget := makeTarget(\"\/\/pkg1:test_store\")\n\taCache.Store(target, nil)\n\taCache.Shutdown()\n\tassert.False(t, mCache.inFlight[target])\n\tassert.True(t, mCache.completed[target])\n}\n\nfunc TestStoreExtra(t *testing.T) {\n\tmCache, aCache := makeCaches()\n\ttarget := makeTarget(\"\/\/pkg1:test_store_extra\")\n\taCache.StoreExtra(target, nil, \"some_other_file\")\n\taCache.Shutdown()\n\tassert.False(t, mCache.inFlight[target])\n\tassert.True(t, mCache.completed[target])\n}\n\nfunc TestRetrieve(t *testing.T) {\n\tmCache, aCache := makeCaches()\n\ttarget := makeTarget(\"\/\/pkg1:test_retrieve\")\n\taCache.Retrieve(target, nil)\n\taCache.Shutdown()\n\tassert.False(t, mCache.inFlight[target])\n\tassert.True(t, mCache.completed[target])\n}\n\nfunc TestRetrieveExtra(t *testing.T) {\n\tmCache, aCache := makeCaches()\n\ttarget := makeTarget(\"\/\/pkg1:test_retrieve_extra\")\n\taCache.RetrieveExtra(target, nil, \"some_other_file\")\n\taCache.Shutdown()\n\tassert.False(t, mCache.inFlight[target])\n\tassert.True(t, mCache.completed[target])\n}\n\nfunc TestClean(t *testing.T) {\n\tmCache, aCache := makeCaches()\n\ttarget := makeTarget(\"\/\/pkg1:test_clean\")\n\taCache.Clean(target)\n\taCache.Shutdown()\n\tassert.False(t, mCache.inFlight[target])\n\tassert.True(t, mCache.completed[target])\n}\n\nfunc TestConcurrentStores(t *testing.T) {\n\t\/\/ The cache shouldn't run multiple concurrent stores for the same target.\n\t\/\/ Our mock cache will panic if it detects that, so here we just throw enough\n\t\/\/ concurrent requests at it to try to make sure that we're likely to exercise that.\n\t\/\/ It's pretty hard to really guarantee that it does happen though.\n\tmCache, aCache := makeCaches()\n\ttarget := makeTarget(\"\/\/pkg1:test_concurrent\")\n\texpected := []string{}\n\tfor i := 0; i < 20; i++ {\n\t\ts := fmt.Sprintf(\"file%02d\", i)\n\t\taCache.StoreExtra(target, nil, s)\n\t\texpected = append(expected, s)\n\t}\n\taCache.Shutdown()\n\tassert.False(t, mCache.inFlight[target])\n\tassert.True(t, mCache.completed[target])\n\tstored := mCache.stored[target]\n\tsort.Strings(stored)\n\tassert.Equal(t, expected, stored)\n}\n\nfunc TestLotsOfConcurrentStores(t *testing.T) {\n\t\/\/ Throw a lot of concurrent store \/ store extra actions at the cache and make sure\n\t\/\/ it does it in order.\n\tconst n = 10\n\tvar wg sync.WaitGroup\n\twg.Add(n)\n\tmCache, aCache := makeCaches()\n\tfor i := 0; i < n; i++ {\n\t\tgo func(i int) {\n\t\t\ttarget := makeTarget(fmt.Sprintf(\"\/\/test_pkg:target%03d\", i))\n\t\t\taCache.Store(target, nil)\n\t\t\taCache.StoreExtra(target, nil, fmt.Sprintf(\"file%03d\", i))\n\t\t\taCache.StoreExtra(target, nil, fmt.Sprintf(\"file%03d_2\", i))\n\t\t\twg.Done()\n\t\t}(i)\n\t}\n\twg.Wait()\n\tassert.Equal(t, n, len(mCache.stored))\n\tfor target, stored := range mCache.stored {\n\t\tassert.Equal(t, []string{\n\t\t\t\"\",\n\t\t\t\"file\" + target.Label.Name[len(target.Label.Name)-3:],\n\t\t\t\"file\" + target.Label.Name[len(target.Label.Name)-3:] + \"_2\",\n\t\t}, stored)\n\t}\n}\n\n\/\/ Fake cache implementation to ensure our async cache behaves itself.\ntype mockCache struct {\n\tsync.Mutex\n\tinFlight  map[*core.BuildTarget]bool\n\tcompleted map[*core.BuildTarget]bool\n\tstored    map[*core.BuildTarget][]string\n}\n\nfunc (c *mockCache) Store(target *core.BuildTarget, key []byte) {\n\tc.StoreExtra(target, key, \"\")\n}\n\nfunc (c *mockCache) StoreExtra(target *core.BuildTarget, key []byte, file string) {\n\tc.Lock()\n\tif c.inFlight[target] {\n\t\tpanic(\"Concurrent store on \" + target.Label.String())\n\t}\n\tc.inFlight[target] = true\n\tc.Unlock()\n\ttime.Sleep(10 * time.Millisecond) \/\/ Fake a small delay to mimic the real thing\n\tc.Lock()\n\tc.inFlight[target] = false\n\tc.completed[target] = true\n\tc.stored[target] = append(c.stored[target], file)\n\tc.Unlock()\n}\n\nfunc (c *mockCache) Retrieve(target *core.BuildTarget, key []byte) bool {\n\tc.Lock()\n\tc.completed[target] = true\n\tc.Unlock()\n\treturn false\n}\n\nfunc (c *mockCache) RetrieveExtra(target *core.BuildTarget, key []byte, file string) bool {\n\treturn c.Retrieve(target, key)\n}\n\nfunc (c *mockCache) Clean(target *core.BuildTarget) {\n\tc.Retrieve(target, nil)\n}\n\nfunc (*mockCache) Shutdown() {}\n\nfunc makeTarget(label string) *core.BuildTarget {\n\treturn core.NewBuildTarget(core.ParseBuildLabel(label, \"\"))\n}\n\nfunc makeCaches() (mockCache, core.Cache) {\n\tmCache := mockCache{\n\t\tinFlight:  make(map[*core.BuildTarget]bool),\n\t\tcompleted: make(map[*core.BuildTarget]bool),\n\t\tstored:    make(map[*core.BuildTarget][]string),\n\t}\n\tconfig := core.DefaultConfiguration()\n\tconfig.Cache.Workers = 10\n\treturn mCache, newAsyncCache(&mCache, config)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ run\n\n\/\/ Copyright 2014 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"runtime\"\n)\n\ntype T struct {\n\tio.Closer\n}\n\nfunc f1() {\n\t\/\/ The 4 here and below depends on the number of internal runtime frames\n\t\/\/ that sit between a deferred function called during panic and\n\t\/\/ the original frame. If that changes, this test will start failing and\n\t\/\/ the number here will need to be updated.\n\tdefer checkLine(4)\n\tvar t *T\n\tvar c io.Closer = t\n\tc.Close()\n}\n\nfunc f2() {\n\tdefer checkLine(4)\n\tvar t T\n\tvar c io.Closer = t\n\tc.Close()\n}\n\nfunc main() {\n\tf1()\n\tf2()\n}\n\nfunc checkLine(n int) {\n\tif err := recover(); err == nil {\n\t\tpanic(\"did not panic\")\n\t}\n\t_, file, line, _ := runtime.Caller(n)\n\tif file != \"<autogenerated>\" || line != 1 {\n\t\tpanic(fmt.Sprintf(\"expected <autogenerated>:1 have %s:%d\", file, line))\n\t}\n}\n<commit_msg>test: fix flakey test case for issue 4388<commit_after>\/\/ run\n\n\/\/ Copyright 2014 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"runtime\"\n)\n\ntype T struct {\n\tio.Closer\n}\n\nfunc f1() {\n\t\/\/ The 4 here and below depends on the number of internal runtime frames\n\t\/\/ that sit between a deferred function called during panic and\n\t\/\/ the original frame. If that changes, this test will start failing and\n\t\/\/ the number here will need to be updated.\n\tdefer checkLine(4)\n\tvar t *T\n\tvar c io.Closer = t\n\tc.Close()\n}\n\nfunc f2() {\n\tdefer checkLine(4)\n\tvar t T\n\tvar c io.Closer = t\n\tc.Close()\n}\n\nfunc main() {\n\tf1()\n\tf2()\n}\n\nfunc checkLine(n int) {\n\tif err := recover(); err == nil {\n\t\tpanic(\"did not panic\")\n\t}\n\tvar file string\n\tvar line int\n\tfor i := 1; i <= n; i++ {\n\t\t_, file, line, _ = runtime.Caller(i)\n\t\tif file != \"<autogenerated>\" || line != 1 {\n\t\t\tcontinue\n\t\t}\n\t\treturn\n\t}\n\tpanic(fmt.Sprintf(\"expected <autogenerated>:1 have %s:%d\", file, line))\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"github.com\/zrepl\/zrepl\/model\"\n\t\"github.com\/zrepl\/zrepl\/sshbytestream\"\n\t\"github.com\/zrepl\/zrepl\/util\"\n\t\/\/ \"bytes\"\n\t_ \"bufio\"\n\t\/\/ \"strings\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t_ \"time\"\n)\n\nfunc main() {\n\n\tmode := flag.String(\"mode\", \"\", \"incoming|outgoing\")\n\tincomingFile := flag.String(\"incoming.file\", \"\", \"file to deliver to callers\")\n\toutgoingHost := flag.String(\"outgoing.sshHost\", \"\", \"ssh host\")\n\toutgoingUser := flag.String(\"outgoing.sshUser\", \"\", \"ssh user\")\n\toutgoingPort := flag.Uint(\"outgoing.sshPort\", 22, \"ssh port\")\n\tflag.Parse()\n\n\tswitch {\n\tcase (*mode == \"incoming\"):\n\n\t\tconn, err := sshbytestream.Incoming()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfile, err := os.Open(*incomingFile)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tchunker := chunking.NewChunker(file)\n\n\t\t_, err = io.Copy(conn, &chunker)\n\t\tif err != nil && err != io.EOF {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfmt.Fprintf(os.Stderr, \"Chunk Count: %d\\n\", chunker.ChunkCount)\n\n\tcase *mode == \"outgoing\":\n\n\t\tconn, err := sshbytestream.Outgoing(\"client\", model.SSHTransport{\n\t\t\tHost:                 *outgoingHost,\n\t\t\tUser:                 *outgoingUser,\n\t\t\tPort:                 uint16(*outgoingPort),\n\t\t\tOptions:              []string{\"Compression=no\"},\n\t\t\tTransportOpenCommand: []string{\"\/tmp\/sshwrap\", \"-mode\", \"incoming\", \"-incoming.file\", \"\/random.img\"},\n\t\t})\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tunchunker := chunking.NewUnchunker(conn)\n\n\t\t_, err = io.Copy(os.Stdout, &unchunker)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tconn.Close()\n\n\t\tfmt.Fprintf(os.Stderr, \"Chunk Count: %d\\n\", unchunker.ChunkCount)\n\n\t\tos.Exit(0)\n\n\tdefault:\n\t\tpanic(\"unsupported mode!\")\n\n\t}\n\n}\n<commit_msg>Lift chunker up to recent sshbytestream changes.<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"github.com\/zrepl\/zrepl\/sshbytestream\"\n\t\"github.com\/zrepl\/zrepl\/util\"\n\t\/\/ \"bytes\"\n\t_ \"bufio\"\n\t\/\/ \"strings\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t_ \"time\"\n)\n\nfunc main() {\n\n\tmode := flag.String(\"mode\", \"\", \"incoming|outgoing\")\n\tincomingFile := flag.String(\"incoming.file\", \"\", \"file to deliver to callers\")\n\toutgoingHost := flag.String(\"outgoing.sshHost\", \"\", \"ssh host\")\n\toutgoingUser := flag.String(\"outgoing.sshUser\", \"\", \"ssh user\")\n\toutgoingIdentity := flag.String(\"outgoing.sshIdentity\", \"\", \"ssh private key\")\n\toutgoingPort := flag.Uint(\"outgoing.sshPort\", 22, \"ssh port\")\n\toutgoingFile := flag.String(\"outgoing.File\", \"\", \"\")\n\tflag.Parse()\n\n\tswitch {\n\tcase (*mode == \"incoming\"):\n\n\t\tconn, err := sshbytestream.Incoming()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfile, err := os.Open(*incomingFile)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tchunker := chunking.NewChunker(file)\n\n\t\t_, err = io.Copy(conn, &chunker)\n\t\tif err != nil && err != io.EOF {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfmt.Fprintf(os.Stderr, \"Chunk Count: %d\\n\", chunker.ChunkCount)\n\n\tcase *mode == \"outgoing\":\n\n\t\tconn, err := sshbytestream.Outgoing(sshbytestream.SSHTransport{\n\t\t\tHost:         *outgoingHost,\n\t\t\tUser:         *outgoingUser,\n\t\t\tIdentityFile: *outgoingIdentity,\n\t\t\tPort:         uint16(*outgoingPort),\n\t\t})\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tf, err := os.OpenFile(*outgoingFile, os.O_WRONLY, 0600)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tunchunker := chunking.NewUnchunker(conn)\n\n\t\t_, err = io.Copy(f, unchunker)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tconn.Close()\n\n\t\tfmt.Fprintf(os.Stderr, \"Chunk Count: %d\\n\", unchunker.ChunkCount)\n\n\t\tos.Exit(0)\n\n\tdefault:\n\t\tpanic(\"unsupported mode!\")\n\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n  pbkdf2 \"github.com\/ctz\/go-fastpbkdf2\"\n\t\"golang.org\/x\/crypto\/scrypt\"\n  \"unsafe\"\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"time\"\n\t\"os\"\n\t\"math\/rand\"\n\t\"github.com\/vsergeev\/btckeygenie\/btckey\"\n)\n\nconst wordSize = int(unsafe.Sizeof(uintptr(0)))\nvar c chan []byte \/\/ goroutine channel\nconst letterBytes = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nfunc random(r *rand.Rand, n int) string {\n    b := make([]byte, n)\n\tfor i := range b {\n        b[i] = letterBytes[r.Intn(62)]\n    }\n\n    return string(b)\n}\n\nfunc main () {\n\tr := rand.New(rand.NewSource(time.Now().Unix()))\n  c = make(chan []byte)\n\n\tvar address string\n\tsaltValue := \"\"\n\n\tif len(os.Args) >= 2 {\n\t\taddress = os.Args[1]\n\t\tif len(os.Args) == 3 {\n\t\t\tsaltValue = os.Args[2]\n\t\t} else {\n\t\t\tsaltValue = \"\";\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Usage: %s [Address] [Salt - optional]\\n\\n\", os.Args[0])\n\t\tos.Exit(0)\n\t}\n\n\tfmt.Printf(\"Using address \\\"%s\\\" and salt \\\"%s\\\"\\n\", address, saltValue)\n\n\ttries := 0\n\tstart := time.Now()\n\tfor {\n\t\tpassphraseValue := random(r, 8)\n\t\tresult := bruteforce(passphraseValue, saltValue, address);\n\t\tif result != \"\" {\n\t\t\tfmt.Printf(\"Found! Passphrase %s\\n\", passphraseValue)\n\t\t\tos.Exit(0)\n\t\t} else {\n\t\t\ttries += 1\n\t\t\tfmt.Printf(\"\\rTried %d passphrases in %s [last passphrase: %s]\", tries, time.Since(start), passphraseValue)\n\t\t}\n\t}\n}\n\nfunc bruteforce(passphraseValue string, saltValue string, address string) string {\n  var priv btckey.PrivateKey\n  var err error\n  go doScrypt(fmt.Sprint(passphraseValue, \"\\x01\"), fmt.Sprint(saltValue, \"\\x01\"), c)\n  go doPbkdf2(fmt.Sprint(passphraseValue, \"\\x02\"), fmt.Sprint(saltValue, \"\\x02\"), c)\n\n  key1, key2 := <-c, <-c\n\n  result := make([]byte, 32)\n  fastXORWords(result, key1, key2)\n\n\terr = priv.FromBytes(result)\n\tif err != nil {\n\t\tfmt.Printf(\"Error importing private key: %s [%s]\\n\", err, passphraseValue)\n\t\treturn \"\"\n\t}\n\n\tif (priv.ToAddressUncompressed() == address) {\n\t\treturn passphraseValue\n\t}\n\n\treturn \"\"\n}\n\nfunc doScrypt(pass string, salt string, c chan []byte) {\n   scryptKey, _ := scrypt.Key([]byte(pass), []byte(salt), 262144, 8, 1, 32)\n   c <- scryptKey\n}\n\nfunc doPbkdf2(pass string, salt string, c chan []byte) {\n  pbkdf2Key := pbkdf2.Key([]byte(pass), []byte(salt), 65536, 32, sha256.New)\n  c <- pbkdf2Key\n}\n\n\/\/ fastXORWords XORs multiples of 4 or 8 bytes (depending on architecture.)\n\/\/ The arguments are assumed to be of equal length.\nfunc fastXORWords(dst, a, b []byte) {\n\tdw := *(*[]uintptr)(unsafe.Pointer(&dst))\n\taw := *(*[]uintptr)(unsafe.Pointer(&a))\n\tbw := *(*[]uintptr)(unsafe.Pointer(&b))\n\tn := len(b) \/ wordSize\n\tfor i := 0; i < n; i++ {\n\t\tdw[i] = aw[i] ^ bw[i]\n\t}\n}\n<commit_msg>print better diagnostic info<commit_after>package main\n\nimport (\n  pbkdf2 \"github.com\/ctz\/go-fastpbkdf2\"\n\t\"golang.org\/x\/crypto\/scrypt\"\n  \"unsafe\"\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"time\"\n\t\"os\"\n\t\"math\/rand\"\n\t\"github.com\/vsergeev\/btckeygenie\/btckey\"\n)\n\nconst wordSize = int(unsafe.Sizeof(uintptr(0)))\nvar c chan []byte \/\/ goroutine channel\nconst letterBytes = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nfunc random(r *rand.Rand, n int) string {\n    b := make([]byte, n)\n\tfor i := range b {\n        b[i] = letterBytes[r.Intn(62)]\n    }\n\n    return string(b)\n}\n\nfunc main () {\n\tr := rand.New(rand.NewSource(time.Now().Unix()))\n  c = make(chan []byte)\n\n\tvar address string\n\tsaltValue := \"\"\n\n\tif len(os.Args) >= 2 {\n\t\taddress = os.Args[1]\n\t\tif len(os.Args) == 3 {\n\t\t\tsaltValue = os.Args[2]\n\t\t} else {\n\t\t\tsaltValue = \"\";\n\t\t}\n\t} else {\n\t\tfmt.Printf(\"Usage: %s [Address] [Salt - optional]\\n\\n\", os.Args[0])\n\t\tos.Exit(0)\n\t}\n\n\tfmt.Printf(\"Using address \\\"%s\\\" and salt \\\"%s\\\"\\n\", address, saltValue)\n\n\ttries := 0\n\tstart := time.Now()\n\tfor {\n\t\tpassphraseValue := random(r, 8)\n\t\tresult := bruteforce(passphraseValue, saltValue, address);\n\t\tif result != \"\" {\n\t\t\tfmt.Printf(\"Found! Passphrase %s\\n\", passphraseValue)\n\t\t\tos.Exit(0)\n\t\t} else {\n\t\t\ttries += 1\n      timeElapsed := time.Since(start)\n      hashRate := float64(tries) \/ (timeElapsed.Seconds())\n\t\t\tfmt.Printf(\"\\rspeed=%.2fh\/s, last=%s, tries=%d, elapsed=%s\", hashRate, passphraseValue, tries, timeElapsed)\n\t\t}\n\t}\n}\n\nfunc bruteforce(passphraseValue string, saltValue string, address string) string {\n  var priv btckey.PrivateKey\n  var err error\n  go doScrypt(fmt.Sprint(passphraseValue, \"\\x01\"), fmt.Sprint(saltValue, \"\\x01\"), c)\n  go doPbkdf2(fmt.Sprint(passphraseValue, \"\\x02\"), fmt.Sprint(saltValue, \"\\x02\"), c)\n\n  key1, key2 := <-c, <-c\n\n  result := make([]byte, 32)\n  fastXORWords(result, key1, key2)\n\n\terr = priv.FromBytes(result)\n\tif err != nil {\n\t\tfmt.Printf(\"Error importing private key: %s [%s]\\n\", err, passphraseValue)\n\t\treturn \"\"\n\t}\n\n\tif (priv.ToAddressUncompressed() == address) {\n\t\treturn passphraseValue\n\t}\n\n\treturn \"\"\n}\n\nfunc doScrypt(pass string, salt string, c chan []byte) {\n   scryptKey, _ := scrypt.Key([]byte(pass), []byte(salt), 262144, 8, 1, 32)\n   c <- scryptKey\n}\n\nfunc doPbkdf2(pass string, salt string, c chan []byte) {\n  pbkdf2Key := pbkdf2.Key([]byte(pass), []byte(salt), 65536, 32, sha256.New)\n  c <- pbkdf2Key\n}\n\n\/\/ fastXORWords XORs multiples of 4 or 8 bytes (depending on architecture.)\n\/\/ The arguments are assumed to be of equal length.\nfunc fastXORWords(dst, a, b []byte) {\n\tdw := *(*[]uintptr)(unsafe.Pointer(&dst))\n\taw := *(*[]uintptr)(unsafe.Pointer(&a))\n\tbw := *(*[]uintptr)(unsafe.Pointer(&b))\n\tn := len(b) \/ wordSize\n\tfor i := 0; i < n; i++ {\n\t\tdw[i] = aw[i] ^ bw[i]\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package timing\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\nvar percentiles = []int{90, 95, 99}\n\nfunc New() *Timing {\n\tt := &Timing{\n\t\tbegin:     time.Now(),\n\t\tresults:   make(chan record, 10),\n\t\tcollected: make(map[string][]record),\n\t}\n\tgo t.collector()\n\treturn t\n}\n\ntype Timing struct {\n\tbegin     time.Time\n\tresults   chan record\n\tdone      int32\n\tcollected map[string][]record\n}\n\nfunc (t *Timing) collector() {\n\tfor result := range t.results {\n\t\tt.collected[result.key] = append(t.collected[result.key], result)\n\t}\n\tatomic.AddInt32(&t.done, 1)\n}\n\nfunc (t *Timing) Log(elapsed time.Duration, key string) {\n\tt.results <- record{\n\t\tkey:     key,\n\t\telapsed: elapsed,\n\t}\n}\n\nfunc (t *Timing) LogSince(begin time.Time, key string) {\n\tt.Log(time.Since(begin), key)\n}\n\nfunc (t *Timing) Report() Report {\n\tdest := make(Report)\n\tt.ReportInto(dest)\n\treturn dest\n}\n\nfunc (t *Timing) ReportInto(dest Report) {\n\tdest[\"elapsed\"] = time.Since(t.begin).String()\n\tif atomic.LoadInt32(&t.done) == 0 {\n\t\tclose(t.results)\n\t}\n\tfor k, records := range t.collected {\n\t\tsort.Sort(recordsByTime(records))\n\n\t\t\/\/ calculate mean\n\t\tvar total time.Duration\n\t\tfor _, record := range records {\n\t\t\ttotal += record.elapsed\n\t\t}\n\t\tdest[fmt.Sprintf(\"%s_avg\", k)] = (total \/ time.Duration(len(records))).String()\n\n\t\t\/\/ calculate all the percentiles\n\t\tfor _, p := range percentiles {\n\t\t\t\/\/ TODO do we need a ceiling operator?\n\t\t\ttarget := len(records) * p \/ 100\n\t\t\tdest[fmt.Sprintf(\"%s_%dth\", k, p)] = records[target].elapsed.String()\n\t\t}\n\t}\n}\n\ntype Report map[string]interface{}\n\ntype record struct {\n\tkey     string\n\telapsed time.Duration\n}\n\ntype recordsByTime []record\n\nfunc (r recordsByTime) Len() int           { return len(r) }\nfunc (r recordsByTime) Less(i, j int) bool { return r[i].elapsed < r[j].elapsed }\nfunc (r recordsByTime) Swap(i, j int)      { r[i], r[j] = r[j], r[i] }\n<commit_msg>Fix a possible off-by-one error<commit_after>package timing\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\nvar percentiles = []int{90, 95, 99}\n\nfunc New() *Timing {\n\tt := &Timing{\n\t\tbegin:     time.Now(),\n\t\tresults:   make(chan record, 10),\n\t\tcollected: make(map[string][]record),\n\t}\n\tgo t.collector()\n\treturn t\n}\n\ntype Timing struct {\n\tbegin     time.Time\n\tresults   chan record\n\tdone      int32\n\tcollected map[string][]record\n}\n\nfunc (t *Timing) collector() {\n\tfor result := range t.results {\n\t\tt.collected[result.key] = append(t.collected[result.key], result)\n\t}\n\tatomic.AddInt32(&t.done, 1)\n}\n\nfunc (t *Timing) Log(elapsed time.Duration, key string) {\n\tt.results <- record{\n\t\tkey:     key,\n\t\telapsed: elapsed,\n\t}\n}\n\nfunc (t *Timing) LogSince(begin time.Time, key string) {\n\tt.Log(time.Since(begin), key)\n}\n\nfunc (t *Timing) Report() Report {\n\tdest := make(Report)\n\tt.ReportInto(dest)\n\treturn dest\n}\n\nfunc (t *Timing) ReportInto(dest Report) {\n\tdest[\"elapsed\"] = time.Since(t.begin).String()\n\tif atomic.LoadInt32(&t.done) == 0 {\n\t\tclose(t.results)\n\t}\n\tfor k, records := range t.collected {\n\t\tsort.Sort(recordsByTime(records))\n\n\t\t\/\/ calculate mean\n\t\tvar total time.Duration\n\t\tfor _, record := range records {\n\t\t\ttotal += record.elapsed\n\t\t}\n\t\tdest[fmt.Sprintf(\"%s_samples\", k)] = len(records)\n\t\tdest[fmt.Sprintf(\"%s_avg\", k)] = (total \/ time.Duration(len(records))).String()\n\n\t\t\/\/ calculate all the percentiles\n\t\tfor _, p := range percentiles {\n\t\t\t\/\/ TODO do we need a ceiling operator?\n\t\t\ttarget := len(records) * p \/ 100\n\t\t\tif target >= len(records) {\n\t\t\t\ttarget = len(records) - 1\n\t\t\t}\n\t\t\tdest[fmt.Sprintf(\"%s_%dth\", k, p)] = records[target].elapsed.String()\n\t\t}\n\t}\n}\n\ntype Report map[string]interface{}\n\ntype record struct {\n\tkey     string\n\telapsed time.Duration\n}\n\ntype recordsByTime []record\n\nfunc (r recordsByTime) Len() int           { return len(r) }\nfunc (r recordsByTime) Less(i, j int) bool { return r[i].elapsed < r[j].elapsed }\nfunc (r recordsByTime) Swap(i, j int)      { r[i], r[j] = r[j], r[i] }\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com\/dynport\/dgtk\/tagparse\"\n)\n\ntype action struct {\n\tpath        string             \/\/ Path used for the routing.\n\tparams      map[string]*option \/\/ Mapping of flags and options (short and long) to according value.\n\topts        []*option          \/\/ The options available for the action.\n\targs        []*argument        \/\/ List of arguments accepted.\n\trunner      Runner             \/\/ Who's connected to the action.\n\tdescription string             \/\/ Description of the action.\n\tvalue       reflect.Value\n}\n\n\/\/ Register an action for the given path with the given runner.\nfunc newAction(path string, r Runner, desc string) (act *action, e error) {\n\n\tact = &action{\n\t\tpath:        path,\n\t\trunner:      r,\n\t\tparams:      map[string]*option{},\n\t\tdescription: desc}\n\n\t\/\/ Inject the \"help\" option (handled specially).\n\thelpOption := &option{field: \"Help\", short: \"h\", long: \"help\", isFlag: true, desc: \"show help for action\"}\n\tact.opts = append(act.opts, helpOption)\n\tact.params[\"h\"] = helpOption\n\tact.params[\"help\"] = helpOption\n\n\tif e := act.reflect(); e != nil {\n\t\treturn nil, e\n\t}\n\treturn act, nil\n}\n\n\/\/ Method to reflect on the action's runner type and determine the according options and arguments.\nfunc (a *action) reflect() (e error) {\n\tv := reflect.ValueOf(a.runner)\n\tif v.Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\ta.value = v\n\te = a.reflectRecurse(v)\n\tif e != nil {\n\t\te = fmt.Errorf(\"%s: %s\", v.Type().Name(), e)\n\t}\n\treturn e\n}\n\nfunc (a *action) reflectRecurse(value reflect.Value) (e error) {\n\tif !value.IsValid() {\n\t\t\/\/ ignore invalid stuff\n\t\treturn nil\n\t}\n\n\tv := reflect.ValueOf(value.Interface())\n\tif v.Kind() == reflect.Ptr {\n\t\tif v.IsNil() {\n\t\t\tv = reflect.New(v.Type().Elem())\n\t\t}\n\t\tv = v.Elem()\n\t}\n\n\tif v.Kind() != reflect.Struct {\n\t\treturn nil\n\t}\n\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Type().Field(i)\n\t\tvalue := v.Field(i)\n\n\t\tif field.PkgPath != \"\" { \/\/ Unexported field have a pkg path set.\n\t\t\tcontinue \/\/ Ignore unexported fields.\n\t\t}\n\n\t\tif field.Anonymous {\n\t\t\te = a.reflectRecurse(reflect.ValueOf(value.Interface()))\n\t\t\tif e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\te = a.handleField(field, value)\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc splitter(tagval string) (key, value string, e error) {\n\tswitch {\n\tcase tagval == \"required\":\n\t\treturn \"required\", \"true\", nil\n\tcase tagval == \"opt\":\n\t\treturn \"type\", \"opt\", nil\n\tcase tagval == \"arg\":\n\t\treturn \"type\", \"arg\", nil\n\tcase strings.HasPrefix(tagval, \"--\"):\n\t\treturn \"long\", tagval[2:], nil\n\tcase strings.HasPrefix(tagval, \"-\"):\n\t\treturn \"short\", tagval[1:], nil\n\t}\n\treturn \"\", \"\", fmt.Errorf(\"failed\")\n}\n\nfunc (a *action) handleField(field reflect.StructField, value reflect.Value) (e error) {\n\ttagMap, e := tagparse.ParseCustom(field, \"cli\", splitter)\n\tif e != nil {\n\t\treturn fmt.Errorf(\"failed to parse tag for field %q: %s\", field.Name, e)\n\t}\n\n\tif len(tagMap) == 0 {\n\t\treturn nil\n\t}\n\n\tswitch tagMap[\"type\"] {\n\tcase \"arg\":\n\t\tif e = a.createArgument(field, value, tagMap); e != nil {\n\t\t\treturn e\n\t\t}\n\tcase \"opt\":\n\t\tif e = a.createOption(field, value, tagMap); e != nil {\n\t\t\treturn e\n\t\t}\n\tdefault:\n\t\tif tagMap[\"type\"] == \"\" {\n\t\t\treturn fmt.Errorf(\"tag for field %q has no type set\", field.Name)\n\t\t}\n\t\treturn fmt.Errorf(\"tag for field %q has unknown type %q\", field.Name, tagMap[\"type\"])\n\t}\n\treturn nil\n}\n\nfunc (a *action) parseArgs(params []string) (e error) {\n\targIdx := 0\n\tignoreOptions := false\n\tfor idx := 0; idx < len(params); idx++ {\n\t\tvalue := params[idx]\n\t\tswitch {\n\t\tcase !ignoreOptions && strings.Contains(value, \" \"): \/\/ Must be an arg!\n\t\t\tif argIdx, e = a.handleArgs(value, argIdx); e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\tcase !ignoreOptions && value == \"--\":\n\t\t\tignoreOptions = true\n\t\tcase !ignoreOptions && strings.HasPrefix(value, \"--\"):\n\t\t\tidx, e = a.handleParams(value[2:], false, params, idx)\n\t\t\tif e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\tcase !ignoreOptions && strings.HasPrefix(value, \"-\"):\n\t\t\tidx, e = a.handleParams(value[1:], true, params, idx)\n\t\t\tif e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\tdefault:\n\t\t\tif argIdx, e = a.handleArgs(value, argIdx); e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\t}\n\t}\n\treturn a.reflectIntoRunner()\n}\n\nfunc (a *action) handleArgs(value string, index int) (int, error) {\n\tif arg := a.argumentForPosition(index); arg != nil {\n\t\targ.setValue(value)\n\t\treturn index + 1, nil\n\t}\n\treturn -1, fmt.Errorf(\"too many arguments given\")\n}\n\nfunc (a *action) handleParams(paramName string, short bool, args []string, idx int) (int, error) {\n\tvar value string\n\tif !short {\n\t\tparts := strings.SplitN(paramName, \"=\", 2)\n\t\tif len(parts) == 2 {\n\t\t\tfmt.Printf(\"--> %s = %s\\n\", parts[0], parts[1])\n\t\t\tparamName = parts[0]\n\t\t\tvalue = parts[1]\n\t\t}\n\t}\n\n\t\/\/ Keep that on top, as this is some special sort of handling. Required to make help appear in usage description,\n\t\/\/ but not be injected to deep.\n\tif paramName == \"h\" || paramName == \"help\" {\n\t\treturn -1, ErrorHelpRequested\n\t}\n\n\toption, found := a.params[paramName]\n\tif !found {\n\t\treturn -1, fmt.Errorf(\"unknown parameter found: %q\", paramName)\n\t}\n\n\tif option.isFlag {\n\t\tif option.value == \"\" || option.value == \"false\" {\n\t\t\toption.value = \"true\"\n\t\t}\n\t} else {\n\t\tif value == \"\" {\n\t\t\tif idx+1 > len(args) {\n\t\t\t\treturn -1, fmt.Errorf(\"missing value for option %q!\", option.field)\n\t\t\t}\n\t\t\tvalue = args[idx+1]\n\t\t\tidx += 1\n\t\t}\n\t\toption.value = value\n\t}\n\treturn idx, nil\n}\n\n\/\/ Use reflection to set values of the runner, if the action was called with a matching route.\nfunc (a *action) reflectIntoRunner() (e error) {\n\tif e = a.reflectOptions(); e != nil {\n\t\treturn e\n\t}\n\tif e = a.reflectArguments(); e != nil {\n\t\treturn e\n\t}\n\treturn nil\n}\n\nfunc (a *action) reflectOptions() (e error) {\n\tfor _, option := range a.opts {\n\t\tif e = option.reflectTo(a.value); e != nil {\n\t\t\treturn e\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (a *action) reflectArguments() (e error) {\n\tfor _, arg := range a.args {\n\t\tif e = arg.reflectTo(a.value); e != nil {\n\t\t\treturn e\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (a *action) showHelp() {\n\ta.showShortHelp()\n\tif a.description != \"\" {\n\t\tlogger.Print(\"  \", a.description)\n\t}\n\n\toptsAvailable := false\n\tif len(a.opts) > 0 {\n\t\toptsAvailable = true\n\t\tlogger.Print(\"  OPTIONS\")\n\t\tfor _, opt := range a.opts {\n\t\t\tlogger.Print(opt.description())\n\t\t}\n\t}\n\tif len(a.args) > 0 {\n\t\tif optsAvailable {\n\t\t\tlogger.Println()\n\t\t}\n\t\tlogger.Print(\"  ARGUMENTS\")\n\t\tfor _, arg := range a.args {\n\t\t\tlogger.Print(arg.description())\n\t\t}\n\t}\n\tlogger.Println()\n}\n\nfunc (a *action) showShortHelp() {\n\tline := strings.Replace(a.path, \"\/\", \" \", -1) + \" \"\n\tfor i := range a.opts {\n\t\tline += \"[\" + a.opts[i].shortDescription(\"|\") + \"] \"\n\t}\n\tfor _, arg := range a.args {\n\t\tline += arg.shortDescription()\n\t\tline += \" \"\n\t}\n\tlogger.Print(line)\n}\n\nfunc (a *action) showTabularHelp(t *table) {\n\toDesc := make([]string, len(a.opts))\n\taDesc := make([]string, len(a.args))\n\tfor i := range a.opts {\n\t\tif a.opts[i].required {\n\t\t\toDesc[i] = \"[\" + a.opts[i].shortDescription(\"|\") + \"]\"\n\t\t}\n\t}\n\tfor i := range a.args {\n\t\taDesc[i] = a.args[i].shortDescription()\n\t}\n\tt.addRow(\n\t\trow{\n\t\t\tstrings.Replace(a.path, \"\/\", \" \", -1),\n\t\t\tstrings.Join(oDesc, \" \"),\n\t\t\tstrings.Join(aDesc, \" \"),\n\t\t\ta.description,\n\t\t})\n}\n<commit_msg>fixed issue with indexing<commit_after>package cli\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com\/dynport\/dgtk\/tagparse\"\n)\n\ntype action struct {\n\tpath        string             \/\/ Path used for the routing.\n\tparams      map[string]*option \/\/ Mapping of flags and options (short and long) to according value.\n\topts        []*option          \/\/ The options available for the action.\n\targs        []*argument        \/\/ List of arguments accepted.\n\trunner      Runner             \/\/ Who's connected to the action.\n\tdescription string             \/\/ Description of the action.\n\tvalue       reflect.Value\n}\n\n\/\/ Register an action for the given path with the given runner.\nfunc newAction(path string, r Runner, desc string) (act *action, e error) {\n\n\tact = &action{\n\t\tpath:        path,\n\t\trunner:      r,\n\t\tparams:      map[string]*option{},\n\t\tdescription: desc}\n\n\t\/\/ Inject the \"help\" option (handled specially).\n\thelpOption := &option{field: \"Help\", short: \"h\", long: \"help\", isFlag: true, desc: \"show help for action\"}\n\tact.opts = append(act.opts, helpOption)\n\tact.params[\"h\"] = helpOption\n\tact.params[\"help\"] = helpOption\n\n\tif e := act.reflect(); e != nil {\n\t\treturn nil, e\n\t}\n\treturn act, nil\n}\n\n\/\/ Method to reflect on the action's runner type and determine the according options and arguments.\nfunc (a *action) reflect() (e error) {\n\tv := reflect.ValueOf(a.runner)\n\tif v.Kind() == reflect.Ptr {\n\t\tv = v.Elem()\n\t}\n\ta.value = v\n\te = a.reflectRecurse(v)\n\tif e != nil {\n\t\te = fmt.Errorf(\"%s: %s\", v.Type().Name(), e)\n\t}\n\treturn e\n}\n\nfunc (a *action) reflectRecurse(value reflect.Value) (e error) {\n\tif !value.IsValid() {\n\t\t\/\/ ignore invalid stuff\n\t\treturn nil\n\t}\n\n\tv := reflect.ValueOf(value.Interface())\n\tif v.Kind() == reflect.Ptr {\n\t\tif v.IsNil() {\n\t\t\tv = reflect.New(v.Type().Elem())\n\t\t}\n\t\tv = v.Elem()\n\t}\n\n\tif v.Kind() != reflect.Struct {\n\t\treturn nil\n\t}\n\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Type().Field(i)\n\t\tvalue := v.Field(i)\n\n\t\tif field.PkgPath != \"\" { \/\/ Unexported field have a pkg path set.\n\t\t\tcontinue \/\/ Ignore unexported fields.\n\t\t}\n\n\t\tif field.Anonymous {\n\t\t\te = a.reflectRecurse(reflect.ValueOf(value.Interface()))\n\t\t\tif e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\te = a.handleField(field, value)\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc splitter(tagval string) (key, value string, e error) {\n\tswitch {\n\tcase tagval == \"required\":\n\t\treturn \"required\", \"true\", nil\n\tcase tagval == \"opt\":\n\t\treturn \"type\", \"opt\", nil\n\tcase tagval == \"arg\":\n\t\treturn \"type\", \"arg\", nil\n\tcase strings.HasPrefix(tagval, \"--\"):\n\t\treturn \"long\", tagval[2:], nil\n\tcase strings.HasPrefix(tagval, \"-\"):\n\t\treturn \"short\", tagval[1:], nil\n\t}\n\treturn \"\", \"\", fmt.Errorf(\"failed\")\n}\n\nfunc (a *action) handleField(field reflect.StructField, value reflect.Value) (e error) {\n\ttagMap, e := tagparse.ParseCustom(field, \"cli\", splitter)\n\tif e != nil {\n\t\treturn fmt.Errorf(\"failed to parse tag for field %q: %s\", field.Name, e)\n\t}\n\n\tif len(tagMap) == 0 {\n\t\treturn nil\n\t}\n\n\tswitch tagMap[\"type\"] {\n\tcase \"arg\":\n\t\tif e = a.createArgument(field, value, tagMap); e != nil {\n\t\t\treturn e\n\t\t}\n\tcase \"opt\":\n\t\tif e = a.createOption(field, value, tagMap); e != nil {\n\t\t\treturn e\n\t\t}\n\tdefault:\n\t\tif tagMap[\"type\"] == \"\" {\n\t\t\treturn fmt.Errorf(\"tag for field %q has no type set\", field.Name)\n\t\t}\n\t\treturn fmt.Errorf(\"tag for field %q has unknown type %q\", field.Name, tagMap[\"type\"])\n\t}\n\treturn nil\n}\n\nfunc (a *action) parseArgs(params []string) (e error) {\n\targIdx := 0\n\tignoreOptions := false\n\tfor idx := 0; idx < len(params); idx++ {\n\t\tvalue := params[idx]\n\t\tswitch {\n\t\tcase !ignoreOptions && strings.Contains(value, \" \"): \/\/ Must be an arg!\n\t\t\tif argIdx, e = a.handleArgs(value, argIdx); e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\tcase !ignoreOptions && value == \"--\":\n\t\t\tignoreOptions = true\n\t\tcase !ignoreOptions && strings.HasPrefix(value, \"--\"):\n\t\t\tidx, e = a.handleParams(value[2:], false, params, idx)\n\t\t\tif e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\tcase !ignoreOptions && strings.HasPrefix(value, \"-\"):\n\t\t\tidx, e = a.handleParams(value[1:], true, params, idx)\n\t\t\tif e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\tdefault:\n\t\t\tif argIdx, e = a.handleArgs(value, argIdx); e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\t}\n\t}\n\treturn a.reflectIntoRunner()\n}\n\nfunc (a *action) handleArgs(value string, index int) (int, error) {\n\tif arg := a.argumentForPosition(index); arg != nil {\n\t\targ.setValue(value)\n\t\treturn index + 1, nil\n\t}\n\treturn -1, fmt.Errorf(\"too many arguments given\")\n}\n\nfunc (a *action) handleParams(paramName string, short bool, args []string, idx int) (int, error) {\n\tvar value string\n\tif !short {\n\t\tparts := strings.SplitN(paramName, \"=\", 2)\n\t\tif len(parts) == 2 {\n\t\t\tfmt.Printf(\"--> %s = %s\\n\", parts[0], parts[1])\n\t\t\tparamName = parts[0]\n\t\t\tvalue = parts[1]\n\t\t}\n\t}\n\n\t\/\/ Keep that on top, as this is some special sort of handling. Required to make help appear in usage description,\n\t\/\/ but not be injected to deep.\n\tif paramName == \"h\" || paramName == \"help\" {\n\t\treturn -1, ErrorHelpRequested\n\t}\n\n\toption, found := a.params[paramName]\n\tif !found {\n\t\treturn -1, fmt.Errorf(\"unknown parameter found: %q\", paramName)\n\t}\n\n\tif option.isFlag {\n\t\tif option.value == \"\" || option.value == \"false\" {\n\t\t\toption.value = \"true\"\n\t\t}\n\t} else {\n\t\tif value == \"\" {\n\t\t\tif idx+1 >= len(args) {\n\t\t\t\treturn -1, fmt.Errorf(\"missing value for option %q!\", option.field)\n\t\t\t}\n\t\t\tvalue = args[idx+1]\n\t\t\tidx += 1\n\t\t}\n\t\toption.value = value\n\t}\n\treturn idx, nil\n}\n\n\/\/ Use reflection to set values of the runner, if the action was called with a matching route.\nfunc (a *action) reflectIntoRunner() (e error) {\n\tif e = a.reflectOptions(); e != nil {\n\t\treturn e\n\t}\n\tif e = a.reflectArguments(); e != nil {\n\t\treturn e\n\t}\n\treturn nil\n}\n\nfunc (a *action) reflectOptions() (e error) {\n\tfor _, option := range a.opts {\n\t\tif e = option.reflectTo(a.value); e != nil {\n\t\t\treturn e\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (a *action) reflectArguments() (e error) {\n\tfor _, arg := range a.args {\n\t\tif e = arg.reflectTo(a.value); e != nil {\n\t\t\treturn e\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (a *action) showHelp() {\n\ta.showShortHelp()\n\tif a.description != \"\" {\n\t\tlogger.Print(\"  \", a.description)\n\t}\n\n\toptsAvailable := false\n\tif len(a.opts) > 0 {\n\t\toptsAvailable = true\n\t\tlogger.Print(\"  OPTIONS\")\n\t\tfor _, opt := range a.opts {\n\t\t\tlogger.Print(opt.description())\n\t\t}\n\t}\n\tif len(a.args) > 0 {\n\t\tif optsAvailable {\n\t\t\tlogger.Println()\n\t\t}\n\t\tlogger.Print(\"  ARGUMENTS\")\n\t\tfor _, arg := range a.args {\n\t\t\tlogger.Print(arg.description())\n\t\t}\n\t}\n\tlogger.Println()\n}\n\nfunc (a *action) showShortHelp() {\n\tline := strings.Replace(a.path, \"\/\", \" \", -1) + \" \"\n\tfor i := range a.opts {\n\t\tline += \"[\" + a.opts[i].shortDescription(\"|\") + \"] \"\n\t}\n\tfor _, arg := range a.args {\n\t\tline += arg.shortDescription()\n\t\tline += \" \"\n\t}\n\tlogger.Print(line)\n}\n\nfunc (a *action) showTabularHelp(t *table) {\n\toDesc := make([]string, len(a.opts))\n\taDesc := make([]string, len(a.args))\n\tfor i := range a.opts {\n\t\tif a.opts[i].required {\n\t\t\toDesc[i] = \"[\" + a.opts[i].shortDescription(\"|\") + \"]\"\n\t\t}\n\t}\n\tfor i := range a.args {\n\t\taDesc[i] = a.args[i].shortDescription()\n\t}\n\tt.addRow(\n\t\trow{\n\t\t\tstrings.Replace(a.path, \"\/\", \" \", -1),\n\t\t\tstrings.Join(oDesc, \" \"),\n\t\t\tstrings.Join(aDesc, \" \"),\n\t\t\ta.description,\n\t\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/99designs\/aws-vault\/prompt\"\n\t\"github.com\/99designs\/aws-vault\/vault\"\n\t\"github.com\/99designs\/keyring\"\n\t\"golang.org\/x\/crypto\/ssh\/terminal\"\n\tkingpin \"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\nconst (\n\tKeyringName = \"aws-vault\"\n)\n\nvar (\n\tkeyringImpl      keyring.Keyring\n\tawsConfig        *vault.Config\n\tpromptsAvailable = prompt.Available()\n)\n\nvar GlobalFlags struct {\n\tDebug        bool\n\tBackend      string\n\tPromptDriver string\n}\n\nfunc ConfigureGlobals(app *kingpin.Application) {\n\tbackendsAvailable := []string{}\n\tfor _, backendType := range keyring.AvailableBackends() {\n\t\tbackendsAvailable = append(backendsAvailable, string(backendType))\n\t}\n\n\tapp.Flag(\"debug\", \"Show debugging output\").\n\t\tBoolVar(&GlobalFlags.Debug)\n\n\tapp.Flag(\"backend\", fmt.Sprintf(\"Secret backend to use %v\", backendsAvailable)).\n\t\tOverrideDefaultFromEnvar(\"AWS_VAULT_BACKEND\").\n\t\tEnumVar(&GlobalFlags.Backend, backendsAvailable...)\n\n\tapp.Flag(\"prompt\", fmt.Sprintf(\"Prompt driver to use %v\", promptsAvailable)).\n\t\tDefault(\"terminal\").\n\t\tOverrideDefaultFromEnvar(\"AWS_VAULT_PROMPT\").\n\t\tEnumVar(&GlobalFlags.PromptDriver, promptsAvailable...)\n\n\tapp.PreAction(func(c *kingpin.ParseContext) (err error) {\n\t\tif !GlobalFlags.Debug {\n\t\t\tlog.SetOutput(ioutil.Discard)\n\t\t} else {\n\t\t\tkeyring.Debug = true\n\t\t}\n\t\tif keyringImpl == nil {\n\t\t\tallowedBackends := []keyring.BackendType{}\n\t\t\tif GlobalFlags.Backend != \"\" {\n\t\t\t\tallowedBackends = append(allowedBackends, keyring.BackendType(GlobalFlags.Backend))\n\t\t\t}\n\n\t\t\tkeyringImpl, err = keyring.Open(keyring.Config{\n\t\t\t\tServiceName:      \"aws-vault\",\n\t\t\t\tAllowedBackends:  allowedBackends,\n\t\t\t\tKeychainName:     \"aws-vault\",\n\t\t\t\tFileDir:          \"~\/.awsvault\/keys\/\",\n\t\t\t\tFilePasswordFunc: fileKeyringPassphrasePrompt,\n\t\t\t\tKWalletAppID:     \"aws-vault\",\n\t\t\t\tKWalletFolder:    \"aws-vault\",\n\t\t\t})\n\t\t}\n\t\tif awsConfig == nil {\n\t\t\tawsConfig, err = vault.LoadConfigFromEnv()\n\t\t}\n\t\treturn err\n\t})\n}\n\nfunc fileKeyringPassphrasePrompt(prompt string) (string, error) {\n\tif password := os.Getenv(\"AWS_VAULT_FILE_PASSPHRASE\"); password != \"\" {\n\t\treturn password, nil\n\t}\n\n\tfmt.Printf(\"%s: \", prompt)\n\tb, err := terminal.ReadPassword(int(os.Stdin.Fd()))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfmt.Println()\n\treturn string(b), nil\n}\n<commit_msg>Use nil slice vs empty slice<commit_after>package cli\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/99designs\/aws-vault\/prompt\"\n\t\"github.com\/99designs\/aws-vault\/vault\"\n\t\"github.com\/99designs\/keyring\"\n\t\"golang.org\/x\/crypto\/ssh\/terminal\"\n\tkingpin \"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\nconst (\n\tKeyringName = \"aws-vault\"\n)\n\nvar (\n\tkeyringImpl      keyring.Keyring\n\tawsConfig        *vault.Config\n\tpromptsAvailable = prompt.Available()\n)\n\nvar GlobalFlags struct {\n\tDebug        bool\n\tBackend      string\n\tPromptDriver string\n}\n\nfunc ConfigureGlobals(app *kingpin.Application) {\n\tbackendsAvailable := []string{}\n\tfor _, backendType := range keyring.AvailableBackends() {\n\t\tbackendsAvailable = append(backendsAvailable, string(backendType))\n\t}\n\n\tapp.Flag(\"debug\", \"Show debugging output\").\n\t\tBoolVar(&GlobalFlags.Debug)\n\n\tapp.Flag(\"backend\", fmt.Sprintf(\"Secret backend to use %v\", backendsAvailable)).\n\t\tOverrideDefaultFromEnvar(\"AWS_VAULT_BACKEND\").\n\t\tEnumVar(&GlobalFlags.Backend, backendsAvailable...)\n\n\tapp.Flag(\"prompt\", fmt.Sprintf(\"Prompt driver to use %v\", promptsAvailable)).\n\t\tDefault(\"terminal\").\n\t\tOverrideDefaultFromEnvar(\"AWS_VAULT_PROMPT\").\n\t\tEnumVar(&GlobalFlags.PromptDriver, promptsAvailable...)\n\n\tapp.PreAction(func(c *kingpin.ParseContext) (err error) {\n\t\tif !GlobalFlags.Debug {\n\t\t\tlog.SetOutput(ioutil.Discard)\n\t\t} else {\n\t\t\tkeyring.Debug = true\n\t\t}\n\t\tif keyringImpl == nil {\n\t\t\tvar allowedBackends []keyring.BackendType\n\t\t\tif GlobalFlags.Backend != \"\" {\n\t\t\t\tallowedBackends = append(allowedBackends, keyring.BackendType(GlobalFlags.Backend))\n\t\t\t}\n\n\t\t\tkeyringImpl, err = keyring.Open(keyring.Config{\n\t\t\t\tServiceName:      \"aws-vault\",\n\t\t\t\tAllowedBackends:  allowedBackends,\n\t\t\t\tKeychainName:     \"aws-vault\",\n\t\t\t\tFileDir:          \"~\/.awsvault\/keys\/\",\n\t\t\t\tFilePasswordFunc: fileKeyringPassphrasePrompt,\n\t\t\t\tKWalletAppID:     \"aws-vault\",\n\t\t\t\tKWalletFolder:    \"aws-vault\",\n\t\t\t})\n\t\t}\n\t\tif awsConfig == nil {\n\t\t\tawsConfig, err = vault.LoadConfigFromEnv()\n\t\t}\n\t\treturn err\n\t})\n}\n\nfunc fileKeyringPassphrasePrompt(prompt string) (string, error) {\n\tif password := os.Getenv(\"AWS_VAULT_FILE_PASSPHRASE\"); password != \"\" {\n\t\treturn password, nil\n\t}\n\n\tfmt.Printf(\"%s: \", prompt)\n\tb, err := terminal.ReadPassword(int(os.Stdin.Fd()))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tfmt.Println()\n\treturn string(b), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package client provides a Stripe client for invoking APIs across all resources\npackage client\n\nimport (\n\t. \"github.com\/stripe\/stripe-go\"\n\t\"github.com\/stripe\/stripe-go\/account\"\n\t\"github.com\/stripe\/stripe-go\/balance\"\n\t\"github.com\/stripe\/stripe-go\/bankaccount\"\n\t\"github.com\/stripe\/stripe-go\/bitcoinreceiver\"\n\t\"github.com\/stripe\/stripe-go\/bitcointransaction\"\n\t\"github.com\/stripe\/stripe-go\/card\"\n\t\"github.com\/stripe\/stripe-go\/charge\"\n\t\"github.com\/stripe\/stripe-go\/countryspec\"\n\t\"github.com\/stripe\/stripe-go\/coupon\"\n\t\"github.com\/stripe\/stripe-go\/customer\"\n\t\"github.com\/stripe\/stripe-go\/discount\"\n\t\"github.com\/stripe\/stripe-go\/dispute\"\n\t\"github.com\/stripe\/stripe-go\/ephemeralkey\"\n\t\"github.com\/stripe\/stripe-go\/event\"\n\t\"github.com\/stripe\/stripe-go\/exchangerate\"\n\t\"github.com\/stripe\/stripe-go\/fee\"\n\t\"github.com\/stripe\/stripe-go\/feerefund\"\n\t\"github.com\/stripe\/stripe-go\/fileupload\"\n\t\"github.com\/stripe\/stripe-go\/invoice\"\n\t\"github.com\/stripe\/stripe-go\/invoiceitem\"\n\t\"github.com\/stripe\/stripe-go\/loginlink\"\n\t\"github.com\/stripe\/stripe-go\/order\"\n\t\"github.com\/stripe\/stripe-go\/orderreturn\"\n\t\"github.com\/stripe\/stripe-go\/paymentsource\"\n\t\"github.com\/stripe\/stripe-go\/payout\"\n\t\"github.com\/stripe\/stripe-go\/plan\"\n\t\"github.com\/stripe\/stripe-go\/product\"\n\t\"github.com\/stripe\/stripe-go\/recipient\"\n\t\"github.com\/stripe\/stripe-go\/refund\"\n\t\"github.com\/stripe\/stripe-go\/reversal\"\n\t\"github.com\/stripe\/stripe-go\/sku\"\n\t\"github.com\/stripe\/stripe-go\/source\"\n\t\"github.com\/stripe\/stripe-go\/sub\"\n\t\"github.com\/stripe\/stripe-go\/subitem\"\n\t\"github.com\/stripe\/stripe-go\/token\"\n\t\"github.com\/stripe\/stripe-go\/transfer\"\n)\n\n\/\/ API is the Stripe client. It contains all the different resources available.\ntype API struct {\n\t\/\/ Charges is the client used to invoke \/charges APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#charges.\n\tCharges *charge.Client\n\t\/\/ Customers is the client used to invoke \/customers APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#customers.\n\tCustomers *customer.Client\n\t\/\/ Cards is the client used to invoke \/cards APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#cards.\n\tCards *card.Client\n\t\/\/ Subscriptions is the client used to invoke \/subscriptions APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#subscriptions.\n\tSubscriptions *sub.Client\n\t\/\/ SubscriptionItems is the client used to invoke subscription's items-related APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#subscription_items.\n\tSubscriptionItems *subitem.Client\n\t\/\/ Plans is the client used to invoke \/plans APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#plans.\n\tPlans *plan.Client\n\t\/\/ Coupons is the client used to invoke \/coupons APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#coupons.\n\tCoupons *coupon.Client\n\t\/\/ Discounts is the client used to invoke discount-related APIs.\n\t\/\/ For mode details see https:\/\/stripe.com\/docs\/api#discounts.\n\tDiscounts *discount.Client\n\t\/\/ Invoices is the client used to invoke \/invoices APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#invoices.\n\tInvoices *invoice.Client\n\t\/\/ InvoiceItems is the client used to invoke \/invoiceitems APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#invoiceitems.\n\tInvoiceItems *invoiceitem.Client\n\t\/\/ LoginLinks is the client used to invoke \/v1\/accounts\/<account_id>\/login_links APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#login_link_object.\n\tLoginLinks *loginlink.Client\n\t\/\/ Disputes is the client used to invoke dispute-related APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#disputes.\n\tDisputes *dispute.Client\n\t\/\/ Transfers is the client used to invoke \/transfers APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#transfers.\n\tTransfers *transfer.Client\n\t\/\/ Payouts is the client used to invoke \/payouts APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#payouts.\n\tPayouts *payout.Client\n\t\/\/ Recipients is the client used to invoke \/recipients APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#recipients.\n\tRecipients *recipient.Client\n\t\/\/ Refunds is the client used to invoke \/refunds APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#refunds.\n\tRefunds *refund.Client\n\t\/\/ Fees is the client used to invoke \/application_fees APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#application_fees.\n\tFees *fee.Client\n\t\/\/ FeeRefunds is the client used to invoke \/application_fees\/refunds APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#fee_refundss.\n\tFeeRefunds *feerefund.Client\n\t\/\/ Account is the client used to invoke \/account APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#account.\n\tAccount *account.Client\n\t\/\/ CountrySpec is the client used to invoke \/country_specs APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#country_specs.\n\tCountrySpec *countryspec.Client\n\t\/\/ Balance is the client used to invoke \/balance and transaction-related APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#balance.\n\tBalance *balance.Client\n\t\/\/ EphemeralKeys is the client used to invoke \/ephemeral_keys APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#ephemeral_keys.\n\tEphemeralKeys *ephemeralkey.Client\n\t\/\/ Events is the client used to invoke \/events APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#events.\n\tEvents *event.Client\n\t\/\/ Tokens is the client used to invoke \/tokens APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#tokens.\n\tTokens *token.Client\n\t\/\/ FileUploads is the client used to invoke the uploads \/files APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#file_uploads.\n\tFileUploads *fileupload.Client\n\t\/\/ BitcoinReceivers is the client used to invoke \/bitcoin\/receivers APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#bitcoin_receivers.\n\tBitcoinReceivers *bitcoinreceiver.Client\n\t\/\/ BitcoinTransactions is the client used to invoke \/bitcoin\/transactions APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#bitcoin_receivers.\n\tBitcoinTransactions *bitcointransaction.Client\n\t\/\/ Reversals is the client used to invoke \/transfers\/reversals APIs.\n\tReversals *reversal.Client\n\t\/\/ BankAccounts is the client used to invoke \/accounts\/bank_accounts APIs.\n\tBankAccounts *bankaccount.Client\n\t\/\/ Products is the client used to invoke \/products APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#products.\n\tProducts *product.Client\n\t\/\/ Orders is the client used to invoke \/orders APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#orders.\n\tOrders *order.Client\n\t\/\/ OrderReturns is the client used to invoke \/order_returns APIs.\n\t\/\/ For more details, see https:\/\/stripe.com\/docs\/api#order_returns.\n\tOrderReturns *orderreturn.Client\n\t\/\/ Skus is the client used to invoke \/skus APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#skus.\n\tSkus *sku.Client\n\t\/\/ Sources is the client used to invoke \/sources APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api#sources.\n\tSources *source.Client\n\t\/\/ PaymentSource is used to invoke \/sources APIs.\n\t\/\/ For more details see https:\/\/stripe.com\/docs\/api.\n\tPaymentSource *paymentsource.Client\n\t\/\/ ExchangeRates is the client used to invoke \/exchange_rates APIs.\n\tExchangeRates *exchangerate.Client\n}\n\n\/\/ Init initializes the Stripe client with the appropriate secret key\n\/\/ as well as providing the ability to override the backend as needed.\nfunc (a *API) Init(key string, backends *Backends) {\n\tif backends == nil {\n\t\tbackends = &Backends{API: GetBackend(APIBackend), Uploads: GetBackend(UploadsBackend)}\n\t}\n\n\ta.Charges = &charge.Client{B: backends.API, Key: key}\n\ta.Customers = &customer.Client{B: backends.API, Key: key}\n\ta.Cards = &card.Client{B: backends.API, Key: key}\n\ta.Subscriptions = &sub.Client{B: backends.API, Key: key}\n\ta.SubscriptionItems = &subitem.Client{B: backends.API, Key: key}\n\ta.Plans = &plan.Client{B: backends.API, Key: key}\n\ta.Coupons = &coupon.Client{B: backends.API, Key: key}\n\ta.Discounts = &discount.Client{B: backends.API, Key: key}\n\ta.Invoices = &invoice.Client{B: backends.API, Key: key}\n\ta.InvoiceItems = &invoiceitem.Client{B: backends.API, Key: key}\n\ta.LoginLinks = &loginlink.Client{B: backends.API, Key: key}\n\ta.Disputes = &dispute.Client{B: backends.API, Key: key}\n\ta.Transfers = &transfer.Client{B: backends.API, Key: key}\n\ta.Payouts = &payout.Client{B: backends.API, Key: key}\n\ta.Recipients = &recipient.Client{B: backends.API, Key: key}\n\ta.Refunds = &refund.Client{B: backends.API, Key: key}\n\ta.Fees = &fee.Client{B: backends.API, Key: key}\n\ta.FeeRefunds = &feerefund.Client{B: backends.API, Key: key}\n\ta.Account = &account.Client{B: backends.API, Key: key}\n\ta.CountrySpec = &countryspec.Client{B: backends.API, Key: key}\n\ta.Balance = &balance.Client{B: backends.API, Key: key}\n\ta.EphemeralKeys = &ephemeralkey.Client{B: backends.API, Key: key}\n\ta.Events = &event.Client{B: backends.API, Key: key}\n\ta.Tokens = &token.Client{B: backends.API, Key: key}\n\ta.FileUploads = &fileupload.Client{B: backends.Uploads, Key: key}\n\ta.BitcoinReceivers = &bitcoinreceiver.Client{B: backends.API, Key: key}\n\ta.BitcoinTransactions = &bitcointransaction.Client{B: backends.API, Key: key}\n\ta.Reversals = &reversal.Client{B: backends.API, Key: key}\n\ta.BankAccounts = &bankaccount.Client{B: backends.API, Key: key}\n\ta.Products = &product.Client{B: backends.API, Key: key}\n\ta.Orders = &order.Client{B: backends.API, Key: key}\n\ta.OrderReturns = &orderreturn.Client{B: backends.API, Key: key}\n\ta.Skus = &sku.Client{B: backends.API, Key: key}\n\ta.Sources = &source.Client{B: backends.API, Key: key}\n\ta.PaymentSource = &paymentsource.Client{B: backends.API, Key: key}\n\ta.ExchangeRates = &exchangerate.Client{B: backends.API, Key: key}\n}\n\n\/\/ New creates a new Stripe client with the appropriate secret key\n\/\/ as well as providing the ability to override the backends as needed.\nfunc New(key string, backends *Backends) *API {\n\tapi := API{}\n\tapi.Init(key, backends)\n\treturn &api\n}\n<commit_msg>Properly order packages in api.go<commit_after>\/\/ Package client provides a Stripe client for invoking APIs across all resources\npackage client\n\nimport (\n\t. \"github.com\/stripe\/stripe-go\"\n\t\"github.com\/stripe\/stripe-go\/account\"\n\t\"github.com\/stripe\/stripe-go\/balance\"\n\t\"github.com\/stripe\/stripe-go\/bankaccount\"\n\t\"github.com\/stripe\/stripe-go\/bitcoinreceiver\"\n\t\"github.com\/stripe\/stripe-go\/bitcointransaction\"\n\t\"github.com\/stripe\/stripe-go\/card\"\n\t\"github.com\/stripe\/stripe-go\/charge\"\n\t\"github.com\/stripe\/stripe-go\/countryspec\"\n\t\"github.com\/stripe\/stripe-go\/coupon\"\n\t\"github.com\/stripe\/stripe-go\/customer\"\n\t\"github.com\/stripe\/stripe-go\/discount\"\n\t\"github.com\/stripe\/stripe-go\/dispute\"\n\t\"github.com\/stripe\/stripe-go\/ephemeralkey\"\n\t\"github.com\/stripe\/stripe-go\/event\"\n\t\"github.com\/stripe\/stripe-go\/exchangerate\"\n\t\"github.com\/stripe\/stripe-go\/fee\"\n\t\"github.com\/stripe\/stripe-go\/feerefund\"\n\t\"github.com\/stripe\/stripe-go\/fileupload\"\n\t\"github.com\/stripe\/stripe-go\/invoice\"\n\t\"github.com\/stripe\/stripe-go\/invoiceitem\"\n\t\"github.com\/stripe\/stripe-go\/loginlink\"\n\t\"github.com\/stripe\/stripe-go\/order\"\n\t\"github.com\/stripe\/stripe-go\/orderreturn\"\n\t\"github.com\/stripe\/stripe-go\/paymentsource\"\n\t\"github.com\/stripe\/stripe-go\/payout\"\n\t\"github.com\/stripe\/stripe-go\/plan\"\n\t\"github.com\/stripe\/stripe-go\/product\"\n\t\"github.com\/stripe\/stripe-go\/recipient\"\n\t\"github.com\/stripe\/stripe-go\/refund\"\n\t\"github.com\/stripe\/stripe-go\/reversal\"\n\t\"github.com\/stripe\/stripe-go\/sku\"\n\t\"github.com\/stripe\/stripe-go\/source\"\n\t\"github.com\/stripe\/stripe-go\/sub\"\n\t\"github.com\/stripe\/stripe-go\/subitem\"\n\t\"github.com\/stripe\/stripe-go\/token\"\n\t\"github.com\/stripe\/stripe-go\/transfer\"\n)\n\n\/\/ API is the Stripe client. It contains all the different resources available.\ntype API struct {\n\t\/\/ Account is the client used to invoke \/accounts APIs.\n\tAccount *account.Client\n\t\/\/ Balance is the client used to invoke \/balance and transaction-related APIs.\n\tBalance *balance.Client\n\t\/\/ BankAccounts is the client used to invoke bank account related APIs.\n\tBankAccounts *bankaccount.Client\n\t\/\/ BitcoinReceivers is the client used to invoke \/bitcoin\/receivers APIs.\n\tBitcoinReceivers *bitcoinreceiver.Client\n\t\/\/ BitcoinTransactions is the client used to invoke \/bitcoin\/transactions APIs.\n\tBitcoinTransactions *bitcointransaction.Client\n\t\/\/ Cards is the client used to invoke card related APIs.\n\tCards *card.Client\n\t\/\/ Charges is the client used to invoke \/charges APIs.\n\tCharges *charge.Client\n\t\/\/ CountrySpec is the client used to invoke \/country_specs APIs.\n\tCountrySpec *countryspec.Client\n\t\/\/ Coupons is the client used to invoke \/coupons APIs.\n\tCoupons *coupon.Client\n\t\/\/ Customers is the client used to invoke \/customers APIs.\n\tCustomers *customer.Client\n\t\/\/ Discounts is the client used to invoke discount related APIs.\n\tDiscounts *discount.Client\n\t\/\/ Disputes is the client used to invoke \/disputes APIs.\n\tDisputes *dispute.Client\n\t\/\/ EphemeralKeys is the client used to invoke \/ephemeral_keys APIs.\n\tEphemeralKeys *ephemeralkey.Client\n\t\/\/ Events is the client used to invoke \/events APIs.\n\tEvents *event.Client\n\t\/\/ ExchangeRates is the client used to invoke \/exchange_rates APIs.\n\tExchangeRates *exchangerate.Client\n\t\/\/ Fees is the client used to invoke \/application_fees APIs.\n\tFees *fee.Client\n\t\/\/ FeeRefunds is the client used to invoke \/application_fees\/refunds APIs.\n\tFeeRefunds *feerefund.Client\n\t\/\/ FileUploads is the client used to invoke the \/files APIs.\n\tFileUploads *fileupload.Client\n\t\/\/ Invoices is the client used to invoke \/invoices APIs.\n\tInvoices *invoice.Client\n\t\/\/ InvoiceItems is the client used to invoke \/invoiceitems APIs.\n\tInvoiceItems *invoiceitem.Client\n\t\/\/ LoginLinks is the client used to invoke login link related APIs.\n\tLoginLinks *loginlink.Client\n\t\/\/ Orders is the client used to invoke \/orders APIs.\n\tOrders *order.Client\n\t\/\/ OrderReturns is the client used to invoke \/order_returns APIs.\n\tOrderReturns *orderreturn.Client\n\t\/\/ PaymentSource is used to invoke customer sources related APIs.\n\tPaymentSource *paymentsource.Client\n\t\/\/ Payouts is the client used to invoke \/payouts APIs.\n\tPayouts *payout.Client\n\t\/\/ Plans is the client used to invoke \/plans APIs.\n\tPlans *plan.Client\n\t\/\/ Products is the client used to invoke \/products APIs.\n\tProducts *product.Client\n\t\/\/ Recipients is the client used to invoke \/recipients APIs.\n\tRecipients *recipient.Client\n\t\/\/ Refunds is the client used to invoke \/refunds APIs.\n\tRefunds *refund.Client\n\t\/\/ Reversals is the client used to invoke \/transfers\/reversals APIs.\n\tReversals *reversal.Client\n\t\/\/ Skus is the client used to invoke \/skus APIs.\n\tSkus *sku.Client\n\t\/\/ Sources is the client used to invoke \/sources APIs.\n\tSources *source.Client\n\t\/\/ Subscriptions is the client used to invoke \/subscriptions APIs.\n\tSubscriptions *sub.Client\n\t\/\/ SubscriptionItems is the client used to invoke subscription's items related APIs.\n\tSubscriptionItems *subitem.Client\n\t\/\/ Tokens is the client used to invoke \/tokens APIs.\n\tTokens *token.Client\n\t\/\/ Transfers is the client used to invoke \/transfers APIs.\n\tTransfers *transfer.Client\n}\n\n\/\/ Init initializes the Stripe client with the appropriate secret key\n\/\/ as well as providing the ability to override the backend as needed.\nfunc (a *API) Init(key string, backends *Backends) {\n\tif backends == nil {\n\t\tbackends = &Backends{API: GetBackend(APIBackend), Uploads: GetBackend(UploadsBackend)}\n\t}\n\n\ta.Account = &account.Client{B: backends.API, Key: key}\n\ta.Balance = &balance.Client{B: backends.API, Key: key}\n\ta.BankAccounts = &bankaccount.Client{B: backends.API, Key: key}\n\ta.BitcoinReceivers = &bitcoinreceiver.Client{B: backends.API, Key: key}\n\ta.BitcoinTransactions = &bitcointransaction.Client{B: backends.API, Key: key}\n\ta.Cards = &card.Client{B: backends.API, Key: key}\n\ta.Charges = &charge.Client{B: backends.API, Key: key}\n\ta.CountrySpec = &countryspec.Client{B: backends.API, Key: key}\n\ta.Coupons = &coupon.Client{B: backends.API, Key: key}\n\ta.Customers = &customer.Client{B: backends.API, Key: key}\n\ta.Discounts = &discount.Client{B: backends.API, Key: key}\n\ta.Disputes = &dispute.Client{B: backends.API, Key: key}\n\ta.EphemeralKeys = &ephemeralkey.Client{B: backends.API, Key: key}\n\ta.ExchangeRates = &exchangerate.Client{B: backends.API, Key: key}\n\ta.Events = &event.Client{B: backends.API, Key: key}\n\ta.Fees = &fee.Client{B: backends.API, Key: key}\n\ta.FeeRefunds = &feerefund.Client{B: backends.API, Key: key}\n\ta.FileUploads = &fileupload.Client{B: backends.Uploads, Key: key}\n\ta.Invoices = &invoice.Client{B: backends.API, Key: key}\n\ta.InvoiceItems = &invoiceitem.Client{B: backends.API, Key: key}\n\ta.LoginLinks = &loginlink.Client{B: backends.API, Key: key}\n\ta.Orders = &order.Client{B: backends.API, Key: key}\n\ta.OrderReturns = &orderreturn.Client{B: backends.API, Key: key}\n\ta.PaymentSource = &paymentsource.Client{B: backends.API, Key: key}\n\ta.Payouts = &payout.Client{B: backends.API, Key: key}\n\ta.Plans = &plan.Client{B: backends.API, Key: key}\n\ta.Products = &product.Client{B: backends.API, Key: key}\n\ta.Recipients = &recipient.Client{B: backends.API, Key: key}\n\ta.Refunds = &refund.Client{B: backends.API, Key: key}\n\ta.Reversals = &reversal.Client{B: backends.API, Key: key}\n\ta.Skus = &sku.Client{B: backends.API, Key: key}\n\ta.Sources = &source.Client{B: backends.API, Key: key}\n\ta.Subscriptions = &sub.Client{B: backends.API, Key: key}\n\ta.SubscriptionItems = &subitem.Client{B: backends.API, Key: key}\n\ta.Tokens = &token.Client{B: backends.API, Key: key}\n\ta.Transfers = &transfer.Client{B: backends.API, Key: key}\n}\n\n\/\/ New creates a new Stripe client with the appropriate secret key\n\/\/ as well as providing the ability to override the backends as needed.\nfunc New(key string, backends *Backends) *API {\n\tapi := API{}\n\tapi.Init(key, backends)\n\treturn &api\n}\n<|endoftext|>"}
{"text":"<commit_before>package fate\n\nimport \"sort\"\n\n\/\/ tokset maintains a set of tokens as a sorted slice of integers.\n\/\/\n\/\/ 1-byte tokens (<= 0xFF) are in buf[0:c1]\n\/\/ 2-byte tokens (<= 0xFFFF) are in buf[c1:c1+2*c2]\n\/\/ 3-byte tokens (<= 0xFFFFFF) are in buf[c1+2*c2:]\n\/\/\n\/\/ They're stored little-endian. Adds are O(log N). Choosing a random\n\/\/ token in the set is O(1).\n\/\/\n\/\/ tokens greater than 0xFFFFFF are not currently supported. This is\n\/\/ enough token space to handle the Web 1T corpus.\ntype tokset struct {\n\tbuf []byte\n\n\t\/\/ count of 2-byte tokens, count of 1-byte tokens\n\tc2 uint16\n\tc1 uint8\n}\n\nfunc (t *tokset) Add(tok token) bool {\n\tswitch {\n\tcase tok <= 0xFF:\n\t\tif len(t.buf) == 0 {\n\t\t\tt.buf = append(t.buf, byte(tok))\n\t\t\tt.c1++\n\t\t\treturn false\n\t\t}\n\n\t\treturn t.add1(tok)\n\tcase tok <= 0xFFFF:\n\t\tif len(t.buf) == 0 {\n\t\t\tt.buf = append(t.buf, byte(tok), byte(tok>>8))\n\t\t\tt.c2++\n\t\t\treturn false\n\t\t}\n\n\t\treturn t.add2(tok)\n\tcase tok <= 0xFFFFFF:\n\t\tif len(t.buf) == 0 {\n\t\t\tt.buf = append(t.buf, byte(tok), byte(tok>>8), byte(tok>>16))\n\t\t\treturn false\n\t\t}\n\n\t\treturn t.add3(tok)\n\t}\n\n\tpanic(\"oops\")\n}\n\nfunc (t *tokset) span1() []byte {\n\treturn t.buf[0:t.c1]\n}\n\nfunc (t *tokset) span2() []byte {\n\treturn t.buf[int(t.c1) : int(t.c1)+2*int(t.c2)]\n}\n\nfunc (t *tokset) span3() []byte {\n\treturn t.buf[int(t.c1)+2*int(t.c2):]\n}\n\nfunc (t *tokset) add1(tok token) bool {\n\tspan := t.span1()\n\tloc := sort.Search(len(span), func(i int) bool {\n\t\treturn token(span[i]) >= tok\n\t})\n\n\tif loc < len(span) && token(span[loc]) == tok {\n\t\treturn true\n\t}\n\n\tt.buf = append(t.buf, 0)\n\tcopy(t.buf[loc+1:], t.buf[loc:])\n\tt.buf[loc] = byte(tok)\n\n\tt.c1++\n\n\treturn false\n}\n\nfunc (t *tokset) add2(tok token) bool {\n\tspan := t.span2()\n\tidx := sort.Search(len(span)\/2, func(i int) bool {\n\t\treturn unpack2(span[2*i:]) >= tok\n\t})\n\n\tif idx < len(span)\/2 && unpack2(span[2*idx:]) == tok {\n\t\treturn true\n\t}\n\n\tt.buf = append(t.buf, 0, 0)\n\n\tloc := int(t.c1) + 2*idx\n\tcopy(t.buf[loc+2:], t.buf[loc:])\n\tput2(t.buf[loc:], tok)\n\n\tt.c2++\n\n\treturn false\n}\nfunc (t *tokset) add3(tok token) bool {\n\tspan := t.span3()\n\tidx := sort.Search(len(span)\/3, func(i int) bool {\n\t\treturn unpack3(span[3*i:]) >= tok\n\t})\n\n\tif idx < len(span)\/3 && unpack3(span[3*idx:]) == tok {\n\t\treturn true\n\t}\n\n\tt.buf = append(t.buf, 0, 0, 0)\n\n\tloc := int(t.c1) + 2*int(t.c2) + 3*idx\n\tcopy(t.buf[loc+3:], t.buf[loc:])\n\tput3(t.buf[loc:], tok)\n\n\treturn false\n}\n\nfunc (t *tokset) Len() int {\n\tif t == nil {\n\t\treturn 0\n\t}\n\n\treturn int(t.c1) + int(t.c2) + len(t.span3())\/3\n}\n\nfunc (t *tokset) Tokens() []token {\n\tif t == nil {\n\t\treturn nil\n\t}\n\n\tvar tokens = make([]token, 0, t.Len())\n\tfor _, val := range t.span1() {\n\t\ttokens = append(tokens, token(val))\n\t}\n\n\tspan2 := t.span2()\n\tfor i := 0; i < len(span2); i += 2 {\n\t\ttokens = append(tokens, unpack2(span2[i:]))\n\t}\n\n\tspan3 := t.span3()\n\tfor i := 0; i < len(span3); i += 3 {\n\t\ttokens = append(tokens, unpack3(span3[i:]))\n\t}\n\n\treturn tokens\n}\n\nfunc put2(buf []byte, tok token) {\n\tbuf[0] = byte(tok)\n\tbuf[1] = byte(tok >> 8)\n}\n\nfunc put3(buf []byte, tok token) {\n\tbuf[0] = byte(tok)\n\tbuf[1] = byte(tok >> 8)\n\tbuf[2] = byte(tok >> 16)\n}\n\nfunc unpack2(buf []byte) token {\n\treturn token(buf[0]) | token(buf[1])<<8\n}\n\nfunc unpack3(buf []byte) token {\n\treturn token(buf[0]) | token(buf[1])<<8 | token(buf[2])<<16\n}\n\nfunc (t tokset) Choice(r Intn) token {\n\tindex := r.Intn(t.Len())\n\n\tswitch {\n\tcase index < int(t.c1):\n\t\treturn token(t.buf[index])\n\tcase index < int(t.c1)+int(t.c2):\n\t\tspan := t.span2()\n\t\treturn unpack2(span[2*(index-int(t.c1)):])\n\tcase index < t.Len():\n\t\tspan := t.span3()\n\t\treturn unpack3(span[3*(index-(int(t.c2)+int(t.c1))):])\n\t}\n\n\tpanic(\"oops\")\n}\n\n\/\/ tokset2 stores constant width tokens in a sorted slice.\ntype tokset2 struct {\n\tt []token\n}\n\n\/\/ Add inserts tok into this set, if not already present. It may\n\/\/ return a new slice, so use its return value as the new set.\n\/\/\n\/\/ Returns a bool signaling whether the token was already in the set\n\/\/ (similar logic to map lookups).\nfunc (t *tokset2) Add(tok token) bool {\n\tsize := len(t.t)\n\n\t\/\/ Fast path for empty sets or brand new tokens.\n\tif size == 0 || tok > t.t[size-1] {\n\t\tt.t = append(t.t, tok)\n\t\treturn false\n\t}\n\n\tloc := sort.Search(size, func(i int) bool { return t.t[i] >= tok })\n\tif t.t[loc] == tok {\n\t\treturn true\n\t}\n\n\tt.t = append(t.t, 0)\n\tcopy(t.t[loc+1:], t.t[loc:])\n\tt.t[loc] = tok\n\n\treturn false\n}\n\nfunc (t *tokset2) Tokens() []token {\n\tif t == nil {\n\t\treturn nil\n\t}\n\n\treturn t.t\n}\n<commit_msg>Move the tokset empty array special cases into add1\/add2\/add3<commit_after>package fate\n\nimport \"sort\"\n\n\/\/ tokset maintains a set of tokens as a sorted slice of integers.\n\/\/\n\/\/ 1-byte tokens (<= 0xFF) are in buf[0:c1]\n\/\/ 2-byte tokens (<= 0xFFFF) are in buf[c1:c1+2*c2]\n\/\/ 3-byte tokens (<= 0xFFFFFF) are in buf[c1+2*c2:]\n\/\/\n\/\/ They're stored little-endian. Adds are O(log N). Choosing a random\n\/\/ token in the set is O(1).\n\/\/\n\/\/ tokens greater than 0xFFFFFF are not currently supported. This is\n\/\/ enough token space to handle the Web 1T corpus.\ntype tokset struct {\n\tbuf []byte\n\n\t\/\/ count of 2-byte tokens, count of 1-byte tokens\n\tc2 uint16\n\tc1 uint8\n}\n\nfunc (t *tokset) Add(tok token) bool {\n\tswitch {\n\tcase tok <= 0xFF:\n\t\treturn t.add1(tok)\n\tcase tok <= 0xFFFF:\n\t\treturn t.add2(tok)\n\tcase tok <= 0xFFFFFF:\n\t\treturn t.add3(tok)\n\t}\n\n\tpanic(\"oops\")\n}\n\nfunc (t *tokset) span1() []byte {\n\treturn t.buf[0:t.c1]\n}\n\nfunc (t *tokset) span2() []byte {\n\treturn t.buf[int(t.c1) : int(t.c1)+2*int(t.c2)]\n}\n\nfunc (t *tokset) span3() []byte {\n\treturn t.buf[int(t.c1)+2*int(t.c2):]\n}\n\nfunc (t *tokset) add1(tok token) bool {\n\tif len(t.buf) == 0 {\n\t\tt.buf = append(t.buf, byte(tok))\n\t\tt.c1++\n\t\treturn false\n\t}\n\n\tspan := t.span1()\n\tloc := sort.Search(len(span), func(i int) bool {\n\t\treturn token(span[i]) >= tok\n\t})\n\n\tif loc < len(span) && token(span[loc]) == tok {\n\t\treturn true\n\t}\n\n\tt.buf = append(t.buf, 0)\n\tcopy(t.buf[loc+1:], t.buf[loc:])\n\tt.buf[loc] = byte(tok)\n\n\tt.c1++\n\n\treturn false\n}\n\nfunc (t *tokset) add2(tok token) bool {\n\tif len(t.buf) == 0 {\n\t\tt.buf = append(t.buf, byte(tok), byte(tok>>8))\n\t\tt.c2++\n\t\treturn false\n\t}\n\n\tspan := t.span2()\n\tidx := sort.Search(len(span)\/2, func(i int) bool {\n\t\treturn unpack2(span[2*i:]) >= tok\n\t})\n\n\tif idx < len(span)\/2 && unpack2(span[2*idx:]) == tok {\n\t\treturn true\n\t}\n\n\tt.buf = append(t.buf, 0, 0)\n\n\tloc := int(t.c1) + 2*idx\n\tcopy(t.buf[loc+2:], t.buf[loc:])\n\tput2(t.buf[loc:], tok)\n\n\tt.c2++\n\n\treturn false\n}\nfunc (t *tokset) add3(tok token) bool {\n\tif len(t.buf) == 0 {\n\t\tt.buf = append(t.buf, byte(tok), byte(tok>>8), byte(tok>>16))\n\t\treturn false\n\t}\n\n\tspan := t.span3()\n\tidx := sort.Search(len(span)\/3, func(i int) bool {\n\t\treturn unpack3(span[3*i:]) >= tok\n\t})\n\n\tif idx < len(span)\/3 && unpack3(span[3*idx:]) == tok {\n\t\treturn true\n\t}\n\n\tt.buf = append(t.buf, 0, 0, 0)\n\n\tloc := int(t.c1) + 2*int(t.c2) + 3*idx\n\tcopy(t.buf[loc+3:], t.buf[loc:])\n\tput3(t.buf[loc:], tok)\n\n\treturn false\n}\n\nfunc (t *tokset) Len() int {\n\tif t == nil {\n\t\treturn 0\n\t}\n\n\treturn int(t.c1) + int(t.c2) + len(t.span3())\/3\n}\n\nfunc (t *tokset) Tokens() []token {\n\tif t == nil {\n\t\treturn nil\n\t}\n\n\tvar tokens = make([]token, 0, t.Len())\n\tfor _, val := range t.span1() {\n\t\ttokens = append(tokens, token(val))\n\t}\n\n\tspan2 := t.span2()\n\tfor i := 0; i < len(span2); i += 2 {\n\t\ttokens = append(tokens, unpack2(span2[i:]))\n\t}\n\n\tspan3 := t.span3()\n\tfor i := 0; i < len(span3); i += 3 {\n\t\ttokens = append(tokens, unpack3(span3[i:]))\n\t}\n\n\treturn tokens\n}\n\nfunc put2(buf []byte, tok token) {\n\tbuf[0] = byte(tok)\n\tbuf[1] = byte(tok >> 8)\n}\n\nfunc put3(buf []byte, tok token) {\n\tbuf[0] = byte(tok)\n\tbuf[1] = byte(tok >> 8)\n\tbuf[2] = byte(tok >> 16)\n}\n\nfunc unpack2(buf []byte) token {\n\treturn token(buf[0]) | token(buf[1])<<8\n}\n\nfunc unpack3(buf []byte) token {\n\treturn token(buf[0]) | token(buf[1])<<8 | token(buf[2])<<16\n}\n\nfunc (t tokset) Choice(r Intn) token {\n\tindex := r.Intn(t.Len())\n\n\tswitch {\n\tcase index < int(t.c1):\n\t\treturn token(t.buf[index])\n\tcase index < int(t.c1)+int(t.c2):\n\t\tspan := t.span2()\n\t\treturn unpack2(span[2*(index-int(t.c1)):])\n\tcase index < t.Len():\n\t\tspan := t.span3()\n\t\treturn unpack3(span[3*(index-(int(t.c2)+int(t.c1))):])\n\t}\n\n\tpanic(\"oops\")\n}\n\n\/\/ tokset2 stores constant width tokens in a sorted slice.\ntype tokset2 struct {\n\tt []token\n}\n\n\/\/ Add inserts tok into this set, if not already present. It may\n\/\/ return a new slice, so use its return value as the new set.\n\/\/\n\/\/ Returns a bool signaling whether the token was already in the set\n\/\/ (similar logic to map lookups).\nfunc (t *tokset2) Add(tok token) bool {\n\tsize := len(t.t)\n\n\t\/\/ Fast path for empty sets or brand new tokens.\n\tif size == 0 || tok > t.t[size-1] {\n\t\tt.t = append(t.t, tok)\n\t\treturn false\n\t}\n\n\tloc := sort.Search(size, func(i int) bool { return t.t[i] >= tok })\n\tif t.t[loc] == tok {\n\t\treturn true\n\t}\n\n\tt.t = append(t.t, 0)\n\tcopy(t.t[loc+1:], t.t[loc:])\n\tt.t[loc] = tok\n\n\treturn false\n}\n\nfunc (t *tokset2) Tokens() []token {\n\tif t == nil {\n\t\treturn nil\n\t}\n\n\treturn t.t\n}\n<|endoftext|>"}
{"text":"<commit_before>package tparse\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n)\n\n\/\/ Parse will return the time value corresponding to the specified layout and value.  It also parses\n\/\/ floating point and integer epoch values.\nfunc Parse(layout, value string) (time.Time, error) {\n\treturn ParseWithMap(layout, value, make(map[string]time.Time))\n}\n\n\/\/ ParseNow will return the time value corresponding to the specified layout and value.  It also\n\/\/ parses floating point and integer epoch values.  It recognizes the special string `now` and\n\/\/ replaces that with the time ParseNow is called.  This allows a suffix adding or subtracting\n\/\/ various values from the base time.  For instance, ParseNow(time.ANSIC, \"now+1d\") will return a\n\/\/ time corresponding to 24 hours from the moment the function is invoked.\n\/\/\n\/\/ In addition to the duration abbreviations recognized by time.ParseDuration, it recognizes various\n\/\/ tokens for days, weeks, months, and years.\n\/\/\n\/\/\tpackage main\n\/\/\n\/\/\timport (\n\/\/\t\t\"fmt\"\n\/\/\t\t\"os\"\n\/\/\t\t\"time\"\n\/\/\n\/\/\t\ttparse \"gopkg.in\/karrick\/tparse.v2\"\n\/\/\t)\n\/\/\n\/\/\tfunc main() {\n\/\/\t\tactual, err := tparse.ParseNow(time.RFC3339, \"now+1d3w4mo7y6h4m\")\n\/\/\t\tif err != nil {\n\/\/\t\t\tfmt.Fprintf(os.Stderr, \"error: %s\\n\", err)\n\/\/\t\t\tos.Exit(1)\n\/\/\t\t}\n\/\/\n\/\/\t\tfmt.Printf(\"time is: %s\\n\", actual)\n\/\/\t}\nfunc ParseNow(layout, value string) (time.Time, error) {\n\tm := map[string]time.Time{\"now\": time.Now()}\n\treturn ParseWithMap(layout, value, m)\n}\n\n\/\/ ParseWithMap will return the time value corresponding to the specified layout and value.  It also\n\/\/ parses floating point and integer epoch values.  It accepts a map of strings to time.Time values,\n\/\/ and if the value string starts with one of the keys in the map, it replaces the string with the\n\/\/ corresponding time.Time value.\n\/\/\n\/\/\tpackage main\n\/\/\n\/\/\timport (\n\/\/\t\t\"fmt\"\n\/\/\t\t\"os\"\n\/\/\t\t\"time\"\n\/\/\n\/\/\t\ttparse \"gopkg.in\/karrick\/tparse.v2\"\n\/\/\t)\n\/\/\n\/\/\tfunc main() {\n\/\/\t\tm := make(map[string]time.Time)\n\/\/\t\tm[\"start\"] = start\n\/\/\n\/\/\t\tend, err := tparse.ParseWithMap(time.RFC3339, \"start+8h\", m)\n\/\/\t\tif err != nil {\n\/\/\t\t\tfmt.Fprintf(os.Stderr, \"error: %s\\n\", err)\n\/\/\t\t\tos.Exit(1)\n\/\/\t\t}\n\/\/\n\/\/\t\tfmt.Printf(\"start: %s; end: %s\\n\", start, end)\n\/\/\t}\nfunc ParseWithMap(layout, value string, dict map[string]time.Time) (time.Time, error) {\n\tif epoch, err := strconv.ParseFloat(value, 64); err == nil && epoch >= 0 {\n\t\ttrunc := math.Trunc(epoch)\n\t\tnanos := fractionToNanos(epoch - trunc)\n\t\treturn time.Unix(int64(trunc), int64(nanos)), nil\n\t}\n\n\tvar matchKey []byte\n\tvar matchTime time.Time\n\t\/\/ find longest matching key in dict\n\tfor k, v := range dict {\n\t\tif strings.HasPrefix(value, k) && len(k) > len(matchKey) {\n\t\t\tmatchKey = []byte(k)\n\t\t\tmatchTime = v\n\t\t}\n\t}\n\tif len(matchKey) > 0 {\n\t\treturn addDuration(matchTime, value[len(matchKey):])\n\t}\n\treturn time.Parse(layout, value)\n}\n\nfunc fractionToNanos(fraction float64) int64 {\n\treturn int64(fraction * float64(time.Second\/time.Nanosecond))\n}\n\n\/\/ on err, returns epoch and error\nfunc addDuration(base time.Time, value string) (time.Time, error) {\n\tif len(value) == 0 {\n\t\treturn base, nil\n\t}\n\tvar epoch time.Time\n\tvar ty, tm, td int\n\tvar tdur time.Duration\n\tvar identifier, setComplete bool\n\tpositive := true\n\tvar iUnit, iNumber int\n\tvar startNumberNextRune bool\n\n\tfor i, rune := range value {\n\t\tif startNumberNextRune {\n\t\t\tiNumber = i\n\t\t\tstartNumberNextRune = false\n\t\t}\n\t\t\/\/ [+-][0-9]+[^-+0-9]+\n\t\tif identifier {\n\t\t\tswitch {\n\t\t\tcase rune == '+', rune == '-':\n\t\t\t\tidentifier = false\n\t\t\t\tsetComplete = true\n\t\t\t\tstartNumberNextRune = true\n\t\t\tcase unicode.IsDigit(rune):\n\t\t\t\tidentifier = false\n\t\t\t\tsetComplete = true\n\t\t\t}\n\t\t\tif setComplete {\n\t\t\t\tif i > 0 {\n\t\t\t\t\t\/\/ we should have all we need for previous set\n\t\t\t\t\ty, m, d, dur, err := bar(value, positive, iNumber, iUnit, i)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn epoch, err\n\t\t\t\t\t}\n\t\t\t\t\tty += y\n\t\t\t\t\ttm += m\n\t\t\t\t\ttd += d\n\t\t\t\t\ttdur += dur\n\t\t\t\t\tiNumber = i\n\t\t\t\t}\n\t\t\t\tsetComplete = false\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase rune == '+':\n\t\t\t\tpositive = true\n\t\t\tcase rune == '-':\n\t\t\t\tpositive = false\n\t\t\t}\n\t\t} else { \/\/ number\n\t\t\tswitch {\n\t\t\tcase rune == '+':\n\t\t\t\tpositive = true\n\t\t\t\tstartNumberNextRune = true\n\t\t\tcase rune == '-':\n\t\t\t\tpositive = false\n\t\t\t\tstartNumberNextRune = true\n\t\t\tcase unicode.IsDigit(rune):\n\t\t\t\t\/\/ nop\n\t\t\tdefault:\n\t\t\t\tidentifier = true\n\t\t\t\tiUnit = i\n\t\t\t}\n\t\t}\n\t}\n\n\tif iNumber < iUnit && iUnit < len(value) {\n\t\ty, m, d, dur, err := bar(value, positive, iNumber, iUnit, len(value))\n\t\tif err != nil {\n\t\t\treturn epoch, err\n\t\t}\n\t\tty += y\n\t\ttm += m\n\t\ttd += d\n\t\ttdur += dur\n\t} else {\n\t\treturn epoch, fmt.Errorf(\"extra characters: %s\", value[iNumber:])\n\t}\n\treturn base.Add(tdur).AddDate(ty, tm, td), nil\n}\n\nfunc bar(value string, positive bool, iNumber, iUnit, i int) (int, int, int, time.Duration, error) {\n\tnumber := value[iNumber:iUnit]\n\tunit := value[iUnit:i]\n\treturn calcDuration(positive, number, unit)\n}\n\nfunc calcDuration(positive bool, number, unit string) (int, int, int, time.Duration, error) {\n\tvalue, err := strconv.Atoi(number)\n\tif err != nil {\n\t\treturn 0, 0, 0, 0, err\n\t}\n\n\tvar y, m, d int\n\tvar duration time.Duration\n\n\t\/\/ NOTE: compare byte slices because some units, i.e. ms, are multi-rune\n\tswitch {\n\tcase bytes.Equal([]byte(unit), []byte(\"d\")) || bytes.Equal([]byte(unit), []byte(\"day\")) || bytes.Equal([]byte(unit), []byte(\"days\")):\n\t\td = value\n\tcase bytes.Equal([]byte(unit), []byte(\"w\")) || bytes.Equal([]byte(unit), []byte(\"week\")) || bytes.Equal([]byte(unit), []byte(\"weeks\")):\n\t\td = 7 * value\n\tcase bytes.Equal([]byte(unit), []byte(\"mo\")) || bytes.Equal([]byte(unit), []byte(\"mon\")) || bytes.Equal([]byte(unit), []byte(\"month\")) || bytes.Equal([]byte(unit), []byte(\"months\")) || bytes.Equal([]byte(unit), []byte(\"mth\")) || bytes.Equal([]byte(unit), []byte(\"mn\")):\n\t\tm = value\n\tcase bytes.Equal([]byte(unit), []byte(\"y\")) || bytes.Equal([]byte(unit), []byte(\"year\")) || bytes.Equal([]byte(unit), []byte(\"years\")):\n\t\ty = value\n\tcase bytes.Equal([]byte(unit), []byte(\"sec\")) || bytes.Equal([]byte(unit), []byte(\"second\")) || bytes.Equal([]byte(unit), []byte(\"seconds\")):\n\t\tduration = time.Duration(value) * time.Second\n\tcase bytes.Equal([]byte(unit), []byte(\"min\")) || bytes.Equal([]byte(unit), []byte(\"minute\")) || bytes.Equal([]byte(unit), []byte(\"minutes\")):\n\t\tduration = time.Duration(value) * time.Minute\n\tcase bytes.Equal([]byte(unit), []byte(\"hr\")) || bytes.Equal([]byte(unit), []byte(\"hour\")) || bytes.Equal([]byte(unit), []byte(\"hours\")):\n\t\tduration = time.Duration(value) * time.Hour\n\n\tdefault:\n\t\tduration, err = time.ParseDuration(number + unit)\n\t}\n\tif !positive {\n\t\ty = -y\n\t\tm = -m\n\t\td = -d\n\t\tduration = -duration\n\t}\n\treturn y, m, d, duration, nil\n}\n<commit_msg>faster performance<commit_after>package tparse\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n)\n\n\/\/ Parse will return the time value corresponding to the specified layout and value.  It also parses\n\/\/ floating point and integer epoch values.\nfunc Parse(layout, value string) (time.Time, error) {\n\treturn ParseWithMap(layout, value, make(map[string]time.Time))\n}\n\n\/\/ ParseNow will return the time value corresponding to the specified layout and value.  It also\n\/\/ parses floating point and integer epoch values.  It recognizes the special string `now` and\n\/\/ replaces that with the time ParseNow is called.  This allows a suffix adding or subtracting\n\/\/ various values from the base time.  For instance, ParseNow(time.ANSIC, \"now+1d\") will return a\n\/\/ time corresponding to 24 hours from the moment the function is invoked.\n\/\/\n\/\/ In addition to the duration abbreviations recognized by time.ParseDuration, it recognizes various\n\/\/ tokens for days, weeks, months, and years.\n\/\/\n\/\/\tpackage main\n\/\/\n\/\/\timport (\n\/\/\t\t\"fmt\"\n\/\/\t\t\"os\"\n\/\/\t\t\"time\"\n\/\/\n\/\/\t\ttparse \"gopkg.in\/karrick\/tparse.v2\"\n\/\/\t)\n\/\/\n\/\/\tfunc main() {\n\/\/\t\tactual, err := tparse.ParseNow(time.RFC3339, \"now+1d3w4mo7y6h4m\")\n\/\/\t\tif err != nil {\n\/\/\t\t\tfmt.Fprintf(os.Stderr, \"error: %s\\n\", err)\n\/\/\t\t\tos.Exit(1)\n\/\/\t\t}\n\/\/\n\/\/\t\tfmt.Printf(\"time is: %s\\n\", actual)\n\/\/\t}\nfunc ParseNow(layout, value string) (time.Time, error) {\n\tm := map[string]time.Time{\"now\": time.Now()}\n\treturn ParseWithMap(layout, value, m)\n}\n\n\/\/ ParseWithMap will return the time value corresponding to the specified layout and value.  It also\n\/\/ parses floating point and integer epoch values.  It accepts a map of strings to time.Time values,\n\/\/ and if the value string starts with one of the keys in the map, it replaces the string with the\n\/\/ corresponding time.Time value.\n\/\/\n\/\/\tpackage main\n\/\/\n\/\/\timport (\n\/\/\t\t\"fmt\"\n\/\/\t\t\"os\"\n\/\/\t\t\"time\"\n\/\/\n\/\/\t\ttparse \"gopkg.in\/karrick\/tparse.v2\"\n\/\/\t)\n\/\/\n\/\/\tfunc main() {\n\/\/\t\tm := make(map[string]time.Time)\n\/\/\t\tm[\"start\"] = start\n\/\/\n\/\/\t\tend, err := tparse.ParseWithMap(time.RFC3339, \"start+8h\", m)\n\/\/\t\tif err != nil {\n\/\/\t\t\tfmt.Fprintf(os.Stderr, \"error: %s\\n\", err)\n\/\/\t\t\tos.Exit(1)\n\/\/\t\t}\n\/\/\n\/\/\t\tfmt.Printf(\"start: %s; end: %s\\n\", start, end)\n\/\/\t}\nfunc ParseWithMap(layout, value string, dict map[string]time.Time) (time.Time, error) {\n\tif epoch, err := strconv.ParseFloat(value, 64); err == nil && epoch >= 0 {\n\t\ttrunc := math.Trunc(epoch)\n\t\tnanos := fractionToNanos(epoch - trunc)\n\t\treturn time.Unix(int64(trunc), int64(nanos)), nil\n\t}\n\n\tvar matchKey []byte\n\tvar matchTime time.Time\n\t\/\/ find longest matching key in dict\n\tfor k, v := range dict {\n\t\tif strings.HasPrefix(value, k) && len(k) > len(matchKey) {\n\t\t\tmatchKey = []byte(k)\n\t\t\tmatchTime = v\n\t\t}\n\t}\n\tif len(matchKey) > 0 {\n\t\treturn addDuration(matchTime, value[len(matchKey):])\n\t}\n\treturn time.Parse(layout, value)\n}\n\nfunc fractionToNanos(fraction float64) int64 {\n\treturn int64(fraction * float64(time.Second\/time.Nanosecond))\n}\n\n\/\/ on err, returns epoch and error\nfunc addDuration(base time.Time, value string) (time.Time, error) {\n\tif len(value) == 0 {\n\t\treturn base, nil\n\t}\n\tvar epoch time.Time\n\tvar ty, tm, td int\n\tvar tdur time.Duration\n\tvar identifier, setComplete bool\n\tpositive := true\n\tvar iUnit, iNumber int\n\tvar startNumberNextRune bool\n\n\tfor i, rune := range value {\n\t\tif startNumberNextRune {\n\t\t\tiNumber = i\n\t\t\tstartNumberNextRune = false\n\t\t}\n\t\t\/\/ [+-][0-9]+[^-+0-9]+\n\t\tif identifier {\n\t\t\tswitch {\n\t\t\tcase rune == '+', rune == '-':\n\t\t\t\tidentifier = false\n\t\t\t\tsetComplete = true\n\t\t\t\tstartNumberNextRune = true\n\t\t\tcase unicode.IsDigit(rune):\n\t\t\t\tidentifier = false\n\t\t\t\tsetComplete = true\n\t\t\t}\n\t\t\tif setComplete {\n\t\t\t\tif i > 0 {\n\t\t\t\t\t\/\/ we should have all we need for previous set\n\t\t\t\t\ty, m, d, dur, err := bar(value, positive, iNumber, iUnit, i)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn epoch, err\n\t\t\t\t\t}\n\t\t\t\t\tty += y\n\t\t\t\t\ttm += m\n\t\t\t\t\ttd += d\n\t\t\t\t\ttdur += dur\n\t\t\t\t\tiNumber = i\n\t\t\t\t}\n\t\t\t\tsetComplete = false\n\t\t\t}\n\t\t\tswitch {\n\t\t\tcase rune == '+':\n\t\t\t\tpositive = true\n\t\t\tcase rune == '-':\n\t\t\t\tpositive = false\n\t\t\t}\n\t\t} else { \/\/ number\n\t\t\tswitch {\n\t\t\tcase rune == '+':\n\t\t\t\tpositive = true\n\t\t\t\tstartNumberNextRune = true\n\t\t\tcase rune == '-':\n\t\t\t\tpositive = false\n\t\t\t\tstartNumberNextRune = true\n\t\t\tcase unicode.IsDigit(rune):\n\t\t\t\t\/\/ nop\n\t\t\tdefault:\n\t\t\t\tidentifier = true\n\t\t\t\tiUnit = i\n\t\t\t}\n\t\t}\n\t}\n\n\tif iNumber < iUnit && iUnit < len(value) {\n\t\ty, m, d, dur, err := bar(value, positive, iNumber, iUnit, len(value))\n\t\tif err != nil {\n\t\t\treturn epoch, err\n\t\t}\n\t\tty += y\n\t\ttm += m\n\t\ttd += d\n\t\ttdur += dur\n\t} else {\n\t\treturn epoch, fmt.Errorf(\"extra characters: %s\", value[iNumber:])\n\t}\n\treturn base.Add(tdur).AddDate(ty, tm, td), nil\n}\n\nfunc bar(value string, positive bool, iNumber, iUnit, i int) (int, int, int, time.Duration, error) {\n\tnumber := value[iNumber:iUnit]\n\tunit := value[iUnit:i]\n\treturn calcDuration(positive, number, unit)\n}\n\nfunc calcDuration(positive bool, number, unit string) (int, int, int, time.Duration, error) {\n\tvalue, err := strconv.Atoi(number)\n\tif err != nil {\n\t\treturn 0, 0, 0, 0, err\n\t}\n\n\tvar y, m, d int\n\tvar duration time.Duration\n\n\t\/\/ NOTE: compare byte slices because some units, i.e. ms, are multi-rune\n\tswitch unit {\n\tcase \"d\", \"day\", \"days\":\n\t\td = value\n\tcase \"w\", \"week\", \"weeks\":\n\t\td = 7 * value\n\tcase \"mo\", \"mon\", \"month\", \"months\", \"mth\", \"mn\":\n\t\tm = value\n\tcase \"y\", \"year\", \"years\":\n\t\ty = value\n\tcase \"sec\", \"second\", \"seconds\":\n\t\tduration = time.Duration(value) * time.Second\n\tcase \"min\", \"minute\", \"minutes\":\n\t\tduration = time.Duration(value) * time.Minute\n\tcase \"hr\", \"hour\", \"hours\":\n\t\tduration = time.Duration(value) * time.Hour\n\tdefault:\n\t\tduration, err = time.ParseDuration(number + unit)\n\t}\n\n\tif !positive {\n\t\ty = -y\n\t\tm = -m\n\t\td = -d\n\t\tduration = -duration\n\t}\n\n\treturn y, m, d, duration, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015-2018 the u-root Authors. All rights reserved\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/u-root\/u-root\/pkg\/golang\"\n\t\"github.com\/u-root\/u-root\/pkg\/shlex\"\n\t\"github.com\/u-root\/u-root\/pkg\/uroot\"\n\t\"github.com\/u-root\/u-root\/pkg\/uroot\/builder\"\n\t\"github.com\/u-root\/u-root\/pkg\/uroot\/initramfs\"\n)\n\n\/\/ multiFlag is used for flags that support multiple invocations, e.g. -files\ntype multiFlag []string\n\nfunc (m *multiFlag) String() string {\n\treturn fmt.Sprint(*m)\n}\n\nfunc (m *multiFlag) Set(value string) error {\n\t*m = append(*m, value)\n\treturn nil\n}\n\n\/\/ Flags for u-root builder.\nvar (\n\tbuild, format, tmpDir, base, outputPath *string\n\tuinitCmd, initCmd                       *string\n\tdefaultShell                            *string\n\tuseExistingInit                         *bool\n\tnoCommands                              *bool\n\textraFiles                              multiFlag\n\tnoStrip                                 *bool\n\tstatsOutputPath                         *string\n\tstatsLabel                              *string\n\tshellbang                               *bool\n)\n\nfunc init() {\n\tvar sh string\n\tswitch golang.Default().GOOS {\n\tcase \"plan9\":\n\t\tsh = \"\"\n\tdefault:\n\t\tsh = \"elvish\"\n\t}\n\n\tbuild = flag.String(\"build\", \"bb\", \"u-root build format (e.g. bb or binary).\")\n\tformat = flag.String(\"format\", \"cpio\", \"Archival format.\")\n\n\ttmpDir = flag.String(\"tmpdir\", \"\", \"Temporary directory to put binaries in.\")\n\n\tbase = flag.String(\"base\", \"\", \"Base archive to add files to. By default, this is a couple of directories like \/bin, \/etc, etc. u-root has a default internally supplied set of files; use base=\/dev\/null if you don't want any base files.\")\n\tuseExistingInit = flag.Bool(\"useinit\", false, \"Use existing init from base archive (only if --base was specified).\")\n\toutputPath = flag.String(\"o\", \"\", \"Path to output initramfs file.\")\n\n\tinitCmd = flag.String(\"initcmd\", \"init\", \"Symlink target for \/init. Can be an absolute path or a u-root command name. Use initcmd=\\\"\\\" if you don't want the symlink.\")\n\tuinitCmd = flag.String(\"uinitcmd\", \"\", \"Symlink target and arguments for \/bin\/uinit. Can be an absolute path or a u-root command name. Use uinitcmd=\\\"\\\" if you don't want the symlink. E.g. -uinitcmd=\\\"echo foobar\\\"\")\n\tdefaultShell = flag.String(\"defaultsh\", sh, \"Default shell. Can be an absolute path or a u-root command name. Use defaultsh=\\\"\\\" if you don't want the symlink.\")\n\n\tnoCommands = flag.Bool(\"nocmd\", false, \"Build no Go commands; initramfs only\")\n\n\tflag.Var(&extraFiles, \"files\", \"Additional files, directories, and binaries (with their ldd dependencies) to add to archive. Can be speficified multiple times.\")\n\n\tnoStrip = flag.Bool(\"no-strip\", false, \"Build unstripped binaries\")\n\tshellbang = flag.Bool(\"shellbang\", false, \"Use #! instead of symlinks for busybox\")\n\n\tstatsOutputPath = flag.String(\"stats-output-path\", \"\", \"Write build stats to this file (JSON)\")\n\n\tstatsLabel = flag.String(\"stats-label\", \"\", \"Use this statsLabel when writing stats\")\n}\n\ntype buildStats struct {\n\tLabel      string  `json:\"label,omitempty\"`\n\tTime       int64   `json:\"time\"`\n\tDuration   float64 `json:\"duration\"`\n\tOutputSize int64   `json:\"output_size\"`\n}\n\nfunc writeBuildStats(stats buildStats, path string) error {\n\tvar allStats []buildStats\n\tif data, err := ioutil.ReadFile(*statsOutputPath); err == nil {\n\t\tjson.Unmarshal(data, &allStats)\n\t}\n\tfound := false\n\tfor i, s := range allStats {\n\t\tif s.Label == stats.Label {\n\t\t\tallStats[i] = stats\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\tallStats = append(allStats, stats)\n\t\tsort.Slice(allStats, func(i, j int) bool {\n\t\t\treturn strings.Compare(allStats[i].Label, allStats[j].Label) == -1\n\t\t})\n\t}\n\tdata, err := json.MarshalIndent(allStats, \"\", \"  \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := ioutil.WriteFile(*statsOutputPath, data, 0644); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc generateLabel() string {\n\tvar baseCmds []string\n\tenv := golang.Default()\n\tif len(flag.Args()) > 0 {\n\t\t\/\/ Use the last component of the name to keep the label short\n\t\tfor _, e := range flag.Args() {\n\t\t\tbaseCmds = append(baseCmds, path.Base(e))\n\t\t}\n\t} else {\n\t\tbaseCmds = []string{\"core\"}\n\t}\n\treturn fmt.Sprintf(\"%s-%s-%s-%s\", *build, env.GOOS, env.GOARCH, strings.Join(baseCmds, \"_\"))\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tstart := time.Now()\n\n\t\/\/ Main is in a separate functions so defers run on return.\n\tif err := Main(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\telapsed := time.Now().Sub(start)\n\n\tstats := buildStats{\n\t\tLabel:    *statsLabel,\n\t\tTime:     start.Unix(),\n\t\tDuration: float64(elapsed.Milliseconds()) \/ 1000,\n\t}\n\tif stats.Label == \"\" {\n\t\tstats.Label = generateLabel()\n\t}\n\tif stat, err := os.Stat(*outputPath); err == nil && stat.ModTime().After(start) {\n\t\tlog.Printf(\"Successfully built %q (size %d).\", *outputPath, stat.Size())\n\t\tstats.OutputSize = stat.Size()\n\t\tif *statsOutputPath != \"\" {\n\t\t\tif err := writeBuildStats(stats, *statsOutputPath); err == nil {\n\t\t\t\tlog.Printf(\"Wrote stats to %q (label %q)\", *statsOutputPath, stats.Label)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Failed to write stats to %s: %v\", *statsOutputPath, err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nvar recommendedVersions = []string{\n\t\"go1.13\",\n\t\"go1.14\",\n\t\"go1.15\",\n\t\"go1.16\",\n}\n\nfunc isRecommendedVersion(v string) bool {\n\tfor _, r := range recommendedVersions {\n\t\tif strings.HasPrefix(v, r) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Main is a separate function so defers are run on return, which they wouldn't\n\/\/ on exit.\nfunc Main() error {\n\tenv := golang.Default()\n\tif env.CgoEnabled {\n\t\tlog.Printf(\"Disabling CGO for u-root...\")\n\t\tenv.CgoEnabled = false\n\t}\n\tlog.Printf(\"Build environment: %s\", env)\n\tif env.GOOS != \"linux\" {\n\t\tlog.Printf(\"GOOS is not linux. Did you mean to set GOOS=linux?\")\n\t}\n\n\tv, err := env.Version()\n\tif err != nil {\n\t\tlog.Printf(\"Could not get environment's Go version, using runtime's version: %v\", err)\n\t\tv = runtime.Version()\n\t}\n\tif !isRecommendedVersion(v) {\n\t\tlog.Printf(`WARNING: You are not using one of the recommended Go versions (have = %s, recommended = %v).\n\t\t\tSome packages may not compile.\n\t\t\tGo to https:\/\/golang.org\/doc\/install to find out how to install a newer version of Go,\n\t\t\tor use https:\/\/godoc.org\/golang.org\/dl\/%s to install an additional version of Go.`,\n\t\t\tv, recommendedVersions, recommendedVersions[0])\n\t}\n\n\tarchiver, err := initramfs.GetArchiver(*format)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger := log.New(os.Stderr, \"\", log.LstdFlags)\n\t\/\/ Open the target initramfs file.\n\tif *outputPath == \"\" {\n\t\tif len(env.GOOS) == 0 && len(env.GOARCH) == 0 {\n\t\t\treturn fmt.Errorf(\"passed no path, GOOS, and GOARCH to CPIOArchiver.OpenWriter\")\n\t\t}\n\t\t*outputPath = fmt.Sprintf(\"\/tmp\/initramfs.%s_%s.cpio\", env.GOOS, env.GOARCH)\n\t}\n\tw, err := archiver.OpenWriter(logger, *outputPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar baseFile initramfs.Reader\n\tif *base != \"\" {\n\t\tbf, err := os.Open(*base)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer bf.Close()\n\t\tbaseFile = archiver.Reader(bf)\n\t} else {\n\t\tbaseFile = uroot.DefaultRamfs().Reader()\n\t}\n\n\ttempDir := *tmpDir\n\tif tempDir == \"\" {\n\t\tvar err error\n\t\ttempDir, err = ioutil.TempDir(\"\", \"u-root\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer os.RemoveAll(tempDir)\n\t} else if _, err := os.Stat(tempDir); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(tempDir, 0755); err != nil {\n\t\t\treturn fmt.Errorf(\"temporary directory %q did not exist; tried to mkdir but failed: %v\", tempDir, err)\n\t\t}\n\t}\n\n\tvar (\n\t\tc           []uroot.Commands\n\t\tinitCommand = *initCmd\n\t)\n\tif !*noCommands {\n\t\tvar b builder.Builder\n\t\tswitch *build {\n\t\tcase \"bb\":\n\t\t\tb = builder.BBBuilder{ShellBang: *shellbang}\n\t\tcase \"binary\":\n\t\t\tb = builder.BinaryBuilder{}\n\t\tcase \"source\":\n\t\t\treturn fmt.Errorf(\"source mode has been deprecated\")\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"could not find builder %q\", *build)\n\t\t}\n\n\t\t\/\/ Resolve globs into package imports.\n\t\t\/\/\n\t\t\/\/ Currently allowed formats:\n\t\t\/\/   Go package imports; e.g. github.com\/u-root\/u-root\/cmds\/ls (must be in $GOPATH)\n\t\t\/\/   Paths to Go package directories; e.g. $GOPATH\/src\/github.com\/u-root\/u-root\/cmds\/*\n\t\tvar pkgs []string\n\t\tfor _, a := range flag.Args() {\n\t\t\tp, ok := templates[a]\n\t\t\tif !ok {\n\t\t\t\tpkgs = append(pkgs, a)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpkgs = append(pkgs, p...)\n\t\t}\n\t\tif len(pkgs) == 0 {\n\t\t\tpkgs = []string{\"github.com\/u-root\/u-root\/cmds\/core\/*\"}\n\t\t}\n\n\t\t\/\/ The command-line tool only allows specifying one build mode\n\t\t\/\/ right now.\n\t\tc = append(c, uroot.Commands{\n\t\t\tBuilder:  b,\n\t\t\tPackages: pkgs,\n\t\t})\n\t}\n\n\topts := uroot.Opts{\n\t\tEnv:             env,\n\t\tCommands:        c,\n\t\tTempDir:         tempDir,\n\t\tExtraFiles:      extraFiles,\n\t\tOutputFile:      w,\n\t\tBaseArchive:     baseFile,\n\t\tUseExistingInit: *useExistingInit,\n\t\tInitCmd:         initCommand,\n\t\tDefaultShell:    *defaultShell,\n\t\tNoStrip:         *noStrip,\n\t}\n\tuinitArgs := shlex.Argv(*uinitCmd)\n\tif len(uinitArgs) > 0 {\n\t\topts.UinitCmd = uinitArgs[0]\n\t}\n\tif len(uinitArgs) > 1 {\n\t\topts.UinitArgs = uinitArgs[1:]\n\t}\n\treturn uroot.CreateInitramfs(logger, opts)\n}\n<commit_msg>Add build tags option to u-root command<commit_after>\/\/ Copyright 2015-2018 the u-root Authors. All rights reserved\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"runtime\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/u-root\/u-root\/pkg\/golang\"\n\t\"github.com\/u-root\/u-root\/pkg\/shlex\"\n\t\"github.com\/u-root\/u-root\/pkg\/uroot\"\n\t\"github.com\/u-root\/u-root\/pkg\/uroot\/builder\"\n\t\"github.com\/u-root\/u-root\/pkg\/uroot\/initramfs\"\n)\n\n\/\/ multiFlag is used for flags that support multiple invocations, e.g. -files\ntype multiFlag []string\n\nfunc (m *multiFlag) String() string {\n\treturn fmt.Sprint(*m)\n}\n\nfunc (m *multiFlag) Set(value string) error {\n\t*m = append(*m, value)\n\treturn nil\n}\n\n\/\/ Flags for u-root builder.\nvar (\n\tbuild, format, tmpDir, base, outputPath *string\n\tuinitCmd, initCmd                       *string\n\tdefaultShell                            *string\n\tuseExistingInit                         *bool\n\tnoCommands                              *bool\n\textraFiles                              multiFlag\n\tnoStrip                                 *bool\n\tstatsOutputPath                         *string\n\tstatsLabel                              *string\n\tshellbang                               *bool\n\ttags                                    *string\n)\n\nfunc init() {\n\tvar sh string\n\tswitch golang.Default().GOOS {\n\tcase \"plan9\":\n\t\tsh = \"\"\n\tdefault:\n\t\tsh = \"elvish\"\n\t}\n\n\tbuild = flag.String(\"build\", \"bb\", \"u-root build format (e.g. bb or binary).\")\n\tformat = flag.String(\"format\", \"cpio\", \"Archival format.\")\n\n\ttmpDir = flag.String(\"tmpdir\", \"\", \"Temporary directory to put binaries in.\")\n\n\tbase = flag.String(\"base\", \"\", \"Base archive to add files to. By default, this is a couple of directories like \/bin, \/etc, etc. u-root has a default internally supplied set of files; use base=\/dev\/null if you don't want any base files.\")\n\tuseExistingInit = flag.Bool(\"useinit\", false, \"Use existing init from base archive (only if --base was specified).\")\n\toutputPath = flag.String(\"o\", \"\", \"Path to output initramfs file.\")\n\n\tinitCmd = flag.String(\"initcmd\", \"init\", \"Symlink target for \/init. Can be an absolute path or a u-root command name. Use initcmd=\\\"\\\" if you don't want the symlink.\")\n\tuinitCmd = flag.String(\"uinitcmd\", \"\", \"Symlink target and arguments for \/bin\/uinit. Can be an absolute path or a u-root command name. Use uinitcmd=\\\"\\\" if you don't want the symlink. E.g. -uinitcmd=\\\"echo foobar\\\"\")\n\tdefaultShell = flag.String(\"defaultsh\", sh, \"Default shell. Can be an absolute path or a u-root command name. Use defaultsh=\\\"\\\" if you don't want the symlink.\")\n\n\tnoCommands = flag.Bool(\"nocmd\", false, \"Build no Go commands; initramfs only\")\n\n\tflag.Var(&extraFiles, \"files\", \"Additional files, directories, and binaries (with their ldd dependencies) to add to archive. Can be speficified multiple times.\")\n\n\tnoStrip = flag.Bool(\"no-strip\", false, \"Build unstripped binaries\")\n\tshellbang = flag.Bool(\"shellbang\", false, \"Use #! instead of symlinks for busybox\")\n\n\tstatsOutputPath = flag.String(\"stats-output-path\", \"\", \"Write build stats to this file (JSON)\")\n\tstatsLabel = flag.String(\"stats-label\", \"\", \"Use this statsLabel when writing stats\")\n\n\ttags = flag.String(\"tags\", \"\", \"Comma separated list of build tags\")\n}\n\ntype buildStats struct {\n\tLabel      string  `json:\"label,omitempty\"`\n\tTime       int64   `json:\"time\"`\n\tDuration   float64 `json:\"duration\"`\n\tOutputSize int64   `json:\"output_size\"`\n}\n\nfunc writeBuildStats(stats buildStats, path string) error {\n\tvar allStats []buildStats\n\tif data, err := ioutil.ReadFile(*statsOutputPath); err == nil {\n\t\tjson.Unmarshal(data, &allStats)\n\t}\n\tfound := false\n\tfor i, s := range allStats {\n\t\tif s.Label == stats.Label {\n\t\t\tallStats[i] = stats\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\tallStats = append(allStats, stats)\n\t\tsort.Slice(allStats, func(i, j int) bool {\n\t\t\treturn strings.Compare(allStats[i].Label, allStats[j].Label) == -1\n\t\t})\n\t}\n\tdata, err := json.MarshalIndent(allStats, \"\", \"  \")\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := ioutil.WriteFile(*statsOutputPath, data, 0644); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc generateLabel() string {\n\tvar baseCmds []string\n\tenv := golang.Default()\n\tif len(flag.Args()) > 0 {\n\t\t\/\/ Use the last component of the name to keep the label short\n\t\tfor _, e := range flag.Args() {\n\t\t\tbaseCmds = append(baseCmds, path.Base(e))\n\t\t}\n\t} else {\n\t\tbaseCmds = []string{\"core\"}\n\t}\n\treturn fmt.Sprintf(\"%s-%s-%s-%s\", *build, env.GOOS, env.GOARCH, strings.Join(baseCmds, \"_\"))\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tstart := time.Now()\n\n\t\/\/ Main is in a separate functions so defers run on return.\n\tif err := Main(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\telapsed := time.Now().Sub(start)\n\n\tstats := buildStats{\n\t\tLabel:    *statsLabel,\n\t\tTime:     start.Unix(),\n\t\tDuration: float64(elapsed.Milliseconds()) \/ 1000,\n\t}\n\tif stats.Label == \"\" {\n\t\tstats.Label = generateLabel()\n\t}\n\tif stat, err := os.Stat(*outputPath); err == nil && stat.ModTime().After(start) {\n\t\tlog.Printf(\"Successfully built %q (size %d).\", *outputPath, stat.Size())\n\t\tstats.OutputSize = stat.Size()\n\t\tif *statsOutputPath != \"\" {\n\t\t\tif err := writeBuildStats(stats, *statsOutputPath); err == nil {\n\t\t\t\tlog.Printf(\"Wrote stats to %q (label %q)\", *statsOutputPath, stats.Label)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Failed to write stats to %s: %v\", *statsOutputPath, err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nvar recommendedVersions = []string{\n\t\"go1.13\",\n\t\"go1.14\",\n\t\"go1.15\",\n\t\"go1.16\",\n}\n\nfunc isRecommendedVersion(v string) bool {\n\tfor _, r := range recommendedVersions {\n\t\tif strings.HasPrefix(v, r) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Main is a separate function so defers are run on return, which they wouldn't\n\/\/ on exit.\nfunc Main() error {\n\tenv := golang.Default()\n\tenv.BuildTags = strings.Split(*tags, \",\")\n\tif env.CgoEnabled {\n\t\tlog.Printf(\"Disabling CGO for u-root...\")\n\t\tenv.CgoEnabled = false\n\t}\n\tlog.Printf(\"Build environment: %s\", env)\n\tif env.GOOS != \"linux\" {\n\t\tlog.Printf(\"GOOS is not linux. Did you mean to set GOOS=linux?\")\n\t}\n\n\tv, err := env.Version()\n\tif err != nil {\n\t\tlog.Printf(\"Could not get environment's Go version, using runtime's version: %v\", err)\n\t\tv = runtime.Version()\n\t}\n\tif !isRecommendedVersion(v) {\n\t\tlog.Printf(`WARNING: You are not using one of the recommended Go versions (have = %s, recommended = %v).\n\t\t\tSome packages may not compile.\n\t\t\tGo to https:\/\/golang.org\/doc\/install to find out how to install a newer version of Go,\n\t\t\tor use https:\/\/godoc.org\/golang.org\/dl\/%s to install an additional version of Go.`,\n\t\t\tv, recommendedVersions, recommendedVersions[0])\n\t}\n\n\tarchiver, err := initramfs.GetArchiver(*format)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlogger := log.New(os.Stderr, \"\", log.LstdFlags)\n\t\/\/ Open the target initramfs file.\n\tif *outputPath == \"\" {\n\t\tif len(env.GOOS) == 0 && len(env.GOARCH) == 0 {\n\t\t\treturn fmt.Errorf(\"passed no path, GOOS, and GOARCH to CPIOArchiver.OpenWriter\")\n\t\t}\n\t\t*outputPath = fmt.Sprintf(\"\/tmp\/initramfs.%s_%s.cpio\", env.GOOS, env.GOARCH)\n\t}\n\tw, err := archiver.OpenWriter(logger, *outputPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar baseFile initramfs.Reader\n\tif *base != \"\" {\n\t\tbf, err := os.Open(*base)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer bf.Close()\n\t\tbaseFile = archiver.Reader(bf)\n\t} else {\n\t\tbaseFile = uroot.DefaultRamfs().Reader()\n\t}\n\n\ttempDir := *tmpDir\n\tif tempDir == \"\" {\n\t\tvar err error\n\t\ttempDir, err = ioutil.TempDir(\"\", \"u-root\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer os.RemoveAll(tempDir)\n\t} else if _, err := os.Stat(tempDir); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(tempDir, 0755); err != nil {\n\t\t\treturn fmt.Errorf(\"temporary directory %q did not exist; tried to mkdir but failed: %v\", tempDir, err)\n\t\t}\n\t}\n\n\tvar (\n\t\tc           []uroot.Commands\n\t\tinitCommand = *initCmd\n\t)\n\tif !*noCommands {\n\t\tvar b builder.Builder\n\t\tswitch *build {\n\t\tcase \"bb\":\n\t\t\tb = builder.BBBuilder{ShellBang: *shellbang}\n\t\tcase \"binary\":\n\t\t\tb = builder.BinaryBuilder{}\n\t\tcase \"source\":\n\t\t\treturn fmt.Errorf(\"source mode has been deprecated\")\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"could not find builder %q\", *build)\n\t\t}\n\n\t\t\/\/ Resolve globs into package imports.\n\t\t\/\/\n\t\t\/\/ Currently allowed formats:\n\t\t\/\/   Go package imports; e.g. github.com\/u-root\/u-root\/cmds\/ls (must be in $GOPATH)\n\t\t\/\/   Paths to Go package directories; e.g. $GOPATH\/src\/github.com\/u-root\/u-root\/cmds\/*\n\t\tvar pkgs []string\n\t\tfor _, a := range flag.Args() {\n\t\t\tp, ok := templates[a]\n\t\t\tif !ok {\n\t\t\t\tpkgs = append(pkgs, a)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpkgs = append(pkgs, p...)\n\t\t}\n\t\tif len(pkgs) == 0 {\n\t\t\tpkgs = []string{\"github.com\/u-root\/u-root\/cmds\/core\/*\"}\n\t\t}\n\n\t\t\/\/ The command-line tool only allows specifying one build mode\n\t\t\/\/ right now.\n\t\tc = append(c, uroot.Commands{\n\t\t\tBuilder:  b,\n\t\t\tPackages: pkgs,\n\t\t})\n\t}\n\n\topts := uroot.Opts{\n\t\tEnv:             env,\n\t\tCommands:        c,\n\t\tTempDir:         tempDir,\n\t\tExtraFiles:      extraFiles,\n\t\tOutputFile:      w,\n\t\tBaseArchive:     baseFile,\n\t\tUseExistingInit: *useExistingInit,\n\t\tInitCmd:         initCommand,\n\t\tDefaultShell:    *defaultShell,\n\t\tNoStrip:         *noStrip,\n\t}\n\tuinitArgs := shlex.Argv(*uinitCmd)\n\tif len(uinitArgs) > 0 {\n\t\topts.UinitCmd = uinitArgs[0]\n\t}\n\tif len(uinitArgs) > 1 {\n\t\topts.UinitArgs = uinitArgs[1:]\n\t}\n\treturn uroot.CreateInitramfs(logger, opts)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 The Terraformer Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\npackage cmd\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/GoogleCloudPlatform\/terraformer\/terraform_utils\/provider_wrapper\"\n\n\t\"github.com\/spf13\/pflag\"\n\n\t\"github.com\/GoogleCloudPlatform\/terraformer\/terraform_utils\"\n\t\"github.com\/GoogleCloudPlatform\/terraformer\/terraform_utils\/terraform_output\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\ntype ImportOptions struct {\n\tResources   []string\n\tPathPattern string\n\tPathOutput  string\n\tState       string\n\tBucket      string\n\tProfile     string\n\tVerbose     bool\n\tZone        string\n\tRegions     []string\n\tProjects    []string\n\tConnect     bool\n\tCompact     bool\n\tFilter      []string\n\tPlan        bool `json:\"-\"`\n\tOutput      string\n}\n\nconst DefaultPathPattern = \"{output}\/{provider}\/{service}\/\"\nconst DefaultPathOutput = \"generated\"\nconst DefaultState = \"local\"\n\nfunc newImportCmd() *cobra.Command {\n\toptions := ImportOptions{}\n\tcmd := &cobra.Command{\n\t\tUse:           \"import\",\n\t\tShort:         \"Import current state to Terraform configuration\",\n\t\tLong:          \"Import current state to Terraform configuration\",\n\t\tSilenceUsage:  true,\n\t\tSilenceErrors: false,\n\t\t\/\/Version:       version.String(),\n\t}\n\n\tcmd.AddCommand(newCmdPlanImporter(options))\n\tfor _, subcommand := range providerImporterSubcommands() {\n\t\tproviderCommand := subcommand(options)\n\t\t_ = providerCommand.MarkPersistentFlagRequired(\"resources\")\n\t\tcmd.AddCommand(providerCommand)\n\t}\n\treturn cmd\n}\n\nfunc Import(provider terraform_utils.ProviderGenerator, options ImportOptions, args []string) error {\n\terr := provider.Init(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tplan := &ImportPlan{\n\t\tProvider:         provider.GetName(),\n\t\tOptions:          options,\n\t\tArgs:             args,\n\t\tImportedResource: map[string][]terraform_utils.Resource{},\n\t}\n\n\tfor _, service := range options.Resources {\n\t\tlog.Println(provider.GetName() + \" importing... \" + service)\n\t\terr = provider.InitService(service, options.Verbose)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprovider.GetService().ParseFilters(options.Filter)\n\t\terr = provider.GetService().InitResources()\n\t\tprovider.GetService().PopulateIgnoreKeys(provider.GetBasicConfig(), options.Verbose)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprovider.GetService().InitialCleanup()\n\n\t\tproviderWrapper, err := provider_wrapper.NewProviderWrapper(provider.GetName(), provider.GetConfig(), options.Verbose)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trefreshedResources, err := terraform_utils.RefreshResources(provider.GetService().GetResources(), providerWrapper)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprovider.GetService().SetResources(refreshedResources)\n\n\t\tfor i := range provider.GetService().GetResources() {\n\t\t\terr = provider.GetService().GetResources()[i].ConvertTFstate(providerWrapper)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tproviderWrapper.Kill()\n\n\t\tprovider.GetService().PostRefreshCleanup()\n\n\t\t\/\/ change structs with additional data for each resource\n\t\terr = provider.GetService().PostConvertHook()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tplan.ImportedResource[service] = append(plan.ImportedResource[service], provider.GetService().GetResources()...)\n\t}\n\tif options.Plan {\n\t\tpath := Path(options.PathPattern, provider.GetName(), \"terraformer\", options.PathOutput)\n\t\treturn ExportPlanFile(plan, path, \"plan.json\")\n\t} else {\n\t\treturn ImportFromPlan(provider, plan)\n\t}\n}\n\nfunc ImportFromPlan(provider terraform_utils.ProviderGenerator, plan *ImportPlan) error {\n\toptions := plan.Options\n\timportedResource := plan.ImportedResource\n\tisServicePath := strings.Contains(options.PathPattern, \"{service}\")\n\n\tif options.Connect {\n\t\tlog.Println(provider.GetName() + \" Connecting.... \")\n\t\timportedResource = terraform_utils.ConnectServices(importedResource, isServicePath, provider.GetResourceConnections())\n\t}\n\n\tif !isServicePath {\n\t\tvar compactedResources []terraform_utils.Resource\n\t\tfor _, resources := range importedResource {\n\t\t\tcompactedResources = append(compactedResources, resources...)\n\t\t}\n\t\te := printService(provider, \"\", options, compactedResources, importedResource)\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t} else {\n\t\tfor serviceName, resources := range importedResource {\n\t\t\te := printService(provider, serviceName, options, resources, importedResource)\n\t\t\tif e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc printService(provider terraform_utils.ProviderGenerator, serviceName string, options ImportOptions, resources []terraform_utils.Resource, importedResource map[string][]terraform_utils.Resource) error {\n\tlog.Println(provider.GetName() + \" save \" + serviceName)\n\t\/\/ Print HCL files for Resources\n\tpath := Path(options.PathPattern, provider.GetName(), serviceName, options.PathOutput)\n\terr := terraform_output.OutputHclFiles(resources, provider, path, serviceName, options.Compact, options.Output)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttfStateFile, err := terraform_utils.PrintTfState(resources)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ print or upload State file\n\tif options.State == \"bucket\" {\n\t\tlog.Println(provider.GetName() + \" upload tfstate to  bucket \" + options.Bucket)\n\t\tbucket := terraform_output.BucketState{\n\t\t\tName: options.Bucket,\n\t\t}\n\t\tif err := bucket.BucketUpload(path, tfStateFile); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ create Bucket file\n\t\tif bucketStateDataFile, err := terraform_utils.Print(bucket.BucketGetTfData(path), map[string]struct{}{}, options.Output); err == nil {\n\t\t\tterraform_output.PrintFile(path+\"\/bucket.tf\", bucketStateDataFile)\n\t\t}\n\t} else {\n\t\tif serviceName == \"\" {\n\t\t\tlog.Println(provider.GetName() + \" save tfstate\")\n\t\t} else {\n\t\t\tlog.Println(provider.GetName() + \" save tfstate for \" + serviceName)\n\t\t}\n\t\tif err := ioutil.WriteFile(path+\"\/terraform.tfstate\", tfStateFile, os.ModePerm); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ Print hcl variables.tf\n\tif serviceName != \"\" {\n\t\tif options.Connect && len(provider.GetResourceConnections()[serviceName]) > 0 {\n\t\t\tvariables := map[string]map[string]map[string]interface{}{}\n\t\t\tvariables[\"data\"] = map[string]map[string]interface{}{}\n\t\t\tvariables[\"data\"][\"terraform_remote_state\"] = map[string]interface{}{}\n\t\t\tif options.State == \"bucket\" {\n\t\t\t\tbucket := terraform_output.BucketState{\n\t\t\t\t\tName: options.Bucket,\n\t\t\t\t}\n\t\t\t\tfor k := range provider.GetResourceConnections()[serviceName] {\n\t\t\t\t\tif _, exist := importedResource[k]; !exist {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tvariables[\"data\"][\"terraform_remote_state\"][k] = map[string]interface{}{\n\t\t\t\t\t\t\"backend\": \"gcs\",\n\t\t\t\t\t\t\"config\": bucket.BucketGetTfData(path),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor k := range provider.GetResourceConnections()[serviceName] {\n\t\t\t\t\tif _, exist := importedResource[k]; !exist {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tvariables[\"data\"][\"terraform_remote_state\"][k] = map[string]interface{}{\n\t\t\t\t\t\t\"backend\": \"local\",\n\t\t\t\t\t\t\"config\": [1]interface{}{map[string]interface{}{\n\t\t\t\t\t\t\t\"path\": strings.Repeat(\"..\/\", strings.Count(path, \"\/\")) + strings.Replace(path, serviceName, k, -1) + \"terraform.tfstate\",\n\t\t\t\t\t\t}},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ create variables file\n\t\t\tif len(provider.GetResourceConnections()[serviceName]) > 0 && options.Connect && len(variables[\"data\"][\"terraform_remote_state\"]) > 0 {\n\t\t\t\tvariablesFile, err := terraform_utils.Print(variables, map[string]struct{}{\"config\": {}}, options.Output)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tterraform_output.PrintFile(path+\"\/variables.\"+terraform_output.GetFileExtension(options.Output), variablesFile)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif options.Connect {\n\t\t\tvariables := map[string]map[string]map[string]interface{}{}\n\t\t\tvariables[\"data\"] = map[string]map[string]interface{}{}\n\t\t\tvariables[\"data\"][\"terraform_remote_state\"] = map[string]interface{}{}\n\t\t\tif options.State == \"bucket\" {\n\t\t\t\tbucket := terraform_output.BucketState{\n\t\t\t\t\tName: options.Bucket,\n\t\t\t\t}\n\t\t\t\tvariables[\"data\"][\"terraform_remote_state\"][\"local\"] = map[string]interface{}{\n\t\t\t\t\t\"backend\": \"gcs\",\n\t\t\t\t\t\"config\": bucket.BucketGetTfData(path),\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvariables[\"data\"][\"terraform_remote_state\"][\"local\"] = map[string]interface{}{\n\t\t\t\t\t\"backend\": \"local\",\n\t\t\t\t\t\"config\": map[string]interface{}{\n\t\t\t\t\t\t\"path\": \"terraform.tfstate\",\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ create variables file\n\t\t\tif options.Connect {\n\t\t\t\tvariablesFile, err := terraform_utils.Print(variables, map[string]struct{}{\"config\": {}}, options.Output)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tterraform_output.PrintFile(path+\"\/variables.\"+terraform_output.GetFileExtension(options.Output), variablesFile)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc Path(pathPattern, providerName, serviceName, output string) string {\n\treturn strings.NewReplacer(\n\t\t\"{provider}\", providerName,\n\t\t\"{service}\", serviceName,\n\t\t\"{output}\", output,\n\t).Replace(pathPattern)\n}\n\nfunc listCmd(provider terraform_utils.ProviderGenerator) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"list\",\n\t\tShort: \"List supported resources for \" + provider.GetName() + \" provider\",\n\t\tLong:  \"List supported resources for \" + provider.GetName() + \" provider\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tservices := []string{}\n\t\t\tfor k := range provider.GetSupportedService() {\n\t\t\t\tservices = append(services, k)\n\t\t\t}\n\t\t\tsort.Strings(services)\n\t\t\tfor _, k := range services {\n\t\t\t\tfmt.Println(k)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tcmd.Flags().AddFlag(&pflag.Flag{Name: \"resources\"})\n\treturn cmd\n}\n\nfunc baseProviderFlags(flag *pflag.FlagSet, options *ImportOptions, sampleRes, sampleFilters string) {\n\tflag.BoolVarP(&options.Connect, \"connect\", \"c\", true, \"\")\n\tflag.BoolVarP(&options.Compact, \"compact\", \"C\", false, \"\")\n\tflag.StringSliceVarP(&options.Resources, \"resources\", \"r\", []string{}, sampleRes)\n\tflag.StringVarP(&options.PathPattern, \"path-pattern\", \"p\", DefaultPathPattern, \"{output}\/{provider}\/\")\n\tflag.StringVarP(&options.PathOutput, \"path-output\", \"o\", DefaultPathOutput, \"\")\n\tflag.StringVarP(&options.State, \"state\", \"s\", DefaultState, \"local or bucket\")\n\tflag.StringVarP(&options.Bucket, \"bucket\", \"b\", \"\", \"gs:\/\/terraform-state\")\n\tflag.StringSliceVarP(&options.Filter, \"filter\", \"f\", []string{}, sampleFilters)\n\tflag.BoolVarP(&options.Verbose, \"verbose\", \"v\", false, \"\")\n\tflag.StringVarP(&options.Output, \"output\", \"O\", \"hcl\", \"output format hcl or json\")\n}\n<commit_msg>FIX: whoopsie<commit_after>\/\/ Copyright 2018 The Terraformer Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\npackage cmd\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/GoogleCloudPlatform\/terraformer\/terraform_utils\/provider_wrapper\"\n\n\t\"github.com\/spf13\/pflag\"\n\n\t\"github.com\/GoogleCloudPlatform\/terraformer\/terraform_utils\"\n\t\"github.com\/GoogleCloudPlatform\/terraformer\/terraform_utils\/terraform_output\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\ntype ImportOptions struct {\n\tResources   []string\n\tPathPattern string\n\tPathOutput  string\n\tState       string\n\tBucket      string\n\tProfile     string\n\tVerbose     bool\n\tZone        string\n\tRegions     []string\n\tProjects    []string\n\tConnect     bool\n\tCompact     bool\n\tFilter      []string\n\tPlan        bool `json:\"-\"`\n\tOutput      string\n}\n\nconst DefaultPathPattern = \"{output}\/{provider}\/{service}\/\"\nconst DefaultPathOutput = \"generated\"\nconst DefaultState = \"local\"\n\nfunc newImportCmd() *cobra.Command {\n\toptions := ImportOptions{}\n\tcmd := &cobra.Command{\n\t\tUse:           \"import\",\n\t\tShort:         \"Import current state to Terraform configuration\",\n\t\tLong:          \"Import current state to Terraform configuration\",\n\t\tSilenceUsage:  true,\n\t\tSilenceErrors: false,\n\t\t\/\/Version:       version.String(),\n\t}\n\n\tcmd.AddCommand(newCmdPlanImporter(options))\n\tfor _, subcommand := range providerImporterSubcommands() {\n\t\tproviderCommand := subcommand(options)\n\t\t_ = providerCommand.MarkPersistentFlagRequired(\"resources\")\n\t\tcmd.AddCommand(providerCommand)\n\t}\n\treturn cmd\n}\n\nfunc Import(provider terraform_utils.ProviderGenerator, options ImportOptions, args []string) error {\n\terr := provider.Init(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tplan := &ImportPlan{\n\t\tProvider:         provider.GetName(),\n\t\tOptions:          options,\n\t\tArgs:             args,\n\t\tImportedResource: map[string][]terraform_utils.Resource{},\n\t}\n\n\tfor _, service := range options.Resources {\n\t\tlog.Println(provider.GetName() + \" importing... \" + service)\n\t\terr = provider.InitService(service, options.Verbose)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprovider.GetService().ParseFilters(options.Filter)\n\t\terr = provider.GetService().InitResources()\n\t\tprovider.GetService().PopulateIgnoreKeys(provider.GetBasicConfig(), options.Verbose)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprovider.GetService().InitialCleanup()\n\n\t\tproviderWrapper, err := provider_wrapper.NewProviderWrapper(provider.GetName(), provider.GetConfig(), options.Verbose)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trefreshedResources, err := terraform_utils.RefreshResources(provider.GetService().GetResources(), providerWrapper)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tprovider.GetService().SetResources(refreshedResources)\n\n\t\tfor i := range provider.GetService().GetResources() {\n\t\t\terr = provider.GetService().GetResources()[i].ConvertTFstate(providerWrapper)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\tproviderWrapper.Kill()\n\n\t\tprovider.GetService().PostRefreshCleanup()\n\n\t\t\/\/ change structs with additional data for each resource\n\t\terr = provider.GetService().PostConvertHook()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tplan.ImportedResource[service] = append(plan.ImportedResource[service], provider.GetService().GetResources()...)\n\t}\n\tif options.Plan {\n\t\tpath := Path(options.PathPattern, provider.GetName(), \"terraformer\", options.PathOutput)\n\t\treturn ExportPlanFile(plan, path, \"plan.json\")\n\t} else {\n\t\treturn ImportFromPlan(provider, plan)\n\t}\n}\n\nfunc ImportFromPlan(provider terraform_utils.ProviderGenerator, plan *ImportPlan) error {\n\toptions := plan.Options\n\timportedResource := plan.ImportedResource\n\tisServicePath := strings.Contains(options.PathPattern, \"{service}\")\n\n\tif options.Connect {\n\t\tlog.Println(provider.GetName() + \" Connecting.... \")\n\t\timportedResource = terraform_utils.ConnectServices(importedResource, isServicePath, provider.GetResourceConnections())\n\t}\n\n\tif !isServicePath {\n\t\tvar compactedResources []terraform_utils.Resource\n\t\tfor _, resources := range importedResource {\n\t\t\tcompactedResources = append(compactedResources, resources...)\n\t\t}\n\t\te := printService(provider, \"\", options, compactedResources, importedResource)\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t} else {\n\t\tfor serviceName, resources := range importedResource {\n\t\t\te := printService(provider, serviceName, options, resources, importedResource)\n\t\t\tif e != nil {\n\t\t\t\treturn e\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc printService(provider terraform_utils.ProviderGenerator, serviceName string, options ImportOptions, resources []terraform_utils.Resource, importedResource map[string][]terraform_utils.Resource) error {\n\tlog.Println(provider.GetName() + \" save \" + serviceName)\n\t\/\/ Print HCL files for Resources\n\tpath := Path(options.PathPattern, provider.GetName(), serviceName, options.PathOutput)\n\terr := terraform_output.OutputHclFiles(resources, provider, path, serviceName, options.Compact, options.Output)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttfStateFile, err := terraform_utils.PrintTfState(resources)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ print or upload State file\n\tif options.State == \"bucket\" {\n\t\tlog.Println(provider.GetName() + \" upload tfstate to  bucket \" + options.Bucket)\n\t\tbucket := terraform_output.BucketState{\n\t\t\tName: options.Bucket,\n\t\t}\n\t\tif err := bucket.BucketUpload(path, tfStateFile); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ create Bucket file\n\t\tif bucketStateDataFile, err := terraform_utils.Print(bucket.BucketGetTfData(path), map[string]struct{}{}, options.Output); err == nil {\n\t\t\tterraform_output.PrintFile(path+\"\/bucket.tf\", bucketStateDataFile)\n\t\t}\n\t} else {\n\t\tif serviceName == \"\" {\n\t\t\tlog.Println(provider.GetName() + \" save tfstate\")\n\t\t} else {\n\t\t\tlog.Println(provider.GetName() + \" save tfstate for \" + serviceName)\n\t\t}\n\t\tif err := ioutil.WriteFile(path+\"\/terraform.tfstate\", tfStateFile, os.ModePerm); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ Print hcl variables.tf\n\tif serviceName != \"\" {\n\t\tif options.Connect && len(provider.GetResourceConnections()[serviceName]) > 0 {\n\t\t\tvariables := map[string]map[string]map[string]interface{}{}\n\t\t\tvariables[\"data\"] = map[string]map[string]interface{}{}\n\t\t\tvariables[\"data\"][\"terraform_remote_state\"] = map[string]interface{}{}\n\t\t\tif options.State == \"bucket\" {\n\t\t\t\tbucket := terraform_output.BucketState{\n\t\t\t\t\tName: options.Bucket,\n\t\t\t\t}\n\t\t\t\tfor k := range provider.GetResourceConnections()[serviceName] {\n\t\t\t\t\tif _, exist := importedResource[k]; !exist {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tvariables[\"data\"][\"terraform_remote_state\"][k] = map[string]interface{}{\n\t\t\t\t\t\t\"backend\": \"gcs\",\n\t\t\t\t\t\t\"config\": bucket.BucketGetTfData(strings.Replace(path, serviceName, k, -1)),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfor k := range provider.GetResourceConnections()[serviceName] {\n\t\t\t\t\tif _, exist := importedResource[k]; !exist {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tvariables[\"data\"][\"terraform_remote_state\"][k] = map[string]interface{}{\n\t\t\t\t\t\t\"backend\": \"local\",\n\t\t\t\t\t\t\"config\": [1]interface{}{map[string]interface{}{\n\t\t\t\t\t\t\t\"path\": strings.Repeat(\"..\/\", strings.Count(path, \"\/\")) + strings.Replace(path, serviceName, k, -1) + \"terraform.tfstate\",\n\t\t\t\t\t\t}},\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ create variables file\n\t\t\tif len(provider.GetResourceConnections()[serviceName]) > 0 && options.Connect && len(variables[\"data\"][\"terraform_remote_state\"]) > 0 {\n\t\t\t\tvariablesFile, err := terraform_utils.Print(variables, map[string]struct{}{\"config\": {}}, options.Output)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tterraform_output.PrintFile(path+\"\/variables.\"+terraform_output.GetFileExtension(options.Output), variablesFile)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif options.Connect {\n\t\t\tvariables := map[string]map[string]map[string]interface{}{}\n\t\t\tvariables[\"data\"] = map[string]map[string]interface{}{}\n\t\t\tvariables[\"data\"][\"terraform_remote_state\"] = map[string]interface{}{}\n\t\t\tif options.State == \"bucket\" {\n\t\t\t\tbucket := terraform_output.BucketState{\n\t\t\t\t\tName: options.Bucket,\n\t\t\t\t}\n\t\t\t\tvariables[\"data\"][\"terraform_remote_state\"][\"local\"] = map[string]interface{}{\n\t\t\t\t\t\"backend\": \"gcs\",\n\t\t\t\t\t\"config\": bucket.BucketGetTfData(path),\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvariables[\"data\"][\"terraform_remote_state\"][\"local\"] = map[string]interface{}{\n\t\t\t\t\t\"backend\": \"local\",\n\t\t\t\t\t\"config\": map[string]interface{}{\n\t\t\t\t\t\t\"path\": \"terraform.tfstate\",\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ create variables file\n\t\t\tif options.Connect {\n\t\t\t\tvariablesFile, err := terraform_utils.Print(variables, map[string]struct{}{\"config\": {}}, options.Output)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tterraform_output.PrintFile(path+\"\/variables.\"+terraform_output.GetFileExtension(options.Output), variablesFile)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc Path(pathPattern, providerName, serviceName, output string) string {\n\treturn strings.NewReplacer(\n\t\t\"{provider}\", providerName,\n\t\t\"{service}\", serviceName,\n\t\t\"{output}\", output,\n\t).Replace(pathPattern)\n}\n\nfunc listCmd(provider terraform_utils.ProviderGenerator) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse:   \"list\",\n\t\tShort: \"List supported resources for \" + provider.GetName() + \" provider\",\n\t\tLong:  \"List supported resources for \" + provider.GetName() + \" provider\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tservices := []string{}\n\t\t\tfor k := range provider.GetSupportedService() {\n\t\t\t\tservices = append(services, k)\n\t\t\t}\n\t\t\tsort.Strings(services)\n\t\t\tfor _, k := range services {\n\t\t\t\tfmt.Println(k)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tcmd.Flags().AddFlag(&pflag.Flag{Name: \"resources\"})\n\treturn cmd\n}\n\nfunc baseProviderFlags(flag *pflag.FlagSet, options *ImportOptions, sampleRes, sampleFilters string) {\n\tflag.BoolVarP(&options.Connect, \"connect\", \"c\", true, \"\")\n\tflag.BoolVarP(&options.Compact, \"compact\", \"C\", false, \"\")\n\tflag.StringSliceVarP(&options.Resources, \"resources\", \"r\", []string{}, sampleRes)\n\tflag.StringVarP(&options.PathPattern, \"path-pattern\", \"p\", DefaultPathPattern, \"{output}\/{provider}\/\")\n\tflag.StringVarP(&options.PathOutput, \"path-output\", \"o\", DefaultPathOutput, \"\")\n\tflag.StringVarP(&options.State, \"state\", \"s\", DefaultState, \"local or bucket\")\n\tflag.StringVarP(&options.Bucket, \"bucket\", \"b\", \"\", \"gs:\/\/terraform-state\")\n\tflag.StringSliceVarP(&options.Filter, \"filter\", \"f\", []string{}, sampleFilters)\n\tflag.BoolVarP(&options.Verbose, \"verbose\", \"v\", false, \"\")\n\tflag.StringVarP(&options.Output, \"output\", \"O\", \"hcl\", \"output format hcl or json\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Prometheus Team\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage ui\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\" \/\/ Comment this line to disable pprof endpoint.\n\t\"path\"\n\n\t\"github.com\/go-kit\/kit\/log\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\/promhttp\"\n\t\"github.com\/prometheus\/common\/route\"\n\n\t\"github.com\/prometheus\/alertmanager\/asset\"\n)\n\n\/\/ Register registers handlers to serve files for the web interface.\nfunc Register(r *route.Router, reloadCh chan<- chan error, logger log.Logger) {\n\tr.Get(\"\/metrics\", promhttp.Handler().ServeHTTP)\n\n\tr.Get(\"\/\", func(w http.ResponseWriter, req *http.Request) {\n\t\treq.URL.Path = \"\/static\/\"\n\t\tfs := http.FileServer(asset.Assets)\n\t\tfs.ServeHTTP(w, req)\n\t})\n\n\tr.Get(\"\/script.js\", func(w http.ResponseWriter, req *http.Request) {\n\t\treq.URL.Path = \"\/static\/script.js\"\n\t\tfs := http.FileServer(asset.Assets)\n\t\tfs.ServeHTTP(w, req)\n\t})\n\n\tr.Get(\"\/favicon.ico\", func(w http.ResponseWriter, req *http.Request) {\n\t\treq.URL.Path = \"\/static\/favicon.ico\"\n\t\tfs := http.FileServer(asset.Assets)\n\t\tfs.ServeHTTP(w, req)\n\t})\n\n\tr.Get(\"\/lib\/*path\", func(w http.ResponseWriter, req *http.Request) {\n\t\treq.URL.Path = path.Join(\"\/static\/lib\", route.Param(req.Context(), \"path\"))\n\t\tfs := http.FileServer(asset.Assets)\n\t\tfs.ServeHTTP(w, req)\n\t})\n\n\tr.Post(\"\/-\/reload\", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\terrc := make(chan error)\n\t\tdefer close(errc)\n\n\t\treloadCh <- errc\n\t\tif err := <-errc; err != nil {\n\t\t\thttp.Error(w, fmt.Sprintf(\"failed to reload config: %s\", err), http.StatusInternalServerError)\n\t\t}\n\t}))\n\n\tr.Get(\"\/-\/healthy\", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tfmt.Fprintf(w, \"OK\")\n\t}))\n\tr.Get(\"\/-\/ready\", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tfmt.Fprintf(w, \"OK\")\n\t}))\n\n\tr.Get(\"\/debug\/*subpath\", http.DefaultServeMux.ServeHTTP)\n\tr.Post(\"\/debug\/*subpath\", http.DefaultServeMux.ServeHTTP)\n}\n<commit_msg>ui\/web: Set HTTP headers to prevent asset caching<commit_after>\/\/ Copyright 2015 Prometheus Team\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage ui\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\" \/\/ Comment this line to disable pprof endpoint.\n\t\"path\"\n\n\t\"github.com\/go-kit\/kit\/log\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\/promhttp\"\n\t\"github.com\/prometheus\/common\/route\"\n\n\t\"github.com\/prometheus\/alertmanager\/asset\"\n)\n\n\/\/ Register registers handlers to serve files for the web interface.\nfunc Register(r *route.Router, reloadCh chan<- chan error, logger log.Logger) {\n\tr.Get(\"\/metrics\", promhttp.Handler().ServeHTTP)\n\n\tr.Get(\"\/\", func(w http.ResponseWriter, req *http.Request) {\n\t\tdisableCaching(w)\n\n\t\treq.URL.Path = \"\/static\/\"\n\t\tfs := http.FileServer(asset.Assets)\n\t\tfs.ServeHTTP(w, req)\n\t})\n\n\tr.Get(\"\/script.js\", func(w http.ResponseWriter, req *http.Request) {\n\t\tdisableCaching(w)\n\n\t\treq.URL.Path = \"\/static\/script.js\"\n\t\tfs := http.FileServer(asset.Assets)\n\t\tfs.ServeHTTP(w, req)\n\t})\n\n\tr.Get(\"\/favicon.ico\", func(w http.ResponseWriter, req *http.Request) {\n\t\tdisableCaching(w)\n\n\t\treq.URL.Path = \"\/static\/favicon.ico\"\n\t\tfs := http.FileServer(asset.Assets)\n\t\tfs.ServeHTTP(w, req)\n\t})\n\n\tr.Get(\"\/lib\/*path\", func(w http.ResponseWriter, req *http.Request) {\n\t\tdisableCaching(w)\n\n\t\treq.URL.Path = path.Join(\"\/static\/lib\", route.Param(req.Context(), \"path\"))\n\t\tfs := http.FileServer(asset.Assets)\n\t\tfs.ServeHTTP(w, req)\n\t})\n\n\tr.Post(\"\/-\/reload\", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\terrc := make(chan error)\n\t\tdefer close(errc)\n\n\t\treloadCh <- errc\n\t\tif err := <-errc; err != nil {\n\t\t\thttp.Error(w, fmt.Sprintf(\"failed to reload config: %s\", err), http.StatusInternalServerError)\n\t\t}\n\t}))\n\n\tr.Get(\"\/-\/healthy\", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tfmt.Fprintf(w, \"OK\")\n\t}))\n\tr.Get(\"\/-\/ready\", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tfmt.Fprintf(w, \"OK\")\n\t}))\n\n\tr.Get(\"\/debug\/*subpath\", http.DefaultServeMux.ServeHTTP)\n\tr.Post(\"\/debug\/*subpath\", http.DefaultServeMux.ServeHTTP)\n}\n\nfunc disableCaching(w http.ResponseWriter) {\n\tw.Header().Set(\"Cache-Control\", \"no-cache, no-store, must-revalidate\")\n\tw.Header().Set(\"Pragma\", \"no-cache\")\n\tw.Header().Set(\"Expires\", \"0\") \/\/ Prevent proxies from caching.\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package virtualmachine provides a client for Virtual Machines.\npackage virtualmachine\n\nimport (\n\t\"encoding\/xml\"\n\t\"fmt\"\n\n\t\"github.com\/Azure\/azure-sdk-for-go\/management\"\n)\n\nconst (\n\tazureDeploymentListURL   = \"services\/hostedservices\/%s\/deployments\"\n\tazureDeploymentURL       = \"services\/hostedservices\/%s\/deployments\/%s\"\n\tdeleteAzureDeploymentURL = \"services\/hostedservices\/%s\/deployments\/%s?comp=media\"\n\tazureRoleURL             = \"services\/hostedservices\/%s\/deployments\/%s\/roles\/%s\"\n\tazureOperationsURL       = \"services\/hostedservices\/%s\/deployments\/%s\/roleinstances\/%s\/Operations\"\n\tazureRoleSizeListURL     = \"rolesizes\"\n\n\terrParamNotSpecified = \"Parameter %s is not specified.\"\n)\n\n\/\/NewClient is used to instantiate a new VirtualMachineClient from an Azure client\nfunc NewClient(client management.Client) VirtualMachineClient {\n\treturn VirtualMachineClient{client: client}\n}\n\n\/\/ CreateDeploymentOptions can be used to create a customized deployement request\ntype CreateDeploymentOptions struct {\n\tDNSServers         []DNSServer\n\tLoadBalancers      []LoadBalancer\n\tReservedIPName     string\n\tVirtualNetworkName string\n}\n\n\/\/ CreateDeployment creates a deployment and then creates a virtual machine\n\/\/ in the deployment based on the specified configuration.\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157194.aspx\nfunc (vm VirtualMachineClient) CreateDeployment(\n\trole Role,\n\tcloudServiceName string,\n\toptions CreateDeploymentOptions) (management.OperationID, error) {\n\n\treq := DeploymentRequest{\n\t\tName:               role.RoleName,\n\t\tDeploymentSlot:     \"Production\",\n\t\tLabel:              role.RoleName,\n\t\tRoleList:           []Role{role},\n\t\tDNSServers:         options.DNSServers,\n\t\tLoadBalancers:      options.LoadBalancers,\n\t\tReservedIPName:     options.ReservedIPName,\n\t\tVirtualNetworkName: options.VirtualNetworkName,\n\t}\n\n\tdata, err := xml.Marshal(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trequestURL := fmt.Sprintf(azureDeploymentListURL, cloudServiceName)\n\treturn vm.client.SendAzurePostRequest(requestURL, data)\n}\n\nfunc (vm VirtualMachineClient) GetDeployment(cloudServiceName, deploymentName string) (DeploymentResponse, error) {\n\tvar deployment DeploymentResponse\n\tif cloudServiceName == \"\" {\n\t\treturn deployment, fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn deployment, fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\trequestURL := fmt.Sprintf(azureDeploymentURL, cloudServiceName, deploymentName)\n\tresponse, azureErr := vm.client.SendAzureGetRequest(requestURL)\n\tif azureErr != nil {\n\t\treturn deployment, azureErr\n\t}\n\n\terr := xml.Unmarshal(response, &deployment)\n\treturn deployment, err\n}\n\nfunc (vm VirtualMachineClient) DeleteDeployment(cloudServiceName, deploymentName string) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\n\trequestURL := fmt.Sprintf(deleteAzureDeploymentURL, cloudServiceName, deploymentName)\n\treturn vm.client.SendAzureDeleteRequest(requestURL)\n}\n\nfunc (vm VirtualMachineClient) GetRole(cloudServiceName, deploymentName, roleName string) (*Role, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn nil, fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn nil, fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn nil, fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\trole := new(Role)\n\n\trequestURL := fmt.Sprintf(azureRoleURL, cloudServiceName, deploymentName, roleName)\n\tresponse, azureErr := vm.client.SendAzureGetRequest(requestURL)\n\tif azureErr != nil {\n\t\treturn nil, azureErr\n\t}\n\n\terr := xml.Unmarshal(response, role)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn role, nil\n}\n\n\/\/ UpdateRole updates the configuration of the specified virtual machine\n\/\/ See https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157187.aspx\nfunc (vm VirtualMachineClient) UpdateRole(cloudServiceName, deploymentName, roleName string, role Role) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\tdata, err := xml.Marshal(PersistentVMRole{Role: role})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trequestURL := fmt.Sprintf(azureRoleURL, cloudServiceName, deploymentName, roleName)\n\treturn vm.client.SendAzurePutRequest(requestURL, \"text\/xml\", data)\n}\n\nfunc (vm VirtualMachineClient) StartRole(cloudServiceName, deploymentName, roleName string) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\tstartRoleOperationBytes, err := xml.Marshal(StartRoleOperation{\n\t\tOperationType: \"StartRoleOperation\",\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trequestURL := fmt.Sprintf(azureOperationsURL, cloudServiceName, deploymentName, roleName)\n\treturn vm.client.SendAzurePostRequest(requestURL, startRoleOperationBytes)\n}\n\nfunc (vm VirtualMachineClient) ShutdownRole(cloudServiceName, deploymentName, roleName string) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\tshutdownRoleOperationBytes, err := xml.Marshal(ShutdownRoleOperation{\n\t\tOperationType: \"ShutdownRoleOperation\",\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trequestURL := fmt.Sprintf(azureOperationsURL, cloudServiceName, deploymentName, roleName)\n\treturn vm.client.SendAzurePostRequest(requestURL, shutdownRoleOperationBytes)\n}\n\nfunc (vm VirtualMachineClient) RestartRole(cloudServiceName, deploymentName, roleName string) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\trestartRoleOperationBytes, err := xml.Marshal(RestartRoleOperation{\n\t\tOperationType: \"RestartRoleOperation\",\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trequestURL := fmt.Sprintf(azureOperationsURL, cloudServiceName, deploymentName, roleName)\n\treturn vm.client.SendAzurePostRequest(requestURL, restartRoleOperationBytes)\n}\n\nfunc (vm VirtualMachineClient) DeleteRole(cloudServiceName, deploymentName, roleName string) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\trequestURL := fmt.Sprintf(azureRoleURL, cloudServiceName, deploymentName, roleName)\n\treturn vm.client.SendAzureDeleteRequest(requestURL)\n}\n\nfunc (vm VirtualMachineClient) GetRoleSizeList() (RoleSizeList, error) {\n\troleSizeList := RoleSizeList{}\n\n\tresponse, err := vm.client.SendAzureGetRequest(azureRoleSizeListURL)\n\tif err != nil {\n\t\treturn roleSizeList, err\n\t}\n\n\terr = xml.Unmarshal(response, &roleSizeList)\n\treturn roleSizeList, err\n}\n\n\/\/ CaptureRole captures a VM role. If reprovisioningConfigurationSet is non-nil,\n\/\/ the VM role is redeployed after capturing the image, otherwise, the original\n\/\/ VM role is deleted.\n\/\/\n\/\/ NOTE: an image resulting from this operation shows up in\n\/\/ osimage.GetImageList() as images with Category \"User\".\nfunc (vm VirtualMachineClient) CaptureRole(cloudServiceName, deploymentName, roleName, imageName, imageLabel string,\n\treprovisioningConfigurationSet *ConfigurationSet) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\tif reprovisioningConfigurationSet != nil &&\n\t\t!(reprovisioningConfigurationSet.ConfigurationSetType == ConfigurationSetTypeLinuxProvisioning ||\n\t\t\treprovisioningConfigurationSet.ConfigurationSetType == ConfigurationSetTypeWindowsProvisioning) {\n\t\treturn \"\", fmt.Errorf(\"ConfigurationSet type can only be WindowsProvisioningConfiguration or LinuxProvisioningConfiguration\")\n\t}\n\n\toperation := CaptureRoleOperation{\n\t\tOperationType:             \"CaptureRoleOperation\",\n\t\tPostCaptureAction:         PostCaptureActionReprovision,\n\t\tProvisioningConfiguration: reprovisioningConfigurationSet,\n\t\tTargetImageLabel:          imageLabel,\n\t\tTargetImageName:           imageName,\n\t}\n\tif reprovisioningConfigurationSet == nil {\n\t\toperation.PostCaptureAction = PostCaptureActionDelete\n\t}\n\n\tdata, err := xml.Marshal(operation)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn vm.client.SendAzurePostRequest(fmt.Sprintf(azureOperationsURL, cloudServiceName, deploymentName, roleName), data)\n}\n<commit_msg>Adding AddRole method so that this bug can be fixed: https:\/\/github.com\/hashicorp\/terraform\/issues\/3568<commit_after>\/\/ Package virtualmachine provides a client for Virtual Machines.\npackage virtualmachine\n\nimport (\n\t\"encoding\/xml\"\n\t\"fmt\"\n\n\t\"github.com\/Azure\/azure-sdk-for-go\/management\"\n)\n\nconst (\n\tazureDeploymentListURL   = \"services\/hostedservices\/%s\/deployments\"\n\tazureDeploymentURL       = \"services\/hostedservices\/%s\/deployments\/%s\"\n\tdeleteAzureDeploymentURL = \"services\/hostedservices\/%s\/deployments\/%s?comp=media\"\n\tazureAddRoleURL          = \"services\/hostedservices\/%s\/deployments\/%s\/roles\"\n\tazureRoleURL             = \"services\/hostedservices\/%s\/deployments\/%s\/roles\/%s\"\n\tazureOperationsURL       = \"services\/hostedservices\/%s\/deployments\/%s\/roleinstances\/%s\/Operations\"\n\tazureRoleSizeListURL     = \"rolesizes\"\n\n\terrParamNotSpecified = \"Parameter %s is not specified.\"\n)\n\n\/\/NewClient is used to instantiate a new VirtualMachineClient from an Azure client\nfunc NewClient(client management.Client) VirtualMachineClient {\n\treturn VirtualMachineClient{client: client}\n}\n\n\/\/ CreateDeploymentOptions can be used to create a customized deployement request\ntype CreateDeploymentOptions struct {\n\tDNSServers         []DNSServer\n\tLoadBalancers      []LoadBalancer\n\tReservedIPName     string\n\tVirtualNetworkName string\n}\n\n\/\/ CreateDeployment creates a deployment and then creates a virtual machine\n\/\/ in the deployment based on the specified configuration.\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157194.aspx\nfunc (vm VirtualMachineClient) CreateDeployment(\n\trole Role,\n\tcloudServiceName string,\n\toptions CreateDeploymentOptions) (management.OperationID, error) {\n\n\treq := DeploymentRequest{\n\t\tName:               role.RoleName,\n\t\tDeploymentSlot:     \"Production\",\n\t\tLabel:              role.RoleName,\n\t\tRoleList:           []Role{role},\n\t\tDNSServers:         options.DNSServers,\n\t\tLoadBalancers:      options.LoadBalancers,\n\t\tReservedIPName:     options.ReservedIPName,\n\t\tVirtualNetworkName: options.VirtualNetworkName,\n\t}\n\n\tdata, err := xml.Marshal(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trequestURL := fmt.Sprintf(azureDeploymentListURL, cloudServiceName)\n\treturn vm.client.SendAzurePostRequest(requestURL, data)\n}\n\nfunc (vm VirtualMachineClient) GetDeployment(cloudServiceName, deploymentName string) (DeploymentResponse, error) {\n\tvar deployment DeploymentResponse\n\tif cloudServiceName == \"\" {\n\t\treturn deployment, fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn deployment, fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\trequestURL := fmt.Sprintf(azureDeploymentURL, cloudServiceName, deploymentName)\n\tresponse, azureErr := vm.client.SendAzureGetRequest(requestURL)\n\tif azureErr != nil {\n\t\treturn deployment, azureErr\n\t}\n\n\terr := xml.Unmarshal(response, &deployment)\n\treturn deployment, err\n}\n\nfunc (vm VirtualMachineClient) DeleteDeployment(cloudServiceName, deploymentName string) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\n\trequestURL := fmt.Sprintf(deleteAzureDeploymentURL, cloudServiceName, deploymentName)\n\treturn vm.client.SendAzureDeleteRequest(requestURL)\n}\n\nfunc (vm VirtualMachineClient) GetRole(cloudServiceName, deploymentName, roleName string) (*Role, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn nil, fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn nil, fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn nil, fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\trole := new(Role)\n\n\trequestURL := fmt.Sprintf(azureRoleURL, cloudServiceName, deploymentName, roleName)\n\tresponse, azureErr := vm.client.SendAzureGetRequest(requestURL)\n\tif azureErr != nil {\n\t\treturn nil, azureErr\n\t}\n\n\terr := xml.Unmarshal(response, role)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn role, nil\n}\n\n\/\/ AddRole adds a Virtual Machine to a deployment of Virtual Machines, where role name = VM name\n\/\/ See https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157186.aspx\nfunc (vm VirtualMachineClient) AddRole(cloudServiceName string, deploymentName string, role Role) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\n\tdata, err := xml.Marshal(PersistentVMRole{Role: role})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trequestURL := fmt.Sprintf(azureAddRoleURL, cloudServiceName, deploymentName)\n\treturn vm.client.SendAzurePostRequest(requestURL, data)\n}\n\n\/\/ UpdateRole updates the configuration of the specified virtual machine\n\/\/ See https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157187.aspx\nfunc (vm VirtualMachineClient) UpdateRole(cloudServiceName, deploymentName, roleName string, role Role) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\tdata, err := xml.Marshal(PersistentVMRole{Role: role})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trequestURL := fmt.Sprintf(azureRoleURL, cloudServiceName, deploymentName, roleName)\n\treturn vm.client.SendAzurePutRequest(requestURL, \"text\/xml\", data)\n}\n\nfunc (vm VirtualMachineClient) StartRole(cloudServiceName, deploymentName, roleName string) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\tstartRoleOperationBytes, err := xml.Marshal(StartRoleOperation{\n\t\tOperationType: \"StartRoleOperation\",\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trequestURL := fmt.Sprintf(azureOperationsURL, cloudServiceName, deploymentName, roleName)\n\treturn vm.client.SendAzurePostRequest(requestURL, startRoleOperationBytes)\n}\n\nfunc (vm VirtualMachineClient) ShutdownRole(cloudServiceName, deploymentName, roleName string) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\tshutdownRoleOperationBytes, err := xml.Marshal(ShutdownRoleOperation{\n\t\tOperationType: \"ShutdownRoleOperation\",\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trequestURL := fmt.Sprintf(azureOperationsURL, cloudServiceName, deploymentName, roleName)\n\treturn vm.client.SendAzurePostRequest(requestURL, shutdownRoleOperationBytes)\n}\n\nfunc (vm VirtualMachineClient) RestartRole(cloudServiceName, deploymentName, roleName string) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\trestartRoleOperationBytes, err := xml.Marshal(RestartRoleOperation{\n\t\tOperationType: \"RestartRoleOperation\",\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\trequestURL := fmt.Sprintf(azureOperationsURL, cloudServiceName, deploymentName, roleName)\n\treturn vm.client.SendAzurePostRequest(requestURL, restartRoleOperationBytes)\n}\n\nfunc (vm VirtualMachineClient) DeleteRole(cloudServiceName, deploymentName, roleName string) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\trequestURL := fmt.Sprintf(azureRoleURL, cloudServiceName, deploymentName, roleName)\n\treturn vm.client.SendAzureDeleteRequest(requestURL)\n}\n\nfunc (vm VirtualMachineClient) GetRoleSizeList() (RoleSizeList, error) {\n\troleSizeList := RoleSizeList{}\n\n\tresponse, err := vm.client.SendAzureGetRequest(azureRoleSizeListURL)\n\tif err != nil {\n\t\treturn roleSizeList, err\n\t}\n\n\terr = xml.Unmarshal(response, &roleSizeList)\n\treturn roleSizeList, err\n}\n\n\/\/ CaptureRole captures a VM role. If reprovisioningConfigurationSet is non-nil,\n\/\/ the VM role is redeployed after capturing the image, otherwise, the original\n\/\/ VM role is deleted.\n\/\/\n\/\/ NOTE: an image resulting from this operation shows up in\n\/\/ osimage.GetImageList() as images with Category \"User\".\nfunc (vm VirtualMachineClient) CaptureRole(cloudServiceName, deploymentName, roleName, imageName, imageLabel string,\n\treprovisioningConfigurationSet *ConfigurationSet) (management.OperationID, error) {\n\tif cloudServiceName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"cloudServiceName\")\n\t}\n\tif deploymentName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"deploymentName\")\n\t}\n\tif roleName == \"\" {\n\t\treturn \"\", fmt.Errorf(errParamNotSpecified, \"roleName\")\n\t}\n\n\tif reprovisioningConfigurationSet != nil &&\n\t\t!(reprovisioningConfigurationSet.ConfigurationSetType == ConfigurationSetTypeLinuxProvisioning ||\n\t\t\treprovisioningConfigurationSet.ConfigurationSetType == ConfigurationSetTypeWindowsProvisioning) {\n\t\treturn \"\", fmt.Errorf(\"ConfigurationSet type can only be WindowsProvisioningConfiguration or LinuxProvisioningConfiguration\")\n\t}\n\n\toperation := CaptureRoleOperation{\n\t\tOperationType:             \"CaptureRoleOperation\",\n\t\tPostCaptureAction:         PostCaptureActionReprovision,\n\t\tProvisioningConfiguration: reprovisioningConfigurationSet,\n\t\tTargetImageLabel:          imageLabel,\n\t\tTargetImageName:           imageName,\n\t}\n\tif reprovisioningConfigurationSet == nil {\n\t\toperation.PostCaptureAction = PostCaptureActionDelete\n\t}\n\n\tdata, err := xml.Marshal(operation)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn vm.client.SendAzurePostRequest(fmt.Sprintf(azureOperationsURL, cloudServiceName, deploymentName, roleName), data)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"crypto\/sha256\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/kr\/binarydist\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"time\"\n)\n\nconst (\n\tupcktimePath = \"cktime\"\n\tplat         = runtime.GOOS + \"-\" + runtime.GOARCH\n)\n\nconst devValidTime = 7 * 24 * time.Hour\n\n\/\/ Update protocol.\n\/\/\n\/\/   GET hk.heroku.com\/hk-current-linux-amd64.json\n\/\/\n\/\/   200 ok\n\/\/   {\n\/\/       \"Version\": \"2\",\n\/\/       \"Sha256\": \"...\" \/\/ base64\n\/\/   }\n\/\/\n\/\/ then\n\/\/\n\/\/   GET hkpatch.s3.amazonaws.com\/hk-1-linux-amd64-to-2\n\/\/\n\/\/   200 ok\n\/\/   [bsdiff data]\n\/\/\n\/\/ or\n\/\/\n\/\/   GET hkdist.s3.amazonaws.com\/hk-2-linux-amd64.gz\n\/\/\n\/\/   200 ok\n\/\/   [gzipped executable data]\ntype Updater struct {\n\thkURL   string\n\tbinURL  string\n\tdiffURL string\n\tdir     string\n\tinfo    struct {\n\t\tVersion   string\n\t\tSha256 []byte\n\t}\n}\n\nfunc (u *Updater) run() {\n\tos.MkdirAll(u.dir, 0777)\n\tif u.wantUpdate() {\n\t\tl := exec.Command(\"logger\", \"-thk\")\n\t\tc := exec.Command(\"hk\", \"update\")\n\t\tif w, err := l.StdinPipe(); err == nil && l.Start() == nil {\n\t\t\tc.Stdout = w\n\t\t\tc.Stderr = w\n\t\t}\n\t\tc.Start()\n\t}\n}\n\nfunc (u *Updater) wantUpdate() bool {\n\tpath := u.dir + upcktimePath\n\tif Version == \"dev\" || readTime(path).After(time.Now()) {\n\t\treturn false\n\t}\n\twait := 24*time.Hour + randDuration(24*time.Hour)\n\treturn writeTime(path, time.Now().Add(wait))\n}\n\nfunc (u *Updater) update() error {\n\tfilename := \"hk\"\n\tif runtime.GOOS == \"windows\" {\n\t\tfilename += \".exe\"\n\t}\n\tpath, err := exec.LookPath(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\told, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = u.fetchInfo()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif u.info.Version == Version {\n\t\treturn nil\n\t}\n\tbin, err := u.fetchAndApplyPatch(old)\n\tif err != nil {\n\t\tbin, err = u.fetchBin()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\th := sha256.New()\n\th.Write(bin)\n\tif !bytes.Equal(h.Sum(nil), u.info.Sha256) {\n\t\treturn errors.New(\"new file hash mismatch after patch\")\n\t}\n\treturn install(old.Name(), bin)\n}\n\nfunc (u *Updater) fetchInfo() error {\n\tr, err := fetch(u.hkURL + \"hk-current-\" + plat + \".json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\terr = json.NewDecoder(r).Decode(&u.info)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(u.info.Sha256) != sha256.Size {\n\t\treturn errors.New(\"bad cmd hash in info\")\n\t}\n\treturn nil\n}\n\nfunc (u *Updater) fetchAndApplyPatch(old io.Reader) ([]byte, error) {\n\tr, err := fetch(u.diffURL + slug(Version) + \"-to-\" + u.info.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Close()\n\tvar buf bytes.Buffer\n\terr = binarydist.Patch(old, &buf, r)\n\treturn buf.Bytes(), err\n}\n\nfunc (u *Updater) fetchBin() ([]byte, error) {\n\tr, err := fetch(u.binURL + slug(u.info.Version) + \".gz\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Close()\n\tbuf := new(bytes.Buffer)\n\tgz, err := gzip.NewReader(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err = io.Copy(buf, gz); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\nfunc install(name string, p []byte) error {\n\texecDir := filepath.Dir(name)\n\tpart := filepath.Join(execDir, \"hk.part\")\n\terr := ioutil.WriteFile(part, p, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.Remove(part)\n\n\t\/\/ move the existing executable to a new file in the same directory\n\toldExecPath := filepath.Join(name, \".old\")\n\terr = os.Rename(name, oldExecPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ move the new executable in to become the new program\n\terr = os.Rename(part, name)\n\n\tif err != nil {\n\t\t\/\/ copy unsuccessful\n\t\terrRecover := os.Rename(oldExecPath, name)\n\t\tif errRecover != nil {\n\t\t\treturn errRecover\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t\/\/ copy successful, remove the old binary\n\t\t_ = os.Remove(oldExecPath)\n\t}\n\n\treturn nil\n}\n\n\/\/ returns a random duration in [0,n).\nfunc randDuration(n time.Duration) time.Duration {\n\treturn time.Duration(rand.Int63n(int64(n)))\n}\n\nfunc slug(ver string) string {\n\treturn \"hk-\" + ver + \"-\" + plat\n}\n\nfunc fetch(url string) (io.ReadCloser, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"bad http status from %s: %v\", url, resp.Status)\n\t}\n\treturn resp.Body, nil\n}\n\nfunc readTime(path string) time.Time {\n\tp, err := ioutil.ReadFile(path)\n\tif os.IsNotExist(err) {\n\t\treturn time.Time{}\n\t}\n\tif err != nil {\n\t\treturn time.Now().Add(1000 * time.Hour)\n\t}\n\tt, err := time.Parse(time.RFC3339, string(p))\n\tif err != nil {\n\t\treturn time.Now().Add(1000 * time.Hour)\n\t}\n\treturn t\n}\n\nfunc writeTime(path string, t time.Time) bool {\n\treturn ioutil.WriteFile(path, []byte(t.Format(time.RFC3339)), 0644) == nil\n}\n<commit_msg>fix oldExecPath again<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"crypto\/sha256\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/kr\/binarydist\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"time\"\n)\n\nconst (\n\tupcktimePath = \"cktime\"\n\tplat         = runtime.GOOS + \"-\" + runtime.GOARCH\n)\n\nconst devValidTime = 7 * 24 * time.Hour\n\n\/\/ Update protocol.\n\/\/\n\/\/   GET hk.heroku.com\/hk-current-linux-amd64.json\n\/\/\n\/\/   200 ok\n\/\/   {\n\/\/       \"Version\": \"2\",\n\/\/       \"Sha256\": \"...\" \/\/ base64\n\/\/   }\n\/\/\n\/\/ then\n\/\/\n\/\/   GET hkpatch.s3.amazonaws.com\/hk-1-linux-amd64-to-2\n\/\/\n\/\/   200 ok\n\/\/   [bsdiff data]\n\/\/\n\/\/ or\n\/\/\n\/\/   GET hkdist.s3.amazonaws.com\/hk-2-linux-amd64.gz\n\/\/\n\/\/   200 ok\n\/\/   [gzipped executable data]\ntype Updater struct {\n\thkURL   string\n\tbinURL  string\n\tdiffURL string\n\tdir     string\n\tinfo    struct {\n\t\tVersion   string\n\t\tSha256 []byte\n\t}\n}\n\nfunc (u *Updater) run() {\n\tos.MkdirAll(u.dir, 0777)\n\tif u.wantUpdate() {\n\t\tl := exec.Command(\"logger\", \"-thk\")\n\t\tc := exec.Command(\"hk\", \"update\")\n\t\tif w, err := l.StdinPipe(); err == nil && l.Start() == nil {\n\t\t\tc.Stdout = w\n\t\t\tc.Stderr = w\n\t\t}\n\t\tc.Start()\n\t}\n}\n\nfunc (u *Updater) wantUpdate() bool {\n\tpath := u.dir + upcktimePath\n\tif Version == \"dev\" || readTime(path).After(time.Now()) {\n\t\treturn false\n\t}\n\twait := 24*time.Hour + randDuration(24*time.Hour)\n\treturn writeTime(path, time.Now().Add(wait))\n}\n\nfunc (u *Updater) update() error {\n\tfilename := \"hk\"\n\tif runtime.GOOS == \"windows\" {\n\t\tfilename += \".exe\"\n\t}\n\tpath, err := exec.LookPath(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\told, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = u.fetchInfo()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif u.info.Version == Version {\n\t\treturn nil\n\t}\n\tbin, err := u.fetchAndApplyPatch(old)\n\tif err != nil {\n\t\tbin, err = u.fetchBin()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\th := sha256.New()\n\th.Write(bin)\n\tif !bytes.Equal(h.Sum(nil), u.info.Sha256) {\n\t\treturn errors.New(\"new file hash mismatch after patch\")\n\t}\n\treturn install(old.Name(), bin)\n}\n\nfunc (u *Updater) fetchInfo() error {\n\tr, err := fetch(u.hkURL + \"hk-current-\" + plat + \".json\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer r.Close()\n\terr = json.NewDecoder(r).Decode(&u.info)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(u.info.Sha256) != sha256.Size {\n\t\treturn errors.New(\"bad cmd hash in info\")\n\t}\n\treturn nil\n}\n\nfunc (u *Updater) fetchAndApplyPatch(old io.Reader) ([]byte, error) {\n\tr, err := fetch(u.diffURL + slug(Version) + \"-to-\" + u.info.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Close()\n\tvar buf bytes.Buffer\n\terr = binarydist.Patch(old, &buf, r)\n\treturn buf.Bytes(), err\n}\n\nfunc (u *Updater) fetchBin() ([]byte, error) {\n\tr, err := fetch(u.binURL + slug(u.info.Version) + \".gz\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer r.Close()\n\tbuf := new(bytes.Buffer)\n\tgz, err := gzip.NewReader(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err = io.Copy(buf, gz); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\nfunc install(name string, p []byte) error {\n\texecDir := filepath.Dir(name)\n\tpart := filepath.Join(execDir, \"hk.part\")\n\terr := ioutil.WriteFile(part, p, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.Remove(part)\n\n\t\/\/ move the existing executable to a new file in the same directory\n\toldExecPath := fmt.Sprintf(\"%s.old\", name)\n\terr = os.Rename(name, oldExecPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ move the new executable in to become the new program\n\terr = os.Rename(part, name)\n\n\tif err != nil {\n\t\t\/\/ copy unsuccessful\n\t\terrRecover := os.Rename(oldExecPath, name)\n\t\tif errRecover != nil {\n\t\t\treturn errRecover\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\t\/\/ copy successful, remove the old binary\n\t\t_ = os.Remove(oldExecPath)\n\t}\n\n\treturn nil\n}\n\n\/\/ returns a random duration in [0,n).\nfunc randDuration(n time.Duration) time.Duration {\n\treturn time.Duration(rand.Int63n(int64(n)))\n}\n\nfunc slug(ver string) string {\n\treturn \"hk-\" + ver + \"-\" + plat\n}\n\nfunc fetch(url string) (io.ReadCloser, error) {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != 200 {\n\t\treturn nil, fmt.Errorf(\"bad http status from %s: %v\", url, resp.Status)\n\t}\n\treturn resp.Body, nil\n}\n\nfunc readTime(path string) time.Time {\n\tp, err := ioutil.ReadFile(path)\n\tif os.IsNotExist(err) {\n\t\treturn time.Time{}\n\t}\n\tif err != nil {\n\t\treturn time.Now().Add(1000 * time.Hour)\n\t}\n\tt, err := time.Parse(time.RFC3339, string(p))\n\tif err != nil {\n\t\treturn time.Now().Add(1000 * time.Hour)\n\t}\n\treturn t\n}\n\nfunc writeTime(path string, t time.Time) bool {\n\treturn ioutil.WriteFile(path, []byte(t.Format(time.RFC3339)), 0644) == nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 The Gogs Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\"os\"\n\"os\/exec\"\n\"strings\"\n\"strconv\"\n\"container\/list\"\n\n\"github.com\/codegangsta\/cli\"\n\/\/\"github.com\/gogits\/gogs\/modules\/log\"\n\"github.com\/gogits\/gogs\/models\"\n\"github.com\/gogits\/gogs\/modules\/base\"\n\"github.com\/qiniu\/log\"\n\"github.com\/gogits\/git\"\n)\n\nvar CmdUpdate = cli.Command{\n\tName:  \"update\",\n\tUsage: \"This command just should be called by ssh shell\",\n\tDescription: `\ngogs serv provide access auth for repositories`,\n\tAction: runUpdate,\n\tFlags:  []cli.Flag{},\n}\n\n\/\/ for command: .\/gogs update\nfunc runUpdate(c *cli.Context) {\n\t\/\/level := \"0\"\n\t\/\/os.MkdirAll(\"log\", os.ModePerm)\n\t\/\/log.NewLogger(10000, \"file\", fmt.Sprintf(`{\"level\":%s,\"filename\":\"%s\"}`, level, \"log\/serv.log\"))\n\t\/\/log.Info(\"start update logging...\")\n\n\tw, _ := os.Create(\"update.log\")\n\tdefer w.Close()\n\n\tlog.SetOutput(w)\n\n\n\n\targs := c.Args()\n\tif len(args) != 3 {\n\t\tlog.Error(\"received less 3 parameters\")\n\t\treturn\n\t}\n\n\trefName := args[0]\n\toldCommitId := args[1]\n\tnewCommitId := args[2]\n\n\tuserName := os.Getenv(\"userName\")\n\tuserId := os.Getenv(\"userId\")\n\t\/\/repoId := os.Getenv(\"repoId\")\n\trepoName := os.Getenv(\"repoName\")\n\n\tlog.Info(\"username\", userName)\n\tlog.Info(\"repoName\", repoName)\n\tf := models.RepoPath(userName, repoName)\n\tlog.Debug(\"f\", f)\n\n\tgitUpdate := exec.Command(\"git\", \"update-server-info\")\n\tgitUpdate.Dir = f\n\tgitUpdate.Run()\n\n\trepo, err := git.OpenRepository(f)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Open repoId: %v\", err)\n\t\treturn\n\t}\n\n\tref, err := repo.LookupReference(refName)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Ref repoId: %v\", err)\n\t\treturn\n\t}\n\n\toldOid, err := git.NewOidFromString(oldCommitId)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Ref repoId: %v\", err)\n\t\treturn\n\t}\n\n\toldCommit, err := repo.LookupCommit(oldOid)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Ref repoId: %v\", err)\n\t\treturn\n\t}\n\n\tnewOid, err := git.NewOidFromString(newCommitId)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Ref repoId: %v\", err)\n\t\treturn\n\t}\n\n\tnewCommit, err := repo.LookupCommit(newOid)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Ref repoId: %v\", err)\n\t\treturn\n\t}\n\n\tvar l *list.List\n\t\/\/ if a new branch\n\tif strings.HasPrefix(oldCommitId, \"0000000\") {\n\t\tl, err = ref.AllCommits()\n\t\t\n\t} else {\n\t\tl = ref.CommitsBetween(newCommit, oldCommit)\n\t}\n\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Commit repoId: %v\", err)\n\t\treturn\n\t}\n\n\tsUserId, err := strconv.Atoi(userId)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Parse userId: %v\", err)\n\t\treturn\n\t}\n\n\trepos, err := models.GetRepositoryByName(int64(sUserId), repoName)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.GetRepositoryByName userId: %v\", err)\n\t\treturn\n\t}\n\n\tcommits := make([][]string, 0)\n\tvar maxCommits = 3\n\tfor e := l.Front(); e != nil; e = e.Next() {\n\t\tcommit := e.Value.(*git.Commit)\n\t\tcommits = append(commits, []string{commit.Id().String(), commit.Message()})\n\t\tif len(commits) >= maxCommits {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/commits = append(commits, []string{lastCommit.Id().String(), lastCommit.Message()})\n\tif err = models.CommitRepoAction(int64(sUserId), userName,\n\t\trepos.Id, repoName, refName, &base.PushCommits{l.Len(), commits}); err != nil {\n\t\tlog.Error(\"runUpdate.models.CommitRepoAction: %v\", err)\n\t}\n}\n<commit_msg>bug fixed<commit_after>\/\/ Copyright 2014 The Gogs Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\"os\"\n\"os\/exec\"\n\"strings\"\n\"strconv\"\n\"container\/list\"\n\n\"github.com\/codegangsta\/cli\"\n\/\/\"github.com\/gogits\/gogs\/modules\/log\"\n\"github.com\/gogits\/gogs\/models\"\n\"github.com\/gogits\/gogs\/modules\/base\"\n\"github.com\/qiniu\/log\"\n\"github.com\/gogits\/git\"\n)\n\nvar CmdUpdate = cli.Command{\n\tName:  \"update\",\n\tUsage: \"This command just should be called by ssh shell\",\n\tDescription: `\ngogs serv provide access auth for repositories`,\n\tAction: runUpdate,\n\tFlags:  []cli.Flag{},\n}\n\n\/\/ for command: .\/gogs update\nfunc runUpdate(c *cli.Context) {\n\t\/\/level := \"0\"\n\t\/\/os.MkdirAll(\"log\", os.ModePerm)\n\t\/\/log.NewLogger(10000, \"file\", fmt.Sprintf(`{\"level\":%s,\"filename\":\"%s\"}`, level, \"log\/serv.log\"))\n\t\/\/log.Info(\"start update logging...\")\n\n\tw, _ := os.Create(\"update.log\")\n\tdefer w.Close()\n\n\tlog.SetOutput(w)\n\n\n\n\targs := c.Args()\n\tif len(args) != 3 {\n\t\tlog.Error(\"received less 3 parameters\")\n\t\treturn\n\t}\n\n\trefName := args[0]\n\toldCommitId := args[1]\n\tnewCommitId := args[2]\n\n\tuserName := os.Getenv(\"userName\")\n\tuserId := os.Getenv(\"userId\")\n\t\/\/repoId := os.Getenv(\"repoId\")\n\trepoName := os.Getenv(\"repoName\")\n\n\tlog.Info(\"username\", userName)\n\tlog.Info(\"repoName\", repoName)\n\tf := models.RepoPath(userName, repoName)\n\tlog.Info(\"f\", f)\n\n\tgitUpdate := exec.Command(\"git\", \"update-server-info\")\n\tgitUpdate.Dir = f\n\tgitUpdate.Run()\n\n\trepo, err := git.OpenRepository(f)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Open repoId: %v\", err)\n\t\treturn\n\t}\n\n\tref, err := repo.LookupReference(refName)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Ref repoId: %v\", err)\n\t\treturn\n\t}\n\n\toldOid, err := git.NewOidFromString(oldCommitId)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Ref repoId: %v\", err)\n\t\treturn\n\t}\n\n\toldCommit, err := repo.LookupCommit(oldOid)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Ref repoId: %v\", err)\n\t\treturn\n\t}\n\n\tnewOid, err := git.NewOidFromString(newCommitId)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Ref repoId: %v\", err)\n\t\treturn\n\t}\n\n\tnewCommit, err := repo.LookupCommit(newOid)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Ref repoId: %v\", err)\n\t\treturn\n\t}\n\n\tvar l *list.List\n\t\/\/ if a new branch\n\tif strings.HasPrefix(oldCommitId, \"0000000\") {\n\t\tl, err = ref.AllCommits()\n\t\t\n\t} else {\n\t\tl = ref.CommitsBetween(newCommit, oldCommit)\n\t}\n\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Commit repoId: %v\", err)\n\t\treturn\n\t}\n\n\tsUserId, err := strconv.Atoi(userId)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.Parse userId: %v\", err)\n\t\treturn\n\t}\n\n\trepos, err := models.GetRepositoryByName(int64(sUserId), repoName)\n\tif err != nil {\n\t\tlog.Error(\"runUpdate.GetRepositoryByName userId: %v\", err)\n\t\treturn\n\t}\n\n\tcommits := make([][]string, 0)\n\tvar maxCommits = 3\n\tfor e := l.Front(); e != nil; e = e.Next() {\n\t\tcommit := e.Value.(*git.Commit)\n\t\tcommits = append(commits, []string{commit.Id().String(), commit.Message()})\n\t\tif len(commits) >= maxCommits {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/commits = append(commits, []string{lastCommit.Id().String(), lastCommit.Message()})\n\tif err = models.CommitRepoAction(int64(sUserId), userName,\n\t\trepos.Id, repoName, refName, &base.PushCommits{l.Len(), commits}); err != nil {\n\t\tlog.Error(\"runUpdate.models.CommitRepoAction: %v\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* {{{ Copyright (c) Paul R. Tagliamonte <paultag@gmail.com>, 2015\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE. }}} *\/\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n)\n\nfunc writeError(w http.ResponseWriter, message string, code int) error {\n\treturn writeJSON(w, map[string]string{\n\t\t\"message\": \"failure\",\n\t\t\"error\":   message,\n\t}, code)\n}\n\nfunc writeSuccess(w http.ResponseWriter, data interface{}, code int) error {\n\treturn writeJSON(w, data, 200)\n}\n\nfunc writeJSON(w http.ResponseWriter, data interface{}, code int) error {\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=UTF-8\")\n\tw.WriteHeader(code)\n\tif err := json.NewEncoder(w).Encode(data); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc HandlePUT(\n\tlog func(string, ...interface{}),\n\tconfig Deceive,\n\tw http.ResponseWriter,\n\tr *http.Request,\n\tclientName string,\n) {\n\tdefer log(\"End request\")\n\n\tlog(\"Incoming request to push to %s\", r.URL.Path)\n\tdir, fpath := path.Split(r.URL.Path)\n\tdir = path.Clean(path.Join(\"\/\", dir))\n\ttargetDir := path.Join(config.Root, dir)\n\n\tif _, err := os.Stat(targetDir); os.IsNotExist(err) {\n\t\tlog(\"Attempting to write to an unknown directory\")\n\t\twriteError(w, \"unknown archive\", 400)\n\t\treturn\n\t}\n\n\ttargetFile := path.Clean(path.Join(targetDir, fpath))\n\tif !strings.HasPrefix(targetFile, config.Root) {\n\t\tlog(\n\t\t\t\"Caught an attempt to write outside the root! Whoah! %s\",\n\t\t\ttargetFile, config.Root,\n\t\t)\n\t\twriteError(w, \"unknown archive\", 400) \/\/ Don't let the client know..\n\t\treturn\n\t}\n\n\tfd, err := os.Create(targetFile)\n\tif err != nil {\n\t\tlog(\"Error creating target: %s: %s\", targetFile, err)\n\t\twriteError(w, \"error creating target!\", 500)\n\t\treturn\n\t}\n\tdefer fd.Close()\n\n\tlog(\"Starting write to target filename\")\n\twritten, err := io.Copy(fd, r.Body)\n\tif err != nil {\n\t\tlog(\"Error writing to target: %s: %s\", targetFile, err)\n\t\twriteError(w, \"error writing to target!\", 500)\n\t\treturn\n\t}\n\tlog(\"Wrote %d bytes.\", written)\n\twriteSuccess(w, map[string]string{\n\t\t\"message\": fmt.Sprintf(\"Wrote %d bytes\", written),\n\t}, 200)\n}\n\nfunc HandleGET(\n\tlog func(string, ...interface{}),\n\tconfig Deceive,\n\tw http.ResponseWriter,\n\tr *http.Request,\n\tclientName string,\n) {\n\tdefer log(\"End request\")\n\tlog(\"GET request to: %s\", r.URL.Path)\n\twriteError(w, \"GET not supported yet.\", 400)\n\treturn\n}\n\nfunc HandleUpload(\n\tlog func(string, ...interface{}),\n\tconfig Deceive,\n\tw http.ResponseWriter,\n\tr *http.Request,\n\tclientName string,\n) {\n\tswitch r.Method {\n\tcase \"PUT\":\n\t\tHandlePUT(log, config, w, r, clientName)\n\tcase \"GET\":\n\t\tHandleGET(log, config, w, r, clientName)\n\tdefault:\n\t\tlog(\"Unknown method\\n\")\n\t\twriteError(w, \"Method not supported\", 400)\n\t}\n}\n\n\/\/ vim: foldmethod=marker\n<commit_msg>remove-newline<commit_after>\/* {{{ Copyright (c) Paul R. Tagliamonte <paultag@gmail.com>, 2015\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE. }}} *\/\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n)\n\nfunc writeError(w http.ResponseWriter, message string, code int) error {\n\treturn writeJSON(w, map[string]string{\n\t\t\"message\": \"failure\",\n\t\t\"error\":   message,\n\t}, code)\n}\n\nfunc writeSuccess(w http.ResponseWriter, data interface{}, code int) error {\n\treturn writeJSON(w, data, 200)\n}\n\nfunc writeJSON(w http.ResponseWriter, data interface{}, code int) error {\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=UTF-8\")\n\tw.WriteHeader(code)\n\tif err := json.NewEncoder(w).Encode(data); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc HandlePUT(\n\tlog func(string, ...interface{}),\n\tconfig Deceive,\n\tw http.ResponseWriter,\n\tr *http.Request,\n\tclientName string,\n) {\n\tdefer log(\"End request\")\n\n\tlog(\"Incoming request to push to %s\", r.URL.Path)\n\tdir, fpath := path.Split(r.URL.Path)\n\tdir = path.Clean(path.Join(\"\/\", dir))\n\ttargetDir := path.Join(config.Root, dir)\n\n\tif _, err := os.Stat(targetDir); os.IsNotExist(err) {\n\t\tlog(\"Attempting to write to an unknown directory\")\n\t\twriteError(w, \"unknown archive\", 400)\n\t\treturn\n\t}\n\n\ttargetFile := path.Clean(path.Join(targetDir, fpath))\n\tif !strings.HasPrefix(targetFile, config.Root) {\n\t\tlog(\n\t\t\t\"Caught an attempt to write outside the root! Whoah! %s\",\n\t\t\ttargetFile, config.Root,\n\t\t)\n\t\twriteError(w, \"unknown archive\", 400) \/\/ Don't let the client know..\n\t\treturn\n\t}\n\n\tfd, err := os.Create(targetFile)\n\tif err != nil {\n\t\tlog(\"Error creating target: %s: %s\", targetFile, err)\n\t\twriteError(w, \"error creating target!\", 500)\n\t\treturn\n\t}\n\tdefer fd.Close()\n\n\tlog(\"Starting write to target filename\")\n\twritten, err := io.Copy(fd, r.Body)\n\tif err != nil {\n\t\tlog(\"Error writing to target: %s: %s\", targetFile, err)\n\t\twriteError(w, \"error writing to target!\", 500)\n\t\treturn\n\t}\n\tlog(\"Wrote %d bytes.\", written)\n\twriteSuccess(w, map[string]string{\n\t\t\"message\": fmt.Sprintf(\"Wrote %d bytes\", written),\n\t}, 200)\n}\n\nfunc HandleGET(\n\tlog func(string, ...interface{}),\n\tconfig Deceive,\n\tw http.ResponseWriter,\n\tr *http.Request,\n\tclientName string,\n) {\n\tdefer log(\"End request\")\n\tlog(\"GET request to: %s\", r.URL.Path)\n\twriteError(w, \"GET not supported yet.\", 400)\n\treturn\n}\n\nfunc HandleUpload(\n\tlog func(string, ...interface{}),\n\tconfig Deceive,\n\tw http.ResponseWriter,\n\tr *http.Request,\n\tclientName string,\n) {\n\tswitch r.Method {\n\tcase \"PUT\":\n\t\tHandlePUT(log, config, w, r, clientName)\n\tcase \"GET\":\n\t\tHandleGET(log, config, w, r, clientName)\n\tdefault:\n\t\tlog(\"Unknown method\")\n\t\twriteError(w, \"Method not supported\", 400)\n\t}\n}\n\n\/\/ vim: foldmethod=marker\n<|endoftext|>"}
{"text":"<commit_before>package vangoh\n\nimport (\n\t\"bytes\"\n\t\"crypto\"\n\t\"crypto\/hmac\"\n\t_ \"crypto\/sha256\"\n\t\"crypto\/subtle\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"hash\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\t\"unsafe\"\n)\n\n\/\/ Expected regex format of the Authorization signature.\n\/\/\n\/\/ An authorization signature consists of three parts:\n\/\/\n\/\/ \tAuthorization: [ORG] [KEY]:[HMAC_SIGNATURE]\n\/\/\n\/\/ The first component is an organizational tag, which must consist of at least\n\/\/ one character, and has a valid character set of alphanumeric characters and\n\/\/ underscores.\n\/\/\n\/\/ This should be followed by a single space, and then the key, which also must\n\/\/ consist of one or more alphanumeric characters and\/or underscores.\n\/\/\n\/\/ The key must be followed by a single colon ':' character, and then the\n\/\/ signature, encoded in Base64 (valid characters being all alphanumeric, plus\n\/\/ \"+\", forward slash \"\/\", and equals sign \"=\" as padding on the end if\n\/\/ needed.)\n\/\/\n\/\/ Any leading or trailing whitespace around the header will be trimmed before\n\/\/ validation.\nconst AuthRegex = \"^[A-Za-z0-9_]+ [A-Za-z0-9_\/+]+:\" +\n\t\"(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$\"\n\n\/\/ Newline character, definited in unicode, to avoid platform dependence.\nconst newline = \"\\u000A\"\n\n\/\/ Vangoh is an object that forms the primary point of configuration of the\n\/\/ middleware HMAC handler. It allows for the configuration of the hashing\n\/\/ function to use, the headers (specified as regexes) to be included in the\n\/\/ computed signature, and the mapping between organization tags and the secret\n\/\/ key providers associated with them.\ntype Vangoh struct {\n\t\/\/ Indicates if there is one global provider for this HMAC checker. If set to\n\t\/\/ a non-nil pointer to a secretProvider, Vangoh will authenticate all\n\t\/\/ requests against this provider regardless of organization specified in the\n\t\/\/ request's Authorization header.\n\tsingleProvider *secretProvider\n\n\t\/\/ A map between org tags, as used in the Authentication section, with the\n\t\/\/ secretProvider that provides the identities for that org.\n\tprovidersByOrg map[string]secretProvider\n\n\t\/\/ The hashing function to be used when computing the HMAC hashes.  Common\n\t\/\/ algorithms for HMAC include SHA1, SHA256, and MD5, but any object that\n\t\/\/ implements hash.Hash should work.\n\talgorithm func() hash.Hash\n\n\t\/\/ Specifies which headers should be used in computing the HMAC signature for\n\t\/\/ each request.  It is common to have an application-wide prefix for headers\n\t\/\/ to be used, i.e. X-Aur-Meta-User or X-Aur-Locale.  This could be\n\t\/\/ represented with the include header \"^X-Aur-\".\n\tincludedHeaders map[string]*regexp.Regexp\n\n\t\/\/ The maximum amount of time that can have passed between the time a request\n\t\/\/ was signed and the time the request was received by the server.\n\tmaxTimeSkew time.Duration\n\n\t\/\/ When true, Handler() includes specific error details in the response when\n\t\/\/ denying incorrectly-authenticated requests.\n\tdebug bool\n}\n\n\/\/ Creates a new Vangoh instance with no secret providers.\nfunc New() *Vangoh {\n\treturn &Vangoh{\n\t\tsingleProvider:  nil,\n\t\tprovidersByOrg:  make(map[string]secretProvider),\n\t\talgorithm:       crypto.SHA256.New,\n\t\tincludedHeaders: make(map[string]*regexp.Regexp),\n\t\tmaxTimeSkew:     time.Minute * 15,\n\t\tdebug:           false,\n\t}\n}\n\n\/\/ Creates a new Vangoh instance that supports a single\n\/\/ secretProvider. Attempting to add providers with AddProvider will fail with an\n\/\/ error.\nfunc NewSingleProvider(provider secretProvider) *Vangoh {\n\tvg := New()\n\tvg.singleProvider = &provider\n\treturn vg\n}\n\n\/*\nAddProvider sets the secret provider of a specific organization. If the Vangoh\ninstance was created to use a single provider for all requests, regardless of\norganization tag, calling AddProvider will fail and return an error. If the\norganization already has a provider, calling AddProvider will fail and return\nan error.\n\nBy supporting different providers based on org tags, there is the ability to\nconfigure authentication sources based on user type or purpose. For instance,\nif an endpoint is going to be used by both a small set of internal services as\nwell as external users, you could create a different provider for each, as\ndemonstrated below.\n\nExample:\n\tfunc main() {\n\t\t\/\/ Create provider for internal services credentials (not included with Vangoh).\n\t\tinternalProvider := providers.NewInMemoryProvider(...)\n\t\t\/\/ Create provider for normal user credentials (not included with Vangoh).\n\t\tuserProvider := providers.NewDatabaseProvider(...)\n\n\t\tvg := vangoh.New()\n\t\t_ = vg.AddProvider(\"INT\", internalProvider)\n\t\t_ = vg.AddProvider(\"API\", userProvider)\n\n\t\t\/\/ ...\n\t}\n\nIn this example, any connections made with the authorization header \"INT\n[userID]:[signature]\" will be authenticated against `internalProvider`, and\nconnections with the header \"API [userID]:[signature]\" will be authenticated\nagainst `userProvider`.\n*\/\nfunc (vg *Vangoh) AddProvider(org string, skp secretProvider) error {\n\tif vg.singleProvider != nil {\n\t\treturn errors.New(\"cannot add a provider when created for a single provider\")\n\t}\n\tif _, ok := vg.providersByOrg[org]; ok {\n\t\treturn errors.New(\"cannot add more than one keyProvider for the same org tag\")\n\t}\n\tvg.providersByOrg[org] = skp\n\treturn nil\n}\n\nfunc (vg *Vangoh) SetAlgorithm(algorithm func() hash.Hash) {\n\tvg.algorithm = algorithm\n}\n\nfunc (vg *Vangoh) SetDebug(debug bool) {\n\tvg.debug = debug\n}\n\n\/*\nIncludeHeader specifies additional headers to include in the construction of\nthe HMAC signature body for a request.\n\nGiven a regex, any non-canonical (e.g. \"X-Aur\", not \"x-aur\") headers that match the\nregex will be included.\n\nFor instance, to match all headers beginning with \"X-Aur-\", we could include\nthe header regex \"X-Aur-.*\".  It is important to note that this funcationality\nuses traditional, non-POSIX regular expressions, and will add anchoring to the\nprovided regex if it is not included.\n\nThis means that the regex \"X-Aur\" will only match headers with key \"X-Aur\"\nexactly.  In order to do prefix matching you must add a wildcard match after,\ni.e. \"X-Aur.*\"\n*\/\nfunc (vg *Vangoh) IncludeHeader(headerRegex string) error {\n\tvar regexBuf bytes.Buffer\n\tif !strings.HasPrefix(headerRegex, \"^\") {\n\t\tregexBuf.WriteString(\"^\")\n\t}\n\tregexBuf.WriteString(headerRegex)\n\tif !strings.HasSuffix(headerRegex, \"$\") {\n\t\tregexBuf.WriteString(\"$\")\n\t}\n\n\tregex := regexBuf.String()\n\tcompiled, err := regexp.Compile(regex)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvg.includedHeaders[regex] = compiled\n\treturn nil\n}\n\n\/*\nSetMaxTimeSkew sets the maximum allowable duration between the date and time specified\nin the Date header and the server time when the response is processed.  If the date in\nthe header exceeds the duration Vangoh will respond to the request with a HTTP status 403 Forbidden.\n\nTo match the behavior of AWS (15 minute skew window):\n\tvg := vangoh.New()\n\tvg.SetMaxTimeSkew(time.Minute * 15)\n\nWhen checking the date header, Vangoh follows the precedent of RFC 2616,\naccepting dates in any of the following formats:\n\tANSIC    = \"Mon Jan _2 15:04:05 2006\"\n\tRFC822   = \"02 Jan 06 15:04 MST\"\n\tRFC822Z  = \"02 Jan 06 15:04 -0700\"\n\tRFC850   = \"Monday, 02-Jan-06 15:04:05 MST\"\n\tRFC1123  = \"Mon, 02 Jan 2006 15:04:05 MST\"\n\tRFC1123Z = \"Mon, 02 Jan 2006 15:04:05 -0700\"\n*\/\nfunc (vg *Vangoh) SetMaxTimeSkew(timeSkew time.Duration) {\n\tvg.maxTimeSkew = timeSkew\n}\n\n\/\/ Checks a request for proper authentication details, returning the relevent\n\/\/ error if the request fails this check or nil if the request passes.\nfunc (vg *Vangoh) AuthenticateRequest(r *http.Request) *AuthenticationError {\n\t\/\/ Parse the ORG, KEY, and SIGNATURE out of the Authorization header.\n\tauthHeader := strings.TrimSpace(r.Header.Get(\"Authorization\"))\n\tif authHeader == \"\" {\n\t\treturn ErrorAuthHeaderMissing\n\t}\n\tmatch, err := regexp.Match(AuthRegex, []byte(authHeader))\n\tif err != nil || !match {\n\t\treturn ErrorAuthHeaderMalformed\n\t}\n\torgSplit := strings.Split(authHeader, \" \")\n\torg := orgSplit[0]\n\tkeySplit := strings.Split(orgSplit[1], \":\")\n\tkey := []byte(keySplit[0])\n\tactualSignatureB64 := keySplit[1]\n\n\t\/\/ Check that the request was made in the acceptable window.\n\tdateHeader := strings.TrimSpace(r.Header.Get(\"Date\"))\n\tif dateHeader == \"\" {\n\t\treturn ErrorDateHeaderMissing\n\t}\n\tdate, err := multiFormatDateParse(\n\t\t\/\/ TODO: break out into const.\n\t\t[]string{\n\t\t\ttime.RFC822,\n\t\t\ttime.RFC822Z,\n\t\t\ttime.RFC850,\n\t\t\ttime.ANSIC,\n\t\t\ttime.RFC1123,\n\t\t\ttime.RFC1123Z},\n\t\tdateHeader)\n\tif err != nil {\n\t\treturn ErrorDateHeaderMalformed\n\t}\n\tpresent := clock.Now()\n\tif present.Sub(date) > vg.maxTimeSkew || date.Sub(present) > vg.maxTimeSkew {\n\t\treturn ErrorDateHeaderTooSkewed\n\t}\n\n\t\/\/ Load the secret key from the appropriate key provider, given the ID from\n\t\/\/ the Authorization header.\n\tvar provider secretProvider\n\tif vg.singleProvider != nil {\n\t\tprovider = *vg.singleProvider\n\t} else {\n\t\tvar exists bool\n\t\tprovider, exists = vg.providersByOrg[org]\n\t\tif !exists {\n\t\t\treturn ErrorAuthOrgUnknown\n\t\t}\n\t}\n\n\tvar voidPtr unsafe.Pointer = nil\n\tvar secret []byte\n\n\tswitch provider := provider.(type) {\n\tcase SecretProviderWithCallback:\n\t\tsecret, err = provider.GetSecret(key, &voidPtr)\n\tcase SecretProvider:\n\t\tsecret, err = provider.GetSecret(key)\n\t}\n\tif err != nil {\n\t\treturn ErrorInProviderKeyLookup\n\t}\n\tif secret == nil {\n\t\treturn ErrorSecretNotFound\n\t}\n\n\t\/\/ Calculate the b64 signature and compare against the one sent by the client.\n\texpectedSignature := vg.ConstructSignature(r, secret)\n\texpectedSignatureB64 := base64.StdEncoding.EncodeToString(expectedSignature)\n\tif subtle.ConstantTimeCompare([]byte(expectedSignatureB64), []byte(actualSignatureB64)) != 1 {\n\t\treturn ErrorHMACSignatureMismatch\n\t}\n\n\tswitch provider := provider.(type) {\n\tcase SecretProviderWithCallback:\n\t\tif voidPtr != nil {\n\t\t\tprovider.SuccessCallback(r, &voidPtr)\n\t\t} else {\n\t\t\tprovider.SuccessCallback(r, nil)\n\t\t}\n\t}\n\t\/\/ If we have made it this far, authentication is successful.\n\treturn nil\n}\n\nfunc (vg *Vangoh) ConstructSignature(r *http.Request, secret []byte) []byte {\n\tsigningString := vg.CreateSigningString(r)\n\tmac := hmac.New(vg.algorithm, secret)\n\tmac.Write([]byte(signingString))\n\treturn mac.Sum(nil)\n}\n\nfunc multiFormatDateParse(formats []string, dateStr string) (time.Time, error) {\n\tfor index := range formats {\n\t\tif date, err := time.Parse(formats[index], dateStr); err == nil {\n\t\t\treturn date, nil\n\t\t}\n\t}\n\treturn time.Time{}, errors.New(\"Date does not match any valid format\")\n}\n\n\/*\nCreateSigningString creates the string used for signature generation, in accordance with\nthe specifications as laid out in the package documentation. Refer there for more detail,\nor to the Amazon Signature V2 documentation: http:\/\/docs.aws.amazon.com\/AmazonS3\/latest\/dev\/RESTAuthentication.html.\n*\/\nfunc (vg *Vangoh) CreateSigningString(r *http.Request) string {\n\tvar buffer bytes.Buffer\n\n\tbuffer.WriteString(r.Method)\n\tbuffer.WriteString(newline)\n\n\tbuffer.WriteString(r.Header.Get(\"Content-MD5\"))\n\tbuffer.WriteString(newline)\n\n\tbuffer.WriteString(r.Header.Get(\"Content-Type\"))\n\tbuffer.WriteString(newline)\n\n\tbuffer.WriteString(r.Header.Get(\"Date\"))\n\tbuffer.WriteString(newline)\n\n\tcustomHeaders := vg.createHeadersString(r)\n\tbuffer.WriteString(customHeaders)\n\n\tbuffer.WriteString(r.URL.Path)\n\n\treturn buffer.String()\n}\n\n\/\/ Create the canonicalized header string part of a request's signature body.\nfunc (vg *Vangoh) createHeadersString(r *http.Request) string {\n\tif len(vg.includedHeaders) == 0 {\n\t\treturn \"\"\n\t}\n\n\t\/\/ For each defined regex, determine the set of headers that match. Repeat\n\t\/\/ for all regexes, without duplication, to get the final set of custom\n\t\/\/ headers to use.\n\tvar sanitizedHeaders = make(map[string][]string)\n\n\tfor _, compiledRegex := range vg.includedHeaders {\n\t\tfor header := range r.Header {\n\t\t\tlowerHeader := strings.ToLower(header)\n\t\t\tif _, found := sanitizedHeaders[lowerHeader]; found {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif compiledRegex.MatchString(header) {\n\t\t\t\tsanitizedHeaders[lowerHeader] = r.Header[header]\n\t\t\t}\n\t\t}\n\t}\n\n\tvar orderedHeaders []string\n\tfor header := range sanitizedHeaders {\n\t\torderedHeaders = append(orderedHeaders, header)\n\t}\n\tsort.Strings(orderedHeaders)\n\n\t\/\/ At this point sanitized contains all the headers to be included in the\n\t\/\/ hash. Now we need to retrieve their values, and sanitize them\n\t\/\/ appropriately.\n\tvar buffer bytes.Buffer\n\tfor header := range orderedHeaders {\n\t\tbuffer.WriteString(orderedHeaders[header])\n\t\tbuffer.WriteString(\":\")\n\n\t\tvar sanitizedValues []string\n\t\tfor i := range sanitizedHeaders[orderedHeaders[header]] {\n\t\t\tstr := sanitizedHeaders[orderedHeaders[header]][i]\n\t\t\tstr = strings.TrimSpace(str)\n\t\t\tstr = strings.Replace(str, \"\\n\", \"\", -1)\n\t\t\tsanitizedValues = append(sanitizedValues, str)\n\t\t}\n\n\t\t\/\/ Note that sanitizedValues are unsorted here - the order that they are\n\t\t\/\/ specified in the header will affect the hash result. This conforms with\n\t\t\/\/ the standard set by AWS, though it may be more reliable to add this\n\t\t\/\/ sorting in at some point.\n\t\tfor i := range sanitizedValues {\n\t\t\tbuffer.WriteString(sanitizedValues[i])\n\t\t\tif i < (len(sanitizedValues) - 1) {\n\t\t\t\tbuffer.WriteString(\",\")\n\t\t\t}\n\t\t}\n\n\t\tbuffer.WriteString(newline)\n\t}\n\n\treturn buffer.String()\n}\n<commit_msg>Fix typo.<commit_after>package vangoh\n\nimport (\n\t\"bytes\"\n\t\"crypto\"\n\t\"crypto\/hmac\"\n\t_ \"crypto\/sha256\"\n\t\"crypto\/subtle\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"hash\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\t\"unsafe\"\n)\n\n\/\/ Expected regex format of the Authorization signature.\n\/\/\n\/\/ An authorization signature consists of three parts:\n\/\/\n\/\/ \tAuthorization: [ORG] [KEY]:[HMAC_SIGNATURE]\n\/\/\n\/\/ The first component is an organizational tag, which must consist of at least\n\/\/ one character, and has a valid character set of alphanumeric characters and\n\/\/ underscores.\n\/\/\n\/\/ This should be followed by a single space, and then the key, which also must\n\/\/ consist of one or more alphanumeric characters and\/or underscores.\n\/\/\n\/\/ The key must be followed by a single colon ':' character, and then the\n\/\/ signature, encoded in Base64 (valid characters being all alphanumeric, plus\n\/\/ \"+\", forward slash \"\/\", and equals sign \"=\" as padding on the end if\n\/\/ needed.)\n\/\/\n\/\/ Any leading or trailing whitespace around the header will be trimmed before\n\/\/ validation.\nconst AuthRegex = \"^[A-Za-z0-9_]+ [A-Za-z0-9_\/+]+:\" +\n\t\"(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$\"\n\n\/\/ Newline character, defined in unicode to avoid platform dependence.\nconst newline = \"\\u000A\"\n\n\/\/ Vangoh is an object that forms the primary point of configuration of the\n\/\/ middleware HMAC handler. It allows for the configuration of the hashing\n\/\/ function to use, the headers (specified as regexes) to be included in the\n\/\/ computed signature, and the mapping between organization tags and the secret\n\/\/ key providers associated with them.\ntype Vangoh struct {\n\t\/\/ Indicates if there is one global provider for this HMAC checker. If set to\n\t\/\/ a non-nil pointer to a secretProvider, Vangoh will authenticate all\n\t\/\/ requests against this provider regardless of organization specified in the\n\t\/\/ request's Authorization header.\n\tsingleProvider *secretProvider\n\n\t\/\/ A map between org tags, as used in the Authentication section, with the\n\t\/\/ secretProvider that provides the identities for that org.\n\tprovidersByOrg map[string]secretProvider\n\n\t\/\/ The hashing function to be used when computing the HMAC hashes.  Common\n\t\/\/ algorithms for HMAC include SHA1, SHA256, and MD5, but any object that\n\t\/\/ implements hash.Hash should work.\n\talgorithm func() hash.Hash\n\n\t\/\/ Specifies which headers should be used in computing the HMAC signature for\n\t\/\/ each request.  It is common to have an application-wide prefix for headers\n\t\/\/ to be used, i.e. X-Aur-Meta-User or X-Aur-Locale.  This could be\n\t\/\/ represented with the include header \"^X-Aur-\".\n\tincludedHeaders map[string]*regexp.Regexp\n\n\t\/\/ The maximum amount of time that can have passed between the time a request\n\t\/\/ was signed and the time the request was received by the server.\n\tmaxTimeSkew time.Duration\n\n\t\/\/ When true, Handler() includes specific error details in the response when\n\t\/\/ denying incorrectly-authenticated requests.\n\tdebug bool\n}\n\n\/\/ Creates a new Vangoh instance with no secret providers.\nfunc New() *Vangoh {\n\treturn &Vangoh{\n\t\tsingleProvider:  nil,\n\t\tprovidersByOrg:  make(map[string]secretProvider),\n\t\talgorithm:       crypto.SHA256.New,\n\t\tincludedHeaders: make(map[string]*regexp.Regexp),\n\t\tmaxTimeSkew:     time.Minute * 15,\n\t\tdebug:           false,\n\t}\n}\n\n\/\/ Creates a new Vangoh instance that supports a single\n\/\/ secretProvider. Attempting to add providers with AddProvider will fail with an\n\/\/ error.\nfunc NewSingleProvider(provider secretProvider) *Vangoh {\n\tvg := New()\n\tvg.singleProvider = &provider\n\treturn vg\n}\n\n\/*\nAddProvider sets the secret provider of a specific organization. If the Vangoh\ninstance was created to use a single provider for all requests, regardless of\norganization tag, calling AddProvider will fail and return an error. If the\norganization already has a provider, calling AddProvider will fail and return\nan error.\n\nBy supporting different providers based on org tags, there is the ability to\nconfigure authentication sources based on user type or purpose. For instance,\nif an endpoint is going to be used by both a small set of internal services as\nwell as external users, you could create a different provider for each, as\ndemonstrated below.\n\nExample:\n\tfunc main() {\n\t\t\/\/ Create provider for internal services credentials (not included with Vangoh).\n\t\tinternalProvider := providers.NewInMemoryProvider(...)\n\t\t\/\/ Create provider for normal user credentials (not included with Vangoh).\n\t\tuserProvider := providers.NewDatabaseProvider(...)\n\n\t\tvg := vangoh.New()\n\t\t_ = vg.AddProvider(\"INT\", internalProvider)\n\t\t_ = vg.AddProvider(\"API\", userProvider)\n\n\t\t\/\/ ...\n\t}\n\nIn this example, any connections made with the authorization header \"INT\n[userID]:[signature]\" will be authenticated against `internalProvider`, and\nconnections with the header \"API [userID]:[signature]\" will be authenticated\nagainst `userProvider`.\n*\/\nfunc (vg *Vangoh) AddProvider(org string, skp secretProvider) error {\n\tif vg.singleProvider != nil {\n\t\treturn errors.New(\"cannot add a provider when created for a single provider\")\n\t}\n\tif _, ok := vg.providersByOrg[org]; ok {\n\t\treturn errors.New(\"cannot add more than one keyProvider for the same org tag\")\n\t}\n\tvg.providersByOrg[org] = skp\n\treturn nil\n}\n\nfunc (vg *Vangoh) SetAlgorithm(algorithm func() hash.Hash) {\n\tvg.algorithm = algorithm\n}\n\nfunc (vg *Vangoh) SetDebug(debug bool) {\n\tvg.debug = debug\n}\n\n\/*\nIncludeHeader specifies additional headers to include in the construction of\nthe HMAC signature body for a request.\n\nGiven a regex, any non-canonical (e.g. \"X-Aur\", not \"x-aur\") headers that match the\nregex will be included.\n\nFor instance, to match all headers beginning with \"X-Aur-\", we could include\nthe header regex \"X-Aur-.*\".  It is important to note that this funcationality\nuses traditional, non-POSIX regular expressions, and will add anchoring to the\nprovided regex if it is not included.\n\nThis means that the regex \"X-Aur\" will only match headers with key \"X-Aur\"\nexactly.  In order to do prefix matching you must add a wildcard match after,\ni.e. \"X-Aur.*\"\n*\/\nfunc (vg *Vangoh) IncludeHeader(headerRegex string) error {\n\tvar regexBuf bytes.Buffer\n\tif !strings.HasPrefix(headerRegex, \"^\") {\n\t\tregexBuf.WriteString(\"^\")\n\t}\n\tregexBuf.WriteString(headerRegex)\n\tif !strings.HasSuffix(headerRegex, \"$\") {\n\t\tregexBuf.WriteString(\"$\")\n\t}\n\n\tregex := regexBuf.String()\n\tcompiled, err := regexp.Compile(regex)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvg.includedHeaders[regex] = compiled\n\treturn nil\n}\n\n\/*\nSetMaxTimeSkew sets the maximum allowable duration between the date and time specified\nin the Date header and the server time when the response is processed.  If the date in\nthe header exceeds the duration Vangoh will respond to the request with a HTTP status 403 Forbidden.\n\nTo match the behavior of AWS (15 minute skew window):\n\tvg := vangoh.New()\n\tvg.SetMaxTimeSkew(time.Minute * 15)\n\nWhen checking the date header, Vangoh follows the precedent of RFC 2616,\naccepting dates in any of the following formats:\n\tANSIC    = \"Mon Jan _2 15:04:05 2006\"\n\tRFC822   = \"02 Jan 06 15:04 MST\"\n\tRFC822Z  = \"02 Jan 06 15:04 -0700\"\n\tRFC850   = \"Monday, 02-Jan-06 15:04:05 MST\"\n\tRFC1123  = \"Mon, 02 Jan 2006 15:04:05 MST\"\n\tRFC1123Z = \"Mon, 02 Jan 2006 15:04:05 -0700\"\n*\/\nfunc (vg *Vangoh) SetMaxTimeSkew(timeSkew time.Duration) {\n\tvg.maxTimeSkew = timeSkew\n}\n\n\/\/ Checks a request for proper authentication details, returning the relevent\n\/\/ error if the request fails this check or nil if the request passes.\nfunc (vg *Vangoh) AuthenticateRequest(r *http.Request) *AuthenticationError {\n\t\/\/ Parse the ORG, KEY, and SIGNATURE out of the Authorization header.\n\tauthHeader := strings.TrimSpace(r.Header.Get(\"Authorization\"))\n\tif authHeader == \"\" {\n\t\treturn ErrorAuthHeaderMissing\n\t}\n\tmatch, err := regexp.Match(AuthRegex, []byte(authHeader))\n\tif err != nil || !match {\n\t\treturn ErrorAuthHeaderMalformed\n\t}\n\torgSplit := strings.Split(authHeader, \" \")\n\torg := orgSplit[0]\n\tkeySplit := strings.Split(orgSplit[1], \":\")\n\tkey := []byte(keySplit[0])\n\tactualSignatureB64 := keySplit[1]\n\n\t\/\/ Check that the request was made in the acceptable window.\n\tdateHeader := strings.TrimSpace(r.Header.Get(\"Date\"))\n\tif dateHeader == \"\" {\n\t\treturn ErrorDateHeaderMissing\n\t}\n\tdate, err := multiFormatDateParse(\n\t\t\/\/ TODO: break out into const.\n\t\t[]string{\n\t\t\ttime.RFC822,\n\t\t\ttime.RFC822Z,\n\t\t\ttime.RFC850,\n\t\t\ttime.ANSIC,\n\t\t\ttime.RFC1123,\n\t\t\ttime.RFC1123Z},\n\t\tdateHeader)\n\tif err != nil {\n\t\treturn ErrorDateHeaderMalformed\n\t}\n\tpresent := clock.Now()\n\tif present.Sub(date) > vg.maxTimeSkew || date.Sub(present) > vg.maxTimeSkew {\n\t\treturn ErrorDateHeaderTooSkewed\n\t}\n\n\t\/\/ Load the secret key from the appropriate key provider, given the ID from\n\t\/\/ the Authorization header.\n\tvar provider secretProvider\n\tif vg.singleProvider != nil {\n\t\tprovider = *vg.singleProvider\n\t} else {\n\t\tvar exists bool\n\t\tprovider, exists = vg.providersByOrg[org]\n\t\tif !exists {\n\t\t\treturn ErrorAuthOrgUnknown\n\t\t}\n\t}\n\n\tvar voidPtr unsafe.Pointer = nil\n\tvar secret []byte\n\n\tswitch provider := provider.(type) {\n\tcase SecretProviderWithCallback:\n\t\tsecret, err = provider.GetSecret(key, &voidPtr)\n\tcase SecretProvider:\n\t\tsecret, err = provider.GetSecret(key)\n\t}\n\tif err != nil {\n\t\treturn ErrorInProviderKeyLookup\n\t}\n\tif secret == nil {\n\t\treturn ErrorSecretNotFound\n\t}\n\n\t\/\/ Calculate the b64 signature and compare against the one sent by the client.\n\texpectedSignature := vg.ConstructSignature(r, secret)\n\texpectedSignatureB64 := base64.StdEncoding.EncodeToString(expectedSignature)\n\tif subtle.ConstantTimeCompare([]byte(expectedSignatureB64), []byte(actualSignatureB64)) != 1 {\n\t\treturn ErrorHMACSignatureMismatch\n\t}\n\n\tswitch provider := provider.(type) {\n\tcase SecretProviderWithCallback:\n\t\tif voidPtr != nil {\n\t\t\tprovider.SuccessCallback(r, &voidPtr)\n\t\t} else {\n\t\t\tprovider.SuccessCallback(r, nil)\n\t\t}\n\t}\n\t\/\/ If we have made it this far, authentication is successful.\n\treturn nil\n}\n\nfunc (vg *Vangoh) ConstructSignature(r *http.Request, secret []byte) []byte {\n\tsigningString := vg.CreateSigningString(r)\n\tmac := hmac.New(vg.algorithm, secret)\n\tmac.Write([]byte(signingString))\n\treturn mac.Sum(nil)\n}\n\nfunc multiFormatDateParse(formats []string, dateStr string) (time.Time, error) {\n\tfor index := range formats {\n\t\tif date, err := time.Parse(formats[index], dateStr); err == nil {\n\t\t\treturn date, nil\n\t\t}\n\t}\n\treturn time.Time{}, errors.New(\"Date does not match any valid format\")\n}\n\n\/*\nCreateSigningString creates the string used for signature generation, in accordance with\nthe specifications as laid out in the package documentation. Refer there for more detail,\nor to the Amazon Signature V2 documentation: http:\/\/docs.aws.amazon.com\/AmazonS3\/latest\/dev\/RESTAuthentication.html.\n*\/\nfunc (vg *Vangoh) CreateSigningString(r *http.Request) string {\n\tvar buffer bytes.Buffer\n\n\tbuffer.WriteString(r.Method)\n\tbuffer.WriteString(newline)\n\n\tbuffer.WriteString(r.Header.Get(\"Content-MD5\"))\n\tbuffer.WriteString(newline)\n\n\tbuffer.WriteString(r.Header.Get(\"Content-Type\"))\n\tbuffer.WriteString(newline)\n\n\tbuffer.WriteString(r.Header.Get(\"Date\"))\n\tbuffer.WriteString(newline)\n\n\tcustomHeaders := vg.createHeadersString(r)\n\tbuffer.WriteString(customHeaders)\n\n\tbuffer.WriteString(r.URL.Path)\n\n\treturn buffer.String()\n}\n\n\/\/ Create the canonicalized header string part of a request's signature body.\nfunc (vg *Vangoh) createHeadersString(r *http.Request) string {\n\tif len(vg.includedHeaders) == 0 {\n\t\treturn \"\"\n\t}\n\n\t\/\/ For each defined regex, determine the set of headers that match. Repeat\n\t\/\/ for all regexes, without duplication, to get the final set of custom\n\t\/\/ headers to use.\n\tvar sanitizedHeaders = make(map[string][]string)\n\n\tfor _, compiledRegex := range vg.includedHeaders {\n\t\tfor header := range r.Header {\n\t\t\tlowerHeader := strings.ToLower(header)\n\t\t\tif _, found := sanitizedHeaders[lowerHeader]; found {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif compiledRegex.MatchString(header) {\n\t\t\t\tsanitizedHeaders[lowerHeader] = r.Header[header]\n\t\t\t}\n\t\t}\n\t}\n\n\tvar orderedHeaders []string\n\tfor header := range sanitizedHeaders {\n\t\torderedHeaders = append(orderedHeaders, header)\n\t}\n\tsort.Strings(orderedHeaders)\n\n\t\/\/ At this point sanitized contains all the headers to be included in the\n\t\/\/ hash. Now we need to retrieve their values, and sanitize them\n\t\/\/ appropriately.\n\tvar buffer bytes.Buffer\n\tfor header := range orderedHeaders {\n\t\tbuffer.WriteString(orderedHeaders[header])\n\t\tbuffer.WriteString(\":\")\n\n\t\tvar sanitizedValues []string\n\t\tfor i := range sanitizedHeaders[orderedHeaders[header]] {\n\t\t\tstr := sanitizedHeaders[orderedHeaders[header]][i]\n\t\t\tstr = strings.TrimSpace(str)\n\t\t\tstr = strings.Replace(str, \"\\n\", \"\", -1)\n\t\t\tsanitizedValues = append(sanitizedValues, str)\n\t\t}\n\n\t\t\/\/ Note that sanitizedValues are unsorted here - the order that they are\n\t\t\/\/ specified in the header will affect the hash result. This conforms with\n\t\t\/\/ the standard set by AWS, though it may be more reliable to add this\n\t\t\/\/ sorting in at some point.\n\t\tfor i := range sanitizedValues {\n\t\t\tbuffer.WriteString(sanitizedValues[i])\n\t\t\tif i < (len(sanitizedValues) - 1) {\n\t\t\t\tbuffer.WriteString(\",\")\n\t\t\t}\n\t\t}\n\n\t\tbuffer.WriteString(newline)\n\t}\n\n\treturn buffer.String()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/api\/types\/container\"\n\t\"github.com\/docker\/docker\/api\/types\/network\"\n\t\"github.com\/docker\/docker\/client\"\n\t\"github.com\/pkg\/errors\"\n)\n\nvar stageMutexes []*sync.Mutex\nvar completedConditions []*sync.Cond\nvar completedStages []bool\nvar stageIndex map[string]int\n\nfunc run(c *client.Client, p *Pipeline, rootpath, filename string) error {\n\t\/\/ generate a version number\/name if the pipeline description didn't\n\tif p.Version == \"\" {\n\t\tp.Version = createName()\n\t}\n\n\tstageMutexes = make([]*sync.Mutex, len(p.Stages))\n\tcompletedConditions = make([]*sync.Cond, len(p.Stages))\n\tcompletedStages = make([]bool, len(p.Stages))\n\n\tfor i := range stageMutexes {\n\t\tstageMutexes[i] = &sync.Mutex{}\n\t\tcompletedConditions[i] = sync.NewCond(stageMutexes[i])\n\t}\n\n\tstageIndex = make(map[string]int, len(p.Stages))\n\n\t\/\/ Name to index mapping\n\tfor i, stage := range p.Stages {\n\t\tstageIndex[stage.Name] = i\n\t}\n\n\te := make(chan error, len(p.Stages))\n\n\tfor i, stage := range p.Stages {\n\t\tgo func(i int, stage *Stage) {\n\t\t\tmountpath := \"\/walrus\/\" + stage.Name\n\t\t\thostpath := rootpath + \"\/\" + stage.Name\n\n\t\t\trepo, tag := getRepoAndTag(stage.Image)\n\t\t\timage := repo + \":\" + tag\n\t\t\t_, err := c.ImagePull(context.Background(), image, types.ImagePullOptions{})\n\t\t\tif err != nil {\n\t\t\t\te <- errors.Wrap(err, \"Could not pull image\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ If the stage has any inputs it waits for these stages to complete\n\t\t\t\/\/ before starting\n\t\t\tif len(stage.Inputs) > 0 {\n\t\t\t\tfor _, input := range stage.Inputs {\n\t\t\t\t\tindex := stageIndex[input]\n\t\t\t\t\tcond := completedConditions[index]\n\t\t\t\t\tcond.L.Lock()\n\t\t\t\t\tfor !completedStages[index] {\n\t\t\t\t\t\tcond.Wait()\n\t\t\t\t\t}\n\t\t\t\t\tcond.L.Unlock()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ try to open output directory, if it exists then we can serve the\n\t\t\t\/\/ \"cached\"\/old results\n\t\t\t_, err = os.Open(hostpath)\n\n\t\t\tif !stage.Cache || err != nil {\n\n\t\t\t\t\/\/ first remove any previous container (note that we're ignoring\n\t\t\t\t\/\/ errors)\n\t\t\t\tc.ContainerRemove(context.Background(), stage.Name, types.ContainerRemoveOptions{})\n\n\t\t\t\t\/\/ Note the 0777 permission bits. We use such liberal bits since\n\t\t\t\t\/\/ we do not know about the users within the docker containers that\n\t\t\t\t\/\/ are going to be run. We want to fix this later!\n\t\t\t\terr = os.MkdirAll(hostpath, 0777)\n\t\t\t\tif err != nil {\n\t\t\t\t\te <- errors.Wrap(err, \"Could not create output directory for stage\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tbinds := []string{hostpath + \":\" + mountpath}\n\t\t\t\tbinds = append(binds, stage.Volumes...)\n\n\t\t\t\tresp, err := c.ContainerCreate(context.Background(),\n\t\t\t\t\t&container.Config{Image: image,\n\t\t\t\t\t\tEnv: stage.Env,\n\t\t\t\t\t\tCmd: stage.Cmd,\n\t\t\t\t\t},\n\t\t\t\t\t&container.HostConfig{\n\t\t\t\t\t\tBinds:       binds,\n\t\t\t\t\t\tVolumesFrom: stage.Inputs},\n\t\t\t\t\t&network.NetworkingConfig{},\n\t\t\t\t\tstage.Name)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\te <- errors.Wrap(err, \"Could not create container \"+stage.Name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontainerId := resp.ID\n\n\t\t\t\terr = c.ContainerStart(context.Background(), containerId,\n\t\t\t\t\ttypes.ContainerStartOptions{})\n\n\t\t\t\tif err != nil {\n\t\t\t\t\te <- errors.Wrap(err, \"Could not start container\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t_, err = c.ContainerWait(context.Background(), containerId)\n\t\t\t\tif err != nil {\n\t\t\t\t\te <- errors.Wrap(err, \"Failed to wait for container to finish\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tcond := completedConditions[i]\n\t\t\tcond.L.Lock()\n\n\t\t\t\/\/ Notifies waiting stages on completion\n\t\t\tcompletedStages[i] = true\n\n\t\t\tcond.Broadcast()\n\t\t\tcond.L.Unlock()\n\n\t\t\tfmt.Println(stage.Name, \"completed successfully.\")\n\n\t\t\te <- nil\n\t\t}(i, stage)\n\t}\n\n\tfor i := 0; i < len(p.Stages); i++ {\n\t\terr := <-e\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Restore permission bits to output directory\n\t\/\/ err := filepath.Walk(rootpath, func(name string, info os.FileInfo, err error) error {\n\t\/\/ \treturn os.Chmod(name, 0666)\n\t\/\/ })\n\t\/\/ if err != nil {\n\t\/\/ \treturn err\n\t\/\/ }\n\n\treturn nil\n}\n\n\/\/ Stops any previously run pipeline and deletes the containers. If any, we\n\/\/ ignore errors from docker.\nfunc stopPreviousRun(c *client.Client, stages []*Stage) {\n\tfor _, stage := range stages {\n\t\tc.ContainerKill(context.Background(), stage.Name, \"9\")\n\t}\n}\n\n\/\/ Generate a list of volume mounts on the form\n\/\/ \/hostpath\/stagename-containerid\/:\/walrus\/stagename\nfunc getInputVolumes(inputs []string, hostpath string) (volumes []string) {\n\tfor _, input := range inputs {\n\t\tvolumes = append(volumes, hostpath+\"\/\"+input+\":\"+\"\/walrus\"+\"\/\"+input)\n\t}\n\treturn volumes\n}\n\nfunc getRepoAndTag(pipelineImage string) (repo, tag string) {\n\trepoAndTag := strings.Split(pipelineImage, \":\")\n\tif len(repoAndTag) == 1 {\n\t\ttag = \"latest\"\n\t} else {\n\t\ttag = repoAndTag[1]\n\t}\n\trepo = repoAndTag[0]\n\n\treturn repo, tag\n}\n\n\/\/ Saves the pipeline configuration (json) to a new .walrus directory in the\n\/\/ output directory specified by the user. Can be used to determine what\n\/\/ produced the output in the output directory.\nfunc saveConfiguration(hostpath string, p *Pipeline) error {\n\tconfigPath := createConfigPath(hostpath)\n\terr := os.Mkdir(configPath, 0777)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not create directory to save old pipeline results\")\n\t}\n\n\tfilename := configPath + \"\/\" + \"pipeline.json\"\n\tf, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not open old pipeline configuration\")\n\t}\n\tb, err := json.Marshal(p)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not marshal pipeline configuration\")\n\t}\n\n\t_, err = f.Write(b)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not write pipeline configuration\")\n\t}\n\n\treturn nil\n\n}\n\n\/\/ Moves the output of the previous runs into new folders for each stage. The\n\/\/ names are STAGENAME-VERSION.\nfunc savePreviousRun(hostpath string) error {\n\n\t\/\/ Check if there is any output from the previous runs\n\tf, err := os.Open(hostpath)\n\tif err != nil {\n\t\t\/\/ Output dir does not exist, nothing to back up.\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn errors.Wrap(err, \"Could not open previous pipeline outputs\")\n\t}\n\tfiles, err := f.Readdir(-1)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not read output directory\")\n\t}\n\n\tif len(files) == 0 {\n\t\treturn errors.Wrap(err, \"No files in output directory, nothing to back up\")\n\t}\n\n\t\/\/ Read old pipeline description to get it's version (use it for renaming)\n\tconfigPath := createConfigPath(hostpath)\n\tconfigFilename := configPath + \"\/\" + \"pipeline.json\"\n\tp, err := ParseConfig(configFilename)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrap(err, \"Could not parse old pipeline configuration\")\n\t}\n\n\tabsPath, err := filepath.Abs(hostpath)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not get the absolute path of the output directory\")\n\t}\n\n\t\/\/ iterate over all stages and move each output folder to a new directory\n\t\/\/ if the stage is cached the directory is copied. .\n\tfor _, stage := range p.Stages {\n\t\tnewFilename := absPath + \"\/\" + stage.Name + \"-\" + p.Version\n\t\toldFilename := absPath + \"\/\" + stage.Name\n\n\t\tif stage.Cache {\n\t\t\terr = copyDir(oldFilename, newFilename)\n\t\t} else {\n\t\t\terr = os.Rename(oldFilename, newFilename)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Could not back up pipeline stage directory\")\n\t\t}\n\t}\n\n\t\/\/ back up the walrus directory as well\n\twalrusDirectory := configPath\n\tnewWalrusDirectory := walrusDirectory + \"-\" + p.Version\n\terr = os.Rename(walrusDirectory, newWalrusDirectory)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Copies one directory to another. NOTE, only one level, not recursive yet.\nfunc copyDir(src, dest string) error {\n\n\terr := os.Mkdir(dest, 0777)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = filepath.Walk(src, func(path string, info os.FileInfo, err error) error {\n\t\t\/\/ nothing to back up\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ if dir then create dir , else a file then copy it\n\t\tif info.IsDir() {\n\t\t} else {\n\t\t\tsrcFile, err := os.Open(path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tdestFilename := dest + \"\/\" + info.Name()\n\t\t\tdestFile, err := os.OpenFile(destFilename, os.O_CREATE, 0644)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t_, err = io.Copy(srcFile, destFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\t\treturn nil\n\t})\n\treturn err\n}\n\n\/\/ Returns the full path of the  walrus configuration directory\nfunc createConfigPath(hostpath string) string {\n\treturn hostpath + \"\/\" + \".walrus\"\n}\n\nfunc fixMountPaths(stages []*Stage) error {\n\tfor i, stage := range stages {\n\t\tupdatedVolumes := []string{}\n\t\tfor _, volume := range stage.Volumes {\n\t\t\thostClientPath := strings.Split(volume, \":\")\n\n\t\t\tif len(hostClientPath) > 2 {\n\t\t\t\treturn errors.New(\"Incorrect volume \" + volume + \" in pipeline description\")\n\t\t\t}\n\n\t\t\thostPath := hostClientPath[0]\n\t\t\tclientPath := hostClientPath[1]\n\n\t\t\tif strings.HasPrefix(hostPath, \"\/\") {\n\t\t\t\tupdatedVolumes = append(updatedVolumes, volume)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tabsPath, err := filepath.Abs(hostPath)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"Could not get the absolute path of the mount path\")\n\t\t\t}\n\t\t\tupdatedVolumes = append(updatedVolumes, absPath+\":\"+clientPath)\n\t\t}\n\t\tstages[i].Volumes = updatedVolumes\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\tvar configFilename = flag.String(\"f\", \"pipeline.json\", \"pipeline description file\")\n\tvar outputDir = flag.String(\"output\", \"walrus\", \"where walrus should store output data on the host\")\n\n\tflag.Parse()\n\n\thostpath, err := filepath.Abs(*outputDir)\n\tif err != nil {\n\t\tfmt.Println(\"Check hostpath\", err)\n\t}\n\n\tflag.Parse()\n\tclient, err := client.NewEnvClient()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tp, err := ParseConfig(*configFilename)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\terr = fixMountPaths(p.Stages)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tstopPreviousRun(client, p.Stages)\n\terr = savePreviousRun(hostpath)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\terr = run(client, p, hostpath, *configFilename)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\terr = saveConfiguration(hostpath, p)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t} else {\n\t\tfmt.Println(\"All stages completed successfully.\",\n\t\t\t\"\\nOutput written to \", hostpath)\n\t}\n\n}\n<commit_msg>wait until docker image is pulled down<commit_after>package main\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/api\/types\/container\"\n\t\"github.com\/docker\/docker\/api\/types\/network\"\n\t\"github.com\/docker\/docker\/client\"\n\t\"github.com\/pkg\/errors\"\n)\n\nvar stageMutexes []*sync.Mutex\nvar completedConditions []*sync.Cond\nvar completedStages []bool\nvar stageIndex map[string]int\n\nfunc run(c *client.Client, p *Pipeline, rootpath, filename string) error {\n\t\/\/ generate a version number\/name if the pipeline description didn't\n\tif p.Version == \"\" {\n\t\tp.Version = createName()\n\t}\n\n\tstageMutexes = make([]*sync.Mutex, len(p.Stages))\n\tcompletedConditions = make([]*sync.Cond, len(p.Stages))\n\tcompletedStages = make([]bool, len(p.Stages))\n\n\tfor i := range stageMutexes {\n\t\tstageMutexes[i] = &sync.Mutex{}\n\t\tcompletedConditions[i] = sync.NewCond(stageMutexes[i])\n\t}\n\n\tstageIndex = make(map[string]int, len(p.Stages))\n\n\t\/\/ Name to index mapping\n\tfor i, stage := range p.Stages {\n\t\tstageIndex[stage.Name] = i\n\t}\n\n\te := make(chan error, len(p.Stages))\n\n\tfor i, stage := range p.Stages {\n\t\tgo func(i int, stage *Stage) {\n\t\t\tmountpath := \"\/walrus\/\" + stage.Name\n\t\t\thostpath := rootpath + \"\/\" + stage.Name\n\n\t\t\trepo, tag := getRepoAndTag(stage.Image)\n\t\t\timage := repo + \":\" + tag\n\t\t\trc, err := c.ImagePull(context.Background(), image,\n\t\t\t\ttypes.ImagePullOptions{})\n\t\t\tif err != nil {\n\t\t\t\te <- errors.Wrap(err, \"Could not pull image\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tdefer rc.Close()\n\n\t\t\t_, err = ioutil.ReadAll(rc)\n\t\t\tif err != nil {\n\t\t\t\te <- errors.Wrap(err, \"error reading image pull\")\n\t\t\t}\n\n\t\t\t\/\/ If the stage has any inputs it waits for these stages to complete\n\t\t\t\/\/ before starting\n\t\t\tif len(stage.Inputs) > 0 {\n\t\t\t\tfor _, input := range stage.Inputs {\n\t\t\t\t\tindex := stageIndex[input]\n\t\t\t\t\tcond := completedConditions[index]\n\t\t\t\t\tcond.L.Lock()\n\t\t\t\t\tfor !completedStages[index] {\n\t\t\t\t\t\tcond.Wait()\n\t\t\t\t\t}\n\t\t\t\t\tcond.L.Unlock()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ try to open output directory, if it exists then we can serve the\n\t\t\t\/\/ \"cached\"\/old results\n\t\t\t_, err = os.Open(hostpath)\n\n\t\t\tif !stage.Cache || err != nil {\n\n\t\t\t\t\/\/ first remove any previous container (note that we're ignoring\n\t\t\t\t\/\/ errors)\n\t\t\t\tc.ContainerRemove(context.Background(), stage.Name, types.ContainerRemoveOptions{})\n\n\t\t\t\t\/\/ Note the 0777 permission bits. We use such liberal bits since\n\t\t\t\t\/\/ we do not know about the users within the docker containers that\n\t\t\t\t\/\/ are going to be run. We want to fix this later!\n\t\t\t\terr = os.MkdirAll(hostpath, 0777)\n\t\t\t\tif err != nil {\n\t\t\t\t\te <- errors.Wrap(err, \"Could not create output directory for stage\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tbinds := []string{hostpath + \":\" + mountpath}\n\t\t\t\tbinds = append(binds, stage.Volumes...)\n\n\t\t\t\tresp, err := c.ContainerCreate(context.Background(),\n\t\t\t\t\t&container.Config{Image: image,\n\t\t\t\t\t\tEnv: stage.Env,\n\t\t\t\t\t\tCmd: stage.Cmd,\n\t\t\t\t\t},\n\t\t\t\t\t&container.HostConfig{\n\t\t\t\t\t\tBinds:       binds,\n\t\t\t\t\t\tVolumesFrom: stage.Inputs},\n\t\t\t\t\t&network.NetworkingConfig{},\n\t\t\t\t\tstage.Name)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\te <- errors.Wrap(err, \"Could not create container \"+stage.Name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcontainerId := resp.ID\n\n\t\t\t\terr = c.ContainerStart(context.Background(), containerId,\n\t\t\t\t\ttypes.ContainerStartOptions{})\n\n\t\t\t\tif err != nil {\n\t\t\t\t\te <- errors.Wrap(err, \"Could not start container\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t_, err = c.ContainerWait(context.Background(), containerId)\n\t\t\t\tif err != nil {\n\t\t\t\t\te <- errors.Wrap(err, \"Failed to wait for container to finish\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tcond := completedConditions[i]\n\t\t\tcond.L.Lock()\n\n\t\t\t\/\/ Notifies waiting stages on completion\n\t\t\tcompletedStages[i] = true\n\n\t\t\tcond.Broadcast()\n\t\t\tcond.L.Unlock()\n\n\t\t\tfmt.Println(stage.Name, \"completed successfully.\")\n\n\t\t\te <- nil\n\t\t}(i, stage)\n\t}\n\n\tfor i := 0; i < len(p.Stages); i++ {\n\t\terr := <-e\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Restore permission bits to output directory\n\t\/\/ err := filepath.Walk(rootpath, func(name string, info os.FileInfo, err error) error {\n\t\/\/ \treturn os.Chmod(name, 0666)\n\t\/\/ })\n\t\/\/ if err != nil {\n\t\/\/ \treturn err\n\t\/\/ }\n\n\treturn nil\n}\n\n\/\/ Stops any previously run pipeline and deletes the containers. If any, we\n\/\/ ignore errors from docker.\nfunc stopPreviousRun(c *client.Client, stages []*Stage) {\n\tfor _, stage := range stages {\n\t\tc.ContainerKill(context.Background(), stage.Name, \"9\")\n\t}\n}\n\n\/\/ Generate a list of volume mounts on the form\n\/\/ \/hostpath\/stagename-containerid\/:\/walrus\/stagename\nfunc getInputVolumes(inputs []string, hostpath string) (volumes []string) {\n\tfor _, input := range inputs {\n\t\tvolumes = append(volumes, hostpath+\"\/\"+input+\":\"+\"\/walrus\"+\"\/\"+input)\n\t}\n\treturn volumes\n}\n\nfunc getRepoAndTag(pipelineImage string) (repo, tag string) {\n\trepoAndTag := strings.Split(pipelineImage, \":\")\n\tif len(repoAndTag) == 1 {\n\t\ttag = \"latest\"\n\t} else {\n\t\ttag = repoAndTag[1]\n\t}\n\trepo = repoAndTag[0]\n\n\treturn repo, tag\n}\n\n\/\/ Saves the pipeline configuration (json) to a new .walrus directory in the\n\/\/ output directory specified by the user. Can be used to determine what\n\/\/ produced the output in the output directory.\nfunc saveConfiguration(hostpath string, p *Pipeline) error {\n\tconfigPath := createConfigPath(hostpath)\n\terr := os.Mkdir(configPath, 0777)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not create directory to save old pipeline results\")\n\t}\n\n\tfilename := configPath + \"\/\" + \"pipeline.json\"\n\tf, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not open old pipeline configuration\")\n\t}\n\tb, err := json.Marshal(p)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not marshal pipeline configuration\")\n\t}\n\n\t_, err = f.Write(b)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not write pipeline configuration\")\n\t}\n\n\treturn nil\n\n}\n\n\/\/ Moves the output of the previous runs into new folders for each stage. The\n\/\/ names are STAGENAME-VERSION.\nfunc savePreviousRun(hostpath string) error {\n\n\t\/\/ Check if there is any output from the previous runs\n\tf, err := os.Open(hostpath)\n\tif err != nil {\n\t\t\/\/ Output dir does not exist, nothing to back up.\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn errors.Wrap(err, \"Could not open previous pipeline outputs\")\n\t}\n\tfiles, err := f.Readdir(-1)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not read output directory\")\n\t}\n\n\tif len(files) == 0 {\n\t\treturn errors.Wrap(err, \"No files in output directory, nothing to back up\")\n\t}\n\n\t\/\/ Read old pipeline description to get it's version (use it for renaming)\n\tconfigPath := createConfigPath(hostpath)\n\tconfigFilename := configPath + \"\/\" + \"pipeline.json\"\n\tp, err := ParseConfig(configFilename)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.Wrap(err, \"Could not parse old pipeline configuration\")\n\t}\n\n\tabsPath, err := filepath.Abs(hostpath)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not get the absolute path of the output directory\")\n\t}\n\n\t\/\/ iterate over all stages and move each output folder to a new directory\n\t\/\/ if the stage is cached the directory is copied. .\n\tfor _, stage := range p.Stages {\n\t\tnewFilename := absPath + \"\/\" + stage.Name + \"-\" + p.Version\n\t\toldFilename := absPath + \"\/\" + stage.Name\n\n\t\tif stage.Cache {\n\t\t\terr = copyDir(oldFilename, newFilename)\n\t\t} else {\n\t\t\terr = os.Rename(oldFilename, newFilename)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"Could not back up pipeline stage directory\")\n\t\t}\n\t}\n\n\t\/\/ back up the walrus directory as well\n\twalrusDirectory := configPath\n\tnewWalrusDirectory := walrusDirectory + \"-\" + p.Version\n\terr = os.Rename(walrusDirectory, newWalrusDirectory)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Copies one directory to another. NOTE, only one level, not recursive yet.\nfunc copyDir(src, dest string) error {\n\n\terr := os.Mkdir(dest, 0777)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = filepath.Walk(src, func(path string, info os.FileInfo, err error) error {\n\t\t\/\/ nothing to back up\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ if dir then create dir , else a file then copy it\n\t\tif info.IsDir() {\n\t\t} else {\n\t\t\tsrcFile, err := os.Open(path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tdestFilename := dest + \"\/\" + info.Name()\n\t\t\tdestFile, err := os.OpenFile(destFilename, os.O_CREATE, 0644)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t_, err = io.Copy(srcFile, destFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\t\treturn nil\n\t})\n\treturn err\n}\n\n\/\/ Returns the full path of the  walrus configuration directory\nfunc createConfigPath(hostpath string) string {\n\treturn hostpath + \"\/\" + \".walrus\"\n}\n\nfunc fixMountPaths(stages []*Stage) error {\n\tfor i, stage := range stages {\n\t\tupdatedVolumes := []string{}\n\t\tfor _, volume := range stage.Volumes {\n\t\t\thostClientPath := strings.Split(volume, \":\")\n\n\t\t\tif len(hostClientPath) > 2 {\n\t\t\t\treturn errors.New(\"Incorrect volume \" + volume + \" in pipeline description\")\n\t\t\t}\n\n\t\t\thostPath := hostClientPath[0]\n\t\t\tclientPath := hostClientPath[1]\n\n\t\t\tif strings.HasPrefix(hostPath, \"\/\") {\n\t\t\t\tupdatedVolumes = append(updatedVolumes, volume)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tabsPath, err := filepath.Abs(hostPath)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"Could not get the absolute path of the mount path\")\n\t\t\t}\n\t\t\tupdatedVolumes = append(updatedVolumes, absPath+\":\"+clientPath)\n\t\t}\n\t\tstages[i].Volumes = updatedVolumes\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\tvar configFilename = flag.String(\"f\", \"pipeline.json\", \"pipeline description file\")\n\tvar outputDir = flag.String(\"output\", \"walrus\", \"where walrus should store output data on the host\")\n\n\tflag.Parse()\n\n\thostpath, err := filepath.Abs(*outputDir)\n\tif err != nil {\n\t\tfmt.Println(\"Check hostpath\", err)\n\t}\n\n\tflag.Parse()\n\tclient, err := client.NewEnvClient()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tp, err := ParseConfig(*configFilename)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\terr = fixMountPaths(p.Stages)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tstopPreviousRun(client, p.Stages)\n\terr = savePreviousRun(hostpath)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\terr = run(client, p, hostpath, *configFilename)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\terr = saveConfiguration(hostpath, p)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t} else {\n\t\tfmt.Println(\"All stages completed successfully.\",\n\t\t\t\"\\nOutput written to \", hostpath)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package trakt\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n)\n\ntype Trakt struct {\n\tUrl         string\n\tApiKey      string\n\tAccessToken string\n}\n\nfunc (t Trakt) Get(path string) (resp *http.Response, err error) {\n\turl := fmt.Sprintf(\"%s%s\", t.Url, path)\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Add(\"Content-type\", \"application\/json\")\n\treq.Header.Add(\"trakt-api-version\", \"2\")\n\treq.Header.Add(\"trakt-api-key\", t.ApiKey)\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", t.AccessToken))\n\treturn client.Do(req)\n}\n<commit_msg>Removing unused packages from import<commit_after>package trakt\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n)\n\ntype Trakt struct {\n\tUrl         string\n\tApiKey      string\n\tAccessToken string\n}\n\nfunc (t Trakt) Get(path string) (resp *http.Response, err error) {\n\turl := fmt.Sprintf(\"%s%s\", t.Url, path)\n\tclient := &http.Client{}\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\treq.Header.Add(\"Content-type\", \"application\/json\")\n\treq.Header.Add(\"trakt-api-version\", \"2\")\n\treq.Header.Add(\"trakt-api-key\", t.ApiKey)\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"Bearer %s\", t.AccessToken))\n\treturn client.Do(req)\n}\n<|endoftext|>"}
{"text":"<commit_before>package libp2pquic\n\nimport (\n\tma \"github.com\/multiformats\/go-multiaddr\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"Transport\", func() {\n\tvar t *QuicTransport\n\n\tBeforeEach(func() {\n\t\tt = NewQuicTransport(nil)\n\t})\n\n\tIt(\"matches\", func() {\n\t\tinvalidAddr, err := ma.NewMultiaddr(\"\/ip4\/127.0.0.1\/udp\/1234\")\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tvalidAddr, err := ma.NewMultiaddr(\"\/ip4\/127.0.0.1\/udp\/1234\/quic\")\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tExpect(t.Matches(invalidAddr)).To(BeFalse())\n\t\tExpect(t.Matches(validAddr)).To(BeTrue())\n\t})\n})\n<commit_msg>add tests for transport.Listen<commit_after>package libp2pquic\n\nimport (\n\tma \"github.com\/multiformats\/go-multiaddr\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"Transport\", func() {\n\tvar t *QuicTransport\n\n\tBeforeEach(func() {\n\t\tt = NewQuicTransport(nil)\n\t})\n\n\tContext(\"listening\", func() {\n\t\tIt(\"creates a new listener\", func() {\n\t\t\tmaddr, err := ma.NewMultiaddr(\"\/ip4\/127.0.0.1\/udp\/1234\/quic\")\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tln, err := t.Listen(maddr)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(ln.Multiaddr()).To(Equal(maddr))\n\t\t})\n\n\t\tIt(\"returns an existing listener\", func() {\n\t\t\tmaddr, err := ma.NewMultiaddr(\"\/ip4\/127.0.0.1\/udp\/1235\/quic\")\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tln, err := t.Listen(maddr)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(ln.Multiaddr()).To(Equal(maddr))\n\t\t\tln2, err := t.Listen(maddr)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\tExpect(ln2).To(Equal(ln))\n\t\t\tExpect(t.listeners).To(HaveLen(1))\n\t\t})\n\t})\n\n\tIt(\"matches\", func() {\n\t\tinvalidAddr, err := ma.NewMultiaddr(\"\/ip4\/127.0.0.1\/udp\/1234\")\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tvalidAddr, err := ma.NewMultiaddr(\"\/ip4\/127.0.0.1\/udp\/1234\/quic\")\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tExpect(t.Matches(invalidAddr)).To(BeFalse())\n\t\tExpect(t.Matches(validAddr)).To(BeTrue())\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n)\n\n\/\/ Transparently intercept HTTPS connections.\n\n\/\/ runTransparentServer transparently intercepts connections, listening at addr.\nfunc runTransparentServer(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlistenerChan <- ln\n\n\tlocalAddresses, err := getLocalAddresses()\n\tif err != nil {\n\t\tlog.Println(\"Error getting list of this server's IP addresses:\", err)\n\t\t\/\/ Continue, but without protection against infinite redirect loops.\n\t}\n\n\tvar tempDelay time.Duration\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tif ne, ok := err.(net.Error); ok && ne.Temporary() {\n\t\t\t\tif tempDelay == 0 {\n\t\t\t\t\ttempDelay = 5 * time.Millisecond\n\t\t\t\t} else {\n\t\t\t\t\ttempDelay *= 2\n\t\t\t\t}\n\t\t\t\tif max := 1 * time.Second; tempDelay > max {\n\t\t\t\t\ttempDelay = max\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"Accept error: %v; retrying in %v\", err, tempDelay)\n\t\t\t\ttime.Sleep(tempDelay)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\tserverAddr, err := realServerAddress(conn)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error getting original address for intercepted connection:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tuser, _, _ := net.SplitHostPort(conn.RemoteAddr().String())\n\n\t\tvar server string\n\t\tif tcpAddr, ok := serverAddr.(*net.TCPAddr); ok {\n\t\t\tserver = tcpAddr.IP.String()\n\t\t} else {\n\t\t\tserver = serverAddr.String()\n\t\t}\n\t\tif localAddresses[server] {\n\t\t\t\/\/ This is not an intercepted connection; it is a direct connection to\n\t\t\t\/\/ our transparent port. If we bump it, we will end up with an infinite\n\t\t\t\/\/ loop of redirects.\n\t\t\tlogTLS(user, serverAddr.String(), \"\", errors.New(\"infinite redirect loop\"))\n\t\t\tconn.Close()\n\t\t\tcontinue\n\t\t}\n\n\t\tgo SSLBump(conn, serverAddr.String(), user, \"\")\n\t}\n\n\tpanic(\"unreachable\")\n}\n\n\/\/ getLocalAddresses returns a set of the IP addresses of this machine's\n\/\/ network interfaces.\nfunc getLocalAddresses() (map[string]bool, error) {\n\tres := map[string]bool{}\n\n\tifs, err := net.Interfaces()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, iface := range ifs {\n\t\taddrs, err := iface.Addrs()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, a := range addrs {\n\t\t\tif ipNet, ok := a.(*net.IPNet); ok {\n\t\t\t\ta = &net.IPAddr{IP: ipNet.IP}\n\t\t\t}\n\t\t\tres[a.String()] = true\n\t\t}\n\t}\n\n\treturn res, nil\n}\n<commit_msg>Make error message for transparent connections more informative.<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"net\"\n\t\"time\"\n)\n\n\/\/ Transparently intercept HTTPS connections.\n\n\/\/ runTransparentServer transparently intercepts connections, listening at addr.\nfunc runTransparentServer(addr string) error {\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlistenerChan <- ln\n\n\tlocalAddresses, err := getLocalAddresses()\n\tif err != nil {\n\t\tlog.Println(\"Error getting list of this server's IP addresses:\", err)\n\t\t\/\/ Continue, but without protection against infinite redirect loops.\n\t}\n\n\tvar tempDelay time.Duration\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\tif ne, ok := err.(net.Error); ok && ne.Temporary() {\n\t\t\t\tif tempDelay == 0 {\n\t\t\t\t\ttempDelay = 5 * time.Millisecond\n\t\t\t\t} else {\n\t\t\t\t\ttempDelay *= 2\n\t\t\t\t}\n\t\t\t\tif max := 1 * time.Second; tempDelay > max {\n\t\t\t\t\ttempDelay = max\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"Accept error: %v; retrying in %v\", err, tempDelay)\n\t\t\t\ttime.Sleep(tempDelay)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\n\t\tserverAddr, err := realServerAddress(conn)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error getting original address for intercepted connection from %v: %v\", conn.RemoteAddr(), err)\n\t\t\tcontinue\n\t\t}\n\t\tuser, _, _ := net.SplitHostPort(conn.RemoteAddr().String())\n\n\t\tvar server string\n\t\tif tcpAddr, ok := serverAddr.(*net.TCPAddr); ok {\n\t\t\tserver = tcpAddr.IP.String()\n\t\t} else {\n\t\t\tserver = serverAddr.String()\n\t\t}\n\t\tif localAddresses[server] {\n\t\t\t\/\/ This is not an intercepted connection; it is a direct connection to\n\t\t\t\/\/ our transparent port. If we bump it, we will end up with an infinite\n\t\t\t\/\/ loop of redirects.\n\t\t\tlogTLS(user, serverAddr.String(), \"\", errors.New(\"infinite redirect loop\"))\n\t\t\tconn.Close()\n\t\t\tcontinue\n\t\t}\n\n\t\tgo SSLBump(conn, serverAddr.String(), user, \"\")\n\t}\n\n\tpanic(\"unreachable\")\n}\n\n\/\/ getLocalAddresses returns a set of the IP addresses of this machine's\n\/\/ network interfaces.\nfunc getLocalAddresses() (map[string]bool, error) {\n\tres := map[string]bool{}\n\n\tifs, err := net.Interfaces()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, iface := range ifs {\n\t\taddrs, err := iface.Addrs()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, a := range addrs {\n\t\t\tif ipNet, ok := a.(*net.IPNet); ok {\n\t\t\t\ta = &net.IPAddr{IP: ipNet.IP}\n\t\t\t}\n\t\t\tres[a.String()] = true\n\t\t}\n\t}\n\n\treturn res, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package widget\n\nimport (\n\t\"fmt\"\n\t\"html\/template\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/qor\/admin\"\n\t\"github.com\/qor\/qor\/resource\"\n\t\"github.com\/qor\/roles\"\n)\n\nvar (\n\troot, _                = os.Getwd()\n\tviewPaths              []string\n\tregisteredWidgets      []*Widget\n\tregisteredWidgetsGroup []*WidgetsGroup\n)\n\n\/\/ Config widget config\ntype Config struct {\n\tDB            *gorm.DB\n\tAdmin         *admin.Admin\n\tPreviewAssets []string\n}\n\nfunc init() {\n\tif path := os.Getenv(\"WEB_ROOT\"); path != \"\" {\n\t\troot = path\n\t}\n}\n\n\/\/ New new widgets container\nfunc New(config *Config) *Widgets {\n\twidgets := &Widgets{Config: config, funcMaps: template.FuncMap{}, AssetFileSystem: &admin.AssetFileSystem{}}\n\n\tif root != \"\" {\n\t\twidgets.RegisterViewPath(path.Join(root, \"app\/views\/widgets\"))\n\t}\n\twidgets.RegisterViewPath(\"app\/views\/widgets\")\n\treturn widgets\n}\n\n\/\/ Widgets widgets container\ntype Widgets struct {\n\tfuncMaps              template.FuncMap\n\tConfig                *Config\n\tResource              *admin.Resource\n\tAssetFileSystem       admin.AssetFSInterface\n\tWidgetSettingResource *admin.Resource\n}\n\n\/\/ SetAssetFS set asset fs for render\nfunc (widgets *Widgets) SetAssetFS(assetFS admin.AssetFSInterface) {\n\tfor _, viewPath := range viewPaths {\n\t\tassetFS.RegisterPath(viewPath)\n\t}\n\n\tassetFS.Compile()\n\n\twidgets.AssetFileSystem = assetFS\n}\n\n\/\/ RegisterWidget register a new widget\nfunc (widgets *Widgets) RegisterWidget(w *Widget) {\n\tregisteredWidgets = append(registeredWidgets, w)\n}\n\n\/\/ RegisterWidgetsGroup register widgets group\nfunc (widgets *Widgets) RegisterWidgetsGroup(group *WidgetsGroup) {\n\tregisteredWidgetsGroup = append(registeredWidgetsGroup, group)\n}\n\n\/\/ RegisterFuncMap register view funcs, it could be used when render templates\nfunc (widgets *Widgets) RegisterFuncMap(name string, fc interface{}) {\n\twidgets.funcMaps[name] = fc\n}\n\n\/\/ ConfigureQorResourceBeforeInitialize a method used to config Widget for qor admin\nfunc (widgets *Widgets) ConfigureQorResourceBeforeInitialize(res resource.Resourcer) {\n\tif res, ok := res.(*admin.Resource); ok {\n\t\t\/\/ register view paths\n\t\tres.GetAdmin().RegisterViewPath(\"github.com\/qor\/widget\/views\")\n\n\t\t\/\/ set resources\n\t\twidgets.Resource = res\n\n\t\t\/\/ set setting resource\n\t\tif widgets.WidgetSettingResource == nil {\n\t\t\twidgets.WidgetSettingResource = res.GetAdmin().NewResource(&QorWidgetSetting{}, &admin.Config{Name: res.Name})\n\t\t}\n\n\t\tres.Name = widgets.WidgetSettingResource.Name\n\n\t\tfor funcName, fc := range funcMap {\n\t\t\tres.GetAdmin().RegisterFuncMap(funcName, fc)\n\t\t}\n\n\t\t\/\/ configure routes\n\t\tcontroller := widgetController{Widgets: widgets}\n\t\trouter := res.GetAdmin().GetRouter()\n\t\trouter.Get(widgets.WidgetSettingResource.ToParam(), controller.Index, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Get(fmt.Sprintf(\"%v\/new\", widgets.WidgetSettingResource.ToParam()), controller.New, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Get(fmt.Sprintf(\"%v\/!setting\", widgets.WidgetSettingResource.ToParam()), controller.Setting, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Get(fmt.Sprintf(\"%v\/%v\", widgets.WidgetSettingResource.ToParam(), widgets.WidgetSettingResource.ParamIDName()), controller.Edit, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Get(fmt.Sprintf(\"%v\/%v\/!preview\", widgets.WidgetSettingResource.ToParam(), widgets.WidgetSettingResource.ParamIDName()), controller.Preview, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Get(fmt.Sprintf(\"%v\/%v\/edit\", widgets.WidgetSettingResource.ToParam(), widgets.WidgetSettingResource.ParamIDName()), controller.Edit, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Put(fmt.Sprintf(\"%v\/%v\", widgets.WidgetSettingResource.ToParam(), widgets.WidgetSettingResource.ParamIDName()), controller.Update, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Post(widgets.WidgetSettingResource.ToParam(), controller.Update, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Get(fmt.Sprintf(\"%v\/inline-edit\", res.ToParam()), controller.InlineEdit, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t}\n}\n\n\/\/ Widget widget struct\ntype Widget struct {\n\tName        string\n\tPreviewIcon string\n\tGroup       string\n\tTemplates   []string\n\tSetting     *admin.Resource\n\tPermission  *roles.Permission\n\tContext     func(context *Context, setting interface{}) *Context\n}\n\n\/\/ WidgetsGroup widgets Group\ntype WidgetsGroup struct {\n\tName    string\n\tWidgets []string\n}\n\n\/\/ GetWidget get widget by name\nfunc GetWidget(name string) *Widget {\n\tfor _, w := range registeredWidgets {\n\t\tif w.Name == name {\n\t\t\treturn w\n\t\t}\n\t}\n\n\tfor _, g := range registeredWidgetsGroup {\n\t\tif g.Name == name {\n\t\t\tfor _, widgetName := range g.Widgets {\n\t\t\t\treturn GetWidget(widgetName)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Don't compile when set assetfs<commit_after>package widget\n\nimport (\n\t\"fmt\"\n\t\"html\/template\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/qor\/admin\"\n\t\"github.com\/qor\/qor\/resource\"\n\t\"github.com\/qor\/roles\"\n)\n\nvar (\n\troot, _                = os.Getwd()\n\tviewPaths              []string\n\tregisteredWidgets      []*Widget\n\tregisteredWidgetsGroup []*WidgetsGroup\n)\n\n\/\/ Config widget config\ntype Config struct {\n\tDB            *gorm.DB\n\tAdmin         *admin.Admin\n\tPreviewAssets []string\n}\n\nfunc init() {\n\tif path := os.Getenv(\"WEB_ROOT\"); path != \"\" {\n\t\troot = path\n\t}\n}\n\n\/\/ New new widgets container\nfunc New(config *Config) *Widgets {\n\twidgets := &Widgets{Config: config, funcMaps: template.FuncMap{}, AssetFileSystem: &admin.AssetFileSystem{}}\n\n\tif root != \"\" {\n\t\twidgets.RegisterViewPath(path.Join(root, \"app\/views\/widgets\"))\n\t}\n\twidgets.RegisterViewPath(\"app\/views\/widgets\")\n\treturn widgets\n}\n\n\/\/ Widgets widgets container\ntype Widgets struct {\n\tfuncMaps              template.FuncMap\n\tConfig                *Config\n\tResource              *admin.Resource\n\tAssetFileSystem       admin.AssetFSInterface\n\tWidgetSettingResource *admin.Resource\n}\n\n\/\/ SetAssetFS set asset fs for render\nfunc (widgets *Widgets) SetAssetFS(assetFS admin.AssetFSInterface) {\n\tfor _, viewPath := range viewPaths {\n\t\tassetFS.RegisterPath(viewPath)\n\t}\n\n\twidgets.AssetFileSystem = assetFS\n}\n\n\/\/ RegisterWidget register a new widget\nfunc (widgets *Widgets) RegisterWidget(w *Widget) {\n\tregisteredWidgets = append(registeredWidgets, w)\n}\n\n\/\/ RegisterWidgetsGroup register widgets group\nfunc (widgets *Widgets) RegisterWidgetsGroup(group *WidgetsGroup) {\n\tregisteredWidgetsGroup = append(registeredWidgetsGroup, group)\n}\n\n\/\/ RegisterFuncMap register view funcs, it could be used when render templates\nfunc (widgets *Widgets) RegisterFuncMap(name string, fc interface{}) {\n\twidgets.funcMaps[name] = fc\n}\n\n\/\/ ConfigureQorResourceBeforeInitialize a method used to config Widget for qor admin\nfunc (widgets *Widgets) ConfigureQorResourceBeforeInitialize(res resource.Resourcer) {\n\tif res, ok := res.(*admin.Resource); ok {\n\t\t\/\/ register view paths\n\t\tres.GetAdmin().RegisterViewPath(\"github.com\/qor\/widget\/views\")\n\n\t\t\/\/ set resources\n\t\twidgets.Resource = res\n\n\t\t\/\/ set setting resource\n\t\tif widgets.WidgetSettingResource == nil {\n\t\t\twidgets.WidgetSettingResource = res.GetAdmin().NewResource(&QorWidgetSetting{}, &admin.Config{Name: res.Name})\n\t\t}\n\n\t\tres.Name = widgets.WidgetSettingResource.Name\n\n\t\tfor funcName, fc := range funcMap {\n\t\t\tres.GetAdmin().RegisterFuncMap(funcName, fc)\n\t\t}\n\n\t\t\/\/ configure routes\n\t\tcontroller := widgetController{Widgets: widgets}\n\t\trouter := res.GetAdmin().GetRouter()\n\t\trouter.Get(widgets.WidgetSettingResource.ToParam(), controller.Index, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Get(fmt.Sprintf(\"%v\/new\", widgets.WidgetSettingResource.ToParam()), controller.New, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Get(fmt.Sprintf(\"%v\/!setting\", widgets.WidgetSettingResource.ToParam()), controller.Setting, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Get(fmt.Sprintf(\"%v\/%v\", widgets.WidgetSettingResource.ToParam(), widgets.WidgetSettingResource.ParamIDName()), controller.Edit, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Get(fmt.Sprintf(\"%v\/%v\/!preview\", widgets.WidgetSettingResource.ToParam(), widgets.WidgetSettingResource.ParamIDName()), controller.Preview, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Get(fmt.Sprintf(\"%v\/%v\/edit\", widgets.WidgetSettingResource.ToParam(), widgets.WidgetSettingResource.ParamIDName()), controller.Edit, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Put(fmt.Sprintf(\"%v\/%v\", widgets.WidgetSettingResource.ToParam(), widgets.WidgetSettingResource.ParamIDName()), controller.Update, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Post(widgets.WidgetSettingResource.ToParam(), controller.Update, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t\trouter.Get(fmt.Sprintf(\"%v\/inline-edit\", res.ToParam()), controller.InlineEdit, &admin.RouteConfig{Resource: widgets.WidgetSettingResource})\n\t}\n}\n\n\/\/ Widget widget struct\ntype Widget struct {\n\tName        string\n\tPreviewIcon string\n\tGroup       string\n\tTemplates   []string\n\tSetting     *admin.Resource\n\tPermission  *roles.Permission\n\tContext     func(context *Context, setting interface{}) *Context\n}\n\n\/\/ WidgetsGroup widgets Group\ntype WidgetsGroup struct {\n\tName    string\n\tWidgets []string\n}\n\n\/\/ GetWidget get widget by name\nfunc GetWidget(name string) *Widget {\n\tfor _, w := range registeredWidgets {\n\t\tif w.Name == name {\n\t\t\treturn w\n\t\t}\n\t}\n\n\tfor _, g := range registeredWidgetsGroup {\n\t\tif g.Name == name {\n\t\t\tfor _, widgetName := range g.Widgets {\n\t\t\t\treturn GetWidget(widgetName)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package statisticalaccumulator\n\n\n\nimport \"math\/big\"\n\n\n\ntype StatisticalAccumulator struct {\n\tn              *big.Rat\n\tsigmaXI        *big.Rat\n\tsigmaXISquared *big.Rat\n\n\tone *big.Rat\n}\n\n\n\nfunc NewStatisticalAccumulator() (*StatisticalAccumulator) {\n\n\tn := new(big.Rat)\n\tn.SetInt64(0)\n\n\tsigmaXI := new(big.Rat)\n\tsigmaXI.SetInt64(0)\n\n\tsigmaXISquared := new(big.Rat)\n\tsigmaXISquared.SetInt64(0)\n\n\tone := new(big.Rat)\n\tone.SetInt64(1)\n\n\n\n\tme := StatisticalAccumulator{\n\t\tn:n,\n\t\tsigmaXI:sigmaXI,\n\t\tsigmaXISquared:sigmaXISquared,\n\t\tone:one,\n\t}\n\n\n\n\treturn &me\n}\n\n\n\nfunc (me *StatisticalAccumulator) PutString(x string) {\n\n\txx := new(big.Rat)\n\txx.SetString(x)\n\n\tme.PutRat(xx)\n}\n\nfunc (me *StatisticalAccumulator) PutRat(x *big.Rat) {\n\n\tme.n.Add(me.n, me.one)\n\n\n\n\tme.sigmaXI.Add(me.sigmaXI, x)\n\n\n\n\txSquared := new(big.Rat)\n\txSquared.Mul(x, x)\n\t\n\tme.sigmaXISquared.Add(me.sigmaXISquared, xSquared)\n}\n\n\n\nfunc (me *StatisticalAccumulator) N() (*big.Rat) {\n\tn := new(big.Rat)\n\tn.Set(me.n)\n\n\n\n\treturn n\n}\n\nfunc (me *StatisticalAccumulator) Mean() (*big.Rat) {\n\tmean := new(big.Rat)\n\n\tmean.Inv(me.n)\n\n\tmean.Mul(mean, me.sigmaXI)\n\n\n\n\treturn mean\n}\n\n\nfunc (me *StatisticalAccumulator) Variance() (*big.Rat) {\n\tvariance := new(big.Rat)\n\n\tvariance.Inv(me.n)\n\n\tvariance.Mul(variance, me.sigmaXISquared)\n\n\n\n\ttemp := new(big.Rat)\n\n\ttemp.Mul(me.n, me.n)\n\ttemp.Inv(temp)\n\n\ttemp.Mul(temp, me.sigmaXI)\n\ttemp.Mul(temp, me.sigmaXI)\n\n\n\tvariance.Sub(variance, temp)\n\n\n\n\treturn variance\n}\n<commit_msg>NewStatisticalAccumulator() -> New()<commit_after>package statisticalaccumulator\n\n\n\nimport \"math\/big\"\n\n\n\ntype StatisticalAccumulator struct {\n\tn              *big.Rat\n\tsigmaXI        *big.Rat\n\tsigmaXISquared *big.Rat\n\n\tone *big.Rat\n}\n\n\n\nfunc New() (*StatisticalAccumulator) {\n\n\tn := new(big.Rat)\n\tn.SetInt64(0)\n\n\tsigmaXI := new(big.Rat)\n\tsigmaXI.SetInt64(0)\n\n\tsigmaXISquared := new(big.Rat)\n\tsigmaXISquared.SetInt64(0)\n\n\tone := new(big.Rat)\n\tone.SetInt64(1)\n\n\n\n\tme := StatisticalAccumulator{\n\t\tn:n,\n\t\tsigmaXI:sigmaXI,\n\t\tsigmaXISquared:sigmaXISquared,\n\t\tone:one,\n\t}\n\n\n\n\treturn &me\n}\n\n\n\nfunc (me *StatisticalAccumulator) PutString(x string) {\n\n\txx := new(big.Rat)\n\txx.SetString(x)\n\n\tme.PutRat(xx)\n}\n\nfunc (me *StatisticalAccumulator) PutRat(x *big.Rat) {\n\n\tme.n.Add(me.n, me.one)\n\n\n\n\tme.sigmaXI.Add(me.sigmaXI, x)\n\n\n\n\txSquared := new(big.Rat)\n\txSquared.Mul(x, x)\n\t\n\tme.sigmaXISquared.Add(me.sigmaXISquared, xSquared)\n}\n\n\n\nfunc (me *StatisticalAccumulator) N() (*big.Rat) {\n\tn := new(big.Rat)\n\tn.Set(me.n)\n\n\n\n\treturn n\n}\n\nfunc (me *StatisticalAccumulator) Mean() (*big.Rat) {\n\tmean := new(big.Rat)\n\n\tmean.Inv(me.n)\n\n\tmean.Mul(mean, me.sigmaXI)\n\n\n\n\treturn mean\n}\n\n\nfunc (me *StatisticalAccumulator) Variance() (*big.Rat) {\n\tvariance := new(big.Rat)\n\n\tvariance.Inv(me.n)\n\n\tvariance.Mul(variance, me.sigmaXISquared)\n\n\n\n\ttemp := new(big.Rat)\n\n\ttemp.Mul(me.n, me.n)\n\ttemp.Inv(temp)\n\n\ttemp.Mul(temp, me.sigmaXI)\n\ttemp.Mul(temp, me.sigmaXI)\n\n\n\tvariance.Sub(variance, temp)\n\n\n\n\treturn variance\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Cockroach Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\/\/\n\/\/ Author: Bram Gruneir (bram+code@cockroachlabs.com)\n\npackage storage\n\nimport (\n\t\"time\"\n\n\t\"github.com\/cockroachdb\/cockroach\/client\"\n\t\"github.com\/cockroachdb\/cockroach\/config\"\n\t\"github.com\/cockroachdb\/cockroach\/gossip\"\n\t\"github.com\/cockroachdb\/cockroach\/roachpb\"\n\t\"github.com\/cockroachdb\/cockroach\/util\"\n\t\"github.com\/cockroachdb\/cockroach\/util\/log\"\n\t\"github.com\/coreos\/etcd\/raft\"\n)\n\nconst (\n\t\/\/ raftLogQueueMaxSize is the max size of the queue.\n\traftLogQueueMaxSize = 100\n\t\/\/ RaftLogQueueTimerDuration is the duration between checking the\n\t\/\/ raft logs.\n\tRaftLogQueueTimerDuration = time.Second\n\t\/\/ RaftLogQueueStaleThreshold is the minimum threshold for stale raft log\n\t\/\/ entries. A stale entry is one which all replicas of the range have\n\t\/\/ progressed past and thus is no longer needed and can be pruned.\n\tRaftLogQueueStaleThreshold = 1\n)\n\n\/\/ raftLogQueue manages a queue of replicas slated to have their raft logs\n\/\/ truncated by removing unneeded entries.\ntype raftLogQueue struct {\n\tbaseQueue\n\tdb *client.DB\n}\n\n\/\/ newRaftLogQueue returns a new instance of raftLogQueue.\nfunc newRaftLogQueue(db *client.DB, gossip *gossip.Gossip) *raftLogQueue {\n\trlq := &raftLogQueue{\n\t\tdb: db,\n\t}\n\trlq.baseQueue = makeBaseQueue(\"raftlog\", rlq, gossip, raftLogQueueMaxSize)\n\treturn rlq\n}\n\nfunc (*raftLogQueue) needsLeaderLease() bool {\n\treturn false\n}\n\nfunc (*raftLogQueue) acceptsUnsplitRanges() bool {\n\treturn true\n}\n\n\/\/ getTruncatableIndexes returns the total number of stale raft log entries that\n\/\/ can be truncated and the oldest index that cannot be pruned.\nfunc getTruncatableIndexes(r *Replica) (uint64, uint64, error) {\n\trangeID := r.RangeID\n\traftStatus := r.store.RaftStatus(rangeID)\n\tif raftStatus == nil {\n\t\tif log.V(1) {\n\t\t\tlog.Infof(\"the raft group doesn't exist for range %d\", rangeID)\n\t\t}\n\t\treturn 0, 0, nil\n\t}\n\n\t\/\/ Is this the raft leader?\n\tif raftStatus.RaftState != raft.StateLeader {\n\t\treturn 0, 0, nil\n\t}\n\n\t\/\/ Find the oldest index still in use by the range.\n\toldestIndex := raftStatus.Applied\n\tfor _, progress := range raftStatus.Progress {\n\t\tif progress.Match < oldestIndex {\n\t\t\toldestIndex = progress.Match\n\t\t}\n\t}\n\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tfirstIndex, err := r.FirstIndex()\n\tif err != nil {\n\t\treturn 0, 0, util.Errorf(\"error retrieving first index for range %d: %s\", rangeID, err)\n\t}\n\n\tif oldestIndex < firstIndex {\n\t\treturn 0, 0, util.Errorf(\"raft log's oldest index is less than the first index for range %d\", rangeID)\n\t}\n\n\t\/\/ Return the number of truncatable indexes.\n\treturn oldestIndex - firstIndex, oldestIndex, nil\n}\n\n\/\/ shouldQueue determines whether a range should be queued for truncating. This\n\/\/ is true only if the replica is the raft leader and if the total number of\n\/\/ the range's raft log's stale entries exceeds RaftLogQueueStaleThreshold.\nfunc (*raftLogQueue) shouldQueue(now roachpb.Timestamp, r *Replica, _ config.SystemConfig) (shouldQ bool,\n\tpriority float64) {\n\n\ttruncatableIndexes, _, err := getTruncatableIndexes(r)\n\tif err != nil {\n\t\tlog.Warning(err)\n\t\treturn false, 0\n\t}\n\n\treturn truncatableIndexes > RaftLogQueueStaleThreshold, float64(truncatableIndexes)\n}\n\n\/\/ process truncates the raft log of the range if the replica is the raft\n\/\/ leader and if the total number of the range's raft log's stale entries\n\/\/ exceeds RaftLogQueueStaleThreshold.\nfunc (rlq *raftLogQueue) process(now roachpb.Timestamp, r *Replica, _ config.SystemConfig) error {\n\n\ttruncatableIndexes, oldestIndex, err := getTruncatableIndexes(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Can and should the raft logs be truncated?\n\tif truncatableIndexes > RaftLogQueueStaleThreshold {\n\t\tif log.V(1) {\n\t\t\tlog.Infof(\"truncating the raft log of range %d to %d\", r.RangeID, oldestIndex)\n\t\t}\n\t\tb := &client.Batch{}\n\t\tb.InternalAddRequest(&roachpb.TruncateLogRequest{\n\t\t\tSpan:    roachpb.Span{Key: r.Desc().StartKey.AsRawKey()},\n\t\t\tIndex:   oldestIndex,\n\t\t\tRangeID: r.RangeID,\n\t\t})\n\t\treturn rlq.db.Run(b).GoError()\n\t}\n\treturn nil\n}\n\n\/\/ timer returns interval between processing successive queued truncations.\nfunc (*raftLogQueue) timer() time.Duration {\n\treturn RaftLogQueueTimerDuration\n}\n\n\/\/ purgatoryChan returns nil.\nfunc (*raftLogQueue) purgatoryChan() <-chan struct{} {\n\treturn nil\n}\n<commit_msg>storage: add more info to a raft truncation error message<commit_after>\/\/ Copyright 2015 The Cockroach Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\/\/\n\/\/ Author: Bram Gruneir (bram+code@cockroachlabs.com)\n\npackage storage\n\nimport (\n\t\"time\"\n\n\t\"github.com\/cockroachdb\/cockroach\/client\"\n\t\"github.com\/cockroachdb\/cockroach\/config\"\n\t\"github.com\/cockroachdb\/cockroach\/gossip\"\n\t\"github.com\/cockroachdb\/cockroach\/roachpb\"\n\t\"github.com\/cockroachdb\/cockroach\/util\"\n\t\"github.com\/cockroachdb\/cockroach\/util\/log\"\n\t\"github.com\/coreos\/etcd\/raft\"\n)\n\nconst (\n\t\/\/ raftLogQueueMaxSize is the max size of the queue.\n\traftLogQueueMaxSize = 100\n\t\/\/ RaftLogQueueTimerDuration is the duration between checking the\n\t\/\/ raft logs.\n\tRaftLogQueueTimerDuration = time.Second\n\t\/\/ RaftLogQueueStaleThreshold is the minimum threshold for stale raft log\n\t\/\/ entries. A stale entry is one which all replicas of the range have\n\t\/\/ progressed past and thus is no longer needed and can be pruned.\n\tRaftLogQueueStaleThreshold = 1\n)\n\n\/\/ raftLogQueue manages a queue of replicas slated to have their raft logs\n\/\/ truncated by removing unneeded entries.\ntype raftLogQueue struct {\n\tbaseQueue\n\tdb *client.DB\n}\n\n\/\/ newRaftLogQueue returns a new instance of raftLogQueue.\nfunc newRaftLogQueue(db *client.DB, gossip *gossip.Gossip) *raftLogQueue {\n\trlq := &raftLogQueue{\n\t\tdb: db,\n\t}\n\trlq.baseQueue = makeBaseQueue(\"raftlog\", rlq, gossip, raftLogQueueMaxSize)\n\treturn rlq\n}\n\nfunc (*raftLogQueue) needsLeaderLease() bool {\n\treturn false\n}\n\nfunc (*raftLogQueue) acceptsUnsplitRanges() bool {\n\treturn true\n}\n\n\/\/ getTruncatableIndexes returns the total number of stale raft log entries that\n\/\/ can be truncated and the oldest index that cannot be pruned.\nfunc getTruncatableIndexes(r *Replica) (uint64, uint64, error) {\n\trangeID := r.RangeID\n\traftStatus := r.store.RaftStatus(rangeID)\n\tif raftStatus == nil {\n\t\tif log.V(1) {\n\t\t\tlog.Infof(\"the raft group doesn't exist for range %d\", rangeID)\n\t\t}\n\t\treturn 0, 0, nil\n\t}\n\n\t\/\/ Is this the raft leader?\n\tif raftStatus.RaftState != raft.StateLeader {\n\t\treturn 0, 0, nil\n\t}\n\n\t\/\/ Find the oldest index still in use by the range.\n\toldestIndex := raftStatus.Applied\n\tfor _, progress := range raftStatus.Progress {\n\t\tif progress.Match < oldestIndex {\n\t\t\toldestIndex = progress.Match\n\t\t}\n\t}\n\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tfirstIndex, err := r.FirstIndex()\n\tif err != nil {\n\t\treturn 0, 0, util.Errorf(\"error retrieving first index for range %d: %s\", rangeID, err)\n\t}\n\n\tif oldestIndex < firstIndex {\n\t\treturn 0, 0, util.Errorf(\"raft log's oldest index (%d) is less than the first index (%d) for range %d\",\n\t\t\toldestIndex, firstIndex, rangeID)\n\t}\n\n\t\/\/ Return the number of truncatable indexes.\n\treturn oldestIndex - firstIndex, oldestIndex, nil\n}\n\n\/\/ shouldQueue determines whether a range should be queued for truncating. This\n\/\/ is true only if the replica is the raft leader and if the total number of\n\/\/ the range's raft log's stale entries exceeds RaftLogQueueStaleThreshold.\nfunc (*raftLogQueue) shouldQueue(now roachpb.Timestamp, r *Replica, _ config.SystemConfig) (shouldQ bool,\n\tpriority float64) {\n\n\ttruncatableIndexes, _, err := getTruncatableIndexes(r)\n\tif err != nil {\n\t\tlog.Warning(err)\n\t\treturn false, 0\n\t}\n\n\treturn truncatableIndexes > RaftLogQueueStaleThreshold, float64(truncatableIndexes)\n}\n\n\/\/ process truncates the raft log of the range if the replica is the raft\n\/\/ leader and if the total number of the range's raft log's stale entries\n\/\/ exceeds RaftLogQueueStaleThreshold.\nfunc (rlq *raftLogQueue) process(now roachpb.Timestamp, r *Replica, _ config.SystemConfig) error {\n\n\ttruncatableIndexes, oldestIndex, err := getTruncatableIndexes(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Can and should the raft logs be truncated?\n\tif truncatableIndexes > RaftLogQueueStaleThreshold {\n\t\tif log.V(1) {\n\t\t\tlog.Infof(\"truncating the raft log of range %d to %d\", r.RangeID, oldestIndex)\n\t\t}\n\t\tb := &client.Batch{}\n\t\tb.InternalAddRequest(&roachpb.TruncateLogRequest{\n\t\t\tSpan:    roachpb.Span{Key: r.Desc().StartKey.AsRawKey()},\n\t\t\tIndex:   oldestIndex,\n\t\t\tRangeID: r.RangeID,\n\t\t})\n\t\treturn rlq.db.Run(b).GoError()\n\t}\n\treturn nil\n}\n\n\/\/ timer returns interval between processing successive queued truncations.\nfunc (*raftLogQueue) timer() time.Duration {\n\treturn RaftLogQueueTimerDuration\n}\n\n\/\/ purgatoryChan returns nil.\nfunc (*raftLogQueue) purgatoryChan() <-chan struct{} {\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build linux\n\npackage storage\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n\t\"math\/rand\"\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestWAL(t *testing.T) {\n\tassert := assert.New(t)\n\n\t\/\/Create temp directory\n\tdir, err := ioutil.TempDir(\"\", \"IosWALTests\")\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir) \/\/ clean up\n\n\t\/\/create file\n  testFile := dir + \"\/test.temp\"\n\twal := openWriteAheadFile(testFile, \"fsync\")\n\tactualBytes, err := ioutil.ReadFile(testFile)\n\tassert.Equal(64*1000*1000,len(actualBytes), \"File is expected size\")\n\n\t\/\/verfiy that write ahead logging works\n  expectedBytes := make([]byte, 100)\n\trand.Read(expectedBytes)\n  wal.writeAhead(expectedBytes)\n  actualBytes, err = ioutil.ReadFile(testFile)\n  assert.Nil(err)\n  \/\/assert.Equal(1001,len(actualBytes), \"Number of bytes read is not same as bytes written\")\n  assert.Equal(expectedBytes,actualBytes[len(actualBytes)-100:], \"Bytes read are not same as written\")\n\n}\n<commit_msg>shifting write ahead test bytes by 1<commit_after>\/\/ +build linux\n\npackage storage\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n\t\"math\/rand\"\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestWAL(t *testing.T) {\n\tassert := assert.New(t)\n\n\t\/\/Create temp directory\n\tdir, err := ioutil.TempDir(\"\", \"IosWALTests\")\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir) \/\/ clean up\n\n\t\/\/create file\n  testFile := dir + \"\/test.temp\"\n\twal := openWriteAheadFile(testFile, \"fsync\")\n\tactualBytes, err := ioutil.ReadFile(testFile)\n\tassert.Equal(64*1000*1000,len(actualBytes), \"File is expected size\")\n\n\t\/\/verfiy that write ahead logging works\n  expectedBytes := make([]byte, 100)\n\trand.Read(expectedBytes)\n  wal.writeAhead(expectedBytes)\n  actualBytes, err = ioutil.ReadFile(testFile)\n  assert.Nil(err)\n  \/\/assert.Equal(1001,len(actualBytes), \"Number of bytes read is not same as bytes written\")\n  assert.Equal(expectedBytes,actualBytes[len(actualBytes)-100+1:], \"Bytes read are not same as written\")\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package revolver provides a revolving file writer.\npackage revolver\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sync\"\n)\n\ntype revWriter struct {\n\tdir      string\n\tprefix   string\n\tsuffix   string\n\tmiddle   func() string\n\tmaxBytes int\n\tmaxFiles int\n\tsize     int\n\tfile     *os.File\n\tlock     *sync.Mutex \/\/ synchronizes file operations\n}\n\n\/\/ Must wraps the call to NewWriter and returns a io.WriteCloser or panics\nfunc Must(w io.WriteCloser, err error) io.WriteCloser {\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"could not create revolving log writer, %v\", err))\n\t}\n\treturn w\n}\n\n\/\/ New  returns a io.WriteCloser that writes revolving files as specified by the given conf.\n\/\/ Calling New will always create a new file even if there is space left in other files.\n\/\/ If the configured directory doesn't exist it will be created.\nfunc New(conf Conf) (io.WriteCloser, error) {\n\tif err := ValidConf(conf); err != nil {\n\t\treturn nil, err\n\t}\n\tconf = clean(conf)\n\treturn NewQuick(conf.Dir, conf.Prefix, conf.Suffix, conf.Middle, conf.MaxBytes, conf.MaxFiles)\n}\n\n\/\/ NewQuick returns a io.WriteCloser that writes revolving files.\n\/\/ Calling New will always create a new file even if there is space left in other files.\n\/\/ If the configured directory doesn't exist it will be created.\nfunc NewQuick(dir, prefix, suffix string, middle func() string, maxBytes, maxFiles int) (io.WriteCloser, error) {\n\tif prefix == \"\" {\n\t\treturn nil, fmt.Errorf(\"revolver, prefix can not be empty\")\n\t}\n\tif middle == nil {\n\t\tmiddle = func() string { return \"\" }\n\t}\n\tif maxBytes < 1 {\n\t\treturn nil, fmt.Errorf(\"revolver, maxBytes must be > 0\")\n\t}\n\tif maxFiles < 1 {\n\t\treturn nil, fmt.Errorf(\"revolver, maxFiles must be > 0\")\n\t}\n\n\tif err := setupDirs(dir); err != nil {\n\t\treturn nil, fmt.Errorf(\"revolver setup, %v\", err)\n\t}\n\tif err := countAndRemoveFiles(dir, prefix, maxFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"revolver, remove, %v\", err)\n\t}\n\n\tfile, err := createFile(dir, prefix, suffix, middle)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"revolver, create, %v\", err)\n\t}\n\n\treturn &revWriter{\n\t\tdir:      filepath.Clean(dir),\n\t\tprefix:   filepath.Clean(prefix),\n\t\tsuffix:   suffix,\n\t\tmiddle:   middle,\n\t\tmaxBytes: maxBytes,\n\t\tmaxFiles: maxFiles,\n\t\tfile:     file,\n\t\tlock:     &sync.Mutex{},\n\t}, nil\n}\n\n\/\/ Write the given bytes into the log file specified by the given conf.\n\/\/ If there is not enough file space left,surplus files will be deleted and a new file will be created.\nfunc (l *revWriter) Write(p []byte) (n int, err error) {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tsize := len(p)\n\tif size > l.maxBytes {\n\t\treturn 0, fmt.Errorf(\"revolver, bytes to write %d over max file size %d\", size, l.maxBytes)\n\t}\n\tif l.file == nil || l.size+size > l.maxBytes {\n\t\tif err := l.close(); err != nil {\n\t\t\treturn 0, fmt.Errorf(\"revolver, close, %v\", err)\n\t\t}\n\n\t\tif err := countAndRemoveFiles(l.dir, l.prefix, l.maxFiles); err != nil {\n\t\t\treturn 0, fmt.Errorf(\"revolver, remove, %v\", err)\n\t\t}\n\n\t\tfile, err := createFile(l.dir, l.prefix, l.suffix, l.middle)\n\t\tif err != nil {\n\t\t\treturn 0, fmt.Errorf(\"revolver, create, %v\", err)\n\n\t\t}\n\t\tl.file = file\n\t\tl.size = 0\n\t}\n\n\tl.size += size\n\treturn l.file.Write(p)\n\n}\n\n\/\/ Close closes the current log file and sets the writer reference to nil.\n\/\/ If the file reference is nil, the returned err is always be nil.\n\/\/ Writing to a nil referencing writer cleans up surplus files and creates a new file.\nfunc (l *revWriter) Close() error {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\treturn l.close()\n}\n\nfunc (l *revWriter) close() error {\n\tif l.file == nil {\n\t\treturn nil\n\t}\n\terr := l.file.Close()\n\tl.file = nil\n\treturn err\n\n}\n<commit_msg>Modified comments.<commit_after>\/\/ Package revolver provides a revolving file writer.\npackage revolver\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sync\"\n)\n\ntype revWriter struct {\n\tdir      string\n\tprefix   string\n\tsuffix   string\n\tmiddle   func() string\n\tmaxBytes int\n\tmaxFiles int\n\tsize     int\n\tfile     *os.File\n\tlock     *sync.Mutex \/\/ synchronizes file operations\n}\n\n\/\/ Must wraps the call to NewWriter and returns a io.WriteCloser or panics\nfunc Must(w io.WriteCloser, err error) io.WriteCloser {\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"could not create revolving log writer, %v\", err))\n\t}\n\treturn w\n}\n\n\/\/ New  returns a io.WriteCloser that writes revolving files as specified by the given conf.\n\/\/ Calling New will always create a new file even if there is space left in other files.\n\/\/ If the configured directory doesn't exist it will be created.\nfunc New(conf Conf) (io.WriteCloser, error) {\n\tif err := ValidConf(conf); err != nil {\n\t\treturn nil, err\n\t}\n\tconf = clean(conf)\n\treturn NewQuick(conf.Dir, conf.Prefix, conf.Suffix, conf.Middle, conf.MaxBytes, conf.MaxFiles)\n}\n\n\/\/ NewQuick is like New with the difference that no Conf struct is needed.\n\/\/ Calling New will always create a new file even if there is space left in other files.\n\/\/ If the configured directory doesn't exist it will be created.\nfunc NewQuick(dir, prefix, suffix string, middle func() string, maxBytes, maxFiles int) (io.WriteCloser, error) {\n\tif prefix == \"\" {\n\t\treturn nil, fmt.Errorf(\"revolver, prefix can not be empty\")\n\t}\n\tif middle == nil {\n\t\tmiddle = func() string { return \"\" }\n\t}\n\tif maxBytes < 1 {\n\t\treturn nil, fmt.Errorf(\"revolver, maxBytes must be > 0\")\n\t}\n\tif maxFiles < 1 {\n\t\treturn nil, fmt.Errorf(\"revolver, maxFiles must be > 0\")\n\t}\n\n\tif err := setupDirs(dir); err != nil {\n\t\treturn nil, fmt.Errorf(\"revolver setup, %v\", err)\n\t}\n\tif err := countAndRemoveFiles(dir, prefix, maxFiles); err != nil {\n\t\treturn nil, fmt.Errorf(\"revolver, remove, %v\", err)\n\t}\n\n\tfile, err := createFile(dir, prefix, suffix, middle)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"revolver, create, %v\", err)\n\t}\n\n\treturn &revWriter{\n\t\tdir:      filepath.Clean(dir),\n\t\tprefix:   filepath.Clean(prefix),\n\t\tsuffix:   suffix,\n\t\tmiddle:   middle,\n\t\tmaxBytes: maxBytes,\n\t\tmaxFiles: maxFiles,\n\t\tfile:     file,\n\t\tlock:     &sync.Mutex{},\n\t}, nil\n}\n\n\/\/ Write writes the given bytes into the current file. The specifics of the file are specified on writer creation.\n\/\/ If there is not enough file space left,surplus files will be deleted and a new file will be created.\nfunc (l *revWriter) Write(p []byte) (n int, err error) {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\n\tsize := len(p)\n\tif size > l.maxBytes {\n\t\treturn 0, fmt.Errorf(\"revolver, bytes to write %d over max file size %d\", size, l.maxBytes)\n\t}\n\tif l.file == nil || l.size+size > l.maxBytes {\n\t\tif err := l.close(); err != nil {\n\t\t\treturn 0, fmt.Errorf(\"revolver, close, %v\", err)\n\t\t}\n\n\t\tif err := countAndRemoveFiles(l.dir, l.prefix, l.maxFiles); err != nil {\n\t\t\treturn 0, fmt.Errorf(\"revolver, remove, %v\", err)\n\t\t}\n\n\t\tfile, err := createFile(l.dir, l.prefix, l.suffix, l.middle)\n\t\tif err != nil {\n\t\t\treturn 0, fmt.Errorf(\"revolver, create, %v\", err)\n\n\t\t}\n\t\tl.file = file\n\t\tl.size = 0\n\t}\n\n\tl.size += size\n\treturn l.file.Write(p)\n\n}\n\n\/\/ Close closes the current log file and sets the writer reference to nil.\n\/\/ If the file reference is nil, the returned err is always be nil.\n\/\/ Writing to a nil referencing writer cleans up surplus files and creates a new file.\nfunc (l *revWriter) Close() error {\n\tl.lock.Lock()\n\tdefer l.lock.Unlock()\n\treturn l.close()\n}\n\nfunc (l *revWriter) close() error {\n\tif l.file == nil {\n\t\treturn nil\n\t}\n\terr := l.file.Close()\n\tl.file = nil\n\treturn err\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package zerolog\n\nimport (\n\t\"io\"\n\t\"sync\"\n)\n\n\/\/ LevelWriter defines as interface a writer may implement in order\n\/\/ to receive level information with payload.\ntype LevelWriter interface {\n\tio.Writer\n\tWriteLevel(level Level, p []byte) (n int, err error)\n}\n\ntype levelWriterAdapter struct {\n\tio.Writer\n}\n\nfunc (lw levelWriterAdapter) WriteLevel(l Level, p []byte) (n int, err error) {\n\treturn lw.Write(p)\n}\n\ntype syncWriter struct {\n\tmu sync.Mutex\n\tlw LevelWriter\n}\n\n\/\/ SyncWriter wraps w so that each call to Write is synchronized with a mutex.\n\/\/ This syncer can be the call to writer's Write method is not thread safe.\n\/\/ Note that os.File Write operation is using write() syscall which is supposed\n\/\/ to be thread-safe on POSIX systems. So there is no need to use this with\n\/\/ os.File on such systems as zerolog guaranties to issue a single Write call\n\/\/ per log event.\nfunc SyncWriter(w io.Writer) io.Writer {\n\tif lw, ok := w.(LevelWriter); ok {\n\t\treturn &syncWriter{lw: lw}\n\t}\n\treturn &syncWriter{lw: levelWriterAdapter{w}}\n}\n\n\/\/ Write implements the io.Writer interface.\nfunc (s *syncWriter) Write(p []byte) (n int, err error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.lw.Write(p)\n}\n\n\/\/ WriteLevel implements the LevelWriter interface.\nfunc (s *syncWriter) WriteLevel(l Level, p []byte) (n int, err error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.lw.WriteLevel(l, p)\n}\n\ntype multiLevelWriter struct {\n\twriters []LevelWriter\n}\n\nfunc (t multiLevelWriter) Write(p []byte) (n int, err error) {\n\tfor _, w := range t.writers {\n\t\tn, err = w.Write(p)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif n != len(p) {\n\t\t\terr = io.ErrShortWrite\n\t\t\treturn\n\t\t}\n\t}\n\treturn len(p), nil\n}\n\nfunc (t multiLevelWriter) WriteLevel(l Level, p []byte) (n int, err error) {\n\tfor _, w := range t.writers {\n\t\tn, err = w.WriteLevel(l, p)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif n != len(p) {\n\t\t\terr = io.ErrShortWrite\n\t\t\treturn\n\t\t}\n\t}\n\treturn len(p), nil\n}\n\n\/\/ MultiLevelWriter creates a writer that duplicates its writes to all the\n\/\/ provided writers, similar to the Unix tee(1) command. If some writers\n\/\/ implement LevelWriter, their WriteLevel method will be used instead of Write.\nfunc MultiLevelWriter(writers ...io.Writer) LevelWriter {\n\tlwriters := make([]LevelWriter, 0, len(writers))\n\tfor _, w := range writers {\n\t\tif lw, ok := w.(LevelWriter); ok {\n\t\t\tlwriters = append(lwriters, lw)\n\t\t} else {\n\t\t\tlwriters = append(lwriters, levelWriterAdapter{w})\n\t\t}\n\t}\n\treturn multiLevelWriter{lwriters}\n}\n<commit_msg>Typo fix (#233)<commit_after>package zerolog\n\nimport (\n\t\"io\"\n\t\"sync\"\n)\n\n\/\/ LevelWriter defines as interface a writer may implement in order\n\/\/ to receive level information with payload.\ntype LevelWriter interface {\n\tio.Writer\n\tWriteLevel(level Level, p []byte) (n int, err error)\n}\n\ntype levelWriterAdapter struct {\n\tio.Writer\n}\n\nfunc (lw levelWriterAdapter) WriteLevel(l Level, p []byte) (n int, err error) {\n\treturn lw.Write(p)\n}\n\ntype syncWriter struct {\n\tmu sync.Mutex\n\tlw LevelWriter\n}\n\n\/\/ SyncWriter wraps w so that each call to Write is synchronized with a mutex.\n\/\/ This syncer can be the call to writer's Write method is not thread safe.\n\/\/ Note that os.File Write operation is using write() syscall which is supposed\n\/\/ to be thread-safe on POSIX systems. So there is no need to use this with\n\/\/ os.File on such systems as zerolog guarantees to issue a single Write call\n\/\/ per log event.\nfunc SyncWriter(w io.Writer) io.Writer {\n\tif lw, ok := w.(LevelWriter); ok {\n\t\treturn &syncWriter{lw: lw}\n\t}\n\treturn &syncWriter{lw: levelWriterAdapter{w}}\n}\n\n\/\/ Write implements the io.Writer interface.\nfunc (s *syncWriter) Write(p []byte) (n int, err error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.lw.Write(p)\n}\n\n\/\/ WriteLevel implements the LevelWriter interface.\nfunc (s *syncWriter) WriteLevel(l Level, p []byte) (n int, err error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.lw.WriteLevel(l, p)\n}\n\ntype multiLevelWriter struct {\n\twriters []LevelWriter\n}\n\nfunc (t multiLevelWriter) Write(p []byte) (n int, err error) {\n\tfor _, w := range t.writers {\n\t\tn, err = w.Write(p)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif n != len(p) {\n\t\t\terr = io.ErrShortWrite\n\t\t\treturn\n\t\t}\n\t}\n\treturn len(p), nil\n}\n\nfunc (t multiLevelWriter) WriteLevel(l Level, p []byte) (n int, err error) {\n\tfor _, w := range t.writers {\n\t\tn, err = w.WriteLevel(l, p)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif n != len(p) {\n\t\t\terr = io.ErrShortWrite\n\t\t\treturn\n\t\t}\n\t}\n\treturn len(p), nil\n}\n\n\/\/ MultiLevelWriter creates a writer that duplicates its writes to all the\n\/\/ provided writers, similar to the Unix tee(1) command. If some writers\n\/\/ implement LevelWriter, their WriteLevel method will be used instead of Write.\nfunc MultiLevelWriter(writers ...io.Writer) LevelWriter {\n\tlwriters := make([]LevelWriter, 0, len(writers))\n\tfor _, w := range writers {\n\t\tif lw, ok := w.(LevelWriter); ok {\n\t\t\tlwriters = append(lwriters, lw)\n\t\t} else {\n\t\t\tlwriters = append(lwriters, levelWriterAdapter{w})\n\t\t}\n\t}\n\treturn multiLevelWriter{lwriters}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nxslate is an extremely powerful template engine, based on Perl5's Text::Xslate\nmodule. Xslate uses a virtual machine to execute pre-compiled template bytecode,\nwhich gives its flexibility while maitaining a very fast execution speed.\n\nNote that RenderString() DOES NOT CACHE THE GENERATED BYTECODE. This has\nsignificant effect on performance if you repeatedly call the same template\n\n*\/\npackage xslate\n\nimport (\n  \"errors\"\n  \"fmt\"\n  \"io\/ioutil\"\n  \"os\"\n  \"reflect\"\n\n  \"github.com\/lestrrat\/go-xslate\/compiler\"\n  \"github.com\/lestrrat\/go-xslate\/loader\"\n  \"github.com\/lestrrat\/go-xslate\/parser\"\n  \"github.com\/lestrrat\/go-xslate\/parser\/tterse\"\n  \"github.com\/lestrrat\/go-xslate\/vm\"\n)\n\ntype Vars vm.Vars\ntype Xslate struct {\n  Flags    int32\n  Vm       *vm.VM\n  Compiler compiler.Compiler\n  Parser   parser.Parser\n  Loader   loader.ByteCodeLoader\n  \/\/ XXX Need to make syntax pluggable\n}\n\ntype ConfigureArgs interface {\n  Get(string) (interface {}, bool)\n}\n\ntype Args map[string]interface {}\n\n\/\/ Given an unconfigured Xslate instance and arguments, sets up\n\/\/ the compiler of said Xslate instance. Current implementation\n\/\/ just uses compiler.New()\nfunc DefaultCompiler(tx *Xslate, args Args) error {\n  tx.Compiler = compiler.New()\n  return nil\n}\n\nfunc DefaultParser(tx *Xslate, args Args) error {\n  syntax, ok := args.Get(\"Syntax\")\n  if ! ok {\n    syntax = \"TTerse\"\n  }\n\n  switch syntax {\n  case \"TTerse\":\n    tx.Parser = tterse.New()\n  default:\n    return errors.New(fmt.Sprintf(\"Syntax '%s' not available\", syntax))\n  }\n  return nil\n}\n\nfunc DefaultLoader(tx *Xslate, args Args) error {\n  var tmp interface {}\n\n  tmp, ok := args.Get(\"CacheDir\")\n  if !ok {\n    tmp, _ = ioutil.TempDir(\"\", \"go-xslate-cache-\")\n  }\n  cacheDir := tmp.(string)\n\n  tmp, ok = args.Get(\"LoadPaths\")\n  if !ok {\n    cwd, _ := os.Getwd()\n    tmp = []string { cwd }\n  }\n  paths := tmp.([]string)\n\n  cache, err := loader.NewFileCache(cacheDir)\n  if err != nil {\n    return err\n  }\n  fetcher, err := loader.NewFileTemplateFetcher(paths)\n  if err != nil {\n    return err\n  }\n  tx.Loader = loader.NewCachedByteCodeLoader(cache, fetcher, tx.Parser, tx.Compiler)\n  return nil\n}\n\nfunc DefaultVm(tx *Xslate, args Args) error {\n  tx.Vm = vm.NewVM()\n  tx.Vm.Loader = tx.Loader\n  return nil\n}\n\nfunc (args Args) Get(key string) (interface {}, bool) {\n  ret, ok := args[key]\n  return ret, ok\n}\n\nfunc (tx *Xslate) configureGeneric(configuror interface {}, args Args) error {\n  ref := reflect.ValueOf(configuror)\n  switch ref.Type().Kind() {\n  case reflect.Func:\n    \/\/ If this is a function, it better take our Xslate instance as the\n    \/\/ sole argument, and initialize it as it pleases\n    if ref.Type().NumIn() != 2 && (ref.Type().In(0).Name() != \"Xslate\" || ref.Type().In(1).Name() != \"Args\") {\n      panic(fmt.Sprintf(`Expected function initializer \"func (tx *Xslate \", but instead of %s`, ref.Type))\n    }\n    cb := configuror.(func(*Xslate, Args) error)\n    err := cb(tx, args)\n    return err\n  }\n  return errors.New(\"Bad configurator\")\n}\n\nfunc (tx *Xslate) Configure(args ConfigureArgs) error {\n  \/\/ The compiler currently does not have any configurable options, but\n  \/\/ one may want to replace the entire compiler struct\n  defaults := map[string]func(*Xslate, Args) error {\n    \"Compiler\": DefaultCompiler,\n    \"Parser\":   DefaultParser,\n    \"Loader\":   DefaultLoader,\n    \"Vm\":       DefaultVm,\n  }\n\n  for _, key := range []string { \"Parser\", \"Compiler\", \"Loader\", \"Vm\" } {\n    configKey := \"Configure\" + key\n    configuror, ok := args.Get(configKey);\n    if !ok {\n      configuror = defaults[key]\n    }\n\n    args, ok := args.Get(key)\n    if !ok {\n      args = Args {}\n    }\n\n    err := tx.configureGeneric(configuror, args.(Args))\n    if err != nil {\n      return err\n    }\n  }\n\n  return nil\n}\n\nfunc New(args ...Args) (*Xslate, error) {\n  tx := &Xslate {}\n\n  \/\/ We jump through hoops because there are A LOT of configuration options\n  \/\/ but most of them only need to use the default values\n  if len(args) <= 0 {\n    args = []Args { Args {} }\n  }\n  err := tx.Configure(args[0])\n  if err != nil {\n    return nil, err\n  }\n  return tx, nil\n}\n\nfunc (tx *Xslate) DumpAST(b bool) {\n  tx.Loader.DumpAST(b)\n}\n\nfunc (tx *Xslate) DumpByteCode(b bool) {\n  tx.Loader.DumpByteCode(b)\n}\n\nfunc (x *Xslate) Render(name string, vars Vars) (string, error) {\n  bc, err := x.Loader.Load(name)\n  if err != nil {\n    return \"\", err\n  }\n  x.Vm.Run(bc, vm.Vars(vars))\n  return x.Vm.OutputString()\n}\n\nfunc (x *Xslate) RenderString(template string, vars Vars) (string, error) {\n  bc, err := x.Loader.LoadString(template)\n  if err != nil {\n    return \"\", err\n  }\n\n  x.Vm.Run(bc, vm.Vars(vars))\n  return x.Vm.OutputString()\n}\n<commit_msg>Respect go vet<commit_after>\/*\nxslate is an extremely powerful template engine, based on Perl5's Text::Xslate\nmodule. Xslate uses a virtual machine to execute pre-compiled template bytecode,\nwhich gives its flexibility while maitaining a very fast execution speed.\n\nNote that RenderString() DOES NOT CACHE THE GENERATED BYTECODE. This has\nsignificant effect on performance if you repeatedly call the same template\n\n*\/\npackage xslate\n\nimport (\n  \"errors\"\n  \"fmt\"\n  \"io\/ioutil\"\n  \"os\"\n  \"reflect\"\n\n  \"github.com\/lestrrat\/go-xslate\/compiler\"\n  \"github.com\/lestrrat\/go-xslate\/loader\"\n  \"github.com\/lestrrat\/go-xslate\/parser\"\n  \"github.com\/lestrrat\/go-xslate\/parser\/tterse\"\n  \"github.com\/lestrrat\/go-xslate\/vm\"\n)\n\ntype Vars vm.Vars\ntype Xslate struct {\n  Flags    int32\n  Vm       *vm.VM\n  Compiler compiler.Compiler\n  Parser   parser.Parser\n  Loader   loader.ByteCodeLoader\n  \/\/ XXX Need to make syntax pluggable\n}\n\ntype ConfigureArgs interface {\n  Get(string) (interface {}, bool)\n}\n\ntype Args map[string]interface {}\n\n\/\/ Given an unconfigured Xslate instance and arguments, sets up\n\/\/ the compiler of said Xslate instance. Current implementation\n\/\/ just uses compiler.New()\nfunc DefaultCompiler(tx *Xslate, args Args) error {\n  tx.Compiler = compiler.New()\n  return nil\n}\n\nfunc DefaultParser(tx *Xslate, args Args) error {\n  syntax, ok := args.Get(\"Syntax\")\n  if ! ok {\n    syntax = \"TTerse\"\n  }\n\n  switch syntax {\n  case \"TTerse\":\n    tx.Parser = tterse.New()\n  default:\n    return errors.New(fmt.Sprintf(\"Syntax '%s' not available\", syntax))\n  }\n  return nil\n}\n\nfunc DefaultLoader(tx *Xslate, args Args) error {\n  var tmp interface {}\n\n  tmp, ok := args.Get(\"CacheDir\")\n  if !ok {\n    tmp, _ = ioutil.TempDir(\"\", \"go-xslate-cache-\")\n  }\n  cacheDir := tmp.(string)\n\n  tmp, ok = args.Get(\"LoadPaths\")\n  if !ok {\n    cwd, _ := os.Getwd()\n    tmp = []string { cwd }\n  }\n  paths := tmp.([]string)\n\n  cache, err := loader.NewFileCache(cacheDir)\n  if err != nil {\n    return err\n  }\n  fetcher, err := loader.NewFileTemplateFetcher(paths)\n  if err != nil {\n    return err\n  }\n  tx.Loader = loader.NewCachedByteCodeLoader(cache, fetcher, tx.Parser, tx.Compiler)\n  return nil\n}\n\nfunc DefaultVm(tx *Xslate, args Args) error {\n  tx.Vm = vm.NewVM()\n  tx.Vm.Loader = tx.Loader\n  return nil\n}\n\nfunc (args Args) Get(key string) (interface {}, bool) {\n  ret, ok := args[key]\n  return ret, ok\n}\n\nfunc (tx *Xslate) configureGeneric(configuror interface {}, args Args) error {\n  ref := reflect.ValueOf(configuror)\n  switch ref.Type().Kind() {\n  case reflect.Func:\n    \/\/ If this is a function, it better take our Xslate instance as the\n    \/\/ sole argument, and initialize it as it pleases\n    if ref.Type().NumIn() != 2 && (ref.Type().In(0).Name() != \"Xslate\" || ref.Type().In(1).Name() != \"Args\") {\n      panic(fmt.Sprintf(`Expected function initializer \"func (tx *Xslate \", but instead of %s`, ref.Type.String()))\n    }\n    cb := configuror.(func(*Xslate, Args) error)\n    err := cb(tx, args)\n    return err\n  }\n  return errors.New(\"Bad configurator\")\n}\n\nfunc (tx *Xslate) Configure(args ConfigureArgs) error {\n  \/\/ The compiler currently does not have any configurable options, but\n  \/\/ one may want to replace the entire compiler struct\n  defaults := map[string]func(*Xslate, Args) error {\n    \"Compiler\": DefaultCompiler,\n    \"Parser\":   DefaultParser,\n    \"Loader\":   DefaultLoader,\n    \"Vm\":       DefaultVm,\n  }\n\n  for _, key := range []string { \"Parser\", \"Compiler\", \"Loader\", \"Vm\" } {\n    configKey := \"Configure\" + key\n    configuror, ok := args.Get(configKey);\n    if !ok {\n      configuror = defaults[key]\n    }\n\n    args, ok := args.Get(key)\n    if !ok {\n      args = Args {}\n    }\n\n    err := tx.configureGeneric(configuror, args.(Args))\n    if err != nil {\n      return err\n    }\n  }\n\n  return nil\n}\n\nfunc New(args ...Args) (*Xslate, error) {\n  tx := &Xslate {}\n\n  \/\/ We jump through hoops because there are A LOT of configuration options\n  \/\/ but most of them only need to use the default values\n  if len(args) <= 0 {\n    args = []Args { Args {} }\n  }\n  err := tx.Configure(args[0])\n  if err != nil {\n    return nil, err\n  }\n  return tx, nil\n}\n\nfunc (tx *Xslate) DumpAST(b bool) {\n  tx.Loader.DumpAST(b)\n}\n\nfunc (tx *Xslate) DumpByteCode(b bool) {\n  tx.Loader.DumpByteCode(b)\n}\n\nfunc (x *Xslate) Render(name string, vars Vars) (string, error) {\n  bc, err := x.Loader.Load(name)\n  if err != nil {\n    return \"\", err\n  }\n  x.Vm.Run(bc, vm.Vars(vars))\n  return x.Vm.OutputString()\n}\n\nfunc (x *Xslate) RenderString(template string, vars Vars) (string, error) {\n  bc, err := x.Loader.LoadString(template)\n  if err != nil {\n    return \"\", err\n  }\n\n  x.Vm.Run(bc, vm.Vars(vars))\n  return x.Vm.OutputString()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package xxhash implements the 64-bit variant of xxHash (XXH64) as described\n\/\/ at http:\/\/cyan4973.github.io\/xxHash\/.\npackage xxhash\n\nimport (\n\t\"encoding\/binary\"\n\t\"hash\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\nconst (\n\tprime1 uint64 = 11400714785074694791\n\tprime2 uint64 = 14029467366897019727\n\tprime3 uint64 = 1609587929392839161\n\tprime4 uint64 = 9650029242287828579\n\tprime5 uint64 = 2870177450012600261\n)\n\n\/\/ NOTE(caleb): I'm using both consts and vars of the primes. Using consts where\n\/\/ possible in the Go code is worth a small (but measurable) performance boost\n\/\/ by avoiding some MOVQs. Vars are needed for the asm and also are useful for\n\/\/ convenience in the Go code in a few places where we need to intentionally\n\/\/ avoid constant arithmetic (e.g., v1 := prime1 + prime2 fails because the\n\/\/ result overflows a uint64).\nvar (\n\tprime1v = prime1\n\tprime2v = prime2\n\tprime3v = prime3\n\tprime4v = prime4\n\tprime5v = prime5\n)\n\n\/\/ Sum64String computes the 64-bit xxHash digest of s.\n\/\/ It may be faster than Sum64([]byte(s)) by avoiding a copy.\n\/\/\n\/\/ TODO(caleb): Consider removing this if an optimization is ever added to make\n\/\/ it unnecessary: https:\/\/golang.org\/issue\/\/2205.\n\/\/\n\/\/ TODO(caleb): We still have a function call; we could instead write Go\/asm\n\/\/ copies of Sum64 for strings to squeeze out a bit more speed.\nfunc Sum64String(s string) uint64 {\n\tvar b []byte\n\tsh := (*reflect.StringHeader)(unsafe.Pointer(&s))\n\tbh := (*reflect.SliceHeader)(unsafe.Pointer(&b))\n\tbh.Data = uintptr(unsafe.Pointer(sh.Data))\n\tbh.Len = sh.Len\n\tbh.Cap = sh.Len\n\treturn Sum64(b)\n}\n\ntype xxh struct {\n\tv1    uint64\n\tv2    uint64\n\tv3    uint64\n\tv4    uint64\n\ttotal int\n\tmem   [32]byte\n\tn     int \/\/ how much of mem is used\n}\n\n\/\/ New creates a new hash.Hash64 that implements the 64-bit xxHash algorithm.\nfunc New() hash.Hash64 {\n\tvar x xxh\n\tx.Reset()\n\treturn &x\n}\n\nfunc (x *xxh) Reset() {\n\tx.n = 0\n\tx.total = 0\n\tx.v1 = prime1v + prime2\n\tx.v2 = prime2\n\tx.v3 = 0\n\tx.v4 = -prime1v\n}\n\nfunc (x *xxh) Size() int      { return 8 }\nfunc (x *xxh) BlockSize() int { return 32 }\n\n\/\/ Write adds more data to x. It always returns len(b), nil.\nfunc (x *xxh) Write(b []byte) (n int, err error) {\n\tn = len(b)\n\tx.total += len(b)\n\n\tif x.n+len(b) < 32 {\n\t\t\/\/ This new data doesn't even fill the current block.\n\t\tcopy(x.mem[x.n:], b)\n\t\tx.n += len(b)\n\t\treturn\n\t}\n\n\tif x.n > 0 {\n\t\t\/\/ Finish off the partial block.\n\t\tcopy(x.mem[x.n:], b)\n\t\tx.v1 = round(x.v1, u64(x.mem[0:8]))\n\t\tx.v2 = round(x.v2, u64(x.mem[8:16]))\n\t\tx.v3 = round(x.v3, u64(x.mem[16:24]))\n\t\tx.v4 = round(x.v4, u64(x.mem[24:32]))\n\t\tb = b[32-x.n:]\n\t\tx.n = 0\n\t}\n\n\tif len(b) >= 32 {\n\t\t\/\/ One or more full blocks left.\n\t\tb = writeBlocks(x, b)\n\t}\n\n\t\/\/ Store any remaining partial block.\n\tcopy(x.mem[:], b)\n\tx.n = len(b)\n\n\treturn\n}\n\nfunc (x *xxh) Sum(b []byte) []byte {\n\ts := x.Sum64()\n\treturn append(\n\t\tb,\n\t\tbyte(s>>56),\n\t\tbyte(s>>48),\n\t\tbyte(s>>40),\n\t\tbyte(s>>32),\n\t\tbyte(s>>24),\n\t\tbyte(s>>16),\n\t\tbyte(s>>8),\n\t\tbyte(s),\n\t)\n}\n\nfunc (x *xxh) Sum64() uint64 {\n\tvar h uint64\n\n\tif x.total >= 32 {\n\t\tv1, v2, v3, v4 := x.v1, x.v2, x.v3, x.v4\n\t\th = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4)\n\t\th = mergeRound(h, v1)\n\t\th = mergeRound(h, v2)\n\t\th = mergeRound(h, v3)\n\t\th = mergeRound(h, v4)\n\t} else {\n\t\th = x.v3 + prime5\n\t}\n\n\th += uint64(x.total)\n\n\ti, end := 0, x.n\n\tfor ; i+8 <= end; i += 8 {\n\t\tk1 := round(0, u64(x.mem[i:i+8]))\n\t\th ^= k1\n\t\th = rol27(h)*prime1 + prime4\n\t}\n\tif i+4 <= end {\n\t\th ^= uint64(u32(x.mem[i:i+4])) * prime1\n\t\th = rol23(h)*prime2 + prime3\n\t\ti += 4\n\t}\n\tfor i < end {\n\t\th ^= uint64(x.mem[i]) * prime5\n\t\th = rol11(h) * prime1\n\t\ti++\n\t}\n\n\th ^= h >> 33\n\th *= prime2\n\th ^= h >> 29\n\th *= prime3\n\th ^= h >> 32\n\n\treturn h\n}\n\nfunc u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) }\nfunc u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) }\n\nfunc round(acc, input uint64) uint64 {\n\tacc += input * prime2\n\tacc = rol31(acc)\n\tacc *= prime1\n\treturn acc\n}\n\nfunc mergeRound(acc, val uint64) uint64 {\n\tval = round(0, val)\n\tacc ^= val\n\tacc = acc*prime1 + prime4\n\treturn acc\n}\n\n\/\/ It's important for performance to get the rotates to actually compile to\n\/\/ ROLQs. gc will do this for us but only if rotate amount is a constant.\n\/\/\n\/\/ TODO(caleb): In Go 1.9 a single function\n\/\/   rol(x uint64, k uint) uint64\n\/\/ should do instead. See https:\/\/golang.org\/issue\/18254.\n\/\/\n\/\/ TODO(caleb): In Go 1.x (1.9?) consider using the new math\/bits package to be more\n\/\/ explicit about things. See https:\/\/golang.org\/issue\/18616.\n\nfunc rol1(x uint64) uint64  { return (x << 1) | (x >> (64 - 1)) }\nfunc rol7(x uint64) uint64  { return (x << 7) | (x >> (64 - 7)) }\nfunc rol11(x uint64) uint64 { return (x << 11) | (x >> (64 - 11)) }\nfunc rol12(x uint64) uint64 { return (x << 12) | (x >> (64 - 12)) }\nfunc rol18(x uint64) uint64 { return (x << 18) | (x >> (64 - 18)) }\nfunc rol23(x uint64) uint64 { return (x << 23) | (x >> (64 - 23)) }\nfunc rol27(x uint64) uint64 { return (x << 27) | (x >> (64 - 27)) }\nfunc rol31(x uint64) uint64 { return (x << 31) | (x >> (64 - 31)) }\n<commit_msg>Remove unnecessary type conversions<commit_after>\/\/ Package xxhash implements the 64-bit variant of xxHash (XXH64) as described\n\/\/ at http:\/\/cyan4973.github.io\/xxHash\/.\npackage xxhash\n\nimport (\n\t\"encoding\/binary\"\n\t\"hash\"\n\t\"reflect\"\n\t\"unsafe\"\n)\n\nconst (\n\tprime1 uint64 = 11400714785074694791\n\tprime2 uint64 = 14029467366897019727\n\tprime3 uint64 = 1609587929392839161\n\tprime4 uint64 = 9650029242287828579\n\tprime5 uint64 = 2870177450012600261\n)\n\n\/\/ NOTE(caleb): I'm using both consts and vars of the primes. Using consts where\n\/\/ possible in the Go code is worth a small (but measurable) performance boost\n\/\/ by avoiding some MOVQs. Vars are needed for the asm and also are useful for\n\/\/ convenience in the Go code in a few places where we need to intentionally\n\/\/ avoid constant arithmetic (e.g., v1 := prime1 + prime2 fails because the\n\/\/ result overflows a uint64).\nvar (\n\tprime1v = prime1\n\tprime2v = prime2\n\tprime3v = prime3\n\tprime4v = prime4\n\tprime5v = prime5\n)\n\n\/\/ Sum64String computes the 64-bit xxHash digest of s.\n\/\/ It may be faster than Sum64([]byte(s)) by avoiding a copy.\n\/\/\n\/\/ TODO(caleb): Consider removing this if an optimization is ever added to make\n\/\/ it unnecessary: https:\/\/golang.org\/issue\/\/2205.\n\/\/\n\/\/ TODO(caleb): We still have a function call; we could instead write Go\/asm\n\/\/ copies of Sum64 for strings to squeeze out a bit more speed.\nfunc Sum64String(s string) uint64 {\n\tvar b []byte\n\tsh := (*reflect.StringHeader)(unsafe.Pointer(&s))\n\tbh := (*reflect.SliceHeader)(unsafe.Pointer(&b))\n\tbh.Data = sh.Data\n\tbh.Len = sh.Len\n\tbh.Cap = sh.Len\n\treturn Sum64(b)\n}\n\ntype xxh struct {\n\tv1    uint64\n\tv2    uint64\n\tv3    uint64\n\tv4    uint64\n\ttotal int\n\tmem   [32]byte\n\tn     int \/\/ how much of mem is used\n}\n\n\/\/ New creates a new hash.Hash64 that implements the 64-bit xxHash algorithm.\nfunc New() hash.Hash64 {\n\tvar x xxh\n\tx.Reset()\n\treturn &x\n}\n\nfunc (x *xxh) Reset() {\n\tx.n = 0\n\tx.total = 0\n\tx.v1 = prime1v + prime2\n\tx.v2 = prime2\n\tx.v3 = 0\n\tx.v4 = -prime1v\n}\n\nfunc (x *xxh) Size() int      { return 8 }\nfunc (x *xxh) BlockSize() int { return 32 }\n\n\/\/ Write adds more data to x. It always returns len(b), nil.\nfunc (x *xxh) Write(b []byte) (n int, err error) {\n\tn = len(b)\n\tx.total += len(b)\n\n\tif x.n+len(b) < 32 {\n\t\t\/\/ This new data doesn't even fill the current block.\n\t\tcopy(x.mem[x.n:], b)\n\t\tx.n += len(b)\n\t\treturn\n\t}\n\n\tif x.n > 0 {\n\t\t\/\/ Finish off the partial block.\n\t\tcopy(x.mem[x.n:], b)\n\t\tx.v1 = round(x.v1, u64(x.mem[0:8]))\n\t\tx.v2 = round(x.v2, u64(x.mem[8:16]))\n\t\tx.v3 = round(x.v3, u64(x.mem[16:24]))\n\t\tx.v4 = round(x.v4, u64(x.mem[24:32]))\n\t\tb = b[32-x.n:]\n\t\tx.n = 0\n\t}\n\n\tif len(b) >= 32 {\n\t\t\/\/ One or more full blocks left.\n\t\tb = writeBlocks(x, b)\n\t}\n\n\t\/\/ Store any remaining partial block.\n\tcopy(x.mem[:], b)\n\tx.n = len(b)\n\n\treturn\n}\n\nfunc (x *xxh) Sum(b []byte) []byte {\n\ts := x.Sum64()\n\treturn append(\n\t\tb,\n\t\tbyte(s>>56),\n\t\tbyte(s>>48),\n\t\tbyte(s>>40),\n\t\tbyte(s>>32),\n\t\tbyte(s>>24),\n\t\tbyte(s>>16),\n\t\tbyte(s>>8),\n\t\tbyte(s),\n\t)\n}\n\nfunc (x *xxh) Sum64() uint64 {\n\tvar h uint64\n\n\tif x.total >= 32 {\n\t\tv1, v2, v3, v4 := x.v1, x.v2, x.v3, x.v4\n\t\th = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4)\n\t\th = mergeRound(h, v1)\n\t\th = mergeRound(h, v2)\n\t\th = mergeRound(h, v3)\n\t\th = mergeRound(h, v4)\n\t} else {\n\t\th = x.v3 + prime5\n\t}\n\n\th += uint64(x.total)\n\n\ti, end := 0, x.n\n\tfor ; i+8 <= end; i += 8 {\n\t\tk1 := round(0, u64(x.mem[i:i+8]))\n\t\th ^= k1\n\t\th = rol27(h)*prime1 + prime4\n\t}\n\tif i+4 <= end {\n\t\th ^= uint64(u32(x.mem[i:i+4])) * prime1\n\t\th = rol23(h)*prime2 + prime3\n\t\ti += 4\n\t}\n\tfor i < end {\n\t\th ^= uint64(x.mem[i]) * prime5\n\t\th = rol11(h) * prime1\n\t\ti++\n\t}\n\n\th ^= h >> 33\n\th *= prime2\n\th ^= h >> 29\n\th *= prime3\n\th ^= h >> 32\n\n\treturn h\n}\n\nfunc u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) }\nfunc u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) }\n\nfunc round(acc, input uint64) uint64 {\n\tacc += input * prime2\n\tacc = rol31(acc)\n\tacc *= prime1\n\treturn acc\n}\n\nfunc mergeRound(acc, val uint64) uint64 {\n\tval = round(0, val)\n\tacc ^= val\n\tacc = acc*prime1 + prime4\n\treturn acc\n}\n\n\/\/ It's important for performance to get the rotates to actually compile to\n\/\/ ROLQs. gc will do this for us but only if rotate amount is a constant.\n\/\/\n\/\/ TODO(caleb): In Go 1.9 a single function\n\/\/   rol(x uint64, k uint) uint64\n\/\/ should do instead. See https:\/\/golang.org\/issue\/18254.\n\/\/\n\/\/ TODO(caleb): In Go 1.x (1.9?) consider using the new math\/bits package to be more\n\/\/ explicit about things. See https:\/\/golang.org\/issue\/18616.\n\nfunc rol1(x uint64) uint64  { return (x << 1) | (x >> (64 - 1)) }\nfunc rol7(x uint64) uint64  { return (x << 7) | (x >> (64 - 7)) }\nfunc rol11(x uint64) uint64 { return (x << 11) | (x >> (64 - 11)) }\nfunc rol12(x uint64) uint64 { return (x << 12) | (x >> (64 - 12)) }\nfunc rol18(x uint64) uint64 { return (x << 18) | (x >> (64 - 18)) }\nfunc rol23(x uint64) uint64 { return (x << 23) | (x >> (64 - 23)) }\nfunc rol27(x uint64) uint64 { return (x << 27) | (x >> (64 - 27)) }\nfunc rol31(x uint64) uint64 { return (x << 31) | (x >> (64 - 31)) }\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017 Pani Networks\n\/\/ All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n\/\/ not use this file except in compliance with the License. You may obtain\n\/\/ a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations\n\/\/ under the License.\n\n\/\/ Romana CNI plugin configures kubernetes pods on Romana network.\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"runtime\"\n\t\"syscall\"\n\n\t\"github.com\/romana\/core\/pkg\/cni\/kubernetes\"\n\n\t\"github.com\/containernetworking\/cni\/pkg\/ip\"\n\t\"github.com\/containernetworking\/cni\/pkg\/ns\"\n\t\"github.com\/containernetworking\/cni\/pkg\/skel\"\n\t\"github.com\/containernetworking\/cni\/pkg\/types\"\n\t\"github.com\/containernetworking\/cni\/pkg\/types\/current\"\n\t\"github.com\/containernetworking\/cni\/pkg\/version\"\n\tutil \"github.com\/romana\/core\/pkg\/cni\"\n\tlog \"github.com\/romana\/rlog\"\n\t\"github.com\/vishvananda\/netlink\"\n)\n\nfunc init() {\n\t\/\/ This ensures that main runs only on main thread (thread group leader).\n\t\/\/ since namespace ops (unshare, setns) are done for a single thread, we\n\t\/\/ must ensure that the goroutine does not jump from OS thread to thread\n\truntime.LockOSThread()\n}\n\n\/\/ cmdAdd is a callback functions that gets called by skel.PluginMain\n\/\/ in response to ADD method.\nfunc cmdAdd(args *skel.CmdArgs) error {\n\tvar err error\n\t\/\/ netConf stores Romana related config\n\t\/\/ that comes form stdin.\n\tnetConf, _, _ := loadConf(args.StdinData)\n\tcniVersion := netConf.CNIVersion\n\tlog.Debugf(\"Loaded netConf %v\", netConf)\n\n\t\/\/ LoadArgs parses kubernetes related parameters from CNI\n\t\/\/ environment variables.\n\tk8sargs := kubernetes.K8sArgs{}\n\terr = types.LoadArgs(args.Args, &k8sargs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to types.LoadArgs, err=%(err)\", err)\n\t}\n\tlog.Debugf(\"Loaded Kubernetes args %v\", k8sargs)\n\n\t\/\/ Retrieves additional information about the pod\n\tpod, err := kubernetes.GetPodDescription(k8sargs, netConf.KubernetesConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Deferring deallocation before allocating ip address,\n\t\/\/ deallocation will be called on any return unless\n\t\/\/ flag set to false.\n\tvar deallocateOnExit = true\n\tdefer func() {\n\t\tif deallocateOnExit {\n\t\t\tdeallocator, err := util.NewRomanaAddressManager(util.DefaultProvider)\n\n\t\t\t\/\/ don't want to panic here\n\t\t\tif netConf != nil && err == nil {\n\t\t\t\tlog.Errorf(\"Deallocating IP on exist, something went wrong\")\n\t\t\t\t_ = deallocator.Deallocate(*netConf, pod.Name)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ Allocating ip address.\n\tallocator, err := util.NewRomanaAddressManager(util.DefaultProvider)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpodAddress, err := allocator.Allocate(*netConf, util.RomanaAllocatorPodDescription{\n\t\tName:        pod.Name,\n\t\tHostname:    netConf.RomanaHostName,\n\t\tNamespace:   pod.Namespace,\n\t\tLabels:      pod.Labels,\n\t\tAnnotations: pod.Annotations,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Networking setup\n\t_, gwAddr, err := GetRomanaGwAddr()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to detect ipv4 address on romana-gw interface, err=(%s)\", err)\n\t}\n\n\tnetns, err := ns.GetNS(args.Netns)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open netns %q: %v\", args.Netns, err)\n\t}\n\tdefer netns.Close()\n\n\t\/\/ Magic variables for callback.\n\tcontIface := &current.Interface{}\n\thostIface := &current.Interface{}\n\tifName := \"eth0\"\n\tmtu := 1500 \/\/TODO for stas, make configurable\n\t_, defaultNet, _ := net.ParseCIDR(\"0.0.0.0\/0\")\n\n\t\/\/ And this is a callback inside the callback, it sets up networking\n\t\/\/ withing a pod namespace, nice thing it save us from shellouts\n\t\/\/ but still, callback within a callback.\n\terr = netns.Do(func(hostNS ns.NetNS) error {\n\t\t\/\/ Creates veth interfacces.\n\t\thostVeth, containerVeth, err := ip.SetupVeth(ifName, mtu, hostNS)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ transportNet is a romana-gw cidr turned into romana-gw.IP\/32\n\t\ttransportNet := net.IPNet{IP: gwAddr.IP, Mask: net.IPMask([]byte{0xff, 0xff, 0xff, 0xff})}\n\t\ttransportRoute := netlink.Route{\n\t\t\tLinkIndex: containerVeth.Index,\n\t\t\tDst:       &transportNet,\n\t\t}\n\n\t\t\/\/ sets up transport route to allow installing default route\n\t\terr = netlink.RouteAdd(&transportRoute)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"route add error=(%s)\", err)\n\t\t}\n\n\t\t\/\/ default route for the pod\n\t\tdefaultRoute := netlink.Route{\n\t\t\tDst:       defaultNet,\n\t\t\tLinkIndex: containerVeth.Index,\n\t\t}\n\t\terr = netlink.RouteAdd(&defaultRoute)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"route add default error=(%s)\", err)\n\t\t}\n\n\t\tcontainerVethLink, err := netlink.LinkByIndex(containerVeth.Index)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to discover container veth, err=(%s)\", err)\n\t\t}\n\n\t\tpodIP, err := netlink.ParseAddr(podAddress.String())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"netlink failed to parse address %s, err=(%s)\", podAddress, err)\n\t\t}\n\n\t\terr = netlink.AddrAdd(containerVethLink, podIP)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to add ip address %s to the interface %s, err=(%s)\", podIP, containerVeth, err)\n\t\t}\n\n\t\tcontIface.Name = containerVeth.Name\n\t\tcontIface.Mac = containerVeth.HardwareAddr.String()\n\t\tcontIface.Sandbox = netns.Path()\n\t\thostIface.Name = hostVeth.Name\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create veth interfaces in namespace %v, err=(%s)\", netns, err)\n\t}\n\n\t\/\/ Rename host part of veth to something convinient.\n\tvethExternalName := k8sargs.MakeVethName()\n\terr = RenameLink(hostIface.Name, vethExternalName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to rename host part of veth interface from %s to %s, err=(%s)\", hostIface.Name, vethExternalName, err)\n\t}\n\n\t\/\/ Return route.\n\terr = AddEndpointRoute(vethExternalName, podAddress)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to setup return route to %s via interface %s, err=(%s)\", podAddress, hostIface.Name, err)\n\t}\n\n\tresult := &current.Result{\n\t\tIPs: []*current.IPConfig{\n\t\t\t&current.IPConfig{\n\t\t\t\tVersion:   \"4\",\n\t\t\t\tAddress:   *podAddress,\n\t\t\t\tInterface: 0,\n\t\t\t},\n\t\t},\n\t}\n\n\tresult.Interfaces = []*current.Interface{hostIface}\n\n\tdeallocateOnExit = false\n\treturn types.PrintResult(result, cniVersion)\n}\n\n\/\/ cmdDel is a callback functions that gets called by skel.PluginMain\n\/\/ in response to DEL method.\nfunc cmdDel(args *skel.CmdArgs) error {\n\tvar err error\n\t\/\/ netConf stores Romana related config\n\t\/\/ that comes form stdin.\n\tnetConf, _, _ := loadConf(args.StdinData)\n\n\t\/\/ LoadArgs parses kubernetes related parameters from CNI\n\t\/\/ environment variables.\n\tk8sargs := kubernetes.K8sArgs{}\n\terr = types.LoadArgs(args.Args, &k8sargs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdeallocator, err := util.NewRomanaAddressManager(util.DefaultProvider)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = deallocator.Deallocate(*netConf, k8sargs.MakePodName())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to tear down pod network for %s, err=(%s)\", k8sargs.MakePodName(), err)\n\t}\n\n\treturn nil\n}\n\n\/\/ GetRomanaGwAddr detects ip address assigned to romana-gw interface.\nfunc GetRomanaGwAddr() (netlink.Link, *net.IPNet, error) {\n\tconst gwIface = \"romana-gw\"\n\tromanaGw, err := netlink.LinkByName(gwIface)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\taddr, err := netlink.AddrList(romanaGw, syscall.AF_INET)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif len(addr) != 1 {\n\t\treturn nil, nil, fmt.Errorf(\"Expected exactly 1 ipv4 address on romana-gw interface, found %d\", len(addr))\n\t}\n\n\treturn romanaGw, addr[0].IPNet, nil\n}\n\n\/\/ RenameLink renames interface.\nfunc RenameLink(curName, newName string) error {\n\tcurVeth, err := netlink.LinkByName(curName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to lookup %q: %v\", curName, err)\n\t}\n\n\tif err = netlink.LinkSetDown(curVeth); err != nil {\n\t\treturn fmt.Errorf(\"failed to set %q up: %v\", curName, err)\n\t}\n\n\terr = netlink.LinkSetName(curVeth, newName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to rename %q: %v\", curVeth, newName)\n\t}\n\n\tnewVeth, err := netlink.LinkByName(newName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to lookup %q: %v\", newName, err)\n\t}\n\n\terr = netlink.LinkSetUp(newVeth)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set %q up: %v\", newVeth, err)\n\t}\n\n\treturn nil\n}\n\n\/\/ AddEndpointRoute adds return \/32 route from host to pod.\nfunc AddEndpointRoute(ifaceName string, ip *net.IPNet) error {\n\tveth, err := netlink.LinkByName(ifaceName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturnRoute := netlink.Route{\n\t\tDst:       ip,\n\t\tLinkIndex: veth.Attrs().Index,\n\t}\n\n\terr = netlink.RouteAdd(&returnRoute)\n\n\treturn nil\n}\n\n\/\/ loadConf initializes romana config from stdin.\nfunc loadConf(bytes []byte) (*util.NetConf, string, error) {\n\tn := &util.NetConf{}\n\tif err := json.Unmarshal(bytes, n); err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"failed to load netconf: %s\", err)\n\t}\n\n\t\/\/ TODO for stas\n\t\/\/ verify config here\n\tif n.RomanaHostName == \"\" {\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn nil, \"\", fmt.Errorf(\"failed to load netconf: %s\", err)\n\t\t}\n\n\t\tn.RomanaHostName = hostname\n\t}\n\n\treturn n, n.CNIVersion, nil\n}\n\nfunc main() {\n\tskel.PluginMain(cmdAdd, cmdDel, version.All)\n}\n<commit_msg>Formating verb fix<commit_after>\/\/ Copyright (c) 2017 Pani Networks\n\/\/ All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n\/\/ not use this file except in compliance with the License. You may obtain\n\/\/ a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations\n\/\/ under the License.\n\n\/\/ Romana CNI plugin configures kubernetes pods on Romana network.\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"runtime\"\n\t\"syscall\"\n\n\t\"github.com\/romana\/core\/pkg\/cni\/kubernetes\"\n\n\t\"github.com\/containernetworking\/cni\/pkg\/ip\"\n\t\"github.com\/containernetworking\/cni\/pkg\/ns\"\n\t\"github.com\/containernetworking\/cni\/pkg\/skel\"\n\t\"github.com\/containernetworking\/cni\/pkg\/types\"\n\t\"github.com\/containernetworking\/cni\/pkg\/types\/current\"\n\t\"github.com\/containernetworking\/cni\/pkg\/version\"\n\tutil \"github.com\/romana\/core\/pkg\/cni\"\n\tlog \"github.com\/romana\/rlog\"\n\t\"github.com\/vishvananda\/netlink\"\n)\n\nfunc init() {\n\t\/\/ This ensures that main runs only on main thread (thread group leader).\n\t\/\/ since namespace ops (unshare, setns) are done for a single thread, we\n\t\/\/ must ensure that the goroutine does not jump from OS thread to thread\n\truntime.LockOSThread()\n}\n\n\/\/ cmdAdd is a callback functions that gets called by skel.PluginMain\n\/\/ in response to ADD method.\nfunc cmdAdd(args *skel.CmdArgs) error {\n\tvar err error\n\t\/\/ netConf stores Romana related config\n\t\/\/ that comes form stdin.\n\tnetConf, _, _ := loadConf(args.StdinData)\n\tcniVersion := netConf.CNIVersion\n\tlog.Debugf(\"Loaded netConf %v\", netConf)\n\n\t\/\/ LoadArgs parses kubernetes related parameters from CNI\n\t\/\/ environment variables.\n\tk8sargs := kubernetes.K8sArgs{}\n\terr = types.LoadArgs(args.Args, &k8sargs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to types.LoadArgs, err=(%s)\", err)\n\t}\n\tlog.Debugf(\"Loaded Kubernetes args %v\", k8sargs)\n\n\t\/\/ Retrieves additional information about the pod\n\tpod, err := kubernetes.GetPodDescription(k8sargs, netConf.KubernetesConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Deferring deallocation before allocating ip address,\n\t\/\/ deallocation will be called on any return unless\n\t\/\/ flag set to false.\n\tvar deallocateOnExit = true\n\tdefer func() {\n\t\tif deallocateOnExit {\n\t\t\tdeallocator, err := util.NewRomanaAddressManager(util.DefaultProvider)\n\n\t\t\t\/\/ don't want to panic here\n\t\t\tif netConf != nil && err == nil {\n\t\t\t\tlog.Errorf(\"Deallocating IP on exist, something went wrong\")\n\t\t\t\t_ = deallocator.Deallocate(*netConf, pod.Name)\n\t\t\t}\n\t\t}\n\t}()\n\n\t\/\/ Allocating ip address.\n\tallocator, err := util.NewRomanaAddressManager(util.DefaultProvider)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpodAddress, err := allocator.Allocate(*netConf, util.RomanaAllocatorPodDescription{\n\t\tName:        pod.Name,\n\t\tHostname:    netConf.RomanaHostName,\n\t\tNamespace:   pod.Namespace,\n\t\tLabels:      pod.Labels,\n\t\tAnnotations: pod.Annotations,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Networking setup\n\t_, gwAddr, err := GetRomanaGwAddr()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to detect ipv4 address on romana-gw interface, err=(%s)\", err)\n\t}\n\n\tnetns, err := ns.GetNS(args.Netns)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open netns %q: %v\", args.Netns, err)\n\t}\n\tdefer netns.Close()\n\n\t\/\/ Magic variables for callback.\n\tcontIface := &current.Interface{}\n\thostIface := &current.Interface{}\n\tifName := \"eth0\"\n\tmtu := 1500 \/\/TODO for stas, make configurable\n\t_, defaultNet, _ := net.ParseCIDR(\"0.0.0.0\/0\")\n\n\t\/\/ And this is a callback inside the callback, it sets up networking\n\t\/\/ withing a pod namespace, nice thing it save us from shellouts\n\t\/\/ but still, callback within a callback.\n\terr = netns.Do(func(hostNS ns.NetNS) error {\n\t\t\/\/ Creates veth interfacces.\n\t\thostVeth, containerVeth, err := ip.SetupVeth(ifName, mtu, hostNS)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ transportNet is a romana-gw cidr turned into romana-gw.IP\/32\n\t\ttransportNet := net.IPNet{IP: gwAddr.IP, Mask: net.IPMask([]byte{0xff, 0xff, 0xff, 0xff})}\n\t\ttransportRoute := netlink.Route{\n\t\t\tLinkIndex: containerVeth.Index,\n\t\t\tDst:       &transportNet,\n\t\t}\n\n\t\t\/\/ sets up transport route to allow installing default route\n\t\terr = netlink.RouteAdd(&transportRoute)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"route add error=(%s)\", err)\n\t\t}\n\n\t\t\/\/ default route for the pod\n\t\tdefaultRoute := netlink.Route{\n\t\t\tDst:       defaultNet,\n\t\t\tLinkIndex: containerVeth.Index,\n\t\t}\n\t\terr = netlink.RouteAdd(&defaultRoute)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"route add default error=(%s)\", err)\n\t\t}\n\n\t\tcontainerVethLink, err := netlink.LinkByIndex(containerVeth.Index)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to discover container veth, err=(%s)\", err)\n\t\t}\n\n\t\tpodIP, err := netlink.ParseAddr(podAddress.String())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"netlink failed to parse address %s, err=(%s)\", podAddress, err)\n\t\t}\n\n\t\terr = netlink.AddrAdd(containerVethLink, podIP)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to add ip address %s to the interface %s, err=(%s)\", podIP, containerVeth, err)\n\t\t}\n\n\t\tcontIface.Name = containerVeth.Name\n\t\tcontIface.Mac = containerVeth.HardwareAddr.String()\n\t\tcontIface.Sandbox = netns.Path()\n\t\thostIface.Name = hostVeth.Name\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create veth interfaces in namespace %v, err=(%s)\", netns, err)\n\t}\n\n\t\/\/ Rename host part of veth to something convinient.\n\tvethExternalName := k8sargs.MakeVethName()\n\terr = RenameLink(hostIface.Name, vethExternalName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to rename host part of veth interface from %s to %s, err=(%s)\", hostIface.Name, vethExternalName, err)\n\t}\n\n\t\/\/ Return route.\n\terr = AddEndpointRoute(vethExternalName, podAddress)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to setup return route to %s via interface %s, err=(%s)\", podAddress, hostIface.Name, err)\n\t}\n\n\tresult := &current.Result{\n\t\tIPs: []*current.IPConfig{\n\t\t\t&current.IPConfig{\n\t\t\t\tVersion:   \"4\",\n\t\t\t\tAddress:   *podAddress,\n\t\t\t\tInterface: 0,\n\t\t\t},\n\t\t},\n\t}\n\n\tresult.Interfaces = []*current.Interface{hostIface}\n\n\tdeallocateOnExit = false\n\treturn types.PrintResult(result, cniVersion)\n}\n\n\/\/ cmdDel is a callback functions that gets called by skel.PluginMain\n\/\/ in response to DEL method.\nfunc cmdDel(args *skel.CmdArgs) error {\n\tvar err error\n\t\/\/ netConf stores Romana related config\n\t\/\/ that comes form stdin.\n\tnetConf, _, _ := loadConf(args.StdinData)\n\n\t\/\/ LoadArgs parses kubernetes related parameters from CNI\n\t\/\/ environment variables.\n\tk8sargs := kubernetes.K8sArgs{}\n\terr = types.LoadArgs(args.Args, &k8sargs)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdeallocator, err := util.NewRomanaAddressManager(util.DefaultProvider)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = deallocator.Deallocate(*netConf, k8sargs.MakePodName())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to tear down pod network for %s, err=(%s)\", k8sargs.MakePodName(), err)\n\t}\n\n\treturn nil\n}\n\n\/\/ GetRomanaGwAddr detects ip address assigned to romana-gw interface.\nfunc GetRomanaGwAddr() (netlink.Link, *net.IPNet, error) {\n\tconst gwIface = \"romana-gw\"\n\tromanaGw, err := netlink.LinkByName(gwIface)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\taddr, err := netlink.AddrList(romanaGw, syscall.AF_INET)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif len(addr) != 1 {\n\t\treturn nil, nil, fmt.Errorf(\"Expected exactly 1 ipv4 address on romana-gw interface, found %d\", len(addr))\n\t}\n\n\treturn romanaGw, addr[0].IPNet, nil\n}\n\n\/\/ RenameLink renames interface.\nfunc RenameLink(curName, newName string) error {\n\tcurVeth, err := netlink.LinkByName(curName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to lookup %q: %v\", curName, err)\n\t}\n\n\tif err = netlink.LinkSetDown(curVeth); err != nil {\n\t\treturn fmt.Errorf(\"failed to set %q up: %v\", curName, err)\n\t}\n\n\terr = netlink.LinkSetName(curVeth, newName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to rename %q: %v\", curVeth, newName)\n\t}\n\n\tnewVeth, err := netlink.LinkByName(newName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to lookup %q: %v\", newName, err)\n\t}\n\n\terr = netlink.LinkSetUp(newVeth)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to set %q up: %v\", newVeth, err)\n\t}\n\n\treturn nil\n}\n\n\/\/ AddEndpointRoute adds return \/32 route from host to pod.\nfunc AddEndpointRoute(ifaceName string, ip *net.IPNet) error {\n\tveth, err := netlink.LinkByName(ifaceName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturnRoute := netlink.Route{\n\t\tDst:       ip,\n\t\tLinkIndex: veth.Attrs().Index,\n\t}\n\n\terr = netlink.RouteAdd(&returnRoute)\n\n\treturn nil\n}\n\n\/\/ loadConf initializes romana config from stdin.\nfunc loadConf(bytes []byte) (*util.NetConf, string, error) {\n\tn := &util.NetConf{}\n\tif err := json.Unmarshal(bytes, n); err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"failed to load netconf: %s\", err)\n\t}\n\n\t\/\/ TODO for stas\n\t\/\/ verify config here\n\tif n.RomanaHostName == \"\" {\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn nil, \"\", fmt.Errorf(\"failed to load netconf: %s\", err)\n\t\t}\n\n\t\tn.RomanaHostName = hostname\n\t}\n\n\treturn n, n.CNIVersion, nil\n}\n\nfunc main() {\n\tskel.PluginMain(cmdAdd, cmdDel, version.All)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/go-ini\/ini\"\n\t\"github.com\/goadapp\/goad\/helpers\"\n\t\"github.com\/goadapp\/goad\/queue\"\n)\n\nfunc main() {\n\n\tvar (\n\t\taddress          string\n\t\tsqsurl           string\n\t\tconcurrencycount int\n\t\tmaxRequestCount  int\n\t\ttimeout          string\n\t\tfrequency        string\n\t\tawsregion        string\n\t\tqueueRegion      string\n\t\trequestMethod    string\n\t\trequestBody      string\n\t\trequestHeaders   helpers.StringsliceFlag\n\t)\n\n\tflag.StringVar(&address, \"u\", \"\", \"URL to load test (required)\")\n\tflag.StringVar(&requestMethod, \"m\", \"GET\", \"HTTP method\")\n\tflag.StringVar(&requestBody, \"b\", \"\", \"HTTP request body\")\n\tflag.StringVar(&awsregion, \"r\", \"\", \"AWS region to run in\")\n\tflag.StringVar(&queueRegion, \"q\", \"\", \"Queue region\")\n\tflag.StringVar(&sqsurl, \"s\", \"\", \"sqsUrl\")\n\tflag.StringVar(&timeout, \"t\", \"15s\", \"request timeout in seconds\")\n\tflag.StringVar(&frequency, \"f\", \"15s\", \"Reporting frequency in seconds\")\n\n\tflag.IntVar(&concurrencycount, \"c\", 10, \"number of concurrent requests\")\n\tflag.IntVar(&maxRequestCount, \"n\", 1000, \"number of total requests to make\")\n\n\tflag.Var(&requestHeaders, \"H\", \"List of headers\")\n\tflag.Parse()\n\n\tclientTimeout, _ := time.ParseDuration(timeout)\n\tfmt.Printf(\"Using a timeout of %s\\n\", clientTimeout)\n\treportingFrequency, _ := time.ParseDuration(frequency)\n\tfmt.Printf(\"Using a reporting frequency of %s\\n\", reportingFrequency)\n\n\t\/\/ InsecureSkipVerify so that sites with self signed certs can be tested\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\tclient.Timeout = clientTimeout\n\n\tcfg, err := ini.Load([]byte(\"raw data\"), \"default.ini\")\n\tif err == nil {\n\t\taddress = cfg.Section(\"general\").Key(\"url\").String()\n\t}\n\tfmt.Printf(\"Will spawn %d workers making %d requests to %s\\n\", concurrencycount, maxRequestCount, address)\n\trunLoadTest(client, sqsurl, address, maxRequestCount, concurrencycount, awsregion, reportingFrequency, queueRegion, requestMethod, requestBody, requestHeaders)\n}\n\ntype RequestResult struct {\n\tTime             int64  `json:\"time\"`\n\tHost             string `json:\"host\"`\n\tType             string `json:\"type\"`\n\tStatus           int    `json:\"status\"`\n\tElapsedFirstByte int64  `json:\"elapsed-first-byte\"`\n\tElapsedLastByte  int64  `json:\"elapsed-last-byte\"`\n\tElapsed          int64  `json:\"elapsed\"`\n\tBytes            int    `json:\"bytes\"`\n\tTimeout          bool   `json:\"timeout\"`\n\tConnectionError  bool   `json:\"connection-error\"`\n\tState            string `json:\"state\"`\n}\n\nfunc runLoadTest(client *http.Client, sqsurl string, url string, totalRequests int, concurrencycount int, awsregion string, reportingFrequency time.Duration, queueRegion string, requestMethod string, requestBody string, requestHeaders []string) {\n\tawsConfig := aws.NewConfig().WithRegion(queueRegion)\n\tsqsAdaptor := queue.NewSQSAdaptor(awsConfig, sqsurl)\n\t\/\/sqsAdaptor := queue.NewDummyAdaptor(sqsurl)\n\tjobs := make(chan struct{}, totalRequests)\n\tch := make(chan RequestResult, totalRequests)\n\tvar wg sync.WaitGroup\n\tloadTestStartTime := time.Now()\n\tvar requestsSoFar int\n\tfor i := 0; i < totalRequests; i++ {\n\t\tjobs <- struct{}{}\n\t}\n\tclose(jobs)\n\tfmt.Print(\"Spawning workers…\")\n\tfor i := 0; i < concurrencycount; i++ {\n\t\twg.Add(1)\n\t\tgo fetch(loadTestStartTime, client, url, totalRequests, jobs, ch, &wg, awsregion, requestMethod, requestBody, requestHeaders)\n\t\tfmt.Print(\".\")\n\t}\n\tfmt.Println(\" done.\\nWaiting for results…\")\n\n\tticker := time.NewTicker(reportingFrequency)\n\tquit := make(chan struct{})\n\tquitting := false\n\n\tfor requestsSoFar < totalRequests && !quitting {\n\t\ti := 0\n\n\t\tvar timeToFirstTotal int64\n\t\tvar requestTimeTotal int64\n\t\ttotBytesRead := 0\n\t\tstatuses := make(map[string]int)\n\t\ttargets := make(map[string]int)\n\t\tvar firstRequestTime int64\n\t\tvar lastRequestTime int64\n\t\tvar slowest int64\n\t\tvar fastest int64\n\t\tvar totalTimedOut int\n\t\tvar totalConnectionError int\n\n\t\tresetStats := false\n\t\tfor requestsSoFar < totalRequests && !quitting && !resetStats {\n\t\t\taggregate := false\n\t\t\tselect {\n\t\t\tcase r := <-ch:\n\t\t\t\ti++\n\t\t\t\trequestsSoFar++\n\t\t\t\tif requestsSoFar%10 == 0 || requestsSoFar == totalRequests {\n\t\t\t\t\tfmt.Printf(\"\\r%.2f%% done (%d requests out of %d)\", (float64(requestsSoFar)\/float64(totalRequests))*100.0, requestsSoFar, totalRequests)\n\t\t\t\t}\n\t\t\t\tif firstRequestTime == 0 {\n\t\t\t\t\tfirstRequestTime = r.Time\n\t\t\t\t}\n\n\t\t\t\tlastRequestTime = r.Time\n\n\t\t\t\tif r.Timeout {\n\t\t\t\t\ttotalTimedOut++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif r.ConnectionError {\n\t\t\t\t\ttotalConnectionError++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif r.ElapsedLastByte > slowest {\n\t\t\t\t\tslowest = r.ElapsedLastByte\n\t\t\t\t}\n\t\t\t\tif fastest == 0 {\n\t\t\t\t\tfastest = r.ElapsedLastByte\n\t\t\t\t} else {\n\t\t\t\t\tif r.ElapsedLastByte < fastest {\n\t\t\t\t\t\tfastest = r.ElapsedLastByte\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttimeToFirstTotal += r.ElapsedFirstByte\n\t\t\t\ttotBytesRead += r.Bytes\n\t\t\t\tstatusStr := strconv.Itoa(r.Status)\n\t\t\t\t_, ok1 := statuses[statusStr]\n\t\t\t\tif !ok1 {\n\t\t\t\t\tstatuses[statusStr] = 1\n\t\t\t\t} else {\n\t\t\t\t\tstatuses[statusStr]++\n\t\t\t\t}\n\t\t\t\t_, ok2 := targets[r.Host]\n\t\t\t\tif !ok2 {\n\t\t\t\t\ttargets[r.Host] = 1\n\t\t\t\t} else {\n\t\t\t\t\ttargets[r.Host]++\n\t\t\t\t}\n\t\t\t\trequestTimeTotal += r.Elapsed\n\t\t\t\tif requestsSoFar == totalRequests {\n\t\t\t\t\tquitting = true\n\t\t\t\t}\n\t\t\tcase <-ticker.C:\n\t\t\t\tif i == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\taggregate = true\n\t\t\tcase <-quit:\n\t\t\t\tticker.Stop()\n\t\t\t\tquitting = true\n\t\t\t}\n\t\t\tif aggregate || quitting {\n\t\t\t\tdurationNanoSeconds := lastRequestTime - firstRequestTime\n\t\t\t\tdurationSeconds := float32(durationNanoSeconds) \/ float32(1000000000)\n\t\t\t\tvar reqPerSec float32\n\t\t\t\tvar kbPerSec float32\n\t\t\t\tif durationSeconds > 0 {\n\t\t\t\t\treqPerSec = float32(i) \/ durationSeconds\n\t\t\t\t\tkbPerSec = (float32(totBytesRead) \/ durationSeconds) \/ 1024.0\n\t\t\t\t} else {\n\t\t\t\t\treqPerSec = 0\n\t\t\t\t\tkbPerSec = 0\n\t\t\t\t}\n\n\t\t\t\tfatalError := \"\"\n\t\t\t\tif (totalTimedOut + totalConnectionError) > i\/2 {\n\t\t\t\t\tfatalError = \"Over 50% of requests failed, aborting\"\n\t\t\t\t\tquitting = true\n\t\t\t\t}\n\t\t\t\taggData := queue.AggData{\n\t\t\t\t\ti,\n\t\t\t\t\ttotalTimedOut,\n\t\t\t\t\ttotalConnectionError,\n\t\t\t\t\ttimeToFirstTotal \/ int64(i),\n\t\t\t\t\ttotBytesRead,\n\t\t\t\t\tstatuses,\n\t\t\t\t\ttargets,\n\t\t\t\t\trequestTimeTotal \/ int64(i),\n\t\t\t\t\treqPerSec,\n\t\t\t\t\tkbPerSec,\n\t\t\t\t\tslowest,\n\t\t\t\t\tfastest,\n\t\t\t\t\tawsregion,\n\t\t\t\t\tfatalError,\n\t\t\t\t}\n\t\t\t\tsqsAdaptor.SendResult(aggData)\n\t\t\t\tresetStats = true\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"\\nYay🎈  - %d requests completed\\n\", requestsSoFar)\n\n}\n\nfunc fetch(loadTestStartTime time.Time, client *http.Client, address string, requestcount int, jobs <-chan struct{}, ch chan RequestResult, wg *sync.WaitGroup, awsregion string, requestMethod string, requestBody string, requestHeaders []string) {\n\tdefer wg.Done()\n\tfor _ = range jobs {\n\t\tstart := time.Now()\n\t\treq, err := http.NewRequest(requestMethod, address, bytes.NewBufferString(requestBody))\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error creating the HTTP request:\", err)\n\t\t\treturn\n\t\t}\n\t\treq.Header.Add(\"Accept-Encoding\", \"gzip\")\n\t\tfor _, v := range requestHeaders {\n\t\t\theader := strings.Split(v, \":\")\n\t\t\tif strings.ToLower(strings.Trim(header[0], \" \")) == \"host\" {\n\t\t\t\treq.Host = strings.Trim(header[1], \" \")\n\t\t\t} else {\n\t\t\t\treq.Header.Add(strings.Trim(header[0], \" \"), strings.Trim(header[1], \" \"))\n\t\t\t}\n\t\t}\n\n\t\tif req.Header.Get(\"User-Agent\") == \"\" {\n\t\t\treq.Header.Add(\"User-Agent\", \"Mozilla\/5.0 (compatible; Goad\/1.0; +https:\/\/goad.io)\")\n\t\t}\n\n\t\tresponse, err := client.Do(req)\n\t\tvar status string\n\t\tvar elapsedFirstByte time.Duration\n\t\tvar elapsedLastByte time.Duration\n\t\tvar elapsed time.Duration\n\t\tvar statusCode int\n\t\tvar bytesRead int\n\t\tbuf := []byte(\" \")\n\t\ttimedOut := false\n\t\tconnectionError := false\n\t\tisRedirect := err != nil && strings.Contains(err.Error(), \"redirect\")\n\t\tif err != nil && !isRedirect {\n\t\t\tstatus = fmt.Sprintf(\"ERROR: %s\\n\", err)\n\t\t\tswitch err := err.(type) {\n\t\t\tcase *url.Error:\n\t\t\t\tif err, ok := err.Err.(net.Error); ok && err.Timeout() {\n\t\t\t\t\ttimedOut = true\n\t\t\t\t}\n\t\t\tcase net.Error:\n\t\t\t\tif err.Timeout() {\n\t\t\t\t\ttimedOut = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !timedOut {\n\t\t\t\tconnectionError = true\n\t\t\t}\n\t\t} else {\n\t\t\tstatusCode = response.StatusCode\n\t\t\telapsedFirstByte = time.Since(start)\n\t\t\tif !isRedirect {\n\t\t\t\t_, err = response.Body.Read(buf)\n\t\t\t\tfirstByteRead := true\n\t\t\t\tif err != nil {\n\t\t\t\t\tstatus = fmt.Sprintf(\"reading first byte failed: %s\\n\", err)\n\t\t\t\t\tfirstByteRead = false\n\t\t\t\t}\n\t\t\t\tbody, err := ioutil.ReadAll(response.Body)\n\t\t\t\tif firstByteRead {\n\t\t\t\t\tbytesRead = len(body) + 1\n\t\t\t\t}\n\t\t\t\telapsedLastByte = time.Since(start)\n\t\t\t\tif err != nil {\n\t\t\t\t\t\/\/ todo: detect timeout here as well\n\t\t\t\t\tstatus = fmt.Sprintf(\"reading response body failed: %s\\n\", err)\n\t\t\t\t\tconnectionError = true\n\t\t\t\t} else {\n\t\t\t\t\tstatus = \"Success\"\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstatus = \"Redirect\"\n\t\t\t}\n\t\t\tresponse.Body.Close()\n\n\t\t\telapsed = time.Since(start)\n\t\t}\n\t\t\/\/fmt.Printf(\"Request end: %d, elapsed: %d\\n\", time.Now().Sub(loadTestStartTime).Nanoseconds(), elapsed.Nanoseconds())\n\t\tresult := RequestResult{\n\t\t\tstart.Sub(loadTestStartTime).Nanoseconds(),\n\t\t\treq.URL.Host,\n\t\t\treq.Method,\n\t\t\tstatusCode,\n\t\t\telapsedFirstByte.Nanoseconds(),\n\t\t\telapsedLastByte.Nanoseconds(),\n\t\t\telapsed.Nanoseconds(),\n\t\t\tbytesRead,\n\t\t\ttimedOut,\n\t\t\tconnectionError,\n\t\t\tstatus,\n\t\t}\n\t\tch <- result\n\t}\n}\n<commit_msg>default.ini gets now loaded and overrides, ISSUE: goad vanilla code is not really updating itself after a new build is created<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/tls\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/go-ini\/ini\"\n\t\"github.com\/goadapp\/goad\/helpers\"\n\t\"github.com\/goadapp\/goad\/queue\"\n)\n\nfunc main() {\n\n\tvar (\n\t\taddress          string\n\t\tsqsurl           string\n\t\tconcurrencycount int\n\t\tmaxRequestCount  int\n\t\ttimeout          string\n\t\tfrequency        string\n\t\tawsregion        string\n\t\tqueueRegion      string\n\t\trequestMethod    string\n\t\trequestBody      string\n\t\trequestHeaders   helpers.StringsliceFlag\n\t)\n\n\tflag.StringVar(&address, \"u\", \"\", \"URL to load test (required)\")\n\tflag.StringVar(&requestMethod, \"m\", \"GET\", \"HTTP method\")\n\tflag.StringVar(&requestBody, \"b\", \"\", \"HTTP request body\")\n\tflag.StringVar(&awsregion, \"r\", \"\", \"AWS region to run in\")\n\tflag.StringVar(&queueRegion, \"q\", \"\", \"Queue region\")\n\tflag.StringVar(&sqsurl, \"s\", \"\", \"sqsUrl\")\n\tflag.StringVar(&timeout, \"t\", \"15s\", \"request timeout in seconds\")\n\tflag.StringVar(&frequency, \"f\", \"15s\", \"Reporting frequency in seconds\")\n\n\tflag.IntVar(&concurrencycount, \"c\", 10, \"number of concurrent requests\")\n\tflag.IntVar(&maxRequestCount, \"n\", 1000, \"number of total requests to make\")\n\n\tflag.Var(&requestHeaders, \"H\", \"List of headers\")\n\tflag.Parse()\n\n\tclientTimeout, _ := time.ParseDuration(timeout)\n\tfmt.Printf(\"Using a timeout of %s\\n\", clientTimeout)\n\treportingFrequency, _ := time.ParseDuration(frequency)\n\tfmt.Printf(\"Using a reporting frequency of %s\\n\", reportingFrequency)\n\n\t\/\/ InsecureSkipVerify so that sites with self signed certs can be tested\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\tclient.Timeout = clientTimeout\n\n\tcfg, err := ini.Load(\"default.ini\")\n\tif err == nil {\n\t\taddress = cfg.Section(\"general\").Key(\"url\").String()\n\t} else {\n\t\tlog.Print(err)\n\t}\n\tfmt.Printf(\"Will spawn %d workers making %d requests to %s\\n\", concurrencycount, maxRequestCount, address)\n\trunLoadTest(client, sqsurl, address, maxRequestCount, concurrencycount, awsregion, reportingFrequency, queueRegion, requestMethod, requestBody, requestHeaders)\n}\n\n\/\/ RequestResult spitted into SQS by the lambda functions\ntype RequestResult struct {\n\tTime             int64  `json:\"time\"`\n\tHost             string `json:\"host\"`\n\tType             string `json:\"type\"`\n\tStatus           int    `json:\"status\"`\n\tElapsedFirstByte int64  `json:\"elapsed-first-byte\"`\n\tElapsedLastByte  int64  `json:\"elapsed-last-byte\"`\n\tElapsed          int64  `json:\"elapsed\"`\n\tBytes            int    `json:\"bytes\"`\n\tTimeout          bool   `json:\"timeout\"`\n\tConnectionError  bool   `json:\"connection-error\"`\n\tState            string `json:\"state\"`\n}\n\nfunc runLoadTest(client *http.Client, sqsurl string, url string, totalRequests int, concurrencycount int, awsregion string, reportingFrequency time.Duration, queueRegion string, requestMethod string, requestBody string, requestHeaders []string) {\n\tawsConfig := aws.NewConfig().WithRegion(queueRegion)\n\tsqsAdaptor := queue.NewSQSAdaptor(awsConfig, sqsurl)\n\t\/\/sqsAdaptor := queue.NewDummyAdaptor(sqsurl)\n\tjobs := make(chan struct{}, totalRequests)\n\tch := make(chan RequestResult, totalRequests)\n\tvar wg sync.WaitGroup\n\tloadTestStartTime := time.Now()\n\tvar requestsSoFar int\n\tfor i := 0; i < totalRequests; i++ {\n\t\tjobs <- struct{}{}\n\t}\n\tclose(jobs)\n\tfmt.Print(\"Spawning workers…\")\n\tfor i := 0; i < concurrencycount; i++ {\n\t\twg.Add(1)\n\t\tgo fetch(loadTestStartTime, client, url, totalRequests, jobs, ch, &wg, awsregion, requestMethod, requestBody, requestHeaders)\n\t\tfmt.Print(\".\")\n\t}\n\tfmt.Println(\" done.\\nWaiting for results…\")\n\n\tticker := time.NewTicker(reportingFrequency)\n\tquit := make(chan struct{})\n\tquitting := false\n\n\tfor requestsSoFar < totalRequests && !quitting {\n\t\ti := 0\n\n\t\tvar timeToFirstTotal int64\n\t\tvar requestTimeTotal int64\n\t\ttotBytesRead := 0\n\t\tstatuses := make(map[string]int)\n\t\ttargets := make(map[string]int)\n\t\tvar firstRequestTime int64\n\t\tvar lastRequestTime int64\n\t\tvar slowest int64\n\t\tvar fastest int64\n\t\tvar totalTimedOut int\n\t\tvar totalConnectionError int\n\n\t\tresetStats := false\n\t\tfor requestsSoFar < totalRequests && !quitting && !resetStats {\n\t\t\taggregate := false\n\t\t\tselect {\n\t\t\tcase r := <-ch:\n\t\t\t\ti++\n\t\t\t\trequestsSoFar++\n\t\t\t\tif requestsSoFar%10 == 0 || requestsSoFar == totalRequests {\n\t\t\t\t\tfmt.Printf(\"\\r%.2f%% done (%d requests out of %d)\", (float64(requestsSoFar)\/float64(totalRequests))*100.0, requestsSoFar, totalRequests)\n\t\t\t\t}\n\t\t\t\tif firstRequestTime == 0 {\n\t\t\t\t\tfirstRequestTime = r.Time\n\t\t\t\t}\n\n\t\t\t\tlastRequestTime = r.Time\n\n\t\t\t\tif r.Timeout {\n\t\t\t\t\ttotalTimedOut++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif r.ConnectionError {\n\t\t\t\t\ttotalConnectionError++\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif r.ElapsedLastByte > slowest {\n\t\t\t\t\tslowest = r.ElapsedLastByte\n\t\t\t\t}\n\t\t\t\tif fastest == 0 {\n\t\t\t\t\tfastest = r.ElapsedLastByte\n\t\t\t\t} else {\n\t\t\t\t\tif r.ElapsedLastByte < fastest {\n\t\t\t\t\t\tfastest = r.ElapsedLastByte\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttimeToFirstTotal += r.ElapsedFirstByte\n\t\t\t\ttotBytesRead += r.Bytes\n\t\t\t\tstatusStr := strconv.Itoa(r.Status)\n\t\t\t\t_, ok1 := statuses[statusStr]\n\t\t\t\tif !ok1 {\n\t\t\t\t\tstatuses[statusStr] = 1\n\t\t\t\t} else {\n\t\t\t\t\tstatuses[statusStr]++\n\t\t\t\t}\n\t\t\t\t_, ok2 := targets[r.Host]\n\t\t\t\tif !ok2 {\n\t\t\t\t\ttargets[r.Host] = 1\n\t\t\t\t} else {\n\t\t\t\t\ttargets[r.Host]++\n\t\t\t\t}\n\t\t\t\trequestTimeTotal += r.Elapsed\n\t\t\t\tif requestsSoFar == totalRequests {\n\t\t\t\t\tquitting = true\n\t\t\t\t}\n\t\t\tcase <-ticker.C:\n\t\t\t\tif i == 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\taggregate = true\n\t\t\tcase <-quit:\n\t\t\t\tticker.Stop()\n\t\t\t\tquitting = true\n\t\t\t}\n\t\t\tif aggregate || quitting {\n\t\t\t\tdurationNanoSeconds := lastRequestTime - firstRequestTime\n\t\t\t\tdurationSeconds := float32(durationNanoSeconds) \/ float32(1000000000)\n\t\t\t\tvar reqPerSec float32\n\t\t\t\tvar kbPerSec float32\n\t\t\t\tif durationSeconds > 0 {\n\t\t\t\t\treqPerSec = float32(i) \/ durationSeconds\n\t\t\t\t\tkbPerSec = (float32(totBytesRead) \/ durationSeconds) \/ 1024.0\n\t\t\t\t} else {\n\t\t\t\t\treqPerSec = 0\n\t\t\t\t\tkbPerSec = 0\n\t\t\t\t}\n\n\t\t\t\tfatalError := \"\"\n\t\t\t\tif (totalTimedOut + totalConnectionError) > i\/2 {\n\t\t\t\t\tfatalError = \"Over 50% of requests failed, aborting\"\n\t\t\t\t\tquitting = true\n\t\t\t\t}\n\t\t\t\taggData := queue.AggData{\n\t\t\t\t\ti,\n\t\t\t\t\ttotalTimedOut,\n\t\t\t\t\ttotalConnectionError,\n\t\t\t\t\ttimeToFirstTotal \/ int64(i),\n\t\t\t\t\ttotBytesRead,\n\t\t\t\t\tstatuses,\n\t\t\t\t\ttargets,\n\t\t\t\t\trequestTimeTotal \/ int64(i),\n\t\t\t\t\treqPerSec,\n\t\t\t\t\tkbPerSec,\n\t\t\t\t\tslowest,\n\t\t\t\t\tfastest,\n\t\t\t\t\tawsregion,\n\t\t\t\t\tfatalError,\n\t\t\t\t}\n\t\t\t\tsqsAdaptor.SendResult(aggData)\n\t\t\t\tresetStats = true\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Printf(\"\\nYay🎈  - %d requests completed\\n\", requestsSoFar)\n\n}\n\nfunc fetch(loadTestStartTime time.Time, client *http.Client, address string, requestcount int, jobs <-chan struct{}, ch chan RequestResult, wg *sync.WaitGroup, awsregion string, requestMethod string, requestBody string, requestHeaders []string) {\n\tdefer wg.Done()\n\tfor _ = range jobs {\n\t\tstart := time.Now()\n\t\treq, err := http.NewRequest(requestMethod, address, bytes.NewBufferString(requestBody))\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error creating the HTTP request:\", err)\n\t\t\treturn\n\t\t}\n\t\treq.Header.Add(\"Accept-Encoding\", \"gzip\")\n\t\tfor _, v := range requestHeaders {\n\t\t\theader := strings.Split(v, \":\")\n\t\t\tif strings.ToLower(strings.Trim(header[0], \" \")) == \"host\" {\n\t\t\t\treq.Host = strings.Trim(header[1], \" \")\n\t\t\t} else {\n\t\t\t\treq.Header.Add(strings.Trim(header[0], \" \"), strings.Trim(header[1], \" \"))\n\t\t\t}\n\t\t}\n\n\t\tif req.Header.Get(\"User-Agent\") == \"\" {\n\t\t\treq.Header.Add(\"User-Agent\", \"Mozilla\/5.0 (compatible; Goad\/1.0; +https:\/\/goad.io)\")\n\t\t}\n\n\t\tresponse, err := client.Do(req)\n\t\tvar status string\n\t\tvar elapsedFirstByte time.Duration\n\t\tvar elapsedLastByte time.Duration\n\t\tvar elapsed time.Duration\n\t\tvar statusCode int\n\t\tvar bytesRead int\n\t\tbuf := []byte(\" \")\n\t\ttimedOut := false\n\t\tconnectionError := false\n\t\tisRedirect := err != nil && strings.Contains(err.Error(), \"redirect\")\n\t\tif err != nil && !isRedirect {\n\t\t\tstatus = fmt.Sprintf(\"ERROR: %s\\n\", err)\n\t\t\tswitch err := err.(type) {\n\t\t\tcase *url.Error:\n\t\t\t\tif err, ok := err.Err.(net.Error); ok && err.Timeout() {\n\t\t\t\t\ttimedOut = true\n\t\t\t\t}\n\t\t\tcase net.Error:\n\t\t\t\tif err.Timeout() {\n\t\t\t\t\ttimedOut = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif !timedOut {\n\t\t\t\tconnectionError = true\n\t\t\t}\n\t\t} else {\n\t\t\tstatusCode = response.StatusCode\n\t\t\telapsedFirstByte = time.Since(start)\n\t\t\tif !isRedirect {\n\t\t\t\t_, err = response.Body.Read(buf)\n\t\t\t\tfirstByteRead := true\n\t\t\t\tif err != nil {\n\t\t\t\t\tstatus = fmt.Sprintf(\"reading first byte failed: %s\\n\", err)\n\t\t\t\t\tfirstByteRead = false\n\t\t\t\t}\n\t\t\t\tbody, err := ioutil.ReadAll(response.Body)\n\t\t\t\tif firstByteRead {\n\t\t\t\t\tbytesRead = len(body) + 1\n\t\t\t\t}\n\t\t\t\telapsedLastByte = time.Since(start)\n\t\t\t\tif err != nil {\n\t\t\t\t\t\/\/ todo: detect timeout here as well\n\t\t\t\t\tstatus = fmt.Sprintf(\"reading response body failed: %s\\n\", err)\n\t\t\t\t\tconnectionError = true\n\t\t\t\t} else {\n\t\t\t\t\tstatus = \"Success\"\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstatus = \"Redirect\"\n\t\t\t}\n\t\t\tresponse.Body.Close()\n\n\t\t\telapsed = time.Since(start)\n\t\t}\n\t\t\/\/fmt.Printf(\"Request end: %d, elapsed: %d\\n\", time.Now().Sub(loadTestStartTime).Nanoseconds(), elapsed.Nanoseconds())\n\t\tresult := RequestResult{\n\t\t\tstart.Sub(loadTestStartTime).Nanoseconds(),\n\t\t\treq.URL.Host,\n\t\t\treq.Method,\n\t\t\tstatusCode,\n\t\t\telapsedFirstByte.Nanoseconds(),\n\t\t\telapsedLastByte.Nanoseconds(),\n\t\t\telapsed.Nanoseconds(),\n\t\t\tbytesRead,\n\t\t\ttimedOut,\n\t\t\tconnectionError,\n\t\t\tstatus,\n\t\t}\n\t\tch <- result\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ +build unit\n\n\/*\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n\nCopyright 2015 Intel Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage movingaverage\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"math\/rand\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/intelsdi-x\/pulse\/control\/plugin\"\n\t\"github.com\/intelsdi-x\/pulse\/control\/plugin\/cpolicy\"\n\t\"github.com\/intelsdi-x\/pulse\/core\/ctypes\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\n\/\/Random number generator\nfunc randInt(min int, max int) int {\n\treturn min + rand.Intn(max-min)\n}\n\nfunc TestMovingAverageProcessor(t *testing.T) {\n\tmeta := Meta()\n\tConvey(\"Meta should return metadata for the plugin\", t, func() {\n\t\tConvey(\"So meta.Name should equal movingaverage\", func() {\n\t\t\tSo(meta.Name, ShouldEqual, \"movingaverage\")\n\t\t})\n\t\tConvey(\"So meta.Version should equal 2\", func() {\n\t\t\tSo(meta.Version, ShouldEqual, 2)\n\t\t})\n\t\tConvey(\"So meta.Type should be of type plugin.ProcessorPluginType\", func() {\n\t\t\tSo(meta.Type, ShouldResemble, plugin.ProcessorPluginType)\n\t\t})\n\t})\n\n\tproc := NewMovingaverageProcessor()\n\tConvey(\"Create Movingaverage processor\", t, func() {\n\t\tConvey(\"So proc should not be nil\", func() {\n\t\t\tSo(proc, ShouldNotBeNil)\n\t\t})\n\t\tConvey(\"So proc should be of type movingAverageProcessor\", func() {\n\t\t\tSo(proc, ShouldHaveSameTypeAs, &movingAverageProcessor{})\n\t\t})\n\t\tConvey(\"proc.GetConfigPolicy should return a config policy\", func() {\n\t\t\tconfigPolicy, _ := proc.GetConfigPolicy()\n\t\t\tConvey(\"So config policy should be a cpolicy.ConfigPolicy\", func() {\n\t\t\t\tSo(configPolicy, ShouldHaveSameTypeAs, &cpolicy.ConfigPolicy{})\n\t\t\t})\n\t\t\ttestConfig := make(map[string]ctypes.ConfigValue)\n\t\t\ttestConfig[\"MovingAvgBufLength\"] = ctypes.ConfigValueInt{Value: 10}\n\t\t\tcfg, errs := configPolicy.Get([]string{\"\"}).Process(testConfig)\n\t\t\tConvey(\"So config policy should process testConfig and return a config\", func() {\n\t\t\t\tSo(cfg, ShouldNotBeNil)\n\t\t\t})\n\t\t\tConvey(\"So testConfig processing should return no errors\", func() {\n\t\t\t\tSo(errs.HasErrors(), ShouldBeFalse)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestMovingAverageProcessorMetrics(t *testing.T) {\n\tConvey(\"Moving Average Processor tests\", t, func() {\n\t\tmetrics := make([]plugin.PluginMetricType, 10)\n\t\tconfig := make(map[string]ctypes.ConfigValue)\n\n\t\tconfig[\"MovingAvgBufLength\"] = ctypes.ConfigValueInt{Value: -1}\n\n\t\tConvey(\"Moving average for int data\", func() {\n\t\t\tfor i, _ := range metrics {\n\t\t\t\ttime.Sleep(3)\n\t\t\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\t\t\tdata := randInt(65, 90)\n\t\t\t\tmetrics[i] = *plugin.NewPluginMetricType([]string{\"foo\", \"bar\"}, time.Now(), \"\", data)\n\t\t\t}\n\t\t\tvar buf bytes.Buffer\n\t\t\tenc := gob.NewEncoder(&buf)\n\t\t\tenc.Encode(metrics)\n\t\t\tmovingAverageObj := NewMovingaverageProcessor()\n\n\t\t\t_, received_data, _ := movingAverageObj.Process(\"pulse.gob\", buf.Bytes(), config)\n\n\t\t\tvar metrics_new []plugin.PluginMetricType\n\n\t\t\t\/\/Decodes the content into pluginMetricType\n\t\t\tdec := gob.NewDecoder(bytes.NewBuffer(received_data))\n\t\t\tdec.Decode(&metrics_new)\n\t\t\tSo(metrics, ShouldNotResemble, metrics_new)\n\n\t\t})\n\n\t\tConvey(\"Moving average for float32 data\", func() {\n\t\t\tconfig[\"MovingAvgBufLength\"] = ctypes.ConfigValueInt{Value: 40}\n\t\t\tfor i, _ := range metrics {\n\t\t\t\ttime.Sleep(3)\n\t\t\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\t\t\tdata := randInt(65, 90)\n\t\t\t\tmetrics[i] = *plugin.NewPluginMetricType([]string{\"foo\", \"bar\"}, time.Now(), \"\", float32(data))\n\t\t\t}\n\t\t\tvar buf bytes.Buffer\n\t\t\tenc := gob.NewEncoder(&buf)\n\t\t\tenc.Encode(metrics)\n\n\t\t\tmovingAverageObj := NewMovingaverageProcessor()\n\n\t\t\t_, received_data, _ := movingAverageObj.Process(\"pulse.gob\", buf.Bytes(), config)\n\n\t\t\tvar metrics_new []plugin.PluginMetricType\n\n\t\t\t\/\/Decodes the content into pluginMetricType\n\t\t\tdec := gob.NewDecoder(bytes.NewBuffer(received_data))\n\t\t\tdec.Decode(&metrics_new)\n\t\t\tSo(metrics, ShouldNotResemble, metrics_new)\n\n\t\t})\n\t\tConvey(\"Moving average for float64 data\", func() {\n\t\t\tfor i, _ := range metrics {\n\t\t\t\ttime.Sleep(3)\n\t\t\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\t\t\tdata := randInt(65, 90)\n\t\t\t\tmetrics[i] = *plugin.NewPluginMetricType([]string{\"foo\", \"bar\"}, time.Now(), \"\", float64(data))\n\t\t\t}\n\t\t\tvar buf bytes.Buffer\n\t\t\tenc := gob.NewEncoder(&buf)\n\t\t\tenc.Encode(metrics)\n\n\t\t\tmovingAverageObj := NewMovingaverageProcessor()\n\n\t\t\t_, received_data, _ := movingAverageObj.Process(\"pulse.gob\", buf.Bytes(), nil)\n\n\t\t\tvar metrics_new []plugin.PluginMetricType\n\n\t\t\t\/\/Decodes the content into pluginMetricType\n\t\t\tdec := gob.NewDecoder(bytes.NewBuffer(received_data))\n\t\t\tdec.Decode(&metrics_new)\n\t\t\tSo(metrics, ShouldNotResemble, metrics_new)\n\n\t\t})\n\n\t\tConvey(\"Moving average for uint32 data\", func() {\n\t\t\tfor i, _ := range metrics {\n\t\t\t\ttime.Sleep(3)\n\t\t\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\t\t\tdata := randInt(65, 90)\n\t\t\t\tmetrics[i] = *plugin.NewPluginMetricType([]string{\"foo\", \"bar\"}, time.Now(), \"\", uint32(data))\n\t\t\t}\n\t\t\tvar buf bytes.Buffer\n\t\t\tenc := gob.NewEncoder(&buf)\n\t\t\tenc.Encode(metrics)\n\t\t\tmovingAverageObj := NewMovingaverageProcessor()\n\n\t\t\t_, received_data, _ := movingAverageObj.Process(\"pulse.gob\", buf.Bytes(), nil)\n\n\t\t\tvar metrics_new []plugin.PluginMetricType\n\n\t\t\t\/\/Decodes the content into pluginMetricType\n\t\t\tdec := gob.NewDecoder(bytes.NewBuffer(received_data))\n\t\t\tdec.Decode(&metrics_new)\n\t\t\tSo(metrics, ShouldNotResemble, metrics_new)\n\n\t\t})\n\n\t\tConvey(\"Moving average for uint64 data\", func() {\n\t\t\tfor i, _ := range metrics {\n\t\t\t\ttime.Sleep(3)\n\t\t\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\t\t\tdata := randInt(65, 90)\n\t\t\t\tmetrics[i] = *plugin.NewPluginMetricType([]string{\"foo\", \"bar\"}, time.Now(), \"\", uint64(data))\n\t\t\t}\n\t\t\tvar buf bytes.Buffer\n\t\t\tenc := gob.NewEncoder(&buf)\n\t\t\tenc.Encode(metrics)\n\t\t\tmovingAverageObj := NewMovingaverageProcessor()\n\n\t\t\t_, received_data, _ := movingAverageObj.Process(\"pulse.gob\", buf.Bytes(), nil)\n\n\t\t\tvar metrics_new []plugin.PluginMetricType\n\n\t\t\t\/\/Decodes the content into pluginMetricType\n\t\t\tdec := gob.NewDecoder(bytes.NewBuffer(received_data))\n\t\t\tdec.Decode(&metrics_new)\n\t\t\tSo(metrics, ShouldNotResemble, metrics_new)\n\n\t\t})\n\n\t\tConvey(\"Moving average for unknown data type\", func() {\n\t\t\tfor i, _ := range metrics {\n\n\t\t\t\tdata := \"I am an unknow data Type\"\n\t\t\t\tmetrics[i] = *plugin.NewPluginMetricType([]string{\"foo\", \"bar\"}, time.Now(), \"\", data)\n\t\t\t}\n\t\t\tvar buf bytes.Buffer\n\t\t\tenc := gob.NewEncoder(&buf)\n\t\t\tenc.Encode(metrics)\n\n\t\t\tmovingAverageObj := NewMovingaverageProcessor()\n\n\t\t\t_, received_data, _ := movingAverageObj.Process(\"pulse.gob\", buf.Bytes(), nil)\n\n\t\t\tvar metrics_new []plugin.PluginMetricType\n\n\t\t\t\/\/Decodes the content into pluginMetricType\n\t\t\tdec := gob.NewDecoder(bytes.NewBuffer(received_data))\n\t\t\tdec.Decode(&metrics_new)\n\t\t\tSo(metrics, ShouldNotResemble, metrics_new)\n\n\t\t})\n\n\t})\n}\n<commit_msg>Update test with new version<commit_after>\/\/\n\/\/ +build unit\n\n\/*\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n\nCopyright 2015 Intel Corporation\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage movingaverage\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"math\/rand\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/intelsdi-x\/pulse\/control\/plugin\"\n\t\"github.com\/intelsdi-x\/pulse\/control\/plugin\/cpolicy\"\n\t\"github.com\/intelsdi-x\/pulse\/core\/ctypes\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\n\/\/Random number generator\nfunc randInt(min int, max int) int {\n\treturn min + rand.Intn(max-min)\n}\n\nfunc TestMovingAverageProcessor(t *testing.T) {\n\tmeta := Meta()\n\tConvey(\"Meta should return metadata for the plugin\", t, func() {\n\t\tConvey(\"So meta.Name should equal movingaverage\", func() {\n\t\t\tSo(meta.Name, ShouldEqual, \"movingaverage\")\n\t\t})\n\t\tConvey(\"So meta.Version should equal 3\", func() {\n\t\t\tSo(meta.Version, ShouldEqual, 3)\n\t\t})\n\t\tConvey(\"So meta.Type should be of type plugin.ProcessorPluginType\", func() {\n\t\t\tSo(meta.Type, ShouldResemble, plugin.ProcessorPluginType)\n\t\t})\n\t})\n\n\tproc := NewMovingaverageProcessor()\n\tConvey(\"Create Movingaverage processor\", t, func() {\n\t\tConvey(\"So proc should not be nil\", func() {\n\t\t\tSo(proc, ShouldNotBeNil)\n\t\t})\n\t\tConvey(\"So proc should be of type movingAverageProcessor\", func() {\n\t\t\tSo(proc, ShouldHaveSameTypeAs, &movingAverageProcessor{})\n\t\t})\n\t\tConvey(\"proc.GetConfigPolicy should return a config policy\", func() {\n\t\t\tconfigPolicy, _ := proc.GetConfigPolicy()\n\t\t\tConvey(\"So config policy should be a cpolicy.ConfigPolicy\", func() {\n\t\t\t\tSo(configPolicy, ShouldHaveSameTypeAs, &cpolicy.ConfigPolicy{})\n\t\t\t})\n\t\t\ttestConfig := make(map[string]ctypes.ConfigValue)\n\t\t\ttestConfig[\"MovingAvgBufLength\"] = ctypes.ConfigValueInt{Value: 10}\n\t\t\tcfg, errs := configPolicy.Get([]string{\"\"}).Process(testConfig)\n\t\t\tConvey(\"So config policy should process testConfig and return a config\", func() {\n\t\t\t\tSo(cfg, ShouldNotBeNil)\n\t\t\t})\n\t\t\tConvey(\"So testConfig processing should return no errors\", func() {\n\t\t\t\tSo(errs.HasErrors(), ShouldBeFalse)\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc TestMovingAverageProcessorMetrics(t *testing.T) {\n\tConvey(\"Moving Average Processor tests\", t, func() {\n\t\tmetrics := make([]plugin.PluginMetricType, 10)\n\t\tconfig := make(map[string]ctypes.ConfigValue)\n\n\t\tconfig[\"MovingAvgBufLength\"] = ctypes.ConfigValueInt{Value: -1}\n\n\t\tConvey(\"Moving average for int data\", func() {\n\t\t\tfor i, _ := range metrics {\n\t\t\t\ttime.Sleep(3)\n\t\t\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\t\t\tdata := randInt(65, 90)\n\t\t\t\tmetrics[i] = *plugin.NewPluginMetricType([]string{\"foo\", \"bar\"}, time.Now(), \"\", data)\n\t\t\t}\n\t\t\tvar buf bytes.Buffer\n\t\t\tenc := gob.NewEncoder(&buf)\n\t\t\tenc.Encode(metrics)\n\t\t\tmovingAverageObj := NewMovingaverageProcessor()\n\n\t\t\t_, received_data, _ := movingAverageObj.Process(\"pulse.gob\", buf.Bytes(), config)\n\n\t\t\tvar metrics_new []plugin.PluginMetricType\n\n\t\t\t\/\/Decodes the content into pluginMetricType\n\t\t\tdec := gob.NewDecoder(bytes.NewBuffer(received_data))\n\t\t\tdec.Decode(&metrics_new)\n\t\t\tSo(metrics, ShouldNotResemble, metrics_new)\n\n\t\t})\n\n\t\tConvey(\"Moving average for float32 data\", func() {\n\t\t\tconfig[\"MovingAvgBufLength\"] = ctypes.ConfigValueInt{Value: 40}\n\t\t\tfor i, _ := range metrics {\n\t\t\t\ttime.Sleep(3)\n\t\t\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\t\t\tdata := randInt(65, 90)\n\t\t\t\tmetrics[i] = *plugin.NewPluginMetricType([]string{\"foo\", \"bar\"}, time.Now(), \"\", float32(data))\n\t\t\t}\n\t\t\tvar buf bytes.Buffer\n\t\t\tenc := gob.NewEncoder(&buf)\n\t\t\tenc.Encode(metrics)\n\n\t\t\tmovingAverageObj := NewMovingaverageProcessor()\n\n\t\t\t_, received_data, _ := movingAverageObj.Process(\"pulse.gob\", buf.Bytes(), config)\n\n\t\t\tvar metrics_new []plugin.PluginMetricType\n\n\t\t\t\/\/Decodes the content into pluginMetricType\n\t\t\tdec := gob.NewDecoder(bytes.NewBuffer(received_data))\n\t\t\tdec.Decode(&metrics_new)\n\t\t\tSo(metrics, ShouldNotResemble, metrics_new)\n\n\t\t})\n\t\tConvey(\"Moving average for float64 data\", func() {\n\t\t\tfor i, _ := range metrics {\n\t\t\t\ttime.Sleep(3)\n\t\t\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\t\t\tdata := randInt(65, 90)\n\t\t\t\tmetrics[i] = *plugin.NewPluginMetricType([]string{\"foo\", \"bar\"}, time.Now(), \"\", float64(data))\n\t\t\t}\n\t\t\tvar buf bytes.Buffer\n\t\t\tenc := gob.NewEncoder(&buf)\n\t\t\tenc.Encode(metrics)\n\n\t\t\tmovingAverageObj := NewMovingaverageProcessor()\n\n\t\t\t_, received_data, _ := movingAverageObj.Process(\"pulse.gob\", buf.Bytes(), nil)\n\n\t\t\tvar metrics_new []plugin.PluginMetricType\n\n\t\t\t\/\/Decodes the content into pluginMetricType\n\t\t\tdec := gob.NewDecoder(bytes.NewBuffer(received_data))\n\t\t\tdec.Decode(&metrics_new)\n\t\t\tSo(metrics, ShouldNotResemble, metrics_new)\n\n\t\t})\n\n\t\tConvey(\"Moving average for uint32 data\", func() {\n\t\t\tfor i, _ := range metrics {\n\t\t\t\ttime.Sleep(3)\n\t\t\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\t\t\tdata := randInt(65, 90)\n\t\t\t\tmetrics[i] = *plugin.NewPluginMetricType([]string{\"foo\", \"bar\"}, time.Now(), \"\", uint32(data))\n\t\t\t}\n\t\t\tvar buf bytes.Buffer\n\t\t\tenc := gob.NewEncoder(&buf)\n\t\t\tenc.Encode(metrics)\n\t\t\tmovingAverageObj := NewMovingaverageProcessor()\n\n\t\t\t_, received_data, _ := movingAverageObj.Process(\"pulse.gob\", buf.Bytes(), nil)\n\n\t\t\tvar metrics_new []plugin.PluginMetricType\n\n\t\t\t\/\/Decodes the content into pluginMetricType\n\t\t\tdec := gob.NewDecoder(bytes.NewBuffer(received_data))\n\t\t\tdec.Decode(&metrics_new)\n\t\t\tSo(metrics, ShouldNotResemble, metrics_new)\n\n\t\t})\n\n\t\tConvey(\"Moving average for uint64 data\", func() {\n\t\t\tfor i, _ := range metrics {\n\t\t\t\ttime.Sleep(3)\n\t\t\t\trand.Seed(time.Now().UTC().UnixNano())\n\t\t\t\tdata := randInt(65, 90)\n\t\t\t\tmetrics[i] = *plugin.NewPluginMetricType([]string{\"foo\", \"bar\"}, time.Now(), \"\", uint64(data))\n\t\t\t}\n\t\t\tvar buf bytes.Buffer\n\t\t\tenc := gob.NewEncoder(&buf)\n\t\t\tenc.Encode(metrics)\n\t\t\tmovingAverageObj := NewMovingaverageProcessor()\n\n\t\t\t_, received_data, _ := movingAverageObj.Process(\"pulse.gob\", buf.Bytes(), nil)\n\n\t\t\tvar metrics_new []plugin.PluginMetricType\n\n\t\t\t\/\/Decodes the content into pluginMetricType\n\t\t\tdec := gob.NewDecoder(bytes.NewBuffer(received_data))\n\t\t\tdec.Decode(&metrics_new)\n\t\t\tSo(metrics, ShouldNotResemble, metrics_new)\n\n\t\t})\n\n\t\tConvey(\"Moving average for unknown data type\", func() {\n\t\t\tfor i, _ := range metrics {\n\n\t\t\t\tdata := \"I am an unknow data Type\"\n\t\t\t\tmetrics[i] = *plugin.NewPluginMetricType([]string{\"foo\", \"bar\"}, time.Now(), \"\", data)\n\t\t\t}\n\t\t\tvar buf bytes.Buffer\n\t\t\tenc := gob.NewEncoder(&buf)\n\t\t\tenc.Encode(metrics)\n\n\t\t\tmovingAverageObj := NewMovingaverageProcessor()\n\n\t\t\t_, received_data, _ := movingAverageObj.Process(\"pulse.gob\", buf.Bytes(), nil)\n\n\t\t\tvar metrics_new []plugin.PluginMetricType\n\n\t\t\t\/\/Decodes the content into pluginMetricType\n\t\t\tdec := gob.NewDecoder(bytes.NewBuffer(received_data))\n\t\t\tdec.Decode(&metrics_new)\n\t\t\tSo(metrics, ShouldNotResemble, metrics_new)\n\n\t\t})\n\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package bootkube\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/coreos-inc\/pluton\"\n\t\"github.com\/coreos-inc\/pluton\/spawn\"\n\n\t\"github.com\/coreos\/mantle\/kola\/cluster\"\n\t\"github.com\/coreos\/mantle\/util\"\n)\n\nfunc bootkubeSmoke(c cluster.TestCluster) error {\n\t\/\/ This should not return until cluster is ready\n\tbc, err := spawn.MakeBootkubeCluster(c, 1, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ run an nginx deployment and ping it\n\tif err := nginxCheck(bc); err != nil {\n\t\treturn fmt.Errorf(\"nginxCheck: %s\", err)\n\t}\n\t\/\/ TODO add more basic or regression tests here\n\treturn nil\n}\n\nfunc bootkubeSmokeEtcd(c cluster.TestCluster) error {\n\t\/\/ This should not return until cluster is ready\n\tbc, err := spawn.MakeBootkubeCluster(c, 1, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ run an nginx deployment and ping it\n\tif err := nginxCheck(bc); err != nil {\n\t\treturn fmt.Errorf(\"nginxCheck: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc nginxCheck(c *pluton.Cluster) error {\n\t\/\/ start nginx deployment\n\t_, err := c.Kubectl(\"run my-nginx --image=nginx --replicas=2 --port=80\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ expose nginx\n\t_, err = c.Kubectl(\"expose deployment my-nginx --port=80 --type=LoadBalancer\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tserviceIP, err := c.Kubectl(\"get service my-nginx --template={{.spec.clusterIP}}\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ curl for welcome message\n\tnginxRunning := func() error {\n\t\tout, err := c.Masters[0].SSH(\"curl \" + serviceIP + \":80\")\n\t\tif err != nil || !bytes.Contains(out, []byte(\"Welcome to nginx!\")) {\n\t\t\treturn fmt.Errorf(\"unable to reach nginx: %s\", out)\n\t\t}\n\t\treturn nil\n\t}\n\tif err := util.Retry(15, 10*time.Second, nginxRunning); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ delete pod\n\t_, err = c.Kubectl(\"delete deployment my-nginx\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>tests\/bootkube: bump nginx test timeout<commit_after>package bootkube\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/coreos-inc\/pluton\"\n\t\"github.com\/coreos-inc\/pluton\/spawn\"\n\n\t\"github.com\/coreos\/mantle\/kola\/cluster\"\n\t\"github.com\/coreos\/mantle\/util\"\n)\n\nfunc bootkubeSmoke(c cluster.TestCluster) error {\n\t\/\/ This should not return until cluster is ready\n\tbc, err := spawn.MakeBootkubeCluster(c, 1, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ run an nginx deployment and ping it\n\tif err := nginxCheck(bc); err != nil {\n\t\treturn fmt.Errorf(\"nginxCheck: %s\", err)\n\t}\n\t\/\/ TODO add more basic or regression tests here\n\treturn nil\n}\n\nfunc bootkubeSmokeEtcd(c cluster.TestCluster) error {\n\t\/\/ This should not return until cluster is ready\n\tbc, err := spawn.MakeBootkubeCluster(c, 1, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ run an nginx deployment and ping it\n\tif err := nginxCheck(bc); err != nil {\n\t\treturn fmt.Errorf(\"nginxCheck: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc nginxCheck(c *pluton.Cluster) error {\n\t\/\/ start nginx deployment\n\t_, err := c.Kubectl(\"run my-nginx --image=nginx --replicas=2 --port=80\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ expose nginx\n\t_, err = c.Kubectl(\"expose deployment my-nginx --port=80 --type=LoadBalancer\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tserviceIP, err := c.Kubectl(\"get service my-nginx --template={{.spec.clusterIP}}\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ curl for welcome message\n\tnginxRunning := func() error {\n\t\tout, err := c.Masters[0].SSH(\"curl \" + serviceIP + \":80\")\n\t\tif err != nil || !bytes.Contains(out, []byte(\"Welcome to nginx!\")) {\n\t\t\treturn fmt.Errorf(\"unable to reach nginx: %s\", out)\n\t\t}\n\t\treturn nil\n\t}\n\tif err := util.Retry(20, 10*time.Second, nginxRunning); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ delete pod\n\t_, err = c.Kubectl(\"delete deployment my-nginx\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package travis\n\nimport \"testing\"\n\nfunc TestIs(t *testing.T) {\n\n}\n<commit_msg>Update test<commit_after>package travis\n\nimport \"testing\"\n\nfunc TestIs(t *testing.T) {\n\tif Is() == true {\n\t\tt.Fatal(\"Should return true\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package kubernetes\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"k8s.io\/client-go\/1.5\/kubernetes\"\n\t\"k8s.io\/client-go\/1.5\/pkg\/api\"\n\t\"k8s.io\/client-go\/1.5\/pkg\/api\/v1\"\n\t\"k8s.io\/client-go\/1.5\/pkg\/labels\"\n\t\"k8s.io\/client-go\/1.5\/pkg\/runtime\"\n\t\"k8s.io\/client-go\/1.5\/pkg\/watch\"\n\t\"k8s.io\/client-go\/1.5\/tools\/cache\"\n)\n\nvar (\n\tnamespace = api.NamespaceAll\n)\n\n\/\/ storeToNamespaceLister makes a Store that lists Namespaces.\ntype storeToNamespaceLister struct {\n\tcache.Store\n}\n\n\/\/ List lists all Namespaces in the store.\nfunc (s *storeToNamespaceLister) List() (ns api.NamespaceList, err error) {\n\tfor _, m := range s.Store.List() {\n\t\tns.Items = append(ns.Items, *(m.(*api.Namespace)))\n\t}\n\treturn ns, nil\n}\n\ntype dnsController struct {\n\tclient *kubernetes.Clientset\n\n\tselector *labels.Selector\n\n\tsvcController *cache.Controller\n\tnsController  *cache.Controller\n\n\tsvcLister cache.StoreToServiceLister\n\tnsLister  storeToNamespaceLister\n\n\t\/\/ stopLock is used to enforce only a single call to Stop is active.\n\t\/\/ Needed because we allow stopping through an http endpoint and\n\t\/\/ allowing concurrent stoppers leads to stack traces.\n\tstopLock sync.Mutex\n\tshutdown bool\n\tstopCh   chan struct{}\n}\n\n\/\/ newDNSController creates a controller for CoreDNS.\nfunc newdnsController(kubeClient *kubernetes.Clientset, resyncPeriod time.Duration, lselector *labels.Selector) *dnsController {\n\tdns := dnsController{\n\t\tclient:   kubeClient,\n\t\tselector: lselector,\n\t\tstopCh:   make(chan struct{}),\n\t}\n\n\tdns.svcLister.Indexer, dns.svcController = cache.NewIndexerInformer(\n\t\t&cache.ListWatch{\n\t\t\tListFunc:  serviceListFunc(dns.client, namespace, dns.selector),\n\t\t\tWatchFunc: serviceWatchFunc(dns.client, namespace, dns.selector),\n\t\t},\n\t\t&api.Service{},\n\t\tresyncPeriod,\n\t\tcache.ResourceEventHandlerFuncs{},\n\t\tcache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc})\n\n\tdns.nsLister.Store, dns.nsController = cache.NewInformer(\n\t\t&cache.ListWatch{\n\t\t\tListFunc:  namespaceListFunc(dns.client, dns.selector),\n\t\t\tWatchFunc: namespaceWatchFunc(dns.client, dns.selector),\n\t\t},\n\t\t&api.Namespace{}, resyncPeriod, cache.ResourceEventHandlerFuncs{})\n\n\treturn &dns\n}\n\nfunc serviceListFunc(c *kubernetes.Clientset, ns string, s *labels.Selector) func(api.ListOptions) (runtime.Object, error) {\n\treturn func(opts api.ListOptions) (runtime.Object, error) {\n\t\tif s != nil {\n\t\t\topts.LabelSelector = *s\n\t\t}\n\t\tlistV1, err := c.Core().Services(ns).List(opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar listAPI api.ServiceList\n\t\terr = v1.Convert_v1_ServiceList_To_api_ServiceList(listV1, &listAPI, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &list_api, err\n\t}\n}\n\nfunc serviceWatchFunc(c *kubernetes.Clientset, ns string, s *labels.Selector) func(options api.ListOptions) (watch.Interface, error) {\n\treturn func(options api.ListOptions) (watch.Interface, error) {\n\t\tif s != nil {\n\t\t\toptions.LabelSelector = *s\n\t\t}\n\t\treturn c.Core().Services(ns).Watch(options)\n\t}\n}\n\nfunc namespaceListFunc(c *kubernetes.Clientset, s *labels.Selector) func(api.ListOptions) (runtime.Object, error) {\n\treturn func(opts api.ListOptions) (runtime.Object, error) {\n\t\tif s != nil {\n\t\t\topts.LabelSelector = *s\n\t\t}\n\t\tlistV1, err := c.Core().Namespaces().List(opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar listAPI api.NamespaceList\n\t\terr = v1.Convert_v1_NamespaceList_To_api_NamespaceList(listV1, &listAPI, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &list_api, err\n\t}\n}\n\nfunc namespaceWatchFunc(c *kubernetes.Clientset, s *labels.Selector) func(options api.ListOptions) (watch.Interface, error) {\n\treturn func(options api.ListOptions) (watch.Interface, error) {\n\t\tif s != nil {\n\t\t\toptions.LabelSelector = *s\n\t\t}\n\t\treturn c.Core().Namespaces().Watch(options)\n\t}\n}\n\nfunc (dns *dnsController) controllersInSync() bool {\n\treturn dns.svcController.HasSynced()\n}\n\n\/\/ Stop stops the  controller.\nfunc (dns *dnsController) Stop() error {\n\tdns.stopLock.Lock()\n\tdefer dns.stopLock.Unlock()\n\n\t\/\/ Only try draining the workqueue if we haven't already.\n\tif !dns.shutdown {\n\t\tclose(dns.stopCh)\n\t\tdns.shutdown = true\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"shutdown already in progress\")\n}\n\n\/\/ Run starts the controller.\nfunc (dns *dnsController) Run() {\n\tgo dns.svcController.Run(dns.stopCh)\n\tgo dns.nsController.Run(dns.stopCh)\n\t<-dns.stopCh\n}\n\nfunc (dns *dnsController) NamespaceList() *api.NamespaceList {\n\tnsList, err := dns.nsLister.List()\n\tif err != nil {\n\t\treturn &api.NamespaceList{}\n\t}\n\n\treturn &nsList\n}\n\nfunc (dns *dnsController) ServiceList() []*api.Service {\n\tsvcs, err := dns.svcLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn []*api.Service{}\n\t}\n\n\treturn svcs\n}\n\n\/\/ ServicesByNamespace returns a map of:\n\/\/\n\/\/ namespacename :: [ kubernetesService ]\nfunc (dns *dnsController) ServicesByNamespace() map[string][]api.Service {\n\tk8sServiceList := dns.ServiceList()\n\titems := make(map[string][]api.Service, len(k8sServiceList))\n\tfor _, i := range k8sServiceList {\n\t\tnamespace := i.Namespace\n\t\titems[namespace] = append(items[namespace], *i)\n\t}\n\n\treturn items\n}\n\n\/\/ ServiceInNamespace returns the Service that matches servicename in the namespace\nfunc (dns *dnsController) ServiceInNamespace(namespace, servicename string) *api.Service {\n\tsvcObj, err := dns.svcLister.Services(namespace).Get(servicename)\n\tif err != nil {\n\t\t\/\/ TODO(...): should return err here\n\t\treturn nil\n\t}\n\treturn svcObj\n}\n<commit_msg>Fix compilation error<commit_after>package kubernetes\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"k8s.io\/client-go\/1.5\/kubernetes\"\n\t\"k8s.io\/client-go\/1.5\/pkg\/api\"\n\t\"k8s.io\/client-go\/1.5\/pkg\/api\/v1\"\n\t\"k8s.io\/client-go\/1.5\/pkg\/labels\"\n\t\"k8s.io\/client-go\/1.5\/pkg\/runtime\"\n\t\"k8s.io\/client-go\/1.5\/pkg\/watch\"\n\t\"k8s.io\/client-go\/1.5\/tools\/cache\"\n)\n\nvar (\n\tnamespace = api.NamespaceAll\n)\n\n\/\/ storeToNamespaceLister makes a Store that lists Namespaces.\ntype storeToNamespaceLister struct {\n\tcache.Store\n}\n\n\/\/ List lists all Namespaces in the store.\nfunc (s *storeToNamespaceLister) List() (ns api.NamespaceList, err error) {\n\tfor _, m := range s.Store.List() {\n\t\tns.Items = append(ns.Items, *(m.(*api.Namespace)))\n\t}\n\treturn ns, nil\n}\n\ntype dnsController struct {\n\tclient *kubernetes.Clientset\n\n\tselector *labels.Selector\n\n\tsvcController *cache.Controller\n\tnsController  *cache.Controller\n\n\tsvcLister cache.StoreToServiceLister\n\tnsLister  storeToNamespaceLister\n\n\t\/\/ stopLock is used to enforce only a single call to Stop is active.\n\t\/\/ Needed because we allow stopping through an http endpoint and\n\t\/\/ allowing concurrent stoppers leads to stack traces.\n\tstopLock sync.Mutex\n\tshutdown bool\n\tstopCh   chan struct{}\n}\n\n\/\/ newDNSController creates a controller for CoreDNS.\nfunc newdnsController(kubeClient *kubernetes.Clientset, resyncPeriod time.Duration, lselector *labels.Selector) *dnsController {\n\tdns := dnsController{\n\t\tclient:   kubeClient,\n\t\tselector: lselector,\n\t\tstopCh:   make(chan struct{}),\n\t}\n\n\tdns.svcLister.Indexer, dns.svcController = cache.NewIndexerInformer(\n\t\t&cache.ListWatch{\n\t\t\tListFunc:  serviceListFunc(dns.client, namespace, dns.selector),\n\t\t\tWatchFunc: serviceWatchFunc(dns.client, namespace, dns.selector),\n\t\t},\n\t\t&api.Service{},\n\t\tresyncPeriod,\n\t\tcache.ResourceEventHandlerFuncs{},\n\t\tcache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc})\n\n\tdns.nsLister.Store, dns.nsController = cache.NewInformer(\n\t\t&cache.ListWatch{\n\t\t\tListFunc:  namespaceListFunc(dns.client, dns.selector),\n\t\t\tWatchFunc: namespaceWatchFunc(dns.client, dns.selector),\n\t\t},\n\t\t&api.Namespace{}, resyncPeriod, cache.ResourceEventHandlerFuncs{})\n\n\treturn &dns\n}\n\nfunc serviceListFunc(c *kubernetes.Clientset, ns string, s *labels.Selector) func(api.ListOptions) (runtime.Object, error) {\n\treturn func(opts api.ListOptions) (runtime.Object, error) {\n\t\tif s != nil {\n\t\t\topts.LabelSelector = *s\n\t\t}\n\t\tlistV1, err := c.Core().Services(ns).List(opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar listAPI api.ServiceList\n\t\terr = v1.Convert_v1_ServiceList_To_api_ServiceList(listV1, &listAPI, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &listAPI, err\n\t}\n}\n\nfunc serviceWatchFunc(c *kubernetes.Clientset, ns string, s *labels.Selector) func(options api.ListOptions) (watch.Interface, error) {\n\treturn func(options api.ListOptions) (watch.Interface, error) {\n\t\tif s != nil {\n\t\t\toptions.LabelSelector = *s\n\t\t}\n\t\treturn c.Core().Services(ns).Watch(options)\n\t}\n}\n\nfunc namespaceListFunc(c *kubernetes.Clientset, s *labels.Selector) func(api.ListOptions) (runtime.Object, error) {\n\treturn func(opts api.ListOptions) (runtime.Object, error) {\n\t\tif s != nil {\n\t\t\topts.LabelSelector = *s\n\t\t}\n\t\tlistV1, err := c.Core().Namespaces().List(opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar listAPI api.NamespaceList\n\t\terr = v1.Convert_v1_NamespaceList_To_api_NamespaceList(listV1, &listAPI, nil)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &listAPI, err\n\t}\n}\n\nfunc namespaceWatchFunc(c *kubernetes.Clientset, s *labels.Selector) func(options api.ListOptions) (watch.Interface, error) {\n\treturn func(options api.ListOptions) (watch.Interface, error) {\n\t\tif s != nil {\n\t\t\toptions.LabelSelector = *s\n\t\t}\n\t\treturn c.Core().Namespaces().Watch(options)\n\t}\n}\n\nfunc (dns *dnsController) controllersInSync() bool {\n\treturn dns.svcController.HasSynced()\n}\n\n\/\/ Stop stops the  controller.\nfunc (dns *dnsController) Stop() error {\n\tdns.stopLock.Lock()\n\tdefer dns.stopLock.Unlock()\n\n\t\/\/ Only try draining the workqueue if we haven't already.\n\tif !dns.shutdown {\n\t\tclose(dns.stopCh)\n\t\tdns.shutdown = true\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"shutdown already in progress\")\n}\n\n\/\/ Run starts the controller.\nfunc (dns *dnsController) Run() {\n\tgo dns.svcController.Run(dns.stopCh)\n\tgo dns.nsController.Run(dns.stopCh)\n\t<-dns.stopCh\n}\n\nfunc (dns *dnsController) NamespaceList() *api.NamespaceList {\n\tnsList, err := dns.nsLister.List()\n\tif err != nil {\n\t\treturn &api.NamespaceList{}\n\t}\n\n\treturn &nsList\n}\n\nfunc (dns *dnsController) ServiceList() []*api.Service {\n\tsvcs, err := dns.svcLister.List(labels.Everything())\n\tif err != nil {\n\t\treturn []*api.Service{}\n\t}\n\n\treturn svcs\n}\n\n\/\/ ServicesByNamespace returns a map of:\n\/\/\n\/\/ namespacename :: [ kubernetesService ]\nfunc (dns *dnsController) ServicesByNamespace() map[string][]api.Service {\n\tk8sServiceList := dns.ServiceList()\n\titems := make(map[string][]api.Service, len(k8sServiceList))\n\tfor _, i := range k8sServiceList {\n\t\tnamespace := i.Namespace\n\t\titems[namespace] = append(items[namespace], *i)\n\t}\n\n\treturn items\n}\n\n\/\/ ServiceInNamespace returns the Service that matches servicename in the namespace\nfunc (dns *dnsController) ServiceInNamespace(namespace, servicename string) *api.Service {\n\tsvcObj, err := dns.svcLister.Services(namespace).Get(servicename)\n\tif err != nil {\n\t\t\/\/ TODO(...): should return err here\n\t\treturn nil\n\t}\n\treturn svcObj\n}\n<|endoftext|>"}
{"text":"<commit_before>package server\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"text\/template\"\n\n\t\"github.com\/urfave\/cli\"\n\n\t\"github.com\/drone\/drone-cli\/drone\/internal\"\n)\n\nvar serverInfoCmd = cli.Command{\n\tName:      \"info\",\n\tUsage:     \"show server details\",\n\tArgsUsage: \"<servername>\",\n\tAction:    serverInfo,\n\tFlags: []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:   \"format\",\n\t\t\tUsage:  \"format output\",\n\t\t\tValue:  tmplServerInfo,\n\t\t\tHidden: true,\n\t\t},\n\t},\n}\n\nfunc serverInfo(c *cli.Context) error {\n\tclient, err := internal.NewAutoscaleClient(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tname := c.Args().First()\n\tif len(name) == 0 {\n\t\treturn fmt.Errorf(\"Missing or invalid server name\")\n\t}\n\n\tserver, err := client.Server(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmpl, err := template.New(\"_\").Parse(c.String(\"format\") + \"\\n\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn tmpl.Execute(os.Stdout, server)\n}\n\n\/\/ template for server information\nvar tmplServerInfo = `Name: {{ .Name }}\nAddress: {{ .Address }}\nRegion: {{ .Region }}\nSize: {{.Size}}\nState: {{ .State }}\n`\n<commit_msg>show error message in server info<commit_after>package server\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"text\/template\"\n\n\t\"github.com\/urfave\/cli\"\n\n\t\"github.com\/drone\/drone-cli\/drone\/internal\"\n)\n\nvar serverInfoCmd = cli.Command{\n\tName:      \"info\",\n\tUsage:     \"show server details\",\n\tArgsUsage: \"<servername>\",\n\tAction:    serverInfo,\n\tFlags: []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:   \"format\",\n\t\t\tUsage:  \"format output\",\n\t\t\tValue:  tmplServerInfo,\n\t\t\tHidden: true,\n\t\t},\n\t},\n}\n\nfunc serverInfo(c *cli.Context) error {\n\tclient, err := internal.NewAutoscaleClient(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tname := c.Args().First()\n\tif len(name) == 0 {\n\t\treturn fmt.Errorf(\"Missing or invalid server name\")\n\t}\n\n\tserver, err := client.Server(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmpl, err := template.New(\"_\").Parse(c.String(\"format\") + \"\\n\")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn tmpl.Execute(os.Stdout, server)\n}\n\n\/\/ template for server information\nvar tmplServerInfo = `Name: {{ .Name }}\nAddress: {{ .Address }}\nRegion:  {{ .Region }}\nSize:    {{.Size}}\nState:   {{ .State }}\n{{ if .Error -}}\nError:   {{ .Error }}\n{{ end -}}\n`\n<|endoftext|>"}
{"text":"<commit_before>package gen4java\n\nvar t4java = `\n{{define \"enum\"}}{{$Enum := title .Name}}\n\/*\n * {{title .Name}} generate by gs2java,don't modify it manually\n *\/\npublic enum {{title .Name}} {\n    {{enumFields .}}\n    private {{enumType .}} value;\n    {{title .Name}}({{enumType .}} val){\n        this.value = val;\n    }\n    @Override\n    public String toString() {\n        switch(this.value)\n        {\n        {{range .Constants}}\n        case {{.Value}}:\n            return \"{{title .Name}}\";\n        {{end}}\n        }\n        return \"{{title .Name}}#\" + this.value;\n    }\n    public {{enumType .}} getValue() {\n        return this.value;\n    }\n    public void marshal(Writer writer) throws Exception\n    {\n        {{if enumSize . | eq 4}} writer.writeUInt32(getValue()); {{else}} writer.writeByte(getValue()); {{end}}\n    }\n    public static {{title .Name}} unmarshal(Reader reader) throws Exception\n    {\n        {{enumType .}} code =  {{if enumSize . | eq 4}} reader.readUInt32(); {{else}} reader.readByte(); {{end}}\n        switch(code)\n        {\n        {{range .Constants}}\n        case {{.Value}}:\n            return {{$Enum}}.{{title .Name}};\n        {{end}}\n        }\n        throw new Exception(\"unknown enum constant :\" + code);\n    }\n}\n{{end}}\n\n{{define \"table\"}}{{$Struct := tableName .}}\npublic class {{$Struct}} {{if isException .}}extends Exception{{end}}\n{\n{{range .Fields}}\n    private  {{typeName .Type}} {{fieldName .Name}} = {{defaultVal .Type}};\n{{end}}\n\n{{if .Fields}}\n    public {{$Struct}}(){\n\n    }\n{{end}}\n\n    public {{$Struct}}{{constructor .Fields}} {\n    {{range .Fields}}\n        this.{{fieldName .Name}} = {{fieldName .Name}};\n    {{end}}\n    }\n\n{{range .Fields}}\n    public {{typeName .Type}} get{{title .Name}}()\n    {\n        return this.{{fieldName .Name}};\n    }\n    public void set{{title .Name}}({{typeName .Type}} arg)\n    {\n        this.{{fieldName .Name}} = arg;\n    }\n{{end}}\n\n{{if isPOD . | not}}\n    public void marshal(Writer writer)  throws Exception\n    {\n        writer.writeByte((byte){{len .Fields}});\n{{range .Fields}}\n        writer.writeByte((byte){{tagValue .Type}});\n        {{marshalField .}}\n{{end}}\n    }\n    public void unmarshal(Reader reader) throws Exception\n    {\n        byte __fields = reader.readByte();\n{{range .Fields}}\n        {\n            byte tag = reader.readByte();\n\n            if(tag != com.gsrpc.Tag.Skip.getValue()) {\n                {{unmarshalField .}}\n            }\n\n            if(-- __fields == 0) {\n                return;\n            }\n        }\n\n{{end}}\n\n        for(int i = 0; i < (int)__fields; i ++) {\n            byte tag = reader.readByte();\n\n            if (tag == com.gsrpc.Tag.Skip.getValue()) {\n                continue;\n            }\n\n            reader.readSkip(tag);\n        }\n    }\n{{else}}\n    public void marshal(Writer writer)  throws Exception\n    {\n{{range .Fields}}\n        {{marshalField .}}\n{{end}}\n    }\n\n    public void unmarshal(Reader reader) throws Exception\n    {\n{{range .Fields}}\n        {\n            {{unmarshalField .}}\n        }\n{{end}}\n    }\n\n{{end}}\n}\n{{end}}\n\n\n{{define \"contract\"}}{{$Contract := title .Name}}\n\npublic interface {{$Contract}} {\n    String NAME = \"{{.FullName}}\";\n{{range .Methods}}\n    {{returnParam .Return}} {{methodName .Name}} {{params .Params}} throws Exception;\n{{end}}\n}\n\n{{end}}\n\n\n{{define \"dispatcher\"}}\n{{$Contract := title .Name}}\n\/*\n * {{title .Name}} generate by gs2java,don't modify it manually\n *\/\npublic final class {{$Contract}}Dispatcher implements com.gsrpc.NamedDispatcher {\n\n    private {{$Contract}} service;\n\n    public {{$Contract}}Dispatcher({{$Contract}} service) {\n        this.service = service;\n    }\n\n    public String name() {\n        return \"{{.FullName}}\";\n    }\n\n    public com.gsrpc.Response dispatch(com.gsrpc.Request call) throws Exception\n    {\n        switch(call.getMethod()){\n        {{range .Methods}}\n        case {{.ID}}: {\n{{range .Params}}{{unmarshalParam . \"call\" 4}}{{end}}\n                {{if isAsync . | not}}\n                {{if .Exceptions}}\n                try{\n                {{end}}\n                    {{methodcall .}}\n\n                    com.gsrpc.Response callReturn = new com.gsrpc.Response();\n                    callReturn.setID(call.getID());\n                    callReturn.setException((byte)-1);\n\n                    {{if notVoid .Return}}\n    {{marshalReturn .Return \"ret\" 4}}\n                    callReturn.setContent(returnParam);\n                    {{end}}\n\n                    return callReturn;\n\n                {{if .Exceptions}}}{{end}}{{range .Exceptions}} catch({{typeName .Type}} e) {\n\n                    com.gsrpc.BufferWriter writer = new com.gsrpc.BufferWriter();\n\n                    e.marshal(writer);\n\n                    com.gsrpc.Response callReturn = new com.gsrpc.Response();\n                    callReturn.setID(call.getID());\n                    callReturn.setException((byte){{.ID}});\n                    callReturn.setContent(writer.getContent());\n\n                    return callReturn;\n                }{{end}}\n                {{else}}\n                {{methodcall .}}\n                {{end}}\n            }\n        {{end}}\n        }\n        return null;\n    }\n}\n{{end}}\n\n\n{{define \"rpc\"}}{{$Contract := title .Name}}\n\/*\n * {{title .Name}} generate by gs2java,don't modify it manually\n *\/\npublic final class {{$Contract}}RPC {\n\n    \/**\n     * gsrpc net interface\n     *\/\n    private com.gsrpc.Channel net;\n\n    \/**\n     * remote service id\n     *\/\n    private short serviceID;\n\n    public {{$Contract}}RPC(com.gsrpc.Channel net, short serviceID){\n        this.net = net;\n        this.serviceID = serviceID;\n    }\n\n    {{range .Methods}}{{$Name := title .Name}}\n    public {{methodRPC .}} throws Exception {\n\n        com.gsrpc.Request request = new com.gsrpc.Request();\n\n        request.setService(this.serviceID);\n\n        request.setMethod((short){{.ID}});\n\n        {{if .Params}}\n        com.gsrpc.Param[] params = new com.gsrpc.Param[{{len .Params}}];\n{{marshalParams .Params}}\n        request.setParams(params);\n        {{end}}\n\n        {{if isAsync . | not}}\n        com.gsrpc.Promise<{{objTypeName .Return}}> promise = new com.gsrpc.Promise<{{objTypeName .Return}}>(timeout){\n            @Override\n            public void Return(Exception e,com.gsrpc.Response callReturn){\n\n                if (e != null) {\n                    Notify(e,null);\n                    return;\n                }\n\n                try{\n\n                    if(callReturn.getException() != (byte)-1) {\n                        switch(callReturn.getException()) {\n                            {{range .Exceptions}}\n                            case {{.ID}}:{\n                            com.gsrpc.BufferReader reader = new com.gsrpc.BufferReader(callReturn.getContent());\n\n                            {{typeName .Type}} exception = {{defaultVal .Type}};\n\n                            {{readType \"exception\" .Type 4}}\n\n                            Notify(exception,null);\n\n                            return;\n                        }\n                        {{end}}\n                        default:\n                            Notify(new com.gsrpc.RemoteException(),null);\n                            return;\n                        }\n                    }\n\n                    {{if notVoid .Return}}\n{{unmarshalReturn .Return \"callReturn\" 5}}\n                    Notify(null,returnParam);\n                    {{else}}\n                    Notify(null,null);\n                    {{end}}\n                }catch(Exception e1) {\n                    Notify(e1,null);\n                }\n            }\n        };\n\n        this.net.send(request,promise);\n\n        return promise;\n        {{else}}\n        this.net.post(request);\n        {{end}}\n    }\n    {{end}}\n}\n{{end}}\n`\n<commit_msg>update jvm generator<commit_after>package gen4java\n\nvar t4java = `\n{{define \"enum\"}}{{$Enum := title .Name}}\n\/*\n * {{title .Name}} generate by gs2java,don't modify it manually\n *\/\npublic enum {{title .Name}} {\n    {{enumFields .}}\n    private {{enumType .}} value;\n    {{title .Name}}({{enumType .}} val){\n        this.value = val;\n    }\n    @Override\n    public String toString() {\n        switch(this.value)\n        {\n        {{range .Constants}}\n        case {{.Value}}:\n            return \"{{title .Name}}\";\n        {{end}}\n        }\n        return \"{{title .Name}}#\" + this.value;\n    }\n    public {{enumType .}} getValue() {\n        return this.value;\n    }\n    public void marshal(Writer writer) throws Exception\n    {\n        {{if enumSize . | eq 4}} writer.writeUInt32(getValue()); {{else}} writer.writeByte(getValue()); {{end}}\n    }\n    public static {{title .Name}} unmarshal(Reader reader) throws Exception\n    {\n        {{enumType .}} code =  {{if enumSize . | eq 4}} reader.readUInt32(); {{else}} reader.readByte(); {{end}}\n        switch(code)\n        {\n        {{range .Constants}}\n        case {{.Value}}:\n            return {{$Enum}}.{{title .Name}};\n        {{end}}\n        }\n        throw new Exception(\"unknown enum constant :\" + code);\n    }\n}\n{{end}}\n\n{{define \"table\"}}{{$Struct := tableName .}}\npublic class {{$Struct}} {{if isException .}}extends Exception{{end}}\n{\n{{range .Fields}}\n    private  {{typeName .Type}} {{fieldName .Name}} = {{defaultVal .Type}};\n{{end}}\n\n{{if .Fields}}\n    public {{$Struct}}(){\n\n    }\n{{end}}\n\n    public {{$Struct}}{{constructor .Fields}} {\n    {{range .Fields}}\n        this.{{fieldName .Name}} = {{fieldName .Name}};\n    {{end}}\n    }\n\n{{range .Fields}}\n    public {{typeName .Type}} get{{title .Name}}()\n    {\n        return this.{{fieldName .Name}};\n    }\n    public void set{{title .Name}}({{typeName .Type}} arg)\n    {\n        this.{{fieldName .Name}} = arg;\n    }\n{{end}}\n\n{{if isPOD . | not}}\n    public void marshal(Writer writer)  throws Exception\n    {\n        writer.writeByte((byte){{len .Fields}});\n{{range .Fields}}\n        writer.writeByte((byte){{tagValue .Type}});\n        {{marshalField .}}\n{{end}}\n    }\n    public void unmarshal(Reader reader) throws Exception\n    {\n        byte __fields = reader.readByte();\n{{range .Fields}}\n        {\n            byte tag = reader.readByte();\n\n            if(tag != com.gsrpc.Tag.Skip.getValue()) {\n                {{unmarshalField .}}\n            }\n\n            if(-- __fields == 0) {\n                return;\n            }\n        }\n\n{{end}}\n\n        for(int i = 0; i < (int)__fields; i ++) {\n            byte tag = reader.readByte();\n\n            if (tag == com.gsrpc.Tag.Skip.getValue()) {\n                continue;\n            }\n\n            reader.readSkip(tag);\n        }\n    }\n{{else}}\n    public void marshal(Writer writer)  throws Exception\n    {\n{{range .Fields}}\n        {{marshalField .}}\n{{end}}\n    }\n\n    public void unmarshal(Reader reader) throws Exception\n    {\n{{range .Fields}}\n        {\n            {{unmarshalField .}}\n        }\n{{end}}\n    }\n\n{{end}}\n}\n{{end}}\n\n\n{{define \"contract\"}}{{$Contract := title .Name}}\n\npublic interface {{$Contract}} {\n    String NAME = \"{{.FullName}}\";\n{{range .Methods}}\n    {{returnParam .Return}} {{methodName .Name}} {{params .Params}} throws Exception;\n{{end}}\n}\n\n{{end}}\n\n\n{{define \"dispatcher\"}}\n{{$Contract := title .Name}}\n\/*\n * {{title .Name}} generate by gs2java,don't modify it manually\n *\/\npublic final class {{$Contract}}Dispatcher implements com.gsrpc.NamedDispatcher {\n\n    private {{$Contract}} service;\n\n    public {{$Contract}}Dispatcher({{$Contract}} service) {\n        this.service = service;\n    }\n\n    public String name() {\n        return \"{{.FullName}}\";\n    }\n\n    public com.gsrpc.Response dispatch(com.gsrpc.Request call) throws Exception\n    {\n        switch(call.getMethod()){\n        {{range .Methods}}\n        case {{.ID}}: {\n{{range .Params}}{{unmarshalParam . \"call\" 4}}{{end}}\n                {{if isAsync . | not}}\n                {{if .Exceptions}}\n                try{\n                {{end}}\n                    {{methodcall .}}\n\n                    com.gsrpc.Response callReturn = new com.gsrpc.Response();\n                    callReturn.setID(call.getID());\n                    callReturn.setException((byte)-1);\n\n                    {{if notVoid .Return}}\n    {{marshalReturn .Return \"ret\" 4}}\n                    callReturn.setContent(returnParam);\n                    {{end}}\n\n                    return callReturn;\n\n                {{if .Exceptions}}}{{end}}{{range .Exceptions}} catch({{typeName .Type}} e) {\n\n                    com.gsrpc.BufferWriter writer = new com.gsrpc.BufferWriter();\n\n                    e.marshal(writer);\n\n                    com.gsrpc.Response callReturn = new com.gsrpc.Response();\n                    callReturn.setID(call.getID());\n                    callReturn.setException((byte){{.ID}});\n                    callReturn.setContent(writer.getContent());\n\n                    return callReturn;\n                }{{end}}\n                {{else}}\n                {{methodcall .}}\n                {{end}}\n            }\n        {{end}}\n        }\n        return null;\n    }\n}\n{{end}}\n\n\n{{define \"rpc\"}}{{$Contract := title .Name}}\n\/*\n * {{title .Name}} generate by gs2java,don't modify it manually\n *\/\npublic final class {{$Contract}}RPC {\n\n    \/**\n     * gsrpc net interface\n     *\/\n    private com.gsrpc.Channel net;\n\n    \/**\n     * remote service id\n     *\/\n    private short serviceID;\n\n    public {{$Contract}}RPC(com.gsrpc.Channel net, short serviceID){\n        this.net = net;\n        this.serviceID = serviceID;\n    }\n\n    public {{$Contract}}RPC(com.gsrpc.Channel net) throws Exception {\n        this.net = net;\n        this.serviceID = com.gsrpc.Register.getInstance().getID({{$Contract}}.NAME);\n    }\n\n    {{range .Methods}}{{$Name := title .Name}}\n    public {{methodRPC .}} throws Exception {\n\n        com.gsrpc.Request request = new com.gsrpc.Request();\n\n        request.setService(this.serviceID);\n\n        request.setMethod((short){{.ID}});\n\n        {{if .Params}}\n        com.gsrpc.Param[] params = new com.gsrpc.Param[{{len .Params}}];\n{{marshalParams .Params}}\n        request.setParams(params);\n        {{end}}\n\n        {{if isAsync . | not}}\n        com.gsrpc.Promise<{{objTypeName .Return}}> promise = new com.gsrpc.Promise<{{objTypeName .Return}}>(timeout){\n            @Override\n            public void Return(Exception e,com.gsrpc.Response callReturn){\n\n                if (e != null) {\n                    Notify(e,null);\n                    return;\n                }\n\n                try{\n\n                    if(callReturn.getException() != (byte)-1) {\n                        switch(callReturn.getException()) {\n                            {{range .Exceptions}}\n                            case {{.ID}}:{\n                            com.gsrpc.BufferReader reader = new com.gsrpc.BufferReader(callReturn.getContent());\n\n                            {{typeName .Type}} exception = {{defaultVal .Type}};\n\n                            {{readType \"exception\" .Type 4}}\n\n                            Notify(exception,null);\n\n                            return;\n                        }\n                        {{end}}\n                        default:\n                            Notify(new com.gsrpc.RemoteException(),null);\n                            return;\n                        }\n                    }\n\n                    {{if notVoid .Return}}\n{{unmarshalReturn .Return \"callReturn\" 5}}\n                    Notify(null,returnParam);\n                    {{else}}\n                    Notify(null,null);\n                    {{end}}\n                }catch(Exception e1) {\n                    Notify(e1,null);\n                }\n            }\n        };\n\n        this.net.send(request,promise);\n\n        return promise;\n        {{else}}\n        this.net.post(request);\n        {{end}}\n    }\n    {{end}}\n}\n{{end}}\n`\n<|endoftext|>"}
{"text":"<commit_before>package integration\n\nimport (\n\t\"bufio\"\n\t\"html\/template\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\thomedir \"github.com\/mitchellh\/go-homedir\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nfunc leaveIt() bool {\n\treturn os.Getenv(\"LEAVE_ARTIFACTS\") != \"\"\n}\n\nfunc GetSSHKeyFile() (string, error) {\n\tdir, err := homedir.Dir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(dir, \".ssh\", \"kismatic-integration-testing.pem\"), nil\n}\n\ntype installOptions struct {\n\tallowPackageInstallation    bool\n\tdisconnectedInstallation    bool\n\tautoConfigureDockerRegistry bool\n\tdockerRegistryIP            string\n\tdockerRegistryPort          int\n\tdockerRegistryCAPath        string\n\tmodifyHostsFiles            bool\n}\n\nfunc installKismaticMini(node NodeDeets, sshKey string) error {\n\tsshUser := node.SSHUser\n\tplan := PlanAWS{\n\t\tEtcd:                     []NodeDeets{node},\n\t\tMaster:                   []NodeDeets{node},\n\t\tWorker:                   []NodeDeets{node},\n\t\tIngress:                  []NodeDeets{node},\n\t\tStorage:                  []NodeDeets{node},\n\t\tMasterNodeFQDN:           node.Hostname,\n\t\tMasterNodeShortName:      node.Hostname,\n\t\tSSHKeyFile:               sshKey,\n\t\tSSHUser:                  sshUser,\n\t\tAllowPackageInstallation: true,\n\t}\n\treturn installKismaticWithPlan(plan, sshKey)\n}\n\nfunc installKismatic(nodes provisionedNodes, installOpts installOptions, sshKey string) error {\n\tsshUser := nodes.master[0].SSHUser\n\tmasterDNS := nodes.master[0].Hostname\n\tif nodes.dnsRecord != nil && nodes.dnsRecord.Name != \"\" {\n\t\tmasterDNS = nodes.dnsRecord.Name\n\t}\n\tplan := PlanAWS{\n\t\tAllowPackageInstallation: installOpts.allowPackageInstallation,\n\t\tDisconnectedInstallation: installOpts.disconnectedInstallation,\n\t\tEtcd:                nodes.etcd,\n\t\tMaster:              nodes.master,\n\t\tWorker:              nodes.worker,\n\t\tIngress:             nodes.ingress,\n\t\tStorage:             nodes.storage,\n\t\tMasterNodeFQDN:      masterDNS,\n\t\tMasterNodeShortName: masterDNS,\n\t\tSSHKeyFile:          sshKey,\n\t\tSSHUser:             sshUser,\n\t\tAutoConfiguredDockerRegistry: installOpts.autoConfigureDockerRegistry,\n\t\tDockerRegistryCAPath:         installOpts.dockerRegistryCAPath,\n\t\tDockerRegistryIP:             installOpts.dockerRegistryIP,\n\t\tDockerRegistryPort:           installOpts.dockerRegistryPort,\n\t\tModifyHostsFiles:             installOpts.modifyHostsFiles,\n\t}\n\treturn installKismaticWithPlan(plan, sshKey)\n}\n\nfunc installKismaticWithPlan(plan PlanAWS, sshKey string) error {\n\tBy(\"Building a template\")\n\ttemplate, err := template.New(\"planAWSOverlay\").Parse(planAWSOverlay)\n\tFailIfError(err, \"Couldn't parse template\")\n\n\tf, err := os.Create(\"kismatic-testing.yaml\")\n\tFailIfError(err, \"Error creating plan\")\n\tdefer f.Close()\n\tw := bufio.NewWriter(f)\n\terr = template.Execute(w, &plan)\n\tFailIfError(err, \"Error filling in plan template\")\n\tw.Flush()\n\n\tBy(\"Punch it Chewie!\")\n\tcmd := exec.Command(\".\/kismatic\", \"install\", \"apply\", \"-f\", f.Name())\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\treturn cmd.Run()\n}\n\nfunc installKismaticWithABadNode() {\n\tBy(\"Building a template\")\n\ttemplate, err := template.New(\"planAWSOverlay\").Parse(planAWSOverlay)\n\tFailIfError(err, \"Couldn't parse template\")\n\n\tBy(\"Faking infrastructure\")\n\tfakeNode := NodeDeets{\n\t\tid:       \"FakeId\",\n\t\tPublicIP: \"10.0.0.0\",\n\t\tHostname: \"FakeHostname\",\n\t}\n\n\tBy(\"Building a plan to set up an overlay network cluster on this hardware\")\n\tsshKey, err := GetSSHKeyFile()\n\tFailIfError(err, \"Error getting SSH Key file\")\n\tplan := PlanAWS{\n\t\tEtcd:                []NodeDeets{fakeNode},\n\t\tMaster:              []NodeDeets{fakeNode},\n\t\tWorker:              []NodeDeets{fakeNode},\n\t\tIngress:             []NodeDeets{fakeNode},\n\t\tMasterNodeFQDN:      \"yep.nope\",\n\t\tMasterNodeShortName: \"yep\",\n\t\tSSHUser:             \"Billy Rubin\",\n\t\tSSHKeyFile:          sshKey,\n\t}\n\tBy(\"Writing plan file out to disk\")\n\tf, err := os.Create(\"kismatic-testing.yaml\")\n\tFailIfError(err, \"Error waiting for nodes\")\n\tdefer f.Close()\n\tw := bufio.NewWriter(f)\n\terr = template.Execute(w, &plan)\n\tFailIfError(err, \"Error filling in plan template\")\n\tw.Flush()\n\tf.Close()\n\n\tBy(\"Validing our plan\")\n\tcmd := exec.Command(\".\/kismatic\", \"install\", \"validate\", \"-f\", f.Name())\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr = cmd.Run()\n\tif err == nil {\n\t\tFail(\"Validation succeeeded even though it shouldn't have\")\n\t}\n\n\tBy(\"Well, try it anyway\")\n\tcmd = exec.Command(\".\/kismatic\", \"install\", \"apply\", \"-f\", f.Name())\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr = cmd.Run()\n\tif err == nil {\n\t\tFail(\"Application succeeeded even though it shouldn't have\")\n\t}\n}\n\nfunc completesInTime(dothis func(), howLong time.Duration) bool {\n\tc1 := make(chan string, 1)\n\tgo func() {\n\t\tdothis()\n\t\tc1 <- \"completed\"\n\t}()\n\n\tselect {\n\tcase <-c1:\n\t\treturn true\n\tcase <-time.After(howLong):\n\t\treturn false\n\t}\n}\n\nfunc canAccessDashboard() error {\n\t\/\/ Access the dashboard a few times to hit all replicas\n\tfor i := 0; i < 3; i++ {\n\t\tcmd := exec.Command(\".\/kismatic\", \"dashboard\", \"--url\", \"-f\", \"kismatic-testing.yaml\")\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\tif err := cmd.Run(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc FailIfError(err error, message ...interface{}) {\n\tExpect(err).ToNot(HaveOccurred(), message...)\n}\n\nfunc FailIfSuccess(err error) {\n\tif err == nil {\n\t\tFail(\"Expected failure\")\n\t}\n}\n\nfunc FileExists(path string) bool {\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n<commit_msg>Use Pubilc IP for master FQDN during integration tests<commit_after>package integration\n\nimport (\n\t\"bufio\"\n\t\"html\/template\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\thomedir \"github.com\/mitchellh\/go-homedir\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nfunc leaveIt() bool {\n\treturn os.Getenv(\"LEAVE_ARTIFACTS\") != \"\"\n}\n\nfunc GetSSHKeyFile() (string, error) {\n\tdir, err := homedir.Dir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(dir, \".ssh\", \"kismatic-integration-testing.pem\"), nil\n}\n\ntype installOptions struct {\n\tallowPackageInstallation    bool\n\tdisconnectedInstallation    bool\n\tautoConfigureDockerRegistry bool\n\tdockerRegistryIP            string\n\tdockerRegistryPort          int\n\tdockerRegistryCAPath        string\n\tmodifyHostsFiles            bool\n}\n\nfunc installKismaticMini(node NodeDeets, sshKey string) error {\n\tsshUser := node.SSHUser\n\tplan := PlanAWS{\n\t\tEtcd:                     []NodeDeets{node},\n\t\tMaster:                   []NodeDeets{node},\n\t\tWorker:                   []NodeDeets{node},\n\t\tIngress:                  []NodeDeets{node},\n\t\tStorage:                  []NodeDeets{node},\n\t\tMasterNodeFQDN:           node.PublicIP,\n\t\tMasterNodeShortName:      node.PublicIP,\n\t\tSSHKeyFile:               sshKey,\n\t\tSSHUser:                  sshUser,\n\t\tAllowPackageInstallation: true,\n\t}\n\treturn installKismaticWithPlan(plan, sshKey)\n}\n\nfunc installKismatic(nodes provisionedNodes, installOpts installOptions, sshKey string) error {\n\tsshUser := nodes.master[0].SSHUser\n\tmasterDNS := nodes.master[0].PublicIP\n\tif nodes.dnsRecord != nil && nodes.dnsRecord.Name != \"\" {\n\t\tmasterDNS = nodes.dnsRecord.Name\n\t}\n\tplan := PlanAWS{\n\t\tAllowPackageInstallation: installOpts.allowPackageInstallation,\n\t\tDisconnectedInstallation: installOpts.disconnectedInstallation,\n\t\tEtcd:                nodes.etcd,\n\t\tMaster:              nodes.master,\n\t\tWorker:              nodes.worker,\n\t\tIngress:             nodes.ingress,\n\t\tStorage:             nodes.storage,\n\t\tMasterNodeFQDN:      masterDNS,\n\t\tMasterNodeShortName: masterDNS,\n\t\tSSHKeyFile:          sshKey,\n\t\tSSHUser:             sshUser,\n\t\tAutoConfiguredDockerRegistry: installOpts.autoConfigureDockerRegistry,\n\t\tDockerRegistryCAPath:         installOpts.dockerRegistryCAPath,\n\t\tDockerRegistryIP:             installOpts.dockerRegistryIP,\n\t\tDockerRegistryPort:           installOpts.dockerRegistryPort,\n\t\tModifyHostsFiles:             installOpts.modifyHostsFiles,\n\t}\n\treturn installKismaticWithPlan(plan, sshKey)\n}\n\nfunc installKismaticWithPlan(plan PlanAWS, sshKey string) error {\n\tBy(\"Building a template\")\n\ttemplate, err := template.New(\"planAWSOverlay\").Parse(planAWSOverlay)\n\tFailIfError(err, \"Couldn't parse template\")\n\n\tf, err := os.Create(\"kismatic-testing.yaml\")\n\tFailIfError(err, \"Error creating plan\")\n\tdefer f.Close()\n\tw := bufio.NewWriter(f)\n\terr = template.Execute(w, &plan)\n\tFailIfError(err, \"Error filling in plan template\")\n\tw.Flush()\n\n\tBy(\"Punch it Chewie!\")\n\tcmd := exec.Command(\".\/kismatic\", \"install\", \"apply\", \"-f\", f.Name())\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\treturn cmd.Run()\n}\n\nfunc installKismaticWithABadNode() {\n\tBy(\"Building a template\")\n\ttemplate, err := template.New(\"planAWSOverlay\").Parse(planAWSOverlay)\n\tFailIfError(err, \"Couldn't parse template\")\n\n\tBy(\"Faking infrastructure\")\n\tfakeNode := NodeDeets{\n\t\tid:       \"FakeId\",\n\t\tPublicIP: \"10.0.0.0\",\n\t\tHostname: \"FakeHostname\",\n\t}\n\n\tBy(\"Building a plan to set up an overlay network cluster on this hardware\")\n\tsshKey, err := GetSSHKeyFile()\n\tFailIfError(err, \"Error getting SSH Key file\")\n\tplan := PlanAWS{\n\t\tEtcd:                []NodeDeets{fakeNode},\n\t\tMaster:              []NodeDeets{fakeNode},\n\t\tWorker:              []NodeDeets{fakeNode},\n\t\tIngress:             []NodeDeets{fakeNode},\n\t\tMasterNodeFQDN:      \"yep.nope\",\n\t\tMasterNodeShortName: \"yep\",\n\t\tSSHUser:             \"Billy Rubin\",\n\t\tSSHKeyFile:          sshKey,\n\t}\n\tBy(\"Writing plan file out to disk\")\n\tf, err := os.Create(\"kismatic-testing.yaml\")\n\tFailIfError(err, \"Error waiting for nodes\")\n\tdefer f.Close()\n\tw := bufio.NewWriter(f)\n\terr = template.Execute(w, &plan)\n\tFailIfError(err, \"Error filling in plan template\")\n\tw.Flush()\n\tf.Close()\n\n\tBy(\"Validing our plan\")\n\tcmd := exec.Command(\".\/kismatic\", \"install\", \"validate\", \"-f\", f.Name())\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr = cmd.Run()\n\tif err == nil {\n\t\tFail(\"Validation succeeeded even though it shouldn't have\")\n\t}\n\n\tBy(\"Well, try it anyway\")\n\tcmd = exec.Command(\".\/kismatic\", \"install\", \"apply\", \"-f\", f.Name())\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr = cmd.Run()\n\tif err == nil {\n\t\tFail(\"Application succeeeded even though it shouldn't have\")\n\t}\n}\n\nfunc completesInTime(dothis func(), howLong time.Duration) bool {\n\tc1 := make(chan string, 1)\n\tgo func() {\n\t\tdothis()\n\t\tc1 <- \"completed\"\n\t}()\n\n\tselect {\n\tcase <-c1:\n\t\treturn true\n\tcase <-time.After(howLong):\n\t\treturn false\n\t}\n}\n\nfunc canAccessDashboard() error {\n\t\/\/ Access the dashboard a few times to hit all replicas\n\tfor i := 0; i < 3; i++ {\n\t\tcmd := exec.Command(\".\/kismatic\", \"dashboard\", \"--url\", \"-f\", \"kismatic-testing.yaml\")\n\t\tcmd.Stdout = os.Stdout\n\t\tcmd.Stderr = os.Stderr\n\t\tif err := cmd.Run(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc FailIfError(err error, message ...interface{}) {\n\tExpect(err).ToNot(HaveOccurred(), message...)\n}\n\nfunc FailIfSuccess(err error) {\n\tif err == nil {\n\t\tFail(\"Expected failure\")\n\t}\n}\n\nfunc FileExists(path string) bool {\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn false\n\t}\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>package dynect\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ ConvenientClient A client with extra helper methods for common actions\ntype ConvenientClient struct {\n\tClient\n}\n\n\/\/ NewConvenientClient Creates a new ConvenientClient\nfunc NewConvenientClient(customerName string) *ConvenientClient {\n\treturn &ConvenientClient{\n\t\tClient{\n\t\t\tCustomerName: customerName,\n\t\t\tTransport:    &http.Transport{Proxy: http.ProxyFromEnvironment},\n\t\t}}\n}\n\n\/\/ CreateZone method to create a zone\nfunc (c *ConvenientClient) CreateZone(zone, rname, serialStyle, ttl string) error {\n\turl := fmt.Sprintf(\"Zone\/%s\/\", zone)\n\tdata := &CreateZoneBlock{\n\t\tRName:       rname,\n\t\tSerialStyle: serialStyle,\n\t\tTTL:         ttl,\n\t}\n\n\tif err := c.Do(\"POST\", url, data, nil); err != nil {\n\t\treturn fmt.Errorf(\"Failed to create zone: %s\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ GetZone method to read a zone\nfunc (c *ConvenientClient) GetZone(z *Zone) error {\n\turl := fmt.Sprintf(\"Zone\/%s\", z.Zone)\n\tdata := &ZoneResponse{}\n\n\tif err := c.Do(\"GET\", url, nil, data); err != nil {\n\t\treturn fmt.Errorf(\"Failed to get zone: %s\", err)\n\t}\n\n\tz.Serial = strconv.Itoa(data.Data.Serial)\n\tz.SerialStyle = data.Data.SerialStyle\n\tz.Zone = data.Data.Zone\n\tz.Type = data.Data.ZoneType\n\n\treturn nil\n}\n\n\/\/ PublishZone Publish a specific zone and the changes for the current session\nfunc (c *ConvenientClient) PublishZone(zone string) error {\n\turl := fmt.Sprintf(\"Zone\/%s\", zone)\n\tdata := &PublishZoneBlock{\n\t\tPublish: true,\n\t}\n\tresp := &PublishZoneResponseBlock{}\n\tif err := c.Do(\"PUT\", url, data, resp); err != nil {\n\t\treturn fmt.Errorf(\"Failed to publish zone: %s\", err)\n\t}\n\turl = fmt.Sprintf(\"Task\/%s\/\", resp.Data.TaskID)\n\trespTask := &TaskStateResponse{}\n\t\/\/ Wait until the zone is published, but no more then 10s\n\tfor i := 0; i < 100; i++ {\n\t\tif err := c.Do(\"GET\", url, nil, respTask); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to get task status: %s %s\", resp.Data.TaskID, err)\n\t\t}\n\t\tlog.Printf(\"Publishing zone %s. Status: %#+v : %#+v\\n\", zone, respTask.Data.Status, respTask)\n\t\tif respTask.Data.Status == \"complete\" {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\n\treturn nil\n}\n\n\/\/ DeleteZoneNode method to delete everything in a zone\nfunc (c *ConvenientClient) DeleteZoneNode(zone string) error {\n\tparentZone := strings.Join(strings.Split(zone, \".\")[1:], \".\")\n\turl := fmt.Sprintf(\"Node\/%s\/%s\", parentZone, zone)\n\n\tif err := c.Do(\"DELETE\", url, nil, nil); err != nil {\n\t\treturn fmt.Errorf(\"Failed to delete zone node: %s\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ DeleteZone method to delete a zone\nfunc (c *ConvenientClient) DeleteZone(zone string) error {\n\turl := fmt.Sprintf(\"Zone\/%s\/\", zone)\n\n\tif err := c.Do(\"DELETE\", url, nil, nil); err != nil {\n\t\treturn fmt.Errorf(\"Failed to delete zone: %s\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ GetRecordID finds the dns record ID by fetching all records for a FQDN\nfunc (c *ConvenientClient) GetRecordID(record *Record) error {\n\tfinalID := \"\"\n\turl := fmt.Sprintf(\"AllRecord\/%s\/%s\", record.Zone, record.FQDN)\n\tvar records AllRecordsResponse\n\terr := c.Do(\"GET\", url, nil, &records)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to find Dyn record id: %s\", err)\n\t}\n\tfor _, recordURL := range records.Data {\n\t\tid := strings.TrimPrefix(recordURL, fmt.Sprintf(\"\/REST\/%sRecord\/%s\/%s\/\", record.Type, record.Zone, record.FQDN))\n\t\tif !strings.Contains(id, \"\/\") && id != \"\" {\n\t\t\tfinalID = id\n\t\t\tlog.Printf(\"[INFO] Found Dyn record ID: %s\", id)\n\t\t}\n\t}\n\tif finalID == \"\" {\n\t\treturn fmt.Errorf(\"Failed to find Dyn record id!\")\n\t}\n\n\trecord.ID = finalID\n\treturn nil\n}\n\n\/\/ CreateRecord Method to create a DNS record\nfunc (c *ConvenientClient) CreateRecord(record *Record) error {\n\tif record.FQDN == \"\" && record.Name == \"\" {\n\t\trecord.FQDN = record.Zone\n\t} else if record.FQDN == \"\" {\n\t\trecord.FQDN = fmt.Sprintf(\"%s.%s\", record.Name, record.Zone)\n\t}\n\trdata, err := buildRData(record)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create Dyn RData: %s\", err)\n\t}\n\turl := fmt.Sprintf(\"%sRecord\/%s\/%s\", record.Type, record.Zone, record.FQDN)\n\tdata := &RecordRequest{\n\t\tRData: rdata,\n\t\tTTL:   record.TTL,\n\t}\n\treturn c.Do(\"POST\", url, data, nil)\n}\n\n\/\/ UpdateRecord Method to update a DNS record\nfunc (c *ConvenientClient) UpdateRecord(record *Record) error {\n\tif record.FQDN == \"\" {\n\t\trecord.FQDN = fmt.Sprintf(\"%s.%s\", record.Name, record.Zone)\n\t}\n\trdata, err := buildRData(record)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create Dyn RData: %s\", err)\n\t}\n\turl := fmt.Sprintf(\"%sRecord\/%s\/%s\/%s\", record.Type, record.Zone, record.FQDN, record.ID)\n\tdata := &RecordRequest{\n\t\tRData: rdata,\n\t\tTTL:   record.TTL,\n\t}\n\treturn c.Do(\"PUT\", url, data, nil)\n}\n\n\/\/ DeleteRecord Method to delete a DNS record\nfunc (c *ConvenientClient) DeleteRecord(record *Record) error {\n\tif record.FQDN == \"\" {\n\t\trecord.FQDN = fmt.Sprintf(\"%s.%s\", record.Name, record.Zone)\n\t}\n\t\/\/ safety check that we have an ID, otherwise we could accidentally delete everything\n\tif record.ID == \"\" {\n\t\treturn fmt.Errorf(\"No ID found! We can't continue!\")\n\t}\n\turl := fmt.Sprintf(\"%sRecord\/%s\/%s\/%s\", record.Type, record.Zone, record.FQDN, record.ID)\n\treturn c.Do(\"DELETE\", url, nil, nil)\n}\n\n\/\/ GetRecord Method to get record details\nfunc (c *ConvenientClient) GetRecord(record *Record) error {\n\turl := fmt.Sprintf(\"%sRecord\/%s\/%s\/%s\", record.Type, record.Zone, record.FQDN, record.ID)\n\tvar rec RecordResponse\n\terr := c.Do(\"GET\", url, nil, &rec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trecord.Zone = rec.Data.Zone\n\trecord.FQDN = rec.Data.FQDN\n\trecord.Name = strings.TrimSuffix(rec.Data.FQDN, \".\"+rec.Data.Zone)\n\trecord.Type = rec.Data.RecordType\n\trecord.TTL = strconv.Itoa(rec.Data.TTL)\n\n\tswitch rec.Data.RecordType {\n\tcase \"A\", \"AAAA\":\n\t\trecord.Value = rec.Data.RData.Address\n\tcase \"ALIAS\":\n\t\trecord.Value = rec.Data.RData.Alias\n\tcase \"CNAME\":\n\t\trecord.Value = rec.Data.RData.CName\n\tcase \"MX\":\n\t\trecord.Value = fmt.Sprintf(\"%d %s\", rec.Data.RData.Preference, rec.Data.RData.Exchange)\n\tcase \"NS\":\n\t\trecord.Value = rec.Data.RData.NSDName\n\tcase \"SOA\":\n\t\trecord.Value = rec.Data.RData.RName\n\tcase \"TXT\", \"SPF\":\n\t\trecord.Value = rec.Data.RData.TxtData\n\tdefault:\n\t\tfmt.Println(\"unknown response\", rec)\n\t\treturn fmt.Errorf(\"Invalid Dyn record type: %s\", rec.Data.RecordType)\n\t}\n\n\treturn nil\n}\n\nfunc buildRData(r *Record) (DataBlock, error) {\n\tvar rdata DataBlock\n\n\tswitch r.Type {\n\tcase \"A\", \"AAAA\":\n\t\trdata = DataBlock{\n\t\t\tAddress: r.Value,\n\t\t}\n\tcase \"ALIAS\":\n\t\trdata = DataBlock{\n\t\t\tAlias: r.Value,\n\t\t}\n\tcase \"CNAME\":\n\t\trdata = DataBlock{\n\t\t\tCName: r.Value,\n\t\t}\n\tcase \"MX\":\n\t\trdata = DataBlock{}\n\t\tfmt.Sscanf(r.Value, \"%d %s\", &rdata.Preference, &rdata.Exchange)\n\tcase \"NS\":\n\t\trdata = DataBlock{\n\t\t\tNSDName: r.Value,\n\t\t}\n\tcase \"SOA\":\n\t\trdata = DataBlock{\n\t\t\tRName: r.Value,\n\t\t}\n\tcase \"TXT\", \"SPF\":\n\t\trdata = DataBlock{\n\t\t\tTxtData: r.Value,\n\t\t}\n\tdefault:\n\t\treturn rdata, fmt.Errorf(\"Invalid Dyn record type: %s\", r.Type)\n\t}\n\n\treturn rdata, nil\n}\n<commit_msg>better variables declaration<commit_after>package dynect\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ ConvenientClient A client with extra helper methods for common actions\ntype ConvenientClient struct {\n\tClient\n}\n\n\/\/ NewConvenientClient Creates a new ConvenientClient\nfunc NewConvenientClient(customerName string) *ConvenientClient {\n\treturn &ConvenientClient{\n\t\tClient{\n\t\t\tCustomerName: customerName,\n\t\t\tTransport:    &http.Transport{Proxy: http.ProxyFromEnvironment},\n\t\t}}\n}\n\n\/\/ CreateZone method to create a zone\nfunc (c *ConvenientClient) CreateZone(zone, rname, serialStyle, ttl string) error {\n\turl := fmt.Sprintf(\"Zone\/%s\/\", zone)\n\tdata := &CreateZoneBlock{\n\t\tRName:       rname,\n\t\tSerialStyle: serialStyle,\n\t\tTTL:         ttl,\n\t}\n\n\tif err := c.Do(\"POST\", url, data, nil); err != nil {\n\t\treturn fmt.Errorf(\"Failed to create zone: %s\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ GetZone method to read a zone\nfunc (c *ConvenientClient) GetZone(z *Zone) error {\n\turl := fmt.Sprintf(\"Zone\/%s\", z.Zone)\n\tdata := &ZoneResponse{}\n\n\tif err := c.Do(\"GET\", url, nil, data); err != nil {\n\t\treturn fmt.Errorf(\"Failed to get zone: %s\", err)\n\t}\n\n\tz.Serial = strconv.Itoa(data.Data.Serial)\n\tz.SerialStyle = data.Data.SerialStyle\n\tz.Zone = data.Data.Zone\n\tz.Type = data.Data.ZoneType\n\n\treturn nil\n}\n\n\/\/ PublishZone Publish a specific zone and the changes for the current session\nfunc (c *ConvenientClient) PublishZone(zone string) error {\n\turl := fmt.Sprintf(\"Zone\/%s\", zone)\n\tdata := &PublishZoneBlock{\n\t\tPublish: true,\n\t}\n\tvar resp PublishZoneResponseBlock\n\tif err := c.Do(\"PUT\", url, data, &resp); err != nil {\n\t\treturn fmt.Errorf(\"Failed to publish zone: %s\", err)\n\t}\n\turl = fmt.Sprintf(\"Task\/%s\/\", resp.Data.TaskID)\n\t\/\/ Wait until the zone is published, but no more then 10s\n\tfor i := 0; i < 100; i++ {\n\t\tvar respTask TaskStateResponse\n\t\tif err := c.Do(\"GET\", url, nil, &respTask); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to get task status: %s %s\", resp.Data.TaskID, err)\n\t\t}\n\t\tlog.Printf(\"Publishing zone %s. Status: %#+v : %#+v\\n\", zone, respTask.Data.Status, respTask)\n\t\tif respTask.Data.Status == \"complete\" {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\n\treturn nil\n}\n\n\/\/ DeleteZoneNode method to delete everything in a zone\nfunc (c *ConvenientClient) DeleteZoneNode(zone string) error {\n\tparentZone := strings.Join(strings.Split(zone, \".\")[1:], \".\")\n\turl := fmt.Sprintf(\"Node\/%s\/%s\", parentZone, zone)\n\n\tif err := c.Do(\"DELETE\", url, nil, nil); err != nil {\n\t\treturn fmt.Errorf(\"Failed to delete zone node: %s\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ DeleteZone method to delete a zone\nfunc (c *ConvenientClient) DeleteZone(zone string) error {\n\turl := fmt.Sprintf(\"Zone\/%s\/\", zone)\n\n\tif err := c.Do(\"DELETE\", url, nil, nil); err != nil {\n\t\treturn fmt.Errorf(\"Failed to delete zone: %s\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ GetRecordID finds the dns record ID by fetching all records for a FQDN\nfunc (c *ConvenientClient) GetRecordID(record *Record) error {\n\tfinalID := \"\"\n\turl := fmt.Sprintf(\"AllRecord\/%s\/%s\", record.Zone, record.FQDN)\n\tvar records AllRecordsResponse\n\terr := c.Do(\"GET\", url, nil, &records)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to find Dyn record id: %s\", err)\n\t}\n\tfor _, recordURL := range records.Data {\n\t\tid := strings.TrimPrefix(recordURL, fmt.Sprintf(\"\/REST\/%sRecord\/%s\/%s\/\", record.Type, record.Zone, record.FQDN))\n\t\tif !strings.Contains(id, \"\/\") && id != \"\" {\n\t\t\tfinalID = id\n\t\t\tlog.Printf(\"[INFO] Found Dyn record ID: %s\", id)\n\t\t}\n\t}\n\tif finalID == \"\" {\n\t\treturn fmt.Errorf(\"Failed to find Dyn record id!\")\n\t}\n\n\trecord.ID = finalID\n\treturn nil\n}\n\n\/\/ CreateRecord Method to create a DNS record\nfunc (c *ConvenientClient) CreateRecord(record *Record) error {\n\tif record.FQDN == \"\" && record.Name == \"\" {\n\t\trecord.FQDN = record.Zone\n\t} else if record.FQDN == \"\" {\n\t\trecord.FQDN = fmt.Sprintf(\"%s.%s\", record.Name, record.Zone)\n\t}\n\trdata, err := buildRData(record)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create Dyn RData: %s\", err)\n\t}\n\turl := fmt.Sprintf(\"%sRecord\/%s\/%s\", record.Type, record.Zone, record.FQDN)\n\tdata := &RecordRequest{\n\t\tRData: rdata,\n\t\tTTL:   record.TTL,\n\t}\n\treturn c.Do(\"POST\", url, data, nil)\n}\n\n\/\/ UpdateRecord Method to update a DNS record\nfunc (c *ConvenientClient) UpdateRecord(record *Record) error {\n\tif record.FQDN == \"\" {\n\t\trecord.FQDN = fmt.Sprintf(\"%s.%s\", record.Name, record.Zone)\n\t}\n\trdata, err := buildRData(record)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create Dyn RData: %s\", err)\n\t}\n\turl := fmt.Sprintf(\"%sRecord\/%s\/%s\/%s\", record.Type, record.Zone, record.FQDN, record.ID)\n\tdata := &RecordRequest{\n\t\tRData: rdata,\n\t\tTTL:   record.TTL,\n\t}\n\treturn c.Do(\"PUT\", url, data, nil)\n}\n\n\/\/ DeleteRecord Method to delete a DNS record\nfunc (c *ConvenientClient) DeleteRecord(record *Record) error {\n\tif record.FQDN == \"\" {\n\t\trecord.FQDN = fmt.Sprintf(\"%s.%s\", record.Name, record.Zone)\n\t}\n\t\/\/ safety check that we have an ID, otherwise we could accidentally delete everything\n\tif record.ID == \"\" {\n\t\treturn fmt.Errorf(\"No ID found! We can't continue!\")\n\t}\n\turl := fmt.Sprintf(\"%sRecord\/%s\/%s\/%s\", record.Type, record.Zone, record.FQDN, record.ID)\n\treturn c.Do(\"DELETE\", url, nil, nil)\n}\n\n\/\/ GetRecord Method to get record details\nfunc (c *ConvenientClient) GetRecord(record *Record) error {\n\turl := fmt.Sprintf(\"%sRecord\/%s\/%s\/%s\", record.Type, record.Zone, record.FQDN, record.ID)\n\tvar rec RecordResponse\n\terr := c.Do(\"GET\", url, nil, &rec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trecord.Zone = rec.Data.Zone\n\trecord.FQDN = rec.Data.FQDN\n\trecord.Name = strings.TrimSuffix(rec.Data.FQDN, \".\"+rec.Data.Zone)\n\trecord.Type = rec.Data.RecordType\n\trecord.TTL = strconv.Itoa(rec.Data.TTL)\n\n\tswitch rec.Data.RecordType {\n\tcase \"A\", \"AAAA\":\n\t\trecord.Value = rec.Data.RData.Address\n\tcase \"ALIAS\":\n\t\trecord.Value = rec.Data.RData.Alias\n\tcase \"CNAME\":\n\t\trecord.Value = rec.Data.RData.CName\n\tcase \"MX\":\n\t\trecord.Value = fmt.Sprintf(\"%d %s\", rec.Data.RData.Preference, rec.Data.RData.Exchange)\n\tcase \"NS\":\n\t\trecord.Value = rec.Data.RData.NSDName\n\tcase \"SOA\":\n\t\trecord.Value = rec.Data.RData.RName\n\tcase \"TXT\", \"SPF\":\n\t\trecord.Value = rec.Data.RData.TxtData\n\tdefault:\n\t\tfmt.Println(\"unknown response\", rec)\n\t\treturn fmt.Errorf(\"Invalid Dyn record type: %s\", rec.Data.RecordType)\n\t}\n\n\treturn nil\n}\n\nfunc buildRData(r *Record) (DataBlock, error) {\n\tvar rdata DataBlock\n\n\tswitch r.Type {\n\tcase \"A\", \"AAAA\":\n\t\trdata = DataBlock{\n\t\t\tAddress: r.Value,\n\t\t}\n\tcase \"ALIAS\":\n\t\trdata = DataBlock{\n\t\t\tAlias: r.Value,\n\t\t}\n\tcase \"CNAME\":\n\t\trdata = DataBlock{\n\t\t\tCName: r.Value,\n\t\t}\n\tcase \"MX\":\n\t\trdata = DataBlock{}\n\t\tfmt.Sscanf(r.Value, \"%d %s\", &rdata.Preference, &rdata.Exchange)\n\tcase \"NS\":\n\t\trdata = DataBlock{\n\t\t\tNSDName: r.Value,\n\t\t}\n\tcase \"SOA\":\n\t\trdata = DataBlock{\n\t\t\tRName: r.Value,\n\t\t}\n\tcase \"TXT\", \"SPF\":\n\t\trdata = DataBlock{\n\t\t\tTxtData: r.Value,\n\t\t}\n\tdefault:\n\t\treturn rdata, fmt.Errorf(\"Invalid Dyn record type: %s\", r.Type)\n\t}\n\n\treturn rdata, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package genetics\n\nimport (\n\t\"testing\"\n\t\"bytes\"\n\t\"github.com\/yaricom\/goNEAT\/neat\"\n\t\"fmt\"\n\t\"strings\"\n\t\"bufio\"\n\t\"github.com\/yaricom\/goNEAT\/neat\/network\"\n\t\"reflect\"\n)\n\nfunc TestPlainGenomeWriter_WriteTrait(t *testing.T) {\n\tparams := []float64{\n\t\t0.40227575878298616, 0.0, 0.0, 0.0, 0.0, 0.3245553261200018, 0.0, 0.12248956525856575,\n\t}\n\ttrait_id := 2\n\ttrait := neat.NewTrait()\n\ttrait.Id = trait_id\n\ttrait.Params = params\n\n\ttrait_str := fmt.Sprintf(\"%d %g %g %g %g %g %g %g %g\",\n\t\ttrait_id, params[0], params[1], params[2], params[3], params[4], params[5], params[6], params[7])\n\n\tout_buffer := bytes.NewBufferString(\"\")\n\twr := plainGenomeWriter{w:bufio.NewWriter(out_buffer)}\n\terr := wr.writeTrait(trait)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\twr.w.Flush()\n\n\tout_str := strings.TrimSpace(out_buffer.String())\n\tif trait_str != out_str {\n\t\tt.Errorf(\"Wrong trait serialization\\n[%s]\\n[%s]\", trait_str, out_str)\n\t}\n}\n\n\/\/ Tests NNode serialization\nfunc TestPlainGenomeWriter_WriteNetworkNode(t *testing.T) {\n\tnode_id, trait_id, ntype, neuron_type := 1, 10, network.SensorNode, network.InputNeuron\n\tnode_str := fmt.Sprintf(\"%d %d %d %d SigmoidSteepenedActivation\", node_id, trait_id, ntype, neuron_type)\n\ttrait := neat.NewTrait()\n\ttrait.Id = 10\n\n\tnode := network.NewNNode(node_id, neuron_type)\n\tnode.Trait = trait\n\tout_buffer := bytes.NewBufferString(\"\")\n\n\twr := plainGenomeWriter{w:bufio.NewWriter(out_buffer)}\n\terr := wr.writeNetworkNode(node)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\twr.w.Flush()\n\n\tout_str := out_buffer.String()\n\n\tif out_str != node_str {\n\t\tt.Errorf(\"Node serialization failed. Expected: %s, but found %s\", node_str, out_str)\n\t}\n}\n\nfunc TestPlainGenomeWriter_WriteConnectionGene(t *testing.T) {\n\t\/\/ gene  1 1 4 1.1983046913458986 0 1.0 1.1983046913458986 0\n\ttraitId, inNodeId, outNodeId, innov_num := 1, 1, 4, int64(1)\n\tweight, mut_num := 1.1983046913458986, 1.1983046913458986\n\trecurrent, enabled := false, false\n\tgene_str := fmt.Sprintf(\"%d %d %d %g %t %d %g %t\",\n\t\ttraitId, inNodeId, outNodeId, weight, recurrent, innov_num, mut_num, enabled)\n\n\ttrait := neat.NewTrait()\n\ttrait.Id = traitId\n\tgene := NewGeneWithTrait(trait, weight, network.NewNNode(1, network.InputNeuron),\n\t\tnetwork.NewNNode(4, network.HiddenNeuron), recurrent, innov_num, mut_num)\n\tgene.IsEnabled = enabled\n\n\tout_buf := bytes.NewBufferString(\"\")\n\n\twr := plainGenomeWriter{w:bufio.NewWriter(out_buf)}\n\terr := wr.writeConnectionGene(gene)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\twr.w.Flush()\n\n\tout_str := out_buf.String()\n\tif gene_str != out_str {\n\t\tt.Errorf(\"Wrong Gene serialization\\n[%s]\\n[%s]\", gene_str, out_str)\n\t}\n}\n\nfunc TestPlainGenomeWriter_WriteGenome(t *testing.T) {\n\tgnome := buildTestGenome(1)\n\tout_buf := bytes.NewBufferString(\"\")\n\twr, err := NewGenomeWriter(bufio.NewWriter(out_buf), PlainGenomeEncoding)\n\tif err == nil {\n\t\terr = wr.WriteGenome(gnome)\n\t}\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tg_scanner := bufio.NewScanner(strings.NewReader(gnome_str))\n\tg_scanner.Split(bufio.ScanLines)\n\n\to_scanner := bufio.NewScanner(out_buf)\n\to_scanner.Split(bufio.ScanLines)\n\n\tfor g_scanner.Scan() {\n\t\tif !o_scanner.Scan() {\n\t\t\tt.Error(\"Unexpected end of genome data\")\n\t\t}\n\t\tg_text := g_scanner.Text()\n\t\to_text := o_scanner.Text()\n\t\tif g_text != o_text {\n\t\t\tt.Error(fmt.Sprintf(\"Lines mismatch [%s] != [%s]\" , g_text, o_text))\n\t\t}\n\t}\n}\n\nfunc TestYamlGenomeWriter_WriteGenome(t *testing.T) {\n\tgnome := buildTestGenome(1)\n\n\t\/\/ append module with it's IO nodes\n\tio_nodes := []*network.NNode{\n\t\t{Id:5, NeuronType: network.HiddenNeuron, ActivationType: network.LinearActivation, Incoming:make([]*network.Link, 0), Outgoing:make([]*network.Link, 0)},\n\t\t{Id:6, NeuronType: network.HiddenNeuron, ActivationType: network.LinearActivation, Incoming:make([]*network.Link, 0), Outgoing:make([]*network.Link, 0)},\n\t\t{Id:7, NeuronType: network.HiddenNeuron, ActivationType: network.NullActivation, Incoming:make([]*network.Link, 0), Outgoing:make([]*network.Link, 0)},\n\t}\n\tgnome.Nodes = append(gnome.Nodes, io_nodes ...)\n\n\t\/\/ connect added nodes\n\tio_conn_genes := []*Gene{\n\t\tnewGene(network.NewLinkWithTrait(gnome.Traits[0], 1.5, gnome.Nodes[0], gnome.Nodes[4], false), 4, 0, true),\n\t\tnewGene(network.NewLinkWithTrait(gnome.Traits[2], 2.5, gnome.Nodes[1], gnome.Nodes[5], false), 5, 0, true),\n\t\tnewGene(network.NewLinkWithTrait(gnome.Traits[1], 3.5, gnome.Nodes[6], gnome.Nodes[3], false), 6, 0, true),\n\t}\n\tgnome.Genes = append(gnome.Genes, io_conn_genes ...)\n\n\t\/\/ add control gene\n\tc_node := &network.NNode{\n\t\tId:8, NeuronType: network.HiddenNeuron,\n\t\tActivationType: network.MultiplyModuleActivation,\n\t}\n\tc_node.Incoming = []*network.Link{\n\t\t{Weight:1.0, InNode:io_nodes[0], OutNode:c_node},\n\t\t{Weight:1.0, InNode:io_nodes[1], OutNode:c_node},\n\t}\n\tc_node.Outgoing = []*network.Link{\n\t\t{Weight:1.0, InNode:c_node, OutNode:io_nodes[2]},\n\t}\n\tgnome.ControlGenes = []*MIMOControlGene{newMIMOGene(c_node, int64(7), 5.5, true)}\n\n\t\/\/ encode genome\n\tout_buf := bytes.NewBufferString(\"\")\n\twr, err := NewGenomeWriter(bufio.NewWriter(out_buf), YAMLGenomeEncoding)\n\tif err == nil {\n\t\terr = wr.WriteGenome(gnome)\n\t}\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\t\/\/t.Log(out_buf.String())\n\n\t\/\/ decode genome and compare\n\tenc := yamlGenomeReader{r:bufio.NewReader(bytes.NewBuffer(out_buf.Bytes()))}\n\tgnome_enc, err := enc.Read()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tif gnome.Id != gnome_enc.Id {\n\t\tt.Error(\"gnome.Id != gnome_enc.Id\", gnome.Id, gnome_enc.Id)\n\t}\n\tif len(gnome.Genes) != len(gnome_enc.Genes) {\n\t\tt.Error(\"len(gnome.Genes) != len(gnome_enc.Genes)\", len(gnome.Genes), len(gnome_enc.Genes))\n\t}\n\tfor i, g := range gnome.Genes {\n\t\tog := gnome_enc.Genes[i]\n\t\tif !g.Link.IsEqualGenetically(og.Link) {\n\t\t\tt.Error(\"!g.Link.IsEqualGenetically(og.Link) at:\", i)\n\t\t}\n\t\tif g.IsEnabled != og.IsEnabled {\n\t\t\tt.Error(\"g.IsEnabled != og.IsEnabled at:\", i)\n\t\t}\n\t\tif g.MutationNum != og.MutationNum {\n\t\t\tt.Error(\"g.MutationNum != og.MutationNum at:\", i)\n\t\t}\n\t\tif g.InnovationNum != og.InnovationNum {\n\t\t\tt.Error(\"g.InnovationNum != og.InnovationNum at:\", i)\n\t\t}\n\t}\n\n\tif len(gnome.Nodes) != len(gnome_enc.Nodes) {\n\t\tt.Error(\"len(gnome.Nodes) != len(gnome_enc.Nodes)\", len(gnome.Nodes), len(gnome_enc.Nodes))\n\t}\n\tfor i, n := range gnome.Nodes {\n\t\tnd := gnome_enc.Nodes[i]\n\t\tif n.Id != nd.Id {\n\t\t\tt.Error(\"n.Id != nd.Id at:\", i)\n\t\t}\n\t\tif n.ActivationType != nd.ActivationType {\n\t\t\tt.Error(\"n.ActivationType != nd.ActivationType at:\", i)\n\t\t}\n\t\tif n.NeuronType != nd.NeuronType {\n\t\t\tt.Error(\"n.NeuronType != nd.NeuronType at:\", i)\n\t\t}\n\t}\n\n\tif len(gnome.Traits) != len(gnome_enc.Traits) {\n\t\tt.Error(\"len(gnome.Traits) != len(gnome_enc.Traits)\", len(gnome.Traits), len(gnome_enc.Traits))\n\t}\n\tfor i, tr := range gnome.Traits {\n\t\tetr := gnome_enc.Traits[i]\n\t\tif tr.Id != etr.Id {\n\t\t\tt.Error(\"tr.Id != etr.Id at:\", i)\n\t\t}\n\t\tif !reflect.DeepEqual(tr.Params, etr.Params) {\n\t\t\tt.Error(\"!reflect.DeepEqual(tr.Params, etr.Params) at:\", i)\n\t\t}\n\t}\n\n\tif len(gnome.ControlGenes) != len(gnome_enc.ControlGenes) {\n\t\tt.Error(\"len(gnome.ControlGenes) != len(gnome_enc.ControlGenes)\",\n\t\t\tlen(gnome.ControlGenes), len(gnome_enc.ControlGenes))\n\t}\n\tfor i, cg := range gnome.ControlGenes {\n\t\tocg := gnome_enc.ControlGenes[i]\n\t\tif cg.IsEnabled != ocg.IsEnabled {\n\t\t\tt.Error(\"cg.IsEnabled != ocg.IsEnabled at: \", i)\n\t\t}\n\t\tif cg.MutationNum != ocg.MutationNum {\n\t\t\tt.Error(\"cg.MutationNum != ocg.MutationNum at:\", i)\n\t\t}\n\t\tif cg.InnovationNum != ocg.InnovationNum {\n\t\t\tt.Error(\"cg.InnovationNum != ocg.InnovationNum at:\", i)\n\t\t}\n\t\tif cg.ControlNode.Id != ocg.ControlNode.Id {\n\t\t\tt.Error(\"cg.ControlNode.Id != ocg.ControlNode.Id at:\", i, cg.ControlNode.Id, ocg.ControlNode.Id)\n\t\t}\n\t\tcheckLinks(cg.ControlNode.Incoming, ocg.ControlNode.Incoming, t)\n\t\tcheckLinks(cg.ControlNode.Outgoing, ocg.ControlNode.Outgoing, t)\n\t}\n}\n\nfunc checkLinks(left, right []*network.Link, t *testing.T) {\n\tif len(left) != len(right) {\n\t\tt.Error(\"Links size mismatch\", len(left), len(right))\n\t}\n\tfor i, l := range left {\n\t\tr := right[i]\n\t\tif l.InNode.Id != r.InNode.Id {\n\t\t\tt.Error(\"l.InNode.Id != r.InNode.Id\", l.InNode.Id, r.InNode.Id)\n\t\t}\n\t\tif l.OutNode.Id != r.OutNode.Id {\n\t\t\tt.Error(\"l.OutNode.Id != r.OutNode.Id\", l.OutNode.Id, r.OutNode.Id )\n\t\t}\n\t\tif l.Weight != r.Weight {\n\t\t\tt.Error(\"l.Weight != r.Weight\", l.Weight, r.Weight)\n\t\t}\n\t}\n}<commit_msg>Modular genome build routine extracted into separate function<commit_after>package genetics\n\nimport (\n\t\"testing\"\n\t\"bytes\"\n\t\"github.com\/yaricom\/goNEAT\/neat\"\n\t\"fmt\"\n\t\"strings\"\n\t\"bufio\"\n\t\"github.com\/yaricom\/goNEAT\/neat\/network\"\n\t\"reflect\"\n)\n\nfunc TestPlainGenomeWriter_WriteTrait(t *testing.T) {\n\tparams := []float64{\n\t\t0.40227575878298616, 0.0, 0.0, 0.0, 0.0, 0.3245553261200018, 0.0, 0.12248956525856575,\n\t}\n\ttrait_id := 2\n\ttrait := neat.NewTrait()\n\ttrait.Id = trait_id\n\ttrait.Params = params\n\n\ttrait_str := fmt.Sprintf(\"%d %g %g %g %g %g %g %g %g\",\n\t\ttrait_id, params[0], params[1], params[2], params[3], params[4], params[5], params[6], params[7])\n\n\tout_buffer := bytes.NewBufferString(\"\")\n\twr := plainGenomeWriter{w:bufio.NewWriter(out_buffer)}\n\terr := wr.writeTrait(trait)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\twr.w.Flush()\n\n\tout_str := strings.TrimSpace(out_buffer.String())\n\tif trait_str != out_str {\n\t\tt.Errorf(\"Wrong trait serialization\\n[%s]\\n[%s]\", trait_str, out_str)\n\t}\n}\n\n\/\/ Tests NNode serialization\nfunc TestPlainGenomeWriter_WriteNetworkNode(t *testing.T) {\n\tnode_id, trait_id, ntype, neuron_type := 1, 10, network.SensorNode, network.InputNeuron\n\tnode_str := fmt.Sprintf(\"%d %d %d %d SigmoidSteepenedActivation\", node_id, trait_id, ntype, neuron_type)\n\ttrait := neat.NewTrait()\n\ttrait.Id = 10\n\n\tnode := network.NewNNode(node_id, neuron_type)\n\tnode.Trait = trait\n\tout_buffer := bytes.NewBufferString(\"\")\n\n\twr := plainGenomeWriter{w:bufio.NewWriter(out_buffer)}\n\terr := wr.writeNetworkNode(node)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\twr.w.Flush()\n\n\tout_str := out_buffer.String()\n\n\tif out_str != node_str {\n\t\tt.Errorf(\"Node serialization failed. Expected: %s, but found %s\", node_str, out_str)\n\t}\n}\n\nfunc TestPlainGenomeWriter_WriteConnectionGene(t *testing.T) {\n\t\/\/ gene  1 1 4 1.1983046913458986 0 1.0 1.1983046913458986 0\n\ttraitId, inNodeId, outNodeId, innov_num := 1, 1, 4, int64(1)\n\tweight, mut_num := 1.1983046913458986, 1.1983046913458986\n\trecurrent, enabled := false, false\n\tgene_str := fmt.Sprintf(\"%d %d %d %g %t %d %g %t\",\n\t\ttraitId, inNodeId, outNodeId, weight, recurrent, innov_num, mut_num, enabled)\n\n\ttrait := neat.NewTrait()\n\ttrait.Id = traitId\n\tgene := NewGeneWithTrait(trait, weight, network.NewNNode(1, network.InputNeuron),\n\t\tnetwork.NewNNode(4, network.HiddenNeuron), recurrent, innov_num, mut_num)\n\tgene.IsEnabled = enabled\n\n\tout_buf := bytes.NewBufferString(\"\")\n\n\twr := plainGenomeWriter{w:bufio.NewWriter(out_buf)}\n\terr := wr.writeConnectionGene(gene)\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\twr.w.Flush()\n\n\tout_str := out_buf.String()\n\tif gene_str != out_str {\n\t\tt.Errorf(\"Wrong Gene serialization\\n[%s]\\n[%s]\", gene_str, out_str)\n\t}\n}\n\nfunc TestPlainGenomeWriter_WriteGenome(t *testing.T) {\n\tgnome := buildTestGenome(1)\n\tout_buf := bytes.NewBufferString(\"\")\n\twr, err := NewGenomeWriter(bufio.NewWriter(out_buf), PlainGenomeEncoding)\n\tif err == nil {\n\t\terr = wr.WriteGenome(gnome)\n\t}\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tg_scanner := bufio.NewScanner(strings.NewReader(gnome_str))\n\tg_scanner.Split(bufio.ScanLines)\n\n\to_scanner := bufio.NewScanner(out_buf)\n\to_scanner.Split(bufio.ScanLines)\n\n\tfor g_scanner.Scan() {\n\t\tif !o_scanner.Scan() {\n\t\t\tt.Error(\"Unexpected end of genome data\")\n\t\t}\n\t\tg_text := g_scanner.Text()\n\t\to_text := o_scanner.Text()\n\t\tif g_text != o_text {\n\t\t\tt.Error(fmt.Sprintf(\"Lines mismatch [%s] != [%s]\" , g_text, o_text))\n\t\t}\n\t}\n}\n\nfunc TestYamlGenomeWriter_WriteGenome(t *testing.T) {\n\tgnome := buildTestModularGenome(1)\n\n\t\/\/ encode genome\n\tout_buf := bytes.NewBufferString(\"\")\n\twr, err := NewGenomeWriter(bufio.NewWriter(out_buf), YAMLGenomeEncoding)\n\tif err == nil {\n\t\terr = wr.WriteGenome(gnome)\n\t}\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\t\/\/t.Log(out_buf.String())\n\n\t\/\/ decode genome and compare\n\tenc := yamlGenomeReader{r:bufio.NewReader(bytes.NewBuffer(out_buf.Bytes()))}\n\tgnome_enc, err := enc.Read()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tif gnome.Id != gnome_enc.Id {\n\t\tt.Error(\"gnome.Id != gnome_enc.Id\", gnome.Id, gnome_enc.Id)\n\t}\n\tif len(gnome.Genes) != len(gnome_enc.Genes) {\n\t\tt.Error(\"len(gnome.Genes) != len(gnome_enc.Genes)\", len(gnome.Genes), len(gnome_enc.Genes))\n\t}\n\tfor i, g := range gnome.Genes {\n\t\tog := gnome_enc.Genes[i]\n\t\tif !g.Link.IsEqualGenetically(og.Link) {\n\t\t\tt.Error(\"!g.Link.IsEqualGenetically(og.Link) at:\", i)\n\t\t}\n\t\tif g.IsEnabled != og.IsEnabled {\n\t\t\tt.Error(\"g.IsEnabled != og.IsEnabled at:\", i)\n\t\t}\n\t\tif g.MutationNum != og.MutationNum {\n\t\t\tt.Error(\"g.MutationNum != og.MutationNum at:\", i)\n\t\t}\n\t\tif g.InnovationNum != og.InnovationNum {\n\t\t\tt.Error(\"g.InnovationNum != og.InnovationNum at:\", i)\n\t\t}\n\t}\n\n\tif len(gnome.Nodes) != len(gnome_enc.Nodes) {\n\t\tt.Error(\"len(gnome.Nodes) != len(gnome_enc.Nodes)\", len(gnome.Nodes), len(gnome_enc.Nodes))\n\t}\n\tfor i, n := range gnome.Nodes {\n\t\tnd := gnome_enc.Nodes[i]\n\t\tif n.Id != nd.Id {\n\t\t\tt.Error(\"n.Id != nd.Id at:\", i)\n\t\t}\n\t\tif n.ActivationType != nd.ActivationType {\n\t\t\tt.Error(\"n.ActivationType != nd.ActivationType at:\", i)\n\t\t}\n\t\tif n.NeuronType != nd.NeuronType {\n\t\t\tt.Error(\"n.NeuronType != nd.NeuronType at:\", i)\n\t\t}\n\t}\n\n\tif len(gnome.Traits) != len(gnome_enc.Traits) {\n\t\tt.Error(\"len(gnome.Traits) != len(gnome_enc.Traits)\", len(gnome.Traits), len(gnome_enc.Traits))\n\t}\n\tfor i, tr := range gnome.Traits {\n\t\tetr := gnome_enc.Traits[i]\n\t\tif tr.Id != etr.Id {\n\t\t\tt.Error(\"tr.Id != etr.Id at:\", i)\n\t\t}\n\t\tif !reflect.DeepEqual(tr.Params, etr.Params) {\n\t\t\tt.Error(\"!reflect.DeepEqual(tr.Params, etr.Params) at:\", i)\n\t\t}\n\t}\n\n\tif len(gnome.ControlGenes) != len(gnome_enc.ControlGenes) {\n\t\tt.Error(\"len(gnome.ControlGenes) != len(gnome_enc.ControlGenes)\",\n\t\t\tlen(gnome.ControlGenes), len(gnome_enc.ControlGenes))\n\t}\n\tfor i, cg := range gnome.ControlGenes {\n\t\tocg := gnome_enc.ControlGenes[i]\n\t\tif cg.IsEnabled != ocg.IsEnabled {\n\t\t\tt.Error(\"cg.IsEnabled != ocg.IsEnabled at: \", i)\n\t\t}\n\t\tif cg.MutationNum != ocg.MutationNum {\n\t\t\tt.Error(\"cg.MutationNum != ocg.MutationNum at:\", i)\n\t\t}\n\t\tif cg.InnovationNum != ocg.InnovationNum {\n\t\t\tt.Error(\"cg.InnovationNum != ocg.InnovationNum at:\", i)\n\t\t}\n\t\tif cg.ControlNode.Id != ocg.ControlNode.Id {\n\t\t\tt.Error(\"cg.ControlNode.Id != ocg.ControlNode.Id at:\", i, cg.ControlNode.Id, ocg.ControlNode.Id)\n\t\t}\n\t\tcheckLinks(cg.ControlNode.Incoming, ocg.ControlNode.Incoming, t)\n\t\tcheckLinks(cg.ControlNode.Outgoing, ocg.ControlNode.Outgoing, t)\n\t}\n}\n\nfunc checkLinks(left, right []*network.Link, t *testing.T) {\n\tif len(left) != len(right) {\n\t\tt.Error(\"Links size mismatch\", len(left), len(right))\n\t}\n\tfor i, l := range left {\n\t\tr := right[i]\n\t\tif l.InNode.Id != r.InNode.Id {\n\t\t\tt.Error(\"l.InNode.Id != r.InNode.Id\", l.InNode.Id, r.InNode.Id)\n\t\t}\n\t\tif l.OutNode.Id != r.OutNode.Id {\n\t\t\tt.Error(\"l.OutNode.Id != r.OutNode.Id\", l.OutNode.Id, r.OutNode.Id )\n\t\t}\n\t\tif l.Weight != r.Weight {\n\t\t\tt.Error(\"l.Weight != r.Weight\", l.Weight, r.Weight)\n\t\t}\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\t\"k8s.io\/client-go\/rest\"\n)\n\nfunc main() {\n\tinitLogrus()\n\n\tkubeClient, err := createKubeClient()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\twebhook := newWebhook(kubeClient)\n\n\ttlsConfig := &tlsConfig{\n\t\tcrtPath: env(\"TLS_CRT\"),\n\t\tkeyPath: env(\"TLS_KEY\"),\n\t}\n\n\tif err = webhook.start(443, tlsConfig, nil); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nvar logLevels = map[string]logrus.Level{\n\t\"panic\": logrus.PanicLevel,\n\t\"fatal\": logrus.FatalLevel,\n\t\"error\": logrus.ErrorLevel,\n\t\"warn\":  logrus.WarnLevel,\n\t\"info\":  logrus.InfoLevel,\n\t\"debug\": logrus.DebugLevel,\n\t\"trace\": logrus.TraceLevel,\n}\n\nfunc initLogrus() {\n\tlogrus.SetOutput(os.Stdout)\n\n\tlogLevel := logrus.DebugLevel\n\tinvalid := false\n\n\trawLogLevel, present := os.LookupEnv(\"LOG_LEVEL\")\n\tif present {\n\t\tif level, valid := logLevels[strings.ToLower(rawLogLevel)]; valid {\n\t\t\tlogLevel = level\n\t\t} else {\n\t\t\tinvalid = true\n\t\t}\n\t}\n\n\tlogrus.SetLevel(logLevel)\n\n\tif invalid {\n\t\tkeys := make([]string, len(logLevels))\n\t\ti := 0\n\t\tfor key := range logLevels {\n\t\t\tkeys[i] = key\n\t\t\ti++\n\t\t}\n\t\tlogrus.Warningf(\"Unknown log level %s, valid log levels are: %v\", rawLogLevel, strings.Join(keys, \", \"))\n\t}\n}\n\nfunc createKubeClient() (*kubeClient, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newKubeClient(config)\n}\n\nfunc env(key string) string {\n\tif value, found := os.LookupEnv(key); found {\n\t\treturn value\n\t}\n\tpanic(fmt.Errorf(\"%s env var not found\", key))\n}\n<commit_msg>Adding the ability to configure the webhook port.<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\t\"k8s.io\/client-go\/rest\"\n)\n\nfunc main() {\n\tinitLogrus()\n\n\tkubeClient, err := createKubeClient()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\twebhook := newWebhook(kubeClient)\n\n\ttlsConfig := &tlsConfig{\n\t\tcrtPath: env(\"TLS_CRT\"),\n\t\tkeyPath: env(\"TLS_KEY\"),\n\t}\n\n\tport, err := port(\"HTTPS_PORT\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err = webhook.start(port, tlsConfig, nil); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nvar logLevels = map[string]logrus.Level{\n\t\"panic\": logrus.PanicLevel,\n\t\"fatal\": logrus.FatalLevel,\n\t\"error\": logrus.ErrorLevel,\n\t\"warn\":  logrus.WarnLevel,\n\t\"info\":  logrus.InfoLevel,\n\t\"debug\": logrus.DebugLevel,\n\t\"trace\": logrus.TraceLevel,\n}\n\nfunc initLogrus() {\n\tlogrus.SetOutput(os.Stdout)\n\n\tlogLevel := logrus.DebugLevel\n\tinvalid := false\n\n\trawLogLevel, present := os.LookupEnv(\"LOG_LEVEL\")\n\tif present {\n\t\tif level, valid := logLevels[strings.ToLower(rawLogLevel)]; valid {\n\t\t\tlogLevel = level\n\t\t} else {\n\t\t\tinvalid = true\n\t\t}\n\t}\n\n\tlogrus.SetLevel(logLevel)\n\n\tif invalid {\n\t\tkeys := make([]string, len(logLevels))\n\t\ti := 0\n\t\tfor key := range logLevels {\n\t\t\tkeys[i] = key\n\t\t\ti++\n\t\t}\n\t\tlogrus.Warningf(\"Unknown log level %s, valid log levels are: %v\", rawLogLevel, strings.Join(keys, \", \"))\n\t}\n}\n\nfunc createKubeClient() (*kubeClient, error) {\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newKubeClient(config)\n}\n\nfunc env(key string) string {\n\tif value, found := os.LookupEnv(key); found {\n\t\treturn value\n\t}\n\tpanic(fmt.Errorf(\"%s env var not found\", key))\n}\n\nfunc port(key string) (int, error) {\n\tif port, found := os.LookupEnv(key); found {\n\t\treturn strconv.Atoi(port)\n\t}\n\treturn 443, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Hajime Hoshi\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build darwin freebsd linux windows\n\/\/ +build !js\n\/\/ +build !android\n\/\/ +build !ios\n\npackage ui\n\nimport (\n\t\"errors\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/go-gl\/glfw\/v3.2\/glfw\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/opengl\"\n)\n\ntype userInterface struct {\n\twindow      *glfw.Window\n\twidth       int\n\theight      int\n\tscale       float64\n\tdeviceScale float64\n\tfuncs       chan func()\n\trunning     bool\n\tsizeChanged bool\n\tm           sync.Mutex\n}\n\nvar currentUI *userInterface\n\nfunc init() {\n\tif err := initialize(); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc initialize() error {\n\truntime.LockOSThread()\n\n\tif err := glfw.Init(); err != nil {\n\t\treturn err\n\t}\n\tglfw.WindowHint(glfw.Visible, glfw.False)\n\tglfw.WindowHint(glfw.Resizable, glfw.False)\n\tglfw.WindowHint(glfw.ContextVersionMajor, 2)\n\tglfw.WindowHint(glfw.ContextVersionMinor, 1)\n\n\t\/\/ As start, create an window with temporary size to create OpenGL context thread.\n\twindow, err := glfw.CreateWindow(16, 16, \"\", nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\thideConsoleWindowOnWindows()\n\tu := &userInterface{\n\t\twindow:      window,\n\t\tfuncs:       make(chan func()),\n\t\tsizeChanged: true,\n\t}\n\tu.window.MakeContextCurrent()\n\tglfw.SwapInterval(1)\n\tcurrentUI = u\n\treturn nil\n}\n\nfunc RunMainThreadLoop(ch <-chan error) error {\n\t\/\/ TODO: Check this is done on the main thread.\n\tcurrentUI.setRunning(true)\n\tdefer func() {\n\t\tcurrentUI.setRunning(false)\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase f := <-currentUI.funcs:\n\t\t\tf()\n\t\tcase err := <-ch:\n\t\t\t\/\/ ch returns a value not only when an error occur but also it is closed.\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc (u *userInterface) isRunning() bool {\n\tu.m.Lock()\n\tdefer u.m.Unlock()\n\treturn u.running\n}\n\nfunc (u *userInterface) setRunning(running bool) {\n\tu.m.Lock()\n\tdefer u.m.Unlock()\n\tu.running = running\n}\n\nfunc (u *userInterface) runOnMainThread(f func() error) error {\n\tif u.funcs == nil {\n\t\t\/\/ already closed\n\t\treturn nil\n\t}\n\tch := make(chan struct{})\n\tvar err error\n\tu.funcs <- func() {\n\t\terr = f()\n\t\tclose(ch)\n\t}\n\t<-ch\n\treturn err\n}\n\nfunc SetScreenSize(width, height int) bool {\n\tu := currentUI\n\tif !u.isRunning() {\n\t\tpanic(\"ui: Run is not called yet\")\n\t}\n\tr := false\n\t_ = u.runOnMainThread(func() error {\n\t\tu.setScreenSize(width, height, u.scale)\n\t\treturn nil\n\t})\n\treturn r\n}\n\nfunc SetScreenScale(scale float64) bool {\n\tu := currentUI\n\tif !u.isRunning() {\n\t\tpanic(\"ui: Run is not called yet\")\n\t}\n\tr := false\n\t_ = u.runOnMainThread(func() error {\n\t\tu.setScreenSize(u.width, u.height, scale)\n\t\treturn nil\n\t})\n\treturn r\n}\n\nfunc ScreenScale() float64 {\n\tu := currentUI\n\tif !u.isRunning() {\n\t\treturn 0\n\t}\n\ts := 0.0\n\t_ = u.runOnMainThread(func() error {\n\t\ts = u.scale\n\t\treturn nil\n\t})\n\treturn s\n}\n\nfunc SetCursorVisibility(visible bool) {\n\t\/\/ This can be called before Run: change the state asyncly.\n\tgo func() {\n\t\t_ = currentUI.runOnMainThread(func() error {\n\t\t\tc := glfw.CursorNormal\n\t\t\tif !visible {\n\t\t\t\tc = glfw.CursorHidden\n\t\t\t}\n\t\t\tcurrentUI.window.SetInputMode(glfw.CursorMode, c)\n\t\t\treturn nil\n\t\t})\n\t}()\n}\n\nfunc Run(width, height int, scale float64, title string, g GraphicsContext) error {\n\tu := currentUI\n\t\/\/ GLContext must be created before setting the screen size, which requires\n\t\/\/ swapping buffers.\n\topengl.Init(currentUI.runOnMainThread)\n\tif err := u.runOnMainThread(func() error {\n\t\tm := glfw.GetPrimaryMonitor()\n\t\tv := m.GetVideoMode()\n\t\tif !u.setScreenSize(width, height, scale) {\n\t\t\treturn errors.New(\"ui: Fail to set the screen size\")\n\t\t}\n\t\tu.window.SetTitle(title)\n\t\tu.window.Show()\n\n\t\tw, h := u.glfwSize()\n\t\tx := (v.Width - w) \/ 2\n\t\ty := (v.Height - h) \/ 3\n\t\tx, y = adjustWindowPosition(x, y)\n\t\tu.window.SetPos(x, y)\n\t\treturn nil\n\t}); err != nil {\n\t\treturn err\n\t}\n\treturn u.loop(g)\n}\n\nfunc (u *userInterface) glfwSize() (int, int) {\n\treturn int(float64(u.width) * u.scale * glfwScale()), int(float64(u.height) * u.scale * glfwScale())\n}\n\nfunc (u *userInterface) actualScreenScale() float64 {\n\tif u.deviceScale == 0 {\n\t\tu.deviceScale = deviceScale()\n\t}\n\treturn u.scale * u.deviceScale\n}\n\nfunc (u *userInterface) pollEvents() {\n\tglfw.PollEvents()\n\tcurrentInput.update(u.window, u.scale*glfwScale())\n}\n\nfunc (u *userInterface) update(g GraphicsContext) error {\n\tshouldClose := false\n\t_ = u.runOnMainThread(func() error {\n\t\tshouldClose = u.window.ShouldClose()\n\t\treturn nil\n\t})\n\tif shouldClose {\n\t\treturn &RegularTermination{}\n\t}\n\n\tactualScale := 0.0\n\t_ = u.runOnMainThread(func() error {\n\t\tif !u.sizeChanged {\n\t\t\treturn nil\n\t\t}\n\t\tu.sizeChanged = false\n\t\tactualScale = u.actualScreenScale()\n\t\treturn nil\n\t})\n\tif 0 < actualScale {\n\t\tg.SetSize(u.width, u.height, actualScale)\n\t}\n\n\t_ = u.runOnMainThread(func() error {\n\t\tu.pollEvents()\n\t\tfor u.window.GetAttrib(glfw.Focused) == 0 {\n\t\t\t\/\/ Wait for an arbitrary period to avoid busy loop.\n\t\t\ttime.Sleep(time.Second \/ 60)\n\t\t\tu.pollEvents()\n\t\t\tif u.window.ShouldClose() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err := g.Update(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (u *userInterface) loop(g GraphicsContext) error {\n\tdefer func() {\n\t\t_ = u.runOnMainThread(func() error {\n\t\t\tglfw.Terminate()\n\t\t\treturn nil\n\t\t})\n\t}()\n\tfor {\n\t\tif err := u.update(g); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ The bound framebuffer must be the default one (0) before swapping buffers.\n\t\tif err := opengl.GetContext().BindScreenFramebuffer(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_ = u.runOnMainThread(func() error {\n\t\t\tu.swapBuffers()\n\t\t\treturn nil\n\t\t})\n\t}\n}\n\nfunc (u *userInterface) swapBuffers() {\n\tu.window.SwapBuffers()\n}\n\nfunc (u *userInterface) setScreenSize(width, height int, scale float64) bool {\n\tif u.width == width && u.height == height && u.scale == scale {\n\t\treturn false\n\t}\n\n\torigScale := u.scale\n\tu.scale = scale\n\n\t\/\/ On Windows, giving a too small width doesn't call a callback (#165).\n\t\/\/ To prevent hanging up, return asap if the width is too small.\n\t\/\/ 252 is an arbitrary number and I guess this is small enough.\n\t\/\/ TODO: The same check should be in ui_js.go\n\tconst minWindowWidth = 252\n\tif int(float64(width)*u.actualScreenScale()) < minWindowWidth {\n\t\tu.scale = origScale\n\t\treturn false\n\t}\n\tu.width = width\n\tu.height = height\n\n\t\/\/ To make sure the current existing framebuffers are rendered,\n\t\/\/ swap buffers here before SetSize is called.\n\tu.swapBuffers()\n\n\tch := make(chan struct{})\n\twindow := u.window\n\twindow.SetFramebufferSizeCallback(func(_ *glfw.Window, width, height int) {\n\t\twindow.SetFramebufferSizeCallback(nil)\n\t\tclose(ch)\n\t})\n\tw, h := u.glfwSize()\n\twindow.SetSize(w, h)\n\nevent:\n\tfor {\n\t\tglfw.PollEvents()\n\t\tselect {\n\t\tcase <-ch:\n\t\t\tbreak event\n\t\tdefault:\n\t\t}\n\t}\n\tu.sizeChanged = true\n\treturn true\n}\n<commit_msg>ui: Avoid recalc the scale factor<commit_after>\/\/ Copyright 2015 Hajime Hoshi\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build darwin freebsd linux windows\n\/\/ +build !js\n\/\/ +build !android\n\/\/ +build !ios\n\npackage ui\n\nimport (\n\t\"errors\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/go-gl\/glfw\/v3.2\/glfw\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/opengl\"\n)\n\ntype userInterface struct {\n\twindow      *glfw.Window\n\twidth       int\n\theight      int\n\tscale       float64\n\tdeviceScale float64\n\tglfwScale   float64\n\tfuncs       chan func()\n\trunning     bool\n\tsizeChanged bool\n\tm           sync.Mutex\n}\n\nvar currentUI *userInterface\n\nfunc init() {\n\tif err := initialize(); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc initialize() error {\n\truntime.LockOSThread()\n\n\tif err := glfw.Init(); err != nil {\n\t\treturn err\n\t}\n\tglfw.WindowHint(glfw.Visible, glfw.False)\n\tglfw.WindowHint(glfw.Resizable, glfw.False)\n\tglfw.WindowHint(glfw.ContextVersionMajor, 2)\n\tglfw.WindowHint(glfw.ContextVersionMinor, 1)\n\n\t\/\/ As start, create an window with temporary size to create OpenGL context thread.\n\twindow, err := glfw.CreateWindow(16, 16, \"\", nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\thideConsoleWindowOnWindows()\n\tu := &userInterface{\n\t\twindow:      window,\n\t\tfuncs:       make(chan func()),\n\t\tsizeChanged: true,\n\t}\n\tu.window.MakeContextCurrent()\n\tglfw.SwapInterval(1)\n\tcurrentUI = u\n\treturn nil\n}\n\nfunc RunMainThreadLoop(ch <-chan error) error {\n\t\/\/ TODO: Check this is done on the main thread.\n\tcurrentUI.setRunning(true)\n\tdefer func() {\n\t\tcurrentUI.setRunning(false)\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase f := <-currentUI.funcs:\n\t\t\tf()\n\t\tcase err := <-ch:\n\t\t\t\/\/ ch returns a value not only when an error occur but also it is closed.\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc (u *userInterface) isRunning() bool {\n\tu.m.Lock()\n\tdefer u.m.Unlock()\n\treturn u.running\n}\n\nfunc (u *userInterface) setRunning(running bool) {\n\tu.m.Lock()\n\tdefer u.m.Unlock()\n\tu.running = running\n}\n\nfunc (u *userInterface) runOnMainThread(f func() error) error {\n\tif u.funcs == nil {\n\t\t\/\/ already closed\n\t\treturn nil\n\t}\n\tch := make(chan struct{})\n\tvar err error\n\tu.funcs <- func() {\n\t\terr = f()\n\t\tclose(ch)\n\t}\n\t<-ch\n\treturn err\n}\n\nfunc SetScreenSize(width, height int) bool {\n\tu := currentUI\n\tif !u.isRunning() {\n\t\tpanic(\"ui: Run is not called yet\")\n\t}\n\tr := false\n\t_ = u.runOnMainThread(func() error {\n\t\tu.setScreenSize(width, height, u.scale)\n\t\treturn nil\n\t})\n\treturn r\n}\n\nfunc SetScreenScale(scale float64) bool {\n\tu := currentUI\n\tif !u.isRunning() {\n\t\tpanic(\"ui: Run is not called yet\")\n\t}\n\tr := false\n\t_ = u.runOnMainThread(func() error {\n\t\tu.setScreenSize(u.width, u.height, scale)\n\t\treturn nil\n\t})\n\treturn r\n}\n\nfunc ScreenScale() float64 {\n\tu := currentUI\n\tif !u.isRunning() {\n\t\treturn 0\n\t}\n\ts := 0.0\n\t_ = u.runOnMainThread(func() error {\n\t\ts = u.scale\n\t\treturn nil\n\t})\n\treturn s\n}\n\nfunc SetCursorVisibility(visible bool) {\n\t\/\/ This can be called before Run: change the state asyncly.\n\tgo func() {\n\t\t_ = currentUI.runOnMainThread(func() error {\n\t\t\tc := glfw.CursorNormal\n\t\t\tif !visible {\n\t\t\t\tc = glfw.CursorHidden\n\t\t\t}\n\t\t\tcurrentUI.window.SetInputMode(glfw.CursorMode, c)\n\t\t\treturn nil\n\t\t})\n\t}()\n}\n\nfunc Run(width, height int, scale float64, title string, g GraphicsContext) error {\n\tu := currentUI\n\t\/\/ GLContext must be created before setting the screen size, which requires\n\t\/\/ swapping buffers.\n\topengl.Init(currentUI.runOnMainThread)\n\tif err := u.runOnMainThread(func() error {\n\t\tm := glfw.GetPrimaryMonitor()\n\t\tv := m.GetVideoMode()\n\t\tif !u.setScreenSize(width, height, scale) {\n\t\t\treturn errors.New(\"ui: Fail to set the screen size\")\n\t\t}\n\t\tu.window.SetTitle(title)\n\t\tu.window.Show()\n\n\t\tw, h := u.glfwSize()\n\t\tx := (v.Width - w) \/ 2\n\t\ty := (v.Height - h) \/ 3\n\t\tx, y = adjustWindowPosition(x, y)\n\t\tu.window.SetPos(x, y)\n\t\treturn nil\n\t}); err != nil {\n\t\treturn err\n\t}\n\treturn u.loop(g)\n}\n\nfunc (u *userInterface) glfwSize() (int, int) {\n\tif u.glfwScale == 0 {\n\t\tu.glfwScale = glfwScale()\n\t}\n\treturn int(float64(u.width) * u.scale * u.glfwScale), int(float64(u.height) * u.scale * u.glfwScale)\n}\n\nfunc (u *userInterface) actualScreenScale() float64 {\n\tif u.deviceScale == 0 {\n\t\tu.deviceScale = deviceScale()\n\t}\n\treturn u.scale * u.deviceScale\n}\n\nfunc (u *userInterface) pollEvents() {\n\tglfw.PollEvents()\n\tif u.glfwScale == 0 {\n\t\tu.glfwScale = glfwScale()\n\t}\n\tcurrentInput.update(u.window, u.scale*u.glfwScale)\n}\n\nfunc (u *userInterface) update(g GraphicsContext) error {\n\tshouldClose := false\n\t_ = u.runOnMainThread(func() error {\n\t\tshouldClose = u.window.ShouldClose()\n\t\treturn nil\n\t})\n\tif shouldClose {\n\t\treturn &RegularTermination{}\n\t}\n\n\tactualScale := 0.0\n\t_ = u.runOnMainThread(func() error {\n\t\tif !u.sizeChanged {\n\t\t\treturn nil\n\t\t}\n\t\tu.sizeChanged = false\n\t\tactualScale = u.actualScreenScale()\n\t\treturn nil\n\t})\n\tif 0 < actualScale {\n\t\tg.SetSize(u.width, u.height, actualScale)\n\t}\n\n\t_ = u.runOnMainThread(func() error {\n\t\tu.pollEvents()\n\t\tfor u.window.GetAttrib(glfw.Focused) == 0 {\n\t\t\t\/\/ Wait for an arbitrary period to avoid busy loop.\n\t\t\ttime.Sleep(time.Second \/ 60)\n\t\t\tu.pollEvents()\n\t\t\tif u.window.ShouldClose() {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err := g.Update(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (u *userInterface) loop(g GraphicsContext) error {\n\tdefer func() {\n\t\t_ = u.runOnMainThread(func() error {\n\t\t\tglfw.Terminate()\n\t\t\treturn nil\n\t\t})\n\t}()\n\tfor {\n\t\tif err := u.update(g); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ The bound framebuffer must be the default one (0) before swapping buffers.\n\t\tif err := opengl.GetContext().BindScreenFramebuffer(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_ = u.runOnMainThread(func() error {\n\t\t\tu.swapBuffers()\n\t\t\treturn nil\n\t\t})\n\t}\n}\n\nfunc (u *userInterface) swapBuffers() {\n\tu.window.SwapBuffers()\n}\n\nfunc (u *userInterface) setScreenSize(width, height int, scale float64) bool {\n\tif u.width == width && u.height == height && u.scale == scale {\n\t\treturn false\n\t}\n\n\torigScale := u.scale\n\tu.scale = scale\n\n\t\/\/ On Windows, giving a too small width doesn't call a callback (#165).\n\t\/\/ To prevent hanging up, return asap if the width is too small.\n\t\/\/ 252 is an arbitrary number and I guess this is small enough.\n\t\/\/ TODO: The same check should be in ui_js.go\n\tconst minWindowWidth = 252\n\tif int(float64(width)*u.actualScreenScale()) < minWindowWidth {\n\t\tu.scale = origScale\n\t\treturn false\n\t}\n\tu.width = width\n\tu.height = height\n\n\t\/\/ To make sure the current existing framebuffers are rendered,\n\t\/\/ swap buffers here before SetSize is called.\n\tu.swapBuffers()\n\n\tch := make(chan struct{})\n\twindow := u.window\n\twindow.SetFramebufferSizeCallback(func(_ *glfw.Window, width, height int) {\n\t\twindow.SetFramebufferSizeCallback(nil)\n\t\tclose(ch)\n\t})\n\tw, h := u.glfwSize()\n\twindow.SetSize(w, h)\n\nevent:\n\tfor {\n\t\tglfw.PollEvents()\n\t\tselect {\n\t\tcase <-ch:\n\t\t\tbreak event\n\t\tdefault:\n\t\t}\n\t}\n\tu.sizeChanged = true\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>package gettext\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nconst (\n\tDEFAULT_LANGUAGE = \"en\"\n)\n\ntype Collection struct {\n\tcatalogs        map[string]*Catalog\n\tdefaultLanguage string\n}\n\nfunc NewCollection() *Collection {\n\treturn &Collection{\n\t\tcatalogs:        map[string]*Catalog{},\n\t\tdefaultLanguage: \"en\",\n\t}\n}\n\nfunc (c *Collection) LoadDirectory(path string) error {\n\tdirectoryPath := fmt.Sprintf(\"%s%s*.mo\", path, string(os.PathSeparator))\n\tfiles, err := filepath.Glob(directoryPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.catalogs = make(map[string]*Catalog, 0)\n\n\tfor _, fileName := range files {\n\t\tlanguage := strings.ToLower(fmt.Sprintf(strings.TrimSuffix(fileName, filepath.Ext(fileName))))\n\n\t\tfilePath := fmt.Sprintf(\"%s%s%s\", path, string(os.PathSeparator), fileName)\n\t\tfileBytes, err := ioutil.ReadFile(filePath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcatalog := NewCatalog()\n\t\tif err := catalog.ReadMo(bytes.NewReader(fileBytes)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.catalogs[language] = catalog\n\t}\n\n\treturn nil\n}\n\nfunc (c *Collection) SetDefaultLanguage(langCode string) {\n\tc.defaultLanguage = langCode\n}\n\nfunc (c *Collection) Get(langCode string) *Catalog {\n\tlangCode = strings.ToLower(langCode)\n\tcatalog, ok := c.catalogs[langCode]\n\tif ok {\n\t\treturn catalog\n\t}\n\n\tcatalog, ok = c.catalogs[strings.Split(langCode, \"-\")[0]]\n\tif ok {\n\t\treturn catalog\n\t}\n\n\tcatalog, ok = c.catalogs[c.defaultLanguage]\n\tif ok {\n\t\treturn catalog\n\t}\n\n\treturn NewCatalog()\n}\n<commit_msg>Fix file retrieve from directories<commit_after>package gettext\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nconst (\n\tDEFAULT_LANGUAGE = \"en\"\n)\n\ntype Collection struct {\n\tcatalogs        map[string]*Catalog\n\tdefaultLanguage string\n}\n\nfunc NewCollection() *Collection {\n\treturn &Collection{\n\t\tcatalogs:        map[string]*Catalog{},\n\t\tdefaultLanguage: \"en\",\n\t}\n}\n\nfunc (c *Collection) LoadDirectory(path string) error {\n\tdirectoryPath := fmt.Sprintf(\"%s%s*.mo\", path, string(os.PathSeparator))\n\tfiles, err := filepath.Glob(directoryPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.catalogs = make(map[string]*Catalog, 0)\n\n\tfor _, fileName := range files {\n\t\tlanguage := strings.ToLower(fmt.Sprintf(strings.TrimSuffix(filepath.Base(fileName), filepath.Ext(fileName))))\n\n\t\tfilePath := fmt.Sprintf(\"%s\", fileName)\n\t\tfmt.Println(language, \"->\", filePath)\n\t\tfileBytes, err := ioutil.ReadFile(filePath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcatalog := NewCatalog()\n\t\tif err := catalog.ReadMo(bytes.NewReader(fileBytes)); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.catalogs[language] = catalog\n\t}\n\n\treturn nil\n}\n\nfunc (c *Collection) SetDefaultLanguage(langCode string) {\n\tc.defaultLanguage = langCode\n}\n\nfunc (c *Collection) Get(langCode string) *Catalog {\n\tlangCode = strings.ToLower(langCode)\n\tcatalog, ok := c.catalogs[langCode]\n\tif ok {\n\t\treturn catalog\n\t}\n\n\tcatalog, ok = c.catalogs[strings.Split(langCode, \"-\")[0]]\n\tif ok {\n\t\treturn catalog\n\t}\n\n\tcatalog, ok = c.catalogs[c.defaultLanguage]\n\tif ok {\n\t\treturn catalog\n\t}\n\n\treturn NewCatalog()\n}\n<|endoftext|>"}
{"text":"<commit_before>package imagectl\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"github.com\/coreos\/go-systemd\/unit\"\n\tsystemd \"github.com\/coreos\/go-systemd\/dbus\"\n)\n\nfunc setupMount(sd *systemd.Conn, what, where, fstype, options string) error {\n\t\/\/ mount -t $type -o$options $what $where\n\n\tsdname := unit.UnitNamePathEscape(where)\n\tsdfile := \"[Mount]\\nWhat=\" + what + \"\\nWhere=\" + where + \"\\nType=\" + fstype + \"\\nOptions=\" + options + \"\\n\"\n\tsdauto := \"[Automount]\\nWhere=\" + where + \"\\n\\n[Install]\\nWantedBy=local-fs.target\\n\"\n\n\tif err := ioutil.WriteFile(\"\/etc\/systemd\/system\/\" + sdname + \".mount\", []byte(sdfile), 0644); err != nil {\n\t\treturn err\n\t}\n\tif err := ioutil.WriteFile(\"\/etc\/systemd\/system\/\" + sdname + \".automount\", []byte(sdauto), 0644); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sd.Reload(); err != nil {\n\t\treturn err\n\t}\n\n\tpossible, _, err := sd.EnableUnitFiles([]string{sdname + \".automount\"}, false, false)\n\tif !possible {\n\t\treturn errors.New(\"Internal error: Auto-generated \" + sdname + \".automount does not have an [Install] section.\")\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = sd.StartUnit(sdname + \".automount\", \"replace\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc destroyMount(sd *systemd.Conn, where string) error {\n\tsdname := unit.UnitNamePathEscape(where)\n\n\t_, err := sd.StopUnit(sdname + \".automount\", \"replace\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = sd.DisableUnitFiles([]string{sdname + \".automount\"}, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := os.Remove(\"\/etc\/systemd\/system\/\" + sdname + \".mount\"); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Remove(\"\/etc\/systemd\/system\/\" + sdname + \".automount\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sd.Reload(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc setupMountOverlay(sd *systemd.Conn, whatRo []string, whatRW, where string) error {\n\tif err := os.MkdirAll(\"\/var\/lib\/image-layers\/.work\", 0700); err != nil {\n\t\treturn err\n\t}\n\n\tif whatRW == \"\" {\n\t\tswitch len(whatRo) {\n\t\t\tcase 0:\n\t\t\t\treturn setupMount(sd, \"tmpfs\", where, \"tmpfs\", \"ro\")\n\t\t\tcase 1:\n\t\t\t\treturn setupMount(sd, whatRo[0], where, \"none\", \"bind,ro\") \/\/ Note: ro probably doesn't work\n\t\t\tdefault:\n\t\t\t\treturn setupMount(sd, \"overlay\", where, \"overlay\", \"lowerdir=\" + strings.Join(whatRo, \":\"))\n\t\t}\n\t} else {\n\t\tswitch len(whatRo) {\n\t\t\tcase 0:\n\t\t\t\treturn setupMount(sd, whatRW, where, \"none\", \"bind\")\n\t\t\tdefault:\n\t\t\t\treturn setupMount(sd, \"overlay\", where, \"overlay\", \"lowerdir=\" + strings.Join(whatRo, \":\") + \",upperdir=\" + whatRW + \",workdir=\/var\/lib\/image-layers\/.work\")\n\t\t}\n\t}\n}\n\nfunc doUnitOperation(op func(name, mode string, ch chan<- string) (int, error), name, mode string) error {\n\tdone := make(chan string)\n\t_, err := op(name, mode, done)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresult := <-done\n\tif result != \"done\" {\n\t\treturn errors.New(result)\n\t}\n\n\treturn nil\n}\n\nfunc mount(sd *systemd.Conn, where string) error {\n\tsdname := unit.UnitNamePathEscape(where)\n\treturn doUnitOperation(sd.StartUnit, sdname + \".mount\", \"replace\")\n}\n\nfunc remount(sd *systemd.Conn, where string) error {\n\tsdname := unit.UnitNamePathEscape(where)\n\treturn doUnitOperation(sd.RestartUnit, sdname + \".mount\", \"replace\")\n}\n\nfunc umount(sd *systemd.Conn, where string) error {\n\tsdname := unit.UnitNamePathEscape(where)\n\treturn doUnitOperation(sd.StopUnit, sdname + \".mount\", \"replace\")\n}\n<commit_msg>imagectl: Fix the order of lower dirs.<commit_after>package imagectl\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"github.com\/coreos\/go-systemd\/unit\"\n\tsystemd \"github.com\/coreos\/go-systemd\/dbus\"\n)\n\nfunc setupMount(sd *systemd.Conn, what, where, fstype, options string) error {\n\t\/\/ mount -t $type -o$options $what $where\n\n\tsdname := unit.UnitNamePathEscape(where)\n\tsdfile := \"[Mount]\\nWhat=\" + what + \"\\nWhere=\" + where + \"\\nType=\" + fstype + \"\\nOptions=\" + options + \"\\n\"\n\tsdauto := \"[Automount]\\nWhere=\" + where + \"\\n\\n[Install]\\nWantedBy=local-fs.target\\n\"\n\n\tif err := ioutil.WriteFile(\"\/etc\/systemd\/system\/\" + sdname + \".mount\", []byte(sdfile), 0644); err != nil {\n\t\treturn err\n\t}\n\tif err := ioutil.WriteFile(\"\/etc\/systemd\/system\/\" + sdname + \".automount\", []byte(sdauto), 0644); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sd.Reload(); err != nil {\n\t\treturn err\n\t}\n\n\tpossible, _, err := sd.EnableUnitFiles([]string{sdname + \".automount\"}, false, false)\n\tif !possible {\n\t\treturn errors.New(\"Internal error: Auto-generated \" + sdname + \".automount does not have an [Install] section.\")\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = sd.StartUnit(sdname + \".automount\", \"replace\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc destroyMount(sd *systemd.Conn, where string) error {\n\tsdname := unit.UnitNamePathEscape(where)\n\n\t_, err := sd.StopUnit(sdname + \".automount\", \"replace\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = sd.DisableUnitFiles([]string{sdname + \".automount\"}, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := os.Remove(\"\/etc\/systemd\/system\/\" + sdname + \".mount\"); err != nil {\n\t\treturn err\n\t}\n\tif err := os.Remove(\"\/etc\/systemd\/system\/\" + sdname + \".automount\"); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sd.Reload(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc setupMountOverlay(sd *systemd.Conn, whatRo []string, whatRW, where string) error {\n\tif err := os.MkdirAll(\"\/var\/lib\/image-layers\/.work\", 0700); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ I guess overlayfs was designed in Australia.\n\twhatRoReversed := make([]string, 0, len(whatRo))\n\tfor i := len(whatRo)-1; i >= 0; i-- {\n\t\twhatRoReversed = append(whatRoReversed, whatRo[i])\n\t}\n\twhatRo = whatRoReversed\n\n\tif whatRW == \"\" {\n\t\tswitch len(whatRo) {\n\t\t\tcase 0:\n\t\t\t\treturn setupMount(sd, \"tmpfs\", where, \"tmpfs\", \"ro\")\n\t\t\tcase 1:\n\t\t\t\treturn setupMount(sd, whatRo[0], where, \"none\", \"bind,ro\") \/\/ Note: ro probably doesn't work\n\t\t\tdefault:\n\t\t\t\treturn setupMount(sd, \"overlay\", where, \"overlay\", \"lowerdir=\" + strings.Join(whatRo, \":\"))\n\t\t}\n\t} else {\n\t\tswitch len(whatRo) {\n\t\t\tcase 0:\n\t\t\t\treturn setupMount(sd, whatRW, where, \"none\", \"bind\")\n\t\t\tdefault:\n\t\t\t\treturn setupMount(sd, \"overlay\", where, \"overlay\", \"lowerdir=\" + strings.Join(whatRo, \":\") + \",upperdir=\" + whatRW + \",workdir=\/var\/lib\/image-layers\/.work\")\n\t\t}\n\t}\n}\n\nfunc doUnitOperation(op func(name, mode string, ch chan<- string) (int, error), name, mode string) error {\n\tdone := make(chan string)\n\t_, err := op(name, mode, done)\n\tif err != nil {\n\t\treturn err\n\t}\n\tresult := <-done\n\tif result != \"done\" {\n\t\treturn errors.New(result)\n\t}\n\n\treturn nil\n}\n\nfunc mount(sd *systemd.Conn, where string) error {\n\tsdname := unit.UnitNamePathEscape(where)\n\treturn doUnitOperation(sd.StartUnit, sdname + \".mount\", \"replace\")\n}\n\nfunc remount(sd *systemd.Conn, where string) error {\n\tsdname := unit.UnitNamePathEscape(where)\n\treturn doUnitOperation(sd.RestartUnit, sdname + \".mount\", \"replace\")\n}\n\nfunc umount(sd *systemd.Conn, where string) error {\n\tsdname := unit.UnitNamePathEscape(where)\n\treturn doUnitOperation(sd.StopUnit, sdname + \".mount\", \"replace\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build windows\n\npackage main\n\nimport (\n\t\"crypto\/md5\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\t\"unicode\/utf16\"\n\t\"unsafe\"\n\n\t\"golang.org\/x\/sys\/windows\/registry\"\n\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/mackerelio\/checkers\"\n\t\"github.com\/mackerelio\/go-check-plugins\/check-windows-eventlog\/internal\/eventlog\"\n)\n\nconst (\n\terrorInvalidParameter = syscall.Errno(87)\n)\n\ntype logOpts struct {\n\tLog            string `long:\"log\" description:\"Event Names (comma separated)\"`\n\tType           string `long:\"type\" description:\"Event Types (comma separated)\"`\n\tSourcePattern  string `long:\"source-pattern\" description:\"Event Source (regexp pattern)\"`\n\tMessagePattern string `long:\"message-pattern\" description:\"Message Pattern (regexp pattern)\"`\n\tWarnOver       int64  `short:\"w\" long:\"warning-over\" description:\"Trigger a warning if matched lines is over a number\"`\n\tCritOver       int64  `short:\"c\" long:\"critical-over\" description:\"Trigger a critical if matched lines is over a number\"`\n\tReturnContent  bool   `short:\"r\" long:\"return\" description:\"Return matched line\"`\n\tStateDir       string `short:\"s\" long:\"state-dir\" default:\"\/var\/mackerel-cache\/check-windows-eventlog\" value-name:\"DIR\" description:\"Dir to keep state files under\"`\n\tNoState        bool   `long:\"no-state\" description:\"Don't use state file and read whole logs\"`\n\tFailFirst      bool   `long:\"fail-first\" description:\"Count errors on first seek\"`\n\tVerbose        bool   `long:\"verbose\" description:\"Verbose output\"`\n\n\tlogList        []string\n\ttypeList       []string\n\tsourcePattern  *regexp.Regexp\n\tmessagePattern *regexp.Regexp\n\torigArgs       []string\n}\n\nfunc stringList(s string) []string {\n\tl := strings.Split(s, \",\")\n\tif len(l) == 0 || l[0] == \"\" {\n\t\treturn []string{}\n\t}\n\treturn l\n}\n\nfunc (opts *logOpts) prepare() error {\n\topts.logList = stringList(opts.Log)\n\tif len(opts.logList) == 0 || opts.logList[0] == \"\" {\n\t\topts.logList = []string{\"Application\"}\n\t}\n\topts.typeList = stringList(opts.Type)\n\n\tvar err error\n\topts.sourcePattern, err = regexp.Compile(opts.SourcePattern)\n\tif err != nil {\n\t\treturn err\n\t}\n\topts.messagePattern, err = regexp.Compile(opts.MessagePattern)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tckr := run(os.Args[1:])\n\tckr.Name = \"Event Log\"\n\tckr.Exit()\n}\n\nfunc parseArgs(args []string) (*logOpts, error) {\n\torigArgs := make([]string, len(args))\n\tcopy(origArgs, args)\n\topts := &logOpts{}\n\t_, err := flags.ParseArgs(opts, args)\n\tif opts.StateDir == \"\" {\n\t\tworkdir := os.Getenv(\"MACKEREL_PLUGIN_WORKDIR\")\n\t\tif workdir == \"\" {\n\t\t\tworkdir = os.TempDir()\n\t\t}\n\t\topts.StateDir = filepath.Join(workdir, \"check-windows-eventlog\")\n\t}\n\topts.origArgs = origArgs\n\treturn opts, err\n}\n\nfunc run(args []string) *checkers.Checker {\n\topts, err := parseArgs(args)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\terr = opts.prepare()\n\tif err != nil {\n\t\treturn checkers.Unknown(err.Error())\n\t}\n\n\tcheckSt := checkers.OK\n\twarnNum := int64(0)\n\tcritNum := int64(0)\n\terrorOverall := \"\"\n\n\tfor _, lt := range opts.logList {\n\t\tw, c, errLines, err := opts.searchLog(lt)\n\t\tif err != nil {\n\t\t\treturn checkers.Unknown(err.Error())\n\t\t}\n\t\twarnNum += w\n\t\tcritNum += c\n\t\tif opts.ReturnContent {\n\t\t\terrorOverall += errLines\n\t\t}\n\t}\n\tmsg := fmt.Sprintf(\"%d warnings, %d criticals.\", warnNum, critNum)\n\tif errorOverall != \"\" {\n\t\tmsg += \"\\n\" + errorOverall\n\t}\n\tif warnNum > opts.WarnOver {\n\t\tcheckSt = checkers.WARNING\n\t}\n\tif critNum > opts.CritOver {\n\t\tcheckSt = checkers.CRITICAL\n\t}\n\treturn checkers.NewChecker(checkSt, msg)\n}\n\nfunc bytesToString(b []byte) (string, uint32) {\n\tvar i int\n\ts := make([]uint16, len(b)\/2)\n\tfor i = range s {\n\t\ts[i] = uint16(b[i*2]) + uint16(b[(i*2)+1])<<8\n\t\tif s[i] == 0 {\n\t\t\ts = s[0:i]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn string(utf16.Decode(s)), uint32(i * 2)\n}\n\nfunc getResourceMessage(providerName, sourceName string, eventID uint32, argsptr uintptr) (string, error) {\n\tregkey := fmt.Sprintf(\n\t\t\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\EventLog\\\\%s\\\\%s\",\n\t\tproviderName, sourceName)\n\tkey, err := registry.OpenKey(registry.LOCAL_MACHINE, regkey, registry.QUERY_VALUE)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer key.Close()\n\n\tval, _, err := key.GetStringValue(\"EventMessageFile\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tval, err = registry.ExpandString(val)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thandle, err := eventlog.LoadLibraryEx(syscall.StringToUTF16Ptr(val), 0,\n\t\teventlog.DONT_RESOLVE_DLL_REFERENCES|eventlog.LOAD_LIBRARY_AS_DATAFILE)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer syscall.CloseHandle(handle)\n\n\tmsgbuf := make([]byte, 1<<16)\n\tnumChars, err := eventlog.FormatMessage(\n\t\tsyscall.FORMAT_MESSAGE_FROM_SYSTEM|\n\t\t\tsyscall.FORMAT_MESSAGE_FROM_HMODULE|\n\t\t\tsyscall.FORMAT_MESSAGE_ARGUMENT_ARRAY,\n\t\thandle,\n\t\teventID,\n\t\t0,\n\t\t&msgbuf[0],\n\t\tuint32(len(msgbuf)),\n\t\targsptr)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tmessage, _ := bytesToString(msgbuf[:numChars*2])\n\tmessage = strings.Replace(message, \"\\r\", \"\", -1)\n\tmessage = strings.TrimSuffix(message, \"\\n\")\n\treturn message, nil\n}\n\nfunc (opts *logOpts) searchLog(logName string) (warnNum, critNum int64, errLines string, err error) {\n\tstateFile := opts.getStateFile(logName)\n\trecordNumber := uint32(0)\n\tif !opts.NoState {\n\t\ts, err := getLastOffset(stateFile)\n\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\treturn 0, 0, \"\", err\n\t\t}\n\t\trecordNumber = uint32(s)\n\t}\n\n\tptr := syscall.StringToUTF16Ptr(logName)\n\th, err := eventlog.OpenEventLog(nil, ptr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer eventlog.CloseEventLog(h)\n\n\tvar num, oldnum, lastNumber uint32\n\n\teventlog.GetNumberOfEventLogRecords(h, &num)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\teventlog.GetOldestEventLogRecord(h, &oldnum)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif recordNumber == 0 {\n\t\tif !opts.NoState && !opts.FailFirst {\n\t\t\terr = writeLastOffset(stateFile, int64(oldnum+num-1))\n\t\t\treturn 0, 0, \"\", err\n\t\t}\n\t}\n\n\tif oldnum <= recordNumber {\n\t\tif recordNumber == oldnum+num-1 {\n\t\t\treturn 0, 0, \"\", nil\n\t\t}\n\t\tlastNumber = recordNumber\n\t\trecordNumber++\n\t} else {\n\t\trecordNumber = oldnum\n\t}\n\n\tsize := uint32(1)\n\tbuf := []byte{0}\n\n\tvar readBytes uint32\n\tvar nextSize uint32\n\tfor i := recordNumber; i < oldnum+num; i++ {\n\t\tflags := eventlog.EVENTLOG_FORWARDS_READ | eventlog.EVENTLOG_SEEK_READ\n\t\tif i == 0 {\n\t\t\tflags = eventlog.EVENTLOG_FORWARDS_READ | eventlog.EVENTLOG_SEQUENTIAL_READ\n\t\t}\n\n\t\terr = eventlog.ReadEventLog(\n\t\t\th,\n\t\t\tflags,\n\t\t\ti,\n\t\t\t&buf[0],\n\t\t\tsize,\n\t\t\t&readBytes,\n\t\t\t&nextSize)\n\t\tif err != nil {\n\t\t\tif err != syscall.ERROR_INSUFFICIENT_BUFFER {\n\t\t\t\tif err != errorInvalidParameter {\n\t\t\t\t\treturn 0, 0, \"\", err\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbuf = make([]byte, nextSize)\n\t\t\tsize = nextSize\n\t\t\terr = eventlog.ReadEventLog(\n\t\t\t\th,\n\t\t\t\tflags,\n\t\t\t\ti,\n\t\t\t\t&buf[0],\n\t\t\t\tsize,\n\t\t\t\t&readBytes,\n\t\t\t\t&nextSize)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"eventlog.ReadEventLog: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tr := *(*eventlog.EVENTLOGRECORD)(unsafe.Pointer(&buf[0]))\n\t\tif opts.Verbose {\n\t\t\tlog.Printf(\"RecordNumber=%v\", r.RecordNumber)\n\t\t\tlog.Printf(\"TimeGenerated=%v\", time.Unix(int64(r.TimeGenerated), 0).String())\n\t\t\tlog.Printf(\"TimeWritten=%v\", time.Unix(int64(r.TimeWritten), 0).String())\n\t\t\tlog.Printf(\"EventID=%v\", r.EventID)\n\t\t}\n\t\tlastNumber = r.RecordNumber\n\n\t\ttn := eventlog.EventType(r.EventType).String()\n\t\tif opts.Verbose {\n\t\t\tlog.Printf(\"EventType=%v\", tn)\n\t\t}\n\t\tif len(opts.typeList) > 0 {\n\t\t\tfound := false\n\t\t\tfor _, typ := range opts.typeList {\n\t\t\t\tif typ == tn {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tsourceName, sourceNameOff := bytesToString(buf[unsafe.Sizeof(eventlog.EVENTLOGRECORD{}):])\n\t\tcomputerName, _ := bytesToString(buf[unsafe.Sizeof(eventlog.EVENTLOGRECORD{})+uintptr(sourceNameOff+2):])\n\t\tif opts.Verbose {\n\t\t\tlog.Printf(\"SourceName=%v\", sourceName)\n\t\t\tlog.Printf(\"ComputerName=%v\", computerName)\n\t\t}\n\n\t\tif opts.sourcePattern != nil {\n\t\t\tif !opts.sourcePattern.MatchString(sourceName) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\toff := uint32(0)\n\t\targs := make([]*byte, uintptr(r.NumStrings)*unsafe.Sizeof((*uint16)(nil)))\n\t\tfor n := 0; n < int(r.NumStrings); n++ {\n\t\t\targs[n] = &buf[r.StringOffset+off]\n\t\t\t_, boff := bytesToString(buf[r.StringOffset+off:])\n\t\t\toff += boff + 2\n\t\t}\n\n\t\tvar argsptr uintptr\n\t\tif r.NumStrings > 0 {\n\t\t\targsptr = uintptr(unsafe.Pointer(&args[0]))\n\t\t}\n\t\tmessage, err := getResourceMessage(logName, sourceName, r.EventID, argsptr)\n\t\tif err == nil {\n\t\t\tif opts.Verbose {\n\t\t\t\tlog.Printf(\"Message=%v\", message)\n\t\t\t}\n\t\t\tif opts.messagePattern != nil {\n\t\t\t\tif !opts.messagePattern.MatchString(message) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif opts.ReturnContent {\n\t\t\terrLines += sourceName + \":\" + strings.Replace(message, \"\\n\", \"\", -1) + \"\\n\"\n\t\t}\n\t\tswitch tn {\n\t\tcase \"Error\":\n\t\t\tcritNum++\n\t\tcase \"Audit Failure\":\n\t\t\tcritNum++\n\t\tcase \"Warning\":\n\t\t\twarnNum++\n\t\t}\n\t}\n\n\tif !opts.NoState {\n\t\terr = writeLastOffset(stateFile, int64(lastNumber))\n\t\tif err != nil {\n\t\t\tlog.Printf(\"writeLastOffset failed: %s\\n\", err.Error())\n\t\t}\n\t}\n\n\tif recordNumber == 0 && !opts.FailFirst {\n\t\treturn 0, 0, \"\", nil\n\t}\n\treturn warnNum, critNum, errLines, nil\n}\n\nvar stateRe = regexp.MustCompile(`^([A-Z]):[\/\\\\]`)\n\nfunc (opts *logOpts) getStateFile(logName string) string {\n\treturn filepath.Join(\n\t\topts.StateDir,\n\t\tfmt.Sprintf(\n\t\t\t\"%s-%x\",\n\t\t\tstateRe.ReplaceAllString(logName, `$1`+string(filepath.Separator)),\n\t\t\tmd5.Sum([]byte(strings.Join(opts.origArgs, \" \"))),\n\t\t),\n\t)\n}\n\nfunc getLastOffset(f string) (int64, error) {\n\t_, err := os.Stat(f)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tb, err := ioutil.ReadFile(f)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ti, err := strconv.ParseInt(strings.Trim(string(b), \" \\r\\n\"), 10, 64)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn i, nil\n}\n\nfunc writeLastOffset(f string, num int64) error {\n\terr := os.MkdirAll(filepath.Dir(f), 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(f, []byte(fmt.Sprintf(\"%d\", num)), 0644)\n}\n<commit_msg>don't look err for getResourceMessage<commit_after>\/\/ +build windows\n\npackage main\n\nimport (\n\t\"crypto\/md5\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\t\"unicode\/utf16\"\n\t\"unsafe\"\n\n\t\"golang.org\/x\/sys\/windows\/registry\"\n\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/mackerelio\/checkers\"\n\t\"github.com\/mackerelio\/go-check-plugins\/check-windows-eventlog\/internal\/eventlog\"\n)\n\nconst (\n\terrorInvalidParameter = syscall.Errno(87)\n)\n\ntype logOpts struct {\n\tLog            string `long:\"log\" description:\"Event Names (comma separated)\"`\n\tType           string `long:\"type\" description:\"Event Types (comma separated)\"`\n\tSourcePattern  string `long:\"source-pattern\" description:\"Event Source (regexp pattern)\"`\n\tMessagePattern string `long:\"message-pattern\" description:\"Message Pattern (regexp pattern)\"`\n\tWarnOver       int64  `short:\"w\" long:\"warning-over\" description:\"Trigger a warning if matched lines is over a number\"`\n\tCritOver       int64  `short:\"c\" long:\"critical-over\" description:\"Trigger a critical if matched lines is over a number\"`\n\tReturnContent  bool   `short:\"r\" long:\"return\" description:\"Return matched line\"`\n\tStateDir       string `short:\"s\" long:\"state-dir\" default:\"\/var\/mackerel-cache\/check-windows-eventlog\" value-name:\"DIR\" description:\"Dir to keep state files under\"`\n\tNoState        bool   `long:\"no-state\" description:\"Don't use state file and read whole logs\"`\n\tFailFirst      bool   `long:\"fail-first\" description:\"Count errors on first seek\"`\n\tVerbose        bool   `long:\"verbose\" description:\"Verbose output\"`\n\n\tlogList        []string\n\ttypeList       []string\n\tsourcePattern  *regexp.Regexp\n\tmessagePattern *regexp.Regexp\n\torigArgs       []string\n}\n\nfunc stringList(s string) []string {\n\tl := strings.Split(s, \",\")\n\tif len(l) == 0 || l[0] == \"\" {\n\t\treturn []string{}\n\t}\n\treturn l\n}\n\nfunc (opts *logOpts) prepare() error {\n\topts.logList = stringList(opts.Log)\n\tif len(opts.logList) == 0 || opts.logList[0] == \"\" {\n\t\topts.logList = []string{\"Application\"}\n\t}\n\topts.typeList = stringList(opts.Type)\n\n\tvar err error\n\topts.sourcePattern, err = regexp.Compile(opts.SourcePattern)\n\tif err != nil {\n\t\treturn err\n\t}\n\topts.messagePattern, err = regexp.Compile(opts.MessagePattern)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tckr := run(os.Args[1:])\n\tckr.Name = \"Event Log\"\n\tckr.Exit()\n}\n\nfunc parseArgs(args []string) (*logOpts, error) {\n\torigArgs := make([]string, len(args))\n\tcopy(origArgs, args)\n\topts := &logOpts{}\n\t_, err := flags.ParseArgs(opts, args)\n\tif opts.StateDir == \"\" {\n\t\tworkdir := os.Getenv(\"MACKEREL_PLUGIN_WORKDIR\")\n\t\tif workdir == \"\" {\n\t\t\tworkdir = os.TempDir()\n\t\t}\n\t\topts.StateDir = filepath.Join(workdir, \"check-windows-eventlog\")\n\t}\n\topts.origArgs = origArgs\n\treturn opts, err\n}\n\nfunc run(args []string) *checkers.Checker {\n\topts, err := parseArgs(args)\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\terr = opts.prepare()\n\tif err != nil {\n\t\treturn checkers.Unknown(err.Error())\n\t}\n\n\tcheckSt := checkers.OK\n\twarnNum := int64(0)\n\tcritNum := int64(0)\n\terrorOverall := \"\"\n\n\tfor _, lt := range opts.logList {\n\t\tw, c, errLines, err := opts.searchLog(lt)\n\t\tif err != nil {\n\t\t\treturn checkers.Unknown(err.Error())\n\t\t}\n\t\twarnNum += w\n\t\tcritNum += c\n\t\tif opts.ReturnContent {\n\t\t\terrorOverall += errLines\n\t\t}\n\t}\n\tmsg := fmt.Sprintf(\"%d warnings, %d criticals.\", warnNum, critNum)\n\tif errorOverall != \"\" {\n\t\tmsg += \"\\n\" + errorOverall\n\t}\n\tif warnNum > opts.WarnOver {\n\t\tcheckSt = checkers.WARNING\n\t}\n\tif critNum > opts.CritOver {\n\t\tcheckSt = checkers.CRITICAL\n\t}\n\treturn checkers.NewChecker(checkSt, msg)\n}\n\nfunc bytesToString(b []byte) (string, uint32) {\n\tvar i int\n\ts := make([]uint16, len(b)\/2)\n\tfor i = range s {\n\t\ts[i] = uint16(b[i*2]) + uint16(b[(i*2)+1])<<8\n\t\tif s[i] == 0 {\n\t\t\ts = s[0:i]\n\t\t\tbreak\n\t\t}\n\t}\n\treturn string(utf16.Decode(s)), uint32(i * 2)\n}\n\nfunc getResourceMessage(providerName, sourceName string, eventID uint32, argsptr uintptr) (string, error) {\n\tregkey := fmt.Sprintf(\n\t\t\"SYSTEM\\\\CurrentControlSet\\\\Services\\\\EventLog\\\\%s\\\\%s\",\n\t\tproviderName, sourceName)\n\tkey, err := registry.OpenKey(registry.LOCAL_MACHINE, regkey, registry.QUERY_VALUE)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer key.Close()\n\n\tval, _, err := key.GetStringValue(\"EventMessageFile\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tval, err = registry.ExpandString(val)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\thandle, err := eventlog.LoadLibraryEx(syscall.StringToUTF16Ptr(val), 0,\n\t\teventlog.DONT_RESOLVE_DLL_REFERENCES|eventlog.LOAD_LIBRARY_AS_DATAFILE)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer syscall.CloseHandle(handle)\n\n\tmsgbuf := make([]byte, 1<<16)\n\tnumChars, err := eventlog.FormatMessage(\n\t\tsyscall.FORMAT_MESSAGE_FROM_SYSTEM|\n\t\t\tsyscall.FORMAT_MESSAGE_FROM_HMODULE|\n\t\t\tsyscall.FORMAT_MESSAGE_ARGUMENT_ARRAY,\n\t\thandle,\n\t\teventID,\n\t\t0,\n\t\t&msgbuf[0],\n\t\tuint32(len(msgbuf)),\n\t\targsptr)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tmessage, _ := bytesToString(msgbuf[:numChars*2])\n\tmessage = strings.Replace(message, \"\\r\", \"\", -1)\n\tmessage = strings.TrimSuffix(message, \"\\n\")\n\treturn message, nil\n}\n\nfunc (opts *logOpts) searchLog(logName string) (warnNum, critNum int64, errLines string, err error) {\n\tstateFile := opts.getStateFile(logName)\n\trecordNumber := uint32(0)\n\tif !opts.NoState {\n\t\ts, err := getLastOffset(stateFile)\n\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\treturn 0, 0, \"\", err\n\t\t}\n\t\trecordNumber = uint32(s)\n\t}\n\n\tptr := syscall.StringToUTF16Ptr(logName)\n\th, err := eventlog.OpenEventLog(nil, ptr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer eventlog.CloseEventLog(h)\n\n\tvar num, oldnum, lastNumber uint32\n\n\teventlog.GetNumberOfEventLogRecords(h, &num)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\teventlog.GetOldestEventLogRecord(h, &oldnum)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif recordNumber == 0 {\n\t\tif !opts.NoState && !opts.FailFirst {\n\t\t\terr = writeLastOffset(stateFile, int64(oldnum+num-1))\n\t\t\treturn 0, 0, \"\", err\n\t\t}\n\t}\n\n\tif oldnum <= recordNumber {\n\t\tif recordNumber == oldnum+num-1 {\n\t\t\treturn 0, 0, \"\", nil\n\t\t}\n\t\tlastNumber = recordNumber\n\t\trecordNumber++\n\t} else {\n\t\trecordNumber = oldnum\n\t}\n\n\tsize := uint32(1)\n\tbuf := []byte{0}\n\n\tvar readBytes uint32\n\tvar nextSize uint32\n\tfor i := recordNumber; i < oldnum+num; i++ {\n\t\tflags := eventlog.EVENTLOG_FORWARDS_READ | eventlog.EVENTLOG_SEEK_READ\n\t\tif i == 0 {\n\t\t\tflags = eventlog.EVENTLOG_FORWARDS_READ | eventlog.EVENTLOG_SEQUENTIAL_READ\n\t\t}\n\n\t\terr = eventlog.ReadEventLog(\n\t\t\th,\n\t\t\tflags,\n\t\t\ti,\n\t\t\t&buf[0],\n\t\t\tsize,\n\t\t\t&readBytes,\n\t\t\t&nextSize)\n\t\tif err != nil {\n\t\t\tif err != syscall.ERROR_INSUFFICIENT_BUFFER {\n\t\t\t\tif err != errorInvalidParameter {\n\t\t\t\t\treturn 0, 0, \"\", err\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbuf = make([]byte, nextSize)\n\t\t\tsize = nextSize\n\t\t\terr = eventlog.ReadEventLog(\n\t\t\t\th,\n\t\t\t\tflags,\n\t\t\t\ti,\n\t\t\t\t&buf[0],\n\t\t\t\tsize,\n\t\t\t\t&readBytes,\n\t\t\t\t&nextSize)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"eventlog.ReadEventLog: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tr := *(*eventlog.EVENTLOGRECORD)(unsafe.Pointer(&buf[0]))\n\t\tif opts.Verbose {\n\t\t\tlog.Printf(\"RecordNumber=%v\", r.RecordNumber)\n\t\t\tlog.Printf(\"TimeGenerated=%v\", time.Unix(int64(r.TimeGenerated), 0).String())\n\t\t\tlog.Printf(\"TimeWritten=%v\", time.Unix(int64(r.TimeWritten), 0).String())\n\t\t\tlog.Printf(\"EventID=%v\", r.EventID)\n\t\t}\n\t\tlastNumber = r.RecordNumber\n\n\t\ttn := eventlog.EventType(r.EventType).String()\n\t\tif opts.Verbose {\n\t\t\tlog.Printf(\"EventType=%v\", tn)\n\t\t}\n\t\tif len(opts.typeList) > 0 {\n\t\t\tfound := false\n\t\t\tfor _, typ := range opts.typeList {\n\t\t\t\tif typ == tn {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tsourceName, sourceNameOff := bytesToString(buf[unsafe.Sizeof(eventlog.EVENTLOGRECORD{}):])\n\t\tcomputerName, _ := bytesToString(buf[unsafe.Sizeof(eventlog.EVENTLOGRECORD{})+uintptr(sourceNameOff+2):])\n\t\tif opts.Verbose {\n\t\t\tlog.Printf(\"SourceName=%v\", sourceName)\n\t\t\tlog.Printf(\"ComputerName=%v\", computerName)\n\t\t}\n\n\t\tif opts.sourcePattern != nil {\n\t\t\tif !opts.sourcePattern.MatchString(sourceName) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\toff := uint32(0)\n\t\targs := make([]*byte, uintptr(r.NumStrings)*unsafe.Sizeof((*uint16)(nil)))\n\t\tfor n := 0; n < int(r.NumStrings); n++ {\n\t\t\targs[n] = &buf[r.StringOffset+off]\n\t\t\t_, boff := bytesToString(buf[r.StringOffset+off:])\n\t\t\toff += boff + 2\n\t\t}\n\n\t\tvar argsptr uintptr\n\t\tif r.NumStrings > 0 {\n\t\t\targsptr = uintptr(unsafe.Pointer(&args[0]))\n\t\t}\n\t\tmessage, _ := getResourceMessage(logName, sourceName, r.EventID, argsptr)\n\t\tif opts.Verbose {\n\t\t\tlog.Printf(\"Message=%v\", message)\n\t\t}\n\t\tif opts.messagePattern != nil {\n\t\t\tif !opts.messagePattern.MatchString(message) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif opts.ReturnContent {\n\t\t\terrLines += sourceName + \":\" + strings.Replace(message, \"\\n\", \"\", -1) + \"\\n\"\n\t\t}\n\t\tswitch tn {\n\t\tcase \"Error\":\n\t\t\tcritNum++\n\t\tcase \"Audit Failure\":\n\t\t\tcritNum++\n\t\tcase \"Warning\":\n\t\t\twarnNum++\n\t\t}\n\t}\n\n\tif !opts.NoState {\n\t\terr = writeLastOffset(stateFile, int64(lastNumber))\n\t\tif err != nil {\n\t\t\tlog.Printf(\"writeLastOffset failed: %s\\n\", err.Error())\n\t\t}\n\t}\n\n\tif recordNumber == 0 && !opts.FailFirst {\n\t\treturn 0, 0, \"\", nil\n\t}\n\treturn warnNum, critNum, errLines, nil\n}\n\nvar stateRe = regexp.MustCompile(`^([A-Z]):[\/\\\\]`)\n\nfunc (opts *logOpts) getStateFile(logName string) string {\n\treturn filepath.Join(\n\t\topts.StateDir,\n\t\tfmt.Sprintf(\n\t\t\t\"%s-%x\",\n\t\t\tstateRe.ReplaceAllString(logName, `$1`+string(filepath.Separator)),\n\t\t\tmd5.Sum([]byte(strings.Join(opts.origArgs, \" \"))),\n\t\t),\n\t)\n}\n\nfunc getLastOffset(f string) (int64, error) {\n\t_, err := os.Stat(f)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tb, err := ioutil.ReadFile(f)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\ti, err := strconv.ParseInt(strings.Trim(string(b), \" \\r\\n\"), 10, 64)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn i, nil\n}\n\nfunc writeLastOffset(f string, num int64) error {\n\terr := os.MkdirAll(filepath.Dir(f), 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(f, []byte(fmt.Sprintf(\"%d\", num)), 0644)\n}\n<|endoftext|>"}
{"text":"<commit_before>package types\n\nimport (\n\t\"regexp\"\n)\n\nvar (\n\tMinNameRegistrationPeriod uint64 = 5\n\n\t\/\/ cost for storing a name for a block is\n\t\/\/ CostPerBlock*CostPerByte*(len(data) + 32)\n\tNameCostPerByte  uint64 = 1\n\tNameCostPerBlock uint64 = 1\n\n\tMaxNameLength = 32\n\tMaxDataLength = 1 << 16\n\n\t\/\/ Name should be alphanum, underscore, slash\n\t\/\/ Data should be anything permitted in JSON\n\tregexpAlphaNum = regexp.MustCompile(\"^[a-zA-Z0-9_\/]*$\")\n\tregexpJSON     = regexp.MustCompile(`^[a-zA-Z0-9_\/ \\-\"':,\\n\\t.{}()\\[\\]]*$`)\n)\n\n\/\/ filter strings\nfunc validateNameRegEntryName(name string) bool {\n\treturn regexpAlphaNum.Match([]byte(name))\n}\n\nfunc validateNameRegEntryData(data string) bool {\n\treturn regexpJSON.Match([]byte(data))\n}\n\n\/\/ base cost is \"effective\" number of bytes\nfunc BaseEntryCost(name, data string) uint64 {\n\treturn uint64(len(data) + 32)\n}\n\ntype NameRegEntry struct {\n\tName    string `json:\"name\"`    \/\/ registered name for the entry\n\tOwner   []byte `json:\"owner\"`   \/\/ address that created the entry\n\tData    string `json:\"data\"`    \/\/ data to store under this name\n\tExpires uint64 `json:\"expires\"` \/\/ block at which this entry expires\n}\n\nfunc (entry *NameRegEntry) Copy() *NameRegEntry {\n\tentryCopy := *entry\n\treturn &entryCopy\n}\n<commit_msg>allow . in names<commit_after>package types\n\nimport (\n\t\"regexp\"\n)\n\nvar (\n\tMinNameRegistrationPeriod uint64 = 5\n\n\t\/\/ cost for storing a name for a block is\n\t\/\/ CostPerBlock*CostPerByte*(len(data) + 32)\n\tNameCostPerByte  uint64 = 1\n\tNameCostPerBlock uint64 = 1\n\n\tMaxNameLength = 32\n\tMaxDataLength = 1 << 16\n\n\t\/\/ Name should be alphanum, underscore, slash\n\t\/\/ Data should be anything permitted in JSON\n\tregexpAlphaNum = regexp.MustCompile(\"^[a-zA-Z0-9._\/]*$\")\n\tregexpJSON     = regexp.MustCompile(`^[a-zA-Z0-9_\/ \\-\"':,\\n\\t.{}()\\[\\]]*$`)\n)\n\n\/\/ filter strings\nfunc validateNameRegEntryName(name string) bool {\n\treturn regexpAlphaNum.Match([]byte(name))\n}\n\nfunc validateNameRegEntryData(data string) bool {\n\treturn regexpJSON.Match([]byte(data))\n}\n\n\/\/ base cost is \"effective\" number of bytes\nfunc BaseEntryCost(name, data string) uint64 {\n\treturn uint64(len(data) + 32)\n}\n\ntype NameRegEntry struct {\n\tName    string `json:\"name\"`    \/\/ registered name for the entry\n\tOwner   []byte `json:\"owner\"`   \/\/ address that created the entry\n\tData    string `json:\"data\"`    \/\/ data to store under this name\n\tExpires uint64 `json:\"expires\"` \/\/ block at which this entry expires\n}\n\nfunc (entry *NameRegEntry) Copy() *NameRegEntry {\n\tentryCopy := *entry\n\treturn &entryCopy\n}\n<|endoftext|>"}
{"text":"<commit_before>package types\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/docker\/engine-api\/types\/container\"\n\t\"github.com\/docker\/engine-api\/types\/network\"\n\t\"github.com\/docker\/engine-api\/types\/registry\"\n\t\"github.com\/docker\/go-connections\/nat\"\n)\n\n\/\/ ContainerCreateResponse contains the information returned to a client on the\n\/\/ creation of a new container.\ntype ContainerCreateResponse struct {\n\t\/\/ ID is the ID of the created container.\n\tID string `json:\"Id\"`\n\n\t\/\/ Warnings are any warnings encountered during the creation of the container.\n\tWarnings []string `json:\"Warnings\"`\n}\n\n\/\/ ContainerExecCreateResponse contains response of Remote API:\n\/\/ POST \"\/containers\/{name:.*}\/exec\"\ntype ContainerExecCreateResponse struct {\n\t\/\/ ID is the exec ID.\n\tID string `json:\"Id\"`\n}\n\n\/\/ ContainerUpdateResponse contains response of Remote API:\n\/\/ POST \/containers\/{name:.*}\/update\ntype ContainerUpdateResponse struct {\n\t\/\/ Warnings are any warnings encountered during the updating of the container.\n\tWarnings []string `json:\"Warnings\"`\n}\n\n\/\/ AuthResponse contains response of Remote API:\n\/\/ POST \"\/auth\"\ntype AuthResponse struct {\n\t\/\/ Status is the authentication status\n\tStatus string `json:\"Status\"`\n}\n\n\/\/ ContainerWaitResponse contains response of Remote API:\n\/\/ POST \"\/containers\/\"+containerID+\"\/wait\"\ntype ContainerWaitResponse struct {\n\t\/\/ StatusCode is the status code of the wait job\n\tStatusCode int `json:\"StatusCode\"`\n}\n\n\/\/ ContainerCommitResponse contains response of Remote API:\n\/\/ POST \"\/commit?container=\"+containerID\ntype ContainerCommitResponse struct {\n\tID string `json:\"Id\"`\n}\n\n\/\/ ContainerChange contains response of Remote API:\n\/\/ GET \"\/containers\/{name:.*}\/changes\"\ntype ContainerChange struct {\n\tKind int\n\tPath string\n}\n\n\/\/ ImageHistory contains response of Remote API:\n\/\/ GET \"\/images\/{name:.*}\/history\"\ntype ImageHistory struct {\n\tID        string `json:\"Id\"`\n\tCreated   int64\n\tCreatedBy string\n\tTags      []string\n\tSize      int64\n\tComment   string\n}\n\n\/\/ ImageDelete contains response of Remote API:\n\/\/ DELETE \"\/images\/{name:.*}\"\ntype ImageDelete struct {\n\tUntagged string `json:\",omitempty\"`\n\tDeleted  string `json:\",omitempty\"`\n}\n\n\/\/ Image contains response of Remote API:\n\/\/ GET \"\/images\/json\"\ntype Image struct {\n\tID          string `json:\"Id\"`\n\tParentID    string `json:\"ParentId\"`\n\tRepoTags    []string\n\tRepoDigests []string\n\tCreated     int64\n\tSize        int64\n\tVirtualSize int64\n\tLabels      map[string]string\n}\n\n\/\/ GraphDriverData returns Image's graph driver config info\n\/\/ when calling inspect command\ntype GraphDriverData struct {\n\tName string\n\tData map[string]string\n}\n\n\/\/ ImageInspect contains response of Remote API:\n\/\/ GET \"\/images\/{name:.*}\/json\"\ntype ImageInspect struct {\n\tID              string `json:\"Id\"`\n\tRepoTags        []string\n\tRepoDigests     []string\n\tParent          string\n\tComment         string\n\tCreated         string\n\tContainer       string\n\tContainerConfig *container.Config\n\tDockerVersion   string\n\tAuthor          string\n\tConfig          *container.Config\n\tArchitecture    string\n\tOs              string\n\tSize            int64\n\tVirtualSize     int64\n\tGraphDriver     GraphDriverData\n}\n\n\/\/ Port stores open ports info of container\n\/\/ e.g. {\"PrivatePort\": 8080, \"PublicPort\": 80, \"Type\": \"tcp\"}\ntype Port struct {\n\tIP          string `json:\",omitempty\"`\n\tPrivatePort int\n\tPublicPort  int `json:\",omitempty\"`\n\tType        string\n}\n\n\/\/ Container contains response of Remote API:\n\/\/ GET  \"\/containers\/json\"\ntype Container struct {\n\tID         string `json:\"Id\"`\n\tNames      []string\n\tImage      string\n\tImageID    string\n\tCommand    string\n\tCreated    int64\n\tPorts      []Port\n\tSizeRw     int64 `json:\",omitempty\"`\n\tSizeRootFs int64 `json:\",omitempty\"`\n\tLabels     map[string]string\n\tStatus     string\n\tHostConfig struct {\n\t\tNetworkMode string `json:\",omitempty\"`\n\t}\n\tNetworkSettings *SummaryNetworkSettings\n}\n\n\/\/ CopyConfig contains request body of Remote API:\n\/\/ POST \"\/containers\/\"+containerID+\"\/copy\"\ntype CopyConfig struct {\n\tResource string\n}\n\n\/\/ ContainerPathStat is used to encode the header from\n\/\/ GET \"\/containers\/{name:.*}\/archive\"\n\/\/ \"Name\" is the file or directory name.\ntype ContainerPathStat struct {\n\tName       string      `json:\"name\"`\n\tSize       int64       `json:\"size\"`\n\tMode       os.FileMode `json:\"mode\"`\n\tMtime      time.Time   `json:\"mtime\"`\n\tLinkTarget string      `json:\"linkTarget\"`\n}\n\n\/\/ ContainerProcessList contains response of Remote API:\n\/\/ GET \"\/containers\/{name:.*}\/top\"\ntype ContainerProcessList struct {\n\tProcesses [][]string\n\tTitles    []string\n}\n\n\/\/ Version contains response of Remote API:\n\/\/ GET \"\/version\"\ntype Version struct {\n\tVersion       string\n\tAPIVersion    string `json:\"ApiVersion\"`\n\tGitCommit     string\n\tGoVersion     string\n\tOs            string\n\tArch          string\n\tKernelVersion string `json:\",omitempty\"`\n\tExperimental  bool   `json:\",omitempty\"`\n\tBuildTime     string `json:\",omitempty\"`\n}\n\n\/\/ Info contains response of Remote API:\n\/\/ GET \"\/info\"\ntype Info struct {\n\tID                 string\n\tContainers         int\n\tImages             int\n\tDriver             string\n\tDriverStatus       [][2]string\n\tPlugins            PluginsInfo\n\tMemoryLimit        bool\n\tSwapLimit          bool\n\tCPUCfsPeriod       bool `json:\"CpuCfsPeriod\"`\n\tCPUCfsQuota        bool `json:\"CpuCfsQuota\"`\n\tCPUShares          bool\n\tCPUSet             bool\n\tIPv4Forwarding     bool\n\tBridgeNfIptables   bool\n\tBridgeNfIP6tables  bool `json:\"BridgeNfIp6tables\"`\n\tDebug              bool\n\tNFd                int\n\tOomKillDisable     bool\n\tNGoroutines        int\n\tSystemTime         string\n\tExecutionDriver    string\n\tLoggingDriver      string\n\tNEventsListener    int\n\tKernelVersion      string\n\tOperatingSystem    string\n\tOSType             string\n\tArchitecture       string\n\tIndexServerAddress string\n\tRegistryConfig     *registry.ServiceConfig\n\tInitSha1           string\n\tInitPath           string\n\tNCPU               int\n\tMemTotal           int64\n\tDockerRootDir      string\n\tHTTPProxy          string `json:\"HttpProxy\"`\n\tHTTPSProxy         string `json:\"HttpsProxy\"`\n\tNoProxy            string\n\tName               string\n\tLabels             []string\n\tExperimentalBuild  bool\n\tServerVersion      string\n\tClusterStore       string\n\tClusterAdvertise   string\n}\n\n\/\/ PluginsInfo is temp struct holds Plugins name\n\/\/ registered with docker daemon. It used by Info struct\ntype PluginsInfo struct {\n\t\/\/ List of Volume plugins registered\n\tVolume []string\n\t\/\/ List of Network plugins registered\n\tNetwork []string\n\t\/\/ List of Authorization plugins registered\n\tAuthorization []string\n}\n\n\/\/ ExecStartCheck is a temp struct used by execStart\n\/\/ Config fields is part of ExecConfig in runconfig package\ntype ExecStartCheck struct {\n\t\/\/ ExecStart will first check if it's detached\n\tDetach bool\n\t\/\/ Check if there's a tty\n\tTty bool\n}\n\n\/\/ ContainerState stores container's running state\n\/\/ it's part of ContainerJSONBase and will return by \"inspect\" command\ntype ContainerState struct {\n\tStatus     string\n\tRunning    bool\n\tPaused     bool\n\tRestarting bool\n\tOOMKilled  bool\n\tDead       bool\n\tPid        int\n\tExitCode   int\n\tError      string\n\tStartedAt  string\n\tFinishedAt string\n}\n\n\/\/ ContainerJSONBase contains response of Remote API:\n\/\/ GET \"\/containers\/{name:.*}\/json\"\ntype ContainerJSONBase struct {\n\tID              string `json:\"Id\"`\n\tCreated         string\n\tPath            string\n\tArgs            []string\n\tState           *ContainerState\n\tImage           string\n\tResolvConfPath  string\n\tHostnamePath    string\n\tHostsPath       string\n\tLogPath         string\n\tName            string\n\tRestartCount    int\n\tDriver          string\n\tMountLabel      string\n\tProcessLabel    string\n\tAppArmorProfile string\n\tExecIDs         []string\n\tHostConfig      *container.HostConfig\n\tGraphDriver     GraphDriverData\n\tSizeRw          *int64 `json:\",omitempty\"`\n\tSizeRootFs      *int64 `json:\",omitempty\"`\n}\n\n\/\/ ContainerJSON is newly used struct along with MountPoint\ntype ContainerJSON struct {\n\t*ContainerJSONBase\n\tMounts          []MountPoint\n\tConfig          *container.Config\n\tNetworkSettings *NetworkSettings\n}\n\n\/\/ NetworkSettings exposes the network settings in the api\ntype NetworkSettings struct {\n\tNetworkSettingsBase\n\tDefaultNetworkSettings\n\tNetworks map[string]*network.EndpointSettings\n}\n\n\/\/ SummaryNetworkSettings provides a summary of container's networks\n\/\/ in \/containers\/json\ntype SummaryNetworkSettings struct {\n\tNetworks map[string]*network.EndpointSettings\n}\n\n\/\/ NetworkSettingsBase holds basic information about networks\ntype NetworkSettingsBase struct {\n\tBridge                 string\n\tSandboxID              string\n\tHairpinMode            bool\n\tLinkLocalIPv6Address   string\n\tLinkLocalIPv6PrefixLen int\n\tPorts                  nat.PortMap\n\tSandboxKey             string\n\tSecondaryIPAddresses   []network.Address\n\tSecondaryIPv6Addresses []network.Address\n}\n\n\/\/ DefaultNetworkSettings holds network information\n\/\/ during the 2 release deprecation period.\n\/\/ It will be removed in Docker 1.11.\ntype DefaultNetworkSettings struct {\n\tEndpointID          string\n\tGateway             string\n\tGlobalIPv6Address   string\n\tGlobalIPv6PrefixLen int\n\tIPAddress           string\n\tIPPrefixLen         int\n\tIPv6Gateway         string\n\tMacAddress          string\n}\n\n\/\/ MountPoint represents a mount point configuration inside the container.\ntype MountPoint struct {\n\tName        string `json:\",omitempty\"`\n\tSource      string\n\tDestination string\n\tDriver      string `json:\",omitempty\"`\n\tMode        string\n\tRW          bool\n\tPropagation string\n}\n\n\/\/ Volume represents the configuration of a volume for the remote API\ntype Volume struct {\n\tName       string \/\/ Name is the name of the volume\n\tDriver     string \/\/ Driver is the Driver name used to create the volume\n\tMountpoint string \/\/ Mountpoint is the location on disk of the volume\n}\n\n\/\/ VolumesListResponse contains the response for the remote API:\n\/\/ GET \"\/volumes\"\ntype VolumesListResponse struct {\n\tVolumes  []*Volume \/\/ Volumes is the list of volumes being returned\n\tWarnings []string  \/\/ Warnings is a list of warnings that occurred when getting the list from the volume drivers\n}\n\n\/\/ VolumeCreateRequest contains the response for the remote API:\n\/\/ POST \"\/volumes\/create\"\ntype VolumeCreateRequest struct {\n\tName       string            \/\/ Name is the requested name of the volume\n\tDriver     string            \/\/ Driver is the name of the driver that should be used to create the volume\n\tDriverOpts map[string]string \/\/ DriverOpts holds the driver specific options to use for when creating the volume.\n}\n\n\/\/ NetworkResource is the body of the \"get network\" http response message\ntype NetworkResource struct {\n\tName       string\n\tID         string `json:\"Id\"`\n\tScope      string\n\tDriver     string\n\tIPAM       network.IPAM\n\tContainers map[string]EndpointResource\n\tOptions    map[string]string\n}\n\n\/\/ EndpointResource contains network resources allocated and used for a container in a network\ntype EndpointResource struct {\n\tName        string\n\tEndpointID  string\n\tMacAddress  string\n\tIPv4Address string\n\tIPv6Address string\n}\n\n\/\/ NetworkCreate is the expected body of the \"create network\" http request message\ntype NetworkCreate struct {\n\tName           string\n\tCheckDuplicate bool\n\tDriver         string\n\tIPAM           network.IPAM\n\tInternal       bool\n\tOptions        map[string]string\n}\n\n\/\/ NetworkCreateResponse is the response message sent by the server for network create call\ntype NetworkCreateResponse struct {\n\tID      string `json:\"Id\"`\n\tWarning string\n}\n\n\/\/ NetworkConnect represents the data to be used to connect a container to the network\ntype NetworkConnect struct {\n\tContainer      string\n\tEndpointConfig *network.EndpointSettings `json:\"endpoint_config\"`\n}\n\n\/\/ NetworkDisconnect represents the data to be used to disconnect a container from the network\ntype NetworkDisconnect struct {\n\tContainer string\n\tForce     bool\n}\n<commit_msg>Remove json tag in NetworkConnect.EndpointConfig<commit_after>package types\n\nimport (\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/docker\/engine-api\/types\/container\"\n\t\"github.com\/docker\/engine-api\/types\/network\"\n\t\"github.com\/docker\/engine-api\/types\/registry\"\n\t\"github.com\/docker\/go-connections\/nat\"\n)\n\n\/\/ ContainerCreateResponse contains the information returned to a client on the\n\/\/ creation of a new container.\ntype ContainerCreateResponse struct {\n\t\/\/ ID is the ID of the created container.\n\tID string `json:\"Id\"`\n\n\t\/\/ Warnings are any warnings encountered during the creation of the container.\n\tWarnings []string `json:\"Warnings\"`\n}\n\n\/\/ ContainerExecCreateResponse contains response of Remote API:\n\/\/ POST \"\/containers\/{name:.*}\/exec\"\ntype ContainerExecCreateResponse struct {\n\t\/\/ ID is the exec ID.\n\tID string `json:\"Id\"`\n}\n\n\/\/ ContainerUpdateResponse contains response of Remote API:\n\/\/ POST \/containers\/{name:.*}\/update\ntype ContainerUpdateResponse struct {\n\t\/\/ Warnings are any warnings encountered during the updating of the container.\n\tWarnings []string `json:\"Warnings\"`\n}\n\n\/\/ AuthResponse contains response of Remote API:\n\/\/ POST \"\/auth\"\ntype AuthResponse struct {\n\t\/\/ Status is the authentication status\n\tStatus string `json:\"Status\"`\n}\n\n\/\/ ContainerWaitResponse contains response of Remote API:\n\/\/ POST \"\/containers\/\"+containerID+\"\/wait\"\ntype ContainerWaitResponse struct {\n\t\/\/ StatusCode is the status code of the wait job\n\tStatusCode int `json:\"StatusCode\"`\n}\n\n\/\/ ContainerCommitResponse contains response of Remote API:\n\/\/ POST \"\/commit?container=\"+containerID\ntype ContainerCommitResponse struct {\n\tID string `json:\"Id\"`\n}\n\n\/\/ ContainerChange contains response of Remote API:\n\/\/ GET \"\/containers\/{name:.*}\/changes\"\ntype ContainerChange struct {\n\tKind int\n\tPath string\n}\n\n\/\/ ImageHistory contains response of Remote API:\n\/\/ GET \"\/images\/{name:.*}\/history\"\ntype ImageHistory struct {\n\tID        string `json:\"Id\"`\n\tCreated   int64\n\tCreatedBy string\n\tTags      []string\n\tSize      int64\n\tComment   string\n}\n\n\/\/ ImageDelete contains response of Remote API:\n\/\/ DELETE \"\/images\/{name:.*}\"\ntype ImageDelete struct {\n\tUntagged string `json:\",omitempty\"`\n\tDeleted  string `json:\",omitempty\"`\n}\n\n\/\/ Image contains response of Remote API:\n\/\/ GET \"\/images\/json\"\ntype Image struct {\n\tID          string `json:\"Id\"`\n\tParentID    string `json:\"ParentId\"`\n\tRepoTags    []string\n\tRepoDigests []string\n\tCreated     int64\n\tSize        int64\n\tVirtualSize int64\n\tLabels      map[string]string\n}\n\n\/\/ GraphDriverData returns Image's graph driver config info\n\/\/ when calling inspect command\ntype GraphDriverData struct {\n\tName string\n\tData map[string]string\n}\n\n\/\/ ImageInspect contains response of Remote API:\n\/\/ GET \"\/images\/{name:.*}\/json\"\ntype ImageInspect struct {\n\tID              string `json:\"Id\"`\n\tRepoTags        []string\n\tRepoDigests     []string\n\tParent          string\n\tComment         string\n\tCreated         string\n\tContainer       string\n\tContainerConfig *container.Config\n\tDockerVersion   string\n\tAuthor          string\n\tConfig          *container.Config\n\tArchitecture    string\n\tOs              string\n\tSize            int64\n\tVirtualSize     int64\n\tGraphDriver     GraphDriverData\n}\n\n\/\/ Port stores open ports info of container\n\/\/ e.g. {\"PrivatePort\": 8080, \"PublicPort\": 80, \"Type\": \"tcp\"}\ntype Port struct {\n\tIP          string `json:\",omitempty\"`\n\tPrivatePort int\n\tPublicPort  int `json:\",omitempty\"`\n\tType        string\n}\n\n\/\/ Container contains response of Remote API:\n\/\/ GET  \"\/containers\/json\"\ntype Container struct {\n\tID         string `json:\"Id\"`\n\tNames      []string\n\tImage      string\n\tImageID    string\n\tCommand    string\n\tCreated    int64\n\tPorts      []Port\n\tSizeRw     int64 `json:\",omitempty\"`\n\tSizeRootFs int64 `json:\",omitempty\"`\n\tLabels     map[string]string\n\tStatus     string\n\tHostConfig struct {\n\t\tNetworkMode string `json:\",omitempty\"`\n\t}\n\tNetworkSettings *SummaryNetworkSettings\n}\n\n\/\/ CopyConfig contains request body of Remote API:\n\/\/ POST \"\/containers\/\"+containerID+\"\/copy\"\ntype CopyConfig struct {\n\tResource string\n}\n\n\/\/ ContainerPathStat is used to encode the header from\n\/\/ GET \"\/containers\/{name:.*}\/archive\"\n\/\/ \"Name\" is the file or directory name.\ntype ContainerPathStat struct {\n\tName       string      `json:\"name\"`\n\tSize       int64       `json:\"size\"`\n\tMode       os.FileMode `json:\"mode\"`\n\tMtime      time.Time   `json:\"mtime\"`\n\tLinkTarget string      `json:\"linkTarget\"`\n}\n\n\/\/ ContainerProcessList contains response of Remote API:\n\/\/ GET \"\/containers\/{name:.*}\/top\"\ntype ContainerProcessList struct {\n\tProcesses [][]string\n\tTitles    []string\n}\n\n\/\/ Version contains response of Remote API:\n\/\/ GET \"\/version\"\ntype Version struct {\n\tVersion       string\n\tAPIVersion    string `json:\"ApiVersion\"`\n\tGitCommit     string\n\tGoVersion     string\n\tOs            string\n\tArch          string\n\tKernelVersion string `json:\",omitempty\"`\n\tExperimental  bool   `json:\",omitempty\"`\n\tBuildTime     string `json:\",omitempty\"`\n}\n\n\/\/ Info contains response of Remote API:\n\/\/ GET \"\/info\"\ntype Info struct {\n\tID                 string\n\tContainers         int\n\tImages             int\n\tDriver             string\n\tDriverStatus       [][2]string\n\tPlugins            PluginsInfo\n\tMemoryLimit        bool\n\tSwapLimit          bool\n\tCPUCfsPeriod       bool `json:\"CpuCfsPeriod\"`\n\tCPUCfsQuota        bool `json:\"CpuCfsQuota\"`\n\tCPUShares          bool\n\tCPUSet             bool\n\tIPv4Forwarding     bool\n\tBridgeNfIptables   bool\n\tBridgeNfIP6tables  bool `json:\"BridgeNfIp6tables\"`\n\tDebug              bool\n\tNFd                int\n\tOomKillDisable     bool\n\tNGoroutines        int\n\tSystemTime         string\n\tExecutionDriver    string\n\tLoggingDriver      string\n\tNEventsListener    int\n\tKernelVersion      string\n\tOperatingSystem    string\n\tOSType             string\n\tArchitecture       string\n\tIndexServerAddress string\n\tRegistryConfig     *registry.ServiceConfig\n\tInitSha1           string\n\tInitPath           string\n\tNCPU               int\n\tMemTotal           int64\n\tDockerRootDir      string\n\tHTTPProxy          string `json:\"HttpProxy\"`\n\tHTTPSProxy         string `json:\"HttpsProxy\"`\n\tNoProxy            string\n\tName               string\n\tLabels             []string\n\tExperimentalBuild  bool\n\tServerVersion      string\n\tClusterStore       string\n\tClusterAdvertise   string\n}\n\n\/\/ PluginsInfo is temp struct holds Plugins name\n\/\/ registered with docker daemon. It used by Info struct\ntype PluginsInfo struct {\n\t\/\/ List of Volume plugins registered\n\tVolume []string\n\t\/\/ List of Network plugins registered\n\tNetwork []string\n\t\/\/ List of Authorization plugins registered\n\tAuthorization []string\n}\n\n\/\/ ExecStartCheck is a temp struct used by execStart\n\/\/ Config fields is part of ExecConfig in runconfig package\ntype ExecStartCheck struct {\n\t\/\/ ExecStart will first check if it's detached\n\tDetach bool\n\t\/\/ Check if there's a tty\n\tTty bool\n}\n\n\/\/ ContainerState stores container's running state\n\/\/ it's part of ContainerJSONBase and will return by \"inspect\" command\ntype ContainerState struct {\n\tStatus     string\n\tRunning    bool\n\tPaused     bool\n\tRestarting bool\n\tOOMKilled  bool\n\tDead       bool\n\tPid        int\n\tExitCode   int\n\tError      string\n\tStartedAt  string\n\tFinishedAt string\n}\n\n\/\/ ContainerJSONBase contains response of Remote API:\n\/\/ GET \"\/containers\/{name:.*}\/json\"\ntype ContainerJSONBase struct {\n\tID              string `json:\"Id\"`\n\tCreated         string\n\tPath            string\n\tArgs            []string\n\tState           *ContainerState\n\tImage           string\n\tResolvConfPath  string\n\tHostnamePath    string\n\tHostsPath       string\n\tLogPath         string\n\tName            string\n\tRestartCount    int\n\tDriver          string\n\tMountLabel      string\n\tProcessLabel    string\n\tAppArmorProfile string\n\tExecIDs         []string\n\tHostConfig      *container.HostConfig\n\tGraphDriver     GraphDriverData\n\tSizeRw          *int64 `json:\",omitempty\"`\n\tSizeRootFs      *int64 `json:\",omitempty\"`\n}\n\n\/\/ ContainerJSON is newly used struct along with MountPoint\ntype ContainerJSON struct {\n\t*ContainerJSONBase\n\tMounts          []MountPoint\n\tConfig          *container.Config\n\tNetworkSettings *NetworkSettings\n}\n\n\/\/ NetworkSettings exposes the network settings in the api\ntype NetworkSettings struct {\n\tNetworkSettingsBase\n\tDefaultNetworkSettings\n\tNetworks map[string]*network.EndpointSettings\n}\n\n\/\/ SummaryNetworkSettings provides a summary of container's networks\n\/\/ in \/containers\/json\ntype SummaryNetworkSettings struct {\n\tNetworks map[string]*network.EndpointSettings\n}\n\n\/\/ NetworkSettingsBase holds basic information about networks\ntype NetworkSettingsBase struct {\n\tBridge                 string\n\tSandboxID              string\n\tHairpinMode            bool\n\tLinkLocalIPv6Address   string\n\tLinkLocalIPv6PrefixLen int\n\tPorts                  nat.PortMap\n\tSandboxKey             string\n\tSecondaryIPAddresses   []network.Address\n\tSecondaryIPv6Addresses []network.Address\n}\n\n\/\/ DefaultNetworkSettings holds network information\n\/\/ during the 2 release deprecation period.\n\/\/ It will be removed in Docker 1.11.\ntype DefaultNetworkSettings struct {\n\tEndpointID          string\n\tGateway             string\n\tGlobalIPv6Address   string\n\tGlobalIPv6PrefixLen int\n\tIPAddress           string\n\tIPPrefixLen         int\n\tIPv6Gateway         string\n\tMacAddress          string\n}\n\n\/\/ MountPoint represents a mount point configuration inside the container.\ntype MountPoint struct {\n\tName        string `json:\",omitempty\"`\n\tSource      string\n\tDestination string\n\tDriver      string `json:\",omitempty\"`\n\tMode        string\n\tRW          bool\n\tPropagation string\n}\n\n\/\/ Volume represents the configuration of a volume for the remote API\ntype Volume struct {\n\tName       string \/\/ Name is the name of the volume\n\tDriver     string \/\/ Driver is the Driver name used to create the volume\n\tMountpoint string \/\/ Mountpoint is the location on disk of the volume\n}\n\n\/\/ VolumesListResponse contains the response for the remote API:\n\/\/ GET \"\/volumes\"\ntype VolumesListResponse struct {\n\tVolumes  []*Volume \/\/ Volumes is the list of volumes being returned\n\tWarnings []string  \/\/ Warnings is a list of warnings that occurred when getting the list from the volume drivers\n}\n\n\/\/ VolumeCreateRequest contains the response for the remote API:\n\/\/ POST \"\/volumes\/create\"\ntype VolumeCreateRequest struct {\n\tName       string            \/\/ Name is the requested name of the volume\n\tDriver     string            \/\/ Driver is the name of the driver that should be used to create the volume\n\tDriverOpts map[string]string \/\/ DriverOpts holds the driver specific options to use for when creating the volume.\n}\n\n\/\/ NetworkResource is the body of the \"get network\" http response message\ntype NetworkResource struct {\n\tName       string\n\tID         string `json:\"Id\"`\n\tScope      string\n\tDriver     string\n\tIPAM       network.IPAM\n\tContainers map[string]EndpointResource\n\tOptions    map[string]string\n}\n\n\/\/ EndpointResource contains network resources allocated and used for a container in a network\ntype EndpointResource struct {\n\tName        string\n\tEndpointID  string\n\tMacAddress  string\n\tIPv4Address string\n\tIPv6Address string\n}\n\n\/\/ NetworkCreate is the expected body of the \"create network\" http request message\ntype NetworkCreate struct {\n\tName           string\n\tCheckDuplicate bool\n\tDriver         string\n\tIPAM           network.IPAM\n\tInternal       bool\n\tOptions        map[string]string\n}\n\n\/\/ NetworkCreateResponse is the response message sent by the server for network create call\ntype NetworkCreateResponse struct {\n\tID      string `json:\"Id\"`\n\tWarning string\n}\n\n\/\/ NetworkConnect represents the data to be used to connect a container to the network\ntype NetworkConnect struct {\n\tContainer      string\n\tEndpointConfig *network.EndpointSettings `json:\",omitempty\"`\n}\n\n\/\/ NetworkDisconnect represents the data to be used to disconnect a container from the network\ntype NetworkDisconnect struct {\n\tContainer string\n\tForce     bool\n}\n<|endoftext|>"}
{"text":"<commit_before>package types\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\/\/ Expression is S-expression\ntype Expression interface{}\n\n\/\/ Number is number of scheme. (based on Go float64)\ntype Number float64\n\n\/\/ Symbol is index of S-expression in some environment.\ntype Symbol string\n\n\/\/ Boolean is boolean of scheme.\ntype Boolean bool\n\nfunc (b Boolean) String() string {\n\tif b {\n\t\treturn \"#t\"\n\t}\n\treturn \"#f\"\n}\n\n\/\/ Pair is cons\ntype Pair struct {\n\tCar Expression\n\tCdr Expression\n}\n\nfunc (p *Pair) String() string {\n\tif p.IsNull() {\n\t\treturn \"()\"\n\t}\n\tif p.IsList() {\n\t\tvar tokens []string\n\t\tpp := p\n\t\tfor {\n\t\t\tif pp.IsNull() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttokens = append(tokens, fmt.Sprintf(\"%v\", pp.Car))\n\t\t\tswitch cdr := pp.Cdr.(type) {\n\t\t\tcase *Pair:\n\t\t\t\tpp = cdr\n\t\t\tdefault:\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn fmt.Sprintf(\"(%s)\", strings.Join(tokens, \" \"))\n\t}\n\treturn fmt.Sprintf(\"(%v . %v)\", p.Car, p.Cdr)\n}\n\n\/\/ IsNull checking if pair is null or not.\nfunc (p *Pair) IsNull() bool {\n\treturn p.Car == nil && p.Cdr == nil\n}\n\n\/\/ IsList returns if pair is list or not.\n\/\/\n\/\/ * empty pair is list\n\/\/ * end of list should be empty pair (empty list)\nfunc (p *Pair) IsList() bool {\n\tpp := p\n\tfor {\n\t\tif pp.IsNull() {\n\t\t\treturn true\n\t\t}\n\t\tswitch cdr := pp.Cdr.(type) {\n\t\tcase *Pair:\n\t\t\tpp = cdr\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n}\n\n\/\/ Append add cons pair to given pair\n\/\/ exp, first arguments of callee, should be car of this pair.\nfunc (p *Pair) Append(exp Expression) *Pair {\n\t\/\/ append exp to tail\n\tpp := p\n\tfor {\n\t\tif pp.IsNull() {\n\t\t\tbreak\n\t\t}\n\t\tpp = pp.Cdr.(*Pair)\n\t}\n\tpp.Car = exp\n\tpp.Cdr = &Pair{}\n\treturn pp\n}\n\n\/\/ NewList makes concatenated pair's list.\n\/\/ Internally, creating last pair and concatenate it with previous pair.\nfunc NewList(args ...Expression) *Pair {\n\t\/\/ In normal, p is prefer to be defined by var statement because of no allocation.\n\t\/\/ But in this case, for empty list should be return empty pair.\n\tp, prev := &Pair{}, &Pair{}\n\tfor i := len(args) - 1; i >= 0; i-- {\n\t\tp = &Pair{args[i], prev}\n\t\tprev = p\n\t}\n\treturn p\n}\n<commit_msg>types.go: to simplify, remove an assignment of prev for NewList<commit_after>package types\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n\/\/ Expression is S-expression\ntype Expression interface{}\n\n\/\/ Number is number of scheme. (based on Go float64)\ntype Number float64\n\n\/\/ Symbol is index of S-expression in some environment.\ntype Symbol string\n\n\/\/ Boolean is boolean of scheme.\ntype Boolean bool\n\nfunc (b Boolean) String() string {\n\tif b {\n\t\treturn \"#t\"\n\t}\n\treturn \"#f\"\n}\n\n\/\/ Pair is cons\ntype Pair struct {\n\tCar Expression\n\tCdr Expression\n}\n\nfunc (p *Pair) String() string {\n\tif p.IsNull() {\n\t\treturn \"()\"\n\t}\n\tif p.IsList() {\n\t\tvar tokens []string\n\t\tpp := p\n\t\tfor {\n\t\t\tif pp.IsNull() {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttokens = append(tokens, fmt.Sprintf(\"%v\", pp.Car))\n\t\t\tswitch cdr := pp.Cdr.(type) {\n\t\t\tcase *Pair:\n\t\t\t\tpp = cdr\n\t\t\tdefault:\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn fmt.Sprintf(\"(%s)\", strings.Join(tokens, \" \"))\n\t}\n\treturn fmt.Sprintf(\"(%v . %v)\", p.Car, p.Cdr)\n}\n\n\/\/ IsNull checking if pair is null or not.\nfunc (p *Pair) IsNull() bool {\n\treturn p.Car == nil && p.Cdr == nil\n}\n\n\/\/ IsList returns if pair is list or not.\n\/\/\n\/\/ * empty pair is list\n\/\/ * end of list should be empty pair (empty list)\nfunc (p *Pair) IsList() bool {\n\tpp := p\n\tfor {\n\t\tif pp.IsNull() {\n\t\t\treturn true\n\t\t}\n\t\tswitch cdr := pp.Cdr.(type) {\n\t\tcase *Pair:\n\t\t\tpp = cdr\n\t\tdefault:\n\t\t\treturn false\n\t\t}\n\t}\n}\n\n\/\/ Append add cons pair to given pair\n\/\/ exp, first arguments of callee, should be car of this pair.\nfunc (p *Pair) Append(exp Expression) *Pair {\n\t\/\/ append exp to tail\n\tpp := p\n\tfor {\n\t\tif pp.IsNull() {\n\t\t\tbreak\n\t\t}\n\t\tpp = pp.Cdr.(*Pair)\n\t}\n\tpp.Car = exp\n\tpp.Cdr = &Pair{}\n\treturn pp\n}\n\n\/\/ NewList makes concatenated pair's list.\n\/\/ Internally, creating last pair and concatenate it with previous pair.\nfunc NewList(args ...Expression) *Pair {\n\t\/\/ In normal, p is prefer to be defined by var statement because of no allocation.\n\t\/\/ But in this case, for empty list should be return empty pair.\n\tp := &Pair{}\n\tfor i := len(args) - 1; i >= 0; i-- {\n\t\tp = &Pair{args[i], p}\n\t}\n\treturn p\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 The Jetstack cert-manager contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage ctl\n\nimport (\n\t\"context\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\tcorev1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/cli-runtime\/pkg\/genericclioptions\"\n\n\t\"github.com\/jetstack\/cert-manager\/cmd\/ctl\/pkg\/create\/certificaterequest\"\n\t\"github.com\/jetstack\/cert-manager\/pkg\/util\/pki\"\n\t\"github.com\/jetstack\/cert-manager\/test\/integration\/framework\"\n)\n\nfunc TestCtlCreateCR(t *testing.T) {\n\tconfig, stopFn := framework.RunControlPlane(t)\n\tdefer stopFn()\n\n\tctx, cancel := context.WithTimeout(context.TODO(), time.Second*20)\n\tdefer cancel()\n\n\t\/\/ Build clients\n\tkubeClient, _, cmCl, _ := framework.NewClients(t, config)\n\n\tvar (\n\t\tcr1Name = \"testcr-1\"\n\t\tcr2Name = \"testcr-2\"\n\t\tcr3Name = \"testcr-3\"\n\t\tcr4Name = \"testcr-4\"\n\t\tns1     = \"testns-1\"\n\t\tns2     = \"testns-2\"\n\t)\n\n\t\/\/ Create Namespaces\n\tfor _, ns := range []string{ns1, ns2} {\n\t\t_, err := kubeClient.CoreV1().Namespaces().Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ns}}, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\ttests := map[string]struct {\n\t\tinputFile      string\n\t\tinputArgs      []string\n\t\tinputNamespace string\n\n\t\texpErr       bool\n\t\texpNamespace string\n\t\texpName      string\n\t}{\n\t\t\"v1alpha2 Certificate given\": {\n\t\t\tinputFile:      \".\/testdata\/create_cr_cert_with_ns1.yaml\",\n\t\t\tinputArgs:      []string{cr1Name},\n\t\t\tinputNamespace: ns1,\n\t\t\texpErr:         false,\n\t\t\texpNamespace:   ns1,\n\t\t\texpName:        cr1Name,\n\t\t},\n\t\t\"v1alpha3 Certificate given\": {\n\t\t\tinputFile:      \".\/testdata\/create_cr_v1alpha3_cert_with_ns1.yaml\",\n\t\t\tinputArgs:      []string{cr2Name},\n\t\t\tinputNamespace: ns1,\n\t\t\texpErr:         false,\n\t\t\texpNamespace:   ns1,\n\t\t\texpName:        cr2Name,\n\t\t},\n\t\t\"conflicting namespaces defined in flag and file\": {\n\t\t\tinputFile:      \".\/testdata\/create_cr_cert_with_ns1.yaml\",\n\t\t\tinputArgs:      []string{cr3Name},\n\t\t\tinputNamespace: ns2,\n\t\t\texpErr:         true,\n\t\t\texpNamespace:   \"\",\n\t\t\texpName:        \"\",\n\t\t},\n\t\t\"file passed in defines resource other than certificate\": {\n\t\t\tinputFile:      \".\/testdata\/create_cr_issuer.yaml\",\n\t\t\tinputArgs:      []string{cr4Name},\n\t\t\tinputNamespace: ns1,\n\t\t\texpErr:         true,\n\t\t\texpNamespace:   \"\",\n\t\t\texpName:        \"\",\n\t\t},\n\t}\n\n\tfor name, test := range tests {\n\t\t\/\/ Run ctl create cr command with input options\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tstreams, _, _, _ := genericclioptions.NewTestIOStreams()\n\n\t\t\t\/\/ Options to run create CR command\n\t\t\topts := &certificaterequest.Options{\n\t\t\t\tCMClient:         cmCl,\n\t\t\t\tRESTConfig:       config,\n\t\t\t\tIOStreams:        streams,\n\t\t\t\tCmdNamespace:     test.inputNamespace,\n\t\t\t\tEnforceNamespace: test.inputNamespace != \"\",\n\t\t\t}\n\n\t\t\topts.Filenames = []string{test.inputFile}\n\n\t\t\terr := opts.Run(test.inputArgs)\n\t\t\tdefer cleanupFileIfExists(test.expName + \".key\")\n\n\t\t\tif err != nil {\n\t\t\t\tif !test.expErr {\n\t\t\t\t\tt.Errorf(\"got unexpected error when trying to create CR: %v\", err)\n\t\t\t\t}\n\t\t\t\tt.Logf(\"got an error, which was expected, details: %v\", err)\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\t\/\/ got no error\n\t\t\t\tif test.expErr {\n\t\t\t\t\tt.Errorf(\"expected but got no error when creating CR\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Finished creating CR, check if everything is expected\n\t\t\tcrName := test.inputArgs[0]\n\t\t\tgotCr, err := cmCl.CertmanagerV1alpha2().CertificateRequests(test.inputNamespace).Get(ctx, crName, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tif gotCr.Namespace != test.expNamespace {\n\t\t\t\tt.Errorf(\"CR created in unexpected Namespace, expected: %s, actual: %s\", test.expNamespace, gotCr.Namespace)\n\t\t\t}\n\n\t\t\tif gotCr.Name != test.expName {\n\t\t\t\tt.Errorf(\"CR created has unexpected Name, expectedL %s, actualL %s\", test.expName, gotCr.Name)\n\t\t\t}\n\n\t\t\t\/\/ Check the file where the private key is stored\n\t\t\tkeyFileName := crName + \".key\"\n\t\t\tkeyData, err := ioutil.ReadFile(keyFileName)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"error when reading file storing private key: %v\", err)\n\t\t\t}\n\t\t\t_, err = pki.DecodePrivateKeyBytes(keyData)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"invalid private key: %v\", err)\n\t\t\t}\n\n\t\t\t\/\/ Clean up CertificateRequest\n\t\t\t\/\/ Everything is expected, so clean up with what is expected\n\t\t\terr = cmCl.CertmanagerV1alpha2().CertificateRequests(test.expNamespace).Delete(ctx, test.expName, metav1.DeleteOptions{})\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc cleanupFileIfExists(fileName string) {\n\t_, err := os.Stat(fileName)\n\tif err == nil {\n\t\terr = os.Remove(fileName)\n\t}\n}\n<commit_msg>Add check for --output-key-file flag<commit_after>\/*\nCopyright 2020 The Jetstack cert-manager contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage ctl\n\nimport (\n\t\"context\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\tcorev1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/cli-runtime\/pkg\/genericclioptions\"\n\n\t\"github.com\/jetstack\/cert-manager\/cmd\/ctl\/pkg\/create\/certificaterequest\"\n\t\"github.com\/jetstack\/cert-manager\/pkg\/util\/pki\"\n\t\"github.com\/jetstack\/cert-manager\/test\/integration\/framework\"\n)\n\nfunc TestCtlCreateCR(t *testing.T) {\n\tconfig, stopFn := framework.RunControlPlane(t)\n\tdefer stopFn()\n\n\tctx, cancel := context.WithTimeout(context.TODO(), time.Second*20)\n\tdefer cancel()\n\n\t\/\/ Build clients\n\tkubeClient, _, cmCl, _ := framework.NewClients(t, config)\n\n\tvar (\n\t\tcr1Name = \"testcr-1\"\n\t\tcr2Name = \"testcr-2\"\n\t\tcr3Name = \"testcr-3\"\n\t\tcr4Name = \"testcr-4\"\n\t\tns1     = \"testns-1\"\n\t\tns2     = \"testns-2\"\n\t)\n\n\t\/\/ Create Namespaces\n\tfor _, ns := range []string{ns1, ns2} {\n\t\t_, err := kubeClient.CoreV1().Namespaces().Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ns}}, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\ttests := map[string]struct {\n\t\tinputFile      string\n\t\tinputArgs      []string\n\t\tinputNamespace string\n\t\tkeyFilename    string\n\n\t\texpErr         bool\n\t\texpNamespace   string\n\t\texpName        string\n\t\texpKeyFilename string\n\t}{\n\t\t\"v1alpha2 Certificate given\": {\n\t\t\tinputFile:      \".\/testdata\/create_cr_cert_with_ns1.yaml\",\n\t\t\tinputArgs:      []string{cr1Name},\n\t\t\tinputNamespace: ns1,\n\t\t\tkeyFilename:    \"\",\n\t\t\texpErr:         false,\n\t\t\texpNamespace:   ns1,\n\t\t\texpName:        cr1Name,\n\t\t\texpKeyFilename: cr1Name + \".key\",\n\t\t},\n\t\t\"v1alpha3 Certificate given\": {\n\t\t\tinputFile:      \".\/testdata\/create_cr_v1alpha3_cert_with_ns1.yaml\",\n\t\t\tinputArgs:      []string{cr2Name},\n\t\t\tinputNamespace: ns1,\n\t\t\tkeyFilename:    \"\",\n\t\t\texpErr:         false,\n\t\t\texpNamespace:   ns1,\n\t\t\texpName:        cr2Name,\n\t\t\texpKeyFilename: cr2Name + \".key\",\n\t\t},\n\t\t\"conflicting namespaces defined in flag and file\": {\n\t\t\tinputFile:      \".\/testdata\/create_cr_cert_with_ns1.yaml\",\n\t\t\tinputArgs:      []string{cr3Name},\n\t\t\tinputNamespace: ns2,\n\t\t\tkeyFilename:    \"\",\n\t\t\texpErr:         true,\n\t\t\texpNamespace:   \"\",\n\t\t\texpName:        \"\",\n\t\t\texpKeyFilename: \"\",\n\t\t},\n\t\t\"file passed in defines resource other than certificate\": {\n\t\t\tinputFile:      \".\/testdata\/create_cr_issuer.yaml\",\n\t\t\tinputArgs:      []string{cr4Name},\n\t\t\tinputNamespace: ns1,\n\t\t\tkeyFilename:    \"\",\n\t\t\texpErr:         true,\n\t\t\texpNamespace:   \"\",\n\t\t\texpName:        \"\",\n\t\t\texpKeyFilename: \"\",\n\t\t},\n\t\t\"path to file to store private key provided\": {\n\t\t\tinputFile:      \".\/testdata\/create_cr_cert_with_ns1.yaml\",\n\t\t\tinputArgs:      []string{cr1Name},\n\t\t\tinputNamespace: ns1,\n\t\t\tkeyFilename:    \"test.key\",\n\t\t\texpErr:         false,\n\t\t\texpNamespace:   ns1,\n\t\t\texpName:        cr1Name,\n\t\t\texpKeyFilename: \"test.key\",\n\t\t},\n\t}\n\n\tfor name, test := range tests {\n\t\t\/\/ Run ctl create cr command with input options\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tstreams, _, _, _ := genericclioptions.NewTestIOStreams()\n\n\t\t\t\/\/ Options to run create CR command\n\t\t\topts := &certificaterequest.Options{\n\t\t\t\tCMClient:         cmCl,\n\t\t\t\tRESTConfig:       config,\n\t\t\t\tIOStreams:        streams,\n\t\t\t\tCmdNamespace:     test.inputNamespace,\n\t\t\t\tEnforceNamespace: test.inputNamespace != \"\",\n\t\t\t\tKeyFilename:      test.keyFilename,\n\t\t\t}\n\n\t\t\topts.Filenames = []string{test.inputFile}\n\n\t\t\terr := opts.Run(test.inputArgs)\n\t\t\tdefer cleanupFileIfExists(test.expName + \".key\")\n\n\t\t\tif err != nil {\n\t\t\t\tif !test.expErr {\n\t\t\t\t\tt.Errorf(\"got unexpected error when trying to create CR: %v\", err)\n\t\t\t\t}\n\t\t\t\tt.Logf(\"got an error, which was expected, details: %v\", err)\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\t\/\/ got no error\n\t\t\t\tif test.expErr {\n\t\t\t\t\tt.Errorf(\"expected but got no error when creating CR\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Finished creating CR, check if everything is expected\n\t\t\tcrName := test.inputArgs[0]\n\t\t\tgotCr, err := cmCl.CertmanagerV1alpha2().CertificateRequests(test.inputNamespace).Get(ctx, crName, metav1.GetOptions{})\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tif gotCr.Namespace != test.expNamespace {\n\t\t\t\tt.Errorf(\"CR created in unexpected Namespace, expected: %s, actual: %s\", test.expNamespace, gotCr.Namespace)\n\t\t\t}\n\n\t\t\tif gotCr.Name != test.expName {\n\t\t\t\tt.Errorf(\"CR created has unexpected Name, expectedL %s, actualL %s\", test.expName, gotCr.Name)\n\t\t\t}\n\n\t\t\t\/\/ Check the file where the private key is stored\n\t\t\tkeyData, err := ioutil.ReadFile(test.expKeyFilename)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"error when reading file storing private key: %v\", err)\n\t\t\t}\n\t\t\t_, err = pki.DecodePrivateKeyBytes(keyData)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"invalid private key: %v\", err)\n\t\t\t}\n\n\t\t\t\/\/ Clean up CertificateRequest\n\t\t\t\/\/ Everything is expected, so clean up with what is expected\n\t\t\terr = cmCl.CertmanagerV1alpha2().CertificateRequests(test.expNamespace).Delete(ctx, test.expName, metav1.DeleteOptions{})\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc cleanupFileIfExists(fileName string) {\n\t_, err := os.Stat(fileName)\n\tif err == nil {\n\t\terr = os.Remove(fileName)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package controller\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/oinume\/lekcije\/server\/config\"\n\t\"github.com\/oinume\/lekcije\/server\/errors\"\n\t\"github.com\/oinume\/lekcije\/server\/model\"\n)\n\nvar _ = fmt.Print\n\nfunc Static(w http.ResponseWriter, r *http.Request) {\n\thttp.ServeFile(w, r, r.URL.Path[1:])\n}\n\nfunc Index(w http.ResponseWriter, r *http.Request) {\n\tif _, err := model.GetLoggedInUser(r.Context()); err == nil {\n\t\thttp.Redirect(w, r, \"\/me\", http.StatusFound)\n\t} else {\n\t\tindexLogout(w, r)\n\t}\n}\n\nfunc indexLogout(w http.ResponseWriter, r *http.Request) {\n\tt := ParseHTMLTemplates(TemplatePath(\"index.html\"))\n\ttype Data struct {\n\t\tcommonTemplateData\n\t}\n\tdata := &Data{\n\t\tcommonTemplateData: getCommonTemplateData(r, false),\n\t}\n\n\tif err := t.Execute(w, data); err != nil {\n\t\tInternalServerError(w, errors.InternalWrapf(err, \"Failed to template.Execute()\"))\n\t\treturn\n\t}\n}\n\nfunc RobotsTxt(w http.ResponseWriter, r *http.Request) {\n\tcontent := `\nUser-agent: *\nAllow: \/\n`\n\t\/\/ TODO: sitemap https:\/\/www.lekcije.com\/sitemap.xml\n\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=utf-8\")\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintln(w, strings.TrimSpace(content))\n}\n\nfunc SitemapXML(w http.ResponseWriter, r *http.Request) {\n\tcontent := fmt.Sprintf(`\n<urlset xmlns=\"http:\/\/www.sitemaps.org\/schemas\/sitemap\/0.9\">\n  <url>\n    <loc>%s\/<\/loc>\n    <priority>1.0<\/priority>\n  <\/url>\n  <url>\n    <loc>%s\/terms<\/loc>\n    <priority>1.0<\/priority>\n  <\/url>\n<\/urlset>\n\t`, config.WebURL(), config.WebURL())\n\tw.Header().Set(\"Content-Type\", \"text\/xml; charset=utf-8\")\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintln(w, strings.TrimSpace(content))\n}\n\nfunc Terms(w http.ResponseWriter, r *http.Request) {\n\tt := ParseHTMLTemplates(TemplatePath(\"terms.html\"))\n\ttype Data struct {\n\t\tcommonTemplateData\n\t}\n\tdata := &Data{\n\t\tcommonTemplateData: getCommonTemplateData(r, false),\n\t}\n\n\tif err := t.Execute(w, data); err != nil {\n\t\tInternalServerError(w, errors.InternalWrapf(err, \"Failed to template.Execute()\"))\n\t\treturn\n\t}\n}\n<commit_msg>Add sitemap<commit_after>package controller\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/oinume\/lekcije\/server\/config\"\n\t\"github.com\/oinume\/lekcije\/server\/errors\"\n\t\"github.com\/oinume\/lekcije\/server\/model\"\n)\n\nvar _ = fmt.Print\n\nfunc Static(w http.ResponseWriter, r *http.Request) {\n\thttp.ServeFile(w, r, r.URL.Path[1:])\n}\n\nfunc Index(w http.ResponseWriter, r *http.Request) {\n\tif _, err := model.GetLoggedInUser(r.Context()); err == nil {\n\t\thttp.Redirect(w, r, \"\/me\", http.StatusFound)\n\t} else {\n\t\tindexLogout(w, r)\n\t}\n}\n\nfunc indexLogout(w http.ResponseWriter, r *http.Request) {\n\tt := ParseHTMLTemplates(TemplatePath(\"index.html\"))\n\ttype Data struct {\n\t\tcommonTemplateData\n\t}\n\tdata := &Data{\n\t\tcommonTemplateData: getCommonTemplateData(r, false),\n\t}\n\n\tif err := t.Execute(w, data); err != nil {\n\t\tInternalServerError(w, errors.InternalWrapf(err, \"Failed to template.Execute()\"))\n\t\treturn\n\t}\n}\n\nfunc RobotsTxt(w http.ResponseWriter, r *http.Request) {\n\tcontent := fmt.Sprintf(`\nUser-agent: *\nAllow: \/\nSitemap: %s\/sitemap.xml\n`, config.WebURL())\n\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=utf-8\")\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintln(w, strings.TrimSpace(content))\n}\n\nfunc SitemapXML(w http.ResponseWriter, r *http.Request) {\n\tcontent := fmt.Sprintf(`\n<urlset xmlns=\"http:\/\/www.sitemaps.org\/schemas\/sitemap\/0.9\">\n  <url>\n    <loc>%s\/<\/loc>\n    <priority>1.0<\/priority>\n  <\/url>\n  <url>\n    <loc>%s\/terms<\/loc>\n    <priority>1.0<\/priority>\n  <\/url>\n<\/urlset>\n\t`, config.WebURL(), config.WebURL())\n\tw.Header().Set(\"Content-Type\", \"text\/xml; charset=utf-8\")\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintln(w, strings.TrimSpace(content))\n}\n\nfunc Terms(w http.ResponseWriter, r *http.Request) {\n\tt := ParseHTMLTemplates(TemplatePath(\"terms.html\"))\n\ttype Data struct {\n\t\tcommonTemplateData\n\t}\n\tdata := &Data{\n\t\tcommonTemplateData: getCommonTemplateData(r, false),\n\t}\n\n\tif err := t.Execute(w, data); err != nil {\n\t\tInternalServerError(w, errors.InternalWrapf(err, \"Failed to template.Execute()\"))\n\t\treturn\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"github.com\/gorilla\/mux\"\n\t. \"gopkg.in\/check.v1\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"vip\/test\"\n)\n\nvar (\n\t_ = Suite(&UploadSuite{})\n)\n\ntype UploadSuite struct{}\n\nfunc (s *UploadSuite) SetUpSuite(c *C) {\n\tsetUpSuite(c)\n}\n\nfunc (s *UploadSuite) SetUpTest(c *C) {\n\tsetUpTest(c)\n\n\tstorage = test.NewStore()\n}\n\nfunc (s *UploadSuite) TestUpload(c *C) {\n\tauthToken = \"lalalatokenlalala\"\n\tos.Setenv(\"DOMAIN_DATA\", \"\")\n\n\trecorder := httptest.NewRecorder()\n\n\t\/\/ Mock up a router so that mux.Vars are passed\n\t\/\/ correctly\n\tm := mux.NewRouter()\n\tm.Handle(\"\/upload\/{bucket_id}\", verifyAuth(handleUpload))\n\tf, err := os.Open(\".\/test\/exif_test_img.jpg\")\n\tc.Assert(err, IsNil)\n\n\treq, err := http.NewRequest(\"POST\", \"http:\/\/localhost:8080\/upload\/samplebucket\", f)\n\tc.Assert(err, IsNil)\n\tfstat, err := os.Stat(\".\/test\/exif_test_img.jpg\")\n\tc.Assert(err, IsNil)\n\treq.ContentLength = fstat.Size()\n\treq.Header.Set(\"Content-Type\", \"image\/jpeg\")\n\treq.Header.Set(\"X-Vip-Token\", authToken)\n\n\tm.ServeHTTP(recorder, req)\n\n\tvar u UploadResponse\n\terr = json.NewDecoder(recorder.Body).Decode(&u)\n\tc.Assert(err, IsNil)\n\tc.Assert(len(u.Url), Not(Equals), 0)\n\n\turi, err := url.Parse(u.Url)\n\tc.Assert(err, IsNil)\n\n\tc.Assert(uri.Scheme, Equals, \"http\")\n\tc.Assert(uri.Host, Equals, \"localhost:8080\")\n\tc.Assert(uri.Path[1:13], Equals, \"samplebucket\")\n\tc.Assert(strings.HasSuffix(uri.Path, \"-2448x3264\"), Equals, true)\n\tc.Assert(recorder.HeaderMap[\"Content-Type\"][0], Equals, \"application\/json\")\n}\n\nfunc (s *UploadSuite) TestEmptyUpload(c *C) {\n\tauthToken = \"lalalatokenlalala\"\n\tos.Setenv(\"ALLOWED_ORIGIN\", \"\")\n\n\trecorder := httptest.NewRecorder()\n\n\t\/\/ Mock up a router so that mux.Vars are passed\n\t\/\/ correctly\n\tm := mux.NewRouter()\n\tm.Handle(\"\/upload\/{bucket_id}\", verifyAuth(handleUpload))\n\tf := &bytes.Reader{}\n\treq, err := http.NewRequest(\"POST\", \"http:\/\/localhost:8080\/upload\/samplebucket\", f)\n\tc.Assert(err, IsNil)\n\n\treq.Header.Set(\"Content-Type\", \"image\/jpeg\")\n\treq.Header.Set(\"X-Vip-Token\", authToken)\n\n\tm.ServeHTTP(recorder, req)\n\tc.Assert(recorder.Code, Equals, http.StatusBadRequest)\n\n\tvar u ErrorResponse\n\terr = json.NewDecoder(recorder.Body).Decode(&u)\n\tc.Assert(err, IsNil)\n\tc.Assert(u.Msg, Equals, \"File must have size greater than 0\")\n}\n\nfunc (s *UploadSuite) TestUnauthorizedUpload(c *C) {\n\tauthToken = \"lalalatokenlalala\"\n\tos.Setenv(\"ALLOWED_ORIGIN\", \"\")\n\n\trecorder := httptest.NewRecorder()\n\n\t\/\/ Mock up a router so that mux.Vars are passed\n\t\/\/ correctly\n\tm := mux.NewRouter()\n\tm.Handle(\"\/upload\/{bucket_id}\", verifyAuth(handleUpload))\n\n\tf, err := os.Open(\".\/test\/awesome.jpeg\")\n\tc.Assert(err, IsNil)\n\n\treq, err := http.NewRequest(\"POST\", \"http:\/\/localhost:8080\/upload\/samplebucket\", f)\n\n\tc.Assert(err, IsNil)\n\n\treq.Header.Set(\"Content-Type\", \"image\/jpeg\")\n\n\tm.ServeHTTP(recorder, req)\n\n\tc.Assert(recorder.Code, Equals, http.StatusUnauthorized)\n}\n\nfunc (s *UploadSuite) TestSetOriginData(c *C) {\n\tauthToken = \"heyheyheyimatoken\"\n\tos.Setenv(\"ALLOWED_ORIGIN\", \"WHATEVER, MAN\")\n\n\trecorder := httptest.NewRecorder()\n\n\tm := mux.NewRouter()\n\tm.Handle(\"\/upload\/{bucket_id}\", verifyAuth(handleUpload))\n\n\tf, err := os.Open(\".\/test\/awesome.jpeg\")\n\tc.Assert(err, IsNil)\n\n\treq, err := http.NewRequest(\"POST\", \"http:\/\/localhost:8080\/upload\/samplebucket\", f)\n\tc.Assert(err, IsNil)\n\tfstat, err := os.Stat(\".\/test\/awesome.jpeg\")\n\tc.Assert(err, IsNil)\n\treq.ContentLength = fstat.Size()\n\treq.Header.Set(\"Origin\", \"WHATEVER, MAN\")\n\tc.Assert(err, IsNil)\n\treq.Header.Set(\"Content-Type\", \"image\/jpeg\")\n\n\tm.ServeHTTP(recorder, req)\n\tc.Assert(recorder.Code, Equals, http.StatusCreated)\n}\n\n\/\/Check Content-Length of JPG File\nfunc (s *UploadSuite) TestContentLengthJpg(c *C) {\n\tf, err := os.Open(\".\/test\/exif_test_img.jpg\")\n\tc.Assert(err, IsNil)\n\n\tfstat, err := os.Stat(\".\/test\/exif_test_img.jpg\")\n\tc.Assert(err, IsNil)\n\n\tdata, err := processFile(f, \"image\/jpeg\", \"\")\n\tc.Assert(err, IsNil)\n\tc.Assert(data.Length, Not(Equals), fstat.Size())\n}\n\n\/\/Check Content-Length of PNG File\nfunc (s *UploadSuite) TestContentLengthPng(c *C) {\n\tf, err := os.Open(\".\/test\/test_inspiration.png\")\n\tc.Assert(err, IsNil)\n\n\tfstat, err := os.Stat(\".\/test\/test_inspiration.png\")\n\tc.Assert(err, IsNil)\n\n\tdata, err := processFile(f, \"image\/png\", \"\")\n\tc.Assert(err, IsNil)\n\tc.Assert(data.Length, Equals, fstat.Size())\n}\n<commit_msg>test upload warmup<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"github.com\/gorilla\/mux\"\n\t. \"gopkg.in\/check.v1\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"vip\/test\"\n)\n\nvar (\n\t_ = Suite(&UploadSuite{})\n)\n\ntype UploadSuite struct{}\n\nfunc (s *UploadSuite) SetUpSuite(c *C) {\n\tsetUpSuite(c)\n}\n\nfunc (s *UploadSuite) SetUpTest(c *C) {\n\tsetUpTest(c)\n\n\tstorage = test.NewStore()\n}\n\nfunc (s *UploadSuite) TestUpload(c *C) {\n\tauthToken = \"lalalatokenlalala\"\n\tos.Setenv(\"DOMAIN_DATA\", \"\")\n\n\trecorder := httptest.NewRecorder()\n\n\t\/\/ Mock up a router so that mux.Vars are passed\n\t\/\/ correctly\n\tm := mux.NewRouter()\n\tm.Handle(\"\/upload\/{bucket_id}\", verifyAuth(handleUpload))\n\tf, err := os.Open(\".\/test\/exif_test_img.jpg\")\n\tc.Assert(err, IsNil)\n\n\treq, err := http.NewRequest(\"POST\", \"http:\/\/localhost:8080\/upload\/samplebucket\", f)\n\tc.Assert(err, IsNil)\n\tfstat, err := os.Stat(\".\/test\/exif_test_img.jpg\")\n\tc.Assert(err, IsNil)\n\treq.ContentLength = fstat.Size()\n\treq.Header.Set(\"Content-Type\", \"image\/jpeg\")\n\treq.Header.Set(\"X-Vip-Token\", authToken)\n\n\tm.ServeHTTP(recorder, req)\n\n\tvar u UploadResponse\n\terr = json.NewDecoder(recorder.Body).Decode(&u)\n\tc.Assert(err, IsNil)\n\tc.Assert(len(u.Url), Not(Equals), 0)\n\n\turi, err := url.Parse(u.Url)\n\tc.Assert(err, IsNil)\n\n\tc.Assert(uri.Scheme, Equals, \"http\")\n\tc.Assert(uri.Host, Equals, \"localhost:8080\")\n\tc.Assert(uri.Path[1:13], Equals, \"samplebucket\")\n\tc.Assert(strings.HasSuffix(uri.Path, \"-2448x3264\"), Equals, true)\n\tc.Assert(recorder.HeaderMap[\"Content-Type\"][0], Equals, \"application\/json\")\n}\n\nfunc (s *UploadSuite) TestUploadWarmup(c *C) {\n\tauthToken = \"lalalatokenlalala\"\n\tos.Setenv(\"DOMAIN_DATA\", \"\")\n\n\trecorder := httptest.NewRecorder()\n\n\t\/\/ Mock up a router so that mux.Vars are passed\n\t\/\/ correctly\n\tm := mux.NewRouter()\n\tm.Handle(\"\/upload\/{bucket_id}\", verifyAuth(handleUpload))\n\tf, err := os.Open(\".\/test\/exif_test_img.jpg\")\n\tc.Assert(err, IsNil)\n\n\treq, err := http.NewRequest(\"POST\", \"http:\/\/localhost:8080\/upload\/samplebucket\", f)\n\tc.Assert(err, IsNil)\n\tfstat, err := os.Stat(\".\/test\/exif_test_img.jpg\")\n\tc.Assert(err, IsNil)\n\treq.ContentLength = fstat.Size()\n\treq.Header.Set(\"X-Vip-Warmup\", \"s=3,s=100&c=true\")\n\treq.Header.Set(\"Content-Type\", \"image\/jpeg\")\n\treq.Header.Set(\"X-Vip-Token\", authToken)\n\n\tm.ServeHTTP(recorder, req)\n\n\tvar u UploadResponse\n\terr = json.NewDecoder(recorder.Body).Decode(&u)\n\tc.Assert(err, IsNil)\n}\n\nfunc (s *UploadSuite) TestEmptyUpload(c *C) {\n\tauthToken = \"lalalatokenlalala\"\n\tos.Setenv(\"ALLOWED_ORIGIN\", \"\")\n\n\trecorder := httptest.NewRecorder()\n\n\t\/\/ Mock up a router so that mux.Vars are passed\n\t\/\/ correctly\n\tm := mux.NewRouter()\n\tm.Handle(\"\/upload\/{bucket_id}\", verifyAuth(handleUpload))\n\tf := &bytes.Reader{}\n\treq, err := http.NewRequest(\"POST\", \"http:\/\/localhost:8080\/upload\/samplebucket\", f)\n\tc.Assert(err, IsNil)\n\n\treq.Header.Set(\"Content-Type\", \"image\/jpeg\")\n\treq.Header.Set(\"X-Vip-Token\", authToken)\n\n\tm.ServeHTTP(recorder, req)\n\tc.Assert(recorder.Code, Equals, http.StatusBadRequest)\n\n\tvar u ErrorResponse\n\terr = json.NewDecoder(recorder.Body).Decode(&u)\n\tc.Assert(err, IsNil)\n\tc.Assert(u.Msg, Equals, \"File must have size greater than 0\")\n}\n\nfunc (s *UploadSuite) TestUnauthorizedUpload(c *C) {\n\tauthToken = \"lalalatokenlalala\"\n\tos.Setenv(\"ALLOWED_ORIGIN\", \"\")\n\n\trecorder := httptest.NewRecorder()\n\n\t\/\/ Mock up a router so that mux.Vars are passed\n\t\/\/ correctly\n\tm := mux.NewRouter()\n\tm.Handle(\"\/upload\/{bucket_id}\", verifyAuth(handleUpload))\n\n\tf, err := os.Open(\".\/test\/awesome.jpeg\")\n\tc.Assert(err, IsNil)\n\n\treq, err := http.NewRequest(\"POST\", \"http:\/\/localhost:8080\/upload\/samplebucket\", f)\n\n\tc.Assert(err, IsNil)\n\n\treq.Header.Set(\"Content-Type\", \"image\/jpeg\")\n\n\tm.ServeHTTP(recorder, req)\n\n\tc.Assert(recorder.Code, Equals, http.StatusUnauthorized)\n}\n\nfunc (s *UploadSuite) TestSetOriginData(c *C) {\n\tauthToken = \"heyheyheyimatoken\"\n\tos.Setenv(\"ALLOWED_ORIGIN\", \"WHATEVER, MAN\")\n\n\trecorder := httptest.NewRecorder()\n\n\tm := mux.NewRouter()\n\tm.Handle(\"\/upload\/{bucket_id}\", verifyAuth(handleUpload))\n\n\tf, err := os.Open(\".\/test\/awesome.jpeg\")\n\tc.Assert(err, IsNil)\n\n\treq, err := http.NewRequest(\"POST\", \"http:\/\/localhost:8080\/upload\/samplebucket\", f)\n\tc.Assert(err, IsNil)\n\tfstat, err := os.Stat(\".\/test\/awesome.jpeg\")\n\tc.Assert(err, IsNil)\n\treq.ContentLength = fstat.Size()\n\treq.Header.Set(\"Origin\", \"WHATEVER, MAN\")\n\tc.Assert(err, IsNil)\n\treq.Header.Set(\"Content-Type\", \"image\/jpeg\")\n\n\tm.ServeHTTP(recorder, req)\n\tc.Assert(recorder.Code, Equals, http.StatusCreated)\n}\n\n\/\/Check Content-Length of JPG File\nfunc (s *UploadSuite) TestContentLengthJpg(c *C) {\n\tf, err := os.Open(\".\/test\/exif_test_img.jpg\")\n\tc.Assert(err, IsNil)\n\n\tfstat, err := os.Stat(\".\/test\/exif_test_img.jpg\")\n\tc.Assert(err, IsNil)\n\n\tdata, err := processFile(f, \"image\/jpeg\", \"\")\n\tc.Assert(err, IsNil)\n\tc.Assert(data.Length, Not(Equals), fstat.Size())\n}\n\n\/\/Check Content-Length of PNG File\nfunc (s *UploadSuite) TestContentLengthPng(c *C) {\n\tf, err := os.Open(\".\/test\/test_inspiration.png\")\n\tc.Assert(err, IsNil)\n\n\tfstat, err := os.Stat(\".\/test\/test_inspiration.png\")\n\tc.Assert(err, IsNil)\n\n\tdata, err := processFile(f, \"image\/png\", \"\")\n\tc.Assert(err, IsNil)\n\tc.Assert(data.Length, Equals, fstat.Size())\n}\n<|endoftext|>"}
{"text":"<commit_before>package util\n\nimport (\n\t\"crypto\/aes\"\n\t\"crypto\/cipher\"\n\t\"crypto\/hmac\"\n\t\"crypto\/md5\"\n\t\"crypto\/sha256\"\n\t\"encoding\/base64\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"hash\"\n\t\"strings\"\n)\n\n\/\/ 微信签名算法方式\nconst (\n\tSignTypeMD5        = `MD5`\n\tSignTypeHMACSHA256 = `HMAC-SHA256`\n)\n\n\/\/EncryptMsg 加密消息\nfunc EncryptMsg(random, rawXMLMsg []byte, appID, aesKey string) (encrtptMsg []byte, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"panic error: err=%v\", e)\n\t\t\treturn\n\t\t}\n\t}()\n\tvar key []byte\n\tkey, err = aesKeyDecode(aesKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tciphertext := AESEncryptMsg(random, rawXMLMsg, appID, key)\n\tencrtptMsg = []byte(base64.StdEncoding.EncodeToString(ciphertext))\n\treturn\n}\n\n\/\/AESEncryptMsg ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]\n\/\/参考：github.com\/chanxuehong\/wechat.v2\nfunc AESEncryptMsg(random, rawXMLMsg []byte, appID string, aesKey []byte) (ciphertext []byte) {\n\tconst (\n\t\tBlockSize = 32            \/\/ PKCS#7\n\t\tBlockMask = BlockSize - 1 \/\/ BLOCK_SIZE 为 2^n 时, 可以用 mask 获取针对 BLOCK_SIZE 的余数\n\t)\n\n\tappIDOffset := 20 + len(rawXMLMsg)\n\tcontentLen := appIDOffset + len(appID)\n\tamountToPad := BlockSize - contentLen&BlockMask\n\tplaintextLen := contentLen + amountToPad\n\n\tplaintext := make([]byte, plaintextLen)\n\n\t\/\/ 拼接\n\tcopy(plaintext[:16], random)\n\tencodeNetworkByteOrder(plaintext[16:20], uint32(len(rawXMLMsg)))\n\tcopy(plaintext[20:], rawXMLMsg)\n\tcopy(plaintext[appIDOffset:], appID)\n\n\t\/\/ PKCS#7 补位\n\tfor i := contentLen; i < plaintextLen; i++ {\n\t\tplaintext[i] = byte(amountToPad)\n\t}\n\n\t\/\/ 加密\n\tblock, err := aes.NewCipher(aesKey[:])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tmode := cipher.NewCBCEncrypter(block, aesKey[:16])\n\tmode.CryptBlocks(plaintext, plaintext)\n\n\tciphertext = plaintext\n\treturn\n}\n\n\/\/DecryptMsg 消息解密\nfunc DecryptMsg(appID, encryptedMsg, aesKey string) (random, rawMsgXMLBytes []byte, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"panic error: err=%v\", e)\n\t\t\treturn\n\t\t}\n\t}()\n\tvar encryptedMsgBytes, key, getAppIDBytes []byte\n\tencryptedMsgBytes, err = base64.StdEncoding.DecodeString(encryptedMsg)\n\tif err != nil {\n\t\treturn\n\t}\n\tkey, err = aesKeyDecode(aesKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trandom, rawMsgXMLBytes, getAppIDBytes, err = AESDecryptMsg(encryptedMsgBytes, key)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"消息解密失败,%v\", err)\n\t\treturn\n\t}\n\tif appID != string(getAppIDBytes) {\n\t\terr = fmt.Errorf(\"消息解密校验APPID失败\")\n\t\treturn\n\t}\n\treturn\n}\n\nfunc aesKeyDecode(encodedAESKey string) (key []byte, err error) {\n\tif len(encodedAESKey) != 43 {\n\t\terr = fmt.Errorf(\"the length of encodedAESKey must be equal to 43\")\n\t\treturn\n\t}\n\tkey, err = base64.StdEncoding.DecodeString(encodedAESKey + \"=\")\n\tif err != nil {\n\t\treturn\n\t}\n\tif len(key) != 32 {\n\t\terr = fmt.Errorf(\"encodingAESKey invalid\")\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/ AESDecryptMsg ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]\n\/\/参考：github.com\/chanxuehong\/wechat.v2\nfunc AESDecryptMsg(ciphertext []byte, aesKey []byte) (random, rawXMLMsg, appID []byte, err error) {\n\tconst (\n\t\tBlockSize = 32            \/\/ PKCS#7\n\t\tBlockMask = BlockSize - 1 \/\/ BLOCK_SIZE 为 2^n 时, 可以用 mask 获取针对 BLOCK_SIZE 的余数\n\t)\n\n\tif len(ciphertext) < BlockSize {\n\t\terr = fmt.Errorf(\"the length of ciphertext too short: %d\", len(ciphertext))\n\t\treturn\n\t}\n\tif len(ciphertext)&BlockMask != 0 {\n\t\terr = fmt.Errorf(\"ciphertext is not a multiple of the block size, the length is %d\", len(ciphertext))\n\t\treturn\n\t}\n\n\tplaintext := make([]byte, len(ciphertext)) \/\/ len(plaintext) >= BLOCK_SIZE\n\n\t\/\/ 解密\n\tblock, err := aes.NewCipher(aesKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tmode := cipher.NewCBCDecrypter(block, aesKey[:16])\n\tmode.CryptBlocks(plaintext, ciphertext)\n\n\t\/\/ PKCS#7 去除补位\n\tamountToPad := int(plaintext[len(plaintext)-1])\n\tif amountToPad < 1 || amountToPad > BlockSize {\n\t\terr = fmt.Errorf(\"the amount to pad is incorrect: %d\", amountToPad)\n\t\treturn\n\t}\n\tplaintext = plaintext[:len(plaintext)-amountToPad]\n\n\t\/\/ 反拼接\n\t\/\/ len(plaintext) == 16+4+len(rawXMLMsg)+len(appId)\n\tif len(plaintext) <= 20 {\n\t\terr = fmt.Errorf(\"plaintext too short, the length is %d\", len(plaintext))\n\t\treturn\n\t}\n\trawXMLMsgLen := int(decodeNetworkByteOrder(plaintext[16:20]))\n\tif rawXMLMsgLen < 0 {\n\t\terr = fmt.Errorf(\"incorrect msg length: %d\", rawXMLMsgLen)\n\t\treturn\n\t}\n\tappIDOffset := 20 + rawXMLMsgLen\n\tif len(plaintext) <= appIDOffset {\n\t\terr = fmt.Errorf(\"msg length too large: %d\", rawXMLMsgLen)\n\t\treturn\n\t}\n\n\trandom = plaintext[:16:20]\n\trawXMLMsg = plaintext[20:appIDOffset:appIDOffset]\n\tappID = plaintext[appIDOffset:]\n\treturn\n}\n\n\/\/ 把整数 n 格式化成 4 字节的网络字节序\nfunc encodeNetworkByteOrder(orderBytes []byte, n uint32) {\n\torderBytes[0] = byte(n >> 24)\n\torderBytes[1] = byte(n >> 16)\n\torderBytes[2] = byte(n >> 8)\n\torderBytes[3] = byte(n)\n}\n\n\/\/ 从 4 字节的网络字节序里解析出整数\nfunc decodeNetworkByteOrder(orderBytes []byte) (n uint32) {\n\treturn uint32(orderBytes[0])<<24 |\n\t\tuint32(orderBytes[1])<<16 |\n\t\tuint32(orderBytes[2])<<8 |\n\t\tuint32(orderBytes[3])\n}\n\n\/\/ CalculateSign 计算签名\nfunc CalculateSign(content, signType, key string) (string, error) {\n\tvar h hash.Hash\n\tif signType == SignTypeMD5 {\n\t\th = md5.New()\n\t} else {\n\t\th = hmac.New(sha256.New, []byte(key))\n\t}\n\n\tif _, err := h.Write([]byte(content)); err != nil {\n\t\treturn ``, err\n\t}\n\treturn strings.ToUpper(hex.EncodeToString(h.Sum(nil))), nil\n}\n\n\/\/ ParamSign 计算所传参数的签名\nfunc ParamSign(p map[string]string, key string) (string, error) {\n\tbizKey := \"&key=\" + key\n\tstr := OrderParam(p, bizKey)\n\n\tvar signType string\n\tswitch p[\"sign_type\"] {\n\tcase SignTypeMD5, SignTypeHMACSHA256:\n\t\tsignType = p[\"sign_type\"]\n\tcase ``:\n\t\tsignType = SignTypeMD5\n\tdefault:\n\t\treturn ``, errors.New(`invalid sign_type`)\n\t}\n\n\treturn CalculateSign(str, signType, key)\n}\n<commit_msg>fix:修复微信回调signType为空的问题 #282 (#283)<commit_after>package util\n\nimport (\n\t\"crypto\/aes\"\n\t\"crypto\/cipher\"\n\t\"crypto\/hmac\"\n\t\"crypto\/md5\"\n\t\"crypto\/sha256\"\n\t\"encoding\/base64\"\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"hash\"\n\t\"strings\"\n)\n\n\/\/ 微信签名算法方式\nconst (\n\tSignTypeMD5        = `MD5`\n\tSignTypeHMACSHA256 = `HMAC-SHA256`\n)\n\n\/\/EncryptMsg 加密消息\nfunc EncryptMsg(random, rawXMLMsg []byte, appID, aesKey string) (encrtptMsg []byte, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"panic error: err=%v\", e)\n\t\t\treturn\n\t\t}\n\t}()\n\tvar key []byte\n\tkey, err = aesKeyDecode(aesKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tciphertext := AESEncryptMsg(random, rawXMLMsg, appID, key)\n\tencrtptMsg = []byte(base64.StdEncoding.EncodeToString(ciphertext))\n\treturn\n}\n\n\/\/AESEncryptMsg ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]\n\/\/参考：github.com\/chanxuehong\/wechat.v2\nfunc AESEncryptMsg(random, rawXMLMsg []byte, appID string, aesKey []byte) (ciphertext []byte) {\n\tconst (\n\t\tBlockSize = 32            \/\/ PKCS#7\n\t\tBlockMask = BlockSize - 1 \/\/ BLOCK_SIZE 为 2^n 时, 可以用 mask 获取针对 BLOCK_SIZE 的余数\n\t)\n\n\tappIDOffset := 20 + len(rawXMLMsg)\n\tcontentLen := appIDOffset + len(appID)\n\tamountToPad := BlockSize - contentLen&BlockMask\n\tplaintextLen := contentLen + amountToPad\n\n\tplaintext := make([]byte, plaintextLen)\n\n\t\/\/ 拼接\n\tcopy(plaintext[:16], random)\n\tencodeNetworkByteOrder(plaintext[16:20], uint32(len(rawXMLMsg)))\n\tcopy(plaintext[20:], rawXMLMsg)\n\tcopy(plaintext[appIDOffset:], appID)\n\n\t\/\/ PKCS#7 补位\n\tfor i := contentLen; i < plaintextLen; i++ {\n\t\tplaintext[i] = byte(amountToPad)\n\t}\n\n\t\/\/ 加密\n\tblock, err := aes.NewCipher(aesKey[:])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tmode := cipher.NewCBCEncrypter(block, aesKey[:16])\n\tmode.CryptBlocks(plaintext, plaintext)\n\n\tciphertext = plaintext\n\treturn\n}\n\n\/\/DecryptMsg 消息解密\nfunc DecryptMsg(appID, encryptedMsg, aesKey string) (random, rawMsgXMLBytes []byte, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"panic error: err=%v\", e)\n\t\t\treturn\n\t\t}\n\t}()\n\tvar encryptedMsgBytes, key, getAppIDBytes []byte\n\tencryptedMsgBytes, err = base64.StdEncoding.DecodeString(encryptedMsg)\n\tif err != nil {\n\t\treturn\n\t}\n\tkey, err = aesKeyDecode(aesKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\trandom, rawMsgXMLBytes, getAppIDBytes, err = AESDecryptMsg(encryptedMsgBytes, key)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"消息解密失败,%v\", err)\n\t\treturn\n\t}\n\tif appID != string(getAppIDBytes) {\n\t\terr = fmt.Errorf(\"消息解密校验APPID失败\")\n\t\treturn\n\t}\n\treturn\n}\n\nfunc aesKeyDecode(encodedAESKey string) (key []byte, err error) {\n\tif len(encodedAESKey) != 43 {\n\t\terr = fmt.Errorf(\"the length of encodedAESKey must be equal to 43\")\n\t\treturn\n\t}\n\tkey, err = base64.StdEncoding.DecodeString(encodedAESKey + \"=\")\n\tif err != nil {\n\t\treturn\n\t}\n\tif len(key) != 32 {\n\t\terr = fmt.Errorf(\"encodingAESKey invalid\")\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/ AESDecryptMsg ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]\n\/\/参考：github.com\/chanxuehong\/wechat.v2\nfunc AESDecryptMsg(ciphertext []byte, aesKey []byte) (random, rawXMLMsg, appID []byte, err error) {\n\tconst (\n\t\tBlockSize = 32            \/\/ PKCS#7\n\t\tBlockMask = BlockSize - 1 \/\/ BLOCK_SIZE 为 2^n 时, 可以用 mask 获取针对 BLOCK_SIZE 的余数\n\t)\n\n\tif len(ciphertext) < BlockSize {\n\t\terr = fmt.Errorf(\"the length of ciphertext too short: %d\", len(ciphertext))\n\t\treturn\n\t}\n\tif len(ciphertext)&BlockMask != 0 {\n\t\terr = fmt.Errorf(\"ciphertext is not a multiple of the block size, the length is %d\", len(ciphertext))\n\t\treturn\n\t}\n\n\tplaintext := make([]byte, len(ciphertext)) \/\/ len(plaintext) >= BLOCK_SIZE\n\n\t\/\/ 解密\n\tblock, err := aes.NewCipher(aesKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tmode := cipher.NewCBCDecrypter(block, aesKey[:16])\n\tmode.CryptBlocks(plaintext, ciphertext)\n\n\t\/\/ PKCS#7 去除补位\n\tamountToPad := int(plaintext[len(plaintext)-1])\n\tif amountToPad < 1 || amountToPad > BlockSize {\n\t\terr = fmt.Errorf(\"the amount to pad is incorrect: %d\", amountToPad)\n\t\treturn\n\t}\n\tplaintext = plaintext[:len(plaintext)-amountToPad]\n\n\t\/\/ 反拼接\n\t\/\/ len(plaintext) == 16+4+len(rawXMLMsg)+len(appId)\n\tif len(plaintext) <= 20 {\n\t\terr = fmt.Errorf(\"plaintext too short, the length is %d\", len(plaintext))\n\t\treturn\n\t}\n\trawXMLMsgLen := int(decodeNetworkByteOrder(plaintext[16:20]))\n\tif rawXMLMsgLen < 0 {\n\t\terr = fmt.Errorf(\"incorrect msg length: %d\", rawXMLMsgLen)\n\t\treturn\n\t}\n\tappIDOffset := 20 + rawXMLMsgLen\n\tif len(plaintext) <= appIDOffset {\n\t\terr = fmt.Errorf(\"msg length too large: %d\", rawXMLMsgLen)\n\t\treturn\n\t}\n\n\trandom = plaintext[:16:20]\n\trawXMLMsg = plaintext[20:appIDOffset:appIDOffset]\n\tappID = plaintext[appIDOffset:]\n\treturn\n}\n\n\/\/ 把整数 n 格式化成 4 字节的网络字节序\nfunc encodeNetworkByteOrder(orderBytes []byte, n uint32) {\n\torderBytes[0] = byte(n >> 24)\n\torderBytes[1] = byte(n >> 16)\n\torderBytes[2] = byte(n >> 8)\n\torderBytes[3] = byte(n)\n}\n\n\/\/ 从 4 字节的网络字节序里解析出整数\nfunc decodeNetworkByteOrder(orderBytes []byte) (n uint32) {\n\treturn uint32(orderBytes[0])<<24 |\n\t\tuint32(orderBytes[1])<<16 |\n\t\tuint32(orderBytes[2])<<8 |\n\t\tuint32(orderBytes[3])\n}\n\n\/\/ CalculateSign 计算签名\nfunc CalculateSign(content, signType, key string) (string, error) {\n\tvar h hash.Hash\n\tif signType == SignTypeHMACSHA256 {\n\t\th = hmac.New(sha256.New, []byte(key))\n\t} else {\n\t\th = md5.New()\n\t}\n\n\tif _, err := h.Write([]byte(content)); err != nil {\n\t\treturn ``, err\n\t}\n\treturn strings.ToUpper(hex.EncodeToString(h.Sum(nil))), nil\n}\n\n\/\/ ParamSign 计算所传参数的签名\nfunc ParamSign(p map[string]string, key string) (string, error) {\n\tbizKey := \"&key=\" + key\n\tstr := OrderParam(p, bizKey)\n\n\tvar signType string\n\tswitch p[\"sign_type\"] {\n\tcase SignTypeMD5, SignTypeHMACSHA256:\n\t\tsignType = p[\"sign_type\"]\n\tcase ``:\n\t\tsignType = SignTypeMD5\n\tdefault:\n\t\treturn ``, errors.New(`invalid sign_type`)\n\t}\n\n\treturn CalculateSign(str, signType, key)\n}\n<|endoftext|>"}
{"text":"<commit_before>package util\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"time\"\n)\n\ntype githubResponse struct {\n\tName string `json:\"name\"`\n}\n\n\/\/ CheckForRigUpdate checks to see if an upgrdate to rig is available, if so, return a message\nfunc CheckForRigUpdate(curRigVersion string) string {\n\t\/\/ Do we want to do sematic version checking?\n\tif tag, err := currentRigReleaseTag(); err != nil {\n\t\treturn \"\"\n\t} else if tag != curRigVersion {\n\t\treturn \"An update for rig is available: \" + tag\n\t}\n\treturn \"\"\n}\n\n\/\/ Return the current release tag for rig\nfunc currentRigReleaseTag() (string, error) {\n\t\/\/ Fetch some json from github containing the latest release name\n\turl := \"https:\/\/api.github.com\/repos\/phase2\/rig\/releases\/latest\"\n\tclient := http.Client{\n\t\tTimeout: time.Second * 2, \/\/ Maximum of 2 secs\n\t}\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\tif Logger().IsVerbose {\n\t\t\tLogger().Warning(\"NewRequest %s failed:\\n%s\", url, err)\n\t\t}\n\t\treturn \"\", err\n\t}\n\t\/\/ Execute the request\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tif Logger().IsVerbose {\n\t\t\tLogger().Warning(\"GET %s failed:\\n%s\", url, err)\n\t\t}\n\t\treturn \"\", err\n\t}\n\t\/\/ Collect the response\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tif Logger().IsVerbose {\n\t\t\tLogger().Warning(\"ReadAll %s failed:\\n%s\", url, err)\n\t\t}\n\t\treturn \"\", err\n\t}\n\tif response.StatusCode != 200 {\n\t\tif Logger().IsVerbose {\n\t\t\tLogger().Warning(\"ReadAll %s failed: %s\", url, response.Status)\n\t\t}\n\t\treturn \"\", errors.New(response.Status)\n\t}\n\t\/\/ Decode the json, pick off the name field\n\tdecoder := githubResponse{}\n\tif err = json.Unmarshal(body, &decoder); err != nil {\n\t\tif Logger().IsVerbose {\n\t\t\tLogger().Warning(\"Unmarshal %s failed:\\n%s\", url, err)\n\t\t}\n\t\treturn \"\", err\n\t}\n\tif Logger().IsVerbose {\n\t\tLogger().Info(\"rig current release tag: %s\", decoder.Name)\n\t}\n\treturn decoder.Name, nil\n}\n<commit_msg>Fix linting error<commit_after>package util\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"time\"\n)\n\ntype githubResponse struct {\n\tName string `json:\"name\"`\n}\n\n\/\/ CheckForRigUpdate checks to see if an upgrdate to rig is available, if so, return a message\nfunc CheckForRigUpdate(curRigVersion string) string {\n\t\/\/ Do we want to do sematic version checking?\n\tif tag, err := currentRigReleaseTag(); err != nil {\n\t\treturn \"\"\n\t} else if tag != curRigVersion {\n\t\treturn \"An update for rig is available: \" + tag\n\t}\n\treturn \"\"\n}\n\n\/\/ Return the current release tag for rig\nfunc currentRigReleaseTag() (string, error) {\n\t\/\/ Fetch some json from github containing the latest release name\n\turl := \"https:\/\/api.github.com\/repos\/phase2\/rig\/releases\/latest\"\n\tresponse, err := getRigReleaseTagResponse(url)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer response.Body.Close()\n\t\/\/ Collect the response\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\tif Logger().IsVerbose {\n\t\t\tLogger().Warning(\"ReadAll %s failed:\\n%s\", url, err)\n\t\t}\n\t\treturn \"\", err\n\t}\n\tif response.StatusCode != 200 {\n\t\tif Logger().IsVerbose {\n\t\t\tLogger().Warning(\"ReadAll %s failed: %s\", url, response.Status)\n\t\t}\n\t\treturn \"\", errors.New(response.Status)\n\t}\n\t\/\/ Decode the json, pick off the name field\n\tdecoder := githubResponse{}\n\tif err = json.Unmarshal(body, &decoder); err != nil {\n\t\tif Logger().IsVerbose {\n\t\t\tLogger().Warning(\"Unmarshal %s failed:\\n%s\", url, err)\n\t\t}\n\t\treturn \"\", err\n\t}\n\tif Logger().IsVerbose {\n\t\tLogger().Info(\"rig current release tag: %s\", decoder.Name)\n\t}\n\treturn decoder.Name, nil\n}\n\nfunc getRigReleaseTagResponse(url string) (*http.Response, error) {\n\tclient := http.Client{\n\t\tTimeout: time.Second * 2, \/\/ Maximum of 2 secs\n\t}\n\treq, err := http.NewRequest(http.MethodGet, url, nil)\n\tif err != nil {\n\t\tif Logger().IsVerbose {\n\t\t\tLogger().Warning(\"NewRequest %s failed:\\n%s\", url, err)\n\t\t}\n\t\treturn nil, err\n\t}\n\t\/\/ Execute the request\n\tresponse, err := client.Do(req)\n\tif err != nil {\n\t\tif Logger().IsVerbose {\n\t\t\tLogger().Warning(\"GET %s failed:\\n%s\", url, err)\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn response, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package utils\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"image\/color\"\n\t\"math\"\n\t\"strconv\"\n)\n\n\/*********\tStart \tDrawCircle ********\/\n\nfunc DrawCircle(centerX, centerY, radius, thick int, c color.RGBA, rgba *image.RGBA) {\n\tminX, maxX := centerX-radius-thick, centerX+radius+thick\n\tminY, maxY := centerY-radius-thick, centerY+radius+thick\n\tfor x := minX; x < maxX; x++ {\n\t\tfor y := minY; y < maxY; y++ {\n\t\t\tif possibleCirclePoint(centerX, centerY, x, y, radius, thick) {\n\t\t\t\trgba.Set(x, y, c)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc possibleCirclePoint(cx, cy, x, y, r, thick int) bool {\n\tdx, dy := cx-x, cy-y\n\tif (dx*dx+dy*dy > (r+thick)*(r+thick)) || (dx*dx+dy*dy < (r-thick)*(r-thick)) {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/*********  Start   DrawLine   ********\/\nfunc DrawLine(x0, y0, x1, y1, thick int, c color.RGBA, rgba *image.RGBA) {\n\tdx := math.Abs(float64(x1 - x0))\n\tdy := math.Abs(float64(y1 - y0))\n\tsx, sy := 1, 1\n\tif x0 >= x1 {\n\t\tsx = -1\n\t}\n\tif y0 >= y1 {\n\t\tsy = -1\n\t}\n\terr := dx - dy\n\tfor {\n\t\trgba.Set(x0, y0, c)\n\t\tfor i := 1; i <= thick; i++ {\n\t\t\trgba.Set(x0+i, y0, c)\n\t\t\trgba.Set(x0, y0+i, c)\n\t\t}\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\treturn\n\t\t}\n\t\te2 := err * 2\n\t\tif e2 > -dy {\n\t\t\terr -= dy\n\t\t\tx0 += sx\n\t\t}\n\t\tif e2 < dx {\n\t\t\terr += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n}\n\n\/*\n\t*********  Start   DrawDataLineByData   ********\n\tThe first parameter is a map\n\tIn this map, string is the subject's title on each vertex\n*\/\nfunc DrawDataLineByData(data map[string]int, thick int, rgba *image.RGBA, lineColor, fontColor color.RGBA) {\n\t\/*\n\t\t1st layer -- 1000\n\t\t2nd layer -- 500\n\t\t3rd layer -- 100\n\t*\/\n\tcenterX, centerY := rgba.Bounds().Max.X\/2, rgba.Bounds().Max.Y\/2\n\tradius, radians := GetRadiusRadians(rgba, len(data))\n\n\tcc, n := 0, len(data)\n\tx0, x1, fx, y0, y1, fy := 0, 0, 0, 0, 0, 0\n\n\tfor key, v := range data {\n\t\ttmpRadians := radians * float64(cc)\n\t\tx0, y0 = x1, y1\n\t\tvar tmp float64\n\t\tif v <= 100 {\n\t\t\ttmp = float64(v) \/ float64(100) \/ 3\n\t\t} else if v > 100 && v <= 500 {\n\t\t\ttmp = float64(1.0\/3.0) + float64(v-100)\/float64(400)\/3\n\t\t} else if v > 500 && v <= 1000 {\n\t\t\ttmp = float64(2.0\/3.0) + float64(v-500)\/float64(500)\/3\n\t\t} else {\n\t\t\ttmp = 1.0\n\t\t}\n\n\t\tx1 = ToInt(math.Sin(tmpRadians)*tmp*float64(radius)) + centerX\n\t\ty1 = ToInt(math.Cos(tmpRadians)*tmp*float64(radius)) + centerY\n\n\t\tif cc == 0 {\n\t\t\tfx, fy = x1, y1\n\t\t} else if cc < n-1 {\n\t\t\tDrawLine(x0, y0, x1, y1, thick, lineColor, rgba)\n\t\t} else if cc == n-1 {\n\t\t\tDrawLine(x0, y0, x1, y1, thick, lineColor, rgba)\n\t\t\tDrawLine(fx, fy, x1, y1, thick, lineColor, rgba)\n\t\t}\n\t\t\/\/DrawString\n\t\ttx, ty := calFontPosition(x1, y1, centerX, centerY)\n\t\tDrawString(tx, ty, key, rgba, fontColor)\n\t\tcc++\n\t}\n}\n\n\/*\n\t*********  Start   DrawDataLineByPercentage   ********\n\tThe first parameter is a map\n\tIn this map, string is the subject's title on each vertex\n*\/\nfunc DrawDataLineByPercentage(data map[string]int, thick int, rgba *image.RGBA, lineColor, fontColor color.RGBA) {\n\tvar sum float64\n\tfor _, v := range data {\n\t\tsum += float64(v)\n\t}\n\t\/*\n\t\t1st layer -- 100%\n\t\t2nd layer -- 40%\n\t\t3rd layer -- 5%\n\t*\/\n\tcenterX, centerY := rgba.Bounds().Max.X\/2, rgba.Bounds().Max.Y\/2\n\tradius, radians := GetRadiusRadians(rgba, len(data))\n\n\tcc, n := 0, len(data)\n\tx0, x1, fx, y0, y1, fy := 0, 0, 0, 0, 0, 0\n\n\tfor key, v := range data {\n\t\tfmt.Println(v, float64(v)\/sum, getVertexPerByPer(v, sum))\n\n\t\ttmpRadians := radians * float64(cc)\n\t\tx0, y0 = x1, y1\n\t\tper := getVertexPerByPer(v, sum)\n\t\t\/\/ per := float64(v) \/ sum\n\n\t\t\/\/ if per <= 0.05 {\n\t\t\/\/ \tper = per \/ 0.05 \/ 3\n\t\t\/\/ } else if per > 0.05 && per <= 0.4 {\n\t\t\/\/ \tper = float64(1.0\/3.0) + float64((per-0.05)\/0.35\/3)\n\t\t\/\/ } else if per > 0.4 && per <= 1 {\n\t\t\/\/ \tper = float64(2.0\/3.0) + float64((per-0.4)\/0.6\/3)\n\t\t\/\/}\n\n\t\tx1 = ToInt(math.Sin(tmpRadians)*per*float64(radius)) + centerX\n\t\ty1 = ToInt(math.Cos(tmpRadians)*per*float64(radius)) + centerY\n\n\t\tif cc == 0 {\n\t\t\tfx, fy = x1, y1\n\t\t} else if cc < n-1 {\n\t\t\tDrawLine(x0, y0, x1, y1, thick, lineColor, rgba)\n\t\t} else if cc == n-1 {\n\t\t\tDrawLine(x0, y0, x1, y1, thick, lineColor, rgba)\n\t\t\tDrawLine(fx, fy, x1, y1, thick, lineColor, rgba)\n\t\t}\n\t\t\/\/DrawString\n\t\ttx, ty := calFontPosition(x1, y1, centerX, centerY)\n\t\tDrawString(tx, ty, key, rgba, fontColor)\n\t\tcc++\n\t}\n\tfmt.Println(subFunc(0))\n\tfmt.Println(subFunc(1) \/ subFunc(3))\n\tfmt.Println(subFunc(2) \/ subFunc(3))\n\tfmt.Println(subFunc(3) \/ subFunc(3))\n}\n\n\/*\n\tThis function only used for generate point position.\n\n\tGet Radius according to the img's X & Y axis.\n\n\tGet Radians according to N and radius.\n*\/\nfunc GetRadiusRadians(img *image.RGBA, n int) (radius int, radians float64) {\n\ttmpMin := getMinimum(img.Bounds().Max.X, img.Bounds().Max.Y)\n\tif tmpMin\/2 <= 50 {\n\t\tradius = tmpMin \/ 2\n\t} else {\n\t\tradius = tmpMin \/ 2 * 4 \/ 5\n\t}\n\tradians = math.Pi * 2.0 \/ float64(n)\n\treturn\n}\n\n\/**************\t\tPrivate Function\t*******************\/\n\/\/ func getVertexPerByVal() {\n\/\/ \tkey, ok := Config.GetSetting(\"equal_division\")\n\/\/ \tlayers, ok2 := Config.GetSetting(\"layers\")\n\/\/ \tif !ok {\n\/\/ \t\tfmt.Println(\"equal_division not set in config.conf\")\n\/\/ \t\t\/\/return 0.0\n\/\/ \t}\n\/\/ \tif !ok2 {\n\/\/ \t\tfmt.Println(\"layers not set in config.conf\")\n\/\/ \t\t\/\/return 0.0\n\/\/ \t}\n\n\/\/ \tif key == \"0\" {\n\n\/\/ \t} else {\n\n\/\/ \t}\n\/\/ }\n\nfunc getVertexPerByPer(v int, sum float64) float64 {\n\t\/\/ per := float64(v) \/ sum\n\n\t\/\/ if per <= 0.05 {\n\t\/\/ \tper = per \/ 0.05 \/ 3\n\t\/\/ } else if per > 0.05 && per <= 0.4 {\n\t\/\/ \tper = float64(1.0\/3.0) + float64((per-0.05)\/0.35\/3)\n\t\/\/ } else if per > 0.4 && per <= 1 {\n\t\/\/ \tper = float64(2.0\/3.0) + float64((per-0.4)\/0.6\/3)\n\t\/\/}\n\tequal, ok := Config.GetSetting(\"equal_division\")\n\tl, ok2 := Config.GetSetting(\"layers\")\n\tif !ok {\n\t\tfmt.Println(\"equal_division not set in config.conf\")\n\t\treturn 0.0\n\t}\n\tif !ok2 {\n\t\tfmt.Println(\"layers not set in config.conf\")\n\t\treturn 0.0\n\t}\n\n\tlayers, _ := strconv.Atoi(l)\n\n\tif equal == \"0\" {\n\t\tper := float64(v) \/ sum\n\t\tans := 0.0\n\t\tdd := subFunc(layers)\n\t\tfor i := 0; i < layers; i++ {\n\t\t\ttt := subFunc(i) \/ dd\n\t\t\tif per > tt {\n\t\t\t\tper -= tt\n\t\t\t\tans += subFunc(i) \/ dd\n\t\t\t} else {\n\t\t\t\tans += per \/ (subFunc(i+1) - subFunc(i))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn ans\n\t} else {\n\t\treturn float64(v) \/ sum\n\t}\n}\n\nfunc subFunc(layers int) float64 {\n\treturn math.Sqrt(float64(layers)) + float64(layers)*1.5\n}\n\nfunc getMinimum(tmp ...int) int {\n\tif len(tmp) == 0 {\n\t\treturn 0\n\t}\n\n\tif len(tmp) == 1 {\n\t\treturn tmp[0]\n\t}\n\n\tmin := tmp[0]\n\tfor i := range tmp {\n\t\tif min > tmp[i] {\n\t\t\tmin = tmp[i]\n\t\t}\n\t}\n\treturn min\n}\n\nfunc calFontPosition(x0, y0, centerX, centerY int) (x, y int) {\n\toffset := 50\n\tx, y = x0, y0\n\tif x0 < centerX {\n\t\tx = x0 - offset\n\t} else if x0 > centerX {\n\t\tx = x0 + offset\n\t}\n\n\tif y0 < centerY {\n\t\ty = y0 - offset\n\t} else if y0 > centerY {\n\t\ty = y + offset\n\n\t}\n\treturn\n}\n<commit_msg>2016-03-29 13:53:54<commit_after>package utils\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"image\/color\"\n\t\"math\"\n\t\"strconv\"\n)\n\n\/*********\tStart \tDrawCircle ********\/\n\nfunc DrawCircle(centerX, centerY, radius, thick int, c color.RGBA, rgba *image.RGBA) {\n\tminX, maxX := centerX-radius-thick, centerX+radius+thick\n\tminY, maxY := centerY-radius-thick, centerY+radius+thick\n\tfor x := minX; x < maxX; x++ {\n\t\tfor y := minY; y < maxY; y++ {\n\t\t\tif possibleCirclePoint(centerX, centerY, x, y, radius, thick) {\n\t\t\t\trgba.Set(x, y, c)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc possibleCirclePoint(cx, cy, x, y, r, thick int) bool {\n\tdx, dy := cx-x, cy-y\n\tif (dx*dx+dy*dy > (r+thick)*(r+thick)) || (dx*dx+dy*dy < (r-thick)*(r-thick)) {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/*********  Start   DrawLine   ********\/\nfunc DrawLine(x0, y0, x1, y1, thick int, c color.RGBA, rgba *image.RGBA) {\n\tdx := math.Abs(float64(x1 - x0))\n\tdy := math.Abs(float64(y1 - y0))\n\tsx, sy := 1, 1\n\tif x0 >= x1 {\n\t\tsx = -1\n\t}\n\tif y0 >= y1 {\n\t\tsy = -1\n\t}\n\terr := dx - dy\n\tfor {\n\t\trgba.Set(x0, y0, c)\n\t\tfor i := 1; i <= thick; i++ {\n\t\t\trgba.Set(x0+i, y0, c)\n\t\t\trgba.Set(x0, y0+i, c)\n\t\t}\n\t\tif x0 == x1 && y0 == y1 {\n\t\t\treturn\n\t\t}\n\t\te2 := err * 2\n\t\tif e2 > -dy {\n\t\t\terr -= dy\n\t\t\tx0 += sx\n\t\t}\n\t\tif e2 < dx {\n\t\t\terr += dx\n\t\t\ty0 += sy\n\t\t}\n\t}\n}\n\n\/*\n\t*********  Start   DrawDataLineByData   ********\n\tThe first parameter is a map\n\tIn this map, string is the subject's title on each vertex\n*\/\nfunc DrawDataLineByData(data map[string]int, thick int, rgba *image.RGBA, lineColor, fontColor color.RGBA) {\n\t\/*\n\t\t1st layer -- 1000\n\t\t2nd layer -- 500\n\t\t3rd layer -- 100\n\t*\/\n\tcenterX, centerY := rgba.Bounds().Max.X\/2, rgba.Bounds().Max.Y\/2\n\tradius, radians := GetRadiusRadians(rgba, len(data))\n\n\tcc, n := 0, len(data)\n\tx0, x1, fx, y0, y1, fy := 0, 0, 0, 0, 0, 0\n\n\tfor key, v := range data {\n\t\ttmpRadians := radians * float64(cc)\n\t\tx0, y0 = x1, y1\n\t\tvar tmp float64\n\t\tif v <= 100 {\n\t\t\ttmp = float64(v) \/ float64(100) \/ 3\n\t\t} else if v > 100 && v <= 500 {\n\t\t\ttmp = float64(1.0\/3.0) + float64(v-100)\/float64(400)\/3\n\t\t} else if v > 500 && v <= 1000 {\n\t\t\ttmp = float64(2.0\/3.0) + float64(v-500)\/float64(500)\/3\n\t\t} else {\n\t\t\ttmp = 1.0\n\t\t}\n\n\t\tx1 = ToInt(math.Sin(tmpRadians)*tmp*float64(radius)) + centerX\n\t\ty1 = ToInt(math.Cos(tmpRadians)*tmp*float64(radius)) + centerY\n\n\t\tif cc == 0 {\n\t\t\tfx, fy = x1, y1\n\t\t} else if cc < n-1 {\n\t\t\tDrawLine(x0, y0, x1, y1, thick, lineColor, rgba)\n\t\t} else if cc == n-1 {\n\t\t\tDrawLine(x0, y0, x1, y1, thick, lineColor, rgba)\n\t\t\tDrawLine(fx, fy, x1, y1, thick, lineColor, rgba)\n\t\t}\n\t\t\/\/DrawString\n\t\ttx, ty := calFontPosition(x1, y1, centerX, centerY)\n\t\tDrawString(tx, ty, key, rgba, fontColor)\n\t\tcc++\n\t}\n}\n\n\/*\n\t*********  Start   DrawDataLineByPercentage   ********\n\tThe first parameter is a map\n\tIn this map, string is the subject's title on each vertex\n*\/\nfunc DrawDataLineByPercentage(data map[string]int, thick int, rgba *image.RGBA, lineColor, fontColor color.RGBA) {\n\tvar sum float64\n\tfor _, v := range data {\n\t\tsum += float64(v)\n\t}\n\t\/*\n\t\t1st layer -- 100%\n\t\t2nd layer -- 40%\n\t\t3rd layer -- 5%\n\t*\/\n\tcenterX, centerY := rgba.Bounds().Max.X\/2, rgba.Bounds().Max.Y\/2\n\tradius, radians := GetRadiusRadians(rgba, len(data))\n\n\tcc, n := 0, len(data)\n\tx0, x1, fx, y0, y1, fy := 0, 0, 0, 0, 0, 0\n\n\tfor key, v := range data {\n\t\tfmt.Println(v, float64(v)\/sum, getVertexPerByPer(v, sum))\n\n\t\ttmpRadians := radians * float64(cc)\n\t\tx0, y0 = x1, y1\n\t\t\/\/per := getVertexPerByPer(v, sum)\n\t\tper := float64(v) \/ sum\n\n\t\tif per <= 0.05 {\n\t\t\tper = per \/ 0.05 \/ 3\n\t\t} else if per > 0.05 && per <= 0.4 {\n\t\t\tper = float64(1.0\/3.0) + float64((per-0.05)\/0.35\/3)\n\t\t} else if per > 0.4 && per <= 1 {\n\t\t\tper = float64(2.0\/3.0) + float64((per-0.4)\/0.6\/3)\n\t\t}\n\n\t\tx1 = ToInt(math.Sin(tmpRadians)*per*float64(radius)) + centerX\n\t\ty1 = ToInt(math.Cos(tmpRadians)*per*float64(radius)) + centerY\n\n\t\tif cc == 0 {\n\t\t\tfx, fy = x1, y1\n\t\t} else if cc < n-1 {\n\t\t\tDrawLine(x0, y0, x1, y1, thick, lineColor, rgba)\n\t\t} else if cc == n-1 {\n\t\t\tDrawLine(x0, y0, x1, y1, thick, lineColor, rgba)\n\t\t\tDrawLine(fx, fy, x1, y1, thick, lineColor, rgba)\n\t\t}\n\t\t\/\/DrawString\n\t\ttx, ty := calFontPosition(x1, y1, centerX, centerY)\n\t\tDrawString(tx, ty, key, rgba, fontColor)\n\t\tcc++\n\t}\n\tfmt.Println(subFunc(0))\n\tfmt.Println(subFunc(1) \/ subFunc(3))\n\tfmt.Println(subFunc(2) \/ subFunc(3))\n\tfmt.Println(subFunc(3) \/ subFunc(3))\n}\n\n\/*\n\tThis function only used for generate point position.\n\n\tGet Radius according to the img's X & Y axis.\n\n\tGet Radians according to N and radius.\n*\/\nfunc GetRadiusRadians(img *image.RGBA, n int) (radius int, radians float64) {\n\ttmpMin := getMinimum(img.Bounds().Max.X, img.Bounds().Max.Y)\n\tif tmpMin\/2 <= 50 {\n\t\tradius = tmpMin \/ 2\n\t} else {\n\t\tradius = tmpMin \/ 2 * 4 \/ 5\n\t}\n\tradians = math.Pi * 2.0 \/ float64(n)\n\treturn\n}\n\n\/**************\t\tPrivate Function\t*******************\/\n\/\/ func getVertexPerByVal() {\n\/\/ \tkey, ok := Config.GetSetting(\"equal_division\")\n\/\/ \tlayers, ok2 := Config.GetSetting(\"layers\")\n\/\/ \tif !ok {\n\/\/ \t\tfmt.Println(\"equal_division not set in config.conf\")\n\/\/ \t\t\/\/return 0.0\n\/\/ \t}\n\/\/ \tif !ok2 {\n\/\/ \t\tfmt.Println(\"layers not set in config.conf\")\n\/\/ \t\t\/\/return 0.0\n\/\/ \t}\n\n\/\/ \tif key == \"0\" {\n\n\/\/ \t} else {\n\n\/\/ \t}\n\/\/ }\n\nfunc getVertexPerByPer(v int, sum float64) float64 {\n\t\/\/ per := float64(v) \/ sum\n\n\t\/\/ if per <= 0.05 {\n\t\/\/ \tper = per \/ 0.05 \/ 3\n\t\/\/ } else if per > 0.05 && per <= 0.4 {\n\t\/\/ \tper = float64(1.0\/3.0) + float64((per-0.05)\/0.35\/3)\n\t\/\/ } else if per > 0.4 && per <= 1 {\n\t\/\/ \tper = float64(2.0\/3.0) + float64((per-0.4)\/0.6\/3)\n\t\/\/}\n\tequal, ok := Config.GetSetting(\"equal_division\")\n\tl, ok2 := Config.GetSetting(\"layers\")\n\tif !ok {\n\t\tfmt.Println(\"equal_division not set in config.conf\")\n\t\treturn 0.0\n\t}\n\tif !ok2 {\n\t\tfmt.Println(\"layers not set in config.conf\")\n\t\treturn 0.0\n\t}\n\n\tlayers, _ := strconv.Atoi(l)\n\n\tif equal == \"0\" {\n\t\tper := float64(v) \/ sum\n\t\tans := 0.0\n\t\tdd := subFunc(layers)\n\t\tfor i := 0; i < layers; i++ {\n\t\t\ttt := subFunc(i) \/ dd\n\t\t\tif per > tt {\n\t\t\t\tper -= tt\n\t\t\t\tans += subFunc(i) \/ dd\n\t\t\t} else {\n\t\t\t\tans += per \/ (subFunc(i+1) - subFunc(i))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\treturn ans\n\t} else {\n\t\treturn float64(v) \/ sum\n\t}\n}\n\nfunc subFunc(layers int) float64 {\n\treturn math.Sqrt(float64(layers)) + float64(layers)*1.5\n}\n\nfunc getMinimum(tmp ...int) int {\n\tif len(tmp) == 0 {\n\t\treturn 0\n\t}\n\n\tif len(tmp) == 1 {\n\t\treturn tmp[0]\n\t}\n\n\tmin := tmp[0]\n\tfor i := range tmp {\n\t\tif min > tmp[i] {\n\t\t\tmin = tmp[i]\n\t\t}\n\t}\n\treturn min\n}\n\nfunc calFontPosition(x0, y0, centerX, centerY int) (x, y int) {\n\toffset := 50\n\tx, y = x0, y0\n\tif x0 < centerX {\n\t\tx = x0 - offset\n\t} else if x0 > centerX {\n\t\tx = x0 + offset\n\t}\n\n\tif y0 < centerY {\n\t\ty = y0 - offset\n\t} else if y0 > centerY {\n\t\ty = y + offset\n\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package github\n\nimport (\n\t\"errors\"\n\t\"net\/http\"\n\n\t\"github.com\/dghubble\/gologin\"\n\toauth2Login \"github.com\/dghubble\/gologin\/oauth2\"\n\t\"github.com\/google\/go-github\/github\"\n\t\"golang.org\/x\/oauth2\"\n)\n\n\/\/ Github login errors\nvar (\n\tErrUnableToGetGithubUser = errors.New(\"github: unable to get Github User\")\n)\n\n\/\/ StateHandler checks for a state cookie. If found, the state value is read\n\/\/ and added to the ctx. Otherwise, a non-guessable value is added to the ctx\n\/\/ and to a (short-lived) state cookie issued to the requester.\n\/\/\n\/\/ Implements OAuth 2 RFC 6749 10.12 CSRF Protection. If you wish to issue\n\/\/ state params differently, write a http.Handler which sets the ctx state,\n\/\/ using oauth2 WithState(ctx, state) since it is required by LoginHandler\n\/\/ and CallbackHandler.\nfunc StateHandler(config gologin.CookieConfig, success http.Handler) http.Handler {\n\treturn oauth2Login.StateHandler(config, success)\n}\n\n\/\/ LoginHandler handles Github login requests by reading the state value from\n\/\/ the ctx and redirecting requests to the AuthURL with that state value.\nfunc LoginHandler(config *oauth2.Config, failure http.Handler) http.Handler {\n\treturn oauth2Login.LoginHandler(config, failure)\n}\n\n\/\/ CallbackHandler handles Github redirection URI requests and adds the Github\n\/\/ access token and User to the ctx. If authentication succeeds, handling\n\/\/ delegates to the success handler, otherwise to the failure handler.\nfunc CallbackHandler(config *oauth2.Config, success, failure http.Handler) http.Handler {\n\tsuccess = githubHandler(config, success, failure)\n\treturn oauth2Login.CallbackHandler(config, success, failure)\n}\n\n\/\/ githubHandler is a http.Handler that gets the OAuth2 Token from the ctx to\n\/\/ get the corresponding Github User. If successful, the User is added to the\n\/\/ ctx and the success handler is called. Otherwise, the failure handler is\n\/\/ called.\nfunc githubHandler(config *oauth2.Config, success, failure http.Handler) http.Handler {\n\tif failure == nil {\n\t\tfailure = gologin.DefaultFailureHandler\n\t}\n\tfn := func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\ttoken, err := oauth2Login.TokenFromContext(ctx)\n\t\tif err != nil {\n\t\t\tctx = gologin.WithError(ctx, err)\n\t\t\tfailure.ServeHTTP(w, req.WithContext(ctx))\n\t\t\treturn\n\t\t}\n\t\thttpClient := config.Client(ctx, token)\n\t\tgithubClient := github.NewClient(httpClient)\n\t\tuser, resp, err := githubClient.Users.Get(\"\")\n\t\terr = validateResponse(user, resp, err)\n\t\tif err != nil {\n\t\t\tctx = gologin.WithError(ctx, err)\n\t\t\tfailure.ServeHTTP(w, req.WithContext(ctx))\n\t\t\treturn\n\t\t}\n\t\tctx = WithUser(ctx, user)\n\t\tsuccess.ServeHTTP(w, req.WithContext(ctx))\n\t}\n\treturn http.HandlerFunc(fn)\n}\n\n\/\/ validateResponse returns an error if the given Github user, raw\n\/\/ http.Response, or error are unexpected. Returns nil if they are valid.\nfunc validateResponse(user *github.User, resp *github.Response, err error) error {\n\tif err != nil || resp.StatusCode != http.StatusOK {\n\t\treturn ErrUnableToGetGithubUser\n\t}\n\tif user == nil || user.ID == nil {\n\t\treturn ErrUnableToGetGithubUser\n\t}\n\treturn nil\n}\n<commit_msg>Add context to Github GetUsers call<commit_after>package github\n\nimport (\n\t\"errors\"\n\t\"net\/http\"\n\n\t\"github.com\/dghubble\/gologin\"\n\toauth2Login \"github.com\/dghubble\/gologin\/oauth2\"\n\t\"github.com\/google\/go-github\/github\"\n\t\"golang.org\/x\/oauth2\"\n)\n\n\/\/ Github login errors\nvar (\n\tErrUnableToGetGithubUser = errors.New(\"github: unable to get Github User\")\n)\n\n\/\/ StateHandler checks for a state cookie. If found, the state value is read\n\/\/ and added to the ctx. Otherwise, a non-guessable value is added to the ctx\n\/\/ and to a (short-lived) state cookie issued to the requester.\n\/\/\n\/\/ Implements OAuth 2 RFC 6749 10.12 CSRF Protection. If you wish to issue\n\/\/ state params differently, write a http.Handler which sets the ctx state,\n\/\/ using oauth2 WithState(ctx, state) since it is required by LoginHandler\n\/\/ and CallbackHandler.\nfunc StateHandler(config gologin.CookieConfig, success http.Handler) http.Handler {\n\treturn oauth2Login.StateHandler(config, success)\n}\n\n\/\/ LoginHandler handles Github login requests by reading the state value from\n\/\/ the ctx and redirecting requests to the AuthURL with that state value.\nfunc LoginHandler(config *oauth2.Config, failure http.Handler) http.Handler {\n\treturn oauth2Login.LoginHandler(config, failure)\n}\n\n\/\/ CallbackHandler handles Github redirection URI requests and adds the Github\n\/\/ access token and User to the ctx. If authentication succeeds, handling\n\/\/ delegates to the success handler, otherwise to the failure handler.\nfunc CallbackHandler(config *oauth2.Config, success, failure http.Handler) http.Handler {\n\tsuccess = githubHandler(config, success, failure)\n\treturn oauth2Login.CallbackHandler(config, success, failure)\n}\n\n\/\/ githubHandler is a http.Handler that gets the OAuth2 Token from the ctx to\n\/\/ get the corresponding Github User. If successful, the User is added to the\n\/\/ ctx and the success handler is called. Otherwise, the failure handler is\n\/\/ called.\nfunc githubHandler(config *oauth2.Config, success, failure http.Handler) http.Handler {\n\tif failure == nil {\n\t\tfailure = gologin.DefaultFailureHandler\n\t}\n\tfn := func(w http.ResponseWriter, req *http.Request) {\n\t\tctx := req.Context()\n\t\ttoken, err := oauth2Login.TokenFromContext(ctx)\n\t\tif err != nil {\n\t\t\tctx = gologin.WithError(ctx, err)\n\t\t\tfailure.ServeHTTP(w, req.WithContext(ctx))\n\t\t\treturn\n\t\t}\n\t\thttpClient := config.Client(ctx, token)\n\t\tgithubClient := github.NewClient(httpClient)\n\t\tuser, resp, err := githubClient.Users.Get(ctx, \"\")\n\t\terr = validateResponse(user, resp, err)\n\t\tif err != nil {\n\t\t\tctx = gologin.WithError(ctx, err)\n\t\t\tfailure.ServeHTTP(w, req.WithContext(ctx))\n\t\t\treturn\n\t\t}\n\t\tctx = WithUser(ctx, user)\n\t\tsuccess.ServeHTTP(w, req.WithContext(ctx))\n\t}\n\treturn http.HandlerFunc(fn)\n}\n\n\/\/ validateResponse returns an error if the given Github user, raw\n\/\/ http.Response, or error are unexpected. Returns nil if they are valid.\nfunc validateResponse(user *github.User, resp *github.Response, err error) error {\n\tif err != nil || resp.StatusCode != http.StatusOK {\n\t\treturn ErrUnableToGetGithubUser\n\t}\n\tif user == nil || user.ID == nil {\n\t\treturn ErrUnableToGetGithubUser\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package utils\n\nimport (\n\t\"log\"\n\ttext \"text\/template\"\n\n\t\"html\/template\"\n\n\t\"github.com\/patrickalin\/bloomsky-client-go\/assembly\"\n)\n\n\/*\nGetTemplate retrieve a template\n*\/\nfunc GetTemplate(templateName string, templateLocation string, funcs map[string]interface{}, dev bool) *text.Template {\n\tif dev {\n\t\tt, err := text.New(templateName).Funcs(funcs).ParseFiles(templateLocation)\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Load template console : %v\", err)\n\t\t}\n\t\treturn t\n\t}\n\n\tassetBloomsky, err := assembly.Asset(templateLocation)\n\tt, err := text.New(templateName).Funcs(funcs).Parse(string(assetBloomsky[:]))\n\tif err != nil {\n\t\tlog.Fatalf(\"Load template console : %v\", err)\n\t}\n\treturn t\n}\n\n\/\/ \"bloomsky_header.html\",\"tmpl\/bloomsky_header.html\",map[string]interface{}{\"T\": config.translateFunc,}\nfunc GetHtmlTemplate(templateName string, templatesLocation []string, funcs map[string]interface{}, dev bool) *template.Template {\n\tif dev {\n\t\tt := template.New(templateName)\n\t\tt.Funcs(funcs)\n\t\tt, err := t.ParseFiles(templatesLocation...)\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Template part 1 : %v\", err)\n\t\t}\n\n\t\treturn t\n\t}\n\n\tasset, err := assembly.Asset(templatesLocation[0])\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Template part 1 assembly: %v\", err)\n\t}\n\n\tt, err := template.New(templateName).Funcs(funcs).Parse(string(asset[:]))\n\n\tif err != nil {\n\t\tlog.Fatalf(\"Template part 1 : %v\", err)\n\t}\n\treturn t\n\n}\n<commit_msg>using asset<commit_after>package utils\n\nimport (\n\t\"log\"\n\ttext \"text\/template\"\n\n\t\"html\/template\"\n\n\t\"github.com\/patrickalin\/bloomsky-client-go\/assembly\"\n)\n\n\/*\nGetTemplate retrieve a template\n*\/\nfunc GetTemplate(templateName string, templateLocation string, funcs map[string]interface{}, dev bool) *text.Template {\n\tif dev {\n\t\tt, err := text.New(templateName).Funcs(funcs).ParseFiles(templateLocation)\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Load template console : %v\", err)\n\t\t}\n\t\treturn t\n\t}\n\n\tassetBloomsky, err := assembly.Asset(templateLocation)\n\tt, err := text.New(templateName).Funcs(funcs).Parse(string(assetBloomsky[:]))\n\tif err != nil {\n\t\tlog.Fatalf(\"Load template console : %v\", err)\n\t}\n\treturn t\n}\n\n\/\/ \"bloomsky_header.html\",\"tmpl\/bloomsky_header.html\",map[string]interface{}{\"T\": config.translateFunc,}\nfunc GetHtmlTemplate(templateName string, templatesLocation []string, funcs map[string]interface{}, dev bool) *template.Template {\n\tt := template.New(templateName)\n\tt.Funcs(funcs)\n\tif dev {\n\n\t\tt, err := t.ParseFiles(templatesLocation...)\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Template part 1 : %v\", err)\n\t\t}\n\n\t\treturn t\n\t}\n\n\tfor _, l := range templatesLocation {\n\t\tasset, err := assembly.Asset(l)\n\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Template part 1 assembly: %v\", err)\n\t\t}\n\t\tt, err = t.Parse(string(asset[:]))\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Template part 1 : %v\", err)\n\t\t}\n\t}\n\n\treturn t\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package forecast\n\nimport (\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n)\n\n\/\/ URL example:  \"https:\/\/api.forecast.io\/forecast\/APIKEY\/LATITUDE,LONGITUDE,TIME?units=ca\"\nconst (\n\tBASEURL = \"https:\/\/api.forecast.io\/forecast\"\n)\n\ntype Flags struct {\n\tDarkSkyUnavailable string\n\tDarkSkyStations    []string\n\tDataPointStations  []string\n\tISDStations        []string\n\tLAMPStations       []string\n\tMETARStations      []string\n\tMETNOLicense       string\n\tSources            []string\n\tUnits              string\n}\n\ntype DataPoint struct {\n\tTime                   float64\n\tSummary                string\n\tIcon                   string\n\tSunriseTime            float64\n\tSunsetTime             float64\n\tPrecipIntensity        float64\n\tPrecipIntensityMax     float64\n\tPrecipIntensityMaxTime float64\n\tPrecipProbability      float64\n\tPrecipType             string\n\tPrecipAccumulation     float64\n\tTemperature            float64\n\tTemperatureMin         float64\n\tTemperatureMinTime     float64\n\tTemperatureMax         float64\n\tTemperatureMaxTime     float64\n\tDewPoint               float64\n\tWindSpeed              float64\n\tWindBearing            float64\n\tCloudCover             float64\n\tHumidity               float64\n\tPressure               float64\n\tVisibility             float64\n\tOzone                  float64\n}\n\ntype DataBlock struct {\n\tSummary string\n\tIcon    string\n\tData    []DataPoint\n}\n\ntype alert struct {\n\tTitle   string\n\tExpires float64\n\tURI     string\n}\n\ntype Forecast struct {\n\tLatitude  float64\n\tLongitude float64\n\tTimezone  string\n\tOffset    float64\n\tCurrently DataPoint\n\tMinutely  DataBlock\n\tHourly    DataBlock\n\tDaily     DataBlock\n\tAlerts    []alert\n\tFlags     Flags\n\tAPICalls  int\n}\n\ntype Units string\n\nconst (\n\tCA Units = \"ca\"\n\tSI Units = \"si\"\n)\n\nfunc Get(key string, lat string, long string, time string, units Units) (*Forecast, error) {\n\tcoord := lat + \",\" + long\n\n\tvar url string\n\tif time == \"now\" {\n\t\turl = BASEURL + \"\/\" + key + \"\/\" + coord + \"?units=\" + string(units)\n\t} else {\n\t\turl = BASEURL + \"\/\" + key + \"\/\" + coord + \",\" + time + \"?units=\" + string(units)\n\t}\n\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr}\n\tres, err := client.Get(url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar f Forecast\n\terr = json.Unmarshal(body, &f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcalls, _ := strconv.Atoi(res.Header.Get(\"X-Forecast-API-Calls\"))\n\tf.APICalls = calls\n\n\treturn &f, nil\n}\n<commit_msg>finally working, was probably always working were it not for my key setup<commit_after>package forecast\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n)\n\n\/\/ URL example:  \"https:\/\/api.forecast.io\/forecast\/APIKEY\/LATITUDE,LONGITUDE,TIME?units=ca\"\nconst (\n\tBASEURL = \"https:\/\/api.forecast.io\/forecast\"\n)\n\ntype Flags struct {\n\tDarkSkyUnavailable string\n\tDarkSkyStations    []string\n\tDataPointStations  []string\n\tISDStations        []string\n\tLAMPStations       []string\n\tMETARStations      []string\n\tMETNOLicense       string\n\tSources            []string\n\tUnits              string\n}\n\ntype DataPoint struct {\n\tTime                   float64\n\tSummary                string\n\tIcon                   string\n\tSunriseTime            float64\n\tSunsetTime             float64\n\tPrecipIntensity        float64\n\tPrecipIntensityMax     float64\n\tPrecipIntensityMaxTime float64\n\tPrecipProbability      float64\n\tPrecipType             string\n\tPrecipAccumulation     float64\n\tTemperature            float64\n\tTemperatureMin         float64\n\tTemperatureMinTime     float64\n\tTemperatureMax         float64\n\tTemperatureMaxTime     float64\n\tDewPoint               float64\n\tWindSpeed              float64\n\tWindBearing            float64\n\tCloudCover             float64\n\tHumidity               float64\n\tPressure               float64\n\tVisibility             float64\n\tOzone                  float64\n}\n\ntype DataBlock struct {\n\tSummary string\n\tIcon    string\n\tData    []DataPoint\n}\n\ntype alert struct {\n\tTitle   string\n\tExpires float64\n\tURI     string\n}\n\ntype Forecast struct {\n\tLatitude  float64\n\tLongitude float64\n\tTimezone  string\n\tOffset    float64\n\tCurrently DataPoint\n\tMinutely  DataBlock\n\tHourly    DataBlock\n\tDaily     DataBlock\n\tAlerts    []alert\n\tFlags     Flags\n\tAPICalls  int\n}\n\ntype Units string\n\nconst (\n\tCA Units = \"ca\"\n\tSI Units = \"si\"\n)\n\nfunc Get(key string, lat string, long string, time string, units Units) (*Forecast, error) {\n\tcoord := lat + \",\" + long\n\n\tvar url string\n\tif time == \"now\" {\n\t\turl = BASEURL + \"\/\" + key + \"\/\" + coord + \"?units=\" + string(units)\n\t} else {\n\t\turl = BASEURL + \"\/\" + key + \"\/\" + coord + \",\" + time + \"?units=\" + string(units)\n\t}\n\n\tres, err := http.Get(url)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar f Forecast\n\terr = json.Unmarshal(body, &f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcalls, _ := strconv.Atoi(res.Header.Get(\"X-Forecast-API-Calls\"))\n\tf.APICalls = calls\n\n\treturn &f, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package vault\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\n\t\"encoding\/gob\"\n\t\"golang.org\/x\/crypto\/nacl\/secretbox\"\n\t\"golang.org\/x\/crypto\/scrypt\"\n)\n\nconst (\n\tscryptN = 16384\n\tscryptR = 8\n\tscryptP = 1\n\tkeyLen  = 32\n)\n\nvar (\n\tErrNoSuchCredential = errors.New(\"credential at specified location does not exist in vault\")\n\tErrCouldNotDecrypt  = errors.New(\"provided decryption key is incorrect or the provided vault is corrupt\")\n)\n\n\/\/ Vault is an atomic, consistent, and durable password database, using NACL\n\/\/ secretbox.\ntype Vault struct {\n\tdata   []byte\n\tnonce  [24]byte\n\tsecret [32]byte\n}\n\ntype Credential struct {\n\tUsername string\n\tPassword string\n}\n\nfunc New(passphrase string) (*Vault, error) {\n\tvar nonce [24]byte\n\tif _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar secret [32]byte\n\tkey, err := scrypt.Key([]byte(passphrase), nonce[:], scryptN, scryptR, scryptP, keyLen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcopy(secret[:], key)\n\n\tv := &Vault{\n\t\tnonce:  nonce,\n\t\tsecret: secret,\n\t}\n\n\terr = v.encrypt(make(map[string]*Credential))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn v, nil\n}\n\nfunc (v *Vault) decrypt() (map[string]*Credential, error) {\n\tdecryptedData, success := secretbox.Open([]byte{}, v.data[len(v.nonce):], &v.nonce, &v.secret)\n\tif !success {\n\t\treturn nil, ErrCouldNotDecrypt\n\t}\n\n\tcredentials := make(map[string]*Credential)\n\terr := gob.NewDecoder(bytes.NewBuffer(decryptedData)).Decode(&credentials)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn credentials, nil\n}\n\nfunc (v *Vault) encrypt(creds map[string]*Credential) error {\n\tvar buf bytes.Buffer\n\terr := gob.NewEncoder(&buf).Encode(creds)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tv.data = secretbox.Seal(v.nonce[:], buf.Bytes(), &v.nonce, &v.secret)\n\n\treturn nil\n}\n\nfunc (v *Vault) Add(location string, credential Credential) error {\n\tcreds, err := v.decrypt()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcreds[location] = &credential\n\n\terr = v.encrypt(creds)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (v *Vault) Get(location string) (*Credential, error) {\n\tcreds, err := v.decrypt()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcred, ok := creds[location]\n\tif !ok {\n\t\treturn nil, ErrNoSuchCredential\n\t}\n\treturn cred, nil\n}\n\nfunc (v *Vault) Save(filename string) error {\n\ttempfile, err := ioutil.TempFile(path.Dir(filename), \"passio-temp\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(tempfile, bytes.NewBuffer(v.data))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.Rename(tempfile.Name(), filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc Open(filename string, passphrase string) (*Vault, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar encryptedData bytes.Buffer\n\t_, err = io.Copy(&encryptedData, f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar nonce [24]byte\n\tcopy(nonce[:], encryptedData.Bytes()[:24])\n\n\tkey, err := scrypt.Key([]byte(passphrase), nonce[:], scryptN, scryptR, scryptP, keyLen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar secret [32]byte\n\tcopy(secret[:], key)\n\n\tvault := &Vault{\n\t\tdata:   encryptedData.Bytes(),\n\t\tnonce:  nonce,\n\t\tsecret: secret,\n\t}\n\n\tcreds, err := vault.decrypt()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err = io.ReadFull(rand.Reader, nonce[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey, err = scrypt.Key([]byte(passphrase), nonce[:], scryptN, scryptR, scryptP, keyLen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcopy(secret[:], key)\n\n\tvault.secret = secret\n\tvault.nonce = nonce\n\tif err = vault.encrypt(creds); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vault, nil\n}\n<commit_msg>add Locations()<commit_after>package vault\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\n\t\"encoding\/gob\"\n\t\"golang.org\/x\/crypto\/nacl\/secretbox\"\n\t\"golang.org\/x\/crypto\/scrypt\"\n)\n\nconst (\n\tscryptN = 16384\n\tscryptR = 8\n\tscryptP = 1\n\tkeyLen  = 32\n)\n\nvar (\n\tErrNoSuchCredential = errors.New(\"credential at specified location does not exist in vault\")\n\tErrCouldNotDecrypt  = errors.New(\"provided decryption key is incorrect or the provided vault is corrupt\")\n)\n\n\/\/ Vault is an atomic, consistent, and durable password database, using NACL\n\/\/ secretbox.\ntype Vault struct {\n\tdata   []byte\n\tnonce  [24]byte\n\tsecret [32]byte\n}\n\ntype Credential struct {\n\tUsername string\n\tPassword string\n}\n\nfunc New(passphrase string) (*Vault, error) {\n\tvar nonce [24]byte\n\tif _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar secret [32]byte\n\tkey, err := scrypt.Key([]byte(passphrase), nonce[:], scryptN, scryptR, scryptP, keyLen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcopy(secret[:], key)\n\n\tv := &Vault{\n\t\tnonce:  nonce,\n\t\tsecret: secret,\n\t}\n\n\terr = v.encrypt(make(map[string]*Credential))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn v, nil\n}\n\nfunc (v *Vault) decrypt() (map[string]*Credential, error) {\n\tdecryptedData, success := secretbox.Open([]byte{}, v.data[len(v.nonce):], &v.nonce, &v.secret)\n\tif !success {\n\t\treturn nil, ErrCouldNotDecrypt\n\t}\n\n\tcredentials := make(map[string]*Credential)\n\terr := gob.NewDecoder(bytes.NewBuffer(decryptedData)).Decode(&credentials)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn credentials, nil\n}\n\nfunc (v *Vault) encrypt(creds map[string]*Credential) error {\n\tvar buf bytes.Buffer\n\terr := gob.NewEncoder(&buf).Encode(creds)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tv.data = secretbox.Seal(v.nonce[:], buf.Bytes(), &v.nonce, &v.secret)\n\n\treturn nil\n}\n\nfunc (v *Vault) Add(location string, credential Credential) error {\n\tcreds, err := v.decrypt()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcreds[location] = &credential\n\n\terr = v.encrypt(creds)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (v *Vault) Get(location string) (*Credential, error) {\n\tcreds, err := v.decrypt()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcred, ok := creds[location]\n\tif !ok {\n\t\treturn nil, ErrNoSuchCredential\n\t}\n\treturn cred, nil\n}\n\nfunc (v *Vault) Save(filename string) error {\n\ttempfile, err := ioutil.TempFile(path.Dir(filename), \"passio-temp\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = io.Copy(tempfile, bytes.NewBuffer(v.data))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = os.Rename(tempfile.Name(), filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (v *Vault) Locations() ([]string, error) {\n\tvar locations []string\n\tcreds, err := v.decrypt()\n\tif err != nil {\n\t\treturn locations, err\n\t}\n\n\tfor location, _ := range creds {\n\t\tlocations = append(locations, location)\n\t}\n\treturn locations, nil\n}\n\nfunc Open(filename string, passphrase string) (*Vault, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar encryptedData bytes.Buffer\n\t_, err = io.Copy(&encryptedData, f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar nonce [24]byte\n\tcopy(nonce[:], encryptedData.Bytes()[:24])\n\n\tkey, err := scrypt.Key([]byte(passphrase), nonce[:], scryptN, scryptR, scryptP, keyLen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar secret [32]byte\n\tcopy(secret[:], key)\n\n\tvault := &Vault{\n\t\tdata:   encryptedData.Bytes(),\n\t\tnonce:  nonce,\n\t\tsecret: secret,\n\t}\n\n\tcreds, err := vault.decrypt()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err = io.ReadFull(rand.Reader, nonce[:]); err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey, err = scrypt.Key([]byte(passphrase), nonce[:], scryptN, scryptR, scryptP, keyLen)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcopy(secret[:], key)\n\n\tvault.secret = secret\n\tvault.nonce = nonce\n\tif err = vault.encrypt(creds); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vault, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage common\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/klog\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/measurement\"\n\tmeasurementutil \"k8s.io\/perf-tests\/clusterloader2\/pkg\/measurement\/util\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/util\"\n)\n\nconst (\n\tcpuProfileName    = \"CPUProfile\"\n\tmemoryProfileName = \"MemoryProfile\"\n\tmutexProfileName  = \"MutexProfile\"\n)\n\nfunc init() {\n\tif err := measurement.Register(cpuProfileName, createProfileMeasurementFactory(cpuProfileName, \"profile\")); err != nil {\n\t\tklog.Fatalf(\"Cannot register %s: %v\", cpuProfileName, err)\n\t}\n\tif err := measurement.Register(memoryProfileName, createProfileMeasurementFactory(memoryProfileName, \"heap\")); err != nil {\n\t\tklog.Fatalf(\"Cannot register %s: %v\", memoryProfileName, err)\n\t}\n\tif err := measurement.Register(mutexProfileName, createProfileMeasurementFactory(mutexProfileName, \"mutex\")); err != nil {\n\t\tklog.Fatalf(\"Cannot register %s: %v\", mutexProfileName, err)\n\t}\n}\n\ntype profileConfig struct {\n\tcomponentName string\n\tprovider      string\n\thosts         []string\n\tkind          string\n}\n\nfunc (p *profileMeasurement) populateProfileConfig(config *measurement.MeasurementConfig) error {\n\tvar err error\n\tif p.config.componentName, err = util.GetString(config.Params, \"componentName\"); err != nil {\n\t\treturn err\n\t}\n\tif p.config.provider, err = util.GetStringOrDefault(config.Params, \"provider\", config.ClusterFramework.GetClusterConfig().Provider); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\ntype profileMeasurement struct {\n\tname      string\n\tconfig    *profileConfig\n\tsummaries []measurement.Summary\n\tisRunning bool\n\tstopCh    chan struct{}\n\twg        sync.WaitGroup\n}\n\nfunc createProfileMeasurementFactory(name, kind string) func() measurement.Measurement {\n\treturn func() measurement.Measurement {\n\t\treturn &profileMeasurement{\n\t\t\tname:   name,\n\t\t\tconfig: &profileConfig{kind: kind},\n\t\t}\n\t}\n}\n\nfunc (p *profileMeasurement) start(config *measurement.MeasurementConfig) error {\n\tp.config.hosts = config.ClusterFramework.GetClusterConfig().MasterIPs\n\tif len(p.config.hosts) < 1 {\n\t\treturn errors.New(\"Profile measurements will be disabled due to no MasterIps\")\n\t}\n\n\tif err := p.populateProfileConfig(config); err != nil {\n\t\treturn err\n\t}\n\tp.summaries = make([]measurement.Summary, 0)\n\tp.isRunning = true\n\tp.stopCh = make(chan struct{})\n\tp.wg.Add(1)\n\n\t\/\/ Currently length of the test is proportional to the cluster size.\n\t\/\/ So for now we make the profiling frequency proportional to the cluster size.\n\t\/\/ We may want to revisit ot adjust it in the future.\n\tnumNodes := config.ClusterFramework.GetClusterConfig().Nodes\n\tprofileFrequency := time.Duration(5+numNodes\/250) * time.Minute\n\n\tgo func() {\n\t\tdefer p.wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-p.stopCh:\n\t\t\t\treturn\n\t\t\tcase <-time.After(profileFrequency):\n\t\t\t\tprofileSummaries, err := p.gatherProfile(config.ClusterFramework.GetClientSets().GetClient())\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"failed to gather profile for %#v: %v\", *p.config, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif profileSummaries != nil {\n\t\t\t\t\tp.summaries = append(p.summaries, profileSummaries...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn nil\n}\n\nfunc (p *profileMeasurement) stop() {\n\tif !p.isRunning {\n\t\treturn\n\t}\n\tclose(p.stopCh)\n\tp.wg.Wait()\n}\n\n\/\/ Execute gathers memory profile of a given component.\nfunc (p *profileMeasurement) Execute(config *measurement.MeasurementConfig) ([]measurement.Summary, error) {\n\taction, err := util.GetString(config.Params, \"action\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch action {\n\tcase \"start\":\n\t\tif p.isRunning {\n\t\t\tklog.Infof(\"%s: measurement already running\", p)\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, p.start(config)\n\tcase \"gather\":\n\t\tp.stop()\n\t\treturn p.summaries, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown action %v\", action)\n\t}\n}\n\n\/\/ Dispose cleans up after the measurement.\nfunc (*profileMeasurement) Dispose() {}\n\n\/\/ String returns string representation of this measurement.\nfunc (p *profileMeasurement) String() string {\n\treturn p.name\n}\n\nfunc (p *profileMeasurement) gatherProfile(c clientset.Interface) ([]measurement.Summary, error) {\n\tprofilePort, err := getPortForComponent(p.config.componentName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"profile gathering failed finding component port: %v\", err)\n\t}\n\tgetCommand := fmt.Sprintf(\"curl -s localhost:%v\/debug\/pprof\/%s\", profilePort, p.config.kind)\n\n\tvar summaries []measurement.Summary\n\tfor _, host := range p.config.hosts {\n\t\tprofilePrefix := fmt.Sprintf(\"%s_%s_%s\", host, p.config.componentName, p.name)\n\n\t\tif p.config.componentName == \"kube-apiserver\" {\n\t\t\tbody, err := c.CoreV1().RESTClient().Get().AbsPath(\"\/debug\/pprof\/\" + p.config.kind).DoRaw()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tsummary := measurement.CreateSummary(profilePrefix, \"pprof\", string(body))\n\t\t\tsummaries = append(summaries, summary)\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Get the profile data over SSH.\n\t\t\/\/ Start by checking that the provider allows us to do so.\n\t\tif p.config.provider == \"gke\" {\n\t\t\t\/\/ Only logging error for gke. SSHing to gke master is not supported.\n\t\t\tklog.Warningf(\"%s: failed to execute curl command on master through SSH\", p.name)\n\t\t\treturn nil, nil\n\t\t}\n\n\t\tsshResult, err := measurementutil.SSH(getCommand, host+\":22\", p.config.provider)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to execute curl command on master node %s through SSH: %v\", host, err)\n\t\t}\n\t\tsummaries = append(summaries, measurement.CreateSummary(profilePrefix, \"pprof\", sshResult.Stdout))\n\t}\n\n\treturn summaries, nil\n}\n\nfunc getPortForComponent(componentName string) (int, error) {\n\tswitch componentName {\n\tcase \"etcd\":\n\t\treturn 2379, nil\n\tcase \"kube-scheduler\":\n\t\treturn 10251, nil\n\tcase \"kube-controller-manager\":\n\t\treturn 10252, nil\n\t}\n\treturn -1, fmt.Errorf(\"port for component %v unknown\", componentName)\n}\n<commit_msg>Profile measurements should warn instead of fail on lack of master IPs<commit_after>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage common\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/klog\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/measurement\"\n\tmeasurementutil \"k8s.io\/perf-tests\/clusterloader2\/pkg\/measurement\/util\"\n\t\"k8s.io\/perf-tests\/clusterloader2\/pkg\/util\"\n)\n\nconst (\n\tcpuProfileName    = \"CPUProfile\"\n\tmemoryProfileName = \"MemoryProfile\"\n\tmutexProfileName  = \"MutexProfile\"\n)\n\nfunc init() {\n\tif err := measurement.Register(cpuProfileName, createProfileMeasurementFactory(cpuProfileName, \"profile\")); err != nil {\n\t\tklog.Fatalf(\"Cannot register %s: %v\", cpuProfileName, err)\n\t}\n\tif err := measurement.Register(memoryProfileName, createProfileMeasurementFactory(memoryProfileName, \"heap\")); err != nil {\n\t\tklog.Fatalf(\"Cannot register %s: %v\", memoryProfileName, err)\n\t}\n\tif err := measurement.Register(mutexProfileName, createProfileMeasurementFactory(mutexProfileName, \"mutex\")); err != nil {\n\t\tklog.Fatalf(\"Cannot register %s: %v\", mutexProfileName, err)\n\t}\n}\n\ntype profileConfig struct {\n\tcomponentName string\n\tprovider      string\n\thosts         []string\n\tkind          string\n}\n\nfunc (p *profileMeasurement) populateProfileConfig(config *measurement.MeasurementConfig) error {\n\tvar err error\n\tif p.config.componentName, err = util.GetString(config.Params, \"componentName\"); err != nil {\n\t\treturn err\n\t}\n\tif p.config.provider, err = util.GetStringOrDefault(config.Params, \"provider\", config.ClusterFramework.GetClusterConfig().Provider); err != nil {\n\t\treturn err\n\t}\n\tp.config.hosts = config.ClusterFramework.GetClusterConfig().MasterIPs\n\treturn nil\n}\n\ntype profileMeasurement struct {\n\tname      string\n\tconfig    *profileConfig\n\tsummaries []measurement.Summary\n\tisRunning bool\n\tstopCh    chan struct{}\n\twg        sync.WaitGroup\n}\n\nfunc createProfileMeasurementFactory(name, kind string) func() measurement.Measurement {\n\treturn func() measurement.Measurement {\n\t\treturn &profileMeasurement{\n\t\t\tname:   name,\n\t\t\tconfig: &profileConfig{kind: kind},\n\t\t}\n\t}\n}\n\nfunc (p *profileMeasurement) start(config *measurement.MeasurementConfig) error {\n\tif err := p.populateProfileConfig(config); err != nil {\n\t\treturn err\n\t}\n\tif len(p.config.hosts) < 1 {\n\t\tklog.Warning(\"Profile measurements will be disabled due to no MasterIps\")\n\t\treturn nil\n\t}\n\n\tp.summaries = make([]measurement.Summary, 0)\n\tp.isRunning = true\n\tp.stopCh = make(chan struct{})\n\tp.wg.Add(1)\n\n\t\/\/ Currently length of the test is proportional to the cluster size.\n\t\/\/ So for now we make the profiling frequency proportional to the cluster size.\n\t\/\/ We may want to revisit ot adjust it in the future.\n\tnumNodes := config.ClusterFramework.GetClusterConfig().Nodes\n\tprofileFrequency := time.Duration(5+numNodes\/250) * time.Minute\n\n\tgo func() {\n\t\tdefer p.wg.Done()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-p.stopCh:\n\t\t\t\treturn\n\t\t\tcase <-time.After(profileFrequency):\n\t\t\t\tprofileSummaries, err := p.gatherProfile(config.ClusterFramework.GetClientSets().GetClient())\n\t\t\t\tif err != nil {\n\t\t\t\t\tklog.Errorf(\"failed to gather profile for %#v: %v\", *p.config, err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif profileSummaries != nil {\n\t\t\t\t\tp.summaries = append(p.summaries, profileSummaries...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn nil\n}\n\nfunc (p *profileMeasurement) stop() {\n\tif !p.isRunning {\n\t\treturn\n\t}\n\tclose(p.stopCh)\n\tp.wg.Wait()\n}\n\n\/\/ Execute gathers memory profile of a given component.\nfunc (p *profileMeasurement) Execute(config *measurement.MeasurementConfig) ([]measurement.Summary, error) {\n\taction, err := util.GetString(config.Params, \"action\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch action {\n\tcase \"start\":\n\t\tif p.isRunning {\n\t\t\tklog.Infof(\"%s: measurement already running\", p)\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, p.start(config)\n\tcase \"gather\":\n\t\tp.stop()\n\t\treturn p.summaries, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown action %v\", action)\n\t}\n}\n\n\/\/ Dispose cleans up after the measurement.\nfunc (*profileMeasurement) Dispose() {}\n\n\/\/ String returns string representation of this measurement.\nfunc (p *profileMeasurement) String() string {\n\treturn p.name\n}\n\nfunc (p *profileMeasurement) gatherProfile(c clientset.Interface) ([]measurement.Summary, error) {\n\tprofilePort, err := getPortForComponent(p.config.componentName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"profile gathering failed finding component port: %v\", err)\n\t}\n\tgetCommand := fmt.Sprintf(\"curl -s localhost:%v\/debug\/pprof\/%s\", profilePort, p.config.kind)\n\n\tvar summaries []measurement.Summary\n\tfor _, host := range p.config.hosts {\n\t\tprofilePrefix := fmt.Sprintf(\"%s_%s_%s\", host, p.config.componentName, p.name)\n\n\t\tif p.config.componentName == \"kube-apiserver\" {\n\t\t\tbody, err := c.CoreV1().RESTClient().Get().AbsPath(\"\/debug\/pprof\/\" + p.config.kind).DoRaw()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tsummary := measurement.CreateSummary(profilePrefix, \"pprof\", string(body))\n\t\t\tsummaries = append(summaries, summary)\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Get the profile data over SSH.\n\t\t\/\/ Start by checking that the provider allows us to do so.\n\t\tif p.config.provider == \"gke\" {\n\t\t\t\/\/ Only logging error for gke. SSHing to gke master is not supported.\n\t\t\tklog.Warningf(\"%s: failed to execute curl command on master through SSH\", p.name)\n\t\t\treturn nil, nil\n\t\t}\n\n\t\tsshResult, err := measurementutil.SSH(getCommand, host+\":22\", p.config.provider)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to execute curl command on master node %s through SSH: %v\", host, err)\n\t\t}\n\t\tsummaries = append(summaries, measurement.CreateSummary(profilePrefix, \"pprof\", sshResult.Stdout))\n\t}\n\n\treturn summaries, nil\n}\n\nfunc getPortForComponent(componentName string) (int, error) {\n\tswitch componentName {\n\tcase \"etcd\":\n\t\treturn 2379, nil\n\tcase \"kube-scheduler\":\n\t\treturn 10251, nil\n\tcase \"kube-controller-manager\":\n\t\treturn 10252, nil\n\t}\n\treturn -1, fmt.Errorf(\"port for component %v unknown\", componentName)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage config\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"strconv\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"k8s.io\/klog\"\n\n\tv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\tnetutil \"k8s.io\/apimachinery\/pkg\/util\/net\"\n\tbootstraputil \"k8s.io\/cluster-bootstrap\/token\/util\"\n\tkubeadmapi \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\"\n\tkubeadmscheme \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\/scheme\"\n\tkubeadmapiv1beta2 \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\/v1beta2\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\/validation\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/componentconfigs\"\n\tkubeadmconstants \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/constants\"\n\tkubeadmutil \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/util\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/util\/config\/strict\"\n\tkubeadmruntime \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/util\/runtime\"\n)\n\n\/\/ SetInitDynamicDefaults checks and sets configuration values for the InitConfiguration object\nfunc SetInitDynamicDefaults(cfg *kubeadmapi.InitConfiguration) error {\n\tif err := SetBootstrapTokensDynamicDefaults(&cfg.BootstrapTokens); err != nil {\n\t\treturn err\n\t}\n\tif err := SetNodeRegistrationDynamicDefaults(&cfg.NodeRegistration, true); err != nil {\n\t\treturn err\n\t}\n\tif err := SetAPIEndpointDynamicDefaults(&cfg.LocalAPIEndpoint); err != nil {\n\t\treturn err\n\t}\n\treturn SetClusterDynamicDefaults(&cfg.ClusterConfiguration, &cfg.LocalAPIEndpoint)\n}\n\n\/\/ SetBootstrapTokensDynamicDefaults checks and sets configuration values for the BootstrapTokens object\nfunc SetBootstrapTokensDynamicDefaults(cfg *[]kubeadmapi.BootstrapToken) error {\n\t\/\/ Populate the .Token field with a random value if unset\n\t\/\/ We do this at this layer, and not the API defaulting layer\n\t\/\/ because of possible security concerns, and more practically\n\t\/\/ because we can't return errors in the API object defaulting\n\t\/\/ process but here we can.\n\tfor i, bt := range *cfg {\n\t\tif bt.Token != nil && len(bt.Token.String()) > 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\ttokenStr, err := bootstraputil.GenerateBootstrapToken()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"couldn't generate random token\")\n\t\t}\n\t\ttoken, err := kubeadmapi.NewBootstrapTokenString(tokenStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t(*cfg)[i].Token = token\n\t}\n\n\treturn nil\n}\n\n\/\/ SetNodeRegistrationDynamicDefaults checks and sets configuration values for the NodeRegistration object\nfunc SetNodeRegistrationDynamicDefaults(cfg *kubeadmapi.NodeRegistrationOptions, ControlPlaneTaint bool) error {\n\tvar err error\n\tcfg.Name, err = kubeadmutil.GetHostname(cfg.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Only if the slice is nil, we should append the control-plane taint. This allows the user to specify an empty slice for no default control-plane taint\n\tif ControlPlaneTaint && cfg.Taints == nil {\n\t\tcfg.Taints = []v1.Taint{kubeadmconstants.ControlPlaneTaint}\n\t}\n\n\tif cfg.CRISocket == \"\" {\n\t\tcfg.CRISocket, err = kubeadmruntime.DetectCRISocket()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tklog.V(1).Infof(\"detected and using CRI socket: %s\", cfg.CRISocket)\n\t}\n\n\treturn nil\n}\n\n\/\/ SetAPIEndpointDynamicDefaults checks and sets configuration values for the APIEndpoint object\nfunc SetAPIEndpointDynamicDefaults(cfg *kubeadmapi.APIEndpoint) error {\n\t\/\/ validate cfg.API.AdvertiseAddress.\n\taddressIP := net.ParseIP(cfg.AdvertiseAddress)\n\tif addressIP == nil && cfg.AdvertiseAddress != \"\" {\n\t\treturn errors.Errorf(\"couldn't use \\\"%s\\\" as \\\"apiserver-advertise-address\\\", must be ipv4 or ipv6 address\", cfg.AdvertiseAddress)\n\t}\n\n\t\/\/ kubeadm allows users to specify address=Loopback as a selector for global unicast IP address that can be found on loopback interface.\n\t\/\/ e.g. This is required for network setups where default routes are present, but network interfaces use only link-local addresses (e.g. as described in RFC5549).\n\tif addressIP.IsLoopback() {\n\t\tloopbackIP, err := netutil.ChooseBindAddressForInterface(netutil.LoopbackInterfaceName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif loopbackIP != nil {\n\t\t\tklog.V(4).Infof(\"Found active IP %v on loopback interface\", loopbackIP.String())\n\t\t\tcfg.AdvertiseAddress = loopbackIP.String()\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"unable to resolve link-local addresses\")\n\t}\n\n\t\/\/ This is the same logic as the API Server uses, except that if no interface is found the address is set to 0.0.0.0, which is invalid and cannot be used\n\t\/\/ for bootstrapping a cluster.\n\tip, err := ChooseAPIServerBindAddress(addressIP)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.AdvertiseAddress = ip.String()\n\n\treturn nil\n}\n\n\/\/ SetClusterDynamicDefaults checks and sets values for the ClusterConfiguration object\nfunc SetClusterDynamicDefaults(cfg *kubeadmapi.ClusterConfiguration, LocalAPIEndpoint *kubeadmapi.APIEndpoint) error {\n\t\/\/ Default all the embedded ComponentConfig structs\n\tcomponentconfigs.Default(cfg, LocalAPIEndpoint)\n\n\t\/\/ Resolve possible version labels and validate version string\n\tif err := NormalizeKubernetesVersion(cfg); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ If ControlPlaneEndpoint is specified without a port number defaults it to\n\t\/\/ the bindPort number of the APIEndpoint.\n\t\/\/ This will allow join of additional control plane instances with different bindPort number\n\tif cfg.ControlPlaneEndpoint != \"\" {\n\t\thost, port, err := kubeadmutil.ParseHostPort(cfg.ControlPlaneEndpoint)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif port == \"\" {\n\t\t\tcfg.ControlPlaneEndpoint = net.JoinHostPort(host, strconv.FormatInt(int64(LocalAPIEndpoint.BindPort), 10))\n\t\t}\n\t}\n\n\t\/\/ Downcase SANs. Some domain names (like ELBs) have capitals in them.\n\tLowercaseSANs(cfg.APIServer.CertSANs)\n\treturn nil\n}\n\n\/\/ DefaultedInitConfiguration takes a versioned init config (often populated by flags), defaults it and converts it into internal InitConfiguration\nfunc DefaultedInitConfiguration(versionedInitCfg *kubeadmapiv1beta2.InitConfiguration, versionedClusterCfg *kubeadmapiv1beta2.ClusterConfiguration) (*kubeadmapi.InitConfiguration, error) {\n\tinternalcfg := &kubeadmapi.InitConfiguration{}\n\n\t\/\/ Takes passed flags into account; the defaulting is executed once again enforcing assignment of\n\t\/\/ static default values to cfg only for values not provided with flags\n\tkubeadmscheme.Scheme.Default(versionedInitCfg)\n\tif err := kubeadmscheme.Scheme.Convert(versionedInitCfg, internalcfg, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\tkubeadmscheme.Scheme.Default(versionedClusterCfg)\n\tif err := kubeadmscheme.Scheme.Convert(versionedClusterCfg, &internalcfg.ClusterConfiguration, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Applies dynamic defaults to settings not provided with flags\n\tif err := SetInitDynamicDefaults(internalcfg); err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Validates cfg (flags\/configs + defaults + dynamic defaults)\n\tif err := validation.ValidateInitConfiguration(internalcfg).ToAggregate(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn internalcfg, nil\n}\n\n\/\/ LoadInitConfigurationFromFile loads a supported versioned InitConfiguration from a file, converts it into internal config, defaults it and verifies it.\nfunc LoadInitConfigurationFromFile(cfgPath string) (*kubeadmapi.InitConfiguration, error) {\n\tklog.V(1).Infof(\"loading configuration from %q\", cfgPath)\n\n\tb, err := ioutil.ReadFile(cfgPath)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to read config from %q \", cfgPath)\n\t}\n\n\treturn BytesToInitConfiguration(b)\n}\n\n\/\/ LoadOrDefaultInitConfiguration takes a path to a config file and a versioned configuration that can serve as the default config\n\/\/ If cfgPath is specified, the versioned configs will always get overridden with the one in the file (specified by cfgPath).\n\/\/ The external, versioned configuration is defaulted and converted to the internal type.\n\/\/ Right thereafter, the configuration is defaulted again with dynamic values (like IP addresses of a machine, etc)\n\/\/ Lastly, the internal config is validated and returned.\nfunc LoadOrDefaultInitConfiguration(cfgPath string, versionedInitCfg *kubeadmapiv1beta2.InitConfiguration, versionedClusterCfg *kubeadmapiv1beta2.ClusterConfiguration) (*kubeadmapi.InitConfiguration, error) {\n\tif cfgPath != \"\" {\n\t\t\/\/ Loads configuration from config file, if provided\n\t\t\/\/ Nb. --config overrides command line flags\n\t\treturn LoadInitConfigurationFromFile(cfgPath)\n\t}\n\n\treturn DefaultedInitConfiguration(versionedInitCfg, versionedClusterCfg)\n}\n\n\/\/ BytesToInitConfiguration converts a byte slice to an internal, defaulted and validated InitConfiguration object.\n\/\/ The map may contain many different YAML documents. These YAML documents are parsed one-by-one\n\/\/ and well-known ComponentConfig GroupVersionKinds are stored inside of the internal InitConfiguration struct.\n\/\/ The resulting InitConfiguration is then dynamically defaulted and validated prior to return.\nfunc BytesToInitConfiguration(b []byte) (*kubeadmapi.InitConfiguration, error) {\n\tgvkmap, err := kubeadmutil.SplitYAMLDocuments(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn documentMapToInitConfiguration(gvkmap, false)\n}\n\n\/\/ documentMapToInitConfiguration converts a map of GVKs and YAML documents to defaulted and validated configuration object.\nfunc documentMapToInitConfiguration(gvkmap kubeadmapi.DocumentMap, allowDeprecated bool) (*kubeadmapi.InitConfiguration, error) {\n\tvar initcfg *kubeadmapi.InitConfiguration\n\tvar clustercfg *kubeadmapi.ClusterConfiguration\n\n\tfor gvk, fileContent := range gvkmap {\n\t\t\/\/ first, check if this GVK is supported and possibly not deprecated\n\t\tif err := validateSupportedVersion(gvk.GroupVersion(), allowDeprecated); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ verify the validity of the YAML\n\t\tstrict.VerifyUnmarshalStrict(fileContent, gvk)\n\n\t\tif kubeadmutil.GroupVersionKindsHasInitConfiguration(gvk) {\n\t\t\t\/\/ Set initcfg to an empty struct value the deserializer will populate\n\t\t\tinitcfg = &kubeadmapi.InitConfiguration{}\n\t\t\t\/\/ Decode the bytes into the internal struct. Under the hood, the bytes will be unmarshalled into the\n\t\t\t\/\/ right external version, defaulted, and converted into the internal version.\n\t\t\tif err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), fileContent, initcfg); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif kubeadmutil.GroupVersionKindsHasClusterConfiguration(gvk) {\n\t\t\t\/\/ Set clustercfg to an empty struct value the deserializer will populate\n\t\t\tclustercfg = &kubeadmapi.ClusterConfiguration{}\n\t\t\t\/\/ Decode the bytes into the internal struct. Under the hood, the bytes will be unmarshalled into the\n\t\t\t\/\/ right external version, defaulted, and converted into the internal version.\n\t\t\tif err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), fileContent, clustercfg); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Printf(\"[config] WARNING: Ignored YAML document with GroupVersionKind %v\\n\", gvk)\n\t}\n\n\t\/\/ Enforce that InitConfiguration and\/or ClusterConfiguration has to exist among the YAML documents\n\tif initcfg == nil && clustercfg == nil {\n\t\treturn nil, errors.New(\"no InitConfiguration or ClusterConfiguration kind was found in the YAML file\")\n\t}\n\n\t\/\/ If InitConfiguration wasn't given, default it by creating an external struct instance, default it and convert into the internal type\n\tif initcfg == nil {\n\t\textinitcfg := &kubeadmapiv1beta2.InitConfiguration{}\n\t\tkubeadmscheme.Scheme.Default(extinitcfg)\n\t\t\/\/ Set initcfg to an empty struct value the deserializer will populate\n\t\tinitcfg = &kubeadmapi.InitConfiguration{}\n\t\tif err := kubeadmscheme.Scheme.Convert(extinitcfg, initcfg, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t\/\/ If ClusterConfiguration was given, populate it in the InitConfiguration struct\n\tif clustercfg != nil {\n\t\tinitcfg.ClusterConfiguration = *clustercfg\n\t}\n\n\t\/\/ Load any component configs\n\tif err := componentconfigs.FetchFromDocumentMap(&initcfg.ClusterConfiguration, gvkmap); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Applies dynamic defaults to settings not provided with flags\n\tif err := SetInitDynamicDefaults(initcfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Validates cfg (flags\/configs + defaults + dynamic defaults)\n\tif err := validation.ValidateInitConfiguration(initcfg).ToAggregate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn initcfg, nil\n}\n\n\/\/ MarshalInitConfigurationToBytes marshals the internal InitConfiguration object to bytes. It writes the embedded\n\/\/ ClusterConfiguration object with ComponentConfigs out as separate YAML documents\nfunc MarshalInitConfigurationToBytes(cfg *kubeadmapi.InitConfiguration, gv schema.GroupVersion) ([]byte, error) {\n\tinitbytes, err := kubeadmutil.MarshalToYamlForCodecs(cfg, gv, kubeadmscheme.Codecs)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tallFiles := [][]byte{initbytes}\n\n\t\/\/ Exception: If the specified groupversion is targeting the internal type, don't print embedded ClusterConfiguration contents\n\t\/\/ This is mostly used for unit testing. In a real scenario the internal version of the API is never marshalled as-is.\n\tif gv.Version != runtime.APIVersionInternal {\n\t\tclusterbytes, err := kubeadmutil.MarshalToYamlForCodecs(&cfg.ClusterConfiguration, gv, kubeadmscheme.Codecs)\n\t\tif err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t\tallFiles = append(allFiles, clusterbytes)\n\t}\n\treturn bytes.Join(allFiles, []byte(kubeadmconstants.YAMLDocumentSeparator)), nil\n}\n<commit_msg>kubeadm: Fix a false positive in a warning<commit_after>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage config\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"strconv\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"k8s.io\/klog\"\n\n\tv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\tnetutil \"k8s.io\/apimachinery\/pkg\/util\/net\"\n\tbootstraputil \"k8s.io\/cluster-bootstrap\/token\/util\"\n\tkubeadmapi \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\"\n\tkubeadmscheme \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\/scheme\"\n\tkubeadmapiv1beta2 \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\/v1beta2\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\/validation\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/componentconfigs\"\n\tkubeadmconstants \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/constants\"\n\tkubeadmutil \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/util\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/util\/config\/strict\"\n\tkubeadmruntime \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/util\/runtime\"\n)\n\n\/\/ SetInitDynamicDefaults checks and sets configuration values for the InitConfiguration object\nfunc SetInitDynamicDefaults(cfg *kubeadmapi.InitConfiguration) error {\n\tif err := SetBootstrapTokensDynamicDefaults(&cfg.BootstrapTokens); err != nil {\n\t\treturn err\n\t}\n\tif err := SetNodeRegistrationDynamicDefaults(&cfg.NodeRegistration, true); err != nil {\n\t\treturn err\n\t}\n\tif err := SetAPIEndpointDynamicDefaults(&cfg.LocalAPIEndpoint); err != nil {\n\t\treturn err\n\t}\n\treturn SetClusterDynamicDefaults(&cfg.ClusterConfiguration, &cfg.LocalAPIEndpoint)\n}\n\n\/\/ SetBootstrapTokensDynamicDefaults checks and sets configuration values for the BootstrapTokens object\nfunc SetBootstrapTokensDynamicDefaults(cfg *[]kubeadmapi.BootstrapToken) error {\n\t\/\/ Populate the .Token field with a random value if unset\n\t\/\/ We do this at this layer, and not the API defaulting layer\n\t\/\/ because of possible security concerns, and more practically\n\t\/\/ because we can't return errors in the API object defaulting\n\t\/\/ process but here we can.\n\tfor i, bt := range *cfg {\n\t\tif bt.Token != nil && len(bt.Token.String()) > 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\ttokenStr, err := bootstraputil.GenerateBootstrapToken()\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"couldn't generate random token\")\n\t\t}\n\t\ttoken, err := kubeadmapi.NewBootstrapTokenString(tokenStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t(*cfg)[i].Token = token\n\t}\n\n\treturn nil\n}\n\n\/\/ SetNodeRegistrationDynamicDefaults checks and sets configuration values for the NodeRegistration object\nfunc SetNodeRegistrationDynamicDefaults(cfg *kubeadmapi.NodeRegistrationOptions, ControlPlaneTaint bool) error {\n\tvar err error\n\tcfg.Name, err = kubeadmutil.GetHostname(cfg.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Only if the slice is nil, we should append the control-plane taint. This allows the user to specify an empty slice for no default control-plane taint\n\tif ControlPlaneTaint && cfg.Taints == nil {\n\t\tcfg.Taints = []v1.Taint{kubeadmconstants.ControlPlaneTaint}\n\t}\n\n\tif cfg.CRISocket == \"\" {\n\t\tcfg.CRISocket, err = kubeadmruntime.DetectCRISocket()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tklog.V(1).Infof(\"detected and using CRI socket: %s\", cfg.CRISocket)\n\t}\n\n\treturn nil\n}\n\n\/\/ SetAPIEndpointDynamicDefaults checks and sets configuration values for the APIEndpoint object\nfunc SetAPIEndpointDynamicDefaults(cfg *kubeadmapi.APIEndpoint) error {\n\t\/\/ validate cfg.API.AdvertiseAddress.\n\taddressIP := net.ParseIP(cfg.AdvertiseAddress)\n\tif addressIP == nil && cfg.AdvertiseAddress != \"\" {\n\t\treturn errors.Errorf(\"couldn't use \\\"%s\\\" as \\\"apiserver-advertise-address\\\", must be ipv4 or ipv6 address\", cfg.AdvertiseAddress)\n\t}\n\n\t\/\/ kubeadm allows users to specify address=Loopback as a selector for global unicast IP address that can be found on loopback interface.\n\t\/\/ e.g. This is required for network setups where default routes are present, but network interfaces use only link-local addresses (e.g. as described in RFC5549).\n\tif addressIP.IsLoopback() {\n\t\tloopbackIP, err := netutil.ChooseBindAddressForInterface(netutil.LoopbackInterfaceName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif loopbackIP != nil {\n\t\t\tklog.V(4).Infof(\"Found active IP %v on loopback interface\", loopbackIP.String())\n\t\t\tcfg.AdvertiseAddress = loopbackIP.String()\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"unable to resolve link-local addresses\")\n\t}\n\n\t\/\/ This is the same logic as the API Server uses, except that if no interface is found the address is set to 0.0.0.0, which is invalid and cannot be used\n\t\/\/ for bootstrapping a cluster.\n\tip, err := ChooseAPIServerBindAddress(addressIP)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.AdvertiseAddress = ip.String()\n\n\treturn nil\n}\n\n\/\/ SetClusterDynamicDefaults checks and sets values for the ClusterConfiguration object\nfunc SetClusterDynamicDefaults(cfg *kubeadmapi.ClusterConfiguration, LocalAPIEndpoint *kubeadmapi.APIEndpoint) error {\n\t\/\/ Default all the embedded ComponentConfig structs\n\tcomponentconfigs.Default(cfg, LocalAPIEndpoint)\n\n\t\/\/ Resolve possible version labels and validate version string\n\tif err := NormalizeKubernetesVersion(cfg); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ If ControlPlaneEndpoint is specified without a port number defaults it to\n\t\/\/ the bindPort number of the APIEndpoint.\n\t\/\/ This will allow join of additional control plane instances with different bindPort number\n\tif cfg.ControlPlaneEndpoint != \"\" {\n\t\thost, port, err := kubeadmutil.ParseHostPort(cfg.ControlPlaneEndpoint)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif port == \"\" {\n\t\t\tcfg.ControlPlaneEndpoint = net.JoinHostPort(host, strconv.FormatInt(int64(LocalAPIEndpoint.BindPort), 10))\n\t\t}\n\t}\n\n\t\/\/ Downcase SANs. Some domain names (like ELBs) have capitals in them.\n\tLowercaseSANs(cfg.APIServer.CertSANs)\n\treturn nil\n}\n\n\/\/ DefaultedInitConfiguration takes a versioned init config (often populated by flags), defaults it and converts it into internal InitConfiguration\nfunc DefaultedInitConfiguration(versionedInitCfg *kubeadmapiv1beta2.InitConfiguration, versionedClusterCfg *kubeadmapiv1beta2.ClusterConfiguration) (*kubeadmapi.InitConfiguration, error) {\n\tinternalcfg := &kubeadmapi.InitConfiguration{}\n\n\t\/\/ Takes passed flags into account; the defaulting is executed once again enforcing assignment of\n\t\/\/ static default values to cfg only for values not provided with flags\n\tkubeadmscheme.Scheme.Default(versionedInitCfg)\n\tif err := kubeadmscheme.Scheme.Convert(versionedInitCfg, internalcfg, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\tkubeadmscheme.Scheme.Default(versionedClusterCfg)\n\tif err := kubeadmscheme.Scheme.Convert(versionedClusterCfg, &internalcfg.ClusterConfiguration, nil); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Applies dynamic defaults to settings not provided with flags\n\tif err := SetInitDynamicDefaults(internalcfg); err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Validates cfg (flags\/configs + defaults + dynamic defaults)\n\tif err := validation.ValidateInitConfiguration(internalcfg).ToAggregate(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn internalcfg, nil\n}\n\n\/\/ LoadInitConfigurationFromFile loads a supported versioned InitConfiguration from a file, converts it into internal config, defaults it and verifies it.\nfunc LoadInitConfigurationFromFile(cfgPath string) (*kubeadmapi.InitConfiguration, error) {\n\tklog.V(1).Infof(\"loading configuration from %q\", cfgPath)\n\n\tb, err := ioutil.ReadFile(cfgPath)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to read config from %q \", cfgPath)\n\t}\n\n\treturn BytesToInitConfiguration(b)\n}\n\n\/\/ LoadOrDefaultInitConfiguration takes a path to a config file and a versioned configuration that can serve as the default config\n\/\/ If cfgPath is specified, the versioned configs will always get overridden with the one in the file (specified by cfgPath).\n\/\/ The external, versioned configuration is defaulted and converted to the internal type.\n\/\/ Right thereafter, the configuration is defaulted again with dynamic values (like IP addresses of a machine, etc)\n\/\/ Lastly, the internal config is validated and returned.\nfunc LoadOrDefaultInitConfiguration(cfgPath string, versionedInitCfg *kubeadmapiv1beta2.InitConfiguration, versionedClusterCfg *kubeadmapiv1beta2.ClusterConfiguration) (*kubeadmapi.InitConfiguration, error) {\n\tif cfgPath != \"\" {\n\t\t\/\/ Loads configuration from config file, if provided\n\t\t\/\/ Nb. --config overrides command line flags\n\t\treturn LoadInitConfigurationFromFile(cfgPath)\n\t}\n\n\treturn DefaultedInitConfiguration(versionedInitCfg, versionedClusterCfg)\n}\n\n\/\/ BytesToInitConfiguration converts a byte slice to an internal, defaulted and validated InitConfiguration object.\n\/\/ The map may contain many different YAML documents. These YAML documents are parsed one-by-one\n\/\/ and well-known ComponentConfig GroupVersionKinds are stored inside of the internal InitConfiguration struct.\n\/\/ The resulting InitConfiguration is then dynamically defaulted and validated prior to return.\nfunc BytesToInitConfiguration(b []byte) (*kubeadmapi.InitConfiguration, error) {\n\tgvkmap, err := kubeadmutil.SplitYAMLDocuments(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn documentMapToInitConfiguration(gvkmap, false)\n}\n\n\/\/ documentMapToInitConfiguration converts a map of GVKs and YAML documents to defaulted and validated configuration object.\nfunc documentMapToInitConfiguration(gvkmap kubeadmapi.DocumentMap, allowDeprecated bool) (*kubeadmapi.InitConfiguration, error) {\n\tvar initcfg *kubeadmapi.InitConfiguration\n\tvar clustercfg *kubeadmapi.ClusterConfiguration\n\n\tfor gvk, fileContent := range gvkmap {\n\t\t\/\/ first, check if this GVK is supported and possibly not deprecated\n\t\tif err := validateSupportedVersion(gvk.GroupVersion(), allowDeprecated); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ verify the validity of the YAML\n\t\tstrict.VerifyUnmarshalStrict(fileContent, gvk)\n\n\t\tif kubeadmutil.GroupVersionKindsHasInitConfiguration(gvk) {\n\t\t\t\/\/ Set initcfg to an empty struct value the deserializer will populate\n\t\t\tinitcfg = &kubeadmapi.InitConfiguration{}\n\t\t\t\/\/ Decode the bytes into the internal struct. Under the hood, the bytes will be unmarshalled into the\n\t\t\t\/\/ right external version, defaulted, and converted into the internal version.\n\t\t\tif err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), fileContent, initcfg); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif kubeadmutil.GroupVersionKindsHasClusterConfiguration(gvk) {\n\t\t\t\/\/ Set clustercfg to an empty struct value the deserializer will populate\n\t\t\tclustercfg = &kubeadmapi.ClusterConfiguration{}\n\t\t\t\/\/ Decode the bytes into the internal struct. Under the hood, the bytes will be unmarshalled into the\n\t\t\t\/\/ right external version, defaulted, and converted into the internal version.\n\t\t\tif err := runtime.DecodeInto(kubeadmscheme.Codecs.UniversalDecoder(), fileContent, clustercfg); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ If the group is neither a kubeadm core type or of a supported component config group, we dump a warning about it being ignored\n\t\tif !componentconfigs.Scheme.IsGroupRegistered(gvk.Group) {\n\t\t\tfmt.Printf(\"[config] WARNING: Ignored YAML document with GroupVersionKind %v\\n\", gvk)\n\t\t}\n\t}\n\n\t\/\/ Enforce that InitConfiguration and\/or ClusterConfiguration has to exist among the YAML documents\n\tif initcfg == nil && clustercfg == nil {\n\t\treturn nil, errors.New(\"no InitConfiguration or ClusterConfiguration kind was found in the YAML file\")\n\t}\n\n\t\/\/ If InitConfiguration wasn't given, default it by creating an external struct instance, default it and convert into the internal type\n\tif initcfg == nil {\n\t\textinitcfg := &kubeadmapiv1beta2.InitConfiguration{}\n\t\tkubeadmscheme.Scheme.Default(extinitcfg)\n\t\t\/\/ Set initcfg to an empty struct value the deserializer will populate\n\t\tinitcfg = &kubeadmapi.InitConfiguration{}\n\t\tif err := kubeadmscheme.Scheme.Convert(extinitcfg, initcfg, nil); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t\/\/ If ClusterConfiguration was given, populate it in the InitConfiguration struct\n\tif clustercfg != nil {\n\t\tinitcfg.ClusterConfiguration = *clustercfg\n\t}\n\n\t\/\/ Load any component configs\n\tif err := componentconfigs.FetchFromDocumentMap(&initcfg.ClusterConfiguration, gvkmap); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Applies dynamic defaults to settings not provided with flags\n\tif err := SetInitDynamicDefaults(initcfg); err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Validates cfg (flags\/configs + defaults + dynamic defaults)\n\tif err := validation.ValidateInitConfiguration(initcfg).ToAggregate(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn initcfg, nil\n}\n\n\/\/ MarshalInitConfigurationToBytes marshals the internal InitConfiguration object to bytes. It writes the embedded\n\/\/ ClusterConfiguration object with ComponentConfigs out as separate YAML documents\nfunc MarshalInitConfigurationToBytes(cfg *kubeadmapi.InitConfiguration, gv schema.GroupVersion) ([]byte, error) {\n\tinitbytes, err := kubeadmutil.MarshalToYamlForCodecs(cfg, gv, kubeadmscheme.Codecs)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\tallFiles := [][]byte{initbytes}\n\n\t\/\/ Exception: If the specified groupversion is targeting the internal type, don't print embedded ClusterConfiguration contents\n\t\/\/ This is mostly used for unit testing. In a real scenario the internal version of the API is never marshalled as-is.\n\tif gv.Version != runtime.APIVersionInternal {\n\t\tclusterbytes, err := kubeadmutil.MarshalToYamlForCodecs(&cfg.ClusterConfiguration, gv, kubeadmscheme.Codecs)\n\t\tif err != nil {\n\t\t\treturn []byte{}, err\n\t\t}\n\t\tallFiles = append(allFiles, clusterbytes)\n\t}\n\treturn bytes.Join(allFiles, []byte(kubeadmconstants.YAMLDocumentSeparator)), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016, RadiantBlue Technologies, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage workflow\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/venicegeo\/pz-gocommon\/elasticsearch\"\n\t\"github.com\/venicegeo\/pz-gocommon\/gocommon\"\n)\n\ntype TriggerDB struct {\n\t*ResourceDB\n\tmapping string\n}\n\nfunc NewTriggerDB(service *WorkflowService, esi elasticsearch.IIndex) (*TriggerDB, error) {\n\n\trdb, err := NewResourceDB(service, esi, TriggerIndexSettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tardb := TriggerDB{ResourceDB: rdb, mapping: TriggerDBMapping}\n\treturn &ardb, nil\n}\n\nfunc (db *TriggerDB) PostTrigger(trigger *Trigger, id piazza.Ident) (piazza.Ident, error) {\n\n\t{ \/\/CHECK SERVICE EXISTS\n\t\tjobData := trigger.Job.JobType.Data\n\t\tserviceId := jobData[\"serviceId\"]\n\t\tstrServiceId, ok := serviceId.(string)\n\t\tif !ok {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData faile: serviceId field not of type string\")\n\t\t}\n\t\tserviceControllerURL, err := db.service.sys.GetURL(\"pz-servicecontroller\")\n\t\tif err != nil {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed to find ServiceController: %s\", err)\n\t\t}\n\t\tresponse, err := http.Get(serviceControllerURL)\n\t\tif err != nil {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed to make request to ServiceController: %s\", err)\n\t\t}\n\t\tif response.StatusCode != 200 {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData: serviceId %s does not exist\", strServiceId)\n\t\t}\n\t}\n\n\tifaceObj := trigger.Condition.Query\n\t\/\/log.Printf(\"Query: %v\", ifaceObj)\n\tbody, err := json.Marshal(ifaceObj)\n\tif err != nil {\n\t\treturn piazza.NoIdent, err\n\t}\n\n\tjson := string(body)\n\t\/\/log.Printf(\"Current json: %s\", json)\n\t\/\/ Remove trailing }\n\tjson = json[:len(json)-1]\n\tjson += \",\\\"type\\\":[\"\n\t\/\/ Add the types that the percolation query can match\n\tfor _, id := range trigger.Condition.EventTypeIds {\n\t\tjson += fmt.Sprintf(\"\\\"%s\\\",\", id)\n\t}\n\tjson = json[:len(json)-1]\n\t\/\/ Add back trailing } and ] to close array\n\tjson += \"]}\"\n\n\t\/\/log.Printf(\"Posting percolation query: %s\", body)\n\tindexResult, err := db.service.eventDB.Esi.AddPercolationQuery(string(trigger.TriggerId), piazza.JsonString(body))\n\tif err != nil {\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData addpercquery failed: %s\", err)\n\t}\n\tif indexResult == nil {\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData addpercquery failed: no indexResult\")\n\t}\n\tif !indexResult.Created {\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData addpercquery failed: not created\")\n\t}\n\n\t\/\/log.Printf(\"percolation query added: ID: %s, Type: %s, Index: %s\", indexResult.Id, indexResult.Type, indexResult.Index)\n\t\/\/log.Printf(\"percolation id: %s\", indexResult.Id)\n\ttrigger.PercolationId = piazza.Ident(indexResult.Id)\n\n\tindexResult2, err := db.Esi.PostData(db.mapping, id.String(), trigger)\n\tif err != nil {\n\t\tdb.service.eventDB.Esi.DeletePercolationQuery(string(trigger.TriggerId))\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed: %s\", err)\n\t}\n\tif !indexResult2.Created {\n\t\tdb.service.eventDB.Esi.DeletePercolationQuery(string(trigger.TriggerId))\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed: not created\")\n\t}\n\n\treturn id, nil\n}\n\nfunc (db *TriggerDB) GetAll(format *piazza.JsonPagination) ([]Trigger, int64, error) {\n\ttriggers := []Trigger{}\n\n\texists, err := db.Esi.TypeExists(db.mapping)\n\tif err != nil {\n\t\treturn triggers, 0, err\n\t}\n\tif !exists {\n\t\treturn triggers, 0, nil\n\t}\n\n\tsearchResult, err := db.Esi.FilterByMatchAll(db.mapping, format)\n\tif err != nil {\n\t\treturn nil, 0, LoggedError(\"TriggerDB.GetAll failed: %s\", err)\n\t}\n\tif searchResult == nil {\n\t\treturn nil, 0, LoggedError(\"TriggerDB.GetAll failed: no searchResult\")\n\t}\n\n\tif searchResult != nil && searchResult.GetHits() != nil {\n\n\t\tfor _, hit := range *searchResult.GetHits() {\n\t\t\tvar trigger Trigger\n\t\t\terr := json.Unmarshal(*hit.Source, &trigger)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\ttriggers = append(triggers, trigger)\n\t\t}\n\t}\n\treturn triggers, searchResult.TotalHits(), nil\n}\n\nfunc (db *TriggerDB) GetOne(id piazza.Ident) (*Trigger, bool, error) {\n\n\tgetResult, err := db.Esi.GetByID(db.mapping, id.String())\n\tif err != nil {\n\t\treturn nil, getResult.Found, LoggedError(\"TriggerDB.GetOne failed: %s\", err)\n\t}\n\tif getResult == nil {\n\t\treturn nil, true, LoggedError(\"TriggerDB.GetOne failed: no getResult\")\n\t}\n\n\tsrc := getResult.Source\n\tvar obj Trigger\n\terr = json.Unmarshal(*src, &obj)\n\tif err != nil {\n\t\treturn nil, getResult.Found, err\n\t}\n\n\treturn &obj, getResult.Found, nil\n}\n\nfunc (db *TriggerDB) DeleteTrigger(id piazza.Ident) (bool, error) {\n\n\ttrigger, found, err := db.GetOne(id)\n\tif err != nil {\n\t\treturn found, err\n\t}\n\tif trigger == nil {\n\t\treturn false, nil\n\t}\n\n\tdeleteResult, err := db.Esi.DeleteByID(db.mapping, string(id))\n\tif err != nil {\n\t\treturn deleteResult.Found, LoggedError(\"TriggerDB.DeleteById failed: %s\", err)\n\t}\n\tif deleteResult == nil {\n\t\treturn false, LoggedError(\"TriggerDB.DeleteById failed: no deleteResult\")\n\t}\n\tif !deleteResult.Found {\n\t\treturn false, nil\n\t}\n\n\tdeleteResult2, err := db.service.eventDB.Esi.DeletePercolationQuery(string(trigger.PercolationId))\n\tif err != nil {\n\t\treturn deleteResult2.Found, LoggedError(\"TriggerDB.DeleteById percquery failed: %s\", err)\n\t}\n\tif deleteResult2 == nil {\n\t\treturn false, LoggedError(\"TriggerDB.DeleteById percquery failed: no deleteResult\")\n\t}\n\n\treturn deleteResult2.Found, nil\n}\n<commit_msg>guard service controller usage when mocked<commit_after>\/\/ Copyright 2016, RadiantBlue Technologies, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage workflow\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/venicegeo\/pz-gocommon\/elasticsearch\"\n\t\"github.com\/venicegeo\/pz-gocommon\/gocommon\"\n)\n\ntype TriggerDB struct {\n\t*ResourceDB\n\tmapping string\n}\n\nfunc NewTriggerDB(service *WorkflowService, esi elasticsearch.IIndex) (*TriggerDB, error) {\n\n\trdb, err := NewResourceDB(service, esi, TriggerIndexSettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tardb := TriggerDB{ResourceDB: rdb, mapping: TriggerDBMapping}\n\treturn &ardb, nil\n}\n\nfunc (db *TriggerDB) PostTrigger(trigger *Trigger, id piazza.Ident) (piazza.Ident, error) {\n\n\t{ \/\/CHECK SERVICE EXISTS\n\t\tjobData := trigger.Job.JobType.Data\n\t\tserviceId := jobData[\"serviceId\"]\n\t\tstrServiceId, ok := serviceId.(string)\n\t\tif !ok {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData faile: serviceId field not of type string\")\n\t\t}\n\t\tserviceControllerURL, err := db.service.sys.GetURL(\"pz-servicecontroller\")\n\t\tif err == nil {\n\t\t\t\/\/ TODO:\n\t\t\t\/\/ if err is nil, we have a servicecontroller to talk to\n\t\t\t\/\/ if err is not nil, we'll assume we are mocking (which means\n\t\t\t\/\/ we have no servicecontroller client to mock)\n\t\t\tresponse, err := http.Get(serviceControllerURL)\n\t\t\tif err != nil {\n\t\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed to make request to ServiceController: %s\", err)\n\t\t\t}\n\t\t\tif response.StatusCode != 200 {\n\t\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData: serviceId %s does not exist\", strServiceId)\n\t\t\t}\n\t\t}\n\t}\n\n\tifaceObj := trigger.Condition.Query\n\t\/\/log.Printf(\"Query: %v\", ifaceObj)\n\tbody, err := json.Marshal(ifaceObj)\n\tif err != nil {\n\t\treturn piazza.NoIdent, err\n\t}\n\n\tjson := string(body)\n\t\/\/log.Printf(\"Current json: %s\", json)\n\t\/\/ Remove trailing }\n\tjson = json[:len(json)-1]\n\tjson += \",\\\"type\\\":[\"\n\t\/\/ Add the types that the percolation query can match\n\tfor _, id := range trigger.Condition.EventTypeIds {\n\t\tjson += fmt.Sprintf(\"\\\"%s\\\",\", id)\n\t}\n\tjson = json[:len(json)-1]\n\t\/\/ Add back trailing } and ] to close array\n\tjson += \"]}\"\n\n\t\/\/log.Printf(\"Posting percolation query: %s\", body)\n\tindexResult, err := db.service.eventDB.Esi.AddPercolationQuery(string(trigger.TriggerId), piazza.JsonString(body))\n\tif err != nil {\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData addpercquery failed: %s\", err)\n\t}\n\tif indexResult == nil {\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData addpercquery failed: no indexResult\")\n\t}\n\tif !indexResult.Created {\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData addpercquery failed: not created\")\n\t}\n\n\t\/\/log.Printf(\"percolation query added: ID: %s, Type: %s, Index: %s\", indexResult.Id, indexResult.Type, indexResult.Index)\n\t\/\/log.Printf(\"percolation id: %s\", indexResult.Id)\n\ttrigger.PercolationId = piazza.Ident(indexResult.Id)\n\n\tindexResult2, err := db.Esi.PostData(db.mapping, id.String(), trigger)\n\tif err != nil {\n\t\tdb.service.eventDB.Esi.DeletePercolationQuery(string(trigger.TriggerId))\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed: %s\", err)\n\t}\n\tif !indexResult2.Created {\n\t\tdb.service.eventDB.Esi.DeletePercolationQuery(string(trigger.TriggerId))\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed: not created\")\n\t}\n\n\treturn id, nil\n}\n\nfunc (db *TriggerDB) GetAll(format *piazza.JsonPagination) ([]Trigger, int64, error) {\n\ttriggers := []Trigger{}\n\n\texists, err := db.Esi.TypeExists(db.mapping)\n\tif err != nil {\n\t\treturn triggers, 0, err\n\t}\n\tif !exists {\n\t\treturn triggers, 0, nil\n\t}\n\n\tsearchResult, err := db.Esi.FilterByMatchAll(db.mapping, format)\n\tif err != nil {\n\t\treturn nil, 0, LoggedError(\"TriggerDB.GetAll failed: %s\", err)\n\t}\n\tif searchResult == nil {\n\t\treturn nil, 0, LoggedError(\"TriggerDB.GetAll failed: no searchResult\")\n\t}\n\n\tif searchResult != nil && searchResult.GetHits() != nil {\n\n\t\tfor _, hit := range *searchResult.GetHits() {\n\t\t\tvar trigger Trigger\n\t\t\terr := json.Unmarshal(*hit.Source, &trigger)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\ttriggers = append(triggers, trigger)\n\t\t}\n\t}\n\treturn triggers, searchResult.TotalHits(), nil\n}\n\nfunc (db *TriggerDB) GetOne(id piazza.Ident) (*Trigger, bool, error) {\n\n\tgetResult, err := db.Esi.GetByID(db.mapping, id.String())\n\tif err != nil {\n\t\treturn nil, getResult.Found, LoggedError(\"TriggerDB.GetOne failed: %s\", err)\n\t}\n\tif getResult == nil {\n\t\treturn nil, true, LoggedError(\"TriggerDB.GetOne failed: no getResult\")\n\t}\n\n\tsrc := getResult.Source\n\tvar obj Trigger\n\terr = json.Unmarshal(*src, &obj)\n\tif err != nil {\n\t\treturn nil, getResult.Found, err\n\t}\n\n\treturn &obj, getResult.Found, nil\n}\n\nfunc (db *TriggerDB) DeleteTrigger(id piazza.Ident) (bool, error) {\n\n\ttrigger, found, err := db.GetOne(id)\n\tif err != nil {\n\t\treturn found, err\n\t}\n\tif trigger == nil {\n\t\treturn false, nil\n\t}\n\n\tdeleteResult, err := db.Esi.DeleteByID(db.mapping, string(id))\n\tif err != nil {\n\t\treturn deleteResult.Found, LoggedError(\"TriggerDB.DeleteById failed: %s\", err)\n\t}\n\tif deleteResult == nil {\n\t\treturn false, LoggedError(\"TriggerDB.DeleteById failed: no deleteResult\")\n\t}\n\tif !deleteResult.Found {\n\t\treturn false, nil\n\t}\n\n\tdeleteResult2, err := db.service.eventDB.Esi.DeletePercolationQuery(string(trigger.PercolationId))\n\tif err != nil {\n\t\treturn deleteResult2.Found, LoggedError(\"TriggerDB.DeleteById percquery failed: %s\", err)\n\t}\n\tif deleteResult2 == nil {\n\t\treturn false, LoggedError(\"TriggerDB.DeleteById percquery failed: no deleteResult\")\n\t}\n\n\treturn deleteResult2.Found, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package vision\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/daviddengcn\/go-assert\"\n)\n\nfunc TestLoad(t *testing.T) {\n\tdatasets := [...]struct {\n\t\twidth, height int\n\t\tfn            string\n\t}{\n\t\t{177, 177, \"gray-177x177.jpg\"},\n\t\t{500, 374, \"ycbcr-500x374.jpg\"},\n\t\t{500, 374, \"pal-500x374.gif\"},\n\t\t{16, 16, \"nrgba-16x16.png\"},\n\t}\n\n\tos.MkdirAll(\"testout\", 0755)\n\n\tfor _, d := range datasets {\n\t\timg, err := ImageFromFile(\"testdata\/\" + d.fn)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tt.Logf(\"Image loaded: %v\", d.fn)\n\n\t\tvar m GrayImage\n\t\tm.SetImage(img)\n\n\t\tif m.Width != d.width || m.Height != d.height {\n\t\t\tt.Errorf(\"(GrayImage) Wrong size: %d, %d, expected %d, %d\",\n\t\t\t\tm.Width, m.Height, d.width, d.height)\n\t\t}\n\t\toutImg := m.AsImage()\n\t\tif outImg.Bounds().Dx() != d.width || outImg.Bounds().Dy() != d.height {\n\t\t\tt.Errorf(\"(AsImage) Wrong size: %d, %d, expected %d, %d\",\n\t\t\t\toutImg.Bounds().Dx, outImg.Bounds().Dy, d.width, d.height)\n\t\t}\n\n\t\tif err := SaveImageAsPng(outImg, \"testout\/gray-\"+d.fn+\".png\"); err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar rgbImg RGBImage\n\t\trgbImg.SetImage(img)\n\t\tif rgbImg.Width != d.width || rgbImg.Height != d.height {\n\t\t\tt.Errorf(\"(RGBImage) Wrong size: %d, %d, expected %d, %d\",\n\t\t\t\trgbImg.Width, rgbImg.Height, d.width, d.height)\n\t\t}\n\n\t\toutImg = rgbImg.AsImage()\n\t\tif outImg.Bounds().Dx() != d.width || outImg.Bounds().Dy() != d.height {\n\t\t\tt.Errorf(\"(AsImage) Wrong size: %d, %d, expected %d, %d\",\n\t\t\t\toutImg.Bounds().Dx, outImg.Bounds().Dy, d.width, d.height)\n\t\t}\n\n\t\tif err := SaveImageAsPng(outImg, \"testout\/rgb-\"+d.fn+\".png\"); err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\nfunc TestResize(t *testing.T) {\n\tvar gray GrayImage\n\tgray.Resize(Size{123, 456})\n\tassert.Equals(t, \"Size\", gray.Size, Size{123, 456})\n\tassert.Equals(t, \"len(Pixels)\", len(gray.Pixels), 123*456)\n\n\tvar ig IntGrayImage\n\tig.Resize(Size{123, 555})\n\tassert.Equals(t, \"Size\", ig.Size, Size{123, 555})\n\tassert.Equals(t, \"len(Pixels)\", len(ig.Pixels), 123*555)\n\n\tvar rgb RGBImage\n\trgb.Resize(Size{123, 456})\n\tassert.Equals(t, \"Size\", rgb.Size, Size{123, 456})\n\tassert.Equals(t, \"len(Pixels)\", len(rgb.Pixels), 123*456)\n}\n\nfunc TestFill(t *testing.T) {\n\tvar gray GrayImage\n\tgray.Resize(Size{456, 123})\n\tgray.Fill(123)\n\tassert.Equals(t, \"[0,0]\", gray.Pixels[0], byte(123))\n\t\n\tvar ig IntGrayImage\n\tig.Resize(Size{555, 123})\n\tig.Fill(12345)\n\tassert.Equals(t, \"[0,0]\", ig.Pixels[0], int(12345))\n\t\n\tvar rgb RGBImage\n\trgb.Resize(Size{456, 123})\n\trgb.Fill(RGB{1, 2, 3})\n\tassert.Equals(t, \"[0,0]\", rgb.Pixels[0], RGB{1, 2, 3})\n}<commit_msg>Fix a format bug found by go vet<commit_after>package vision\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/daviddengcn\/go-assert\"\n)\n\nfunc TestLoad(t *testing.T) {\n\tdatasets := [...]struct {\n\t\twidth, height int\n\t\tfn            string\n\t}{\n\t\t{177, 177, \"gray-177x177.jpg\"},\n\t\t{500, 374, \"ycbcr-500x374.jpg\"},\n\t\t{500, 374, \"pal-500x374.gif\"},\n\t\t{16, 16, \"nrgba-16x16.png\"},\n\t}\n\n\tos.MkdirAll(\"testout\", 0755)\n\n\tfor _, d := range datasets {\n\t\timg, err := ImageFromFile(\"testdata\/\" + d.fn)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tt.Logf(\"Image loaded: %v\", d.fn)\n\n\t\tvar m GrayImage\n\t\tm.SetImage(img)\n\n\t\tif m.Width != d.width || m.Height != d.height {\n\t\t\tt.Errorf(\"(GrayImage) Wrong size: %d, %d, expected %d, %d\",\n\t\t\t\tm.Width, m.Height, d.width, d.height)\n\t\t}\n\t\toutImg := m.AsImage()\n\t\tif outImg.Bounds().Dx() != d.width || outImg.Bounds().Dy() != d.height {\n\t\t\tt.Errorf(\"(AsImage) Wrong size: %d, %d, expected %d, %d\",\n\t\t\t\toutImg.Bounds().Dx(), outImg.Bounds().Dy(), d.width, d.height)\n\t\t}\n\n\t\tif err := SaveImageAsPng(outImg, \"testout\/gray-\"+d.fn+\".png\"); err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar rgbImg RGBImage\n\t\trgbImg.SetImage(img)\n\t\tif rgbImg.Width != d.width || rgbImg.Height != d.height {\n\t\t\tt.Errorf(\"(RGBImage) Wrong size: %d, %d, expected %d, %d\",\n\t\t\t\trgbImg.Width, rgbImg.Height, d.width, d.height)\n\t\t}\n\n\t\toutImg = rgbImg.AsImage()\n\t\tif outImg.Bounds().Dx() != d.width || outImg.Bounds().Dy() != d.height {\n\t\t\tt.Errorf(\"(AsImage) Wrong size: %d, %d, expected %d, %d\",\n\t\t\t\toutImg.Bounds().Dx(), outImg.Bounds().Dy(), d.width, d.height)\n\t\t}\n\n\t\tif err := SaveImageAsPng(outImg, \"testout\/rgb-\"+d.fn+\".png\"); err != nil {\n\t\t\tt.Error(err)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\nfunc TestResize(t *testing.T) {\n\tvar gray GrayImage\n\tgray.Resize(Size{123, 456})\n\tassert.Equals(t, \"Size\", gray.Size, Size{123, 456})\n\tassert.Equals(t, \"len(Pixels)\", len(gray.Pixels), 123*456)\n\n\tvar ig IntGrayImage\n\tig.Resize(Size{123, 555})\n\tassert.Equals(t, \"Size\", ig.Size, Size{123, 555})\n\tassert.Equals(t, \"len(Pixels)\", len(ig.Pixels), 123*555)\n\n\tvar rgb RGBImage\n\trgb.Resize(Size{123, 456})\n\tassert.Equals(t, \"Size\", rgb.Size, Size{123, 456})\n\tassert.Equals(t, \"len(Pixels)\", len(rgb.Pixels), 123*456)\n}\n\nfunc TestFill(t *testing.T) {\n\tvar gray GrayImage\n\tgray.Resize(Size{456, 123})\n\tgray.Fill(123)\n\tassert.Equals(t, \"[0,0]\", gray.Pixels[0], byte(123))\n\n\tvar ig IntGrayImage\n\tig.Resize(Size{555, 123})\n\tig.Fill(12345)\n\tassert.Equals(t, \"[0,0]\", ig.Pixels[0], int(12345))\n\n\tvar rgb RGBImage\n\trgb.Resize(Size{456, 123})\n\trgb.Fill(RGB{1, 2, 3})\n\tassert.Equals(t, \"[0,0]\", rgb.Pixels[0], RGB{1, 2, 3})\n}\n<|endoftext|>"}
{"text":"<commit_before>package gitstats\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t. \"github.com\/intelsdi-x\/snap-plugin-utilities\/logger\"\n\t\"github.com\/intelsdi-x\/snap\/control\/plugin\"\n\t\"github.com\/intelsdi-x\/snap\/control\/plugin\/cpolicy\"\n\t\"github.com\/intelsdi-x\/snap\/core\"\n\t\"github.com\/intelsdi-x\/snap\/core\/ctypes\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nconst (\n\t\/\/ Name of plugin\n\tName = \"rt-gitstats\"\n\t\/\/ Version of plugin\n\tVersion = 1\n\t\/\/ Type of plugin\n\tType = plugin.CollectorPluginType\n)\n\n\/\/ make sure that we actually satisify requierd interface\nvar _ plugin.CollectorPlugin = (*Gitstats)(nil)\n\nvar (\n\trepoMetricNames = []string{\n\t\t\"forks\",\n\t\t\"issues\",\n\t\t\"network\",\n\t\t\"stars\",\n\t\t\"subscribers\",\n\t\t\"watches\",\n\t\t\"size\",\n\t}\n\tuserMetricNames = []string{\n\t\t\"public_repos\",\n\t\t\"public_gists\",\n\t\t\"followers\",\n\t\t\"following\",\n\t\t\"private_repos\",\n\t\t\"private_gists\",\n\t\t\"plan_private_repos\",\n\t\t\"plan_seats\",\n\t\t\"plan_filled_seats\",\n\t}\n)\n\ntype Gitstats struct {\n}\n\n\/\/ CollectMetrics collects metrics for testing\nfunc (f *Gitstats) CollectMetrics(mts []plugin.MetricType) ([]plugin.MetricType, error) {\n\tvar err error\n\n\tconf := mts[0].Config().Table()\n\taccessToken, ok := conf[\"access_token\"]\n\tif !ok || accessToken.(ctypes.ConfigValueStr).Value == \"\" {\n\t\treturn nil, fmt.Errorf(\"access token missing from config, %v\", conf)\n\t}\n\n\tmetrics, err := gitStats(accessToken.(ctypes.ConfigValueStr).Value, mts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn metrics, nil\n}\n\ntype repoName struct {\n\tRepo  string\n\tOwner string\n}\n\nfunc gitStats(accessToken string, mts []plugin.MetricType) ([]plugin.MetricType, error) {\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: accessToken},\n\t)\n\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\tclient := github.NewClient(tc)\n\tcollectionTime := time.Now()\n\trepos := make(map[string]map[string]map[string]int)\n\tusers := make(map[string]map[string]int)\n\n\tuserRepos := make(map[string]struct{})\n\n\tauthUser := \"\"\n\tmetrics := make([]plugin.MetricType, 0)\n\n\tfor _, m := range mts {\n\t\tns := m.Namespace().Strings()\n\t\tswitch ns[3] {\n\t\tcase \"repo\":\n\t\t\tuser := ns[4]\n\t\t\trepo := ns[5]\n\t\t\tstat := ns[6]\n\n\t\t\tif user == \"*\" {\n\t\t\t\t\/\/need to get user\n\t\t\t\tif authUser == \"\" {\n\t\t\t\t\tgitUser, _, err := client.Users.Get(\"\")\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get authenticated user.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tstats, err := userStats(gitUser, client)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get stats from user object.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tusers[*gitUser.Login] = stats\n\t\t\t\t\tauthUser = *gitUser.Login\n\t\t\t\t}\n\t\t\t\tuser = authUser\n\t\t\t}\n\t\t\tif repo == \"*\" {\n\t\t\t\t\/\/ we only need to list a users repos once.\n\t\t\t\tif _, ok := userRepos[user]; !ok {\n\t\t\t\t\trepoList, _, err := client.Repositories.List(user, nil)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get repos owned by user.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tuserRepos[user] = struct{}{}\n\t\t\t\t\tif _, ok := repos[user]; !ok {\n\t\t\t\t\t\trepos[user] = make(map[string]map[string]int)\n\t\t\t\t\t}\n\t\t\t\t\tfor _, r := range repoList {\n\t\t\t\t\t\tstats, err := repoStats(&r)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tLogError(\"failed to get stats from repo object.\", err)\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\t\t\t\t\t\trepos[user][*r.Name] = stats\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor repo, stats := range repos[user] {\n\t\t\t\t\tmt := plugin.MetricType{\n\t\t\t\t\t\tData_:      stats[stat],\n\t\t\t\t\t\tNamespace_: core.NewNamespace(\"raintank\", \"apps\", \"gitstats\", \"repo\", user, repo, stat),\n\t\t\t\t\t\tTimestamp_: collectionTime,\n\t\t\t\t\t\tVersion_:   m.Version(),\n\t\t\t\t\t}\n\t\t\t\t\tmetrics = append(metrics, mt)\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tif _, ok := repos[user]; !ok {\n\t\t\t\t\trepos[user] = make(map[string]map[string]int)\n\t\t\t\t}\n\t\t\t\tif _, ok := repos[user][repo]; !ok {\n\t\t\t\t\tr, _, err := client.Repositories.Get(user, repo)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to user repos.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tstats, err := repoStats(r)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get stats from repo object.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\trepos[user][repo] = stats\n\t\t\t\t}\n\t\t\t\tmt := plugin.MetricType{\n\t\t\t\t\tData_:      repos[user][repo][stat],\n\t\t\t\t\tNamespace_: core.NewNamespace(\"raintank\", \"apps\", \"gitstats\", \"repo\", user, repo, stat),\n\t\t\t\t\tTimestamp_: collectionTime,\n\t\t\t\t\tVersion_:   m.Version(),\n\t\t\t\t}\n\t\t\t\tmetrics = append(metrics, mt)\n\t\t\t}\n\n\t\tcase \"user\":\n\t\t\tuser := ns[4]\n\t\t\tstat := ns[5]\n\t\t\tif user == \"*\" {\n\t\t\t\t\/\/need to get user\n\t\t\t\tif authUser == \"\" {\n\t\t\t\t\tgitUser, _, err := client.Users.Get(user)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get authenticated user.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tauthUser = *gitUser.Login\n\t\t\t\t\tstats, err := userStats(gitUser, client)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get stats from user object\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tusers[*gitUser.Login] = stats\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif _, ok := users[user]; !ok {\n\t\t\t\t\tu, _, err := client.Users.Get(user)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to lookup user.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tstats, err := userStats(u, client)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get stats from user object.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tusers[user] = stats\n\t\t\t\t}\n\t\t\t}\n\t\t\tmt := plugin.MetricType{\n\t\t\t\tData_:      users[user][stat],\n\t\t\t\tNamespace_: core.NewNamespace(\"raintank\", \"apps\", \"gitstats\", \"user\", user, stat),\n\t\t\t\tTimestamp_: collectionTime,\n\t\t\t\tVersion_:   m.Version(),\n\t\t\t}\n\t\t\tmetrics = append(metrics, mt)\n\t\t}\n\t}\n\n\treturn metrics, nil\n}\n\nfunc userStats(user *github.User, client *github.Client) (map[string]int, error) {\n\tstats := make(map[string]int)\n\tif user.PublicRepos != nil {\n\t\tstats[\"public_repos\"] = *user.PublicRepos\n\t}\n\tif user.PublicGists != nil {\n\t\tstats[\"public_gists\"] = *user.PublicGists\n\t}\n\tif user.Followers != nil {\n\t\tstats[\"followers\"] = *user.Followers\n\t}\n\tif user.Following != nil {\n\t\tstats[\"following\"] = *user.Following\n\t}\n\n\tif *user.Type == \"Organization\" {\n\t\torg, _, err := client.Organizations.Get(*user.Login)\n\t\tif err != nil {\n\t\t\tLogError(\"failed to lookup org data.\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tif org.PrivateGists != nil {\n\t\t\tstats[\"private_gists\"] = *org.PrivateGists\n\t\t}\n\t\tif org.TotalPrivateRepos != nil {\n\t\t\tstats[\"private_repos\"] = *org.TotalPrivateRepos\n\t\t}\n\t\tif org.DiskUsage != nil {\n\t\t\tstats[\"disk_usage\"] = *org.DiskUsage\n\t\t}\n\t}\n\n\treturn stats, nil\n}\n\nfunc repoStats(resp *github.Repository) (map[string]int, error) {\n\tstats := make(map[string]int)\n\n\tif resp.ForksCount != nil {\n\t\tstats[\"forks\"] = *resp.ForksCount\n\t}\n\tif resp.OpenIssuesCount != nil {\n\t\tstats[\"issues\"] = *resp.OpenIssuesCount\n\t}\n\tif resp.NetworkCount != nil {\n\t\tstats[\"network\"] = *resp.NetworkCount\n\t}\n\tif resp.StargazersCount != nil {\n\t\tstats[\"stars\"] = *resp.StargazersCount\n\t}\n\tif resp.SubscribersCount != nil {\n\t\tstats[\"subcribers\"] = *resp.SubscribersCount\n\t}\n\tif resp.WatchersCount != nil {\n\t\tstats[\"watchers\"] = *resp.WatchersCount\n\t}\n\tif resp.Size != nil {\n\t\tstats[\"size\"] = *resp.Size\n\t}\n\treturn stats, nil\n}\n\n\/\/GetMetricTypes returns metric types for testing\nfunc (f *Gitstats) GetMetricTypes(cfg plugin.ConfigType) ([]plugin.MetricType, error) {\n\tmts := make([]plugin.MetricType, 0)\n\tfor _, metricName := range repoMetricNames {\n\t\tmts = append(mts, plugin.MetricType{\n\t\t\tNamespace_: core.NewNamespace(\"raintank\", \"apps\", \"gitstats\", \"repo\").\n\t\t\t\tAddDynamicElement(\"owner\", \"repository owner\").\n\t\t\t\tAddDynamicElement(\"repo\", \"repository name\").\n\t\t\t\tAddStaticElement(metricName),\n\t\t\tConfig_: cfg.ConfigDataNode,\n\t\t})\n\t}\n\tfor _, metricName := range userMetricNames {\n\t\tmts = append(mts, plugin.MetricType{\n\t\t\tNamespace_: core.NewNamespace(\"raintank\", \"apps\", \"gitstats\", \"user\").\n\t\t\t\tAddDynamicElement(\"user\", \"user or orginisation name\").\n\t\t\t\tAddStaticElement(metricName),\n\t\t\tConfig_: cfg.ConfigDataNode,\n\t\t})\n\t}\n\treturn mts, nil\n}\n\n\/\/GetConfigPolicy returns a ConfigPolicyTree for testing\nfunc (f *Gitstats) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) {\n\tc := cpolicy.New()\n\trule, _ := cpolicy.NewStringRule(\"access_token\", true)\n\tp := cpolicy.NewPolicyNode()\n\tp.Add(rule)\n\tc.Add([]string{\"raintank\", \"apps\", \"gitstats\"}, p)\n\treturn c, nil\n}\n\n\/\/Meta returns meta data for testing\nfunc Meta() *plugin.PluginMeta {\n\treturn plugin.NewPluginMeta(\n\t\tName,\n\t\tVersion,\n\t\tType,\n\t\t[]string{plugin.SnapGOBContentType},\n\t\t[]string{plugin.SnapGOBContentType},\n\t\tplugin.Unsecure(true),\n\t\tplugin.ConcurrencyCount(1000),\n\t)\n}\n<commit_msg>update to work with latest go-github lib<commit_after>package gitstats\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t. \"github.com\/intelsdi-x\/snap-plugin-utilities\/logger\"\n\t\"github.com\/intelsdi-x\/snap\/control\/plugin\"\n\t\"github.com\/intelsdi-x\/snap\/control\/plugin\/cpolicy\"\n\t\"github.com\/intelsdi-x\/snap\/core\"\n\t\"github.com\/intelsdi-x\/snap\/core\/ctypes\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nconst (\n\t\/\/ Name of plugin\n\tName = \"rt-gitstats\"\n\t\/\/ Version of plugin\n\tVersion = 1\n\t\/\/ Type of plugin\n\tType = plugin.CollectorPluginType\n)\n\n\/\/ make sure that we actually satisify requierd interface\nvar _ plugin.CollectorPlugin = (*Gitstats)(nil)\n\nvar (\n\trepoMetricNames = []string{\n\t\t\"forks\",\n\t\t\"issues\",\n\t\t\"network\",\n\t\t\"stars\",\n\t\t\"subscribers\",\n\t\t\"watches\",\n\t\t\"size\",\n\t}\n\tuserMetricNames = []string{\n\t\t\"public_repos\",\n\t\t\"public_gists\",\n\t\t\"followers\",\n\t\t\"following\",\n\t\t\"private_repos\",\n\t\t\"private_gists\",\n\t\t\"plan_private_repos\",\n\t\t\"plan_seats\",\n\t\t\"plan_filled_seats\",\n\t}\n)\n\ntype Gitstats struct {\n}\n\n\/\/ CollectMetrics collects metrics for testing\nfunc (f *Gitstats) CollectMetrics(mts []plugin.MetricType) ([]plugin.MetricType, error) {\n\tvar err error\n\n\tconf := mts[0].Config().Table()\n\taccessToken, ok := conf[\"access_token\"]\n\tif !ok || accessToken.(ctypes.ConfigValueStr).Value == \"\" {\n\t\treturn nil, fmt.Errorf(\"access token missing from config, %v\", conf)\n\t}\n\n\tmetrics, err := gitStats(accessToken.(ctypes.ConfigValueStr).Value, mts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn metrics, nil\n}\n\ntype repoName struct {\n\tRepo  string\n\tOwner string\n}\n\nfunc gitStats(accessToken string, mts []plugin.MetricType) ([]plugin.MetricType, error) {\n\tts := oauth2.StaticTokenSource(\n\t\t&oauth2.Token{AccessToken: accessToken},\n\t)\n\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\tclient := github.NewClient(tc)\n\tcollectionTime := time.Now()\n\trepos := make(map[string]map[string]map[string]int)\n\tusers := make(map[string]map[string]int)\n\n\tuserRepos := make(map[string]struct{})\n\n\tauthUser := \"\"\n\tmetrics := make([]plugin.MetricType, 0)\n\n\tfor _, m := range mts {\n\t\tns := m.Namespace().Strings()\n\t\tswitch ns[3] {\n\t\tcase \"repo\":\n\t\t\tuser := ns[4]\n\t\t\trepo := ns[5]\n\t\t\tstat := ns[6]\n\n\t\t\tif user == \"*\" {\n\t\t\t\t\/\/need to get user\n\t\t\t\tif authUser == \"\" {\n\t\t\t\t\tgitUser, _, err := client.Users.Get(\"\")\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get authenticated user.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tstats, err := userStats(gitUser, client)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get stats from user object.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tusers[*gitUser.Login] = stats\n\t\t\t\t\tauthUser = *gitUser.Login\n\t\t\t\t}\n\t\t\t\tuser = authUser\n\t\t\t}\n\t\t\tif repo == \"*\" {\n\t\t\t\t\/\/ we only need to list a users repos once.\n\t\t\t\tif _, ok := userRepos[user]; !ok {\n\t\t\t\t\trepoList, _, err := client.Repositories.List(user, nil)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get repos owned by user.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tuserRepos[user] = struct{}{}\n\t\t\t\t\tif _, ok := repos[user]; !ok {\n\t\t\t\t\t\trepos[user] = make(map[string]map[string]int)\n\t\t\t\t\t}\n\t\t\t\t\tfor _, r := range repoList {\n\t\t\t\t\t\tstats, err := repoStats(r)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tLogError(\"failed to get stats from repo object.\", err)\n\t\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t\t}\n\t\t\t\t\t\trepos[user][*r.Name] = stats\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor repo, stats := range repos[user] {\n\t\t\t\t\tmt := plugin.MetricType{\n\t\t\t\t\t\tData_:      stats[stat],\n\t\t\t\t\t\tNamespace_: core.NewNamespace(\"raintank\", \"apps\", \"gitstats\", \"repo\", user, repo, stat),\n\t\t\t\t\t\tTimestamp_: collectionTime,\n\t\t\t\t\t\tVersion_:   m.Version(),\n\t\t\t\t\t}\n\t\t\t\t\tmetrics = append(metrics, mt)\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tif _, ok := repos[user]; !ok {\n\t\t\t\t\trepos[user] = make(map[string]map[string]int)\n\t\t\t\t}\n\t\t\t\tif _, ok := repos[user][repo]; !ok {\n\t\t\t\t\tr, _, err := client.Repositories.Get(user, repo)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to user repos.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tstats, err := repoStats(r)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get stats from repo object.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\trepos[user][repo] = stats\n\t\t\t\t}\n\t\t\t\tmt := plugin.MetricType{\n\t\t\t\t\tData_:      repos[user][repo][stat],\n\t\t\t\t\tNamespace_: core.NewNamespace(\"raintank\", \"apps\", \"gitstats\", \"repo\", user, repo, stat),\n\t\t\t\t\tTimestamp_: collectionTime,\n\t\t\t\t\tVersion_:   m.Version(),\n\t\t\t\t}\n\t\t\t\tmetrics = append(metrics, mt)\n\t\t\t}\n\n\t\tcase \"user\":\n\t\t\tuser := ns[4]\n\t\t\tstat := ns[5]\n\t\t\tif user == \"*\" {\n\t\t\t\t\/\/need to get user\n\t\t\t\tif authUser == \"\" {\n\t\t\t\t\tgitUser, _, err := client.Users.Get(user)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get authenticated user.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tauthUser = *gitUser.Login\n\t\t\t\t\tstats, err := userStats(gitUser, client)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get stats from user object\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tusers[*gitUser.Login] = stats\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif _, ok := users[user]; !ok {\n\t\t\t\t\tu, _, err := client.Users.Get(user)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to lookup user.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tstats, err := userStats(u, client)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tLogError(\"failed to get stats from user object.\", err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tusers[user] = stats\n\t\t\t\t}\n\t\t\t}\n\t\t\tmt := plugin.MetricType{\n\t\t\t\tData_:      users[user][stat],\n\t\t\t\tNamespace_: core.NewNamespace(\"raintank\", \"apps\", \"gitstats\", \"user\", user, stat),\n\t\t\t\tTimestamp_: collectionTime,\n\t\t\t\tVersion_:   m.Version(),\n\t\t\t}\n\t\t\tmetrics = append(metrics, mt)\n\t\t}\n\t}\n\n\treturn metrics, nil\n}\n\nfunc userStats(user *github.User, client *github.Client) (map[string]int, error) {\n\tstats := make(map[string]int)\n\tif user.PublicRepos != nil {\n\t\tstats[\"public_repos\"] = *user.PublicRepos\n\t}\n\tif user.PublicGists != nil {\n\t\tstats[\"public_gists\"] = *user.PublicGists\n\t}\n\tif user.Followers != nil {\n\t\tstats[\"followers\"] = *user.Followers\n\t}\n\tif user.Following != nil {\n\t\tstats[\"following\"] = *user.Following\n\t}\n\n\tif *user.Type == \"Organization\" {\n\t\torg, _, err := client.Organizations.Get(*user.Login)\n\t\tif err != nil {\n\t\t\tLogError(\"failed to lookup org data.\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\tif org.PrivateGists != nil {\n\t\t\tstats[\"private_gists\"] = *org.PrivateGists\n\t\t}\n\t\tif org.TotalPrivateRepos != nil {\n\t\t\tstats[\"private_repos\"] = *org.TotalPrivateRepos\n\t\t}\n\t\tif org.DiskUsage != nil {\n\t\t\tstats[\"disk_usage\"] = *org.DiskUsage\n\t\t}\n\t}\n\n\treturn stats, nil\n}\n\nfunc repoStats(resp *github.Repository) (map[string]int, error) {\n\tstats := make(map[string]int)\n\n\tif resp.ForksCount != nil {\n\t\tstats[\"forks\"] = *resp.ForksCount\n\t}\n\tif resp.OpenIssuesCount != nil {\n\t\tstats[\"issues\"] = *resp.OpenIssuesCount\n\t}\n\tif resp.NetworkCount != nil {\n\t\tstats[\"network\"] = *resp.NetworkCount\n\t}\n\tif resp.StargazersCount != nil {\n\t\tstats[\"stars\"] = *resp.StargazersCount\n\t}\n\tif resp.SubscribersCount != nil {\n\t\tstats[\"subcribers\"] = *resp.SubscribersCount\n\t}\n\tif resp.WatchersCount != nil {\n\t\tstats[\"watchers\"] = *resp.WatchersCount\n\t}\n\tif resp.Size != nil {\n\t\tstats[\"size\"] = *resp.Size\n\t}\n\treturn stats, nil\n}\n\n\/\/GetMetricTypes returns metric types for testing\nfunc (f *Gitstats) GetMetricTypes(cfg plugin.ConfigType) ([]plugin.MetricType, error) {\n\tmts := make([]plugin.MetricType, 0)\n\tfor _, metricName := range repoMetricNames {\n\t\tmts = append(mts, plugin.MetricType{\n\t\t\tNamespace_: core.NewNamespace(\"raintank\", \"apps\", \"gitstats\", \"repo\").\n\t\t\t\tAddDynamicElement(\"owner\", \"repository owner\").\n\t\t\t\tAddDynamicElement(\"repo\", \"repository name\").\n\t\t\t\tAddStaticElement(metricName),\n\t\t\tConfig_: cfg.ConfigDataNode,\n\t\t})\n\t}\n\tfor _, metricName := range userMetricNames {\n\t\tmts = append(mts, plugin.MetricType{\n\t\t\tNamespace_: core.NewNamespace(\"raintank\", \"apps\", \"gitstats\", \"user\").\n\t\t\t\tAddDynamicElement(\"user\", \"user or orginisation name\").\n\t\t\t\tAddStaticElement(metricName),\n\t\t\tConfig_: cfg.ConfigDataNode,\n\t\t})\n\t}\n\treturn mts, nil\n}\n\n\/\/GetConfigPolicy returns a ConfigPolicyTree for testing\nfunc (f *Gitstats) GetConfigPolicy() (*cpolicy.ConfigPolicy, error) {\n\tc := cpolicy.New()\n\trule, _ := cpolicy.NewStringRule(\"access_token\", true)\n\tp := cpolicy.NewPolicyNode()\n\tp.Add(rule)\n\tc.Add([]string{\"raintank\", \"apps\", \"gitstats\"}, p)\n\treturn c, nil\n}\n\n\/\/Meta returns meta data for testing\nfunc Meta() *plugin.PluginMeta {\n\treturn plugin.NewPluginMeta(\n\t\tName,\n\t\tVersion,\n\t\tType,\n\t\t[]string{plugin.SnapGOBContentType},\n\t\t[]string{plugin.SnapGOBContentType},\n\t\tplugin.Unsecure(true),\n\t\tplugin.ConcurrencyCount(1000),\n\t)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n  \"bufio\"\n  \"io\"\n  \"fmt\"\n  \"log\"\n  \"os\"\n  \"path\"\n)\n\nfunc main() {\n  if len(os.Args) != 3 {\n    log.Fatalf(\"Usage: %s input-file output-file\", path.Base(os.Args[0]))\n  }\n\n  i, err := os.Open(os.Args[1])\n  if err != nil {\n    log.Fatalf(\"Cannot open %q for reading: %v\", os.Args[1], err)\n  }\n  defer i.Close()\n  r := bufio.NewReader(i)\n\n  o, err := os.Create(os.Args[2])\n  if err != nil {\n    log.Fatalf(\"Cannot create new file %q: %v\", os.Args[2], err)\n  }\n  defer o.Close()\n  w := bufio.NewWriter(o)\n  defer w.Flush()\n\n  for {\n    err = processBlock(r, w)\n    if err == io.EOF {\n      log.Println(\"Successfully reached EOF\")\n      break\n    }\n    if err != nil {\n      log.Fatalf(\"Error whilst processing file: %v\", err)\n    }\n  }\n}\n\nfunc processBlock(r *bufio.Reader, w *bufio.Writer) error {\n  var err error\n  start := true\n  for {\n    buf, err := r.Peek(1)\n    if err != nil {\n      return err\n    }\n    if start && (buf[0] != '0') {\n      return fmt.Errorf(\"Expecting '0', got %q\", buf[0])\n    }\n    if (!start) && (buf[0] == '0') {\n      break\n    }\n\n    line, err := r.ReadString('\\n')\n    if len(line) > 0 {\n      if _, werr := w.WriteString(line); err != nil {\n        return werr\n      }\n    }\n    \n    start = false\n\n    if err == io.EOF {\n      break\n    }\n    if err != nil {\n      return err\n    }\n  }\n  return err\n}\n<commit_msg>Tidy up error detection.<commit_after>package main\n\nimport (\n  \"bufio\"\n  \"io\"\n  \"fmt\"\n  \"log\"\n  \"os\"\n  \"path\"\n)\n\nfunc main() {\n  if len(os.Args) != 3 {\n    log.Fatalf(\"Usage: %s input-file output-file\", path.Base(os.Args[0]))\n  }\n\n  i, err := os.Open(os.Args[1])\n  if err != nil {\n    log.Fatalf(\"Cannot open %q for reading: %v\", os.Args[1], err)\n  }\n  defer i.Close()\n  r := bufio.NewReader(i)\n\n  o, err := os.Create(os.Args[2])\n  if err != nil {\n    log.Fatalf(\"Cannot create new file %q: %v\", os.Args[2], err)\n  }\n  defer o.Close()\n  w := bufio.NewWriter(o)\n  defer w.Flush()\n\n  for {\n    err = processBlock(r, w)\n    if err == io.EOF {\n      log.Println(\"Successfully reached EOF\")\n      break\n    }\n    if err != nil {\n      log.Fatalf(\"Error whilst processing file: %v\", err)\n    }\n  }\n}\n\nfunc processBlock(r *bufio.Reader, w *bufio.Writer) error {\n  var err error\n  start := true\n  for {\n    buf, err := r.Peek(1)\n    if err != nil {\n      return err\n    }\n    if start && (buf[0] != '0') {\n      return fmt.Errorf(\"expecting %q, got %q\", '0', buf[0])\n    }\n    if (!start) && (buf[0] == '0') {\n      break\n    }\n\n    line, err := r.ReadString('\\n')\n    if len(line) > 0 {\n      if _, werr := w.WriteString(line); err != nil {\n        return werr\n      }\n    }\n\n    start = false\n\n    if err == io.EOF {\n      break\n    }\n    if err != nil {\n      return err\n    }\n  }\n  return err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014, Google Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage etcdtopo\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com\/coreos\/go-etcd\/etcd\"\n\tctlproto \"github.com\/youtube\/vitess\/go\/cmd\/vtctld\/proto\"\n\t\"github.com\/youtube\/vitess\/go\/vt\/topo\"\n)\n\nconst (\n\texplorerRoot = \"\/etcd\"\n\tglobalCell   = \"global\"\n)\n\n\/\/ Explorer is an implementation of vtctld's Explorer interface for etcd.\ntype Explorer struct {\n\tts *Server\n}\n\n\/\/ NewExplorer implements vtctld Explorer.\nfunc NewExplorer(ts *Server) *Explorer {\n\treturn &Explorer{ts: ts}\n}\n\n\/\/ GetKeyspacePath implements vtctld Explorer.\nfunc (ex Explorer) GetKeyspacePath(keyspace string) string {\n\treturn path.Join(explorerRoot, globalCell, keyspaceDirPath(keyspace))\n}\n\n\/\/ GetShardPath implements vtctld Explorer.\nfunc (ex Explorer) GetShardPath(keyspace, shard string) string {\n\treturn path.Join(explorerRoot, globalCell, shardDirPath(keyspace, shard))\n}\n\n\/\/ GetSrvKeyspacePath implements vtctld Explorer.\nfunc (ex Explorer) GetSrvKeyspacePath(cell, keyspace string) string {\n\treturn path.Join(explorerRoot, cell, srvKeyspaceDirPath(keyspace))\n}\n\n\/\/ GetSrvShardPath implements vtctld Explorer.\nfunc (ex Explorer) GetSrvShardPath(cell, keyspace, shard string) string {\n\treturn path.Join(explorerRoot, cell, srvShardDirPath(keyspace, shard))\n}\n\n\/\/ GetSrvTypePath implements vtctld Explorer.\nfunc (ex Explorer) GetSrvTypePath(cell, keyspace, shard string, tabletType topo.TabletType) string {\n\treturn path.Join(explorerRoot, cell, endPointsDirPath(keyspace, shard, string(tabletType)))\n}\n\n\/\/ GetTabletPath implements vtctld Explorer.\nfunc (ex Explorer) GetTabletPath(alias topo.TabletAlias) string {\n\treturn path.Join(explorerRoot, alias.Cell, tabletDirPath(alias.TabletUidStr()))\n}\n\n\/\/ GetReplicationSlaves implements vtctld Explorer.\nfunc (ex Explorer) GetReplicationSlaves(cell, keyspace, shard string) string {\n\treturn path.Join(explorerRoot, cell, shardReplicationDirPath(keyspace, shard))\n}\n\n\/\/ HandlePath implements vtctld Explorer.\nfunc (ex Explorer) HandlePath(actionRepo ctlproto.ActionRepository, rPath string, r *http.Request) interface{} {\n\tresult := newExplorerResult(rPath)\n\n\t\/\/ Cut off explorerRoot prefix.\n\tif !strings.HasPrefix(rPath, explorerRoot) {\n\t\tresult.Error = \"invalid etcd explorer path: \" + rPath\n\t\treturn result\n\t}\n\trPath = rPath[len(explorerRoot):]\n\n\t\/\/ Root is a list of cells.\n\tif rPath == \"\" {\n\t\tcells, err := ex.ts.getCellList()\n\t\tif err != nil {\n\t\t\tresult.Error = err.Error()\n\t\t\treturn result\n\t\t}\n\t\tresult.Children = append([]string{globalCell}, cells...)\n\t\treturn result\n\t}\n\n\t\/\/ Get a client for the requested cell.\n\tvar client Client\n\tcell, rPath, err := splitCellPath(rPath)\n\tif err != nil {\n\t\tresult.Error = err.Error()\n\t\treturn result\n\t}\n\tif cell == globalCell {\n\t\tclient = ex.ts.getGlobal()\n\t} else {\n\t\tclient, err = ex.ts.getCell(cell)\n\t\tif err != nil {\n\t\t\tresult.Error = \"Can't get cell: \" + err.Error()\n\t\t\treturn result\n\t\t}\n\t}\n\n\t\/\/ Get the requested node data.\n\tresp, err := client.Get(rPath, true \/* sort *\/, false \/* recursive *\/)\n\tif err != nil {\n\t\tresult.Error = err.Error()\n\t\treturn result\n\t}\n\tif resp.Node == nil {\n\t\tresult.Error = ErrBadResponse.Error()\n\t\treturn result\n\t}\n\tresult.Data = getNodeData(client, resp.Node)\n\n\t\/\/ Populate children.\n\tfor _, node := range resp.Node.Nodes {\n\t\tresult.Children = append(result.Children, path.Base(node.Key))\n\t}\n\n\t\/\/ Populate actions.\n\tif m, _ := path.Match(keyspaceDirPath(\"*\"), rPath); m {\n\t\tactionRepo.PopulateKeyspaceActions(result.Actions, path.Base(rPath))\n\t} else if m, _ := path.Match(shardDirPath(\"*\", \"*\"), rPath); m {\n\t\tif keyspace, shard, err := splitShardDirPath(rPath); err == nil {\n\t\t\tactionRepo.PopulateShardActions(result.Actions, keyspace, shard)\n\t\t}\n\t} else if m, _ := path.Match(tabletDirPath(\"*\"), rPath); m {\n\t\tactionRepo.PopulateTabletActions(result.Actions, path.Base(rPath), r)\n\t\taddTabletLinks(result, result.Data)\n\t}\n\treturn result\n}\n\ntype explorerResult struct {\n\tPath     string\n\tData     string\n\tLinks    map[string]template.URL\n\tChildren []string\n\tActions  map[string]template.URL\n\tError    string\n}\n\nfunc newExplorerResult(p string) *explorerResult {\n\treturn &explorerResult{\n\t\tLinks:   make(map[string]template.URL),\n\t\tActions: make(map[string]template.URL),\n\t\tPath:    p,\n\t}\n}\n\nfunc getNodeData(client Client, node *etcd.Node) string {\n\tif !node.Dir {\n\t\treturn node.Value\n\t}\n\t\/\/ Directories don't have data, but some directories have a special data file.\n\tresp, err := client.Get(path.Join(node.Key, dataFilename), false \/* sort *\/, false \/* recursive *\/)\n\tif err != nil || resp.Node == nil {\n\t\treturn \"\"\n\t}\n\treturn resp.Node.Value\n}\n\n\/\/ splitCellPath returns the cell name, and the rest of the path.\n\/\/ For example: \"\/cell\/rest\/of\/path\" -> \"cell\", \"\/rest\/of\/path\"\nfunc splitCellPath(p string) (cell, rest string, err error) {\n\tparts := strings.SplitN(p, \"\/\", 3)\n\tif len(parts) < 2 || parts[0] != \"\" {\n\t\treturn \"\", \"\", fmt.Errorf(\"invalid etcd explorer path: %v\", p)\n\t}\n\tif len(parts) < 3 {\n\t\treturn parts[1], \"\/\", nil\n\t}\n\treturn parts[1], \"\/\" + parts[2], nil\n}\n\n\/\/ splitShardDirPath takes a path that matches the path.Match() pattern\n\/\/ shardDirPath(\"*\", \"*\") and returns the keyspace and shard.\n\/\/\n\/\/ We assume the path is of the form \"\/vt\/keyspaces\/*\/*\".\n\/\/ If that ever changes, the unit test for this function will detect it.\nfunc splitShardDirPath(p string) (keyspace, shard string, err error) {\n\tparts := strings.Split(p, \"\/\")\n\tif len(parts) != 5 {\n\t\treturn \"\", \"\", fmt.Errorf(\"invalid shard dir path: %v\", p)\n\t}\n\treturn parts[3], parts[4], nil\n}\n\nfunc addTabletLinks(result *explorerResult, data string) {\n\tt := &topo.Tablet{}\n\terr := json.Unmarshal([]byte(data), t)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif port, ok := t.Portmap[\"vt\"]; ok {\n\t\tresult.Links[\"status\"] = template.URL(fmt.Sprintf(\"http:\/\/%v:%v\/debug\/status\", t.Hostname, port))\n\t}\n\n\tif !t.Parent.IsZero() {\n\t\tresult.Links[\"parent\"] = template.URL(\n\t\t\tpath.Join(explorerRoot, t.Parent.Cell, tabletDirPath(t.Parent.String())))\n\t}\n}\n<commit_msg>Use full tablet alias for etcd explorer, not just uid.<commit_after>\/\/ Copyright 2014, Google Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage etcdtopo\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com\/coreos\/go-etcd\/etcd\"\n\tctlproto \"github.com\/youtube\/vitess\/go\/cmd\/vtctld\/proto\"\n\t\"github.com\/youtube\/vitess\/go\/vt\/topo\"\n)\n\nconst (\n\texplorerRoot = \"\/etcd\"\n\tglobalCell   = \"global\"\n)\n\n\/\/ Explorer is an implementation of vtctld's Explorer interface for etcd.\ntype Explorer struct {\n\tts *Server\n}\n\n\/\/ NewExplorer implements vtctld Explorer.\nfunc NewExplorer(ts *Server) *Explorer {\n\treturn &Explorer{ts: ts}\n}\n\n\/\/ GetKeyspacePath implements vtctld Explorer.\nfunc (ex Explorer) GetKeyspacePath(keyspace string) string {\n\treturn path.Join(explorerRoot, globalCell, keyspaceDirPath(keyspace))\n}\n\n\/\/ GetShardPath implements vtctld Explorer.\nfunc (ex Explorer) GetShardPath(keyspace, shard string) string {\n\treturn path.Join(explorerRoot, globalCell, shardDirPath(keyspace, shard))\n}\n\n\/\/ GetSrvKeyspacePath implements vtctld Explorer.\nfunc (ex Explorer) GetSrvKeyspacePath(cell, keyspace string) string {\n\treturn path.Join(explorerRoot, cell, srvKeyspaceDirPath(keyspace))\n}\n\n\/\/ GetSrvShardPath implements vtctld Explorer.\nfunc (ex Explorer) GetSrvShardPath(cell, keyspace, shard string) string {\n\treturn path.Join(explorerRoot, cell, srvShardDirPath(keyspace, shard))\n}\n\n\/\/ GetSrvTypePath implements vtctld Explorer.\nfunc (ex Explorer) GetSrvTypePath(cell, keyspace, shard string, tabletType topo.TabletType) string {\n\treturn path.Join(explorerRoot, cell, endPointsDirPath(keyspace, shard, string(tabletType)))\n}\n\n\/\/ GetTabletPath implements vtctld Explorer.\nfunc (ex Explorer) GetTabletPath(alias topo.TabletAlias) string {\n\treturn path.Join(explorerRoot, alias.Cell, tabletDirPath(alias.String()))\n}\n\n\/\/ GetReplicationSlaves implements vtctld Explorer.\nfunc (ex Explorer) GetReplicationSlaves(cell, keyspace, shard string) string {\n\treturn path.Join(explorerRoot, cell, shardReplicationDirPath(keyspace, shard))\n}\n\n\/\/ HandlePath implements vtctld Explorer.\nfunc (ex Explorer) HandlePath(actionRepo ctlproto.ActionRepository, rPath string, r *http.Request) interface{} {\n\tresult := newExplorerResult(rPath)\n\n\t\/\/ Cut off explorerRoot prefix.\n\tif !strings.HasPrefix(rPath, explorerRoot) {\n\t\tresult.Error = \"invalid etcd explorer path: \" + rPath\n\t\treturn result\n\t}\n\trPath = rPath[len(explorerRoot):]\n\n\t\/\/ Root is a list of cells.\n\tif rPath == \"\" {\n\t\tcells, err := ex.ts.getCellList()\n\t\tif err != nil {\n\t\t\tresult.Error = err.Error()\n\t\t\treturn result\n\t\t}\n\t\tresult.Children = append([]string{globalCell}, cells...)\n\t\treturn result\n\t}\n\n\t\/\/ Get a client for the requested cell.\n\tvar client Client\n\tcell, rPath, err := splitCellPath(rPath)\n\tif err != nil {\n\t\tresult.Error = err.Error()\n\t\treturn result\n\t}\n\tif cell == globalCell {\n\t\tclient = ex.ts.getGlobal()\n\t} else {\n\t\tclient, err = ex.ts.getCell(cell)\n\t\tif err != nil {\n\t\t\tresult.Error = \"Can't get cell: \" + err.Error()\n\t\t\treturn result\n\t\t}\n\t}\n\n\t\/\/ Get the requested node data.\n\tresp, err := client.Get(rPath, true \/* sort *\/, false \/* recursive *\/)\n\tif err != nil {\n\t\tresult.Error = err.Error()\n\t\treturn result\n\t}\n\tif resp.Node == nil {\n\t\tresult.Error = ErrBadResponse.Error()\n\t\treturn result\n\t}\n\tresult.Data = getNodeData(client, resp.Node)\n\n\t\/\/ Populate children.\n\tfor _, node := range resp.Node.Nodes {\n\t\tresult.Children = append(result.Children, path.Base(node.Key))\n\t}\n\n\t\/\/ Populate actions.\n\tif m, _ := path.Match(keyspaceDirPath(\"*\"), rPath); m {\n\t\tactionRepo.PopulateKeyspaceActions(result.Actions, path.Base(rPath))\n\t} else if m, _ := path.Match(shardDirPath(\"*\", \"*\"), rPath); m {\n\t\tif keyspace, shard, err := splitShardDirPath(rPath); err == nil {\n\t\t\tactionRepo.PopulateShardActions(result.Actions, keyspace, shard)\n\t\t}\n\t} else if m, _ := path.Match(tabletDirPath(\"*\"), rPath); m {\n\t\tactionRepo.PopulateTabletActions(result.Actions, path.Base(rPath), r)\n\t\taddTabletLinks(result, result.Data)\n\t}\n\treturn result\n}\n\ntype explorerResult struct {\n\tPath     string\n\tData     string\n\tLinks    map[string]template.URL\n\tChildren []string\n\tActions  map[string]template.URL\n\tError    string\n}\n\nfunc newExplorerResult(p string) *explorerResult {\n\treturn &explorerResult{\n\t\tLinks:   make(map[string]template.URL),\n\t\tActions: make(map[string]template.URL),\n\t\tPath:    p,\n\t}\n}\n\nfunc getNodeData(client Client, node *etcd.Node) string {\n\tif !node.Dir {\n\t\treturn node.Value\n\t}\n\t\/\/ Directories don't have data, but some directories have a special data file.\n\tresp, err := client.Get(path.Join(node.Key, dataFilename), false \/* sort *\/, false \/* recursive *\/)\n\tif err != nil || resp.Node == nil {\n\t\treturn \"\"\n\t}\n\treturn resp.Node.Value\n}\n\n\/\/ splitCellPath returns the cell name, and the rest of the path.\n\/\/ For example: \"\/cell\/rest\/of\/path\" -> \"cell\", \"\/rest\/of\/path\"\nfunc splitCellPath(p string) (cell, rest string, err error) {\n\tparts := strings.SplitN(p, \"\/\", 3)\n\tif len(parts) < 2 || parts[0] != \"\" {\n\t\treturn \"\", \"\", fmt.Errorf(\"invalid etcd explorer path: %v\", p)\n\t}\n\tif len(parts) < 3 {\n\t\treturn parts[1], \"\/\", nil\n\t}\n\treturn parts[1], \"\/\" + parts[2], nil\n}\n\n\/\/ splitShardDirPath takes a path that matches the path.Match() pattern\n\/\/ shardDirPath(\"*\", \"*\") and returns the keyspace and shard.\n\/\/\n\/\/ We assume the path is of the form \"\/vt\/keyspaces\/*\/*\".\n\/\/ If that ever changes, the unit test for this function will detect it.\nfunc splitShardDirPath(p string) (keyspace, shard string, err error) {\n\tparts := strings.Split(p, \"\/\")\n\tif len(parts) != 5 {\n\t\treturn \"\", \"\", fmt.Errorf(\"invalid shard dir path: %v\", p)\n\t}\n\treturn parts[3], parts[4], nil\n}\n\nfunc addTabletLinks(result *explorerResult, data string) {\n\tt := &topo.Tablet{}\n\terr := json.Unmarshal([]byte(data), t)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif port, ok := t.Portmap[\"vt\"]; ok {\n\t\tresult.Links[\"status\"] = template.URL(fmt.Sprintf(\"http:\/\/%v:%v\/debug\/status\", t.Hostname, port))\n\t}\n\n\tif !t.Parent.IsZero() {\n\t\tresult.Links[\"parent\"] = template.URL(\n\t\t\tpath.Join(explorerRoot, t.Parent.Cell, tabletDirPath(t.Parent.String())))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package test contains utilities to test topo.Server\n\/\/ implementations. If you are testing your implementation, you will\n\/\/ want to call CheckAll in your test method. For an example, look at\n\/\/ the tests in github.com\/youtube\/vitess\/go\/vt\/zktopo.\npackage test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/youtube\/vitess\/go\/vt\/key\"\n\t\"github.com\/youtube\/vitess\/go\/vt\/topo\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ CheckServingGraph makes sure the serving graph functions work properly.\nfunc CheckServingGraph(ctx context.Context, t *testing.T, ts topo.Server) {\n\tcell := getLocalCell(t, ts)\n\n\t\/\/ test individual cell\/keyspace\/shard\/type entries\n\tif _, err := ts.GetSrvTabletTypesPerShard(cell, \"test_keyspace\", \"-10\"); err != topo.ErrNoNode {\n\t\tt.Errorf(\"GetSrvTabletTypesPerShard(invalid): %v\", err)\n\t}\n\tif _, err := ts.GetEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER); err != topo.ErrNoNode {\n\t\tt.Errorf(\"GetEndPoints(invalid): %v\", err)\n\t}\n\n\tendPoints := topo.EndPoints{\n\t\tEntries: []topo.EndPoint{\n\t\t\ttopo.EndPoint{\n\t\t\t\tUid:          1,\n\t\t\t\tHost:         \"host1\",\n\t\t\t\tNamedPortMap: map[string]int{\"vt\": 1234, \"mysql\": 1235, \"vts\": 1236},\n\t\t\t},\n\t\t},\n\t}\n\n\tif err := topo.UpdateEndPoints(ctx, ts, cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER, &endPoints); err != nil {\n\t\tt.Fatalf(\"UpdateEndPoints(master): %v\", err)\n\t}\n\tif types, err := ts.GetSrvTabletTypesPerShard(cell, \"test_keyspace\", \"-10\"); err != nil || len(types) != 1 || types[0] != topo.TYPE_MASTER {\n\t\tt.Errorf(\"GetSrvTabletTypesPerShard(1): %v %v\", err, types)\n\t}\n\n\t\/\/ Delete the SrvShard (need to delete endpoints first).\n\tif err := ts.DeleteEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER); err != nil {\n\t\tt.Errorf(\"DeleteEndPoints: %v\", err)\n\t}\n\tif err := ts.DeleteSrvShard(cell, \"test_keyspace\", \"-10\"); err != nil {\n\t\tt.Errorf(\"DeleteSrvShard: %v\", err)\n\t}\n\tif _, err := ts.GetSrvShard(cell, \"test_keyspace\", \"-10\"); err != topo.ErrNoNode {\n\t\tt.Errorf(\"GetSrvShard(deleted) got %v, want ErrNoNode\", err)\n\t}\n\n\t\/\/ Re-add endpoints.\n\tif err := topo.UpdateEndPoints(ctx, ts, cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER, &endPoints); err != nil {\n\t\tt.Fatalf(\"UpdateEndPoints(master): %v\", err)\n\t}\n\n\taddrs, err := ts.GetEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER)\n\tif err != nil {\n\t\tt.Errorf(\"GetEndPoints: %v\", err)\n\t}\n\tif len(addrs.Entries) != 1 || addrs.Entries[0].Uid != 1 {\n\t\tt.Errorf(\"GetEndPoints(1): %v\", addrs)\n\t}\n\tif pm := addrs.Entries[0].NamedPortMap; pm[\"vt\"] != 1234 || pm[\"mysql\"] != 1235 || pm[\"vts\"] != 1236 {\n\t\tt.Errorf(\"GetSrcTabletType(1).NamedPortmap: want %v, got %v\", endPoints.Entries[0].NamedPortMap, pm)\n\t}\n\n\tif err := ts.UpdateTabletEndpoint(cell, \"test_keyspace\", \"-10\", topo.TYPE_REPLICA, &topo.EndPoint{Uid: 2, Host: \"host2\"}); err != nil {\n\t\tt.Fatalf(\"UpdateTabletEndpoint(invalid): %v\", err)\n\t}\n\tif err := ts.UpdateTabletEndpoint(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER, &topo.EndPoint{Uid: 1, Host: \"host2\"}); err != nil {\n\t\tt.Fatalf(\"UpdateTabletEndpoint(master): %v\", err)\n\t}\n\tif addrs, err := ts.GetEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER); err != nil || len(addrs.Entries) != 1 || addrs.Entries[0].Uid != 1 {\n\t\tt.Errorf(\"GetEndPoints(2): %v %v\", err, addrs)\n\t}\n\tif err := ts.UpdateTabletEndpoint(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER, &topo.EndPoint{Uid: 3, Host: \"host3\"}); err != nil {\n\t\tt.Fatalf(\"UpdateTabletEndpoint(master): %v\", err)\n\t}\n\tif addrs, err := ts.GetEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER); err != nil || len(addrs.Entries) != 2 {\n\t\tt.Errorf(\"GetEndPoints(2): %v %v\", err, addrs)\n\t}\n\n\tif err := ts.DeleteEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_REPLICA); err != topo.ErrNoNode {\n\t\tt.Errorf(\"DeleteEndPoints(unknown): %v\", err)\n\t}\n\tif err := ts.DeleteEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER); err != nil {\n\t\tt.Errorf(\"DeleteEndPoints(master): %v\", err)\n\t}\n\n\t\/\/ test cell\/keyspace\/shard entries (SrvShard)\n\tsrvShard := topo.SrvShard{\n\t\tServedTypes: []topo.TabletType{topo.TYPE_MASTER},\n\t\tTabletTypes: []topo.TabletType{topo.TYPE_REPLICA, topo.TYPE_RDONLY},\n\t}\n\tif err := ts.UpdateSrvShard(cell, \"test_keyspace\", \"-10\", &srvShard); err != nil {\n\t\tt.Fatalf(\"UpdateSrvShard(1): %v\", err)\n\t}\n\tif _, err := ts.GetSrvShard(cell, \"test_keyspace\", \"666\"); err != topo.ErrNoNode {\n\t\tt.Errorf(\"GetSrvShard(invalid): %v\", err)\n\t}\n\tif s, err := ts.GetSrvShard(cell, \"test_keyspace\", \"-10\"); err != nil ||\n\t\tlen(s.ServedTypes) != 1 ||\n\t\ts.ServedTypes[0] != topo.TYPE_MASTER ||\n\t\tlen(s.TabletTypes) != 2 ||\n\t\ts.TabletTypes[0] != topo.TYPE_REPLICA ||\n\t\ts.TabletTypes[1] != topo.TYPE_RDONLY {\n\t\tt.Errorf(\"GetSrvShard(valid): %v\", err)\n\t}\n\n\t\/\/ test cell\/keyspace entries (SrvKeyspace)\n\tsrvKeyspace := topo.SrvKeyspace{\n\t\tPartitions: map[topo.TabletType]*topo.KeyspacePartition{\n\t\t\ttopo.TYPE_MASTER: &topo.KeyspacePartition{\n\t\t\t\tShards: []topo.SrvShard{\n\t\t\t\t\ttopo.SrvShard{\n\t\t\t\t\t\tServedTypes: []topo.TabletType{topo.TYPE_MASTER},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tTabletTypes:        []topo.TabletType{topo.TYPE_MASTER},\n\t\tShardingColumnName: \"video_id\",\n\t\tShardingColumnType: key.KIT_UINT64,\n\t\tServedFrom: map[topo.TabletType]string{\n\t\t\ttopo.TYPE_REPLICA: \"other_keyspace\",\n\t\t},\n\t}\n\tif err := ts.UpdateSrvKeyspace(cell, \"test_keyspace\", &srvKeyspace); err != nil {\n\t\tt.Errorf(\"UpdateSrvKeyspace(1): %v\", err)\n\t}\n\tif _, err := ts.GetSrvKeyspace(cell, \"test_keyspace666\"); err != topo.ErrNoNode {\n\t\tt.Errorf(\"GetSrvKeyspace(invalid): %v\", err)\n\t}\n\tif k, err := ts.GetSrvKeyspace(cell, \"test_keyspace\"); err != nil ||\n\t\tlen(k.TabletTypes) != 1 ||\n\t\tk.TabletTypes[0] != topo.TYPE_MASTER ||\n\t\tlen(k.Partitions) != 1 ||\n\t\tlen(k.Partitions[topo.TYPE_MASTER].Shards) != 1 ||\n\t\tlen(k.Partitions[topo.TYPE_MASTER].Shards[0].ServedTypes) != 1 ||\n\t\tk.Partitions[topo.TYPE_MASTER].Shards[0].ServedTypes[0] != topo.TYPE_MASTER ||\n\t\tk.ShardingColumnName != \"video_id\" ||\n\t\tk.ShardingColumnType != key.KIT_UINT64 ||\n\t\tk.ServedFrom[topo.TYPE_REPLICA] != \"other_keyspace\" {\n\t\tt.Errorf(\"GetSrvKeyspace(valid): %v %v\", err, k)\n\t}\n\tif k, err := ts.GetSrvKeyspaceNames(cell); err != nil || len(k) != 1 || k[0] != \"test_keyspace\" {\n\t\tt.Errorf(\"GetSrvKeyspaceNames(): %v\", err)\n\t}\n\n\t\/\/ check that updating a SrvKeyspace out of the blue works\n\tif err := ts.UpdateSrvKeyspace(cell, \"unknown_keyspace_so_far\", &srvKeyspace); err != nil {\n\t\tt.Fatalf(\"UpdateSrvKeyspace(2): %v\", err)\n\t}\n\tif k, err := ts.GetSrvKeyspace(cell, \"unknown_keyspace_so_far\"); err != nil ||\n\t\tlen(k.TabletTypes) != 1 ||\n\t\tk.TabletTypes[0] != topo.TYPE_MASTER ||\n\t\tlen(k.Partitions) != 1 ||\n\t\tlen(k.Partitions[topo.TYPE_MASTER].Shards) != 1 ||\n\t\tlen(k.Partitions[topo.TYPE_MASTER].Shards[0].ServedTypes) != 1 ||\n\t\tk.Partitions[topo.TYPE_MASTER].Shards[0].ServedTypes[0] != topo.TYPE_MASTER ||\n\t\tk.ShardingColumnName != \"video_id\" ||\n\t\tk.ShardingColumnType != key.KIT_UINT64 ||\n\t\tk.ServedFrom[topo.TYPE_REPLICA] != \"other_keyspace\" {\n\t\tt.Errorf(\"GetSrvKeyspace(out of the blue): %v %v\", err, *k)\n\t}\n}\n\n\/\/ CheckWatchEndPoints makes sure WatchEndPoints works as expected\nfunc CheckWatchEndPoints(ctx context.Context, t *testing.T, ts topo.Server) {\n\tcell := getLocalCell(t, ts)\n\tkeyspace := \"test_keyspace\"\n\tshard := \"-10\"\n\ttabletType := topo.TYPE_MASTER\n\n\t\/\/ start watching, should get nil first\n\tnotifications, stopWatching, err := ts.WatchEndPoints(cell, keyspace, shard, tabletType)\n\tif err != nil {\n\t\tt.Fatalf(\"WatchEndPoints failed: %v\", err)\n\t}\n\tep, ok := <-notifications\n\tif !ok || ep != nil {\n\t\tt.Fatalf(\"first value is wrong: %v %v\", ep, ok)\n\t}\n\n\t\/\/ update the endpoints, should get a notification\n\tendPoints := topo.EndPoints{\n\t\tEntries: []topo.EndPoint{\n\t\t\ttopo.EndPoint{\n\t\t\t\tUid:          1,\n\t\t\t\tHost:         \"host1\",\n\t\t\t\tNamedPortMap: map[string]int{\"vt\": 1234, \"mysql\": 1235, \"vts\": 1236},\n\t\t\t},\n\t\t},\n\t}\n\tif err := topo.UpdateEndPoints(ctx, ts, cell, keyspace, shard, tabletType, &endPoints); err != nil {\n\t\tt.Fatalf(\"UpdateEndPoints failed: %v\", err)\n\t}\n\tfor {\n\t\tep, ok := <-notifications\n\t\tif !ok {\n\t\t\tt.Fatalf(\"watch channel is closed???\")\n\t\t}\n\t\tif ep == nil {\n\t\t\t\/\/ duplicate notification of the first value, that's OK\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ non-empty value, that one should be ours\n\t\tif !reflect.DeepEqual(&endPoints, ep) {\n\t\t\tt.Fatalf(\"first value is wrong: %v %v\", ep, ok)\n\t\t}\n\t\tbreak\n\t}\n\n\t\/\/ delete the endpoints, should get a notification\n\tif err := ts.DeleteEndPoints(cell, keyspace, shard, tabletType); err != nil {\n\t\tt.Fatalf(\"DeleteEndPoints failed: %v\", err)\n\t}\n\tfor {\n\t\tep, ok := <-notifications\n\t\tif !ok {\n\t\t\tt.Fatalf(\"watch channel is closed???\")\n\t\t}\n\t\tif ep == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ duplicate notification of the first value, that's OK,\n\t\t\/\/ but value better be good.\n\t\tif !reflect.DeepEqual(&endPoints, ep) {\n\t\t\tt.Fatalf(\"duplicate notification value is bad: %v\", ep)\n\t\t}\n\t}\n\n\t\/\/ re-create the value, a bit different, should get a notification\n\tendPoints.Entries[0].Uid = 2\n\tif err := topo.UpdateEndPoints(ctx, ts, cell, keyspace, shard, tabletType, &endPoints); err != nil {\n\t\tt.Fatalf(\"UpdateEndPoints failed: %v\", err)\n\t}\n\tfor {\n\t\tep, ok := <-notifications\n\t\tif !ok {\n\t\t\tt.Fatalf(\"watch channel is closed???\")\n\t\t}\n\t\tif ep == nil {\n\t\t\t\/\/ duplicate notification of the closed value, that's OK\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ non-empty value, that one should be ours\n\t\tif !reflect.DeepEqual(&endPoints, ep) {\n\t\t\tt.Fatalf(\"value after delete \/ re-create is wrong: %v %v\", ep, ok)\n\t\t}\n\t\tbreak\n\t}\n\n\t\/\/ close the stopWatching channel, should eventually get a closed\n\t\/\/ notifications channel too\n\tclose(stopWatching)\n\tfor {\n\t\tep, ok := <-notifications\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tif !reflect.DeepEqual(&endPoints, ep) {\n\t\t\tt.Fatalf(\"duplicate notification value is bad: %v\", ep)\n\t\t}\n\t}\n}\n<commit_msg>Adding unit tests for ShardReference packing.<commit_after>\/\/ Package test contains utilities to test topo.Server\n\/\/ implementations. If you are testing your implementation, you will\n\/\/ want to call CheckAll in your test method. For an example, look at\n\/\/ the tests in github.com\/youtube\/vitess\/go\/vt\/zktopo.\npackage test\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/youtube\/vitess\/go\/vt\/key\"\n\t\"github.com\/youtube\/vitess\/go\/vt\/topo\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ CheckServingGraph makes sure the serving graph functions work properly.\nfunc CheckServingGraph(ctx context.Context, t *testing.T, ts topo.Server) {\n\tcell := getLocalCell(t, ts)\n\n\t\/\/ test individual cell\/keyspace\/shard\/type entries\n\tif _, err := ts.GetSrvTabletTypesPerShard(cell, \"test_keyspace\", \"-10\"); err != topo.ErrNoNode {\n\t\tt.Errorf(\"GetSrvTabletTypesPerShard(invalid): %v\", err)\n\t}\n\tif _, err := ts.GetEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER); err != topo.ErrNoNode {\n\t\tt.Errorf(\"GetEndPoints(invalid): %v\", err)\n\t}\n\n\tendPoints := topo.EndPoints{\n\t\tEntries: []topo.EndPoint{\n\t\t\ttopo.EndPoint{\n\t\t\t\tUid:          1,\n\t\t\t\tHost:         \"host1\",\n\t\t\t\tNamedPortMap: map[string]int{\"vt\": 1234, \"mysql\": 1235, \"vts\": 1236},\n\t\t\t},\n\t\t},\n\t}\n\n\tif err := topo.UpdateEndPoints(ctx, ts, cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER, &endPoints); err != nil {\n\t\tt.Fatalf(\"UpdateEndPoints(master): %v\", err)\n\t}\n\tif types, err := ts.GetSrvTabletTypesPerShard(cell, \"test_keyspace\", \"-10\"); err != nil || len(types) != 1 || types[0] != topo.TYPE_MASTER {\n\t\tt.Errorf(\"GetSrvTabletTypesPerShard(1): %v %v\", err, types)\n\t}\n\n\t\/\/ Delete the SrvShard (need to delete endpoints first).\n\tif err := ts.DeleteEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER); err != nil {\n\t\tt.Errorf(\"DeleteEndPoints: %v\", err)\n\t}\n\tif err := ts.DeleteSrvShard(cell, \"test_keyspace\", \"-10\"); err != nil {\n\t\tt.Errorf(\"DeleteSrvShard: %v\", err)\n\t}\n\tif _, err := ts.GetSrvShard(cell, \"test_keyspace\", \"-10\"); err != topo.ErrNoNode {\n\t\tt.Errorf(\"GetSrvShard(deleted) got %v, want ErrNoNode\", err)\n\t}\n\n\t\/\/ Re-add endpoints.\n\tif err := topo.UpdateEndPoints(ctx, ts, cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER, &endPoints); err != nil {\n\t\tt.Fatalf(\"UpdateEndPoints(master): %v\", err)\n\t}\n\n\taddrs, err := ts.GetEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER)\n\tif err != nil {\n\t\tt.Errorf(\"GetEndPoints: %v\", err)\n\t}\n\tif len(addrs.Entries) != 1 || addrs.Entries[0].Uid != 1 {\n\t\tt.Errorf(\"GetEndPoints(1): %v\", addrs)\n\t}\n\tif pm := addrs.Entries[0].NamedPortMap; pm[\"vt\"] != 1234 || pm[\"mysql\"] != 1235 || pm[\"vts\"] != 1236 {\n\t\tt.Errorf(\"GetSrcTabletType(1).NamedPortmap: want %v, got %v\", endPoints.Entries[0].NamedPortMap, pm)\n\t}\n\n\tif err := ts.UpdateTabletEndpoint(cell, \"test_keyspace\", \"-10\", topo.TYPE_REPLICA, &topo.EndPoint{Uid: 2, Host: \"host2\"}); err != nil {\n\t\tt.Fatalf(\"UpdateTabletEndpoint(invalid): %v\", err)\n\t}\n\tif err := ts.UpdateTabletEndpoint(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER, &topo.EndPoint{Uid: 1, Host: \"host2\"}); err != nil {\n\t\tt.Fatalf(\"UpdateTabletEndpoint(master): %v\", err)\n\t}\n\tif addrs, err := ts.GetEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER); err != nil || len(addrs.Entries) != 1 || addrs.Entries[0].Uid != 1 {\n\t\tt.Errorf(\"GetEndPoints(2): %v %v\", err, addrs)\n\t}\n\tif err := ts.UpdateTabletEndpoint(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER, &topo.EndPoint{Uid: 3, Host: \"host3\"}); err != nil {\n\t\tt.Fatalf(\"UpdateTabletEndpoint(master): %v\", err)\n\t}\n\tif addrs, err := ts.GetEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER); err != nil || len(addrs.Entries) != 2 {\n\t\tt.Errorf(\"GetEndPoints(2): %v %v\", err, addrs)\n\t}\n\n\tif err := ts.DeleteEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_REPLICA); err != topo.ErrNoNode {\n\t\tt.Errorf(\"DeleteEndPoints(unknown): %v\", err)\n\t}\n\tif err := ts.DeleteEndPoints(cell, \"test_keyspace\", \"-10\", topo.TYPE_MASTER); err != nil {\n\t\tt.Errorf(\"DeleteEndPoints(master): %v\", err)\n\t}\n\n\t\/\/ test cell\/keyspace\/shard entries (SrvShard)\n\tsrvShard := topo.SrvShard{\n\t\tServedTypes: []topo.TabletType{topo.TYPE_MASTER},\n\t\tTabletTypes: []topo.TabletType{topo.TYPE_REPLICA, topo.TYPE_RDONLY},\n\t}\n\tif err := ts.UpdateSrvShard(cell, \"test_keyspace\", \"-10\", &srvShard); err != nil {\n\t\tt.Fatalf(\"UpdateSrvShard(1): %v\", err)\n\t}\n\tif _, err := ts.GetSrvShard(cell, \"test_keyspace\", \"666\"); err != topo.ErrNoNode {\n\t\tt.Errorf(\"GetSrvShard(invalid): %v\", err)\n\t}\n\tif s, err := ts.GetSrvShard(cell, \"test_keyspace\", \"-10\"); err != nil ||\n\t\tlen(s.ServedTypes) != 1 ||\n\t\ts.ServedTypes[0] != topo.TYPE_MASTER ||\n\t\tlen(s.TabletTypes) != 2 ||\n\t\ts.TabletTypes[0] != topo.TYPE_REPLICA ||\n\t\ts.TabletTypes[1] != topo.TYPE_RDONLY {\n\t\tt.Errorf(\"GetSrvShard(valid): %v\", err)\n\t}\n\n\t\/\/ test cell\/keyspace entries (SrvKeyspace)\n\tsrvKeyspace := topo.SrvKeyspace{\n\t\tPartitions: map[topo.TabletType]*topo.KeyspacePartition{\n\t\t\ttopo.TYPE_MASTER: &topo.KeyspacePartition{\n\t\t\t\tShards: []topo.SrvShard{\n\t\t\t\t\ttopo.SrvShard{\n\t\t\t\t\t\tServedTypes: []topo.TabletType{topo.TYPE_MASTER},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tShardReferences: []topo.ShardReference{\n\t\t\t\t\ttopo.ShardReference{\n\t\t\t\t\t\tName:     \"-80\",\n\t\t\t\t\t\tKeyRange: newKeyRange(\"-80\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tTabletTypes:        []topo.TabletType{topo.TYPE_MASTER},\n\t\tShardingColumnName: \"video_id\",\n\t\tShardingColumnType: key.KIT_UINT64,\n\t\tServedFrom: map[topo.TabletType]string{\n\t\t\ttopo.TYPE_REPLICA: \"other_keyspace\",\n\t\t},\n\t}\n\tif err := ts.UpdateSrvKeyspace(cell, \"test_keyspace\", &srvKeyspace); err != nil {\n\t\tt.Errorf(\"UpdateSrvKeyspace(1): %v\", err)\n\t}\n\tif _, err := ts.GetSrvKeyspace(cell, \"test_keyspace666\"); err != topo.ErrNoNode {\n\t\tt.Errorf(\"GetSrvKeyspace(invalid): %v\", err)\n\t}\n\tif k, err := ts.GetSrvKeyspace(cell, \"test_keyspace\"); err != nil ||\n\t\tlen(k.TabletTypes) != 1 ||\n\t\tk.TabletTypes[0] != topo.TYPE_MASTER ||\n\t\tlen(k.Partitions) != 1 ||\n\t\tlen(k.Partitions[topo.TYPE_MASTER].Shards) != 1 ||\n\t\tlen(k.Partitions[topo.TYPE_MASTER].Shards[0].ServedTypes) != 1 ||\n\t\tk.Partitions[topo.TYPE_MASTER].Shards[0].ServedTypes[0] != topo.TYPE_MASTER ||\n\t\tlen(k.Partitions[topo.TYPE_MASTER].ShardReferences) != 1 ||\n\t\tk.Partitions[topo.TYPE_MASTER].ShardReferences[0].Name != \"-80\" ||\n\t\tk.Partitions[topo.TYPE_MASTER].ShardReferences[0].KeyRange != newKeyRange(\"-80\") ||\n\t\tk.ShardingColumnName != \"video_id\" ||\n\t\tk.ShardingColumnType != key.KIT_UINT64 ||\n\t\tk.ServedFrom[topo.TYPE_REPLICA] != \"other_keyspace\" {\n\t\tt.Errorf(\"GetSrvKeyspace(valid): %v %v\", err, k)\n\t}\n\tif k, err := ts.GetSrvKeyspaceNames(cell); err != nil || len(k) != 1 || k[0] != \"test_keyspace\" {\n\t\tt.Errorf(\"GetSrvKeyspaceNames(): %v\", err)\n\t}\n\n\t\/\/ check that updating a SrvKeyspace out of the blue works\n\tif err := ts.UpdateSrvKeyspace(cell, \"unknown_keyspace_so_far\", &srvKeyspace); err != nil {\n\t\tt.Fatalf(\"UpdateSrvKeyspace(2): %v\", err)\n\t}\n\tif k, err := ts.GetSrvKeyspace(cell, \"unknown_keyspace_so_far\"); err != nil ||\n\t\tlen(k.TabletTypes) != 1 ||\n\t\tk.TabletTypes[0] != topo.TYPE_MASTER ||\n\t\tlen(k.Partitions) != 1 ||\n\t\tlen(k.Partitions[topo.TYPE_MASTER].Shards) != 1 ||\n\t\tlen(k.Partitions[topo.TYPE_MASTER].Shards[0].ServedTypes) != 1 ||\n\t\tk.Partitions[topo.TYPE_MASTER].Shards[0].ServedTypes[0] != topo.TYPE_MASTER ||\n\t\tlen(k.Partitions[topo.TYPE_MASTER].ShardReferences) != 1 ||\n\t\tk.Partitions[topo.TYPE_MASTER].ShardReferences[0].Name != \"-80\" ||\n\t\tk.Partitions[topo.TYPE_MASTER].ShardReferences[0].KeyRange != newKeyRange(\"-80\") ||\n\t\tk.ShardingColumnName != \"video_id\" ||\n\t\tk.ShardingColumnType != key.KIT_UINT64 ||\n\t\tk.ServedFrom[topo.TYPE_REPLICA] != \"other_keyspace\" {\n\t\tt.Errorf(\"GetSrvKeyspace(out of the blue): %v %v\", err, *k)\n\t}\n}\n\n\/\/ CheckWatchEndPoints makes sure WatchEndPoints works as expected\nfunc CheckWatchEndPoints(ctx context.Context, t *testing.T, ts topo.Server) {\n\tcell := getLocalCell(t, ts)\n\tkeyspace := \"test_keyspace\"\n\tshard := \"-10\"\n\ttabletType := topo.TYPE_MASTER\n\n\t\/\/ start watching, should get nil first\n\tnotifications, stopWatching, err := ts.WatchEndPoints(cell, keyspace, shard, tabletType)\n\tif err != nil {\n\t\tt.Fatalf(\"WatchEndPoints failed: %v\", err)\n\t}\n\tep, ok := <-notifications\n\tif !ok || ep != nil {\n\t\tt.Fatalf(\"first value is wrong: %v %v\", ep, ok)\n\t}\n\n\t\/\/ update the endpoints, should get a notification\n\tendPoints := topo.EndPoints{\n\t\tEntries: []topo.EndPoint{\n\t\t\ttopo.EndPoint{\n\t\t\t\tUid:          1,\n\t\t\t\tHost:         \"host1\",\n\t\t\t\tNamedPortMap: map[string]int{\"vt\": 1234, \"mysql\": 1235, \"vts\": 1236},\n\t\t\t},\n\t\t},\n\t}\n\tif err := topo.UpdateEndPoints(ctx, ts, cell, keyspace, shard, tabletType, &endPoints); err != nil {\n\t\tt.Fatalf(\"UpdateEndPoints failed: %v\", err)\n\t}\n\tfor {\n\t\tep, ok := <-notifications\n\t\tif !ok {\n\t\t\tt.Fatalf(\"watch channel is closed???\")\n\t\t}\n\t\tif ep == nil {\n\t\t\t\/\/ duplicate notification of the first value, that's OK\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ non-empty value, that one should be ours\n\t\tif !reflect.DeepEqual(&endPoints, ep) {\n\t\t\tt.Fatalf(\"first value is wrong: %v %v\", ep, ok)\n\t\t}\n\t\tbreak\n\t}\n\n\t\/\/ delete the endpoints, should get a notification\n\tif err := ts.DeleteEndPoints(cell, keyspace, shard, tabletType); err != nil {\n\t\tt.Fatalf(\"DeleteEndPoints failed: %v\", err)\n\t}\n\tfor {\n\t\tep, ok := <-notifications\n\t\tif !ok {\n\t\t\tt.Fatalf(\"watch channel is closed???\")\n\t\t}\n\t\tif ep == nil {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ duplicate notification of the first value, that's OK,\n\t\t\/\/ but value better be good.\n\t\tif !reflect.DeepEqual(&endPoints, ep) {\n\t\t\tt.Fatalf(\"duplicate notification value is bad: %v\", ep)\n\t\t}\n\t}\n\n\t\/\/ re-create the value, a bit different, should get a notification\n\tendPoints.Entries[0].Uid = 2\n\tif err := topo.UpdateEndPoints(ctx, ts, cell, keyspace, shard, tabletType, &endPoints); err != nil {\n\t\tt.Fatalf(\"UpdateEndPoints failed: %v\", err)\n\t}\n\tfor {\n\t\tep, ok := <-notifications\n\t\tif !ok {\n\t\t\tt.Fatalf(\"watch channel is closed???\")\n\t\t}\n\t\tif ep == nil {\n\t\t\t\/\/ duplicate notification of the closed value, that's OK\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ non-empty value, that one should be ours\n\t\tif !reflect.DeepEqual(&endPoints, ep) {\n\t\t\tt.Fatalf(\"value after delete \/ re-create is wrong: %v %v\", ep, ok)\n\t\t}\n\t\tbreak\n\t}\n\n\t\/\/ close the stopWatching channel, should eventually get a closed\n\t\/\/ notifications channel too\n\tclose(stopWatching)\n\tfor {\n\t\tep, ok := <-notifications\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tif !reflect.DeepEqual(&endPoints, ep) {\n\t\t\tt.Fatalf(\"duplicate notification value is bad: %v\", ep)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ ----------------------------------------------------------------------------\n\/\/\n\/\/     ***     AUTO GENERATED CODE    ***    AUTO GENERATED CODE     ***\n\/\/\n\/\/ ----------------------------------------------------------------------------\n\/\/\n\/\/     This file is automatically generated by Magic Modules and manual\n\/\/     changes will be clobbered when the file is regenerated.\n\/\/\n\/\/     Please read more about how to change this file in\n\/\/     .github\/CONTRIBUTING.md.\n\/\/\n\/\/ ----------------------------------------------------------------------------\n\npackage google\n\nimport \"reflect\"\n\nfunc GetCloudTasksQueueCaiObject(d TerraformResourceData, config *Config) (Asset, error) {\n\tname, err := assetName(d, config, \"\/\/cloudtasks.googleapis.com\/projects\/{{project}}\/locations\/{{location}}\/queues\/{{name}}\")\n\tif err != nil {\n\t\treturn Asset{}, err\n\t}\n\tif obj, err := GetCloudTasksQueueApiObject(d, config); err == nil {\n\t\treturn Asset{\n\t\t\tName: name,\n\t\t\tType: \"cloudtasks.googleapis.com\/Queue\",\n\t\t\tResource: &AssetResource{\n\t\t\t\tVersion:              \"v2\",\n\t\t\t\tDiscoveryDocumentURI: \"https:\/\/www.googleapis.com\/discovery\/v1\/apis\/cloudtasks\/v2\/rest\",\n\t\t\t\tDiscoveryName:        \"Queue\",\n\t\t\t\tData:                 obj,\n\t\t\t},\n\t\t}, nil\n\t} else {\n\t\treturn Asset{}, err\n\t}\n}\n\nfunc GetCloudTasksQueueApiObject(d TerraformResourceData, config *Config) (map[string]interface{}, error) {\n\tobj := make(map[string]interface{})\n\tnameProp, err := expandCloudTasksQueueName(d.Get(\"name\"), d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if v, ok := d.GetOkExists(\"name\"); !isEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) {\n\t\tobj[\"name\"] = nameProp\n\t}\n\tappEngineRoutingOverrideProp, err := expandCloudTasksQueueAppEngineRoutingOverride(d.Get(\"app_engine_routing_override\"), d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if v, ok := d.GetOkExists(\"app_engine_routing_override\"); !isEmptyValue(reflect.ValueOf(appEngineRoutingOverrideProp)) && (ok || !reflect.DeepEqual(v, appEngineRoutingOverrideProp)) {\n\t\tobj[\"appEngineRoutingOverride\"] = appEngineRoutingOverrideProp\n\t}\n\trateLimitsProp, err := expandCloudTasksQueueRateLimits(d.Get(\"rate_limits\"), d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if v, ok := d.GetOkExists(\"rate_limits\"); !isEmptyValue(reflect.ValueOf(rateLimitsProp)) && (ok || !reflect.DeepEqual(v, rateLimitsProp)) {\n\t\tobj[\"rateLimits\"] = rateLimitsProp\n\t}\n\tretryConfigProp, err := expandCloudTasksQueueRetryConfig(d.Get(\"retry_config\"), d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if v, ok := d.GetOkExists(\"retry_config\"); !isEmptyValue(reflect.ValueOf(retryConfigProp)) && (ok || !reflect.DeepEqual(v, retryConfigProp)) {\n\t\tobj[\"retryConfig\"] = retryConfigProp\n\t}\n\n\treturn obj, nil\n}\n\nfunc expandCloudTasksQueueName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn replaceVars(d, config, \"projects\/{{project}}\/locations\/{{location}}\/queues\/{{name}}\")\n}\n\nfunc expandCloudTasksQueueAppEngineRoutingOverride(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\tl := v.([]interface{})\n\tif len(l) == 0 || l[0] == nil {\n\t\treturn nil, nil\n\t}\n\traw := l[0]\n\toriginal := raw.(map[string]interface{})\n\ttransformed := make(map[string]interface{})\n\n\ttransformedService, err := expandCloudTasksQueueAppEngineRoutingOverrideService(original[\"service\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedService); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"service\"] = transformedService\n\t}\n\n\ttransformedVersion, err := expandCloudTasksQueueAppEngineRoutingOverrideVersion(original[\"version\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedVersion); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"version\"] = transformedVersion\n\t}\n\n\ttransformedInstance, err := expandCloudTasksQueueAppEngineRoutingOverrideInstance(original[\"instance\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedInstance); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"instance\"] = transformedInstance\n\t}\n\n\ttransformedHost, err := expandCloudTasksQueueAppEngineRoutingOverrideHost(original[\"host\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedHost); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"host\"] = transformedHost\n\t}\n\n\treturn transformed, nil\n}\n\nfunc expandCloudTasksQueueAppEngineRoutingOverrideService(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueAppEngineRoutingOverrideVersion(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueAppEngineRoutingOverrideInstance(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueAppEngineRoutingOverrideHost(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRateLimits(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\tl := v.([]interface{})\n\tif len(l) == 0 || l[0] == nil {\n\t\treturn nil, nil\n\t}\n\traw := l[0]\n\toriginal := raw.(map[string]interface{})\n\ttransformed := make(map[string]interface{})\n\n\ttransformedMaxDispatchesPerSecond, err := expandCloudTasksQueueRateLimitsMaxDispatchesPerSecond(original[\"max_dispatches_per_second\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxDispatchesPerSecond); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxDispatchesPerSecond\"] = transformedMaxDispatchesPerSecond\n\t}\n\n\ttransformedMaxConcurrentDispatches, err := expandCloudTasksQueueRateLimitsMaxConcurrentDispatches(original[\"max_concurrent_dispatches\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxConcurrentDispatches); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxConcurrentDispatches\"] = transformedMaxConcurrentDispatches\n\t}\n\n\ttransformedMaxBurstSize, err := expandCloudTasksQueueRateLimitsMaxBurstSize(original[\"max_burst_size\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxBurstSize); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxBurstSize\"] = transformedMaxBurstSize\n\t}\n\n\treturn transformed, nil\n}\n\nfunc expandCloudTasksQueueRateLimitsMaxDispatchesPerSecond(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRateLimitsMaxConcurrentDispatches(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRateLimitsMaxBurstSize(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRetryConfig(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\tl := v.([]interface{})\n\tif len(l) == 0 || l[0] == nil {\n\t\treturn nil, nil\n\t}\n\traw := l[0]\n\toriginal := raw.(map[string]interface{})\n\ttransformed := make(map[string]interface{})\n\n\ttransformedMaxAttempts, err := expandCloudTasksQueueRetryConfigMaxAttempts(original[\"max_attempts\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxAttempts); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxAttempts\"] = transformedMaxAttempts\n\t}\n\n\ttransformedMaxRetryDuration, err := expandCloudTasksQueueRetryConfigMaxRetryDuration(original[\"max_retry_duration\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxRetryDuration); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxRetryDuration\"] = transformedMaxRetryDuration\n\t}\n\n\ttransformedMinBackoff, err := expandCloudTasksQueueRetryConfigMinBackoff(original[\"min_backoff\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMinBackoff); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"minBackoff\"] = transformedMinBackoff\n\t}\n\n\ttransformedMaxBackoff, err := expandCloudTasksQueueRetryConfigMaxBackoff(original[\"max_backoff\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxBackoff); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxBackoff\"] = transformedMaxBackoff\n\t}\n\n\ttransformedMaxDoublings, err := expandCloudTasksQueueRetryConfigMaxDoublings(original[\"max_doublings\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxDoublings); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxDoublings\"] = transformedMaxDoublings\n\t}\n\n\treturn transformed, nil\n}\n\nfunc expandCloudTasksQueueRetryConfigMaxAttempts(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRetryConfigMaxRetryDuration(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRetryConfigMinBackoff(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRetryConfigMaxBackoff(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRetryConfigMaxDoublings(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n<commit_msg> Added stackdriver_logging_config to cloud_tasks_queue resource (#4077) (#545)<commit_after>\/\/ ----------------------------------------------------------------------------\n\/\/\n\/\/     ***     AUTO GENERATED CODE    ***    AUTO GENERATED CODE     ***\n\/\/\n\/\/ ----------------------------------------------------------------------------\n\/\/\n\/\/     This file is automatically generated by Magic Modules and manual\n\/\/     changes will be clobbered when the file is regenerated.\n\/\/\n\/\/     Please read more about how to change this file in\n\/\/     .github\/CONTRIBUTING.md.\n\/\/\n\/\/ ----------------------------------------------------------------------------\n\npackage google\n\nimport \"reflect\"\n\nfunc GetCloudTasksQueueCaiObject(d TerraformResourceData, config *Config) (Asset, error) {\n\tname, err := assetName(d, config, \"\/\/cloudtasks.googleapis.com\/projects\/{{project}}\/locations\/{{location}}\/queues\/{{name}}\")\n\tif err != nil {\n\t\treturn Asset{}, err\n\t}\n\tif obj, err := GetCloudTasksQueueApiObject(d, config); err == nil {\n\t\treturn Asset{\n\t\t\tName: name,\n\t\t\tType: \"cloudtasks.googleapis.com\/Queue\",\n\t\t\tResource: &AssetResource{\n\t\t\t\tVersion:              \"v2\",\n\t\t\t\tDiscoveryDocumentURI: \"https:\/\/www.googleapis.com\/discovery\/v1\/apis\/cloudtasks\/v2\/rest\",\n\t\t\t\tDiscoveryName:        \"Queue\",\n\t\t\t\tData:                 obj,\n\t\t\t},\n\t\t}, nil\n\t} else {\n\t\treturn Asset{}, err\n\t}\n}\n\nfunc GetCloudTasksQueueApiObject(d TerraformResourceData, config *Config) (map[string]interface{}, error) {\n\tobj := make(map[string]interface{})\n\tnameProp, err := expandCloudTasksQueueName(d.Get(\"name\"), d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if v, ok := d.GetOkExists(\"name\"); !isEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) {\n\t\tobj[\"name\"] = nameProp\n\t}\n\tappEngineRoutingOverrideProp, err := expandCloudTasksQueueAppEngineRoutingOverride(d.Get(\"app_engine_routing_override\"), d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if v, ok := d.GetOkExists(\"app_engine_routing_override\"); !isEmptyValue(reflect.ValueOf(appEngineRoutingOverrideProp)) && (ok || !reflect.DeepEqual(v, appEngineRoutingOverrideProp)) {\n\t\tobj[\"appEngineRoutingOverride\"] = appEngineRoutingOverrideProp\n\t}\n\trateLimitsProp, err := expandCloudTasksQueueRateLimits(d.Get(\"rate_limits\"), d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if v, ok := d.GetOkExists(\"rate_limits\"); !isEmptyValue(reflect.ValueOf(rateLimitsProp)) && (ok || !reflect.DeepEqual(v, rateLimitsProp)) {\n\t\tobj[\"rateLimits\"] = rateLimitsProp\n\t}\n\tretryConfigProp, err := expandCloudTasksQueueRetryConfig(d.Get(\"retry_config\"), d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if v, ok := d.GetOkExists(\"retry_config\"); !isEmptyValue(reflect.ValueOf(retryConfigProp)) && (ok || !reflect.DeepEqual(v, retryConfigProp)) {\n\t\tobj[\"retryConfig\"] = retryConfigProp\n\t}\n\tstackdriverLoggingConfigProp, err := expandCloudTasksQueueStackdriverLoggingConfig(d.Get(\"stackdriver_logging_config\"), d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if v, ok := d.GetOkExists(\"stackdriver_logging_config\"); !isEmptyValue(reflect.ValueOf(stackdriverLoggingConfigProp)) && (ok || !reflect.DeepEqual(v, stackdriverLoggingConfigProp)) {\n\t\tobj[\"stackdriverLoggingConfig\"] = stackdriverLoggingConfigProp\n\t}\n\n\treturn obj, nil\n}\n\nfunc expandCloudTasksQueueName(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn replaceVars(d, config, \"projects\/{{project}}\/locations\/{{location}}\/queues\/{{name}}\")\n}\n\nfunc expandCloudTasksQueueAppEngineRoutingOverride(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\tl := v.([]interface{})\n\tif len(l) == 0 || l[0] == nil {\n\t\treturn nil, nil\n\t}\n\traw := l[0]\n\toriginal := raw.(map[string]interface{})\n\ttransformed := make(map[string]interface{})\n\n\ttransformedService, err := expandCloudTasksQueueAppEngineRoutingOverrideService(original[\"service\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedService); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"service\"] = transformedService\n\t}\n\n\ttransformedVersion, err := expandCloudTasksQueueAppEngineRoutingOverrideVersion(original[\"version\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedVersion); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"version\"] = transformedVersion\n\t}\n\n\ttransformedInstance, err := expandCloudTasksQueueAppEngineRoutingOverrideInstance(original[\"instance\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedInstance); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"instance\"] = transformedInstance\n\t}\n\n\ttransformedHost, err := expandCloudTasksQueueAppEngineRoutingOverrideHost(original[\"host\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedHost); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"host\"] = transformedHost\n\t}\n\n\treturn transformed, nil\n}\n\nfunc expandCloudTasksQueueAppEngineRoutingOverrideService(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueAppEngineRoutingOverrideVersion(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueAppEngineRoutingOverrideInstance(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueAppEngineRoutingOverrideHost(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRateLimits(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\tl := v.([]interface{})\n\tif len(l) == 0 || l[0] == nil {\n\t\treturn nil, nil\n\t}\n\traw := l[0]\n\toriginal := raw.(map[string]interface{})\n\ttransformed := make(map[string]interface{})\n\n\ttransformedMaxDispatchesPerSecond, err := expandCloudTasksQueueRateLimitsMaxDispatchesPerSecond(original[\"max_dispatches_per_second\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxDispatchesPerSecond); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxDispatchesPerSecond\"] = transformedMaxDispatchesPerSecond\n\t}\n\n\ttransformedMaxConcurrentDispatches, err := expandCloudTasksQueueRateLimitsMaxConcurrentDispatches(original[\"max_concurrent_dispatches\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxConcurrentDispatches); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxConcurrentDispatches\"] = transformedMaxConcurrentDispatches\n\t}\n\n\ttransformedMaxBurstSize, err := expandCloudTasksQueueRateLimitsMaxBurstSize(original[\"max_burst_size\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxBurstSize); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxBurstSize\"] = transformedMaxBurstSize\n\t}\n\n\treturn transformed, nil\n}\n\nfunc expandCloudTasksQueueRateLimitsMaxDispatchesPerSecond(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRateLimitsMaxConcurrentDispatches(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRateLimitsMaxBurstSize(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRetryConfig(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\tl := v.([]interface{})\n\tif len(l) == 0 || l[0] == nil {\n\t\treturn nil, nil\n\t}\n\traw := l[0]\n\toriginal := raw.(map[string]interface{})\n\ttransformed := make(map[string]interface{})\n\n\ttransformedMaxAttempts, err := expandCloudTasksQueueRetryConfigMaxAttempts(original[\"max_attempts\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxAttempts); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxAttempts\"] = transformedMaxAttempts\n\t}\n\n\ttransformedMaxRetryDuration, err := expandCloudTasksQueueRetryConfigMaxRetryDuration(original[\"max_retry_duration\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxRetryDuration); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxRetryDuration\"] = transformedMaxRetryDuration\n\t}\n\n\ttransformedMinBackoff, err := expandCloudTasksQueueRetryConfigMinBackoff(original[\"min_backoff\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMinBackoff); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"minBackoff\"] = transformedMinBackoff\n\t}\n\n\ttransformedMaxBackoff, err := expandCloudTasksQueueRetryConfigMaxBackoff(original[\"max_backoff\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxBackoff); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxBackoff\"] = transformedMaxBackoff\n\t}\n\n\ttransformedMaxDoublings, err := expandCloudTasksQueueRetryConfigMaxDoublings(original[\"max_doublings\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedMaxDoublings); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"maxDoublings\"] = transformedMaxDoublings\n\t}\n\n\treturn transformed, nil\n}\n\nfunc expandCloudTasksQueueRetryConfigMaxAttempts(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRetryConfigMaxRetryDuration(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRetryConfigMinBackoff(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRetryConfigMaxBackoff(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueRetryConfigMaxDoublings(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n\nfunc expandCloudTasksQueueStackdriverLoggingConfig(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\tl := v.([]interface{})\n\tif len(l) == 0 || l[0] == nil {\n\t\treturn nil, nil\n\t}\n\traw := l[0]\n\toriginal := raw.(map[string]interface{})\n\ttransformed := make(map[string]interface{})\n\n\ttransformedSamplingRatio, err := expandCloudTasksQueueStackdriverLoggingConfigSamplingRatio(original[\"sampling_ratio\"], d, config)\n\tif err != nil {\n\t\treturn nil, err\n\t} else if val := reflect.ValueOf(transformedSamplingRatio); val.IsValid() && !isEmptyValue(val) {\n\t\ttransformed[\"samplingRatio\"] = transformedSamplingRatio\n\t}\n\n\treturn transformed, nil\n}\n\nfunc expandCloudTasksQueueStackdriverLoggingConfigSamplingRatio(v interface{}, d TerraformResourceData, config *Config) (interface{}, error) {\n\treturn v, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package indicators\n\nimport (\n\t\"container\/list\"\n\t\"errors\"\n\t\"github.com\/thetruetrade\/gotrade\"\n)\n\n\/\/ A Rate of Change Indicator (Roc), no storage, for use in other indicators\ntype RocWithoutStorage struct {\n\t*baseIndicator\n\t*baseFloatBounds\n\n\t\/\/ private variables\n\tvalueAvailableAction ValueAvailableActionFloat\n\tperiodCounter        int\n\tperiodHistory        *list.List\n\ttimePeriod           int\n}\n\n\/\/ NewRocWithoutStorage creates a Rate of Change Indicator (Roc) without storage\nfunc NewRocWithoutStorage(timePeriod int, valueAvailableAction ValueAvailableActionFloat) (indicator *RocWithoutStorage, err error) {\n\n\t\/\/ an indicator without storage MUST have a value available action\n\tif valueAvailableAction == nil {\n\t\treturn nil, ErrValueAvailableActionIsNil\n\t}\n\n\t\/\/ the minimum timeperiod for this indicator is 1\n\tif timePeriod < 1 {\n\t\treturn nil, errors.New(\"timePeriod is less than the minimum (1)\")\n\t}\n\n\t\/\/ check the maximum timeperiod\n\tif timePeriod > MaximumLookbackPeriod {\n\t\treturn nil, errors.New(\"timePeriod is greater than the maximum (100000)\")\n\t}\n\n\tlookback := timePeriod\n\tind := RocWithoutStorage{\n\t\tbaseIndicator:        newBaseIndicator(lookback),\n\t\tbaseFloatBounds:      newBaseFloatBounds(),\n\t\tperiodCounter:        (timePeriod * -1),\n\t\tperiodHistory:        list.New(),\n\t\tvalueAvailableAction: valueAvailableAction,\n\t\ttimePeriod:           timePeriod,\n\t}\n\n\treturn &ind, nil\n}\n\n\/\/ A Rate of Change Indicator (Roc)\ntype Roc struct {\n\t*RocWithoutStorage\n\tselectData gotrade.DataSelectionFunc\n\n\t\/\/ public variables\n\tData []float64\n}\n\n\/\/ NewRoc creates a Rate of Change Indicator (Roc) for online usage\nfunc NewRoc(timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Roc, err error) {\n\tind := Roc{selectData: selectData}\n\tind.RocWithoutStorage, err = NewRocWithoutStorage(timePeriod,\n\t\tfunc(dataItem float64, streamBarIndex int) {\n\t\t\tind.Data = append(ind.Data, dataItem)\n\t\t})\n\n\treturn &ind, err\n}\n\n\/\/ NewDefaultRoc creates a Rate of Change Indicator (Roc) for online usage with default parameters\n\/\/\t- timePeriod: 10\nfunc NewDefaultRoc() (indicator *Roc, err error) {\n\ttimePeriod := 10\n\treturn NewRoc(timePeriod, gotrade.UseClosePrice)\n}\n\n\/\/ NewRocWithSrcLen creates a Rate of Change Indicator (Roc) for offline usage\nfunc NewRocWithSrcLen(sourceLength uint, timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Roc, err error) {\n\tind, err := NewRoc(timePeriod, selectData)\n\n\t\/\/ only initialise the storage if there is enough source data to require it\n\tif sourceLength-uint(ind.GetLookbackPeriod()) > 1 {\n\t\tind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod()))\n\t}\n\n\treturn ind, err\n}\n\n\/\/ NewDefaultRocWithSrcLen creates a Rate of Change Indicator (Roc) for offline usage with default parameters\nfunc NewDefaultRocWithSrcLen(sourceLength uint) (indicator *Roc, err error) {\n\tind, err := NewDefaultRoc()\n\n\t\/\/ only initialise the storage if there is enough source data to require it\n\tif sourceLength-uint(ind.GetLookbackPeriod()) > 1 {\n\t\tind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod()))\n\t}\n\n\treturn ind, err\n}\n\n\/\/ NewRocForStream creates a Rate of Change Indicator (Roc) for online usage with a source data stream\nfunc NewRocForStream(priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Roc, err error) {\n\tind, err := NewRoc(timePeriod, selectData)\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ NewDefaultRocForStream creates a Rate of Change Indicator (Roc) for online usage with a source data stream\nfunc NewDefaultRocForStream(priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Roc, err error) {\n\tind, err := NewDefaultRoc()\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ NewRocForStreamWithSrcLen creates a Rate of Change Indicator (Roc) for offline usage with a source data stream\nfunc NewRocForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Roc, err error) {\n\tind, err := NewRocWithSrcLen(sourceLength, timePeriod, selectData)\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ NewDefaultRocForStreamWithSrcLen creates a Rate of Change Indicator (Roc) for offline usage with a source data stream\nfunc NewDefaultRocForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Roc, err error) {\n\tind, err := NewDefaultRocWithSrcLen(sourceLength)\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ ReceiveDOHLCVTick consumes a source data DOHLCV price tick\nfunc (ind *Roc) ReceiveDOHLCVTick(tickData gotrade.DOHLCV, streamBarIndex int) {\n\tvar selectedData = ind.selectData(tickData)\n\tind.ReceiveTick(selectedData, streamBarIndex)\n}\n\nfunc (ind *RocWithoutStorage) ReceiveTick(tickData float64, streamBarIndex int) {\n\tind.periodCounter += 1\n\tind.periodHistory.PushBack(tickData)\n\n\tif ind.periodCounter > 0 {\n\n\t\t\/\/    Roc = (price\/previousPrice - 1) * 100\n\t\tpreviousPrice := ind.periodHistory.Front().Value.(float64)\n\n\t\t\/\/ increment the number of results this indicator can be expected to return\n\t\tind.dataLength += 1\n\t\tif ind.validFromBar == -1 {\n\t\t\t\/\/ set the streamBarIndex from which this indicator returns valid results\n\t\t\tind.validFromBar = streamBarIndex\n\t\t}\n\t\tvar result float64\n\t\tif previousPrice != 0 {\n\t\t\tresult = 100.0 * ((tickData \/ previousPrice) - 1)\n\t\t} else {\n\t\t\tresult = 0.0\n\t\t}\n\n\t\t\/\/ update the maximum result value\n\t\tif result > ind.maxValue {\n\t\t\tind.maxValue = result\n\t\t}\n\n\t\t\/\/ update the minimum result value\n\t\tif result < ind.minValue {\n\t\t\tind.minValue = result\n\t\t}\n\n\t\t\/\/ notify of a new result value though the value available action\n\t\tind.valueAvailableAction(result, streamBarIndex)\n\t}\n\n\tif ind.periodHistory.Len() > ind.timePeriod {\n\t\tfirst := ind.periodHistory.Front()\n\t\tind.periodHistory.Remove(first)\n\t}\n}\n<commit_msg>#76 Remove duplication - roc<commit_after>package indicators\n\nimport (\n\t\"container\/list\"\n\t\"errors\"\n\t\"github.com\/thetruetrade\/gotrade\"\n)\n\n\/\/ A Rate of Change Indicator (Roc), no storage, for use in other indicators\ntype RocWithoutStorage struct {\n\t*baseIndicatorWithFloatBounds\n\n\t\/\/ private variables\n\tperiodCounter int\n\tperiodHistory *list.List\n\ttimePeriod    int\n}\n\n\/\/ NewRocWithoutStorage creates a Rate of Change Indicator (Roc) without storage\nfunc NewRocWithoutStorage(timePeriod int, valueAvailableAction ValueAvailableActionFloat) (indicator *RocWithoutStorage, err error) {\n\n\t\/\/ an indicator without storage MUST have a value available action\n\tif valueAvailableAction == nil {\n\t\treturn nil, ErrValueAvailableActionIsNil\n\t}\n\n\t\/\/ the minimum timeperiod for this indicator is 1\n\tif timePeriod < 1 {\n\t\treturn nil, errors.New(\"timePeriod is less than the minimum (1)\")\n\t}\n\n\t\/\/ check the maximum timeperiod\n\tif timePeriod > MaximumLookbackPeriod {\n\t\treturn nil, errors.New(\"timePeriod is greater than the maximum (100000)\")\n\t}\n\n\tlookback := timePeriod\n\tind := RocWithoutStorage{\n\t\tbaseIndicatorWithFloatBounds: newBaseIndicatorWithFloatBounds(lookback, valueAvailableAction),\n\t\tperiodCounter:                (timePeriod * -1),\n\t\tperiodHistory:                list.New(),\n\t\ttimePeriod:                   timePeriod,\n\t}\n\n\treturn &ind, nil\n}\n\n\/\/ A Rate of Change Indicator (Roc)\ntype Roc struct {\n\t*RocWithoutStorage\n\tselectData gotrade.DataSelectionFunc\n\n\t\/\/ public variables\n\tData []float64\n}\n\n\/\/ NewRoc creates a Rate of Change Indicator (Roc) for online usage\nfunc NewRoc(timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Roc, err error) {\n\tind := Roc{selectData: selectData}\n\tind.RocWithoutStorage, err = NewRocWithoutStorage(timePeriod,\n\t\tfunc(dataItem float64, streamBarIndex int) {\n\t\t\tind.Data = append(ind.Data, dataItem)\n\t\t})\n\n\treturn &ind, err\n}\n\n\/\/ NewDefaultRoc creates a Rate of Change Indicator (Roc) for online usage with default parameters\n\/\/\t- timePeriod: 10\nfunc NewDefaultRoc() (indicator *Roc, err error) {\n\ttimePeriod := 10\n\treturn NewRoc(timePeriod, gotrade.UseClosePrice)\n}\n\n\/\/ NewRocWithSrcLen creates a Rate of Change Indicator (Roc) for offline usage\nfunc NewRocWithSrcLen(sourceLength uint, timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Roc, err error) {\n\tind, err := NewRoc(timePeriod, selectData)\n\n\t\/\/ only initialise the storage if there is enough source data to require it\n\tif sourceLength-uint(ind.GetLookbackPeriod()) > 1 {\n\t\tind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod()))\n\t}\n\n\treturn ind, err\n}\n\n\/\/ NewDefaultRocWithSrcLen creates a Rate of Change Indicator (Roc) for offline usage with default parameters\nfunc NewDefaultRocWithSrcLen(sourceLength uint) (indicator *Roc, err error) {\n\tind, err := NewDefaultRoc()\n\n\t\/\/ only initialise the storage if there is enough source data to require it\n\tif sourceLength-uint(ind.GetLookbackPeriod()) > 1 {\n\t\tind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod()))\n\t}\n\n\treturn ind, err\n}\n\n\/\/ NewRocForStream creates a Rate of Change Indicator (Roc) for online usage with a source data stream\nfunc NewRocForStream(priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Roc, err error) {\n\tind, err := NewRoc(timePeriod, selectData)\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ NewDefaultRocForStream creates a Rate of Change Indicator (Roc) for online usage with a source data stream\nfunc NewDefaultRocForStream(priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Roc, err error) {\n\tind, err := NewDefaultRoc()\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ NewRocForStreamWithSrcLen creates a Rate of Change Indicator (Roc) for offline usage with a source data stream\nfunc NewRocForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DataSelectionFunc) (indicator *Roc, err error) {\n\tind, err := NewRocWithSrcLen(sourceLength, timePeriod, selectData)\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ NewDefaultRocForStreamWithSrcLen creates a Rate of Change Indicator (Roc) for offline usage with a source data stream\nfunc NewDefaultRocForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Roc, err error) {\n\tind, err := NewDefaultRocWithSrcLen(sourceLength)\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\n}\n\n\/\/ ReceiveDOHLCVTick consumes a source data DOHLCV price tick\nfunc (ind *Roc) ReceiveDOHLCVTick(tickData gotrade.DOHLCV, streamBarIndex int) {\n\tvar selectedData = ind.selectData(tickData)\n\tind.ReceiveTick(selectedData, streamBarIndex)\n}\n\nfunc (ind *RocWithoutStorage) ReceiveTick(tickData float64, streamBarIndex int) {\n\tind.periodCounter += 1\n\tind.periodHistory.PushBack(tickData)\n\n\tif ind.periodCounter > 0 {\n\n\t\t\/\/    Roc = (price\/previousPrice - 1) * 100\n\t\tpreviousPrice := ind.periodHistory.Front().Value.(float64)\n\n\t\tvar result float64\n\t\tif previousPrice != 0 {\n\t\t\tresult = 100.0 * ((tickData \/ previousPrice) - 1)\n\t\t} else {\n\t\t\tresult = 0.0\n\t\t}\n\n\t\tind.UpdateIndicatorWithNewValue(result, streamBarIndex)\n\t}\n\n\tif ind.periodHistory.Len() > ind.timePeriod {\n\t\tfirst := ind.periodHistory.Front()\n\t\tind.periodHistory.Remove(first)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012, 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage state\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"labix.org\/v2\/mgo\/txn\"\n\t\"launchpad.net\/juju-core\/utils\"\n)\n\n\/\/ minimumUnitsDoc allows for keeping track of relevant changes on the\n\/\/ service MinimumUnits field and on the number of alive units for the service.\n\/\/ A new document is created when MinimumUnits is set to a non zero value.\n\/\/ A document is deleted when either the associated service is destroyed\n\/\/ or MinimumUnits is restored to zero. The Revno is increased when either\n\/\/ MinimumUnits for a service is increased or a unit is destroyed.\n\/\/ TODO(frankban): the MinimumUnitsWatcher reacts to changes sending events,\n\/\/ each one describing one or more services. A worker reacts to those events\n\/\/ ensuring the number of units for the service is never less than the actual\n\/\/ alive units: new units are added if required (see EnsureMinimumUnits below).\ntype minimumUnitsDoc struct {\n\t\/\/ Since the referred entity type is always the Service, it is safe here\n\t\/\/ to use the service name as id in place of its globalKey.\n\tServiceName string `bson:\"_id\"`\n\tRevno       int\n\tTxnRevno    int64 `bson:\"txn-revno\"`\n}\n\n\/\/ SetMinimumUnits changes the amount of minimum units required by the service.\nfunc (s *Service) SetMinimumUnits(minimumUnits int) (err error) {\n\tdefer utils.ErrorContextf(&err, \"cannot set minimum units for service %q\", s)\n\tif minimumUnits < 0 {\n\t\treturn errors.New(\"minimum units must be a positive number\")\n\t}\n\tserviceName := s.doc.Name\n\tserviceOp := txn.Op{\n\t\tC:      s.st.services.Name,\n\t\tId:     serviceName,\n\t\tAssert: isAliveDoc,\n\t\tUpdate: D{{\"$set\", D{{\"minimumunits\", minimumUnits}}}},\n\t}\n\t\/\/ Removing the document never fails. Racing clients trying to create the\n\t\/\/ document generate one failure, but the second attempt should succeed.\n\t\/\/ If one client tries to update the document, and a racing client removes\n\t\/\/ it, the former should be able to re-create the document in the second\n\t\/\/ attempt. If the referred-to service advanced his life cycle to a not\n\t\/\/ alive state, an error is returned after two failing attempts.\n\tfor i := 0; i < 3; i++ {\n\t\tops := []txn.Op{serviceOp}\n\t\tif count, err := s.st.minimumUnits.FindId(serviceName).Count(); err != nil {\n\t\t\treturn err\n\t\t} else if count == 0 {\n\t\t\tif i == 2 {\n\t\t\t\treturn errors.New(\"service is no longer alive\")\n\t\t\t}\n\t\t\tif minimumUnits != 0 {\n\t\t\t\tops = append(ops, minimumUnitsInsertOp(s.st, s.doc.Name))\n\t\t\t}\n\t\t} else {\n\t\t\tif minimumUnits == 0 {\n\t\t\t\tops = append(ops, minimumUnitsRemoveOp(s.st, s.doc.Name))\n\t\t\t} else if minimumUnits > s.doc.MinimumUnits {\n\t\t\t\tops = append(ops, minimumUnitsUpdateOp(s.st, s.doc.Name))\n\t\t\t}\n\t\t}\n\t\tif err := s.st.runTransaction(ops); err == nil {\n\t\t\ts.doc.MinimumUnits = minimumUnits\n\t\t\treturn nil\n\t\t} else if err != txn.ErrAborted {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn ErrExcessiveContention\n}\n\n\/\/ minimumUnitsInsertOp returns the operation required to insert a minimum\n\/\/ units document for the service in MongoDB.\nfunc minimumUnitsInsertOp(st *State, serviceName string) txn.Op {\n\treturn txn.Op{\n\t\tC:      st.minimumUnits.Name,\n\t\tId:     serviceName,\n\t\tAssert: txn.DocMissing,\n\t\tInsert: &minimumUnitsDoc{ServiceName: serviceName},\n\t}\n}\n\n\/\/ minimumUnitsIncreaseOp returns the operation required to increase the\n\/\/ minimum units revno for the service in MongoDB, ignoring the case of\n\/\/ document not existing. This is included in the operations performed when\n\/\/ a unit is destroyed: if the document exists, then we need to update the\n\/\/ Revno. If the service does not require a minimum amount of units, then\n\/\/ the operation is a noop.\nfunc minimumUnitsIncreaseOp(st *State, serviceName string) txn.Op {\n\treturn txn.Op{\n\t\tC:      st.minimumUnits.Name,\n\t\tId:     serviceName,\n\t\tUpdate: D{{\"$inc\", D{{\"revno\", 1}}}},\n\t}\n}\n\n\/\/ minimumUnitsUpdateOp returns the operation required to increase the\n\/\/ minimum units revno for the service in MongoDB. The document must exist.\nfunc minimumUnitsUpdateOp(st *State, serviceName string) txn.Op {\n\top := minimumUnitsIncreaseOp(st, serviceName)\n\top.Assert = txn.DocExists\n\treturn op\n}\n\n\/\/ minimumUnitsRemoveOp returns the operation required to remove the minimum\n\/\/ units document from MongoDB.\nfunc minimumUnitsRemoveOp(st *State, serviceName string) txn.Op {\n\treturn txn.Op{\n\t\tC:      st.minimumUnits.Name,\n\t\tId:     serviceName,\n\t\tRemove: true,\n\t}\n}\n\n\/\/ MinimumUnits returns the minimum units count for the service.\nfunc (s *Service) MinimumUnits() int {\n\treturn s.doc.MinimumUnits\n}\n\n\/\/ AliveUnitsCount returns the amount of alive units of the service.\nfunc (s *Service) AliveUnitsCount() (int, error) {\n\tquery := D{{\"service\", s.doc.Name}, {\"life\", Alive}}\n\talive, err := s.st.units.Find(query).Count()\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\n\t\t\t\"cannot get alive units count from service %q: %v\", s, err)\n\t}\n\treturn alive, nil\n}\n\n\/\/ EnsureMinimumUnits adds new units if the service MinimumUnits value is\n\/\/ greater than the number of alive units.\nfunc (s *Service) EnsureMinimumUnits() error {\n\taliveUnits, err := s.AliveUnitsCount()\n\tif err != nil {\n\t\treturn err\n\t}\n\tmissing := s.MinimumUnits() - aliveUnits\n\tif missing <= 0 {\n\t\treturn nil\n\t}\n\tfor i := 0; i < missing; i++ {\n\t\tunit, err := s.AddUnit()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot add unit %d\/%d to service %q: %v\",\n\t\t\t\ti+1, missing, s.Name(), err)\n\t\t}\n\t\tif err := s.st.AssignUnit(unit, AssignNew); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Comment changes as per review.<commit_after>\/\/ Copyright 2012, 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage state\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"labix.org\/v2\/mgo\/txn\"\n\t\"launchpad.net\/juju-core\/utils\"\n)\n\n\/\/ minimumUnitsDoc keeps track of relevant changes on the service's\n\/\/ MinimumUnits field and on the number of alive units for the service.\n\/\/ A new document is created when MinimumUnits is set to a non zero value.\n\/\/ A document is deleted when either the associated service is destroyed\n\/\/ or MinimumUnits is restored to zero. The Revno is increased when either\n\/\/ MinimumUnits for a service is increased or a unit is destroyed.\n\/\/ TODO(frankban): the MinimumUnitsWatcher reacts to changes sending events,\n\/\/ each one describing one or more services. A worker reacts to those events\n\/\/ ensuring the number of units for the service is never less than the actual\n\/\/ alive units: new units are added if required (see EnsureMinimumUnits below).\ntype minimumUnitsDoc struct {\n\t\/\/ ServiceName is safe to be used here in place of its globalKey, since\n\t\/\/ the referred entity type is always the Service.\n\tServiceName string `bson:\"_id\"`\n\tRevno       int\n\tTxnRevno    int64 `bson:\"txn-revno\"`\n}\n\n\/\/ SetMinimumUnits changes the amount of minimum units required by the service.\nfunc (s *Service) SetMinimumUnits(minimumUnits int) (err error) {\n\tdefer utils.ErrorContextf(&err, \"cannot set minimum units for service %q\", s)\n\tif minimumUnits < 0 {\n\t\treturn errors.New(\"minimum units must be a positive number\")\n\t}\n\tserviceName := s.doc.Name\n\tserviceOp := txn.Op{\n\t\tC:      s.st.services.Name,\n\t\tId:     serviceName,\n\t\tAssert: isAliveDoc,\n\t\tUpdate: D{{\"$set\", D{{\"minimumunits\", minimumUnits}}}},\n\t}\n\t\/\/ Removing the document never fails. Racing clients trying to create the\n\t\/\/ document generate one failure, but the second attempt should succeed.\n\t\/\/ If one client tries to update the document, and a racing client removes\n\t\/\/ it, the former should be able to re-create the document in the second\n\t\/\/ attempt. If the referred-to service advanced his life cycle to a not\n\t\/\/ alive state, an error is returned after two failing attempts.\n\tfor i := 0; i < 3; i++ {\n\t\tops := []txn.Op{serviceOp}\n\t\tif count, err := s.st.minimumUnits.FindId(serviceName).Count(); err != nil {\n\t\t\treturn err\n\t\t} else if count == 0 {\n\t\t\tif i == 2 {\n\t\t\t\treturn errors.New(\"service is no longer alive\")\n\t\t\t}\n\t\t\tif minimumUnits != 0 {\n\t\t\t\tops = append(ops, minimumUnitsInsertOp(s.st, s.doc.Name))\n\t\t\t}\n\t\t} else {\n\t\t\tif minimumUnits == 0 {\n\t\t\t\tops = append(ops, minimumUnitsRemoveOp(s.st, s.doc.Name))\n\t\t\t} else if minimumUnits > s.doc.MinimumUnits {\n\t\t\t\tops = append(ops, minimumUnitsUpdateOp(s.st, s.doc.Name))\n\t\t\t}\n\t\t}\n\t\tif err := s.st.runTransaction(ops); err == nil {\n\t\t\ts.doc.MinimumUnits = minimumUnits\n\t\t\treturn nil\n\t\t} else if err != txn.ErrAborted {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn ErrExcessiveContention\n}\n\n\/\/ minimumUnitsInsertOp returns the operation required to insert a minimum\n\/\/ units document for the service in MongoDB.\nfunc minimumUnitsInsertOp(st *State, serviceName string) txn.Op {\n\treturn txn.Op{\n\t\tC:      st.minimumUnits.Name,\n\t\tId:     serviceName,\n\t\tAssert: txn.DocMissing,\n\t\tInsert: &minimumUnitsDoc{ServiceName: serviceName},\n\t}\n}\n\n\/\/ minimumUnitsIncreaseOp returns the operation required to increase the\n\/\/ minimum units revno for the service in MongoDB, ignoring the case of\n\/\/ document not existing. This is included in the operations performed when\n\/\/ a unit is destroyed: if the document exists, then we need to update the\n\/\/ Revno. If the service does not require a minimum amount of units, then\n\/\/ the operation is a noop.\nfunc minimumUnitsIncreaseOp(st *State, serviceName string) txn.Op {\n\treturn txn.Op{\n\t\tC:      st.minimumUnits.Name,\n\t\tId:     serviceName,\n\t\tUpdate: D{{\"$inc\", D{{\"revno\", 1}}}},\n\t}\n}\n\n\/\/ minimumUnitsUpdateOp returns the operation required to increase the\n\/\/ minimum units revno for the service in MongoDB. The document must exist.\nfunc minimumUnitsUpdateOp(st *State, serviceName string) txn.Op {\n\top := minimumUnitsIncreaseOp(st, serviceName)\n\top.Assert = txn.DocExists\n\treturn op\n}\n\n\/\/ minimumUnitsRemoveOp returns the operation required to remove the minimum\n\/\/ units document from MongoDB.\nfunc minimumUnitsRemoveOp(st *State, serviceName string) txn.Op {\n\treturn txn.Op{\n\t\tC:      st.minimumUnits.Name,\n\t\tId:     serviceName,\n\t\tRemove: true,\n\t}\n}\n\n\/\/ MinimumUnits returns the minimum units count for the service.\nfunc (s *Service) MinimumUnits() int {\n\treturn s.doc.MinimumUnits\n}\n\n\/\/ AliveUnitsCount returns the amount of alive units of the service.\nfunc (s *Service) AliveUnitsCount() (int, error) {\n\tquery := D{{\"service\", s.doc.Name}, {\"life\", Alive}}\n\talive, err := s.st.units.Find(query).Count()\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\n\t\t\t\"cannot get alive units count from service %q: %v\", s, err)\n\t}\n\treturn alive, nil\n}\n\n\/\/ EnsureMinimumUnits adds new units if the service MinimumUnits value is\n\/\/ greater than the number of alive units.\nfunc (s *Service) EnsureMinimumUnits() error {\n\taliveUnits, err := s.AliveUnitsCount()\n\tif err != nil {\n\t\treturn err\n\t}\n\tmissing := s.MinimumUnits() - aliveUnits\n\tif missing <= 0 {\n\t\treturn nil\n\t}\n\tfor i := 0; i < missing; i++ {\n\t\tunit, err := s.AddUnit()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"cannot add unit %d\/%d to service %q: %v\",\n\t\t\t\ti+1, missing, s.Name(), err)\n\t\t}\n\t\tif err := s.st.AssignUnit(unit, AssignNew); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package configuration\n\nimport (\n\t\"cf\"\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n)\n\nconst (\n\tfilePermissions      = 0644\n\tdirPermissions       = 0700\n\tcurrentConfigVersion = 2\n)\n\nvar singleton *Configuration\n\ntype ConfigurationRepository interface {\n\tGet() (config *Configuration, err error)\n\tDelete()\n\tSave() (err error)\n\tClearTokens() (err error)\n\tClearSession() (err error)\n\tSetOrganization(org cf.OrganizationFields) (err error)\n\tSetSpace(space cf.SpaceFields) (err error)\n}\n\ntype ConfigurationDiskRepository struct{}\n\nfunc NewConfigurationDiskRepository() (repo ConfigurationDiskRepository) {\n\treturn ConfigurationDiskRepository{}\n}\n\nfunc (repo ConfigurationDiskRepository) SetOrganization(org cf.OrganizationFields) (err error) {\n\tconfig, err := repo.Get()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconfig.OrganizationFields = org\n\tconfig.SpaceFields = cf.SpaceFields{}\n\n\treturn saveConfiguration(config)\n}\n\nfunc (repo ConfigurationDiskRepository) SetSpace(space cf.SpaceFields) (err error) {\n\tconfig, err := repo.Get()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconfig.SpaceFields = space\n\n\treturn saveConfiguration(config)\n}\n\nfunc (repo ConfigurationDiskRepository) Get() (c *Configuration, err error) {\n\tif singleton == nil {\n\t\tsingleton, err = repo.load()\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn singleton, nil\n}\n\nfunc (repo ConfigurationDiskRepository) Delete() {\n\tfile, err := ConfigFile()\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tos.Remove(file)\n\tsingleton = nil\n}\n\nfunc (repo ConfigurationDiskRepository) Save() (err error) {\n\tc, err := repo.Get()\n\tif err != nil {\n\t\treturn\n\t}\n\treturn saveConfiguration(c)\n}\n\nfunc (repo ConfigurationDiskRepository) ClearTokens() (err error) {\n\tc, err := repo.Get()\n\tif err != nil {\n\t\treturn\n\t}\n\tc.AccessToken = \"\"\n\tc.RefreshToken = \"\"\n\treturn\n}\n\nfunc (repo ConfigurationDiskRepository) ClearSession() (err error) {\n\terr = repo.ClearTokens()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tc, err := repo.Get()\n\tif err != nil {\n\t\treturn\n\t}\n\tc.OrganizationFields = cf.OrganizationFields{}\n\tc.SpaceFields = cf.SpaceFields{}\n\n\treturn saveConfiguration(c)\n}\n\n\/\/ Keep this one public for configtest\/configuration.go\nfunc ConfigFile() (file string, err error) {\n\n\tconfigDir := filepath.Join(userHomeDir(), \".cf\")\n\n\terr = os.MkdirAll(configDir, dirPermissions)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfile = filepath.Join(configDir, \"config.json\")\n\treturn\n}\n\n\/\/ See: http:\/\/stackoverflow.com\/questions\/7922270\/obtain-users-home-directory\n\/\/ we can't cross compile using cgo and use user.Current()\nfunc userHomeDir() string {\n\tif runtime.GOOS == \"windows\" {\n\t\thome := os.Getenv(\"HOMEDRIVE\") + os.Getenv(\"HOMEPATH\")\n\t\tif home == \"\" {\n\t\t\thome = os.Getenv(\"USERPROFILE\")\n\t\t}\n\t\treturn home\n\t}\n\n\treturn os.Getenv(\"HOME\")\n}\n\nfunc defaultConfig() (c *Configuration) {\n\tc = new(Configuration)\n\tc.Target = \"\"\n\tc.ApiVersion = \"\"\n\tc.AuthorizationEndpoint = \"\"\n\tc.ApplicationStartTimeout = 30 \/\/ seconds\n\tc.ConfigVersion = currentConfigVersion\n\n\treturn\n}\n\nfunc (repo ConfigurationDiskRepository) load() (c *Configuration, parseError error) {\n\tfile, readError := ConfigFile()\n\tc = new(Configuration)\n\n\tif readError != nil {\n\t\tc := defaultConfig()\n\t\treturn c, saveConfiguration(c)\n\t}\n\n\tdata, readError := ioutil.ReadFile(file)\n\n\tif readError != nil {\n\t\tc := defaultConfig()\n\t\treturn c, saveConfiguration(c)\n\t}\n\n\tparseError = json.Unmarshal(data, c)\n\tif parseError != nil {\n\t\treturn\n\t}\n\n\tif c.ConfigVersion < currentConfigVersion {\n\t\tc = defaultConfig()\n\t\treturn c, nil\n\t}\n\n\treturn\n}\n\nfunc saveConfiguration(config *Configuration) (err error) {\n\tbytes, err := json.Marshal(config)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfile, err := ConfigFile()\n\n\tif err != nil {\n\t\treturn\n\t}\n\terr = ioutil.WriteFile(file, bytes, filePermissions)\n\n\treturn\n}\n<commit_msg>config file should not be world readable<commit_after>package configuration\n\nimport (\n\t\"cf\"\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n)\n\nconst (\n\tfilePermissions      = 0600\n\tdirPermissions       = 0700\n\tcurrentConfigVersion = 2\n)\n\nvar singleton *Configuration\n\ntype ConfigurationRepository interface {\n\tGet() (config *Configuration, err error)\n\tDelete()\n\tSave() (err error)\n\tClearTokens() (err error)\n\tClearSession() (err error)\n\tSetOrganization(org cf.OrganizationFields) (err error)\n\tSetSpace(space cf.SpaceFields) (err error)\n}\n\ntype ConfigurationDiskRepository struct{}\n\nfunc NewConfigurationDiskRepository() (repo ConfigurationDiskRepository) {\n\treturn ConfigurationDiskRepository{}\n}\n\nfunc (repo ConfigurationDiskRepository) SetOrganization(org cf.OrganizationFields) (err error) {\n\tconfig, err := repo.Get()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconfig.OrganizationFields = org\n\tconfig.SpaceFields = cf.SpaceFields{}\n\n\treturn saveConfiguration(config)\n}\n\nfunc (repo ConfigurationDiskRepository) SetSpace(space cf.SpaceFields) (err error) {\n\tconfig, err := repo.Get()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconfig.SpaceFields = space\n\n\treturn saveConfiguration(config)\n}\n\nfunc (repo ConfigurationDiskRepository) Get() (c *Configuration, err error) {\n\tif singleton == nil {\n\t\tsingleton, err = repo.load()\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\treturn singleton, nil\n}\n\nfunc (repo ConfigurationDiskRepository) Delete() {\n\tfile, err := ConfigFile()\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tos.Remove(file)\n\tsingleton = nil\n}\n\nfunc (repo ConfigurationDiskRepository) Save() (err error) {\n\tc, err := repo.Get()\n\tif err != nil {\n\t\treturn\n\t}\n\treturn saveConfiguration(c)\n}\n\nfunc (repo ConfigurationDiskRepository) ClearTokens() (err error) {\n\tc, err := repo.Get()\n\tif err != nil {\n\t\treturn\n\t}\n\tc.AccessToken = \"\"\n\tc.RefreshToken = \"\"\n\treturn\n}\n\nfunc (repo ConfigurationDiskRepository) ClearSession() (err error) {\n\terr = repo.ClearTokens()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tc, err := repo.Get()\n\tif err != nil {\n\t\treturn\n\t}\n\tc.OrganizationFields = cf.OrganizationFields{}\n\tc.SpaceFields = cf.SpaceFields{}\n\n\treturn saveConfiguration(c)\n}\n\n\/\/ Keep this one public for configtest\/configuration.go\nfunc ConfigFile() (file string, err error) {\n\n\tconfigDir := filepath.Join(userHomeDir(), \".cf\")\n\n\terr = os.MkdirAll(configDir, dirPermissions)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfile = filepath.Join(configDir, \"config.json\")\n\treturn\n}\n\n\/\/ See: http:\/\/stackoverflow.com\/questions\/7922270\/obtain-users-home-directory\n\/\/ we can't cross compile using cgo and use user.Current()\nfunc userHomeDir() string {\n\tif runtime.GOOS == \"windows\" {\n\t\thome := os.Getenv(\"HOMEDRIVE\") + os.Getenv(\"HOMEPATH\")\n\t\tif home == \"\" {\n\t\t\thome = os.Getenv(\"USERPROFILE\")\n\t\t}\n\t\treturn home\n\t}\n\n\treturn os.Getenv(\"HOME\")\n}\n\nfunc defaultConfig() (c *Configuration) {\n\tc = new(Configuration)\n\tc.Target = \"\"\n\tc.ApiVersion = \"\"\n\tc.AuthorizationEndpoint = \"\"\n\tc.ApplicationStartTimeout = 30 \/\/ seconds\n\tc.ConfigVersion = currentConfigVersion\n\n\treturn\n}\n\nfunc (repo ConfigurationDiskRepository) load() (c *Configuration, parseError error) {\n\tfile, readError := ConfigFile()\n\tc = new(Configuration)\n\n\tif readError != nil {\n\t\tc := defaultConfig()\n\t\treturn c, saveConfiguration(c)\n\t}\n\n\tdata, readError := ioutil.ReadFile(file)\n\n\tif readError != nil {\n\t\tc := defaultConfig()\n\t\treturn c, saveConfiguration(c)\n\t}\n\n\tparseError = json.Unmarshal(data, c)\n\tif parseError != nil {\n\t\treturn\n\t}\n\n\tif c.ConfigVersion < currentConfigVersion {\n\t\tc = defaultConfig()\n\t\treturn c, nil\n\t}\n\n\treturn\n}\n\nfunc saveConfiguration(config *Configuration) (err error) {\n\tbytes, err := json.Marshal(config)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfile, err := ConfigFile()\n\n\tif err != nil {\n\t\treturn\n\t}\n\terr = ioutil.WriteFile(file, bytes, filePermissions)\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package cancel\n\nimport \"context\"\n\n\/\/ Canceller is a simple wrapper for a cancellable context which makes the associated context.CancelFunc more easily\n\/\/ accessible.\ntype Canceller struct {\n\tcontext.Context\n\tCancel context.CancelFunc\n}\n\n\/\/ New returns a new canceller with the parent context.\nfunc New(ctx context.Context) *Canceller {\n\tctx, cancel := context.WithCancel(ctx)\n\treturn &Canceller{\n\t\tContext: ctx,\n\t\tCancel:  cancel,\n\t}\n}\n<commit_msg>shared\/cancel: Use multiline import syntax.<commit_after>package cancel\n\nimport (\n\t\"context\"\n)\n\n\/\/ Canceller is a simple wrapper for a cancellable context which makes the associated context.CancelFunc more easily\n\/\/ accessible.\ntype Canceller struct {\n\tcontext.Context\n\tCancel context.CancelFunc\n}\n\n\/\/ New returns a new canceller with the parent context.\nfunc New(ctx context.Context) *Canceller {\n\tctx, cancel := context.WithCancel(ctx)\n\treturn &Canceller{\n\t\tContext: ctx,\n\t\tCancel:  cancel,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package levant\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\tnomad \"github.com\/hashicorp\/nomad\/api\"\n\tnomadStructs \"github.com\/hashicorp\/nomad\/nomad\/structs\"\n\t\"github.com\/jrasell\/levant\/logging\"\n)\n\ntype nomadClient struct {\n\tnomad *nomad.Client\n}\n\n\/\/ NomadClient is an interface to the Nomad API and deployment functions.\ntype NomadClient interface {\n\t\/\/ Deploy triggers a register of the job resulting in a Nomad deployment which\n\t\/\/ is monitored to determine the eventual state.\n\tDeploy(*nomad.Job, int, bool) bool\n}\n\n\/\/ NewNomadClient is used to create a new client to interact with Nomad.\nfunc NewNomadClient(addr string) (NomadClient, error) {\n\tconfig := nomad.DefaultConfig()\n\n\tif addr != \"\" {\n\t\tconfig.Address = addr\n\t}\n\n\tc, err := nomad.NewClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &nomadClient{nomad: c}, nil\n}\n\n\/\/ Deploy triggers a register of the job resulting in a Nomad deployment which\n\/\/ is monitored to determine the eventual state.\nfunc (c *nomadClient) Deploy(job *nomad.Job, autoPromote int, forceCount bool) (success bool) {\n\n\t\/\/ Validate the job to check it is syntactically correct.\n\tif _, _, err := c.nomad.Jobs().Validate(job, nil); err != nil {\n\t\tlogging.Error(\"levant\/deploy: job validation failed: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ If job.Type isn't set we can't continue\n\tif job.Type == nil {\n\t\tlogging.Error(\"levant\/deploy: Nomad job `type` is not set, should be set to `service`\")\n\t\treturn\n\t}\n\n\tif !forceCount {\n\t\tlogging.Debug(\"levant\/deploy: running dynamic job count updater for job %s\", *job.Name)\n\t\tif err := c.dynamicGroupCountUpdater(job); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ Check that the job has at least 1 TaskGroup with count > 0 (GH-16)\n\tTGCount := 0\n\tfor _, group := range job.TaskGroups {\n\t\tTGCount += *group.Count\n\t}\n\tif TGCount == 0 {\n\t\tlogging.Error(\"levant\/deploy: all TaskGroups have a count of 0, nothing to do\")\n\t\treturn\n\t}\n\n\tlogging.Info(\"levant\/deploy: triggering a deployment of job %s\", *job.Name)\n\n\teval, _, err := c.nomad.Jobs().Register(job, nil)\n\tif err != nil {\n\t\tlogging.Error(\"levant\/deploy: unable to register job %s with Nomad: %v\", *job.Name, err)\n\t\treturn\n\t}\n\n\t\/\/ GH-50: batch job types do not return an evaluation upon registration.\n\tif eval == nil && *job.Type == nomadStructs.JobTypeBatch {\n\t\tlogging.Debug(\"levant\/deploy: job type %s does not create evaluations\", nomadStructs.JobTypeBatch)\n\t\treturn true\n\t}\n\n\t\/\/ Trigger the evaluationInspector to identify any potential errors in the\n\t\/\/ Nomad evaluation run. As far as I can tell from testing; a single alloc\n\t\/\/ failure in an evaluation means no allocs will be placed so we exit here.\n\terr = c.evaluationInspector(&eval.EvalID)\n\tif err != nil {\n\t\tlogging.Error(\"levant\/deploy: %v\", err)\n\t\treturn\n\t}\n\n\tswitch *job.Type {\n\tcase nomadStructs.JobTypeService:\n\t\tlogging.Info(\"levant\/deploy: beginning deployment watcher for job %s\", *job.Name)\n\n\t\t\/\/ Get the deploymentID from the evaluationID so that we can watch the\n\t\t\/\/ deployment for end status.\n\t\tdepID, err := c.getDeploymentID(eval.EvalID)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"levant\/deploy: unable to get info of evaluation %s: %v\", eval.EvalID, err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Get the success of the deployment.\n\t\tsuccess = c.deploymentWatcher(depID, autoPromote)\n\n\t\t\/\/ If the deployment has not been successful; check whether the job is\n\t\t\/\/ configured to auto-revert so that this can be tracked.\n\t\tif !success {\n\t\t\tdep, _, err := c.nomad.Deployments().Info(depID, nil)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"levant\/deploy: unable to query deployment %s for auto-revert check: %v\",\n\t\t\t\t\tdep.ID, err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tc.checkAutoRevert(dep)\n\t\t}\n\n\tdefault:\n\t\tlogging.Debug(\"levant\/deploy: job type %s does not support Nomad deployment model\", *job.Type)\n\t\tsuccess = true\n\t}\n\n\treturn\n}\n\nfunc (c *nomadClient) evaluationInspector(evalID *string) error {\n\n\tfor {\n\t\tevalInfo, _, err := c.nomad.Evaluations().Info(*evalID, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch evalInfo.Status {\n\t\tcase nomadStructs.EvalStatusComplete, nomadStructs.EvalStatusFailed, nomadStructs.EvalStatusCancelled:\n\t\t\tif len(evalInfo.FailedTGAllocs) == 0 {\n\t\t\t\tlogging.Info(\"levant\/deploy: evaluation %s finished successfully\", *evalID)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tvar class, dimension []string\n\n\t\t\tfor group, metrics := range evalInfo.FailedTGAllocs {\n\n\t\t\t\t\/\/ Iterate the classes and dimensions to generate lists of each failure.\n\t\t\t\tfor c := range metrics.ClassExhausted {\n\t\t\t\t\tclass = append(class, c)\n\t\t\t\t}\n\t\t\t\tfor d := range metrics.DimensionExhausted {\n\t\t\t\t\tdimension = append(dimension, d)\n\t\t\t\t}\n\n\t\t\t\tlogging.Error(\"levant\/deploy: task group %s failed to place %v allocs, failed on %v and exhausted %v\",\n\t\t\t\t\tgroup, metrics.CoalescedFailures+1, class, dimension)\n\t\t\t}\n\n\t\t\treturn fmt.Errorf(\"evaluation %v finished with status %s but failed to place allocations\",\n\t\t\t\t*evalID, evalInfo.Status)\n\n\t\tdefault:\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\nfunc (c *nomadClient) deploymentWatcher(depID string, autoPromote int) (success bool) {\n\n\tvar canaryChan chan interface{}\n\tdeploymentChan := make(chan interface{})\n\n\tt := time.Now()\n\twt := time.Duration(5 * time.Second)\n\n\t\/\/ Setup the canaryChan and launch the autoPromote go routine if autoPromote\n\t\/\/ has been enabled.\n\tif autoPromote > 0 {\n\t\tcanaryChan = make(chan interface{})\n\t\tgo c.canaryAutoPromote(depID, autoPromote, canaryChan, deploymentChan)\n\t}\n\n\tq := &nomad.QueryOptions{WaitIndex: 1, AllowStale: true, WaitTime: wt}\n\n\tfor {\n\n\t\tdep, meta, err := c.nomad.Deployments().Info(depID, q)\n\t\tlogging.Debug(\"levant\/deploy: deployment %v running for %.2fs\", depID, time.Since(t).Seconds())\n\n\t\t\/\/ Listen for the deploymentChan closing which indicates Levant should exit\n\t\t\/\/ the deployment watcher.\n\t\tselect {\n\t\tcase <-deploymentChan:\n\t\t\treturn false\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlogging.Error(\"levant\/deploy: unable to get info of deployment %s: %v\", depID, err)\n\t\t\treturn\n\t\t}\n\n\t\tif meta.LastIndex <= q.WaitIndex {\n\t\t\tcontinue\n\t\t}\n\n\t\tq.WaitIndex = meta.LastIndex\n\n\t\tcont, err := c.checkDeploymentStatus(dep, canaryChan)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\n\t\tif cont {\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn true\n\t\t}\n\t}\n}\n\nfunc (c *nomadClient) checkDeploymentStatus(dep *nomad.Deployment, shutdownChan chan interface{}) (bool, error) {\n\n\tswitch dep.Status {\n\tcase nomadStructs.DeploymentStatusSuccessful:\n\t\tlogging.Info(\"levant\/deploy: deployment %v has completed successfully\", dep.ID)\n\t\treturn false, nil\n\tcase nomadStructs.DeploymentStatusRunning:\n\t\treturn true, nil\n\tdefault:\n\t\tif shutdownChan != nil {\n\t\t\tlogging.Debug(\"levant\/deploy: deployment %v meaning canary auto promote will shutdown\", dep.Status)\n\t\t\tclose(shutdownChan)\n\t\t}\n\n\t\tlogging.Error(\"levant\/deploy: deployment %v has status %s\", dep.ID, dep.Status)\n\n\t\t\/\/ Launch the failure inspector.\n\t\tc.checkFailedDeployment(&dep.ID)\n\n\t\treturn false, fmt.Errorf(\"deployment failed\")\n\t}\n}\n\n\/\/ canaryAutoPromote handles Levant's canary-auto-promote functionality.\nfunc (c *nomadClient) canaryAutoPromote(depID string, waitTime int, shutdownChan, deploymentChan chan interface{}) {\n\n\t\/\/ Setup the AutoPromote timer.\n\tautoPromote := time.After(time.Duration(waitTime) * time.Second)\n\n\tfor {\n\t\tselect {\n\t\tcase <-autoPromote:\n\t\t\tlogging.Info(\"levant\/deploy: auto-promote period %vs has been reached for deployment %s\",\n\t\t\t\twaitTime, depID)\n\n\t\t\t\/\/ Check the deployment is healthy before promoting.\n\t\t\tif healthy := c.checkCanaryDeploymentHealth(depID); !healthy {\n\t\t\t\tlogging.Error(\"levant\/deploy: the canary deployment %s has unhealthy allocations, unable to promote\", depID)\n\t\t\t\tclose(deploymentChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlogging.Info(\"levant\/deploy: triggering auto promote of deployment %s\", depID)\n\n\t\t\t\/\/ Promote the deployment.\n\t\t\t_, _, err := c.nomad.Deployments().PromoteAll(depID, nil)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"levant\/deploy: unable to promote deployment %s: %v\", depID, err)\n\t\t\t\tclose(deploymentChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase <-shutdownChan:\n\t\t\tlogging.Info(\"levant\/deploy: canary auto promote has been shutdown\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ checkCanaryDeploymentHealth is used to check the health status of each\n\/\/ task-group within a canary deployment.\nfunc (c *nomadClient) checkCanaryDeploymentHealth(depID string) (healthy bool) {\n\n\tvar unhealthy int\n\n\tdep, _, err := c.nomad.Deployments().Info(depID, &nomad.QueryOptions{AllowStale: true})\n\tif err != nil {\n\t\tlogging.Error(\"levant\/deploy: unable to query deployment %s for health: %v\", depID, err)\n\t\treturn\n\t}\n\n\t\/\/ Itertate each task in the deployment to determine is health status. If an\n\t\/\/ unhealthy task is found, incrament the unhealthy counter.\n\tfor taskName, taskInfo := range dep.TaskGroups {\n\t\tif taskInfo.DesiredCanaries != taskInfo.HealthyAllocs {\n\t\t\tlogging.Error(\"levant\/deploy: task %s has unhealthy allocations in deployment %s\", taskName, depID)\n\t\t\tunhealthy++\n\t\t}\n\t}\n\n\t\/\/ If zero unhealthy tasks were found, continue with the auto promotion.\n\tif unhealthy == 0 {\n\t\tlogging.Debug(\"levant\/deploy: deployment %s has 0 unhealthy allocations\", depID)\n\t\thealthy = true\n\t}\n\n\treturn\n}\n\n\/\/ getDeploymentID finds the Nomad deploymentID associated to a Nomad\n\/\/ evaluationID. This is only needed as sometimes Nomad initially returns eval\n\/\/ info with an empty deploymentID; and a retry is required in order to get the\n\/\/ updated response from Nomad.\nfunc (c *nomadClient) getDeploymentID(evalID string) (depID string, err error) {\n\n\tvar evalInfo *nomad.Evaluation\n\n\tfor {\n\t\tif evalInfo, _, err = c.nomad.Evaluations().Info(evalID, nil); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif evalInfo.DeploymentID == \"\" {\n\t\t\tlogging.Debug(\"levant\/deploy: Nomad returned an empty deployment for evaluation %v; retrying\", evalID)\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t\tcontinue\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn evalInfo.DeploymentID, nil\n}\n\n\/\/ dynamicGroupCountUpdater takes the templated and rendered job and updates the\n\/\/ group counts based on the currently deployed job; if its running.\nfunc (c *nomadClient) dynamicGroupCountUpdater(job *nomad.Job) error {\n\n\t\/\/ Gather information about the current state, if any, of the job on the\n\t\/\/ Nomad cluster.\n\trJob, _, err := c.nomad.Jobs().Info(*job.Name, &nomad.QueryOptions{})\n\n\t\/\/ This is a hack due to GH-1849; we check the error string for 404 which\n\t\/\/ indicates the job is not running, not that there was an error in the API\n\t\/\/ call.\n\tif err != nil && strings.Contains(err.Error(), \"404\") {\n\t\tlogging.Info(\"levant\/deploy: job %s not running, using template file group counts\", *job.Name)\n\t\treturn nil\n\t} else if err != nil {\n\t\tlogging.Error(\"levant\/deploy: unable to perform job evaluation: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Iterate the templated job and the Nomad returned job and update group count\n\t\/\/ based on matches.\n\tfor _, rGroup := range rJob.TaskGroups {\n\t\tfor _, group := range job.TaskGroups {\n\t\t\tif *rGroup.Name == *group.Name {\n\t\t\t\tlogging.Info(\"levant\/deploy: using dynamic count %v for job %s and group %s\",\n\t\t\t\t\t*rGroup.Count, *job.Name, *group.Name)\n\t\t\t\tgroup.Count = rGroup.Count\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Fix issue where system jobs cause panic.<commit_after>package levant\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\tnomad \"github.com\/hashicorp\/nomad\/api\"\n\tnomadStructs \"github.com\/hashicorp\/nomad\/nomad\/structs\"\n\t\"github.com\/jrasell\/levant\/logging\"\n)\n\ntype nomadClient struct {\n\tnomad *nomad.Client\n}\n\n\/\/ NomadClient is an interface to the Nomad API and deployment functions.\ntype NomadClient interface {\n\t\/\/ Deploy triggers a register of the job resulting in a Nomad deployment which\n\t\/\/ is monitored to determine the eventual state.\n\tDeploy(*nomad.Job, int, bool) bool\n}\n\n\/\/ NewNomadClient is used to create a new client to interact with Nomad.\nfunc NewNomadClient(addr string) (NomadClient, error) {\n\tconfig := nomad.DefaultConfig()\n\n\tif addr != \"\" {\n\t\tconfig.Address = addr\n\t}\n\n\tc, err := nomad.NewClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &nomadClient{nomad: c}, nil\n}\n\n\/\/ Deploy triggers a register of the job resulting in a Nomad deployment which\n\/\/ is monitored to determine the eventual state.\nfunc (c *nomadClient) Deploy(job *nomad.Job, autoPromote int, forceCount bool) (success bool) {\n\n\t\/\/ Validate the job to check it is syntactically correct.\n\tif _, _, err := c.nomad.Jobs().Validate(job, nil); err != nil {\n\t\tlogging.Error(\"levant\/deploy: job validation failed: %v\", err)\n\t\treturn\n\t}\n\n\t\/\/ If job.Type isn't set we can't continue\n\tif job.Type == nil {\n\t\tlogging.Error(\"levant\/deploy: Nomad job `type` is not set, should be set to `service`\")\n\t\treturn\n\t}\n\n\tif !forceCount {\n\t\tlogging.Debug(\"levant\/deploy: running dynamic job count updater for job %s\", *job.Name)\n\t\tif err := c.dynamicGroupCountUpdater(job); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\t\/\/ Check that the job has at least 1 TaskGroup with count > 0 (GH-16) if the\n\t\/\/ job is not a System job. Systems jobs do not define counts so cannot be\n\t\/\/ checked.\n\tif *job.Type != nomadStructs.JobTypeSystem {\n\t\ttgCount := 0\n\t\tfor _, group := range job.TaskGroups {\n\t\t\ttgCount += *group.Count\n\t\t}\n\t\tif tgCount == 0 {\n\t\t\tlogging.Error(\"levant\/deploy: all TaskGroups have a count of 0, nothing to do\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tlogging.Info(\"levant\/deploy: triggering a deployment of job %s\", *job.Name)\n\n\teval, _, err := c.nomad.Jobs().Register(job, nil)\n\tif err != nil {\n\t\tlogging.Error(\"levant\/deploy: unable to register job %s with Nomad: %v\", *job.Name, err)\n\t\treturn\n\t}\n\n\t\/\/ GH-50: batch job types do not return an evaluation upon registration.\n\tif eval == nil && *job.Type == nomadStructs.JobTypeBatch {\n\t\tlogging.Debug(\"levant\/deploy: job type %s does not create evaluations\", nomadStructs.JobTypeBatch)\n\t\treturn true\n\t}\n\n\t\/\/ Trigger the evaluationInspector to identify any potential errors in the\n\t\/\/ Nomad evaluation run. As far as I can tell from testing; a single alloc\n\t\/\/ failure in an evaluation means no allocs will be placed so we exit here.\n\terr = c.evaluationInspector(&eval.EvalID)\n\tif err != nil {\n\t\tlogging.Error(\"levant\/deploy: %v\", err)\n\t\treturn\n\t}\n\n\tswitch *job.Type {\n\tcase nomadStructs.JobTypeService:\n\t\tlogging.Info(\"levant\/deploy: beginning deployment watcher for job %s\", *job.Name)\n\n\t\t\/\/ Get the deploymentID from the evaluationID so that we can watch the\n\t\t\/\/ deployment for end status.\n\t\tdepID, err := c.getDeploymentID(eval.EvalID)\n\t\tif err != nil {\n\t\t\tlogging.Error(\"levant\/deploy: unable to get info of evaluation %s: %v\", eval.EvalID, err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Get the success of the deployment.\n\t\tsuccess = c.deploymentWatcher(depID, autoPromote)\n\n\t\t\/\/ If the deployment has not been successful; check whether the job is\n\t\t\/\/ configured to auto-revert so that this can be tracked.\n\t\tif !success {\n\t\t\tdep, _, err := c.nomad.Deployments().Info(depID, nil)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"levant\/deploy: unable to query deployment %s for auto-revert check: %v\",\n\t\t\t\t\tdep.ID, err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tc.checkAutoRevert(dep)\n\t\t}\n\n\tdefault:\n\t\tlogging.Debug(\"levant\/deploy: job type %s does not support Nomad deployment model\", *job.Type)\n\t\tsuccess = true\n\t}\n\n\treturn\n}\n\nfunc (c *nomadClient) evaluationInspector(evalID *string) error {\n\n\tfor {\n\t\tevalInfo, _, err := c.nomad.Evaluations().Info(*evalID, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tswitch evalInfo.Status {\n\t\tcase nomadStructs.EvalStatusComplete, nomadStructs.EvalStatusFailed, nomadStructs.EvalStatusCancelled:\n\t\t\tif len(evalInfo.FailedTGAllocs) == 0 {\n\t\t\t\tlogging.Info(\"levant\/deploy: evaluation %s finished successfully\", *evalID)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tvar class, dimension []string\n\n\t\t\tfor group, metrics := range evalInfo.FailedTGAllocs {\n\n\t\t\t\t\/\/ Iterate the classes and dimensions to generate lists of each failure.\n\t\t\t\tfor c := range metrics.ClassExhausted {\n\t\t\t\t\tclass = append(class, c)\n\t\t\t\t}\n\t\t\t\tfor d := range metrics.DimensionExhausted {\n\t\t\t\t\tdimension = append(dimension, d)\n\t\t\t\t}\n\n\t\t\t\tlogging.Error(\"levant\/deploy: task group %s failed to place %v allocs, failed on %v and exhausted %v\",\n\t\t\t\t\tgroup, metrics.CoalescedFailures+1, class, dimension)\n\t\t\t}\n\n\t\t\treturn fmt.Errorf(\"evaluation %v finished with status %s but failed to place allocations\",\n\t\t\t\t*evalID, evalInfo.Status)\n\n\t\tdefault:\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\nfunc (c *nomadClient) deploymentWatcher(depID string, autoPromote int) (success bool) {\n\n\tvar canaryChan chan interface{}\n\tdeploymentChan := make(chan interface{})\n\n\tt := time.Now()\n\twt := time.Duration(5 * time.Second)\n\n\t\/\/ Setup the canaryChan and launch the autoPromote go routine if autoPromote\n\t\/\/ has been enabled.\n\tif autoPromote > 0 {\n\t\tcanaryChan = make(chan interface{})\n\t\tgo c.canaryAutoPromote(depID, autoPromote, canaryChan, deploymentChan)\n\t}\n\n\tq := &nomad.QueryOptions{WaitIndex: 1, AllowStale: true, WaitTime: wt}\n\n\tfor {\n\n\t\tdep, meta, err := c.nomad.Deployments().Info(depID, q)\n\t\tlogging.Debug(\"levant\/deploy: deployment %v running for %.2fs\", depID, time.Since(t).Seconds())\n\n\t\t\/\/ Listen for the deploymentChan closing which indicates Levant should exit\n\t\t\/\/ the deployment watcher.\n\t\tselect {\n\t\tcase <-deploymentChan:\n\t\t\treturn false\n\t\tdefault:\n\t\t\tbreak\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlogging.Error(\"levant\/deploy: unable to get info of deployment %s: %v\", depID, err)\n\t\t\treturn\n\t\t}\n\n\t\tif meta.LastIndex <= q.WaitIndex {\n\t\t\tcontinue\n\t\t}\n\n\t\tq.WaitIndex = meta.LastIndex\n\n\t\tcont, err := c.checkDeploymentStatus(dep, canaryChan)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\n\t\tif cont {\n\t\t\tcontinue\n\t\t} else {\n\t\t\treturn true\n\t\t}\n\t}\n}\n\nfunc (c *nomadClient) checkDeploymentStatus(dep *nomad.Deployment, shutdownChan chan interface{}) (bool, error) {\n\n\tswitch dep.Status {\n\tcase nomadStructs.DeploymentStatusSuccessful:\n\t\tlogging.Info(\"levant\/deploy: deployment %v has completed successfully\", dep.ID)\n\t\treturn false, nil\n\tcase nomadStructs.DeploymentStatusRunning:\n\t\treturn true, nil\n\tdefault:\n\t\tif shutdownChan != nil {\n\t\t\tlogging.Debug(\"levant\/deploy: deployment %v meaning canary auto promote will shutdown\", dep.Status)\n\t\t\tclose(shutdownChan)\n\t\t}\n\n\t\tlogging.Error(\"levant\/deploy: deployment %v has status %s\", dep.ID, dep.Status)\n\n\t\t\/\/ Launch the failure inspector.\n\t\tc.checkFailedDeployment(&dep.ID)\n\n\t\treturn false, fmt.Errorf(\"deployment failed\")\n\t}\n}\n\n\/\/ canaryAutoPromote handles Levant's canary-auto-promote functionality.\nfunc (c *nomadClient) canaryAutoPromote(depID string, waitTime int, shutdownChan, deploymentChan chan interface{}) {\n\n\t\/\/ Setup the AutoPromote timer.\n\tautoPromote := time.After(time.Duration(waitTime) * time.Second)\n\n\tfor {\n\t\tselect {\n\t\tcase <-autoPromote:\n\t\t\tlogging.Info(\"levant\/deploy: auto-promote period %vs has been reached for deployment %s\",\n\t\t\t\twaitTime, depID)\n\n\t\t\t\/\/ Check the deployment is healthy before promoting.\n\t\t\tif healthy := c.checkCanaryDeploymentHealth(depID); !healthy {\n\t\t\t\tlogging.Error(\"levant\/deploy: the canary deployment %s has unhealthy allocations, unable to promote\", depID)\n\t\t\t\tclose(deploymentChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlogging.Info(\"levant\/deploy: triggering auto promote of deployment %s\", depID)\n\n\t\t\t\/\/ Promote the deployment.\n\t\t\t_, _, err := c.nomad.Deployments().PromoteAll(depID, nil)\n\t\t\tif err != nil {\n\t\t\t\tlogging.Error(\"levant\/deploy: unable to promote deployment %s: %v\", depID, err)\n\t\t\t\tclose(deploymentChan)\n\t\t\t\treturn\n\t\t\t}\n\n\t\tcase <-shutdownChan:\n\t\t\tlogging.Info(\"levant\/deploy: canary auto promote has been shutdown\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ checkCanaryDeploymentHealth is used to check the health status of each\n\/\/ task-group within a canary deployment.\nfunc (c *nomadClient) checkCanaryDeploymentHealth(depID string) (healthy bool) {\n\n\tvar unhealthy int\n\n\tdep, _, err := c.nomad.Deployments().Info(depID, &nomad.QueryOptions{AllowStale: true})\n\tif err != nil {\n\t\tlogging.Error(\"levant\/deploy: unable to query deployment %s for health: %v\", depID, err)\n\t\treturn\n\t}\n\n\t\/\/ Itertate each task in the deployment to determine is health status. If an\n\t\/\/ unhealthy task is found, incrament the unhealthy counter.\n\tfor taskName, taskInfo := range dep.TaskGroups {\n\t\tif taskInfo.DesiredCanaries != taskInfo.HealthyAllocs {\n\t\t\tlogging.Error(\"levant\/deploy: task %s has unhealthy allocations in deployment %s\", taskName, depID)\n\t\t\tunhealthy++\n\t\t}\n\t}\n\n\t\/\/ If zero unhealthy tasks were found, continue with the auto promotion.\n\tif unhealthy == 0 {\n\t\tlogging.Debug(\"levant\/deploy: deployment %s has 0 unhealthy allocations\", depID)\n\t\thealthy = true\n\t}\n\n\treturn\n}\n\n\/\/ getDeploymentID finds the Nomad deploymentID associated to a Nomad\n\/\/ evaluationID. This is only needed as sometimes Nomad initially returns eval\n\/\/ info with an empty deploymentID; and a retry is required in order to get the\n\/\/ updated response from Nomad.\nfunc (c *nomadClient) getDeploymentID(evalID string) (depID string, err error) {\n\n\tvar evalInfo *nomad.Evaluation\n\n\tfor {\n\t\tif evalInfo, _, err = c.nomad.Evaluations().Info(evalID, nil); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif evalInfo.DeploymentID == \"\" {\n\t\t\tlogging.Debug(\"levant\/deploy: Nomad returned an empty deployment for evaluation %v; retrying\", evalID)\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t\tcontinue\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn evalInfo.DeploymentID, nil\n}\n\n\/\/ dynamicGroupCountUpdater takes the templated and rendered job and updates the\n\/\/ group counts based on the currently deployed job; if its running.\nfunc (c *nomadClient) dynamicGroupCountUpdater(job *nomad.Job) error {\n\n\t\/\/ Gather information about the current state, if any, of the job on the\n\t\/\/ Nomad cluster.\n\trJob, _, err := c.nomad.Jobs().Info(*job.Name, &nomad.QueryOptions{})\n\n\t\/\/ This is a hack due to GH-1849; we check the error string for 404 which\n\t\/\/ indicates the job is not running, not that there was an error in the API\n\t\/\/ call.\n\tif err != nil && strings.Contains(err.Error(), \"404\") {\n\t\tlogging.Info(\"levant\/deploy: job %s not running, using template file group counts\", *job.Name)\n\t\treturn nil\n\t} else if err != nil {\n\t\tlogging.Error(\"levant\/deploy: unable to perform job evaluation: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Iterate the templated job and the Nomad returned job and update group count\n\t\/\/ based on matches.\n\tfor _, rGroup := range rJob.TaskGroups {\n\t\tfor _, group := range job.TaskGroups {\n\t\t\tif *rGroup.Name == *group.Name {\n\t\t\t\tlogging.Info(\"levant\/deploy: using dynamic count %v for job %s and group %s\",\n\t\t\t\t\t*rGroup.Count, *job.Name, *group.Name)\n\t\t\t\tgroup.Count = rGroup.Count\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage logopt\n\nimport (\n\t\"internal\/testenv\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\nconst srcCode = `package x\ntype pair struct {a,b int}\nfunc bar(y *pair) *int {\n\treturn &y.b\n}\nvar a []int\nfunc foo(w, z *pair) *int {\n\tif *bar(w) > 0 {\n\t\treturn bar(z)\n\t}\n\tif a[1] > 0 {\n\t\ta = a[:2]\n\t}\n\treturn &a[0]\n}\n\n\/\/ address taking prevents closure inlining\nfunc n() int {\n\tfoo := func() int { return 1 }\n\tbar := &foo\n\tx := (*bar)() + foo()\n\treturn x\n}\n`\n\nfunc want(t *testing.T, out string, desired string) {\n\t\/\/ On Windows, Unicode escapes in the JSON output end up \"normalized\" elsewhere to \/u....,\n\t\/\/ so \"normalize\" what we're looking for to match that.\n\ts := strings.ReplaceAll(desired, string(os.PathSeparator), \"\/\")\n\tif !strings.Contains(out, s) {\n\t\tt.Errorf(\"did not see phrase %s in \\n%s\", s, out)\n\t}\n}\n\nfunc wantN(t *testing.T, out string, desired string, n int) {\n\tif strings.Count(out, desired) != n {\n\t\tt.Errorf(\"expected exactly %d occurences of %s in \\n%s\", n, desired, out)\n\t}\n}\n\nfunc TestPathStuff(t *testing.T) {\n\tsep := string(filepath.Separator)\n\tif path, whine := parseLogPath(\"file:\/\/\/c:foo\"); path != \"c:foo\" || whine != \"\" { \/\/ good path\n\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t}\n\tif path, whine := parseLogPath(\"file:\/\/\/foo\"); path != sep+\"foo\" || whine != \"\" { \/\/ good path\n\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t}\n\tif path, whine := parseLogPath(\"foo\"); path != \"\" || whine == \"\" { \/\/ BAD path\n\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t}\n\tif sep == \"\\\\\" { \/\/ On WINDOWS ONLY\n\t\tif path, whine := parseLogPath(\"C:\/foo\"); path != \"C:\\\\foo\" || whine != \"\" { \/\/ good path\n\t\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t\t}\n\t\tif path, whine := parseLogPath(\"c:foo\"); path != \"\" || whine == \"\" { \/\/ BAD path\n\t\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t\t}\n\t\tif path, whine := parseLogPath(\"\/foo\"); path != \"\" || whine == \"\" { \/\/ BAD path\n\t\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t\t}\n\t} else { \/\/ ON UNIX ONLY\n\t\tif path, whine := parseLogPath(\"\/foo\"); path != sep+\"foo\" || whine != \"\" { \/\/ good path\n\t\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t\t}\n\t}\n}\n\nfunc TestLogOpt(t *testing.T) {\n\tt.Parallel()\n\n\ttestenv.MustHaveGoBuild(t)\n\n\tdir, err := ioutil.TempDir(\"\", \"TestLogOpt\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\n\tdir = fixSlash(dir) \/\/ Normalize the directory name as much as possible, for Windows testing\n\tsrc := filepath.Join(dir, \"file.go\")\n\tif err := ioutil.WriteFile(src, []byte(srcCode), 0644); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\toutfile := filepath.Join(dir, \"file.o\")\n\n\tt.Run(\"JSON_fails\", func(t *testing.T) {\n\t\t\/\/ Test malformed flag\n\t\tout, err := testLogOpt(t, \"-json=foo\", src, outfile)\n\t\tif err == nil {\n\t\t\tt.Error(\"-json=foo succeeded unexpectedly\")\n\t\t}\n\t\twant(t, out, \"option should be\")\n\t\twant(t, out, \"number\")\n\n\t\t\/\/ Test a version number that is currently unsupported (and should remain unsupported for a while)\n\t\tout, err = testLogOpt(t, \"-json=9,foo\", src, outfile)\n\t\tif err == nil {\n\t\t\tt.Error(\"-json=0,foo succeeded unexpectedly\")\n\t\t}\n\t\twant(t, out, \"version must be\")\n\n\t})\n\n\t\/\/ replace d (dir)  with t (\"tmpdir\") and convert path separators to '\/'\n\tnormalize := func(out []byte, d, t string) string {\n\t\ts := string(out)\n\t\ts = strings.ReplaceAll(s, d, t)\n\t\ts = strings.ReplaceAll(s, string(os.PathSeparator), \"\/\")\n\t\treturn s\n\t}\n\n\t\/\/ Ensure that <128 byte copies are not reported and that 128-byte copies are.\n\t\/\/ Check at both 1 and 8-byte alignments.\n\tt.Run(\"Copy\", func(t *testing.T) {\n\t\tconst copyCode = `package x\nfunc s128a1(x *[128]int8) [128]int8 { \n\treturn *x\n}\nfunc s127a1(x *[127]int8) [127]int8 {\n\treturn *x\n}\nfunc s16a8(x *[16]int64) [16]int64 {\n\treturn *x\n}\nfunc s15a8(x *[15]int64) [15]int64 {\n\treturn *x\n}\n`\n\t\tcopy := filepath.Join(dir, \"copy.go\")\n\t\tif err := ioutil.WriteFile(copy, []byte(copyCode), 0644); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\toutcopy := filepath.Join(dir, \"copy.o\")\n\n\t\t\/\/ On not-amd64, test the host architecture and os\n\t\tarches := []string{runtime.GOARCH}\n\t\tgoos0 := runtime.GOOS\n\t\tif runtime.GOARCH == \"amd64\" { \/\/ Test many things with \"linux\" (wasm will get \"js\")\n\t\t\tarches = []string{\"arm\", \"arm64\", \"386\", \"amd64\", \"mips\", \"mips64\", \"ppc64le\", \"riscv64\", \"s390x\", \"wasm\"}\n\t\t\tgoos0 = \"linux\"\n\t\t}\n\n\t\tfor _, arch := range arches {\n\t\t\tt.Run(arch, func(t *testing.T) {\n\t\t\t\tgoos := goos0\n\t\t\t\tif arch == \"wasm\" {\n\t\t\t\t\tgoos = \"js\"\n\t\t\t\t}\n\t\t\t\t_, err := testCopy(t, dir, arch, goos, copy, outcopy)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Error(\"-json=0,file:\/\/log\/opt should have succeeded\")\n\t\t\t\t}\n\t\t\t\tlogged, err := ioutil.ReadFile(filepath.Join(dir, \"log\", \"opt\", \"x\", \"copy.json\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Error(\"-json=0,file:\/\/log\/opt missing expected log file\")\n\t\t\t\t}\n\t\t\t\tslogged := normalize(logged, string(uriIfy(dir)), string(uriIfy(\"tmpdir\")))\n\t\t\t\tt.Logf(\"%s\", slogged)\n\t\t\t\twant(t, slogged, `{\"range\":{\"start\":{\"line\":3,\"character\":2},\"end\":{\"line\":3,\"character\":2}},\"severity\":3,\"code\":\"copy\",\"source\":\"go compiler\",\"message\":\"128 bytes\"}`)\n\t\t\t\twant(t, slogged, `{\"range\":{\"start\":{\"line\":9,\"character\":2},\"end\":{\"line\":9,\"character\":2}},\"severity\":3,\"code\":\"copy\",\"source\":\"go compiler\",\"message\":\"128 bytes\"}`)\n\t\t\t\twantN(t, slogged, `\"code\":\"copy\"`, 2)\n\t\t\t})\n\t\t}\n\t})\n\n\t\/\/ Some architectures don't fault on nil dereference, so nilchecks are eliminated differently.\n\t\/\/ The N-way copy test also doesn't need to run N-ways N times.\n\tif runtime.GOARCH != \"amd64\" {\n\t\treturn\n\t}\n\n\tt.Run(\"Success\", func(t *testing.T) {\n\t\t\/\/ This test is supposed to succeed\n\n\t\t\/\/ Note 'file:\/\/' is the I-Know-What-I-Am-Doing way of specifying a file, also to deal with corner cases for Windows.\n\t\t_, err := testLogOptDir(t, dir, \"-json=0,file:\/\/log\/opt\", src, outfile)\n\t\tif err != nil {\n\t\t\tt.Error(\"-json=0,file:\/\/log\/opt should have succeeded\")\n\t\t}\n\t\tlogged, err := ioutil.ReadFile(filepath.Join(dir, \"log\", \"opt\", \"x\", \"file.json\"))\n\t\tif err != nil {\n\t\t\tt.Error(\"-json=0,file:\/\/log\/opt missing expected log file\")\n\t\t}\n\t\t\/\/ All this delicacy with uriIfy and filepath.Join is to get this test to work right on Windows.\n\t\tslogged := normalize(logged, string(uriIfy(dir)), string(uriIfy(\"tmpdir\")))\n\t\tt.Logf(\"%s\", slogged)\n\t\t\/\/ below shows proper nilcheck\n\t\twant(t, slogged, `{\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}},\"severity\":3,\"code\":\"nilcheck\",\"source\":\"go compiler\",\"message\":\"\",`+\n\t\t\t`\"relatedInformation\":[{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":4,\"character\":11},\"end\":{\"line\":4,\"character\":11}}},\"message\":\"inlineLoc\"}]}`)\n\t\twant(t, slogged, `{\"range\":{\"start\":{\"line\":11,\"character\":6},\"end\":{\"line\":11,\"character\":6}},\"severity\":3,\"code\":\"isInBounds\",\"source\":\"go compiler\",\"message\":\"\"}`)\n\t\twant(t, slogged, `{\"range\":{\"start\":{\"line\":7,\"character\":6},\"end\":{\"line\":7,\"character\":6}},\"severity\":3,\"code\":\"canInlineFunction\",\"source\":\"go compiler\",\"message\":\"cost: 35\"}`)\n\t\t\/\/ escape analysis explanation\n\t\twant(t, slogged, `{\"range\":{\"start\":{\"line\":7,\"character\":13},\"end\":{\"line\":7,\"character\":13}},\"severity\":3,\"code\":\"leak\",\"source\":\"go compiler\",\"message\":\"parameter z leaks to ~r2 with derefs=0\",`+\n\t\t\t`\"relatedInformation\":[`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}}},\"message\":\"escflow:    flow: y = z:\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}}},\"message\":\"escflow:      from y := z (assign-pair)\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}}},\"message\":\"escflow:    flow: ~R0 = y:\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":4,\"character\":11},\"end\":{\"line\":4,\"character\":11}}},\"message\":\"inlineLoc\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}}},\"message\":\"escflow:      from y.b (dot of pointer)\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":4,\"character\":11},\"end\":{\"line\":4,\"character\":11}}},\"message\":\"inlineLoc\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}}},\"message\":\"escflow:      from \\u0026y.b (address-of)\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":4,\"character\":9},\"end\":{\"line\":4,\"character\":9}}},\"message\":\"inlineLoc\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}}},\"message\":\"escflow:      from ~R0 = \\u003cN\\u003e (assign-pair)\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":3},\"end\":{\"line\":9,\"character\":3}}},\"message\":\"escflow:    flow: ~r2 = ~R0:\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":3},\"end\":{\"line\":9,\"character\":3}}},\"message\":\"escflow:      from return (*int)(~R0) (return)\"}]}`)\n\t})\n}\n\nfunc testLogOpt(t *testing.T, flag, src, outfile string) (string, error) {\n\trun := []string{testenv.GoToolPath(t), \"tool\", \"compile\", flag, \"-o\", outfile, src}\n\tt.Log(run)\n\tcmd := exec.Command(run[0], run[1:]...)\n\tout, err := cmd.CombinedOutput()\n\tt.Logf(\"%s\", out)\n\treturn string(out), err\n}\n\nfunc testLogOptDir(t *testing.T, dir, flag, src, outfile string) (string, error) {\n\t\/\/ Notice the specified import path \"x\"\n\trun := []string{testenv.GoToolPath(t), \"tool\", \"compile\", \"-p\", \"x\", flag, \"-o\", outfile, src}\n\tt.Log(run)\n\tcmd := exec.Command(run[0], run[1:]...)\n\tcmd.Dir = dir\n\tout, err := cmd.CombinedOutput()\n\tt.Logf(\"%s\", out)\n\treturn string(out), err\n}\n\nfunc testCopy(t *testing.T, dir, goarch, goos, src, outfile string) (string, error) {\n\t\/\/ Notice the specified import path \"x\"\n\trun := []string{testenv.GoToolPath(t), \"tool\", \"compile\", \"-p\", \"x\", \"-json=0,file:\/\/log\/opt\", \"-o\", outfile, src}\n\tt.Log(run)\n\tcmd := exec.Command(run[0], run[1:]...)\n\tcmd.Dir = dir\n\tcmd.Env = append(os.Environ(), \"GOARCH=\"+goarch, \"GOOS=\"+goos)\n\tout, err := cmd.CombinedOutput()\n\tt.Logf(\"%s\", out)\n\treturn string(out), err\n}\n<commit_msg>cmd\/compile: fix message typo<commit_after>\/\/ Copyright 2019 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage logopt\n\nimport (\n\t\"internal\/testenv\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\nconst srcCode = `package x\ntype pair struct {a,b int}\nfunc bar(y *pair) *int {\n\treturn &y.b\n}\nvar a []int\nfunc foo(w, z *pair) *int {\n\tif *bar(w) > 0 {\n\t\treturn bar(z)\n\t}\n\tif a[1] > 0 {\n\t\ta = a[:2]\n\t}\n\treturn &a[0]\n}\n\n\/\/ address taking prevents closure inlining\nfunc n() int {\n\tfoo := func() int { return 1 }\n\tbar := &foo\n\tx := (*bar)() + foo()\n\treturn x\n}\n`\n\nfunc want(t *testing.T, out string, desired string) {\n\t\/\/ On Windows, Unicode escapes in the JSON output end up \"normalized\" elsewhere to \/u....,\n\t\/\/ so \"normalize\" what we're looking for to match that.\n\ts := strings.ReplaceAll(desired, string(os.PathSeparator), \"\/\")\n\tif !strings.Contains(out, s) {\n\t\tt.Errorf(\"did not see phrase %s in \\n%s\", s, out)\n\t}\n}\n\nfunc wantN(t *testing.T, out string, desired string, n int) {\n\tif strings.Count(out, desired) != n {\n\t\tt.Errorf(\"expected exactly %d occurrences of %s in \\n%s\", n, desired, out)\n\t}\n}\n\nfunc TestPathStuff(t *testing.T) {\n\tsep := string(filepath.Separator)\n\tif path, whine := parseLogPath(\"file:\/\/\/c:foo\"); path != \"c:foo\" || whine != \"\" { \/\/ good path\n\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t}\n\tif path, whine := parseLogPath(\"file:\/\/\/foo\"); path != sep+\"foo\" || whine != \"\" { \/\/ good path\n\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t}\n\tif path, whine := parseLogPath(\"foo\"); path != \"\" || whine == \"\" { \/\/ BAD path\n\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t}\n\tif sep == \"\\\\\" { \/\/ On WINDOWS ONLY\n\t\tif path, whine := parseLogPath(\"C:\/foo\"); path != \"C:\\\\foo\" || whine != \"\" { \/\/ good path\n\t\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t\t}\n\t\tif path, whine := parseLogPath(\"c:foo\"); path != \"\" || whine == \"\" { \/\/ BAD path\n\t\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t\t}\n\t\tif path, whine := parseLogPath(\"\/foo\"); path != \"\" || whine == \"\" { \/\/ BAD path\n\t\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t\t}\n\t} else { \/\/ ON UNIX ONLY\n\t\tif path, whine := parseLogPath(\"\/foo\"); path != sep+\"foo\" || whine != \"\" { \/\/ good path\n\t\t\tt.Errorf(\"path='%s', whine='%s'\", path, whine)\n\t\t}\n\t}\n}\n\nfunc TestLogOpt(t *testing.T) {\n\tt.Parallel()\n\n\ttestenv.MustHaveGoBuild(t)\n\n\tdir, err := ioutil.TempDir(\"\", \"TestLogOpt\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(dir)\n\n\tdir = fixSlash(dir) \/\/ Normalize the directory name as much as possible, for Windows testing\n\tsrc := filepath.Join(dir, \"file.go\")\n\tif err := ioutil.WriteFile(src, []byte(srcCode), 0644); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\toutfile := filepath.Join(dir, \"file.o\")\n\n\tt.Run(\"JSON_fails\", func(t *testing.T) {\n\t\t\/\/ Test malformed flag\n\t\tout, err := testLogOpt(t, \"-json=foo\", src, outfile)\n\t\tif err == nil {\n\t\t\tt.Error(\"-json=foo succeeded unexpectedly\")\n\t\t}\n\t\twant(t, out, \"option should be\")\n\t\twant(t, out, \"number\")\n\n\t\t\/\/ Test a version number that is currently unsupported (and should remain unsupported for a while)\n\t\tout, err = testLogOpt(t, \"-json=9,foo\", src, outfile)\n\t\tif err == nil {\n\t\t\tt.Error(\"-json=0,foo succeeded unexpectedly\")\n\t\t}\n\t\twant(t, out, \"version must be\")\n\n\t})\n\n\t\/\/ replace d (dir)  with t (\"tmpdir\") and convert path separators to '\/'\n\tnormalize := func(out []byte, d, t string) string {\n\t\ts := string(out)\n\t\ts = strings.ReplaceAll(s, d, t)\n\t\ts = strings.ReplaceAll(s, string(os.PathSeparator), \"\/\")\n\t\treturn s\n\t}\n\n\t\/\/ Ensure that <128 byte copies are not reported and that 128-byte copies are.\n\t\/\/ Check at both 1 and 8-byte alignments.\n\tt.Run(\"Copy\", func(t *testing.T) {\n\t\tconst copyCode = `package x\nfunc s128a1(x *[128]int8) [128]int8 { \n\treturn *x\n}\nfunc s127a1(x *[127]int8) [127]int8 {\n\treturn *x\n}\nfunc s16a8(x *[16]int64) [16]int64 {\n\treturn *x\n}\nfunc s15a8(x *[15]int64) [15]int64 {\n\treturn *x\n}\n`\n\t\tcopy := filepath.Join(dir, \"copy.go\")\n\t\tif err := ioutil.WriteFile(copy, []byte(copyCode), 0644); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\toutcopy := filepath.Join(dir, \"copy.o\")\n\n\t\t\/\/ On not-amd64, test the host architecture and os\n\t\tarches := []string{runtime.GOARCH}\n\t\tgoos0 := runtime.GOOS\n\t\tif runtime.GOARCH == \"amd64\" { \/\/ Test many things with \"linux\" (wasm will get \"js\")\n\t\t\tarches = []string{\"arm\", \"arm64\", \"386\", \"amd64\", \"mips\", \"mips64\", \"ppc64le\", \"riscv64\", \"s390x\", \"wasm\"}\n\t\t\tgoos0 = \"linux\"\n\t\t}\n\n\t\tfor _, arch := range arches {\n\t\t\tt.Run(arch, func(t *testing.T) {\n\t\t\t\tgoos := goos0\n\t\t\t\tif arch == \"wasm\" {\n\t\t\t\t\tgoos = \"js\"\n\t\t\t\t}\n\t\t\t\t_, err := testCopy(t, dir, arch, goos, copy, outcopy)\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Error(\"-json=0,file:\/\/log\/opt should have succeeded\")\n\t\t\t\t}\n\t\t\t\tlogged, err := ioutil.ReadFile(filepath.Join(dir, \"log\", \"opt\", \"x\", \"copy.json\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Error(\"-json=0,file:\/\/log\/opt missing expected log file\")\n\t\t\t\t}\n\t\t\t\tslogged := normalize(logged, string(uriIfy(dir)), string(uriIfy(\"tmpdir\")))\n\t\t\t\tt.Logf(\"%s\", slogged)\n\t\t\t\twant(t, slogged, `{\"range\":{\"start\":{\"line\":3,\"character\":2},\"end\":{\"line\":3,\"character\":2}},\"severity\":3,\"code\":\"copy\",\"source\":\"go compiler\",\"message\":\"128 bytes\"}`)\n\t\t\t\twant(t, slogged, `{\"range\":{\"start\":{\"line\":9,\"character\":2},\"end\":{\"line\":9,\"character\":2}},\"severity\":3,\"code\":\"copy\",\"source\":\"go compiler\",\"message\":\"128 bytes\"}`)\n\t\t\t\twantN(t, slogged, `\"code\":\"copy\"`, 2)\n\t\t\t})\n\t\t}\n\t})\n\n\t\/\/ Some architectures don't fault on nil dereference, so nilchecks are eliminated differently.\n\t\/\/ The N-way copy test also doesn't need to run N-ways N times.\n\tif runtime.GOARCH != \"amd64\" {\n\t\treturn\n\t}\n\n\tt.Run(\"Success\", func(t *testing.T) {\n\t\t\/\/ This test is supposed to succeed\n\n\t\t\/\/ Note 'file:\/\/' is the I-Know-What-I-Am-Doing way of specifying a file, also to deal with corner cases for Windows.\n\t\t_, err := testLogOptDir(t, dir, \"-json=0,file:\/\/log\/opt\", src, outfile)\n\t\tif err != nil {\n\t\t\tt.Error(\"-json=0,file:\/\/log\/opt should have succeeded\")\n\t\t}\n\t\tlogged, err := ioutil.ReadFile(filepath.Join(dir, \"log\", \"opt\", \"x\", \"file.json\"))\n\t\tif err != nil {\n\t\t\tt.Error(\"-json=0,file:\/\/log\/opt missing expected log file\")\n\t\t}\n\t\t\/\/ All this delicacy with uriIfy and filepath.Join is to get this test to work right on Windows.\n\t\tslogged := normalize(logged, string(uriIfy(dir)), string(uriIfy(\"tmpdir\")))\n\t\tt.Logf(\"%s\", slogged)\n\t\t\/\/ below shows proper nilcheck\n\t\twant(t, slogged, `{\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}},\"severity\":3,\"code\":\"nilcheck\",\"source\":\"go compiler\",\"message\":\"\",`+\n\t\t\t`\"relatedInformation\":[{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":4,\"character\":11},\"end\":{\"line\":4,\"character\":11}}},\"message\":\"inlineLoc\"}]}`)\n\t\twant(t, slogged, `{\"range\":{\"start\":{\"line\":11,\"character\":6},\"end\":{\"line\":11,\"character\":6}},\"severity\":3,\"code\":\"isInBounds\",\"source\":\"go compiler\",\"message\":\"\"}`)\n\t\twant(t, slogged, `{\"range\":{\"start\":{\"line\":7,\"character\":6},\"end\":{\"line\":7,\"character\":6}},\"severity\":3,\"code\":\"canInlineFunction\",\"source\":\"go compiler\",\"message\":\"cost: 35\"}`)\n\t\t\/\/ escape analysis explanation\n\t\twant(t, slogged, `{\"range\":{\"start\":{\"line\":7,\"character\":13},\"end\":{\"line\":7,\"character\":13}},\"severity\":3,\"code\":\"leak\",\"source\":\"go compiler\",\"message\":\"parameter z leaks to ~r2 with derefs=0\",`+\n\t\t\t`\"relatedInformation\":[`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}}},\"message\":\"escflow:    flow: y = z:\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}}},\"message\":\"escflow:      from y := z (assign-pair)\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}}},\"message\":\"escflow:    flow: ~R0 = y:\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":4,\"character\":11},\"end\":{\"line\":4,\"character\":11}}},\"message\":\"inlineLoc\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}}},\"message\":\"escflow:      from y.b (dot of pointer)\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":4,\"character\":11},\"end\":{\"line\":4,\"character\":11}}},\"message\":\"inlineLoc\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}}},\"message\":\"escflow:      from \\u0026y.b (address-of)\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":4,\"character\":9},\"end\":{\"line\":4,\"character\":9}}},\"message\":\"inlineLoc\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":13},\"end\":{\"line\":9,\"character\":13}}},\"message\":\"escflow:      from ~R0 = \\u003cN\\u003e (assign-pair)\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":3},\"end\":{\"line\":9,\"character\":3}}},\"message\":\"escflow:    flow: ~r2 = ~R0:\"},`+\n\t\t\t`{\"location\":{\"uri\":\"file:\/\/tmpdir\/file.go\",\"range\":{\"start\":{\"line\":9,\"character\":3},\"end\":{\"line\":9,\"character\":3}}},\"message\":\"escflow:      from return (*int)(~R0) (return)\"}]}`)\n\t})\n}\n\nfunc testLogOpt(t *testing.T, flag, src, outfile string) (string, error) {\n\trun := []string{testenv.GoToolPath(t), \"tool\", \"compile\", flag, \"-o\", outfile, src}\n\tt.Log(run)\n\tcmd := exec.Command(run[0], run[1:]...)\n\tout, err := cmd.CombinedOutput()\n\tt.Logf(\"%s\", out)\n\treturn string(out), err\n}\n\nfunc testLogOptDir(t *testing.T, dir, flag, src, outfile string) (string, error) {\n\t\/\/ Notice the specified import path \"x\"\n\trun := []string{testenv.GoToolPath(t), \"tool\", \"compile\", \"-p\", \"x\", flag, \"-o\", outfile, src}\n\tt.Log(run)\n\tcmd := exec.Command(run[0], run[1:]...)\n\tcmd.Dir = dir\n\tout, err := cmd.CombinedOutput()\n\tt.Logf(\"%s\", out)\n\treturn string(out), err\n}\n\nfunc testCopy(t *testing.T, dir, goarch, goos, src, outfile string) (string, error) {\n\t\/\/ Notice the specified import path \"x\"\n\trun := []string{testenv.GoToolPath(t), \"tool\", \"compile\", \"-p\", \"x\", \"-json=0,file:\/\/log\/opt\", \"-o\", outfile, src}\n\tt.Log(run)\n\tcmd := exec.Command(run[0], run[1:]...)\n\tcmd.Dir = dir\n\tcmd.Env = append(os.Environ(), \"GOARCH=\"+goarch, \"GOOS=\"+goos)\n\tout, err := cmd.CombinedOutput()\n\tt.Logf(\"%s\", out)\n\treturn string(out), err\n}\n<|endoftext|>"}
{"text":"<commit_before>package lfs\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"testing\"\n\n\t\"github.com\/github\/git-lfs\/vendor\/_nuts\/github.com\/technoweenie\/assert\"\n)\n\nfunc TestWriterWithCallback(t *testing.T) {\n\tcalled := 0\n\tcalledRead := make([]int64, 0, 2)\n\n\treader := &CallbackReader{\n\t\tTotalSize: 5,\n\t\tReader:    bytes.NewBufferString(\"BOOYA\"),\n\t\tC: func(total int64, read int64, current int) error {\n\t\t\tcalled += 1\n\t\t\tcalledRead = append(calledRead, read)\n\t\t\tassert.Equal(t, 5, int(total))\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treadBuf := make([]byte, 3)\n\tn, err := reader.Read(readBuf)\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, \"BOO\", string(readBuf[0:n]))\n\n\tn, err = reader.Read(readBuf)\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, \"YA\", string(readBuf[0:n]))\n\n\tassert.Equal(t, 2, called)\n\tassert.Equal(t, 2, len(calledRead))\n\tassert.Equal(t, 3, int(calledRead[0]))\n\tassert.Equal(t, 5, int(calledRead[1]))\n}\n\nfunc TestCopyWithCallback(t *testing.T) {\n\tbuf := bytes.NewBufferString(\"BOOYA\")\n\n\tcalled := 0\n\tcalledWritten := make([]int64, 0, 2)\n\n\tn, err := CopyWithCallback(ioutil.Discard, buf, 5, func(total int64, written int64, current int) error {\n\t\tcalled += 1\n\t\tcalledWritten = append(calledWritten, written)\n\t\tassert.Equal(t, 5, int(total))\n\t\treturn nil\n\t})\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, 5, int(n))\n\n\tassert.Equal(t, 1, called)\n\tassert.Equal(t, 1, len(calledWritten))\n\tassert.Equal(t, 5, int(calledWritten[0]))\n}\n<commit_msg>アアー アアアア アー<commit_after>package lfs\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"testing\"\n\n\t\"github.com\/github\/git-lfs\/vendor\/_nuts\/github.com\/technoweenie\/assert\"\n)\n\nfunc TestWriterWithCallback(t *testing.T) {\n\tcalled := 0\n\tcalledRead := make([]int64, 0, 2)\n\n\treader := &CallbackReader{\n\t\tTotalSize: 5,\n\t\tReader:    bytes.NewBufferString(\"BOOYA\"),\n\t\tC: func(total int64, read int64, current int) error {\n\t\t\tcalled += 1\n\t\t\tcalledRead = append(calledRead, read)\n\t\t\tassert.Equal(t, 5, int(total))\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treadBuf := make([]byte, 3)\n\tn, err := reader.Read(readBuf)\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, \"BOO\", string(readBuf[0:n]))\n\n\tn, err = reader.Read(readBuf)\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, \"YA\", string(readBuf[0:n]))\n\n\tassert.Equal(t, 2, called)\n\tassert.Equal(t, 2, len(calledRead))\n\tassert.Equal(t, 3, int(calledRead[0]))\n\tassert.Equal(t, 5, int(calledRead[1]))\n}\n\nfunc TestCopyWithCallback(t *testing.T) {\n\tbuf := bytes.NewBufferString(\"BOOYA\")\n\n\tcalled := 0\n\tcalledWritten := make([]int64, 0, 2)\n\n\tn, err := CopyWithCallback(ioutil.Discard, buf, 5, func(total int64, written int64, current int) error {\n\t\tcalled += 1\n\t\tcalledWritten = append(calledWritten, written)\n\t\tassert.Equal(t, 5, int(total))\n\t\treturn nil\n\t})\n\tassert.Equal(t, nil, err)\n\tassert.Equal(t, 5, int(n))\n\n\tassert.Equal(t, 1, called)\n\tassert.Equal(t, 1, len(calledWritten))\n\tassert.Equal(t, 5, int(calledWritten[0]))\n}\n\nfunc TestFilterIncludeExclude(t *testing.T) {\n\n\t\/\/ Inclusion\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, nil))\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\/filename.dat\"}, nil))\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"blank\", \"something\", \"test\/filename.dat\", \"foo\"}, nil))\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"blank\", \"something\", \"foo\"}, nil))\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\/notfilename.dat\"}, nil))\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\"}, nil))\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\/*\"}, nil))\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"nottest\"}, nil))\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"nottest\/*\"}, nil))\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\/fil*\"}, nil))\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\/g*\"}, nil))\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"tes*\/*\"}, nil))\n\n\t\/\/ Exclusion\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"test\/filename.dat\"}))\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"blank\", \"something\", \"test\/filename.dat\", \"foo\"}))\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"blank\", \"something\", \"foo\"}))\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"test\/notfilename.dat\"}))\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"test\"}))\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"test\/*\"}))\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"nottest\"}))\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"nottest\/*\"}))\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"test\/fil*\"}))\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"test\/g*\"}))\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"tes*\/*\"}))\n\n\t\/\/ Both\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\/filename.dat\"}, []string{\"test\/notfilename.dat\"}))\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\"}, []string{\"test\/filename.dat\"}))\n\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\/*\"}, []string{\"test\/notfile*\"}))\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\/*\"}, []string{\"test\/file*\"}))\n\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"another\/*\", \"test\/*\"}, []string{\"test\/notfilename.dat\", \"test\/filename.dat\"}))\n\n\tif IsWindows() {\n\t\t\/\/ Extra tests because Windows git reports filenames with \/ separators\n\t\t\/\/ but we need to allow \\ separators in include\/exclude too\n\t\t\/\/ Can only test this ON Windows because of filepath behaviour\n\t\t\/\/ Inclusion\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, nil))\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\\\\filename.dat\"}, nil))\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"blank\", \"something\", \"test\\\\filename.dat\", \"foo\"}, nil))\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"blank\", \"something\", \"foo\"}, nil))\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\\\\notfilename.dat\"}, nil))\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\"}, nil))\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\\\\*\"}, nil))\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"nottest\"}, nil))\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"nottest\\\\*\"}, nil))\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\\\\fil*\"}, nil))\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\\\\g*\"}, nil))\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"tes*\\\\*\"}, nil))\n\n\t\t\/\/ Exclusion\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"test\\\\filename.dat\"}))\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"blank\", \"something\", \"test\\\\filename.dat\", \"foo\"}))\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"blank\", \"something\", \"foo\"}))\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"test\\\\notfilename.dat\"}))\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"test\"}))\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"test\\\\*\"}))\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"nottest\"}))\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"nottest\\\\*\"}))\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"test\\\\fil*\"}))\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"test\\\\g*\"}))\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", nil, []string{\"tes*\\\\*\"}))\n\n\t\t\/\/ Both\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\\\\filename.dat\"}, []string{\"test\\\\notfilename.dat\"}))\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\"}, []string{\"test\\\\filename.dat\"}))\n\t\tassert.Equal(t, true, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\\\\*\"}, []string{\"test\\\\notfile*\"}))\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"test\\\\*\"}, []string{\"test\\\\file*\"}))\n\t\tassert.Equal(t, false, FilenamePassesIncludeExcludeFilter(\"test\/filename.dat\", []string{\"another\\\\*\", \"test\\\\*\"}, []string{\"test\\\\notfilename.dat\", \"test\\\\filename.dat\"}))\n\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Change metric name (#30)<commit_after><|endoftext|>"}
{"text":"<commit_before>package gqt_test\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\n\t\"code.cloudfoundry.org\/garden\"\n\t\"code.cloudfoundry.org\/guardian\/gqt\/runner\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"Networking Uniqueness\", func() {\n\tvar (\n\t\tclient *runner.RunningGarden\n\t)\n\n\tBeforeEach(func() {\n\t\tclient = runner.Start(config)\n\t})\n\n\tAfterEach(func() {\n\t\tExpect(client.DestroyAndStop()).To(Succeed())\n\t})\n\n\tIt(\"should not allocate duplicate subnets\", func() {\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tgo func() {\n\t\t\t\tdefer GinkgoRecover()\n\n\t\t\t\tcreate(client, 5)\n\t\t\t}()\n\t\t}\n\n\t\tEventually(numContainers(client), \"20s\").Should(Equal(50))\n\t\tExpect(numBridges()).To(Equal(50))\n\t})\n})\n\nfunc create(client *runner.RunningGarden, n int) {\n\tfor i := 0; i < n; i++ {\n\t\t_, err := client.Create(garden.ContainerSpec{})\n\t\tExpect(err).NotTo(HaveOccurred())\n\t}\n}\n\nfunc numContainers(client *runner.RunningGarden) func() int {\n\treturn func() int {\n\t\tcontainers, err := client.Containers(nil)\n\t\tExpect(err).NotTo(HaveOccurred())\n\t\treturn len(containers)\n\t}\n}\n\nfunc numBridges() int {\n\tintfs, err := net.Interfaces()\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbridgeCount := 0\n\n\tfor _, intf := range intfs {\n\t\tif strings.Contains(intf.Name, fmt.Sprintf(\"w%dbrdg\", GinkgoParallelNode())) {\n\t\t\tbridgeCount++\n\t\t}\n\t}\n\n\treturn bridgeCount\n}\n<commit_msg>Revert \"Add unique net test\"<commit_after><|endoftext|>"}
{"text":"<commit_before>package standard\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\n\t\"github.com\/webx-top\/echo\/engine\"\n\t\"github.com\/webx-top\/echo\/logger\"\n)\n\ntype Response struct {\n\tconfig         *engine.Config\n\tresponse       http.ResponseWriter\n\trequest        *http.Request\n\theader         engine.Header\n\tstatus         int\n\tsize           int64\n\tcommitted      bool\n\twriter         io.Writer\n\tlogger         logger.Logger\n\tbody           []byte\n\tkeepBody       bool\n\tresponseWriter *responseWriter\n}\n\nfunc NewResponse(w http.ResponseWriter, r *http.Request, l logger.Logger) *Response {\n\treturn &Response{\n\t\tresponse: w,\n\t\trequest:  r,\n\t\theader:   &Header{Header: w.Header()},\n\t\twriter:   w,\n\t\tlogger:   l,\n\t}\n}\n\nfunc (r *Response) Header() engine.Header {\n\treturn r.header\n}\n\nfunc (r *Response) WriteHeader(code int) {\n\tif r.committed {\n\t\tr.logger.Warn(\"response already committed\")\n\t\treturn\n\t}\n\tr.status = code\n\tr.response.WriteHeader(code)\n\tr.committed = true\n}\n\nfunc (r *Response) KeepBody(on bool) {\n\tr.keepBody = on\n}\n\nfunc (r *Response) Write(b []byte) (n int, err error) {\n\tif !r.committed {\n\t\tif r.status == 0 {\n\t\t\tr.status = http.StatusOK\n\t\t}\n\t\tr.WriteHeader(r.status)\n\t}\n\tif r.keepBody {\n\t\tr.body = append(r.body, b...)\n\t}\n\tn, err = r.writer.Write(b)\n\tr.size += int64(n)\n\treturn\n}\n\nfunc (r *Response) Status() int {\n\treturn r.status\n}\n\nfunc (r *Response) Size() int64 {\n\treturn r.size\n}\n\nfunc (r *Response) Committed() bool {\n\treturn r.committed\n}\n\nfunc (r *Response) SetWriter(w io.Writer) {\n\tr.writer = w\n}\n\nfunc (r *Response) Writer() io.Writer {\n\treturn r.writer\n}\n\nfunc (r *Response) Object() interface{} {\n\treturn r.response\n}\n\nfunc (r *Response) Error(errMsg string, args ...int) {\n\tif len(args) > 0 {\n\t\tr.status = args[0]\n\t} else {\n\t\tr.status = http.StatusInternalServerError\n\t}\n\tr.Write(engine.Str2bytes(errMsg))\n\tr.WriteHeader(r.status)\n}\n\nfunc (r *Response) reset(w http.ResponseWriter, req *http.Request, h engine.Header) {\n\tr.response = w\n\tr.request = req\n\tr.header = h\n\tr.status = http.StatusOK\n\tr.size = 0\n\tr.committed = false\n\tr.writer = w\n\tr.body = nil\n\tr.keepBody = false\n\tr.responseWriter = &responseWriter{r}\n}\n\nfunc (r *Response) Hijack(fn func(net.Conn)) {\n\tconn, bufrw, err := r.response.(http.Hijacker).Hijack()\n\tif err != nil {\n\t\tr.logger.Error(err)\n\t}\n\t_ = bufrw\n\tfn(conn)\n\tconn.Close()\n\tr.committed = true\n}\n\nfunc (r *Response) Body() []byte {\n\treturn r.body\n}\n\nfunc (r *Response) Redirect(url string, code int) {\n\thttp.Redirect(r.response, r.request, url, code)\n\tr.committed = true\n}\n\nfunc (r *Response) NotFound() {\n\thttp.Error(r.response, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\tr.committed = true\n}\n\nfunc (r *Response) SetCookie(cookie *http.Cookie) {\n\tr.header.Add(engine.HeaderSetCookie, cookie.String())\n}\n\nfunc (r *Response) ServeFile(file string) {\n\tr.keepBody = false\n\thttp.ServeFile(r.response, r.request, file)\n\tr.committed = true\n}\n\nfunc (r *Response) Stream(step func(io.Writer) bool) {\n\tw := r.response\n\tclientGone := w.(http.CloseNotifier).CloseNotify()\n\tfor {\n\t\tselect {\n\t\tcase <-clientGone:\n\t\t\treturn\n\t\tdefault:\n\t\t\tkeepOpen := step(w)\n\t\t\tw.(http.Flusher).Flush()\n\t\t\tif !keepOpen {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (r *Response) StdResponseWriter() http.ResponseWriter {\n\treturn r.responseWriter\n}\n\ntype responseWriter struct {\n\tresponse *Response\n}\n\nfunc (r *responseWriter) Header() http.Header {\n\treturn r.response.header.(*Header).Header\n}\n\nfunc (r *responseWriter) Write(b []byte) (n int, err error) {\n\treturn r.response.Write(b)\n}\n\nfunc (r *responseWriter) WriteHeader(code int) {\n\tr.response.WriteHeader(code)\n}\n<commit_msg>update<commit_after>package standard\n\nimport (\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\n\t\"github.com\/webx-top\/echo\/engine\"\n\t\"github.com\/webx-top\/echo\/logger\"\n)\n\ntype Response struct {\n\tconfig         *engine.Config\n\tresponse       http.ResponseWriter\n\trequest        *http.Request\n\theader         engine.Header\n\tstatus         int\n\tsize           int64\n\tcommitted      bool\n\twriter         io.Writer\n\tlogger         logger.Logger\n\tbody           []byte\n\tkeepBody       bool\n\tresponseWriter *responseWriter\n}\n\nfunc NewResponse(w http.ResponseWriter, r *http.Request, l logger.Logger) *Response {\n\treturn &Response{\n\t\tresponse: w,\n\t\trequest:  r,\n\t\theader:   &Header{Header: w.Header()},\n\t\twriter:   w,\n\t\tlogger:   l,\n\t}\n}\n\nfunc (r *Response) Header() engine.Header {\n\treturn r.header\n}\n\nfunc (r *Response) WriteHeader(code int) {\n\tif r.committed {\n\t\tr.logger.Warn(\"response already committed\")\n\t\treturn\n\t}\n\tr.status = code\n\tr.response.WriteHeader(code)\n\tr.committed = true\n}\n\nfunc (r *Response) KeepBody(on bool) {\n\tr.keepBody = on\n}\n\nfunc (r *Response) Write(b []byte) (n int, err error) {\n\tif !r.committed {\n\t\tif r.status == 0 {\n\t\t\tr.status = http.StatusOK\n\t\t}\n\t\tr.WriteHeader(r.status)\n\t}\n\tif r.keepBody {\n\t\tr.body = append(r.body, b...)\n\t}\n\tn, err = r.writer.Write(b)\n\tr.size += int64(n)\n\treturn\n}\n\nfunc (r *Response) Status() int {\n\treturn r.status\n}\n\nfunc (r *Response) Size() int64 {\n\treturn r.size\n}\n\nfunc (r *Response) Committed() bool {\n\treturn r.committed\n}\n\nfunc (r *Response) SetWriter(w io.Writer) {\n\tr.writer = w\n}\n\nfunc (r *Response) Writer() io.Writer {\n\treturn r.writer\n}\n\nfunc (r *Response) Object() interface{} {\n\treturn r.response\n}\n\nfunc (r *Response) Error(errMsg string, args ...int) {\n\tif len(args) > 0 {\n\t\tr.status = args[0]\n\t} else {\n\t\tr.status = http.StatusInternalServerError\n\t}\n\tr.Write(engine.Str2bytes(errMsg))\n\tr.WriteHeader(r.status)\n}\n\nfunc (r *Response) reset(w http.ResponseWriter, req *http.Request, h engine.Header) {\n\tr.response = w\n\tr.request = req\n\tr.header = h\n\tr.status = http.StatusOK\n\tr.size = 0\n\tr.committed = false\n\tr.writer = w\n\tr.body = nil\n\tr.keepBody = false\n\tr.responseWriter = &responseWriter{r}\n}\n\nfunc (r *Response) Hijack(fn func(net.Conn)) {\n\tconn, bufrw, err := r.response.(http.Hijacker).Hijack()\n\tif err != nil {\n\t\tr.logger.Error(err)\n\t}\n\t_ = bufrw\n\tfn(conn)\n\tconn.Close()\n\tr.committed = true\n}\n\nfunc (r *Response) Body() []byte {\n\treturn r.body\n}\n\nfunc (r *Response) Redirect(url string, code int) {\n\thttp.Redirect(r.response, r.request, url, code)\n\tr.committed = true\n}\n\nfunc (r *Response) NotFound() {\n\thttp.Error(r.response, http.StatusText(http.StatusNotFound), http.StatusNotFound)\n\tr.committed = true\n}\n\nfunc (r *Response) SetCookie(cookie *http.Cookie) {\n\tr.header.Add(engine.HeaderSetCookie, cookie.String())\n}\n\nfunc (r *Response) ServeFile(file string) {\n\tr.keepBody = false\n\thttp.ServeFile(r.response, r.request, file)\n\tr.committed = true\n}\n\nfunc (r *Response) Stream(step func(io.Writer) bool) {\n\tw := r.response\n\tclientGone := w.(http.CloseNotifier).CloseNotify()\n\tfor {\n\t\tselect {\n\t\tcase <-clientGone:\n\t\t\treturn\n\t\tdefault:\n\t\t\tkeepOpen := step(w)\n\t\t\tw.(http.Flusher).Flush()\n\t\t\tif !keepOpen {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (r *Response) StdResponseWriter() http.ResponseWriter {\n\treturn r.responseWriter\n}\n\ntype responseWriter struct {\n\tresponse *Response\n}\n\nfunc (r *responseWriter) StatusCode() int {\n\tif r.response.Status() == 0 {\n\t\treturn http.StatusOK\n\t}\n\treturn r.response.Status()\n}\n\nfunc (r *responseWriter) Header() http.Header {\n\treturn r.response.header.(*Header).Header\n}\n\nfunc (r *responseWriter) Write(b []byte) (n int, err error) {\n\treturn r.response.Write(b)\n}\n\nfunc (r *responseWriter) WriteHeader(code int) {\n\tr.response.WriteHeader(code)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n    \"flag\"\n    \"log\"\n    \"os\"\n    \"image\/png\"\n    \"errors\"\n    \"functorama.com\/demo\/libgodelbrot\"\n)\n\ntype commandLine struct {\n    iterateLimit uint\n    divergeLimit float64\n    width uint\n    height uint\n    filename string\n    xOffset float64\n    yOffset float64\n    zoom float64\n    mode string \n    regionCollapse uint  \n}\n\nfunc parseArguments(args *commandLine) {\n    xOffset := real(libgodelbrot.MagicOffset)\n    yOffset := imag(libgodelbrot.MagicOffset)\n\n    flag.UintVar(&args.iterateLimit, \"iterateLimit\", 255, \"Maximum number of iterations\")\n    flag.Float64Var(&args.divergeLimit, \"divergeLimit\", 4.0, \"Limit where function is said to diverge to infinity\")\n    flag.UintVar(&args.width, \"imageWidth\", 800, \"Width of output PNG\")\n    flag.UintVar(&args.height, \"imageHeight\", 600, \"Height of output PNG\")\n    flag.StringVar(&args.filename, \"filename\", \"mandelbrot.png\", \"Name of output PNG\")\n    flag.Float64Var(&args.xOffset, \"realOffset\", xOffset, \"Leftmost position of complex plane projected onto PNG image\")\n    flag.Float64Var(&args.yOffset, \"imagOffset\", yOffset, \"Topmost position of complex plane projected onto PNG image\")\n    flag.Float64Var(&args.zoom, \"zoom\", 1.0, \"Look into the eyeball\")\n    flag.StringVar(&args.mode, \"mode\", \"sequential\", \"Render mode\")\n    flag.UintVar(&args.regionCollapse, 2, \"Pixel width of region at which sequential render is forced\")\n    flag.Parse()\n}\n\nfunc extractRenderParameters(args commandLine) (*libgodelbrot.RenderConfig, error) {\n    if args.iterateLimit > 255 {\n        return nil, errors.New(\"iterateLimit out of bounds (uint8)\")\n    }\n\n    if args.divergeLimit <= 0.0 {\n        return nil, errors.New(\"divergeLimit out of bounds (positive float64)\")\n    }\n\n    if args.zoom <= 0.0 {\n        return nil, errors.New(\"zoom out of bounds (positive float64)\")\n    }\n\n    parameters := libgodelbrot.RenderConfig{\n        IterateLimit: uint8(args.iterateLimit),\n        DivergeLimit: args.divergeLimit,\n        Width: args.width,\n        Height: args.height,\n        XOffset: args.xOffset,\n        YOffset: args.yOffset,\n        Zoom: args.zoom,\n        RegionCollapse: args.regionCollapse,\n    }\n    config := parameters.Configure()\n    return config, nil\n}\n\nfunc main() {\n    args := commandLine{}\n    parseArguments(&args)\n\n    var renderer libgodelbrot.Renderer\n    switch args.mode {\n    case \"sequential\":\n        renderer = libgodelbrot.SequentialRender\n    case \"region\":\n        renderer = libgodelbrot.RegionRender\n    default:\n        log.Fatal(\"Unknown renderer\")\n    }\n\n    config, validationError := extractRenderParameters(args)\n    if validationError != nil {\n        log.Fatal(validationError)\n    }\n\n    \/\/ Redscale is the only palette we have available\n    redscale := NewRedscalePalette(config.IterateLimit)\n\n    image, renderError := renderer(config, redscale)\n    if renderError != nil {\n        log.Fatal(renderError)\n    }\n\n    file, fileError := os.Create(args.filename)\n\n    if fileError != nil {\n        log.Fatal(fileError)\n    }\n    defer file.Close()\n\n    writeError := png.Encode(file, image)\n\n    if writeError != nil {\n        log.Fatal(writeError)\n    }\n}<commit_msg>Changed --filename argument to --output<commit_after>package main\n\nimport (\n    \"flag\"\n    \"log\"\n    \"os\"\n    \"image\/png\"\n    \"errors\"\n    \"functorama.com\/demo\/libgodelbrot\"\n)\n\ntype commandLine struct {\n    iterateLimit uint\n    divergeLimit float64\n    width uint\n    height uint\n    filename string\n    xOffset float64\n    yOffset float64\n    zoom float64\n    mode string \n    regionCollapse uint  \n}\n\nfunc parseArguments(args *commandLine) {\n    xOffset := real(libgodelbrot.MagicOffset)\n    yOffset := imag(libgodelbrot.MagicOffset)\n\n    flag.UintVar(&args.iterateLimit, \"iterateLimit\", 255, \"Maximum number of iterations\")\n    flag.Float64Var(&args.divergeLimit, \"divergeLimit\", 4.0, \"Limit where function is said to diverge to infinity\")\n    flag.UintVar(&args.width, \"imageWidth\", 800, \"Width of output PNG\")\n    flag.UintVar(&args.height, \"imageHeight\", 600, \"Height of output PNG\")\n    flag.StringVar(&args.filename, \"output\", \"mandelbrot.png\", \"Name of output PNG\")\n    flag.Float64Var(&args.xOffset, \"realOffset\", xOffset, \"Leftmost position of complex plane projected onto PNG image\")\n    flag.Float64Var(&args.yOffset, \"imagOffset\", yOffset, \"Topmost position of complex plane projected onto PNG image\")\n    flag.Float64Var(&args.zoom, \"zoom\", 1.0, \"Look into the eyeball\")\n    flag.StringVar(&args.mode, \"mode\", \"sequential\", \"Render mode\")\n    flag.UintVar(&args.regionCollapse, 2, \"Pixel width of region at which sequential render is forced\")\n    flag.Parse()\n}\n\nfunc extractRenderParameters(args commandLine) (*libgodelbrot.RenderConfig, error) {\n    if args.iterateLimit > 255 {\n        return nil, errors.New(\"iterateLimit out of bounds (uint8)\")\n    }\n\n    if args.divergeLimit <= 0.0 {\n        return nil, errors.New(\"divergeLimit out of bounds (positive float64)\")\n    }\n\n    if args.zoom <= 0.0 {\n        return nil, errors.New(\"zoom out of bounds (positive float64)\")\n    }\n\n    parameters := libgodelbrot.RenderConfig{\n        IterateLimit: uint8(args.iterateLimit),\n        DivergeLimit: args.divergeLimit,\n        Width: args.width,\n        Height: args.height,\n        XOffset: args.xOffset,\n        YOffset: args.yOffset,\n        Zoom: args.zoom,\n        RegionCollapse: args.regionCollapse,\n    }\n    config := parameters.Configure()\n    return config, nil\n}\n\nfunc main() {\n    args := commandLine{}\n    parseArguments(&args)\n\n    var renderer libgodelbrot.Renderer\n    switch args.mode {\n    case \"sequential\":\n        renderer = libgodelbrot.SequentialRender\n    case \"region\":\n        renderer = libgodelbrot.RegionRender\n    default:\n        log.Fatal(\"Unknown renderer\")\n    }\n\n    config, validationError := extractRenderParameters(args)\n    if validationError != nil {\n        log.Fatal(validationError)\n    }\n\n    \/\/ Redscale is the only palette we have available\n    redscale := NewRedscalePalette(config.IterateLimit)\n\n    image, renderError := renderer(config, redscale)\n    if renderError != nil {\n        log.Fatal(renderError)\n    }\n\n    file, fileError := os.Create(args.filename)\n\n    if fileError != nil {\n        log.Fatal(fileError)\n    }\n    defer file.Close()\n\n    writeError := png.Encode(file, image)\n\n    if writeError != nil {\n        log.Fatal(writeError)\n    }\n}<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright ©2017 The gonum Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage path\n\nimport (\n\t\"gonum.org\/v1\/gonum\/graph\"\n\t\"gonum.org\/v1\/gonum\/graph\/internal\/set\"\n)\n\n\/\/ Dominators returns immediate dominators for all nodes in the flow graph\n\/\/ g starting from the given root node.\nfunc Dominators(root graph.Node, g graph.Directed) map[int64]graph.Node {\n\t\/\/ The algorithm used here is the Lengauer and Tarjan\n\t\/\/ algorithm described in https:\/\/doi.org\/10.1145%2F357062.357071\n\n\tlt := lengauerTarjan{\n\t\tparent: make(map[int64]graph.Node),\n\t\tpred:   make(map[int64][]graph.Node),\n\t\tsemi:   make(map[int64]int),\n\t\tvertex: make([]graph.Node, 1), \/\/ FIXME(kortschak): The current implementation requires non-zero node numbers.\n\t\tbucket: make(map[int64]set.Nodes),\n\t\tdom:    make(map[int64]graph.Node),\n\n\t\tancestor: make(map[int64]graph.Node),\n\t\tlabel:    make(map[int64]graph.Node),\n\t}\n\n\t\/\/ step 1.\n\tlt.dfs(g, root)\n\n\tfor i := lt.n; i >= 2; i-- {\n\t\tw := lt.vertex[i]\n\t\twid := w.ID()\n\t\t\/\/ step 2.\n\t\tfor _, v := range lt.pred[wid] {\n\t\t\tuid := lt.eval(v).ID()\n\t\t\tif lt.semi[uid] < lt.semi[wid] {\n\t\t\t\tlt.semi[wid] = lt.semi[uid]\n\t\t\t}\n\t\t}\n\n\t\tb, ok := lt.bucket[lt.vertex[lt.semi[wid]].ID()]\n\t\tif !ok {\n\t\t\tb = make(set.Nodes)\n\t\t\tlt.bucket[lt.vertex[lt.semi[wid]].ID()] = b\n\t\t}\n\t\tb.Add(w)\n\t\tlt.link(lt.parent[wid], w)\n\n\t\t\/\/ step 3.\n\t\tfor _, v := range lt.bucket[lt.parent[wid].ID()] {\n\t\t\tvid := v.ID()\n\t\t\tlt.bucket[lt.parent[wid].ID()].Remove(v)\n\t\t\tu := lt.eval(v)\n\t\t\tif lt.semi[u.ID()] < lt.semi[vid] {\n\t\t\t\tlt.dom[vid] = u\n\t\t\t} else {\n\t\t\t\tlt.dom[vid] = lt.parent[wid]\n\t\t\t}\n\t\t}\n\n\t}\n\n\t\/\/ step 4.\n\tfor i := 2; i <= lt.n; i++ {\n\t\tw := lt.vertex[i]\n\t\twid := w.ID()\n\t\tif lt.dom[wid].ID() != lt.vertex[lt.semi[wid]].ID() {\n\t\t\tlt.dom[wid] = lt.dom[lt.dom[wid].ID()]\n\t\t}\n\t}\n\tdelete(lt.dom, root.ID())\n\n\treturn lt.dom\n}\n\ntype lengauerTarjan struct {\n\t\/\/ The vertex which is the parent of vertex w\n\t\/\/ in the spanning tree generated by the search.\n\tparent map[int64]graph.Node\n\n\t\/\/ The set of vertices v such that (v, w) is an edge\n\t\/\/ of the graph.\n\tpred map[int64][]graph.Node\n\n\t\/\/ semi[w] is a number defined as follows:\n\t\/\/ (i)   Before vertex w is numbered, semi[w] = 0, false.\n\t\/\/ (ii)  After w is numbered but before its semidominator\n\t\/\/       is computed, semi[w] is the number of w.\n\t\/\/ (iii) After the semidominator of w is computed, semi[w]\n\t\/\/       is the number of the semidominator of w.\n\tsemi map[int64]int\n\n\t\/\/ vertex[i] is the vertex whose number is i.\n\tvertex []graph.Node\n\n\t\/\/ bucket[w] is the set of vertices whose\n\t\/\/ semidominator is w.\n\tbucket map[int64]set.Nodes\n\n\t\/\/ dom[w] is vertex defined as follows:\n\t\/\/ (i)  After step 3, if the semidominator of w is its\n\t\/\/      immediate dominator, then dom[w] is the immediate\n\t\/\/      dominator of w. Otherwise dom[w] is a vertex v\n\t\/\/      whose number is smaller than w and whose immediate\n\t\/\/      dominator is also w's immediate dominator.\n\t\/\/ (ii) After step 4, dom[w] is the immediate dominator of w.\n\tdom map[int64]graph.Node\n\n\t\/\/ In general ancestor[v] = 0 only if v is a tree root\n\t\/\/ in the forest; otherwise ancestor[v] is an ancestor\n\t\/\/ of v in the forest.\n\tancestor map[int64]graph.Node\n\n\t\/\/ Initially label[v] is v.\n\tlabel map[int64]graph.Node\n\n\tn int\n}\n\nfunc (lt *lengauerTarjan) dfs(g graph.Directed, v graph.Node) {\n\tvid := v.ID()\n\tlt.n++\n\tlt.semi[vid] = lt.n\n\tlt.label[vid] = v\n\tlt.vertex = append(lt.vertex, v)\n\tfor _, w := range g.From(v) {\n\t\twid := w.ID()\n\t\tif _, ok := lt.semi[wid]; !ok {\n\t\t\tlt.parent[wid] = v\n\t\t\tlt.dfs(g, w)\n\t\t}\n\t\tlt.pred[wid] = append(lt.pred[wid], v)\n\t}\n}\n\nfunc (lt *lengauerTarjan) compress(v graph.Node) {\n\tvid := v.ID()\n\tif _, ok := lt.ancestor[lt.ancestor[vid].ID()]; ok {\n\t\tlt.compress(lt.ancestor[vid])\n\t\tif lt.semi[lt.label[lt.ancestor[vid].ID()].ID()] < lt.semi[lt.label[vid].ID()] {\n\t\t\tlt.label[vid] = lt.label[lt.ancestor[vid].ID()]\n\t\t}\n\t\tlt.ancestor[vid] = lt.ancestor[lt.ancestor[vid].ID()]\n\t}\n}\n\nfunc (lt *lengauerTarjan) eval(v graph.Node) graph.Node {\n\tvid := v.ID()\n\tif _, ok := lt.ancestor[vid]; !ok {\n\t\treturn v\n\t}\n\tlt.compress(v)\n\treturn lt.label[vid]\n}\n\nfunc (lt *lengauerTarjan) link(v, w graph.Node) {\n\tlt.ancestor[w.ID()] = v\n}\n<commit_msg>graph\/path: replace recursive dfs with iterative implementation<commit_after>\/\/ Copyright ©2017 The gonum Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage path\n\nimport (\n\t\"gonum.org\/v1\/gonum\/graph\"\n\t\"gonum.org\/v1\/gonum\/graph\/internal\/set\"\n\t\"gonum.org\/v1\/gonum\/graph\/traverse\"\n)\n\n\/\/ Dominators returns immediate dominators for all nodes in the flow graph\n\/\/ g starting from the given root node.\nfunc Dominators(root graph.Node, g graph.Directed) map[int64]graph.Node {\n\t\/\/ The algorithm used here is the Lengauer and Tarjan\n\t\/\/ algorithm described in https:\/\/doi.org\/10.1145%2F357062.357071\n\n\tlt := lengauerTarjan{\n\t\tparent: make(map[int64]graph.Node),\n\t\tpred:   make(map[int64][]graph.Node),\n\t\tsemi:   make(map[int64]int),\n\t\tvertex: make([]graph.Node, 1), \/\/ FIXME(kortschak): The current implementation requires non-zero node numbers.\n\t\tbucket: make(map[int64]set.Nodes),\n\t\tdom:    make(map[int64]graph.Node),\n\n\t\tancestor: make(map[int64]graph.Node),\n\t\tlabel:    make(map[int64]graph.Node),\n\t}\n\n\t\/\/ step 1.\n\tlt.dfs(g, root)\n\n\tfor i := len(lt.vertex) - 1; i >= 2; i-- {\n\t\tw := lt.vertex[i]\n\t\twid := w.ID()\n\t\t\/\/ step 2.\n\t\tfor _, v := range lt.pred[wid] {\n\t\t\tuid := lt.eval(v).ID()\n\t\t\tif lt.semi[uid] < lt.semi[wid] {\n\t\t\t\tlt.semi[wid] = lt.semi[uid]\n\t\t\t}\n\t\t}\n\n\t\tb, ok := lt.bucket[lt.vertex[lt.semi[wid]].ID()]\n\t\tif !ok {\n\t\t\tb = make(set.Nodes)\n\t\t\tlt.bucket[lt.vertex[lt.semi[wid]].ID()] = b\n\t\t}\n\t\tb.Add(w)\n\t\tlt.link(lt.parent[wid], w)\n\n\t\t\/\/ step 3.\n\t\tfor _, v := range lt.bucket[lt.parent[wid].ID()] {\n\t\t\tvid := v.ID()\n\t\t\tlt.bucket[lt.parent[wid].ID()].Remove(v)\n\t\t\tu := lt.eval(v)\n\t\t\tif lt.semi[u.ID()] < lt.semi[vid] {\n\t\t\t\tlt.dom[vid] = u\n\t\t\t} else {\n\t\t\t\tlt.dom[vid] = lt.parent[wid]\n\t\t\t}\n\t\t}\n\n\t}\n\n\t\/\/ step 4.\n\tfor _, w := range lt.vertex[2:] {\n\t\twid := w.ID()\n\t\tif lt.dom[wid].ID() != lt.vertex[lt.semi[wid]].ID() {\n\t\t\tlt.dom[wid] = lt.dom[lt.dom[wid].ID()]\n\t\t}\n\t}\n\tdelete(lt.dom, root.ID())\n\n\treturn lt.dom\n}\n\ntype lengauerTarjan struct {\n\t\/\/ The vertex which is the parent of vertex w\n\t\/\/ in the spanning tree generated by the search.\n\tparent map[int64]graph.Node\n\n\t\/\/ The set of vertices v such that (v, w) is an edge\n\t\/\/ of the graph.\n\tpred map[int64][]graph.Node\n\n\t\/\/ semi[w] is a number defined as follows:\n\t\/\/ (i)   Before vertex w is numbered, semi[w] = 0, false.\n\t\/\/ (ii)  After w is numbered but before its semidominator\n\t\/\/       is computed, semi[w] is the number of w.\n\t\/\/ (iii) After the semidominator of w is computed, semi[w]\n\t\/\/       is the number of the semidominator of w.\n\tsemi map[int64]int\n\n\t\/\/ vertex[i] is the vertex whose number is i.\n\tvertex []graph.Node\n\n\t\/\/ bucket[w] is the set of vertices whose\n\t\/\/ semidominator is w.\n\tbucket map[int64]set.Nodes\n\n\t\/\/ dom[w] is vertex defined as follows:\n\t\/\/ (i)  After step 3, if the semidominator of w is its\n\t\/\/      immediate dominator, then dom[w] is the immediate\n\t\/\/      dominator of w. Otherwise dom[w] is a vertex v\n\t\/\/      whose number is smaller than w and whose immediate\n\t\/\/      dominator is also w's immediate dominator.\n\t\/\/ (ii) After step 4, dom[w] is the immediate dominator of w.\n\tdom map[int64]graph.Node\n\n\t\/\/ In general ancestor[v] = 0 only if v is a tree root\n\t\/\/ in the forest; otherwise ancestor[v] is an ancestor\n\t\/\/ of v in the forest.\n\tancestor map[int64]graph.Node\n\n\t\/\/ Initially label[v] is v.\n\tlabel map[int64]graph.Node\n}\n\nfunc (lt *lengauerTarjan) dfs(g graph.Directed, root graph.Node) {\n\tdf := traverse.DepthFirst{EdgeFilter: func(e graph.Edge) bool {\n\t\tu := e.From()\n\t\tvid := e.To().ID()\n\t\tlt.pred[vid] = append(lt.pred[vid], u)\n\t\tif _, ok := lt.semi[vid]; ok {\n\t\t\treturn false\n\t\t}\n\t\tlt.parent[vid] = u\n\t\treturn true\n\t}}\n\tdf.Walk(g, root, func(u graph.Node) bool {\n\t\tuid := u.ID()\n\t\tlt.label[uid] = u\n\t\tlt.semi[uid] = len(lt.vertex)\n\t\tlt.vertex = append(lt.vertex, u)\n\t\treturn false\n\t})\n}\n\nfunc (lt *lengauerTarjan) compress(v graph.Node) {\n\tvid := v.ID()\n\tif _, ok := lt.ancestor[lt.ancestor[vid].ID()]; ok {\n\t\tlt.compress(lt.ancestor[vid])\n\t\tif lt.semi[lt.label[lt.ancestor[vid].ID()].ID()] < lt.semi[lt.label[vid].ID()] {\n\t\t\tlt.label[vid] = lt.label[lt.ancestor[vid].ID()]\n\t\t}\n\t\tlt.ancestor[vid] = lt.ancestor[lt.ancestor[vid].ID()]\n\t}\n}\n\nfunc (lt *lengauerTarjan) eval(v graph.Node) graph.Node {\n\tvid := v.ID()\n\tif _, ok := lt.ancestor[vid]; !ok {\n\t\treturn v\n\t}\n\tlt.compress(v)\n\treturn lt.label[vid]\n}\n\nfunc (lt *lengauerTarjan) link(v, w graph.Node) {\n\tlt.ancestor[w.ID()] = v\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"os\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/rackerlabs\/libcarina\"\n\t\"github.com\/rgbkrk\/interlocarina\/plugins\"\n\t\"github.com\/rgbkrk\/interlocarina\/version\"\n)\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"interlock\"\n\tapp.Version = version.FullVersion()\n\tapp.Author = \"@rgbkrk\"\n\tapp.Email = \"\"\n\tapp.Usage = \"event driven docker plugins\"\n\tapp.Before = func(c *cli.Context) error {\n\t\tif c.GlobalBool(\"debug\") {\n\t\t\tlog.SetLevel(log.DebugLevel)\n\t\t}\n\t\treturn nil\n\t}\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"username\",\n\t\t\tUsage: \"carina username\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"api-key\",\n\t\t\tUsage: \"carina API key\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"clustername\",\n\t\t\tUsage: \"name of the swarm cluster\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"endpoint\",\n\t\t\tValue: libcarina.BetaEndpoint,\n\t\t\tUsage: \"endpoint for carina\",\n\t\t},\n\t\tcli.StringSliceFlag{\n\t\t\tName:  \"plugin, p\",\n\t\t\tUsage: \"enable plugin\",\n\t\t\tValue: &cli.StringSlice{},\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"debug, D\",\n\t\t\tUsage: \"enable debug\",\n\t\t},\n\t}\n\t\/\/ base commands\n\tbaseCommands := []cli.Command{\n\t\t{\n\t\t\tName:   \"start\",\n\t\t\tAction: cmdStart,\n\t\t},\n\t\t{\n\t\t\tName:   \"list-plugins\",\n\t\t\tAction: cmdListPlugins,\n\t\t},\n\t\t{\n\t\t\tName:   \"info\",\n\t\t\tAction: cmdInfo,\n\t\t},\n\t}\n\t\/\/ plugin supplied commands\n\tbaseCommands = append(baseCommands, plugins.GetCommands()...)\n\n\tapp.Commands = baseCommands\n\n\tif err := app.Run(os.Args); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>Alias apikey anyway.<commit_after>package main\n\nimport (\n\t\"os\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/rackerlabs\/libcarina\"\n\t\"github.com\/rgbkrk\/interlocarina\/plugins\"\n\t\"github.com\/rgbkrk\/interlocarina\/version\"\n)\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"interlock\"\n\tapp.Version = version.FullVersion()\n\tapp.Author = \"@rgbkrk\"\n\tapp.Email = \"\"\n\tapp.Usage = \"event driven docker plugins\"\n\tapp.Before = func(c *cli.Context) error {\n\t\tif c.GlobalBool(\"debug\") {\n\t\t\tlog.SetLevel(log.DebugLevel)\n\t\t}\n\t\treturn nil\n\t}\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"username\",\n\t\t\tUsage: \"carina username\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"api-key, apikey\",\n\t\t\tUsage: \"carina API key\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"clustername\",\n\t\t\tUsage: \"name of the swarm cluster\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"endpoint\",\n\t\t\tValue: libcarina.BetaEndpoint,\n\t\t\tUsage: \"endpoint for carina\",\n\t\t},\n\t\tcli.StringSliceFlag{\n\t\t\tName:  \"plugin, p\",\n\t\t\tUsage: \"enable plugin\",\n\t\t\tValue: &cli.StringSlice{},\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"debug, D\",\n\t\t\tUsage: \"enable debug\",\n\t\t},\n\t}\n\t\/\/ base commands\n\tbaseCommands := []cli.Command{\n\t\t{\n\t\t\tName:   \"start\",\n\t\t\tAction: cmdStart,\n\t\t},\n\t\t{\n\t\t\tName:   \"list-plugins\",\n\t\t\tAction: cmdListPlugins,\n\t\t},\n\t\t{\n\t\t\tName:   \"info\",\n\t\t\tAction: cmdInfo,\n\t\t},\n\t}\n\t\/\/ plugin supplied commands\n\tbaseCommands = append(baseCommands, plugins.GetCommands()...)\n\n\tapp.Commands = baseCommands\n\n\tif err := app.Run(os.Args); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package internal provides support for package cloud.\n\/\/\n\/\/ Users should not import this package directly.\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n)\n\nconst userAgent = \"gcloud-golang\/0.1\"\n\n\/\/ UATransport is an http.RoundTripper that appends\n\/\/ Google Cloud client's user-agent to the original\n\/\/ request's user-agent header.\ntype UATransport struct {\n\t\/\/ Base represents the actual http.RoundTripper\n\t\/\/ the requests will be delegated to.\n\tBase http.RoundTripper\n}\n\n\/\/ RoundTrip appends a user-agent to the existing user-agent\n\/\/ header and delegates the request to the base http.RoundTripper.\nfunc (t *UATransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\t\/\/ TODO(jbd): Is it OK to mutate request? UATransport is internal only.\n\tua := req.Header.Get(\"User-Agent\")\n\tif ua == \"\" {\n\t\tua = userAgent\n\t} else {\n\t\tua = fmt.Sprintf(\"%s;%s\", ua, userAgent)\n\t}\n\treq.Header.Set(\"User-Agent\", ua)\n\treturn t.Base.RoundTrip(req)\n}\n<commit_msg>storage: UATransport shouldn't mutate the request.<commit_after>\/\/ Copyright 2014 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package internal provides support for package cloud.\n\/\/\n\/\/ Users should not import this package directly.\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n)\n\nconst userAgent = \"gcloud-golang\/0.1\"\n\n\/\/ UATransport is an http.RoundTripper that appends\n\/\/ Google Cloud client's user-agent to the original\n\/\/ request's user-agent header.\ntype UATransport struct {\n\t\/\/ Base represents the actual http.RoundTripper\n\t\/\/ the requests will be delegated to.\n\tBase http.RoundTripper\n}\n\n\/\/ RoundTrip appends a user-agent to the existing user-agent\n\/\/ header and delegates the request to the base http.RoundTripper.\nfunc (t *UATransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\treq = cloneRequest(req)\n\tua := req.Header.Get(\"User-Agent\")\n\tif ua == \"\" {\n\t\tua = userAgent\n\t} else {\n\t\tua = fmt.Sprintf(\"%s;%s\", ua, userAgent)\n\t}\n\treq.Header.Set(\"User-Agent\", ua)\n\treturn t.Base.RoundTrip(req)\n}\n\n\/\/ cloneRequest returns a clone of the provided *http.Request.\n\/\/ The clone is a shallow copy of the struct and its Header map.\nfunc cloneRequest(r *http.Request) *http.Request {\n\t\/\/ shallow copy of the struct\n\tr2 := new(http.Request)\n\t*r2 = *r\n\t\/\/ deep copy of the Header\n\tr2.Header = make(http.Header)\n\tfor k, s := range r.Header {\n\t\tr2.Header[k] = s\n\t}\n\treturn r2\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\n\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"context\"\n\t\"crypto\/sha512\"\n\t\"database\/sql\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\n\t\"github.com\/apache\/incubator-trafficcontrol\/lib\/go-log\"\n\ttc \"github.com\/apache\/incubator-trafficcontrol\/lib\/go-tc\"\n\t\"github.com\/apache\/incubator-trafficcontrol\/traffic_ops\/tocookie\"\n)\n\nconst ServerName = \"traffic_ops_golang\" + \"\/\" + Version\n\ntype AuthBase struct {\n\tnoAuth        bool\n\tsecret        string\n\tprivLevelStmt *sql.Stmt\n\toverride      Middleware\n}\n\nfunc (a AuthBase) GetWrapper(privLevelRequired int) Middleware {\n\tif a.override != nil {\n\t\treturn a.override\n\t}\n\treturn func(handlerFunc http.HandlerFunc) http.HandlerFunc {\n\t\tif a.noAuth {\n\t\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tctx := r.Context()\n\t\t\t\tctx = context.WithValue(ctx, UserNameKey, \"-\")\n\t\t\t\tctx = context.WithValue(ctx, PrivLevelKey, PrivLevelInvalid)\n\t\t\t\thandlerFunc(w, r.WithContext(ctx))\n\t\t\t}\n\t\t}\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\/\/ TODO remove, and make username available to wrapLogTime\n\t\t\tstart := time.Now()\n\t\t\tiw := &Interceptor{w: w}\n\t\t\tw = iw\n\t\t\tusername := \"-\"\n\t\t\tdefer func() {\n\t\t\t\tlog.EventfRaw(`%s - %s [%s] \"%v %v HTTP\/1.1\" %v %v %v \"%v\"`, r.RemoteAddr, username, time.Now().Format(AccessLogTimeFormat), r.Method, r.URL.Path, iw.code, iw.byteCount, int(time.Now().Sub(start)\/time.Millisecond), r.UserAgent())\n\t\t\t}()\n\n\t\t\thandleUnauthorized := func(reason string) {\n\t\t\t\tstatus := http.StatusUnauthorized\n\t\t\t\tw.WriteHeader(status)\n\t\t\t\tfmt.Fprintf(w, http.StatusText(status))\n\t\t\t\tlog.Infof(\"%v %v %v %v returned unauthorized: %v\\n\", r.RemoteAddr, r.Method, r.URL.Path, username, reason)\n\t\t\t}\n\n\t\t\tcookie, err := r.Cookie(tocookie.Name)\n\t\t\tif err != nil {\n\t\t\t\thandleUnauthorized(\"error getting cookie: \" + err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif cookie == nil {\n\t\t\t\thandleUnauthorized(\"no auth cookie\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\toldCookie, err := tocookie.Parse(a.secret, cookie.Value)\n\t\t\tif err != nil {\n\t\t\t\thandleUnauthorized(\"cookie error: \" + err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tusername = oldCookie.AuthData\n\t\t\tprivLevel := PrivLevel(a.privLevelStmt, username)\n\t\t\tif privLevel < privLevelRequired {\n\t\t\t\thandleUnauthorized(\"insufficient privileges\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tnewCookieVal := tocookie.Refresh(oldCookie, a.secret)\n\t\t\thttp.SetCookie(w, &http.Cookie{Name: tocookie.Name, Value: newCookieVal, Path: \"\/\", HttpOnly: true})\n\n\t\t\tctx := r.Context()\n\t\t\tctx = context.WithValue(ctx, UserNameKey, username)\n\t\t\tctx = context.WithValue(ctx, PrivLevelKey, privLevel)\n\n\t\t\thandlerFunc(w, r.WithContext(ctx))\n\t\t}\n\t}\n}\n\nfunc wrapHeaders(h http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept, Set-Cookie, Cookie\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST,GET,OPTIONS,PUT,DELETE\")\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"X-Server-Name\", ServerName)\n\t\tiw := &BodyInterceptor{w: w}\n\t\th(iw, r)\n\n\t\tsha := sha512.Sum512(iw.Body())\n\t\tw.Header().Set(\"Whole-Content-SHA512\", base64.StdEncoding.EncodeToString(sha[:]))\n\n\t\tgzipResponse(w, r, iw.Body())\n\n\t}\n}\n\nconst AccessLogTimeFormat = \"02\/Jan\/2006:15:04:05 -0700\"\n\nfunc wrapAccessLog(secret string, h http.Handler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tiw := &Interceptor{w: w}\n\t\tuser := \"-\"\n\t\tcookie, err := r.Cookie(tocookie.Name)\n\t\tif err == nil && cookie != nil {\n\t\t\tcookie, err := tocookie.Parse(secret, cookie.Value)\n\t\t\tif err == nil {\n\t\t\t\tuser = cookie.AuthData\n\t\t\t}\n\t\t}\n\t\tstart := time.Now()\n\t\tdefer func() {\n\t\t\tlog.EventfRaw(`%s - %s [%s] \"%v %v HTTP\/1.1\" %v %v %v \"%v\"`, r.RemoteAddr, user, time.Now().Format(AccessLogTimeFormat), r.Method, r.URL.Path, iw.code, iw.byteCount, int(time.Now().Sub(start)\/time.Millisecond), r.UserAgent())\n\t\t}()\n\t\th.ServeHTTP(iw, r)\n\t}\n}\n\n\/\/ gzipResponse takes a function which cannot error and returns only bytes, and wraps it as a http.HandlerFunc. The errContext is logged if the write fails, and should be enough information to trace the problem (function name, endpoint, request parameters, etc).\nfunc gzipResponse(w http.ResponseWriter, r *http.Request, bytes []byte) {\n\n\tbytes, err := gzipIfAccepts(r, w, bytes)\n\tif err != nil {\n\t\tlog.Errorf(\"gzipping request '%v': %v\\n\", r.URL.EscapedPath(), err)\n\t\tcode := http.StatusInternalServerError\n\t\tw.WriteHeader(code)\n\t\tif _, err := w.Write([]byte(http.StatusText(code))); err != nil {\n\t\t\tlog.Warnf(\"received error writing data request %v: %v\\n\", r.URL.EscapedPath(), err)\n\t\t}\n\t\treturn\n\t}\n\n\tw.Write(bytes)\n}\n\n\/\/ wrapBytes takes a function which cannot error and returns only bytes, and wraps it as a http.HandlerFunc. The errContext is logged if the write fails, and should be enough information to trace the problem (function name, endpoint, request parameters, etc).\n\/\/TODO: drichardson - refactor these to a generic area\nfunc wrapBytes(f func() []byte, contentType string) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tbytes := f()\n\t\tbytes, err := gzipIfAccepts(r, w, bytes)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"gzipping request '%v': %v\\n\", r.URL.EscapedPath(), err)\n\t\t\tcode := http.StatusInternalServerError\n\t\t\tw.WriteHeader(code)\n\t\t\tif _, err := w.Write([]byte(http.StatusText(code))); err != nil {\n\t\t\t\tlog.Warnf(\"received error writing data request %v: %v\\n\", r.URL.EscapedPath(), err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(tc.ContentType, contentType)\n\t\tlog.Write(w, bytes, r.URL.EscapedPath())\n\t}\n}\n\n\/\/ gzipIfAccepts gzips the given bytes, writes a `Content-Encoding: gzip` header to the given writer, and returns the gzipped bytes, if the Request supports GZip (has an Accept-Encoding header). Else, returns the bytes unmodified. Note the given bytes are NOT written to the given writer. It is assumed the bytes may need to pass thru other middleware before being written.\n\/\/TODO: drichardson - refactor these to a generic area\nfunc gzipIfAccepts(r *http.Request, w http.ResponseWriter, b []byte) ([]byte, error) {\n\t\/\/ TODO this could be made more efficient by wrapping ResponseWriter with the GzipWriter, and letting callers writer directly to it - but then we'd have to deal with Closing the gzip.Writer.\n\tif len(b) == 0 || !acceptsGzip(r) {\n\t\treturn b, nil\n\t}\n\tw.Header().Set(tc.ContentEncoding, tc.Gzip)\n\n\tbuf := bytes.Buffer{}\n\tzw := gzip.NewWriter(&buf)\n\n\tif _, err := zw.Write(b); err != nil {\n\t\treturn nil, fmt.Errorf(\"gzipping bytes: %v\", err)\n\t}\n\n\tif err := zw.Close(); err != nil {\n\t\treturn nil, fmt.Errorf(\"closing gzip writer: %v\", err)\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\nfunc acceptsGzip(r *http.Request) bool {\n\tencodingHeaders := r.Header[\"Accept-Encoding\"] \/\/ headers are case-insensitive, but Go promises to Canonical-Case requests\n\tfor _, encodingHeader := range encodingHeaders {\n\t\tencodingHeader = stripAllWhitespace(encodingHeader)\n\t\tencodings := strings.Split(encodingHeader, \",\")\n\t\tfor _, encoding := range encodings {\n\t\t\tif strings.ToLower(encoding) == tc.Gzip { \/\/ encoding is case-insensitive, per the RFC\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc stripAllWhitespace(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif unicode.IsSpace(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\ntype Interceptor struct {\n\tw         http.ResponseWriter\n\tcode      int\n\tbyteCount int\n}\n\nfunc (i *Interceptor) WriteHeader(rc int) {\n\ti.w.WriteHeader(rc)\n\ti.code = rc\n}\n\nfunc (i *Interceptor) Write(b []byte) (int, error) {\n\twi, werr := i.w.Write(b)\n\ti.byteCount += wi\n\tif i.code == 0 {\n\t\ti.code = 200\n\t}\n\treturn wi, werr\n}\n\nfunc (i *Interceptor) Header() http.Header {\n\treturn i.w.Header()\n}\n\n\/\/ BodyInterceptor fulfills the Writer interface, but records the body and doesn't actually write. This allows performing operations on the entire body written by a handler, for example, compressing or hashing. To actually write, call `RealWrite()`. Note this means `len(b)` and `nil` are always returned by `Write()`, any real write errors will be returned by `RealWrite()`.\ntype BodyInterceptor struct {\n\tw    http.ResponseWriter\n\tbody []byte\n}\n\nfunc (i *BodyInterceptor) WriteHeader(rc int) {\n\ti.w.WriteHeader(rc)\n}\nfunc (i *BodyInterceptor) Write(b []byte) (int, error) {\n\ti.body = append(i.body, b...)\n\treturn len(b), nil\n}\nfunc (i *BodyInterceptor) Header() http.Header {\n\treturn i.w.Header()\n}\nfunc (i *BodyInterceptor) RealWrite(b []byte) (int, error) {\n\twi, werr := i.w.Write(i.body)\n\treturn wi, werr\n}\nfunc (i *BodyInterceptor) Body() []byte {\n\treturn i.body\n}\n<commit_msg>remove unused wrapBytes<commit_after>package main\n\n\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"context\"\n\t\"crypto\/sha512\"\n\t\"database\/sql\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\"\n\n\t\"github.com\/apache\/incubator-trafficcontrol\/lib\/go-log\"\n\ttc \"github.com\/apache\/incubator-trafficcontrol\/lib\/go-tc\"\n\t\"github.com\/apache\/incubator-trafficcontrol\/traffic_ops\/tocookie\"\n)\n\nconst ServerName = \"traffic_ops_golang\" + \"\/\" + Version\n\ntype AuthBase struct {\n\tnoAuth        bool\n\tsecret        string\n\tprivLevelStmt *sql.Stmt\n\toverride      Middleware\n}\n\nfunc (a AuthBase) GetWrapper(privLevelRequired int) Middleware {\n\tif a.override != nil {\n\t\treturn a.override\n\t}\n\treturn func(handlerFunc http.HandlerFunc) http.HandlerFunc {\n\t\tif a.noAuth {\n\t\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tctx := r.Context()\n\t\t\t\tctx = context.WithValue(ctx, UserNameKey, \"-\")\n\t\t\t\tctx = context.WithValue(ctx, PrivLevelKey, PrivLevelInvalid)\n\t\t\t\thandlerFunc(w, r.WithContext(ctx))\n\t\t\t}\n\t\t}\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\/\/ TODO remove, and make username available to wrapLogTime\n\t\t\tstart := time.Now()\n\t\t\tiw := &Interceptor{w: w}\n\t\t\tw = iw\n\t\t\tusername := \"-\"\n\t\t\tdefer func() {\n\t\t\t\tlog.EventfRaw(`%s - %s [%s] \"%v %v HTTP\/1.1\" %v %v %v \"%v\"`, r.RemoteAddr, username, time.Now().Format(AccessLogTimeFormat), r.Method, r.URL.Path, iw.code, iw.byteCount, int(time.Now().Sub(start)\/time.Millisecond), r.UserAgent())\n\t\t\t}()\n\n\t\t\thandleUnauthorized := func(reason string) {\n\t\t\t\tstatus := http.StatusUnauthorized\n\t\t\t\tw.WriteHeader(status)\n\t\t\t\tfmt.Fprintf(w, http.StatusText(status))\n\t\t\t\tlog.Infof(\"%v %v %v %v returned unauthorized: %v\\n\", r.RemoteAddr, r.Method, r.URL.Path, username, reason)\n\t\t\t}\n\n\t\t\tcookie, err := r.Cookie(tocookie.Name)\n\t\t\tif err != nil {\n\t\t\t\thandleUnauthorized(\"error getting cookie: \" + err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif cookie == nil {\n\t\t\t\thandleUnauthorized(\"no auth cookie\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\toldCookie, err := tocookie.Parse(a.secret, cookie.Value)\n\t\t\tif err != nil {\n\t\t\t\thandleUnauthorized(\"cookie error: \" + err.Error())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tusername = oldCookie.AuthData\n\t\t\tprivLevel := PrivLevel(a.privLevelStmt, username)\n\t\t\tif privLevel < privLevelRequired {\n\t\t\t\thandleUnauthorized(\"insufficient privileges\")\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tnewCookieVal := tocookie.Refresh(oldCookie, a.secret)\n\t\t\thttp.SetCookie(w, &http.Cookie{Name: tocookie.Name, Value: newCookieVal, Path: \"\/\", HttpOnly: true})\n\n\t\t\tctx := r.Context()\n\t\t\tctx = context.WithValue(ctx, UserNameKey, username)\n\t\t\tctx = context.WithValue(ctx, PrivLevelKey, privLevel)\n\n\t\t\thandlerFunc(w, r.WithContext(ctx))\n\t\t}\n\t}\n}\n\nfunc wrapHeaders(h http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Header().Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Origin, X-Requested-With, Content-Type, Accept, Set-Cookie, Cookie\")\n\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST,GET,OPTIONS,PUT,DELETE\")\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"X-Server-Name\", ServerName)\n\t\tiw := &BodyInterceptor{w: w}\n\t\th(iw, r)\n\n\t\tsha := sha512.Sum512(iw.Body())\n\t\tw.Header().Set(\"Whole-Content-SHA512\", base64.StdEncoding.EncodeToString(sha[:]))\n\n\t\tgzipResponse(w, r, iw.Body())\n\n\t}\n}\n\nconst AccessLogTimeFormat = \"02\/Jan\/2006:15:04:05 -0700\"\n\nfunc wrapAccessLog(secret string, h http.Handler) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tiw := &Interceptor{w: w}\n\t\tuser := \"-\"\n\t\tcookie, err := r.Cookie(tocookie.Name)\n\t\tif err == nil && cookie != nil {\n\t\t\tcookie, err := tocookie.Parse(secret, cookie.Value)\n\t\t\tif err == nil {\n\t\t\t\tuser = cookie.AuthData\n\t\t\t}\n\t\t}\n\t\tstart := time.Now()\n\t\tdefer func() {\n\t\t\tlog.EventfRaw(`%s - %s [%s] \"%v %v HTTP\/1.1\" %v %v %v \"%v\"`, r.RemoteAddr, user, time.Now().Format(AccessLogTimeFormat), r.Method, r.URL.Path, iw.code, iw.byteCount, int(time.Now().Sub(start)\/time.Millisecond), r.UserAgent())\n\t\t}()\n\t\th.ServeHTTP(iw, r)\n\t}\n}\n\n\/\/ gzipResponse takes a function which cannot error and returns only bytes, and wraps it as a http.HandlerFunc. The errContext is logged if the write fails, and should be enough information to trace the problem (function name, endpoint, request parameters, etc).\nfunc gzipResponse(w http.ResponseWriter, r *http.Request, bytes []byte) {\n\n\tbytes, err := gzipIfAccepts(r, w, bytes)\n\tif err != nil {\n\t\tlog.Errorf(\"gzipping request '%v': %v\\n\", r.URL.EscapedPath(), err)\n\t\tcode := http.StatusInternalServerError\n\t\tw.WriteHeader(code)\n\t\tif _, err := w.Write([]byte(http.StatusText(code))); err != nil {\n\t\t\tlog.Warnf(\"received error writing data request %v: %v\\n\", r.URL.EscapedPath(), err)\n\t\t}\n\t\treturn\n\t}\n\n\tw.Write(bytes)\n}\n\n\/\/ gzipIfAccepts gzips the given bytes, writes a `Content-Encoding: gzip` header to the given writer, and returns the gzipped bytes, if the Request supports GZip (has an Accept-Encoding header). Else, returns the bytes unmodified. Note the given bytes are NOT written to the given writer. It is assumed the bytes may need to pass thru other middleware before being written.\n\/\/TODO: drichardson - refactor these to a generic area\nfunc gzipIfAccepts(r *http.Request, w http.ResponseWriter, b []byte) ([]byte, error) {\n\t\/\/ TODO this could be made more efficient by wrapping ResponseWriter with the GzipWriter, and letting callers writer directly to it - but then we'd have to deal with Closing the gzip.Writer.\n\tif len(b) == 0 || !acceptsGzip(r) {\n\t\treturn b, nil\n\t}\n\tw.Header().Set(tc.ContentEncoding, tc.Gzip)\n\n\tbuf := bytes.Buffer{}\n\tzw := gzip.NewWriter(&buf)\n\n\tif _, err := zw.Write(b); err != nil {\n\t\treturn nil, fmt.Errorf(\"gzipping bytes: %v\", err)\n\t}\n\n\tif err := zw.Close(); err != nil {\n\t\treturn nil, fmt.Errorf(\"closing gzip writer: %v\", err)\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\nfunc acceptsGzip(r *http.Request) bool {\n\tencodingHeaders := r.Header[\"Accept-Encoding\"] \/\/ headers are case-insensitive, but Go promises to Canonical-Case requests\n\tfor _, encodingHeader := range encodingHeaders {\n\t\tencodingHeader = stripAllWhitespace(encodingHeader)\n\t\tencodings := strings.Split(encodingHeader, \",\")\n\t\tfor _, encoding := range encodings {\n\t\t\tif strings.ToLower(encoding) == tc.Gzip { \/\/ encoding is case-insensitive, per the RFC\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\nfunc stripAllWhitespace(s string) string {\n\treturn strings.Map(func(r rune) rune {\n\t\tif unicode.IsSpace(r) {\n\t\t\treturn -1\n\t\t}\n\t\treturn r\n\t}, s)\n}\n\ntype Interceptor struct {\n\tw         http.ResponseWriter\n\tcode      int\n\tbyteCount int\n}\n\nfunc (i *Interceptor) WriteHeader(rc int) {\n\ti.w.WriteHeader(rc)\n\ti.code = rc\n}\n\nfunc (i *Interceptor) Write(b []byte) (int, error) {\n\twi, werr := i.w.Write(b)\n\ti.byteCount += wi\n\tif i.code == 0 {\n\t\ti.code = 200\n\t}\n\treturn wi, werr\n}\n\nfunc (i *Interceptor) Header() http.Header {\n\treturn i.w.Header()\n}\n\n\/\/ BodyInterceptor fulfills the Writer interface, but records the body and doesn't actually write. This allows performing operations on the entire body written by a handler, for example, compressing or hashing. To actually write, call `RealWrite()`. Note this means `len(b)` and `nil` are always returned by `Write()`, any real write errors will be returned by `RealWrite()`.\ntype BodyInterceptor struct {\n\tw    http.ResponseWriter\n\tbody []byte\n}\n\nfunc (i *BodyInterceptor) WriteHeader(rc int) {\n\ti.w.WriteHeader(rc)\n}\nfunc (i *BodyInterceptor) Write(b []byte) (int, error) {\n\ti.body = append(i.body, b...)\n\treturn len(b), nil\n}\nfunc (i *BodyInterceptor) Header() http.Header {\n\treturn i.w.Header()\n}\nfunc (i *BodyInterceptor) RealWrite(b []byte) (int, error) {\n\twi, werr := i.w.Write(i.body)\n\treturn wi, werr\n}\nfunc (i *BodyInterceptor) Body() []byte {\n\treturn i.body\n}\n<|endoftext|>"}
{"text":"<commit_before>package haaasd\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nvar (\n\tconfig = Config{HapHome: \"\/HOME\"}\n\thap    = NewHaproxy(\"master\",&config, \"TST\", \"DEV\", \"1.4.22\")\n)\n\nfunc TestGetReloadScript(t *testing.T) {\n\tconfig.HapHome = \"\/HOME\"\n\tresult := hap.getReloadScript()\n\texpected := \"\/HOME\/TST\/scripts\/hapctlTSTDEV\"\n\tAssertEquals(t, expected, result)\n}\n\nfunc TestCreateSkeleton(t *testing.T) {\n\ttmpdir, _ := ioutil.TempDir(\"\", \"haaas\")\n\tdefer os.Remove(tmpdir)\n\tconfig.HapHome = tmpdir\n\thap.createSkeleton(\"mycorrelationid\")\n\tAssertFileExists(t, tmpdir+\"\/TST\/Config\")\n\tAssertFileExists(t, tmpdir+\"\/TST\/logs\/TSTDEV\")\n\tAssertFileExists(t, tmpdir+\"\/TST\/scripts\")\n\tAssertFileExists(t, tmpdir+\"\/TST\/version-1\")\n\tif runtime.GOOS != \"windows\" {\n\t\tAssertIsSymlink(t, tmpdir+\"\/TST\/Config\/haproxy\")\n\t\tAssertIsSymlink(t, tmpdir+\"\/TST\/scripts\/hapctlTSTDEV\")\n\t}\n}\n\nfunc TestArchivePath(t *testing.T) {\n\tconfig.HapHome = \"\/HOME\"\n\tresult := hap.confArchivePath()\n\texpected := \"\/HOME\/TST\/version-1\/hapTSTDEV.conf\"\n\tAssertEquals(t, expected, result)\n}\n\nfunc AssertFileExists(t *testing.T, file string) {\n\tif _, err := os.Stat(file); os.IsNotExist(err) {\n\t\tt.Logf(\"File or directory '%s' does not exists\", file)\n\t\tt.Fail()\n\t}\n}\n\nfunc AssertIsSymlink(t *testing.T, file string) {\n\tfi, err := os.Lstat(file)\n\tif err != nil || (fi.Mode()&os.ModeSymlink != os.ModeSymlink) {\n\t\tt.Logf(\"File or directory '%s' does not exists\", file)\n\t\tt.Fail()\n\t}\n}\n\nfunc AssertEquals(t *testing.T, expected interface{}, result interface{}) {\n\tif result != expected {\n\t\tt.Logf(\"Expected '%s', got '%s'\", expected, result)\n\t\tt.Fail()\n\t}\n}\n<commit_msg>fix unit test<commit_after>package haaasd\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nvar (\n\tconfig = Config{HapHome: \"\/HOME\"}\n\thap    = NewHaproxy(\"master\",&config, \"TST\", \"DEV\", \"1.4.22\", Context{})\n)\n\nfunc TestGetReloadScript(t *testing.T) {\n\tconfig.HapHome = \"\/HOME\"\n\tresult := hap.getReloadScript()\n\texpected := \"\/HOME\/TST\/scripts\/hapctlTSTDEV\"\n\tAssertEquals(t, expected, result)\n}\n\nfunc TestCreateSkeleton(t *testing.T) {\n\ttmpdir, _ := ioutil.TempDir(\"\", \"haaas\")\n\tdefer os.Remove(tmpdir)\n\tconfig.HapHome = tmpdir\n\thap.createSkeleton(\"mycorrelationid\")\n\tAssertFileExists(t, tmpdir+\"\/TST\/Config\")\n\tAssertFileExists(t, tmpdir+\"\/TST\/logs\/TSTDEV\")\n\tAssertFileExists(t, tmpdir+\"\/TST\/scripts\")\n\tAssertFileExists(t, tmpdir+\"\/TST\/version-1\")\n\tif runtime.GOOS != \"windows\" {\n\t\tAssertIsSymlink(t, tmpdir+\"\/TST\/Config\/haproxy\")\n\t\tAssertIsSymlink(t, tmpdir+\"\/TST\/scripts\/hapctlTSTDEV\")\n\t}\n}\n\nfunc TestArchivePath(t *testing.T) {\n\tconfig.HapHome = \"\/HOME\"\n\tresult := hap.confArchivePath()\n\texpected := \"\/HOME\/TST\/version-1\/hapTSTDEV.conf\"\n\tAssertEquals(t, expected, result)\n}\n\nfunc AssertFileExists(t *testing.T, file string) {\n\tif _, err := os.Stat(file); os.IsNotExist(err) {\n\t\tt.Logf(\"File or directory '%s' does not exists\", file)\n\t\tt.Fail()\n\t}\n}\n\nfunc AssertIsSymlink(t *testing.T, file string) {\n\tfi, err := os.Lstat(file)\n\tif err != nil || (fi.Mode()&os.ModeSymlink != os.ModeSymlink) {\n\t\tt.Logf(\"File or directory '%s' does not exists\", file)\n\t\tt.Fail()\n\t}\n}\n\nfunc AssertEquals(t *testing.T, expected interface{}, result interface{}) {\n\tif result != expected {\n\t\tt.Logf(\"Expected '%s', got '%s'\", expected, result)\n\t\tt.Fail()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package wlog\n\n\/\/ PrefixUI is a wrapper for UI that prefixes all strings.\n\/\/ It does add a space betweem the prefix and message.\n\/\/ If no prefix is specified (\"\") then it does not prefix the space.\ntype PrefixUI struct {\n\tLogPrefix     string\n\tOutputPrefix  string\n\tSuccessPrefix string\n\tInfoPrefix    string\n\tErrorPrefix   string\n\tWarnPrefix    string\n\tRunningPrefix string\n\tAskPrefix     string\n\tUI            UI\n}\n\n\/\/ Log prefixes to message before writing to Writer.\n\/\/ LogPrefix is used to prefix the message.\nfunc (ui *PrefixUI) Log(message string) {\n\tif ui.LogPrefix != \"\" {\n\t\tmessage = ui.LogPrefix + \" \" + message\n\t}\n\tui.UI.Log(message)\n}\n\n\/\/ Output simply writes to Writer.\n\/\/ OutputPrefix is used to prefix the message.\nfunc (ui *PrefixUI) Output(message string) {\n\tif ui.OutputPrefix != \"\" {\n\t\tmessage = ui.OutputPrefix + \" \" + message\n\t}\n\tui.UI.Output(message)\n}\n\n\/\/ Success calls Output to write.\n\/\/ Useful when you want separate colors or prefixes.\n\/\/ SuccessPrefix is used to prefix the message.\nfunc (ui *PrefixUI) Success(message string) {\n\tif ui.SuccessPrefix != \"\" {\n\t\tmessage = ui.SuccessPrefix + \" \" + message\n\t}\n\tui.UI.Output(message)\n}\n\n\/\/ Info calls Output to write.\n\/\/ Useful when you want separate colors or prefixes.\n\/\/ InfoPrefix is used to prefix the message.\nfunc (ui *PrefixUI) Info(message string) {\n\tif ui.InfoPrefix != \"\" {\n\t\tmessage = ui.InfoPrefix + \" \" + message\n\t}\n\tui.UI.Output(message)\n}\n\n\/\/ Error writes message to ErrorWriter.\n\/\/ ErrorPrefix is used to prefix the message.\nfunc (ui *PrefixUI) Error(message string) {\n\tif ui.ErrorPrefix != \"\" {\n\t\tmessage = ui.ErrorPrefix + \" \" + message\n\t}\n\tui.UI.Error(message)\n}\n\n\/\/ Warn calls Error to write.\n\/\/ Useful when you want separate colors or prefixes.\n\/\/ WarnPrefix is used to prefix message.\nfunc (ui *PrefixUI) Warn(message string) {\n\tif ui.WarnPrefix != \"\" {\n\t\tmessage = ui.WarnPrefix + \" \" + message\n\t}\n\tui.UI.Warn(message)\n}\n\n\/\/ Running calls Output to write.\n\/\/ Useful when you want separate colors or prefixes.\n\/\/ RunningPrefix is used to prefix message.\nfunc (ui *PrefixUI) Running(message string) {\n\tif ui.RunningPrefix != \"\" {\n\t\tmessage = ui.RunningPrefix + \" \" + message\n\t}\n\tui.UI.Running(message)\n}\n\n\/\/Ask will call UI.Ask with message then wait for UI.Ask to return a response and\/or error.\n\/\/It will clean the response by removing any carriage returns and new lines that if finds.\n\/\/If a message is not used (\"\") then it will not prompt user before waiting on a response.\n\/\/AskPrefix is used to prefix message.\nfunc (ui *PrefixUI) Ask(message string) (string, error) {\n\tif ui.AskPrefix != \"\" {\n\t\tmessage = ui.AskPrefix + \" \" + message\n\t}\n\tres, err := ui.UI.Ask(message)\n\treturn res, err\n}\n<commit_msg>Fixed prefix wrapper<commit_after>package wlog\n\n\/\/ PrefixUI is a wrapper for UI that prefixes all strings.\n\/\/ It does add a space betweem the prefix and message.\n\/\/ If no prefix is specified (\"\") then it does not prefix the space.\ntype PrefixUI struct {\n\tLogPrefix     string\n\tOutputPrefix  string\n\tSuccessPrefix string\n\tInfoPrefix    string\n\tErrorPrefix   string\n\tWarnPrefix    string\n\tRunningPrefix string\n\tAskPrefix     string\n\tUI            UI\n}\n\n\/\/ Log calls UI.Log to write.\n\/\/ LogPrefix is used to prefix the message.\nfunc (ui *PrefixUI) Log(message string) {\n\tif ui.LogPrefix != \"\" {\n\t\tmessage = ui.LogPrefix + \" \" + message\n\t}\n\tui.UI.Log(message)\n}\n\n\/\/ Output calls UI.Output to write.\n\/\/ OutputPrefix is used to prefix the message.\nfunc (ui *PrefixUI) Output(message string) {\n\tif ui.OutputPrefix != \"\" {\n\t\tmessage = ui.OutputPrefix + \" \" + message\n\t}\n\tui.UI.Output(message)\n}\n\n\/\/ Success calls UI.Success to write.\n\/\/ Useful when you want separate colors or prefixes.\n\/\/ SuccessPrefix is used to prefix the message.\nfunc (ui *PrefixUI) Success(message string) {\n\tif ui.SuccessPrefix != \"\" {\n\t\tmessage = ui.SuccessPrefix + \" \" + message\n\t}\n\tui.UI.Success(message)\n}\n\n\/\/ Info calls UI.Info to write.\n\/\/ Useful when you want separate colors or prefixes.\n\/\/ InfoPrefix is used to prefix the message.\nfunc (ui *PrefixUI) Info(message string) {\n\tif ui.InfoPrefix != \"\" {\n\t\tmessage = ui.InfoPrefix + \" \" + message\n\t}\n\tui.UI.Info(message)\n}\n\n\/\/ Error call UI.Error to write.\n\/\/ ErrorPrefix is used to prefix the message.\nfunc (ui *PrefixUI) Error(message string) {\n\tif ui.ErrorPrefix != \"\" {\n\t\tmessage = ui.ErrorPrefix + \" \" + message\n\t}\n\tui.UI.Error(message)\n}\n\n\/\/ Warn calls UI.Warn to write.\n\/\/ Useful when you want separate colors or prefixes.\n\/\/ WarnPrefix is used to prefix message.\nfunc (ui *PrefixUI) Warn(message string) {\n\tif ui.WarnPrefix != \"\" {\n\t\tmessage = ui.WarnPrefix + \" \" + message\n\t}\n\tui.UI.Warn(message)\n}\n\n\/\/ Running calls Output to write.\n\/\/ Useful when you want separate colors or prefixes.\n\/\/ RunningPrefix is used to prefix message.\nfunc (ui *PrefixUI) Running(message string) {\n\tif ui.RunningPrefix != \"\" {\n\t\tmessage = ui.RunningPrefix + \" \" + message\n\t}\n\tui.UI.Running(message)\n}\n\n\/\/Ask will call UI.Ask with message then wait for UI.Ask to return a response and\/or error.\n\/\/It will clean the response by removing any carriage returns and new lines that if finds.\n\/\/If a message is not used (\"\") then it will not prompt user before waiting on a response.\n\/\/AskPrefix is used to prefix message.\nfunc (ui *PrefixUI) Ask(message string) (string, error) {\n\tif ui.AskPrefix != \"\" {\n\t\tmessage = ui.AskPrefix + \" \" + message\n\t}\n\tres, err := ui.UI.Ask(message)\n\treturn res, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright 2016 IBM Corp.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage virtual\n\nimport (\n\t\"time\"\n\n\t\"github.ibm.com\/riethm\/gopherlayer.git\/datatypes\"\n\t\"github.ibm.com\/riethm\/gopherlayer.git\/helpers\/product\"\n\t\"github.ibm.com\/riethm\/gopherlayer.git\/services\"\n\t\"github.ibm.com\/riethm\/gopherlayer.git\/session\"\n\t\"github.ibm.com\/riethm\/gopherlayer.git\/sl\"\n)\n\n\/\/ Upgrade a virtual guest specified with an id, and a set of features to\n\/\/ upgrade. When the upgrade takes place can also be specified (`when`), but\n\/\/ this is optional. The time set will be 'now' if left as nil.\n\/\/ The features to upgrade are specified as the options used in\n\/\/ GetProductPrices().\nfunc UpgradeVirtualGuest(\n\tsess *session.Session,\n\tid int,\n\toptions map[string]float64,\n\twhen ...time.Time,\n) (datatypes.Container_Product_Order_Receipt, error) {\n\n\tpkg, err := product.GetPackageByType(sess, \"VIRTUAL_SERVER_INSTANCE\")\n\tif err != nil {\n\t\treturn datatypes.Container_Product_Order_Receipt{}, err\n\t}\n\n\tproductItems, err := product.GetPackageProducts(sess, *pkg.Id)\n\tif err != nil {\n\t\treturn datatypes.Container_Product_Order_Receipt{}, err\n\t}\n\n\tprices := product.SelectProductPricesByCategory(productItems, options)\n\n\tupgradeTime := time.Now().UTC().Format(time.RFC3339)\n\tif len(when) > 0 {\n\t\tupgradeTime = when[0].UTC().Format(time.RFC3339)\n\t}\n\n\torder := datatypes.Container_Product_Order{\n\t\tPackageId: pkg.Id,\n\t\tVirtualGuests: []datatypes.Virtual_Guest{\n\t\t\t{Id: &id},\n\t\t},\n\t\tPrices: prices,\n\t\tProperties: []datatypes.Container_Product_Order_Property{\n\t\t\t{\n\t\t\t\tName:  sl.String(\"MAINTENANCE_WINDOW\"),\n\t\t\t\tValue: &upgradeTime,\n\t\t\t},\n\t\t},\n\t}\n\n\torderService := services.GetProductOrderService(sess)\n\treturn orderService.PlaceOrder(&order, sl.Bool(false))\n}\n<commit_msg>Fix UpgradeVirtualGuest to use the correct datatype for the order<commit_after>\/**\n * Copyright 2016 IBM Corp.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage virtual\n\nimport (\n\t\"time\"\n\n\t\"github.ibm.com\/riethm\/gopherlayer.git\/datatypes\"\n\t\"github.ibm.com\/riethm\/gopherlayer.git\/helpers\/product\"\n\t\"github.ibm.com\/riethm\/gopherlayer.git\/services\"\n\t\"github.ibm.com\/riethm\/gopherlayer.git\/session\"\n\t\"github.ibm.com\/riethm\/gopherlayer.git\/sl\"\n)\n\n\/\/ Upgrade a virtual guest specified with an id, and a set of features to\n\/\/ upgrade. When the upgrade takes place can also be specified (`when`), but\n\/\/ this is optional. The time set will be 'now' if left as nil.\n\/\/ The features to upgrade are specified as the options used in\n\/\/ GetProductPrices().\nfunc UpgradeVirtualGuest(\n\tsess *session.Session,\n\tid int,\n\toptions map[string]float64,\n\twhen ...time.Time,\n) (datatypes.Container_Product_Order_Receipt, error) {\n\n\tpkg, err := product.GetPackageByType(sess, \"VIRTUAL_SERVER_INSTANCE\")\n\tif err != nil {\n\t\treturn datatypes.Container_Product_Order_Receipt{}, err\n\t}\n\n\tproductItems, err := product.GetPackageProducts(sess, *pkg.Id)\n\tif err != nil {\n\t\treturn datatypes.Container_Product_Order_Receipt{}, err\n\t}\n\n\tprices := product.SelectProductPricesByCategory(productItems, options)\n\n\tupgradeTime := time.Now().UTC().Format(time.RFC3339)\n\tif len(when) > 0 {\n\t\tupgradeTime = when[0].UTC().Format(time.RFC3339)\n\t}\n\n\torder := datatypes.Container_Product_Order_Virtual_Guest_Upgrade{\n\t\tContainer_Product_Order_Virtual_Guest: datatypes.Container_Product_Order_Virtual_Guest{\n\t\t\tContainer_Product_Order_Hardware_Server: datatypes.Container_Product_Order_Hardware_Server{\n\t\t\t\tContainer_Product_Order: datatypes.Container_Product_Order{\n\t\t\t\t\tPackageId: pkg.Id,\n\t\t\t\t\tVirtualGuests: []datatypes.Virtual_Guest{\n\t\t\t\t\t\t{Id: &id},\n\t\t\t\t\t},\n\t\t\t\t\tPrices: prices,\n\t\t\t\t\tProperties: []datatypes.Container_Product_Order_Property{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:  sl.String(\"MAINTENANCE_WINDOW\"),\n\t\t\t\t\t\t\tValue: &upgradeTime,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\torderService := services.GetProductOrderService(sess)\n\treturn orderService.PlaceOrder(&order, sl.Bool(false))\n}\n<|endoftext|>"}
{"text":"<commit_before>package apidsl\n\nimport (\n\t\"fmt\"\n\t\"mime\"\n\t\"strings\"\n\n\t\"github.com\/goadesign\/goa\/design\"\n\t\"github.com\/goadesign\/goa\/dslengine\"\n)\n\n\/\/ Counter used to create unique media type names for identifier-less media types.\nvar mediaTypeCount int\n\n\/\/ MediaType implements the media type definition apidsl. A media type definition describes the\n\/\/ representation of a resource used in a response body. This includes listing all the *potential*\n\/\/ resource attributes that can appear in the body. Views specify which of the attributes are\n\/\/ actually rendered so that the same media type definition may represent multiple rendering of a\n\/\/ given resource representation.\n\/\/\n\/\/ All media types must define a view named \"default\". This view is used to render the media type in\n\/\/ response bodies when no other view is specified.\n\/\/\n\/\/ A media type definition may also define links to other media types. This is done by first\n\/\/ defining an attribute for the linked-to media type and then referring to that attribute in the\n\/\/ Links apidsl. Views may then elect to render one or the other or both. Links are rendered using the\n\/\/ special \"link\" view. Media types that are linked to must define that view. Here is an example\n\/\/ showing all the possible media type sub-definitions:\n\/\/\n\/\/\tMediaType(\"application\/vnd.goa.example.bottle\", func() {\n\/\/\t\tDescription(\"A bottle of wine\")\n\/\/\t\tAPIVersion(\"1.0\")\n\/\/\t\tTypeName(\"BottleMedia\") \t\t\/\/ Optionally override the default generated name\n\/\/\t\tAttributes(func() {\n\/\/\t\t\tAttribute(\"id\", Integer, \"ID of bottle\")\n\/\/\t\t\tAttribute(\"href\", String, \"API href of bottle\")\n\/\/\t\t\tAttribute(\"account\", Account, \"Owner account\")\n\/\/\t\t\tAttribute(\"origin\", Origin, \"Details on wine origin\")\n\/\/\t\t\tLinks(func() {\n\/\/\t\t\t\tLink(\"account\")\t\t\/\/ Defines a link to the Account media type\n\/\/\t\t\t\tLink(\"origin\", \"tiny\")\t\/\/ Overrides the default view used to render links\n\/\/\t\t\t})\n\/\/\t\t\tRequired(\"id\", \"href\")\n\/\/\t\t})\n\/\/\t\tView(\"default\", func() {\n\/\/\t\t\tAttribute(\"id\")\n\/\/\t\t\tAttribute(\"href\")\n\/\/\t\t\tAttribute(\"links\")\t\/\/ Default view renders links\n\/\/\t\t})\n\/\/\t\tView(\"extended\", func() {\n\/\/\t\t\tAttribute(\"id\")\n\/\/\t\t\tAttribute(\"href\")\n\/\/\t\t\tAttribute(\"account\")\t\/\/ Extended view renders account inline\n\/\/\t\t\tAttribute(\"origin\")\t\/\/ Extended view renders origin inline\n\/\/\t\t\tAttribute(\"links\")\t\/\/ Extended view also renders links\n\/\/\t\t})\n\/\/ \t})\n\/\/\n\/\/ This function returns the media type definition so it can be referred to throughout the apidsl.\nfunc MediaType(identifier string, apidsl func()) *design.MediaTypeDefinition {\n\tif design.Design.MediaTypes == nil {\n\t\tdesign.Design.MediaTypes = make(map[string]*design.MediaTypeDefinition)\n\t}\n\tif dslengine.TopLevelDefinition(true) {\n\t\t\/\/ Validate Media Type\n\t\tidentifier, params, err := mime.ParseMediaType(identifier)\n\t\tif err != nil {\n\t\t\tdslengine.ReportError(\"invalid media type identifier %#v: %s\",\n\t\t\t\tidentifier, err)\n\t\t\t\/\/ We don't return so that other errors may be\n\t\t\t\/\/ captured in this one run.\n\t\t\tidentifier = \"plain\/text\"\n\t\t}\n\t\tcanonicalID := design.CanonicalIdentifier(identifier)\n\t\t\/\/ Validate that media type identifier doesn't clash\n\t\tif _, ok := design.Design.MediaTypes[canonicalID]; ok {\n\t\t\tdslengine.ReportError(\"media type %#v is defined twice\", identifier)\n\t\t\treturn nil\n\t\t}\n\t\tparts := strings.Split(identifier, \"+\")\n\t\t\/\/ Make sure it has the `+json` suffix (TBD update when goa supports other encodings)\n\t\tif len(parts) > 1 {\n\t\t\tparts = parts[1:]\n\t\t\tfound := false\n\t\t\tfor _, part := range parts {\n\t\t\t\tif part == \"json\" {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tidentifier += \"+json\"\n\t\t\t}\n\t\t}\n\t\tidentifier = mime.FormatMediaType(identifier, params)\n\t\t\/\/ Concoct a Go type name from the identifier, should it be possible to set it in the apidsl?\n\t\t\/\/ pros: control the type name generated, cons: not needed in apidsl, adds one more thing to worry about\n\t\tlastPart := identifier\n\t\tlastPartIndex := strings.LastIndex(identifier, \"\/\")\n\t\tif lastPartIndex > -1 {\n\t\t\tlastPart = identifier[lastPartIndex+1:]\n\t\t}\n\t\tplusIndex := strings.Index(lastPart, \"+\")\n\t\tif plusIndex > 0 {\n\t\t\tlastPart = lastPart[:plusIndex]\n\t\t}\n\t\tlastPart = strings.TrimPrefix(lastPart, \"vnd.\")\n\t\telems := strings.Split(lastPart, \".\")\n\t\tfor i, e := range elems {\n\t\t\telems[i] = strings.Title(e)\n\t\t}\n\t\ttypeName := strings.Join(elems, \"\")\n\t\tif typeName == \"\" {\n\t\t\tmediaTypeCount++\n\t\t\ttypeName = fmt.Sprintf(\"MediaType%d\", mediaTypeCount)\n\t\t}\n\t\t\/\/ Now save the type in the API media types map\n\t\tmt := design.NewMediaTypeDefinition(typeName, identifier, apidsl)\n\t\tdesign.Design.MediaTypes[canonicalID] = mt\n\t\treturn mt\n\t}\n\treturn nil\n}\n\n\/\/ Media sets a response media type by name or by reference using a value returned by MediaType:\n\/\/\n\/\/\tResponse(\"NotFound\", func() {\n\/\/\t\tStatus(404)\n\/\/\t\tMedia(\"application\/json\")\n\/\/\t})\n\/\/\n\/\/ Media can be used inside Response or ResponseTemplate.\nfunc Media(val interface{}) {\n\tif r, ok := responseDefinition(true); ok {\n\t\tif m, ok := val.(*design.MediaTypeDefinition); ok {\n\t\t\tif m != nil {\n\t\t\t\tr.MediaType = m.Identifier\n\t\t\t}\n\t\t} else if identifier, ok := val.(string); ok {\n\t\t\tr.MediaType = identifier\n\t\t} else {\n\t\t\tdslengine.ReportError(\"media type must be a string or a pointer to MediaTypeDefinition, got %#v\", val)\n\t\t}\n\t}\n}\n\n\/\/ Reference sets a type or media type reference. The value itself can be a type or a media type.\n\/\/ The reference type attributes define the default properties for attributes with the same name in\n\/\/ the type using the reference. So for example if a type is defined as such:\n\/\/\n\/\/\tvar Bottle = Type(\"bottle\", func() {\n\/\/\t\tAttribute(\"name\", func() {\n\/\/\t\t\tMinLength(3)\n\/\/\t\t})\n\/\/\t\tAttribute(\"vintage\", Integer, func() {\n\/\/\t\t\tMinimum(1970)\n\/\/\t\t})\n\/\/\t\tAttribute(\"somethingelse\")\n\/\/\t})\n\/\/\n\/\/ Declaring the following media type:\n\/\/\n\/\/\tvar BottleMedia = MediaType(\"vnd.goa.bottle\", func() {\n\/\/\t\tReference(Bottle)\n\/\/\t\tAttributes(func() {\n\/\/\t\t\tAttribute(\"id\", Integer)\n\/\/\t\t\tAttribute(\"name\")\n\/\/\t\t\tAttribute(\"vintage\")\n\/\/\t\t})\n\/\/\t})\n\/\/\n\/\/ defines the \"name\" and \"vintage\" attributes with the same type and validations as defined in\n\/\/ the Bottle type.\nfunc Reference(t design.DataType) {\n\tif mt, ok := mediaTypeDefinition(false); ok {\n\t\tmt.Reference = t\n\t} else if ut, ok := typeDefinition(true); ok {\n\t\tut.Reference = t\n\t}\n}\n\n\/\/ TypeName makes it possible to set the Go struct name for a type or media type in the generated\n\/\/ code. By default goagen uses the name (type) or identifier (media type) given in the apidsl and\n\/\/ computes a valid Go identifier from it. This function makes it possible to override that and\n\/\/ provide a custom name. name must be a valid Go identifier.\nfunc TypeName(name string) {\n\tif mt, ok := mediaTypeDefinition(false); ok {\n\t\tmt.TypeName = name\n\t} else if ut, ok := typeDefinition(true); ok {\n\t\tut.TypeName = name\n\t}\n}\n\n\/\/ View adds a new view to a media type. A view has a name and lists attributes that are\n\/\/ rendered when the view is used to produce a response. The attribute names must appear in the\n\/\/ media type definition. If an attribute is itself a media type then the view may specify which\n\/\/ view to use when rendering the attribute using the View function in the View apidsl. If not\n\/\/ specified then the view named \"default\" is used. Examples:\n\/\/\n\/\/\tView(\"default\", func() {\n\/\/\t\tAttribute(\"id\")\t\t\/\/ \"id\" and \"name\" must be media type attributes\n\/\/\t\tAttribute(\"name\")\n\/\/\t})\n\/\/\n\/\/\tView(\"extended\", func() {\n\/\/\t\tAttribute(\"id\")\n\/\/\t\tAttribute(\"name\")\n\/\/\t\tAttribute(\"origin\", func() {\n\/\/\t\t\tView(\"extended\")\t\/\/ Use view \"extended\" to render attribute \"origin\"\n\/\/\t\t})\n\/\/\t})\nfunc View(name string, apidsl ...func()) {\n\tif mt, ok := mediaTypeDefinition(false); ok {\n\t\tif !mt.Type.IsObject() && !mt.Type.IsArray() {\n\t\t\tdslengine.ReportError(\"cannot define view on non object and non collection media types\")\n\t\t\treturn\n\t\t}\n\t\tif mt.Views == nil {\n\t\t\tmt.Views = make(map[string]*design.ViewDefinition)\n\t\t} else {\n\t\t\tif _, ok = mt.Views[name]; ok {\n\t\t\t\tdslengine.ReportError(\"multiple definitions for view %#v in media type %#v\", name, mt.TypeName)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tat := &design.AttributeDefinition{}\n\t\tok := false\n\t\tif len(apidsl) > 0 {\n\t\t\tok = dslengine.Execute(apidsl[0], at)\n\t\t} else if mt.Type.IsArray() {\n\t\t\t\/\/ inherit view from collection element if present\n\t\t\telem := mt.Type.ToArray().ElemType\n\t\t\tif elem != nil {\n\t\t\t\tif pa, ok2 := elem.Type.(*design.MediaTypeDefinition); ok2 {\n\t\t\t\t\tif v, ok2 := pa.Views[name]; ok2 {\n\t\t\t\t\t\tat = v.AttributeDefinition\n\t\t\t\t\t\tok = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdslengine.ReportError(\"unknown view %#v\", name)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ok {\n\t\t\to := at.Type.ToObject()\n\t\t\tif o != nil {\n\t\t\t\tmto := mt.Type.ToObject()\n\t\t\t\tif mto == nil {\n\t\t\t\t\tmto = mt.Type.ToArray().ElemType.Type.ToObject()\n\t\t\t\t}\n\t\t\t\tfor n, cat := range o {\n\t\t\t\t\tif existing, ok := mto[n]; ok {\n\t\t\t\t\t\tdup := existing.Dup()\n\t\t\t\t\t\tdup.View = cat.View\n\t\t\t\t\t\to[n] = dup\n\t\t\t\t\t} else if n != \"links\" {\n\t\t\t\t\t\tdslengine.ReportError(\"unknown attribute %#v\", n)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tmt.Views[name] = &design.ViewDefinition{\n\t\t\t\tAttributeDefinition: at,\n\t\t\t\tName:                name,\n\t\t\t\tParent:              mt,\n\t\t\t}\n\t\t}\n\t} else if a, ok := attributeDefinition(true); ok {\n\t\ta.View = name\n\t}\n}\n\n\/\/ Attributes implements the media type attributes apidsl. See MediaType.\nfunc Attributes(apidsl func()) {\n\tif mt, ok := mediaTypeDefinition(true); ok {\n\t\tdslengine.Execute(apidsl, mt)\n\t}\n}\n\n\/\/ Links implements the media type links apidsl. See MediaType.\nfunc Links(apidsl func()) {\n\tif mt, ok := mediaTypeDefinition(true); ok {\n\t\tdslengine.Execute(apidsl, mt)\n\t}\n}\n\n\/\/ Link adds a link to a media type. At the minimum a link has a name corresponding to one of the\n\/\/ media type attribute names. A link may also define the view used to render the linked-to\n\/\/ attribute. The default view used to render links is \"link\". Examples:\n\/\/\n\/\/\tLink(\"origin\")\t\t\/\/ Use the \"link\" view of the \"origin\" attribute\n\/\/\tLink(\"account\", \"tiny\")\t\/\/ Use the \"tiny\" view of the \"account\" attribute\nfunc Link(name string, view ...string) {\n\tif mt, ok := mediaTypeDefinition(true); ok {\n\t\tif mt.Links == nil {\n\t\t\tmt.Links = make(map[string]*design.LinkDefinition)\n\t\t} else {\n\t\t\tif _, ok := mt.Links[name]; ok {\n\t\t\t\tdslengine.ReportError(\"duplicate definition for link %#v\", name)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tlink := &design.LinkDefinition{Name: name, Parent: mt}\n\t\tif len(view) > 1 {\n\t\t\tdslengine.ReportError(\"invalid syntax in Link definition for %#v, allowed syntax is Link(name) or Link(name, view)\", name)\n\t\t}\n\t\tif len(view) > 0 {\n\t\t\tlink.View = view[0]\n\t\t} else {\n\t\t\tlink.View = \"link\"\n\t\t}\n\t\tmt.Links[name] = link\n\t}\n}\n\n\/\/ CollectionOf creates a collection media type from its element media type. A collection media\n\/\/ type represents the content of responses that return a collection of resources such as \"list\"\n\/\/ actions. This function can be called from any place where a media type can be used.\n\/\/ The resulting media type identifier is built from the element media type by appending the media\n\/\/ type parameter \"type\" with value \"collection\".\nfunc CollectionOf(v interface{}, apidsl ...func()) *design.MediaTypeDefinition {\n\tif design.GeneratedMediaTypes == nil {\n\t\tdesign.GeneratedMediaTypes = make(design.MediaTypeRoot)\n\t\tdslengine.Roots = append(dslengine.Roots, design.GeneratedMediaTypes)\n\t}\n\tvar m *design.MediaTypeDefinition\n\tvar ok bool\n\tm, ok = v.(*design.MediaTypeDefinition)\n\tif !ok {\n\t\tif id, ok := v.(string); ok {\n\t\t\tm = design.Design.MediaTypes[design.CanonicalIdentifier(id)]\n\t\t}\n\t}\n\tif m == nil {\n\t\tdslengine.ReportError(\"invalid CollectionOf argument: not a media type and not a known media type identifier\")\n\t\treturn nil\n\t}\n\tid := m.Identifier\n\tmediatype, params, err := mime.ParseMediaType(id)\n\tif err != nil {\n\t\tdslengine.ReportError(\"invalid media type identifier %#v: %s\", id, err)\n\t\treturn nil\n\t}\n\thasType := false\n\tfor param := range params {\n\t\tif param == \"type\" {\n\t\t\thasType = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !hasType {\n\t\tparams[\"type\"] = \"collection\"\n\t}\n\tid = mime.FormatMediaType(mediatype, params)\n\ttypeName := m.TypeName + \"Collection\"\n\tif mt, ok := design.GeneratedMediaTypes[typeName]; ok {\n\t\t\/\/ Already have a type for this collection, reuse it.\n\t\treturn mt\n\t}\n\tmt := design.NewMediaTypeDefinition(typeName, id, func() {\n\t\tif mt, ok := mediaTypeDefinition(true); ok {\n\t\t\tmt.TypeName = typeName\n\t\t\tmt.AttributeDefinition = &design.AttributeDefinition{Type: ArrayOf(m)}\n\t\t\tmt.APIVersions = m.APIVersions\n\t\t\tif len(apidsl) > 0 {\n\t\t\t\tdslengine.Execute(apidsl[0], mt)\n\t\t\t}\n\t\t\tif mt.Views == nil {\n\t\t\t\t\/\/ If the apidsl didn't create any views (or there is no apidsl at all)\n\t\t\t\t\/\/ then inherit the views from the collection element.\n\t\t\t\tmt.Views = make(map[string]*design.ViewDefinition)\n\t\t\t\tfor n, v := range m.Views {\n\t\t\t\t\tmt.Views[n] = v\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\t\/\/ Do not execute the apidsl right away, will be done last to make sure the element apidsl has run\n\t\/\/ first.\n\tdesign.GeneratedMediaTypes[typeName] = mt\n\treturn mt\n}\n<commit_msg>rename variables<commit_after>package apidsl\n\nimport (\n\t\"fmt\"\n\t\"mime\"\n\t\"strings\"\n\n\t\"github.com\/goadesign\/goa\/design\"\n\t\"github.com\/goadesign\/goa\/dslengine\"\n)\n\n\/\/ Counter used to create unique media type names for identifier-less media types.\nvar mediaTypeCount int\n\n\/\/ MediaType implements the media type definition dsl. A media type definition describes the\n\/\/ representation of a resource used in a response body. This includes listing all the *potential*\n\/\/ resource attributes that can appear in the body. Views specify which of the attributes are\n\/\/ actually rendered so that the same media type definition may represent multiple rendering of a\n\/\/ given resource representation.\n\/\/\n\/\/ All media types must define a view named \"default\". This view is used to render the media type in\n\/\/ response bodies when no other view is specified.\n\/\/\n\/\/ A media type definition may also define links to other media types. This is done by first\n\/\/ defining an attribute for the linked-to media type and then referring to that attribute in the\n\/\/ Links dsl. Views may then elect to render one or the other or both. Links are rendered using the\n\/\/ special \"link\" view. Media types that are linked to must define that view. Here is an example\n\/\/ showing all the possible media type sub-definitions:\n\/\/\n\/\/\tMediaType(\"application\/vnd.goa.example.bottle\", func() {\n\/\/\t\tDescription(\"A bottle of wine\")\n\/\/\t\tAPIVersion(\"1.0\")\n\/\/\t\tTypeName(\"BottleMedia\") \t\t\/\/ Optionally override the default generated name\n\/\/\t\tAttributes(func() {\n\/\/\t\t\tAttribute(\"id\", Integer, \"ID of bottle\")\n\/\/\t\t\tAttribute(\"href\", String, \"API href of bottle\")\n\/\/\t\t\tAttribute(\"account\", Account, \"Owner account\")\n\/\/\t\t\tAttribute(\"origin\", Origin, \"Details on wine origin\")\n\/\/\t\t\tLinks(func() {\n\/\/\t\t\t\tLink(\"account\")\t\t\/\/ Defines a link to the Account media type\n\/\/\t\t\t\tLink(\"origin\", \"tiny\")\t\/\/ Overrides the default view used to render links\n\/\/\t\t\t})\n\/\/\t\t\tRequired(\"id\", \"href\")\n\/\/\t\t})\n\/\/\t\tView(\"default\", func() {\n\/\/\t\t\tAttribute(\"id\")\n\/\/\t\t\tAttribute(\"href\")\n\/\/\t\t\tAttribute(\"links\")\t\/\/ Default view renders links\n\/\/\t\t})\n\/\/\t\tView(\"extended\", func() {\n\/\/\t\t\tAttribute(\"id\")\n\/\/\t\t\tAttribute(\"href\")\n\/\/\t\t\tAttribute(\"account\")\t\/\/ Extended view renders account inline\n\/\/\t\t\tAttribute(\"origin\")\t\/\/ Extended view renders origin inline\n\/\/\t\t\tAttribute(\"links\")\t\/\/ Extended view also renders links\n\/\/\t\t})\n\/\/ \t})\n\/\/\n\/\/ This function returns the media type definition so it can be referred to throughout the dsl.\nfunc MediaType(identifier string, dsl func()) *design.MediaTypeDefinition {\n\tif design.Design.MediaTypes == nil {\n\t\tdesign.Design.MediaTypes = make(map[string]*design.MediaTypeDefinition)\n\t}\n\tif dslengine.TopLevelDefinition(true) {\n\t\t\/\/ Validate Media Type\n\t\tidentifier, params, err := mime.ParseMediaType(identifier)\n\t\tif err != nil {\n\t\t\tdslengine.ReportError(\"invalid media type identifier %#v: %s\",\n\t\t\t\tidentifier, err)\n\t\t\t\/\/ We don't return so that other errors may be\n\t\t\t\/\/ captured in this one run.\n\t\t\tidentifier = \"plain\/text\"\n\t\t}\n\t\tcanonicalID := design.CanonicalIdentifier(identifier)\n\t\t\/\/ Validate that media type identifier doesn't clash\n\t\tif _, ok := design.Design.MediaTypes[canonicalID]; ok {\n\t\t\tdslengine.ReportError(\"media type %#v is defined twice\", identifier)\n\t\t\treturn nil\n\t\t}\n\t\tparts := strings.Split(identifier, \"+\")\n\t\t\/\/ Make sure it has the `+json` suffix (TBD update when goa supports other encodings)\n\t\tif len(parts) > 1 {\n\t\t\tparts = parts[1:]\n\t\t\tfound := false\n\t\t\tfor _, part := range parts {\n\t\t\t\tif part == \"json\" {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tidentifier += \"+json\"\n\t\t\t}\n\t\t}\n\t\tidentifier = mime.FormatMediaType(identifier, params)\n\t\t\/\/ Concoct a Go type name from the identifier, should it be possible to set it in the dsl?\n\t\t\/\/ pros: control the type name generated, cons: not needed in dsl, adds one more thing to worry about\n\t\tlastPart := identifier\n\t\tlastPartIndex := strings.LastIndex(identifier, \"\/\")\n\t\tif lastPartIndex > -1 {\n\t\t\tlastPart = identifier[lastPartIndex+1:]\n\t\t}\n\t\tplusIndex := strings.Index(lastPart, \"+\")\n\t\tif plusIndex > 0 {\n\t\t\tlastPart = lastPart[:plusIndex]\n\t\t}\n\t\tlastPart = strings.TrimPrefix(lastPart, \"vnd.\")\n\t\telems := strings.Split(lastPart, \".\")\n\t\tfor i, e := range elems {\n\t\t\telems[i] = strings.Title(e)\n\t\t}\n\t\ttypeName := strings.Join(elems, \"\")\n\t\tif typeName == \"\" {\n\t\t\tmediaTypeCount++\n\t\t\ttypeName = fmt.Sprintf(\"MediaType%d\", mediaTypeCount)\n\t\t}\n\t\t\/\/ Now save the type in the API media types map\n\t\tmt := design.NewMediaTypeDefinition(typeName, identifier, dsl)\n\t\tdesign.Design.MediaTypes[canonicalID] = mt\n\t\treturn mt\n\t}\n\treturn nil\n}\n\n\/\/ Media sets a response media type by name or by reference using a value returned by MediaType:\n\/\/\n\/\/\tResponse(\"NotFound\", func() {\n\/\/\t\tStatus(404)\n\/\/\t\tMedia(\"application\/json\")\n\/\/\t})\n\/\/\n\/\/ Media can be used inside Response or ResponseTemplate.\nfunc Media(val interface{}) {\n\tif r, ok := responseDefinition(true); ok {\n\t\tif m, ok := val.(*design.MediaTypeDefinition); ok {\n\t\t\tif m != nil {\n\t\t\t\tr.MediaType = m.Identifier\n\t\t\t}\n\t\t} else if identifier, ok := val.(string); ok {\n\t\t\tr.MediaType = identifier\n\t\t} else {\n\t\t\tdslengine.ReportError(\"media type must be a string or a pointer to MediaTypeDefinition, got %#v\", val)\n\t\t}\n\t}\n}\n\n\/\/ Reference sets a type or media type reference. The value itself can be a type or a media type.\n\/\/ The reference type attributes define the default properties for attributes with the same name in\n\/\/ the type using the reference. So for example if a type is defined as such:\n\/\/\n\/\/\tvar Bottle = Type(\"bottle\", func() {\n\/\/\t\tAttribute(\"name\", func() {\n\/\/\t\t\tMinLength(3)\n\/\/\t\t})\n\/\/\t\tAttribute(\"vintage\", Integer, func() {\n\/\/\t\t\tMinimum(1970)\n\/\/\t\t})\n\/\/\t\tAttribute(\"somethingelse\")\n\/\/\t})\n\/\/\n\/\/ Declaring the following media type:\n\/\/\n\/\/\tvar BottleMedia = MediaType(\"vnd.goa.bottle\", func() {\n\/\/\t\tReference(Bottle)\n\/\/\t\tAttributes(func() {\n\/\/\t\t\tAttribute(\"id\", Integer)\n\/\/\t\t\tAttribute(\"name\")\n\/\/\t\t\tAttribute(\"vintage\")\n\/\/\t\t})\n\/\/\t})\n\/\/\n\/\/ defines the \"name\" and \"vintage\" attributes with the same type and validations as defined in\n\/\/ the Bottle type.\nfunc Reference(t design.DataType) {\n\tif mt, ok := mediaTypeDefinition(false); ok {\n\t\tmt.Reference = t\n\t} else if ut, ok := typeDefinition(true); ok {\n\t\tut.Reference = t\n\t}\n}\n\n\/\/ TypeName makes it possible to set the Go struct name for a type or media type in the generated\n\/\/ code. By default goagen uses the name (type) or identifier (media type) given in the dsl and\n\/\/ computes a valid Go identifier from it. This function makes it possible to override that and\n\/\/ provide a custom name. name must be a valid Go identifier.\nfunc TypeName(name string) {\n\tif mt, ok := mediaTypeDefinition(false); ok {\n\t\tmt.TypeName = name\n\t} else if ut, ok := typeDefinition(true); ok {\n\t\tut.TypeName = name\n\t}\n}\n\n\/\/ View adds a new view to a media type. A view has a name and lists attributes that are\n\/\/ rendered when the view is used to produce a response. The attribute names must appear in the\n\/\/ media type definition. If an attribute is itself a media type then the view may specify which\n\/\/ view to use when rendering the attribute using the View function in the View dsl. If not\n\/\/ specified then the view named \"default\" is used. Examples:\n\/\/\n\/\/\tView(\"default\", func() {\n\/\/\t\tAttribute(\"id\")\t\t\/\/ \"id\" and \"name\" must be media type attributes\n\/\/\t\tAttribute(\"name\")\n\/\/\t})\n\/\/\n\/\/\tView(\"extended\", func() {\n\/\/\t\tAttribute(\"id\")\n\/\/\t\tAttribute(\"name\")\n\/\/\t\tAttribute(\"origin\", func() {\n\/\/\t\t\tView(\"extended\")\t\/\/ Use view \"extended\" to render attribute \"origin\"\n\/\/\t\t})\n\/\/\t})\nfunc View(name string, dsl ...func()) {\n\tif mt, ok := mediaTypeDefinition(false); ok {\n\t\tif !mt.Type.IsObject() && !mt.Type.IsArray() {\n\t\t\tdslengine.ReportError(\"cannot define view on non object and non collection media types\")\n\t\t\treturn\n\t\t}\n\t\tif mt.Views == nil {\n\t\t\tmt.Views = make(map[string]*design.ViewDefinition)\n\t\t} else {\n\t\t\tif _, ok = mt.Views[name]; ok {\n\t\t\t\tdslengine.ReportError(\"multiple definitions for view %#v in media type %#v\", name, mt.TypeName)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tat := &design.AttributeDefinition{}\n\t\tok := false\n\t\tif len(dsl) > 0 {\n\t\t\tok = dslengine.Execute(dsl[0], at)\n\t\t} else if mt.Type.IsArray() {\n\t\t\t\/\/ inherit view from collection element if present\n\t\t\telem := mt.Type.ToArray().ElemType\n\t\t\tif elem != nil {\n\t\t\t\tif pa, ok2 := elem.Type.(*design.MediaTypeDefinition); ok2 {\n\t\t\t\t\tif v, ok2 := pa.Views[name]; ok2 {\n\t\t\t\t\t\tat = v.AttributeDefinition\n\t\t\t\t\t\tok = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdslengine.ReportError(\"unknown view %#v\", name)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif ok {\n\t\t\to := at.Type.ToObject()\n\t\t\tif o != nil {\n\t\t\t\tmto := mt.Type.ToObject()\n\t\t\t\tif mto == nil {\n\t\t\t\t\tmto = mt.Type.ToArray().ElemType.Type.ToObject()\n\t\t\t\t}\n\t\t\t\tfor n, cat := range o {\n\t\t\t\t\tif existing, ok := mto[n]; ok {\n\t\t\t\t\t\tdup := existing.Dup()\n\t\t\t\t\t\tdup.View = cat.View\n\t\t\t\t\t\to[n] = dup\n\t\t\t\t\t} else if n != \"links\" {\n\t\t\t\t\t\tdslengine.ReportError(\"unknown attribute %#v\", n)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tmt.Views[name] = &design.ViewDefinition{\n\t\t\t\tAttributeDefinition: at,\n\t\t\t\tName:                name,\n\t\t\t\tParent:              mt,\n\t\t\t}\n\t\t}\n\t} else if a, ok := attributeDefinition(true); ok {\n\t\ta.View = name\n\t}\n}\n\n\/\/ Attributes implements the media type attributes dsl. See MediaType.\nfunc Attributes(dsl func()) {\n\tif mt, ok := mediaTypeDefinition(true); ok {\n\t\tdslengine.Execute(dsl, mt)\n\t}\n}\n\n\/\/ Links implements the media type links dsl. See MediaType.\nfunc Links(dsl func()) {\n\tif mt, ok := mediaTypeDefinition(true); ok {\n\t\tdslengine.Execute(dsl, mt)\n\t}\n}\n\n\/\/ Link adds a link to a media type. At the minimum a link has a name corresponding to one of the\n\/\/ media type attribute names. A link may also define the view used to render the linked-to\n\/\/ attribute. The default view used to render links is \"link\". Examples:\n\/\/\n\/\/\tLink(\"origin\")\t\t\/\/ Use the \"link\" view of the \"origin\" attribute\n\/\/\tLink(\"account\", \"tiny\")\t\/\/ Use the \"tiny\" view of the \"account\" attribute\nfunc Link(name string, view ...string) {\n\tif mt, ok := mediaTypeDefinition(true); ok {\n\t\tif mt.Links == nil {\n\t\t\tmt.Links = make(map[string]*design.LinkDefinition)\n\t\t} else {\n\t\t\tif _, ok := mt.Links[name]; ok {\n\t\t\t\tdslengine.ReportError(\"duplicate definition for link %#v\", name)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tlink := &design.LinkDefinition{Name: name, Parent: mt}\n\t\tif len(view) > 1 {\n\t\t\tdslengine.ReportError(\"invalid syntax in Link definition for %#v, allowed syntax is Link(name) or Link(name, view)\", name)\n\t\t}\n\t\tif len(view) > 0 {\n\t\t\tlink.View = view[0]\n\t\t} else {\n\t\t\tlink.View = \"link\"\n\t\t}\n\t\tmt.Links[name] = link\n\t}\n}\n\n\/\/ CollectionOf creates a collection media type from its element media type. A collection media\n\/\/ type represents the content of responses that return a collection of resources such as \"list\"\n\/\/ actions. This function can be called from any place where a media type can be used.\n\/\/ The resulting media type identifier is built from the element media type by appending the media\n\/\/ type parameter \"type\" with value \"collection\".\nfunc CollectionOf(v interface{}, dsl ...func()) *design.MediaTypeDefinition {\n\tif design.GeneratedMediaTypes == nil {\n\t\tdesign.GeneratedMediaTypes = make(design.MediaTypeRoot)\n\t\tdslengine.Roots = append(dslengine.Roots, design.GeneratedMediaTypes)\n\t}\n\tvar m *design.MediaTypeDefinition\n\tvar ok bool\n\tm, ok = v.(*design.MediaTypeDefinition)\n\tif !ok {\n\t\tif id, ok := v.(string); ok {\n\t\t\tm = design.Design.MediaTypes[design.CanonicalIdentifier(id)]\n\t\t}\n\t}\n\tif m == nil {\n\t\tdslengine.ReportError(\"invalid CollectionOf argument: not a media type and not a known media type identifier\")\n\t\treturn nil\n\t}\n\tid := m.Identifier\n\tmediatype, params, err := mime.ParseMediaType(id)\n\tif err != nil {\n\t\tdslengine.ReportError(\"invalid media type identifier %#v: %s\", id, err)\n\t\treturn nil\n\t}\n\thasType := false\n\tfor param := range params {\n\t\tif param == \"type\" {\n\t\t\thasType = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !hasType {\n\t\tparams[\"type\"] = \"collection\"\n\t}\n\tid = mime.FormatMediaType(mediatype, params)\n\ttypeName := m.TypeName + \"Collection\"\n\tif mt, ok := design.GeneratedMediaTypes[typeName]; ok {\n\t\t\/\/ Already have a type for this collection, reuse it.\n\t\treturn mt\n\t}\n\tmt := design.NewMediaTypeDefinition(typeName, id, func() {\n\t\tif mt, ok := mediaTypeDefinition(true); ok {\n\t\t\tmt.TypeName = typeName\n\t\t\tmt.AttributeDefinition = &design.AttributeDefinition{Type: ArrayOf(m)}\n\t\t\tmt.APIVersions = m.APIVersions\n\t\t\tif len(dsl) > 0 {\n\t\t\t\tdslengine.Execute(dsl[0], mt)\n\t\t\t}\n\t\t\tif mt.Views == nil {\n\t\t\t\t\/\/ If the dsl didn't create any views (or there is no dsl at all)\n\t\t\t\t\/\/ then inherit the views from the collection element.\n\t\t\t\tmt.Views = make(map[string]*design.ViewDefinition)\n\t\t\t\tfor n, v := range m.Views {\n\t\t\t\t\tmt.Views[n] = v\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\t\/\/ Do not execute the dsl right away, will be done last to make sure the element dsl has run\n\t\/\/ first.\n\tdesign.GeneratedMediaTypes[typeName] = mt\n\treturn mt\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\tworker \"github.com\/contribsys\/faktory_worker_go\"\n\t\"github.com\/getsentry\/raven-go\"\n\t\"github.com\/gobuffalo\/envy\"\n\t\"github.com\/jmoiron\/sqlx\"\n\tkeycloak \"github.com\/kindlyops\/mappamundi\/havenapi\/keycloak\"\n\t_ \"github.com\/lib\/pq\"\n\t\"github.com\/nleof\/goyesql\"\n)\n\n\/\/ Registration is a data type for the registration funnel\ntype Registration struct {\n\tID         string `db:\"uuid\"`\n\tEmail      string `db:\"email\"`\n\tIP         string `db:\"ip_address\"`\n\tSurveyJSON string `db:\"survey_results\"`\n\tRegistered bool   `db:\"registered\"`\n\tCreatedAt  string `db:\"created_at\"`\n}\n\n\/\/ SurveyResponse is a data type for the survey\ntype SurveyResponse struct {\n\tID             string `json:\"uuid\"`\n\tUserID         string `json:\"user_id\"`\n\tEmail          string `json:\"user_email\"`\n\tOrg            string `json:\"org\"`\n\tAnswerID       string `json:\"answer_id\"`\n\tGroupNumber    int    `json:\"group_number\"`\n\tPointsAssigned int    `json:\"points_assigned\"`\n\tCreatedAt      string `json:\"created_at\"`\n}\n\n\/\/ SurveyResponses is for a collection of SurveyResponse.\ntype SurveyResponses struct {\n\tCollection []SurveyResponse\n}\n\nvar dbUser = envy.Get(\"DATABASE_USERNAME\", \"postgres\")\nvar dbName = envy.Get(\"DATABASE_NAME\", \"mappamundi_dev\")\nvar dbPassword = envy.Get(\"DATABASE_PASSWORD\", \"postgres\")\nvar dbHost = envy.Get(\"DATABASE_HOST\", \"db\")\nvar dbOptions = fmt.Sprintf(\n\t\"user=%s dbname=%s password=%s host=%s sslmode=disable\",\n\tdbUser,\n\tdbName,\n\tdbPassword,\n\tdbHost,\n)\n\n\/\/ Q is a map of SQL queries\nvar Q goyesql.Queries\n\n\/\/ CreateUser creates a new user with keycloak\nfunc CreateUser(ctx worker.Context, args ...interface{}) error {\n\tfmt.Println(\"Working on CreateUser job\", ctx.Jid())\n\tuserEmail := args[0].(string)\n\terr := keycloak.CreateUser(userEmail)\n\thandleError(err)\n\tfmt.Println(\"Created User: \", userEmail)\n\treturn err\n}\n\n\/\/ SaveSurvey saves the survey responses to the new user.\nfunc SaveSurvey(ctx worker.Context, args ...interface{}) error {\n\tfmt.Println(\"Working on SaveSurvey job\", ctx.Jid())\n\tuserEmail := args[0].(string)\n\n\t\/\/ db is for the postgres connection.\n\tdb, err := sqlx.Connect(\n\t\t\"postgres\",\n\t\tdbOptions,\n\t)\n\thandleError(err)\n\n\tdefer db.Close()\n\n\t\/\/ Grab the users registration funnel info so we can use the survey data.\n\tregistration := []Registration{}\n\terr = db.Select(&registration, \"SELECT * FROM mappa.registration_funnel_1 WHERE registered=false AND email=$1 LIMIT 1\", userEmail)\n\tlog.Printf(\"SQL Result found user: %v\", registration)\n\thandleError(err)\n\n\t\/\/ Set registered to true\n\ttx, err := db.Begin()\n\thandleError(err)\n\n\t_, err = tx.Exec(\"UPDATE mappa.registration_funnel_1 SET registered = true WHERE email=$1\", userEmail)\n\thandleError(err)\n\t_, err = tx.Exec(\"SELECT set_config('request.jwt.claim.email', $1, true)\", userEmail)\n\thandleError(err)\n\t_, err = tx.Exec(\"SELECT set_config('request.jwt.claim.sub', $1, true)\", registration[0].ID)\n\thandleError(err)\n\torg, _ := json.Marshal(nil)\n\t_, err = tx.Exec(\"SELECT set_config('request.jwt.claim.org', $1, true)\", string(org))\n\thandleError(err)\n\n\t\/\/ Collect the survey JSON\n\tsurveyString := registration[0].SurveyJSON\n\tlog.Printf(\"Survey Json found: %s\", surveyString)\n\tresponses := make([]SurveyResponse, 0)\n\terr = json.Unmarshal([]byte(surveyString), &responses)\n\tlog.Printf(\"Responses found: %v\", responses)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, response := range responses {\n\t\t_, err = tx.Exec(\n\t\t\t\"INSERT INTO mappa.ipsative_responses (answer_id, group_number, points_assigned) VALUES ($1, $2, $3)\",\n\t\t\tresponse.AnswerID,\n\t\t\tresponse.GroupNumber,\n\t\t\tresponse.PointsAssigned,\n\t\t)\n\t\thandleError(err)\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn err\n}\n\nfunc handleError(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc setupAndRun() {\n\n\tmgr := worker.NewManager()\n\n\t\/\/ register job types and the function to execute them\n\tmgr.Register(\"CreateUser\", CreateUser)\n\tmgr.Register(\"SaveSurvey\", SaveSurvey)\n\n\t\/\/ use up to N goroutines to execute jobs\n\tmgr.Concurrency = 20\n\n\t\/\/ pull jobs from these queues, in this order of precedence\n\tmgr.Queues = []string{\"critical\", \"default\", \"bulk\"}\n\tfmt.Printf(\"Haven worker started, processing jobs\\n\")\n\t\/\/ Start processing jobs, this method does not return\n\tmgr.Run()\n}\n\nfunc main() {\n\tdsn, ok := os.LookupEnv(\"SENTRY_DSN\")\n\tif ok {\n\t\traven.SetDSN(dsn)\n\t\traven.CapturePanic(setupAndRun, nil)\n\t} else {\n\t\tsetupAndRun()\n\t}\n}\n<commit_msg>Raven reads SENTRY_DSN from Env automatically.<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\tworker \"github.com\/contribsys\/faktory_worker_go\"\n\t\"github.com\/getsentry\/raven-go\"\n\t\"github.com\/gobuffalo\/envy\"\n\t\"github.com\/jmoiron\/sqlx\"\n\tkeycloak \"github.com\/kindlyops\/mappamundi\/havenapi\/keycloak\"\n\t_ \"github.com\/lib\/pq\"\n\t\"github.com\/nleof\/goyesql\"\n)\n\n\/\/ Registration is a data type for the registration funnel\ntype Registration struct {\n\tID         string `db:\"uuid\"`\n\tEmail      string `db:\"email\"`\n\tIP         string `db:\"ip_address\"`\n\tSurveyJSON string `db:\"survey_results\"`\n\tRegistered bool   `db:\"registered\"`\n\tCreatedAt  string `db:\"created_at\"`\n}\n\n\/\/ SurveyResponse is a data type for the survey\ntype SurveyResponse struct {\n\tID             string `json:\"uuid\"`\n\tUserID         string `json:\"user_id\"`\n\tEmail          string `json:\"user_email\"`\n\tOrg            string `json:\"org\"`\n\tAnswerID       string `json:\"answer_id\"`\n\tGroupNumber    int    `json:\"group_number\"`\n\tPointsAssigned int    `json:\"points_assigned\"`\n\tCreatedAt      string `json:\"created_at\"`\n}\n\n\/\/ SurveyResponses is for a collection of SurveyResponse.\ntype SurveyResponses struct {\n\tCollection []SurveyResponse\n}\n\nvar dbUser = envy.Get(\"DATABASE_USERNAME\", \"postgres\")\nvar dbName = envy.Get(\"DATABASE_NAME\", \"mappamundi_dev\")\nvar dbPassword = envy.Get(\"DATABASE_PASSWORD\", \"postgres\")\nvar dbHost = envy.Get(\"DATABASE_HOST\", \"db\")\nvar dbOptions = fmt.Sprintf(\n\t\"user=%s dbname=%s password=%s host=%s sslmode=disable\",\n\tdbUser,\n\tdbName,\n\tdbPassword,\n\tdbHost,\n)\n\n\/\/ Q is a map of SQL queries\nvar Q goyesql.Queries\n\n\/\/ CreateUser creates a new user with keycloak\nfunc CreateUser(ctx worker.Context, args ...interface{}) error {\n\tfmt.Println(\"Working on CreateUser job\", ctx.Jid())\n\tuserEmail := args[0].(string)\n\terr := keycloak.CreateUser(userEmail)\n\thandleError(err)\n\tfmt.Println(\"Created User: \", userEmail)\n\treturn err\n}\n\n\/\/ SaveSurvey saves the survey responses to the new user.\nfunc SaveSurvey(ctx worker.Context, args ...interface{}) error {\n\tfmt.Println(\"Working on SaveSurvey job\", ctx.Jid())\n\tuserEmail := args[0].(string)\n\n\t\/\/ db is for the postgres connection.\n\tdb, err := sqlx.Connect(\n\t\t\"postgres\",\n\t\tdbOptions,\n\t)\n\thandleError(err)\n\n\tdefer db.Close()\n\n\t\/\/ Grab the users registration funnel info so we can use the survey data.\n\tregistration := []Registration{}\n\terr = db.Select(&registration, \"SELECT * FROM mappa.registration_funnel_1 WHERE registered=false AND email=$1 LIMIT 1\", userEmail)\n\tlog.Printf(\"SQL Result found user: %v\", registration)\n\thandleError(err)\n\n\t\/\/ Set registered to true\n\ttx, err := db.Begin()\n\thandleError(err)\n\n\t_, err = tx.Exec(\"UPDATE mappa.registration_funnel_1 SET registered = true WHERE email=$1\", userEmail)\n\thandleError(err)\n\t_, err = tx.Exec(\"SELECT set_config('request.jwt.claim.email', $1, true)\", userEmail)\n\thandleError(err)\n\t_, err = tx.Exec(\"SELECT set_config('request.jwt.claim.sub', $1, true)\", registration[0].ID)\n\thandleError(err)\n\torg, _ := json.Marshal(nil)\n\t_, err = tx.Exec(\"SELECT set_config('request.jwt.claim.org', $1, true)\", string(org))\n\thandleError(err)\n\n\t\/\/ Collect the survey JSON\n\tsurveyString := registration[0].SurveyJSON\n\tlog.Printf(\"Survey Json found: %s\", surveyString)\n\tresponses := make([]SurveyResponse, 0)\n\terr = json.Unmarshal([]byte(surveyString), &responses)\n\tlog.Printf(\"Responses found: %v\", responses)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfor _, response := range responses {\n\t\t_, err = tx.Exec(\n\t\t\t\"INSERT INTO mappa.ipsative_responses (answer_id, group_number, points_assigned) VALUES ($1, $2, $3)\",\n\t\t\tresponse.AnswerID,\n\t\t\tresponse.GroupNumber,\n\t\t\tresponse.PointsAssigned,\n\t\t)\n\t\thandleError(err)\n\t}\n\n\terr = tx.Commit()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn err\n}\n\nfunc handleError(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc setupAndRun() {\n\n\tmgr := worker.NewManager()\n\n\t\/\/ register job types and the function to execute them\n\tmgr.Register(\"CreateUser\", CreateUser)\n\tmgr.Register(\"SaveSurvey\", SaveSurvey)\n\n\t\/\/ use up to N goroutines to execute jobs\n\tmgr.Concurrency = 20\n\n\t\/\/ pull jobs from these queues, in this order of precedence\n\tmgr.Queues = []string{\"critical\", \"default\", \"bulk\"}\n\tfmt.Printf(\"Haven worker started, processing jobs\\n\")\n\t\/\/ Start processing jobs, this method does not return\n\tmgr.Run()\n}\n\nfunc main() {\n\traven.CapturePanic(setupAndRun, nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package wpaconnect\n\nimport (\n\t\"errors\"\n\t\"github.com\/mark2b\/wpa-connect\/internal\/wpa_cli\"\n\n\t\"fmt\"\n\t\"github.com\/godbus\/dbus\"\n\t\"net\"\n\t\"time\"\n\t\"github.com\/mark2b\/wpa-connect\/internal\/log\"\n\t\"github.com\/mark2b\/wpa-connect\/internal\/wpa_dbus\"\n)\n\nfunc (self *connectManager) Connect(ssid string, password string, timeout time.Duration) (connectionInfo ConnectionInfo, e error) {\n\tself.deadTime = time.Now().Add(timeout)\n\tself.context = &connectContext{}\n\tself.context.scanDone = make(chan bool)\n\tself.context.connectDone = make(chan bool)\n\tif wpa, err := wpa_dbus.NewWPA(); err == nil {\n\t\twpa.WaitForSignals(self.onSignal)\n\t\twpa.AddSignalsObserver()\n\t\tif wpa.ReadInterface(self.NetInterface); wpa.Error == nil {\n\t\t\tiface := wpa.Interface\n\t\t\tiface.AddSignalsObserver()\n\t\t\tself.context.phaseWaitForScanDone = true\n\t\t\tgo func() {\n\t\t\t\ttime.Sleep(self.deadTime.Sub(time.Now()))\n\t\t\t\tself.context.scanDone <- false\n\t\t\t\tself.context.error = errors.New(\"timeout\")\n\t\t\t}()\n\t\t\tif iface.Scan(); iface.Error == nil {\n\t\t\t\t\/\/ Wait for scan done\n\t\t\t\tif <-self.context.scanDone; self.context.error == nil {\n\t\t\t\t\tif iface.ReadBSSList(); iface.Error == nil {\n\t\t\t\t\t\tbssMap := make(map[string]wpa_dbus.BSSWPA, 0)\n\t\t\t\t\t\tfor _, bss := range iface.BSSs {\n\t\t\t\t\t\t\tif bss.ReadSSID(); bss.Error == nil {\n\t\t\t\t\t\t\t\tbssMap[bss.SSID] = bss\n\t\t\t\t\t\t\t\tlog.Log.Debug(bss.SSID, bss.BSSID)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\te = err\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif e == nil {\n\t\t\t\t\t\t\tif bss, exists := bssMap[ssid]; exists {\n\t\t\t\t\t\t\t\tif bss.ReadSSID(); bss.Error == nil {\n\t\t\t\t\t\t\t\t\tif err := self.connectToBSS(&bss, iface, password); err == nil {\n\t\t\t\t\t\t\t\t\t\t\/\/ Connected, save configuration\n\t\t\t\t\t\t\t\t\t\tcli := wpa_cli.WPACli{NetInterface: self.NetInterface}\n\t\t\t\t\t\t\t\t\t\tif err := cli.SaveConfig(); err == nil {\n\t\t\t\t\t\t\t\t\t\t\tconnectionInfo = ConnectionInfo{NetInterface: self.NetInterface, SSID: ssid,\n\t\t\t\t\t\t\t\t\t\t\t\tIP4: self.context.ip4, IP6: self.context.ip6}\n\t\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t\te = err\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\te = err\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\te = bss.Error\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\te = errors.New(\"ssid_not_found\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\te = iface.Error\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\te = self.context.error\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\te = wpa.Error\n\t\t\t}\n\t\t\tiface.RemoveSignalsObserver()\n\t\t} else {\n\t\t\te = wpa.Error\n\t\t}\n\t\twpa.RemoveSignalsObserver()\n\t\twpa.StopWaitForSignals()\n\t} else {\n\t\te = err\n\t}\n\treturn\n}\n\nfunc (self *connectManager) connectToBSS(bss *wpa_dbus.BSSWPA, iface *wpa_dbus.InterfaceWPA, password string) (e error) {\n\taddNetworkArgs := map[string]dbus.Variant{\n\t\t\"ssid\": dbus.MakeVariant(bss.SSID),\n\t\t\"psk\":  dbus.MakeVariant(password)}\n\tif iface.RemoveAllNetworks().AddNetwork(addNetworkArgs); iface.Error == nil {\n\t\tnetwork := iface.NewNetwork\n\t\tself.context.phaseWaitForInterfaceConnected = true\n\t\tgo func() {\n\t\t\ttime.Sleep(self.deadTime.Sub(time.Now()))\n\t\t\tself.context.connectDone <- false\n\t\t\tself.context.error = errors.New(\"timeout\")\n\t\t}()\n\t\tif network.Select(); network.Error == nil {\n\t\t\tif connected := <-self.context.connectDone; self.context.error == nil {\n\t\t\t\tif connected {\n\t\t\t\t\tif err := self.readNetAddress(); err == nil {\n\t\t\t\t\t} else {\n\t\t\t\t\t\te = err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif iface.ReadDisconnectReason(); iface.Error == nil {\n\t\t\t\t\t\te = errors.New(fmt.Sprintf(\"connection_failed, reason=%d\", iface.DisconnectReason))\n\t\t\t\t\t} else {\n\t\t\t\t\t\te = errors.New(\"connection_failed\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\te = self.context.error\n\t\t\t}\n\t\t} else {\n\t\t\te = network.Error\n\t\t}\n\t} else {\n\t\te = iface.Error\n\t}\n\treturn\n}\n\nfunc (self *connectManager) onSignal(wpa *wpa_dbus.WPA, signal *dbus.Signal) {\n\tlog.Log.Debug(signal.Name, signal.Path)\n\tswitch signal.Name {\n\tcase \"fi.w1.wpa_supplicant1.Interface.BSSAdded\":\n\tcase \"fi.w1.wpa_supplicant1.Interface.BSSRemoved\":\n\t\tbreak\n\tcase \"fi.w1.wpa_supplicant1.Interface.ScanDone\":\n\t\tself.processScanDone(wpa, signal)\n\tcase \"fi.w1.wpa_supplicant1.Interface.PropertiesChanged\":\n\t\tlog.Log.Debug(signal.Name, signal.Path, signal.Body)\n\t\tself.processInterfacePropertiesChanged(wpa, signal)\n\tdefault:\n\t\tlog.Log.Debug(signal.Name, signal.Path, signal.Body)\n\t}\n}\n\nfunc (self *connectManager) readNetAddress() (e error) {\n\tif netIface, err := net.InterfaceByName(self.NetInterface); err == nil {\n\t\tfor time.Now().Before(self.deadTime) && !self.context.hasIP() {\n\t\t\tif addrs, err := netIface.Addrs(); err == nil {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\tif ip, _, err := net.ParseCIDR(addr.String()); err == nil {\n\t\t\t\t\t\tif self.context.ip4 == nil {\n\t\t\t\t\t\t\tself.context.ip4 = ip.To4()\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif self.context.ip6 == nil {\n\t\t\t\t\t\t\tself.context.ip6 = ip.To16()\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\te = err\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\te = err\n\t\t\t}\n\t\t\ttime.Sleep(time.Millisecond * 500)\n\t\t}\n\t\tif !self.context.hasIP() {\n\t\t\te = errors.New(\"address_not_allocated\")\n\t\t}\n\t} else {\n\t\te = err\n\t}\n\treturn\n}\n\nfunc (self *connectManager) processScanDone(wpa *wpa_dbus.WPA, signal *dbus.Signal) {\n\tlog.Log.Debug(\"processScanDone\")\n\tif self.context.phaseWaitForScanDone {\n\t\tself.context.phaseWaitForScanDone = false\n\t\tself.context.scanDone <- true\n\t}\n}\n\nfunc (self *connectManager) processInterfacePropertiesChanged(wpa *wpa_dbus.WPA, signal *dbus.Signal) {\n\tlog.Log.Debug(\"processInterfacePropertiesChanged\")\n\tlog.Log.Debug(\"phaseWaitForInterfaceConnected\", self.context.phaseWaitForInterfaceConnected)\n\tif self.context.phaseWaitForInterfaceConnected {\n\t\tif len(signal.Body) > 0 {\n\t\t\tproperties := signal.Body[0].(map[string]dbus.Variant)\n\t\t\tif stateVariant, hasState := properties[\"State\"]; hasState {\n\t\t\t\tif state, ok := stateVariant.Value().(string); ok {\n\t\t\t\t\tlog.Log.Debug(\"State\", state)\n\t\t\t\t\tif state == \"completed\" {\n\t\t\t\t\t\tself.context.phaseWaitForInterfaceConnected = false\n\t\t\t\t\t\tself.context.connectDone <- true\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else if state == \"disconnected\" {\n\t\t\t\t\t\t\/\/self.context.phaseWaitForInterfaceConnected = false\n\t\t\t\t\t\t\/\/self.context.connectDone <- false\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (self *connectContext) hasIP() bool {\n\treturn self.ip4 != nil && self.ip6 != nil\n}\n\nfunc NewConnectManager(netInterface string) *connectManager {\n\treturn &connectManager{NetInterface: netInterface}\n}\n\ntype ConnectionInfo struct {\n\tNetInterface string\n\tSSID         string\n\tIP4          net.IP\n\tIP6          net.IP\n}\n\ntype connectContext struct {\n\tphaseWaitForScanDone           bool\n\tphaseWaitForInterfaceConnected bool\n\tscanDone                       chan bool\n\tconnectDone                    chan bool\n\tip4                            net.IP\n\tip6                            net.IP\n\terror                          error\n}\n\ntype connectManager struct {\n\tcontext      *connectContext\n\tdeadTime     time.Time\n\tNetInterface string\n}\n\nvar (\n\tConnectManager = &connectManager{NetInterface: \"wlan0\"}\n)\n<commit_msg>add support for connecting to unsecured ssid and hidden network<commit_after>package wpaconnect\n\nimport (\n\t\"errors\"\n\t\"github.com\/mark2b\/wpa-connect\/internal\/wpa_cli\"\n\n\t\"fmt\"\n\t\"github.com\/godbus\/dbus\"\n\t\"github.com\/mark2b\/wpa-connect\/internal\/log\"\n\t\"github.com\/mark2b\/wpa-connect\/internal\/wpa_dbus\"\n\t\"net\"\n\t\"time\"\n)\n\nfunc (self *connectManager) Connect(ssid string, password string, timeout time.Duration) (connectionInfo ConnectionInfo, e error) {\n\tself.deadTime = time.Now().Add(timeout)\n\tself.context = &connectContext{}\n\tself.context.scanDone = make(chan bool)\n\tself.context.connectDone = make(chan bool)\n\tif wpa, err := wpa_dbus.NewWPA(); err == nil {\n\t\twpa.WaitForSignals(self.onSignal)\n\t\twpa.AddSignalsObserver()\n\t\tif wpa.ReadInterface(self.NetInterface); wpa.Error == nil {\n\t\t\tiface := wpa.Interface\n\t\t\tiface.AddSignalsObserver()\n\t\t\tself.context.phaseWaitForScanDone = true\n\t\t\tgo func() {\n\t\t\t\ttime.Sleep(self.deadTime.Sub(time.Now()))\n\t\t\t\tself.context.scanDone <- false\n\t\t\t\tself.context.error = errors.New(\"timeout\")\n\t\t\t}()\n\t\t\tif iface.Scan(); iface.Error == nil {\n\t\t\t\t\/\/ Wait for scan done\n\t\t\t\tif <-self.context.scanDone; self.context.error == nil {\n\t\t\t\t\tif iface.ReadBSSList(); iface.Error == nil {\n\t\t\t\t\t\tbssMap := make(map[string]wpa_dbus.BSSWPA, 0)\n\t\t\t\t\t\tfor _, bss := range iface.BSSs {\n\t\t\t\t\t\t\tif bss.ReadSSID(); bss.Error == nil {\n\t\t\t\t\t\t\t\tbssMap[bss.SSID] = bss\n\t\t\t\t\t\t\t\tlog.Log.Debug(bss.SSID, bss.BSSID)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\te = err\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif e == nil {\n\t\t\t\t\t\t\t_, exists := bssMap[ssid]\n\t\t\t\t\t\t\tif err := self.connectToBSS(&wpa_dbus.BSSWPA{\n\t\t\t\t\t\t\t\tSSID: ssid,\n\t\t\t\t\t\t\t}, iface, password, !exists); err == nil {\n\t\t\t\t\t\t\t\t\/\/ Connected, save configuration\n\t\t\t\t\t\t\t\tcli := wpa_cli.WPACli{NetInterface: self.NetInterface}\n\t\t\t\t\t\t\t\tif err := cli.SaveConfig(); err == nil {\n\t\t\t\t\t\t\t\t\tconnectionInfo = ConnectionInfo{NetInterface: self.NetInterface, SSID: ssid,\n\t\t\t\t\t\t\t\t\t\tIP4: self.context.ip4, IP6: self.context.ip6}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\te = err\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\te = err\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\te = iface.Error\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\te = self.context.error\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\te = wpa.Error\n\t\t\t}\n\t\t\tiface.RemoveSignalsObserver()\n\t\t} else {\n\t\t\te = wpa.Error\n\t\t}\n\t\twpa.RemoveSignalsObserver()\n\t\twpa.StopWaitForSignals()\n\t} else {\n\t\te = err\n\t}\n\treturn\n}\n\nfunc (self *connectManager) connectToBSS(bss *wpa_dbus.BSSWPA, iface *wpa_dbus.InterfaceWPA, password string, isHidden bool) (e error) {\n\taddNetworkArgs := map[string]dbus.Variant{\n\t\t\"ssid\": dbus.MakeVariant(bss.SSID),\n\t}\n\tif isHidden {\n\t\taddNetworkArgs[\"scan_ssid\"] = dbus.MakeVariant(1)\n\t}\n\tif password == \"\" {\n\t\taddNetworkArgs[\"key_mgmt\"] = dbus.MakeVariant(\"NONE\")\n\t} else {\n\t\taddNetworkArgs[\"psk\"] = dbus.MakeVariant(password)\n\t}\n\tif iface.RemoveAllNetworks().AddNetwork(addNetworkArgs); iface.Error == nil {\n\t\tnetwork := iface.NewNetwork\n\t\tself.context.phaseWaitForInterfaceConnected = true\n\t\tgo func() {\n\t\t\ttime.Sleep(self.deadTime.Sub(time.Now()))\n\t\t\tself.context.connectDone <- false\n\t\t\tself.context.error = errors.New(\"timeout\")\n\t\t}()\n\t\tif network.Select(); network.Error == nil {\n\t\t\tif connected := <-self.context.connectDone; self.context.error == nil {\n\t\t\t\tif connected {\n\t\t\t\t\tif err := self.readNetAddress(); err == nil {\n\t\t\t\t\t} else {\n\t\t\t\t\t\te = err\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif iface.ReadDisconnectReason(); iface.Error == nil {\n\t\t\t\t\t\te = errors.New(fmt.Sprintf(\"connection_failed, reason=%d\", iface.DisconnectReason))\n\t\t\t\t\t} else {\n\t\t\t\t\t\te = errors.New(\"connection_failed\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\te = self.context.error\n\t\t\t}\n\t\t} else {\n\t\t\te = network.Error\n\t\t}\n\t} else {\n\t\te = iface.Error\n\t}\n\treturn\n}\n\nfunc (self *connectManager) onSignal(wpa *wpa_dbus.WPA, signal *dbus.Signal) {\n\tlog.Log.Debug(signal.Name, signal.Path)\n\tswitch signal.Name {\n\tcase \"fi.w1.wpa_supplicant1.Interface.BSSAdded\":\n\tcase \"fi.w1.wpa_supplicant1.Interface.BSSRemoved\":\n\t\tbreak\n\tcase \"fi.w1.wpa_supplicant1.Interface.ScanDone\":\n\t\tself.processScanDone(wpa, signal)\n\tcase \"fi.w1.wpa_supplicant1.Interface.PropertiesChanged\":\n\t\tlog.Log.Debug(signal.Name, signal.Path, signal.Body)\n\t\tself.processInterfacePropertiesChanged(wpa, signal)\n\tdefault:\n\t\tlog.Log.Debug(signal.Name, signal.Path, signal.Body)\n\t}\n}\n\nfunc (self *connectManager) readNetAddress() (e error) {\n\tif netIface, err := net.InterfaceByName(self.NetInterface); err == nil {\n\t\tfor time.Now().Before(self.deadTime) && !self.context.hasIP() {\n\t\t\tif addrs, err := netIface.Addrs(); err == nil {\n\t\t\t\tfor _, addr := range addrs {\n\t\t\t\t\tif ip, _, err := net.ParseCIDR(addr.String()); err == nil {\n\t\t\t\t\t\tif self.context.ip4 == nil {\n\t\t\t\t\t\t\tself.context.ip4 = ip.To4()\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif self.context.ip6 == nil {\n\t\t\t\t\t\t\tself.context.ip6 = ip.To16()\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\te = err\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\te = err\n\t\t\t}\n\t\t\ttime.Sleep(time.Millisecond * 500)\n\t\t}\n\t\tif !self.context.hasIP() {\n\t\t\te = errors.New(\"address_not_allocated\")\n\t\t}\n\t} else {\n\t\te = err\n\t}\n\treturn\n}\n\nfunc (self *connectManager) processScanDone(wpa *wpa_dbus.WPA, signal *dbus.Signal) {\n\tlog.Log.Debug(\"processScanDone\")\n\tif self.context.phaseWaitForScanDone {\n\t\tself.context.phaseWaitForScanDone = false\n\t\tself.context.scanDone <- true\n\t}\n}\n\nfunc (self *connectManager) processInterfacePropertiesChanged(wpa *wpa_dbus.WPA, signal *dbus.Signal) {\n\tlog.Log.Debug(\"processInterfacePropertiesChanged\")\n\tlog.Log.Debug(\"phaseWaitForInterfaceConnected\", self.context.phaseWaitForInterfaceConnected)\n\tif self.context.phaseWaitForInterfaceConnected {\n\t\tif len(signal.Body) > 0 {\n\t\t\tproperties := signal.Body[0].(map[string]dbus.Variant)\n\t\t\tif stateVariant, hasState := properties[\"State\"]; hasState {\n\t\t\t\tif state, ok := stateVariant.Value().(string); ok {\n\t\t\t\t\tlog.Log.Debug(\"State\", state)\n\t\t\t\t\tif state == \"completed\" {\n\t\t\t\t\t\tself.context.phaseWaitForInterfaceConnected = false\n\t\t\t\t\t\tself.context.connectDone <- true\n\t\t\t\t\t\treturn\n\t\t\t\t\t} else if state == \"disconnected\" {\n\t\t\t\t\t\t\/\/self.context.phaseWaitForInterfaceConnected = false\n\t\t\t\t\t\t\/\/self.context.connectDone <- false\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (self *connectContext) hasIP() bool {\n\treturn self.ip4 != nil && self.ip6 != nil\n}\n\nfunc NewConnectManager(netInterface string) *connectManager {\n\treturn &connectManager{NetInterface: netInterface}\n}\n\ntype ConnectionInfo struct {\n\tNetInterface string\n\tSSID         string\n\tIP4          net.IP\n\tIP6          net.IP\n}\n\ntype connectContext struct {\n\tphaseWaitForScanDone           bool\n\tphaseWaitForInterfaceConnected bool\n\tscanDone                       chan bool\n\tconnectDone                    chan bool\n\tip4                            net.IP\n\tip6                            net.IP\n\terror                          error\n}\n\ntype connectManager struct {\n\tcontext      *connectContext\n\tdeadTime     time.Time\n\tNetInterface string\n}\n\nvar (\n\tConnectManager = &connectManager{NetInterface: \"wlan0\"}\n)\n<|endoftext|>"}
{"text":"<commit_before>package wsdlgen\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"io\/ioutil\"\n\n\t\"aqwari.net\/xml\/internal\/commandline\"\n\t\"aqwari.net\/xml\/internal\/gen\"\n\t\"aqwari.net\/xml\/xsdgen\"\n)\n\n\/\/ The GenSource method converts the AST returned by GenAST to formatted\n\/\/ Go source code.\nfunc (cfg *Config) GenSource(files ...string) ([]byte, error) {\n\tfile, err := cfg.GenAST(files...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn gen.FormattedSource(file)\n}\n\n\/\/ GenCLI creates a file containing Go source generated from a WSDL\n\/\/ definition. It is intended to be called from the main function of any\n\/\/ command-line interfaces to the wsdlgen package.\nfunc (cfg *Config) GenCLI(arguments ...string) error {\n\tvar (\n\t\terr          error\n\t\treplaceRules commandline.ReplaceRuleList\n\t\tports        commandline.Strings\n\t\tfs           = flag.NewFlagSet(\"wsdlgen\", flag.ExitOnError)\n\t\tpackageName  = fs.String(\"pkg\", \"\", \"name of the generated package\")\n\t\tcomment      = fs.String(\"c\", \"\", \"First line of package-level comments\")\n\t\toutput       = fs.String(\"o\", \"wsdlgen_output.go\", \"name of the output file\")\n\t\tverbose      = fs.Bool(\"v\", false, \"print verbose output\")\n\t\tdebug        = fs.Bool(\"vv\", false, \"print debug output\")\n\t)\n\tfs.Var(&replaceRules, \"r\", \"replacement rule 'regex -> repl' (can be used multiple times)\")\n\tfs.Var(&ports, \"port\", \"gen code for this port (can be used multiple times)\")\n\tfs.Parse(arguments)\n\tif fs.NArg() == 0 {\n\t\treturn errors.New(\"Usage: wsdlgen [-r rule] [-o file] [-port name] [-pkg pkg] file ...\")\n\t}\n\n\tif *debug {\n\t\tcfg.Option(LogLevel(5))\n\t} else if *verbose {\n\t\tcfg.Option(LogLevel(1))\n\t}\n\tif len(*packageName) > 0 {\n\t\tcfg.Option(PackageName(*packageName))\n\t\tcfg.XSDOption(xsdgen.PackageName(*packageName))\n\t}\n\tif len(*comment) > 0 {\n\t\tcfg.Option(PackageComment(*comment))\n\t}\n\tif len(ports) > 0 {\n\t\tcfg.Option(OnlyPorts(ports...))\n\t}\n\tfor _, r := range replaceRules {\n\t\tcfg.XSDOption(xsdgen.Replace(r.From.String(), r.To))\n\t}\n\tfile, err := cfg.GenAST(fs.Args()...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := gen.FormattedSource(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(*output, data, 0666)\n}\n\n\/\/ The GenCLI function generates Go source code using the default\n\/\/ options chosen by the wsdlgen package. It is meant to be used from\n\/\/ the main package of a command-line program.\nfunc GenCLI(args ...string) error {\n\tvar cfg Config\n\tcfg.Option(DefaultOptions...)\n\tcfg.XSDOption(xsdgen.DefaultOptions...)\n\treturn cfg.GenCLI(args...)\n}\n<commit_msg>Write to stderr when using top-level GenCLI function<commit_after>package wsdlgen\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\n\t\"aqwari.net\/xml\/internal\/commandline\"\n\t\"aqwari.net\/xml\/internal\/gen\"\n\t\"aqwari.net\/xml\/xsdgen\"\n)\n\n\/\/ The GenSource method converts the AST returned by GenAST to formatted\n\/\/ Go source code.\nfunc (cfg *Config) GenSource(files ...string) ([]byte, error) {\n\tfile, err := cfg.GenAST(files...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn gen.FormattedSource(file)\n}\n\n\/\/ GenCLI creates a file containing Go source generated from a WSDL\n\/\/ definition. It is intended to be called from the main function of any\n\/\/ command-line interfaces to the wsdlgen package.\nfunc (cfg *Config) GenCLI(arguments ...string) error {\n\tvar (\n\t\terr          error\n\t\treplaceRules commandline.ReplaceRuleList\n\t\tports        commandline.Strings\n\t\tfs           = flag.NewFlagSet(\"wsdlgen\", flag.ExitOnError)\n\t\tpackageName  = fs.String(\"pkg\", \"\", \"name of the generated package\")\n\t\tcomment      = fs.String(\"c\", \"\", \"First line of package-level comments\")\n\t\toutput       = fs.String(\"o\", \"wsdlgen_output.go\", \"name of the output file\")\n\t\tverbose      = fs.Bool(\"v\", false, \"print verbose output\")\n\t\tdebug        = fs.Bool(\"vv\", false, \"print debug output\")\n\t)\n\tfs.Var(&replaceRules, \"r\", \"replacement rule 'regex -> repl' (can be used multiple times)\")\n\tfs.Var(&ports, \"port\", \"gen code for this port (can be used multiple times)\")\n\tfs.Parse(arguments)\n\tif fs.NArg() == 0 {\n\t\treturn errors.New(\"Usage: wsdlgen [-r rule] [-o file] [-port name] [-pkg pkg] file ...\")\n\t}\n\n\tif *debug {\n\t\tcfg.Option(LogLevel(5))\n\t} else if *verbose {\n\t\tcfg.Option(LogLevel(1))\n\t}\n\tif len(*packageName) > 0 {\n\t\tcfg.Option(PackageName(*packageName))\n\t\tcfg.XSDOption(xsdgen.PackageName(*packageName))\n\t}\n\tif len(*comment) > 0 {\n\t\tcfg.Option(PackageComment(*comment))\n\t}\n\tif len(ports) > 0 {\n\t\tcfg.Option(OnlyPorts(ports...))\n\t}\n\tfor _, r := range replaceRules {\n\t\tcfg.XSDOption(xsdgen.Replace(r.From.String(), r.To))\n\t}\n\tfile, err := cfg.GenAST(fs.Args()...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := gen.FormattedSource(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn ioutil.WriteFile(*output, data, 0666)\n}\n\n\/\/ The GenCLI function generates Go source code using the default\n\/\/ options chosen by the wsdlgen package. It is meant to be used from\n\/\/ the main package of a command-line program.\nfunc GenCLI(args ...string) error {\n\tvar cfg Config\n\tcfg.Option(DefaultOptions...)\n\tcfg.XSDOption(xsdgen.DefaultOptions...)\n\tcfg.Option(LogOutput(log.New(os.Stderr, \"\", 0)))\n\treturn cfg.GenCLI(args...)\n}\n<|endoftext|>"}
{"text":"<commit_before>package ipfix\n\nimport (\n\t\"encoding\/binary\"\n\t\"hash\/fnv\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar ShardNo = 32\n\ntype MemCache []TemplatesShard\n\ntype Data struct {\n\tTemplateRecords\n\ttimestamp int64\n}\n\ntype TemplatesShard struct {\n\ttemplate map[string]Data\n\tsync.RWMutex\n}\n\nfunc NewCache() MemCache {\n\tm := make(MemCache, ShardNo)\n\tfor i := 0; i < ShardNo; i++ {\n\t\tm[i] = TemplatesShard{template: make(map[string]Data)}\n\t}\n\treturn m\n}\n\nfunc (m MemCache) getShard(id uint16, addr net.IP) (TemplatesShard, []byte) {\n\tb := make([]byte, 2)\n\tbinary.BigEndian.PutUint16(b, id)\n\tkey := append(addr, b...)\n\n\thash := fnv.New32()\n\thash.Write(key)\n\treturn m[uint(hash.Sum32())%uint(ShardNo)], key\n}\n\nfunc (m *MemCache) insert(id uint16, addr net.IP, tr TemplateRecords) {\n\tshard, key := m.getShard(id, addr)\n\tshard.Lock()\n\tdefer shard.Unlock()\n\tshard.template[string(key)] = Data{tr, time.Now().Unix()}\n}\n\nfunc (m *MemCache) retrieve(id uint16, addr net.IP) (TemplateRecords, bool) {\n\tshard, key := m.getShard(id, addr)\n\tshard.RLock()\n\tdefer shard.RUnlock()\n\tv, ok := shard.template[string(key)]\n\treturn v.TemplateRecords, ok\n}\n\nfunc (m *MemCache) remove(id int, addr string) {\n\t\/\/ TODO\n}\n\nfunc (m *MemCache) cleanup(id int, addr string) {\n\t\/\/ TODO\n}\n\nfunc (m *MemCache) dump(id int, addr string) {\n\t\/\/ TODO\n}\n<commit_msg>change template type to interface<commit_after>package ipfix\n\nimport (\n\t\"encoding\/binary\"\n\t\"hash\/fnv\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar ShardNo = 32\n\ntype MemCache []TemplatesShard\n\ntype Data struct {\n\tTemplateRecords interface{}\n\ttimestamp       int64\n}\n\ntype TemplatesShard struct {\n\ttemplate map[string]Data\n\tsync.RWMutex\n}\n\nfunc NewCache() MemCache {\n\tm := make(MemCache, ShardNo)\n\tfor i := 0; i < ShardNo; i++ {\n\t\tm[i] = TemplatesShard{template: make(map[string]Data)}\n\t}\n\treturn m\n}\n\nfunc (m MemCache) getShard(id uint16, addr net.IP) (TemplatesShard, []byte) {\n\tb := make([]byte, 2)\n\tbinary.BigEndian.PutUint16(b, id)\n\tkey := append(addr, b...)\n\n\thash := fnv.New32()\n\thash.Write(key)\n\treturn m[uint(hash.Sum32())%uint(ShardNo)], key\n}\n\nfunc (m *MemCache) insert(id uint16, addr net.IP, tr interface{}) {\n\tshard, key := m.getShard(id, addr)\n\tshard.Lock()\n\tdefer shard.Unlock()\n\tshard.template[string(key)] = Data{tr, time.Now().Unix()}\n}\n\nfunc (m *MemCache) retrieve(id uint16, addr net.IP) (interface{}, bool) {\n\tshard, key := m.getShard(id, addr)\n\tshard.RLock()\n\tdefer shard.RUnlock()\n\tv, ok := shard.template[string(key)]\n\treturn v.TemplateRecords, ok\n}\n\nfunc (m *MemCache) remove(id int, addr string) {\n\t\/\/ TODO\n}\n\nfunc (m *MemCache) cleanup(id int, addr string) {\n\t\/\/ TODO\n}\n\nfunc (m *MemCache) dump(id int, addr string) {\n\t\/\/ TODO\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build windows\n\npackage i18n_test\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/cloudfoundry\/cli\/cf\/configuration\/core_config\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/i18n\"\n\ttestconfig \"github.com\/cloudfoundry\/cli\/testhelpers\/configuration\"\n\t\"github.com\/pivotal-cf-experimental\/jibber_jabber\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"i18n.Init() function\", func() {\n\tvar (\n\t\tconfigRepo core_config.ReadWriter\n\t)\n\n\tBeforeEach(func() {\n\t\ti18n.Resources_path = filepath.Join(\"cf\", \"i18n\", \"test_fixtures\")\n\t\tconfigRepo = testconfig.NewRepositoryWithDefaults()\n\t})\n\n\tDescribe(\"When a user has a locale configuration set\", func() {\n\t\tContext(\"creates a valid T function\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tconfigRepo.SetLocale(\"en_US\")\n\t\t\t})\n\n\t\t\tIt(\"returns a usable T function for simple strings\", func() {\n\t\t\t\tT := i18n.Init(configRepo)\n\t\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\t\ttranslation := T(\"Hello world!\")\n\t\t\t\tΩ(\"Hello world!\").Should(Equal(translation))\n\t\t\t})\n\n\t\t\tIt(\"returns a usable T function for complex strings (interpolated)\", func() {\n\t\t\t\tT := i18n.Init(configRepo)\n\t\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\t\ttranslation := T(\"Deleting domain {{.DomainName}} as {{.Username}}...\", map[string]interface{}{\"DomainName\": \"foo.com\", \"Username\": \"Anand\"})\n\t\t\t\tΩ(\"Deleting domain foo.com as Anand...\").Should(Equal(translation))\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"When a user does not have a locale configuration set\", func() {\n\t\tBeforeEach(func() {\n\t\t\tos.Setenv(\"LC_ALL\", \"en_US.UTF-8\")\n\n\t\t\t\/\/All these tests require the system language to be English\n\t\t\tΩ(jibber_jabber.DetectIETF()).Should(Equal(\"en-US\"))\n\t\t})\n\n\t\tContext(\"creates a valid T function\", func() {\n\t\t\tIt(\"returns a usable T function for simple strings\", func() {\n\t\t\t\tT := i18n.Init(configRepo)\n\t\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\t\ttranslation := T(\"Change user password\")\n\t\t\t\tΩ(\"Change user password\").Should(Equal(translation))\n\t\t\t})\n\n\t\t\tIt(\"returns a usable T function for complex strings (interpolated)\", func() {\n\t\t\t\tT := i18n.Init(configRepo)\n\t\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\t\ttranslation := T(\"Deleting domain {{.DomainName}} as {{.Username}}...\", map[string]interface{}{\"DomainName\": \"foo\", \"Username\": \"Anand\"})\n\t\t\t\tΩ(\"Deleting domain foo as Anand...\").Should(Equal(translation))\n\t\t\t})\n\t\t})\n\n\t})\n\n\tDescribe(\"When locale is HK\/TW\", func() {\n\t\tIt(\"matches zh_CN to zh_Hans\", func() {\n\t\t\tos.Setenv(\"LC_ALL\", \"zh_CN.UTF-8\")\n\t\t\tT := i18n.Init(configRepo)\n\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\ttranslation := T(\"No buildpacks found\")\n\t\t\tΩ(\"buildpack未找到\").Should(Equal(translation))\n\t\t})\n\n\t\tIt(\"matches zh_TW to zh_Hant\", func() {\n\t\t\tos.Setenv(\"LC_ALL\", \"zh_TW.UTF-8\")\n\t\t\tT := i18n.Init(configRepo)\n\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\ttranslation := T(\"No buildpacks found\")\n\t\t\tΩ(\"(Hant)No buildpacks found\").Should(Equal(translation))\n\t\t})\n\n\t\tIt(\"matches zh_HK to zh_Hant\", func() {\n\t\t\tos.Setenv(\"LC_ALL\", \"zh_HK.UTF-8\")\n\t\t\tT := i18n.Init(configRepo)\n\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\ttranslation := T(\"No buildpacks found\")\n\t\t\tΩ(\"(Hant)No buildpacks found\").Should(Equal(translation))\n\t\t})\n\t})\n})\n<commit_msg>Revert \"fix failing HK\/TW Windows 32 unit test\"<commit_after>\/\/ +build windows\n\npackage i18n_test\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/cloudfoundry\/cli\/cf\/configuration\/core_config\"\n\t\"github.com\/cloudfoundry\/cli\/cf\/i18n\"\n\ttestconfig \"github.com\/cloudfoundry\/cli\/testhelpers\/configuration\"\n\t\"github.com\/pivotal-cf-experimental\/jibber_jabber\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"i18n.Init() function\", func() {\n\tvar (\n\t\tconfigRepo core_config.ReadWriter\n\t)\n\n\tBeforeEach(func() {\n\t\ti18n.Resources_path = filepath.Join(\"cf\", \"i18n\", \"test_fixtures\")\n\t\tconfigRepo = testconfig.NewRepositoryWithDefaults()\n\t})\n\n\tDescribe(\"When a user has a locale configuration set\", func() {\n\t\tContext(\"creates a valid T function\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tconfigRepo.SetLocale(\"en_US\")\n\t\t\t})\n\n\t\t\tIt(\"returns a usable T function for simple strings\", func() {\n\t\t\t\tT := i18n.Init(configRepo)\n\t\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\t\ttranslation := T(\"Hello world!\")\n\t\t\t\tΩ(\"Hello world!\").Should(Equal(translation))\n\t\t\t})\n\n\t\t\tIt(\"returns a usable T function for complex strings (interpolated)\", func() {\n\t\t\t\tT := i18n.Init(configRepo)\n\t\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\t\ttranslation := T(\"Deleting domain {{.DomainName}} as {{.Username}}...\", map[string]interface{}{\"DomainName\": \"foo.com\", \"Username\": \"Anand\"})\n\t\t\t\tΩ(\"Deleting domain foo.com as Anand...\").Should(Equal(translation))\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"When a user does not have a locale configuration set\", func() {\n\t\tBeforeEach(func() {\n\t\t\t\/\/All these tests require the system language to be English\n\t\t\tΩ(jibber_jabber.DetectIETF()).Should(Equal(\"en-US\"))\n\t\t})\n\n\t\tContext(\"creates a valid T function\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tos.Setenv(\"LC_ALL\", \"en_US.UTF-8\")\n\t\t\t})\n\n\t\t\tIt(\"returns a usable T function for simple strings\", func() {\n\t\t\t\tT := i18n.Init(configRepo)\n\t\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\t\ttranslation := T(\"Change user password\")\n\t\t\t\tΩ(\"Change user password\").Should(Equal(translation))\n\t\t\t})\n\n\t\t\tIt(\"returns a usable T function for complex strings (interpolated)\", func() {\n\t\t\t\tT := i18n.Init(configRepo)\n\t\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\t\ttranslation := T(\"Deleting domain {{.DomainName}} as {{.Username}}...\", map[string]interface{}{\"DomainName\": \"foo\", \"Username\": \"Anand\"})\n\t\t\t\tΩ(\"Deleting domain foo as Anand...\").Should(Equal(translation))\n\t\t\t})\n\t\t})\n\n\t\tIt(\"matches zh_CN to zh_Hans\", func() {\n\t\t\tos.Setenv(\"LC_ALL\", \"zh_CN.UTF-8\")\n\t\t\tT := i18n.Init(configRepo)\n\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\ttranslation := T(\"No buildpacks found\")\n\t\t\tΩ(\"buildpack未找到\").Should(Equal(translation))\n\t\t})\n\n\t\tIt(\"matches zh_TW to zh_Hant\", func() {\n\t\t\tos.Setenv(\"LC_ALL\", \"zh_TW.UTF-8\")\n\t\t\tT := i18n.Init(configRepo)\n\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\ttranslation := T(\"No buildpacks found\")\n\t\t\tΩ(\"(Hant)No buildpacks found\").Should(Equal(translation))\n\t\t})\n\n\t\tIt(\"matches zh_HK to zh_Hant\", func() {\n\t\t\tos.Setenv(\"LC_ALL\", \"zh_HK.UTF-8\")\n\t\t\tT := i18n.Init(configRepo)\n\t\t\tΩ(T).ShouldNot(BeNil())\n\n\t\t\ttranslation := T(\"No buildpacks found\")\n\t\t\tΩ(\"(Hant)No buildpacks found\").Should(Equal(translation))\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package ramsql\n\nimport (\n\t\"database\/sql\/driver\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/proullon\/ramsql\/engine\/log\"\n)\n\n\/\/ Stmt implements the Statement interface of sql\/driver\ntype Stmt struct {\n\tconn     *Conn\n\tquery    string\n\tnumInput int\n}\n\nfunc countArguments(query string) int {\n\tfor id := 1; id > 0; id++ {\n\t\tsep := fmt.Sprintf(\"$%d\", id)\n\t\tif strings.Count(query, sep) == 0 {\n\t\t\treturn id - 1\n\t\t}\n\t}\n\n\treturn -1\n}\n\nfunc prepareStatement(c *Conn, query string) *Stmt {\n\n\t\/\/ Parse number of arguments here\n\t\/\/ Should handler either Postgres ($*) or ODBC (?) parameter markers\n\tnumInput := strings.Count(query, \"?\")\n\t\/\/ if numInput == 0, maybe it's Postgres format\n\tif numInput == 0 {\n\t\tnumInput = countArguments(query)\n\t}\n\n\t\/\/ Create statement\n\tstmt := &Stmt{\n\t\tconn:     c,\n\t\tquery:    query,\n\t\tnumInput: numInput,\n\t}\n\n\tstmt.conn.mutex.Lock()\n\treturn stmt\n}\n\n\/\/ Close closes the statement.\n\/\/\n\/\/ As of Go 1.1, a Stmt will not be closed if it's in use\n\/\/ by any queries.\nfunc (s *Stmt) Close() error {\n\treturn fmt.Errorf(\"Not implemented.\")\n}\n\n\/\/ NumInput returns the number of placeholder parameters.\n\/\/\n\/\/ If NumInput returns >= 0, the sql package will sanity check\n\/\/ argument counts from callers and return errors to the caller\n\/\/ before the statement's Exec or Query methods are called.\n\/\/\n\/\/ NumInput may also return -1, if the driver doesn't know\n\/\/ its number of placeholders. In that case, the sql package\n\/\/ will not sanity check Exec or Query argument counts.\nfunc (s *Stmt) NumInput() int {\n\treturn s.numInput\n}\n\n\/\/ Exec executes a query that doesn't return rows, such\n\/\/ as an INSERT or UPDATE.\nfunc (s *Stmt) Exec(args []driver.Value) (driver.Result, error) {\n\tdefer s.conn.mutex.Unlock()\n\tvar finalQuery string\n\n\t\/\/ replace $* by arguments in query string\n\tfinalQuery = replaceArguments(s.query, args)\n\tlog.Info(\"Exec <%s>\\n\", finalQuery)\n\n\t\/\/ Send query to server\n\terr := s.conn.conn.WriteExec(finalQuery)\n\tif err != nil {\n\t\tlog.Warning(\"Exec: Cannot send query to server: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Cannot send query to server: %s\", err)\n\t}\n\n\t\/\/ Get answer from server\n\tlastInsertedID, rowsAffected, err := s.conn.conn.ReadResult()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Create a driver.Result\n\treturn newResult(lastInsertedID, rowsAffected), nil\n}\n\n\/\/ Query executes a query that may return rows, such as a\n\/\/ SELECT.\nfunc (s *Stmt) Query(args []driver.Value) (driver.Rows, error) {\n\tdefer s.conn.mutex.Unlock()\n\n\tfinalQuery := replaceArguments(s.query, args)\n\tlog.Info(\"Query <%s>\\n\", finalQuery)\n\terr := s.conn.conn.WriteQuery(finalQuery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trowsChannel, err := s.conn.conn.ReadRows()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr := newRows(rowsChannel)\n\treturn r, nil\n}\n\n\/\/ replace $* by arguments in query string\nfunc replaceArguments(query string, args []driver.Value) string {\n\n\tholder := regexp.MustCompile(`[^\\$]\\$[0-9]+`)\n\treplacedQuery := \"\"\n\n\tif strings.Count(query, \"?\") == len(args) {\n\t\treturn replaceArgumentsODBC(query, args)\n\t}\n\n\tallloc := holder.FindAllIndex([]byte(query), -1)\n\tqueryB := []byte(query)\n\tfor i, loc := range allloc {\n\t\tmatch := queryB[loc[0]+1 : loc[1]]\n\n\t\tindex, err := strconv.Atoi(string(match[1:]))\n\t\tif err != nil {\n\t\t\tlog.Warning(\"Matched %s as a placeholder but cannot get index: %s\\n\", match, err)\n\t\t\treturn query\n\t\t}\n\n\t\tvar v string\n\t\tif args[index-1] == nil {\n\t\t\tv = \"null\"\n\t\t} else {\n\t\t\tv = fmt.Sprintf(\"$$%v$$\", args[index-1])\n\t\t}\n\t\tif i == 0 {\n\t\t\treplacedQuery = fmt.Sprintf(\"%s%s%s\", replacedQuery, string(queryB[:loc[0]+1]), v)\n\t\t} else {\n\t\t\treplacedQuery = fmt.Sprintf(\"%s%s%s\", replacedQuery, string(queryB[allloc[i-1][1]:loc[0]+1]), v)\n\t\t}\n\t}\n\t\/\/ add remaining query\n\treplacedQuery = fmt.Sprintf(\"%s%s\", replacedQuery, string(queryB[allloc[len(allloc)-1][1]:]))\n\n\treturn replacedQuery\n}\n\nfunc replaceArgumentsODBC(query string, args []driver.Value) string {\n\tvar finalQuery string\n\n\tqueryParts := strings.Split(query, \"?\")\n\tfinalQuery = queryParts[0]\n\tfor i := range args {\n\t\targ := fmt.Sprintf(\"%v\", args[i])\n\t\t_, ok := args[i].(string)\n\t\tif ok && !strings.HasSuffix(query, \"'\") {\n\t\t\targ = \"$$\" + arg + \"$$\"\n\t\t}\n\t\tfinalQuery += arg\n\t\tfinalQuery += queryParts[i+1]\n\t}\n\n\treturn finalQuery\n}\n<commit_msg>fix (driver): prevent panic<commit_after>package ramsql\n\nimport (\n\t\"database\/sql\/driver\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/proullon\/ramsql\/engine\/log\"\n)\n\n\/\/ Stmt implements the Statement interface of sql\/driver\ntype Stmt struct {\n\tconn     *Conn\n\tquery    string\n\tnumInput int\n}\n\nfunc countArguments(query string) int {\n\tfor id := 1; id > 0; id++ {\n\t\tsep := fmt.Sprintf(\"$%d\", id)\n\t\tif strings.Count(query, sep) == 0 {\n\t\t\treturn id - 1\n\t\t}\n\t}\n\n\treturn -1\n}\n\nfunc prepareStatement(c *Conn, query string) *Stmt {\n\n\t\/\/ Parse number of arguments here\n\t\/\/ Should handler either Postgres ($*) or ODBC (?) parameter markers\n\tnumInput := strings.Count(query, \"?\")\n\t\/\/ if numInput == 0, maybe it's Postgres format\n\tif numInput == 0 {\n\t\tnumInput = countArguments(query)\n\t}\n\n\t\/\/ Create statement\n\tstmt := &Stmt{\n\t\tconn:     c,\n\t\tquery:    query,\n\t\tnumInput: numInput,\n\t}\n\n\tstmt.conn.mutex.Lock()\n\treturn stmt\n}\n\n\/\/ Close closes the statement.\n\/\/\n\/\/ As of Go 1.1, a Stmt will not be closed if it's in use\n\/\/ by any queries.\nfunc (s *Stmt) Close() error {\n\treturn fmt.Errorf(\"Not implemented.\")\n}\n\n\/\/ NumInput returns the number of placeholder parameters.\n\/\/\n\/\/ If NumInput returns >= 0, the sql package will sanity check\n\/\/ argument counts from callers and return errors to the caller\n\/\/ before the statement's Exec or Query methods are called.\n\/\/\n\/\/ NumInput may also return -1, if the driver doesn't know\n\/\/ its number of placeholders. In that case, the sql package\n\/\/ will not sanity check Exec or Query argument counts.\nfunc (s *Stmt) NumInput() int {\n\treturn s.numInput\n}\n\n\/\/ Exec executes a query that doesn't return rows, such\n\/\/ as an INSERT or UPDATE.\nfunc (s *Stmt) Exec(args []driver.Value) (r driver.Result, err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"fatalf error: %s\", r)\n\t\t\treturn\n\t\t}\n\t}()\n\tdefer s.conn.mutex.Unlock()\n\n\tvar finalQuery string\n\n\t\/\/ replace $* by arguments in query string\n\tfinalQuery = replaceArguments(s.query, args)\n\tlog.Info(\"Exec <%s>\\n\", finalQuery)\n\n\t\/\/ Send query to server\n\terr = s.conn.conn.WriteExec(finalQuery)\n\tif err != nil {\n\t\tlog.Warning(\"Exec: Cannot send query to server: %s\", err)\n\t\treturn nil, fmt.Errorf(\"Cannot send query to server: %s\", err)\n\t}\n\n\t\/\/ Get answer from server\n\tlastInsertedID, rowsAffected, err := s.conn.conn.ReadResult()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Create a driver.Result\n\treturn newResult(lastInsertedID, rowsAffected), nil\n}\n\n\/\/ Query executes a query that may return rows, such as a\n\/\/ SELECT.\nfunc (s *Stmt) Query(args []driver.Value) (r driver.Rows, err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"fatalf error: %s\", r)\n\t\t\treturn\n\t\t}\n\t}()\n\tdefer s.conn.mutex.Unlock()\n\n\tfinalQuery := replaceArguments(s.query, args)\n\tlog.Info(\"Query <%s>\\n\", finalQuery)\n\terr = s.conn.conn.WriteQuery(finalQuery)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trowsChannel, err := s.conn.conn.ReadRows()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr = newRows(rowsChannel)\n\treturn r, nil\n}\n\n\/\/ replace $* by arguments in query string\nfunc replaceArguments(query string, args []driver.Value) string {\n\n\tholder := regexp.MustCompile(`[^\\$]\\$[0-9]+`)\n\treplacedQuery := \"\"\n\n\tif strings.Count(query, \"?\") == len(args) {\n\t\treturn replaceArgumentsODBC(query, args)\n\t}\n\n\tallloc := holder.FindAllIndex([]byte(query), -1)\n\tqueryB := []byte(query)\n\tfor i, loc := range allloc {\n\t\tmatch := queryB[loc[0]+1 : loc[1]]\n\n\t\tindex, err := strconv.Atoi(string(match[1:]))\n\t\tif err != nil {\n\t\t\tlog.Warning(\"Matched %s as a placeholder but cannot get index: %s\\n\", match, err)\n\t\t\treturn query\n\t\t}\n\n\t\tvar v string\n\t\tif args[index-1] == nil {\n\t\t\tv = \"null\"\n\t\t} else {\n\t\t\tv = fmt.Sprintf(\"$$%v$$\", args[index-1])\n\t\t}\n\t\tif i == 0 {\n\t\t\treplacedQuery = fmt.Sprintf(\"%s%s%s\", replacedQuery, string(queryB[:loc[0]+1]), v)\n\t\t} else {\n\t\t\treplacedQuery = fmt.Sprintf(\"%s%s%s\", replacedQuery, string(queryB[allloc[i-1][1]:loc[0]+1]), v)\n\t\t}\n\t}\n\t\/\/ add remaining query\n\treplacedQuery = fmt.Sprintf(\"%s%s\", replacedQuery, string(queryB[allloc[len(allloc)-1][1]:]))\n\n\treturn replacedQuery\n}\n\nfunc replaceArgumentsODBC(query string, args []driver.Value) string {\n\tvar finalQuery string\n\n\tqueryParts := strings.Split(query, \"?\")\n\tfinalQuery = queryParts[0]\n\tfor i := range args {\n\t\targ := fmt.Sprintf(\"%v\", args[i])\n\t\t_, ok := args[i].(string)\n\t\tif ok && !strings.HasSuffix(query, \"'\") {\n\t\t\targ = \"$$\" + arg + \"$$\"\n\t\t}\n\t\tfinalQuery += arg\n\t\tfinalQuery += queryParts[i+1]\n\t}\n\n\treturn finalQuery\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*******************************************************************************\nThe MIT License (MIT)\n\nCopyright (c) 2013-2014 Hajime Nakagami\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*******************************************************************************\/\n\npackage firebirdsql\n\nimport (\n\t\"database\/sql\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestBasic(t *testing.T) {\n\tconn, err := sql.Open(\"firebirdsql_createdb\", \"sysdba:masterkey@localhost:3050\/tmp\/go_test_basic.fdb\")\n\tdefer conn.Close()\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error connecting: %v\", err)\n\t}\n\tvar sql string\n\tvar n int\n\n\tsql = \"SELECT Count(*) FROM rdb$relations where rdb$relation_name='FOO'\"\n\terr = conn.QueryRow(sql).Scan(&n)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif n > 0 {\n\t\tconn.Exec(\"DROP TABLE foo\")\n\t}\n\n\tsql = `\n        CREATE TABLE foo (\n            a INTEGER NOT NULL,\n            b VARCHAR(30) NOT NULL UNIQUE,\n            c VARCHAR(1024),\n            d DECIMAL(16,3) DEFAULT -0.123,\n            e DATE DEFAULT '1967-08-11',\n            f TIMESTAMP DEFAULT '1967-08-11 23:45:01',\n            g TIME DEFAULT '23:45:01',\n            h BLOB SUB_TYPE 1, \n            i DOUBLE PRECISION DEFAULT 0.0,\n            j FLOAT DEFAULT 0.0,\n            PRIMARY KEY (a),\n            CONSTRAINT CHECK_A CHECK (a <> 0)\n        )\n    `\n\tconn.Exec(sql)\n\t_, err = conn.Exec(\"CREATE TABLE foo (a INTEGER)\")\n\tif err == nil {\n\t\tt.Fatalf(\"Need metadata update error\")\n\t}\n\tif err.Error() != \"unsuccessful metadata update\\nTable FOO already exists\\n\" {\n\t\tt.Fatalf(\"Bad message:%v\", err.Error())\n\t}\n\n\t\/\/ 3 records insert\n\tconn.Exec(\"insert into foo(a, b, c,h) values (1, 'a', 'b','This is a memo')\")\n\tconn.Exec(\"insert into foo(a, b, c, e, g, i, j) values (2, 'A', 'B', '1999-01-25', '00:00:01', 0.1, 0.1)\")\n\tconn.Exec(\"insert into foo(a, b, c, e, g, i, j) values (3, 'X', 'Y', '2001-07-05', '00:01:02', 0.2, 0.2)\")\n\n\terr = conn.QueryRow(\"select count(*) cnt from foo\").Scan(&n)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif n != 3 {\n\t\tt.Fatalf(\"Error bad record count: %v\", n)\n\t}\n\n\trows, err := conn.Query(\"select a, b, c, d, e, f, g, i, j from foo\")\n\tvar a int\n\tvar b, c string\n\tvar d float64\n\tvar e time.Time\n\tvar f time.Time\n\tvar g time.Time\n\tvar i float64\n\tvar j float32\n\n\tfor rows.Next() {\n\t\trows.Scan(&a, &b, &c, &d, &e, &f, &g, &i, &j)\n\t}\n\n\tstmt, _ := conn.Prepare(\"select count(*) from foo where a=? and b=? and d=? and e=? and f=? and g=?\")\n\tep := time.Date(1967, 8, 11, 0, 0, 0, 0, time.UTC)\n\tfp := time.Date(1967, 8, 11, 23, 45, 1, 0, time.UTC)\n\tgp, err := time.Parse(\"15:04:05\", \"23:45:01\")\n\terr = stmt.QueryRow(1, \"a\", -0.123, ep, fp, gp).Scan(&n)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif n != 1 {\n\t\tt.Fatalf(\"Error bad record count: %v\", n)\n\t}\n}\n\nfunc TestReturning(t *testing.T) {\n\tconn, _ := sql.Open(\"firebirdsql_createdb\", \"SYSDBA:masterkey@localhost:3050\/tmp\/go_test_returning.fdb\")\n\tdefer conn.Close()\n\n\tconn.Exec(`\n        CREATE TABLE test_returning (\n            f1 integer NOT NULL,\n            f2 integer default 2,\n            f3 varchar(20) default 'abc')`)\n\tfor i := 0; i < 2; i++ {\n\n\t\trows, err := conn.Query(\"INSERT INTO test_returning (f1) values (1) returning f2, f3\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error Insert returning : %v\", err)\n\t\t}\n\t\tvar f2 int\n\t\tvar f3 string\n\t\trows.Next()\n\t\trows.Scan(&f2, &f3)\n\t\tif f2 != 2 || f3 != \"abc\" {\n\t\t\tt.Fatalf(\"Bad value insert returning: %v,%v\", f2, f3)\n\t\t}\n\t}\n\n}\n\nfunc TestIssue2(t *testing.T) {\n\tconn, _ := sql.Open(\"firebirdsql_createdb\", \"sysdba:masterkey@localhost:3050\/tmp\/go_test_issue2.fdb\")\n\n\t_, err := conn.Exec(`\n        CREATE TABLE test_issue2\n         (f1 integer NOT NULL,\n          f2 integer,\n          f3 integer NOT NULL,\n          f4 integer NOT NULL,\n          f5 integer NOT NULL,\n          f6 integer NOT NULL,\n          f7 varchar(255) NOT NULL,\n          f8 varchar(255) NOT NULL,\n          f9 varchar(255) NOT NULL,\n          f10 varchar(255) NOT NULL,\n          f11 varchar(255) NOT NULL,\n          f12 varchar(255) NOT NULL,\n          f13 varchar(255) NOT NULL,\n          f14 varchar(255) NOT NULL,\n          f15 integer,\n          f16 integer,\n          f17 integer,\n          f18 integer,\n          f19 integer,\n          f20 integer,\n          f21 integer,\n          f22 varchar(1),\n          f23 varchar(255),\n          f24 integer,\n          f25 varchar(64),\n          f26 integer)`)\n\tdefer conn.Close()\n\tif err != nil {\n\t\tt.Fatalf(\"Error Create Table: %v\", err)\n\t}\n\n\t_, err = conn.Exec(`\n        INSERT INTO test_issue2 VALUES\n        (1, 2, 3, 4, 5, 6, '7', '8', '9', '10', '11', '12', '13', '14',\n          15, 16, 17, 18, 19, 20, 21, 'A', '23', 24, '25', '26')`)\n\tif err != nil {\n\t\tt.Fatalf(\"Error Insert: %v\", err)\n\t}\n\n\trows, err := conn.Query(\"SELECT * FROM test_issue2\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error Query: %v\", err)\n\t}\n\tfor rows.Next() {\n\t}\n}\n\nfunc TestIssue3(t *testing.T) {\n\tconn, _ := sql.Open(\"firebirdsql_createdb\", \"sysdba:masterkey@localhost:3050\/tmp\/go_test_issue3.fdb\")\n\ttoo_many := 401\n\n\tconn.Exec(\"CREATE TABLE test_issue3 (f1 integer NOT NULL)\")\n\tdefer conn.Close()\n\tstmt, _ := conn.Prepare(\"INSERT INTO test_issue3 values (?)\")\n\tfor i := 0; i < too_many; i++ {\n\t\tstmt.Exec(i + 1)\n\t}\n\n\trows, _ := conn.Query(\"SELECT * FROM test_issue3 ORDER BY f1\")\n\ti := 0\n\tvar n int\n\tfor rows.Next() {\n\t\trows.Scan(&n)\n\t\ti++\n\t\tif i != n {\n\t\t\tt.Fatalf(\"Error %v != %v\", n, i)\n\t\t}\n\t}\n\tif i != too_many {\n\t\tt.Fatalf(\"Can't get all %v records. only %v\", too_many, i)\n\t}\n}\n\nfunc TestError(t *testing.T) {\n\tconn, err := sql.Open(\"firebirdsql_createdb\", \"sysdba:masterkey@localhost:3050\/tmp\/go_test_error.fdb\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error connecting: %v\", err)\n\t}\n\t_, err = conn.Exec(\"incorrect sql statement\")\n\tif err == nil || err.Error() != \"Dynamic SQL Error\\nSQL error code = -104\\nToken unknown - line 1, column 1\\nincorrect\\n\" {\n\t\tt.Fatalf(\"Incorrect error\")\n\t}\n}\n\n\/*\nfunc TestFB3(t *testing.T) {\n\tconn, err := sql.Open(\"firebirdsql_createdb\", \"sysdba:masterkey@localhost:3050\/tmp\/go_test_fb3.fdb\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error connecting: %v\", err)\n\t}\n\tvar sql string\n\tvar n int\n\n\tsql = \"SELECT Count(*) FROM rdb$relations where rdb$relation_name='TEST_FB3'\"\n\terr = conn.QueryRow(sql).Scan(&n)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif n > 0 {\n\t\tconn.Exec(\"DROP TABLE test_fb3\")\n\t}\n\n\tsql = `\n        CREATE TABLE test_fb3 (\n            b BOOLEAN\n        )\n    `\n\tconn.Exec(sql)\n\tconn.Exec(\"insert into test_fb3(b) values (true)\")\n\tconn.Exec(\"insert into test_fb3(b) values (false)\")\n    var b bool\n\terr = conn.QueryRow(\"select * from test_fb3 where b is true\").Scan(&b)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif b != true{\n\t\tconn.Exec(\"Invalid boolean value\")\n\t}\n\terr = conn.QueryRow(\"select * from test_fb3 where b is false\").Scan(&b)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif b != false{\n\t\tconn.Exec(\"Invalid boolean value\")\n\t}\n\n\tstmt, _ := conn.Prepare(\"select * from test_fb3 where b=?\")\n\terr = stmt.QueryRow(true).Scan(&b)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif b != false{\n\t\tconn.Exec(\"Invalid boolean value\")\n\t}\n\n\tdefer conn.Close()\n}\n*\/\n<commit_msg>'firebirdsql_createdb' driver Can't call Query() multi time. So Please use 'firebirdsql' driver #5<commit_after>\/*******************************************************************************\nThe MIT License (MIT)\n\nCopyright (c) 2013-2014 Hajime Nakagami\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n*******************************************************************************\/\n\npackage firebirdsql\n\nimport (\n\t\"database\/sql\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestBasic(t *testing.T) {\n\tconn, err := sql.Open(\"firebirdsql_createdb\", \"sysdba:masterkey@localhost:3050\/tmp\/go_test_basic.fdb\")\n\tdefer conn.Close()\n\n\tif err != nil {\n\t\tt.Fatalf(\"Error connecting: %v\", err)\n\t}\n\tvar sql string\n\tvar n int\n\n\tsql = \"SELECT Count(*) FROM rdb$relations where rdb$relation_name='FOO'\"\n\terr = conn.QueryRow(sql).Scan(&n)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif n > 0 {\n\t\tconn.Exec(\"DROP TABLE foo\")\n\t}\n\n\tsql = `\n        CREATE TABLE foo (\n            a INTEGER NOT NULL,\n            b VARCHAR(30) NOT NULL UNIQUE,\n            c VARCHAR(1024),\n            d DECIMAL(16,3) DEFAULT -0.123,\n            e DATE DEFAULT '1967-08-11',\n            f TIMESTAMP DEFAULT '1967-08-11 23:45:01',\n            g TIME DEFAULT '23:45:01',\n            h BLOB SUB_TYPE 1, \n            i DOUBLE PRECISION DEFAULT 0.0,\n            j FLOAT DEFAULT 0.0,\n            PRIMARY KEY (a),\n            CONSTRAINT CHECK_A CHECK (a <> 0)\n        )\n    `\n\tconn.Exec(sql)\n\t_, err = conn.Exec(\"CREATE TABLE foo (a INTEGER)\")\n\tif err == nil {\n\t\tt.Fatalf(\"Need metadata update error\")\n\t}\n\tif err.Error() != \"unsuccessful metadata update\\nTable FOO already exists\\n\" {\n\t\tt.Fatalf(\"Bad message:%v\", err.Error())\n\t}\n\n\t\/\/ 3 records insert\n\tconn.Exec(\"insert into foo(a, b, c,h) values (1, 'a', 'b','This is a memo')\")\n\tconn.Exec(\"insert into foo(a, b, c, e, g, i, j) values (2, 'A', 'B', '1999-01-25', '00:00:01', 0.1, 0.1)\")\n\tconn.Exec(\"insert into foo(a, b, c, e, g, i, j) values (3, 'X', 'Y', '2001-07-05', '00:01:02', 0.2, 0.2)\")\n\n\terr = conn.QueryRow(\"select count(*) cnt from foo\").Scan(&n)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif n != 3 {\n\t\tt.Fatalf(\"Error bad record count: %v\", n)\n\t}\n\n\trows, err := conn.Query(\"select a, b, c, d, e, f, g, i, j from foo\")\n\tvar a int\n\tvar b, c string\n\tvar d float64\n\tvar e time.Time\n\tvar f time.Time\n\tvar g time.Time\n\tvar i float64\n\tvar j float32\n\n\tfor rows.Next() {\n\t\trows.Scan(&a, &b, &c, &d, &e, &f, &g, &i, &j)\n\t}\n\n\tstmt, _ := conn.Prepare(\"select count(*) from foo where a=? and b=? and d=? and e=? and f=? and g=?\")\n\tep := time.Date(1967, 8, 11, 0, 0, 0, 0, time.UTC)\n\tfp := time.Date(1967, 8, 11, 23, 45, 1, 0, time.UTC)\n\tgp, err := time.Parse(\"15:04:05\", \"23:45:01\")\n\terr = stmt.QueryRow(1, \"a\", -0.123, ep, fp, gp).Scan(&n)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif n != 1 {\n\t\tt.Fatalf(\"Error bad record count: %v\", n)\n\t}\n}\n\nfunc TestReturning(t *testing.T) {\n\tconn, _ := sql.Open(\"firebirdsql_createdb\", \"SYSDBA:masterkey@localhost:3050\/tmp\/go_test_returning.fdb\")\n\tdefer conn.Close()\n\n\tconn.Exec(`\n        CREATE TABLE test_returning (\n            f1 integer NOT NULL,\n            f2 integer default 2,\n            f3 varchar(20) default 'abc')`)\n\tconn.Close()\n\n\tconn, _ = sql.Open(\"firebirdsql\", \"SYSDBA:masterkey@localhost:3050\/tmp\/go_test_returning.fdb\")\n\n\tfor i := 0; i < 2; i++ {\n\n\t\trows, err := conn.Query(\"INSERT INTO test_returning (f1) values (1) returning f2, f3\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error Insert returning : %v\", err)\n\t\t}\n\t\tvar f2 int\n\t\tvar f3 string\n\t\trows.Next()\n\t\trows.Scan(&f2, &f3)\n\t\tif f2 != 2 || f3 != \"abc\" {\n\t\t\tt.Fatalf(\"Bad value insert returning: %v,%v\", f2, f3)\n\t\t}\n\t}\n\n}\n\nfunc TestIssue2(t *testing.T) {\n\tconn, _ := sql.Open(\"firebirdsql_createdb\", \"sysdba:masterkey@localhost:3050\/tmp\/go_test_issue2.fdb\")\n\n\t_, err := conn.Exec(`\n        CREATE TABLE test_issue2\n         (f1 integer NOT NULL,\n          f2 integer,\n          f3 integer NOT NULL,\n          f4 integer NOT NULL,\n          f5 integer NOT NULL,\n          f6 integer NOT NULL,\n          f7 varchar(255) NOT NULL,\n          f8 varchar(255) NOT NULL,\n          f9 varchar(255) NOT NULL,\n          f10 varchar(255) NOT NULL,\n          f11 varchar(255) NOT NULL,\n          f12 varchar(255) NOT NULL,\n          f13 varchar(255) NOT NULL,\n          f14 varchar(255) NOT NULL,\n          f15 integer,\n          f16 integer,\n          f17 integer,\n          f18 integer,\n          f19 integer,\n          f20 integer,\n          f21 integer,\n          f22 varchar(1),\n          f23 varchar(255),\n          f24 integer,\n          f25 varchar(64),\n          f26 integer)`)\n\tdefer conn.Close()\n\tif err != nil {\n\t\tt.Fatalf(\"Error Create Table: %v\", err)\n\t}\n\n\t_, err = conn.Exec(`\n        INSERT INTO test_issue2 VALUES\n        (1, 2, 3, 4, 5, 6, '7', '8', '9', '10', '11', '12', '13', '14',\n          15, 16, 17, 18, 19, 20, 21, 'A', '23', 24, '25', '26')`)\n\tif err != nil {\n\t\tt.Fatalf(\"Error Insert: %v\", err)\n\t}\n\n\trows, err := conn.Query(\"SELECT * FROM test_issue2\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error Query: %v\", err)\n\t}\n\tfor rows.Next() {\n\t}\n}\n\nfunc TestIssue3(t *testing.T) {\n\tconn, _ := sql.Open(\"firebirdsql_createdb\", \"sysdba:masterkey@localhost:3050\/tmp\/go_test_issue3.fdb\")\n\ttoo_many := 401\n\n\tconn.Exec(\"CREATE TABLE test_issue3 (f1 integer NOT NULL)\")\n\tdefer conn.Close()\n\tstmt, _ := conn.Prepare(\"INSERT INTO test_issue3 values (?)\")\n\tfor i := 0; i < too_many; i++ {\n\t\tstmt.Exec(i + 1)\n\t}\n\n\trows, _ := conn.Query(\"SELECT * FROM test_issue3 ORDER BY f1\")\n\ti := 0\n\tvar n int\n\tfor rows.Next() {\n\t\trows.Scan(&n)\n\t\ti++\n\t\tif i != n {\n\t\t\tt.Fatalf(\"Error %v != %v\", n, i)\n\t\t}\n\t}\n\tif i != too_many {\n\t\tt.Fatalf(\"Can't get all %v records. only %v\", too_many, i)\n\t}\n}\n\nfunc TestError(t *testing.T) {\n\tconn, err := sql.Open(\"firebirdsql_createdb\", \"sysdba:masterkey@localhost:3050\/tmp\/go_test_error.fdb\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error connecting: %v\", err)\n\t}\n\t_, err = conn.Exec(\"incorrect sql statement\")\n\tif err == nil || err.Error() != \"Dynamic SQL Error\\nSQL error code = -104\\nToken unknown - line 1, column 1\\nincorrect\\n\" {\n\t\tt.Fatalf(\"Incorrect error\")\n\t}\n}\n\n\/*\nfunc TestFB3(t *testing.T) {\n\tconn, err := sql.Open(\"firebirdsql_createdb\", \"sysdba:masterkey@localhost:3050\/tmp\/go_test_fb3.fdb\")\n\tif err != nil {\n\t\tt.Fatalf(\"Error connecting: %v\", err)\n\t}\n\tvar sql string\n\tvar n int\n\n\tsql = \"SELECT Count(*) FROM rdb$relations where rdb$relation_name='TEST_FB3'\"\n\terr = conn.QueryRow(sql).Scan(&n)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif n > 0 {\n\t\tconn.Exec(\"DROP TABLE test_fb3\")\n\t}\n\n\tsql = `\n        CREATE TABLE test_fb3 (\n            b BOOLEAN\n        )\n    `\n\tconn.Exec(sql)\n\tconn.Exec(\"insert into test_fb3(b) values (true)\")\n\tconn.Exec(\"insert into test_fb3(b) values (false)\")\n    var b bool\n\terr = conn.QueryRow(\"select * from test_fb3 where b is true\").Scan(&b)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif b != true{\n\t\tconn.Exec(\"Invalid boolean value\")\n\t}\n\terr = conn.QueryRow(\"select * from test_fb3 where b is false\").Scan(&b)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif b != false{\n\t\tconn.Exec(\"Invalid boolean value\")\n\t}\n\n\tstmt, _ := conn.Prepare(\"select * from test_fb3 where b=?\")\n\terr = stmt.QueryRow(true).Scan(&b)\n\tif err != nil {\n\t\tt.Fatalf(\"Error QueryRow: %v\", err)\n\t}\n\tif b != false{\n\t\tconn.Exec(\"Invalid boolean value\")\n\t}\n\n\tdefer conn.Close()\n}\n*\/\n<|endoftext|>"}
{"text":"<commit_before>package integration_test\n\nimport (\n\t\"fmt\"\n\t\"os\/exec\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry\/libbuildpack\/cutlass\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"Deploy app with\", func() {\n\tvar (\n\t\tapp                       *cutlass.App\n\t\tserviceName, serviceName2 string\n\t\tdynatraceAPI              *cutlass.App\n\t\tdynatraceAPIURI           string\n\t)\n\n\tvar RunCf = func(args ...string) error {\n\t\tcommand := exec.Command(\"cf\", args...)\n\t\tcommand.Stdout = GinkgoWriter\n\t\tcommand.Stderr = GinkgoWriter\n\t\treturn command.Run()\n\t}\n\n\tBeforeEach(func() {\n\t\tdynatraceAPI = cutlass.New(Fixtures(\"fake_dynatrace_api\"))\n\t\tdynatraceAPI.SetEnv(\"BP_DEBUG\", \"true\")\n\n\t\tExpect(dynatraceAPI.Push()).To(Succeed())\n\t\tEventually(func() ([]string, error) { return dynatraceAPI.InstanceStates() }, 60*time.Second).Should(Equal([]string{\"RUNNING\"}))\n\n\t\tvar err error\n\t\tdynatraceAPIURI, err = dynatraceAPI.GetUrl(\"\")\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\tapp = cutlass.New(Fixtures(\"with_dynatrace\"))\n\t\tapp.SetEnv(\"BP_DEBUG\", \"true\")\n\t\tExpect(app.PushNoStart()).To(Succeed())\n\t})\n\n\tAfterEach(func() {\n\t\tapp = DestroyApp(app)\n\t\tdynatraceAPI = DestroyApp(dynatraceAPI)\n\n\t\tif serviceName != \"\" {\n\t\t\t_ = RunCf(\"delete-service\", \"-f\", serviceName)\n\t\t\tserviceName = \"\"\n\t\t}\n\t\tif serviceName2 != \"\" {\n\t\t\t_ = RunCf(\"delete-service\", \"-f\", serviceName2)\n\t\t\tserviceName2 = \"\"\n\t\t}\n\t})\n\n\tFIt(\"single dynatrace service without manifest.json\", func() {\n\t\tserviceName = \"dynatrace-service-\" + cutlass.RandStringRunes(20)\n\t\tExpect(RunCf(\"cups\", serviceName, \"-p\", fmt.Sprintf(`{\"apitoken\":\"TOKEN\",\"apiurl\":\"%s\/without-agent-path\",\"environmentid\":\"envid\"}`, dynatraceAPIURI))).To(Succeed())\n\t\tExpect(RunCf(\"bind-service\", app.Name, serviceName)).To(Succeed())\n\t\tExpect(RunCf(\"start\", app.Name)).To(Succeed())\n\t\tConfirmRunning(app)\n\t\tExpect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())\n\n\t\tBy(\"initializing dynatrace agent\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Initializing\"))\n\n\t\tBy(\"detecting single dynatrace service\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Found one matching Dynatrace service\"))\n\n\t\tBy(\"downloading dynatrace agent\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Downloading Dynatrace OneAgent Installer\"))\n\n\t\tBy(\"extracting dynatrace agent\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Extracting Dynatrace OneAgent\"))\n\n\t\tBy(\"removing dynatrace agent installer\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Removing Dynatrace OneAgent Installer\"))\n\n\t\tBy(\"adding environment vars\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Adding Dynatrace specific Environment Vars\"))\n\n\t\tBy(\"LD_PRELOAD settings\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Adding Dynatrace LD_PRELOAD settings\"))\n\n\t\tBy(\"checking for manifest.json fallback\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Agent path not found in manifest.json, using fallback\"))\n\t})\n\n\tIt(\"Deploy app with multiple dynatrace services\", func() {\n\t\tserviceName = \"dynatrace-service-\" + cutlass.RandStringRunes(20)\n\t\tExpect(RunCf(\"cups\", serviceName, \"-p\", fmt.Sprintf(`{\"apitoken\":\"TOKEN\",\"apiurl\":\"%s\",\"environmentid\":\"envid\"}`, dynatraceAPIURI))).To(Succeed())\n\t\tExpect(RunCf(\"bind-service\", app.Name, serviceName)).To(Succeed())\n\n\t\tserviceName2 = \"dynatrace-service-\" + cutlass.RandStringRunes(20)\n\t\tExpect(RunCf(\"cups\", serviceName2, \"-p\", fmt.Sprintf(`{\"apitoken\":\"TOKEN\",\"apiurl\":\"%s\",\"environmentid\":\"envid_dupe\"}`, dynatraceAPIURI))).To(Succeed())\n\t\tExpect(RunCf(\"bind-service\", app.Name, serviceName2)).To(Succeed())\n\n\t\tBy(\"deployment should fail\")\n\t\tExpect(RunCf(\"start\", app.Name)).ToNot(Succeed())\n\t\tExpect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())\n\n\t\tBy(\"initializing dynatrace agent\")\n\t\tEventually(app.Stdout.String).Should(ContainSubstring(\"Initializing\"))\n\n\t\tBy(\"detecting multiple dynatrace services\")\n\t\tEventually(app.Stdout.String).Should(ContainSubstring(\"More than one matching service found!\"))\n\t})\n\n\tIt(\"Deploy app with single dynatrace service, wrong url and skiperrors on true\", func() {\n\t\tserviceName = \"dynatrace-service-\" + cutlass.RandStringRunes(20)\n\t\tExpect(RunCf(\"cups\", serviceName, \"-p\", fmt.Sprintf(`{\"apitoken\":\"TOKEN\",\"apiurl\":\"%s\/no-such-endpoint\",\"environmentid\":\"envid\",\"skiperrors\":\"true\"}`, dynatraceAPIURI))).To(Succeed())\n\t\tExpect(RunCf(\"bind-service\", app.Name, serviceName)).To(Succeed())\n\n\t\tBy(\"deployment should not fail\")\n\t\tExpect(RunCf(\"start\", app.Name)).To(Succeed())\n\t\tExpect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())\n\n\t\tBy(\"initializing dynatrace agent\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Initializing\"))\n\n\t\tBy(\"detecting single dynatrace service\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Found one matching Dynatrace service\"))\n\n\t\tBy(\"downloading dynatrace agent\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Downloading Dynatrace OneAgent Installer\"))\n\n\t\tBy(\"download retries work\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, retrying in 4 seconds\"))\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, retrying in 5 seconds\"))\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, retrying in 7 seconds\"))\n\n\t\tBy(\"should exit gracefully\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, skipping installation\"))\n\n\t\tBy(\"no further installer logs\")\n\t\tExpect(app.Stdout.String()).ToNot(ContainSubstring(\"Extracting Dynatrace OneAgent\"))\n\t})\n\n\tIt(\"Deploy app with single dynatrace service, wrong url and skiperrors not set\", func() {\n\t\tserviceName = \"dynatrace-service-\" + cutlass.RandStringRunes(20)\n\t\tExpect(RunCf(\"cups\", serviceName, \"-p\", fmt.Sprintf(`{\"apitoken\":\"TOKEN\",\"apiurl\":\"%s\/no-such-endpoint\",\"environmentid\":\"envid\"}`, dynatraceAPIURI))).To(Succeed())\n\t\tExpect(RunCf(\"bind-service\", app.Name, serviceName)).To(Succeed())\n\n\t\tBy(\"deployment should fail\")\n\t\tExpect(RunCf(\"start\", app.Name)).ToNot(Succeed())\n\t\tExpect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())\n\n\t\tBy(\"initializing dynatrace agent\")\n\t\tEventually(app.Stdout.String).Should(ContainSubstring(\"Initializing\"))\n\n\t\tBy(\"detecting single dynatrace service\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Found one matching Dynatrace service\"))\n\n\t\tBy(\"downloading dynatrace agent\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Downloading Dynatrace OneAgent Installer\"))\n\n\t\tBy(\"download retries work\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, retrying in 4 seconds\"))\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, retrying in 5 seconds\"))\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, retrying in 7 seconds\"))\n\n\t\tBy(\"error during agent download\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"ERROR: Dynatrace agent download failed\"))\n\n\t\tBy(\"no further installer logs\")\n\t\tExpect(app.Stdout.String()).ToNot(ContainSubstring(\"Extracting Dynatrace OneAgent\"))\n\t})\n})\n<commit_msg>Unfocus integration spec<commit_after>package integration_test\n\nimport (\n\t\"fmt\"\n\t\"os\/exec\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry\/libbuildpack\/cutlass\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"Deploy app with\", func() {\n\tvar (\n\t\tapp                       *cutlass.App\n\t\tserviceName, serviceName2 string\n\t\tdynatraceAPI              *cutlass.App\n\t\tdynatraceAPIURI           string\n\t)\n\n\tvar RunCf = func(args ...string) error {\n\t\tcommand := exec.Command(\"cf\", args...)\n\t\tcommand.Stdout = GinkgoWriter\n\t\tcommand.Stderr = GinkgoWriter\n\t\treturn command.Run()\n\t}\n\n\tBeforeEach(func() {\n\t\tdynatraceAPI = cutlass.New(Fixtures(\"fake_dynatrace_api\"))\n\t\tdynatraceAPI.SetEnv(\"BP_DEBUG\", \"true\")\n\n\t\tExpect(dynatraceAPI.Push()).To(Succeed())\n\t\tEventually(func() ([]string, error) { return dynatraceAPI.InstanceStates() }, 60*time.Second).Should(Equal([]string{\"RUNNING\"}))\n\n\t\tvar err error\n\t\tdynatraceAPIURI, err = dynatraceAPI.GetUrl(\"\")\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\tapp = cutlass.New(Fixtures(\"with_dynatrace\"))\n\t\tapp.SetEnv(\"BP_DEBUG\", \"true\")\n\t\tExpect(app.PushNoStart()).To(Succeed())\n\t})\n\n\tAfterEach(func() {\n\t\tapp = DestroyApp(app)\n\t\tdynatraceAPI = DestroyApp(dynatraceAPI)\n\n\t\tif serviceName != \"\" {\n\t\t\t_ = RunCf(\"delete-service\", \"-f\", serviceName)\n\t\t\tserviceName = \"\"\n\t\t}\n\t\tif serviceName2 != \"\" {\n\t\t\t_ = RunCf(\"delete-service\", \"-f\", serviceName2)\n\t\t\tserviceName2 = \"\"\n\t\t}\n\t})\n\n\tIt(\"single dynatrace service without manifest.json\", func() {\n\t\tserviceName = \"dynatrace-service-\" + cutlass.RandStringRunes(20)\n\t\tExpect(RunCf(\"cups\", serviceName, \"-p\", fmt.Sprintf(`{\"apitoken\":\"TOKEN\",\"apiurl\":\"%s\/without-agent-path\",\"environmentid\":\"envid\"}`, dynatraceAPIURI))).To(Succeed())\n\t\tExpect(RunCf(\"bind-service\", app.Name, serviceName)).To(Succeed())\n\t\tExpect(RunCf(\"start\", app.Name)).To(Succeed())\n\t\tConfirmRunning(app)\n\t\tExpect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())\n\n\t\tBy(\"initializing dynatrace agent\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Initializing\"))\n\n\t\tBy(\"detecting single dynatrace service\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Found one matching Dynatrace service\"))\n\n\t\tBy(\"downloading dynatrace agent\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Downloading Dynatrace OneAgent Installer\"))\n\n\t\tBy(\"extracting dynatrace agent\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Extracting Dynatrace OneAgent\"))\n\n\t\tBy(\"removing dynatrace agent installer\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Removing Dynatrace OneAgent Installer\"))\n\n\t\tBy(\"adding environment vars\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Adding Dynatrace specific Environment Vars\"))\n\n\t\tBy(\"LD_PRELOAD settings\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Adding Dynatrace LD_PRELOAD settings\"))\n\n\t\tBy(\"checking for manifest.json fallback\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Agent path not found in manifest.json, using fallback\"))\n\t})\n\n\tIt(\"Deploy app with multiple dynatrace services\", func() {\n\t\tserviceName = \"dynatrace-service-\" + cutlass.RandStringRunes(20)\n\t\tExpect(RunCf(\"cups\", serviceName, \"-p\", fmt.Sprintf(`{\"apitoken\":\"TOKEN\",\"apiurl\":\"%s\",\"environmentid\":\"envid\"}`, dynatraceAPIURI))).To(Succeed())\n\t\tExpect(RunCf(\"bind-service\", app.Name, serviceName)).To(Succeed())\n\n\t\tserviceName2 = \"dynatrace-service-\" + cutlass.RandStringRunes(20)\n\t\tExpect(RunCf(\"cups\", serviceName2, \"-p\", fmt.Sprintf(`{\"apitoken\":\"TOKEN\",\"apiurl\":\"%s\",\"environmentid\":\"envid_dupe\"}`, dynatraceAPIURI))).To(Succeed())\n\t\tExpect(RunCf(\"bind-service\", app.Name, serviceName2)).To(Succeed())\n\n\t\tBy(\"deployment should fail\")\n\t\tExpect(RunCf(\"start\", app.Name)).ToNot(Succeed())\n\t\tExpect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())\n\n\t\tBy(\"initializing dynatrace agent\")\n\t\tEventually(app.Stdout.String).Should(ContainSubstring(\"Initializing\"))\n\n\t\tBy(\"detecting multiple dynatrace services\")\n\t\tEventually(app.Stdout.String).Should(ContainSubstring(\"More than one matching service found!\"))\n\t})\n\n\tIt(\"Deploy app with single dynatrace service, wrong url and skiperrors on true\", func() {\n\t\tserviceName = \"dynatrace-service-\" + cutlass.RandStringRunes(20)\n\t\tExpect(RunCf(\"cups\", serviceName, \"-p\", fmt.Sprintf(`{\"apitoken\":\"TOKEN\",\"apiurl\":\"%s\/no-such-endpoint\",\"environmentid\":\"envid\",\"skiperrors\":\"true\"}`, dynatraceAPIURI))).To(Succeed())\n\t\tExpect(RunCf(\"bind-service\", app.Name, serviceName)).To(Succeed())\n\n\t\tBy(\"deployment should not fail\")\n\t\tExpect(RunCf(\"start\", app.Name)).To(Succeed())\n\t\tExpect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())\n\n\t\tBy(\"initializing dynatrace agent\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Initializing\"))\n\n\t\tBy(\"detecting single dynatrace service\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Found one matching Dynatrace service\"))\n\n\t\tBy(\"downloading dynatrace agent\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Downloading Dynatrace OneAgent Installer\"))\n\n\t\tBy(\"download retries work\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, retrying in 4 seconds\"))\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, retrying in 5 seconds\"))\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, retrying in 7 seconds\"))\n\n\t\tBy(\"should exit gracefully\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, skipping installation\"))\n\n\t\tBy(\"no further installer logs\")\n\t\tExpect(app.Stdout.String()).ToNot(ContainSubstring(\"Extracting Dynatrace OneAgent\"))\n\t})\n\n\tIt(\"Deploy app with single dynatrace service, wrong url and skiperrors not set\", func() {\n\t\tserviceName = \"dynatrace-service-\" + cutlass.RandStringRunes(20)\n\t\tExpect(RunCf(\"cups\", serviceName, \"-p\", fmt.Sprintf(`{\"apitoken\":\"TOKEN\",\"apiurl\":\"%s\/no-such-endpoint\",\"environmentid\":\"envid\"}`, dynatraceAPIURI))).To(Succeed())\n\t\tExpect(RunCf(\"bind-service\", app.Name, serviceName)).To(Succeed())\n\n\t\tBy(\"deployment should fail\")\n\t\tExpect(RunCf(\"start\", app.Name)).ToNot(Succeed())\n\t\tExpect(app.ConfirmBuildpack(buildpackVersion)).To(Succeed())\n\n\t\tBy(\"initializing dynatrace agent\")\n\t\tEventually(app.Stdout.String).Should(ContainSubstring(\"Initializing\"))\n\n\t\tBy(\"detecting single dynatrace service\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Found one matching Dynatrace service\"))\n\n\t\tBy(\"downloading dynatrace agent\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Downloading Dynatrace OneAgent Installer\"))\n\n\t\tBy(\"download retries work\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, retrying in 4 seconds\"))\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, retrying in 5 seconds\"))\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"Error during installer download, retrying in 7 seconds\"))\n\n\t\tBy(\"error during agent download\")\n\t\tExpect(app.Stdout.String()).To(ContainSubstring(\"ERROR: Dynatrace agent download failed\"))\n\n\t\tBy(\"no further installer logs\")\n\t\tExpect(app.Stdout.String()).ToNot(ContainSubstring(\"Extracting Dynatrace OneAgent\"))\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>\/\/ uploadHandler controls showing the upload form and the\n\/\/ processing of POSTed data.  Files are saved automatically\n\/\/ (via http package) to env(TMPDIR). Files are then moved to\n\/\/ the specified assets directory.\n\/\/\n\/\/ NOTE: It is strongly recommended that you set the TMPDIR\n\/\/ environment variable when you launch the evh service and\n\/\/ set it to a directory on the same filesystem as assets.\n\/\/ Moving the temp file to the permament location will be\n\/\/ much faster this way.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n)\n\n\/\/This is where the action happens.\nfunc uploadHandler(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Redirect to SSL if enabled\n\tif r.TLS == nil && Config.Server.Ssl {\n\t\tredirectToSsl(w, r)\n\t\treturn\n\t}\n\n\t\/\/ Get a new Page object\n\tvar page = NewPage()\n\t\/\/ Set the appropriate protocol prefix for URLs\n\tif r.TLS != nil {\n\t\tpage.HttpProto = \"https\"\n\t}\n\n\t\/\/ Prep our available expirations\n\tvar expirations = ExpandExpirations()\n\tpage.Expirations = ExpirationsToHtmlMap(expirations)\n\n\tswitch r.Method {\n\t\/\/ Show the upload form\n\tcase \"GET\":\n\t\tDisplayPage(w, r, \"upload\", page)\n\n\t\/\/ Process form submission\n\tcase \"POST\":\n\t\t\/\/ Initialize our file count to zero\n\t\tvar filecount = 0\n\n\t\t\/\/ New request object\n\t\treq, reqerr := NewRequest(r.RemoteAddr)\n\t\tif reqerr != nil {\n\t\t\treq.Log(reqerr.Error())\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Setup our tracker\n\t\tpage.Tracker = NewTracker(req.Dnldcode)\n\n\t\t\/\/ This is the download URL for the session, not used for individual files\n\t\treq.Log(\"New incoming transfer starting for\", r.RemoteAddr)\n\n\t\t\/\/ Parse the multipart form in the request (set max memory in bytes)\n\t\terr := r.ParseMultipartForm(10000)\n\t\tif err != nil {\n\t\t\tpage.Message = \"Transfer aborted (client disconnected)\"\n\t\t\treq.Log(string(page.Message))\n\t\t} else {\n\t\t\t\/\/ Store form values\n\t\t\tpage.Tracker.Description = r.FormValue(\"FileDescr\")\n\t\t\tpage.Tracker.SrcEmail = r.FormValue(\"SrcEmail\")\n\t\t\tpage.Tracker.DstEmail = r.FormValue(\"DstEmail\")\n\t\t\tpage.Tracker.Expiration = r.FormValue(\"Expires\")\n\n\t\t\tif r.FormValue(\"client\") == \"1\" {\n\t\t\t\tpage.Tracker.CliUpload = true\n\t\t\t}\n\n\t\t\t\/\/ Path to save file to\n\t\t\treq.Path = filepath.Join(Config.Server.Assets, req.Dnldcode)\n\n\t\t\t\/\/ Get the *fileheaders and keep count of uploadedjack filesN\n\t\t\t\/\/   We don't care what the form field is called, just iterate over all form fields of type file\n\t\t\tfor fieldname, files := range r.MultipartForm.File {\n\t\t\t\treq.Log(\"Processing files field:\", fieldname)\n\t\t\t\tfor i, _ := range files {\n\t\t\t\t\tvar filename = ScrubFilename(files[i].Header.Get(\"Content-Disposition\"))\n\t\t\t\t\tfilecount++\n\n\t\t\t\t\t\/\/ Create a File object\n\t\t\t\t\tvar newfile = NewFile(filename, req.Path)\n\n\t\t\t\t\t\/\/ Move the temp file to the permament location\n\t\t\t\t\terr := newfile.Save(files[i])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treq.Errors = append(req.Errors, err.Error())\n\t\t\t\t\t\treq.Log()\n\t\t\t\t\t} else {\n\t\t\t\t\t\treq.Log(fmt.Sprintf(\"Saved file (%s, %.2f MB): %s\", newfile.Name, newfile.Size\/1024\/1024, newfile.Path))\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Update our tracker\n\t\t\t\t\tpage.Tracker.Files = append(page.Tracker.Files, newfile)\n\t\t\t\t\tpage.Tracker.Size += newfile.Size\n\t\t\t\t\tpage.Tracker.SizeMB += float64(page.Tracker.Size) \/ 1024 \/ 1024\n\t\t\t\t\tpage.Tracker.AddLog(\"Added file \" + newfile.Name)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Set our expiration\n\t\t\tif val, ok := expirations[page.Tracker.Expiration]; ok {\n\t\t\t\tpage.Tracker.ExpirationDate = val\n\t\t\t} else {\n\t\t\t\treq.Log(\"Invalid expiration specified, using default of 1 day\")\n\t\t\t\tpage.Tracker.ExpirationDate = expirations[\"1:d\"]\n\t\t\t}\n\t\t\tpage.Tracker.ExpirationStr = page.Tracker.ExpirationDate.Format(TimeLayout)\n\n\t\t\t\/\/ Send notification\n\t\t\treq.Notify(&page)\n\t\t\tpage.Tracker.Save()\n\t\t}\n\n\t\t\/\/ DisplayPage result message (using template.HTML() allows the template to show the non-garbled URL)\n\t\tvar filespageurl = page.BaseUrl + DownloadUrlPath + page.Tracker.Dnldcode + \"?vercode=\" + page.Tracker.Vercode\n\t\tif r.FormValue(\"client\") == \"1\" {\n\t\t\tpage.Message = template.HTML(fmt.Sprintf(\"Successfully uploaded %d of %d files.  Your files are available here:\\n%s\\n\", page.Tracker.CountSaved(), filecount, filespageurl))\n\t\t\tDisplayPage(w, r, \"uploadPlain\", page)\n\t\t} else {\n\t\t\tpage.Message = template.HTML(fmt.Sprintf(\"Successfully uploaded %d of %d files.  Your files are available <a href=\\\"%s\\\">here<\/a>.\", page.Tracker.CountSaved(), filecount, filespageurl))\n\t\t\tDisplayPage(w, r, \"upload\", page)\n\t\t}\n\tdefault:\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t}\n}\n<commit_msg>Fixed bug in Tracker.SizeMB calculation.<commit_after>\/\/ uploadHandler controls showing the upload form and the\n\/\/ processing of POSTed data.  Files are saved automatically\n\/\/ (via http package) to env(TMPDIR). Files are then moved to\n\/\/ the specified assets directory.\n\/\/\n\/\/ NOTE: It is strongly recommended that you set the TMPDIR\n\/\/ environment variable when you launch the evh service and\n\/\/ set it to a directory on the same filesystem as assets.\n\/\/ Moving the temp file to the permament location will be\n\/\/ much faster this way.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n)\n\n\/\/This is where the action happens.\nfunc uploadHandler(w http.ResponseWriter, r *http.Request) {\n\t\/\/ Redirect to SSL if enabled\n\tif r.TLS == nil && Config.Server.Ssl {\n\t\tredirectToSsl(w, r)\n\t\treturn\n\t}\n\n\t\/\/ Get a new Page object\n\tvar page = NewPage()\n\t\/\/ Set the appropriate protocol prefix for URLs\n\tif r.TLS != nil {\n\t\tpage.HttpProto = \"https\"\n\t}\n\n\t\/\/ Prep our available expirations\n\tvar expirations = ExpandExpirations()\n\tpage.Expirations = ExpirationsToHtmlMap(expirations)\n\n\tswitch r.Method {\n\t\/\/ Show the upload form\n\tcase \"GET\":\n\t\tDisplayPage(w, r, \"upload\", page)\n\n\t\/\/ Process form submission\n\tcase \"POST\":\n\t\t\/\/ Initialize our file count to zero\n\t\tvar filecount = 0\n\n\t\t\/\/ New request object\n\t\treq, reqerr := NewRequest(r.RemoteAddr)\n\t\tif reqerr != nil {\n\t\t\treq.Log(reqerr.Error())\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ Setup our tracker\n\t\tpage.Tracker = NewTracker(req.Dnldcode)\n\n\t\t\/\/ This is the download URL for the session, not used for individual files\n\t\treq.Log(\"New incoming transfer starting for\", r.RemoteAddr)\n\n\t\t\/\/ Parse the multipart form in the request (set max memory in bytes)\n\t\terr := r.ParseMultipartForm(10000)\n\t\tif err != nil {\n\t\t\tpage.Message = \"Transfer aborted (client disconnected)\"\n\t\t\treq.Log(string(page.Message))\n\t\t} else {\n\t\t\t\/\/ Store form values\n\t\t\tpage.Tracker.Description = r.FormValue(\"FileDescr\")\n\t\t\tpage.Tracker.SrcEmail = r.FormValue(\"SrcEmail\")\n\t\t\tpage.Tracker.DstEmail = r.FormValue(\"DstEmail\")\n\t\t\tpage.Tracker.Expiration = r.FormValue(\"Expires\")\n\n\t\t\tif r.FormValue(\"client\") == \"1\" {\n\t\t\t\tpage.Tracker.CliUpload = true\n\t\t\t}\n\n\t\t\t\/\/ Path to save file to\n\t\t\treq.Path = filepath.Join(Config.Server.Assets, req.Dnldcode)\n\n\t\t\t\/\/ Get the *fileheaders and keep count of uploadedjack filesN\n\t\t\t\/\/   We don't care what the form field is called, just iterate over all form fields of type file\n\t\t\tfor fieldname, files := range r.MultipartForm.File {\n\t\t\t\treq.Log(\"Processing files field:\", fieldname)\n\t\t\t\tfor i, _ := range files {\n\t\t\t\t\tvar filename = ScrubFilename(files[i].Header.Get(\"Content-Disposition\"))\n\t\t\t\t\tfilecount++\n\n\t\t\t\t\t\/\/ Create a File object\n\t\t\t\t\tvar newfile = NewFile(filename, req.Path)\n\n\t\t\t\t\t\/\/ Move the temp file to the permament location\n\t\t\t\t\terr := newfile.Save(files[i])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treq.Errors = append(req.Errors, err.Error())\n\t\t\t\t\t\treq.Log()\n\t\t\t\t\t} else {\n\t\t\t\t\t\treq.Log(fmt.Sprintf(\"Saved file (%s, %.2f MB): %s\", newfile.Name, newfile.Size\/1024\/1024, newfile.Path))\n\t\t\t\t\t}\n\n\t\t\t\t\t\/\/ Update our tracker\n\t\t\t\t\tpage.Tracker.Files = append(page.Tracker.Files, newfile)\n\t\t\t\t\tpage.Tracker.Size += newfile.Size\n\t\t\t\t\tpage.Tracker.SizeMB = page.Tracker.Size \/ 1024 \/ 1024\n\t\t\t\t\tpage.Tracker.AddLog(\"Added file \" + newfile.Name)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Set our expiration\n\t\t\tif val, ok := expirations[page.Tracker.Expiration]; ok {\n\t\t\t\tpage.Tracker.ExpirationDate = val\n\t\t\t} else {\n\t\t\t\treq.Log(\"Invalid expiration specified, using default of 1 day\")\n\t\t\t\tpage.Tracker.ExpirationDate = expirations[\"1:d\"]\n\t\t\t}\n\t\t\tpage.Tracker.ExpirationStr = page.Tracker.ExpirationDate.Format(TimeLayout)\n\n\t\t\t\/\/ Send notification\n\t\t\treq.Notify(&page)\n\t\t\tpage.Tracker.Save()\n\t\t}\n\n\t\t\/\/ DisplayPage result message (using template.HTML() allows the template to show the non-garbled URL)\n\t\tvar filespageurl = page.BaseUrl + DownloadUrlPath + page.Tracker.Dnldcode + \"?vercode=\" + page.Tracker.Vercode\n\t\tif r.FormValue(\"client\") == \"1\" {\n\t\t\tpage.Message = template.HTML(fmt.Sprintf(\"Successfully uploaded %d of %d files.  Your files are available here:\\n%s\\n\", page.Tracker.CountSaved(), filecount, filespageurl))\n\t\t\tDisplayPage(w, r, \"uploadPlain\", page)\n\t\t} else {\n\t\t\tpage.Message = template.HTML(fmt.Sprintf(\"Successfully uploaded %d of %d files.  Your files are available <a href=\\\"%s\\\">here<\/a>.\", page.Tracker.CountSaved(), filecount, filespageurl))\n\t\t\tDisplayPage(w, r, \"upload\", page)\n\t\t}\n\tdefault:\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\n\t\"github.com\/julienschmidt\/httprouter\"\n)\n\n\/* Read functions\n *\/\nfunc ListMonitoring(w http.ResponseWriter, r *http.Request,\n\t_ httprouter.Params) {\n\tdefer PanicCatcher(w)\n\n\treturnChannel := make(chan somaResult)\n\thandler := handlerMap[\"monitoringReadHandler\"].(somaMonitoringReadHandler)\n\thandler.input <- somaMonitoringRequest{\n\t\taction: \"list\",\n\t\treply:  returnChannel,\n\t}\n\tresult := <-returnChannel\n\n\t\/\/ declare here since goto does not jump over declarations\n\tcReq := proto.NewMonitoringFilter()\n\tif result.Failure() {\n\t\tgoto skip\n\t}\n\n\t_ = DecodeJsonBody(r, &cReq)\n\tif cReq.Filter.Monitoring.Name != \"\" {\n\t\tfiltered := make([]somaMonitoringResult, 0)\n\t\tfor _, i := range result.Systems {\n\t\t\tif i.Monitoring.Name == cReq.Filter.Monitoring.Name {\n\t\t\t\tfiltered = append(filtered, i)\n\t\t\t}\n\t\t}\n\t\tresult.Systems = filtered\n\t}\n\nskip:\n\tSendMonitoringReply(&w, &result)\n}\n\nfunc ShowMonitoring(w http.ResponseWriter, r *http.Request,\n\tparams httprouter.Params) {\n\tdefer PanicCatcher(w)\n\n\treturnChannel := make(chan somaResult)\n\thandler := handlerMap[\"monitoringReadHandler\"].(somaMonitoringReadHandler)\n\thandler.input <- somaMonitoringRequest{\n\t\taction: \"show\",\n\t\treply:  returnChannel,\n\t\tMonitoring: proto.Monitoring{\n\t\t\tId: params.ByName(\"monitoring\"),\n\t\t},\n\t}\n\tresult := <-returnChannel\n\tSendMonitoringReply(&w, &result)\n}\n\n\/* Write functions\n *\/\nfunc AddMonitoring(w http.ResponseWriter, r *http.Request,\n\t_ httprouter.Params) {\n\tdefer PanicCatcher(w)\n\n\tcReq := proto.NewMonitoringRequest()\n\terr := DecodeJsonBody(r, &cReq)\n\tif err != nil {\n\t\tDispatchBadRequest(&w, err)\n\t\treturn\n\t}\n\n\treturnChannel := make(chan somaResult)\n\thandler := handlerMap[\"monitoringWriteHandler\"].(somaMonitoringWriteHandler)\n\thandler.input <- somaMonitoringRequest{\n\t\taction: \"add\",\n\t\treply:  returnChannel,\n\t\tMonitoring: proto.Monitoring{\n\t\t\tName:     cReq.Monitoring.Name,\n\t\t\tMode:     cReq.Monitoring.Mode,\n\t\t\tContact:  cReq.Monitoring.Contact,\n\t\t\tTeamId:   cReq.Monitoring.TeamId,\n\t\t\tCallback: cReq.Monitoring.Callback,\n\t\t},\n\t}\n\tresult := <-returnChannel\n\tSendMonitoringReply(&w, &result)\n}\n\nfunc DeleteMonitoring(w http.ResponseWriter, r *http.Request,\n\tparams httprouter.Params) {\n\tdefer PanicCatcher(w)\n\n\treturnChannel := make(chan somaResult)\n\thandler := handlerMap[\"monitoringWriteHandler\"].(somaMonitoringWriteHandler)\n\thandler.input <- somaMonitoringRequest{\n\t\taction: \"delete\",\n\t\treply:  returnChannel,\n\t\tMonitoring: proto.Monitoring{\n\t\t\tId: params.ByName(\"monitoring\"),\n\t\t},\n\t}\n\tresult := <-returnChannel\n\tSendMonitoringReply(&w, &result)\n}\n\n\/* Utility\n *\/\nfunc SendMonitoringReply(w *http.ResponseWriter, r *somaResult) {\n\tresult := proto.NewMonitoringResult()\n\tif r.MarkErrors(&result) {\n\t\tgoto dispatch\n\t}\n\tfor _, i := range (*r).Systems {\n\t\t*result.Monitorings = append(*result.Monitorings, i.Monitoring)\n\t\tif i.ResultError != nil {\n\t\t\t*result.Errors = append(*result.Errors, i.ResultError.Error())\n\t\t}\n\t}\n\ndispatch:\n\tjson, err := json.Marshal(result)\n\tif err != nil {\n\t\tDispatchInternalError(w, err)\n\t\treturn\n\t}\n\tDispatchJsonReply(w, &json)\n\treturn\n}\n\n\/\/ vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix\n<commit_msg>Enforce monitoring name not containing . char<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/julienschmidt\/httprouter\"\n)\n\n\/* Read functions\n *\/\nfunc ListMonitoring(w http.ResponseWriter, r *http.Request,\n\t_ httprouter.Params) {\n\tdefer PanicCatcher(w)\n\n\treturnChannel := make(chan somaResult)\n\thandler := handlerMap[\"monitoringReadHandler\"].(somaMonitoringReadHandler)\n\thandler.input <- somaMonitoringRequest{\n\t\taction: \"list\",\n\t\treply:  returnChannel,\n\t}\n\tresult := <-returnChannel\n\n\t\/\/ declare here since goto does not jump over declarations\n\tcReq := proto.NewMonitoringFilter()\n\tif result.Failure() {\n\t\tgoto skip\n\t}\n\n\t_ = DecodeJsonBody(r, &cReq)\n\tif cReq.Filter.Monitoring.Name != \"\" {\n\t\tfiltered := make([]somaMonitoringResult, 0)\n\t\tfor _, i := range result.Systems {\n\t\t\tif i.Monitoring.Name == cReq.Filter.Monitoring.Name {\n\t\t\t\tfiltered = append(filtered, i)\n\t\t\t}\n\t\t}\n\t\tresult.Systems = filtered\n\t}\n\nskip:\n\tSendMonitoringReply(&w, &result)\n}\n\nfunc ShowMonitoring(w http.ResponseWriter, r *http.Request,\n\tparams httprouter.Params) {\n\tdefer PanicCatcher(w)\n\n\treturnChannel := make(chan somaResult)\n\thandler := handlerMap[\"monitoringReadHandler\"].(somaMonitoringReadHandler)\n\thandler.input <- somaMonitoringRequest{\n\t\taction: \"show\",\n\t\treply:  returnChannel,\n\t\tMonitoring: proto.Monitoring{\n\t\t\tId: params.ByName(\"monitoring\"),\n\t\t},\n\t}\n\tresult := <-returnChannel\n\tSendMonitoringReply(&w, &result)\n}\n\n\/* Write functions\n *\/\nfunc AddMonitoring(w http.ResponseWriter, r *http.Request,\n\t_ httprouter.Params) {\n\tdefer PanicCatcher(w)\n\n\tcReq := proto.NewMonitoringRequest()\n\terr := DecodeJsonBody(r, &cReq)\n\tif err != nil {\n\t\tDispatchBadRequest(&w, err)\n\t\treturn\n\t}\n\tif strings.Contains(cReq.Monitoring.Name, `.`) {\n\t\tDispatchBadRequest(&w, fmt.Errorf(`Invalid monitoring system name containing . character`))\n\t\treturn\n\t}\n\n\treturnChannel := make(chan somaResult)\n\thandler := handlerMap[\"monitoringWriteHandler\"].(somaMonitoringWriteHandler)\n\thandler.input <- somaMonitoringRequest{\n\t\taction: \"add\",\n\t\treply:  returnChannel,\n\t\tMonitoring: proto.Monitoring{\n\t\t\tName:     cReq.Monitoring.Name,\n\t\t\tMode:     cReq.Monitoring.Mode,\n\t\t\tContact:  cReq.Monitoring.Contact,\n\t\t\tTeamId:   cReq.Monitoring.TeamId,\n\t\t\tCallback: cReq.Monitoring.Callback,\n\t\t},\n\t}\n\tresult := <-returnChannel\n\tSendMonitoringReply(&w, &result)\n}\n\nfunc DeleteMonitoring(w http.ResponseWriter, r *http.Request,\n\tparams httprouter.Params) {\n\tdefer PanicCatcher(w)\n\n\treturnChannel := make(chan somaResult)\n\thandler := handlerMap[\"monitoringWriteHandler\"].(somaMonitoringWriteHandler)\n\thandler.input <- somaMonitoringRequest{\n\t\taction: \"delete\",\n\t\treply:  returnChannel,\n\t\tMonitoring: proto.Monitoring{\n\t\t\tId: params.ByName(\"monitoring\"),\n\t\t},\n\t}\n\tresult := <-returnChannel\n\tSendMonitoringReply(&w, &result)\n}\n\n\/* Utility\n *\/\nfunc SendMonitoringReply(w *http.ResponseWriter, r *somaResult) {\n\tresult := proto.NewMonitoringResult()\n\tif r.MarkErrors(&result) {\n\t\tgoto dispatch\n\t}\n\tfor _, i := range (*r).Systems {\n\t\t*result.Monitorings = append(*result.Monitorings, i.Monitoring)\n\t\tif i.ResultError != nil {\n\t\t\t*result.Errors = append(*result.Errors, i.ResultError.Error())\n\t\t}\n\t}\n\ndispatch:\n\tjson, err := json.Marshal(result)\n\tif err != nil {\n\t\tDispatchInternalError(w, err)\n\t\treturn\n\t}\n\tDispatchJsonReply(w, &json)\n\treturn\n}\n\n\/\/ vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix\n<|endoftext|>"}
{"text":"<commit_before>package middleware\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/remind101\/pkg\/httpx\"\n\t\"github.com\/remind101\/pkg\/logger\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ StdoutLogger is a logger.Logger generator that generates a logger that writes\n\/\/ to stdout.\nvar StdoutLogger = stdLogger(os.Stdout)\n\n\/\/ LogTo is an httpx middleware that wraps the handler to insert a logger and\n\/\/ log the request to it.\nfunc LogTo(h httpx.Handler, f func(context.Context, *http.Request) logger.Logger) httpx.Handler {\n\treturn InsertLogger(Log(h), f)\n}\n\n\/\/ InsertLogger returns an httpx.Handler middleware that will call f to generate\n\/\/ a logger, then insert it into the context.\nfunc InsertLogger(h httpx.Handler, f func(context.Context, *http.Request) logger.Logger) httpx.Handler {\n\treturn httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\t\tl := f(ctx, r)\n\t\tctx = logger.WithLogger(ctx, l)\n\t\treturn h.ServeHTTPContext(ctx, w, r)\n\t})\n}\n\nfunc stdLogger(out io.Writer) func(context.Context, *http.Request) logger.Logger {\n\treturn func(ctx context.Context, r *http.Request) logger.Logger {\n\t\treturn logger.New(log.New(out, fmt.Sprintf(\"request_id=%s \", httpx.RequestID(ctx)), 0))\n\t}\n}\n\n\/\/ Logger is middleware that logs the request details to the logger.Logger\n\/\/ embedded within the context.\ntype Logger struct {\n\t\/\/ handler is the wrapped httpx.Handler\n\thandler httpx.Handler\n}\n\nfunc Log(h httpx.Handler) *Logger {\n\treturn &Logger{\n\t\thandler: h,\n\t}\n}\n\nfunc (h *Logger) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\trw := NewResponseWriter(w)\n\n\tt := time.Now()\n\n\terr := h.handler.ServeHTTPContext(ctx, rw, r)\n\n\tms := fmt.Sprintf(\"%d\", (int(time.Now().Sub(t)).Seconds() * 1000))\n\n\tlogger.Info(ctx, \"request\",\n\t\t\"method\", r.Method,\n\t\t\"path\", r.URL.Path,\n\t\t\"status\", rw.Status(),\n\t\t\"ms\", ms,\n\t)\n\n\treturn err\n}\n<commit_msg>Fix tests<commit_after>package middleware\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/remind101\/pkg\/httpx\"\n\t\"github.com\/remind101\/pkg\/logger\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ StdoutLogger is a logger.Logger generator that generates a logger that writes\n\/\/ to stdout.\nvar StdoutLogger = stdLogger(os.Stdout)\n\n\/\/ LogTo is an httpx middleware that wraps the handler to insert a logger and\n\/\/ log the request to it.\nfunc LogTo(h httpx.Handler, f func(context.Context, *http.Request) logger.Logger) httpx.Handler {\n\treturn InsertLogger(Log(h), f)\n}\n\n\/\/ InsertLogger returns an httpx.Handler middleware that will call f to generate\n\/\/ a logger, then insert it into the context.\nfunc InsertLogger(h httpx.Handler, f func(context.Context, *http.Request) logger.Logger) httpx.Handler {\n\treturn httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\t\tl := f(ctx, r)\n\t\tctx = logger.WithLogger(ctx, l)\n\t\treturn h.ServeHTTPContext(ctx, w, r)\n\t})\n}\n\nfunc stdLogger(out io.Writer) func(context.Context, *http.Request) logger.Logger {\n\treturn func(ctx context.Context, r *http.Request) logger.Logger {\n\t\treturn logger.New(log.New(out, fmt.Sprintf(\"request_id=%s \", httpx.RequestID(ctx)), 0))\n\t}\n}\n\n\/\/ Logger is middleware that logs the request details to the logger.Logger\n\/\/ embedded within the context.\ntype Logger struct {\n\t\/\/ handler is the wrapped httpx.Handler\n\thandler httpx.Handler\n}\n\nfunc Log(h httpx.Handler) *Logger {\n\treturn &Logger{\n\t\thandler: h,\n\t}\n}\n\nfunc (h *Logger) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\trw := NewResponseWriter(w)\n\n\tt := time.Now()\n\n\terr := h.handler.ServeHTTPContext(ctx, rw, r)\n\n\tms := fmt.Sprintf(\"%d\", (int(time.Now().Sub(t).Seconds() * 1000)))\n\n\tlogger.Info(ctx, \"request\",\n\t\t\"method\", r.Method,\n\t\t\"path\", r.URL.Path,\n\t\t\"status\", rw.Status(),\n\t\t\"ms\", ms,\n\t)\n\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Copyright 2021, Sander van Harmelen\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\npackage gitlab\n\nimport (\n\t\"encoding\/json\"\n\t\"testing\"\n)\n\nfunc TestBuildEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/build.json\")\n\n\tvar event *BuildEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Build Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Build Event is null\")\n\t}\n\n\tif event.BuildID != 1977 {\n\t\tt.Errorf(\"BuildID is %v, want %v\", event.BuildID, 1977)\n\t}\n}\n\nfunc TestDeploymentEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/deployment.json\")\n\n\tvar event *DeploymentEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Deployment Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Deployment Event is null\")\n\t}\n\n\tif event.Project.ID != 30 {\n\t\tt.Errorf(\"Project.ID is %v, want %v\", event.Project.ID, 30)\n\t}\n\n\tif event.User.Name == \"\" {\n\t\tt.Errorf(\"Username is %s, want %s\", event.User.Name, \"Administrator\")\n\t}\n\n\tif event.CommitTitle != \"Add new file\" {\n\t\tt.Errorf(\"CommitTitle is %s, want %s\", event.CommitTitle, \"Add new file\")\n\t}\n}\n\nfunc TestIssueCommentEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/note_issue.json\")\n\n\tvar event *IssueCommentEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Issue Comment Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event.ObjectKind != string(NoteEventTargetType) {\n\t\tt.Errorf(\"ObjectKind is %v, want %v\", event.ObjectKind, NoteEventTargetType)\n\t}\n\n\tif event.ProjectID != 5 {\n\t\tt.Errorf(\"ProjectID is %v, want %v\", event.ProjectID, 5)\n\t}\n\n\tif event.ObjectAttributes.NoteableType != \"Issue\" {\n\t\tt.Errorf(\"NoteableType is %v, want %v\", event.ObjectAttributes.NoteableType, \"Issue\")\n\t}\n\n\tif event.Issue.Title != \"test_issue\" {\n\t\tt.Errorf(\"Issue title is %v, want %v\", event.Issue.Title, \"test_issue\")\n\t}\n\n\tif len(event.Issue.Labels) == 0 || event.Issue.Labels[0].ID != 25 {\n\t\tt.Errorf(\"Label id is null\")\n\t}\n}\n\nfunc TestIssueEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/issue.json\")\n\n\tvar event *IssueEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Issue Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\tif event.Project.ID != 1 {\n\t\tt.Errorf(\"Project.ID is %v, want %v\", event.Project.ID, 1)\n\t}\n\tif event.Changes.TotalTimeSpent.Previous != 8100 {\n\t\tt.Errorf(\"Changes.TotalTimeSpent.Previous is %v , want %v\", event.Changes.TotalTimeSpent.Previous, 8100)\n\t}\n\tif event.Changes.TotalTimeSpent.Current != 9900 {\n\t\tt.Errorf(\"Changes.TotalTimeSpent.Current is %v , want %v\", event.Changes.TotalTimeSpent.Current, 8100)\n\t}\n}\n\nfunc TestMergeEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/merge_request.json\")\n\n\tvar event *MergeEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Merge Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Merge Event is null\")\n\t}\n\n\tif event.ObjectAttributes.ID != 99 {\n\t\tt.Errorf(\"ObjectAttributes.ID is %v, want %v\", event.ObjectAttributes.ID, 99)\n\t}\n\n\tif event.ObjectAttributes.Source.Homepage != \"http:\/\/example.com\/awesome_space\/awesome_project\" {\n\t\tt.Errorf(\"ObjectAttributes.Source.Homepage is %v, want %v\", event.ObjectAttributes.Source.Homepage, \"http:\/\/example.com\/awesome_space\/awesome_project\")\n\t}\n\n\tif event.ObjectAttributes.LastCommit.ID != \"da1560886d4f094c3e6c9ef40349f7d38b5d27d7\" {\n\t\tt.Errorf(\"ObjectAttributes.LastCommit.ID is %v, want %s\", event.ObjectAttributes.LastCommit.ID, \"da1560886d4f094c3e6c9ef40349f7d38b5d27d7\")\n\t}\n\tif event.ObjectAttributes.Assignee.Name != \"User1\" {\n\t\tt.Errorf(\"Assignee.Name is %v, want %v\", event.ObjectAttributes.ID, \"User1\")\n\t}\n\n\tif event.ObjectAttributes.Assignee.Username != \"user1\" {\n\t\tt.Errorf(\"ObjectAttributes is %v, want %v\", event.ObjectAttributes.Assignee.Username, \"user1\")\n\t}\n\n\tif event.User.Name == \"\" {\n\t\tt.Errorf(\"Username is %s, want %s\", event.User.Name, \"Administrator\")\n\t}\n\n\tif event.ObjectAttributes.LastCommit.Timestamp == nil {\n\t\tt.Errorf(\"Timestamp isn't nil\")\n\t}\n\n\tif name := event.ObjectAttributes.LastCommit.Author.Name; name != \"GitLab dev user\" {\n\t\tt.Errorf(\"Commit Username is %s, want %s\", name, \"GitLab dev user\")\n\t}\n}\n\nfunc TestMergeEventUnmarshalFromGroup(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/group_merge_request.json\")\n\n\tvar event *MergeEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Group Merge Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Group Merge Event is null\")\n\t}\n\n\tif event.ObjectKind != \"merge_request\" {\n\t\tt.Errorf(\"ObjectKind is %v, want %v\", event.ObjectKind, \"merge_request\")\n\t}\n\n\tif event.User.Username != \"root\" {\n\t\tt.Errorf(\"User.Username is %v, want %v\", event.User.Username, \"root\")\n\t}\n\n\tif event.Project.Name != exampleProjectName {\n\t\tt.Errorf(\"Project.Name is %v, want %v\", event.Project.Name, exampleProjectName)\n\t}\n\n\tif event.ObjectAttributes.ID != 15917 {\n\t\tt.Errorf(\"ObjectAttributes.ID is %v, want %v\", event.ObjectAttributes.ID, 15917)\n\t}\n\n\tif event.ObjectAttributes.Source.Name != exampleProjectName {\n\t\tt.Errorf(\"ObjectAttributes.Source.Name is %v, want %v\", event.ObjectAttributes.Source.Name, exampleProjectName)\n\t}\n\n\tif event.ObjectAttributes.LastCommit.Author.Email != \"test.user@mail.com\" {\n\t\tt.Errorf(\"ObjectAttributes.LastCommit.Author.Email is %v, want %v\", event.ObjectAttributes.LastCommit.Author.Email, \"test.user@mail.com\")\n\t}\n\n\tif event.Repository.Name != exampleProjectName {\n\t\tt.Errorf(\"Repository.Name is %v, want %v\", event.Repository.Name, exampleProjectName)\n\t}\n\n\tif event.Assignee.Username != \"root\" {\n\t\tt.Errorf(\"Assignee.Username is %v, want %v\", event.Assignee, \"root\")\n\t}\n\n\tif event.User.Name == \"\" {\n\t\tt.Errorf(\"Username is %s, want %s\", event.User.Name, \"Administrator\")\n\t}\n\n\tif event.ObjectAttributes.LastCommit.Timestamp == nil {\n\t\tt.Errorf(\"Timestamp isn't nil\")\n\t}\n\n\tif name := event.ObjectAttributes.LastCommit.Author.Name; name != \"Test User\" {\n\t\tt.Errorf(\"Commit Username is %s, want %s\", name, \"Test User\")\n\t}\n}\n\nfunc TestPipelineEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/pipeline.json\")\n\n\tvar event *PipelineEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Pipeline Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Pipeline Event is null\")\n\t}\n\n\tif event.ObjectAttributes.ID != 31 {\n\t\tt.Errorf(\"ObjectAttributes is %v, want %v\", event.ObjectAttributes.ID, 1977)\n\t}\n\n\tif event.User.Name == \"\" {\n\t\tt.Errorf(\"Username is %s, want %s\", event.User.Name, \"Administrator\")\n\t}\n\n\tif event.Commit.Timestamp == nil {\n\t\tt.Errorf(\"Timestamp isn't nil\")\n\t}\n\n\tif name := event.Commit.Author.Name; name != \"User\" {\n\t\tt.Errorf(\"Commit Username is %s, want %s\", name, \"User\")\n\t}\n}\n\nfunc TestPushEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/push.json\")\n\tvar event *PushEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Push Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Push Event is null\")\n\t}\n\n\tif event.ProjectID != 15 {\n\t\tt.Errorf(\"ProjectID is %v, want %v\", event.ProjectID, 15)\n\t}\n\n\tif event.UserName != exampleEventUserName {\n\t\tt.Errorf(\"Username is %s, want %s\", event.UserName, exampleEventUserName)\n\t}\n\n\tif event.Commits[0] == nil || event.Commits[0].Timestamp == nil {\n\t\tt.Errorf(\"Commit Timestamp isn't nil\")\n\t}\n\n\tif event.Commits[0] == nil || event.Commits[0].Author.Name != \"Jordi Mallach\" {\n\t\tt.Errorf(\"Commit Username is %s, want %s\", event.UserName, \"Jordi Mallach\")\n\t}\n}\n\nfunc TestReleaseEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/release.json\")\n\n\tvar event *ReleaseEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Release Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Release Event is null\")\n\t}\n\n\tif event.Project.ID != 327622 {\n\t\tt.Errorf(\"Project.ID is %v, want %v\", event.Project.ID, 327622)\n\t}\n\n\tif event.Commit.Title != \"Merge branch 'example-branch' into 'master'\" {\n\t\tt.Errorf(\"Commit title is %s, want %s\", event.Commit.Title, \"Merge branch 'example-branch' into 'master'\")\n\t}\n\n\tif len(event.Assets.Sources) != 4 {\n\t\tt.Errorf(\"Asset sources length is %d, want %d\", len(event.Assets.Sources), 4)\n\t}\n\n\tif event.Assets.Sources[0].Format != \"zip\" {\n\t\tt.Errorf(\"First asset source format is %s, want %s\", event.Assets.Sources[0].Format, \"zip\")\n\t}\n\n\tif len(event.Assets.Links) != 1 {\n\t\tt.Errorf(\"Asset links length is %d, want %d\", len(event.Assets.Links), 1)\n\t}\n\n\tif event.Assets.Links[0].Name != \"Changelog\" {\n\t\tt.Errorf(\"First asset link name is %s, want %s\", event.Assets.Links[0].Name, \"Changelog\")\n\t}\n\n\tif event.Commit.Author.Name != \"User\" {\n\t\tt.Errorf(\"Commit author name is %s, want %s\", event.Commit.Author.Name, \"User\")\n\t}\n}\n<commit_msg>tests(event_webhook_types): test the value properly<commit_after>\/\/\n\/\/ Copyright 2021, Sander van Harmelen\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\npackage gitlab\n\nimport (\n\t\"encoding\/json\"\n\t\"testing\"\n)\n\nfunc TestBuildEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/build.json\")\n\n\tvar event *BuildEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Build Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Build Event is null\")\n\t}\n\n\tif event.BuildID != 1977 {\n\t\tt.Errorf(\"BuildID is %v, want %v\", event.BuildID, 1977)\n\t}\n}\n\nfunc TestDeploymentEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/deployment.json\")\n\n\tvar event *DeploymentEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Deployment Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Deployment Event is null\")\n\t}\n\n\tif event.Project.ID != 30 {\n\t\tt.Errorf(\"Project.ID is %v, want %v\", event.Project.ID, 30)\n\t}\n\n\tif event.User.Name == \"\" {\n\t\tt.Errorf(\"Username is %s, want %s\", event.User.Name, \"Administrator\")\n\t}\n\n\tif event.CommitTitle != \"Add new file\" {\n\t\tt.Errorf(\"CommitTitle is %s, want %s\", event.CommitTitle, \"Add new file\")\n\t}\n}\n\nfunc TestIssueCommentEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/note_issue.json\")\n\n\tvar event *IssueCommentEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Issue Comment Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event.ObjectKind != string(NoteEventTargetType) {\n\t\tt.Errorf(\"ObjectKind is %v, want %v\", event.ObjectKind, NoteEventTargetType)\n\t}\n\n\tif event.ProjectID != 5 {\n\t\tt.Errorf(\"ProjectID is %v, want %v\", event.ProjectID, 5)\n\t}\n\n\tif event.ObjectAttributes.NoteableType != \"Issue\" {\n\t\tt.Errorf(\"NoteableType is %v, want %v\", event.ObjectAttributes.NoteableType, \"Issue\")\n\t}\n\n\tif event.Issue.Title != \"test_issue\" {\n\t\tt.Errorf(\"Issue title is %v, want %v\", event.Issue.Title, \"test_issue\")\n\t}\n\n\tif len(event.Issue.Labels) == 0 || event.Issue.Labels[0].ID != 25 {\n\t\tt.Errorf(\"Label id is null\")\n\t}\n}\n\nfunc TestIssueEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/issue.json\")\n\n\tvar event *IssueEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Issue Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\tif event.Project.ID != 1 {\n\t\tt.Errorf(\"Project.ID is %v, want %v\", event.Project.ID, 1)\n\t}\n\tif event.Changes.TotalTimeSpent.Previous != 8100 {\n\t\tt.Errorf(\"Changes.TotalTimeSpent.Previous is %v , want %v\", event.Changes.TotalTimeSpent.Previous, 8100)\n\t}\n\tif event.Changes.TotalTimeSpent.Current != 9900 {\n\t\tt.Errorf(\"Changes.TotalTimeSpent.Current is %v , want %v\", event.Changes.TotalTimeSpent.Current, 8100)\n\t}\n}\n\nfunc TestMergeEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/merge_request.json\")\n\n\tvar event *MergeEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Merge Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Merge Event is null\")\n\t}\n\n\tif event.ObjectAttributes.ID != 99 {\n\t\tt.Errorf(\"ObjectAttributes.ID is %v, want %v\", event.ObjectAttributes.ID, 99)\n\t}\n\n\tif event.ObjectAttributes.Source.Homepage != \"http:\/\/example.com\/awesome_space\/awesome_project\" {\n\t\tt.Errorf(\"ObjectAttributes.Source.Homepage is %v, want %v\", event.ObjectAttributes.Source.Homepage, \"http:\/\/example.com\/awesome_space\/awesome_project\")\n\t}\n\n\tif event.ObjectAttributes.LastCommit.ID != \"da1560886d4f094c3e6c9ef40349f7d38b5d27d7\" {\n\t\tt.Errorf(\"ObjectAttributes.LastCommit.ID is %v, want %s\", event.ObjectAttributes.LastCommit.ID, \"da1560886d4f094c3e6c9ef40349f7d38b5d27d7\")\n\t}\n\tif event.ObjectAttributes.Assignee.Name != \"User1\" {\n\t\tt.Errorf(\"Assignee.Name is %v, want %v\", event.ObjectAttributes.ID, \"User1\")\n\t}\n\n\tif event.ObjectAttributes.Assignee.Username != \"user1\" {\n\t\tt.Errorf(\"ObjectAttributes is %v, want %v\", event.ObjectAttributes.Assignee.Username, \"user1\")\n\t}\n\n\tif event.User.Name != \"Administrator\" {\n\t\tt.Errorf(\"Username is %s, want %s\", event.User.Name, \"Administrator\")\n\t}\n\n\tif event.ObjectAttributes.LastCommit.Timestamp == nil {\n\t\tt.Errorf(\"Timestamp isn't nil\")\n\t}\n\n\tif name := event.ObjectAttributes.LastCommit.Author.Name; name != \"GitLab dev user\" {\n\t\tt.Errorf(\"Commit Username is %s, want %s\", name, \"GitLab dev user\")\n\t}\n}\n\nfunc TestMergeEventUnmarshalFromGroup(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/group_merge_request.json\")\n\n\tvar event *MergeEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Group Merge Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Group Merge Event is null\")\n\t}\n\n\tif event.ObjectKind != \"merge_request\" {\n\t\tt.Errorf(\"ObjectKind is %v, want %v\", event.ObjectKind, \"merge_request\")\n\t}\n\n\tif event.User.Username != \"root\" {\n\t\tt.Errorf(\"User.Username is %v, want %v\", event.User.Username, \"root\")\n\t}\n\n\tif event.Project.Name != exampleProjectName {\n\t\tt.Errorf(\"Project.Name is %v, want %v\", event.Project.Name, exampleProjectName)\n\t}\n\n\tif event.ObjectAttributes.ID != 15917 {\n\t\tt.Errorf(\"ObjectAttributes.ID is %v, want %v\", event.ObjectAttributes.ID, 15917)\n\t}\n\n\tif event.ObjectAttributes.Source.Name != exampleProjectName {\n\t\tt.Errorf(\"ObjectAttributes.Source.Name is %v, want %v\", event.ObjectAttributes.Source.Name, exampleProjectName)\n\t}\n\n\tif event.ObjectAttributes.LastCommit.Author.Email != \"test.user@mail.com\" {\n\t\tt.Errorf(\"ObjectAttributes.LastCommit.Author.Email is %v, want %v\", event.ObjectAttributes.LastCommit.Author.Email, \"test.user@mail.com\")\n\t}\n\n\tif event.Repository.Name != exampleProjectName {\n\t\tt.Errorf(\"Repository.Name is %v, want %v\", event.Repository.Name, exampleProjectName)\n\t}\n\n\tif event.Assignee.Username != \"root\" {\n\t\tt.Errorf(\"Assignee.Username is %v, want %v\", event.Assignee, \"root\")\n\t}\n\n\tif event.User.Name == \"\" {\n\t\tt.Errorf(\"Username is %s, want %s\", event.User.Name, \"Administrator\")\n\t}\n\n\tif event.ObjectAttributes.LastCommit.Timestamp == nil {\n\t\tt.Errorf(\"Timestamp isn't nil\")\n\t}\n\n\tif name := event.ObjectAttributes.LastCommit.Author.Name; name != \"Test User\" {\n\t\tt.Errorf(\"Commit Username is %s, want %s\", name, \"Test User\")\n\t}\n}\n\nfunc TestPipelineEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/pipeline.json\")\n\n\tvar event *PipelineEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Pipeline Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Pipeline Event is null\")\n\t}\n\n\tif event.ObjectAttributes.ID != 31 {\n\t\tt.Errorf(\"ObjectAttributes is %v, want %v\", event.ObjectAttributes.ID, 1977)\n\t}\n\n\tif event.User.Name == \"\" {\n\t\tt.Errorf(\"Username is %s, want %s\", event.User.Name, \"Administrator\")\n\t}\n\n\tif event.Commit.Timestamp == nil {\n\t\tt.Errorf(\"Timestamp isn't nil\")\n\t}\n\n\tif name := event.Commit.Author.Name; name != \"User\" {\n\t\tt.Errorf(\"Commit Username is %s, want %s\", name, \"User\")\n\t}\n}\n\nfunc TestPushEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/push.json\")\n\tvar event *PushEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Push Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Push Event is null\")\n\t}\n\n\tif event.ProjectID != 15 {\n\t\tt.Errorf(\"ProjectID is %v, want %v\", event.ProjectID, 15)\n\t}\n\n\tif event.UserName != exampleEventUserName {\n\t\tt.Errorf(\"Username is %s, want %s\", event.UserName, exampleEventUserName)\n\t}\n\n\tif event.Commits[0] == nil || event.Commits[0].Timestamp == nil {\n\t\tt.Errorf(\"Commit Timestamp isn't nil\")\n\t}\n\n\tif event.Commits[0] == nil || event.Commits[0].Author.Name != \"Jordi Mallach\" {\n\t\tt.Errorf(\"Commit Username is %s, want %s\", event.UserName, \"Jordi Mallach\")\n\t}\n}\n\nfunc TestReleaseEventUnmarshal(t *testing.T) {\n\tjsonObject := loadFixture(\"testdata\/webhooks\/release.json\")\n\n\tvar event *ReleaseEvent\n\terr := json.Unmarshal(jsonObject, &event)\n\n\tif err != nil {\n\t\tt.Errorf(\"Release Event can not unmarshaled: %v\\n \", err.Error())\n\t}\n\n\tif event == nil {\n\t\tt.Errorf(\"Release Event is null\")\n\t}\n\n\tif event.Project.ID != 327622 {\n\t\tt.Errorf(\"Project.ID is %v, want %v\", event.Project.ID, 327622)\n\t}\n\n\tif event.Commit.Title != \"Merge branch 'example-branch' into 'master'\" {\n\t\tt.Errorf(\"Commit title is %s, want %s\", event.Commit.Title, \"Merge branch 'example-branch' into 'master'\")\n\t}\n\n\tif len(event.Assets.Sources) != 4 {\n\t\tt.Errorf(\"Asset sources length is %d, want %d\", len(event.Assets.Sources), 4)\n\t}\n\n\tif event.Assets.Sources[0].Format != \"zip\" {\n\t\tt.Errorf(\"First asset source format is %s, want %s\", event.Assets.Sources[0].Format, \"zip\")\n\t}\n\n\tif len(event.Assets.Links) != 1 {\n\t\tt.Errorf(\"Asset links length is %d, want %d\", len(event.Assets.Links), 1)\n\t}\n\n\tif event.Assets.Links[0].Name != \"Changelog\" {\n\t\tt.Errorf(\"First asset link name is %s, want %s\", event.Assets.Links[0].Name, \"Changelog\")\n\t}\n\n\tif event.Commit.Author.Name != \"User\" {\n\t\tt.Errorf(\"Commit author name is %s, want %s\", event.Commit.Author.Name, \"User\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build linux\n\npackage qemu\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"syscall\"\n\t\"unsafe\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/hyperhq\/runv\/hypervisor\/network\"\n)\n\nconst (\n\tIFNAMSIZ       = 16\n\tCIFF_TAP       = 0x0002\n\tCIFF_NO_PI     = 0x1000\n\tCIFF_ONE_QUEUE = 0x2000\n)\n\ntype ifReq struct {\n\tName  [IFNAMSIZ]byte\n\tFlags uint16\n\tpad   [0x28 - 0x10 - 2]byte\n}\n\nfunc GetTapFd(device, bridge, options string) (int, error) {\n\tvar (\n\t\treq   ifReq\n\t\terrno syscall.Errno\n\t)\n\n\ttapFile, err := os.OpenFile(\"\/dev\/net\/tun\", os.O_RDWR, 0)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\treq.Flags = CIFF_TAP | CIFF_NO_PI | CIFF_ONE_QUEUE\n\tcopy(req.Name[:len(req.Name)-1], []byte(device))\n\t_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, tapFile.Fd(),\n\t\tuintptr(syscall.TUNSETIFF),\n\t\tuintptr(unsafe.Pointer(&req)))\n\tif errno != 0 {\n\t\ttapFile.Close()\n\t\treturn -1, fmt.Errorf(\"create tap device failed\\n\")\n\t}\n\t_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, tapFile.Fd(), uintptr(syscall.TUNSETPERSIST), 0)\n\tif errno != 0 {\n\t\ttapFile.Close()\n\t\treturn -1, fmt.Errorf(\"clear tap device persist flag failed\\n\")\n\t}\n\n\terr = network.UpAndAddToBridge(device, bridge, options)\n\tif err != nil {\n\t\tglog.Errorf(\"Add to bridge failed %s %s\", bridge, device)\n\t\ttapFile.Close()\n\t\treturn -1, err\n\t}\n\n\treturn int(tapFile.Fd()), nil\n}\n\nfunc GetVhostUserPort(device, bridge, sockPath, option string) error {\n\tglog.V(3).Infof(\"Found ovs bridge %s, attaching tap %s to it\\n\", bridge, device)\n\t\/\/ append vhost-server-path\n\toptions := fmt.Sprintf(\"vhost-server-path=%s\/%s\", sockPath, device)\n\tif option != \"\" {\n\t\toptions = options + \",\" + option\n\t}\n\n\t\/\/ ovs command \"ovs-vsctl add-port BRIDGE PORT\" add netwok device PORT to BRIDGE,\n\t\/\/ PORT and BRIDGE here indicate the device name respectively.\n\tout, err := exec.Command(\"ovs-vsctl\", \"--may-exist\", \"add-port\", bridge, device, \"--\", \"set\", \"Interface\", device, \"type=dpdkvhostuserclient\", \"options:\"+options).CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Ovs failed to add port: %s, error :%v\", strings.TrimSpace(string(out)), err)\n\t}\n\n\treturn nil\n}\n<commit_msg>Fix network performance issue on arm64 for runv<commit_after>\/\/ +build linux\n\npackage qemu\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"syscall\"\n\t\"unsafe\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/hyperhq\/runv\/hypervisor\/network\"\n)\n\nconst (\n\tIFNAMSIZ       = 16\n\tCIFF_TAP       = 0x0002\n\tCIFF_NO_PI     = 0x1000\n\tCIFF_ONE_QUEUE = 0x2000\n\tCIFF_VNET_HDR  = 0x4000\n)\n\ntype ifReq struct {\n\tName  [IFNAMSIZ]byte\n\tFlags uint16\n\tpad   [0x28 - 0x10 - 2]byte\n}\n\nfunc GetTapFd(device, bridge, options string) (int, error) {\n\tvar (\n\t\treq   ifReq\n\t\terrno syscall.Errno\n\t)\n\n\ttapFile, err := os.OpenFile(\"\/dev\/net\/tun\", os.O_RDWR, 0)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\n\treq.Flags = CIFF_TAP | CIFF_NO_PI | CIFF_ONE_QUEUE | CIFF_VNET_HDR\n\tcopy(req.Name[:len(req.Name)-1], []byte(device))\n\t_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, tapFile.Fd(),\n\t\tuintptr(syscall.TUNSETIFF),\n\t\tuintptr(unsafe.Pointer(&req)))\n\tif errno != 0 {\n\t\ttapFile.Close()\n\t\treturn -1, fmt.Errorf(\"create tap device failed\\n\")\n\t}\n\t_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, tapFile.Fd(), uintptr(syscall.TUNSETPERSIST), 0)\n\tif errno != 0 {\n\t\ttapFile.Close()\n\t\treturn -1, fmt.Errorf(\"clear tap device persist flag failed\\n\")\n\t}\n\n\terr = network.UpAndAddToBridge(device, bridge, options)\n\tif err != nil {\n\t\tglog.Errorf(\"Add to bridge failed %s %s\", bridge, device)\n\t\ttapFile.Close()\n\t\treturn -1, err\n\t}\n\n\treturn int(tapFile.Fd()), nil\n}\n\nfunc GetVhostUserPort(device, bridge, sockPath, option string) error {\n\tglog.V(3).Infof(\"Found ovs bridge %s, attaching tap %s to it\\n\", bridge, device)\n\t\/\/ append vhost-server-path\n\toptions := fmt.Sprintf(\"vhost-server-path=%s\/%s\", sockPath, device)\n\tif option != \"\" {\n\t\toptions = options + \",\" + option\n\t}\n\n\t\/\/ ovs command \"ovs-vsctl add-port BRIDGE PORT\" add netwok device PORT to BRIDGE,\n\t\/\/ PORT and BRIDGE here indicate the device name respectively.\n\tout, err := exec.Command(\"ovs-vsctl\", \"--may-exist\", \"add-port\", bridge, device, \"--\", \"set\", \"Interface\", device, \"type=dpdkvhostuserclient\", \"options:\"+options).CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Ovs failed to add port: %s, error :%v\", strings.TrimSpace(string(out)), err)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Davis Webb\n\/\/ Copyright 2015 Zhandos Suleimenov\n\/\/ Copyright 2015 Luke Shumaker\n\npackage handlers\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/jinzhu\/gorm\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/mail\"\n\t\"net\/url\"\n\t\"os\"\n\t\"periwinkle\/cfg\"\n\t\"periwinkle\/store\"\n\t\"periwinkle\/twilio\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc HandleSMS(r io.Reader, name string, db *gorm.DB) uint8 {\n\tpanic(\"TODO\")\n}\n\n\/\/ Returns the status of the message: queued, sending, sent,\n\/\/ delivered, undelivered, failed.  If an error occurs, it returns\n\/\/ Error.\nfunc sender(message mail.Message, to string) (status string, err error) {\n\tgroup := message.Header.Get(\"From\")\n\tuser := store.GetUserByAddress(cfg.DB, \"email\", message.Header.Get(\"From\"))\n\n\tsms_from := group                   \/\/ TODO: numberFor(group)\n\tsms_to := strings.Split(to, \"@\")[1] \/\/test 0 or 1\n\tsms_body := user.FullName + \":\" + message.Header.Get(\"Subject\")\n\n\t\/\/ account SID for Twilio account\n\taccount_sid := os.Getenv(\"TWILIO_ACCOUNTID\")\n\n\t\/\/ Authorization token for Twilio account\n\tauth_token := os.Getenv(\"TWILIO_TOKEN\")\n\n\tmessages_url := \"https:\/\/api.twilio.com\/2010-04-01\/Accounts\/\" + account_sid + \"\/Messages.json\"\n\n\tv := url.Values{}\n\tv.Set(\"From\", sms_from)\n\tv.Set(\"To\", sms_to)\n\tv.Set(\"Body\", sms_body)\n\tv.Set(\"StatusCallback\", \"http:\/\/\"+cfg.WebRoot+\"\/callbacks\/twilio-sms\")\n\n\tclient := &http.Client{}\n\n\treq, err := http.NewRequest(\"POST\", messages_url, bytes.NewBuffer([]byte(v.Encode())))\n\tif err != nil {\n\t\treturn\n\t}\n\treq.SetBasicAuth(account_sid, auth_token)\n\treq.Header.Add(\"Accept\", \"application\/json\")\n\treq.Header.Add(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\n\tresp, err := client.Do(req)\n\tdefer resp.Body.Close()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode == 200 || resp.StatusCode == 201 {\n\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\tmessage := twilio.Message{}\n\t\tjson.Unmarshal([]byte(body), &message)\n\t\tsms_status, err := SmsWaitForCallback(message.Sid)\n\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\ttime.Sleep(time.Second)\n\t\tif sms_status.ErrorCode != \"\" {\n\t\t\treturn sms_status.MessageStatus, fmt.Errorf(\"%s\", sms_status.ErrorCode)\n\t\t}\n\t\tif sms_status.MessageStatus == \"queued\" || sms_status.MessageStatus == \"sending\" || sms_status.MessageStatus == \"sent\" {\n\t\t\ttime.Sleep(time.Second)\n\t\t}\n\t\tstatus = sms_status.MessageStatus\n\t\terr = fmt.Errorf(\"%s\", sms_status.ErrorCode)\n\t\treturn status, err\n\t} else {\n\t\terr = fmt.Errorf(\"%s\", resp.Status)\n\t\treturn\n\t}\n}\n<commit_msg>smshandler fix<commit_after>\/\/ Copyright 2015 Davis Webb\n\/\/ Copyright 2015 Zhandos Suleimenov\n\/\/ Copyright 2015 Luke Shumaker\n\npackage handlers\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/jinzhu\/gorm\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/mail\"\n\t\"net\/url\"\n\t\"os\"\n\t\"periwinkle\/cfg\"\n\t\"periwinkle\/store\"\n\t\"periwinkle\/twilio\"\n\t\"strings\"\n\t\"time\"\n\t\"postfixpipe\"\n)\n\nfunc HandleSMS(r io.Reader, name string, db *gorm.DB) uint8 {\n\tmessage, err := mail.ReadMessage(r)\n\tif err != nil {\n\t\treturn postfixpipe.EX_NOINPUT\n\t}\n\tstatus, err := sender(*message, name, db)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn postfixpipe.EX_NOINPUT\n\t}\n\tlog.Println(status)\n\treturn postfixpipe.EX_OK\n}\n\n\/\/ Returns the status of the message: queued, sending, sent,\n\/\/ delivered, undelivered, failed.  If an error occurs, it returns\n\/\/ Error.\nfunc sender(message mail.Message, to string, db *gorm.DB) (status string, err error) {\n\t\/\/group := message.Header.Get(\"From\")\n\tuser := store.GetUserByAddress(db, \"email\", message.Header.Get(\"From\"))\n\n\tsms_from := \"+17653569541\"   \/\/ TODO: group:numberFor(group)\n\tsms_to := strings.Split(to, \"@\")[1] \/\/test 0 or 1\n\tsms_body := user.FullName + \":\" + message.Header.Get(\"Subject\")\n\n\t\/\/ account SID for Twilio account\n\taccount_sid := os.Getenv(\"TWILIO_ACCOUNTID\")\n\n\t\/\/ Authorization token for Twilio account\n\tauth_token := os.Getenv(\"TWILIO_TOKEN\")\n\n\tmessages_url := \"https:\/\/api.twilio.com\/2010-04-01\/Accounts\/\" + account_sid + \"\/Messages.json\"\n\n\tv := url.Values{}\n\tv.Set(\"From\", sms_from)\n\tv.Set(\"To\", sms_to)\n\tv.Set(\"Body\", sms_body)\n\tv.Set(\"StatusCallback\", \"http:\/\/\"+cfg.WebRoot+\"\/callbacks\/twilio-sms\")\n\n\tclient := &http.Client{}\n\n\treq, err := http.NewRequest(\"POST\", messages_url, bytes.NewBuffer([]byte(v.Encode())))\n\tif err != nil {\n\t\treturn\n\t}\n\treq.SetBasicAuth(account_sid, auth_token)\n\treq.Header.Add(\"Accept\", \"application\/json\")\n\treq.Header.Add(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\n\tresp, err := client.Do(req)\n\tdefer resp.Body.Close()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.StatusCode == 200 || resp.StatusCode == 201 {\n\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"%v\", err)\n\t\t}\n\n\t\tmessage := twilio.Message{}\n\t\tjson.Unmarshal([]byte(body), &message)\n\t\tsms_status, err := SmsWaitForCallback(message.Sid)\n\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"%v\", err)\n\t\t}\n\t\t\n\t\tif sms_status.MessageStatus == \"undelivered\" || sms_status.MessageStatus == \"failed\" {\n\t\t\treturn sms_status.MessageStatus, fmt.Errorf(\"%s\", sms_status.ErrorCode)\n\t\t}\n\t\tif sms_status.MessageStatus == \"queued\" || sms_status.MessageStatus == \"sending\" || sms_status.MessageStatus == \"sent\" {\n\t\t\ttime.Sleep(time.Second)\n\t\t\tsms_status, err = SmsWaitForCallback(message.Sid)\n\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"%s\", err)\n\t\t\t}\n\t\t}\n\n\t\tif sms_status.MessageStatus == \"undelivered\" || sms_status.MessageStatus == \"failed\" {\n\t\t\treturn sms_status.MessageStatus, fmt.Errorf(\"%s\", sms_status.ErrorCode)\n\t\t}\n\n\t\tstatus = sms_status.MessageStatus\n\t\terr = nil\n\t\treturn status, err\n\t} else {\n\t\terr = fmt.Errorf(\"%s\", resp.Status)\n\t\treturn\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package pachyderm\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"github.com\/hashicorp\/vault\/logical\"\n\t\"github.com\/hashicorp\/vault\/logical\/framework\"\n\tpclient \"github.com\/pachyderm\/pachyderm\/src\/client\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\/auth\"\n)\n\nfunc (b *backend) revokePath() *framework.Path {\n\n\treturn &framework.Path{\n\t\tPattern: \"revoke\",\n\t\tFields: map[string]*framework.FieldSchema{\n\t\t\t\"user_token\": &framework.FieldSchema{\n\t\t\t\tType: framework.TypeString,\n\t\t\t},\n\t\t},\n\t\tCallbacks: map[logical.Operation]framework.OperationFunc{\n\t\t\tlogical.UpdateOperation: b.pathRevoke,\n\t\t},\n\t}\n}\n\nfunc (b *backend) pathRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {\n\tuserToken := d.Get(\"user_token\").(string)\n\tif len(userToken) == 0 {\n\t\treturn nil, logical.ErrInvalidRequest\n\t}\n\n\tconfig, err := b.Config(ctx, req.Storage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(config.AdminToken) == 0 {\n\t\treturn nil, errors.New(\"plugin is missing admin token\")\n\t}\n\tif len(config.PachdAddress) == 0 {\n\t\treturn nil, errors.New(\"plugin is missing pachd_address\")\n\t}\n\n\terr = b.revokeUserCredentials(ctx, config.PachdAddress, userToken, config.AdminToken)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Compose the response\n\t\/\/ TODO: Not sure if this is the right way to return a successful response\n\treturn &logical.Response{\n\t\tAuth: &logical.Auth{},\n\t}, nil\n}\n\nfunc (b *backend) revokeUserCredentials(ctx context.Context, pachdAddress string, userToken string, adminToken string) error {\n\t\/\/ This is where we'd make the actual pachyderm calls to create the user\n\t\/\/ token using the admin token. For now, for testing purposes, we just do an action that only an\n\t\/\/ admin could do\n\n\t\/\/ Setup a single use client w the given admin token \/ address\n\tclient, err := pclient.NewFromAddress(pachdAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient = client.WithCtx(ctx)\n\tclient.SetAuthToken(adminToken)\n\n\t_, err = client.AuthAPIClient.ModifyAdmins(client.Ctx(), &auth.ModifyAdminsRequest{\n\t\tRemove: []string{\"tweetybird\"},\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>Implement \/revoke in vault plugin<commit_after>package pachyderm\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"github.com\/hashicorp\/vault\/logical\"\n\t\"github.com\/hashicorp\/vault\/logical\/framework\"\n\tpclient \"github.com\/pachyderm\/pachyderm\/src\/client\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\/auth\"\n)\n\nfunc (b *backend) revokePath() *framework.Path {\n\n\treturn &framework.Path{\n\t\tPattern: \"revoke\",\n\t\tFields: map[string]*framework.FieldSchema{\n\t\t\t\"user_token\": &framework.FieldSchema{\n\t\t\t\tType: framework.TypeString,\n\t\t\t},\n\t\t},\n\t\tCallbacks: map[logical.Operation]framework.OperationFunc{\n\t\t\tlogical.UpdateOperation: b.pathRevoke,\n\t\t},\n\t}\n}\n\nfunc (b *backend) pathRevoke(ctx context.Context, req *logical.Request, d *framework.FieldData) (*logical.Response, error) {\n\tuserToken := d.Get(\"user_token\").(string)\n\tif len(userToken) == 0 {\n\t\treturn nil, logical.ErrInvalidRequest\n\t}\n\n\tconfig, err := b.Config(ctx, req.Storage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(config.AdminToken) == 0 {\n\t\treturn nil, errors.New(\"plugin is missing admin token\")\n\t}\n\tif len(config.PachdAddress) == 0 {\n\t\treturn nil, errors.New(\"plugin is missing pachd_address\")\n\t}\n\n\terr = b.revokeUserCredentials(ctx, config.PachdAddress, userToken, config.AdminToken)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Compose the response\n\t\/\/ TODO: Not sure if this is the right way to return a successful response\n\treturn &logical.Response{\n\t\tAuth: &logical.Auth{},\n\t}, nil\n}\n\nfunc (b *backend) revokeUserCredentials(ctx context.Context, pachdAddress string, userToken string, adminToken string) error {\n\t\/\/ Setup a single use client w the given admin token \/ address\n\tclient, err := pclient.NewFromAddress(pachdAddress)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient = client.WithCtx(ctx)\n\tclient.SetAuthToken(adminToken)\n\t_, err = client.AuthAPIClient.RevokeAuthToken(client.Ctx(), &auth.RevokeAuthTokenRequest{\n\t\tToken: userToken,\n\t})\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n)\n\n\/\/ resourceMap is the mapping of resources we support to their basic\n\/\/ operations. This makes it easy to implement new resource types.\nvar resourceMap *resource.Map\n\nfunc init() {\n\tresourceMap = &resource.Map{\n\t\tMapping: map[string]resource.Resource{\n\t\t\t\"aws_elb\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_elb_create,\n\t\t\t\tUpdate:  resource_aws_elb_update,\n\t\t\t\tDestroy: resource_aws_elb_destroy,\n\t\t\t\tDiff:    resource_aws_elb_diff,\n\t\t\t\tRefresh: resource_aws_elb_refresh,\n\t\t\t},\n\n\t\t\t\"aws_eip\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_eip_create,\n\t\t\t\tDestroy: resource_aws_eip_destroy,\n\t\t\t\tDiff:    resource_aws_eip_diff,\n\t\t\t\tRefresh: resource_aws_eip_refresh,\n\t\t\t},\n\n\t\t\t\"aws_instance\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_instance_create,\n\t\t\t\tDestroy: resource_aws_instance_destroy,\n\t\t\t\tDiff:    resource_aws_instance_diff,\n\t\t\t\tRefresh: resource_aws_instance_refresh,\n\t\t\t},\n\n\t\t\t\"aws_internet_gateway\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_internet_gateway_create,\n\t\t\t\tDestroy: resource_aws_internet_gateway_destroy,\n\t\t\t\tDiff:    resource_aws_internet_gateway_diff,\n\t\t\t\tRefresh: resource_aws_internet_gateway_refresh,\n\t\t\t},\n\n\t\t\t\"aws_route_table\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_route_table_create,\n\t\t\t\tDestroy: resource_aws_route_table_destroy,\n\t\t\t\tDiff:    resource_aws_route_table_diff,\n\t\t\t\tRefresh: resource_aws_route_table_refresh,\n\t\t\t},\n\n\t\t\t\"aws_security_group\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_security_group_create,\n\t\t\t\tDestroy: resource_aws_security_group_destroy,\n\t\t\t\tDiff:    resource_aws_security_group_diff,\n\t\t\t\tRefresh: resource_aws_security_group_refresh,\n\t\t\t},\n\n\t\t\t\"aws_subnet\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_subnet_create,\n\t\t\t\tDestroy: resource_aws_subnet_destroy,\n\t\t\t\tDiff:    resource_aws_subnet_diff,\n\t\t\t\tRefresh: resource_aws_subnet_refresh,\n\t\t\t},\n\n\t\t\t\"aws_vpc\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_vpc_create,\n\t\t\t\tDestroy: resource_aws_vpc_destroy,\n\t\t\t\tDiff:    resource_aws_vpc_diff,\n\t\t\t\tRefresh: resource_aws_vpc_refresh,\n\t\t\t},\n\t\t},\n\t}\n}\n<commit_msg>providers\/aws: validation of route table<commit_after>package aws\n\nimport (\n\t\"github.com\/hashicorp\/terraform\/helper\/config\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n)\n\n\/\/ resourceMap is the mapping of resources we support to their basic\n\/\/ operations. This makes it easy to implement new resource types.\nvar resourceMap *resource.Map\n\nfunc init() {\n\tresourceMap = &resource.Map{\n\t\tMapping: map[string]resource.Resource{\n\t\t\t\"aws_elb\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_elb_create,\n\t\t\t\tUpdate:  resource_aws_elb_update,\n\t\t\t\tDestroy: resource_aws_elb_destroy,\n\t\t\t\tDiff:    resource_aws_elb_diff,\n\t\t\t\tRefresh: resource_aws_elb_refresh,\n\t\t\t},\n\n\t\t\t\"aws_eip\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_eip_create,\n\t\t\t\tDestroy: resource_aws_eip_destroy,\n\t\t\t\tDiff:    resource_aws_eip_diff,\n\t\t\t\tRefresh: resource_aws_eip_refresh,\n\t\t\t},\n\n\t\t\t\"aws_instance\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_instance_create,\n\t\t\t\tDestroy: resource_aws_instance_destroy,\n\t\t\t\tDiff:    resource_aws_instance_diff,\n\t\t\t\tRefresh: resource_aws_instance_refresh,\n\t\t\t},\n\n\t\t\t\"aws_internet_gateway\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_internet_gateway_create,\n\t\t\t\tDestroy: resource_aws_internet_gateway_destroy,\n\t\t\t\tDiff:    resource_aws_internet_gateway_diff,\n\t\t\t\tRefresh: resource_aws_internet_gateway_refresh,\n\t\t\t},\n\n\t\t\t\"aws_route_table\": resource.Resource{\n\t\t\t\tConfigValidator: &config.Validator{\n\t\t\t\t\tRequired: []string{\"vpc_id\"},\n\t\t\t\t},\n\t\t\t\tCreate:  resource_aws_route_table_create,\n\t\t\t\tDestroy: resource_aws_route_table_destroy,\n\t\t\t\tDiff:    resource_aws_route_table_diff,\n\t\t\t\tRefresh: resource_aws_route_table_refresh,\n\t\t\t},\n\n\t\t\t\"aws_security_group\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_security_group_create,\n\t\t\t\tDestroy: resource_aws_security_group_destroy,\n\t\t\t\tDiff:    resource_aws_security_group_diff,\n\t\t\t\tRefresh: resource_aws_security_group_refresh,\n\t\t\t},\n\n\t\t\t\"aws_subnet\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_subnet_create,\n\t\t\t\tDestroy: resource_aws_subnet_destroy,\n\t\t\t\tDiff:    resource_aws_subnet_diff,\n\t\t\t\tRefresh: resource_aws_subnet_refresh,\n\t\t\t},\n\n\t\t\t\"aws_vpc\": resource.Resource{\n\t\t\t\tCreate:  resource_aws_vpc_create,\n\t\t\t\tDestroy: resource_aws_vpc_destroy,\n\t\t\t\tDiff:    resource_aws_vpc_diff,\n\t\t\t\tRefresh: resource_aws_vpc_refresh,\n\t\t\t},\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package edit implements a command line editor.\npackage edit\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com\/elves\/elvish\/eval\"\n\t\"github.com\/elves\/elvish\/parse\"\n\t\"github.com\/elves\/elvish\/store\"\n\t\"github.com\/elves\/elvish\/sys\"\n\t\"github.com\/elves\/elvish\/util\"\n)\n\nvar Logger = util.GetLogger(\"[edit] \")\n\nconst (\n\tlackEOLRune = '\\u23ce'\n\tlackEOL     = \"\\033[7m\" + string(lackEOLRune) + \"\\033[m\"\n)\n\n\/\/ Editor keeps the status of the line editor.\ntype Editor struct {\n\tfile   *os.File\n\twriter *writer\n\treader *Reader\n\tsigs   chan os.Signal\n\tstore  *store.Store\n\tevaler *eval.Evaler\n\tcmdSeq int\n\tps1    Prompt\n\trps1   Prompt\n\teditorState\n}\n\ntype editorState struct {\n\t\/\/ States used during ReadLine. Reset at the beginning of ReadLine.\n\tactive                bool\n\tsavedTermios          *sys.Termios\n\ttokens                []Token\n\tprompt, rprompt, line string\n\tdot                   int\n\tnotifications         []string\n\ttips                  []string\n\n\tmode Mode\n\n\tinsert          insert\n\tcommand         command\n\tcompletion      completion\n\tcompletionLines int\n\tnavigation      navigation\n\thistory         historyState\n\thistoryListing  historyListing\n\tlocation        location\n\n\tisExternal      map[string]bool\n\tparseErrorAtEnd bool\n\t\/\/ Used for builtins.\n\tlastKey    Key\n\tnextAction action\n}\n\n\/\/ NewEditor creates an Editor.\nfunc NewEditor(file *os.File, sigs chan os.Signal, ev *eval.Evaler, st *store.Store) *Editor {\n\tseq := -1\n\tif st != nil {\n\t\tvar err error\n\t\tseq, err = st.NextCmdSeq()\n\t\tif err != nil {\n\t\t\t\/\/ TODO(xiaq): Also report the error\n\t\t\tseq = -1\n\t\t}\n\t}\n\n\tprompt, rprompt := defaultPrompts()\n\n\ted := &Editor{\n\t\tfile:   file,\n\t\twriter: newWriter(file),\n\t\treader: NewReader(file),\n\t\tsigs:   sigs,\n\t\tstore:  st,\n\t\tevaler: ev,\n\t\tcmdSeq: seq,\n\t\tps1:    prompt,\n\t\trps1:   rprompt,\n\t}\n\tev.AddModule(\"le\", makeModule(ed))\n\treturn ed\n}\n\nfunc (ed *Editor) flash() {\n\t\/\/ TODO implement fish-like flash effect\n}\n\nfunc (ed *Editor) addTip(format string, args ...interface{}) {\n\ted.tips = append(ed.tips, fmt.Sprintf(format, args...))\n}\n\nfunc (ed *Editor) notify(format string, args ...interface{}) {\n\ted.notifications = append(ed.notifications, fmt.Sprintf(format, args...))\n}\n\nfunc (ed *Editor) refresh(fullRefresh bool, tips bool) error {\n\t\/\/ Re-lex the line, unless we are in modeCompletion\n\tsrc := ed.line\n\tif ed.mode.Mode() != modeCompletion {\n\t\tn, err := parse.Parse(src)\n\t\ted.parseErrorAtEnd = err != nil && atEnd(err, len(src))\n\t\tif err != nil {\n\t\t\t\/\/ If all the errors happen at the end, it is liekly complaining about missing texts that will eventually be inserted. Don't show such errors.\n\t\t\t\/\/ XXX We may need a more reliable criteria.\n\t\t\tif tips && !ed.parseErrorAtEnd {\n\t\t\t\ted.addTip(\"parser error: %s\", err)\n\t\t\t}\n\t\t}\n\t\tif n == nil {\n\t\t\ted.tokens = []Token{{ParserError, src, nil, \"\"}}\n\t\t} else {\n\t\t\ted.tokens = tokenize(src, n)\n\t\t\t_, err := ed.evaler.Compile(n)\n\t\t\tif err != nil {\n\t\t\t\tif tips && !atEnd(err, len(src)) {\n\t\t\t\t\ted.addTip(\"compiler error: %s\", err)\n\t\t\t\t}\n\t\t\t\tif err, ok := err.(*util.PosError); ok {\n\t\t\t\t\tp := err.Begin\n\t\t\t\t\tfor i, token := range ed.tokens {\n\t\t\t\t\t\tif token.Node.Begin() <= p && p < token.Node.End() {\n\t\t\t\t\t\t\ted.tokens[i].MoreStyle += styleForCompilerError\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor i, t := range ed.tokens {\n\t\t\tfor _, stylist := range stylists {\n\t\t\t\ted.tokens[i].MoreStyle += stylist(t.Node, ed)\n\t\t\t}\n\t\t}\n\t}\n\treturn ed.writer.refresh(&ed.editorState, fullRefresh)\n}\n\nfunc atEnd(e error, n int) bool {\n\tswitch e := e.(type) {\n\tcase *util.PosError:\n\t\treturn e.Begin == n\n\tcase *util.Errors:\n\t\tfor _, child := range e.Errors {\n\t\t\tif !atEnd(child, n) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\/\/ insertAtDot inserts text at the dot and moves the dot after it.\nfunc (ed *Editor) insertAtDot(text string) {\n\ted.line = ed.line[:ed.dot] + text + ed.line[ed.dot:]\n\ted.dot += len(text)\n}\n\nfunc setupTerminal(file *os.File) (*sys.Termios, error) {\n\tfd := int(file.Fd())\n\tterm, err := sys.NewTermiosFromFd(fd)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't get terminal attribute: %s\", err)\n\t}\n\n\tsavedTermios := term.Copy()\n\n\tterm.SetICanon(false)\n\tterm.SetEcho(false)\n\tterm.SetVMin(1)\n\tterm.SetVTime(0)\n\n\terr = term.ApplyToFd(fd)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't set up terminal attribute: %s\", err)\n\t}\n\n\t\/*\n\t\terr = sys.FlushInput(fd)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"can't flush input: %s\", err)\n\t\t}\n\t*\/\n\n\treturn savedTermios, nil\n}\n\n\/\/ startReadLine prepares the terminal for the editor.\nfunc (ed *Editor) startReadLine() error {\n\tsavedTermios, err := setupTerminal(ed.file)\n\tif err != nil {\n\t\treturn err\n\t}\n\ted.savedTermios = savedTermios\n\n\t_, width := sys.GetWinsize(int(ed.file.Fd()))\n\t\/\/ Turn on autowrap, write lackEOL along with enough padding to fill the\n\t\/\/ whole screen. If the cursor was in the first column, we end up in the\n\t\/\/ same line (just off the line boundary); otherwise we are now in the next\n\t\/\/ line. We now rewind to the first column and erase anything there. The\n\t\/\/ final effect is that a lackEOL gets written if and only if the cursor\n\t\/\/ was not in the first column.\n\tfmt.Fprintf(ed.file, \"\\033[?7h%s%*s\\r \\r\", lackEOL, width-WcWidth(lackEOLRune), \"\")\n\n\t\/\/ Turn off autowrap. The edito has its own wrapping mechanism. Doing\n\t\/\/ wrapping manually means that when the actual width of some characters\n\t\/\/ are greater than what our wcwidth implementation tells us, characters at\n\t\/\/ the end of that line gets hidden -- compared to pushed to the next line,\n\t\/\/ which is more disastrous.\n\ted.file.WriteString(\"\\033[?7l\")\n\t\/\/ Turn on SGR-style mouse tracking.\n\t\/\/ed.file.WriteString(\"\\033[?1000;1006h\")\n\treturn nil\n}\n\n\/\/ finishReadLine puts the terminal in a state suitable for other programs to\n\/\/ use.\nfunc (ed *Editor) finishReadLine(addError func(error)) {\n\ted.mode = &ed.insert\n\ted.tips = nil\n\ted.dot = len(ed.line)\n\t\/\/ TODO Perhaps make it optional to NOT clear the rprompt\n\ted.rprompt = \"\"\n\taddError(ed.refresh(false, false))\n\ted.file.WriteString(\"\\n\")\n\n\t\/\/ ed.reader.Stop()\n\ted.reader.Quit()\n\n\t\/\/ Turn on autowrap.\n\ted.file.WriteString(\"\\033[?7h\")\n\t\/\/ Turn off mouse tracking.\n\t\/\/ed.file.WriteString(\"\\033[?1000;1006l\")\n\n\t\/\/ restore termios\n\terr := ed.savedTermios.ApplyToFd(int(ed.file.Fd()))\n\n\tif err != nil {\n\t\taddError(fmt.Errorf(\"can't restore terminal attribute: %s\", err))\n\t}\n\ted.savedTermios = nil\n\ted.editorState = editorState{}\n}\n\n\/\/ ReadLine reads a line interactively.\nfunc (ed *Editor) ReadLine() (line string, err error) {\n\ted.editorState = editorState{active: true}\n\ted.mode = &ed.insert\n\n\tisExternalCh := make(chan map[string]bool, 1)\n\tgo getIsExternal(ed.evaler, isExternalCh)\n\n\ted.writer.resetOldBuf()\n\tgo ed.reader.Run()\n\n\te := ed.startReadLine()\n\tif e != nil {\n\t\treturn \"\", e\n\t}\n\tdefer ed.finishReadLine(func(e error) {\n\t\tif e != nil {\n\t\t\terr = util.CatError(err, e)\n\t\t}\n\t})\n\n\tfullRefresh := false\nMainLoop:\n\tfor {\n\t\ted.prompt = ed.ps1.Call(ed)\n\t\ted.rprompt = ed.rps1.Call(ed)\n\n\t\terr := ed.refresh(fullRefresh, true)\n\t\tfullRefresh = false\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\ted.tips = nil\n\n\t\tselect {\n\t\tcase m := <-isExternalCh:\n\t\t\ted.isExternal = m\n\t\tcase sig := <-ed.sigs:\n\t\t\t\/\/ TODO(xiaq): Maybe support customizable handling of signals\n\t\t\tswitch sig {\n\t\t\tcase syscall.SIGINT:\n\t\t\t\t\/\/ Start over\n\t\t\t\ted.editorState = editorState{\n\t\t\t\t\tsavedTermios: ed.savedTermios,\n\t\t\t\t\tisExternal:   ed.isExternal,\n\t\t\t\t}\n\t\t\t\tgoto MainLoop\n\t\t\tcase syscall.SIGWINCH:\n\t\t\t\tfullRefresh = true\n\t\t\t\tcontinue MainLoop\n\t\t\tcase syscall.SIGCHLD:\n\t\t\t\t\/\/ ignore\n\t\t\tdefault:\n\t\t\t\ted.addTip(\"ignored signal %s\", sig)\n\t\t\t}\n\t\tcase err := <-ed.reader.ErrorChan():\n\t\t\ted.notify(\"reader error: %s\", err.Error())\n\t\tcase mouse := <-ed.reader.MouseChan():\n\t\t\ted.addTip(\"mouse: %+v\", mouse)\n\t\tcase <-ed.reader.CPRChan():\n\t\t\t\/\/ Ignore CPR\n\t\tcase k := <-ed.reader.KeyChan():\n\t\tlookupKey:\n\t\t\tkeyBinding, ok := keyBindings[ed.mode.Mode()]\n\t\t\tif !ok {\n\t\t\t\ted.addTip(\"No binding for current mode\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfn, bound := keyBinding[k]\n\t\t\tif !bound {\n\t\t\t\tfn = keyBinding[Default]\n\t\t\t}\n\n\t\t\ted.lastKey = k\n\t\t\tfn.Call(ed)\n\t\t\tact := ed.nextAction\n\t\t\ted.nextAction = action{}\n\n\t\t\tswitch act.typ {\n\t\t\tcase noAction:\n\t\t\t\tcontinue\n\t\t\tcase reprocessKey:\n\t\t\t\terr = ed.refresh(false, true)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t\tgoto lookupKey\n\t\t\tcase exitReadLine:\n\t\t\t\tif act.returnErr == nil && act.returnLine != \"\" {\n\t\t\t\t\ted.appendHistory(act.returnLine)\n\t\t\t\t}\n\t\t\t\treturn act.returnLine, act.returnErr\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>Cosmetics.<commit_after>\/\/ Package edit implements a command line editor.\npackage edit\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com\/elves\/elvish\/eval\"\n\t\"github.com\/elves\/elvish\/parse\"\n\t\"github.com\/elves\/elvish\/store\"\n\t\"github.com\/elves\/elvish\/sys\"\n\t\"github.com\/elves\/elvish\/util\"\n)\n\nvar Logger = util.GetLogger(\"[edit] \")\n\nconst (\n\tlackEOLRune = '\\u23ce'\n\tlackEOL     = \"\\033[7m\" + string(lackEOLRune) + \"\\033[m\"\n)\n\n\/\/ Editor keeps the status of the line editor.\ntype Editor struct {\n\tfile   *os.File\n\twriter *writer\n\treader *Reader\n\tsigs   chan os.Signal\n\tstore  *store.Store\n\tevaler *eval.Evaler\n\tcmdSeq int\n\tps1    Prompt\n\trps1   Prompt\n\teditorState\n}\n\ntype editorState struct {\n\t\/\/ States used during ReadLine. Reset at the beginning of ReadLine.\n\tactive       bool\n\tsavedTermios *sys.Termios\n\n\tnotifications []string\n\ttips          []string\n\n\ttokens  []Token\n\tprompt  string\n\trprompt string\n\tline    string\n\tdot     int\n\n\tmode Mode\n\n\tinsert          insert\n\tcommand         command\n\tcompletion      completion\n\tcompletionLines int\n\tnavigation      navigation\n\thistory         historyState\n\thistoryListing  historyListing\n\tlocation        location\n\n\tisExternal      map[string]bool\n\tparseErrorAtEnd bool\n\t\/\/ Used for builtins.\n\tlastKey    Key\n\tnextAction action\n}\n\n\/\/ NewEditor creates an Editor.\nfunc NewEditor(file *os.File, sigs chan os.Signal, ev *eval.Evaler, st *store.Store) *Editor {\n\tseq := -1\n\tif st != nil {\n\t\tvar err error\n\t\tseq, err = st.NextCmdSeq()\n\t\tif err != nil {\n\t\t\t\/\/ TODO(xiaq): Also report the error\n\t\t\tseq = -1\n\t\t}\n\t}\n\n\tprompt, rprompt := defaultPrompts()\n\n\ted := &Editor{\n\t\tfile:   file,\n\t\twriter: newWriter(file),\n\t\treader: NewReader(file),\n\t\tsigs:   sigs,\n\t\tstore:  st,\n\t\tevaler: ev,\n\t\tcmdSeq: seq,\n\t\tps1:    prompt,\n\t\trps1:   rprompt,\n\t}\n\tev.AddModule(\"le\", makeModule(ed))\n\treturn ed\n}\n\nfunc (ed *Editor) flash() {\n\t\/\/ TODO implement fish-like flash effect\n}\n\nfunc (ed *Editor) addTip(format string, args ...interface{}) {\n\ted.tips = append(ed.tips, fmt.Sprintf(format, args...))\n}\n\nfunc (ed *Editor) notify(format string, args ...interface{}) {\n\ted.notifications = append(ed.notifications, fmt.Sprintf(format, args...))\n}\n\nfunc (ed *Editor) refresh(fullRefresh bool, tips bool) error {\n\t\/\/ Re-lex the line, unless we are in modeCompletion\n\tsrc := ed.line\n\tif ed.mode.Mode() != modeCompletion {\n\t\tn, err := parse.Parse(src)\n\t\ted.parseErrorAtEnd = err != nil && atEnd(err, len(src))\n\t\tif err != nil {\n\t\t\t\/\/ If all the errors happen at the end, it is liekly complaining about missing texts that will eventually be inserted. Don't show such errors.\n\t\t\t\/\/ XXX We may need a more reliable criteria.\n\t\t\tif tips && !ed.parseErrorAtEnd {\n\t\t\t\ted.addTip(\"parser error: %s\", err)\n\t\t\t}\n\t\t}\n\t\tif n == nil {\n\t\t\ted.tokens = []Token{{ParserError, src, nil, \"\"}}\n\t\t} else {\n\t\t\ted.tokens = tokenize(src, n)\n\t\t\t_, err := ed.evaler.Compile(n)\n\t\t\tif err != nil {\n\t\t\t\tif tips && !atEnd(err, len(src)) {\n\t\t\t\t\ted.addTip(\"compiler error: %s\", err)\n\t\t\t\t}\n\t\t\t\tif err, ok := err.(*util.PosError); ok {\n\t\t\t\t\tp := err.Begin\n\t\t\t\t\tfor i, token := range ed.tokens {\n\t\t\t\t\t\tif token.Node.Begin() <= p && p < token.Node.End() {\n\t\t\t\t\t\t\ted.tokens[i].MoreStyle += styleForCompilerError\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor i, t := range ed.tokens {\n\t\t\tfor _, stylist := range stylists {\n\t\t\t\ted.tokens[i].MoreStyle += stylist(t.Node, ed)\n\t\t\t}\n\t\t}\n\t}\n\treturn ed.writer.refresh(&ed.editorState, fullRefresh)\n}\n\nfunc atEnd(e error, n int) bool {\n\tswitch e := e.(type) {\n\tcase *util.PosError:\n\t\treturn e.Begin == n\n\tcase *util.Errors:\n\t\tfor _, child := range e.Errors {\n\t\t\tif !atEnd(child, n) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\n\/\/ insertAtDot inserts text at the dot and moves the dot after it.\nfunc (ed *Editor) insertAtDot(text string) {\n\ted.line = ed.line[:ed.dot] + text + ed.line[ed.dot:]\n\ted.dot += len(text)\n}\n\nfunc setupTerminal(file *os.File) (*sys.Termios, error) {\n\tfd := int(file.Fd())\n\tterm, err := sys.NewTermiosFromFd(fd)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't get terminal attribute: %s\", err)\n\t}\n\n\tsavedTermios := term.Copy()\n\n\tterm.SetICanon(false)\n\tterm.SetEcho(false)\n\tterm.SetVMin(1)\n\tterm.SetVTime(0)\n\n\terr = term.ApplyToFd(fd)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"can't set up terminal attribute: %s\", err)\n\t}\n\n\t\/*\n\t\terr = sys.FlushInput(fd)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"can't flush input: %s\", err)\n\t\t}\n\t*\/\n\n\treturn savedTermios, nil\n}\n\n\/\/ startReadLine prepares the terminal for the editor.\nfunc (ed *Editor) startReadLine() error {\n\tsavedTermios, err := setupTerminal(ed.file)\n\tif err != nil {\n\t\treturn err\n\t}\n\ted.savedTermios = savedTermios\n\n\t_, width := sys.GetWinsize(int(ed.file.Fd()))\n\t\/\/ Turn on autowrap, write lackEOL along with enough padding to fill the\n\t\/\/ whole screen. If the cursor was in the first column, we end up in the\n\t\/\/ same line (just off the line boundary); otherwise we are now in the next\n\t\/\/ line. We now rewind to the first column and erase anything there. The\n\t\/\/ final effect is that a lackEOL gets written if and only if the cursor\n\t\/\/ was not in the first column.\n\tfmt.Fprintf(ed.file, \"\\033[?7h%s%*s\\r \\r\", lackEOL, width-WcWidth(lackEOLRune), \"\")\n\n\t\/\/ Turn off autowrap. The edito has its own wrapping mechanism. Doing\n\t\/\/ wrapping manually means that when the actual width of some characters\n\t\/\/ are greater than what our wcwidth implementation tells us, characters at\n\t\/\/ the end of that line gets hidden -- compared to pushed to the next line,\n\t\/\/ which is more disastrous.\n\ted.file.WriteString(\"\\033[?7l\")\n\t\/\/ Turn on SGR-style mouse tracking.\n\t\/\/ed.file.WriteString(\"\\033[?1000;1006h\")\n\treturn nil\n}\n\n\/\/ finishReadLine puts the terminal in a state suitable for other programs to\n\/\/ use.\nfunc (ed *Editor) finishReadLine(addError func(error)) {\n\ted.mode = &ed.insert\n\ted.tips = nil\n\ted.dot = len(ed.line)\n\t\/\/ TODO Perhaps make it optional to NOT clear the rprompt\n\ted.rprompt = \"\"\n\taddError(ed.refresh(false, false))\n\ted.file.WriteString(\"\\n\")\n\n\t\/\/ ed.reader.Stop()\n\ted.reader.Quit()\n\n\t\/\/ Turn on autowrap.\n\ted.file.WriteString(\"\\033[?7h\")\n\t\/\/ Turn off mouse tracking.\n\t\/\/ed.file.WriteString(\"\\033[?1000;1006l\")\n\n\t\/\/ restore termios\n\terr := ed.savedTermios.ApplyToFd(int(ed.file.Fd()))\n\n\tif err != nil {\n\t\taddError(fmt.Errorf(\"can't restore terminal attribute: %s\", err))\n\t}\n\ted.savedTermios = nil\n\ted.editorState = editorState{}\n}\n\n\/\/ ReadLine reads a line interactively.\nfunc (ed *Editor) ReadLine() (line string, err error) {\n\ted.editorState = editorState{active: true}\n\ted.mode = &ed.insert\n\n\tisExternalCh := make(chan map[string]bool, 1)\n\tgo getIsExternal(ed.evaler, isExternalCh)\n\n\ted.writer.resetOldBuf()\n\tgo ed.reader.Run()\n\n\te := ed.startReadLine()\n\tif e != nil {\n\t\treturn \"\", e\n\t}\n\tdefer ed.finishReadLine(func(e error) {\n\t\tif e != nil {\n\t\t\terr = util.CatError(err, e)\n\t\t}\n\t})\n\n\tfullRefresh := false\nMainLoop:\n\tfor {\n\t\ted.prompt = ed.ps1.Call(ed)\n\t\ted.rprompt = ed.rps1.Call(ed)\n\n\t\terr := ed.refresh(fullRefresh, true)\n\t\tfullRefresh = false\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\ted.tips = nil\n\n\t\tselect {\n\t\tcase m := <-isExternalCh:\n\t\t\ted.isExternal = m\n\t\tcase sig := <-ed.sigs:\n\t\t\t\/\/ TODO(xiaq): Maybe support customizable handling of signals\n\t\t\tswitch sig {\n\t\t\tcase syscall.SIGINT:\n\t\t\t\t\/\/ Start over\n\t\t\t\ted.editorState = editorState{\n\t\t\t\t\tsavedTermios: ed.savedTermios,\n\t\t\t\t\tisExternal:   ed.isExternal,\n\t\t\t\t}\n\t\t\t\tgoto MainLoop\n\t\t\tcase syscall.SIGWINCH:\n\t\t\t\tfullRefresh = true\n\t\t\t\tcontinue MainLoop\n\t\t\tcase syscall.SIGCHLD:\n\t\t\t\t\/\/ ignore\n\t\t\tdefault:\n\t\t\t\ted.addTip(\"ignored signal %s\", sig)\n\t\t\t}\n\t\tcase err := <-ed.reader.ErrorChan():\n\t\t\ted.notify(\"reader error: %s\", err.Error())\n\t\tcase mouse := <-ed.reader.MouseChan():\n\t\t\ted.addTip(\"mouse: %+v\", mouse)\n\t\tcase <-ed.reader.CPRChan():\n\t\t\t\/\/ Ignore CPR\n\t\tcase k := <-ed.reader.KeyChan():\n\t\tlookupKey:\n\t\t\tkeyBinding, ok := keyBindings[ed.mode.Mode()]\n\t\t\tif !ok {\n\t\t\t\ted.addTip(\"No binding for current mode\")\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfn, bound := keyBinding[k]\n\t\t\tif !bound {\n\t\t\t\tfn = keyBinding[Default]\n\t\t\t}\n\n\t\t\ted.lastKey = k\n\t\t\tfn.Call(ed)\n\t\t\tact := ed.nextAction\n\t\t\ted.nextAction = action{}\n\n\t\t\tswitch act.typ {\n\t\t\tcase noAction:\n\t\t\t\tcontinue\n\t\t\tcase reprocessKey:\n\t\t\t\terr = ed.refresh(false, true)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn \"\", err\n\t\t\t\t}\n\t\t\t\tgoto lookupKey\n\t\t\tcase exitReadLine:\n\t\t\t\tif act.returnErr == nil && act.returnLine != \"\" {\n\t\t\t\t\ted.appendHistory(act.returnLine)\n\t\t\t\t}\n\t\t\t\treturn act.returnLine, act.returnErr\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package mppuma\n\nimport \"testing\"\n\nfunc TestGraphDefinition(t *testing.T) {\n\n\tvar puma PumaPlugin\n\n\tgraphdef := puma.GraphDefinition()\n\n\tif len(graphdef) != 2 {\n\t\tt.Errorf(\"GraphDefinition: %d should be %d\", len(graphdef), 2)\n\t}\n}\n\nfunc TestGraphDefinitionWithGC(t *testing.T) {\n\n\tvar puma PumaPlugin\n\tpuma.WithGC = true\n\n\tgraphdef := puma.GraphDefinition()\n\n\tif len(graphdef) != 3 {\n\t\tt.Errorf(\"GraphDefinitionWithGC: %d should be %d\", len(graphdef), 3)\n\t}\n}\n<commit_msg>Fix test<commit_after>package mppuma\n\nimport \"testing\"\n\nfunc TestGraphDefinition(t *testing.T) {\n\tdesired := 4\n\n\tvar puma PumaPlugin\n\n\tgraphdef := puma.GraphDefinition()\n\n\tif len(graphdef) != desired {\n\t\tt.Errorf(\"GraphDefinition: %d should be %d\", len(graphdef), desired)\n\t}\n}\n\nfunc TestGraphDefinitionWithGC(t *testing.T) {\n\tdesired := 8\n\n\tvar puma PumaPlugin\n\tpuma.WithGC = true\n\n\tgraphdef := puma.GraphDefinition()\n\n\tif len(graphdef) != desired {\n\t\tt.Errorf(\"GraphDefinitionWithGC: %d should be %d\", len(graphdef), desired)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package lib\n\nimport (\n\t\"time\"\n)\n\nconst windows = 2\n\ntype RateLimit struct {\n\tPeriod time.Duration\n\tRate   uint\n\ttoks   chan struct{}\n\tpaused bool\n}\n\nfunc (r *RateLimit) Start() {\n\tr.paused = false\n\tif r.toks == nil {\n\t\tr.toks = make(chan struct{}, windows*r.Rate)\n\t}\n\tgo func() {\n\t\tfor true {\n\t\t\tfor i := uint(0); i < r.Rate; i++ {\n\t\t\t\tr.toks <- struct{}{}\n\t\t\t}\n\t\t\ttime.Sleep(r.Period)\n\t\t\tif r.paused {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (r *RateLimit) Stop() {\n\tr.paused = true\n}\n\nfunc (r *RateLimit) TryGet() bool {\n\tselect {\n\tcase _ = <-r.toks:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc (r *RateLimit) Get() {\n\t_ = <-r.toks\n}\n<commit_msg>Switch rate limiter windowsize to 1.<commit_after>package lib\n\nimport (\n\t\"time\"\n)\n\nconst windows = 1\n\ntype RateLimit struct {\n\tPeriod time.Duration\n\tRate   uint\n\ttoks   chan struct{}\n\tpaused bool\n}\n\nfunc (r *RateLimit) Start() {\n\tr.paused = false\n\tif r.toks == nil {\n\t\tr.toks = make(chan struct{}, windows*r.Rate)\n\t}\n\tgo func() {\n\t\tfor true {\n\t\t\tfor i := uint(0); i < r.Rate; i++ {\n\t\t\t\tr.toks <- struct{}{}\n\t\t\t}\n\t\t\ttime.Sleep(r.Period)\n\t\t\tif r.paused {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (r *RateLimit) Stop() {\n\tr.paused = true\n}\n\nfunc (r *RateLimit) TryGet() bool {\n\tselect {\n\tcase _ = <-r.toks:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc (r *RateLimit) Get() {\n\t_ = <-r.toks\n}\n<|endoftext|>"}
{"text":"<commit_before>package xpath\n\/* \n#cgo pkg-config: libxml-2.0\n#include <libxml\/xpath.h> \n#include <libxml\/xpathInternals.h>\n#include <libxml\/parser.h>\n\nvoid xmlXPathContextSetNode(xmlXPathContext *ctx, xmlNode *new_node) { \n\tctx->node = new_node;\n}\n\nxmlNode* fetchNode(xmlNodeSet *nodeset, int index) {\n  \treturn nodeset->nodeTab[index];\n}\n*\/\nimport \"C\"\nimport \"unsafe\"\n\ntype XPath struct {\n\tContextPtr *C.xmlXPathContext\n\tResultPtr  *C.xmlXPathObject\n}\n\nfunc NewXPath(docPtr unsafe.Pointer) (xpath *XPath) {\n\tif docPtr == nil {\n\t\treturn\n\t}\n\txpath = &XPath{ContextPtr: C.xmlXPathNewContext((*C.xmlDoc)(docPtr)), ResultPtr: nil}\n\treturn\n}\n\nfunc (xpath *XPath) RegisterNamespace(prefix, href string) bool {\n\tvar prefixPtr unsafe.Pointer = nil\n\tif len(prefix) > 0 {\n\t\tprefixBytes := []byte(prefix)\n\t\tprefixPtr = unsafe.Pointer(&prefixBytes[0])\n\t}\n\t\n\tvar hrefPtr unsafe.Pointer = nil\n\tif len(href) > 0 {\n\t\threfBytes := []byte(href)\n\t\threfPtr = unsafe.Pointer(&hrefBytes[0])\n\t}\n\n\tresult := C.xmlXPathRegisterNs(xpath.ContextPtr, (*C.xmlChar)(prefixPtr), (*C.xmlChar)(hrefPtr))\n\treturn result == 0\n}\n\nfunc (xpath *XPath) Evaluate(nodePtr unsafe.Pointer, xpathExpr *Expression) (nodes []unsafe.Pointer){\n\tif nodePtr == nil {\n\t\treturn\n\t}\n\tC.xmlXPathContextSetNode(xpath.ContextPtr, (*C.xmlNode)(nodePtr))\n\tif xpath.ResultPtr != nil {\n\t\tC.xmlXPathFreeObject(xpath.ResultPtr)\n\t}\n\txpath.ResultPtr = C.xmlXPathCompiledEval(xpathExpr.Ptr, xpath.ContextPtr)\n\tnodesetPtr := xpath.ResultPtr.nodesetval\n\tif nodesetSize := int(nodesetPtr.nodeNr); nodesetSize > 0 {\n\t\tnodes = make([]unsafe.Pointer, nodesetSize)\n\t\tfor i := 0; i < nodesetSize; i ++ {\n\t\t\tnodes[i] = unsafe.Pointer(C.fetchNode(nodesetPtr, C.int(i)))\n\t\t}\n\t}\n\treturn\n}\n\nfunc (xpath *XPath) Free() {\n\tif xpath.ContextPtr != nil {\n\t\tC.xmlXPathFreeContext(xpath.ContextPtr)\n\t}\n\tif xpath.ResultPtr != nil {\n\t\tC.xmlXPathFreeObject(xpath.ResultPtr)\n\t}\n}<commit_msg>check for nil xpath result<commit_after>package xpath\n\/* \n#cgo pkg-config: libxml-2.0\n#include <libxml\/xpath.h> \n#include <libxml\/xpathInternals.h>\n#include <libxml\/parser.h>\n\nvoid xmlXPathContextSetNode(xmlXPathContext *ctx, xmlNode *new_node) { \n\tctx->node = new_node;\n}\n\nxmlNode* fetchNode(xmlNodeSet *nodeset, int index) {\n  \treturn nodeset->nodeTab[index];\n}\n*\/\nimport \"C\"\nimport \"unsafe\"\n\ntype XPath struct {\n\tContextPtr *C.xmlXPathContext\n\tResultPtr  *C.xmlXPathObject\n}\n\nfunc NewXPath(docPtr unsafe.Pointer) (xpath *XPath) {\n\tif docPtr == nil {\n\t\treturn\n\t}\n\txpath = &XPath{ContextPtr: C.xmlXPathNewContext((*C.xmlDoc)(docPtr)), ResultPtr: nil}\n\treturn\n}\n\nfunc (xpath *XPath) RegisterNamespace(prefix, href string) bool {\n\tvar prefixPtr unsafe.Pointer = nil\n\tif len(prefix) > 0 {\n\t\tprefixBytes := []byte(prefix)\n\t\tprefixPtr = unsafe.Pointer(&prefixBytes[0])\n\t}\n\t\n\tvar hrefPtr unsafe.Pointer = nil\n\tif len(href) > 0 {\n\t\threfBytes := []byte(href)\n\t\threfPtr = unsafe.Pointer(&hrefBytes[0])\n\t}\n\n\tresult := C.xmlXPathRegisterNs(xpath.ContextPtr, (*C.xmlChar)(prefixPtr), (*C.xmlChar)(hrefPtr))\n\treturn result == 0\n}\n\nfunc (xpath *XPath) Evaluate(nodePtr unsafe.Pointer, xpathExpr *Expression) (nodes []unsafe.Pointer){\n\tif nodePtr == nil {\n\t\treturn\n\t}\n\tC.xmlXPathContextSetNode(xpath.ContextPtr, (*C.xmlNode)(nodePtr))\n\tif xpath.ResultPtr != nil {\n\t\tC.xmlXPathFreeObject(xpath.ResultPtr)\n\t}\n\txpath.ResultPtr = C.xmlXPathCompiledEval(xpathExpr.Ptr, xpath.ContextPtr)\n\tif nodesetPtr := xpath.ResultPtr.nodesetval; nodesetPtr != nil {\n\t\tif nodesetSize := int(nodesetPtr.nodeNr); nodesetSize > 0 {\n\t\t\tnodes = make([]unsafe.Pointer, nodesetSize)\n\t\t\tfor i := 0; i < nodesetSize; i ++ {\n\t\t\t\tnodes[i] = unsafe.Pointer(C.fetchNode(nodesetPtr, C.int(i)))\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc (xpath *XPath) Free() {\n\tif xpath.ContextPtr != nil {\n\t\tC.xmlXPathFreeContext(xpath.ContextPtr)\n\t}\n\tif xpath.ResultPtr != nil {\n\t\tC.xmlXPathFreeObject(xpath.ResultPtr)\n\t}\n}<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2020 Dgraph Labs, Inc. and Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage z\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\t\"unsafe\"\n\n\t\"github.com\/dustin\/go-humanize\"\n)\n\n\/\/ Allocator amortizes the cost of small allocations by allocating memory in bigger chunks.\n\/\/ Internally it uses z.Calloc to allocate memory. Once allocated, the memory is not moved,\n\/\/ so it is safe to use the allocated bytes to unsafe cast them to Go struct pointers.\ntype Allocator struct {\n\tsync.Mutex\n\tpageSize int\n\tcurBuf   int\n\tcurIdx   int\n\tbuffers  [][]byte\n\tsize     uint64\n\tRef      uint64\n\tTag      string\n\treused   int\n\n\tfreelist map[int]uint64 \/\/ Key is the size. Value is the first node of that size.\n}\n\n\/\/ allocs keeps references to all Allocators, so we can safely discard them later.\nvar allocsMu *sync.Mutex\nvar allocRef uint64\nvar allocs map[uint64]*Allocator\nvar calculatedLog2 []int\nvar allocatorPool chan *Allocator\nvar numGets int64\n\nfunc init() {\n\tallocsMu = new(sync.Mutex)\n\tallocs = make(map[uint64]*Allocator)\n\n\t\/\/ Set up a unique Ref per process.\n\trand.Seed(time.Now().UnixNano())\n\tallocRef = uint64(rand.Int63n(1<<16)) << 48\n\n\tcalculatedLog2 = make([]int, 1025)\n\tfor i := 1; i <= 1024; i++ {\n\t\tcalculatedLog2[i] = int(math.Log2(float64(i)))\n\t}\n\tallocatorPool = make(chan *Allocator, 8)\n\tgo freeupAllocators()\n\t\/\/ fmt.Printf(\"Using z.Allocator with starting ref: %x\\n\", allocRef)\n}\n\nfunc freeupAllocators() {\n\tticker := time.NewTicker(2 * time.Second)\n\tdefer ticker.Stop()\n\n\tvar last int64\n\tfor range ticker.C {\n\t\tgets := atomic.LoadInt64(&numGets)\n\t\tif gets != last {\n\t\t\t\/\/ Some retrievals were made since the last time. So, let's avoid doing a release.\n\t\t\tlast = gets\n\t\t\tcontinue\n\t\t}\n\t\tselect {\n\t\tcase alloc := <-allocatorPool:\n\t\t\talloc.Release()\n\t\tdefault:\n\t\t}\n\t}\n}\n\nfunc GetAllocatorFromPool(sz int) *Allocator {\n\tatomic.AddInt64(&numGets, 1)\n\tselect {\n\tcase alloc := <-allocatorPool:\n\t\talloc.Reset()\n\t\treturn alloc\n\tdefault:\n\t\treturn NewAllocator(sz)\n\t}\n}\nfunc ReturnAllocator(a *Allocator) {\n\ta.TrimTo(400 << 20)\n\n\tselect {\n\tcase allocatorPool <- a:\n\t\treturn\n\tdefault:\n\t\ta.Release()\n\t}\n}\n\n\/\/ NewAllocator creates an allocator starting with the given size.\nfunc NewAllocator(sz int) *Allocator {\n\tref := atomic.AddUint64(&allocRef, 1)\n\ta := &Allocator{\n\t\tpageSize: sz,\n\t\tRef:      ref,\n\t\tfreelist: make(map[int]uint64),\n\t}\n\n\tallocsMu.Lock()\n\tallocs[ref] = a\n\tallocsMu.Unlock()\n\treturn a\n}\n\nfunc (a *Allocator) Reset() {\n\ta.curBuf, a.curIdx = 0, 0\n\ta.freelist = make(map[int]uint64)\n}\n\nfunc PrintAllocators() {\n\tallocsMu.Lock()\n\ttags := make(map[string]int)\n\tvar total uint64\n\tfor _, ac := range allocs {\n\t\ttags[ac.Tag]++\n\t\ttotal += ac.Allocated()\n\t}\n\tfor tag, count := range tags {\n\t\tfmt.Printf(\"Allocator Tag: %s Count: %d\\n\", tag, count)\n\t}\n\tfmt.Printf(\"Total allocators: %d. Total Size: %s\\n\",\n\t\tlen(allocs), humanize.IBytes(total))\n\tallocsMu.Unlock()\n}\n\n\/\/ AllocatorFrom would return the allocator corresponding to the ref.\nfunc AllocatorFrom(ref uint64) *Allocator {\n\tallocsMu.Lock()\n\ta := allocs[ref]\n\tallocsMu.Unlock()\n\treturn a\n}\n\n\/\/ Size returns the size of the allocations so far.\nfunc (a *Allocator) Size() uint64 {\n\ta.Lock()\n\tdefer a.Unlock()\n\n\treturn a.size\n}\n\nfunc log2(sz int) int {\n\tif sz < len(calculatedLog2) {\n\t\treturn calculatedLog2[sz]\n\t}\n\tpow := 10\n\tsz >>= 10\n\tfor sz > 1 {\n\t\tsz >>= 1\n\t\tpow++\n\t}\n\treturn pow\n}\n\nfunc (a *Allocator) addToFreelist(b []byte) {\n\tif len(b) < 32 {\n\t\t\/\/ Don't do anything.\n\t\treturn\n\t}\n\n\tl2 := log2(len(b))\n\troot := a.freelist[l2]\n\tn := node(b)\n\t\/\/ Length would be the first 8 bytes.\n\tn.setAt(0, uint64(len(b)))\n\t\/\/ Followed by the pointer to the next byte array.\n\tn.setAt(8, root)\n\ta.freelist[l2] = uint64(uintptr(unsafe.Pointer(&b[0])))\n}\n\nfunc (a *Allocator) Return(b []byte) {\n\t\/\/ Turning this off for now.\n\t\/\/ a.Lock()\n\t\/\/ defer a.Unlock()\n\t\/\/ a.addToFreelist(b)\n}\n\nfunc getBuf(p uint64, sz int) []byte {\n\treturn (*[MaxArrayLen]byte)(unsafe.Pointer(uintptr(p)))[:sz:sz]\n}\n\nfunc (a *Allocator) fromFreeList(need int) []byte {\n\tvar last uint64\n\tspan := log2(need)\n\tn := a.freelist[span]\n\tfor n != 0 {\n\t\tcurBuf := getBuf(n, 16)\n\t\tcurNode := node(curBuf)\n\t\tsz := int(curNode.uint64(0))\n\t\tif sz < need {\n\t\t\tlast, n = n, curNode.uint64(8)\n\t\t\tcontinue\n\t\t}\n\t\tcurBuf = getBuf(n, sz)\n\t\tuse := curBuf[:need]\n\t\tleft := curBuf[need:]\n\n\t\tnext := node(curBuf).uint64(8)\n\t\tif last == 0 {\n\t\t\ta.freelist[span] = next\n\t\t} else if last > 0 {\n\t\t\tlastBuf := getBuf(last, 16)\n\t\t\tnode(lastBuf).setAt(8, next)\n\t\t}\n\n\t\ta.addToFreelist(left)\n\t\tZeroOut(use, 0, 16) \/\/ just zero out the initial 16 bytes.\n\t\treturn use\n\t}\n\treturn nil\n}\n\nfunc (a *Allocator) Allocated() uint64 {\n\ta.Lock()\n\tdefer a.Unlock()\n\tvar alloc int\n\tfor _, b := range a.buffers {\n\t\talloc += cap(b)\n\t}\n\treturn uint64(alloc)\n}\n\nfunc (a *Allocator) TrimTo(max int) {\n\ta.Lock()\n\tdefer a.Unlock()\n\n\tvar alloc int\n\tidx := -1\n\tfor i, b := range a.buffers {\n\t\talloc += len(b)\n\t\tif alloc >= max {\n\t\t\tidx = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif idx == -1 {\n\t\treturn\n\t}\n\tfor _, b := range a.buffers[idx:] {\n\t\tfmt.Printf(\"Trim: Removing buffer of size: %d\\n\", len(b))\n\t\tFree(b)\n\t}\n\ta.buffers = a.buffers[:idx]\n\talloc = 0\n\tfor _, b := range a.buffers {\n\t\talloc += len(b)\n\t}\n\tfmt.Printf(\"Trim: Final size: %d\\n\", alloc)\n}\n\n\/\/ Release would release the memory back. Remember to make this call to avoid memory leaks.\nfunc (a *Allocator) Release() {\n\tif a == nil {\n\t\treturn\n\t}\n\n\ta.Lock()\n\tdefer a.Unlock()\n\n\tvar alloc int\n\tfor _, b := range a.buffers {\n\t\talloc += len(b)\n\t\tFree(b)\n\t}\n\t\/\/ ratio := float64(a.reused) \/ float64(alloc)\n\t\/\/ if ratio == 0.0 || ratio > 0.5 {\n\tfmt.Printf(\"Releasing Allocator Size: %s\\n\",\n\t\thumanize.IBytes(uint64(alloc)))\n\t\/\/ }\n\n\tallocsMu.Lock()\n\tdelete(allocs, a.Ref)\n\tallocsMu.Unlock()\n}\n\nconst maxAlloc = 1 << 30\n\nfunc (a *Allocator) MaxAlloc() int {\n\treturn maxAlloc\n}\n\nconst nodeAlign = int(unsafe.Sizeof(uint64(0))) - 1\n\nfunc (a *Allocator) AllocateAligned(sz int) []byte {\n\ttsz := sz + nodeAlign\n\tout := a.Allocate(tsz)\n\t\/\/ TODO: We should align based on out's address.\n\taligned := (a.curIdx - tsz + nodeAlign) & ^nodeAlign\n\n\tstart := tsz - (a.curIdx - aligned)\n\treturn out[start : start+sz]\n}\n\nfunc (a *Allocator) Copy(buf []byte) []byte {\n\tif a == nil {\n\t\treturn append([]byte{}, buf...)\n\t}\n\tout := a.Allocate(len(buf))\n\tcopy(out, buf)\n\treturn out\n}\n\nfunc (a *Allocator) addBufferWithMinSize(sz int) {\n\tfor {\n\t\ta.pageSize *= 2 \/\/ Do multiply by 2 here.\n\t\tif a.pageSize >= sz {\n\t\t\tbreak\n\t\t}\n\t}\n\tif a.pageSize > maxAlloc {\n\t\ta.pageSize = maxAlloc\n\t}\n\n\tbuf := Calloc(a.pageSize)\n\ta.buffers = append(a.buffers, buf)\n}\n\n\/\/ Allocate would allocate a byte slice of length sz. It is safe to use this memory to unsafe cast\n\/\/ to Go structs.\nfunc (a *Allocator) Allocate(sz int) []byte {\n\tif a == nil {\n\t\treturn make([]byte, sz)\n\t}\n\ta.Lock()\n\tdefer a.Unlock()\n\n\tif len(a.buffers) == 0 {\n\t\tbuf := Calloc(a.pageSize)\n\t\ta.buffers = append(a.buffers, buf)\n\t}\n\tif sz >= maxAlloc {\n\t\tpanic(fmt.Sprintf(\"Allocate call exceeds max allocation possible.\"+\n\t\t\t\" Requested: %d. Max Allowed: %d\\n\", sz, maxAlloc))\n\t}\n\t\/\/ Turning this off for now. This slows down allocations somewhat. Even though it shows a 50%\n\t\/\/ reuse ratio, we get a better bang for the buck by just reusing an entire Allocator for the\n\t\/\/ next cycle.\n\t\/\/\n\t\/\/ if out := a.fromFreeList(sz); out != nil {\n\t\/\/ \ta.reused += len(out)\n\t\/\/ \treturn out\n\t\/\/ }\n\tcb := a.buffers[a.curBuf]\n\tfor len(cb) < a.curIdx+sz {\n\t\ta.curBuf++\n\t\ta.curIdx = 0\n\t\tif a.curBuf == len(a.buffers) {\n\t\t\ta.addBufferWithMinSize(sz)\n\t\t}\n\t\tcb = a.buffers[a.curBuf]\n\t}\n\n\tslice := cb[a.curIdx : a.curIdx+sz]\n\ta.curIdx += sz\n\ta.size += uint64(sz)\n\treturn slice\n}\n<commit_msg>Fix infinite loop in allocator (#214)<commit_after>\/*\n * Copyright 2020 Dgraph Labs, Inc. and Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage z\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\t\"unsafe\"\n\n\t\"github.com\/dustin\/go-humanize\"\n)\n\n\/\/ Allocator amortizes the cost of small allocations by allocating memory in bigger chunks.\n\/\/ Internally it uses z.Calloc to allocate memory. Once allocated, the memory is not moved,\n\/\/ so it is safe to use the allocated bytes to unsafe cast them to Go struct pointers.\ntype Allocator struct {\n\tsync.Mutex\n\tpageSize int\n\tcurBuf   int\n\tcurIdx   int\n\tbuffers  [][]byte\n\tsize     uint64\n\tRef      uint64\n\tTag      string\n\treused   int\n\n\tfreelist map[int]uint64 \/\/ Key is the size. Value is the first node of that size.\n}\n\n\/\/ allocs keeps references to all Allocators, so we can safely discard them later.\nvar allocsMu *sync.Mutex\nvar allocRef uint64\nvar allocs map[uint64]*Allocator\nvar calculatedLog2 []int\nvar allocatorPool chan *Allocator\nvar numGets int64\n\nfunc init() {\n\tallocsMu = new(sync.Mutex)\n\tallocs = make(map[uint64]*Allocator)\n\n\t\/\/ Set up a unique Ref per process.\n\trand.Seed(time.Now().UnixNano())\n\tallocRef = uint64(rand.Int63n(1<<16)) << 48\n\n\tcalculatedLog2 = make([]int, 1025)\n\tfor i := 1; i <= 1024; i++ {\n\t\tcalculatedLog2[i] = int(math.Log2(float64(i)))\n\t}\n\tallocatorPool = make(chan *Allocator, 8)\n\tgo freeupAllocators()\n\t\/\/ fmt.Printf(\"Using z.Allocator with starting ref: %x\\n\", allocRef)\n}\n\nfunc freeupAllocators() {\n\tticker := time.NewTicker(2 * time.Second)\n\tdefer ticker.Stop()\n\n\tvar last int64\n\tfor range ticker.C {\n\t\tgets := atomic.LoadInt64(&numGets)\n\t\tif gets != last {\n\t\t\t\/\/ Some retrievals were made since the last time. So, let's avoid doing a release.\n\t\t\tlast = gets\n\t\t\tcontinue\n\t\t}\n\t\tselect {\n\t\tcase alloc := <-allocatorPool:\n\t\t\talloc.Release()\n\t\tdefault:\n\t\t}\n\t}\n}\n\nfunc GetAllocatorFromPool(sz int) *Allocator {\n\tatomic.AddInt64(&numGets, 1)\n\tselect {\n\tcase alloc := <-allocatorPool:\n\t\talloc.Reset()\n\t\treturn alloc\n\tdefault:\n\t\treturn NewAllocator(sz)\n\t}\n}\nfunc ReturnAllocator(a *Allocator) {\n\ta.TrimTo(400 << 20)\n\n\tselect {\n\tcase allocatorPool <- a:\n\t\treturn\n\tdefault:\n\t\ta.Release()\n\t}\n}\n\n\/\/ NewAllocator creates an allocator starting with the given size.\nfunc NewAllocator(sz int) *Allocator {\n\tref := atomic.AddUint64(&allocRef, 1)\n\t\/\/ We should not allow a zero sized page because addBufferWithMinSize\n\t\/\/ will run into an infinite loop trying to double the pagesize.\n\tif sz == 0 {\n\t\tsz = smallBufferSize\n\t}\n\ta := &Allocator{\n\t\tpageSize: sz,\n\t\tRef:      ref,\n\t\tfreelist: make(map[int]uint64),\n\t}\n\n\tallocsMu.Lock()\n\tallocs[ref] = a\n\tallocsMu.Unlock()\n\treturn a\n}\n\nfunc (a *Allocator) Reset() {\n\ta.curBuf, a.curIdx = 0, 0\n\ta.freelist = make(map[int]uint64)\n}\n\nfunc PrintAllocators() {\n\tallocsMu.Lock()\n\ttags := make(map[string]int)\n\tvar total uint64\n\tfor _, ac := range allocs {\n\t\ttags[ac.Tag]++\n\t\ttotal += ac.Allocated()\n\t}\n\tfor tag, count := range tags {\n\t\tfmt.Printf(\"Allocator Tag: %s Count: %d\\n\", tag, count)\n\t}\n\tfmt.Printf(\"Total allocators: %d. Total Size: %s\\n\",\n\t\tlen(allocs), humanize.IBytes(total))\n\tallocsMu.Unlock()\n}\n\n\/\/ AllocatorFrom would return the allocator corresponding to the ref.\nfunc AllocatorFrom(ref uint64) *Allocator {\n\tallocsMu.Lock()\n\ta := allocs[ref]\n\tallocsMu.Unlock()\n\treturn a\n}\n\n\/\/ Size returns the size of the allocations so far.\nfunc (a *Allocator) Size() uint64 {\n\ta.Lock()\n\tdefer a.Unlock()\n\n\treturn a.size\n}\n\nfunc log2(sz int) int {\n\tif sz < len(calculatedLog2) {\n\t\treturn calculatedLog2[sz]\n\t}\n\tpow := 10\n\tsz >>= 10\n\tfor sz > 1 {\n\t\tsz >>= 1\n\t\tpow++\n\t}\n\treturn pow\n}\n\nfunc (a *Allocator) addToFreelist(b []byte) {\n\tif len(b) < 32 {\n\t\t\/\/ Don't do anything.\n\t\treturn\n\t}\n\n\tl2 := log2(len(b))\n\troot := a.freelist[l2]\n\tn := node(b)\n\t\/\/ Length would be the first 8 bytes.\n\tn.setAt(0, uint64(len(b)))\n\t\/\/ Followed by the pointer to the next byte array.\n\tn.setAt(8, root)\n\ta.freelist[l2] = uint64(uintptr(unsafe.Pointer(&b[0])))\n}\n\nfunc (a *Allocator) Return(b []byte) {\n\t\/\/ Turning this off for now.\n\t\/\/ a.Lock()\n\t\/\/ defer a.Unlock()\n\t\/\/ a.addToFreelist(b)\n}\n\nfunc getBuf(p uint64, sz int) []byte {\n\treturn (*[MaxArrayLen]byte)(unsafe.Pointer(uintptr(p)))[:sz:sz]\n}\n\nfunc (a *Allocator) fromFreeList(need int) []byte {\n\tvar last uint64\n\tspan := log2(need)\n\tn := a.freelist[span]\n\tfor n != 0 {\n\t\tcurBuf := getBuf(n, 16)\n\t\tcurNode := node(curBuf)\n\t\tsz := int(curNode.uint64(0))\n\t\tif sz < need {\n\t\t\tlast, n = n, curNode.uint64(8)\n\t\t\tcontinue\n\t\t}\n\t\tcurBuf = getBuf(n, sz)\n\t\tuse := curBuf[:need]\n\t\tleft := curBuf[need:]\n\n\t\tnext := node(curBuf).uint64(8)\n\t\tif last == 0 {\n\t\t\ta.freelist[span] = next\n\t\t} else if last > 0 {\n\t\t\tlastBuf := getBuf(last, 16)\n\t\t\tnode(lastBuf).setAt(8, next)\n\t\t}\n\n\t\ta.addToFreelist(left)\n\t\tZeroOut(use, 0, 16) \/\/ just zero out the initial 16 bytes.\n\t\treturn use\n\t}\n\treturn nil\n}\n\nfunc (a *Allocator) Allocated() uint64 {\n\ta.Lock()\n\tdefer a.Unlock()\n\tvar alloc int\n\tfor _, b := range a.buffers {\n\t\talloc += cap(b)\n\t}\n\treturn uint64(alloc)\n}\n\nfunc (a *Allocator) TrimTo(max int) {\n\ta.Lock()\n\tdefer a.Unlock()\n\n\tvar alloc int\n\tidx := -1\n\tfor i, b := range a.buffers {\n\t\talloc += len(b)\n\t\tif alloc >= max {\n\t\t\tidx = i\n\t\t\tbreak\n\t\t}\n\t}\n\tif idx == -1 {\n\t\treturn\n\t}\n\tfor _, b := range a.buffers[idx:] {\n\t\tfmt.Printf(\"Trim: Removing buffer of size: %d\\n\", len(b))\n\t\tFree(b)\n\t}\n\ta.buffers = a.buffers[:idx]\n\talloc = 0\n\tfor _, b := range a.buffers {\n\t\talloc += len(b)\n\t}\n\tfmt.Printf(\"Trim: Final size: %d\\n\", alloc)\n}\n\n\/\/ Release would release the memory back. Remember to make this call to avoid memory leaks.\nfunc (a *Allocator) Release() {\n\tif a == nil {\n\t\treturn\n\t}\n\n\ta.Lock()\n\tdefer a.Unlock()\n\n\tvar alloc int\n\tfor _, b := range a.buffers {\n\t\talloc += len(b)\n\t\tFree(b)\n\t}\n\t\/\/ ratio := float64(a.reused) \/ float64(alloc)\n\t\/\/ if ratio == 0.0 || ratio > 0.5 {\n\tfmt.Printf(\"Releasing Allocator Size: %s\\n\",\n\t\thumanize.IBytes(uint64(alloc)))\n\t\/\/ }\n\n\tallocsMu.Lock()\n\tdelete(allocs, a.Ref)\n\tallocsMu.Unlock()\n}\n\nconst maxAlloc = 1 << 30\n\nfunc (a *Allocator) MaxAlloc() int {\n\treturn maxAlloc\n}\n\nconst nodeAlign = int(unsafe.Sizeof(uint64(0))) - 1\n\nfunc (a *Allocator) AllocateAligned(sz int) []byte {\n\ttsz := sz + nodeAlign\n\tout := a.Allocate(tsz)\n\t\/\/ TODO: We should align based on out's address.\n\taligned := (a.curIdx - tsz + nodeAlign) & ^nodeAlign\n\n\tstart := tsz - (a.curIdx - aligned)\n\treturn out[start : start+sz]\n}\n\nfunc (a *Allocator) Copy(buf []byte) []byte {\n\tif a == nil {\n\t\treturn append([]byte{}, buf...)\n\t}\n\tout := a.Allocate(len(buf))\n\tcopy(out, buf)\n\treturn out\n}\n\nfunc (a *Allocator) addBufferWithMinSize(sz int) {\n\tfor {\n\t\ta.pageSize *= 2 \/\/ Do multiply by 2 here.\n\t\tif a.pageSize >= sz {\n\t\t\tbreak\n\t\t}\n\t}\n\tif a.pageSize > maxAlloc {\n\t\ta.pageSize = maxAlloc\n\t}\n\n\tbuf := Calloc(a.pageSize)\n\ta.buffers = append(a.buffers, buf)\n}\n\n\/\/ Allocate would allocate a byte slice of length sz. It is safe to use this memory to unsafe cast\n\/\/ to Go structs.\nfunc (a *Allocator) Allocate(sz int) []byte {\n\tif a == nil {\n\t\treturn make([]byte, sz)\n\t}\n\ta.Lock()\n\tdefer a.Unlock()\n\n\tif len(a.buffers) == 0 {\n\t\tbuf := Calloc(a.pageSize)\n\t\ta.buffers = append(a.buffers, buf)\n\t}\n\tif sz >= maxAlloc {\n\t\tpanic(fmt.Sprintf(\"Allocate call exceeds max allocation possible.\"+\n\t\t\t\" Requested: %d. Max Allowed: %d\\n\", sz, maxAlloc))\n\t}\n\t\/\/ Turning this off for now. This slows down allocations somewhat. Even though it shows a 50%\n\t\/\/ reuse ratio, we get a better bang for the buck by just reusing an entire Allocator for the\n\t\/\/ next cycle.\n\t\/\/\n\t\/\/ if out := a.fromFreeList(sz); out != nil {\n\t\/\/ \ta.reused += len(out)\n\t\/\/ \treturn out\n\t\/\/ }\n\tcb := a.buffers[a.curBuf]\n\tfor len(cb) < a.curIdx+sz {\n\t\ta.curBuf++\n\t\ta.curIdx = 0\n\t\tif a.curBuf == len(a.buffers) {\n\t\t\ta.addBufferWithMinSize(sz)\n\t\t}\n\t\tcb = a.buffers[a.curBuf]\n\t}\n\n\tslice := cb[a.curIdx : a.curIdx+sz]\n\ta.curIdx += sz\n\ta.size += uint64(sz)\n\treturn slice\n}\n<|endoftext|>"}
{"text":"<commit_before>package setup\n\nimport (\n\t\"github.com\/mholt\/caddy\/middleware\/fastcgi\"\n\t\"testing\"\n)\n\nfunc TestFastCGI(t *testing.T) {\n\n\tc := NewTestController(`fastcgi \/ 127.0.0.1:9000`)\n\n\tmid, err := FastCGI(c)\n\n\tif err != nil {\n\t\tt.Errorf(\"Expected no errors, got: %v\", err)\n\t}\n\n\tif mid == nil {\n\t\tt.Fatal(\"Expected middleware, was nil instead\")\n\t}\n\n\thandler := mid(EmptyNext)\n\tmyHandler, ok := handler.(fastcgi.Handler)\n\n\tif !ok {\n\t\tt.Fatalf(\"Expected handler to be type , got: %#v\", handler)\n\t}\n\n\tif myHandler.Rules[0].Path != \"\/\" {\n\t\tt.Errorf(\"Expected \/ as the Path\")\n\t}\n\tif myHandler.Rules[0].Address != \"127.0.0.1:9000\" {\n\t\tt.Errorf(\"Expected 127.0.0.1:9000 as the Address\")\n\t}\n\n}\n<commit_msg>Complete Test set  For config\/setup\/fastcgi.go<commit_after>package setup\n\nimport (\n\t\"fmt\"\n\t\"github.com\/mholt\/caddy\/middleware\/fastcgi\"\n\t\"testing\"\n)\n\nfunc TestFastCGI(t *testing.T) {\n\n\tc := NewTestController(`fastcgi \/ 127.0.0.1:9000`)\n\n\tmid, err := FastCGI(c)\n\n\tif err != nil {\n\t\tt.Errorf(\"Expected no errors, got: %v\", err)\n\t}\n\n\tif mid == nil {\n\t\tt.Fatal(\"Expected middleware, was nil instead\")\n\t}\n\n\thandler := mid(EmptyNext)\n\tmyHandler, ok := handler.(fastcgi.Handler)\n\n\tif !ok {\n\t\tt.Fatalf(\"Expected handler to be type , got: %#v\", handler)\n\t}\n\n\tif myHandler.Rules[0].Path != \"\/\" {\n\t\tt.Errorf(\"Expected \/ as the Path\")\n\t}\n\tif myHandler.Rules[0].Address != \"127.0.0.1:9000\" {\n\t\tt.Errorf(\"Expected 127.0.0.1:9000 as the Address\")\n\t}\n\n}\n\nfunc TestFastcgiParse(t *testing.T) {\n\ttests := []struct {\n\t\tinputFastcgiConfig    string\n\t\tshouldErr             bool\n\t\texpectedFastcgiConfig []fastcgi.Rule\n\t}{\n\n\t\t{`fastcgi \/blog 127.0.0.1:9000 php`,\n\t\t\tfalse, []fastcgi.Rule{{\n\t\t\t\tPath:       \"\/blog\",\n\t\t\t\tAddress:    \"127.0.0.1:9000\",\n\t\t\t\tExt:        \".php\",\n\t\t\t\tSplitPath:  \".php\",\n\t\t\t\tIndexFiles: []string{\"index.php\"},\n\t\t\t}}},\n\t}\n\tfor i, test := range tests {\n\t\tc := NewTestController(test.inputFastcgiConfig)\n\t\tactualFastcgiConfigs, err := fastcgiParse(c)\n\n\t\tif err == nil && test.shouldErr {\n\t\t\tt.Errorf(\"Test %d didn't error, but it should have\", i)\n\t\t} else if err != nil && !test.shouldErr {\n\t\t\tt.Errorf(\"Test %d errored, but it shouldn't have; got '%v'\", i, err)\n\t\t}\n\t\tif len(actualFastcgiConfigs) != len(test.expectedFastcgiConfig) {\n\t\t\tt.Fatalf(\"Test %d expected %d no of FastCGI configs, but got %d \",\n\t\t\t\ti, len(test.expectedFastcgiConfig), len(actualFastcgiConfigs))\n\t\t}\n\t\tfor j, actualFastcgiConfig := range actualFastcgiConfigs {\n\n\t\t\tif actualFastcgiConfig.Path != test.expectedFastcgiConfig[j].Path {\n\t\t\t\tt.Errorf(\"Test %d expected %dth FastCGI Path to be  %s  , but got %s\",\n\t\t\t\t\ti, j, test.expectedFastcgiConfig[j].Path, actualFastcgiConfig.Path)\n\t\t\t}\n\n\t\t\tif actualFastcgiConfig.Address != test.expectedFastcgiConfig[j].Address {\n\t\t\t\tt.Errorf(\"Test %d expected %dth FastCGI Address to be  %s  , but got %s\",\n\t\t\t\t\ti, j, test.expectedFastcgiConfig[j].Address, actualFastcgiConfig.Address)\n\t\t\t}\n\n\t\t\tif actualFastcgiConfig.Ext != test.expectedFastcgiConfig[j].Ext {\n\t\t\t\tt.Errorf(\"Test %d expected %dth FastCGI Ext to be  %s  , but got %s\",\n\t\t\t\t\ti, j, test.expectedFastcgiConfig[j].Ext, actualFastcgiConfig.Ext)\n\t\t\t}\n\n\t\t\tif actualFastcgiConfig.SplitPath != test.expectedFastcgiConfig[j].SplitPath {\n\t\t\t\tt.Errorf(\"Test %d expected %dth FastCGI SplitPath to be  %s  , but got %s\",\n\t\t\t\t\ti, j, test.expectedFastcgiConfig[j].SplitPath, actualFastcgiConfig.SplitPath)\n\t\t\t}\n\n\t\t\tif fmt.Sprint(actualFastcgiConfig.IndexFiles) != fmt.Sprint(test.expectedFastcgiConfig[j].IndexFiles) {\n\t\t\t\tt.Errorf(\"Test %d expected %dth FastCGI IndexFiles to be  %s  , but got %s\",\n\t\t\t\t\ti, j, test.expectedFastcgiConfig[j].IndexFiles, actualFastcgiConfig.IndexFiles)\n\t\t\t}\n\t\t}\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package csv\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestMarshalNested(t *testing.T) {\n\ttype Nested struct {\n\t\tV1 string `csv:\"v1\"`\n\t\tA1 int    `csv:\"-\"`\n\t\tA2 int\n\t\tS1 struct {\n\t\t\tV2 string `csv:\"v2\"`\n\t\t\tS2 struct {\n\t\t\t\tV3 int `csv:\"v3\"`\n\t\t\t}\n\t\t}\n\t}\n\n\tvar v Nested\n\tv.V1 = \"a\"\n\tv.S1.V2 = \"b\"\n\tv.S1.S2.V3 = 1\n\tbuf, err := Marshal(v)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\texpected := \"a,b,1\\n\"\n\tactual := string(buf)\n\tif actual != expected {\n\t\tt.Fatalf(\"expected %s, got %s\", expected, actual)\n\t}\n}\n\ntype iter struct {\n\ta     reflect.Value\n\ti     int\n\tlevel int\n}\n\nfunc newIter(v reflect.Value, path [][]string, level int) *iter {\n\treturn &iter{\n\t\ta:     findFieldByPath(v, path[level]),\n\t\tlevel: level,\n\t}\n}\n\nfunc (it *iter) New() reflect.Value {\n\treturn reflect.New(it.a.Type().Elem()).Elem()\n}\n\nfunc (it *iter) Next(v reflect.Value) bool {\n\tif it.i >= it.a.Len() {\n\t\treturn false\n\t}\n\tv.Set(it.a.Index(it.i))\n\tit.i++\n\treturn it.i <= it.a.Len()\n}\n\nfunc findFieldByPath(v reflect.Value, path []string) reflect.Value {\n\tfor _, name := range path {\n\t\tv = v.FieldByName(name)\n\t}\n\treturn v\n}\n\nfunc unmarshal(v reflect.Value, delimiter rune, tag string) ([]byte, error) {\n\tw := new(bytes.Buffer)\n\tenc := Encoder{w: w, Delimiter: ',', Tag: \"csv2\"}\n\tif err := enc.encode(v); err != nil {\n\t\treturn nil, err\n\t}\n\treturn w.Bytes(), nil\n}\n\nfunc TestMarshalSlice(t *testing.T) {\n\ttype (\n\t\tLeaf struct {\n\t\t\tV1 int `csv2:\"v1\"`\n\t\t\tV2 int `csv2:\"v2\"`\n\t\t}\n\t\tLevel2 struct {\n\t\t\tV3   int `csv2:\"v3\"`\n\t\t\tLeaf []Leaf\n\t\t\tV4   int `csv2:\"v4\"`\n\t\t}\n\t\tLevel1 struct {\n\t\t\tLevel2 []Level2\n\t\t}\n\t\tStruct struct {\n\t\t\tV1     string `csv:\"v1\" csv2:\"v1\"`\n\t\t\tLevel1 Level1 `csv:\"-\"`\n\t\t\tV3     string `csv:\"v3\" csv2:\"v3\"`\n\t\t\tV4     string `csv:\"v4\"`\n\t\t}\n\t)\n\tst := Struct{\n\t\tV1: \"a\",\n\t\tLevel1: Level1{[]Level2{\n\t\t\t{1, []Leaf{{3, 4}, {5, 6}}, 2},\n\t\t}},\n\t\tV3: \"b\",\n\t\tV4: \"c\",\n\t}\n\n\tpath := [][]string{[]string{\"Level1\", \"Level2\"}, []string{\"Leaf\"}}\n\tw := new(bytes.Buffer)\n\tif err := expand(w, reflect.ValueOf(st), path); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tactual := w.String()\n\n\texpected := \"a,b,1,2,3,4\\na,b,1,2,5,6\\n\"\n\tif actual != expected {\n\t\tt.Fatalf(\"expected %s, got %s\", expected, actual)\n\t}\n\n}\n\nfunc expand(w io.Writer, v reflect.Value, path [][]string) error {\n\tvar buf [][]byte\n\tfields, err := unmarshal(v, ',', \"csv2\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tits := []*iter{newIter(v, path, 0)}\n\tbuf = append(buf, fields)\n\tfor {\n\t\tit := its[len(its)-1]\n\t\tv = it.New()\n\t\tif !it.Next(v) {\n\t\t\tbuf = buf[:len(buf)-1]\n\t\t\tits = its[:len(its)-1]\n\t\t\tbreak\n\t\t}\n\t\tfields, err := unmarshal(v, ',', \"csv2\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif it.level+1 < len(path) {\n\t\t\tits = append(its, newIter(v, path, it.level+1))\n\t\t\tbuf = append(buf, fields)\n\t\t} else {\n\t\t\tbuf = append(buf, fields)\n\t\t\tif _, err := w.Write(append(bytes.Join(buf, []byte{','}), '\\n')); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbuf = buf[:len(buf)-1]\n\t\t}\n\t}\n\treturn nil\n}\n\ntype Types struct {\n\tV1 string    `csv:\"v1\"`\n\tV2 int       `csv:\"v2\"`\n\tV3 float64   `csv:\"v3\"`\n\tV4 time.Time `csv:\"v4\"`\n}\n<commit_msg>refactor<commit_after>package csv\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestMarshalNested(t *testing.T) {\n\ttype Nested struct {\n\t\tV1 string `csv:\"v1\"`\n\t\tA1 int    `csv:\"-\"`\n\t\tA2 int\n\t\tS1 struct {\n\t\t\tV2 string `csv:\"v2\"`\n\t\t\tS2 struct {\n\t\t\t\tV3 int `csv:\"v3\"`\n\t\t\t}\n\t\t}\n\t}\n\n\tvar v Nested\n\tv.V1 = \"a\"\n\tv.S1.V2 = \"b\"\n\tv.S1.S2.V3 = 1\n\tbuf, err := Marshal(v)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\texpected := \"a,b,1\\n\"\n\tactual := string(buf)\n\tif actual != expected {\n\t\tt.Fatalf(\"expected %s, got %s\", expected, actual)\n\t}\n}\n\ntype iter struct {\n\ta     reflect.Value\n\ti     int\n\tlevel int\n}\n\nfunc newIter(v reflect.Value, path [][]string, level int) *iter {\n\treturn &iter{\n\t\ta:     findFieldByPath(v, path[level]),\n\t\tlevel: level,\n\t}\n}\n\nfunc (it *iter) New() reflect.Value {\n\treturn reflect.New(it.a.Type().Elem()).Elem()\n}\n\nfunc (it *iter) Next(v reflect.Value) bool {\n\tif it.i >= it.a.Len() {\n\t\treturn false\n\t}\n\tv.Set(it.a.Index(it.i))\n\tit.i++\n\treturn it.i <= it.a.Len()\n}\n\nfunc findFieldByPath(v reflect.Value, path []string) reflect.Value {\n\tfor _, name := range path {\n\t\tv = v.FieldByName(name)\n\t}\n\treturn v\n}\n\nfunc unmarshal(v reflect.Value, delimiter rune, tag string) ([]byte, error) {\n\tw := new(bytes.Buffer)\n\tenc := Encoder{w: w, Delimiter: ',', Tag: \"csv2\"}\n\tif err := enc.encode(v); err != nil {\n\t\treturn nil, err\n\t}\n\treturn w.Bytes(), nil\n}\n\nfunc TestMarshalSlice(t *testing.T) {\n\ttype (\n\t\tLeaf struct {\n\t\t\tV1 int `csv2:\"v1\"`\n\t\t\tV2 int `csv2:\"v2\"`\n\t\t}\n\t\tLevel2 struct {\n\t\t\tV3   int `csv2:\"v3\"`\n\t\t\tLeaf []Leaf\n\t\t\tV4   int `csv2:\"v4\"`\n\t\t}\n\t\tLevel1 struct {\n\t\t\tLevel2 []Level2\n\t\t}\n\t\tStruct struct {\n\t\t\tV1     string `csv:\"v1\" csv2:\"v1\"`\n\t\t\tLevel1 Level1 `csv:\"-\"`\n\t\t\tV3     string `csv:\"v3\" csv2:\"v3\"`\n\t\t\tV4     string `csv:\"v4\"`\n\t\t}\n\t)\n\tst := Struct{\n\t\tV1: \"a\",\n\t\tLevel1: Level1{[]Level2{\n\t\t\t{1, []Leaf{{3, 4}, {5, 6}}, 2},\n\t\t}},\n\t\tV3: \"b\",\n\t\tV4: \"c\",\n\t}\n\n\tpath := [][]string{[]string{\"Level1\", \"Level2\"}, []string{\"Leaf\"}}\n\tw := new(bytes.Buffer)\n\tif err := expand(w, reflect.ValueOf(st), path); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tactual := w.String()\n\n\texpected := \"a,b,1,2,3,4\\na,b,1,2,5,6\\n\"\n\tif actual != expected {\n\t\tt.Fatalf(\"expected %s, got %s\", expected, actual)\n\t}\n\n}\n\nfunc expand(w io.Writer, v reflect.Value, path [][]string) error {\n\tfields, err := unmarshal(v, ',', \"csv2\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tits := []*iter{newIter(v, path, 0)}\n\tbuf := [][]byte{fields}\n\tfor {\n\t\tit := its[len(its)-1]\n\t\tv = it.New()\n\t\tif !it.Next(v) {\n\t\t\tbuf = buf[:len(buf)-1]\n\t\t\tits = its[:len(its)-1]\n\t\t\tbreak\n\t\t}\n\t\tfields, err := unmarshal(v, ',', \"csv2\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif it.level+1 < len(path) {\n\t\t\tits = append(its, newIter(v, path, it.level+1))\n\t\t\tbuf = append(buf, fields)\n\t\t} else {\n\t\t\tbuf = append(buf, fields)\n\t\t\tif _, err := w.Write(append(bytes.Join(buf, []byte{','}), '\\n')); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tbuf = buf[:len(buf)-1]\n\t\t}\n\t}\n\treturn nil\n}\n\ntype Types struct {\n\tV1 string    `csv:\"v1\"`\n\tV2 int       `csv:\"v2\"`\n\tV3 float64   `csv:\"v3\"`\n\tV4 time.Time `csv:\"v4\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package gitlab\n\nimport \"fmt\"\n\n\/\/ EpicIssuesService handles communication with the epic issue related methods\n\/\/ of the GitLab API.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epic_issues.html\ntype EpicIssuesService struct {\n\tclient *Client\n}\n\n\/\/ EpicIssueAssignment contains both the Epic and Issue objects returned from\n\/\/ Gitlab w\/ the assignment ID\ntype EpicIssueAssignment struct {\n\tID    int    `json:\"id\"`\n\tEpic  *Epic  `json:\"epic\"`\n\tIssue *Issue `json:\"issue\"`\n}\n\n\/\/ ListEpicIssues get a list of epic issues.\n\/\/\n\/\/ Gitlab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ee\/api\/epic_issues.html#list-issues-for-an-epic\nfunc (s *EpicIssuesService) ListEpicIssues(gid interface{}, epic int, opt *ListOptions, options ...RequestOptionFunc) ([]*Issue, *Response, error) {\n\tgroup, err := parseID(gid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"groups\/%s\/epics\/%d\/issues\", pathEscape(group), epic)\n\n\treq, err := s.client.NewRequest(\"GET\", u, opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar issues []*Issue\n\tresp, err := s.client.Do(req, &issues)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn issues, resp, err\n}\n\n\/\/ AssignEpicIssue assigns an existing issue to an Epic.\n\/\/\n\/\/ Gitlab API Docs:\n\/\/ https:\/\/docs.gitlab.com\/ee\/api\/epic_issues.html#assign-an-issue-to-the-epic\nfunc (s *EpicIssuesService) AssignEpicIssue(gid interface{}, epic, issue int, options ...RequestOptionFunc) (*EpicIssueAssignment, *Response, error) {\n\tgroup, err := parseID(gid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tu := fmt.Sprintf(\"groups\/%s\/epics\/%d\/issues\/%d\", pathEscape(group), epic, issue)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar a *EpicIssueAssignment\n\n\tresp, err := s.client.Do(req, &a)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn a, resp, err\n}\n\n\/\/ RemoveEpicIssue removes an issue from an Epic.\n\/\/\n\/\/ Gitlab API Docs:\n\/\/ https:\/\/docs.gitlab.com\/ee\/api\/epic_issues.html#remove-an-issue-from-the-epic\nfunc (s *EpicIssuesService) RemoveEpicIssue(gid interface{}, epic int, epicIssue int, options ...RequestOptionFunc) (*EpicIssueAssignment, *Response, error) {\n\tgroup, err := parseID(gid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tu := fmt.Sprintf(\"groups\/%s\/epics\/%d\/issues\/%d\", pathEscape(group), epic, epicIssue)\n\n\treq, err := s.client.NewRequest(\"DELETE\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar a *EpicIssueAssignment\n\n\tresp, err := s.client.Do(req, &a)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn a, resp, err\n}\n\n\/\/ UpdateEpicIsssueAssignmentOptions describes options to move issues within an epic\ntype UpdateEpicIsssueAssignmentOptions struct {\n\t*ListOptions\n\tMoveBeforeID int `json:\"move_before_id\"`\n\tMoveAfterID  int `json:\"move_after_id\"`\n}\n\n\/\/ UpdateEpicIssueAssignment moves an issue before or after another issue in an\n\/\/ epic issue list.\n\/\/\n\/\/ Gitlab API Docs:\n\/\/ https:\/\/docs.gitlab.com\/ee\/api\/epic_issues.html#update-epic---issue-association\nfunc (s *EpicIssuesService) UpdateEpicIssueAssignment(gid interface{}, epic int, epicIssue int, opt *UpdateEpicIsssueAssignmentOptions, options ...RequestOptionFunc) ([]*Issue, *Response, error) {\n\tgroup, err := parseID(gid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"groups\/%s\/epics\/%d\/issues\/%d\", pathEscape(group), epic, epicIssue)\n\n\treq, err := s.client.NewRequest(\"PUT\", u, opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar issues []*Issue\n\tresp, err := s.client.Do(req, &issues)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn issues, resp, err\n}\n<commit_msg>remove excess newline<commit_after>package gitlab\n\nimport \"fmt\"\n\n\/\/ EpicIssuesService handles communication with the epic issue related methods\n\/\/ of the GitLab API.\n\/\/\n\/\/ GitLab API docs: https:\/\/docs.gitlab.com\/ee\/api\/epic_issues.html\ntype EpicIssuesService struct {\n\tclient *Client\n}\n\n\/\/ EpicIssueAssignment contains both the Epic and Issue objects returned from\n\/\/ Gitlab w\/ the assignment ID\ntype EpicIssueAssignment struct {\n\tID    int    `json:\"id\"`\n\tEpic  *Epic  `json:\"epic\"`\n\tIssue *Issue `json:\"issue\"`\n}\n\n\/\/ ListEpicIssues get a list of epic issues.\n\/\/\n\/\/ Gitlab API docs:\n\/\/ https:\/\/docs.gitlab.com\/ee\/api\/epic_issues.html#list-issues-for-an-epic\nfunc (s *EpicIssuesService) ListEpicIssues(gid interface{}, epic int, opt *ListOptions, options ...RequestOptionFunc) ([]*Issue, *Response, error) {\n\tgroup, err := parseID(gid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"groups\/%s\/epics\/%d\/issues\", pathEscape(group), epic)\n\n\treq, err := s.client.NewRequest(\"GET\", u, opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar issues []*Issue\n\tresp, err := s.client.Do(req, &issues)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn issues, resp, err\n}\n\n\/\/ AssignEpicIssue assigns an existing issue to an Epic.\n\/\/\n\/\/ Gitlab API Docs:\n\/\/ https:\/\/docs.gitlab.com\/ee\/api\/epic_issues.html#assign-an-issue-to-the-epic\nfunc (s *EpicIssuesService) AssignEpicIssue(gid interface{}, epic, issue int, options ...RequestOptionFunc) (*EpicIssueAssignment, *Response, error) {\n\tgroup, err := parseID(gid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"groups\/%s\/epics\/%d\/issues\/%d\", pathEscape(group), epic, issue)\n\n\treq, err := s.client.NewRequest(\"POST\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar a *EpicIssueAssignment\n\n\tresp, err := s.client.Do(req, &a)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn a, resp, err\n}\n\n\/\/ RemoveEpicIssue removes an issue from an Epic.\n\/\/\n\/\/ Gitlab API Docs:\n\/\/ https:\/\/docs.gitlab.com\/ee\/api\/epic_issues.html#remove-an-issue-from-the-epic\nfunc (s *EpicIssuesService) RemoveEpicIssue(gid interface{}, epic int, epicIssue int, options ...RequestOptionFunc) (*EpicIssueAssignment, *Response, error) {\n\tgroup, err := parseID(gid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tu := fmt.Sprintf(\"groups\/%s\/epics\/%d\/issues\/%d\", pathEscape(group), epic, epicIssue)\n\n\treq, err := s.client.NewRequest(\"DELETE\", u, nil, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar a *EpicIssueAssignment\n\n\tresp, err := s.client.Do(req, &a)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn a, resp, err\n}\n\n\/\/ UpdateEpicIsssueAssignmentOptions describes options to move issues within an epic\ntype UpdateEpicIsssueAssignmentOptions struct {\n\t*ListOptions\n\tMoveBeforeID int `json:\"move_before_id\"`\n\tMoveAfterID  int `json:\"move_after_id\"`\n}\n\n\/\/ UpdateEpicIssueAssignment moves an issue before or after another issue in an\n\/\/ epic issue list.\n\/\/\n\/\/ Gitlab API Docs:\n\/\/ https:\/\/docs.gitlab.com\/ee\/api\/epic_issues.html#update-epic---issue-association\nfunc (s *EpicIssuesService) UpdateEpicIssueAssignment(gid interface{}, epic int, epicIssue int, opt *UpdateEpicIsssueAssignmentOptions, options ...RequestOptionFunc) ([]*Issue, *Response, error) {\n\tgroup, err := parseID(gid)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tu := fmt.Sprintf(\"groups\/%s\/epics\/%d\/issues\/%d\", pathEscape(group), epic, epicIssue)\n\n\treq, err := s.client.NewRequest(\"PUT\", u, opt, options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar issues []*Issue\n\tresp, err := s.client.Do(req, &issues)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn issues, resp, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage twenty48\n\nimport (\n\t\"fmt\"\n\t\"math\/rand\"\n\n\t\"github.com\/hajimehoshi\/ebiten\"\n\t\"github.com\/hajimehoshi\/ebiten\/ebitenutil\"\n)\n\ntype Board struct {\n\tsize  int\n\ttiles map[*Tile]struct{}\n}\n\nfunc NewBoard(size int) *Board {\n\tb := &Board{\n\t\tsize:  size,\n\t\ttiles: map[*Tile]struct{}{},\n\t}\n\tfor i := 0; i < 2; i++ {\n\t\tb.addRandomTile()\n\t}\n\treturn b\n}\n\nfunc (b *Board) addRandomTile() bool {\n\tcells := make([]bool, b.size*b.size)\n\tfor t := range b.tiles {\n\t\ti := t.x + t.y*b.size\n\t\tcells[i] = true\n\t}\n\tavailableCells := []int{}\n\tfor i, b := range cells {\n\t\tif b {\n\t\t\tcontinue\n\t\t}\n\t\tavailableCells = append(availableCells, i)\n\t}\n\tif len(availableCells) == 0 {\n\t\treturn false\n\t}\n\tc := availableCells[rand.Intn(len(availableCells))]\n\tv := 2\n\tif rand.Intn(10) == 0 {\n\t\tv = 4\n\t}\n\tx := c % b.size\n\ty := c \/ b.size\n\tt := NewTile(v, x, y)\n\tb.tiles[t] = struct{}{}\n\treturn true\n}\n\nfunc (b *Board) Move(dir Dir) {\n\tb.addRandomTile()\n}\n\nfunc (b *Board) Draw(screen *ebiten.Image) error {\n\tposToTile := map[int]*Tile{}\n\tfor t := range b.tiles {\n\t\ti := t.x + t.y*b.size\n\t\tposToTile[i] = t\n\t}\n\tstr := \"\"\n\tfor j := 0; j < b.size; j++ {\n\t\tfor i := 0; i < b.size; i++ {\n\t\t\tt := posToTile[i+j*b.size]\n\t\t\tif t != nil {\n\t\t\t\tstr += fmt.Sprintf(\"[%4d]\", t.value)\n\t\t\t} else {\n\t\t\t\tstr += \"[    ]\"\n\t\t\t}\n\t\t}\n\t\tstr += \"\\n\"\n\t}\n\tebitenutil.DebugPrint(screen, str)\n\treturn nil\n}\n<commit_msg>examples\/2048: Implement the rule<commit_after>\/\/ Copyright 2016 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage twenty48\n\nimport (\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sort\"\n\n\t\"github.com\/hajimehoshi\/ebiten\"\n\t\"github.com\/hajimehoshi\/ebiten\/ebitenutil\"\n)\n\ntype Board struct {\n\tsize  int\n\ttiles map[*Tile]struct{}\n}\n\nfunc NewBoard(size int) *Board {\n\tb := &Board{\n\t\tsize:  size,\n\t\ttiles: map[*Tile]struct{}{},\n\t}\n\tfor i := 0; i < 2; i++ {\n\t\tb.addRandomTile()\n\t}\n\treturn b\n}\n\nfunc (b *Board) addRandomTile() bool {\n\tcells := make([]bool, b.size*b.size)\n\tfor t := range b.tiles {\n\t\ti := t.x + t.y*b.size\n\t\tcells[i] = true\n\t}\n\tavailableCells := []int{}\n\tfor i, b := range cells {\n\t\tif b {\n\t\t\tcontinue\n\t\t}\n\t\tavailableCells = append(availableCells, i)\n\t}\n\tif len(availableCells) == 0 {\n\t\treturn false\n\t}\n\tc := availableCells[rand.Intn(len(availableCells))]\n\tv := 2\n\tif rand.Intn(10) == 0 {\n\t\tv = 4\n\t}\n\tx := c % b.size\n\ty := c \/ b.size\n\tt := NewTile(v, x, y)\n\tb.tiles[t] = struct{}{}\n\treturn true\n}\n\nfunc tileAt(tiles map[*Tile]struct{}, x, y int) *Tile {\n\tfor t := range tiles {\n\t\tif t.x == x && t.y == y {\n\t\t\treturn t\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (b *Board) tileAt(x, y int) *Tile {\n\treturn tileAt(b.tiles, x, y)\n}\n\nfunc (b *Board) Move(dir Dir) {\n\tvx, vy := dir.Vector()\n\ttx := []int{}\n\tty := []int{}\n\tfor i := 0; i < b.size; i++ {\n\t\ttx = append(tx, i)\n\t\tty = append(ty, i)\n\t}\n\tif vx > 0 {\n\t\tsort.Sort(sort.Reverse(sort.IntSlice(tx)))\n\t}\n\tif vy > 0 {\n\t\tsort.Sort(sort.Reverse(sort.IntSlice(ty)))\n\t}\n\tnextTiles := map[*Tile]struct{}{}\n\tmerged := map[*Tile]bool{}\n\tfor _, j := range ty {\n\t\tfor _, i := range tx {\n\t\t\tt := b.tileAt(i, j)\n\t\t\tif t == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tii := i\n\t\t\tjj := j\n\t\t\tfor {\n\t\t\t\tni := ii + vx\n\t\t\t\tnj := jj + vy\n\t\t\t\tif ni < 0 || ni >= b.size || nj < 0 || nj >= b.size {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttt := b.tileAt(ni, nj)\n\t\t\t\tif tt == nil {\n\t\t\t\t\tii = ni\n\t\t\t\t\tjj = nj\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tnt := tileAt(nextTiles, ni, nj)\n\t\t\t\tif t.value == tt.value && (nt == nil || !merged[nt]) {\n\t\t\t\t\tii = ni\n\t\t\t\t\tjj = nj\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif tt := b.tileAt(ii, jj); tt != t && tt != nil {\n\t\t\t\tt.value += tt.value\n\t\t\t\tmerged[t] = true\n\t\t\t\tdelete(nextTiles, tt)\n\t\t\t}\n\t\t\tt.x = ii\n\t\t\tt.y = jj\n\t\t\tnextTiles[t] = struct{}{}\n\t\t}\n\t}\n\tb.tiles = nextTiles\n\tb.addRandomTile()\n}\n\nfunc (b *Board) Draw(screen *ebiten.Image) error {\n\tstr := \"\"\n\tfor j := 0; j < b.size; j++ {\n\t\tfor i := 0; i < b.size; i++ {\n\t\t\tt := b.tileAt(i, j)\n\t\t\tif t != nil {\n\t\t\t\tstr += fmt.Sprintf(\"[%4d]\", t.value)\n\t\t\t} else {\n\t\t\t\tstr += \"[    ]\"\n\t\t\t}\n\t\t}\n\t\tstr += \"\\n\"\n\t}\n\tebitenutil.DebugPrint(screen, str)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ syncwatcher.go\npackage main\n\nimport (\n  \"code.google.com\/p\/go.exp\/fsnotify\"\n  \"fmt\"\n  \"os\"\n  \"bufio\"\n  \"io\/ioutil\"\n  \"net\/http\"\n  \"encoding\/json\"\n  \"log\"\n  \"flag\"\n  \"net\/url\"\n  \"strings\"\n)\n\n\ntype Configuration struct {\n  Version      int\n  Repositories []RepositoryConfiguration\n}\n\ntype RepositoryConfiguration struct {\n  ID              string\n  Directory       string\n  ReadOnly        bool\n  RescanIntervalS int\n}\n\n\n\/\/ HTTP Parameters\nvar (\n  target    string\n  authUser  string\n  authPass  string\n  csrfToken string\n  csrfFile  string\n  apiKey    string\n)\n\n\nfunc main() {\n  flag.StringVar(&target, \"target\", \"localhost:8080\", \"Target\")\n  flag.StringVar(&authUser, \"user\", \"\", \"Username\")\n  flag.StringVar(&authPass, \"pass\", \"\", \"Password\")\n  flag.StringVar(&csrfFile, \"csrf\", \"\", \"CSRF token file\")\n  flag.StringVar(&apiKey, \"api\", \"\", \"API key\")\n  flag.Parse()\n\n  if len(csrfFile) > 0 {\n    fd, err := os.Open(csrfFile)\n    if err != nil {\n      log.Fatal(err)\n    }\n    s := bufio.NewScanner(fd)\n    for s.Scan() {\n      csrfToken = s.Text()\n    }\n    fd.Close()\n  }\n\n  repos := getRepos()\n  for i := range repos {\n    repo := repos[i]\n    go watchRepo(repo.ID, repo.Directory)\n  }\n\n  println(\"Press enter to exit\")\n  fmt.Scanln();\n}\n\nfunc getRepos() []RepositoryConfiguration {\n  r, err := http.NewRequest(\"GET\", \"http:\/\/\"+target+\"\/rest\/config\", nil)\n  if err != nil {\n    log.Fatal(err)\n  }\n  if len(csrfToken) > 0 {\n    r.Header.Set(\"X-CSRF-Token\", csrfToken)\n  }\n  if len(authUser) > 0 {\n    r.SetBasicAuth(authUser, authPass)\n  }\n  if len(apiKey) > 0 {\n    r.Header.Set(\"X-API-Key\", apiKey)\n  }\n  res, err := http.DefaultClient.Do(r)\n  if err != nil {\n    log.Fatal(err)\n  }\n  defer res.Body.Close()\n  if res.StatusCode != 200 {\n    log.Fatalf(\"Status %d != 200 for GET\", res.StatusCode)\n  }\n  bs, err := ioutil.ReadAll(res.Body)\n  if err != nil {\n    log.Fatal(err)\n  }\n  var cfg Configuration\n  err = json.Unmarshal(bs, &cfg)\n  if err != nil {\n    log.Fatal(err)\n  }\n  return cfg.Repositories\n}\n\nfunc watchRepo(repo string, directory string) {\n  sw, err := NewSyncWatcher()\n  if sw == nil || err != nil {\n    log.Fatal(err)\n  }\n  defer sw.Close()\n  err = sw.Watch(directory)\n  if err != nil {\n    log.Fatal(err)\n  }\n  log.Println(\"Watching \"+repo+\": \"+directory)\n  for {\n    ev, ok := waitForEvent(sw)\n    if ok && ev != nil {\n      sub := strings.TrimPrefix(ev.Name, directory)\n      sub = strings.TrimPrefix(sub, string(os.PathSeparator))\n      informChange(repo, sub)\n    }\n  }\n}\n\nfunc waitForEvent(sw *SyncWatcher) (ev *fsnotify.FileEvent, ok bool) {\n  select {\n  case ev, ok = <-sw.Event:\n    if !ok {\n      log.Fatal(\"Event: channel closed\")\n    }\n  case err, eok := <-sw.Error:\n    log.Fatal(err, eok)\n  }\n  return\n}\n\nfunc informChange(repo string, sub string) {\n  data := url.Values {}\n  data.Set(\"repo\", repo)\n  data.Set(\"sub\", sub)\n  r, err := http.NewRequest(\"POST\", \"http:\/\/\"+target+\"\/rest\/scan?\"+data.Encode(), nil)\n  if err != nil {\n    log.Fatal(err)\n  }\n  if len(csrfToken) > 0 {\n    r.Header.Set(\"X-CSRF-Token\", csrfToken)\n  }\n  if len(authUser) > 0 {\n    r.SetBasicAuth(authUser, authPass)\n  }\n  if len(apiKey) > 0 {\n    r.Header.Set(\"X-API-Key\", apiKey)\n  }\n  res, err := http.DefaultClient.Do(r)\n  if err != nil {\n    log.Fatal(err)\n  }\n  defer res.Body.Close()\n  if res.StatusCode != 200 {\n    log.Fatalf(\"Status %d != 200 for POST\", res.StatusCode)\n  } else {\n    log.Println(\"Syncthing will index change in \"+repo+\": \"+sub)\n  }\n}\n<commit_msg>^C to exit<commit_after>\/\/ syncwatcher.go\npackage main\n\nimport (\n  \"code.google.com\/p\/go.exp\/fsnotify\"\n  \"os\"\n  \"bufio\"\n  \"io\/ioutil\"\n  \"net\/http\"\n  \"encoding\/json\"\n  \"log\"\n  \"flag\"\n  \"net\/url\"\n  \"strings\"\n)\n\n\ntype Configuration struct {\n  Version      int\n  Repositories []RepositoryConfiguration\n}\n\ntype RepositoryConfiguration struct {\n  ID              string\n  Directory       string\n  ReadOnly        bool\n  RescanIntervalS int\n}\n\n\n\/\/ HTTP Parameters\nvar (\n  target    string\n  authUser  string\n  authPass  string\n  csrfToken string\n  csrfFile  string\n  apiKey    string\n)\n\n\/\/ Main\nvar (\n\tstop = make(chan int)\n)\n\nfunc main() {\n  flag.StringVar(&target, \"target\", \"localhost:8080\", \"Target\")\n  flag.StringVar(&authUser, \"user\", \"\", \"Username\")\n  flag.StringVar(&authPass, \"pass\", \"\", \"Password\")\n  flag.StringVar(&csrfFile, \"csrf\", \"\", \"CSRF token file\")\n  flag.StringVar(&apiKey, \"api\", \"\", \"API key\")\n  flag.Parse()\n\n  if len(csrfFile) > 0 {\n    fd, err := os.Open(csrfFile)\n    if err != nil {\n      log.Fatal(err)\n    }\n    s := bufio.NewScanner(fd)\n    for s.Scan() {\n      csrfToken = s.Text()\n    }\n    fd.Close()\n  }\n\n  repos := getRepos()\n  for i := range repos {\n    repo := repos[i]\n    go watchRepo(repo.ID, repo.Directory)\n  }\n\n  code := <-stop\n  println(\"Exiting\")\n  os.Exit(code)\n\n}\n\nfunc getRepos() []RepositoryConfiguration {\n  r, err := http.NewRequest(\"GET\", \"http:\/\/\"+target+\"\/rest\/config\", nil)\n  if err != nil {\n    log.Fatal(err)\n  }\n  if len(csrfToken) > 0 {\n    r.Header.Set(\"X-CSRF-Token\", csrfToken)\n  }\n  if len(authUser) > 0 {\n    r.SetBasicAuth(authUser, authPass)\n  }\n  if len(apiKey) > 0 {\n    r.Header.Set(\"X-API-Key\", apiKey)\n  }\n  res, err := http.DefaultClient.Do(r)\n  if err != nil {\n    log.Fatal(err)\n  }\n  defer res.Body.Close()\n  if res.StatusCode != 200 {\n    log.Fatalf(\"Status %d != 200 for GET\", res.StatusCode)\n  }\n  bs, err := ioutil.ReadAll(res.Body)\n  if err != nil {\n    log.Fatal(err)\n  }\n  var cfg Configuration\n  err = json.Unmarshal(bs, &cfg)\n  if err != nil {\n    log.Fatal(err)\n  }\n  return cfg.Repositories\n}\n\nfunc watchRepo(repo string, directory string) {\n  sw, err := NewSyncWatcher()\n  if sw == nil || err != nil {\n    log.Fatal(err)\n  }\n  defer sw.Close()\n  err = sw.Watch(directory)\n  if err != nil {\n    log.Fatal(err)\n  }\n  log.Println(\"Watching \"+repo+\": \"+directory)\n  for {\n    ev, ok := waitForEvent(sw)\n    if ok && ev != nil {\n      sub := strings.TrimPrefix(ev.Name, directory)\n      sub = strings.TrimPrefix(sub, string(os.PathSeparator))\n      informChange(repo, sub)\n    }\n  }\n}\n\nfunc waitForEvent(sw *SyncWatcher) (ev *fsnotify.FileEvent, ok bool) {\n  select {\n  case ev, ok = <-sw.Event:\n    if !ok {\n      log.Fatal(\"Event: channel closed\")\n    }\n  case err, eok := <-sw.Error:\n    log.Fatal(err, eok)\n  }\n  return\n}\n\nfunc informChange(repo string, sub string) {\n  data := url.Values {}\n  data.Set(\"repo\", repo)\n  data.Set(\"sub\", sub)\n  r, err := http.NewRequest(\"POST\", \"http:\/\/\"+target+\"\/rest\/scan?\"+data.Encode(), nil)\n  if err != nil {\n    log.Fatal(err)\n  }\n  if len(csrfToken) > 0 {\n    r.Header.Set(\"X-CSRF-Token\", csrfToken)\n  }\n  if len(authUser) > 0 {\n    r.SetBasicAuth(authUser, authPass)\n  }\n  if len(apiKey) > 0 {\n    r.Header.Set(\"X-API-Key\", apiKey)\n  }\n  res, err := http.DefaultClient.Do(r)\n  if err != nil {\n    log.Fatal(err)\n  }\n  defer res.Body.Close()\n  if res.StatusCode != 200 {\n    log.Fatalf(\"Status %d != 200 for POST\", res.StatusCode)\n  } else {\n    log.Println(\"Syncthing will index change in \"+repo+\": \"+sub)\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>package fakemetrics\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/grafana\/metrictank\/clock\"\n\t\"github.com\/grafana\/metrictank\/logger\"\n\t\"github.com\/grafana\/metrictank\/schema\"\n\t\"github.com\/grafana\/metrictank\/stacktest\/fakemetrics\/out\"\n\t\"github.com\/grafana\/metrictank\/stacktest\/fakemetrics\/out\/carbon\"\n\t\"github.com\/grafana\/metrictank\/stacktest\/fakemetrics\/out\/kafkamdm\"\n\t\"github.com\/raintank\/met\"\n\t\"github.com\/raintank\/met\/helper\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\nfunc init() {\n\tformatter := &logger.TextFormatter{}\n\tformatter.TimestampFormat = \"2006-01-02 15:04:05.000\"\n\tlog.SetFormatter(formatter)\n\tlog.SetLevel(log.InfoLevel)\n}\n\nfunc generateMetrics(num int) []*schema.MetricData {\n\tmetrics := make([]*schema.MetricData, num)\n\n\tfor i := 0; i < num; i++ {\n\t\tname := fmt.Sprintf(\"some.id.of.a.metric.%d\", i)\n\t\tm := &schema.MetricData{\n\t\t\tOrgId:    1,\n\t\t\tName:     name,\n\t\t\tInterval: 1,\n\t\t\tValue:    1,\n\t\t\tUnit:     \"s\",\n\t\t\tMtype:    \"gauge\",\n\t\t}\n\t\tm.SetId()\n\t\tmetrics[i] = m\n\t}\n\n\treturn metrics\n}\n\ntype FakeMetrics struct {\n\to       out.Out\n\tmetrics []*schema.MetricData\n\tclose   chan struct{}\n\tclosed  bool\n}\n\nfunc NewFakeMetrics(metrics []*schema.MetricData, o out.Out, stats met.Backend) *FakeMetrics {\n\tfm := &FakeMetrics{\n\t\to:       o,\n\t\tmetrics: metrics,\n\t\tclose:   make(chan struct{}),\n\t}\n\tgo fm.run()\n\treturn fm\n}\n\nfunc NewKafka(num int, timeout time.Duration, v2 bool) *FakeMetrics {\n\tstats, _ := helper.New(false, \"\", \"standard\", \"\", \"\")\n\tout, err := kafkamdm.New(\"mdm\", []string{\"localhost:9092\"}, \"none\", timeout, stats, \"lastNum\", v2)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create kafka-mdm output. %s\", err.Error())\n\t}\n\treturn NewFakeMetrics(generateMetrics(num), out, stats)\n}\n\nfunc NewCarbon(num int) *FakeMetrics {\n\tstats, _ := helper.New(false, \"\", \"standard\", \"\", \"\")\n\tout, err := carbon.New(\"localhost:2003\", stats)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create kafka-mdm output. %s\", err.Error())\n\t}\n\treturn NewFakeMetrics(generateMetrics(num), out, stats)\n}\n\nfunc (f *FakeMetrics) Close() error {\n\tif f.closed {\n\t\treturn nil\n\t}\n\tf.close <- struct{}{}\n\treturn f.o.Close()\n}\n\nfunc (f *FakeMetrics) run() {\n\t\/\/ advantage over regular ticker:\n\t\/\/ 1) no ticks dropped\n\t\/\/ 2) ticks come asap after the start of a new second, so we can measure better how long it took to get the data\n\tticker := clock.AlignedTick(time.Second)\n\n\tfor {\n\t\tselect {\n\t\tcase <-f.close:\n\t\t\treturn\n\t\tcase tick := <-ticker:\n\t\t\tunix := tick.Unix()\n\t\t\tfor i := range f.metrics {\n\t\t\t\tf.metrics[i].Time = unix\n\t\t\t}\n\t\t\terr := f.o.Flush(f.metrics)\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"failed to send data to output: %s\", err))\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>fix: make stacktest use an actual lossless ticker<commit_after>package fakemetrics\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/grafana\/metrictank\/clock\"\n\t\"github.com\/grafana\/metrictank\/logger\"\n\t\"github.com\/grafana\/metrictank\/schema\"\n\t\"github.com\/grafana\/metrictank\/stacktest\/fakemetrics\/out\"\n\t\"github.com\/grafana\/metrictank\/stacktest\/fakemetrics\/out\/carbon\"\n\t\"github.com\/grafana\/metrictank\/stacktest\/fakemetrics\/out\/kafkamdm\"\n\t\"github.com\/raintank\/met\"\n\t\"github.com\/raintank\/met\/helper\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\nfunc init() {\n\tformatter := &logger.TextFormatter{}\n\tformatter.TimestampFormat = \"2006-01-02 15:04:05.000\"\n\tlog.SetFormatter(formatter)\n\tlog.SetLevel(log.InfoLevel)\n}\n\nfunc generateMetrics(num int) []*schema.MetricData {\n\tmetrics := make([]*schema.MetricData, num)\n\n\tfor i := 0; i < num; i++ {\n\t\tname := fmt.Sprintf(\"some.id.of.a.metric.%d\", i)\n\t\tm := &schema.MetricData{\n\t\t\tOrgId:    1,\n\t\t\tName:     name,\n\t\t\tInterval: 1,\n\t\t\tValue:    1,\n\t\t\tUnit:     \"s\",\n\t\t\tMtype:    \"gauge\",\n\t\t}\n\t\tm.SetId()\n\t\tmetrics[i] = m\n\t}\n\n\treturn metrics\n}\n\ntype FakeMetrics struct {\n\to       out.Out\n\tmetrics []*schema.MetricData\n\tclose   chan struct{}\n\tclosed  bool\n}\n\nfunc NewFakeMetrics(metrics []*schema.MetricData, o out.Out, stats met.Backend) *FakeMetrics {\n\tfm := &FakeMetrics{\n\t\to:       o,\n\t\tmetrics: metrics,\n\t\tclose:   make(chan struct{}),\n\t}\n\tgo fm.run()\n\treturn fm\n}\n\nfunc NewKafka(num int, timeout time.Duration, v2 bool) *FakeMetrics {\n\tstats, _ := helper.New(false, \"\", \"standard\", \"\", \"\")\n\tout, err := kafkamdm.New(\"mdm\", []string{\"localhost:9092\"}, \"none\", timeout, stats, \"lastNum\", v2)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create kafka-mdm output. %s\", err.Error())\n\t}\n\treturn NewFakeMetrics(generateMetrics(num), out, stats)\n}\n\nfunc NewCarbon(num int) *FakeMetrics {\n\tstats, _ := helper.New(false, \"\", \"standard\", \"\", \"\")\n\tout, err := carbon.New(\"localhost:2003\", stats)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create kafka-mdm output. %s\", err.Error())\n\t}\n\treturn NewFakeMetrics(generateMetrics(num), out, stats)\n}\n\nfunc (f *FakeMetrics) Close() error {\n\tif f.closed {\n\t\treturn nil\n\t}\n\tf.close <- struct{}{}\n\treturn f.o.Close()\n}\n\nfunc (f *FakeMetrics) run() {\n\t\/\/ advantage over regular ticker:\n\t\/\/ 1) no ticks dropped: a hiccup in flushing should be handled by still producing all stats and flushing them when we can\n\t\/\/ 2) ticks come asap after the start of a new second, so we can measure better how long it took to get the data\n\tticker := clock.AlignedTickLossless(time.Second)\n\n\tfor {\n\t\tselect {\n\t\tcase <-f.close:\n\t\t\treturn\n\t\tcase tick := <-ticker:\n\t\t\tunix := tick.Unix()\n\t\t\tfor i := range f.metrics {\n\t\t\t\tf.metrics[i].Time = unix\n\t\t\t}\n\t\t\terr := f.o.Flush(f.metrics)\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Sprintf(\"failed to send data to output: %s\", err))\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2014 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage proxy\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com\/golang\/glog\"\n\t\"golang.org\/x\/net\/html\"\n\t\"golang.org\/x\/net\/html\/atom\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/net\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/sets\"\n)\n\n\/\/ atomsToAttrs states which attributes of which tags require URL substitution.\n\/\/ Sources: http:\/\/www.w3.org\/TR\/REC-html40\/index\/attributes.html\n\/\/          http:\/\/www.w3.org\/html\/wg\/drafts\/html\/master\/index.html#attributes-1\nvar atomsToAttrs = map[atom.Atom]sets.String{\n\tatom.A:          sets.NewString(\"href\"),\n\tatom.Applet:     sets.NewString(\"codebase\"),\n\tatom.Area:       sets.NewString(\"href\"),\n\tatom.Audio:      sets.NewString(\"src\"),\n\tatom.Base:       sets.NewString(\"href\"),\n\tatom.Blockquote: sets.NewString(\"cite\"),\n\tatom.Body:       sets.NewString(\"background\"),\n\tatom.Button:     sets.NewString(\"formaction\"),\n\tatom.Command:    sets.NewString(\"icon\"),\n\tatom.Del:        sets.NewString(\"cite\"),\n\tatom.Embed:      sets.NewString(\"src\"),\n\tatom.Form:       sets.NewString(\"action\"),\n\tatom.Frame:      sets.NewString(\"longdesc\", \"src\"),\n\tatom.Head:       sets.NewString(\"profile\"),\n\tatom.Html:       sets.NewString(\"manifest\"),\n\tatom.Iframe:     sets.NewString(\"longdesc\", \"src\"),\n\tatom.Img:        sets.NewString(\"longdesc\", \"src\", \"usemap\"),\n\tatom.Input:      sets.NewString(\"src\", \"usemap\", \"formaction\"),\n\tatom.Ins:        sets.NewString(\"cite\"),\n\tatom.Link:       sets.NewString(\"href\"),\n\tatom.Object:     sets.NewString(\"classid\", \"codebase\", \"data\", \"usemap\"),\n\tatom.Q:          sets.NewString(\"cite\"),\n\tatom.Script:     sets.NewString(\"src\"),\n\tatom.Source:     sets.NewString(\"src\"),\n\tatom.Video:      sets.NewString(\"poster\", \"src\"),\n\n\t\/\/ TODO: css URLs hidden in style elements.\n}\n\n\/\/ Transport is a transport for text\/html content that replaces URLs in html\n\/\/ content with the prefix of the proxy server\ntype Transport struct {\n\tScheme      string\n\tHost        string\n\tPathPrepend string\n\n\thttp.RoundTripper\n}\n\n\/\/ RoundTrip implements the http.RoundTripper interface\nfunc (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {\n\t\/\/ Add reverse proxy headers.\n\tforwardedURI := path.Join(t.PathPrepend, req.URL.Path)\n\tif strings.HasSuffix(req.URL.Path, \"\/\") {\n\t\tforwardedURI = forwardedURI + \"\/\"\n\t}\n\treq.Header.Set(\"X-Forwarded-Uri\", forwardedURI)\n\tif len(t.Host) > 0 {\n\t\treq.Header.Set(\"X-Forwarded-Host\", t.Host)\n\t}\n\tif len(t.Scheme) > 0 {\n\t\treq.Header.Set(\"X-Forwarded-Proto\", t.Scheme)\n\t}\n\n\trt := t.RoundTripper\n\tif rt == nil {\n\t\trt = http.DefaultTransport\n\t}\n\tresp, err := rt.RoundTrip(req)\n\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"Error: '%s'\\nTrying to reach: '%v'\", err.Error(), req.URL.String())\n\t\tresp = &http.Response{\n\t\t\tStatusCode: http.StatusServiceUnavailable,\n\t\t\tBody:       ioutil.NopCloser(strings.NewReader(message)),\n\t\t}\n\t\treturn resp, nil\n\t}\n\n\tif redirect := resp.Header.Get(\"Location\"); redirect != \"\" {\n\t\tresp.Header.Set(\"Location\", t.rewriteURL(redirect, req.URL, req.Host))\n\t\treturn resp, nil\n\t}\n\n\tcType := resp.Header.Get(\"Content-Type\")\n\tcType = strings.TrimSpace(strings.SplitN(cType, \";\", 2)[0])\n\tif cType != \"text\/html\" {\n\t\t\/\/ Do nothing, simply pass through\n\t\treturn resp, nil\n\t}\n\n\treturn t.rewriteResponse(req, resp)\n}\n\nvar _ = net.RoundTripperWrapper(&Transport{})\n\nfunc (rt *Transport) WrappedRoundTripper() http.RoundTripper {\n\treturn rt.RoundTripper\n}\n\n\/\/ rewriteURL rewrites a single URL to go through the proxy, if the URL refers\n\/\/ to the same host as sourceURL, which is the page on which the target URL\n\/\/ occurred, or if the URL matches the sourceHost. If any error occurs (e.g.\n\/\/ parsing), it returns targetURL.\nfunc (t *Transport) rewriteURL(targetURL string, sourceURL *url.URL, sourceHost string) string {\n\turl, err := url.Parse(targetURL)\n\tif err != nil {\n\t\treturn targetURL\n\t}\n\n\tisDifferentHost := url.Host != \"\" && url.Host != sourceURL.Host && url.Host != sourceHost\n\tisRelative := !strings.HasPrefix(url.Path, \"\/\")\n\tif isDifferentHost || isRelative {\n\t\treturn targetURL\n\t}\n\n\t\/\/ Do not rewrite scheme and host if the Transport has empty scheme and host\n\t\/\/ when targetURL already contains the sourceHost\n\tif !(url.Host == sourceHost && t.Scheme == \"\" && t.Host == \"\") {\n\t\turl.Scheme = t.Scheme\n\t\turl.Host = t.Host\n\t}\n\n\torigPath := url.Path\n\t\/\/ Do not rewrite URL if the sourceURL already contains the necessary prefix.\n\tif strings.HasPrefix(url.Path, t.PathPrepend) {\n\t\treturn url.String()\n\t}\n\turl.Path = path.Join(t.PathPrepend, url.Path)\n\tif strings.HasSuffix(origPath, \"\/\") {\n\t\t\/\/ Add back the trailing slash, which was stripped by path.Join().\n\t\turl.Path += \"\/\"\n\t}\n\n\treturn url.String()\n}\n\n\/\/ rewriteHTML scans the HTML for tags with url-valued attributes, and updates\n\/\/ those values with the urlRewriter function. The updated HTML is output to the\n\/\/ writer.\nfunc rewriteHTML(reader io.Reader, writer io.Writer, urlRewriter func(string) string) error {\n\t\/\/ Note: This assumes the content is UTF-8.\n\ttokenizer := html.NewTokenizer(reader)\n\n\tvar err error\n\tfor err == nil {\n\t\ttokenType := tokenizer.Next()\n\t\tswitch tokenType {\n\t\tcase html.ErrorToken:\n\t\t\terr = tokenizer.Err()\n\t\tcase html.StartTagToken, html.SelfClosingTagToken:\n\t\t\ttoken := tokenizer.Token()\n\t\t\tif urlAttrs, ok := atomsToAttrs[token.DataAtom]; ok {\n\t\t\t\tfor i, attr := range token.Attr {\n\t\t\t\t\tif urlAttrs.Has(attr.Key) {\n\t\t\t\t\t\ttoken.Attr[i].Val = urlRewriter(attr.Val)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t_, err = writer.Write([]byte(token.String()))\n\t\tdefault:\n\t\t\t_, err = writer.Write(tokenizer.Raw())\n\t\t}\n\t}\n\tif err != io.EOF {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ rewriteResponse modifies an HTML response by updating absolute links referring\n\/\/ to the original host to instead refer to the proxy transport.\nfunc (t *Transport) rewriteResponse(req *http.Request, resp *http.Response) (*http.Response, error) {\n\torigBody := resp.Body\n\tdefer origBody.Close()\n\n\tnewContent := &bytes.Buffer{}\n\tvar reader io.Reader = origBody\n\tvar writer io.Writer = newContent\n\tencoding := resp.Header.Get(\"Content-Encoding\")\n\tswitch encoding {\n\tcase \"gzip\":\n\t\tvar err error\n\t\treader, err = gzip.NewReader(reader)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"errorf making gzip reader: %v\", err)\n\t\t}\n\t\tgzw := gzip.NewWriter(writer)\n\t\tdefer gzw.Close()\n\t\twriter = gzw\n\t\/\/ TODO: support flate, other encodings.\n\tcase \"\":\n\t\t\/\/ This is fine\n\tdefault:\n\t\t\/\/ Some encoding we don't understand-- don't try to parse this\n\t\tglog.Errorf(\"Proxy encountered encoding %v for text\/html; can't understand this so not fixing links.\", encoding)\n\t\treturn resp, nil\n\t}\n\n\turlRewriter := func(targetUrl string) string {\n\t\treturn t.rewriteURL(targetUrl, req.URL, req.Host)\n\t}\n\terr := rewriteHTML(reader, writer, urlRewriter)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to rewrite URLs: %v\", err)\n\t\treturn resp, err\n\t}\n\n\tresp.Body = ioutil.NopCloser(newContent)\n\t\/\/ Update header node with new content-length\n\t\/\/ TODO: Remove any hash\/signature headers here?\n\tresp.Header.Del(\"Content-Length\")\n\tresp.ContentLength = int64(newContent.Len())\n\n\treturn resp, err\n}\n<commit_msg>Change name from sourceHost to sourceRequestHost.<commit_after>\/*\nCopyright 2014 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage proxy\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com\/golang\/glog\"\n\t\"golang.org\/x\/net\/html\"\n\t\"golang.org\/x\/net\/html\/atom\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/net\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/sets\"\n)\n\n\/\/ atomsToAttrs states which attributes of which tags require URL substitution.\n\/\/ Sources: http:\/\/www.w3.org\/TR\/REC-html40\/index\/attributes.html\n\/\/          http:\/\/www.w3.org\/html\/wg\/drafts\/html\/master\/index.html#attributes-1\nvar atomsToAttrs = map[atom.Atom]sets.String{\n\tatom.A:          sets.NewString(\"href\"),\n\tatom.Applet:     sets.NewString(\"codebase\"),\n\tatom.Area:       sets.NewString(\"href\"),\n\tatom.Audio:      sets.NewString(\"src\"),\n\tatom.Base:       sets.NewString(\"href\"),\n\tatom.Blockquote: sets.NewString(\"cite\"),\n\tatom.Body:       sets.NewString(\"background\"),\n\tatom.Button:     sets.NewString(\"formaction\"),\n\tatom.Command:    sets.NewString(\"icon\"),\n\tatom.Del:        sets.NewString(\"cite\"),\n\tatom.Embed:      sets.NewString(\"src\"),\n\tatom.Form:       sets.NewString(\"action\"),\n\tatom.Frame:      sets.NewString(\"longdesc\", \"src\"),\n\tatom.Head:       sets.NewString(\"profile\"),\n\tatom.Html:       sets.NewString(\"manifest\"),\n\tatom.Iframe:     sets.NewString(\"longdesc\", \"src\"),\n\tatom.Img:        sets.NewString(\"longdesc\", \"src\", \"usemap\"),\n\tatom.Input:      sets.NewString(\"src\", \"usemap\", \"formaction\"),\n\tatom.Ins:        sets.NewString(\"cite\"),\n\tatom.Link:       sets.NewString(\"href\"),\n\tatom.Object:     sets.NewString(\"classid\", \"codebase\", \"data\", \"usemap\"),\n\tatom.Q:          sets.NewString(\"cite\"),\n\tatom.Script:     sets.NewString(\"src\"),\n\tatom.Source:     sets.NewString(\"src\"),\n\tatom.Video:      sets.NewString(\"poster\", \"src\"),\n\n\t\/\/ TODO: css URLs hidden in style elements.\n}\n\n\/\/ Transport is a transport for text\/html content that replaces URLs in html\n\/\/ content with the prefix of the proxy server\ntype Transport struct {\n\tScheme      string\n\tHost        string\n\tPathPrepend string\n\n\thttp.RoundTripper\n}\n\n\/\/ RoundTrip implements the http.RoundTripper interface\nfunc (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {\n\t\/\/ Add reverse proxy headers.\n\tforwardedURI := path.Join(t.PathPrepend, req.URL.Path)\n\tif strings.HasSuffix(req.URL.Path, \"\/\") {\n\t\tforwardedURI = forwardedURI + \"\/\"\n\t}\n\treq.Header.Set(\"X-Forwarded-Uri\", forwardedURI)\n\tif len(t.Host) > 0 {\n\t\treq.Header.Set(\"X-Forwarded-Host\", t.Host)\n\t}\n\tif len(t.Scheme) > 0 {\n\t\treq.Header.Set(\"X-Forwarded-Proto\", t.Scheme)\n\t}\n\n\trt := t.RoundTripper\n\tif rt == nil {\n\t\trt = http.DefaultTransport\n\t}\n\tresp, err := rt.RoundTrip(req)\n\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"Error: '%s'\\nTrying to reach: '%v'\", err.Error(), req.URL.String())\n\t\tresp = &http.Response{\n\t\t\tStatusCode: http.StatusServiceUnavailable,\n\t\t\tBody:       ioutil.NopCloser(strings.NewReader(message)),\n\t\t}\n\t\treturn resp, nil\n\t}\n\n\tif redirect := resp.Header.Get(\"Location\"); redirect != \"\" {\n\t\tresp.Header.Set(\"Location\", t.rewriteURL(redirect, req.URL, req.Host))\n\t\treturn resp, nil\n\t}\n\n\tcType := resp.Header.Get(\"Content-Type\")\n\tcType = strings.TrimSpace(strings.SplitN(cType, \";\", 2)[0])\n\tif cType != \"text\/html\" {\n\t\t\/\/ Do nothing, simply pass through\n\t\treturn resp, nil\n\t}\n\n\treturn t.rewriteResponse(req, resp)\n}\n\nvar _ = net.RoundTripperWrapper(&Transport{})\n\nfunc (rt *Transport) WrappedRoundTripper() http.RoundTripper {\n\treturn rt.RoundTripper\n}\n\n\/\/ rewriteURL rewrites a single URL to go through the proxy, if the URL refers\n\/\/ to the same host as sourceURL, which is the page on which the target URL\n\/\/ occurred, or if the URL matches the sourceRequestHost. If any error occurs (e.g.\n\/\/ parsing), it returns targetURL.\nfunc (t *Transport) rewriteURL(targetURL string, sourceURL *url.URL, sourceRequestHost string) string {\n\turl, err := url.Parse(targetURL)\n\tif err != nil {\n\t\treturn targetURL\n\t}\n\n\tisDifferentHost := url.Host != \"\" && url.Host != sourceURL.Host && url.Host != sourceRequestHost\n\tisRelative := !strings.HasPrefix(url.Path, \"\/\")\n\tif isDifferentHost || isRelative {\n\t\treturn targetURL\n\t}\n\n\t\/\/ Do not rewrite scheme and host if the Transport has empty scheme and host\n\t\/\/ when targetURL already contains the sourceRequestHost\n\tif !(url.Host == sourceRequestHost && t.Scheme == \"\" && t.Host == \"\") {\n\t\turl.Scheme = t.Scheme\n\t\turl.Host = t.Host\n\t}\n\n\torigPath := url.Path\n\t\/\/ Do not rewrite URL if the sourceURL already contains the necessary prefix.\n\tif strings.HasPrefix(url.Path, t.PathPrepend) {\n\t\treturn url.String()\n\t}\n\turl.Path = path.Join(t.PathPrepend, url.Path)\n\tif strings.HasSuffix(origPath, \"\/\") {\n\t\t\/\/ Add back the trailing slash, which was stripped by path.Join().\n\t\turl.Path += \"\/\"\n\t}\n\n\treturn url.String()\n}\n\n\/\/ rewriteHTML scans the HTML for tags with url-valued attributes, and updates\n\/\/ those values with the urlRewriter function. The updated HTML is output to the\n\/\/ writer.\nfunc rewriteHTML(reader io.Reader, writer io.Writer, urlRewriter func(string) string) error {\n\t\/\/ Note: This assumes the content is UTF-8.\n\ttokenizer := html.NewTokenizer(reader)\n\n\tvar err error\n\tfor err == nil {\n\t\ttokenType := tokenizer.Next()\n\t\tswitch tokenType {\n\t\tcase html.ErrorToken:\n\t\t\terr = tokenizer.Err()\n\t\tcase html.StartTagToken, html.SelfClosingTagToken:\n\t\t\ttoken := tokenizer.Token()\n\t\t\tif urlAttrs, ok := atomsToAttrs[token.DataAtom]; ok {\n\t\t\t\tfor i, attr := range token.Attr {\n\t\t\t\t\tif urlAttrs.Has(attr.Key) {\n\t\t\t\t\t\ttoken.Attr[i].Val = urlRewriter(attr.Val)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t_, err = writer.Write([]byte(token.String()))\n\t\tdefault:\n\t\t\t_, err = writer.Write(tokenizer.Raw())\n\t\t}\n\t}\n\tif err != io.EOF {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ rewriteResponse modifies an HTML response by updating absolute links referring\n\/\/ to the original host to instead refer to the proxy transport.\nfunc (t *Transport) rewriteResponse(req *http.Request, resp *http.Response) (*http.Response, error) {\n\torigBody := resp.Body\n\tdefer origBody.Close()\n\n\tnewContent := &bytes.Buffer{}\n\tvar reader io.Reader = origBody\n\tvar writer io.Writer = newContent\n\tencoding := resp.Header.Get(\"Content-Encoding\")\n\tswitch encoding {\n\tcase \"gzip\":\n\t\tvar err error\n\t\treader, err = gzip.NewReader(reader)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"errorf making gzip reader: %v\", err)\n\t\t}\n\t\tgzw := gzip.NewWriter(writer)\n\t\tdefer gzw.Close()\n\t\twriter = gzw\n\t\/\/ TODO: support flate, other encodings.\n\tcase \"\":\n\t\t\/\/ This is fine\n\tdefault:\n\t\t\/\/ Some encoding we don't understand-- don't try to parse this\n\t\tglog.Errorf(\"Proxy encountered encoding %v for text\/html; can't understand this so not fixing links.\", encoding)\n\t\treturn resp, nil\n\t}\n\n\turlRewriter := func(targetUrl string) string {\n\t\treturn t.rewriteURL(targetUrl, req.URL, req.Host)\n\t}\n\terr := rewriteHTML(reader, writer, urlRewriter)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to rewrite URLs: %v\", err)\n\t\treturn resp, err\n\t}\n\n\tresp.Body = ioutil.NopCloser(newContent)\n\t\/\/ Update header node with new content-length\n\t\/\/ TODO: Remove any hash\/signature headers here?\n\tresp.Header.Del(\"Content-Length\")\n\tresp.ContentLength = int64(newContent.Len())\n\n\treturn resp, err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage events\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/clock\"\n\tutilruntime \"k8s.io\/apimachinery\/pkg\/util\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/watch\"\n\t\"k8s.io\/client-go\/tools\/reference\"\n\n\t\"k8s.io\/api\/events\/v1beta1\"\n\t\"k8s.io\/client-go\/tools\/record\/util\"\n\t\"k8s.io\/klog\"\n)\n\ntype recorderImpl struct {\n\tscheme              *runtime.Scheme\n\treportingController string\n\treportingInstance   string\n\t*watch.Broadcaster\n\tclock clock.Clock\n}\n\nfunc (recorder *recorderImpl) Eventf(regarding runtime.Object, related runtime.Object, eventtype, reason, action, note string, args ...interface{}) {\n\ttimestamp := metav1.MicroTime{time.Now()}\n\tmessage := fmt.Sprintf(note, args...)\n\trefRegarding, err := reference.GetReference(recorder.scheme, regarding)\n\tif err != nil {\n\t\tklog.Errorf(\"Could not construct reference to: '%#v' due to: '%v'. Will not report event: '%v' '%v' '%v'\", regarding, err, eventtype, reason, message)\n\t\treturn\n\t}\n\trefRelated, err := reference.GetReference(recorder.scheme, related)\n\tif err != nil {\n\t\tklog.Errorf(\"Could not construct reference to: '%#v' due to: '%v'.\", related, err)\n\t}\n\tif !util.ValidateEventType(eventtype) {\n\t\tklog.Errorf(\"Unsupported event type: '%v'\", eventtype)\n\t\treturn\n\t}\n\tevent := recorder.makeEvent(refRegarding, refRelated, timestamp, eventtype, reason, message, recorder.reportingController, recorder.reportingInstance, action)\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\t\trecorder.Action(watch.Added, event)\n\t}()\n}\n\nfunc (recorder *recorderImpl) makeEvent(refRegarding *v1.ObjectReference, refRelated *v1.ObjectReference, timestamp metav1.MicroTime, eventtype, reason, message string, reportingController string, reportingInstance string, action string) *v1beta1.Event {\n\tt := metav1.Time{Time: recorder.clock.Now()}\n\tnamespace := refRegarding.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = metav1.NamespaceSystem\n\t}\n\treturn &v1beta1.Event{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName:      fmt.Sprintf(\"%v.%x\", refRegarding.Name, t.UnixNano()),\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tEventTime:           timestamp,\n\t\tSeries:              nil,\n\t\tReportingController: reportingController,\n\t\tReportingInstance:   reportingInstance,\n\t\tAction:              action,\n\t\tReason:              reason,\n\t\tRegarding:           *refRegarding,\n\t\tRelated:             refRelated,\n\t\tNote:                message,\n\t\tType:                eventtype,\n\t\t\/\/ TODO: remove this when we change conversion to convert eventSource\n\t\t\/\/ to reportingController\n\t\tDeprecatedSource: v1.EventSource{Component: reportingController},\n\t}\n}\n<commit_msg>Tolerate the case if `related` event is nil<commit_after>\/*\nCopyright 2019 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage events\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/clock\"\n\tutilruntime \"k8s.io\/apimachinery\/pkg\/util\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/watch\"\n\t\"k8s.io\/client-go\/tools\/reference\"\n\n\t\"k8s.io\/api\/events\/v1beta1\"\n\t\"k8s.io\/client-go\/tools\/record\/util\"\n\t\"k8s.io\/klog\"\n)\n\ntype recorderImpl struct {\n\tscheme              *runtime.Scheme\n\treportingController string\n\treportingInstance   string\n\t*watch.Broadcaster\n\tclock clock.Clock\n}\n\nfunc (recorder *recorderImpl) Eventf(regarding runtime.Object, related runtime.Object, eventtype, reason, action, note string, args ...interface{}) {\n\ttimestamp := metav1.MicroTime{time.Now()}\n\tmessage := fmt.Sprintf(note, args...)\n\trefRegarding, err := reference.GetReference(recorder.scheme, regarding)\n\tif err != nil {\n\t\tklog.Errorf(\"Could not construct reference to: '%#v' due to: '%v'. Will not report event: '%v' '%v' '%v'\", regarding, err, eventtype, reason, message)\n\t\treturn\n\t}\n\trefRelated, err := reference.GetReference(recorder.scheme, related)\n\tif err != nil {\n\t\tklog.V(9).Infof(\"Could not construct reference to: '%#v' due to: '%v'.\", related, err)\n\t}\n\tif !util.ValidateEventType(eventtype) {\n\t\tklog.Errorf(\"Unsupported event type: '%v'\", eventtype)\n\t\treturn\n\t}\n\tevent := recorder.makeEvent(refRegarding, refRelated, timestamp, eventtype, reason, message, recorder.reportingController, recorder.reportingInstance, action)\n\tgo func() {\n\t\tdefer utilruntime.HandleCrash()\n\t\trecorder.Action(watch.Added, event)\n\t}()\n}\n\nfunc (recorder *recorderImpl) makeEvent(refRegarding *v1.ObjectReference, refRelated *v1.ObjectReference, timestamp metav1.MicroTime, eventtype, reason, message string, reportingController string, reportingInstance string, action string) *v1beta1.Event {\n\tt := metav1.Time{Time: recorder.clock.Now()}\n\tnamespace := refRegarding.Namespace\n\tif namespace == \"\" {\n\t\tnamespace = metav1.NamespaceSystem\n\t}\n\treturn &v1beta1.Event{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName:      fmt.Sprintf(\"%v.%x\", refRegarding.Name, t.UnixNano()),\n\t\t\tNamespace: namespace,\n\t\t},\n\t\tEventTime:           timestamp,\n\t\tSeries:              nil,\n\t\tReportingController: reportingController,\n\t\tReportingInstance:   reportingInstance,\n\t\tAction:              action,\n\t\tReason:              reason,\n\t\tRegarding:           *refRegarding,\n\t\tRelated:             refRelated,\n\t\tNote:                message,\n\t\tType:                eventtype,\n\t\t\/\/ TODO: remove this when we change conversion to convert eventSource\n\t\t\/\/ to reportingController\n\t\tDeprecatedSource: v1.EventSource{Component: reportingController},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\n\/\/ This is a basic example to illustrate how to access the Fidor API\n\/\/ using Go.\n\/\/\n\/\/ To run this example type:\n\/\/\n\/\/     $ go run example.go\n\/\/\n\/\/ And point your browser to:\n\/\/\n\/\/     $ http:\/\/localhost:8080\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n)\n\n\/\/ The following sections define the settings you require for the\n\/\/ app to be able to connect to and authorize itself against the api.\n\n\/\/ app ID and secret, can be found in this apps \"Details\" page in the\n\/\/ AppManager.\nvar client_id = \"<CLIENT_ID>\"\nvar client_secret = \"<CLIENT_SECRET>\"\n\n\/\/ Fidor's OAuth Endpoint (this changes between Sandbox and Production)\nvar fidor_oauth_url = \"<FIDOR_OAUTH_URL>\" \/\/ e.g https:\/\/fidor.com\/api_sandbox\/oauth\n\/\/ The OAuth Endpoint this App provides\nvar oauth_cb_url = \"<APP_URL>\"\n\n\/\/ The URL of the Fidor API (this changes between Sandbox and\n\/\/ Production)\nvar fidor_api_url = \"<FIDOR_API_URL>\" \/\/ e.g https:\/\/fidor.com\/api_sandbox vs \/api\n\n\n\n\nfunc main() {\n\t\/\/ register a handler function (see next function) to service\n\t\/\/ requests ...\n\thttp.HandleFunc(\"\/\", indexHandler)\n\tfmt.Printf(\"Now open http:\/\/localhost:8080\")\n\t\/\/ ... and start listening.\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc indexHandler(w http.ResponseWriter, r *http.Request) {\n\n\t\/\/ ignore any favicon requests, etc.\n\tif r.URL.Path != \"\/\" {\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\t\/\/ check whether we have a GET parameter named `code`, if so,\n\t\/\/ this is a redirect back from the Fidor OAuth server.\n\tvalues := r.URL.Query()\n\tif values[\"code\"] != nil {\n\t\t\/\/ retrieve the actual OAuth access token ....\n\t\tcode := values.Get(\"code\")\n\t\tif token, err := retrieveTokenFromCode(code); err != nil {\n\t\t\tfmt.Printf(\"err: %v\\n\", err)\n\t\t\tw.WriteHeader(500)\n\t\t\tfmt.Fprintf(w, \"Unfortunately, an error occurred retrieving oauth token\")\n\t\t} else {\n\t\t\t\/\/ ... and finally, greet the user and assemble links\n\t\t\trenderWelcome(w, token)\n\t\t}\n\t} else {\n\t\t\/\/ we don't have an oauth `code` yet, so we need to\n\t\t\/\/ redirect the user to the OAuth provider to get one ...\n\t\toauth_url := fmt.Sprintf(\"%s\/authorize?client_id=%s&state=123&response_type=code&redirect_uri=%s\",\n\t\t\tfidor_oauth_url,\n\t\t\tclient_id,\n\t\t\turl.QueryEscape(oauth_cb_url))\n\n\t\theader := w.Header()\n\t\theader.Add(\"location\", oauth_url)\n\t\tw.WriteHeader(307)\n\t}\n}\n\n\n\/\/ Our TokenResponse representation used to pick it out from the JSON\n\/\/ returned by the OAuth server.\ntype TokenResponse struct {\n\tToken string `json:\"access_token\"`\n}\n\n\/\/ Use the OAuth code that the user's browser picked up from the OAuth\n\/\/ server to request an OAuth access_token to use in API requests.\nfunc retrieveTokenFromCode(code string) (token string, err error) {\n\t\/\/ assemble the API endpoint URL and request payload\n\ttokenUrl := fmt.Sprintf(\"%s\/token\", fidor_oauth_url)\n\ttokenPayload := url.Values{\n\t\t\"client_id\":     {client_id},\n\t\t\"client_secret\": {client_secret},\n\t\t\"code\":          {code},\n\t\t\"redirect_uri\":  {url.QueryEscape(oauth_cb_url)},\n\t}\n\t\/\/ Call API\n\tif resp, err := http.PostForm(tokenUrl, tokenPayload); err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\t\/\/ if successful, pick the access_token out of the reply.\n\t\tvar tokenResponse TokenResponse\n\t\tdecoder := json.NewDecoder(resp.Body)\n\t\tif err = decoder.Decode(&tokenResponse); err != nil {\n\t\t\treturn \"\", err\n\t\t} else {\n\t\t\treturn tokenResponse.Token, nil\n\t\t}\n\t}\n}\n\n\n\/\/ Our server code only makes a single call to the API to retrieve user\n\/\/ information. This is our internal representation of the returned JSON\n\/\/ used to pick out the user's email.\ntype UserResponse struct {\n\tEmail string `json:\"email\"`\n}\n\n\/\/ function to retrieve user information from the API\nfunc getUser(token string) (u UserResponse, err error) {\n\t\/\/ Assemble endpoint URL...\n\turl := fmt.Sprintf(\"%s\/users\/current?access_token=%s\", fidor_api_url, token)\n\tif resp, err := http.Get(url); err != nil {\n\t\treturn u, err\n\t} else {\n\t\tdecoder := json.NewDecoder(resp.Body)\n\t\tif err = decoder.Decode(&u); err != nil {\n\t\t\treturn u, err\n\t\t} else {\n\t\t\treturn u, nil\n\t\t}\n\t}\n}\n\n\n\/\/ once all the OAuth calls have been taken care of, this function is\n\/\/ called from the http handler. It retrieves the user's email address\n\/\/ and inserts links to `transaction` and `accounts` endpoints.\n\nfunc renderWelcome(w http.ResponseWriter, token string) {\n\tif user, err := getUser(token); err != nil {\n\t\tfmt.Printf(\"err: %v\\n\", err)\n\t\tw.WriteHeader(500)\n\t} else {\n\t\ttxLink := fmt.Sprintf(\"%s\/transactions?access_token=%s\", fidor_api_url, token)\n\t\tacctsLink := fmt.Sprintf(\"%s\/accounts?access_token=%s\", fidor_api_url, token)\n\t\tfmt.Fprintf(w, indexTemplate, user.Email, token, txLink, acctsLink)\n\t}\n}\n\nvar indexTemplate = `\n<html>\n<head>\n<\/head>\n<body>\n\t<h1>Welcome %s!<\/h1>\n\t<i>retrieved <tt>access_token<\/tt>: %s<\/i>\n\t<p><a href=\"%s\">Transactions<\/a><\/p>\n\t<p><a href=\"%s\">Accounts<\/a><\/p>\n<\/body>\n<\/html>\n`\n<commit_msg>added missing oauth params to go example<commit_after>package main\n\n\/\/ This is a basic example to illustrate how to access the Fidor API\n\/\/ using Go.\n\/\/\n\/\/ To run this example type:\n\/\/\n\/\/     $ go run example.go\n\/\/\n\/\/ And point your browser to:\n\/\/\n\/\/     $ http:\/\/localhost:8080\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"errors\"\n)\n\n\/\/ The following sections define the settings you require for the\n\/\/ app to be able to connect to and authorize itself against the api.\n\n\/\/ app ID and secret, can be found in this apps \"Details\" page in the\n\/\/ AppManager.\nvar client_id     = \"<CLIENT_ID>\"\nvar client_secret = \"<CLIENT_SECRET>\"\n\n\/\/ Fidor's OAuth Endpoint (this changes between Sandbox and Production)\nvar fidor_oauth_url = \"<FIDOR_OAUTH_URL>\" \/\/ e.g https:\/\/fidor.com\/api_sandbox\/oauth\n\/\/ The OAuth Endpoint this App provides\nvar oauth_cb_url    = \"<APP_URL>\"\n\n\/\/ The URL of the Fidor API (this changes between Sandbox and\n\/\/ Production)\nvar fidor_api_url   = \"<FIDOR_API_URL>\" \/\/ e.g https:\/\/fidor.com\/api_sandbox vs \/api\n\n\n\n\nfunc main() {\n\t\/\/ register a handler function (see next function) to service\n\t\/\/ requests ...\n\thttp.HandleFunc(\"\/\", indexHandler)\n\tfmt.Printf(\"Now open http:\/\/localhost:8080\")\n\t\/\/ ... and start listening.\n\thttp.ListenAndServe(\":8080\", nil)\n}\n\nfunc indexHandler(w http.ResponseWriter, r *http.Request) {\n\n\t\/\/ ignore any favicon requests, etc.\n\tif r.URL.Path != \"\/\" {\n\t\tw.WriteHeader(404)\n\t\treturn\n\t}\n\n\t\/\/ check whether we have a GET parameter named `code`, if so,\n\t\/\/ this is a redirect back from the Fidor OAuth server.\n\tvalues := r.URL.Query()\n\tif values[\"code\"] != nil {\n\t\t\/\/ retrieve the actual OAuth access token ....\n\t\tcode := values.Get(\"code\")\n\t\tif token, err := retrieveTokenFromCode(code); err != nil {\n\t\t\tfmt.Printf(\"err: %v\\n\", err)\n\t\t\tw.WriteHeader(500)\n\t\t\tfmt.Fprintf(w, \"Unfortunately, an error occurred retrieving oauth token\")\n\t\t} else {\n\t\t\t\/\/ ... and finally, greet the user and assemble links\n\t\t\trenderWelcome(w, token)\n\t\t}\n\t} else {\n\t\t\/\/ we don't have an oauth `code` yet, so we need to\n\t\t\/\/ redirect the user to the OAuth provider to get one ...\n\t\toauth_url := fmt.Sprintf(\"%s\/authorize?client_id=%s&state=123&response_type=code&redirect_uri=%s\",\n\t\t\tfidor_oauth_url,\n\t\t\tclient_id,\n\t\t\turl.QueryEscape(oauth_cb_url))\n\n\t\theader := w.Header()\n\t\theader.Add(\"location\", oauth_url)\n\t\tw.WriteHeader(307)\n\t}\n}\n\n\n\/\/ Our TokenResponse representation used to pick it out from the JSON\n\/\/ returned by the OAuth server.\ntype TokenResponse struct {\n\tToken string `json:\"access_token\"`\n}\n\n\/\/ Use the OAuth code that the user's browser picked up from the OAuth\n\/\/ server to request an OAuth access_token to use in API requests.\nfunc retrieveTokenFromCode(code string) (token string, err error) {\n\t\/\/ assemble the API endpoint URL and request payload\n\ttokenUrl := fmt.Sprintf(\"%s\/token\", fidor_oauth_url)\n\ttokenPayload := url.Values{\n\t\t\"client_id\":     {client_id},\n\t\t\"client_secret\": {client_secret},\n\t\t\"code\":          {code},\n\t\t\"redirect_uri\":  {url.QueryEscape(oauth_cb_url)},\n\t\t\"grant_type\":    {\"autorization_code\"}\n\t}\n\t\/\/ Call API\n\tif resp, err := http.PostForm(tokenUrl, tokenPayload); err != nil {\n\t\tprintln(err)\n\t\treturn \"\", err\n\t} else {\n\t\tif resp.StatusCode != 200 {\n\t\t\treturn \"\", errors.New(resp.Status)\n\t\t}\n\t\t\/\/ if successful, pick the access_token out of the reply.\n\t\tvar tokenResponse TokenResponse\n\t\tdecoder := json.NewDecoder(resp.Body)\n\t\tif err = decoder.Decode(&tokenResponse); err != nil {\n\t\t\treturn \"\", err\n\t\t} else {\n\t\t\treturn tokenResponse.Token, nil\n\t\t}\n\t}\n}\n\n\n\/\/ Our server code only makes a single call to the API to retrieve user\n\/\/ information. This is our internal representation of the returned JSON\n\/\/ used to pick out the user's email.\ntype UserResponse struct {\n\tEmail string `json:\"email\"`\n}\n\n\/\/ function to retrieve user information from the API\nfunc getUser(token string) (u UserResponse, err error) {\n\t\/\/ Assemble endpoint URL...\n\turl := fmt.Sprintf(\"%s\/users\/current?access_token=%s\", fidor_api_url, token)\n\tif resp, err := http.Get(url); err != nil {\n\t\treturn u, err\n\t} else {\n\t\tdecoder := json.NewDecoder(resp.Body)\n\t\tif err = decoder.Decode(&u); err != nil {\n\t\t\treturn u, err\n\t\t} else {\n\t\t\treturn u, nil\n\t\t}\n\t}\n}\n\n\n\/\/ once all the OAuth calls have been taken care of, this function is\n\/\/ called from the http handler. It retrieves the user's email address\n\/\/ and inserts links to `transaction` and `accounts` endpoints.\n\nfunc renderWelcome(w http.ResponseWriter, token string) {\n\tif user, err := getUser(token); err != nil {\n\t\tfmt.Printf(\"err: %v\\n\", err)\n\t\tw.WriteHeader(500)\n\t} else {\n\t\ttxLink := fmt.Sprintf(\"%s\/transactions?access_token=%s\", fidor_api_url, token)\n\t\tacctsLink := fmt.Sprintf(\"%s\/accounts?access_token=%s\", fidor_api_url, token)\n\t\tfmt.Fprintf(w, indexTemplate, user.Email, token, txLink, acctsLink)\n\t}\n}\n\nvar indexTemplate = `\n<html>\n<head>\n<\/head>\n<body>\n\t<h1>Welcome %s!<\/h1>\n\t<i>retrieved <tt>access_token<\/tt>: %s<\/i>\n\t<p><a href=\"%s\">Transactions<\/a><\/p>\n\t<p><a href=\"%s\">Accounts<\/a><\/p>\n<\/body>\n<\/html>\n`\n<|endoftext|>"}
{"text":"<commit_before>package libstns\n\nimport (\n\t\"os\"\n\n\t\"github.com\/shirou\/gopsutil\/host\"\n)\n\nfunc AfterOsBoot() int {\n\thost, err := host.Info()\n\n\tif err != nil {\n\t\treturn NSS_STATUS_UNAVAIL\n\t}\n\n\tif host.PlatformFamily == \"debian\" && (os.Args[0] == \"\/sbin\/init\" || os.Args[0] == \"dbus-daemon\") {\n\t\treturn NSS_STATUS_NOTFOUND\n\t}\n\n\treturn NSS_STATUS_SUCCESS\n}\n<commit_msg>fix pid<commit_after>package libstns\n\nimport (\n\t\"os\"\n\n\t\"github.com\/shirou\/gopsutil\/host\"\n)\n\nfunc AfterOsBoot() int {\n\tif _, err := os.FindProcess(1); err != nil {\n\t\treturn NSS_STATUS_UNAVAIL\n\t}\n\n\tif os.Args[0] == \"\/sbin\/init\" || os.Args[0] == \"dbus-daemon\" {\n\t\thost, err := host.Info()\n\n\t\tif err != nil {\n\t\t\treturn NSS_STATUS_UNAVAIL\n\t\t}\n\n\t\tif host.PlatformFamily == \"debian\" {\n\t\t\treturn NSS_STATUS_NOTFOUND\n\t\t}\n\t}\n\treturn NSS_STATUS_SUCCESS\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/adam000\/Go-SDL2\/image\"\n\t\"github.com\/adam000\/Go-SDL2\/sdl\"\n)\n\nvar fullscreen = flag.Bool(\"fullscreen\", false, \"fullscreen window\")\n\nfunc main() {\n\tflag.Parse()\n\tif flag.NArg() == 0 {\n\t\tflag.Usage()\n\t\tsdl.Quit()\n\t\tos.Exit(2)\n\t}\n\tvar err error\n\tgo sdl.Do(func() { err = run() })\n\tsdl.Main()\n\n\tif err := run(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc run() error {\n\tdefer sdl.Quit()\n\tsdl.Init(sdl.InitVideo)\n\n\tsurfaces, err := loadImages(flag.Args())\n\tdefer func() {\n\t\tfor _, s := range surfaces {\n\t\t\ts.Free()\n\t\t}\n\t}()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, renderer, err := openWindow(flag.Arg(0), maxSize(surfaces))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttextures, err := convertToTextures(renderer, surfaces)\n\tdefer func() {\n\t\tfor _, t := range textures {\n\t\t\tt.Destroy()\n\t\t}\n\t}()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmainLoop(renderer, textures)\n\treturn nil\n}\n\nfunc mainLoop(renderer sdl.Renderer, textures []sdl.Texture) {\n\tcurrTex := 0\n\tfor {\n\t\t\/\/ Poll for events\n\t\tfor {\n\t\t\tev := sdl.PollEvent()\n\t\t\tif ev == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tswitch ev.Type() {\n\t\t\tcase sdl.QuitEventType:\n\t\t\t\tfmt.Println(\"QUIT\")\n\t\t\t\treturn\n\t\t\tcase sdl.KeyDownEventType:\n\t\t\t\tfmt.Println(\"KEY\")\n\t\t\t\t\/\/ TODO(light): advance texture\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Display image\n\t\trenderer.Clear()\n\t\trenderer.CopyTexture(textures[currTex], nil, nil)\n\t\trenderer.Present()\n\n\t\t\/\/ Wait a bit\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}\n\nfunc openWindow(title string, size sdl.Point) (sdl.Window, sdl.Renderer, error) {\n\tvar windowFlags sdl.WindowFlag\n\tif *fullscreen {\n\t\twindowFlags |= sdl.WindowFullscreen\n\t}\n\twindow, err := sdl.NewWindow(title, 0, 0, size.X, size.Y, windowFlags)\n\tif err != nil {\n\t\treturn window, sdl.Renderer{}, err\n\t}\n\trenderer, err := sdl.NewRenderer(window, -1, 0)\n\treturn window, renderer, err\n}\n\nfunc loadImages(names []string) ([]sdl.Surface, error) {\n\tsurfaces := make([]sdl.Surface, 0, len(names))\n\tfor _, name := range names {\n\t\ts, err := image.Load(name)\n\t\tif err != nil {\n\t\t\treturn surfaces, &os.PathError{Op: \"open\", Path: name, Err: err}\n\t\t}\n\t\tsurfaces = append(surfaces, s)\n\t}\n\treturn surfaces, nil\n}\n\nfunc convertToTextures(renderer sdl.Renderer, surfaces []sdl.Surface) ([]sdl.Texture, error) {\n\ttextures := make([]sdl.Texture, 0, len(surfaces))\n\tfor _, s := range surfaces {\n\t\tt, err := s.ToTexture(renderer)\n\t\tif err != nil {\n\t\t\treturn textures, err\n\t\t}\n\t\ttextures = append(textures, t)\n\t}\n\treturn textures, nil\n}\n\nfunc maxSize(s []sdl.Surface) sdl.Point {\n\tvar size sdl.Point\n\tfor _, ss := range s {\n\t\tz := ss.Size()\n\t\tif z.X > size.X {\n\t\t\tsize.X = z.X\n\t\t}\n\t\tif z.Y > size.Y {\n\t\t\tsize.Y = z.Y\n\t\t}\n\t}\n\treturn size\n}\n<commit_msg>Fix double run in showimage demo<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/adam000\/Go-SDL2\/image\"\n\t\"github.com\/adam000\/Go-SDL2\/sdl\"\n)\n\nvar fullscreen = flag.Bool(\"fullscreen\", false, \"fullscreen window\")\n\nfunc main() {\n\tflag.Parse()\n\tif flag.NArg() == 0 {\n\t\tflag.Usage()\n\t\tsdl.Quit()\n\t\tos.Exit(2)\n\t}\n\tvar err error\n\tgo sdl.Do(func() { err = run() })\n\tsdl.Main()\n\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc run() error {\n\tdefer sdl.Quit()\n\tsdl.Init(sdl.InitVideo)\n\n\tsurfaces, err := loadImages(flag.Args())\n\tdefer func() {\n\t\tfor _, s := range surfaces {\n\t\t\ts.Free()\n\t\t}\n\t}()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, renderer, err := openWindow(flag.Arg(0), maxSize(surfaces))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttextures, err := convertToTextures(renderer, surfaces)\n\tdefer func() {\n\t\tfor _, t := range textures {\n\t\t\tt.Destroy()\n\t\t}\n\t}()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmainLoop(renderer, textures)\n\treturn nil\n}\n\nfunc mainLoop(renderer sdl.Renderer, textures []sdl.Texture) {\n\tcurrTex := 0\n\tfor {\n\t\t\/\/ Poll for events\n\t\tfor {\n\t\t\tev := sdl.PollEvent()\n\t\t\tif ev == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tswitch ev.Type() {\n\t\t\tcase sdl.QuitEventType:\n\t\t\t\tfmt.Println(\"QUIT\")\n\t\t\t\treturn\n\t\t\tcase sdl.KeyDownEventType:\n\t\t\t\tfmt.Println(\"KEY\")\n\t\t\t\t\/\/ TODO(light): advance texture\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Display image\n\t\trenderer.Clear()\n\t\trenderer.CopyTexture(textures[currTex], nil, nil)\n\t\trenderer.Present()\n\n\t\t\/\/ Wait a bit\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}\n\nfunc openWindow(title string, size sdl.Point) (sdl.Window, sdl.Renderer, error) {\n\tvar windowFlags sdl.WindowFlag\n\tif *fullscreen {\n\t\twindowFlags |= sdl.WindowFullscreen\n\t}\n\twindow, err := sdl.NewWindow(title, 0, 0, size.X, size.Y, windowFlags)\n\tif err != nil {\n\t\treturn window, sdl.Renderer{}, err\n\t}\n\trenderer, err := sdl.NewRenderer(window, -1, 0)\n\treturn window, renderer, err\n}\n\nfunc loadImages(names []string) ([]sdl.Surface, error) {\n\tsurfaces := make([]sdl.Surface, 0, len(names))\n\tfor _, name := range names {\n\t\ts, err := image.Load(name)\n\t\tif err != nil {\n\t\t\treturn surfaces, &os.PathError{Op: \"open\", Path: name, Err: err}\n\t\t}\n\t\tsurfaces = append(surfaces, s)\n\t}\n\treturn surfaces, nil\n}\n\nfunc convertToTextures(renderer sdl.Renderer, surfaces []sdl.Surface) ([]sdl.Texture, error) {\n\ttextures := make([]sdl.Texture, 0, len(surfaces))\n\tfor _, s := range surfaces {\n\t\tt, err := s.ToTexture(renderer)\n\t\tif err != nil {\n\t\t\treturn textures, err\n\t\t}\n\t\ttextures = append(textures, t)\n\t}\n\treturn textures, nil\n}\n\nfunc maxSize(s []sdl.Surface) sdl.Point {\n\tvar size sdl.Point\n\tfor _, ss := range s {\n\t\tz := ss.Size()\n\t\tif z.X > size.X {\n\t\t\tsize.X = z.X\n\t\t}\n\t\tif z.Y > size.Y {\n\t\t\tsize.Y = z.Y\n\t\t}\n\t}\n\treturn size\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Support for MCP-23017 I2C port expander.\n\n\/\/ Currently only supports basic GPIO (input and output). It does not support interupt features.\n\npackage mcp23017\n\nimport (\n\t\"fmt\"\n\t\"hwio\"\n)\n\nconst (\n\t\/\/ This is the default address if pins A2, A1 and A0 are grounded. So device address is base + (A2, A1, A0)\n\tDEFAULT_BASE_ADDRESS = 0x20\n\n\tREG_IODIRA  = 0x00\n\tREG_IODIRB  = 0x01\n\tREG_IPOLA   = 0x02\n\tREG_IPOLB   = 0x03\n\tREG_GPINENA = 0x04\n\tREG_GPINENB = 0x05\n\tREG_DEFVALA = 0x06\n\tREG_DEFVALB = 0x07\n\tREG_INTCONA = 0x08\n\tREG_INTCONB = 0x09\n\tREG_IOCON   = 0x0a\n\tREG_GPPUA   = 0x0c\n\tREG_GPPUB   = 0x0d\n\tREG_INTFA   = 0x0e\n\tREG_INTFB   = 0x0f\n\tREG_INTCAPA = 0x10\n\tREG_INTCAPB = 0x11\n\tREG_GPIOA   = 0x12\n\tREG_GPIOB   = 0x13\n\tREG_OLATA   = 0x14\n\tREG_OLATB   = 0x15\n)\n\ntype MCP23017 struct {\n\tdevice hwio.I2CDevice\n}\n\n\/\/ Create a new isntance, and set it to use Bank 0. The address can either be what is wired on\n\/\/ (A2,A1,A0) of the physical device, in which case this is added to the base address for the device\n\/\/ (0x20). Otherwise, you can use 0x20-0x27. Anything else will return an error.\nfunc NewMCP23017(module hwio.I2CModule, address int) (*MCP23017, error) {\n\tif address < 8 {\n\t\taddress += DEFAULT_BASE_ADDRESS\n\t}\n\n\tif address < 0x20 || address > 0x27 {\n\t\treturn nil, fmt.Errorf(\"Device address %d is invalid for an MCP23017. It must be in the range 0x20-0x27\", address)\n\t}\n\n\tdevice := module.GetDevice(address)\n\tresult := &MCP23017{device: device}\n\n\t\/\/ set config reg, force BANK=0, SEQOP=0. Note that this only works if already in BANK0, which is default on power-up\n\tdevice.WriteByte(REG_IOCON, 0)\n\n\treturn result, nil\n}\n\n\/\/ Set direction bits for port A. A 1 bit indicates corresponding pin will be an input,\n\/\/ A 0 bit indicates it will be an output.\nfunc (d *MCP23017) SetDirA(value byte) error {\n\treturn d.device.WriteByte(REG_IODIRA, value)\n}\n\n\/\/ Set direction bits for port A. A 1 bit indicates corresponding pin will be an input,\n\/\/ A 0 bit indicates it will be an output.\nfunc (d *MCP23017) SetDirB(value byte) error {\n\treturn d.device.WriteByte(REG_IODIRB, value)\n}\n\n\/\/ Read from port A\nfunc (d *MCP23017) GetPortA() (byte, error) {\n\treturn d.device.ReadByte(REG_GPIOA)\n}\n\n\/\/ Read from port B\nfunc (d *MCP23017) GetPortB() (byte, error) {\n\treturn d.device.ReadByte(REG_GPIOB)\n}\n\n\/\/ Write to port A\nfunc (d *MCP23017) SetPortA(value byte) error {\n\treturn d.device.WriteByte(REG_OLATA, value)\n}\n\n\/\/ Write to port B\nfunc (d *MCP23017) SetPortB(value byte) error {\n\treturn d.device.WriteByte(REG_OLATA, value)\n}\n\n\/\/ Set pull-up configuration for port A. If a bit is 1 and the corresponding pin is\n\/\/ an input, a pull-up resistor of about 100K is enabled. A zero bit indicates no pull-up.\nfunc (d *MCP23017) SetPullupA(value byte) error {\n\treturn d.device.WriteByte(REG_GPPUA, value)\n}\n\n\/\/ Set pull-up configuration for port B. If a bit is 1 and the corresponding pin is\n\/\/ an input, a pull-up resistor of about 100K is enabled. A zero bit indicates no pull-up.\nfunc (d *MCP23017) SetPullupB(value byte) error {\n\treturn d.device.WriteByte(REG_GPPUB, value)\n}\n<commit_msg>fix import path<commit_after>\/\/ Support for MCP-23017 I2C port expander.\n\n\/\/ Currently only supports basic GPIO (input and output). It does not support interupt features.\n\npackage mcp23017\n\nimport (\n\t\"fmt\"\n\t\"github.com\/mrmorphic\/hwio\"\n)\n\nconst (\n\t\/\/ This is the default address if pins A2, A1 and A0 are grounded. So device address is base + (A2, A1, A0)\n\tDEFAULT_BASE_ADDRESS = 0x20\n\n\tREG_IODIRA  = 0x00\n\tREG_IODIRB  = 0x01\n\tREG_IPOLA   = 0x02\n\tREG_IPOLB   = 0x03\n\tREG_GPINENA = 0x04\n\tREG_GPINENB = 0x05\n\tREG_DEFVALA = 0x06\n\tREG_DEFVALB = 0x07\n\tREG_INTCONA = 0x08\n\tREG_INTCONB = 0x09\n\tREG_IOCON   = 0x0a\n\tREG_GPPUA   = 0x0c\n\tREG_GPPUB   = 0x0d\n\tREG_INTFA   = 0x0e\n\tREG_INTFB   = 0x0f\n\tREG_INTCAPA = 0x10\n\tREG_INTCAPB = 0x11\n\tREG_GPIOA   = 0x12\n\tREG_GPIOB   = 0x13\n\tREG_OLATA   = 0x14\n\tREG_OLATB   = 0x15\n)\n\ntype MCP23017 struct {\n\tdevice hwio.I2CDevice\n}\n\n\/\/ Create a new isntance, and set it to use Bank 0. The address can either be what is wired on\n\/\/ (A2,A1,A0) of the physical device, in which case this is added to the base address for the device\n\/\/ (0x20). Otherwise, you can use 0x20-0x27. Anything else will return an error.\nfunc NewMCP23017(module hwio.I2CModule, address int) (*MCP23017, error) {\n\tif address < 8 {\n\t\taddress += DEFAULT_BASE_ADDRESS\n\t}\n\n\tif address < 0x20 || address > 0x27 {\n\t\treturn nil, fmt.Errorf(\"Device address %d is invalid for an MCP23017. It must be in the range 0x20-0x27\", address)\n\t}\n\n\tdevice := module.GetDevice(address)\n\tresult := &MCP23017{device: device}\n\n\t\/\/ set config reg, force BANK=0, SEQOP=0. Note that this only works if already in BANK0, which is default on power-up\n\tdevice.WriteByte(REG_IOCON, 0)\n\n\treturn result, nil\n}\n\n\/\/ Set direction bits for port A. A 1 bit indicates corresponding pin will be an input,\n\/\/ A 0 bit indicates it will be an output.\nfunc (d *MCP23017) SetDirA(value byte) error {\n\treturn d.device.WriteByte(REG_IODIRA, value)\n}\n\n\/\/ Set direction bits for port A. A 1 bit indicates corresponding pin will be an input,\n\/\/ A 0 bit indicates it will be an output.\nfunc (d *MCP23017) SetDirB(value byte) error {\n\treturn d.device.WriteByte(REG_IODIRB, value)\n}\n\n\/\/ Read from port A\nfunc (d *MCP23017) GetPortA() (byte, error) {\n\treturn d.device.ReadByte(REG_GPIOA)\n}\n\n\/\/ Read from port B\nfunc (d *MCP23017) GetPortB() (byte, error) {\n\treturn d.device.ReadByte(REG_GPIOB)\n}\n\n\/\/ Write to port A\nfunc (d *MCP23017) SetPortA(value byte) error {\n\treturn d.device.WriteByte(REG_OLATA, value)\n}\n\n\/\/ Write to port B\nfunc (d *MCP23017) SetPortB(value byte) error {\n\treturn d.device.WriteByte(REG_OLATA, value)\n}\n\n\/\/ Set pull-up configuration for port A. If a bit is 1 and the corresponding pin is\n\/\/ an input, a pull-up resistor of about 100K is enabled. A zero bit indicates no pull-up.\nfunc (d *MCP23017) SetPullupA(value byte) error {\n\treturn d.device.WriteByte(REG_GPPUA, value)\n}\n\n\/\/ Set pull-up configuration for port B. If a bit is 1 and the corresponding pin is\n\/\/ an input, a pull-up resistor of about 100K is enabled. A zero bit indicates no pull-up.\nfunc (d *MCP23017) SetPullupB(value byte) error {\n\treturn d.device.WriteByte(REG_GPPUB, value)\n}\n<|endoftext|>"}
{"text":"<commit_before>package influxql\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/davecgh\/go-spew\/spew\"\n)\n\nimport \"sort\"\n\ntype point struct {\n\tseriesID uint64\n\ttime     int64\n\tvalue    interface{}\n}\n\ntype testIterator struct {\n\tvalues []point\n}\n\nfunc (t *testIterator) Next() (seriesID uint64, timestamp int64, value interface{}) {\n\tif len(t.values) > 0 {\n\t\tv := t.values[0]\n\t\tt.values = t.values[1:]\n\t\treturn v.seriesID, v.time, v.value\n\t}\n\n\treturn 0, 0, nil\n}\n\nfunc TestMapMeanNoValues(t *testing.T) {\n\titer := &testIterator{}\n\tif got := MapMean(iter); got != nil {\n\t\tt.Errorf(\"output mismatch: exp nil got %v\", got)\n\t}\n}\n\nfunc TestMapMean(t *testing.T) {\n\n\ttests := []struct {\n\t\tinput  []point\n\t\toutput *meanMapOutput\n\t}{\n\t\t{ \/\/ Single point\n\t\t\tinput:  []point{point{0, 1, 1.0}},\n\t\t\toutput: &meanMapOutput{1, 1},\n\t\t},\n\t\t{ \/\/ Two points\n\t\t\tinput: []point{\n\t\t\t\tpoint{0, 1, 2.0},\n\t\t\t\tpoint{0, 2, 8.0},\n\t\t\t},\n\t\t\toutput: &meanMapOutput{2, 5.0},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\titer := &testIterator{\n\t\t\tvalues: test.input,\n\t\t}\n\n\t\tgot := MapMean(iter)\n\t\tif got == nil {\n\t\t\tt.Fatalf(\"MapMean(%v): output mismatch: exp %v got %v\", test.input, test.output, got)\n\t\t}\n\n\t\tif got.(*meanMapOutput).Count != test.output.Count || got.(*meanMapOutput).Mean != test.output.Mean {\n\t\t\tt.Errorf(\"output mismatch: exp %v got %v\", test.output, got)\n\t\t}\n\t}\n}\nfunc TestInitializeMapFuncPercentile(t *testing.T) {\n\t\/\/ No args\n\tc := &Call{\n\t\tName: \"percentile\",\n\t\tArgs: []Expr{},\n\t}\n\t_, err := InitializeMapFunc(c)\n\tif err == nil {\n\t\tt.Errorf(\"InitializeMapFunc(%v) expected error. got nil\", c)\n\t}\n\n\tif exp := \"expected two arguments for percentile()\"; err.Error() != exp {\n\t\tt.Errorf(\"InitializeMapFunc(%v) mismatch. exp %v got %v\", c, exp, err.Error())\n\t}\n\n\t\/\/ No percentile arg\n\tc = &Call{\n\t\tName: \"percentile\",\n\t\tArgs: []Expr{\n\t\t\t&VarRef{Val: \"field1\"},\n\t\t},\n\t}\n\n\t_, err = InitializeMapFunc(c)\n\tif err == nil {\n\t\tt.Errorf(\"InitializeMapFunc(%v) expected error. got nil\", c)\n\t}\n\n\tif exp := \"expected two arguments for percentile()\"; err.Error() != exp {\n\t\tt.Errorf(\"InitializeMapFunc(%v) mismatch. exp %v got %v\", c, exp, err.Error())\n\t}\n}\n\nfunc TestInitializeMapFuncDerivative(t *testing.T) {\n\n\tfor _, fn := range []string{\"derivative\", \"non_negative_derivative\"} {\n\t\t\/\/ No args should fail\n\t\tc := &Call{\n\t\t\tName: fn,\n\t\t\tArgs: []Expr{},\n\t\t}\n\n\t\t_, err := InitializeMapFunc(c)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"InitializeMapFunc(%v) expected error.  got nil\", c)\n\t\t}\n\n\t\t\/\/ Single field arg should return MapEcho\n\t\tc = &Call{\n\t\t\tName: fn,\n\t\t\tArgs: []Expr{\n\t\t\t\t&VarRef{Val: \" field1\"},\n\t\t\t\t&DurationLiteral{Val: time.Hour},\n\t\t\t},\n\t\t}\n\n\t\t_, err = InitializeMapFunc(c)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"InitializeMapFunc(%v) unexpected error.  got %v\", c, err)\n\t\t}\n\n\t\t\/\/ Nested Aggregate func should return the map func for the nested aggregate\n\t\tc = &Call{\n\t\t\tName: fn,\n\t\t\tArgs: []Expr{\n\t\t\t\t&Call{Name: \"mean\", Args: []Expr{&VarRef{Val: \"field1\"}}},\n\t\t\t\t&DurationLiteral{Val: time.Hour},\n\t\t\t},\n\t\t}\n\n\t\t_, err = InitializeMapFunc(c)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"InitializeMapFunc(%v) unexpected error.  got %v\", c, err)\n\t\t}\n\t}\n}\n\nfunc TestInitializeReduceFuncPercentile(t *testing.T) {\n\t\/\/ No args\n\tc := &Call{\n\t\tName: \"percentile\",\n\t\tArgs: []Expr{},\n\t}\n\t_, err := InitializeReduceFunc(c)\n\tif err == nil {\n\t\tt.Errorf(\"InitializedReduceFunc(%v) expected error. got nil\", c)\n\t}\n\n\tif exp := \"expected float argument in percentile()\"; err.Error() != exp {\n\t\tt.Errorf(\"InitializedReduceFunc(%v) mismatch. exp %v got %v\", c, exp, err.Error())\n\t}\n\n\t\/\/ No percentile arg\n\tc = &Call{\n\t\tName: \"percentile\",\n\t\tArgs: []Expr{\n\t\t\t&VarRef{Val: \"field1\"},\n\t\t},\n\t}\n\n\t_, err = InitializeReduceFunc(c)\n\tif err == nil {\n\t\tt.Errorf(\"InitializedReduceFunc(%v) expected error. got nil\", c)\n\t}\n\n\tif exp := \"expected float argument in percentile()\"; err.Error() != exp {\n\t\tt.Errorf(\"InitializedReduceFunc(%v) mismatch. exp %v got %v\", c, exp, err.Error())\n\t}\n}\n\nfunc TestReducePercentileNil(t *testing.T) {\n\n\t\/\/ ReducePercentile should ignore nil values when calculating the percentile\n\tfn := ReducePercentile(100)\n\tinput := []interface{}{\n\t\tnil,\n\t}\n\n\tgot := fn(input)\n\tif got != nil {\n\t\tt.Fatalf(\"ReducePercentile(100) returned wrong type. exp nil got %v\", got)\n\t}\n}\n\nfunc TestMapDistinct(t *testing.T) {\n\tconst ( \/\/ prove that we're ignoring seriesID\n\t\tseriesId1 = iota + 1\n\t\tseriesId2\n\t)\n\n\tconst ( \/\/ prove that we're ignoring time\n\t\ttimeId1 = iota + 1\n\t\ttimeId2\n\t\ttimeId3\n\t\ttimeId4\n\t\ttimeId5\n\t\ttimeId6\n\t)\n\n\titer := &testIterator{\n\t\tvalues: []point{\n\t\t\t{seriesId1, timeId1, uint64(1)},\n\t\t\t{seriesId1, timeId2, uint64(1)},\n\t\t\t{seriesId1, timeId3, \"1\"},\n\t\t\t{seriesId2, timeId4, uint64(1)},\n\t\t\t{seriesId2, timeId5, float64(1.0)},\n\t\t\t{seriesId2, timeId6, \"1\"},\n\t\t},\n\t}\n\n\tvalues := MapDistinct(iter).(distinctValues)\n\n\tif exp, got := 3, len(values); exp != got {\n\t\tt.Errorf(\"Wrong number of values. exp %v got %v\", exp, got)\n\t}\n\n\tsort.Sort(values)\n\n\texp := distinctValues{\n\t\tuint64(1),\n\t\tfloat64(1),\n\t\t\"1\",\n\t}\n\n\tif !reflect.DeepEqual(values, exp) {\n\t\tt.Errorf(\"Wrong values. exp %v got %v\", spew.Sdump(exp), spew.Sdump(values))\n\t}\n}\n\nfunc TestMapDistinctNil(t *testing.T) {\n\titer := &testIterator{\n\t\tvalues: []point{},\n\t}\n\n\tvalues := MapDistinct(iter)\n\n\tif values != nil {\n\t\tt.Errorf(\"Wrong values. exp nil got %v\", spew.Sdump(values))\n\t}\n}\n\nfunc TestReduceDistinct(t *testing.T) {\n\tv1 := distinctValues{\n\t\t\"2\",\n\t\t\"1\",\n\t\tfloat64(2.0),\n\t\tfloat64(1),\n\t\tuint64(2),\n\t\tuint64(1),\n\t\ttrue,\n\t\tfalse,\n\t}\n\n\texpect := distinctValues{\n\t\tuint64(1),\n\t\tfloat64(1),\n\t\tuint64(2),\n\t\tfloat64(2),\n\t\tfalse,\n\t\ttrue,\n\t\t\"1\",\n\t\t\"2\",\n\t}\n\n\tgot := ReduceDistinct([]interface{}{v1, v1, expect})\n\n\tif !reflect.DeepEqual(got, expect) {\n\t\tt.Errorf(\"Wrong values. exp %v got %v\", spew.Sdump(expect), spew.Sdump(got))\n\t}\n}\n\nfunc TestReduceDistinctNil(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tvalues []interface{}\n\t}{\n\t\t{\n\t\t\tname:   \"nil values\",\n\t\t\tvalues: nil,\n\t\t},\n\t\t{\n\t\t\tname:   \"nil mapper\",\n\t\t\tvalues: []interface{}{nil},\n\t\t},\n\t\t{\n\t\t\tname:   \"no mappers\",\n\t\t\tvalues: []interface{}{},\n\t\t},\n\t\t{\n\t\t\tname:   \"empty mappper (len 1)\",\n\t\t\tvalues: []interface{}{distinctValues{}},\n\t\t},\n\t\t{\n\t\t\tname:   \"empty mappper (len 2)\",\n\t\t\tvalues: []interface{}{distinctValues{}, distinctValues{}},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Log(test.name)\n\t\tgot := ReduceDistinct(test.values)\n\t\tif got != nil {\n\t\t\tt.Errorf(\"Wrong values. exp nil got %v\", spew.Sdump(got))\n\t\t}\n\t}\n}\n\nfunc Test_distinctValues_Sort(t *testing.T) {\n\tvalues := distinctValues{\n\t\t\"2\",\n\t\t\"1\",\n\t\tfloat64(2.0),\n\t\tfloat64(1),\n\t\tuint64(2),\n\t\tuint64(1),\n\t\ttrue,\n\t\tfalse,\n\t}\n\n\texpect := distinctValues{\n\t\tuint64(1),\n\t\tfloat64(1),\n\t\tuint64(2),\n\t\tfloat64(2),\n\t\tfalse,\n\t\ttrue,\n\t\t\"1\",\n\t\t\"2\",\n\t}\n\n\tsort.Sort(values)\n\n\tif !reflect.DeepEqual(values, expect) {\n\t\tt.Errorf(\"Wrong values. exp %v got %v\", spew.Sdump(expect), spew.Sdump(values))\n\t}\n}\n\nvar getSortedRangeData = []float64{\n\t60, 61, 62, 63, 64, 65, 66, 67, 68, 69,\n\t20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n\t0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n\t40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\n\t10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n\t50, 51, 52, 53, 54, 55, 56, 57, 58, 59,\n\t30, 31, 32, 33, 34, 35, 36, 37, 38, 39,\n}\n\nvar getSortedRangeTests = []struct {\n\tname     string\n\tdata     []float64\n\tstart    int\n\tcount    int\n\texpected []float64\n}{\n\t{\"first 5\", getSortedRangeData, 0, 5, []float64{0, 1, 2, 3, 4}},\n\t{\"0 length\", getSortedRangeData, 8, 0, []float64{}},\n\t{\"past end of data\", getSortedRangeData, len(getSortedRangeData) - 3, 5, []float64{67, 68, 69}},\n}\n\nfunc TestGetSortedRange(t *testing.T) {\n\tfor _, tt := range getSortedRangeTests {\n\t\tresults := getSortedRange(tt.data, tt.start, tt.count)\n\t\tif len(results) != len(tt.expected) {\n\t\t\tt.Errorf(\"Test %s failed.  Expected getSortedRange to return %v but got %v\", tt.name, tt.expected, results)\n\t\t}\n\t\tfor i, point := range tt.expected {\n\t\t\tif point != results[i] {\n\t\t\t\tt.Errorf(\"Test %s failed. getSortedRange returned wrong result for index %v.  Expected %v but got %v\", tt.name, i, point, results[i])\n\t\t\t}\n\t\t}\n\t}\n}\n\nvar benchGetSortedRangeResults []float64\n\nfunc BenchmarkGetSortedRangeByPivot(b *testing.B) {\n\tdata := make([]float64, len(getSortedRangeData))\n\tvar results []float64\n\tfor i := 0; i < b.N; i++ {\n\t\tcopy(data, getSortedRangeData)\n\t\tresults = getSortedRange(data, 8, 15)\n\t}\n\tbenchGetSortedRangeResults = results\n}\n\nfunc BenchmarkGetSortedRangeBySort(b *testing.B) {\n\tdata := make([]float64, len(getSortedRangeData))\n\tvar results []float64\n\tfor i := 0; i < b.N; i++ {\n\t\tcopy(data, getSortedRangeData)\n\t\tsort.Float64s(data)\n\t\tresults = data[8:23]\n\t}\n\tbenchGetSortedRangeResults = results\n}\n<commit_msg>add MapCountDistinct\/ReduceCountDistinct function tests<commit_after>package influxql\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/davecgh\/go-spew\/spew\"\n)\n\nimport \"sort\"\n\ntype point struct {\n\tseriesID uint64\n\ttime     int64\n\tvalue    interface{}\n}\n\ntype testIterator struct {\n\tvalues []point\n}\n\nfunc (t *testIterator) Next() (seriesID uint64, timestamp int64, value interface{}) {\n\tif len(t.values) > 0 {\n\t\tv := t.values[0]\n\t\tt.values = t.values[1:]\n\t\treturn v.seriesID, v.time, v.value\n\t}\n\n\treturn 0, 0, nil\n}\n\nfunc TestMapMeanNoValues(t *testing.T) {\n\titer := &testIterator{}\n\tif got := MapMean(iter); got != nil {\n\t\tt.Errorf(\"output mismatch: exp nil got %v\", got)\n\t}\n}\n\nfunc TestMapMean(t *testing.T) {\n\n\ttests := []struct {\n\t\tinput  []point\n\t\toutput *meanMapOutput\n\t}{\n\t\t{ \/\/ Single point\n\t\t\tinput:  []point{point{0, 1, 1.0}},\n\t\t\toutput: &meanMapOutput{1, 1},\n\t\t},\n\t\t{ \/\/ Two points\n\t\t\tinput: []point{\n\t\t\t\tpoint{0, 1, 2.0},\n\t\t\t\tpoint{0, 2, 8.0},\n\t\t\t},\n\t\t\toutput: &meanMapOutput{2, 5.0},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\titer := &testIterator{\n\t\t\tvalues: test.input,\n\t\t}\n\n\t\tgot := MapMean(iter)\n\t\tif got == nil {\n\t\t\tt.Fatalf(\"MapMean(%v): output mismatch: exp %v got %v\", test.input, test.output, got)\n\t\t}\n\n\t\tif got.(*meanMapOutput).Count != test.output.Count || got.(*meanMapOutput).Mean != test.output.Mean {\n\t\t\tt.Errorf(\"output mismatch: exp %v got %v\", test.output, got)\n\t\t}\n\t}\n}\nfunc TestInitializeMapFuncPercentile(t *testing.T) {\n\t\/\/ No args\n\tc := &Call{\n\t\tName: \"percentile\",\n\t\tArgs: []Expr{},\n\t}\n\t_, err := InitializeMapFunc(c)\n\tif err == nil {\n\t\tt.Errorf(\"InitializeMapFunc(%v) expected error. got nil\", c)\n\t}\n\n\tif exp := \"expected two arguments for percentile()\"; err.Error() != exp {\n\t\tt.Errorf(\"InitializeMapFunc(%v) mismatch. exp %v got %v\", c, exp, err.Error())\n\t}\n\n\t\/\/ No percentile arg\n\tc = &Call{\n\t\tName: \"percentile\",\n\t\tArgs: []Expr{\n\t\t\t&VarRef{Val: \"field1\"},\n\t\t},\n\t}\n\n\t_, err = InitializeMapFunc(c)\n\tif err == nil {\n\t\tt.Errorf(\"InitializeMapFunc(%v) expected error. got nil\", c)\n\t}\n\n\tif exp := \"expected two arguments for percentile()\"; err.Error() != exp {\n\t\tt.Errorf(\"InitializeMapFunc(%v) mismatch. exp %v got %v\", c, exp, err.Error())\n\t}\n}\n\nfunc TestInitializeMapFuncDerivative(t *testing.T) {\n\n\tfor _, fn := range []string{\"derivative\", \"non_negative_derivative\"} {\n\t\t\/\/ No args should fail\n\t\tc := &Call{\n\t\t\tName: fn,\n\t\t\tArgs: []Expr{},\n\t\t}\n\n\t\t_, err := InitializeMapFunc(c)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"InitializeMapFunc(%v) expected error.  got nil\", c)\n\t\t}\n\n\t\t\/\/ Single field arg should return MapEcho\n\t\tc = &Call{\n\t\t\tName: fn,\n\t\t\tArgs: []Expr{\n\t\t\t\t&VarRef{Val: \" field1\"},\n\t\t\t\t&DurationLiteral{Val: time.Hour},\n\t\t\t},\n\t\t}\n\n\t\t_, err = InitializeMapFunc(c)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"InitializeMapFunc(%v) unexpected error.  got %v\", c, err)\n\t\t}\n\n\t\t\/\/ Nested Aggregate func should return the map func for the nested aggregate\n\t\tc = &Call{\n\t\t\tName: fn,\n\t\t\tArgs: []Expr{\n\t\t\t\t&Call{Name: \"mean\", Args: []Expr{&VarRef{Val: \"field1\"}}},\n\t\t\t\t&DurationLiteral{Val: time.Hour},\n\t\t\t},\n\t\t}\n\n\t\t_, err = InitializeMapFunc(c)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"InitializeMapFunc(%v) unexpected error.  got %v\", c, err)\n\t\t}\n\t}\n}\n\nfunc TestInitializeReduceFuncPercentile(t *testing.T) {\n\t\/\/ No args\n\tc := &Call{\n\t\tName: \"percentile\",\n\t\tArgs: []Expr{},\n\t}\n\t_, err := InitializeReduceFunc(c)\n\tif err == nil {\n\t\tt.Errorf(\"InitializedReduceFunc(%v) expected error. got nil\", c)\n\t}\n\n\tif exp := \"expected float argument in percentile()\"; err.Error() != exp {\n\t\tt.Errorf(\"InitializedReduceFunc(%v) mismatch. exp %v got %v\", c, exp, err.Error())\n\t}\n\n\t\/\/ No percentile arg\n\tc = &Call{\n\t\tName: \"percentile\",\n\t\tArgs: []Expr{\n\t\t\t&VarRef{Val: \"field1\"},\n\t\t},\n\t}\n\n\t_, err = InitializeReduceFunc(c)\n\tif err == nil {\n\t\tt.Errorf(\"InitializedReduceFunc(%v) expected error. got nil\", c)\n\t}\n\n\tif exp := \"expected float argument in percentile()\"; err.Error() != exp {\n\t\tt.Errorf(\"InitializedReduceFunc(%v) mismatch. exp %v got %v\", c, exp, err.Error())\n\t}\n}\n\nfunc TestReducePercentileNil(t *testing.T) {\n\n\t\/\/ ReducePercentile should ignore nil values when calculating the percentile\n\tfn := ReducePercentile(100)\n\tinput := []interface{}{\n\t\tnil,\n\t}\n\n\tgot := fn(input)\n\tif got != nil {\n\t\tt.Fatalf(\"ReducePercentile(100) returned wrong type. exp nil got %v\", got)\n\t}\n}\n\nfunc TestMapDistinct(t *testing.T) {\n\tconst ( \/\/ prove that we're ignoring seriesID\n\t\tseriesId1 = iota + 1\n\t\tseriesId2\n\t)\n\n\tconst ( \/\/ prove that we're ignoring time\n\t\ttimeId1 = iota + 1\n\t\ttimeId2\n\t\ttimeId3\n\t\ttimeId4\n\t\ttimeId5\n\t\ttimeId6\n\t)\n\n\titer := &testIterator{\n\t\tvalues: []point{\n\t\t\t{seriesId1, timeId1, uint64(1)},\n\t\t\t{seriesId1, timeId2, uint64(1)},\n\t\t\t{seriesId1, timeId3, \"1\"},\n\t\t\t{seriesId2, timeId4, uint64(1)},\n\t\t\t{seriesId2, timeId5, float64(1.0)},\n\t\t\t{seriesId2, timeId6, \"1\"},\n\t\t},\n\t}\n\n\tvalues := MapDistinct(iter).(distinctValues)\n\n\tif exp, got := 3, len(values); exp != got {\n\t\tt.Errorf(\"Wrong number of values. exp %v got %v\", exp, got)\n\t}\n\n\tsort.Sort(values)\n\n\texp := distinctValues{\n\t\tuint64(1),\n\t\tfloat64(1),\n\t\t\"1\",\n\t}\n\n\tif !reflect.DeepEqual(values, exp) {\n\t\tt.Errorf(\"Wrong values. exp %v got %v\", spew.Sdump(exp), spew.Sdump(values))\n\t}\n}\n\nfunc TestMapDistinctNil(t *testing.T) {\n\titer := &testIterator{\n\t\tvalues: []point{},\n\t}\n\n\tvalues := MapDistinct(iter)\n\n\tif values != nil {\n\t\tt.Errorf(\"Wrong values. exp nil got %v\", spew.Sdump(values))\n\t}\n}\n\nfunc TestReduceDistinct(t *testing.T) {\n\tv1 := distinctValues{\n\t\t\"2\",\n\t\t\"1\",\n\t\tfloat64(2.0),\n\t\tfloat64(1),\n\t\tuint64(2),\n\t\tuint64(1),\n\t\ttrue,\n\t\tfalse,\n\t}\n\n\texpect := distinctValues{\n\t\tuint64(1),\n\t\tfloat64(1),\n\t\tuint64(2),\n\t\tfloat64(2),\n\t\tfalse,\n\t\ttrue,\n\t\t\"1\",\n\t\t\"2\",\n\t}\n\n\tgot := ReduceDistinct([]interface{}{v1, v1, expect})\n\n\tif !reflect.DeepEqual(got, expect) {\n\t\tt.Errorf(\"Wrong values. exp %v got %v\", spew.Sdump(expect), spew.Sdump(got))\n\t}\n}\n\nfunc TestReduceDistinctNil(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tvalues []interface{}\n\t}{\n\t\t{\n\t\t\tname:   \"nil values\",\n\t\t\tvalues: nil,\n\t\t},\n\t\t{\n\t\t\tname:   \"nil mapper\",\n\t\t\tvalues: []interface{}{nil},\n\t\t},\n\t\t{\n\t\t\tname:   \"no mappers\",\n\t\t\tvalues: []interface{}{},\n\t\t},\n\t\t{\n\t\t\tname:   \"empty mappper (len 1)\",\n\t\t\tvalues: []interface{}{distinctValues{}},\n\t\t},\n\t\t{\n\t\t\tname:   \"empty mappper (len 2)\",\n\t\t\tvalues: []interface{}{distinctValues{}, distinctValues{}},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Log(test.name)\n\t\tgot := ReduceDistinct(test.values)\n\t\tif got != nil {\n\t\t\tt.Errorf(\"Wrong values. exp nil got %v\", spew.Sdump(got))\n\t\t}\n\t}\n}\n\nfunc Test_distinctValues_Sort(t *testing.T) {\n\tvalues := distinctValues{\n\t\t\"2\",\n\t\t\"1\",\n\t\tfloat64(2.0),\n\t\tfloat64(1),\n\t\tuint64(2),\n\t\tuint64(1),\n\t\ttrue,\n\t\tfalse,\n\t}\n\n\texpect := distinctValues{\n\t\tuint64(1),\n\t\tfloat64(1),\n\t\tuint64(2),\n\t\tfloat64(2),\n\t\tfalse,\n\t\ttrue,\n\t\t\"1\",\n\t\t\"2\",\n\t}\n\n\tsort.Sort(values)\n\n\tif !reflect.DeepEqual(values, expect) {\n\t\tt.Errorf(\"Wrong values. exp %v got %v\", spew.Sdump(expect), spew.Sdump(values))\n\t}\n}\n\nfunc TestMapCountDistinct(t *testing.T) {\n\tconst ( \/\/ prove that we're ignoring seriesID\n\t\tseriesId1 = iota + 1\n\t\tseriesId2\n\t)\n\n\tconst ( \/\/ prove that we're ignoring time\n\t\ttimeId1 = iota + 1\n\t\ttimeId2\n\t\ttimeId3\n\t\ttimeId4\n\t\ttimeId5\n\t\ttimeId6\n\t\ttimeId7\n\t)\n\n\titer := &testIterator{\n\t\tvalues: []point{\n\t\t\t{seriesId1, timeId1, uint64(1)},\n\t\t\t{seriesId1, timeId2, uint64(1)},\n\t\t\t{seriesId1, timeId3, \"1\"},\n\t\t\t{seriesId2, timeId4, uint64(1)},\n\t\t\t{seriesId2, timeId5, float64(1.0)},\n\t\t\t{seriesId2, timeId6, \"1\"},\n\t\t\t{seriesId2, timeId7, true},\n\t\t},\n\t}\n\n\tvalues := MapCountDistinct(iter).(map[interface{}]struct{})\n\n\tif exp, got := 4, len(values); exp != got {\n\t\tt.Errorf(\"Wrong number of values. exp %v got %v\", exp, got)\n\t}\n\n\texp := map[interface{}]struct{}{\n\t\tuint64(1):  struct{}{},\n\t\tfloat64(1): struct{}{},\n\t\t\"1\":        struct{}{},\n\t\ttrue:       struct{}{},\n\t}\n\n\tif !reflect.DeepEqual(values, exp) {\n\t\tt.Errorf(\"Wrong values. exp %v got %v\", spew.Sdump(exp), spew.Sdump(values))\n\t}\n}\n\nfunc TestMapCountDistinctNil(t *testing.T) {\n\titer := &testIterator{\n\t\tvalues: []point{},\n\t}\n\n\tvalues := MapCountDistinct(iter)\n\n\tif values != nil {\n\t\tt.Errorf(\"Wrong values. exp nil got %v\", spew.Sdump(values))\n\t}\n}\n\nfunc TestReduceCountDistinct(t *testing.T) {\n\tv1 := map[interface{}]struct{}{\n\t\t\"2\":          struct{}{},\n\t\t\"1\":          struct{}{},\n\t\tfloat64(2.0): struct{}{},\n\t\tfloat64(1):   struct{}{},\n\t\tuint64(2):    struct{}{},\n\t\tuint64(1):    struct{}{},\n\t\ttrue:         struct{}{},\n\t\tfalse:        struct{}{},\n\t}\n\n\tv2 := map[interface{}]struct{}{\n\t\tuint64(1):  struct{}{},\n\t\tfloat64(1): struct{}{},\n\t\tuint64(2):  struct{}{},\n\t\tfloat64(2): struct{}{},\n\t\tfalse:      struct{}{},\n\t\ttrue:       struct{}{},\n\t\t\"1\":        struct{}{},\n\t\t\"2\":        struct{}{},\n\t}\n\n\texp := 8\n\tgot := ReduceCountDistinct([]interface{}{v1, v1, v2})\n\n\tif !reflect.DeepEqual(got, exp) {\n\t\tt.Errorf(\"Wrong values. exp %v got %v\", spew.Sdump(exp), spew.Sdump(got))\n\t}\n}\n\nfunc TestReduceCountDistinctNil(t *testing.T) {\n\temptyResults := make(map[interface{}]struct{})\n\ttests := []struct {\n\t\tname   string\n\t\tvalues []interface{}\n\t}{\n\t\t{\n\t\t\tname:   \"nil values\",\n\t\t\tvalues: nil,\n\t\t},\n\t\t{\n\t\t\tname:   \"nil mapper\",\n\t\t\tvalues: []interface{}{nil},\n\t\t},\n\t\t{\n\t\t\tname:   \"no mappers\",\n\t\t\tvalues: []interface{}{},\n\t\t},\n\t\t{\n\t\t\tname:   \"empty mappper (len 1)\",\n\t\t\tvalues: []interface{}{emptyResults},\n\t\t},\n\t\t{\n\t\t\tname:   \"empty mappper (len 2)\",\n\t\t\tvalues: []interface{}{emptyResults, emptyResults},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Log(test.name)\n\t\tgot := ReduceCountDistinct(test.values)\n\t\tif got != 0 {\n\t\t\tt.Errorf(\"Wrong values. exp nil got %v\", spew.Sdump(got))\n\t\t}\n\t}\n}\n\nvar getSortedRangeData = []float64{\n\t60, 61, 62, 63, 64, 65, 66, 67, 68, 69,\n\t20, 21, 22, 23, 24, 25, 26, 27, 28, 29,\n\t0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n\t40, 41, 42, 43, 44, 45, 46, 47, 48, 49,\n\t10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n\t50, 51, 52, 53, 54, 55, 56, 57, 58, 59,\n\t30, 31, 32, 33, 34, 35, 36, 37, 38, 39,\n}\n\nvar getSortedRangeTests = []struct {\n\tname     string\n\tdata     []float64\n\tstart    int\n\tcount    int\n\texpected []float64\n}{\n\t{\"first 5\", getSortedRangeData, 0, 5, []float64{0, 1, 2, 3, 4}},\n\t{\"0 length\", getSortedRangeData, 8, 0, []float64{}},\n\t{\"past end of data\", getSortedRangeData, len(getSortedRangeData) - 3, 5, []float64{67, 68, 69}},\n}\n\nfunc TestGetSortedRange(t *testing.T) {\n\tfor _, tt := range getSortedRangeTests {\n\t\tresults := getSortedRange(tt.data, tt.start, tt.count)\n\t\tif len(results) != len(tt.expected) {\n\t\t\tt.Errorf(\"Test %s failed.  Expected getSortedRange to return %v but got %v\", tt.name, tt.expected, results)\n\t\t}\n\t\tfor i, point := range tt.expected {\n\t\t\tif point != results[i] {\n\t\t\t\tt.Errorf(\"Test %s failed. getSortedRange returned wrong result for index %v.  Expected %v but got %v\", tt.name, i, point, results[i])\n\t\t\t}\n\t\t}\n\t}\n}\n\nvar benchGetSortedRangeResults []float64\n\nfunc BenchmarkGetSortedRangeByPivot(b *testing.B) {\n\tdata := make([]float64, len(getSortedRangeData))\n\tvar results []float64\n\tfor i := 0; i < b.N; i++ {\n\t\tcopy(data, getSortedRangeData)\n\t\tresults = getSortedRange(data, 8, 15)\n\t}\n\tbenchGetSortedRangeResults = results\n}\n\nfunc BenchmarkGetSortedRangeBySort(b *testing.B) {\n\tdata := make([]float64, len(getSortedRangeData))\n\tvar results []float64\n\tfor i := 0; i < b.N; i++ {\n\t\tcopy(data, getSortedRangeData)\n\t\tsort.Float64s(data)\n\t\tresults = data[8:23]\n\t}\n\tbenchGetSortedRangeResults = results\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright 2018 The Bazel Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage golang\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/bazelbuild\/bazel-gazelle\/label\"\n\t\"github.com\/bazelbuild\/bazel-gazelle\/language\"\n\t\"github.com\/bazelbuild\/bazel-gazelle\/rule\"\n)\n\nfunc importReposFromModules(args language.ImportReposArgs) language.ImportReposResult {\n\tdir := filepath.Dir(args.Path)\n\n\t\/\/ List all modules except for the main module, including implicit indirect\n\t\/\/ dependencies.\n\ttype module struct {\n\t\tPath, Version, Sum string\n\t\tMain               bool\n\t\tReplace            *struct {\n\t\t\tPath, Version string\n\t\t}\n\t}\n\t\/\/ path@version can be used as a unique identifier for looking up sums\n\tpathToModule := map[string]*module{}\n\tdata, err := goListModules(dir)\n\tif err != nil {\n\t\treturn language.ImportReposResult{Error: err}\n\t}\n\tdec := json.NewDecoder(bytes.NewReader(data))\n\tfor dec.More() {\n\t\tmod := new(module)\n\t\tif err := dec.Decode(mod); err != nil {\n\t\t\treturn language.ImportReposResult{Error: err}\n\t\t}\n\t\tif mod.Main {\n\t\t\tcontinue\n\t\t}\n\t\tif mod.Replace != nil {\n\t\t\tif filepath.IsAbs(mod.Replace.Path) || build.IsLocalImport(mod.Replace.Path) {\n\t\t\t\tlog.Printf(\"go_repository does not support file path replacements for %s -> %s\", mod.Path,\n\t\t\t\t\tmod.Replace.Path)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpathToModule[mod.Replace.Path+\"@\"+mod.Replace.Version] = mod\n\t\t} else {\n\t\t\tpathToModule[mod.Path+\"@\"+mod.Version] = mod\n\t\t}\n\t}\n\n\t\/\/ Load sums from go.sum. Ideally, they're all there.\n\tgoSumPath := filepath.Join(filepath.Dir(args.Path), \"go.sum\")\n\tdata, _ = ioutil.ReadFile(goSumPath)\n\tlines := bytes.Split(data, []byte(\"\\n\"))\n\tfor _, line := range lines {\n\t\tline = bytes.TrimSpace(line)\n\t\tfields := bytes.Fields(line)\n\t\tif len(fields) != 3 {\n\t\t\tcontinue\n\t\t}\n\t\tpath, version, sum := string(fields[0]), string(fields[1]), string(fields[2])\n\t\tif strings.HasSuffix(version, \"\/go.mod\") {\n\t\t\tcontinue\n\t\t}\n\t\tif mod, ok := pathToModule[path+\"@\"+version]; ok {\n\t\t\tmod.Sum = sum\n\t\t}\n\t}\n\n\t\/\/ If sums are missing, run 'go mod download' to get them.\n\t\/\/ This must be done in a temporary directory because 'go mod download'\n\t\/\/ may modify go.mod and go.sum. It does not support -mod=readonly.\n\tvar missingSumArgs []string\n\tfor pathVer, mod := range pathToModule {\n\t\tif mod.Sum == \"\" {\n\t\t\tmissingSumArgs = append(missingSumArgs, pathVer)\n\t\t}\n\t}\n\n\tif len(missingSumArgs) > 0 {\n\t\ttmpDir, err := ioutil.TempDir(\"\", \"\")\n\t\tif err != nil {\n\t\t\treturn language.ImportReposResult{Error: fmt.Errorf(\"finding module sums: %v\", err)}\n\t\t}\n\t\tdefer os.RemoveAll(tmpDir)\n\t\tdata, err := goModDownload(tmpDir, missingSumArgs)\n\t\tif err != nil {\n\t\t\treturn language.ImportReposResult{Error: err}\n\t\t}\n\t\tdec = json.NewDecoder(bytes.NewReader(data))\n\t\tfor dec.More() {\n\t\t\tvar dl module\n\t\t\tif err := dec.Decode(&dl); err != nil {\n\t\t\t\treturn language.ImportReposResult{Error: err}\n\t\t\t}\n\t\t\tif mod, ok := pathToModule[dl.Path+\"@\"+dl.Version]; ok {\n\t\t\t\tmod.Sum = dl.Sum\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Translate to repository rules.\n\tgen := make([]*rule.Rule, 0, len(pathToModule))\n\tfor pathVer, mod := range pathToModule {\n\t\tif mod.Sum == \"\" {\n\t\t\tlog.Printf(\"could not determine sum for module %s\", pathVer)\n\t\t\tcontinue\n\t\t}\n\t\tr := rule.NewRule(\"go_repository\", label.ImportPathToBazelRepoName(mod.Path))\n\t\tr.SetAttr(\"importpath\", mod.Path)\n\t\tr.SetAttr(\"sum\", mod.Sum)\n\t\tif mod.Replace == nil {\n\t\t\tr.SetAttr(\"version\", mod.Version)\n\t\t} else {\n\t\t\tr.SetAttr(\"replace\", mod.Replace.Path)\n\t\t\tr.SetAttr(\"version\", mod.Replace.Version)\n\t\t}\n\t\tgen = append(gen, r)\n\t}\n\tsort.Slice(gen, func(i, j int) bool {\n\t\treturn gen[i].Name() < gen[j].Name()\n\t})\n\treturn language.ImportReposResult{Gen: gen}\n}\n\n\/\/ goListModules invokes \"go list\" in a directory containing a go.mod file.\nvar goListModules = func(dir string) ([]byte, error) {\n\treturn runGoCommandForOutput(dir, \"list\", \"-mod=readonly\", \"-m\", \"-json\", \"all\")\n}\n\n\/\/ goModDownload invokes \"go mod download\" in a directory containing a\n\/\/ go.mod file.\nvar goModDownload = func(dir string, args []string) ([]byte, error) {\n\tdlArgs := []string{\"mod\", \"download\", \"-json\"}\n\tdlArgs = append(dlArgs, args...)\n\treturn runGoCommandForOutput(dir, dlArgs...)\n}\n\n\/\/ findGoTool attempts to locate the go executable. If GOROOT is set, we'll\n\/\/ prefer the one in there; otherwise, we'll rely on PATH. If the wrapper\n\/\/ script generated by the gazelle rule is invoked by Bazel, it will set\n\/\/ GOROOT to the configured SDK. We don't want to rely on the host SDK in\n\/\/ that situation.\nfunc findGoTool() string {\n\tpath := \"go\" \/\/ rely on PATH by default\n\tif goroot, ok := os.LookupEnv(\"GOROOT\"); ok {\n\t\tpath = filepath.Join(goroot, \"bin\", \"go\")\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\tpath += \".exe\"\n\t}\n\treturn path\n}\n\nfunc runGoCommandForOutput(dir string, args ...string) ([]byte, error) {\n\tgoTool := findGoTool()\n\tenv := os.Environ()\n\tenv = append(env, \"GO111MODULE=on\")\n\tif os.Getenv(\"GOCACHE\") == \"\" && os.Getenv(\"HOME\") == \"\" {\n\t\tgocache, err := ioutil.TempDir(\"\", \"\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tenv = append(env, \"GOCACHE=\"+gocache)\n\t\tdefer os.RemoveAll(gocache)\n\t}\n\tif os.Getenv(\"GOPATH\") == \"\" && os.Getenv(\"HOME\") == \"\" {\n\t\tgopath, err := ioutil.TempDir(\"\", \"\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tenv = append(env, \"GOPATH=\"+gopath)\n\t\tdefer os.RemoveAll(gopath)\n\t}\n\tcmd := exec.Command(goTool, args...)\n\tstderr := &bytes.Buffer{}\n\tcmd.Stderr = stderr\n\tcmd.Dir = dir\n\tcmd.Env = env\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\tvar errStr string\n\t\tvar xerr *exec.ExitError\n\t\tif errors.As(err, &xerr) {\n\t\t\terrStr = strings.TrimSpace(stderr.String())\n\t\t} else {\n\t\t\terrStr = err.Error()\n\t\t}\n\t\treturn nil, fmt.Errorf(\"running '%s %s': %s\", cmd.Path, strings.Join(cmd.Args, \" \"), errStr)\n\t}\n\treturn out, nil\n}\n<commit_msg>gazelle: add -e flag for go list 1.16 (#1019)<commit_after>\/* Copyright 2018 The Bazel Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage golang\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"go\/build\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/bazelbuild\/bazel-gazelle\/label\"\n\t\"github.com\/bazelbuild\/bazel-gazelle\/language\"\n\t\"github.com\/bazelbuild\/bazel-gazelle\/rule\"\n)\n\nfunc importReposFromModules(args language.ImportReposArgs) language.ImportReposResult {\n\tdir := filepath.Dir(args.Path)\n\n\t\/\/ List all modules except for the main module, including implicit indirect\n\t\/\/ dependencies.\n\ttype module struct {\n\t\tPath, Version, Sum string\n\t\tMain               bool\n\t\tReplace            *struct {\n\t\t\tPath, Version string\n\t\t}\n\t}\n\t\/\/ path@version can be used as a unique identifier for looking up sums\n\tpathToModule := map[string]*module{}\n\tdata, err := goListModules(dir)\n\tif err != nil {\n\t\treturn language.ImportReposResult{Error: err}\n\t}\n\tdec := json.NewDecoder(bytes.NewReader(data))\n\tfor dec.More() {\n\t\tmod := new(module)\n\t\tif err := dec.Decode(mod); err != nil {\n\t\t\treturn language.ImportReposResult{Error: err}\n\t\t}\n\t\tif mod.Main {\n\t\t\tcontinue\n\t\t}\n\t\tif mod.Replace != nil {\n\t\t\tif filepath.IsAbs(mod.Replace.Path) || build.IsLocalImport(mod.Replace.Path) {\n\t\t\t\tlog.Printf(\"go_repository does not support file path replacements for %s -> %s\", mod.Path,\n\t\t\t\t\tmod.Replace.Path)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpathToModule[mod.Replace.Path+\"@\"+mod.Replace.Version] = mod\n\t\t} else {\n\t\t\tpathToModule[mod.Path+\"@\"+mod.Version] = mod\n\t\t}\n\t}\n\n\t\/\/ Load sums from go.sum. Ideally, they're all there.\n\tgoSumPath := filepath.Join(filepath.Dir(args.Path), \"go.sum\")\n\tdata, _ = ioutil.ReadFile(goSumPath)\n\tlines := bytes.Split(data, []byte(\"\\n\"))\n\tfor _, line := range lines {\n\t\tline = bytes.TrimSpace(line)\n\t\tfields := bytes.Fields(line)\n\t\tif len(fields) != 3 {\n\t\t\tcontinue\n\t\t}\n\t\tpath, version, sum := string(fields[0]), string(fields[1]), string(fields[2])\n\t\tif strings.HasSuffix(version, \"\/go.mod\") {\n\t\t\tcontinue\n\t\t}\n\t\tif mod, ok := pathToModule[path+\"@\"+version]; ok {\n\t\t\tmod.Sum = sum\n\t\t}\n\t}\n\n\t\/\/ If sums are missing, run 'go mod download' to get them.\n\t\/\/ This must be done in a temporary directory because 'go mod download'\n\t\/\/ may modify go.mod and go.sum. It does not support -mod=readonly.\n\tvar missingSumArgs []string\n\tfor pathVer, mod := range pathToModule {\n\t\tif mod.Sum == \"\" {\n\t\t\tmissingSumArgs = append(missingSumArgs, pathVer)\n\t\t}\n\t}\n\n\tif len(missingSumArgs) > 0 {\n\t\ttmpDir, err := ioutil.TempDir(\"\", \"\")\n\t\tif err != nil {\n\t\t\treturn language.ImportReposResult{Error: fmt.Errorf(\"finding module sums: %v\", err)}\n\t\t}\n\t\tdefer os.RemoveAll(tmpDir)\n\t\tdata, err := goModDownload(tmpDir, missingSumArgs)\n\t\tif err != nil {\n\t\t\treturn language.ImportReposResult{Error: err}\n\t\t}\n\t\tdec = json.NewDecoder(bytes.NewReader(data))\n\t\tfor dec.More() {\n\t\t\tvar dl module\n\t\t\tif err := dec.Decode(&dl); err != nil {\n\t\t\t\treturn language.ImportReposResult{Error: err}\n\t\t\t}\n\t\t\tif mod, ok := pathToModule[dl.Path+\"@\"+dl.Version]; ok {\n\t\t\t\tmod.Sum = dl.Sum\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Translate to repository rules.\n\tgen := make([]*rule.Rule, 0, len(pathToModule))\n\tfor pathVer, mod := range pathToModule {\n\t\tif mod.Sum == \"\" {\n\t\t\tlog.Printf(\"could not determine sum for module %s\", pathVer)\n\t\t\tcontinue\n\t\t}\n\t\tr := rule.NewRule(\"go_repository\", label.ImportPathToBazelRepoName(mod.Path))\n\t\tr.SetAttr(\"importpath\", mod.Path)\n\t\tr.SetAttr(\"sum\", mod.Sum)\n\t\tif mod.Replace == nil {\n\t\t\tr.SetAttr(\"version\", mod.Version)\n\t\t} else {\n\t\t\tr.SetAttr(\"replace\", mod.Replace.Path)\n\t\t\tr.SetAttr(\"version\", mod.Replace.Version)\n\t\t}\n\t\tgen = append(gen, r)\n\t}\n\tsort.Slice(gen, func(i, j int) bool {\n\t\treturn gen[i].Name() < gen[j].Name()\n\t})\n\treturn language.ImportReposResult{Gen: gen}\n}\n\n\/\/ goListModules invokes \"go list\" in a directory containing a go.mod file.\nvar goListModules = func(dir string) ([]byte, error) {\n\treturn runGoCommandForOutput(dir, \"list\", \"-mod=readonly\", \"-e\", \"-m\", \"-json\", \"all\")\n}\n\n\/\/ goModDownload invokes \"go mod download\" in a directory containing a\n\/\/ go.mod file.\nvar goModDownload = func(dir string, args []string) ([]byte, error) {\n\tdlArgs := []string{\"mod\", \"download\", \"-json\"}\n\tdlArgs = append(dlArgs, args...)\n\treturn runGoCommandForOutput(dir, dlArgs...)\n}\n\n\/\/ findGoTool attempts to locate the go executable. If GOROOT is set, we'll\n\/\/ prefer the one in there; otherwise, we'll rely on PATH. If the wrapper\n\/\/ script generated by the gazelle rule is invoked by Bazel, it will set\n\/\/ GOROOT to the configured SDK. We don't want to rely on the host SDK in\n\/\/ that situation.\nfunc findGoTool() string {\n\tpath := \"go\" \/\/ rely on PATH by default\n\tif goroot, ok := os.LookupEnv(\"GOROOT\"); ok {\n\t\tpath = filepath.Join(goroot, \"bin\", \"go\")\n\t}\n\tif runtime.GOOS == \"windows\" {\n\t\tpath += \".exe\"\n\t}\n\treturn path\n}\n\nfunc runGoCommandForOutput(dir string, args ...string) ([]byte, error) {\n\tgoTool := findGoTool()\n\tenv := os.Environ()\n\tenv = append(env, \"GO111MODULE=on\")\n\tif os.Getenv(\"GOCACHE\") == \"\" && os.Getenv(\"HOME\") == \"\" {\n\t\tgocache, err := ioutil.TempDir(\"\", \"\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tenv = append(env, \"GOCACHE=\"+gocache)\n\t\tdefer os.RemoveAll(gocache)\n\t}\n\tif os.Getenv(\"GOPATH\") == \"\" && os.Getenv(\"HOME\") == \"\" {\n\t\tgopath, err := ioutil.TempDir(\"\", \"\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tenv = append(env, \"GOPATH=\"+gopath)\n\t\tdefer os.RemoveAll(gopath)\n\t}\n\tcmd := exec.Command(goTool, args...)\n\tstderr := &bytes.Buffer{}\n\tcmd.Stderr = stderr\n\tcmd.Dir = dir\n\tcmd.Env = env\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\tvar errStr string\n\t\tvar xerr *exec.ExitError\n\t\tif errors.As(err, &xerr) {\n\t\t\terrStr = strings.TrimSpace(stderr.String())\n\t\t} else {\n\t\t\terrStr = err.Error()\n\t\t}\n\t\treturn nil, fmt.Errorf(\"running '%s %s': %s\", cmd.Path, strings.Join(cmd.Args, \" \"), errStr)\n\t}\n\treturn out, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package build\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"koding\/kite\/kd\/util\"\n\t\"koding\/tools\/deps\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"text\/template\"\n\n\t\"github.com\/fatih\/file\"\n)\n\ntype Build struct {\n\tappName    string\n\tversion    string\n\toutput     string\n\tbinaryPath string\n\timportPath string\n\tfiles      string\n}\n\nfunc NewBuild() *Build {\n\treturn &Build{}\n}\n\nfunc (b *Build) Definition() string {\n\treturn \"Build deployable install packages\"\n}\n\nfunc (b *Build) Exec(args []string) error {\n\tusage := \"Usage: kd build --import <importPath> || --bin <binaryPath> --files <filesPath>\"\n\tif len(args) == 0 {\n\t\treturn errors.New(usage)\n\t}\n\n\tf := flag.NewFlagSet(\"build\", flag.ContinueOnError)\n\tf.StringVar(&b.importPath, \"import\", \"\", \"Go importpath to be packaged\")\n\tf.StringVar(&b.binaryPath, \"bin\", \"\", \"Binary to be packaged\")\n\tf.StringVar(&b.files, \"files\", \"\", \"Files to be included with the package\")\n\tf.Parse(args)\n\n\tif b.binaryPath != \"\" {\n\t\tb.appName = filepath.Base(b.binaryPath)\n\t} else if b.importPath != \"\" {\n\t\tb.appName = filepath.Base(b.importPath)\n\t} else {\n\t\treturn errors.New(\"build: --import or --bin should be defined.\")\n\t}\n\n\tb.version = \"0.0.1\"\n\tb.output = fmt.Sprintf(\"%s.%s-%s\", b.appName, runtime.GOOS, runtime.GOARCH)\n\n\terr := b.do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (b *Build) do() error {\n\tswitch runtime.GOOS {\n\tcase \"darwin\":\n\t\terr := b.darwin()\n\t\tif err != nil {\n\t\t\tlog.Println(\"darwin:\", err)\n\t\t}\n\tcase \"linux\":\n\t\terr := b.linux()\n\t\tif err != nil {\n\t\t\tlog.Println(\"linux:\", err)\n\t\t}\n\t}\n\n\t\/\/ also create a tar.gz regardless of os\n\treturn b.tarGzFile()\n}\n\nfunc (b *Build) linux() error {\n\treturn nil\n}\n\nfunc (b *Build) tarGzFile() error {\n\tbuildFolder, err := ioutil.TempDir(\".\", \"kd-build\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(buildFolder)\n\n\tif b.importPath != \"\" {\n\t\tgopath := os.Getenv(\"GOPATH\")\n\t\tif gopath == \"\" {\n\t\t\treturn errors.New(\"GOPATH is not set\")\n\t\t}\n\n\t\t\/\/ or use \"go list koding\/...\" for all packages and commands\n\t\tpackages := []string{b.importPath}\n\t\td, err := deps.LoadDeps(packages...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = d.InstallDeps()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuildFolder = filepath.Join(d.BuildGoPath, b.appName)\n\t} else {\n\t\terr := file.Copy(b.binaryPath, buildFolder)\n\t\tif err != nil {\n\t\t\tlog.Println(\"copy assets\", err)\n\t\t}\n\t}\n\n\t\/\/ copy package files, such as templates\n\tif b.files != \"\" {\n\t\terr := file.Copy(b.files, buildFolder)\n\t\tif err != nil {\n\t\t\tlog.Println(\"copy assets\", err)\n\t\t}\n\t}\n\n\t\/\/ create tar.gz file from final director\n\ttarFile := fmt.Sprintf(\"%s.%s-%s.tar.gz\", b.appName, runtime.GOOS, runtime.GOARCH)\n\terr = util.MakeTar(tarFile, buildFolder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"'%s' is created and ready for deploy\\n\", tarFile)\n\treturn nil\n}\n\n\/\/ darwin is building a new .pkg installer for darwin based OS'es.\nfunc (b *Build) darwin() error {\n\tversion := b.version\n\tif b.output == \"\" {\n\t\tb.output = fmt.Sprintf(\"koding-%s\", b.appName)\n\t}\n\n\tscriptDir := \"build\/darwin\/scripts\"\n\tinstallRoot := \".\/root\" \/\/ TODO REMOVE\n\n\tos.RemoveAll(installRoot) \/\/ clean up old build before we continue\n\tinstallRootUsr := filepath.Join(installRoot, \"\/usr\/local\/bin\")\n\n\tos.MkdirAll(installRootUsr, 0755)\n\terr := util.CopyFile(b.binaryPath, installRootUsr+\"\/\"+b.appName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttempDest, err := ioutil.TempDir(\"\", \"tempDest\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(tempDest)\n\n\tb.createScripts(scriptDir)\n\tb.createLaunchAgent(installRoot)\n\n\tcmdPkg := exec.Command(\"pkgbuild\",\n\t\t\"--identifier\", fmt.Sprintf(\"com.koding.kite.%s.pkg\", b.appName),\n\t\t\"--version\", version,\n\t\t\"--scripts\", scriptDir,\n\t\t\"--root\", installRoot,\n\t\t\"--install-location\", \"\/\",\n\t\tfmt.Sprintf(\"%s\/com.koding.kite.%s.pkg\", tempDest, b.appName),\n\t\t\/\/ used for next step, also set up for distribution.xml\n\t)\n\n\t_, err = cmdPkg.CombinedOutput()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdistributionFile := \"build\/darwin\/Distribution.xml\"\n\tresources := \"build\/darwin\/Resources\"\n\ttargetFile := b.output + \".pkg\"\n\n\tb.createDistribution(distributionFile)\n\n\tcmdBuild := exec.Command(\"productbuild\",\n\t\t\"--distribution\", distributionFile,\n\t\t\"--resources\", resources,\n\t\t\"--package-path\", tempDest,\n\t\ttargetFile,\n\t)\n\n\t_, err = cmdBuild.CombinedOutput()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"'%s' is created and ready for deploy\\n\", targetFile)\n\treturn nil\n}\n\nfunc (b *Build) createLaunchAgent(rootDir string) {\n\tlaunchDir := fmt.Sprintf(\"%s\/Library\/LaunchAgents\/\", rootDir)\n\tos.MkdirAll(launchDir, 0700)\n\n\tlaunchFile := fmt.Sprintf(\"%s\/com.koding.kite.%s.plist\", launchDir, b.appName)\n\n\tlFile, err := os.Create(launchFile)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tt := template.Must(template.New(\"launchAgent\").Parse(launchAgent))\n\tt.Execute(lFile, b.appName)\n\n}\n\nfunc (b *Build) createDistribution(file string) {\n\tdistFile, err := os.Create(file)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tt := template.Must(template.New(\"distribution\").Parse(distribution))\n\tt.Execute(distFile, b.appName)\n\n}\n\nfunc (b *Build) createScripts(scriptDir string) {\n\tos.MkdirAll(scriptDir, 0700) \/\/ does return nil if exists\n\n\tpostInstallFile, err := os.Create(scriptDir + \"\/postInstall\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tpostInstallFile.Chmod(0755)\n\n\tpreInstallFile, err := os.Create(scriptDir + \"\/preInstall\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tpreInstallFile.Chmod(0755)\n\n\tt := template.Must(template.New(\"postInstall\").Parse(postInstall))\n\tt.Execute(postInstallFile, b.appName)\n\n\tt = template.Must(template.New(\"preInstall\").Parse(preInstall))\n\tt.Execute(preInstallFile, b.appName)\n}\n\nfunc fileExist(dir string) bool {\n\tvar err error\n\t_, err = os.Stat(dir)\n\tif err == nil {\n\t\treturn true \/\/ file exist\n\t}\n\n\tif os.IsNotExist(err) {\n\t\treturn false \/\/ file does not exist\n\t}\n\n\tpanic(err) \/\/ permission errors or something else bad\n}\n<commit_msg>build: include files seperated with commas<commit_after>package build\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"koding\/kite\/kd\/util\"\n\t\"koding\/tools\/deps\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/fatih\/file\"\n)\n\ntype Build struct {\n\tappName    string\n\tversion    string\n\toutput     string\n\tbinaryPath string\n\timportPath string\n\tfiles      string\n}\n\nfunc NewBuild() *Build {\n\treturn &Build{}\n}\n\nfunc (b *Build) Definition() string {\n\treturn \"Build deployable install packages\"\n}\n\nfunc (b *Build) Exec(args []string) error {\n\tusage := \"Usage: kd build --import <importPath> || --bin <binaryPath> --files <filesPath>\"\n\tif len(args) == 0 {\n\t\treturn errors.New(usage)\n\t}\n\n\tf := flag.NewFlagSet(\"build\", flag.ContinueOnError)\n\tf.StringVar(&b.importPath, \"import\", \"\", \"Go importpath to be packaged\")\n\tf.StringVar(&b.binaryPath, \"bin\", \"\", \"Binary to be packaged\")\n\tf.StringVar(&b.files, \"files\", \"\", \"Files to be included with the package\")\n\tf.Parse(args)\n\n\tif b.binaryPath != \"\" {\n\t\tb.appName = filepath.Base(b.binaryPath)\n\t} else if b.importPath != \"\" {\n\t\tb.appName = filepath.Base(b.importPath)\n\t} else {\n\t\treturn errors.New(\"build: --import or --bin should be defined.\")\n\t}\n\n\tb.version = \"0.0.1\"\n\tb.output = fmt.Sprintf(\"%s.%s-%s\", b.appName, runtime.GOOS, runtime.GOARCH)\n\n\terr := b.do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (b *Build) do() error {\n\tswitch runtime.GOOS {\n\tcase \"darwin\":\n\t\terr := b.darwin()\n\t\tif err != nil {\n\t\t\tlog.Println(\"darwin:\", err)\n\t\t}\n\tcase \"linux\":\n\t\terr := b.linux()\n\t\tif err != nil {\n\t\t\tlog.Println(\"linux:\", err)\n\t\t}\n\t}\n\n\t\/\/ also create a tar.gz regardless of os\n\treturn b.tarGzFile()\n}\n\nfunc (b *Build) linux() error {\n\treturn nil\n}\n\nfunc (b *Build) tarGzFile() error {\n\tbuildFolder, err := ioutil.TempDir(\".\", \"kd-build\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(buildFolder)\n\n\tif b.importPath != \"\" {\n\t\tgopath := os.Getenv(\"GOPATH\")\n\t\tif gopath == \"\" {\n\t\t\treturn errors.New(\"GOPATH is not set\")\n\t\t}\n\n\t\t\/\/ or use \"go list koding\/...\" for all packages and commands\n\t\tpackages := []string{b.importPath}\n\t\td, err := deps.LoadDeps(packages...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = d.InstallDeps()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuildFolder = filepath.Join(d.BuildGoPath, b.appName)\n\t} else {\n\t\terr := file.Copy(b.binaryPath, buildFolder)\n\t\tif err != nil {\n\t\t\tlog.Println(\"copy assets\", err)\n\t\t}\n\t}\n\n\t\/\/ include given files\n\tif b.files != \"\" {\n\t\tfiles := strings.Split(b.files, \",\")\n\t\tfor _, path := range files {\n\t\t\terr := file.Copy(path, buildFolder)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"copy assets\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ create tar.gz file from final director\n\ttarFile := fmt.Sprintf(\"%s.%s-%s.tar.gz\", b.appName, runtime.GOOS, runtime.GOARCH)\n\terr = util.MakeTar(tarFile, buildFolder)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"'%s' is created and ready for deploy\\n\", tarFile)\n\treturn nil\n}\n\n\/\/ darwin is building a new .pkg installer for darwin based OS'es.\nfunc (b *Build) darwin() error {\n\tversion := b.version\n\tif b.output == \"\" {\n\t\tb.output = fmt.Sprintf(\"koding-%s\", b.appName)\n\t}\n\n\tscriptDir := \"build\/darwin\/scripts\"\n\tinstallRoot := \".\/root\" \/\/ TODO REMOVE\n\n\tos.RemoveAll(installRoot) \/\/ clean up old build before we continue\n\tinstallRootUsr := filepath.Join(installRoot, \"\/usr\/local\/bin\")\n\n\tos.MkdirAll(installRootUsr, 0755)\n\terr := util.CopyFile(b.binaryPath, installRootUsr+\"\/\"+b.appName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttempDest, err := ioutil.TempDir(\"\", \"tempDest\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(tempDest)\n\n\tb.createScripts(scriptDir)\n\tb.createLaunchAgent(installRoot)\n\n\tcmdPkg := exec.Command(\"pkgbuild\",\n\t\t\"--identifier\", fmt.Sprintf(\"com.koding.kite.%s.pkg\", b.appName),\n\t\t\"--version\", version,\n\t\t\"--scripts\", scriptDir,\n\t\t\"--root\", installRoot,\n\t\t\"--install-location\", \"\/\",\n\t\tfmt.Sprintf(\"%s\/com.koding.kite.%s.pkg\", tempDest, b.appName),\n\t\t\/\/ used for next step, also set up for distribution.xml\n\t)\n\n\t_, err = cmdPkg.CombinedOutput()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdistributionFile := \"build\/darwin\/Distribution.xml\"\n\tresources := \"build\/darwin\/Resources\"\n\ttargetFile := b.output + \".pkg\"\n\n\tb.createDistribution(distributionFile)\n\n\tcmdBuild := exec.Command(\"productbuild\",\n\t\t\"--distribution\", distributionFile,\n\t\t\"--resources\", resources,\n\t\t\"--package-path\", tempDest,\n\t\ttargetFile,\n\t)\n\n\t_, err = cmdBuild.CombinedOutput()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"'%s' is created and ready for deploy\\n\", targetFile)\n\treturn nil\n}\n\nfunc (b *Build) createLaunchAgent(rootDir string) {\n\tlaunchDir := fmt.Sprintf(\"%s\/Library\/LaunchAgents\/\", rootDir)\n\tos.MkdirAll(launchDir, 0700)\n\n\tlaunchFile := fmt.Sprintf(\"%s\/com.koding.kite.%s.plist\", launchDir, b.appName)\n\n\tlFile, err := os.Create(launchFile)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tt := template.Must(template.New(\"launchAgent\").Parse(launchAgent))\n\tt.Execute(lFile, b.appName)\n\n}\n\nfunc (b *Build) createDistribution(file string) {\n\tdistFile, err := os.Create(file)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tt := template.Must(template.New(\"distribution\").Parse(distribution))\n\tt.Execute(distFile, b.appName)\n\n}\n\nfunc (b *Build) createScripts(scriptDir string) {\n\tos.MkdirAll(scriptDir, 0700) \/\/ does return nil if exists\n\n\tpostInstallFile, err := os.Create(scriptDir + \"\/postInstall\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tpostInstallFile.Chmod(0755)\n\n\tpreInstallFile, err := os.Create(scriptDir + \"\/preInstall\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tpreInstallFile.Chmod(0755)\n\n\tt := template.Must(template.New(\"postInstall\").Parse(postInstall))\n\tt.Execute(postInstallFile, b.appName)\n\n\tt = template.Must(template.New(\"preInstall\").Parse(preInstall))\n\tt.Execute(preInstallFile, b.appName)\n}\n\nfunc fileExist(dir string) bool {\n\tvar err error\n\t_, err = os.Stat(dir)\n\tif err == nil {\n\t\treturn true \/\/ file exist\n\t}\n\n\tif os.IsNotExist(err) {\n\t\treturn false \/\/ file does not exist\n\t}\n\n\tpanic(err) \/\/ permission errors or something else bad\n}\n<|endoftext|>"}
{"text":"<commit_before>package buildserver\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/concourse\/atc\"\n\t\"github.com\/concourse\/atc\/db\"\n\t\"github.com\/concourse\/atc\/event\"\n\t\"github.com\/vito\/go-sse\/sse\"\n)\n\nconst ProtocolVersionHeader = \"X-ATC-Stream-Version\"\nconst CurrentProtocolVersion = \"2.0\"\n\nfunc NewEventHandler(buildsDB BuildsDB, buildID int, censor bool) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tflusher := w.(http.Flusher)\n\t\tclosed := w.(http.CloseNotifier).CloseNotify()\n\n\t\tw.Header().Add(\"Content-Type\", \"text\/event-stream; charset=utf-8\")\n\t\tw.Header().Add(\"Cache-Control\", \"no-cache, no-store, must-revalidate\")\n\t\tw.Header().Add(\"Connection\", \"keep-alive\")\n\t\tw.Header().Add(ProtocolVersionHeader, CurrentProtocolVersion)\n\n\t\tvar start uint = 0\n\t\tif r.Header.Get(\"Last-Event-ID\") != \"\" {\n\t\t\t_, err := fmt.Sscanf(r.Header.Get(\"Last-Event-ID\"), \"%d\", &start)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tstart++\n\t\t}\n\n\t\tevents, err := buildsDB.GetBuildEvents(buildID, start)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\n\t\tdefer events.Close()\n\n\t\tes := make(chan atc.Event)\n\t\terrs := make(chan error, 1)\n\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tev, err := events.Next()\n\t\t\t\tif err != nil {\n\t\t\t\t\terrs <- err\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase es <- ev:\n\t\t\t\t\tcase <-closed:\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase ev := <-es:\n\t\t\t\tif censor {\n\t\t\t\t\tev = ev.Censored()\n\t\t\t\t}\n\n\t\t\t\tpayload, err := json.Marshal(event.Message{ev})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\terr = sse.Event{\n\t\t\t\t\tID:   fmt.Sprintf(\"%d\", start),\n\t\t\t\t\tName: \"event\",\n\t\t\t\t\tData: payload,\n\t\t\t\t}.Write(w)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tstart++\n\n\t\t\t\tflusher.Flush()\n\t\t\tcase err := <-errs:\n\t\t\t\tif err == db.ErrEndOfBuildEventStream {\n\t\t\t\t\terr = sse.Event{Name: \"end\"}.Write(w)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\tcase <-closed:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\treturn\n\t})\n}\n<commit_msg>gzip encode event stream<commit_after>package buildserver\n\nimport (\n\t\"compress\/gzip\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/concourse\/atc\"\n\t\"github.com\/concourse\/atc\/db\"\n\t\"github.com\/concourse\/atc\/event\"\n\t\"github.com\/vito\/go-sse\/sse\"\n)\n\nconst ProtocolVersionHeader = \"X-ATC-Stream-Version\"\nconst CurrentProtocolVersion = \"2.0\"\n\nfunc NewEventHandler(buildsDB BuildsDB, buildID int, censor bool) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tflusher := w.(http.Flusher)\n\t\tclosed := w.(http.CloseNotifier).CloseNotify()\n\n\t\tw.Header().Add(\"Content-Type\", \"text\/event-stream; charset=utf-8\")\n\t\tw.Header().Add(\"Cache-Control\", \"no-cache, no-store, must-revalidate\")\n\t\tw.Header().Add(\"Connection\", \"keep-alive\")\n\t\tw.Header().Add(ProtocolVersionHeader, CurrentProtocolVersion)\n\n\t\tvar start uint = 0\n\t\tif r.Header.Get(\"Last-Event-ID\") != \"\" {\n\t\t\t_, err := fmt.Sscanf(r.Header.Get(\"Last-Event-ID\"), \"%d\", &start)\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tstart++\n\t\t}\n\n\t\tvar responseWriter io.Writer = w\n\n\t\tw.Header().Add(\"Vary\", \"Accept-Encoding\")\n\t\tif strings.Contains(r.Header.Get(\"Accept-Encoding\"), \"gzip\") {\n\t\t\tw.Header().Set(\"Content-Encoding\", \"gzip\")\n\n\t\t\tgz := gzip.NewWriter(w)\n\t\t\tdefer gz.Close()\n\n\t\t\tresponseWriter = gz\n\t\t}\n\n\t\tevents, err := buildsDB.GetBuildEvents(buildID, start)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\n\t\tdefer events.Close()\n\n\t\tes := make(chan atc.Event)\n\t\terrs := make(chan error, 1)\n\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tev, err := events.Next()\n\t\t\t\tif err != nil {\n\t\t\t\t\terrs <- err\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase es <- ev:\n\t\t\t\t\tcase <-closed:\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase ev := <-es:\n\t\t\t\tif censor {\n\t\t\t\t\tev = ev.Censored()\n\t\t\t\t}\n\n\t\t\t\tpayload, err := json.Marshal(event.Message{ev})\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\terr = sse.Event{\n\t\t\t\t\tID:   fmt.Sprintf(\"%d\", start),\n\t\t\t\t\tName: \"event\",\n\t\t\t\t\tData: payload,\n\t\t\t\t}.Write(responseWriter)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tstart++\n\n\t\t\t\tflusher.Flush()\n\t\t\tcase err := <-errs:\n\t\t\t\tif err == db.ErrEndOfBuildEventStream {\n\t\t\t\t\terr = sse.Event{Name: \"end\"}.Write(responseWriter)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\tcase <-closed:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\treturn\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package integration_test\n\nimport (\n\t\"encoding\/gob\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\n\t\"github.com\/concourse\/atc\/api\/resources\"\n\tthijack \"github.com\/concourse\/turbine\/api\/hijack\"\n\t\"github.com\/kr\/pty\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\t\"github.com\/onsi\/gomega\/ghttp\"\n)\n\nvar _ = FDescribe(\"Hijacking\", func() {\n\tvar atcServer *ghttp.Server\n\tvar hijacked <-chan struct{}\n\n\tBeforeEach(func() {\n\t\tatcServer = ghttp.NewServer()\n\t\thijacked = nil\n\n\t\tos.Setenv(\"ATC_URL\", atcServer.URL())\n\t})\n\n\thijackHandler := func(didHijack chan<- struct{}) http.HandlerFunc {\n\t\treturn ghttp.CombineHandlers(\n\t\t\tghttp.VerifyRequest(\"POST\", \"\/api\/v1\/builds\/3\/hijack\"),\n\t\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\n\t\t\t\tsconn, sbr, err := w.(http.Hijacker).Hijack()\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t\tdefer sconn.Close()\n\n\t\t\t\tclose(didHijack)\n\n\t\t\t\tdecoder := gob.NewDecoder(sbr)\n\n\t\t\t\tvar payload thijack.ProcessPayload\n\n\t\t\t\terr = decoder.Decode(&payload)\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t\tΩ(payload).Should(Equal(thijack.ProcessPayload{\n\t\t\t\t\tStdin: []byte(\"marco\"),\n\t\t\t\t}))\n\n\t\t\t\t_, err = sconn.Write([]byte(\"polo\"))\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\t\t\t},\n\t\t)\n\t}\n\n\thijack := func(args ...string) {\n\t\tpty, tty, err := pty.Open()\n\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\tflyCmd := exec.Command(flyPath, append([]string{\"hijack\"}, args...)...)\n\t\tflyCmd.Stdin = tty\n\n\t\tsess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)\n\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\tEventually(hijacked).Should(BeClosed())\n\n\t\t_, err = pty.WriteString(\"marco\")\n\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\tEventually(sess).Should(gbytes.Say(\"polo\"))\n\n\t\terr = pty.Close()\n\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\tEventually(sess).Should(gexec.Exit(0))\n\t}\n\n\tContext(\"with no arguments\", func() {\n\t\tBeforeEach(func() {\n\t\t\tdidHijack := make(chan struct{})\n\t\t\thijacked = didHijack\n\n\t\t\tatcServer.AppendHandlers(\n\t\t\t\tghttp.CombineHandlers(\n\t\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/api\/v1\/builds\"),\n\t\t\t\t\tghttp.RespondWithJSONEncoded(200, []resources.Build{\n\t\t\t\t\t\t{ID: 3, Name: \"3\", Status: \"started\"},\n\t\t\t\t\t\t{ID: 2, Name: \"2\", Status: \"started\"},\n\t\t\t\t\t\t{ID: 1, Name: \"1\", Status: \"finished\"},\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\thijackHandler(didHijack),\n\t\t\t)\n\t\t})\n\n\t\tIt(\"hijacks the most recent build\", func() {\n\t\t\thijack()\n\t\t})\n\t})\n\n\tContext(\"with a specific job\", func() {\n\t\tContext(\"when the job has a next build\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tdidHijack := make(chan struct{})\n\t\t\t\thijacked = didHijack\n\n\t\t\t\tatcServer.AppendHandlers(\n\t\t\t\t\tghttp.CombineHandlers(\n\t\t\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/api\/v1\/jobs\/some-job\"),\n\t\t\t\t\t\tghttp.RespondWithJSONEncoded(200, resources.Job{\n\t\t\t\t\t\t\tNextBuild: &resources.Build{\n\t\t\t\t\t\t\t\tID:      3,\n\t\t\t\t\t\t\t\tName:    \"3\",\n\t\t\t\t\t\t\t\tStatus:  \"started\",\n\t\t\t\t\t\t\t\tJobName: \"some-job\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tFinishedBuild: &resources.Build{\n\t\t\t\t\t\t\t\tID:      2,\n\t\t\t\t\t\t\t\tName:    \"2\",\n\t\t\t\t\t\t\t\tStatus:  \"failed\",\n\t\t\t\t\t\t\t\tJobName: \"some-job\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\thijackHandler(didHijack),\n\t\t\t\t)\n\t\t\t})\n\n\t\t\tIt(\"hijacks the job's next build\", func() {\n\t\t\t\thijack(\"--job\", \"some-job\")\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the job only has a finished build\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tdidHijack := make(chan struct{})\n\t\t\t\thijacked = didHijack\n\n\t\t\t\tatcServer.AppendHandlers(\n\t\t\t\t\tghttp.CombineHandlers(\n\t\t\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/api\/v1\/jobs\/some-job\"),\n\t\t\t\t\t\tghttp.RespondWithJSONEncoded(200, resources.Job{\n\t\t\t\t\t\t\tNextBuild: nil,\n\t\t\t\t\t\t\tFinishedBuild: &resources.Build{\n\t\t\t\t\t\t\t\tID:      3,\n\t\t\t\t\t\t\t\tName:    \"3\",\n\t\t\t\t\t\t\t\tStatus:  \"failed\",\n\t\t\t\t\t\t\t\tJobName: \"some-job\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\thijackHandler(didHijack),\n\t\t\t\t)\n\t\t\t})\n\n\t\t\tIt(\"hijacks the job's finished build\", func() {\n\t\t\t\thijack(\"--job\", \"some-job\")\n\t\t\t})\n\t\t})\n\n\t\tContext(\"with a specific build of the job\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tdidHijack := make(chan struct{})\n\t\t\t\thijacked = didHijack\n\n\t\t\t\tatcServer.AppendHandlers(\n\t\t\t\t\tghttp.CombineHandlers(\n\t\t\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/api\/v1\/jobs\/some-job\/builds\/3\"),\n\t\t\t\t\t\tghttp.RespondWithJSONEncoded(200, resources.Build{\n\t\t\t\t\t\t\tID:      3,\n\t\t\t\t\t\t\tName:    \"3\",\n\t\t\t\t\t\t\tStatus:  \"failed\",\n\t\t\t\t\t\t\tJobName: \"some-job\",\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\thijackHandler(didHijack),\n\t\t\t\t)\n\t\t\t})\n\n\t\t\tIt(\"hijacks the given build\", func() {\n\t\t\t\thijack(\"--job\", \"some-job\", \"--build\", \"3\")\n\t\t\t})\n\t\t})\n\t})\n})\n<commit_msg>remove accidental focus<commit_after>package integration_test\n\nimport (\n\t\"encoding\/gob\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\n\t\"github.com\/concourse\/atc\/api\/resources\"\n\tthijack \"github.com\/concourse\/turbine\/api\/hijack\"\n\t\"github.com\/kr\/pty\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\t\"github.com\/onsi\/gomega\/ghttp\"\n)\n\nvar _ = Describe(\"Hijacking\", func() {\n\tvar atcServer *ghttp.Server\n\tvar hijacked <-chan struct{}\n\n\tBeforeEach(func() {\n\t\tatcServer = ghttp.NewServer()\n\t\thijacked = nil\n\n\t\tos.Setenv(\"ATC_URL\", atcServer.URL())\n\t})\n\n\thijackHandler := func(didHijack chan<- struct{}) http.HandlerFunc {\n\t\treturn ghttp.CombineHandlers(\n\t\t\tghttp.VerifyRequest(\"POST\", \"\/api\/v1\/builds\/3\/hijack\"),\n\t\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\n\t\t\t\tsconn, sbr, err := w.(http.Hijacker).Hijack()\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t\tdefer sconn.Close()\n\n\t\t\t\tclose(didHijack)\n\n\t\t\t\tdecoder := gob.NewDecoder(sbr)\n\n\t\t\t\tvar payload thijack.ProcessPayload\n\n\t\t\t\terr = decoder.Decode(&payload)\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\t\tΩ(payload).Should(Equal(thijack.ProcessPayload{\n\t\t\t\t\tStdin: []byte(\"marco\"),\n\t\t\t\t}))\n\n\t\t\t\t_, err = sconn.Write([]byte(\"polo\"))\n\t\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\t\t\t},\n\t\t)\n\t}\n\n\thijack := func(args ...string) {\n\t\tpty, tty, err := pty.Open()\n\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\tflyCmd := exec.Command(flyPath, append([]string{\"hijack\"}, args...)...)\n\t\tflyCmd.Stdin = tty\n\n\t\tsess, err := gexec.Start(flyCmd, GinkgoWriter, GinkgoWriter)\n\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\tEventually(hijacked).Should(BeClosed())\n\n\t\t_, err = pty.WriteString(\"marco\")\n\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\tEventually(sess).Should(gbytes.Say(\"polo\"))\n\n\t\terr = pty.Close()\n\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\tEventually(sess).Should(gexec.Exit(0))\n\t}\n\n\tContext(\"with no arguments\", func() {\n\t\tBeforeEach(func() {\n\t\t\tdidHijack := make(chan struct{})\n\t\t\thijacked = didHijack\n\n\t\t\tatcServer.AppendHandlers(\n\t\t\t\tghttp.CombineHandlers(\n\t\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/api\/v1\/builds\"),\n\t\t\t\t\tghttp.RespondWithJSONEncoded(200, []resources.Build{\n\t\t\t\t\t\t{ID: 3, Name: \"3\", Status: \"started\"},\n\t\t\t\t\t\t{ID: 2, Name: \"2\", Status: \"started\"},\n\t\t\t\t\t\t{ID: 1, Name: \"1\", Status: \"finished\"},\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t\thijackHandler(didHijack),\n\t\t\t)\n\t\t})\n\n\t\tIt(\"hijacks the most recent build\", func() {\n\t\t\thijack()\n\t\t})\n\t})\n\n\tContext(\"with a specific job\", func() {\n\t\tContext(\"when the job has a next build\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tdidHijack := make(chan struct{})\n\t\t\t\thijacked = didHijack\n\n\t\t\t\tatcServer.AppendHandlers(\n\t\t\t\t\tghttp.CombineHandlers(\n\t\t\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/api\/v1\/jobs\/some-job\"),\n\t\t\t\t\t\tghttp.RespondWithJSONEncoded(200, resources.Job{\n\t\t\t\t\t\t\tNextBuild: &resources.Build{\n\t\t\t\t\t\t\t\tID:      3,\n\t\t\t\t\t\t\t\tName:    \"3\",\n\t\t\t\t\t\t\t\tStatus:  \"started\",\n\t\t\t\t\t\t\t\tJobName: \"some-job\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tFinishedBuild: &resources.Build{\n\t\t\t\t\t\t\t\tID:      2,\n\t\t\t\t\t\t\t\tName:    \"2\",\n\t\t\t\t\t\t\t\tStatus:  \"failed\",\n\t\t\t\t\t\t\t\tJobName: \"some-job\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\thijackHandler(didHijack),\n\t\t\t\t)\n\t\t\t})\n\n\t\t\tIt(\"hijacks the job's next build\", func() {\n\t\t\t\thijack(\"--job\", \"some-job\")\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the job only has a finished build\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tdidHijack := make(chan struct{})\n\t\t\t\thijacked = didHijack\n\n\t\t\t\tatcServer.AppendHandlers(\n\t\t\t\t\tghttp.CombineHandlers(\n\t\t\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/api\/v1\/jobs\/some-job\"),\n\t\t\t\t\t\tghttp.RespondWithJSONEncoded(200, resources.Job{\n\t\t\t\t\t\t\tNextBuild: nil,\n\t\t\t\t\t\t\tFinishedBuild: &resources.Build{\n\t\t\t\t\t\t\t\tID:      3,\n\t\t\t\t\t\t\t\tName:    \"3\",\n\t\t\t\t\t\t\t\tStatus:  \"failed\",\n\t\t\t\t\t\t\t\tJobName: \"some-job\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\thijackHandler(didHijack),\n\t\t\t\t)\n\t\t\t})\n\n\t\t\tIt(\"hijacks the job's finished build\", func() {\n\t\t\t\thijack(\"--job\", \"some-job\")\n\t\t\t})\n\t\t})\n\n\t\tContext(\"with a specific build of the job\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tdidHijack := make(chan struct{})\n\t\t\t\thijacked = didHijack\n\n\t\t\t\tatcServer.AppendHandlers(\n\t\t\t\t\tghttp.CombineHandlers(\n\t\t\t\t\t\tghttp.VerifyRequest(\"GET\", \"\/api\/v1\/jobs\/some-job\/builds\/3\"),\n\t\t\t\t\t\tghttp.RespondWithJSONEncoded(200, resources.Build{\n\t\t\t\t\t\t\tID:      3,\n\t\t\t\t\t\t\tName:    \"3\",\n\t\t\t\t\t\t\tStatus:  \"failed\",\n\t\t\t\t\t\t\tJobName: \"some-job\",\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t\thijackHandler(didHijack),\n\t\t\t\t)\n\t\t\t})\n\n\t\t\tIt(\"hijacks the given build\", func() {\n\t\t\t\thijack(\"--job\", \"some-job\", \"--build\", \"3\")\n\t\t\t})\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package kickbox\n\nimport (\n\t\"encoding\/json\"\n)\n\n\/\/ KickboxResultBuilder implements our ResultBuilder interface and creates the\n\/\/ actual Result struct (the response from Kickbox)\ntype KickboxResultBuilder struct{}\n\n\/\/ NewResult creates a new Result object from an JSON API response\nfunc (b KickboxResultBuilder) NewResult(response []byte) (*Result, error) {\n\tresult := Result{}\n\tif err := json.Unmarshal(response, &result); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &result, nil\n}\n\n\/\/ IsDeliverable returns true if the API returns \"result: deliverable\"\nfunc (r Result) IsDeliverable() bool {\n\treturn (r.Result == \"deliverable\")\n}\n\n\/\/ IsUndeliverable returns true if the API returns \"result: undeliverable\"\nfunc (r Result) IsUndeliverable() bool {\n\treturn (r.Result == \"undeliverable\")\n}\n\n\/\/ IsRisky returns true if the API returns \"result: risky\"\nfunc (r Result) IsRisky() bool {\n\treturn (r.Result == \"risky\")\n}\n\n\/\/ IsUnknown returns true if the API returns \"result: unknown\"\nfunc (r Result) IsUnknown() bool {\n\treturn (r.Result == \"unknown\")\n}\n<commit_msg>Consistent struct creation<commit_after>package kickbox\n\nimport (\n\t\"encoding\/json\"\n)\n\n\/\/ KickboxResultBuilder implements our ResultBuilder interface and creates the\n\/\/ actual Result struct (the response from Kickbox)\ntype KickboxResultBuilder struct{}\n\n\/\/ NewResult creates a new Result object from an JSON API response\nfunc (b KickboxResultBuilder) NewResult(response []byte) (*Result, error) {\n\tresult := &Result{}\n\tif err := json.Unmarshal(response, result); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\n\/\/ IsDeliverable returns true if the API returns \"result: deliverable\"\nfunc (r Result) IsDeliverable() bool {\n\treturn (r.Result == \"deliverable\")\n}\n\n\/\/ IsUndeliverable returns true if the API returns \"result: undeliverable\"\nfunc (r Result) IsUndeliverable() bool {\n\treturn (r.Result == \"undeliverable\")\n}\n\n\/\/ IsRisky returns true if the API returns \"result: risky\"\nfunc (r Result) IsRisky() bool {\n\treturn (r.Result == \"risky\")\n}\n\n\/\/ IsUnknown returns true if the API returns \"result: unknown\"\nfunc (r Result) IsUnknown() bool {\n\treturn (r.Result == \"unknown\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/c-bata\/go-prompt-toolkit\/prompt\"\n)\n\nfunc executor(t string) string {\n\tr := \"Your input: \" + t\n\treturn r\n}\n\nfunc completer(t string) []string {\n\treturn []string{\n\t\t\"users\",\n\t\t\"sites\",\n\t\t\"articles\",\n\t\t\"comments\",\n\t}\n}\n\nfunc main() {\n\tpt := prompt.NewPrompt(\n\t\texecutor,\n\t\tcompleter,\n\t\tprompt.OptionPrefix(\">>> \"),\n\t\tprompt.OptionTitle(\"sqlite3-cli\"),\n\t\tprompt.OptionOutputTextColor(prompt.DarkGray),\n\t)\n\tdefer fmt.Println(\"\\nGoodbye!\")\n\tpt.Run()\n}\n<commit_msg>Update example<commit_after>package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/c-bata\/go-prompt-toolkit\"\n)\n\nfunc executor(t string) string {\n\tr := \"Your input: \" + t\n\treturn r\n}\n\nfunc completer(t string) []string {\n\treturn []string{\n\t\t\"users\",\n\t\t\"sites\",\n\t\t\"articles\",\n\t\t\"comments\",\n\t}\n}\n\nfunc main() {\n\tpt := prompt.NewPrompt(\n\t\texecutor,\n\t\tcompleter,\n\t\tprompt.OptionPrefix(\">>> \"),\n\t\tprompt.OptionTitle(\"sqlite3-cli\"),\n\t\tprompt.OptionOutputTextColor(prompt.DarkGray),\n\t)\n\tdefer fmt.Println(\"\\nGoodbye!\")\n\tpt.Run()\n}\n<|endoftext|>"}
{"text":"<commit_before>package logger\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/bugsnag\/bugsnag-go\"\n\t\"github.com\/juju\/loggo\"\n\t\"github.com\/wolfeidau\/loggo-syslog\"\n)\n\nfunc init() {\n\n\tif os.Getenv(\"DEBUG\") != \"\" {\n\t\t\/\/ set the default logger to info\n\t\tloggo.GetLogger(\"\").SetLogLevel(loggo.DEBUG)\n\t} else {\n\t\t\/\/ set the default logger to info\n\t\tloggo.GetLogger(\"\").SetLogLevel(loggo.INFO)\n\t}\n}\n\n\/\/ Logger wrapper for the internal logger with some extra helpers\ntype Logger struct {\n\tloggo.Logger\n}\n\n\/\/ GetLogger builds a ninja logger with the given name\nfunc GetLogger(name string) *Logger {\n\tl := loggo.GetLogger(name)\n\n\t\/\/ are we in a terminal?\n\tif !IsTerminal() {\n\n\t\t\/\/ we need to use a different writer\n\t\tloggo.RemoveWriter(\"default\")\n\n\t\t\/\/ setup the syslog writer as the default passing the\n\t\tloggo.RegisterWriter(\"default\", lsyslog.NewDefaultSyslogWriter(loggo.TRACE, \"ninja\"), loggo.TRACE)\n\t}\n\n\treturn &Logger{l}\n}\n\n\/\/ HandleError This notifies bugsnag and logs the error.\nfunc (l *Logger) HandleError(err error, msg string) {\n\tl.Errorf(\"%s : %v\", msg, err)\n\tbugsnag.Notify(err)\n}\n\n\/\/ FatalError This notifies bugsnag and logs the error then quits.\nfunc (l *Logger) FatalError(err error, msg string) {\n\tl.Errorf(\"%s : %v\", msg, err)\n\tbugsnag.Notify(err)\n\tos.Exit(1)\n}\n\n\/\/ HandleErrorf This notifies bugsnag and logs the error based on the args.\nfunc (l *Logger) HandleErrorf(err error, msg string, args ...interface{}) {\n\tl.Errorf(msg, args)\n\tbugsnag.Notify(err)\n}\n\n\/\/ FatalErrorf This notifies bugsnag and logs the error based on the args then quits\nfunc (l *Logger) FatalErrorf(err error, msg string, args ...interface{}) {\n\tl.Errorf(msg, args)\n\tbugsnag.Notify(err)\n\tos.Exit(1)\n}\n\n\/\/ FatalErrorf This notifies bugsnag and logs the error based on the args then quits\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) {\n\tl.Errorf(msg, args)\n\tbugsnag.Notify(fmt.Errorf(msg, args))\n\tos.Exit(1)\n}\n<commit_msg>Kill all output from loggers in underlying libs.<commit_after>package logger\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/bugsnag\/bugsnag-go\"\n\t\"github.com\/juju\/loggo\"\n\t\"github.com\/wolfeidau\/loggo-syslog\"\n)\n\nfunc init() {\n\n\tif os.Getenv(\"DEBUG\") != \"\" {\n\t\t\/\/ set the default logger to info\n\t\tloggo.GetLogger(\"\").SetLogLevel(loggo.DEBUG)\n\t} else {\n\t\t\/\/ set the default logger to info\n\t\tloggo.GetLogger(\"\").SetLogLevel(loggo.INFO)\n\t}\n}\n\n\/\/ Logger wrapper for the internal logger with some extra helpers\ntype Logger struct {\n\tloggo.Logger\n}\n\n\/\/ GetLogger builds a ninja logger with the given name\nfunc GetLogger(name string) *Logger {\n\tl := loggo.GetLogger(name)\n\n\t\/\/ are we in a terminal?\n\tif !IsTerminal() {\n\n\t\t\/\/ kill output from std logger\n\t\tlog.SetOutput(ioutil.Discard)\n\n\t\t\/\/ we need to use a different writer\n\t\tloggo.RemoveWriter(\"default\")\n\n\t\t\/\/ setup the syslog writer as the default passing the\n\t\tloggo.RegisterWriter(\"default\", lsyslog.NewDefaultSyslogWriter(loggo.TRACE, \"ninja\"), loggo.TRACE)\n\t}\n\n\treturn &Logger{l}\n}\n\n\/\/ HandleError This notifies bugsnag and logs the error.\nfunc (l *Logger) HandleError(err error, msg string) {\n\tl.Errorf(\"%s : %v\", msg, err)\n\tbugsnag.Notify(err)\n}\n\n\/\/ FatalError This notifies bugsnag and logs the error then quits.\nfunc (l *Logger) FatalError(err error, msg string) {\n\tl.Errorf(\"%s : %v\", msg, err)\n\tbugsnag.Notify(err)\n\tos.Exit(1)\n}\n\n\/\/ HandleErrorf This notifies bugsnag and logs the error based on the args.\nfunc (l *Logger) HandleErrorf(err error, msg string, args ...interface{}) {\n\tl.Errorf(msg, args)\n\tbugsnag.Notify(err)\n}\n\n\/\/ FatalErrorf This notifies bugsnag and logs the error based on the args then quits\nfunc (l *Logger) FatalErrorf(err error, msg string, args ...interface{}) {\n\tl.Errorf(msg, args)\n\tbugsnag.Notify(err)\n\tos.Exit(1)\n}\n\n\/\/ FatalErrorf This notifies bugsnag and logs the error based on the args then quits\nfunc (l *Logger) Fatalf(msg string, args ...interface{}) {\n\tl.Errorf(msg, args)\n\tbugsnag.Notify(fmt.Errorf(msg, args))\n\tos.Exit(1)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2021 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Functions for cleaning the database of unwanted module versions.\n\npackage postgres\n\nimport (\n\t\"context\"\n\t\"database\/sql\"\n\n\t\"golang.org\/x\/pkgsite\/internal\/derrors\"\n)\n\n\/\/ A ModuleVersion holds a module path and version.\ntype ModuleVersion struct {\n\tModulePath string\n\tVersion    string\n}\n\nfunc (mv ModuleVersion) String() string {\n\treturn mv.ModulePath + \"@\" + mv.Version\n}\n\n\/\/ GetModuleVersionsToClean returns module versions that can be removed from the database.\n\/\/ Only module versions that were updated more than daysOld days ago will be considered.\n\/\/ At most limit module versions will be returned.\nfunc (db *DB) GetModuleVersionsToClean(ctx context.Context, daysOld, limit int) (modvers []ModuleVersion, err error) {\n\tdefer derrors.WrapStack(&err, \"GetModuleVersionsToClean(%d, %d)\", daysOld, limit)\n\n\t\/\/ Get all pseudo-versions that were added before the given number of days.\n\t\/\/ Then remove:\n\t\/\/ - The ones that are the latest versions for their module,\n\t\/\/ - The ones in search_documents (since the latest version of a package might be at an older version),\n\t\/\/ - The ones that the master or main branch resolves to.\n\tquery := `\n\t\tSELECT module_path, version\n\t\tFROM modules\n\t\tWHERE version_type = 'pseudo'\n\t\tAND CURRENT_TIMESTAMP - updated_at > make_interval(days => $1)\n\t\tEXCEPT (\n\t\t\tSELECT p.path, l.good_version\n\t\t\tFROM latest_module_versions l\n\t\t\tINNER JOIN paths p ON p.id = l.module_path_id\n\t\t\tWHERE good_version != ''\n\t\t)\n\t\tEXCEPT (\n\t\t\tSELECT module_path, version\n\t\t\tFROM search_documents\n\t\t)\n\t\tEXCEPT (\n\t\t\tSELECT module_path, resolved_version\n\t\t\tFROM version_map\n\t\t\tWHERE requested_version IN ('master', 'main')\n\t\t)\n\t\tLIMIT $2\n\t`\n\n\terr = db.db.RunQuery(ctx, query, func(rows *sql.Rows) error {\n\t\tvar mv ModuleVersion\n\t\tif err := rows.Scan(&mv.ModulePath, &mv.Version); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmodvers = append(modvers, mv)\n\t\treturn nil\n\t}, daysOld, limit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn modvers, nil\n}\n\n\/\/ CleanModuleVersions deletes each module version from the DB and marks it as cleaned\n\/\/ in module_version_states.\nfunc (db *DB) CleanModuleVersions(ctx context.Context, mvs []ModuleVersion, reason string) (err error) {\n\tdefer derrors.Wrap(&err, \"CleanModuleVersions(%d modules)\", len(mvs))\n\n\tstatus := derrors.ToStatus(derrors.Cleaned)\n\tfor _, mv := range mvs {\n\t\tif err := db.UpdateModuleVersionStatus(ctx, mv.ModulePath, mv.Version, status, reason); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := db.DeleteModule(ctx, mv.ModulePath, mv.Version); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ CleanModule deletes all versions of the given module path from the DB and marks them\n\/\/ as cleaned in module_version_states.\nfunc (db *DB) CleanModule(ctx context.Context, modulePath, reason string) (err error) {\n\tdefer derrors.Wrap(&err, \"CleanModule(%q)\", modulePath)\n\n\tvar mvs []ModuleVersion\n\terr = db.db.RunQuery(ctx, `\n\t\tSELECT version\n\t\tFROM modules\n\t\tWHERE module_path = $1\n\t`, func(rows *sql.Rows) error {\n\t\tvar v string\n\t\tif err := rows.Scan(&v); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmvs = append(mvs, ModuleVersion{modulePath, v})\n\t\treturn nil\n\t}, modulePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn db.CleanModuleVersions(ctx, mvs, reason)\n}\n<commit_msg>internal\/postgres: do not clean std@dev.fuzz<commit_after>\/\/ Copyright 2021 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Functions for cleaning the database of unwanted module versions.\n\npackage postgres\n\nimport (\n\t\"context\"\n\t\"database\/sql\"\n\n\t\"golang.org\/x\/pkgsite\/internal\/derrors\"\n)\n\n\/\/ A ModuleVersion holds a module path and version.\ntype ModuleVersion struct {\n\tModulePath string\n\tVersion    string\n}\n\nfunc (mv ModuleVersion) String() string {\n\treturn mv.ModulePath + \"@\" + mv.Version\n}\n\n\/\/ GetModuleVersionsToClean returns module versions that can be removed from the database.\n\/\/ Only module versions that were updated more than daysOld days ago will be considered.\n\/\/ At most limit module versions will be returned.\nfunc (db *DB) GetModuleVersionsToClean(ctx context.Context, daysOld, limit int) (modvers []ModuleVersion, err error) {\n\tdefer derrors.WrapStack(&err, \"GetModuleVersionsToClean(%d, %d)\", daysOld, limit)\n\n\t\/\/ Get all pseudo-versions that were added before the given number of days.\n\t\/\/ Then remove:\n\t\/\/ - The ones that are the latest versions for their module,\n\t\/\/ - The ones in search_documents (since the latest version of a package might be at an older version),\n\t\/\/ - The ones that the master or main branch resolves to.\n\tquery := `\n\t\tSELECT module_path, version\n\t\tFROM modules\n\t\tWHERE version_type = 'pseudo'\n\t\tAND CURRENT_TIMESTAMP - updated_at > make_interval(days => $1)\n\t\tEXCEPT (\n\t\t\tSELECT p.path, l.good_version\n\t\t\tFROM latest_module_versions l\n\t\t\tINNER JOIN paths p ON p.id = l.module_path_id\n\t\t\tWHERE good_version != ''\n\t\t)\n\t\tEXCEPT (\n\t\t\tSELECT module_path, version\n\t\t\tFROM search_documents\n\t\t)\n\t\tEXCEPT (\n\t\t\tSELECT module_path, resolved_version\n\t\t\tFROM version_map\n\t\t\tWHERE requested_version IN ('master', 'main', 'dev.fuzz')\n\t\t)\n\t\tLIMIT $2\n\t`\n\n\terr = db.db.RunQuery(ctx, query, func(rows *sql.Rows) error {\n\t\tvar mv ModuleVersion\n\t\tif err := rows.Scan(&mv.ModulePath, &mv.Version); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmodvers = append(modvers, mv)\n\t\treturn nil\n\t}, daysOld, limit)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn modvers, nil\n}\n\n\/\/ CleanModuleVersions deletes each module version from the DB and marks it as cleaned\n\/\/ in module_version_states.\nfunc (db *DB) CleanModuleVersions(ctx context.Context, mvs []ModuleVersion, reason string) (err error) {\n\tdefer derrors.Wrap(&err, \"CleanModuleVersions(%d modules)\", len(mvs))\n\n\tstatus := derrors.ToStatus(derrors.Cleaned)\n\tfor _, mv := range mvs {\n\t\tif err := db.UpdateModuleVersionStatus(ctx, mv.ModulePath, mv.Version, status, reason); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := db.DeleteModule(ctx, mv.ModulePath, mv.Version); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ CleanModule deletes all versions of the given module path from the DB and marks them\n\/\/ as cleaned in module_version_states.\nfunc (db *DB) CleanModule(ctx context.Context, modulePath, reason string) (err error) {\n\tdefer derrors.Wrap(&err, \"CleanModule(%q)\", modulePath)\n\n\tvar mvs []ModuleVersion\n\terr = db.db.RunQuery(ctx, `\n\t\tSELECT version\n\t\tFROM modules\n\t\tWHERE module_path = $1\n\t`, func(rows *sql.Rows) error {\n\t\tvar v string\n\t\tif err := rows.Scan(&v); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmvs = append(mvs, ModuleVersion{modulePath, v})\n\t\treturn nil\n\t}, modulePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn db.CleanModuleVersions(ctx, mvs, reason)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The Ceph-CSI Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\npackage util\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestRoundOffBytes(t *testing.T) {\n\ttype args struct {\n\t\tbytes int64\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant int64\n\t}{\n\t\t{\n\t\t\t\"1MiB conversions\",\n\t\t\targs{\n\t\t\t\tbytes: 1048576,\n\t\t\t},\n\t\t\t1048576,\n\t\t},\n\t\t{\n\t\t\t\"1000kiB conversion\",\n\t\t\targs{\n\t\t\t\tbytes: 1000,\n\t\t\t},\n\t\t\t1048576, \/\/ equal to 1MiB\n\t\t},\n\t\t{\n\t\t\t\"1.5Mib conversion\",\n\t\t\targs{\n\t\t\t\tbytes: 1572864,\n\t\t\t},\n\t\t\t2097152, \/\/ equal to 2MiB\n\t\t},\n\t\t{\n\t\t\t\"1.1MiB conversion\",\n\t\t\targs{\n\t\t\t\tbytes: 1153434,\n\t\t\t},\n\t\t\t2097152, \/\/ equal to 2MiB\n\t\t},\n\t\t{\n\t\t\t\"1.5GiB conversion\",\n\t\t\targs{\n\t\t\t\tbytes: 1610612736,\n\t\t\t},\n\t\t\t2147483648, \/\/ equal to 2GiB\n\t\t},\n\t\t{\n\t\t\t\"1.1GiB conversion\",\n\t\t\targs{\n\t\t\t\tbytes: 1181116007,\n\t\t\t},\n\t\t\t2147483648, \/\/ equal to 2GiB\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tts := tt\n\t\tt.Run(ts.name, func(t *testing.T) {\n\t\t\tif got := RoundOffBytes(ts.args.bytes); got != ts.want {\n\t\t\t\tt.Errorf(\"RoundOffBytes() = %v, want %v\", got, ts.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRoundOffVolSize(t *testing.T) {\n\ttype args struct {\n\t\tsize int64\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant int64\n\t}{\n\t\t{\n\t\t\t\"1MiB conversions\",\n\t\t\targs{\n\t\t\t\tsize: 1048576,\n\t\t\t},\n\t\t\t1, \/\/ MiB\n\t\t},\n\t\t{\n\t\t\t\"1000kiB conversion\",\n\t\t\targs{\n\t\t\t\tsize: 1000,\n\t\t\t},\n\t\t\t1, \/\/ MiB\n\t\t},\n\t\t{\n\t\t\t\"1.5Mib conversion\",\n\t\t\targs{\n\t\t\t\tsize: 1572864,\n\t\t\t},\n\t\t\t2, \/\/ MiB\n\t\t},\n\t\t{\n\t\t\t\"1.1MiB conversion\",\n\t\t\targs{\n\t\t\t\tsize: 1153434,\n\t\t\t},\n\t\t\t2, \/\/ MiB\n\t\t},\n\t\t{\n\t\t\t\"1.5GiB conversion\",\n\t\t\targs{\n\t\t\t\tsize: 1610612736,\n\t\t\t},\n\t\t\t2048, \/\/ MiB\n\t\t},\n\t\t{\n\t\t\t\"1.1GiB conversion\",\n\t\t\targs{\n\t\t\t\tsize: 1181116007,\n\t\t\t},\n\t\t\t2048, \/\/ MiB\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tts := tt\n\t\tt.Run(ts.name, func(t *testing.T) {\n\t\t\tif got := RoundOffVolSize(ts.args.size); got != ts.want {\n\t\t\t\tt.Errorf(\"RoundOffVolSize() = %v, want %v\", got, ts.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetKernelVersion(t *testing.T) {\n\tversion, err := GetKernelVersion()\n\tif err != nil {\n\t\tt.Errorf(\"failed to get kernel version: %s\", err)\n\t}\n\tif version == \"\" {\n\t\tt.Error(\"version is empty, this is unexpected?!\")\n\t}\n\tif strings.HasSuffix(version, \"\\x00\") {\n\t\tt.Error(\"version ends with \\\\x00 byte(s)\")\n\t}\n}\n\nfunc TestMountOptionsAdd(t *testing.T) {\n\tmoaTests := []struct {\n\t\tname         string\n\t\tmountOptions string\n\t\toption       []string\n\t\tresult       string\n\t}{\n\t\t{\n\t\t\t\"add option to empty string\",\n\t\t\t\"\",\n\t\t\t[]string{\"new_option\"},\n\t\t\t\"new_option\",\n\t\t},\n\t\t{\n\t\t\t\"add empty option to string\",\n\t\t\t\"orig_option\",\n\t\t\t[]string{\"\"},\n\t\t\t\"orig_option\",\n\t\t},\n\t\t{\n\t\t\t\"add empty option to empty string\",\n\t\t\t\"\",\n\t\t\t[]string{\"\"},\n\t\t\t\"\",\n\t\t},\n\t\t{\n\t\t\t\"add option to single option string\",\n\t\t\t\"orig_option\",\n\t\t\t[]string{\"new_option\"},\n\t\t\t\"orig_option,new_option\",\n\t\t},\n\t\t{\n\t\t\t\"add option to multi option string\",\n\t\t\t\"orig_option,2nd_option\",\n\t\t\t[]string{\"new_option\"},\n\t\t\t\"orig_option,2nd_option,new_option\",\n\t\t},\n\t\t{\n\t\t\t\"add redundant option to multi option string\",\n\t\t\t\"orig_option,2nd_option\",\n\t\t\t[]string{\"2nd_option\"},\n\t\t\t\"orig_option,2nd_option\",\n\t\t},\n\t\t{\n\t\t\t\"add option to multi option string starting with ,\",\n\t\t\t\",orig_option,2nd_option\",\n\t\t\t[]string{\"new_option\"},\n\t\t\t\"orig_option,2nd_option,new_option\",\n\t\t},\n\t\t{\n\t\t\t\"add option to multi option string with trailing ,\",\n\t\t\t\"orig_option,2nd_option,\",\n\t\t\t[]string{\"new_option\"},\n\t\t\t\"orig_option,2nd_option,new_option\",\n\t\t},\n\t\t{\n\t\t\t\"add options to multi option string\",\n\t\t\t\"orig_option,2nd_option,\",\n\t\t\t[]string{\"new_option\", \"another_option\"},\n\t\t\t\"orig_option,2nd_option,new_option,another_option\",\n\t\t},\n\t\t{\n\t\t\t\"add options (one redundant) to multi option string\",\n\t\t\t\"orig_option,2nd_option,\",\n\t\t\t[]string{\"new_option\", \"2nd_option\", \"another_option\"},\n\t\t\t\"orig_option,2nd_option,new_option,another_option\",\n\t\t},\n\t}\n\n\tfor _, moaTest := range moaTests {\n\t\tmt := moaTest\n\t\tt.Run(moaTest.name, func(t *testing.T) {\n\t\t\tresult := MountOptionsAdd(mt.mountOptions, mt.option...)\n\t\t\tif result != mt.result {\n\t\t\t\tt.Errorf(\"MountOptionsAdd(): %v, want %v\", result, mt.result)\n\t\t\t}\n\t\t})\n\t}\n}\nfunc TestCheckKernelSupport(t *testing.T) {\n\tsupportsQuota := []string{\n\t\t\"4.17.0\",\n\t\t\"5.0.0\",\n\t\t\"4.17.0-rc1\",\n\t\t\"4.18.0-80.el8\",\n\t\t\"3.10.0-1062.el7.x86_64\",     \/\/ 1st backport\n\t\t\"3.10.0-1062.4.1.el7.x86_64\", \/\/ updated backport\n\t}\n\n\tnoQuota := []string{\n\t\t\"2.6.32-754.15.3.el6.x86_64\", \/\/ too old\n\t\t\"3.10.0-123.el7.x86_64\",      \/\/ too old for backport\n\t\t\"3.10.0-1062.4.1.el8.x86_64\", \/\/ nonexisting RHEL-8 kernel\n\t\t\"3.11.0-123.el7.x86_64\",      \/\/ nonexisting RHEL-7 kernel\n\t}\n\n\tquotaSupport := []KernelVersion{\n\t\t{4, 17, 0, 0, \"\", false},       \/\/ standard 4.17+ versions\n\t\t{3, 10, 0, 1062, \".el7\", true}, \/\/ RHEL-7.7\n\t}\n\tfor _, kernel := range supportsQuota {\n\t\tok := CheckKernelSupport(kernel, quotaSupport)\n\t\tif !ok {\n\t\t\tt.Errorf(\"support expected for %s\", kernel)\n\t\t}\n\t}\n\n\tfor _, kernel := range noQuota {\n\t\tok := CheckKernelSupport(kernel, quotaSupport)\n\t\tif ok {\n\t\t\tt.Errorf(\"no support expected for %s\", kernel)\n\t\t}\n\t}\n\n\tsupportsDeepFlatten := []string{\n\t\t\"5.2.0\",\n\t\t\"5.3.0\",\n\t}\n\n\tnoDeepFlatten := []string{\n\t\t\"4.18.0\",                     \/\/ too old\n\t\t\"3.10.0-123.el7.x86_64\",      \/\/ too old for backport\n\t\t\"3.10.0-1062.4.1.el8.x86_64\", \/\/ nonexisting RHEL-8 kernel\n\t\t\"3.11.0-123.el7.x86_64\",      \/\/ nonexisting RHEL-7 kernel\n\t}\n\n\tdeepFlattenSupport := []KernelVersion{\n\t\t{5, 2, 0, 0, \"\", false}, \/\/ standard 5.2+ versions\n\t}\n\tfor _, kernel := range supportsDeepFlatten {\n\t\tok := CheckKernelSupport(kernel, deepFlattenSupport)\n\t\tif !ok {\n\t\t\tt.Errorf(\"support expected for %s\", kernel)\n\t\t}\n\t}\n\n\tfor _, kernel := range noDeepFlatten {\n\t\tok := CheckKernelSupport(kernel, deepFlattenSupport)\n\t\tif ok {\n\t\t\tt.Errorf(\"no support expected for %s\", kernel)\n\t\t}\n\t}\n}\n<commit_msg>util: update unit testing for deep flatten<commit_after>\/*\nCopyright 2019 The Ceph-CSI Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\npackage util\n\nimport (\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestRoundOffBytes(t *testing.T) {\n\ttype args struct {\n\t\tbytes int64\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant int64\n\t}{\n\t\t{\n\t\t\t\"1MiB conversions\",\n\t\t\targs{\n\t\t\t\tbytes: 1048576,\n\t\t\t},\n\t\t\t1048576,\n\t\t},\n\t\t{\n\t\t\t\"1000kiB conversion\",\n\t\t\targs{\n\t\t\t\tbytes: 1000,\n\t\t\t},\n\t\t\t1048576, \/\/ equal to 1MiB\n\t\t},\n\t\t{\n\t\t\t\"1.5Mib conversion\",\n\t\t\targs{\n\t\t\t\tbytes: 1572864,\n\t\t\t},\n\t\t\t2097152, \/\/ equal to 2MiB\n\t\t},\n\t\t{\n\t\t\t\"1.1MiB conversion\",\n\t\t\targs{\n\t\t\t\tbytes: 1153434,\n\t\t\t},\n\t\t\t2097152, \/\/ equal to 2MiB\n\t\t},\n\t\t{\n\t\t\t\"1.5GiB conversion\",\n\t\t\targs{\n\t\t\t\tbytes: 1610612736,\n\t\t\t},\n\t\t\t2147483648, \/\/ equal to 2GiB\n\t\t},\n\t\t{\n\t\t\t\"1.1GiB conversion\",\n\t\t\targs{\n\t\t\t\tbytes: 1181116007,\n\t\t\t},\n\t\t\t2147483648, \/\/ equal to 2GiB\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tts := tt\n\t\tt.Run(ts.name, func(t *testing.T) {\n\t\t\tif got := RoundOffBytes(ts.args.bytes); got != ts.want {\n\t\t\t\tt.Errorf(\"RoundOffBytes() = %v, want %v\", got, ts.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRoundOffVolSize(t *testing.T) {\n\ttype args struct {\n\t\tsize int64\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant int64\n\t}{\n\t\t{\n\t\t\t\"1MiB conversions\",\n\t\t\targs{\n\t\t\t\tsize: 1048576,\n\t\t\t},\n\t\t\t1, \/\/ MiB\n\t\t},\n\t\t{\n\t\t\t\"1000kiB conversion\",\n\t\t\targs{\n\t\t\t\tsize: 1000,\n\t\t\t},\n\t\t\t1, \/\/ MiB\n\t\t},\n\t\t{\n\t\t\t\"1.5Mib conversion\",\n\t\t\targs{\n\t\t\t\tsize: 1572864,\n\t\t\t},\n\t\t\t2, \/\/ MiB\n\t\t},\n\t\t{\n\t\t\t\"1.1MiB conversion\",\n\t\t\targs{\n\t\t\t\tsize: 1153434,\n\t\t\t},\n\t\t\t2, \/\/ MiB\n\t\t},\n\t\t{\n\t\t\t\"1.5GiB conversion\",\n\t\t\targs{\n\t\t\t\tsize: 1610612736,\n\t\t\t},\n\t\t\t2048, \/\/ MiB\n\t\t},\n\t\t{\n\t\t\t\"1.1GiB conversion\",\n\t\t\targs{\n\t\t\t\tsize: 1181116007,\n\t\t\t},\n\t\t\t2048, \/\/ MiB\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tts := tt\n\t\tt.Run(ts.name, func(t *testing.T) {\n\t\t\tif got := RoundOffVolSize(ts.args.size); got != ts.want {\n\t\t\t\tt.Errorf(\"RoundOffVolSize() = %v, want %v\", got, ts.want)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetKernelVersion(t *testing.T) {\n\tversion, err := GetKernelVersion()\n\tif err != nil {\n\t\tt.Errorf(\"failed to get kernel version: %s\", err)\n\t}\n\tif version == \"\" {\n\t\tt.Error(\"version is empty, this is unexpected?!\")\n\t}\n\tif strings.HasSuffix(version, \"\\x00\") {\n\t\tt.Error(\"version ends with \\\\x00 byte(s)\")\n\t}\n}\n\nfunc TestMountOptionsAdd(t *testing.T) {\n\tmoaTests := []struct {\n\t\tname         string\n\t\tmountOptions string\n\t\toption       []string\n\t\tresult       string\n\t}{\n\t\t{\n\t\t\t\"add option to empty string\",\n\t\t\t\"\",\n\t\t\t[]string{\"new_option\"},\n\t\t\t\"new_option\",\n\t\t},\n\t\t{\n\t\t\t\"add empty option to string\",\n\t\t\t\"orig_option\",\n\t\t\t[]string{\"\"},\n\t\t\t\"orig_option\",\n\t\t},\n\t\t{\n\t\t\t\"add empty option to empty string\",\n\t\t\t\"\",\n\t\t\t[]string{\"\"},\n\t\t\t\"\",\n\t\t},\n\t\t{\n\t\t\t\"add option to single option string\",\n\t\t\t\"orig_option\",\n\t\t\t[]string{\"new_option\"},\n\t\t\t\"orig_option,new_option\",\n\t\t},\n\t\t{\n\t\t\t\"add option to multi option string\",\n\t\t\t\"orig_option,2nd_option\",\n\t\t\t[]string{\"new_option\"},\n\t\t\t\"orig_option,2nd_option,new_option\",\n\t\t},\n\t\t{\n\t\t\t\"add redundant option to multi option string\",\n\t\t\t\"orig_option,2nd_option\",\n\t\t\t[]string{\"2nd_option\"},\n\t\t\t\"orig_option,2nd_option\",\n\t\t},\n\t\t{\n\t\t\t\"add option to multi option string starting with ,\",\n\t\t\t\",orig_option,2nd_option\",\n\t\t\t[]string{\"new_option\"},\n\t\t\t\"orig_option,2nd_option,new_option\",\n\t\t},\n\t\t{\n\t\t\t\"add option to multi option string with trailing ,\",\n\t\t\t\"orig_option,2nd_option,\",\n\t\t\t[]string{\"new_option\"},\n\t\t\t\"orig_option,2nd_option,new_option\",\n\t\t},\n\t\t{\n\t\t\t\"add options to multi option string\",\n\t\t\t\"orig_option,2nd_option,\",\n\t\t\t[]string{\"new_option\", \"another_option\"},\n\t\t\t\"orig_option,2nd_option,new_option,another_option\",\n\t\t},\n\t\t{\n\t\t\t\"add options (one redundant) to multi option string\",\n\t\t\t\"orig_option,2nd_option,\",\n\t\t\t[]string{\"new_option\", \"2nd_option\", \"another_option\"},\n\t\t\t\"orig_option,2nd_option,new_option,another_option\",\n\t\t},\n\t}\n\n\tfor _, moaTest := range moaTests {\n\t\tmt := moaTest\n\t\tt.Run(moaTest.name, func(t *testing.T) {\n\t\t\tresult := MountOptionsAdd(mt.mountOptions, mt.option...)\n\t\t\tif result != mt.result {\n\t\t\t\tt.Errorf(\"MountOptionsAdd(): %v, want %v\", result, mt.result)\n\t\t\t}\n\t\t})\n\t}\n}\nfunc TestCheckKernelSupport(t *testing.T) {\n\tsupportsQuota := []string{\n\t\t\"4.17.0\",\n\t\t\"5.0.0\",\n\t\t\"4.17.0-rc1\",\n\t\t\"4.18.0-80.el8\",\n\t\t\"3.10.0-1062.el7.x86_64\",     \/\/ 1st backport\n\t\t\"3.10.0-1062.4.1.el7.x86_64\", \/\/ updated backport\n\t}\n\n\tnoQuota := []string{\n\t\t\"2.6.32-754.15.3.el6.x86_64\", \/\/ too old\n\t\t\"3.10.0-123.el7.x86_64\",      \/\/ too old for backport\n\t\t\"3.10.0-1062.4.1.el8.x86_64\", \/\/ nonexisting RHEL-8 kernel\n\t\t\"3.11.0-123.el7.x86_64\",      \/\/ nonexisting RHEL-7 kernel\n\t}\n\n\tquotaSupport := []KernelVersion{\n\t\t{4, 17, 0, 0, \"\", false},       \/\/ standard 4.17+ versions\n\t\t{3, 10, 0, 1062, \".el7\", true}, \/\/ RHEL-7.7\n\t}\n\tfor _, kernel := range supportsQuota {\n\t\tok := CheckKernelSupport(kernel, quotaSupport)\n\t\tif !ok {\n\t\t\tt.Errorf(\"support expected for %s\", kernel)\n\t\t}\n\t}\n\n\tfor _, kernel := range noQuota {\n\t\tok := CheckKernelSupport(kernel, quotaSupport)\n\t\tif ok {\n\t\t\tt.Errorf(\"no support expected for %s\", kernel)\n\t\t}\n\t}\n\n\tsupportsDeepFlatten := []string{\n\t\t\"5.1.0\", \/\/ 5.1+ supports deep-flatten\n\t\t\"5.3.0\",\n\t\t\"4.18.0-193.9.1.el8_2.x86_64\", \/\/ RHEL 8.2 kernel\n\t}\n\n\tnoDeepFlatten := []string{\n\t\t\"4.18.0\",                     \/\/ too old\n\t\t\"3.10.0-123.el7.x86_64\",      \/\/ too old for backport\n\t\t\"3.10.0-1062.4.1.el8.x86_64\", \/\/ nonexisting RHEL-8 kernel\n\t\t\"3.11.0-123.el7.x86_64\",      \/\/ nonexisting RHEL-7 kernel\n\t}\n\n\tdeepFlattenSupport := []KernelVersion{\n\t\t{5, 1, 0, 0, \"\", false},       \/\/ standard 5.1+ versions\n\t\t{4, 18, 0, 193, \".el8\", true}, \/\/ RHEL 8.2 backport\n\t}\n\tfor _, kernel := range supportsDeepFlatten {\n\t\tok := CheckKernelSupport(kernel, deepFlattenSupport)\n\t\tif !ok {\n\t\t\tt.Errorf(\"support expected for %s\", kernel)\n\t\t}\n\t}\n\n\tfor _, kernel := range noDeepFlatten {\n\t\tok := CheckKernelSupport(kernel, deepFlattenSupport)\n\t\tif ok {\n\t\t\tt.Errorf(\"no support expected for %s\", kernel)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Finish interpolate.go<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc generateInitialConditions(leftEndPoint float64, rightEndPoint float64, numPoints int) ([]float64, []float64) {\n\tvar deltaX = (rightEndPoint - leftEndPoint) \/ float64(numPoints)\n\tvar xVals = make([]float64, numPoints+1)\n\tvar yVals = make([]float64, numPoints+1)\n\tfor i := 0; i <= numPoints; i++ {\n\t\txVals[i] = leftEndPoint + float64(i)*deltaX\n\t\tyVals[i] = math.Sin(20 * xVals[i]) \/\/ Change test function here\n\t}\n\treturn xVals, yVals\n}\n\nfunc printPolynomial(coeff []float64) {\n\tvar degree = len(coeff) - 1\n\tfmt.Print(coeff[0])\n\tfor i := 1; i <= degree; i++ {\n\t\tfmt.Print(\" + \")\n\t\tfmt.Printf(\"%f\", coeff[i])\n\t\tfmt.Print(\"x^\", i)\n\t}\n}\n\nfunc main() {\n\tleftEndPoint := float64(0)\n\trightEndPoint := float64(1)\n\tnumPoints := int(6)\n\txVals, yVals := generateInitialConditions(leftEndPoint, rightEndPoint, numPoints)\n\t\/\/ We follow the algorithm outlined on page 332\n\tcoeff := yVals\n\tfor j := 1; j <= numPoints; j++ {\n\t\tfor i := numPoints; i >= j; i-- {\n\t\t\tcoeff[i] = (coeff[i] - coeff[i-1]) \/ (xVals[i] - xVals[i-j])\n\t\t}\n\t}\n\t\/\/fmt.Print(\"p(x) = \")\n\tprintPolynomial(coeff)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Politecnico di Torino\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\npackage router\n\n\/\/Sanity Check Packet -> minimum length and correct checksum\n\/\/decrement TTL and recompute packet checksum (l3 recompute checksum)\n\n\/\/lookup in the longest prefix matching table:\n\/\/destination ip address of the packet.\n\n\/\/LONGEST PREFIX MATCHING trivialimplementation\n\nvar RouterCode = `\n#include <linux\/ip.h>\n#include <linux\/bpf.h>\n\n\/\/ #define BPF_TRACE\n#undef BPF_TRACE\n\n#define BPF_LOG\n\/\/ #undef BPF_LOG\n\n#define ROUTING_TABLE_DIM 10\n#define ROUTER_PORT_N     10\n#define ARP_TABLE_DIM     10\n\n#define IP_TTL_OFFSET  8\n#define IP_CSUM_OFFSET 10\n\n#define ETH_DST_OFFSET  0\n#define ETH_SRC_OFFSET  6\n#define ETH_TYPE_OFFSET 12\n\n\/*Routing Table Entry*\/\nstruct rt_entry{\n  u32 network;  \/\/network: e.g. 192.168.1.0\n  u32 netmask;  \/\/netmask: e.g. 255.255.255.0\n  u32 port;     \/\/port of the router\n};\n\n\/*Router Port*\/\nstruct r_port{\n  u32 ip;       \/\/ip addr : e.g. 192.168.1.254\n  u32 netmask;  \/\/netmask : e.g. 255.255.255.0\n  u64 mac;      \/\/mac addr: e.g. a1:b2:c3:ab:cd:ef\n};\n\n\/*Arp Table Key*\/\nstruct arp_table_key{\n  u32 ip;       \/\/ip addr : e.g. 192.168.1.2\n  u32 port;     \/\/port    : e.g. 1\n};\n\n\/*\n  The Routing table is implemented as an array of struct rt_entry (Routing Table Entry)\n  the longest prefix matching algorithm (at least a simplified version)\n  is implemented performing a bounded loop over the entries of the routing table.\n  We assume that the control plane puts entry ordered from the longest netmask\n  to the shortest one.\n*\/\nBPF_TABLE(\"array\", u32, struct rt_entry, routing_table, ROUTING_TABLE_DIM);\n\n\/*\n  Router Port table provides a way to simulate the physical interface of the router\n  The ip address is used to answer to the arp request (TO IMPLEMENT)\n  The mac address is used as mac_scr for the outcoming packet on that interface,\n  and as mac address contained in the arp reply\n*\/\nBPF_TABLE(\"hash\", u32, struct r_port, router_port, ROUTER_PORT_N);\n\n\/*\n  We shold have an arp table for each port of the router?\n  For now we assume to send packet exiting the router interfaces in broadcast\n  (mac dst = ff:ff:ff:ff:ff:ff)\n\n  How can we implement multiple arp tables?\n  One possible implementation using one single map is the following\n  key{ ip + port number } -> value {mac_address}\n*\/\nBPF_TABLE(\"hash\", struct arp_table_key, u64, arp_table, ARP_TABLE_DIM);\n\nstatic int handle_rx(void *skb, struct metadata *md) {\n  u8 *cursor = 0;\n  struct ethernet_t *ethernet = cursor_advance(cursor, sizeof(*ethernet));\n\n  #ifdef BPF_TRACE\n    bpf_trace_printk(\"[router]: in_ifc:%d\\n\", md->in_ifc);\n    bpf_trace_printk(\"[router]: eth_type:%x mac_scr:%lx mac_dst:%lx\\n\",\n      ethernet->type, ethernet->src, ethernet->dst);\n  #endif\n\n  \/\/TODO\n  \/\/sanity check of the packet.\n  \/\/if something wrong -> DROP the packet\n\n  struct ip_t *ip = cursor_advance(cursor, sizeof(*ip));\n\n  #ifdef BPF_TRACE\n    bpf_trace_printk(\"[router]: ttl:%u ip_scr:%x ip_dst:%x \\n\", ip->ttl, ip->src, ip->dst);\n    \/\/ bpf_trace_printk(\"[router]: (before) ttl: %d checksum: %x\\n\", ip->ttl, ip->hchecksum);\n  #endif\n\n  \/*\n    decrement TTL and recompute packet checksum (l3 recompute checksum).\n    if ttl <= 1 DROP the packet.\n    eventually send ICMP message for the packet dropped.\n    (maybe to avoid for security reasons)\n  *\/\n\n  __u8 old_ttl = ip->ttl;\n  __u8 new_ttl;\n\n  if (old_ttl <= 1) {\n    #ifdef BPF_TRACE\n      bpf_trace_printk(\"[router]: packet DROP (ttl <= 1)\\n\");\n    #endif\n    return RX_DROP;\n  }\n\n  new_ttl = old_ttl - 1;\n  bpf_l3_csum_replace(skb, sizeof(*ethernet) + IP_CSUM_OFFSET , old_ttl, new_ttl, sizeof(__u16));\n  bpf_skb_store_bytes(skb, sizeof(*ethernet) + IP_TTL_OFFSET , &new_ttl, sizeof(old_ttl), 0);\n\n  #ifdef BPF_TRACE\n    \/\/ bpf_trace_printk(\"[router]: (after ) ttl: %d checksum: %x\\n\",ip->ttl,ip->hchecksum);\n  #endif\n\n  \/*\n    ROUTING ALGORITHM (simplified)\n\n    for each item in the routing table (upbounded loop)\n    apply the netmask on dst_ip_address\n    (possible optimization, not recompute if at next iteration the netmask is the same)\n    if masked address == network in the routing table\n      1- change src mac to otuput port mac\n      2- change dst mac to lookup arp table (or send to fffffffffffff)\n      3- forward the packet to dst port\n  *\/\n\n  int i = 0;\n  struct rt_entry *rt_entry_p = 0;\n\n  u64 new_src_mac = 0;\n  u64 new_dst_mac = 0;\n  u32 out_port = 0;\n  struct r_port *r_port_p = 0;\n\n  #pragma unroll\n  for (i = 0; i < ROUTING_TABLE_DIM; i++) {\n    u32 t = i;\n    rt_entry_p = routing_table.lookup(&t);\n     if (rt_entry_p) {\n      if ((ip->dst & rt_entry_p->netmask) == rt_entry_p->network) {\n        goto FORWARD;\n      }\n    }\n  }\n\nDROP:\n  #ifdef BPF_LOG\n    bpf_trace_printk(\"[router]: in: %d out: -- DROP\\n\", md->in_ifc);\n  #endif\n  return RX_DROP;\n\nFORWARD:\n  \/\/Select out interface\n  out_port = rt_entry_p->port;\n  if (out_port <= 0)\n    goto DROP;\n\n  #ifdef BPF_LOG\n    bpf_trace_printk(\"[router]: routing table match (#%d) network: %x\\n\",\n      i, rt_entry_p->network);\n  #endif\n\n  \/\/change src mac\n  r_port_p = router_port.lookup(&out_port);\n  if (r_port_p) {\n    new_src_mac = r_port_p->mac;\n    bpf_skb_store_bytes(skb,ETH_SRC_OFFSET, &new_src_mac, 6, 0);\n  }\n\n  \/\/change dst mac to ff:ff:ff:ff:ff:ff (TODO arp table)\n  new_dst_mac = 0xffffffffffff;\n  bpf_skb_store_bytes(skb, ETH_DST_OFFSET, &new_dst_mac, 6, 0);\n\n  #ifdef BPF_TRACE\n    bpf_trace_printk(\"[router]: eth_type:%x mac_scr:%lx mac_dst:%lx\\n\",\n      ethernet->type, ethernet->src, ethernet->dst);\n    bpf_trace_printk(\"[router]: out_ifc: %d\\n\", out_port);\n  #endif\n\n  #ifdef BPF_LOG\n    bpf_trace_printk(\"[router]: in: %d out: %d REDIRECT\\n\", md->in_ifc, out_port);\n  #endif\n\n  pkt_redirect(skb,md,out_port);\n  return RX_REDIRECT;\n\n}\n`\n<commit_msg>iomodules\/router: respond arp requests<commit_after>\/\/ Copyright 2016 Politecnico di Torino\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\npackage router\n\n\/\/Sanity Check Packet -> minimum length and correct checksum\n\/\/decrement TTL and recompute packet checksum (l3 recompute checksum)\n\n\/\/lookup in the longest prefix matching table:\n\/\/destination ip address of the packet.\n\n\/\/LONGEST PREFIX MATCHING trivialimplementation\n\nvar RouterCode = `\n#include <linux\/ip.h>\n#include <linux\/bpf.h>\n#include <linux\/kernel.h>\n\n\/\/ #define BPF_TRACE\n#undef BPF_TRACE\n\n#define BPF_LOG\n\/\/ #undef BPF_LOG\n\n#define ROUTING_TABLE_DIM 10\n#define ROUTER_PORT_N     10\n#define ARP_TABLE_DIM     10\n\n#define IP_TTL_OFFSET  8\n#define IP_CSUM_OFFSET 10\n\n#define ETH_DST_OFFSET  0\n#define ETH_SRC_OFFSET  6\n#define ETH_TYPE_OFFSET 12\n\n\/*Routing Table Entry*\/\nstruct rt_entry{\n  u32 network;  \/\/network: e.g. 192.168.1.0\n  u32 netmask;  \/\/netmask: e.g. 255.255.255.0\n  u32 port;     \/\/port of the router\n};\n\n\/*Router Port*\/\nstruct r_port{\n  u32 ip;       \/\/ip addr : e.g. 192.168.1.254\n  u32 netmask;  \/\/netmask : e.g. 255.255.255.0\n  u64 mac;      \/\/mac addr: e.g. a1:b2:c3:ab:cd:ef\n};\n\n\/*Arp Table Key*\/\nstruct arp_table_key{\n  u32 ip;       \/\/ip addr : e.g. 192.168.1.2\n  u32 port;     \/\/port    : e.g. 1\n};\n\n\/*\n  The Routing table is implemented as an array of struct rt_entry (Routing Table Entry)\n  the longest prefix matching algorithm (at least a simplified version)\n  is implemented performing a bounded loop over the entries of the routing table.\n  We assume that the control plane puts entry ordered from the longest netmask\n  to the shortest one.\n*\/\nBPF_TABLE(\"array\", u32, struct rt_entry, routing_table, ROUTING_TABLE_DIM);\n\n\/*\n  Router Port table provides a way to simulate the physical interface of the router\n  The ip address is used to answer to the arp request (TO IMPLEMENT)\n  The mac address is used as mac_scr for the outcoming packet on that interface,\n  and as mac address contained in the arp reply\n*\/\nBPF_TABLE(\"hash\", u32, struct r_port, router_port, ROUTER_PORT_N);\n\n\/*\n  We shold have an arp table for each port of the router?\n  For now we assume to send packet exiting the router interfaces in broadcast\n  (mac dst = ff:ff:ff:ff:ff:ff)\n\n  How can we implement multiple arp tables?\n  One possible implementation using one single map is the following\n  key{ ip + port number } -> value {mac_address}\n*\/\nBPF_TABLE(\"hash\", u32, u64, arp_table, ARP_TABLE_DIM);\n\nstatic int handle_rx(void *skb, struct metadata *md) {\n  u8 *cursor = 0;\n  struct ethernet_t *ethernet = cursor_advance(cursor, sizeof(*ethernet));\n\n  #ifdef BPF_TRACE\n    bpf_trace_printk(\"[router]: in_ifc:%d\\n\", md->in_ifc);\n    bpf_trace_printk(\"[router]: eth_type:%x mac_scr:%lx mac_dst:%lx\\n\",\n      ethernet->type, ethernet->src, ethernet->dst);\n  #endif\n\n  \/\/TODO\n  \/\/sanity check of the packet.\n  \/\/if something wrong -> DROP the packet\n\n  \/\/ is it an ipv4 packet?\n  if (ethernet->type == 0x0800) {\n    struct ip_t *ip = cursor_advance(cursor, sizeof(*ip));\n\n    #ifdef BPF_TRACE\n      bpf_trace_printk(\"[router]: ttl:%u ip_scr:%x ip_dst:%x \\n\", ip->ttl, ip->src, ip->dst);\n      \/\/ bpf_trace_printk(\"[router]: (before) ttl: %d checksum: %x\\n\", ip->ttl, ip->hchecksum);\n    #endif\n\n    \/*\n      decrement TTL and recompute packet checksum (l3 recompute checksum).\n      if ttl <= 1 DROP the packet.\n      eventually send ICMP message for the packet dropped.\n      (maybe to avoid for security reasons)\n    *\/\n\n    __u8 old_ttl = ip->ttl;\n    __u8 new_ttl;\n\n    if (old_ttl <= 1) {\n      #ifdef BPF_TRACE\n        bpf_trace_printk(\"[router]: packet DROP (ttl <= 1)\\n\");\n      #endif\n      return RX_DROP;\n    }\n\n    new_ttl = old_ttl - 1;\n    bpf_l3_csum_replace(skb, sizeof(*ethernet) + IP_CSUM_OFFSET , old_ttl, new_ttl, sizeof(__u16));\n    bpf_skb_store_bytes(skb, sizeof(*ethernet) + IP_TTL_OFFSET , &new_ttl, sizeof(old_ttl), 0);\n\n    #ifdef BPF_TRACE\n      \/\/ bpf_trace_printk(\"[router]: (after ) ttl: %d checksum: %x\\n\",ip->ttl,ip->hchecksum);\n    #endif\n\n    \/*\n      ROUTING ALGORITHM (simplified)\n\n      for each item in the routing table (upbounded loop)\n      apply the netmask on dst_ip_address\n      (possible optimization, not recompute if at next iteration the netmask is the same)\n      if masked address == network in the routing table\n        1- change src mac to otuput port mac\n        2- change dst mac to lookup arp table (or send to fffffffffffff)\n        3- forward the packet to dst port\n    *\/\n\n    int i = 0;\n    struct rt_entry *rt_entry_p = 0;\n\n    u64 new_src_mac = 0;\n    u64 new_dst_mac = 0;\n    u32 out_port = 0;\n    struct r_port *r_port_p = 0;\n\n    #pragma unroll\n    for (i = 0; i < ROUTING_TABLE_DIM; i++) {\n      u32 t = i;\n      rt_entry_p = routing_table.lookup(&t);\n       if (rt_entry_p) {\n        if ((ip->dst & rt_entry_p->netmask) == rt_entry_p->network) {\n          goto FORWARD;\n        }\n      }\n    }\n\n  DROP:\n    #ifdef BPF_LOG\n      bpf_trace_printk(\"[router]: in: %d out: -- DROP\\n\", md->in_ifc);\n    #endif\n    return RX_DROP;\n\n  FORWARD:\n    \/\/Select out interface\n    out_port = rt_entry_p->port;\n    if (out_port <= 0)\n      goto DROP;\n\n    #ifdef BPF_LOG\n      bpf_trace_printk(\"[router]: routing table match (#%d) network: %x\\n\",\n        i, rt_entry_p->network);\n    #endif\n\n    \/\/change src mac\n    r_port_p = router_port.lookup(&out_port);\n    if (r_port_p) {\n      new_src_mac = cpu_to_be64(r_port_p->mac<<16);\n      bpf_skb_store_bytes(skb,ETH_SRC_OFFSET, &new_src_mac, 6, 0);\n    }\n\n    \/\/change dst mac to ff:ff:ff:ff:ff:ff (TODO arp table)\n    new_dst_mac = 0xffffffffffff;\n    bpf_skb_store_bytes(skb, ETH_DST_OFFSET, &new_dst_mac, 6, 0);\n\n    #ifdef BPF_TRACE\n      bpf_trace_printk(\"[router]: eth_type:%x mac_scr:%lx mac_dst:%lx\\n\",\n        ethernet->type, ethernet->src, ethernet->dst);\n      bpf_trace_printk(\"[router]: out_ifc: %d\\n\", out_port);\n    #endif\n\n    #ifdef BPF_LOG\n      bpf_trace_printk(\"[router]: in: %d out: %d REDIRECT\\n\", md->in_ifc, out_port);\n    #endif\n\n    pkt_redirect(skb,md,out_port);\n    return RX_REDIRECT;\n  }\n  else if(ethernet->type == 0x0806) { \/\/ is it ARP?\n    struct arp_t *arp = cursor_advance(cursor, sizeof(*arp));\n    if (arp->oper == 1) {\t\/\/ arp request?\n      bpf_trace_printk(\"[arp]: packet is arp request\\n\");\n\n      struct r_port *port = router_port.lookup(&md->in_ifc);\n      if (!port)\n        return RX_DROP;\n      if (arp->tpa == port->ip) {\n        bpf_trace_printk(\"[arp]: Somebody is asking for my address\\n\");\n\n        \/* answer arp request *\/\n\n        u16 two = cpu_to_be16(0x0002);\n        u64 mymac = cpu_to_be64(port->mac<<16);\n        u64 remotemac = arp->sha;\n        remotemac = cpu_to_be64(remotemac<<16);\n        u32 myip = cpu_to_be32(port->ip);\n        u32 remoteip = arp->spa;\n        remoteip = cpu_to_be32(remoteip);\n\n        bpf_skb_store_bytes(skb, 0, &remotemac, 6, 0); \/\/ dst_mac\n        bpf_skb_store_bytes(skb, 6, &mymac, 6, 0); \/\/ src_mac\n        bpf_skb_store_bytes(skb, sizeof(*ethernet)+6, &two, 2, 0); \/\/ operation\n        bpf_skb_store_bytes(skb, sizeof(*ethernet)+8, &mymac, 6, 0);\/\/ sha\n        bpf_skb_store_bytes(skb, sizeof(*ethernet)+14, &myip, 4, 1);\/\/ spa\n        bpf_skb_store_bytes(skb, sizeof(*ethernet)+18, &remotemac, 6, 0);\/\/ tha\n        bpf_skb_store_bytes(skb, sizeof(*ethernet)+24, &remoteip, 4, 0);\/\/ tpa\n\n        pkt_redirect(skb, md, md->in_ifc);\n\n        return RX_REDIRECT;\n\n      }\n    }\n    else if (arp->oper == 2) { \/\/arp reply\n      bpf_trace_printk(\"[arp]: packet is arp reply\\n\");\n\n      struct r_port *port = router_port.lookup(&md->in_ifc);\n      if (!port)\n        return RX_DROP;\n      if (arp->sha == port->mac && arp->spa == port->ip) {\n        u64 mac_ = port->mac;\n        u32 ip_ = port->ip;\n        arp_table.update(&ip_, &mac_);\n        return RX_DROP;\n      }\n    }\n\t}\n\n  return RX_DROP;\n}\n`\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013-2016 Adam Presley. All rights reserved\n\/\/ Use of this source code is governed by the MIT license\n\/\/ that can be found in the LICENSE file.\n\npackage datetime\n\nimport (\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar dateInputFormats = []string{\n\t\"Mon, 02 Jan 2006 15:04:05 -0700\",\n\t\"Mon, 02 Jan 2006 15:04:05 -0700 MST\",\n\t\"Mon, 02 Jan 2006 15:04:05 -0700 (MST)\",\n\t\"Mon, 2 Jan 2006 15:04:05 -0700 (MST)\",\n\t\"02 Jan 2006 15:04:05 -0700\",\n}\n\n\/*\nParseDateTime takes a date\/time string and attempts to parse it and return a newly formatted\ndate\/time that looks like YYYY-MM-DD HH:MM:SS\n*\/\nfunc ParseDateTime(dateString string) string {\n\toutputFormat := \"2006-01-02 15:04:05\"\n\tvar parsedTime time.Time\n\tvar err error\n\n\tdateString = strings.TrimSpace(dateString)\n\tresult := \"\"\n\n\tfor _, inputFormat := range dateInputFormats {\n\t\tif parsedTime, err = time.Parse(inputFormat, dateString); err == nil {\n\t\t\tresult = parsedTime.Format(outputFormat)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif result == \"\" {\n\t\tlog.Printf(\"libmailslurper: ERROR - Parsing date %s\", dateString)\n\t\tresult = dateString\n\t}\n\n\treturn result\n}\n<commit_msg>Now parsing another date format. closes #41<commit_after>\/\/ Copyright 2013-2016 Adam Presley. All rights reserved\n\/\/ Use of this source code is governed by the MIT license\n\/\/ that can be found in the LICENSE file.\n\npackage datetime\n\nimport (\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar dateInputFormats = []string{\n\t\"Mon, 02 Jan 2006 15:04:05 -0700\",\n\t\"Mon, 02 Jan 2006 15:04:05 -0700 MST\",\n\t\"Mon, 02 Jan 2006 15:04:05 -0700 (MST)\",\n\t\"Mon, 2 Jan 2006 15:04:05 -0700 (MST)\",\n\t\"02 Jan 2006 15:04:05 -0700\",\n\t\"2 Jan 2006 15:04:05 -0700\",\n}\n\n\/*\nParseDateTime takes a date\/time string and attempts to parse it and return a newly formatted\ndate\/time that looks like YYYY-MM-DD HH:MM:SS\n*\/\nfunc ParseDateTime(dateString string) string {\n\toutputFormat := \"2006-01-02 15:04:05\"\n\tvar parsedTime time.Time\n\tvar err error\n\n\tdateString = strings.TrimSpace(dateString)\n\tresult := \"\"\n\n\tfor _, inputFormat := range dateInputFormats {\n\t\tif parsedTime, err = time.Parse(inputFormat, dateString); err == nil {\n\t\t\tresult = parsedTime.Format(outputFormat)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif result == \"\" {\n\t\tlog.Printf(\"libmailslurper: ERROR - Parsing date %s\", dateString)\n\t\tresult = dateString\n\t}\n\n\treturn result\n}\n<|endoftext|>"}
{"text":"<commit_before>package mails\n\nimport (\n\t\"bytes\"\n\t\"crypto\/md5\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"sync\"\n\n\t\"github.com\/toomore\/mailbox\/campaign\"\n\t\"github.com\/toomore\/mailbox\/utils\"\n)\n\nvar (\n\thtmla    = regexp.MustCompile(`href=\"(http[s]?:\/\/[a-zA-z0-9\/\\.:?=,-@%()_&\\+]+)\"`)\n\twashireg = regexp.MustCompile(`href=\"({{WASHI}}.+{{\\\/WASHI}})\"`)\n)\n\n\/\/ ReplaceReader is to replace reader open mail link\nfunc ReplaceReader(html *[]byte, cid string, seed string, uid string) {\n\tdata := url.Values{}\n\tdata.Set(\"c\", cid)\n\tdata.Set(\"u\", uid)\n\thm := campaign.MakeMacSeed(seed, data)\n\t*html = bytes.Replace(\n\t\t*html,\n\t\t[]byte(\"{{READER}}\"),\n\t\t[]byte(fmt.Sprintf(\"https:\/\/%s\/read\/%x?%s\", os.Getenv(\"mailbox_web_site\"), hm, data.Encode())),\n\t\t1)\n}\n\n\/\/ ReplaceFname is to replace FNAME tag\nfunc ReplaceFname(html *[]byte, fname string) {\n\t*html = bytes.Replace(*html, []byte(\"{{FNAME}}\"), []byte(fname), -1)\n}\n\n\/\/ ReplaceLname is to replace FNAME tag\nfunc ReplaceLname(html *[]byte, lname string) {\n\t*html = bytes.Replace(*html, []byte(\"{{LNAME}}\"), []byte(lname), -1)\n}\n\n\/\/ ReplaceATag is to replace HTML a tag\nfunc ReplaceATag(html *[]byte, allATags map[string]LinksData, cid string, seed string, uid string) {\n\tdata := url.Values{}\n\tdata.Set(\"c\", cid)\n\tdata.Set(\"u\", uid)\n\tdata.Set(\"t\", \"a\")\n\n\tfor _, v := range allATags {\n\t\tdata.Set(\"l\", v.LinkID)\n\t\thm := campaign.MakeMacSeed(seed, data)\n\n\t\t*html = bytes.Replace(*html, []byte(fmt.Sprintf(\"href=\\\"%s\\\"\", v.URL)),\n\t\t\t[]byte(fmt.Sprintf(\"href=\\\"https:\/\/%s\/door\/%x?%s\\\"\", os.Getenv(\"mailbox_web_site\"), hm, data.Encode())), -1)\n\t}\n}\n\n\/\/ ReplaceWashiTag is to replace HTML a tag\nfunc ReplaceWashiTag(html *[]byte, allATags map[string]LinksData, cid string, seed string, uid string) {\n\tdata := url.Values{}\n\tdata.Set(\"c\", cid)\n\tdata.Set(\"u\", uid)\n\n\tfor _, v := range allATags {\n\t\tdata.Set(\"l\", v.LinkID)\n\t\thm := campaign.MakeMacSeed(seed, data)\n\n\t\t*html = bytes.Replace(*html, []byte(fmt.Sprintf(\"href=\\\"%s\\\"\", v.URL)),\n\t\t\t[]byte(fmt.Sprintf(\"href=\\\"https:\/\/%s\/washi\/%x?%s\\\"\", os.Getenv(\"mailbox_web_site\"), hm, data.Encode())), -1)\n\t}\n}\n\n\/\/ LinksData is the link data\ntype LinksData struct {\n\tMd5h   string\n\tLinkID string\n\tURL    []byte\n}\n\n\/\/ FilterATags is to filter, find all a tag data\nfunc FilterATags(body *[]byte, cid string) map[string]LinksData {\n\treturn filteratags(htmla, body, cid)\n}\n\n\/\/ FilterWashiTags is to filter, find all {{WASHI}} tag data\nfunc FilterWashiTags(body *[]byte, cid string) map[string]LinksData {\n\treturn filteratags(washireg, body, cid)\n}\n\nfunc filteratags(rg *regexp.Regexp, body *[]byte, cid string) map[string]LinksData {\n\tallATags := rg.FindAllSubmatch(*body, -1)\n\tresult := make(map[string]LinksData)\n\tvar wg sync.WaitGroup\n\twg.Add(len(allATags))\n\tfor _, v := range allATags {\n\t\tgo func(url []byte) {\n\t\t\tmd5h := md5.New()\n\t\t\tmd5h.Write(url)\n\t\t\tmd5hstr := fmt.Sprintf(\"%x\", md5h.Sum(nil))\n\t\t\tlinkID := fmt.Sprintf(\"%s\", utils.GenSeed())\n\t\t\t_, err := utils.GetConn().Query(`INSERT INTO links(id,cid,url,urlhash) VALUES(?,?,?,?)`, linkID, cid, url, md5hstr)\n\t\t\tif err != nil {\n\t\t\t\trows, _ := utils.GetConn().Query(`SELECT id FROM links WHERE cid=? AND urlhash=?`, cid, md5hstr)\n\t\t\t\tfor rows.Next() {\n\t\t\t\t\trows.Scan(&linkID)\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult[linkID] = LinksData{\n\t\t\t\tMd5h:   md5hstr,\n\t\t\t\tLinkID: linkID,\n\t\t\t\tURL:    url,\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(v[1])\n\t}\n\twg.Wait()\n\treturn result\n}\n<commit_msg>Fixed many conn<commit_after>package mails\n\nimport (\n\t\"bytes\"\n\t\"crypto\/md5\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"sync\"\n\n\t\"github.com\/toomore\/mailbox\/campaign\"\n\t\"github.com\/toomore\/mailbox\/utils\"\n)\n\nvar (\n\thtmla    = regexp.MustCompile(`href=\"(http[s]?:\/\/[a-zA-z0-9\/\\.:?=,-@%()_&\\+]+)\"`)\n\twashireg = regexp.MustCompile(`href=\"({{WASHI}}.+{{\\\/WASHI}})\"`)\n)\n\n\/\/ ReplaceReader is to replace reader open mail link\nfunc ReplaceReader(html *[]byte, cid string, seed string, uid string) {\n\tdata := url.Values{}\n\tdata.Set(\"c\", cid)\n\tdata.Set(\"u\", uid)\n\thm := campaign.MakeMacSeed(seed, data)\n\t*html = bytes.Replace(\n\t\t*html,\n\t\t[]byte(\"{{READER}}\"),\n\t\t[]byte(fmt.Sprintf(\"https:\/\/%s\/read\/%x?%s\", os.Getenv(\"mailbox_web_site\"), hm, data.Encode())),\n\t\t1)\n}\n\n\/\/ ReplaceFname is to replace FNAME tag\nfunc ReplaceFname(html *[]byte, fname string) {\n\t*html = bytes.Replace(*html, []byte(\"{{FNAME}}\"), []byte(fname), -1)\n}\n\n\/\/ ReplaceLname is to replace FNAME tag\nfunc ReplaceLname(html *[]byte, lname string) {\n\t*html = bytes.Replace(*html, []byte(\"{{LNAME}}\"), []byte(lname), -1)\n}\n\n\/\/ ReplaceATag is to replace HTML a tag\nfunc ReplaceATag(html *[]byte, allATags map[string]LinksData, cid string, seed string, uid string) {\n\tdata := url.Values{}\n\tdata.Set(\"c\", cid)\n\tdata.Set(\"u\", uid)\n\tdata.Set(\"t\", \"a\")\n\n\tfor _, v := range allATags {\n\t\tdata.Set(\"l\", v.LinkID)\n\t\thm := campaign.MakeMacSeed(seed, data)\n\n\t\t*html = bytes.Replace(*html, []byte(fmt.Sprintf(\"href=\\\"%s\\\"\", v.URL)),\n\t\t\t[]byte(fmt.Sprintf(\"href=\\\"https:\/\/%s\/door\/%x?%s\\\"\", os.Getenv(\"mailbox_web_site\"), hm, data.Encode())), -1)\n\t}\n}\n\n\/\/ ReplaceWashiTag is to replace HTML a tag\nfunc ReplaceWashiTag(html *[]byte, allATags map[string]LinksData, cid string, seed string, uid string) {\n\tdata := url.Values{}\n\tdata.Set(\"c\", cid)\n\tdata.Set(\"u\", uid)\n\n\tfor _, v := range allATags {\n\t\tdata.Set(\"l\", v.LinkID)\n\t\thm := campaign.MakeMacSeed(seed, data)\n\n\t\t*html = bytes.Replace(*html, []byte(fmt.Sprintf(\"href=\\\"%s\\\"\", v.URL)),\n\t\t\t[]byte(fmt.Sprintf(\"href=\\\"https:\/\/%s\/washi\/%x?%s\\\"\", os.Getenv(\"mailbox_web_site\"), hm, data.Encode())), -1)\n\t}\n}\n\n\/\/ LinksData is the link data\ntype LinksData struct {\n\tMd5h   string\n\tLinkID string\n\tURL    []byte\n}\n\n\/\/ FilterATags is to filter, find all a tag data\nfunc FilterATags(body *[]byte, cid string) map[string]LinksData {\n\treturn filteratags(htmla, body, cid)\n}\n\n\/\/ FilterWashiTags is to filter, find all {{WASHI}} tag data\nfunc FilterWashiTags(body *[]byte, cid string) map[string]LinksData {\n\treturn filteratags(washireg, body, cid)\n}\n\nfunc filteratags(rg *regexp.Regexp, body *[]byte, cid string) map[string]LinksData {\n\tvar (\n\t\tallATags = rg.FindAllSubmatch(*body, -1)\n\t\tconn     = utils.GetConn()\n\t\tresult   = make(map[string]LinksData)\n\t\twg       sync.WaitGroup\n\t)\n\twg.Add(len(allATags))\n\tfor _, v := range allATags {\n\t\tgo func(url []byte) {\n\t\t\tmd5h := md5.New()\n\t\t\tmd5h.Write(url)\n\t\t\tmd5hstr := fmt.Sprintf(\"%x\", md5h.Sum(nil))\n\t\t\tlinkID := fmt.Sprintf(\"%s\", utils.GenSeed())\n\t\t\t_, err := conn.Query(`INSERT INTO links(id,cid,url,urlhash) VALUES(?,?,?,?)`, linkID, cid, url, md5hstr)\n\t\t\tif err != nil {\n\t\t\t\trows, _ := conn.Query(`SELECT id FROM links WHERE cid=? AND urlhash=?`, cid, md5hstr)\n\t\t\t\tfor rows.Next() {\n\t\t\t\t\trows.Scan(&linkID)\n\t\t\t\t}\n\t\t\t}\n\t\t\tresult[linkID] = LinksData{\n\t\t\t\tMd5h:   md5hstr,\n\t\t\t\tLinkID: linkID,\n\t\t\t\tURL:    url,\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(v[1])\n\t}\n\twg.Wait()\n\tconn.Close()\n\treturn result\n}\n<|endoftext|>"}
{"text":"<commit_before>package gps\n\nimport (\n\t\"strings\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\t\"reflect\"\n)\n\n\/\/ func validateNMEAChecksum determines if a string is a properly formatted NMEA sentence with a valid checksum.\n\/\/\n\/\/ If the input string is valid, output is the input stripped of the \"$\" token and checksum, along with a boolean 'true'\n\/\/ If the input string is the incorrect format, the checksum is missing\/invalid, or checksum calculation fails, an error string and\n\/\/ boolean 'false' are returned\n\/\/\n\/\/ Checksum is calculated as XOR of all bytes between \"$\" and \"*\"\nfunc validateNMEAChecksum(s string) (string, bool) {\n\t\/\/validate format. NMEA sentences start with \"$\" and end in \"*xx\" where xx is the XOR value of all bytes between\n\tif !(strings.HasPrefix(s, \"$\") && strings.Contains(s, \"*\")) {\n\t\treturn \"Invalid NMEA message\", false\n\t}\n\n\t\/\/ strip leading \"$\" and split at \"*\"\n\ts_split := strings.Split(strings.TrimPrefix(s, \"$\"), \"*\")\n\ts_out := s_split[0]\n\ts_cs := s_split[1]\n\n\tif len(s_cs) < 2 {\n\t\treturn \"Missing checksum. Fewer than two bytes after asterisk\", false\n\t}\n\n\tcs, err := strconv.ParseUint(s_cs[:2], 16, 8)\n\tif err != nil {\n\t\treturn \"Invalid checksum\", false\n\t}\n\n\tcs_calc := byte(0)\n\tfor i := range s_out {\n\t\tcs_calc = cs_calc ^ byte(s_out[i])\n\t}\n\n\tif cs_calc != byte(cs) {\n\t\treturn fmt.Sprintf(\"Checksum failed. Calculated %#X; expected %#X\", cs_calc, cs), false\n\t}\n\n\treturn s_out, true\n}\n\nfunc createChecksummedNMEASentence(raw []byte) []byte {\n\tcs_calc := byte(0)\n\tfor _,v := range raw {\n\t\tcs_calc ^= v\n\t}\n\n\treturn []byte(fmt.Sprintf(\"$%s*%02X\\r\\n\", raw, cs_calc))\n}\n\nfunc processNMEASentence(line string, situation *SituationData) {\n\tsentence, valid := validateNMEAChecksum(line)\n\tif !valid {\n\t\tlog.Printf(\"GPS Error: invalid NMEA string: %s\\n\", sentence)\n\t\treturn \n\t}\n\n\t\/\/log.Printf(\"Begin parse of %s\\n\", sentence)\n\tParseMessage(sentence, situation)\n}\n\ntype NMEA struct {\n\tSentence string\n\tTokens []string\n\tSituation *SituationData\n}\n\n\/\/ we split the sentence on commas, and use the first field via reflection to find a method with the same name\nfunc ParseMessage(sentence string, situation *SituationData) *NMEA {\n\tn := &NMEA{ sentence, strings.Split(sentence, \",\"), situation }\n\n\t\/\/log.Printf(\"NMEA Message type %s, data: %v\\n\", n.Tokens[0], n.Tokens[1:])\n\n\tv := reflect.ValueOf(n)\n\tm := v.MethodByName(n.Tokens[0])\n\n\tif (m == reflect.Value{}) {\n\t\treturn nil\n\t}\n\n\tm.Call(nil)\n\n\treturn n\n}\n\nfunc durationSinceMidnight(fixtime string) (int, error) {\n\thr, err := strconv.Atoi(fixtime[0:2]); if err != nil { return 0, err }\n\tmin, err := strconv.Atoi(fixtime[2:4]); if err != nil { return 0, err }\n\tsec, err := strconv.Atoi(fixtime[4:6]); if err != nil { return 0, err }\n\n\treturn sec + min*60 + hr*60*60, nil\n}\n\nfunc parseLatLon(s string, neg bool) (float32, error) {\n\tminpos := len(s) - 6\n\tdeg, err := strconv.Atoi(s[0:minpos]); if err != nil { return 0.0, err }\n\tmin, err := strconv.ParseFloat(s[minpos:], 32); if err != nil { return 0.0, err }\n\n\tsign := 1; if neg { sign = -1 }\n\n\treturn float32(sign) * (float32(deg) + float32(min\/60.0)), nil \n}\n\nfunc (n *NMEA) GNGGA() { n.GPGGA() } \/\/ ublox 8 uses GNGGA in place of GPGGA to indicate multiple nav sources (GPS\/GLONASS)\nfunc (n *NMEA) GPGGA() {\n\tlog.Printf(\"In GPGGA\\n\")\n\ts := n.Situation\n\n\ts.Mu_GPS.Lock(); defer s.Mu_GPS.Unlock()\n\n\td, err := durationSinceMidnight(n.Tokens[1]); if err != nil { return }\n\ts.LastFixSinceMidnightUTC = uint32(d)\n\n\tif len(n.Tokens[2]) < 4 || len(n.Tokens[4]) < 4 { return } \/\/ sanity check lat\/lon\n\n\tlat, err := parseLatLon(n.Tokens[2], n.Tokens[3] == \"S\"); if err != nil { return }\n\tlon, err := parseLatLon(n.Tokens[4], n.Tokens[5] == \"W\"); if err != nil { return }\n\n\ts.Lat = lat; s.Lng = lon\n\n\tlog.Printf(\"Situation: %v\\n\", s)\n}\n\n\nfunc (n *NMEA) GPGSA() {\n\tlog.Printf(\"In GPGSA\\n\")\n\n\n}\n<commit_msg>situation constructor (mutexes weren't getting init'd)<commit_after>package gps\n\nimport (\n\t\"strings\"\n\t\"fmt\"\n\t\"log\"\n\t\"strconv\"\n\t\"reflect\"\n)\n\n\/\/ func validateNMEAChecksum determines if a string is a properly formatted NMEA sentence with a valid checksum.\n\/\/\n\/\/ If the input string is valid, output is the input stripped of the \"$\" token and checksum, along with a boolean 'true'\n\/\/ If the input string is the incorrect format, the checksum is missing\/invalid, or checksum calculation fails, an error string and\n\/\/ boolean 'false' are returned\n\/\/\n\/\/ Checksum is calculated as XOR of all bytes between \"$\" and \"*\"\nfunc validateNMEAChecksum(s string) (string, bool) {\n\t\/\/validate format. NMEA sentences start with \"$\" and end in \"*xx\" where xx is the XOR value of all bytes between\n\tif !(strings.HasPrefix(s, \"$\") && strings.Contains(s, \"*\")) {\n\t\treturn \"Invalid NMEA message\", false\n\t}\n\n\t\/\/ strip leading \"$\" and split at \"*\"\n\ts_split := strings.Split(strings.TrimPrefix(s, \"$\"), \"*\")\n\ts_out := s_split[0]\n\ts_cs := s_split[1]\n\n\tif len(s_cs) < 2 {\n\t\treturn \"Missing checksum. Fewer than two bytes after asterisk\", false\n\t}\n\n\tcs, err := strconv.ParseUint(s_cs[:2], 16, 8)\n\tif err != nil {\n\t\treturn \"Invalid checksum\", false\n\t}\n\n\tcs_calc := byte(0)\n\tfor i := range s_out {\n\t\tcs_calc = cs_calc ^ byte(s_out[i])\n\t}\n\n\tif cs_calc != byte(cs) {\n\t\treturn fmt.Sprintf(\"Checksum failed. Calculated %#X; expected %#X\", cs_calc, cs), false\n\t}\n\n\treturn s_out, true\n}\n\nfunc createChecksummedNMEASentence(raw []byte) []byte {\n\tcs_calc := byte(0)\n\tfor _,v := range raw {\n\t\tcs_calc ^= v\n\t}\n\n\treturn []byte(fmt.Sprintf(\"$%s*%02X\\r\\n\", raw, cs_calc))\n}\n\nfunc processNMEASentence(line string, situation *SituationData) {\n\tsentence, valid := validateNMEAChecksum(line)\n\tif !valid {\n\t\tlog.Printf(\"GPS Error: invalid NMEA string: %s\\n\", sentence)\n\t\treturn \n\t}\n\n\t\/\/log.Printf(\"Begin parse of %s\\n\", sentence)\n\tParseMessage(sentence, situation)\n}\n\ntype NMEA struct {\n\tSentence string\n\tTokens []string\n\tSituation *SituationData\n}\n\n\/\/ we split the sentence on commas, and use the first field via reflection to find a method with the same name\nfunc ParseMessage(sentence string, situation *SituationData) *NMEA {\n\tn := &NMEA{ sentence, strings.Split(sentence, \",\"), situation }\n\n\t\/\/log.Printf(\"NMEA Message type %s, data: %v\\n\", n.Tokens[0], n.Tokens[1:])\n\n\tv := reflect.ValueOf(n)\n\tm := v.MethodByName(n.Tokens[0])\n\n\tif (m == reflect.Value{}) {\n\t\treturn nil\n\t}\n\n\tm.Call(nil)\n\n\treturn n\n}\n\nfunc durationSinceMidnight(fixtime string) (int, error) {\n\thr, err := strconv.Atoi(fixtime[0:2]); if err != nil { return 0, err }\n\tmin, err := strconv.Atoi(fixtime[2:4]); if err != nil { return 0, err }\n\tsec, err := strconv.Atoi(fixtime[4:6]); if err != nil { return 0, err }\n\n\treturn sec + min*60 + hr*60*60, nil\n}\n\nfunc parseLatLon(s string, neg bool) (float32, error) {\n\tminpos := len(s) - 5\n\tdeg, err := strconv.Atoi(s[0:minpos]); if err != nil { return 0.0, err }\n\tmin, err := strconv.ParseFloat(s[minpos:], 32); if err != nil { return 0.0, err }\n\n\tsign := 1; if neg { sign = -1 }\n\n\treturn float32(sign) * (float32(deg) + float32(min\/60.0)), nil \n}\n\nfunc (n *NMEA) GNGGA() { n.GPGGA() } \/\/ ublox 8 uses GNGGA in place of GPGGA to indicate multiple nav sources (GPS\/GLONASS)\nfunc (n *NMEA) GPGGA() {\n\tlog.Printf(\"In GPGGA\\n\")\n\ts := n.Situation\n\n\ts.Mu_GPS.Lock(); defer s.Mu_GPS.Unlock()\n\n\td, err := durationSinceMidnight(n.Tokens[1]); if err != nil { return }\n\ts.LastFixSinceMidnightUTC = uint32(d)\n\n\tif len(n.Tokens[2]) < 4 || len(n.Tokens[4]) < 4 { return } \/\/ sanity check lat\/lon\n\n\tlat, err := parseLatLon(n.Tokens[2], n.Tokens[3] == \"S\"); if err != nil { return }\n\tlon, err := parseLatLon(n.Tokens[4], n.Tokens[5] == \"W\"); if err != nil { return }\n\n\ts.Lat = lat; s.Lng = lon\n\n\tlog.Printf(\"Situation: %v\\n\", s)\n}\n\n\nfunc (n *NMEA) GPGSA() {\n\tlog.Printf(\"In GPGSA\\n\")\n\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package goevent_test\n\nimport (\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com\/pocke\/goevent\"\n)\n\nfunc TestEventNew(t *testing.T) {\n\tp := goevent.New()\n\tt.Log(\"Event: %+v\", p)\n}\n\nfunc TestOnTrigger(t *testing.T) {\n\tp := goevent.New()\n\n\ti := 1\n\terr := p.On(func(j int) {\n\t\ti += j\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = p.Trigger(2)\n\tif i != 3 {\n\t\tt.Errorf(\"Expected i == 3, Got i == %d\", i)\n\t}\n\tif err != nil {\n\t\tt.Error(\"should not return error When not reject. But got %s.\", err)\n\t}\n\n\terr = p.Trigger(\"2\")\n\tif err == nil {\n\t\tt.Error(\"should return error when invalid type. But got nil\")\n\t}\n}\n\nfunc TestManyTrigger(t *testing.T) {\n\tp := goevent.New()\n\ti := 0\n\tp.On(func(j int) {\n\t\ti += j\n\t})\n\n\tfor j := 0; j < 1000; j++ {\n\t\tp.Trigger(1)\n\t}\n\n\tif i != 1000 {\n\t\tt.Errorf(\"i should be 1000, but got %d\", i)\n\t}\n}\n\nfunc TestManyOn(t *testing.T) {\n\tp := goevent.New()\n\ti := 0\n\tm := sync.Mutex{}\n\tfor j := 0; j < 1000; j++ {\n\t\tp.On(func(j int) {\n\t\t\tm.Lock()\n\t\t\tdefer m.Unlock()\n\t\t\ti += j\n\t\t})\n\t}\n\tp.Trigger(1)\n\tif i != 1000 {\n\t\tt.Errorf(\"i should be 1000, but got %d\", i)\n\t}\n}\n\nfunc TestOnWhenNotFunction(t *testing.T) {\n\tp := goevent.New()\n\terr := p.On(\"foobar\")\n\tif err == nil {\n\t\tt.Error(\"should return error When recieve not function. But got nil.\")\n\t}\n}\n\nfunc TestOnWhenInvalidArgs(t *testing.T) {\n\tp := goevent.New()\n\tp.On(func(i int) {})\n\n\terr := p.On(func() {})\n\tif err == nil {\n\t\tt.Error(\"Should return error when different argument num. But got nil\")\n\t}\n\n\terr = p.On(func(s string) {})\n\tif err == nil {\n\t\tt.Error(\"Should return error when different args type. But got nil\")\n\t}\n}\n\nfunc TestOff(t *testing.T) {\n\tp := goevent.New()\n\ti := 0\n\tj := 0\n\tk := 0\n\n\tp.On(func() { j++ })\n\tf := func() { i++ }\n\tp.On(f)\n\tp.On(func() { k++ })\n\n\tp.Trigger()\n\tif i != 1 {\n\t\tt.Errorf(\"i expected 1, but got %d\", i)\n\t}\n\tif j != 1 {\n\t\tt.Errorf(\"j expected 1, but got %d\", j)\n\t}\n\tif k != 1 {\n\t\tt.Errorf(\"k expected 1, but got %d\", k)\n\t}\n\n\terr := p.Off(f)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tp.Trigger()\n\tif i != 1 {\n\t\tt.Errorf(\"i expected 1, but got %d\", i)\n\t}\n\tif j != 2 {\n\t\tt.Errorf(\"j expected 2, but got %d\", j)\n\t}\n\tif k != 2 {\n\t\tt.Errorf(\"k expected 2, but got %d\", k)\n\t}\n\n\terr = p.Off(f)\n\tif err == nil {\n\t\tt.Errorf(\"should return error when Listener doesn't exists. but got nil\")\n\t}\n}\n<commit_msg>add test<commit_after>package goevent_test\n\nimport (\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com\/pocke\/goevent\"\n)\n\nfunc TestEventNew(t *testing.T) {\n\tp := goevent.New()\n\tt.Log(\"Event: %+v\", p)\n}\n\nfunc TestOnTrigger(t *testing.T) {\n\tp := goevent.New()\n\n\ti := 1\n\terr := p.On(func(j int) {\n\t\ti += j\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = p.Trigger(2)\n\tif i != 3 {\n\t\tt.Errorf(\"Expected i == 3, Got i == %d\", i)\n\t}\n\tif err != nil {\n\t\tt.Error(\"should not return error When not reject. But got %s.\", err)\n\t}\n\n\terr = p.Trigger(\"2\")\n\tif err == nil {\n\t\tt.Error(\"should return error when invalid type. But got nil\")\n\t}\n}\n\nfunc TestManyTrigger(t *testing.T) {\n\tp := goevent.New()\n\ti := 0\n\tp.On(func(j int) {\n\t\ti += j\n\t})\n\n\tfor j := 0; j < 1000; j++ {\n\t\tp.Trigger(1)\n\t}\n\n\tif i != 1000 {\n\t\tt.Errorf(\"i should be 1000, but got %d\", i)\n\t}\n}\n\nfunc TestManyOn(t *testing.T) {\n\tp := goevent.New()\n\ti := 0\n\tm := sync.Mutex{}\n\tfor j := 0; j < 1000; j++ {\n\t\tp.On(func(j int) {\n\t\t\tm.Lock()\n\t\t\tdefer m.Unlock()\n\t\t\ti += j\n\t\t})\n\t}\n\tp.Trigger(1)\n\tif i != 1000 {\n\t\tt.Errorf(\"i should be 1000, but got %d\", i)\n\t}\n}\n\nfunc TestManyArgs(t *testing.T) {\n\te := goevent.New()\n\tvar res []int\n\te.On(func(i, j, k int) {\n\t\tres = append(res, i)\n\t\tres = append(res, j)\n\t\tres = append(res, k)\n\t})\n\te.Trigger(1, 2, 3)\n\tif !(res[0] == 1 && res[1] == 2 && res[2] == 3) {\n\t\tt.Errorf(\"res expected %v, but got %v\", []int{1, 2, 3}, res)\n\t}\n}\n\nfunc TestOnWhenNotFunction(t *testing.T) {\n\tp := goevent.New()\n\terr := p.On(\"foobar\")\n\tif err == nil {\n\t\tt.Error(\"should return error When recieve not function. But got nil.\")\n\t}\n}\n\nfunc TestOnWhenInvalidArgs(t *testing.T) {\n\tp := goevent.New()\n\tp.On(func(i int) {})\n\n\terr := p.On(func() {})\n\tif err == nil {\n\t\tt.Error(\"Should return error when different argument num. But got nil\")\n\t}\n\n\terr = p.On(func(s string) {})\n\tif err == nil {\n\t\tt.Error(\"Should return error when different args type. But got nil\")\n\t}\n}\n\nfunc TestOff(t *testing.T) {\n\tp := goevent.New()\n\ti := 0\n\tj := 0\n\tk := 0\n\n\tp.On(func() { j++ })\n\tf := func() { i++ }\n\tp.On(f)\n\tp.On(func() { k++ })\n\n\tp.Trigger()\n\tif i != 1 {\n\t\tt.Errorf(\"i expected 1, but got %d\", i)\n\t}\n\tif j != 1 {\n\t\tt.Errorf(\"j expected 1, but got %d\", j)\n\t}\n\tif k != 1 {\n\t\tt.Errorf(\"k expected 1, but got %d\", k)\n\t}\n\n\terr := p.Off(f)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tp.Trigger()\n\tif i != 1 {\n\t\tt.Errorf(\"i expected 1, but got %d\", i)\n\t}\n\tif j != 2 {\n\t\tt.Errorf(\"j expected 2, but got %d\", j)\n\t}\n\tif k != 2 {\n\t\tt.Errorf(\"k expected 2, but got %d\", k)\n\t}\n\n\terr = p.Off(f)\n\tif err == nil {\n\t\tt.Errorf(\"should return error when Listener doesn't exists. but got nil\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gostats\n\nimport(\n  \"testing\"\n  \"os\"\n  \"time\"\n  \"github.com\/stretchr\/testify\/assert\"\n)\n\ntype metricNameTest struct{\n  Source    string\n  Expected  string\n}\nfunc TestSanitizeMetricName(t *testing.T){\n  cases := []metricNameTest{\n    metricNameTest{\"mymetricname\", \"mymetricname\"},\n    metricNameTest{\"my metric name\", \"my_metric_name\"},\n    metricNameTest{\"my\/metric\/name\", \"my_metric_name\"},\n    metricNameTest{\"my.metric name\", \"my_metric_name\"},\n    metricNameTest{\"my-metric\/name\", \"my-metric_name\"},\n    metricNameTest{\"my-metric@name\", \"my-metricname\"},\n  }\n\n  for _,c := range cases{\n    n := sanitizeMetricName(c.Source)\n    if n != c.Expected{\n      assert.Equal(t, c.Expected, n, \"metric name should be sanitized correctly\")\n    }\n  }\n}\n\nfunc TestNew(t *testing.T){\n  s := New()\n  h, _ := os.Hostname()\n  assert.Equal(t, sanitizeMetricName(h), s.Hostname, \"hostname should be set\")\n  assert.Equal(t, \"gostats\", s.ClientName, \"default client name should be set\")\n\n  s.Hostname = \"localhost\"\n  assert.Equal(t, \"gostats.localhost\", s.MetricBase(), \"metric base should be correct\")\n}\n\nfunc TestStart(t *testing.T){\n  s, err := Start(\"localhost:8015\", 5, \"testclient\")\n  defer s.Stop()\n\n  assert.Nil(t, err)\n\n  s.Hostname = \"localhost\"\n  assert.Equal(t, \"testclient.localhost\", s.MetricBase(), \"metric base should be correct\")\n  assert.Equal(t, time.Duration(5*time.Second), s.PushInterval, \"push interval should be correct\")\n  assert.Equal(t, \"localhost:8015\", s.StatsdHost, \"statsd host should be correct\")\n}\n<commit_msg>Fix tests<commit_after>package gostats\n\nimport(\n  \"testing\"\n  \"os\"\n  \"time\"\n  \"github.com\/stretchr\/testify\/assert\"\n)\n\ntype metricNameTest struct{\n  Source    string\n  Expected  string\n}\nfunc TestSanitizeMetricName(t *testing.T){\n  cases := []metricNameTest{\n    metricNameTest{\"mymetricname\", \"mymetricname\"},\n    metricNameTest{\"my metric name\", \"my_metric_name\"},\n    metricNameTest{\"my\/metric\/name\", \"my_metric_name\"},\n    metricNameTest{\"my.metric name\", \"my_metric_name\"},\n    metricNameTest{\"my-metric\/name\", \"my-metric_name\"},\n    metricNameTest{\"my-metric@name\", \"my-metricname\"},\n  }\n\n  for _,c := range cases{\n    n := sanitizeMetricName(c.Source)\n    if n != c.Expected{\n      assert.Equal(t, c.Expected, n, \"metric name should be sanitized correctly\")\n    }\n  }\n}\n\nfunc TestNew(t *testing.T){\n  s := New()\n  h, _ := os.Hostname()\n  assert.Equal(t, sanitizeMetricName(h), s.Hostname, \"hostname should be set\")\n  assert.Equal(t, \"gostats\", s.ClientName, \"default client name should be set\")\n\n  s.Hostname = \"localhost\"\n  assert.Equal(t, \"gostats.gostats.localhost.\", s.MetricBase(), \"metric base should be correct\")\n}\n\nfunc TestStart(t *testing.T){\n  s, err := Start(\"localhost:8015\", 5, \"testclient\")\n  defer s.Stop()\n\n  assert.Nil(t, err)\n\n  s.Hostname = \"localhost\"\n  assert.Equal(t, \"gostats.testclient.localhost.\", s.MetricBase(), \"metric base should be correct\")\n  assert.Equal(t, time.Duration(5*time.Second), s.PushInterval, \"push interval should be correct\")\n  assert.Equal(t, \"localhost:8015\", s.StatsdHost, \"statsd host should be correct\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package graph\n\nimport (\n\t\"database\/sql\/driver\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"sourcegraph.com\/sourcegraph\/srcgraph\/repo\"\n)\n\ntype (\n\tSID        int64\n\tSymbolPath string\n\tSymbolKind string\n)\n\n\/\/ SymbolKey specifies a symbol, either concretely or abstractly. A concrete\n\/\/ symbol key has a non-empty CommitID and refers to a symbol defined in a\n\/\/ specific commit. An abstract symbol key has an empty CommitID and is\n\/\/ considered to refer to symbols from any number of commits (so long as the\n\/\/ Repo, UnitType, Unit, and Path match).\n\/\/\n\/\/ You can think of CommitID as the time dimension. With an empty CommitID, you\n\/\/ are referring to a symbol that may or may not exist at various times. With a\n\/\/ non-empty CommitID, you are referring to a specific definition of a symbol at\n\/\/ the time specified by the CommitID.\ntype SymbolKey struct {\n\t\/\/ Repo is the VCS repository that defines this symbol. Its Elasticsearch mapping is defined\n\t\/\/ separately.\n\tRepo repo.URI `json:\",omitempty\"`\n\n\t\/\/ CommitID is the ID of the VCS commit that this symbol was defined in. The\n\t\/\/ CommitID is always a full commit ID (40 hexadecimal characters for git\n\t\/\/ and hg), never a branch or tag name.\n\tCommitID string `db:\"commit_id\" json:\",omitempty\"`\n\n\t\/\/ UnitType is the type name of the source unit (obtained from unit.Type(u))\n\t\/\/ that this symbol was defined in.\n\tUnitType string `db:\"unit_type\" json:\",omitempty\"`\n\n\t\/\/ Unit is the name of the source unit (obtained from u.Name()) that this\n\t\/\/ symbol was defined in.\n\tUnit string `json:\",omitempty\"`\n\n\t\/\/ Path is the path to this symbol, relative to the repo. Its Elasticsearch mapping is defined\n\t\/\/ separately (because it is a multi_field, which the struct tag can't currently represent).\n\tPath SymbolPath\n}\n\nfunc (s SymbolKey) String() string {\n\tb, err := json.Marshal(s)\n\tif err != nil {\n\t\tpanic(\"SymbolKey.String: \" + err.Error())\n\t}\n\treturn string(b)\n}\n\ntype Symbol struct {\n\t\/\/ SID is a unique, sequential ID for a symbol. It is regenerated each time\n\t\/\/ the symbol is emitted by the grapher and saved to the database. The SID\n\t\/\/ is used as an optimization (e.g., joins are faster on SID than on\n\t\/\/ SymbolKey).\n\tSID SID `db:\"sid\" json:\",omitempty\" elastic:\"type:integer,index:no\"`\n\n\t\/\/ SymbolKey is the natural unique key for a symbol. It is stable\n\t\/\/ (subsequent runs of a grapher will emit the same symbols with the same\n\t\/\/ SymbolKeys).\n\tSymbolKey\n\n\t\/\/ SpecificPath is the language-specific \"path\" to this symbol, using\n\t\/\/ language-specific separators (e.g., \"::\" and \".\" instead of \"\/\", which is\n\t\/\/ used in the SymbolKey.Path value).\n\tSpecificPath string `db:\"specific_path\"`\n\n\t\/\/ Kind is the language-independent kind of this symbol.\n\tKind SymbolKind `elastic:\"type:string,index:analyzed\"`\n\n\t\/\/ SpecificKind is the language-specific kind of this symbol (which is in\n\t\/\/ some cases equal to the Kind).\n\tSpecificKind string `db:\"specific_kind\"`\n\n\tName string\n\n\t\/\/ Callable is true if this symbol may be called or invoked, such as in the\n\t\/\/ case of functions or methods.\n\tCallable bool `db:\"callable\"`\n\n\tFile string `elastic:\"type:string,index:no\"`\n\n\tDefStart int `db:\"def_start\" elastic:\"type:integer,index:no\"`\n\tDefEnd   int `db:\"def_end\" elastic:\"type:integer,index:no\"`\n\n\tExported bool `elastic:\"type:boolean,index:not_analyzed\"`\n\n\t\/\/ Test is whether this symbol is defined in test code (as opposed to main\n\t\/\/ code). For example, definitions in Go *_test.go files have Test = true.\n\tTest bool `elastic:\"type:boolean,index:not_analyzed\"`\n\n\tTypeExpr string `db:\"type_expr\" json:\",omitempty\"`\n}\n\nfunc (s *Symbol) Language() string {\n\tswitch s.UnitType {\n\tcase \"GoPackage\":\n\t\treturn \"Go\"\n\t\t\/\/ TODO(sqs): add Python, JS, etc.\n\t}\n\treturn \"unknown language\"\n}\n\n\/\/ TODO!(sqs): factor this into the individual source unit packages\nfunc (s *Symbol) Signature() string {\n\tvar removeOwnImportPath = func(str string) string {\n\t\tif s.UnitType == \"GoPackage\" {\n\t\t\treturn strings.Replace(strings.Replace(str, string(s.Repo)+\".\", \"\", -1), string(s.Repo)+\"\/\", \"\", -1)\n\t\t}\n\t\treturn str\n\t}\n\n\tif s.TypeExpr == \"\" {\n\t\treturn \"\"\n\t}\n\tif !s.Callable {\n\t\tif (s.Kind == Field || s.Kind == Var || s.Kind == Type) && len(s.TypeExpr) < 50 {\n\t\t\treturn \" \" + removeOwnImportPath(s.TypeExpr)\n\t\t}\n\t\treturn \"\"\n\t}\n\n\tswitch s.UnitType {\n\tcase \"GoPackage\":\n\t\treturn removeOwnImportPath(strings.TrimPrefix(s.TypeExpr, \"func\"))\n\tcase \"js\":\n\t\treturn strings.TrimPrefix(s.TypeExpr, \"fn\")\n\tcase \"python\":\n\t\t\/\/ remove up to first paren\n\t\ti := strings.Index(s.TypeExpr, \"(\")\n\t\tif i == -1 {\n\t\t\treturn s.TypeExpr\n\t\t}\n\t\treturn s.TypeExpr[:i]\n\tcase \"ruby\":\n\t\treturn s.TypeExpr\n\t}\n\treturn s.TypeExpr\n}\n\nfunc (s *Symbol) sortKey() string { return s.SymbolKey.String() }\n\n\/\/ Propagate describes type\/value propagation in code. A Propagate entry from A\n\/\/ (src) to B (dst) indicates that the type\/value of A propagates to B. In Tern,\n\/\/ this is indicated by A having a \"fwd\" property whose value is an array that\n\/\/ includes B.\n\/\/\n\/\/\n\/\/ ## Motivation & example\n\/\/\n\/\/ For example, consider the following JavaScript code:\n\/\/\n\/\/   var a = Foo;\n\/\/   var b = a;\n\/\/\n\/\/ Foo, a, and b are each their own symbol. We could resolve all of them to the\n\/\/ symbol of their original type (perhaps Foo), but there are occasions when you\n\/\/ do want to see only the definition of a or b and examples thereof. Therefore,\n\/\/ we need to represent them as distinct symbols.\n\/\/\n\/\/ Even though Foo, a, and b are distinct symbols, there are propagation\n\/\/ relationships between them that are important to represent. The type of Foo\n\/\/ propagates to both a and b, and the type of a propagates to b. In this case,\n\/\/ we would have 3 Propagates: Propagate{Src: \"Foo\", Dst: \"a\"}, Propagate{Src:\n\/\/ \"Foo\", Dst: \"b\"}, and Propagate{Src: \"a\", Dst: \"b\"}. (The propagation\n\/\/ relationships could be described by just the first and last Propagates, but\n\/\/ we explicitly include all paths as a denormalization optimization to avoid\n\/\/ requiring an unbounded number of DB queries to determine which symbols a type\n\/\/ propagates to or from.)\n\/\/\n\/\/\n\/\/ ## Directionality\n\/\/\n\/\/ Propagation is unidirectional, in the general case. In the example above, if\n\/\/ Foo referred to a JavaScript object and if the code were evaluated, any\n\/\/ *runtime* type changes (e.g., setting a property) on Foo, a, and b would be\n\/\/ reflected on all of the others. But this doesn't hold for static analysis;\n\/\/ it's not always true that if a property \"a.x\" or \"b.x\" exists, then \"Foo.x\"\n\/\/ exists. The simplest example is when Foo is an external definition. Perhaps\n\/\/ this example file (which uses Foo as a library) modifies Foo to add a new\n\/\/ property, but other libraries that use Foo would never see that property\n\/\/ because they wouldn't be executed in the same context as this example file.\n\/\/ So, in general, we cannot say that Foo receives all types applied to symbols\n\/\/ that Foo propagates to.\n\/\/\n\/\/\n\/\/ ## Hypothetical Python example\n\/\/\n\/\/ Consider the following 2 Python files:\n\/\/\n\/\/   \"\"\"file1.py\"\"\"\n\/\/   class Foo(object): end\n\/\/\n\/\/   \"\"\"file2.py\"\"\"\n\/\/   from .file1 import Foo\n\/\/   Foo2 = Foo\n\/\/\n\/\/ In this example, there would be one Propagate: Propagate{Src: \"file1\/Foo\",\n\/\/ Dst: \"file2\/Foo2}.\ntype Propagate struct {\n\t\/\/ Src is the symbol whose type\/value is being propagated to the dst symbol.\n\tSrcRepo     repo.URI\n\tSrcPath     SymbolPath\n\tSrcUnit     string\n\tSrcUnitType string\n\n\t\/\/ Dst is the symbol that is receiving a propagated type\/value from the src symbol.\n\tDstRepo     repo.URI\n\tDstPath     SymbolPath\n\tDstUnit     string\n\tDstUnitType string\n}\n\nconst (\n\tConst   SymbolKind = \"const\"\n\tField              = \"field\"\n\tFunc               = \"func\"\n\tModule             = \"module\"\n\tPackage            = \"package\"\n\tType               = \"type\"\n\tVar                = \"var\"\n)\n\nvar AllSymbolKinds = []SymbolKind{Const, Field, Func, Module, Package, Type, Var}\n\n\/\/ Returns true iff k is a known symbol kind.\nfunc (k SymbolKind) Valid() bool {\n\tfor _, kk := range AllSymbolKinds {\n\t\tif k == kk {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc KindName(k string) string {\n\tif strings.HasSuffix(k, \"_module\") {\n\t\treturn \"module\"\n\t}\n\treturn strings.Replace(k, \"_\", \" \", -1)\n}\n\ntype ConstData struct {\n\tConstValue string\n}\n\n\/\/ SQL\n\nfunc (x SID) Value() (driver.Value, error) {\n\treturn int64(x), nil\n}\n\nfunc (x *SID) Scan(v interface{}) error {\n\tif data, ok := v.(int64); ok {\n\t\t*x = SID(data)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%T.Scan failed: %v\", x, v)\n}\n\nfunc (x SymbolPath) Value() (driver.Value, error) {\n\treturn string(x), nil\n}\n\nfunc (x *SymbolPath) Scan(v interface{}) error {\n\tif data, ok := v.([]byte); ok {\n\t\t*x = SymbolPath(data)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%T.Scan failed: %v\", x, v)\n}\n\nfunc (x SymbolKind) Value() (driver.Value, error) {\n\treturn string(x), nil\n}\n\nfunc (x *SymbolKind) Scan(v interface{}) error {\n\tif data, ok := v.([]byte); ok {\n\t\t*x = SymbolKind(data)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%T.Scan failed: %v\", x, v)\n}\n\nfunc (x *ConstData) Value() (driver.Value, error) {\n\tif x == nil {\n\t\treturn nil, nil\n\t}\n\treturn json.Marshal(x)\n}\n\nfunc (x *ConstData) Scan(v interface{}) error {\n\tif data, ok := v.([]byte); ok {\n\t\treturn json.Unmarshal(data, x)\n\t}\n\treturn fmt.Errorf(\"%T.Scan failed: %v\", x, v)\n}\n\n\/\/ Debugging\n\nfunc (x Symbol) String() string {\n\ts, _ := json.Marshal(x)\n\treturn string(s)\n}\n\n\/\/ Sorting\n\ntype Symbols []*Symbol\n\nfunc (vs Symbols) Len() int           { return len(vs) }\nfunc (vs Symbols) Swap(i, j int)      { vs[i], vs[j] = vs[j], vs[i] }\nfunc (vs Symbols) Less(i, j int) bool { return vs[i].sortKey() < vs[j].sortKey() }\n\nfunc (syms Symbols) Keys() (keys []SymbolKey) {\n\tkeys = make([]SymbolKey, len(syms))\n\tfor i, sym := range syms {\n\t\tkeys[i] = sym.SymbolKey\n\t}\n\treturn\n}\n\nfunc (syms Symbols) SIDs() (ids []SID) {\n\tids = make([]SID, len(syms))\n\tfor i, sym := range syms {\n\t\tids[i] = sym.SID\n\t}\n\treturn\n}\n\nfunc ParseSIDs(sidstrs []string) (sids []SID) {\n\tsids = make([]SID, len(sidstrs))\n\tfor i, sidstr := range sidstrs {\n\t\tsid, err := strconv.Atoi(sidstr)\n\t\tif err == nil {\n\t\t\tsids[i] = SID(sid)\n\t\t}\n\t}\n\treturn\n}\n<commit_msg>Test field omitempty (json tag)<commit_after>package graph\n\nimport (\n\t\"database\/sql\/driver\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"sourcegraph.com\/sourcegraph\/srcgraph\/repo\"\n)\n\ntype (\n\tSID        int64\n\tSymbolPath string\n\tSymbolKind string\n)\n\n\/\/ SymbolKey specifies a symbol, either concretely or abstractly. A concrete\n\/\/ symbol key has a non-empty CommitID and refers to a symbol defined in a\n\/\/ specific commit. An abstract symbol key has an empty CommitID and is\n\/\/ considered to refer to symbols from any number of commits (so long as the\n\/\/ Repo, UnitType, Unit, and Path match).\n\/\/\n\/\/ You can think of CommitID as the time dimension. With an empty CommitID, you\n\/\/ are referring to a symbol that may or may not exist at various times. With a\n\/\/ non-empty CommitID, you are referring to a specific definition of a symbol at\n\/\/ the time specified by the CommitID.\ntype SymbolKey struct {\n\t\/\/ Repo is the VCS repository that defines this symbol. Its Elasticsearch mapping is defined\n\t\/\/ separately.\n\tRepo repo.URI `json:\",omitempty\"`\n\n\t\/\/ CommitID is the ID of the VCS commit that this symbol was defined in. The\n\t\/\/ CommitID is always a full commit ID (40 hexadecimal characters for git\n\t\/\/ and hg), never a branch or tag name.\n\tCommitID string `db:\"commit_id\" json:\",omitempty\"`\n\n\t\/\/ UnitType is the type name of the source unit (obtained from unit.Type(u))\n\t\/\/ that this symbol was defined in.\n\tUnitType string `db:\"unit_type\" json:\",omitempty\"`\n\n\t\/\/ Unit is the name of the source unit (obtained from u.Name()) that this\n\t\/\/ symbol was defined in.\n\tUnit string `json:\",omitempty\"`\n\n\t\/\/ Path is the path to this symbol, relative to the repo. Its Elasticsearch mapping is defined\n\t\/\/ separately (because it is a multi_field, which the struct tag can't currently represent).\n\tPath SymbolPath\n}\n\nfunc (s SymbolKey) String() string {\n\tb, err := json.Marshal(s)\n\tif err != nil {\n\t\tpanic(\"SymbolKey.String: \" + err.Error())\n\t}\n\treturn string(b)\n}\n\ntype Symbol struct {\n\t\/\/ SID is a unique, sequential ID for a symbol. It is regenerated each time\n\t\/\/ the symbol is emitted by the grapher and saved to the database. The SID\n\t\/\/ is used as an optimization (e.g., joins are faster on SID than on\n\t\/\/ SymbolKey).\n\tSID SID `db:\"sid\" json:\",omitempty\" elastic:\"type:integer,index:no\"`\n\n\t\/\/ SymbolKey is the natural unique key for a symbol. It is stable\n\t\/\/ (subsequent runs of a grapher will emit the same symbols with the same\n\t\/\/ SymbolKeys).\n\tSymbolKey\n\n\t\/\/ SpecificPath is the language-specific \"path\" to this symbol, using\n\t\/\/ language-specific separators (e.g., \"::\" and \".\" instead of \"\/\", which is\n\t\/\/ used in the SymbolKey.Path value).\n\tSpecificPath string `db:\"specific_path\"`\n\n\t\/\/ Kind is the language-independent kind of this symbol.\n\tKind SymbolKind `elastic:\"type:string,index:analyzed\"`\n\n\t\/\/ SpecificKind is the language-specific kind of this symbol (which is in\n\t\/\/ some cases equal to the Kind).\n\tSpecificKind string `db:\"specific_kind\"`\n\n\tName string\n\n\t\/\/ Callable is true if this symbol may be called or invoked, such as in the\n\t\/\/ case of functions or methods.\n\tCallable bool `db:\"callable\"`\n\n\tFile string `elastic:\"type:string,index:no\"`\n\n\tDefStart int `db:\"def_start\" elastic:\"type:integer,index:no\"`\n\tDefEnd   int `db:\"def_end\" elastic:\"type:integer,index:no\"`\n\n\tExported bool `elastic:\"type:boolean,index:not_analyzed\"`\n\n\t\/\/ Test is whether this symbol is defined in test code (as opposed to main\n\t\/\/ code). For example, definitions in Go *_test.go files have Test = true.\n\tTest bool `elastic:\"type:boolean,index:not_analyzed\" json:\",omitempty\"`\n\n\tTypeExpr string `db:\"type_expr\" json:\",omitempty\"`\n}\n\nfunc (s *Symbol) Language() string {\n\tswitch s.UnitType {\n\tcase \"GoPackage\":\n\t\treturn \"Go\"\n\t\t\/\/ TODO(sqs): add Python, JS, etc.\n\t}\n\treturn \"unknown language\"\n}\n\n\/\/ TODO!(sqs): factor this into the individual source unit packages\nfunc (s *Symbol) Signature() string {\n\tvar removeOwnImportPath = func(str string) string {\n\t\tif s.UnitType == \"GoPackage\" {\n\t\t\treturn strings.Replace(strings.Replace(str, string(s.Repo)+\".\", \"\", -1), string(s.Repo)+\"\/\", \"\", -1)\n\t\t}\n\t\treturn str\n\t}\n\n\tif s.TypeExpr == \"\" {\n\t\treturn \"\"\n\t}\n\tif !s.Callable {\n\t\tif (s.Kind == Field || s.Kind == Var || s.Kind == Type) && len(s.TypeExpr) < 50 {\n\t\t\treturn \" \" + removeOwnImportPath(s.TypeExpr)\n\t\t}\n\t\treturn \"\"\n\t}\n\n\tswitch s.UnitType {\n\tcase \"GoPackage\":\n\t\treturn removeOwnImportPath(strings.TrimPrefix(s.TypeExpr, \"func\"))\n\tcase \"js\":\n\t\treturn strings.TrimPrefix(s.TypeExpr, \"fn\")\n\tcase \"python\":\n\t\t\/\/ remove up to first paren\n\t\ti := strings.Index(s.TypeExpr, \"(\")\n\t\tif i == -1 {\n\t\t\treturn s.TypeExpr\n\t\t}\n\t\treturn s.TypeExpr[:i]\n\tcase \"ruby\":\n\t\treturn s.TypeExpr\n\t}\n\treturn s.TypeExpr\n}\n\nfunc (s *Symbol) sortKey() string { return s.SymbolKey.String() }\n\n\/\/ Propagate describes type\/value propagation in code. A Propagate entry from A\n\/\/ (src) to B (dst) indicates that the type\/value of A propagates to B. In Tern,\n\/\/ this is indicated by A having a \"fwd\" property whose value is an array that\n\/\/ includes B.\n\/\/\n\/\/\n\/\/ ## Motivation & example\n\/\/\n\/\/ For example, consider the following JavaScript code:\n\/\/\n\/\/   var a = Foo;\n\/\/   var b = a;\n\/\/\n\/\/ Foo, a, and b are each their own symbol. We could resolve all of them to the\n\/\/ symbol of their original type (perhaps Foo), but there are occasions when you\n\/\/ do want to see only the definition of a or b and examples thereof. Therefore,\n\/\/ we need to represent them as distinct symbols.\n\/\/\n\/\/ Even though Foo, a, and b are distinct symbols, there are propagation\n\/\/ relationships between them that are important to represent. The type of Foo\n\/\/ propagates to both a and b, and the type of a propagates to b. In this case,\n\/\/ we would have 3 Propagates: Propagate{Src: \"Foo\", Dst: \"a\"}, Propagate{Src:\n\/\/ \"Foo\", Dst: \"b\"}, and Propagate{Src: \"a\", Dst: \"b\"}. (The propagation\n\/\/ relationships could be described by just the first and last Propagates, but\n\/\/ we explicitly include all paths as a denormalization optimization to avoid\n\/\/ requiring an unbounded number of DB queries to determine which symbols a type\n\/\/ propagates to or from.)\n\/\/\n\/\/\n\/\/ ## Directionality\n\/\/\n\/\/ Propagation is unidirectional, in the general case. In the example above, if\n\/\/ Foo referred to a JavaScript object and if the code were evaluated, any\n\/\/ *runtime* type changes (e.g., setting a property) on Foo, a, and b would be\n\/\/ reflected on all of the others. But this doesn't hold for static analysis;\n\/\/ it's not always true that if a property \"a.x\" or \"b.x\" exists, then \"Foo.x\"\n\/\/ exists. The simplest example is when Foo is an external definition. Perhaps\n\/\/ this example file (which uses Foo as a library) modifies Foo to add a new\n\/\/ property, but other libraries that use Foo would never see that property\n\/\/ because they wouldn't be executed in the same context as this example file.\n\/\/ So, in general, we cannot say that Foo receives all types applied to symbols\n\/\/ that Foo propagates to.\n\/\/\n\/\/\n\/\/ ## Hypothetical Python example\n\/\/\n\/\/ Consider the following 2 Python files:\n\/\/\n\/\/   \"\"\"file1.py\"\"\"\n\/\/   class Foo(object): end\n\/\/\n\/\/   \"\"\"file2.py\"\"\"\n\/\/   from .file1 import Foo\n\/\/   Foo2 = Foo\n\/\/\n\/\/ In this example, there would be one Propagate: Propagate{Src: \"file1\/Foo\",\n\/\/ Dst: \"file2\/Foo2}.\ntype Propagate struct {\n\t\/\/ Src is the symbol whose type\/value is being propagated to the dst symbol.\n\tSrcRepo     repo.URI\n\tSrcPath     SymbolPath\n\tSrcUnit     string\n\tSrcUnitType string\n\n\t\/\/ Dst is the symbol that is receiving a propagated type\/value from the src symbol.\n\tDstRepo     repo.URI\n\tDstPath     SymbolPath\n\tDstUnit     string\n\tDstUnitType string\n}\n\nconst (\n\tConst   SymbolKind = \"const\"\n\tField              = \"field\"\n\tFunc               = \"func\"\n\tModule             = \"module\"\n\tPackage            = \"package\"\n\tType               = \"type\"\n\tVar                = \"var\"\n)\n\nvar AllSymbolKinds = []SymbolKind{Const, Field, Func, Module, Package, Type, Var}\n\n\/\/ Returns true iff k is a known symbol kind.\nfunc (k SymbolKind) Valid() bool {\n\tfor _, kk := range AllSymbolKinds {\n\t\tif k == kk {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc KindName(k string) string {\n\tif strings.HasSuffix(k, \"_module\") {\n\t\treturn \"module\"\n\t}\n\treturn strings.Replace(k, \"_\", \" \", -1)\n}\n\ntype ConstData struct {\n\tConstValue string\n}\n\n\/\/ SQL\n\nfunc (x SID) Value() (driver.Value, error) {\n\treturn int64(x), nil\n}\n\nfunc (x *SID) Scan(v interface{}) error {\n\tif data, ok := v.(int64); ok {\n\t\t*x = SID(data)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%T.Scan failed: %v\", x, v)\n}\n\nfunc (x SymbolPath) Value() (driver.Value, error) {\n\treturn string(x), nil\n}\n\nfunc (x *SymbolPath) Scan(v interface{}) error {\n\tif data, ok := v.([]byte); ok {\n\t\t*x = SymbolPath(data)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%T.Scan failed: %v\", x, v)\n}\n\nfunc (x SymbolKind) Value() (driver.Value, error) {\n\treturn string(x), nil\n}\n\nfunc (x *SymbolKind) Scan(v interface{}) error {\n\tif data, ok := v.([]byte); ok {\n\t\t*x = SymbolKind(data)\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%T.Scan failed: %v\", x, v)\n}\n\nfunc (x *ConstData) Value() (driver.Value, error) {\n\tif x == nil {\n\t\treturn nil, nil\n\t}\n\treturn json.Marshal(x)\n}\n\nfunc (x *ConstData) Scan(v interface{}) error {\n\tif data, ok := v.([]byte); ok {\n\t\treturn json.Unmarshal(data, x)\n\t}\n\treturn fmt.Errorf(\"%T.Scan failed: %v\", x, v)\n}\n\n\/\/ Debugging\n\nfunc (x Symbol) String() string {\n\ts, _ := json.Marshal(x)\n\treturn string(s)\n}\n\n\/\/ Sorting\n\ntype Symbols []*Symbol\n\nfunc (vs Symbols) Len() int           { return len(vs) }\nfunc (vs Symbols) Swap(i, j int)      { vs[i], vs[j] = vs[j], vs[i] }\nfunc (vs Symbols) Less(i, j int) bool { return vs[i].sortKey() < vs[j].sortKey() }\n\nfunc (syms Symbols) Keys() (keys []SymbolKey) {\n\tkeys = make([]SymbolKey, len(syms))\n\tfor i, sym := range syms {\n\t\tkeys[i] = sym.SymbolKey\n\t}\n\treturn\n}\n\nfunc (syms Symbols) SIDs() (ids []SID) {\n\tids = make([]SID, len(syms))\n\tfor i, sym := range syms {\n\t\tids[i] = sym.SID\n\t}\n\treturn\n}\n\nfunc ParseSIDs(sidstrs []string) (sids []SID) {\n\tsids = make([]SID, len(sidstrs))\n\tfor i, sidstr := range sidstrs {\n\t\tsid, err := strconv.Atoi(sidstr)\n\t\tif err == nil {\n\t\t\tsids[i] = SID(sid)\n\t\t}\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package graph\n\nimport (\n\t\"encoding\/hex\"\n\t\"fmt\"\n\n\t\"github.com\/cayleygraph\/quad\"\n)\n\n\/\/ Ref defines an opaque \"quad store reference\" type. However the backend wishes\n\/\/ to implement it, a Ref is merely a token to a quad or a node that the\n\/\/ backing store itself understands, and the base iterators pass around.\n\/\/\n\/\/ For example, in a very traditional, graphd-style graph, these are int64s\n\/\/ (guids of the primitives). In a very direct sort of graph, these could be\n\/\/ pointers to structs, or merely quads, or whatever works best for the\n\/\/ backing store.\n\/\/\n\/\/ These must be comparable, or return a comparable version on Key.\ntype Ref interface {\n\t\/\/ Key returns a dynamic type that is comparable according to the Go language specification.\n\t\/\/ The returned value must be unique for each receiver value.\n\tKey() interface{}\n}\n\nfunc HashOf(s quad.Value) (out ValueHash) {\n\tif s == nil {\n\t\treturn\n\t}\n\tquad.HashTo(s, out[:])\n\treturn\n}\n\nvar _ Ref = ValueHash{}\n\n\/\/ ValueHash is a hash of a single value.\ntype ValueHash [quad.HashSize]byte\n\nfunc (h ValueHash) Valid() bool {\n\treturn h != ValueHash{}\n}\nfunc (h ValueHash) Key() interface{} { return h }\nfunc (h ValueHash) String() string {\n\tif !h.Valid() {\n\t\treturn \"\"\n\t}\n\treturn hex.EncodeToString(h[:])\n}\n\n\/\/ PreFetchedValue is an optional interface for graph.Ref to indicate that\n\/\/ quadstore has already loaded a value into memory.\ntype PreFetchedValue interface {\n\tRef\n\tNameOf() quad.Value\n}\n\nfunc PreFetched(v quad.Value) PreFetchedValue {\n\treturn fetchedValue{v}\n}\n\ntype fetchedValue struct {\n\tVal quad.Value\n}\n\nfunc (v fetchedValue) IsNode() bool       { return true }\nfunc (v fetchedValue) NameOf() quad.Value { return v.Val }\nfunc (v fetchedValue) Key() interface{}   { return v.Val }\n\n\/\/ Keyer provides a method for comparing types that are not otherwise comparable.\n\/\/ The Key method must return a dynamic type that is comparable according to the\n\/\/ Go language specification. The returned value must be unique for each receiver\n\/\/ value.\n\/\/\n\/\/ Deprecated: Ref contains the same method now.\ntype Keyer = Ref\n\n\/\/ ToKey prepares Ref to be stored inside maps, calling Key() if necessary.\nfunc ToKey(v Ref) interface{} {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.Key()\n}\n\nvar _ Ref = QuadHash{}\n\ntype QuadHash struct {\n\tSubject   ValueHash\n\tPredicate ValueHash\n\tObject    ValueHash\n\tLabel     ValueHash\n}\n\nfunc (q QuadHash) Dirs() [4]ValueHash {\n\treturn [4]ValueHash{\n\t\tq.Subject,\n\t\tq.Predicate,\n\t\tq.Object,\n\t\tq.Label,\n\t}\n}\nfunc (q QuadHash) Key() interface{} { return q }\nfunc (q QuadHash) Get(d quad.Direction) ValueHash {\n\tswitch d {\n\tcase quad.Subject:\n\t\treturn q.Subject\n\tcase quad.Predicate:\n\t\treturn q.Predicate\n\tcase quad.Object:\n\t\treturn q.Object\n\tcase quad.Label:\n\t\treturn q.Label\n\t}\n\tpanic(fmt.Errorf(\"unknown direction: %v\", d))\n}\nfunc (q *QuadHash) Set(d quad.Direction, h ValueHash) {\n\tswitch d {\n\tcase quad.Subject:\n\t\tq.Subject = h\n\tcase quad.Predicate:\n\t\tq.Predicate = h\n\tcase quad.Object:\n\t\tq.Object = h\n\tcase quad.Label:\n\t\tq.Label = h\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown direction: %v\", d))\n\t}\n}\n<commit_msg>graph: remove deprecated Keyer type<commit_after>package graph\n\nimport (\n\t\"encoding\/hex\"\n\t\"fmt\"\n\n\t\"github.com\/cayleygraph\/quad\"\n)\n\n\/\/ Ref defines an opaque \"quad store reference\" type. However the backend wishes\n\/\/ to implement it, a Ref is merely a token to a quad or a node that the\n\/\/ backing store itself understands, and the base iterators pass around.\n\/\/\n\/\/ For example, in a very traditional, graphd-style graph, these are int64s\n\/\/ (guids of the primitives). In a very direct sort of graph, these could be\n\/\/ pointers to structs, or merely quads, or whatever works best for the\n\/\/ backing store.\n\/\/\n\/\/ These must be comparable, or return a comparable version on Key.\ntype Ref interface {\n\t\/\/ Key returns a dynamic type that is comparable according to the Go language specification.\n\t\/\/ The returned value must be unique for each receiver value.\n\tKey() interface{}\n}\n\nfunc HashOf(s quad.Value) (out ValueHash) {\n\tif s == nil {\n\t\treturn\n\t}\n\tquad.HashTo(s, out[:])\n\treturn\n}\n\nvar _ Ref = ValueHash{}\n\n\/\/ ValueHash is a hash of a single value.\ntype ValueHash [quad.HashSize]byte\n\nfunc (h ValueHash) Valid() bool {\n\treturn h != ValueHash{}\n}\nfunc (h ValueHash) Key() interface{} { return h }\nfunc (h ValueHash) String() string {\n\tif !h.Valid() {\n\t\treturn \"\"\n\t}\n\treturn hex.EncodeToString(h[:])\n}\n\n\/\/ PreFetchedValue is an optional interface for graph.Ref to indicate that\n\/\/ quadstore has already loaded a value into memory.\ntype PreFetchedValue interface {\n\tRef\n\tNameOf() quad.Value\n}\n\nfunc PreFetched(v quad.Value) PreFetchedValue {\n\treturn fetchedValue{v}\n}\n\ntype fetchedValue struct {\n\tVal quad.Value\n}\n\nfunc (v fetchedValue) IsNode() bool       { return true }\nfunc (v fetchedValue) NameOf() quad.Value { return v.Val }\nfunc (v fetchedValue) Key() interface{}   { return v.Val }\n\n\/\/ ToKey prepares Ref to be stored inside maps, calling Key() if necessary.\nfunc ToKey(v Ref) interface{} {\n\tif v == nil {\n\t\treturn nil\n\t}\n\treturn v.Key()\n}\n\nvar _ Ref = QuadHash{}\n\ntype QuadHash struct {\n\tSubject   ValueHash\n\tPredicate ValueHash\n\tObject    ValueHash\n\tLabel     ValueHash\n}\n\nfunc (q QuadHash) Dirs() [4]ValueHash {\n\treturn [4]ValueHash{\n\t\tq.Subject,\n\t\tq.Predicate,\n\t\tq.Object,\n\t\tq.Label,\n\t}\n}\nfunc (q QuadHash) Key() interface{} { return q }\nfunc (q QuadHash) Get(d quad.Direction) ValueHash {\n\tswitch d {\n\tcase quad.Subject:\n\t\treturn q.Subject\n\tcase quad.Predicate:\n\t\treturn q.Predicate\n\tcase quad.Object:\n\t\treturn q.Object\n\tcase quad.Label:\n\t\treturn q.Label\n\t}\n\tpanic(fmt.Errorf(\"unknown direction: %v\", d))\n}\nfunc (q *QuadHash) Set(d quad.Direction, h ValueHash) {\n\tswitch d {\n\tcase quad.Subject:\n\t\tq.Subject = h\n\tcase quad.Predicate:\n\t\tq.Predicate = h\n\tcase quad.Object:\n\t\tq.Object = h\n\tcase quad.Label:\n\t\tq.Label = h\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown direction: %v\", d))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2010 The draw2d Authors. All rights reserved.\n\/\/ created: 21\/11\/2010 by Laurent Le Goff, Stani Michiels\n\n\/\/ Load a png image and rotate it\npackage main\n\nimport (\n\t\"image\/color\"\n\t\"math\"\n\n\t\"github.com\/stanim\/draw2d\"\n\t\"github.com\/stanim\/draw2d\/pdf2d\"\n\t\"github.com\/stanim\/gofpdf\"\n)\n\nfunc main() {\n\t\/\/ Margin between the image and the frame\n\tconst margin = 30\n\t\/\/ Line width od the frame\n\tconst lineWidth = 3\n\n\t\/\/ Initialize the graphic context on an RGBA image\n\tdest := gofpdf.New(\"P\", \"mm\", \"A4\", \"..\/font\")\n\tdest.AddPage()\n\t\/\/ Size of destination image\n\tdw, dh := dest.GetPageSize()\n\tgc := pdf2d.NewGraphicContext(dest)\n\t\/\/ Draw frame\n\tgc.SetFillColor(color.RGBA{0xff, 0xff, 0xff, 0xff})\n\tdraw2d.RoundRect(gc, lineWidth, lineWidth, dw-lineWidth, dh-lineWidth, 100, 100)\n\tgc.SetLineWidth(lineWidth)\n\tgc.FillStroke()\n\n\t\/\/ load the source image\n\tsource, err := draw2d.LoadFromPngFile(\"gopher.png\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t\/\/ Size of source image\n\tsw, sh := float64(source.Bounds().Dx()), float64(source.Bounds().Dy())\n\t\/\/ Draw image to fit in the frame\n\t\/\/ TODO Seems to have a transform bug here on draw image\n\tscale := math.Min((dw-margin*2)\/sw, (dh-margin*2)\/sh)\n\tgc.Translate(margin, margin)\n\tgc.Scale(scale, scale)\n\n\tgc.DrawImage(source)\n\n\t\/\/ Save to pdf\n\tpdf2d.SaveToPdfFile(\"frame-image.pdf\", dest)\n}\n<commit_msg>moved line in frame-image<commit_after>\/\/ Copyright 2010 The draw2d Authors. All rights reserved.\n\/\/ created: 21\/11\/2010 by Laurent Le Goff, Stani Michiels\n\n\/\/ Load a png image and rotate it\npackage main\n\nimport (\n\t\"image\/color\"\n\t\"math\"\n\n\t\"github.com\/stanim\/draw2d\"\n\t\"github.com\/stanim\/draw2d\/pdf2d\"\n\t\"github.com\/stanim\/gofpdf\"\n)\n\nfunc main() {\n\t\/\/ Margin between the image and the frame\n\tconst margin = 30\n\t\/\/ Line width od the frame\n\tconst lineWidth = 3\n\n\t\/\/ Initialize the graphic context on an RGBA image\n\tdest := gofpdf.New(\"P\", \"mm\", \"A4\", \"..\/font\")\n\tdest.AddPage()\n\tgc := pdf2d.NewGraphicContext(dest)\n\t\/\/ Size of destination image\n\tdw, dh := dest.GetPageSize()\n\t\/\/ Draw frame\n\tgc.SetFillColor(color.RGBA{0xff, 0xff, 0xff, 0xff})\n\tdraw2d.RoundRect(gc, lineWidth, lineWidth, dw-lineWidth, dh-lineWidth, 100, 100)\n\tgc.SetLineWidth(lineWidth)\n\tgc.FillStroke()\n\n\t\/\/ load the source image\n\tsource, err := draw2d.LoadFromPngFile(\"gopher.png\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t\/\/ Size of source image\n\tsw, sh := float64(source.Bounds().Dx()), float64(source.Bounds().Dy())\n\t\/\/ Draw image to fit in the frame\n\t\/\/ TODO Seems to have a transform bug here on draw image\n\tscale := math.Min((dw-margin*2)\/sw, (dh-margin*2)\/sh)\n\tgc.Translate(margin, margin)\n\tgc.Scale(scale, scale)\n\n\tgc.DrawImage(source)\n\n\t\/\/ Save to pdf\n\tpdf2d.SaveToPdfFile(\"frame-image.pdf\", dest)\n}\n<|endoftext|>"}
{"text":"<commit_before>package storage\n\nimport (\n\t\"github.com\/ActiveState\/log\"\n\t\"runtime\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\ntype Tracker interface {\n\tUpdate(instKey string, childKey string, childVal int64)\n\tLoadTailers()\n\tRemove(key string)\n\tRegisterInstance(instKey string)\n\tInitializeChildNode(instKey string, childkey string, offSet int64)\n\tSubmit()\n\tStartSubmissionTimer(retentionPeriod time.Duration)\n\tIsInstanceRegistered(instKey string) bool\n\tIsChildNodeInitialized(instKey string, childkey string) bool\n\tGetFileCachedOffset(instkey string, fname string) int64\n}\n\ntype TailNode map[string]int64\n\ntype Tailer struct {\n\tInstances map[string]TailNode\n}\n\ntype tracker struct {\n\tstorage       Storage\n\tCached        *Tailer \/\/ do not expose this, it should ONLY be updated via Tracker methods\n\tmux           *sync.Mutex\n\ttimerStopChan chan struct{} \/\/ used to send quit signal to timer\n}\n\nvar (\n\tMinIOTicker = 5 * time.Second\n)\n\nfunc NewTracker(s Storage) Tracker {\n\treturn &tracker{\n\t\tstorage: s,\n\t\tmux:     &sync.Mutex{},\n\t\tCached: &Tailer{\n\t\t\tInstances: make(map[string]TailNode),\n\t\t},\n\t\ttimerStopChan: make(chan struct{}),\n\t}\n}\n\nfunc (t *tracker) StartSubmissionTimer(retentionPeriod time.Duration) {\n\tif retentionPeriod.Seconds() <= MinIOTicker.Seconds() {\n\t\tseconds := retentionPeriod \/ (1000 * time.Millisecond)\n\t\tlog.Warnf(\"IMPORTANT: Setting retention period to %ds will increase your IO Rate\", seconds)\n\n\t}\n\tticker := time.NewTicker(retentionPeriod)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tt.Submit()\n\t\t\tcase <-t.timerStopChan:\n\t\t\t\tticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n}\n\nfunc (t *tracker) RegisterInstance(instKey string) {\n\tt.mux.Lock()\n\tif _, instance_exist := t.Cached.Instances[instKey]; !instance_exist {\n\t\tt.Cached.Instances[instKey] = TailNode{}\n\t\tlog.Info(\"Current status : \", t.Cached.Instances)\n\t}\n\tt.mux.Unlock()\n}\n\n\/\/ this is mainly used for testing since we are not exposing Cached via interface\nfunc (t *tracker) IsInstanceRegistered(instKey string) bool {\n\tvar exist bool\n\tt.mux.Lock()\n\tif _, instance_exist := t.Cached.Instances[instKey]; instance_exist {\n\t\texist = instance_exist\n\t}\n\tt.mux.Unlock()\n\treturn exist\n}\n\nfunc (t *tracker) IsChildNodeInitialized(instKey string, childkey string) bool {\n\tvar exist bool\n\tt.mux.Lock()\n\tif tailNode, instance_exist := t.Cached.Instances[instKey]; instance_exist {\n\t\tif _, childNode_exist := tailNode[childkey]; childNode_exist {\n\t\t\texist = childNode_exist\n\t\t}\n\t}\n\tt.mux.Unlock()\n\treturn exist\n}\n\nfunc (t *tracker) InitializeChildNode(instKey string, childkey string, offSet int64) {\n\tt.mux.Lock()\n\tif tailNode, instance_exist := t.Cached.Instances[instKey]; instance_exist {\n\t\tif _, childNode_exist := tailNode[childkey]; !childNode_exist {\n\t\t\ttailNode[childkey] = offSet\n\t\t\tt.Cached.Instances[instKey] = tailNode\n\t\t\tlog.Info(\"Current status : \", t.Cached.Instances)\n\t\t}\n\t}\n\tt.mux.Unlock()\n\truntime.Gosched()\n}\n\nfunc (t *tracker) GetFileCachedOffset(instkey string, fname string) int64 {\n\tvar offset int64\n\tt.mux.Lock()\n\tif tailNode, instance_exist := t.Cached.Instances[instkey]; instance_exist {\n\t\toffset = tailNode[fname]\n\t}\n\tt.mux.Unlock()\n\truntime.Gosched()\n\treturn offset\n}\n\nfunc (t *tracker) Update(instKey string, childKey string, childVal int64) {\n\tvar offset int64 = 0\n\tif tailNode, instance_exist := t.Cached.Instances[instKey]; instance_exist {\n\t\tif _, childNode_exist := tailNode[childKey]; childNode_exist {\n\t\t\tatomic.StoreInt64(&offset, childVal)\n\t\t\ttailNode[childKey] = offset\n\t\t}\n\t}\n}\n\nfunc (t *tracker) Remove(key string) {\n\tlog.Info(\"Removing the following key %s from cached instances\", key)\n\tt.mux.Lock()\n\tdelete(t.Cached.Instances, key)\n\tt.mux.Unlock()\n\tt.Submit()\n}\n\nfunc (t *tracker) LoadTailers() {\n\tt.mux.Lock()\n\tt.storage.Load(&t.Cached)\n\tlog.Info(\"Loaded the following tailers from previous session:\", t.Cached.Instances)\n\tt.mux.Unlock()\n}\n\nfunc (t *tracker) Submit() {\n\tt.mux.Lock()\n\tlog.Info(\"Storing the offset in the following instances:\", t.Cached.Instances)\n\tt.storage.Write(t.Cached)\n\tt.mux.Unlock()\n}\n<commit_msg>300409-updated the tailnode offset to an struct boxedInt64 so we can refrence the address during atomic store<commit_after>package storage\n\nimport (\n\t\"github.com\/ActiveState\/log\"\n\t\"runtime\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n)\n\ntype Tracker interface {\n\tUpdate(instKey string, childKey string, childVal int64)\n\tLoadTailers()\n\tRemove(key string)\n\tRegisterInstance(instKey string)\n\tInitializeChildNode(instKey string, childkey string, offSet int64)\n\tSubmit()\n\tStartSubmissionTimer(retentionPeriod time.Duration)\n\tIsInstanceRegistered(instKey string) bool\n\tIsChildNodeInitialized(instKey string, childkey string) bool\n\tGetFileCachedOffset(instkey string, fname string) int64\n}\n\ntype boxedInt64 struct { v int64}\n\ntype TailNode map[string]*boxedInt64\n\ntype Tailer struct {\n\tInstances map[string]TailNode\n}\n\ntype tracker struct {\n\tstorage       Storage\n\tCached        *Tailer \/\/ do not expose this, it should ONLY be updated via Tracker methods\n\tmux           *sync.Mutex\n\ttimerStopChan chan struct{} \/\/ used to send quit signal to timer\n}\n\nvar (\n\tMinIOTicker = 5 * time.Second\n)\n\nfunc NewTracker(s Storage) Tracker {\n\treturn &tracker{\n\t\tstorage: s,\n\t\tmux:     &sync.Mutex{},\n\t\tCached: &Tailer{\n\t\t\tInstances: make(map[string]TailNode),\n\t\t},\n\t\ttimerStopChan: make(chan struct{}),\n\t}\n}\n\nfunc (t *tracker) StartSubmissionTimer(retentionPeriod time.Duration) {\n\tif retentionPeriod.Seconds() <= MinIOTicker.Seconds() {\n\t\tseconds := retentionPeriod \/ (1000 * time.Millisecond)\n\t\tlog.Warnf(\"IMPORTANT: Setting retention period to %ds will increase your IO Rate\", seconds)\n\n\t}\n\tticker := time.NewTicker(retentionPeriod)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tt.Submit()\n\t\t\tcase <-t.timerStopChan:\n\t\t\t\tticker.Stop()\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n}\n\nfunc (t *tracker) RegisterInstance(instKey string) {\n\tt.mux.Lock()\n\tif _, instance_exist := t.Cached.Instances[instKey]; !instance_exist {\n\t\tt.Cached.Instances[instKey] = TailNode{}\n\t\tlog.Info(\"Current status : \", t.Cached.Instances)\n\t}\n\tt.mux.Unlock()\n}\n\n\/\/ this is mainly used for testing since we are not exposing Cached via interface\nfunc (t *tracker) IsInstanceRegistered(instKey string) bool {\n\tvar exist bool\n\tt.mux.Lock()\n\tif _, instance_exist := t.Cached.Instances[instKey]; instance_exist {\n\t\texist = instance_exist\n\t}\n\tt.mux.Unlock()\n\treturn exist\n}\n\nfunc (t *tracker) IsChildNodeInitialized(instKey string, childkey string) bool {\n\tvar exist bool\n\tt.mux.Lock()\n\tif tailNode, instance_exist := t.Cached.Instances[instKey]; instance_exist {\n\t\tif _, childNode_exist := tailNode[childkey]; childNode_exist {\n\t\t\texist = childNode_exist\n\t\t}\n\t}\n\tt.mux.Unlock()\n\treturn exist\n}\n\nfunc (t *tracker) InitializeChildNode(instKey string, childkey string, offSet int64) {\n\tt.mux.Lock()\n\tif tailNode, instance_exist := t.Cached.Instances[instKey]; instance_exist {\n\t\tif _, childNode_exist := tailNode[childkey]; !childNode_exist {\n\t\t\ttailNode[childkey] = &boxedInt64{v: offSet}\n\t\t\tt.Cached.Instances[instKey] = tailNode\n\t\t\tlog.Info(\"Current status : \", t.Cached.Instances)\n\t\t}\n\t}\n\tt.mux.Unlock()\n\truntime.Gosched()\n}\n\nfunc (t *tracker) GetFileCachedOffset(instkey string, fname string) int64 {\n\tvar offset int64\n\tt.mux.Lock()\n\tif tailNode, instance_exist := t.Cached.Instances[instkey]; instance_exist {\n\t\toffset = tailNode[fname].v\n\t}\n\tt.mux.Unlock()\n\truntime.Gosched()\n\treturn offset\n}\n\nfunc (t *tracker) Update(instKey string, childKey string, childVal int64) {\n\tif tailNode, instance_exist := t.Cached.Instances[instKey]; instance_exist {\n\t\tif _, childNode_exist := tailNode[childKey]; childNode_exist {\n\t\t\tatomic.StoreInt64(&tailNode[childKey].v, childVal)\n\t\t}\n\t}\n}\n\nfunc (t *tracker) Remove(key string) {\n\tlog.Info(\"Removing the following key %s from cached instances\", key)\n\tt.mux.Lock()\n\tdelete(t.Cached.Instances, key)\n\tt.mux.Unlock()\n\tt.Submit()\n}\n\nfunc (t *tracker) LoadTailers() {\n\tt.mux.Lock()\n\tt.storage.Load(&t.Cached)\n\tlog.Info(\"Loaded the following tailers from previous session:\", t.Cached.Instances)\n\tt.mux.Unlock()\n}\n\nfunc (t *tracker) Submit() {\n\tt.mux.Lock()\n\tlog.Info(\"Storing the offset in the following instances:\", t.Cached.Instances)\n\tt.storage.Write(t.Cached)\n\tt.mux.Unlock()\n}\n<|endoftext|>"}
{"text":"<commit_before>package common\n\nimport (\n\t\"encoding\/base32\"\n\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/rancher\/norman\/types\"\n\t\"github.com\/rancher\/norman\/types\/slice\"\n\t\"github.com\/rancher\/rancher\/pkg\/auth\/tokens\"\n\t\"github.com\/rancher\/rancher\/pkg\/randomtoken\"\n\t\"github.com\/rancher\/types\/apis\/management.cattle.io\/v3\"\n\t\"github.com\/rancher\/types\/config\"\n\t\"github.com\/rancher\/types\/user\"\n\terrors2 \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\t\"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n)\n\nconst (\n\tuserAuthHeader        = \"Impersonate-User\"\n\tuserByPrincipalIndex  = \"auth.management.cattle.io\/userByPrincipal\"\n\tcrtbsByPrincipalIndex = \"auth.management.cattle.io\/crtbByPrincipal\"\n\tprtbsByPrincipalIndex = \"auth.management.cattle.io\/prtbByPrincipal\"\n)\n\nfunc NewUserManager(scaledContext *config.ScaledContext) (user.Manager, error) {\n\tuserInformer := scaledContext.Management.Users(\"\").Controller().Informer()\n\tuserIndexers := map[string]cache.IndexFunc{\n\t\tuserByPrincipalIndex: userByPrincipal,\n\t}\n\tif err := userInformer.AddIndexers(userIndexers); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcrtbInformer := scaledContext.Management.ClusterRoleTemplateBindings(\"\").Controller().Informer()\n\tcrtbIndexers := map[string]cache.IndexFunc{\n\t\tcrtbsByPrincipalIndex: crtbsByPrincipals,\n\t}\n\tif err := crtbInformer.AddIndexers(crtbIndexers); err != nil {\n\t\treturn nil, err\n\t}\n\n\tprtbInformer := scaledContext.Management.ProjectRoleTemplateBindings(\"\").Controller().Informer()\n\tprtbIndexers := map[string]cache.IndexFunc{\n\t\tprtbsByPrincipalIndex: prtbsByPrincipals,\n\t}\n\tif err := prtbInformer.AddIndexers(prtbIndexers); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &userManager{\n\t\tusers:              scaledContext.Management.Users(\"\"),\n\t\tuserIndexer:        userInformer.GetIndexer(),\n\t\tcrtbIndexer:        crtbInformer.GetIndexer(),\n\t\tprtbIndexer:        prtbInformer.GetIndexer(),\n\t\ttokens:             scaledContext.Management.Tokens(\"\"),\n\t\ttokenLister:        scaledContext.Management.Tokens(\"\").Controller().Lister(),\n\t\tglobalRoleBindings: scaledContext.Management.GlobalRoleBindings(\"\"),\n\t}, nil\n}\n\ntype userManager struct {\n\tusers              v3.UserInterface\n\tglobalRoleBindings v3.GlobalRoleBindingInterface\n\tuserIndexer        cache.Indexer\n\tcrtbIndexer        cache.Indexer\n\tprtbIndexer        cache.Indexer\n\ttokenLister        v3.TokenLister\n\ttokens             v3.TokenInterface\n}\n\nfunc (m *userManager) SetPrincipalOnCurrentUser(apiContext *types.APIContext, principal v3.Principal) (*v3.User, error) {\n\tuserID := m.GetUser(apiContext)\n\tif userID == \"\" {\n\t\treturn nil, errors.New(\"user not provided\")\n\t}\n\n\tuser, err := m.users.Get(userID, v1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif providerExists(user.PrincipalIDs, principal.Provider) {\n\t\tvar principalIDs []string\n\t\tfor _, id := range user.PrincipalIDs {\n\t\t\tif !strings.Contains(id, principal.Provider) {\n\t\t\t\tprincipalIDs = append(principalIDs, id)\n\t\t\t}\n\t\t}\n\t\tuser.PrincipalIDs = principalIDs\n\t}\n\n\tif !slice.ContainsString(user.PrincipalIDs, principal.Name) {\n\t\tuser.PrincipalIDs = append(user.PrincipalIDs, principal.Name)\n\t\treturn m.users.Update(user)\n\t}\n\treturn user, nil\n}\n\nfunc (m *userManager) GetUser(apiContext *types.APIContext) string {\n\treturn apiContext.Request.Header.Get(userAuthHeader)\n}\n\n\/\/ checkis if the supplied principal can login based on the accessMode and allowed principals\nfunc (m *userManager) CheckAccess(accessMode string, allowedPrincipalIDs []string, userPrinc v3.Principal, groups []v3.Principal) (bool, error) {\n\tif accessMode == \"unrestricted\" || accessMode == \"\" {\n\t\treturn true, nil\n\t}\n\n\tif accessMode == \"required\" || accessMode == \"restricted\" {\n\t\tuser, err := m.checkCache(userPrinc.Name)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tuserPrincipals := []string{userPrinc.Name}\n\t\tif user != nil {\n\t\t\tfor _, p := range user.PrincipalIDs {\n\t\t\t\tuserPrincipals = append(userPrincipals, p)\n\t\t\t}\n\t\t}\n\n\t\tfor _, p := range userPrincipals {\n\t\t\tif slice.ContainsString(allowedPrincipalIDs, p) {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t\tfor _, g := range groups {\n\t\t\tif slice.ContainsString(allowedPrincipalIDs, g.Name) {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t\tif accessMode == \"restricted\" {\n\t\t\t\/\/ check if any of the user's principals are in a project or cluster\n\t\t\tvar principals []string\n\t\t\tfor _, g := range groups {\n\t\t\t\tprincipals = append(principals, g.Name)\n\t\t\t}\n\t\t\tif user != nil {\n\t\t\t\tprincipals = append(principals, userPrincipals...)\n\t\t\t}\n\n\t\t\treturn m.atLeastOnePrincipalInProjectOrCluster(principals)\n\t\t}\n\t\treturn false, nil\n\t}\n\treturn false, errors.Errorf(\"Unsupported accessMode: %v\", accessMode)\n}\n\nfunc (m *userManager) EnsureToken(tokenName, description, userName string) (string, error) {\n\tif strings.HasPrefix(tokenName, \"token-\") {\n\t\treturn \"\", errors.New(\"token names can't start with token-\")\n\t}\n\n\ttoken, err := m.tokenLister.Get(\"\", tokenName)\n\tif errors2.IsNotFound(err) {\n\t\ttoken, err = nil, nil\n\t} else if err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif token == nil {\n\t\tkey, err := randomtoken.Generate()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to generate token key\")\n\t\t}\n\n\t\ttoken = &v3.Token{\n\t\t\tObjectMeta: v1.ObjectMeta{\n\t\t\t\tName: tokenName,\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\ttokens.UserIDLabel: userName,\n\t\t\t\t},\n\t\t\t},\n\t\t\tTTLMillis:    0,\n\t\t\tDescription:  description,\n\t\t\tUserID:       userName,\n\t\t\tAuthProvider: \"local\",\n\t\t\tIsDerived:    true,\n\t\t\tToken:        key,\n\t\t}\n\n\t\tcreatedToken, err := m.tokens.Create(token)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\ttoken = createdToken\n\n\t}\n\n\treturn token.Name + \":\" + token.Token, nil\n}\n\nfunc (m *userManager) EnsureUser(principalName, displayName string) (*v3.User, error) {\n\t\/\/ First check the local cache\n\tu, err := m.checkCache(principalName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif u != nil {\n\t\treturn u, nil\n\t}\n\n\t\/\/ Not in cache, query API by label\n\tu, labelSet, err := m.checkLabels(principalName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif u != nil {\n\t\treturn u, nil\n\t}\n\n\t\/\/ Doesn't exist, create user\n\tuser := &v3.User{\n\t\tObjectMeta: v1.ObjectMeta{\n\t\t\tGenerateName: \"user-\",\n\t\t\tLabels:       labelSet,\n\t\t},\n\t\tDisplayName:  displayName,\n\t\tPrincipalIDs: []string{principalName},\n\t}\n\n\tcreated, err := m.users.Create(user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = m.globalRoleBindings.Create(&v3.GlobalRoleBinding{\n\t\tObjectMeta: v1.ObjectMeta{\n\t\t\tGenerateName: \"globalrolebinding-\",\n\t\t},\n\t\tUserName:       created.Name,\n\t\tGlobalRoleName: \"user\",\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn created, nil\n}\n\nfunc (m *userManager) checkCache(principalName string) (*v3.User, error) {\n\tusers, err := m.userIndexer.ByIndex(userByPrincipalIndex, principalName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(users) > 1 {\n\t\treturn nil, errors.Errorf(\"can't find unique user for principal %v\", principalName)\n\t}\n\tif len(users) == 1 {\n\t\tu := users[0].(*v3.User)\n\t\treturn u.DeepCopy(), nil\n\t}\n\treturn nil, nil\n}\n\nfunc (m *userManager) atLeastOnePrincipalInProjectOrCluster(principals []string) (bool, error) {\n\tfor _, principal := range principals {\n\t\tcrtbs, err := m.crtbIndexer.ByIndex(crtbsByPrincipalIndex, principal)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif len(crtbs) > 0 {\n\t\t\treturn true, nil\n\t\t}\n\t\tprtbs, err := m.prtbIndexer.ByIndex(prtbsByPrincipalIndex, principal)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif len(prtbs) > 0 {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n\nfunc (m *userManager) checkLabels(principalName string) (*v3.User, labels.Set, error) {\n\tencodedPrincipalID := base32.HexEncoding.WithPadding(base32.NoPadding).EncodeToString([]byte(principalName))\n\tif len(encodedPrincipalID) > 63 {\n\t\tencodedPrincipalID = encodedPrincipalID[:63]\n\t}\n\tset := labels.Set(map[string]string{encodedPrincipalID: \"hashed-principal-name\"})\n\tusers, err := m.users.List(v1.ListOptions{LabelSelector: set.String()})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif len(users.Items) == 0 {\n\t\treturn nil, set, nil\n\t}\n\n\tvar match *v3.User\n\tfor _, u := range users.Items {\n\t\tif slice.ContainsString(u.PrincipalIDs, principalName) {\n\t\t\tif match != nil {\n\t\t\t\t\/\/ error out on duplicates\n\t\t\t\treturn nil, nil, errors.Errorf(\"can't find unique user for principal %v\", principalName)\n\t\t\t}\n\t\t\tmatch = &u\n\t\t}\n\t}\n\n\treturn match, set, nil\n}\n\nfunc userByPrincipal(obj interface{}) ([]string, error) {\n\tu, ok := obj.(*v3.User)\n\tif !ok {\n\t\treturn []string{}, nil\n\t}\n\n\treturn u.PrincipalIDs, nil\n}\n\nfunc crtbsByPrincipals(obj interface{}) ([]string, error) {\n\tvar principals []string\n\tb, ok := obj.(*v3.ClusterRoleTemplateBinding)\n\tif !ok {\n\t\treturn []string{}, nil\n\t}\n\tif b.GroupPrincipalName != \"\" {\n\t\tprincipals = append(principals, b.GroupPrincipalName)\n\t}\n\tif b.UserPrincipalName != \"\" {\n\t\tprincipals = append(principals, b.UserPrincipalName)\n\t}\n\treturn principals, nil\n}\n\nfunc prtbsByPrincipals(obj interface{}) ([]string, error) {\n\tvar principals []string\n\tb, ok := obj.(*v3.ProjectRoleTemplateBinding)\n\tif !ok {\n\t\treturn []string{}, nil\n\t}\n\tif b.GroupPrincipalName != \"\" {\n\t\tprincipals = append(principals, b.GroupPrincipalName)\n\t}\n\tif b.UserPrincipalName != \"\" {\n\t\tprincipals = append(principals, b.UserPrincipalName)\n\t}\n\treturn principals, nil\n}\n\nfunc providerExists(principalIDs []string, provider string) bool {\n\tfor _, id := range principalIDs {\n\t\tsplitID := strings.Split(id, \":\")[0]\n\t\tif strings.Contains(splitID, provider) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>Fix logic around restricted access<commit_after>package common\n\nimport (\n\t\"encoding\/base32\"\n\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/rancher\/norman\/types\"\n\t\"github.com\/rancher\/norman\/types\/slice\"\n\t\"github.com\/rancher\/rancher\/pkg\/auth\/tokens\"\n\t\"github.com\/rancher\/rancher\/pkg\/randomtoken\"\n\t\"github.com\/rancher\/types\/apis\/management.cattle.io\/v3\"\n\t\"github.com\/rancher\/types\/config\"\n\t\"github.com\/rancher\/types\/user\"\n\terrors2 \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\t\"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n)\n\nconst (\n\tuserAuthHeader               = \"Impersonate-User\"\n\tuserByPrincipalIndex         = \"auth.management.cattle.io\/userByPrincipal\"\n\tcrtbsByPrincipalAndUserIndex = \"auth.management.cattle.io\/crtbByPrincipalAndUser\"\n\tprtbsByPrincipalAndUserIndex = \"auth.management.cattle.io\/prtbByPrincipalAndUser\"\n)\n\nfunc NewUserManager(scaledContext *config.ScaledContext) (user.Manager, error) {\n\tuserInformer := scaledContext.Management.Users(\"\").Controller().Informer()\n\tuserIndexers := map[string]cache.IndexFunc{\n\t\tuserByPrincipalIndex: userByPrincipal,\n\t}\n\tif err := userInformer.AddIndexers(userIndexers); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcrtbInformer := scaledContext.Management.ClusterRoleTemplateBindings(\"\").Controller().Informer()\n\tcrtbIndexers := map[string]cache.IndexFunc{\n\t\tcrtbsByPrincipalAndUserIndex: crtbsByPrincipalAndUser,\n\t}\n\tif err := crtbInformer.AddIndexers(crtbIndexers); err != nil {\n\t\treturn nil, err\n\t}\n\n\tprtbInformer := scaledContext.Management.ProjectRoleTemplateBindings(\"\").Controller().Informer()\n\tprtbIndexers := map[string]cache.IndexFunc{\n\t\tprtbsByPrincipalAndUserIndex: prtbsByPrincipalAndUser,\n\t}\n\tif err := prtbInformer.AddIndexers(prtbIndexers); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &userManager{\n\t\tusers:              scaledContext.Management.Users(\"\"),\n\t\tuserIndexer:        userInformer.GetIndexer(),\n\t\tcrtbIndexer:        crtbInformer.GetIndexer(),\n\t\tprtbIndexer:        prtbInformer.GetIndexer(),\n\t\ttokens:             scaledContext.Management.Tokens(\"\"),\n\t\ttokenLister:        scaledContext.Management.Tokens(\"\").Controller().Lister(),\n\t\tglobalRoleBindings: scaledContext.Management.GlobalRoleBindings(\"\"),\n\t}, nil\n}\n\ntype userManager struct {\n\tusers              v3.UserInterface\n\tglobalRoleBindings v3.GlobalRoleBindingInterface\n\tuserIndexer        cache.Indexer\n\tcrtbIndexer        cache.Indexer\n\tprtbIndexer        cache.Indexer\n\ttokenLister        v3.TokenLister\n\ttokens             v3.TokenInterface\n}\n\nfunc (m *userManager) SetPrincipalOnCurrentUser(apiContext *types.APIContext, principal v3.Principal) (*v3.User, error) {\n\tuserID := m.GetUser(apiContext)\n\tif userID == \"\" {\n\t\treturn nil, errors.New(\"user not provided\")\n\t}\n\n\tuser, err := m.users.Get(userID, v1.GetOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif providerExists(user.PrincipalIDs, principal.Provider) {\n\t\tvar principalIDs []string\n\t\tfor _, id := range user.PrincipalIDs {\n\t\t\tif !strings.Contains(id, principal.Provider) {\n\t\t\t\tprincipalIDs = append(principalIDs, id)\n\t\t\t}\n\t\t}\n\t\tuser.PrincipalIDs = principalIDs\n\t}\n\n\tif !slice.ContainsString(user.PrincipalIDs, principal.Name) {\n\t\tuser.PrincipalIDs = append(user.PrincipalIDs, principal.Name)\n\t\treturn m.users.Update(user)\n\t}\n\treturn user, nil\n}\n\nfunc (m *userManager) GetUser(apiContext *types.APIContext) string {\n\treturn apiContext.Request.Header.Get(userAuthHeader)\n}\n\n\/\/ checkis if the supplied principal can login based on the accessMode and allowed principals\nfunc (m *userManager) CheckAccess(accessMode string, allowedPrincipalIDs []string, userPrinc v3.Principal, groups []v3.Principal) (bool, error) {\n\tif accessMode == \"unrestricted\" || accessMode == \"\" {\n\t\treturn true, nil\n\t}\n\n\tif accessMode == \"required\" || accessMode == \"restricted\" {\n\t\tuser, err := m.checkCache(userPrinc.Name)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tuserPrincipals := []string{userPrinc.Name}\n\t\tif user != nil {\n\t\t\tfor _, p := range user.PrincipalIDs {\n\t\t\t\tif userPrinc.Name != p {\n\t\t\t\t\tuserPrincipals = append(userPrincipals, p)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor _, p := range userPrincipals {\n\t\t\tif slice.ContainsString(allowedPrincipalIDs, p) {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t\tfor _, g := range groups {\n\t\t\tif slice.ContainsString(allowedPrincipalIDs, g.Name) {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\n\t\tif accessMode == \"restricted\" {\n\t\t\t\/\/ check if any of the user's principals are in a project or cluster\n\t\t\tvar userNameAndPrincipals []string\n\t\t\tfor _, g := range groups {\n\t\t\t\tuserNameAndPrincipals = append(userNameAndPrincipals, g.Name)\n\t\t\t}\n\t\t\tif user != nil {\n\t\t\t\tuserNameAndPrincipals = append(userNameAndPrincipals, user.Name)\n\t\t\t\tuserNameAndPrincipals = append(userNameAndPrincipals, userPrincipals...)\n\t\t\t}\n\n\t\t\treturn m.userExistsInClusterOrProject(userNameAndPrincipals)\n\t\t}\n\t\treturn false, nil\n\t}\n\treturn false, errors.Errorf(\"Unsupported accessMode: %v\", accessMode)\n}\n\nfunc (m *userManager) EnsureToken(tokenName, description, userName string) (string, error) {\n\tif strings.HasPrefix(tokenName, \"token-\") {\n\t\treturn \"\", errors.New(\"token names can't start with token-\")\n\t}\n\n\ttoken, err := m.tokenLister.Get(\"\", tokenName)\n\tif errors2.IsNotFound(err) {\n\t\ttoken, err = nil, nil\n\t} else if err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif token == nil {\n\t\tkey, err := randomtoken.Generate()\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to generate token key\")\n\t\t}\n\n\t\ttoken = &v3.Token{\n\t\t\tObjectMeta: v1.ObjectMeta{\n\t\t\t\tName: tokenName,\n\t\t\t\tLabels: map[string]string{\n\t\t\t\t\ttokens.UserIDLabel: userName,\n\t\t\t\t},\n\t\t\t},\n\t\t\tTTLMillis:    0,\n\t\t\tDescription:  description,\n\t\t\tUserID:       userName,\n\t\t\tAuthProvider: \"local\",\n\t\t\tIsDerived:    true,\n\t\t\tToken:        key,\n\t\t}\n\n\t\tcreatedToken, err := m.tokens.Create(token)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\ttoken = createdToken\n\n\t}\n\n\treturn token.Name + \":\" + token.Token, nil\n}\n\nfunc (m *userManager) EnsureUser(principalName, displayName string) (*v3.User, error) {\n\t\/\/ First check the local cache\n\tu, err := m.checkCache(principalName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif u != nil {\n\t\treturn u, nil\n\t}\n\n\t\/\/ Not in cache, query API by label\n\tu, labelSet, err := m.checkLabels(principalName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif u != nil {\n\t\treturn u, nil\n\t}\n\n\t\/\/ Doesn't exist, create user\n\tuser := &v3.User{\n\t\tObjectMeta: v1.ObjectMeta{\n\t\t\tGenerateName: \"user-\",\n\t\t\tLabels:       labelSet,\n\t\t},\n\t\tDisplayName:  displayName,\n\t\tPrincipalIDs: []string{principalName},\n\t}\n\n\tcreated, err := m.users.Create(user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = m.globalRoleBindings.Create(&v3.GlobalRoleBinding{\n\t\tObjectMeta: v1.ObjectMeta{\n\t\t\tGenerateName: \"globalrolebinding-\",\n\t\t},\n\t\tUserName:       created.Name,\n\t\tGlobalRoleName: \"user\",\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn created, nil\n}\n\nfunc (m *userManager) checkCache(principalName string) (*v3.User, error) {\n\tusers, err := m.userIndexer.ByIndex(userByPrincipalIndex, principalName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(users) > 1 {\n\t\treturn nil, errors.Errorf(\"can't find unique user for principal %v\", principalName)\n\t}\n\tif len(users) == 1 {\n\t\tu := users[0].(*v3.User)\n\t\treturn u.DeepCopy(), nil\n\t}\n\treturn nil, nil\n}\n\nfunc (m *userManager) userExistsInClusterOrProject(userNameAndPrincipals []string) (bool, error) {\n\tfor _, principal := range userNameAndPrincipals {\n\t\tcrtbs, err := m.crtbIndexer.ByIndex(crtbsByPrincipalAndUserIndex, principal)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif len(crtbs) > 0 {\n\t\t\treturn true, nil\n\t\t}\n\t\tprtbs, err := m.prtbIndexer.ByIndex(prtbsByPrincipalAndUserIndex, principal)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif len(prtbs) > 0 {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n\nfunc (m *userManager) checkLabels(principalName string) (*v3.User, labels.Set, error) {\n\tencodedPrincipalID := base32.HexEncoding.WithPadding(base32.NoPadding).EncodeToString([]byte(principalName))\n\tif len(encodedPrincipalID) > 63 {\n\t\tencodedPrincipalID = encodedPrincipalID[:63]\n\t}\n\tset := labels.Set(map[string]string{encodedPrincipalID: \"hashed-principal-name\"})\n\tusers, err := m.users.List(v1.ListOptions{LabelSelector: set.String()})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif len(users.Items) == 0 {\n\t\treturn nil, set, nil\n\t}\n\n\tvar match *v3.User\n\tfor _, u := range users.Items {\n\t\tif slice.ContainsString(u.PrincipalIDs, principalName) {\n\t\t\tif match != nil {\n\t\t\t\t\/\/ error out on duplicates\n\t\t\t\treturn nil, nil, errors.Errorf(\"can't find unique user for principal %v\", principalName)\n\t\t\t}\n\t\t\tmatch = &u\n\t\t}\n\t}\n\n\treturn match, set, nil\n}\n\nfunc userByPrincipal(obj interface{}) ([]string, error) {\n\tu, ok := obj.(*v3.User)\n\tif !ok {\n\t\treturn []string{}, nil\n\t}\n\n\treturn u.PrincipalIDs, nil\n}\n\nfunc crtbsByPrincipalAndUser(obj interface{}) ([]string, error) {\n\tvar principals []string\n\tb, ok := obj.(*v3.ClusterRoleTemplateBinding)\n\tif !ok {\n\t\treturn []string{}, nil\n\t}\n\tif b.GroupPrincipalName != \"\" {\n\t\tprincipals = append(principals, b.GroupPrincipalName)\n\t}\n\tif b.UserPrincipalName != \"\" {\n\t\tprincipals = append(principals, b.UserPrincipalName)\n\t}\n\tif b.UserName != \"\" {\n\t\tprincipals = append(principals, b.UserName)\n\t}\n\treturn principals, nil\n}\n\nfunc prtbsByPrincipalAndUser(obj interface{}) ([]string, error) {\n\tvar principals []string\n\tb, ok := obj.(*v3.ProjectRoleTemplateBinding)\n\tif !ok {\n\t\treturn []string{}, nil\n\t}\n\tif b.GroupPrincipalName != \"\" {\n\t\tprincipals = append(principals, b.GroupPrincipalName)\n\t}\n\tif b.UserPrincipalName != \"\" {\n\t\tprincipals = append(principals, b.UserPrincipalName)\n\t}\n\tif b.UserName != \"\" {\n\t\tprincipals = append(principals, b.UserName)\n\t}\n\treturn principals, nil\n}\n\nfunc providerExists(principalIDs []string, provider string) bool {\n\tfor _, id := range principalIDs {\n\t\tsplitID := strings.Split(id, \":\")[0]\n\t\tif strings.Contains(splitID, provider) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package kubernetes\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\tkapp \"k8s.io\/kubernetes\/cmd\/kubelet\/app\"\n\tclient \"k8s.io\/kubernetes\/pkg\/client\/unversioned\"\n\t\"k8s.io\/kubernetes\/pkg\/cloudprovider\"\n\t\"k8s.io\/kubernetes\/pkg\/kubelet\"\n\t\"k8s.io\/kubernetes\/pkg\/kubelet\/dockertools\"\n\tkubelettypes \"k8s.io\/kubernetes\/pkg\/kubelet\/types\"\n\t\"k8s.io\/kubernetes\/pkg\/util\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/errors\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/oom\"\n\n\tosdnapi \"github.com\/openshift\/openshift-sdn\/plugins\/osdn\/api\"\n\t\"github.com\/openshift\/openshift-sdn\/plugins\/osdn\/factory\"\n\tconfigapi \"github.com\/openshift\/origin\/pkg\/cmd\/server\/api\"\n\t\"github.com\/openshift\/origin\/pkg\/cmd\/server\/crypto\"\n\tcmdutil \"github.com\/openshift\/origin\/pkg\/cmd\/util\"\n\t\"github.com\/openshift\/origin\/pkg\/cmd\/util\/clientcmd\"\n\tcmdflags \"github.com\/openshift\/origin\/pkg\/cmd\/util\/flags\"\n\t\"github.com\/openshift\/origin\/pkg\/cmd\/util\/variable\"\n)\n\n\/\/ NodeConfig represents the required parameters to start the OpenShift node\n\/\/ through Kubernetes. All fields are required.\ntype NodeConfig struct {\n\t\/\/ BindAddress is the address to bind to\n\tBindAddress string\n\t\/\/ VolumeDir is the directory that volumes will be stored under\n\tVolumeDir string\n\t\/\/ AllowDisabledDocker if true, will make the Kubelet ignore errors from Docker\n\tAllowDisabledDocker bool\n\t\/\/ Client to connect to the master.\n\tClient *client.Client\n\t\/\/ DockerClient is a client to connect to Docker\n\tDockerClient dockertools.DockerInterface\n\t\/\/ KubeletServer contains the KubeletServer configuration\n\tKubeletServer *kapp.KubeletServer\n\t\/\/ KubeletConfig is the configuration for the kubelet, fully initialized\n\tKubeletConfig *kapp.KubeletConfig\n\t\/\/ IPTablesSyncPeriod is how often iptable rules are refreshed\n\tIPTablesSyncPeriod string\n\n\t\/\/ Maximum transmission unit for the network packets\n\tMTU uint\n\t\/\/ SDNPlugin is an optional SDN plugin\n\tSDNPlugin osdnapi.OsdnPlugin\n\t\/\/ EndpointsFilterer is an optional endpoints filterer\n\tFilteringEndpointsHandler osdnapi.FilteringEndpointsConfigHandler\n}\n\nfunc BuildKubernetesNodeConfig(options configapi.NodeConfig) (*NodeConfig, error) {\n\toriginClient, _, err := configapi.GetOpenShiftClient(options.MasterKubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkubeClient, _, err := configapi.GetKubeClient(options.MasterKubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif options.NodeName == \"localhost\" {\n\t\tglog.Warningf(`Using \"localhost\" as node name will not resolve from all locations`)\n\t}\n\n\tvar dnsIP net.IP\n\tif len(options.DNSIP) > 0 {\n\t\tdnsIP = net.ParseIP(options.DNSIP)\n\t\tif dnsIP == nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid DNS IP: %s\", options.DNSIP)\n\t\t}\n\t}\n\n\tclientCAs, err := util.CertPoolFromFile(options.ServingInfo.ClientCA)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\timageTemplate := variable.NewDefaultImageTemplate()\n\timageTemplate.Format = options.ImageConfig.Format\n\timageTemplate.Latest = options.ImageConfig.Latest\n\n\tvar path string\n\tvar fileCheckInterval int64\n\tif options.PodManifestConfig != nil {\n\t\tpath = options.PodManifestConfig.Path\n\t\tfileCheckInterval = options.PodManifestConfig.FileCheckIntervalSeconds\n\t}\n\n\tvar dockerExecHandler dockertools.ExecHandler\n\n\tswitch options.DockerConfig.ExecHandlerName {\n\tcase configapi.DockerExecHandlerNative:\n\t\tdockerExecHandler = &dockertools.NativeExecHandler{}\n\tcase configapi.DockerExecHandlerNsenter:\n\t\tdockerExecHandler = &dockertools.NsenterExecHandler{}\n\t}\n\n\tkubeAddressStr, kubePortStr, err := net.SplitHostPort(options.ServingInfo.BindAddress)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot parse node address: %v\", err)\n\t}\n\tkubePort, err := strconv.Atoi(kubePortStr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot parse node port: %v\", err)\n\t}\n\tkubeAddress := net.ParseIP(kubeAddressStr)\n\tif kubeAddress == nil {\n\t\treturn nil, fmt.Errorf(\"Invalid DNS IP: %s\", kubeAddressStr)\n\t}\n\n\t\/\/ declare the OpenShift defaults from config\n\tserver := kapp.NewKubeletServer()\n\tserver.Config = path\n\tserver.RootDirectory = options.VolumeDirectory\n\n\t\/\/ kubelet finds the node IP address by doing net.ParseIP(hostname) and if that fails,\n\t\/\/ it does net.LookupIP(NodeName) and picks the first non-loopback address.\n\t\/\/ Pass node IP as hostname to make kubelet use the desired IP address.\n\tif len(options.NodeIP) > 0 {\n\t\tserver.HostnameOverride = options.NodeIP\n\t} else {\n\t\tserver.HostnameOverride = options.NodeName\n\t}\n\tserver.AllowPrivileged = true\n\tserver.RegisterNode = true\n\tserver.Address = kubeAddress\n\tserver.Port = uint(kubePort)\n\tserver.ReadOnlyPort = 0 \/\/ no read only access\n\tserver.CAdvisorPort = 0 \/\/ no unsecured cadvisor access\n\tserver.HealthzPort = 0  \/\/ no unsecured healthz access\n\tserver.ClusterDNS = dnsIP\n\tserver.ClusterDomain = options.DNSDomain\n\tserver.NetworkPluginName = options.NetworkConfig.NetworkPluginName\n\tserver.HostNetworkSources = strings.Join([]string{kubelettypes.ApiserverSource, kubelettypes.FileSource}, \",\")\n\tserver.HostPIDSources = strings.Join([]string{kubelettypes.ApiserverSource, kubelettypes.FileSource}, \",\")\n\tserver.HostIPCSources = strings.Join([]string{kubelettypes.ApiserverSource, kubelettypes.FileSource}, \",\")\n\tserver.HTTPCheckFrequency = 0 \/\/ no remote HTTP pod creation access\n\tserver.FileCheckFrequency = time.Duration(fileCheckInterval) * time.Second\n\tserver.PodInfraContainerImage = imageTemplate.ExpandOrDie(\"pod\")\n\tserver.CPUCFSQuota = true \/\/ enable cpu cfs quota enforcement by default\n\n\t\/\/ prevents kube from generating certs\n\tserver.TLSCertFile = options.ServingInfo.ServerCert.CertFile\n\tserver.TLSPrivateKeyFile = options.ServingInfo.ServerCert.KeyFile\n\n\tif value := cmdutil.Env(\"OPENSHIFT_CONTAINERIZED\", \"\"); len(value) > 0 {\n\t\tserver.Containerized = value == \"true\"\n\t}\n\n\t\/\/ resolve extended arguments\n\t\/\/ TODO: this should be done in config validation (along with the above) so we can provide\n\t\/\/ proper errors\n\tif err := cmdflags.Resolve(options.KubeletArguments, server.AddFlags); len(err) > 0 {\n\t\treturn nil, errors.NewAggregate(err)\n\t}\n\n\tcfg, err := server.UnsecuredKubeletConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ provide any config overrides\n\tcfg.NodeName = options.NodeName\n\tcfg.KubeClient = kubeClient\n\tcfg.DockerExecHandler = dockerExecHandler\n\n\t\/\/ docker-in-docker (dind) deployments are used for testing\n\t\/\/ networking plugins.  Running openshift under dind won't work\n\t\/\/ with the real oom adjuster due to the state of the cgroups path\n\t\/\/ in a dind container that uses systemd for init.\n\t\/\/\n\t\/\/ TODO(marun) Make dind cgroups compatible with openshift\n\tif value := cmdutil.Env(\"OPENSHIFT_DIND\", \"\"); value == \"true\" {\n\t\tglog.Warningf(\"Using FakeOOMAdjuster for docker-in-docker compatibility\")\n\t\tcfg.OOMAdjuster = oom.NewFakeOOMAdjuster()\n\t}\n\n\t\/\/ Setup auth\n\tosClient, osClientConfig, err := configapi.GetOpenShiftClient(options.MasterKubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthnTTL, err := time.ParseDuration(options.AuthConfig.AuthenticationCacheTTL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthn, err := newAuthenticator(clientCAs, clientcmd.AnonymousClientConfig(*osClientConfig), authnTTL, options.AuthConfig.AuthenticationCacheSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tauthzAttr, err := newAuthorizerAttributesGetter(options.NodeName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tauthzTTL, err := time.ParseDuration(options.AuthConfig.AuthorizationCacheTTL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthz, err := newAuthorizer(osClient, authzTTL, options.AuthConfig.AuthorizationCacheSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg.Auth = kubelet.NewKubeletAuth(authn, authzAttr, authz)\n\n\t\/\/ Make sure the node doesn't think it is in standalone mode\n\t\/\/ This is required for the node to enforce nodeSelectors on pods, to set hostIP on pod status updates, etc\n\tcfg.StandaloneMode = false\n\n\t\/\/ TODO: could be cleaner\n\tif configapi.UseTLS(options.ServingInfo) {\n\t\textraCerts, err := configapi.GetNamedCertificateMap(options.ServingInfo.NamedCertificates)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcfg.TLSOptions = &kubelet.TLSOptions{\n\t\t\tConfig: crypto.SecureTLSConfig(&tls.Config{\n\t\t\t\t\/\/ RequestClientCert lets us request certs, but allow requests without client certs\n\t\t\t\t\/\/ Verification is done by the authn layer\n\t\t\t\tClientAuth: tls.RequestClientCert,\n\t\t\t\tClientCAs:  clientCAs,\n\t\t\t\t\/\/ Set SNI certificate func\n\t\t\t\t\/\/ Do not use NameToCertificate, since that requires certificates be included in the server's tlsConfig.Certificates list,\n\t\t\t\t\/\/ which we do not control when running with http.Server#ListenAndServeTLS\n\t\t\t\tGetCertificate: cmdutil.GetCertificateFunc(extraCerts),\n\t\t\t}),\n\t\t\tCertFile: options.ServingInfo.ServerCert.CertFile,\n\t\t\tKeyFile:  options.ServingInfo.ServerCert.KeyFile,\n\t\t}\n\t} else {\n\t\tcfg.TLSOptions = nil\n\t}\n\n\t\/\/ Prepare cloud provider\n\tcloud, err := cloudprovider.InitCloudProvider(server.CloudProvider, server.CloudConfigFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif cloud != nil {\n\t\tglog.V(2).Infof(\"Successfully initialized cloud provider: %q from the config file: %q\\n\", server.CloudProvider, server.CloudConfigFile)\n\t}\n\tcfg.Cloud = cloud\n\n\tsdnPlugin, endpointFilter, err := factory.NewPlugin(options.NetworkConfig.NetworkPluginName, originClient, kubeClient, options.NodeName, options.NodeIP)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"SDN initialization failed: %v\", err)\n\t} else if sdnPlugin != nil {\n\t\tcfg.NetworkPlugins = append(cfg.NetworkPlugins, sdnPlugin)\n\t}\n\n\tconfig := &NodeConfig{\n\t\tBindAddress: options.ServingInfo.BindAddress,\n\n\t\tAllowDisabledDocker: options.AllowDisabledDocker,\n\n\t\tClient: kubeClient,\n\n\t\tVolumeDir: options.VolumeDirectory,\n\n\t\tKubeletServer: server,\n\t\tKubeletConfig: cfg,\n\n\t\tIPTablesSyncPeriod: options.IPTablesSyncPeriod,\n\t\tMTU:                options.NetworkConfig.MTU,\n\n\t\tSDNPlugin:                 sdnPlugin,\n\t\tFilteringEndpointsHandler: endpointFilter,\n\t}\n\n\treturn config, nil\n}\n<commit_msg>Fix dind compatibility with centos\/rhel<commit_after>package kubernetes\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\tkapp \"k8s.io\/kubernetes\/cmd\/kubelet\/app\"\n\tclient \"k8s.io\/kubernetes\/pkg\/client\/unversioned\"\n\t\"k8s.io\/kubernetes\/pkg\/cloudprovider\"\n\t\"k8s.io\/kubernetes\/pkg\/kubelet\"\n\t\"k8s.io\/kubernetes\/pkg\/kubelet\/dockertools\"\n\tkubelettypes \"k8s.io\/kubernetes\/pkg\/kubelet\/types\"\n\t\"k8s.io\/kubernetes\/pkg\/util\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/errors\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/oom\"\n\n\tosdnapi \"github.com\/openshift\/openshift-sdn\/plugins\/osdn\/api\"\n\t\"github.com\/openshift\/openshift-sdn\/plugins\/osdn\/factory\"\n\tconfigapi \"github.com\/openshift\/origin\/pkg\/cmd\/server\/api\"\n\t\"github.com\/openshift\/origin\/pkg\/cmd\/server\/crypto\"\n\tcmdutil \"github.com\/openshift\/origin\/pkg\/cmd\/util\"\n\t\"github.com\/openshift\/origin\/pkg\/cmd\/util\/clientcmd\"\n\tcmdflags \"github.com\/openshift\/origin\/pkg\/cmd\/util\/flags\"\n\t\"github.com\/openshift\/origin\/pkg\/cmd\/util\/variable\"\n)\n\n\/\/ NodeConfig represents the required parameters to start the OpenShift node\n\/\/ through Kubernetes. All fields are required.\ntype NodeConfig struct {\n\t\/\/ BindAddress is the address to bind to\n\tBindAddress string\n\t\/\/ VolumeDir is the directory that volumes will be stored under\n\tVolumeDir string\n\t\/\/ AllowDisabledDocker if true, will make the Kubelet ignore errors from Docker\n\tAllowDisabledDocker bool\n\t\/\/ Client to connect to the master.\n\tClient *client.Client\n\t\/\/ DockerClient is a client to connect to Docker\n\tDockerClient dockertools.DockerInterface\n\t\/\/ KubeletServer contains the KubeletServer configuration\n\tKubeletServer *kapp.KubeletServer\n\t\/\/ KubeletConfig is the configuration for the kubelet, fully initialized\n\tKubeletConfig *kapp.KubeletConfig\n\t\/\/ IPTablesSyncPeriod is how often iptable rules are refreshed\n\tIPTablesSyncPeriod string\n\n\t\/\/ Maximum transmission unit for the network packets\n\tMTU uint\n\t\/\/ SDNPlugin is an optional SDN plugin\n\tSDNPlugin osdnapi.OsdnPlugin\n\t\/\/ EndpointsFilterer is an optional endpoints filterer\n\tFilteringEndpointsHandler osdnapi.FilteringEndpointsConfigHandler\n}\n\nfunc BuildKubernetesNodeConfig(options configapi.NodeConfig) (*NodeConfig, error) {\n\toriginClient, _, err := configapi.GetOpenShiftClient(options.MasterKubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkubeClient, _, err := configapi.GetKubeClient(options.MasterKubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif options.NodeName == \"localhost\" {\n\t\tglog.Warningf(`Using \"localhost\" as node name will not resolve from all locations`)\n\t}\n\n\tvar dnsIP net.IP\n\tif len(options.DNSIP) > 0 {\n\t\tdnsIP = net.ParseIP(options.DNSIP)\n\t\tif dnsIP == nil {\n\t\t\treturn nil, fmt.Errorf(\"Invalid DNS IP: %s\", options.DNSIP)\n\t\t}\n\t}\n\n\tclientCAs, err := util.CertPoolFromFile(options.ServingInfo.ClientCA)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\timageTemplate := variable.NewDefaultImageTemplate()\n\timageTemplate.Format = options.ImageConfig.Format\n\timageTemplate.Latest = options.ImageConfig.Latest\n\n\tvar path string\n\tvar fileCheckInterval int64\n\tif options.PodManifestConfig != nil {\n\t\tpath = options.PodManifestConfig.Path\n\t\tfileCheckInterval = options.PodManifestConfig.FileCheckIntervalSeconds\n\t}\n\n\tvar dockerExecHandler dockertools.ExecHandler\n\n\tswitch options.DockerConfig.ExecHandlerName {\n\tcase configapi.DockerExecHandlerNative:\n\t\tdockerExecHandler = &dockertools.NativeExecHandler{}\n\tcase configapi.DockerExecHandlerNsenter:\n\t\tdockerExecHandler = &dockertools.NsenterExecHandler{}\n\t}\n\n\tkubeAddressStr, kubePortStr, err := net.SplitHostPort(options.ServingInfo.BindAddress)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot parse node address: %v\", err)\n\t}\n\tkubePort, err := strconv.Atoi(kubePortStr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot parse node port: %v\", err)\n\t}\n\tkubeAddress := net.ParseIP(kubeAddressStr)\n\tif kubeAddress == nil {\n\t\treturn nil, fmt.Errorf(\"Invalid DNS IP: %s\", kubeAddressStr)\n\t}\n\n\t\/\/ declare the OpenShift defaults from config\n\tserver := kapp.NewKubeletServer()\n\tserver.Config = path\n\tserver.RootDirectory = options.VolumeDirectory\n\n\t\/\/ kubelet finds the node IP address by doing net.ParseIP(hostname) and if that fails,\n\t\/\/ it does net.LookupIP(NodeName) and picks the first non-loopback address.\n\t\/\/ Pass node IP as hostname to make kubelet use the desired IP address.\n\tif len(options.NodeIP) > 0 {\n\t\tserver.HostnameOverride = options.NodeIP\n\t} else {\n\t\tserver.HostnameOverride = options.NodeName\n\t}\n\tserver.AllowPrivileged = true\n\tserver.RegisterNode = true\n\tserver.Address = kubeAddress\n\tserver.Port = uint(kubePort)\n\tserver.ReadOnlyPort = 0 \/\/ no read only access\n\tserver.CAdvisorPort = 0 \/\/ no unsecured cadvisor access\n\tserver.HealthzPort = 0  \/\/ no unsecured healthz access\n\tserver.ClusterDNS = dnsIP\n\tserver.ClusterDomain = options.DNSDomain\n\tserver.NetworkPluginName = options.NetworkConfig.NetworkPluginName\n\tserver.HostNetworkSources = strings.Join([]string{kubelettypes.ApiserverSource, kubelettypes.FileSource}, \",\")\n\tserver.HostPIDSources = strings.Join([]string{kubelettypes.ApiserverSource, kubelettypes.FileSource}, \",\")\n\tserver.HostIPCSources = strings.Join([]string{kubelettypes.ApiserverSource, kubelettypes.FileSource}, \",\")\n\tserver.HTTPCheckFrequency = 0 \/\/ no remote HTTP pod creation access\n\tserver.FileCheckFrequency = time.Duration(fileCheckInterval) * time.Second\n\tserver.PodInfraContainerImage = imageTemplate.ExpandOrDie(\"pod\")\n\tserver.CPUCFSQuota = true \/\/ enable cpu cfs quota enforcement by default\n\n\t\/\/ prevents kube from generating certs\n\tserver.TLSCertFile = options.ServingInfo.ServerCert.CertFile\n\tserver.TLSPrivateKeyFile = options.ServingInfo.ServerCert.KeyFile\n\n\tif value := cmdutil.Env(\"OPENSHIFT_CONTAINERIZED\", \"\"); len(value) > 0 {\n\t\tserver.Containerized = value == \"true\"\n\t}\n\n\t\/\/ resolve extended arguments\n\t\/\/ TODO: this should be done in config validation (along with the above) so we can provide\n\t\/\/ proper errors\n\tif err := cmdflags.Resolve(options.KubeletArguments, server.AddFlags); len(err) > 0 {\n\t\treturn nil, errors.NewAggregate(err)\n\t}\n\n\tcfg, err := server.UnsecuredKubeletConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ provide any config overrides\n\tcfg.NodeName = options.NodeName\n\tcfg.KubeClient = kubeClient\n\tcfg.DockerExecHandler = dockerExecHandler\n\n\t\/\/ docker-in-docker (dind) deployments are used for testing\n\t\/\/ networking plugins.  Running openshift under dind won't work\n\t\/\/ with the real oom adjuster due to the state of the cgroups path\n\t\/\/ in a dind container that uses systemd for init.  Similarly,\n\t\/\/ cgroup manipulation of the nested docker daemon doesn't work\n\t\/\/ properly under centos\/rhel and should be disabled by setting\n\t\/\/ the name of the container to an empty string.\n\t\/\/\n\t\/\/ This workaround should become unnecessary once user namespaces\n\tif value := cmdutil.Env(\"OPENSHIFT_DIND\", \"\"); value == \"true\" {\n\t\tglog.Warningf(\"Using FakeOOMAdjuster for docker-in-docker compatibility\")\n\t\tcfg.OOMAdjuster = oom.NewFakeOOMAdjuster()\n\t\tglog.Warningf(\"Disabling cgroup manipulation of nested docker daemon for docker-in-docker compatibility\")\n\t\tcfg.DockerDaemonContainer = \"\"\n\t}\n\n\t\/\/ Setup auth\n\tosClient, osClientConfig, err := configapi.GetOpenShiftClient(options.MasterKubeConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthnTTL, err := time.ParseDuration(options.AuthConfig.AuthenticationCacheTTL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthn, err := newAuthenticator(clientCAs, clientcmd.AnonymousClientConfig(*osClientConfig), authnTTL, options.AuthConfig.AuthenticationCacheSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tauthzAttr, err := newAuthorizerAttributesGetter(options.NodeName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tauthzTTL, err := time.ParseDuration(options.AuthConfig.AuthorizationCacheTTL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tauthz, err := newAuthorizer(osClient, authzTTL, options.AuthConfig.AuthorizationCacheSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg.Auth = kubelet.NewKubeletAuth(authn, authzAttr, authz)\n\n\t\/\/ Make sure the node doesn't think it is in standalone mode\n\t\/\/ This is required for the node to enforce nodeSelectors on pods, to set hostIP on pod status updates, etc\n\tcfg.StandaloneMode = false\n\n\t\/\/ TODO: could be cleaner\n\tif configapi.UseTLS(options.ServingInfo) {\n\t\textraCerts, err := configapi.GetNamedCertificateMap(options.ServingInfo.NamedCertificates)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcfg.TLSOptions = &kubelet.TLSOptions{\n\t\t\tConfig: crypto.SecureTLSConfig(&tls.Config{\n\t\t\t\t\/\/ RequestClientCert lets us request certs, but allow requests without client certs\n\t\t\t\t\/\/ Verification is done by the authn layer\n\t\t\t\tClientAuth: tls.RequestClientCert,\n\t\t\t\tClientCAs:  clientCAs,\n\t\t\t\t\/\/ Set SNI certificate func\n\t\t\t\t\/\/ Do not use NameToCertificate, since that requires certificates be included in the server's tlsConfig.Certificates list,\n\t\t\t\t\/\/ which we do not control when running with http.Server#ListenAndServeTLS\n\t\t\t\tGetCertificate: cmdutil.GetCertificateFunc(extraCerts),\n\t\t\t}),\n\t\t\tCertFile: options.ServingInfo.ServerCert.CertFile,\n\t\t\tKeyFile:  options.ServingInfo.ServerCert.KeyFile,\n\t\t}\n\t} else {\n\t\tcfg.TLSOptions = nil\n\t}\n\n\t\/\/ Prepare cloud provider\n\tcloud, err := cloudprovider.InitCloudProvider(server.CloudProvider, server.CloudConfigFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif cloud != nil {\n\t\tglog.V(2).Infof(\"Successfully initialized cloud provider: %q from the config file: %q\\n\", server.CloudProvider, server.CloudConfigFile)\n\t}\n\tcfg.Cloud = cloud\n\n\tsdnPlugin, endpointFilter, err := factory.NewPlugin(options.NetworkConfig.NetworkPluginName, originClient, kubeClient, options.NodeName, options.NodeIP)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"SDN initialization failed: %v\", err)\n\t} else if sdnPlugin != nil {\n\t\tcfg.NetworkPlugins = append(cfg.NetworkPlugins, sdnPlugin)\n\t}\n\n\tconfig := &NodeConfig{\n\t\tBindAddress: options.ServingInfo.BindAddress,\n\n\t\tAllowDisabledDocker: options.AllowDisabledDocker,\n\n\t\tClient: kubeClient,\n\n\t\tVolumeDir: options.VolumeDirectory,\n\n\t\tKubeletServer: server,\n\t\tKubeletConfig: cfg,\n\n\t\tIPTablesSyncPeriod: options.IPTablesSyncPeriod,\n\t\tMTU:                options.NetworkConfig.MTU,\n\n\t\tSDNPlugin:                 sdnPlugin,\n\t\tFilteringEndpointsHandler: endpointFilter,\n\t}\n\n\treturn config, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package controller\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/service\/ec2\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ec2\/ec2iface\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"k8s.io\/client-go\/kubernetes\/fake\"\n\t\"k8s.io\/client-go\/pkg\/api\/v1\"\n)\n\ntype mockEC2Client struct {\n\tec2iface.EC2API\n\tres           *ec2.ModifyInstanceAttributeOutput\n\terr           error\n\tCalledCounter int\n}\n\nfunc (c *mockEC2Client) ModifyInstanceAttribute(*ec2.ModifyInstanceAttributeInput) (*ec2.ModifyInstanceAttributeOutput, error) {\n\tc.CalledCounter = c.CalledCounter + 1\n\treturn c.res, c.err\n}\n\nfunc NewMockEC2Client() *mockEC2Client {\n\treturn &mockEC2Client{CalledCounter: 0}\n}\n\nfunc TestDisableSrcDstIfEnabled(t *testing.T) {\n\tannotations := map[string]string{SrcDstCheckDisabledAnnotation: \"true\"}\n\tnode0 := &v1.Node{Spec: v1.NodeSpec{ProviderID: \"aws:\/\/\/us-mock-1\/i-abcdefgh\"}, ObjectMeta: v1.ObjectMeta{Name: \"node0\", UID: \"01\"}}\n\tnode1 := &v1.Node{Spec: v1.NodeSpec{ProviderID: \"aws:\/\/\/us-mock-1\/i-bcdefdaf\"}, ObjectMeta: v1.ObjectMeta{Name: \"node1\", UID: \"02\"}}\n\tnode1.Annotations = annotations\n\n\tvar tests = []struct {\n\t\tnode                     *v1.Node\n\t\tdisableSrcDstCheckCalled bool\n\t}{\n\t\t{node0, true},\n\t\t{node1, false},\n\t}\n\n\tec2Client := NewMockEC2Client()\n\tkubeClient := fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{*node0, *node1}})\n\n\tc := &Controller{\n\t\tec2Client: ec2Client,\n\t\tclient:    kubeClient,\n\t}\n\n\tfor _, tt := range tests {\n\t\tcalledCount := ec2Client.CalledCounter\n\t\tc.disableSrcDstIfEnabled(tt.node)\n\t\tcalled := (ec2Client.CalledCounter - calledCount) > 0\n\t\tassert.Equal(\n\t\t\tt,\n\t\t\tcalled,\n\t\t\ttt.disableSrcDstCheckCalled,\n\t\t\t\"Verify that ModifyInstanceAttribute will get called if node needs srcdstcheck disabled\",\n\t\t)\n\t}\n\n\t\/\/ Validate that node did get updated with SrcDstCheckDisabledAnnotation\n\tupdatedNodes, err := kubeClient.Core().Nodes().List(v1.ListOptions{})\n\tassert.Nil(t, err)\n\tfor _, updatedNode := range updatedNodes.Items {\n\t\tfmt.Printf(\"%v\", updatedNode.Annotations)\n\t\tassert.NotEmpty(t, updatedNode.Annotations)\n\t\tassert.NotNil(t, updatedNode.Annotations[SrcDstCheckDisabledAnnotation])\n\t}\n}\n\nfunc TestGetInstanceIDFromProviderID(t *testing.T) {\n\n\tvar tests = []struct {\n\t\tproviderID         string\n\t\texpectedInstanceID string\n\t\texpectedError      bool\n\t}{\n\t\t{\"aws:\/\/\/us-west-2a\/i-09fc5a0ae524b0333\", \"i-09fc5a0ae524b0333\", false},\n\t\t{\"aws:\/\/us-west-2a\/i-a123hd52\", \"i-a123hd52\", false},\n\t\t{\"gce:\/\/us-west-1a\/test\", \"\", true},\n\t\t{\"this_will_fail\", \"\", true},\n\t\t{\"i-a123hd52\", \"\", true},\n\t}\n\n\tfor _, tt := range tests {\n\t\tinstanceID, err := GetInstanceIDFromProviderID(tt.providerID)\n\t\tif !tt.expectedError {\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\ttt.expectedInstanceID,\n\t\t\t\t*instanceID,\n\t\t\t\t\"Check if instance ID is parsed out correctly from provider ID\",\n\t\t\t)\n\t\t} else {\n\t\t\tassert.NotNil(\n\t\t\t\tt,\n\t\t\t\terr,\n\t\t\t\terr.Error(),\n\t\t\t)\n\t\t}\n\t}\n\n}\n<commit_msg>remove unnecessary print in testcase<commit_after>package controller\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/service\/ec2\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ec2\/ec2iface\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"k8s.io\/client-go\/kubernetes\/fake\"\n\t\"k8s.io\/client-go\/pkg\/api\/v1\"\n)\n\ntype mockEC2Client struct {\n\tec2iface.EC2API\n\tres           *ec2.ModifyInstanceAttributeOutput\n\terr           error\n\tCalledCounter int\n}\n\nfunc (c *mockEC2Client) ModifyInstanceAttribute(*ec2.ModifyInstanceAttributeInput) (*ec2.ModifyInstanceAttributeOutput, error) {\n\tc.CalledCounter = c.CalledCounter + 1\n\treturn c.res, c.err\n}\n\nfunc NewMockEC2Client() *mockEC2Client {\n\treturn &mockEC2Client{CalledCounter: 0}\n}\n\nfunc TestDisableSrcDstIfEnabled(t *testing.T) {\n\tannotations := map[string]string{SrcDstCheckDisabledAnnotation: \"true\"}\n\tnode0 := &v1.Node{Spec: v1.NodeSpec{ProviderID: \"aws:\/\/\/us-mock-1\/i-abcdefgh\"}, ObjectMeta: v1.ObjectMeta{Name: \"node0\", UID: \"01\"}}\n\tnode1 := &v1.Node{Spec: v1.NodeSpec{ProviderID: \"aws:\/\/\/us-mock-1\/i-bcdefdaf\"}, ObjectMeta: v1.ObjectMeta{Name: \"node1\", UID: \"02\"}}\n\tnode1.Annotations = annotations\n\n\tvar tests = []struct {\n\t\tnode                     *v1.Node\n\t\tdisableSrcDstCheckCalled bool\n\t}{\n\t\t{node0, true},\n\t\t{node1, false},\n\t}\n\n\tec2Client := NewMockEC2Client()\n\tkubeClient := fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{*node0, *node1}})\n\n\tc := &Controller{\n\t\tec2Client: ec2Client,\n\t\tclient:    kubeClient,\n\t}\n\n\tfor _, tt := range tests {\n\t\tcalledCount := ec2Client.CalledCounter\n\t\tc.disableSrcDstIfEnabled(tt.node)\n\t\tcalled := (ec2Client.CalledCounter - calledCount) > 0\n\t\tassert.Equal(\n\t\t\tt,\n\t\t\tcalled,\n\t\t\ttt.disableSrcDstCheckCalled,\n\t\t\t\"Verify that ModifyInstanceAttribute will get called if node needs srcdstcheck disabled\",\n\t\t)\n\t}\n\n\t\/\/ Validate that node did get updated with SrcDstCheckDisabledAnnotation\n\tupdatedNodes, err := kubeClient.Core().Nodes().List(v1.ListOptions{})\n\tassert.Nil(t, err)\n\tfor _, updatedNode := range updatedNodes.Items {\n\t\tassert.NotEmpty(t, updatedNode.Annotations)\n\t\tassert.NotNil(t, updatedNode.Annotations[SrcDstCheckDisabledAnnotation])\n\t}\n}\n\nfunc TestGetInstanceIDFromProviderID(t *testing.T) {\n\n\tvar tests = []struct {\n\t\tproviderID         string\n\t\texpectedInstanceID string\n\t\texpectedError      bool\n\t}{\n\t\t{\"aws:\/\/\/us-west-2a\/i-09fc5a0ae524b0333\", \"i-09fc5a0ae524b0333\", false},\n\t\t{\"aws:\/\/us-west-2a\/i-a123hd52\", \"i-a123hd52\", false},\n\t\t{\"gce:\/\/us-west-1a\/test\", \"\", true},\n\t\t{\"this_will_fail\", \"\", true},\n\t\t{\"i-a123hd52\", \"\", true},\n\t}\n\n\tfor _, tt := range tests {\n\t\tinstanceID, err := GetInstanceIDFromProviderID(tt.providerID)\n\t\tif !tt.expectedError {\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\ttt.expectedInstanceID,\n\t\t\t\t*instanceID,\n\t\t\t\t\"Check if instance ID is parsed out correctly from provider ID\",\n\t\t\t)\n\t\t} else {\n\t\t\tassert.NotNil(\n\t\t\t\tt,\n\t\t\t\terr,\n\t\t\t\terr.Error(),\n\t\t\t)\n\t\t}\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package controllers\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"time\"\n\n\t\"github.com\/libopenstorage\/stork\/drivers\/volume\"\n\tstork_api \"github.com\/libopenstorage\/stork\/pkg\/apis\/stork\/v1alpha1\"\n\t\"github.com\/libopenstorage\/stork\/pkg\/controllers\"\n\t\"github.com\/libopenstorage\/stork\/pkg\/k8sutils\"\n\t\"github.com\/libopenstorage\/stork\/pkg\/version\"\n\t\"github.com\/portworx\/sched-ops\/k8s\/apiextensions\"\n\t\"github.com\/portworx\/sched-ops\/k8s\/core\"\n\tstorkops \"github.com\/portworx\/sched-ops\/k8s\/stork\"\n\t\"github.com\/sirupsen\/logrus\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tapiextensionsv1beta1 \"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\/v1beta1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\trestclient \"k8s.io\/client-go\/rest\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n\t\"k8s.io\/client-go\/tools\/record\"\n\truntimeclient \"sigs.k8s.io\/controller-runtime\/pkg\/client\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/manager\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/reconcile\"\n)\n\nconst (\n\tvalidateCRDInterval time.Duration = 5 * time.Second\n\tvalidateCRDTimeout  time.Duration = 1 * time.Minute\n)\n\n\/\/ NewClusterPair creates a new instance of ClusterPairController.\nfunc NewClusterPair(mgr manager.Manager, d volume.Driver, r record.EventRecorder) *ClusterPairController {\n\treturn &ClusterPairController{\n\t\tclient:    mgr.GetClient(),\n\t\tvolDriver: d,\n\t\trecorder:  r,\n\t}\n}\n\n\/\/ ClusterPairController controller to watch over ClusterPair\ntype ClusterPairController struct {\n\tclient runtimeclient.Client\n\n\tvolDriver volume.Driver\n\trecorder  record.EventRecorder\n}\n\n\/\/ Init initialize the cluster pair controller\nfunc (c *ClusterPairController) Init(mgr manager.Manager) error {\n\terr := c.createCRD()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn controllers.RegisterTo(mgr, \"cluster-pair-controller\", c, &stork_api.ClusterPair{})\n}\n\n\/\/ Reconcile manages ClusterPair resources.\nfunc (c *ClusterPairController) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {\n\tlogrus.Tracef(\"Reconciling ClusterPair %s\/%s\", request.Namespace, request.Name)\n\n\t\/\/ Fetch the ApplicationBackup instance\n\tbackup := &stork_api.ClusterPair{}\n\terr := c.client.Get(context.TODO(), request.NamespacedName, backup)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t\/\/ Request object not found, could have been deleted after reconcile request.\n\t\t\t\/\/ Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t\/\/ Return and don't requeue\n\t\t\treturn reconcile.Result{}, nil\n\t\t}\n\t\t\/\/ Error reading the object - requeue the request.\n\t\treturn reconcile.Result{RequeueAfter: controllers.DefaultRequeueError}, err\n\t}\n\n\tif !controllers.ContainsFinalizer(backup, controllers.FinalizerCleanup) {\n\t\tcontrollers.SetFinalizer(backup, controllers.FinalizerCleanup)\n\t\treturn reconcile.Result{Requeue: true}, c.client.Update(context.TODO(), backup)\n\t}\n\n\tif err = c.handle(context.TODO(), backup); err != nil {\n\t\tlogrus.Errorf(\"%s: %s\/%s: %s\", reflect.TypeOf(c), backup.Namespace, backup.Name, err)\n\t\treturn reconcile.Result{RequeueAfter: controllers.DefaultRequeueError}, err\n\t}\n\n\treturn reconcile.Result{RequeueAfter: controllers.DefaultRequeue}, nil\n}\n\nfunc (c *ClusterPairController) handle(ctx context.Context, clusterPair *stork_api.ClusterPair) error {\n\tif clusterPair.DeletionTimestamp != nil {\n\t\tif controllers.ContainsFinalizer(clusterPair, controllers.FinalizerCleanup) {\n\t\t\tif err := c.cleanup(clusterPair); err != nil {\n\t\t\t\tlogrus.Errorf(\"%s: %s\", reflect.TypeOf(c), err)\n\t\t\t\tc.recorder.Event(\n\t\t\t\t\tclusterPair,\n\t\t\t\t\tv1.EventTypeWarning,\n\t\t\t\t\tstring(stork_api.ClusterPairStatusDeleting),\n\t\t\t\t\tfmt.Sprintf(\"Cluster Pair delete failed: %v\", err.Error()),\n\t\t\t\t)\n\t\t\t\t\/\/ Do not delete the cluster pair CR\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tif clusterPair.GetFinalizers() != nil {\n\t\t\tcontrollers.RemoveFinalizer(clusterPair, controllers.FinalizerCleanup)\n\t\t\treturn c.client.Update(ctx, clusterPair)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif _, ok := clusterPair.Spec.Options[\"token\"]; !ok {\n\t\tclusterPair.Status.StorageStatus = stork_api.ClusterPairStatusNotProvided\n\t\tc.recorder.Event(clusterPair,\n\t\t\tv1.EventTypeNormal,\n\t\t\tstring(clusterPair.Status.StorageStatus),\n\t\t\t\"Skipping storage pairing since no storage options provided\")\n\t\terr := c.client.Update(context.TODO(), clusterPair)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif clusterPair.Status.StorageStatus != stork_api.ClusterPairStatusReady {\n\t\t\tremoteID, err := c.volDriver.CreatePair(clusterPair)\n\t\t\tif err != nil {\n\t\t\t\tclusterPair.Status.StorageStatus = stork_api.ClusterPairStatusError\n\t\t\t\tc.recorder.Event(clusterPair,\n\t\t\t\t\tv1.EventTypeWarning,\n\t\t\t\t\tstring(clusterPair.Status.StorageStatus),\n\t\t\t\t\terr.Error())\n\t\t\t} else {\n\t\t\t\tclusterPair.Status.StorageStatus = stork_api.ClusterPairStatusReady\n\t\t\t\tc.recorder.Event(clusterPair,\n\t\t\t\t\tv1.EventTypeNormal,\n\t\t\t\t\tstring(clusterPair.Status.StorageStatus),\n\t\t\t\t\t\"Storage successfully paired\")\n\t\t\t\tclusterPair.Status.RemoteStorageID = remoteID\n\t\t\t}\n\t\t\terr = c.client.Update(context.TODO(), clusterPair)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tif clusterPair.Status.SchedulerStatus != stork_api.ClusterPairStatusReady {\n\t\tclusterPair.Status.SchedulerStatus = stork_api.ClusterPairStatusError\n\t\tremoteConfig, err := getClusterPairSchedulerConfig(clusterPair.Name, clusterPair.Namespace)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tclient, err := kubernetes.NewForConfig(remoteConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err = client.ServerVersion(); err != nil {\n\t\t\tc.recorder.Event(clusterPair,\n\t\t\t\tv1.EventTypeWarning,\n\t\t\t\tstring(clusterPair.Status.SchedulerStatus),\n\t\t\t\terr.Error())\n\t\t\treturn c.client.Update(context.TODO(), clusterPair)\n\t\t}\n\t\tif err := c.createBackupLocationOnRemote(remoteConfig, clusterPair); err != nil {\n\t\t\tc.recorder.Event(clusterPair,\n\t\t\t\tv1.EventTypeWarning,\n\t\t\t\tstring(clusterPair.Status.SchedulerStatus),\n\t\t\t\terr.Error())\n\t\t\treturn c.client.Update(context.TODO(), clusterPair)\n\t\t}\n\t\tclusterPair.Status.SchedulerStatus = stork_api.ClusterPairStatusReady\n\t\tc.recorder.Event(clusterPair,\n\t\t\tv1.EventTypeNormal,\n\t\t\tstring(clusterPair.Status.SchedulerStatus),\n\t\t\t\"Scheduler successfully paired\")\n\n\t\terr = c.client.Update(context.TODO(), clusterPair)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc getClusterPairSchedulerConfig(clusterPairName string, namespace string) (*restclient.Config, error) {\n\tclusterPair, err := storkops.Instance().GetClusterPair(clusterPairName, namespace)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting clusterpair (%v\/%v): %v\", namespace, clusterPairName, err)\n\t}\n\tremoteClientConfig := clientcmd.NewNonInteractiveClientConfig(\n\t\tclusterPair.Spec.Config,\n\t\tclusterPair.Spec.Config.CurrentContext,\n\t\t&clientcmd.ConfigOverrides{},\n\t\tclientcmd.NewDefaultClientConfigLoadingRules())\n\treturn remoteClientConfig.ClientConfig()\n}\n\nfunc getClusterPairStorageStatus(clusterPairName string, namespace string) (stork_api.ClusterPairStatusType, error) {\n\tclusterPair, err := storkops.Instance().GetClusterPair(clusterPairName, namespace)\n\tif err != nil {\n\t\treturn stork_api.ClusterPairStatusInitial, fmt.Errorf(\"error getting clusterpair %v (%v): %v\", clusterPairName, namespace, err)\n\t}\n\treturn clusterPair.Status.StorageStatus, nil\n}\n\nfunc getClusterPairSchedulerStatus(clusterPairName string, namespace string) (stork_api.ClusterPairStatusType, error) {\n\tclusterPair, err := storkops.Instance().GetClusterPair(clusterPairName, namespace)\n\tif err != nil {\n\t\treturn stork_api.ClusterPairStatusInitial, fmt.Errorf(\"error getting clusterpair: %v\", err)\n\t}\n\treturn clusterPair.Status.SchedulerStatus, nil\n}\n\nfunc (c *ClusterPairController) cleanup(clusterPair *stork_api.ClusterPair) error {\n\tskipDelete := false\n\tif clusterPair.Status.RemoteStorageID != \"\" {\n\t\t\/\/ verify if any other cluster pair using the same RemoteStorageID\n\t\tcpList, err := storkops.Instance().ListClusterPairs(\"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, cp := range cpList.Items {\n\t\t\t\/\/ No need to handle current reconciled clusterpair\n\t\t\t\/\/ Since clusterPair will have deleteTimeStamp set and will be ignored\n\t\t\tif cp.Status.RemoteStorageID == clusterPair.Status.RemoteStorageID &&\n\t\t\t\tcp.DeletionTimestamp == nil {\n\t\t\t\tskipDelete = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif !skipDelete {\n\t\treturn c.volDriver.DeletePair(clusterPair)\n\t}\n\treturn nil\n}\n\nfunc (c *ClusterPairController) createCRD() error {\n\tresource := apiextensions.CustomResource{\n\t\tName:    stork_api.ClusterPairResourceName,\n\t\tPlural:  stork_api.ClusterPairResourcePlural,\n\t\tGroup:   stork_api.SchemeGroupVersion.Group,\n\t\tVersion: stork_api.SchemeGroupVersion.Version,\n\t\tScope:   apiextensionsv1beta1.NamespaceScoped,\n\t\tKind:    reflect.TypeOf(stork_api.ClusterPair{}).Name(),\n\t}\n\tok, err := version.RequiresV1Registration()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ok {\n\t\terr := k8sutils.CreateCRD(resource)\n\t\tif err != nil && !errors.IsAlreadyExists(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn apiextensions.Instance().ValidateCRD(resource.Plural+\".\"+resource.Group, validateCRDTimeout, validateCRDInterval)\n\t}\n\terr = apiextensions.Instance().CreateCRDV1beta1(resource)\n\tif err != nil && !errors.IsAlreadyExists(err) {\n\t\treturn err\n\t}\n\treturn apiextensions.Instance().ValidateCRDV1beta1(resource, validateCRDTimeout, validateCRDInterval)\n}\n\nfunc (c *ClusterPairController) createBackupLocationOnRemote(remoteConfig *restclient.Config, clusterPair *stork_api.ClusterPair) error {\n\tif bkpl, ok := clusterPair.Spec.Options[stork_api.BackupLocationResourceName]; ok {\n\t\tremoteClient, err := storkops.NewForConfig(remoteConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclient, err := kubernetes.NewForConfig(remoteConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tns, err := core.Instance().GetNamespace(clusterPair.Namespace)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Don't create if the namespace already exists on the remote cluster\n\t\t_, err = client.CoreV1().Namespaces().Get(context.TODO(), clusterPair.Namespace, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\t\/\/ create namespace on destination cluster\n\t\t\t_, err = client.CoreV1().Namespaces().Create(context.TODO(), &v1.Namespace{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName:        ns.Name,\n\t\t\t\t\tLabels:      ns.Labels,\n\t\t\t\t\tAnnotations: ns.Annotations,\n\t\t\t\t},\n\t\t\t}, metav1.CreateOptions{})\n\t\t\tif err != nil && !errors.IsAlreadyExists(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\t\/\/ create backuplocation on destination cluster\n\t\tresp, err := storkops.Instance().GetBackupLocation(bkpl, clusterPair.GetNamespace())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp.ResourceVersion = \"\"\n\t\tif _, err := remoteClient.CreateBackupLocation(resp); err != nil && !errors.IsAlreadyExists(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Check empty RemotepairID before deleting clusterpair<commit_after>package controllers\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"time\"\n\n\t\"github.com\/libopenstorage\/stork\/drivers\/volume\"\n\tstork_api \"github.com\/libopenstorage\/stork\/pkg\/apis\/stork\/v1alpha1\"\n\t\"github.com\/libopenstorage\/stork\/pkg\/controllers\"\n\t\"github.com\/libopenstorage\/stork\/pkg\/k8sutils\"\n\t\"github.com\/libopenstorage\/stork\/pkg\/version\"\n\t\"github.com\/portworx\/sched-ops\/k8s\/apiextensions\"\n\t\"github.com\/portworx\/sched-ops\/k8s\/core\"\n\tstorkops \"github.com\/portworx\/sched-ops\/k8s\/stork\"\n\t\"github.com\/sirupsen\/logrus\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tapiextensionsv1beta1 \"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\/v1beta1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\trestclient \"k8s.io\/client-go\/rest\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n\t\"k8s.io\/client-go\/tools\/record\"\n\truntimeclient \"sigs.k8s.io\/controller-runtime\/pkg\/client\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/manager\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/reconcile\"\n)\n\nconst (\n\tvalidateCRDInterval time.Duration = 5 * time.Second\n\tvalidateCRDTimeout  time.Duration = 1 * time.Minute\n)\n\n\/\/ NewClusterPair creates a new instance of ClusterPairController.\nfunc NewClusterPair(mgr manager.Manager, d volume.Driver, r record.EventRecorder) *ClusterPairController {\n\treturn &ClusterPairController{\n\t\tclient:    mgr.GetClient(),\n\t\tvolDriver: d,\n\t\trecorder:  r,\n\t}\n}\n\n\/\/ ClusterPairController controller to watch over ClusterPair\ntype ClusterPairController struct {\n\tclient runtimeclient.Client\n\n\tvolDriver volume.Driver\n\trecorder  record.EventRecorder\n}\n\n\/\/ Init initialize the cluster pair controller\nfunc (c *ClusterPairController) Init(mgr manager.Manager) error {\n\terr := c.createCRD()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn controllers.RegisterTo(mgr, \"cluster-pair-controller\", c, &stork_api.ClusterPair{})\n}\n\n\/\/ Reconcile manages ClusterPair resources.\nfunc (c *ClusterPairController) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {\n\tlogrus.Tracef(\"Reconciling ClusterPair %s\/%s\", request.Namespace, request.Name)\n\n\t\/\/ Fetch the ApplicationBackup instance\n\tbackup := &stork_api.ClusterPair{}\n\terr := c.client.Get(context.TODO(), request.NamespacedName, backup)\n\tif err != nil {\n\t\tif errors.IsNotFound(err) {\n\t\t\t\/\/ Request object not found, could have been deleted after reconcile request.\n\t\t\t\/\/ Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.\n\t\t\t\/\/ Return and don't requeue\n\t\t\treturn reconcile.Result{}, nil\n\t\t}\n\t\t\/\/ Error reading the object - requeue the request.\n\t\treturn reconcile.Result{RequeueAfter: controllers.DefaultRequeueError}, err\n\t}\n\n\tif !controllers.ContainsFinalizer(backup, controllers.FinalizerCleanup) {\n\t\tcontrollers.SetFinalizer(backup, controllers.FinalizerCleanup)\n\t\treturn reconcile.Result{Requeue: true}, c.client.Update(context.TODO(), backup)\n\t}\n\n\tif err = c.handle(context.TODO(), backup); err != nil {\n\t\tlogrus.Errorf(\"%s: %s\/%s: %s\", reflect.TypeOf(c), backup.Namespace, backup.Name, err)\n\t\treturn reconcile.Result{RequeueAfter: controllers.DefaultRequeueError}, err\n\t}\n\n\treturn reconcile.Result{RequeueAfter: controllers.DefaultRequeue}, nil\n}\n\nfunc (c *ClusterPairController) handle(ctx context.Context, clusterPair *stork_api.ClusterPair) error {\n\tif clusterPair.DeletionTimestamp != nil {\n\t\tif controllers.ContainsFinalizer(clusterPair, controllers.FinalizerCleanup) {\n\t\t\tif err := c.cleanup(clusterPair); err != nil {\n\t\t\t\tlogrus.Errorf(\"%s: %s\", reflect.TypeOf(c), err)\n\t\t\t\tc.recorder.Event(\n\t\t\t\t\tclusterPair,\n\t\t\t\t\tv1.EventTypeWarning,\n\t\t\t\t\tstring(stork_api.ClusterPairStatusDeleting),\n\t\t\t\t\tfmt.Sprintf(\"Cluster Pair delete failed: %v\", err.Error()),\n\t\t\t\t)\n\t\t\t\t\/\/ Do not delete the cluster pair CR\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\tif clusterPair.GetFinalizers() != nil {\n\t\t\tcontrollers.RemoveFinalizer(clusterPair, controllers.FinalizerCleanup)\n\t\t\treturn c.client.Update(ctx, clusterPair)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif _, ok := clusterPair.Spec.Options[\"token\"]; !ok {\n\t\tclusterPair.Status.StorageStatus = stork_api.ClusterPairStatusNotProvided\n\t\tc.recorder.Event(clusterPair,\n\t\t\tv1.EventTypeNormal,\n\t\t\tstring(clusterPair.Status.StorageStatus),\n\t\t\t\"Skipping storage pairing since no storage options provided\")\n\t\terr := c.client.Update(context.TODO(), clusterPair)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif clusterPair.Status.StorageStatus != stork_api.ClusterPairStatusReady {\n\t\t\tremoteID, err := c.volDriver.CreatePair(clusterPair)\n\t\t\tif err != nil {\n\t\t\t\tclusterPair.Status.StorageStatus = stork_api.ClusterPairStatusError\n\t\t\t\tc.recorder.Event(clusterPair,\n\t\t\t\t\tv1.EventTypeWarning,\n\t\t\t\t\tstring(clusterPair.Status.StorageStatus),\n\t\t\t\t\terr.Error())\n\t\t\t} else {\n\t\t\t\tclusterPair.Status.StorageStatus = stork_api.ClusterPairStatusReady\n\t\t\t\tc.recorder.Event(clusterPair,\n\t\t\t\t\tv1.EventTypeNormal,\n\t\t\t\t\tstring(clusterPair.Status.StorageStatus),\n\t\t\t\t\t\"Storage successfully paired\")\n\t\t\t\tclusterPair.Status.RemoteStorageID = remoteID\n\t\t\t}\n\t\t\terr = c.client.Update(context.TODO(), clusterPair)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tif clusterPair.Status.SchedulerStatus != stork_api.ClusterPairStatusReady {\n\t\tclusterPair.Status.SchedulerStatus = stork_api.ClusterPairStatusError\n\t\tremoteConfig, err := getClusterPairSchedulerConfig(clusterPair.Name, clusterPair.Namespace)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tclient, err := kubernetes.NewForConfig(remoteConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err = client.ServerVersion(); err != nil {\n\t\t\tc.recorder.Event(clusterPair,\n\t\t\t\tv1.EventTypeWarning,\n\t\t\t\tstring(clusterPair.Status.SchedulerStatus),\n\t\t\t\terr.Error())\n\t\t\treturn c.client.Update(context.TODO(), clusterPair)\n\t\t}\n\t\tif err := c.createBackupLocationOnRemote(remoteConfig, clusterPair); err != nil {\n\t\t\tc.recorder.Event(clusterPair,\n\t\t\t\tv1.EventTypeWarning,\n\t\t\t\tstring(clusterPair.Status.SchedulerStatus),\n\t\t\t\terr.Error())\n\t\t\treturn c.client.Update(context.TODO(), clusterPair)\n\t\t}\n\t\tclusterPair.Status.SchedulerStatus = stork_api.ClusterPairStatusReady\n\t\tc.recorder.Event(clusterPair,\n\t\t\tv1.EventTypeNormal,\n\t\t\tstring(clusterPair.Status.SchedulerStatus),\n\t\t\t\"Scheduler successfully paired\")\n\n\t\terr = c.client.Update(context.TODO(), clusterPair)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc getClusterPairSchedulerConfig(clusterPairName string, namespace string) (*restclient.Config, error) {\n\tclusterPair, err := storkops.Instance().GetClusterPair(clusterPairName, namespace)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error getting clusterpair (%v\/%v): %v\", namespace, clusterPairName, err)\n\t}\n\tremoteClientConfig := clientcmd.NewNonInteractiveClientConfig(\n\t\tclusterPair.Spec.Config,\n\t\tclusterPair.Spec.Config.CurrentContext,\n\t\t&clientcmd.ConfigOverrides{},\n\t\tclientcmd.NewDefaultClientConfigLoadingRules())\n\treturn remoteClientConfig.ClientConfig()\n}\n\nfunc getClusterPairStorageStatus(clusterPairName string, namespace string) (stork_api.ClusterPairStatusType, error) {\n\tclusterPair, err := storkops.Instance().GetClusterPair(clusterPairName, namespace)\n\tif err != nil {\n\t\treturn stork_api.ClusterPairStatusInitial, fmt.Errorf(\"error getting clusterpair %v (%v): %v\", clusterPairName, namespace, err)\n\t}\n\treturn clusterPair.Status.StorageStatus, nil\n}\n\nfunc getClusterPairSchedulerStatus(clusterPairName string, namespace string) (stork_api.ClusterPairStatusType, error) {\n\tclusterPair, err := storkops.Instance().GetClusterPair(clusterPairName, namespace)\n\tif err != nil {\n\t\treturn stork_api.ClusterPairStatusInitial, fmt.Errorf(\"error getting clusterpair: %v\", err)\n\t}\n\treturn clusterPair.Status.SchedulerStatus, nil\n}\n\nfunc (c *ClusterPairController) cleanup(clusterPair *stork_api.ClusterPair) error {\n\tskipDelete := false\n\tif clusterPair.Status.RemoteStorageID != \"\" {\n\t\t\/\/ verify if any other cluster pair using the same RemoteStorageID\n\t\tcpList, err := storkops.Instance().ListClusterPairs(\"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, cp := range cpList.Items {\n\t\t\t\/\/ No need to handle current reconciled clusterpair\n\t\t\t\/\/ Since clusterPair will have deleteTimeStamp set and will be ignored\n\t\t\tif cp.Status.RemoteStorageID == clusterPair.Status.RemoteStorageID &&\n\t\t\t\tcp.DeletionTimestamp == nil {\n\t\t\t\tskipDelete = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif !skipDelete && clusterPair.Status.RemoteStorageID != \"\" {\n\t\treturn c.volDriver.DeletePair(clusterPair)\n\t}\n\treturn nil\n}\n\nfunc (c *ClusterPairController) createCRD() error {\n\tresource := apiextensions.CustomResource{\n\t\tName:    stork_api.ClusterPairResourceName,\n\t\tPlural:  stork_api.ClusterPairResourcePlural,\n\t\tGroup:   stork_api.SchemeGroupVersion.Group,\n\t\tVersion: stork_api.SchemeGroupVersion.Version,\n\t\tScope:   apiextensionsv1beta1.NamespaceScoped,\n\t\tKind:    reflect.TypeOf(stork_api.ClusterPair{}).Name(),\n\t}\n\tok, err := version.RequiresV1Registration()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ok {\n\t\terr := k8sutils.CreateCRD(resource)\n\t\tif err != nil && !errors.IsAlreadyExists(err) {\n\t\t\treturn err\n\t\t}\n\t\treturn apiextensions.Instance().ValidateCRD(resource.Plural+\".\"+resource.Group, validateCRDTimeout, validateCRDInterval)\n\t}\n\terr = apiextensions.Instance().CreateCRDV1beta1(resource)\n\tif err != nil && !errors.IsAlreadyExists(err) {\n\t\treturn err\n\t}\n\treturn apiextensions.Instance().ValidateCRDV1beta1(resource, validateCRDTimeout, validateCRDInterval)\n}\n\nfunc (c *ClusterPairController) createBackupLocationOnRemote(remoteConfig *restclient.Config, clusterPair *stork_api.ClusterPair) error {\n\tif bkpl, ok := clusterPair.Spec.Options[stork_api.BackupLocationResourceName]; ok {\n\t\tremoteClient, err := storkops.NewForConfig(remoteConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tclient, err := kubernetes.NewForConfig(remoteConfig)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tns, err := core.Instance().GetNamespace(clusterPair.Namespace)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Don't create if the namespace already exists on the remote cluster\n\t\t_, err = client.CoreV1().Namespaces().Get(context.TODO(), clusterPair.Namespace, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\t\/\/ create namespace on destination cluster\n\t\t\t_, err = client.CoreV1().Namespaces().Create(context.TODO(), &v1.Namespace{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName:        ns.Name,\n\t\t\t\t\tLabels:      ns.Labels,\n\t\t\t\t\tAnnotations: ns.Annotations,\n\t\t\t\t},\n\t\t\t}, metav1.CreateOptions{})\n\t\t\tif err != nil && !errors.IsAlreadyExists(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\t\/\/ create backuplocation on destination cluster\n\t\tresp, err := storkops.Instance().GetBackupLocation(bkpl, clusterPair.GetNamespace())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tresp.ResourceVersion = \"\"\n\t\tif _, err := remoteClient.CreateBackupLocation(resp); err != nil && !errors.IsAlreadyExists(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2014 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage json\n\nimport \"testing\"\n\nfunc TestSimpleMetaFactoryInterpret(t *testing.T) {\n\tfactory := SimpleMetaFactory{}\n\tgvk, err := factory.Interpret([]byte(`{\"apiVersion\":\"1\",\"kind\":\"object\"}`))\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif gvk.Version != \"1\" || gvk.Kind != \"object\" {\n\t\tt.Errorf(\"unexpected interpret: %#v\", gvk)\n\t}\n\n\t\/\/ no kind or version\n\tgvk, err = factory.Interpret([]byte(`{}`))\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif gvk.Version != \"\" || gvk.Kind != \"\" {\n\t\tt.Errorf(\"unexpected interpret: %#v\", gvk)\n\t}\n\n\t\/\/ unparsable\n\tgvk, err = factory.Interpret([]byte(`{`))\n\tif err == nil {\n\t\tt.Errorf(\"unexpected non-error\")\n\t}\n}\n<commit_msg>Fix staticcheck failures for vendor\/k8s.io\/apimachinery\/pkg\/runtime<commit_after>\/*\nCopyright 2014 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage json\n\nimport \"testing\"\n\nfunc TestSimpleMetaFactoryInterpret(t *testing.T) {\n\tfactory := SimpleMetaFactory{}\n\tgvk, err := factory.Interpret([]byte(`{\"apiVersion\":\"1\",\"kind\":\"object\"}`))\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif gvk.Version != \"1\" || gvk.Kind != \"object\" {\n\t\tt.Errorf(\"unexpected interpret: %#v\", gvk)\n\t}\n\n\t\/\/ no kind or version\n\tgvk, err = factory.Interpret([]byte(`{}`))\n\tif err != nil {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n\tif gvk.Version != \"\" || gvk.Kind != \"\" {\n\t\tt.Errorf(\"unexpected interpret: %#v\", gvk)\n\t}\n\n\t\/\/ unparsable\n\t_, err = factory.Interpret([]byte(`{`))\n\tif err == nil {\n\t\tt.Errorf(\"unexpected non-error\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright IBM Corp. All Rights Reserved.\n\nSPDX-License-Identifier: Apache-2.0\n*\/\n\npackage metadata_test\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"testing\"\n\n\tcommon \"github.com\/hyperledger\/fabric\/common\/metadata\"\n\t\"github.com\/hyperledger\/fabric\/orderer\/common\/metadata\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestGetVersionInfo(t *testing.T) {\n\texpected := fmt.Sprintf(\"%s:\\n Version: %s\\n Go version: %s\\n OS\/Arch: %s\",\n\t\tmetadata.ProgramName, common.Version, runtime.Version(),\n\t\tfmt.Sprintf(\"%s\/%s\", runtime.GOOS, runtime.GOARCH))\n\tassert.Equal(t, expected, metadata.GetVersionInfo())\n}\n<commit_msg>[FAB-5446] Fix orderer metadata local test<commit_after>\/*\nCopyright IBM Corp. All Rights Reserved.\n\nSPDX-License-Identifier: Apache-2.0\n*\/\n\npackage metadata_test\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"testing\"\n\n\tcommon \"github.com\/hyperledger\/fabric\/common\/metadata\"\n\t\"github.com\/hyperledger\/fabric\/orderer\/common\/metadata\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestGetVersionInfo(t *testing.T) {\n\t\/\/ This test would always fail for development versions because if\n\t\/\/ common.Version is not set, the string returned is \"development version\"\n\t\/\/ Set it here for this test to avoid this.\n\tif common.Version == \"\" {\n\t\tcommon.Version = \"testVersion\"\n\t}\n\n\texpected := fmt.Sprintf(\"%s:\\n Version: %s\\n Go version: %s\\n OS\/Arch: %s\",\n\t\tmetadata.ProgramName, common.Version, runtime.Version(),\n\t\tfmt.Sprintf(\"%s\/%s\", runtime.GOOS, runtime.GOARCH))\n\tassert.Equal(t, expected, metadata.GetVersionInfo())\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/koding\/bongo\"\n)\n\n\/\/ NotificationActivity stores each user NotificationActivity related to notification content.\n\/\/ When a user makes duplicate NotificationActivity for the same content\n\/\/ old one is set as obsolete and new one is added to NotificationActivity table\ntype NotificationActivity struct {\n\t\/\/ unique identifier of NotificationActivity\n\tId int64 `json:\"id\"`\n\n\t\/\/ notification content foreign key\n\tNotificationContentId int64 `json:\"notificationContentId\" sql:\"NOT NULL\"`\n\n\t\/\/ message foreign key\n\tMessageId int64 `json:\"messageId,string\"`\n\n\t\/\/ notifier account foreign key\n\tActorId int64 `json:\"actorId,string\" sql:\"NOT NULL\"`\n\n\t\/\/ activity creation time\n\tCreatedAt time.Time `json:\"createdAt\" sql:\"NOT NULL\"`\n\n\t\/\/ activity obsolete information\n\tObsolete bool `json:\"obsolete\" sql:\"NOT NULL\"`\n}\n\n\/\/ Create method creates a new activity with obsolete field set as false\n\/\/ If there already exists one activity with same ActorId and\n\/\/ NotificationContentId pair, old one is set as obsolete, and\n\/\/ new one is created\nfunc (a *NotificationActivity) Create() error {\n\ts := map[string]interface{}{\n\t\t\"notification_content_id\": a.NotificationContentId,\n\t\t\"actor_id\":                a.ActorId,\n\t\t\/\/ \"message_id\":              a.MessageId,\n\t\t\"obsolete\": false,\n\t}\n\n\tq := bongo.NewQS(s)\n\tfound := true\n\tif err := a.One(q); err != nil {\n\t\tif err != bongo.RecordNotFound {\n\t\t\treturn err\n\t\t}\n\t\tfound = false\n\t}\n\n\tif found {\n\t\tif err := bongo.B.Update(a); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ta.Id = 0\n\t\ta.Obsolete = false\n\t}\n\n\treturn bongo.B.Create(a)\n}\n\nfunc (a *NotificationActivity) FetchByContentIds(ids []int64) ([]NotificationActivity, error) {\n\tactivities := make([]NotificationActivity, 0)\n\terr := bongo.B.DB.Table(a.BongoName()).\n\t\tWhere(\"notification_content_id IN (?)\", ids).\n\t\tOrder(\"id asc\").\n\t\tFind(&activities).Error\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn activities, nil\n}\n\nfunc (a *NotificationActivity) FetchMapByContentIds(ids []int64) (map[int64][]NotificationActivity, error) {\n\tif len(ids) == 0 {\n\t\treturn make(map[int64][]NotificationActivity), nil\n\t}\n\taList, err := a.FetchByContentIds(ids)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taMap := make(map[int64][]NotificationActivity)\n\tfor _, activity := range aList {\n\t\taMap[activity.NotificationContentId] = append(aMap[activity.NotificationContentId], activity)\n\t}\n\n\treturn aMap, nil\n}\n\nfunc (a *NotificationActivity) LastActivity() error {\n\ts := map[string]interface{}{\n\t\t\"notification_content_id\": a.NotificationContentId,\n\t\t\"obsolete\":                false,\n\t}\n\n\tq := bongo.NewQS(s)\n\tq.Sort = map[string]string{\n\t\t\"id\": \"DESC\",\n\t}\n\n\treturn a.One(q)\n}\n\nfunc (a *NotificationActivity) FetchContent() (*NotificationContent, error) {\n\tif a.NotificationContentId == 0 {\n\t\treturn nil, fmt.Errorf(\"NotificationContentId is not set\")\n\t}\n\tnc := NewNotificationContent()\n\tif err := nc.ById(a.NotificationContentId); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif a.MessageId != 0 {\n\t\tnc.TargetId = a.MessageId\n\t}\n\n\treturn nc, nil\n}\n<commit_msg>email: fix wrong comment notification email content<commit_after>package models\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/koding\/bongo\"\n)\n\n\/\/ NotificationActivity stores each user NotificationActivity related to notification content.\n\/\/ When a user makes duplicate NotificationActivity for the same content\n\/\/ old one is set as obsolete and new one is added to NotificationActivity table\ntype NotificationActivity struct {\n\t\/\/ unique identifier of NotificationActivity\n\tId int64 `json:\"id\"`\n\n\t\/\/ notification content foreign key\n\tNotificationContentId int64 `json:\"notificationContentId\" sql:\"NOT NULL\"`\n\n\t\/\/ message foreign key\n\tMessageId int64 `json:\"messageId,string\"`\n\n\t\/\/ notifier account foreign key\n\tActorId int64 `json:\"actorId,string\" sql:\"NOT NULL\"`\n\n\t\/\/ activity creation time\n\tCreatedAt time.Time `json:\"createdAt\" sql:\"NOT NULL\"`\n\n\t\/\/ activity obsolete information\n\tObsolete bool `json:\"obsolete\" sql:\"NOT NULL\"`\n}\n\n\/\/ Create method creates a new activity with obsolete field set as false\n\/\/ If there already exists one activity with same ActorId and\n\/\/ NotificationContentId pair, old one is set as obsolete, and\n\/\/ new one is created\nfunc (a *NotificationActivity) Create() error {\n\tactivity := NewNotificationActivity()\n\t*activity = *a\n\ts := map[string]interface{}{\n\t\t\"notification_content_id\": a.NotificationContentId,\n\t\t\"actor_id\":                a.ActorId,\n\t\t\/\/ \"message_id\":              a.MessageId,\n\t\t\"obsolete\": false,\n\t}\n\n\tq := bongo.NewQS(s)\n\tfound := true\n\tif err := activity.One(q); err != nil {\n\t\tif err != bongo.RecordNotFound {\n\t\t\treturn err\n\t\t}\n\t\tfound = false\n\t}\n\n\tif found {\n\t\tif err := bongo.B.Update(activity); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ta.Id = 0\n\t\ta.Obsolete = false\n\t}\n\n\treturn bongo.B.Create(a)\n}\n\nfunc (a *NotificationActivity) FetchByContentIds(ids []int64) ([]NotificationActivity, error) {\n\tactivities := make([]NotificationActivity, 0)\n\terr := bongo.B.DB.Table(a.BongoName()).\n\t\tWhere(\"notification_content_id IN (?)\", ids).\n\t\tOrder(\"id asc\").\n\t\tFind(&activities).Error\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn activities, nil\n}\n\nfunc (a *NotificationActivity) FetchMapByContentIds(ids []int64) (map[int64][]NotificationActivity, error) {\n\tif len(ids) == 0 {\n\t\treturn make(map[int64][]NotificationActivity), nil\n\t}\n\taList, err := a.FetchByContentIds(ids)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taMap := make(map[int64][]NotificationActivity)\n\tfor _, activity := range aList {\n\t\taMap[activity.NotificationContentId] = append(aMap[activity.NotificationContentId], activity)\n\t}\n\n\treturn aMap, nil\n}\n\nfunc (a *NotificationActivity) LastActivity() error {\n\ts := map[string]interface{}{\n\t\t\"notification_content_id\": a.NotificationContentId,\n\t\t\"obsolete\":                false,\n\t}\n\n\tq := bongo.NewQS(s)\n\tq.Sort = map[string]string{\n\t\t\"created_at\": \"DESC\",\n\t}\n\n\treturn a.One(q)\n}\n\nfunc (a *NotificationActivity) FetchContent() (*NotificationContent, error) {\n\tif a.NotificationContentId == 0 {\n\t\treturn nil, fmt.Errorf(\"NotificationContentId is not set\")\n\t}\n\tnc := NewNotificationContent()\n\tif err := nc.ById(a.NotificationContentId); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif a.MessageId != 0 {\n\t\tnc.TargetId = a.MessageId\n\t}\n\n\treturn nc, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package imjasonh\n\n\/\/ TODO: Support other request\/response formats besides JSON (e.g., xml, gob)\n\/\/ TODO: Figure out if PropertyList can support nested objects, or fail if they are detected.\n\/\/ TODO: Add rudimentary single-property queries, pagination, sorting, etc.\n\/\/ TODO: Allow clients to specify the Kind? Namespace datastore by user identity (and maintain user identity)?\n\nimport (\n\t\"appengine\"\n\t\"appengine\/datastore\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\nconst (\n\tkind       = \"JsonObject\"\n\tidKey      = \"_id\"\n\tcreatedKey = \"_created\"\n)\n\nfunc init() {\n\thttp.HandleFunc(\"\/jsonstore\", jsonstore)\n\thttp.HandleFunc(\"\/jsonstore\/\", jsonstore)\n}\n\n\/\/ jsonstore dispatches requests to the relevant API method and arranges certain common state\nfunc jsonstore(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\n\tc := appengine.NewContext(r)\n\tif r.URL.Path == \"\/jsonstore\" {\n\t\tswitch r.Method {\n\t\tcase \"POST\":\n\t\t\tinsert(w, r.Body, c)\n\t\t\treturn\n\t\tcase \"GET\":\n\t\t\tlist(w, c)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tsid := r.URL.Path[len(\"\/jsonstore\/\"):]\n\t\tif path == \"\" {\n\t\t\thttp.Error(w, \"Must specify ID\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tid, err := strconv.ParseInt(sid, 10, 64)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tswitch r.Method {\n\t\tcase \"GET\":\n\t\t\tget(w, id, c)\n\t\t\treturn\n\t\tcase \"DELETE\":\n\t\t\tdelete(w, id, c)\n\t\t\treturn\n\t\tcase \"POST\":\n\t\t\t\/\/ This is strictly \"replace all properties\/values\", not \"add new properties, update existing\"\n\t\t\tupdate(w, id, r.Body, c)\n\t\t\treturn\n\t\t}\n\t}\n\thttp.Error(w, \"Unsupported Method\", http.StatusMethodNotAllowed)\n}\n\nfunc delete(w http.ResponseWriter, id int64, c appengine.Context) {\n\tk := datastore.NewKey(c, kind, \"\", id, nil)\n\tif err := datastore.Delete(c, k); err != nil {\n\t\tif err == datastore.ErrNoSuchEntity {\n\t\t\thttp.Error(w, \"Not Found\", http.StatusNotFound)\n\t\t} else {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n}\n\nfunc get(w http.ResponseWriter, id int64, c appengine.Context) {\n\tk := datastore.NewKey(c, kind, \"\", id, nil)\n\tvar plist datastore.PropertyList\n\tif err := datastore.Get(c, k, &plist); err != nil {\n\t\tif err == datastore.ErrNoSuchEntity {\n\t\t\thttp.Error(w, \"Not Found\", http.StatusNotFound)\n\t\t} else {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\tm := plistToMap(plist, k)\n\tjson.NewEncoder(w).Encode(m)\n}\n\nfunc insert(w http.ResponseWriter, r io.Reader, c appengine.Context) {\n\tvar m map[string]interface{}\n\tif err := json.NewDecoder(r).Decode(&m); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tm[createdKey] = time.Now()\n\n\tplist := mapToPlist(m)\n\n\tk := datastore.NewIncompleteKey(c, kind, nil)\n\tk, err := datastore.Put(c, k, &plist)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tm[idKey] = k.IntID()\n\tjson.NewEncoder(w).Encode(m)\n}\n\n\/\/ plistToMap transforms a PropertyList such as you would get from the datastore into a map[string]interface{} suitable for JSON-encoding.\nfunc plistToMap(plist datastore.PropertyList, k *datastore.Key) map[string]interface{} {\n\tm := make(map[string]interface{})\n\tfor _, p := range plist {\n\t\tif _, exists := m[p.Name]; exists {\n\t\t\tif _, isArr := m[p.Name].([]interface{}); isArr {\n\t\t\t\tm[p.Name] = append(m[p.Name].([]interface{}), p.Value)\n\t\t\t} else {\n\t\t\t\tm[p.Name] = []interface{}{m[p.Name], p.Value}\n\t\t\t}\n\t\t} else {\n\t\t\tm[p.Name] = p.Value\n\t\t}\n\t}\n\tm[idKey] = k.IntID()\n\treturn m\n}\n\n\/\/ mapToPlist transforms a map[string]interface{} such as you would get from decoding JSON into a PropertyList to store in the datastore.\nfunc mapToPlist(m map[string]interface{}) datastore.PropertyList {\n\tplist := make(datastore.PropertyList, 0, len(m))\n\tfor k, v := range m {\n\t\tif _, mult := v.([]interface{}); mult {\n\t\t\tfor _, mv := range v.([]interface{}) {\n\t\t\t\tplist = append(plist, datastore.Property{\n\t\t\t\t\tName:     k,\n\t\t\t\t\tValue:    mv,\n\t\t\t\t\tMultiple: true,\n\t\t\t\t})\n\t\t\t}\n\t\t} else {\n\t\t\tplist = append(plist, datastore.Property{\n\t\t\t\tName:  k,\n\t\t\t\tValue: v,\n\t\t\t})\n\t\t}\n\t}\n\treturn plist\n}\n\nfunc list(w http.ResponseWriter, c appengine.Context) {\n\tlimit := 10\n\tq := datastore.NewQuery(kind).Limit(limit)\n\n\tr := make([]map[string]interface{}, 0, limit)\n\n\tfor t := q.Run(c); ; {\n\t\tvar plist datastore.PropertyList\n\t\tk, err := t.Next(&plist)\n\t\tif err == datastore.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tm := plistToMap(plist, k)\n\t\tr = append(r, m)\n\t}\n\tjson.NewEncoder(w).Encode(r)\n}\n\nfunc update(w http.ResponseWriter, id int64, r io.Reader, c appengine.Context) {\n\tvar m map[string]interface{}\n\tif err := json.NewDecoder(r).Decode(&m); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tplist := mapToPlist(m)\n\n\tk := datastore.NewKey(c, kind, \"\", id, nil)\n\tif _, err := datastore.Put(c, k, &plist); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tm[idKey] = id\n\tjson.NewEncoder(w).Encode(m)\n}\n<commit_msg>Beginnings of support for queries, return nextStartToken in list response<commit_after>package imjasonh\n\n\/\/ TODO: Support other request\/response formats besides JSON (e.g., xml, gob)\n\/\/ TODO: Figure out if PropertyList can support nested objects, or fail if they are detected.\n\/\/ TODO: Add rudimentary single-property queries, pagination, sorting, etc.\n\/\/ TODO: Allow clients to specify the Kind? Namespace datastore by user identity (and maintain user identity)?\n\nimport (\n\t\"appengine\"\n\t\"appengine\/datastore\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\nconst (\n\tkind         = \"JsonObject\"\n\tidKey        = \"_id\"\n\tcreatedKey   = \"_created\"\n\tdefaultLimit = 10\n)\n\nfunc init() {\n\thttp.HandleFunc(\"\/jsonstore\", jsonstore)\n\thttp.HandleFunc(\"\/jsonstore\/\", jsonstore)\n}\n\ntype UserQuery struct {\n\tLimit, Offset                      int\n\tFilterKey, FilterType, FilterValue string\n\tCursor                             string\n}\n\n\/\/ jsonstore dispatches requests to the relevant API method and arranges certain common state\nfunc jsonstore(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Access-Control-Allow-Origin\", \"*\")\n\n\tc := appengine.NewContext(r)\n\tif r.URL.Path == \"\/jsonstore\" {\n\t\tswitch r.Method {\n\t\tcase \"POST\":\n\t\t\tinsert(w, r.Body, c)\n\t\t\treturn\n\t\tcase \"GET\":\n\t\t\t\/\/ TODO: Parse user request into UserQuery and pass to list method\n\t\t\tlist(w, UserQuery{}, c)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tsid := r.URL.Path[len(\"\/jsonstore\/\"):]\n\t\tif path == \"\" {\n\t\t\thttp.Error(w, \"Must specify ID\", http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tid, err := strconv.ParseInt(sid, 10, 64)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\tswitch r.Method {\n\t\tcase \"GET\":\n\t\t\tget(w, id, c)\n\t\t\treturn\n\t\tcase \"DELETE\":\n\t\t\tdelete(w, id, c)\n\t\t\treturn\n\t\tcase \"POST\":\n\t\t\t\/\/ This is strictly \"replace all properties\/values\", not \"add new properties, update existing\"\n\t\t\tupdate(w, id, r.Body, c)\n\t\t\treturn\n\t\t}\n\t}\n\thttp.Error(w, \"Unsupported Method\", http.StatusMethodNotAllowed)\n}\n\nfunc delete(w http.ResponseWriter, id int64, c appengine.Context) {\n\tk := datastore.NewKey(c, kind, \"\", id, nil)\n\tif err := datastore.Delete(c, k); err != nil {\n\t\tif err == datastore.ErrNoSuchEntity {\n\t\t\thttp.Error(w, \"Not Found\", http.StatusNotFound)\n\t\t} else {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n}\n\nfunc get(w http.ResponseWriter, id int64, c appengine.Context) {\n\tk := datastore.NewKey(c, kind, \"\", id, nil)\n\tvar plist datastore.PropertyList\n\tif err := datastore.Get(c, k, &plist); err != nil {\n\t\tif err == datastore.ErrNoSuchEntity {\n\t\t\thttp.Error(w, \"Not Found\", http.StatusNotFound)\n\t\t} else {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\treturn\n\t}\n\tm := plistToMap(plist, k)\n\tjson.NewEncoder(w).Encode(m)\n}\n\nfunc insert(w http.ResponseWriter, r io.Reader, c appengine.Context) {\n\tvar m map[string]interface{}\n\tif err := json.NewDecoder(r).Decode(&m); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tm[createdKey] = time.Now()\n\n\tplist := mapToPlist(m)\n\n\tk := datastore.NewIncompleteKey(c, kind, nil)\n\tk, err := datastore.Put(c, k, &plist)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tm[idKey] = k.IntID()\n\tjson.NewEncoder(w).Encode(m)\n}\n\n\/\/ plistToMap transforms a PropertyList such as you would get from the datastore into a map[string]interface{} suitable for JSON-encoding.\nfunc plistToMap(plist datastore.PropertyList, k *datastore.Key) map[string]interface{} {\n\tm := make(map[string]interface{})\n\tfor _, p := range plist {\n\t\tif _, exists := m[p.Name]; exists {\n\t\t\tif _, isArr := m[p.Name].([]interface{}); isArr {\n\t\t\t\tm[p.Name] = append(m[p.Name].([]interface{}), p.Value)\n\t\t\t} else {\n\t\t\t\tm[p.Name] = []interface{}{m[p.Name], p.Value}\n\t\t\t}\n\t\t} else {\n\t\t\tm[p.Name] = p.Value\n\t\t}\n\t}\n\tm[idKey] = k.IntID()\n\treturn m\n}\n\n\/\/ mapToPlist transforms a map[string]interface{} such as you would get from decoding JSON into a PropertyList to store in the datastore.\nfunc mapToPlist(m map[string]interface{}) datastore.PropertyList {\n\tplist := make(datastore.PropertyList, 0, len(m))\n\tfor k, v := range m {\n\t\tif _, mult := v.([]interface{}); mult {\n\t\t\tfor _, mv := range v.([]interface{}) {\n\t\t\t\tplist = append(plist, datastore.Property{\n\t\t\t\t\tName:     k,\n\t\t\t\t\tValue:    mv,\n\t\t\t\t\tMultiple: true,\n\t\t\t\t})\n\t\t\t}\n\t\t} else {\n\t\t\tplist = append(plist, datastore.Property{\n\t\t\t\tName:  k,\n\t\t\t\tValue: v,\n\t\t\t})\n\t\t}\n\t}\n\treturn plist\n}\n\nfunc list(w http.ResponseWriter, uq UserQuery, c appengine.Context) {\n\tlimit := 3\n\tq := datastore.NewQuery(kind).Limit(limit)\n\n\titems := make([]map[string]interface{}, 0, limit)\n\n\tvar crs datastore.Cursor\n\tfor t := q.Run(c); ; {\n\t\tvar plist datastore.PropertyList\n\t\tk, err := t.Next(&plist)\n\t\tif err == datastore.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tm := plistToMap(plist, k)\n\t\titems = append(items, m)\n\t\tif crs, err = t.Cursor(); err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t}\n\tr := map[string]interface{}{\n\t\t\"items\":          items,\n\t\t\"nextStartToken\": crs.String(),\n\t}\n\tjson.NewEncoder(w).Encode(r)\n}\n\nfunc update(w http.ResponseWriter, id int64, r io.Reader, c appengine.Context) {\n\tvar m map[string]interface{}\n\tif err := json.NewDecoder(r).Decode(&m); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tplist := mapToPlist(m)\n\n\tk := datastore.NewKey(c, kind, \"\", id, nil)\n\tif _, err := datastore.Put(c, k, &plist); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tm[idKey] = id\n\tjson.NewEncoder(w).Encode(m)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The Upspin Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package keyloader loads public and private keys from the user's home directory.\npackage keyloader\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"upspin.io\/errors\"\n\t\"upspin.io\/factotum\"\n\t\"upspin.io\/upspin\"\n)\n\nconst (\n\tkeyloaderErr = \"keyloader: %v\"\n)\n\nvar (\n\terrNoKeysFound = errors.Str(\"no keys found\")\n\terrNilContext  = errors.Str(\"nil context\")\n\tzeroPrivKey    string\n\tzeroPubKey     upspin.PublicKey\n)\n\n\/\/ Load reads a key pair from the user's .ssh directory and loads\n\/\/ them into the context.\nfunc Load(context upspin.Context) error {\n\tif context == nil {\n\t\treturn errors.E(Load, errors.Invalid, errors.Str(\"nil context\"))\n\t}\n\tpub, priv, err := privateKey(\"Load\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar f upspin.Factotum\n\tf, err = factotum.New(pub, priv)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontext.SetFactotum(f)\n\treturn nil\n}\n\n\/\/ publicKey returns the public key of the current user by reading from $HOME\/.ssh\/.\nfunc publicKey(op string) (upspin.PublicKey, error) {\n\tf, err := os.Open(filepath.Join(sshdir(), \"public.upspinkey\"))\n\tif err != nil {\n\t\treturn zeroPubKey, errors.E(op, errors.NotExist, errNoKeysFound)\n\t}\n\tdefer f.Close()\n\tbuf := make([]byte, 400) \/\/ enough for p521\n\tn, err := f.Read(buf)\n\tif err != nil {\n\t\treturn zeroPubKey, errors.Errorf(keyloaderErr, err)\n\t}\n\treturn upspin.PublicKey(string(buf[:n])), nil\n}\n\n\/\/ privateKey returns the private key of the current user by reading from $HOME\/.ssh\/.\nfunc privateKey(op string) (upspin.PublicKey, string, error) {\n\tf, err := os.Open(filepath.Join(sshdir(), \"secret.upspinkey\"))\n\tif err != nil {\n\t\treturn zeroPubKey, zeroPrivKey, errors.E(op, errors.NotExist, errNoKeysFound)\n\t}\n\tdefer f.Close()\n\tbuf := make([]byte, 200) \/\/ enough for p521\n\tn, err := f.Read(buf)\n\tif err != nil {\n\t\treturn zeroPubKey, zeroPrivKey, errors.Errorf(keyloaderErr, err)\n\t}\n\tbuf = bytes.TrimSpace(buf[:n])\n\tpubkey, err := publicKey(op)\n\tif err != nil {\n\t\treturn zeroPubKey, zeroPrivKey, err\n\t}\n\treturn pubkey, string(buf), nil\n\t\/\/ TODO sanity check that Private is consistent with Public\n}\n\nfunc sshdir() string {\n\thome := os.Getenv(\"HOME\")\n\tif len(home) == 0 {\n\t\tpanic(\"no home directory\")\n\t}\n\treturn filepath.Join(home, \".ssh\")\n}\n<commit_msg>key\/keyloader: improve error checking, pass through OS errors<commit_after>\/\/ Copyright 2016 The Upspin Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package keyloader loads public and private keys from the user's home directory.\npackage keyloader\n\nimport (\n\t\"bytes\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"upspin.io\/errors\"\n\t\"upspin.io\/factotum\"\n\t\"upspin.io\/upspin\"\n)\n\nvar (\n\terrNilContext = errors.Str(\"nil context\")\n\tzeroPrivKey   string\n\tzeroPubKey    upspin.PublicKey\n)\n\n\/\/ Load reads a key pair from the user's .ssh directory and loads\n\/\/ them into the context.\nfunc Load(context upspin.Context) error {\n\tif context == nil {\n\t\treturn errors.E(Load, errors.Invalid, errors.Str(\"nil context\"))\n\t}\n\tpub, priv, err := privateKey(\"Load\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar f upspin.Factotum\n\tf, err = factotum.New(pub, priv)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcontext.SetFactotum(f)\n\treturn nil\n}\n\n\/\/ publicKey returns the public key of the current user by reading from $HOME\/.ssh\/.\nfunc publicKey(op string) (upspin.PublicKey, error) {\n\tf, err := os.Open(filepath.Join(sshdir(), \"public.upspinkey\"))\n\tif os.IsNotExist(err) {\n\t\treturn zeroPubKey, errors.E(op, errors.NotExist, err)\n\t}\n\tif err != nil {\n\t\treturn zeroPubKey, errors.E(op, errors.IO, err)\n\t}\n\tdefer f.Close()\n\tbuf := make([]byte, 400) \/\/ enough for p521\n\tn, err := f.Read(buf)\n\tif err != nil {\n\t\treturn zeroPubKey, errors.E(op, errors.IO, err)\n\t}\n\treturn upspin.PublicKey(string(buf[:n])), nil\n}\n\n\/\/ privateKey returns the private key of the current user by reading from $HOME\/.ssh\/.\nfunc privateKey(op string) (upspin.PublicKey, string, error) {\n\tf, err := os.Open(filepath.Join(sshdir(), \"secret.upspinkey\"))\n\tif os.IsNotExist(err) {\n\t\treturn zeroPubKey, zeroPrivKey, errors.E(op, errors.NotExist, err)\n\t}\n\tif err != nil {\n\t\treturn zeroPubKey, zeroPrivKey, errors.E(op, errors.IO, err)\n\t}\n\tdefer f.Close()\n\tbuf := make([]byte, 200) \/\/ enough for p521\n\tn, err := f.Read(buf)\n\tif err != nil {\n\t\treturn zeroPubKey, zeroPrivKey, errors.E(op, errors.IO, err)\n\t}\n\tbuf = bytes.TrimSpace(buf[:n])\n\tpubkey, err := publicKey(op)\n\tif err != nil {\n\t\treturn zeroPubKey, zeroPrivKey, err\n\t}\n\treturn pubkey, string(buf), nil\n\t\/\/ TODO sanity check that Private is consistent with Public\n}\n\nfunc sshdir() string {\n\thome := os.Getenv(\"HOME\")\n\tif len(home) == 0 {\n\t\tpanic(\"no home directory\")\n\t}\n\treturn filepath.Join(home, \".ssh\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package elasticsearch\n\nimport (\n\t\"math\"\n\t\"math\/rand\"\n\t\"time\"\n\n\t\"github.com\/elastic\/libbeat\/logp\"\n)\n\ntype Connection struct {\n\tUrl      string\n\tUsername string\n\tPassword string\n\n\tdead       bool\n\tdead_count int\n\ttimer      *time.Timer\n\ttimeout    time.Duration\n}\n\nconst (\n\tdefault_dead_timeout = 60 \/\/seconds\n)\n\ntype ConnectionPool struct {\n\tConnections []*Connection\n\trr          int \/\/round robin\n\n\t\/\/ options\n\tDead_timeout time.Duration\n}\n\nfunc (pool *ConnectionPool) SetConnections(urls []string, username string, password string) error {\n\n\tvar connections []*Connection\n\n\tfor _, url := range urls {\n\t\tconn := Connection{\n\t\t\tUrl:      url,\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t}\n\t\t\/\/ set default settings\n\t\tconn.dead_count = 0\n\t\tconnections = append(connections, &conn)\n\t}\n\tpool.Connections = connections\n\tpool.rr = -1\n\tpool.Dead_timeout = default_dead_timeout\n\treturn nil\n}\n\nfunc (pool *ConnectionPool) SetDeadTimeout(timeout int) {\n\tpool.Dead_timeout = time.Duration(timeout)\n}\n\nfunc (pool *ConnectionPool) SelectRoundRobin() *Connection {\n\n\tfor count := 0; count < len(pool.Connections); count++ {\n\n\t\tpool.rr += 1\n\t\tpool.rr = pool.rr % len(pool.Connections)\n\t\tconn := pool.Connections[pool.rr]\n\t\tif conn.dead == false {\n\t\t\treturn conn\n\t\t}\n\t}\n\n\t\/\/ no connection is alive, return a random connection\n\tpool.rr = rand.Intn(len(pool.Connections))\n\treturn pool.Connections[pool.rr]\n}\n\nfunc (pool *ConnectionPool) GetConnection() *Connection {\n\n\tif len(pool.Connections) > 1 {\n\t\treturn pool.SelectRoundRobin()\n\t}\n\t\/\/ only one connection, no need to select one connection\n\treturn pool.Connections[0]\n}\n\n\/\/ If a connection fails, it will be marked as dead and put on timeout.\n\/\/ timeout = default_timeout * 2 ** (fail_count - 1)\n\/\/ When the timeout is over, the connection will be resurrected and\n\/\/ returned to the live pool\nfunc (pool *ConnectionPool) MarkDead(conn *Connection) error {\n\n\tlogp.Debug(\"elasticsearch\", \"Mark dead %s\", conn.Url)\n\tconn.dead = true\n\tconn.dead_count = conn.dead_count + 1\n\tconn.timeout = pool.Dead_timeout * time.Duration(math.Pow(2, float64(conn.dead_count)-1))\n\tconn.timer = time.AfterFunc(conn.timeout*time.Second, func() {\n\t\t\/\/ timeout expires\n\t\tconn.dead = false\n\t\tlogp.Debug(\"elasticsearch\", \"Timeout expired. Mark it as alive: %s\", conn.Url)\n\t})\n\n\treturn nil\n}\n\n\/\/ A connection that has been previously marked as dead and succeeds will be marked\n\/\/ as live and the dead_count is set to zero\nfunc (pool *ConnectionPool) MarkLive(conn *Connection) error {\n\tif conn.dead {\n\t\tlogp.Debug(\"elasticsearch\", \"Mark live %s\", conn.Url)\n\t\tconn.dead = false\n\t\tconn.dead_count = 0\n\t\tconn.timer.Stop()\n\t}\n\treturn nil\n}\n<commit_msg>Don't mark a node dead if it is dead already<commit_after>package elasticsearch\n\nimport (\n\t\"math\"\n\t\"math\/rand\"\n\t\"time\"\n\n\t\"github.com\/elastic\/libbeat\/logp\"\n)\n\ntype Connection struct {\n\tUrl      string\n\tUsername string\n\tPassword string\n\n\tdead       bool\n\tdead_count int\n\ttimer      *time.Timer\n}\n\nconst (\n\tdefault_dead_timeout = 60 \/\/seconds\n)\n\ntype ConnectionPool struct {\n\tConnections []*Connection\n\trr          int \/\/round robin\n\n\t\/\/ options\n\tDead_timeout time.Duration\n}\n\nfunc (pool *ConnectionPool) SetConnections(urls []string, username string, password string) error {\n\n\tvar connections []*Connection\n\n\tfor _, url := range urls {\n\t\tconn := Connection{\n\t\t\tUrl:      url,\n\t\t\tUsername: username,\n\t\t\tPassword: password,\n\t\t}\n\t\t\/\/ set default settings\n\t\tconn.dead_count = 0\n\t\tconnections = append(connections, &conn)\n\t}\n\tpool.Connections = connections\n\tpool.rr = -1\n\tpool.Dead_timeout = default_dead_timeout\n\treturn nil\n}\n\nfunc (pool *ConnectionPool) SetDeadTimeout(timeout int) {\n\tpool.Dead_timeout = time.Duration(timeout)\n}\n\nfunc (pool *ConnectionPool) SelectRoundRobin() *Connection {\n\n\tfor count := 0; count < len(pool.Connections); count++ {\n\n\t\tpool.rr += 1\n\t\tpool.rr = pool.rr % len(pool.Connections)\n\t\tconn := pool.Connections[pool.rr]\n\t\tif conn.dead == false {\n\t\t\treturn conn\n\t\t}\n\t}\n\n\t\/\/ no connection is alive, return a random connection\n\tpool.rr = rand.Intn(len(pool.Connections))\n\treturn pool.Connections[pool.rr]\n}\n\nfunc (pool *ConnectionPool) GetConnection() *Connection {\n\n\tif len(pool.Connections) > 1 {\n\t\treturn pool.SelectRoundRobin()\n\t}\n\t\/\/ only one connection, no need to select one connection\n\treturn pool.Connections[0]\n}\n\n\/\/ If a connection fails, it will be marked as dead and put on timeout.\n\/\/ timeout = default_timeout * 2 ** (fail_count - 1)\n\/\/ When the timeout is over, the connection will be resurrected and\n\/\/ returned to the live pool\nfunc (pool *ConnectionPool) MarkDead(conn *Connection) error {\n\n\tif !conn.dead {\n\t\tlogp.Debug(\"elasticsearch\", \"Mark dead %s\", conn.Url)\n\t\tconn.dead = true\n\t\tconn.dead_count = conn.dead_count + 1\n\t\ttimeout := pool.Dead_timeout * time.Duration(math.Pow(2, float64(conn.dead_count)-1))\n\t\tconn.timer = time.AfterFunc(timeout*time.Second, func() {\n\t\t\t\/\/ timeout expires\n\t\t\tconn.dead = false\n\t\t\tlogp.Debug(\"elasticsearch\", \"Timeout expired. Mark it as alive: %s\", conn.Url)\n\t\t})\n\t}\n\n\treturn nil\n}\n\n\/\/ A connection that has been previously marked as dead and succeeds will be marked\n\/\/ as live and the dead_count is set to zero\nfunc (pool *ConnectionPool) MarkLive(conn *Connection) error {\n\tif conn.dead {\n\t\tlogp.Debug(\"elasticsearch\", \"Mark live %s\", conn.Url)\n\t\tconn.dead = false\n\t\tconn.dead_count = 0\n\t\tconn.timer.Stop()\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ functions (not methods) related to AWS go here\n\npackage master\n\nimport (\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/aaronang\/cong-the-ripper\/lib\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ec2\"\n)\n\n\/\/ createSlaves creates a new slave instance.\nfunc createSlaves(svc *ec2.EC2, count int, slavePort, masterIP, masterPort string) ([]*ec2.Instance, error) {\n\tvar script = `#!\/bin\/bash\n\nset -x\n\nsu centos <<'EOF'\nsource ~\/.bashrc\ngo get github.com\/aaronang\/cong-the-ripper\/cmd\/slave\ngo install github.com\/aaronang\/cong-the-ripper\/cmd\/slave\n~\/go\/bin\/slave --port=%v --master-ip=%v --master-port=%v > ~\/console.log 2>&1 &\nEOF\n`\n\tuserData := []byte(fmt.Sprintf(script, slavePort, masterIP, masterPort))\n\tparams := &ec2.RunInstancesInput{\n\t\tImageId:      aws.String(lib.SlaveImage),\n\t\tInstanceType: aws.String(lib.SlaveType),\n\t\tMinCount:     aws.Int64(int64(count)),\n\t\tMaxCount:     aws.Int64(int64(count)),\n\t\tIamInstanceProfile: &ec2.IamInstanceProfileSpecification{\n\t\t\tArn: aws.String(lib.SlaveARN),\n\t\t},\n\t\tKeyName:          aws.String(\"Cong the Ripper\"),\n\t\tSecurityGroupIds: []*string{aws.String(\"sg-646fbb02\")},\n\t\tUserData:         aws.String(base64.StdEncoding.EncodeToString(userData)),\n\t}\n\tresp, err := svc.RunInstances(params)\n\treturn resp.Instances, err\n}\n\nfunc instancesFromIPs(svc *ec2.EC2, ips []string) []*ec2.Instance {\n\tif ips == nil || len(ips) == 0 {\n\t\treturn nil\n\t}\n\n\tawsIPs := make([]*string, len(ips))\n\tfor i := range awsIPs {\n\t\tawsIPs[i] = aws.String(ips[i])\n\t}\n\n\tparams := ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName:   aws.String(\"ip-address\"),\n\t\t\t\tValues: awsIPs,\n\t\t\t},\n\t\t},\n\t}\n\n\tres, err := svc.DescribeInstances(&params)\n\tif err != nil {\n\t\tlog.Println(\"Failed to find instance from its public IP\", err)\n\t\treturn nil\n\t}\n\n\t\/\/ the index should be valid, if not we crash\n\treturn res.Reservations[0].Instances\n}\n\n\/\/ terminateSlaves terminates a slave instance.\nfunc terminateSlaves(svc *ec2.EC2, instances []*ec2.Instance) (*ec2.TerminateInstancesOutput, error) {\n\tparams := &ec2.TerminateInstancesInput{\n\t\tInstanceIds: instanceIds(instances),\n\t}\n\treturn svc.TerminateInstances(params)\n}\n\n\/\/ sendTask sends a task to a slave instance.\nfunc sendTask(t *lib.Task, addr string) (*http.Response, error) {\n\turl := lib.Protocol + addr + lib.TasksCreatePath\n\tbody, err := t.ToJSON()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\treturn http.Post(url, lib.BodyType, bytes.NewBuffer(body))\n}\n\nfunc newEC2() *ec2.EC2 {\n\tsess, err := session.NewSession(&aws.Config{\n\t\tRegion: aws.String(lib.AWSRegion)},\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ec2.New(sess)\n}\n\nfunc instanceIds(instances []*ec2.Instance) []*string {\n\tinstanceIds := make([]*string, len(instances))\n\tfor i, instance := range instances {\n\t\tinstanceIds[i] = instance.InstanceId\n\t}\n\treturn instanceIds\n}\n\nfunc getPublicIP(svc *ec2.EC2, instance *ec2.Instance) *string {\n\tparams := ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName: aws.String(\"instance-state-name\"),\n\t\t\t\tValues: []*string{\n\t\t\t\t\taws.String(\"pending\"),\n\t\t\t\t\taws.String(\"running\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tInstanceIds: []*string{\n\t\t\tinstance.InstanceId,\n\t\t},\n\t}\n\n\tvar i int\n\tfor {\n\t\tres, err := svc.DescribeInstances(&params)\n\n\t\t\/\/ ignore the error because we may try again\n\t\tif err == nil &&\n\t\t\tlen(res.Reservations) == 1 &&\n\t\t\tlen(res.Reservations[0].Instances) == 1 {\n\n\t\t\tif res.Reservations[0].Instances[0].PublicIpAddress != nil {\n\t\t\t\treturn res.Reservations[0].Instances[0].PublicIpAddress\n\t\t\t}\n\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t\ti++\n\t\tif i > 12 {\n\t\t\tlog.Println(\"Unable to find public IP\")\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\nfunc mapToKeys(mymap map[string]slave) []string {\n\tkeys := make([]string, len(mymap))\n\ti := 0\n\tfor k := range mymap {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\treturn keys\n}\n<commit_msg>Add update flag to go get for setting up the slave<commit_after>\/\/ functions (not methods) related to AWS go here\n\npackage master\n\nimport (\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/aaronang\/cong-the-ripper\/lib\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ec2\"\n)\n\n\/\/ createSlaves creates a new slave instance.\nfunc createSlaves(svc *ec2.EC2, count int, slavePort, masterIP, masterPort string) ([]*ec2.Instance, error) {\n\tvar script = `#!\/bin\/bash\n\nset -x\n\nsu centos <<'EOF'\nsource ~\/.bashrc\ngo get -u github.com\/aaronang\/cong-the-ripper\/cmd\/slave\ngo install github.com\/aaronang\/cong-the-ripper\/cmd\/slave\n~\/go\/bin\/slave --port=%v --master-ip=%v --master-port=%v > ~\/console.log 2>&1 &\nEOF\n`\n\tuserData := []byte(fmt.Sprintf(script, slavePort, masterIP, masterPort))\n\tparams := &ec2.RunInstancesInput{\n\t\tImageId:      aws.String(lib.SlaveImage),\n\t\tInstanceType: aws.String(lib.SlaveType),\n\t\tMinCount:     aws.Int64(int64(count)),\n\t\tMaxCount:     aws.Int64(int64(count)),\n\t\tIamInstanceProfile: &ec2.IamInstanceProfileSpecification{\n\t\t\tArn: aws.String(lib.SlaveARN),\n\t\t},\n\t\tKeyName:          aws.String(\"Cong the Ripper\"),\n\t\tSecurityGroupIds: []*string{aws.String(\"sg-646fbb02\")},\n\t\tUserData:         aws.String(base64.StdEncoding.EncodeToString(userData)),\n\t}\n\tresp, err := svc.RunInstances(params)\n\treturn resp.Instances, err\n}\n\nfunc instancesFromIPs(svc *ec2.EC2, ips []string) []*ec2.Instance {\n\tif ips == nil || len(ips) == 0 {\n\t\treturn nil\n\t}\n\n\tawsIPs := make([]*string, len(ips))\n\tfor i := range awsIPs {\n\t\tawsIPs[i] = aws.String(ips[i])\n\t}\n\n\tparams := ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName:   aws.String(\"ip-address\"),\n\t\t\t\tValues: awsIPs,\n\t\t\t},\n\t\t},\n\t}\n\n\tres, err := svc.DescribeInstances(&params)\n\tif err != nil {\n\t\tlog.Println(\"Failed to find instance from its public IP\", err)\n\t\treturn nil\n\t}\n\n\t\/\/ the index should be valid, if not we crash\n\treturn res.Reservations[0].Instances\n}\n\n\/\/ terminateSlaves terminates a slave instance.\nfunc terminateSlaves(svc *ec2.EC2, instances []*ec2.Instance) (*ec2.TerminateInstancesOutput, error) {\n\tparams := &ec2.TerminateInstancesInput{\n\t\tInstanceIds: instanceIds(instances),\n\t}\n\treturn svc.TerminateInstances(params)\n}\n\n\/\/ sendTask sends a task to a slave instance.\nfunc sendTask(t *lib.Task, addr string) (*http.Response, error) {\n\turl := lib.Protocol + addr + lib.TasksCreatePath\n\tbody, err := t.ToJSON()\n\tif err != nil {\n\t\tlog.Panicln(err)\n\t}\n\treturn http.Post(url, lib.BodyType, bytes.NewBuffer(body))\n}\n\nfunc newEC2() *ec2.EC2 {\n\tsess, err := session.NewSession(&aws.Config{\n\t\tRegion: aws.String(lib.AWSRegion)},\n\t)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ec2.New(sess)\n}\n\nfunc instanceIds(instances []*ec2.Instance) []*string {\n\tinstanceIds := make([]*string, len(instances))\n\tfor i, instance := range instances {\n\t\tinstanceIds[i] = instance.InstanceId\n\t}\n\treturn instanceIds\n}\n\nfunc getPublicIP(svc *ec2.EC2, instance *ec2.Instance) *string {\n\tparams := ec2.DescribeInstancesInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName: aws.String(\"instance-state-name\"),\n\t\t\t\tValues: []*string{\n\t\t\t\t\taws.String(\"pending\"),\n\t\t\t\t\taws.String(\"running\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tInstanceIds: []*string{\n\t\t\tinstance.InstanceId,\n\t\t},\n\t}\n\n\tvar i int\n\tfor {\n\t\tres, err := svc.DescribeInstances(&params)\n\n\t\t\/\/ ignore the error because we may try again\n\t\tif err == nil &&\n\t\t\tlen(res.Reservations) == 1 &&\n\t\t\tlen(res.Reservations[0].Instances) == 1 {\n\n\t\t\tif res.Reservations[0].Instances[0].PublicIpAddress != nil {\n\t\t\t\treturn res.Reservations[0].Instances[0].PublicIpAddress\n\t\t\t}\n\n\t\t}\n\t\ttime.Sleep(10 * time.Second)\n\t\ti++\n\t\tif i > 12 {\n\t\t\tlog.Println(\"Unable to find public IP\")\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\nfunc mapToKeys(mymap map[string]slave) []string {\n\tkeys := make([]string, len(mymap))\n\ti := 0\n\tfor k := range mymap {\n\t\tkeys[i] = k\n\t\ti++\n\t}\n\treturn keys\n}\n<|endoftext|>"}
{"text":"<commit_before>package helpers\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\tgot \"html\/template\"\n\t\"io\"\n\t\"strings\"\n\n\tparser \"github.com\/fragmenta\/view\/internal\/html\"\n)\n\n\/\/ NB all HTML with user input must be escaped, see https:\/\/www.owasp.org\/index.php\/XSS_Prevention_Cheatsheet\n\n\/\/ These two should instead be using assets package?\n\n\/\/ Style inserts a css tag\nfunc Style(name string) got.HTML {\n\treturn got.HTML(fmt.Sprintf(\"<link href=\\\"\/assets\/styles\/%s.css\\\" media=\\\"all\\\" rel=\\\"stylesheet\\\" type=\\\"text\/css\\\" \/>\", EscapeURL(name)))\n}\n\n\/\/ Script inserts a script tag\nfunc Script(name string) got.HTML {\n\treturn got.HTML(fmt.Sprintf(\"<script src=\\\"\/assets\/scripts\/%s.js\\\" type=\\\"text\/javascript\\\"><\/script>\", EscapeURL(name)))\n}\n\n\/\/ Escape escapes HTML using HTMLEscapeString\nfunc Escape(s string) string {\n\treturn got.HTMLEscapeString(s)\n}\n\n\/\/ EscapeURL escapes URLs using HTMLEscapeString\nfunc EscapeURL(s string) string {\n\treturn got.URLQueryEscaper(s)\n}\n\n\/\/ Link returns got.HTML with an anchor link given text and URL required\n\/\/ Attributes (if supplied) should not contain user input\nfunc Link(t string, u string, a ...string) got.HTML {\n\tattributes := \"\"\n\tif len(a) > 0 {\n\t\tattributes = strings.Join(a, \" \")\n\t}\n\treturn got.HTML(fmt.Sprintf(\"<a href=\\\"%s\\\" %s>%s<\/a>\", Escape(u), Escape(attributes), Escape(t)))\n}\n\n\/\/ HTML returns a string (which must not contain user input) as go template HTML\nfunc HTML(s string) got.HTML {\n\treturn got.HTML(s)\n}\n\n\/\/ HTMLAttribute returns a string (which must not contain user input) as go template HTMLAttr\nfunc HTMLAttribute(s string) got.HTMLAttr {\n\treturn got.HTMLAttr(s)\n}\n\n\/\/ URL returns returns a string (which must not contain user input) as go template URL\nfunc URL(s string) got.URL {\n\treturn got.URL(s)\n}\n\n\/\/ Strip all html tags and returns as go template HTML\nfunc Strip(s string) got.HTML {\n\treturn Sanitize(s, []string{}, []string{})\n}\n\n\/\/ Sanitize sanitises html, allowing some tags using the html parser from golang.org\/x\/net\/html and returns as go template HTML\n\/\/ Usage: sanitize.HTMLAllowing(\"<b id=id>my html<\/b>\",[]string{\"b\"},[]string{\"id\")\nfunc Sanitize(s string, args ...[]string) got.HTML {\n\n\tvar ignoreTags = []string{\"title\", \"script\", \"style\", \"iframe\", \"frame\", \"frameset\", \"noframes\", \"noembed\", \"embed\", \"applet\", \"object\"}\n\tvar defaultTags = []string{\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\", \"div\", \"span\", \"hr\", \"p\", \"br\", \"b\", \"i\", \"ol\", \"ul\", \"li\", \"strong\", \"em\", \"a\", \"img\"}\n\tvar defaultAttributes = []string{\"id\", \"class\", \"src\", \"title\", \"alt\", \"name\", \"rel\", \"href\"}\n\n\tallowedTags := defaultTags\n\tif len(args) > 0 {\n\t\tallowedTags = args[0]\n\t}\n\tallowedAttributes := defaultAttributes\n\tif len(args) > 1 {\n\t\tallowedAttributes = args[1]\n\t}\n\n\t\/\/ Parse the html\n\ttokenizer := parser.NewTokenizer(strings.NewReader(s))\n\n\tbuffer := bytes.NewBufferString(\"\")\n\tignore := \"\"\n\n\tfor {\n\t\ttokenType := tokenizer.Next()\n\t\ttoken := tokenizer.Token()\n\n\t\tswitch tokenType {\n\n\t\tcase parser.ErrorToken:\n\t\t\terr := tokenizer.Err()\n\t\t\tif err == io.EOF {\n\t\t\t\treturn got.HTML(buffer.String())\n\t\t\t}\n\n\t\t\tfmt.Println(\"Error parsing html\") \/\/ we should perhaps return an error\n\t\t\treturn got.HTML(\"\")\n\n\t\tcase parser.StartTagToken:\n\n\t\t\tif len(ignore) == 0 && includes(allowedTags, token.Data) {\n\t\t\t\ttoken.Attr = cleanAttributes(token.Attr, allowedAttributes)\n\t\t\t\tbuffer.WriteString(token.String())\n\t\t\t} else if includes(ignoreTags, token.Data) {\n\t\t\t\tignore = token.Data\n\t\t\t}\n\n\t\tcase parser.SelfClosingTagToken:\n\n\t\t\tif len(ignore) == 0 && includes(allowedTags, token.Data) {\n\t\t\t\ttoken.Attr = cleanAttributes(token.Attr, allowedAttributes)\n\t\t\t\tbuffer.WriteString(token.String())\n\t\t\t} else if token.Data == ignore {\n\t\t\t\tignore = \"\"\n\t\t\t}\n\n\t\tcase parser.EndTagToken:\n\t\t\tif len(ignore) == 0 && includes(allowedTags, token.Data) {\n\t\t\t\ttoken.Attr = []parser.Attribute{}\n\t\t\t\tbuffer.WriteString(token.String())\n\t\t\t} else if token.Data == ignore {\n\t\t\t\tignore = \"\"\n\t\t\t}\n\n\t\tcase parser.TextToken:\n\t\t\t\/\/ We allow text content through, unless ignoring this entire tag and its contents (including other tags)\n\t\t\tif ignore == \"\" {\n\t\t\t\tbuffer.WriteString(token.String())\n\t\t\t}\n\t\tcase parser.CommentToken:\n\t\t\t\/\/ We ignore comments by default\n\t\tcase parser.DoctypeToken:\n\t\t\t\/\/ We ignore doctypes by default - html5 does not require them and this is intended for sanitizing snippets of text\n\t\tdefault:\n\t\t\t\/\/ We ignore unknown token types by default\n\n\t\t}\n\n\t}\n\n}\n\n\/\/ cleanAttributes removes all attributes except those in the allowed list\nfunc cleanAttributes(a []parser.Attribute, allowed []string) []parser.Attribute {\n\tif len(a) == 0 {\n\t\treturn a\n\t}\n\n\tvar cleaned []parser.Attribute\n\tfor _, attr := range a {\n\t\tif includes(allowed, attr.Key) {\n\t\t\tcleaned = append(cleaned, attr)\n\t\t}\n\t}\n\treturn cleaned\n}\n\n\/\/ includes returns true if this array of strings contains string s\nfunc includes(a []string, s string) bool {\n\tfor _, as := range a {\n\t\tif as == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>Added pre and code to default sanitize allowed tags<commit_after>package helpers\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\tgot \"html\/template\"\n\t\"io\"\n\t\"strings\"\n\n\tparser \"github.com\/fragmenta\/view\/internal\/html\"\n)\n\n\/\/ NB all HTML with user input must be escaped, see https:\/\/www.owasp.org\/index.php\/XSS_Prevention_Cheatsheet\n\n\/\/ These two should instead be using assets package?\n\n\/\/ Style inserts a css tag\nfunc Style(name string) got.HTML {\n\treturn got.HTML(fmt.Sprintf(\"<link href=\\\"\/assets\/styles\/%s.css\\\" media=\\\"all\\\" rel=\\\"stylesheet\\\" type=\\\"text\/css\\\" \/>\", EscapeURL(name)))\n}\n\n\/\/ Script inserts a script tag\nfunc Script(name string) got.HTML {\n\treturn got.HTML(fmt.Sprintf(\"<script src=\\\"\/assets\/scripts\/%s.js\\\" type=\\\"text\/javascript\\\"><\/script>\", EscapeURL(name)))\n}\n\n\/\/ Escape escapes HTML using HTMLEscapeString\nfunc Escape(s string) string {\n\treturn got.HTMLEscapeString(s)\n}\n\n\/\/ EscapeURL escapes URLs using HTMLEscapeString\nfunc EscapeURL(s string) string {\n\treturn got.URLQueryEscaper(s)\n}\n\n\/\/ Link returns got.HTML with an anchor link given text and URL required\n\/\/ Attributes (if supplied) should not contain user input\nfunc Link(t string, u string, a ...string) got.HTML {\n\tattributes := \"\"\n\tif len(a) > 0 {\n\t\tattributes = strings.Join(a, \" \")\n\t}\n\treturn got.HTML(fmt.Sprintf(\"<a href=\\\"%s\\\" %s>%s<\/a>\", Escape(u), Escape(attributes), Escape(t)))\n}\n\n\/\/ HTML returns a string (which must not contain user input) as go template HTML\nfunc HTML(s string) got.HTML {\n\treturn got.HTML(s)\n}\n\n\/\/ HTMLAttribute returns a string (which must not contain user input) as go template HTMLAttr\nfunc HTMLAttribute(s string) got.HTMLAttr {\n\treturn got.HTMLAttr(s)\n}\n\n\/\/ URL returns returns a string (which must not contain user input) as go template URL\nfunc URL(s string) got.URL {\n\treturn got.URL(s)\n}\n\n\/\/ Strip all html tags and returns as go template HTML\nfunc Strip(s string) got.HTML {\n\treturn Sanitize(s, []string{}, []string{})\n}\n\n\/\/ Sanitize sanitises html, allowing some tags using the html parser from golang.org\/x\/net\/html and returns as go template HTML\n\/\/ Usage: sanitize.HTMLAllowing(\"<b id=id>my html<\/b>\",[]string{\"b\"},[]string{\"id\")\nfunc Sanitize(s string, args ...[]string) got.HTML {\n\n\tvar ignoreTags = []string{\"title\", \"script\", \"style\", \"iframe\", \"frame\", \"frameset\", \"noframes\", \"noembed\", \"embed\", \"applet\", \"object\"}\n\tvar defaultTags = []string{\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\", \"div\", \"span\", \"hr\", \"p\", \"br\", \"b\", \"i\", \"ol\", \"ul\", \"li\", \"strong\", \"em\", \"a\", \"img\", \"pre\", \"code\"}\n\tvar defaultAttributes = []string{\"id\", \"class\", \"src\", \"title\", \"alt\", \"name\", \"rel\", \"href\"}\n\n\tallowedTags := defaultTags\n\tif len(args) > 0 {\n\t\tallowedTags = args[0]\n\t}\n\tallowedAttributes := defaultAttributes\n\tif len(args) > 1 {\n\t\tallowedAttributes = args[1]\n\t}\n\n\t\/\/ Parse the html\n\ttokenizer := parser.NewTokenizer(strings.NewReader(s))\n\n\tbuffer := bytes.NewBufferString(\"\")\n\tignore := \"\"\n\n\tfor {\n\t\ttokenType := tokenizer.Next()\n\t\ttoken := tokenizer.Token()\n\n\t\tswitch tokenType {\n\n\t\tcase parser.ErrorToken:\n\t\t\terr := tokenizer.Err()\n\t\t\tif err == io.EOF {\n\t\t\t\treturn got.HTML(buffer.String())\n\t\t\t}\n\n\t\t\tfmt.Println(\"Error parsing html\") \/\/ we should perhaps return an error\n\t\t\treturn got.HTML(\"\")\n\n\t\tcase parser.StartTagToken:\n\n\t\t\tif len(ignore) == 0 && includes(allowedTags, token.Data) {\n\t\t\t\ttoken.Attr = cleanAttributes(token.Attr, allowedAttributes)\n\t\t\t\tbuffer.WriteString(token.String())\n\t\t\t} else if includes(ignoreTags, token.Data) {\n\t\t\t\tignore = token.Data\n\t\t\t}\n\n\t\tcase parser.SelfClosingTagToken:\n\n\t\t\tif len(ignore) == 0 && includes(allowedTags, token.Data) {\n\t\t\t\ttoken.Attr = cleanAttributes(token.Attr, allowedAttributes)\n\t\t\t\tbuffer.WriteString(token.String())\n\t\t\t} else if token.Data == ignore {\n\t\t\t\tignore = \"\"\n\t\t\t}\n\n\t\tcase parser.EndTagToken:\n\t\t\tif len(ignore) == 0 && includes(allowedTags, token.Data) {\n\t\t\t\ttoken.Attr = []parser.Attribute{}\n\t\t\t\tbuffer.WriteString(token.String())\n\t\t\t} else if token.Data == ignore {\n\t\t\t\tignore = \"\"\n\t\t\t}\n\n\t\tcase parser.TextToken:\n\t\t\t\/\/ We allow text content through, unless ignoring this entire tag and its contents (including other tags)\n\t\t\tif ignore == \"\" {\n\t\t\t\tbuffer.WriteString(token.String())\n\t\t\t}\n\t\tcase parser.CommentToken:\n\t\t\t\/\/ We ignore comments by default\n\t\tcase parser.DoctypeToken:\n\t\t\t\/\/ We ignore doctypes by default - html5 does not require them and this is intended for sanitizing snippets of text\n\t\tdefault:\n\t\t\t\/\/ We ignore unknown token types by default\n\n\t\t}\n\n\t}\n\n}\n\n\/\/ cleanAttributes removes all attributes except those in the allowed list\nfunc cleanAttributes(a []parser.Attribute, allowed []string) []parser.Attribute {\n\tif len(a) == 0 {\n\t\treturn a\n\t}\n\n\tvar cleaned []parser.Attribute\n\tfor _, attr := range a {\n\t\tif includes(allowed, attr.Key) {\n\t\t\tcleaned = append(cleaned, attr)\n\t\t}\n\t}\n\treturn cleaned\n}\n\n\/\/ includes returns true if this array of strings contains string s\nfunc includes(a []string, s string) bool {\n\tfor _, as := range a {\n\t\tif as == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package hhr\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tflagReadFile = \"\"\n)\n\nfunc init() {\n\tflag.StringVar(&flagReadFile, \"hhr\", flagReadFile,\n\t\t\"The HHR file to use for tests.\")\n\tflag.Parse()\n\n\tlog.SetFlags(0)\n}\n\nfunc ExampleRead() {\n\tr := getFile()\n\n\thhr, err := Read(r)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\n\thit := hhr.Hits[9]\n\tfmt.Println(hit.Num)\n\tfmt.Println(hit.Name)\n\tfmt.Printf(\"%0.3f\\n\", hit.Prob)\n\tfmt.Println(hit.EValue)\n\tfmt.Println(hit.PValue)\n\tfmt.Println(hit.ViterbiScore)\n\tfmt.Println(hit.SSScore)\n\tfmt.Println(hit.NumAlignedCols)\n\tfmt.Println(hit.QueryStart)\n\tfmt.Println(hit.QueryEnd)\n\tfmt.Println(hit.TemplateStart)\n\tfmt.Println(hit.TemplateEnd)\n\tfmt.Println(hit.NumTemplateCols)\n\tfmt.Printf(\"%s\\n\", hit.Aligned.QSeq)\n\tfmt.Printf(\"%s\\n\", hit.Aligned.TSeq)\n\t\/\/ Output:\n\t\/\/ 10\n\t\/\/ 2fxaD\n\t\/\/ 0.571\n\t\/\/ 0.24\n\t\/\/ 0.00011\n\t\/\/ 34.3\n\t\/\/ 0\n\t\/\/ 47\n\t\/\/ 106\n\t\/\/ 154\n\t\/\/ 46\n\t\/\/ 94\n\t\/\/ 207\n\t\/\/ IGNSAFELLLEVAKSGEKGINTMDLAQVTGQDPRSVTGRIKKINH--LLTS \n\t\/\/ LNINEHHILWIAY--QLNGASISEIAKFGVMHVSTAFNFSKKLEERGYLRF \n}\n\nfunc getFile() *os.File {\n\tif len(flagReadFile) == 0 {\n\t\tlog.Fatalf(\"Please set the '--hhr path\/to\/file.hhr' flag.\")\n\t}\n\n\tr, err := os.Open(flagReadFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\treturn r\n}\n<commit_msg>gofmt<commit_after>package hhr\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\nvar (\n\tflagReadFile = \"\"\n)\n\nfunc init() {\n\tflag.StringVar(&flagReadFile, \"hhr\", flagReadFile,\n\t\t\"The HHR file to use for tests.\")\n\tflag.Parse()\n\n\tlog.SetFlags(0)\n}\n\nfunc ExampleRead() {\n\tr := getFile()\n\n\thhr, err := Read(r)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\n\thit := hhr.Hits[9]\n\tfmt.Println(hit.Num)\n\tfmt.Println(hit.Name)\n\tfmt.Printf(\"%0.3f\\n\", hit.Prob)\n\tfmt.Println(hit.EValue)\n\tfmt.Println(hit.PValue)\n\tfmt.Println(hit.ViterbiScore)\n\tfmt.Println(hit.SSScore)\n\tfmt.Println(hit.NumAlignedCols)\n\tfmt.Println(hit.QueryStart)\n\tfmt.Println(hit.QueryEnd)\n\tfmt.Println(hit.TemplateStart)\n\tfmt.Println(hit.TemplateEnd)\n\tfmt.Println(hit.NumTemplateCols)\n\tfmt.Printf(\"%s\\n\", hit.Aligned.QSeq)\n\tfmt.Printf(\"%s\\n\", hit.Aligned.TSeq)\n\t\/\/ Output:\n\t\/\/ 10\n\t\/\/ 2fxaD\n\t\/\/ 0.571\n\t\/\/ 0.24\n\t\/\/ 0.00011\n\t\/\/ 34.3\n\t\/\/ 0\n\t\/\/ 47\n\t\/\/ 106\n\t\/\/ 154\n\t\/\/ 46\n\t\/\/ 94\n\t\/\/ 207\n\t\/\/ IGNSAFELLLEVAKSGEKGINTMDLAQVTGQDPRSVTGRIKKINH--LLTS\n\t\/\/ LNINEHHILWIAY--QLNGASISEIAKFGVMHVSTAFNFSKKLEERGYLRF\n}\n\nfunc getFile() *os.File {\n\tif len(flagReadFile) == 0 {\n\t\tlog.Fatalf(\"Please set the '--hhr path\/to\/file.hhr' flag.\")\n\t}\n\n\tr, err := os.Open(flagReadFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\treturn r\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Volker Dobler.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ validhtml.go contains checks to slighty validate a HTML document.\n\npackage ht\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"golang.org\/x\/net\/html\"\n\t\"golang.org\/x\/text\/language\"\n)\n\nfunc init() {\n\tRegisterCheck(ValidHTML{})\n}\n\n\/\/ ValidHTML checks for valid HTML 5; well kinda: It make sure that some\n\/\/ common but easy to detect fuckups are not present. The following issues\n\/\/ are detected:\n\/\/   * 'doctype':   not exactly one DOCTYPE\n\/\/   * 'structure': ill-formed tag nesting \/ tag closing\n\/\/   * 'uniqueids': uniqness of id attribute values\n\/\/   * 'lang':      ill-formed lang attributes\n\/\/   * 'attr':      dupplicate attributes\n\/\/   * 'escaping':  unescaped &, < and > characters or unknown entities\n\/\/   * 'label':     reference to nonexisting id in label tags\n\/\/   * 'url':       malformed URLs\n\/\/\n\/\/ Notes:\n\/\/  - HTML5 allows unescaped & in several circumstances but ValidHTML\n\/\/    reports all stray & as an error.\n\/\/  - The lang attributes are parse very lax, e.g. the non-canonical form\n\/\/    'de_CH' is considered valid (and equivalent to 'de-CH'). I don't\n\/\/    know how browser handle this.\ntype ValidHTML struct {\n\t\/\/ Ignore is a space separated list of issues to ignore.\n\t\/\/ You normaly won't skip detection of these issues as all issues\n\t\/\/ are fundamental flaws which are easy to fix.\n\tIgnore string `json:\",omitempty\"`\n}\n\n\/\/ Execute implements Check's Execute method.\nfunc (v ValidHTML) Execute(t *Test) error {\n\tif t.Response.BodyErr != nil {\n\t\treturn ErrBadBody\n\t}\n\n\tmask, _ := ignoreMask(v.Ignore)\n\tstate := newHTMLState(t.Response.BodyStr, mask)\n\n\t\/\/ Parse document and record local errors in state.\n\tz := html.NewTokenizer(state)\n\tdepth := 0\ndone:\n\tfor {\n\t\ttt := z.Next()\n\t\t\/\/ fmt.Printf(\"%s%s: \", strings.Repeat(\"  \", depth), tt)\n\t\tswitch tt {\n\t\tcase html.ErrorToken:\n\t\t\tif z.Err() == io.EOF {\n\t\t\t\tbreak done\n\t\t\t}\n\t\t\treturn z.Err()\n\t\tcase html.TextToken:\n\t\t\t\/\/ fmt.Printf(\" %q\\n\", z.Text())\n\t\t\t\/\/ fmt.Println()\n\t\t\tif depth > 0 {\n\t\t\t\tstate.checkEscaping(string(z.Raw()))\n\t\t\t}\n\t\tcase html.StartTagToken, html.SelfClosingTagToken:\n\t\t\traw := string(z.Raw())\n\t\t\tif len(raw) > 3 {\n\t\t\t\tstate.checkEscaping(raw[1 : len(raw)-1])\n\t\t\t}\n\t\t\ttn, hasAttr := z.TagName()\n\t\t\t\/\/ Some tags are empty and may be written in the self-closing\n\t\t\t\/\/ variant \"<br\/>\" or simply empty like \"<br>\".\n\t\t\t\/\/ TODO: Maybe allow the non-compliant form \"<br><\/br>\" too?\n\t\t\tif tt != html.SelfClosingTagToken && !emptyHTMLElement[string(tn)] {\n\t\t\t\tstate.push(string(tn))\n\t\t\t\tdepth++\n\t\t\t}\n\t\t\ttag := string(tn)\n\t\t\t\/\/ fmt.Printf(\" %s  \", tag)\n\t\t\tstate.count(tag)\n\t\t\tattrs := map[string]string{}\n\t\t\tvar bkey, bval []byte\n\t\t\tfor hasAttr {\n\t\t\t\tbkey, bval, hasAttr = z.TagAttr()\n\t\t\t\tkey, val := string(bkey), string(bval)\n\t\t\t\t\/\/ fmt.Printf(\"%s=%s \", key, val)\n\t\t\t\tif _, ok := attrs[key]; ok {\n\t\t\t\t\tif state.ignore&issueAttr == 0 {\n\t\t\t\t\t\tstate.err(fmt.Errorf(\"duplicate attribute '%s'\", key))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tattrs[key] = val\n\t\t\t\tswitch {\n\t\t\t\tcase key == \"id\":\n\t\t\t\t\tstate.checkID(val)\n\t\t\t\tcase tag == \"label\" && key == \"for\":\n\t\t\t\t\tstate.recordLabel(val)\n\t\t\t\tcase key == \"lang\":\n\t\t\t\t\tstate.checkLang(val)\n\t\t\t\tcase (tag == \"a\" && key == \"href\") ||\n\t\t\t\t\t(tag == \"img\" && key == \"src\"): \/\/ TODO link?\n\t\t\t\t\tstate.checkURL(val)\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ fmt.Println()\n\t\tcase html.EndTagToken:\n\t\t\ttn, _ := z.TagName()\n\t\t\t\/\/ fmt.Println(\" \", string(tn))\n\t\t\tstate.pop(string(tn))\n\t\t\tdepth--\n\t\tcase html.CommentToken:\n\t\tcase html.DoctypeToken:\n\t\t\tstate.count(\"DOCTYPE\")\n\t\t}\n\t}\n\n\t\/\/ Check for global errors.\n\tstate.line++ \/\/ Global errors are reported \"after the last line\".\n\tif state.ignore&issueDoctype == 0 {\n\t\tif d := state.elementCount[\"DOCTYPE\"]; d != 1 {\n\t\t\tstate.err(fmt.Errorf(\"found %d DOCTYPE\", d))\n\t\t}\n\t}\n\tif state.ignore&issueLabelRef == 0 {\n\t\tfor _, id := range state.labelFor {\n\t\t\tif _, ok := state.seenIDs[id]; !ok {\n\t\t\t\tstate.err(fmt.Errorf(\"label references unknown id '%s'\", id))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(state.errors) == 0 {\n\t\treturn nil\n\t}\n\n\tif len(state.errors) == 0 {\n\t\treturn nil\n\t}\n\treturn state.errors\n}\n\n\/\/ Prepare implements Check's Prepare method.\nfunc (v ValidHTML) Prepare() error {\n\t_, err := ignoreMask(v.Ignore)\n\treturn err\n}\n\n\/\/ emptyHTMLElement is the list of all HTML5 elements which are empty, that\n\/\/ is they are implecitely self-closing and can be written either in\n\/\/ XML-style like e.g. \"<br\/>\" or in HTML5-style just \"<br>\".\n\/\/ The list was taken from:\n\/\/   - http:\/\/www.elharo.com\/blog\/software-development\/web-development\/2007\/01\/29\/all-empty-tags-in-html\/\n\/\/ Someone should check the whole list here: http:\/\/www.w3schools.com\/tags\/default.asp\nvar emptyHTMLElement = map[string]bool{\n\t\"br\":    true,\n\t\"hr\":    true,\n\t\"meta\":  true,\n\t\"base\":  true,\n\t\"link\":  true,\n\t\"img\":   true,\n\t\"embed\": true,\n\t\"param\": true,\n\t\"area\":  true,\n\t\"col\":   true,\n\t\"input\": true,\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Types of issues to ignore\n\ntype htmlIssue uint32\n\nconst (\n\tissueIgnoreNone htmlIssue = 0\n\tissueDoctype    htmlIssue = 1 << (iota - 1)\n\tissueStructure\n\tissueUniqIDs\n\tissueLangTag\n\tissueAttr\n\tissueEscaping\n\tissueLabelRef\n\tissueURL\n)\n\nfunc ignoreMask(s string) (htmlIssue, error) {\n\t\/\/ what an ugly hack\n\tconst issueNames = \"doctype  structureuniqueidslang     attr     escaping label    url      \"\n\tmask := htmlIssue(0)\n\ts = strings.ToLower(s)\n\tfor _, p := range strings.Split(s, \" \") {\n\t\tif p == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\ti := strings.Index(issueNames, p)\n\t\tif i == -1 {\n\t\t\treturn mask, fmt.Errorf(\"no such html issue '%s'\", p)\n\t\t}\n\t\tmask |= 1 << uint(i\/9)\n\t}\n\treturn mask, nil\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ htmlState\n\n\/\/ htmlState collects information about a HTML document.\ntype htmlState struct {\n\tbody string\n\ti    int\n\tline int\n\n\telementCount map[string]int\n\tseenIDs      map[string]bool\n\topenTags     []string\n\tlabelFor     []string\n\terrors       ErrorList\n\n\tignore     htmlIssue\n\tbadNesting bool\n}\n\nfunc newHTMLState(body string, ignore htmlIssue) *htmlState {\n\treturn &htmlState{\n\t\tbody:         body,\n\t\ti:            0,\n\t\tline:         0,\n\t\telementCount: make(map[string]int, 50),\n\t\tseenIDs:      make(map[string]bool),\n\t\topenTags:     make([]string, 0, 50),\n\t\tlabelFor:     make([]string, 0, 10),\n\t\terrors:       make(ErrorList, 0),\n\t\tbadNesting:   false,\n\t\tignore:       ignore,\n\t}\n}\n\nfunc (s *htmlState) Read(buf []byte) (int, error) {\n\tn := 0\n\tlast := byte(0)\n\tfor n < len(buf) && s.i < len(s.body) && last != '\\n' {\n\t\tbuf[n] = s.body[s.i]\n\t\tlast = s.body[s.i]\n\t\tn++\n\t\ts.i++\n\t}\n\ts.line++\n\tif s.i == len(s.body) {\n\t\treturn n, io.EOF\n\t}\n\treturn n, nil\n}\n\n\/\/ err records the error e.\nfunc (s *htmlState) err(e error) {\n\ts.errors = append(s.errors, PosError{Err: e, Line: s.line})\n}\n\n\/\/ count the tag\nfunc (s *htmlState) count(tag string) {\n\ts.elementCount[tag] = s.elementCount[tag] + 1\n}\n\n\/\/ checkID chesk for duplicate ids.\nfunc (s *htmlState) checkID(id string) {\n\tif s.ignore&issueUniqIDs == 0 {\n\t\tif _, seen := s.seenIDs[id]; seen {\n\t\t\ts.err(fmt.Errorf(\"duplicate id '%s'\", id))\n\t\t}\n\t}\n\ts.seenIDs[id] = true\n}\n\n\/\/ record the id from a <label for=\"id\"> tag.\nfunc (s *htmlState) recordLabel(id string) {\n\ts.labelFor = append(s.labelFor, id)\n}\n\n\/\/ checkEscaping of text\nfunc (s *htmlState) checkEscaping(text string) {\n\tif s.ignore&issueEscaping != 0 {\n\t\treturn\n\t}\n\n\t\/\/ Javascript is full of unescaped <, > and && and content of 'noscript'\n\t\/\/ and 'iframe' seems to be unparsed by package html: Skip check of\n\t\/\/ proper escaping inside these elements.\n\tif n := len(s.openTags); n > 0 &&\n\t\t(s.openTags[n-1] == \"script\" || s.openTags[n-1] == \"noscript\" || s.openTags[n-1] == \"iframe\") {\n\t\treturn\n\t}\n\n\tif strings.Index(text, \"<\") != -1 {\n\t\ts.err(fmt.Errorf(\"unescaped '<'\"))\n\t}\n\tif strings.Index(text, \">\") != -1 {\n\t\ts.err(fmt.Errorf(\"unescaped '>'\"))\n\t}\n\tfor len(text) > 0 {\n\t\tif i := strings.Index(text, \"&\"); i != -1 {\n\t\t\ttext = text[i:]\n\t\t\tif strings.HasPrefix(text, \"&amp;\") {\n\t\t\t\ttext = text[5:]\n\t\t\t} else {\n\t\t\t\tue := html.UnescapeString(text)\n\t\t\t\tif strings.HasPrefix(ue, \"&\") {\n\t\t\t\t\ts.err(fmt.Errorf(\"unescaped '&' or unknow entity\"))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttext = text[1:]\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n\/\/ checkLang tries to parse the language tag lang.\nfunc (s *htmlState) checkLang(lang string) {\n\tif s.ignore&issueLangTag != 0 {\n\t\treturn\n\t}\n\t_, err := language.Parse(lang)\n\tswitch e := err.(type) {\n\tcase nil:\n\t\t\/\/ No error.\n\tcase language.ValueError:\n\t\ts.err(fmt.Errorf(\"language tag '%s' has bad part %s\", lang, e.Subtag()))\n\tdefault:\n\t\t\/\/ A syntax error.\n\t\ts.err(fmt.Errorf(\"language tag '%s' is ill-formed\", lang))\n\t}\n}\n\n\/\/ checkURL raw to be properly encoded. HTML escaping has been checked already.\n\/\/ for now just dissalow spaces\nfunc (s *htmlState) checkURL(raw string) {\n\tif s.ignore&issueURL != 0 {\n\t\treturn\n\t}\n\n\tif strings.HasPrefix(raw, \"mailto:\") {\n\t\tif strings.Index(raw, \"@\") == -1 {\n\t\t\ts.err(fmt.Errorf(\"not an email address\"))\n\t\t}\n\t\treturn\n\t}\n\n\tu, err := url.Parse(raw)\n\tif err != nil {\n\t\ts.err(fmt.Errorf(\"bad URL '%s': %s\", raw, err.Error()))\n\t\treturn\n\t}\n\tif u.Opaque != \"\" {\n\t\ts.err(fmt.Errorf(\"bad URL part '%s'\", u.Opaque))\n\t\treturn\n\t}\n\n\tif strings.Index(raw, \" \") != -1 {\n\t\ts.err(fmt.Errorf(\"unencoded space in URL\"))\n\t}\n}\n\n\/\/ push tag on stack of open tags\nfunc (s *htmlState) push(tag string) {\n\ts.openTags = append(s.openTags, tag)\n}\n\n\/\/ try to pop tag from stack of open tags, record error if failed.\nfunc (s *htmlState) pop(tag string) {\n\tn := len(s.openTags)\n\tif n == 0 {\n\t\tif s.ignore&issueStructure == 0 {\n\t\t\ts.err(fmt.Errorf(\"no open tags left to close %s\", tag))\n\t\t}\n\t\treturn\n\t}\n\tpop := s.openTags[n-1]\n\ts.openTags = s.openTags[:n-1]\n\tif s.ignore&issueStructure != 0 {\n\t\treturn\n\t}\n\tif pop != tag && !s.badNesting { \/\/ report broken structure just once.\n\t\ts.err(fmt.Errorf(\"tag '%s' closed by '%s'\", pop, tag))\n\t\ts.badNesting = true\n\t}\n}\n<commit_msg>ht: refactor and improve link checking<commit_after>\/\/ Copyright 2015 Volker Dobler.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ validhtml.go contains checks to slighty validate a HTML document.\n\npackage ht\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"golang.org\/x\/net\/html\"\n\t\"golang.org\/x\/text\/language\"\n)\n\nfunc init() {\n\tRegisterCheck(ValidHTML{})\n}\n\n\/\/ ValidHTML checks for valid HTML 5; well kinda: It make sure that some\n\/\/ common but easy to detect fuckups are not present. The following issues\n\/\/ are detected:\n\/\/   * 'doctype':   not exactly one DOCTYPE\n\/\/   * 'structure': ill-formed tag nesting \/ tag closing\n\/\/   * 'uniqueids': uniqness of id attribute values\n\/\/   * 'lang':      ill-formed lang attributes\n\/\/   * 'attr':      dupplicate attributes\n\/\/   * 'escaping':  unescaped &, < and > characters or unknown entities\n\/\/   * 'label':     reference to nonexisting id in label tags\n\/\/   * 'url':       malformed URLs\n\/\/\n\/\/ Notes:\n\/\/  - HTML5 allows unescaped & in several circumstances but ValidHTML\n\/\/    reports all stray & as an error.\n\/\/  - The lang attributes are parse very lax, e.g. the non-canonical form\n\/\/    'de_CH' is considered valid (and equivalent to 'de-CH'). I don't\n\/\/    know how browser handle this.\ntype ValidHTML struct {\n\t\/\/ Ignore is a space separated list of issues to ignore.\n\t\/\/ You normaly won't skip detection of these issues as all issues\n\t\/\/ are fundamental flaws which are easy to fix.\n\tIgnore string `json:\",omitempty\"`\n}\n\n\/\/ Execute implements Check's Execute method.\nfunc (v ValidHTML) Execute(t *Test) error {\n\tif t.Response.BodyErr != nil {\n\t\treturn ErrBadBody\n\t}\n\n\tmask, _ := ignoreMask(v.Ignore)\n\tstate := newHTMLState(t.Response.BodyStr, mask)\n\n\t\/\/ Parse document and record local errors in state.\n\tz := html.NewTokenizer(state)\n\tdepth := 0\ndone:\n\tfor {\n\t\ttt := z.Next()\n\t\t\/\/ fmt.Printf(\"%s%s: \", strings.Repeat(\"  \", depth), tt)\n\t\tswitch tt {\n\t\tcase html.ErrorToken:\n\t\t\tif z.Err() == io.EOF {\n\t\t\t\tbreak done\n\t\t\t}\n\t\t\treturn z.Err()\n\t\tcase html.TextToken:\n\t\t\t\/\/ fmt.Printf(\" %q\\n\", z.Text())\n\t\t\t\/\/ fmt.Println()\n\t\t\tif depth > 0 {\n\t\t\t\tstate.checkEscaping(string(z.Raw()))\n\t\t\t}\n\t\tcase html.StartTagToken, html.SelfClosingTagToken:\n\t\t\traw := string(z.Raw())\n\t\t\tif len(raw) > 3 {\n\t\t\t\tstate.checkEscaping(raw[1 : len(raw)-1])\n\t\t\t}\n\t\t\ttn, hasAttr := z.TagName()\n\t\t\t\/\/ Some tags are empty and may be written in the self-closing\n\t\t\t\/\/ variant \"<br\/>\" or simply empty like \"<br>\".\n\t\t\t\/\/ TODO: Maybe allow the non-compliant form \"<br><\/br>\" too?\n\t\t\tif tt != html.SelfClosingTagToken && !emptyHTMLElement[string(tn)] {\n\t\t\t\tstate.push(string(tn))\n\t\t\t\tdepth++\n\t\t\t}\n\t\t\ttag := string(tn)\n\t\t\t\/\/ fmt.Printf(\" %s  \", tag)\n\t\t\tstate.count(tag)\n\t\t\tattrs := map[string]string{}\n\t\t\tvar bkey, bval []byte\n\t\t\tfor hasAttr {\n\t\t\t\tbkey, bval, hasAttr = z.TagAttr()\n\t\t\t\tkey, val := string(bkey), string(bval)\n\t\t\t\t\/\/ fmt.Printf(\"%s=%s \", key, val)\n\t\t\t\tif _, ok := attrs[key]; ok {\n\t\t\t\t\tif state.ignore&issueAttr == 0 {\n\t\t\t\t\t\tstate.err(fmt.Errorf(\"duplicate attribute '%s'\", key))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tattrs[key] = val\n\t\t\t\tswitch {\n\t\t\t\tcase key == \"id\":\n\t\t\t\t\tstate.checkID(val)\n\t\t\t\tcase tag == \"label\" && key == \"for\":\n\t\t\t\t\tstate.recordLabel(val)\n\t\t\t\tcase key == \"lang\":\n\t\t\t\t\tstate.checkLang(val)\n\t\t\t\tcase isURLAttr(tag, key):\n\t\t\t\t\tstate.checkURL(val)\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ fmt.Println()\n\t\tcase html.EndTagToken:\n\t\t\ttn, _ := z.TagName()\n\t\t\t\/\/ fmt.Println(\" \", string(tn))\n\t\t\tstate.pop(string(tn))\n\t\t\tdepth--\n\t\tcase html.CommentToken:\n\t\tcase html.DoctypeToken:\n\t\t\tstate.count(\"DOCTYPE\")\n\t\t}\n\t}\n\n\t\/\/ Check for global errors.\n\tstate.line++ \/\/ Global errors are reported \"after the last line\".\n\tif state.ignore&issueDoctype == 0 {\n\t\tif d := state.elementCount[\"DOCTYPE\"]; d != 1 {\n\t\t\tstate.err(fmt.Errorf(\"found %d DOCTYPE\", d))\n\t\t}\n\t}\n\tif state.ignore&issueLabelRef == 0 {\n\t\tfor _, id := range state.labelFor {\n\t\t\tif _, ok := state.seenIDs[id]; !ok {\n\t\t\t\tstate.err(fmt.Errorf(\"label references unknown id '%s'\", id))\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(state.errors) == 0 {\n\t\treturn nil\n\t}\n\n\tif len(state.errors) == 0 {\n\t\treturn nil\n\t}\n\treturn state.errors\n}\n\n\/\/ return true if attr contains the URL of the tag.\nfunc isURLAttr(tag, attr string) bool {\n\tif a, ok := linkURLattr[tag]; ok {\n\t\treturn attr == a.attr\n\t}\n\treturn false\n}\n\n\/\/ Prepare implements Check's Prepare method.\nfunc (v ValidHTML) Prepare() error {\n\t_, err := ignoreMask(v.Ignore)\n\treturn err\n}\n\n\/\/ emptyHTMLElement is the list of all HTML5 elements which are empty, that\n\/\/ is they are implecitely self-closing and can be written either in\n\/\/ XML-style like e.g. \"<br\/>\" or in HTML5-style just \"<br>\".\n\/\/ The list was taken from:\n\/\/   - http:\/\/www.elharo.com\/blog\/software-development\/web-development\/2007\/01\/29\/all-empty-tags-in-html\/\n\/\/ Someone should check the whole list here: http:\/\/www.w3schools.com\/tags\/default.asp\nvar emptyHTMLElement = map[string]bool{\n\t\"br\":    true,\n\t\"hr\":    true,\n\t\"meta\":  true,\n\t\"base\":  true,\n\t\"link\":  true,\n\t\"img\":   true,\n\t\"embed\": true,\n\t\"param\": true,\n\t\"area\":  true,\n\t\"col\":   true,\n\t\"input\": true,\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Types of issues to ignore\n\ntype htmlIssue uint32\n\nconst (\n\tissueIgnoreNone htmlIssue = 0\n\tissueDoctype    htmlIssue = 1 << (iota - 1)\n\tissueStructure\n\tissueUniqIDs\n\tissueLangTag\n\tissueAttr\n\tissueEscaping\n\tissueLabelRef\n\tissueURL\n)\n\nfunc ignoreMask(s string) (htmlIssue, error) {\n\t\/\/ what an ugly hack\n\tconst issueNames = \"doctype  structureuniqueidslang     attr     escaping label    url      \"\n\tmask := htmlIssue(0)\n\ts = strings.ToLower(s)\n\tfor _, p := range strings.Split(s, \" \") {\n\t\tif p == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\ti := strings.Index(issueNames, p)\n\t\tif i == -1 {\n\t\t\treturn mask, fmt.Errorf(\"no such html issue '%s'\", p)\n\t\t}\n\t\tmask |= 1 << uint(i\/9)\n\t}\n\treturn mask, nil\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ htmlState\n\n\/\/ htmlState collects information about a HTML document.\ntype htmlState struct {\n\tbody string\n\ti    int\n\tline int\n\n\telementCount map[string]int\n\tseenIDs      map[string]bool\n\topenTags     []string\n\tlabelFor     []string\n\terrors       ErrorList\n\n\tignore     htmlIssue\n\tbadNesting bool\n}\n\nfunc newHTMLState(body string, ignore htmlIssue) *htmlState {\n\treturn &htmlState{\n\t\tbody:         body,\n\t\ti:            0,\n\t\tline:         0,\n\t\telementCount: make(map[string]int, 50),\n\t\tseenIDs:      make(map[string]bool),\n\t\topenTags:     make([]string, 0, 50),\n\t\tlabelFor:     make([]string, 0, 10),\n\t\terrors:       make(ErrorList, 0),\n\t\tbadNesting:   false,\n\t\tignore:       ignore,\n\t}\n}\n\nfunc (s *htmlState) Read(buf []byte) (int, error) {\n\tn := 0\n\tlast := byte(0)\n\tfor n < len(buf) && s.i < len(s.body) && last != '\\n' {\n\t\tbuf[n] = s.body[s.i]\n\t\tlast = s.body[s.i]\n\t\tn++\n\t\ts.i++\n\t}\n\ts.line++\n\tif s.i == len(s.body) {\n\t\treturn n, io.EOF\n\t}\n\treturn n, nil\n}\n\n\/\/ err records the error e.\nfunc (s *htmlState) err(e error) {\n\ts.errors = append(s.errors, PosError{Err: e, Line: s.line})\n}\n\n\/\/ count the tag\nfunc (s *htmlState) count(tag string) {\n\ts.elementCount[tag] = s.elementCount[tag] + 1\n}\n\n\/\/ checkID chesk for duplicate ids.\nfunc (s *htmlState) checkID(id string) {\n\tif s.ignore&issueUniqIDs == 0 {\n\t\tif _, seen := s.seenIDs[id]; seen {\n\t\t\ts.err(fmt.Errorf(\"duplicate id '%s'\", id))\n\t\t}\n\t}\n\ts.seenIDs[id] = true\n}\n\n\/\/ record the id from a <label for=\"id\"> tag.\nfunc (s *htmlState) recordLabel(id string) {\n\ts.labelFor = append(s.labelFor, id)\n}\n\n\/\/ checkEscaping of text\nfunc (s *htmlState) checkEscaping(text string) {\n\tif s.ignore&issueEscaping != 0 {\n\t\treturn\n\t}\n\n\t\/\/ Javascript is full of unescaped <, > and && and content of 'noscript'\n\t\/\/ and 'iframe' seems to be unparsed by package html: Skip check of\n\t\/\/ proper escaping inside these elements.\n\tif n := len(s.openTags); n > 0 &&\n\t\t(s.openTags[n-1] == \"script\" || s.openTags[n-1] == \"noscript\" || s.openTags[n-1] == \"iframe\") {\n\t\treturn\n\t}\n\n\tif strings.Index(text, \"<\") != -1 {\n\t\ts.err(fmt.Errorf(\"unescaped '<'\"))\n\t}\n\tif strings.Index(text, \">\") != -1 {\n\t\ts.err(fmt.Errorf(\"unescaped '>'\"))\n\t}\n\tfor len(text) > 0 {\n\t\tif i := strings.Index(text, \"&\"); i != -1 {\n\t\t\ttext = text[i:]\n\t\t\tif strings.HasPrefix(text, \"&amp;\") {\n\t\t\t\ttext = text[5:]\n\t\t\t} else {\n\t\t\t\tue := html.UnescapeString(text)\n\t\t\t\tif strings.HasPrefix(ue, \"&\") {\n\t\t\t\t\ts.err(fmt.Errorf(\"unescaped '&' or unknow entity\"))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttext = text[1:]\n\t\t\t}\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n\/\/ checkLang tries to parse the language tag lang.\nfunc (s *htmlState) checkLang(lang string) {\n\tif s.ignore&issueLangTag != 0 {\n\t\treturn\n\t}\n\t_, err := language.Parse(lang)\n\tswitch e := err.(type) {\n\tcase nil:\n\t\t\/\/ No error.\n\tcase language.ValueError:\n\t\ts.err(fmt.Errorf(\"language tag '%s' has bad part %s\", lang, e.Subtag()))\n\tdefault:\n\t\t\/\/ A syntax error.\n\t\ts.err(fmt.Errorf(\"language tag '%s' is ill-formed\", lang))\n\t}\n}\n\n\/\/ checkURL raw to be properly encoded. HTML escaping has been checked already.\n\/\/ for now just dissalow spaces\nfunc (s *htmlState) checkURL(raw string) {\n\tif s.ignore&issueURL != 0 {\n\t\treturn\n\t}\n\n\tif strings.HasPrefix(raw, \"mailto:\") {\n\t\tif strings.Index(raw, \"@\") == -1 {\n\t\t\ts.err(fmt.Errorf(\"not an email address\"))\n\t\t}\n\t\treturn\n\t}\n\n\tu, err := url.Parse(raw)\n\tif err != nil {\n\t\ts.err(fmt.Errorf(\"bad URL '%s': %s\", raw, err.Error()))\n\t\treturn\n\t}\n\tif u.Opaque != \"\" {\n\t\ts.err(fmt.Errorf(\"bad URL part '%s'\", u.Opaque))\n\t\treturn\n\t}\n\n\tif strings.Index(raw, \" \") != -1 {\n\t\ts.err(fmt.Errorf(\"unencoded space in URL\"))\n\t}\n}\n\n\/\/ push tag on stack of open tags\nfunc (s *htmlState) push(tag string) {\n\ts.openTags = append(s.openTags, tag)\n}\n\n\/\/ try to pop tag from stack of open tags, record error if failed.\nfunc (s *htmlState) pop(tag string) {\n\tn := len(s.openTags)\n\tif n == 0 {\n\t\tif s.ignore&issueStructure == 0 {\n\t\t\ts.err(fmt.Errorf(\"no open tags left to close %s\", tag))\n\t\t}\n\t\treturn\n\t}\n\tpop := s.openTags[n-1]\n\ts.openTags = s.openTags[:n-1]\n\tif s.ignore&issueStructure != 0 {\n\t\treturn\n\t}\n\tif pop != tag && !s.badNesting { \/\/ report broken structure just once.\n\t\ts.err(fmt.Errorf(\"tag '%s' closed by '%s'\", pop, tag))\n\t\ts.badNesting = true\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n\n\t\"github.com\/garyburd\/redigo\/redis\"\n\t\"github.com\/gorilla\/mux\"\n)\n\nfunc defineRoutes() {\n\tr := mux.NewRouter()\n\n\tr.HandleFunc(\"\/api\/controllers\/{controller_id}\/sensors\", getCoordinatorSensors).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/controllers\/{controller_id}\", putCoordinator).Methods(\"POST\", \"PUT\")\n\tr.HandleFunc(\"\/api\/controllers\/{controller_id}\/{hash}\", getCoordinator).Methods(\"GET\")\n\n\tr.HandleFunc(\"\/api\/sensors\/{sensor_id}\", putSensor).Methods(\"POST\", \"PUT\")\n\tr.HandleFunc(\"\/api\/sensors\/{sensor_id}\/ticks\", getSensorTicks).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/sensors\/{sensor_id}\/dots\", getSensorDots).Methods(\"GET\")\n\n\t\/\/ FIXME: deprecated\n\tr.HandleFunc(\"\/api\/log\", getLogsV1).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/logs\", getLogsV1).Methods(\"GET\")\n\n\tr.HandleFunc(\"\/api\/debug_log\", getDebugLogs).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/debug_logs\", getDebugLogs).Methods(\"GET\")\n\n\tr.HandleFunc(\"\/api\/v1\/log\", getLogsV1).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/v1\/logs\", getLogsV1).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/v2\/log\", getLogsV2).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/v2\/logs\", getLogsV2).Methods(\"GET\")\n\n\thttp.Handle(\"\/\", r)\n}\n\nfunc getCoordinator(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tcoordinatorID, ok := mux.Vars(r)[\"controller_id\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing controller_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\thashToken, ok := mux.Vars(r)[\"hash\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing token hash\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tredisClient := redisPool.Get()\n\tdefer redisClient.Close()\n\n\tc := &coordinator{ID: coordinatorID, Token: hashToken}\n\n\tcoordinatorHash, err := redis.String(redisClient.Do(\"HGET\", c.key(), \"token\"))\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif coordinatorHash != c.Token {\n\t\thttp.Error(w, \"Incorrect hash for this coordinator\", http.StatusUnauthorized)\n\t}\n\n\tcoordinatorName, err := redis.String(redisClient.Do(\"HGET\", c.key(), \"name\"))\n\tif err != nil {\n\t\tif err != redis.ErrNil {\n\t\t\tlog.Println(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tcoordinatorName = c.ID\n\t}\n\tc.Name = coordinatorName\n\n\tb, err := json.Marshal(c)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc putCoordinator(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tcoordinatorID, ok := mux.Vars(r)[\"controller_id\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing controller_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar c coordinator\n\tif err := json.Unmarshal(b, &c); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tc.ID = coordinatorID\n\n\tredisClient := redisPool.Get()\n\tdefer redisClient.Close()\n\n\t_, err = redisClient.Do(\"HSET\", c.key(), \"name\", c.Name)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc putSensor(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tsensorID, exists := mux.Vars(r)[\"sensor_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing or invalid sensor_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar s sensor\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tredisClient := redisPool.Get()\n\tdefer redisClient.Close()\n\n\t_, err = redisClient.Do(\"HMSET\", keyOfSensor(sensorID), \"lat\", s.Lat, \"lng\", s.Lng)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc getCoordinatorSensors(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tcoordinatorID, ok := mux.Vars(r)[\"controller_id\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing controller_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tredisClient := redisPool.Get()\n\tdefer redisClient.Close()\n\n\tids, err := redis.Strings(redisClient.Do(\"SMEMBERS\", keyOfCoordinatorSensors(coordinatorID)))\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsensors := make([]*sensor, 0)\n\tfor _, sensorID := range ids {\n\t\tif len(sensorID) == 0 {\n\t\t\tlog.Println(err)\n\t\t\thttp.Error(w, \"Invalid or missing sensor ID\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\ts := &sensor{ID: sensorID, ControllerID: coordinatorID}\n\n\t\t\/\/ Get lat, lng of sensor\n\t\tbb, err := redisClient.Do(\"HMGET\", keyOfSensor(sensorID), \"lat\", \"lng\")\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tif bb != nil {\n\t\t\tlist := bb.([]interface{})\n\t\t\tif len(list) > 0 {\n\t\t\t\tif list[0] != nil {\n\t\t\t\t\ts.Lat = string(list[0].([]byte))\n\t\t\t\t}\n\t\t\t\tif list[1] != nil {\n\t\t\t\t\ts.Lng = string(list[1].([]byte))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Get last tick of sensor\n\t\tticks, err := findTicksByRange(sensorID, 0, 0)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tif len(ticks) > 0 {\n\t\t\ts.LastTick = &ticks[0].Datetime\n\n\t\t}\n\n\t\tsensors = append(sensors, s)\n\t}\n\n\tb, err := json.Marshal(sensors)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getSensorDots(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tsensorID, exists := mux.Vars(r)[\"sensor_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing sensor_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstart, err := strconv.Atoi(r.FormValue(\"start\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid start\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tend, err := strconv.Atoi(r.FormValue(\"end\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid end\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdotsPerDay, err := strconv.Atoi(r.FormValue(\"dots_per_day\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid dots_per_day\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif dotsPerDay < 0 || dotsPerDay > 24 {\n\t\thttp.Error(w, \"dots_per_day must be in range 0-24\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tredisClient := redisPool.Get()\n\tdefer redisClient.Close()\n\n\tticks, err := findTicksByScore(sensorID, start, end)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar dots []*tick\n\tif dotsPerDay > 0 {\n\t\tdots = findAverages(ticks, dotsPerDay, start, end)\n\t} else {\n\t\tdots = ticks\n\t}\n\n\tb, err := json.Marshal(dots)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getSensorTicks(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tsensorID, exists := mux.Vars(r)[\"sensor_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing sensor_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstart, err := strconv.Atoi(r.FormValue(\"start\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid start\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tend, err := strconv.Atoi(r.FormValue(\"end\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid end\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tresult, err := findTicksByScore(sensorID, start, end)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(result)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getLogsV1(w http.ResponseWriter, r *http.Request) {\n\tgetLogs(w, r, loggingKeyV1)\n}\n\nfunc getLogsV2(w http.ResponseWriter, r *http.Request) {\n\tgetLogs(w, r, loggingKeyV2)\n}\n\nfunc getLogs(w http.ResponseWriter, r *http.Request, key string) {\n\tredisClient := redisPool.Get()\n\tdefer redisClient.Close()\n\n\tbb, err := redisClient.Do(\"LRANGE\", key, 0, 1000)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text\/plain\")\n\tfor _, item := range bb.([]interface{}) {\n\t\ts := string(item.([]byte))\n\t\ts = strconv.Quote(s)\n\t\tw.Write([]byte(s))\n\t\tw.Write([]byte(\"\\n\\r\"))\n\t}\n}\n\nfunc getDebugLogs(w http.ResponseWriter, r *http.Request) {\n\tgetLogs(w, r, debugLogKey)\n}\n<commit_msg>rename controller routes<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n\n\t\"github.com\/garyburd\/redigo\/redis\"\n\t\"github.com\/gorilla\/mux\"\n)\n\nfunc defineRoutes() {\n\tr := mux.NewRouter()\n\n\tr.HandleFunc(\"\/api\/coordinators\/{coordinator_id}\/sensors\", getCoordinatorSensors).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/coordinators\/{coordinator_id}\", putCoordinator).Methods(\"POST\", \"PUT\")\n\tr.HandleFunc(\"\/api\/coordinators\/{coordinator_id}\/{hash}\", getCoordinator).Methods(\"GET\")\n\n\tr.HandleFunc(\"\/api\/sensors\/{sensor_id}\", putSensor).Methods(\"POST\", \"PUT\")\n\tr.HandleFunc(\"\/api\/sensors\/{sensor_id}\/ticks\", getSensorTicks).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/sensors\/{sensor_id}\/dots\", getSensorDots).Methods(\"GET\")\n\n\t\/\/ FIXME: deprecated\n\tr.HandleFunc(\"\/api\/log\", getLogsV1).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/logs\", getLogsV1).Methods(\"GET\")\n\n\tr.HandleFunc(\"\/api\/debug_log\", getDebugLogs).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/debug_logs\", getDebugLogs).Methods(\"GET\")\n\n\tr.HandleFunc(\"\/api\/v1\/log\", getLogsV1).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/v1\/logs\", getLogsV1).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/v2\/log\", getLogsV2).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/v2\/logs\", getLogsV2).Methods(\"GET\")\n\n\thttp.Handle(\"\/\", r)\n}\n\nfunc getCoordinator(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tcoordinatorID, ok := mux.Vars(r)[\"coordinator_id\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\thashToken, ok := mux.Vars(r)[\"hash\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing token hash\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tredisClient := redisPool.Get()\n\tdefer redisClient.Close()\n\n\tc := &coordinator{ID: coordinatorID, Token: hashToken}\n\n\tcoordinatorHash, err := redis.String(redisClient.Do(\"HGET\", c.key(), \"token\"))\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif coordinatorHash != c.Token {\n\t\thttp.Error(w, \"Incorrect hash for this coordinator\", http.StatusUnauthorized)\n\t}\n\n\tcoordinatorName, err := redis.String(redisClient.Do(\"HGET\", c.key(), \"name\"))\n\tif err != nil {\n\t\tif err != redis.ErrNil {\n\t\t\tlog.Println(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tcoordinatorName = c.ID\n\t}\n\tc.Name = coordinatorName\n\n\tb, err := json.Marshal(c)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc putCoordinator(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tcoordinatorID, ok := mux.Vars(r)[\"coordinator_id\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar c coordinator\n\tif err := json.Unmarshal(b, &c); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tc.ID = coordinatorID\n\n\tredisClient := redisPool.Get()\n\tdefer redisClient.Close()\n\n\t_, err = redisClient.Do(\"HSET\", c.key(), \"name\", c.Name)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc putSensor(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tsensorID, exists := mux.Vars(r)[\"sensor_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing or invalid sensor_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar s sensor\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tredisClient := redisPool.Get()\n\tdefer redisClient.Close()\n\n\t_, err = redisClient.Do(\"HMSET\", keyOfSensor(sensorID), \"lat\", s.Lat, \"lng\", s.Lng)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc getCoordinatorSensors(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tcoordinatorID, ok := mux.Vars(r)[\"coordinator_id\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tredisClient := redisPool.Get()\n\tdefer redisClient.Close()\n\n\tids, err := redis.Strings(redisClient.Do(\"SMEMBERS\", keyOfCoordinatorSensors(coordinatorID)))\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tsensors := make([]*sensor, 0)\n\tfor _, sensorID := range ids {\n\t\tif len(sensorID) == 0 {\n\t\t\tlog.Println(err)\n\t\t\thttp.Error(w, \"Invalid or missing sensor ID\", http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\ts := &sensor{ID: sensorID, ControllerID: coordinatorID}\n\n\t\t\/\/ Get lat, lng of sensor\n\t\tbb, err := redisClient.Do(\"HMGET\", keyOfSensor(sensorID), \"lat\", \"lng\")\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tif bb != nil {\n\t\t\tlist := bb.([]interface{})\n\t\t\tif len(list) > 0 {\n\t\t\t\tif list[0] != nil {\n\t\t\t\t\ts.Lat = string(list[0].([]byte))\n\t\t\t\t}\n\t\t\t\tif list[1] != nil {\n\t\t\t\t\ts.Lng = string(list[1].([]byte))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Get last tick of sensor\n\t\tticks, err := findTicksByRange(sensorID, 0, 0)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tif len(ticks) > 0 {\n\t\t\ts.LastTick = &ticks[0].Datetime\n\n\t\t}\n\n\t\tsensors = append(sensors, s)\n\t}\n\n\tb, err := json.Marshal(sensors)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getSensorDots(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tsensorID, exists := mux.Vars(r)[\"sensor_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing sensor_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstart, err := strconv.Atoi(r.FormValue(\"start\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid start\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tend, err := strconv.Atoi(r.FormValue(\"end\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid end\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdotsPerDay, err := strconv.Atoi(r.FormValue(\"dots_per_day\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid dots_per_day\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif dotsPerDay < 0 || dotsPerDay > 24 {\n\t\thttp.Error(w, \"dots_per_day must be in range 0-24\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tredisClient := redisPool.Get()\n\tdefer redisClient.Close()\n\n\tticks, err := findTicksByScore(sensorID, start, end)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar dots []*tick\n\tif dotsPerDay > 0 {\n\t\tdots = findAverages(ticks, dotsPerDay, start, end)\n\t} else {\n\t\tdots = ticks\n\t}\n\n\tb, err := json.Marshal(dots)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getSensorTicks(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tsensorID, exists := mux.Vars(r)[\"sensor_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing sensor_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstart, err := strconv.Atoi(r.FormValue(\"start\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid start\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tend, err := strconv.Atoi(r.FormValue(\"end\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid end\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tresult, err := findTicksByScore(sensorID, start, end)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(result)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getLogsV1(w http.ResponseWriter, r *http.Request) {\n\tgetLogs(w, r, loggingKeyV1)\n}\n\nfunc getLogsV2(w http.ResponseWriter, r *http.Request) {\n\tgetLogs(w, r, loggingKeyV2)\n}\n\nfunc getLogs(w http.ResponseWriter, r *http.Request, key string) {\n\tredisClient := redisPool.Get()\n\tdefer redisClient.Close()\n\n\tbb, err := redisClient.Do(\"LRANGE\", key, 0, 1000)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text\/plain\")\n\tfor _, item := range bb.([]interface{}) {\n\t\ts := string(item.([]byte))\n\t\ts = strconv.Quote(s)\n\t\tw.Write([]byte(s))\n\t\tw.Write([]byte(\"\\n\\r\"))\n\t}\n}\n\nfunc getDebugLogs(w http.ResponseWriter, r *http.Request) {\n\tgetLogs(w, r, debugLogKey)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/toggl\/bugsnag\"\n)\n\nfunc defineRoutes() {\n\tr := mux.NewRouter()\n\n\tr.HandleFunc(\"\/api\/coordinators\/{coordinator_id}\/sensors\", getCoordinatorSensors).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/coordinators\/{coordinator_id}\/readings\", getCoordinatorReadings).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/coordinators\/{coordinator_id}\/log\", getCoordinatorLog).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/coordinators\/{coordinator_id}\", putCoordinator).Methods(\"POST\", \"PUT\")\n\tr.HandleFunc(\"\/api\/coordinators\/{coordinator_id}\/{hash}\", getCoordinator).Methods(\"GET\")\n\n\tr.HandleFunc(\"\/api\/sensors\/{sensor_id}\", putSensor).Methods(\"POST\", \"PUT\")\n\tr.HandleFunc(\"\/api\/sensors\/{sensor_id}\/ticks\", getSensorTicks).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/sensors\/{sensor_id}\/dots\", getSensorDots).Methods(\"GET\")\n\n\tr.HandleFunc(\"\/api\/admin\/coordinators\", getAdminCoordinators).Methods(\"GET\")\n\n\tr.HandleFunc(\"\/api\/v1\/log\", getCSVLogs).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/v1\/logs\", getCSVLogs).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/v2\/log\", getJSONLogs).Methods(\"GET\")\n\tr.HandleFunc(\"\/api\/v2\/logs\", getJSONLogs).Methods(\"GET\")\n\n\thttp.Handle(\"\/\", r)\n}\n\nfunc getAdminCoordinators(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tauth, err := parseToken(r)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif auth == nil {\n\t\tw.Header().Set(\"WWW-Authenticate\", \"Basic realm=\\\"Ardusensor admin\\\"\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\tif auth.Username != *adminUsername || auth.Password != *adminPassword {\n\t\tw.Header().Set(\"WWW-Authenticate\", \"Basic realm=\\\"Ardusensor admin\\\"\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tcoordinators, err := coordinators()\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tb, err := json.MarshalIndent(coordinators, \"\", \"\\t\")\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getCoordinatorLog(w http.ResponseWriter, r *http.Request) {\n\tcoordinatorID, err := strconv.Atoi(mux.Vars(r)[\"coordinator_id\"])\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\twriteLogs(w, r, loggingKeyJSON, coordinatorID)\n}\n\nfunc getCoordinator(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tcoordinatorID, ok := mux.Vars(r)[\"coordinator_id\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\thashToken, ok := mux.Vars(r)[\"hash\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing token hash\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tc, err := loadCoordinator(coordinatorID)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif hashToken != c.Token {\n\t\thttp.Error(w, \"Incorrect token for this coordinator\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(c)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc putCoordinator(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tcoordinatorID, ok := mux.Vars(r)[\"coordinator_id\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar c coordinator\n\tif err := json.Unmarshal(b, &c); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif err := setCoordinatorLabel(coordinatorID, c.Label); err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc putSensor(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tsensorID, exists := mux.Vars(r)[\"sensor_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing or invalid sensor_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar s sensor\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\ts.ID = sensorID\n\n\tif err := s.save(); err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tb, err = json.Marshal(s)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getCoordinatorSensors(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tcoordinatorID, ok := mux.Vars(r)[\"coordinator_id\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tsensors, err := sensorsOfCoordinator(coordinatorID)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(sensors)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getSensorDots(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tsensorID, exists := mux.Vars(r)[\"sensor_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing sensor_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstart, err := strconv.Atoi(r.FormValue(\"start\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid start\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tend, err := strconv.Atoi(r.FormValue(\"end\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid end\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdotsPerDay, err := strconv.Atoi(r.FormValue(\"dots_per_day\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid dots_per_day\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif dotsPerDay < 0 || dotsPerDay > 24 {\n\t\thttp.Error(w, \"dots_per_day must be in range 0-24\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tticks, err := findTicksByScore(sensorID, start, end)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar dots []*tick\n\tif dotsPerDay > 0 {\n\t\tdots = findAverages(ticks, dotsPerDay, start, end)\n\t} else {\n\t\tdots = ticks\n\t}\n\n\tb, err := json.Marshal(dots)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getSensorTicks(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tsensorID, exists := mux.Vars(r)[\"sensor_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing sensor_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstart, err := strconv.Atoi(r.FormValue(\"start\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid start\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tend, err := strconv.Atoi(r.FormValue(\"end\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid end\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tresult, err := findTicksByScore(sensorID, start, end)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(result)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getCoordinatorReadings(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\ts, exists := mux.Vars(r)[\"coordinator_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tcoordinatorID, err := strconv.ParseInt(s, 10, 64)\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstart, err := strconv.Atoi(r.FormValue(\"start\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid start\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tend, err := strconv.Atoi(r.FormValue(\"end\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid end\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tresult, err := coordinatorReadings(coordinatorID, start, end)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(result)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getCSVLogs(w http.ResponseWriter, r *http.Request) {\n\twriteLogs(w, r, loggingKeyCSV, 0)\n}\n\nfunc getJSONLogs(w http.ResponseWriter, r *http.Request) {\n\twriteLogs(w, r, loggingKeyJSON, 0)\n}\n\nfunc writeLogs(w http.ResponseWriter, r *http.Request, key string, coordinatorID int) {\n\tb, err := getLogs(key, coordinatorID)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"text\/plain\")\n\tw.Write(b)\n}\n<commit_msg>\/api subrouter<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/toggl\/bugsnag\"\n)\n\nfunc defineRoutes() {\n\tr := mux.NewRouter()\n\n\tapi := r.PathPrefix(\"\/api\").Subrouter()\n\n\tapi.HandleFunc(\"\/coordinators\/{coordinator_id}\/sensors\", getCoordinatorSensors).Methods(\"GET\")\n\tapi.HandleFunc(\"\/coordinators\/{coordinator_id}\/readings\", getCoordinatorReadings).Methods(\"GET\")\n\tapi.HandleFunc(\"\/coordinators\/{coordinator_id}\/log\", getCoordinatorLog).Methods(\"GET\")\n\tapi.HandleFunc(\"\/coordinators\/{coordinator_id}\", putCoordinator).Methods(\"POST\", \"PUT\")\n\tapi.HandleFunc(\"\/coordinators\/{coordinator_id}\/{hash}\", getCoordinator).Methods(\"GET\")\n\n\tapi.HandleFunc(\"\/sensors\/{sensor_id}\", putSensor).Methods(\"POST\", \"PUT\")\n\tapi.HandleFunc(\"\/sensors\/{sensor_id}\/ticks\", getSensorTicks).Methods(\"GET\")\n\tapi.HandleFunc(\"\/sensors\/{sensor_id}\/dots\", getSensorDots).Methods(\"GET\")\n\n\tapi.HandleFunc(\"\/admin\/coordinators\", getAdminCoordinators).Methods(\"GET\")\n\n\tapi.HandleFunc(\"\/log\", getCSVLogs).Methods(\"GET\")\n\tapi.HandleFunc(\"\/v1\/logs\", getCSVLogs).Methods(\"GET\")\n\tapi.HandleFunc(\"\/v2\/log\", getJSONLogs).Methods(\"GET\")\n\tapi.HandleFunc(\"\/v2\/logs\", getJSONLogs).Methods(\"GET\")\n\n\thttp.Handle(\"\/\", r)\n}\n\nfunc getAdminCoordinators(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tauth, err := parseToken(r)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif auth == nil {\n\t\tw.Header().Set(\"WWW-Authenticate\", \"Basic realm=\\\"Ardusensor admin\\\"\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\tif auth.Username != *adminUsername || auth.Password != *adminPassword {\n\t\tw.Header().Set(\"WWW-Authenticate\", \"Basic realm=\\\"Ardusensor admin\\\"\")\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tcoordinators, err := coordinators()\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tb, err := json.MarshalIndent(coordinators, \"\", \"\\t\")\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getCoordinatorLog(w http.ResponseWriter, r *http.Request) {\n\tcoordinatorID, err := strconv.Atoi(mux.Vars(r)[\"coordinator_id\"])\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\twriteLogs(w, r, loggingKeyJSON, coordinatorID)\n}\n\nfunc getCoordinator(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tcoordinatorID, ok := mux.Vars(r)[\"coordinator_id\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\thashToken, ok := mux.Vars(r)[\"hash\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing token hash\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tc, err := loadCoordinator(coordinatorID)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif hashToken != c.Token {\n\t\thttp.Error(w, \"Incorrect token for this coordinator\", http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(c)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc putCoordinator(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tcoordinatorID, ok := mux.Vars(r)[\"coordinator_id\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar c coordinator\n\tif err := json.Unmarshal(b, &c); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif err := setCoordinatorLabel(coordinatorID, c.Label); err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}\n\nfunc putSensor(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tsensorID, exists := mux.Vars(r)[\"sensor_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing or invalid sensor_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tvar s sensor\n\tif err := json.Unmarshal(b, &s); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\ts.ID = sensorID\n\n\tif err := s.save(); err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tb, err = json.Marshal(s)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getCoordinatorSensors(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tcoordinatorID, ok := mux.Vars(r)[\"coordinator_id\"]\n\tif !ok {\n\t\thttp.Error(w, \"Missing coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tsensors, err := sensorsOfCoordinator(coordinatorID)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(sensors)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getSensorDots(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tsensorID, exists := mux.Vars(r)[\"sensor_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing sensor_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstart, err := strconv.Atoi(r.FormValue(\"start\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid start\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tend, err := strconv.Atoi(r.FormValue(\"end\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid end\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tdotsPerDay, err := strconv.Atoi(r.FormValue(\"dots_per_day\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid dots_per_day\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif dotsPerDay < 0 || dotsPerDay > 24 {\n\t\thttp.Error(w, \"dots_per_day must be in range 0-24\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tticks, err := findTicksByScore(sensorID, start, end)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar dots []*tick\n\tif dotsPerDay > 0 {\n\t\tdots = findAverages(ticks, dotsPerDay, start, end)\n\t} else {\n\t\tdots = ticks\n\t}\n\n\tb, err := json.Marshal(dots)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getSensorTicks(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\tsensorID, exists := mux.Vars(r)[\"sensor_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing sensor_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstart, err := strconv.Atoi(r.FormValue(\"start\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid start\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tend, err := strconv.Atoi(r.FormValue(\"end\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid end\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tresult, err := findTicksByScore(sensorID, start, end)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(result)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getCoordinatorReadings(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(r)\n\n\ts, exists := mux.Vars(r)[\"coordinator_id\"]\n\tif !exists {\n\t\thttp.Error(w, \"Missing coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tcoordinatorID, err := strconv.ParseInt(s, 10, 64)\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid coordinator_id\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tstart, err := strconv.Atoi(r.FormValue(\"start\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid start\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tend, err := strconv.Atoi(r.FormValue(\"end\"))\n\tif err != nil {\n\t\thttp.Error(w, \"Missing or invalid end\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tresult, err := coordinatorReadings(coordinatorID, start, end)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tb, err := json.Marshal(result)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}\n\nfunc getCSVLogs(w http.ResponseWriter, r *http.Request) {\n\twriteLogs(w, r, loggingKeyCSV, 0)\n}\n\nfunc getJSONLogs(w http.ResponseWriter, r *http.Request) {\n\twriteLogs(w, r, loggingKeyJSON, 0)\n}\n\nfunc writeLogs(w http.ResponseWriter, r *http.Request, key string, coordinatorID int) {\n\tb, err := getLogs(key, coordinatorID)\n\tif err != nil {\n\t\tbugsnag.Notify(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"text\/plain\")\n\tw.Write(b)\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/mediaconvert\"\n\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/validation\"\n)\n\nfunc resourceAwsMediaConvertQueue() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsMediaConvertQueueCreate,\n\t\tRead:   resourceAwsMediaConvertQueueRead,\n\t\tUpdate: resourceAwsMediaConvertQueueUpdate,\n\t\tDelete: resourceAwsMediaConvertQueueDelete,\n\n\t\tImporter: &schema.ResourceImporter{\n\t\t\tState: schema.ImportStatePassthrough,\n\t\t},\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"arn\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"description\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"pricing_plan\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tDefault:  mediaconvert.PricingPlanOnDemand,\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\tmediaconvert.PricingPlanOnDemand,\n\t\t\t\t\tmediaconvert.PricingPlanReserved,\n\t\t\t\t}, false),\n\t\t\t},\n\t\t\t\"reservation_plan_settings\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tComputed: true,\n\t\t\t\tMaxItems: 1,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"commitment\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\t\t\t\tmediaconvert.CommitmentOneYear,\n\t\t\t\t\t\t\t}, false),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"renewal_type\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\t\t\t\tmediaconvert.RenewalTypeAutoRenew,\n\t\t\t\t\t\t\t\tmediaconvert.RenewalTypeExpire,\n\t\t\t\t\t\t\t}, false),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"reserved_slots\": {\n\t\t\t\t\t\t\tType:     schema.TypeInt,\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"status\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault:  mediaconvert.QueueStatusActive,\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\tmediaconvert.QueueStatusActive,\n\t\t\t\t\tmediaconvert.QueueStatusPaused,\n\t\t\t\t}, false),\n\t\t\t},\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsMediaConvertQueueCreate(d *schema.ResourceData, meta interface{}) error {\n\toriginalConn := meta.(*AWSClient).mediaconvertconn\n\n\tendpointURL, err := getAwsMediaConvertEndpoint(originalConn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting Media Convert Endpoint: %s\", err)\n\t}\n\n\tsess, err := session.NewSession(&originalConn.Config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating AWS session: %s\", err)\n\t}\n\tconn := mediaconvert.New(sess.Copy(&aws.Config{Endpoint: aws.String(endpointURL)}))\n\n\tcreateOpts := &mediaconvert.CreateQueueInput{\n\t\tName:        aws.String(d.Get(\"name\").(string)),\n\t\tStatus:      aws.String(d.Get(\"status\").(string)),\n\t\tPricingPlan: aws.String(d.Get(\"pricing_plan\").(string)),\n\t\tTags:        tagsFromMapGeneric(d.Get(\"tags\").(map[string]interface{})),\n\t}\n\n\tif v, ok := d.GetOk(\"description\"); ok {\n\t\tcreateOpts.Description = aws.String(v.(string))\n\t}\n\n\tif v, ok := d.GetOk(\"reservation_plan_settings\"); ok {\n\t\treservationPlanSettings := v.([]interface{})[0].(map[string]interface{})\n\t\tcreateOpts.ReservationPlanSettings = expandMediaConvertReservationPlanSettings(reservationPlanSettings)\n\t}\n\n\tresp, err := conn.CreateQueue(createOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating Media Convert Queue: %s\", err)\n\t}\n\n\td.SetId(aws.StringValue(resp.Queue.Name))\n\n\treturn resourceAwsMediaConvertQueueRead(d, meta)\n}\n\nfunc resourceAwsMediaConvertQueueRead(d *schema.ResourceData, meta interface{}) error {\n\toriginalConn := meta.(*AWSClient).mediaconvertconn\n\n\tendpointURL, err := getAwsMediaConvertEndpoint(originalConn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting Media Convert Endpoint: %s\", err)\n\t}\n\n\tsess, err := session.NewSession(&originalConn.Config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating AWS session: %s\", err)\n\t}\n\tconn := mediaconvert.New(sess.Copy(&aws.Config{Endpoint: aws.String(endpointURL)}))\n\n\tgetOpts := &mediaconvert.GetQueueInput{\n\t\tName: aws.String(d.Id()),\n\t}\n\n\tresp, err := conn.GetQueue(getOpts)\n\tif isAWSErr(err, mediaconvert.ErrCodeNotFoundException, \"\") {\n\t\tlog.Printf(\"[WARN] Media Convert Queue (%s) not found, removing from state\", d.Id())\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting Media Convert Queue: %s\", err)\n\t}\n\n\td.Set(\"arn\", resp.Queue.Arn)\n\td.Set(\"name\", resp.Queue.Name)\n\td.Set(\"description\", resp.Queue.Description)\n\td.Set(\"pricing_plan\", resp.Queue.PricingPlan)\n\td.Set(\"status\", resp.Queue.Status)\n\n\tif err := d.Set(\"reservation_plan_settings\", flattenMediaConvertReservationPlan(resp.Queue.ReservationPlan)); err != nil {\n\t\treturn fmt.Errorf(\"Error setting Media Convert Queue reservation_plan_settings: %s\", err)\n\t}\n\n\tif err := saveTagsMediaConvert(conn, d, aws.StringValue(resp.Queue.Arn)); err != nil {\n\t\treturn fmt.Errorf(\"Error setting Media Convert Queue tags: %s\", err)\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsMediaConvertQueueUpdate(d *schema.ResourceData, meta interface{}) error {\n\toriginalConn := meta.(*AWSClient).mediaconvertconn\n\n\tendpointURL, err := getAwsMediaConvertEndpoint(originalConn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting Media Convert Endpoint: %s\", err)\n\t}\n\n\tsess, err := session.NewSession(&originalConn.Config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating AWS session: %s\", err)\n\t}\n\tconn := mediaconvert.New(sess.Copy(&aws.Config{Endpoint: aws.String(endpointURL)}))\n\n\tupdateOpts := &mediaconvert.UpdateQueueInput{\n\t\tName:   aws.String(d.Id()),\n\t\tStatus: aws.String(d.Get(\"status\").(string)),\n\t}\n\n\tif v, ok := d.GetOk(\"description\"); ok {\n\t\tupdateOpts.Description = aws.String(v.(string))\n\t}\n\n\tif v, ok := d.GetOk(\"reservation_plan_settings\"); ok {\n\t\treservationPlanSettings := v.([]interface{})[0].(map[string]interface{})\n\t\tupdateOpts.ReservationPlanSettings = expandMediaConvertReservationPlanSettings(reservationPlanSettings)\n\t}\n\n\t_, err = conn.UpdateQueue(updateOpts)\n\tif isAWSErr(err, mediaconvert.ErrCodeNotFoundException, \"\") {\n\t\tlog.Printf(\"[WARN] Media Convert Queue (%s) not found, removing from state\", d.Id())\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error updating Media Convert Queue: %s\", err)\n\t}\n\n\tif err := setTagsMediaConvert(conn, d, d.Get(\"arn\").(string)); err != nil {\n\t\treturn fmt.Errorf(\"error updating Media Convert Queue (%s) tags: %s\", d.Id(), err)\n\t}\n\n\treturn resourceAwsMediaConvertQueueRead(d, meta)\n}\n\nfunc resourceAwsMediaConvertQueueDelete(d *schema.ResourceData, meta interface{}) error {\n\toriginalConn := meta.(*AWSClient).mediaconvertconn\n\n\tendpointURL, err := getAwsMediaConvertEndpoint(originalConn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting Media Convert Endpoint: %s\", err)\n\t}\n\n\tsess, err := session.NewSession(&originalConn.Config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating AWS session: %s\", err)\n\t}\n\tconn := mediaconvert.New(sess.Copy(&aws.Config{Endpoint: aws.String(endpointURL)}))\n\n\tdelOpts := &mediaconvert.DeleteQueueInput{\n\t\tName: aws.String(d.Id()),\n\t}\n\n\t_, err = conn.DeleteQueue(delOpts)\n\tif isAWSErr(err, mediaconvert.ErrCodeNotFoundException, \"\") {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting Media Convert Queue: %s\", err)\n\t}\n\n\treturn nil\n}\n\nfunc getAwsMediaConvertEndpoint(conn *mediaconvert.MediaConvert) (string, error) {\n\tdescOpts := &mediaconvert.DescribeEndpointsInput{\n\t\tMode: aws.String(mediaconvert.DescribeEndpointsModeDefault),\n\t}\n\n\tresp, err := conn.DescribeEndpoints(descOpts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tendpoint := resp.Endpoints[0]\n\n\treturn aws.StringValue(endpoint.Url), nil\n}\n<commit_msg>fix to use keyvaluetags for aws_mediaconvert_queue resource<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/session\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/mediaconvert\"\n\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/keyvaluetags\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/validation\"\n)\n\nfunc resourceAwsMediaConvertQueue() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsMediaConvertQueueCreate,\n\t\tRead:   resourceAwsMediaConvertQueueRead,\n\t\tUpdate: resourceAwsMediaConvertQueueUpdate,\n\t\tDelete: resourceAwsMediaConvertQueueDelete,\n\n\t\tImporter: &schema.ResourceImporter{\n\t\t\tState: schema.ImportStatePassthrough,\n\t\t},\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"arn\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"description\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t},\n\t\t\t\"pricing_plan\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tDefault:  mediaconvert.PricingPlanOnDemand,\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\tmediaconvert.PricingPlanOnDemand,\n\t\t\t\t\tmediaconvert.PricingPlanReserved,\n\t\t\t\t}, false),\n\t\t\t},\n\t\t\t\"reservation_plan_settings\": {\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tComputed: true,\n\t\t\t\tMaxItems: 1,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"commitment\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\t\t\t\tmediaconvert.CommitmentOneYear,\n\t\t\t\t\t\t\t}, false),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"renewal_type\": {\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\t\t\t\tmediaconvert.RenewalTypeAutoRenew,\n\t\t\t\t\t\t\t\tmediaconvert.RenewalTypeExpire,\n\t\t\t\t\t\t\t}, false),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"reserved_slots\": {\n\t\t\t\t\t\t\tType:     schema.TypeInt,\n\t\t\t\t\t\t\tRequired: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"status\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tDefault:  mediaconvert.QueueStatusActive,\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{\n\t\t\t\t\tmediaconvert.QueueStatusActive,\n\t\t\t\t\tmediaconvert.QueueStatusPaused,\n\t\t\t\t}, false),\n\t\t\t},\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsMediaConvertQueueCreate(d *schema.ResourceData, meta interface{}) error {\n\toriginalConn := meta.(*AWSClient).mediaconvertconn\n\n\tendpointURL, err := getAwsMediaConvertEndpoint(originalConn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting Media Convert Endpoint: %s\", err)\n\t}\n\n\tsess, err := session.NewSession(&originalConn.Config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating AWS session: %s\", err)\n\t}\n\tconn := mediaconvert.New(sess.Copy(&aws.Config{Endpoint: aws.String(endpointURL)}))\n\n\tcreateOpts := &mediaconvert.CreateQueueInput{\n\t\tName:        aws.String(d.Get(\"name\").(string)),\n\t\tStatus:      aws.String(d.Get(\"status\").(string)),\n\t\tPricingPlan: aws.String(d.Get(\"pricing_plan\").(string)),\n\t\tTags:        keyvaluetags.New(d.Get(\"tags\").(map[string]interface{})).IgnoreAws().MediaconvertTags(),\n\t}\n\n\tif v, ok := d.GetOk(\"description\"); ok {\n\t\tcreateOpts.Description = aws.String(v.(string))\n\t}\n\n\tif v, ok := d.GetOk(\"reservation_plan_settings\"); ok {\n\t\treservationPlanSettings := v.([]interface{})[0].(map[string]interface{})\n\t\tcreateOpts.ReservationPlanSettings = expandMediaConvertReservationPlanSettings(reservationPlanSettings)\n\t}\n\n\tresp, err := conn.CreateQueue(createOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating Media Convert Queue: %s\", err)\n\t}\n\n\td.SetId(aws.StringValue(resp.Queue.Name))\n\n\treturn resourceAwsMediaConvertQueueRead(d, meta)\n}\n\nfunc resourceAwsMediaConvertQueueRead(d *schema.ResourceData, meta interface{}) error {\n\toriginalConn := meta.(*AWSClient).mediaconvertconn\n\n\tendpointURL, err := getAwsMediaConvertEndpoint(originalConn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting Media Convert Endpoint: %s\", err)\n\t}\n\n\tsess, err := session.NewSession(&originalConn.Config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating AWS session: %s\", err)\n\t}\n\tconn := mediaconvert.New(sess.Copy(&aws.Config{Endpoint: aws.String(endpointURL)}))\n\n\tgetOpts := &mediaconvert.GetQueueInput{\n\t\tName: aws.String(d.Id()),\n\t}\n\n\tresp, err := conn.GetQueue(getOpts)\n\tif isAWSErr(err, mediaconvert.ErrCodeNotFoundException, \"\") {\n\t\tlog.Printf(\"[WARN] Media Convert Queue (%s) not found, removing from state\", d.Id())\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting Media Convert Queue: %s\", err)\n\t}\n\n\td.Set(\"arn\", resp.Queue.Arn)\n\td.Set(\"name\", resp.Queue.Name)\n\td.Set(\"description\", resp.Queue.Description)\n\td.Set(\"pricing_plan\", resp.Queue.PricingPlan)\n\td.Set(\"status\", resp.Queue.Status)\n\n\tif err := d.Set(\"reservation_plan_settings\", flattenMediaConvertReservationPlan(resp.Queue.ReservationPlan)); err != nil {\n\t\treturn fmt.Errorf(\"Error setting Media Convert Queue reservation_plan_settings: %s\", err)\n\t}\n\n\ttags, err := keyvaluetags.MediaconvertListTags(conn, aws.StringValue(resp.Queue.Arn))\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error listing tags for Media Convert Queue (%s): %s\", d.Id(), err)\n\t}\n\n\tif err := d.Set(\"tags\", tags.IgnoreAws().Map()); err != nil {\n\t\treturn fmt.Errorf(\"error setting tags: %s\", err)\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsMediaConvertQueueUpdate(d *schema.ResourceData, meta interface{}) error {\n\toriginalConn := meta.(*AWSClient).mediaconvertconn\n\n\tendpointURL, err := getAwsMediaConvertEndpoint(originalConn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting Media Convert Endpoint: %s\", err)\n\t}\n\n\tsess, err := session.NewSession(&originalConn.Config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating AWS session: %s\", err)\n\t}\n\tconn := mediaconvert.New(sess.Copy(&aws.Config{Endpoint: aws.String(endpointURL)}))\n\n\t\tupdateOpts := &mediaconvert.UpdateQueueInput{\n\t\t\tName:   aws.String(d.Id()),\n\t\t\tStatus: aws.String(d.Get(\"status\").(string)),\n\t\t}\n\n\t\tif v, ok := d.GetOk(\"description\"); ok {\n\t\t\tupdateOpts.Description = aws.String(v.(string))\n\t\t}\n\n\t\tif v, ok := d.GetOk(\"reservation_plan_settings\"); ok {\n\t\t\treservationPlanSettings := v.([]interface{})[0].(map[string]interface{})\n\t\t\tupdateOpts.ReservationPlanSettings = expandMediaConvertReservationPlanSettings(reservationPlanSettings)\n\t\t}\n\n\t\t_, err = conn.UpdateQueue(updateOpts)\n\t\tif isAWSErr(err, mediaconvert.ErrCodeNotFoundException, \"\") {\n\t\t\tlog.Printf(\"[WARN] Media Convert Queue (%s) not found, removing from state\", d.Id())\n\t\t\td.SetId(\"\")\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error updating Media Convert Queue: %s\", err)\n\t\t}\n\t}\n\n\tif d.HasChange(\"tags\") {\n\t\to, n := d.GetChange(\"tags\")\n\t\tif err := keyvaluetags.MediaconvertUpdateTags(conn, d.Get(\"arn\").(string), o, n); err != nil {\n\t\t\treturn fmt.Errorf(\"error updating tags: %s\", err)\n\t\t}\n\t}\n\n\treturn resourceAwsMediaConvertQueueRead(d, meta)\n}\n\nfunc resourceAwsMediaConvertQueueDelete(d *schema.ResourceData, meta interface{}) error {\n\toriginalConn := meta.(*AWSClient).mediaconvertconn\n\n\tendpointURL, err := getAwsMediaConvertEndpoint(originalConn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting Media Convert Endpoint: %s\", err)\n\t}\n\n\tsess, err := session.NewSession(&originalConn.Config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating AWS session: %s\", err)\n\t}\n\tconn := mediaconvert.New(sess.Copy(&aws.Config{Endpoint: aws.String(endpointURL)}))\n\n\tdelOpts := &mediaconvert.DeleteQueueInput{\n\t\tName: aws.String(d.Id()),\n\t}\n\n\t_, err = conn.DeleteQueue(delOpts)\n\tif isAWSErr(err, mediaconvert.ErrCodeNotFoundException, \"\") {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error deleting Media Convert Queue: %s\", err)\n\t}\n\n\treturn nil\n}\n\nfunc getAwsMediaConvertEndpoint(conn *mediaconvert.MediaConvert) (string, error) {\n\tdescOpts := &mediaconvert.DescribeEndpointsInput{\n\t\tMode: aws.String(mediaconvert.DescribeEndpointsModeDefault),\n\t}\n\n\tresp, err := conn.DescribeEndpoints(descOpts)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tendpoint := resp.Endpoints[0]\n\n\treturn aws.StringValue(endpoint.Url), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/hashicorp\/atlas-go\/v1\"\n)\n\nvar (\n\tVersion string\n)\n\nfunc init() {\n\tlog.SetOutput(ioutil.Discard)\n}\n\nfunc ToJson(obj interface{}) (interface{}, error) {\n\tdata, err := json.Marshal(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn string(data), nil\n}\n\nfunc search(c *cli.Context) {\n\n\tif c.String(\"user\") == \"\" || c.String(\"artifact\") == \"\" || c.String(\"type\") == \"\" {\n\t\tcli.ShowAppHelp(c)\n\t\tos.Exit(1)\n\t}\n\n\tsearchOpts := &atlas.ArtifactSearchOpts{\n\t\tUser: c.String(\"user\"),\n\t\tName: c.String(\"artifact\"),\n\t\tType: c.String(\"type\"),\n\t}\n\tif len(c.StringSlice(\"meta\")) > 0 {\n\t\tfilter := map[string]string{}\n\t\tfor _, m := range c.StringSlice(\"meta\") {\n\t\t\tpair := strings.Split(m, \"=\")\n\t\t\tfilter[pair[0]] = pair[1]\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"FILTER: %#v\\n\", filter)\n\t\tsearchOpts.Metadata = filter\n\t}\n\tclient := atlas.DefaultClient()\n\n\tversions, err := client.ArtifactSearch(searchOpts)\n\tif err != nil {\n\t\tfmt.Errorf(\"search error: %#v\", err)\n\t\tos.Exit(1)\n\t}\n\n\tfnMap := template.FuncMap{}\n\tfnMap[\"json\"] = ToJson\n\ttmpl, err := template.New(\"artifact\").Funcs(fnMap).Parse(c.String(\"format\") + \"\\n\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, v := range versions {\n\t\t\/\/fmt.Println(\"ver: %#v\", v)\n\t\terr = tmpl.Execute(os.Stdout, v)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n}\n\nfunc main() {\n\tfmt.Fprintln(os.Stderr, \"Search atlas.hashicorp artifacts ...\")\n\n\tapp := cli.NewApp()\n\tapp.Name = \"atlifacts\"\n\tapp.Usage = \"query atlas.hashicorp.com artifacts\"\n\tapp.Version = Version\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:   \"user, u\",\n\t\t\tUsage:  \"atlas user\",\n\t\t\tEnvVar: \"ATLAS_USER\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"artifact, a\",\n\t\t\tUsage:  \"atlas artifact\",\n\t\t\tEnvVar: \"ATLAS_ARTIFACT_NAME\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"type, t\",\n\t\t\tUsage:  \"atlas artifact type\",\n\t\t\tEnvVar: \"ATLAS_ARTIFACT_TYPE\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"format, f\",\n\t\t\tValue: \"{{.Slug}}\",\n\t\t\tUsage: \"output format in golang template\",\n\t\t},\n\t\tcli.StringSliceFlag{\n\t\t\tName:  \"meta, m\",\n\t\t\tUsage: \"meta field as fielter\",\n\t\t},\n\t}\n\tapp.Action = search\n\n\tapp.Run(os.Args)\n\n}\n<commit_msg>Fixing typo<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"text\/template\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/hashicorp\/atlas-go\/v1\"\n)\n\nvar (\n\tVersion string\n)\n\nfunc init() {\n\tlog.SetOutput(ioutil.Discard)\n}\n\nfunc ToJson(obj interface{}) (interface{}, error) {\n\tdata, err := json.Marshal(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn string(data), nil\n}\n\nfunc search(c *cli.Context) {\n\n\tif c.String(\"user\") == \"\" || c.String(\"artifact\") == \"\" || c.String(\"type\") == \"\" {\n\t\tcli.ShowAppHelp(c)\n\t\tos.Exit(1)\n\t}\n\n\tsearchOpts := &atlas.ArtifactSearchOpts{\n\t\tUser: c.String(\"user\"),\n\t\tName: c.String(\"artifact\"),\n\t\tType: c.String(\"type\"),\n\t}\n\tif len(c.StringSlice(\"meta\")) > 0 {\n\t\tfilter := map[string]string{}\n\t\tfor _, m := range c.StringSlice(\"meta\") {\n\t\t\tpair := strings.Split(m, \"=\")\n\t\t\tfilter[pair[0]] = pair[1]\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"FILTER: %#v\\n\", filter)\n\t\tsearchOpts.Metadata = filter\n\t}\n\tclient := atlas.DefaultClient()\n\n\tversions, err := client.ArtifactSearch(searchOpts)\n\tif err != nil {\n\t\tfmt.Errorf(\"search error: %#v\", err)\n\t\tos.Exit(1)\n\t}\n\n\tfnMap := template.FuncMap{}\n\tfnMap[\"json\"] = ToJson\n\ttmpl, err := template.New(\"artifact\").Funcs(fnMap).Parse(c.String(\"format\") + \"\\n\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor _, v := range versions {\n\t\t\/\/fmt.Println(\"ver: %#v\", v)\n\t\terr = tmpl.Execute(os.Stdout, v)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n}\n\nfunc main() {\n\tfmt.Fprintln(os.Stderr, \"Search atlas.hashicorp artifacts ...\")\n\n\tapp := cli.NewApp()\n\tapp.Name = \"atlifacts\"\n\tapp.Usage = \"query atlas.hashicorp.com artifacts\"\n\tapp.Version = Version\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:   \"user, u\",\n\t\t\tUsage:  \"atlas user\",\n\t\t\tEnvVar: \"ATLAS_USER\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"artifact, a\",\n\t\t\tUsage:  \"atlas artifact\",\n\t\t\tEnvVar: \"ATLAS_ARTIFACT_NAME\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:   \"type, t\",\n\t\t\tUsage:  \"atlas artifact type\",\n\t\t\tEnvVar: \"ATLAS_ARTIFACT_TYPE\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"format, f\",\n\t\t\tValue: \"{{.Slug}}\",\n\t\t\tUsage: \"output format in golang template\",\n\t\t},\n\t\tcli.StringSliceFlag{\n\t\t\tName:  \"meta, m\",\n\t\t\tUsage: \"meta field as filter\",\n\t\t},\n\t}\n\tapp.Action = search\n\n\tapp.Run(os.Args)\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package libreofficekit\n\n\/*\n#cgo CFLAGS: -I .\/ -D LOK_USE_UNSTABLE_API\n#cgo LDFLAGS: -ldl\n#include <lokbridge.h>\n*\/\nimport \"C\"\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"unsafe\"\n)\n\ntype Office struct {\n\thandle *C.struct__LibreOfficeKit\n\tmutex  *sync.Mutex\n}\n\nfunc NewOffice(path string) (*Office, error) {\n\toffice := new(Office)\n\n\tc_path := C.CString(path)\n\tdefer C.free(unsafe.Pointer(c_path))\n\n\tlokit := C.lok_init(c_path)\n\tif lokit == nil {\n\t\treturn nil, fmt.Errorf(\"Failed to initialize LibreOfficeKit with path: '%s'\", path)\n\t}\n\n\toffice.handle = lokit\n\toffice.mutex = &sync.Mutex{}\n\n\treturn office, nil\n\n}\n\nfunc (self *Office) Close() {\n\tC.destroy_office(self.handle)\n}\n\nfunc (self *Office) GetError() string {\n\tmessage := C.get_error(self.handle)\n\treturn C.GoString(message)\n}\n\nfunc (self *Office) LoadDocument(path string) (*Document, error) {\n\tdocument := new(Document)\n\tc_path := C.CString(path)\n\tdefer C.free(unsafe.Pointer(c_path))\n\thandle := C.document_load(self.handle, c_path)\n\tif handle == nil {\n\t\treturn nil, fmt.Errorf(\"Failed to load document\")\n\t}\n\tdocument.handle = handle\n\treturn document, nil\n}\n\nconst (\n\tTextDocument = iota\n\tSpreadsheetDocument\n\tPresentationDocument\n\tDrawingDocument\n\tOtherDocument\n)\n\ntype Document struct {\n\thandle *C.struct__LibreOfficeKitDocument\n}\n\nfunc (self *Document) Close() {\n\tC.destroy_document(self.handle)\n}\n\nfunc (self *Document) GetType() int {\n\treturn int(C.get_document_type(self.handle))\n}\n\nfunc (self *Document) GetParts() int {\n\treturn int(C.get_document_parts(self.handle))\n}\n\nfunc (self *Document) GetPart() int {\n\treturn int(C.get_document_part(self.handle))\n}\n\nfunc (self *Document) SetPart(part int) {\n\tC.set_document_part(self.handle, C.int(part))\n}\n\nfunc (self *Document) GetPartName(part int) string {\n\tc_part := C.int(part)\n\tc_part_name := C.get_document_part_name(self.handle, c_part)\n\tdefer C.free(unsafe.Pointer(c_part_name))\n\treturn C.GoString(c_part_name)\n}\n\nfunc (self *Document) GetSize() (int, int) {\n\twidth := C.long(0)\n\theigth := C.long(0)\n\tC.get_document_size(self.handle, &width, &heigth)\n\treturn int(width), int(heigth)\n}\n\nfunc (self *Document) InitializeForRendering(arguments string) {\n\tc_arguments := C.CString(arguments)\n\tdefer C.free(unsafe.Pointer(c_arguments))\n\tC.initialize_for_rendering(self.handle, c_arguments)\n}\n\nfunc (self *Document) SaveAs(path string, format string, filter string) error {\n\tc_path := C.CString(path)\n\tdefer C.free(unsafe.Pointer(c_path))\n\tc_format := C.CString(format)\n\tdefer C.free(unsafe.Pointer(c_format))\n\tc_filter := C.CString(filter)\n\tdefer C.free(unsafe.Pointer(c_filter))\n\tstatus := C.document_save(self.handle, c_path, c_format, c_filter)\n\tif status != 0 {\n\t\treturn fmt.Errorf(\"Failed to save document\")\n\t} else {\n\t\treturn nil\n\t}\n}\n<commit_msg>Add documentation to Document struct and its methods<commit_after>package libreofficekit\n\n\/*\n#cgo CFLAGS: -I .\/ -D LOK_USE_UNSTABLE_API\n#cgo LDFLAGS: -ldl\n#include <lokbridge.h>\n*\/\nimport \"C\"\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"unsafe\"\n)\n\ntype Office struct {\n\thandle *C.struct__LibreOfficeKit\n\tmutex  *sync.Mutex\n}\n\nfunc NewOffice(path string) (*Office, error) {\n\toffice := new(Office)\n\n\tc_path := C.CString(path)\n\tdefer C.free(unsafe.Pointer(c_path))\n\n\tlokit := C.lok_init(c_path)\n\tif lokit == nil {\n\t\treturn nil, fmt.Errorf(\"Failed to initialize LibreOfficeKit with path: '%s'\", path)\n\t}\n\n\toffice.handle = lokit\n\toffice.mutex = &sync.Mutex{}\n\n\treturn office, nil\n\n}\n\nfunc (self *Office) Close() {\n\tC.destroy_office(self.handle)\n}\n\nfunc (self *Office) GetError() string {\n\tmessage := C.get_error(self.handle)\n\treturn C.GoString(message)\n}\n\nfunc (self *Office) LoadDocument(path string) (*Document, error) {\n\tdocument := new(Document)\n\tc_path := C.CString(path)\n\tdefer C.free(unsafe.Pointer(c_path))\n\thandle := C.document_load(self.handle, c_path)\n\tif handle == nil {\n\t\treturn nil, fmt.Errorf(\"Failed to load document\")\n\t}\n\tdocument.handle = handle\n\treturn document, nil\n}\n\n\/\/ Types of documents returned by Document.GetType function\nconst (\n\tTextDocument = iota\n\tSpreadsheetDocument\n\tPresentationDocument\n\tDrawingDocument\n\tOtherDocument\n)\n\ntype Document struct {\n\thandle *C.struct__LibreOfficeKitDocument\n}\n\nfunc (self *Document) Close() {\n\tC.destroy_document(self.handle)\n}\n\n\/\/ Returns type of loaded document\nfunc (self *Document) GetType() int {\n\treturn int(C.get_document_type(self.handle))\n}\n\n\/\/ Returns count of slides (for presentations) or pages (for text documents)\nfunc (self *Document) GetParts() int {\n\treturn int(C.get_document_parts(self.handle))\n}\n\n\/\/ GetPart returns current part of document, e.g.\n\/\/ if document was just loaded it's current part will be 0\nfunc (self *Document) GetPart() int {\n\treturn int(C.get_document_part(self.handle))\n}\n\n\/\/ SetPart updates current part of document\nfunc (self *Document) SetPart(part int) {\n\tC.set_document_part(self.handle, C.int(part))\n}\n\n\/\/ Returns current slide title (for presentations) or page title (for text documents)\nfunc (self *Document) GetPartName(part int) string {\n\tc_part := C.int(part)\n\tc_part_name := C.get_document_part_name(self.handle, c_part)\n\tdefer C.free(unsafe.Pointer(c_part_name))\n\treturn C.GoString(c_part_name)\n}\n\n\/\/ GetSize returns width and height of document in twips (1 Twip = 1\/1440th of an inch)\n\/\/ You can convert twips to pixels by this formula: (width or height) * (1.0 \/ 1440.0) * DPI\nfunc (self *Document) GetSize() (int, int) {\n\twidth := C.long(0)\n\theigth := C.long(0)\n\tC.get_document_size(self.handle, &width, &heigth)\n\treturn int(width), int(heigth)\n}\n\n\/\/ Must be called before performing any rendering-related actions\nfunc (self *Document) InitializeForRendering(arguments string) {\n\tc_arguments := C.CString(arguments)\n\tdefer C.free(unsafe.Pointer(c_arguments))\n\tC.initialize_for_rendering(self.handle, c_arguments)\n}\n\n\/\/ Saves document at desired path in desired format with applied filter rules\n\/\/ Actual (from libreoffice) error message can be read with Office.GetError\nfunc (self *Document) SaveAs(path string, format string, filter string) error {\n\tc_path := C.CString(path)\n\tdefer C.free(unsafe.Pointer(c_path))\n\tc_format := C.CString(format)\n\tdefer C.free(unsafe.Pointer(c_format))\n\tc_filter := C.CString(filter)\n\tdefer C.free(unsafe.Pointer(c_filter))\n\tstatus := C.document_save(self.handle, c_path, c_format, c_filter)\n\tif status != 0 {\n\t\treturn fmt.Errorf(\"Failed to save document\")\n\t} else {\n\t\treturn nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package errors\n\nimport (\n\t\"testing\"\n)\n\nfunc TestTrimSourcePath(t *testing.T) {\n\tcases := []struct {\n\t\tname, path, trim string\n\t}{\n\t\t{\"main.main\", \"D:\/Gowork\/src\/github.com\/y4v8\/test\/main.go\", \"main.go\"},\n\t\t{\"main.main\", \"D:\/main.go\", \"main.go\"},\n\t\t{\"github.com\/y4v8\/test\/m.MyFunc\", \"D:\/Gowork\/src\/github.com\/y4v8\/test\/m\/tst.go\", \"github.com\/y4v8\/test\/m\/tst.go\"},\n\t}\n\n\tfor _, c := range cases {\n\t\ttrim := trimSourcePath(c.name, c.path)\n\t\tif trim != c.trim {\n\t\t\tt.Errorf(`[%v] for path=[%v], want [%v]`, trim, c.path, c.trim)\n\t\t}\n\t}\n}\n<commit_msg>added tests<commit_after>package errors\n\nimport (\n\t\"testing\"\n\t\"strings\"\n\te \"errors\"\n)\n\nfunc TestTrimSourcePath(t *testing.T) {\n\tcases := []struct {\n\t\tname, path, result string\n\t}{\n\t\t{\n\t\t\tname:   \"main.main\",\n\t\t\tpath:   \"D:\/Gowork\/src\/github.com\/y4v8\/test\/main.go\",\n\t\t\tresult: \"main.go\",\n\t\t}, {\n\t\t\tname:   \"main.main\",\n\t\t\tpath:   \"D:\/main.go\",\n\t\t\tresult: \"main.go\",\n\t\t}, {\n\t\t\tname:   \"github.com\/y4v8\/test\/m.MyFunc\",\n\t\t\tpath:   \"D:\/Gowork\/src\/github.com\/y4v8\/test\/m\/tst.go\",\n\t\t\tresult: \"github.com\/y4v8\/test\/m\/tst.go\",\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tresult := trimSourcePath(c.name, c.path)\n\n\t\tif result != c.result {\n\t\t\tt.Errorf(`(\"%v\", \"%v\") = \"%v\", expected \"%v\"`, c.name, c.path, result, c.result)\n\t\t}\n\t}\n}\n\nfunc TestNew(t *testing.T) {\n\tcases := []struct {\n\t\ttext   string\n\t\tparams []interface{}\n\t\tsuffix string\n\t}{\n\t\t{\n\t\t\ttext:   \"test error %v %v %v\",\n\t\t\tparams: []interface{}{1, 2, 3},\n\t\t\tsuffix: \"test error 1 2 3\",\n\t\t}, {\n\t\t\ttext:   \"test error\",\n\t\t\tparams: nil,\n\t\t\tsuffix: \"test error\",\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\terr := New(c.text, c.params...)\n\n\t\tresult := err.Error()\n\t\tif !strings.HasSuffix(result, c.suffix) {\n\t\t\tt.Errorf(`(\"%v\", %v) = \"%v\", expected \"%v\"`, c.text, c.params, result, c.suffix)\n\t\t}\n\t}\n}\n\nfunc TestAppend(t *testing.T) {\n\tcases := []struct {\n\t\terr      error\n\t\ttext     string\n\t\tparams   []interface{}\n\t\tsuffixes []string\n\t}{\n\t\t{\n\t\t\terr:      e.New(\"test error\"),\n\t\t\ttext:     \"append error %v %v %v\",\n\t\t\tparams:   []interface{}{1, 2, 3},\n\t\t\tsuffixes: []string{\"test error\", \"append error 1 2 3\"},\n\t\t}, {\n\t\t\terr:      nil,\n\t\t\ttext:     \"append error %v %v %v\",\n\t\t\tparams:   []interface{}{1, 2, 3},\n\t\t\tsuffixes: []string{\"append error 1 2 3\"},\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\terr := Append(c.err, c.text, c.params...)\n\n\t\tresult := errorSuffixes(err, c.suffixes)\n\n\t\tresultString := strings.Join(result, \",\")\n\t\ttestString := strings.Join(c.suffixes, \",\")\n\t\tif resultString != testString {\n\t\t\tt.Errorf(`(\"%v\", \"%v\", %v) = %v, expected %v`, c.err, c.text, c.params, result, c.suffixes)\n\t\t}\n\t}\n}\n\nfunc TestWrap(t *testing.T) {\n\tcases := []struct {\n\t\terrors   []error\n\t\tsuffixes []string\n\t}{\n\t\t{\n\t\t\terrors:   []error{e.New(\"error1\"), e.New(\"error2\"), e.New(\"error3\")},\n\t\t\tsuffixes: []string{\"error1\", \"error2\", \"error3\"},\n\t\t}, {\n\t\t\terrors:   []error{nil},\n\t\t\tsuffixes: []string{\"\"},\n\t\t}, {\n\t\t\terrors:   []error{nil, e.New(\"error2\"), e.New(\"error3\")},\n\t\t\tsuffixes: []string{\"error2\", \"error3\"},\n\t\t}, {\n\t\t\terrors:   []error{e.New(\"error1\"), nil, e.New(\"error3\")},\n\t\t\tsuffixes: []string{\"error1\", \"error3\"},\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\terr := Wrap(c.errors...)\n\n\t\tresult := errorSuffixes(err, c.suffixes)\n\n\t\tresultString := strings.Join(result, \",\")\n\t\ttestString := strings.Join(c.suffixes, \",\")\n\t\tif resultString != testString {\n\t\t\tt.Errorf(`(%v) = %v, expected %v`, c.errors, result, c.suffixes)\n\t\t}\n\t}\n}\n\nfunc errorSuffixes(err error, suffixes []string) []string {\n\tif err == nil {\n\t\treturn []string{}\n\t}\n\tsplit := strings.Split(err.Error(), \"\\n\")\n\tresult := make([]string, len(split))\n\tfor i := range split {\n\t\tif len(split[i]) > len(suffixes[i]) {\n\t\t\tresult[i] = split[i][len(split[i])-len(suffixes[i]):]\n\t\t} else {\n\t\t\tresult[i] = split[i]\n\t\t}\n\t}\n\treturn result\n}\n<|endoftext|>"}
{"text":"<commit_before>package dsl_test\n\nimport (\n\t\"testing\"\n\n\t\"reflect\"\n\n\t\"github.com\/goadesign\/goa\/design\"\n\t. \"github.com\/goadesign\/goa\/design\/dsl\"\n\t\"github.com\/goadesign\/goa\/eval\"\n)\n\nfunc TestEndpoint(t *testing.T) {\n\tcases := map[string]struct {\n\t\tExpr   eval.Expression\n\t\tDSL    func()\n\t\tAssert map[string]func(t *testing.T, s *design.EndpointExpr)\n\t}{\n\t\t\"basic\": {\n\t\t\t&design.ServiceExpr{},\n\t\t\tfunc() {\n\t\t\t\tEndpoint(\"basic\", func() {\n\t\t\t\t\tDescription(\"Optional description\")\n\t\t\t\t\t\/\/ Docs allows linking to external documentation.\n\t\t\t\t\tDocs(func() {\n\t\t\t\t\t\tDescription(\"Optional description\")\n\t\t\t\t\t\tURL(\"https:\/\/goa.design\")\n\t\t\t\t\t})\n\t\t\t\t\tRequest(func() {\n\t\t\t\t\t\tDescription(\"Optional description\")\n\t\t\t\t\t\tAttribute(\"required\", design.String)\n\t\t\t\t\t\tRequired(\"required\")\n\t\t\t\t\t})\n\t\t\t\t\tResponse(func() {\n\t\t\t\t\t\tDescription(\"Optional description\")\n\t\t\t\t\t\tAttribute(\"required\", design.String)\n\t\t\t\t\t\tRequired(\"required\")\n\t\t\t\t\t})\n\t\t\t\t\tError(\"basic_error\")\n\t\t\t\t\tError(\"basic_media_error\", design.ErrorMedia)\n\t\t\t\t\tMetadata(\"name\", \"some value\", \"some other value\")\n\t\t\t\t})\n\t\t\t\tEndpoint(\"another\", func() {\n\t\t\t\t\t\/\/ Docs allows linking to external documentation.\n\t\t\t\t\tDocs(func() {\n\t\t\t\t\t\tDescription(\"Optional description\")\n\t\t\t\t\t\tURL(\"https:\/\/goa.design\")\n\t\t\t\t\t})\n\t\t\t\t\tRequest(design.String)\n\t\t\t\t\tResponse(design.String)\n\t\t\t\t\tError(\"basic_media_error\", design.ErrorMedia)\n\t\t\t\t})\n\t\t\t},\n\t\t\tmap[string]func(t *testing.T, s *design.EndpointExpr){\n\t\t\t\t\"basic\": func(t *testing.T, e *design.EndpointExpr) {\n\t\t\t\t\tassertEndpointDescription(t, \"Optional description\", e.Description)\n\t\t\t\t\tassertEndpointDocs(t, e.Docs, \"https:\/\/goa.design\", \"Optional description\")\n\t\t\t\t\tif len(e.Errors) != 2 {\n\t\t\t\t\t\tt.Errorf(\"expected %d error definitions but got %d \", 2, len(e.Errors))\n\t\t\t\t\t}\n\t\t\t\t\tassertEndpointError(t, e.Errors[0], \"basic_error\", design.ErrorMedia)\n\t\t\t\t\tassertEndpointError(t, e.Errors[1], \"basic_media_error\", design.ErrorMedia)\n\t\t\t\t\texpectedMeta := design.MetadataExpr{\n\t\t\t\t\t\t\"name\": []string{\"some value\", \"some other value\"},\n\t\t\t\t\t}\n\t\t\t\t\tassertEndpointMetaData(t, e.Metadata, expectedMeta)\n\t\t\t\t\texpectedReq := &design.UserTypeExpr{\n\t\t\t\t\t\tTypeName:      \"BasicRequest\",\n\t\t\t\t\t\tAttributeExpr: &design.AttributeExpr{Description: \"Optional description\", Type: &design.Object{}}}\n\t\t\t\t\tassertEndpointRequestResponse(t, \"Request\", e.Request, expectedReq)\n\t\t\t\t\texpectedRes := &design.UserTypeExpr{\n\t\t\t\t\t\tTypeName:      \"BasicResponse\",\n\t\t\t\t\t\tAttributeExpr: &design.AttributeExpr{Description: \"Optional description\", Type: &design.Object{}}}\n\t\t\t\t\tassertEndpointRequestResponse(t, \"Response\", e.Response, expectedRes)\n\t\t\t\t},\n\t\t\t\t\"another\": func(t *testing.T, e *design.EndpointExpr) {\n\t\t\t\t\tassertEndpointDocs(t, e.Docs, \"https:\/\/goa.design\", \"Optional description\")\n\t\t\t\t\tif len(e.Errors) != 1 {\n\t\t\t\t\t\tt.Errorf(\"expected %d error definitions but got %d \", 1, len(e.Errors))\n\t\t\t\t\t}\n\t\t\t\t\tassertEndpointError(t, e.Errors[0], \"basic_media_error\", design.ErrorMedia)\n\t\t\t\t\texpectedReq := &design.UserTypeExpr{TypeName: \"AnotherRequest\", AttributeExpr: &design.AttributeExpr{Type: design.String}}\n\t\t\t\t\tassertEndpointRequestResponse(t, \"Request\", e.Request, expectedReq)\n\t\t\t\t\texpectedRes := &design.UserTypeExpr{TypeName: \"AnotherResponse\", AttributeExpr: &design.AttributeExpr{Type: design.String}}\n\t\t\t\t\tassertEndpointRequestResponse(t, \"Response\", e.Response, expectedRes)\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\t\/\/Run our tests\n\tfor k, tc := range cases {\n\t\tt.Run(k, func(t *testing.T) {\n\t\t\teval.Context = &eval.DSLContext{}\n\t\t\teval.Execute(tc.DSL, tc.Expr)\n\t\t\tevalService := tc.Expr.(*design.ServiceExpr)\n\t\t\tif eval.Context.Errors != nil {\n\t\t\t\tt.Errorf(\"%s: Endpoint failed unexpectedly with %s\", k, eval.Context.Errors)\n\t\t\t}\n\t\t\tfor _, e := range evalService.Endpoints {\n\t\t\t\tif _, ok := tc.Assert[e.Name]; !ok {\n\t\t\t\t\tt.Errorf(\"no assert found for endpoint %s \", e.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttc.Assert[e.Name](t, e)\n\t\t\t}\n\t\t})\n\t}\n}\n\n\/\/helper funcs\nfunc assertEndpointDocs(t *testing.T, doc *design.DocsExpr, url, desc string) {\n\tif doc.Description != desc {\n\t\tt.Errorf(\"expected docs description '%s' to match '%s' \", desc, doc.Description)\n\t}\n\tif doc.URL != url {\n\t\tt.Errorf(\"expected docs url '%s' to match '%s' \", url, doc.URL)\n\t}\n}\n\nfunc assertEndpointDescription(t *testing.T, expectedDesc, actualDesc string) {\n\tif expectedDesc != actualDesc {\n\t\tt.Errorf(\"expected description '%s' to match '%s' \", actualDesc, expectedDesc)\n\t}\n}\n\nfunc assertEndpointError(t *testing.T, actual *design.ErrorExpr, name string, dt design.DataType) {\n\tif actual.Name != name {\n\t\tt.Errorf(\"expected error to have name %s but got %s \", name, actual.Name)\n\t}\n\n\tif actual.AttributeExpr.Type != dt {\n\t\tt.Errorf(\"expected the error DataType to be %v but got %v \", dt, actual.AttributeExpr.Type)\n\t}\n}\n\nfunc assertEndpointMetaData(t *testing.T, actual design.MetadataExpr, expected design.MetadataExpr) {\n\tfor key, val := range actual {\n\t\tvals, ok := expected[key]\n\t\tif !ok {\n\t\t\tt.Errorf(\"metaData was missing expected key %s \", key)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, metaVal := range val {\n\t\t\tif !hasValue(vals, metaVal) {\n\t\t\t\tt.Errorf(\"metaData was missing expected value %s \", metaVal)\n\t\t\t}\n\t\t}\n\n\t}\n}\n\nfunc assertEndpointRequestResponse(t *testing.T, assertType string, actual design.DataType, expected *design.UserTypeExpr) {\n\tut, ok := actual.(*design.UserTypeExpr)\n\tif !ok {\n\t\tt.Errorf(\"expected endpoint %s to be a *UserTypeExpr but got %v\", assertType, reflect.TypeOf(ut))\n\t}\n\tif ut.Name() != expected.Name() {\n\t\tt.Errorf(\"expected endpoint %s name %s to match %s\", assertType, ut.Name(), expected.Name())\n\t}\n\tif ut.AttributeExpr.Type.Name() != expected.Type.Name() {\n\t\tt.Errorf(\"expected endpoint %s TypeName %s to match %s \", assertType, ut.Type.Name(), expected.Type.Name())\n\t}\n\tif ut.Description != expected.Description {\n\t\tt.Errorf(\"expected endpoint %s description %s to match %s\", assertType, ut.Description, expected.Description)\n\t}\n\n}\n<commit_msg>add nil check<commit_after>package dsl_test\n\nimport (\n\t\"testing\"\n\n\t\"reflect\"\n\n\t\"github.com\/goadesign\/goa\/design\"\n\t. \"github.com\/goadesign\/goa\/design\/dsl\"\n\t\"github.com\/goadesign\/goa\/eval\"\n)\n\nfunc TestEndpoint(t *testing.T) {\n\tcases := map[string]struct {\n\t\tExpr   eval.Expression\n\t\tDSL    func()\n\t\tAssert map[string]func(t *testing.T, s *design.EndpointExpr)\n\t}{\n\t\t\"basic\": {\n\t\t\t&design.ServiceExpr{},\n\t\t\tfunc() {\n\t\t\t\tEndpoint(\"basic\", func() {\n\t\t\t\t\tDescription(\"Optional description\")\n\t\t\t\t\t\/\/ Docs allows linking to external documentation.\n\t\t\t\t\tDocs(func() {\n\t\t\t\t\t\tDescription(\"Optional description\")\n\t\t\t\t\t\tURL(\"https:\/\/goa.design\")\n\t\t\t\t\t})\n\t\t\t\t\tRequest(func() {\n\t\t\t\t\t\tDescription(\"Optional description\")\n\t\t\t\t\t\tAttribute(\"required\", design.String)\n\t\t\t\t\t\tRequired(\"required\")\n\t\t\t\t\t})\n\t\t\t\t\tResponse(func() {\n\t\t\t\t\t\tDescription(\"Optional description\")\n\t\t\t\t\t\tAttribute(\"required\", design.String)\n\t\t\t\t\t\tRequired(\"required\")\n\t\t\t\t\t})\n\t\t\t\t\tError(\"basic_error\")\n\t\t\t\t\tError(\"basic_media_error\", design.ErrorMedia)\n\t\t\t\t\tMetadata(\"name\", \"some value\", \"some other value\")\n\t\t\t\t})\n\t\t\t\tEndpoint(\"another\", func() {\n\t\t\t\t\t\/\/ Docs allows linking to external documentation.\n\t\t\t\t\tDocs(func() {\n\t\t\t\t\t\tDescription(\"Optional description\")\n\t\t\t\t\t\tURL(\"https:\/\/goa.design\")\n\t\t\t\t\t})\n\t\t\t\t\tRequest(design.String)\n\t\t\t\t\tResponse(design.String)\n\t\t\t\t\tError(\"basic_media_error\", design.ErrorMedia)\n\t\t\t\t})\n\t\t\t},\n\t\t\tmap[string]func(t *testing.T, s *design.EndpointExpr){\n\t\t\t\t\"basic\": func(t *testing.T, e *design.EndpointExpr) {\n\t\t\t\t\tassertEndpointDescription(t, \"Optional description\", e.Description)\n\t\t\t\t\tassertEndpointDocs(t, e.Docs, \"https:\/\/goa.design\", \"Optional description\")\n\t\t\t\t\tif len(e.Errors) != 2 {\n\t\t\t\t\t\tt.Errorf(\"expected %d error definitions but got %d \", 2, len(e.Errors))\n\t\t\t\t\t}\n\t\t\t\t\tassertEndpointError(t, e.Errors[0], \"basic_error\", design.ErrorMedia)\n\t\t\t\t\tassertEndpointError(t, e.Errors[1], \"basic_media_error\", design.ErrorMedia)\n\t\t\t\t\texpectedMeta := design.MetadataExpr{\n\t\t\t\t\t\t\"name\": []string{\"some value\", \"some other value\"},\n\t\t\t\t\t}\n\t\t\t\t\tassertEndpointMetaData(t, e.Metadata, expectedMeta)\n\t\t\t\t\texpectedReq := &design.UserTypeExpr{\n\t\t\t\t\t\tTypeName:      \"BasicRequest\",\n\t\t\t\t\t\tAttributeExpr: &design.AttributeExpr{Description: \"Optional description\", Type: &design.Object{}}}\n\t\t\t\t\tassertEndpointRequestResponse(t, \"Request\", e.Request, expectedReq)\n\t\t\t\t\texpectedRes := &design.UserTypeExpr{\n\t\t\t\t\t\tTypeName:      \"BasicResponse\",\n\t\t\t\t\t\tAttributeExpr: &design.AttributeExpr{Description: \"Optional description\", Type: &design.Object{}}}\n\t\t\t\t\tassertEndpointRequestResponse(t, \"Response\", e.Response, expectedRes)\n\t\t\t\t},\n\t\t\t\t\"another\": func(t *testing.T, e *design.EndpointExpr) {\n\t\t\t\t\tassertEndpointDocs(t, e.Docs, \"https:\/\/goa.design\", \"Optional description\")\n\t\t\t\t\tif len(e.Errors) != 1 {\n\t\t\t\t\t\tt.Errorf(\"expected %d error definitions but got %d \", 1, len(e.Errors))\n\t\t\t\t\t}\n\t\t\t\t\tassertEndpointError(t, e.Errors[0], \"basic_media_error\", design.ErrorMedia)\n\t\t\t\t\texpectedReq := &design.UserTypeExpr{TypeName: \"AnotherRequest\", AttributeExpr: &design.AttributeExpr{Type: design.String}}\n\t\t\t\t\tassertEndpointRequestResponse(t, \"Request\", e.Request, expectedReq)\n\t\t\t\t\texpectedRes := &design.UserTypeExpr{TypeName: \"AnotherResponse\", AttributeExpr: &design.AttributeExpr{Type: design.String}}\n\t\t\t\t\tassertEndpointRequestResponse(t, \"Response\", e.Response, expectedRes)\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\t\/\/Run our tests\n\tfor k, tc := range cases {\n\t\tt.Run(k, func(t *testing.T) {\n\t\t\teval.Context = &eval.DSLContext{}\n\t\t\teval.Execute(tc.DSL, tc.Expr)\n\t\t\tevalService := tc.Expr.(*design.ServiceExpr)\n\t\t\tif eval.Context.Errors != nil {\n\t\t\t\tt.Errorf(\"%s: Endpoint failed unexpectedly with %s\", k, eval.Context.Errors)\n\t\t\t}\n\t\t\tfor _, e := range evalService.Endpoints {\n\t\t\t\tif _, ok := tc.Assert[e.Name]; !ok {\n\t\t\t\t\tt.Errorf(\"no assert found for endpoint %s \", e.Name)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\ttc.Assert[e.Name](t, e)\n\t\t\t}\n\t\t})\n\t}\n}\n\n\/\/helper funcs\nfunc assertEndpointDocs(t *testing.T, doc *design.DocsExpr, url, desc string) {\n\tif doc.Description != desc {\n\t\tt.Errorf(\"expected docs description '%s' to match '%s' \", desc, doc.Description)\n\t}\n\tif doc.URL != url {\n\t\tt.Errorf(\"expected docs url '%s' to match '%s' \", url, doc.URL)\n\t}\n}\n\nfunc assertEndpointDescription(t *testing.T, expectedDesc, actualDesc string) {\n\tif expectedDesc != actualDesc {\n\t\tt.Errorf(\"expected description '%s' to match '%s' \", actualDesc, expectedDesc)\n\t}\n}\n\nfunc assertEndpointError(t *testing.T, actual *design.ErrorExpr, name string, dt design.DataType) {\n\tif actual.Name != name {\n\t\tt.Errorf(\"expected error to have name %s but got %s \", name, actual.Name)\n\t}\n\n\tif actual.AttributeExpr.Type != dt {\n\t\tt.Errorf(\"expected the error DataType to be %v but got %v \", dt, actual.AttributeExpr.Type)\n\t}\n}\n\nfunc assertEndpointMetaData(t *testing.T, actual design.MetadataExpr, expected design.MetadataExpr) {\n\tfor key, val := range actual {\n\t\tvals, ok := expected[key]\n\t\tif !ok {\n\t\t\tt.Errorf(\"metaData was missing expected key %s \", key)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, metaVal := range val {\n\t\t\tif !hasValue(vals, metaVal) {\n\t\t\t\tt.Errorf(\"metaData was missing expected value %s \", metaVal)\n\t\t\t}\n\t\t}\n\n\t}\n}\n\nfunc assertEndpointRequestResponse(t *testing.T, assertType string, actual design.DataType, expected *design.UserTypeExpr) {\n\tut, ok := actual.(*design.UserTypeExpr)\n\tif !ok || ut == nil {\n\t\tt.Errorf(\"expected endpoint %s to be a *UserTypeExpr but got %v\", assertType, reflect.TypeOf(ut))\n\t}\n\tif ut.Name() != expected.Name() {\n\t\tt.Errorf(\"expected endpoint %s name %s to match %s\", assertType, ut.Name(), expected.Name())\n\t}\n\tif ut.AttributeExpr.Type.Name() != expected.Type.Name() {\n\t\tt.Errorf(\"expected endpoint %s TypeName %s to match %s \", assertType, ut.Type.Name(), expected.Type.Name())\n\t}\n\tif ut.Description != expected.Description {\n\t\tt.Errorf(\"expected endpoint %s description %s to match %s\", assertType, ut.Description, expected.Description)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package controllers\n\nimport (\n\t\"fmt\"\n\t\"github.com\/shopspring\/decimal\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\n\tcommon \"github.com\/nttdots\/go-dots\/dots_common\"\n\t\"github.com\/nttdots\/go-dots\/dots_common\/messages\"\n\t\"github.com\/nttdots\/go-dots\/dots_server\/models\"\n\tdots_config \"github.com\/nttdots\/go-dots\/dots_server\/config\"\n)\n\n\/*\n * Controller for the session_configuration API.\n *\/\ntype SessionConfiguration struct {\n\tController\n}\n\nfunc (m *SessionConfiguration) HandleGet(request Request, customer *models.Customer) (res Response, err error) {\n        log.Debugf(\"[GET]SessionConfig customer.Id=%+v\", customer.Id)\n\tsignalSessionConfiguration, err := models.GetCurrentSignalSessionConfiguration(customer.Id)\n\tif err != nil {\n\t\tres = Response{\n\t\t\tType: common.NonConfirmable,\n\t\t\tCode: common.BadRequest,\n\t\t\tBody: nil,\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ TODO: check found or not\n\n\tconfig := dots_config.GetServerSystemConfig().SignalConfigurationParameter\n\n\tresp := messages.ConfigurationResponse{}\n\tresp.SignalConfigs = messages.ConfigurationResponseConfigs{}\n\tresp.SignalConfigs.MitigationConfig = messages.ConfigurationResponseConfig{}\n\tresp.SignalConfigs.MitigationConfig.HeartbeatInterval.SetMinMax(config.HeartbeatInterval)\n\tresp.SignalConfigs.MitigationConfig.MissingHbAllowed.SetMinMax(config.MissingHbAllowed)\n\tresp.SignalConfigs.MitigationConfig.MaxRetransmit.SetMinMax(config.MaxRetransmit)\n\tresp.SignalConfigs.MitigationConfig.AckTimeout.SetMinMax(config.AckTimeout)\n\tresp.SignalConfigs.MitigationConfig.AckRandomFactor.SetMinMax(config.AckRandomFactor)\n\n\tresp.SignalConfigs.MitigationConfig.HeartbeatInterval.CurrentValue = signalSessionConfiguration.HeartbeatInterval\n\tresp.SignalConfigs.MitigationConfig.MissingHbAllowed.CurrentValue  = signalSessionConfiguration.MissingHbAllowed\n\tresp.SignalConfigs.MitigationConfig.MaxRetransmit.CurrentValue     = signalSessionConfiguration.MaxRetransmit\n\tresp.SignalConfigs.MitigationConfig.AckTimeout.CurrentValue        = signalSessionConfiguration.AckTimeout\n\tresp.SignalConfigs.MitigationConfig.AckRandomFactor.CurrentValue   = decimal.NewFromFloat(signalSessionConfiguration.AckRandomFactor)\n\tresp.SignalConfigs.MitigationConfig.TriggerMitigation              = signalSessionConfiguration.TriggerMitigation\n\n\t\/\/ TODO: support Idle-Config\n\tres = Response{\n\t\t\tType: common.NonConfirmable,\n\t\t\tCode: common.Content,\n\t\t\tBody: resp,\n\t}\n\n\treturn\n}\n\n\/*\n * Handles session_configuration PUT requests and start the mitigation.\n *  1. Validate the received session configuration requests.\n *  2. return the validation results.\n *\n * parameter:\n *  request request message\n *  customer request source Customer\n * return:\n *  res response message\n *  err error\n *\/\nfunc (m *SessionConfiguration) HandlePut(newRequest Request, customer *models.Customer) (res Response, err error) {\n\n\trequest := newRequest.Body\n\n\tif request == nil {\n\t\tres = Response{\n\t\t\tType: common.NonConfirmable,\n\t\t\tCode: common.BadRequest,\n\t\t\tBody: nil,\n\t\t}\n\t\treturn\n\t}\n\n\tpayload := &request.(*messages.SignalConfigRequest).SignalConfigs.MitigationConfig\n\tsessionConfigurationPayloadDisplay(payload)\n\t\/\/ TODO: support IdleConfig, draft-17+\n\n\tackRandomFactor, _ := payload.AckRandomFactor.CurrentValue.Float64()\n\t\/\/ validate\n\tsignalSessionConfiguration := models.NewSignalSessionConfiguration(\n\t\tpayload.SessionId,\n\t\tpayload.HeartbeatInterval.CurrentValue,\n\t\tpayload.MissingHbAllowed.CurrentValue,\n\t\tpayload.MaxRetransmit.CurrentValue,\n\t\tpayload.AckTimeout.CurrentValue,\n\t\tackRandomFactor,\n\t\tpayload.TriggerMitigation,\n\t)\n\tv := models.SignalConfigurationValidator{}\n\tvalidateResult := v.Validate(signalSessionConfiguration, *customer)\n\tif !validateResult {\n\t\tgoto ResponseNG\n\t} else {\n\t\t\/\/ Register SignalConfigurationParameter\n\t\t_, err = models.CreateSignalSessionConfiguration(*signalSessionConfiguration, *customer)\n\t\tif err != nil {\n\t\t\tgoto ResponseNG\n\t\t}\n\n\t\tgoto ResponseOK\n\t}\n\nResponseNG:\n\/\/ on validation error\n\tres = Response{\n\t\tType: common.NonConfirmable,\n\t\tCode: common.BadRequest,\n\t\tBody: nil,\n\t}\n\treturn\nResponseOK:\n\/\/ on validation success\n\tres = Response{\n\t\tType: common.NonConfirmable,\n\t\tCode: common.Created,\n\t\tBody: nil,\n\t}\n\treturn\n}\n\nfunc (m *SessionConfiguration) HandleDelete(newRequest Request, customer *models.Customer) (res Response, err error) {\n\terr = models.DeleteSignalSessionConfigurationByCustomerId(customer.Id)\n\tif err != nil {\n\t\tres = Response{\n\t\t\tType: common.NonConfirmable,\n\t\t\tCode: common.InternalServerError,\n\t\t\tBody: nil,\n\t\t}\n\t\treturn\n\t}\n\n\tres = Response{\n\t\tType: common.NonConfirmable,\n\t\tCode: common.Deleted,\n\t\tBody: nil,\n\t}\n\treturn\n}\n\n\n\/*\n * Parse the request body and display the contents of the messages to stdout.\n*\/\nfunc sessionConfigurationPayloadDisplay(data *messages.SignalConfig) {\n\n\tvar result string = \"\\n\"\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %d\\n\", \"session-id\", data.SessionId)\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %d\\n\", \"heartbeat-interval\", data.HeartbeatInterval)\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %d\\n\", \"missing-hb-allowed\", data.MissingHbAllowed)\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %d\\n\", \"max-retransmit\", data.MaxRetransmit)\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %d\\n\", \"ack-timeout\", data.AckTimeout)\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %f\\n\", \"ack-random-factor\", data.AckRandomFactor)\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %f\\n\", \"trigger-mitigation\", data.TriggerMitigation)\n\tlog.Infoln(result)\n}\n<commit_msg>Fix response of SessionConfig to CoAP Ack<commit_after>package controllers\n\nimport (\n\t\"fmt\"\n\t\"github.com\/shopspring\/decimal\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\n\tcommon \"github.com\/nttdots\/go-dots\/dots_common\"\n\t\"github.com\/nttdots\/go-dots\/dots_common\/messages\"\n\t\"github.com\/nttdots\/go-dots\/dots_server\/models\"\n\tdots_config \"github.com\/nttdots\/go-dots\/dots_server\/config\"\n)\n\n\/*\n * Controller for the session_configuration API.\n *\/\ntype SessionConfiguration struct {\n\tController\n}\n\nfunc (m *SessionConfiguration) HandleGet(request Request, customer *models.Customer) (res Response, err error) {\n        log.Debugf(\"[GET]SessionConfig customer.Id=%+v\", customer.Id)\n\tsignalSessionConfiguration, err := models.GetCurrentSignalSessionConfiguration(customer.Id)\n\tif err != nil {\n\t\tres = Response{\n\t\t\tType: common.Acknowledgement,\n\t\t\tCode: common.BadRequest,\n\t\t\tBody: nil,\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ TODO: check found or not\n\n\tconfig := dots_config.GetServerSystemConfig().SignalConfigurationParameter\n\n\tresp := messages.ConfigurationResponse{}\n\tresp.SignalConfigs = messages.ConfigurationResponseConfigs{}\n\tresp.SignalConfigs.MitigationConfig = messages.ConfigurationResponseConfig{}\n\tresp.SignalConfigs.MitigationConfig.HeartbeatInterval.SetMinMax(config.HeartbeatInterval)\n\tresp.SignalConfigs.MitigationConfig.MissingHbAllowed.SetMinMax(config.MissingHbAllowed)\n\tresp.SignalConfigs.MitigationConfig.MaxRetransmit.SetMinMax(config.MaxRetransmit)\n\tresp.SignalConfigs.MitigationConfig.AckTimeout.SetMinMax(config.AckTimeout)\n\tresp.SignalConfigs.MitigationConfig.AckRandomFactor.SetMinMax(config.AckRandomFactor)\n\n\tresp.SignalConfigs.MitigationConfig.HeartbeatInterval.CurrentValue = signalSessionConfiguration.HeartbeatInterval\n\tresp.SignalConfigs.MitigationConfig.MissingHbAllowed.CurrentValue  = signalSessionConfiguration.MissingHbAllowed\n\tresp.SignalConfigs.MitigationConfig.MaxRetransmit.CurrentValue     = signalSessionConfiguration.MaxRetransmit\n\tresp.SignalConfigs.MitigationConfig.AckTimeout.CurrentValue        = signalSessionConfiguration.AckTimeout\n\tresp.SignalConfigs.MitigationConfig.AckRandomFactor.CurrentValue   = decimal.NewFromFloat(signalSessionConfiguration.AckRandomFactor)\n\tresp.SignalConfigs.MitigationConfig.TriggerMitigation              = signalSessionConfiguration.TriggerMitigation\n\n\t\/\/ TODO: support Idle-Config\n\tres = Response{\n\t\t\tType: common.Acknowledgement,\n\t\t\tCode: common.Content,\n\t\t\tBody: resp,\n\t}\n\n\treturn\n}\n\n\/*\n * Handles session_configuration PUT requests and start the mitigation.\n *  1. Validate the received session configuration requests.\n *  2. return the validation results.\n *\n * parameter:\n *  request request message\n *  customer request source Customer\n * return:\n *  res response message\n *  err error\n *\/\nfunc (m *SessionConfiguration) HandlePut(newRequest Request, customer *models.Customer) (res Response, err error) {\n\n\trequest := newRequest.Body\n\n\tif request == nil {\n\t\tres = Response{\n\t\t\tType: common.Acknowledgement,\n\t\t\tCode: common.BadRequest,\n\t\t\tBody: nil,\n\t\t}\n\t\treturn\n\t}\n\n\tpayload := &request.(*messages.SignalConfigRequest).SignalConfigs.MitigationConfig\n\tsessionConfigurationPayloadDisplay(payload)\n\t\/\/ TODO: support IdleConfig, draft-17+\n\n\tackRandomFactor, _ := payload.AckRandomFactor.CurrentValue.Float64()\n\t\/\/ validate\n\tsignalSessionConfiguration := models.NewSignalSessionConfiguration(\n\t\tpayload.SessionId,\n\t\tpayload.HeartbeatInterval.CurrentValue,\n\t\tpayload.MissingHbAllowed.CurrentValue,\n\t\tpayload.MaxRetransmit.CurrentValue,\n\t\tpayload.AckTimeout.CurrentValue,\n\t\tackRandomFactor,\n\t\tpayload.TriggerMitigation,\n\t)\n\tv := models.SignalConfigurationValidator{}\n\tvalidateResult := v.Validate(signalSessionConfiguration, *customer)\n\tif !validateResult {\n\t\tgoto ResponseNG\n\t} else {\n\t\t\/\/ Register SignalConfigurationParameter\n\t\t_, err = models.CreateSignalSessionConfiguration(*signalSessionConfiguration, *customer)\n\t\tif err != nil {\n\t\t\tgoto ResponseNG\n\t\t}\n\n\t\tgoto ResponseOK\n\t}\n\nResponseNG:\n\/\/ on validation error\n\tres = Response{\n\t\tType: common.Acknowledgement,\n\t\tCode: common.BadRequest,\n\t\tBody: nil,\n\t}\n\treturn\nResponseOK:\n\/\/ on validation success\n\tres = Response{\n\t\tType: common.Acknowledgement,\n\t\tCode: common.Created,\n\t\tBody: nil,\n\t}\n\treturn\n}\n\nfunc (m *SessionConfiguration) HandleDelete(newRequest Request, customer *models.Customer) (res Response, err error) {\n\terr = models.DeleteSignalSessionConfigurationByCustomerId(customer.Id)\n\tif err != nil {\n\t\tres = Response{\n\t\t\tType: common.Acknowledgement,\n\t\t\tCode: common.InternalServerError,\n\t\t\tBody: nil,\n\t\t}\n\t\treturn\n\t}\n\n\tres = Response{\n\t\tType: common.Acknowledgement,\n\t\tCode: common.Deleted,\n\t\tBody: nil,\n\t}\n\treturn\n}\n\n\n\/*\n * Parse the request body and display the contents of the messages to stdout.\n*\/\nfunc sessionConfigurationPayloadDisplay(data *messages.SignalConfig) {\n\n\tvar result string = \"\\n\"\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %d\\n\", \"session-id\", data.SessionId)\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %d\\n\", \"heartbeat-interval\", data.HeartbeatInterval)\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %d\\n\", \"missing-hb-allowed\", data.MissingHbAllowed)\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %d\\n\", \"max-retransmit\", data.MaxRetransmit)\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %d\\n\", \"ack-timeout\", data.AckTimeout)\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %f\\n\", \"ack-random-factor\", data.AckRandomFactor)\n\tresult += fmt.Sprintf(\"   \\\"%s\\\": %f\\n\", \"trigger-mitigation\", data.TriggerMitigation)\n\tlog.Infoln(result)\n}\n<|endoftext|>"}
{"text":"<commit_before>package dsl_test\n\nimport (\n\t\"testing\"\n\n\t\"fmt\"\n\n\t\"github.com\/goadesign\/goa\/design\"\n\t. \"github.com\/goadesign\/goa\/design\/dsl\"\n\t\"github.com\/goadesign\/goa\/eval\"\n)\n\nfunc TestEndpoint(t *testing.T) {\n\tcases := map[string]struct {\n\t\tExpr   eval.Expression\n\t\tDSL    func()\n\t\tAssert func(testName string, t *testing.T, s *design.ServiceExpr)\n\t}{\n\t\t\"basic endpoint\": {\n\t\t\t&design.ServiceExpr{},\n\t\t\tfunc() {\n\t\t\t\tEndpoint(\"basic\", func() {\n\t\t\t\t\tDescription(\"basic endpoint\")\n\t\t\t\t})\n\t\t\t},\n\t\t\tfunc(testName string, t *testing.T, s *design.ServiceExpr) {\n\t\t\t\tif len(s.Endpoints) != 1 {\n\t\t\t\t\tt.Errorf(\"%s: expected %d endpoints but got %d\", testName, 1, len(s.Endpoints))\n\t\t\t\t}\n\t\t\t\tfor _, e := range s.Endpoints {\n\t\t\t\t\tif err := assertEndpointDescription(\"basic endpoint\", e.Description); err != nil {\n\t\t\t\t\t\tt.Errorf(\"%s assert failed %s \", testName, err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t\"basic endpoint with docs\": {\n\t\t\t&design.ServiceExpr{},\n\t\t\tfunc() {\n\t\t\t\tEndpoint(\"basic\", func() {\n\t\t\t\t\tDescription(\"basic endpoint\")\n\t\t\t\t\tDocs(func() {\n\t\t\t\t\t\tURL(\"http:\/\/example.com\")\n\t\t\t\t\t\tDescription(\"some docs\")\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t},\n\t\t\tfunc(testName string, t *testing.T, s *design.ServiceExpr) {\n\t\t\t\tif len(s.Endpoints) != 1 {\n\t\t\t\t\tt.Errorf(\"%s: expected %d endpoints but got %d\", testName, 1, len(s.Endpoints))\n\t\t\t\t}\n\t\t\t\tfor _, e := range s.Endpoints {\n\t\t\t\t\tif err := assertEndpointDescription(\"basic endpoint\", e.Description); err != nil {\n\t\t\t\t\t\tt.Errorf(\"%s assert failed %s \", testName, err.Error())\n\t\t\t\t\t}\n\t\t\t\t\tif err := assertEndpointDocs(e.Docs, \"http:\/\/example.com\", \"some docs\"); err != nil {\n\t\t\t\t\t\tt.Errorf(\"%s assert failed %s \", testName, err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t}\n\n\tfor k, tc := range cases {\n\t\tt.Run(k, func(t *testing.T) {\n\t\t\teval.Context = &eval.DSLContext{}\n\t\t\teval.Execute(tc.DSL, tc.Expr)\n\t\t\t\/\/After evaling the service our endpoints are present but need to also need to have thier DSL func exectuted.\n\t\t\tevalService := tc.Expr.(*design.ServiceExpr)\n\t\t\tfor _, endpointExp := range evalService.Endpoints {\n\t\t\t\teval.Execute(endpointExp.DSLFunc, endpointExp)\n\t\t\t}\n\t\t\tif eval.Context.Errors != nil {\n\t\t\t\tt.Errorf(\"%s: Endpoint failed unexpectedly with %s\", k, eval.Context.Errors)\n\t\t\t}\n\t\t\tif tc.Assert != nil {\n\t\t\t\ttc.Assert(k, t, evalService)\n\t\t\t}\n\t\t})\n\t}\n}\n\n\/\/helper funcs\nfunc assertEndpointDocs(doc *design.DocsExpr, url, desc string) error {\n\tif doc.Description != desc {\n\t\treturn fmt.Errorf(\"expected docs description '%s' to match '%s' \", desc, doc.Description)\n\t}\n\tif doc.URL != url {\n\t\treturn fmt.Errorf(\"expected docs url '%s' to match '%s' \", url, doc.URL)\n\t}\n\treturn nil\n}\n\nfunc assertEndpointDescription(expectedDesc, actualDesc string) error {\n\tif expectedDesc != actualDesc {\n\t\treturn fmt.Errorf(\"expected description '%s' to match '%s' \", actualDesc, expectedDesc)\n\t}\n\treturn nil\n}\n<commit_msg>another pass at better structure for tests<commit_after>package dsl_test\n\nimport (\n\t\"testing\"\n\n\t\"reflect\"\n\n\t\"github.com\/goadesign\/goa\/design\"\n\t. \"github.com\/goadesign\/goa\/design\/dsl\"\n\t\"github.com\/goadesign\/goa\/eval\"\n)\n\nfunc TestEndpoint(t *testing.T) {\n\tcases := map[string]struct {\n\t\tExpr   eval.Expression\n\t\tDSL    func()\n\t\tAssert map[string]func(t *testing.T, s *design.EndpointExpr)\n\t}{\n\t\t\"basic\": {\n\t\t\t&design.ServiceExpr{},\n\t\t\tfunc() {\n\t\t\t\tEndpoint(\"basic\", func() {\n\t\t\t\t\tDescription(\"Optional description\")\n\n\t\t\t\t\t\/\/ Docs allows linking to external documentation.\n\t\t\t\t\tDocs(func() {\n\t\t\t\t\t\tDescription(\"Optional description\")\n\t\t\t\t\t\tURL(\"https:\/\/goa.design\")\n\t\t\t\t\t})\n\t\t\t\t\tRequest(func() {\n\t\t\t\t\t\tDescription(\"Optional description\")\n\t\t\t\t\t\tAttribute(\"required\", design.String)\n\t\t\t\t\t\tRequired(\"required\")\n\t\t\t\t\t})\n\t\t\t\t\tResponse(func() {\n\t\t\t\t\t\tDescription(\"Optional description\")\n\t\t\t\t\t\tAttribute(\"required\", design.String)\n\t\t\t\t\t\tRequired(\"required\")\n\t\t\t\t\t})\n\t\t\t\t\tError(\"basic_error\")\n\t\t\t\t\tError(\"basic_media_error\", design.ErrorMedia)\n\t\t\t\t\tMetadata(\"name\", \"some value\", \"some other value\")\n\t\t\t\t})\n\t\t\t},\n\t\t\tmap[string]func(t *testing.T, s *design.EndpointExpr){\n\t\t\t\t\"basic\": func(t *testing.T, e *design.EndpointExpr) {\n\t\t\t\t\tassertEndpointDescription(t, \"Optional description\", e.Description)\n\t\t\t\t\tassertEndpointDocs(t, e.Docs, \"https:\/\/goa.design\", \"Optional description\")\n\t\t\t\t\tif len(e.Errors) != 2 {\n\t\t\t\t\t\tt.Errorf(\"expected %d error definitions but got %d \", 1, len(e.Errors))\n\t\t\t\t\t}\n\t\t\t\t\tassertEndpointError(t, e.Errors[0], \"basic_error\", design.ErrorMedia)\n\t\t\t\t\tassertEndpointError(t, e.Errors[1], \"basic_media_error\", design.ErrorMedia)\n\t\t\t\t\texpectedMeta := design.MetadataExpr{\n\t\t\t\t\t\t\"name\": []string{\"some value\", \"some other value\"},\n\t\t\t\t\t}\n\t\t\t\t\tassertEndpointMetaData(t, e.Metadata, expectedMeta)\n\t\t\t\t\texpectedReq := &design.UserTypeExpr{TypeName: \"BasicRequest\"}\n\t\t\t\t\tassertEndpointRequestResponse(t, \"Request\", e.Request, expectedReq)\n\t\t\t\t\texpectedRes := &design.UserTypeExpr{TypeName: \"BasicResponse\"}\n\t\t\t\t\tassertEndpointRequestResponse(t, \"Response\", e.Response, expectedRes)\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\t\/\/Run our tests\n\tfor k, tc := range cases {\n\t\tt.Run(k, func(t *testing.T) {\n\t\t\teval.Context = &eval.DSLContext{}\n\t\t\teval.Execute(tc.DSL, tc.Expr)\n\t\t\tevalService := tc.Expr.(*design.ServiceExpr)\n\t\t\tif eval.Context.Errors != nil {\n\t\t\t\tt.Errorf(\"%s: Endpoint failed unexpectedly with %s\", k, eval.Context.Errors)\n\t\t\t}\n\t\t\tfor _, e := range evalService.Endpoints {\n\t\t\t\tif _, ok := tc.Assert[e.Name]; !ok {\n\t\t\t\t\tt.Errorf(\"no assert found for endpoint %s \", e.Name)\n\t\t\t\t}\n\t\t\t\ttc.Assert[e.Name](t, e)\n\t\t\t}\n\t\t})\n\t}\n}\n\n\/\/helper funcs\nfunc assertEndpointDocs(t *testing.T, doc *design.DocsExpr, url, desc string) {\n\tif doc.Description != desc {\n\t\tt.Errorf(\"expected docs description '%s' to match '%s' \", desc, doc.Description)\n\t}\n\tif doc.URL != url {\n\t\tt.Errorf(\"expected docs url '%s' to match '%s' \", url, doc.URL)\n\t}\n}\n\nfunc assertEndpointDescription(t *testing.T, expectedDesc, actualDesc string) {\n\tif expectedDesc != actualDesc {\n\t\tt.Errorf(\"expected description '%s' to match '%s' \", actualDesc, expectedDesc)\n\t}\n}\n\nfunc assertEndpointError(t *testing.T, actual *design.ErrorExpr, name string, dt design.DataType) {\n\tif actual.Name != name {\n\t\tt.Errorf(\"expected error to have name %s but got %s \", name, actual.Name)\n\t}\n\n\tif actual.AttributeExpr.Type != dt {\n\t\tt.Errorf(\"expected the error DataType to be %v but got %v \", dt, actual.AttributeExpr.Type)\n\t}\n}\n\nfunc assertEndpointMetaData(t *testing.T, actual design.MetadataExpr, expected design.MetadataExpr) {\n\tfor key, val := range actual {\n\t\tvals, ok := expected[key]\n\t\tif !ok {\n\t\t\tt.Errorf(\"metaData was missing expected key %s \", key)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, metaVal := range val {\n\t\t\tif !hasValue(vals, metaVal) {\n\t\t\t\tt.Errorf(\"metaData was missing expected value %s \", metaVal)\n\t\t\t}\n\t\t}\n\n\t}\n}\n\nfunc assertEndpointRequestResponse(t *testing.T, assertType string, actual design.DataType, expected *design.UserTypeExpr) {\n\tut, ok := actual.(*design.UserTypeExpr)\n\tif !ok {\n\t\tt.Errorf(\"expected endpoint %s to be a *UserTypeExpr but got %v\", assertType, reflect.TypeOf(ut))\n\t}\n\tif ut.Name() != expected.Name() {\n\t\tt.Errorf(\"expected endpoint %s name %s to match %s\", assertType, ut.Name(), expected.Name())\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build !appengine\n\npackage aetest\n\nimport (\n\t\"bufio\"\n\t\"crypto\/rand\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/appengine\/internal\"\n)\n\n\/\/ NewInstance launches a running instance of api_server.py which can be used\n\/\/ for multiple test Contexts that delegate all App Engine API calls to that\n\/\/ instance.\n\/\/ If opts is nil the default values are used.\nfunc NewInstance(opts *Options) (Instance, error) {\n\ti := &instance{\n\t\topts:           opts,\n\t\tappID:          \"testapp\",\n\t\tstartupTimeout: 15 * time.Second,\n\t}\n\tif opts != nil {\n\t\tif opts.AppID != \"\" {\n\t\t\ti.appID = opts.AppID\n\t\t}\n\t\tif opts.StartupTimeout > 0 {\n\t\t\ti.startupTimeout = opts.StartupTimeout\n\t\t}\n\t}\n\tif err := i.startChild(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn i, nil\n}\n\nfunc newSessionID() string {\n\tvar buf [16]byte\n\tio.ReadFull(rand.Reader, buf[:])\n\treturn fmt.Sprintf(\"%x\", buf[:])\n}\n\n\/\/ instance implements the Instance interface.\ntype instance struct {\n\topts           *Options\n\tchild          *exec.Cmd\n\tapiURL         *url.URL \/\/ base URL of API HTTP server\n\tadminURL       string   \/\/ base URL of admin HTTP server\n\tappDir         string\n\tappID          string\n\tstartupTimeout time.Duration\n\trelFuncs       []func() \/\/ funcs to release any associated contexts\n}\n\n\/\/ NewRequest returns an *http.Request associated with this instance.\nfunc (i *instance) NewRequest(method, urlStr string, body io.Reader) (*http.Request, error) {\n\treq, err := http.NewRequest(method, urlStr, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Associate this request.\n\treq, release := internal.RegisterTestRequest(req, i.apiURL, func(ctx context.Context) context.Context {\n\t\tctx = internal.WithAppIDOverride(ctx, \"dev~\"+i.appID)\n\t\treturn ctx\n\t})\n\ti.relFuncs = append(i.relFuncs, release)\n\n\treturn req, nil\n}\n\n\/\/ Close kills the child api_server.py process, releasing its resources.\nfunc (i *instance) Close() (err error) {\n\tfor _, rel := range i.relFuncs {\n\t\trel()\n\t}\n\ti.relFuncs = nil\n\tchild := i.child\n\tif child == nil {\n\t\treturn nil\n\t}\n\tdefer func() {\n\t\ti.child = nil\n\t\terr1 := os.RemoveAll(i.appDir)\n\t\tif err == nil {\n\t\t\terr = err1\n\t\t}\n\t}()\n\n\tif p := child.Process; p != nil {\n\t\terrc := make(chan error, 1)\n\t\tgo func() {\n\t\t\terrc <- child.Wait()\n\t\t}()\n\n\t\t\/\/ Call the quit handler on the admin server.\n\t\tres, err := http.Get(i.adminURL + \"\/quit\")\n\t\tif err != nil {\n\t\t\tp.Kill()\n\t\t\treturn fmt.Errorf(\"unable to call \/quit handler: %v\", err)\n\t\t}\n\t\tres.Body.Close()\n\t\tselect {\n\t\tcase <-time.After(15 * time.Second):\n\t\t\tp.Kill()\n\t\t\treturn errors.New(\"timeout killing child process\")\n\t\tcase err = <-errc:\n\t\t\t\/\/ Do nothing.\n\t\t}\n\t}\n\treturn\n}\n\nfunc fileExists(path string) bool {\n\t_, err := os.Stat(path)\n\treturn err == nil\n}\n\nfunc findPython() (path string, err error) {\n\tfor _, name := range []string{\"python2.7\", \"python\"} {\n\t\tpath, err = exec.LookPath(name)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc findDevAppserver() (string, error) {\n\tif p := os.Getenv(\"APPENGINE_DEV_APPSERVER\"); p != \"\" {\n\t\tif fileExists(p) {\n\t\t\treturn p, nil\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"invalid APPENGINE_DEV_APPSERVER environment variable; path %q doesn't exist\", p)\n\t}\n\treturn exec.LookPath(\"dev_appserver.py\")\n}\n\nvar apiServerAddrRE = regexp.MustCompile(`Starting API server at: (\\S+)`)\nvar adminServerAddrRE = regexp.MustCompile(`Starting admin server at: (\\S+)`)\n\nfunc (i *instance) startChild() (err error) {\n\tif PrepareDevAppserver != nil {\n\t\tif err := PrepareDevAppserver(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tpython, err := findPython()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not find python interpreter: %v\", err)\n\t}\n\tdevAppserver, err := findDevAppserver()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not find dev_appserver.py: %v\", err)\n\t}\n\n\ti.appDir, err = ioutil.TempDir(\"\", \"appengine-aetest\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tos.RemoveAll(i.appDir)\n\t\t}\n\t}()\n\terr = os.Mkdir(filepath.Join(i.appDir, \"app\"), 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(filepath.Join(i.appDir, \"app\", \"app.yaml\"), []byte(i.appYAML()), 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(filepath.Join(i.appDir, \"app\", \"stubapp.go\"), []byte(appSource), 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tappserverArgs := []string{\n\t\tdevAppserver,\n\t\t\"--port=0\",\n\t\t\"--api_port=0\",\n\t\t\"--admin_port=0\",\n\t\t\"--automatic_restart=false\",\n\t\t\"--skip_sdk_update_check=true\",\n\t\t\"--clear_datastore=true\",\n\t\t\"--clear_search_indexes=true\",\n\t\t\"--datastore_path\", filepath.Join(i.appDir, \"datastore\"),\n\t}\n\tif i.opts != nil && i.opts.StronglyConsistentDatastore {\n\t\tappserverArgs = append(appserverArgs, \"--datastore_consistency_policy=consistent\")\n\t}\n\tif i.opts != nil && i.opts.SupportDatastoreEmulator != nil {\n\t\tappserverArgs = append(appserverArgs, fmt.Sprintf(\"--support_datastore_emulator=%t\", *i.opts.SupportDatastoreEmulator))\n\t}\n\tappserverArgs = append(appserverArgs, filepath.Join(i.appDir, \"app\"))\n\n\ti.child = exec.Command(python,\n\t\tappserverArgs...,\n\t)\n\ti.child.Stdout = os.Stdout\n\tvar stderr io.Reader\n\tstderr, err = i.child.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = i.child.Start(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Read stderr until we have read the URLs of the API server and admin interface.\n\terrc := make(chan error, 1)\n\tgo func() {\n\t\ts := bufio.NewScanner(stderr)\n\t\tfor s.Scan() {\n\t\t\t\/\/ Pass stderr along as we go so the user can see it.\n\t\t\tif !(i.opts != nil && i.opts.SuppressDevAppServerLog) {\n\t\t\t\tfmt.Fprintln(os.Stderr, s.Text())\n\t\t\t}\n\t\t\tif match := apiServerAddrRE.FindStringSubmatch(s.Text()); match != nil {\n\t\t\t\tu, err := url.Parse(match[1])\n\t\t\t\tif err != nil {\n\t\t\t\t\terrc <- fmt.Errorf(\"failed to parse API URL %q: %v\", match[1], err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ti.apiURL = u\n\t\t\t}\n\t\t\tif match := adminServerAddrRE.FindStringSubmatch(s.Text()); match != nil {\n\t\t\t\ti.adminURL = match[1]\n\t\t\t}\n\t\t\tif i.adminURL != \"\" && i.apiURL != nil {\n\t\t\t\t\/\/ Pass along stderr to the user after we're done with it.\n\t\t\t\tif !(i.opts != nil && i.opts.SuppressDevAppServerLog) {\n\t\t\t\t\tgo io.Copy(os.Stderr, stderr)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\terrc <- s.Err()\n\t}()\n\n\tselect {\n\tcase <-time.After(i.startupTimeout):\n\t\tif p := i.child.Process; p != nil {\n\t\t\tp.Kill()\n\t\t}\n\t\treturn errors.New(\"timeout starting child process\")\n\tcase err := <-errc:\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading child process stderr: %v\", err)\n\t\t}\n\t}\n\tif i.adminURL == \"\" {\n\t\treturn errors.New(\"unable to find admin server URL\")\n\t}\n\tif i.apiURL == nil {\n\t\treturn errors.New(\"unable to find API server URL\")\n\t}\n\treturn nil\n}\n\nfunc (i *instance) appYAML() string {\n\treturn fmt.Sprintf(appYAMLTemplate, i.appID)\n}\n\nconst appYAMLTemplate = `\napplication: %s\nversion: 1\nruntime: go\napi_version: go1\n\nhandlers:\n- url: \/.*\n  script: _go_app\n`\n\nconst appSource = `\npackage main\nimport \"google.golang.org\/appengine\"\nfunc main() { appengine.Main() }\n`\n<commit_msg>aetest: appYAMLTemplate should use runtime: go111 (#214)<commit_after>\/\/ +build !appengine\n\npackage aetest\n\nimport (\n\t\"bufio\"\n\t\"crypto\/rand\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/appengine\/internal\"\n)\n\n\/\/ NewInstance launches a running instance of api_server.py which can be used\n\/\/ for multiple test Contexts that delegate all App Engine API calls to that\n\/\/ instance.\n\/\/ If opts is nil the default values are used.\nfunc NewInstance(opts *Options) (Instance, error) {\n\ti := &instance{\n\t\topts:           opts,\n\t\tappID:          \"testapp\",\n\t\tstartupTimeout: 15 * time.Second,\n\t}\n\tif opts != nil {\n\t\tif opts.AppID != \"\" {\n\t\t\ti.appID = opts.AppID\n\t\t}\n\t\tif opts.StartupTimeout > 0 {\n\t\t\ti.startupTimeout = opts.StartupTimeout\n\t\t}\n\t}\n\tif err := i.startChild(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn i, nil\n}\n\nfunc newSessionID() string {\n\tvar buf [16]byte\n\tio.ReadFull(rand.Reader, buf[:])\n\treturn fmt.Sprintf(\"%x\", buf[:])\n}\n\n\/\/ instance implements the Instance interface.\ntype instance struct {\n\topts           *Options\n\tchild          *exec.Cmd\n\tapiURL         *url.URL \/\/ base URL of API HTTP server\n\tadminURL       string   \/\/ base URL of admin HTTP server\n\tappDir         string\n\tappID          string\n\tstartupTimeout time.Duration\n\trelFuncs       []func() \/\/ funcs to release any associated contexts\n}\n\n\/\/ NewRequest returns an *http.Request associated with this instance.\nfunc (i *instance) NewRequest(method, urlStr string, body io.Reader) (*http.Request, error) {\n\treq, err := http.NewRequest(method, urlStr, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Associate this request.\n\treq, release := internal.RegisterTestRequest(req, i.apiURL, func(ctx context.Context) context.Context {\n\t\tctx = internal.WithAppIDOverride(ctx, \"dev~\"+i.appID)\n\t\treturn ctx\n\t})\n\ti.relFuncs = append(i.relFuncs, release)\n\n\treturn req, nil\n}\n\n\/\/ Close kills the child api_server.py process, releasing its resources.\nfunc (i *instance) Close() (err error) {\n\tfor _, rel := range i.relFuncs {\n\t\trel()\n\t}\n\ti.relFuncs = nil\n\tchild := i.child\n\tif child == nil {\n\t\treturn nil\n\t}\n\tdefer func() {\n\t\ti.child = nil\n\t\terr1 := os.RemoveAll(i.appDir)\n\t\tif err == nil {\n\t\t\terr = err1\n\t\t}\n\t}()\n\n\tif p := child.Process; p != nil {\n\t\terrc := make(chan error, 1)\n\t\tgo func() {\n\t\t\terrc <- child.Wait()\n\t\t}()\n\n\t\t\/\/ Call the quit handler on the admin server.\n\t\tres, err := http.Get(i.adminURL + \"\/quit\")\n\t\tif err != nil {\n\t\t\tp.Kill()\n\t\t\treturn fmt.Errorf(\"unable to call \/quit handler: %v\", err)\n\t\t}\n\t\tres.Body.Close()\n\t\tselect {\n\t\tcase <-time.After(15 * time.Second):\n\t\t\tp.Kill()\n\t\t\treturn errors.New(\"timeout killing child process\")\n\t\tcase err = <-errc:\n\t\t\t\/\/ Do nothing.\n\t\t}\n\t}\n\treturn\n}\n\nfunc fileExists(path string) bool {\n\t_, err := os.Stat(path)\n\treturn err == nil\n}\n\nfunc findPython() (path string, err error) {\n\tfor _, name := range []string{\"python2.7\", \"python\"} {\n\t\tpath, err = exec.LookPath(name)\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\nfunc findDevAppserver() (string, error) {\n\tif p := os.Getenv(\"APPENGINE_DEV_APPSERVER\"); p != \"\" {\n\t\tif fileExists(p) {\n\t\t\treturn p, nil\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"invalid APPENGINE_DEV_APPSERVER environment variable; path %q doesn't exist\", p)\n\t}\n\treturn exec.LookPath(\"dev_appserver.py\")\n}\n\nvar apiServerAddrRE = regexp.MustCompile(`Starting API server at: (\\S+)`)\nvar adminServerAddrRE = regexp.MustCompile(`Starting admin server at: (\\S+)`)\n\nfunc (i *instance) startChild() (err error) {\n\tif PrepareDevAppserver != nil {\n\t\tif err := PrepareDevAppserver(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tpython, err := findPython()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not find python interpreter: %v\", err)\n\t}\n\tdevAppserver, err := findDevAppserver()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not find dev_appserver.py: %v\", err)\n\t}\n\n\ti.appDir, err = ioutil.TempDir(\"\", \"appengine-aetest\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tos.RemoveAll(i.appDir)\n\t\t}\n\t}()\n\terr = os.Mkdir(filepath.Join(i.appDir, \"app\"), 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(filepath.Join(i.appDir, \"app\", \"app.yaml\"), []byte(i.appYAML()), 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(filepath.Join(i.appDir, \"app\", \"stubapp.go\"), []byte(appSource), 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tappserverArgs := []string{\n\t\tdevAppserver,\n\t\t\"--port=0\",\n\t\t\"--api_port=0\",\n\t\t\"--admin_port=0\",\n\t\t\"--automatic_restart=false\",\n\t\t\"--skip_sdk_update_check=true\",\n\t\t\"--clear_datastore=true\",\n\t\t\"--clear_search_indexes=true\",\n\t\t\"--datastore_path\", filepath.Join(i.appDir, \"datastore\"),\n\t}\n\tif i.opts != nil && i.opts.StronglyConsistentDatastore {\n\t\tappserverArgs = append(appserverArgs, \"--datastore_consistency_policy=consistent\")\n\t}\n\tif i.opts != nil && i.opts.SupportDatastoreEmulator != nil {\n\t\tappserverArgs = append(appserverArgs, fmt.Sprintf(\"--support_datastore_emulator=%t\", *i.opts.SupportDatastoreEmulator))\n\t}\n\tappserverArgs = append(appserverArgs, filepath.Join(i.appDir, \"app\"))\n\n\ti.child = exec.Command(python,\n\t\tappserverArgs...,\n\t)\n\ti.child.Stdout = os.Stdout\n\tvar stderr io.Reader\n\tstderr, err = i.child.StderrPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = i.child.Start(); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Read stderr until we have read the URLs of the API server and admin interface.\n\terrc := make(chan error, 1)\n\tgo func() {\n\t\ts := bufio.NewScanner(stderr)\n\t\tfor s.Scan() {\n\t\t\t\/\/ Pass stderr along as we go so the user can see it.\n\t\t\tif !(i.opts != nil && i.opts.SuppressDevAppServerLog) {\n\t\t\t\tfmt.Fprintln(os.Stderr, s.Text())\n\t\t\t}\n\t\t\tif match := apiServerAddrRE.FindStringSubmatch(s.Text()); match != nil {\n\t\t\t\tu, err := url.Parse(match[1])\n\t\t\t\tif err != nil {\n\t\t\t\t\terrc <- fmt.Errorf(\"failed to parse API URL %q: %v\", match[1], err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\ti.apiURL = u\n\t\t\t}\n\t\t\tif match := adminServerAddrRE.FindStringSubmatch(s.Text()); match != nil {\n\t\t\t\ti.adminURL = match[1]\n\t\t\t}\n\t\t\tif i.adminURL != \"\" && i.apiURL != nil {\n\t\t\t\t\/\/ Pass along stderr to the user after we're done with it.\n\t\t\t\tif !(i.opts != nil && i.opts.SuppressDevAppServerLog) {\n\t\t\t\t\tgo io.Copy(os.Stderr, stderr)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\terrc <- s.Err()\n\t}()\n\n\tselect {\n\tcase <-time.After(i.startupTimeout):\n\t\tif p := i.child.Process; p != nil {\n\t\t\tp.Kill()\n\t\t}\n\t\treturn errors.New(\"timeout starting child process\")\n\tcase err := <-errc:\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error reading child process stderr: %v\", err)\n\t\t}\n\t}\n\tif i.adminURL == \"\" {\n\t\treturn errors.New(\"unable to find admin server URL\")\n\t}\n\tif i.apiURL == nil {\n\t\treturn errors.New(\"unable to find API server URL\")\n\t}\n\treturn nil\n}\n\nfunc (i *instance) appYAML() string {\n\treturn fmt.Sprintf(appYAMLTemplate, i.appID)\n}\n\nconst appYAMLTemplate = `\napplication: %s\nversion: 1\nruntime: go111\n\nhandlers:\n- url: \/.*\n  script: _go_app\n`\n\nconst appSource = `\npackage main\nimport \"google.golang.org\/appengine\"\nfunc main() { appengine.Main() }\n`\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright 2018 The Kythe Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ Package span implements utilities to resolve byte offsets within a file to\n\/\/ line and column numbers.\npackage span \/\/ import \"kythe.io\/kythe\/go\/util\/span\"\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"sort\"\n\n\t\"github.com\/sergi\/go-diff\/diffmatchpatch\"\n\n\tcpb \"kythe.io\/kythe\/proto\/common_go_proto\"\n\txpb \"kythe.io\/kythe\/proto\/xref_go_proto\"\n)\n\n\/\/ InBounds reports whether [start,end) is bounded by the specified [startBoundary,endBoundary) span.\nfunc InBounds(kind xpb.DecorationsRequest_SpanKind, start, end, startBoundary, endBoundary int32) bool {\n\tswitch kind {\n\tcase xpb.DecorationsRequest_WITHIN_SPAN:\n\t\treturn start >= startBoundary && end <= endBoundary\n\tcase xpb.DecorationsRequest_AROUND_SPAN:\n\t\treturn start <= startBoundary && end >= endBoundary\n\tdefault:\n\t\tlog.Printf(\"WARNING: unknown DecorationsRequest_SpanKind: %v\", kind)\n\t}\n\treturn false\n}\n\n\/\/ Patcher uses a computed diff between two texts to map spans from the original\n\/\/ text to the new text.\ntype Patcher struct {\n\tdmp  *diffmatchpatch.DiffMatchPatch\n\tdiff []diffmatchpatch.Diff\n}\n\n\/\/ NewPatcher returns a Patcher based on the diff between oldText and newText.\nfunc NewPatcher(oldText, newText []byte) (p *Patcher, err error) {\n\tdefer func() {\n\t\t\/\/ dmp may panic on some large requests; catch it and return an error instead\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"diffmatchpatch panic: %v\", r)\n\t\t}\n\t}()\n\tdmp := diffmatchpatch.New()\n\treturn &Patcher{dmp, dmp.DiffCleanupEfficiency(dmp.DiffMain(string(oldText), string(newText), true))}, nil\n}\n\n\/\/ Patch returns the resulting span of mapping the given span from the Patcher's\n\/\/ constructed oldText to its newText.  If the span no longer exists in newText\n\/\/ or is invalid, the returned bool will be false.  As a convenience, if p==nil,\n\/\/ the original span will be returned.\nfunc (p *Patcher) Patch(spanStart, spanEnd int32) (newStart, newEnd int32, exists bool) {\n\tif spanStart > spanEnd {\n\t\treturn 0, 0, false\n\t} else if p == nil {\n\t\treturn spanStart, spanEnd, true\n\t}\n\n\tvar old, new int32\n\tfor _, d := range p.diff {\n\t\tl := int32(len(d.Text))\n\t\tif old > spanStart {\n\t\t\treturn 0, 0, false\n\t\t}\n\t\tswitch d.Type {\n\t\tcase diffmatchpatch.DiffEqual:\n\t\t\tif old <= spanStart && spanEnd <= old+l {\n\t\t\t\tnewStart = new + (spanStart - old)\n\t\t\t\tnewEnd = new + (spanEnd - old)\n\t\t\t\texists = true\n\t\t\t\treturn\n\t\t\t}\n\t\t\told += l\n\t\t\tnew += l\n\t\tcase diffmatchpatch.DiffDelete:\n\t\t\told += l\n\t\tcase diffmatchpatch.DiffInsert:\n\t\t\tnew += l\n\t\t}\n\t}\n\n\treturn 0, 0, false\n}\n\n\/\/ PatchSpan returns the given Span's byte offsets mapped from the Patcher's\n\/\/ oldText to its newText using Patcher.Patch.\nfunc (p *Patcher) PatchSpan(span *cpb.Span) (newStart, newEnd int32, exists bool) {\n\treturn p.Patch(span.GetStart().GetByteOffset(), span.GetEnd().GetByteOffset())\n}\n\n\/\/ Normalizer fixes xref.Locations within a given source text so that each point\n\/\/ has consistent byte_offset, line_number, and column_offset fields within the\n\/\/ range of text's length and its line lengths.\ntype Normalizer struct {\n\ttextLen   int32\n\tlineLen   []int32\n\tprefixLen []int32\n}\n\n\/\/ NewNormalizer returns a Normalizer for Locations within text.\nfunc NewNormalizer(text []byte) *Normalizer {\n\tlines := bytes.Split(text, lineEnd)\n\tlineLen := make([]int32, len(lines))\n\tprefixLen := make([]int32, len(lines))\n\tfor i := 1; i < len(lines); i++ {\n\t\tlineLen[i-1] = int32(len(lines[i-1]) + len(lineEnd))\n\t\tprefixLen[i] = prefixLen[i-1] + lineLen[i-1]\n\t}\n\tlineLen[len(lines)-1] = int32(len(lines[len(lines)-1]) + len(lineEnd))\n\treturn &Normalizer{int32(len(text)), lineLen, prefixLen}\n}\n\n\/\/ Location returns a normalized location within the Normalizer's text.\n\/\/ Normalized FILE locations have no start\/end points.  Normalized SPAN\n\/\/ locations have fully populated start\/end points clamped in the range [0,\n\/\/ len(text)).\nfunc (n *Normalizer) Location(loc *xpb.Location) (*xpb.Location, error) {\n\tnl := &xpb.Location{}\n\tif loc == nil {\n\t\treturn nl, nil\n\t}\n\tnl.Ticket = loc.Ticket\n\tnl.Kind = loc.Kind\n\tif loc.Kind == xpb.Location_FILE {\n\t\treturn nl, nil\n\t}\n\n\tif loc.Span == nil {\n\t\treturn nil, errors.New(\"invalid SPAN: missing span\")\n\t} else if loc.Span.Start == nil {\n\t\treturn nil, errors.New(\"invalid SPAN: missing span start point\")\n\t} else if loc.Span.End == nil {\n\t\treturn nil, errors.New(\"invalid SPAN: missing span end point\")\n\t}\n\n\tnl.Span = n.Span(loc.Span)\n\n\tstart, end := nl.Span.Start.ByteOffset, nl.Span.End.ByteOffset\n\tif start > end {\n\t\treturn nil, fmt.Errorf(\"invalid SPAN: start (%d) is after end (%d)\", start, end)\n\t}\n\treturn nl, nil\n}\n\n\/\/ Span returns a Span with its start and end normalized.\nfunc (n *Normalizer) Span(s *cpb.Span) *cpb.Span {\n\tif s == nil {\n\t\treturn nil\n\t}\n\treturn &cpb.Span{\n\t\tStart: n.Point(s.Start),\n\t\tEnd:   n.Point(s.End),\n\t}\n}\n\n\/\/ SpanOffsets returns a Span based on normalized start and end byte offsets.\nfunc (n *Normalizer) SpanOffsets(start, end int32) *cpb.Span {\n\treturn &cpb.Span{\n\t\tStart: n.ByteOffset(start),\n\t\tEnd:   n.ByteOffset(end),\n\t}\n}\n\nvar lineEnd = []byte(\"\\n\")\n\n\/\/ Point returns a normalized point within the Normalizer's text.  A normalized\n\/\/ point has all of its fields set consistently and clamped within the range\n\/\/ [0,len(text)).\nfunc (n *Normalizer) Point(p *cpb.Point) *cpb.Point {\n\tif p == nil {\n\t\treturn nil\n\t}\n\n\tif p.ByteOffset > 0 {\n\t\treturn n.ByteOffset(p.ByteOffset)\n\t} else if p.LineNumber > 0 {\n\t\tnp := &cpb.Point{\n\t\t\tLineNumber:   p.LineNumber,\n\t\t\tColumnOffset: p.ColumnOffset,\n\t\t}\n\n\t\tif totalLines := int32(len(n.lineLen)); p.LineNumber > totalLines {\n\t\t\tnp.LineNumber = totalLines\n\t\t\tnp.ColumnOffset = n.lineLen[np.LineNumber-1] - 1\n\t\t}\n\t\tif np.ColumnOffset < 0 {\n\t\t\tnp.ColumnOffset = 0\n\t\t} else if np.ColumnOffset > 0 {\n\t\t\tif lineLen := n.lineLen[np.LineNumber-1] - 1; p.ColumnOffset > lineLen {\n\t\t\t\tnp.ColumnOffset = lineLen\n\t\t\t}\n\t\t}\n\n\t\tnp.ByteOffset = n.prefixLen[np.LineNumber-1] + np.ColumnOffset\n\n\t\treturn np\n\t}\n\n\treturn &cpb.Point{LineNumber: 1}\n}\n\n\/\/ ByteOffset returns a normalized point based on the given offset within the\n\/\/ Normalizer's text.  A normalized point has all of its fields set consistently\n\/\/ and clamped within the range [0,len(text)).\nfunc (n *Normalizer) ByteOffset(offset int32) *cpb.Point {\n\tnp := &cpb.Point{ByteOffset: offset}\n\tif np.ByteOffset > n.textLen {\n\t\tnp.ByteOffset = n.textLen\n\t}\n\n\tnp.LineNumber = int32(sort.Search(len(n.lineLen), func(i int) bool {\n\t\treturn n.prefixLen[i] > np.ByteOffset\n\t}))\n\tnp.ColumnOffset = np.ByteOffset - n.prefixLen[np.LineNumber-1]\n\n\treturn np\n}\n<commit_msg>perf(serving): reduce patching to offsets; drop text (#5422)<commit_after>\/*\n * Copyright 2018 The Kythe Authors. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ Package span implements utilities to resolve byte offsets within a file to\n\/\/ line and column numbers.\npackage span \/\/ import \"kythe.io\/kythe\/go\/util\/span\"\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"sort\"\n\n\t\"github.com\/sergi\/go-diff\/diffmatchpatch\"\n\n\tcpb \"kythe.io\/kythe\/proto\/common_go_proto\"\n\txpb \"kythe.io\/kythe\/proto\/xref_go_proto\"\n)\n\n\/\/ InBounds reports whether [start,end) is bounded by the specified [startBoundary,endBoundary) span.\nfunc InBounds(kind xpb.DecorationsRequest_SpanKind, start, end, startBoundary, endBoundary int32) bool {\n\tswitch kind {\n\tcase xpb.DecorationsRequest_WITHIN_SPAN:\n\t\treturn start >= startBoundary && end <= endBoundary\n\tcase xpb.DecorationsRequest_AROUND_SPAN:\n\t\treturn start <= startBoundary && end >= endBoundary\n\tdefault:\n\t\tlog.Printf(\"WARNING: unknown DecorationsRequest_SpanKind: %v\", kind)\n\t}\n\treturn false\n}\n\n\/\/ Patcher uses a computed diff between two texts to map spans from the original\n\/\/ text to the new text.\ntype Patcher struct {\n\tspans []diff\n}\n\n\/\/ NewPatcher returns a Patcher based on the diff between oldText and newText.\nfunc NewPatcher(oldText, newText []byte) (p *Patcher, err error) {\n\tdefer func() {\n\t\t\/\/ dmp may panic on some large requests; catch it and return an error instead\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"diffmatchpatch panic: %v\", r)\n\t\t}\n\t}()\n\tdmp := diffmatchpatch.New()\n\tdiff := dmp.DiffCleanupEfficiency(dmp.DiffMain(string(oldText), string(newText), true))\n\treturn &Patcher{mapToOffsets(diff)}, nil\n}\n\ntype diff struct {\n\tLength int32\n\tType   diffmatchpatch.Operation\n}\n\nfunc mapToOffsets(ds []diffmatchpatch.Diff) []diff {\n\tres := make([]diff, len(ds))\n\tfor i, d := range ds {\n\t\tres[i] = diff{Length: int32(len(d.Text)), Type: d.Type}\n\t}\n\treturn res\n}\n\n\/\/ Patch returns the resulting span of mapping the given span from the Patcher's\n\/\/ constructed oldText to its newText.  If the span no longer exists in newText\n\/\/ or is invalid, the returned bool will be false.  As a convenience, if p==nil,\n\/\/ the original span will be returned.\nfunc (p *Patcher) Patch(spanStart, spanEnd int32) (newStart, newEnd int32, exists bool) {\n\tif spanStart > spanEnd {\n\t\treturn 0, 0, false\n\t} else if p == nil {\n\t\treturn spanStart, spanEnd, true\n\t}\n\n\tvar old, new int32\n\tfor _, d := range p.spans {\n\t\tl := d.Length\n\t\tif old > spanStart {\n\t\t\treturn 0, 0, false\n\t\t}\n\t\tswitch d.Type {\n\t\tcase diffmatchpatch.DiffEqual:\n\t\t\tif old <= spanStart && spanEnd <= old+l {\n\t\t\t\tnewStart = new + (spanStart - old)\n\t\t\t\tnewEnd = new + (spanEnd - old)\n\t\t\t\texists = true\n\t\t\t\treturn\n\t\t\t}\n\t\t\told += l\n\t\t\tnew += l\n\t\tcase diffmatchpatch.DiffDelete:\n\t\t\told += l\n\t\tcase diffmatchpatch.DiffInsert:\n\t\t\tnew += l\n\t\t}\n\t}\n\n\treturn 0, 0, false\n}\n\n\/\/ PatchSpan returns the given Span's byte offsets mapped from the Patcher's\n\/\/ oldText to its newText using Patcher.Patch.\nfunc (p *Patcher) PatchSpan(span *cpb.Span) (newStart, newEnd int32, exists bool) {\n\treturn p.Patch(span.GetStart().GetByteOffset(), span.GetEnd().GetByteOffset())\n}\n\n\/\/ Normalizer fixes xref.Locations within a given source text so that each point\n\/\/ has consistent byte_offset, line_number, and column_offset fields within the\n\/\/ range of text's length and its line lengths.\ntype Normalizer struct {\n\ttextLen   int32\n\tlineLen   []int32\n\tprefixLen []int32\n}\n\n\/\/ NewNormalizer returns a Normalizer for Locations within text.\nfunc NewNormalizer(text []byte) *Normalizer {\n\tlines := bytes.Split(text, lineEnd)\n\tlineLen := make([]int32, len(lines))\n\tprefixLen := make([]int32, len(lines))\n\tfor i := 1; i < len(lines); i++ {\n\t\tlineLen[i-1] = int32(len(lines[i-1]) + len(lineEnd))\n\t\tprefixLen[i] = prefixLen[i-1] + lineLen[i-1]\n\t}\n\tlineLen[len(lines)-1] = int32(len(lines[len(lines)-1]) + len(lineEnd))\n\treturn &Normalizer{int32(len(text)), lineLen, prefixLen}\n}\n\n\/\/ Location returns a normalized location within the Normalizer's text.\n\/\/ Normalized FILE locations have no start\/end points.  Normalized SPAN\n\/\/ locations have fully populated start\/end points clamped in the range [0,\n\/\/ len(text)).\nfunc (n *Normalizer) Location(loc *xpb.Location) (*xpb.Location, error) {\n\tnl := &xpb.Location{}\n\tif loc == nil {\n\t\treturn nl, nil\n\t}\n\tnl.Ticket = loc.Ticket\n\tnl.Kind = loc.Kind\n\tif loc.Kind == xpb.Location_FILE {\n\t\treturn nl, nil\n\t}\n\n\tif loc.Span == nil {\n\t\treturn nil, errors.New(\"invalid SPAN: missing span\")\n\t} else if loc.Span.Start == nil {\n\t\treturn nil, errors.New(\"invalid SPAN: missing span start point\")\n\t} else if loc.Span.End == nil {\n\t\treturn nil, errors.New(\"invalid SPAN: missing span end point\")\n\t}\n\n\tnl.Span = n.Span(loc.Span)\n\n\tstart, end := nl.Span.Start.ByteOffset, nl.Span.End.ByteOffset\n\tif start > end {\n\t\treturn nil, fmt.Errorf(\"invalid SPAN: start (%d) is after end (%d)\", start, end)\n\t}\n\treturn nl, nil\n}\n\n\/\/ Span returns a Span with its start and end normalized.\nfunc (n *Normalizer) Span(s *cpb.Span) *cpb.Span {\n\tif s == nil {\n\t\treturn nil\n\t}\n\treturn &cpb.Span{\n\t\tStart: n.Point(s.Start),\n\t\tEnd:   n.Point(s.End),\n\t}\n}\n\n\/\/ SpanOffsets returns a Span based on normalized start and end byte offsets.\nfunc (n *Normalizer) SpanOffsets(start, end int32) *cpb.Span {\n\treturn &cpb.Span{\n\t\tStart: n.ByteOffset(start),\n\t\tEnd:   n.ByteOffset(end),\n\t}\n}\n\nvar lineEnd = []byte(\"\\n\")\n\n\/\/ Point returns a normalized point within the Normalizer's text.  A normalized\n\/\/ point has all of its fields set consistently and clamped within the range\n\/\/ [0,len(text)).\nfunc (n *Normalizer) Point(p *cpb.Point) *cpb.Point {\n\tif p == nil {\n\t\treturn nil\n\t}\n\n\tif p.ByteOffset > 0 {\n\t\treturn n.ByteOffset(p.ByteOffset)\n\t} else if p.LineNumber > 0 {\n\t\tnp := &cpb.Point{\n\t\t\tLineNumber:   p.LineNumber,\n\t\t\tColumnOffset: p.ColumnOffset,\n\t\t}\n\n\t\tif totalLines := int32(len(n.lineLen)); p.LineNumber > totalLines {\n\t\t\tnp.LineNumber = totalLines\n\t\t\tnp.ColumnOffset = n.lineLen[np.LineNumber-1] - 1\n\t\t}\n\t\tif np.ColumnOffset < 0 {\n\t\t\tnp.ColumnOffset = 0\n\t\t} else if np.ColumnOffset > 0 {\n\t\t\tif lineLen := n.lineLen[np.LineNumber-1] - 1; p.ColumnOffset > lineLen {\n\t\t\t\tnp.ColumnOffset = lineLen\n\t\t\t}\n\t\t}\n\n\t\tnp.ByteOffset = n.prefixLen[np.LineNumber-1] + np.ColumnOffset\n\n\t\treturn np\n\t}\n\n\treturn &cpb.Point{LineNumber: 1}\n}\n\n\/\/ ByteOffset returns a normalized point based on the given offset within the\n\/\/ Normalizer's text.  A normalized point has all of its fields set consistently\n\/\/ and clamped within the range [0,len(text)).\nfunc (n *Normalizer) ByteOffset(offset int32) *cpb.Point {\n\tnp := &cpb.Point{ByteOffset: offset}\n\tif np.ByteOffset > n.textLen {\n\t\tnp.ByteOffset = n.textLen\n\t}\n\n\tnp.LineNumber = int32(sort.Search(len(n.lineLen), func(i int) bool {\n\t\treturn n.prefixLen[i] > np.ByteOffset\n\t}))\n\tnp.ColumnOffset = np.ByteOffset - n.prefixLen[np.LineNumber-1]\n\n\treturn np\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Vanadium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage profilescmdline_test\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"v.io\/jiri\/jiri\"\n\t\"v.io\/jiri\/jiritest\"\n\t\"v.io\/jiri\/profiles\"\n\t\"v.io\/jiri\/profiles\/profilescmdline\"\n\t\"v.io\/jiri\/profiles\/profilesreader\"\n\t\"v.io\/x\/lib\/envvar\"\n\t\"v.io\/x\/lib\/gosh\"\n)\n\nfunc TestManagerArgs(t *testing.T) {\n\tprofilescmdline.Reset()\n\tp := parent\n\tprofilescmdline.RegisterManagementCommands(&p, false, \"\", \"\", jiri.ProfilesRootDir)\n\tif got, want := len(p.Children), 5; got != want {\n\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t}\n\ttype cl struct {\n\t\targs string\n\t\tn    int\n\t}\n\tcls := map[string]cl{\n\t\t\"install\":   cl{\"--profiles-db=db --profiles-dir=root --target=arch-os --env=a=b,c=d --force=false\", 5},\n\t\t\"uninstall\": cl{\"--profiles-db=db --profiles-dir=root --target=arch-os --all-targets --v\", 5},\n\t\t\"cleanup\":   cl{\"--profiles-db=db --profiles-dir=root --gc --rm-all --v\", 5},\n\t\t\"update\":    cl{\"--profiles-db=db --profiles-dir=root -v\", 3},\n\t\t\"available\": cl{\"-v\", 1},\n\t}\n\tfor _, c := range p.Children {\n\t\targs := cls[c.Name].args\n\t\tif err := c.Flags.Parse(strings.Split(args, \" \")); err != nil {\n\t\t\tt.Errorf(\"failed to parse for %s: %s: %v\", c.Name, args, err)\n\t\t\tcontinue\n\t\t}\n\t\tif got, want := c.Flags.NFlag(), cls[c.Name].n; got != want {\n\t\t\tt.Errorf(\"%s: got %v, want %v\", c.Name, got, want)\n\t\t}\n\t}\n}\n\nvar (\n\tbuildInstallersOnce, buildJiriOnce     sync.Once\n\tbuildInstallersBinDir, buildJiriBinDir = \"\", \"\"\n)\n\n\/\/ TODO(sadovsky): This code leaves a lot of temp dirs behind. It would be nice\n\/\/ to restructure things so that all temporary artifacts get cleaned up.\nfunc buildInstallers(t *testing.T) string {\n\tbuildInstallersOnce.Do(func() {\n\t\tbinDir, err := ioutil.TempDir(\"\", \"\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tsh := gosh.NewShell(t)\n\t\tdefer sh.Cleanup()\n\t\tprefix := \"v.io\/jiri\/profiles\/profilescmdline\/internal\/\"\n\t\tgosh.BuildGoPkg(sh, binDir, \"v.io\/jiri\/cmd\/jiri\", \"-o\", \"jiri\")\n\t\tgosh.BuildGoPkg(sh, binDir, prefix+\"i1\", \"-o\", \"jiri-profile-i1\")\n\t\tgosh.BuildGoPkg(sh, binDir, prefix+\"i2\", \"-o\", \"jiri-profile-i2\")\n\t\tbuildInstallersBinDir = binDir\n\t})\n\treturn buildInstallersBinDir\n}\n\nfunc buildJiri(t *testing.T) string {\n\tbuildJiriOnce.Do(func() {\n\t\tbinDir, err := ioutil.TempDir(\"\", \"\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tsh := gosh.NewShell(t)\n\t\tdefer sh.Cleanup()\n\t\tgosh.BuildGoPkg(sh, binDir, \"v.io\/jiri\/cmd\/jiri\", \"-o\", \"jiri\")\n\t\tbuildJiriBinDir = binDir\n\t})\n\treturn buildJiriBinDir\n}\n\nfunc run(sh *gosh.Shell, dir, bin string, args ...string) string {\n\tcmd := sh.Cmd(filepath.Join(dir, bin), args...)\n\tif testing.Verbose() {\n\t\tcmd.PropagateOutput = true\n\t}\n\treturn cmd.Stdout()\n}\n\nfunc TestManagerAvailable(t *testing.T) {\n\tfake, cleanup := jiritest.NewFakeJiriRoot(t)\n\tdefer cleanup()\n\tdir, sh := buildInstallers(t), gosh.NewShell(t)\n\tsh.Vars[\"JIRI_ROOT\"] = fake.X.Root\n\tsh.Vars[\"PATH\"] = envvar.PrependUsingSeparator(dir, os.Getenv(\"PATH\"), \":\")\n\tstdout := run(sh, dir, \"jiri\", \"profile\", \"available\", \"-v\")\n\tfor _, installer := range []string{\"i1\", \"i2\"} {\n\t\tre := regexp.MustCompile(\"Available Subcommands:.*profile-\" + installer + \".*\\n\")\n\t\tif got := stdout; !re.MatchString(got) {\n\t\t\tt.Errorf(\"%v does not match %v\\n\", got, re.String())\n\t\t}\n\t\tif got, want := stdout, installer+\":eg\"; !strings.Contains(got, want) {\n\t\t\tt.Errorf(\"%v does not contain %v\\n\", got, want)\n\t\t}\n\t}\n\tos.RemoveAll(filepath.Join(fake.X.Root, jiri.ProfilesDBDir))\n\tstdout = run(sh, dir, \"jiri\", \"profile\", \"available\", \"-v\")\n\tif got, want := strings.TrimSpace(stdout), \"Available Subcommands:\"; got != want {\n\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t}\n}\n\nfunc loc() string {\n\t_, file, line, _ := runtime.Caller(2)\n\treturn fmt.Sprintf(\"%s:%d\", filepath.Base(file), line)\n}\nfunc exists(filename string) bool {\n\t_, err := os.Stat(filename)\n\treturn err == nil\n}\n\nfunc contains(t *testing.T, filename, want string) {\n\to, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got := string(o); got != want {\n\t\tt.Errorf(\"%s: %s: got %v, want %v\", loc(), filename, got, want)\n\t}\n}\n\nfunc cat(msg, filename string) {\n\to, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Fprintln(os.Stderr, msg)\n\tfmt.Fprintln(os.Stderr, string(o))\n\tfmt.Fprintln(os.Stderr, msg)\n}\n\nfunc removeDate(s string) string {\n\tvar result bytes.Buffer\n\tscanner := bufio.NewScanner(bytes.NewBufferString(s))\n\tre := regexp.MustCompile(\"(.*) date=\\\".*\\\"\")\n\tfor scanner.Scan() {\n\t\tresult.WriteString(re.ReplaceAllString(scanner.Text(), \"$1\"))\n\t\tresult.WriteString(\"\\n\")\n\t}\n\treturn strings.TrimSpace(result.String())\n}\n\nfunc cmpFiles(t *testing.T, gotFilename, wantFilename string) {\n\tg, err := ioutil.ReadFile(gotFilename)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tw, err := ioutil.ReadFile(wantFilename)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got, want := removeDate(strings.TrimSpace(string(g))), removeDate(strings.TrimSpace(string(w))); got != want {\n\t\tt.Errorf(\"%s: got %v, want %v from %q and %q\", loc(), got, want, gotFilename, wantFilename)\n\t}\n}\n\nfunc TestManagerInstallUninstall(t *testing.T) {\n\tfake, cleanup := jiritest.NewFakeJiriRoot(t)\n\tdefer cleanup()\n\tdir, sh := buildInstallers(t), gosh.NewShell(t)\n\tsh.Vars[\"JIRI_ROOT\"] = fake.X.Root\n\tsh.Vars[\"PATH\"] = envvar.PrependUsingSeparator(dir, os.Getenv(\"PATH\"), \":\")\n\n\trun(sh, dir, \"jiri\", \"profile\", \"list\", \"-v\")\n\n\ti1 := filepath.Join(fake.X.Root, \".jiri_root\/profile_db\/i1\")\n\ti2 := filepath.Join(fake.X.Root, \".jiri_root\/profile_db\/i2\")\n\n\trun(sh, dir, \"jiri\", \"profile\", \"install\", \"--target=arch-os\", \"i1:eg\", \"i2:eg\")\n\tfor _, installer := range []string{\"i1\", \"i2\"} {\n\t\ttdir := filepath.Join(fake.X.Root, jiri.ProfilesRootDir, installer, \"eg\", \"arch_os\")\n\t\tcontains(t, filepath.Join(tdir, \"version\"), \"3\")\n\t\tcontains(t, filepath.Join(tdir, \"3\"), \"3\")\n\t}\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1a.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2a.xml\"))\n\n\trun(sh, dir, \"jiri\", \"profile\", \"install\", \"--target=arch-os@2\", \"i1:eg\", \"i2:eg\")\n\t\/\/ Installs are idempotent.\n\trun(sh, dir, \"jiri\", \"profile\", \"install\", \"--target=arch-os@2\", \"i1:eg\", \"i2:eg\")\n\tfor _, installer := range []string{\"i1\", \"i2\"} {\n\t\ttdir := filepath.Join(fake.X.Root, jiri.ProfilesRootDir, installer, \"eg\", \"arch_os\")\n\t\tcontains(t, filepath.Join(tdir, \"version\"), \"2\")\n\t\tcontains(t, filepath.Join(tdir, \"3\"), \"3\")\n\t\tcontains(t, filepath.Join(tdir, \"2\"), \"2\")\n\t}\n\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1b.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2b.xml\"))\n\n\trun(sh, dir, \"jiri\", \"profile\", \"uninstall\", \"--target=arch-os@2\", \"i1:eg\", \"i2:eg\")\n\tfor _, installer := range []string{\"i1\", \"i2\"} {\n\t\ttdir := filepath.Join(fake.X.Root, jiri.ProfilesRootDir, installer, \"eg\", \"arch_os\")\n\t\tcontains(t, filepath.Join(tdir, \"version\"), \"2\")\n\t\tcontains(t, filepath.Join(tdir, \"3\"), \"3\")\n\t\tif got, want := exists(filepath.Join(tdir, \"2\")), false; got != want {\n\t\t\tt.Errorf(\"%s: got %v, want %v\", filepath.Join(tdir, \"2\"), got, want)\n\t\t}\n\t}\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1c.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2c.xml\"))\n\n\t\/\/ Put v2 back.\n\trun(sh, dir, \"jiri\", \"profile\", \"list\", \"-v\")\n\trun(sh, dir, \"jiri\", \"profile\", \"install\", \"--target=arch-os@2\", \"i1:eg\", \"i2:eg\")\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1b.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2b.xml\"))\n}\n\nfunc TestManagerUpdate(t *testing.T) {\n\tfake, cleanup := jiritest.NewFakeJiriRoot(t)\n\tdefer cleanup()\n\tdir, sh := buildInstallers(t), gosh.NewShell(t)\n\tsh.Vars[\"JIRI_ROOT\"] = fake.X.Root\n\tsh.Vars[\"PATH\"] = dir\n\n\ti1 := filepath.Join(fake.X.Root, \".jiri_root\/profile_db\/i1\")\n\ti2 := filepath.Join(fake.X.Root, \".jiri_root\/profile_db\/i2\")\n\n\trun(sh, dir, \"jiri\", \"profile\", \"install\", \"--target=arch-os@2\", \"i1:eg\", \"i2:eg\")\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1d.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2d.xml\"))\n\n\trun(sh, dir, \"jiri\", \"profile\", \"update\")\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1e.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2e.xml\"))\n\n\trun(sh, dir, \"jiri\", \"profile\", \"cleanup\", \"-gc\")\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1f.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2f.xml\"))\n}\n\n\/\/ Test using a fake jiri root.\nfunc TestJiriFakeRoot(t *testing.T) {\n\tfake, cleanup := jiritest.NewFakeJiriRoot(t)\n\tdefer cleanup()\n\tprofilesDBDir := filepath.Join(fake.X.Root, jiri.ProfilesDBDir)\n\t_ = cleanup\n\tpdb := profiles.NewDB()\n\tt1, err := profiles.NewTarget(\"cpu1-os1@1\", \"A=B,C=D\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tpdb.InstallProfile(\"test\", \"b\", \"\")\n\tif err := pdb.AddProfileTarget(\"test\", \"b\", t1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := pdb.Write(fake.X, \"test\", profilesDBDir); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\trd, err := profilesreader.NewReader(fake.X, profilesreader.UseProfiles, profilesDBDir)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif got, want := rd.ProfileNames(), []string{\"test:b\"}; !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t}\n\n\tdir, sh := buildJiri(t), gosh.NewShell(t)\n\tsh.Vars[\"JIRI_ROOT\"] = fake.X.Root\n\tsh.Vars[\"PATH\"] = envvar.PrependUsingSeparator(dir, os.Getenv(\"PATH\"), \":\")\n\trun(sh, dir, \"jiri\", \"profile\", \"list\", \"-v\")\n}\n<commit_msg>jiri: Add helper functions to envvar to manipulate token lists.<commit_after>\/\/ Copyright 2015 The Vanadium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage profilescmdline_test\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"v.io\/jiri\/jiri\"\n\t\"v.io\/jiri\/jiritest\"\n\t\"v.io\/jiri\/profiles\"\n\t\"v.io\/jiri\/profiles\/profilescmdline\"\n\t\"v.io\/jiri\/profiles\/profilesreader\"\n\t\"v.io\/x\/lib\/envvar\"\n\t\"v.io\/x\/lib\/gosh\"\n)\n\nfunc TestManagerArgs(t *testing.T) {\n\tprofilescmdline.Reset()\n\tp := parent\n\tprofilescmdline.RegisterManagementCommands(&p, false, \"\", \"\", jiri.ProfilesRootDir)\n\tif got, want := len(p.Children), 5; got != want {\n\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t}\n\ttype cl struct {\n\t\targs string\n\t\tn    int\n\t}\n\tcls := map[string]cl{\n\t\t\"install\":   cl{\"--profiles-db=db --profiles-dir=root --target=arch-os --env=a=b,c=d --force=false\", 5},\n\t\t\"uninstall\": cl{\"--profiles-db=db --profiles-dir=root --target=arch-os --all-targets --v\", 5},\n\t\t\"cleanup\":   cl{\"--profiles-db=db --profiles-dir=root --gc --rm-all --v\", 5},\n\t\t\"update\":    cl{\"--profiles-db=db --profiles-dir=root -v\", 3},\n\t\t\"available\": cl{\"-v\", 1},\n\t}\n\tfor _, c := range p.Children {\n\t\targs := cls[c.Name].args\n\t\tif err := c.Flags.Parse(strings.Split(args, \" \")); err != nil {\n\t\t\tt.Errorf(\"failed to parse for %s: %s: %v\", c.Name, args, err)\n\t\t\tcontinue\n\t\t}\n\t\tif got, want := c.Flags.NFlag(), cls[c.Name].n; got != want {\n\t\t\tt.Errorf(\"%s: got %v, want %v\", c.Name, got, want)\n\t\t}\n\t}\n}\n\nvar (\n\tbuildInstallersOnce, buildJiriOnce     sync.Once\n\tbuildInstallersBinDir, buildJiriBinDir = \"\", \"\"\n)\n\n\/\/ TODO(sadovsky): This code leaves a lot of temp dirs behind. It would be nice\n\/\/ to restructure things so that all temporary artifacts get cleaned up.\nfunc buildInstallers(t *testing.T) string {\n\tbuildInstallersOnce.Do(func() {\n\t\tbinDir, err := ioutil.TempDir(\"\", \"\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tsh := gosh.NewShell(t)\n\t\tdefer sh.Cleanup()\n\t\tprefix := \"v.io\/jiri\/profiles\/profilescmdline\/internal\/\"\n\t\tgosh.BuildGoPkg(sh, binDir, \"v.io\/jiri\/cmd\/jiri\", \"-o\", \"jiri\")\n\t\tgosh.BuildGoPkg(sh, binDir, prefix+\"i1\", \"-o\", \"jiri-profile-i1\")\n\t\tgosh.BuildGoPkg(sh, binDir, prefix+\"i2\", \"-o\", \"jiri-profile-i2\")\n\t\tbuildInstallersBinDir = binDir\n\t})\n\treturn buildInstallersBinDir\n}\n\nfunc buildJiri(t *testing.T) string {\n\tbuildJiriOnce.Do(func() {\n\t\tbinDir, err := ioutil.TempDir(\"\", \"\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tsh := gosh.NewShell(t)\n\t\tdefer sh.Cleanup()\n\t\tgosh.BuildGoPkg(sh, binDir, \"v.io\/jiri\/cmd\/jiri\", \"-o\", \"jiri\")\n\t\tbuildJiriBinDir = binDir\n\t})\n\treturn buildJiriBinDir\n}\n\nfunc run(sh *gosh.Shell, dir, bin string, args ...string) string {\n\tcmd := sh.Cmd(filepath.Join(dir, bin), args...)\n\tif testing.Verbose() {\n\t\tcmd.PropagateOutput = true\n\t}\n\treturn cmd.Stdout()\n}\n\nfunc TestManagerAvailable(t *testing.T) {\n\tfake, cleanup := jiritest.NewFakeJiriRoot(t)\n\tdefer cleanup()\n\tdir, sh := buildInstallers(t), gosh.NewShell(t)\n\tsh.Vars[\"JIRI_ROOT\"] = fake.X.Root\n\tsh.Vars[\"PATH\"] = envvar.PrependUniqueToken(sh.Vars[\"PATH\"], \":\", dir)\n\tstdout := run(sh, dir, \"jiri\", \"profile\", \"available\", \"-v\")\n\tfor _, installer := range []string{\"i1\", \"i2\"} {\n\t\tre := regexp.MustCompile(\"Available Subcommands:.*profile-\" + installer + \".*\\n\")\n\t\tif got := stdout; !re.MatchString(got) {\n\t\t\tt.Errorf(\"%v does not match %v\\n\", got, re.String())\n\t\t}\n\t\tif got, want := stdout, installer+\":eg\"; !strings.Contains(got, want) {\n\t\t\tt.Errorf(\"%v does not contain %v\\n\", got, want)\n\t\t}\n\t}\n\tos.RemoveAll(filepath.Join(fake.X.Root, jiri.ProfilesDBDir))\n\tstdout = run(sh, dir, \"jiri\", \"profile\", \"available\", \"-v\")\n\tif got, want := strings.TrimSpace(stdout), \"Available Subcommands:\"; got != want {\n\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t}\n}\n\nfunc loc() string {\n\t_, file, line, _ := runtime.Caller(2)\n\treturn fmt.Sprintf(\"%s:%d\", filepath.Base(file), line)\n}\nfunc exists(filename string) bool {\n\t_, err := os.Stat(filename)\n\treturn err == nil\n}\n\nfunc contains(t *testing.T, filename, want string) {\n\to, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got := string(o); got != want {\n\t\tt.Errorf(\"%s: %s: got %v, want %v\", loc(), filename, got, want)\n\t}\n}\n\nfunc cat(msg, filename string) {\n\to, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Fprintln(os.Stderr, msg)\n\tfmt.Fprintln(os.Stderr, string(o))\n\tfmt.Fprintln(os.Stderr, msg)\n}\n\nfunc removeDate(s string) string {\n\tvar result bytes.Buffer\n\tscanner := bufio.NewScanner(bytes.NewBufferString(s))\n\tre := regexp.MustCompile(\"(.*) date=\\\".*\\\"\")\n\tfor scanner.Scan() {\n\t\tresult.WriteString(re.ReplaceAllString(scanner.Text(), \"$1\"))\n\t\tresult.WriteString(\"\\n\")\n\t}\n\treturn strings.TrimSpace(result.String())\n}\n\nfunc cmpFiles(t *testing.T, gotFilename, wantFilename string) {\n\tg, err := ioutil.ReadFile(gotFilename)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tw, err := ioutil.ReadFile(wantFilename)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got, want := removeDate(strings.TrimSpace(string(g))), removeDate(strings.TrimSpace(string(w))); got != want {\n\t\tt.Errorf(\"%s: got %v, want %v from %q and %q\", loc(), got, want, gotFilename, wantFilename)\n\t}\n}\n\nfunc TestManagerInstallUninstall(t *testing.T) {\n\tfake, cleanup := jiritest.NewFakeJiriRoot(t)\n\tdefer cleanup()\n\tdir, sh := buildInstallers(t), gosh.NewShell(t)\n\tsh.Vars[\"JIRI_ROOT\"] = fake.X.Root\n\tsh.Vars[\"PATH\"] = envvar.PrependUniqueToken(sh.Vars[\"PATH\"], \":\", dir)\n\n\trun(sh, dir, \"jiri\", \"profile\", \"list\", \"-v\")\n\n\ti1 := filepath.Join(fake.X.Root, \".jiri_root\/profile_db\/i1\")\n\ti2 := filepath.Join(fake.X.Root, \".jiri_root\/profile_db\/i2\")\n\n\trun(sh, dir, \"jiri\", \"profile\", \"install\", \"--target=arch-os\", \"i1:eg\", \"i2:eg\")\n\tfor _, installer := range []string{\"i1\", \"i2\"} {\n\t\ttdir := filepath.Join(fake.X.Root, jiri.ProfilesRootDir, installer, \"eg\", \"arch_os\")\n\t\tcontains(t, filepath.Join(tdir, \"version\"), \"3\")\n\t\tcontains(t, filepath.Join(tdir, \"3\"), \"3\")\n\t}\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1a.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2a.xml\"))\n\n\trun(sh, dir, \"jiri\", \"profile\", \"install\", \"--target=arch-os@2\", \"i1:eg\", \"i2:eg\")\n\t\/\/ Installs are idempotent.\n\trun(sh, dir, \"jiri\", \"profile\", \"install\", \"--target=arch-os@2\", \"i1:eg\", \"i2:eg\")\n\tfor _, installer := range []string{\"i1\", \"i2\"} {\n\t\ttdir := filepath.Join(fake.X.Root, jiri.ProfilesRootDir, installer, \"eg\", \"arch_os\")\n\t\tcontains(t, filepath.Join(tdir, \"version\"), \"2\")\n\t\tcontains(t, filepath.Join(tdir, \"3\"), \"3\")\n\t\tcontains(t, filepath.Join(tdir, \"2\"), \"2\")\n\t}\n\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1b.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2b.xml\"))\n\n\trun(sh, dir, \"jiri\", \"profile\", \"uninstall\", \"--target=arch-os@2\", \"i1:eg\", \"i2:eg\")\n\tfor _, installer := range []string{\"i1\", \"i2\"} {\n\t\ttdir := filepath.Join(fake.X.Root, jiri.ProfilesRootDir, installer, \"eg\", \"arch_os\")\n\t\tcontains(t, filepath.Join(tdir, \"version\"), \"2\")\n\t\tcontains(t, filepath.Join(tdir, \"3\"), \"3\")\n\t\tif got, want := exists(filepath.Join(tdir, \"2\")), false; got != want {\n\t\t\tt.Errorf(\"%s: got %v, want %v\", filepath.Join(tdir, \"2\"), got, want)\n\t\t}\n\t}\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1c.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2c.xml\"))\n\n\t\/\/ Put v2 back.\n\trun(sh, dir, \"jiri\", \"profile\", \"list\", \"-v\")\n\trun(sh, dir, \"jiri\", \"profile\", \"install\", \"--target=arch-os@2\", \"i1:eg\", \"i2:eg\")\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1b.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2b.xml\"))\n}\n\nfunc TestManagerUpdate(t *testing.T) {\n\tfake, cleanup := jiritest.NewFakeJiriRoot(t)\n\tdefer cleanup()\n\tdir, sh := buildInstallers(t), gosh.NewShell(t)\n\tsh.Vars[\"JIRI_ROOT\"] = fake.X.Root\n\tsh.Vars[\"PATH\"] = dir\n\n\ti1 := filepath.Join(fake.X.Root, \".jiri_root\/profile_db\/i1\")\n\ti2 := filepath.Join(fake.X.Root, \".jiri_root\/profile_db\/i2\")\n\n\trun(sh, dir, \"jiri\", \"profile\", \"install\", \"--target=arch-os@2\", \"i1:eg\", \"i2:eg\")\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1d.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2d.xml\"))\n\n\trun(sh, dir, \"jiri\", \"profile\", \"update\")\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1e.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2e.xml\"))\n\n\trun(sh, dir, \"jiri\", \"profile\", \"cleanup\", \"-gc\")\n\tcmpFiles(t, i1, filepath.Join(\"testdata\", \"i1f.xml\"))\n\tcmpFiles(t, i2, filepath.Join(\"testdata\", \"i2f.xml\"))\n}\n\n\/\/ Test using a fake jiri root.\nfunc TestJiriFakeRoot(t *testing.T) {\n\tfake, cleanup := jiritest.NewFakeJiriRoot(t)\n\tdefer cleanup()\n\tprofilesDBDir := filepath.Join(fake.X.Root, jiri.ProfilesDBDir)\n\t_ = cleanup\n\tpdb := profiles.NewDB()\n\tt1, err := profiles.NewTarget(\"cpu1-os1@1\", \"A=B,C=D\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tpdb.InstallProfile(\"test\", \"b\", \"\")\n\tif err := pdb.AddProfileTarget(\"test\", \"b\", t1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := pdb.Write(fake.X, \"test\", profilesDBDir); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\trd, err := profilesreader.NewReader(fake.X, profilesreader.UseProfiles, profilesDBDir)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif got, want := rd.ProfileNames(), []string{\"test:b\"}; !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"got %v, want %v\", got, want)\n\t}\n\n\tdir, sh := buildJiri(t), gosh.NewShell(t)\n\tsh.Vars[\"JIRI_ROOT\"] = fake.X.Root\n\tsh.Vars[\"PATH\"] = envvar.PrependUniqueToken(sh.Vars[\"PATH\"], \":\", dir)\n\trun(sh, dir, \"jiri\", \"profile\", \"list\", \"-v\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package github\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/hashicorp\/vault\/helper\/policyutil\"\n\t\"github.com\/hashicorp\/vault\/logical\"\n\t\"github.com\/hashicorp\/vault\/logical\/framework\"\n)\n\nfunc pathLogin(b *backend) *framework.Path {\n\treturn &framework.Path{\n\t\tPattern: \"login\",\n\t\tFields: map[string]*framework.FieldSchema{\n\t\t\t\"token\": &framework.FieldSchema{\n\t\t\t\tType:        framework.TypeString,\n\t\t\t\tDescription: \"GitHub personal API token\",\n\t\t\t},\n\t\t},\n\n\t\tCallbacks: map[logical.Operation]framework.OperationFunc{\n\t\t\tlogical.UpdateOperation: b.pathLogin,\n\t\t},\n\t}\n}\n\nfunc (b *backend) pathLogin(\n\treq *logical.Request, data *framework.FieldData) (*logical.Response, error) {\n\n\ttoken := data.Get(\"token\").(string)\n\n\tvar verifyResp *verifyCredentialsResp\n\tif verifyResponse, resp, err := b.verifyCredentials(req, token); err != nil {\n\t\treturn nil, err\n\t} else if resp != nil {\n\t\treturn resp, nil\n\t} else {\n\t\tverifyResp = verifyResponse\n\t}\n\n\tconfig, err := b.Config(req.Storage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tttl, _, err := b.SanitizeTTLStr(config.TTL.String(), config.MaxTTL.String())\n\tif err != nil {\n\t\treturn logical.ErrorResponse(fmt.Sprintf(\"[ERR]:%s\", err)), nil\n\t}\n\n\treturn &logical.Response{\n\t\tAuth: &logical.Auth{\n\t\t\tInternalData: map[string]interface{}{\n\t\t\t\t\"token\": token,\n\t\t\t},\n\t\t\tPolicies: verifyResp.Policies,\n\t\t\tMetadata: map[string]string{\n\t\t\t\t\"username\": *verifyResp.User.Login,\n\t\t\t\t\"org\":      *verifyResp.Org.Login,\n\t\t\t},\n\t\t\tDisplayName: *verifyResp.User.Login,\n\t\t\tLeaseOptions: logical.LeaseOptions{\n\t\t\t\tTTL:       ttl,\n\t\t\t\tRenewable: true,\n\t\t\t},\n\t\t},\n\t}, nil\n}\n\nfunc (b *backend) pathLoginRenew(\n\treq *logical.Request, d *framework.FieldData) (*logical.Response, error) {\n\n\ttoken := req.Auth.InternalData[\"token\"].(string)\n\n\tvar verifyResp *verifyCredentialsResp\n\tif verifyResponse, resp, err := b.verifyCredentials(req, token); err != nil {\n\t\treturn nil, err\n\t} else if resp != nil {\n\t\treturn resp, nil\n\t} else {\n\t\tverifyResp = verifyResponse\n\t}\n\tif !policyutil.EquivalentPolicies(verifyResp.Policies, req.Auth.Policies) {\n\t\treturn nil, fmt.Errorf(\"policies do not match\")\n\t}\n\n\tconfig, err := b.Config(req.Storage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn framework.LeaseExtend(config.TTL, config.MaxTTL, b.System())(req, d)\n}\n\nfunc (b *backend) verifyCredentials(req *logical.Request, token string) (*verifyCredentialsResp, *logical.Response, error) {\n\tconfig, err := b.Config(req.Storage)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif config.Org == \"\" {\n\t\treturn nil, logical.ErrorResponse(\n\t\t\t\"configure the github credential backend first\"), nil\n\t}\n\n\tclient, err := b.Client(token)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif config.BaseURL != \"\" {\n\t\tparsedURL, err := url.Parse(config.BaseURL)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"Successfully parsed base_url when set but failing to parse now: %s\", err)\n\t\t}\n\t\tclient.BaseURL = parsedURL\n\t}\n\n\t\/\/ Get the user\n\tuser, _, err := client.Users.Get(\"\")\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Verify that the user is part of the organization\n\tvar org *github.Organization\n\n\torgOpt := &github.ListOptions{\n\t\tPerPage: 100,\n\t}\n\n\tvar allOrgs []github.Organization\n\tfor {\n\t\torgs, resp, err := client.Organizations.List(\"\", orgOpt)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tallOrgs = append(allOrgs, orgs...)\n\t\tif resp.NextPage == 0 {\n\t\t\tbreak\n\t\t}\n\t\torgOpt.Page = resp.NextPage\n\t}\n\n\tfor _, o := range allOrgs {\n\t\tif strings.ToLower(*o.Login) == strings.ToLower(config.Org) {\n\t\t\torg = &o\n\t\t\tbreak\n\t\t}\n\t}\n\tif org == nil {\n\t\treturn nil, logical.ErrorResponse(\"user is not part of required org\"), nil\n\t}\n\n\t\/\/ Get the teams that this user is part of to determine the policies\n\tvar teamNames []string\n\n\tteamOpt := &github.ListOptions{\n\t\tPerPage: 100,\n\t}\n\n\tvar allTeams []github.Team\n\tfor {\n\t\tteams, resp, err := client.Organizations.ListUserTeams(teamOpt)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tallTeams = append(allTeams, teams...)\n\t\tif resp.NextPage == 0 {\n\t\t\tbreak\n\t\t}\n\t\tteamOpt.Page = resp.NextPage\n\t}\n\n\tfor _, t := range allTeams {\n\t\t\/\/ We only care about teams that are part of the organization we use\n\t\tif *t.Organization.ID != *org.ID {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Append the names so we can get the policies\n\t\tteamNames = append(teamNames, *t.Name)\n\t\tif *t.Name != *t.Slug {\n\t\t\tteamNames = append(teamNames, *t.Slug)\n\t\t}\n\t}\n\n\tpoliciesList, err := b.Map.Policies(req.Storage, teamNames...)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn &verifyCredentialsResp{\n\t\tUser:     user,\n\t\tOrg:      org,\n\t\tPolicies: policiesList,\n\t}, nil, nil\n}\n\ntype verifyCredentialsResp struct {\n\tUser     *github.User\n\tOrg      *github.Organization\n\tPolicies []string\n}\n<commit_msg>Fix panic when renewing a github token from a previous version of Vault<commit_after>package github\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/hashicorp\/vault\/helper\/policyutil\"\n\t\"github.com\/hashicorp\/vault\/logical\"\n\t\"github.com\/hashicorp\/vault\/logical\/framework\"\n)\n\nfunc pathLogin(b *backend) *framework.Path {\n\treturn &framework.Path{\n\t\tPattern: \"login\",\n\t\tFields: map[string]*framework.FieldSchema{\n\t\t\t\"token\": &framework.FieldSchema{\n\t\t\t\tType:        framework.TypeString,\n\t\t\t\tDescription: \"GitHub personal API token\",\n\t\t\t},\n\t\t},\n\n\t\tCallbacks: map[logical.Operation]framework.OperationFunc{\n\t\t\tlogical.UpdateOperation: b.pathLogin,\n\t\t},\n\t}\n}\n\nfunc (b *backend) pathLogin(\n\treq *logical.Request, data *framework.FieldData) (*logical.Response, error) {\n\n\ttoken := data.Get(\"token\").(string)\n\n\tvar verifyResp *verifyCredentialsResp\n\tif verifyResponse, resp, err := b.verifyCredentials(req, token); err != nil {\n\t\treturn nil, err\n\t} else if resp != nil {\n\t\treturn resp, nil\n\t} else {\n\t\tverifyResp = verifyResponse\n\t}\n\n\tconfig, err := b.Config(req.Storage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tttl, _, err := b.SanitizeTTLStr(config.TTL.String(), config.MaxTTL.String())\n\tif err != nil {\n\t\treturn logical.ErrorResponse(fmt.Sprintf(\"[ERR]:%s\", err)), nil\n\t}\n\n\treturn &logical.Response{\n\t\tAuth: &logical.Auth{\n\t\t\tInternalData: map[string]interface{}{\n\t\t\t\t\"token\": token,\n\t\t\t},\n\t\t\tPolicies: verifyResp.Policies,\n\t\t\tMetadata: map[string]string{\n\t\t\t\t\"username\": *verifyResp.User.Login,\n\t\t\t\t\"org\":      *verifyResp.Org.Login,\n\t\t\t},\n\t\t\tDisplayName: *verifyResp.User.Login,\n\t\t\tLeaseOptions: logical.LeaseOptions{\n\t\t\t\tTTL:       ttl,\n\t\t\t\tRenewable: true,\n\t\t\t},\n\t\t},\n\t}, nil\n}\n\nfunc (b *backend) pathLoginRenew(\n\treq *logical.Request, d *framework.FieldData) (*logical.Response, error) {\n\n\tif req.Auth == nil {\n\t\treturn nil, fmt.Errorf(\"request auth was nil\")\n\t}\n\n\ttokenInt, ok := req.Auth.InternalData[\"token\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"token created in previous version of Vault cannot be validated properly at renewal time\")\n\t}\n\ttoken := tokenInt.(string)\n\n\tvar verifyResp *verifyCredentialsResp\n\tif verifyResponse, resp, err := b.verifyCredentials(req, token); err != nil {\n\t\treturn nil, err\n\t} else if resp != nil {\n\t\treturn resp, nil\n\t} else {\n\t\tverifyResp = verifyResponse\n\t}\n\tif !policyutil.EquivalentPolicies(verifyResp.Policies, req.Auth.Policies) {\n\t\treturn nil, fmt.Errorf(\"policies do not match\")\n\t}\n\n\tconfig, err := b.Config(req.Storage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn framework.LeaseExtend(config.TTL, config.MaxTTL, b.System())(req, d)\n}\n\nfunc (b *backend) verifyCredentials(req *logical.Request, token string) (*verifyCredentialsResp, *logical.Response, error) {\n\tconfig, err := b.Config(req.Storage)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif config.Org == \"\" {\n\t\treturn nil, logical.ErrorResponse(\n\t\t\t\"configure the github credential backend first\"), nil\n\t}\n\n\tclient, err := b.Client(token)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tif config.BaseURL != \"\" {\n\t\tparsedURL, err := url.Parse(config.BaseURL)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"Successfully parsed base_url when set but failing to parse now: %s\", err)\n\t\t}\n\t\tclient.BaseURL = parsedURL\n\t}\n\n\t\/\/ Get the user\n\tuser, _, err := client.Users.Get(\"\")\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t\/\/ Verify that the user is part of the organization\n\tvar org *github.Organization\n\n\torgOpt := &github.ListOptions{\n\t\tPerPage: 100,\n\t}\n\n\tvar allOrgs []github.Organization\n\tfor {\n\t\torgs, resp, err := client.Organizations.List(\"\", orgOpt)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tallOrgs = append(allOrgs, orgs...)\n\t\tif resp.NextPage == 0 {\n\t\t\tbreak\n\t\t}\n\t\torgOpt.Page = resp.NextPage\n\t}\n\n\tfor _, o := range allOrgs {\n\t\tif strings.ToLower(*o.Login) == strings.ToLower(config.Org) {\n\t\t\torg = &o\n\t\t\tbreak\n\t\t}\n\t}\n\tif org == nil {\n\t\treturn nil, logical.ErrorResponse(\"user is not part of required org\"), nil\n\t}\n\n\t\/\/ Get the teams that this user is part of to determine the policies\n\tvar teamNames []string\n\n\tteamOpt := &github.ListOptions{\n\t\tPerPage: 100,\n\t}\n\n\tvar allTeams []github.Team\n\tfor {\n\t\tteams, resp, err := client.Organizations.ListUserTeams(teamOpt)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tallTeams = append(allTeams, teams...)\n\t\tif resp.NextPage == 0 {\n\t\t\tbreak\n\t\t}\n\t\tteamOpt.Page = resp.NextPage\n\t}\n\n\tfor _, t := range allTeams {\n\t\t\/\/ We only care about teams that are part of the organization we use\n\t\tif *t.Organization.ID != *org.ID {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Append the names so we can get the policies\n\t\tteamNames = append(teamNames, *t.Name)\n\t\tif *t.Name != *t.Slug {\n\t\t\tteamNames = append(teamNames, *t.Slug)\n\t\t}\n\t}\n\n\tpoliciesList, err := b.Map.Policies(req.Storage, teamNames...)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\treturn &verifyCredentialsResp{\n\t\tUser:     user,\n\t\tOrg:      org,\n\t\tPolicies: policiesList,\n\t}, nil, nil\n}\n\ntype verifyCredentialsResp struct {\n\tUser     *github.User\n\tOrg      *github.Organization\n\tPolicies []string\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 The lime Authors.\n\/\/ Use of this source code is governed by a 2-clause\n\/\/ BSD-style license that can be found in the LICENSE file.\n\npackage commands\n\nimport (\n\t. \"github.com\/limetext\/lime\/backend\"\n\t\"testing\"\n)\n\nfunc TestNewWindow(t *testing.T) {\n\ted := GetEditor()\n\tl := len(ed.Windows())\n\ted.CommandHandler().RunWindowCommand(ed.ActiveWindow(), \"new_window\", nil)\n\n\tif len(ed.Windows()) != l+1 {\n\t\tt.Errorf(\"Expected %d window, but got %d\", l+1, len(ed.Windows()))\n\t}\n}\n\nfunc TestCloseAll(t *testing.T) {\n\ted := GetEditor()\n\n\tw := ed.NewWindow()\n\tdefer w.Close()\n\n\tl := len(w.Views())\n\n\ted.CommandHandler().RunWindowCommand(w, \"new_file\", nil)\n\ted.CommandHandler().RunWindowCommand(w, \"new_file\", nil)\n\ted.CommandHandler().RunWindowCommand(w, \"new_file\", nil)\n\n\ted.CommandHandler().RunWindowCommand(w, \"close_all\", nil)\n\n\tif len(w.Views()) != l {\n\t\tt.Errorf(\"Expected %d views, but got %d\", l, len(w.Views()))\n\t}\n}\n\nfunc TestCloseWindow(t *testing.T) {\n\ted := GetEditor()\n\tw := ed.NewWindow()\n\tl := len(ed.Windows())\n\ted.CommandHandler().RunWindowCommand(w, \"close_window\", nil)\n\n\tif len(ed.Windows()) != l-1 {\n\t\tt.Errorf(\"Expected %d window, but got %d\", l-1, len(ed.Windows()))\n\t}\n}\n\nfunc TestNewAppWindow(t *testing.T) {\n\ted := GetEditor()\n\tl := len(ed.Windows())\n\ted.CommandHandler().RunApplicationCommand(\"new_window\", nil)\n\n\tif len(ed.Windows()) != l+1 {\n\t\tt.Errorf(\"Expected %d window, but got %d\", l+1, len(ed.Windows()))\n\t}\n}\n\nfunc TestCloseAppWindow(t *testing.T) {\n\ted := GetEditor()\n\t_ = ed.NewWindow()\n\tl := len(ed.Windows())\n\ted.CommandHandler().RunApplicationCommand(\"close_window\", nil)\n\n\tif len(ed.Windows()) != l-1 {\n\t\tt.Errorf(\"Expected %d window, but got %d\", l-1, len(ed.Windows()))\n\t}\n}\n<commit_msg>Make sure the test checks that all the views are closed.<commit_after>\/\/ Copyright 2013 The lime Authors.\n\/\/ Use of this source code is governed by a 2-clause\n\/\/ BSD-style license that can be found in the LICENSE file.\n\npackage commands\n\nimport (\n\t. \"github.com\/limetext\/lime\/backend\"\n\t\"testing\"\n)\n\nfunc TestNewWindow(t *testing.T) {\n\ted := GetEditor()\n\tl := len(ed.Windows())\n\ted.CommandHandler().RunWindowCommand(ed.ActiveWindow(), \"new_window\", nil)\n\n\tif len(ed.Windows()) != l+1 {\n\t\tt.Errorf(\"Expected %d window, but got %d\", l+1, len(ed.Windows()))\n\t}\n}\n\nfunc TestCloseAll(t *testing.T) {\n\ted := GetEditor()\n\n\tw := ed.NewWindow()\n\tdefer w.Close()\n\n\ted.CommandHandler().RunWindowCommand(w, \"new_file\", nil)\n\ted.CommandHandler().RunWindowCommand(w, \"new_file\", nil)\n\ted.CommandHandler().RunWindowCommand(w, \"new_file\", nil)\n\n\ted.CommandHandler().RunWindowCommand(w, \"close_all\", nil)\n\n\tif len(w.Views()) != 0 {\n\t\tt.Errorf(\"Expected no views, but got %d\", len(w.Views()))\n\t}\n}\n\nfunc TestCloseWindow(t *testing.T) {\n\ted := GetEditor()\n\tw := ed.NewWindow()\n\tl := len(ed.Windows())\n\ted.CommandHandler().RunWindowCommand(w, \"close_window\", nil)\n\n\tif len(ed.Windows()) != l-1 {\n\t\tt.Errorf(\"Expected %d window, but got %d\", l-1, len(ed.Windows()))\n\t}\n}\n\nfunc TestNewAppWindow(t *testing.T) {\n\ted := GetEditor()\n\tl := len(ed.Windows())\n\ted.CommandHandler().RunApplicationCommand(\"new_window\", nil)\n\n\tif len(ed.Windows()) != l+1 {\n\t\tt.Errorf(\"Expected %d window, but got %d\", l+1, len(ed.Windows()))\n\t}\n}\n\nfunc TestCloseAppWindow(t *testing.T) {\n\ted := GetEditor()\n\t_ = ed.NewWindow()\n\tl := len(ed.Windows())\n\ted.CommandHandler().RunApplicationCommand(\"close_window\", nil)\n\n\tif len(ed.Windows()) != l-1 {\n\t\tt.Errorf(\"Expected %d window, but got %d\", l-1, len(ed.Windows()))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package schedops\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/libopenstorage\/openstorage\/api\"\n\t\"github.com\/portworx\/torpedo\/drivers\/node\"\n\t\"github.com\/portworx\/torpedo\/drivers\/scheduler\"\n\t\"github.com\/portworx\/torpedo\/drivers\/volume\"\n\t\"github.com\/portworx\/torpedo\/pkg\/errors\"\n\t\"github.com\/portworx\/torpedo\/pkg\/k8sops\"\n\t\"github.com\/portworx\/torpedo\/pkg\/task\"\n)\n\nconst (\n\t\/\/ k8sPxRunningLabelKey is the label key used for px state\n\tk8sPxRunningLabelKey = \"px\/enabled\"\n\t\/\/ k8sPxNotRunningLabelValue is label value for a not running px state\n\tk8sPxNotRunningLabelValue = \"false\"\n\t\/\/ k8sPodsRootDir is the directory under which k8s keeps all pods data\n\tk8sPodsRootDir = \"\/var\/lib\/kubelet\/pods\"\n)\n\ntype k8sSchedOps struct{}\n\nfunc (k *k8sSchedOps) DisableOnNode(n node.Node) error {\n\treturn k8sops.Instance().AddLabelOnNode(n.Name, k8sPxRunningLabelKey, k8sPxNotRunningLabelValue)\n}\n\nfunc (k *k8sSchedOps) ValidateOnNode(n node.Node) error {\n\treturn &errors.ErrNotSupported{\n\t\tType:      \"Function\",\n\t\tOperation: \"ValidateOnNode\",\n\t}\n}\n\nfunc (k *k8sSchedOps) EnableOnNode(n node.Node) error {\n\treturn k8sops.Instance().RemoveLabelOnNode(n.Name, k8sPxRunningLabelKey)\n}\n\nfunc (k *k8sSchedOps) ValidateAddLabels(replicaNodes []api.Node, vol *api.Volume) error {\n\tpvc, ok := vol.Locator.VolumeLabels[\"pvc\"]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tvar missingLabelNodes []string\n\tfor _, rs := range replicaNodes {\n\t\tt := func() (interface{}, error) {\n\t\t\tn, err := k8sops.Instance().GetNodeByName(rs.Id)\n\t\t\tif err == nil && n != nil {\n\t\t\t\treturn n.Labels, nil\n\t\t\t}\n\n\t\t\taddrs := []string{rs.DataIp, rs.MgmtIp}\n\t\t\tn, err = k8sops.Instance().SearchNodeByAddresses(addrs)\n\t\t\tif err == nil && n != nil {\n\t\t\t\treturn n.Labels, nil\n\t\t\t}\n\n\t\t\treturn nil, fmt.Errorf(\"failed to locate node using id: %s and addresses: %v\", rs.Id, addrs)\n\t\t}\n\n\t\tret, err := task.DoRetryWithTimeout(t, 1*time.Minute, 5*time.Second)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnodeLabels := ret.(map[string]string)\n\t\tif _, ok := nodeLabels[pvc]; !ok {\n\t\t\tmissingLabelNodes = append(missingLabelNodes, rs.Id)\n\t\t}\n\t}\n\n\tif len(missingLabelNodes) > 0 {\n\t\treturn &ErrLabelMissingOnNode{\n\t\t\tLabel: pvc,\n\t\t\tNodes: missingLabelNodes,\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (k *k8sSchedOps) ValidateRemoveLabels(vol *volume.Volume, sched scheduler.Driver) error {\n\tpvcLabel := vol.Name\n\tvar staleLabelNodes []string\n\tfor _, n := range sched.GetNodes() {\n\t\tif n.Type == node.TypeWorker {\n\t\t\tt := func() (interface{}, error) {\n\t\t\t\treturn k8sops.Instance().GetLabelsOnNode(n.Name)\n\t\t\t}\n\t\t\tret, err := task.DoRetryWithTimeout(t, 1*time.Minute, 5*time.Second)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnodeLabels := ret.(map[string]string)\n\t\t\tif _, ok := nodeLabels[pvcLabel]; ok {\n\t\t\t\tstaleLabelNodes = append(staleLabelNodes, n.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(staleLabelNodes) > 0 {\n\t\treturn &ErrLabelNotRemovedFromNode{\n\t\t\tLabel: pvcLabel,\n\t\t\tNodes: staleLabelNodes,\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (k *k8sSchedOps) GetVolumeName(vol *volume.Volume) string {\n\tif vol != nil && vol.ID != \"\" {\n\t\treturn fmt.Sprintf(\"pvc-%s\", vol.ID)\n\t}\n\treturn \"\"\n}\n\nfunc (k *k8sSchedOps) ValidateVolumeCleanup(sched scheduler.Driver, d node.Driver) error {\n\tnodeToPodsMap := make(map[string][]string)\n\tnodeMap := make(map[string]node.Node)\n\n\tconnOpts := node.ConnectionOpts{\n\t\tTimeout:         1 * time.Minute,\n\t\tTimeBeforeRetry: 10 * time.Second,\n\t}\n\tlistVolOpts := node.FindOpts{\n\t\tConnectionOpts: connOpts,\n\t\tName:           \"*portworx-volume\",\n\t}\n\n\tfor _, n := range sched.GetNodes() {\n\t\tif n.Type == node.TypeWorker {\n\t\t\tvolDirList, _ := d.FindFiles(k8sPodsRootDir, n, listVolOpts)\n\t\t\tnodeToPodsMap[n.Name] = separateFilePaths(volDirList)\n\t\t\tnodeMap[n.Name] = n\n\t\t}\n\t}\n\n\texistingPods, _ := k8sops.Instance().GetPods(\"\")\n\n\torphanPodsMap := make(map[string][]string)\n\tdirtyVolPodsMap := make(map[string][]string)\n\n\tfor nodeName, volDirPaths := range nodeToPodsMap {\n\t\tvar orphanPods []string\n\t\tvar dirtyVolPods []string\n\n\t\tfor _, path := range volDirPaths {\n\t\t\tpodUID := extractPodUID(path)\n\t\t\tfound := false\n\t\t\tfor _, existingPod := range existingPods.Items {\n\t\t\t\tif podUID == string(existingPod.UID) {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif found {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\torphanPods = append(orphanPods, podUID)\n\n\t\t\t\/\/ Check if there are files under portworx volume\n\t\t\t\/\/ We use a depth of 2 because the files stored in the volume are in the pvc\n\t\t\t\/\/ directory under the portworx-volume folder for that pod. For instance,\n\t\t\t\/\/ ..\/kubernetes-io~portworx-volume\/pvc-<id>\/<all_user_files>\n\t\t\tn := nodeMap[nodeName]\n\t\t\tfindFileOpts := node.FindOpts{\n\t\t\t\tConnectionOpts: connOpts,\n\t\t\t\tMinDepth:       2,\n\t\t\t\tMaxDepth:       2,\n\t\t\t}\n\t\t\tfiles, _ := d.FindFiles(path, n, findFileOpts)\n\t\t\tif len(strings.TrimSpace(files)) > 0 {\n\t\t\t\tdirtyVolPods = append(dirtyVolPods, podUID)\n\t\t\t}\n\t\t}\n\n\t\tif len(orphanPods) > 0 {\n\t\t\torphanPodsMap[nodeName] = orphanPods\n\t\t\tif len(dirtyVolPods) > 0 {\n\t\t\t\tdirtyVolPodsMap[nodeName] = dirtyVolPods\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(orphanPodsMap) == 0 {\n\t\treturn nil\n\t}\n\treturn &ErrFailedToCleanupVolume{\n\t\tOrphanPods:   orphanPodsMap,\n\t\tDirtyVolPods: dirtyVolPodsMap,\n\t}\n}\n\nfunc separateFilePaths(volDirList string) []string {\n\ttrimmedList := strings.TrimSpace(volDirList)\n\tif trimmedList == \"\" {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(trimmedList, \"\\n\")\n}\n\nfunc extractPodUID(volDirPath string) string {\n\tre := regexp.MustCompile(k8sPodsRootDir +\n\t\t\"\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/.*\")\n\tmatch := re.FindStringSubmatch(volDirPath)\n\tif len(match) > 1 {\n\t\treturn match[1]\n\t}\n\treturn \"\"\n}\n\nfunc init() {\n\tk := &k8sSchedOps{}\n\tRegister(\"k8s\", k)\n}\n<commit_msg>increase timeout to check for removal of volume labels<commit_after>package schedops\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/libopenstorage\/openstorage\/api\"\n\t\"github.com\/portworx\/torpedo\/drivers\/node\"\n\t\"github.com\/portworx\/torpedo\/drivers\/scheduler\"\n\t\"github.com\/portworx\/torpedo\/drivers\/volume\"\n\t\"github.com\/portworx\/torpedo\/pkg\/errors\"\n\t\"github.com\/portworx\/torpedo\/pkg\/k8sops\"\n\t\"github.com\/portworx\/torpedo\/pkg\/task\"\n)\n\nconst (\n\t\/\/ k8sPxRunningLabelKey is the label key used for px state\n\tk8sPxRunningLabelKey = \"px\/enabled\"\n\t\/\/ k8sPxNotRunningLabelValue is label value for a not running px state\n\tk8sPxNotRunningLabelValue = \"false\"\n\t\/\/ k8sPodsRootDir is the directory under which k8s keeps all pods data\n\tk8sPodsRootDir = \"\/var\/lib\/kubelet\/pods\"\n)\n\ntype k8sSchedOps struct{}\n\nfunc (k *k8sSchedOps) DisableOnNode(n node.Node) error {\n\treturn k8sops.Instance().AddLabelOnNode(n.Name, k8sPxRunningLabelKey, k8sPxNotRunningLabelValue)\n}\n\nfunc (k *k8sSchedOps) ValidateOnNode(n node.Node) error {\n\treturn &errors.ErrNotSupported{\n\t\tType:      \"Function\",\n\t\tOperation: \"ValidateOnNode\",\n\t}\n}\n\nfunc (k *k8sSchedOps) EnableOnNode(n node.Node) error {\n\treturn k8sops.Instance().RemoveLabelOnNode(n.Name, k8sPxRunningLabelKey)\n}\n\nfunc (k *k8sSchedOps) ValidateAddLabels(replicaNodes []api.Node, vol *api.Volume) error {\n\tpvc, ok := vol.Locator.VolumeLabels[\"pvc\"]\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tvar missingLabelNodes []string\n\tfor _, rs := range replicaNodes {\n\t\tt := func() (interface{}, error) {\n\t\t\tn, err := k8sops.Instance().GetNodeByName(rs.Id)\n\t\t\tif err == nil && n != nil {\n\t\t\t\treturn n.Labels, nil\n\t\t\t}\n\n\t\t\taddrs := []string{rs.DataIp, rs.MgmtIp}\n\t\t\tn, err = k8sops.Instance().SearchNodeByAddresses(addrs)\n\t\t\tif err == nil && n != nil {\n\t\t\t\treturn n.Labels, nil\n\t\t\t}\n\n\t\t\treturn nil, fmt.Errorf(\"failed to locate node using id: %s and addresses: %v\", rs.Id, addrs)\n\t\t}\n\n\t\tret, err := task.DoRetryWithTimeout(t, 1*time.Minute, 5*time.Second)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnodeLabels := ret.(map[string]string)\n\t\tif _, ok := nodeLabels[pvc]; !ok {\n\t\t\tmissingLabelNodes = append(missingLabelNodes, rs.Id)\n\t\t}\n\t}\n\n\tif len(missingLabelNodes) > 0 {\n\t\treturn &ErrLabelMissingOnNode{\n\t\t\tLabel: pvc,\n\t\t\tNodes: missingLabelNodes,\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (k *k8sSchedOps) ValidateRemoveLabels(vol *volume.Volume, sched scheduler.Driver) error {\n\tpvcLabel := vol.Name\n\tvar staleLabelNodes []string\n\tfor _, n := range sched.GetNodes() {\n\t\tif n.Type == node.TypeWorker {\n\t\t\tt := func() (interface{}, error) {\n\t\t\t\treturn k8sops.Instance().GetLabelsOnNode(n.Name)\n\t\t\t}\n\t\t\tret, err := task.DoRetryWithTimeout(t, 5*time.Minute, 5*time.Second)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tnodeLabels := ret.(map[string]string)\n\t\t\tif _, ok := nodeLabels[pvcLabel]; ok {\n\t\t\t\tstaleLabelNodes = append(staleLabelNodes, n.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(staleLabelNodes) > 0 {\n\t\treturn &ErrLabelNotRemovedFromNode{\n\t\t\tLabel: pvcLabel,\n\t\t\tNodes: staleLabelNodes,\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (k *k8sSchedOps) GetVolumeName(vol *volume.Volume) string {\n\tif vol != nil && vol.ID != \"\" {\n\t\treturn fmt.Sprintf(\"pvc-%s\", vol.ID)\n\t}\n\treturn \"\"\n}\n\nfunc (k *k8sSchedOps) ValidateVolumeCleanup(sched scheduler.Driver, d node.Driver) error {\n\tnodeToPodsMap := make(map[string][]string)\n\tnodeMap := make(map[string]node.Node)\n\n\tconnOpts := node.ConnectionOpts{\n\t\tTimeout:         1 * time.Minute,\n\t\tTimeBeforeRetry: 10 * time.Second,\n\t}\n\tlistVolOpts := node.FindOpts{\n\t\tConnectionOpts: connOpts,\n\t\tName:           \"*portworx-volume\",\n\t}\n\n\tfor _, n := range sched.GetNodes() {\n\t\tif n.Type == node.TypeWorker {\n\t\t\tvolDirList, _ := d.FindFiles(k8sPodsRootDir, n, listVolOpts)\n\t\t\tnodeToPodsMap[n.Name] = separateFilePaths(volDirList)\n\t\t\tnodeMap[n.Name] = n\n\t\t}\n\t}\n\n\texistingPods, _ := k8sops.Instance().GetPods(\"\")\n\n\torphanPodsMap := make(map[string][]string)\n\tdirtyVolPodsMap := make(map[string][]string)\n\n\tfor nodeName, volDirPaths := range nodeToPodsMap {\n\t\tvar orphanPods []string\n\t\tvar dirtyVolPods []string\n\n\t\tfor _, path := range volDirPaths {\n\t\t\tpodUID := extractPodUID(path)\n\t\t\tfound := false\n\t\t\tfor _, existingPod := range existingPods.Items {\n\t\t\t\tif podUID == string(existingPod.UID) {\n\t\t\t\t\tfound = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif found {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\torphanPods = append(orphanPods, podUID)\n\n\t\t\t\/\/ Check if there are files under portworx volume\n\t\t\t\/\/ We use a depth of 2 because the files stored in the volume are in the pvc\n\t\t\t\/\/ directory under the portworx-volume folder for that pod. For instance,\n\t\t\t\/\/ ..\/kubernetes-io~portworx-volume\/pvc-<id>\/<all_user_files>\n\t\t\tn := nodeMap[nodeName]\n\t\t\tfindFileOpts := node.FindOpts{\n\t\t\t\tConnectionOpts: connOpts,\n\t\t\t\tMinDepth:       2,\n\t\t\t\tMaxDepth:       2,\n\t\t\t}\n\t\t\tfiles, _ := d.FindFiles(path, n, findFileOpts)\n\t\t\tif len(strings.TrimSpace(files)) > 0 {\n\t\t\t\tdirtyVolPods = append(dirtyVolPods, podUID)\n\t\t\t}\n\t\t}\n\n\t\tif len(orphanPods) > 0 {\n\t\t\torphanPodsMap[nodeName] = orphanPods\n\t\t\tif len(dirtyVolPods) > 0 {\n\t\t\t\tdirtyVolPodsMap[nodeName] = dirtyVolPods\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(orphanPodsMap) == 0 {\n\t\treturn nil\n\t}\n\treturn &ErrFailedToCleanupVolume{\n\t\tOrphanPods:   orphanPodsMap,\n\t\tDirtyVolPods: dirtyVolPodsMap,\n\t}\n}\n\nfunc separateFilePaths(volDirList string) []string {\n\ttrimmedList := strings.TrimSpace(volDirList)\n\tif trimmedList == \"\" {\n\t\treturn []string{}\n\t}\n\treturn strings.Split(trimmedList, \"\\n\")\n}\n\nfunc extractPodUID(volDirPath string) string {\n\tre := regexp.MustCompile(k8sPodsRootDir +\n\t\t\"\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/.*\")\n\tmatch := re.FindStringSubmatch(volDirPath)\n\tif len(match) > 1 {\n\t\treturn match[1]\n\t}\n\treturn \"\"\n}\n\nfunc init() {\n\tk := &k8sSchedOps{}\n\tRegister(\"k8s\", k)\n}\n<|endoftext|>"}
{"text":"<commit_before>package linebot\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/ API URLs\nconst (\n\tEndPoint          = \"https:\/\/api.line.me\"\n\tPushMessage       = \"\/v2\/bot\/message\/push\"\n\tReplyMessage      = \"\/v2\/bot\/message\/reply\"\n\tGetMessageContent = \"\/v2\/bot\/message\/%s\/content\"\n\tLeaveGroup        = \"\/v2\/bot\/group\/%s\/leave\"\n\tLeaveRoom         = \"\/v2\/bot\/room\/%s\/leave\"\n\tGetProfile        = \"\/v2\/bot\/profile\/%s\"\n)\n\n\/\/ APISendResult ...\ntype APISendResult struct {\n\tMessage string `json:\"message\"`\n}\n\n\/\/ BasicResponse ...\ntype BasicResponse struct {\n}\n\n\/\/ MessageContentResponse ...\ntype MessageContentResponse struct {\n\tContent       io.ReadCloser\n\tContentLength int64\n\tContentType   string\n}\n\n\/\/ UserProfileResponse ...\ntype UserProfileResponse struct {\n\tUserID        string `json:\"userId\"`\n\tDisplayName   string `json:\"displayName\"`\n\tPictureURL    string `json:\"pictureUrl\"`\n\tStatusMessage string `json:\"statusMessage\"`\n}\n\n\/\/ Client ...\ntype Client struct {\n\tendPoint           string\n\tchannelAccessToken string\n}\n\nvar eventHandler EventHandler\nvar channelSecret string\n\n\/\/ NewClient ...\nfunc NewClient(channelAccessToken string) *Client {\n\treturn &Client{\n\t\tchannelAccessToken: channelAccessToken,\n\t\tendPoint:           EndPoint,\n\t}\n}\n\n\/\/ SetEventHandler ...\nfunc (c *Client) SetEventHandler(event EventHandler) {\n\teventHandler = event\n}\n\n\/\/ SetChannelSecret ...\nfunc (c *Client) SetChannelSecret(secret string) {\n\tchannelSecret = secret\n}\n\nfunc (c *Client) setHeader(req *http.Request) *http.Request {\n\treq.Header.Set(\"Content-Type\", \"application\/json; charset=UTF-8\")\n\treq.Header.Set(\"X-LINE-ChannelToken\", c.channelAccessToken)\n\treq.Header.Set(\"Authorization\", \"Bearer \"+c.channelAccessToken)\n\treq.Header.Set(\"User-Agent\", \"dongri\/line-bot-sdk-go\")\n\treturn req\n}\n\nfunc (c *Client) do(req *http.Request) (*http.Response, []byte, error) {\n\treq = c.setHeader(req)\n\tclient := &http.Client{\n\t\tTimeout: time.Duration(30 * time.Second),\n\t}\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn res, nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode < 200 || res.StatusCode >= 400 {\n\t\tbody, readErr := ioutil.ReadAll(res.Body)\n\t\tif readErr != nil {\n\t\t\treturn res, nil, readErr\n\t\t}\n\t\tvar result APISendResult\n\t\tif unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {\n\t\t\treturn res, nil, unmarshalErr\n\t\t}\n\t\tfmt.Println(result)\n\t\treturn res, nil, errors.New(\"server error status code: \" + strconv.Itoa(res.StatusCode))\n\t}\n\tbody, err := ioutil.ReadAll(res.Body)\n\treturn res, body, err\n}\n\n\/\/ ReplyMessage ...\nfunc (c *Client) ReplyMessage(replyToken string, messages ...Message) (*APISendResult, error) {\n\treplyMessage := struct {\n\t\tReplyToken string    `json:\"replyToken\"`\n\t\tMessages   []Message `json:\"messages\"`\n\t}{\n\t\tReplyToken: replyToken,\n\t\tMessages:   messages,\n\t}\n\tb, err := json.Marshal(replyMessage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := http.NewRequest(\"POST\", EndPoint+ReplyMessage, bytes.NewBuffer(b))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, body, err := c.do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar result APISendResult\n\tif err := json.Unmarshal(body, &result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}\n\n\/\/ GetMessageContent ...\nfunc (c *Client) GetMessageContent(messageID string) (*MessageContentResponse, error) {\n\tendpoint := fmt.Sprintf(EndPoint+GetMessageContent, messageID)\n\treq, err := http.NewRequest(\"GET\", endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres, _, err := c.do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := MessageContentResponse{\n\t\tContent:       res.Body,\n\t\tContentType:   res.Header.Get(\"Content-Type\"),\n\t\tContentLength: res.ContentLength,\n\t}\n\treturn &result, nil\n}\n\n\/\/ GetProfile ...\nfunc (c *Client) GetProfile(userID string) (*UserProfileResponse, error) {\n\tendpoint := fmt.Sprintf(EndPoint+GetProfile, userID)\n\treq, err := http.NewRequest(\"GET\", endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, body, err := c.do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := UserProfileResponse{}\n\tif err := json.Unmarshal(body, &result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}\n\n\/\/ LeaveGroup ...\nfunc (c *Client) LeaveGroup(groupID string) (*BasicResponse, error) {\n\tendpoint := fmt.Sprintf(EndPoint+LeaveGroup, groupID)\n\treq, err := http.NewRequest(\"POST\", endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, body, err := c.do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := BasicResponse{}\n\tif err := json.Unmarshal(body, &result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}\n\n\/\/ LeaveRoom ...\nfunc (c *Client) LeaveRoom(roomID string) (*BasicResponse, error) {\n\tendpoint := fmt.Sprintf(EndPoint+LeaveRoom, roomID)\n\treq, err := http.NewRequest(\"POST\", endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, body, err := c.do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := BasicResponse{}\n\tif err := json.Unmarshal(body, &result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}\n<commit_msg>Fix: content type<commit_after>package linebot\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/ API URLs\nconst (\n\tEndPoint          = \"https:\/\/api.line.me\"\n\tPushMessage       = \"\/v2\/bot\/message\/push\"\n\tReplyMessage      = \"\/v2\/bot\/message\/reply\"\n\tGetMessageContent = \"\/v2\/bot\/message\/%s\/content\"\n\tLeaveGroup        = \"\/v2\/bot\/group\/%s\/leave\"\n\tLeaveRoom         = \"\/v2\/bot\/room\/%s\/leave\"\n\tGetProfile        = \"\/v2\/bot\/profile\/%s\"\n)\n\n\/\/ APISendResult ...\ntype APISendResult struct {\n\tMessage string `json:\"message\"`\n}\n\n\/\/ BasicResponse ...\ntype BasicResponse struct {\n}\n\n\/\/ MessageContentResponse ...\ntype MessageContentResponse struct {\n\tContent       []byte\n\tContentLength int64\n\tContentType   string\n}\n\n\/\/ UserProfileResponse ...\ntype UserProfileResponse struct {\n\tUserID        string `json:\"userId\"`\n\tDisplayName   string `json:\"displayName\"`\n\tPictureURL    string `json:\"pictureUrl\"`\n\tStatusMessage string `json:\"statusMessage\"`\n}\n\n\/\/ Client ...\ntype Client struct {\n\tendPoint           string\n\tchannelAccessToken string\n}\n\nvar eventHandler EventHandler\nvar channelSecret string\n\n\/\/ NewClient ...\nfunc NewClient(channelAccessToken string) *Client {\n\treturn &Client{\n\t\tchannelAccessToken: channelAccessToken,\n\t\tendPoint:           EndPoint,\n\t}\n}\n\n\/\/ SetEventHandler ...\nfunc (c *Client) SetEventHandler(event EventHandler) {\n\teventHandler = event\n}\n\n\/\/ SetChannelSecret ...\nfunc (c *Client) SetChannelSecret(secret string) {\n\tchannelSecret = secret\n}\n\nfunc (c *Client) setHeader(req *http.Request) *http.Request {\n\treq.Header.Set(\"Content-Type\", \"application\/json; charset=UTF-8\")\n\treq.Header.Set(\"X-LINE-ChannelToken\", c.channelAccessToken)\n\treq.Header.Set(\"Authorization\", \"Bearer \"+c.channelAccessToken)\n\treq.Header.Set(\"User-Agent\", \"dongri\/line-bot-sdk-go\")\n\treturn req\n}\n\nfunc (c *Client) do(req *http.Request) (*http.Response, []byte, error) {\n\treq = c.setHeader(req)\n\tclient := &http.Client{\n\t\tTimeout: time.Duration(30 * time.Second),\n\t}\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\treturn res, nil, err\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode < 200 || res.StatusCode >= 400 {\n\t\tbody, readErr := ioutil.ReadAll(res.Body)\n\t\tif readErr != nil {\n\t\t\treturn res, nil, readErr\n\t\t}\n\t\tvar result APISendResult\n\t\tif unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {\n\t\t\treturn res, nil, unmarshalErr\n\t\t}\n\t\tfmt.Println(result)\n\t\treturn res, nil, errors.New(\"server error status code: \" + strconv.Itoa(res.StatusCode))\n\t}\n\tbody, err := ioutil.ReadAll(res.Body)\n\treturn res, body, err\n}\n\n\/\/ ReplyMessage ...\nfunc (c *Client) ReplyMessage(replyToken string, messages ...Message) (*APISendResult, error) {\n\treplyMessage := struct {\n\t\tReplyToken string    `json:\"replyToken\"`\n\t\tMessages   []Message `json:\"messages\"`\n\t}{\n\t\tReplyToken: replyToken,\n\t\tMessages:   messages,\n\t}\n\tb, err := json.Marshal(replyMessage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := http.NewRequest(\"POST\", EndPoint+ReplyMessage, bytes.NewBuffer(b))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, body, err := c.do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar result APISendResult\n\tif err := json.Unmarshal(body, &result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}\n\n\/\/ GetMessageContent ...\nfunc (c *Client) GetMessageContent(messageID string) (*MessageContentResponse, error) {\n\tendpoint := fmt.Sprintf(EndPoint+GetMessageContent, messageID)\n\treq, err := http.NewRequest(\"GET\", endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres, body, err := c.do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := MessageContentResponse{\n\t\tContent:       body,\n\t\tContentType:   res.Header.Get(\"Content-Type\"),\n\t\tContentLength: res.ContentLength,\n\t}\n\treturn &result, nil\n}\n\n\/\/ GetProfile ...\nfunc (c *Client) GetProfile(userID string) (*UserProfileResponse, error) {\n\tendpoint := fmt.Sprintf(EndPoint+GetProfile, userID)\n\treq, err := http.NewRequest(\"GET\", endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, body, err := c.do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := UserProfileResponse{}\n\tif err := json.Unmarshal(body, &result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}\n\n\/\/ LeaveGroup ...\nfunc (c *Client) LeaveGroup(groupID string) (*BasicResponse, error) {\n\tendpoint := fmt.Sprintf(EndPoint+LeaveGroup, groupID)\n\treq, err := http.NewRequest(\"POST\", endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, body, err := c.do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := BasicResponse{}\n\tif err := json.Unmarshal(body, &result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}\n\n\/\/ LeaveRoom ...\nfunc (c *Client) LeaveRoom(roomID string) (*BasicResponse, error) {\n\tendpoint := fmt.Sprintf(EndPoint+LeaveRoom, roomID)\n\treq, err := http.NewRequest(\"POST\", endpoint, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, body, err := c.do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := BasicResponse{}\n\tif err := json.Unmarshal(body, &result); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ (c) 2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage health\n\nimport (\n\t\"net\/http\"\n\t\"time\"\n\n\thealth \"github.com\/AppsFlyer\/go-sundheit\"\n\t\"github.com\/AppsFlyer\/go-sundheit\/checks\"\n\t\"github.com\/gorilla\/rpc\/v2\"\n\n\t\"github.com\/ava-labs\/avalanchego\/snow\/engine\/common\"\n\t\"github.com\/ava-labs\/avalanchego\/utils\/constants\"\n\t\"github.com\/ava-labs\/avalanchego\/utils\/json\"\n\t\"github.com\/ava-labs\/avalanchego\/utils\/logging\"\n)\n\n\/\/ defaultCheckOpts is a Check whose properties represent a default Check\nvar defaultCheckOpts = check{\n\texecutionPeriod: 30 * time.Second,\n\tinitialDelay:    10 * time.Second,\n}\n\n\/\/ Health observes a set of vital signs and makes them available through an HTTP\n\/\/ API.\ntype Health struct {\n\tlog logging.Logger\n\t\/\/ performs the underlying health checks\n\thealth health.Health\n}\n\n\/\/ NewService creates a new Health service\nfunc NewService(log logging.Logger) *Health {\n\treturn &Health{log, health.New()}\n}\n\n\/\/ Handler returns an HTTPHandler providing RPC access to the Health service\nfunc (h *Health) Handler() (*common.HTTPHandler, error) {\n\tnewServer := rpc.NewServer()\n\tcodec := json.NewCodec()\n\tnewServer.RegisterCodec(codec, \"application\/json\")\n\tnewServer.RegisterCodec(codec, \"application\/json;charset=UTF-8\")\n\tif err := newServer.RegisterService(h, \"health\"); err != nil {\n\t\treturn nil, err\n\t}\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == http.MethodGet { \/\/ GET request --> return 200 if getLiveness returns true, else 503\n\t\t\tif _, healthy := h.health.Results(); healthy {\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t} else {\n\t\t\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t\t\t}\n\t\t} else {\n\t\t\tnewServer.ServeHTTP(w, r) \/\/ Other request --> use JSON RPC\n\t\t}\n\t})\n\treturn &common.HTTPHandler{LockOptions: common.NoLock, Handler: handler}, nil\n}\n\n\/\/ RegisterHeartbeat adds a check with default options and a CheckFn that checks\n\/\/ the given heartbeater for a recent heartbeat\nfunc (h *Health) RegisterHeartbeat(name string, hb Heartbeater, max time.Duration) error {\n\treturn h.RegisterCheck(&check{\n\t\tname:            name,\n\t\tcheckFn:         HeartbeatCheckFn(hb, max),\n\t\tinitialDelay:    constants.DefaultHealthCheckInitialDelay,\n\t\texecutionPeriod: constants.DefaultHealthCheckExecutionPeriod,\n\t})\n}\n\n\/\/ RegisterMonotonicCheckFunc adds a Check with default options and the given CheckFn\n\/\/ After it passes once, its logic (checkFunc) is never run again; it just passes\nfunc (h *Health) RegisterMonotonicCheckFunc(name string, checkFn func() (interface{}, error)) error {\n\tcheck := monotonicCheck{check: defaultCheckOpts}\n\tcheck.name = name\n\tcheck.checkFn = checkFn\n\treturn h.RegisterCheck(check)\n}\n\n\/\/ RegisterCheck adds the given Check\nfunc (h *Health) RegisterCheck(c checks.Check) error {\n\treturn h.health.RegisterCheck(&health.Config{\n\t\tInitialDelay:    constants.DefaultHealthCheckInitialDelay,\n\t\tExecutionPeriod: constants.DefaultHealthCheckExecutionPeriod,\n\t\tCheck:           c,\n\t})\n}\n\n\/\/ GetLivenessArgs are the arguments for GetLiveness\ntype GetLivenessArgs struct{}\n\n\/\/ GetLivenessReply is the response for GetLiveness\ntype GetLivenessReply struct {\n\tChecks  map[string]health.Result `json:\"checks\"`\n\tHealthy bool                     `json:\"healthy\"`\n}\n\n\/\/ GetLiveness returns a summation of the health of the node\nfunc (h *Health) GetLiveness(_ *http.Request, _ *GetLivenessArgs, reply *GetLivenessReply) error {\n\th.log.Info(\"Health: GetLiveness called\")\n\treply.Checks, reply.Healthy = h.health.Results()\n\treturn nil\n}\n<commit_msg>cleanup<commit_after>\/\/ (c) 2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage health\n\nimport (\n\t\"net\/http\"\n\t\"time\"\n\n\thealth \"github.com\/AppsFlyer\/go-sundheit\"\n\t\"github.com\/AppsFlyer\/go-sundheit\/checks\"\n\t\"github.com\/gorilla\/rpc\/v2\"\n\n\t\"github.com\/ava-labs\/avalanchego\/snow\/engine\/common\"\n\t\"github.com\/ava-labs\/avalanchego\/utils\/constants\"\n\t\"github.com\/ava-labs\/avalanchego\/utils\/json\"\n\t\"github.com\/ava-labs\/avalanchego\/utils\/logging\"\n)\n\n\/\/ Health observes a set of vital signs and makes them available through an HTTP\n\/\/ API.\ntype Health struct {\n\tlog logging.Logger\n\t\/\/ performs the underlying health checks\n\thealth health.Health\n}\n\n\/\/ NewService creates a new Health service\nfunc NewService(log logging.Logger) *Health {\n\treturn &Health{log, health.New()}\n}\n\n\/\/ Handler returns an HTTPHandler providing RPC access to the Health service\nfunc (h *Health) Handler() (*common.HTTPHandler, error) {\n\tnewServer := rpc.NewServer()\n\tcodec := json.NewCodec()\n\tnewServer.RegisterCodec(codec, \"application\/json\")\n\tnewServer.RegisterCodec(codec, \"application\/json;charset=UTF-8\")\n\tif err := newServer.RegisterService(h, \"health\"); err != nil {\n\t\treturn nil, err\n\t}\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Method == http.MethodGet { \/\/ GET request --> return 200 if getLiveness returns true, else 503\n\t\t\tif _, healthy := h.health.Results(); healthy {\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t} else {\n\t\t\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t\t\t}\n\t\t} else {\n\t\t\tnewServer.ServeHTTP(w, r) \/\/ Other request --> use JSON RPC\n\t\t}\n\t})\n\treturn &common.HTTPHandler{LockOptions: common.NoLock, Handler: handler}, nil\n}\n\n\/\/ RegisterHeartbeat adds a check with default options and a CheckFn that checks\n\/\/ the given heartbeater for a recent heartbeat\nfunc (h *Health) RegisterHeartbeat(name string, hb Heartbeater, max time.Duration) error {\n\treturn h.RegisterCheck(&check{\n\t\tname:            name,\n\t\tcheckFn:         HeartbeatCheckFn(hb, max),\n\t\tinitialDelay:    constants.DefaultHealthCheckInitialDelay,\n\t\texecutionPeriod: constants.DefaultHealthCheckExecutionPeriod,\n\t})\n}\n\n\/\/ RegisterMonotonicCheckFunc adds a Check with default options and the given CheckFn\n\/\/ After it passes once, its logic (checkFunc) is never run again; it just passes\nfunc (h *Health) RegisterMonotonicCheckFunc(name string, checkFn func() (interface{}, error)) error {\n\tcheck := monotonicCheck{\n\t\tcheck: check{\n\t\t\tname: name,\n\t\t\tcheckFn: checkFn,\n\t\t\texecutionPeriod: constants.DefaultHealthCheckExecutionPeriod,\n\t\t\tinitialDelay: constants.DefaultHealthCheckInitialDelay,\n\t\t}\n\t}\n\treturn h.RegisterCheck(check)\n}\n\n\/\/ RegisterCheck adds the given Check\nfunc (h *Health) RegisterCheck(c checks.Check) error {\n\treturn h.health.RegisterCheck(&health.Config{\n\t\tInitialDelay:    constants.DefaultHealthCheckInitialDelay,\n\t\tExecutionPeriod: constants.DefaultHealthCheckExecutionPeriod,\n\t\tCheck:           c,\n\t})\n}\n\n\/\/ GetLivenessArgs are the arguments for GetLiveness\ntype GetLivenessArgs struct{}\n\n\/\/ GetLivenessReply is the response for GetLiveness\ntype GetLivenessReply struct {\n\tChecks  map[string]health.Result `json:\"checks\"`\n\tHealthy bool                     `json:\"healthy\"`\n}\n\n\/\/ GetLiveness returns a summation of the health of the node\nfunc (h *Health) GetLiveness(_ *http.Request, _ *GetLivenessArgs, reply *GetLivenessReply) error {\n\th.log.Info(\"Health: GetLiveness called\")\n\treply.Checks, reply.Healthy = h.health.Results()\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build ignore\n\npackage main\n\nimport (\n\t\".\"\n\t\"flag\"\n\t\"github.com\/bmizerany\/pat\"\n\t\"github.com\/timeredbull\/tsuru\/api\/app\"\n\t\"github.com\/timeredbull\/tsuru\/api\/auth\"\n\t\"github.com\/timeredbull\/tsuru\/config\"\n\t\"github.com\/timeredbull\/tsuru\/api\/service\"\n\t\"github.com\/timeredbull\/tsuru\/db\"\n\t\"github.com\/timeredbull\/tsuru\/log\"\n\tstdlog \"log\"\n\t\"log\/syslog\"\n\t\"net\/http\"\n)\n\nfunc main() {\n\tvar err error\n\tlog.Target, err = syslog.NewLogger(syslog.LOG_INFO, stdlog.LstdFlags)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tconfigFile := flag.String(\"config\", \"\/etc\/tsuru\/tsuru.conf\", \"tsuru config file\")\n\tdry := flag.Bool(\"dry\", false, \"dry-run: does not start the server (for testing purpose)\")\n\tflag.Parse()\n\terr = config.ReadConfigFile(*configFile)\n\tif err != nil {\n\t\tlog.Panic(err.Error())\n\t}\n\tdb.Session, err = db.Open(config.GetString(\"database:host\"), config.GetString(\"database:name\"))\n\tif err != nil {\n\t\tlog.Panic(err.Error())\n\t}\n\tdefer db.Session.Close()\n\tm := pat.New()\n\n\tm.Post(\"\/services\", webserver.Handler(service.CreateHandler))\n\tm.Get(\"\/services\", webserver.Handler(service.ServicesHandler))\n\tm.Get(\"\/services\/types\", webserver.Handler(service.ServiceTypesHandler))\n\tm.Get(\"\/services\/:name\", webserver.Handler(service.DeleteHandler))\n\tm.Post(\"\/services\/bind\", webserver.Handler(service.BindHandler))\n\tm.Post(\"\/services\/unbind\", webserver.Handler(service.UnbindHandler))\n\n\tm.Get(\"\/apps\/:name\/delete\", webserver.Handler(app.AppDelete))\n\tm.Get(\"\/apps\/:name\/clone\", webserver.Handler(app.CloneRepositoryHandler))\n\tm.Get(\"\/apps\/:name\", webserver.Handler(app.AppInfo))\n\tm.Post(\"\/apps\/:name\/application\", webserver.Handler(app.Upload))\n\tm.Get(\"\/apps\", webserver.Handler(app.AppList))\n\tm.Post(\"\/apps\", webserver.Handler(app.CreateAppHandler))\n\tm.Put(\"\/apps\/:app\/:team\", webserver.AuthorizationRequiredHandler(app.GrantAccessToTeamHandler))\n\tm.Del(\"\/apps\/:app\/:team\", webserver.AuthorizationRequiredHandler(app.RevokeAccessFromTeamHandler))\n\n\tm.Post(\"\/users\", webserver.Handler(auth.CreateUser))\n\tm.Post(\"\/users\/:email\/tokens\", webserver.Handler(auth.Login))\n\tm.Get(\"\/users\/check-authorization\", webserver.Handler(auth.CheckAuthorization))\n\n\tm.Post(\"\/teams\", webserver.AuthorizationRequiredHandler(auth.CreateTeam))\n\tm.Put(\"\/teams\/:team\/:user\", webserver.AuthorizationRequiredHandler(auth.AddUserToTeam))\n\tm.Del(\"\/teams\/:team\/:user\", webserver.AuthorizationRequiredHandler(auth.RemoveUserFromTeam))\n\n\tlisten := config.GetString(\"listen\")\n\tif !*dry {\n\t\tlog.Fatal(http.ListenAndServe(listen, m))\n\t}\n}\n<commit_msg>api\/webserver: using the new GetString signature<commit_after>\/\/ +build ignore\n\npackage main\n\nimport (\n\t\".\"\n\t\"flag\"\n\t\"github.com\/bmizerany\/pat\"\n\t\"github.com\/timeredbull\/tsuru\/api\/app\"\n\t\"github.com\/timeredbull\/tsuru\/api\/auth\"\n\t\"github.com\/timeredbull\/tsuru\/config\"\n\t\"github.com\/timeredbull\/tsuru\/api\/service\"\n\t\"github.com\/timeredbull\/tsuru\/db\"\n\t\"github.com\/timeredbull\/tsuru\/log\"\n\tstdlog \"log\"\n\t\"log\/syslog\"\n\t\"net\/http\"\n)\n\nfunc main() {\n\tvar err error\n\tlog.Target, err = syslog.NewLogger(syslog.LOG_INFO, stdlog.LstdFlags)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tconfigFile := flag.String(\"config\", \"\/etc\/tsuru\/tsuru.conf\", \"tsuru config file\")\n\tdry := flag.Bool(\"dry\", false, \"dry-run: does not start the server (for testing purpose)\")\n\tflag.Parse()\n\terr = config.ReadConfigFile(*configFile)\n\tif err != nil {\n\t\tlog.Panic(err.Error())\n\t}\n\tconnString, err := config.GetString(\"database:host\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdbName, err := config.GetString(\"database:name\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdb.Session, err = db.Open(connString, dbName)\n\tif err != nil {\n\t\tlog.Panic(err.Error())\n\t}\n\tdefer db.Session.Close()\n\tm := pat.New()\n\n\tm.Post(\"\/services\", webserver.Handler(service.CreateHandler))\n\tm.Get(\"\/services\", webserver.Handler(service.ServicesHandler))\n\tm.Get(\"\/services\/types\", webserver.Handler(service.ServiceTypesHandler))\n\tm.Get(\"\/services\/:name\", webserver.Handler(service.DeleteHandler))\n\tm.Post(\"\/services\/bind\", webserver.Handler(service.BindHandler))\n\tm.Post(\"\/services\/unbind\", webserver.Handler(service.UnbindHandler))\n\n\tm.Get(\"\/apps\/:name\/delete\", webserver.Handler(app.AppDelete))\n\tm.Get(\"\/apps\/:name\/clone\", webserver.Handler(app.CloneRepositoryHandler))\n\tm.Get(\"\/apps\/:name\", webserver.Handler(app.AppInfo))\n\tm.Post(\"\/apps\/:name\/application\", webserver.Handler(app.Upload))\n\tm.Get(\"\/apps\", webserver.Handler(app.AppList))\n\tm.Post(\"\/apps\", webserver.Handler(app.CreateAppHandler))\n\tm.Put(\"\/apps\/:app\/:team\", webserver.AuthorizationRequiredHandler(app.GrantAccessToTeamHandler))\n\tm.Del(\"\/apps\/:app\/:team\", webserver.AuthorizationRequiredHandler(app.RevokeAccessFromTeamHandler))\n\n\tm.Post(\"\/users\", webserver.Handler(auth.CreateUser))\n\tm.Post(\"\/users\/:email\/tokens\", webserver.Handler(auth.Login))\n\tm.Get(\"\/users\/check-authorization\", webserver.Handler(auth.CheckAuthorization))\n\n\tm.Post(\"\/teams\", webserver.AuthorizationRequiredHandler(auth.CreateTeam))\n\tm.Put(\"\/teams\/:team\/:user\", webserver.AuthorizationRequiredHandler(auth.AddUserToTeam))\n\tm.Del(\"\/teams\/:team\/:user\", webserver.AuthorizationRequiredHandler(auth.RemoveUserFromTeam))\n\n\tlisten, err := config.GetString(\"listen\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif !*dry {\n\t\tlog.Fatal(http.ListenAndServe(listen, m))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package controllers\n\nimport (\n\t\"github.com\/lfq7413\/tomato\/rest\"\n\t\"github.com\/lfq7413\/tomato\/types\"\n\t\"github.com\/lfq7413\/tomato\/utils\"\n)\n\n\/\/ LogoutController ...\ntype LogoutController struct {\n\tObjectsController\n}\n\n\/\/ HandleLogOut ...\n\/\/ @router \/ [post]\nfunc (l *LogoutController) HandleLogOut() {\n\tif l.Info != nil && l.Info.SessionToken != \"\" {\n\t\twhere := types.M{\n\t\t\t\"sessionToken\": l.Info.SessionToken,\n\t\t}\n\t\t\/\/ TODO 处理错误\n\t\trecords, _ := rest.Find(rest.Master(), \"_Session\", where, types.M{})\n\t\tif utils.HasResults(records) {\n\t\t\tresults := utils.SliceInterface(records[\"results\"])\n\t\t\tobj := utils.MapInterface(results[0])\n\t\t\trest.Delete(rest.Master(), \"_Session\", utils.String(obj[\"objectId\"]))\n\t\t}\n\t}\n\tl.Data[\"json\"] = types.M{}\n\tl.ServeJSON()\n}\n\n\/\/ Get ...\n\/\/ @router \/ [get]\nfunc (l *LogoutController) Get() {\n\tl.ObjectsController.Get()\n}\n\n\/\/ Delete ...\n\/\/ @router \/ [delete]\nfunc (l *LogoutController) Delete() {\n\tl.ObjectsController.Delete()\n}\n\n\/\/ Put ...\n\/\/ @router \/ [put]\nfunc (l *LogoutController) Put() {\n\tl.ObjectsController.Put()\n}\n<commit_msg>重构 logout.go<commit_after>package controllers\n\nimport (\n\t\"github.com\/lfq7413\/tomato\/errs\"\n\t\"github.com\/lfq7413\/tomato\/rest\"\n\t\"github.com\/lfq7413\/tomato\/types\"\n\t\"github.com\/lfq7413\/tomato\/utils\"\n)\n\n\/\/ LogoutController 处理 \/logout 接口的请求\ntype LogoutController struct {\n\tObjectsController\n}\n\n\/\/ HandleLogOut 处理用户退出请求\n\/\/ @router \/ [post]\nfunc (l *LogoutController) HandleLogOut() {\n\tif l.Info != nil && l.Info.SessionToken != \"\" {\n\t\twhere := types.M{\n\t\t\t\"sessionToken\": l.Info.SessionToken,\n\t\t}\n\t\trecords, err := rest.Find(rest.Master(), \"_Session\", where, types.M{})\n\n\t\tif err != nil {\n\t\t\tl.Data[\"json\"] = errs.ErrorToMap(err)\n\t\t\tl.ServeJSON()\n\t\t\treturn\n\t\t}\n\t\tif utils.HasResults(records) {\n\t\t\tresults := utils.SliceInterface(records[\"results\"])\n\t\t\tobj := utils.MapInterface(results[0])\n\t\t\terr := rest.Delete(rest.Master(), \"_Session\", utils.String(obj[\"objectId\"]))\n\t\t\tif err != nil {\n\t\t\t\tl.Data[\"json\"] = errs.ErrorToMap(err)\n\t\t\t\tl.ServeJSON()\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tl.Data[\"json\"] = types.M{}\n\tl.ServeJSON()\n}\n\n\/\/ Get ...\n\/\/ @router \/ [get]\nfunc (l *LogoutController) Get() {\n\tl.ObjectsController.Get()\n}\n\n\/\/ Delete ...\n\/\/ @router \/ [delete]\nfunc (l *LogoutController) Delete() {\n\tl.ObjectsController.Delete()\n}\n\n\/\/ Put ...\n\/\/ @router \/ [put]\nfunc (l *LogoutController) Put() {\n\tl.ObjectsController.Put()\n}\n<|endoftext|>"}
{"text":"<commit_before>package physics\n\nimport (\n\t\"bytes\"\n\t\"compress\/flate\"\n\n\t\"github.com\/egonelbre\/exp\/bit\"\n\t\"github.com\/egonelbre\/exp\/bit\/expgolomb\"\n)\n\nfunc encode32(v int32) uint64 { return uint64(bit.AbsEncode(int64(v))) }\nfunc decode32(v uint64) int32 { return int32(bit.AbsDecode(v)) }\n\nfunc write(w *bit.Writer, v int32, bits uint64) {\n\tw.WriteBits(uint64(v), bits)\n}\nfunc read(r *bit.Reader, bits uint64) int32 {\n\tv, _ := r.ReadBits(bits)\n\treturn int32(v)\n}\n\nfunc write32(w *bit.Writer, v int32, bits uint64) {\n\tw.WriteBits(bit.AbsEncode(int64(v)), bits)\n}\n\nfunc read32(r *bit.Reader, bits uint64) int32 {\n\tv, _ := r.ReadBits(bits)\n\treturn int32(bit.AbsDecode(v))\n}\n\ntype bits struct {\n\tABC uint64\n\tXYZ uint64\n}\n\nfunc (b *bits) WriteTo(w *bit.Writer) {\n\texpgolomb.WriteInt(w, int(b.ABC)-0xA)\n\texpgolomb.WriteInt(w, int(b.XYZ)-0xA)\n}\n\nfunc (b *bits) ReadFrom(r *bit.Reader) {\n\tabc, _ := expgolomb.ReadInt(r)\n\txyz, _ := expgolomb.ReadInt(r)\n\n\tb.ABC = uint64(abc + 0xA)\n\tb.XYZ = uint64(xyz + 0xA)\n}\n\nfunc (b *bits) Update(baseline, current *Frame) {\n\tfor i, cube := range current.Cubes {\n\t\tbase := baseline.Cubes[i]\n\t\tb.ABC = maxbits(b.ABC, cube.A^base.A)\n\t\tb.ABC = maxbits(b.ABC, cube.B^base.B)\n\t\tb.ABC = maxbits(b.ABC, cube.C^base.C)\n\t\tb.XYZ = maxbits(b.XYZ, cube.X^base.X)\n\t\tb.XYZ = maxbits(b.XYZ, cube.Y^base.Y)\n\t\tb.XYZ = maxbits(b.XYZ, cube.Z^base.Z)\n\t}\n}\n\nfunc maxbits(a uint64, b int32) uint64 {\n\tx := bit.AbsEncode(int64(b))\n\tw := bit.ScanRight(x) + 1\n\tif a < w {\n\t\treturn w\n\t}\n\treturn a\n}\n\nfunc (s *State) Encode() []byte {\n\tvar buf bytes.Buffer\n\n\tpack, _ := flate.NewWriter(&buf, flate.DefaultCompression)\n\tw := bit.NewWriter(pack)\n\n\tbaseline := s.Baseline()\n\tcurrent := s.Current()\n\n\tvar bits bits\n\tbits.Update(baseline, current)\n\tbits.WriteTo(w)\n\n\tfor i, cube := range current.Cubes {\n\t\tbase := baseline.Cubes[i]\n\n\t\twrite(w, cube.Interacting^base.Interacting, 1)\n\t\twrite(w, cube.Largest^base.Largest, 2)\n\n\t\twrite32(w, cube.A^base.A, bits.ABC)\n\t\twrite32(w, cube.B^base.B, bits.ABC)\n\t\twrite32(w, cube.C^base.C, bits.ABC)\n\n\t\twrite32(w, cube.X^base.X, bits.XYZ)\n\t\twrite32(w, cube.Y^base.Y, bits.XYZ)\n\t\twrite32(w, cube.Z^base.Z, bits.XYZ)\n\t}\n\n\tw.Close()\n\tpack.Close()\n\treturn buf.Bytes()\n}\n\nfunc (s *State) Decode(snapshot []byte) {\n\tbuf := bytes.NewBuffer(snapshot)\n\tpack := flate.NewReader(buf)\n\tr := bit.NewReader(pack)\n\n\tbaseline := s.Baseline()\n\tcurrent := s.Current()\n\n\tvar bits bits\n\tbits.ReadFrom(r)\n\n\tfor i := range current.Cubes {\n\t\tbase := baseline.Cubes[i]\n\t\tcube := &current.Cubes[i]\n\n\t\tcube.Interacting = read(r, 1) ^ base.Interacting\n\t\tcube.Largest = read(r, 2) ^ base.Largest\n\n\t\tcube.A = read32(r, bits.ABC) ^ base.A\n\t\tcube.B = read32(r, bits.ABC) ^ base.B\n\t\tcube.C = read32(r, bits.ABC) ^ base.C\n\n\t\tcube.X = read32(r, bits.XYZ) ^ base.X\n\t\tcube.Y = read32(r, bits.XYZ) ^ base.Y\n\t\tcube.Z = read32(r, bits.XYZ) ^ base.Z\n\t}\n}\n<commit_msg>Fix things<commit_after>package physics\n\nimport (\n\t\"bytes\"\n\t\"compress\/flate\"\n\n\t\"github.com\/egonelbre\/exp\/bit\"\n)\n\nfunc encode32(v int32) uint64 { return uint64(bit.AbsEncode(int64(v))) }\nfunc decode32(v uint64) int32 { return int32(bit.AbsDecode(v)) }\n\nfunc write(w *bit.Writer, v int32, bits uint64) {\n\tw.WriteBits(uint64(v), bits)\n}\nfunc read(r *bit.Reader, bits uint64) int32 {\n\tv, _ := r.ReadBits(bits)\n\treturn int32(v)\n}\n\nfunc write32(w *bit.Writer, v int32, bits uint64) {\n\tw.WriteBits(bit.AbsEncode(int64(v)), bits)\n}\n\nfunc read32(r *bit.Reader, bits uint64) int32 {\n\tv, _ := r.ReadBits(bits)\n\treturn int32(bit.AbsDecode(v))\n}\n\nfunc maxbits(vs ...int32) (r uint64) {\n\tr = 0\n\tfor _, x := range vs {\n\t\tif x != 0 {\n\t\t\tbits := bit.ScanRight(bit.AbsEncode(int64(x))) + 4\n\t\t\tif r < bits {\n\t\t\t\tr = bits\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\nfunc deltabits(base, cube *Cube) uint64 {\n\treturn maxbits(\n\t\tcube.Interacting^base.Interacting,\n\t\tcube.Largest^base.Largest,\n\t\tcube.A^base.A,\n\t\tcube.B^base.B,\n\t\tcube.C^base.C,\n\t\tcube.X^base.X,\n\t\tcube.Y^base.Y,\n\t\tcube.Z^base.Z,\n\t)\n}\n\nfunc (s *State) Encode() []byte {\n\tvar buf bytes.Buffer\n\n\tpack, _ := flate.NewWriter(&buf, flate.DefaultCompression)\n\tw := bit.NewWriter(pack)\n\n\tbaseline := s.Baseline()\n\tcurrent := s.Current()\n\n\tfor i, cube := range current.Cubes {\n\t\tbase := baseline.Cubes[i]\n\n\t\t\/\/bits := deltabits(&base, &cube)\n\t\tbits := uint64(32)\n\n\t\t\/\/w.WriteBits(bits, 6)\n\t\t\/\/if bits == 0 {\n\t\t\/\/\tcontinue\n\t\t\/\/}\n\n\t\t\/\/if bits == 0 {\n\t\t\/\/\tw.WriteBit(0)\n\t\t\/\/\tcontinue\n\t\t\/\/}\n\t\t\/\/w.WriteBit(1)\n\t\t\/\/w.WriteBits(bits, 6)\n\t\t\/\/expgolomb.WriteInt(w, int(bits)-9)\n\n\t\twrite(w, cube.Interacting^base.Interacting, 1)\n\t\twrite(w, cube.Largest^base.Largest, 2)\n\n\t\twrite32(w, cube.A^base.A, bits)\n\t\twrite32(w, cube.B^base.B, bits)\n\t\twrite32(w, cube.C^base.C, bits)\n\t\twrite32(w, cube.X^base.X, bits)\n\t\twrite32(w, cube.Y^base.Y, bits)\n\t\twrite32(w, cube.Z^base.Z, bits)\n\t}\n\n\tw.Close()\n\tpack.Close()\n\treturn buf.Bytes()\n}\n\nfunc (s *State) Decode(snapshot []byte) {\n\tbuf := bytes.NewBuffer(snapshot)\n\tpack := flate.NewReader(buf)\n\tr := bit.NewReader(pack)\n\n\tbaseline := s.Baseline()\n\tcurrent := s.Current()\n\n\tfor i := range current.Cubes {\n\t\tbase := baseline.Cubes[i]\n\t\tcube := &current.Cubes[i]\n\n\t\tbits := uint64(32)\n\t\t\/\/bits, _ := r.ReadBits(6)\n\t\t\/\/if bits == 0 {\n\t\t\/\/\tcontinue\n\t\t\/\/}\n\n\t\t\/\/xbits, _ := expgolomb.ReadInt(r)\n\t\t\/\/if xbits == 0 {\n\t\t\/\/\tcontinue\n\t\t\/\/}\n\t\t\/\/bits := uint64(xbits + 9)\n\n\t\tcube.Interacting = read(r, 1) ^ base.Interacting\n\t\tcube.Largest = read(r, 2) ^ base.Largest\n\n\t\tcube.A = read32(r, bits) ^ base.A\n\t\tcube.B = read32(r, bits) ^ base.B\n\t\tcube.C = read32(r, bits) ^ base.C\n\n\t\tcube.X = read32(r, bits) ^ base.X\n\t\tcube.Y = read32(r, bits) ^ base.Y\n\t\tcube.Z = read32(r, bits) ^ base.Z\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage clientbuilder\n\nimport (\n\t\"k8s.io\/client-go\/discovery\"\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\trestclient \"k8s.io\/client-go\/rest\"\n\t\"k8s.io\/klog\/v2\"\n)\n\n\/\/ ControllerClientBuilder allows you to get clients and configs for controllers\n\/\/ Please note a copy also exists in staging\/src\/k8s.io\/cloud-provider\/cloud.go\n\/\/ TODO: Extract this into a separate controller utilities repo (issues\/68947)\ntype ControllerClientBuilder interface {\n\tConfig(name string) (*restclient.Config, error)\n\tConfigOrDie(name string) *restclient.Config\n\tClient(name string) (clientset.Interface, error)\n\tClientOrDie(name string) clientset.Interface\n\tDiscoveryClient(name string) (discovery.DiscoveryInterface, error)\n\tDiscoveryClientOrDie(name string) discovery.DiscoveryInterface\n}\n\n\/\/ SimpleControllerClientBuilder returns a fixed client with different user agents\ntype SimpleControllerClientBuilder struct {\n\t\/\/ ClientConfig is a skeleton config to clone and use as the basis for each controller client\n\tClientConfig *restclient.Config\n}\n\n\/\/ Config returns a client config for a fixed client\nfunc (b SimpleControllerClientBuilder) Config(name string) (*restclient.Config, error) {\n\tclientConfig := *b.ClientConfig\n\treturn restclient.AddUserAgent(&clientConfig, name), nil\n}\n\n\/\/ ConfigOrDie returns a client config if no error from previous config func.\n\/\/ If it gets an error getting the client, it will log the error and kill the process it's running in.\nfunc (b SimpleControllerClientBuilder) ConfigOrDie(name string) *restclient.Config {\n\tclientConfig, err := b.Config(name)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn clientConfig\n}\n\n\/\/ Client returns a clientset.Interface built from the ClientBuilder\nfunc (b SimpleControllerClientBuilder) Client(name string) (clientset.Interface, error) {\n\tclientConfig, err := b.Config(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientset.NewForConfig(clientConfig)\n}\n\n\/\/ ClientOrDie returns a clientset.interface built from the ClientBuilder with no error.\n\/\/ If it gets an error getting the client, it will log the error and kill the process it's running in.\nfunc (b SimpleControllerClientBuilder) ClientOrDie(name string) clientset.Interface {\n\tclient, err := b.Client(name)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn client\n}\n\n\/\/ DiscoveryClientOrDie returns a discovery.DiscoveryInterface built from the ClientBuilder\n\/\/ Discovery is special because it will artificially pump the burst quite high to handle the many discovery requests.\nfunc (b SimpleControllerClientBuilder) DiscoveryClient(name string) (discovery.DiscoveryInterface, error) {\n\tclientConfig, err := b.Config(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Discovery makes a lot of requests infrequently.  This allows the burst to succeed and refill to happen\n\t\/\/ in just a few seconds.\n\tclientConfig.Burst = 200\n\tclientConfig.QPS = 20\n\treturn clientset.NewForConfig(clientConfig)\n}\n\n\/\/ DiscoveryClientOrDie returns a discovery.DiscoveryInterface built from the ClientBuilder with no error.\n\/\/ Discovery is special because it will artificially pump the burst quite high to handle the many discovery requests.\n\/\/ If it gets an error getting the client, it will log the error and kill the process it's running in.\nfunc (b SimpleControllerClientBuilder) DiscoveryClientOrDie(name string) discovery.DiscoveryInterface {\n\tclient, err := b.DiscoveryClient(name)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn client\n}\n<commit_msg>Fix a typo in comment<commit_after>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage clientbuilder\n\nimport (\n\t\"k8s.io\/client-go\/discovery\"\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\trestclient \"k8s.io\/client-go\/rest\"\n\t\"k8s.io\/klog\/v2\"\n)\n\n\/\/ ControllerClientBuilder allows you to get clients and configs for controllers\n\/\/ Please note a copy also exists in staging\/src\/k8s.io\/cloud-provider\/cloud.go\n\/\/ TODO: Extract this into a separate controller utilities repo (issues\/68947)\ntype ControllerClientBuilder interface {\n\tConfig(name string) (*restclient.Config, error)\n\tConfigOrDie(name string) *restclient.Config\n\tClient(name string) (clientset.Interface, error)\n\tClientOrDie(name string) clientset.Interface\n\tDiscoveryClient(name string) (discovery.DiscoveryInterface, error)\n\tDiscoveryClientOrDie(name string) discovery.DiscoveryInterface\n}\n\n\/\/ SimpleControllerClientBuilder returns a fixed client with different user agents\ntype SimpleControllerClientBuilder struct {\n\t\/\/ ClientConfig is a skeleton config to clone and use as the basis for each controller client\n\tClientConfig *restclient.Config\n}\n\n\/\/ Config returns a client config for a fixed client\nfunc (b SimpleControllerClientBuilder) Config(name string) (*restclient.Config, error) {\n\tclientConfig := *b.ClientConfig\n\treturn restclient.AddUserAgent(&clientConfig, name), nil\n}\n\n\/\/ ConfigOrDie returns a client config if no error from previous config func.\n\/\/ If it gets an error getting the client, it will log the error and kill the process it's running in.\nfunc (b SimpleControllerClientBuilder) ConfigOrDie(name string) *restclient.Config {\n\tclientConfig, err := b.Config(name)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn clientConfig\n}\n\n\/\/ Client returns a clientset.Interface built from the ClientBuilder\nfunc (b SimpleControllerClientBuilder) Client(name string) (clientset.Interface, error) {\n\tclientConfig, err := b.Config(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn clientset.NewForConfig(clientConfig)\n}\n\n\/\/ ClientOrDie returns a clientset.interface built from the ClientBuilder with no error.\n\/\/ If it gets an error getting the client, it will log the error and kill the process it's running in.\nfunc (b SimpleControllerClientBuilder) ClientOrDie(name string) clientset.Interface {\n\tclient, err := b.Client(name)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn client\n}\n\n\/\/ DiscoveryClient returns a discovery.DiscoveryInterface built from the ClientBuilder\n\/\/ Discovery is special because it will artificially pump the burst quite high to handle the many discovery requests.\nfunc (b SimpleControllerClientBuilder) DiscoveryClient(name string) (discovery.DiscoveryInterface, error) {\n\tclientConfig, err := b.Config(name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Discovery makes a lot of requests infrequently.  This allows the burst to succeed and refill to happen\n\t\/\/ in just a few seconds.\n\tclientConfig.Burst = 200\n\tclientConfig.QPS = 20\n\treturn clientset.NewForConfig(clientConfig)\n}\n\n\/\/ DiscoveryClientOrDie returns a discovery.DiscoveryInterface built from the ClientBuilder with no error.\n\/\/ Discovery is special because it will artificially pump the burst quite high to handle the many discovery requests.\n\/\/ If it gets an error getting the client, it will log the error and kill the process it's running in.\nfunc (b SimpleControllerClientBuilder) DiscoveryClientOrDie(name string) discovery.DiscoveryInterface {\n\tclient, err := b.DiscoveryClient(name)\n\tif err != nil {\n\t\tklog.Fatal(err)\n\t}\n\treturn client\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The Kubernetes Authors.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ This file contains functionality and constants for the L7-ILB feature\n\/\/ Since this also currently affects backend resources (since they are alpha-regional\n\/\/ instead of ga-global), this feature is also included in pkg\/backends\/features.go\npackage features\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/GoogleCloudPlatform\/k8s-cloud-provider\/pkg\/cloud\/filter\"\n\t\"github.com\/GoogleCloudPlatform\/k8s-cloud-provider\/pkg\/cloud\/meta\"\n\t\"k8s.io\/klog\"\n\t\"k8s.io\/legacy-cloud-providers\/gce\"\n)\n\nvar ErrSubnetNotFound = errors.New(\"active subnet not found\")\n\n\/\/ Get Subnet source range for ILB\n\/\/ TODO: (shance) refactor to use filter\nfunc ILBSubnetSourceRange(cloud *gce.Cloud, region string) (string, error) {\n\tsubnets, err := cloud.Compute().AlphaSubnetworks().List(context.Background(), region, filter.None)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error obtaining subnets for region %s, %v\", region, err)\n\t}\n\n\tfor _, subnet := range subnets {\n\t\tif subnet.Role == \"ACTIVE\" && subnet.Purpose == \"INTERNAL_HTTPS_LOAD_BALANCER\" {\n\t\t\tklog.V(3).Infof(\"Found L7-ILB Subnet %s - %s\", subnet.Name, subnet.IpCidrRange)\n\t\t\treturn subnet.IpCidrRange, nil\n\t\t}\n\t}\n\treturn \"\", ErrSubnetNotFound\n}\n\n\/\/ L7ILBVersion is a helper to get the version of L7-ILB\nfunc L7ILBVersions() *ResourceVersions {\n\treturn versionsFromFeatures([]string{FeatureL7ILB})\n}\n\n\/\/ L7ILBScope is a helper to get the scope of L7-ILB\nfunc L7ILBScope() meta.KeyType {\n\treturn scopeFromFeatures([]string{FeatureL7ILB})\n}\n<commit_msg>Update list subnets call to Beta for L7-ILB<commit_after>\/*\nCopyright 2019 The Kubernetes Authors.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ This file contains functionality and constants for the L7-ILB feature\n\/\/ Since this also currently affects backend resources (since they are alpha-regional\n\/\/ instead of ga-global), this feature is also included in pkg\/backends\/features.go\npackage features\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/GoogleCloudPlatform\/k8s-cloud-provider\/pkg\/cloud\/filter\"\n\t\"github.com\/GoogleCloudPlatform\/k8s-cloud-provider\/pkg\/cloud\/meta\"\n\t\"k8s.io\/klog\"\n\t\"k8s.io\/legacy-cloud-providers\/gce\"\n)\n\nvar ErrSubnetNotFound = errors.New(\"active subnet not found\")\n\n\/\/ Get Subnet source range for ILB\n\/\/ TODO: (shance) refactor to use filter\nfunc ILBSubnetSourceRange(cloud *gce.Cloud, region string) (string, error) {\n\tsubnets, err := cloud.Compute().BetaSubnetworks().List(context.Background(), region, filter.None)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error obtaining subnets for region %s, %v\", region, err)\n\t}\n\n\tfor _, subnet := range subnets {\n\t\tif subnet.Role == \"ACTIVE\" && subnet.Purpose == \"INTERNAL_HTTPS_LOAD_BALANCER\" {\n\t\t\tklog.V(3).Infof(\"Found L7-ILB Subnet %s - %s\", subnet.Name, subnet.IpCidrRange)\n\t\t\treturn subnet.IpCidrRange, nil\n\t\t}\n\t}\n\treturn \"\", ErrSubnetNotFound\n}\n\n\/\/ L7ILBVersion is a helper to get the version of L7-ILB\nfunc L7ILBVersions() *ResourceVersions {\n\treturn versionsFromFeatures([]string{FeatureL7ILB})\n}\n\n\/\/ L7ILBScope is a helper to get the scope of L7-ILB\nfunc L7ILBScope() meta.KeyType {\n\treturn scopeFromFeatures([]string{FeatureL7ILB})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build csharp\n\npackage modules\n\n\/\/ To enable the message height limit module, you need .NET Core on your server\n\n\/\/ #cgo LDFLAGS: -L..\/..\/3rdParty\/MessageHeightTwitch\/c-interop -lcoreruncommon -ldl -lstdc++\n\/\/ #include \"..\/..\/3rdParty\/MessageHeightTwitch\/c-interop\/exports.h\"\n\/\/ #include <stdlib.h>\nimport \"C\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"unsafe\"\n\n\t\"github.com\/pajlada\/pajbot2\/pkg\"\n\t\"github.com\/pajlada\/pajbot2\/pkg\/utils\"\n)\n\nvar _ pkg.Module = &MessageHeightLimit{}\n\nfunc floatPtr(v float32) *float32 {\n\treturn &v\n}\n\nvar messageHeightLimitSpec *moduleSpec\n\nfunc init() {\n\tmessageHeightLimitSpec = &moduleSpec{\n\t\tid:    \"message_height_limit\",\n\t\tname:  \"Message height limit\",\n\t\tmaker: NewMessageHeightLimit,\n\n\t\tenabledByDefault: false,\n\n\t\tparameters: map[string]*moduleParameterSpec{\n\t\t\t\"HeightLimit\": &moduleParameterSpec{\n\t\t\t\tdescription:  \"Max height of a message before it's timed out\",\n\t\t\t\tdefaultValue: floatPtr(95),\n\t\t\t},\n\t\t},\n\t}\n\n\tRegister(messageHeightLimitSpec)\n}\n\ntype MessageHeightLimit struct {\n\tbotChannel pkg.BotChannel\n\n\tserver *server\n\n\tHeightLimit floatParameter `json:\",omitempty\"`\n\n\tuserViolationCount map[string]int\n}\n\nfunc NewMessageHeightLimit() pkg.Module {\n\treturn &MessageHeightLimit{\n\t\tserver: &_server,\n\n\t\tHeightLimit: floatParameter{\n\t\t\tdefaultValue: messageHeightLimitSpec.parameters[\"HeightLimit\"].defaultValue.(*float32),\n\t\t},\n\t\tuserViolationCount: make(map[string]int),\n\t}\n}\n\nvar clrInitialized = false\n\nvar messageHeightLimitLibraryInitialized = false\nvar charMapPath string\n\nfunc initCLR() error {\n\texecutableDir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Executable dir\", executableDir)\n\tfmt.Println(\"os args 0:\", os.Args[0])\n\n\tclrPath := utils.GetEnv(\"LIBCOREFOLDER\", \"\/usr\/share\/dotnet\/shared\/Microsoft.NETCore.App\/2.1.5\")\n\n\t\/\/ Path to our own executable\n\tclr1 := C.CString(executableDir + \"\/bot\")\n\n\tfmt.Println(executableDir)\n\n\t\/\/ Folder where libcoreclr.so is located\n\tclr2 := C.CString(clrPath)\n\n\t\/\/ Path to library we want to use\n\tclr3 := C.CString(executableDir + \"\/MessageHeightTwitch.dll\")\n\n\tvar res C.int\n\n\tres = C.LoadCLRRuntime(\n\t\tclr1,\n\t\tclr2,\n\t\tclr3)\n\n\tC.free(unsafe.Pointer(clr1))\n\tC.free(unsafe.Pointer(clr2))\n\tC.free(unsafe.Pointer(clr3))\n\n\tif res != 0 {\n\t\treturn errors.New(\"Failed to load CLR Runtime\")\n\t}\n\n\tcharMapPath = executableDir + \"\/charmap.bin.gz\"\n\n\tclrInitialized = true\n\n\treturn nil\n}\n\nfunc initChannel(channelName string) error {\n\tchannel := C.CString(channelName)\n\n\tres := C.InitChannel(channel)\n\n\tif res != 1 {\n\t\treturn errors.New(\"Failed to init Channel \" + channelName)\n\t}\n\n\tC.free(unsafe.Pointer(channel))\n\n\treturn nil\n}\n\nfunc initMessageHeightLimitLibrary() error {\n\tcharMap := C.CString(charMapPath)\n\n\tfmt.Println(charMapPath)\n\n\tres := C.InitCharMap(charMap)\n\n\tC.free(unsafe.Pointer(charMap))\n\n\tif res != 1 {\n\t\treturn errors.New(fmt.Sprintf(\"Failed to init CharMap: %d\", int(res)))\n\t}\n\n\tmessageHeightLimitLibraryInitialized = true\n\n\treturn nil\n}\n\nfunc (m *MessageHeightLimit) Initialize(botChannel pkg.BotChannel, settings []byte) (err error) {\n\tm.botChannel = botChannel\n\n\tif !clrInitialized {\n\t\terr = initCLR()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\terr = initMessageHeightLimitLibrary()\n\t}\n\n\tif err := initChannel(botChannel.ChannelName()); err != nil {\n\t\treturn err\n\t}\n\n\tif err := loadModule(settings, m); err != nil {\n\t\tfmt.Println(\"Error loading module:\", err)\n\t}\n\n\treturn\n}\n\nfunc (m *MessageHeightLimit) Disable() error {\n\treturn nil\n}\n\nfunc (m *MessageHeightLimit) Spec() pkg.ModuleSpec {\n\treturn messageHeightLimitSpec\n}\n\nfunc (m *MessageHeightLimit) BotChannel() pkg.BotChannel {\n\treturn m.botChannel\n}\n\nfunc (m *MessageHeightLimit) OnWhisper(bot pkg.Sender, user pkg.User, message pkg.Message) error {\n\treturn nil\n}\n\nfunc (m *MessageHeightLimit) getHeight(channel pkg.Channel, user pkg.User, message pkg.Message) float32 {\n\tchannelString := C.CString(channel.GetChannel())\n\tinput := C.CString(message.GetText())\n\tloginName := C.CString(user.GetName())\n\tdisplayName := C.CString(user.GetDisplayName())\n\n\tvar emoteStrings []*C.char\n\n\tvar te []C.TwitchEmote\n\n\treader := message.GetTwitchReader()\n\tfor reader.Next() {\n\t\temote := reader.Get()\n\t\temoteCode := C.CString(emote.GetName())\n\t\temoteURL := C.CString(fmt.Sprintf(\"https:\/\/static-cdn.jtvnw.net\/emoticons\/v1\/%s\/1.0\", emote.GetID()))\n\n\t\tte = append(te, C.TwitchEmote{emoteCode, emoteURL})\n\n\t\temoteStrings = append(emoteStrings, emoteCode)\n\t\temoteStrings = append(emoteStrings, emoteURL)\n\t}\n\n\tvar pArray unsafe.Pointer\n\n\tif len(te) > 0 {\n\t\tpArray = unsafe.Pointer(&te[0])\n\t}\n\n\tbadgeCount := C.int(len(user.GetBadges()))\n\n\theight := C.CalculateMessageHeightDirect(\n\t\tchannelString,\n\t\tinput,                      \/\/ Message text\n\t\tloginName,                  \/\/ Login name\n\t\tdisplayName,                \/\/ Display name\n\t\tbadgeCount,                 \/\/ Badge count\n\t\t((*C.TwitchEmote)(pArray)), \/\/ Array of emotes\n\t\tC.int(len(te)),             \/\/ Emote array size\n\t)\n\n\tC.free(unsafe.Pointer(channelString))\n\tC.free(unsafe.Pointer(input))\n\tC.free(unsafe.Pointer(loginName))\n\tC.free(unsafe.Pointer(displayName))\n\n\tfor _, str := range emoteStrings {\n\t\tC.free(unsafe.Pointer(str))\n\t}\n\n\treturn float32(height)\n}\n\nfunc (m *MessageHeightLimit) OnMessage(bot pkg.Sender, channel pkg.Channel, user pkg.User, message pkg.Message, action pkg.Action) error {\n\tif !messageHeightLimitLibraryInitialized {\n\t\treturn nil\n\t}\n\n\tif user.GetName() == \"gazatu2\" {\n\t\treturn nil\n\t}\n\n\tif user.GetName() == \"supibot\" {\n\t\treturn nil\n\t}\n\n\tif user.GetName() == \"titlechange_bot\" {\n\t\treturn nil\n\t}\n\n\tif user.IsModerator() || user.IsBroadcaster(channel) {\n\t\tif strings.HasPrefix(message.GetText(), \"!\") {\n\t\t\tparts := strings.Split(message.GetText(), \" \")\n\t\t\tif parts[0] == \"!heightlimit\" {\n\t\t\t\tif len(parts) >= 2 {\n\t\t\t\t\tif err := m.HeightLimit.Parse(parts[1]); err != nil {\n\t\t\t\t\t\tbot.Mention(channel, user, err.Error())\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\n\t\t\t\t\tbot.Mention(channel, user, \"Height limit set to \"+utils.Float32ToString(m.HeightLimit.Get()))\n\t\t\t\t\tsaveModule(m)\n\t\t\t\t} else {\n\t\t\t\t\tbot.Mention(channel, user, \"Height limit is \"+utils.Float32ToString(m.HeightLimit.Get()))\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif parts[0] == \"!heighttest\" {\n\t\t\t\theight := m.getHeight(channel, user, message)\n\t\t\t\tbot.Mention(channel, user, fmt.Sprintf(\"your message height is %.2f\", height))\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\tconst maxTimeoutLength = 1800\n\n\theight := m.getHeight(channel, user, message)\n\t\/\/ bot.Mention(channel, user, fmt.Sprintf(\"Message height: %f\\n\", height))\n\n\tif height > m.HeightLimit.Get() {\n\t\t\/\/ Message height is too tall\n\t\tmessageLength := len([]rune(message.GetText()))\n\t\tvar fitsIn7Bit int\n\t\tvar doesntFitIn7Bit int\n\t\tfor _, r := range message.GetText() {\n\t\t\tif r > 0x7a || r < 0x20 {\n\t\t\t\tdoesntFitIn7Bit++\n\t\t\t} else {\n\t\t\t\tfitsIn7Bit++\n\t\t\t}\n\t\t}\n\n\t\tfmt.Printf(\"Message length: %d. Fits: %d. Don't fit: %d\\n\", messageLength, doesntFitIn7Bit, fitsIn7Bit)\n\t\tvar ratio float32\n\t\tratio = float32(doesntFitIn7Bit) \/ float32(messageLength)\n\t\tvar reason string\n\t\tuserViolations := 0\n\t\ttimeoutDuration := int(math.Min(math.Pow(float64(height-m.HeightLimit.Get()), 1.2), maxTimeoutLength))\n\t\tif ratio > 0.5 {\n\t\t\ttimeoutDuration = timeoutDuration + 90\n\t\t}\n\n\t\tif ratio > 0.5 && height > 140.0 {\n\t\t\tm.userViolationCount[user.GetID()] = m.userViolationCount[user.GetID()] + 1\n\t\t\tuserViolations = m.userViolationCount[user.GetID()]\n\t\t\ttimeoutDuration = timeoutDuration * userViolations\n\t\t\ttimeoutDuration = utils.MinInt(3600*24*7, timeoutDuration)\n\t\t\treason = fmt.Sprintf(\"Your message is too tall: %.1f - %.3f A\", height, ratio)\n\t\t\tbot.Whisper(user, fmt.Sprintf(\"Your message is too long and contains too many non-ascii characters. Your next timeout will be multiplied by %d\", userViolations))\n\t\t} else {\n\t\t\treason = fmt.Sprintf(\"Your message is too tall: %.1f - %.3f\", height, ratio)\n\t\t}\n\n\t\treason = fmt.Sprintf(\"Your message is too tall: %.0f (%d)\", height, userViolations)\n\t\taction.Set(pkg.Timeout{\n\t\t\tDuration: timeoutDuration,\n\t\t\tReason:   reason,\n\t\t})\n\t}\n\n\treturn nil\n}\n<commit_msg>add a minimum timeout duration<commit_after>\/\/ +build csharp\n\npackage modules\n\n\/\/ To enable the message height limit module, you need .NET Core on your server\n\n\/\/ #cgo LDFLAGS: -L..\/..\/3rdParty\/MessageHeightTwitch\/c-interop -lcoreruncommon -ldl -lstdc++\n\/\/ #include \"..\/..\/3rdParty\/MessageHeightTwitch\/c-interop\/exports.h\"\n\/\/ #include <stdlib.h>\nimport \"C\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"unsafe\"\n\n\t\"github.com\/pajlada\/pajbot2\/pkg\"\n\t\"github.com\/pajlada\/pajbot2\/pkg\/utils\"\n)\n\nvar _ pkg.Module = &MessageHeightLimit{}\n\nfunc floatPtr(v float32) *float32 {\n\treturn &v\n}\n\nvar messageHeightLimitSpec *moduleSpec\n\nfunc init() {\n\tmessageHeightLimitSpec = &moduleSpec{\n\t\tid:    \"message_height_limit\",\n\t\tname:  \"Message height limit\",\n\t\tmaker: NewMessageHeightLimit,\n\n\t\tenabledByDefault: false,\n\n\t\tparameters: map[string]*moduleParameterSpec{\n\t\t\t\"HeightLimit\": &moduleParameterSpec{\n\t\t\t\tdescription:  \"Max height of a message before it's timed out\",\n\t\t\t\tdefaultValue: floatPtr(95),\n\t\t\t},\n\t\t},\n\t}\n\n\tRegister(messageHeightLimitSpec)\n}\n\ntype MessageHeightLimit struct {\n\tbotChannel pkg.BotChannel\n\n\tserver *server\n\n\tHeightLimit floatParameter `json:\",omitempty\"`\n\n\tuserViolationCount map[string]int\n}\n\nfunc NewMessageHeightLimit() pkg.Module {\n\treturn &MessageHeightLimit{\n\t\tserver: &_server,\n\n\t\tHeightLimit: floatParameter{\n\t\t\tdefaultValue: messageHeightLimitSpec.parameters[\"HeightLimit\"].defaultValue.(*float32),\n\t\t},\n\t\tuserViolationCount: make(map[string]int),\n\t}\n}\n\nvar clrInitialized = false\n\nvar messageHeightLimitLibraryInitialized = false\nvar charMapPath string\n\nfunc initCLR() error {\n\texecutableDir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"Executable dir\", executableDir)\n\tfmt.Println(\"os args 0:\", os.Args[0])\n\n\tclrPath := utils.GetEnv(\"LIBCOREFOLDER\", \"\/usr\/share\/dotnet\/shared\/Microsoft.NETCore.App\/2.1.5\")\n\n\t\/\/ Path to our own executable\n\tclr1 := C.CString(executableDir + \"\/bot\")\n\n\tfmt.Println(executableDir)\n\n\t\/\/ Folder where libcoreclr.so is located\n\tclr2 := C.CString(clrPath)\n\n\t\/\/ Path to library we want to use\n\tclr3 := C.CString(executableDir + \"\/MessageHeightTwitch.dll\")\n\n\tvar res C.int\n\n\tres = C.LoadCLRRuntime(\n\t\tclr1,\n\t\tclr2,\n\t\tclr3)\n\n\tC.free(unsafe.Pointer(clr1))\n\tC.free(unsafe.Pointer(clr2))\n\tC.free(unsafe.Pointer(clr3))\n\n\tif res != 0 {\n\t\treturn errors.New(\"Failed to load CLR Runtime\")\n\t}\n\n\tcharMapPath = executableDir + \"\/charmap.bin.gz\"\n\n\tclrInitialized = true\n\n\treturn nil\n}\n\nfunc initChannel(channelName string) error {\n\tchannel := C.CString(channelName)\n\n\tres := C.InitChannel(channel)\n\n\tif res != 1 {\n\t\treturn errors.New(\"Failed to init Channel \" + channelName)\n\t}\n\n\tC.free(unsafe.Pointer(channel))\n\n\treturn nil\n}\n\nfunc initMessageHeightLimitLibrary() error {\n\tcharMap := C.CString(charMapPath)\n\n\tfmt.Println(charMapPath)\n\n\tres := C.InitCharMap(charMap)\n\n\tC.free(unsafe.Pointer(charMap))\n\n\tif res != 1 {\n\t\treturn errors.New(fmt.Sprintf(\"Failed to init CharMap: %d\", int(res)))\n\t}\n\n\tmessageHeightLimitLibraryInitialized = true\n\n\treturn nil\n}\n\nfunc (m *MessageHeightLimit) Initialize(botChannel pkg.BotChannel, settings []byte) (err error) {\n\tm.botChannel = botChannel\n\n\tif !clrInitialized {\n\t\terr = initCLR()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\terr = initMessageHeightLimitLibrary()\n\t}\n\n\tif err := initChannel(botChannel.ChannelName()); err != nil {\n\t\treturn err\n\t}\n\n\tif err := loadModule(settings, m); err != nil {\n\t\tfmt.Println(\"Error loading module:\", err)\n\t}\n\n\treturn\n}\n\nfunc (m *MessageHeightLimit) Disable() error {\n\treturn nil\n}\n\nfunc (m *MessageHeightLimit) Spec() pkg.ModuleSpec {\n\treturn messageHeightLimitSpec\n}\n\nfunc (m *MessageHeightLimit) BotChannel() pkg.BotChannel {\n\treturn m.botChannel\n}\n\nfunc (m *MessageHeightLimit) OnWhisper(bot pkg.Sender, user pkg.User, message pkg.Message) error {\n\treturn nil\n}\n\nfunc (m *MessageHeightLimit) getHeight(channel pkg.Channel, user pkg.User, message pkg.Message) float32 {\n\tchannelString := C.CString(channel.GetChannel())\n\tinput := C.CString(message.GetText())\n\tloginName := C.CString(user.GetName())\n\tdisplayName := C.CString(user.GetDisplayName())\n\n\tvar emoteStrings []*C.char\n\n\tvar te []C.TwitchEmote\n\n\treader := message.GetTwitchReader()\n\tfor reader.Next() {\n\t\temote := reader.Get()\n\t\temoteCode := C.CString(emote.GetName())\n\t\temoteURL := C.CString(fmt.Sprintf(\"https:\/\/static-cdn.jtvnw.net\/emoticons\/v1\/%s\/1.0\", emote.GetID()))\n\n\t\tte = append(te, C.TwitchEmote{emoteCode, emoteURL})\n\n\t\temoteStrings = append(emoteStrings, emoteCode)\n\t\temoteStrings = append(emoteStrings, emoteURL)\n\t}\n\n\tvar pArray unsafe.Pointer\n\n\tif len(te) > 0 {\n\t\tpArray = unsafe.Pointer(&te[0])\n\t}\n\n\tbadgeCount := C.int(len(user.GetBadges()))\n\n\theight := C.CalculateMessageHeightDirect(\n\t\tchannelString,\n\t\tinput,                      \/\/ Message text\n\t\tloginName,                  \/\/ Login name\n\t\tdisplayName,                \/\/ Display name\n\t\tbadgeCount,                 \/\/ Badge count\n\t\t((*C.TwitchEmote)(pArray)), \/\/ Array of emotes\n\t\tC.int(len(te)),             \/\/ Emote array size\n\t)\n\n\tC.free(unsafe.Pointer(channelString))\n\tC.free(unsafe.Pointer(input))\n\tC.free(unsafe.Pointer(loginName))\n\tC.free(unsafe.Pointer(displayName))\n\n\tfor _, str := range emoteStrings {\n\t\tC.free(unsafe.Pointer(str))\n\t}\n\n\treturn float32(height)\n}\n\nfunc (m *MessageHeightLimit) OnMessage(bot pkg.Sender, channel pkg.Channel, user pkg.User, message pkg.Message, action pkg.Action) error {\n\tif !messageHeightLimitLibraryInitialized {\n\t\treturn nil\n\t}\n\n\tif user.GetName() == \"gazatu2\" {\n\t\treturn nil\n\t}\n\n\tif user.GetName() == \"supibot\" {\n\t\treturn nil\n\t}\n\n\tif user.GetName() == \"titlechange_bot\" {\n\t\treturn nil\n\t}\n\n\tif user.IsModerator() || user.IsBroadcaster(channel) || user.HasPermission(channel, pkg.PermissionModeration) {\n\t\tif strings.HasPrefix(message.GetText(), \"!\") {\n\t\t\tparts := strings.Split(message.GetText(), \" \")\n\t\t\tif parts[0] == \"!heightlimit\" {\n\t\t\t\tif len(parts) >= 2 {\n\t\t\t\t\tif err := m.HeightLimit.Parse(parts[1]); err != nil {\n\t\t\t\t\t\tbot.Mention(channel, user, err.Error())\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\n\t\t\t\t\tbot.Mention(channel, user, \"Height limit set to \"+utils.Float32ToString(m.HeightLimit.Get()))\n\t\t\t\t\tsaveModule(m)\n\t\t\t\t} else {\n\t\t\t\t\tbot.Mention(channel, user, \"Height limit is \"+utils.Float32ToString(m.HeightLimit.Get()))\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif parts[0] == \"!heighttest\" {\n\t\t\t\theight := m.getHeight(channel, user, message)\n\t\t\t\tbot.Mention(channel, user, fmt.Sprintf(\"your message height is %.2f\", height))\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\tconst minTimeoutLength = 10\n\tconst maxTimeoutLength = 1800\n\n\theight := m.getHeight(channel, user, message)\n\t\/\/ bot.Mention(channel, user, fmt.Sprintf(\"Message height: %f\\n\", height))\n\n\tif height > m.HeightLimit.Get() {\n\t\t\/\/ Message height is too tall\n\t\tmessageLength := len([]rune(message.GetText()))\n\t\tvar fitsIn7Bit int\n\t\tvar doesntFitIn7Bit int\n\t\tfor _, r := range message.GetText() {\n\t\t\tif r > 0x7a || r < 0x20 {\n\t\t\t\tdoesntFitIn7Bit++\n\t\t\t} else {\n\t\t\t\tfitsIn7Bit++\n\t\t\t}\n\t\t}\n\n\t\tfmt.Printf(\"Message length: %d. Fits: %d. Don't fit: %d\\n\", messageLength, doesntFitIn7Bit, fitsIn7Bit)\n\t\tvar ratio float32\n\t\tratio = float32(doesntFitIn7Bit) \/ float32(messageLength)\n\t\tvar reason string\n\t\tuserViolations := 0\n\t\ttimeoutDuration := int(math.Min(math.Pow(float64(height-m.HeightLimit.Get()), 1.2), maxTimeoutLength))\n\t\tif ratio > 0.5 {\n\t\t\ttimeoutDuration = timeoutDuration + 90\n\t\t}\n\n\t\ttimeoutDuration = utils.MaxInt(minTimeoutLength, timeoutDuration)\n\n\t\tif ratio > 0.5 && height > 140.0 {\n\t\t\tm.userViolationCount[user.GetID()] = m.userViolationCount[user.GetID()] + 1\n\t\t\tuserViolations = m.userViolationCount[user.GetID()]\n\t\t\ttimeoutDuration = timeoutDuration * userViolations\n\t\t\ttimeoutDuration = utils.MinInt(3600*24*7, timeoutDuration)\n\t\t\treason = fmt.Sprintf(\"Your message is too tall: %.1f - %.3f A\", height, ratio)\n\t\t\tbot.Whisper(user, fmt.Sprintf(\"Your message is too long and contains too many non-ascii characters. Your next timeout will be multiplied by %d\", userViolations))\n\t\t} else {\n\t\t\treason = fmt.Sprintf(\"Your message is too tall: %.1f - %.3f\", height, ratio)\n\t\t}\n\n\t\treason = fmt.Sprintf(\"Your message is too tall: %.0f (%d)\", height, userViolations)\n\t\taction.Set(pkg.Timeout{\n\t\t\tDuration: timeoutDuration,\n\t\t\tReason:   reason,\n\t\t})\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package termite\n\nimport (\n\t\"github.com\/hanwen\/go-fuse\/fuse\"\n\t\"log\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar _ = log.Printf\n\nfunc testStat(t *testing.T, n string) *os.FileInfo {\n\tt.Logf(\"stat %q\", n)\n\tf, _ := os.Lstat(n)\n\treturn f\n}\n\nfunc getattr(t *testing.T, n string) *FileAttr {\n\tt.Logf(\"getattr %q\", n)\n\tfi, _ := os.Lstat(n)\n\ta := FileAttr{\n\t\tFileInfo: fi,\n\t}\n\tif !a.Deletion() {\n\t\ta.ReadFromFs(n)\n\t}\n\treturn &a\n}\n\nfunc TestAttrCacheNil(t *testing.T) {\n\tac := NewAttributeCache(\n\t\tfunc(n string) *FileAttr {\n\t\treturn nil\n\t},\n\t\tfunc(n string) *os.FileInfo {\n\t\treturn nil\n\t})\n\n\tr := ac.Get(\"\")\n\tif r == nil || !r.Deletion() {\n\t\tt.Errorf(\"should return deletion for error, got: %v\", r)\n\t}\n}\n\nfunc TestAttrCache(t *testing.T) {\n\tdir, err := ioutil.TempDir(\"\", \"termite\")\n\tcheck(err)\n\tsyscall.Umask(0)\n\n\tac := NewAttributeCache(\n\t\tfunc(n string) *FileAttr {\n\t\t\treturn getattr(t, filepath.Join(dir, n))\n\t\t},\n\t\tfunc(n string) *os.FileInfo {\n\t\t\treturn testStat(t, filepath.Join(dir, n))\n\t\t})\n\terr = ioutil.WriteFile(dir+\"\/file\", []byte{42}, 0604)\n\tcheck(err)\n\n\tf := ac.Get(\"file\")\n\tif f.Deletion() {\n\t\tt.Fatalf(\"Got deletion %v\", f)\n\t}\n\tif f.Mode&0777 != 0604 {\n\t\tt.Fatalf(\"Got %o want %o\", f.Mode&0777, 0604)\n\t}\n\tif !ac.Have(\"\") {\n\t\tt.Fatalf(\"Must have parent too\")\n\t}\n\td := ac.GetDir(\"\")\n\tif d.NameModeMap == nil || d.NameModeMap[\"file\"] == 0 {\n\t\tt.Fatalf(\"root NameModeMap wrong %v\", d.NameModeMap)\n\t}\n\n\tupd := FileAttr{\n\t\tPath:     \"unknown\/file\",\n\t\tFileInfo: &os.FileInfo{Mode: fuse.S_IFLNK | 0666},\n\t\tLink:     \"target\",\n\t}\n\n\tac.Update([]*FileAttr{&upd})\n\tif ac.Have(\"unknown\/file\") || ac.Have(\"unknown\") {\n\t\tt.Fatalf(\"Should have ignored unknown directory\")\n\t}\n\n\t\/\/ Make sure timestamps change.\n\ttime.Sleep(15e6)\n\terr = ioutil.WriteFile(dir+\"\/other\", []byte{43}, 0666)\n\tcheck(err)\n\terr = os.Chmod(dir+\"\/file\", 0666)\n\tcheck(err)\n\n\tac.Refresh(\"\")\n\n\td = ac.GetDir(\"\")\n\tif d.NameModeMap[\"other\"] == 0 {\n\t\tt.Fatalf(\"Should have 'other' in root %v\", d)\n\t}\n\tf = ac.Get(\"file\")\n\tif f.Mode&0777 != 0666 {\n\t\tt.Fatalf(\"Got %o , want 0666\", f.Mode)\n\t}\n\n}\n<commit_msg>Use larger timeout on attrcache test.<commit_after>package termite\n\nimport (\n\t\"github.com\/hanwen\/go-fuse\/fuse\"\n\t\"log\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar _ = log.Printf\n\nfunc testStat(t *testing.T, n string) *os.FileInfo {\n\tt.Logf(\"stat %q\", n)\n\tf, _ := os.Lstat(n)\n\treturn f\n}\n\nfunc getattr(t *testing.T, n string) *FileAttr {\n\tt.Logf(\"getattr %q\", n)\n\tfi, _ := os.Lstat(n)\n\ta := FileAttr{\n\t\tFileInfo: fi,\n\t}\n\tif !a.Deletion() {\n\t\ta.ReadFromFs(n)\n\t}\n\treturn &a\n}\n\nfunc TestAttrCacheNil(t *testing.T) {\n\tac := NewAttributeCache(\n\t\tfunc(n string) *FileAttr {\n\t\treturn nil\n\t},\n\t\tfunc(n string) *os.FileInfo {\n\t\treturn nil\n\t})\n\n\tr := ac.Get(\"\")\n\tif r == nil || !r.Deletion() {\n\t\tt.Errorf(\"should return deletion for error, got: %v\", r)\n\t}\n}\n\nfunc TestAttrCache(t *testing.T) {\n\tdir, err := ioutil.TempDir(\"\", \"termite\")\n\tcheck(err)\n\tsyscall.Umask(0)\n\n\tac := NewAttributeCache(\n\t\tfunc(n string) *FileAttr {\n\t\t\treturn getattr(t, filepath.Join(dir, n))\n\t\t},\n\t\tfunc(n string) *os.FileInfo {\n\t\t\treturn testStat(t, filepath.Join(dir, n))\n\t\t})\n\terr = ioutil.WriteFile(dir+\"\/file\", []byte{42}, 0604)\n\tcheck(err)\n\n\tf := ac.Get(\"file\")\n\tif f.Deletion() {\n\t\tt.Fatalf(\"Got deletion %v\", f)\n\t}\n\tif f.Mode&0777 != 0604 {\n\t\tt.Fatalf(\"Got %o want %o\", f.Mode&0777, 0604)\n\t}\n\tif !ac.Have(\"\") {\n\t\tt.Fatalf(\"Must have parent too\")\n\t}\n\td := ac.GetDir(\"\")\n\tif d.NameModeMap == nil || d.NameModeMap[\"file\"] == 0 {\n\t\tt.Fatalf(\"root NameModeMap wrong %v\", d.NameModeMap)\n\t}\n\n\tupd := FileAttr{\n\t\tPath:     \"unknown\/file\",\n\t\tFileInfo: &os.FileInfo{Mode: fuse.S_IFLNK | 0666},\n\t\tLink:     \"target\",\n\t}\n\n\tac.Update([]*FileAttr{&upd})\n\tif ac.Have(\"unknown\/file\") || ac.Have(\"unknown\") {\n\t\tt.Fatalf(\"Should have ignored unknown directory\")\n\t}\n\n\t\/\/ Make sure timestamps change.\n\ttime.Sleep(150e6)\n\terr = ioutil.WriteFile(dir+\"\/other\", []byte{43}, 0666)\n\tcheck(err)\n\terr = os.Chmod(dir+\"\/file\", 0666)\n\tcheck(err)\n\n\tac.Refresh(\"\")\n\n\td = ac.GetDir(\"\")\n\tif d.NameModeMap[\"other\"] == 0 {\n\t\tt.Fatalf(\"Should have 'other' in root %v\", d)\n\t}\n\tf = ac.Get(\"file\")\n\tif f.Mode&0777 != 0666 {\n\t\tt.Fatalf(\"Got %o , want 0666\", f.Mode)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package atm\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\/\/create template directory and sub directories\nfunc createDirs(t *testing.T) {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif err := os.MkdirAll(dir+\"\/templates\/atoms\/fonts\", os.ModeDir|os.ModePerm); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := os.MkdirAll(dir+\"\/templates\/pages\/front-page\", os.ModeDir|os.ModePerm); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc createTestTemplates(t *testing.T) {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = writeTemplateFile(dir+\"\/templates\/top-level.html\", ``)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = writeTemplateFile(dir+\"\/templates\/none.none\", ``)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = writeTemplateFile(dir+\"\/templates\/atoms\/atom-1.html\", ``)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = writeTemplateFile(dir+\"\/templates\/atoms\/atom-2.tpl\", ``)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = writeTemplateFile(dir+\"\/templates\/atoms\/fonts\/font-1.html\", ``)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc writeTemplateFile(path, contents string) error {\n\ttemplateFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer templateFile.Close()\n\t_, err = templateFile.WriteString(contents)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc destroyAll(t *testing.T) {\n\tif err := os.RemoveAll(\".\/templates\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestMeetsInterface(t *testing.T) {\n\tvar _ Manager = New()\n}\n\nfunc TestErrorOnExecutingTemplate(t *testing.T) {\n\tvar m Manager = New()\n\n\terr := m.ExecuteTemplate(os.Stdin, \"testing\", nil)\n\n\tif err == nil {\n\t\tt.Fatal(\"Expected error but got none.\")\n\t}\n\n\terr = m.ExecuteTemplate(os.Stdin, \"root\", nil)\n\n\tif err == nil {\n\t\tt.Fatal(\"Expected error but got none.\")\n\t}\n}\n\nfunc TestNoTemplatesAreFound(t *testing.T) {\n\tcreateDirs(t)\n\tdefer destroyAll(t)\n\n\tvar man Manager = New()\n\tman.AddDirectories(\".\/templates\")\n\tman.ParseTemplates()\n\tif len(man.Templates()) > 0 {\n\t\tt.Fatal(\"There were templates even though the directories were empty.\")\n\t}\n}\n\nfunc TestDefaultTemplatesAreFound(t *testing.T) {\n\tcreateDirs(t)\n\tcreateTestTemplates(t)\n\tdefer destroyAll(t)\n\n\tvar man Manager = New()\n\n\tman.AddDirectories(\".\/templates\")\n\tman.ParseTemplates()\n\tif len(man.Templates()) != 4 {\n\t\tt.Fatalf(\"We expected 4 templates but had : %d\", len(man.Templates()))\n\t}\n}\n<commit_msg>Finished merge with origin\/master<commit_after>package atm\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n\/\/create template directory and sub directories\nfunc createDirs(t *testing.T) {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := os.MkdirAll(dir+\"\/templates\/atoms\/fonts\", os.ModeDir|os.ModePerm); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := os.MkdirAll(dir+\"\/templates\/pages\/front-page\", os.ModeDir|os.ModePerm); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc createTestTemplates(t *testing.T) {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = writeTemplateFile(dir+\"\/templates\/top-level.html\", ``)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = writeTemplateFile(dir+\"\/templates\/none.none\", ``)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = writeTemplateFile(dir+\"\/templates\/atoms\/atom-1.html\", ``)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = writeTemplateFile(dir+\"\/templates\/atoms\/atom-2.tpl\", ``)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = writeTemplateFile(dir+\"\/templates\/atoms\/fonts\/font-1.html\", ``)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc writeTemplateFile(path, contents string) error {\n\ttemplateFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer templateFile.Close()\n\t_, err = templateFile.WriteString(contents)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc destroyAll(t *testing.T) {\n\tif err := os.RemoveAll(\".\/templates\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestMeetsInterface(t *testing.T) {\n\tvar _ Manager = New()\n}\n\nfunc TestErrorOnExecutingTemplate(t *testing.T) {\n\tvar m Manager = New()\n\n\terr := m.ExecuteTemplate(os.Stdin, \"testing\", nil)\n\n\tif err == nil {\n\t\tt.Fatal(\"Expected error but got none.\")\n\t}\n\n\terr = m.ExecuteTemplate(os.Stdin, \"root\", nil)\n\n\tif err == nil {\n\t\tt.Fatal(\"Expected error but got none.\")\n\t}\n}\n\nfunc TestNoTemplatesAreFound(t *testing.T) {\n\tcreateDirs(t)\n\tdefer destroyAll(t)\n\n\tvar man Manager = New()\n\tman.AddDirectories(\".\/templates\")\n\tman.ParseTemplates()\n\tif len(man.Templates()) > 0 {\n\t\tt.Fatal(\"There were templates even though the directories were empty.\")\n\t}\n}\n\nfunc TestDefaultTemplatesAreFound(t *testing.T) {\n\tcreateDirs(t)\n\tcreateTestTemplates(t)\n\tdefer destroyAll(t)\n\n\tvar man Manager = New()\n\n\tman.AddDirectories(\".\/templates\")\n\tman.ParseTemplates()\n\tif len(man.Templates()) != 4 {\n\t\tt.Fatalf(\"We expected 4 templates but had : %d\", len(man.Templates()))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package v1\n\nimport (\n\t\"net\"\n\n\t\"github.com\/sapcc\/kubernikus\/pkg\/api\/models\"\n\t\"github.com\/sapcc\/kubernikus\/pkg\/util\/ip\"\n\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\n\/\/ +genclient\n\/\/ +k8s:deepcopy-gen:interfaces=k8s.io\/apimachinery\/pkg\/runtime.Object\n\ntype Kluster struct {\n\tmetav1.TypeMeta   `json:\",inline\"`\n\tmetav1.ObjectMeta `json:\"metadata\"`\n\tSpec              models.KlusterSpec   `json:\"spec\"`\n\tStatus            models.KlusterStatus `json:\"status,omitempty\"`\n}\n\n\/\/ +k8s:deepcopy-gen:interfaces=k8s.io\/apimachinery\/pkg\/runtime.Object\n\ntype KlusterList struct {\n\tmetav1.TypeMeta `json:\",inline\"`\n\tmetav1.ListMeta `json:\"metadata\"`\n\tItems           []Kluster `json:\"items\"`\n}\n\nfunc (spec Kluster) Account() string {\n\treturn spec.ObjectMeta.Labels[\"account\"]\n}\n\nfunc (spec Kluster) ApiServiceIP() (net.IP, error) {\n\t_, ipnet, err := net.ParseCIDR(spec.Spec.ServiceCIDR)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tip, err := ip.GetIndexedIP(ipnet, 1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ip, nil\n\n}\n\nfunc (k *Kluster) NeedsFinalizer(finalizer string) bool {\n\tif k.ObjectMeta.DeletionTimestamp != nil {\n\t\t\/\/ already deleted. do not add another finalizer anymore\n\t\treturn false\n\t}\n\n\tfor _, f := range k.ObjectMeta.Finalizers {\n\t\tif f == finalizer {\n\t\t\t\/\/ Finalizer is already present, nothing to do\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (k *Kluster) HasFinalizer(finalizer string) bool {\n\tif k.ObjectMeta.DeletionTimestamp == nil {\n\t\t\/\/ not deleted. do not remove finalizers at this time\n\t\treturn false\n\t}\n\n\tfor _, f := range k.ObjectMeta.Finalizers {\n\t\tif f == finalizer {\n\t\t\t\/\/ Finalizer is already present\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (k *Kluster) AddFinalizer(finalizer string) {\n\tif k.NeedsFinalizer(finalizer) {\n\t\tk.Finalizers = append(k.Finalizers, finalizer)\n\t}\n}\n\nfunc (k *Kluster) RemoveFinalizer(finalizer string) {\n\tif k.HasFinalizer(finalizer) {\n\t\tfor i, f := range k.Finalizers {\n\t\t\tif f == finalizer {\n\t\t\t\tk.Finalizers = append(k.Finalizers[:i], k.Finalizers[i+1:]...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (k *Kluster) Disabled() bool {\n\treturn k.Status.MigrationsPending\n}\n<commit_msg>Improve error message<commit_after>package v1\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"github.com\/sapcc\/kubernikus\/pkg\/api\/models\"\n\t\"github.com\/sapcc\/kubernikus\/pkg\/util\/ip\"\n\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\n\/\/ +genclient\n\/\/ +k8s:deepcopy-gen:interfaces=k8s.io\/apimachinery\/pkg\/runtime.Object\n\ntype Kluster struct {\n\tmetav1.TypeMeta   `json:\",inline\"`\n\tmetav1.ObjectMeta `json:\"metadata\"`\n\tSpec              models.KlusterSpec   `json:\"spec\"`\n\tStatus            models.KlusterStatus `json:\"status,omitempty\"`\n}\n\n\/\/ +k8s:deepcopy-gen:interfaces=k8s.io\/apimachinery\/pkg\/runtime.Object\n\ntype KlusterList struct {\n\tmetav1.TypeMeta `json:\",inline\"`\n\tmetav1.ListMeta `json:\"metadata\"`\n\tItems           []Kluster `json:\"items\"`\n}\n\nfunc (spec Kluster) Account() string {\n\treturn spec.ObjectMeta.Labels[\"account\"]\n}\n\nfunc (spec Kluster) ApiServiceIP() (net.IP, error) {\n\t_, ipnet, err := net.ParseCIDR(spec.Spec.ServiceCIDR)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed to parse service CIDR: %s\", err)\n\t}\n\tip, err := ip.GetIndexedIP(ipnet, 1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ip, nil\n\n}\n\nfunc (k *Kluster) NeedsFinalizer(finalizer string) bool {\n\tif k.ObjectMeta.DeletionTimestamp != nil {\n\t\t\/\/ already deleted. do not add another finalizer anymore\n\t\treturn false\n\t}\n\n\tfor _, f := range k.ObjectMeta.Finalizers {\n\t\tif f == finalizer {\n\t\t\t\/\/ Finalizer is already present, nothing to do\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc (k *Kluster) HasFinalizer(finalizer string) bool {\n\tif k.ObjectMeta.DeletionTimestamp == nil {\n\t\t\/\/ not deleted. do not remove finalizers at this time\n\t\treturn false\n\t}\n\n\tfor _, f := range k.ObjectMeta.Finalizers {\n\t\tif f == finalizer {\n\t\t\t\/\/ Finalizer is already present\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (k *Kluster) AddFinalizer(finalizer string) {\n\tif k.NeedsFinalizer(finalizer) {\n\t\tk.Finalizers = append(k.Finalizers, finalizer)\n\t}\n}\n\nfunc (k *Kluster) RemoveFinalizer(finalizer string) {\n\tif k.HasFinalizer(finalizer) {\n\t\tfor i, f := range k.Finalizers {\n\t\t\tif f == finalizer {\n\t\t\t\tk.Finalizers = append(k.Finalizers[:i], k.Finalizers[i+1:]...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (k *Kluster) Disabled() bool {\n\treturn k.Status.MigrationsPending\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is part of the KubeVirt project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * Copyright 2020 Red Hat, Inc.\n *\n *\/\n\npackage network\n\nimport (\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\/v2\"\n\t. \"github.com\/onsi\/gomega\"\n\n\t\"kubevirt.io\/kubevirt\/tests\/util\"\n\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\n\tv1 \"kubevirt.io\/api\/core\/v1\"\n\t\"kubevirt.io\/client-go\/kubecli\"\n\n\t\"kubevirt.io\/kubevirt\/tests\"\n\t\"kubevirt.io\/kubevirt\/tests\/console\"\n\tcd \"kubevirt.io\/kubevirt\/tests\/containerdisk\"\n\t\"kubevirt.io\/kubevirt\/tests\/libnet\"\n\t\"kubevirt.io\/kubevirt\/tests\/libvmi\"\n)\n\nvar _ = SIGDescribe(\"Primary Pod Network\", func() {\n\tvar virtClient kubecli.KubevirtClient\n\tBeforeEach(func() {\n\t\ttests.BeforeTestCleanup()\n\n\t\tvar err error\n\t\tvirtClient, err = kubecli.GetKubevirtClient()\n\t\tExpect(err).NotTo(HaveOccurred(), \"Should successfully initialize an API client\")\n\t})\n\n\tDescribe(\"Status\", func() {\n\t\tAssertReportedIP := func(vmi *v1.VirtualMachineInstance) {\n\t\t\tBy(\"Getting pod of the VMI\")\n\t\t\tvmiPod := tests.GetRunningPodByVirtualMachineInstance(vmi, util.NamespaceTestDefault)\n\n\t\t\tBy(\"Making sure IP\/s reported on the VMI matches the ones on the pod\")\n\t\t\tExpect(libnet.ValidateVMIandPodIPMatch(vmi, vmiPod)).To(Succeed(), \"Should have matching IP\/s between pod and vmi\")\n\t\t}\n\n\t\tContext(\"VMI connected to the pod network using the default (implicit) binding\", func() {\n\t\t\tvar vmi *v1.VirtualMachineInstance\n\n\t\t\tBeforeEach(func() {\n\t\t\t\tvmi = setupVMI(virtClient, vmiWithDefaultBinding())\n\t\t\t})\n\n\t\t\tIt(\"should report PodIP as its own on interface status\", func() { AssertReportedIP(vmi) })\n\t\t})\n\n\t\tContext(\"VMI connected to the pod network using bridge binding\", func() {\n\t\t\tWhen(\"Guest Agent exists\", func() {\n\t\t\t\tvar (\n\t\t\t\t\tvmi   *v1.VirtualMachineInstance\n\t\t\t\t\tvmiIP = func() string {\n\t\t\t\t\t\tvar err error\n\t\t\t\t\t\tvmi, err = virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})\n\t\t\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"should success retrieving VMI to get IP\")\n\t\t\t\t\t\treturn vmi.Status.Interfaces[0].IP\n\t\t\t\t\t}\n\n\t\t\t\t\tvmiIPs = func() []string {\n\t\t\t\t\t\tvar err error\n\t\t\t\t\t\tvmi, err = virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})\n\t\t\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"should success retrieving VMI to get IPs\")\n\t\t\t\t\t\treturn vmi.Status.Interfaces[0].IPs\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tlibnet.SkipWhenClusterNotSupportIpv4(virtClient)\n\t\t\t\t\tvar err error\n\n\t\t\t\t\tvmi, err = newFedoraWithGuestAgentAndDefaultInterface(libvmi.InterfaceDeviceWithBridgeBinding(libvmi.DefaultInterfaceName))\n\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\tvmi, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)\n\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\t\ttests.WaitForSuccessfulVMIStart(vmi)\n\t\t\t\t\ttests.WaitAgentConnected(virtClient, vmi)\n\t\t\t\t})\n\n\t\t\t\tIt(\"should report PodIP\/s IPv4 as its own on interface status\", func() {\n\t\t\t\t\tvmiPod := tests.GetRunningPodByVirtualMachineInstance(vmi, vmi.Namespace)\n\t\t\t\t\tEventually(vmiIP).Should(Equal(vmiPod.Status.PodIP), \"should contain VMI Status IP as Pod status ip\")\n\t\t\t\t\tEventually(vmiIPs).Should(ContainElement(vmiPod.Status.PodIP), \"should contain IPv4 reported by guest agent\")\n\t\t\t\t})\n\n\t\t\t\tIt(\"should report VMIs static IPv6 at interface status\", func() {\n\t\t\t\t\tEventually(vmiIPs).Should(ContainElement(libnet.DefaultIPv6Address), \"should contain IPv6 address set by cloud-init and reported by guest agent\")\n\t\t\t\t})\n\t\t\t})\n\t\t\tWhen(\"no Guest Agent exists\", func() {\n\t\t\t\tvar vmi *v1.VirtualMachineInstance\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tvmi = setupVMI(virtClient, vmiWithBridgeBinding())\n\t\t\t\t})\n\n\t\t\t\tIt(\"should report PodIP as its own on interface status\", func() { AssertReportedIP(vmi) })\n\t\t\t})\n\t\t})\n\n\t\tContext(\"VMI connected to the pod network using masquerade binding\", func() {\n\t\t\tWhen(\"Guest Agent exists\", func() {\n\t\t\t\tvar vmi *v1.VirtualMachineInstance\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\ttmpVmi, err := newFedoraWithGuestAgentAndDefaultInterface(libvmi.InterfaceDeviceWithMasqueradeBinding())\n\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\ttmpVmi, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(tmpVmi)\n\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\t\tvmi = tests.WaitUntilVMIReady(tmpVmi, console.LoginToFedora)\n\n\t\t\t\t\ttests.WaitAgentConnected(virtClient, vmi)\n\t\t\t\t})\n\n\t\t\t\tIt(\"[test_id:4153]should report PodIP\/s as its own on interface status\", func() {\n\t\t\t\t\tvmiPod := tests.GetRunningPodByVirtualMachineInstance(vmi, vmi.Namespace)\n\t\t\t\t\tConsistently(func() error {\n\t\t\t\t\t\tvmi, err := virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn libnet.ValidateVMIandPodIPMatch(vmi, vmiPod)\n\t\t\t\t\t}, 5*time.Second, time.Second).Should(Succeed())\n\t\t\t\t})\n\n\t\t\t})\n\n\t\t\tWhen(\"no Guest Agent exists\", func() {\n\t\t\t\tvar vmi *v1.VirtualMachineInstance\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tvmi = setupVMI(virtClient, vmiWithMasqueradeBinding())\n\t\t\t\t})\n\n\t\t\t\tIt(\"[Conformance] should report PodIP as its own on interface status\", func() { AssertReportedIP(vmi) })\n\t\t\t})\n\t\t})\n\t})\n})\n\nfunc setupVMI(virtClient kubecli.KubevirtClient, vmi *v1.VirtualMachineInstance) *v1.VirtualMachineInstance {\n\tBy(\"Creating the VMI\")\n\tvar err error\n\tvmi, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)\n\tExpect(err).NotTo(HaveOccurred(), \"VMI should be successfully created\")\n\n\tBy(\"Waiting until the VMI gets ready\")\n\tvmi = tests.WaitUntilVMIReady(vmi, console.LoginToAlpine)\n\n\treturn vmi\n}\n\nfunc vmiWithDefaultBinding() *v1.VirtualMachineInstance {\n\tvmi := tests.NewRandomVMIWithEphemeralDisk(cd.ContainerDiskFor(cd.ContainerDiskAlpine))\n\tvmi.Spec.Domain.Devices.Interfaces = nil\n\tvmi.Spec.Networks = nil\n\treturn vmi\n}\n\nfunc vmiWithBridgeBinding() *v1.VirtualMachineInstance {\n\tvmi := tests.NewRandomVMIWithEphemeralDisk(cd.ContainerDiskFor(cd.ContainerDiskAlpine))\n\tvmi.Spec.Domain.Devices.Interfaces = []v1.Interface{*v1.DefaultBridgeNetworkInterface()}\n\tvmi.Spec.Networks = []v1.Network{*v1.DefaultPodNetwork()}\n\treturn vmi\n}\n\nfunc vmiWithMasqueradeBinding() *v1.VirtualMachineInstance {\n\tvmi := tests.NewRandomVMIWithEphemeralDisk(cd.ContainerDiskFor(cd.ContainerDiskAlpine))\n\tvmi.Spec.Domain.Devices.Interfaces = []v1.Interface{*v1.DefaultMasqueradeNetworkInterface()}\n\tvmi.Spec.Networks = []v1.Network{*v1.DefaultPodNetwork()}\n\treturn vmi\n}\n\nfunc newFedoraWithGuestAgentAndDefaultInterface(iface v1.Interface) (*v1.VirtualMachineInstance, error) {\n\tnetworkData, err := libnet.CreateDefaultCloudInitNetworkData()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvmi := libvmi.NewFedora(\n\t\tlibvmi.WithInterface(iface),\n\t\tlibvmi.WithNetwork(v1.DefaultPodNetwork()),\n\t\tlibvmi.WithCloudInitNoCloudNetworkData(networkData, false),\n\t)\n\treturn vmi, nil\n}\n<commit_msg>tests, network, primary-pod: Use libvmi for default binding<commit_after>\/*\n * This file is part of the KubeVirt project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * Copyright 2020 Red Hat, Inc.\n *\n *\/\n\npackage network\n\nimport (\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\/v2\"\n\t. \"github.com\/onsi\/gomega\"\n\n\t\"kubevirt.io\/kubevirt\/tests\/util\"\n\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\n\tv1 \"kubevirt.io\/api\/core\/v1\"\n\t\"kubevirt.io\/client-go\/kubecli\"\n\n\t\"kubevirt.io\/kubevirt\/tests\"\n\t\"kubevirt.io\/kubevirt\/tests\/console\"\n\tcd \"kubevirt.io\/kubevirt\/tests\/containerdisk\"\n\t\"kubevirt.io\/kubevirt\/tests\/libnet\"\n\t\"kubevirt.io\/kubevirt\/tests\/libvmi\"\n)\n\nvar _ = SIGDescribe(\"Primary Pod Network\", func() {\n\tvar virtClient kubecli.KubevirtClient\n\tBeforeEach(func() {\n\t\ttests.BeforeTestCleanup()\n\n\t\tvar err error\n\t\tvirtClient, err = kubecli.GetKubevirtClient()\n\t\tExpect(err).NotTo(HaveOccurred(), \"Should successfully initialize an API client\")\n\t})\n\n\tDescribe(\"Status\", func() {\n\t\tAssertReportedIP := func(vmi *v1.VirtualMachineInstance) {\n\t\t\tBy(\"Getting pod of the VMI\")\n\t\t\tvmiPod := tests.GetRunningPodByVirtualMachineInstance(vmi, util.NamespaceTestDefault)\n\n\t\t\tBy(\"Making sure IP\/s reported on the VMI matches the ones on the pod\")\n\t\t\tExpect(libnet.ValidateVMIandPodIPMatch(vmi, vmiPod)).To(Succeed(), \"Should have matching IP\/s between pod and vmi\")\n\t\t}\n\n\t\tContext(\"VMI connected to the pod network using the default (implicit) binding\", func() {\n\t\t\tvar vmi *v1.VirtualMachineInstance\n\n\t\t\tBeforeEach(func() {\n\t\t\t\tvmi = setupVMI(virtClient, libvmi.NewAlpine())\n\t\t\t})\n\n\t\t\tIt(\"should report PodIP as its own on interface status\", func() { AssertReportedIP(vmi) })\n\t\t})\n\n\t\tContext(\"VMI connected to the pod network using bridge binding\", func() {\n\t\t\tWhen(\"Guest Agent exists\", func() {\n\t\t\t\tvar (\n\t\t\t\t\tvmi   *v1.VirtualMachineInstance\n\t\t\t\t\tvmiIP = func() string {\n\t\t\t\t\t\tvar err error\n\t\t\t\t\t\tvmi, err = virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})\n\t\t\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"should success retrieving VMI to get IP\")\n\t\t\t\t\t\treturn vmi.Status.Interfaces[0].IP\n\t\t\t\t\t}\n\n\t\t\t\t\tvmiIPs = func() []string {\n\t\t\t\t\t\tvar err error\n\t\t\t\t\t\tvmi, err = virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})\n\t\t\t\t\t\tExpectWithOffset(1, err).ToNot(HaveOccurred(), \"should success retrieving VMI to get IPs\")\n\t\t\t\t\t\treturn vmi.Status.Interfaces[0].IPs\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tlibnet.SkipWhenClusterNotSupportIpv4(virtClient)\n\t\t\t\t\tvar err error\n\n\t\t\t\t\tvmi, err = newFedoraWithGuestAgentAndDefaultInterface(libvmi.InterfaceDeviceWithBridgeBinding(libvmi.DefaultInterfaceName))\n\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\tvmi, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)\n\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\t\ttests.WaitForSuccessfulVMIStart(vmi)\n\t\t\t\t\ttests.WaitAgentConnected(virtClient, vmi)\n\t\t\t\t})\n\n\t\t\t\tIt(\"should report PodIP\/s IPv4 as its own on interface status\", func() {\n\t\t\t\t\tvmiPod := tests.GetRunningPodByVirtualMachineInstance(vmi, vmi.Namespace)\n\t\t\t\t\tEventually(vmiIP).Should(Equal(vmiPod.Status.PodIP), \"should contain VMI Status IP as Pod status ip\")\n\t\t\t\t\tEventually(vmiIPs).Should(ContainElement(vmiPod.Status.PodIP), \"should contain IPv4 reported by guest agent\")\n\t\t\t\t})\n\n\t\t\t\tIt(\"should report VMIs static IPv6 at interface status\", func() {\n\t\t\t\t\tEventually(vmiIPs).Should(ContainElement(libnet.DefaultIPv6Address), \"should contain IPv6 address set by cloud-init and reported by guest agent\")\n\t\t\t\t})\n\t\t\t})\n\t\t\tWhen(\"no Guest Agent exists\", func() {\n\t\t\t\tvar vmi *v1.VirtualMachineInstance\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tvmi = setupVMI(virtClient, vmiWithBridgeBinding())\n\t\t\t\t})\n\n\t\t\t\tIt(\"should report PodIP as its own on interface status\", func() { AssertReportedIP(vmi) })\n\t\t\t})\n\t\t})\n\n\t\tContext(\"VMI connected to the pod network using masquerade binding\", func() {\n\t\t\tWhen(\"Guest Agent exists\", func() {\n\t\t\t\tvar vmi *v1.VirtualMachineInstance\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\ttmpVmi, err := newFedoraWithGuestAgentAndDefaultInterface(libvmi.InterfaceDeviceWithMasqueradeBinding())\n\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\ttmpVmi, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(tmpVmi)\n\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\t\tvmi = tests.WaitUntilVMIReady(tmpVmi, console.LoginToFedora)\n\n\t\t\t\t\ttests.WaitAgentConnected(virtClient, vmi)\n\t\t\t\t})\n\n\t\t\t\tIt(\"[test_id:4153]should report PodIP\/s as its own on interface status\", func() {\n\t\t\t\t\tvmiPod := tests.GetRunningPodByVirtualMachineInstance(vmi, vmi.Namespace)\n\t\t\t\t\tConsistently(func() error {\n\t\t\t\t\t\tvmi, err := virtClient.VirtualMachineInstance(vmi.Namespace).Get(vmi.Name, &metav1.GetOptions{})\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn libnet.ValidateVMIandPodIPMatch(vmi, vmiPod)\n\t\t\t\t\t}, 5*time.Second, time.Second).Should(Succeed())\n\t\t\t\t})\n\n\t\t\t})\n\n\t\t\tWhen(\"no Guest Agent exists\", func() {\n\t\t\t\tvar vmi *v1.VirtualMachineInstance\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tvmi = setupVMI(virtClient, vmiWithMasqueradeBinding())\n\t\t\t\t})\n\n\t\t\t\tIt(\"[Conformance] should report PodIP as its own on interface status\", func() { AssertReportedIP(vmi) })\n\t\t\t})\n\t\t})\n\t})\n})\n\nfunc setupVMI(virtClient kubecli.KubevirtClient, vmi *v1.VirtualMachineInstance) *v1.VirtualMachineInstance {\n\tBy(\"Creating the VMI\")\n\tvar err error\n\tvmi, err = virtClient.VirtualMachineInstance(util.NamespaceTestDefault).Create(vmi)\n\tExpect(err).NotTo(HaveOccurred(), \"VMI should be successfully created\")\n\n\tBy(\"Waiting until the VMI gets ready\")\n\tvmi = tests.WaitUntilVMIReady(vmi, console.LoginToAlpine)\n\n\treturn vmi\n}\n\nfunc vmiWithBridgeBinding() *v1.VirtualMachineInstance {\n\tvmi := tests.NewRandomVMIWithEphemeralDisk(cd.ContainerDiskFor(cd.ContainerDiskAlpine))\n\tvmi.Spec.Domain.Devices.Interfaces = []v1.Interface{*v1.DefaultBridgeNetworkInterface()}\n\tvmi.Spec.Networks = []v1.Network{*v1.DefaultPodNetwork()}\n\treturn vmi\n}\n\nfunc vmiWithMasqueradeBinding() *v1.VirtualMachineInstance {\n\tvmi := tests.NewRandomVMIWithEphemeralDisk(cd.ContainerDiskFor(cd.ContainerDiskAlpine))\n\tvmi.Spec.Domain.Devices.Interfaces = []v1.Interface{*v1.DefaultMasqueradeNetworkInterface()}\n\tvmi.Spec.Networks = []v1.Network{*v1.DefaultPodNetwork()}\n\treturn vmi\n}\n\nfunc newFedoraWithGuestAgentAndDefaultInterface(iface v1.Interface) (*v1.VirtualMachineInstance, error) {\n\tnetworkData, err := libnet.CreateDefaultCloudInitNetworkData()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvmi := libvmi.NewFedora(\n\t\tlibvmi.WithInterface(iface),\n\t\tlibvmi.WithNetwork(v1.DefaultPodNetwork()),\n\t\tlibvmi.WithCloudInitNoCloudNetworkData(networkData, false),\n\t)\n\treturn vmi, nil\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>progress on issue #19<commit_after><|endoftext|>"}
{"text":"<commit_before>package jobs\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/meifamily\/logrus\"\n\n\t\"github.com\/liam-lai\/ptt-alertor\/models\/ptt\/article\"\n\tboard \"github.com\/liam-lai\/ptt-alertor\/models\/ptt\/board\/redis\"\n\tuser \"github.com\/liam-lai\/ptt-alertor\/models\/user\/redis\"\n)\n\nconst checkBoardDuration = 180\n\ntype Checker struct {\n\temail      string\n\tline       string\n\tlineNotify string\n\tmessenger  string\n\tboard      string\n\tkeyword    string\n\tauthor     string\n\tarticles   article.Articles\n\tsubType    string\n\tword       string\n}\n\nfunc (cker Checker) String() string {\n\tsubType := \"關鍵字\"\n\tif cker.author != \"\" {\n\t\tsubType = \"作者\"\n\t}\n\treturn fmt.Sprintf(\"%s@%s\\r\\n看板：%s；%s：%s%s\", cker.word, cker.board, cker.board, subType, cker.word, cker.articles.String())\n}\n\nfunc (cker Checker) Self() Checker {\n\treturn cker\n}\n\nfunc (cker Checker) Run() {\n\tboardCh := make(chan *board.Board)\n\tgo func() {\n\t\tfor {\n\t\t\tbds := new(board.Board).All()\n\t\t\tfor _, bd := range bds {\n\t\t\t\ttime.Sleep(checkBoardDuration * time.Millisecond)\n\t\t\t\tgo checkNewArticle(bd, boardCh)\n\t\t\t}\n\t\t}\n\t}()\n\tckerCh := make(chan Checker)\n\n\tfor {\n\t\tselect {\n\t\tcase bd := <-boardCh:\n\t\t\tcheckSubscriber(bd, cker, ckerCh)\n\t\tcase cker := <-ckerCh:\n\t\t\tcker.subType = \"keyword\"\n\t\t\tcker.word = cker.keyword\n\t\t\tif cker.author != \"\" {\n\t\t\t\tcker.subType = \"author\"\n\t\t\t\tcker.word = cker.author\n\t\t\t}\n\t\t\tgo sendMessage(cker)\n\t\t}\n\t}\n}\n\nfunc checkNewArticle(bd *board.Board, boardCh chan *board.Board) {\n\tbd.WithNewArticles()\n\tif bd.NewArticles == nil {\n\t\tbd.Articles = bd.OnlineArticles\n\t\tlog.WithField(\"board\", bd.Name).Info(\"Created Articles\")\n\t\tbd.Save()\n\t}\n\tif len(bd.NewArticles) != 0 {\n\t\tbd.Articles = bd.OnlineArticles\n\t\tlog.WithField(\"board\", bd.Name).Info(\"Updated Articles\")\n\t\tbd.Save()\n\t\tboardCh <- bd\n\t}\n}\n\nfunc checkSubscriber(bd *board.Board, cker Checker, ckerCh chan Checker) {\n\tusers := new(user.User).All()\n\tfor _, user := range users {\n\t\tif user.Enable {\n\t\t\tcker.email = user.Profile.Email\n\t\t\tcker.line = user.Profile.Line\n\t\t\tcker.lineNotify = user.Profile.LineAccessToken\n\t\t\tcker.messenger = user.Profile.Messenger\n\t\t\tgo subscribeChecker(user, bd, cker, ckerCh)\n\t\t}\n\t}\n}\n\nfunc subscribeChecker(user *user.User, bd *board.Board, cker Checker, ckerCh chan Checker) {\n\tfor _, sub := range user.Subscribes {\n\t\tif bd.Name == sub.Board {\n\t\t\tcker.board = sub.Board\n\t\t\tfor _, keyword := range sub.Keywords {\n\t\t\t\tgo keywordChecker(keyword, bd, cker, ckerCh)\n\t\t\t}\n\t\t\tfor _, author := range sub.Authors {\n\t\t\t\tgo authorChecker(author, bd, cker, ckerCh)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc keywordChecker(keyword string, bd *board.Board, cker Checker, ckerCh chan Checker) {\n\tkeywordArticles := make(article.Articles, 0)\n\tfor _, newAtcl := range bd.NewArticles {\n\t\tif newAtcl.MatchKeyword(keyword) {\n\t\t\tnewAtcl.Author = \"\"\n\t\t\tkeywordArticles = append(keywordArticles, newAtcl)\n\t\t}\n\t}\n\tif len(keywordArticles) != 0 {\n\t\tcker.keyword = keyword\n\t\tcker.articles = keywordArticles\n\t\tckerCh <- cker\n\t}\n}\n\nfunc authorChecker(author string, bd *board.Board, cker Checker, ckerCh chan Checker) {\n\tauthorArticles := make(article.Articles, 0)\n\tfor _, newAtcl := range bd.NewArticles {\n\t\tif strings.EqualFold(newAtcl.Author, author) {\n\t\t\tauthorArticles = append(authorArticles, newAtcl)\n\t\t}\n\t}\n\tif len(authorArticles) != 0 {\n\t\tcker.author = author\n\t\tcker.articles = authorArticles\n\t\tckerCh <- cker\n\t}\n\n}\n<commit_msg>try to decrease fetch duration<commit_after>package jobs\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/meifamily\/logrus\"\n\n\t\"github.com\/liam-lai\/ptt-alertor\/models\/ptt\/article\"\n\tboard \"github.com\/liam-lai\/ptt-alertor\/models\/ptt\/board\/redis\"\n\tuser \"github.com\/liam-lai\/ptt-alertor\/models\/user\/redis\"\n)\n\nconst checkBoardDuration = 150\n\ntype Checker struct {\n\temail      string\n\tline       string\n\tlineNotify string\n\tmessenger  string\n\tboard      string\n\tkeyword    string\n\tauthor     string\n\tarticles   article.Articles\n\tsubType    string\n\tword       string\n}\n\nfunc (cker Checker) String() string {\n\tsubType := \"關鍵字\"\n\tif cker.author != \"\" {\n\t\tsubType = \"作者\"\n\t}\n\treturn fmt.Sprintf(\"%s@%s\\r\\n看板：%s；%s：%s%s\", cker.word, cker.board, cker.board, subType, cker.word, cker.articles.String())\n}\n\nfunc (cker Checker) Self() Checker {\n\treturn cker\n}\n\nfunc (cker Checker) Run() {\n\tboardCh := make(chan *board.Board)\n\tgo func() {\n\t\tfor {\n\t\t\tbds := new(board.Board).All()\n\t\t\tfor _, bd := range bds {\n\t\t\t\ttime.Sleep(checkBoardDuration * time.Millisecond)\n\t\t\t\tgo checkNewArticle(bd, boardCh)\n\t\t\t}\n\t\t}\n\t}()\n\tckerCh := make(chan Checker)\n\n\tfor {\n\t\tselect {\n\t\tcase bd := <-boardCh:\n\t\t\tcheckSubscriber(bd, cker, ckerCh)\n\t\tcase cker := <-ckerCh:\n\t\t\tcker.subType = \"keyword\"\n\t\t\tcker.word = cker.keyword\n\t\t\tif cker.author != \"\" {\n\t\t\t\tcker.subType = \"author\"\n\t\t\t\tcker.word = cker.author\n\t\t\t}\n\t\t\tgo sendMessage(cker)\n\t\t}\n\t}\n}\n\nfunc checkNewArticle(bd *board.Board, boardCh chan *board.Board) {\n\tbd.WithNewArticles()\n\tif bd.NewArticles == nil {\n\t\tbd.Articles = bd.OnlineArticles\n\t\tlog.WithField(\"board\", bd.Name).Info(\"Created Articles\")\n\t\tbd.Save()\n\t}\n\tif len(bd.NewArticles) != 0 {\n\t\tbd.Articles = bd.OnlineArticles\n\t\tlog.WithField(\"board\", bd.Name).Info(\"Updated Articles\")\n\t\tbd.Save()\n\t\tboardCh <- bd\n\t}\n}\n\nfunc checkSubscriber(bd *board.Board, cker Checker, ckerCh chan Checker) {\n\tusers := new(user.User).All()\n\tfor _, user := range users {\n\t\tif user.Enable {\n\t\t\tcker.email = user.Profile.Email\n\t\t\tcker.line = user.Profile.Line\n\t\t\tcker.lineNotify = user.Profile.LineAccessToken\n\t\t\tcker.messenger = user.Profile.Messenger\n\t\t\tgo subscribeChecker(user, bd, cker, ckerCh)\n\t\t}\n\t}\n}\n\nfunc subscribeChecker(user *user.User, bd *board.Board, cker Checker, ckerCh chan Checker) {\n\tfor _, sub := range user.Subscribes {\n\t\tif bd.Name == sub.Board {\n\t\t\tcker.board = sub.Board\n\t\t\tfor _, keyword := range sub.Keywords {\n\t\t\t\tgo keywordChecker(keyword, bd, cker, ckerCh)\n\t\t\t}\n\t\t\tfor _, author := range sub.Authors {\n\t\t\t\tgo authorChecker(author, bd, cker, ckerCh)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc keywordChecker(keyword string, bd *board.Board, cker Checker, ckerCh chan Checker) {\n\tkeywordArticles := make(article.Articles, 0)\n\tfor _, newAtcl := range bd.NewArticles {\n\t\tif newAtcl.MatchKeyword(keyword) {\n\t\t\tnewAtcl.Author = \"\"\n\t\t\tkeywordArticles = append(keywordArticles, newAtcl)\n\t\t}\n\t}\n\tif len(keywordArticles) != 0 {\n\t\tcker.keyword = keyword\n\t\tcker.articles = keywordArticles\n\t\tckerCh <- cker\n\t}\n}\n\nfunc authorChecker(author string, bd *board.Board, cker Checker, ckerCh chan Checker) {\n\tauthorArticles := make(article.Articles, 0)\n\tfor _, newAtcl := range bd.NewArticles {\n\t\tif strings.EqualFold(newAtcl.Author, author) {\n\t\t\tauthorArticles = append(authorArticles, newAtcl)\n\t\t}\n\t}\n\tif len(authorArticles) != 0 {\n\t\tcker.author = author\n\t\tcker.articles = authorArticles\n\t\tckerCh <- cker\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage apiserver\n\nimport (\n\t\"k8s.io\/component-base\/metrics\"\n\t\"k8s.io\/component-base\/metrics\/legacyregistry\"\n)\n\n\/*\n * By default, all the following metrics are defined as falling under\n * ALPHA stability level https:\/\/github.com\/kubernetes\/enhancements\/blob\/master\/keps\/sig-instrumentation\/20190404-kubernetes-control-plane-metrics-stability.md#stability-classes)\n *\n * Promoting the stability level of the metric is a responsibility of the component owner, since it\n * involves explicitly acknowledging support for the metric across multiple releases, in accordance with\n * the metric stability policy.\n *\/\nvar (\n\tunavailableCounter = metrics.NewCounterVec(\n\t\t&metrics.CounterOpts{\n\t\t\tName:           \"aggregator_unavailable_apiservice_count\",\n\t\t\tHelp:           \"Counter of APIServices which are marked as unavailable broken down by APIService name and reason.\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t},\n\t\t[]string{\"name\", \"reason\"},\n\t)\n\tunavailableGauge = metrics.NewGaugeVec(\n\t\t&metrics.GaugeOpts{\n\t\t\tName:           \"aggregator_unavailable_apiservice\",\n\t\t\tHelp:           \"Gauge of APIServices which are marked as unavailable broken down by APIService name.\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t},\n\t\t[]string{\"name\"},\n\t)\n)\n\nfunc init() {\n\tlegacyregistry.MustRegister(unavailableCounter)\n\tlegacyregistry.MustRegister(unavailableGauge)\n}\n<commit_msg>kube-aggregator: changes the name of aggregator_unavailable_apiservice_count metrics<commit_after>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage apiserver\n\nimport (\n\t\"k8s.io\/component-base\/metrics\"\n\t\"k8s.io\/component-base\/metrics\/legacyregistry\"\n)\n\n\/*\n * By default, all the following metrics are defined as falling under\n * ALPHA stability level https:\/\/github.com\/kubernetes\/enhancements\/blob\/master\/keps\/sig-instrumentation\/20190404-kubernetes-control-plane-metrics-stability.md#stability-classes)\n *\n * Promoting the stability level of the metric is a responsibility of the component owner, since it\n * involves explicitly acknowledging support for the metric across multiple releases, in accordance with\n * the metric stability policy.\n *\/\nvar (\n\tunavailableCounter = metrics.NewCounterVec(\n\t\t&metrics.CounterOpts{\n\t\t\tName:           \"aggregator_unavailable_apiservice_total\",\n\t\t\tHelp:           \"Counter of APIServices which are marked as unavailable broken down by APIService name and reason.\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t},\n\t\t[]string{\"name\", \"reason\"},\n\t)\n\tunavailableGauge = metrics.NewGaugeVec(\n\t\t&metrics.GaugeOpts{\n\t\t\tName:           \"aggregator_unavailable_apiservice\",\n\t\t\tHelp:           \"Gauge of APIServices which are marked as unavailable broken down by APIService name.\",\n\t\t\tStabilityLevel: metrics.ALPHA,\n\t\t},\n\t\t[]string{\"name\"},\n\t)\n)\n\nfunc init() {\n\tlegacyregistry.MustRegister(unavailableCounter)\n\tlegacyregistry.MustRegister(unavailableGauge)\n}\n<|endoftext|>"}
{"text":"<commit_before>package commands\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\tmh \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multihash\"\n\tcmds \"github.com\/jbenet\/go-ipfs\/commands\"\n\t\"github.com\/jbenet\/go-ipfs\/core\"\n\tdag \"github.com\/jbenet\/go-ipfs\/merkledag\"\n\tu \"github.com\/jbenet\/go-ipfs\/util\"\n)\n\n\/\/ KeyList is a general type for outputting lists of keys\ntype KeyList struct {\n\tKeys []string\n}\n\n\/\/ KeyListTextMarshaler outputs a KeyList as plaintext, one key per line\nfunc KeyListTextMarshaler(res cmds.Response) ([]byte, error) {\n\toutput := res.Output().(*KeyList)\n\ts := strings.Join(output.Keys, \"\\n\")\n\treturn []byte(s), nil\n}\n\nvar refsCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Lists link hashes from an object\",\n\t\tShortDescription: `\nRetrieves the object named by <ipfs-path> and displays the link\nhashes it contains, with the following format:\n\n  <link base58 hash>\n\nNote: list all refs recursively with -r.\n`,\n\t},\n\n\tArguments: []cmds.Argument{\n\t\tcmds.StringArg(\"ipfs-path\", true, true, \"Path to the object(s) to list refs from\"),\n\t},\n\tOptions: []cmds.Option{\n\t\tcmds.BoolOption(\"unique\", \"u\", \"Omit duplicate refs from output\"),\n\t\tcmds.BoolOption(\"recursive\", \"r\", \"Recursively list links of child nodes\"),\n\t},\n\tRun: func(req cmds.Request) (interface{}, error) {\n\t\tn, err := req.Context().GetNode()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tunique, found, err := req.Option(\"unique\").Bool()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !found {\n\t\t\tunique = false\n\t\t}\n\n\t\trecursive, found, err := req.Option(\"recursive\").Bool()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !found {\n\t\t\trecursive = false\n\t\t}\n\n\t\treturn getRefs(n, req.Arguments(), unique, recursive)\n\t},\n\tType: &KeyList{},\n\tMarshalers: cmds.MarshalerMap{\n\t\tcmds.Text: KeyListTextMarshaler,\n\t},\n}\n\nfunc getRefs(n *core.IpfsNode, paths []string, unique, recursive bool) (*KeyList, error) {\n\tvar refsSeen map[u.Key]bool\n\tif unique {\n\t\trefsSeen = make(map[u.Key]bool)\n\t}\n\n\trefs := make([]string, 0)\n\n\tfor _, path := range paths {\n\t\tobject, err := n.Resolver.ResolvePath(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\trefs, err = addRefs(n, object, refs, refsSeen, recursive)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &KeyList{refs}, nil\n}\n\nfunc addRefs(n *core.IpfsNode, object *dag.Node, refs []string, refsSeen map[u.Key]bool, recursive bool) ([]string, error) {\n\tfor _, link := range object.Links {\n\t\tvar found bool\n\t\tfound, refs = addRef(link.Hash, refs, refsSeen)\n\n\t\tif recursive && !found {\n\t\t\tchild, err := n.DAG.Get(u.Key(link.Hash))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"cannot retrieve %s (%s)\", link.Hash.B58String(), err)\n\t\t\t}\n\n\t\t\trefs, err = addRefs(n, child, refs, refsSeen, recursive)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn refs, nil\n}\n\nfunc addRef(h mh.Multihash, refs []string, refsSeen map[u.Key]bool) (bool, []string) {\n\tif refsSeen != nil {\n\t\t_, found := refsSeen[u.Key(h)]\n\t\tif found {\n\t\t\treturn true, refs\n\t\t}\n\t\trefsSeen[u.Key(h)] = true\n\t}\n\n\trefs = append(refs, h.B58String())\n\treturn false, refs\n}\n<commit_msg>core\/commands: Fixed 'refs' option name collision<commit_after>package commands\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\tmh \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multihash\"\n\tcmds \"github.com\/jbenet\/go-ipfs\/commands\"\n\t\"github.com\/jbenet\/go-ipfs\/core\"\n\tdag \"github.com\/jbenet\/go-ipfs\/merkledag\"\n\tu \"github.com\/jbenet\/go-ipfs\/util\"\n)\n\n\/\/ KeyList is a general type for outputting lists of keys\ntype KeyList struct {\n\tKeys []string\n}\n\n\/\/ KeyListTextMarshaler outputs a KeyList as plaintext, one key per line\nfunc KeyListTextMarshaler(res cmds.Response) ([]byte, error) {\n\toutput := res.Output().(*KeyList)\n\ts := strings.Join(output.Keys, \"\\n\")\n\treturn []byte(s), nil\n}\n\nvar refsCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Lists link hashes from an object\",\n\t\tShortDescription: `\nRetrieves the object named by <ipfs-path> and displays the link\nhashes it contains, with the following format:\n\n  <link base58 hash>\n\nNote: list all refs recursively with -r.\n`,\n\t},\n\n\tArguments: []cmds.Argument{\n\t\tcmds.StringArg(\"ipfs-path\", true, true, \"Path to the object(s) to list refs from\"),\n\t},\n\tOptions: []cmds.Option{\n\t\tcmds.BoolOption(\"unique\", \"u\", \"Omit duplicate refs from output\"),\n\t\tcmds.BoolOption(\"rec\", \"R\", \"Recursively list links of child nodes\"),\n\t},\n\tRun: func(req cmds.Request) (interface{}, error) {\n\t\tn, err := req.Context().GetNode()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tunique, found, err := req.Option(\"unique\").Bool()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !found {\n\t\t\tunique = false\n\t\t}\n\n\t\trecursive, found, err := req.Option(\"recursive\").Bool()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !found {\n\t\t\trecursive = false\n\t\t}\n\n\t\treturn getRefs(n, req.Arguments(), unique, recursive)\n\t},\n\tType: &KeyList{},\n\tMarshalers: cmds.MarshalerMap{\n\t\tcmds.Text: KeyListTextMarshaler,\n\t},\n}\n\nfunc getRefs(n *core.IpfsNode, paths []string, unique, recursive bool) (*KeyList, error) {\n\tvar refsSeen map[u.Key]bool\n\tif unique {\n\t\trefsSeen = make(map[u.Key]bool)\n\t}\n\n\trefs := make([]string, 0)\n\n\tfor _, path := range paths {\n\t\tobject, err := n.Resolver.ResolvePath(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\trefs, err = addRefs(n, object, refs, refsSeen, recursive)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &KeyList{refs}, nil\n}\n\nfunc addRefs(n *core.IpfsNode, object *dag.Node, refs []string, refsSeen map[u.Key]bool, recursive bool) ([]string, error) {\n\tfor _, link := range object.Links {\n\t\tvar found bool\n\t\tfound, refs = addRef(link.Hash, refs, refsSeen)\n\n\t\tif recursive && !found {\n\t\t\tchild, err := n.DAG.Get(u.Key(link.Hash))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"cannot retrieve %s (%s)\", link.Hash.B58String(), err)\n\t\t\t}\n\n\t\t\trefs, err = addRefs(n, child, refs, refsSeen, recursive)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn refs, nil\n}\n\nfunc addRef(h mh.Multihash, refs []string, refsSeen map[u.Key]bool) (bool, []string) {\n\tif refsSeen != nil {\n\t\t_, found := refsSeen[u.Key(h)]\n\t\tif found {\n\t\t\treturn true, refs\n\t\t}\n\t\trefsSeen[u.Key(h)] = true\n\t}\n\n\trefs = append(refs, h.B58String())\n\treturn false, refs\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014 Pagoda Box Inc.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can\n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\npackage jobs\n\n\/\/\nimport (\n\t\"github.com\/nanobox-io\/nanobox-boxfile\"\n\n\t\"github.com\/nanobox-io\/nanobox-server\/config\"\n\t\"github.com\/nanobox-io\/nanobox-server\/util\/docker\"\n\t\"github.com\/nanobox-io\/nanobox-server\/util\/script\"\n\t\"github.com\/nanobox-io\/nanobox-server\/util\/worker\"\n)\n\n\/\/\ntype Startup struct{}\n\n\/\/ process on startup\nfunc (j *Startup) Process() {\n\tconfig.Log.Info(\"starting startup job\")\n\n\tdocker.RemoveContainer(\"exec1\")\n\t\/\/ TODO get the boxfile. merge with build boxfile(if any) and call:\n\t\/\/ configureRoutes(box)\n\t\/\/ configurePorts(box)\n\tbox := combinedBox()\n\n\tconfigureRoutes(box)\n\tconfigurePorts(box)\n\n\t\/\/ we also need to set up a ssh tunnel for each running docker container\n\t\/\/ this is easiest to do by creating a ServiceEnv job and working it\n\tworker := worker.New()\n\tworker.Blocking = true\n\tworker.Concurrent = true\n\n\tserviceContainers, _ := docker.ListContainers(\"service\")\n\tfor _, container := range serviceContainers {\n\t\ts := ServiceEnv{UID: container.Config.Labels[\"uid\"]}\n\t\tworker.Queue(&s)\n\t}\n\n\tworker.Process()\n}\n<commit_msg>clean<commit_after>\/\/ Copyright (c) 2014 Pagoda Box Inc.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public License,\n\/\/ v. 2.0. If a copy of the MPL was not distributed with this file, You can\n\/\/ obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\npackage jobs\n\n\/\/\nimport (\n\n\t\"github.com\/nanobox-io\/nanobox-server\/config\"\n\t\"github.com\/nanobox-io\/nanobox-server\/util\/docker\"\n\t\"github.com\/nanobox-io\/nanobox-server\/util\/worker\"\n)\n\n\/\/\ntype Startup struct{}\n\n\/\/ process on startup\nfunc (j *Startup) Process() {\n\tconfig.Log.Info(\"starting startup job\")\n\n\tdocker.RemoveContainer(\"exec1\")\n\t\/\/ TODO get the boxfile. merge with build boxfile(if any) and call:\n\t\/\/ configureRoutes(box)\n\t\/\/ configurePorts(box)\n\tbox := combinedBox()\n\n\tconfigureRoutes(box)\n\tconfigurePorts(box)\n\n\t\/\/ we also need to set up a ssh tunnel for each running docker container\n\t\/\/ this is easiest to do by creating a ServiceEnv job and working it\n\tworker := worker.New()\n\tworker.Blocking = true\n\tworker.Concurrent = true\n\n\tserviceContainers, _ := docker.ListContainers(\"service\")\n\tfor _, container := range serviceContainers {\n\t\ts := ServiceEnv{UID: container.Config.Labels[\"uid\"]}\n\t\tworker.Queue(&s)\n\t}\n\n\tworker.Process()\n}\n<|endoftext|>"}
{"text":"<commit_before>package brightbox\n\nimport (\n\t\"time\"\n)\n\n\/\/ LoadBalancer represents a Load Balancer\n\/\/ https:\/\/api.gb1.brightbox.com\/1.0\/#load_balancer\ntype LoadBalancer struct {\n\tId            string\n\tName          string\n\tStatus        string\n\tCreatedAt     *time.Time `json:\"created_at\"`\n\tDeletedAt     *time.Time `json:\"deleted_at\"`\n\tLocked        bool\n\tHttpsRedirect bool `json:\"https_redirect\"`\n\tAccount       Account\n\tNodes         []Server\n\tCloudIPs      []CloudIP `json:\"cloud_ips\"`\n\tPolicy        string\n\tBufferSize    int `json:\"buffer_size\"`\n\tListeners     []LoadBalancerListener\n\tHealthcheck   LoadBalancerHealthcheck\n\tCertificate   *LoadBalancerCertificate\n\tAcme          *LoadBalancerAcme\n}\n\n\/\/ LoadBalancerCertificate represents a certificate on a LoadBalancer\ntype LoadBalancerCertificate struct {\n\tExpiresAt time.Time `json:\"expires_at\"`\n\tValidFrom time.Time `json:\"valid_from\"`\n\tSslV3     bool      `json:\"sslv3\"`\n\tIssuer    string    `json:\"issuer\"`\n\tSubject   string    `json:\"subject\"`\n}\n\n\/\/ LoadBalancerAcme represents an ACME object on a LoadBalancer\ntype LoadBalancerAcme struct {\n\tCertificate *LoadBalancerAcmeCertificate `json:\"certificate\"`\n\tDomains     []LoadBalancerAcmeDomain     `json:domains\"`\n}\n\n\/\/ LoadBalancerAcmeCertificate represents an ACME issued certificate on\n\/\/ a LoadBalancer\ntype LoadBalancerAcmeCertificate struct {\n\tFingerprint string    `json:\"fingerprint\"`\n\tExpiresAt   time.Time `json:\"expires_at\"`\n\tIssuedAt    time.Time `json:\"issued_at\"`\n}\n\n\/\/ LoadBalancerAcmeDomains represents a domain for which ACME support\n\/\/ has been requested\ntype LoadBalancerAcmeDomain struct {\n\tIdentifier  string `json:\"identifier\"`\n\tStatus      string `json:\"status\"`\n\tLastMessage string `json:\"last_message\"`\n}\n\n\/\/ LoadBalancerHealthcheck represents a health check on a LoadBalancer\ntype LoadBalancerHealthcheck struct {\n\tType          string `json:\"type\"`\n\tPort          int    `json:\"port\"`\n\tRequest       string `json:\"request,omitempty\"`\n\tInterval      int    `json:\"interval,omitempty\"`\n\tTimeout       int    `json:\"timeout,omitempty\"`\n\tThresholdUp   int    `json:\"threshold_up,omitempty\"`\n\tThresholdDown int    `json:\"threshold_down,omitempty\"`\n}\n\n\/\/ LoadBalancerListener represents a listener on a LoadBalancer\ntype LoadBalancerListener struct {\n\tProtocol      string `json:\"protocol,omitempty\"`\n\tIn            int    `json:\"in,omitempty\"`\n\tOut           int    `json:\"out,omitempty\"`\n\tTimeout       int    `json:\"timeout,omitempty\"`\n\tProxyProtocol string `json:\"proxy_protocol,omitempty\"`\n}\n\n\/\/ LoadBalancerOptions is used in conjunction with CreateLoadBalancer and\n\/\/ UpdateLoadBalancer to create and update load balancers\ntype LoadBalancerOptions struct {\n\tId                    string                   `json:\"-\"`\n\tName                  *string                  `json:\"name,omitempty\"`\n\tNodes                 []LoadBalancerNode       `json:\"nodes,omitempty\"`\n\tPolicy                *string                  `json:\"policy,omitempty\"`\n\tBufferSize            *int                     `json:\"buffer_size,omitempty\"`\n\tListeners             []LoadBalancerListener   `json:\"listeners,omitempty\"`\n\tHealthcheck           *LoadBalancerHealthcheck `json:\"healthcheck,omitempty\"`\n\tDomains               []string                 `json:\"domains,omitempty\"`\n\tCertificatePem        *string                  `json:\"certificate_pem,omitempty\"`\n\tCertificatePrivateKey *string                  `json:\"certificate_private_key,omitempty\"`\n\tSslV3                 *bool                    `json:\"sslv3,omitempty\"`\n}\n\n\/\/ LoadBalancerNode is used in conjunction with LoadBalancerOptions,\n\/\/ AddNodesToLoadBalancer, RemoveNodesFromLoadBalancer to specify a list of\n\/\/ servers to use as load balancer nodes. The Node parameter should be a server\n\/\/ identifier.\ntype LoadBalancerNode struct {\n\tNode string `json:\"node\"`\n}\n\n\/\/ LoadBalancers retrieves a list of all load balancers\nfunc (c *Client) LoadBalancers() ([]LoadBalancer, error) {\n\tvar lbs []LoadBalancer\n\t_, err := c.MakeApiRequest(\"GET\", \"\/1.0\/load_balancers\", nil, &lbs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lbs, err\n}\n\n\/\/ LoadBalancer retrieves a detailed view of one load balancer\nfunc (c *Client) LoadBalancer(identifier string) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"GET\", \"\/1.0\/load_balancers\/\"+identifier, nil, lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, err\n}\n\n\/\/ CreateLoadBalancer creates a new load balancer.\n\/\/\n\/\/ It takes a LoadBalancerOptions struct for specifying name and other\n\/\/ attributes.  Not all attributes can be specified at create time (such as Id,\n\/\/ which is allocated for you)\nfunc (c *Client) CreateLoadBalancer(newLB *LoadBalancerOptions) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"POST\", \"\/1.0\/load_balancers\", newLB, &lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, nil\n}\n\n\/\/ UpdateLoadBalancer updates an existing load balancer.\n\/\/\n\/\/ It takes a LoadBalancerOptions struct for specifying name and other\n\/\/ attributes. Provide the identifier using the Id attribute.\nfunc (c *Client) UpdateLoadBalancer(newLB *LoadBalancerOptions) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"PUT\", \"\/1.0\/load_balancers\/\"+newLB.Id, newLB, &lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, nil\n}\n\n\/\/ DestroyLoadBalancer issues a request to destroy the load balancer\nfunc (c *Client) DestroyLoadBalancer(identifier string) error {\n\t_, err := c.MakeApiRequest(\"DELETE\", \"\/1.0\/load_balancers\/\"+identifier, nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ AddNodesToLoadBalancer adds nodes to an existing load balancer.\nfunc (c *Client) AddNodesToLoadBalancer(loadBalancerID string, nodes []LoadBalancerNode) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"POST\", \"\/1.0\/load_balancers\/\"+loadBalancerID+\"\/add_nodes\", nodes, &lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, nil\n}\n\n\/\/ RemoveNodesFromLoadBalancer removes nodes from an existing load balancer.\nfunc (c *Client) RemoveNodesFromLoadBalancer(loadBalancerID string, nodes []LoadBalancerNode) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"POST\", \"\/1.0\/load_balancers\/\"+loadBalancerID+\"\/remove_nodes\", nodes, &lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, nil\n}\n\n\/\/ AddListenersToLoadBalancer adds listeners to an existing load balancer.\nfunc (c *Client) AddListenersToLoadBalancer(loadBalancerID string, listeners []LoadBalancerListener) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"POST\", \"\/1.0\/load_balancers\/\"+loadBalancerID+\"\/add_listeners\", listeners, &lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, nil\n}\n\n\/\/ RemoveListenersFromLoadBalancer removes listeners to an existing load balancer.\nfunc (c *Client) RemoveListenersFromLoadBalancer(loadBalancerID string, listeners []LoadBalancerListener) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"POST\", \"\/1.0\/load_balancers\/\"+loadBalancerID+\"\/remove_listeners\", listeners, &lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, nil\n}\n<commit_msg>Add HttpsRedirect to Loadbalancer Options<commit_after>package brightbox\n\nimport (\n\t\"time\"\n)\n\n\/\/ LoadBalancer represents a Load Balancer\n\/\/ https:\/\/api.gb1.brightbox.com\/1.0\/#load_balancer\ntype LoadBalancer struct {\n\tId            string\n\tName          string\n\tStatus        string\n\tCreatedAt     *time.Time `json:\"created_at\"`\n\tDeletedAt     *time.Time `json:\"deleted_at\"`\n\tLocked        bool\n\tHttpsRedirect bool `json:\"https_redirect\"`\n\tAccount       Account\n\tNodes         []Server\n\tCloudIPs      []CloudIP `json:\"cloud_ips\"`\n\tPolicy        string\n\tBufferSize    int `json:\"buffer_size\"`\n\tListeners     []LoadBalancerListener\n\tHealthcheck   LoadBalancerHealthcheck\n\tCertificate   *LoadBalancerCertificate\n\tAcme          *LoadBalancerAcme\n}\n\n\/\/ LoadBalancerCertificate represents a certificate on a LoadBalancer\ntype LoadBalancerCertificate struct {\n\tExpiresAt time.Time `json:\"expires_at\"`\n\tValidFrom time.Time `json:\"valid_from\"`\n\tSslV3     bool      `json:\"sslv3\"`\n\tIssuer    string    `json:\"issuer\"`\n\tSubject   string    `json:\"subject\"`\n}\n\n\/\/ LoadBalancerAcme represents an ACME object on a LoadBalancer\ntype LoadBalancerAcme struct {\n\tCertificate *LoadBalancerAcmeCertificate `json:\"certificate\"`\n\tDomains     []LoadBalancerAcmeDomain     `json:domains\"`\n}\n\n\/\/ LoadBalancerAcmeCertificate represents an ACME issued certificate on\n\/\/ a LoadBalancer\ntype LoadBalancerAcmeCertificate struct {\n\tFingerprint string    `json:\"fingerprint\"`\n\tExpiresAt   time.Time `json:\"expires_at\"`\n\tIssuedAt    time.Time `json:\"issued_at\"`\n}\n\n\/\/ LoadBalancerAcmeDomains represents a domain for which ACME support\n\/\/ has been requested\ntype LoadBalancerAcmeDomain struct {\n\tIdentifier  string `json:\"identifier\"`\n\tStatus      string `json:\"status\"`\n\tLastMessage string `json:\"last_message\"`\n}\n\n\/\/ LoadBalancerHealthcheck represents a health check on a LoadBalancer\ntype LoadBalancerHealthcheck struct {\n\tType          string `json:\"type\"`\n\tPort          int    `json:\"port\"`\n\tRequest       string `json:\"request,omitempty\"`\n\tInterval      int    `json:\"interval,omitempty\"`\n\tTimeout       int    `json:\"timeout,omitempty\"`\n\tThresholdUp   int    `json:\"threshold_up,omitempty\"`\n\tThresholdDown int    `json:\"threshold_down,omitempty\"`\n}\n\n\/\/ LoadBalancerListener represents a listener on a LoadBalancer\ntype LoadBalancerListener struct {\n\tProtocol      string `json:\"protocol,omitempty\"`\n\tIn            int    `json:\"in,omitempty\"`\n\tOut           int    `json:\"out,omitempty\"`\n\tTimeout       int    `json:\"timeout,omitempty\"`\n\tProxyProtocol string `json:\"proxy_protocol,omitempty\"`\n}\n\n\/\/ LoadBalancerOptions is used in conjunction with CreateLoadBalancer and\n\/\/ UpdateLoadBalancer to create and update load balancers\ntype LoadBalancerOptions struct {\n\tId                    string                   `json:\"-\"`\n\tName                  *string                  `json:\"name,omitempty\"`\n\tNodes                 []LoadBalancerNode       `json:\"nodes,omitempty\"`\n\tPolicy                *string                  `json:\"policy,omitempty\"`\n\tBufferSize            *int                     `json:\"buffer_size,omitempty\"`\n\tListeners             []LoadBalancerListener   `json:\"listeners,omitempty\"`\n\tHealthcheck           *LoadBalancerHealthcheck `json:\"healthcheck,omitempty\"`\n\tDomains               []string                 `json:\"domains,omitempty\"`\n\tCertificatePem        *string                  `json:\"certificate_pem,omitempty\"`\n\tCertificatePrivateKey *string                  `json:\"certificate_private_key,omitempty\"`\n\tSslV3                 *bool                    `json:\"sslv3,omitempty\"`\n\tHttpsRedirect         *bool                    `json:\"https_redirect,omitempty\"`\n}\n\n\/\/ LoadBalancerNode is used in conjunction with LoadBalancerOptions,\n\/\/ AddNodesToLoadBalancer, RemoveNodesFromLoadBalancer to specify a list of\n\/\/ servers to use as load balancer nodes. The Node parameter should be a server\n\/\/ identifier.\ntype LoadBalancerNode struct {\n\tNode string `json:\"node\"`\n}\n\n\/\/ LoadBalancers retrieves a list of all load balancers\nfunc (c *Client) LoadBalancers() ([]LoadBalancer, error) {\n\tvar lbs []LoadBalancer\n\t_, err := c.MakeApiRequest(\"GET\", \"\/1.0\/load_balancers\", nil, &lbs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lbs, err\n}\n\n\/\/ LoadBalancer retrieves a detailed view of one load balancer\nfunc (c *Client) LoadBalancer(identifier string) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"GET\", \"\/1.0\/load_balancers\/\"+identifier, nil, lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, err\n}\n\n\/\/ CreateLoadBalancer creates a new load balancer.\n\/\/\n\/\/ It takes a LoadBalancerOptions struct for specifying name and other\n\/\/ attributes.  Not all attributes can be specified at create time (such as Id,\n\/\/ which is allocated for you)\nfunc (c *Client) CreateLoadBalancer(newLB *LoadBalancerOptions) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"POST\", \"\/1.0\/load_balancers\", newLB, &lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, nil\n}\n\n\/\/ UpdateLoadBalancer updates an existing load balancer.\n\/\/\n\/\/ It takes a LoadBalancerOptions struct for specifying name and other\n\/\/ attributes. Provide the identifier using the Id attribute.\nfunc (c *Client) UpdateLoadBalancer(newLB *LoadBalancerOptions) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"PUT\", \"\/1.0\/load_balancers\/\"+newLB.Id, newLB, &lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, nil\n}\n\n\/\/ DestroyLoadBalancer issues a request to destroy the load balancer\nfunc (c *Client) DestroyLoadBalancer(identifier string) error {\n\t_, err := c.MakeApiRequest(\"DELETE\", \"\/1.0\/load_balancers\/\"+identifier, nil, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ AddNodesToLoadBalancer adds nodes to an existing load balancer.\nfunc (c *Client) AddNodesToLoadBalancer(loadBalancerID string, nodes []LoadBalancerNode) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"POST\", \"\/1.0\/load_balancers\/\"+loadBalancerID+\"\/add_nodes\", nodes, &lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, nil\n}\n\n\/\/ RemoveNodesFromLoadBalancer removes nodes from an existing load balancer.\nfunc (c *Client) RemoveNodesFromLoadBalancer(loadBalancerID string, nodes []LoadBalancerNode) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"POST\", \"\/1.0\/load_balancers\/\"+loadBalancerID+\"\/remove_nodes\", nodes, &lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, nil\n}\n\n\/\/ AddListenersToLoadBalancer adds listeners to an existing load balancer.\nfunc (c *Client) AddListenersToLoadBalancer(loadBalancerID string, listeners []LoadBalancerListener) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"POST\", \"\/1.0\/load_balancers\/\"+loadBalancerID+\"\/add_listeners\", listeners, &lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, nil\n}\n\n\/\/ RemoveListenersFromLoadBalancer removes listeners to an existing load balancer.\nfunc (c *Client) RemoveListenersFromLoadBalancer(loadBalancerID string, listeners []LoadBalancerListener) (*LoadBalancer, error) {\n\tlb := new(LoadBalancer)\n\t_, err := c.MakeApiRequest(\"POST\", \"\/1.0\/load_balancers\/\"+loadBalancerID+\"\/remove_listeners\", listeners, &lb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lb, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 bs authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage metric\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"time\"\n\n\tstatsdClient \"github.com\/quipo\/statsd\"\n)\n\nfunc newStatsd() statter {\n\tvar (\n\t\tdefaultPrefix string = \"\"\n\t\tdefaultPort   string = \"8125\"\n\t\tdefaultHost   string = \"localhost\"\n\t)\n\tprefix := os.Getenv(\"METRICS_STATSD_CLIENT\")\n\tif prefix == \"\" {\n\t\tprefix = defaultPrefix\n\t}\n\tport := os.Getenv(\"METRICS_STATSD_PORT\")\n\tif port == \"\" {\n\t\tport = defaultPort\n\t}\n\thost := os.Getenv(\"METRICS_STATSD_HOST\")\n\tif host == \"\" {\n\t\thost = defaultHost\n\t}\n\treturn &statsd{\n\t\tHost:   host,\n\t\tPort:   port,\n\t\tPrefix: prefix,\n\t}\n}\n\ntype statsd struct {\n\tHost   string\n\tPort   string\n\tPrefix string\n}\n\nfunc (s *statsd) Send(app, hostname, key, value string) error {\n\tprefix := fmt.Sprintf(\"%stsuru.app.host\", s.Prefix)\n\tclient := statsdClient.NewStatsdClient(net.JoinHostPort(s.Host, s.Port), prefix)\n\tclient.CreateSocket()\n\tinterval := time.Second * 2\n\tstats := statsdClient.NewStatsdBuffer(interval, client)\n\terr := stats.Gauge(key, 0.0)\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] unable to send metrics to statsd via UDP: %s\", err)\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>metrics: fix environ name<commit_after>\/\/ Copyright 2015 bs authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage metric\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"time\"\n\n\tstatsdClient \"github.com\/quipo\/statsd\"\n)\n\nfunc newStatsd() statter {\n\tvar (\n\t\tdefaultPrefix string = \"\"\n\t\tdefaultPort   string = \"8125\"\n\t\tdefaultHost   string = \"localhost\"\n\t)\n\tprefix := os.Getenv(\"METRICS_STATSD_PREFIX\")\n\tif prefix == \"\" {\n\t\tprefix = defaultPrefix\n\t}\n\tport := os.Getenv(\"METRICS_STATSD_PORT\")\n\tif port == \"\" {\n\t\tport = defaultPort\n\t}\n\thost := os.Getenv(\"METRICS_STATSD_HOST\")\n\tif host == \"\" {\n\t\thost = defaultHost\n\t}\n\treturn &statsd{\n\t\tHost:   host,\n\t\tPort:   port,\n\t\tPrefix: prefix,\n\t}\n}\n\ntype statsd struct {\n\tHost   string\n\tPort   string\n\tPrefix string\n}\n\nfunc (s *statsd) Send(app, hostname, key, value string) error {\n\tprefix := fmt.Sprintf(\"%stsuru.app.host\", s.Prefix)\n\tclient := statsdClient.NewStatsdClient(net.JoinHostPort(s.Host, s.Port), prefix)\n\tclient.CreateSocket()\n\tinterval := time.Second * 2\n\tstats := statsdClient.NewStatsdBuffer(interval, client)\n\terr := stats.Gauge(key, 0.0)\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] unable to send metrics to statsd via UDP: %s\", err)\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package connection\n\nimport (\n\t\"testing\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc TestParse(t *testing.T) {\n\tConvey(\"Check connection\", t, func() {\n\t\tdb := MustGet()\n\t\tSo(db, ShouldNotBeNil)\n\t\terr := db.Ping()\n\t\tSo(err, ShouldBeNil)\n\t})\n}\n<commit_msg>rename test to a better name<commit_after>package connection\n\nimport (\n\t\"testing\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc TestMustGet(t *testing.T) {\n\tConvey(\"Check connection\", t, func() {\n\t\tdb := MustGet()\n\t\tSo(db, ShouldNotBeNil)\n\t\terr := db.Ping()\n\t\tSo(err, ShouldBeNil)\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package commands\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\tbstore \"github.com\/ipfs\/go-ipfs\/blocks\/blockstore\"\n\tcmds \"github.com\/ipfs\/go-ipfs\/commands\"\n\tcorerepo \"github.com\/ipfs\/go-ipfs\/core\/corerepo\"\n\tconfig \"github.com\/ipfs\/go-ipfs\/repo\/config\"\n\tfsrepo \"github.com\/ipfs\/go-ipfs\/repo\/fsrepo\"\n\tlockfile \"github.com\/ipfs\/go-ipfs\/repo\/fsrepo\/lock\"\n\n\tu \"gx\/ipfs\/QmWbjfz3u6HkAdPh34dgPchGbQjob6LXLhAeCGii2TX69n\/go-ipfs-util\"\n\tcid \"gx\/ipfs\/QmYhQaCYEcaPPjxJX7YcPcVKkQfRy6sJ7B3XmGFk82XYdQ\/go-cid\"\n)\n\ntype RepoVersion struct {\n\tVersion string\n}\n\nvar RepoCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Manipulate the IPFS repo.\",\n\t\tShortDescription: `\n'ipfs repo' is a plumbing command used to manipulate the repo.\n`,\n\t},\n\n\tSubcommands: map[string]*cmds.Command{\n\t\t\"gc\":      repoGcCmd,\n\t\t\"stat\":    repoStatCmd,\n\t\t\"fsck\":    RepoFsckCmd,\n\t\t\"version\": repoVersionCmd,\n\t\t\"verify\":  repoVerifyCmd,\n\t},\n}\n\n\/\/ GcResult is the result returned by \"repo gc\" command.\ntype GcResult struct {\n\tKey   *cid.Cid\n\tError string `json:\",omitempty\"`\n}\n\nvar repoGcCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Perform a garbage collection sweep on the repo.\",\n\t\tShortDescription: `\n'ipfs repo gc' is a plumbing command that will sweep the local\nset of stored objects and remove ones that are not pinned in\norder to reclaim hard disk space.\n`,\n\t},\n\tOptions: []cmds.Option{\n\t\tcmds.BoolOption(\"quiet\", \"q\", \"Write minimal output.\").Default(false),\n\t\tcmds.BoolOption(\"stream-errors\", \"Stream errors.\").Default(false),\n\t},\n\tRun: func(req cmds.Request, res cmds.Response) {\n\t\tn, err := req.InvocContext().GetNode()\n\t\tif err != nil {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\n\t\tstreamErrors, _, _ := res.Request().Option(\"stream-errors\").Bool()\n\n\t\tgcOutChan := corerepo.GarbageCollectAsync(n, req.Context())\n\n\t\toutChan := make(chan interface{}, cap(gcOutChan))\n\t\tres.SetOutput((<-chan interface{})(outChan))\n\n\t\tgo func() {\n\t\t\tdefer close(outChan)\n\t\t\tif streamErrors {\n\t\t\t\terrs := false\n\t\t\t\tfor res := range gcOutChan {\n\t\t\t\t\tif res.Error != nil {\n\t\t\t\t\t\toutChan <- &GcResult{Error: res.Error.Error()}\n\t\t\t\t\t\terrs = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\toutChan <- &GcResult{Key: res.KeyRemoved}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif errs {\n\t\t\t\t\tres.SetError(fmt.Errorf(\"encountered errors during gc run\"), cmds.ErrNormal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr := corerepo.CollectResult(req.Context(), gcOutChan, func(k *cid.Cid) {\n\t\t\t\t\toutChan <- &GcResult{Key: k}\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t},\n\tType: GcResult{},\n\tMarshalers: cmds.MarshalerMap{\n\t\tcmds.Text: func(res cmds.Response) (io.Reader, error) {\n\t\t\toutChan, ok := res.Output().(<-chan interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil, u.ErrCast()\n\t\t\t}\n\n\t\t\tquiet, _, err := res.Request().Option(\"quiet\").Bool()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tmarshal := func(v interface{}) (io.Reader, error) {\n\t\t\t\tobj, ok := v.(*GcResult)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, u.ErrCast()\n\t\t\t\t}\n\n\t\t\t\tif obj.Error != \"\" {\n\t\t\t\t\tfmt.Fprintf(res.Stderr(), \"Error: %s\\n\", obj.Error)\n\t\t\t\t\treturn nil, nil\n\t\t\t\t}\n\n\t\t\t\tif quiet {\n\t\t\t\t\treturn bytes.NewBufferString(obj.Key.String() + \"\\n\"), nil\n\t\t\t\t} else {\n\t\t\t\t\treturn bytes.NewBufferString(fmt.Sprintf(\"removed %s\\n\", obj.Key)), nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn &cmds.ChannelMarshaler{\n\t\t\t\tChannel:   outChan,\n\t\t\t\tMarshaler: marshal,\n\t\t\t\tRes:       res,\n\t\t\t}, nil\n\t\t},\n\t},\n}\n\nvar repoStatCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Get stats for the currently used repo.\",\n\t\tShortDescription: `\n'ipfs repo stat' is a plumbing command that will scan the local\nset of stored objects and print repo statistics. It outputs to stdout:\nNumObjects      int Number of objects in the local repo.\nRepoPath        string The path to the repo being currently used.\nRepoSize        int Size in bytes that the repo is currently taking.\nVersion         string The repo version.\n`,\n\t},\n\tRun: func(req cmds.Request, res cmds.Response) {\n\t\tn, err := req.InvocContext().GetNode()\n\t\tif err != nil {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\n\t\tstat, err := corerepo.RepoStat(n, req.Context())\n\t\tif err != nil {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\n\t\tres.SetOutput(stat)\n\t},\n\tOptions: []cmds.Option{\n\t\tcmds.BoolOption(\"human\", \"Output RepoSize in MiB.\").Default(false),\n\t},\n\tType: corerepo.Stat{},\n\tMarshalers: cmds.MarshalerMap{\n\t\tcmds.Text: func(res cmds.Response) (io.Reader, error) {\n\t\t\tstat, ok := res.Output().(*corerepo.Stat)\n\t\t\tif !ok {\n\t\t\t\treturn nil, u.ErrCast()\n\t\t\t}\n\n\t\t\thuman, _, err := res.Request().Option(\"human\").Bool()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\tfmt.Fprintf(buf, \"NumObjects \\t %d\\n\", stat.NumObjects)\n\t\t\tsizeInMiB := stat.RepoSize \/ (1024 * 1024)\n\t\t\tif human && sizeInMiB > 0 {\n\t\t\t\tfmt.Fprintf(buf, \"RepoSize (MiB) \\t %d\\n\", sizeInMiB)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(buf, \"RepoSize \\t %d\\n\", stat.RepoSize)\n\t\t\t}\n\t\t\tmaxSizeInMiB := stat.StorageMax \/ (1024 * 1024)\n\t\t\tif human && maxSizeInMiB > 0 {\n\t\t\t\tfmt.Fprintf(buf, \"StorageMax (MiB) \\t %d\\n\", maxSizeInMiB)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(buf, \"StorageMax \\t %d\\n\", stat.StorageMax)\n\t\t\t}\n\t\t\tfmt.Fprintf(buf, \"RepoPath \\t %s\\n\", stat.RepoPath)\n\t\t\tfmt.Fprintf(buf, \"Version \\t %s\\n\", stat.Version)\n\n\t\t\treturn buf, nil\n\t\t},\n\t},\n}\n\nvar RepoFsckCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Remove repo lockfiles.\",\n\t\tShortDescription: `\n'ipfs repo fsck' is a plumbing command that will remove repo and level db\nlockfiles, as well as the api file. This command can only run when no ipfs\ndaemons are running.\n`,\n\t},\n\tRun: func(req cmds.Request, res cmds.Response) {\n\t\tconfigRoot := req.InvocContext().ConfigRoot\n\n\t\tdsPath, err := config.DataStorePath(configRoot)\n\t\tif err != nil {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\n\t\tdsLockFile := filepath.Join(dsPath, \"LOCK\") \/\/ TODO: get this lockfile programmatically\n\t\trepoLockFile := filepath.Join(configRoot, lockfile.LockFile)\n\t\tapiFile := filepath.Join(configRoot, \"api\") \/\/ TODO: get this programmatically\n\n\t\tlog.Infof(\"Removing repo lockfile: %s\", repoLockFile)\n\t\tlog.Infof(\"Removing datastore lockfile: %s\", dsLockFile)\n\t\tlog.Infof(\"Removing api file: %s\", apiFile)\n\n\t\terr = os.Remove(repoLockFile)\n\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\t\terr = os.Remove(dsLockFile)\n\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\t\terr = os.Remove(apiFile)\n\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\n\t\tres.SetOutput(&MessageOutput{\"Lockfiles have been removed.\\n\"})\n\t},\n\tType: MessageOutput{},\n\tMarshalers: cmds.MarshalerMap{\n\t\tcmds.Text: MessageTextMarshaler,\n\t},\n}\n\ntype VerifyProgress struct {\n\tMessage  string\n\tProgress int\n}\n\nvar repoVerifyCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Verify all blocks in repo are not corrupted.\",\n\t},\n\tRun: func(req cmds.Request, res cmds.Response) {\n\t\tnd, err := req.InvocContext().GetNode()\n\t\tif err != nil {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\n\t\tout := make(chan interface{})\n\t\tgo func() {\n\t\t\tdefer close(out)\n\t\t\tbs := bstore.NewBlockstore(nd.Repo.Datastore())\n\n\t\t\tbs.HashOnRead(true)\n\n\t\t\tkeys, err := bs.AllKeysChan(req.Context())\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar fails int\n\t\t\tvar i int\n\t\t\tfor k := range keys {\n\t\t\t\t_, err := bs.Get(k)\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &VerifyProgress{\n\t\t\t\t\t\tMessage: fmt.Sprintf(\"block %s was corrupt (%s)\", k, err),\n\t\t\t\t\t}\n\t\t\t\t\tfails++\n\t\t\t\t}\n\t\t\t\ti++\n\t\t\t\tout <- &VerifyProgress{Progress: i}\n\t\t\t}\n\t\t\tif fails == 0 {\n\t\t\t\tout <- &VerifyProgress{Message: \"verify complete, all blocks validated.\"}\n\t\t\t} else {\n\t\t\t\tout <- &VerifyProgress{Message: \"verify complete, some blocks were corrupt.\"}\n\t\t\t}\n\t\t}()\n\n\t\tres.SetOutput((<-chan interface{})(out))\n\t},\n\tType: VerifyProgress{},\n\tMarshalers: cmds.MarshalerMap{\n\t\tcmds.Text: func(res cmds.Response) (io.Reader, error) {\n\t\t\tout := res.Output().(<-chan interface{})\n\n\t\t\tmarshal := func(v interface{}) (io.Reader, error) {\n\t\t\t\tobj, ok := v.(*VerifyProgress)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, u.ErrCast()\n\t\t\t\t}\n\n\t\t\t\tbuf := new(bytes.Buffer)\n\t\t\t\tif obj.Message != \"\" {\n\t\t\t\t\tif strings.Contains(obj.Message, \"blocks were corrupt\") {\n\t\t\t\t\t\treturn nil, fmt.Errorf(obj.Message)\n\t\t\t\t\t}\n\t\t\t\t\tif len(obj.Message) < 20 {\n\t\t\t\t\t\tobj.Message += \"             \"\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Fprintln(buf, obj.Message)\n\t\t\t\t\treturn buf, nil\n\t\t\t\t}\n\n\t\t\t\tfmt.Fprintf(buf, \"%d blocks processed.\\r\", obj.Progress)\n\t\t\t\treturn buf, nil\n\t\t\t}\n\n\t\t\treturn &cmds.ChannelMarshaler{\n\t\t\t\tChannel:   out,\n\t\t\t\tMarshaler: marshal,\n\t\t\t\tRes:       res,\n\t\t\t}, nil\n\t\t},\n\t},\n}\n\nvar repoVersionCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Show the repo version.\",\n\t\tShortDescription: `\n'ipfs repo version' returns the current repo version.\n`,\n\t},\n\n\tOptions: []cmds.Option{\n\t\tcmds.BoolOption(\"quiet\", \"q\", \"Write minimal output.\"),\n\t},\n\tRun: func(req cmds.Request, res cmds.Response) {\n\t\tres.SetOutput(&RepoVersion{\n\t\t\tVersion: fmt.Sprint(fsrepo.RepoVersion),\n\t\t})\n\t},\n\tType: RepoVersion{},\n\tMarshalers: cmds.MarshalerMap{\n\t\tcmds.Text: func(res cmds.Response) (io.Reader, error) {\n\t\t\tresponse := res.Output().(*RepoVersion)\n\n\t\t\tquiet, _, err := res.Request().Option(\"quiet\").Bool()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\tif quiet {\n\t\t\t\tbuf = bytes.NewBufferString(fmt.Sprintf(\"fs-repo@%s\\n\", response.Version))\n\t\t\t} else {\n\t\t\t\tbuf = bytes.NewBufferString(fmt.Sprintf(\"ipfs repo version fs-repo@%s\\n\", response.Version))\n\t\t\t}\n\t\t\treturn buf, nil\n\n\t\t},\n\t},\n}\n<commit_msg>Use tabwritter for better formatted output.<commit_after>package commands\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\n\tbstore \"github.com\/ipfs\/go-ipfs\/blocks\/blockstore\"\n\tcmds \"github.com\/ipfs\/go-ipfs\/commands\"\n\tcorerepo \"github.com\/ipfs\/go-ipfs\/core\/corerepo\"\n\tconfig \"github.com\/ipfs\/go-ipfs\/repo\/config\"\n\tfsrepo \"github.com\/ipfs\/go-ipfs\/repo\/fsrepo\"\n\tlockfile \"github.com\/ipfs\/go-ipfs\/repo\/fsrepo\/lock\"\n\n\tu \"gx\/ipfs\/QmWbjfz3u6HkAdPh34dgPchGbQjob6LXLhAeCGii2TX69n\/go-ipfs-util\"\n\tcid \"gx\/ipfs\/QmYhQaCYEcaPPjxJX7YcPcVKkQfRy6sJ7B3XmGFk82XYdQ\/go-cid\"\n)\n\ntype RepoVersion struct {\n\tVersion string\n}\n\nvar RepoCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Manipulate the IPFS repo.\",\n\t\tShortDescription: `\n'ipfs repo' is a plumbing command used to manipulate the repo.\n`,\n\t},\n\n\tSubcommands: map[string]*cmds.Command{\n\t\t\"gc\":      repoGcCmd,\n\t\t\"stat\":    repoStatCmd,\n\t\t\"fsck\":    RepoFsckCmd,\n\t\t\"version\": repoVersionCmd,\n\t\t\"verify\":  repoVerifyCmd,\n\t},\n}\n\n\/\/ GcResult is the result returned by \"repo gc\" command.\ntype GcResult struct {\n\tKey   *cid.Cid\n\tError string `json:\",omitempty\"`\n}\n\nvar repoGcCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Perform a garbage collection sweep on the repo.\",\n\t\tShortDescription: `\n'ipfs repo gc' is a plumbing command that will sweep the local\nset of stored objects and remove ones that are not pinned in\norder to reclaim hard disk space.\n`,\n\t},\n\tOptions: []cmds.Option{\n\t\tcmds.BoolOption(\"quiet\", \"q\", \"Write minimal output.\").Default(false),\n\t\tcmds.BoolOption(\"stream-errors\", \"Stream errors.\").Default(false),\n\t},\n\tRun: func(req cmds.Request, res cmds.Response) {\n\t\tn, err := req.InvocContext().GetNode()\n\t\tif err != nil {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\n\t\tstreamErrors, _, _ := res.Request().Option(\"stream-errors\").Bool()\n\n\t\tgcOutChan := corerepo.GarbageCollectAsync(n, req.Context())\n\n\t\toutChan := make(chan interface{}, cap(gcOutChan))\n\t\tres.SetOutput((<-chan interface{})(outChan))\n\n\t\tgo func() {\n\t\t\tdefer close(outChan)\n\t\t\tif streamErrors {\n\t\t\t\terrs := false\n\t\t\t\tfor res := range gcOutChan {\n\t\t\t\t\tif res.Error != nil {\n\t\t\t\t\t\toutChan <- &GcResult{Error: res.Error.Error()}\n\t\t\t\t\t\terrs = true\n\t\t\t\t\t} else {\n\t\t\t\t\t\toutChan <- &GcResult{Key: res.KeyRemoved}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif errs {\n\t\t\t\t\tres.SetError(fmt.Errorf(\"encountered errors during gc run\"), cmds.ErrNormal)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr := corerepo.CollectResult(req.Context(), gcOutChan, func(k *cid.Cid) {\n\t\t\t\t\toutChan <- &GcResult{Key: k}\n\t\t\t\t})\n\t\t\t\tif err != nil {\n\t\t\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t},\n\tType: GcResult{},\n\tMarshalers: cmds.MarshalerMap{\n\t\tcmds.Text: func(res cmds.Response) (io.Reader, error) {\n\t\t\toutChan, ok := res.Output().(<-chan interface{})\n\t\t\tif !ok {\n\t\t\t\treturn nil, u.ErrCast()\n\t\t\t}\n\n\t\t\tquiet, _, err := res.Request().Option(\"quiet\").Bool()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tmarshal := func(v interface{}) (io.Reader, error) {\n\t\t\t\tobj, ok := v.(*GcResult)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, u.ErrCast()\n\t\t\t\t}\n\n\t\t\t\tif obj.Error != \"\" {\n\t\t\t\t\tfmt.Fprintf(res.Stderr(), \"Error: %s\\n\", obj.Error)\n\t\t\t\t\treturn nil, nil\n\t\t\t\t}\n\n\t\t\t\tif quiet {\n\t\t\t\t\treturn bytes.NewBufferString(obj.Key.String() + \"\\n\"), nil\n\t\t\t\t} else {\n\t\t\t\t\treturn bytes.NewBufferString(fmt.Sprintf(\"removed %s\\n\", obj.Key)), nil\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn &cmds.ChannelMarshaler{\n\t\t\t\tChannel:   outChan,\n\t\t\t\tMarshaler: marshal,\n\t\t\t\tRes:       res,\n\t\t\t}, nil\n\t\t},\n\t},\n}\n\nvar repoStatCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Get stats for the currently used repo.\",\n\t\tShortDescription: `\n'ipfs repo stat' is a plumbing command that will scan the local\nset of stored objects and print repo statistics. It outputs to stdout:\nNumObjects      int Number of objects in the local repo.\nRepoPath        string The path to the repo being currently used.\nRepoSize        int Size in bytes that the repo is currently taking.\nVersion         string The repo version.\n`,\n\t},\n\tRun: func(req cmds.Request, res cmds.Response) {\n\t\tn, err := req.InvocContext().GetNode()\n\t\tif err != nil {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\n\t\tstat, err := corerepo.RepoStat(n, req.Context())\n\t\tif err != nil {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\n\t\tres.SetOutput(stat)\n\t},\n\tOptions: []cmds.Option{\n\t\tcmds.BoolOption(\"human\", \"Output RepoSize in MiB.\").Default(false),\n\t},\n\tType: corerepo.Stat{},\n\tMarshalers: cmds.MarshalerMap{\n\t\tcmds.Text: func(res cmds.Response) (io.Reader, error) {\n\t\t\tstat, ok := res.Output().(*corerepo.Stat)\n\t\t\tif !ok {\n\t\t\t\treturn nil, u.ErrCast()\n\t\t\t}\n\n\t\t\thuman, _, err := res.Request().Option(\"human\").Bool()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\twtr := tabwriter.NewWriter(buf, 0, 0, 1, ' ', 0)\n\t\t\tfmt.Fprintf(wtr, \"NumObjects:\\t%d\\n\", stat.NumObjects)\n\t\t\tsizeInMiB := stat.RepoSize \/ (1024 * 1024)\n\t\t\tif human && sizeInMiB > 0 {\n\t\t\t\tfmt.Fprintf(wtr, \"RepoSize (MiB):\\t%d\\n\", sizeInMiB)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(wtr, \"RepoSize:\\t%d\\n\", stat.RepoSize)\n\t\t\t}\n\t\t\tmaxSizeInMiB := stat.StorageMax \/ (1024 * 1024)\n\t\t\tif human && maxSizeInMiB > 0 {\n\t\t\t\tfmt.Fprintf(wtr, \"StorageMax (MiB):\\t%d\\n\", maxSizeInMiB)\n\t\t\t} else {\n\t\t\t\tfmt.Fprintf(wtr, \"StorageMax:\\t%d\\n\", stat.StorageMax)\n\t\t\t}\n\t\t\tfmt.Fprintf(wtr, \"RepoPath:\\t%s\\n\", stat.RepoPath)\n\t\t\tfmt.Fprintf(wtr, \"Version:\\t%s\\n\", stat.Version)\n\t\t\twtr.Flush()\n\n\t\t\treturn buf, nil\n\t\t},\n\t},\n}\n\nvar RepoFsckCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Remove repo lockfiles.\",\n\t\tShortDescription: `\n'ipfs repo fsck' is a plumbing command that will remove repo and level db\nlockfiles, as well as the api file. This command can only run when no ipfs\ndaemons are running.\n`,\n\t},\n\tRun: func(req cmds.Request, res cmds.Response) {\n\t\tconfigRoot := req.InvocContext().ConfigRoot\n\n\t\tdsPath, err := config.DataStorePath(configRoot)\n\t\tif err != nil {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\n\t\tdsLockFile := filepath.Join(dsPath, \"LOCK\") \/\/ TODO: get this lockfile programmatically\n\t\trepoLockFile := filepath.Join(configRoot, lockfile.LockFile)\n\t\tapiFile := filepath.Join(configRoot, \"api\") \/\/ TODO: get this programmatically\n\n\t\tlog.Infof(\"Removing repo lockfile: %s\", repoLockFile)\n\t\tlog.Infof(\"Removing datastore lockfile: %s\", dsLockFile)\n\t\tlog.Infof(\"Removing api file: %s\", apiFile)\n\n\t\terr = os.Remove(repoLockFile)\n\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\t\terr = os.Remove(dsLockFile)\n\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\t\terr = os.Remove(apiFile)\n\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\n\t\tres.SetOutput(&MessageOutput{\"Lockfiles have been removed.\\n\"})\n\t},\n\tType: MessageOutput{},\n\tMarshalers: cmds.MarshalerMap{\n\t\tcmds.Text: MessageTextMarshaler,\n\t},\n}\n\ntype VerifyProgress struct {\n\tMessage  string\n\tProgress int\n}\n\nvar repoVerifyCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Verify all blocks in repo are not corrupted.\",\n\t},\n\tRun: func(req cmds.Request, res cmds.Response) {\n\t\tnd, err := req.InvocContext().GetNode()\n\t\tif err != nil {\n\t\t\tres.SetError(err, cmds.ErrNormal)\n\t\t\treturn\n\t\t}\n\n\t\tout := make(chan interface{})\n\t\tgo func() {\n\t\t\tdefer close(out)\n\t\t\tbs := bstore.NewBlockstore(nd.Repo.Datastore())\n\n\t\t\tbs.HashOnRead(true)\n\n\t\t\tkeys, err := bs.AllKeysChan(req.Context())\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar fails int\n\t\t\tvar i int\n\t\t\tfor k := range keys {\n\t\t\t\t_, err := bs.Get(k)\n\t\t\t\tif err != nil {\n\t\t\t\t\tout <- &VerifyProgress{\n\t\t\t\t\t\tMessage: fmt.Sprintf(\"block %s was corrupt (%s)\", k, err),\n\t\t\t\t\t}\n\t\t\t\t\tfails++\n\t\t\t\t}\n\t\t\t\ti++\n\t\t\t\tout <- &VerifyProgress{Progress: i}\n\t\t\t}\n\t\t\tif fails == 0 {\n\t\t\t\tout <- &VerifyProgress{Message: \"verify complete, all blocks validated.\"}\n\t\t\t} else {\n\t\t\t\tout <- &VerifyProgress{Message: \"verify complete, some blocks were corrupt.\"}\n\t\t\t}\n\t\t}()\n\n\t\tres.SetOutput((<-chan interface{})(out))\n\t},\n\tType: VerifyProgress{},\n\tMarshalers: cmds.MarshalerMap{\n\t\tcmds.Text: func(res cmds.Response) (io.Reader, error) {\n\t\t\tout := res.Output().(<-chan interface{})\n\n\t\t\tmarshal := func(v interface{}) (io.Reader, error) {\n\t\t\t\tobj, ok := v.(*VerifyProgress)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, u.ErrCast()\n\t\t\t\t}\n\n\t\t\t\tbuf := new(bytes.Buffer)\n\t\t\t\tif obj.Message != \"\" {\n\t\t\t\t\tif strings.Contains(obj.Message, \"blocks were corrupt\") {\n\t\t\t\t\t\treturn nil, fmt.Errorf(obj.Message)\n\t\t\t\t\t}\n\t\t\t\t\tif len(obj.Message) < 20 {\n\t\t\t\t\t\tobj.Message += \"             \"\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Fprintln(buf, obj.Message)\n\t\t\t\t\treturn buf, nil\n\t\t\t\t}\n\n\t\t\t\tfmt.Fprintf(buf, \"%d blocks processed.\\r\", obj.Progress)\n\t\t\t\treturn buf, nil\n\t\t\t}\n\n\t\t\treturn &cmds.ChannelMarshaler{\n\t\t\t\tChannel:   out,\n\t\t\t\tMarshaler: marshal,\n\t\t\t\tRes:       res,\n\t\t\t}, nil\n\t\t},\n\t},\n}\n\nvar repoVersionCmd = &cmds.Command{\n\tHelptext: cmds.HelpText{\n\t\tTagline: \"Show the repo version.\",\n\t\tShortDescription: `\n'ipfs repo version' returns the current repo version.\n`,\n\t},\n\n\tOptions: []cmds.Option{\n\t\tcmds.BoolOption(\"quiet\", \"q\", \"Write minimal output.\"),\n\t},\n\tRun: func(req cmds.Request, res cmds.Response) {\n\t\tres.SetOutput(&RepoVersion{\n\t\t\tVersion: fmt.Sprint(fsrepo.RepoVersion),\n\t\t})\n\t},\n\tType: RepoVersion{},\n\tMarshalers: cmds.MarshalerMap{\n\t\tcmds.Text: func(res cmds.Response) (io.Reader, error) {\n\t\t\tresponse := res.Output().(*RepoVersion)\n\n\t\t\tquiet, _, err := res.Request().Option(\"quiet\").Bool()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\tif quiet {\n\t\t\t\tbuf = bytes.NewBufferString(fmt.Sprintf(\"fs-repo@%s\\n\", response.Version))\n\t\t\t} else {\n\t\t\t\tbuf = bytes.NewBufferString(fmt.Sprintf(\"ipfs repo version fs-repo@%s\\n\", response.Version))\n\t\t\t}\n\t\t\treturn buf, nil\n\n\t\t},\n\t},\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013, 2014 The Joker Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage joker\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t. \"github.com\/osmano807\/joker\/interfaces\"\n\t\"github.com\/osmano807\/joker\/plugins\"\n\t\"io\"\n\t\"log\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n)\n\nvar NewSquidFormat bool = false\nvar exitWaitGroup sync.WaitGroup\nvar outputStream *log.Logger \/\/ Hack because fmt is not thread safe\n\nfunc Main() {\n\trunPluginsInit()\n\toutputStream = log.New(os.Stdout, \"\", 0)\n\treaderLoop(os.Stdin)\n}\n\n\/\/ run some initialization code for each plugin\nfunc runPluginsInit() {\n\tfor _, p := range plugins.PLUGINS_LIST {\n\t\tp.Init()\n\t}\n}\n\n\/\/ Executes the main reading loop of squid requests\nfunc readerLoop(input io.Reader) {\n\trd := bufio.NewReader(input)\n\tfor {\n\t\tline, err := rd.ReadString('\\n')\n\t\tif err != nil && err != io.EOF { \/\/ EOF is handled on the next if\n\t\t\tlog.Fatalln(\"Erro inesperado\", err)\n\t\t}\n\t\tfields := strings.Fields(line)\n\t\tif ln := len(fields); ln == 0 {\n\t\t\tlog.Println(\"Esperando goroutines\")\n\t\t\texitWaitGroup.Wait()\n\t\t\tlog.Println(\"Normal exit from squid\")\n\t\t\treturn\n\t\t} else if ln < 4 {\n\t\t\tlog.Println(\"Linha com erro:\", line)\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Println(\"Fields are:\", fields)\n\t\til := parse(fields)\n\t\tlog.Println(\"Parsed:\", il, il.URL.Host)\n\t\thandleInput(il)\n\t}\n}\n\nfunc handleInput(il *InputLine) {\n\tfn := func() {\n\t\tlog.Println(\"Handling...\")\n\n\t\tvar ol *OutputLine\n\n\t\tfor _, myp := range plugins.PLUGINS_LIST {\n\t\t\tol = myp.Handle(il)\n\t\t\tif ol.Result != NO_CHANGE {\n\t\t\t\tlog.Println(\"Match found by plugin\", myp.Name())\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tprintOutput(il, ol)\n\n\t\tif il.ChannelId != NON_CONCURRENT {\n\t\t\tlog.Println(\"Done goroutine\")\n\t\t\texitWaitGroup.Done()\n\t\t}\n\n\t\tlog.Println(\"Exiting handling...\")\n\t}\n\tif il.ChannelId == NON_CONCURRENT { \/\/ Sequential\n\t\tfn()\n\t} else {\n\t\tlog.Println(\"Starting goroutine\")\n\t\texitWaitGroup.Add(1)\n\t\tgo fn()\n\t}\n}\n\nfunc printOutput(il *InputLine, ol *OutputLine) {\n\tvar buffer bytes.Buffer\n\n\tif ol.ChannelId != NON_CONCURRENT {\n\t\tbuffer.WriteString(strconv.Itoa(ol.ChannelId))\n\t\tbuffer.WriteString(\" \")\n\t}\n\n\tif NewSquidFormat {\n\t\t\/\/ OK\tSuccess. A new storage ID is presented for this URL.\n\t\t\/\/ ERR\tSuccess. No change for this URL.\n\t\t\/\/ BH\tFailure. The helper encountered a problem.\n\n\t\tswitch ol.Result {\n\t\tcase NO_CHANGE:\n\t\t\tbuffer.WriteString(\"ERR\") \/\/ Squid misleading return code\n\t\tcase NEW_STOREID:\n\t\t\tbuffer.WriteString(\"OK store-id=\")\n\t\t\tbuffer.WriteString(ol.StoreId)\n\n\t\t}\n\t} else {\n\t\tswitch ol.Result {\n\t\tcase NO_CHANGE:\n\t\t\tbuffer.WriteString(il.URL.String())\n\t\tcase NEW_STOREID:\n\t\t\tbuffer.WriteString(ol.StoreId)\n\n\t\t}\n\t}\n\n\tlog.Println(\"Result:\", buffer.String())\n\n\toutputStream.Println(buffer.String())\n}\n\nfunc parse(s []string) (il *InputLine) {\n\til = &InputLine{}\n\tstart := 1\n\tif ChannelId, err := strconv.ParseUint(s[0], 10, 0); err != nil {\n\t\til.ChannelId = NON_CONCURRENT\n\t\tstart = 0\n\t} else {\n\t\til.ChannelId = int(ChannelId)\n\t}\n\n\tif URL, err := url.Parse(s[start]); err != nil {\n\t\tlog.Println(\"Error!\")\n\t\treturn\n\t} else {\n\t\til.URL = URL\n\t}\n\n\tlog.Println(\"start:\", start)\n\n\til.Method = s[start+3]\n\n\treturn\n\n}\n<commit_msg>Add a error handling<commit_after>\/\/ Copyright (c) 2013, 2014 The Joker Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage joker\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t. \"github.com\/osmano807\/joker\/interfaces\"\n\t\"github.com\/osmano807\/joker\/plugins\"\n\t\"io\"\n\t\"log\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n)\n\nvar NewSquidFormat bool = false\nvar exitWaitGroup sync.WaitGroup\nvar outputStream *log.Logger \/\/ Hack because fmt is not thread safe\n\nfunc Main() {\n\trunPluginsInit()\n\toutputStream = log.New(os.Stdout, \"\", 0)\n\treaderLoop(os.Stdin)\n}\n\n\/\/ run some initialization code for each plugin\nfunc runPluginsInit() {\n\tfor _, p := range plugins.PLUGINS_LIST {\n\t\tp.Init()\n\t}\n}\n\n\/\/ Executes the main reading loop of squid requests\nfunc readerLoop(input io.Reader) {\n\trd := bufio.NewReader(input)\n\tfor {\n\t\tline, err := rd.ReadString('\\n')\n\t\tif err != nil && err != io.EOF { \/\/ EOF is handled on the next if\n\t\t\tlog.Fatalln(\"Erro inesperado\", err)\n\t\t}\n\t\tfields := strings.Fields(line)\n\t\tif ln := len(fields); ln == 0 {\n\t\t\tlog.Println(\"Esperando goroutines\")\n\t\t\texitWaitGroup.Wait()\n\t\t\tlog.Println(\"Normal exit from squid\")\n\t\t\treturn\n\t\t} else if ln < 4 {\n\t\t\tlog.Println(\"Linha com erro:\", line)\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Println(\"Fields are:\", fields)\n\t\til, err := parse(fields)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Erro inesperado\", err)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Println(\"Parsed:\", il, il.URL.Host)\n\t\thandleInput(il)\n\t}\n}\n\nfunc handleInput(il *InputLine) {\n\tfn := func() {\n\t\tlog.Println(\"Handling...\")\n\n\t\tvar ol *OutputLine\n\n\t\tfor _, myp := range plugins.PLUGINS_LIST {\n\t\t\tol = myp.Handle(il)\n\t\t\tif ol.Result != NO_CHANGE {\n\t\t\t\tlog.Println(\"Match found by plugin\", myp.Name())\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tprintOutput(il, ol)\n\n\t\tif il.ChannelId != NON_CONCURRENT {\n\t\t\tlog.Println(\"Done goroutine\")\n\t\t\texitWaitGroup.Done()\n\t\t}\n\n\t\tlog.Println(\"Exiting handling...\")\n\t}\n\tif il.ChannelId == NON_CONCURRENT { \/\/ Sequential\n\t\tfn()\n\t} else {\n\t\tlog.Println(\"Starting goroutine\")\n\t\texitWaitGroup.Add(1)\n\t\tgo fn()\n\t}\n}\n\nfunc printOutput(il *InputLine, ol *OutputLine) {\n\tvar buffer bytes.Buffer\n\n\tif ol.ChannelId != NON_CONCURRENT {\n\t\tbuffer.WriteString(strconv.Itoa(ol.ChannelId))\n\t\tbuffer.WriteString(\" \")\n\t}\n\n\tif NewSquidFormat {\n\t\t\/\/ OK\tSuccess. A new storage ID is presented for this URL.\n\t\t\/\/ ERR\tSuccess. No change for this URL.\n\t\t\/\/ BH\tFailure. The helper encountered a problem.\n\n\t\tswitch ol.Result {\n\t\tcase NO_CHANGE:\n\t\t\tbuffer.WriteString(\"ERR\") \/\/ Squid misleading return code\n\t\tcase NEW_STOREID:\n\t\t\tbuffer.WriteString(\"OK store-id=\")\n\t\t\tbuffer.WriteString(ol.StoreId)\n\n\t\t}\n\t} else {\n\t\tswitch ol.Result {\n\t\tcase NO_CHANGE:\n\t\t\tbuffer.WriteString(il.URL.String())\n\t\tcase NEW_STOREID:\n\t\t\tbuffer.WriteString(ol.StoreId)\n\n\t\t}\n\t}\n\n\tlog.Println(\"Result:\", buffer.String())\n\n\toutputStream.Println(buffer.String())\n}\n\nfunc parse(s []string) (il *InputLine, oerr error) {\n\til = &InputLine{}\n\toerr = nil\n\tstart := 1\n\tif ChannelId, err := strconv.ParseUint(s[0], 10, 0); err != nil {\n\t\til.ChannelId = NON_CONCURRENT\n\t\tstart = 0\n\t} else {\n\t\til.ChannelId = int(ChannelId)\n\t}\n\n\tif URL, err := url.Parse(s[start]); err != nil {\n\t\tlog.Println(\"Error!\")\n\t\toerr = err\n\t\treturn\n\t} else {\n\t\til.URL = URL\n\t}\n\n\tlog.Println(\"start:\", start)\n\n\til.Method = s[start+3]\n\n\treturn\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ package bitswap implements the IPFS Exchange interface with the BitSwap\n\/\/ bilateral exchange protocol.\npackage bitswap\n\nimport (\n\t\"time\"\n\n\tcontext \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/go.net\/context\"\n\n\tblocks \"github.com\/jbenet\/go-ipfs\/blocks\"\n\tblockstore \"github.com\/jbenet\/go-ipfs\/blocks\/blockstore\"\n\texchange \"github.com\/jbenet\/go-ipfs\/exchange\"\n\tbsmsg \"github.com\/jbenet\/go-ipfs\/exchange\/bitswap\/message\"\n\tbsnet \"github.com\/jbenet\/go-ipfs\/exchange\/bitswap\/network\"\n\tnotifications \"github.com\/jbenet\/go-ipfs\/exchange\/bitswap\/notifications\"\n\tstrategy \"github.com\/jbenet\/go-ipfs\/exchange\/bitswap\/strategy\"\n\tpeer \"github.com\/jbenet\/go-ipfs\/peer\"\n\tu \"github.com\/jbenet\/go-ipfs\/util\"\n\t\"github.com\/jbenet\/go-ipfs\/util\/eventlog\"\n)\n\nvar log = eventlog.Logger(\"bitswap\")\n\n\/\/ New initializes a BitSwap instance that communicates over the\n\/\/ provided BitSwapNetwork. This function registers the returned instance as\n\/\/ the network delegate.\n\/\/ Runs until context is cancelled\nfunc New(parent context.Context, p peer.Peer, network bsnet.BitSwapNetwork, routing bsnet.Routing,\n\tbstore blockstore.Blockstore, nice bool) exchange.Interface {\n\n\tctx, cancelFunc := context.WithCancel(parent)\n\n\tnotif := notifications.New()\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tnotif.Shutdown()\n\t}()\n\n\tbs := &bitswap{\n\t\tblockstore:    bstore,\n\t\tcancelFunc:    cancelFunc,\n\t\tnotifications: notif,\n\t\tstrategy:      strategy.New(nice),\n\t\trouting:       routing,\n\t\tsender:        network,\n\t\twantlist:      u.NewKeySet(),\n\t\tbatchRequests: make(chan []u.Key, 32),\n\t}\n\tnetwork.SetDelegate(bs)\n\tgo bs.loop(ctx)\n\n\treturn bs\n}\n\n\/\/ bitswap instances implement the bitswap protocol.\ntype bitswap struct {\n\n\t\/\/ sender delivers messages on behalf of the session\n\tsender bsnet.BitSwapNetwork\n\n\t\/\/ blockstore is the local database\n\t\/\/ NB: ensure threadsafety\n\tblockstore blockstore.Blockstore\n\n\t\/\/ routing interface for communication\n\trouting bsnet.Routing\n\n\tnotifications notifications.PubSub\n\n\t\/\/ Requests for a set of related blocks\n\t\/\/ the assumption is made that the same peer is likely to\n\t\/\/ have more than a single block in the set\n\tbatchRequests chan []u.Key\n\n\t\/\/ strategy listens to network traffic and makes decisions about how to\n\t\/\/ interact with partners.\n\t\/\/ TODO(brian): save the strategy's state to the datastore\n\tstrategy strategy.Strategy\n\n\twantlist u.KeySet\n\n\t\/\/ cancelFunc signals cancellation to the bitswap event loop\n\tcancelFunc func()\n}\n\n\/\/ GetBlock attempts to retrieve a particular block from peers within the\n\/\/ deadline enforced by the context.\nfunc (bs *bitswap) GetBlock(parent context.Context, k u.Key) (*blocks.Block, error) {\n\n\t\/\/ make sure to derive a new |ctx| and pass it to children. It's correct to\n\t\/\/ listen on |parent| here, but incorrect to pass |parent| to new async\n\t\/\/ functions. This is difficult to enforce. May this comment keep you safe.\n\n\tctx, cancelFunc := context.WithCancel(parent)\n\n\tctx = eventlog.ContextWithMetadata(ctx, eventlog.Uuid(\"GetBlockRequest\"))\n\tlog.Event(ctx, \"GetBlockRequestBegin\", &k)\n\n\tdefer func() {\n\t\tcancelFunc()\n\t\tlog.Event(ctx, \"GetBlockRequestEnd\", &k)\n\t}()\n\n\tpromise, err := bs.GetBlocks(parent, []u.Key{k})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tselect {\n\tcase block := <-promise:\n\t\treturn block, nil\n\tcase <-parent.Done():\n\t\treturn nil, parent.Err()\n\t}\n\n}\n\n\/\/ GetBlocks returns a channel where the caller may receive blocks that\n\/\/ correspond to the provided |keys|. Returns an error if BitSwap is unable to\n\/\/ begin this request within the deadline enforced by the context.\n\/\/\n\/\/ NB: Your request remains open until the context expires. To conserve\n\/\/ resources, provide a context with a reasonably short deadline (ie. not one\n\/\/ that lasts throughout the lifetime of the server)\nfunc (bs *bitswap) GetBlocks(ctx context.Context, keys []u.Key) (<-chan *blocks.Block, error) {\n\t\/\/ TODO log the request\n\n\tpromise := bs.notifications.Subscribe(ctx, keys...)\n\tselect {\n\tcase bs.batchRequests <- keys:\n\t\treturn promise, nil\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\t}\n}\n\nfunc (bs *bitswap) sendWantListTo(ctx context.Context, peers <-chan peer.Peer) error {\n\tif peers == nil {\n\t\tpanic(\"Cant send wantlist to nil peerchan\")\n\t}\n\tmessage := bsmsg.New()\n\tfor _, wanted := range bs.wantlist.Keys() {\n\t\tmessage.AddWanted(wanted)\n\t}\n\tfor peerToQuery := range peers {\n\t\tlog.Event(ctx, \"PeerToQuery\", peerToQuery)\n\t\tgo func(p peer.Peer) {\n\n\t\t\tlog.Event(ctx, \"DialPeer\", p)\n\t\t\terr := bs.sender.DialPeer(ctx, p)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error sender.DialPeer(%s): %s\", p, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresponse, err := bs.sender.SendRequest(ctx, p, message)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error sender.SendRequest(%s) = %s\", p, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ FIXME ensure accounting is handled correctly when\n\t\t\t\/\/ communication fails. May require slightly different API to\n\t\t\t\/\/ get better guarantees. May need shared sequence numbers.\n\t\t\tbs.strategy.MessageSent(p, message)\n\n\t\t\tif response == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tbs.ReceiveMessage(ctx, p, response)\n\t\t}(peerToQuery)\n\t}\n\treturn nil\n}\n\n\/\/ TODO ensure only one active request per key\nfunc (bs *bitswap) loop(parent context.Context) {\n\n\tctx, cancel := context.WithCancel(parent)\n\n\t\/\/ Every so often, we should resend out our current want list\n\trebroadcastTime := time.Second * 5\n\n\tbroadcastSignal := time.NewTicker(bs.strategy.GetRebroadcastDelay())\n\tdefer func() {\n\t\tcancel() \/\/ signal to derived async functions\n\t\tbroadcastSignal.Stop()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-broadcastSignal.C:\n\t\t\tfor _, k := range bs.wantlist.Keys() {\n\t\t\t\tproviders := bs.routing.FindProvidersAsync(ctx, k, maxProvidersPerRequest)\n\t\t\t\terr := bs.sendWantListTo(ctx, providers)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"error sending wantlist: %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\tcase ks := <-bs.batchRequests:\n\t\t\t\/\/ TODO: implement batching on len(ks) > X for some X\n\t\t\tif len(ks) == 0 {\n\t\t\t\tlog.Warning(\"Received batch request for zero blocks\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, k := range ks {\n\t\t\t\tbs.wantlist.Add(k)\n\t\t\t}\n\t\t\tproviders := bs.routing.FindProvidersAsync(ctx, ks[0], maxProvidersPerRequest)\n\n\t\t\terr := bs.sendWantListTo(ctx, providers)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"error sending wantlist: %s\", err)\n\t\t\t}\n\t\tcase <-parent.Done():\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ HasBlock announces the existance of a block to this bitswap service. The\n\/\/ service will potentially notify its peers.\nfunc (bs *bitswap) HasBlock(ctx context.Context, blk *blocks.Block) error {\n\tlog.Debugf(\"Has Block %s\", blk.Key())\n\tbs.wantlist.Remove(blk.Key())\n\tbs.sendToPeersThatWant(ctx, blk)\n\treturn bs.routing.Provide(ctx, blk.Key())\n}\n\n\/\/ TODO(brian): handle errors\nfunc (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (\n\tpeer.Peer, bsmsg.BitSwapMessage) {\n\tlog.Debugf(\"ReceiveMessage from %s\", p)\n\tlog.Debugf(\"Message wantlist: %v\", incoming.Wantlist())\n\n\tif p == nil {\n\t\tlog.Error(\"Received message from nil peer!\")\n\t\t\/\/ TODO propagate the error upward\n\t\treturn nil, nil\n\t}\n\tif incoming == nil {\n\t\tlog.Error(\"Got nil bitswap message!\")\n\t\t\/\/ TODO propagate the error upward\n\t\treturn nil, nil\n\t}\n\n\t\/\/ Record message bytes in ledger\n\t\/\/ TODO: this is bad, and could be easily abused.\n\t\/\/ Should only track *useful* messages in ledger\n\tbs.strategy.MessageReceived(p, incoming) \/\/ FIRST\n\n\tfor _, block := range incoming.Blocks() {\n\t\t\/\/ TODO verify blocks?\n\t\tif err := bs.blockstore.Put(block); err != nil {\n\t\t\tlog.Criticalf(\"error putting block: %s\", err)\n\t\t\tcontinue \/\/ FIXME(brian): err ignored\n\t\t}\n\t\tbs.notifications.Publish(block)\n\t\tbs.wantlist.Remove(block.Key())\n\t\terr := bs.HasBlock(ctx, block)\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"HasBlock errored: %s\", err)\n\t\t}\n\t}\n\n\tfor _, key := range incoming.Wantlist() {\n\t\t\/\/ TODO: might be better to check if we have the block before checking\n\t\t\/\/\t\t\tif we should send it to someone\n\t\tif bs.strategy.ShouldSendBlockToPeer(key, p) {\n\t\t\tif block, errBlockNotFound := bs.blockstore.Get(key); errBlockNotFound != nil {\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\t\/\/ Create a separate message to send this block in\n\t\t\t\tblkmsg := bsmsg.New()\n\n\t\t\t\t\/\/ TODO: only send this the first time\n\t\t\t\tfor _, k := range bs.wantlist.Keys() {\n\t\t\t\t\tblkmsg.AddWanted(k)\n\t\t\t\t}\n\n\t\t\t\tblkmsg.AddBlock(block)\n\t\t\t\tbs.strategy.MessageSent(p, blkmsg)\n\t\t\t\tbs.send(ctx, p, blkmsg)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, nil\n}\n\nfunc (bs *bitswap) ReceiveError(err error) {\n\tlog.Errorf(\"Bitswap ReceiveError: %s\", err)\n\t\/\/ TODO log the network error\n\t\/\/ TODO bubble the network error up to the parent context\/error logger\n}\n\n\/\/ send strives to ensure that accounting is always performed when a message is\n\/\/ sent\nfunc (bs *bitswap) send(ctx context.Context, p peer.Peer, m bsmsg.BitSwapMessage) {\n\tbs.sender.SendMessage(ctx, p, m)\n\tbs.strategy.MessageSent(p, m)\n}\n\nfunc (bs *bitswap) sendToPeersThatWant(ctx context.Context, block *blocks.Block) {\n\tlog.Debugf(\"Sending %v to peers that want it\", block.Key())\n\n\tfor _, p := range bs.strategy.Peers() {\n\t\tif bs.strategy.BlockIsWantedByPeer(block.Key(), p) {\n\t\t\tlog.Debugf(\"%v wants %v\", p, block.Key())\n\t\t\tif bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {\n\t\t\t\tmessage := bsmsg.New()\n\t\t\t\tmessage.AddBlock(block)\n\t\t\t\tfor _, wanted := range bs.wantlist.Keys() {\n\t\t\t\t\tmessage.AddWanted(wanted)\n\t\t\t\t}\n\t\t\t\tbs.send(ctx, p, message)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (bs *bitswap) Close() error {\n\tbs.cancelFunc()\n\treturn nil \/\/ to conform to Closer interface\n}\n<commit_msg>fix(bitswap) pass derived context to called functions<commit_after>\/\/ package bitswap implements the IPFS Exchange interface with the BitSwap\n\/\/ bilateral exchange protocol.\npackage bitswap\n\nimport (\n\t\"time\"\n\n\tcontext \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/go.net\/context\"\n\n\tblocks \"github.com\/jbenet\/go-ipfs\/blocks\"\n\tblockstore \"github.com\/jbenet\/go-ipfs\/blocks\/blockstore\"\n\texchange \"github.com\/jbenet\/go-ipfs\/exchange\"\n\tbsmsg \"github.com\/jbenet\/go-ipfs\/exchange\/bitswap\/message\"\n\tbsnet \"github.com\/jbenet\/go-ipfs\/exchange\/bitswap\/network\"\n\tnotifications \"github.com\/jbenet\/go-ipfs\/exchange\/bitswap\/notifications\"\n\tstrategy \"github.com\/jbenet\/go-ipfs\/exchange\/bitswap\/strategy\"\n\tpeer \"github.com\/jbenet\/go-ipfs\/peer\"\n\tu \"github.com\/jbenet\/go-ipfs\/util\"\n\t\"github.com\/jbenet\/go-ipfs\/util\/eventlog\"\n)\n\nvar log = eventlog.Logger(\"bitswap\")\n\n\/\/ New initializes a BitSwap instance that communicates over the\n\/\/ provided BitSwapNetwork. This function registers the returned instance as\n\/\/ the network delegate.\n\/\/ Runs until context is cancelled\nfunc New(parent context.Context, p peer.Peer, network bsnet.BitSwapNetwork, routing bsnet.Routing,\n\tbstore blockstore.Blockstore, nice bool) exchange.Interface {\n\n\tctx, cancelFunc := context.WithCancel(parent)\n\n\tnotif := notifications.New()\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tnotif.Shutdown()\n\t}()\n\n\tbs := &bitswap{\n\t\tblockstore:    bstore,\n\t\tcancelFunc:    cancelFunc,\n\t\tnotifications: notif,\n\t\tstrategy:      strategy.New(nice),\n\t\trouting:       routing,\n\t\tsender:        network,\n\t\twantlist:      u.NewKeySet(),\n\t\tbatchRequests: make(chan []u.Key, 32),\n\t}\n\tnetwork.SetDelegate(bs)\n\tgo bs.loop(ctx)\n\n\treturn bs\n}\n\n\/\/ bitswap instances implement the bitswap protocol.\ntype bitswap struct {\n\n\t\/\/ sender delivers messages on behalf of the session\n\tsender bsnet.BitSwapNetwork\n\n\t\/\/ blockstore is the local database\n\t\/\/ NB: ensure threadsafety\n\tblockstore blockstore.Blockstore\n\n\t\/\/ routing interface for communication\n\trouting bsnet.Routing\n\n\tnotifications notifications.PubSub\n\n\t\/\/ Requests for a set of related blocks\n\t\/\/ the assumption is made that the same peer is likely to\n\t\/\/ have more than a single block in the set\n\tbatchRequests chan []u.Key\n\n\t\/\/ strategy listens to network traffic and makes decisions about how to\n\t\/\/ interact with partners.\n\t\/\/ TODO(brian): save the strategy's state to the datastore\n\tstrategy strategy.Strategy\n\n\twantlist u.KeySet\n\n\t\/\/ cancelFunc signals cancellation to the bitswap event loop\n\tcancelFunc func()\n}\n\n\/\/ GetBlock attempts to retrieve a particular block from peers within the\n\/\/ deadline enforced by the context.\nfunc (bs *bitswap) GetBlock(parent context.Context, k u.Key) (*blocks.Block, error) {\n\n\t\/\/ Any async work initiated by this function must end when this function\n\t\/\/ returns. To ensure this, derive a new context. Note that it is okay to\n\t\/\/ listen on parent in this scope, but NOT okay to pass |parent| to\n\t\/\/ functions called by this one. Otherwise those functions won't return\n\t\/\/ when this context Otherwise those functions won't return when this\n\t\/\/ context's cancel func is executed. This is difficult to enforce. May\n\t\/\/ this comment keep you safe.\n\n\tctx, cancelFunc := context.WithCancel(parent)\n\n\tctx = eventlog.ContextWithMetadata(ctx, eventlog.Uuid(\"GetBlockRequest\"))\n\tlog.Event(ctx, \"GetBlockRequestBegin\", &k)\n\n\tdefer func() {\n\t\tcancelFunc()\n\t\tlog.Event(ctx, \"GetBlockRequestEnd\", &k)\n\t}()\n\n\tpromise, err := bs.GetBlocks(ctx, []u.Key{k})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tselect {\n\tcase block := <-promise:\n\t\treturn block, nil\n\tcase <-parent.Done():\n\t\treturn nil, parent.Err()\n\t}\n\n}\n\n\/\/ GetBlocks returns a channel where the caller may receive blocks that\n\/\/ correspond to the provided |keys|. Returns an error if BitSwap is unable to\n\/\/ begin this request within the deadline enforced by the context.\n\/\/\n\/\/ NB: Your request remains open until the context expires. To conserve\n\/\/ resources, provide a context with a reasonably short deadline (ie. not one\n\/\/ that lasts throughout the lifetime of the server)\nfunc (bs *bitswap) GetBlocks(ctx context.Context, keys []u.Key) (<-chan *blocks.Block, error) {\n\t\/\/ TODO log the request\n\n\tpromise := bs.notifications.Subscribe(ctx, keys...)\n\tselect {\n\tcase bs.batchRequests <- keys:\n\t\treturn promise, nil\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\t}\n}\n\nfunc (bs *bitswap) sendWantListTo(ctx context.Context, peers <-chan peer.Peer) error {\n\tif peers == nil {\n\t\tpanic(\"Cant send wantlist to nil peerchan\")\n\t}\n\tmessage := bsmsg.New()\n\tfor _, wanted := range bs.wantlist.Keys() {\n\t\tmessage.AddWanted(wanted)\n\t}\n\tfor peerToQuery := range peers {\n\t\tlog.Event(ctx, \"PeerToQuery\", peerToQuery)\n\t\tgo func(p peer.Peer) {\n\n\t\t\tlog.Event(ctx, \"DialPeer\", p)\n\t\t\terr := bs.sender.DialPeer(ctx, p)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error sender.DialPeer(%s): %s\", p, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresponse, err := bs.sender.SendRequest(ctx, p, message)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Error sender.SendRequest(%s) = %s\", p, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ FIXME ensure accounting is handled correctly when\n\t\t\t\/\/ communication fails. May require slightly different API to\n\t\t\t\/\/ get better guarantees. May need shared sequence numbers.\n\t\t\tbs.strategy.MessageSent(p, message)\n\n\t\t\tif response == nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tbs.ReceiveMessage(ctx, p, response)\n\t\t}(peerToQuery)\n\t}\n\treturn nil\n}\n\n\/\/ TODO ensure only one active request per key\nfunc (bs *bitswap) loop(parent context.Context) {\n\n\tctx, cancel := context.WithCancel(parent)\n\n\t\/\/ Every so often, we should resend out our current want list\n\trebroadcastTime := time.Second * 5\n\n\tbroadcastSignal := time.NewTicker(bs.strategy.GetRebroadcastDelay())\n\tdefer func() {\n\t\tcancel() \/\/ signal to derived async functions\n\t\tbroadcastSignal.Stop()\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-broadcastSignal.C:\n\t\t\tfor _, k := range bs.wantlist.Keys() {\n\t\t\t\tproviders := bs.routing.FindProvidersAsync(ctx, k, maxProvidersPerRequest)\n\t\t\t\terr := bs.sendWantListTo(ctx, providers)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"error sending wantlist: %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\tcase ks := <-bs.batchRequests:\n\t\t\t\/\/ TODO: implement batching on len(ks) > X for some X\n\t\t\tif len(ks) == 0 {\n\t\t\t\tlog.Warning(\"Received batch request for zero blocks\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor _, k := range ks {\n\t\t\t\tbs.wantlist.Add(k)\n\t\t\t}\n\t\t\tproviders := bs.routing.FindProvidersAsync(ctx, ks[0], maxProvidersPerRequest)\n\n\t\t\terr := bs.sendWantListTo(ctx, providers)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"error sending wantlist: %s\", err)\n\t\t\t}\n\t\tcase <-parent.Done():\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ HasBlock announces the existance of a block to this bitswap service. The\n\/\/ service will potentially notify its peers.\nfunc (bs *bitswap) HasBlock(ctx context.Context, blk *blocks.Block) error {\n\tlog.Debugf(\"Has Block %s\", blk.Key())\n\tbs.wantlist.Remove(blk.Key())\n\tbs.sendToPeersThatWant(ctx, blk)\n\treturn bs.routing.Provide(ctx, blk.Key())\n}\n\n\/\/ TODO(brian): handle errors\nfunc (bs *bitswap) ReceiveMessage(ctx context.Context, p peer.Peer, incoming bsmsg.BitSwapMessage) (\n\tpeer.Peer, bsmsg.BitSwapMessage) {\n\tlog.Debugf(\"ReceiveMessage from %s\", p)\n\tlog.Debugf(\"Message wantlist: %v\", incoming.Wantlist())\n\n\tif p == nil {\n\t\tlog.Error(\"Received message from nil peer!\")\n\t\t\/\/ TODO propagate the error upward\n\t\treturn nil, nil\n\t}\n\tif incoming == nil {\n\t\tlog.Error(\"Got nil bitswap message!\")\n\t\t\/\/ TODO propagate the error upward\n\t\treturn nil, nil\n\t}\n\n\t\/\/ Record message bytes in ledger\n\t\/\/ TODO: this is bad, and could be easily abused.\n\t\/\/ Should only track *useful* messages in ledger\n\tbs.strategy.MessageReceived(p, incoming) \/\/ FIRST\n\n\tfor _, block := range incoming.Blocks() {\n\t\t\/\/ TODO verify blocks?\n\t\tif err := bs.blockstore.Put(block); err != nil {\n\t\t\tlog.Criticalf(\"error putting block: %s\", err)\n\t\t\tcontinue \/\/ FIXME(brian): err ignored\n\t\t}\n\t\tbs.notifications.Publish(block)\n\t\tbs.wantlist.Remove(block.Key())\n\t\terr := bs.HasBlock(ctx, block)\n\t\tif err != nil {\n\t\t\tlog.Warningf(\"HasBlock errored: %s\", err)\n\t\t}\n\t}\n\n\tfor _, key := range incoming.Wantlist() {\n\t\t\/\/ TODO: might be better to check if we have the block before checking\n\t\t\/\/\t\t\tif we should send it to someone\n\t\tif bs.strategy.ShouldSendBlockToPeer(key, p) {\n\t\t\tif block, errBlockNotFound := bs.blockstore.Get(key); errBlockNotFound != nil {\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\t\/\/ Create a separate message to send this block in\n\t\t\t\tblkmsg := bsmsg.New()\n\n\t\t\t\t\/\/ TODO: only send this the first time\n\t\t\t\tfor _, k := range bs.wantlist.Keys() {\n\t\t\t\t\tblkmsg.AddWanted(k)\n\t\t\t\t}\n\n\t\t\t\tblkmsg.AddBlock(block)\n\t\t\t\tbs.strategy.MessageSent(p, blkmsg)\n\t\t\t\tbs.send(ctx, p, blkmsg)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, nil\n}\n\nfunc (bs *bitswap) ReceiveError(err error) {\n\tlog.Errorf(\"Bitswap ReceiveError: %s\", err)\n\t\/\/ TODO log the network error\n\t\/\/ TODO bubble the network error up to the parent context\/error logger\n}\n\n\/\/ send strives to ensure that accounting is always performed when a message is\n\/\/ sent\nfunc (bs *bitswap) send(ctx context.Context, p peer.Peer, m bsmsg.BitSwapMessage) {\n\tbs.sender.SendMessage(ctx, p, m)\n\tbs.strategy.MessageSent(p, m)\n}\n\nfunc (bs *bitswap) sendToPeersThatWant(ctx context.Context, block *blocks.Block) {\n\tlog.Debugf(\"Sending %v to peers that want it\", block.Key())\n\n\tfor _, p := range bs.strategy.Peers() {\n\t\tif bs.strategy.BlockIsWantedByPeer(block.Key(), p) {\n\t\t\tlog.Debugf(\"%v wants %v\", p, block.Key())\n\t\t\tif bs.strategy.ShouldSendBlockToPeer(block.Key(), p) {\n\t\t\t\tmessage := bsmsg.New()\n\t\t\t\tmessage.AddBlock(block)\n\t\t\t\tfor _, wanted := range bs.wantlist.Keys() {\n\t\t\t\t\tmessage.AddWanted(wanted)\n\t\t\t\t}\n\t\t\t\tbs.send(ctx, p, message)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (bs *bitswap) Close() error {\n\tbs.cancelFunc()\n\treturn nil \/\/ to conform to Closer interface\n}\n<|endoftext|>"}
{"text":"<commit_before>package bip39\n\nimport (\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"crypto\/sha512\"\n\t\"encoding\/binary\"\n\t\"math\/big\"\n\t\"strings\"\n\n\t\"golang.org\/x\/crypto\/pbkdf2\"\n)\n\nvar (\n\t\/\/ Some bitwise operands for working with big.Ints\n\tlast11BitsMask          = big.NewInt(2047)\n\trightShift11BitsDivider = big.NewInt(2048)\n\tbigOne                  = big.NewInt(1)\n\tbigTwo                  = big.NewInt(2)\n\n\t\/\/ WordList sets the language used for the mnemonic\n\tWordList = EnglishWordList\n\n\t\/\/ ReverseWordMap is a reverse lookup of Wordlist\n\tReverseWordMap = map[string]int{}\n)\n\nfunc init() {\n\tfor i, v := range WordList {\n\t\tReverseWordMap[v] = i\n\t}\n}\n\n\/\/ NewEntropy will create random entropy bytes\n\/\/ so long as the requested size bitSize is an appropriate size.\nfunc NewEntropy(bitSize int) ([]byte, error) {\n\terr := validateEntropyBitSize(bitSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tentropy := make([]byte, bitSize\/8)\n\t_, err = rand.Read(entropy)\n\treturn entropy, err\n}\n\n\/\/ NewMnemonic will return a string consisting of the mnemonic words for\n\/\/ the given entropy.\n\/\/ If the provide entropy is invalid, an error will be returned.\nfunc NewMnemonic(entropy []byte) (string, error) {\n\t\/\/ Compute some lengths for convenience\n\tentropyBitLength := len(entropy) * 8\n\tchecksumBitLength := entropyBitLength \/ 32\n\tsentenceLength := (entropyBitLength + checksumBitLength) \/ 11\n\n\terr := validateEntropyBitSize(entropyBitLength)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t\/\/ Add checksum to entropy\n\tentropy = addChecksum(entropy)\n\n\t\/\/ Break entropy up into sentenceLength chunks of 11 bits\n\t\/\/ For each word AND mask the rightmost 11 bits and find the word at that index\n\t\/\/ Then bitshift entropy 11 bits right and repeat\n\t\/\/ Add to the last empty slot so we can work with LSBs instead of MSB\n\n\t\/\/ Entropy as an int so we can bitmask without worrying about bytes slices\n\tentropyInt := new(big.Int).SetBytes(entropy)\n\n\t\/\/ Slice to hold words in\n\twords := make([]string, sentenceLength)\n\n\t\/\/ Throw away big int for AND masking\n\tword := big.NewInt(0)\n\n\tfor i := sentenceLength - 1; i >= 0; i-- {\n\t\t\/\/ Get 11 right most bits and bitshift 11 to the right for next time\n\t\tword.And(entropyInt, last11BitsMask)\n\t\tentropyInt.Div(entropyInt, rightShift11BitsDivider)\n\n\t\t\/\/ Get the bytes representing the 11 bits as a 2 byte slice\n\t\twordBytes := padByteSlice(word.Bytes(), 2)\n\n\t\t\/\/ Convert bytes to an index and add that word to the list\n\t\twords[i] = WordList[binary.BigEndian.Uint16(wordBytes)]\n\t}\n\n\treturn strings.Join(words, \" \"), nil\n}\n\n\/\/ MnemonicToByteArray takes a mnemonic string and turns it into a byte array\n\/\/ suitable for creating another mnemonic.\n\/\/ An error is returned if the mnemonic is invalid.\nfunc MnemonicToByteArray(mnemonic string) ([]byte, error) {\n\tvar (\n\t\tmnemonicSlice    = strings.Split(mnemonic, \" \")\n\t\tentropyBitSize   = len(mnemonicSlice) * 11\n\t\tchecksumBitSize  = entropyBitSize % 32\n\t\tfullByteSize     = (entropyBitSize-checksumBitSize)\/8 + 1\n\t\tchecksumByteSize = fullByteSize - (fullByteSize % 4)\n\t)\n\n\t\/\/ Pre validate\n\tif !IsMnemonicValid(mnemonic) {\n\t\treturn nil, ErrInvalidMnemonic\n\t}\n\n\terr := validateEntropyWithChecksumBitSize(entropyBitSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Convert word indices to a `big.Int` representing the entropy\n\tchecksummedEntropy := big.NewInt(0)\n\tmodulo := big.NewInt(2048)\n\tfor _, v := range mnemonicSlice {\n\t\tindex, ok := ReverseWordMap[v]\n\t\tif !ok {\n\t\t\treturn nil, UnknownWordErr{Word: v}\n\t\t}\n\t\tadd := big.NewInt(int64(index))\n\t\tchecksummedEntropy.Mul(checksummedEntropy, modulo)\n\t\tchecksummedEntropy.Add(checksummedEntropy, add)\n\t}\n\n\t\/\/ Calculate the unchecksummed entropy so we can validate that the checksum is\n\t\/\/ correct\n\tchecksumModulo := big.NewInt(0).Exp(bigTwo, big.NewInt(int64(checksumBitSize)), nil)\n\trawEntropy := big.NewInt(0).Div(checksummedEntropy, checksumModulo)\n\n\t\/\/ Convert `big.Int`s to byte padded byte slices\n\trawEntropyBytes := padByteSlice(rawEntropy.Bytes(), checksumByteSize)\n\tchecksummedEntropyBytes := padByteSlice(checksummedEntropy.Bytes(), fullByteSize)\n\n\t\/\/ Validate that the checksum is correct\n\tnewChecksummedEntropyBytes := padByteSlice(addChecksum(rawEntropyBytes), fullByteSize)\n\tif !compareByteSlices(checksummedEntropyBytes, newChecksummedEntropyBytes) {\n\t\treturn nil, ErrChecksumIncorrect\n\t}\n\n\treturn checksummedEntropyBytes, nil\n}\n\n\/\/ NewSeedWithErrorChecking creates a hashed seed output given the mnemonic string and a password.\n\/\/ An error is returned if the mnemonic is not convertible to a byte array.\nfunc NewSeedWithErrorChecking(mnemonic string, password string) ([]byte, error) {\n\t_, err := MnemonicToByteArray(mnemonic)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewSeed(mnemonic, password), nil\n}\n\n\/\/ NewSeed creates a hashed seed output given a provided string and password.\n\/\/ No checking is performed to validate that the string provided is a valid mnemonic.\nfunc NewSeed(mnemonic string, password string) []byte {\n\treturn pbkdf2.Key([]byte(mnemonic), []byte(\"mnemonic\"+password), 2048, 64, sha512.New)\n}\n\n\/\/ IsMnemonicValid attempts to verify that the provided mnemonic is valid.\n\/\/ Validity is determined by both the number of words being appropriate,\n\/\/ and that all the words in the mnemonic are present in the word list.\nfunc IsMnemonicValid(mnemonic string) bool {\n\t\/\/ Create a list of all the words in the mnemonic sentence\n\twords := strings.Fields(mnemonic)\n\n\t\/\/Get num of words\n\tnumOfWords := len(words)\n\n\t\/\/ The number of words should be 12, 15, 18, 21 or 24\n\tif numOfWords%3 != 0 || numOfWords < 12 || numOfWords > 24 {\n\t\treturn false\n\t}\n\n\t\/\/ Check if all words belong in the wordlist\n\tfor i := 0; i < numOfWords; i++ {\n\t\tif !contains(WordList, words[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\/\/ Appends to data the first (len(data) \/ 32)bits of the result of sha256(data)\n\/\/ Currently only supports data up to 32 bytes\nfunc addChecksum(data []byte) []byte {\n\t\/\/ Get first byte of sha256\n\thasher := sha256.New()\n\thasher.Write(data)\n\thash := hasher.Sum(nil)\n\tfirstChecksumByte := hash[0]\n\n\t\/\/ len() is in bytes so we divide by 4\n\tchecksumBitLength := uint(len(data) \/ 4)\n\n\t\/\/ For each bit of check sum we want we shift the data one the left\n\t\/\/ and then set the (new) right most bit equal to checksum bit at that index\n\t\/\/ staring from the left\n\tdataBigInt := new(big.Int).SetBytes(data)\n\tfor i := uint(0); i < checksumBitLength; i++ {\n\t\t\/\/ Bitshift 1 left\n\t\tdataBigInt.Mul(dataBigInt, bigTwo)\n\n\t\t\/\/ Set rightmost bit if leftmost checksum bit is set\n\t\tif uint8(firstChecksumByte&(1<<(7-i))) > 0 {\n\t\t\tdataBigInt.Or(dataBigInt, bigOne)\n\t\t}\n\t}\n\n\treturn dataBigInt.Bytes()\n}\n\n\/\/ validateEntropyBitSize ensures that entropy is the correct size for being a\n\/\/ mnemonic.\nfunc validateEntropyBitSize(bitSize int) error {\n\tif (bitSize%32) != 0 || bitSize < 128 || bitSize > 256 {\n\t\treturn ErrEntropyLengthInvalid\n\t}\n\treturn nil\n}\n\n\/\/ validateEntropyWithChecksumBitSize ensures that the given number of bits is a\n\/\/ valid length for seed entropy with an attached checksum.\nfunc validateEntropyWithChecksumBitSize(bitSize int) error {\n\tif (bitSize != 128+4) && (bitSize != 160+5) && (bitSize != 192+6) && (bitSize != 224+7) && (bitSize != 256+8) {\n\t\treturn EntropySizeErr{int((bitSize - bitSize%32) + (bitSize-bitSize%32)\/32), bitSize}\n\t}\n\treturn nil\n}\n\n\/\/ padByteSlice returns a byte slice of the given size with contents of the\n\/\/ given slice left padded and any empty spaces filled with 0's.\nfunc padByteSlice(slice []byte, length int) []byte {\n\tif len(slice) >= length {\n\t\treturn slice\n\t}\n\tnewSlice := make([]byte, length-len(slice))\n\treturn append(newSlice, slice...)\n}\n\n\/\/ contains checks if a given string is in a given slice of strings.\nfunc contains(s []string, e string) bool {\n\tfor _, a := range s {\n\t\tif a == e {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ compareByteSlices returns true of the byte slices have equal contents and\n\/\/ returns false otherwise.\nfunc compareByteSlices(a, b []byte) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n<commit_msg>FEATURE: Allow setting word list at runtime.<commit_after>package bip39\n\nimport (\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"crypto\/sha512\"\n\t\"encoding\/binary\"\n\t\"math\/big\"\n\t\"strings\"\n\n\t\"golang.org\/x\/crypto\/pbkdf2\"\n)\n\nvar (\n\t\/\/ Some bitwise operands for working with big.Ints\n\tlast11BitsMask          = big.NewInt(2047)\n\trightShift11BitsDivider = big.NewInt(2048)\n\tbigOne                  = big.NewInt(1)\n\tbigTwo                  = big.NewInt(2)\n\n\t\/\/ WordList sets the language used for the mnemonic\n\tWordList []string\n\n\t\/\/ ReverseWordMap is a reverse lookup of Wordlist\n\tReverseWordMap map[string]int\n\n\t\/\/ DefaultWordList specifies the wordlist to use upon initialization\n\tDefaultWordList = EnglishWordList\n)\n\nfunc init() {\n\tSetWordList(DefaultWordList)\n}\n\n\/\/ SetWordList sets the list of words to use for mnemonics. Currently the list\n\/\/ that is set is used package-wide.\nfunc SetWordList(wordList []string) {\n\tWordList = wordList\n\tReverseWordMap = map[string]int{}\n\tfor i, v := range WordList {\n\t\tReverseWordMap[v] = i\n\t}\n}\n\n\/\/ NewEntropy will create random entropy bytes\n\/\/ so long as the requested size bitSize is an appropriate size.\nfunc NewEntropy(bitSize int) ([]byte, error) {\n\terr := validateEntropyBitSize(bitSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tentropy := make([]byte, bitSize\/8)\n\t_, err = rand.Read(entropy)\n\treturn entropy, err\n}\n\n\/\/ NewMnemonic will return a string consisting of the mnemonic words for\n\/\/ the given entropy.\n\/\/ If the provide entropy is invalid, an error will be returned.\nfunc NewMnemonic(entropy []byte) (string, error) {\n\t\/\/ Compute some lengths for convenience\n\tentropyBitLength := len(entropy) * 8\n\tchecksumBitLength := entropyBitLength \/ 32\n\tsentenceLength := (entropyBitLength + checksumBitLength) \/ 11\n\n\terr := validateEntropyBitSize(entropyBitLength)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t\/\/ Add checksum to entropy\n\tentropy = addChecksum(entropy)\n\n\t\/\/ Break entropy up into sentenceLength chunks of 11 bits\n\t\/\/ For each word AND mask the rightmost 11 bits and find the word at that index\n\t\/\/ Then bitshift entropy 11 bits right and repeat\n\t\/\/ Add to the last empty slot so we can work with LSBs instead of MSB\n\n\t\/\/ Entropy as an int so we can bitmask without worrying about bytes slices\n\tentropyInt := new(big.Int).SetBytes(entropy)\n\n\t\/\/ Slice to hold words in\n\twords := make([]string, sentenceLength)\n\n\t\/\/ Throw away big int for AND masking\n\tword := big.NewInt(0)\n\n\tfor i := sentenceLength - 1; i >= 0; i-- {\n\t\t\/\/ Get 11 right most bits and bitshift 11 to the right for next time\n\t\tword.And(entropyInt, last11BitsMask)\n\t\tentropyInt.Div(entropyInt, rightShift11BitsDivider)\n\n\t\t\/\/ Get the bytes representing the 11 bits as a 2 byte slice\n\t\twordBytes := padByteSlice(word.Bytes(), 2)\n\n\t\t\/\/ Convert bytes to an index and add that word to the list\n\t\twords[i] = WordList[binary.BigEndian.Uint16(wordBytes)]\n\t}\n\n\treturn strings.Join(words, \" \"), nil\n}\n\n\/\/ MnemonicToByteArray takes a mnemonic string and turns it into a byte array\n\/\/ suitable for creating another mnemonic.\n\/\/ An error is returned if the mnemonic is invalid.\nfunc MnemonicToByteArray(mnemonic string) ([]byte, error) {\n\tvar (\n\t\tmnemonicSlice    = strings.Split(mnemonic, \" \")\n\t\tentropyBitSize   = len(mnemonicSlice) * 11\n\t\tchecksumBitSize  = entropyBitSize % 32\n\t\tfullByteSize     = (entropyBitSize-checksumBitSize)\/8 + 1\n\t\tchecksumByteSize = fullByteSize - (fullByteSize % 4)\n\t)\n\n\t\/\/ Pre validate\n\tif !IsMnemonicValid(mnemonic) {\n\t\treturn nil, ErrInvalidMnemonic\n\t}\n\n\terr := validateEntropyWithChecksumBitSize(entropyBitSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Convert word indices to a `big.Int` representing the entropy\n\tchecksummedEntropy := big.NewInt(0)\n\tmodulo := big.NewInt(2048)\n\tfor _, v := range mnemonicSlice {\n\t\tindex, ok := ReverseWordMap[v]\n\t\tif !ok {\n\t\t\treturn nil, UnknownWordErr{Word: v}\n\t\t}\n\t\tadd := big.NewInt(int64(index))\n\t\tchecksummedEntropy.Mul(checksummedEntropy, modulo)\n\t\tchecksummedEntropy.Add(checksummedEntropy, add)\n\t}\n\n\t\/\/ Calculate the unchecksummed entropy so we can validate that the checksum is\n\t\/\/ correct\n\tchecksumModulo := big.NewInt(0).Exp(bigTwo, big.NewInt(int64(checksumBitSize)), nil)\n\trawEntropy := big.NewInt(0).Div(checksummedEntropy, checksumModulo)\n\n\t\/\/ Convert `big.Int`s to byte padded byte slices\n\trawEntropyBytes := padByteSlice(rawEntropy.Bytes(), checksumByteSize)\n\tchecksummedEntropyBytes := padByteSlice(checksummedEntropy.Bytes(), fullByteSize)\n\n\t\/\/ Validate that the checksum is correct\n\tnewChecksummedEntropyBytes := padByteSlice(addChecksum(rawEntropyBytes), fullByteSize)\n\tif !compareByteSlices(checksummedEntropyBytes, newChecksummedEntropyBytes) {\n\t\treturn nil, ErrChecksumIncorrect\n\t}\n\n\treturn checksummedEntropyBytes, nil\n}\n\n\/\/ NewSeedWithErrorChecking creates a hashed seed output given the mnemonic string and a password.\n\/\/ An error is returned if the mnemonic is not convertible to a byte array.\nfunc NewSeedWithErrorChecking(mnemonic string, password string) ([]byte, error) {\n\t_, err := MnemonicToByteArray(mnemonic)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewSeed(mnemonic, password), nil\n}\n\n\/\/ NewSeed creates a hashed seed output given a provided string and password.\n\/\/ No checking is performed to validate that the string provided is a valid mnemonic.\nfunc NewSeed(mnemonic string, password string) []byte {\n\treturn pbkdf2.Key([]byte(mnemonic), []byte(\"mnemonic\"+password), 2048, 64, sha512.New)\n}\n\n\/\/ IsMnemonicValid attempts to verify that the provided mnemonic is valid.\n\/\/ Validity is determined by both the number of words being appropriate,\n\/\/ and that all the words in the mnemonic are present in the word list.\nfunc IsMnemonicValid(mnemonic string) bool {\n\t\/\/ Create a list of all the words in the mnemonic sentence\n\twords := strings.Fields(mnemonic)\n\n\t\/\/Get num of words\n\tnumOfWords := len(words)\n\n\t\/\/ The number of words should be 12, 15, 18, 21 or 24\n\tif numOfWords%3 != 0 || numOfWords < 12 || numOfWords > 24 {\n\t\treturn false\n\t}\n\n\t\/\/ Check if all words belong in the wordlist\n\tfor i := 0; i < numOfWords; i++ {\n\t\tif !contains(WordList, words[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\/\/ Appends to data the first (len(data) \/ 32)bits of the result of sha256(data)\n\/\/ Currently only supports data up to 32 bytes\nfunc addChecksum(data []byte) []byte {\n\t\/\/ Get first byte of sha256\n\thasher := sha256.New()\n\thasher.Write(data)\n\thash := hasher.Sum(nil)\n\tfirstChecksumByte := hash[0]\n\n\t\/\/ len() is in bytes so we divide by 4\n\tchecksumBitLength := uint(len(data) \/ 4)\n\n\t\/\/ For each bit of check sum we want we shift the data one the left\n\t\/\/ and then set the (new) right most bit equal to checksum bit at that index\n\t\/\/ staring from the left\n\tdataBigInt := new(big.Int).SetBytes(data)\n\tfor i := uint(0); i < checksumBitLength; i++ {\n\t\t\/\/ Bitshift 1 left\n\t\tdataBigInt.Mul(dataBigInt, bigTwo)\n\n\t\t\/\/ Set rightmost bit if leftmost checksum bit is set\n\t\tif uint8(firstChecksumByte&(1<<(7-i))) > 0 {\n\t\t\tdataBigInt.Or(dataBigInt, bigOne)\n\t\t}\n\t}\n\n\treturn dataBigInt.Bytes()\n}\n\n\/\/ validateEntropyBitSize ensures that entropy is the correct size for being a\n\/\/ mnemonic.\nfunc validateEntropyBitSize(bitSize int) error {\n\tif (bitSize%32) != 0 || bitSize < 128 || bitSize > 256 {\n\t\treturn ErrEntropyLengthInvalid\n\t}\n\treturn nil\n}\n\n\/\/ validateEntropyWithChecksumBitSize ensures that the given number of bits is a\n\/\/ valid length for seed entropy with an attached checksum.\nfunc validateEntropyWithChecksumBitSize(bitSize int) error {\n\tif (bitSize != 128+4) && (bitSize != 160+5) && (bitSize != 192+6) && (bitSize != 224+7) && (bitSize != 256+8) {\n\t\treturn EntropySizeErr{int((bitSize - bitSize%32) + (bitSize-bitSize%32)\/32), bitSize}\n\t}\n\treturn nil\n}\n\n\/\/ padByteSlice returns a byte slice of the given size with contents of the\n\/\/ given slice left padded and any empty spaces filled with 0's.\nfunc padByteSlice(slice []byte, length int) []byte {\n\tif len(slice) >= length {\n\t\treturn slice\n\t}\n\tnewSlice := make([]byte, length-len(slice))\n\treturn append(newSlice, slice...)\n}\n\n\/\/ contains checks if a given string is in a given slice of strings.\nfunc contains(s []string, e string) bool {\n\tfor _, a := range s {\n\t\tif a == e {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ compareByteSlices returns true of the byte slices have equal contents and\n\/\/ returns false otherwise.\nfunc compareByteSlices(a, b []byte) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := range a {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>package templater\n\nimport (\n\t\"reflect\"\n\t\"errors\"\n\t\"strings\"\n\t\"log\"\n\t\"strconv\"\n\t\"fmt\"\n\t\"regexp\"\n\n\t\"github.com\/InnovaCo\/serve\/utils\/templater\/lexer\"\n\t\"github.com\/InnovaCo\/serve\/utils\/templater\/token\"\n\t\"github.com\/InnovaCo\/serve\/utils\/gabs\"\n)\n\nvar ModifyFuncs = map[string]interface{}{\n\t\"replace\": replace,\n\t\"same\": same,\n\t\"reverse\": reverse,\n}\n\nfunc replace(old, r, new string) string {\n\treturn regexp.MustCompile(r).ReplaceAllString(old, new)\n}\n\nfunc same(s string) string {\n\treturn s\n}\n\nfunc reverse(s bool) bool {\n\treturn !s\n}\n\ntype Modify struct {\n\tcontext *gabs.Container\n}\n\nfunc (this Modify) SetFunc(name string, function interface{}) error {\n\tif _, ok := ModifyFuncs[name]; ok {\n\t\treturn fmt.Errorf(\"function %s exist\", name)\n\t}\n\tModifyFuncs[name] = function\n\treturn nil\n}\n\nfunc (this Modify) Call(name string, params ... interface{}) (reflect.Value, error) {\n\tlog.Printf(\"modify call: func=%s args=%v\\n\", name, params)\n\n\tif _, ok := ModifyFuncs[name]; !ok {\n\t\treturn reflect.Value{}, fmt.Errorf(\"function %v not register\", name)\n\t}\n\n    f := reflect.ValueOf(ModifyFuncs[name])\n    if len(params) != f.Type().NumIn() {\n\t\treturn reflect.Value{}, errors.New(\"The number of params is not adapted.\")\n    }\n    in := make([]reflect.Value, len(params))\n    for k, param := range params {\n        in[k] = reflect.ValueOf(param)\n    }\n\treturn f.Call(in)[0], nil\n}\n\nfunc (this Modify) convert(val string) interface{} {\n\tif i, err := strconv.Atoi(val); err == nil {\n\t\treturn i\n\t} else if f, err := strconv.ParseFloat(val, 64); err == nil {\n\t\treturn f\n\t} else  if b, err := strconv.ParseBool(val); err == nil {\n\t\treturn b\n\t}\n\tb := []byte(val)\n\tif (b[0] == []byte(\"\\\"\")[0] && b[len(b) - 1] == []byte(\"\\\"\")[0]) ||\n\t\t(b[0] == []byte(\"'\")[0] && b[len(b) - 1] == []byte(\"'\")[0])\t{\n\t\treturn string(b[1:len(val)-1])\n\t}\n\treturn fmt.Sprintf(\"%v\", val)\n}\n\nfunc (this Modify) clearFunc(s []byte) []string {\n\treturn strings.Split(strings.TrimSpace(string([]byte(strings.TrimSpace(string(s)))[1:])), \"(\")\n}\n\nfunc (this Modify) clearArg(s []byte) string {\n\ta := []byte(strings.TrimSpace(string(s)))\n\tif a[0] == []byte(\",\")[0] {\n\t\treturn strings.TrimSpace(string(a[1:]))\n\t}\n\treturn string(a)\n}\n\nfunc (this Modify) parseFunc(s []byte) (string, []interface{}, error) {\n\tf := this.clearFunc(s)\n\tfuncName := f[0]\n\tfuncArgs := []interface{}{nil}\n\tif len(f) == 1 {\n\t\treturn funcName, funcArgs, nil\n\t}\n\tfl := lexer.NewLexer([]byte(f[1]))\n\tfor ftok := fl.Scan(); ftok.Type == token.TokMap.Type(\"arg\"); ftok = fl.Scan() {\n\t\tfuncArgs = append(funcArgs, this.convert(this.clearArg(ftok.Lit)))\n\t}\n\treturn funcName, funcArgs, nil\n}\n\nfunc (this Modify) resolve(v string) (string, error) {\n\t\/\/fmt.Printf(\"--> resolve: %v\\n\", v)\n\tif this.context == nil {\n\t\t\/\/fmt.Printf(\"<-- resolve: %v\\n\", v)\n\t\treturn v, nil\n\t}\n\tif value := this.context.Path(v).Data(); value != nil {\n\t\t\/\/fmt.Printf(\"find: %v\\n\", value)\n\t\tv = fmt.Sprintf(\"%v\", value)\n\t} else {\n\t\t\/\/fmt.Println(this.context.String())\n\t\t\/\/fmt.Printf(\"<-- resolve: %v\\n\", v)\n\t\treturn v, nil\n\t}\n\tif s, err := Template(v, this.context); err != nil {\n\t\t\/\/fmt.Println(\"<-- fuck\", v)\n\t\treturn v, nil\n\t} else {\n\t\t\/\/fmt.Println(\"<--\", v)\n\t\treturn s, nil\n\t}\n}\n\nfunc (this Modify) Exec(s string) (interface{}, error) {\n\tl := lexer.NewLexer([]byte(s))\n\tvar res interface{}\n\tres = nil\n\n\tfor tok := l.Scan(); (tok.Type == token.TokMap.Type(\"var\")) ||\n\t\t\t\t\t\t (tok.Type == token.TokMap.Type(\"func\")) ||\n\t                     (tok.Type == token.TokMap.Type(\"match\")); tok = l.Scan() {\n\t\tswitch {\n\t\t\tcase tok.Type == token.TokMap.Type(\"var\"):\n\t\t\t\t\/\/fmt.Printf(\"var token: %v\\n\", string(tok.Lit))\n\t\t\t\tif val, err := this.resolve(string(tok.Lit)); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t} else {\n\t\t\t\t\tres = this.convert(val)\n\t\t\t\t}\n\t\t\tcase tok.Type == token.TokMap.Type(\"func\"):\n\t\t\t\t\/\/fmt.Printf(\"func token: %v\\n\", string(tok.Lit))\n\t\t\t\tif funcName, funcArgs, err := this.parseFunc(tok.Lit); err == nil {\n\t\t\t\t\tfuncArgs[0] = res\n\t\t\t\t\tif fv, err := this.Call(funcName, funcArgs...); err != nil {\n\t\t\t\t\t\treturn nil, fmt.Errorf(\"execution error %s: %v\", funcName, err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tres = this.convert(fv.String())\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error parse %s: %v\", tok.Lit, err )\n\t\t\t\t}\n\t\t\tcase tok.Type == token.TokMap.Type(\"match\"):\n\t\t\t\t\/\/fmt.Printf(\"match token: %v\\n\", string(tok.Lit))\n\t\t\t\treturn s, nil\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"unknown token %v\\n\", string(tok.Lit))\n\t\t}\n\t}\n\treturn res, nil\n}\n\nfunc ModifyExec(s interface{}, context *gabs.Container) (interface{}, error) {\n\tswitch s.(type) {\n\t\tcase string:\n\t\t\tif strings.Contains(s.(string), \"{{\") && strings.Contains(s.(string), \"}}\") {\n\t\t\t\treturn nil, fmt.Errorf(\"find symbols '{{' and '}}' in %v\", s)\n\t\t\t}\n\t\t\treturn Modify{context}.Exec(fmt.Sprintf(\"%v\",s))\n\t}\n\treturn s, nil\n}<commit_msg>fix templater<commit_after>package templater\n\nimport (\n\t\"reflect\"\n\t\"errors\"\n\t\"strings\"\n\t\"log\"\n\t\"strconv\"\n\t\"fmt\"\n\t\"regexp\"\n\n\t\"github.com\/InnovaCo\/serve\/utils\/templater\/lexer\"\n\t\"github.com\/InnovaCo\/serve\/utils\/templater\/token\"\n\t\"github.com\/InnovaCo\/serve\/utils\/gabs\"\n)\n\nvar ModifyFuncs = map[string]interface{}{\n\t\"replace\": replace,\n\t\"same\": same,\n\t\"reverse\": reverse,\n}\n\nfunc replace(old, r, new string) string {\n\treturn regexp.MustCompile(r).ReplaceAllString(old, new)\n}\n\nfunc same(s string) string {\n\treturn s\n}\n\nfunc reverse(s bool) bool {\n\treturn !s\n}\n\ntype Modify struct {\n\tcontext *gabs.Container\n}\n\nfunc (this Modify) SetFunc(name string, function interface{}) error {\n\tif _, ok := ModifyFuncs[name]; ok {\n\t\treturn fmt.Errorf(\"function %s exist\", name)\n\t}\n\tModifyFuncs[name] = function\n\treturn nil\n}\n\nfunc (this Modify) Call(name string, params ... interface{}) (reflect.Value, error) {\n\tlog.Printf(\"modify call: func=%s args=%v\\n\", name, params)\n\n\tif _, ok := ModifyFuncs[name]; !ok {\n\t\treturn reflect.Value{}, fmt.Errorf(\"function %v not register\", name)\n\t}\n\n    f := reflect.ValueOf(ModifyFuncs[name])\n    if len(params) != f.Type().NumIn() {\n\t\treturn reflect.Value{}, errors.New(\"The number of params is not adapted.\")\n    }\n    in := make([]reflect.Value, len(params))\n    for k, param := range params {\n        in[k] = reflect.ValueOf(param)\n    }\n\treturn f.Call(in)[0], nil\n}\n\nfunc (this Modify) convert(val string) interface{} {\n\tif i, err := strconv.Atoi(val); err == nil {\n\t\treturn i\n\t} else if f, err := strconv.ParseFloat(val, 64); err == nil {\n\t\treturn f\n\t} else  if b, err := strconv.ParseBool(val); err == nil {\n\t\treturn b\n\t}\n\tb := []byte(val)\n\tif (b[0] == []byte(\"\\\"\")[0] && b[len(b) - 1] == []byte(\"\\\"\")[0]) ||\n\t\t(b[0] == []byte(\"'\")[0] && b[len(b) - 1] == []byte(\"'\")[0])\t{\n\t\treturn string(b[1:len(val)-1])\n\t}\n\treturn fmt.Sprintf(\"%v\", val)\n}\n\nfunc (this Modify) clearFunc(s []byte) []string {\n\treturn strings.Split(strings.TrimSpace(string([]byte(strings.TrimSpace(string(s)))[1:])), \"(\")\n}\n\nfunc (this Modify) clearArg(s []byte) string {\n\ta := []byte(strings.TrimSpace(string(s)))\n\tif a[0] == []byte(\",\")[0] {\n\t\treturn strings.TrimSpace(string(a[1:]))\n\t}\n\treturn string(a)\n}\n\nfunc (this Modify) parseFunc(s []byte) (string, []interface{}, error) {\n\tf := this.clearFunc(s)\n\tfuncName := f[0]\n\tfuncArgs := []interface{}{nil}\n\tif len(f) == 1 {\n\t\treturn funcName, funcArgs, nil\n\t}\n\tfl := lexer.NewLexer([]byte(f[1]))\n\tfor ftok := fl.Scan(); ftok.Type == token.TokMap.Type(\"arg\"); ftok = fl.Scan() {\n\t\tfuncArgs = append(funcArgs, this.convert(this.clearArg(ftok.Lit)))\n\t}\n\treturn funcName, funcArgs, nil\n}\n\nfunc (this Modify) resolve(v string) (string, error) {\n\t\/\/fmt.Printf(\"--> resolve: %v\\n\", v)\n\tif this.context == nil {\n\t\t\/\/fmt.Printf(\"<-- resolve: %v\\n\", v)\n\t\treturn v, nil\n\t}\n\tif value := this.context.Path(v).Data(); value != nil {\n\t\t\/\/fmt.Printf(\"find: %v\\n\", value)\n\t\tv = fmt.Sprintf(\"%v\", value)\n\t} else {\n\t\t\/\/fmt.Println(this.context.String())\n\t\t\/\/fmt.Printf(\"<-- resolve: %v\\n\", v)\n\t\treturn v, nil\n\t}\n\tif s, err := Template(v, this.context); err != nil {\n\t\t\/\/fmt.Println(\"<-- fuck\", v)\n\t\treturn v, nil\n\t} else {\n\t\t\/\/fmt.Println(\"<--\", v)\n\t\treturn s, nil\n\t}\n}\n\nfunc (this Modify) Exec(s string) (interface{}, error) {\n\tl := lexer.NewLexer([]byte(s))\n\tvar res interface{}\n\tres = nil\n\n\tfor tok := l.Scan(); (tok.Type == token.TokMap.Type(\"var\")) ||\n\t\t\t\t\t\t (tok.Type == token.TokMap.Type(\"func\")); tok = l.Scan() {\n\t\tswitch {\n\t\t\tcase tok.Type == token.TokMap.Type(\"var\"):\n\t\t\t\t\/\/fmt.Printf(\"var token: %v\\n\", string(tok.Lit))\n\t\t\t\tif val, err := this.resolve(string(tok.Lit)); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t} else {\n\t\t\t\t\tres = this.convert(val)\n\t\t\t\t}\n\t\t\tcase tok.Type == token.TokMap.Type(\"func\"):\n\t\t\t\t\/\/fmt.Printf(\"func token: %v\\n\", string(tok.Lit))\n\t\t\t\tif funcName, funcArgs, err := this.parseFunc(tok.Lit); err == nil {\n\t\t\t\t\tfuncArgs[0] = res\n\t\t\t\t\tif fv, err := this.Call(funcName, funcArgs...); err != nil {\n\t\t\t\t\t\treturn nil, fmt.Errorf(\"execution error %s: %v\", funcName, err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tres = this.convert(fv.String())\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error parse %s: %v\", tok.Lit, err )\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"unknown token %v\\n\", string(tok.Lit))\n\t\t}\n\t}\n\treturn res, nil\n}\n\nfunc ModifyExec(s interface{}, context *gabs.Container) (interface{}, error) {\n\tswitch s.(type) {\n\t\tcase string:\n\t\t\tif strings.Contains(s.(string), \"{{\") && strings.Contains(s.(string), \"}}\") {\n\t\t\t\treturn nil, fmt.Errorf(\"find symbols '{{' and '}}' in %v\", s)\n\t\t\t}\n\t\t\treturn Modify{context}.Exec(fmt.Sprintf(\"%v\",s))\n\t}\n\treturn s, nil\n}<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage acr\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\tcr \"github.com\/Azure\/azure-sdk-for-go\/services\/containerregistry\/mgmt\/2018-09-01\/containerregistry\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\/tag\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/docker\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/schema\/latest\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/util\"\n\t\"github.com\/pkg\/errors\"\n)\n\nconst BuildStatusHeader = \"x-ms-meta-Complete\"\n\nfunc (b *Builder) Build(ctx context.Context, out io.Writer, tagger tag.Tagger, artifacts []*latest.Artifact) ([]build.Artifact, error) {\n\treturn build.InParallel(ctx, out, tagger, artifacts, b.buildArtifact)\n}\n\nfunc (b *Builder) buildArtifact(ctx context.Context, out io.Writer, tagger tag.Tagger, artifact *latest.Artifact) (string, error) {\n\tclient, err := b.NewRegistriesClient()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get new registries client\")\n\t}\n\n\timageTag, err := tagger.GenerateFullyQualifiedImageName(artifact.Workspace, &tag.Options{\n\t\tDigest:    util.RandomID(),\n\t\tImageName: artifact.ImageName,\n\t})\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"create fully qualified image name\")\n\t}\n\tregistryName := getRegistryName(imageTag)\n\n\tresourceGroup, err := getResourceGroup(ctx, client, registryName)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get resource group\")\n\t}\n\n\tresult, err := client.GetBuildSourceUploadURL(ctx, resourceGroup, registryName)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"build source upload url\")\n\t}\n\tblob := NewBlobStorage(*result.UploadURL)\n\n\terr = docker.CreateDockerTarGzContext(ctx, blob.Buffer, artifact.Workspace, artifact.DockerArtifact)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"create context tar.gz\")\n\t}\n\n\terr = blob.UploadFileToBlob()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"upload file to blob\")\n\t}\n\n\t\/\/acr needs the image tag formatted as <repository>:<tag>\n\timageTag = getImageTagWithoutFQDN(imageTag)\n\n\tbuildRequest := cr.DockerBuildRequest{\n\t\tImageNames:     &[]string{imageTag},\n\t\tIsPushEnabled:  util.BoolPtr(true),\n\t\tSourceLocation: result.RelativePath,\n\t\tPlatform: &cr.PlatformProperties{\n\t\t\tVariant:      cr.V8,\n\t\t\tOs:           cr.Linux,\n\t\t\tArchitecture: cr.Amd64,\n\t\t},\n\t\tDockerFilePath: &artifact.DockerArtifact.DockerfilePath,\n\t\tType:           cr.TypeDockerBuildRequest,\n\t}\n\tfuture, err := client.ScheduleRun(ctx, resourceGroup, registryName, buildRequest)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"schedule build request\")\n\t}\n\n\trun, err := future.Result(*client)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get run id\")\n\t}\n\trunID := *run.RunID\n\n\trunsClient := cr.NewRunsClient(b.SubscriptionID)\n\trunsClient.Authorizer = client.Authorizer\n\tlogURL, err := runsClient.GetLogSasURL(ctx, resourceGroup, registryName, runID)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get log url\")\n\t}\n\n\terr = streamBuildLogs(*logURL.LogLink, out)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"polling build status\")\n\t}\n\n\treturn imageTag, nil\n}\n\nfunc streamBuildLogs(logURL string, out io.Writer) error {\n\toffset := int32(0)\n\tfor {\n\t\tresp, err := http.Get(logURL)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif resp.StatusCode == http.StatusNotFound {\n\t\t\t\/\/if blob is not available yet, try again\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\tscanner := bufio.NewScanner(resp.Body)\n\t\tline := int32(0)\n\t\tfor scanner.Scan() {\n\t\t\tif line >= offset {\n\t\t\t\tout.Write(scanner.Bytes())\n\t\t\t\tout.Write([]byte(\"\\n\"))\n\t\t\t\toffset++\n\t\t\t}\n\t\t\tline++\n\t\t}\n\t\tresp.Body.Close()\n\n\t\tif offset > 0 {\n\t\t\tswitch resp.Header.Get(BuildStatusHeader) {\n\t\t\tcase \"\":\n\t\t\t\tcontinue\n\t\t\tcase \"internalerror\":\n\t\t\tcase \"failed\":\n\t\t\t\treturn errors.New(\"run failed\")\n\t\t\tcase \"timedout\":\n\t\t\t\treturn errors.New(\"run timed out\")\n\t\t\tcase \"canceled\":\n\t\t\t\treturn errors.New(\"run was canceled\")\n\t\t\tdefault:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\t}\n}\n\nfunc getResourceGroup(ctx context.Context, client *cr.RegistriesClient, registryName string) (string, error) {\n\tregistryList, err := client.List(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, registry := range registryList.Values() {\n\t\tif strings.ToLower(*registry.Name) == registryName {\n\t\t\t\/\/registry.ID returns the exact path to the container registry\n\t\t\t\/\/e.g. \/subscriptions\/<subscriptionId>\/resourceGroups\/<resourceGroup>\/...\n\t\t\t\/\/so the resourceGroup is the fourth element of the split\n\t\t\treturn strings.Split(*registry.ID, \"\/\")[4], nil\n\t\t}\n\t}\n\n\treturn \"\", errors.New(\"Couldn't find resource group of registry\")\n}\n\nfunc getImageTagWithoutFQDN(imageTag string) string {\n\treturn imageTag[strings.Index(imageTag, \"\/\")+1:]\n}\n\n\/\/acr URL is <registryname>.azurecr.io\nfunc getRegistryName(imageTag string) string {\n\treturn strings.ToLower(imageTag[:strings.Index(imageTag, \".\")])\n}\n<commit_msg>Don't export build status header<commit_after>\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage acr\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\tcr \"github.com\/Azure\/azure-sdk-for-go\/services\/containerregistry\/mgmt\/2018-09-01\/containerregistry\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\/tag\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/docker\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/schema\/latest\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/util\"\n\t\"github.com\/pkg\/errors\"\n)\n\nconst buildStatusHeader = \"x-ms-meta-Complete\"\n\nfunc (b *Builder) Build(ctx context.Context, out io.Writer, tagger tag.Tagger, artifacts []*latest.Artifact) ([]build.Artifact, error) {\n\treturn build.InParallel(ctx, out, tagger, artifacts, b.buildArtifact)\n}\n\nfunc (b *Builder) buildArtifact(ctx context.Context, out io.Writer, tagger tag.Tagger, artifact *latest.Artifact) (string, error) {\n\tclient, err := b.NewRegistriesClient()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get new registries client\")\n\t}\n\n\timageTag, err := tagger.GenerateFullyQualifiedImageName(artifact.Workspace, &tag.Options{\n\t\tDigest:    util.RandomID(),\n\t\tImageName: artifact.ImageName,\n\t})\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"create fully qualified image name\")\n\t}\n\tregistryName := getRegistryName(imageTag)\n\n\tresourceGroup, err := getResourceGroup(ctx, client, registryName)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get resource group\")\n\t}\n\n\tresult, err := client.GetBuildSourceUploadURL(ctx, resourceGroup, registryName)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"build source upload url\")\n\t}\n\tblob := NewBlobStorage(*result.UploadURL)\n\n\terr = docker.CreateDockerTarGzContext(ctx, blob.Buffer, artifact.Workspace, artifact.DockerArtifact)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"create context tar.gz\")\n\t}\n\n\terr = blob.UploadFileToBlob()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"upload file to blob\")\n\t}\n\n\t\/\/acr needs the image tag formatted as <repository>:<tag>\n\timageTag = getImageTagWithoutFQDN(imageTag)\n\n\tbuildRequest := cr.DockerBuildRequest{\n\t\tImageNames:     &[]string{imageTag},\n\t\tIsPushEnabled:  util.BoolPtr(true),\n\t\tSourceLocation: result.RelativePath,\n\t\tPlatform: &cr.PlatformProperties{\n\t\t\tVariant:      cr.V8,\n\t\t\tOs:           cr.Linux,\n\t\t\tArchitecture: cr.Amd64,\n\t\t},\n\t\tDockerFilePath: &artifact.DockerArtifact.DockerfilePath,\n\t\tType:           cr.TypeDockerBuildRequest,\n\t}\n\tfuture, err := client.ScheduleRun(ctx, resourceGroup, registryName, buildRequest)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"schedule build request\")\n\t}\n\n\trun, err := future.Result(*client)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get run id\")\n\t}\n\trunID := *run.RunID\n\n\trunsClient := cr.NewRunsClient(b.SubscriptionID)\n\trunsClient.Authorizer = client.Authorizer\n\tlogURL, err := runsClient.GetLogSasURL(ctx, resourceGroup, registryName, runID)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get log url\")\n\t}\n\n\terr = streamBuildLogs(*logURL.LogLink, out)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"polling build status\")\n\t}\n\n\treturn imageTag, nil\n}\n\nfunc streamBuildLogs(logURL string, out io.Writer) error {\n\toffset := int32(0)\n\tfor {\n\t\tresp, err := http.Get(logURL)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif resp.StatusCode == http.StatusNotFound {\n\t\t\t\/\/if blob is not available yet, try again\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\tscanner := bufio.NewScanner(resp.Body)\n\t\tline := int32(0)\n\t\tfor scanner.Scan() {\n\t\t\tif line >= offset {\n\t\t\t\tout.Write(scanner.Bytes())\n\t\t\t\tout.Write([]byte(\"\\n\"))\n\t\t\t\toffset++\n\t\t\t}\n\t\t\tline++\n\t\t}\n\t\tresp.Body.Close()\n\n\t\tif offset > 0 {\n\t\t\tswitch resp.Header.Get(buildStatusHeader) {\n\t\t\tcase \"\":\n\t\t\t\tcontinue\n\t\t\tcase \"internalerror\":\n\t\t\tcase \"failed\":\n\t\t\t\treturn errors.New(\"run failed\")\n\t\t\tcase \"timedout\":\n\t\t\t\treturn errors.New(\"run timed out\")\n\t\t\tcase \"canceled\":\n\t\t\t\treturn errors.New(\"run was canceled\")\n\t\t\tdefault:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\t}\n}\n\nfunc getResourceGroup(ctx context.Context, client *cr.RegistriesClient, registryName string) (string, error) {\n\tregistryList, err := client.List(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, registry := range registryList.Values() {\n\t\tif strings.ToLower(*registry.Name) == registryName {\n\t\t\t\/\/registry.ID returns the exact path to the container registry\n\t\t\t\/\/e.g. \/subscriptions\/<subscriptionId>\/resourceGroups\/<resourceGroup>\/...\n\t\t\t\/\/so the resourceGroup is the fourth element of the split\n\t\t\treturn strings.Split(*registry.ID, \"\/\")[4], nil\n\t\t}\n\t}\n\n\treturn \"\", errors.New(\"Couldn't find resource group of registry\")\n}\n\nfunc getImageTagWithoutFQDN(imageTag string) string {\n\treturn imageTag[strings.Index(imageTag, \"\/\")+1:]\n}\n\n\/\/acr URL is <registryname>.azurecr.io\nfunc getRegistryName(imageTag string) string {\n\treturn strings.ToLower(imageTag[:strings.Index(imageTag, \".\")])\n}\n<|endoftext|>"}
{"text":"<commit_before>package xor\n\nimport (\n\t\"testing\"\n\t\"time\"\n\t\"os\"\n\t\"fmt\"\n\t\"github.com\/yaricom\/goNEAT\/neat\"\n\t\"github.com\/yaricom\/goNEAT\/neat\/genetics\"\n\t\"math\/rand\"\n\t\"github.com\/yaricom\/goNEAT\/experiments\"\n)\n\n\/\/ The integration test running over multiple iterations in order to detect if any random errors occur.\nfunc TestXOR(t *testing.T) {\n\t\/\/ the numbers will be different every time we run.\n\trand.Seed(time.Now().Unix())\n\n\tout_dir_path, context_path, genome_path := \"..\/..\/out\", \"..\/..\/data\/xor.neat\", \"..\/..\/data\/xorstartgenes\"\n\n\t\/\/ Load context configuration\n\tconfigFile, err := os.Open(context_path)\n\tif err != nil {\n\t\tt.Error(\"Failed to load context\", err)\n\t\treturn\n\t}\n\tcontext := neat.LoadContext(configFile)\n\tneat.LogLevel = neat.LogLevelInfo\n\n\t\/\/ Load Genome\n\tfmt.Println(\"Loading start genome for XOR experiment\")\n\tgenomeFile, err := os.Open(genome_path)\n\tif err != nil {\n\t\tt.Error(\"Failed to open genome file\")\n\t\treturn\n\t}\n\tstart_genome, err := genetics.ReadGenome(genomeFile, 1)\n\tif err != nil {\n\t\tt.Error(\"Failed to read start genome\")\n\t\treturn\n\t}\n\n\t\/\/ Check if output dir exists\n\tif _, err := os.Stat(out_dir_path); err == nil {\n\t\t\/\/ clear it\n\t\tos.RemoveAll(out_dir_path)\n\t}\n\t\/\/ create output dir\n\terr = os.MkdirAll(out_dir_path, os.ModePerm)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create output directory, reason: %s\", err)\n\t\treturn\n\t}\n\n\t\/\/ The 100 runs XOR experiment\n\tcontext.NumRuns = 100\n\texperiment := experiments.Experiment {\n\t\tId:0,\n\t\tTrials:make(experiments.Trials, context.NumRuns),\n\t}\n\terr = XOR(context, start_genome, out_dir_path, &experiment)\n\tif err != nil {\n\t\tt.Error(\"Failed to perform XOR experiment:\", err)\n\t\treturn\n\t}\n\n\t\/\/ Find winner statistics\n\tavg_nodes, avg_genes, avg_evals := experiment.AvgWinnerNGE()\n\n\t\/\/ check results\n\tif avg_nodes < 5 {\n\t\tt.Error(\"avg_nodes < 5\", avg_nodes)\n\t} else if avg_nodes > 15 {\n\t\tt.Error(\"avg_nodes > 15\", avg_nodes)\n\t}\n\n\tif avg_genes < 7 {\n\t\tt.Error(\"avg_genes < 7\", avg_genes)\n\t} else if avg_genes > 20 {\n\t\tt.Error(\"avg_genes > 20\", avg_genes)\n\t}\n\n\tmax_evals := float64(context.PopSize * context.NumGenerations)\n\tif avg_evals > max_evals {\n\t\tt.Error(\"avg_evals > max_evals\", avg_evals, max_evals)\n\t}\n\n\tt.Logf(\"avg_nodes: %.1f, avg_genes: %.1f, avg_evals: %.1f\\n\", avg_nodes, avg_genes, avg_evals)\n\tmean_complexity, mean_diversity, mean_age := 0.0, 0.0, 0.0\n\tfor _, t := range experiment.Trials {\n\t\tmean_complexity += t.Complexity().Mean()\n\t\tmean_diversity += t.Diversity().Mean()\n\t\tmean_age += t.Age().Mean()\n\t}\n\tcount := float64(len(experiment.Trials))\n\tmean_complexity \/= count\n\tmean_diversity \/= count\n\tmean_age \/= count\n\tt.Logf(\"mean: complexity=%.1f, diversity=%.1f, age=%.1f\", mean_complexity, mean_diversity, mean_age)\n}\n\n\n\/\/ The XOR integration test for disconnected inputs running over multiple iterations in order to detect if any random errors occur.\nfunc TestXOR_disconnected(t *testing.T) {\n\t\/\/ the numbers will be different every time we run.\n\trand.Seed(time.Now().Unix())\n\n\tout_dir_path, context_path, genome_path := \"..\/..\/out\", \"..\/..\/data\/xor.neat\", \"..\/..\/data\/xorstartgenes\"\n\n\t\/\/ Load context configuration\n\tconfigFile, err := os.Open(context_path)\n\tif err != nil {\n\t\tt.Error(\"Failed to load context\", err)\n\t\treturn\n\t}\n\tcontext := neat.LoadContext(configFile)\n\tneat.LogLevel = neat.LogLevelInfo\n\n\t\/\/ Load Genome\n\tfmt.Println(\"Loading start genome for XOR experiment\")\n\tgenomeFile, err := os.Open(genome_path)\n\tif err != nil {\n\t\tt.Error(\"Failed to open genome file\")\n\t\treturn\n\t}\n\tstart_genome, err := genetics.ReadGenome(genomeFile, 1)\n\tif err != nil {\n\t\tt.Error(\"Failed to read start genome\")\n\t\treturn\n\t}\n\n\t\/\/ Check if output dir exists\n\tif _, err := os.Stat(out_dir_path); err == nil {\n\t\t\/\/ clear it\n\t\tos.RemoveAll(out_dir_path)\n\t}\n\t\/\/ create output dir\n\terr = os.MkdirAll(out_dir_path, os.ModePerm)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create output directory, reason: %s\", err)\n\t\treturn\n\t}\n\n\t\/\/ The 100 runs XOR experiment\n\tcontext.NumRuns = 100\n\texperiment := experiments.Experiment {\n\t\tId:0,\n\t\tTrials:make(experiments.Trials, context.NumRuns),\n\t}\n\terr = XOR(context, start_genome, out_dir_path, &experiment)\n\tif err != nil {\n\t\tt.Error(\"Failed to perform XOR experiment:\", err)\n\t\treturn\n\t}\n\n\t\/\/ Find winner statistics\n\tavg_nodes, avg_genes, avg_evals := experiment.AvgWinnerNGE()\n\n\t\/\/ check results\n\tif avg_nodes < 5 {\n\t\tt.Error(\"avg_nodes < 5\", avg_nodes)\n\t} else if avg_nodes > 15 {\n\t\tt.Error(\"avg_nodes > 15\", avg_nodes)\n\t}\n\n\tif avg_genes < 7 {\n\t\tt.Error(\"avg_genes < 7\", avg_genes)\n\t} else if avg_genes > 20 {\n\t\tt.Error(\"avg_genes > 20\", avg_genes)\n\t}\n\n\tmax_evals := float64(context.PopSize * context.NumGenerations)\n\tif avg_evals > max_evals {\n\t\tt.Error(\"avg_evals > max_evals\", avg_evals, max_evals)\n\t}\n\n\tt.Logf(\"avg_nodes: %.1f, avg_genes: %.1f, avg_evals: %.1f\\n\", avg_nodes, avg_genes, avg_evals)\n\tmean_complexity, mean_diversity, mean_age := 0.0, 0.0, 0.0\n\tfor _, t := range experiment.Trials {\n\t\tmean_complexity += t.Complexity().Mean()\n\t\tmean_diversity += t.Diversity().Mean()\n\t\tmean_age += t.Age().Mean()\n\t}\n\tcount := float64(len(experiment.Trials))\n\tmean_complexity \/= count\n\tmean_diversity \/= count\n\tmean_age \/= count\n\tt.Logf(\"mean: complexity=%.1f, diversity=%.1f, age=%.1f\", mean_complexity, mean_diversity, mean_age)\n}<commit_msg>Fixes in order to use updated experiment generalization.<commit_after>package xor\n\nimport (\n\t\"testing\"\n\t\"time\"\n\t\"os\"\n\t\"fmt\"\n\t\"github.com\/yaricom\/goNEAT\/neat\"\n\t\"github.com\/yaricom\/goNEAT\/neat\/genetics\"\n\t\"math\/rand\"\n\t\"github.com\/yaricom\/goNEAT\/experiments\"\n)\n\n\/\/ The integration test running over multiple iterations in order to detect if any random errors occur.\nfunc TestXOR(t *testing.T) {\n\t\/\/ the numbers will be different every time we run.\n\trand.Seed(time.Now().Unix())\n\n\tout_dir_path, context_path, genome_path := \"..\/..\/out\", \"..\/..\/data\/xor.neat\", \"..\/..\/data\/xorstartgenes\"\n\n\t\/\/ Load context configuration\n\tconfigFile, err := os.Open(context_path)\n\tif err != nil {\n\t\tt.Error(\"Failed to load context\", err)\n\t\treturn\n\t}\n\tcontext := neat.LoadContext(configFile)\n\tneat.LogLevel = neat.LogLevelInfo\n\n\t\/\/ Load Genome\n\tfmt.Println(\"Loading start genome for XOR experiment\")\n\tgenomeFile, err := os.Open(genome_path)\n\tif err != nil {\n\t\tt.Error(\"Failed to open genome file\")\n\t\treturn\n\t}\n\tstart_genome, err := genetics.ReadGenome(genomeFile, 1)\n\tif err != nil {\n\t\tt.Error(\"Failed to read start genome\")\n\t\treturn\n\t}\n\n\t\/\/ Check if output dir exists\n\tif _, err := os.Stat(out_dir_path); err == nil {\n\t\t\/\/ clear it\n\t\tos.RemoveAll(out_dir_path)\n\t}\n\t\/\/ create output dir\n\terr = os.MkdirAll(out_dir_path, os.ModePerm)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create output directory, reason: %s\", err)\n\t\treturn\n\t}\n\n\t\/\/ The 100 runs XOR experiment\n\tcontext.NumRuns = 100\n\texperiment := experiments.Experiment {\n\t\tId:0,\n\t\tTrials:make(experiments.Trials, context.NumRuns),\n\t}\n\terr = experiment.Execute(context, start_genome, XOREpochEvaluator{OutputPath:out_dir_path})\n\tif err != nil {\n\t\tt.Error(\"Failed to perform XOR experiment:\", err)\n\t\treturn\n\t}\n\n\t\/\/ Find winner statistics\n\tavg_nodes, avg_genes, avg_evals := experiment.AvgWinnerNGE()\n\n\t\/\/ check results\n\tif avg_nodes < 5 {\n\t\tt.Error(\"avg_nodes < 5\", avg_nodes)\n\t} else if avg_nodes > 15 {\n\t\tt.Error(\"avg_nodes > 15\", avg_nodes)\n\t}\n\n\tif avg_genes < 7 {\n\t\tt.Error(\"avg_genes < 7\", avg_genes)\n\t} else if avg_genes > 20 {\n\t\tt.Error(\"avg_genes > 20\", avg_genes)\n\t}\n\n\tmax_evals := float64(context.PopSize * context.NumGenerations)\n\tif avg_evals > max_evals {\n\t\tt.Error(\"avg_evals > max_evals\", avg_evals, max_evals)\n\t}\n\n\tt.Logf(\"avg_nodes: %.1f, avg_genes: %.1f, avg_evals: %.1f\\n\", avg_nodes, avg_genes, avg_evals)\n\tmean_complexity, mean_diversity, mean_age := 0.0, 0.0, 0.0\n\tfor _, t := range experiment.Trials {\n\t\tmean_complexity += t.Complexity().Mean()\n\t\tmean_diversity += t.Diversity().Mean()\n\t\tmean_age += t.Age().Mean()\n\t}\n\tcount := float64(len(experiment.Trials))\n\tmean_complexity \/= count\n\tmean_diversity \/= count\n\tmean_age \/= count\n\tt.Logf(\"mean: complexity=%.1f, diversity=%.1f, age=%.1f\", mean_complexity, mean_diversity, mean_age)\n}\n\n\n\/\/ The XOR integration test for disconnected inputs running over multiple iterations in order to detect if any random errors occur.\nfunc TestXOR_disconnected(t *testing.T) {\n\t\/\/ the numbers will be different every time we run.\n\trand.Seed(time.Now().Unix())\n\n\tout_dir_path, context_path, genome_path := \"..\/..\/out\", \"..\/..\/data\/xor.neat\", \"..\/..\/data\/xorstartgenes\"\n\n\t\/\/ Load context configuration\n\tconfigFile, err := os.Open(context_path)\n\tif err != nil {\n\t\tt.Error(\"Failed to load context\", err)\n\t\treturn\n\t}\n\tcontext := neat.LoadContext(configFile)\n\tneat.LogLevel = neat.LogLevelInfo\n\n\t\/\/ Load Genome\n\tfmt.Println(\"Loading start genome for XOR experiment\")\n\tgenomeFile, err := os.Open(genome_path)\n\tif err != nil {\n\t\tt.Error(\"Failed to open genome file\")\n\t\treturn\n\t}\n\tstart_genome, err := genetics.ReadGenome(genomeFile, 1)\n\tif err != nil {\n\t\tt.Error(\"Failed to read start genome\")\n\t\treturn\n\t}\n\n\t\/\/ Check if output dir exists\n\tif _, err := os.Stat(out_dir_path); err == nil {\n\t\t\/\/ clear it\n\t\tos.RemoveAll(out_dir_path)\n\t}\n\t\/\/ create output dir\n\terr = os.MkdirAll(out_dir_path, os.ModePerm)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to create output directory, reason: %s\", err)\n\t\treturn\n\t}\n\n\t\/\/ The 100 runs XOR experiment\n\tcontext.NumRuns = 100\n\texperiment := experiments.Experiment {\n\t\tId:0,\n\t\tTrials:make(experiments.Trials, context.NumRuns),\n\t}\n\terr = experiment.Execute(context, start_genome, XOREpochEvaluator{OutputPath:out_dir_path})\n\tif err != nil {\n\t\tt.Error(\"Failed to perform XOR experiment:\", err)\n\t\treturn\n\t}\n\n\t\/\/ Find winner statistics\n\tavg_nodes, avg_genes, avg_evals := experiment.AvgWinnerNGE()\n\n\t\/\/ check results\n\tif avg_nodes < 5 {\n\t\tt.Error(\"avg_nodes < 5\", avg_nodes)\n\t} else if avg_nodes > 15 {\n\t\tt.Error(\"avg_nodes > 15\", avg_nodes)\n\t}\n\n\tif avg_genes < 7 {\n\t\tt.Error(\"avg_genes < 7\", avg_genes)\n\t} else if avg_genes > 20 {\n\t\tt.Error(\"avg_genes > 20\", avg_genes)\n\t}\n\n\tmax_evals := float64(context.PopSize * context.NumGenerations)\n\tif avg_evals > max_evals {\n\t\tt.Error(\"avg_evals > max_evals\", avg_evals, max_evals)\n\t}\n\n\tt.Logf(\"avg_nodes: %.1f, avg_genes: %.1f, avg_evals: %.1f\\n\", avg_nodes, avg_genes, avg_evals)\n\tmean_complexity, mean_diversity, mean_age := 0.0, 0.0, 0.0\n\tfor _, t := range experiment.Trials {\n\t\tmean_complexity += t.Complexity().Mean()\n\t\tmean_diversity += t.Diversity().Mean()\n\t\tmean_age += t.Age().Mean()\n\t}\n\tcount := float64(len(experiment.Trials))\n\tmean_complexity \/= count\n\tmean_diversity \/= count\n\tmean_age \/= count\n\tt.Logf(\"mean: complexity=%.1f, diversity=%.1f, age=%.1f\", mean_complexity, mean_diversity, mean_age)\n}<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Fission Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cms\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.uber.org\/zap\"\n\tapiv1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/fields\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n\n\tfv1 \"github.com\/fission\/fission\/pkg\/apis\/fission.io\/v1\"\n\t\"github.com\/fission\/fission\/pkg\/crd\"\n\tnd \"github.com\/fission\/fission\/pkg\/executor\/newdeploy\"\n\tgpm \"github.com\/fission\/fission\/pkg\/executor\/poolmgr\"\n)\n\ntype (\n\tConfigSecretController struct {\n\t\tlogger *zap.Logger\n\n\t\tconfigmapController cache.Controller\n\t\tsecretController    cache.Controller\n\n\t\tfissionClient *crd.FissionClient\n\t}\n)\n\n\/\/MakeConfigSecretController makes a controller for configmaps and secrets which changes related functions\nfunc MakeConfigSecretController(logger *zap.Logger, fissionClient *crd.FissionClient,\n\tkubernetesClient *kubernetes.Clientset, ndm *nd.NewDeploy, gpm *gpm.GenericPoolManager) *ConfigSecretController {\n\tlogger.Debug(\"Creating ConfigMap & Secret Controller\")\n\t_, cmcontroller := initConfigmapController(logger, fissionClient, kubernetesClient, ndm, gpm)\n\t_, scontroller := initSecretController(logger, fissionClient, kubernetesClient, ndm, gpm)\n\tcmsController := &ConfigSecretController{\n\t\tlogger:              logger,\n\t\tconfigmapController: cmcontroller,\n\t\tsecretController:    scontroller,\n\t\tfissionClient:       fissionClient,\n\t}\n\treturn cmsController\n}\n\n\/\/Run runs the controllers for configmaps and secrets\nfunc (csController *ConfigSecretController) Run(ctx context.Context) {\n\tgo csController.configmapController.Run(ctx.Done())\n\tgo csController.secretController.Run(ctx.Done())\n}\n\nfunc initConfigmapController(logger *zap.Logger, fissionClient *crd.FissionClient,\n\tkubernetesClient *kubernetes.Clientset, ndm *nd.NewDeploy, gpm *gpm.GenericPoolManager) (cache.Store, cache.Controller) {\n\tresyncPeriod := 30 * time.Second\n\tlistWatch := cache.NewListWatchFromClient(kubernetesClient.AppsV1().RESTClient(), \"configmaps\", metav1.NamespaceAll, fields.Everything())\n\tstore, controller := cache.NewInformer(listWatch, &apiv1.ConfigMap{}, resyncPeriod, cache.ResourceEventHandlerFuncs{\n\t\tAddFunc:    func(obj interface{}) {},\n\t\tDeleteFunc: func(obj interface{}) {},\n\t\tUpdateFunc: func(oldObj interface{}, newObj interface{}) {\n\t\t\toldCm := oldObj.(*apiv1.ConfigMap)\n\t\t\tnewCm := newObj.(*apiv1.ConfigMap)\n\t\t\tif oldCm.ObjectMeta.ResourceVersion != newCm.ObjectMeta.ResourceVersion {\n\t\t\t\tif newCm.ObjectMeta.Namespace != \"kube-system\" {\n\t\t\t\t\tlogger.Debug(\"Configmap changed\",\n\t\t\t\t\t\tzap.String(\"configmap_name\", newCm.ObjectMeta.Name),\n\t\t\t\t\t\tzap.String(\"configmap_namespace\", newCm.ObjectMeta.Namespace))\n\n\t\t\t\t}\n\n\t\t\t\tfuncs, err := getConfigmapRelatedFuncs(logger, &newCm.ObjectMeta, fissionClient)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(\"Failed to get functions related to secret\", zap.String(\"secret_name\", newCm.ObjectMeta.Name), zap.String(\"secret_namespace\", newCm.ObjectMeta.Namespace))\n\t\t\t\t}\n\t\t\t\trecyclePods(logger, funcs, ndm, gpm)\n\t\t\t}\n\n\t\t},\n\t})\n\treturn store, controller\n}\n\nfunc getConfigmapRelatedFuncs(logger *zap.Logger, m *metav1.ObjectMeta, fissionClient *crd.FissionClient) ([]fv1.Function, error) {\n\tfuncList, err := fissionClient.Functions(metav1.NamespaceAll).List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ In future a cache that populates at start and is updated on changes might be better solution\n\trelatedFunctions := make([]fv1.Function, 0)\n\tfor _, f := range funcList.Items {\n\t\tfor _, cm := range f.Spec.ConfigMaps {\n\t\t\tif (cm.Name == m.Name) && (cm.Namespace == m.Namespace) {\n\t\t\t\trelatedFunctions = append(relatedFunctions, f)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn relatedFunctions, nil\n}\n\nfunc initSecretController(logger *zap.Logger, fissionClient *crd.FissionClient,\n\tkubernetesClient *kubernetes.Clientset, ndm *nd.NewDeploy, gpm *gpm.GenericPoolManager) (cache.Store, cache.Controller) {\n\tresyncPeriod := 30 * time.Second\n\tlistWatch := cache.NewListWatchFromClient(kubernetesClient.AppsV1().RESTClient(), \"secrets\", metav1.NamespaceAll, fields.Everything())\n\tstore, controller := cache.NewInformer(listWatch, &apiv1.Secret{}, resyncPeriod, cache.ResourceEventHandlerFuncs{\n\t\tAddFunc:    func(obj interface{}) {},\n\t\tDeleteFunc: func(obj interface{}) {},\n\t\tUpdateFunc: func(oldObj interface{}, newObj interface{}) {\n\t\t\toldS := oldObj.(*apiv1.Secret)\n\t\t\tnewS := newObj.(*apiv1.Secret)\n\t\t\tif oldS.ObjectMeta.ResourceVersion != newS.ObjectMeta.ResourceVersion {\n\t\t\t\tif newS.ObjectMeta.Namespace != \"kube-system\" {\n\t\t\t\t\tlogger.Debug(\"Secret changed\",\n\t\t\t\t\t\tzap.String(\"configmap_name\", newS.ObjectMeta.Name),\n\t\t\t\t\t\tzap.String(\"configmap_namespace\", newS.ObjectMeta.Namespace))\n\n\t\t\t\t}\n\n\t\t\t\tfuncs, err := getSecretRelatedFuncs(logger, &newS.ObjectMeta, fissionClient)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(\"Failed to get functions related to secret\", zap.String(\"secret_name\", newS.ObjectMeta.Name), zap.String(\"secret_namespace\", newS.ObjectMeta.Namespace))\n\t\t\t\t}\n\t\t\t\trecyclePods(logger, funcs, ndm, gpm)\n\t\t\t}\n\n\t\t},\n\t})\n\treturn store, controller\n\n}\n\nfunc getSecretRelatedFuncs(logger *zap.Logger, m *metav1.ObjectMeta, fissionClient *crd.FissionClient) ([]fv1.Function, error) {\n\tfuncList, err := fissionClient.Functions(metav1.NamespaceAll).List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ In future a cache that populates at start and is updated on changes might be better solution\n\trelatedFunctions := make([]fv1.Function, 0)\n\tfor _, f := range funcList.Items {\n\t\tfor _, secret := range f.Spec.Secrets {\n\t\t\tif (secret.Name == m.Name) && (secret.Namespace == m.Namespace) {\n\t\t\t\trelatedFunctions = append(relatedFunctions, f)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn relatedFunctions, nil\n}\n\nfunc recyclePods(logger *zap.Logger, funcs []fv1.Function, ndm *nd.NewDeploy, gpm *gpm.GenericPoolManager) {\n\tfor _, f := range funcs {\n\t\tvar err error\n\n\t\tswitch f.Spec.InvokeStrategy.ExecutionStrategy.ExecutorType {\n\t\tcase fv1.ExecutorTypeNewdeploy:\n\t\t\terr = ndm.RefreshFuncPods(logger, f)\n\t\tcase fv1.ExecutorTypePoolmgr:\n\t\t\terr = gpm.RefreshFuncPods(logger, f)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Failed to recycle pods for function after configmap changed\",\n\t\t\t\tzap.Error(err),\n\t\t\t\tzap.Any(\"function\", f))\n\t\t}\n\t}\n}\n<commit_msg>Fix executor unable to list secrets\/configmaps (#1307)<commit_after>\/*\nCopyright 2016 The Fission Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cms\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.uber.org\/zap\"\n\tapiv1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/fields\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n\n\tfv1 \"github.com\/fission\/fission\/pkg\/apis\/fission.io\/v1\"\n\t\"github.com\/fission\/fission\/pkg\/crd\"\n\tnd \"github.com\/fission\/fission\/pkg\/executor\/newdeploy\"\n\tgpm \"github.com\/fission\/fission\/pkg\/executor\/poolmgr\"\n)\n\ntype (\n\tConfigSecretController struct {\n\t\tlogger *zap.Logger\n\n\t\tconfigmapController cache.Controller\n\t\tsecretController    cache.Controller\n\n\t\tfissionClient *crd.FissionClient\n\t}\n)\n\n\/\/MakeConfigSecretController makes a controller for configmaps and secrets which changes related functions\nfunc MakeConfigSecretController(logger *zap.Logger, fissionClient *crd.FissionClient,\n\tkubernetesClient *kubernetes.Clientset, ndm *nd.NewDeploy, gpm *gpm.GenericPoolManager) *ConfigSecretController {\n\tlogger.Debug(\"Creating ConfigMap & Secret Controller\")\n\t_, cmcontroller := initConfigmapController(logger, fissionClient, kubernetesClient, ndm, gpm)\n\t_, scontroller := initSecretController(logger, fissionClient, kubernetesClient, ndm, gpm)\n\tcmsController := &ConfigSecretController{\n\t\tlogger:              logger,\n\t\tconfigmapController: cmcontroller,\n\t\tsecretController:    scontroller,\n\t\tfissionClient:       fissionClient,\n\t}\n\treturn cmsController\n}\n\n\/\/Run runs the controllers for configmaps and secrets\nfunc (csController *ConfigSecretController) Run(ctx context.Context) {\n\tgo csController.configmapController.Run(ctx.Done())\n\tgo csController.secretController.Run(ctx.Done())\n}\n\nfunc initConfigmapController(logger *zap.Logger, fissionClient *crd.FissionClient,\n\tkubernetesClient *kubernetes.Clientset, ndm *nd.NewDeploy, gpm *gpm.GenericPoolManager) (cache.Store, cache.Controller) {\n\tresyncPeriod := 30 * time.Second\n\tlistWatch := cache.NewListWatchFromClient(kubernetesClient.CoreV1().RESTClient(), \"configmaps\", metav1.NamespaceAll, fields.Everything())\n\tstore, controller := cache.NewInformer(listWatch, &apiv1.ConfigMap{}, resyncPeriod, cache.ResourceEventHandlerFuncs{\n\t\tAddFunc:    func(obj interface{}) {},\n\t\tDeleteFunc: func(obj interface{}) {},\n\t\tUpdateFunc: func(oldObj interface{}, newObj interface{}) {\n\t\t\toldCm := oldObj.(*apiv1.ConfigMap)\n\t\t\tnewCm := newObj.(*apiv1.ConfigMap)\n\t\t\tif oldCm.ObjectMeta.ResourceVersion != newCm.ObjectMeta.ResourceVersion {\n\t\t\t\tif newCm.ObjectMeta.Namespace != \"kube-system\" {\n\t\t\t\t\tlogger.Debug(\"Configmap changed\",\n\t\t\t\t\t\tzap.String(\"configmap_name\", newCm.ObjectMeta.Name),\n\t\t\t\t\t\tzap.String(\"configmap_namespace\", newCm.ObjectMeta.Namespace))\n\t\t\t\t}\n\n\t\t\t\tfuncs, err := getConfigmapRelatedFuncs(logger, &newCm.ObjectMeta, fissionClient)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(\"Failed to get functions related to secret\", zap.String(\"secret_name\", newCm.ObjectMeta.Name), zap.String(\"secret_namespace\", newCm.ObjectMeta.Namespace))\n\t\t\t\t}\n\t\t\t\trecyclePods(logger, funcs, ndm, gpm)\n\t\t\t}\n\t\t},\n\t})\n\treturn store, controller\n}\n\nfunc getConfigmapRelatedFuncs(logger *zap.Logger, m *metav1.ObjectMeta, fissionClient *crd.FissionClient) ([]fv1.Function, error) {\n\tfuncList, err := fissionClient.Functions(metav1.NamespaceAll).List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ In future a cache that populates at start and is updated on changes might be better solution\n\trelatedFunctions := make([]fv1.Function, 0)\n\tfor _, f := range funcList.Items {\n\t\tfor _, cm := range f.Spec.ConfigMaps {\n\t\t\tif (cm.Name == m.Name) && (cm.Namespace == m.Namespace) {\n\t\t\t\trelatedFunctions = append(relatedFunctions, f)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn relatedFunctions, nil\n}\n\nfunc initSecretController(logger *zap.Logger, fissionClient *crd.FissionClient,\n\tkubernetesClient *kubernetes.Clientset, ndm *nd.NewDeploy, gpm *gpm.GenericPoolManager) (cache.Store, cache.Controller) {\n\tresyncPeriod := 30 * time.Second\n\tlistWatch := cache.NewListWatchFromClient(kubernetesClient.CoreV1().RESTClient(), \"secrets\", metav1.NamespaceAll, fields.Everything())\n\tstore, controller := cache.NewInformer(listWatch, &apiv1.Secret{}, resyncPeriod, cache.ResourceEventHandlerFuncs{\n\t\tAddFunc:    func(obj interface{}) {},\n\t\tDeleteFunc: func(obj interface{}) {},\n\t\tUpdateFunc: func(oldObj interface{}, newObj interface{}) {\n\t\t\toldS := oldObj.(*apiv1.Secret)\n\t\t\tnewS := newObj.(*apiv1.Secret)\n\t\t\tif oldS.ObjectMeta.ResourceVersion != newS.ObjectMeta.ResourceVersion {\n\t\t\t\tif newS.ObjectMeta.Namespace != \"kube-system\" {\n\t\t\t\t\tlogger.Debug(\"Secret changed\",\n\t\t\t\t\t\tzap.String(\"configmap_name\", newS.ObjectMeta.Name),\n\t\t\t\t\t\tzap.String(\"configmap_namespace\", newS.ObjectMeta.Namespace))\n\n\t\t\t\t}\n\n\t\t\t\tfuncs, err := getSecretRelatedFuncs(logger, &newS.ObjectMeta, fissionClient)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(\"Failed to get functions related to secret\", zap.String(\"secret_name\", newS.ObjectMeta.Name), zap.String(\"secret_namespace\", newS.ObjectMeta.Namespace))\n\t\t\t\t}\n\t\t\t\trecyclePods(logger, funcs, ndm, gpm)\n\t\t\t}\n\n\t\t},\n\t})\n\treturn store, controller\n\n}\n\nfunc getSecretRelatedFuncs(logger *zap.Logger, m *metav1.ObjectMeta, fissionClient *crd.FissionClient) ([]fv1.Function, error) {\n\tfuncList, err := fissionClient.Functions(metav1.NamespaceAll).List(metav1.ListOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ In future a cache that populates at start and is updated on changes might be better solution\n\trelatedFunctions := make([]fv1.Function, 0)\n\tfor _, f := range funcList.Items {\n\t\tfor _, secret := range f.Spec.Secrets {\n\t\t\tif (secret.Name == m.Name) && (secret.Namespace == m.Namespace) {\n\t\t\t\trelatedFunctions = append(relatedFunctions, f)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn relatedFunctions, nil\n}\n\nfunc recyclePods(logger *zap.Logger, funcs []fv1.Function, ndm *nd.NewDeploy, gpm *gpm.GenericPoolManager) {\n\tfor _, f := range funcs {\n\t\tvar err error\n\n\t\tswitch f.Spec.InvokeStrategy.ExecutionStrategy.ExecutorType {\n\t\tcase fv1.ExecutorTypeNewdeploy:\n\t\t\terr = ndm.RefreshFuncPods(logger, f)\n\t\tcase fv1.ExecutorTypePoolmgr:\n\t\t\terr = gpm.RefreshFuncPods(logger, f)\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Failed to recycle pods for function after configmap changed\",\n\t\t\t\tzap.Error(err),\n\t\t\t\tzap.Any(\"function\", f))\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 The gVisor Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage stack\n\nimport (\n\t\"fmt\"\n\n\t\"gvisor.dev\/gvisor\/pkg\/log\"\n\t\"gvisor.dev\/gvisor\/pkg\/tcpip\"\n\t\"gvisor.dev\/gvisor\/pkg\/tcpip\/header\"\n)\n\n\/\/ AcceptTarget accepts packets.\ntype AcceptTarget struct {\n\t\/\/ NetworkProtocol is the network protocol the target is used with.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (*AcceptTarget) Action(*PacketBuffer, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\n\treturn RuleAccept, 0\n}\n\n\/\/ DropTarget drops packets.\ntype DropTarget struct {\n\t\/\/ NetworkProtocol is the network protocol the target is used with.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (*DropTarget) Action(*PacketBuffer, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\n\treturn RuleDrop, 0\n}\n\n\/\/ ErrorTarget logs an error and drops the packet. It represents a target that\n\/\/ should be unreachable.\ntype ErrorTarget struct {\n\t\/\/ NetworkProtocol is the network protocol the target is used with.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (*ErrorTarget) Action(*PacketBuffer, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\n\tlog.Debugf(\"ErrorTarget triggered.\")\n\treturn RuleDrop, 0\n}\n\n\/\/ UserChainTarget marks a rule as the beginning of a user chain.\ntype UserChainTarget struct {\n\t\/\/ Name is the chain name.\n\tName string\n\n\t\/\/ NetworkProtocol is the network protocol the target is used with.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (*UserChainTarget) Action(*PacketBuffer, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\n\tpanic(\"UserChainTarget should never be called.\")\n}\n\n\/\/ ReturnTarget returns from the current chain. If the chain is a built-in, the\n\/\/ hook's underflow should be called.\ntype ReturnTarget struct {\n\t\/\/ NetworkProtocol is the network protocol the target is used with.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (*ReturnTarget) Action(*PacketBuffer, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\n\treturn RuleReturn, 0\n}\n\n\/\/ RedirectTarget redirects the packet to this machine by modifying the\n\/\/ destination port\/IP. Outgoing packets are redirected to the loopback device,\n\/\/ and incoming packets are redirected to the incoming interface (rather than\n\/\/ forwarded).\ntype RedirectTarget struct {\n\t\/\/ Port indicates port used to redirect. It is immutable.\n\tPort uint16\n\n\t\/\/ NetworkProtocol is the network protocol the target is used with. It\n\t\/\/ is immutable.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (rt *RedirectTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, addressEP AddressableEndpoint) (RuleVerdict, int) {\n\t\/\/ Sanity check.\n\tif rt.NetworkProtocol != pkt.NetworkProtocolNumber {\n\t\tpanic(fmt.Sprintf(\n\t\t\t\"RedirectTarget.Action with NetworkProtocol %d called on packet with NetworkProtocolNumber %d\",\n\t\t\trt.NetworkProtocol, pkt.NetworkProtocolNumber))\n\t}\n\n\t\/\/ Packet is already manipulated.\n\tif pkt.NatDone {\n\t\treturn RuleAccept, 0\n\t}\n\n\t\/\/ Drop the packet if network and transport header are not set.\n\tif pkt.NetworkHeader().View().IsEmpty() || pkt.TransportHeader().View().IsEmpty() {\n\t\treturn RuleDrop, 0\n\t}\n\n\t\/\/ Change the address to loopback (127.0.0.1 or ::1) in Output and to\n\t\/\/ the primary address of the incoming interface in Prerouting.\n\tvar address tcpip.Address\n\tswitch hook {\n\tcase Output:\n\t\tif pkt.NetworkProtocolNumber == header.IPv4ProtocolNumber {\n\t\t\taddress = tcpip.Address([]byte{127, 0, 0, 1})\n\t\t} else {\n\t\t\taddress = header.IPv6Loopback\n\t\t}\n\tcase Prerouting:\n\t\t\/\/ addressEP is expected to be set for the prerouting hook.\n\t\taddress = addressEP.MainAddress().Address\n\tdefault:\n\t\tpanic(\"redirect target is supported only on output and prerouting hooks\")\n\t}\n\n\tswitch protocol := pkt.TransportProtocolNumber; protocol {\n\tcase header.UDPProtocolNumber:\n\t\tudpHeader := header.UDP(pkt.TransportHeader().View())\n\n\t\tif hook == Output {\n\t\t\t\/\/ Only calculate the checksum if offloading isn't supported.\n\t\t\trequiresChecksum := r.RequiresTXTransportChecksum()\n\t\t\trewritePacket(\n\t\t\t\tpkt.Network(),\n\t\t\t\tudpHeader,\n\t\t\t\tfalse, \/* updateSRCFields *\/\n\t\t\t\trequiresChecksum,\n\t\t\t\trequiresChecksum,\n\t\t\t\trt.Port,\n\t\t\t\taddress,\n\t\t\t)\n\t\t} else {\n\t\t\tudpHeader.SetDestinationPort(rt.Port)\n\t\t}\n\n\t\tpkt.NatDone = true\n\tcase header.TCPProtocolNumber:\n\t\tif t := pkt.tuple; t != nil {\n\t\t\tt.conn.performNAT(pkt, hook, r, rt.Port, address, true \/* dnat *\/)\n\t\t}\n\tdefault:\n\t\treturn RuleDrop, 0\n\t}\n\n\treturn RuleAccept, 0\n}\n\n\/\/ SNATTarget modifies the source port\/IP in the outgoing packets.\ntype SNATTarget struct {\n\tAddr tcpip.Address\n\tPort uint16\n\n\t\/\/ NetworkProtocol is the network protocol the target is used with. It\n\t\/\/ is immutable.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\nfunc snatAction(pkt *PacketBuffer, hook Hook, r *Route, port uint16, address tcpip.Address) (RuleVerdict, int) {\n\t\/\/ Packet is already manipulated.\n\tif pkt.NatDone {\n\t\treturn RuleAccept, 0\n\t}\n\n\t\/\/ Drop the packet if network and transport header are not set.\n\tif pkt.NetworkHeader().View().IsEmpty() || pkt.TransportHeader().View().IsEmpty() {\n\t\treturn RuleDrop, 0\n\t}\n\n\t\/\/ TODO(https:\/\/gvisor.dev\/issue\/5773): If the port is in use, pick a\n\t\/\/ different port.\n\tif port == 0 {\n\t\tswitch protocol := pkt.TransportProtocolNumber; protocol {\n\t\tcase header.UDPProtocolNumber:\n\t\t\tport = header.UDP(pkt.TransportHeader().View()).SourcePort()\n\t\tcase header.TCPProtocolNumber:\n\t\t\tport = header.TCP(pkt.TransportHeader().View()).SourcePort()\n\t\t}\n\t}\n\n\tif t := pkt.tuple; t != nil {\n\t\tt.conn.performNAT(pkt, hook, r, port, address, false \/* dnat *\/)\n\t}\n\n\treturn RuleAccept, 0\n}\n\n\/\/ Action implements Target.Action.\nfunc (st *SNATTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, _ AddressableEndpoint) (RuleVerdict, int) {\n\t\/\/ Sanity check.\n\tif st.NetworkProtocol != pkt.NetworkProtocolNumber {\n\t\tpanic(fmt.Sprintf(\n\t\t\t\"SNATTarget.Action with NetworkProtocol %d called on packet with NetworkProtocolNumber %d\",\n\t\t\tst.NetworkProtocol, pkt.NetworkProtocolNumber))\n\t}\n\n\tswitch hook {\n\tcase Postrouting, Input:\n\tcase Prerouting, Output, Forward:\n\t\tpanic(fmt.Sprintf(\"%s not supported\", hook))\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"%s unrecognized\", hook))\n\t}\n\n\treturn snatAction(pkt, hook, r, st.Port, st.Addr)\n}\n\n\/\/ MasqueradeTarget modifies the source port\/IP in the outgoing packets.\ntype MasqueradeTarget struct {\n\t\/\/ NetworkProtocol is the network protocol the target is used with. It\n\t\/\/ is immutable.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (mt *MasqueradeTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, addressEP AddressableEndpoint) (RuleVerdict, int) {\n\t\/\/ Sanity check.\n\tif mt.NetworkProtocol != pkt.NetworkProtocolNumber {\n\t\tpanic(fmt.Sprintf(\n\t\t\t\"MasqueradeTarget.Action with NetworkProtocol %d called on packet with NetworkProtocolNumber %d\",\n\t\t\tmt.NetworkProtocol, pkt.NetworkProtocolNumber))\n\t}\n\n\tswitch hook {\n\tcase Postrouting:\n\tcase Prerouting, Input, Forward, Output:\n\t\tpanic(fmt.Sprintf(\"masquerade target is supported only on postrouting hook; hook = %d\", hook))\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"%s unrecognized\", hook))\n\t}\n\n\t\/\/ addressEP is expected to be set for the postrouting hook.\n\tep := addressEP.AcquireOutgoingPrimaryAddress(pkt.Network().DestinationAddress(), false \/* allowExpired *\/)\n\tif ep == nil {\n\t\t\/\/ No address exists that we can use as a source address.\n\t\treturn RuleDrop, 0\n\t}\n\n\taddress := ep.AddressWithPrefix().Address\n\tep.DecRef()\n\treturn snatAction(pkt, hook, r, 0 \/* port *\/, address)\n}\n\nfunc rewritePacket(n header.Network, t header.ChecksummableTransport, updateSRCFields, fullChecksum, updatePseudoHeader bool, newPort uint16, newAddr tcpip.Address) {\n\tif updateSRCFields {\n\t\tif fullChecksum {\n\t\t\tt.SetSourcePortWithChecksumUpdate(newPort)\n\t\t} else {\n\t\t\tt.SetSourcePort(newPort)\n\t\t}\n\t} else {\n\t\tif fullChecksum {\n\t\t\tt.SetDestinationPortWithChecksumUpdate(newPort)\n\t\t} else {\n\t\t\tt.SetDestinationPort(newPort)\n\t\t}\n\t}\n\n\tif updatePseudoHeader {\n\t\tvar oldAddr tcpip.Address\n\t\tif updateSRCFields {\n\t\t\toldAddr = n.SourceAddress()\n\t\t} else {\n\t\t\toldAddr = n.DestinationAddress()\n\t\t}\n\n\t\tt.UpdateChecksumPseudoHeaderAddress(oldAddr, newAddr, fullChecksum)\n\t}\n\n\tif checksummableNetHeader, ok := n.(header.ChecksummableNetwork); ok {\n\t\tif updateSRCFields {\n\t\t\tchecksummableNetHeader.SetSourceAddressWithChecksumUpdate(newAddr)\n\t\t} else {\n\t\t\tchecksummableNetHeader.SetDestinationAddressWithChecksumUpdate(newAddr)\n\t\t}\n\t} else if updateSRCFields {\n\t\tn.SetSourceAddress(newAddr)\n\t} else {\n\t\tn.SetDestinationAddress(newAddr)\n\t}\n}\n<commit_msg>Track UDP packets performing REDIRECT NAT<commit_after>\/\/ Copyright 2019 The gVisor Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage stack\n\nimport (\n\t\"fmt\"\n\n\t\"gvisor.dev\/gvisor\/pkg\/log\"\n\t\"gvisor.dev\/gvisor\/pkg\/tcpip\"\n\t\"gvisor.dev\/gvisor\/pkg\/tcpip\/header\"\n)\n\n\/\/ AcceptTarget accepts packets.\ntype AcceptTarget struct {\n\t\/\/ NetworkProtocol is the network protocol the target is used with.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (*AcceptTarget) Action(*PacketBuffer, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\n\treturn RuleAccept, 0\n}\n\n\/\/ DropTarget drops packets.\ntype DropTarget struct {\n\t\/\/ NetworkProtocol is the network protocol the target is used with.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (*DropTarget) Action(*PacketBuffer, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\n\treturn RuleDrop, 0\n}\n\n\/\/ ErrorTarget logs an error and drops the packet. It represents a target that\n\/\/ should be unreachable.\ntype ErrorTarget struct {\n\t\/\/ NetworkProtocol is the network protocol the target is used with.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (*ErrorTarget) Action(*PacketBuffer, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\n\tlog.Debugf(\"ErrorTarget triggered.\")\n\treturn RuleDrop, 0\n}\n\n\/\/ UserChainTarget marks a rule as the beginning of a user chain.\ntype UserChainTarget struct {\n\t\/\/ Name is the chain name.\n\tName string\n\n\t\/\/ NetworkProtocol is the network protocol the target is used with.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (*UserChainTarget) Action(*PacketBuffer, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\n\tpanic(\"UserChainTarget should never be called.\")\n}\n\n\/\/ ReturnTarget returns from the current chain. If the chain is a built-in, the\n\/\/ hook's underflow should be called.\ntype ReturnTarget struct {\n\t\/\/ NetworkProtocol is the network protocol the target is used with.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (*ReturnTarget) Action(*PacketBuffer, Hook, *Route, AddressableEndpoint) (RuleVerdict, int) {\n\treturn RuleReturn, 0\n}\n\n\/\/ RedirectTarget redirects the packet to this machine by modifying the\n\/\/ destination port\/IP. Outgoing packets are redirected to the loopback device,\n\/\/ and incoming packets are redirected to the incoming interface (rather than\n\/\/ forwarded).\ntype RedirectTarget struct {\n\t\/\/ Port indicates port used to redirect. It is immutable.\n\tPort uint16\n\n\t\/\/ NetworkProtocol is the network protocol the target is used with. It\n\t\/\/ is immutable.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (rt *RedirectTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, addressEP AddressableEndpoint) (RuleVerdict, int) {\n\t\/\/ Sanity check.\n\tif rt.NetworkProtocol != pkt.NetworkProtocolNumber {\n\t\tpanic(fmt.Sprintf(\n\t\t\t\"RedirectTarget.Action with NetworkProtocol %d called on packet with NetworkProtocolNumber %d\",\n\t\t\trt.NetworkProtocol, pkt.NetworkProtocolNumber))\n\t}\n\n\t\/\/ Packet is already manipulated.\n\tif pkt.NatDone {\n\t\treturn RuleAccept, 0\n\t}\n\n\t\/\/ Drop the packet if network and transport header are not set.\n\tif pkt.NetworkHeader().View().IsEmpty() || pkt.TransportHeader().View().IsEmpty() {\n\t\treturn RuleDrop, 0\n\t}\n\n\t\/\/ Change the address to loopback (127.0.0.1 or ::1) in Output and to\n\t\/\/ the primary address of the incoming interface in Prerouting.\n\tvar address tcpip.Address\n\tswitch hook {\n\tcase Output:\n\t\tif pkt.NetworkProtocolNumber == header.IPv4ProtocolNumber {\n\t\t\taddress = tcpip.Address([]byte{127, 0, 0, 1})\n\t\t} else {\n\t\t\taddress = header.IPv6Loopback\n\t\t}\n\tcase Prerouting:\n\t\t\/\/ addressEP is expected to be set for the prerouting hook.\n\t\taddress = addressEP.MainAddress().Address\n\tdefault:\n\t\tpanic(\"redirect target is supported only on output and prerouting hooks\")\n\t}\n\n\tif t := pkt.tuple; t != nil {\n\t\tt.conn.performNAT(pkt, hook, r, rt.Port, address, true \/* dnat *\/)\n\t\treturn RuleAccept, 0\n\t}\n\n\treturn RuleDrop, 0\n}\n\n\/\/ SNATTarget modifies the source port\/IP in the outgoing packets.\ntype SNATTarget struct {\n\tAddr tcpip.Address\n\tPort uint16\n\n\t\/\/ NetworkProtocol is the network protocol the target is used with. It\n\t\/\/ is immutable.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\nfunc snatAction(pkt *PacketBuffer, hook Hook, r *Route, port uint16, address tcpip.Address) (RuleVerdict, int) {\n\t\/\/ Packet is already manipulated.\n\tif pkt.NatDone {\n\t\treturn RuleAccept, 0\n\t}\n\n\t\/\/ Drop the packet if network and transport header are not set.\n\tif pkt.NetworkHeader().View().IsEmpty() || pkt.TransportHeader().View().IsEmpty() {\n\t\treturn RuleDrop, 0\n\t}\n\n\t\/\/ TODO(https:\/\/gvisor.dev\/issue\/5773): If the port is in use, pick a\n\t\/\/ different port.\n\tif port == 0 {\n\t\tswitch protocol := pkt.TransportProtocolNumber; protocol {\n\t\tcase header.UDPProtocolNumber:\n\t\t\tport = header.UDP(pkt.TransportHeader().View()).SourcePort()\n\t\tcase header.TCPProtocolNumber:\n\t\t\tport = header.TCP(pkt.TransportHeader().View()).SourcePort()\n\t\t}\n\t}\n\n\tif t := pkt.tuple; t != nil {\n\t\tt.conn.performNAT(pkt, hook, r, port, address, false \/* dnat *\/)\n\t}\n\n\treturn RuleAccept, 0\n}\n\n\/\/ Action implements Target.Action.\nfunc (st *SNATTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, _ AddressableEndpoint) (RuleVerdict, int) {\n\t\/\/ Sanity check.\n\tif st.NetworkProtocol != pkt.NetworkProtocolNumber {\n\t\tpanic(fmt.Sprintf(\n\t\t\t\"SNATTarget.Action with NetworkProtocol %d called on packet with NetworkProtocolNumber %d\",\n\t\t\tst.NetworkProtocol, pkt.NetworkProtocolNumber))\n\t}\n\n\tswitch hook {\n\tcase Postrouting, Input:\n\tcase Prerouting, Output, Forward:\n\t\tpanic(fmt.Sprintf(\"%s not supported\", hook))\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"%s unrecognized\", hook))\n\t}\n\n\treturn snatAction(pkt, hook, r, st.Port, st.Addr)\n}\n\n\/\/ MasqueradeTarget modifies the source port\/IP in the outgoing packets.\ntype MasqueradeTarget struct {\n\t\/\/ NetworkProtocol is the network protocol the target is used with. It\n\t\/\/ is immutable.\n\tNetworkProtocol tcpip.NetworkProtocolNumber\n}\n\n\/\/ Action implements Target.Action.\nfunc (mt *MasqueradeTarget) Action(pkt *PacketBuffer, hook Hook, r *Route, addressEP AddressableEndpoint) (RuleVerdict, int) {\n\t\/\/ Sanity check.\n\tif mt.NetworkProtocol != pkt.NetworkProtocolNumber {\n\t\tpanic(fmt.Sprintf(\n\t\t\t\"MasqueradeTarget.Action with NetworkProtocol %d called on packet with NetworkProtocolNumber %d\",\n\t\t\tmt.NetworkProtocol, pkt.NetworkProtocolNumber))\n\t}\n\n\tswitch hook {\n\tcase Postrouting:\n\tcase Prerouting, Input, Forward, Output:\n\t\tpanic(fmt.Sprintf(\"masquerade target is supported only on postrouting hook; hook = %d\", hook))\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"%s unrecognized\", hook))\n\t}\n\n\t\/\/ addressEP is expected to be set for the postrouting hook.\n\tep := addressEP.AcquireOutgoingPrimaryAddress(pkt.Network().DestinationAddress(), false \/* allowExpired *\/)\n\tif ep == nil {\n\t\t\/\/ No address exists that we can use as a source address.\n\t\treturn RuleDrop, 0\n\t}\n\n\taddress := ep.AddressWithPrefix().Address\n\tep.DecRef()\n\treturn snatAction(pkt, hook, r, 0 \/* port *\/, address)\n}\n\nfunc rewritePacket(n header.Network, t header.ChecksummableTransport, updateSRCFields, fullChecksum, updatePseudoHeader bool, newPort uint16, newAddr tcpip.Address) {\n\tif updateSRCFields {\n\t\tif fullChecksum {\n\t\t\tt.SetSourcePortWithChecksumUpdate(newPort)\n\t\t} else {\n\t\t\tt.SetSourcePort(newPort)\n\t\t}\n\t} else {\n\t\tif fullChecksum {\n\t\t\tt.SetDestinationPortWithChecksumUpdate(newPort)\n\t\t} else {\n\t\t\tt.SetDestinationPort(newPort)\n\t\t}\n\t}\n\n\tif updatePseudoHeader {\n\t\tvar oldAddr tcpip.Address\n\t\tif updateSRCFields {\n\t\t\toldAddr = n.SourceAddress()\n\t\t} else {\n\t\t\toldAddr = n.DestinationAddress()\n\t\t}\n\n\t\tt.UpdateChecksumPseudoHeaderAddress(oldAddr, newAddr, fullChecksum)\n\t}\n\n\tif checksummableNetHeader, ok := n.(header.ChecksummableNetwork); ok {\n\t\tif updateSRCFields {\n\t\t\tchecksummableNetHeader.SetSourceAddressWithChecksumUpdate(newAddr)\n\t\t} else {\n\t\t\tchecksummableNetHeader.SetDestinationAddressWithChecksumUpdate(newAddr)\n\t\t}\n\t} else if updateSRCFields {\n\t\tn.SetSourceAddress(newAddr)\n\t} else {\n\t\tn.SetDestinationAddress(newAddr)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ SPDX-License-Identifier: Apache-2.0\n\/\/ Copyright 2018 Authors of Cilium\n\n\/\/go:build !privileged_tests\n\/\/ +build !privileged_tests\n\npackage dnsproxy\n\nimport (\n\t. \"gopkg.in\/check.v1\"\n)\n\ntype DNSProxyHelperTestSuite struct{}\n\nvar _ = Suite(&DNSProxyHelperTestSuite{})\n<commit_msg>dnsproxy: unit test GetSelectorRegexMap<commit_after>\/\/ SPDX-License-Identifier: Apache-2.0\n\/\/ Copyright 2018 Authors of Cilium\n\n\/\/go:build !privileged_tests\n\/\/ +build !privileged_tests\n\npackage dnsproxy\n\nimport (\n\t\"github.com\/cilium\/cilium\/pkg\/identity\"\n\t\"github.com\/cilium\/cilium\/pkg\/policy\"\n\t\"github.com\/cilium\/cilium\/pkg\/policy\/api\"\n\t\"github.com\/golang\/groupcache\/lru\"\n\t. \"gopkg.in\/check.v1\"\n\t\"testing\"\n)\n\ntype DNSProxyHelperTestSuite struct{}\n\nvar _ = Suite(&DNSProxyHelperTestSuite{})\n\n\/\/ Hook up gocheck into the \"go test\" runner.\nfunc TestNonPrivileged(t *testing.T) {\n\tTestingT(t)\n}\n\nfunc (s *DNSProxyHelperTestSuite) TestGetSelectorRegexMap(c *C) {\n\tselector := MockCachedSelector{}\n\n\tdnsName := \"example.name.\"\n\n\tl7 := policy.L7DataMap{\n\t\tselector: &policy.PerSelectorPolicy{\n\t\t\tL7Rules: api.L7Rules{DNS: []api.PortRuleDNS{\n\t\t\t\t{\n\t\t\t\t\tMatchName: dnsName,\n\t\t\t\t},\n\t\t\t}},\n\t\t},\n\t}\n\tcache := &lru.Cache{}\n\tm, err := GetSelectorRegexMap(l7, cache)\n\n\tc.Assert(err, Equals, nil)\n\n\tregex, ok := m[selector]\n\n\tc.Assert(ok, Equals, true)\n\n\tc.Assert(regex.MatchString(dnsName), Equals, true)\n\tc.Assert(regex.MatchString(dnsName+\"trolo\"), Equals, false)\n}\n\ntype MockCachedSelector struct{}\n\nfunc (m MockCachedSelector) GetSelections() []identity.NumericIdentity {\n\treturn nil\n}\n\nfunc (m MockCachedSelector) Selects(_ identity.NumericIdentity) bool {\n\treturn false\n}\n\nfunc (m MockCachedSelector) IsWildcard() bool {\n\treturn false\n}\n\nfunc (m MockCachedSelector) IsNone() bool {\n\treturn false\n}\n\nfunc (m MockCachedSelector) String() string {\n\treturn \"string\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package alerting\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"golang.org\/x\/sync\/errgroup\"\n\n\t\"github.com\/grafana\/grafana\/pkg\/bus\"\n\t\"github.com\/grafana\/grafana\/pkg\/components\/imguploader\"\n\t\"github.com\/grafana\/grafana\/pkg\/components\/renderer\"\n\t\"github.com\/grafana\/grafana\/pkg\/log\"\n\tm \"github.com\/grafana\/grafana\/pkg\/models\"\n)\n\ntype RootNotifier struct {\n\tlog log.Logger\n}\n\nfunc NewRootNotifier() *RootNotifier {\n\treturn &RootNotifier{\n\t\tlog: log.New(\"alerting.notifier\"),\n\t}\n}\n\nfunc (n *RootNotifier) GetType() string {\n\treturn \"root\"\n}\n\nfunc (n *RootNotifier) NeedsImage() bool {\n\treturn false\n}\n\nfunc (n *RootNotifier) PassesFilter(rule *Rule) bool {\n\treturn false\n}\n\nfunc (n *RootNotifier) GetNotifierId() int64 {\n\treturn 0\n}\n\nfunc (n *RootNotifier) GetIsDefault() bool {\n\treturn false\n}\n\nfunc (n *RootNotifier) Notify(context *EvalContext) error {\n\tnotifiers, err := n.getNotifiers(context.Rule.OrgId, context.Rule.Notifications, context)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn.log.Info(\"Sending notifications for\", \"ruleId\", context.Rule.Id, \"sent count\", len(notifiers))\n\n\tif len(notifiers) == 0 {\n\t\treturn nil\n\t}\n\n\terr = n.uploadImage(context)\n\tif err != nil {\n\t\tn.log.Error(\"Failed to upload alert panel image\", \"error\", err)\n\t\treturn err\n\t}\n\n\treturn n.sendNotifications(context, notifiers)\n}\n\nfunc (n *RootNotifier) sendNotifications(context *EvalContext, notifiers []Notifier) error {\n\tg, _ := errgroup.WithContext(context.Ctx)\n\n\tfor _, notifier := range notifiers {\n\t\tnot := notifier \/\/avoid updating scope variable in go routine\n\t\tn.log.Info(\"Sending notification\", \"type\", not.GetType(), \"id\", not.GetNotifierId(), \"isDefault\", not.GetIsDefault())\n\t\tg.Go(func() error { return not.Notify(context) })\n\t}\n\n\treturn g.Wait()\n}\n\nfunc (n *RootNotifier) uploadImage(context *EvalContext) (err error) {\n\tuploader, err := imguploader.NewImageUploader()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trenderOpts := &renderer.RenderOpts{\n\t\tWidth:   \"800\",\n\t\tHeight:  \"400\",\n\t\tTimeout: \"30\",\n\t\tOrgId:   context.Rule.OrgId,\n\t}\n\n\tif slug, err := context.GetDashboardSlug(); err != nil {\n\t\treturn err\n\t} else {\n\t\trenderOpts.Path = fmt.Sprintf(\"dashboard-solo\/db\/%s?&panelId=%d\", slug, context.Rule.PanelId)\n\t}\n\n\tif imagePath, err := renderer.RenderToPng(renderOpts); err != nil {\n\t\treturn err\n\t} else {\n\t\tcontext.ImageOnDiskPath = imagePath\n\t}\n\n\tcontext.ImagePublicUrl, err = uploader.Upload(context.ImageOnDiskPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn.log.Info(\"uploaded\", \"url\", context.ImagePublicUrl)\n\treturn nil\n}\n\nfunc (n *RootNotifier) getNotifiers(orgId int64, notificationIds []int64, context *EvalContext) ([]Notifier, error) {\n\tquery := &m.GetAlertNotificationsToSendQuery{OrgId: orgId, Ids: notificationIds}\n\n\tif err := bus.Dispatch(query); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result []Notifier\n\tfor _, notification := range query.Result {\n\t\tif not, err := n.createNotifierFor(notification); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tif shouldUseNotification(not, context) {\n\t\t\t\tresult = append(result, not)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result, nil\n}\n\nfunc (n *RootNotifier) createNotifierFor(model *m.AlertNotification) (Notifier, error) {\n\tfactory, found := notifierFactories[model.Type]\n\tif !found {\n\t\treturn nil, errors.New(\"Unsupported notification type\")\n\t}\n\n\treturn factory(model)\n}\n\nfunc shouldUseNotification(notifier Notifier, context *EvalContext) bool {\n\tif !context.Firing {\n\t\treturn true\n\t}\n\n\tif context.Error != nil {\n\t\treturn true\n\t}\n\n\treturn notifier.PassesFilter(context.Rule)\n}\n\ntype NotifierFactory func(notification *m.AlertNotification) (Notifier, error)\n\nvar notifierFactories map[string]NotifierFactory = make(map[string]NotifierFactory)\n\nfunc RegisterNotifier(typeName string, factory NotifierFactory) {\n\tnotifierFactories[typeName] = factory\n}\n<commit_msg>fix(notifications): failed image upload should not stop notification<commit_after>package alerting\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"golang.org\/x\/sync\/errgroup\"\n\n\t\"github.com\/grafana\/grafana\/pkg\/bus\"\n\t\"github.com\/grafana\/grafana\/pkg\/components\/imguploader\"\n\t\"github.com\/grafana\/grafana\/pkg\/components\/renderer\"\n\t\"github.com\/grafana\/grafana\/pkg\/log\"\n\tm \"github.com\/grafana\/grafana\/pkg\/models\"\n)\n\ntype RootNotifier struct {\n\tlog log.Logger\n}\n\nfunc NewRootNotifier() *RootNotifier {\n\treturn &RootNotifier{\n\t\tlog: log.New(\"alerting.notifier\"),\n\t}\n}\n\nfunc (n *RootNotifier) GetType() string {\n\treturn \"root\"\n}\n\nfunc (n *RootNotifier) NeedsImage() bool {\n\treturn false\n}\n\nfunc (n *RootNotifier) PassesFilter(rule *Rule) bool {\n\treturn false\n}\n\nfunc (n *RootNotifier) GetNotifierId() int64 {\n\treturn 0\n}\n\nfunc (n *RootNotifier) GetIsDefault() bool {\n\treturn false\n}\n\nfunc (n *RootNotifier) Notify(context *EvalContext) error {\n\tnotifiers, err := n.getNotifiers(context.Rule.OrgId, context.Rule.Notifications, context)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn.log.Info(\"Sending notifications for\", \"ruleId\", context.Rule.Id, \"sent count\", len(notifiers))\n\n\tif len(notifiers) == 0 {\n\t\treturn nil\n\t}\n\n\tif err = n.uploadImage(context); err != nil {\n\t\tn.log.Error(\"Failed to upload alert panel image.\", \"error\", err)\n\t}\n\n\treturn n.sendNotifications(context, notifiers)\n}\n\nfunc (n *RootNotifier) sendNotifications(context *EvalContext, notifiers []Notifier) error {\n\tg, _ := errgroup.WithContext(context.Ctx)\n\n\tfor _, notifier := range notifiers {\n\t\tnot := notifier \/\/avoid updating scope variable in go routine\n\t\tn.log.Info(\"Sending notification\", \"type\", not.GetType(), \"id\", not.GetNotifierId(), \"isDefault\", not.GetIsDefault())\n\t\tg.Go(func() error { return not.Notify(context) })\n\t}\n\n\treturn g.Wait()\n}\n\nfunc (n *RootNotifier) uploadImage(context *EvalContext) (err error) {\n\tuploader, err := imguploader.NewImageUploader()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trenderOpts := &renderer.RenderOpts{\n\t\tWidth:   \"800\",\n\t\tHeight:  \"400\",\n\t\tTimeout: \"30\",\n\t\tOrgId:   context.Rule.OrgId,\n\t}\n\n\tif slug, err := context.GetDashboardSlug(); err != nil {\n\t\treturn err\n\t} else {\n\t\trenderOpts.Path = fmt.Sprintf(\"dashboard-solo\/db\/%s?&panelId=%d\", slug, context.Rule.PanelId)\n\t}\n\n\tif imagePath, err := renderer.RenderToPng(renderOpts); err != nil {\n\t\treturn err\n\t} else {\n\t\tcontext.ImageOnDiskPath = imagePath\n\t}\n\n\tcontext.ImagePublicUrl, err = uploader.Upload(context.ImageOnDiskPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn.log.Info(\"uploaded\", \"url\", context.ImagePublicUrl)\n\treturn nil\n}\n\nfunc (n *RootNotifier) getNotifiers(orgId int64, notificationIds []int64, context *EvalContext) ([]Notifier, error) {\n\tquery := &m.GetAlertNotificationsToSendQuery{OrgId: orgId, Ids: notificationIds}\n\n\tif err := bus.Dispatch(query); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar result []Notifier\n\tfor _, notification := range query.Result {\n\t\tif not, err := n.createNotifierFor(notification); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tif shouldUseNotification(not, context) {\n\t\t\t\tresult = append(result, not)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result, nil\n}\n\nfunc (n *RootNotifier) createNotifierFor(model *m.AlertNotification) (Notifier, error) {\n\tfactory, found := notifierFactories[model.Type]\n\tif !found {\n\t\treturn nil, errors.New(\"Unsupported notification type\")\n\t}\n\n\treturn factory(model)\n}\n\nfunc shouldUseNotification(notifier Notifier, context *EvalContext) bool {\n\tif !context.Firing {\n\t\treturn true\n\t}\n\n\tif context.Error != nil {\n\t\treturn true\n\t}\n\n\treturn notifier.PassesFilter(context.Rule)\n}\n\ntype NotifierFactory func(notification *m.AlertNotification) (Notifier, error)\n\nvar notifierFactories map[string]NotifierFactory = make(map[string]NotifierFactory)\n\nfunc RegisterNotifier(typeName string, factory NotifierFactory) {\n\tnotifierFactories[typeName] = factory\n}\n<|endoftext|>"}
{"text":"<commit_before>package slack\n\n\/\/ @NOTE: Blocks are in beta and subject to change.\n\n\/\/ More Information: https:\/\/api.slack.com\/block-kit\n\n\/\/ MessageBlockType defines a named string type to define each block type\n\/\/ as a constant for use within the package.\ntype MessageBlockType string\n\nconst (\n\tMBTSection MessageBlockType = \"section\"\n\tMBTDivider MessageBlockType = \"divider\"\n\tMBTImage   MessageBlockType = \"image\"\n\tMBTAction  MessageBlockType = \"actions\"\n\tMBTContext MessageBlockType = \"context\"\n)\n\n\/\/ Block defines an interface all block types should implement\n\/\/ to ensure consistency between blocks.\ntype Block interface {\n\tBlockType() MessageBlockType\n}\n\n\/\/ Blocks is a convenience struct defined to allow dynamic unmarshalling of\n\/\/ the \"blocks\" value in Slack's JSON response, which varies depending on block type\ntype Blocks struct {\n\tBlockSet []Block `json:\"blocks,omitempty\"`\n}\n\n\/\/ BlockAction is the action callback sent when a block is interacted with\ntype BlockAction struct {\n\tActionID             string            `json:\"action_id\"`\n\tBlockID              string            `json:\"block_id\"`\n\tType                 actionType        `json:\"type\"`\n\tText                 TextBlockObject   `json:\"text\"`\n\tValue                string            `json:\"value\"`\n\tActionTs             string            `json:\"action_ts\"`\n\tSelectedOption       OptionBlockObject `json:\"selected_option\"`\n\tSelectedUser         string            `json:\"selected_user\"`\n\tSelectedChannel      string            `json:\"selected_channel\"`\n\tSelectedConversation string            `json:\"selected_conversation\"`\n\tSelectedDate         string            `json:\"selected_date\"`\n\tInitialOption        OptionBlockObject `json:\"initial_option\"`\n\tInitialUser          string            `json:\"initial_user\"`\n\tInitialChannel       string            `json:\"initial_channel\"`\n\tInitialConversation  string            `json:\"initial_conversation\"`\n\tInitialDate          string            `json:\"initial_date\"`\n}\n\n\/\/ actionType returns the type of the action\nfunc (b BlockAction) actionType() actionType {\n\treturn b.Type\n}\n\n\/\/ NewBlockMessage creates a new Message that contains one or more blocks to be displayed\nfunc NewBlockMessage(blocks ...Block) Message {\n\treturn Message{\n\t\tMsg: Msg{\n\t\t\tBlocks: Blocks{\n\t\t\t\tBlockSet: blocks,\n\t\t\t},\n\t\t},\n\t}\n}\n\n\/\/ AddBlockMessage appends a block to the end of the existing list of blocks\nfunc AddBlockMessage(message Message, newBlk Block) Message {\n\tmessage.Msg.Blocks.BlockSet = append(message.Msg.Blocks.BlockSet, newBlk)\n\treturn message\n}\n<commit_msg>Add BlockAction missing SelectedOptions field<commit_after>package slack\n\n\/\/ @NOTE: Blocks are in beta and subject to change.\n\n\/\/ More Information: https:\/\/api.slack.com\/block-kit\n\n\/\/ MessageBlockType defines a named string type to define each block type\n\/\/ as a constant for use within the package.\ntype MessageBlockType string\n\nconst (\n\tMBTSection MessageBlockType = \"section\"\n\tMBTDivider MessageBlockType = \"divider\"\n\tMBTImage   MessageBlockType = \"image\"\n\tMBTAction  MessageBlockType = \"actions\"\n\tMBTContext MessageBlockType = \"context\"\n)\n\n\/\/ Block defines an interface all block types should implement\n\/\/ to ensure consistency between blocks.\ntype Block interface {\n\tBlockType() MessageBlockType\n}\n\n\/\/ Blocks is a convenience struct defined to allow dynamic unmarshalling of\n\/\/ the \"blocks\" value in Slack's JSON response, which varies depending on block type\ntype Blocks struct {\n\tBlockSet []Block `json:\"blocks,omitempty\"`\n}\n\n\/\/ BlockAction is the action callback sent when a block is interacted with\ntype BlockAction struct {\n\tActionID             string              `json:\"action_id\"`\n\tBlockID              string              `json:\"block_id\"`\n\tType                 actionType          `json:\"type\"`\n\tText                 TextBlockObject     `json:\"text\"`\n\tValue                string              `json:\"value\"`\n\tActionTs             string              `json:\"action_ts\"`\n\tSelectedOption       OptionBlockObject   `json:\"selected_option\"`\n\tSelectedOptions      []OptionBlockObject `json:\"selected_options\"`\n\tSelectedUser         string              `json:\"selected_user\"`\n\tSelectedChannel      string              `json:\"selected_channel\"`\n\tSelectedConversation string              `json:\"selected_conversation\"`\n\tSelectedDate         string              `json:\"selected_date\"`\n\tInitialOption        OptionBlockObject   `json:\"initial_option\"`\n\tInitialUser          string              `json:\"initial_user\"`\n\tInitialChannel       string              `json:\"initial_channel\"`\n\tInitialConversation  string              `json:\"initial_conversation\"`\n\tInitialDate          string              `json:\"initial_date\"`\n}\n\n\/\/ actionType returns the type of the action\nfunc (b BlockAction) actionType() actionType {\n\treturn b.Type\n}\n\n\/\/ NewBlockMessage creates a new Message that contains one or more blocks to be displayed\nfunc NewBlockMessage(blocks ...Block) Message {\n\treturn Message{\n\t\tMsg: Msg{\n\t\t\tBlocks: Blocks{\n\t\t\t\tBlockSet: blocks,\n\t\t\t},\n\t\t},\n\t}\n}\n\n\/\/ AddBlockMessage appends a block to the end of the existing list of blocks\nfunc AddBlockMessage(message Message, newBlk Block) Message {\n\tmessage.Msg.Blocks.BlockSet = append(message.Msg.Blocks.BlockSet, newBlk)\n\treturn message\n}\n<|endoftext|>"}
{"text":"<commit_before>package logging\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n)\n\n\/\/ ErrorLogger provides the interface for outputting errors to a log sink\ntype ErrorLogger interface {\n\tError(parameters ...interface{})\n}\n\n\/\/ Logger defines the expected methods to be provided by logging infrastructure.\n\/\/ This interface uses different idioms than those used by golang's stdlib Logger.\ntype Logger interface {\n\tErrorLogger\n\n\tTrace(parameters ...interface{})\n\tDebug(parameters ...interface{})\n\tInfo(parameters ...interface{})\n\tWarn(parameters ...interface{})\n}\n\n\/\/ PrintLogger exposes a Printf method for infrastructure that uses that method\n\/\/ for logging.\ntype PrintLogger struct {\n\tlogger Logger\n}\n\nfunc (printLogger PrintLogger) Printf(format string, parameters ...interface{}) {\n\tallParameters := make([]interface{}, 0, len(parameters)+1)\n\tallParameters[0] = format\n\tcopy(allParameters[1:], parameters)\n\n\tprintLogger.logger.Info(allParameters...)\n}\n\nconst (\n\ttraceLevel string = \"[TRACE] \"\n\tdebugLevel string = \"[DEBUG] \"\n\tinfoLevel  string = \"[INFO]  \"\n\twarnLevel  string = \"[WARN]  \"\n\terrorLevel string = \"[ERROR] \"\n\tfatalLevel string = \"[FATAL] \"\n)\n\n\/\/ LoggerWriter is a default, built-in logging type that simply writes output\n\/\/ to an embedded io.Writer.  This is a \"poor man's\" Logger.  It should normally\n\/\/ only be used in utilities and tests.\n\/\/\n\/\/ This logger will panic if any io errors occur.\ntype LoggerWriter struct {\n\tio.Writer\n}\n\nfunc (l *LoggerWriter) logf(level, format string, parameters []interface{}) {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(level)\n\n\tif _, err := fmt.Fprintf(&buffer, format, parameters...); err != nil {\n\t\tpanic(err)\n\t}\n\n\tbuffer.WriteRune('\\n')\n\tif _, err := l.Write(buffer.Bytes()); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc (l *LoggerWriter) formatf(level string, parameters []interface{}) {\n\tif len(parameters) > 0 {\n\t\tformat, ok := parameters[0].(string)\n\t\tif !ok {\n\t\t\tif stringer, ok := parameters[0].(fmt.Stringer); ok {\n\t\t\t\tformat = stringer.String()\n\t\t\t} else {\n\t\t\t\tformat = fmt.Sprintf(\"%v\", parameters[0])\n\t\t\t}\n\t\t}\n\n\t\tl.logf(level, format, parameters[1:])\n\t} else {\n\t\tl.logf(level, \"\", parameters)\n\t}\n}\n\nfunc (l *LoggerWriter) Trace(parameters ...interface{}) { l.formatf(traceLevel, parameters) }\nfunc (l *LoggerWriter) Debug(parameters ...interface{}) { l.formatf(debugLevel, parameters) }\nfunc (l *LoggerWriter) Info(parameters ...interface{})  { l.formatf(infoLevel, parameters) }\nfunc (l *LoggerWriter) Warn(parameters ...interface{})  { l.formatf(warnLevel, parameters) }\nfunc (l *LoggerWriter) Error(parameters ...interface{}) { l.formatf(errorLevel, parameters) }\n\nfunc (l *LoggerWriter) Printf(format string, parameters ...interface{}) {\n\tl.logf(infoLevel, format, parameters)\n}\n<commit_msg>Export delegate field<commit_after>package logging\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n)\n\n\/\/ ErrorLogger provides the interface for outputting errors to a log sink\ntype ErrorLogger interface {\n\tError(parameters ...interface{})\n}\n\n\/\/ Logger defines the expected methods to be provided by logging infrastructure.\n\/\/ This interface uses different idioms than those used by golang's stdlib Logger.\ntype Logger interface {\n\tErrorLogger\n\n\tTrace(parameters ...interface{})\n\tDebug(parameters ...interface{})\n\tInfo(parameters ...interface{})\n\tWarn(parameters ...interface{})\n}\n\n\/\/ PrintLogger exposes a Printf method for infrastructure that uses that method\n\/\/ for logging.\ntype PrintLogger struct {\n\tDelegate Logger\n}\n\nfunc (printLogger PrintLogger) Printf(format string, parameters ...interface{}) {\n\tallParameters := make([]interface{}, 0, len(parameters)+1)\n\tallParameters[0] = format\n\tcopy(allParameters[1:], parameters)\n\n\tprintLogger.Delegate.Info(allParameters...)\n}\n\nconst (\n\ttraceLevel string = \"[TRACE] \"\n\tdebugLevel string = \"[DEBUG] \"\n\tinfoLevel  string = \"[INFO]  \"\n\twarnLevel  string = \"[WARN]  \"\n\terrorLevel string = \"[ERROR] \"\n\tfatalLevel string = \"[FATAL] \"\n)\n\n\/\/ LoggerWriter is a default, built-in logging type that simply writes output\n\/\/ to an embedded io.Writer.  This is a \"poor man's\" Logger.  It should normally\n\/\/ only be used in utilities and tests.\n\/\/\n\/\/ This logger will panic if any io errors occur.\ntype LoggerWriter struct {\n\tio.Writer\n}\n\nfunc (l *LoggerWriter) logf(level, format string, parameters []interface{}) {\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(level)\n\n\tif _, err := fmt.Fprintf(&buffer, format, parameters...); err != nil {\n\t\tpanic(err)\n\t}\n\n\tbuffer.WriteRune('\\n')\n\tif _, err := l.Write(buffer.Bytes()); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc (l *LoggerWriter) formatf(level string, parameters []interface{}) {\n\tif len(parameters) > 0 {\n\t\tformat, ok := parameters[0].(string)\n\t\tif !ok {\n\t\t\tif stringer, ok := parameters[0].(fmt.Stringer); ok {\n\t\t\t\tformat = stringer.String()\n\t\t\t} else {\n\t\t\t\tformat = fmt.Sprintf(\"%v\", parameters[0])\n\t\t\t}\n\t\t}\n\n\t\tl.logf(level, format, parameters[1:])\n\t} else {\n\t\tl.logf(level, \"\", parameters)\n\t}\n}\n\nfunc (l *LoggerWriter) Trace(parameters ...interface{}) { l.formatf(traceLevel, parameters) }\nfunc (l *LoggerWriter) Debug(parameters ...interface{}) { l.formatf(debugLevel, parameters) }\nfunc (l *LoggerWriter) Info(parameters ...interface{})  { l.formatf(infoLevel, parameters) }\nfunc (l *LoggerWriter) Warn(parameters ...interface{})  { l.formatf(warnLevel, parameters) }\nfunc (l *LoggerWriter) Error(parameters ...interface{}) { l.formatf(errorLevel, parameters) }\n\nfunc (l *LoggerWriter) Printf(format string, parameters ...interface{}) {\n\tl.logf(infoLevel, format, parameters)\n}\n<|endoftext|>"}
{"text":"<commit_before>package login\n\nimport (\n\t\"context\"\n\t\"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/bwplotka\/oidc\"\n)\n\nconst (\n\tcodeParam  = \"code\"\n\tstateParam = \"state\"\n\n\terrParam     = \"error\"\n\terrDescParam = \"error_description\"\n)\n\nfunc rand128Bits() string {\n\tbuff := make([]byte, 16) \/\/ 128 bit random ID.\n\tif _, err := io.ReadFull(rand.Reader, buff); err != nil {\n\t\tpanic(err)\n\t}\n\treturn strings.TrimRight(base64.URLEncoding.EncodeToString(buff), \"=\")\n}\n\n\/\/ open opens the specified URL in the default browser of the user.\nfunc openBrowser(url string) error {\n\tvar cmd string\n\tvar args []string\n\n\tswitch runtime.GOOS {\n\tcase \"windows\":\n\t\tcmd = \"cmd\"\n\t\targs = []string{\"\/c\", \"start\"}\n\tcase \"darwin\":\n\t\tcmd = \"open\"\n\tdefault: \/\/ \"linux\", \"freebsd\", \"openbsd\", \"netbsd\"\n\t\tcmd = \"xdg-open\"\n\t}\n\targs = append(args, url)\n\treturn exec.Command(cmd, args...).Start()\n}\n\n\/\/ callbackResponse contains return message from callback server including token or error.\ntype callbackResponse struct {\n\ttoken *oidc.Token\n\terr   error\n}\n\n\/\/ callbackRequest specifies values that are needed for expected callback handling.\ntype callbackRequest struct {\n\tctx           context.Context\n\texpectedState string\n\n\tcfg    oidc.Config\n\tclient *oidc.Client\n}\n\n\/\/ CallbackServer carries a callback handler for OIDC auth code flow.\n\/\/ NOTE: This is not thread-safe in terms of multiple logins in the same time.\ntype CallbackServer struct {\n\tredirectURL string\n\tcallbackCh  chan *callbackResponse\n\n\t\/\/ CallbackReq is written in separate thread so guard that.\n\tcallbackReqMu sync.Mutex\n\t\/\/ If empty, nothing is expected, so callback should immediately return err.\n\tcallbackReq *callbackRequest\n}\n\n\/\/ NewServer creates HTTP server with OIDC callback on the bindAddress an argument. BindAddress is the ultimately a redirectURL that all clients MUST register\n\/\/ first on the OIDC server. It can (and is recommended) to point to localhost. Bind Address must include port. You can specify 0 if your\n\/\/ OIDC provider support wildcard on port (almost all server does NOT).\nfunc NewServer(bindAddress string) (srv *CallbackServer, closeSrv func(), err error) {\n\tbindURL, err := url.Parse(bindAddress)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"BindAddress is not in a form of URL. Err: %v\", err)\n\t}\n\n\tlistener, err := net.Listen(\"tcp\", bindURL.Host)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"Failed to Listen for tcp on: %s. Err: %v\", bindURL.Host, err)\n\t}\n\n\ts := &CallbackServer{\n\t\tredirectURL: fmt.Sprintf(\"http:\/\/%s%s\", listener.Addr().String(), bindURL.Path),\n\t\tcallbackCh:  make(chan *callbackResponse),\n\t}\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(bindURL.Path, s.callbackHandler)\n\n\tgo func() {\n\t\thttp.Serve(listener, mux)\n\t}()\n\n\treturn s, func() {\n\t\tlistener.Close()\n\t\tclose(s.callbackCh)\n\t}, nil\n}\n\n\/\/ NewReuseServer creates HTTP server with OIDC callback registered on given HTTP mux. Server constructed in such way\n\/\/ is not responsible for serving the callback. This is responsibility of the caller.\nfunc NewReuseServer(pattern string, listenAddress string, mux *http.ServeMux) *CallbackServer {\n\ts := &CallbackServer{\n\t\tredirectURL: fmt.Sprintf(\"http:\/\/%s%s\", listenAddress, pattern),\n\t\tcallbackCh:  make(chan *callbackResponse),\n\t}\n\tmux.HandleFunc(pattern, s.callbackHandler)\n\treturn s\n}\n\n\/\/ callbackHandler handles redirect from OIDC provider with either code or error parameters.\n\/\/ If none callback is expected it will return error.\n\/\/ In case of valid code with corresponded state it will perform token exchange with OIDC provider.\n\/\/ Any message is propagated via Go channel if the callback was expected.\n\/\/ NOTE: This is not thread-safe in terms of multiple logins in the same time.\nfunc (s *CallbackServer) callbackHandler(w http.ResponseWriter, r *http.Request) {\n\ts.callbackReqMu.Lock()\n\tif s.callbackReq == nil {\n\t\tw.WriteHeader(http.StatusPreconditionFailed)\n\t\tw.Write([]byte(\"Did not expect OIDC callback\"))\n\t\treturn\n\t}\n\tdefer func() {\n\t\ts.callbackReq = nil\n\t\ts.callbackReqMu.Unlock()\n\t}()\n\n\terr := r.ParseForm()\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Failed to parse request form. Err: %v\", err)\n\t\ts.errRespond(w, r, err)\n\t\treturn\n\t}\n\n\tcode, state, err := parseCallbackRequest(r.Form)\n\tif err != nil {\n\t\ts.errRespond(w, r, err)\n\t\treturn\n\t}\n\n\tif state != s.callbackReq.expectedState {\n\t\terr := fmt.Errorf(\"Invalid state parameter. Got %s, expected: %s\", state, s.callbackReq.expectedState)\n\t\ts.errRespond(w, r, err)\n\t\treturn\n\t}\n\n\tctx := mergeContexts(r.Context(), s.callbackReq.ctx)\n\toidcToken, err := s.callbackReq.client.Exchange(ctx, s.callbackReq.cfg, code)\n\tif err != nil {\n\t\ts.errRespond(w, r, err)\n\t\treturn\n\t}\n\n\tcallbackResponse := &callbackResponse{\n\t\ttoken: oidcToken,\n\t}\n\tOKCallbackResponse(w, r)\n\tselect {\n\tcase <-s.callbackReq.ctx.Done():\n\tcase s.callbackCh <- callbackResponse:\n\t}\n\treturn\n}\n\nfunc parseCallbackRequest(form url.Values) (code string, state string, err error) {\n\tstate = form.Get(stateParam)\n\tif state == \"\" {\n\t\treturn \"\", \"\", errors.New(\"User session error. No state parameter.\")\n\t}\n\n\tif errorCode := form.Get(errParam); errorCode != \"\" {\n\t\t\/\/ Got error from provider. Passing through.\n\t\treturn \"\", \"\", fmt.Errorf(\"Got error from provider: %s Desc: %s\", errorCode, form.Get(errDescParam))\n\t}\n\n\tcode = form.Get(codeParam)\n\tif code == \"\" {\n\t\treturn \"\", \"\", errors.New(\"Missing code token.\")\n\t}\n\n\treturn code, state, nil\n}\n\n\/\/ OKCallbackResponse is package wide function variable that returns HTTP response on successful OIDC `code` flow.\nvar OKCallbackResponse = func(w http.ResponseWriter, _ *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"OIDC authentication flow is completed. You can close browser tab.\"))\n}\n\n\/\/ ErrCallbackResponse is package wide function variable that returns HTTP response on failed OIDC `code` flow.\n\/\/ Note that, by default we don't want user to see anything wrong on browser side. All errors are propagated to command.\n\/\/ If it is required otherwise, override this function.\nvar ErrCallbackResponse = func(w http.ResponseWriter, _ *http.Request, _ error) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"OIDC authentication flow is completed. You can close browser tab.\"))\n}\n\nfunc (s *CallbackServer) errRespond(w http.ResponseWriter, r *http.Request, err error) {\n\tcallbackResponse := &callbackResponse{\n\t\terr: err,\n\t}\n\tErrCallbackResponse(w, r, err)\n\n\tselect {\n\tcase <-s.callbackReq.ctx.Done():\n\tcase s.callbackCh <- callbackResponse:\n\t}\n\treturn\n}\n\nfunc mergeContexts(originalCtx context.Context, oidcCtx context.Context) context.Context {\n\tif customClient := originalCtx.Value(oidc.HTTPClientCtxKey); customClient != nil {\n\t\treturn originalCtx\n\t}\n\treturn context.WithValue(originalCtx, oidc.HTTPClientCtxKey, oidcCtx.Value(oidc.HTTPClientCtxKey))\n}\n\nfunc (s *CallbackServer) ExpectCallback(callbackReq *callbackRequest) {\n\ts.callbackReqMu.Lock()\n\tdefer s.callbackReqMu.Unlock()\n\ts.callbackReq = callbackReq\n}\n\nfunc (s *CallbackServer) Callback() <-chan *callbackResponse {\n\treturn s.callbackCh\n}\n\nfunc (s *CallbackServer) RedirectURL() string {\n\treturn s.redirectURL\n}\n<commit_msg>Escape ampersand when opening a new browser on windows. (#28)<commit_after>package login\n\nimport (\n\t\"context\"\n\t\"crypto\/rand\"\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/bwplotka\/oidc\"\n)\n\nconst (\n\tcodeParam  = \"code\"\n\tstateParam = \"state\"\n\n\terrParam     = \"error\"\n\terrDescParam = \"error_description\"\n)\n\nfunc rand128Bits() string {\n\tbuff := make([]byte, 16) \/\/ 128 bit random ID.\n\tif _, err := io.ReadFull(rand.Reader, buff); err != nil {\n\t\tpanic(err)\n\t}\n\treturn strings.TrimRight(base64.URLEncoding.EncodeToString(buff), \"=\")\n}\n\n\/\/ open opens the specified URL in the default browser of the user.\nfunc openBrowser(url string) error {\n\tvar cmd string\n\tvar args []string\n\n\tswitch runtime.GOOS {\n\tcase \"windows\":\n\t\tcmd = \"cmd\"\n\t\targs = []string{\"\/c\", \"start\"}\n\t\t\/\/ If we don't escape &, cmd will ignore everything after the first &.\n\t\turl = strings.Replace(url, \"&\", \"^&\", -1)\n\tcase \"darwin\":\n\t\tcmd = \"open\"\n\tdefault: \/\/ \"linux\", \"freebsd\", \"openbsd\", \"netbsd\"\n\t\tcmd = \"xdg-open\"\n\t}\n\targs = append(args, url)\n\treturn exec.Command(cmd, args...).Start()\n}\n\n\/\/ callbackResponse contains return message from callback server including token or error.\ntype callbackResponse struct {\n\ttoken *oidc.Token\n\terr   error\n}\n\n\/\/ callbackRequest specifies values that are needed for expected callback handling.\ntype callbackRequest struct {\n\tctx           context.Context\n\texpectedState string\n\n\tcfg    oidc.Config\n\tclient *oidc.Client\n}\n\n\/\/ CallbackServer carries a callback handler for OIDC auth code flow.\n\/\/ NOTE: This is not thread-safe in terms of multiple logins in the same time.\ntype CallbackServer struct {\n\tredirectURL string\n\tcallbackCh  chan *callbackResponse\n\n\t\/\/ CallbackReq is written in separate thread so guard that.\n\tcallbackReqMu sync.Mutex\n\t\/\/ If empty, nothing is expected, so callback should immediately return err.\n\tcallbackReq *callbackRequest\n}\n\n\/\/ NewServer creates HTTP server with OIDC callback on the bindAddress an argument. BindAddress is the ultimately a redirectURL that all clients MUST register\n\/\/ first on the OIDC server. It can (and is recommended) to point to localhost. Bind Address must include port. You can specify 0 if your\n\/\/ OIDC provider support wildcard on port (almost all server does NOT).\nfunc NewServer(bindAddress string) (srv *CallbackServer, closeSrv func(), err error) {\n\tbindURL, err := url.Parse(bindAddress)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"BindAddress is not in a form of URL. Err: %v\", err)\n\t}\n\n\tlistener, err := net.Listen(\"tcp\", bindURL.Host)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"Failed to Listen for tcp on: %s. Err: %v\", bindURL.Host, err)\n\t}\n\n\ts := &CallbackServer{\n\t\tredirectURL: fmt.Sprintf(\"http:\/\/%s%s\", listener.Addr().String(), bindURL.Path),\n\t\tcallbackCh:  make(chan *callbackResponse),\n\t}\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(bindURL.Path, s.callbackHandler)\n\n\tgo func() {\n\t\thttp.Serve(listener, mux)\n\t}()\n\n\treturn s, func() {\n\t\tlistener.Close()\n\t\tclose(s.callbackCh)\n\t}, nil\n}\n\n\/\/ NewReuseServer creates HTTP server with OIDC callback registered on given HTTP mux. Server constructed in such way\n\/\/ is not responsible for serving the callback. This is responsibility of the caller.\nfunc NewReuseServer(pattern string, listenAddress string, mux *http.ServeMux) *CallbackServer {\n\ts := &CallbackServer{\n\t\tredirectURL: fmt.Sprintf(\"http:\/\/%s%s\", listenAddress, pattern),\n\t\tcallbackCh:  make(chan *callbackResponse),\n\t}\n\tmux.HandleFunc(pattern, s.callbackHandler)\n\treturn s\n}\n\n\/\/ callbackHandler handles redirect from OIDC provider with either code or error parameters.\n\/\/ If none callback is expected it will return error.\n\/\/ In case of valid code with corresponded state it will perform token exchange with OIDC provider.\n\/\/ Any message is propagated via Go channel if the callback was expected.\n\/\/ NOTE: This is not thread-safe in terms of multiple logins in the same time.\nfunc (s *CallbackServer) callbackHandler(w http.ResponseWriter, r *http.Request) {\n\ts.callbackReqMu.Lock()\n\tif s.callbackReq == nil {\n\t\tw.WriteHeader(http.StatusPreconditionFailed)\n\t\tw.Write([]byte(\"Did not expect OIDC callback\"))\n\t\treturn\n\t}\n\tdefer func() {\n\t\ts.callbackReq = nil\n\t\ts.callbackReqMu.Unlock()\n\t}()\n\n\terr := r.ParseForm()\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Failed to parse request form. Err: %v\", err)\n\t\ts.errRespond(w, r, err)\n\t\treturn\n\t}\n\n\tcode, state, err := parseCallbackRequest(r.Form)\n\tif err != nil {\n\t\ts.errRespond(w, r, err)\n\t\treturn\n\t}\n\n\tif state != s.callbackReq.expectedState {\n\t\terr := fmt.Errorf(\"Invalid state parameter. Got %s, expected: %s\", state, s.callbackReq.expectedState)\n\t\ts.errRespond(w, r, err)\n\t\treturn\n\t}\n\n\tctx := mergeContexts(r.Context(), s.callbackReq.ctx)\n\toidcToken, err := s.callbackReq.client.Exchange(ctx, s.callbackReq.cfg, code)\n\tif err != nil {\n\t\ts.errRespond(w, r, err)\n\t\treturn\n\t}\n\n\tcallbackResponse := &callbackResponse{\n\t\ttoken: oidcToken,\n\t}\n\tOKCallbackResponse(w, r)\n\tselect {\n\tcase <-s.callbackReq.ctx.Done():\n\tcase s.callbackCh <- callbackResponse:\n\t}\n\treturn\n}\n\nfunc parseCallbackRequest(form url.Values) (code string, state string, err error) {\n\tstate = form.Get(stateParam)\n\tif state == \"\" {\n\t\treturn \"\", \"\", errors.New(\"User session error. No state parameter.\")\n\t}\n\n\tif errorCode := form.Get(errParam); errorCode != \"\" {\n\t\t\/\/ Got error from provider. Passing through.\n\t\treturn \"\", \"\", fmt.Errorf(\"Got error from provider: %s Desc: %s\", errorCode, form.Get(errDescParam))\n\t}\n\n\tcode = form.Get(codeParam)\n\tif code == \"\" {\n\t\treturn \"\", \"\", errors.New(\"Missing code token.\")\n\t}\n\n\treturn code, state, nil\n}\n\n\/\/ OKCallbackResponse is package wide function variable that returns HTTP response on successful OIDC `code` flow.\nvar OKCallbackResponse = func(w http.ResponseWriter, _ *http.Request) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"OIDC authentication flow is completed. You can close browser tab.\"))\n}\n\n\/\/ ErrCallbackResponse is package wide function variable that returns HTTP response on failed OIDC `code` flow.\n\/\/ Note that, by default we don't want user to see anything wrong on browser side. All errors are propagated to command.\n\/\/ If it is required otherwise, override this function.\nvar ErrCallbackResponse = func(w http.ResponseWriter, _ *http.Request, _ error) {\n\tw.WriteHeader(http.StatusOK)\n\tw.Write([]byte(\"OIDC authentication flow is completed. You can close browser tab.\"))\n}\n\nfunc (s *CallbackServer) errRespond(w http.ResponseWriter, r *http.Request, err error) {\n\tcallbackResponse := &callbackResponse{\n\t\terr: err,\n\t}\n\tErrCallbackResponse(w, r, err)\n\n\tselect {\n\tcase <-s.callbackReq.ctx.Done():\n\tcase s.callbackCh <- callbackResponse:\n\t}\n\treturn\n}\n\nfunc mergeContexts(originalCtx context.Context, oidcCtx context.Context) context.Context {\n\tif customClient := originalCtx.Value(oidc.HTTPClientCtxKey); customClient != nil {\n\t\treturn originalCtx\n\t}\n\treturn context.WithValue(originalCtx, oidc.HTTPClientCtxKey, oidcCtx.Value(oidc.HTTPClientCtxKey))\n}\n\nfunc (s *CallbackServer) ExpectCallback(callbackReq *callbackRequest) {\n\ts.callbackReqMu.Lock()\n\tdefer s.callbackReqMu.Unlock()\n\ts.callbackReq = callbackReq\n}\n\nfunc (s *CallbackServer) Callback() <-chan *callbackResponse {\n\treturn s.callbackCh\n}\n\nfunc (s *CallbackServer) RedirectURL() string {\n\treturn s.redirectURL\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2014-2016 The btcsuite developers\n\/\/ Use of this source code is governed by an ISC\n\/\/ license that can be found in the LICENSE file.\n\npackage mining\n\nimport (\n\t\"sort\"\n\t\"time\"\n\n\tlog \"github.com\/sirupsen\/logrus\"\n\n\t\"github.com\/bytom\/account\"\n\t\"github.com\/bytom\/blockchain\/txbuilder\"\n\t\"github.com\/bytom\/consensus\"\n\t\"github.com\/bytom\/errors\"\n\t\"github.com\/bytom\/protocol\"\n\t\"github.com\/bytom\/protocol\/bc\"\n\t\"github.com\/bytom\/protocol\/bc\/types\"\n\t\"github.com\/bytom\/protocol\/state\"\n\t\"github.com\/bytom\/protocol\/validation\"\n\t\"github.com\/bytom\/protocol\/vm\/vmutil\"\n)\n\n\/\/ createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy\n\/\/ based on the passed block height to the provided address.  When the address\n\/\/ is nil, the coinbase transaction will instead be redeemable by anyone.\nfunc createCoinbaseTx(accountManager *account.Manager, amount uint64, blockHeight uint64) (tx *types.Tx, err error) {\n\tamount += consensus.BlockSubsidy(blockHeight)\n\n\tvar script []byte\n\tif accountManager == nil {\n\t\tscript, err = vmutil.DefaultCoinbaseProgram()\n\t} else {\n\t\tscript, err = accountManager.GetCoinbaseControlProgram()\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbuilder := txbuilder.NewBuilder(time.Now())\n\tif err = builder.AddInput(types.NewCoinbaseInput([]byte(string(blockHeight))), &txbuilder.SigningInstruction{}); err != nil {\n\t\treturn\n\t}\n\tif err = builder.AddOutput(types.NewTxOutput(*consensus.BTMAssetID, amount, script)); err != nil {\n\t\treturn\n\t}\n\t_, txData, err := builder.Build()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbyteData, err := txData.MarshalText()\n\tif err != nil {\n\t\treturn\n\t}\n\ttxData.SerializedSize = uint64(len(byteData))\n\n\ttx = &types.Tx{\n\t\tTxData: *txData,\n\t\tTx:     types.MapTx(txData),\n\t}\n\treturn\n}\n\n\/\/ NewBlockTemplate returns a new block template that is ready to be solved\nfunc NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager) (b *types.Block, err error) {\n\tview := state.NewUtxoViewpoint()\n\ttxStatus := bc.NewTransactionStatus()\n\ttxStatus.SetStatus(0, false)\n\ttxEntries := []*bc.Tx{nil}\n\tgasUsed := uint64(0)\n\ttxFee := uint64(0)\n\n\t\/\/ get preblock info for generate next block\n\tpreBlockHeader := c.BestBlockHeader()\n\tpreBlockHash := preBlockHeader.Hash()\n\tnextBlockHeight := preBlockHeader.Height + 1\n\tnextBits, err := c.CalcNextBits(&preBlockHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb = &types.Block{\n\t\tBlockHeader: types.BlockHeader{\n\t\t\tVersion:           1,\n\t\t\tHeight:            nextBlockHeight,\n\t\t\tPreviousBlockHash: preBlockHash,\n\t\t\tTimestamp:         uint64(time.Now().Unix()),\n\t\t\tBlockCommitment:   types.BlockCommitment{},\n\t\t\tBits:              nextBits,\n\t\t},\n\t}\n\tbcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}\n\tb.Transactions = []*types.Tx{nil}\n\n\ttxs := txPool.GetTransactions()\n\tsort.Sort(ByTime(txs))\n\tfor _, txDesc := range txs {\n\t\ttx := txDesc.Tx.Tx\n\t\tgasOnlyTx := false\n\n\t\tif err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {\n\t\t\tlog.WithField(\"error\", err).Error(\"mining block generate skip tx due to\")\n\t\t\ttxPool.RemoveTransaction(&tx.ID)\n\t\t\tcontinue\n\t\t}\n\n\t\tgasStatus, err := validation.ValidateTx(tx, bcBlock)\n\t\tif err != nil {\n\t\t\tif !gasStatus.GasValid {\n\t\t\t\tlog.WithField(\"error\", err).Error(\"mining block generate skip tx due to\")\n\t\t\t\ttxPool.RemoveTransaction(&tx.ID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgasOnlyTx = true\n\t\t}\n\n\t\tif gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {\n\t\t\tbreak\n\t\t}\n\n\t\tif err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {\n\t\t\tlog.WithField(\"error\", err).Error(\"mining block generate skip tx due to\")\n\t\t\ttxPool.RemoveTransaction(&tx.ID)\n\t\t\tcontinue\n\t\t}\n\n\t\ttxStatus.SetStatus(len(b.Transactions), gasOnlyTx)\n\t\tb.Transactions = append(b.Transactions, txDesc.Tx)\n\t\ttxEntries = append(txEntries, tx)\n\t\tgasUsed += uint64(gasStatus.GasUsed)\n\t\ttxFee += txDesc.Fee\n\n\t\tif gasUsed == consensus.MaxBlockGas {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/ creater coinbase transaction\n\tb.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"fail on createCoinbaseTx\")\n\t}\n\ttxEntries[0] = b.Transactions[0].Tx\n\n\tb.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = bc.TxMerkleRoot(txEntries)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb.BlockHeader.BlockCommitment.TransactionStatusHash, err = bc.TxStatusMerkleRoot(txStatus.VerifyStatus)\n\treturn b, err\n}\n<commit_msg>fix the coinbase generate bug<commit_after>\/\/ Copyright (c) 2014-2016 The btcsuite developers\n\/\/ Use of this source code is governed by an ISC\n\/\/ license that can be found in the LICENSE file.\n\npackage mining\n\nimport (\n\t\"sort\"\n\t\"strconv\"\n\t\"time\"\n\n\tlog \"github.com\/sirupsen\/logrus\"\n\n\t\"github.com\/bytom\/account\"\n\t\"github.com\/bytom\/blockchain\/txbuilder\"\n\t\"github.com\/bytom\/consensus\"\n\t\"github.com\/bytom\/errors\"\n\t\"github.com\/bytom\/protocol\"\n\t\"github.com\/bytom\/protocol\/bc\"\n\t\"github.com\/bytom\/protocol\/bc\/types\"\n\t\"github.com\/bytom\/protocol\/state\"\n\t\"github.com\/bytom\/protocol\/validation\"\n\t\"github.com\/bytom\/protocol\/vm\/vmutil\"\n)\n\n\/\/ createCoinbaseTx returns a coinbase transaction paying an appropriate subsidy\n\/\/ based on the passed block height to the provided address.  When the address\n\/\/ is nil, the coinbase transaction will instead be redeemable by anyone.\nfunc createCoinbaseTx(accountManager *account.Manager, amount uint64, blockHeight uint64) (tx *types.Tx, err error) {\n\tamount += consensus.BlockSubsidy(blockHeight)\n\n\tvar script []byte\n\tif accountManager == nil {\n\t\tscript, err = vmutil.DefaultCoinbaseProgram()\n\t} else {\n\t\tscript, err = accountManager.GetCoinbaseControlProgram()\n\t}\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbuilder := txbuilder.NewBuilder(time.Now())\n\tif err = builder.AddInput(types.NewCoinbaseInput(\n\t\tappend([]byte{0x00}, []byte(strconv.FormatUint(blockHeight, 10))...),\n\t), &txbuilder.SigningInstruction{}); err != nil {\n\t\treturn\n\t}\n\tif err = builder.AddOutput(types.NewTxOutput(*consensus.BTMAssetID, amount, script)); err != nil {\n\t\treturn\n\t}\n\t_, txData, err := builder.Build()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbyteData, err := txData.MarshalText()\n\tif err != nil {\n\t\treturn\n\t}\n\ttxData.SerializedSize = uint64(len(byteData))\n\n\ttx = &types.Tx{\n\t\tTxData: *txData,\n\t\tTx:     types.MapTx(txData),\n\t}\n\treturn\n}\n\n\/\/ NewBlockTemplate returns a new block template that is ready to be solved\nfunc NewBlockTemplate(c *protocol.Chain, txPool *protocol.TxPool, accountManager *account.Manager) (b *types.Block, err error) {\n\tview := state.NewUtxoViewpoint()\n\ttxStatus := bc.NewTransactionStatus()\n\ttxStatus.SetStatus(0, false)\n\ttxEntries := []*bc.Tx{nil}\n\tgasUsed := uint64(0)\n\ttxFee := uint64(0)\n\n\t\/\/ get preblock info for generate next block\n\tpreBlockHeader := c.BestBlockHeader()\n\tpreBlockHash := preBlockHeader.Hash()\n\tnextBlockHeight := preBlockHeader.Height + 1\n\tnextBits, err := c.CalcNextBits(&preBlockHash)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb = &types.Block{\n\t\tBlockHeader: types.BlockHeader{\n\t\t\tVersion:           1,\n\t\t\tHeight:            nextBlockHeight,\n\t\t\tPreviousBlockHash: preBlockHash,\n\t\t\tTimestamp:         uint64(time.Now().Unix()),\n\t\t\tBlockCommitment:   types.BlockCommitment{},\n\t\t\tBits:              nextBits,\n\t\t},\n\t}\n\tbcBlock := &bc.Block{BlockHeader: &bc.BlockHeader{Height: nextBlockHeight}}\n\tb.Transactions = []*types.Tx{nil}\n\n\ttxs := txPool.GetTransactions()\n\tsort.Sort(ByTime(txs))\n\tfor _, txDesc := range txs {\n\t\ttx := txDesc.Tx.Tx\n\t\tgasOnlyTx := false\n\n\t\tif err := c.GetTransactionsUtxo(view, []*bc.Tx{tx}); err != nil {\n\t\t\tlog.WithField(\"error\", err).Error(\"mining block generate skip tx due to\")\n\t\t\ttxPool.RemoveTransaction(&tx.ID)\n\t\t\tcontinue\n\t\t}\n\n\t\tgasStatus, err := validation.ValidateTx(tx, bcBlock)\n\t\tif err != nil {\n\t\t\tif !gasStatus.GasValid {\n\t\t\t\tlog.WithField(\"error\", err).Error(\"mining block generate skip tx due to\")\n\t\t\t\ttxPool.RemoveTransaction(&tx.ID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tgasOnlyTx = true\n\t\t}\n\n\t\tif gasUsed+uint64(gasStatus.GasUsed) > consensus.MaxBlockGas {\n\t\t\tbreak\n\t\t}\n\n\t\tif err := view.ApplyTransaction(bcBlock, tx, gasOnlyTx); err != nil {\n\t\t\tlog.WithField(\"error\", err).Error(\"mining block generate skip tx due to\")\n\t\t\ttxPool.RemoveTransaction(&tx.ID)\n\t\t\tcontinue\n\t\t}\n\n\t\ttxStatus.SetStatus(len(b.Transactions), gasOnlyTx)\n\t\tb.Transactions = append(b.Transactions, txDesc.Tx)\n\t\ttxEntries = append(txEntries, tx)\n\t\tgasUsed += uint64(gasStatus.GasUsed)\n\t\ttxFee += txDesc.Fee\n\n\t\tif gasUsed == consensus.MaxBlockGas {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/ creater coinbase transaction\n\tb.Transactions[0], err = createCoinbaseTx(accountManager, txFee, nextBlockHeight)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"fail on createCoinbaseTx\")\n\t}\n\ttxEntries[0] = b.Transactions[0].Tx\n\n\tb.BlockHeader.BlockCommitment.TransactionsMerkleRoot, err = bc.TxMerkleRoot(txEntries)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb.BlockHeader.BlockCommitment.TransactionStatusHash, err = bc.TxStatusMerkleRoot(txStatus.VerifyStatus)\n\treturn b, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package orderedtask\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype Msg struct {\n\ttext   string\n\toffset uint64\n}\n\nfunc TestSimpleExample(test *testing.T) {\n\t\/\/runtime.GOMAXPROCS(2)\n\tconst MsgCnt = 5000\n\tconst PoolSize = 6\n\n\t\/\/Create the pool with PoolSize workers\n\t\/\/  Note: if you lower the pool size, the total runtime gets longer due to the\n\t\/\/       lack of parallelization.\n\t\/\/\n\tpool := NewPool(PoolSize, func(workerlocal map[string]interface{}, t *Task) {\n\t\tvar buf bytes.Buffer\n\t\tif b, ok := workerlocal[\"buf\"]; !ok {\n\t\t\t\/\/worker local is not shared between go routines, so it's a good place to place a store a reusable items like buffers\n\t\t\tbuf = bytes.Buffer{}\n\t\t\tworkerlocal[\"buf\"] = buf\n\t\t} else {\n\t\t\tbuf = b.(bytes.Buffer)\n\t\t}\n\t\tbuf.Reset()\n\n\t\tmsg := t.Input.(*Msg)\n\t\tamt := time.Duration(rand.Intn(5))\n\t\ttime.Sleep(time.Millisecond * amt) \/\/ long running operation\n\t\tt.Output = msg\n\t})\n\n\twg := &sync.WaitGroup{}\n\n\t\/\/Consume messages from the pool\n\t\/\/  Note: they should be in order by the offset\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ti := 0\n\t\texpectedoffset := uint64(0)\n\t\tfor t := range pool.Results() {\n\t\t\tmsg := t.Output.(*Msg)\n\t\t\t\/\/fmt.Printf(\"msg off:%v text:%v \\n\", msg.offset, msg.text)\n\n\t\t\ti++\n\t\t\tif i == MsgCnt-1 {\n\t\t\t\treturn\n\t\t\t} else if msg.offset != expectedoffset {\n\t\t\t\ttest.Fatalf(\"the offsets weren't in order: got:%d expected:%d\", msg.offset, expectedoffset)\n\t\t\t}\n\t\t\texpectedoffset++\n\t\t}\n\t}()\n\n\t\/\/Produce messages into the pool\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor i := 0; i < MsgCnt; i++ {\n\t\t\tm := &Msg{fmt.Sprintf(\"{'foo':'%d'}\", i), uint64(i)}\n\t\t\tpool.Enqueue() <- &Task{Index: m.offset, Input: m}\n\t\t}\n\t}()\n\n\twg.Wait()\n}\n\nfunc TestSlowConsumers(test *testing.T) {\n\n\tconst MsgCnt = 200\n\tconst PoolSize = 2\n\tconst ConsumerSleep = 5\n\n\tmsgchan := make(chan *Task, 10)\n\n\tpool := NewPool(PoolSize, func(workerlocal map[string]interface{}, t *Task) {\n\t\tmsg := t.Input.(*Msg)\n\t\tamt := time.Duration(rand.Intn(2))\n\t\ttime.Sleep(time.Millisecond * amt)\n\t\tt.Output = msg\n\t})\n\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor i := 0; i < MsgCnt; i++ {\n\t\t\tm := &Msg{fmt.Sprintf(\"{'foo':'%d'}\", i), uint64(i)}\n\t\t\tmsgchan <- &Task{Index: m.offset, Input: m}\n\t\t}\n\t\tclose(msgchan)\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ti := 0\n\t\texpectedoffset := uint64(0)\n\n\t\t\/\/ticketbox := pool.GetTicketBox()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase pool.Enqueue() <- <-msgchan:\n\t\t\tcase t := <-pool.Results():\n\t\t\t\t\/\/ticketbox.ReturnTicket()\n\n\t\t\t\tmsg := t.Output.(*Msg)\n\t\t\t\ti++\n\t\t\t\tif i == MsgCnt-1 {\n\t\t\t\t\treturn\n\t\t\t\t} else if msg.offset != expectedoffset {\n\t\t\t\t\ttest.Fatalf(\"out of order: got:%d expected:%d\", msg.offset, expectedoffset)\n\t\t\t\t}\n\t\t\t\texpectedoffset++\n\t\t\t\tamt := time.Duration(ConsumerSleep)\n\t\t\t\ttime.Sleep(time.Millisecond * amt)\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Wait()\n}\n\nfunc TestSlowProducers(test *testing.T) {\n\n\tconst MsgCnt = 10000\n\tconst PoolSize = 2\n\n\tpool := NewPool(PoolSize, func(workerlocal map[string]interface{}, t *Task) {\n\t\tmsg := t.Input.(*Msg)\n\t\tamt := time.Duration(rand.Intn(10))\n\t\ttime.Sleep(time.Millisecond * amt)\n\t\tt.Output = msg\n\t})\n\n\tproducechan := make(chan *Task, 200)\n\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor i := 0; i < MsgCnt; i++ {\n\t\t\tm := &Msg{fmt.Sprintf(\"{'foo':'%d'}\", i), uint64(i)}\n\t\t\tproducechan <- &Task{Index: m.offset, Input: m}\n\t\t}\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ti := 0\n\t\texpectedoffset := uint64(0)\n\t\tgetData := func() *Task {\n\t\t\ttask := <-producechan\n\t\t\treturn task\n\t\t}\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase pool.Enqueue() <- getData():\n\t\t\t\tpool.Enqueue()\n\t\t\t\tamt := time.Duration(rand.Intn(15))\n\t\t\t\ttime.Sleep(time.Millisecond * amt)\n\t\t\tcase t := <-pool.Results():\n\t\t\t\tmsg := t.Output.(*Msg)\n\n\t\t\t\ti++\n\t\t\t\tif i == MsgCnt-1 {\n\t\t\t\t\treturn\n\t\t\t\t} else if msg.offset != expectedoffset {\n\t\t\t\t\ttest.Fatalf(\"the offsets weren't in order: got:%d expected:%d\", msg.offset, expectedoffset)\n\t\t\t\t}\n\t\t\t\texpectedoffset++\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Wait()\n}\n\nfunc TestFastWorkers(test *testing.T) {\n\n\tconst MsgCnt = 50000\n\tconst PoolSize = 2\n\n\tpool := NewPool(PoolSize, func(workerlocal map[string]interface{}, t *Task) {\n\t\tmsg := t.Input.(*Msg)\n\t\tt.Output = msg\n\t})\n\n\twg := &sync.WaitGroup{}\n\n\t\/\/Produce messages into the pool\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor i := 0; i < MsgCnt; i++ {\n\t\t\tm := &Msg{fmt.Sprintf(\"{'foo':'%d'}\", i), uint64(i)}\n\t\t\tpool.Enqueue() <- &Task{Index: m.offset, Input: m}\n\t\t}\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ti := 0\n\t\texpectedoffset := uint64(0)\n\t\tfor t := range pool.Results() {\n\t\t\tmsg := t.Output.(*Msg)\n\n\t\t\ti++\n\t\t\tif i == MsgCnt-1 {\n\t\t\t\treturn\n\t\t\t} else if msg.offset != expectedoffset {\n\t\t\t\ttest.Fatalf(\"the offsets weren't in order: got:%d expected:%d\", msg.offset, expectedoffset)\n\t\t\t}\n\t\t\texpectedoffset++\n\t\t}\n\t}()\n\n\twg.Wait()\n}\n<commit_msg>put in the ticker box changes.<commit_after>package orderedtask\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype Msg struct {\n\ttext   string\n\toffset uint64\n}\n\nfunc TestSimpleExample(test *testing.T) {\n\t\/\/runtime.GOMAXPROCS(2)\n\tconst MsgCnt = 5000\n\tconst PoolSize = 6\n\n\t\/\/Create the pool with PoolSize workers\n\t\/\/  Note: if you lower the pool size, the total runtime gets longer due to the\n\t\/\/       lack of parallelization.\n\t\/\/\n\tpool := NewPool(PoolSize, func(workerlocal map[string]interface{}, t *Task) {\n\t\tvar buf bytes.Buffer\n\t\tif b, ok := workerlocal[\"buf\"]; !ok {\n\t\t\t\/\/worker local is not shared between go routines, so it's a good place to place a store a reusable items like buffers\n\t\t\tbuf = bytes.Buffer{}\n\t\t\tworkerlocal[\"buf\"] = buf\n\t\t} else {\n\t\t\tbuf = b.(bytes.Buffer)\n\t\t}\n\t\tbuf.Reset()\n\n\t\tmsg := t.Input.(*Msg)\n\t\tamt := time.Duration(rand.Intn(5))\n\t\ttime.Sleep(time.Millisecond * amt) \/\/ long running operation\n\t\tt.Output = msg\n\t})\n\n\twg := &sync.WaitGroup{}\n\n\t\/\/Consume messages from the pool\n\t\/\/  Note: they should be in order by the offset\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ti := 0\n\t\texpectedoffset := uint64(0)\n\t\tfor t := range pool.Results() {\n\t\t\tmsg := t.Output.(*Msg)\n\t\t\t\/\/fmt.Printf(\"msg off:%v text:%v \\n\", msg.offset, msg.text)\n\n\t\t\ti++\n\t\t\tif i == MsgCnt-1 {\n\t\t\t\treturn\n\t\t\t} else if msg.offset != expectedoffset {\n\t\t\t\ttest.Fatalf(\"the offsets weren't in order: got:%d expected:%d\", msg.offset, expectedoffset)\n\t\t\t}\n\t\t\texpectedoffset++\n\t\t}\n\t}()\n\n\t\/\/Produce messages into the pool\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor i := 0; i < MsgCnt; i++ {\n\t\t\tm := &Msg{fmt.Sprintf(\"{'foo':'%d'}\", i), uint64(i)}\n\t\t\tpool.Enqueue() <- &Task{Index: m.offset, Input: m}\n\t\t}\n\t}()\n\n\twg.Wait()\n}\n\nfunc TestSlowConsumers(test *testing.T) {\n\n\tconst MsgCnt = 200\n\tconst PoolSize = 2\n\tconst ConsumerSleep = 5\n\n\tmsgchan := make(chan *Task, 10)\n\n\tpool := NewPool(PoolSize, func(workerlocal map[string]interface{}, t *Task) {\n\t\tmsg := t.Input.(*Msg)\n\t\tamt := time.Duration(rand.Intn(2))\n\t\ttime.Sleep(time.Millisecond * amt)\n\t\tt.Output = msg\n\t})\n\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor i := 0; i < MsgCnt; i++ {\n\t\t\tm := &Msg{fmt.Sprintf(\"{'foo':'%d'}\", i), uint64(i)}\n\t\t\tmsgchan <- &Task{Index: m.offset, Input: m}\n\t\t}\n\t\tclose(msgchan)\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ti := 0\n\t\texpectedoffset := uint64(0)\n\n\t\tticketbox := pool.GetTicketBox()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticketbox.Tickets():\n\t\t\t\tt, ok := <-msgchan\n\t\t\t\tif ok {\n\t\t\t\t\tpool.Enqueue() <- t\n\t\t\t\t}\n\t\t\tcase t := <-pool.Results():\n\t\t\t\tticketbox.ReturnTicket()\n\n\t\t\t\tmsg := t.Output.(*Msg)\n\t\t\t\ti++\n\t\t\t\tif i == MsgCnt-1 {\n\t\t\t\t\treturn\n\t\t\t\t} else if msg.offset != expectedoffset {\n\t\t\t\t\ttest.Fatalf(\"out of order: got:%d expected:%d\", msg.offset, expectedoffset)\n\t\t\t\t}\n\t\t\t\texpectedoffset++\n\t\t\t\tamt := time.Duration(ConsumerSleep)\n\t\t\t\ttime.Sleep(time.Millisecond * amt)\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Wait()\n}\n\nfunc TestSlowProducers(test *testing.T) {\n\n\tconst MsgCnt = 10000\n\tconst PoolSize = 2\n\n\tpool := NewPool(PoolSize, func(workerlocal map[string]interface{}, t *Task) {\n\t\tmsg := t.Input.(*Msg)\n\t\tamt := time.Duration(rand.Intn(10))\n\t\ttime.Sleep(time.Millisecond * amt)\n\t\tt.Output = msg\n\t})\n\n\tproducechan := make(chan *Task, 200)\n\n\twg := &sync.WaitGroup{}\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor i := 0; i < MsgCnt; i++ {\n\t\t\tm := &Msg{fmt.Sprintf(\"{'foo':'%d'}\", i), uint64(i)}\n\t\t\tproducechan <- &Task{Index: m.offset, Input: m}\n\t\t}\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ti := 0\n\t\texpectedoffset := uint64(0)\n\t\tgetData := func() *Task {\n\t\t\ttask := <-producechan\n\t\t\treturn task\n\t\t}\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase pool.Enqueue() <- getData():\n\t\t\t\tpool.Enqueue()\n\t\t\t\tamt := time.Duration(rand.Intn(15))\n\t\t\t\ttime.Sleep(time.Millisecond * amt)\n\t\t\tcase t := <-pool.Results():\n\t\t\t\tmsg := t.Output.(*Msg)\n\n\t\t\t\ti++\n\t\t\t\tif i == MsgCnt-1 {\n\t\t\t\t\treturn\n\t\t\t\t} else if msg.offset != expectedoffset {\n\t\t\t\t\ttest.Fatalf(\"the offsets weren't in order: got:%d expected:%d\", msg.offset, expectedoffset)\n\t\t\t\t}\n\t\t\t\texpectedoffset++\n\t\t\t}\n\t\t}\n\t}()\n\n\twg.Wait()\n}\n\nfunc TestFastWorkers(test *testing.T) {\n\n\tconst MsgCnt = 50000\n\tconst PoolSize = 2\n\n\tpool := NewPool(PoolSize, func(workerlocal map[string]interface{}, t *Task) {\n\t\tmsg := t.Input.(*Msg)\n\t\tt.Output = msg\n\t})\n\n\twg := &sync.WaitGroup{}\n\n\t\/\/Produce messages into the pool\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor i := 0; i < MsgCnt; i++ {\n\t\t\tm := &Msg{fmt.Sprintf(\"{'foo':'%d'}\", i), uint64(i)}\n\t\t\tpool.Enqueue() <- &Task{Index: m.offset, Input: m}\n\t\t}\n\t}()\n\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\ti := 0\n\t\texpectedoffset := uint64(0)\n\t\tfor t := range pool.Results() {\n\t\t\tmsg := t.Output.(*Msg)\n\n\t\t\ti++\n\t\t\tif i == MsgCnt-1 {\n\t\t\t\treturn\n\t\t\t} else if msg.offset != expectedoffset {\n\t\t\t\ttest.Fatalf(\"the offsets weren't in order: got:%d expected:%d\", msg.offset, expectedoffset)\n\t\t\t}\n\t\t\texpectedoffset++\n\t\t}\n\t}()\n\n\twg.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The Upspin Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage tree\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"upspin.io\/context\"\n\t\"upspin.io\/errors\"\n\t\"upspin.io\/factotum\"\n\t\"upspin.io\/key\/inprocess\"\n\t\"upspin.io\/upspin\"\n\n\t_ \"upspin.io\/pack\/ee\"\n\t_ \"upspin.io\/store\/inprocess\"\n)\n\nconst (\n\tuserName   = \"user@domain.com\"\n\tserverName = \"tree@server.com\"\n)\n\n\/\/ This test checks the tree for log consistency by exercising the life-cycle of a tree,\n\/\/ from creating a new tree from scratch, adding new nodes, flushing it to Store then\n\/\/ adding more nodes to a new tree and having to load it from the Store.\nfunc TestPutNodes(t *testing.T) {\n\tcfg := newConfigForTesting(t)\n\ttree := New(userName, cfg)\n\n\tdir1 := upspin.DirEntry{\n\t\tName:    userName + \"\/\",\n\t\tAttr:    upspin.AttrDirectory,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  serverName,\n\t}\n\terr := tree.Put(&dir1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdir2 := upspin.DirEntry{\n\t\tName:    userName + \"\/dir\",\n\t\tAttr:    upspin.AttrDirectory,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  serverName,\n\t}\n\terr = tree.Put(&dir2)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdir3 := upspin.DirEntry{\n\t\tName:    userName + \"\/dir\/doc.pdf\",\n\t\tAttr:    upspin.AttrNone,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  serverName,\n\t}\n\terr = tree.Put(&dir3)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Verify three log entries were written.\n\tif got, want := cfg.Log.LastIndex(), 2; got != want {\n\t\tt.Fatalf(\"LastIndex = %d, want %d\", got, want)\n\t}\n\tentries, err := cfg.Log.Read(0, 3)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !reflect.DeepEqual(entries[0], dir1) {\n\t\tt.Errorf(\"dir1 = %v, want %v\", entries[0], dir1)\n\t}\n\tif !reflect.DeepEqual(entries[1], dir2) {\n\t\tt.Errorf(\"dir2 = %v, want %v\", entries[1], dir2)\n\t}\n\tif !reflect.DeepEqual(entries[2], dir3) {\n\t\tt.Errorf(\"dir3 = %v, want %v\", entries[2], dir3)\n\t}\n\n\t\/\/ Lookup path.\n\tde, dirty, err := tree.Lookup(userName + \"\/dir\/doc.pdf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !dirty {\n\t\tt.Errorf(\"dirty = %v, want %v\", dirty, true)\n\t}\n\tif !reflect.DeepEqual(*de, dir3) {\n\t\tt.Errorf(\"de = %v, want %v\", de, dir3)\n\t}\n\n\t\/\/ Flush to later build a new tree and verify new is equivalent to old.\n\terr = tree.Flush()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ New log index shows we're now at the end of the log.\n\tgot, err := cfg.LogIndex.ReadLastIndex()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif want := cfg.Log.LastIndex(); got != want {\n\t\tt.Fatalf(\"cfg.Log.LastIndex() = %d, want %d\", got, want)\n\t}\n\n\t\/\/ Lookup now returns !dirty.\n\tde, dirty, err = tree.Lookup(userName + \"\/dir\/doc.pdf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif dirty {\n\t\tt.Errorf(\"dirty = %v, want %v\", dirty, false)\n\t}\n\tif !reflect.DeepEqual(*de, dir3) {\n\t\tt.Errorf(\"de = %v, want %v\", de, dir3)\n\t}\n\n\t\/\/ Now start a new tree from scratch and confirm it is loaded from the Store.\n\ttree2 := New(userName, cfg)\n\n\tdir4 := &upspin.DirEntry{\n\t\tName:    userName + \"\/dir\/img.jpg\",\n\t\tAttr:    upspin.AttrNone,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  userName, \/\/ This was written by the user, the server is just packing it in a dir block.\n\t}\n\terr = tree2.Put(dir4)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got, want := cfg.Log.LastIndex(), 3; got != want {\n\t\tt.Fatalf(\"cfg.Log.LastIndex() = %d, want %d\", cfg.Log.LastIndex(), want)\n\t}\n\n\t\/\/ Delete dir4.\n\terr = tree2.Delete(userName + \"\/dir\/img.jpg\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t\/\/ Lookup won't return it.\n\t_, _, err = tree.Lookup(userName + \"\/dir\/img.jpg\")\n\texpectedErr := errors.E(\"Delete\", errors.NotExist, upspin.PathName(userName+\"\/dir\/img.jpg\"))\n\tif errors.Match(expectedErr, err) {\n\t\tt.Fatalf(\"err = %s, want = %s\", err, expectedErr)\n\t}\n\t\/\/ One new entry was written to the log (an updated dir2).\n\tif got, want := cfg.Log.LastIndex(), 4; got != want {\n\t\tt.Fatalf(\"cfg.Log.LastIndex() = %d, want %d\", cfg.Log.LastIndex(), want)\n\t}\n\t\/\/ Verify logged entry is a new dir2\n\tentries, err = cfg.Log.Read(4, 1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got, want := entries[0].Name, upspin.PathName(userName+\"\/dir\"); got != want {\n\t\tt.Errorf(\"entries[0].Name = %s, want = %s\", got, want)\n\t}\n}\n\n\/\/ Test that an empty root can be saved and retrieved.\n\/\/ Roots are handled differently than other directory entries.\nfunc TestPutEmptyRoot(t *testing.T) {\n\tcfg := newConfigForTesting(t)\n\ttree := New(userName, cfg)\n\n\tdir1 := &upspin.DirEntry{\n\t\tName:    userName + \"\/\",\n\t\tAttr:    upspin.AttrDirectory,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  serverName,\n\t}\n\terr := tree.Put(dir1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = tree.Flush()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Now start a new tree from scratch and confirm it is loaded from the Store just the same.\n\ttree2 := New(userName, cfg)\n\n\tdir2 := &upspin.DirEntry{\n\t\tName:    userName + \"\/dir\",\n\t\tAttr:    upspin.AttrDirectory,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  serverName,\n\t}\n\terr = tree2.Put(dir2)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Try to put a file under an non-existent dir\n\tdir3 := &upspin.DirEntry{\n\t\tName:    userName + \"\/invaliddir\/myfile.txt\",\n\t\tAttr:    upspin.AttrNone,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  serverName,\n\t}\n\terr = tree2.Put(dir3)\n\tif err == nil {\n\t\tt.Fatal(\"Expected error, got none\")\n\t}\n\texpectedErr := errors.E(errors.NotExist)\n\tif !errors.Match(expectedErr, err) {\n\t\tt.Errorf(\"err = %s, want %s\", err, expectedErr)\n\t}\n}\n\n\/\/ TODO: TestPutLargeNode: test that a huge DirEntry (>blockSize) gets split into multiple ones.\n\/\/ TODO: Run all tests in loop using Plain and Debug packs as well.\n\/\/ TODO: test more error cases.\n\/\/ TODO: Implement and test starting the tree from a non-empty log and a log index not at the end of the log.\n\n\/\/ newConfigForTesting creates a config with mocks, fakes, inprocess and otherwise testing\n\/\/ versions of the Tree's dependencies.\nfunc newConfigForTesting(t *testing.T) *Config {\n\tpubKey := upspin.PublicKey(\"p256\\n104278369061367353805983276707664349405797936579880352274235000127123465616334\\n26941412685198548642075210264642864401950753555952207894712845271039438170192\\n\")\n\t\/\/ TODO: rename factotum.DeprecatedNew to NewWithKeys or NewForTesting.\n\tfactotum, err := factotum.DeprecatedNew(\n\t\tpubKey,\n\t\t\"82201047360680847258309465671292633303992565667422607675215625927005262185934\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tendpointInProcess := upspin.Endpoint{\n\t\tTransport: upspin.InProcess,\n\t\tNetAddr:   \"\",\n\t}\n\tcontext := context.New().\n\t\tSetFactotum(factotum).\n\t\tSetUserName(serverName).\n\t\tSetStoreEndpoint(endpointInProcess).\n\t\tSetKeyEndpoint(endpointInProcess).\n\t\tSetPacking(upspin.EEPack)\n\tkey := context.KeyServer()\n\ttestKey, ok := key.(*inprocess.Service)\n\tif !ok {\n\t\tt.Fatal(err)\n\t}\n\t\/\/ Set the public key for the tree, since it must do Auth against the Store.\n\ttestKey.SetPublicKeys(serverName, []upspin.PublicKey{pubKey})\n\n\t\/\/ Set the public key for the user, since EE Pack requires the dir owner to have a wrapped key.\n\t\/\/ TODO: re-think this for directories, but probably correct as-is because if the dir server goes\n\t\/\/ rogue or fails, the user can always run a dir server locally as himself and retrieve dir blocks.\n\ttestKey.SetPublicKeys(userName, []upspin.PublicKey{pubKey})\n\n\treturn &Config{\n\t\tContext: context,\n\t\tLog: &fakeLog{\n\t\t\tuser: userName,\n\t\t},\n\t\tLogIndex: &fakeLogIndex{\n\t\t\tuser: userName,\n\t\t},\n\t}\n}\n\n\/\/ fakeLog implements a simple, in-memory Log for testing.\ntype fakeLog struct {\n\tuser       upspin.UserName\n\tdirEntries []upspin.DirEntry\n}\n\nvar _ Log = (*fakeLog)(nil)\n\n\/\/ fakeLog implements a simple, in-memory LogIndex for testing.\ntype fakeLogIndex struct {\n\tuser      upspin.UserName\n\troot      *upspin.DirEntry\n\tlastIndex int\n}\n\nvar _ LogIndex = (*fakeLogIndex)(nil)\n\n\/\/ User returns the user name for whom this log logs.\nfunc (l *fakeLog) User() upspin.UserName {\n\treturn l.user\n}\n\n\/\/ Append appends a DirEntry at the end of the log.\nfunc (l *fakeLog) Append(de *upspin.DirEntry) error {\n\tl.dirEntries = append(l.dirEntries, *de)\n\treturn nil\n}\n\n\/\/ Read reads at most n entries from the log starting at index.\nfunc (l *fakeLog) Read(index, n int) ([]upspin.DirEntry, error) {\n\treturn l.dirEntries[index : index+n], nil \/\/ No error checking.\n}\n\n\/\/ LastIndex returns the index of the most-recently-appended entry.\nfunc (l *fakeLog) LastIndex() int {\n\treturn len(l.dirEntries) - 1\n}\n\n\/\/ Root returns the location of the user's root.\nfunc (l *fakeLogIndex) Root() (*upspin.DirEntry, error) {\n\tif l.root != nil {\n\t\treturn l.root, nil\n\t}\n\treturn nil, errors.E(errors.NotExist)\n}\n\n\/\/ SaveRoot saves the user's root.\nfunc (l *fakeLogIndex) SaveRoot(r *upspin.DirEntry) error {\n\tl.root = r\n\treturn nil\n}\n\n\/\/ User returns the user name who owns the root of the tree that this\n\/\/ log index represents.\nfunc (l *fakeLogIndex) User() upspin.UserName {\n\treturn l.user\n}\n\n\/\/ ReadLastIndex reads from stable storage the index saved by SaveLastIndex.\nfunc (l *fakeLogIndex) ReadLastIndex() (int, error) {\n\treturn l.lastIndex, nil\n}\n\n\/\/ SaveLastIndex saves to stable storage the last index processed.\nfunc (l *fakeLogIndex) SaveLastIndex(idx int) error {\n\tl.lastIndex = idx\n\treturn nil\n}\n<commit_msg>dir\/server\/tree: fix tests to work with new Factotum<commit_after>\/\/ Copyright 2016 The Upspin Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage tree\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"upspin.io\/context\"\n\t\"upspin.io\/errors\"\n\t\"upspin.io\/factotum\"\n\t\"upspin.io\/key\/inprocess\"\n\t\"upspin.io\/log\"\n\t\"upspin.io\/upspin\"\n\n\t_ \"upspin.io\/pack\/ee\"\n\t_ \"upspin.io\/store\/inprocess\"\n)\n\nconst (\n\tuserName   = \"user@domain.com\"\n\tserverName = \"tree@server.com\"\n)\n\n\/\/ This test checks the tree for log consistency by exercising the life-cycle of a tree,\n\/\/ from creating a new tree from scratch, adding new nodes, flushing it to Store then\n\/\/ adding more nodes to a new tree and having to load it from the Store.\nfunc TestPutNodes(t *testing.T) {\n\tcfg := newConfigForTesting(t)\n\ttree := New(userName, cfg)\n\n\tdir1 := upspin.DirEntry{\n\t\tName:    userName + \"\/\",\n\t\tAttr:    upspin.AttrDirectory,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  serverName,\n\t}\n\terr := tree.Put(&dir1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdir2 := upspin.DirEntry{\n\t\tName:    userName + \"\/dir\",\n\t\tAttr:    upspin.AttrDirectory,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  serverName,\n\t}\n\terr = tree.Put(&dir2)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdir3 := upspin.DirEntry{\n\t\tName:    userName + \"\/dir\/doc.pdf\",\n\t\tAttr:    upspin.AttrNone,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  serverName,\n\t}\n\terr = tree.Put(&dir3)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Verify three log entries were written.\n\tif got, want := cfg.Log.LastIndex(), 2; got != want {\n\t\tt.Fatalf(\"LastIndex = %d, want %d\", got, want)\n\t}\n\tentries, err := cfg.Log.Read(0, 3)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !reflect.DeepEqual(entries[0], dir1) {\n\t\tt.Errorf(\"dir1 = %v, want %v\", entries[0], dir1)\n\t}\n\tif !reflect.DeepEqual(entries[1], dir2) {\n\t\tt.Errorf(\"dir2 = %v, want %v\", entries[1], dir2)\n\t}\n\tif !reflect.DeepEqual(entries[2], dir3) {\n\t\tt.Errorf(\"dir3 = %v, want %v\", entries[2], dir3)\n\t}\n\n\t\/\/ Lookup path.\n\tde, dirty, err := tree.Lookup(userName + \"\/dir\/doc.pdf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif !dirty {\n\t\tt.Errorf(\"dirty = %v, want %v\", dirty, true)\n\t}\n\tif !reflect.DeepEqual(*de, dir3) {\n\t\tt.Errorf(\"de = %v, want %v\", de, dir3)\n\t}\n\n\t\/\/ Flush to later build a new tree and verify new is equivalent to old.\n\terr = tree.Flush()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ New log index shows we're now at the end of the log.\n\tgot, err := cfg.LogIndex.ReadLastIndex()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif want := cfg.Log.LastIndex(); got != want {\n\t\tt.Fatalf(\"cfg.Log.LastIndex() = %d, want %d\", got, want)\n\t}\n\n\t\/\/ Lookup now returns !dirty.\n\tde, dirty, err = tree.Lookup(userName + \"\/dir\/doc.pdf\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif dirty {\n\t\tt.Errorf(\"dirty = %v, want %v\", dirty, false)\n\t}\n\tif !reflect.DeepEqual(*de, dir3) {\n\t\tt.Errorf(\"de = %v, want %v\", de, dir3)\n\t}\n\n\t\/\/ Now start a new tree from scratch and confirm it is loaded from the Store.\n\ttree2 := New(userName, cfg)\n\n\tdir4 := &upspin.DirEntry{\n\t\tName:    userName + \"\/dir\/img.jpg\",\n\t\tAttr:    upspin.AttrNone,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  userName, \/\/ This was written by the user, the server is just packing it in a dir block.\n\t}\n\terr = tree2.Put(dir4)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got, want := cfg.Log.LastIndex(), 3; got != want {\n\t\tt.Fatalf(\"cfg.Log.LastIndex() = %d, want %d\", cfg.Log.LastIndex(), want)\n\t}\n\n\t\/\/ Delete dir4.\n\terr = tree2.Delete(userName + \"\/dir\/img.jpg\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t\/\/ Lookup won't return it.\n\t_, _, err = tree.Lookup(userName + \"\/dir\/img.jpg\")\n\texpectedErr := errors.E(\"Delete\", errors.NotExist, upspin.PathName(userName+\"\/dir\/img.jpg\"))\n\tif errors.Match(expectedErr, err) {\n\t\tt.Fatalf(\"err = %s, want = %s\", err, expectedErr)\n\t}\n\t\/\/ One new entry was written to the log (an updated dir2).\n\tif got, want := cfg.Log.LastIndex(), 4; got != want {\n\t\tt.Fatalf(\"cfg.Log.LastIndex() = %d, want %d\", cfg.Log.LastIndex(), want)\n\t}\n\t\/\/ Verify logged entry is a new dir2\n\tentries, err = cfg.Log.Read(4, 1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got, want := entries[0].Name, upspin.PathName(userName+\"\/dir\"); got != want {\n\t\tt.Errorf(\"entries[0].Name = %s, want = %s\", got, want)\n\t}\n}\n\n\/\/ Test that an empty root can be saved and retrieved.\n\/\/ Roots are handled differently than other directory entries.\nfunc TestPutEmptyRoot(t *testing.T) {\n\tcfg := newConfigForTesting(t)\n\ttree := New(userName, cfg)\n\n\tdir1 := &upspin.DirEntry{\n\t\tName:    userName + \"\/\",\n\t\tAttr:    upspin.AttrDirectory,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  serverName,\n\t}\n\terr := tree.Put(dir1)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\terr = tree.Flush()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Now start a new tree from scratch and confirm it is loaded from the Store just the same.\n\ttree2 := New(userName, cfg)\n\n\tdir2 := &upspin.DirEntry{\n\t\tName:    userName + \"\/dir\",\n\t\tAttr:    upspin.AttrDirectory,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  serverName,\n\t}\n\terr = tree2.Put(dir2)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t\/\/ Try to put a file under an non-existent dir\n\tdir3 := &upspin.DirEntry{\n\t\tName:    userName + \"\/invaliddir\/myfile.txt\",\n\t\tAttr:    upspin.AttrNone,\n\t\tPacking: cfg.Context.Packing(),\n\t\tWriter:  serverName,\n\t}\n\terr = tree2.Put(dir3)\n\tif err == nil {\n\t\tt.Fatal(\"Expected error, got none\")\n\t}\n\texpectedErr := errors.E(errors.NotExist)\n\tif !errors.Match(expectedErr, err) {\n\t\tt.Errorf(\"err = %s, want %s\", err, expectedErr)\n\t}\n}\n\n\/\/ TODO: TestPutLargeNode: test that a huge DirEntry (>blockSize) gets split into multiple ones.\n\/\/ TODO: Run all tests in loop using Plain and Debug packs as well.\n\/\/ TODO: test more error cases.\n\/\/ TODO: Implement and test starting the tree from a non-empty log and a log index not at the end of the log.\n\n\/\/ newConfigForTesting creates a config with mocks, fakes, inprocess and otherwise testing\n\/\/ versions of the Tree's dependencies.\nfunc newConfigForTesting(t *testing.T) *Config {\n\tfactotum, err := factotum.New(repo(\"key\/testdata\/upspin-test\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tendpointInProcess := upspin.Endpoint{\n\t\tTransport: upspin.InProcess,\n\t\tNetAddr:   \"\",\n\t}\n\tcontext := context.New().\n\t\tSetFactotum(factotum).\n\t\tSetUserName(serverName).\n\t\tSetStoreEndpoint(endpointInProcess).\n\t\tSetKeyEndpoint(endpointInProcess).\n\t\tSetPacking(upspin.EEPack)\n\tkey := context.KeyServer()\n\ttestKey, ok := key.(*inprocess.Service)\n\tif !ok {\n\t\tt.Fatal(err)\n\t}\n\t\/\/ Set the public key for the tree, since it must do Auth against the Store.\n\ttestKey.SetPublicKeys(serverName, []upspin.PublicKey{factotum.PublicKey()})\n\n\t\/\/ Set the public key for the user, since EE Pack requires the dir owner to have a wrapped key.\n\t\/\/ TODO: re-think this for directories, but probably correct as-is because if the dir server goes\n\t\/\/ rogue or fails, the user can always run a dir server locally as himself and retrieve dir blocks.\n\ttestKey.SetPublicKeys(userName, []upspin.PublicKey{factotum.PublicKey()})\n\n\treturn &Config{\n\t\tContext: context,\n\t\tLog: &fakeLog{\n\t\t\tuser: userName,\n\t\t},\n\t\tLogIndex: &fakeLogIndex{\n\t\t\tuser: userName,\n\t\t},\n\t}\n}\n\n\/\/ fakeLog implements a simple, in-memory Log for testing.\ntype fakeLog struct {\n\tuser       upspin.UserName\n\tdirEntries []upspin.DirEntry\n}\n\nvar _ Log = (*fakeLog)(nil)\n\n\/\/ fakeLog implements a simple, in-memory LogIndex for testing.\ntype fakeLogIndex struct {\n\tuser      upspin.UserName\n\troot      *upspin.DirEntry\n\tlastIndex int\n}\n\nvar _ LogIndex = (*fakeLogIndex)(nil)\n\n\/\/ User returns the user name for whom this log logs.\nfunc (l *fakeLog) User() upspin.UserName {\n\treturn l.user\n}\n\n\/\/ Append appends a DirEntry at the end of the log.\nfunc (l *fakeLog) Append(de *upspin.DirEntry) error {\n\tl.dirEntries = append(l.dirEntries, *de)\n\treturn nil\n}\n\n\/\/ Read reads at most n entries from the log starting at index.\nfunc (l *fakeLog) Read(index, n int) ([]upspin.DirEntry, error) {\n\treturn l.dirEntries[index : index+n], nil \/\/ No error checking.\n}\n\n\/\/ LastIndex returns the index of the most-recently-appended entry.\nfunc (l *fakeLog) LastIndex() int {\n\treturn len(l.dirEntries) - 1\n}\n\n\/\/ Root returns the location of the user's root.\nfunc (l *fakeLogIndex) Root() (*upspin.DirEntry, error) {\n\tif l.root != nil {\n\t\treturn l.root, nil\n\t}\n\treturn nil, errors.E(errors.NotExist)\n}\n\n\/\/ SaveRoot saves the user's root.\nfunc (l *fakeLogIndex) SaveRoot(r *upspin.DirEntry) error {\n\tl.root = r\n\treturn nil\n}\n\n\/\/ User returns the user name who owns the root of the tree that this\n\/\/ log index represents.\nfunc (l *fakeLogIndex) User() upspin.UserName {\n\treturn l.user\n}\n\n\/\/ ReadLastIndex reads from stable storage the index saved by SaveLastIndex.\nfunc (l *fakeLogIndex) ReadLastIndex() (int, error) {\n\treturn l.lastIndex, nil\n}\n\n\/\/ SaveLastIndex saves to stable storage the last index processed.\nfunc (l *fakeLogIndex) SaveLastIndex(idx int) error {\n\tl.lastIndex = idx\n\treturn nil\n}\n\n\/\/ repo returns the local pathname of a file in the upspin repository.\nfunc repo(dir string) string {\n\tgopath := os.Getenv(\"GOPATH\")\n\tif len(gopath) == 0 {\n\t\tlog.Fatal(\"no GOPATH\")\n\t}\n\treturn filepath.Join(gopath, \"src\/upspin.io\/\"+dir)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/docker-library\/go-dockerlibrary\/manifest\"\n\t\"github.com\/docker-library\/go-dockerlibrary\/pkg\/execpipe\"\n\n\tgoGit \"gopkg.in\/src-d\/go-git.v4\"\n\tgoGitConfig \"gopkg.in\/src-d\/go-git.v4\/config\"\n\tgoGitPlumbing \"gopkg.in\/src-d\/go-git.v4\/plumbing\"\n)\n\nfunc gitCache() string {\n\treturn filepath.Join(defaultCache, \"git\")\n}\n\nfunc gitCommand(args ...string) *exec.Cmd {\n\tif debugFlag {\n\t\tfmt.Printf(\"$ git %q\\n\", args)\n\t}\n\tcmd := exec.Command(\"git\", args...)\n\tcmd.Dir = gitCache()\n\treturn cmd\n}\n\nfunc git(args ...string) ([]byte, error) {\n\tout, err := gitCommand(args...).Output()\n\tif err != nil {\n\t\tif ee, ok := err.(*exec.ExitError); ok {\n\t\t\treturn nil, fmt.Errorf(\"%v\\ncommand: git %q\\n%s\", ee, args, string(ee.Stderr))\n\t\t}\n\t}\n\treturn out, err\n}\n\nvar gitRepo *goGit.Repository\n\nfunc ensureGitInit() error {\n\tif gitRepo != nil {\n\t\treturn nil\n\t}\n\n\tgitCacheDir := gitCache()\n\terr := os.MkdirAll(gitCacheDir, os.ModePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgitRepo, err = goGit.PlainInit(gitCacheDir, true)\n\tif err == goGit.ErrRepositoryAlreadyExists {\n\t\tgitRepo, err = goGit.PlainOpen(gitCacheDir)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ ensure garbage collection is disabled so we keep dangling commits\n\tconfig, err := gitRepo.Config()\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.Raw = config.Raw.SetOption(\"gc\", \"\", \"auto\", \"0\")\n\tgitRepo.Storer.SetConfig(config)\n\n\treturn nil\n}\n\nvar fullGitCommitRegex = regexp.MustCompile(`^[0-9a-f]{40}$|^[0-9a-f]{64}$`)\n\nfunc getGitCommit(commit string) (string, error) {\n\tif fullGitCommitRegex.MatchString(commit) {\n\t\t_, err := gitRepo.CommitObject(goGitPlumbing.NewHash(commit))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn commit, nil\n\t}\n\n\th, err := gitRepo.ResolveRevision(goGitPlumbing.Revision(commit + \"^{commit}\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn h.String(), nil\n}\n\nfunc gitStream(args ...string) (io.ReadCloser, error) {\n\treturn execpipe.Run(gitCommand(args...))\n}\n\nfunc gitArchive(commit string, dir string) (io.ReadCloser, error) {\n\tif dir == \".\" {\n\t\tdir = \"\"\n\t} else {\n\t\tdir += \"\/\"\n\t}\n\treturn gitStream(\"archive\", \"--format=tar\", commit+\":\"+dir)\n}\n\nfunc gitShow(commit string, file string) (string, error) {\n\tgitCommit, err := gitRepo.CommitObject(goGitPlumbing.NewHash(commit))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tgitFile, err := gitCommit.File(file)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcontents, err := gitFile.Contents()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn contents, nil\n}\n\n\/\/ for gitNormalizeForTagUsage()\n\/\/ see http:\/\/stackoverflow.com\/a\/26382358\/433558\nvar (\n\tgitBadTagChars = regexp.MustCompile(`(?:` + strings.Join([]string{\n\t\t`[^0-9a-zA-Z\/._-]+`,\n\n\t\t\/\/ They can include slash `\/` for hierarchical (directory) grouping, but no slash-separated component can begin with a dot `.` or end with the sequence `.lock`.\n\t\t`\/[.]+`,\n\t\t`[.]lock(?:\/|$)`,\n\n\t\t\/\/ They cannot have two consecutive dots `..` anywhere.\n\t\t`[.][.]+`,\n\n\t\t\/\/ They cannot end with a dot `.`\n\t\t\/\/ They cannot begin or end with a slash `\/`\n\t\t`[\/.]+$`,\n\t\t`^[\/.]+`,\n\t}, `|`) + `)`)\n\n\tgitMultipleSlashes = regexp.MustCompile(`(?:\/\/+)`)\n)\n\n\/\/ strip\/replace \"bad\" characters from text for use as a Git tag\nfunc gitNormalizeForTagUsage(text string) string {\n\treturn gitMultipleSlashes.ReplaceAllString(gitBadTagChars.ReplaceAllString(text, \"-\"), \"\/\")\n}\n\nvar gitRepoCache = map[string]string{}\n\nfunc (r Repo) fetchGitRepo(arch string, entry *manifest.Manifest2822Entry) (string, error) {\n\tcacheKey := strings.Join([]string{\n\t\tentry.ArchGitRepo(arch),\n\t\tentry.ArchGitFetch(arch),\n\t\tentry.ArchGitCommit(arch),\n\t}, \"\\n\")\n\tif commit, ok := gitRepoCache[cacheKey]; ok {\n\t\tentry.SetGitCommit(arch, commit)\n\t\treturn commit, nil\n\t}\n\n\terr := ensureGitInit()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif manifest.GitCommitRegex.MatchString(entry.ArchGitCommit(arch)) {\n\t\tcommit, err := getGitCommit(entry.ArchGitCommit(arch))\n\t\tif err == nil {\n\t\t\tgitRepoCache[cacheKey] = commit\n\t\t\tentry.SetGitCommit(arch, commit)\n\t\t\treturn commit, nil\n\t\t}\n\t}\n\n\tfetchString := entry.ArchGitFetch(arch) + \":\"\n\tif entry.ArchGitCommit(arch) == \"FETCH_HEAD\" {\n\t\t\/\/ fetch remote tag references to a local tag ref so that we can cache them and not re-fetch every time\n\t\tlocalRef := \"refs\/tags\/\" + gitNormalizeForTagUsage(cacheKey)\n\t\tcommit, err := getGitCommit(localRef)\n\t\tif err == nil {\n\t\t\tgitRepoCache[cacheKey] = commit\n\t\t\tentry.SetGitCommit(arch, commit)\n\t\t\treturn commit, nil\n\t\t}\n\t\tfetchString += localRef\n\t} else {\n\t\t\/\/ we create a temporary remote dir so that we can clean it up completely afterwards\n\t\trefBase := \"refs\/remotes\"\n\t\trefBaseDir := filepath.Join(gitCache(), refBase)\n\n\t\terr := os.MkdirAll(refBaseDir, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\ttempRefDir, err := ioutil.TempDir(refBaseDir, \"temp\")\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tdefer os.RemoveAll(tempRefDir)\n\n\t\ttempRef := path.Join(refBase, filepath.Base(tempRefDir))\n\t\tif entry.ArchGitFetch(arch) == manifest.DefaultLineBasedFetch {\n\t\t\t\/\/ backwards compat (see manifest\/line-based.go in go-dockerlibrary)\n\t\t\tfetchString += tempRef + \"\/*\"\n\t\t} else {\n\t\t\tfetchString += tempRef + \"\/temp\"\n\t\t}\n\t}\n\n\tif strings.HasPrefix(entry.ArchGitRepo(arch), \"git:\/\/github.com\/\") {\n\t\tfmt.Fprintf(os.Stderr, \"warning: insecure protocol git:\/\/ detected: %s\\n\", entry.ArchGitRepo(arch))\n\t\tentry.SetGitRepo(arch, strings.Replace(entry.ArchGitRepo(arch), \"git:\/\/\", \"https:\/\/\", 1))\n\t}\n\n\tgitRemote, err := gitRepo.CreateRemoteAnonymous(&goGitConfig.RemoteConfig{\n\t\tName: \"anonymous\",\n\t\tURLs: []string{entry.ArchGitRepo(arch)},\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = gitRemote.Fetch(&goGit.FetchOptions{\n\t\tRefSpecs: []goGitConfig.RefSpec{goGitConfig.RefSpec(fetchString)},\n\t\tTags:     goGit.NoTags,\n\n\t\t\/\/Progress: os.Stdout,\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcommit, err := getGitCommit(entry.ArchGitCommit(arch))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t_, err = gitRepo.CreateTag(arch+\"\/\"+r.RepoName+\"\/\"+entry.Tags[0], goGitPlumbing.NewHash(commit), nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tgitRepoCache[cacheKey] = commit\n\tentry.SetGitCommit(arch, commit)\n\treturn commit, nil\n}\n<commit_msg>Add \"DeleteTag\" before \"CreateTag\" to avoid \"ErrTagExists\"<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/docker-library\/go-dockerlibrary\/manifest\"\n\t\"github.com\/docker-library\/go-dockerlibrary\/pkg\/execpipe\"\n\n\tgoGit \"gopkg.in\/src-d\/go-git.v4\"\n\tgoGitConfig \"gopkg.in\/src-d\/go-git.v4\/config\"\n\tgoGitPlumbing \"gopkg.in\/src-d\/go-git.v4\/plumbing\"\n)\n\nfunc gitCache() string {\n\treturn filepath.Join(defaultCache, \"git\")\n}\n\nfunc gitCommand(args ...string) *exec.Cmd {\n\tif debugFlag {\n\t\tfmt.Printf(\"$ git %q\\n\", args)\n\t}\n\tcmd := exec.Command(\"git\", args...)\n\tcmd.Dir = gitCache()\n\treturn cmd\n}\n\nfunc git(args ...string) ([]byte, error) {\n\tout, err := gitCommand(args...).Output()\n\tif err != nil {\n\t\tif ee, ok := err.(*exec.ExitError); ok {\n\t\t\treturn nil, fmt.Errorf(\"%v\\ncommand: git %q\\n%s\", ee, args, string(ee.Stderr))\n\t\t}\n\t}\n\treturn out, err\n}\n\nvar gitRepo *goGit.Repository\n\nfunc ensureGitInit() error {\n\tif gitRepo != nil {\n\t\treturn nil\n\t}\n\n\tgitCacheDir := gitCache()\n\terr := os.MkdirAll(gitCacheDir, os.ModePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgitRepo, err = goGit.PlainInit(gitCacheDir, true)\n\tif err == goGit.ErrRepositoryAlreadyExists {\n\t\tgitRepo, err = goGit.PlainOpen(gitCacheDir)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ ensure garbage collection is disabled so we keep dangling commits\n\tconfig, err := gitRepo.Config()\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig.Raw = config.Raw.SetOption(\"gc\", \"\", \"auto\", \"0\")\n\tgitRepo.Storer.SetConfig(config)\n\n\treturn nil\n}\n\nvar fullGitCommitRegex = regexp.MustCompile(`^[0-9a-f]{40}$|^[0-9a-f]{64}$`)\n\nfunc getGitCommit(commit string) (string, error) {\n\tif fullGitCommitRegex.MatchString(commit) {\n\t\t_, err := gitRepo.CommitObject(goGitPlumbing.NewHash(commit))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn commit, nil\n\t}\n\n\th, err := gitRepo.ResolveRevision(goGitPlumbing.Revision(commit + \"^{commit}\"))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn h.String(), nil\n}\n\nfunc gitStream(args ...string) (io.ReadCloser, error) {\n\treturn execpipe.Run(gitCommand(args...))\n}\n\nfunc gitArchive(commit string, dir string) (io.ReadCloser, error) {\n\tif dir == \".\" {\n\t\tdir = \"\"\n\t} else {\n\t\tdir += \"\/\"\n\t}\n\treturn gitStream(\"archive\", \"--format=tar\", commit+\":\"+dir)\n}\n\nfunc gitShow(commit string, file string) (string, error) {\n\tgitCommit, err := gitRepo.CommitObject(goGitPlumbing.NewHash(commit))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tgitFile, err := gitCommit.File(file)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcontents, err := gitFile.Contents()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn contents, nil\n}\n\n\/\/ for gitNormalizeForTagUsage()\n\/\/ see http:\/\/stackoverflow.com\/a\/26382358\/433558\nvar (\n\tgitBadTagChars = regexp.MustCompile(`(?:` + strings.Join([]string{\n\t\t`[^0-9a-zA-Z\/._-]+`,\n\n\t\t\/\/ They can include slash `\/` for hierarchical (directory) grouping, but no slash-separated component can begin with a dot `.` or end with the sequence `.lock`.\n\t\t`\/[.]+`,\n\t\t`[.]lock(?:\/|$)`,\n\n\t\t\/\/ They cannot have two consecutive dots `..` anywhere.\n\t\t`[.][.]+`,\n\n\t\t\/\/ They cannot end with a dot `.`\n\t\t\/\/ They cannot begin or end with a slash `\/`\n\t\t`[\/.]+$`,\n\t\t`^[\/.]+`,\n\t}, `|`) + `)`)\n\n\tgitMultipleSlashes = regexp.MustCompile(`(?:\/\/+)`)\n)\n\n\/\/ strip\/replace \"bad\" characters from text for use as a Git tag\nfunc gitNormalizeForTagUsage(text string) string {\n\treturn gitMultipleSlashes.ReplaceAllString(gitBadTagChars.ReplaceAllString(text, \"-\"), \"\/\")\n}\n\nvar gitRepoCache = map[string]string{}\n\nfunc (r Repo) fetchGitRepo(arch string, entry *manifest.Manifest2822Entry) (string, error) {\n\tcacheKey := strings.Join([]string{\n\t\tentry.ArchGitRepo(arch),\n\t\tentry.ArchGitFetch(arch),\n\t\tentry.ArchGitCommit(arch),\n\t}, \"\\n\")\n\tif commit, ok := gitRepoCache[cacheKey]; ok {\n\t\tentry.SetGitCommit(arch, commit)\n\t\treturn commit, nil\n\t}\n\n\terr := ensureGitInit()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif manifest.GitCommitRegex.MatchString(entry.ArchGitCommit(arch)) {\n\t\tcommit, err := getGitCommit(entry.ArchGitCommit(arch))\n\t\tif err == nil {\n\t\t\tgitRepoCache[cacheKey] = commit\n\t\t\tentry.SetGitCommit(arch, commit)\n\t\t\treturn commit, nil\n\t\t}\n\t}\n\n\tfetchString := entry.ArchGitFetch(arch) + \":\"\n\tif entry.ArchGitCommit(arch) == \"FETCH_HEAD\" {\n\t\t\/\/ fetch remote tag references to a local tag ref so that we can cache them and not re-fetch every time\n\t\tlocalRef := \"refs\/tags\/\" + gitNormalizeForTagUsage(cacheKey)\n\t\tcommit, err := getGitCommit(localRef)\n\t\tif err == nil {\n\t\t\tgitRepoCache[cacheKey] = commit\n\t\t\tentry.SetGitCommit(arch, commit)\n\t\t\treturn commit, nil\n\t\t}\n\t\tfetchString += localRef\n\t} else {\n\t\t\/\/ we create a temporary remote dir so that we can clean it up completely afterwards\n\t\trefBase := \"refs\/remotes\"\n\t\trefBaseDir := filepath.Join(gitCache(), refBase)\n\n\t\terr := os.MkdirAll(refBaseDir, os.ModePerm)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\ttempRefDir, err := ioutil.TempDir(refBaseDir, \"temp\")\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tdefer os.RemoveAll(tempRefDir)\n\n\t\ttempRef := path.Join(refBase, filepath.Base(tempRefDir))\n\t\tif entry.ArchGitFetch(arch) == manifest.DefaultLineBasedFetch {\n\t\t\t\/\/ backwards compat (see manifest\/line-based.go in go-dockerlibrary)\n\t\t\tfetchString += tempRef + \"\/*\"\n\t\t} else {\n\t\t\tfetchString += tempRef + \"\/temp\"\n\t\t}\n\t}\n\n\tif strings.HasPrefix(entry.ArchGitRepo(arch), \"git:\/\/github.com\/\") {\n\t\tfmt.Fprintf(os.Stderr, \"warning: insecure protocol git:\/\/ detected: %s\\n\", entry.ArchGitRepo(arch))\n\t\tentry.SetGitRepo(arch, strings.Replace(entry.ArchGitRepo(arch), \"git:\/\/\", \"https:\/\/\", 1))\n\t}\n\n\tgitRemote, err := gitRepo.CreateRemoteAnonymous(&goGitConfig.RemoteConfig{\n\t\tName: \"anonymous\",\n\t\tURLs: []string{entry.ArchGitRepo(arch)},\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = gitRemote.Fetch(&goGit.FetchOptions{\n\t\tRefSpecs: []goGitConfig.RefSpec{goGitConfig.RefSpec(fetchString)},\n\t\tTags:     goGit.NoTags,\n\n\t\t\/\/Progress: os.Stdout,\n\t})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcommit, err := getGitCommit(entry.ArchGitCommit(arch))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tgitTag := arch+\"\/\"+r.RepoName+\"\/\"+entry.Tags[0]\n\tgitRepo.DeleteTag(gitTag) \/\/ avoid \"ErrTagExists\"\n\t_, err = gitRepo.CreateTag(gitTag, goGitPlumbing.NewHash(commit), nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tgitRepoCache[cacheKey] = commit\n\tentry.SetGitCommit(arch, commit)\n\treturn commit, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"golang.org\/x\/sys\/unix\"\n\n\t\"github.com\/lxc\/lxd\/lxd\/response\"\n\t\"github.com\/lxc\/lxd\/shared\"\n)\n\nvar fileCmd = APIEndpoint{\n\tName: \"file\",\n\tPath: \"files\",\n\n\tGet:    APIEndpointAction{Handler: fileHandler},\n\tPost:   APIEndpointAction{Handler: fileHandler},\n\tDelete: APIEndpointAction{Handler: fileHandler},\n}\n\nfunc fileHandler(d *Daemon, r *http.Request) response.Response {\n\tpath := r.FormValue(\"path\")\n\tif path == \"\" {\n\t\treturn response.BadRequest(fmt.Errorf(\"missing path argument\"))\n\t}\n\n\tswitch r.Method {\n\tcase \"GET\":\n\t\treturn fileGet(path, r)\n\tcase \"POST\":\n\t\treturn filePost(path, r)\n\tcase \"DELETE\":\n\t\treturn fileDelete(path, r)\n\tdefault:\n\t\treturn response.NotFound(fmt.Errorf(\"Method '%s' not found\", r.Method))\n\t}\n}\n\nfunc fileGet(path string, r *http.Request) response.Response {\n\tuid, gid, mode, fType, dirEnts, err := getFileInfo(path)\n\tif err != nil {\n\t\treturn response.SmartError(err)\n\t}\n\n\theaders := map[string]string{\n\t\t\"X-LXD-uid\":  fmt.Sprintf(\"%d\", uid),\n\t\t\"X-LXD-gid\":  fmt.Sprintf(\"%d\", gid),\n\t\t\"X-LXD-mode\": fmt.Sprintf(\"%04o\", mode),\n\t\t\"X-LXD-type\": fType,\n\t}\n\n\tif fType == \"file\" || fType == \"symlink\" {\n\t\t\/\/ Make a file response struct\n\t\tfiles := make([]response.FileResponseEntry, 1)\n\t\tfiles[0].Identifier = filepath.Base(path)\n\n\t\tf, err := ioutil.TempFile(filepath.Dir(path), \"lxd_getfile_\")\n\t\tif err != nil {\n\t\t\treturn response.SmartError(err)\n\t\t}\n\t\tdefer f.Close()\n\n\t\tif fType == \"file\" {\n\t\t\tsrc, err := os.Open(path)\n\t\t\tif err != nil {\n\t\t\t\treturn response.SmartError(err)\n\t\t\t}\n\t\t\tdefer src.Close()\n\n\t\t\t_, err = io.Copy(f, src)\n\t\t\tif err != nil {\n\t\t\t\treturn response.SmartError(err)\n\t\t\t}\n\t\t} else {\n\t\t\ttarget, err := os.Readlink(path)\n\t\t\tif err != nil {\n\t\t\t\treturn response.SmartError(err)\n\t\t\t}\n\n\t\t\t_, err = f.WriteString(target + \"\\n\")\n\t\t\tif err != nil {\n\t\t\t\treturn response.SmartError(err)\n\t\t\t}\n\t\t}\n\n\t\tfiles[0].Path = f.Name()\n\t\tfiles[0].Filename = filepath.Base(path)\n\n\t\treturn response.FileResponse(r, files, headers, true)\n\t} else if fType == \"directory\" {\n\t\treturn response.SyncResponseHeaders(true, dirEnts, headers)\n\t}\n\n\treturn response.InternalError(fmt.Errorf(\"bad file type %s\", fType))\n}\n\nfunc filePost(path string, r *http.Request) response.Response {\n\t\/\/ Extract file ownership and mode from headers\n\tuid, gid, mode, fType, write := shared.ParseLXDFileHeaders(r.Header)\n\n\tif !shared.StringInSlice(write, []string{\"overwrite\", \"append\"}) {\n\t\treturn response.BadRequest(fmt.Errorf(\"Bad file write mode: %s\", write))\n\t}\n\n\tif fType == \"file\" {\n\t\t\/\/ Write file content to a tempfile\n\t\ttemp, err := ioutil.TempFile(\"\", \"lxd_forkputfile_\")\n\t\tif err != nil {\n\t\t\treturn response.InternalError(err)\n\t\t}\n\t\tdefer func() {\n\t\t\ttemp.Close()\n\t\t\tos.Remove(temp.Name())\n\t\t}()\n\n\t\t_, err = io.Copy(temp, r.Body)\n\t\tif err != nil {\n\t\t\treturn response.InternalError(err)\n\t\t}\n\n\t\t\/\/ Transfer the file into the container\n\t\terr = filePush(\"file\", temp.Name(), path, uid, gid, mode, write)\n\t\tif err != nil {\n\t\t\treturn response.InternalError(err)\n\t\t}\n\n\t\treturn response.EmptySyncResponse\n\t} else if fType == \"symlink\" {\n\t\ttarget, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn response.InternalError(err)\n\t\t}\n\n\t\terr = filePush(\"symlink\", string(target), path, uid, gid, mode, write)\n\t\tif err != nil {\n\t\t\treturn response.InternalError(err)\n\t\t}\n\t\treturn response.EmptySyncResponse\n\t} else if fType == \"directory\" {\n\t\terr := filePush(\"directory\", \"\", path, uid, gid, mode, write)\n\t\tif err != nil {\n\t\t\treturn response.InternalError(err)\n\t\t}\n\t\treturn response.EmptySyncResponse\n\t}\n\n\treturn response.BadRequest(fmt.Errorf(\"Bad file type: %s\", fType))\n}\n\nfunc fileDelete(path string, r *http.Request) response.Response {\n\terr := os.Remove(path)\n\tif err != nil {\n\t\treturn response.SmartError(err)\n\t}\n\n\treturn response.EmptySyncResponse\n}\n\nfunc getFileInfo(path string) (int64, int64, os.FileMode, string, []string, error) {\n\tvar stat unix.Stat_t\n\n\terr := os.Chdir(\"\/\")\n\tif err != nil {\n\t\treturn -1, -1, 0, \"\", nil, err\n\t}\n\n\tfi, err := os.Lstat(path)\n\tif err != nil {\n\t\treturn -1, -1, 0, \"\", nil, err\n\t}\n\n\terr = unix.Lstat(path, &stat)\n\tif err != nil {\n\t\treturn -1, -1, 0, \"\", nil, err\n\t}\n\n\tvar fType string\n\tvar dirEnts []string\n\n\tif fi.Mode().IsDir() {\n\t\tfType = \"directory\"\n\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn -1, -1, 0, \"\", nil, err\n\t\t}\n\n\t\tdirEnts, err = f.Readdirnames(0)\n\t\tif err != nil {\n\t\t\treturn -1, -1, 0, \"\", nil, err\n\t\t}\n\n\t} else {\n\t\tif fi.Mode()&os.ModeSymlink != 0 {\n\t\t\tfType = \"symlink\"\n\t\t} else {\n\t\t\tfType = \"file\"\n\t\t}\n\t}\n\n\t\/\/ 0xFFF = 0b7777\n\treturn int64(stat.Uid), int64(stat.Gid), fi.Mode() & 0xFFF, fType, dirEnts, nil\n}\n\nfunc filePush(fType string, srcpath string, dstpath string, uid int64, gid int64, mode int, write string) error {\n\tswitch fType {\n\tcase \"file\":\n\t\tif !shared.PathExists(dstpath) {\n\t\t\tif uid == -1 {\n\t\t\t\tuid = 0\n\t\t\t}\n\n\t\t\tif gid == -1 {\n\t\t\t\tgid = 0\n\t\t\t}\n\n\t\t\tif mode == -1 {\n\t\t\t\tmode = 0\n\t\t\t}\n\t\t}\n\n\t\tflags := os.O_CREATE | os.O_WRONLY\n\n\t\tif write == \"overwrite\" {\n\t\t\tflags |= os.O_TRUNC\n\t\t} else if write == \"append\" {\n\t\t\tflags |= os.O_APPEND\n\t\t}\n\n\t\tdst, err := os.OpenFile(dstpath, flags, os.FileMode(mode))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer dst.Close()\n\n\t\tsrc, err := os.Open(srcpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer src.Close()\n\n\t\t_, err = io.Copy(dst, src)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = os.Chown(dst.Name(), int(uid), int(gid))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\tcase \"symlink\":\n\t\tif uid == -1 {\n\t\t\tuid = 0\n\t\t}\n\n\t\tif gid == -1 {\n\t\t\tgid = 0\n\t\t}\n\n\t\terr := os.Symlink(srcpath, dstpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = os.Lchown(dstpath, int(uid), int(gid))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\tcase \"directory\":\n\t\tif uid == -1 {\n\t\t\tuid = 0\n\t\t}\n\n\t\tif gid == -1 {\n\t\t\tgid = 0\n\t\t}\n\n\t\tif mode == -1 {\n\t\t\tmode = 0\n\t\t}\n\n\t\terr := os.MkdirAll(dstpath, os.FileMode(mode))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = os.Chown(dstpath, int(uid), int(gid))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"Bad file type: %s\", fType)\n}\n<commit_msg>lxd-agent: Update for FileResponse changes<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"golang.org\/x\/sys\/unix\"\n\n\t\"github.com\/lxc\/lxd\/lxd\/response\"\n\t\"github.com\/lxc\/lxd\/shared\"\n)\n\nvar fileCmd = APIEndpoint{\n\tName: \"file\",\n\tPath: \"files\",\n\n\tGet:    APIEndpointAction{Handler: fileHandler},\n\tPost:   APIEndpointAction{Handler: fileHandler},\n\tDelete: APIEndpointAction{Handler: fileHandler},\n}\n\nfunc fileHandler(d *Daemon, r *http.Request) response.Response {\n\tpath := r.FormValue(\"path\")\n\tif path == \"\" {\n\t\treturn response.BadRequest(fmt.Errorf(\"missing path argument\"))\n\t}\n\n\tswitch r.Method {\n\tcase \"GET\":\n\t\treturn fileGet(path, r)\n\tcase \"POST\":\n\t\treturn filePost(path, r)\n\tcase \"DELETE\":\n\t\treturn fileDelete(path, r)\n\tdefault:\n\t\treturn response.NotFound(fmt.Errorf(\"Method '%s' not found\", r.Method))\n\t}\n}\n\nfunc fileGet(path string, r *http.Request) response.Response {\n\tuid, gid, mode, fType, dirEnts, err := getFileInfo(path)\n\tif err != nil {\n\t\treturn response.SmartError(err)\n\t}\n\n\theaders := map[string]string{\n\t\t\"X-LXD-uid\":  fmt.Sprintf(\"%d\", uid),\n\t\t\"X-LXD-gid\":  fmt.Sprintf(\"%d\", gid),\n\t\t\"X-LXD-mode\": fmt.Sprintf(\"%04o\", mode),\n\t\t\"X-LXD-type\": fType,\n\t}\n\n\tif fType == \"file\" || fType == \"symlink\" {\n\t\t\/\/ Make a file response struct\n\t\tfiles := make([]response.FileResponseEntry, 1)\n\t\tfiles[0].Identifier = filepath.Base(path)\n\n\t\tf, err := ioutil.TempFile(filepath.Dir(path), \"lxd_getfile_\")\n\t\tif err != nil {\n\t\t\treturn response.SmartError(err)\n\t\t}\n\t\tdefer f.Close()\n\n\t\tif fType == \"file\" {\n\t\t\tsrc, err := os.Open(path)\n\t\t\tif err != nil {\n\t\t\t\treturn response.SmartError(err)\n\t\t\t}\n\t\t\tdefer src.Close()\n\n\t\t\t_, err = io.Copy(f, src)\n\t\t\tif err != nil {\n\t\t\t\treturn response.SmartError(err)\n\t\t\t}\n\t\t} else {\n\t\t\ttarget, err := os.Readlink(path)\n\t\t\tif err != nil {\n\t\t\t\treturn response.SmartError(err)\n\t\t\t}\n\n\t\t\t_, err = f.WriteString(target + \"\\n\")\n\t\t\tif err != nil {\n\t\t\t\treturn response.SmartError(err)\n\t\t\t}\n\t\t}\n\n\t\tfiles[0].Path = f.Name()\n\t\tfiles[0].Filename = filepath.Base(path)\n\t\tfiles[0].Cleanup = func() { os.Remove(f.Name()) }\n\n\t\treturn response.FileResponse(r, files, headers)\n\t} else if fType == \"directory\" {\n\t\treturn response.SyncResponseHeaders(true, dirEnts, headers)\n\t}\n\n\treturn response.InternalError(fmt.Errorf(\"bad file type %s\", fType))\n}\n\nfunc filePost(path string, r *http.Request) response.Response {\n\t\/\/ Extract file ownership and mode from headers\n\tuid, gid, mode, fType, write := shared.ParseLXDFileHeaders(r.Header)\n\n\tif !shared.StringInSlice(write, []string{\"overwrite\", \"append\"}) {\n\t\treturn response.BadRequest(fmt.Errorf(\"Bad file write mode: %s\", write))\n\t}\n\n\tif fType == \"file\" {\n\t\t\/\/ Write file content to a tempfile\n\t\ttemp, err := ioutil.TempFile(\"\", \"lxd_forkputfile_\")\n\t\tif err != nil {\n\t\t\treturn response.InternalError(err)\n\t\t}\n\t\tdefer func() {\n\t\t\ttemp.Close()\n\t\t\tos.Remove(temp.Name())\n\t\t}()\n\n\t\t_, err = io.Copy(temp, r.Body)\n\t\tif err != nil {\n\t\t\treturn response.InternalError(err)\n\t\t}\n\n\t\t\/\/ Transfer the file into the container\n\t\terr = filePush(\"file\", temp.Name(), path, uid, gid, mode, write)\n\t\tif err != nil {\n\t\t\treturn response.InternalError(err)\n\t\t}\n\n\t\treturn response.EmptySyncResponse\n\t} else if fType == \"symlink\" {\n\t\ttarget, err := ioutil.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\treturn response.InternalError(err)\n\t\t}\n\n\t\terr = filePush(\"symlink\", string(target), path, uid, gid, mode, write)\n\t\tif err != nil {\n\t\t\treturn response.InternalError(err)\n\t\t}\n\t\treturn response.EmptySyncResponse\n\t} else if fType == \"directory\" {\n\t\terr := filePush(\"directory\", \"\", path, uid, gid, mode, write)\n\t\tif err != nil {\n\t\t\treturn response.InternalError(err)\n\t\t}\n\t\treturn response.EmptySyncResponse\n\t}\n\n\treturn response.BadRequest(fmt.Errorf(\"Bad file type: %s\", fType))\n}\n\nfunc fileDelete(path string, r *http.Request) response.Response {\n\terr := os.Remove(path)\n\tif err != nil {\n\t\treturn response.SmartError(err)\n\t}\n\n\treturn response.EmptySyncResponse\n}\n\nfunc getFileInfo(path string) (int64, int64, os.FileMode, string, []string, error) {\n\tvar stat unix.Stat_t\n\n\terr := os.Chdir(\"\/\")\n\tif err != nil {\n\t\treturn -1, -1, 0, \"\", nil, err\n\t}\n\n\tfi, err := os.Lstat(path)\n\tif err != nil {\n\t\treturn -1, -1, 0, \"\", nil, err\n\t}\n\n\terr = unix.Lstat(path, &stat)\n\tif err != nil {\n\t\treturn -1, -1, 0, \"\", nil, err\n\t}\n\n\tvar fType string\n\tvar dirEnts []string\n\n\tif fi.Mode().IsDir() {\n\t\tfType = \"directory\"\n\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn -1, -1, 0, \"\", nil, err\n\t\t}\n\n\t\tdirEnts, err = f.Readdirnames(0)\n\t\tif err != nil {\n\t\t\treturn -1, -1, 0, \"\", nil, err\n\t\t}\n\n\t} else {\n\t\tif fi.Mode()&os.ModeSymlink != 0 {\n\t\t\tfType = \"symlink\"\n\t\t} else {\n\t\t\tfType = \"file\"\n\t\t}\n\t}\n\n\t\/\/ 0xFFF = 0b7777\n\treturn int64(stat.Uid), int64(stat.Gid), fi.Mode() & 0xFFF, fType, dirEnts, nil\n}\n\nfunc filePush(fType string, srcpath string, dstpath string, uid int64, gid int64, mode int, write string) error {\n\tswitch fType {\n\tcase \"file\":\n\t\tif !shared.PathExists(dstpath) {\n\t\t\tif uid == -1 {\n\t\t\t\tuid = 0\n\t\t\t}\n\n\t\t\tif gid == -1 {\n\t\t\t\tgid = 0\n\t\t\t}\n\n\t\t\tif mode == -1 {\n\t\t\t\tmode = 0\n\t\t\t}\n\t\t}\n\n\t\tflags := os.O_CREATE | os.O_WRONLY\n\n\t\tif write == \"overwrite\" {\n\t\t\tflags |= os.O_TRUNC\n\t\t} else if write == \"append\" {\n\t\t\tflags |= os.O_APPEND\n\t\t}\n\n\t\tdst, err := os.OpenFile(dstpath, flags, os.FileMode(mode))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer dst.Close()\n\n\t\tsrc, err := os.Open(srcpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer src.Close()\n\n\t\t_, err = io.Copy(dst, src)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = os.Chown(dst.Name(), int(uid), int(gid))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\tcase \"symlink\":\n\t\tif uid == -1 {\n\t\t\tuid = 0\n\t\t}\n\n\t\tif gid == -1 {\n\t\t\tgid = 0\n\t\t}\n\n\t\terr := os.Symlink(srcpath, dstpath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = os.Lchown(dstpath, int(uid), int(gid))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\tcase \"directory\":\n\t\tif uid == -1 {\n\t\t\tuid = 0\n\t\t}\n\n\t\tif gid == -1 {\n\t\t\tgid = 0\n\t\t}\n\n\t\tif mode == -1 {\n\t\t\tmode = 0\n\t\t}\n\n\t\terr := os.MkdirAll(dstpath, os.FileMode(mode))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = os.Chown(dstpath, int(uid), int(gid))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"Bad file type: %s\", fType)\n}\n<|endoftext|>"}
{"text":"<commit_before>package volman_test\n\nimport (\n\t\"encoding\/json\"\n\t\"os\"\n\t\"testing\"\n\n\t\"fmt\"\n\t\"path\"\n\t\"path\/filepath\"\n\n\t\"code.cloudfoundry.org\/inigo\/gardenrunner\"\n\t\"code.cloudfoundry.org\/inigo\/helpers\"\n\t\"code.cloudfoundry.org\/inigo\/world\"\n\t\"code.cloudfoundry.org\/lager\"\n\t\"code.cloudfoundry.org\/lager\/ginkgoreporter\"\n\t\"code.cloudfoundry.org\/lager\/lagertest\"\n\t\"code.cloudfoundry.org\/localip\"\n\t\"code.cloudfoundry.org\/voldriver\"\n\t\"code.cloudfoundry.org\/volman\"\n\t\"github.com\/cloudfoundry-incubator\/garden\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t\"github.com\/onsi\/ginkgo\/config\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\t\"github.com\/tedsuo\/ifrit\"\n\t\"github.com\/tedsuo\/ifrit\/ginkgomon\"\n)\n\nvar (\n\tcomponentMaker world.ComponentMaker\n\n\tgardenProcess ifrit.Process\n\tgardenClient  garden.Client\n\n\tvolmanClient        volman.Manager\n\tdriverSyncer        ifrit.Runner\n\tdriverSyncerProcess ifrit.Process\n\tlocalDriverProcess  ifrit.Process\n\n\tlogger lager.Logger\n\n\tdriverPluginsPath string\n)\n\nvar _ = SynchronizedBeforeSuite(func() []byte {\n\tpayload, err := json.Marshal(world.BuiltArtifacts{\n\t\tExecutables: CompileTestedExecutables(),\n\t})\n\tExpect(err).NotTo(HaveOccurred())\n\n\treturn payload\n}, func(encodedBuiltArtifacts []byte) {\n\tvar builtArtifacts world.BuiltArtifacts\n\n\terr := json.Unmarshal(encodedBuiltArtifacts, &builtArtifacts)\n\tExpect(err).NotTo(HaveOccurred())\n\n\tlocalIP, err := localip.LocalIP()\n\tExpect(err).NotTo(HaveOccurred())\n\n\tcomponentMaker = helpers.MakeComponentMaker(builtArtifacts, localIP)\n})\n\nvar _ = BeforeEach(func() {\n\tlogger = lagertest.NewTestLogger(\"volman-inigo-suite\")\n\n\tgardenProcess = ginkgomon.Invoke(componentMaker.Garden())\n\tgardenClient = componentMaker.GardenClient()\n\n\tlocalDriverProcess = ginkgomon.Invoke(componentMaker.VolmanDriver(logger))\n\n\t\/\/ make a dummy spec file not corresponding to a running driver just to make sure volman ignores it\n\tdriverPluginsPath = path.Join(componentMaker.VolmanDriverConfigDir, fmt.Sprintf(\"node-%d\", config.GinkgoConfig.ParallelNode))\n\tvoldriver.WriteDriverSpec(logger, driverPluginsPath, \"deaddriver\", \"json\", []byte(`{\"Name\":\"deaddriver\",\"Addr\":\"https:\/\/127.0.0.1:1111\"}`))\n\n\tvolmanClient, driverSyncer = componentMaker.VolmanClient(logger)\n\tdriverSyncerProcess = ginkgomon.Invoke(driverSyncer)\n\n})\n\nvar _ = AfterEach(func() {\n\tdestroyContainerErrors := helpers.CleanupGarden(gardenClient)\n\n\thelpers.StopProcesses(gardenProcess, driverSyncerProcess, localDriverProcess)\n\n\tExpect(destroyContainerErrors).To(\n\t\tBeEmpty(),\n\t\t\"%d containers failed to be destroyed!\",\n\t\tlen(destroyContainerErrors),\n\t)\n\n\tos.Remove(filepath.Join(driverPluginsPath, \"deaddriver.json\"))\n})\n\nfunc TestVolman(t *testing.T) {\n\thelpers.RegisterDefaultTimeouts()\n\n\tRegisterFailHandler(Fail)\n\n\tRunSpecsWithDefaultAndCustomReporters(t, \"Volman Integration Suite\", []Reporter{\n\t\tginkgoreporter.New(GinkgoWriter),\n\t})\n}\n\nfunc CompileTestedExecutables() world.BuiltExecutables {\n\tvar err error\n\n\tbuiltExecutables := world.BuiltExecutables{}\n\n\tbuiltExecutables[\"garden\"], err = gexec.BuildIn(os.Getenv(\"GARDEN_GOPATH\"), gardenrunner.GardenServerPackageName(), \"-race\", \"-a\", \"-tags\", \"daemon\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"local-driver\"], err = gexec.Build(\"github.com\/cloudfoundry-incubator\/localdriver\/cmd\/localdriver\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"auctioneer\"], err = gexec.BuildIn(os.Getenv(\"AUCTIONEER_GOPATH\"), \"code.cloudfoundry.org\/auctioneer\/cmd\/auctioneer\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"rep\"], err = gexec.BuildIn(os.Getenv(\"REP_GOPATH\"), \"code.cloudfoundry.org\/rep\/cmd\/rep\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"bbs\"], err = gexec.BuildIn(os.Getenv(\"BBS_GOPATH\"), \"code.cloudfoundry.org\/bbs\/cmd\/bbs\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"file-server\"], err = gexec.BuildIn(os.Getenv(\"FILE_SERVER_GOPATH\"), \"code.cloudfoundry.org\/fileserver\/cmd\/file-server\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"route-emitter\"], err = gexec.BuildIn(os.Getenv(\"ROUTE_EMITTER_GOPATH\"), \"code.cloudfoundry.org\/route-emitter\/cmd\/route-emitter\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"router\"], err = gexec.BuildIn(os.Getenv(\"ROUTER_GOPATH\"), \"github.com\/cloudfoundry\/gorouter\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"ssh-proxy\"], err = gexec.Build(\"code.cloudfoundry.org\/diego-ssh\/cmd\/ssh-proxy\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\treturn builtExecutables\n}\n<commit_msg>localdriver -> code.cloudfoundry.org [#127201811](https:\/\/www.pivotaltracker.com\/story\/show\/127201811)<commit_after>package volman_test\n\nimport (\n\t\"encoding\/json\"\n\t\"os\"\n\t\"testing\"\n\n\t\"fmt\"\n\t\"path\"\n\t\"path\/filepath\"\n\n\t\"code.cloudfoundry.org\/inigo\/gardenrunner\"\n\t\"code.cloudfoundry.org\/inigo\/helpers\"\n\t\"code.cloudfoundry.org\/inigo\/world\"\n\t\"code.cloudfoundry.org\/lager\"\n\t\"code.cloudfoundry.org\/lager\/ginkgoreporter\"\n\t\"code.cloudfoundry.org\/lager\/lagertest\"\n\t\"code.cloudfoundry.org\/localip\"\n\t\"code.cloudfoundry.org\/voldriver\"\n\t\"code.cloudfoundry.org\/volman\"\n\t\"github.com\/cloudfoundry-incubator\/garden\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t\"github.com\/onsi\/ginkgo\/config\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\t\"github.com\/tedsuo\/ifrit\"\n\t\"github.com\/tedsuo\/ifrit\/ginkgomon\"\n)\n\nvar (\n\tcomponentMaker world.ComponentMaker\n\n\tgardenProcess ifrit.Process\n\tgardenClient  garden.Client\n\n\tvolmanClient        volman.Manager\n\tdriverSyncer        ifrit.Runner\n\tdriverSyncerProcess ifrit.Process\n\tlocalDriverProcess  ifrit.Process\n\n\tlogger lager.Logger\n\n\tdriverPluginsPath string\n)\n\nvar _ = SynchronizedBeforeSuite(func() []byte {\n\tpayload, err := json.Marshal(world.BuiltArtifacts{\n\t\tExecutables: CompileTestedExecutables(),\n\t})\n\tExpect(err).NotTo(HaveOccurred())\n\n\treturn payload\n}, func(encodedBuiltArtifacts []byte) {\n\tvar builtArtifacts world.BuiltArtifacts\n\n\terr := json.Unmarshal(encodedBuiltArtifacts, &builtArtifacts)\n\tExpect(err).NotTo(HaveOccurred())\n\n\tlocalIP, err := localip.LocalIP()\n\tExpect(err).NotTo(HaveOccurred())\n\n\tcomponentMaker = helpers.MakeComponentMaker(builtArtifacts, localIP)\n})\n\nvar _ = BeforeEach(func() {\n\tlogger = lagertest.NewTestLogger(\"volman-inigo-suite\")\n\n\tgardenProcess = ginkgomon.Invoke(componentMaker.Garden())\n\tgardenClient = componentMaker.GardenClient()\n\n\tlocalDriverProcess = ginkgomon.Invoke(componentMaker.VolmanDriver(logger))\n\n\t\/\/ make a dummy spec file not corresponding to a running driver just to make sure volman ignores it\n\tdriverPluginsPath = path.Join(componentMaker.VolmanDriverConfigDir, fmt.Sprintf(\"node-%d\", config.GinkgoConfig.ParallelNode))\n\tvoldriver.WriteDriverSpec(logger, driverPluginsPath, \"deaddriver\", \"json\", []byte(`{\"Name\":\"deaddriver\",\"Addr\":\"https:\/\/127.0.0.1:1111\"}`))\n\n\tvolmanClient, driverSyncer = componentMaker.VolmanClient(logger)\n\tdriverSyncerProcess = ginkgomon.Invoke(driverSyncer)\n\n})\n\nvar _ = AfterEach(func() {\n\tdestroyContainerErrors := helpers.CleanupGarden(gardenClient)\n\n\thelpers.StopProcesses(gardenProcess, driverSyncerProcess, localDriverProcess)\n\n\tExpect(destroyContainerErrors).To(\n\t\tBeEmpty(),\n\t\t\"%d containers failed to be destroyed!\",\n\t\tlen(destroyContainerErrors),\n\t)\n\n\tos.Remove(filepath.Join(driverPluginsPath, \"deaddriver.json\"))\n})\n\nfunc TestVolman(t *testing.T) {\n\thelpers.RegisterDefaultTimeouts()\n\n\tRegisterFailHandler(Fail)\n\n\tRunSpecsWithDefaultAndCustomReporters(t, \"Volman Integration Suite\", []Reporter{\n\t\tginkgoreporter.New(GinkgoWriter),\n\t})\n}\n\nfunc CompileTestedExecutables() world.BuiltExecutables {\n\tvar err error\n\n\tbuiltExecutables := world.BuiltExecutables{}\n\n\tbuiltExecutables[\"garden\"], err = gexec.BuildIn(os.Getenv(\"GARDEN_GOPATH\"), gardenrunner.GardenServerPackageName(), \"-race\", \"-a\", \"-tags\", \"daemon\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"local-driver\"], err = gexec.Build(\"code.cloudfoundry.org\/localdriver\/cmd\/localdriver\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"auctioneer\"], err = gexec.BuildIn(os.Getenv(\"AUCTIONEER_GOPATH\"), \"code.cloudfoundry.org\/auctioneer\/cmd\/auctioneer\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"rep\"], err = gexec.BuildIn(os.Getenv(\"REP_GOPATH\"), \"code.cloudfoundry.org\/rep\/cmd\/rep\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"bbs\"], err = gexec.BuildIn(os.Getenv(\"BBS_GOPATH\"), \"code.cloudfoundry.org\/bbs\/cmd\/bbs\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"file-server\"], err = gexec.BuildIn(os.Getenv(\"FILE_SERVER_GOPATH\"), \"code.cloudfoundry.org\/fileserver\/cmd\/file-server\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"route-emitter\"], err = gexec.BuildIn(os.Getenv(\"ROUTE_EMITTER_GOPATH\"), \"code.cloudfoundry.org\/route-emitter\/cmd\/route-emitter\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"router\"], err = gexec.BuildIn(os.Getenv(\"ROUTER_GOPATH\"), \"github.com\/cloudfoundry\/gorouter\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\tbuiltExecutables[\"ssh-proxy\"], err = gexec.Build(\"code.cloudfoundry.org\/diego-ssh\/cmd\/ssh-proxy\", \"-race\")\n\tExpect(err).NotTo(HaveOccurred())\n\n\treturn builtExecutables\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 The Gitea Authors. All rights reserved.\n\/\/ Copyright 2018 Jonas Franz. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage migrations\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"code.gitea.io\/gitea\/modules\/log\"\n\t\"code.gitea.io\/gitea\/modules\/migrations\/base\"\n\n\t\"github.com\/google\/go-github\/v24\/github\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nvar (\n\t_ base.Downloader        = &GithubDownloaderV3{}\n\t_ base.DownloaderFactory = &GithubDownloaderV3Factory{}\n)\n\nfunc init() {\n\tRegisterDownloaderFactory(&GithubDownloaderV3Factory{})\n}\n\n\/\/ GithubDownloaderV3Factory defines a github downloader v3 factory\ntype GithubDownloaderV3Factory struct {\n}\n\n\/\/ Match returns ture if the migration remote URL matched this downloader factory\nfunc (f *GithubDownloaderV3Factory) Match(opts base.MigrateOptions) (bool, error) {\n\tu, err := url.Parse(opts.RemoteURL)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn u.Host == \"github.com\" && opts.AuthUsername != \"\", nil\n}\n\n\/\/ New returns a Downloader related to this factory according MigrateOptions\nfunc (f *GithubDownloaderV3Factory) New(opts base.MigrateOptions) (base.Downloader, error) {\n\tu, err := url.Parse(opts.RemoteURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfields := strings.Split(u.Path, \"\/\")\n\toldOwner := fields[1]\n\toldName := strings.TrimSuffix(fields[2], \".git\")\n\n\tlog.Trace(\"Create github downloader: %s\/%s\", oldOwner, oldName)\n\n\treturn NewGithubDownloaderV3(opts.AuthUsername, opts.AuthPassword, oldOwner, oldName), nil\n}\n\n\/\/ GithubDownloaderV3 implements a Downloader interface to get repository informations\n\/\/ from github via APIv3\ntype GithubDownloaderV3 struct {\n\tctx       context.Context\n\tclient    *github.Client\n\trepoOwner string\n\trepoName  string\n\tuserName  string\n\tpassword  string\n}\n\n\/\/ NewGithubDownloaderV3 creates a github Downloader via github v3 API\nfunc NewGithubDownloaderV3(userName, password, repoOwner, repoName string) *GithubDownloaderV3 {\n\tvar downloader = GithubDownloaderV3{\n\t\tuserName:  userName,\n\t\tpassword:  password,\n\t\tctx:       context.Background(),\n\t\trepoOwner: repoOwner,\n\t\trepoName:  repoName,\n\t}\n\n\tvar client *http.Client\n\tif userName != \"\" {\n\t\tif password == \"\" {\n\t\t\tts := oauth2.StaticTokenSource(\n\t\t\t\t&oauth2.Token{AccessToken: userName},\n\t\t\t)\n\t\t\tclient = oauth2.NewClient(downloader.ctx, ts)\n\t\t} else {\n\t\t\tclient = &http.Client{\n\t\t\t\tTransport: &http.Transport{\n\t\t\t\t\tProxy: func(req *http.Request) (*url.URL, error) {\n\t\t\t\t\t\treq.SetBasicAuth(userName, password)\n\t\t\t\t\t\treturn nil, nil\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\tdownloader.client = github.NewClient(client)\n\treturn &downloader\n}\n\n\/\/ GetRepoInfo returns a repository information\nfunc (g *GithubDownloaderV3) GetRepoInfo() (*base.Repository, error) {\n\tgr, _, err := g.client.Repositories.Get(g.ctx, g.repoOwner, g.repoName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ convert github repo to stand Repo\n\treturn &base.Repository{\n\t\tOwner:       g.repoOwner,\n\t\tName:        gr.GetName(),\n\t\tIsPrivate:   *gr.Private,\n\t\tDescription: gr.GetDescription(),\n\t\tCloneURL:    gr.GetCloneURL(),\n\t}, nil\n}\n\n\/\/ GetMilestones returns milestones\nfunc (g *GithubDownloaderV3) GetMilestones() ([]*base.Milestone, error) {\n\tvar perPage = 100\n\tvar milestones = make([]*base.Milestone, 0, perPage)\n\tfor i := 1; ; i++ {\n\t\tms, _, err := g.client.Issues.ListMilestones(g.ctx, g.repoOwner, g.repoName,\n\t\t\t&github.MilestoneListOptions{\n\t\t\t\tState: \"all\",\n\t\t\t\tListOptions: github.ListOptions{\n\t\t\t\t\tPage:    i,\n\t\t\t\t\tPerPage: perPage,\n\t\t\t\t}})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, m := range ms {\n\t\t\tvar desc string\n\t\t\tif m.Description != nil {\n\t\t\t\tdesc = *m.Description\n\t\t\t}\n\t\t\tvar state = \"open\"\n\t\t\tif m.State != nil {\n\t\t\t\tstate = *m.State\n\t\t\t}\n\t\t\tmilestones = append(milestones, &base.Milestone{\n\t\t\t\tTitle:       *m.Title,\n\t\t\t\tDescription: desc,\n\t\t\t\tDeadline:    m.DueOn,\n\t\t\t\tState:       state,\n\t\t\t\tCreated:     *m.CreatedAt,\n\t\t\t\tUpdated:     m.UpdatedAt,\n\t\t\t\tClosed:      m.ClosedAt,\n\t\t\t})\n\t\t}\n\t\tif len(ms) < perPage {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn milestones, nil\n}\n\nfunc convertGithubLabel(label *github.Label) *base.Label {\n\tvar desc string\n\tif label.Description != nil {\n\t\tdesc = *label.Description\n\t}\n\treturn &base.Label{\n\t\tName:        *label.Name,\n\t\tColor:       *label.Color,\n\t\tDescription: desc,\n\t}\n}\n\n\/\/ GetLabels returns labels\nfunc (g *GithubDownloaderV3) GetLabels() ([]*base.Label, error) {\n\tvar perPage = 100\n\tvar labels = make([]*base.Label, 0, perPage)\n\tfor i := 1; ; i++ {\n\t\tls, _, err := g.client.Issues.ListLabels(g.ctx, g.repoOwner, g.repoName,\n\t\t\t&github.ListOptions{\n\t\t\t\tPage:    i,\n\t\t\t\tPerPage: perPage,\n\t\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, label := range ls {\n\t\t\tlabels = append(labels, convertGithubLabel(label))\n\t\t}\n\t\tif len(ls) < perPage {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn labels, nil\n}\n\nfunc (g *GithubDownloaderV3) convertGithubRelease(rel *github.RepositoryRelease) *base.Release {\n\tvar (\n\t\tname string\n\t\tdesc string\n\t)\n\tif rel.Body != nil {\n\t\tdesc = *rel.Body\n\t}\n\tif rel.Name != nil {\n\t\tname = *rel.Name\n\t}\n\n\tr := &base.Release{\n\t\tTagName:         *rel.TagName,\n\t\tTargetCommitish: *rel.TargetCommitish,\n\t\tName:            name,\n\t\tBody:            desc,\n\t\tDraft:           *rel.Draft,\n\t\tPrerelease:      *rel.Prerelease,\n\t\tCreated:         rel.CreatedAt.Time,\n\t\tPublished:       rel.PublishedAt.Time,\n\t}\n\n\tfor _, asset := range rel.Assets {\n\t\tu, _ := url.Parse(*asset.BrowserDownloadURL)\n\t\tu.User = url.UserPassword(g.userName, g.password)\n\t\tr.Assets = append(r.Assets, base.ReleaseAsset{\n\t\t\tURL:           u.String(),\n\t\t\tName:          *asset.Name,\n\t\t\tContentType:   asset.ContentType,\n\t\t\tSize:          asset.Size,\n\t\t\tDownloadCount: asset.DownloadCount,\n\t\t\tCreated:       asset.CreatedAt.Time,\n\t\t\tUpdated:       asset.UpdatedAt.Time,\n\t\t})\n\t}\n\treturn r\n}\n\n\/\/ GetReleases returns releases\nfunc (g *GithubDownloaderV3) GetReleases() ([]*base.Release, error) {\n\tvar perPage = 100\n\tvar releases = make([]*base.Release, 0, perPage)\n\tfor i := 1; ; i++ {\n\t\tls, _, err := g.client.Repositories.ListReleases(g.ctx, g.repoOwner, g.repoName,\n\t\t\t&github.ListOptions{\n\t\t\t\tPage:    i,\n\t\t\t\tPerPage: perPage,\n\t\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, release := range ls {\n\t\t\treleases = append(releases, g.convertGithubRelease(release))\n\t\t}\n\t\tif len(ls) < perPage {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn releases, nil\n}\n\nfunc convertGithubReactions(reactions *github.Reactions) *base.Reactions {\n\treturn &base.Reactions{\n\t\tTotalCount: *reactions.TotalCount,\n\t\tPlusOne:    *reactions.PlusOne,\n\t\tMinusOne:   *reactions.MinusOne,\n\t\tLaugh:      *reactions.Laugh,\n\t\tConfused:   *reactions.Confused,\n\t\tHeart:      *reactions.Heart,\n\t\tHooray:     *reactions.Hooray,\n\t}\n}\n\n\/\/ GetIssues returns issues according start and limit\nfunc (g *GithubDownloaderV3) GetIssues(page, perPage int) ([]*base.Issue, bool, error) {\n\topt := &github.IssueListByRepoOptions{\n\t\tSort:      \"created\",\n\t\tDirection: \"asc\",\n\t\tState:     \"all\",\n\t\tListOptions: github.ListOptions{\n\t\t\tPerPage: perPage,\n\t\t\tPage:    page,\n\t\t},\n\t}\n\n\tvar allIssues = make([]*base.Issue, 0, perPage)\n\n\tissues, _, err := g.client.Issues.ListByRepo(g.ctx, g.repoOwner, g.repoName, opt)\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"error while listing repos: %v\", err)\n\t}\n\tfor _, issue := range issues {\n\t\tif issue.IsPullRequest() {\n\t\t\tcontinue\n\t\t}\n\t\tvar body string\n\t\tif issue.Body != nil {\n\t\t\tbody = *issue.Body\n\t\t}\n\t\tvar milestone string\n\t\tif issue.Milestone != nil {\n\t\t\tmilestone = *issue.Milestone.Title\n\t\t}\n\t\tvar labels = make([]*base.Label, 0, len(issue.Labels))\n\t\tfor _, l := range issue.Labels {\n\t\t\tlabels = append(labels, convertGithubLabel(&l))\n\t\t}\n\t\tvar reactions *base.Reactions\n\t\tif issue.Reactions != nil {\n\t\t\treactions = convertGithubReactions(issue.Reactions)\n\t\t}\n\n\t\tvar email string\n\t\tif issue.User.Email != nil {\n\t\t\temail = *issue.User.Email\n\t\t}\n\t\tallIssues = append(allIssues, &base.Issue{\n\t\t\tTitle:       *issue.Title,\n\t\t\tNumber:      int64(*issue.Number),\n\t\t\tPosterName:  *issue.User.Login,\n\t\t\tPosterEmail: email,\n\t\t\tContent:     body,\n\t\t\tMilestone:   milestone,\n\t\t\tState:       *issue.State,\n\t\t\tCreated:     *issue.CreatedAt,\n\t\t\tLabels:      labels,\n\t\t\tReactions:   reactions,\n\t\t\tClosed:      issue.ClosedAt,\n\t\t\tIsLocked:    *issue.Locked,\n\t\t})\n\t}\n\n\treturn allIssues, len(issues) < perPage, nil\n}\n\n\/\/ GetComments returns comments according issueNumber\nfunc (g *GithubDownloaderV3) GetComments(issueNumber int64) ([]*base.Comment, error) {\n\tvar allComments = make([]*base.Comment, 0, 100)\n\topt := &github.IssueListCommentsOptions{\n\t\tSort:      \"created\",\n\t\tDirection: \"asc\",\n\t\tListOptions: github.ListOptions{\n\t\t\tPerPage: 100,\n\t\t},\n\t}\n\tfor {\n\t\tcomments, resp, err := g.client.Issues.ListComments(g.ctx, g.repoOwner, g.repoName, int(issueNumber), opt)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error while listing repos: %v\", err)\n\t\t}\n\t\tfor _, comment := range comments {\n\t\t\tvar email string\n\t\t\tif comment.User.Email != nil {\n\t\t\t\temail = *comment.User.Email\n\t\t\t}\n\t\t\tvar reactions *base.Reactions\n\t\t\tif comment.Reactions != nil {\n\t\t\t\treactions = convertGithubReactions(comment.Reactions)\n\t\t\t}\n\t\t\tallComments = append(allComments, &base.Comment{\n\t\t\t\tPosterName:  *comment.User.Login,\n\t\t\t\tPosterEmail: email,\n\t\t\t\tContent:     *comment.Body,\n\t\t\t\tCreated:     *comment.CreatedAt,\n\t\t\t\tReactions:   reactions,\n\t\t\t})\n\t\t}\n\t\tif resp.NextPage == 0 {\n\t\t\tbreak\n\t\t}\n\t\topt.Page = resp.NextPage\n\t}\n\treturn allComments, nil\n}\n\n\/\/ GetPullRequests returns pull requests according page and perPage\nfunc (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullRequest, error) {\n\topt := &github.PullRequestListOptions{\n\t\tSort:      \"created\",\n\t\tDirection: \"asc\",\n\t\tState:     \"all\",\n\t\tListOptions: github.ListOptions{\n\t\t\tPerPage: perPage,\n\t\t\tPage:    page,\n\t\t},\n\t}\n\tvar allPRs = make([]*base.PullRequest, 0, perPage)\n\n\tprs, _, err := g.client.PullRequests.List(g.ctx, g.repoOwner, g.repoName, opt)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while listing repos: %v\", err)\n\t}\n\tfor _, pr := range prs {\n\t\tvar body string\n\t\tif pr.Body != nil {\n\t\t\tbody = *pr.Body\n\t\t}\n\t\tvar milestone string\n\t\tif pr.Milestone != nil {\n\t\t\tmilestone = *pr.Milestone.Title\n\t\t}\n\t\tvar labels = make([]*base.Label, 0, len(pr.Labels))\n\t\tfor _, l := range pr.Labels {\n\t\t\tlabels = append(labels, convertGithubLabel(l))\n\t\t}\n\n\t\t\/\/ FIXME: This API missing reactions, we may need another extra request to get reactions\n\n\t\tvar email string\n\t\tif pr.User.Email != nil {\n\t\t\temail = *pr.User.Email\n\t\t}\n\t\tvar merged bool\n\t\t\/\/ pr.Merged is not valid, so use MergedAt to test if it's merged\n\t\tif pr.MergedAt != nil {\n\t\t\tmerged = true\n\t\t}\n\n\t\tvar headRepoName string\n\t\tvar cloneURL string\n\t\tif pr.Head.Repo != nil {\n\t\t\theadRepoName = *pr.Head.Repo.Name\n\t\t\tcloneURL = *pr.Head.Repo.CloneURL\n\t\t}\n\t\tvar mergeCommitSHA string\n\t\tif pr.MergeCommitSHA != nil {\n\t\t\tmergeCommitSHA = *pr.MergeCommitSHA\n\t\t}\n\n\t\tallPRs = append(allPRs, &base.PullRequest{\n\t\t\tTitle:          *pr.Title,\n\t\t\tNumber:         int64(*pr.Number),\n\t\t\tPosterName:     *pr.User.Login,\n\t\t\tPosterEmail:    email,\n\t\t\tContent:        body,\n\t\t\tMilestone:      milestone,\n\t\t\tState:          *pr.State,\n\t\t\tCreated:        *pr.CreatedAt,\n\t\t\tClosed:         pr.ClosedAt,\n\t\t\tLabels:         labels,\n\t\t\tMerged:         merged,\n\t\t\tMergeCommitSHA: mergeCommitSHA,\n\t\t\tMergedTime:     pr.MergedAt,\n\t\t\tIsLocked:       pr.ActiveLockReason != nil,\n\t\t\tHead: base.PullRequestBranch{\n\t\t\t\tRef:       *pr.Head.Ref,\n\t\t\t\tSHA:       *pr.Head.SHA,\n\t\t\t\tRepoName:  headRepoName,\n\t\t\t\tOwnerName: *pr.Head.User.Login,\n\t\t\t\tCloneURL:  cloneURL,\n\t\t\t},\n\t\t\tBase: base.PullRequestBranch{\n\t\t\t\tRef:       *pr.Base.Ref,\n\t\t\t\tSHA:       *pr.Base.SHA,\n\t\t\t\tRepoName:  *pr.Base.Repo.Name,\n\t\t\t\tOwnerName: *pr.Base.User.Login,\n\t\t\t},\n\t\t\tPatchURL: *pr.PatchURL,\n\t\t})\n\t}\n\n\treturn allPRs, nil\n}\n<commit_msg>Fix migration panic when Head.User is not exist (#7226)<commit_after>\/\/ Copyright 2019 The Gitea Authors. All rights reserved.\n\/\/ Copyright 2018 Jonas Franz. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage migrations\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"code.gitea.io\/gitea\/modules\/log\"\n\t\"code.gitea.io\/gitea\/modules\/migrations\/base\"\n\n\t\"github.com\/google\/go-github\/v24\/github\"\n\t\"golang.org\/x\/oauth2\"\n)\n\nvar (\n\t_ base.Downloader        = &GithubDownloaderV3{}\n\t_ base.DownloaderFactory = &GithubDownloaderV3Factory{}\n)\n\nfunc init() {\n\tRegisterDownloaderFactory(&GithubDownloaderV3Factory{})\n}\n\n\/\/ GithubDownloaderV3Factory defines a github downloader v3 factory\ntype GithubDownloaderV3Factory struct {\n}\n\n\/\/ Match returns ture if the migration remote URL matched this downloader factory\nfunc (f *GithubDownloaderV3Factory) Match(opts base.MigrateOptions) (bool, error) {\n\tu, err := url.Parse(opts.RemoteURL)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn u.Host == \"github.com\" && opts.AuthUsername != \"\", nil\n}\n\n\/\/ New returns a Downloader related to this factory according MigrateOptions\nfunc (f *GithubDownloaderV3Factory) New(opts base.MigrateOptions) (base.Downloader, error) {\n\tu, err := url.Parse(opts.RemoteURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfields := strings.Split(u.Path, \"\/\")\n\toldOwner := fields[1]\n\toldName := strings.TrimSuffix(fields[2], \".git\")\n\n\tlog.Trace(\"Create github downloader: %s\/%s\", oldOwner, oldName)\n\n\treturn NewGithubDownloaderV3(opts.AuthUsername, opts.AuthPassword, oldOwner, oldName), nil\n}\n\n\/\/ GithubDownloaderV3 implements a Downloader interface to get repository informations\n\/\/ from github via APIv3\ntype GithubDownloaderV3 struct {\n\tctx       context.Context\n\tclient    *github.Client\n\trepoOwner string\n\trepoName  string\n\tuserName  string\n\tpassword  string\n}\n\n\/\/ NewGithubDownloaderV3 creates a github Downloader via github v3 API\nfunc NewGithubDownloaderV3(userName, password, repoOwner, repoName string) *GithubDownloaderV3 {\n\tvar downloader = GithubDownloaderV3{\n\t\tuserName:  userName,\n\t\tpassword:  password,\n\t\tctx:       context.Background(),\n\t\trepoOwner: repoOwner,\n\t\trepoName:  repoName,\n\t}\n\n\tvar client *http.Client\n\tif userName != \"\" {\n\t\tif password == \"\" {\n\t\t\tts := oauth2.StaticTokenSource(\n\t\t\t\t&oauth2.Token{AccessToken: userName},\n\t\t\t)\n\t\t\tclient = oauth2.NewClient(downloader.ctx, ts)\n\t\t} else {\n\t\t\tclient = &http.Client{\n\t\t\t\tTransport: &http.Transport{\n\t\t\t\t\tProxy: func(req *http.Request) (*url.URL, error) {\n\t\t\t\t\t\treq.SetBasicAuth(userName, password)\n\t\t\t\t\t\treturn nil, nil\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\tdownloader.client = github.NewClient(client)\n\treturn &downloader\n}\n\n\/\/ GetRepoInfo returns a repository information\nfunc (g *GithubDownloaderV3) GetRepoInfo() (*base.Repository, error) {\n\tgr, _, err := g.client.Repositories.Get(g.ctx, g.repoOwner, g.repoName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ convert github repo to stand Repo\n\treturn &base.Repository{\n\t\tOwner:       g.repoOwner,\n\t\tName:        gr.GetName(),\n\t\tIsPrivate:   *gr.Private,\n\t\tDescription: gr.GetDescription(),\n\t\tCloneURL:    gr.GetCloneURL(),\n\t}, nil\n}\n\n\/\/ GetMilestones returns milestones\nfunc (g *GithubDownloaderV3) GetMilestones() ([]*base.Milestone, error) {\n\tvar perPage = 100\n\tvar milestones = make([]*base.Milestone, 0, perPage)\n\tfor i := 1; ; i++ {\n\t\tms, _, err := g.client.Issues.ListMilestones(g.ctx, g.repoOwner, g.repoName,\n\t\t\t&github.MilestoneListOptions{\n\t\t\t\tState: \"all\",\n\t\t\t\tListOptions: github.ListOptions{\n\t\t\t\t\tPage:    i,\n\t\t\t\t\tPerPage: perPage,\n\t\t\t\t}})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, m := range ms {\n\t\t\tvar desc string\n\t\t\tif m.Description != nil {\n\t\t\t\tdesc = *m.Description\n\t\t\t}\n\t\t\tvar state = \"open\"\n\t\t\tif m.State != nil {\n\t\t\t\tstate = *m.State\n\t\t\t}\n\t\t\tmilestones = append(milestones, &base.Milestone{\n\t\t\t\tTitle:       *m.Title,\n\t\t\t\tDescription: desc,\n\t\t\t\tDeadline:    m.DueOn,\n\t\t\t\tState:       state,\n\t\t\t\tCreated:     *m.CreatedAt,\n\t\t\t\tUpdated:     m.UpdatedAt,\n\t\t\t\tClosed:      m.ClosedAt,\n\t\t\t})\n\t\t}\n\t\tif len(ms) < perPage {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn milestones, nil\n}\n\nfunc convertGithubLabel(label *github.Label) *base.Label {\n\tvar desc string\n\tif label.Description != nil {\n\t\tdesc = *label.Description\n\t}\n\treturn &base.Label{\n\t\tName:        *label.Name,\n\t\tColor:       *label.Color,\n\t\tDescription: desc,\n\t}\n}\n\n\/\/ GetLabels returns labels\nfunc (g *GithubDownloaderV3) GetLabels() ([]*base.Label, error) {\n\tvar perPage = 100\n\tvar labels = make([]*base.Label, 0, perPage)\n\tfor i := 1; ; i++ {\n\t\tls, _, err := g.client.Issues.ListLabels(g.ctx, g.repoOwner, g.repoName,\n\t\t\t&github.ListOptions{\n\t\t\t\tPage:    i,\n\t\t\t\tPerPage: perPage,\n\t\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, label := range ls {\n\t\t\tlabels = append(labels, convertGithubLabel(label))\n\t\t}\n\t\tif len(ls) < perPage {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn labels, nil\n}\n\nfunc (g *GithubDownloaderV3) convertGithubRelease(rel *github.RepositoryRelease) *base.Release {\n\tvar (\n\t\tname string\n\t\tdesc string\n\t)\n\tif rel.Body != nil {\n\t\tdesc = *rel.Body\n\t}\n\tif rel.Name != nil {\n\t\tname = *rel.Name\n\t}\n\n\tr := &base.Release{\n\t\tTagName:         *rel.TagName,\n\t\tTargetCommitish: *rel.TargetCommitish,\n\t\tName:            name,\n\t\tBody:            desc,\n\t\tDraft:           *rel.Draft,\n\t\tPrerelease:      *rel.Prerelease,\n\t\tCreated:         rel.CreatedAt.Time,\n\t\tPublished:       rel.PublishedAt.Time,\n\t}\n\n\tfor _, asset := range rel.Assets {\n\t\tu, _ := url.Parse(*asset.BrowserDownloadURL)\n\t\tu.User = url.UserPassword(g.userName, g.password)\n\t\tr.Assets = append(r.Assets, base.ReleaseAsset{\n\t\t\tURL:           u.String(),\n\t\t\tName:          *asset.Name,\n\t\t\tContentType:   asset.ContentType,\n\t\t\tSize:          asset.Size,\n\t\t\tDownloadCount: asset.DownloadCount,\n\t\t\tCreated:       asset.CreatedAt.Time,\n\t\t\tUpdated:       asset.UpdatedAt.Time,\n\t\t})\n\t}\n\treturn r\n}\n\n\/\/ GetReleases returns releases\nfunc (g *GithubDownloaderV3) GetReleases() ([]*base.Release, error) {\n\tvar perPage = 100\n\tvar releases = make([]*base.Release, 0, perPage)\n\tfor i := 1; ; i++ {\n\t\tls, _, err := g.client.Repositories.ListReleases(g.ctx, g.repoOwner, g.repoName,\n\t\t\t&github.ListOptions{\n\t\t\t\tPage:    i,\n\t\t\t\tPerPage: perPage,\n\t\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor _, release := range ls {\n\t\t\treleases = append(releases, g.convertGithubRelease(release))\n\t\t}\n\t\tif len(ls) < perPage {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn releases, nil\n}\n\nfunc convertGithubReactions(reactions *github.Reactions) *base.Reactions {\n\treturn &base.Reactions{\n\t\tTotalCount: *reactions.TotalCount,\n\t\tPlusOne:    *reactions.PlusOne,\n\t\tMinusOne:   *reactions.MinusOne,\n\t\tLaugh:      *reactions.Laugh,\n\t\tConfused:   *reactions.Confused,\n\t\tHeart:      *reactions.Heart,\n\t\tHooray:     *reactions.Hooray,\n\t}\n}\n\n\/\/ GetIssues returns issues according start and limit\nfunc (g *GithubDownloaderV3) GetIssues(page, perPage int) ([]*base.Issue, bool, error) {\n\topt := &github.IssueListByRepoOptions{\n\t\tSort:      \"created\",\n\t\tDirection: \"asc\",\n\t\tState:     \"all\",\n\t\tListOptions: github.ListOptions{\n\t\t\tPerPage: perPage,\n\t\t\tPage:    page,\n\t\t},\n\t}\n\n\tvar allIssues = make([]*base.Issue, 0, perPage)\n\n\tissues, _, err := g.client.Issues.ListByRepo(g.ctx, g.repoOwner, g.repoName, opt)\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\"error while listing repos: %v\", err)\n\t}\n\tfor _, issue := range issues {\n\t\tif issue.IsPullRequest() {\n\t\t\tcontinue\n\t\t}\n\t\tvar body string\n\t\tif issue.Body != nil {\n\t\t\tbody = *issue.Body\n\t\t}\n\t\tvar milestone string\n\t\tif issue.Milestone != nil {\n\t\t\tmilestone = *issue.Milestone.Title\n\t\t}\n\t\tvar labels = make([]*base.Label, 0, len(issue.Labels))\n\t\tfor _, l := range issue.Labels {\n\t\t\tlabels = append(labels, convertGithubLabel(&l))\n\t\t}\n\t\tvar reactions *base.Reactions\n\t\tif issue.Reactions != nil {\n\t\t\treactions = convertGithubReactions(issue.Reactions)\n\t\t}\n\n\t\tvar email string\n\t\tif issue.User.Email != nil {\n\t\t\temail = *issue.User.Email\n\t\t}\n\t\tallIssues = append(allIssues, &base.Issue{\n\t\t\tTitle:       *issue.Title,\n\t\t\tNumber:      int64(*issue.Number),\n\t\t\tPosterName:  *issue.User.Login,\n\t\t\tPosterEmail: email,\n\t\t\tContent:     body,\n\t\t\tMilestone:   milestone,\n\t\t\tState:       *issue.State,\n\t\t\tCreated:     *issue.CreatedAt,\n\t\t\tLabels:      labels,\n\t\t\tReactions:   reactions,\n\t\t\tClosed:      issue.ClosedAt,\n\t\t\tIsLocked:    *issue.Locked,\n\t\t})\n\t}\n\n\treturn allIssues, len(issues) < perPage, nil\n}\n\n\/\/ GetComments returns comments according issueNumber\nfunc (g *GithubDownloaderV3) GetComments(issueNumber int64) ([]*base.Comment, error) {\n\tvar allComments = make([]*base.Comment, 0, 100)\n\topt := &github.IssueListCommentsOptions{\n\t\tSort:      \"created\",\n\t\tDirection: \"asc\",\n\t\tListOptions: github.ListOptions{\n\t\t\tPerPage: 100,\n\t\t},\n\t}\n\tfor {\n\t\tcomments, resp, err := g.client.Issues.ListComments(g.ctx, g.repoOwner, g.repoName, int(issueNumber), opt)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error while listing repos: %v\", err)\n\t\t}\n\t\tfor _, comment := range comments {\n\t\t\tvar email string\n\t\t\tif comment.User.Email != nil {\n\t\t\t\temail = *comment.User.Email\n\t\t\t}\n\t\t\tvar reactions *base.Reactions\n\t\t\tif comment.Reactions != nil {\n\t\t\t\treactions = convertGithubReactions(comment.Reactions)\n\t\t\t}\n\t\t\tallComments = append(allComments, &base.Comment{\n\t\t\t\tPosterName:  *comment.User.Login,\n\t\t\t\tPosterEmail: email,\n\t\t\t\tContent:     *comment.Body,\n\t\t\t\tCreated:     *comment.CreatedAt,\n\t\t\t\tReactions:   reactions,\n\t\t\t})\n\t\t}\n\t\tif resp.NextPage == 0 {\n\t\t\tbreak\n\t\t}\n\t\topt.Page = resp.NextPage\n\t}\n\treturn allComments, nil\n}\n\n\/\/ GetPullRequests returns pull requests according page and perPage\nfunc (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullRequest, error) {\n\topt := &github.PullRequestListOptions{\n\t\tSort:      \"created\",\n\t\tDirection: \"asc\",\n\t\tState:     \"all\",\n\t\tListOptions: github.ListOptions{\n\t\t\tPerPage: perPage,\n\t\t\tPage:    page,\n\t\t},\n\t}\n\tvar allPRs = make([]*base.PullRequest, 0, perPage)\n\n\tprs, _, err := g.client.PullRequests.List(g.ctx, g.repoOwner, g.repoName, opt)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error while listing repos: %v\", err)\n\t}\n\tfor _, pr := range prs {\n\t\tvar body string\n\t\tif pr.Body != nil {\n\t\t\tbody = *pr.Body\n\t\t}\n\t\tvar milestone string\n\t\tif pr.Milestone != nil {\n\t\t\tmilestone = *pr.Milestone.Title\n\t\t}\n\t\tvar labels = make([]*base.Label, 0, len(pr.Labels))\n\t\tfor _, l := range pr.Labels {\n\t\t\tlabels = append(labels, convertGithubLabel(l))\n\t\t}\n\n\t\t\/\/ FIXME: This API missing reactions, we may need another extra request to get reactions\n\n\t\tvar email string\n\t\tif pr.User.Email != nil {\n\t\t\temail = *pr.User.Email\n\t\t}\n\t\tvar merged bool\n\t\t\/\/ pr.Merged is not valid, so use MergedAt to test if it's merged\n\t\tif pr.MergedAt != nil {\n\t\t\tmerged = true\n\t\t}\n\n\t\tvar (\n\t\t\theadRepoName string\n\t\t\tcloneURL     string\n\t\t\theadRef      string\n\t\t\theadSHA      string\n\t\t)\n\t\tif pr.Head.Repo != nil {\n\t\t\tif pr.Head.Repo.Name != nil {\n\t\t\t\theadRepoName = *pr.Head.Repo.Name\n\t\t\t}\n\t\t\tif pr.Head.Repo.CloneURL != nil {\n\t\t\t\tcloneURL = *pr.Head.Repo.CloneURL\n\t\t\t}\n\t\t}\n\t\tif pr.Head.Ref != nil {\n\t\t\theadRef = *pr.Head.Ref\n\t\t}\n\t\tif pr.Head.SHA != nil {\n\t\t\theadSHA = *pr.Head.SHA\n\t\t}\n\t\tvar mergeCommitSHA string\n\t\tif pr.MergeCommitSHA != nil {\n\t\t\tmergeCommitSHA = *pr.MergeCommitSHA\n\t\t}\n\n\t\tvar headUserName string\n\t\tif pr.Head.User != nil && pr.Head.User.Login != nil {\n\t\t\theadUserName = *pr.Head.User.Login\n\t\t}\n\n\t\tallPRs = append(allPRs, &base.PullRequest{\n\t\t\tTitle:          *pr.Title,\n\t\t\tNumber:         int64(*pr.Number),\n\t\t\tPosterName:     *pr.User.Login,\n\t\t\tPosterEmail:    email,\n\t\t\tContent:        body,\n\t\t\tMilestone:      milestone,\n\t\t\tState:          *pr.State,\n\t\t\tCreated:        *pr.CreatedAt,\n\t\t\tClosed:         pr.ClosedAt,\n\t\t\tLabels:         labels,\n\t\t\tMerged:         merged,\n\t\t\tMergeCommitSHA: mergeCommitSHA,\n\t\t\tMergedTime:     pr.MergedAt,\n\t\t\tIsLocked:       pr.ActiveLockReason != nil,\n\t\t\tHead: base.PullRequestBranch{\n\t\t\t\tRef:       headRef,\n\t\t\t\tSHA:       headSHA,\n\t\t\t\tRepoName:  headRepoName,\n\t\t\t\tOwnerName: headUserName,\n\t\t\t\tCloneURL:  cloneURL,\n\t\t\t},\n\t\t\tBase: base.PullRequestBranch{\n\t\t\t\tRef:       *pr.Base.Ref,\n\t\t\t\tSHA:       *pr.Base.SHA,\n\t\t\t\tRepoName:  *pr.Base.Repo.Name,\n\t\t\t\tOwnerName: *pr.Base.User.Login,\n\t\t\t},\n\t\t\tPatchURL: *pr.PatchURL,\n\t\t})\n\t}\n\n\treturn allPRs, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/jingweno\/travisarchive\/db\"\n\t\"github.com\/jingweno\/travisarchive\/filestore\"\n\t\"github.com\/jingweno\/travisarchive\/util\"\n\t\"github.com\/joho\/godotenv\"\n)\n\nvar (\n\texecDir  string\n\tmongoURL string\n)\n\nfunc init() {\n\tgodotenv.Load(\"..\/.env\")\n\tflag.StringVar(&execDir, \"e\", \"\", \"dir to the mongoexport executable\")\n\tflag.StringVar(&mongoURL, \"u\", os.Getenv(\"MONGO_URL\"), \"URL of the Mongo server\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif execDir == \"\" {\n\t\tlog.Fatal(fmt.Errorf(\"specify the dir to the mongoexport executable with -e\"))\n\t}\n\n\tif mongoURL == \"\" {\n\t\tlog.Fatal(fmt.Errorf(\"specify the URL of Mongo server with -u\"))\n\t}\n\n\tdb, err := db.Connect()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcols, err := db.DB().CollectionNames()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\texportBuilds(db, cols)\n}\n\nfunc exportBuilds(db *db.DB, cols []string) {\n\toneDayAgo := time.Now().UTC().Add(-24 * time.Hour)\n\tfor _, col := range cols {\n\t\td, err := util.ParseBuildTime(col)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif d.UTC().After(oneDayAgo) {\n\t\t\tcontinue\n\t\t}\n\n\t\toutfile, err := exportC(col)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\toutzip, err := archiveFile(outfile)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\terr = uploadZipfile(outzip)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\terr = dropC(db, col)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t}\n}\n\nfunc dropC(db *db.DB, col string) error {\n\terr := db.DropC(col)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"dropped collection %s\\n\", col)\n\n\treturn nil\n}\n\nfunc exportC(col string) (string, error) {\n\tlog.Printf(\"exporting %s...\\n\", col)\n\tcmd := &MongoExport{ExecDir: execDir, URL: mongoURL, ColName: col}\n\toutfile, err := cmd.Run()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tlog.Printf(\"exported to %s\\n\", outfile)\n\n\treturn outfile, nil\n}\n\nfunc archiveFile(outfile string) (string, error) {\n\tarchiver := &Archiver{outfile}\n\toutzip, err := archiver.Archive()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tlog.Printf(\"archived to %s\\n\", outzip)\n\n\treturn outzip, nil\n}\n\nfunc uploadZipfile(outzip string) error {\n\tzipfile, err := os.Open(outzip)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer zipfile.Close()\n\n\tfilename := fmt.Sprintf(\"\/builds\/%s\", filepath.Base(outzip))\n\tds, err := filestore.New(\"s3\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ds.Upload(filename, \"application\/zip\", zipfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"uploaded to s3 %s\", filename)\n\n\treturn nil\n}\n<commit_msg>Only drop collections that are 3 days old<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/jingweno\/travisarchive\/db\"\n\t\"github.com\/jingweno\/travisarchive\/filestore\"\n\t\"github.com\/jingweno\/travisarchive\/util\"\n\t\"github.com\/joho\/godotenv\"\n)\n\nvar (\n\texecDir  string\n\tmongoURL string\n)\n\nfunc init() {\n\tgodotenv.Load(\"..\/.env\")\n\tflag.StringVar(&execDir, \"e\", \"\", \"dir to the mongoexport executable\")\n\tflag.StringVar(&mongoURL, \"u\", os.Getenv(\"MONGO_URL\"), \"URL of the Mongo server\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif execDir == \"\" {\n\t\tlog.Fatal(fmt.Errorf(\"specify the dir to the mongoexport executable with -e\"))\n\t}\n\n\tif mongoURL == \"\" {\n\t\tlog.Fatal(fmt.Errorf(\"specify the URL of Mongo server with -u\"))\n\t}\n\n\tdb, err := db.Connect()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcols, err := db.DB().CollectionNames()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\texportBuilds(db, cols)\n}\n\nfunc exportBuilds(db *db.DB, cols []string) {\n\toneDayAgo := time.Now().UTC().Add(-24 * time.Hour)\n\tthreeDaysAgo := time.Now().UTC().Add(-3 * 24 * time.Hour)\n\tfor _, col := range cols {\n\t\td, err := util.ParseBuildTime(col)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif d.UTC().After(oneDayAgo) {\n\t\t\tcontinue\n\t\t}\n\n\t\toutfile, err := exportC(col)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\toutzip, err := archiveFile(outfile)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\terr = uploadZipfile(outzip)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ only drop collections that are 3 days old\n\t\tif d.UTC().Before(threeDaysAgo) {\n\t\t\terr = dropC(db, col)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc dropC(db *db.DB, col string) error {\n\terr := db.DropC(col)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"dropped collection %s\\n\", col)\n\n\treturn nil\n}\n\nfunc exportC(col string) (string, error) {\n\tlog.Printf(\"exporting %s...\\n\", col)\n\tcmd := &MongoExport{ExecDir: execDir, URL: mongoURL, ColName: col}\n\toutfile, err := cmd.Run()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tlog.Printf(\"exported to %s\\n\", outfile)\n\n\treturn outfile, nil\n}\n\nfunc archiveFile(outfile string) (string, error) {\n\tarchiver := &Archiver{outfile}\n\toutzip, err := archiver.Archive()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tlog.Printf(\"archived to %s\\n\", outzip)\n\n\treturn outzip, nil\n}\n\nfunc uploadZipfile(outzip string) error {\n\tzipfile, err := os.Open(outzip)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer zipfile.Close()\n\n\tfilename := fmt.Sprintf(\"\/builds\/%s\", filepath.Base(outzip))\n\tds, err := filestore.New(\"s3\")\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ds.Upload(filename, \"application\/zip\", zipfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"uploaded to s3 %s\", filename)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package mail_test\n\nimport (\n\t\"bufio\"\n\t\"crypto\/rand\"\n\t\"crypto\/tls\"\n\t\"log\"\n\t\"net\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nfunc TestMailSuite(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"mail\")\n}\n\nconst (\n\tcertPEM = `-----BEGIN CERTIFICATE-----\nMIID4DCCAsigAwIBAgIJANRk1GTj0oKXMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNV\nBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRUwEwYDVQQHDAxTYW50YSBNb25p\nY2ExFTATBgNVBAoMDFBpdm90YWwgTGFiczEWMBQGA1UECwwNQ2xvdWQgRm91bmRy\neTEUMBIGA1UEAwwLZGV2ZWxvcG1lbnQwHhcNMTQwNzA3MTgxODE1WhcNMjQwNzA0\nMTgxODE1WjB+MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEVMBMG\nA1UEBwwMU2FudGEgTW9uaWNhMRUwEwYDVQQKDAxQaXZvdGFsIExhYnMxFjAUBgNV\nBAsMDUNsb3VkIEZvdW5kcnkxFDASBgNVBAMMC2RldmVsb3BtZW50MIIBIjANBgkq\nhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyT+YaveHuISiyHBQhStt4HqXBpAK2arS\nF15roOXSI2L6O8LlMaotI4j1OQNf19\/6Q\/OiBWGGBsVuf0ywde+Ikb9RMuq9FU15\nhRXecfFyK1PU7MXMUzzY5tnh9Tcgau6t+O7OgMNGSulU3tt3xV4kQ7oKulv\/aHW7\n3tTGs6Iib4MlXzp8BM7llA5XmggTL2evwGgO\/tKEyoWVOCAaIFfYkf4AGf47xfu6\nB6qLpd3o6mdTL2xyZIrRvsCJk+\/ToaCRs6ibaM9BiRXktIFRYGlg6fY2KWvxLOL6\nYD9PacHvgCCF4ONPEIL69gWks01RpOU60c5MhndNRiRW9+JuRlLMdQIDAQABo2Ew\nXzAPBgNVHREECDAGhwR\/AAABMB0GA1UdDgQWBBRuNXjTwoXq++HZLTjF4nLhOg9w\n2DAfBgNVHSMEGDAWgBRuNXjTwoXq++HZLTjF4nLhOg9w2DAMBgNVHRMEBTADAQH\/\nMA0GCSqGSIb3DQEBBQUAA4IBAQCv1sk2oJ55l9LfP6bQkR\/nADHVZT5SSitAXpVF\nPDhk7yMtrokP2SkgOgVLlgs3H\/qxaowaqg6zeSPdnAhWM\/n0r25zx2HYO1KLcHvF\nvRYAb2skOoiYrHo6OOGHfhYj+c0ikgag\/0CDy9EZ05\/b5xPCMRoRzyp9t2gJpaqz\n5TYIwMbDqs0E9pJT\/ZjAQauwYUggxmUdhLUBnaKzzjGy7AOAldJVi\/N1MMoNQInI\nFyGrPuv4+T355ntQ274RGdytyYjMmvBANWX5+xzCJfoKlsfMxQNRgiwhNHjpqgZK\ne+\/BhTCOY1sHLFwd0eZ\/4psN9\/ytZRtcH3Y8waIwuQi3MlH5\n-----END CERTIFICATE-----`\n\tkeyPEM = `-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAyT+YaveHuISiyHBQhStt4HqXBpAK2arSF15roOXSI2L6O8Ll\nMaotI4j1OQNf19\/6Q\/OiBWGGBsVuf0ywde+Ikb9RMuq9FU15hRXecfFyK1PU7MXM\nUzzY5tnh9Tcgau6t+O7OgMNGSulU3tt3xV4kQ7oKulv\/aHW73tTGs6Iib4MlXzp8\nBM7llA5XmggTL2evwGgO\/tKEyoWVOCAaIFfYkf4AGf47xfu6B6qLpd3o6mdTL2xy\nZIrRvsCJk+\/ToaCRs6ibaM9BiRXktIFRYGlg6fY2KWvxLOL6YD9PacHvgCCF4ONP\nEIL69gWks01RpOU60c5MhndNRiRW9+JuRlLMdQIDAQABAoIBAQDHU3zUXY0Inh5Y\n5p1p+OTgVKtnLZ4Bj2Z9DOEPQPHMaMkuDdBSS5pfutQffw8b0tSfHx0XtUs5Q604\n2q1gcjpTGSoEg2l6Qv0catejBaCt919KkHLa8sZmh+F8rfgm0XZwu56+\/CqQIeEU\nxk0vqBnFFuxvPpWPUiUdBKQ14V24EWvpkzIk1PcFXzLAimmfLvrKLnfPqZbXug0L\n7kVSqLjNPWdltwWcVQ+uEgVv9TLRbEcxNIt2\/DbSxplxjTlmX3O5hzzJMYcjrPpZ\n2haoNdFyNb4y3G4F1nNrNzsTkQYfyOZBPmvMAJrx66vtEE0En9nYlq4xfjgjDr0j\nzJMhMa31AoGBAO7SV+ORuEAQ53wQU7ccvn4F8FQBaeNbSpTiHmARW0iEIvHkvp0N\n0aEdbo8aunFXNneEULP0I8tn0pBqeXjJIuh1epk3sqQg6xGodOsDK3ivIj6oaYtk\nifIVTcCL+dsCLXLMrdjAvbUWGtgS1SfZU4aRxehlH8UISaftnOE1NzdHAoGBANe5\nYR2eLb0JPwRluFeiOhiEwlkrdai8vlk8EBHSUmku\/sG7a8UuttqL1dGaUuedGfUk\n0igc3WWGU0M7JNrrk2c6BuhqwQd57A3FlvEXon4kzQAWXGWfsU2KVq51HG+\/8Cfp\n7pIybTr6ysulVtNSh1NxPwO0wgWYnmarC1kKUjRjAoGAXB5Ydlgb6OJcV9d4YxY8\nSCIETHLrJB5vizQZIVcwja0iSYnBGJVe+bV\/ksVtixBn2vv3oSIXuHrIlpnrVvLG\ne0HtUzJPvs1PvtTqnEfxubBcFi0h4Pmb1\/vtrMqRSq\/xVemrWQMnabUoD5ZcD+3d\nMPgDjZuMAJUszBB0Rc4gCTsCgYBtCRkKJFpP8u10JonfWXLt06R795h32jaH2fDx\nYRIgcg14FGgreSoZGpbPY6ZFxUVKf\/rtJXHOD+\/jynAdavbNNSoqrVK1ma1zZIyf\nfWe3RJiNU8AN6YJvg92+PhlKboRPWFEqeex15C8+cWqKU2ttBI9qKyHqPDLMB+Yr\ncikMqwKBgDLBKiVLqSeli1BrlURWGMyl7j+NgYNdih+M2Ra8dAuWt6BTQfjYW53u\nEK8URF8KvO4+PR5pRJDCNx6+uOLoTsBE7KBYEiLzK9rTpEBQIv35h4hmF75SNiF\/\ngMirbaXT377nSX0oPon0P1iUgl5tUJNqYnYdA+qcpoeCvXuObAzm\n-----END RSA PRIVATE KEY-----`\n\tStateUnknown   = \"unknown\"\n\tStateConnected = \"connected\"\n\tStateClosed    = \"closed\"\n)\n\ntype SMTPServer struct {\n\tURL             url.URL\n\tCurrentDelivery Delivery\n\tDeliveries      []Delivery\n\tListener        *net.TCPListener\n\tSupportsTLS     bool\n\tConnectWait     time.Duration\n\thalt            chan bool\n\tConnectionState string\n\tFailsHello      bool\n}\n\ntype Delivery struct {\n\tRecipient string\n\tSender    string\n\tData      []string\n\tUsedTLS   bool\n}\n\nfunc NewSMTPServer(user, pass string) *SMTPServer {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlistener, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlistenerURL, err := url.Parse(listener.Addr().String())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tserver := SMTPServer{\n\t\tURL:             *listenerURL,\n\t\tListener:        listener,\n\t\tConnectionState: StateUnknown,\n\t\thalt:            make(chan bool),\n\t}\n\tserver.Run()\n\treturn &server\n}\n\nfunc (server *SMTPServer) Run() {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-server.halt:\n\t\t\t\treturn\n\t\t\tcase connection := <-server.Accept():\n\t\t\t\tgo server.Respond(connection)\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (server *SMTPServer) Accept() chan *net.TCPConn {\n\tconnectionChan := make(chan *net.TCPConn)\n\n\tgo func() {\n\t\tconnection, err := server.Listener.AcceptTCP()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tconnectionChan <- connection\n\t}()\n\n\treturn connectionChan\n}\n\nfunc (server *SMTPServer) Close() {\n\tserver.halt <- true\n\tserver.Listener.Close()\n}\n\nfunc (server *SMTPServer) Respond(conn net.Conn) {\n\t<-time.After(server.ConnectWait)\n\tserver.ConnectionState = StateConnected\n\n\tinput := bufio.NewReader(conn)\n\toutput := bufio.NewWriter(conn)\n\tserver.Broadcast(output)\n\nLoop:\n\tfor {\n\t\tmsg, _ := input.ReadString('\\n')\n\t\tswitch {\n\t\tcase strings.Contains(msg, \"EHLO\"):\n\t\t\tserver.RespondToEHLO(output)\n\t\tcase strings.Contains(msg, \"STARTTLS\"):\n\t\t\tconn, input, output = server.RespondToStartTLS(conn, input, output)\n\t\tcase strings.Contains(msg, \"AUTH PLAIN\"):\n\t\t\tserver.RespondToAuthPlain(output)\n\t\tcase strings.Contains(msg, \"MAIL FROM\"):\n\t\t\tserver.RespondToMailFrom(output, msg)\n\t\tcase strings.Contains(msg, \"RCPT TO\"):\n\t\t\tserver.RespondToRcptTo(output, msg)\n\t\tcase strings.Contains(msg, \"DATA\"):\n\t\t\tserver.RespondToData(output)\n\t\t\tserver.RecordData(output, input)\n\t\tcase strings.Contains(msg, \"QUIT\"):\n\t\t\tserver.RespondToQuit(output)\n\t\t\tbreak Loop\n\t\t}\n\t}\n\tserver.Deliveries = append(server.Deliveries, server.CurrentDelivery)\n\tserver.CurrentDelivery = Delivery{}\n}\n\nfunc (server *SMTPServer) Broadcast(output *bufio.Writer) {\n\toutput.WriteString(\"220 localhost\\r\\n\")\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RespondToEHLO(output *bufio.Writer) {\n\tif server.FailsHello {\n\t\toutput.WriteString(\"550-FOOBAR\\n\")\n\t\toutput.WriteString(\"550 CRAZYBANANA\\r\\n\")\n\t\toutput.Flush()\n\t\treturn\n\t}\n\n\toutput.WriteString(\"250-localhost Hello\\n\")\n\tif server.SupportsTLS {\n\t\toutput.WriteString(\"250-STARTTLS\\n\")\n\t\toutput.WriteString(\"250 AUTH PLAIN LOGIN\\r\\n\")\n\t} else {\n\t\toutput.WriteString(\"250 AUTH LOGIN\\r\\n\")\n\t}\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RespondToStartTLS(conn net.Conn, input *bufio.Reader, output *bufio.Writer) (*tls.Conn, *bufio.Reader, *bufio.Writer) {\n\toutput.WriteString(\"220 Go ahead\\r\\n\")\n\toutput.Flush()\n\n\tserver.CurrentDelivery.UsedTLS = true\n\n\tcert, err := tls.X509KeyPair([]byte(certPEM), []byte(keyPEM))\n\tif err != nil {\n\t\tlog.Fatalf(\"server: loadkeys: %s\", err)\n\t}\n\tconfig := tls.Config{Certificates: []tls.Certificate{cert}}\n\tconfig.Rand = rand.Reader\n\ttlsConn := tls.Server(conn, &config)\n\n\treturn tlsConn, bufio.NewReader(tlsConn), bufio.NewWriter(tlsConn)\n}\n\nfunc (server *SMTPServer) RespondToAuthPlain(output *bufio.Writer) {\n\toutput.WriteString(\"235 OK, Go ahead\\r\\n\")\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RespondToMailFrom(output *bufio.Writer, msg string) {\n\tsender := strings.TrimSpace(msg)\n\tsender = strings.TrimPrefix(sender, \"MAIL FROM:\")\n\tsender = strings.Trim(sender, \"<>\")\n\tserver.CurrentDelivery.Sender = sender\n\n\toutput.WriteString(\"250 OK\\r\\n\")\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RespondToRcptTo(output *bufio.Writer, msg string) {\n\trecipient := strings.TrimSpace(msg)\n\trecipient = strings.TrimPrefix(recipient, \"RCPT TO:\")\n\trecipient = strings.Trim(recipient, \"<>\")\n\tserver.CurrentDelivery.Recipient = recipient\n\n\toutput.WriteString(\"250 OK\\r\\n\")\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RespondToData(output *bufio.Writer) {\n\toutput.WriteString(\"354 OK\\r\\n\")\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RecordData(output *bufio.Writer, input *bufio.Reader) {\n\tfor {\n\t\tmsg, err := input.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tif strings.TrimSpace(msg) == \".\" {\n\t\t\tbreak\n\t\t}\n\t\tserver.CurrentDelivery.Data = append(server.CurrentDelivery.Data, strings.TrimSpace(msg))\n\t}\n\toutput.WriteString(\"250 Written safely to disk.\\r\\n\")\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RespondToQuit(output *bufio.Writer) {\n\toutput.WriteString(\"221 BYE\\r\\n\")\n\toutput.Flush()\n\tserver.ConnectionState = StateClosed\n}\n<commit_msg>URL parsing behaviour changed in go1.8<commit_after>package mail_test\n\nimport (\n\t\"bufio\"\n\t\"crypto\/rand\"\n\t\"crypto\/tls\"\n\t\"log\"\n\t\"net\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nfunc TestMailSuite(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"mail\")\n}\n\nconst (\n\tcertPEM = `-----BEGIN CERTIFICATE-----\nMIID4DCCAsigAwIBAgIJANRk1GTj0oKXMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNV\nBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRUwEwYDVQQHDAxTYW50YSBNb25p\nY2ExFTATBgNVBAoMDFBpdm90YWwgTGFiczEWMBQGA1UECwwNQ2xvdWQgRm91bmRy\neTEUMBIGA1UEAwwLZGV2ZWxvcG1lbnQwHhcNMTQwNzA3MTgxODE1WhcNMjQwNzA0\nMTgxODE1WjB+MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEVMBMG\nA1UEBwwMU2FudGEgTW9uaWNhMRUwEwYDVQQKDAxQaXZvdGFsIExhYnMxFjAUBgNV\nBAsMDUNsb3VkIEZvdW5kcnkxFDASBgNVBAMMC2RldmVsb3BtZW50MIIBIjANBgkq\nhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyT+YaveHuISiyHBQhStt4HqXBpAK2arS\nF15roOXSI2L6O8LlMaotI4j1OQNf19\/6Q\/OiBWGGBsVuf0ywde+Ikb9RMuq9FU15\nhRXecfFyK1PU7MXMUzzY5tnh9Tcgau6t+O7OgMNGSulU3tt3xV4kQ7oKulv\/aHW7\n3tTGs6Iib4MlXzp8BM7llA5XmggTL2evwGgO\/tKEyoWVOCAaIFfYkf4AGf47xfu6\nB6qLpd3o6mdTL2xyZIrRvsCJk+\/ToaCRs6ibaM9BiRXktIFRYGlg6fY2KWvxLOL6\nYD9PacHvgCCF4ONPEIL69gWks01RpOU60c5MhndNRiRW9+JuRlLMdQIDAQABo2Ew\nXzAPBgNVHREECDAGhwR\/AAABMB0GA1UdDgQWBBRuNXjTwoXq++HZLTjF4nLhOg9w\n2DAfBgNVHSMEGDAWgBRuNXjTwoXq++HZLTjF4nLhOg9w2DAMBgNVHRMEBTADAQH\/\nMA0GCSqGSIb3DQEBBQUAA4IBAQCv1sk2oJ55l9LfP6bQkR\/nADHVZT5SSitAXpVF\nPDhk7yMtrokP2SkgOgVLlgs3H\/qxaowaqg6zeSPdnAhWM\/n0r25zx2HYO1KLcHvF\nvRYAb2skOoiYrHo6OOGHfhYj+c0ikgag\/0CDy9EZ05\/b5xPCMRoRzyp9t2gJpaqz\n5TYIwMbDqs0E9pJT\/ZjAQauwYUggxmUdhLUBnaKzzjGy7AOAldJVi\/N1MMoNQInI\nFyGrPuv4+T355ntQ274RGdytyYjMmvBANWX5+xzCJfoKlsfMxQNRgiwhNHjpqgZK\ne+\/BhTCOY1sHLFwd0eZ\/4psN9\/ytZRtcH3Y8waIwuQi3MlH5\n-----END CERTIFICATE-----`\n\tkeyPEM = `-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAyT+YaveHuISiyHBQhStt4HqXBpAK2arSF15roOXSI2L6O8Ll\nMaotI4j1OQNf19\/6Q\/OiBWGGBsVuf0ywde+Ikb9RMuq9FU15hRXecfFyK1PU7MXM\nUzzY5tnh9Tcgau6t+O7OgMNGSulU3tt3xV4kQ7oKulv\/aHW73tTGs6Iib4MlXzp8\nBM7llA5XmggTL2evwGgO\/tKEyoWVOCAaIFfYkf4AGf47xfu6B6qLpd3o6mdTL2xy\nZIrRvsCJk+\/ToaCRs6ibaM9BiRXktIFRYGlg6fY2KWvxLOL6YD9PacHvgCCF4ONP\nEIL69gWks01RpOU60c5MhndNRiRW9+JuRlLMdQIDAQABAoIBAQDHU3zUXY0Inh5Y\n5p1p+OTgVKtnLZ4Bj2Z9DOEPQPHMaMkuDdBSS5pfutQffw8b0tSfHx0XtUs5Q604\n2q1gcjpTGSoEg2l6Qv0catejBaCt919KkHLa8sZmh+F8rfgm0XZwu56+\/CqQIeEU\nxk0vqBnFFuxvPpWPUiUdBKQ14V24EWvpkzIk1PcFXzLAimmfLvrKLnfPqZbXug0L\n7kVSqLjNPWdltwWcVQ+uEgVv9TLRbEcxNIt2\/DbSxplxjTlmX3O5hzzJMYcjrPpZ\n2haoNdFyNb4y3G4F1nNrNzsTkQYfyOZBPmvMAJrx66vtEE0En9nYlq4xfjgjDr0j\nzJMhMa31AoGBAO7SV+ORuEAQ53wQU7ccvn4F8FQBaeNbSpTiHmARW0iEIvHkvp0N\n0aEdbo8aunFXNneEULP0I8tn0pBqeXjJIuh1epk3sqQg6xGodOsDK3ivIj6oaYtk\nifIVTcCL+dsCLXLMrdjAvbUWGtgS1SfZU4aRxehlH8UISaftnOE1NzdHAoGBANe5\nYR2eLb0JPwRluFeiOhiEwlkrdai8vlk8EBHSUmku\/sG7a8UuttqL1dGaUuedGfUk\n0igc3WWGU0M7JNrrk2c6BuhqwQd57A3FlvEXon4kzQAWXGWfsU2KVq51HG+\/8Cfp\n7pIybTr6ysulVtNSh1NxPwO0wgWYnmarC1kKUjRjAoGAXB5Ydlgb6OJcV9d4YxY8\nSCIETHLrJB5vizQZIVcwja0iSYnBGJVe+bV\/ksVtixBn2vv3oSIXuHrIlpnrVvLG\ne0HtUzJPvs1PvtTqnEfxubBcFi0h4Pmb1\/vtrMqRSq\/xVemrWQMnabUoD5ZcD+3d\nMPgDjZuMAJUszBB0Rc4gCTsCgYBtCRkKJFpP8u10JonfWXLt06R795h32jaH2fDx\nYRIgcg14FGgreSoZGpbPY6ZFxUVKf\/rtJXHOD+\/jynAdavbNNSoqrVK1ma1zZIyf\nfWe3RJiNU8AN6YJvg92+PhlKboRPWFEqeex15C8+cWqKU2ttBI9qKyHqPDLMB+Yr\ncikMqwKBgDLBKiVLqSeli1BrlURWGMyl7j+NgYNdih+M2Ra8dAuWt6BTQfjYW53u\nEK8URF8KvO4+PR5pRJDCNx6+uOLoTsBE7KBYEiLzK9rTpEBQIv35h4hmF75SNiF\/\ngMirbaXT377nSX0oPon0P1iUgl5tUJNqYnYdA+qcpoeCvXuObAzm\n-----END RSA PRIVATE KEY-----`\n\tStateUnknown   = \"unknown\"\n\tStateConnected = \"connected\"\n\tStateClosed    = \"closed\"\n)\n\ntype SMTPServer struct {\n\tURL             url.URL\n\tCurrentDelivery Delivery\n\tDeliveries      []Delivery\n\tListener        *net.TCPListener\n\tSupportsTLS     bool\n\tConnectWait     time.Duration\n\thalt            chan bool\n\tConnectionState string\n\tFailsHello      bool\n}\n\ntype Delivery struct {\n\tRecipient string\n\tSender    string\n\tData      []string\n\tUsedTLS   bool\n}\n\nfunc NewSMTPServer(user, pass string) *SMTPServer {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlistener, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlistenerURL, err := url.Parse(\"\/\/\" + listener.Addr().String())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tserver := SMTPServer{\n\t\tURL:             *listenerURL,\n\t\tListener:        listener,\n\t\tConnectionState: StateUnknown,\n\t\thalt:            make(chan bool),\n\t}\n\tserver.Run()\n\treturn &server\n}\n\nfunc (server *SMTPServer) Run() {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-server.halt:\n\t\t\t\treturn\n\t\t\tcase connection := <-server.Accept():\n\t\t\t\tgo server.Respond(connection)\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (server *SMTPServer) Accept() chan *net.TCPConn {\n\tconnectionChan := make(chan *net.TCPConn)\n\n\tgo func() {\n\t\tconnection, err := server.Listener.AcceptTCP()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tconnectionChan <- connection\n\t}()\n\n\treturn connectionChan\n}\n\nfunc (server *SMTPServer) Close() {\n\tserver.halt <- true\n\tserver.Listener.Close()\n}\n\nfunc (server *SMTPServer) Respond(conn net.Conn) {\n\t<-time.After(server.ConnectWait)\n\tserver.ConnectionState = StateConnected\n\n\tinput := bufio.NewReader(conn)\n\toutput := bufio.NewWriter(conn)\n\tserver.Broadcast(output)\n\nLoop:\n\tfor {\n\t\tmsg, _ := input.ReadString('\\n')\n\t\tswitch {\n\t\tcase strings.Contains(msg, \"EHLO\"):\n\t\t\tserver.RespondToEHLO(output)\n\t\tcase strings.Contains(msg, \"STARTTLS\"):\n\t\t\tconn, input, output = server.RespondToStartTLS(conn, input, output)\n\t\tcase strings.Contains(msg, \"AUTH PLAIN\"):\n\t\t\tserver.RespondToAuthPlain(output)\n\t\tcase strings.Contains(msg, \"MAIL FROM\"):\n\t\t\tserver.RespondToMailFrom(output, msg)\n\t\tcase strings.Contains(msg, \"RCPT TO\"):\n\t\t\tserver.RespondToRcptTo(output, msg)\n\t\tcase strings.Contains(msg, \"DATA\"):\n\t\t\tserver.RespondToData(output)\n\t\t\tserver.RecordData(output, input)\n\t\tcase strings.Contains(msg, \"QUIT\"):\n\t\t\tserver.RespondToQuit(output)\n\t\t\tbreak Loop\n\t\t}\n\t}\n\tserver.Deliveries = append(server.Deliveries, server.CurrentDelivery)\n\tserver.CurrentDelivery = Delivery{}\n}\n\nfunc (server *SMTPServer) Broadcast(output *bufio.Writer) {\n\toutput.WriteString(\"220 localhost\\r\\n\")\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RespondToEHLO(output *bufio.Writer) {\n\tif server.FailsHello {\n\t\toutput.WriteString(\"550-FOOBAR\\n\")\n\t\toutput.WriteString(\"550 CRAZYBANANA\\r\\n\")\n\t\toutput.Flush()\n\t\treturn\n\t}\n\n\toutput.WriteString(\"250-localhost Hello\\n\")\n\tif server.SupportsTLS {\n\t\toutput.WriteString(\"250-STARTTLS\\n\")\n\t\toutput.WriteString(\"250 AUTH PLAIN LOGIN\\r\\n\")\n\t} else {\n\t\toutput.WriteString(\"250 AUTH LOGIN\\r\\n\")\n\t}\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RespondToStartTLS(conn net.Conn, input *bufio.Reader, output *bufio.Writer) (*tls.Conn, *bufio.Reader, *bufio.Writer) {\n\toutput.WriteString(\"220 Go ahead\\r\\n\")\n\toutput.Flush()\n\n\tserver.CurrentDelivery.UsedTLS = true\n\n\tcert, err := tls.X509KeyPair([]byte(certPEM), []byte(keyPEM))\n\tif err != nil {\n\t\tlog.Fatalf(\"server: loadkeys: %s\", err)\n\t}\n\tconfig := tls.Config{Certificates: []tls.Certificate{cert}}\n\tconfig.Rand = rand.Reader\n\ttlsConn := tls.Server(conn, &config)\n\n\treturn tlsConn, bufio.NewReader(tlsConn), bufio.NewWriter(tlsConn)\n}\n\nfunc (server *SMTPServer) RespondToAuthPlain(output *bufio.Writer) {\n\toutput.WriteString(\"235 OK, Go ahead\\r\\n\")\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RespondToMailFrom(output *bufio.Writer, msg string) {\n\tsender := strings.TrimSpace(msg)\n\tsender = strings.TrimPrefix(sender, \"MAIL FROM:\")\n\tsender = strings.Trim(sender, \"<>\")\n\tserver.CurrentDelivery.Sender = sender\n\n\toutput.WriteString(\"250 OK\\r\\n\")\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RespondToRcptTo(output *bufio.Writer, msg string) {\n\trecipient := strings.TrimSpace(msg)\n\trecipient = strings.TrimPrefix(recipient, \"RCPT TO:\")\n\trecipient = strings.Trim(recipient, \"<>\")\n\tserver.CurrentDelivery.Recipient = recipient\n\n\toutput.WriteString(\"250 OK\\r\\n\")\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RespondToData(output *bufio.Writer) {\n\toutput.WriteString(\"354 OK\\r\\n\")\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RecordData(output *bufio.Writer, input *bufio.Reader) {\n\tfor {\n\t\tmsg, err := input.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tif strings.TrimSpace(msg) == \".\" {\n\t\t\tbreak\n\t\t}\n\t\tserver.CurrentDelivery.Data = append(server.CurrentDelivery.Data, strings.TrimSpace(msg))\n\t}\n\toutput.WriteString(\"250 Written safely to disk.\\r\\n\")\n\toutput.Flush()\n}\n\nfunc (server *SMTPServer) RespondToQuit(output *bufio.Writer) {\n\toutput.WriteString(\"221 BYE\\r\\n\")\n\toutput.Flush()\n\tserver.ConnectionState = StateClosed\n}\n<|endoftext|>"}
{"text":"<commit_before>package model\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype DataPoint struct {\n\tTimestamp\tint32\n\tValue\t\tfloat64\n}\n\ntype Metric struct {\n\tName\t\tstring\n\tDataPoints\t[]*DataPoint\n\tStep            time.Duration  \/\/ seconds\n\tStart           int32\n\tEnd\t\tint32\n}\n\ntype ViewMetric struct {\n\tTarget\t\tstring\t\t`json:target`\n\tDataPoints\t[][]interface{}\t`json:datapoints`\n}\n\nfunc NewDataPoint(ts int32, value float64) *DataPoint {\n\treturn &DataPoint{Timestamp: ts, Value: value}\n}\n\nfunc (d *DataPoint) String() string {\n\treturn fmt.Sprintf(\"datapoint timestamp=%d, value=%f\", d.Timestamp, d.Value)\n}\n\nfunc NewMetric(name string, datapoint []*DataPoint) *Metric {\n\treturn &Metric{Name: name, DataPoints: datapoint}\n}\n\nfunc (m *Metric) Count() int {\n\treturn len(m.DataPoints)\n}\n\n\n\/*\nAn example of json response\n{\n    \"target\": \"server1.cpu.softirq.percentage\",\n    \"datapoints\": [\n      [\n        0.244669050464,\n        1474725188\n      ],\n      [\n        0.236104685209,\n        1474725248\n      ],\n}\n*\/\n\n\/\/ AsResponse converts Metric into ViewMetric type\nfunc (m *Metric) AsResponse() *ViewMetric {\n\tdatapoints := make([][]interface{}, 0, len(m.DataPoints))\n\tfor _, dp := range m.DataPoints {\n\t\tp := make([]interface{}, 2)\n\t\tp[0], p[1] = dp.Value, dp.Timestamp\n\t\tdatapoints = append(datapoints, p)\n\t}\n\treturn &ViewMetric{Target: m.Name, DataPoints: datapoints}\n}\n<commit_msg>Fix missing double quote<commit_after>package model\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype DataPoint struct {\n\tTimestamp\tint32\n\tValue\t\tfloat64\n}\n\ntype Metric struct {\n\tName\t\tstring\n\tDataPoints\t[]*DataPoint\n\tStep            time.Duration  \/\/ seconds\n\tStart           int32\n\tEnd\t\tint32\n}\n\ntype ViewMetric struct {\n\tTarget\t\tstring\t\t`json:\"target\"`\n\tDataPoints\t[][]interface{}\t`json:\"datapoints\"`\n}\n\nfunc NewDataPoint(ts int32, value float64) *DataPoint {\n\treturn &DataPoint{Timestamp: ts, Value: value}\n}\n\nfunc (d *DataPoint) String() string {\n\treturn fmt.Sprintf(\"datapoint timestamp=%d, value=%f\", d.Timestamp, d.Value)\n}\n\nfunc NewMetric(name string, datapoint []*DataPoint) *Metric {\n\treturn &Metric{Name: name, DataPoints: datapoint}\n}\n\nfunc (m *Metric) Count() int {\n\treturn len(m.DataPoints)\n}\n\n\n\/*\nAn example of json response\n{\n    \"target\": \"server1.cpu.softirq.percentage\",\n    \"datapoints\": [\n      [\n        0.244669050464,\n        1474725188\n      ],\n      [\n        0.236104685209,\n        1474725248\n      ],\n}\n*\/\n\n\/\/ AsResponse converts Metric into ViewMetric type\nfunc (m *Metric) AsResponse() *ViewMetric {\n\tdatapoints := make([][]interface{}, 0, len(m.DataPoints))\n\tfor _, dp := range m.DataPoints {\n\t\tp := make([]interface{}, 2)\n\t\tp[0], p[1] = dp.Value, dp.Timestamp\n\t\tdatapoints = append(datapoints, p)\n\t}\n\treturn &ViewMetric{Target: m.Name, DataPoints: datapoints}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 The Gogs Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage models\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Unknwon\/com\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"github.com\/go-xorm\/core\"\n\t\"github.com\/go-xorm\/xorm\"\n\t_ \"github.com\/lib\/pq\"\n\n\t\"github.com\/gogits\/gogs\/models\/migrations\"\n\t\"github.com\/gogits\/gogs\/modules\/log\"\n\t\"github.com\/gogits\/gogs\/modules\/setting\"\n)\n\n\/\/ Engine represents a xorm engine or session.\ntype Engine interface {\n\tDelete(interface{}) (int64, error)\n\tExec(string, ...interface{}) (sql.Result, error)\n\tFind(interface{}, ...interface{}) error\n\tGet(interface{}) (bool, error)\n\tInsert(...interface{}) (int64, error)\n\tInsertOne(interface{}) (int64, error)\n\tId(interface{}) *xorm.Session\n\tSql(string, ...interface{}) *xorm.Session\n\tWhere(string, ...interface{}) *xorm.Session\n}\n\nfunc sessionRelease(sess *xorm.Session) {\n\tif !sess.IsCommitedOrRollbacked {\n\t\tsess.Rollback()\n\t}\n\tsess.Close()\n}\n\n\/\/ Note: get back time.Time from database Go sees it at UTC where they are really Local.\n\/\/ \tSo this function makes correct timezone offset.\nfunc regulateTimeZone(t time.Time) time.Time {\n\tif !setting.UseMySQL {\n\t\treturn t\n\t}\n\n\tzone := t.Local().Format(\"-0700\")\n\tif len(zone) != 5 {\n\t\tlog.Error(4, \"Unprocessable timezone: %s - %s\", t.Local(), zone)\n\t\treturn t\n\t}\n\thour := com.StrTo(zone[2:3]).MustInt()\n\tminutes := com.StrTo(zone[3:5]).MustInt()\n\n\tif zone[0] == '-' {\n\t\treturn t.Add(time.Duration(hour) * time.Hour).Add(time.Duration(minutes) * time.Minute)\n\t}\n\treturn t.Add(-1 * time.Duration(hour) * time.Hour).Add(-1 * time.Duration(minutes) * time.Minute)\n}\n\nvar (\n\tx         *xorm.Engine\n\ttables    []interface{}\n\tHasEngine bool\n\n\tDbCfg struct {\n\t\tType, Host, Name, User, Passwd, Path, SSLMode string\n\t}\n\n\tEnableSQLite3 bool\n\tEnableTidb    bool\n)\n\nfunc init() {\n\ttables = append(tables,\n\t\tnew(User), new(PublicKey), new(AccessToken),\n\t\tnew(Repository), new(DeployKey), new(Collaboration), new(Access),\n\t\tnew(Watch), new(Star), new(Follow), new(Action),\n\t\tnew(Issue), new(PullRequest), new(Comment), new(Attachment), new(IssueUser),\n\t\tnew(Label), new(IssueLabel), new(Milestone),\n\t\tnew(Mirror), new(Release), new(LoginSource), new(Webhook),\n\t\tnew(UpdateTask), new(HookTask),\n\t\tnew(Team), new(OrgUser), new(TeamUser), new(TeamRepo),\n\t\tnew(Notice), new(EmailAddress))\n\n\tgonicNames := []string{\"SSL\"}\n\tfor _, name := range gonicNames {\n\t\tcore.LintGonicMapper[name] = true\n\t}\n}\n\nfunc LoadConfigs() {\n\tsec := setting.Cfg.Section(\"database\")\n\tDbCfg.Type = sec.Key(\"DB_TYPE\").String()\n\tswitch DbCfg.Type {\n\tcase \"sqlite3\":\n\t\tsetting.UseSQLite3 = true\n\tcase \"mysql\":\n\t\tsetting.UseMySQL = true\n\tcase \"postgres\":\n\t\tsetting.UsePostgreSQL = true\n\tcase \"tidb\":\n\t\tsetting.UseTiDB = true\n\t}\n\tDbCfg.Host = sec.Key(\"HOST\").String()\n\tDbCfg.Name = sec.Key(\"NAME\").String()\n\tDbCfg.User = sec.Key(\"USER\").String()\n\tif len(DbCfg.Passwd) == 0 {\n\t\tDbCfg.Passwd = sec.Key(\"PASSWD\").String()\n\t}\n\tDbCfg.SSLMode = sec.Key(\"SSL_MODE\").String()\n\tDbCfg.Path = sec.Key(\"PATH\").MustString(\"data\/gogs.db\")\n}\n\nfunc getEngine() (*xorm.Engine, error) {\n\tcnnstr := \"\"\n\tswitch DbCfg.Type {\n\tcase \"mysql\":\n\t\tif DbCfg.Host[0] == '\/' { \/\/ looks like a unix socket\n\t\t\tcnnstr = fmt.Sprintf(\"%s:%s@unix(%s)\/%s?charset=utf8&parseTime=true\",\n\t\t\t\tDbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name)\n\t\t} else {\n\t\t\tcnnstr = fmt.Sprintf(\"%s:%s@tcp(%s)\/%s?charset=utf8&parseTime=true\",\n\t\t\t\tDbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name)\n\t\t}\n\tcase \"postgres\":\n\t\tvar host, port = \"127.0.0.1\", \"5432\"\n\t\tfields := strings.Split(DbCfg.Host, \":\")\n\t\tif len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {\n\t\t\thost = fields[0]\n\t\t}\n\t\tif len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {\n\t\t\tport = fields[1]\n\t\t}\n\t\tcnnstr = fmt.Sprintf(\"postgres:\/\/%s:%s@%s:%s\/%s?sslmode=%s\",\n\t\t\turl.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, DbCfg.SSLMode)\n\tcase \"sqlite3\":\n\t\tif !EnableSQLite3 {\n\t\t\treturn nil, fmt.Errorf(\"Unknown database type: %s\", DbCfg.Type)\n\t\t}\n\t\tif err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Fail to create directories: %v\", err)\n\t\t}\n\t\tcnnstr = \"file:\" + DbCfg.Path + \"?cache=shared&mode=rwc\"\n\tcase \"tidb\":\n\t\tif !EnableTidb {\n\t\t\treturn nil, fmt.Errorf(\"Unknown database type: %s\", DbCfg.Type)\n\t\t}\n\t\tif err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Fail to create directories: %v\", err)\n\t\t}\n\t\tcnnstr = \"goleveldb:\/\/\" + DbCfg.Path\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown database type: %s\", DbCfg.Type)\n\t}\n\treturn xorm.NewEngine(DbCfg.Type, cnnstr)\n}\n\nfunc NewTestEngine(x *xorm.Engine) (err error) {\n\tx, err = getEngine()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Connect to database: %v\", err)\n\t}\n\n\tx.SetMapper(core.GonicMapper{})\n\treturn x.StoreEngine(\"InnoDB\").Sync2(tables...)\n}\n\nfunc SetEngine() (err error) {\n\tx, err = getEngine()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Fail to connect to database: %v\", err)\n\t}\n\n\tx.SetMapper(core.GonicMapper{})\n\n\t\/\/ WARNING: for serv command, MUST remove the output to os.stdout,\n\t\/\/ so use log file to instead print to stdout.\n\tlogPath := path.Join(setting.LogRootPath, \"xorm.log\")\n\tos.MkdirAll(path.Dir(logPath), os.ModePerm)\n\n\tf, err := os.Create(logPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Fail to create xorm.log: %v\", err)\n\t}\n\tx.SetLogger(xorm.NewSimpleLogger(f))\n\n\tx.ShowSQL = true\n\tx.ShowInfo = true\n\tx.ShowDebug = true\n\tx.ShowErr = true\n\tx.ShowWarn = true\n\treturn nil\n}\n\nfunc NewEngine() (err error) {\n\tif err = SetEngine(); err != nil {\n\t\treturn err\n\t}\n\n\tif err = migrations.Migrate(x); err != nil {\n\t\treturn fmt.Errorf(\"migrate: %v\", err)\n\t}\n\n\tif err = x.StoreEngine(\"InnoDB\").Sync2(tables...); err != nil {\n\t\treturn fmt.Errorf(\"sync database struct error: %v\\n\", err)\n\t}\n\n\treturn nil\n}\n\ntype Statistic struct {\n\tCounter struct {\n\t\tUser, Org, PublicKey,\n\t\tRepo, Watch, Star, Action, Access,\n\t\tIssue, Comment, Oauth, Follow,\n\t\tMirror, Release, LoginSource, Webhook,\n\t\tMilestone, Label, HookTask,\n\t\tTeam, UpdateTask, Attachment int64\n\t}\n}\n\nfunc GetStatistic() (stats Statistic) {\n\tstats.Counter.User = CountUsers()\n\tstats.Counter.Org = CountOrganizations()\n\tstats.Counter.PublicKey, _ = x.Count(new(PublicKey))\n\tstats.Counter.Repo = CountRepositories()\n\tstats.Counter.Watch, _ = x.Count(new(Watch))\n\tstats.Counter.Star, _ = x.Count(new(Star))\n\tstats.Counter.Action, _ = x.Count(new(Action))\n\tstats.Counter.Access, _ = x.Count(new(Access))\n\tstats.Counter.Issue, _ = x.Count(new(Issue))\n\tstats.Counter.Comment, _ = x.Count(new(Comment))\n\tstats.Counter.Oauth = 0\n\tstats.Counter.Follow, _ = x.Count(new(Follow))\n\tstats.Counter.Mirror, _ = x.Count(new(Mirror))\n\tstats.Counter.Release, _ = x.Count(new(Release))\n\tstats.Counter.LoginSource = CountLoginSources()\n\tstats.Counter.Webhook, _ = x.Count(new(Webhook))\n\tstats.Counter.Milestone, _ = x.Count(new(Milestone))\n\tstats.Counter.Label, _ = x.Count(new(Label))\n\tstats.Counter.HookTask, _ = x.Count(new(HookTask))\n\tstats.Counter.Team, _ = x.Count(new(Team))\n\tstats.Counter.UpdateTask, _ = x.Count(new(UpdateTask))\n\tstats.Counter.Attachment, _ = x.Count(new(Attachment))\n\treturn\n}\n\nfunc Ping() error {\n\treturn x.Ping()\n}\n\n\/\/ DumpDatabase dumps all data from database to file system.\nfunc DumpDatabase(filePath string) error {\n\treturn x.DumpAllToFile(filePath)\n}\n<commit_msg>fix dependency broken because xorm's API changed<commit_after>\/\/ Copyright 2014 The Gogs Authors. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage models\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Unknwon\/com\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"github.com\/go-xorm\/core\"\n\t\"github.com\/go-xorm\/xorm\"\n\t_ \"github.com\/lib\/pq\"\n\n\t\"github.com\/gogits\/gogs\/models\/migrations\"\n\t\"github.com\/gogits\/gogs\/modules\/log\"\n\t\"github.com\/gogits\/gogs\/modules\/setting\"\n)\n\n\/\/ Engine represents a xorm engine or session.\ntype Engine interface {\n\tDelete(interface{}) (int64, error)\n\tExec(string, ...interface{}) (sql.Result, error)\n\tFind(interface{}, ...interface{}) error\n\tGet(interface{}) (bool, error)\n\tInsert(...interface{}) (int64, error)\n\tInsertOne(interface{}) (int64, error)\n\tId(interface{}) *xorm.Session\n\tSql(string, ...interface{}) *xorm.Session\n\tWhere(string, ...interface{}) *xorm.Session\n}\n\nfunc sessionRelease(sess *xorm.Session) {\n\tif !sess.IsCommitedOrRollbacked {\n\t\tsess.Rollback()\n\t}\n\tsess.Close()\n}\n\n\/\/ Note: get back time.Time from database Go sees it at UTC where they are really Local.\n\/\/ \tSo this function makes correct timezone offset.\nfunc regulateTimeZone(t time.Time) time.Time {\n\tif !setting.UseMySQL {\n\t\treturn t\n\t}\n\n\tzone := t.Local().Format(\"-0700\")\n\tif len(zone) != 5 {\n\t\tlog.Error(4, \"Unprocessable timezone: %s - %s\", t.Local(), zone)\n\t\treturn t\n\t}\n\thour := com.StrTo(zone[2:3]).MustInt()\n\tminutes := com.StrTo(zone[3:5]).MustInt()\n\n\tif zone[0] == '-' {\n\t\treturn t.Add(time.Duration(hour) * time.Hour).Add(time.Duration(minutes) * time.Minute)\n\t}\n\treturn t.Add(-1 * time.Duration(hour) * time.Hour).Add(-1 * time.Duration(minutes) * time.Minute)\n}\n\nvar (\n\tx         *xorm.Engine\n\ttables    []interface{}\n\tHasEngine bool\n\n\tDbCfg struct {\n\t\tType, Host, Name, User, Passwd, Path, SSLMode string\n\t}\n\n\tEnableSQLite3 bool\n\tEnableTidb    bool\n)\n\nfunc init() {\n\ttables = append(tables,\n\t\tnew(User), new(PublicKey), new(AccessToken),\n\t\tnew(Repository), new(DeployKey), new(Collaboration), new(Access),\n\t\tnew(Watch), new(Star), new(Follow), new(Action),\n\t\tnew(Issue), new(PullRequest), new(Comment), new(Attachment), new(IssueUser),\n\t\tnew(Label), new(IssueLabel), new(Milestone),\n\t\tnew(Mirror), new(Release), new(LoginSource), new(Webhook),\n\t\tnew(UpdateTask), new(HookTask),\n\t\tnew(Team), new(OrgUser), new(TeamUser), new(TeamRepo),\n\t\tnew(Notice), new(EmailAddress))\n\n\tgonicNames := []string{\"SSL\"}\n\tfor _, name := range gonicNames {\n\t\tcore.LintGonicMapper[name] = true\n\t}\n}\n\nfunc LoadConfigs() {\n\tsec := setting.Cfg.Section(\"database\")\n\tDbCfg.Type = sec.Key(\"DB_TYPE\").String()\n\tswitch DbCfg.Type {\n\tcase \"sqlite3\":\n\t\tsetting.UseSQLite3 = true\n\tcase \"mysql\":\n\t\tsetting.UseMySQL = true\n\tcase \"postgres\":\n\t\tsetting.UsePostgreSQL = true\n\tcase \"tidb\":\n\t\tsetting.UseTiDB = true\n\t}\n\tDbCfg.Host = sec.Key(\"HOST\").String()\n\tDbCfg.Name = sec.Key(\"NAME\").String()\n\tDbCfg.User = sec.Key(\"USER\").String()\n\tif len(DbCfg.Passwd) == 0 {\n\t\tDbCfg.Passwd = sec.Key(\"PASSWD\").String()\n\t}\n\tDbCfg.SSLMode = sec.Key(\"SSL_MODE\").String()\n\tDbCfg.Path = sec.Key(\"PATH\").MustString(\"data\/gogs.db\")\n}\n\nfunc getEngine() (*xorm.Engine, error) {\n\tcnnstr := \"\"\n\tswitch DbCfg.Type {\n\tcase \"mysql\":\n\t\tif DbCfg.Host[0] == '\/' { \/\/ looks like a unix socket\n\t\t\tcnnstr = fmt.Sprintf(\"%s:%s@unix(%s)\/%s?charset=utf8&parseTime=true\",\n\t\t\t\tDbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name)\n\t\t} else {\n\t\t\tcnnstr = fmt.Sprintf(\"%s:%s@tcp(%s)\/%s?charset=utf8&parseTime=true\",\n\t\t\t\tDbCfg.User, DbCfg.Passwd, DbCfg.Host, DbCfg.Name)\n\t\t}\n\tcase \"postgres\":\n\t\tvar host, port = \"127.0.0.1\", \"5432\"\n\t\tfields := strings.Split(DbCfg.Host, \":\")\n\t\tif len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {\n\t\t\thost = fields[0]\n\t\t}\n\t\tif len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {\n\t\t\tport = fields[1]\n\t\t}\n\t\tcnnstr = fmt.Sprintf(\"postgres:\/\/%s:%s@%s:%s\/%s?sslmode=%s\",\n\t\t\turl.QueryEscape(DbCfg.User), url.QueryEscape(DbCfg.Passwd), host, port, DbCfg.Name, DbCfg.SSLMode)\n\tcase \"sqlite3\":\n\t\tif !EnableSQLite3 {\n\t\t\treturn nil, fmt.Errorf(\"Unknown database type: %s\", DbCfg.Type)\n\t\t}\n\t\tif err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Fail to create directories: %v\", err)\n\t\t}\n\t\tcnnstr = \"file:\" + DbCfg.Path + \"?cache=shared&mode=rwc\"\n\tcase \"tidb\":\n\t\tif !EnableTidb {\n\t\t\treturn nil, fmt.Errorf(\"Unknown database type: %s\", DbCfg.Type)\n\t\t}\n\t\tif err := os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Fail to create directories: %v\", err)\n\t\t}\n\t\tcnnstr = \"goleveldb:\/\/\" + DbCfg.Path\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown database type: %s\", DbCfg.Type)\n\t}\n\treturn xorm.NewEngine(DbCfg.Type, cnnstr)\n}\n\nfunc NewTestEngine(x *xorm.Engine) (err error) {\n\tx, err = getEngine()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Connect to database: %v\", err)\n\t}\n\n\tx.SetMapper(core.GonicMapper{})\n\treturn x.StoreEngine(\"InnoDB\").Sync2(tables...)\n}\n\nfunc SetEngine() (err error) {\n\tx, err = getEngine()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Fail to connect to database: %v\", err)\n\t}\n\n\tx.SetMapper(core.GonicMapper{})\n\n\t\/\/ WARNING: for serv command, MUST remove the output to os.stdout,\n\t\/\/ so use log file to instead print to stdout.\n\tlogPath := path.Join(setting.LogRootPath, \"xorm.log\")\n\tos.MkdirAll(path.Dir(logPath), os.ModePerm)\n\n\tf, err := os.Create(logPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Fail to create xorm.log: %v\", err)\n\t}\n\tx.SetLogger(xorm.NewSimpleLogger(f))\n\tx.ShowSQL(true)\n\treturn nil\n}\n\nfunc NewEngine() (err error) {\n\tif err = SetEngine(); err != nil {\n\t\treturn err\n\t}\n\n\tif err = migrations.Migrate(x); err != nil {\n\t\treturn fmt.Errorf(\"migrate: %v\", err)\n\t}\n\n\tif err = x.StoreEngine(\"InnoDB\").Sync2(tables...); err != nil {\n\t\treturn fmt.Errorf(\"sync database struct error: %v\\n\", err)\n\t}\n\n\treturn nil\n}\n\ntype Statistic struct {\n\tCounter struct {\n\t\tUser, Org, PublicKey,\n\t\tRepo, Watch, Star, Action, Access,\n\t\tIssue, Comment, Oauth, Follow,\n\t\tMirror, Release, LoginSource, Webhook,\n\t\tMilestone, Label, HookTask,\n\t\tTeam, UpdateTask, Attachment int64\n\t}\n}\n\nfunc GetStatistic() (stats Statistic) {\n\tstats.Counter.User = CountUsers()\n\tstats.Counter.Org = CountOrganizations()\n\tstats.Counter.PublicKey, _ = x.Count(new(PublicKey))\n\tstats.Counter.Repo = CountRepositories()\n\tstats.Counter.Watch, _ = x.Count(new(Watch))\n\tstats.Counter.Star, _ = x.Count(new(Star))\n\tstats.Counter.Action, _ = x.Count(new(Action))\n\tstats.Counter.Access, _ = x.Count(new(Access))\n\tstats.Counter.Issue, _ = x.Count(new(Issue))\n\tstats.Counter.Comment, _ = x.Count(new(Comment))\n\tstats.Counter.Oauth = 0\n\tstats.Counter.Follow, _ = x.Count(new(Follow))\n\tstats.Counter.Mirror, _ = x.Count(new(Mirror))\n\tstats.Counter.Release, _ = x.Count(new(Release))\n\tstats.Counter.LoginSource = CountLoginSources()\n\tstats.Counter.Webhook, _ = x.Count(new(Webhook))\n\tstats.Counter.Milestone, _ = x.Count(new(Milestone))\n\tstats.Counter.Label, _ = x.Count(new(Label))\n\tstats.Counter.HookTask, _ = x.Count(new(HookTask))\n\tstats.Counter.Team, _ = x.Count(new(Team))\n\tstats.Counter.UpdateTask, _ = x.Count(new(UpdateTask))\n\tstats.Counter.Attachment, _ = x.Count(new(Attachment))\n\treturn\n}\n\nfunc Ping() error {\n\treturn x.Ping()\n}\n\n\/\/ DumpDatabase dumps all data from database to file system.\nfunc DumpDatabase(filePath string) error {\n\treturn x.DumpAllToFile(filePath)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"log\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"flag\"\n\t\"path\/filepath\"\n)\n\nvar redirFile string\nvar db map[string]string\n\nfunc main() {\n\tflag.StringVar(&redirFile, \"redirFile\", \"redirs.json\", \"The path to the file to use as persistent storage\")\n\tport := flag.String(\"port\", \"8080\", \"Which port to start the HTTP server on\")\n\tflag.Parse()\n\n\tinitializeRedirections()\n\tstartHttpServer(*port)\n}\n\nfunc initializeRedirections() {\n\tvar err error\n\tdb, err = readRedirectFile()\n\tif err != nil {\n\t\tlog.Panicf(\"Could not read redir file, %+v\", err)\n\t}\n}\n\nfunc readRedirectFile() (map[string]string, error) {\n\tabsPath, err := filepath.Abs(redirFile)\n\tif err != nil {\n\t\tlog.Printf(\"Could not read absolute path of %s. Everything is fine but I can't tell you exactly where the config file is\\n\", err)\n\t}\n\n\tlog.Printf(\"Reading redirects from %s\\n\", absPath)\n\tif _, err := os.Stat(redirFile); os.IsNotExist(err) {\n\t\tlog.Printf(\"%s was not found, starting without any redirects\\n\", redirFile)\n\t\treturn make(map[string]string), nil\n\t}\n\n\tb, err := ioutil.ReadFile(redirFile)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Unable to read the redirect file, \" + err.Error())\n\t}\n\n\tm := make(map[string]string)\n\terr = json.Unmarshal(b, &m)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Unable to parse contents of redirect file, \" + err.Error())\n\t}\n\n\tlog.Printf(\"Starting with the following redirs:\\n%v\\n\", string(b))\n\treturn m, nil\n}\n\nfunc startHttpServer(port string) {\n\thttp.HandleFunc(\"\/\", routeRequest)\n\tlog.Printf(\"Starting http server on port %s\\n\", port)\n\terr := http.ListenAndServe(\":\" + port, nil)\n\tif err != nil {\n\t\tlog.Panicf(\"Error occured in the http server, %v\\n\", err)\n\t}\n}\n\nfunc addRedirection(shortName, redirectTo string) error {\n\tlog.Printf(\"Adding or updating redirect %s -> %s\", shortName, redirectTo)\n\tdb[shortName] = redirectTo\n\treturn persistRedirections()\n}\n\nfunc removeRedirection(shortName string) error {\n\tdelete(db, shortName)\n\treturn persistRedirections()\n}\n\nfunc persistRedirections() error {\n\tb, err := json.MarshalIndent(db, \"\", \"    \")\n\tif err != nil {\n\t\treturn errors.New(\"Unable to marshal the current redirects to JSON, \" + err.Error())\n\t}\n\treturn ioutil.WriteFile(redirFile, b, 0644)\n}\n\nfunc routeRequest(w http.ResponseWriter, r *http.Request) {\n\tshortName := r.URL.Path[1:]\n\tlog.Printf(\"Got request for %s\", shortName)\n\n\tif len(shortName) == 0 {\n\t\tfmt.Fprintf(w, \"Welcome to go-shorty\\nTo add a redirect GET to %s\/add\/short=url\\nTo delete GET to %s\/delete\/short\", r.URL.Host, r.URL.Host)\n\t} else if strings.HasPrefix(shortName, \"add\/\") {\n\t\tassumeRequestIsAddRedir(w, r)\n\t} else if strings.HasPrefix(shortName, \"remove\/\") {\n\t\tassumeRequestIsRemoveRedir(w, r)\n\t} else {\n\t\tassumeRequestIsARedir(w, r)\n\t}\n}\n\nfunc assumeRequestIsAddRedir(w http.ResponseWriter, r *http.Request) {\n\tfrom, to, err := parseFromAndTo(r)\n\tif err != nil {\n\t\tlog.Printf(\"Could not parse add redirect input %v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr = addRedirection(from, to)\n\tif err == nil {\n\t\tfmt.Fprintf(w, \"Successfully added redirect %s -> %s\", from, to)\n\t} else {\n\t\treply := fmt.Sprintf(\"Failed adding redirect %s -> %s , %+v\", from, to, err)\n\t\thttp.Error(w, reply, 500)\n\t}\n}\n\nfunc parseFromAndTo(r *http.Request) (string, string, error) {\n\ta := strings.Split(r.URL.Path, \"\/\")\n\tif len(a) < 2 {\n\t\treply := fmt.Sprintf(\"Invalid add format, use %s\/add\/from=to\", r.Host)\n\t\treturn \"\", \"\", errors.New(reply);\n\t}\n\n\trawParts := strings.Split(a[2], \"=\")\n\tif len(rawParts) < 2 {\n\t\treply := fmt.Sprintf(\"Invalid add format, use %s\/add\/from=to\", r.Host)\n\t\treturn \"\", \"\", errors.New(reply)\n\t}\n\n\tfrom := rawParts[0]\n\n\ti := strings.Index(r.URL.Path, from + \"=\") + len(from + \"=\")\n\tto := r.URL.Path[i:]\n\tif !strings.Contains(to, \":\/\/\") && strings.Contains(to, \":\/\") {\n\t\tto = strings.Replace(to, \":\/\", \":\/\/\", 1)\n\t}\n\tif !strings.Contains(to, \":\/\/\") {\n\t\tto = \"http:\/\/\" + to\n\t}\n\n\treturn from, to, nil\n}\n\nfunc assumeRequestIsRemoveRedir(w http.ResponseWriter, r *http.Request) {\n\ta := strings.Split(r.URL.Path, \"\/\")\n\tif len(a) < 2 {\n\t\treply := fmt.Sprintf(\"Invalid add format, use %s\/delete\/short\", r.Host)\n\t\thttp.Error(w, reply, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tfrom := a[2]\n\terr := removeRedirection(from)\n\tif err == nil {\n\t\tfmt.Fprint(w, \"Successfully deleted redirect %s \", from,)\n\t} else {\n\t\treply := fmt.Sprintf(\"Failed removing redirect %s, %+v\", from, err)\n\t\thttp.Error(w, reply, 500)\n\t}\n}\n\nfunc assumeRequestIsARedir(w http.ResponseWriter, r *http.Request) {\n\tshortName := r.URL.Path[1:]\n\tfound, redirectTo, err := tryFindMatchForShortName(shortName)\n\tif err != nil {\n\t\tlog.Printf(\"Failed looking up match for %s, %+v\", shortName, err)\n\t\treply := fmt.Sprintf(\"Failed looking up match for %s, %+v\", shortName, err)\n\t\thttp.Error(w, reply, 500)\n\n\t} else if found {\n\t\tlog.Printf(\"Found match %s -> %s\", shortName, redirectTo)\n\t\t\/\/ TODO: Check if the match is something that can be redirected to\n\t\t\/\/ it e.g, has to start with a valid protocol such as http:\/\/\n\t\thttp.Redirect(w, r, redirectTo, http.StatusFound)\n\n\t} else {\n\t\tlog.Printf(\"No match for %s found\", shortName)\n\t\treply := fmt.Sprintf(\"No match for %s found\", shortName)\n\t\thttp.Error(w, reply, 404)\n\n\t}\n}\n\nfunc tryFindMatchForShortName(shortName string) (bool, string, error) {\n\tres := db[shortName]\n\treturn res != \"\", res, nil\n}<commit_msg>Fixed bug where the query string was not passed to add, added more server side logging<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"log\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"flag\"\n\t\"path\/filepath\"\n)\n\nvar redirFile string\nvar db map[string]string\n\nfunc main() {\n\tflag.StringVar(&redirFile, \"redirFile\", \"redirs.json\", \"The path to the file to use as persistent storage\")\n\tport := flag.String(\"port\", \"8080\", \"Which port to start the HTTP server on\")\n\tflag.Parse()\n\n\tinitializeRedirections()\n\tstartHttpServer(*port)\n}\n\nfunc initializeRedirections() {\n\tvar err error\n\tdb, err = readRedirectFile()\n\tif err != nil {\n\t\tlog.Panicf(\"Could not read redir file, %+v\", err)\n\t}\n}\n\nfunc readRedirectFile() (map[string]string, error) {\n\tabsPath, err := filepath.Abs(redirFile)\n\tif err != nil {\n\t\tlog.Printf(\"Could not read absolute path of %s. Everything is fine but I can't tell you exactly where the config file is\\n\", err)\n\t}\n\n\tlog.Printf(\"Reading redirects from %s\\n\", absPath)\n\tif _, err := os.Stat(redirFile); os.IsNotExist(err) {\n\t\tlog.Printf(\"%s was not found, starting without any redirects\\n\", redirFile)\n\t\treturn make(map[string]string), nil\n\t}\n\n\tb, err := ioutil.ReadFile(redirFile)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Unable to read the redirect file, \" + err.Error())\n\t}\n\n\tm := make(map[string]string)\n\terr = json.Unmarshal(b, &m)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Unable to parse contents of redirect file, \" + err.Error())\n\t}\n\n\tlog.Printf(\"Starting with the following redirs:\\n%v\\n\", string(b))\n\treturn m, nil\n}\n\nfunc startHttpServer(port string) {\n\thttp.HandleFunc(\"\/\", routeRequest)\n\tlog.Printf(\"Starting http server on port %s\\n\", port)\n\terr := http.ListenAndServe(\":\" + port, nil)\n\tif err != nil {\n\t\tlog.Panicf(\"Error occured in the http server, %v\\n\", err)\n\t}\n}\n\nfunc addRedirection(shortName, redirectTo string) error {\n\tlog.Printf(\"Adding or updating redirect %s -> %s\", shortName, redirectTo)\n\tdb[shortName] = redirectTo\n\treturn persistRedirections()\n}\n\nfunc removeRedirection(shortName string) error {\n\tdelete(db, shortName)\n\treturn persistRedirections()\n}\n\nfunc persistRedirections() error {\n\tb, err := json.MarshalIndent(db, \"\", \"    \")\n\tif err != nil {\n\t\treturn errors.New(\"Unable to marshal the current redirects to JSON, \" + err.Error())\n\t}\n\treturn ioutil.WriteFile(redirFile, b, 0644)\n}\n\nfunc routeRequest(w http.ResponseWriter, r *http.Request) {\n\tshortName := r.RequestURI\n\tlog.Printf(\"Got request for %s\", shortName)\n\n\tif len(shortName) == 0 {\n\t\tfmt.Fprintf(w, \"Welcome to go-shorty\\nTo add a redirect GET to %s\/add\/short=url\\nTo delete GET to %s\/delete\/short\", r.URL.Host, r.URL.Host)\n\t} else if strings.HasPrefix(shortName, \"\/add\/\") {\n\t\tassumeRequestIsAddRedir(w, r)\n\t} else if strings.HasPrefix(shortName, \"\/delete\/\") {\n\t\tassumeRequestIsRemoveRedir(w, r)\n\t} else {\n\t\tassumeRequestIsARedir(w, r)\n\t}\n}\n\nfunc assumeRequestIsAddRedir(w http.ResponseWriter, r *http.Request) {\n\tfrom, to, err := parseFromAndTo(r.RequestURI)\n\tif err != nil {\n\t\tlog.Printf(\"Could not parse add redirect input %v\", err)\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\terr = addRedirection(from, to)\n\tif err == nil {\n\t\ts := fmt.Sprintf( \"Successfully added redirect %s -> %s\", from, to)\n\t\tlog.Println(s)\n\t\tfmt.Fprintf(w, s)\n\t} else {\n\t\treply := fmt.Sprintf(\"Failed adding redirect %s -> %s , %+v\", from, to, err)\n\t\tlog.Println(reply)\n\t\thttp.Error(w, reply, 500)\n\t}\n}\n\nfunc parseFromAndTo(rawString string) (string, string, error) {\n\ta := strings.Split(rawString, \"\/\")\n\tif len(a) < 2 {\n\t\treply := fmt.Sprintf(\"Invalid add format, use \/add\/from=to\")\n\t\treturn \"\", \"\", errors.New(reply);\n\t}\n\n\trawParts := strings.Split(a[2], \"=\")\n\tif len(rawParts) < 2 {\n\t\treply := fmt.Sprintf(\"Invalid add format, use \/add\/from=to\")\n\t\treturn \"\", \"\", errors.New(reply)\n\t}\n\n\tfrom := rawParts[0]\n\n\ti := strings.Index(rawString, from + \"=\") + len(from + \"=\")\n\tto := rawString[i:]\n\tif !strings.Contains(to, \":\/\/\") && strings.Contains(to, \":\/\") {\n\t\tto = strings.Replace(to, \":\/\", \":\/\/\", 1)\n\t}\n\tif !strings.Contains(to, \":\/\/\") {\n\t\tto = \"http:\/\/\" + to\n\t}\n\n\treturn from, to, nil\n}\n\nfunc assumeRequestIsRemoveRedir(w http.ResponseWriter, r *http.Request) {\n\ta := strings.Split(r.URL.Path, \"\/\")\n\tif len(a) < 2 {\n\t\treply := fmt.Sprintf(\"Invalid add format, use %s\/delete\/short\", r.Host)\n\t\tlog.Println(reply)\n\t\thttp.Error(w, reply, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tfrom := a[2]\n\terr := removeRedirection(from)\n\tif err == nil {\n\t\treply := fmt.Sprintf(\"Successfully deleted redirect %s \", from)\n\t\tlog.Println(reply)\n\t\tfmt.Fprint(w, reply)\n\t} else {\n\t\treply := fmt.Sprintf(\"Failed removing redirect %s, %+v\", from, err)\n\t\tlog.Println(reply)\n\t\thttp.Error(w, reply, 500)\n\t}\n}\n\nfunc assumeRequestIsARedir(w http.ResponseWriter, r *http.Request) {\n\tshortName := r.URL.Path[1:]\n\tfound, redirectTo, err := tryFindMatchForShortName(shortName)\n\tif err != nil {\n\t\tlog.Printf(\"Failed looking up match for %s, %+v\", shortName, err)\n\t\treply := fmt.Sprintf(\"Failed looking up match for %s, %+v\", shortName, err)\n\t\thttp.Error(w, reply, 500)\n\n\t} else if found {\n\t\tlog.Printf(\"Found match %s -> %s\", shortName, redirectTo)\n\t\t\/\/ TODO: Check if the match is something that can be redirected to\n\t\t\/\/ it e.g, has to start with a valid protocol such as http:\/\/\n\t\thttp.Redirect(w, r, redirectTo, http.StatusFound)\n\n\t} else {\n\t\tlog.Printf(\"No match for %s found\", shortName)\n\t\treply := fmt.Sprintf(\"No match for %s found\", shortName)\n\t\thttp.Error(w, reply, 404)\n\n\t}\n}\n\nfunc tryFindMatchForShortName(shortName string) (bool, string, error) {\n\tres := db[shortName]\n\treturn res != \"\", res, nil\n}<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"time\"\n\n\tenvmanModels \"github.com\/bitrise-io\/envman\/models\"\n)\n\n\/\/ StepSourceModel ...\ntype StepSourceModel struct {\n\tGit    string `json:\"git,omitempty\" yaml:\"git,omitempty\"`\n\tCommit string `json:\"commit,omitempty\" yaml:\"commit,omitempty\"`\n}\n\n\/\/ DependencyModel ...\ntype DependencyModel struct {\n\tManager string `json:\"manager,omitempty\" yaml:\"manager,omitempty\"`\n\tName    string `json:\"name,omitempty\" yaml:\"name,omitempty\"`\n}\n\n\/\/ BrewDepModel ...\ntype BrewDepModel struct {\n\tName string `json:\"name,omitempty\" yaml:\"name,omitempty\"`\n}\n\n\/\/ AptGetDepModel ...\ntype AptGetDepModel struct {\n\tName string `json:\"name,omitempty\" yaml:\"name,omitempty\"`\n}\n\n\/\/ DepsModel ...\ntype DepsModel struct {\n\tBrew   []BrewDepModel   `json:\"brew,omitempty\" yaml:\"brew,omitempty\"`\n\tAptGet []AptGetDepModel `json:\"apt_get,omitempty\" yaml:\"apt_get,omitempty\"`\n}\n\n\/\/ StepModel ...\ntype StepModel struct {\n\tTitle       *string `json:\"title,omitempty\" yaml:\"title,omitempty\"`\n\tSummary     *string `json:\"summary,omitempty\" yaml:\"summary,omitempty\"`\n\tDescription *string `json:\"description,omitempty\" yaml:\"description,omitempty\"`\n\t\/\/\n\tWebsite       *string `json:\"website,omitempty\" yaml:\"website,omitempty\"`\n\tSourceCodeURL *string `json:\"source_code_url,omitempty\" yaml:\"source_code_url,omitempty\"`\n\tSupportURL    *string `json:\"support_url,omitempty\" yaml:\"support_url,omitempty\"`\n\t\/\/ auto-generated at share\n\tPublishedAt *time.Time        `json:\"published_at,omitempty\" yaml:\"published_at,omitempty\"`\n\tSource      StepSourceModel   `json:\"source,omitempty\" yaml:\"source,omitempty\"`\n\tAssetURLs   map[string]string `json:\"asset_urls,omitempty\" yaml:\"asset_urls,omitempty\"`\n\t\/\/\n\tHostOsTags          []string          `json:\"host_os_tags,omitempty\" yaml:\"host_os_tags,omitempty\"`\n\tProjectTypeTags     []string          `json:\"project_type_tags,omitempty\" yaml:\"project_type_tags,omitempty\"`\n\tTypeTags            []string          `json:\"type_tags,omitempty\" yaml:\"type_tags,omitempty\"`\n\tDependencies        []DependencyModel `json:\"dependencies,omitempty\" yaml:\"dependencies,omitempty\"`\n\tDeps                DepsModel         `json:\"deps,omitempty\" yaml:\"deps,omitempty\"`\n\tIsRequiresAdminUser *bool             `json:\"is_requires_admin_user,omitempty\" yaml:\"is_requires_admin_user,omitempty\"`\n\t\/\/ IsAlwaysRun : if true then this step will always run,\n\t\/\/  even if a previous step fails.\n\tIsAlwaysRun *bool `json:\"is_always_run,omitempty\" yaml:\"is_always_run,omitempty\"`\n\t\/\/ IsSkippable : if true and this step fails the build will still continue.\n\t\/\/  If false then the build will be marked as failed and only those\n\t\/\/  steps will run which are marked with IsAlwaysRun.\n\tIsSkippable *bool `json:\"is_skippable,omitempty\" yaml:\"is_skippable,omitempty\"`\n\t\/\/ RunIf : only run the step if the template example evaluates to true\n\tRunIf *string `json:\"run_if,omitempty\" yaml:\"run_if,omitempty\"`\n\t\/\/\n\tInputs  []envmanModels.EnvironmentItemModel `json:\"inputs,omitempty\" yaml:\"inputs,omitempty\"`\n\tOutputs []envmanModels.EnvironmentItemModel `json:\"outputs,omitempty\" yaml:\"outputs,omitempty\"`\n}\n\n\/\/ StepGroupModel ...\ntype StepGroupModel struct {\n\tLatestVersionNumber string               `json:\"latest_version_number\"`\n\tVersions            map[string]StepModel `json:\"versions\"`\n}\n\n\/\/ StepHash ...\ntype StepHash map[string]StepGroupModel\n\n\/\/ DownloadLocationModel ...\ntype DownloadLocationModel struct {\n\tType string `json:\"type\"`\n\tSrc  string `json:\"src\"`\n}\n\n\/\/ StepCollectionModel ...\ntype StepCollectionModel struct {\n\tFormatVersion         string                  `json:\"format_version\" yaml:\"format_version\"`\n\tGeneratedAtTimeStamp  int64                   `json:\"generated_at_timestamp\" yaml:\"generated_at_timestamp\"`\n\tSteplibSource         string                  `json:\"steplib_source\" yaml:\"steplib_source\"`\n\tDownloadLocations     []DownloadLocationModel `json:\"download_locations\" yaml:\"download_locations\"`\n\tAssetsDownloadBaseURI string                  `json:\"assets_download_base_uri\" yaml:\"assets_download_base_uri\"`\n\tSteps                 StepHash                `json:\"steps\" yaml:\"steps\"`\n}\n\n\/\/ EnvInfoModel ...\ntype EnvInfoModel struct {\n\tKey          string   `json:\"key,omitempty\" yaml:\"key,omitempty\"`\n\tTitle        string   `json:\"title,omitempty\" yaml:\"title,omitempty\"`\n\tDescription  string   `json:\"description,omitempty\" yaml:\"description,omitempty\"`\n\tValueOptions []string `json:\"value_options,omitempty\" yaml:\"value_options,omitempty\"`\n\tDefaultValue string   `json:\"default_value,omitempty\" yaml:\"default_value,omitempty\"`\n\tIsExpand     bool     `json:\"is_expand\" yaml:\"is_expand\"`\n}\n\n\/\/ StepInfoModel ...\ntype StepInfoModel struct {\n\tID          string         `json:\"step_id,omitempty\" yaml:\"step_id,omitempty\"`\n\tVersion     string         `json:\"step_version,omitempty\" yaml:\"step_version,omitempty\"`\n\tLatest      string         `json:\"latest_version,omitempty\" yaml:\"latest_version,omitempty\"`\n\tDescription string         `json:\"description,omitempty\" yaml:\"description,omitempty\"`\n\tSource      string         `json:\"source,omitempty\" yaml:\"source,omitempty\"`\n\tStepLib     string         `json:\"steplib,omitempty\" yaml:\"steplib,omitempty\"`\n\tInputs      []EnvInfoModel `json:\"inputs,omitempty\" yaml:\"inputs,omitempty\"`\n\tOutputs     []EnvInfoModel `json:\"outputs,omitempty\" yaml:\"outputs,omitempty\"`\n}\n\n\/\/ StepListModel ...\ntype StepListModel struct {\n\tStepLib string   `json:\"steplib,omitempty\" yaml:\"steplib,omitempty\"`\n\tSteps   []string `json:\"steps,omitempty\" yaml:\"steps,omitempty\"`\n}\n<commit_msg>check only deps<commit_after>package models\n\nimport (\n\t\"time\"\n\n\tenvmanModels \"github.com\/bitrise-io\/envman\/models\"\n)\n\n\/\/ StepSourceModel ...\ntype StepSourceModel struct {\n\tGit    string `json:\"git,omitempty\" yaml:\"git,omitempty\"`\n\tCommit string `json:\"commit,omitempty\" yaml:\"commit,omitempty\"`\n}\n\n\/\/ DependencyModel ...\ntype DependencyModel struct {\n\tManager string `json:\"manager,omitempty\" yaml:\"manager,omitempty\"`\n\tName    string `json:\"name,omitempty\" yaml:\"name,omitempty\"`\n}\n\n\/\/ BrewDepModel ...\ntype BrewDepModel struct {\n\tName string `json:\"name,omitempty\" yaml:\"name,omitempty\"`\n}\n\n\/\/ AptGetDepModel ...\ntype AptGetDepModel struct {\n\tName string `json:\"name,omitempty\" yaml:\"name,omitempty\"`\n}\n\n\/\/ CheckOnlyDepModel ...\ntype CheckOnlyDepModel struct {\n\tName string `json:\"name,omitempty\" yaml:\"name,omitempty\"`\n}\n\n\/\/ DepsModel ...\ntype DepsModel struct {\n\tBrew     []BrewDepModel      `json:\"brew,omitempty\" yaml:\"brew,omitempty\"`\n\tAptGet   []AptGetDepModel    `json:\"apt_get,omitempty\" yaml:\"apt_get,omitempty\"`\n\tTryCheck []CheckOnlyDepModel `json:\"check_only,omitempty\" yaml:\"check_only,omitempty\"`\n}\n\n\/\/ StepModel ...\ntype StepModel struct {\n\tTitle       *string `json:\"title,omitempty\" yaml:\"title,omitempty\"`\n\tSummary     *string `json:\"summary,omitempty\" yaml:\"summary,omitempty\"`\n\tDescription *string `json:\"description,omitempty\" yaml:\"description,omitempty\"`\n\t\/\/\n\tWebsite       *string `json:\"website,omitempty\" yaml:\"website,omitempty\"`\n\tSourceCodeURL *string `json:\"source_code_url,omitempty\" yaml:\"source_code_url,omitempty\"`\n\tSupportURL    *string `json:\"support_url,omitempty\" yaml:\"support_url,omitempty\"`\n\t\/\/ auto-generated at share\n\tPublishedAt *time.Time        `json:\"published_at,omitempty\" yaml:\"published_at,omitempty\"`\n\tSource      StepSourceModel   `json:\"source,omitempty\" yaml:\"source,omitempty\"`\n\tAssetURLs   map[string]string `json:\"asset_urls,omitempty\" yaml:\"asset_urls,omitempty\"`\n\t\/\/\n\tHostOsTags          []string          `json:\"host_os_tags,omitempty\" yaml:\"host_os_tags,omitempty\"`\n\tProjectTypeTags     []string          `json:\"project_type_tags,omitempty\" yaml:\"project_type_tags,omitempty\"`\n\tTypeTags            []string          `json:\"type_tags,omitempty\" yaml:\"type_tags,omitempty\"`\n\tDependencies        []DependencyModel `json:\"dependencies,omitempty\" yaml:\"dependencies,omitempty\"`\n\tDeps                DepsModel         `json:\"deps,omitempty\" yaml:\"deps,omitempty\"`\n\tIsRequiresAdminUser *bool             `json:\"is_requires_admin_user,omitempty\" yaml:\"is_requires_admin_user,omitempty\"`\n\t\/\/ IsAlwaysRun : if true then this step will always run,\n\t\/\/  even if a previous step fails.\n\tIsAlwaysRun *bool `json:\"is_always_run,omitempty\" yaml:\"is_always_run,omitempty\"`\n\t\/\/ IsSkippable : if true and this step fails the build will still continue.\n\t\/\/  If false then the build will be marked as failed and only those\n\t\/\/  steps will run which are marked with IsAlwaysRun.\n\tIsSkippable *bool `json:\"is_skippable,omitempty\" yaml:\"is_skippable,omitempty\"`\n\t\/\/ RunIf : only run the step if the template example evaluates to true\n\tRunIf *string `json:\"run_if,omitempty\" yaml:\"run_if,omitempty\"`\n\t\/\/\n\tInputs  []envmanModels.EnvironmentItemModel `json:\"inputs,omitempty\" yaml:\"inputs,omitempty\"`\n\tOutputs []envmanModels.EnvironmentItemModel `json:\"outputs,omitempty\" yaml:\"outputs,omitempty\"`\n}\n\n\/\/ StepGroupModel ...\ntype StepGroupModel struct {\n\tLatestVersionNumber string               `json:\"latest_version_number\"`\n\tVersions            map[string]StepModel `json:\"versions\"`\n}\n\n\/\/ StepHash ...\ntype StepHash map[string]StepGroupModel\n\n\/\/ DownloadLocationModel ...\ntype DownloadLocationModel struct {\n\tType string `json:\"type\"`\n\tSrc  string `json:\"src\"`\n}\n\n\/\/ StepCollectionModel ...\ntype StepCollectionModel struct {\n\tFormatVersion         string                  `json:\"format_version\" yaml:\"format_version\"`\n\tGeneratedAtTimeStamp  int64                   `json:\"generated_at_timestamp\" yaml:\"generated_at_timestamp\"`\n\tSteplibSource         string                  `json:\"steplib_source\" yaml:\"steplib_source\"`\n\tDownloadLocations     []DownloadLocationModel `json:\"download_locations\" yaml:\"download_locations\"`\n\tAssetsDownloadBaseURI string                  `json:\"assets_download_base_uri\" yaml:\"assets_download_base_uri\"`\n\tSteps                 StepHash                `json:\"steps\" yaml:\"steps\"`\n}\n\n\/\/ EnvInfoModel ...\ntype EnvInfoModel struct {\n\tKey          string   `json:\"key,omitempty\" yaml:\"key,omitempty\"`\n\tTitle        string   `json:\"title,omitempty\" yaml:\"title,omitempty\"`\n\tDescription  string   `json:\"description,omitempty\" yaml:\"description,omitempty\"`\n\tValueOptions []string `json:\"value_options,omitempty\" yaml:\"value_options,omitempty\"`\n\tDefaultValue string   `json:\"default_value,omitempty\" yaml:\"default_value,omitempty\"`\n\tIsExpand     bool     `json:\"is_expand\" yaml:\"is_expand\"`\n}\n\n\/\/ StepInfoModel ...\ntype StepInfoModel struct {\n\tID          string         `json:\"step_id,omitempty\" yaml:\"step_id,omitempty\"`\n\tVersion     string         `json:\"step_version,omitempty\" yaml:\"step_version,omitempty\"`\n\tLatest      string         `json:\"latest_version,omitempty\" yaml:\"latest_version,omitempty\"`\n\tDescription string         `json:\"description,omitempty\" yaml:\"description,omitempty\"`\n\tSource      string         `json:\"source,omitempty\" yaml:\"source,omitempty\"`\n\tStepLib     string         `json:\"steplib,omitempty\" yaml:\"steplib,omitempty\"`\n\tInputs      []EnvInfoModel `json:\"inputs,omitempty\" yaml:\"inputs,omitempty\"`\n\tOutputs     []EnvInfoModel `json:\"outputs,omitempty\" yaml:\"outputs,omitempty\"`\n}\n\n\/\/ StepListModel ...\ntype StepListModel struct {\n\tStepLib string   `json:\"steplib,omitempty\" yaml:\"steplib,omitempty\"`\n\tSteps   []string `json:\"steps,omitempty\" yaml:\"steps,omitempty\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/logvoyage\/logvoyage\/shared\/config\"\n\n\t_ \"github.com\/jinzhu\/gorm\/dialects\/postgres\"\n)\n\nvar db *gorm.DB\n\nfunc InitDatabase() {\n\tif db == nil {\n\t\tdb = NewConnection()\n\t}\n}\n\n\/\/ NewConnection creates new database connection\nfunc NewConnection() *gorm.DB {\n\tdsn := fmt.Sprintf(\n\t\t\"host=%s port=%s user=%s dbname=%s sslmode=%s password=%s\",\n\t\tconfig.Get(\"db.address\"),\n\t\tconfig.Get(\"db.port\"),\n\t\tconfig.Get(\"db.user\"),\n\t\tconfig.Get(\"db.database\"),\n\t\tconfig.Get(\"db.sslmode\"),\n\t\tconfig.Get(\"db.password\"),\n\t)\n\tdb, err := gorm.Open(\"postgres\", dsn)\n\tif err != nil {\n\t\tlog.Println(\"Database connection error:\", err)\n\t}\n\tdb.LogMode(true)\n\treturn db\n}\n\n\/\/ GetConnection returns database connection instance\nfunc GetConnection() *gorm.DB {\n\treturn db\n}\n\ntype BaseModel struct {\n\tID        uint       `gorm:\"primary_key\" json:\"id\"`\n\tCreatedAt time.Time  `json:\"created_at\"`\n\tUpdatedAt time.Time  `json:\"updated_at\"`\n\tDeletedAt *time.Time `sql:\"index\" json:\"deleted_at\"`\n}\n<commit_msg>Added todo<commit_after>package models\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/logvoyage\/logvoyage\/shared\/config\"\n\n\t_ \"github.com\/jinzhu\/gorm\/dialects\/postgres\"\n)\n\nvar db *gorm.DB\n\nfunc InitDatabase() {\n\tif db == nil {\n\t\tdb = NewConnection()\n\t}\n}\n\n\/\/ NewConnection creates new database connection\nfunc NewConnection() *gorm.DB {\n\tdsn := fmt.Sprintf(\n\t\t\"host=%s port=%s user=%s dbname=%s sslmode=%s password=%s\",\n\t\tconfig.Get(\"db.address\"),\n\t\tconfig.Get(\"db.port\"),\n\t\tconfig.Get(\"db.user\"),\n\t\tconfig.Get(\"db.database\"),\n\t\tconfig.Get(\"db.sslmode\"),\n\t\tconfig.Get(\"db.password\"),\n\t)\n\tdb, err := gorm.Open(\"postgres\", dsn)\n\tif err != nil {\n\t\tlog.Println(\"Database connection error:\", err)\n\t}\n\tdb.LogMode(true)\n\treturn db\n}\n\n\/\/ GetConnection returns database connection instance\nfunc GetConnection() *gorm.DB {\n\treturn db\n}\n\ntype BaseModel struct {\n\tID        uint       `gorm:\"primary_key\" json:\"id\"`\n\tCreatedAt time.Time  `json:\"created_at\"`\n\tUpdatedAt time.Time  `json:\"updated_at\"`\n\tDeletedAt *time.Time `sql:\"index\" json:\"deleted_at\"` \/\/ TODO: Remove deleted_at. Records should be deleted permanently.\n}\n<|endoftext|>"}
{"text":"<commit_before>package drouter\n\nimport (\n\tdockerclient \"github.com\/docker\/engine-api\/client\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\t\/\/dockertypes \"github.com\/docker\/engine-api\/types\"\n\t\/\/dockerevents \"github.com\/docker\/engine-api\/types\/events\"\n\t\/\/dockerfilters \"github.com\/docker\/engine-api\/types\/filters\"\n)\n\nvar (\n\tdc *dockerclient.Client\n)\n\nfunc TestMain(m *testing.M) {\n\texitStatus := 1\n\tdefer func() { os.Exit(exitStatus) }()\n\tvar err error\n\n\tdefaultHeaders := map[string]string{\"User-Agent\": \"engine-api-cli-1.0\"}\n\tdc, err = dockerclient.NewClient(\"unix:\/\/\/var\/run\/docker.sock\", \"v1.23\", nil, defaultHeaders)\n\tif err != nil {\n\t\treturn\n\t}\n\n\texitStatus = m.Run()\n}\n\n\/\/ A most basic test to make sure it doesn't die on start\nfunc TestRunClose(t *testing.T) {\n\topts := &DistributedRouterOptions{\n\t\tAggressive: true,\n\t}\n\n\tquit := make(chan struct{})\n\tech := make(chan error)\n\tgo func() {\n\t\tech <- Run(opts, quit)\n\t}()\n\n\ttimeoutCh := make(chan struct{})\n\tgo func() {\n\t\ttime.Sleep(10 * time.Second)\n\t\tclose(timeoutCh)\n\t}()\n\n\tvar err error\n\tselect {\n\tcase _ = <-timeoutCh:\n\t\tclose(quit)\n\t\terr = <-ech\n\tcase err = <-ech:\n\t}\n\n\tif err != nil {\n\t\tt.Errorf(\"Error on Run Return: %v\", err)\n\t}\n}\n\nfunc newContainer() (*container, error) {\n}\n\n\/*\nevery mode needs to do the following:\nn1 := non drouter network\nc1 := container on n1\nn2 := drouter network\nc2 := container on c2\nn3 := drouter network\nc3 := drouter network on n3\nc23 := container on network n2 and n3\nn4 := drouter network\n\nstart drouter\n\n\/\/test networks:\n-not connected to n1\n-connected to n2\n-connected to n3\nif aggressive:\n\t-connected to n4\nelse:\n\t-not connected to n4\n\n\/\/ test containers:\n-c1 routes unchanged\nif !containerGateway:\n\t-c2 contains route to n3\n\t-c3 contains route to n2\n\t-c23 routes unchanged\nelse:\n\t-c2 gateway changed\n\t-c3 gateway changed\n\t-c23 gateway is one of the correct options\n\n\n\n*\/\n<commit_msg>some test progress<commit_after>package drouter\n\nimport (\n\tdockerclient \"github.com\/docker\/engine-api\/client\"\n\t\"golang.org\/x\/net\/context\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\t\/\/dockertypes \"github.com\/docker\/engine-api\/types\"\n\t\/\/dockerevents \"github.com\/docker\/engine-api\/types\/events\"\n\t\/\/dockerfilters \"github.com\/docker\/engine-api\/types\/filters\"\n)\n\nvar (\n\tdc *dockerclient.Client\n\tbg context.Context\n)\n\nfunc TestMain(m *testing.M) {\n\texitStatus := 1\n\tdefer func() { os.Exit(exitStatus) }()\n\tvar err error\n\n\tdefaultHeaders := map[string]string{\"User-Agent\": \"engine-api-cli-1.0\"}\n\tdc, err = dockerclient.NewClient(\"unix:\/\/\/var\/run\/docker.sock\", \"v1.23\", nil, defaultHeaders)\n\tif err != nil {\n\t\treturn\n\t}\n\tbg = context.Background()\n\n\texitStatus = m.Run()\n}\n\n\/\/ A most basic test to make sure it doesn't die on start\nfunc TestRunClose(t *testing.T) {\n\topts := &DistributedRouterOptions{\n\t\tAggressive: true,\n\t}\n\n\tquit := make(chan struct{})\n\tech := make(chan error)\n\tgo func() {\n\t\tech <- Run(opts, quit)\n\t}()\n\n\ttimeoutCh := make(chan struct{})\n\tgo func() {\n\t\ttime.Sleep(10 * time.Second)\n\t\tclose(timeoutCh)\n\t}()\n\n\tvar err error\n\tselect {\n\tcase _ = <-timeoutCh:\n\t\tclose(quit)\n\t\terr = <-ech\n\tcase err = <-ech:\n\t}\n\n\tif err != nil {\n\t\tt.Errorf(\"Error on Run Return: %v\", err)\n\t}\n}\n\nfunc createNetwork(n int) {\n\tname := fmt.Stringf(\"n%v\", n)\n\tdc.NetworkCreate(bg, name, dockertypes.NetworkCreate{\n\t\tOptions: make(map[string]string{\"drouter\": \"true\"}),\n\t\tIPAM: dockerNetworkTypes.IPAM{\n\t\t\tConfig: []dockerNetworkTypes.IPAMConfig{\n\t\t\t\tdockerNetworkTypes.IPAMConfig{\n\t\t\t\t\tSubnet:  fmt.Stringf(\"192.168.242.%v\/29\", n*8),\n\t\t\t\t\tGateway: fmt.Stringf(\"192.168.242.%v\/29\", n*8+1),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n}\n\nvar n []*network\nvar c []*container\n\nfunc newNetwork()\n\nfunc newContainer() (*container, error) {\n}\n\n\/*\n\/\/ startup & shutdown tests\nn0 := non drouter network\nc0 := container on n0\nn1 := drouter network\nc1 := container on n1\nn2 := drouter network\nc2 := drouter network on n2\nn3 := drouter network\n\nstart drouter\n\ndocker events expected:\n\t- self connect to n1\n\t- self connect to n2\n\tif aggresive:\n\t\t- self connect to n3\n\nroute events expected:\n\t- self direct to n1\n\t- self direct to n2\n\tif aggressive:\n\t\t- self direct to n3\n\tif containergateway:\n\t\t- gateway change on c1\n\t\t- gateway change on c2\n\tif !containergateway:\n\t\t- c1 to n2 via self-n1 - after direct to n1\n\t\t- c2 to n1 via self-n2 - after direct to n2\n\t\tif aggressive:\n\t\t\t- c1 to n3 via self-n1 - after direct to n3\n\t\t\t- c2 to n3 via self-n2 - after direct to n3\n\nstop drouter\n\ndocker events expected:\n\t- self disconnect from n1\n\t- self disconnect from n2\n\tif aggressive:\n\t\t- self disconnect from n3\n\nroute events expected:\n\t\/\/ remember we don't see route loss on interface down\n\tif containergateway:\n\t\t- gateway change to orig on c1\n\t\t- gateway change to orig on c2\n\tif !containergateway:\n\t\t- lose c1 to n2 - before self disconnect on n2\n\t\t- lose c2 to n1 - before self disconnect on n1\n\t\tif aggressive:\n\t\t\t- lose c1 to n3 - before self disconnect on n3\n\t\t\t- lose c2 to n3 - before self disconnect on n3\n\n\/\/ multi-connected tests\n\n\n\/\/ multi-subnet on dockernet test\n\n*\/\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/authelia\/authelia\/internal\/utils\"\n)\n\nvar arch string\n\nvar supportedArch = []string{\"amd64\", \"arm32v7\", \"arm64v8\", \"darwin\"}\nvar defaultArch = \"amd64\"\nvar buildkiteQEMU = os.Getenv(\"BUILDKITE_AGENT_META_DATA_QEMU\")\nvar ciBranch = os.Getenv(\"BUILDKITE_BRANCH\")\nvar ciPullRequest = os.Getenv(\"BUILDKITE_PULL_REQUEST\")\nvar ciTag = os.Getenv(\"BUILDKITE_TAG\")\nvar dockerTags = regexp.MustCompile(`v(?P<Patch>(?P<Minor>(?P<Major>\\d+)\\.\\d+)\\.\\d+.*)`)\nvar ignoredSuffixes = regexp.MustCompile(\"alpha|beta\")\nvar publicRepo = regexp.MustCompile(`.*\\:.*`)\nvar tags = dockerTags.FindStringSubmatch(ciTag)\n\nfunc init() {\n\tDockerBuildCmd.PersistentFlags().StringVar(&arch, \"arch\", defaultArch, \"target architecture among: \"+strings.Join(supportedArch, \", \"))\n\tDockerPushCmd.PersistentFlags().StringVar(&arch, \"arch\", defaultArch, \"target architecture among: \"+strings.Join(supportedArch, \", \"))\n}\n\nfunc checkArchIsSupported(arch string) {\n\tfor _, a := range supportedArch {\n\t\tif arch == a {\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Fatal(\"Architecture is not supported. Please select one of \" + strings.Join(supportedArch, \", \") + \".\")\n}\n\nfunc dockerBuildOfficialImage(arch string) error {\n\tdocker := &Docker{}\n\t\/\/ Set default Architecture Dockerfile to amd64\n\tdockerfile := \"Dockerfile\"\n\t\/\/ Set version of QEMU\n\tqemuversion := \"v4.2.0-6\"\n\n\t\/\/ If not the default value\n\tif arch != defaultArch {\n\t\tdockerfile = fmt.Sprintf(\"%s.%s\", dockerfile, arch)\n\t}\n\n\tif arch == \"arm32v7\" {\n\t\tif buildkiteQEMU != \"true\" {\n\t\t\terr := utils.CommandWithStdout(\"docker\", \"run\", \"--rm\", \"--privileged\", \"multiarch\/qemu-user-static\", \"--reset\", \"-p\", \"yes\").Run()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t\terr := utils.CommandWithStdout(\"bash\", \"-c\", \"wget https:\/\/github.com\/multiarch\/qemu-user-static\/releases\/download\/\"+qemuversion+\"\/qemu-arm-static -O .\/qemu-arm-static && chmod +x .\/qemu-arm-static\").Run()\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else if arch == \"arm64v8\" {\n\t\tif buildkiteQEMU != \"true\" {\n\t\t\terr := utils.CommandWithStdout(\"docker\", \"run\", \"--rm\", \"--privileged\", \"multiarch\/qemu-user-static\", \"--reset\", \"-p\", \"yes\").Run()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t\terr := utils.CommandWithStdout(\"bash\", \"-c\", \"wget https:\/\/github.com\/multiarch\/qemu-user-static\/releases\/download\/\"+qemuversion+\"\/qemu-aarch64-static -O .\/qemu-aarch64-static && chmod +x .\/qemu-aarch64-static\").Run()\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tgitTag := ciTag\n\tif gitTag == \"\" {\n\t\t\/\/ If commit is not tagged, mark the build has having master tag.\n\t\tgitTag = \"master\"\n\t}\n\n\tcmd := utils.Shell(\"git rev-parse HEAD\")\n\tcmd.Stdout = nil\n\tcmd.Stderr = nil\n\tcommitBytes, err := cmd.Output()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcommitHash := strings.Trim(string(commitBytes), \"\\n\")\n\n\treturn docker.Build(IntermediateDockerImageName, dockerfile, \".\", gitTag, commitHash)\n}\n\n\/\/ DockerBuildCmd Command for building docker image of Authelia.\nvar DockerBuildCmd = &cobra.Command{\n\tUse:   \"build\",\n\tShort: \"Build the docker image of Authelia\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tlog.Infof(\"Building Docker image %s...\", DockerImageName)\n\t\tcheckArchIsSupported(arch)\n\t\terr := dockerBuildOfficialImage(arch)\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tdocker := &Docker{}\n\t\terr = docker.Tag(IntermediateDockerImageName, DockerImageName)\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t},\n}\n\n\/\/ DockerPushCmd Command for pushing Authelia docker image to Docker Hub\nvar DockerPushCmd = &cobra.Command{\n\tUse:   \"push-image\",\n\tShort: \"Publish Authelia docker image to Docker Hub\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tlog.Infof(\"Pushing Docker image %s to Docker Hub...\", DockerImageName)\n\t\tcheckArchIsSupported(arch)\n\t\tpublishDockerImage(arch)\n\t},\n}\n\n\/\/ DockerManifestCmd Command for pushing Authelia docker manifest to Docker Hub\nvar DockerManifestCmd = &cobra.Command{\n\tUse:   \"push-manifest\",\n\tShort: \"Publish Authelia docker manifest to Docker Hub\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tlog.Infof(\"Pushing Docker manifest of %s to Docker Hub...\", DockerImageName)\n\t\tpublishDockerManifest()\n\t},\n}\n\nfunc login(docker *Docker) {\n\tusername := os.Getenv(\"DOCKER_USERNAME\")\n\tpassword := os.Getenv(\"DOCKER_PASSWORD\")\n\n\tif username == \"\" {\n\t\tlog.Fatal(errors.New(\"DOCKER_USERNAME is empty\"))\n\t}\n\n\tif password == \"\" {\n\t\tlog.Fatal(errors.New(\"DOCKER_PASSWORD is empty\"))\n\t}\n\n\tlog.Infof(\"Login to Docker Hub as %s\", username)\n\terr := docker.Login(username, password)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Login to Docker Hub failed\", err)\n\t}\n}\n\nfunc deploy(docker *Docker, tag string) {\n\timageWithTag := DockerImageName + \":\" + tag\n\n\tlog.Infof(\"Docker image %s will be deployed on Docker Hub\", imageWithTag)\n\n\tif err := docker.Tag(DockerImageName, imageWithTag); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif err := docker.Push(imageWithTag); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc deployManifest(docker *Docker, tag string, amd64tag string, arm32v7tag string, arm64v8tag string) {\n\tdockerImagePrefix := DockerImageName + \":\"\n\n\tlog.Infof(\"Docker manifest %s%s will be deployed on Docker Hub\", dockerImagePrefix, tag)\n\n\terr := docker.Manifest(dockerImagePrefix+tag, dockerImagePrefix+amd64tag, dockerImagePrefix+arm32v7tag, dockerImagePrefix+arm64v8tag)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttags := []string{amd64tag, arm32v7tag, arm64v8tag}\n\tfor _, t := range tags {\n\t\tlog.Infof(\"Docker removing tag for %s%s on Docker Hub\", dockerImagePrefix, t)\n\n\t\tif err := docker.CleanTag(t); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\nfunc publishDockerImage(arch string) {\n\tdocker := &Docker{}\n\n\tif ciTag != \"\" {\n\t\tif len(tags) == 4 {\n\t\t\tlog.Infof(\"Detected tags: '%s' | '%s' | '%s'\", tags[1], tags[2], tags[3])\n\n\t\t\tlogin(docker)\n\t\t\tdeploy(docker, tags[1]+\"-\"+arch)\n\t\t\tif !ignoredSuffixes.MatchString(ciTag) {\n\t\t\t\tdeploy(docker, tags[2]+\"-\"+arch)\n\t\t\t\tdeploy(docker, tags[3]+\"-\"+arch)\n\t\t\t\tdeploy(docker, \"latest-\"+arch)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Fatal(\"Docker image will not be published, the specified tag does not conform to the standard\")\n\t\t}\n\t} else if ciBranch != \"master\" && !publicRepo.MatchString(ciBranch) {\n\t\tlogin(docker)\n\t\tdeploy(docker, ciBranch+\"-\"+arch)\n\t} else if ciBranch != \"master\" && publicRepo.MatchString(ciBranch) {\n\t\tlogin(docker)\n\t\tdeploy(docker, \"PR\"+ciPullRequest+\"-\"+arch)\n\t} else if ciBranch == \"master\" && ciPullRequest == \"false\" {\n\t\tlogin(docker)\n\t\tdeploy(docker, \"master-\"+arch)\n\t} else {\n\t\tlog.Info(\"Docker image will not be published\")\n\t}\n}\n\nfunc publishDockerManifest() {\n\tdocker := &Docker{}\n\n\tif ciTag != \"\" {\n\t\tif len(tags) == 4 {\n\t\t\tlog.Infof(\"Detected tags: '%s' | '%s' | '%s'\", tags[1], tags[2], tags[3])\n\n\t\t\tlogin(docker)\n\t\t\tdeployManifest(docker, tags[1], tags[1]+\"-amd64\", tags[1]+\"-arm32v7\", tags[1]+\"-arm64v8\")\n\t\t\tpublishDockerReadme(docker)\n\n\t\t\tif !ignoredSuffixes.MatchString(ciTag) {\n\t\t\t\tdeployManifest(docker, tags[2], tags[2]+\"-amd64\", tags[2]+\"-arm32v7\", tags[2]+\"-arm64v8\")\n\t\t\t\tdeployManifest(docker, tags[3], tags[3]+\"-amd64\", tags[3]+\"-arm32v7\", tags[3]+\"-arm64v8\")\n\t\t\t\tdeployManifest(docker, \"latest\", \"latest-amd64\", \"latest-arm32v7\", \"latest-arm64v8\")\n\t\t\t\tpublishDockerReadme(docker)\n\t\t\t\tupdateMicroBadger(docker)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Fatal(\"Docker manifest will not be published, the specified tag does not conform to the standard\")\n\t\t}\n\t} else if ciBranch != \"master\" && !publicRepo.MatchString(ciBranch) {\n\t\tlogin(docker)\n\t\tdeployManifest(docker, ciBranch, ciBranch+\"-amd64\", ciBranch+\"-arm32v7\", ciBranch+\"-arm64v8\")\n\t} else if ciBranch != \"master\" && publicRepo.MatchString(ciBranch) {\n\t\tlogin(docker)\n\t\tdeployManifest(docker, \"PR\"+ciPullRequest, \"PR\"+ciPullRequest+\"-amd64\", \"PR\"+ciPullRequest+\"-arm32v7\", \"PR\"+ciPullRequest+\"-arm64v8\")\n\t} else if ciBranch == \"master\" && ciPullRequest == \"false\" {\n\t\tlogin(docker)\n\t\tdeployManifest(docker, \"master\", \"master-amd64\", \"master-arm32v7\", \"master-arm64v8\")\n\t\tpublishDockerReadme(docker)\n\t} else {\n\t\tlog.Info(\"Docker manifest will not be published\")\n\t}\n}\n\nfunc publishDockerReadme(docker *Docker) {\n\tlog.Info(\"Docker pushing README.md to Docker Hub\")\n\n\tif err := docker.PublishReadme(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\nfunc updateMicroBadger(docker *Docker) {\n\tlog.Info(\"Updating MicroBadger metadata from Docker Hub\")\n\n\tif err := docker.UpdateMicroBadger(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>[MISC] Update QEMU to v4.2.0-7 (#921)<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/authelia\/authelia\/internal\/utils\"\n)\n\nvar arch string\n\nvar supportedArch = []string{\"amd64\", \"arm32v7\", \"arm64v8\", \"darwin\"}\nvar defaultArch = \"amd64\"\nvar buildkiteQEMU = os.Getenv(\"BUILDKITE_AGENT_META_DATA_QEMU\")\nvar ciBranch = os.Getenv(\"BUILDKITE_BRANCH\")\nvar ciPullRequest = os.Getenv(\"BUILDKITE_PULL_REQUEST\")\nvar ciTag = os.Getenv(\"BUILDKITE_TAG\")\nvar dockerTags = regexp.MustCompile(`v(?P<Patch>(?P<Minor>(?P<Major>\\d+)\\.\\d+)\\.\\d+.*)`)\nvar ignoredSuffixes = regexp.MustCompile(\"alpha|beta\")\nvar publicRepo = regexp.MustCompile(`.*\\:.*`)\nvar tags = dockerTags.FindStringSubmatch(ciTag)\n\nfunc init() {\n\tDockerBuildCmd.PersistentFlags().StringVar(&arch, \"arch\", defaultArch, \"target architecture among: \"+strings.Join(supportedArch, \", \"))\n\tDockerPushCmd.PersistentFlags().StringVar(&arch, \"arch\", defaultArch, \"target architecture among: \"+strings.Join(supportedArch, \", \"))\n}\n\nfunc checkArchIsSupported(arch string) {\n\tfor _, a := range supportedArch {\n\t\tif arch == a {\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Fatal(\"Architecture is not supported. Please select one of \" + strings.Join(supportedArch, \", \") + \".\")\n}\n\nfunc dockerBuildOfficialImage(arch string) error {\n\tdocker := &Docker{}\n\t\/\/ Set default Architecture Dockerfile to amd64\n\tdockerfile := \"Dockerfile\"\n\t\/\/ Set version of QEMU\n\tqemuversion := \"v4.2.0-7\"\n\n\t\/\/ If not the default value\n\tif arch != defaultArch {\n\t\tdockerfile = fmt.Sprintf(\"%s.%s\", dockerfile, arch)\n\t}\n\n\tif arch == \"arm32v7\" {\n\t\tif buildkiteQEMU != \"true\" {\n\t\t\terr := utils.CommandWithStdout(\"docker\", \"run\", \"--rm\", \"--privileged\", \"multiarch\/qemu-user-static\", \"--reset\", \"-p\", \"yes\").Run()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t\terr := utils.CommandWithStdout(\"bash\", \"-c\", \"wget https:\/\/github.com\/multiarch\/qemu-user-static\/releases\/download\/\"+qemuversion+\"\/qemu-arm-static -O .\/qemu-arm-static && chmod +x .\/qemu-arm-static\").Run()\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else if arch == \"arm64v8\" {\n\t\tif buildkiteQEMU != \"true\" {\n\t\t\terr := utils.CommandWithStdout(\"docker\", \"run\", \"--rm\", \"--privileged\", \"multiarch\/qemu-user-static\", \"--reset\", \"-p\", \"yes\").Run()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\n\t\terr := utils.CommandWithStdout(\"bash\", \"-c\", \"wget https:\/\/github.com\/multiarch\/qemu-user-static\/releases\/download\/\"+qemuversion+\"\/qemu-aarch64-static -O .\/qemu-aarch64-static && chmod +x .\/qemu-aarch64-static\").Run()\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tgitTag := ciTag\n\tif gitTag == \"\" {\n\t\t\/\/ If commit is not tagged, mark the build has having master tag.\n\t\tgitTag = \"master\"\n\t}\n\n\tcmd := utils.Shell(\"git rev-parse HEAD\")\n\tcmd.Stdout = nil\n\tcmd.Stderr = nil\n\tcommitBytes, err := cmd.Output()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tcommitHash := strings.Trim(string(commitBytes), \"\\n\")\n\n\treturn docker.Build(IntermediateDockerImageName, dockerfile, \".\", gitTag, commitHash)\n}\n\n\/\/ DockerBuildCmd Command for building docker image of Authelia.\nvar DockerBuildCmd = &cobra.Command{\n\tUse:   \"build\",\n\tShort: \"Build the docker image of Authelia\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tlog.Infof(\"Building Docker image %s...\", DockerImageName)\n\t\tcheckArchIsSupported(arch)\n\t\terr := dockerBuildOfficialImage(arch)\n\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\n\t\tdocker := &Docker{}\n\t\terr = docker.Tag(IntermediateDockerImageName, DockerImageName)\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t},\n}\n\n\/\/ DockerPushCmd Command for pushing Authelia docker image to Docker Hub\nvar DockerPushCmd = &cobra.Command{\n\tUse:   \"push-image\",\n\tShort: \"Publish Authelia docker image to Docker Hub\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tlog.Infof(\"Pushing Docker image %s to Docker Hub...\", DockerImageName)\n\t\tcheckArchIsSupported(arch)\n\t\tpublishDockerImage(arch)\n\t},\n}\n\n\/\/ DockerManifestCmd Command for pushing Authelia docker manifest to Docker Hub\nvar DockerManifestCmd = &cobra.Command{\n\tUse:   \"push-manifest\",\n\tShort: \"Publish Authelia docker manifest to Docker Hub\",\n\tRun: func(cmd *cobra.Command, args []string) {\n\t\tlog.Infof(\"Pushing Docker manifest of %s to Docker Hub...\", DockerImageName)\n\t\tpublishDockerManifest()\n\t},\n}\n\nfunc login(docker *Docker) {\n\tusername := os.Getenv(\"DOCKER_USERNAME\")\n\tpassword := os.Getenv(\"DOCKER_PASSWORD\")\n\n\tif username == \"\" {\n\t\tlog.Fatal(errors.New(\"DOCKER_USERNAME is empty\"))\n\t}\n\n\tif password == \"\" {\n\t\tlog.Fatal(errors.New(\"DOCKER_PASSWORD is empty\"))\n\t}\n\n\tlog.Infof(\"Login to Docker Hub as %s\", username)\n\terr := docker.Login(username, password)\n\n\tif err != nil {\n\t\tlog.Fatal(\"Login to Docker Hub failed\", err)\n\t}\n}\n\nfunc deploy(docker *Docker, tag string) {\n\timageWithTag := DockerImageName + \":\" + tag\n\n\tlog.Infof(\"Docker image %s will be deployed on Docker Hub\", imageWithTag)\n\n\tif err := docker.Tag(DockerImageName, imageWithTag); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif err := docker.Push(imageWithTag); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc deployManifest(docker *Docker, tag string, amd64tag string, arm32v7tag string, arm64v8tag string) {\n\tdockerImagePrefix := DockerImageName + \":\"\n\n\tlog.Infof(\"Docker manifest %s%s will be deployed on Docker Hub\", dockerImagePrefix, tag)\n\n\terr := docker.Manifest(dockerImagePrefix+tag, dockerImagePrefix+amd64tag, dockerImagePrefix+arm32v7tag, dockerImagePrefix+arm64v8tag)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ttags := []string{amd64tag, arm32v7tag, arm64v8tag}\n\tfor _, t := range tags {\n\t\tlog.Infof(\"Docker removing tag for %s%s on Docker Hub\", dockerImagePrefix, t)\n\n\t\tif err := docker.CleanTag(t); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\nfunc publishDockerImage(arch string) {\n\tdocker := &Docker{}\n\n\tif ciTag != \"\" {\n\t\tif len(tags) == 4 {\n\t\t\tlog.Infof(\"Detected tags: '%s' | '%s' | '%s'\", tags[1], tags[2], tags[3])\n\n\t\t\tlogin(docker)\n\t\t\tdeploy(docker, tags[1]+\"-\"+arch)\n\t\t\tif !ignoredSuffixes.MatchString(ciTag) {\n\t\t\t\tdeploy(docker, tags[2]+\"-\"+arch)\n\t\t\t\tdeploy(docker, tags[3]+\"-\"+arch)\n\t\t\t\tdeploy(docker, \"latest-\"+arch)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Fatal(\"Docker image will not be published, the specified tag does not conform to the standard\")\n\t\t}\n\t} else if ciBranch != \"master\" && !publicRepo.MatchString(ciBranch) {\n\t\tlogin(docker)\n\t\tdeploy(docker, ciBranch+\"-\"+arch)\n\t} else if ciBranch != \"master\" && publicRepo.MatchString(ciBranch) {\n\t\tlogin(docker)\n\t\tdeploy(docker, \"PR\"+ciPullRequest+\"-\"+arch)\n\t} else if ciBranch == \"master\" && ciPullRequest == \"false\" {\n\t\tlogin(docker)\n\t\tdeploy(docker, \"master-\"+arch)\n\t} else {\n\t\tlog.Info(\"Docker image will not be published\")\n\t}\n}\n\nfunc publishDockerManifest() {\n\tdocker := &Docker{}\n\n\tif ciTag != \"\" {\n\t\tif len(tags) == 4 {\n\t\t\tlog.Infof(\"Detected tags: '%s' | '%s' | '%s'\", tags[1], tags[2], tags[3])\n\n\t\t\tlogin(docker)\n\t\t\tdeployManifest(docker, tags[1], tags[1]+\"-amd64\", tags[1]+\"-arm32v7\", tags[1]+\"-arm64v8\")\n\t\t\tpublishDockerReadme(docker)\n\n\t\t\tif !ignoredSuffixes.MatchString(ciTag) {\n\t\t\t\tdeployManifest(docker, tags[2], tags[2]+\"-amd64\", tags[2]+\"-arm32v7\", tags[2]+\"-arm64v8\")\n\t\t\t\tdeployManifest(docker, tags[3], tags[3]+\"-amd64\", tags[3]+\"-arm32v7\", tags[3]+\"-arm64v8\")\n\t\t\t\tdeployManifest(docker, \"latest\", \"latest-amd64\", \"latest-arm32v7\", \"latest-arm64v8\")\n\t\t\t\tpublishDockerReadme(docker)\n\t\t\t\tupdateMicroBadger(docker)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Fatal(\"Docker manifest will not be published, the specified tag does not conform to the standard\")\n\t\t}\n\t} else if ciBranch != \"master\" && !publicRepo.MatchString(ciBranch) {\n\t\tlogin(docker)\n\t\tdeployManifest(docker, ciBranch, ciBranch+\"-amd64\", ciBranch+\"-arm32v7\", ciBranch+\"-arm64v8\")\n\t} else if ciBranch != \"master\" && publicRepo.MatchString(ciBranch) {\n\t\tlogin(docker)\n\t\tdeployManifest(docker, \"PR\"+ciPullRequest, \"PR\"+ciPullRequest+\"-amd64\", \"PR\"+ciPullRequest+\"-arm32v7\", \"PR\"+ciPullRequest+\"-arm64v8\")\n\t} else if ciBranch == \"master\" && ciPullRequest == \"false\" {\n\t\tlogin(docker)\n\t\tdeployManifest(docker, \"master\", \"master-amd64\", \"master-arm32v7\", \"master-arm64v8\")\n\t\tpublishDockerReadme(docker)\n\t} else {\n\t\tlog.Info(\"Docker manifest will not be published\")\n\t}\n}\n\nfunc publishDockerReadme(docker *Docker) {\n\tlog.Info(\"Docker pushing README.md to Docker Hub\")\n\n\tif err := docker.PublishReadme(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\nfunc updateMicroBadger(docker *Docker) {\n\tlog.Info(\"Updating MicroBadger metadata from Docker Hub\")\n\n\tif err := docker.UpdateMicroBadger(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package brain\n\nimport (\n    \"encoding\/json\"\n)\n\n\/\/ MigrationJobQueue is a list of disc IDs that are still to be migrated as\n\/\/ part of a migration job.\ntype MigrationJobQueue struct {\n\tDiscs []int `json:\"discs,omitempty\"`\n}\n\n\/\/ MigrationJobLocations represents source or target locations for a migration\n\/\/ job. Discs, pools and tails maybe represented by ID number, label or UUID.\ntype MigrationJobLocations struct {\n\tDiscs []json.Number `json:\"discs,omitempty\"`\n\tPools []json.Number `json:\"pools,omitempty\"`\n\tTails []json.Number `json:\"tails,omitempty\"`\n}\n\n\/\/ MigrationJobDestinations represents available desintations for a migration\n\/\/ job. Unlike MigrationJobLocations, these are represented using ID number\n\/\/ only.\ntype MigrationJobDestinations struct {\n\tPools []int `json:\"pools,omitempty\"`\n}\n\n\/\/ MigrationJobOptions represents options on a migration job.\ntype MigrationJobOptions struct {\n\tPriority int `json:\"priority,omitempty\"`\n}\n\n\/\/ MigrationJobDiscStatus represents the current status of a migration job.\n\/\/ Each entry is a list of disc IDs indicating the fate of discs that\n\/\/ have been removed from the queue.\ntype MigrationJobDiscStatus struct {\n\tDone      []int `json:\"done,omitempty\"`\n\tErrored   []int `json:\"errored,omitempty\"`\n\tCancelled []int `json:\"cancelled,omitempty\"`\n\tSkipped   []int `json:\"skipped,omitempty\"`\n}\n\n\/\/ MigrationJobStatus captures the status of a migration job, currently only\n\/\/ discs.\ntype MigrationJobStatus struct {\n\tDiscs MigrationJobDiscStatus `json:\"discs,omitempty\"`\n}\n\n\/\/ MigrationJobSpec is a specification of a migration job to be created\ntype MigrationJobSpec struct {\n\tOptions      MigrationJobOptions   `json:\"options,imotempty\"`\n\tSources      MigrationJobLocations `json:\"sources,omitempty\"`\n\tDestinations MigrationJobLocations `json:\"destinations,omitempty\"`\n}\n\n\/\/ MigrationJob is a representation of a migration job.\ntype MigrationJob struct {\n\tID           int                      `json:\"id,omitempty\"`\n\tArgs         MigrationJobSpec         `json:\"args,omitempty\"`\n\tQueue        MigrationJobQueue        `json:\"queue,omitempty\"`\n\tDestinations MigrationJobDestinations `json:\"destinations,omitempty\"`\n\tStatus       MigrationJobStatus       `json:\"status,omitempty\"`\n\tPriority     int                      `json:\"priority,omitempty\"`\n\tStartedAt    string                   `json:\"started_at,omitempty\"`\n\tFinishedAt   string                   `json:\"finished_at,omitempty\"`\n\tCreatedAt    string                   `json:\"created_at,omitempty\"`\n\tUpdatedAt    string                   `json:\"updated_at,omitempty\"`\n}\n<commit_msg>add new struct for updating migrations<commit_after>package brain\n\nimport (\n\t\"encoding\/json\"\n)\n\n\/\/MigrationJobModify represents the modifications possible on a migration job\ntype MigrationJobModification struct {\n\tCancel  MigrationJobLocations `json:\"cancel,omitempty\"`\n\tOptions MigrationJobOptions   `json:\"options,omitempty\"`\n}\n\n\/\/ MigrationJobQueue is a list of disc IDs that are still to be migrated as\n\/\/ part of a migration job.\ntype MigrationJobQueue struct {\n\tDiscs []int `json:\"discs,omitempty\"`\n}\n\n\/\/ MigrationJobLocations represents source or target locations for a migration\n\/\/ job. Discs, pools and tails maybe represented by ID number, label or UUID.\ntype MigrationJobLocations struct {\n\tDiscs []json.Number `json:\"discs,omitempty\"`\n\tPools []json.Number `json:\"pools,omitempty\"`\n\tTails []json.Number `json:\"tails,omitempty\"`\n}\n\n\/\/ MigrationJobDestinations represents available desintations for a migration\n\/\/ job. Unlike MigrationJobLocations, these are represented using ID number\n\/\/ only.\ntype MigrationJobDestinations struct {\n\tPools []int `json:\"pools,omitempty\"`\n}\n\n\/\/ MigrationJobOptions represents options on a migration job.\ntype MigrationJobOptions struct {\n\tPriority int `json:\"priority,omitempty\"`\n}\n\n\/\/ MigrationJobDiscStatus represents the current status of a migration job.\n\/\/ Each entry is a list of disc IDs indicating the fate of discs that\n\/\/ have been removed from the queue.\ntype MigrationJobDiscStatus struct {\n\tDone      []int `json:\"done,omitempty\"`\n\tErrored   []int `json:\"errored,omitempty\"`\n\tCancelled []int `json:\"cancelled,omitempty\"`\n\tSkipped   []int `json:\"skipped,omitempty\"`\n}\n\n\/\/ MigrationJobStatus captures the status of a migration job, currently only\n\/\/ discs.\ntype MigrationJobStatus struct {\n\tDiscs MigrationJobDiscStatus `json:\"discs,omitempty\"`\n}\n\n\/\/ MigrationJobSpec is a specification of a migration job to be created\ntype MigrationJobSpec struct {\n\tOptions      MigrationJobOptions   `json:\"options,imotempty\"`\n\tSources      MigrationJobLocations `json:\"sources,omitempty\"`\n\tDestinations MigrationJobLocations `json:\"destinations,omitempty\"`\n}\n\n\/\/ MigrationJob is a representation of a migration job.\ntype MigrationJob struct {\n\tID           int                      `json:\"id,omitempty\"`\n\tArgs         MigrationJobSpec         `json:\"args,omitempty\"`\n\tQueue        MigrationJobQueue        `json:\"queue,omitempty\"`\n\tDestinations MigrationJobDestinations `json:\"destinations,omitempty\"`\n\tStatus       MigrationJobStatus       `json:\"status,omitempty\"`\n\tPriority     int                      `json:\"priority,omitempty\"`\n\tStartedAt    string                   `json:\"started_at,omitempty\"`\n\tFinishedAt   string                   `json:\"finished_at,omitempty\"`\n\tCreatedAt    string                   `json:\"created_at,omitempty\"`\n\tUpdatedAt    string                   `json:\"updated_at,omitempty\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package v1\n\nimport (\n\t\"fmt\"\n\n\t\"git.zxq.co\/ripple\/ocl\"\n\t\"git.zxq.co\/ripple\/rippleapi\/common\"\n)\n\ntype leaderboardUser struct {\n\tuserData\n\tChosenMode    modeData `json:\"chosen_mode\"`\n\tPlayStyle     int      `json:\"play_style\"`\n\tFavouriteMode int      `json:\"favourite_mode\"`\n}\n\ntype leaderboardResponse struct {\n\tcommon.ResponseBase\n\tUsers []leaderboardUser `json:\"users\"`\n}\n\nconst lbUserQuery = `\nSELECT\n\tusers.id, users.username, users.register_datetime, users.privileges, users.latest_activity,\n\n\tusers_stats.username_aka, users_stats.country,\n\tusers_stats.play_style, users_stats.favourite_mode,\n\n\tusers_stats.ranked_score_%[1]s, users_stats.total_score_%[1]s, users_stats.playcount_%[1]s,\n\tusers_stats.replays_watched_%[1]s, users_stats.total_hits_%[1]s,\n\tusers_stats.avg_accuracy_%[1]s, users_stats.pp_%[1]s, leaderboard_%[1]s.position as %[1]s_position\nFROM leaderboard_%[1]s\nINNER JOIN users ON users.id = leaderboard_%[1]s.user\nINNER JOIN users_stats ON users_stats.id = leaderboard_%[1]s.user\n%[2]s`\n\n\/\/ LeaderboardGET gets the leaderboard.\nfunc LeaderboardGET(md common.MethodData) common.CodeMessager {\n\tm := getMode(md.Query(\"mode\"))\n\t\/\/ Admins may not want to see banned users on the leaderboard.\n\t\/\/ This is the default setting. In case they do, they have to activate see_everything.\n\tquery := fmt.Sprintf(lbUserQuery, m, `WHERE `+md.User.OnlyUserPublic(md.HasQuery(\"see_everything\"))+\n\t\t` ORDER BY leaderboard_`+m+`.position `+common.Paginate(md.Query(\"p\"), md.Query(\"l\"), 500))\n\trows, err := md.DB.Query(query)\n\tif err != nil {\n\t\tmd.Err(err)\n\t\treturn Err500\n\t}\n\tvar resp leaderboardResponse\n\tfor rows.Next() {\n\t\tvar u leaderboardUser\n\t\terr := rows.Scan(\n\t\t\t&u.ID, &u.Username, &u.RegisteredOn, &u.Privileges, &u.LatestActivity,\n\n\t\t\t&u.UsernameAKA, &u.Country, &u.PlayStyle, &u.FavouriteMode,\n\n\t\t\t&u.ChosenMode.RankedScore, &u.ChosenMode.TotalScore, &u.ChosenMode.PlayCount,\n\t\t\t&u.ChosenMode.ReplaysWatched, &u.ChosenMode.TotalHits,\n\t\t\t&u.ChosenMode.Accuracy, &u.ChosenMode.PP, &u.ChosenMode.GlobalLeaderboardRank,\n\t\t)\n\t\tif err != nil {\n\t\t\tmd.Err(err)\n\t\t\tcontinue\n\t\t}\n\t\tu.ChosenMode.Level = ocl.GetLevelPrecise(int64(u.ChosenMode.TotalScore))\n\t\tresp.Users = append(resp.Users, u)\n\t}\n\tresp.Code = 200\n\treturn resp\n}\n<commit_msg>Add ability to filter leaderboard by country (country ranking) (NOT ON WEBSITE RN)<commit_after>package v1\n\nimport (\n\t\"fmt\"\n\n\t\"git.zxq.co\/ripple\/ocl\"\n\t\"git.zxq.co\/ripple\/rippleapi\/common\"\n)\n\ntype leaderboardUser struct {\n\tuserData\n\tChosenMode    modeData `json:\"chosen_mode\"`\n\tPlayStyle     int      `json:\"play_style\"`\n\tFavouriteMode int      `json:\"favourite_mode\"`\n}\n\ntype leaderboardResponse struct {\n\tcommon.ResponseBase\n\tUsers []leaderboardUser `json:\"users\"`\n}\n\nconst lbUserQuery = `\nSELECT\n\tusers.id, users.username, users.register_datetime, users.privileges, users.latest_activity,\n\n\tusers_stats.username_aka, users_stats.country,\n\tusers_stats.play_style, users_stats.favourite_mode,\n\n\tusers_stats.ranked_score_%[1]s, users_stats.total_score_%[1]s, users_stats.playcount_%[1]s,\n\tusers_stats.replays_watched_%[1]s, users_stats.total_hits_%[1]s,\n\tusers_stats.avg_accuracy_%[1]s, users_stats.pp_%[1]s, leaderboard_%[1]s.position as %[1]s_position\nFROM leaderboard_%[1]s\nINNER JOIN users ON users.id = leaderboard_%[1]s.user\nINNER JOIN users_stats ON users_stats.id = leaderboard_%[1]s.user\n%[2]s`\n\n\/\/ LeaderboardGET gets the leaderboard.\nfunc LeaderboardGET(md common.MethodData) common.CodeMessager {\n\tm := getMode(md.Query(\"mode\"))\n\tw := &common.WhereClause{\n\t\tClause: \"WHERE \" + md.User.OnlyUserPublic(md.HasQuery(\"see_everything\")),\n\t}\n\tw.Where(\"users_stats.country = ?\", md.Query(\"country\"))\n\t\/\/ Admins may not want to see banned users on the leaderboard.\n\t\/\/ This is the default setting. In case they do, they have to activate see_everything.\n\tquery := fmt.Sprintf(lbUserQuery, m, w.Clause+\n\t\t` ORDER BY leaderboard_`+m+`.position `+common.Paginate(md.Query(\"p\"), md.Query(\"l\"), 500))\n\trows, err := md.DB.Query(query, w.Params...)\n\tif err != nil {\n\t\tmd.Err(err)\n\t\treturn Err500\n\t}\n\tvar resp leaderboardResponse\n\tfor rows.Next() {\n\t\tvar u leaderboardUser\n\t\terr := rows.Scan(\n\t\t\t&u.ID, &u.Username, &u.RegisteredOn, &u.Privileges, &u.LatestActivity,\n\n\t\t\t&u.UsernameAKA, &u.Country, &u.PlayStyle, &u.FavouriteMode,\n\n\t\t\t&u.ChosenMode.RankedScore, &u.ChosenMode.TotalScore, &u.ChosenMode.PlayCount,\n\t\t\t&u.ChosenMode.ReplaysWatched, &u.ChosenMode.TotalHits,\n\t\t\t&u.ChosenMode.Accuracy, &u.ChosenMode.PP, &u.ChosenMode.GlobalLeaderboardRank,\n\t\t)\n\t\tif err != nil {\n\t\t\tmd.Err(err)\n\t\t\tcontinue\n\t\t}\n\t\tu.ChosenMode.Level = ocl.GetLevelPrecise(int64(u.ChosenMode.TotalScore))\n\t\tresp.Users = append(resp.Users, u)\n\t}\n\tresp.Code = 200\n\treturn resp\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright GoFrame Author(https:\/\/goframe.org). All Rights Reserved.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the MIT License.\n\/\/ If a copy of the MIT was not distributed with this file,\n\/\/ You can obtain one at https:\/\/github.com\/gogf\/gf.\n\npackage gtime_test\n\nimport (\n\t\"github.com\/gogf\/gf\/frame\/g\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/gogf\/gf\/os\/gtime\"\n\t\"github.com\/gogf\/gf\/test\/gtest\"\n)\n\n\/\/ DATA RACE!\n\/\/time.Now()\n\/\/    \/home\/travis\/.gimme\/versions\/go1.11.13.linux.amd64\/src\/time\/time.go:1060 +0xcf\n\/\/time.sendTime()\n\/\/    \/home\/travis\/.gimme\/versions\/go1.11.13.linux.amd64\/src\/time\/sleep.go:141 +0x44\n\/\/func Test_SetTimeZone(t *testing.T) {\n\/\/\tgtest.C(t, func(t *gtest.T) {\n\/\/\t\tgtime.SetTimeZone(\"Asia\/Shanghai\")\n\/\/\t\tt.Assert(time.Local.String(), \"Asia\/Shanghai\")\n\/\/\t})\n\/\/}\n\nfunc Test_Nanosecond(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tnanos := gtime.TimestampNano()\n\t\ttimeTemp := time.Unix(0, nanos)\n\t\tt.Assert(nanos, timeTemp.UnixNano())\n\t})\n}\n\nfunc Test_Microsecond(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tmicros := gtime.TimestampMicro()\n\t\ttimeTemp := time.Unix(0, micros*1e3)\n\t\tt.Assert(micros, timeTemp.UnixNano()\/1e3)\n\t})\n}\n\nfunc Test_Millisecond(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tmillis := gtime.TimestampMilli()\n\t\ttimeTemp := time.Unix(0, millis*1e6)\n\t\tt.Assert(millis, timeTemp.UnixNano()\/1e6)\n\t})\n}\n\nfunc Test_Second(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\ts := gtime.Timestamp()\n\t\ttimeTemp := time.Unix(s, 0)\n\t\tt.Assert(s, timeTemp.Unix())\n\t})\n}\n\nfunc Test_Date(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tt.Assert(gtime.Date(), time.Now().Format(\"2006-01-02\"))\n\t})\n}\n\nfunc Test_Datetime(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tdatetime := gtime.Datetime()\n\t\ttimeTemp, err := gtime.StrToTime(datetime, \"Y-m-d H:i:s\")\n\t\tif err != nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\t\tt.Assert(datetime, timeTemp.Time.Format(\"2006-01-02 15:04:05\"))\n\t})\n}\n\nfunc Test_ISO8601(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tiso8601 := gtime.ISO8601()\n\t\tt.Assert(iso8601, gtime.Now().Format(\"c\"))\n\t})\n}\n\nfunc Test_RFC822(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\trfc822 := gtime.RFC822()\n\t\tt.Assert(rfc822, gtime.Now().Format(\"r\"))\n\t})\n}\n\nfunc Test_StrToTime(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\t\/\/ Correct datetime string.\n\t\tvar testDateTimes = []string{\n\t\t\t\"2006-01-02 15:04:05\",\n\t\t\t\"2006\/01\/02 15:04:05\",\n\t\t\t\"2006.01.02 15:04:05.000\",\n\t\t\t\"2006.01.02 - 15:04:05\",\n\t\t\t\"2006.01.02 15:04:05 +0800 CST\",\n\t\t\t\"2006-01-02T20:05:06+05:01:01\",\n\t\t\t\"2006-01-02T14:03:04Z01:01:01\",\n\t\t\t\"2006-01-02T15:04:05Z\",\n\t\t\t\"02-jan-2006 15:04:05\",\n\t\t\t\"02\/jan\/2006 15:04:05\",\n\t\t\t\"02.jan.2006 15:04:05\",\n\t\t\t\"02.jan.2006:15:04:05\",\n\t\t}\n\n\t\tfor _, item := range testDateTimes {\n\t\t\ttimeTemp, err := gtime.StrToTime(item)\n\t\t\tt.Assert(err, nil)\n\t\t\tt.Assert(timeTemp.Time.Format(\"2006-01-02 15:04:05\"), \"2006-01-02 15:04:05\")\n\t\t}\n\n\t\t\/\/ Correct date string,.\n\t\tvar testDates = []string{\n\t\t\t\"2006.01.02\",\n\t\t\t\"2006.01.02 00:00\",\n\t\t\t\"2006.01.02 00:00:00.000\",\n\t\t}\n\n\t\tfor _, item := range testDates {\n\t\t\ttimeTemp, err := gtime.StrToTime(item)\n\t\t\tt.Assert(err, nil)\n\t\t\tt.Assert(timeTemp.Time.Format(\"2006-01-02 15:04:05\"), \"2006-01-02 00:00:00\")\n\t\t}\n\n\t\t\/\/ Correct time string.\n\t\tvar testTimes = g.MapStrStr{\n\t\t\t\"16:12:01\":     \"15:04:05\",\n\t\t\t\"16:12:01.789\": \"15:04:05.000\",\n\t\t}\n\n\t\tfor k, v := range testTimes {\n\t\t\ttime1, err := gtime.StrToTime(k)\n\t\t\tt.Assert(err, nil)\n\t\t\ttime2, err := time.ParseInLocation(v, k, time.Local)\n\t\t\tt.Assert(err, nil)\n\t\t\tt.Assert(time1.Time, time2)\n\t\t}\n\n\t\t\/\/ formatToStdLayout\n\t\tvar testDateFormats = []string{\n\t\t\t\"Y-m-d H:i:s\",\n\t\t\t\"\\\\T\\\\i\\\\m\\\\e Y-m-d H:i:s\",\n\t\t\t\"Y-m-d H:i:s\\\\\",\n\t\t\t\"Y-m-j G:i:s.u\",\n\t\t\t\"Y-m-j G:i:su\",\n\t\t}\n\n\t\tvar testDateFormatsResult = []string{\n\t\t\t\"2007-01-02 15:04:05\",\n\t\t\t\"Time 2007-01-02 15:04:05\",\n\t\t\t\"2007-01-02 15:04:05\",\n\t\t\t\"2007-01-02 15:04:05.000\",\n\t\t\t\"2007-01-02 15:04:05.000\",\n\t\t}\n\n\t\tfor index, item := range testDateFormats {\n\t\t\ttimeTemp, err := gtime.StrToTime(testDateFormatsResult[index], item)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"test fail\")\n\t\t\t}\n\t\t\tt.Assert(timeTemp.Time.Format(\"2006-01-02 15:04:05.000\"), \"2007-01-02 15:04:05.000\")\n\t\t}\n\n\t\t\/\/ 异常日期列表\n\t\tvar testDatesFail = []string{\n\t\t\t\"2006.01\",\n\t\t\t\"06..02\",\n\t\t}\n\n\t\tfor _, item := range testDatesFail {\n\t\t\t_, err := gtime.StrToTime(item)\n\t\t\tif err == nil {\n\t\t\t\tt.Error(\"test fail\")\n\t\t\t}\n\t\t}\n\n\t\t\/\/test err\n\t\t_, err := gtime.StrToTime(\"2006-01-02 15:04:05\", \"aabbccdd\")\n\t\tif err == nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\t})\n}\n\nfunc Test_ConvertZone(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\t\/\/现行时间\n\t\tnowUTC := time.Now().UTC()\n\t\ttestZone := \"America\/Los_Angeles\"\n\n\t\t\/\/转换为洛杉矶时间\n\t\tt1, err := gtime.ConvertZone(nowUTC.Format(\"2006-01-02 15:04:05\"), testZone, \"\")\n\t\tif err != nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\n\t\t\/\/使用洛杉矶时区解析上面转换后的时间\n\t\tlaStr := t1.Time.Format(\"2006-01-02 15:04:05\")\n\t\tloc, err := time.LoadLocation(testZone)\n\t\tt2, err := time.ParseInLocation(\"2006-01-02 15:04:05\", laStr, loc)\n\n\t\t\/\/判断是否与现行时间匹配\n\t\tt.Assert(t2.UTC().Unix(), nowUTC.Unix())\n\n\t})\n\n\t\/\/test err\n\tgtest.C(t, func(t *gtest.T) {\n\t\t\/\/现行时间\n\t\tnowUTC := time.Now().UTC()\n\t\t\/\/t.Log(nowUTC.Unix())\n\t\ttestZone := \"errZone\"\n\n\t\t\/\/错误时间输入\n\t\t_, err := gtime.ConvertZone(nowUTC.Format(\"06..02 15:04:05\"), testZone, \"\")\n\t\tif err == nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\t\t\/\/错误时区输入\n\t\t_, err = gtime.ConvertZone(nowUTC.Format(\"2006-01-02 15:04:05\"), testZone, \"\")\n\t\tif err == nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\t\t\/\/错误时区输入\n\t\t_, err = gtime.ConvertZone(nowUTC.Format(\"2006-01-02 15:04:05\"), testZone, testZone)\n\t\tif err == nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\t})\n}\n\nfunc Test_ParseDuration(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\td, err := gtime.ParseDuration(\"1d\")\n\t\tt.Assert(err, nil)\n\t\tt.Assert(d.String(), \"24h0m0s\")\n\t})\n\tgtest.C(t, func(t *gtest.T) {\n\t\td, err := gtime.ParseDuration(\"1d2h3m\")\n\t\tt.Assert(err, nil)\n\t\tt.Assert(d.String(), \"26h3m0s\")\n\t})\n\tgtest.C(t, func(t *gtest.T) {\n\t\td, err := gtime.ParseDuration(\"-1d2h3m\")\n\t\tt.Assert(err, nil)\n\t\tt.Assert(d.String(), \"-26h3m0s\")\n\t})\n\tgtest.C(t, func(t *gtest.T) {\n\t\td, err := gtime.ParseDuration(\"3m\")\n\t\tt.Assert(err, nil)\n\t\tt.Assert(d.String(), \"3m0s\")\n\t})\n\t\/\/ error\n\tgtest.C(t, func(t *gtest.T) {\n\t\td, err := gtime.ParseDuration(\"-1dd2h3m\")\n\t\tt.AssertNE(err, nil)\n\t\tt.Assert(d.String(), \"0s\")\n\t})\n}\n\nfunc Test_ParseTimeFromContent(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\ttimeTemp := gtime.ParseTimeFromContent(\"我是中文2006-01-02 15:04:05我也是中文\", \"Y-m-d H:i:s\")\n\t\tt.Assert(timeTemp.Time.Format(\"2006-01-02 15:04:05\"), \"2006-01-02 15:04:05\")\n\n\t\ttimeTemp1 := gtime.ParseTimeFromContent(\"我是中文2006-01-02 15:04:05我也是中文\")\n\t\tt.Assert(timeTemp1.Time.Format(\"2006-01-02 15:04:05\"), \"2006-01-02 15:04:05\")\n\n\t\ttimeTemp2 := gtime.ParseTimeFromContent(\"我是中文02.jan.2006 15:04:05我也是中文\")\n\t\tt.Assert(timeTemp2.Time.Format(\"2006-01-02 15:04:05\"), \"2006-01-02 15:04:05\")\n\n\t\t\/\/test err\n\t\ttimeTempErr := gtime.ParseTimeFromContent(\"我是中文\", \"Y-m-d H:i:s\")\n\t\tif timeTempErr != nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\t})\n}\n\nfunc Test_FuncCost(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tgtime.FuncCost(func() {\n\n\t\t})\n\t})\n}\n<commit_msg>fix issue of data race in unit testing case for package gtime<commit_after>\/\/ Copyright GoFrame Author(https:\/\/goframe.org). All Rights Reserved.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the MIT License.\n\/\/ If a copy of the MIT was not distributed with this file,\n\/\/ You can obtain one at https:\/\/github.com\/gogf\/gf.\n\npackage gtime_test\n\nimport (\n\t\"github.com\/gogf\/gf\/frame\/g\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/gogf\/gf\/os\/gtime\"\n\t\"github.com\/gogf\/gf\/test\/gtest\"\n)\n\nfunc init() {\n\tgtime.SetTimeZone(\"Asia\/Shanghai\")\n}\nfunc Test_SetTimeZone(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tt.Assert(time.Local.String(), \"Asia\/Shanghai\")\n\t})\n}\n\nfunc Test_Nanosecond(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tnanos := gtime.TimestampNano()\n\t\ttimeTemp := time.Unix(0, nanos)\n\t\tt.Assert(nanos, timeTemp.UnixNano())\n\t})\n}\n\nfunc Test_Microsecond(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tmicros := gtime.TimestampMicro()\n\t\ttimeTemp := time.Unix(0, micros*1e3)\n\t\tt.Assert(micros, timeTemp.UnixNano()\/1e3)\n\t})\n}\n\nfunc Test_Millisecond(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tmillis := gtime.TimestampMilli()\n\t\ttimeTemp := time.Unix(0, millis*1e6)\n\t\tt.Assert(millis, timeTemp.UnixNano()\/1e6)\n\t})\n}\n\nfunc Test_Second(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\ts := gtime.Timestamp()\n\t\ttimeTemp := time.Unix(s, 0)\n\t\tt.Assert(s, timeTemp.Unix())\n\t})\n}\n\nfunc Test_Date(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tt.Assert(gtime.Date(), time.Now().Format(\"2006-01-02\"))\n\t})\n}\n\nfunc Test_Datetime(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tdatetime := gtime.Datetime()\n\t\ttimeTemp, err := gtime.StrToTime(datetime, \"Y-m-d H:i:s\")\n\t\tif err != nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\t\tt.Assert(datetime, timeTemp.Time.Format(\"2006-01-02 15:04:05\"))\n\t})\n}\n\nfunc Test_ISO8601(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tiso8601 := gtime.ISO8601()\n\t\tt.Assert(iso8601, gtime.Now().Format(\"c\"))\n\t})\n}\n\nfunc Test_RFC822(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\trfc822 := gtime.RFC822()\n\t\tt.Assert(rfc822, gtime.Now().Format(\"r\"))\n\t})\n}\n\nfunc Test_StrToTime(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\t\/\/ Correct datetime string.\n\t\tvar testDateTimes = []string{\n\t\t\t\"2006-01-02 15:04:05\",\n\t\t\t\"2006\/01\/02 15:04:05\",\n\t\t\t\"2006.01.02 15:04:05.000\",\n\t\t\t\"2006.01.02 - 15:04:05\",\n\t\t\t\"2006.01.02 15:04:05 +0800 CST\",\n\t\t\t\"2006-01-02T20:05:06+05:01:01\",\n\t\t\t\"2006-01-02T14:03:04Z01:01:01\",\n\t\t\t\"2006-01-02T15:04:05Z\",\n\t\t\t\"02-jan-2006 15:04:05\",\n\t\t\t\"02\/jan\/2006 15:04:05\",\n\t\t\t\"02.jan.2006 15:04:05\",\n\t\t\t\"02.jan.2006:15:04:05\",\n\t\t}\n\n\t\tfor _, item := range testDateTimes {\n\t\t\ttimeTemp, err := gtime.StrToTime(item)\n\t\t\tt.Assert(err, nil)\n\t\t\tt.Assert(timeTemp.Time.Format(\"2006-01-02 15:04:05\"), \"2006-01-02 15:04:05\")\n\t\t}\n\n\t\t\/\/ Correct date string,.\n\t\tvar testDates = []string{\n\t\t\t\"2006.01.02\",\n\t\t\t\"2006.01.02 00:00\",\n\t\t\t\"2006.01.02 00:00:00.000\",\n\t\t}\n\n\t\tfor _, item := range testDates {\n\t\t\ttimeTemp, err := gtime.StrToTime(item)\n\t\t\tt.Assert(err, nil)\n\t\t\tt.Assert(timeTemp.Time.Format(\"2006-01-02 15:04:05\"), \"2006-01-02 00:00:00\")\n\t\t}\n\n\t\t\/\/ Correct time string.\n\t\tvar testTimes = g.MapStrStr{\n\t\t\t\"16:12:01\":     \"15:04:05\",\n\t\t\t\"16:12:01.789\": \"15:04:05.000\",\n\t\t}\n\n\t\tfor k, v := range testTimes {\n\t\t\ttime1, err := gtime.StrToTime(k)\n\t\t\tt.Assert(err, nil)\n\t\t\ttime2, err := time.ParseInLocation(v, k, time.Local)\n\t\t\tt.Assert(err, nil)\n\t\t\tt.Assert(time1.Time, time2)\n\t\t}\n\n\t\t\/\/ formatToStdLayout\n\t\tvar testDateFormats = []string{\n\t\t\t\"Y-m-d H:i:s\",\n\t\t\t\"\\\\T\\\\i\\\\m\\\\e Y-m-d H:i:s\",\n\t\t\t\"Y-m-d H:i:s\\\\\",\n\t\t\t\"Y-m-j G:i:s.u\",\n\t\t\t\"Y-m-j G:i:su\",\n\t\t}\n\n\t\tvar testDateFormatsResult = []string{\n\t\t\t\"2007-01-02 15:04:05\",\n\t\t\t\"Time 2007-01-02 15:04:05\",\n\t\t\t\"2007-01-02 15:04:05\",\n\t\t\t\"2007-01-02 15:04:05.000\",\n\t\t\t\"2007-01-02 15:04:05.000\",\n\t\t}\n\n\t\tfor index, item := range testDateFormats {\n\t\t\ttimeTemp, err := gtime.StrToTime(testDateFormatsResult[index], item)\n\t\t\tif err != nil {\n\t\t\t\tt.Error(\"test fail\")\n\t\t\t}\n\t\t\tt.Assert(timeTemp.Time.Format(\"2006-01-02 15:04:05.000\"), \"2007-01-02 15:04:05.000\")\n\t\t}\n\n\t\t\/\/ 异常日期列表\n\t\tvar testDatesFail = []string{\n\t\t\t\"2006.01\",\n\t\t\t\"06..02\",\n\t\t}\n\n\t\tfor _, item := range testDatesFail {\n\t\t\t_, err := gtime.StrToTime(item)\n\t\t\tif err == nil {\n\t\t\t\tt.Error(\"test fail\")\n\t\t\t}\n\t\t}\n\n\t\t\/\/test err\n\t\t_, err := gtime.StrToTime(\"2006-01-02 15:04:05\", \"aabbccdd\")\n\t\tif err == nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\t})\n}\n\nfunc Test_ConvertZone(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\t\/\/现行时间\n\t\tnowUTC := time.Now().UTC()\n\t\ttestZone := \"America\/Los_Angeles\"\n\n\t\t\/\/转换为洛杉矶时间\n\t\tt1, err := gtime.ConvertZone(nowUTC.Format(\"2006-01-02 15:04:05\"), testZone, \"\")\n\t\tif err != nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\n\t\t\/\/使用洛杉矶时区解析上面转换后的时间\n\t\tlaStr := t1.Time.Format(\"2006-01-02 15:04:05\")\n\t\tloc, err := time.LoadLocation(testZone)\n\t\tt2, err := time.ParseInLocation(\"2006-01-02 15:04:05\", laStr, loc)\n\n\t\t\/\/判断是否与现行时间匹配\n\t\tt.Assert(t2.UTC().Unix(), nowUTC.Unix())\n\n\t})\n\n\t\/\/test err\n\tgtest.C(t, func(t *gtest.T) {\n\t\t\/\/现行时间\n\t\tnowUTC := time.Now().UTC()\n\t\t\/\/t.Log(nowUTC.Unix())\n\t\ttestZone := \"errZone\"\n\n\t\t\/\/错误时间输入\n\t\t_, err := gtime.ConvertZone(nowUTC.Format(\"06..02 15:04:05\"), testZone, \"\")\n\t\tif err == nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\t\t\/\/错误时区输入\n\t\t_, err = gtime.ConvertZone(nowUTC.Format(\"2006-01-02 15:04:05\"), testZone, \"\")\n\t\tif err == nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\t\t\/\/错误时区输入\n\t\t_, err = gtime.ConvertZone(nowUTC.Format(\"2006-01-02 15:04:05\"), testZone, testZone)\n\t\tif err == nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\t})\n}\n\nfunc Test_ParseDuration(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\td, err := gtime.ParseDuration(\"1d\")\n\t\tt.Assert(err, nil)\n\t\tt.Assert(d.String(), \"24h0m0s\")\n\t})\n\tgtest.C(t, func(t *gtest.T) {\n\t\td, err := gtime.ParseDuration(\"1d2h3m\")\n\t\tt.Assert(err, nil)\n\t\tt.Assert(d.String(), \"26h3m0s\")\n\t})\n\tgtest.C(t, func(t *gtest.T) {\n\t\td, err := gtime.ParseDuration(\"-1d2h3m\")\n\t\tt.Assert(err, nil)\n\t\tt.Assert(d.String(), \"-26h3m0s\")\n\t})\n\tgtest.C(t, func(t *gtest.T) {\n\t\td, err := gtime.ParseDuration(\"3m\")\n\t\tt.Assert(err, nil)\n\t\tt.Assert(d.String(), \"3m0s\")\n\t})\n\t\/\/ error\n\tgtest.C(t, func(t *gtest.T) {\n\t\td, err := gtime.ParseDuration(\"-1dd2h3m\")\n\t\tt.AssertNE(err, nil)\n\t\tt.Assert(d.String(), \"0s\")\n\t})\n}\n\nfunc Test_ParseTimeFromContent(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\ttimeTemp := gtime.ParseTimeFromContent(\"我是中文2006-01-02 15:04:05我也是中文\", \"Y-m-d H:i:s\")\n\t\tt.Assert(timeTemp.Time.Format(\"2006-01-02 15:04:05\"), \"2006-01-02 15:04:05\")\n\n\t\ttimeTemp1 := gtime.ParseTimeFromContent(\"我是中文2006-01-02 15:04:05我也是中文\")\n\t\tt.Assert(timeTemp1.Time.Format(\"2006-01-02 15:04:05\"), \"2006-01-02 15:04:05\")\n\n\t\ttimeTemp2 := gtime.ParseTimeFromContent(\"我是中文02.jan.2006 15:04:05我也是中文\")\n\t\tt.Assert(timeTemp2.Time.Format(\"2006-01-02 15:04:05\"), \"2006-01-02 15:04:05\")\n\n\t\t\/\/test err\n\t\ttimeTempErr := gtime.ParseTimeFromContent(\"我是中文\", \"Y-m-d H:i:s\")\n\t\tif timeTempErr != nil {\n\t\t\tt.Error(\"test fail\")\n\t\t}\n\t})\n}\n\nfunc Test_FuncCost(t *testing.T) {\n\tgtest.C(t, func(t *gtest.T) {\n\t\tgtime.FuncCost(func() {\n\n\t\t})\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Added the IHC parameters as optimizable, for real. Made the output dir contain final results as both plot and JSON. Made the x values not used (e.g. when running BM outputs) still get the correct default values.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ +build qemu\n\/\/ +build network\n\n\/\/ We only run these tests when network is activated, as the package can't run\n\/\/ in parallel with QEMU engine tests. It'll also be fully covered by QEMU\n\/\/ engine tests, so it's not like we strictly need to run this very often.\n\/\/ If running all tests use ^go test -p 1` to ensure that multiple packages\n\/\/ don't run in parallel.\n\npackage network\n\nimport (\n\t\"net\/http\"\n\t\"testing\"\n)\n\nfunc TestNetworkCreateDestroy(t *testing.T) {\n\tfor i := 0; i < 2; i++ {\n\t\tdebug(\" - Creating network pool\")\n\t\tp, err := NewPool(3)\n\t\tnilOrPanic(err, \"Failed to create pool\")\n\n\t\tn1, err := p.Network()\n\t\tnilOrPanic(err, \"Failed to get network\")\n\t\tn2, err := p.Network()\n\t\tnilOrPanic(err, \"Failed to get network\")\n\t\tn3, err := p.Network()\n\t\tnilOrPanic(err, \"Failed to get network\")\n\t\t_, err = p.Network()\n\t\tassert(err == ErrAllNetworksInUse, \"Expected ErrAllNetworksInUse\")\n\n\t\t\/\/ Let's make a request to metaDataIP and get a 400 error\n\t\treq, err := http.NewRequest(http.MethodGet, \"http:\/\/\"+metaDataIP, nil)\n\t\tnilOrPanic(err, \"Failed to create http request\")\n\t\tres, err := http.DefaultClient.Do(req)\n\t\tnilOrPanic(err, \"Failed to do http request\")\n\t\tassert(res.StatusCode == http.StatusForbidden, \"Expected forbidden\")\n\t\tres.Body.Close()\n\n\t\tn1.Release()\n\t\tn1, err = p.Network()\n\t\tnilOrPanic(err, \"Failed to get network\")\n\n\t\tn1.Release()\n\t\tn2.Release()\n\t\tn3.Release()\n\n\t\tdebug(\" - Destroying network pool\")\n\t\terr = p.Dispose()\n\t\tnilOrPanic(err, \"Failed to dispose networks.\")\n\n\t\tdebug(\" - Network pool destroyed\")\n\t}\n}\n<commit_msg>Fixing more tests following???<commit_after>\/\/ +build qemu\n\/\/ +build network\n\n\/\/ We only run these tests when network is activated, as the package can't run\n\/\/ in parallel with QEMU engine tests. It'll also be fully covered by QEMU\n\/\/ engine tests, so it's not like we strictly need to run this very often.\n\/\/ If running all tests use ^go test -p 1` to ensure that multiple packages\n\/\/ don't run in parallel.\n\npackage network\n\nimport (\n\t\"net\/http\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc TestNetworkCreateDestroy(t *testing.T) {\n\tfor i := 0; i < 2; i++ {\n\t\tdebug(\" - Creating network pool\")\n\t\tp, err := NewPool(3)\n\t\trequire.NoError(t, err, \"Failed to create pool\")\n\n\t\tn1, err := p.Network()\n\t\trequire.NoError(t, err, \"Failed to get network\")\n\t\tn2, err := p.Network()\n\t\trequire.NoError(t, err, \"Failed to get network\")\n\t\tn3, err := p.Network()\n\t\trequire.NoError(t, err, \"Failed to get network\")\n\t\t_, err = p.Network()\n\t\trequire.True(t, err == ErrAllNetworksInUse, \"Expected ErrAllNetworksInUse\")\n\n\t\t\/\/ Let's make a request to metaDataIP and get a 400 error\n\t\treq, err := http.NewRequest(http.MethodGet, \"http:\/\/\"+metaDataIP, nil)\n\t\trequire.NoError(t, err, \"Failed to create http request\")\n\t\tres, err := http.DefaultClient.Do(req)\n\t\trequire.NoError(t, err, \"Failed to do http request\")\n\t\trequire.True(t, res.StatusCode == http.StatusForbidden, \"Expected forbidden\")\n\t\tres.Body.Close()\n\n\t\tn1.Release()\n\t\tn1, err = p.Network()\n\t\trequire.NoError(t, err, \"Failed to get network\")\n\n\t\tn1.Release()\n\t\tn2.Release()\n\t\tn3.Release()\n\n\t\tdebug(\" - Destroying network pool\")\n\t\terr = p.Dispose()\n\t\trequire.NoError(t, err, \"Failed to dispose networks.\")\n\n\t\tdebug(\" - Network pool destroyed\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage net\n\nimport (\n\t\"os\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nvar listenMulticastUDPTests = []struct {\n\tnet   string\n\tgaddr *UDPAddr\n\tflags Flags\n\tipv6  bool\n}{\n\t\/\/ cf. RFC 4727: Experimental Values in IPv4, IPv6, ICMPv4, ICMPv6, UDP, and TCP Headers\n\t{\"udp\", &UDPAddr{IPv4(224, 0, 0, 254), 12345}, FlagUp | FlagLoopback, false},\n\t{\"udp4\", &UDPAddr{IPv4(224, 0, 0, 254), 12345}, FlagUp | FlagLoopback, false},\n\t{\"udp\", &UDPAddr{ParseIP(\"ff0e::114\"), 12345}, FlagUp | FlagLoopback, true},\n\t{\"udp6\", &UDPAddr{ParseIP(\"ff01::114\"), 12345}, FlagUp | FlagLoopback, true},\n\t{\"udp6\", &UDPAddr{ParseIP(\"ff02::114\"), 12345}, FlagUp | FlagLoopback, true},\n\t{\"udp6\", &UDPAddr{ParseIP(\"ff04::114\"), 12345}, FlagUp | FlagLoopback, true},\n\t{\"udp6\", &UDPAddr{ParseIP(\"ff05::114\"), 12345}, FlagUp | FlagLoopback, true},\n\t{\"udp6\", &UDPAddr{ParseIP(\"ff08::114\"), 12345}, FlagUp | FlagLoopback, true},\n\t{\"udp6\", &UDPAddr{ParseIP(\"ff0e::114\"), 12345}, FlagUp | FlagLoopback, true},\n}\n\nfunc TestListenMulticastUDP(t *testing.T) {\n\tswitch runtime.GOOS {\n\tcase \"netbsd\", \"openbsd\", \"plan9\", \"windows\":\n\t\treturn\n\tcase \"linux\":\n\t\tif runtime.GOARCH == \"arm\" {\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor _, tt := range listenMulticastUDPTests {\n\t\tif tt.ipv6 && (!supportsIPv6 || os.Getuid() != 0) {\n\t\t\tcontinue\n\t\t}\n\t\tift, err := Interfaces()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Interfaces failed: %v\", err)\n\t\t}\n\t\tvar ifi *Interface\n\t\tfor _, x := range ift {\n\t\t\tif x.Flags&tt.flags == tt.flags {\n\t\t\t\tifi = &x\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif ifi == nil {\n\t\t\tt.Logf(\"an appropriate multicast interface not found\")\n\t\t\treturn\n\t\t}\n\t\tc, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"ListenMulticastUDP failed: %v\", err)\n\t\t}\n\t\tdefer c.Close() \/\/ test to listen concurrently across multiple listeners\n\t\tif !tt.ipv6 {\n\t\t\ttestIPv4MulticastSocketOptions(t, c.fd, ifi)\n\t\t} else {\n\t\t\ttestIPv6MulticastSocketOptions(t, c.fd, ifi)\n\t\t}\n\t\tifmat, err := ifi.MulticastAddrs()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"MulticastAddrs failed: %v\", err)\n\t\t}\n\t\tvar found bool\n\t\tfor _, ifma := range ifmat {\n\t\t\tif ifma.(*IPAddr).IP.Equal(tt.gaddr.IP) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tt.Fatalf(\"%q not found in RIB\", tt.gaddr.String())\n\t\t}\n\t}\n}\n\nfunc TestSimpleListenMulticastUDP(t *testing.T) {\n\tswitch runtime.GOOS {\n\tcase \"plan9\":\n\t\treturn\n\t}\n\n\tfor _, tt := range listenMulticastUDPTests {\n\t\tif tt.ipv6 {\n\t\t\tcontinue\n\t\t}\n\t\ttt.flags = FlagUp | FlagMulticast\n\t\tift, err := Interfaces()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Interfaces failed: %v\", err)\n\t\t}\n\t\tvar ifi *Interface\n\t\tfor _, x := range ift {\n\t\t\tif x.Flags&tt.flags == tt.flags {\n\t\t\t\tifi = &x\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif ifi == nil {\n\t\t\tt.Logf(\"an appropriate multicast interface not found\")\n\t\t\treturn\n\t\t}\n\t\tc, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"ListenMulticastUDP failed: %v\", err)\n\t\t}\n\t\tc.Close()\n\t}\n}\n\nfunc testIPv4MulticastSocketOptions(t *testing.T, fd *netFD, ifi *Interface) {\n\tifmc, err := ipv4MulticastInterface(fd)\n\tif err != nil {\n\t\tt.Fatalf(\"ipv4MulticastInterface failed: %v\", err)\n\t}\n\tt.Logf(\"IPv4 multicast interface: %v\", ifmc)\n\terr = setIPv4MulticastInterface(fd, ifi)\n\tif err != nil {\n\t\tt.Fatalf(\"setIPv4MulticastInterface failed: %v\", err)\n\t}\n\n\tttl, err := ipv4MulticastTTL(fd)\n\tif err != nil {\n\t\tt.Fatalf(\"ipv4MulticastTTL failed: %v\", err)\n\t}\n\tt.Logf(\"IPv4 multicast TTL: %v\", ttl)\n\terr = setIPv4MulticastTTL(fd, 1)\n\tif err != nil {\n\t\tt.Fatalf(\"setIPv4MulticastTTL failed: %v\", err)\n\t}\n\n\tloop, err := ipv4MulticastLoopback(fd)\n\tif err != nil {\n\t\tt.Fatalf(\"ipv4MulticastLoopback failed: %v\", err)\n\t}\n\tt.Logf(\"IPv4 multicast loopback: %v\", loop)\n\terr = setIPv4MulticastLoopback(fd, false)\n\tif err != nil {\n\t\tt.Fatalf(\"setIPv4MulticastLoopback failed: %v\", err)\n\t}\n}\n\nfunc testIPv6MulticastSocketOptions(t *testing.T, fd *netFD, ifi *Interface) {\n\tifmc, err := ipv6MulticastInterface(fd)\n\tif err != nil {\n\t\tt.Fatalf(\"ipv6MulticastInterface failed: %v\", err)\n\t}\n\tt.Logf(\"IPv6 multicast interface: %v\", ifmc)\n\terr = setIPv6MulticastInterface(fd, ifi)\n\tif err != nil {\n\t\tt.Fatalf(\"setIPv6MulticastInterface failed: %v\", err)\n\t}\n\n\thoplim, err := ipv6MulticastHopLimit(fd)\n\tif err != nil {\n\t\tt.Fatalf(\"ipv6MulticastHopLimit failed: %v\", err)\n\t}\n\tt.Logf(\"IPv6 multicast hop limit: %v\", hoplim)\n\terr = setIPv6MulticastHopLimit(fd, 1)\n\tif err != nil {\n\t\tt.Fatalf(\"setIPv6MulticastHopLimit failed: %v\", err)\n\t}\n\n\tloop, err := ipv6MulticastLoopback(fd)\n\tif err != nil {\n\t\tt.Fatalf(\"ipv6MulticastLoopback failed: %v\", err)\n\t}\n\tt.Logf(\"IPv6 multicast loopback: %v\", loop)\n\terr = setIPv6MulticastLoopback(fd, false)\n\tif err != nil {\n\t\tt.Fatalf(\"setIPv6MulticastLoopback failed: %v\", err)\n\t}\n}\n<commit_msg>net: disable multicast test on Alpha GNU\/Linux<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage net\n\nimport (\n\t\"os\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nvar listenMulticastUDPTests = []struct {\n\tnet   string\n\tgaddr *UDPAddr\n\tflags Flags\n\tipv6  bool\n}{\n\t\/\/ cf. RFC 4727: Experimental Values in IPv4, IPv6, ICMPv4, ICMPv6, UDP, and TCP Headers\n\t{\"udp\", &UDPAddr{IPv4(224, 0, 0, 254), 12345}, FlagUp | FlagLoopback, false},\n\t{\"udp4\", &UDPAddr{IPv4(224, 0, 0, 254), 12345}, FlagUp | FlagLoopback, false},\n\t{\"udp\", &UDPAddr{ParseIP(\"ff0e::114\"), 12345}, FlagUp | FlagLoopback, true},\n\t{\"udp6\", &UDPAddr{ParseIP(\"ff01::114\"), 12345}, FlagUp | FlagLoopback, true},\n\t{\"udp6\", &UDPAddr{ParseIP(\"ff02::114\"), 12345}, FlagUp | FlagLoopback, true},\n\t{\"udp6\", &UDPAddr{ParseIP(\"ff04::114\"), 12345}, FlagUp | FlagLoopback, true},\n\t{\"udp6\", &UDPAddr{ParseIP(\"ff05::114\"), 12345}, FlagUp | FlagLoopback, true},\n\t{\"udp6\", &UDPAddr{ParseIP(\"ff08::114\"), 12345}, FlagUp | FlagLoopback, true},\n\t{\"udp6\", &UDPAddr{ParseIP(\"ff0e::114\"), 12345}, FlagUp | FlagLoopback, true},\n}\n\nfunc TestListenMulticastUDP(t *testing.T) {\n\tswitch runtime.GOOS {\n\tcase \"netbsd\", \"openbsd\", \"plan9\", \"windows\":\n\t\treturn\n\tcase \"linux\":\n\t\tif runtime.GOARCH == \"arm\" || runtime.GOARCH == \"alpha\" {\n\t\t\treturn\n\t\t}\n\t}\n\n\tfor _, tt := range listenMulticastUDPTests {\n\t\tif tt.ipv6 && (!supportsIPv6 || os.Getuid() != 0) {\n\t\t\tcontinue\n\t\t}\n\t\tift, err := Interfaces()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Interfaces failed: %v\", err)\n\t\t}\n\t\tvar ifi *Interface\n\t\tfor _, x := range ift {\n\t\t\tif x.Flags&tt.flags == tt.flags {\n\t\t\t\tifi = &x\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif ifi == nil {\n\t\t\tt.Logf(\"an appropriate multicast interface not found\")\n\t\t\treturn\n\t\t}\n\t\tc, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"ListenMulticastUDP failed: %v\", err)\n\t\t}\n\t\tdefer c.Close() \/\/ test to listen concurrently across multiple listeners\n\t\tif !tt.ipv6 {\n\t\t\ttestIPv4MulticastSocketOptions(t, c.fd, ifi)\n\t\t} else {\n\t\t\ttestIPv6MulticastSocketOptions(t, c.fd, ifi)\n\t\t}\n\t\tifmat, err := ifi.MulticastAddrs()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"MulticastAddrs failed: %v\", err)\n\t\t}\n\t\tvar found bool\n\t\tfor _, ifma := range ifmat {\n\t\t\tif ifma.(*IPAddr).IP.Equal(tt.gaddr.IP) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tt.Fatalf(\"%q not found in RIB\", tt.gaddr.String())\n\t\t}\n\t}\n}\n\nfunc TestSimpleListenMulticastUDP(t *testing.T) {\n\tswitch runtime.GOOS {\n\tcase \"plan9\":\n\t\treturn\n\t}\n\n\tfor _, tt := range listenMulticastUDPTests {\n\t\tif tt.ipv6 {\n\t\t\tcontinue\n\t\t}\n\t\ttt.flags = FlagUp | FlagMulticast\n\t\tift, err := Interfaces()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Interfaces failed: %v\", err)\n\t\t}\n\t\tvar ifi *Interface\n\t\tfor _, x := range ift {\n\t\t\tif x.Flags&tt.flags == tt.flags {\n\t\t\t\tifi = &x\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif ifi == nil {\n\t\t\tt.Logf(\"an appropriate multicast interface not found\")\n\t\t\treturn\n\t\t}\n\t\tc, err := ListenMulticastUDP(tt.net, ifi, tt.gaddr)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"ListenMulticastUDP failed: %v\", err)\n\t\t}\n\t\tc.Close()\n\t}\n}\n\nfunc testIPv4MulticastSocketOptions(t *testing.T, fd *netFD, ifi *Interface) {\n\tifmc, err := ipv4MulticastInterface(fd)\n\tif err != nil {\n\t\tt.Fatalf(\"ipv4MulticastInterface failed: %v\", err)\n\t}\n\tt.Logf(\"IPv4 multicast interface: %v\", ifmc)\n\terr = setIPv4MulticastInterface(fd, ifi)\n\tif err != nil {\n\t\tt.Fatalf(\"setIPv4MulticastInterface failed: %v\", err)\n\t}\n\n\tttl, err := ipv4MulticastTTL(fd)\n\tif err != nil {\n\t\tt.Fatalf(\"ipv4MulticastTTL failed: %v\", err)\n\t}\n\tt.Logf(\"IPv4 multicast TTL: %v\", ttl)\n\terr = setIPv4MulticastTTL(fd, 1)\n\tif err != nil {\n\t\tt.Fatalf(\"setIPv4MulticastTTL failed: %v\", err)\n\t}\n\n\tloop, err := ipv4MulticastLoopback(fd)\n\tif err != nil {\n\t\tt.Fatalf(\"ipv4MulticastLoopback failed: %v\", err)\n\t}\n\tt.Logf(\"IPv4 multicast loopback: %v\", loop)\n\terr = setIPv4MulticastLoopback(fd, false)\n\tif err != nil {\n\t\tt.Fatalf(\"setIPv4MulticastLoopback failed: %v\", err)\n\t}\n}\n\nfunc testIPv6MulticastSocketOptions(t *testing.T, fd *netFD, ifi *Interface) {\n\tifmc, err := ipv6MulticastInterface(fd)\n\tif err != nil {\n\t\tt.Fatalf(\"ipv6MulticastInterface failed: %v\", err)\n\t}\n\tt.Logf(\"IPv6 multicast interface: %v\", ifmc)\n\terr = setIPv6MulticastInterface(fd, ifi)\n\tif err != nil {\n\t\tt.Fatalf(\"setIPv6MulticastInterface failed: %v\", err)\n\t}\n\n\thoplim, err := ipv6MulticastHopLimit(fd)\n\tif err != nil {\n\t\tt.Fatalf(\"ipv6MulticastHopLimit failed: %v\", err)\n\t}\n\tt.Logf(\"IPv6 multicast hop limit: %v\", hoplim)\n\terr = setIPv6MulticastHopLimit(fd, 1)\n\tif err != nil {\n\t\tt.Fatalf(\"setIPv6MulticastHopLimit failed: %v\", err)\n\t}\n\n\tloop, err := ipv6MulticastLoopback(fd)\n\tif err != nil {\n\t\tt.Fatalf(\"ipv6MulticastLoopback failed: %v\", err)\n\t}\n\tt.Logf(\"IPv6 multicast loopback: %v\", loop)\n\terr = setIPv6MulticastLoopback(fd, false)\n\tif err != nil {\n\t\tt.Fatalf(\"setIPv6MulticastLoopback failed: %v\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"net\/http\"\n\t\"os\/exec\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/NetSys\/quilt\/api\"\n\t\"github.com\/NetSys\/quilt\/api\/client\/getter\"\n\t\"github.com\/NetSys\/quilt\/db\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\nfunc main() {\n\tclientGetter := getter.New()\n\n\tclnt, err := clientGetter.Client(api.DefaultSocket)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"FAILED, couldn't get quiltctl client\")\n\t}\n\tdefer clnt.Close()\n\n\tleader, err := clientGetter.LeaderClient(clnt)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"FAILED, couldn't get leader client\")\n\t}\n\n\tcontainers, err := leader.QueryContainers()\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"FAILED, couldn't query containers\")\n\t}\n\n\tmachines, err := clnt.QueryMachines()\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"FAILED, couldn't query machines\")\n\t}\n\n\tif logContainers(containers) && httpGetTest(machines, containers) {\n\t\tlog.Info(\"PASSED\")\n\t} else {\n\t\tlog.Info(\"FAILED\")\n\t}\n}\n\nfunc logContainers(containers []db.Container) bool {\n\tvar failed bool\n\tfor _, c := range containers {\n\t\tcmd := exec.Command(\"quilt\", \"logs\", strconv.Itoa(c.StitchID))\n\t\tout, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"Failed to log: %s\", c)\n\t\t\tfailed = true\n\t\t}\n\t\tlog.Infof(\"Container: %s\\n%s\\n\\n\", c, string(out))\n\t}\n\n\treturn !failed\n}\n\nfunc httpGetTest(machines []db.Machine, containers []db.Container) bool {\n\tlog.Info(\"HTTP Get Test\")\n\n\tminionIPMap := map[string]string{}\n\tfor _, m := range machines {\n\t\tminionIPMap[m.PrivateIP] = m.PublicIP\n\t}\n\n\tvar publicIPs []string\n\tfor _, c := range containers {\n\t\tif strings.Contains(c.Image, \"haproxy\") {\n\t\t\tip, ok := minionIPMap[c.Minion]\n\t\t\tif !ok {\n\t\t\t\tlog.WithField(\"container\", c).Fatal(\n\t\t\t\t\t\"FAILED, HAProxy with no public IP\")\n\t\t\t}\n\t\t\tpublicIPs = append(publicIPs, ip)\n\t\t}\n\t}\n\n\tlog.Info(\"Public IPs: \", publicIPs)\n\tif len(publicIPs) == 0 {\n\t\tlog.Fatal(\"FAILED, Found no public IPs\")\n\t}\n\n\tvar failed bool\n\tfor i := 0; i < 25; i++ {\n\t\tfor _, ip := range publicIPs {\n\t\t\tresp, err := http.Get(\"http:\/\/\" + ip)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).Error(\"HTTP Error\")\n\t\t\t\tfailed = true\n\t\t\t}\n\n\t\t\tif resp.StatusCode == 200 {\n\t\t\t\tlog.Info(resp)\n\t\t\t} else {\n\t\t\t\tlog.Error(resp)\n\t\t\t\tfailed = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn !failed\n}\n<commit_msg>tester: Fix a panic in the mean test<commit_after>package main\n\nimport (\n\t\"net\/http\"\n\t\"os\/exec\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/NetSys\/quilt\/api\"\n\t\"github.com\/NetSys\/quilt\/api\/client\/getter\"\n\t\"github.com\/NetSys\/quilt\/db\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n)\n\nfunc main() {\n\tclientGetter := getter.New()\n\n\tclnt, err := clientGetter.Client(api.DefaultSocket)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"FAILED, couldn't get quiltctl client\")\n\t}\n\tdefer clnt.Close()\n\n\tleader, err := clientGetter.LeaderClient(clnt)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"FAILED, couldn't get leader client\")\n\t}\n\n\tcontainers, err := leader.QueryContainers()\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"FAILED, couldn't query containers\")\n\t}\n\n\tmachines, err := clnt.QueryMachines()\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"FAILED, couldn't query machines\")\n\t}\n\n\tif logContainers(containers) && httpGetTest(machines, containers) {\n\t\tlog.Info(\"PASSED\")\n\t} else {\n\t\tlog.Info(\"FAILED\")\n\t}\n}\n\nfunc logContainers(containers []db.Container) bool {\n\tvar failed bool\n\tfor _, c := range containers {\n\t\tcmd := exec.Command(\"quilt\", \"logs\", strconv.Itoa(c.StitchID))\n\t\tout, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"Failed to log: %s\", c)\n\t\t\tfailed = true\n\t\t}\n\t\tlog.Infof(\"Container: %s\\n%s\\n\\n\", c, string(out))\n\t}\n\n\treturn !failed\n}\n\nfunc httpGetTest(machines []db.Machine, containers []db.Container) bool {\n\tlog.Info(\"HTTP Get Test\")\n\n\tminionIPMap := map[string]string{}\n\tfor _, m := range machines {\n\t\tminionIPMap[m.PrivateIP] = m.PublicIP\n\t}\n\n\tvar publicIPs []string\n\tfor _, c := range containers {\n\t\tif strings.Contains(c.Image, \"haproxy\") {\n\t\t\tip, ok := minionIPMap[c.Minion]\n\t\t\tif !ok {\n\t\t\t\tlog.WithField(\"container\", c).Fatal(\n\t\t\t\t\t\"FAILED, HAProxy with no public IP\")\n\t\t\t}\n\t\t\tpublicIPs = append(publicIPs, ip)\n\t\t}\n\t}\n\n\tlog.Info(\"Public IPs: \", publicIPs)\n\tif len(publicIPs) == 0 {\n\t\tlog.Fatal(\"FAILED, Found no public IPs\")\n\t}\n\n\tvar failed bool\n\tfor i := 0; i < 25; i++ {\n\t\tfor _, ip := range publicIPs {\n\t\t\tresp, err := http.Get(\"http:\/\/\" + ip)\n\t\t\tif err != nil {\n\t\t\t\tlog.WithError(err).Error(\"HTTP Error\")\n\t\t\t\tfailed = true\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif resp.StatusCode == 200 {\n\t\t\t\tlog.Info(resp)\n\t\t\t} else {\n\t\t\t\tlog.Error(resp)\n\t\t\t\tfailed = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn !failed\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build linux\n\npackage sysstat\n\nimport (\n\t\"bufio\"\n\t\"encoding\/csv\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/influxdata\/telegraf\"\n\t\"github.com\/influxdata\/telegraf\/plugins\/inputs\"\n)\n\nvar (\n\tfirstTimestamp time.Time\n\texecCommand    = exec.Command \/\/ execCommand is used to mock commands in tests.\n\tdfltActivities = []string{\"DISK\"}\n)\n\nconst parseInterval = 1 \/\/ parseInterval is the interval (in seconds) where the parsing of the binary file takes place.\n\ntype Sysstat struct {\n\t\/\/ Sadc represents the path to the sadc collector utility.\n\tSadc string `toml:\"sadc_path\"`\n\n\t\/\/ Sadf represents the path to the sadf cmd.\n\tSadf string `toml:\"sadf_path\"`\n\n\t\/\/ Activities is a list of activities that are passed as argument to the\n\t\/\/ collector utility (e.g: DISK, SNMP etc...)\n\t\/\/ The more activities that are added, the more data is collected.\n\tActivities []string\n\n\t\/\/ Options is a map of options.\n\t\/\/\n\t\/\/ The key represents the actual option that the Sadf command is called with and\n\t\/\/ the value represents the description for that option.\n\t\/\/\n\t\/\/ For example, if you have the following options map:\n\t\/\/    map[string]string{\"-C\": \"cpu\", \"-d\": \"disk\"}\n\t\/\/ The Sadf command is run with the options -C and -d to extract cpu and\n\t\/\/ disk metrics from the collected binary file.\n\t\/\/\n\t\/\/ If Group is false (see below), each metric will be prefixed with the corresponding description\n\t\/\/ and represents itself a measurement.\n\t\/\/\n\t\/\/ If Group is true, metrics are grouped to a single measurement with the corresponding description as name.\n\tOptions map[string]string\n\n\t\/\/ Group determines if metrics are grouped or not.\n\tGroup bool\n\n\t\/\/ DeviceTags adds the possibility to add additional tags for devices.\n\tDeviceTags map[string][]map[string]string `toml:\"device_tags\"`\n\ttmpFile    string\n\tinterval   int\n}\n\nfunc (*Sysstat) Description() string {\n\treturn \"Sysstat metrics collector\"\n}\n\nvar sampleConfig = `\n  ## Path to the sadc command.\n  #\n  ## On Debian and Arch Linux the default path is \/usr\/lib\/sa\/sadc whereas\n  ## on RHEL and CentOS the default path is \/usr\/lib64\/sa\/sadc\n  sadc_path = \"\/usr\/lib\/sa\/sadc\" # required\n  #\n  #\n  ## Path to the sadf command, if it is not in PATH\n  # sadf_path = \"\/usr\/bin\/sadf\"\n  #\n  #\n  ## Activities is a list of activities, that are passed as argument to the\n  ## sadc collector utility (e.g: DISK, SNMP etc...)\n  ## The more activities that are added, the more data is collected.\n  # activities = [\"DISK\"]\n  #\n  #\n  ## Group metrics to measurements.\n  ##\n  ## If group is false each metric will be prefixed with a description\n  ## and represents itself a measurement.\n  ##\n  ## If Group is true, corresponding metrics are grouped to a single measurement.\n  # group = false\n  #\n  #\n  ## Options for the sadf command. The values on the left represent the sadf options and\n  ## the values on the right their description (wich are used for grouping and prefixing metrics).\n  [inputs.sysstat.options]\n\t-C = \"cpu\"\n\t-B = \"paging\"\n\t-b = \"io\"\n\t-d = \"disk\"             # requires DISK activity\n\t-H = \"hugepages\"\n\t\"-n ALL\" = \"network\"\n\t\"-P ALL\" = \"per_cpu\"\n\t-q = \"queue\"\n\t-R = \"mem\"\n\t\"-r ALL\" = \"mem_util\"\n\t-S = \"swap_util\"\n\t-u = \"cpu_util\"\n\t-v = \"inode\"\n\t-W = \"swap\"\n\t-w = \"task\"\n  #\t\"-I ALL\" = \"interrupts\" # requires INT activity\n  #\n  #\n  ## Device tags can be used to add additional tags for devices. For example the configuration below\n  ## adds a tag vg with value rootvg for all metrics with sda devices.\n  # [[inputs.sysstat.device_tags.sda]]\n  #  vg = \"rootvg\"\n`\n\nfunc (*Sysstat) SampleConfig() string {\n\treturn sampleConfig\n}\n\nfunc (s *Sysstat) Gather(acc telegraf.Accumulator) error {\n\tif s.interval == 0 {\n\t\tif firstTimestamp.IsZero() {\n\t\t\tfirstTimestamp = time.Now()\n\t\t} else {\n\t\t\ts.interval = int(time.Since(firstTimestamp).Seconds())\n\t\t}\n\t}\n\tts := time.Now().Add(time.Duration(s.interval) * time.Second)\n\tif err := s.collect(); err != nil {\n\t\treturn err\n\t}\n\tvar wg sync.WaitGroup\n\terrorChannel := make(chan error, len(s.Options)*2)\n\tfor option := range s.Options {\n\t\twg.Add(1)\n\t\tgo func(acc telegraf.Accumulator, option string) {\n\t\t\tdefer wg.Done()\n\t\t\tif err := s.parse(acc, option, ts); err != nil {\n\t\t\t\terrorChannel <- err\n\t\t\t}\n\t\t}(acc, option)\n\t}\n\twg.Wait()\n\tclose(errorChannel)\n\n\terrorStrings := []string{}\n\tfor err := range errorChannel {\n\t\terrorStrings = append(errorStrings, err.Error())\n\t}\n\n\tif _, err := os.Stat(s.tmpFile); err == nil {\n\t\tif err := os.Remove(s.tmpFile); err != nil {\n\t\t\terrorStrings = append(errorStrings, err.Error())\n\t\t}\n\t}\n\n\tif len(errorStrings) == 0 {\n\t\treturn nil\n\t}\n\treturn errors.New(strings.Join(errorStrings, \"\\n\"))\n}\n\n\/\/ collect collects sysstat data with the collector utility sadc. It runs the following command:\n\/\/     Sadc -S <Activity1> -S <Activity2> ... <collectInterval> 2 tmpFile\n\/\/ The above command collects system metrics during <collectInterval> and saves it in binary form to tmpFile.\nfunc (s *Sysstat) collect() error {\n\tif len(s.Activities) == 0 {\n\t\ts.Activities = dfltActivities\n\t}\n\tif len(s.Sadf) == 0 {\n\t\tsadf, err := exec.LookPath(\"sadf\")\n\t\tif err != nil {\n\t\t\treturn errors.New(\"sadf not in $PATH, configure path to sadf\")\n\t\t}\n\t\ts.Sadf = sadf\n\t}\n\toptions := []string{}\n\tfor _, act := range s.Activities {\n\t\toptions = append(options, \"-S\", act)\n\t}\n\ts.tmpFile = path.Join(\"\/tmp\", fmt.Sprintf(\"sysstat-%d\", time.Now().Unix()))\n\tcollectInterval := s.interval - parseInterval \/\/ collectInterval has to be smaller than the telegraf data collection interval\n\n\tif collectInterval < 0 { \/\/ If true, interval is not defined yet and Gather is run for the first time.\n\t\tcollectInterval = 1 \/\/ In that case we only collect for 1 second.\n\t}\n\n\toptions = append(options, strconv.Itoa(collectInterval), \"2\", s.tmpFile)\n\tcmd := execCommand(s.Sadc, options...)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to run command %s: %s\", strings.Join(cmd.Args, \" \"), string(out))\n\t}\n\treturn nil\n}\n\n\/\/ parse runs Sadf on the previously saved tmpFile:\n\/\/    Sadf -p -- -p <option> tmpFile\n\/\/ and parses the output to add it to the telegraf.Accumulator acc.\nfunc (s *Sysstat) parse(acc telegraf.Accumulator, option string, ts time.Time) error {\n\tcmd := execCommand(s.Sadf, s.sadfOptions(option)...)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := cmd.Start(); err != nil {\n\t\treturn fmt.Errorf(\"running command '%s' failed: %s\", strings.Join(cmd.Args, \" \"), err)\n\t}\n\n\tr := bufio.NewReader(stdout)\n\tcsv := csv.NewReader(r)\n\tcsv.Comma = '\\t'\n\tcsv.FieldsPerRecord = 6\n\tvar measurement string\n\t\/\/ groupData to accumulate data when Group=true\n\ttype groupData struct {\n\t\ttags   map[string]string\n\t\tfields map[string]interface{}\n\t}\n\tm := make(map[string]groupData)\n\tfor {\n\t\trecord, err := csv.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdevice := record[3]\n\t\tvalue, err := strconv.ParseFloat(record[5], 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttags := map[string]string{}\n\t\tif device != \"-\" {\n\t\t\ttags[\"device\"] = device\n\t\t\tif addTags, ok := s.DeviceTags[device]; ok {\n\t\t\t\tfor _, tag := range addTags {\n\t\t\t\t\tfor k, v := range tag {\n\t\t\t\t\t\ttags[k] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\tif s.Group {\n\t\t\tmeasurement = s.Options[option]\n\t\t\tif _, ok := m[device]; !ok {\n\t\t\t\tm[device] = groupData{\n\t\t\t\t\tfields: make(map[string]interface{}),\n\t\t\t\t\ttags:   make(map[string]string),\n\t\t\t\t}\n\t\t\t}\n\t\t\tg, _ := m[device]\n\t\t\tif len(g.tags) == 0 {\n\t\t\t\tfor k, v := range tags {\n\t\t\t\t\tg.tags[k] = v\n\t\t\t\t}\n\t\t\t}\n\t\t\tg.fields[escape(record[4])] = value\n\t\t} else {\n\t\t\tmeasurement = s.Options[option] + \"_\" + escape(record[4])\n\t\t\tfields := map[string]interface{}{\n\t\t\t\t\"value\": value,\n\t\t\t}\n\t\t\tacc.AddFields(measurement, fields, tags, ts)\n\t\t}\n\n\t}\n\tif s.Group {\n\t\tfor _, v := range m {\n\t\t\tacc.AddFields(measurement, v.fields, v.tags, ts)\n\t\t}\n\t}\n\tif err := cmd.Wait(); err != nil {\n\t\treturn fmt.Errorf(\"command %s failed with %s\", strings.Join(cmd.Args, \" \"), err)\n\t}\n\treturn nil\n}\n\n\/\/ sadfOptions creates the correct options for the sadf utility.\nfunc (s *Sysstat) sadfOptions(activityOption string) []string {\n\toptions := []string{\n\t\t\"-p\",\n\t\t\"--\",\n\t\t\"-p\",\n\t}\n\n\topts := strings.Split(activityOption, \" \")\n\toptions = append(options, opts...)\n\toptions = append(options, s.tmpFile)\n\n\treturn options\n}\n\n\/\/ escape removes % and \/ chars in field names\nfunc escape(dirty string) string {\n\tvar fieldEscaper = strings.NewReplacer(\n\t\t`%`, \"pct_\",\n\t\t`\/`, \"_per_\",\n\t)\n\treturn fieldEscaper.Replace(dirty)\n}\n\nfunc init() {\n\tinputs.Add(\"sysstat\", func() telegraf.Input {\n\t\treturn &Sysstat{}\n\t})\n}\n<commit_msg>change group=true by default<commit_after>\/\/ +build linux\n\npackage sysstat\n\nimport (\n\t\"bufio\"\n\t\"encoding\/csv\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/influxdata\/telegraf\"\n\t\"github.com\/influxdata\/telegraf\/plugins\/inputs\"\n)\n\nvar (\n\tfirstTimestamp time.Time\n\texecCommand    = exec.Command \/\/ execCommand is used to mock commands in tests.\n\tdfltActivities = []string{\"DISK\"}\n)\n\nconst parseInterval = 1 \/\/ parseInterval is the interval (in seconds) where the parsing of the binary file takes place.\n\ntype Sysstat struct {\n\t\/\/ Sadc represents the path to the sadc collector utility.\n\tSadc string `toml:\"sadc_path\"`\n\n\t\/\/ Sadf represents the path to the sadf cmd.\n\tSadf string `toml:\"sadf_path\"`\n\n\t\/\/ Activities is a list of activities that are passed as argument to the\n\t\/\/ collector utility (e.g: DISK, SNMP etc...)\n\t\/\/ The more activities that are added, the more data is collected.\n\tActivities []string\n\n\t\/\/ Options is a map of options.\n\t\/\/\n\t\/\/ The key represents the actual option that the Sadf command is called with and\n\t\/\/ the value represents the description for that option.\n\t\/\/\n\t\/\/ For example, if you have the following options map:\n\t\/\/    map[string]string{\"-C\": \"cpu\", \"-d\": \"disk\"}\n\t\/\/ The Sadf command is run with the options -C and -d to extract cpu and\n\t\/\/ disk metrics from the collected binary file.\n\t\/\/\n\t\/\/ If Group is false (see below), each metric will be prefixed with the corresponding description\n\t\/\/ and represents itself a measurement.\n\t\/\/\n\t\/\/ If Group is true, metrics are grouped to a single measurement with the corresponding description as name.\n\tOptions map[string]string\n\n\t\/\/ Group determines if metrics are grouped or not.\n\tGroup bool\n\n\t\/\/ DeviceTags adds the possibility to add additional tags for devices.\n\tDeviceTags map[string][]map[string]string `toml:\"device_tags\"`\n\ttmpFile    string\n\tinterval   int\n}\n\nfunc (*Sysstat) Description() string {\n\treturn \"Sysstat metrics collector\"\n}\n\nvar sampleConfig = `\n  ## Path to the sadc command.\n  #\n  ## On Debian and Arch Linux the default path is \/usr\/lib\/sa\/sadc whereas\n  ## on RHEL and CentOS the default path is \/usr\/lib64\/sa\/sadc\n  sadc_path = \"\/usr\/lib\/sa\/sadc\" # required\n  #\n  #\n  ## Path to the sadf command, if it is not in PATH\n  # sadf_path = \"\/usr\/bin\/sadf\"\n  #\n  #\n  ## Activities is a list of activities, that are passed as argument to the\n  ## sadc collector utility (e.g: DISK, SNMP etc...)\n  ## The more activities that are added, the more data is collected.\n  # activities = [\"DISK\"]\n  #\n  #\n  ## Group metrics to measurements.\n  ##\n  ## If group is false each metric will be prefixed with a description\n  ## and represents itself a measurement.\n  ##\n  ## If Group is true, corresponding metrics are grouped to a single measurement.\n  # group = false\n  #\n  #\n  ## Options for the sadf command. The values on the left represent the sadf options and\n  ## the values on the right their description (wich are used for grouping and prefixing metrics).\n  [inputs.sysstat.options]\n\t-C = \"cpu\"\n\t-B = \"paging\"\n\t-b = \"io\"\n\t-d = \"disk\"             # requires DISK activity\n\t-H = \"hugepages\"\n\t\"-n ALL\" = \"network\"\n\t\"-P ALL\" = \"per_cpu\"\n\t-q = \"queue\"\n\t-R = \"mem\"\n\t\"-r ALL\" = \"mem_util\"\n\t-S = \"swap_util\"\n\t-u = \"cpu_util\"\n\t-v = \"inode\"\n\t-W = \"swap\"\n\t-w = \"task\"\n  #\t\"-I ALL\" = \"interrupts\" # requires INT activity\n  #\n  #\n  ## Device tags can be used to add additional tags for devices. For example the configuration below\n  ## adds a tag vg with value rootvg for all metrics with sda devices.\n  # [[inputs.sysstat.device_tags.sda]]\n  #  vg = \"rootvg\"\n`\n\nfunc (*Sysstat) SampleConfig() string {\n\treturn sampleConfig\n}\n\nfunc (s *Sysstat) Gather(acc telegraf.Accumulator) error {\n\tif s.interval == 0 {\n\t\tif firstTimestamp.IsZero() {\n\t\t\tfirstTimestamp = time.Now()\n\t\t} else {\n\t\t\ts.interval = int(time.Since(firstTimestamp).Seconds())\n\t\t}\n\t}\n\tts := time.Now().Add(time.Duration(s.interval) * time.Second)\n\tif err := s.collect(); err != nil {\n\t\treturn err\n\t}\n\tvar wg sync.WaitGroup\n\terrorChannel := make(chan error, len(s.Options)*2)\n\tfor option := range s.Options {\n\t\twg.Add(1)\n\t\tgo func(acc telegraf.Accumulator, option string) {\n\t\t\tdefer wg.Done()\n\t\t\tif err := s.parse(acc, option, ts); err != nil {\n\t\t\t\terrorChannel <- err\n\t\t\t}\n\t\t}(acc, option)\n\t}\n\twg.Wait()\n\tclose(errorChannel)\n\n\terrorStrings := []string{}\n\tfor err := range errorChannel {\n\t\terrorStrings = append(errorStrings, err.Error())\n\t}\n\n\tif _, err := os.Stat(s.tmpFile); err == nil {\n\t\tif err := os.Remove(s.tmpFile); err != nil {\n\t\t\terrorStrings = append(errorStrings, err.Error())\n\t\t}\n\t}\n\n\tif len(errorStrings) == 0 {\n\t\treturn nil\n\t}\n\treturn errors.New(strings.Join(errorStrings, \"\\n\"))\n}\n\n\/\/ collect collects sysstat data with the collector utility sadc. It runs the following command:\n\/\/     Sadc -S <Activity1> -S <Activity2> ... <collectInterval> 2 tmpFile\n\/\/ The above command collects system metrics during <collectInterval> and saves it in binary form to tmpFile.\nfunc (s *Sysstat) collect() error {\n\tif len(s.Activities) == 0 {\n\t\ts.Activities = dfltActivities\n\t}\n\tif len(s.Sadf) == 0 {\n\t\tsadf, err := exec.LookPath(\"sadf\")\n\t\tif err != nil {\n\t\t\treturn errors.New(\"sadf not in $PATH, configure path to sadf\")\n\t\t}\n\t\ts.Sadf = sadf\n\t}\n\toptions := []string{}\n\tfor _, act := range s.Activities {\n\t\toptions = append(options, \"-S\", act)\n\t}\n\ts.tmpFile = path.Join(\"\/tmp\", fmt.Sprintf(\"sysstat-%d\", time.Now().Unix()))\n\tcollectInterval := s.interval - parseInterval \/\/ collectInterval has to be smaller than the telegraf data collection interval\n\n\tif collectInterval < 0 { \/\/ If true, interval is not defined yet and Gather is run for the first time.\n\t\tcollectInterval = 1 \/\/ In that case we only collect for 1 second.\n\t}\n\n\toptions = append(options, strconv.Itoa(collectInterval), \"2\", s.tmpFile)\n\tcmd := execCommand(s.Sadc, options...)\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to run command %s: %s\", strings.Join(cmd.Args, \" \"), string(out))\n\t}\n\treturn nil\n}\n\n\/\/ parse runs Sadf on the previously saved tmpFile:\n\/\/    Sadf -p -- -p <option> tmpFile\n\/\/ and parses the output to add it to the telegraf.Accumulator acc.\nfunc (s *Sysstat) parse(acc telegraf.Accumulator, option string, ts time.Time) error {\n\tcmd := execCommand(s.Sadf, s.sadfOptions(option)...)\n\tstdout, err := cmd.StdoutPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := cmd.Start(); err != nil {\n\t\treturn fmt.Errorf(\"running command '%s' failed: %s\", strings.Join(cmd.Args, \" \"), err)\n\t}\n\n\tr := bufio.NewReader(stdout)\n\tcsv := csv.NewReader(r)\n\tcsv.Comma = '\\t'\n\tcsv.FieldsPerRecord = 6\n\tvar measurement string\n\t\/\/ groupData to accumulate data when Group=true\n\ttype groupData struct {\n\t\ttags   map[string]string\n\t\tfields map[string]interface{}\n\t}\n\tm := make(map[string]groupData)\n\tfor {\n\t\trecord, err := csv.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tdevice := record[3]\n\t\tvalue, err := strconv.ParseFloat(record[5], 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttags := map[string]string{}\n\t\tif device != \"-\" {\n\t\t\ttags[\"device\"] = device\n\t\t\tif addTags, ok := s.DeviceTags[device]; ok {\n\t\t\t\tfor _, tag := range addTags {\n\t\t\t\t\tfor k, v := range tag {\n\t\t\t\t\t\ttags[k] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\tif s.Group {\n\t\t\tmeasurement = s.Options[option]\n\t\t\tif _, ok := m[device]; !ok {\n\t\t\t\tm[device] = groupData{\n\t\t\t\t\tfields: make(map[string]interface{}),\n\t\t\t\t\ttags:   make(map[string]string),\n\t\t\t\t}\n\t\t\t}\n\t\t\tg, _ := m[device]\n\t\t\tif len(g.tags) == 0 {\n\t\t\t\tfor k, v := range tags {\n\t\t\t\t\tg.tags[k] = v\n\t\t\t\t}\n\t\t\t}\n\t\t\tg.fields[escape(record[4])] = value\n\t\t} else {\n\t\t\tmeasurement = s.Options[option] + \"_\" + escape(record[4])\n\t\t\tfields := map[string]interface{}{\n\t\t\t\t\"value\": value,\n\t\t\t}\n\t\t\tacc.AddFields(measurement, fields, tags, ts)\n\t\t}\n\n\t}\n\tif s.Group {\n\t\tfor _, v := range m {\n\t\t\tacc.AddFields(measurement, v.fields, v.tags, ts)\n\t\t}\n\t}\n\tif err := cmd.Wait(); err != nil {\n\t\treturn fmt.Errorf(\"command %s failed with %s\", strings.Join(cmd.Args, \" \"), err)\n\t}\n\treturn nil\n}\n\n\/\/ sadfOptions creates the correct options for the sadf utility.\nfunc (s *Sysstat) sadfOptions(activityOption string) []string {\n\toptions := []string{\n\t\t\"-p\",\n\t\t\"--\",\n\t\t\"-p\",\n\t}\n\n\topts := strings.Split(activityOption, \" \")\n\toptions = append(options, opts...)\n\toptions = append(options, s.tmpFile)\n\n\treturn options\n}\n\n\/\/ escape removes % and \/ chars in field names\nfunc escape(dirty string) string {\n\tvar fieldEscaper = strings.NewReplacer(\n\t\t`%`, \"pct_\",\n\t\t`\/`, \"_per_\",\n\t)\n\treturn fieldEscaper.Replace(dirty)\n}\n\nfunc init() {\n\tinputs.Add(\"sysstat\", func() telegraf.Input {\n\t\treturn &Sysstat{\n\t\t\tGroup: true,\n\t\t}\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ package blockstore implements a thin wrapper over a datastore, giving a\n\/\/ clean interface for Getting and Putting block objects.\npackage blockstore\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\n\tblocks \"github.com\/ipfs\/go-ipfs\/blocks\"\n\tdshelp \"github.com\/ipfs\/go-ipfs\/thirdparty\/ds-help\"\n\n\tds \"gx\/ipfs\/QmRWDav6mzWseLWeYfVd5fvUKiVe9xNH29YfMF438fG364\/go-datastore\"\n\tdsns \"gx\/ipfs\/QmRWDav6mzWseLWeYfVd5fvUKiVe9xNH29YfMF438fG364\/go-datastore\/namespace\"\n\tdsq \"gx\/ipfs\/QmRWDav6mzWseLWeYfVd5fvUKiVe9xNH29YfMF438fG364\/go-datastore\/query\"\n\tlogging \"gx\/ipfs\/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52\/go-log\"\n\tcid \"gx\/ipfs\/QmcTcsTvfaeEBRFo1TkFgT8sRmgi1n1LTZpecfVP8fzpGD\/go-cid\"\n)\n\nvar log = logging.Logger(\"blockstore\")\n\n\/\/ BlockPrefix namespaces blockstore datastores\nvar BlockPrefix = ds.NewKey(\"blocks\")\n\nvar ValueTypeMismatch = errors.New(\"the retrieved value is not a Block\")\nvar ErrHashMismatch = errors.New(\"block in storage has different hash than requested\")\n\nvar ErrNotFound = errors.New(\"blockstore: block not found\")\n\n\/\/ Blockstore wraps a Datastore\ntype Blockstore interface {\n\tDeleteBlock(*cid.Cid) error\n\tHas(*cid.Cid) (bool, error)\n\tGet(*cid.Cid) (blocks.Block, error)\n\tPut(blocks.Block) error\n\tPutMany([]blocks.Block) error\n\n\tAllKeysChan(ctx context.Context) (<-chan *cid.Cid, error)\n}\n\ntype GCLocker interface {\n\t\/\/ GCLock locks the blockstore for garbage collection. No operations\n\t\/\/ that expect to finish with a pin should ocurr simultaneously.\n\t\/\/ Reading during GC is safe, and requires no lock.\n\tGCLock() Unlocker\n\n\t\/\/ PinLock locks the blockstore for sequences of puts expected to finish\n\t\/\/ with a pin (before GC). Multiple put->pin sequences can write through\n\t\/\/ at the same time, but no GC should not happen simulatenously.\n\t\/\/ Reading during Pinning is safe, and requires no lock.\n\tPinLock() Unlocker\n\n\t\/\/ GcRequested returns true if GCLock has been called and is waiting to\n\t\/\/ take the lock\n\tGCRequested() bool\n}\n\ntype GCBlockstore interface {\n\tBlockstore\n\tGCLocker\n}\n\nfunc NewGCBlockstore(bs Blockstore, gcl GCLocker) GCBlockstore {\n\treturn gcBlockstore{bs, gcl}\n}\n\ntype gcBlockstore struct {\n\tBlockstore\n\tGCLocker\n}\n\nfunc NewBlockstore(d ds.Batching) *blockstore {\n\tvar dsb ds.Batching\n\tdd := dsns.Wrap(d, BlockPrefix)\n\tdsb = dd\n\treturn &blockstore{\n\t\tdatastore: dsb,\n\t}\n}\n\ntype blockstore struct {\n\tdatastore ds.Batching\n\n\tlk      sync.RWMutex\n\tgcreq   int32\n\tgcreqlk sync.Mutex\n\n\trehash bool\n}\n\nfunc (bs *blockstore) HashOnRead(enabled bool) {\n\tbs.rehash = enabled\n}\n\nfunc (bs *blockstore) Get(k *cid.Cid) (blocks.Block, error) {\n\tif k == nil {\n\t\tlog.Error(\"nil cid in blockstore\")\n\t\treturn nil, ErrNotFound\n\t}\n\n\tmaybeData, err := bs.datastore.Get(dshelp.CidToDsKey(k))\n\tif err == ds.ErrNotFound {\n\t\treturn nil, ErrNotFound\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbdata, ok := maybeData.([]byte)\n\tif !ok {\n\t\treturn nil, ValueTypeMismatch\n\t}\n\n\tif bs.rehash {\n\t\trbcid, err := k.Prefix().Sum(bdata)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !rbcid.Equals(k) {\n\t\t\treturn nil, ErrHashMismatch\n\t\t}\n\n\t\treturn blocks.NewBlockWithCid(bdata, rbcid)\n\t} else {\n\t\treturn blocks.NewBlockWithCid(bdata, k)\n\t}\n}\n\nfunc (bs *blockstore) Put(block blocks.Block) error {\n\tk := dshelp.CidToDsKey(block.Cid())\n\n\t\/\/ Has is cheaper than Put, so see if we already have it\n\texists, err := bs.datastore.Has(k)\n\tif err == nil && exists {\n\t\treturn nil \/\/ already stored.\n\t}\n\treturn bs.datastore.Put(k, block.RawData())\n}\n\nfunc (bs *blockstore) PutMany(blocks []blocks.Block) error {\n\tt, err := bs.datastore.Batch()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, b := range blocks {\n\t\tk := dshelp.CidToDsKey(b.Cid())\n\t\texists, err := bs.datastore.Has(k)\n\t\tif err == nil && exists {\n\t\t\tcontinue\n\t\t}\n\n\t\terr = t.Put(k, b.RawData())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn t.Commit()\n}\n\nfunc (bs *blockstore) Has(k *cid.Cid) (bool, error) {\n\treturn bs.datastore.Has(dshelp.CidToDsKey(k))\n}\n\nfunc (s *blockstore) DeleteBlock(k *cid.Cid) error {\n\treturn s.datastore.Delete(dshelp.CidToDsKey(k))\n}\n\n\/\/ AllKeysChan runs a query for keys from the blockstore.\n\/\/ this is very simplistic, in the future, take dsq.Query as a param?\n\/\/\n\/\/ AllKeysChan respects context\nfunc (bs *blockstore) AllKeysChan(ctx context.Context) (<-chan *cid.Cid, error) {\n\n\t\/\/ KeysOnly, because that would be _a lot_ of data.\n\tq := dsq.Query{KeysOnly: true}\n\t\/\/ datastore\/namespace does *NOT* fix up Query.Prefix\n\tq.Prefix = BlockPrefix.String()\n\tres, err := bs.datastore.Query(q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toutput := make(chan *cid.Cid, dsq.KeysOnlyBufSize)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tres.Close() \/\/ ensure exit (signals early exit, too)\n\t\t\tclose(output)\n\t\t}()\n\n\t\tfor {\n\t\t\te, ok := res.NextSync()\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif e.Error != nil {\n\t\t\t\tlog.Debug(\"blockstore.AllKeysChan got err:\", e.Error)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ need to convert to key.Key using key.KeyFromDsKey.\n\t\t\tk, err := dshelp.DsKeyToCid(ds.RawKey(e.Key))\n\t\t\tif err != nil {\n\t\t\t\tlog.Warningf(\"error parsing key from DsKey: \", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase output <- k:\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn output, nil\n}\n\nfunc NewGCLocker() *gclocker {\n\treturn &gclocker{}\n}\n\ntype gclocker struct {\n\tlk      sync.RWMutex\n\tgcreq   int32\n\tgcreqlk sync.Mutex\n}\n\ntype Unlocker interface {\n\tUnlock()\n}\n\ntype unlocker struct {\n\tunlock func()\n}\n\nfunc (u *unlocker) Unlock() {\n\tu.unlock()\n\tu.unlock = nil \/\/ ensure its not called twice\n}\n\nfunc (bs *gclocker) GCLock() Unlocker {\n\tatomic.AddInt32(&bs.gcreq, 1)\n\tbs.lk.Lock()\n\tatomic.AddInt32(&bs.gcreq, -1)\n\treturn &unlocker{bs.lk.Unlock}\n}\n\nfunc (bs *gclocker) PinLock() Unlocker {\n\tbs.lk.RLock()\n\treturn &unlocker{bs.lk.RUnlock}\n}\n\nfunc (bs *gclocker) GCRequested() bool {\n\treturn atomic.LoadInt32(&bs.gcreq) > 0\n}\n<commit_msg>blockstore.AllKeyChan: fix\/cleanup error handling<commit_after>\/\/ package blockstore implements a thin wrapper over a datastore, giving a\n\/\/ clean interface for Getting and Putting block objects.\npackage blockstore\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\n\tblocks \"github.com\/ipfs\/go-ipfs\/blocks\"\n\tdshelp \"github.com\/ipfs\/go-ipfs\/thirdparty\/ds-help\"\n\n\tds \"gx\/ipfs\/QmRWDav6mzWseLWeYfVd5fvUKiVe9xNH29YfMF438fG364\/go-datastore\"\n\tdsns \"gx\/ipfs\/QmRWDav6mzWseLWeYfVd5fvUKiVe9xNH29YfMF438fG364\/go-datastore\/namespace\"\n\tdsq \"gx\/ipfs\/QmRWDav6mzWseLWeYfVd5fvUKiVe9xNH29YfMF438fG364\/go-datastore\/query\"\n\tlogging \"gx\/ipfs\/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52\/go-log\"\n\tcid \"gx\/ipfs\/QmcTcsTvfaeEBRFo1TkFgT8sRmgi1n1LTZpecfVP8fzpGD\/go-cid\"\n)\n\nvar log = logging.Logger(\"blockstore\")\n\n\/\/ BlockPrefix namespaces blockstore datastores\nvar BlockPrefix = ds.NewKey(\"blocks\")\n\nvar ValueTypeMismatch = errors.New(\"the retrieved value is not a Block\")\nvar ErrHashMismatch = errors.New(\"block in storage has different hash than requested\")\n\nvar ErrNotFound = errors.New(\"blockstore: block not found\")\n\n\/\/ Blockstore wraps a Datastore\ntype Blockstore interface {\n\tDeleteBlock(*cid.Cid) error\n\tHas(*cid.Cid) (bool, error)\n\tGet(*cid.Cid) (blocks.Block, error)\n\tPut(blocks.Block) error\n\tPutMany([]blocks.Block) error\n\n\tAllKeysChan(ctx context.Context) (<-chan *cid.Cid, error)\n}\n\ntype GCLocker interface {\n\t\/\/ GCLock locks the blockstore for garbage collection. No operations\n\t\/\/ that expect to finish with a pin should ocurr simultaneously.\n\t\/\/ Reading during GC is safe, and requires no lock.\n\tGCLock() Unlocker\n\n\t\/\/ PinLock locks the blockstore for sequences of puts expected to finish\n\t\/\/ with a pin (before GC). Multiple put->pin sequences can write through\n\t\/\/ at the same time, but no GC should not happen simulatenously.\n\t\/\/ Reading during Pinning is safe, and requires no lock.\n\tPinLock() Unlocker\n\n\t\/\/ GcRequested returns true if GCLock has been called and is waiting to\n\t\/\/ take the lock\n\tGCRequested() bool\n}\n\ntype GCBlockstore interface {\n\tBlockstore\n\tGCLocker\n}\n\nfunc NewGCBlockstore(bs Blockstore, gcl GCLocker) GCBlockstore {\n\treturn gcBlockstore{bs, gcl}\n}\n\ntype gcBlockstore struct {\n\tBlockstore\n\tGCLocker\n}\n\nfunc NewBlockstore(d ds.Batching) *blockstore {\n\tvar dsb ds.Batching\n\tdd := dsns.Wrap(d, BlockPrefix)\n\tdsb = dd\n\treturn &blockstore{\n\t\tdatastore: dsb,\n\t}\n}\n\ntype blockstore struct {\n\tdatastore ds.Batching\n\n\tlk      sync.RWMutex\n\tgcreq   int32\n\tgcreqlk sync.Mutex\n\n\trehash bool\n}\n\nfunc (bs *blockstore) HashOnRead(enabled bool) {\n\tbs.rehash = enabled\n}\n\nfunc (bs *blockstore) Get(k *cid.Cid) (blocks.Block, error) {\n\tif k == nil {\n\t\tlog.Error(\"nil cid in blockstore\")\n\t\treturn nil, ErrNotFound\n\t}\n\n\tmaybeData, err := bs.datastore.Get(dshelp.CidToDsKey(k))\n\tif err == ds.ErrNotFound {\n\t\treturn nil, ErrNotFound\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbdata, ok := maybeData.([]byte)\n\tif !ok {\n\t\treturn nil, ValueTypeMismatch\n\t}\n\n\tif bs.rehash {\n\t\trbcid, err := k.Prefix().Sum(bdata)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !rbcid.Equals(k) {\n\t\t\treturn nil, ErrHashMismatch\n\t\t}\n\n\t\treturn blocks.NewBlockWithCid(bdata, rbcid)\n\t} else {\n\t\treturn blocks.NewBlockWithCid(bdata, k)\n\t}\n}\n\nfunc (bs *blockstore) Put(block blocks.Block) error {\n\tk := dshelp.CidToDsKey(block.Cid())\n\n\t\/\/ Has is cheaper than Put, so see if we already have it\n\texists, err := bs.datastore.Has(k)\n\tif err == nil && exists {\n\t\treturn nil \/\/ already stored.\n\t}\n\treturn bs.datastore.Put(k, block.RawData())\n}\n\nfunc (bs *blockstore) PutMany(blocks []blocks.Block) error {\n\tt, err := bs.datastore.Batch()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, b := range blocks {\n\t\tk := dshelp.CidToDsKey(b.Cid())\n\t\texists, err := bs.datastore.Has(k)\n\t\tif err == nil && exists {\n\t\t\tcontinue\n\t\t}\n\n\t\terr = t.Put(k, b.RawData())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn t.Commit()\n}\n\nfunc (bs *blockstore) Has(k *cid.Cid) (bool, error) {\n\treturn bs.datastore.Has(dshelp.CidToDsKey(k))\n}\n\nfunc (s *blockstore) DeleteBlock(k *cid.Cid) error {\n\treturn s.datastore.Delete(dshelp.CidToDsKey(k))\n}\n\n\/\/ AllKeysChan runs a query for keys from the blockstore.\n\/\/ this is very simplistic, in the future, take dsq.Query as a param?\n\/\/\n\/\/ AllKeysChan respects context\nfunc (bs *blockstore) AllKeysChan(ctx context.Context) (<-chan *cid.Cid, error) {\n\n\t\/\/ KeysOnly, because that would be _a lot_ of data.\n\tq := dsq.Query{KeysOnly: true}\n\t\/\/ datastore\/namespace does *NOT* fix up Query.Prefix\n\tq.Prefix = BlockPrefix.String()\n\tres, err := bs.datastore.Query(q)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\toutput := make(chan *cid.Cid, dsq.KeysOnlyBufSize)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tres.Close() \/\/ ensure exit (signals early exit, too)\n\t\t\tclose(output)\n\t\t}()\n\n\t\tfor {\n\t\t\te, ok := res.NextSync()\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif e.Error != nil {\n\t\t\t\tlog.Errorf(\"blockstore.AllKeysChan got err:\", e.Error)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t\/\/ need to convert to key.Key using key.KeyFromDsKey.\n\t\t\tk, err := dshelp.DsKeyToCid(ds.RawKey(e.Key))\n\t\t\tif err != nil {\n\t\t\t\tlog.Warningf(\"error parsing key from DsKey: \", err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\tcase output <- k:\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn output, nil\n}\n\nfunc NewGCLocker() *gclocker {\n\treturn &gclocker{}\n}\n\ntype gclocker struct {\n\tlk      sync.RWMutex\n\tgcreq   int32\n\tgcreqlk sync.Mutex\n}\n\ntype Unlocker interface {\n\tUnlock()\n}\n\ntype unlocker struct {\n\tunlock func()\n}\n\nfunc (u *unlocker) Unlock() {\n\tu.unlock()\n\tu.unlock = nil \/\/ ensure its not called twice\n}\n\nfunc (bs *gclocker) GCLock() Unlocker {\n\tatomic.AddInt32(&bs.gcreq, 1)\n\tbs.lk.Lock()\n\tatomic.AddInt32(&bs.gcreq, -1)\n\treturn &unlocker{bs.lk.Unlock}\n}\n\nfunc (bs *gclocker) PinLock() Unlocker {\n\tbs.lk.RLock()\n\treturn &unlocker{bs.lk.RUnlock}\n}\n\nfunc (bs *gclocker) GCRequested() bool {\n\treturn atomic.LoadInt32(&bs.gcreq) > 0\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * MediaType\n *\n * Copyright © 2014 Trevor N. Suarez (Rican7)\n *\/\n\npackage mediatype\n\nimport (\n\t\"testing\"\n)\n\n\/**\n * Variables\n *\/\n\nvar validComplexMediaType = \"application\/vnd.google-earth.kml+xml; charset=utf-8\"\n\nvar validMediaTypeStrings = []string{\n\t\"example\",\n\t\"application\/json\",\n\t\"application\/xhtml+xml\",\n\t\"audio\/vnd.rn-realaudio\",\n\t\"image\/vnd.djvu\",\n}\n\nvar invalidMediaTypeStrings = []string{\n\t\"application\/vnd\/json\",\n\t\"invalid\/+json.really\/sick\",\n}\n\n\/**\n * Helper functions\n *\/\n\n\/\/ Parse our valid media types\nfunc parseValidMediaTypes() (map[string]MediaType, map[string]error) {\n\tmediaTypes := make(map[string]MediaType)\n\terrors := make(map[string]error)\n\n\tfor _, val := range validMediaTypeStrings {\n\t\tmt, err := Parse(val)\n\n\t\tif nil != mt {\n\t\t\tmediaTypes[val] = mt\n\t\t}\n\n\t\tif nil != err {\n\t\t\terrors[val] = err\n\t\t}\n\t}\n\n\treturn mediaTypes, errors\n}\n\n\/\/ Parse our invalid media types\nfunc parseInvalidMediaTypes() (map[string]MediaType, map[string]error) {\n\tmediaTypes := make(map[string]MediaType)\n\terrors := make(map[string]error)\n\n\tfor _, val := range invalidMediaTypeStrings {\n\t\tmt, err := Parse(val)\n\n\t\tif nil != mt {\n\t\t\tmediaTypes[val] = mt\n\t\t}\n\n\t\tif nil != err {\n\t\t\terrors[val] = err\n\t\t}\n\t}\n\n\treturn mediaTypes, errors\n}\n\n\/**\n * Tests functions\n *\/\n\nfunc TestParse(t *testing.T) {\n\t_, validErrs := parseValidMediaTypes()\n\tinvalid, _ := parseInvalidMediaTypes()\n\n\tfor key, err := range validErrs {\n\t\tt.Errorf(\"Parsing failed for valid '%s' with error '%s'\", key, err)\n\t}\n\n\tfor key, _ := range invalid {\n\t\tt.Errorf(\"Parsing succeeded for invalid '%s'\", key)\n\t}\n}\n\nfunc TestFullType(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\n\t\tif mt.FullType() != \"application\/vnd.google-earth.kml+xml\" {\n\t\t\tt.Errorf(\"Incorrect full type for %+v\", mt)\n\t\t}\n\t}\n}\n\nfunc TestParameters(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\t\tcorrectParameters := map[string]string{\"charset\": \"utf-8\"}\n\n\t\tfor i, tree := range mt.Parameters() {\n\t\t\tif tree != correctParameters[i] {\n\t\t\t\tt.Errorf(\"Incorrect parameters for %+v\", mt)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestMainType(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\n\t\tif mt.MainType() != \"application\" {\n\t\t\tt.Errorf(\"Incorrect main type for %+v\", mt)\n\t\t}\n\t}\n}\n\nfunc TestSubType(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\n\t\tif mt.SubType() != \"kml\" {\n\t\t\tt.Errorf(\"Incorrect sub type for %+v\", mt)\n\t\t}\n\t}\n}\n\nfunc TestTrees(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\t\tcorrectTrees := []string{\"vnd\", \"google-earth\"}\n\n\t\tfor i, tree := range mt.Trees() {\n\t\t\tif tree != correctTrees[i] {\n\t\t\t\tt.Errorf(\"Incorrect trees for %+v\", mt)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestPrefix(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\n\t\tif mt.Prefix() != \"vnd\" {\n\t\t\tt.Errorf(\"Incorrect prefix for %+v\", mt)\n\t\t}\n\t}\n}\n\nfunc TestSuffix(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\n\t\tif mt.Suffix() != \"xml\" {\n\t\t\tt.Errorf(\"Incorrect suffix for %+v\", mt)\n\t\t}\n\t}\n}\n\nfunc TestString(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\n\t\tif mt.String() != validComplexMediaType {\n\t\t\tt.Errorf(\"Incorrect string for %+v\", mt)\n\t\t}\n\t}\n}\n<commit_msg>Oh... uhhhh, thanks golint!<commit_after>\/**\n * MediaType\n *\n * Copyright © 2014 Trevor N. Suarez (Rican7)\n *\/\n\npackage mediatype\n\nimport (\n\t\"testing\"\n)\n\n\/**\n * Variables\n *\/\n\nvar validComplexMediaType = \"application\/vnd.google-earth.kml+xml; charset=utf-8\"\n\nvar validMediaTypeStrings = []string{\n\t\"example\",\n\t\"application\/json\",\n\t\"application\/xhtml+xml\",\n\t\"audio\/vnd.rn-realaudio\",\n\t\"image\/vnd.djvu\",\n}\n\nvar invalidMediaTypeStrings = []string{\n\t\"application\/vnd\/json\",\n\t\"invalid\/+json.really\/sick\",\n}\n\n\/**\n * Helper functions\n *\/\n\n\/\/ Parse our valid media types\nfunc parseValidMediaTypes() (map[string]MediaType, map[string]error) {\n\tmediaTypes := make(map[string]MediaType)\n\terrors := make(map[string]error)\n\n\tfor _, val := range validMediaTypeStrings {\n\t\tmt, err := Parse(val)\n\n\t\tif nil != mt {\n\t\t\tmediaTypes[val] = mt\n\t\t}\n\n\t\tif nil != err {\n\t\t\terrors[val] = err\n\t\t}\n\t}\n\n\treturn mediaTypes, errors\n}\n\n\/\/ Parse our invalid media types\nfunc parseInvalidMediaTypes() (map[string]MediaType, map[string]error) {\n\tmediaTypes := make(map[string]MediaType)\n\terrors := make(map[string]error)\n\n\tfor _, val := range invalidMediaTypeStrings {\n\t\tmt, err := Parse(val)\n\n\t\tif nil != mt {\n\t\t\tmediaTypes[val] = mt\n\t\t}\n\n\t\tif nil != err {\n\t\t\terrors[val] = err\n\t\t}\n\t}\n\n\treturn mediaTypes, errors\n}\n\n\/**\n * Tests functions\n *\/\n\nfunc TestParse(t *testing.T) {\n\t_, validErrs := parseValidMediaTypes()\n\tinvalid, _ := parseInvalidMediaTypes()\n\n\tfor key, err := range validErrs {\n\t\tt.Errorf(\"Parsing failed for valid '%s' with error '%s'\", key, err)\n\t}\n\n\tfor key := range invalid {\n\t\tt.Errorf(\"Parsing succeeded for invalid '%s'\", key)\n\t}\n}\n\nfunc TestFullType(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\n\t\tif mt.FullType() != \"application\/vnd.google-earth.kml+xml\" {\n\t\t\tt.Errorf(\"Incorrect full type for %+v\", mt)\n\t\t}\n\t}\n}\n\nfunc TestParameters(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\t\tcorrectParameters := map[string]string{\"charset\": \"utf-8\"}\n\n\t\tfor i, tree := range mt.Parameters() {\n\t\t\tif tree != correctParameters[i] {\n\t\t\t\tt.Errorf(\"Incorrect parameters for %+v\", mt)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestMainType(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\n\t\tif mt.MainType() != \"application\" {\n\t\t\tt.Errorf(\"Incorrect main type for %+v\", mt)\n\t\t}\n\t}\n}\n\nfunc TestSubType(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\n\t\tif mt.SubType() != \"kml\" {\n\t\t\tt.Errorf(\"Incorrect sub type for %+v\", mt)\n\t\t}\n\t}\n}\n\nfunc TestTrees(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\t\tcorrectTrees := []string{\"vnd\", \"google-earth\"}\n\n\t\tfor i, tree := range mt.Trees() {\n\t\t\tif tree != correctTrees[i] {\n\t\t\t\tt.Errorf(\"Incorrect trees for %+v\", mt)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestPrefix(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\n\t\tif mt.Prefix() != \"vnd\" {\n\t\t\tt.Errorf(\"Incorrect prefix for %+v\", mt)\n\t\t}\n\t}\n}\n\nfunc TestSuffix(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\n\t\tif mt.Suffix() != \"xml\" {\n\t\t\tt.Errorf(\"Incorrect suffix for %+v\", mt)\n\t\t}\n\t}\n}\n\nfunc TestString(t *testing.T) {\n\tmt, err := Parse(validComplexMediaType)\n\n\tif nil != err {\n\t\tt.Errorf(\"Parsing failed for valid '%s'\", validComplexMediaType)\n\t} else {\n\n\t\tif mt.String() != validComplexMediaType {\n\t\t\tt.Errorf(\"Incorrect string for %+v\", mt)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Based on ssh\/terminal:\n\/\/ Copyright 2013 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build appengine\n\npackage logrus\n\nfunc initTerminal(w io.Writer) {\n}\n<commit_msg>Fix copypasta<commit_after>\/\/ Based on ssh\/terminal:\n\/\/ Copyright 2018 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build appengine\n\npackage logrus\n\nimport \"io\"\n\nfunc initTerminal(w io.Writer) {\n}\n<|endoftext|>"}
{"text":"<commit_before>package cache\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/VictoriaMetrics\/fastcache\"\n\t\"github.com\/go-redis\/redis\/v8\"\n\t\"github.com\/klauspost\/compress\/s2\"\n\t\"github.com\/vmihailenco\/bufpool\"\n\t\"github.com\/vmihailenco\/msgpack\/v5\"\n\t\"go4.org\/syncutil\/singleflight\"\n)\n\nconst compressionThreshold = 64\n\nconst (\n\tnoCompression = 0x0\n\ts2Compression = 0x1\n)\n\nvar ErrCacheMiss = errors.New(\"cache: key is missing\")\nvar errRedisLocalCacheNil = errors.New(\"cache: both Redis and LocalCache are nil\")\n\ntype rediser interface {\n\tSet(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.StatusCmd\n\tSetXX(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.BoolCmd\n\tSetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.BoolCmd\n\n\tGet(ctx context.Context, key string) *redis.StringCmd\n\tDel(ctx context.Context, keys ...string) *redis.IntCmd\n}\n\ntype Item struct {\n\tCtx context.Context\n\n\tKey   string\n\tValue interface{}\n\n\t\/\/ TTL is the cache expiration time.\n\t\/\/ Default TTL is 1 hour.\n\tTTL time.Duration\n\n\t\/\/ Do returns value to be cached.\n\tDo func(*Item) (interface{}, error)\n\n\t\/\/ IfExists only sets the key if it already exist.\n\tIfExists bool\n\n\t\/\/ IfNotExists only sets the key if it does not already exist.\n\tIfNotExists bool\n\n\t\/\/ SkipLocalCache skips local cache as if it is not set.\n\tSkipLocalCache bool\n}\n\nfunc (item *Item) Context() context.Context {\n\tif item.Ctx == nil {\n\t\treturn context.Background()\n\t}\n\treturn item.Ctx\n}\n\nfunc (item *Item) value() (interface{}, error) {\n\tif item.Do != nil {\n\t\treturn item.Do(item)\n\t}\n\tif item.Value != nil {\n\t\treturn item.Value, nil\n\t}\n\treturn nil, nil\n}\n\nfunc (item *Item) ttl() time.Duration {\n\tif item.TTL < 0 {\n\t\treturn 0\n\t}\n\tif item.TTL < time.Second {\n\t\treturn time.Hour\n\t}\n\treturn item.TTL\n}\n\n\/\/------------------------------------------------------------------------------\n\ntype Options struct {\n\tRedis rediser\n\n\tLocalCache    *fastcache.Cache\n\tLocalCacheTTL time.Duration\n\n\tStatsEnabled bool\n}\n\nfunc (opt *Options) init() {\n\tswitch opt.LocalCacheTTL {\n\tcase -1:\n\t\topt.LocalCacheTTL = 0\n\tcase 0:\n\t\topt.LocalCacheTTL = time.Minute\n\t}\n}\n\ntype Cache struct {\n\topt *Options\n\n\tgroup singleflight.Group\n\n\thits   uint64\n\tmisses uint64\n}\n\nfunc New(opt *Options) *Cache {\n\topt.init()\n\treturn &Cache{\n\t\topt: opt,\n\t}\n}\n\n\/\/ Set caches the item.\nfunc (cd *Cache) Set(item *Item) error {\n\t_, _, err := cd.set(item)\n\treturn err\n}\n\nfunc (cd *Cache) set(item *Item) ([]byte, bool, error) {\n\tvalue, err := item.value()\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tb, err := cd.Marshal(value)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tif cd.opt.LocalCache != nil {\n\t\tcd.localSet(item.Key, b)\n\t}\n\n\tif cd.opt.Redis == nil {\n\t\tif cd.opt.LocalCache == nil {\n\t\t\treturn b, true, errRedisLocalCacheNil\n\t\t}\n\t\treturn b, true, nil\n\t}\n\n\tif item.IfExists {\n\t\treturn b, true, cd.opt.Redis.SetXX(item.Context(), item.Key, b, item.ttl()).Err()\n\t}\n\n\tif item.IfNotExists {\n\t\treturn b, true, cd.opt.Redis.SetNX(item.Context(), item.Key, b, item.ttl()).Err()\n\t}\n\n\treturn b, true, cd.opt.Redis.Set(item.Context(), item.Key, b, item.ttl()).Err()\n}\n\n\/\/ Exists reports whether value for the given key exists.\nfunc (cd *Cache) Exists(ctx context.Context, key string) bool {\n\treturn cd.Get(ctx, key, nil) == nil\n}\n\n\/\/ Get gets the value for the given key.\nfunc (cd *Cache) Get(ctx context.Context, key string, value interface{}) error {\n\treturn cd.get(ctx, key, value, false)\n}\n\n\/\/ Get gets the value for the given key skipping local cache.\nfunc (cd *Cache) GetSkippingLocalCache(\n\tctx context.Context, key string, value interface{},\n) error {\n\treturn cd.get(ctx, key, value, true)\n}\n\nfunc (cd *Cache) get(\n\tctx context.Context,\n\tkey string,\n\tvalue interface{},\n\tskipLocalCache bool,\n) error {\n\tb, err := cd.getBytes(ctx, key, skipLocalCache)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn cd.Unmarshal(b, value)\n}\n\nfunc (cd *Cache) getBytes(ctx context.Context, key string, skipLocalCache bool) ([]byte, error) {\n\tif !skipLocalCache && cd.opt.LocalCache != nil {\n\t\tb, ok := cd.localGet(key)\n\t\tif ok {\n\t\t\treturn b, nil\n\t\t}\n\t}\n\n\tif cd.opt.Redis == nil {\n\t\tif cd.opt.LocalCache == nil {\n\t\t\treturn nil, errRedisLocalCacheNil\n\t\t}\n\t\treturn nil, ErrCacheMiss\n\t}\n\n\tb, err := cd.opt.Redis.Get(ctx, key).Bytes()\n\tif err != nil {\n\t\tif cd.opt.StatsEnabled {\n\t\t\tatomic.AddUint64(&cd.misses, 1)\n\t\t}\n\t\tif err == redis.Nil {\n\t\t\treturn nil, ErrCacheMiss\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif cd.opt.StatsEnabled {\n\t\tatomic.AddUint64(&cd.hits, 1)\n\t}\n\n\tif !skipLocalCache && cd.opt.LocalCache != nil {\n\t\tcd.localSet(key, b)\n\t}\n\treturn b, nil\n}\n\n\/\/ Once gets the item.Value for the given item.Key from the cache or\n\/\/ executes, caches, and returns the results of the given item.Func,\n\/\/ making sure that only one execution is in-flight for a given item.Key\n\/\/ at a time. If a duplicate comes in, the duplicate caller waits for the\n\/\/ original to complete and receives the same results.\nfunc (cd *Cache) Once(item *Item) error {\n\tb, cached, err := cd.getSetItemBytesOnce(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif item.Value == nil || len(b) == 0 {\n\t\treturn nil\n\t}\n\n\tif err := cd.Unmarshal(b, item.Value); err != nil {\n\t\tif cached {\n\t\t\t_ = cd.Delete(item.Context(), item.Key)\n\t\t\treturn cd.Once(item)\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (cd *Cache) getSetItemBytesOnce(item *Item) (b []byte, cached bool, err error) {\n\tif cd.opt.LocalCache != nil {\n\t\tb, ok := cd.localGet(item.Key)\n\t\tif ok {\n\t\t\treturn b, true, nil\n\t\t}\n\t}\n\n\tv, err := cd.group.Do(item.Key, func() (interface{}, error) {\n\t\tb, err := cd.getBytes(item.Context(), item.Key, item.SkipLocalCache)\n\t\tif err == nil {\n\t\t\tcached = true\n\t\t\treturn b, nil\n\t\t}\n\n\t\tb, ok, err := cd.set(item)\n\t\tif ok {\n\t\t\treturn b, nil\n\t\t}\n\t\treturn nil, err\n\t})\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\treturn v.([]byte), cached, nil\n}\n\nfunc (cd *Cache) Delete(ctx context.Context, key string) error {\n\tif cd.opt.LocalCache != nil {\n\t\tcd.opt.LocalCache.Del([]byte(key))\n\t}\n\n\tif cd.opt.Redis == nil {\n\t\tif cd.opt.LocalCache == nil {\n\t\t\treturn errRedisLocalCacheNil\n\t\t}\n\t\treturn nil\n\t}\n\n\tdeleted, err := cd.opt.Redis.Del(ctx, key).Result()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif deleted == 0 {\n\t\treturn ErrCacheMiss\n\t}\n\treturn nil\n}\n\nfunc (cd *Cache) localSet(key string, b []byte) {\n\tif cd.opt.LocalCacheTTL > 0 {\n\t\tpos := len(b)\n\t\tb = append(b, make([]byte, 4)...)\n\t\tencodeTime(b[pos:], time.Now())\n\t}\n\n\tcd.opt.LocalCache.Set([]byte(key), b)\n}\n\nfunc (cd *Cache) localGet(key string) ([]byte, bool) {\n\tb, ok := cd.opt.LocalCache.HasGet(nil, []byte(key))\n\tif !ok {\n\t\treturn b, false\n\t}\n\n\tif len(b) == 0 || cd.opt.LocalCacheTTL == 0 {\n\t\treturn b, true\n\t}\n\tif len(b) < 4 {\n\t\tpanic(\"not reached\")\n\t}\n\n\ttm := decodeTime(b[len(b)-4:])\n\tif time.Since(tm) > cd.opt.LocalCacheTTL {\n\t\tcd.opt.LocalCache.Del([]byte(key))\n\t\treturn nil, false\n\t}\n\n\treturn b[:len(b)-4], true\n}\n\nfunc (cd *Cache) Marshal(value interface{}) ([]byte, error) {\n\tswitch value := value.(type) {\n\tcase nil:\n\t\treturn nil, nil\n\tcase []byte:\n\t\treturn value, nil\n\tcase string:\n\t\treturn []byte(value), nil\n\t}\n\n\tenc := msgpack.GetEncoder()\n\n\tvar buf bytes.Buffer\n\tenc.Reset(&buf)\n\tenc.UseCompactInts(true)\n\n\terr := enc.Encode(value)\n\n\tmsgpack.PutEncoder(enc)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb := buf.Bytes()\n\n\tif len(b) < compressionThreshold {\n\t\tb = append(b, noCompression)\n\t\treturn b, nil\n\t}\n\n\tb = s2.Encode(nil, b)\n\tb = append(b, s2Compression)\n\n\treturn b, nil\n}\n\nfunc (cd *Cache) Unmarshal(b []byte, value interface{}) error {\n\tif len(b) == 0 {\n\t\treturn nil\n\t}\n\n\tswitch value := value.(type) {\n\tcase nil:\n\t\treturn nil\n\tcase *[]byte:\n\t\treflect.ValueOf(value).Elem().SetBytes(b)\n\t\treturn nil\n\tcase *string:\n\t\treflect.ValueOf(value).Elem().SetString(string(b))\n\t\treturn nil\n\t}\n\n\tif len(b) == 0 {\n\t\treturn nil\n\t}\n\n\tswitch c := b[len(b)-1]; c {\n\tcase noCompression:\n\t\tb = b[:len(b)-1]\n\tcase s2Compression:\n\t\tb = b[:len(b)-1]\n\n\t\tn, err := s2.DecodedLen(b)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuf := bufpool.Get(n)\n\t\tdefer bufpool.Put(buf)\n\n\t\tb, err = s2.Decode(buf.Bytes(), b)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"uknownn compression method: %x\", c)\n\t}\n\n\treturn msgpack.Unmarshal(b, value)\n}\n\n\/\/------------------------------------------------------------------------------\n\ntype Stats struct {\n\tHits   uint64\n\tMisses uint64\n}\n\n\/\/ Stats returns cache statistics.\nfunc (cd *Cache) Stats() *Stats {\n\tif !cd.opt.StatsEnabled {\n\t\treturn nil\n\t}\n\treturn &Stats{\n\t\tHits:   atomic.LoadUint64(&cd.hits),\n\t\tMisses: atomic.LoadUint64(&cd.misses),\n\t}\n}\n\n\/\/------------------------------------------------------------------------------\n\nvar epoch = time.Date(2020, time.January, 01, 00, 0, 0, 0, time.UTC).Unix()\n\nfunc encodeTime(b []byte, tm time.Time) {\n\tsecs := tm.Unix() - epoch\n\tbinary.LittleEndian.PutUint32(b, uint32(secs))\n}\n\nfunc decodeTime(b []byte) time.Time {\n\tsecs := binary.LittleEndian.Uint32(b)\n\treturn time.Unix(int64(secs)+epoch, 0)\n}\n<commit_msg>Reduce number of allocs<commit_after>package cache\n\nimport (\n\t\"context\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/VictoriaMetrics\/fastcache\"\n\t\"github.com\/go-redis\/redis\/v8\"\n\t\"github.com\/klauspost\/compress\/s2\"\n\t\"github.com\/vmihailenco\/bufpool\"\n\t\"github.com\/vmihailenco\/msgpack\/v5\"\n\t\"go4.org\/syncutil\/singleflight\"\n)\n\nconst compressionThreshold = 64\n\nconst (\n\tnoCompression = 0x0\n\ts2Compression = 0x1\n)\n\nvar ErrCacheMiss = errors.New(\"cache: key is missing\")\nvar errRedisLocalCacheNil = errors.New(\"cache: both Redis and LocalCache are nil\")\n\ntype rediser interface {\n\tSet(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.StatusCmd\n\tSetXX(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.BoolCmd\n\tSetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.BoolCmd\n\n\tGet(ctx context.Context, key string) *redis.StringCmd\n\tDel(ctx context.Context, keys ...string) *redis.IntCmd\n}\n\ntype Item struct {\n\tCtx context.Context\n\n\tKey   string\n\tValue interface{}\n\n\t\/\/ TTL is the cache expiration time.\n\t\/\/ Default TTL is 1 hour.\n\tTTL time.Duration\n\n\t\/\/ Do returns value to be cached.\n\tDo func(*Item) (interface{}, error)\n\n\t\/\/ IfExists only sets the key if it already exist.\n\tIfExists bool\n\n\t\/\/ IfNotExists only sets the key if it does not already exist.\n\tIfNotExists bool\n\n\t\/\/ SkipLocalCache skips local cache as if it is not set.\n\tSkipLocalCache bool\n}\n\nfunc (item *Item) Context() context.Context {\n\tif item.Ctx == nil {\n\t\treturn context.Background()\n\t}\n\treturn item.Ctx\n}\n\nfunc (item *Item) value() (interface{}, error) {\n\tif item.Do != nil {\n\t\treturn item.Do(item)\n\t}\n\tif item.Value != nil {\n\t\treturn item.Value, nil\n\t}\n\treturn nil, nil\n}\n\nfunc (item *Item) ttl() time.Duration {\n\tif item.TTL < 0 {\n\t\treturn 0\n\t}\n\tif item.TTL < time.Second {\n\t\treturn time.Hour\n\t}\n\treturn item.TTL\n}\n\n\/\/------------------------------------------------------------------------------\n\ntype Options struct {\n\tRedis rediser\n\n\tLocalCache    *fastcache.Cache\n\tLocalCacheTTL time.Duration\n\n\tStatsEnabled bool\n}\n\nfunc (opt *Options) init() {\n\tswitch opt.LocalCacheTTL {\n\tcase -1:\n\t\topt.LocalCacheTTL = 0\n\tcase 0:\n\t\topt.LocalCacheTTL = time.Minute\n\t}\n}\n\ntype Cache struct {\n\topt *Options\n\n\tgroup   singleflight.Group\n\tbufpool bufpool.Pool\n\n\thits   uint64\n\tmisses uint64\n}\n\nfunc New(opt *Options) *Cache {\n\topt.init()\n\treturn &Cache{\n\t\topt: opt,\n\t}\n}\n\n\/\/ Set caches the item.\nfunc (cd *Cache) Set(item *Item) error {\n\t_, _, err := cd.set(item)\n\treturn err\n}\n\nfunc (cd *Cache) set(item *Item) ([]byte, bool, error) {\n\tvalue, err := item.value()\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tb, err := cd.Marshal(value)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\tif cd.opt.LocalCache != nil {\n\t\tcd.localSet(item.Key, b)\n\t}\n\n\tif cd.opt.Redis == nil {\n\t\tif cd.opt.LocalCache == nil {\n\t\t\treturn b, true, errRedisLocalCacheNil\n\t\t}\n\t\treturn b, true, nil\n\t}\n\n\tif item.IfExists {\n\t\treturn b, true, cd.opt.Redis.SetXX(item.Context(), item.Key, b, item.ttl()).Err()\n\t}\n\n\tif item.IfNotExists {\n\t\treturn b, true, cd.opt.Redis.SetNX(item.Context(), item.Key, b, item.ttl()).Err()\n\t}\n\n\treturn b, true, cd.opt.Redis.Set(item.Context(), item.Key, b, item.ttl()).Err()\n}\n\n\/\/ Exists reports whether value for the given key exists.\nfunc (cd *Cache) Exists(ctx context.Context, key string) bool {\n\treturn cd.Get(ctx, key, nil) == nil\n}\n\n\/\/ Get gets the value for the given key.\nfunc (cd *Cache) Get(ctx context.Context, key string, value interface{}) error {\n\treturn cd.get(ctx, key, value, false)\n}\n\n\/\/ Get gets the value for the given key skipping local cache.\nfunc (cd *Cache) GetSkippingLocalCache(\n\tctx context.Context, key string, value interface{},\n) error {\n\treturn cd.get(ctx, key, value, true)\n}\n\nfunc (cd *Cache) get(\n\tctx context.Context,\n\tkey string,\n\tvalue interface{},\n\tskipLocalCache bool,\n) error {\n\tb, err := cd.getBytes(ctx, key, skipLocalCache)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn cd.Unmarshal(b, value)\n}\n\nfunc (cd *Cache) getBytes(ctx context.Context, key string, skipLocalCache bool) ([]byte, error) {\n\tif !skipLocalCache && cd.opt.LocalCache != nil {\n\t\tb, ok := cd.localGet(key)\n\t\tif ok {\n\t\t\treturn b, nil\n\t\t}\n\t}\n\n\tif cd.opt.Redis == nil {\n\t\tif cd.opt.LocalCache == nil {\n\t\t\treturn nil, errRedisLocalCacheNil\n\t\t}\n\t\treturn nil, ErrCacheMiss\n\t}\n\n\tb, err := cd.opt.Redis.Get(ctx, key).Bytes()\n\tif err != nil {\n\t\tif cd.opt.StatsEnabled {\n\t\t\tatomic.AddUint64(&cd.misses, 1)\n\t\t}\n\t\tif err == redis.Nil {\n\t\t\treturn nil, ErrCacheMiss\n\t\t}\n\t\treturn nil, err\n\t}\n\n\tif cd.opt.StatsEnabled {\n\t\tatomic.AddUint64(&cd.hits, 1)\n\t}\n\n\tif !skipLocalCache && cd.opt.LocalCache != nil {\n\t\tcd.localSet(key, b)\n\t}\n\treturn b, nil\n}\n\n\/\/ Once gets the item.Value for the given item.Key from the cache or\n\/\/ executes, caches, and returns the results of the given item.Func,\n\/\/ making sure that only one execution is in-flight for a given item.Key\n\/\/ at a time. If a duplicate comes in, the duplicate caller waits for the\n\/\/ original to complete and receives the same results.\nfunc (cd *Cache) Once(item *Item) error {\n\tb, cached, err := cd.getSetItemBytesOnce(item)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif item.Value == nil || len(b) == 0 {\n\t\treturn nil\n\t}\n\n\tif err := cd.Unmarshal(b, item.Value); err != nil {\n\t\tif cached {\n\t\t\t_ = cd.Delete(item.Context(), item.Key)\n\t\t\treturn cd.Once(item)\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (cd *Cache) getSetItemBytesOnce(item *Item) (b []byte, cached bool, err error) {\n\tif cd.opt.LocalCache != nil {\n\t\tb, ok := cd.localGet(item.Key)\n\t\tif ok {\n\t\t\treturn b, true, nil\n\t\t}\n\t}\n\n\tv, err := cd.group.Do(item.Key, func() (interface{}, error) {\n\t\tb, err := cd.getBytes(item.Context(), item.Key, item.SkipLocalCache)\n\t\tif err == nil {\n\t\t\tcached = true\n\t\t\treturn b, nil\n\t\t}\n\n\t\tb, ok, err := cd.set(item)\n\t\tif ok {\n\t\t\treturn b, nil\n\t\t}\n\t\treturn nil, err\n\t})\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\treturn v.([]byte), cached, nil\n}\n\nfunc (cd *Cache) Delete(ctx context.Context, key string) error {\n\tif cd.opt.LocalCache != nil {\n\t\tcd.opt.LocalCache.Del([]byte(key))\n\t}\n\n\tif cd.opt.Redis == nil {\n\t\tif cd.opt.LocalCache == nil {\n\t\t\treturn errRedisLocalCacheNil\n\t\t}\n\t\treturn nil\n\t}\n\n\tdeleted, err := cd.opt.Redis.Del(ctx, key).Result()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif deleted == 0 {\n\t\treturn ErrCacheMiss\n\t}\n\treturn nil\n}\n\nfunc (cd *Cache) localSet(key string, b []byte) {\n\tif cd.opt.LocalCacheTTL > 0 {\n\t\tpos := len(b)\n\t\tb = append(b, make([]byte, 4)...)\n\t\tencodeTime(b[pos:], time.Now())\n\t}\n\n\tcd.opt.LocalCache.Set([]byte(key), b)\n}\n\nfunc (cd *Cache) localGet(key string) ([]byte, bool) {\n\tb, ok := cd.opt.LocalCache.HasGet(nil, []byte(key))\n\tif !ok {\n\t\treturn b, false\n\t}\n\n\tif len(b) == 0 || cd.opt.LocalCacheTTL == 0 {\n\t\treturn b, true\n\t}\n\tif len(b) < 4 {\n\t\tpanic(\"not reached\")\n\t}\n\n\ttm := decodeTime(b[len(b)-4:])\n\tif time.Since(tm) > cd.opt.LocalCacheTTL {\n\t\tcd.opt.LocalCache.Del([]byte(key))\n\t\treturn nil, false\n\t}\n\n\treturn b[:len(b)-4], true\n}\n\nfunc (cd *Cache) Marshal(value interface{}) ([]byte, error) {\n\tswitch value := value.(type) {\n\tcase nil:\n\t\treturn nil, nil\n\tcase []byte:\n\t\treturn value, nil\n\tcase string:\n\t\treturn []byte(value), nil\n\t}\n\n\tbuf := cd.bufpool.Get()\n\tdefer cd.bufpool.Put(buf)\n\n\tenc := msgpack.GetEncoder()\n\tenc.Reset(buf)\n\tenc.UseCompactInts(true)\n\n\terr := enc.Encode(value)\n\n\tmsgpack.PutEncoder(enc)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif buf.Len() < compressionThreshold {\n\t\tb := make([]byte, buf.Len()+1)\n\t\tcopy(b, buf.Bytes())\n\t\tb[len(b)-1] = noCompression\n\t\treturn b, nil\n\t}\n\n\tb := make([]byte, s2.MaxEncodedLen(buf.Len())+1)\n\tb = s2.Encode(b, buf.Bytes())\n\tb = append(b, s2Compression)\n\n\treturn b, nil\n}\n\nfunc (cd *Cache) Unmarshal(b []byte, value interface{}) error {\n\tif len(b) == 0 {\n\t\treturn nil\n\t}\n\n\tswitch value := value.(type) {\n\tcase nil:\n\t\treturn nil\n\tcase *[]byte:\n\t\t*value = b\n\t\treturn nil\n\tcase *string:\n\t\t*value = string(b)\n\t\treturn nil\n\t}\n\n\tif len(b) == 0 {\n\t\treturn nil\n\t}\n\n\tswitch c := b[len(b)-1]; c {\n\tcase noCompression:\n\t\tb = b[:len(b)-1]\n\tcase s2Compression:\n\t\tb = b[:len(b)-1]\n\n\t\tn, err := s2.DecodedLen(b)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tbuf := bufpool.Get(n)\n\t\tdefer bufpool.Put(buf)\n\n\t\tb, err = s2.Decode(buf.Bytes(), b)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"uknownn compression method: %x\", c)\n\t}\n\n\treturn msgpack.Unmarshal(b, value)\n}\n\n\/\/------------------------------------------------------------------------------\n\ntype Stats struct {\n\tHits   uint64\n\tMisses uint64\n}\n\n\/\/ Stats returns cache statistics.\nfunc (cd *Cache) Stats() *Stats {\n\tif !cd.opt.StatsEnabled {\n\t\treturn nil\n\t}\n\treturn &Stats{\n\t\tHits:   atomic.LoadUint64(&cd.hits),\n\t\tMisses: atomic.LoadUint64(&cd.misses),\n\t}\n}\n\n\/\/------------------------------------------------------------------------------\n\nvar epoch = time.Date(2020, time.January, 01, 00, 0, 0, 0, time.UTC).Unix()\n\nfunc encodeTime(b []byte, tm time.Time) {\n\tsecs := tm.Unix() - epoch\n\tbinary.LittleEndian.PutUint32(b, uint32(secs))\n}\n\nfunc decodeTime(b []byte) time.Time {\n\tsecs := binary.LittleEndian.Uint32(b)\n\treturn time.Unix(int64(secs)+epoch, 0)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 The Terraformer Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage terraformutils\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/hashicorp\/hcl\/hcl\/ast\"\n\thclPrinter \"github.com\/hashicorp\/hcl\/hcl\/printer\"\n\thclParcer \"github.com\/hashicorp\/hcl\/json\/parser\"\n)\n\n\/\/ Copy code from https:\/\/github.com\/kubernetes\/kops project with few changes for support many provider and heredoc\n\nconst safeChars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_\"\n\nvar unsafeChars = regexp.MustCompile(`[^0-9A-Za-z_]`)\n\n\/\/ sanitizer fixes up an invalid HCL AST, as produced by the HCL parser for JSON\ntype astSanitizer struct{}\n\n\/\/ output prints creates b printable HCL output and returns it.\nfunc (v *astSanitizer) visit(n interface{}) {\n\tswitch t := n.(type) {\n\tcase *ast.File:\n\t\tv.visit(t.Node)\n\tcase *ast.ObjectList:\n\t\tvar index int\n\t\tfor {\n\t\t\tif index == len(t.Items) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tv.visit(t.Items[index])\n\t\t\tindex++\n\t\t}\n\tcase *ast.ObjectKey:\n\tcase *ast.ObjectItem:\n\t\tv.visitObjectItem(t)\n\tcase *ast.LiteralType:\n\tcase *ast.ListType:\n\tcase *ast.ObjectType:\n\t\tv.visit(t.List)\n\tdefault:\n\t\tfmt.Printf(\" unknown type: %T\\n\", n)\n\t}\n}\n\nfunc (v *astSanitizer) visitObjectItem(o *ast.ObjectItem) {\n\tfor i, k := range o.Keys {\n\t\tif i == 0 {\n\t\t\ttext := k.Token.Text\n\t\t\tif text != \"\" && text[0] == '\"' && text[len(text)-1] == '\"' {\n\t\t\t\tv := text[1 : len(text)-1]\n\t\t\t\tsafe := true\n\t\t\t\tfor _, c := range v {\n\t\t\t\t\tif !strings.ContainsRune(safeChars, c) {\n\t\t\t\t\t\tsafe = false\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif safe {\n\t\t\t\t\tk.Token.Text = v\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tswitch t := o.Val.(type) {\n\tcase *ast.LiteralType: \/\/ heredoc support\n\t\tif strings.HasPrefix(t.Token.Text, `\"<<`) {\n\t\t\tt.Token.Text = t.Token.Text[1:]\n\t\t\tt.Token.Text = t.Token.Text[:len(t.Token.Text)-1]\n\t\t\tt.Token.Text = strings.ReplaceAll(t.Token.Text, `\\n`, \"\\n\")\n\t\t\tt.Token.Text = strings.ReplaceAll(t.Token.Text, `\\t`, \"\")\n\t\t\tt.Token.Type = 10\n\t\t\t\/\/ check if text json for Unquote and Indent\n\t\t\ttmp := map[string]interface{}{}\n\t\t\tjsonTest := t.Token.Text\n\t\t\tlines := strings.Split(jsonTest, \"\\n\")\n\t\t\tjsonTest = strings.Join(lines[1:len(lines)-1], \"\\n\")\n\t\t\tjsonTest = strings.ReplaceAll(jsonTest, \"\\\\\\\"\", \"\\\"\")\n\t\t\t\/\/ it's json we convert to heredoc back\n\t\t\terr := json.Unmarshal([]byte(jsonTest), &tmp)\n\t\t\tif err == nil {\n\t\t\t\tdataJSONBytes, err := json.MarshalIndent(tmp, \"\", \"  \")\n\t\t\t\tif err == nil {\n\t\t\t\t\tjsonData := strings.Split(string(dataJSONBytes), \"\\n\")\n\t\t\t\t\t\/\/ first line for heredoc\n\t\t\t\t\tjsonData = append([]string{lines[0]}, jsonData...)\n\t\t\t\t\t\/\/ last line for heredoc\n\t\t\t\t\tjsonData = append(jsonData, lines[len(lines)-1])\n\t\t\t\t\thereDoc := strings.Join(jsonData, \"\\n\")\n\t\t\t\t\tt.Token.Text = hereDoc\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tdefault:\n\t}\n\n\t\/\/ A hack so that Assign.IsValid is true, so that the printer will output =\n\to.Assign.Line = 1\n\n\tv.visit(o.Val)\n}\n\nfunc Print(data interface{}, mapsObjects map[string]struct{}, format string) ([]byte, error) {\n\tswitch format {\n\tcase \"hcl\":\n\t\treturn hclPrint(data, mapsObjects)\n\tcase \"json\":\n\t\treturn jsonPrint(data)\n\t}\n\treturn []byte{}, errors.New(\"error: unknown output format\")\n}\n\nfunc hclPrint(data interface{}, mapsObjects map[string]struct{}) ([]byte, error) {\n\tdataBytesJSON, err := jsonPrint(data)\n\tif err != nil {\n\t\treturn dataBytesJSON, err\n\t}\n\tdataJSON := string(dataBytesJSON)\n\tnodes, err := hclParcer.Parse([]byte(dataJSON))\n\tif err != nil {\n\t\tlog.Println(dataJSON)\n\t\treturn []byte{}, fmt.Errorf(\"error parsing terraform json: %v\", err)\n\t}\n\tvar sanitizer astSanitizer\n\tsanitizer.visit(nodes)\n\n\tvar b bytes.Buffer\n\terr = hclPrinter.Fprint(&b, nodes)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error writing HCL: %v\", err)\n\t}\n\ts := b.String()\n\n\t\/\/ Remove extra whitespace...\n\ts = strings.ReplaceAll(s, \"\\n\\n\", \"\\n\")\n\n\t\/\/ ...but leave whitespace between resources\n\ts = strings.ReplaceAll(s, \"}\\nresource\", \"}\\n\\nresource\")\n\n\t\/\/ Apply Terraform style (alignment etc.)\n\tformatted, err := hclPrinter.Format([]byte(s))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ hack for support terraform 0.12\n\tformatted = terraform12Adjustments(formatted, mapsObjects)\n\t\/\/ hack for support terraform 0.13\n\tformatted = terraform13Adjustments(formatted)\n\tif err != nil {\n\t\tlog.Println(\"Invalid HCL follows:\")\n\t\tfor i, line := range strings.Split(s, \"\\n\") {\n\t\t\tfmt.Printf(\"%4d|\\t%s\\n\", i+1, line)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"error formatting HCL: %v\", err)\n\t}\n\n\treturn formatted, nil\n}\n\nfunc terraform12Adjustments(formatted []byte, mapsObjects map[string]struct{}) []byte {\n\tsingletonListFix := regexp.MustCompile(`^\\s*\\w+ = {`)\n\tsingletonListFixEnd := regexp.MustCompile(`^\\s*}`)\n\n\ts := string(formatted)\n\told := \" = {\"\n\tnewEquals := \" {\"\n\tlines := strings.Split(s, \"\\n\")\n\tprefix := make([]string, 0)\n\tfor i, line := range lines {\n\t\tif singletonListFixEnd.MatchString(line) && len(prefix) > 0 {\n\t\t\tprefix = prefix[:len(prefix)-1]\n\t\t\tcontinue\n\t\t}\n\t\tif !singletonListFix.MatchString(line) {\n\t\t\tcontinue\n\t\t}\n\t\tkey := strings.Trim(strings.Split(line, old)[0], \" \")\n\t\tprefix = append(prefix, key)\n\t\tif _, exist := mapsObjects[strings.Join(prefix, \".\")]; exist {\n\t\t\tcontinue\n\t\t}\n\t\tlines[i] = strings.ReplaceAll(line, old, newEquals)\n\t}\n\ts = strings.Join(lines, \"\\n\")\n\treturn []byte(s)\n}\n\nfunc terraform13Adjustments(formatted []byte) []byte {\n\ts := string(formatted)\n\toldRequiredProviders := \"\\\"required_providers\\\"\"\n\tnewRequiredProviders := \"required_providers\"\n\tlines := strings.Split(s, \"\\n\")\n\tproviderRequirementDefinition := false\n\tfor i, line := range lines {\n\t\tif providerRequirementDefinition {\n\t\t\tline = strings.ReplaceAll(line, \" {\", \" = {\")\n\t\t}\n\t\tproviderRequirementDefinition = strings.Contains(line, newRequiredProviders)\n\t\tlines[i] = strings.Replace(line, oldRequiredProviders, newRequiredProviders, 1)\n\t}\n\ts = strings.Join(lines, \"\\n\")\n\treturn []byte(s)\n}\n\nfunc escapeRune(s string) string {\n\treturn fmt.Sprintf(\"-%04X-\", s)\n}\n\n\/\/ Sanitize name for terraform style\nfunc TfSanitize(name string) string {\n\tname = unsafeChars.ReplaceAllStringFunc(name, escapeRune)\n\tname = \"tfer--\" + name\n\treturn name\n}\n\n\/\/ Print hcl file from TerraformResource + provider\nfunc HclPrintResource(resources []Resource, providerData map[string]interface{}, output string) ([]byte, error) {\n\tresourcesByType := map[string]map[string]interface{}{}\n\tmapsObjects := map[string]struct{}{}\n\tindexRe := regexp.MustCompile(`\\.[0-9]+`)\n\tfor _, res := range resources {\n\t\tr := resourcesByType[res.InstanceInfo.Type]\n\t\tif r == nil {\n\t\t\tr = make(map[string]interface{})\n\t\t\tresourcesByType[res.InstanceInfo.Type] = r\n\t\t}\n\n\t\tif r[res.ResourceName] != nil {\n\t\t\tlog.Println(resources)\n\t\t\tlog.Printf(\"[ERR]: duplicate resource found: %s.%s\", res.InstanceInfo.Type, res.ResourceName)\n\t\t\tcontinue\n\t\t}\n\n\t\tr[res.ResourceName] = res.Item\n\n\t\tfor k := range res.InstanceState.Attributes {\n\t\t\tif strings.HasSuffix(k, \".%\") {\n\t\t\t\tkey := strings.TrimSuffix(k, \".%\")\n\t\t\t\tmapsObjects[indexRe.ReplaceAllString(key, \"\")] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\n\tdata := map[string]interface{}{}\n\tif len(resourcesByType) > 0 {\n\t\tdata[\"resource\"] = resourcesByType\n\t}\n\tif len(providerData) > 0 {\n\t\tdata[\"provider\"] = providerData\n\t}\n\tvar err error\n\n\thclBytes, err := Print(data, mapsObjects, output)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\treturn hclBytes, nil\n}\n<commit_msg>style: fix typo<commit_after>\/\/ Copyright 2018 The Terraformer Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage terraformutils\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/hashicorp\/hcl\/hcl\/ast\"\n\thclPrinter \"github.com\/hashicorp\/hcl\/hcl\/printer\"\n\thclParser \"github.com\/hashicorp\/hcl\/json\/parser\"\n)\n\n\/\/ Copy code from https:\/\/github.com\/kubernetes\/kops project with few changes for support many provider and heredoc\n\nconst safeChars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_\"\n\nvar unsafeChars = regexp.MustCompile(`[^0-9A-Za-z_]`)\n\n\/\/ sanitizer fixes up an invalid HCL AST, as produced by the HCL parser for JSON\ntype astSanitizer struct{}\n\n\/\/ output prints creates b printable HCL output and returns it.\nfunc (v *astSanitizer) visit(n interface{}) {\n\tswitch t := n.(type) {\n\tcase *ast.File:\n\t\tv.visit(t.Node)\n\tcase *ast.ObjectList:\n\t\tvar index int\n\t\tfor {\n\t\t\tif index == len(t.Items) {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tv.visit(t.Items[index])\n\t\t\tindex++\n\t\t}\n\tcase *ast.ObjectKey:\n\tcase *ast.ObjectItem:\n\t\tv.visitObjectItem(t)\n\tcase *ast.LiteralType:\n\tcase *ast.ListType:\n\tcase *ast.ObjectType:\n\t\tv.visit(t.List)\n\tdefault:\n\t\tfmt.Printf(\" unknown type: %T\\n\", n)\n\t}\n}\n\nfunc (v *astSanitizer) visitObjectItem(o *ast.ObjectItem) {\n\tfor i, k := range o.Keys {\n\t\tif i == 0 {\n\t\t\ttext := k.Token.Text\n\t\t\tif text != \"\" && text[0] == '\"' && text[len(text)-1] == '\"' {\n\t\t\t\tv := text[1 : len(text)-1]\n\t\t\t\tsafe := true\n\t\t\t\tfor _, c := range v {\n\t\t\t\t\tif !strings.ContainsRune(safeChars, c) {\n\t\t\t\t\t\tsafe = false\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif safe {\n\t\t\t\t\tk.Token.Text = v\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tswitch t := o.Val.(type) {\n\tcase *ast.LiteralType: \/\/ heredoc support\n\t\tif strings.HasPrefix(t.Token.Text, `\"<<`) {\n\t\t\tt.Token.Text = t.Token.Text[1:]\n\t\t\tt.Token.Text = t.Token.Text[:len(t.Token.Text)-1]\n\t\t\tt.Token.Text = strings.ReplaceAll(t.Token.Text, `\\n`, \"\\n\")\n\t\t\tt.Token.Text = strings.ReplaceAll(t.Token.Text, `\\t`, \"\")\n\t\t\tt.Token.Type = 10\n\t\t\t\/\/ check if text json for Unquote and Indent\n\t\t\ttmp := map[string]interface{}{}\n\t\t\tjsonTest := t.Token.Text\n\t\t\tlines := strings.Split(jsonTest, \"\\n\")\n\t\t\tjsonTest = strings.Join(lines[1:len(lines)-1], \"\\n\")\n\t\t\tjsonTest = strings.ReplaceAll(jsonTest, \"\\\\\\\"\", \"\\\"\")\n\t\t\t\/\/ it's json we convert to heredoc back\n\t\t\terr := json.Unmarshal([]byte(jsonTest), &tmp)\n\t\t\tif err == nil {\n\t\t\t\tdataJSONBytes, err := json.MarshalIndent(tmp, \"\", \"  \")\n\t\t\t\tif err == nil {\n\t\t\t\t\tjsonData := strings.Split(string(dataJSONBytes), \"\\n\")\n\t\t\t\t\t\/\/ first line for heredoc\n\t\t\t\t\tjsonData = append([]string{lines[0]}, jsonData...)\n\t\t\t\t\t\/\/ last line for heredoc\n\t\t\t\t\tjsonData = append(jsonData, lines[len(lines)-1])\n\t\t\t\t\thereDoc := strings.Join(jsonData, \"\\n\")\n\t\t\t\t\tt.Token.Text = hereDoc\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tdefault:\n\t}\n\n\t\/\/ A hack so that Assign.IsValid is true, so that the printer will output =\n\to.Assign.Line = 1\n\n\tv.visit(o.Val)\n}\n\nfunc Print(data interface{}, mapsObjects map[string]struct{}, format string) ([]byte, error) {\n\tswitch format {\n\tcase \"hcl\":\n\t\treturn hclPrint(data, mapsObjects)\n\tcase \"json\":\n\t\treturn jsonPrint(data)\n\t}\n\treturn []byte{}, errors.New(\"error: unknown output format\")\n}\n\nfunc hclPrint(data interface{}, mapsObjects map[string]struct{}) ([]byte, error) {\n\tdataBytesJSON, err := jsonPrint(data)\n\tif err != nil {\n\t\treturn dataBytesJSON, err\n\t}\n\tdataJSON := string(dataBytesJSON)\n\tnodes, err := hclParser.Parse([]byte(dataJSON))\n\tif err != nil {\n\t\tlog.Println(dataJSON)\n\t\treturn []byte{}, fmt.Errorf(\"error parsing terraform json: %v\", err)\n\t}\n\tvar sanitizer astSanitizer\n\tsanitizer.visit(nodes)\n\n\tvar b bytes.Buffer\n\terr = hclPrinter.Fprint(&b, nodes)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error writing HCL: %v\", err)\n\t}\n\ts := b.String()\n\n\t\/\/ Remove extra whitespace...\n\ts = strings.ReplaceAll(s, \"\\n\\n\", \"\\n\")\n\n\t\/\/ ...but leave whitespace between resources\n\ts = strings.ReplaceAll(s, \"}\\nresource\", \"}\\n\\nresource\")\n\n\t\/\/ Apply Terraform style (alignment etc.)\n\tformatted, err := hclPrinter.Format([]byte(s))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ hack for support terraform 0.12\n\tformatted = terraform12Adjustments(formatted, mapsObjects)\n\t\/\/ hack for support terraform 0.13\n\tformatted = terraform13Adjustments(formatted)\n\tif err != nil {\n\t\tlog.Println(\"Invalid HCL follows:\")\n\t\tfor i, line := range strings.Split(s, \"\\n\") {\n\t\t\tfmt.Printf(\"%4d|\\t%s\\n\", i+1, line)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"error formatting HCL: %v\", err)\n\t}\n\n\treturn formatted, nil\n}\n\nfunc terraform12Adjustments(formatted []byte, mapsObjects map[string]struct{}) []byte {\n\tsingletonListFix := regexp.MustCompile(`^\\s*\\w+ = {`)\n\tsingletonListFixEnd := regexp.MustCompile(`^\\s*}`)\n\n\ts := string(formatted)\n\told := \" = {\"\n\tnewEquals := \" {\"\n\tlines := strings.Split(s, \"\\n\")\n\tprefix := make([]string, 0)\n\tfor i, line := range lines {\n\t\tif singletonListFixEnd.MatchString(line) && len(prefix) > 0 {\n\t\t\tprefix = prefix[:len(prefix)-1]\n\t\t\tcontinue\n\t\t}\n\t\tif !singletonListFix.MatchString(line) {\n\t\t\tcontinue\n\t\t}\n\t\tkey := strings.Trim(strings.Split(line, old)[0], \" \")\n\t\tprefix = append(prefix, key)\n\t\tif _, exist := mapsObjects[strings.Join(prefix, \".\")]; exist {\n\t\t\tcontinue\n\t\t}\n\t\tlines[i] = strings.ReplaceAll(line, old, newEquals)\n\t}\n\ts = strings.Join(lines, \"\\n\")\n\treturn []byte(s)\n}\n\nfunc terraform13Adjustments(formatted []byte) []byte {\n\ts := string(formatted)\n\toldRequiredProviders := \"\\\"required_providers\\\"\"\n\tnewRequiredProviders := \"required_providers\"\n\tlines := strings.Split(s, \"\\n\")\n\tproviderRequirementDefinition := false\n\tfor i, line := range lines {\n\t\tif providerRequirementDefinition {\n\t\t\tline = strings.ReplaceAll(line, \" {\", \" = {\")\n\t\t}\n\t\tproviderRequirementDefinition = strings.Contains(line, newRequiredProviders)\n\t\tlines[i] = strings.Replace(line, oldRequiredProviders, newRequiredProviders, 1)\n\t}\n\ts = strings.Join(lines, \"\\n\")\n\treturn []byte(s)\n}\n\nfunc escapeRune(s string) string {\n\treturn fmt.Sprintf(\"-%04X-\", s)\n}\n\n\/\/ Sanitize name for terraform style\nfunc TfSanitize(name string) string {\n\tname = unsafeChars.ReplaceAllStringFunc(name, escapeRune)\n\tname = \"tfer--\" + name\n\treturn name\n}\n\n\/\/ Print hcl file from TerraformResource + provider\nfunc HclPrintResource(resources []Resource, providerData map[string]interface{}, output string) ([]byte, error) {\n\tresourcesByType := map[string]map[string]interface{}{}\n\tmapsObjects := map[string]struct{}{}\n\tindexRe := regexp.MustCompile(`\\.[0-9]+`)\n\tfor _, res := range resources {\n\t\tr := resourcesByType[res.InstanceInfo.Type]\n\t\tif r == nil {\n\t\t\tr = make(map[string]interface{})\n\t\t\tresourcesByType[res.InstanceInfo.Type] = r\n\t\t}\n\n\t\tif r[res.ResourceName] != nil {\n\t\t\tlog.Println(resources)\n\t\t\tlog.Printf(\"[ERR]: duplicate resource found: %s.%s\", res.InstanceInfo.Type, res.ResourceName)\n\t\t\tcontinue\n\t\t}\n\n\t\tr[res.ResourceName] = res.Item\n\n\t\tfor k := range res.InstanceState.Attributes {\n\t\t\tif strings.HasSuffix(k, \".%\") {\n\t\t\t\tkey := strings.TrimSuffix(k, \".%\")\n\t\t\t\tmapsObjects[indexRe.ReplaceAllString(key, \"\")] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\n\tdata := map[string]interface{}{}\n\tif len(resourcesByType) > 0 {\n\t\tdata[\"resource\"] = resourcesByType\n\t}\n\tif len(providerData) > 0 {\n\t\tdata[\"provider\"] = providerData\n\t}\n\tvar err error\n\n\thclBytes, err := Print(data, mapsObjects, output)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\treturn hclBytes, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package tachymeter\n\nimport (\n\t\"sort\"\n\t\"time\"\n)\n\n\/\/ Satisfy sort for timeSlice.\n\/\/ Sorts in increasing order of duration.\n\nfunc (p timeSlice) Len() int {\n\treturn len(p)\n}\n\nfunc (p timeSlice) Less(i, j int) bool {\n\treturn int64(p[i]) < int64(p[j])\n}\n\nfunc (p timeSlice) Swap(i, j int) {\n\tp[i], p[j] = p[j], p[i]\n}\n\n\/\/ Calc calcs data held in a *Tachymeter\n\/\/ and returns a *Metrics.\nfunc (m *Tachymeter) Calc() *Metrics {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tmetrics := &Metrics{}\n\tif m.Count == 0 {\n\t\treturn metrics\n\t}\n\n\ttimes := m.Times[:m.TimesUsed]\n\tsort.Sort(times)\n\n\tmetrics.Samples = m.TimesUsed\n\tmetrics.Count = m.Count\n\tmetrics.Time.Total = calcTimeTotal(times)\n\tmetrics.Time.Avg = calcAvg(times, metrics.Samples)\n\tmetrics.Time.Median = times[len(times)\/2]\n\tmetrics.Time.P95 = calcP95(times)\n\tmetrics.Time.Long5p = calcLong5p(times)\n\tmetrics.Time.Short5p = calcShort5p(times)\n\tmetrics.Time.Max = times[metrics.Samples-1]\n\tmetrics.Time.Min = times[0]\n\n\tvar rateTime float64\n\tif m.WallTime != 0 {\n\t\trateTime = float64(metrics.Count) \/ float64(m.WallTime)\n\t} else {\n\t\trateTime = float64(metrics.Samples) \/ float64(metrics.Time.Total)\n\t}\n\tmetrics.Rate.Second = rateTime * 1e9\n\n\treturn metrics\n}\n\n\/\/ These should be self-explanatory:\n\nfunc calcTimeTotal(d []time.Duration) time.Duration {\n\tvar total time.Duration\n\tfor _, t := range d {\n\t\ttotal += t\n\t}\n\n\treturn total\n}\n\nfunc calcAvg(d []time.Duration, c int) time.Duration {\n\tvar total time.Duration\n\tfor _, t := range d {\n\t\ttotal += t\n\t}\n\treturn time.Duration(int(total) \/ c)\n}\n\nfunc calcP95(d []time.Duration) time.Duration {\n\treturn d[int(float64(len(d))*0.95+0.5)-1]\n}\n\nfunc calcLong5p(d []time.Duration) time.Duration {\n\tset := d[int(float64(len(d))*0.95+0.5)-1:]\n\n\tif len(set) == 0 {\n\t\treturn d[len(d)-1]\n\t}\n\n\tvar t time.Duration\n\tvar i int\n\tfor _, n := range set {\n\t\tt += n\n\t\ti++\n\t}\n\n\treturn time.Duration(int(t) \/ i)\n}\n\nfunc calcShort5p(d []time.Duration) time.Duration {\n\tset := d[:int(float64(len(d))*0.05+0.5)]\n\n\tif len(set) == 0 {\n\t\treturn d[0]\n\t}\n\n\tvar t time.Duration\n\tvar i int\n\tfor _, n := range set {\n\t\tt += n\n\t\ti++\n\t}\n\n\treturn time.Duration(int(t) \/ i)\n}\n<commit_msg>range fix<commit_after>package tachymeter\n\nimport (\n\t\"sort\"\n\t\"time\"\n)\n\n\/\/ Satisfy sort for timeSlice.\n\/\/ Sorts in increasing order of duration.\n\nfunc (p timeSlice) Len() int {\n\treturn len(p)\n}\n\nfunc (p timeSlice) Less(i, j int) bool {\n\treturn int64(p[i]) < int64(p[j])\n}\n\nfunc (p timeSlice) Swap(i, j int) {\n\tp[i], p[j] = p[j], p[i]\n}\n\n\/\/ Calc calcs data held in a *Tachymeter\n\/\/ and returns a *Metrics.\nfunc (m *Tachymeter) Calc() *Metrics {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\tmetrics := &Metrics{}\n\tif m.Count == 0 {\n\t\treturn metrics\n\t}\n\n\ttimes := m.Times[:m.TimesUsed]\n\tsort.Sort(times)\n\n\tmetrics.Samples = m.TimesUsed\n\tmetrics.Count = m.Count\n\tmetrics.Time.Total = calcTimeTotal(times)\n\tmetrics.Time.Avg = calcAvg(times, metrics.Samples)\n\tmetrics.Time.Median = times[len(times)\/2]\n\tmetrics.Time.P95 = calcP95(times)\n\tmetrics.Time.Long5p = calcLong5p(times)\n\tmetrics.Time.Short5p = calcShort5p(times)\n\tmetrics.Time.Max = times[metrics.Samples-1]\n\tmetrics.Time.Min = times[0]\n\n\tvar rateTime float64\n\tif m.WallTime != 0 {\n\t\trateTime = float64(metrics.Count) \/ float64(m.WallTime)\n\t} else {\n\t\trateTime = float64(metrics.Samples) \/ float64(metrics.Time.Total)\n\t}\n\tmetrics.Rate.Second = rateTime * 1e9\n\n\treturn metrics\n}\n\n\/\/ These should be self-explanatory:\n\nfunc calcTimeTotal(d []time.Duration) time.Duration {\n\tvar total time.Duration\n\tfor _, t := range d {\n\t\ttotal += t\n\t}\n\n\treturn total\n}\n\nfunc calcAvg(d []time.Duration, c int) time.Duration {\n\tvar total time.Duration\n\tfor _, t := range d {\n\t\ttotal += t\n\t}\n\treturn time.Duration(int(total) \/ c)\n}\n\nfunc calcP95(d []time.Duration) time.Duration {\n\treturn d[int(float64(len(d))*0.95+0.5)-1]\n}\n\nfunc calcLong5p(d []time.Duration) time.Duration {\n\tset := d[int(float64(len(d))*0.95+0.5):]\n\n\tif len(set) <= 1 {\n\t\treturn d[len(d)-1]\n\t}\n\n\tvar t time.Duration\n\tvar i int\n\tfor _, n := range set {\n\t\tt += n\n\t\ti++\n\t}\n\n\treturn time.Duration(int(t) \/ i)\n}\n\nfunc calcShort5p(d []time.Duration) time.Duration {\n\tset := d[:int(float64(len(d))*0.05+0.5)]\n\n\tif len(set) <= 1 {\n\t\treturn d[0]\n\t}\n\n\tvar t time.Duration\n\tvar i int\n\tfor _, n := range set {\n\t\tt += n\n\t\ti++\n\t}\n\n\treturn time.Duration(int(t) \/ i)\n}\n<|endoftext|>"}
{"text":"<commit_before>package version\n\nimport (\n\t\"fmt\"\n\t\"github.com\/majestrate\/XD\/lib\/constants\"\n)\n\nconst Name = \"XD\"\n\nvar Major = \"0\"\n\nvar Minor = \"3\"\n\nvar Patch = \"4\"\n\nvar Git string\n\nfunc Version() string {\n\tv := fmt.Sprintf(\"%s-%s.%s.%s\", Name, Major, Minor, Patch)\n\tif len(Git) > 0 && constants.UseGitVersion {\n\t\tv += fmt.Sprintf(\"-%s\", Git)\n\t}\n\treturn v\n}\n<commit_msg>bump version<commit_after>package version\n\nimport (\n\t\"fmt\"\n\t\"github.com\/majestrate\/XD\/lib\/constants\"\n)\n\nconst Name = \"XD\"\n\nvar Major = \"0\"\n\nvar Minor = \"4\"\n\nvar Patch = \"0\"\n\nvar Git string\n\nfunc Version() string {\n\tv := fmt.Sprintf(\"%s-%s.%s.%s\", Name, Major, Minor, Patch)\n\tif len(Git) > 0 && constants.UseGitVersion {\n\t\tv += fmt.Sprintf(\"-%s\", Git)\n\t}\n\treturn v\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package chalk lets you colour your terminal string\n\/\/ styles. There are three things you can do so far:\n\/\/\n\/\/\n\/\/ Change the string's colour\n\/\/\n\/\/ There are eight colours: black, red, green, yellow,\n\/\/ blue, magenta, cyan and white. They are extremely easy\n\/\/ to use:\n\/\/\n\/\/   fmt.Println(chalk.Blue(\"This is blue text!\"))\n\/\/\n\/\/\n\/\/ Change the string's background colour\n\/\/\n\/\/ There are the same eight background colours. They can\n\/\/ be used by doing:\n\/\/\n\/\/   fmt.Println(chalk.BgBlue(\"The background of this text is blue.\"))\n\/\/\n\/\/\n\/\/ Underline\n\/\/\n\/\/ You can easily underline some text by doing:\n\/\/\n\/\/   fmt.Println(chalk.Underline(\"Here is some underlined text.\"))\n\/\/\n\/\/ That's it! It's pretty simple, but I hope to add more\n\/\/ more styles and options in the near future.\n\/\/\npackage chalk\n\ntype fg string\ntype bg string\ntype ul string\n\nfunc (f *fg) BgRed(s string) string {\n\treturn BgRed(Red(s))\n}\n\n\/\/ Black colours your string black\nfunc Black(s string) string {\n\treturn \"\\033[30m\" + s + \"\\033[0m\"\n}\n\n\/\/ Red colours your string red\nfunc Red(s string) string {\n\treturn \"\\033[31m\" + s + \"\\033[0m\"\n}\n\n\/\/ Green colours your string green\nfunc Green(s string) string {\n\treturn \"\\033[32m\" + s + \"\\033[0m\"\n}\n\n\/\/ Yellow colours your string yellow\nfunc Yellow(s string) string {\n\treturn \"\\033[33m\" + s + \"\\033[0m\"\n}\n\n\/\/ Blue colours your string blue\nfunc Blue(s string) string {\n\treturn \"\\033[34m\" + s + \"\\033[0m\"\n}\n\n\/\/ Magenta colours your string magenta\nfunc Magenta(s string) string {\n\treturn \"\\033[35m\" + s + \"\\033[0m\"\n}\n\n\/\/ Cyan colours your string cyan\nfunc Cyan(s string) string {\n\treturn \"\\033[36m\" + s + \"\\033[0m\"\n}\n\n\/\/ White colours your string white\nfunc White(s string) string {\n\treturn \"\\033[37m\" + s + \"\\033[0m\"\n}\n\n\/\/ Underline places an underline under your string\nfunc Underline(s string) string {\n\treturn \"\\u001b[4m\" + s + \"\\u001b[24m\"\n}\n\n\/\/ BgBlack colours the background of your string black\nfunc BgBlack(s string) string {\n\treturn \"\\u001b[40m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgRed colours the background of your string red\nfunc BgRed(s string) string {\n\treturn \"\\u001b[41m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgGreen colours the background of your strinYellowreen\nfunc BgGreen(s string) string {\n\treturn \"\\u001b[42m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgYellow colours the background of your string yellow\nfunc BgYellow(s string) string {\n\treturn \"\\u001b[43m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgBlue colours the background of your string blue\nfunc BgBlue(s string) string {\n\treturn \"\\u001b[44m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgMagenta colours the background of your string magenta\nfunc BgMagenta(s string) string {\n\treturn \"\\u001b[45m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgCyan colours the background of your string cyan\nfunc BgCyan(s string) string {\n\treturn \"\\u001b[46m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgWhite colours the background of your string white\nfunc BgWhite(s string) string {\n\treturn \"\\u001b[47m\" + s + \"\\u001b[49m\"\n}\n<commit_msg>Remove weird stuff<commit_after>\/\/ Package chalk lets you colour your terminal string\n\/\/ styles. There are three things you can do so far:\n\/\/\n\/\/\n\/\/ Change the string's colour\n\/\/\n\/\/ There are eight colours: black, red, green, yellow,\n\/\/ blue, magenta, cyan and white. They are extremely easy\n\/\/ to use:\n\/\/\n\/\/   fmt.Println(chalk.Blue(\"This is blue text!\"))\n\/\/\n\/\/\n\/\/ Change the string's background colour\n\/\/\n\/\/ There are the same eight background colours. They can\n\/\/ be used by doing:\n\/\/\n\/\/   fmt.Println(chalk.BgBlue(\"The background of this text is blue.\"))\n\/\/\n\/\/\n\/\/ Underline\n\/\/\n\/\/ You can easily underline some text by doing:\n\/\/\n\/\/   fmt.Println(chalk.Underline(\"Here is some underlined text.\"))\n\/\/\n\/\/ That's it! It's pretty simple, but I hope to add more\n\/\/ more styles and options in the near future.\n\/\/\npackage chalk\n\n\/\/ Black colours your string black\nfunc Black(s string) string {\n\treturn \"\\033[30m\" + s + \"\\033[0m\"\n}\n\n\/\/ Red colours your string red\nfunc Red(s string) string {\n\treturn \"\\033[31m\" + s + \"\\033[0m\"\n}\n\n\/\/ Green colours your string green\nfunc Green(s string) string {\n\treturn \"\\033[32m\" + s + \"\\033[0m\"\n}\n\n\/\/ Yellow colours your string yellow\nfunc Yellow(s string) string {\n\treturn \"\\033[33m\" + s + \"\\033[0m\"\n}\n\n\/\/ Blue colours your string blue\nfunc Blue(s string) string {\n\treturn \"\\033[34m\" + s + \"\\033[0m\"\n}\n\n\/\/ Magenta colours your string magenta\nfunc Magenta(s string) string {\n\treturn \"\\033[35m\" + s + \"\\033[0m\"\n}\n\n\/\/ Cyan colours your string cyan\nfunc Cyan(s string) string {\n\treturn \"\\033[36m\" + s + \"\\033[0m\"\n}\n\n\/\/ White colours your string white\nfunc White(s string) string {\n\treturn \"\\033[37m\" + s + \"\\033[0m\"\n}\n\n\/\/ Underline places an underline under your string\nfunc Underline(s string) string {\n\treturn \"\\u001b[4m\" + s + \"\\u001b[24m\"\n}\n\n\/\/ BgBlack colours the background of your string black\nfunc BgBlack(s string) string {\n\treturn \"\\u001b[40m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgRed colours the background of your string red\nfunc BgRed(s string) string {\n\treturn \"\\u001b[41m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgGreen colours the background of your strinYellowreen\nfunc BgGreen(s string) string {\n\treturn \"\\u001b[42m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgYellow colours the background of your string yellow\nfunc BgYellow(s string) string {\n\treturn \"\\u001b[43m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgBlue colours the background of your string blue\nfunc BgBlue(s string) string {\n\treturn \"\\u001b[44m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgMagenta colours the background of your string magenta\nfunc BgMagenta(s string) string {\n\treturn \"\\u001b[45m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgCyan colours the background of your string cyan\nfunc BgCyan(s string) string {\n\treturn \"\\u001b[46m\" + s + \"\\u001b[49m\"\n}\n\n\/\/ BgWhite colours the background of your string white\nfunc BgWhite(s string) string {\n\treturn \"\\u001b[47m\" + s + \"\\u001b[49m\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"net\/url\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\t\"github.com\/bradfitz\/gomemcache\/memcache\"\n\t\"github.com\/BurntSushi\/toml\"\n)\n\ntype Config struct {\n\tUpstream string\n\tReqFanFactor int\n\tTimeoutMS int\n\tMemcacheHosts []string\n\tMemcacheSeconds int\n}\n\nfunc snd (c chan string, s string) {\n\tgo func () { c <- s }()\n}\n\n\/\/ start starts Charm up and returns a done channel for the done message\nfunc start(confPath string) (chan string) {\n\tdone := make(chan string)\n\n\t\/\/ print a welcome message\n\tlog.Print(\"Charm is starting up.\")\n\t\/\/ read the config file\n\tlog.Printf(\".   . Reading %s\", confPath)\n\ttomlData, err := ioutil.ReadFile(confPath)\n\tif err != nil {\n\t\tsnd(done, fmt.Sprintf(\"Could not read file at %s\", confPath))\n\t\treturn done\n\t}\n\t\/\/ populate the config struct\n\tlog.Print(\".   . Loading config\")\n\tvar conf Config\n\t_, err = toml.Decode(string(tomlData), &conf)\n\tif err != nil {\n\t\tsnd(done, \"Could not decode config\")\n\t\treturn done\n\t}\n\t\/\/ report on the configuration\n\tlog.Print(\"Charm is configured!\")\n\tlog.Printf(\".   . Stabilizing %v\", conf.Upstream)\n\tlog.Printf(\".   . with %v duplicate requests\", conf.ReqFanFactor)\n\tlog.Printf(\".   . and a %v milisecond timeout.\", conf.TimeoutMS)\n\tlog.Printf(\n\t\t\".   . memcached at %v for %v seconds.\",\n\t\tconf.MemcacheHosts,\n\t\tconf.MemcacheSeconds,\n\t)\n\tgo run(conf, done)\n\treturn done\n}\n\ntype stableTransport struct {\n\twrappedTransport http.RoundTripper\n\treqFanFactor int\n\tcacheResponse chan *http.Response\n}\n\n\/\/ stableTransport.RoundTrip makes many round trips and returns the first\n\/\/ response\nfunc (t *stableTransport) RoundTrip(r *http.Request) (*http.Response, error) {\n\tc := make(chan *http.Response)\n\tif t.wrappedTransport == nil {\n\t\tt.wrappedTransport = http.DefaultTransport\n\t}\n\t\/\/ fan out requests, send responses to the channel, log errors, don't\n\t\/\/ wait very long for someone to recieve our response\n\tfor i := 0; i < t.reqFanFactor; i++ {\n\t\tgo func () {\n\t\t\tresp, err := t.wrappedTransport.RoundTrip(r)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"transport-error: %v\", err)\n\t\t\t} else {\n\t\t\t\tselect {\n\t\t\t\tcase c <- resp:\n\t\t\t\t\t\/\/ they were still waiting for the first\n\t\t\t\t\t\/\/ response and they recieved it from c\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(1 * time.Millisecond):\n\t\t\t\t\t\/\/ no one was waiting to recieve from c\n\t\t\t\t\t\/\/ so this is not the first response\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\t\/\/ wait to reviece the first response\n\tfirst := <-c\n\t\/\/ copy the first respnse for caching\n\tcacheCopy := new(http.Response)\n\t*cacheCopy = *first\n\tif first.Body != nil {\n\t\tbodyBytes, err := ioutil.ReadAll(first.Body)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error reading response body:\", err)\n\t\t}\n\t\tcacheBytes := make([]byte, len(bodyBytes))\n\t\tcopy(cacheBytes, bodyBytes)\n\t\tfirst.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))\n\t\tcacheCopy.Body = ioutil.NopCloser(bytes.NewBuffer(cacheBytes))\n\t}\n\t\/\/ send the copy to be cached if they want it\n\tgo func () {\n\t\tselect {\n\t\tcase t.cacheResponse <- cacheCopy:\n\t\t\treturn\n\t\tcase <-time.After(15 * time.Millisecond):\n\t\t\treturn\n\t\t}\n\t}()\n\t\/\/ return the first response to the handler\n\treturn first, nil\n}\n\n\/\/ cacheKey returns a string to be used as the cache key for a request\nfunc cacheKey(r *http.Request) (string, error) {\n\t\/\/ We need to be careful here.\n\t\/\/ There is serious potential to accidently ignore permissions if we\n\t\/\/ cache requests too broadly. For example, if our cache key is the path\n\t\/\/ and a super-admin cache-misses on \/some\/restricted\/path then a\n\t\/\/ restricted user could be given the cached result from that super\n\t\/\/  admin request.\n\n\tkeyStr := \"\"\n\tkeyStr += r.Method\n\tkeyStr += r.URL.Host\n\tkeyStr += r.URL.Path\n\tkeyStr += r.URL.RawQuery\n\n\t\/\/ TODO: extract which headers to cache on into a config option\n\tkeyStr += r.Header[\"X-Forwarded-Email\"][0]\n\n\tkey := sha256.Sum224([]byte(keyStr))\n\treturn hex.EncodeToString(key[:sha256.Size224]), nil\n}\n\n\/\/ copyHeader copies headers to the des from the src\n\/\/ this code is copied from the reverse proxy library in go\nfunc copyHeader(dst, src http.Header) {\n\tfor k, vv := range src {\n\t\tfor _, v := range vv {\n\t\t\tdst.Add(k, v)\n\t\t}\n\t}\n}\n\n\/\/ copyTrailer builds up the trailer header from Trailer\n\/\/ this code is copied from the reverse proxy library in go\nfunc copyTrailer(w http.ResponseWriter, r *http.Response) {\n\tif len(r.Trailer) > 0 {\n\t\tvar trailerKeys []string\n\t\tfor k := range r.Trailer {\n\t\t\ttrailerKeys = append(trailerKeys, k)\n\t\t}\n\t\tw.Header().Add(\"Trailer\", strings.Join(trailerKeys, \", \"))\n\t}\n}\n\n\/\/ Conf.ServeHTTP checks memcache then proxies\/caches with a stable transport\nfunc (conf Config) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\t\/\/ check memcache\n\tmc := memcache.New(conf.MemcacheHosts...)\n\tkey, err := cacheKey(r)\n\tif err != nil {\n\t\tlog.Println(\"cache key error for Request:\", r)\n\t} else {\n\t\titem, err := mc.Get(key)\n\t\tif err == nil { \/\/cache hit\n\t\t\tlog.Println(\n\t\t\t\t\"INFO: cache hit\",\n\t\t\t\tr.Method,\n\t\t\t\tr.URL.Host,\n\t\t\t\tr.URL.Path,\n\t\t\t\tr.URL.RawQuery,\n\t\t\t\tr.Header[\"X-Forwarded-Email\"],\n\t\t\t)\n\t\t\t\/\/ get the cached response\n\t\t\tresponse, err := http.ReadResponse(\n\t\t\t\tbufio.NewReader(bytes.NewReader(item.Value)),\n\t\t\t\tr,\n\t\t\t)\n\t\t\tif err == nil {\n\t\t\t\t\/\/ get the bytes out of the body first so if\n\t\t\t\t\/\/ if there is an error we aren't half way into\n\t\t\t\t\/\/ responding when we call it a cache miss\n\t\t\t\tbodyBytes, err := ioutil.ReadAll(response.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"could not read cached response\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t\/\/ respond with the cached response\n\t\t\t\t\/\/ copy the headers to the response writer\n\t\t\t\tcopyHeader(w.Header(), response.Header)\n\t\t\t\tcopyTrailer(w, response)\n\t\t\t\tw.WriteHeader(response.StatusCode)\n\t\t\t\t\/\/ from reverse proxy code in go\n\t\t\t\tif len(response.Trailer) > 0 {\n\t\t\t\t\t\/\/ Forse chunking if we saw a trailer.\n\t\t\t\t\t\/\/ Prevents net\/http from calculating\n\t\t\t\t\t\/\/ length for short bodies and adding\n\t\t\t\t\t\/\/ Content-Length.\n\t\t\t\t\tif fl, ok := w.(http.Flusher); ok {\n\t\t\t\t\t\tfl.Flush()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tw.Write(bodyBytes)\n\t\t\t\tresponse.Body.Close()\n\t\t\t\t\/\/ copy trailers like in go reverse proxy lib\n\t\t\t\tcopyHeader(w.Header(), response.Trailer)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ cache miss\n\tlog.Println(\n\t\t\"INFO: cache miss\",\n\t\tr.Method,\n\t\tr.URL.Host,\n\t\tr.URL.Path,\n\t\tr.URL.RawQuery,\n\t\tr.Header[\"X-Forwarded-Email\"],\n\t)\n\tupstreamURL, err := url.Parse(conf.Upstream)\n\tif err != nil {\n\t\tlog.Fatal(\"error parsing Upstream URL\", conf.Upstream)\n\t}\n\tresponseChan := make(chan *http.Response)\n\tproxy := httputil.NewSingleHostReverseProxy(upstreamURL)\n\tproxy.Transport = &stableTransport{\n\t\tproxy.Transport,\n\t\tconf.ReqFanFactor,\n\t\tresponseChan,\n\t}\n\tproxy.ServeHTTP(w, r)\n\n\t\/\/ if the transport has a response waiting on the channel, cache it if\n\t\/\/ we have a cache\n\tif cacheKey != nil {\n\t\tselect {\n\t\tcase resp := <- responseChan:\n\t\t\tdump, err := httputil.DumpResponse(resp, true)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\n\t\t\t\t\t\"ERROR: couldn't dump response:\",\n\t\t\t\t\terr,\n\t\t\t\t)\n\t\t\t\treturn\n\t\t\t}\n\t\t\titem := &memcache.Item{\n\t\t\t\tKey: key,\n\t\t\t\tValue: dump,\n\t\t\t\tExpiration: int32(conf.MemcacheSeconds),\n\t\t\t}\n\t\t\terr = mc.Set(item)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"ERROR: memcached set error:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-time.After(1 * time.Millisecond):\n\t\t\treturn\n\t\t}\n\t}\n\n}\n\n\/\/ run\nfunc run(conf Config, done chan string) {\n\t\/\/ serve the config under a timeout\n\ttimeout := time.Duration(conf.TimeoutMS) * time.Millisecond\n\tlog.Fatal(http.ListenAndServe(\n\t\t\":8000\",\n\t\thttp.TimeoutHandler(conf, timeout, \"upstream timeout\"),\n\t))\n}\n\nfunc main() {\n\t\/\/ start Charm,\n\tdone := start(\"\/secret\/charm.conf\")\n\tstop := make(chan bool)\n\t\/\/ start some logging of the number of goroutines\n\tgo func() {\n\t\tlog.Println(\n\t\t\t\"Charm is currently using\",\n\t\t\truntime.NumGoroutine(),\n\t\t\t\"goroutines.\",\n\t\t)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-time.After(10 * time.Minute):\n\t\t\t\tlog.Println(\n\t\t\t\t\t\"Charm is currently using\",\n\t\t\t\t\truntime.NumGoroutine(),\n\t\t\t\t\t\"goroutines.\",\n\t\t\t\t)\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\t\/\/ when Charm is done, log the message and quit.\n        log.Print(<-done)\n\tclose(stop)\n}\n<commit_msg>adds comments for clarity of strategy<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"net\/url\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\t\"github.com\/bradfitz\/gomemcache\/memcache\"\n\t\"github.com\/BurntSushi\/toml\"\n)\n\ntype Config struct {\n\tUpstream string\n\tReqFanFactor int\n\tTimeoutMS int\n\tMemcacheHosts []string\n\tMemcacheSeconds int\n}\n\nfunc snd (c chan string, s string) {\n\tgo func () { c <- s }()\n}\n\n\/\/ start starts Charm up and returns a done channel for the done message\nfunc start(confPath string) (chan string) {\n\tdone := make(chan string)\n\n\t\/\/ print a welcome message\n\tlog.Print(\"Charm is starting up.\")\n\t\/\/ read the config file\n\tlog.Printf(\".   . Reading %s\", confPath)\n\ttomlData, err := ioutil.ReadFile(confPath)\n\tif err != nil {\n\t\tsnd(done, fmt.Sprintf(\"Could not read file at %s\", confPath))\n\t\treturn done\n\t}\n\t\/\/ populate the config struct\n\tlog.Print(\".   . Loading config\")\n\tvar conf Config\n\t_, err = toml.Decode(string(tomlData), &conf)\n\tif err != nil {\n\t\tsnd(done, \"Could not decode config\")\n\t\treturn done\n\t}\n\t\/\/ report on the configuration\n\tlog.Print(\"Charm is configured!\")\n\tlog.Printf(\".   . Stabilizing %v\", conf.Upstream)\n\tlog.Printf(\".   . with %v duplicate requests\", conf.ReqFanFactor)\n\tlog.Printf(\".   . and a %v milisecond timeout.\", conf.TimeoutMS)\n\tlog.Printf(\n\t\t\".   . memcached at %v for %v seconds.\",\n\t\tconf.MemcacheHosts,\n\t\tconf.MemcacheSeconds,\n\t)\n\tgo run(conf, done)\n\treturn done\n}\n\ntype stableTransport struct {\n\t\/\/ wrappedTransport: the transport we are stabilizing\n\twrappedTransport http.RoundTripper\n\t\/\/ reqFanFactor: how many times to duplicate the request\n\treqFanFactor int\n\t\/\/ cacheResponse: a channel whose reciever caches responses sent\n\tcacheResponse chan *http.Response\n}\n\n\/\/ stableTransport.RoundTrip makes many round trips and returns the first\n\/\/ response\nfunc (t *stableTransport) RoundTrip(r *http.Request) (*http.Response, error) {\n\tc := make(chan *http.Response)\n\tif t.wrappedTransport == nil {\n\t\tt.wrappedTransport = http.DefaultTransport\n\t}\n\t\/\/ fan out requests, send responses to the channel, log errors, don't\n\t\/\/ wait very long for someone to recieve our response\n\tfor i := 0; i < t.reqFanFactor; i++ {\n\t\tgo func () {\n\t\t\tresp, err := t.wrappedTransport.RoundTrip(r)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"transport-error: %v\", err)\n\t\t\t} else {\n\t\t\t\tselect {\n\t\t\t\tcase c <- resp:\n\t\t\t\t\t\/\/ they were still waiting for the first\n\t\t\t\t\t\/\/ response and they recieved it from c\n\t\t\t\t\treturn\n\t\t\t\tcase <-time.After(1 * time.Millisecond):\n\t\t\t\t\t\/\/ no one was waiting to recieve from c\n\t\t\t\t\t\/\/ so this is not the first response\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\t\/\/ wait to reviece the first response\n\tfirst := <-c\n\t\/\/ copy the first respnse for caching\n\tcacheCopy := new(http.Response)\n\t*cacheCopy = *first\n\tif first.Body != nil {\n\t\tbodyBytes, err := ioutil.ReadAll(first.Body)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error reading response body:\", err)\n\t\t}\n\t\tcacheBytes := make([]byte, len(bodyBytes))\n\t\tcopy(cacheBytes, bodyBytes)\n\t\tfirst.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))\n\t\tcacheCopy.Body = ioutil.NopCloser(bytes.NewBuffer(cacheBytes))\n\t}\n\t\/\/ send the copy to be cached if they want it\n\tgo func () {\n\t\tselect {\n\t\tcase t.cacheResponse <- cacheCopy:\n\t\t\treturn\n\t\tcase <-time.After(15 * time.Millisecond):\n\t\t\treturn\n\t\t}\n\t}()\n\t\/\/ return the first response to the handler\n\treturn first, nil\n}\n\n\/\/ cacheKey returns a string to be used as the cache key for a request\nfunc cacheKey(r *http.Request) (string, error) {\n\t\/\/ We need to be careful here.\n\t\/\/ There is serious potential to accidently ignore permissions if we\n\t\/\/ cache requests too broadly. For example, if our cache key is the path\n\t\/\/ and a super-admin cache-misses on \/some\/restricted\/path then a\n\t\/\/ restricted user could be given the cached result from that super\n\t\/\/  admin request.\n\n\tkeyStr := \"\"\n\tkeyStr += r.Method\n\tkeyStr += r.URL.Host\n\tkeyStr += r.URL.Path\n\tkeyStr += r.URL.RawQuery\n\n\t\/\/ TODO: extract which headers to cache on into a config option\n\tkeyStr += r.Header[\"X-Forwarded-Email\"][0]\n\n\tkey := sha256.Sum224([]byte(keyStr))\n\treturn hex.EncodeToString(key[:sha256.Size224]), nil\n}\n\n\/\/ copyHeader copies headers to the des from the src\n\/\/ this code is copied from the reverse proxy library in go\nfunc copyHeader(dst, src http.Header) {\n\tfor k, vv := range src {\n\t\tfor _, v := range vv {\n\t\t\tdst.Add(k, v)\n\t\t}\n\t}\n}\n\n\/\/ copyTrailer builds up the trailer header from Trailer\n\/\/ this code is copied from the reverse proxy library in go\nfunc copyTrailer(w http.ResponseWriter, r *http.Response) {\n\tif len(r.Trailer) > 0 {\n\t\tvar trailerKeys []string\n\t\tfor k := range r.Trailer {\n\t\t\ttrailerKeys = append(trailerKeys, k)\n\t\t}\n\t\tw.Header().Add(\"Trailer\", strings.Join(trailerKeys, \", \"))\n\t}\n}\n\n\/\/ Conf.ServeHTTP checks memcache then proxies\/caches with a stable transport\nfunc (conf Config) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\t\/\/ check memcache\n\tmc := memcache.New(conf.MemcacheHosts...)\n\tkey, err := cacheKey(r)\n\tif err != nil {\n\t\tlog.Println(\"cache key error for Request:\", r)\n\t} else {\n\t\titem, err := mc.Get(key)\n\t\tif err == nil { \/\/cache hit\n\t\t\tlog.Println(\n\t\t\t\t\"INFO: cache hit\",\n\t\t\t\tr.Method,\n\t\t\t\tr.URL.Host,\n\t\t\t\tr.URL.Path,\n\t\t\t\tr.URL.RawQuery,\n\t\t\t\tr.Header[\"X-Forwarded-Email\"],\n\t\t\t)\n\t\t\t\/\/ get the cached response\n\t\t\tresponse, err := http.ReadResponse(\n\t\t\t\tbufio.NewReader(bytes.NewReader(item.Value)),\n\t\t\t\tr,\n\t\t\t)\n\t\t\tif err == nil {\n\t\t\t\t\/\/ get the bytes out of the body first so if\n\t\t\t\t\/\/ if there is an error we aren't half way into\n\t\t\t\t\/\/ responding when we call it a cache miss\n\t\t\t\tbodyBytes, err := ioutil.ReadAll(response.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(\"could not read cached response\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t\/\/ respond with the cached response\n\t\t\t\t\/\/ copy the headers to the response writer\n\t\t\t\tcopyHeader(w.Header(), response.Header)\n\t\t\t\tcopyTrailer(w, response)\n\t\t\t\tw.WriteHeader(response.StatusCode)\n\t\t\t\t\/\/ from reverse proxy code in go\n\t\t\t\tif len(response.Trailer) > 0 {\n\t\t\t\t\t\/\/ Forse chunking if we saw a trailer.\n\t\t\t\t\t\/\/ Prevents net\/http from calculating\n\t\t\t\t\t\/\/ length for short bodies and adding\n\t\t\t\t\t\/\/ Content-Length.\n\t\t\t\t\tif fl, ok := w.(http.Flusher); ok {\n\t\t\t\t\t\tfl.Flush()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tw.Write(bodyBytes)\n\t\t\t\tresponse.Body.Close()\n\t\t\t\t\/\/ copy trailers like in go reverse proxy lib\n\t\t\t\tcopyHeader(w.Header(), response.Trailer)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ cache miss\n\tlog.Println(\n\t\t\"INFO: cache miss\",\n\t\tr.Method,\n\t\tr.URL.Host,\n\t\tr.URL.Path,\n\t\tr.URL.RawQuery,\n\t\tr.Header[\"X-Forwarded-Email\"],\n\t)\n\tupstreamURL, err := url.Parse(conf.Upstream)\n\tif err != nil {\n\t\tlog.Fatal(\"error parsing Upstream URL\", conf.Upstream)\n\t}\n\tresponseChan := make(chan *http.Response)\n\tproxy := httputil.NewSingleHostReverseProxy(upstreamURL)\n\tproxy.Transport = &stableTransport{\n\t\tproxy.Transport,\n\t\tconf.ReqFanFactor,\n\t\tresponseChan,\n\t}\n\tproxy.ServeHTTP(w, r)\n\n\t\/\/ if the transport has a response waiting on the channel, cache it if\n\t\/\/ we have a cache\n\tif cacheKey != nil {\n\t\tselect {\n\t\tcase resp := <- responseChan:\n\t\t\tdump, err := httputil.DumpResponse(resp, true)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\n\t\t\t\t\t\"ERROR: couldn't dump response:\",\n\t\t\t\t\terr,\n\t\t\t\t)\n\t\t\t\treturn\n\t\t\t}\n\t\t\titem := &memcache.Item{\n\t\t\t\tKey: key,\n\t\t\t\tValue: dump,\n\t\t\t\tExpiration: int32(conf.MemcacheSeconds),\n\t\t\t}\n\t\t\terr = mc.Set(item)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"ERROR: memcached set error:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\tcase <-time.After(1 * time.Millisecond):\n\t\t\treturn\n\t\t}\n\t}\n\n}\n\n\/\/ run\nfunc run(conf Config, done chan string) {\n\t\/\/ serve the config under a timeout\n\ttimeout := time.Duration(conf.TimeoutMS) * time.Millisecond\n\tlog.Fatal(http.ListenAndServe(\n\t\t\":8000\",\n\t\thttp.TimeoutHandler(conf, timeout, \"upstream timeout\"),\n\t))\n}\n\nfunc main() {\n\t\/\/ start Charm,\n\tdone := start(\"\/secret\/charm.conf\")\n\tstop := make(chan bool)\n\t\/\/ start some logging of the number of goroutines\n\tgo func() {\n\t\tlog.Println(\n\t\t\t\"Charm is currently using\",\n\t\t\truntime.NumGoroutine(),\n\t\t\t\"goroutines.\",\n\t\t)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-time.After(10 * time.Minute):\n\t\t\t\tlog.Println(\n\t\t\t\t\t\"Charm is currently using\",\n\t\t\t\t\truntime.NumGoroutine(),\n\t\t\t\t\t\"goroutines.\",\n\t\t\t\t)\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\t\/\/ when Charm is done, log the message and quit.\n        log.Print(<-done)\n\tclose(stop)\n}\n<|endoftext|>"}
{"text":"<commit_before>package ci\n\nimport (\n\t\/\/\"fmt\"\n\t\"net\/http\"\n)\n\nfunc init() {\n\thttp.HandleFunc(\"\/\", handler)\n}\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\t\/\/redirect_map := map[string]string {\n\t\/\/\t\"libraries\": \"https:\/\/drone.io\/dominic-mlab\/m-lab.libraries?key=BV8KN727SQ1JMEK7DKIGSO97SLBDJL2O\",\n\t\/\/\t\"ns\": \"https:\/\/drone.io\/dominic-mlab\/m-lab.ns?key=S4MHVE51D5KN5SGK1IOV1TA0SGK21RBF\",\n\t\/\/}\n\n\/\/\tif r.Method == \"POST\" {\n\t\tr.Header.Write(w);\n\t\t\/\/ TODO: post to drone.io based on contents\n\t\t\/\/http.Redirect(w, r, redirect_map[\"libraries\"], http.StatusFound)\n\/\/\t}\n}\n<commit_msg>Log request to track down filter point<commit_after>package ci\n\nimport (\n\t\"appengine\"\n\t\"net\/http\"\n)\n\nfunc init() {\n\thttp.HandleFunc(\"\/\", handler)\n}\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\t\/\/redirect_map := map[string]string {\n\t\/\/\t\"libraries\": \"https:\/\/drone.io\/dominic-mlab\/m-lab.libraries?key=BV8KN727SQ1JMEK7DKIGSO97SLBDJL2O\",\n\t\/\/\t\"ns\": \"https:\/\/drone.io\/dominic-mlab\/m-lab.ns?key=S4MHVE51D5KN5SGK1IOV1TA0SGK21RBF\",\n\t\/\/}\n\n\/\/\tif r.Method == \"POST\" {\n\t\tc := appengine.NewContext(r)\n\t\tc.Debugf(\"Request: %#v\", r)\n\t\t\/\/ TODO: post to drone.io based on contents\n\t\t\/\/http.Redirect(w, r, redirect_map[\"libraries\"], http.StatusFound)\n\/\/\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ clock counts down to or up from a target time.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tconst (\n\t\tindent          = \"\\t\"\n\t\thighlight_start = \"\\x1b[1;36m\"\n\t\thighlight_end   = \"\\x1b[0m\"\n\t)\n\tfmt.Print(indent, highlight_start, \"Just Go\", highlight_end, \"\\n\")\n\ttarget := time.Date(2015, 11, 25, 17, 44, 0, 0, time.Local)\n\tfmt.Print(indent, target.Format(time.UnixDate), \"\\n\")\n\n\tvar (\n\t\tprevious time.Time\n\t\tdays     int\n\t\tsign     string\n\t)\n\tfor {\n\t\tnow := time.Now()\n\t\tnow = now.Add(time.Duration(-now.Nanosecond())) \/\/ truncate to second\n\t\tif now != previous {\n\t\t\tprevious = now\n\t\t\tremaining := target.Sub(now)\n\t\t\tif remaining >= 0 {\n\t\t\t\tsign = \"-\" \/\/ countdown is \"T minus...\"\n\t\t\t} else {\n\t\t\t\tsign = \"+\" \/\/ count up is \"T plus...\"\n\t\t\t\tremaining = -remaining\n\t\t\t}\n\t\t\tif remaining >= 24*time.Hour {\n\t\t\t\tdays = int(remaining \/ (24 * time.Hour))\n\t\t\t\tremaining = remaining % (24 * time.Hour)\n\t\t\t}\n\t\t\tfmt.Print(indent, now.Format(time.UnixDate), \"  \", sign)\n\t\t\tif days > 0 {\n\t\t\t\tfmt.Print(days, \"d\")\n\t\t\t}\n\t\t\tfmt.Print(remaining, \"          \\r\")\n\t\t}\n\t\ttime.Sleep(50 * time.Millisecond)\n\t}\n}\n<commit_msg>retargeting<commit_after>\/\/ clock counts down to or up from a target time.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\tconst (\n\t\tindent          = \"\\t\"\n\t\thighlight_start = \"\\x1b[1;36m\"\n\t\thighlight_end   = \"\\x1b[0m\"\n\t)\n\tfmt.Print(indent, highlight_start, \"Just Go\", highlight_end, \"\\n\")\n\ttarget := time.Date(2015, 11, 30, 0, 0, 0, 0, time.UTC)\n\tfmt.Print(indent, target.Format(time.UnixDate), \"\\n\")\n\n\tvar (\n\t\tprevious time.Time\n\t\tdays     int\n\t\tsign     string\n\t)\n\tfor {\n\t\tnow := time.Now()\n\t\tnow = now.Add(time.Duration(-now.Nanosecond())) \/\/ truncate to second\n\t\tif now != previous {\n\t\t\tprevious = now\n\t\t\tremaining := target.Sub(now)\n\t\t\tif remaining >= 0 {\n\t\t\t\tsign = \"-\" \/\/ countdown is \"T minus...\"\n\t\t\t} else {\n\t\t\t\tsign = \"+\" \/\/ count up is \"T plus...\"\n\t\t\t\tremaining = -remaining\n\t\t\t}\n\t\t\tif remaining >= 24*time.Hour {\n\t\t\t\tdays = int(remaining \/ (24 * time.Hour))\n\t\t\t\tremaining = remaining % (24 * time.Hour)\n\t\t\t}\n\t\t\tfmt.Print(indent, now.Format(time.UnixDate), \"  \", sign)\n\t\t\tif days > 0 {\n\t\t\t\tfmt.Print(days, \"d\")\n\t\t\t}\n\t\t\tfmt.Print(remaining, \"          \\r\")\n\t\t}\n\t\ttime.Sleep(50 * time.Millisecond)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Clock counts down to or up from a target time.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n)\n\n\/\/ Update target and motto as desired.\nvar (\n\ttarget = time.Date(2019, 11, 10, 0, 0, 0, 0, time.Local)\n\tmotto  = \"Just Go\"\n)\n\nfunc main() {\n\tprintTargetTime(target, motto)\n\texitOnEnterKey()\n\n\tvar previous time.Time\n\tfor {\n\t\tnow := time.Now().Truncate(time.Second)\n\t\tif now != previous {\n\t\t\tprevious = now\n\t\t\tcountdown := now.Sub(target) \/\/ Negative times are before the target\n\t\t\tprintCountdown(now.In(target.Location()), countdown)\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}\n\nfunc exitOnEnterKey() {\n\tgo func() {\n\t\tbuf := make([]byte, 1)\n\t\t_, _ = os.Stdin.Read(buf)\n\t\tos.Exit(0)\n\t}()\n}\n\nconst (\n\thighlightStart = \"\\x1b[1;35m\"\n\thighlightEnd   = \"\\x1b[0m\"\n\tindent         = \"\\t\"\n)\n\nfunc printTargetTime(target time.Time, motto string) {\n\tfmt.Print(indent, highlightStart, motto, highlightEnd, \"\\n\")\n\tfmt.Print(indent, target.Format(time.UnixDate), \"\\n\")\n}\n\nfunc printCountdown(now time.Time, countdown time.Duration) {\n\tvar sign string\n\tif countdown >= 0 {\n\t\tsign = \"+\"\n\t} else {\n\t\tsign = \"-\"\n\t\tcountdown = -countdown\n\t}\n\n\tdays := int(countdown \/ (24 * time.Hour))\n\tcountdown = countdown % (24 * time.Hour)\n\n\tfmt.Print(indent, now.Format(time.UnixDate), \"  \", sign)\n\tif days > 0 {\n\t\tfmt.Print(days, \"d\")\n\t}\n\tfmt.Print(countdown, \"          \\r\")\n\tos.Stdout.Sync()\n}\n<commit_msg>Simplify<commit_after>\/\/ Clock counts down to or up from a target time.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n)\n\n\/\/ Update target and motto as desired.\nvar (\n\ttarget = time.Date(2019, 11, 15, 0, 0, 0, 0, time.Local)\n\tmotto  = \"Just Go\"\n)\n\nfunc main() {\n\tprintTargetTime(target, motto)\n\texitOnEnterKey()\n\n\tvar previous time.Time\n\tfor {\n\t\tnow := time.Now().Truncate(time.Second)\n\t\tif now != previous {\n\t\t\tprevious = now\n\t\t\tcountdown := now.Sub(target) \/\/ Negative times are before the target\n\t\t\tprintCountdown(now.In(target.Location()), countdown)\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}\n\nfunc exitOnEnterKey() {\n\tgo func() {\n\t\tbuf := make([]byte, 1)\n\t\t_, _ = os.Stdin.Read(buf)\n\t\tos.Exit(0)\n\t}()\n}\n\nconst (\n\thighlightStart = \"\\x1b[1;35m\"\n\thighlightEnd   = \"\\x1b[0m\"\n\tindent         = \"\\t\"\n)\n\nfunc printTargetTime(target time.Time, motto string) {\n\tfmt.Print(indent, highlightStart, motto, highlightEnd, \"\\n\")\n\tfmt.Print(indent, target.Format(time.UnixDate), \"\\n\")\n}\n\nfunc printCountdown(now time.Time, countdown time.Duration) {\n\tvar sign string\n\tif countdown >= 0 {\n\t\tsign = \"+\"\n\t} else {\n\t\tsign = \"-\"\n\t\tcountdown = -countdown\n\t}\n\n\tdays := int(countdown \/ (24 * time.Hour))\n\tcountdown = countdown % (24 * time.Hour)\n\n\tfmt.Print(indent, now.Format(time.UnixDate), \"  \", sign)\n\tif days > 0 {\n\t\tfmt.Print(days, \"d\")\n\t}\n\tfmt.Print(countdown, \"          \\r\")\n\tos.Stdout.Sync()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Clock counts down to or up from a target time.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n)\n\n\/\/ Update target and motto as desired.\nvar (\n\ttarget = time.Date(2019, 7, 20, 0, 0, 0, 0, time.Local)\n\tmotto  = \"Just Go\"\n)\n\nfunc main() {\n\tprintTargetTime(target, motto)\n\texitOnEnterKey()\n\n\tvar previous time.Time\n\tfor {\n\t\tnow := time.Now().Truncate(time.Second)\n\t\tif now != previous {\n\t\t\tprevious = now\n\t\t\tcountdown := now.Sub(target) \/\/ Negative times are before the target\n\t\t\tprintCountdown(now.In(target.Location()), countdown)\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}\n\nfunc exitOnEnterKey() {\n\tgo func() {\n\t\tbuf := make([]byte, 1)\n\t\t_, _ = os.Stdin.Read(buf)\n\t\tos.Exit(0)\n\t}()\n}\n\nconst (\n\thighlightStart = \"\\x1b[1;35m\"\n\thighlightEnd   = \"\\x1b[0m\"\n\tindent         = \"\\t\"\n)\n\nfunc printTargetTime(target time.Time, motto string) {\n\tfmt.Print(indent, highlightStart, motto, highlightEnd, \"\\n\")\n\tfmt.Print(indent, target.Format(time.UnixDate), \"\\n\")\n}\n\nfunc printCountdown(now time.Time, countdown time.Duration) {\n\tvar sign string\n\tif countdown >= 0 {\n\t\tsign = \"+\"\n\t} else {\n\t\tsign = \"-\"\n\t\tcountdown = -countdown\n\t}\n\n\tdays := int(countdown \/ (24 * time.Hour))\n\tcountdown = countdown % (24 * time.Hour)\n\n\tfmt.Print(indent, now.Format(time.UnixDate), \"  \", sign)\n\tif days > 0 {\n\t\tfmt.Print(days, \"d\")\n\t}\n\tfmt.Print(countdown, \"          \\r\")\n\tos.Stdout.Sync()\n}\n<commit_msg>simple reset<commit_after>\/\/ Clock counts down to or up from a target time.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n)\n\n\/\/ Update target and motto as desired.\nvar (\n\ttarget = time.Date(2019, 7, 26, 0, 0, 0, 0, time.Local)\n\tmotto  = \"Just Go\"\n)\n\nfunc main() {\n\tprintTargetTime(target, motto)\n\texitOnEnterKey()\n\n\tvar previous time.Time\n\tfor {\n\t\tnow := time.Now().Truncate(time.Second)\n\t\tif now != previous {\n\t\t\tprevious = now\n\t\t\tcountdown := now.Sub(target) \/\/ Negative times are before the target\n\t\t\tprintCountdown(now.In(target.Location()), countdown)\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}\n\nfunc exitOnEnterKey() {\n\tgo func() {\n\t\tbuf := make([]byte, 1)\n\t\t_, _ = os.Stdin.Read(buf)\n\t\tos.Exit(0)\n\t}()\n}\n\nconst (\n\thighlightStart = \"\\x1b[1;35m\"\n\thighlightEnd   = \"\\x1b[0m\"\n\tindent         = \"\\t\"\n)\n\nfunc printTargetTime(target time.Time, motto string) {\n\tfmt.Print(indent, highlightStart, motto, highlightEnd, \"\\n\")\n\tfmt.Print(indent, target.Format(time.UnixDate), \"\\n\")\n}\n\nfunc printCountdown(now time.Time, countdown time.Duration) {\n\tvar sign string\n\tif countdown >= 0 {\n\t\tsign = \"+\"\n\t} else {\n\t\tsign = \"-\"\n\t\tcountdown = -countdown\n\t}\n\n\tdays := int(countdown \/ (24 * time.Hour))\n\tcountdown = countdown % (24 * time.Hour)\n\n\tfmt.Print(indent, now.Format(time.UnixDate), \"  \", sign)\n\tif days > 0 {\n\t\tfmt.Print(days, \"d\")\n\t}\n\tfmt.Print(countdown, \"          \\r\")\n\tos.Stdout.Sync()\n}\n<|endoftext|>"}
{"text":"<commit_before>package msgp\n\nimport (\n\t\"testing\"\n)\n\n\/\/ EndlessReader is an io.Reader\n\/\/ that loops over the same data\n\/\/ endlessly. It is used for benchmarking.\ntype EndlessReader struct {\n\ttb     *testing.B\n\tdata   []byte\n\toffset int\n}\n\n\/\/ NewEndlessReader returns a new endless reader\nfunc NewEndlessReader(b []byte, tb *testing.B) *EndlessReader {\n\treturn &EndlessReader{tb: tb, data: b, offset: 0}\n}\n\n\/\/ Read implements io.Reader. In practice, it\n\/\/ always returns (len(p), nil), although it\n\/\/ fills the supplied slice while the benchmark\n\/\/ timer is stopped.\nfunc (c *EndlessReader) Read(p []byte) (int, error) {\n\tc.tb.StopTimer()\n\tvar n int\n\tl := len(p)\n\tm := len(c.data)\n\tfor n < l {\n\t\tnn := copy(p[n:], c.data[c.offset:])\n\t\tn += nn\n\t\tc.offset += nn\n\t\tc.offset %= m\n\t}\n\tc.tb.StartTimer()\n\treturn n, nil\n}\n<commit_msg>Break dependency on \"testing\" package<commit_after>package msgp\n\ntype timer interface {\n\tStartTimer()\n\tStopTimer()\n}\n\n\/\/ EndlessReader is an io.Reader\n\/\/ that loops over the same data\n\/\/ endlessly. It is used for benchmarking.\ntype EndlessReader struct {\n\ttb     timer\n\tdata   []byte\n\toffset int\n}\n\n\/\/ NewEndlessReader returns a new endless reader\nfunc NewEndlessReader(b []byte, tb timer) *EndlessReader {\n\treturn &EndlessReader{tb: tb, data: b, offset: 0}\n}\n\n\/\/ Read implements io.Reader. In practice, it\n\/\/ always returns (len(p), nil), although it\n\/\/ fills the supplied slice while the benchmark\n\/\/ timer is stopped.\nfunc (c *EndlessReader) Read(p []byte) (int, error) {\n\tc.tb.StopTimer()\n\tvar n int\n\tl := len(p)\n\tm := len(c.data)\n\tfor n < l {\n\t\tnn := copy(p[n:], c.data[c.offset:])\n\t\tn += nn\n\t\tc.offset += nn\n\t\tc.offset %= m\n\t}\n\tc.tb.StartTimer()\n\treturn n, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package menu\n\nimport (\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/fatih\/color\"\n\t\"github.com\/miquella\/ask\"\n\t\"golang.org\/x\/crypto\/ssh\"\n\n\t\"github.com\/miquella\/vaulted\/lib\"\n)\n\ntype SSHKeyMenu struct {\n\t*Menu\n}\n\nfunc (m *SSHKeyMenu) Help() {\n\tmenuColor.Set()\n\tdefer color.Unset()\n\n\tfmt.Println(\"a,add      - Add\")\n\tfmt.Println(\"D,delete   - Delete\")\n\tfmt.Println(\"g,generate - Generate Key\")\n\tfmt.Println(\"v          - HashiCorp Vault Signing URL\")\n\tfmt.Println(\"u,users    - HashiCorp Vault User Principals\")\n\tfmt.Println(\"e          - Expose External SSH Agent\")\n\tfmt.Println(\"?,help     - Help\")\n\tfmt.Println(\"b,back     - Back\")\n\tfmt.Println(\"q,quit     - Quit\")\n}\n\nfunc (m *SSHKeyMenu) Handler() error {\n\tfor {\n\t\tvar err error\n\t\tm.Printer()\n\t\tinput, err := interaction.ReadMenu(\"Edit ssh keys: [a,D,g,v,u,e,b]: \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch input {\n\t\tcase \"a\", \"add\", \"key\", \"keys\":\n\t\t\terr = m.AddSSHKey()\n\t\tcase \"D\", \"delete\", \"remove\":\n\t\t\tvar key string\n\t\t\tkey, err = interaction.ReadValue(\"Key: \")\n\t\t\tif err == nil {\n\t\t\t\tif _, exists := m.Vault.SSHKeys[key]; exists {\n\t\t\t\t\tdelete(m.Vault.SSHKeys, key)\n\t\t\t\t} else {\n\t\t\t\t\tcolor.Red(\"Key '%s' not found\", key)\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"g\", \"generate\":\n\t\t\tif m.Vault.SSHOptions == nil {\n\t\t\t\tm.Vault.SSHOptions = &vaulted.SSHOptions{}\n\t\t\t}\n\t\t\tm.Vault.SSHOptions.GenerateRSAKey = !m.Vault.SSHOptions.GenerateRSAKey\n\t\tcase \"v\":\n\t\t\tsigningUrl, err := interaction.ReadValue(\"HashiCorp Vault signing URL: \")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif m.Vault.SSHOptions == nil {\n\t\t\t\tm.Vault.SSHOptions = &vaulted.SSHOptions{}\n\t\t\t}\n\t\t\tm.Vault.SSHOptions.VaultSigningUrl = signingUrl\n\n\t\t\tif signingUrl != \"\" && !m.Vault.SSHOptions.GenerateRSAKey {\n\t\t\t\tgenerateKey, _ := interaction.ReadValue(\"Would you like to enable RSA key generation (y\/n): \")\n\t\t\t\tif generateKey == \"y\" {\n\t\t\t\t\tm.Vault.SSHOptions.GenerateRSAKey = true\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"u\", \"users\":\n\t\t\tuserPrincipals, err := interaction.ReadValue(\"HashiCorp Vault user principals (comma separated): \")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif m.Vault.SSHOptions == nil {\n\t\t\t\tm.Vault.SSHOptions = &vaulted.SSHOptions{}\n\t\t\t}\n\t\t\tif userPrincipals != \"\" {\n\t\t\t\tm.Vault.SSHOptions.ValidPrincipals = strings.Split(userPrincipals, \",\")\n\t\t\t} else {\n\t\t\t\tm.Vault.SSHOptions.ValidPrincipals = []string{}\n\t\t\t}\n\t\tcase \"e\":\n\t\t\tif m.Vault.SSHOptions == nil {\n\t\t\t\tm.Vault.SSHOptions = &vaulted.SSHOptions{}\n\t\t\t}\n\t\t\tm.Vault.SSHOptions.DisableProxy = !m.Vault.SSHOptions.DisableProxy\n\t\tcase \"b\", \"back\":\n\t\t\treturn nil\n\t\tcase \"q\", \"quit\", \"exit\":\n\t\t\tvar confirm string\n\t\t\tconfirm, err = interaction.ReadValue(\"Are you sure you wish to save and exit the vault? (y\/n): \")\n\t\t\tif err == nil {\n\t\t\t\tif confirm == \"y\" {\n\t\t\t\t\treturn ErrSaveAndExit\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"?\", \"help\":\n\t\t\tm.Help()\n\t\tdefault:\n\t\t\tcolor.Red(\"Command not recognized\")\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc (m *SSHKeyMenu) AddSSHKey() error {\n\tvar err error\n\n\thomeDir := \"\"\n\tuser, err := user.Current()\n\tif err == nil {\n\t\thomeDir = user.HomeDir\n\t} else {\n\t\thomeDir = os.Getenv(\"HOME\")\n\t}\n\n\tdefaultFilename := \"\"\n\tfilename := \"\"\n\tif homeDir != \"\" {\n\t\tdefaultFilename = filepath.Join(homeDir, \".ssh\", \"id_rsa\")\n\t\tfilename, err = interaction.ReadValue(fmt.Sprintf(\"Key file (default: %s): \", defaultFilename))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif filename == \"\" {\n\t\t\tfilename = defaultFilename\n\t\t}\n\t\tif !filepath.IsAbs(filename) {\n\t\t\tfilename = filepath.Join(filepath.Join(homeDir, \".ssh\"), filename)\n\t\t}\n\t} else {\n\t\tfilename, err = interaction.ReadValue(\"Key file: \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tdecryptedBlock, err := loadAndDecryptKey(filename)\n\tif err != nil {\n\t\tcolor.Red(\"%v\", err)\n\t\treturn nil\n\t}\n\n\tcomment := loadPublicKeyComment(filename + \".pub\")\n\tvar name string\n\tif comment != \"\" {\n\t\tname, err = interaction.ReadValue(fmt.Sprintf(\"Name (default: %s): \", comment))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif name == \"\" {\n\t\t\tname = comment\n\t\t}\n\t} else {\n\t\tname, err = interaction.ReadValue(\"Name: \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif name == \"\" {\n\t\t\tname = filename\n\t\t}\n\t}\n\n\tif m.Vault.SSHKeys == nil {\n\t\tm.Vault.SSHKeys = make(map[string]string)\n\t}\n\tm.Vault.SSHKeys[name] = string(pem.EncodeToMemory(decryptedBlock))\n\n\treturn nil\n}\n\nfunc loadAndDecryptKey(filename string) (*pem.Block, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, _ := pem.Decode(data)\n\tif block == nil {\n\t\treturn nil, err\n\t}\n\n\tif x509.IsEncryptedPEMBlock(block) {\n\t\tvar passphrase string\n\t\tvar decryptedBytes []byte\n\t\tfor i := 0; i < 3; i++ {\n\t\t\tpassphrase, err = ask.HiddenAsk(\"Passphrase: \")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tdecryptedBytes, err = x509.DecryptPEMBlock(block, []byte(passphrase))\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err != x509.IncorrectPasswordError {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &pem.Block{\n\t\t\tType:  block.Type,\n\t\t\tBytes: decryptedBytes,\n\t\t}, nil\n\t}\n\treturn block, nil\n}\n\nfunc loadPublicKeyComment(filename string) string {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tdefer f.Close()\n\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\t_, comment, _, _, err := ssh.ParseAuthorizedKey(data)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn comment\n}\n\nfunc (m *SSHKeyMenu) Printer() {\n\tcolor.Cyan(\"\\nSSH Agent:\")\n\tcolor.Cyan(\"  Keys:\")\n\tif len(m.Vault.SSHKeys) > 0 || m.Vault.SSHOptions != nil && m.Vault.SSHOptions.GenerateRSAKey {\n\t\tkeys := []string{}\n\t\tfor key := range m.Vault.SSHKeys {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t\tsort.Strings(keys)\n\n\t\tfor _, key := range keys {\n\t\t\tgreen.Printf(\"    %s\\n\", key)\n\t\t}\n\n\t\tif m.Vault.SSHOptions != nil && m.Vault.SSHOptions.GenerateRSAKey {\n\t\t\tfaintColor.Print(\"    <generated RSA key>\\n\")\n\t\t}\n\t} else {\n\t\tfmt.Println(\"    [Empty]\")\n\t}\n\n\tif m.Vault.SSHOptions != nil {\n\t\tif m.Vault.SSHOptions.VaultSigningUrl != \"\" || len(m.Vault.SSHOptions.ValidPrincipals) > 0 {\n\t\t\tcolor.Cyan(\"\\n  Signing (HashiCorp Vault):\")\n\t\t\tif m.Vault.SSHOptions.VaultSigningUrl != \"\" {\n\t\t\t\tgreen.Printf(\"    URL: \")\n\t\t\t\tfmt.Printf(\"%s\\n\", m.Vault.SSHOptions.VaultSigningUrl)\n\t\t\t}\n\n\t\t\tif len(m.Vault.SSHOptions.ValidPrincipals) > 0 {\n\t\t\t\tgreen.Printf(\"    User: \")\n\t\t\t\tfmt.Printf(\"%s\\n\", m.Vault.SSHOptions.ValidPrincipals)\n\t\t\t}\n\n\t\t\tcyan.Print(\"\\n  Expose external SSH agent: \")\n\t\t\tfmt.Printf(\"%t\\n\", !m.Vault.SSHOptions.DisableProxy)\n\t\t}\n\t}\n}\n<commit_msg>clean up SSH options in edit menu<commit_after>package menu\n\nimport (\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/fatih\/color\"\n\t\"github.com\/miquella\/ask\"\n\t\"golang.org\/x\/crypto\/ssh\"\n\n\t\"github.com\/miquella\/vaulted\/lib\"\n)\n\ntype SSHKeyMenu struct {\n\t*Menu\n}\n\nfunc (m *SSHKeyMenu) Help() {\n\tmenuColor.Set()\n\tdefer color.Unset()\n\n\tfmt.Println(\"a,add      - Add\")\n\tfmt.Println(\"D,delete   - Delete\")\n\tfmt.Println(\"g,generate - Generate Key\")\n\tfmt.Println(\"v          - HashiCorp Vault Signing URL\")\n\tfmt.Println(\"u,users    - HashiCorp Vault User Principals\")\n\tfmt.Println(\"E          - Expose External SSH Agent\")\n\tfmt.Println(\"?,help     - Help\")\n\tfmt.Println(\"b,back     - Back\")\n\tfmt.Println(\"q,quit     - Quit\")\n}\n\nfunc (m *SSHKeyMenu) Handler() error {\n\tfor {\n\t\tvar err error\n\t\tm.Printer()\n\t\tinput, err := interaction.ReadMenu(\"Edit ssh keys: [a,D,g,v,u,E,b]: \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch input {\n\t\tcase \"a\", \"add\", \"key\", \"keys\":\n\t\t\terr = m.AddSSHKey()\n\t\tcase \"D\", \"delete\", \"remove\":\n\t\t\tvar key string\n\t\t\tkey, err = interaction.ReadValue(\"Key: \")\n\t\t\tif err == nil {\n\t\t\t\tif _, exists := m.Vault.SSHKeys[key]; exists {\n\t\t\t\t\tdelete(m.Vault.SSHKeys, key)\n\t\t\t\t} else {\n\t\t\t\t\tcolor.Red(\"Key '%s' not found\", key)\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"g\", \"generate\":\n\t\t\tif m.Vault.SSHOptions == nil {\n\t\t\t\tm.Vault.SSHOptions = &vaulted.SSHOptions{}\n\t\t\t}\n\t\t\tm.Vault.SSHOptions.GenerateRSAKey = !m.Vault.SSHOptions.GenerateRSAKey\n\t\tcase \"v\":\n\t\t\tsigningUrl, err := interaction.ReadValue(\"HashiCorp Vault signing URL: \")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif m.Vault.SSHOptions == nil {\n\t\t\t\tm.Vault.SSHOptions = &vaulted.SSHOptions{}\n\t\t\t}\n\t\t\tm.Vault.SSHOptions.VaultSigningUrl = signingUrl\n\n\t\t\tif signingUrl != \"\" && !m.Vault.SSHOptions.GenerateRSAKey {\n\t\t\t\tgenerateKey, _ := interaction.ReadValue(\"Would you like to enable RSA key generation (y\/n): \")\n\t\t\t\tif generateKey == \"y\" {\n\t\t\t\t\tm.Vault.SSHOptions.GenerateRSAKey = true\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"u\", \"users\":\n\t\t\tuserPrincipals, err := interaction.ReadValue(\"HashiCorp Vault user principals (comma separated): \")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif m.Vault.SSHOptions == nil {\n\t\t\t\tm.Vault.SSHOptions = &vaulted.SSHOptions{}\n\t\t\t}\n\t\t\tif userPrincipals != \"\" {\n\t\t\t\tm.Vault.SSHOptions.ValidPrincipals = strings.Split(userPrincipals, \",\")\n\t\t\t} else {\n\t\t\t\tm.Vault.SSHOptions.ValidPrincipals = []string{}\n\t\t\t}\n\t\tcase \"E\":\n\t\t\tif m.Vault.SSHOptions == nil {\n\t\t\t\tm.Vault.SSHOptions = &vaulted.SSHOptions{}\n\t\t\t}\n\t\t\tm.Vault.SSHOptions.DisableProxy = !m.Vault.SSHOptions.DisableProxy\n\t\tcase \"b\", \"back\":\n\t\t\treturn nil\n\t\tcase \"q\", \"quit\", \"exit\":\n\t\t\tvar confirm string\n\t\t\tconfirm, err = interaction.ReadValue(\"Are you sure you wish to save and exit the vault? (y\/n): \")\n\t\t\tif err == nil {\n\t\t\t\tif confirm == \"y\" {\n\t\t\t\t\treturn ErrSaveAndExit\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"?\", \"help\":\n\t\t\tm.Help()\n\t\tdefault:\n\t\t\tcolor.Red(\"Command not recognized\")\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc (m *SSHKeyMenu) AddSSHKey() error {\n\tvar err error\n\n\thomeDir := \"\"\n\tuser, err := user.Current()\n\tif err == nil {\n\t\thomeDir = user.HomeDir\n\t} else {\n\t\thomeDir = os.Getenv(\"HOME\")\n\t}\n\n\tdefaultFilename := \"\"\n\tfilename := \"\"\n\tif homeDir != \"\" {\n\t\tdefaultFilename = filepath.Join(homeDir, \".ssh\", \"id_rsa\")\n\t\tfilename, err = interaction.ReadValue(fmt.Sprintf(\"Key file (default: %s): \", defaultFilename))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif filename == \"\" {\n\t\t\tfilename = defaultFilename\n\t\t}\n\t\tif !filepath.IsAbs(filename) {\n\t\t\tfilename = filepath.Join(filepath.Join(homeDir, \".ssh\"), filename)\n\t\t}\n\t} else {\n\t\tfilename, err = interaction.ReadValue(\"Key file: \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tdecryptedBlock, err := loadAndDecryptKey(filename)\n\tif err != nil {\n\t\tcolor.Red(\"%v\", err)\n\t\treturn nil\n\t}\n\n\tcomment := loadPublicKeyComment(filename + \".pub\")\n\tvar name string\n\tif comment != \"\" {\n\t\tname, err = interaction.ReadValue(fmt.Sprintf(\"Name (default: %s): \", comment))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif name == \"\" {\n\t\t\tname = comment\n\t\t}\n\t} else {\n\t\tname, err = interaction.ReadValue(\"Name: \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif name == \"\" {\n\t\t\tname = filename\n\t\t}\n\t}\n\n\tif m.Vault.SSHKeys == nil {\n\t\tm.Vault.SSHKeys = make(map[string]string)\n\t}\n\tm.Vault.SSHKeys[name] = string(pem.EncodeToMemory(decryptedBlock))\n\n\treturn nil\n}\n\nfunc loadAndDecryptKey(filename string) (*pem.Block, error) {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblock, _ := pem.Decode(data)\n\tif block == nil {\n\t\treturn nil, err\n\t}\n\n\tif x509.IsEncryptedPEMBlock(block) {\n\t\tvar passphrase string\n\t\tvar decryptedBytes []byte\n\t\tfor i := 0; i < 3; i++ {\n\t\t\tpassphrase, err = ask.HiddenAsk(\"Passphrase: \")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tdecryptedBytes, err = x509.DecryptPEMBlock(block, []byte(passphrase))\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err != x509.IncorrectPasswordError {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &pem.Block{\n\t\t\tType:  block.Type,\n\t\t\tBytes: decryptedBytes,\n\t\t}, nil\n\t}\n\treturn block, nil\n}\n\nfunc loadPublicKeyComment(filename string) string {\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tdefer f.Close()\n\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\t_, comment, _, _, err := ssh.ParseAuthorizedKey(data)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn comment\n}\n\nfunc (m *SSHKeyMenu) Printer() {\n\tcolor.Cyan(\"\\nSSH Agent:\")\n\tcolor.Cyan(\"  Keys:\")\n\tif len(m.Vault.SSHKeys) > 0 || m.Vault.SSHOptions != nil && m.Vault.SSHOptions.GenerateRSAKey {\n\t\tkeys := []string{}\n\t\tfor key := range m.Vault.SSHKeys {\n\t\t\tkeys = append(keys, key)\n\t\t}\n\t\tsort.Strings(keys)\n\n\t\tfor _, key := range keys {\n\t\t\tgreen.Printf(\"    %s\\n\", key)\n\t\t}\n\n\t\tif m.Vault.SSHOptions != nil && m.Vault.SSHOptions.GenerateRSAKey {\n\t\t\tfaintColor.Print(\"    <generated RSA key>\\n\")\n\t\t}\n\t} else {\n\t\tfmt.Println(\"    [Empty]\")\n\t}\n\n\tif m.Vault.SSHOptions != nil {\n\t\tif m.Vault.SSHOptions.VaultSigningUrl != \"\" || len(m.Vault.SSHOptions.ValidPrincipals) > 0 {\n\t\t\tcolor.Cyan(\"\\n  Signing (HashiCorp Vault):\")\n\t\t\tif m.Vault.SSHOptions.VaultSigningUrl != \"\" {\n\t\t\t\tgreen.Printf(\"    URL: \")\n\t\t\t\tfmt.Printf(\"%s\\n\", m.Vault.SSHOptions.VaultSigningUrl)\n\t\t\t}\n\n\t\t\tif len(m.Vault.SSHOptions.ValidPrincipals) > 0 {\n\t\t\t\tgreen.Printf(\"    User(s): \")\n\t\t\t\tfmt.Printf(\"%s\\n\", strings.Join(m.Vault.SSHOptions.ValidPrincipals, \", \"))\n\t\t\t}\n\n\t\t\tcyan.Print(\"\\n  Expose external SSH agent: \")\n\t\t\tfmt.Printf(\"%t\\n\", !m.Vault.SSHOptions.DisableProxy)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013, 2015 Ben Morgan. All rights reserved.\n\/\/ Use of this source code is governed by an MIT license\n\/\/ that can be found in the LICENSE file.\n\n\/\/ Copyright 2013, Meng Zhang. All rights reserved.\n\/\/ URL: https:\/\/github.com\/wsxiaoys\/terminal\n\/\/ File URL: https:\/\/github.com\/wsxiaoys\/terminal\/blob\/decf4e097e2e3471b254da8d30c3599d330fe7ba\/color\/color.go\n\n\/\/ Package color provides printing in ANSI colors.\n\/\/\n\/\/ TODO: Need to document this. See the Color function for now.\n\/\/\n\/\/ This package uses code from [github.com\/wsxiaoys\/terminal](https:\/\/github.com\/wsxiaoys\/terminal). Many thanks.\npackage color\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"golang.org\/x\/crypto\/ssh\/terminal\"\n)\n\n\/\/ Mapping from character to concrete escape code.\nvar codeMap = map[int]int{\n\t'|': 0,\n\t'!': 1,\n\t'.': 2,\n\t'\/': 3,\n\t'_': 4,\n\t'^': 5,\n\t'&': 6,\n\t'?': 7,\n\t'-': 8,\n\n\t'k': 30,\n\t'r': 31,\n\t'g': 32,\n\t'y': 33,\n\t'b': 34,\n\t'm': 35,\n\t'c': 36,\n\t'w': 37,\n\t'd': 39,\n\n\t'K': 40,\n\t'R': 41,\n\t'G': 42,\n\t'Y': 43,\n\t'B': 44,\n\t'M': 45,\n\t'C': 46,\n\t'W': 47,\n\t'D': 49,\n}\n\n\/\/ ErrInvalidEscape is an error that is used when the parser panics.\nvar ErrInvalidEscape = errors.New(\"invalid escape rune\")\nvar ErrUnexpectedEOF = errors.New(\"unexpected EOF while parsing\")\n\n\/\/ ColorReset is the string that resets the text to default style.\nconst ColorReset = \"\\033[0m\"\n\n\/\/ ColorCode compiles a color syntax string like \"rG\" to escape code.\nfunc ColorCode(s string) string {\n\tattr := 0\n\tfg := 39\n\tbg := 49\n\n\tfor _, key := range s {\n\t\tc, ok := codeMap[int(key)]\n\t\tif !ok {\n\t\t\tpanic(\"wrong color syntax: \" + string(key))\n\t\t}\n\n\t\tswitch {\n\t\tcase 0 <= c && c <= 8:\n\t\t\tattr = c\n\t\tcase 30 <= c && c <= 37:\n\t\t\tfg = c\n\t\tcase 40 <= c && c <= 47:\n\t\t\tbg = c\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"\\033[%d;%d;%dm\", attr, fg, bg)\n}\n\n\/\/ Color translates a string into an escaped string.\n\/\/\n\/\/ This example will output the text with a Blue foreground and a Black background\n\/\/      color.Println(\"@{bK}Example Text\")\n\/\/\n\/\/ This one will output the text with a red foreground\n\/\/      color.Println(\"@rExample Text\")\n\/\/\n\/\/ This one will escape the @\n\/\/      color.Println(\"@@\")\n\/\/\n\/\/ Full color syntax code\n\/\/      @{rgbcmykwRGBCMYKW}  foreground\/background color\n\/\/        r\/R:  Red\n\/\/        g\/G:  Green\n\/\/        b\/B:  Blue\n\/\/        c\/C:  Cyan\n\/\/        m\/M:  Magenta\n\/\/        y\/Y:  Yellow\n\/\/        k\/K:  Black\n\/\/        w\/W:  White\n\/\/      @{|}  Reset format style\n\/\/      @{!.\/_} Bold \/ Dim \/ Italic \/ Underline\n\/\/      @{^&} Blink \/ Fast blink\n\/\/      @{?} Reverse the foreground and background color\n\/\/      @{-} Hide the text\n\/\/ Note some of the functions are not widely supported, like \"Fast blink\" and \"Italic\".\nfunc Color(s string, escape rune) string {\n\treturn newParser(escape, true).translateReset(s)\n}\n\n\/\/ Decolor cleans a string of @x color codes.\nfunc Decolor(s string, escape rune) string {\n\treturn newParser(escape, false).translateReset(s)\n}\n\n\/\/ Uncolor cleans a string of ANSI color codes.\nfunc Uncolor(s string) string {\n\tpanic(\"not implemented\")\n}\n\ntype Colorizer struct {\n\tw io.Writer\n\t*parser\n}\n\nfunc NewColorizer() *Colorizer {\n\treturn &Colorizer{\n\t\tw:      os.Stdout,\n\t\tparser: newParser('@', true),\n\t}\n}\n\nfunc (c *Colorizer) EscapeChar() rune {\n\treturn c.parser.escape\n}\n\n\/\/ SetEscapeChar sets the escape character, which can be one of the following characters:\n\/\/\n\/\/\t\t@ * + = ~\n\/\/\n\/\/ If it is none of these characters, then this function panics with ErrInvalidEscape.\nfunc (c *Colorizer) SetEscapeChar(r rune) {\n\tif c.EscapeChar() == r {\n\t\treturn\n\t}\n\n\tfor _, q := range []rune{'*', '@', '+', '=', '~'} {\n\t\tif r == q {\n\t\t\tc.parser.escape = r\n\t\t\treturn\n\t\t}\n\t}\n\n\tpanic(ErrInvalidEscape)\n}\n\nfunc (c *Colorizer) Enabled() bool {\n\treturn c.parser.color\n}\n\nfunc (c *Colorizer) SetEnabled(b bool) {\n\tif c.Enabled() == b {\n\t\treturn\n\t}\n\tc.parser.color = b\n}\n\nfunc (c *Colorizer) SetOutput(w io.Writer) {\n\tc.w = w\n}\n\nfunc (c *Colorizer) SetFile(f *os.File) {\n\tc.SetEnabled(terminal.IsTerminal(int(f.Fd())))\n\tc.w = f\n}\n\nfunc (c *Colorizer) Color(s string) string {\n\treturn c.translateReset(s)\n}\n\nfunc (c *Colorizer) colorAny(args []interface{}) []interface{} {\n\tn := len(args)\n\tr := make([]interface{}, n, n+1)\n\tfor i, x := range args {\n\t\tif str, ok := x.(string); ok {\n\t\t\tx = c.translateOnly(str)\n\t\t}\n\t\tr[i] = x\n\t}\n\tif c.Enabled() {\n\t\tr = append(r, ColorReset)\n\t}\n\treturn r\n}\n\nfunc (c *Colorizer) Print(a ...interface{}) (int, error) {\n\treturn fmt.Fprint(c.w, c.colorAny(a)...)\n}\nfunc (c *Colorizer) Println(a ...interface{}) (int, error) {\n\treturn fmt.Fprintln(c.w, c.colorAny(a)...)\n}\nfunc (c *Colorizer) Printf(format string, a ...interface{}) (int, error) {\n\treturn fmt.Fprintf(c.w, c.translateReset(format), a...)\n}\nfunc (c *Colorizer) Fprint(w io.Writer, a ...interface{}) (int, error) {\n\treturn fmt.Fprint(w, c.colorAny(a)...)\n}\nfunc (c *Colorizer) Fprintln(w io.Writer, a ...interface{}) (int, error) {\n\treturn fmt.Fprintln(w, c.colorAny(a)...)\n}\nfunc (c *Colorizer) Fprintf(w io.Writer, format string, a ...interface{}) (int, error) {\n\treturn fmt.Fprintf(w, c.translateReset(format), a...)\n}\nfunc (c *Colorizer) Sprint(a ...interface{}) string {\n\treturn fmt.Sprint(c.colorAny(a)...)\n}\nfunc (c *Colorizer) Sprintln(a ...interface{}) string {\n\treturn fmt.Sprintln(c.colorAny(a)...)\n}\nfunc (c *Colorizer) Sprintf(format string, a ...interface{}) string {\n\treturn fmt.Sprintf(c.translateReset(format), a...)\n}\n\ntype parser struct {\n\tescape rune\n\tcolor  bool\n}\n\nfunc newParser(escape rune, color bool) *parser {\n\treturn &parser{\n\t\tescape: escape,\n\t\tcolor:  color,\n\t}\n}\n\ntype handler func(p *parser, in, out *bytes.Buffer) (handler, error)\n\nfunc (p *parser) translateReset(s string) string {\n\tin := bytes.NewBufferString(s)\n\tout := bytes.NewBufferString(\"\")\n\n\tvar h = handleRegular\n\tvar err error\n\tfor {\n\t\th, err = h(p, in, out)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif h == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif p.color {\n\t\tout.WriteString(ColorReset)\n\t}\n\treturn out.String()\n}\n\nfunc (p *parser) translateOnly(s string) string {\n\tin := bytes.NewBufferString(s)\n\tout := bytes.NewBufferString(\"\")\n\n\tvar h = handleRegular\n\tvar err error\n\tfor {\n\t\th, err = h(p, in, out)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif h == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn out.String()\n}\n\nfunc handleRegular(p *parser, in, out *bytes.Buffer) (handler, error) {\n\tfor {\n\t\tr, _, err := in.ReadRune()\n\t\t\/\/ The only error that can happen here is that we have reached the end of file,\n\t\t\/\/ or that a rune is messed up. If the rune is messed up, we treat it normally.\n\t\t\/\/ This is why we only check for io.EOF.\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\tif r == p.escape {\n\t\t\treturn handleEscape, nil\n\t\t}\n\t\tout.WriteRune(r)\n\t}\n\treturn nil, nil\n}\n\nfunc handleEscape(p *parser, in, out *bytes.Buffer) (handler, error) {\n\tr, _, err := in.ReadRune()\n\tif err == io.EOF {\n\t\treturn nil, ErrUnexpectedEOF\n\t}\n\n\tif r == '{' {\n\t\treturn handleEscapeClause, nil\n\t} else if r == p.escape {\n\t\tout.WriteRune(p.escape)\n\t} else if p.color {\n\t\tout.WriteString(ColorCode(string(r)))\n\t}\n\treturn handleRegular, nil\n}\n\nfunc handleEscapeClause(p *parser, in, out *bytes.Buffer) (handler, error) {\n\tbs := bytes.NewBufferString(\"\")\n\tfor {\n\t\tr, _, err := in.ReadRune()\n\t\tif err == io.EOF {\n\t\t\treturn nil, ErrUnexpectedEOF\n\t\t}\n\n\t\tif r == '}' {\n\t\t\tbreak\n\t\t}\n\t\tbs.WriteRune(r)\n\t}\n\n\tif p.color {\n\t\tout.WriteString(ColorCode(bs.String()))\n\t}\n\treturn handleRegular, nil\n}\n<commit_msg>Adding Set(string) error function<commit_after>\/\/ Copyright 2013, 2015 Ben Morgan. All rights reserved.\n\/\/ Use of this source code is governed by an MIT license\n\/\/ that can be found in the LICENSE file.\n\n\/\/ Copyright 2013, Meng Zhang. All rights reserved.\n\/\/ URL: https:\/\/github.com\/wsxiaoys\/terminal\n\/\/ File URL: https:\/\/github.com\/wsxiaoys\/terminal\/blob\/decf4e097e2e3471b254da8d30c3599d330fe7ba\/color\/color.go\n\n\/\/ Package color provides printing in ANSI colors.\n\/\/\n\/\/ TODO: Need to document this. See the Color function for now.\n\/\/\n\/\/ This package uses code from [github.com\/wsxiaoys\/terminal](https:\/\/github.com\/wsxiaoys\/terminal). Many thanks.\npackage color\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\n\t\"golang.org\/x\/crypto\/ssh\/terminal\"\n)\n\n\/\/ Mapping from character to concrete escape code.\nvar codeMap = map[int]int{\n\t'|': 0,\n\t'!': 1,\n\t'.': 2,\n\t'\/': 3,\n\t'_': 4,\n\t'^': 5,\n\t'&': 6,\n\t'?': 7,\n\t'-': 8,\n\n\t'k': 30,\n\t'r': 31,\n\t'g': 32,\n\t'y': 33,\n\t'b': 34,\n\t'm': 35,\n\t'c': 36,\n\t'w': 37,\n\t'd': 39,\n\n\t'K': 40,\n\t'R': 41,\n\t'G': 42,\n\t'Y': 43,\n\t'B': 44,\n\t'M': 45,\n\t'C': 46,\n\t'W': 47,\n\t'D': 49,\n}\n\n\/\/ ErrInvalidEscape is an error that is used when the parser panics.\nvar ErrInvalidEscape = errors.New(\"invalid escape rune\")\nvar ErrUnexpectedEOF = errors.New(\"unexpected EOF while parsing\")\n\n\/\/ ColorReset is the string that resets the text to default style.\nconst ColorReset = \"\\033[0m\"\n\n\/\/ ColorCode compiles a color syntax string like \"rG\" to escape code.\nfunc ColorCode(s string) string {\n\tattr := 0\n\tfg := 39\n\tbg := 49\n\n\tfor _, key := range s {\n\t\tc, ok := codeMap[int(key)]\n\t\tif !ok {\n\t\t\tpanic(\"wrong color syntax: \" + string(key))\n\t\t}\n\n\t\tswitch {\n\t\tcase 0 <= c && c <= 8:\n\t\t\tattr = c\n\t\tcase 30 <= c && c <= 37:\n\t\t\tfg = c\n\t\tcase 40 <= c && c <= 47:\n\t\t\tbg = c\n\t\t}\n\t}\n\treturn fmt.Sprintf(\"\\033[%d;%d;%dm\", attr, fg, bg)\n}\n\n\/\/ Color translates a string into an escaped string.\n\/\/\n\/\/ This example will output the text with a Blue foreground and a Black background\n\/\/      color.Println(\"@{bK}Example Text\")\n\/\/\n\/\/ This one will output the text with a red foreground\n\/\/      color.Println(\"@rExample Text\")\n\/\/\n\/\/ This one will escape the @\n\/\/      color.Println(\"@@\")\n\/\/\n\/\/ Full color syntax code\n\/\/      @{rgbcmykwRGBCMYKW}  foreground\/background color\n\/\/        r\/R:  Red\n\/\/        g\/G:  Green\n\/\/        b\/B:  Blue\n\/\/        c\/C:  Cyan\n\/\/        m\/M:  Magenta\n\/\/        y\/Y:  Yellow\n\/\/        k\/K:  Black\n\/\/        w\/W:  White\n\/\/      @{|}  Reset format style\n\/\/      @{!.\/_} Bold \/ Dim \/ Italic \/ Underline\n\/\/      @{^&} Blink \/ Fast blink\n\/\/      @{?} Reverse the foreground and background color\n\/\/      @{-} Hide the text\n\/\/ Note some of the functions are not widely supported, like \"Fast blink\" and \"Italic\".\nfunc Color(s string, escape rune) string {\n\treturn newParser(escape, true).translateReset(s)\n}\n\n\/\/ Decolor cleans a string of @x color codes.\nfunc Decolor(s string, escape rune) string {\n\treturn newParser(escape, false).translateReset(s)\n}\n\n\/\/ Uncolor cleans a string of ANSI color codes.\nfunc Uncolor(s string) string {\n\tpanic(\"not implemented\")\n}\n\ntype Colorizer struct {\n\tw io.Writer\n\t*parser\n}\n\nfunc New() *Colorizer {\n\treturn &Colorizer{\n\t\tw:      os.Stdout,\n\t\tparser: newParser('@', true),\n\t}\n}\n\nfunc (c *Colorizer) EscapeChar() rune {\n\treturn c.parser.escape\n}\n\n\/\/ Set sets c on or off, with s one of \"auto\", \"always\", or \"never\",\n\/\/ otherwise an error is returned.\n\/\/\n\/\/ Note: if \"auto\" is passed, and SetOutput was passed an io.Writer that\n\/\/ is not an *os.File, nothing will happen.\n\/\/ This lets you decide whether you want it to fall back to enabled or disabled.\nfunc (c *Colorizer) Set(s string) (err error) {\n\tswitch s {\n\tcase \"auto\":\n\t\tif w, ok := c.w.(*os.File); ok {\n\t\t\tc.SetFile(w)\n\t\t}\n\t\t\/\/ TODO: Decide what to do in this case. It's a writer, but not to a file,\n\t\t\/\/ so I don't know how it will act. The conservative thing to do would be\n\t\t\/\/ to disable it, the liberal thing would be to allow the user (programmer)\n\t\t\/\/ to decide before-hand what will happen.\n\tcase \"always\":\n\t\tc.SetEnabled(true)\n\tcase \"never\":\n\t\tc.SetEnabled(false)\n\tdefault:\n\t\terr = errors.New(\"expect one of auto, always, or never\")\n\t}\n\treturn err\n}\n\n\/\/ SetEscapeChar sets the escape character, which can be one of the following characters:\n\/\/\n\/\/\t\t@ * + = ~\n\/\/\n\/\/ If it is none of these characters, then this function panics with ErrInvalidEscape.\nfunc (c *Colorizer) SetEscapeChar(r rune) {\n\tif c.EscapeChar() == r {\n\t\treturn\n\t}\n\n\tfor _, q := range []rune{'*', '@', '+', '=', '~'} {\n\t\tif r == q {\n\t\t\tc.parser.escape = r\n\t\t\treturn\n\t\t}\n\t}\n\n\tpanic(ErrInvalidEscape)\n}\n\nfunc (c *Colorizer) Enabled() bool {\n\treturn c.parser.color\n}\n\nfunc (c *Colorizer) SetEnabled(b bool) {\n\tif c.Enabled() == b {\n\t\treturn\n\t}\n\tc.parser.color = b\n}\n\nfunc (c *Colorizer) SetOutput(w io.Writer) {\n\tc.w = w\n}\n\nfunc (c *Colorizer) SetFile(f *os.File) {\n\tc.SetEnabled(terminal.IsTerminal(int(f.Fd())))\n\tc.w = f\n}\n\nfunc (c *Colorizer) Color(s string) string {\n\treturn c.translateReset(s)\n}\n\nfunc (c *Colorizer) colorAny(args []interface{}) []interface{} {\n\tn := len(args)\n\tr := make([]interface{}, n, n+1)\n\tfor i, x := range args {\n\t\tif str, ok := x.(string); ok {\n\t\t\tx = c.translateOnly(str)\n\t\t}\n\t\tr[i] = x\n\t}\n\tif c.Enabled() {\n\t\tr = append(r, ColorReset)\n\t}\n\treturn r\n}\n\nfunc (c *Colorizer) Print(a ...interface{}) (int, error) {\n\treturn fmt.Fprint(c.w, c.colorAny(a)...)\n}\nfunc (c *Colorizer) Println(a ...interface{}) (int, error) {\n\treturn fmt.Fprintln(c.w, c.colorAny(a)...)\n}\nfunc (c *Colorizer) Printf(format string, a ...interface{}) (int, error) {\n\treturn fmt.Fprintf(c.w, c.translateReset(format), a...)\n}\nfunc (c *Colorizer) Fprint(w io.Writer, a ...interface{}) (int, error) {\n\treturn fmt.Fprint(w, c.colorAny(a)...)\n}\nfunc (c *Colorizer) Fprintln(w io.Writer, a ...interface{}) (int, error) {\n\treturn fmt.Fprintln(w, c.colorAny(a)...)\n}\nfunc (c *Colorizer) Fprintf(w io.Writer, format string, a ...interface{}) (int, error) {\n\treturn fmt.Fprintf(w, c.translateReset(format), a...)\n}\nfunc (c *Colorizer) Sprint(a ...interface{}) string {\n\treturn fmt.Sprint(c.colorAny(a)...)\n}\nfunc (c *Colorizer) Sprintln(a ...interface{}) string {\n\treturn fmt.Sprintln(c.colorAny(a)...)\n}\nfunc (c *Colorizer) Sprintf(format string, a ...interface{}) string {\n\treturn fmt.Sprintf(c.translateReset(format), a...)\n}\n\ntype parser struct {\n\tescape rune\n\tcolor  bool\n}\n\nfunc newParser(escape rune, color bool) *parser {\n\treturn &parser{\n\t\tescape: escape,\n\t\tcolor:  color,\n\t}\n}\n\ntype handler func(p *parser, in, out *bytes.Buffer) (handler, error)\n\nfunc (p *parser) translateReset(s string) string {\n\tin := bytes.NewBufferString(s)\n\tout := bytes.NewBufferString(\"\")\n\n\tvar h = handleRegular\n\tvar err error\n\tfor {\n\t\th, err = h(p, in, out)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif h == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tif p.color {\n\t\tout.WriteString(ColorReset)\n\t}\n\treturn out.String()\n}\n\nfunc (p *parser) translateOnly(s string) string {\n\tin := bytes.NewBufferString(s)\n\tout := bytes.NewBufferString(\"\")\n\n\tvar h = handleRegular\n\tvar err error\n\tfor {\n\t\th, err = h(p, in, out)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif h == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn out.String()\n}\n\nfunc handleRegular(p *parser, in, out *bytes.Buffer) (handler, error) {\n\tfor {\n\t\tr, _, err := in.ReadRune()\n\t\t\/\/ The only error that can happen here is that we have reached the end of file,\n\t\t\/\/ or that a rune is messed up. If the rune is messed up, we treat it normally.\n\t\t\/\/ This is why we only check for io.EOF.\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\n\t\tif r == p.escape {\n\t\t\treturn handleEscape, nil\n\t\t}\n\t\tout.WriteRune(r)\n\t}\n\treturn nil, nil\n}\n\nfunc handleEscape(p *parser, in, out *bytes.Buffer) (handler, error) {\n\tr, _, err := in.ReadRune()\n\tif err == io.EOF {\n\t\treturn nil, ErrUnexpectedEOF\n\t}\n\n\tif r == '{' {\n\t\treturn handleEscapeClause, nil\n\t} else if r == p.escape {\n\t\tout.WriteRune(p.escape)\n\t} else if p.color {\n\t\tout.WriteString(ColorCode(string(r)))\n\t}\n\treturn handleRegular, nil\n}\n\nfunc handleEscapeClause(p *parser, in, out *bytes.Buffer) (handler, error) {\n\tbs := bytes.NewBufferString(\"\")\n\tfor {\n\t\tr, _, err := in.ReadRune()\n\t\tif err == io.EOF {\n\t\t\treturn nil, ErrUnexpectedEOF\n\t\t}\n\n\t\tif r == '}' {\n\t\t\tbreak\n\t\t}\n\t\tbs.WriteRune(r)\n\t}\n\n\tif p.color {\n\t\tout.WriteString(ColorCode(bs.String()))\n\t}\n\treturn handleRegular, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ File: .\/blockfreight\/lib\/leveldb\/leveldb.go\n\/\/ Summary: Application code for Blockfreight™ | The blockchain of global freight.\n\/\/ License: MIT License\n\/\/ Company: Blockfreight, Inc.\n\/\/ Author: Julian Nunez, Neil Tran, Julian Smith, Gian Felipe & contributors\n\/\/ Site: https:\/\/blockfreight.com\n\/\/ Support: <support@blockfreight.com>\n\n\/\/ Copyright © 2017 Blockfreight, Inc. All Rights Reserved.\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/\/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\/\/ =================================================================================================================================================\n\/\/ =================================================================================================================================================\n\/\/\n\/\/ BBBBBBBBBBBb     lll                                kkk             ffff                         iii                  hhh            ttt\n\/\/ BBBB``````BBBB   lll                                kkk            fff                           ```                  hhh            ttt\n\/\/ BBBB      BBBB   lll      oooooo        ccccccc     kkk    kkkk  fffffff  rrr  rrr    eeeee      iii     gggggg ggg   hhh  hhhhh   tttttttt\n\/\/ BBBBBBBBBBBB     lll    ooo    oooo    ccc    ccc   kkk   kkk    fffffff  rrrrrrrr eee    eeee   iii   gggg   ggggg   hhhh   hhhh  tttttttt\n\/\/ BBBBBBBBBBBBBB   lll   ooo      ooo   ccc           kkkkkkk        fff    rrrr    eeeeeeeeeeeee  iii  gggg      ggg   hhh     hhh    ttt\n\/\/ BBBB       BBB   lll   ooo      ooo   ccc           kkkk kkkk      fff    rrr     eeeeeeeeeeeee  iii   ggg      ggg   hhh     hhh    ttt\n\/\/ BBBB      BBBB   lll   oooo    oooo   cccc    ccc   kkk   kkkk     fff    rrr      eee      eee  iii    ggg    gggg   hhh     hhh    tttt    ....\n\/\/ BBBBBBBBBBBBB    lll     oooooooo       ccccccc     kkk     kkkk   fff    rrr       eeeeeeeee    iii     gggggg ggg   hhh     hhh     ttttt  ....\n\/\/                                                                                                        ggg      ggg\n\/\/   Blockfreight™ | The blockchain of global freight.                                                      ggggggggg\n\/\/\n\/\/ =================================================================================================================================================\n\/\/ =================================================================================================================================================\n\n\/\/ Package leveldb provides some useful functions to work with LevelDB.\n\/\/ It has common database functions as OpenDB, CloseDB, Insert and Iterate.\npackage leveldb\n\nimport (\n\t\/\/ =======================\n\t\/\/ Golang Standard library\n\t\/\/ =======================\n\t\"encoding\/json\" \/\/ Implements encoding and decoding of JSON as defined in RFC 4627.\n\t\"errors\"        \/\/ Implements functions to manipulate errors.\n\n\t\/\/ ====================\n\t\/\/ Third-party packages\n\t\/\/ ====================\n\t\"github.com\/syndtr\/goleveldb\/leveldb\" \/\/ Implementation of the LevelDB key\/value database in the Go programming language.\n\n\t\/\/ ======================\n\t\/\/ Blockfreight™ packages\n\t\/\/ ======================\n\t\"github.com\/blockfreight\/go-bftx\/lib\/app\/bf_tx\" \/\/ Defines the Blockfreight™ Transaction (BF_TX) transaction standard and provides some useful functions to work with the BF_TX.\n)\n\nvar dbPath = \"bft-db\" \/\/Folder name where is going to be the LevelDB\n\n\/\/ OpenDB is a function that receives the path of the DB, creates or opens that DB and return ir with a possible error if that occurred.\nfunc OpenDB(dbPath string) (db *leveldb.DB, err error) {\n\tdb, err = leveldb.OpenFile(dbPath, nil)\n\treturn db, err\n\n}\n\n\/\/ CloseDB is a function that receives a DB pointer that closes the connection to DB.\nfunc CloseDB(db *leveldb.DB) {\n\tdb.Close()\n}\n\n\/\/ InsertBFTX is a function that receives the key and value strings to insert a tuple in determined DB, the final parameter. As result, it returns a true or false bool.\nfunc InsertBFTX(key string, value string, db *leveldb.DB) error {\n\treturn db.Put([]byte(key), []byte(value), nil)\n}\n\n\/\/ Total is a function that returns the total of BF_TX stored in the DB.\nfunc Total() (int, error) {\n\tdb, err := OpenDB(dbPath)\n\tdefer CloseDB(db)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\titer := db.NewIterator(nil, nil)\n\tn := 0\n\tfor iter.Next() {\n\t\tn += 1\n\t}\n\titer.Release()\n\treturn n, iter.Error()\n}\n\n\/\/ RecordOnDB is a function that receives the content of the BF_RX JSON to insert it into the DB and return true or false according to the result.\nfunc RecordOnDB(id string, json string) error {\n\tdb, err := OpenDB(dbPath)\n\tdefer CloseDB(db)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = InsertBFTX(id, json, db)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ GetBfTx is a function that receives a bf_tx id, and returns the BF_TX if it exists.\nfunc GetBfTx(id string) (bf_tx.BF_TX, error) {\n\tvar bftx bf_tx.BF_TX\n\tdb, err := OpenDB(dbPath)\n\tdefer CloseDB(db)\n\tif err != nil {\n\t\treturn bftx, err\n\t}\n\n\tdata, err := db.Get([]byte(id), nil)\n\tif err != nil {\n\t\tif err.Error() == \"leveldb: not found\" {\n\t\t\treturn bftx, errors.New(\"LevelDB Get function: BF_TX not found.\")\n\t\t}\n\t\treturn bftx, errors.New(\"LevelDB Get function: \" + err.Error())\n\t}\n\n\tjson.Unmarshal(data, &bftx)\n\treturn bftx, nil\n}\n\n\/\/ Verify is a function that receives a content and look for a BF_TX that has the same content.\nfunc Verify(jcontent string) ([]byte, error) {\n\tvar bftx bf_tx.BF_TX\n\tdb, err := OpenDB(dbPath)\n\tdefer CloseDB(db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titer := db.NewIterator(nil, nil)\n\tfor iter.Next() {\n\t\tkey := iter.Key()\n\t\tvalue := iter.Value()\n\n\t\t\/\/ Get a BF_TX by id\n\t\tjson.Unmarshal(value, &bftx)\n\n\t\t\/\/ Reinitialize the BF_TX\n\t\tbftx = bf_tx.Reinitialize(bftx)\n\n\t\t\/\/ Get the BF_TX old_content in string format\n\t\tcontent, err := bf_tx.BFTXContent(bftx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif jcontent == content {\n\t\t\titer.Release()\n\t\t\t\/\/strconv.Atoi(string(buf))\n\t\t\treturn key, nil\n\t\t}\n\t}\n\titer.Release()\n\n\treturn nil, iter.Error()\n}\n\n\/\/ =================================================\n\/\/ Blockfreight™ | The blockchain of global freight.\n\/\/ =================================================\n\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                    BBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                       BBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBB        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBB        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBB         BBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                     BBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBBB        BBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBBBB       BBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBBB        BBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBB        BBB       BBBBB\n\/\/ BBBBBBB                       BBBB       BBBBB\n\/\/ BBBBBBB                    BBBBBBB       BBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\n\/\/ ==================================================\n\/\/ Blockfreight™ | The blockchain for global freight.\n\/\/ ==================================================\n<commit_msg>bft-db now instantiates in go-bftx directory<commit_after>\/\/ File: .\/blockfreight\/lib\/leveldb\/leveldb.go\n\/\/ Summary: Application code for Blockfreight™ | The blockchain of global freight.\n\/\/ License: MIT License\n\/\/ Company: Blockfreight, Inc.\n\/\/ Author: Julian Nunez, Neil Tran, Julian Smith, Gian Felipe & contributors\n\/\/ Site: https:\/\/blockfreight.com\n\/\/ Support: <support@blockfreight.com>\n\n\/\/ Copyright © 2017 Blockfreight, Inc. All Rights Reserved.\n\n\/\/ Permission is hereby granted, free of charge, to any person obtaining\n\/\/ a copy of this software and associated documentation files (the \"Software\"),\n\/\/ to deal in the Software without restriction, including without limitation\n\/\/ the rights to use, copy, modify, merge, publish, distribute, sublicense,\n\/\/ and\/or sell copies of the Software, and to permit persons to whom the\n\/\/ Software is furnished to do so, subject to the following conditions:\n\n\/\/ The above copyright notice and this permission notice shall be\n\/\/ included in all copies or substantial portions of the Software.\n\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\/\/ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\/\/ =================================================================================================================================================\n\/\/ =================================================================================================================================================\n\/\/\n\/\/ BBBBBBBBBBBb     lll                                kkk             ffff                         iii                  hhh            ttt\n\/\/ BBBB``````BBBB   lll                                kkk            fff                           ```                  hhh            ttt\n\/\/ BBBB      BBBB   lll      oooooo        ccccccc     kkk    kkkk  fffffff  rrr  rrr    eeeee      iii     gggggg ggg   hhh  hhhhh   tttttttt\n\/\/ BBBBBBBBBBBB     lll    ooo    oooo    ccc    ccc   kkk   kkk    fffffff  rrrrrrrr eee    eeee   iii   gggg   ggggg   hhhh   hhhh  tttttttt\n\/\/ BBBBBBBBBBBBBB   lll   ooo      ooo   ccc           kkkkkkk        fff    rrrr    eeeeeeeeeeeee  iii  gggg      ggg   hhh     hhh    ttt\n\/\/ BBBB       BBB   lll   ooo      ooo   ccc           kkkk kkkk      fff    rrr     eeeeeeeeeeeee  iii   ggg      ggg   hhh     hhh    ttt\n\/\/ BBBB      BBBB   lll   oooo    oooo   cccc    ccc   kkk   kkkk     fff    rrr      eee      eee  iii    ggg    gggg   hhh     hhh    tttt    ....\n\/\/ BBBBBBBBBBBBB    lll     oooooooo       ccccccc     kkk     kkkk   fff    rrr       eeeeeeeee    iii     gggggg ggg   hhh     hhh     ttttt  ....\n\/\/                                                                                                        ggg      ggg\n\/\/   Blockfreight™ | The blockchain of global freight.                                                      ggggggggg\n\/\/\n\/\/ =================================================================================================================================================\n\/\/ =================================================================================================================================================\n\n\/\/ Package leveldb provides some useful functions to work with LevelDB.\n\/\/ It has common database functions as OpenDB, CloseDB, Insert and Iterate.\npackage leveldb\n\nimport (\n\t\/\/ =======================\n\t\/\/ Golang Standard library\n\t\/\/ =======================\n\t\"encoding\/json\" \/\/ Implements encoding and decoding of JSON as defined in RFC 4627.\n\t\"errors\"        \/\/ Implements functions to manipulate errors.\n\t\"os\"            \/\/ Provides a platform-independent interface to operating system functionality.\n\n\t\/\/ ====================\n\t\/\/ Third-party packages\n\t\/\/ ====================\n\t\"github.com\/syndtr\/goleveldb\/leveldb\" \/\/ Implementation of the LevelDB key\/value database in the Go programming language.\n\n\t\/\/ ======================\n\t\/\/ Blockfreight™ packages\n\t\/\/ ======================\n\t\"github.com\/blockfreight\/go-bftx\/lib\/app\/bf_tx\" \/\/ Defines the Blockfreight™ Transaction (BF_TX) transaction standard and provides some useful functions to work with the BF_TX.\n)\n\nvar dbPath = os.Getenv(\"GOPATH\") + \"\/src\/github.com\/blockfreight\/go-bftx\/bft-db\" \/\/Folder name where is going to be the LevelDB\n\n\/\/ OpenDB is a function that receives the path of the DB, creates or opens that DB and return ir with a possible error if that occurred.\nfunc OpenDB(dbPath string) (db *leveldb.DB, err error) {\n\tdb, err = leveldb.OpenFile(dbPath, nil)\n\treturn db, err\n}\n\n\/\/ CloseDB is a function that receives a DB pointer that closes the connection to DB.\nfunc CloseDB(db *leveldb.DB) {\n\tdb.Close()\n}\n\n\/\/ InsertBFTX is a function that receives the key and value strings to insert a tuple in determined DB, the final parameter. As result, it returns a true or false bool.\nfunc InsertBFTX(key string, value string, db *leveldb.DB) error {\n\treturn db.Put([]byte(key), []byte(value), nil)\n}\n\n\/\/ Total is a function that returns the total of BF_TX stored in the DB.\nfunc Total() (int, error) {\n\tdb, err := OpenDB(dbPath)\n\tdefer CloseDB(db)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\titer := db.NewIterator(nil, nil)\n\tn := 0\n\tfor iter.Next() {\n\t\tn += 1\n\t}\n\titer.Release()\n\treturn n, iter.Error()\n}\n\n\/\/ RecordOnDB is a function that receives the content of the BF_RX JSON to insert it into the DB and return true or false according to the result.\nfunc RecordOnDB(id string, json string) error {\n\tdb, err := OpenDB(dbPath)\n\tdefer CloseDB(db)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = InsertBFTX(id, json, db)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ GetBfTx is a function that receives a bf_tx id, and returns the BF_TX if it exists.\nfunc GetBfTx(id string) (bf_tx.BF_TX, error) {\n\tvar bftx bf_tx.BF_TX\n\tdb, err := OpenDB(dbPath)\n\tdefer CloseDB(db)\n\tif err != nil {\n\t\treturn bftx, err\n\t}\n\n\tdata, err := db.Get([]byte(id), nil)\n\tif err != nil {\n\t\tif err.Error() == \"leveldb: not found\" {\n\t\t\treturn bftx, errors.New(\"LevelDB Get function: BF_TX not found.\")\n\t\t}\n\t\treturn bftx, errors.New(\"LevelDB Get function: \" + err.Error())\n\t}\n\n\tjson.Unmarshal(data, &bftx)\n\treturn bftx, nil\n}\n\n\/\/ Verify is a function that receives a content and look for a BF_TX that has the same content.\nfunc Verify(jcontent string) ([]byte, error) {\n\tvar bftx bf_tx.BF_TX\n\tdb, err := OpenDB(dbPath)\n\tdefer CloseDB(db)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\titer := db.NewIterator(nil, nil)\n\tfor iter.Next() {\n\t\tkey := iter.Key()\n\t\tvalue := iter.Value()\n\n\t\t\/\/ Get a BF_TX by id\n\t\tjson.Unmarshal(value, &bftx)\n\n\t\t\/\/ Reinitialize the BF_TX\n\t\tbftx = bf_tx.Reinitialize(bftx)\n\n\t\t\/\/ Get the BF_TX old_content in string format\n\t\tcontent, err := bf_tx.BFTXContent(bftx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif jcontent == content {\n\t\t\titer.Release()\n\t\t\t\/\/strconv.Atoi(string(buf))\n\t\t\treturn key, nil\n\t\t}\n\t}\n\titer.Release()\n\n\treturn nil, iter.Error()\n}\n\n\/\/ =================================================\n\/\/ Blockfreight™ | The blockchain of global freight.\n\/\/ =================================================\n\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                    BBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                       BBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBB        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBB        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBB         BBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                     BBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBB                        BBBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBBB        BBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBBBB       BBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBBB        BBBBBBBBBBBBBB\n\/\/ BBBBBBB       BBBBBBBBB        BBB       BBBBB\n\/\/ BBBBBBB                       BBBB       BBBBB\n\/\/ BBBBBBB                    BBBBBBB       BBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\/\/ BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\n\/\/ ==================================================\n\/\/ Blockfreight™ | The blockchain for global freight.\n\/\/ ==================================================\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The Upspin Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package flags defines command-line flags to make them consistent between binaries.\n\/\/ Not all flags make sense for all binaries.\npackage flags \/\/ import \"upspin.io\/flags\"\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"upspin.io\/log\"\n)\n\n\/\/ flagVar represents a flag in this package.\ntype flagVar struct {\n\tset  func()        \/\/ Set the value at parse time.\n\targ  func() string \/\/ Return the argument to set the flag.\n\targ2 func() string \/\/ Return the argument to set the second flag; usually nil.\n}\n\nconst (\n\tdefaultBlockSize  = 1024 * 1024 \/\/ Keep in sync with upspin.BlockSize.]\n\tdefaultHTTPAddr   = \":80\"\n\tdefaultHTTPSAddr  = \":443\"\n\tdefaultLog        = \"info\"\n\tdefaultServerKind = \"inprocess\"\n)\n\nvar (\n\t\/\/ BlockSize is the block size used when writing large files. The default is 1MB.\n\tBlockSize = defaultBlockSize\n\n\t\/\/ CacheDir specifies the directory for the various file caches.\n\tdefaultCacheDir = filepath.Join(os.Getenv(\"HOME\"), \"upspin\")\n\tCacheDir        = defaultCacheDir\n\n\t\/\/ Config names the Upspin configuration file to use.\n\tdefaultConfig = filepath.Join(os.Getenv(\"HOME\"), \"upspin\", \"config\")\n\tConfig        = defaultConfig\n\n\t\/\/ HTTPAddr is the network address on which to listen for incoming\n\t\/\/ insecure network connections.\n\tHTTPAddr = defaultHTTPAddr\n\n\t\/\/ HTTPSAddr is the network address on which to listen for incoming\n\t\/\/ secure network connections.\n\tHTTPSAddr = defaultHTTPSAddr\n\n\t\/\/ LetsEncryptCache is the location of a file in which the Let's\n\t\/\/ Encrypt certificates are stored. The containing directory should\n\t\/\/ be owner-accessible only (chmod 0700).\n\tLetsEncryptCache = \"\"\n\n\t\/\/ Log sets the level of logging (implements flag.Value).\n\tLog logFlag\n\n\t\/\/ NetAddr is the publicly accessible network address of this server.\n\tNetAddr = \"\"\n\n\t\/\/ Project is the project name on GCP; used by servers, upspin-deploy,\n\t\/\/ and cmd\/upspin setupdomain.\n\tProject = \"\"\n\n\t\/\/ ServerConfig specifies configuration options (\"key=value\") for servers.\n\tServerConfig []string\n\n\t\/\/ ServerKind is the implementation kind of this server.\n\tServerKind = defaultServerKind\n\n\t\/\/ StoreServerName is the Upspin user name of the StoreServer.\n\tStoreServerUser = \"\"\n\n\t\/\/ TLSCertFile and TLSKeyFile specify the location of a TLS\n\t\/\/ certificate\/key pair used for serving TLS (HTTPS).\n\tTLSCertFile = \"\"\n\tTLSKeyFile  = \"\"\n)\n\n\/\/ flags is a map of flag registration functions keyed by flag name,\n\/\/ used by Parse to register specific (or all) flags.\nvar flags = map[string]*flagVar{\n\t\"addr\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&NetAddr, \"addr\", \"\", \"publicly accessible network address (`host:port`)\")\n\t\t},\n\t\targ: func() string { return strArg(\"addr\", NetAddr, \"\") },\n\t},\n\t\"blocksize\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.IntVar(&BlockSize, \"blocksize\", BlockSize, \"`size` of blocks when writing larg:e files\")\n\t\t},\n\t\targ: func() string {\n\t\t\tif BlockSize == defaultBlockSize {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn fmt.Sprintf(\"-blocksize=%d\", BlockSize)\n\t\t},\n\t},\n\t\"cachedir\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&CacheDir, \"cachedir\", CacheDir, \"`directory` containing all file caches\")\n\t\t},\n\t\targ: func() string {\n\t\t\treturn strArg(\"cachedir\", CacheDir, defaultCacheDir)\n\t\t},\n\t},\n\t\"config\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&Config, \"config\", Config, \"user's configuration `file`\")\n\t\t},\n\t\targ: func() string { return strArg(\"config\", Config, defaultConfig) },\n\t},\n\t\"http\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&HTTPAddr, \"http\", HTTPAddr, \"`address` for incoming insecure network connections\")\n\t\t},\n\t\targ: func() string { return strArg(\"http\", HTTPAddr, defaultHTTPAddr) },\n\t},\n\t\"https\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&HTTPSAddr, \"https\", HTTPSAddr, \"`address` for incoming secure network connections\")\n\t\t},\n\t\targ: func() string { return strArg(\"https\", HTTPSAddr, defaultHTTPSAddr) },\n\t},\n\t\"kind\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&ServerKind, \"kind\", ServerKind, \"server implementation `kind` (inprocess, gcp)\")\n\t\t},\n\t\targ: func() string { return strArg(\"kind\", ServerKind, defaultServerKind) },\n\t},\n\t\"letscache\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&LetsEncryptCache, \"letscache\", \"\", \"Let's Encrypt cache `directory`\")\n\t\t},\n\t\targ: func() string { return strArg(\"letscache\", LetsEncryptCache, \"\") },\n\t},\n\t\"log\": &flagVar{\n\t\tset: func() {\n\t\t\tLog.Set(\"info\")\n\t\t\tflag.Var(&Log, \"log\", \"`level` of logging: debug, info, error, disabled\")\n\t\t},\n\t\targ: func() string { return strArg(\"log\", Log.String(), defaultLog) },\n\t},\n\t\"project\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&Project, \"project\", Project, \"GCP `project` name\")\n\t\t},\n\t\targ: func() string { return strArg(\"-project=\", Project, \"\") },\n\t},\n\t\"serverconfig\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.Var(configFlag{&ServerConfig}, \"serverconfig\", \"comma-separated list of configuration options (key=value) for this server\")\n\t\t},\n\t\targ: func() string { return strArg(\"-serverconfig=\", configFlag{&ServerConfig}.String(), \"\") },\n\t},\n\t\"storeserveruser\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&StoreServerUser, \"storeserveruser\", \"\", \"user name of the StoreServer\")\n\t\t},\n\t\targ: func() string { return strArg(\"storeserveruser\", StoreServerUser, \"\") },\n\t},\n\t\"tls\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&TLSCertFile, \"tls_cert\", \"\", \"TLS Certificate `file` in PEM format\")\n\t\t\tflag.StringVar(&TLSKeyFile, \"tls_key\", \"\", \"TLS Key `file` in PEM format\")\n\t\t},\n\t\targ:  func() string { return strArg(\"tls_cert\", TLSCertFile, \"\") },\n\t\targ2: func() string { return strArg(\"tls_key\", TLSKeyFile, \"\") },\n\t},\n}\n\n\/\/ Parse registers the command-line flags for the given flag names\n\/\/ and calls flag.Parse. Passing zero names registers all flags.\n\/\/ Passing an unknown name triggers a panic.\n\/\/\n\/\/ For example:\n\/\/ \tflags.Parse(\"config\", \"endpoint\") \/\/ Register Config and Endpoint.\n\/\/ or\n\/\/ \tflags.Parse() \/\/ Register all flags.\nfunc Parse(names ...string) {\n\tif len(names) == 0 {\n\t\t\/\/ Register all flags if no names provided.\n\t\tfor _, flag := range flags {\n\t\t\tflag.set()\n\t\t}\n\t} else {\n\t\tfor _, n := range names {\n\t\t\tflag, ok := flags[n]\n\t\t\tif !ok {\n\t\t\t\tpanic(fmt.Sprintf(\"unknown flag %q\", n))\n\t\t\t}\n\t\t\tflag.set()\n\t\t}\n\t}\n\tflag.Parse()\n}\n\n\/\/ Args returns a slice of -flag=value strings that will recreate\n\/\/ the state of the flags. Flags set to their default value are elided.\nfunc Args() []string {\n\tvar args []string\n\tfor _, flag := range flags {\n\t\targ := flag.arg()\n\t\tif arg == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\targs = append(args, arg)\n\t\tif flag.arg2 != nil {\n\t\t\targs = append(args, flag.arg2())\n\t\t}\n\t}\n\treturn args\n}\n\n\/\/ strArg returns a command-line argument that will recreate the flag,\n\/\/ or the empty string if the value is the default.\nfunc strArg(name, value, _default string) string {\n\tif value == _default {\n\t\treturn \"\"\n\t}\n\treturn \"-\" + name + \"=\" + value\n}\n\ntype logFlag string\n\n\/\/ String implements flag.Value.\nfunc (f logFlag) String() string {\n\treturn string(f)\n}\n\n\/\/ Set implements flag.Value.\nfunc (f *logFlag) Set(level string) error {\n\terr := log.SetLevel(level)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*f = logFlag(log.GetLevel())\n\treturn nil\n}\n\n\/\/ Get implements flag.Getter.\nfunc (logFlag) Get() interface{} {\n\treturn log.GetLevel()\n}\n\ntype configFlag struct {\n\ts *[]string\n}\n\n\/\/ String implements flag.Value.\nfunc (f configFlag) String() string {\n\tif f.s == nil {\n\t\treturn \"\"\n\t}\n\treturn strings.Join(*f.s, \",\")\n}\n\n\/\/ Set implements flag.Value.\nfunc (f configFlag) Set(s string) error {\n\tss := strings.Split(strings.TrimSpace(s), \",\")\n\t\/\/ Drop empty elements.\n\tfor i := 0; i < len(ss); i++ {\n\t\tif ss[i] == \"\" {\n\t\t\tss = append(ss[:i], ss[i+1:]...)\n\t\t}\n\t}\n\t*f.s = ss\n\treturn nil\n}\n\n\/\/ Get implements flag.Getter.\nfunc (f configFlag) Get() interface{} {\n\tif f.s == nil {\n\t\treturn \"\"\n\t}\n\treturn *f.s\n}\n<commit_msg>flags: delete - and = from a few calls to setVar<commit_after>\/\/ Copyright 2016 The Upspin Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package flags defines command-line flags to make them consistent between binaries.\n\/\/ Not all flags make sense for all binaries.\npackage flags \/\/ import \"upspin.io\/flags\"\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"upspin.io\/log\"\n)\n\n\/\/ flagVar represents a flag in this package.\ntype flagVar struct {\n\tset  func()        \/\/ Set the value at parse time.\n\targ  func() string \/\/ Return the argument to set the flag.\n\targ2 func() string \/\/ Return the argument to set the second flag; usually nil.\n}\n\nconst (\n\tdefaultBlockSize  = 1024 * 1024 \/\/ Keep in sync with upspin.BlockSize.]\n\tdefaultHTTPAddr   = \":80\"\n\tdefaultHTTPSAddr  = \":443\"\n\tdefaultLog        = \"info\"\n\tdefaultServerKind = \"inprocess\"\n)\n\nvar (\n\t\/\/ BlockSize is the block size used when writing large files. The default is 1MB.\n\tBlockSize = defaultBlockSize\n\n\t\/\/ CacheDir specifies the directory for the various file caches.\n\tdefaultCacheDir = filepath.Join(os.Getenv(\"HOME\"), \"upspin\")\n\tCacheDir        = defaultCacheDir\n\n\t\/\/ Config names the Upspin configuration file to use.\n\tdefaultConfig = filepath.Join(os.Getenv(\"HOME\"), \"upspin\", \"config\")\n\tConfig        = defaultConfig\n\n\t\/\/ HTTPAddr is the network address on which to listen for incoming\n\t\/\/ insecure network connections.\n\tHTTPAddr = defaultHTTPAddr\n\n\t\/\/ HTTPSAddr is the network address on which to listen for incoming\n\t\/\/ secure network connections.\n\tHTTPSAddr = defaultHTTPSAddr\n\n\t\/\/ LetsEncryptCache is the location of a file in which the Let's\n\t\/\/ Encrypt certificates are stored. The containing directory should\n\t\/\/ be owner-accessible only (chmod 0700).\n\tLetsEncryptCache = \"\"\n\n\t\/\/ Log sets the level of logging (implements flag.Value).\n\tLog logFlag\n\n\t\/\/ NetAddr is the publicly accessible network address of this server.\n\tNetAddr = \"\"\n\n\t\/\/ Project is the project name on GCP; used by servers, upspin-deploy,\n\t\/\/ and cmd\/upspin setupdomain.\n\tProject = \"\"\n\n\t\/\/ ServerConfig specifies configuration options (\"key=value\") for servers.\n\tServerConfig []string\n\n\t\/\/ ServerKind is the implementation kind of this server.\n\tServerKind = defaultServerKind\n\n\t\/\/ StoreServerName is the Upspin user name of the StoreServer.\n\tStoreServerUser = \"\"\n\n\t\/\/ TLSCertFile and TLSKeyFile specify the location of a TLS\n\t\/\/ certificate\/key pair used for serving TLS (HTTPS).\n\tTLSCertFile = \"\"\n\tTLSKeyFile  = \"\"\n)\n\n\/\/ flags is a map of flag registration functions keyed by flag name,\n\/\/ used by Parse to register specific (or all) flags.\nvar flags = map[string]*flagVar{\n\t\"addr\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&NetAddr, \"addr\", \"\", \"publicly accessible network address (`host:port`)\")\n\t\t},\n\t\targ: func() string { return strArg(\"addr\", NetAddr, \"\") },\n\t},\n\t\"blocksize\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.IntVar(&BlockSize, \"blocksize\", BlockSize, \"`size` of blocks when writing larg:e files\")\n\t\t},\n\t\targ: func() string {\n\t\t\tif BlockSize == defaultBlockSize {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\treturn fmt.Sprintf(\"-blocksize=%d\", BlockSize)\n\t\t},\n\t},\n\t\"cachedir\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&CacheDir, \"cachedir\", CacheDir, \"`directory` containing all file caches\")\n\t\t},\n\t\targ: func() string {\n\t\t\treturn strArg(\"cachedir\", CacheDir, defaultCacheDir)\n\t\t},\n\t},\n\t\"config\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&Config, \"config\", Config, \"user's configuration `file`\")\n\t\t},\n\t\targ: func() string { return strArg(\"config\", Config, defaultConfig) },\n\t},\n\t\"http\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&HTTPAddr, \"http\", HTTPAddr, \"`address` for incoming insecure network connections\")\n\t\t},\n\t\targ: func() string { return strArg(\"http\", HTTPAddr, defaultHTTPAddr) },\n\t},\n\t\"https\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&HTTPSAddr, \"https\", HTTPSAddr, \"`address` for incoming secure network connections\")\n\t\t},\n\t\targ: func() string { return strArg(\"https\", HTTPSAddr, defaultHTTPSAddr) },\n\t},\n\t\"kind\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&ServerKind, \"kind\", ServerKind, \"server implementation `kind` (inprocess, gcp)\")\n\t\t},\n\t\targ: func() string { return strArg(\"kind\", ServerKind, defaultServerKind) },\n\t},\n\t\"letscache\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&LetsEncryptCache, \"letscache\", \"\", \"Let's Encrypt cache `directory`\")\n\t\t},\n\t\targ: func() string { return strArg(\"letscache\", LetsEncryptCache, \"\") },\n\t},\n\t\"log\": &flagVar{\n\t\tset: func() {\n\t\t\tLog.Set(\"info\")\n\t\t\tflag.Var(&Log, \"log\", \"`level` of logging: debug, info, error, disabled\")\n\t\t},\n\t\targ: func() string { return strArg(\"log\", Log.String(), defaultLog) },\n\t},\n\t\"project\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&Project, \"project\", Project, \"GCP `project` name\")\n\t\t},\n\t\targ: func() string { return strArg(\"project\", Project, \"\") },\n\t},\n\t\"serverconfig\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.Var(configFlag{&ServerConfig}, \"serverconfig\", \"comma-separated list of configuration options (key=value) for this server\")\n\t\t},\n\t\targ: func() string { return strArg(\"serverconfig\", configFlag{&ServerConfig}.String(), \"\") },\n\t},\n\t\"storeserveruser\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&StoreServerUser, \"storeserveruser\", \"\", \"user name of the StoreServer\")\n\t\t},\n\t\targ: func() string { return strArg(\"storeserveruser\", StoreServerUser, \"\") },\n\t},\n\t\"tls\": &flagVar{\n\t\tset: func() {\n\t\t\tflag.StringVar(&TLSCertFile, \"tls_cert\", \"\", \"TLS Certificate `file` in PEM format\")\n\t\t\tflag.StringVar(&TLSKeyFile, \"tls_key\", \"\", \"TLS Key `file` in PEM format\")\n\t\t},\n\t\targ:  func() string { return strArg(\"tls_cert\", TLSCertFile, \"\") },\n\t\targ2: func() string { return strArg(\"tls_key\", TLSKeyFile, \"\") },\n\t},\n}\n\n\/\/ Parse registers the command-line flags for the given flag names\n\/\/ and calls flag.Parse. Passing zero names registers all flags.\n\/\/ Passing an unknown name triggers a panic.\n\/\/\n\/\/ For example:\n\/\/ \tflags.Parse(\"config\", \"endpoint\") \/\/ Register Config and Endpoint.\n\/\/ or\n\/\/ \tflags.Parse() \/\/ Register all flags.\nfunc Parse(names ...string) {\n\tif len(names) == 0 {\n\t\t\/\/ Register all flags if no names provided.\n\t\tfor _, flag := range flags {\n\t\t\tflag.set()\n\t\t}\n\t} else {\n\t\tfor _, n := range names {\n\t\t\tflag, ok := flags[n]\n\t\t\tif !ok {\n\t\t\t\tpanic(fmt.Sprintf(\"unknown flag %q\", n))\n\t\t\t}\n\t\t\tflag.set()\n\t\t}\n\t}\n\tflag.Parse()\n}\n\n\/\/ Args returns a slice of -flag=value strings that will recreate\n\/\/ the state of the flags. Flags set to their default value are elided.\nfunc Args() []string {\n\tvar args []string\n\tfor _, flag := range flags {\n\t\targ := flag.arg()\n\t\tif arg == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\targs = append(args, arg)\n\t\tif flag.arg2 != nil {\n\t\t\targs = append(args, flag.arg2())\n\t\t}\n\t}\n\treturn args\n}\n\n\/\/ strArg returns a command-line argument that will recreate the flag,\n\/\/ or the empty string if the value is the default.\nfunc strArg(name, value, _default string) string {\n\tif value == _default {\n\t\treturn \"\"\n\t}\n\treturn \"-\" + name + \"=\" + value\n}\n\ntype logFlag string\n\n\/\/ String implements flag.Value.\nfunc (f logFlag) String() string {\n\treturn string(f)\n}\n\n\/\/ Set implements flag.Value.\nfunc (f *logFlag) Set(level string) error {\n\terr := log.SetLevel(level)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*f = logFlag(log.GetLevel())\n\treturn nil\n}\n\n\/\/ Get implements flag.Getter.\nfunc (logFlag) Get() interface{} {\n\treturn log.GetLevel()\n}\n\ntype configFlag struct {\n\ts *[]string\n}\n\n\/\/ String implements flag.Value.\nfunc (f configFlag) String() string {\n\tif f.s == nil {\n\t\treturn \"\"\n\t}\n\treturn strings.Join(*f.s, \",\")\n}\n\n\/\/ Set implements flag.Value.\nfunc (f configFlag) Set(s string) error {\n\tss := strings.Split(strings.TrimSpace(s), \",\")\n\t\/\/ Drop empty elements.\n\tfor i := 0; i < len(ss); i++ {\n\t\tif ss[i] == \"\" {\n\t\t\tss = append(ss[:i], ss[i+1:]...)\n\t\t}\n\t}\n\t*f.s = ss\n\treturn nil\n}\n\n\/\/ Get implements flag.Getter.\nfunc (f configFlag) Get() interface{} {\n\tif f.s == nil {\n\t\treturn \"\"\n\t}\n\treturn *f.s\n}\n<|endoftext|>"}
{"text":"<commit_before>package libreofficekit\n\nimport (\n\t\"testing\"\n)\n\nconst (\n\tDefaultLibreOfficePath  = \"\/usr\/lib\/libreoffice\/program\/\"\n\tDocumentThatDoesntExist = \"testdata\/kittens.docx\"\n\tSampleDocument          = \"testdata\/sample.docx\"\n)\n\nfunc TestInvalidOfficePath(t *testing.T) {\n\t_, err := NewOffice(\"\/etc\/passwd\")\n\tif err == nil {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestValidOfficePath(t *testing.T) {\n\t_, err := NewOffice(DefaultLibreOfficePath)\n\tif err != nil {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestGetOfficeErrorMessage(t *testing.T) {\n\toffice, _ := NewOffice(DefaultLibreOfficePath)\n\toffice.LoadDocument(DocumentThatDoesntExist)\n\tmessage := office.GetError()\n\tif len(message) == 0 {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestLoadDocumentThatDoesntExist(t *testing.T) {\n\toffice, _ := NewOffice(DefaultLibreOfficePath)\n\t_, err := office.LoadDocument(DocumentThatDoesntExist)\n\tif err == nil {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestSuccessLoadDocument(t *testing.T) {\n\toffice, _ := NewOffice(DefaultLibreOfficePath)\n\t_, err := office.LoadDocument(SampleDocument)\n\tif err != nil {\n\t\tt.Fail()\n\t}\n}\n<commit_msg>Moar tests<commit_after>package libreofficekit\n\nimport (\n\t\"testing\"\n)\n\nconst (\n\tDefaultLibreOfficePath  = \"\/usr\/lib\/libreoffice\/program\/\"\n\tDocumentThatDoesntExist = \"testdata\/kittens.docx\"\n\tSampleDocument          = \"testdata\/sample.docx\"\n)\n\nfunc TestInvalidOfficePath(t *testing.T) {\n\t_, err := NewOffice(\"\/etc\/passwd\")\n\tif err == nil {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestValidOfficePath(t *testing.T) {\n\t_, err := NewOffice(DefaultLibreOfficePath)\n\tif err != nil {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestGetOfficeErrorMessage(t *testing.T) {\n\toffice, _ := NewOffice(DefaultLibreOfficePath)\n\toffice.LoadDocument(DocumentThatDoesntExist)\n\tmessage := office.GetError()\n\tif len(message) == 0 {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestLoadDocumentThatDoesntExist(t *testing.T) {\n\toffice, _ := NewOffice(DefaultLibreOfficePath)\n\t_, err := office.LoadDocument(DocumentThatDoesntExist)\n\tif err == nil {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestSuccessLoadDocument(t *testing.T) {\n\toffice, _ := NewOffice(DefaultLibreOfficePath)\n\t_, err := office.LoadDocument(SampleDocument)\n\tif err != nil {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestGetPartPageRectangles(t *testing.T) {\n\toffice, _ := NewOffice(DefaultLibreOfficePath)\n\tdocument, _ := office.LoadDocument(SampleDocument)\n\trectangles := document.GetPartPageRectangles()\n\tif len(rectangles) != 2 {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestGetParts(t *testing.T) {\n\toffice, _ := NewOffice(DefaultLibreOfficePath)\n\tdocument, _ := office.LoadDocument(SampleDocument)\n\tparts := document.GetParts()\n\tif parts != 2 {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestGetTileMode(t *testing.T) {\n\toffice, _ := NewOffice(DefaultLibreOfficePath)\n\tdocument, _ := office.LoadDocument(SampleDocument)\n\tmode := document.GetTileMode()\n\tif mode != RGBATilemode && mode != BGRATilemode {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestGetViews(t *testing.T) {\n\toffice, _ := NewOffice(DefaultLibreOfficePath)\n\tdocument, _ := office.LoadDocument(SampleDocument)\n\tviews := document.GetViews()\n\tif views != 1 {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestGetType(t *testing.T) {\n\toffice, _ := NewOffice(DefaultLibreOfficePath)\n\tdocument, _ := office.LoadDocument(SampleDocument)\n\tdocumentType := document.GetType()\n\tif documentType != TextDocument {\n\t\tt.Fail()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage kubelet\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"k8s.io\/klog\/v2\"\n\tkubeadmapi \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/constants\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/images\"\n\tkubeadmutil \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/util\"\n)\n\ntype kubeletFlagsOpts struct {\n\tnodeRegOpts              *kubeadmapi.NodeRegistrationOptions\n\tpauseImage               string\n\tregisterTaintsUsingFlags bool\n}\n\n\/\/ GetNodeNameAndHostname obtains the name for this Node using the following precedence\n\/\/ (from lower to higher):\n\/\/ - actual hostname\n\/\/ - NodeRegistrationOptions.Name (same as \"--node-name\" passed to \"kubeadm init\/join\")\n\/\/ - \"hostname-overide\" flag in NodeRegistrationOptions.KubeletExtraArgs\n\/\/ It also returns the hostname or an error if getting the hostname failed.\nfunc GetNodeNameAndHostname(cfg *kubeadmapi.NodeRegistrationOptions) (string, string, error) {\n\thostname, err := kubeadmutil.GetHostname(\"\")\n\tnodeName := hostname\n\tif cfg.Name != \"\" {\n\t\tnodeName = cfg.Name\n\t}\n\tif name, ok := cfg.KubeletExtraArgs[\"hostname-override\"]; ok {\n\t\tnodeName = name\n\t}\n\treturn nodeName, hostname, err\n}\n\n\/\/ WriteKubeletDynamicEnvFile writes an environment file with dynamic flags to the kubelet.\n\/\/ Used at \"kubeadm init\" and \"kubeadm join\" time.\nfunc WriteKubeletDynamicEnvFile(cfg *kubeadmapi.ClusterConfiguration, nodeReg *kubeadmapi.NodeRegistrationOptions, registerTaintsUsingFlags bool, kubeletDir string) error {\n\tflagOpts := kubeletFlagsOpts{\n\t\tnodeRegOpts:              nodeReg,\n\t\tpauseImage:               images.GetPauseImage(cfg),\n\t\tregisterTaintsUsingFlags: registerTaintsUsingFlags,\n\t}\n\tstringMap := buildKubeletArgMap(flagOpts)\n\targList := kubeadmutil.BuildArgumentListFromMap(stringMap, nodeReg.KubeletExtraArgs)\n\tenvFileContent := fmt.Sprintf(\"%s=%q\\n\", constants.KubeletEnvFileVariableName, strings.Join(argList, \" \"))\n\n\treturn writeKubeletFlagBytesToDisk([]byte(envFileContent), kubeletDir)\n}\n\n\/\/buildKubeletArgMapCommon takes a kubeletFlagsOpts object and builds based on that a string-string map with flags\n\/\/that are common to both Linux and Windows\nfunc buildKubeletArgMapCommon(opts kubeletFlagsOpts) map[string]string {\n\tkubeletFlags := map[string]string{}\n\n\tif opts.nodeRegOpts.CRISocket == constants.DefaultDockerCRISocket {\n\t\t\/\/ These flags should only be set when running docker\n\t\tkubeletFlags[\"network-plugin\"] = \"cni\"\n\t\tif opts.pauseImage != \"\" {\n\t\t\tkubeletFlags[\"pod-infra-container-image\"] = opts.pauseImage\n\t\t}\n\t} else {\n\t\tkubeletFlags[\"container-runtime\"] = \"remote\"\n\t\tkubeletFlags[\"container-runtime-endpoint\"] = opts.nodeRegOpts.CRISocket\n\t}\n\n\tif opts.registerTaintsUsingFlags && opts.nodeRegOpts.Taints != nil && len(opts.nodeRegOpts.Taints) > 0 {\n\t\ttaintStrs := []string{}\n\t\tfor _, taint := range opts.nodeRegOpts.Taints {\n\t\t\ttaintStrs = append(taintStrs, taint.ToString())\n\t\t}\n\n\t\tkubeletFlags[\"register-with-taints\"] = strings.Join(taintStrs, \",\")\n\t}\n\n\t\/\/ Pass the \"--hostname-override\" flag to the kubelet only if it's different from the hostname\n\tnodeName, hostname, err := GetNodeNameAndHostname(opts.nodeRegOpts)\n\tif err != nil {\n\t\tklog.Warning(err)\n\t}\n\tif nodeName != hostname {\n\t\tklog.V(1).Infof(\"setting kubelet hostname-override to %q\", nodeName)\n\t\tkubeletFlags[\"hostname-override\"] = nodeName\n\t}\n\n\treturn kubeletFlags\n}\n\n\/\/ writeKubeletFlagBytesToDisk writes a byte slice down to disk at the specific location of the kubelet flag overrides file\nfunc writeKubeletFlagBytesToDisk(b []byte, kubeletDir string) error {\n\tkubeletEnvFilePath := filepath.Join(kubeletDir, constants.KubeletEnvFileName)\n\tfmt.Printf(\"[kubelet-start] Writing kubelet environment file with flags to file %q\\n\", kubeletEnvFilePath)\n\n\t\/\/ creates target folder if not already exists\n\tif err := os.MkdirAll(kubeletDir, 0700); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create directory %q\", kubeletDir)\n\t}\n\tif err := ioutil.WriteFile(kubeletEnvFilePath, b, 0644); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to write kubelet configuration to the file %q\", kubeletEnvFilePath)\n\t}\n\treturn nil\n}\n\n\/\/ buildKubeletArgMap takes a kubeletFlagsOpts object and builds based on that a string-string map with flags\n\/\/ that should be given to the local kubelet daemon.\nfunc buildKubeletArgMap(opts kubeletFlagsOpts) map[string]string {\n\treturn buildKubeletArgMapCommon(opts)\n}\n<commit_msg>kubeadm: pass pod-infra-container-image for all CRs<commit_after>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage kubelet\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"k8s.io\/klog\/v2\"\n\tkubeadmapi \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/apis\/kubeadm\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/constants\"\n\t\"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/images\"\n\tkubeadmutil \"k8s.io\/kubernetes\/cmd\/kubeadm\/app\/util\"\n)\n\ntype kubeletFlagsOpts struct {\n\tnodeRegOpts              *kubeadmapi.NodeRegistrationOptions\n\tpauseImage               string\n\tregisterTaintsUsingFlags bool\n}\n\n\/\/ GetNodeNameAndHostname obtains the name for this Node using the following precedence\n\/\/ (from lower to higher):\n\/\/ - actual hostname\n\/\/ - NodeRegistrationOptions.Name (same as \"--node-name\" passed to \"kubeadm init\/join\")\n\/\/ - \"hostname-overide\" flag in NodeRegistrationOptions.KubeletExtraArgs\n\/\/ It also returns the hostname or an error if getting the hostname failed.\nfunc GetNodeNameAndHostname(cfg *kubeadmapi.NodeRegistrationOptions) (string, string, error) {\n\thostname, err := kubeadmutil.GetHostname(\"\")\n\tnodeName := hostname\n\tif cfg.Name != \"\" {\n\t\tnodeName = cfg.Name\n\t}\n\tif name, ok := cfg.KubeletExtraArgs[\"hostname-override\"]; ok {\n\t\tnodeName = name\n\t}\n\treturn nodeName, hostname, err\n}\n\n\/\/ WriteKubeletDynamicEnvFile writes an environment file with dynamic flags to the kubelet.\n\/\/ Used at \"kubeadm init\" and \"kubeadm join\" time.\nfunc WriteKubeletDynamicEnvFile(cfg *kubeadmapi.ClusterConfiguration, nodeReg *kubeadmapi.NodeRegistrationOptions, registerTaintsUsingFlags bool, kubeletDir string) error {\n\tflagOpts := kubeletFlagsOpts{\n\t\tnodeRegOpts:              nodeReg,\n\t\tpauseImage:               images.GetPauseImage(cfg),\n\t\tregisterTaintsUsingFlags: registerTaintsUsingFlags,\n\t}\n\tstringMap := buildKubeletArgMap(flagOpts)\n\targList := kubeadmutil.BuildArgumentListFromMap(stringMap, nodeReg.KubeletExtraArgs)\n\tenvFileContent := fmt.Sprintf(\"%s=%q\\n\", constants.KubeletEnvFileVariableName, strings.Join(argList, \" \"))\n\n\treturn writeKubeletFlagBytesToDisk([]byte(envFileContent), kubeletDir)\n}\n\n\/\/buildKubeletArgMapCommon takes a kubeletFlagsOpts object and builds based on that a string-string map with flags\n\/\/that are common to both Linux and Windows\nfunc buildKubeletArgMapCommon(opts kubeletFlagsOpts) map[string]string {\n\tkubeletFlags := map[string]string{}\n\n\tif opts.nodeRegOpts.CRISocket == constants.DefaultDockerCRISocket {\n\t\t\/\/ These flags should only be set when running docker\n\t\tkubeletFlags[\"network-plugin\"] = \"cni\"\n\t} else {\n\t\tkubeletFlags[\"container-runtime\"] = \"remote\"\n\t\tkubeletFlags[\"container-runtime-endpoint\"] = opts.nodeRegOpts.CRISocket\n\t}\n\n\t\/\/ This flag passes the pod infra container image (e.g. \"pause\" image) to the kubelet\n\t\/\/ and prevents its garbage collection\n\tif opts.pauseImage != \"\" {\n\t\tkubeletFlags[\"pod-infra-container-image\"] = opts.pauseImage\n\t}\n\n\tif opts.registerTaintsUsingFlags && opts.nodeRegOpts.Taints != nil && len(opts.nodeRegOpts.Taints) > 0 {\n\t\ttaintStrs := []string{}\n\t\tfor _, taint := range opts.nodeRegOpts.Taints {\n\t\t\ttaintStrs = append(taintStrs, taint.ToString())\n\t\t}\n\n\t\tkubeletFlags[\"register-with-taints\"] = strings.Join(taintStrs, \",\")\n\t}\n\n\t\/\/ Pass the \"--hostname-override\" flag to the kubelet only if it's different from the hostname\n\tnodeName, hostname, err := GetNodeNameAndHostname(opts.nodeRegOpts)\n\tif err != nil {\n\t\tklog.Warning(err)\n\t}\n\tif nodeName != hostname {\n\t\tklog.V(1).Infof(\"setting kubelet hostname-override to %q\", nodeName)\n\t\tkubeletFlags[\"hostname-override\"] = nodeName\n\t}\n\n\treturn kubeletFlags\n}\n\n\/\/ writeKubeletFlagBytesToDisk writes a byte slice down to disk at the specific location of the kubelet flag overrides file\nfunc writeKubeletFlagBytesToDisk(b []byte, kubeletDir string) error {\n\tkubeletEnvFilePath := filepath.Join(kubeletDir, constants.KubeletEnvFileName)\n\tfmt.Printf(\"[kubelet-start] Writing kubelet environment file with flags to file %q\\n\", kubeletEnvFilePath)\n\n\t\/\/ creates target folder if not already exists\n\tif err := os.MkdirAll(kubeletDir, 0700); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create directory %q\", kubeletDir)\n\t}\n\tif err := ioutil.WriteFile(kubeletEnvFilePath, b, 0644); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to write kubelet configuration to the file %q\", kubeletEnvFilePath)\n\t}\n\treturn nil\n}\n\n\/\/ buildKubeletArgMap takes a kubeletFlagsOpts object and builds based on that a string-string map with flags\n\/\/ that should be given to the local kubelet daemon.\nfunc buildKubeletArgMap(opts kubeletFlagsOpts) map[string]string {\n\treturn buildKubeletArgMapCommon(opts)\n}\n<|endoftext|>"}
{"text":"<commit_before>package extract_strings\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"go\/ast\"\n\t\"go\/build\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\n\t\"path\/filepath\"\n\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\n\t\"github.com\/maximilien\/i18n4cf\/cmds\"\n\t\"github.com\/maximilien\/i18n4cf\/common\"\n)\n\ntype extractStrings struct {\n\toptions cmds.Options\n\n\ti18nFilename string\n\tpoFilename   string\n\n\tFilename      string\n\tOutputDirname string\n\n\tExtractedStrings map[string]common.StringInfo\n\tFilteredStrings  map[string]string\n\tFilteredRegexps  []*regexp.Regexp\n\n\tTotalStringsDir int\n\tTotalStrings    int\n\tTotalFiles      int\n\n\tIgnoreRegexp *regexp.Regexp\n}\n\nfunc NewExtractStrings(options cmds.Options) extractStrings {\n\tvar compiledRegexp *regexp.Regexp\n\tif options.IgnoreRegexpFlag != \"\" {\n\t\tcompiledReg, err := regexp.Compile(options.IgnoreRegexpFlag)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"WARNING compiling ignore-regexp:\", err)\n\t\t}\n\t\tcompiledRegexp = compiledReg\n\t}\n\n\treturn extractStrings{options: options,\n\t\tFilename:         \"extracted_strings.json\",\n\t\tOutputDirname:    options.OutputDirFlag,\n\t\tExtractedStrings: nil,\n\t\tFilteredStrings:  nil,\n\t\tFilteredRegexps:  nil,\n\t\tTotalStringsDir:  0,\n\t\tTotalStrings:     0,\n\t\tTotalFiles:       0,\n\t\tIgnoreRegexp:     compiledRegexp}\n}\n\nfunc (es *extractStrings) Options() cmds.Options {\n\treturn es.options\n}\n\nfunc (es *extractStrings) Println(a ...interface{}) (int, error) {\n\tif es.options.VerboseFlag {\n\t\treturn fmt.Println(a...)\n\t}\n\n\treturn 0, nil\n}\n\nfunc (es *extractStrings) Printf(msg string, a ...interface{}) (int, error) {\n\tif es.options.VerboseFlag {\n\t\treturn fmt.Printf(msg, a...)\n\t}\n\n\treturn 0, nil\n}\n\nfunc (es *extractStrings) Run() error {\n\tif es.options.FilenameFlag != \"\" {\n\t\treturn es.InspectFile(es.options.FilenameFlag)\n\t} else {\n\t\terr := es.InspectDir(es.options.DirnameFlag, es.options.RecurseFlag)\n\t\tif err != nil {\n\t\t\tes.Println(\"gi18n: could not extract strings from directory:\", es.options.DirnameFlag)\n\t\t\treturn err\n\t\t}\n\t\tes.Println()\n\t\tes.Println(\"Total files parsed:\", es.TotalFiles)\n\t\tes.Println(\"Total extracted strings:\", es.TotalStrings)\n\t}\n\treturn nil\n}\n\nfunc (es *extractStrings) InspectFile(filename string) error {\n\tes.Println(\"gi18n: extracting strings from file:\", filename)\n\tif es.options.DryRunFlag {\n\t\tes.Println(\"WARNING running in -dry-run mode\")\n\t}\n\n\tes.ExtractedStrings = make(map[string]common.StringInfo)\n\tes.FilteredStrings = make(map[string]string)\n\tes.FilteredRegexps = []*regexp.Regexp{}\n\n\tes.setFilename(filename)\n\tes.setI18nFilename(filename)\n\tes.setPoFilename(filename)\n\n\tfset := token.NewFileSet()\n\n\tvar absFilePath = filename\n\tif !filepath.IsAbs(absFilePath) {\n\t\tabsFilePath = filepath.Join(os.Getenv(\"PWD\"), absFilePath)\n\t}\n\n\tfileInfo, err := common.GetAbsFileInfo(absFilePath)\n\tif err != nil {\n\t\tes.Println(err)\n\t}\n\n\tif strings.HasPrefix(fileInfo.Name(), \".\") {\n\t\tes.Println(\"WARNING ignoring file:\", absFilePath)\n\t\treturn nil\n\t}\n\n\tastFile, err := parser.ParseFile(fset, absFilePath, nil, parser.ParseComments|parser.AllErrors)\n\tif err != nil {\n\t\tes.Println(err)\n\t\treturn err\n\t}\n\n\terr = es.loadExcludedStrings()\n\tif err != nil {\n\t\tes.Println(err)\n\t\treturn err\n\t}\n\tes.Println(fmt.Sprintf(\"Loaded %d excluded strings\", len(es.FilteredStrings)))\n\n\terr = es.loadExcludedRegexps()\n\tif err != nil {\n\t\tes.Println(err)\n\t\treturn err\n\t}\n\tes.Println(fmt.Sprintf(\"Loaded %d excluded regexps\", len(es.FilteredRegexps)))\n\n\tes.excludeImports(astFile)\n\n\tes.extractString(astFile, fset)\n\tes.TotalStringsDir += len(es.ExtractedStrings)\n\tes.TotalStrings += len(es.ExtractedStrings)\n\tes.TotalFiles += 1\n\n\tes.Printf(\"Extracted %d strings from file: %s\\n\", len(es.ExtractedStrings), absFilePath)\n\n\tvar outputDirname = es.OutputDirname\n\tif es.options.OutputDirFlag != \"\" {\n\t\tif es.options.OutputMatchImportFlag {\n\t\t\toutputDirname, err = es.findImportPath(absFilePath)\n\t\t\tif err != nil {\n\t\t\t\tes.Println(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else if es.options.OutputMatchPackageFlag {\n\t\t\toutputDirname, err = es.findPackagePath(absFilePath)\n\t\t\tif err != nil {\n\t\t\t\tes.Println(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\toutputDirname, err = common.FindFilePath(absFilePath)\n\t\tif err != nil {\n\t\t\tes.Println(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif es.options.MetaFlag {\n\t\terr = es.saveExtractedStrings(outputDirname)\n\t\tif err != nil {\n\t\t\tes.Println(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = common.SaveStrings(es, es.ExtractedStrings, outputDirname, es.i18nFilename)\n\tif err != nil {\n\t\tes.Println(err)\n\t\treturn err\n\t}\n\n\tif es.options.PoFlag {\n\t\terr = common.SaveStringsInPo(es, es.ExtractedStrings, outputDirname, es.poFilename)\n\t\tif err != nil {\n\t\t\tes.Println(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (es *extractStrings) InspectDir(dirName string, recursive bool) error {\n\tes.Printf(\"gi18n: inspecting dir %s, recursive: %t\\n\", dirName, recursive)\n\tes.Println()\n\n\tfset := token.NewFileSet()\n\tes.TotalStringsDir = 0\n\n\tpackages, err := parser.ParseDir(fset, dirName, nil, parser.ParseComments)\n\tif err != nil {\n\t\tes.Println(err)\n\t\treturn err\n\t}\n\n\tfor k, pkg := range packages {\n\t\tes.Println(\"Extracting strings in package:\", k)\n\t\tfor fileName, _ := range pkg.Files {\n\t\t\tif es.IgnoreRegexp != nil && es.IgnoreRegexp.MatchString(fileName) {\n\t\t\t\tes.Println(\"Using ignore-regexp:\", es.options.IgnoreRegexpFlag)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tes.Println(\"No match for ignore-regexp:\", es.options.IgnoreRegexpFlag)\n\t\t\t}\n\n\t\t\tif strings.HasSuffix(fileName, \".go\") {\n\t\t\t\terr = es.InspectFile(fileName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tes.Println(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tes.Printf(\"Extracted total of %d strings\\n\\n\", es.TotalStringsDir)\n\n\tif recursive {\n\t\tfileInfos, _ := ioutil.ReadDir(dirName)\n\t\tfor _, fileInfo := range fileInfos {\n\t\t\tif fileInfo.IsDir() && !strings.HasPrefix(fileInfo.Name(), \".\") {\n\t\t\t\terr = es.InspectDir(filepath.Join(dirName, fileInfo.Name()), recursive)\n\t\t\t\tif err != nil {\n\t\t\t\t\tes.Println(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (es *extractStrings) findImportPath(filename string) (string, error) {\n\tpath := es.OutputDirname\n\n\tfilePath, err := common.FindFilePath(filename)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR opening file\", err)\n\t\treturn \"\", err\n\t}\n\n\tpkg, err := build.ImportDir(filePath, 0)\n\tsrcPath := \"src\" + string(os.PathSeparator)\n\tif strings.HasPrefix(pkg.Dir, srcPath) {\n\t\tpath = filepath.Join(path, pkg.Dir[len(srcPath):len(pkg.Dir)])\n\t}\n\n\treturn path, nil\n}\n\nfunc (es *extractStrings) findPackagePath(filename string) (string, error) {\n\tpath := es.OutputDirname\n\n\tfilePath, err := common.FindFilePath(filename)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR opening file\", err)\n\t\treturn \"\", err\n\t}\n\n\tpkg, err := build.ImportDir(filePath, 0)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR opening file\", err)\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(path, pkg.Name), nil\n}\n\nfunc (es *extractStrings) saveExtractedStrings(outputDirname string) error {\n\tif len(es.ExtractedStrings) != 0 {\n\t\tes.Println(\"Saving extracted strings to file:\", es.Filename)\n\t}\n\n\tif !es.options.DryRunFlag {\n\t\terr := common.CreateOutputDirsIfNeeded(outputDirname)\n\t\tif err != nil {\n\t\t\tes.Println(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tstringInfos := make([]common.StringInfo, 0)\n\tfor _, stringInfo := range es.ExtractedStrings {\n\t\tstringInfo.Filename = strings.Split(es.Filename, \".extracted.json\")[0]\n\n\t\tstringInfos = append(stringInfos, stringInfo)\n\t}\n\n\tjsonData, err := json.MarshalIndent(stringInfos, \"\", \"   \")\n\tif err != nil {\n\t\tes.Println(err)\n\t\treturn err\n\t}\n\n\tif !es.options.DryRunFlag && len(stringInfos) != 0 {\n\t\tfile, err := os.Create(filepath.Join(outputDirname, es.Filename[strings.LastIndex(es.Filename, string(os.PathSeparator))+1:len(es.Filename)]))\n\t\tdefer file.Close()\n\t\tif err != nil {\n\t\t\tes.Println(err)\n\t\t\treturn err\n\t\t}\n\n\t\tfile.Write(jsonData)\n\t}\n\n\treturn nil\n}\n\nfunc (es *extractStrings) setFilename(filename string) {\n\tes.Filename = filename + \".extracted.json\"\n}\n\nfunc (es *extractStrings) setI18nFilename(filename string) {\n\tes.i18nFilename = filename + \".en.json\"\n}\n\nfunc (es *extractStrings) setPoFilename(filename string) {\n\tes.poFilename = filename + \".en.po\"\n}\n\nfunc (es *extractStrings) loadExcludedStrings() error {\n\t_, err := os.Stat(es.options.ExcludedFilenameFlag)\n\tif os.IsNotExist(err) {\n\t\tes.Println(\"Could not find:\", es.options.ExcludedFilenameFlag)\n\t\treturn nil\n\t}\n\n\tes.Println(\"Excluding strings in file:\", es.options.ExcludedFilenameFlag)\n\n\tcontent, err := ioutil.ReadFile(es.options.ExcludedFilenameFlag)\n\tif err != nil {\n\t\tfmt.Print(err)\n\t\treturn err\n\t}\n\n\tvar excludedStrings common.ExcludedStrings\n\terr = json.Unmarshal(content, &excludedStrings)\n\tif err != nil {\n\t\tfmt.Print(err)\n\t\treturn err\n\t}\n\n\tfor i := range excludedStrings.ExcludedStrings {\n\t\tes.FilteredStrings[excludedStrings.ExcludedStrings[i]] = excludedStrings.ExcludedStrings[i]\n\t}\n\n\treturn nil\n}\n\nfunc (es *extractStrings) loadExcludedRegexps() error {\n\t_, err := os.Stat(es.options.ExcludedFilenameFlag)\n\tif os.IsNotExist(err) {\n\t\tes.Println(\"Could not find:\", es.options.ExcludedFilenameFlag)\n\t\treturn nil\n\t}\n\n\tes.Println(\"Excluding regexps in file:\", es.options.ExcludedFilenameFlag)\n\n\tcontent, err := ioutil.ReadFile(es.options.ExcludedFilenameFlag)\n\tif err != nil {\n\t\tfmt.Print(err)\n\t\treturn err\n\t}\n\n\tvar excludedRegexps common.ExcludedStrings\n\terr = json.Unmarshal(content, &excludedRegexps)\n\tif err != nil {\n\t\tfmt.Print(err)\n\t\treturn err\n\t}\n\n\tfor _, regexpString := range excludedRegexps.ExcludedRegexps {\n\t\tcompiledRegexp, err := regexp.Compile(regexpString)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"WARNING error compiling regexp:\", regexpString)\n\t\t}\n\n\t\tes.FilteredRegexps = append(es.FilteredRegexps, compiledRegexp)\n\t}\n\n\treturn nil\n}\n\nfunc (es *extractStrings) extractString(f *ast.File, fset *token.FileSet) error {\n\tast.Inspect(f, func(n ast.Node) bool {\n\t\tvar s string\n\t\tswitch x := n.(type) {\n\t\tcase *ast.BasicLit:\n\t\t\ts, _ = strconv.Unquote(x.Value)\n\t\t\tif len(s) > 0 && x.Kind == token.STRING && s != \"\\t\" && s != \"\\n\" && s != \" \" && !es.filter(s) { \/\/TODO: fix to remove these: s != \"\\\\t\" && s != \"\\\\n\" && s != \" \"\n\t\t\t\tposition := fset.Position(n.Pos())\n\t\t\t\tstringInfo := common.StringInfo{Value: s,\n\t\t\t\t\tFilename: position.Filename,\n\t\t\t\t\tOffset:   position.Offset,\n\t\t\t\t\tLine:     position.Line,\n\t\t\t\t\tColumn:   position.Column}\n\t\t\t\tes.ExtractedStrings[s] = stringInfo\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\n\treturn nil\n}\n\nfunc (es *extractStrings) excludeImports(astFile *ast.File) {\n\tfor i := range astFile.Imports {\n\t\timportString, _ := strconv.Unquote(astFile.Imports[i].Path.Value)\n\t\tes.FilteredStrings[importString] = importString\n\t}\n\n}\n\nfunc (es *extractStrings) filter(aString string) bool {\n\tfor i := range common.BLANKS {\n\t\tif aString == common.BLANKS[i] {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tif es.FilteredStrings[aString] != \"\" {\n\t\treturn true\n\t}\n\n\tfor _, compiledRegexp := range es.FilteredRegexps {\n\t\tif compiledRegexp.MatchString(aString) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n<commit_msg>More idiomatic way of checking for a key in a map<commit_after>package extract_strings\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"go\/ast\"\n\t\"go\/build\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\n\t\"path\/filepath\"\n\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\n\t\"github.com\/maximilien\/i18n4cf\/cmds\"\n\t\"github.com\/maximilien\/i18n4cf\/common\"\n)\n\ntype extractStrings struct {\n\toptions cmds.Options\n\n\ti18nFilename string\n\tpoFilename   string\n\n\tFilename      string\n\tOutputDirname string\n\n\tExtractedStrings map[string]common.StringInfo\n\tFilteredStrings  map[string]string\n\tFilteredRegexps  []*regexp.Regexp\n\n\tTotalStringsDir int\n\tTotalStrings    int\n\tTotalFiles      int\n\n\tIgnoreRegexp *regexp.Regexp\n}\n\nfunc NewExtractStrings(options cmds.Options) extractStrings {\n\tvar compiledRegexp *regexp.Regexp\n\tif options.IgnoreRegexpFlag != \"\" {\n\t\tcompiledReg, err := regexp.Compile(options.IgnoreRegexpFlag)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"WARNING compiling ignore-regexp:\", err)\n\t\t}\n\t\tcompiledRegexp = compiledReg\n\t}\n\n\treturn extractStrings{options: options,\n\t\tFilename:         \"extracted_strings.json\",\n\t\tOutputDirname:    options.OutputDirFlag,\n\t\tExtractedStrings: nil,\n\t\tFilteredStrings:  nil,\n\t\tFilteredRegexps:  nil,\n\t\tTotalStringsDir:  0,\n\t\tTotalStrings:     0,\n\t\tTotalFiles:       0,\n\t\tIgnoreRegexp:     compiledRegexp}\n}\n\nfunc (es *extractStrings) Options() cmds.Options {\n\treturn es.options\n}\n\nfunc (es *extractStrings) Println(a ...interface{}) (int, error) {\n\tif es.options.VerboseFlag {\n\t\treturn fmt.Println(a...)\n\t}\n\n\treturn 0, nil\n}\n\nfunc (es *extractStrings) Printf(msg string, a ...interface{}) (int, error) {\n\tif es.options.VerboseFlag {\n\t\treturn fmt.Printf(msg, a...)\n\t}\n\n\treturn 0, nil\n}\n\nfunc (es *extractStrings) Run() error {\n\tif es.options.FilenameFlag != \"\" {\n\t\treturn es.InspectFile(es.options.FilenameFlag)\n\t} else {\n\t\terr := es.InspectDir(es.options.DirnameFlag, es.options.RecurseFlag)\n\t\tif err != nil {\n\t\t\tes.Println(\"gi18n: could not extract strings from directory:\", es.options.DirnameFlag)\n\t\t\treturn err\n\t\t}\n\t\tes.Println()\n\t\tes.Println(\"Total files parsed:\", es.TotalFiles)\n\t\tes.Println(\"Total extracted strings:\", es.TotalStrings)\n\t}\n\treturn nil\n}\n\nfunc (es *extractStrings) InspectFile(filename string) error {\n\tes.Println(\"gi18n: extracting strings from file:\", filename)\n\tif es.options.DryRunFlag {\n\t\tes.Println(\"WARNING running in -dry-run mode\")\n\t}\n\n\tes.ExtractedStrings = make(map[string]common.StringInfo)\n\tes.FilteredStrings = make(map[string]string)\n\tes.FilteredRegexps = []*regexp.Regexp{}\n\n\tes.setFilename(filename)\n\tes.setI18nFilename(filename)\n\tes.setPoFilename(filename)\n\n\tfset := token.NewFileSet()\n\n\tvar absFilePath = filename\n\tif !filepath.IsAbs(absFilePath) {\n\t\tabsFilePath = filepath.Join(os.Getenv(\"PWD\"), absFilePath)\n\t}\n\n\tfileInfo, err := common.GetAbsFileInfo(absFilePath)\n\tif err != nil {\n\t\tes.Println(err)\n\t}\n\n\tif strings.HasPrefix(fileInfo.Name(), \".\") {\n\t\tes.Println(\"WARNING ignoring file:\", absFilePath)\n\t\treturn nil\n\t}\n\n\tastFile, err := parser.ParseFile(fset, absFilePath, nil, parser.ParseComments|parser.AllErrors)\n\tif err != nil {\n\t\tes.Println(err)\n\t\treturn err\n\t}\n\n\terr = es.loadExcludedStrings()\n\tif err != nil {\n\t\tes.Println(err)\n\t\treturn err\n\t}\n\tes.Println(fmt.Sprintf(\"Loaded %d excluded strings\", len(es.FilteredStrings)))\n\n\terr = es.loadExcludedRegexps()\n\tif err != nil {\n\t\tes.Println(err)\n\t\treturn err\n\t}\n\tes.Println(fmt.Sprintf(\"Loaded %d excluded regexps\", len(es.FilteredRegexps)))\n\n\tes.excludeImports(astFile)\n\n\tes.extractString(astFile, fset)\n\tes.TotalStringsDir += len(es.ExtractedStrings)\n\tes.TotalStrings += len(es.ExtractedStrings)\n\tes.TotalFiles += 1\n\n\tes.Printf(\"Extracted %d strings from file: %s\\n\", len(es.ExtractedStrings), absFilePath)\n\n\tvar outputDirname = es.OutputDirname\n\tif es.options.OutputDirFlag != \"\" {\n\t\tif es.options.OutputMatchImportFlag {\n\t\t\toutputDirname, err = es.findImportPath(absFilePath)\n\t\t\tif err != nil {\n\t\t\t\tes.Println(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else if es.options.OutputMatchPackageFlag {\n\t\t\toutputDirname, err = es.findPackagePath(absFilePath)\n\t\t\tif err != nil {\n\t\t\t\tes.Println(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\toutputDirname, err = common.FindFilePath(absFilePath)\n\t\tif err != nil {\n\t\t\tes.Println(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif es.options.MetaFlag {\n\t\terr = es.saveExtractedStrings(outputDirname)\n\t\tif err != nil {\n\t\t\tes.Println(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\terr = common.SaveStrings(es, es.ExtractedStrings, outputDirname, es.i18nFilename)\n\tif err != nil {\n\t\tes.Println(err)\n\t\treturn err\n\t}\n\n\tif es.options.PoFlag {\n\t\terr = common.SaveStringsInPo(es, es.ExtractedStrings, outputDirname, es.poFilename)\n\t\tif err != nil {\n\t\t\tes.Println(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (es *extractStrings) InspectDir(dirName string, recursive bool) error {\n\tes.Printf(\"gi18n: inspecting dir %s, recursive: %t\\n\", dirName, recursive)\n\tes.Println()\n\n\tfset := token.NewFileSet()\n\tes.TotalStringsDir = 0\n\n\tpackages, err := parser.ParseDir(fset, dirName, nil, parser.ParseComments)\n\tif err != nil {\n\t\tes.Println(err)\n\t\treturn err\n\t}\n\n\tfor k, pkg := range packages {\n\t\tes.Println(\"Extracting strings in package:\", k)\n\t\tfor fileName, _ := range pkg.Files {\n\t\t\tif es.IgnoreRegexp != nil && es.IgnoreRegexp.MatchString(fileName) {\n\t\t\t\tes.Println(\"Using ignore-regexp:\", es.options.IgnoreRegexpFlag)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tes.Println(\"No match for ignore-regexp:\", es.options.IgnoreRegexpFlag)\n\t\t\t}\n\n\t\t\tif strings.HasSuffix(fileName, \".go\") {\n\t\t\t\terr = es.InspectFile(fileName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tes.Println(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tes.Printf(\"Extracted total of %d strings\\n\\n\", es.TotalStringsDir)\n\n\tif recursive {\n\t\tfileInfos, _ := ioutil.ReadDir(dirName)\n\t\tfor _, fileInfo := range fileInfos {\n\t\t\tif fileInfo.IsDir() && !strings.HasPrefix(fileInfo.Name(), \".\") {\n\t\t\t\terr = es.InspectDir(filepath.Join(dirName, fileInfo.Name()), recursive)\n\t\t\t\tif err != nil {\n\t\t\t\t\tes.Println(err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (es *extractStrings) findImportPath(filename string) (string, error) {\n\tpath := es.OutputDirname\n\n\tfilePath, err := common.FindFilePath(filename)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR opening file\", err)\n\t\treturn \"\", err\n\t}\n\n\tpkg, err := build.ImportDir(filePath, 0)\n\tsrcPath := \"src\" + string(os.PathSeparator)\n\tif strings.HasPrefix(pkg.Dir, srcPath) {\n\t\tpath = filepath.Join(path, pkg.Dir[len(srcPath):len(pkg.Dir)])\n\t}\n\n\treturn path, nil\n}\n\nfunc (es *extractStrings) findPackagePath(filename string) (string, error) {\n\tpath := es.OutputDirname\n\n\tfilePath, err := common.FindFilePath(filename)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR opening file\", err)\n\t\treturn \"\", err\n\t}\n\n\tpkg, err := build.ImportDir(filePath, 0)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR opening file\", err)\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(path, pkg.Name), nil\n}\n\nfunc (es *extractStrings) saveExtractedStrings(outputDirname string) error {\n\tif len(es.ExtractedStrings) != 0 {\n\t\tes.Println(\"Saving extracted strings to file:\", es.Filename)\n\t}\n\n\tif !es.options.DryRunFlag {\n\t\terr := common.CreateOutputDirsIfNeeded(outputDirname)\n\t\tif err != nil {\n\t\t\tes.Println(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tstringInfos := make([]common.StringInfo, 0)\n\tfor _, stringInfo := range es.ExtractedStrings {\n\t\tstringInfo.Filename = strings.Split(es.Filename, \".extracted.json\")[0]\n\n\t\tstringInfos = append(stringInfos, stringInfo)\n\t}\n\n\tjsonData, err := json.MarshalIndent(stringInfos, \"\", \"   \")\n\tif err != nil {\n\t\tes.Println(err)\n\t\treturn err\n\t}\n\n\tif !es.options.DryRunFlag && len(stringInfos) != 0 {\n\t\tfile, err := os.Create(filepath.Join(outputDirname, es.Filename[strings.LastIndex(es.Filename, string(os.PathSeparator))+1:len(es.Filename)]))\n\t\tdefer file.Close()\n\t\tif err != nil {\n\t\t\tes.Println(err)\n\t\t\treturn err\n\t\t}\n\n\t\tfile.Write(jsonData)\n\t}\n\n\treturn nil\n}\n\nfunc (es *extractStrings) setFilename(filename string) {\n\tes.Filename = filename + \".extracted.json\"\n}\n\nfunc (es *extractStrings) setI18nFilename(filename string) {\n\tes.i18nFilename = filename + \".en.json\"\n}\n\nfunc (es *extractStrings) setPoFilename(filename string) {\n\tes.poFilename = filename + \".en.po\"\n}\n\nfunc (es *extractStrings) loadExcludedStrings() error {\n\t_, err := os.Stat(es.options.ExcludedFilenameFlag)\n\tif os.IsNotExist(err) {\n\t\tes.Println(\"Could not find:\", es.options.ExcludedFilenameFlag)\n\t\treturn nil\n\t}\n\n\tes.Println(\"Excluding strings in file:\", es.options.ExcludedFilenameFlag)\n\n\tcontent, err := ioutil.ReadFile(es.options.ExcludedFilenameFlag)\n\tif err != nil {\n\t\tfmt.Print(err)\n\t\treturn err\n\t}\n\n\tvar excludedStrings common.ExcludedStrings\n\terr = json.Unmarshal(content, &excludedStrings)\n\tif err != nil {\n\t\tfmt.Print(err)\n\t\treturn err\n\t}\n\n\tfor i := range excludedStrings.ExcludedStrings {\n\t\tes.FilteredStrings[excludedStrings.ExcludedStrings[i]] = excludedStrings.ExcludedStrings[i]\n\t}\n\n\treturn nil\n}\n\nfunc (es *extractStrings) loadExcludedRegexps() error {\n\t_, err := os.Stat(es.options.ExcludedFilenameFlag)\n\tif os.IsNotExist(err) {\n\t\tes.Println(\"Could not find:\", es.options.ExcludedFilenameFlag)\n\t\treturn nil\n\t}\n\n\tes.Println(\"Excluding regexps in file:\", es.options.ExcludedFilenameFlag)\n\n\tcontent, err := ioutil.ReadFile(es.options.ExcludedFilenameFlag)\n\tif err != nil {\n\t\tfmt.Print(err)\n\t\treturn err\n\t}\n\n\tvar excludedRegexps common.ExcludedStrings\n\terr = json.Unmarshal(content, &excludedRegexps)\n\tif err != nil {\n\t\tfmt.Print(err)\n\t\treturn err\n\t}\n\n\tfor _, regexpString := range excludedRegexps.ExcludedRegexps {\n\t\tcompiledRegexp, err := regexp.Compile(regexpString)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"WARNING error compiling regexp:\", regexpString)\n\t\t}\n\n\t\tes.FilteredRegexps = append(es.FilteredRegexps, compiledRegexp)\n\t}\n\n\treturn nil\n}\n\nfunc (es *extractStrings) extractString(f *ast.File, fset *token.FileSet) error {\n\tast.Inspect(f, func(n ast.Node) bool {\n\t\tvar s string\n\t\tswitch x := n.(type) {\n\t\tcase *ast.BasicLit:\n\t\t\ts, _ = strconv.Unquote(x.Value)\n\t\t\tif len(s) > 0 && x.Kind == token.STRING && s != \"\\t\" && s != \"\\n\" && s != \" \" && !es.filter(s) { \/\/TODO: fix to remove these: s != \"\\\\t\" && s != \"\\\\n\" && s != \" \"\n\t\t\t\tposition := fset.Position(n.Pos())\n\t\t\t\tstringInfo := common.StringInfo{Value: s,\n\t\t\t\t\tFilename: position.Filename,\n\t\t\t\t\tOffset:   position.Offset,\n\t\t\t\t\tLine:     position.Line,\n\t\t\t\t\tColumn:   position.Column}\n\t\t\t\tes.ExtractedStrings[s] = stringInfo\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n\n\treturn nil\n}\n\nfunc (es *extractStrings) excludeImports(astFile *ast.File) {\n\tfor i := range astFile.Imports {\n\t\timportString, _ := strconv.Unquote(astFile.Imports[i].Path.Value)\n\t\tes.FilteredStrings[importString] = importString\n\t}\n\n}\n\nfunc (es *extractStrings) filter(aString string) bool {\n\tfor i := range common.BLANKS {\n\t\tif aString == common.BLANKS[i] {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tif _, ok := es.FilteredStrings[aString]; ok {\n\t\treturn true\n\t}\n\n\tfor _, compiledRegexp := range es.FilteredRegexps {\n\t\tif compiledRegexp.MatchString(aString) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package http provides a http server with features; acme, cors, etc\npackage http\n\nimport (\n\t\"crypto\/tls\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com\/gorilla\/handlers\"\n\t\"github.com\/micro\/go-micro\/api\/server\"\n\t\"github.com\/micro\/go-micro\/util\/log\"\n)\n\ntype httpServer struct {\n\tmux  *http.ServeMux\n\topts server.Options\n\n\tmtx     sync.RWMutex\n\taddress string\n\texit    chan chan error\n}\n\nfunc NewServer(address string) server.Server {\n\treturn &httpServer{\n\t\topts:    server.Options{},\n\t\tmux:     http.NewServeMux(),\n\t\taddress: address,\n\t\texit:    make(chan chan error),\n\t}\n}\n\nfunc (s *httpServer) Address() string {\n\ts.mtx.RLock()\n\tdefer s.mtx.RUnlock()\n\treturn s.address\n}\n\nfunc (s *httpServer) Init(opts ...server.Option) error {\n\tfor _, o := range opts {\n\t\to(&s.opts)\n\t}\n\treturn nil\n}\n\nfunc (s *httpServer) Handle(path string, handler http.Handler) {\n\ts.mux.Handle(path, handlers.CombinedLoggingHandler(os.Stdout, handler))\n}\n\nfunc (s *httpServer) Start() error {\n\tvar l net.Listener\n\tvar err error\n\n\tif s.opts.EnableACME {\n\t\t\/\/ should we check the address to make sure its using :443?\n\t\tl, err = s.opts.ACMEProvider.NewListener(s.opts.ACMEHosts...)\n\t} else if s.opts.EnableTLS && s.opts.TLSConfig != nil {\n\t\tl, err = tls.Listen(\"tcp\", s.address, s.opts.TLSConfig)\n\t} else {\n\t\t\/\/ otherwise plain listen\n\t\tl, err = net.Listen(\"tcp\", s.address)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Logf(\"HTTP API Listening on %s\", l.Addr().String())\n\n\ts.mtx.Lock()\n\ts.address = l.Addr().String()\n\ts.mtx.Unlock()\n\n\tgo func() {\n\t\tif err := http.Serve(l, s.mux); err != nil {\n\t\t\t\/\/ temporary fix\n\t\t\t\/\/log.Fatal(err)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tch := <-s.exit\n\t\tch <- l.Close()\n\t}()\n\n\treturn nil\n}\n\nfunc (s *httpServer) Stop() error {\n\tch := make(chan error)\n\ts.exit <- ch\n\treturn <-ch\n}\n\nfunc (s *httpServer) String() string {\n\treturn \"http\"\n}\n<commit_msg>Add nil check for acme provider<commit_after>\/\/ Package http provides a http server with features; acme, cors, etc\npackage http\n\nimport (\n\t\"crypto\/tls\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com\/gorilla\/handlers\"\n\t\"github.com\/micro\/go-micro\/api\/server\"\n\t\"github.com\/micro\/go-micro\/util\/log\"\n)\n\ntype httpServer struct {\n\tmux  *http.ServeMux\n\topts server.Options\n\n\tmtx     sync.RWMutex\n\taddress string\n\texit    chan chan error\n}\n\nfunc NewServer(address string) server.Server {\n\treturn &httpServer{\n\t\topts:    server.Options{},\n\t\tmux:     http.NewServeMux(),\n\t\taddress: address,\n\t\texit:    make(chan chan error),\n\t}\n}\n\nfunc (s *httpServer) Address() string {\n\ts.mtx.RLock()\n\tdefer s.mtx.RUnlock()\n\treturn s.address\n}\n\nfunc (s *httpServer) Init(opts ...server.Option) error {\n\tfor _, o := range opts {\n\t\to(&s.opts)\n\t}\n\treturn nil\n}\n\nfunc (s *httpServer) Handle(path string, handler http.Handler) {\n\ts.mux.Handle(path, handlers.CombinedLoggingHandler(os.Stdout, handler))\n}\n\nfunc (s *httpServer) Start() error {\n\tvar l net.Listener\n\tvar err error\n\n\tif s.opts.EnableACME && s.opts.ACMEProvider != nil {\n\t\t\/\/ should we check the address to make sure its using :443?\n\t\tl, err = s.opts.ACMEProvider.NewListener(s.opts.ACMEHosts...)\n\t} else if s.opts.EnableTLS && s.opts.TLSConfig != nil {\n\t\tl, err = tls.Listen(\"tcp\", s.address, s.opts.TLSConfig)\n\t} else {\n\t\t\/\/ otherwise plain listen\n\t\tl, err = net.Listen(\"tcp\", s.address)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Logf(\"HTTP API Listening on %s\", l.Addr().String())\n\n\ts.mtx.Lock()\n\ts.address = l.Addr().String()\n\ts.mtx.Unlock()\n\n\tgo func() {\n\t\tif err := http.Serve(l, s.mux); err != nil {\n\t\t\t\/\/ temporary fix\n\t\t\t\/\/log.Fatal(err)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tch := <-s.exit\n\t\tch <- l.Close()\n\t}()\n\n\treturn nil\n}\n\nfunc (s *httpServer) Stop() error {\n\tch := make(chan error)\n\ts.exit <- ch\n\treturn <-ch\n}\n\nfunc (s *httpServer) String() string {\n\treturn \"http\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package knsq\n\nimport (\n\t\"github.com\/bitly\/nsq\/nsq\"\n)\n\n\/\/ MustReader calls nsq.NewReader and panics if nsq.NewReader\n\/\/ returned an error. nsq.NewReader only fails on invalid\n\/\/ topic and channel names.\nfunc MustReader(topic, channel string) *nsq.Reader {\n\tr, err := nsq.NewReader(topic, channel)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn r\n}\n\n\/\/ HandlerFunc is a type that makes a single function\n\/\/ implement to the nsq.Handler interface which consists\n\/\/ of only one function (just like http.HandlerFunc and http.Handler).\ntype HandlerFunc func(message *nsq.Message) error\n\nfunc (f HandlerFunc) HandleMessage(message *nsq.Message) error {\n\treturn f(message)\n}\n\n\/\/ AttachHandler creates a new nsq.Reader for a topic and attaches the\n\/\/ given handler to it.\nfunc AttachHandler(topic, channel string, lookupd string, handler nsq.Handler) error {\n\tmountReader, err := nsq.NewReader(topic, channel)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmountReader.AddHandler(handler)\n\treturn mountReader.ConnectToLookupd(lookupd)\n}\n\n\/\/ AttachEphemeralHandler create a new nsq.Reader for a topic and attaches the\n\/\/ given handler to it. The nsq channel to which the handler gets attached\n\/\/ will be ephemeral. Ephemeral channels will not be buffered to disk and may\n\/\/ drop messages. Ephemeral channels will also not be persisted after its\n\/\/ last client disconnects.\nfunc AttachEphemeralHandler(topic, channel, lookupd string, handler nsq.Handler) error {\n\treturn AttachHandler(topic, channel + \"#ephemeral\", lookupd, handler)\n}\n<commit_msg>reduce name for ephemeral channels in length if it's too long.<commit_after>package knsq\n\nimport (\n\t\"github.com\/bitly\/nsq\/nsq\"\n)\n\n\/\/ MustReader calls nsq.NewReader and panics if nsq.NewReader\n\/\/ returned an error. nsq.NewReader only fails on invalid\n\/\/ topic and channel names.\nfunc MustReader(topic, channel string) *nsq.Reader {\n\tr, err := nsq.NewReader(topic, channel)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn r\n}\n\n\/\/ HandlerFunc is a type that makes a single function\n\/\/ implement to the nsq.Handler interface which consists\n\/\/ of only one function (just like http.HandlerFunc and http.Handler).\ntype HandlerFunc func(message *nsq.Message) error\n\nfunc (f HandlerFunc) HandleMessage(message *nsq.Message) error {\n\treturn f(message)\n}\n\n\/\/ AttachHandler creates a new nsq.Reader for a topic and attaches the\n\/\/ given handler to it.\nfunc AttachHandler(topic, channel string, lookupd string, handler nsq.Handler) error {\n\tmountReader, err := nsq.NewReader(topic, channel)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmountReader.AddHandler(handler)\n\treturn mountReader.ConnectToLookupd(lookupd)\n}\n\n\/\/ AttachEphemeralHandler create a new nsq.Reader for a topic and attaches the\n\/\/ given handler to it. The nsq channel to which the handler gets attached\n\/\/ will be ephemeral. Ephemeral channels will not be buffered to disk and may\n\/\/ drop messages. Ephemeral channels will also not be persisted after its\n\/\/ last client disconnects.\nfunc AttachEphemeralHandler(topic, channel, lookupd string, handler nsq.Handler) error {\n\tephSuffix := \"#ephemeral\"\n\tif (len(channel) + len(ephSuffix) > 32) {\n\t\tchannel = channel[:32 - len(ephSuffix)]\n\t}\n\treturn AttachHandler(topic, channel + ephSuffix, lookupd, handler)\n}\n<|endoftext|>"}
{"text":"<commit_before>package force\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ Custom Error to handle salesforce api responses.\ntype ApiErrors []*ApiError\n\ntype ApiError struct {\n\tFields           []string `json:\"fields,omitempty\" force:\"fields,omitempty\"`\n\tMessage          string   `json:\"message,omitempty\" force:\"message,omitempty\"`\n\tErrorCode        string   `json:\"errorCode,omitempty\" force:\"errorCode,omitempty\"`\n\tErrorName        string   `json:\"error,omitempty\" force:\"error,omitempty\"`\n\tErrorDescription string   `json:\"error_description,omitempty\" force:\"error_description,omitempty\"`\n}\n\nfunc (e ApiErrors) Error() string {\n\treturn fmt.Sprintf(\"%#v\", e)\n}\n\nfunc (e ApiErrors) Validate() bool {\n\tif len(e) != 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (e ApiError) Error() string {\n\treturn fmt.Sprintf(\"%#v\", e)\n}\n\nfunc (e ApiError) Validate() bool {\n\tif len(e.Fields) != 0 || len(e.Message) != 0 || len(e.ErrorCode) != 0 || len(e.ErrorName) != 0 || len(e.ErrorDescription) != 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n<commit_msg>Fixed the Error method for ApiErrors so that it prints each error.<commit_after>package force\n\nimport (\n\t\"fmt\"\n)\n\n\/\/ Custom Error to handle salesforce api responses.\ntype ApiErrors []*ApiError\n\ntype ApiError struct {\n\tFields           []string `json:\"fields,omitempty\" force:\"fields,omitempty\"`\n\tMessage          string   `json:\"message,omitempty\" force:\"message,omitempty\"`\n\tErrorCode        string   `json:\"errorCode,omitempty\" force:\"errorCode,omitempty\"`\n\tErrorName        string   `json:\"error,omitempty\" force:\"error,omitempty\"`\n\tErrorDescription string   `json:\"error_description,omitempty\" force:\"error_description,omitempty\"`\n}\n\nfunc (e ApiErrors) Error() string {\n\treturn fmt.Sprintf(\"%#v\", e.Errors)\n}\n\nfunc (e ApiErrors) Errors() []string {\n\teArr := make([]string, len(e))\n\tfor i, err := range e {\n\t\teArr[i] = err.Error()\n\t}\n\treturn eArr\n}\n\nfunc (e ApiErrors) Validate() bool {\n\tif len(e) != 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (e ApiError) Error() string {\n\treturn fmt.Sprintf(\"%#v\", e)\n}\n\nfunc (e ApiError) Validate() bool {\n\tif len(e.Fields) != 0 || len(e.Message) != 0 || len(e.ErrorCode) != 0 || len(e.ErrorName) != 0 || len(e.ErrorDescription) != 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/coreos\/locksmith\/third_party\/github.com\/coreos\/go-systemd\/dbus\"\n\t\"github.com\/coreos\/locksmith\/third_party\/github.com\/coreos\/go-systemd\/login1\"\n\n\t\"github.com\/coreos\/locksmith\/lock\"\n\t\"github.com\/coreos\/locksmith\/pkg\/machineid\"\n\t\"github.com\/coreos\/locksmith\/updateengine\"\n)\n\nvar (\n\tcmdDaemon = &Command{\n\t\tName:        \"daemon\",\n\t\tSummary:     \"Daemon for reboot needed signal and if reboot able.\",\n\t\tDescription: `Daemon waits for the reboot needed signal coming out of update engine and attempts to acquire the reboot lock. If the reboot lock is acquired then the machine will reboot.`,\n\t\tRun:         runDaemon,\n\t}\n)\n\nconst (\n\tinitialTimeout = time.Second * 5\n\tmaxTimeout     = time.Minute * 5\n)\n\nconst (\n\tStrategyReboot     = \"reboot\"\n\tStrategyEtcdLock   = \"etcd-lock\"\n\tStrategyBestEffort = \"best-effort\"\n)\n\nfunc expBackoff(try int) time.Duration {\n\tsleep := time.Duration(math.Pow(2, float64(try))) * initialTimeout\n\tif sleep > maxTimeout {\n\t\tsleep = maxTimeout\n\t}\n\n\treturn sleep\n}\n\nfunc rebootAndSleep(lgn *login1.Conn) {\n\tlgn.Reboot(false)\n\tfmt.Println(\"Reboot sent. Going to sleep.\")\n\n\t\/\/ Wait a really long time for the reboot to occur.\n\ttime.Sleep(time.Hour * 24 * 7)\n}\n\n\/\/ lockAndReboot attempts to acquire the lock and reboot the machine in an\n\/\/ infinite loop. Returns if the reboot failed.\nfunc lockAndReboot(lck *lock.Lock, lgn *login1.Conn) {\n\ttries := 0\n\tfor {\n\t\terr := lck.Lock()\n\t\tif err != nil && err != lock.ErrExist {\n\t\t\tsleep := expBackoff(tries)\n\t\t\tfmt.Printf(\"Retrying in %v. Error locking: %v\\n\", sleep, err)\n\t\t\ttime.Sleep(sleep)\n\t\t\ttries = tries + 1\n\n\t\t\tcontinue\n\t\t}\n\n\t\trebootAndSleep(lgn)\n\n\t\treturn\n\t}\n}\n\nfunc unlockIfHeld(lck *lock.Lock) {\n\ttries := 0\n\tfor {\n\t\terr := lck.Unlock()\n\t\tif err == nil {\n\t\t\tfmt.Println(\"Unlocked existing lock for this machine\")\n\t\t\treturn\n\t\t} else if err == lock.ErrNotExist {\n\t\t\treturn\n\t\t}\n\n\t\tsleep := expBackoff(tries)\n\t\tfmt.Println(\"Retrying in %v. Error unlocking: %v\", sleep, err)\n\t\ttime.Sleep(sleep)\n\t\ttries = tries + 1\n\t}\n}\n\nfunc setupLock() (lck *lock.Lock, err error) {\n\telc, err := lock.NewEtcdLockClient(nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error initializing etcd client: %v\", err)\n\t}\n\n\tmID := machineid.MachineID(\"\/\")\n\tif mID == \"\" {\n\t\treturn nil, fmt.Errorf(\"Cannot read machine-id\")\n\t}\n\n\tlck = lock.New(mID, elc)\n\n\tunlockIfHeld(lck)\n\n\treturn lck, nil\n}\n\n\/\/ etcdActive returns true if etcd is not in an inactive state according to systemd.\nfunc etcdActive() (running bool, err error) {\n\tsys, err := dbus.New()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tprop, err := sys.GetUnitProperty(\"etcd.service\", \"ActiveState\")\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"Error getting etcd.service ActiveState: %v\", err)\n\t}\n\n\tif prop.Value.Value().(string) == \"inactive\" {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}\n\nfunc reboot(useLock bool, lck *lock.Lock, lgn *login1.Conn) {\n\tif useLock {\n\t\tlockAndReboot(lck, lgn)\n\t}\n\n\trebootAndSleep(lgn)\n\tfmt.Println(\"Error: reboot attempt never finished\")\n}\n\nfunc runDaemon(args []string) int {\n\tvar lck *lock.Lock\n\n\tuseLock := false\n\tswitch s := os.ExpandEnv(\"${LOCKSMITH_STRATEGY}\"); {\n\tcase s == \"\":\n\t\tfallthrough\n\tcase s == StrategyBestEffort:\n\t\trunning, err := etcdActive()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\treturn 1\n\t\t}\n\t\tif running {\n\t\t\tfmt.Println(\"etcd.service is active\")\n\t\t\tuseLock = true\n\t\t} else {\n\t\t\tfmt.Println(\"etcd.service is inactive\")\n\t\t\tuseLock = false\n\t\t}\n\tcase s == StrategyEtcdLock:\n\t\tuseLock = true\n\tcase s == StrategyReboot:\n\t\tuseLock = false\n\tdefault:\n\t\tfmt.Fprintln(os.Stderr, \"Unknown strategy:\", s)\n\t\treturn 1\n\t}\n\n\tue, err := updateengine.New()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Error initializing update1 client:\", err)\n\t\treturn 1\n\t}\n\n\tlgn, err := login1.New()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Error initializing login1 client:\", err)\n\t\treturn 1\n\t}\n\n\tif useLock {\n\t\tlck, err = setupLock()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\treturn 1\n\t\t}\n\t}\n\n\tch := make(chan updateengine.Status, 1)\n\tgo ue.RebootNeededSignal(ch)\n\n\tresult, err := ue.GetStatus()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Cannot get update engine status:\", err)\n\t\treturn 1\n\t}\n\n\tif result.CurrentOperation == updateengine.UpdateStatusUpdatedNeedReboot {\n\t\treboot(useLock, lck, lgn)\n\t\treturn 1\n\t}\n\n\tfmt.Printf(\"locksmithd starting currentOperation=%q strategy=%q useLock=%t\\n\",\n\t\tresult.CurrentOperation,\n\t\tos.ExpandEnv(\"${LOCKSMITH_STRATEGY}\"),\n\t\tuseLock,\n\t)\n\n\t\/\/ Wait for a reboot needed signal\n\t<-ch\n\treboot(useLock, lck, lgn)\n\n\treturn 1\n}\n<commit_msg>feat(daemon): wait until you get a signal to check for etcd<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/coreos\/locksmith\/third_party\/github.com\/coreos\/go-systemd\/dbus\"\n\t\"github.com\/coreos\/locksmith\/third_party\/github.com\/coreos\/go-systemd\/login1\"\n\n\t\"github.com\/coreos\/locksmith\/lock\"\n\t\"github.com\/coreos\/locksmith\/pkg\/machineid\"\n\t\"github.com\/coreos\/locksmith\/updateengine\"\n)\n\nvar (\n\tcmdDaemon = &Command{\n\t\tName:        \"daemon\",\n\t\tSummary:     \"Daemon for reboot needed signal and if reboot able.\",\n\t\tDescription: `Daemon waits for the reboot needed signal coming out of update engine and attempts to acquire the reboot lock. If the reboot lock is acquired then the machine will reboot.`,\n\t\tRun:         runDaemon,\n\t}\n)\n\nconst (\n\tinitialTimeout = time.Second * 5\n\tmaxTimeout     = time.Minute * 5\n)\n\nconst (\n\tStrategyReboot     = \"reboot\"\n\tStrategyEtcdLock   = \"etcd-lock\"\n\tStrategyBestEffort = \"best-effort\"\n)\n\nfunc expBackoff(try int) time.Duration {\n\tsleep := time.Duration(math.Pow(2, float64(try))) * initialTimeout\n\tif sleep > maxTimeout {\n\t\tsleep = maxTimeout\n\t}\n\n\treturn sleep\n}\n\nfunc rebootAndSleep(lgn *login1.Conn) {\n\tlgn.Reboot(false)\n\tfmt.Println(\"Reboot sent. Going to sleep.\")\n\n\t\/\/ Wait a really long time for the reboot to occur.\n\ttime.Sleep(time.Hour * 24 * 7)\n}\n\n\/\/ lockAndReboot attempts to acquire the lock and reboot the machine in an\n\/\/ infinite loop. Returns if the reboot failed.\nfunc (r rebooter) lockAndReboot(lck *lock.Lock) {\n\ttries := 0\n\tfor {\n\t\terr := lck.Lock()\n\t\tif err != nil && err != lock.ErrExist {\n\t\t\tsleep := expBackoff(tries)\n\t\t\tfmt.Printf(\"Retrying in %v. Error locking: %v\\n\", sleep, err)\n\t\t\ttime.Sleep(sleep)\n\t\t\ttries = tries + 1\n\n\t\t\tcontinue\n\t\t}\n\n\t\trebootAndSleep(r.lgn)\n\n\t\treturn\n\t}\n}\n\nfunc unlockIfHeld(lck *lock.Lock) {\n\ttries := 0\n\tfor {\n\t\terr := lck.Unlock()\n\t\tif err == nil {\n\t\t\tfmt.Println(\"Unlocked existing lock for this machine\")\n\t\t\treturn\n\t\t} else if err == lock.ErrNotExist {\n\t\t\treturn\n\t\t}\n\n\t\tsleep := expBackoff(tries)\n\t\tfmt.Println(\"Retrying in %v. Error unlocking: %v\", sleep, err)\n\t\ttime.Sleep(sleep)\n\t\ttries = tries + 1\n\t}\n}\n\nfunc setupLock() (lck *lock.Lock, err error) {\n\telc, err := lock.NewEtcdLockClient(nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error initializing etcd client: %v\", err)\n\t}\n\n\tmID := machineid.MachineID(\"\/\")\n\tif mID == \"\" {\n\t\treturn nil, fmt.Errorf(\"Cannot read machine-id\")\n\t}\n\n\tlck = lock.New(mID, elc)\n\n\tunlockIfHeld(lck)\n\n\treturn lck, nil\n}\n\n\/\/ etcdActive returns true if etcd is not in an inactive state according to systemd.\nfunc etcdActive() (running bool, err error) {\n\tsys, err := dbus.New()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tprop, err := sys.GetUnitProperty(\"etcd.service\", \"ActiveState\")\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"Error getting etcd.service ActiveState: %v\", err)\n\t}\n\n\tif prop.Value.Value().(string) == \"inactive\" {\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}\n\ntype rebooter struct {\n\tstrategy string\n\tlgn *login1.Conn\n}\n\nfunc (r rebooter) useLock() (useLock bool, err error) {\n\tswitch r.strategy {\n\tcase \"\":\n\t\tfallthrough\n\tcase StrategyBestEffort:\n\t\trunning, err := etcdActive()\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tif running {\n\t\t\tfmt.Println(\"etcd.service is active\")\n\t\t\tuseLock = true\n\t\t} else {\n\t\t\tfmt.Println(\"etcd.service is inactive\")\n\t\t\tuseLock = false\n\t\t}\n\tcase StrategyEtcdLock:\n\t\tuseLock = true\n\tcase StrategyReboot:\n\t\tuseLock = false\n\tdefault:\n\t\treturn false, fmt.Errorf(\"Unknown strategy: %s\", r.strategy)\n\t}\n\n\treturn useLock, nil\n}\n\nfunc (r rebooter) reboot() int {\n\tuseLock, err := r.useLock()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\treturn 1\n\t}\n\n\tif useLock {\n\t\tlck, err := setupLock()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\treturn 1\n\t\t}\n\n\t\tr.lockAndReboot(lck)\n\t}\n\n\trebootAndSleep(r.lgn)\n\tfmt.Println(\"Error: reboot attempt never finished\")\n\treturn 1\n}\n\nfunc runDaemon(args []string) int {\n\tstrategy := os.ExpandEnv(\"${LOCKSMITH_STRATEGY}\")\n\n\tue, err := updateengine.New()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Error initializing update1 client:\", err)\n\t\treturn 1\n\t}\n\n\tlgn, err := login1.New()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Error initializing login1 client:\", err)\n\t\treturn 1\n\t}\n\n\n\tch := make(chan updateengine.Status, 1)\n\tgo ue.RebootNeededSignal(ch)\n\n\tr := rebooter{strategy, lgn}\n\n\tresult, err := ue.GetStatus()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"Cannot get update engine status:\", err)\n\t\treturn 1\n\t}\n\n\tif result.CurrentOperation == updateengine.UpdateStatusUpdatedNeedReboot {\n\t\treturn r.reboot()\n\t}\n\n\tfmt.Printf(\"locksmithd starting currentOperation=%q strategy=%q\\n\",\n\t\tresult.CurrentOperation,\n\t\tos.ExpandEnv(\"${LOCKSMITH_STRATEGY}\"),\n\t)\n\n\t\/\/ Wait for a reboot needed signal\n\t<-ch\n\treturn r.reboot()\n}\n<|endoftext|>"}
{"text":"<commit_before>package profile\n\nimport (\n\t\"github.com\/godbus\/dbus\"\n\t\"github.com\/muka\/go-bluetooth\/bluez\"\n)\n\n\/\/ NewAdapter1 create a new Adapter1 client\nfunc NewAdapter1(hostID string) *Adapter1 {\n\ta := new(Adapter1)\n\ta.client = bluez.NewClient(\n\t\t&bluez.Config{\n\t\t\tName:  \"org.bluez\",\n\t\t\tIface: bluez.Adapter1Interface,\n\t\t\tPath:  \"\/org\/bluez\/\" + hostID,\n\t\t\tBus:   bluez.SystemBus,\n\t\t},\n\t)\n\ta.Properties = new(Adapter1Properties)\n\ta.GetProperties()\n\treturn a\n}\n\n\/\/ Adapter1 client\ntype Adapter1 struct {\n\tclient     *bluez.Client\n\tProperties *Adapter1Properties\n}\n\n\/\/Adapter1Properties contains the exposed properties of an interface\ntype Adapter1Properties struct {\n\tUUIDs               []string\n\tDiscoverable        bool\n\tDiscovering         bool\n\tPairable            bool\n\tPowered             bool\n\tAddress             string\n\tAlias               string\n\tModalias            string\n\tName                string\n\tClass               uint32\n\tDiscoverableTimeout uint32\n\tPairableTimeout     uint32\n}\n\n\/\/ Close the connection\nfunc (a *Adapter1) Close() {\n\ta.client.Disconnect()\n}\n\n\/\/GetProperties load all available properties\nfunc (a *Adapter1) GetProperties() (*Adapter1Properties, error) {\n\terr := a.client.GetProperties(a.Properties)\n\treturn a.Properties, err\n}\n\n\/\/SetProperty set a property\nfunc (a *Adapter1) SetProperty(name string, value interface{}) error {\n\treturn a.client.SetProperty(name, value)\n}\n\n\/\/StartDiscovery on the adapter\nfunc (a *Adapter1) StartDiscovery() error {\n\treturn a.client.Call(\"StartDiscovery\", 0).Store()\n}\n\n\/\/StopDiscovery on the adapter\nfunc (a *Adapter1) StopDiscovery() error {\n\treturn a.client.Call(\"StopDiscovery\", 0).Store()\n}\n\n\/\/RemoveDevice from the list\nfunc (a *Adapter1) RemoveDevice(device string) error {\n\treturn a.client.Call(\"RemoveDevice\", 0, dbus.ObjectPath(device)).Store()\n}\n<commit_msg>add support for setting discovery filters<commit_after>package profile\n\nimport (\n\t\"github.com\/godbus\/dbus\"\n\t\"github.com\/muka\/go-bluetooth\/bluez\"\n)\n\n\/\/ NewAdapter1 create a new Adapter1 client\nfunc NewAdapter1(hostID string) *Adapter1 {\n\ta := new(Adapter1)\n\ta.client = bluez.NewClient(\n\t\t&bluez.Config{\n\t\t\tName:  \"org.bluez\",\n\t\t\tIface: bluez.Adapter1Interface,\n\t\t\tPath:  \"\/org\/bluez\/\" + hostID,\n\t\t\tBus:   bluez.SystemBus,\n\t\t},\n\t)\n\ta.Properties = new(Adapter1Properties)\n\ta.GetProperties()\n\treturn a\n}\n\n\/\/ Adapter1 client\ntype Adapter1 struct {\n\tclient     *bluez.Client\n\tProperties *Adapter1Properties\n}\n\n\/\/Adapter1Properties contains the exposed properties of an interface\ntype Adapter1Properties struct {\n\tUUIDs               []string\n\tDiscoverable        bool\n\tDiscovering         bool\n\tPairable            bool\n\tPowered             bool\n\tAddress             string\n\tAlias               string\n\tModalias            string\n\tName                string\n\tClass               uint32\n\tDiscoverableTimeout uint32\n\tPairableTimeout     uint32\n}\n\n\/\/ Close the connection\nfunc (a *Adapter1) Close() {\n\ta.client.Disconnect()\n}\n\n\/\/GetProperties load all available properties\nfunc (a *Adapter1) GetProperties() (*Adapter1Properties, error) {\n\terr := a.client.GetProperties(a.Properties)\n\treturn a.Properties, err\n}\n\n\/\/SetProperty set a property\nfunc (a *Adapter1) SetProperty(name string, value interface{}) error {\n\treturn a.client.SetProperty(name, value)\n}\n\n\/\/StartDiscovery on the adapter\nfunc (a *Adapter1) StartDiscovery() error {\n\treturn a.client.Call(\"StartDiscovery\", 0).Store()\n}\n\n\/\/StopDiscovery on the adapter\nfunc (a *Adapter1) StopDiscovery() error {\n\treturn a.client.Call(\"StopDiscovery\", 0).Store()\n}\n\n\/\/RemoveDevice from the list\nfunc (a *Adapter1) RemoveDevice(device string) error {\n\treturn a.client.Call(\"RemoveDevice\", 0, dbus.ObjectPath(device)).Store()\n}\n\n\/\/GetDiscoveryFilters - get supported discovery filters\nfunc (a *Adapter1) GetDiscoveryFilters() ([]string, error) {\n\tvar f []string\n\terr := a.client.Call(\"GetDiscoveryFilters\", 0).Store(&f)\n\treturn f, err\n}\n\n\/\/SetDiscoveryFilters - set discovery filters.\n\/\/\n\/\/ Example:\n\/\/ \tfilters := map[string]interface{} {\n\/\/\t\t\"RSSI\": int16(-127),\n\/\/\t\t\"Transport\": \"le\",\n\/\/\t\t\"DuplicateData\": true,\n\/\/\t\t\"UUIDs\": []string{\"0x180a\", \"0x1400\"},\n\/\/\t}\n\/\/  adapter.SetDiscoveryFilter(filter)\nfunc (a *Adapter1) SetDiscoveryFilter(f map[string]interface{}) error {\n\treturn a.client.Call(\"SetDiscoveryFilter\", 0, f).Store()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Apcera Inc. All rights reserved.\n\npackage graft\n\nimport (\n\t\"time\"\n)\n\nconst (\n\tVERSION = \"0.1\"\n\n\t\/\/ Election timeout MIN and MAX per RAFT spec suggestion.\n\tMIN_ELECTION_TIMEOUT = 500 * time.Millisecond\n\tMAX_ELECTION_TIMEOUT = 2 * MIN_ELECTION_TIMEOUT\n\n\t\/\/ Heartbeat tick for LEADERS.\n\t\/\/ Should be << MIN_ELECTION_TIMEOUT per RAFT spec.\n\tHEARTBEAT_INTERVAL = 100 * time.Millisecond\n\n\tNO_LEADER = \"\"\n\tNO_VOTE   = \"\"\n\n\t\/\/ Use buffer channels.\n\tCHAN_SIZE = 8\n)\n<commit_msg>Removed channel buffer size<commit_after>\/\/ Copyright 2013 Apcera Inc. All rights reserved.\n\npackage graft\n\nimport (\n\t\"time\"\n)\n\nconst (\n\tVERSION = \"0.1\"\n\n\t\/\/ Election timeout MIN and MAX per RAFT spec suggestion.\n\tMIN_ELECTION_TIMEOUT = 500 * time.Millisecond\n\tMAX_ELECTION_TIMEOUT = 2 * MIN_ELECTION_TIMEOUT\n\n\t\/\/ Heartbeat tick for LEADERS.\n\t\/\/ Should be << MIN_ELECTION_TIMEOUT per RAFT spec.\n\tHEARTBEAT_INTERVAL = 100 * time.Millisecond\n\n\tNO_LEADER = \"\"\n\tNO_VOTE   = \"\"\n)\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage node\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/resource\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/uuid\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n\t\"k8s.io\/apimachinery\/pkg\/watch\"\n\t\"k8s.io\/kubernetes\/test\/e2e\/framework\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\timageutils \"k8s.io\/kubernetes\/test\/utils\/image\"\n)\n\nvar _ = SIGDescribe(\"Pods Extended\", func() {\n\tf := framework.NewDefaultFramework(\"pods\")\n\n\tframework.KubeDescribe(\"Delete Grace Period\", func() {\n\t\tvar podClient *framework.PodClient\n\t\tBeforeEach(func() {\n\t\t\tpodClient = f.PodClient()\n\t\t})\n\t\t\/\/ Flaky issue #36821.\n\t\tframework.ConformanceIt(\"should be submitted and removed  [Flaky]\", func() {\n\t\t\tBy(\"creating the pod\")\n\t\t\tname := \"pod-submit-remove-\" + string(uuid.NewUUID())\n\t\t\tvalue := strconv.Itoa(time.Now().Nanosecond())\n\t\t\tpod := &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: name,\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"name\": \"foo\",\n\t\t\t\t\t\t\"time\": value,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tContainers: []v1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:  \"nginx\",\n\t\t\t\t\t\t\tImage: imageutils.GetE2EImage(imageutils.NginxSlim),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tBy(\"setting up watch\")\n\t\t\tselector := labels.SelectorFromSet(labels.Set(map[string]string{\"time\": value}))\n\t\t\toptions := metav1.ListOptions{LabelSelector: selector.String()}\n\t\t\tpods, err := podClient.List(options)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to query for pod\")\n\t\t\tExpect(len(pods.Items)).To(Equal(0))\n\t\t\toptions = metav1.ListOptions{\n\t\t\t\tLabelSelector:   selector.String(),\n\t\t\t\tResourceVersion: pods.ListMeta.ResourceVersion,\n\t\t\t}\n\t\t\tw, err := podClient.Watch(options)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to set up watch\")\n\n\t\t\tBy(\"submitting the pod to kubernetes\")\n\t\t\tpodClient.Create(pod)\n\n\t\t\tBy(\"verifying the pod is in kubernetes\")\n\t\t\tselector = labels.SelectorFromSet(labels.Set(map[string]string{\"time\": value}))\n\t\t\toptions = metav1.ListOptions{LabelSelector: selector.String()}\n\t\t\tpods, err = podClient.List(options)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to query for pod\")\n\t\t\tExpect(len(pods.Items)).To(Equal(1))\n\n\t\t\tBy(\"verifying pod creation was observed\")\n\t\t\tselect {\n\t\t\tcase event, _ := <-w.ResultChan():\n\t\t\t\tif event.Type != watch.Added {\n\t\t\t\t\tframework.Failf(\"Failed to observe pod creation: %v\", event)\n\t\t\t\t}\n\t\t\tcase <-time.After(framework.PodStartTimeout):\n\t\t\t\tframework.Failf(\"Timeout while waiting for pod creation\")\n\t\t\t}\n\n\t\t\t\/\/ We need to wait for the pod to be running, otherwise the deletion\n\t\t\t\/\/ may be carried out immediately rather than gracefully.\n\t\t\tframework.ExpectNoError(f.WaitForPodRunning(pod.Name))\n\t\t\t\/\/ save the running pod\n\t\t\tpod, err = podClient.Get(pod.Name, metav1.GetOptions{})\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to GET scheduled pod\")\n\n\t\t\t\/\/ start local proxy, so we can send graceful deletion over query string, rather than body parameter\n\t\t\tcmd := framework.KubectlCmd(\"proxy\", \"-p\", \"0\")\n\t\t\tstdout, stderr, err := framework.StartCmdAndStreamOutput(cmd)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to start up proxy\")\n\t\t\tdefer stdout.Close()\n\t\t\tdefer stderr.Close()\n\t\t\tdefer framework.TryKill(cmd)\n\t\t\tbuf := make([]byte, 128)\n\t\t\tvar n int\n\t\t\tn, err = stdout.Read(buf)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to read from kubectl proxy stdout\")\n\t\t\toutput := string(buf[:n])\n\t\t\tproxyRegexp := regexp.MustCompile(\"Starting to serve on 127.0.0.1:([0-9]+)\")\n\t\t\tmatch := proxyRegexp.FindStringSubmatch(output)\n\t\t\tExpect(len(match)).To(Equal(2))\n\t\t\tport, err := strconv.Atoi(match[1])\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to convert port into string\")\n\n\t\t\tendpoint := fmt.Sprintf(\"http:\/\/localhost:%d\/api\/v1\/namespaces\/%s\/pods\/%s?gracePeriodSeconds=30\", port, pod.Namespace, pod.Name)\n\t\t\ttr := &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t\t}\n\t\t\tclient := &http.Client{Transport: tr}\n\t\t\treq, err := http.NewRequest(\"DELETE\", endpoint, nil)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to create http request\")\n\n\t\t\tBy(\"deleting the pod gracefully\")\n\t\t\trsp, err := client.Do(req)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to use http client to send delete\")\n\n\t\t\tdefer rsp.Body.Close()\n\n\t\t\tBy(\"verifying the kubelet observed the termination notice\")\n\t\t\tExpect(wait.Poll(time.Second*5, time.Second*30, func() (bool, error) {\n\t\t\t\tpodList, err := framework.GetKubeletPods(f.ClientSet, pod.Spec.NodeName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tframework.Logf(\"Unable to retrieve kubelet pods for node %v: %v\", pod.Spec.NodeName, err)\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t\tfor _, kubeletPod := range podList.Items {\n\t\t\t\t\tif pod.Name != kubeletPod.Name {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif kubeletPod.ObjectMeta.DeletionTimestamp == nil {\n\t\t\t\t\t\tframework.Logf(\"deletion has not yet been observed\")\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t}\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\t\t\t\tframework.Logf(\"no pod exists with the name we were looking for, assuming the termination request was observed and completed\")\n\t\t\t\treturn true, nil\n\t\t\t})).NotTo(HaveOccurred(), \"kubelet never observed the termination notice\")\n\n\t\t\tBy(\"verifying pod deletion was observed\")\n\t\t\tdeleted := false\n\t\t\ttimeout := false\n\t\t\tvar lastPod *v1.Pod\n\t\t\ttimer := time.After(1 * time.Minute)\n\t\t\tfor !deleted && !timeout {\n\t\t\t\tselect {\n\t\t\t\tcase event, _ := <-w.ResultChan():\n\t\t\t\t\tif event.Type == watch.Deleted {\n\t\t\t\t\t\tlastPod = event.Object.(*v1.Pod)\n\t\t\t\t\t\tdeleted = true\n\t\t\t\t\t}\n\t\t\t\tcase <-timer:\n\t\t\t\t\ttimeout = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !deleted {\n\t\t\t\tframework.Failf(\"Failed to observe pod deletion\")\n\t\t\t}\n\n\t\t\tExpect(lastPod.DeletionTimestamp).ToNot(BeNil())\n\t\t\tExpect(lastPod.Spec.TerminationGracePeriodSeconds).ToNot(BeZero())\n\n\t\t\tselector = labels.SelectorFromSet(labels.Set(map[string]string{\"time\": value}))\n\t\t\toptions = metav1.ListOptions{LabelSelector: selector.String()}\n\t\t\tpods, err = podClient.List(options)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to query for pods\")\n\t\t\tExpect(len(pods.Items)).To(Equal(0))\n\n\t\t})\n\t})\n\n\tframework.KubeDescribe(\"Pods Set QOS Class\", func() {\n\t\tvar podClient *framework.PodClient\n\t\tBeforeEach(func() {\n\t\t\tpodClient = f.PodClient()\n\t\t})\n\t\tframework.ConformanceIt(\"should be submitted and removed \", func() {\n\t\t\tBy(\"creating the pod\")\n\t\t\tname := \"pod-qos-class-\" + string(uuid.NewUUID())\n\t\t\tpod := &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: name,\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"name\": name,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tContainers: []v1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:  \"nginx\",\n\t\t\t\t\t\t\tImage: imageutils.GetE2EImage(imageutils.NginxSlim),\n\t\t\t\t\t\t\tResources: v1.ResourceRequirements{\n\t\t\t\t\t\t\t\tLimits: v1.ResourceList{\n\t\t\t\t\t\t\t\t\tv1.ResourceCPU:    resource.MustParse(\"100m\"),\n\t\t\t\t\t\t\t\t\tv1.ResourceMemory: resource.MustParse(\"100Mi\"),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tRequests: v1.ResourceList{\n\t\t\t\t\t\t\t\t\tv1.ResourceCPU:    resource.MustParse(\"100m\"),\n\t\t\t\t\t\t\t\t\tv1.ResourceMemory: resource.MustParse(\"100Mi\"),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tBy(\"submitting the pod to kubernetes\")\n\t\t\tpodClient.Create(pod)\n\n\t\t\tBy(\"verifying QOS class is set on the pod\")\n\t\t\tpod, err := podClient.Get(name, metav1.GetOptions{})\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to query for pod\")\n\t\t\tExpect(pod.Status.QOSClass == v1.PodQOSGuaranteed)\n\t\t})\n\t})\n})\n<commit_msg>Pod deletion can be contended, causing test failure<commit_after>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage node\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/resource\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/uuid\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n\t\"k8s.io\/apimachinery\/pkg\/watch\"\n\t\"k8s.io\/kubernetes\/test\/e2e\/framework\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\timageutils \"k8s.io\/kubernetes\/test\/utils\/image\"\n)\n\nvar _ = SIGDescribe(\"Pods Extended\", func() {\n\tf := framework.NewDefaultFramework(\"pods\")\n\n\tframework.KubeDescribe(\"Delete Grace Period\", func() {\n\t\tvar podClient *framework.PodClient\n\t\tBeforeEach(func() {\n\t\t\tpodClient = f.PodClient()\n\t\t})\n\t\t\/\/ Flaky issue #36821.\n\t\tframework.ConformanceIt(\"should be submitted and removed  [Flaky]\", func() {\n\t\t\tBy(\"creating the pod\")\n\t\t\tname := \"pod-submit-remove-\" + string(uuid.NewUUID())\n\t\t\tvalue := strconv.Itoa(time.Now().Nanosecond())\n\t\t\tpod := &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: name,\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"name\": \"foo\",\n\t\t\t\t\t\t\"time\": value,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tContainers: []v1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:  \"nginx\",\n\t\t\t\t\t\t\tImage: imageutils.GetE2EImage(imageutils.NginxSlim),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tBy(\"setting up watch\")\n\t\t\tselector := labels.SelectorFromSet(labels.Set(map[string]string{\"time\": value}))\n\t\t\toptions := metav1.ListOptions{LabelSelector: selector.String()}\n\t\t\tpods, err := podClient.List(options)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to query for pod\")\n\t\t\tExpect(len(pods.Items)).To(Equal(0))\n\t\t\toptions = metav1.ListOptions{\n\t\t\t\tLabelSelector:   selector.String(),\n\t\t\t\tResourceVersion: pods.ListMeta.ResourceVersion,\n\t\t\t}\n\t\t\tw, err := podClient.Watch(options)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to set up watch\")\n\n\t\t\tBy(\"submitting the pod to kubernetes\")\n\t\t\tpodClient.Create(pod)\n\n\t\t\tBy(\"verifying the pod is in kubernetes\")\n\t\t\tselector = labels.SelectorFromSet(labels.Set(map[string]string{\"time\": value}))\n\t\t\toptions = metav1.ListOptions{LabelSelector: selector.String()}\n\t\t\tpods, err = podClient.List(options)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to query for pod\")\n\t\t\tExpect(len(pods.Items)).To(Equal(1))\n\n\t\t\tBy(\"verifying pod creation was observed\")\n\t\t\tselect {\n\t\t\tcase event, _ := <-w.ResultChan():\n\t\t\t\tif event.Type != watch.Added {\n\t\t\t\t\tframework.Failf(\"Failed to observe pod creation: %v\", event)\n\t\t\t\t}\n\t\t\tcase <-time.After(framework.PodStartTimeout):\n\t\t\t\tframework.Failf(\"Timeout while waiting for pod creation\")\n\t\t\t}\n\n\t\t\t\/\/ We need to wait for the pod to be running, otherwise the deletion\n\t\t\t\/\/ may be carried out immediately rather than gracefully.\n\t\t\tframework.ExpectNoError(f.WaitForPodRunning(pod.Name))\n\t\t\t\/\/ save the running pod\n\t\t\tpod, err = podClient.Get(pod.Name, metav1.GetOptions{})\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to GET scheduled pod\")\n\n\t\t\t\/\/ start local proxy, so we can send graceful deletion over query string, rather than body parameter\n\t\t\tcmd := framework.KubectlCmd(\"proxy\", \"-p\", \"0\")\n\t\t\tstdout, stderr, err := framework.StartCmdAndStreamOutput(cmd)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to start up proxy\")\n\t\t\tdefer stdout.Close()\n\t\t\tdefer stderr.Close()\n\t\t\tdefer framework.TryKill(cmd)\n\t\t\tbuf := make([]byte, 128)\n\t\t\tvar n int\n\t\t\tn, err = stdout.Read(buf)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to read from kubectl proxy stdout\")\n\t\t\toutput := string(buf[:n])\n\t\t\tproxyRegexp := regexp.MustCompile(\"Starting to serve on 127.0.0.1:([0-9]+)\")\n\t\t\tmatch := proxyRegexp.FindStringSubmatch(output)\n\t\t\tExpect(len(match)).To(Equal(2))\n\t\t\tport, err := strconv.Atoi(match[1])\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to convert port into string\")\n\n\t\t\tendpoint := fmt.Sprintf(\"http:\/\/localhost:%d\/api\/v1\/namespaces\/%s\/pods\/%s?gracePeriodSeconds=30\", port, pod.Namespace, pod.Name)\n\t\t\ttr := &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t\t}\n\t\t\tclient := &http.Client{Transport: tr}\n\t\t\treq, err := http.NewRequest(\"DELETE\", endpoint, nil)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to create http request\")\n\n\t\t\tBy(\"deleting the pod gracefully\")\n\t\t\trsp, err := client.Do(req)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to use http client to send delete\")\n\n\t\t\tdefer rsp.Body.Close()\n\n\t\t\tBy(\"verifying the kubelet observed the termination notice\")\n\t\t\tExpect(wait.Poll(time.Second*5, time.Second*30, func() (bool, error) {\n\t\t\t\tpodList, err := framework.GetKubeletPods(f.ClientSet, pod.Spec.NodeName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tframework.Logf(\"Unable to retrieve kubelet pods for node %v: %v\", pod.Spec.NodeName, err)\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t\tfor _, kubeletPod := range podList.Items {\n\t\t\t\t\tif pod.Name != kubeletPod.Name {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif kubeletPod.ObjectMeta.DeletionTimestamp == nil {\n\t\t\t\t\t\tframework.Logf(\"deletion has not yet been observed\")\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t}\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\t\t\t\tframework.Logf(\"no pod exists with the name we were looking for, assuming the termination request was observed and completed\")\n\t\t\t\treturn true, nil\n\t\t\t})).NotTo(HaveOccurred(), \"kubelet never observed the termination notice\")\n\n\t\t\tBy(\"verifying pod deletion was observed\")\n\t\t\tdeleted := false\n\t\t\ttimeout := false\n\t\t\tvar lastPod *v1.Pod\n\t\t\ttimer := time.After(2 * time.Minute)\n\t\t\tfor !deleted && !timeout {\n\t\t\t\tselect {\n\t\t\t\tcase event, _ := <-w.ResultChan():\n\t\t\t\t\tif event.Type == watch.Deleted {\n\t\t\t\t\t\tlastPod = event.Object.(*v1.Pod)\n\t\t\t\t\t\tdeleted = true\n\t\t\t\t\t}\n\t\t\t\tcase <-timer:\n\t\t\t\t\ttimeout = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !deleted {\n\t\t\t\tframework.Failf(\"Failed to observe pod deletion\")\n\t\t\t}\n\n\t\t\tExpect(lastPod.DeletionTimestamp).ToNot(BeNil())\n\t\t\tExpect(lastPod.Spec.TerminationGracePeriodSeconds).ToNot(BeZero())\n\n\t\t\tselector = labels.SelectorFromSet(labels.Set(map[string]string{\"time\": value}))\n\t\t\toptions = metav1.ListOptions{LabelSelector: selector.String()}\n\t\t\tpods, err = podClient.List(options)\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to query for pods\")\n\t\t\tExpect(len(pods.Items)).To(Equal(0))\n\n\t\t})\n\t})\n\n\tframework.KubeDescribe(\"Pods Set QOS Class\", func() {\n\t\tvar podClient *framework.PodClient\n\t\tBeforeEach(func() {\n\t\t\tpodClient = f.PodClient()\n\t\t})\n\t\tframework.ConformanceIt(\"should be submitted and removed \", func() {\n\t\t\tBy(\"creating the pod\")\n\t\t\tname := \"pod-qos-class-\" + string(uuid.NewUUID())\n\t\t\tpod := &v1.Pod{\n\t\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\t\tName: name,\n\t\t\t\t\tLabels: map[string]string{\n\t\t\t\t\t\t\"name\": name,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSpec: v1.PodSpec{\n\t\t\t\t\tContainers: []v1.Container{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName:  \"nginx\",\n\t\t\t\t\t\t\tImage: imageutils.GetE2EImage(imageutils.NginxSlim),\n\t\t\t\t\t\t\tResources: v1.ResourceRequirements{\n\t\t\t\t\t\t\t\tLimits: v1.ResourceList{\n\t\t\t\t\t\t\t\t\tv1.ResourceCPU:    resource.MustParse(\"100m\"),\n\t\t\t\t\t\t\t\t\tv1.ResourceMemory: resource.MustParse(\"100Mi\"),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tRequests: v1.ResourceList{\n\t\t\t\t\t\t\t\t\tv1.ResourceCPU:    resource.MustParse(\"100m\"),\n\t\t\t\t\t\t\t\t\tv1.ResourceMemory: resource.MustParse(\"100Mi\"),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tBy(\"submitting the pod to kubernetes\")\n\t\t\tpodClient.Create(pod)\n\n\t\t\tBy(\"verifying QOS class is set on the pod\")\n\t\t\tpod, err := podClient.Get(name, metav1.GetOptions{})\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to query for pod\")\n\t\t\tExpect(pod.Status.QOSClass == v1.PodQOSGuaranteed)\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>This is not done yet<commit_after><|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/xiaonanln\/goworld\"\n)\n\nvar (\n\t_SERVICE_NAMES = []string{\n\t\t\"OnlineService\",\n\t\t\"SpaceService\",\n\t}\n)\n\nfunc main() {\n\tgoworld.RegisterSpace(&MySpace{}) \/\/ 注册自定义的Space类型\n\n\tgoworld.RegisterEntity(\"OnlineService\", &OnlineService{})\n\tgoworld.RegisterEntity(\"SpaceService\", &SpaceService{})\n\t\/\/ 注册Account类型\n\tgoworld.RegisterEntity(\"Account\", &Account{})\n\t\/\/ 注册Monster类型\n\tgoworld.RegisterEntity(\"Monster\", &Monster{})\n\t\/\/ 注册Avatar类型，并定义属性\n\tgoworld.RegisterEntity(\"Player\", &Player{})\n\t\/\/ 运行游戏服务器\n\tgoworld.Run()\n}\n<commit_msg>fix unity demo<commit_after>package main\n\nimport (\n\t\"github.com\/xiaonanln\/goworld\"\n)\n\nvar (\n\t_SERVICE_NAMES = []string{\n\t\t\"OnlineService\",\n\t\t\"SpaceService\",\n\t}\n)\n\nfunc main() {\n\tgoworld.RegisterSpace(&MySpace{}) \/\/ 注册自定义的Space类型\n\n\tgoworld.RegisterService(\"OnlineService\", &OnlineService{})\n\tgoworld.RegisterService(\"SpaceService\", &SpaceService{})\n\t\/\/ 注册Account类型\n\tgoworld.RegisterEntity(\"Account\", &Account{})\n\t\/\/ 注册Monster类型\n\tgoworld.RegisterEntity(\"Monster\", &Monster{})\n\t\/\/ 注册Avatar类型，并定义属性\n\tgoworld.RegisterEntity(\"Player\", &Player{})\n\t\/\/ 运行游戏服务器\n\tgoworld.Run()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"os\"\n\t\"log\"\n\t\"net\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\t\"time\"\n)\n\n\/\/ Model\ntype Package struct {\n\tId bson.ObjectId  `bson:\"_id,omitempty\"`\n\tFullName      string\n\tDescription   string\n\tStarsCount    int\n\tForksCount    int\n\tLastUpdatedBy string\n}\n\nfunc main() {\n\n\ttlsConfig := &tls.Config{}\n\n\t\/\/ InsecureSkipVerify controls whether a client verifies the\n\t\/\/ server's certificate chain and host name.\n\t\/\/ If InsecureSkipVerify is true, TLS accepts any certificate\n\t\/\/ presented by the server and any host name in that certificate.\n\t\/\/ In this mode, TLS is susceptible to man-in-the-middle attacks.\n\t\/\/ This should be used only for testing.\n\ttlsConfig.InsecureSkipVerify = true\n\n\t\/\/ DialInfo holds options for establishing a session with a MongoDB cluster.\n\tdialInfo := &mgo.DialInfo{\n\t\tAddrs:    []string{\"golang-couch.documents.azure.com:10255\"}, \/\/ Get HOST + PORT\n\t\tTimeout:  60 * time.Second,\n\t\tDatabase: \"golang-couch\",                                                                             \/\/ It can be anything\n\t\tUsername: \"golang-couch\",                                                                             \/\/ Username\n\t\tPassword: \"Password from azure cosmos db connection string\", \/\/ PASSWORD\n\t}\n\n\tdialInfo.DialServer = func(serverAddress *mgo.ServerAddr) (net.Conn, error) {\n\t\tfmt.Println(serverAddress.String());\n\t\tconnection, err := tls.Dial(\"tcp\", serverAddress.String(), tlsConfig)\n\t\treturn connection, err\n\n\t}\n\n\t\/\/ Create a session which maintains a pool of socket connections\n\t\/\/ to our MongoDB.\n\tsession, err := mgo.DialWithInfo(dialInfo)\n\n\tif err != nil {\n\t\tfmt.Printf(\"Can't connect to mongo, go error %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tdefer session.Close()\n\n\t\/\/ SetSafe changes the session safety mode.\n\t\/\/ If the safe parameter is nil, the session is put in unsafe mode, and writes become fire-and-forget,\n\t\/\/ without error checking. The unsafe mode is faster since operations won't hold on waiting for a confirmation.\n\t\/\/ http:\/\/godoc.org\/labix.org\/v2\/mgo#Session.SetMode.\n\tsession.SetSafe(&mgo.Safe{})\n\n\t\/\/ get collection\n\tcollection := session.DB(\"golang-couch\").C(\"package\")\n\n\t\/\/ insert Document in collection\n\terr = collection.Insert(&Package{\n\t\tFullName:\"react\",\n\t\tDescription:\"A framework for building native apps with React.\",\n\t\tForksCount: 11392,\n\t\tStarsCount:48794,\n\t\tLastUpdatedBy:\"shergin\",\n\n\t})\n\n\tif err != nil {\n\t\tlog.Fatal(\"Problem inserting data: \", err)\n\t\treturn\n\t}\n\n\t\/\/ Get Document from collection\n\tresult := Package{}\n\terr = collection.Find(bson.M{\"fullname\": \"react\"}).One(&result)\n\tif err != nil {\n\t\tlog.Fatal(\"Error finding record: \", err)\n\t\treturn\n\t}\n\n\tfmt.Println(\"Description:\", result.Description)\n\n\t\/\/ update document\n\tupdateQuery := bson.M{\"_id\": result.Id}\n\tchange := bson.M{\"$set\": bson.M{\"fullname\": \"react-native\"}}\n\terr = collection.Update(updateQuery, change)\n\tif err != nil {\n\t\tlog.Fatal(\"Error updating record: \", err)\n\t\treturn\n\t}\n\n\t\/\/ delete document\n\terr = collection.Remove(updateQuery)\n\tif err != nil {\n\t\tlog.Fatal(\"Error deleting record: \", err)\n\t\treturn\n\t}\n}\n<commit_msg>Added model type<commit_after>### Azure Cosmos DB: Build a MongoDB API console app with Golang and the Azure\nportal\n\nAzure Cosmos DB is Microsoft’s globally distributed multi-model database\nservice. You can quickly create and query document, key\/value, and graph\ndatabases, all of which benefit from the global distribution and horizontal\nscale capabilities at the core of Azure Cosmos DB.\n\nThis quick-start demonstrates how to use an existing\n[MongoDB](https:\/\/docs.microsoft.com\/en-us\/azure\/documentdb\/documentdb-protocol-mongodb)\napp written in Golang and connect it to your Azure Cosmos DB database, which\nsupports MongoDB client connections.\n\nIn other words, your Golang application only knows that it’s connecting to a\ndatabase using MongoDB APIs. It is transparent to the application that the data\nis stored in Azure Cosmos DB.\n\nWe’ll cover:\n\n* Prerequisites for this tutorial\n* Creating and connecting to an Azure Cosmos DB account\n* Setting up your application\n* Connect to an Azure Cosmos DB account\n* CRUD Operations\n\n### Prerequisites for the Golang tutorial\n\n1.  Basic knowledge of [GO ](https:\/\/golang.org\/)language\n1.  Azure subscription. (If you don’t have an Azure subscription, create a [free\naccount](https:\/\/azure.microsoft.com\/free\/?WT.mc_id=A261C142F) before you\nbegin.)\n1.  IDE — [Gogland](https:\/\/www.jetbrains.com\/go\/) by Jetbrains or [Visual Studio\nCode](https:\/\/code.visualstudio.com\/) by Mircosoft or [Atom](https:\/\/atom.io\/)\n\n### Creating and connecting to an Azure Cosmos DB account\n\n1.  In a new window, sign in to the [Azure portal](https:\/\/portal.azure.com\/).\n1.  In the left menu, click **New**, click **Databases**, and then click **Azure\nCosmos DB**.\n\n![](https:\/\/cdn-images-1.medium.com\/max\/800\/1*e-QMvThW-2QZ3hEH3VvUQQ.png)\n\n3. In the **New account** blade, specify the desired configuration for the Azure\nCosmos DB account.\n\nWith Azure Cosmos DB, you can choose one of four programming models: Gremlin\n(graph), MongoDB, SQL (DocumentDB), and Table (key-value).\n\nIn this quick start we’ll be programming against the MongoDB API so you’ll\nchoose **MongoDB** as you fill out the form. But if you have graph data for a\nsocial media mes New app, document data from a catalog app, or key\/value (table)\ndata, realize that Azure Cosmos DB can provide a highly available,\nglobally-distributed database service platform for all your mission-critical\napplications.\n\nFill out the New account blade using the information in the screenshot as a\nguide . You will choose unique values as you set up your account so your values\nwill not match the screenshot exactly\n\n![](https:\/\/cdn-images-1.medium.com\/max\/800\/1*XdFlpeNKLe7o3FOtCZ17AQ.png)\n<span class=\"figcaption_hack\">Create Azure Cosmos DB Account<\/span>\n\n4. Click **Create** to create the account.\n\n5. On the toolbar, click **Notifications** to monitor the deployment process.\n\n![](https:\/\/cdn-images-1.medium.com\/max\/800\/1*WTGVkPwkSTxjUzKm2u09Eg.png)\n<span class=\"figcaption_hack\">Check Progress of Azure Cosmos DB Deployment<\/span>\n\n6. Click on **golang-couch** resources.\n\n7. Get connection string information which will be required by client\napplications.\n\n![](https:\/\/cdn-images-1.medium.com\/max\/800\/1*XoslPMsWsv5vqK2vhYAJPw.png)\n<span class=\"figcaption_hack\">Connection information of MongoDB<\/span>\n\n### Setting up your application\n\nIt’s time to make our hands dirty. Open your favorite editor (Gogland, VS Code\nor Atom). For this article, I will use Gogland editor.\n\n1.  Create folder CosmosDBAcces folder inside GOROOT\\src folder\n1.  Run below command to get mgo package\n\n    go get gopkg.in\/mgo.v2\n\n### Connect to an Azure Cosmos DB account\n\n[mgo](http:\/\/labix.org\/mgo) (pronounced as *mango*) is a\n[MongoDB](http:\/\/www.mongodb.org\/) driver for the [Go\nlanguage](http:\/\/golang.org\/) that implements a rich and well tested selection\nof features under a very simple API following standard Go idioms.\n\nAzure Cosmos DB uses latest version of MongoDB v3.2.0. with SSL enabled.\n\n![](https:\/\/cdn-images-1.medium.com\/max\/800\/1*OJwDs_lG45z_K3rzw2_RuQ.png)\n\nOfficially, mgo does not support MongoDB 3.2 version. There is solution to\nignore server certificate validation by mgo. Please refer blog [Connect to\nMongoDB 3.2 on Compose from\nGolang](https:\/\/www.compose.com\/articles\/connect-to-mongo-3-2-on-compose-from-golang\/)\nby [Hays Hutton](ps:\/\/www.compose.com\/articles\/author\/hays-hutton\/)\n\nTo get started we have to configure transport layer security (tls). We have to\nmake sure that client Certificate Authority ignore SSL validation. While this\ndoes open up some attack vectors, it is vastly superior to no SSL. Here are the\ncomments directly from the source code of the tls.Config struct for the\nparticular boolean we need to set:\n\n\nThe following code snippet to connect with MongoDB with GO app. DialInfo holds\noptions for establishing a session with a MongoDB cluster. \n\n    tlsConfig := &tls.Config{}\n\n    \/\/ InsecureSkipVerify controls whether a client verifies the\n    \/\/ server's certificate chain and host name.\n    \/\/ If InsecureSkipVerify is true, TLS accepts any certificate\n    \/\/ presented by the server and any host name in that certificate.\n    \/\/ In this mode, TLS is susceptible to man-in-the-middle attacks.\n    \/\/ This should be used only for testing.\n    tlsConfig.InsecureSkipVerify = true\n\n    \/\/ DialInfo holds options for establishing a session with a MongoDB cluster.\n    dialInfo := &mgo.DialInfo{\n        Addrs:    []string{\"golang-couch.documents.azure.com:10255\"}, \/\/ Get HOST + PORT\n        Timeout:  60 * time.Second,\n        Database: \"golang-couch\", \/\/ It can be anything\n        Username: \"golang-couch\", \/\/ Username\n        Password: \"Password from MongoDB Setting in azure portal\", \/\/ PASSWORD\n    }\n\n    dialInfo.DialServer = func(serverAddress *mgo.ServerAddr) (net.Conn, error) {\n        fmt.Println(serverAddress.String());\n        connection, err := tls.Dial(\"tcp\", serverAddress.String(), tlsConfig)\n        return connection, err\n\n    }\n\n    \/\/ Create a session which maintains a pool of socket connections\n    \/\/ to our MongoDB.\n    session, err := mgo.DialWithInfo(dialInfo)\n\n    if err != nil {\n        fmt.Printf(\"Can't connect to mongo, go error %v\\n\", err)\n        os.Exit(1)\n    }\n\n    defer session.Close()\n\n    \/\/ SetSafe changes the session safety mode.\n    \/\/ If the safe parameter is nil, the session is put in unsafe mode, \/\/ and writes become fire-and-forget,\n    \/\/ without error checking. The unsafe mode is faster since operations won't hold on waiting for a confirmation.\n    \/\/ \n    .\n    session.SetSafe(&mgo.Safe{})\n\n**mgo.Dial()** method is used when there is no SSL connection and for SSL\nconnection **mgo.DialWithInfo()** method is required. \n\nInstance of **DialWIthInfo{}** object will be used to create session object.\nOnce session is established, we can access collection by following code snippet\n\n    collection := session.DB(“golang-couch”).C(“package”)\n\n### CRUD Operations\n\n#### 1. Create Document\n\n    \/\/ Model\n    type Package struct {\n    \tId bson.ObjectId  `bson:\"_id,omitempty\"`\n    \tFullName      string\n    \tDescription   string\n    \tStarsCount    int\n    \tForksCount    int\n    \tLastUpdatedBy string\n    }\n\n    \/\/ insert Document in collection\n    err = collection.Insert(&Package{\n        FullName:\"react\",\n        Description:\"A framework for building native apps with React.\",\n        ForksCount: 11392,\n        StarsCount:48794,\n        LastUpdatedBy:\"shergin\",\n\n    })\n\n    if err != nil {\n        log.Fatal(\"Problem inserting data: \", err)\n        return\n    }\n\n#### 2. Query\/Read Document\n\nAzure Cosmos DB supports rich queries against JSON documents stored in each\ncollection. The following sample code shows a query that you can run against the\ndocuments in your collection.\n\n    \/\/ Get Document from collection\n    result := Package{}\n    err = collection.Find(bson.M{\"fullname\": \"react\"}).One(&result)\n    if err != nil {\n        log.Fatal(\"Error finding record: \", err)\n        return\n    }\n\n    fmt.Println(\"Description:\", result.Description)\n\n#### 3. Update Document\n\n    \/\/ update document\n    updateQuery := bson.M{\"_id\": result.Id}\n    change := bson.M{\"$set\": bson.M{\"fullname\": \"react-native\"}}\n    err = collection.Update(updateQuery, change)\n    if err != nil {\n        log.Fatal(\"Error updating record: \", err)\n        return\n    }\n\n#### 4. Delete Document\n\nAzure Cosmos DB supports deleting JSON documents.\n\n    \/\/ delete document\n    query := bson.M{\"_id\": result.Id}\n    err = collection.Remove(query)\n    if err != nil {\n        log.Fatal(\"Error deleting record: \", err)\n        return\n    }\n\n### Get the complete Golang tutorial solution\n\nPlease have a look at the entire source code at\n[GitHub](https:\/\/github.com\/Golang-Coach\/Lessons\/tree\/master\/CosmosDBAccess).\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"net\"\n  \"io\"\n  \"time\"\n  \"log\"\n  \"os\"\n\t\"encoding\/binary\"\n\t\"code.google.com\/p\/gopacket\/layers\"\n\t\"code.google.com\/p\/gopacket\"\n\t\"flag\"\n)\nvar (\n  NETFLOW_V5_HEADER_SIZE int = 24;\n  NETFLOW_V5_RECORD_SIZE int = 48;\n  PROTOCOL_TCP uint8 = 6\n  PROTOCOL_UDP uint8 = 17\n  NETFLOW_PORT int = 2055\n  NANOSECOND int64 = 1000000000\n  Trace *log.Logger\n  Info *log.Logger\n  Warning *log.Logger\n  Error *log.Logger\n)\n\nfunc construct_ethernet() *layers.Ethernet {\n\treturn &layers.Ethernet{}\n}\n\nfunc construct_ip(srcaddr string, dstaddr string) *layers.IPv4 {\n\treturn &layers.IPv4{\n\t\tSrcIP: net.ParseIP(srcaddr),\n\t\tDstIP: net.ParseIP(dstaddr),\n\t}\n}\n\nfunc construct_udp() *layers.UDP {\n\treturn &layers.UDP{}\n}\n\ntype NETFLOW_v5_header struct {\n\tVersion\t\t\tuint16\n\tCount\t\t\tuint16\n\tSys_uptime\t\tuint32\n\tUnix_secs\t\tuint32\n\tUnix_nsecs\t\tuint32\n\tFlow_sequence\t\tuint32\n\tEngine_type\t\tuint8 \n\tEngine_id\t\tuint8 \n\tSampling_interval\tuint16 \n}\n\ntype NETFLOW_v5_record struct {\n\tSrcaddr\t\tuint32\n\tDstaddr\t\tuint32\n\tNexthop\t\tuint32\n\tInput\t\tuint16\n\tOutput\t\tuint16\n\tDPkts\t\tuint32\n\tDOctets\t\tuint32\n\tFirst\t\tuint32\n\tLast\t\tuint32\n\tSrcport\t\tuint16\n\tDstport\t\tuint16\n\tPad1\t\tuint8\n\tTcp_flags\tuint8\n\tProt\t\tuint8\n\tTos\t\tuint8\n\tSrc_as  \tuint16\n\tDst_as  \tuint16\n\tSrc_mask \tuint8 \n\tDst_mask\tuint8\n\tPad2\t\tuint16\n}\n\n\nfunc v4_to_uint32(addr net.IP) uint32 {\n\tvar ret uint32;\n\tret |= uint32(addr[0])\n\tret |= uint32(addr[1]) << 8\n\tret |= uint32(addr[2]) << 16\n\tret |= uint32(addr[3]) << 24\n\treturn ret\n}\n\nfunc construct_v5_header(count uint16, sampling uint16) NETFLOW_v5_header {\n\theader := NETFLOW_v5_header{\n\t\tVersion:\t\t5,\t\t\/\/Netflow v5\n\t\tCount:\t\t\tcount,\t\t\/\/Number of records in this packet\n\t\tSys_uptime:\t\t0,\t\t\/\/Ignore for now\n\t\tUnix_secs:\t\t0,\t\t\/\/Ignore for now\n\t\tUnix_nsecs:\t\t0,\t\t\/\/Ignore for now\n\t\tFlow_sequence:\t\t0,\t\t\/\/Ignore for now. Eventually want to track sequence numbers\n\t\tEngine_type:\t\t0,\t\t\/\/Ignore for now\n\t\tEngine_id:\t\t0,\t\t\/\/Ignore for now\n\t\tSampling_interval:\tsampling,\t\/\/TODO\n\t}\n\treturn header\n}\n\nfunc insert_v5_header(header NETFLOW_v5_header, buf []byte, offset int) int {\n        binary.BigEndian.PutUint16(buf[offset:], header.Version)\n        binary.BigEndian.PutUint16(buf[offset + 2:], header.Count)\n        binary.BigEndian.PutUint32(buf[offset + 4:], header.Sys_uptime)\n        binary.BigEndian.PutUint32(buf[offset + 8:], header.Unix_secs)\n        binary.BigEndian.PutUint32(buf[offset + 12:], header.Unix_nsecs)\n        binary.BigEndian.PutUint32(buf[offset + 16:], header.Flow_sequence)\n        buf[offset + 20] = header.Engine_type\n        buf[offset + 21] = header.Engine_id\n        binary.BigEndian.PutUint16(buf[offset + 22:], header.Sampling_interval)\n\n\treturn NETFLOW_V5_HEADER_SIZE\n}\n\nfunc construct_v5_record(srcaddr string, dstaddr string, \n\tpkts uint32, l3_bytes uint32, srcport uint16, dstport uint16,\n\tprotocol uint8, src_as uint16, dst_as uint16) NETFLOW_v5_record {\n\n\tsrcip := v4_to_uint32(net.ParseIP(srcaddr))\n\tdstip := v4_to_uint32(net.ParseIP(dstaddr))\n\n\trecord := NETFLOW_v5_record {\n\t\tSrcaddr:\t\tsrcip,\n\t\tDstaddr:\t\tdstip,\n\t\tNexthop:\t\t0,\t\t\t\t\/\/Ignore for now\n\t\tInput:\t\t\t0,\t\t\t\t\/\/Do something with this later\n\t\tOutput:\t\t\t0,\t\t\t\t\/\/^^\n\t\tDPkts:\t\t\tpkts,\n\t\tDOctets:\t\tl3_bytes,\n\t\tFirst:\t\t\t0,\t\t\t\t\/\/Ignore for now\n\t\tLast:\t\t\t0,\t\t\t\t\/\/Ignore for now\n\t\tSrcport:\t\tsrcport,\n\t\tDstport:\t\tdstport,\n\t\tPad1:\t\t\t0,\t\n\t\tTcp_flags:\t\t0,\t\t\t\t\/\/Something with this later\n\t\tProt:\t\t\tPROTOCOL_TCP,\n\t\tTos:\t\t\t0,\n\t\tSrc_as:\t\t\tsrc_as,\n\t\tDst_as:\t\t\tdst_as,\n\t\tSrc_mask:\t\t0,\n\t\tDst_mask:\t\t0,\n\t}\n\treturn record\n}\n\nfunc insert_v5_record(record NETFLOW_v5_record, buf []byte, offset int) int {\n        binary.BigEndian.PutUint32(buf[offset:], record.Srcaddr)\n        binary.BigEndian.PutUint32(buf[offset + 4:], record.Dstaddr)\n        binary.BigEndian.PutUint32(buf[offset + 8:], record.Nexthop)\n        binary.BigEndian.PutUint16(buf[offset + 12:], record.Input)\n        binary.BigEndian.PutUint16(buf[offset + 14:], record.Output)\n        binary.BigEndian.PutUint32(buf[offset + 16:], record.DPkts)\n        binary.BigEndian.PutUint32(buf[offset + 20:], record.DOctets)\n        binary.BigEndian.PutUint32(buf[offset + 24:], record.First)\n        binary.BigEndian.PutUint32(buf[offset + 28:], record.Last)\n        binary.BigEndian.PutUint16(buf[offset + 32:], record.Srcport)\n        binary.BigEndian.PutUint16(buf[offset + 34:], record.Dstport)\n        buf[offset + 36] = record.Pad1\n        buf[offset + 37] = record.Tcp_flags\n        buf[offset + 38] = record.Prot\n        buf[offset + 39] = record.Tos\n        binary.BigEndian.PutUint16(buf[offset + 40:], record.Src_as)\n        binary.BigEndian.PutUint16(buf[offset + 42:], record.Dst_as)\n        buf[offset + 44] = record.Src_mask\n        buf[offset + 45] = record.Dst_mask\n        binary.BigEndian.PutUint16(buf[offset + 46:], record.Pad2)\n\treturn NETFLOW_V5_RECORD_SIZE;\n}\n\nfunc construct_payload(num_records uint16) gopacket.Payload {\n\n\tbuf := gopacket.NewSerializeBuffer()\n\/\/        payload := buf.Bytes()\n        \/\/Allocate the space we will need for the header\n        bytes,err := buf.PrependBytes(NETFLOW_V5_HEADER_SIZE + NETFLOW_V5_RECORD_SIZE*int(num_records))\n\tif err != nil {\n\t\treturn nil\n\t} \n\n\toffset := 0\n\n\theader := construct_v5_header(num_records, 1000)\n\toffset += insert_v5_header(header, bytes, offset)\n\n\tvar record NETFLOW_v5_record;\n\tfor i := 0; i < int(num_records); i++ {\n\t\trecord = construct_v5_record(\"1.1.1.1\", \"2.2.2.2\", 5, 256, 80, 5050, 6, 237, 237)\n\t\tinsert_v5_record(record, bytes, offset)\n\t\t\n\t}\n        \n\treturn gopacket.Payload(bytes)\n}\n\nfunc chk(err error){\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc init_connection(addr net.IP) *net.UDPConn {\n\tconn, err := net.ListenUDP(\"udp\", &net.UDPAddr{IP: addr, Port: 0})\n\tchk(err)\n\treturn conn\n}\n\nfunc send_packet(conn *net.UDPConn, addr net.IP, port int, pkt []byte) {\n\t_, err := conn.WriteToUDP(pkt, &net.UDPAddr{IP: addr, Port: port})\n\tchk(err)\n}\n\n\nfunc Init (\n  traceHandle io.Writer,\n  infoHandle io.Writer,\n  warningHandle io.Writer,\n  errorHandle io.Writer) {\n\n  Trace = log.New(traceHandle, \"TRACE: \", \n    log.Ldate|log.Ltime|log.Lshortfile)\n\n  Info = log.New(infoHandle,\n    \"INFO: \",\n    log.Ldate|log.Ltime|log.Lshortfile)\n\n  Warning = log.New(warningHandle,\n    \"WARNING: \",\n    log.Ldate|log.Ltime|log.Lshortfile)\n\n  Error = log.New(errorHandle,\n    \"ERROR: \",\n    log.Ldate|log.Ltime|log.Lshortfile)\n}\n\nfunc main() {\n  Init(os.Stdout, os.Stdout, os.Stdout, os.Stderr)\n\n\tdst_ip := flag.String(\"dst\", \"127.0.0.1\", \"Destination IP to send the spoofed netflow\")\n\tdst_port := flag.Int(\"port\", NETFLOW_PORT, \"Destination Port to send the spoofed netflow\")\n\trate := flag.Int64(\"rate\", 1, \"Rate in Packets\/s\")\n  runtime := flag.Int64(\"time\", 10, \"Time in seconds to send packets\")\n  flows_per_packet := flag.Uint(\"fpp\", 1, \"flows per packet, max of 30\")\n  flag.Parse()\n\n\tdst_addr := net.ParseIP(*dst_ip)\n\n\tbuf := gopacket.NewSerializeBuffer()\n\topts := gopacket.SerializeOptions{}\n\t\n\tl2 := construct_ethernet()\n\tl3 := construct_ip(\"1.2.3.4\", \"5.6.7.8\")\n\tl4 := construct_udp()\n\n\tpayload := construct_payload(uint16(*flows_per_packet))\n\t\/\/LayerCake\n\tgopacket.SerializeLayers(buf, opts,\n\t\tl2, \n\t\tl3,\n\t\tl4,\n\t\tpayload)\n\tpacketData := buf.Bytes()\n  \n\t\/\/Send the packet to lo\n\tconn := init_connection(dst_addr)\n\n  \/\/Debug timing\n  t0 := time.Now()\n\n  \/\/Simple way for now. Token based approach later\n  throttle := time.Tick(time.Duration(*rate)*time.Second)\n  for i := 0; int64(i) < (*rate)*(*runtime); i++ {\n    <-throttle\n    go send_packet(conn, dst_addr, *dst_port, packetData)\n  }\n\n  t1 := time.Now()\n  Trace.Printf(\"Sent %v packets in %vs\\n\", (*rate)*(*runtime), t1.Sub(t0))\n\tInfo.Println(\"fin\")\n}\n<commit_msg>fix rate limiting<commit_after>package main\n\nimport (\n\t\"net\"\n  \"io\"\n  \"time\"\n  \"log\"\n  \"os\"\n\t\"encoding\/binary\"\n\t\"code.google.com\/p\/gopacket\/layers\"\n\t\"code.google.com\/p\/gopacket\"\n\t\"flag\"\n)\nvar (\n  NETFLOW_V5_HEADER_SIZE int = 24;\n  NETFLOW_V5_RECORD_SIZE int = 48;\n  PROTOCOL_TCP uint8 = 6\n  PROTOCOL_UDP uint8 = 17\n  NETFLOW_PORT int = 2055\n  NANOSECOND int64 = 1000000000\n  Trace *log.Logger\n  Info *log.Logger\n  Warning *log.Logger\n  Error *log.Logger\n)\n\nfunc construct_ethernet() *layers.Ethernet {\n\treturn &layers.Ethernet{}\n}\n\nfunc construct_ip(srcaddr string, dstaddr string) *layers.IPv4 {\n\treturn &layers.IPv4{\n\t\tSrcIP: net.ParseIP(srcaddr),\n\t\tDstIP: net.ParseIP(dstaddr),\n\t}\n}\n\nfunc construct_udp() *layers.UDP {\n\treturn &layers.UDP{}\n}\n\ntype NETFLOW_v5_header struct {\n\tVersion\t\t\tuint16\n\tCount\t\t\tuint16\n\tSys_uptime\t\tuint32\n\tUnix_secs\t\tuint32\n\tUnix_nsecs\t\tuint32\n\tFlow_sequence\t\tuint32\n\tEngine_type\t\tuint8 \n\tEngine_id\t\tuint8 \n\tSampling_interval\tuint16 \n}\n\ntype NETFLOW_v5_record struct {\n\tSrcaddr\t\tuint32\n\tDstaddr\t\tuint32\n\tNexthop\t\tuint32\n\tInput\t\tuint16\n\tOutput\t\tuint16\n\tDPkts\t\tuint32\n\tDOctets\t\tuint32\n\tFirst\t\tuint32\n\tLast\t\tuint32\n\tSrcport\t\tuint16\n\tDstport\t\tuint16\n\tPad1\t\tuint8\n\tTcp_flags\tuint8\n\tProt\t\tuint8\n\tTos\t\tuint8\n\tSrc_as  \tuint16\n\tDst_as  \tuint16\n\tSrc_mask \tuint8 \n\tDst_mask\tuint8\n\tPad2\t\tuint16\n}\n\n\nfunc v4_to_uint32(addr net.IP) uint32 {\n\tvar ret uint32;\n\tret |= uint32(addr[0])\n\tret |= uint32(addr[1]) << 8\n\tret |= uint32(addr[2]) << 16\n\tret |= uint32(addr[3]) << 24\n\treturn ret\n}\n\nfunc construct_v5_header(count uint16, sampling uint16) NETFLOW_v5_header {\n\theader := NETFLOW_v5_header{\n\t\tVersion:\t\t5,\t\t\/\/Netflow v5\n\t\tCount:\t\t\tcount,\t\t\/\/Number of records in this packet\n\t\tSys_uptime:\t\t0,\t\t\/\/Ignore for now\n\t\tUnix_secs:\t\t0,\t\t\/\/Ignore for now\n\t\tUnix_nsecs:\t\t0,\t\t\/\/Ignore for now\n\t\tFlow_sequence:\t\t0,\t\t\/\/Ignore for now. Eventually want to track sequence numbers\n\t\tEngine_type:\t\t0,\t\t\/\/Ignore for now\n\t\tEngine_id:\t\t0,\t\t\/\/Ignore for now\n\t\tSampling_interval:\tsampling,\t\/\/TODO\n\t}\n\treturn header\n}\n\nfunc insert_v5_header(header NETFLOW_v5_header, buf []byte, offset int) int {\n        binary.BigEndian.PutUint16(buf[offset:], header.Version)\n        binary.BigEndian.PutUint16(buf[offset + 2:], header.Count)\n        binary.BigEndian.PutUint32(buf[offset + 4:], header.Sys_uptime)\n        binary.BigEndian.PutUint32(buf[offset + 8:], header.Unix_secs)\n        binary.BigEndian.PutUint32(buf[offset + 12:], header.Unix_nsecs)\n        binary.BigEndian.PutUint32(buf[offset + 16:], header.Flow_sequence)\n        buf[offset + 20] = header.Engine_type\n        buf[offset + 21] = header.Engine_id\n        binary.BigEndian.PutUint16(buf[offset + 22:], header.Sampling_interval)\n\n\treturn NETFLOW_V5_HEADER_SIZE\n}\n\nfunc construct_v5_record(srcaddr string, dstaddr string, \n\tpkts uint32, l3_bytes uint32, srcport uint16, dstport uint16,\n\tprotocol uint8, src_as uint16, dst_as uint16) NETFLOW_v5_record {\n\n\tsrcip := v4_to_uint32(net.ParseIP(srcaddr))\n\tdstip := v4_to_uint32(net.ParseIP(dstaddr))\n\n\trecord := NETFLOW_v5_record {\n\t\tSrcaddr:\t\tsrcip,\n\t\tDstaddr:\t\tdstip,\n\t\tNexthop:\t\t0,\t\t\t\t\/\/Ignore for now\n\t\tInput:\t\t\t0,\t\t\t\t\/\/Do something with this later\n\t\tOutput:\t\t\t0,\t\t\t\t\/\/^^\n\t\tDPkts:\t\t\tpkts,\n\t\tDOctets:\t\tl3_bytes,\n\t\tFirst:\t\t\t0,\t\t\t\t\/\/Ignore for now\n\t\tLast:\t\t\t0,\t\t\t\t\/\/Ignore for now\n\t\tSrcport:\t\tsrcport,\n\t\tDstport:\t\tdstport,\n\t\tPad1:\t\t\t0,\t\n\t\tTcp_flags:\t\t0,\t\t\t\t\/\/Something with this later\n\t\tProt:\t\t\tPROTOCOL_TCP,\n\t\tTos:\t\t\t0,\n\t\tSrc_as:\t\t\tsrc_as,\n\t\tDst_as:\t\t\tdst_as,\n\t\tSrc_mask:\t\t0,\n\t\tDst_mask:\t\t0,\n\t}\n\treturn record\n}\n\nfunc insert_v5_record(record NETFLOW_v5_record, buf []byte, offset int) int {\n        binary.BigEndian.PutUint32(buf[offset:], record.Srcaddr)\n        binary.BigEndian.PutUint32(buf[offset + 4:], record.Dstaddr)\n        binary.BigEndian.PutUint32(buf[offset + 8:], record.Nexthop)\n        binary.BigEndian.PutUint16(buf[offset + 12:], record.Input)\n        binary.BigEndian.PutUint16(buf[offset + 14:], record.Output)\n        binary.BigEndian.PutUint32(buf[offset + 16:], record.DPkts)\n        binary.BigEndian.PutUint32(buf[offset + 20:], record.DOctets)\n        binary.BigEndian.PutUint32(buf[offset + 24:], record.First)\n        binary.BigEndian.PutUint32(buf[offset + 28:], record.Last)\n        binary.BigEndian.PutUint16(buf[offset + 32:], record.Srcport)\n        binary.BigEndian.PutUint16(buf[offset + 34:], record.Dstport)\n        buf[offset + 36] = record.Pad1\n        buf[offset + 37] = record.Tcp_flags\n        buf[offset + 38] = record.Prot\n        buf[offset + 39] = record.Tos\n        binary.BigEndian.PutUint16(buf[offset + 40:], record.Src_as)\n        binary.BigEndian.PutUint16(buf[offset + 42:], record.Dst_as)\n        buf[offset + 44] = record.Src_mask\n        buf[offset + 45] = record.Dst_mask\n        binary.BigEndian.PutUint16(buf[offset + 46:], record.Pad2)\n\treturn NETFLOW_V5_RECORD_SIZE;\n}\n\nfunc construct_payload(num_records uint16) gopacket.Payload {\n\n\tbuf := gopacket.NewSerializeBuffer()\n\/\/        payload := buf.Bytes()\n        \/\/Allocate the space we will need for the header\n        bytes,err := buf.PrependBytes(NETFLOW_V5_HEADER_SIZE + NETFLOW_V5_RECORD_SIZE*int(num_records))\n\tif err != nil {\n\t\treturn nil\n\t} \n\n\toffset := 0\n\n\theader := construct_v5_header(num_records, 1000)\n\toffset += insert_v5_header(header, bytes, offset)\n\n\tvar record NETFLOW_v5_record;\n\tfor i := 0; i < int(num_records); i++ {\n\t\trecord = construct_v5_record(\"1.1.1.1\", \"2.2.2.2\", 5, 256, 80, 5050, 6, 237, 237)\n\t\tinsert_v5_record(record, bytes, offset)\n\t\t\n\t}\n        \n\treturn gopacket.Payload(bytes)\n}\n\nfunc chk(err error){\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc init_connection(addr net.IP) *net.UDPConn {\n\tconn, err := net.ListenUDP(\"udp\", &net.UDPAddr{IP: addr, Port: 0})\n\tchk(err)\n\treturn conn\n}\n\nfunc send_packet(conn *net.UDPConn, addr net.IP, port int, pkt []byte) {\n\t_, err := conn.WriteToUDP(pkt, &net.UDPAddr{IP: addr, Port: port})\n\tchk(err)\n}\n\n\nfunc Init (\n  traceHandle io.Writer,\n  infoHandle io.Writer,\n  warningHandle io.Writer,\n  errorHandle io.Writer) {\n\n  Trace = log.New(traceHandle, \"TRACE: \", \n    log.Ldate|log.Ltime|log.Lshortfile)\n\n  Info = log.New(infoHandle,\n    \"INFO: \",\n    log.Ldate|log.Ltime|log.Lshortfile)\n\n  Warning = log.New(warningHandle,\n    \"WARNING: \",\n    log.Ldate|log.Ltime|log.Lshortfile)\n\n  Error = log.New(errorHandle,\n    \"ERROR: \",\n    log.Ldate|log.Ltime|log.Lshortfile)\n}\n\nfunc main() {\n  Init(os.Stdout, os.Stdout, os.Stdout, os.Stderr)\n\n\tdst_ip := flag.String(\"dst\", \"127.0.0.1\", \"Destination IP to send the spoofed netflow\")\n\tdst_port := flag.Int(\"port\", NETFLOW_PORT, \"Destination Port to send the spoofed netflow\")\n\trate := flag.Int64(\"rate\", 1, \"Rate in Packets\/s\")\n  runtime := flag.Int64(\"time\", 10, \"Time in seconds to send packets\")\n  flows_per_packet := flag.Uint(\"fpp\", 1, \"flows per packet, max of 30\")\n  flag.Parse()\n\n\tdst_addr := net.ParseIP(*dst_ip)\n\n\tbuf := gopacket.NewSerializeBuffer()\n\topts := gopacket.SerializeOptions{}\n\t\n\tl2 := construct_ethernet()\n\tl3 := construct_ip(\"1.2.3.4\", \"5.6.7.8\")\n\tl4 := construct_udp()\n\n\tpayload := construct_payload(uint16(*flows_per_packet))\n\t\/\/LayerCake\n\tgopacket.SerializeLayers(buf, opts,\n\t\tl2, \n\t\tl3,\n\t\tl4,\n\t\tpayload)\n\tpacketData := buf.Bytes()\n  \n\t\/\/Send the packet to lo\n\tconn := init_connection(dst_addr)\n\n  \/\/Debug timing\n  t0 := time.Now()\n\n  \/\/Simple way for now. Token based approach later\n  throttle := time.Tick(1e9 \/ time.Duration(*rate))\n  for i := 0; int64(i) < (*rate)*(*runtime); i++ {\n    <-throttle\n    go send_packet(conn, dst_addr, *dst_port, packetData)\n  }\n\n  t1 := time.Now()\n  Trace.Printf(\"Sent %v packets in %vs\\n\", (*rate)*(*runtime), t1.Sub(t0))\n\tInfo.Println(\"fin\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package qt_recipe\n\nimport (\n\t\"encoding\/csv\"\n\t\"encoding\/json\"\n\trice \"github.com\/GeertJohan\/go.rice\"\n\t\"github.com\/pkg\/profile\"\n\tmo_path2 \"github.com\/watermint\/toolbox\/domain\/common\/model\/mo_path\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/api\/dbx_context\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/api\/dbx_context_impl\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/model\/mo_path\"\n\t\"github.com\/watermint\/toolbox\/essentials\/go\/es_project\"\n\t\"github.com\/watermint\/toolbox\/essentials\/go\/es_resource\"\n\t\"github.com\/watermint\/toolbox\/essentials\/io\/es_stdout\"\n\t\"github.com\/watermint\/toolbox\/essentials\/log\/es_log\"\n\t\"github.com\/watermint\/toolbox\/essentials\/log\/stats\/es_memory\"\n\t\"github.com\/watermint\/toolbox\/essentials\/log\/wrapper\/lgw_golog\"\n\t\"github.com\/watermint\/toolbox\/essentials\/terminal\/es_dialogue\"\n\t\"github.com\/watermint\/toolbox\/infra\/app\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_budget\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_control\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_exit\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_job_impl\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_opt\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_resource\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_workspace\"\n\t\"github.com\/watermint\/toolbox\/infra\/network\/nw_ratelimit\"\n\t\"github.com\/watermint\/toolbox\/infra\/network\/nw_replay\"\n\t\"github.com\/watermint\/toolbox\/infra\/recipe\/rc_recipe\"\n\t\"github.com\/watermint\/toolbox\/infra\/recipe\/rc_spec\"\n\t\"github.com\/watermint\/toolbox\/infra\/ui\/app_msg_container_impl\"\n\t\"github.com\/watermint\/toolbox\/infra\/ui\/app_ui\"\n\t\"github.com\/watermint\/toolbox\/quality\/infra\/qt_errors\"\n\t\"github.com\/watermint\/toolbox\/quality\/infra\/qt_file\"\n\t\"github.com\/watermint\/toolbox\/quality\/infra\/qt_secure\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n)\n\nconst (\n\tTestTeamFolderName = \"watermint-toolbox-test\"\n)\n\nfunc NewTestDropboxFolderPath(rel ...string) mo_path.DropboxPath {\n\treturn mo_path.NewDropboxPath(\"\/\" + TestTeamFolderName).ChildPath(rel...)\n}\n\nfunc MustMakeTestFolder(ctl app_control.Control, name string, withContent bool) (path string) {\n\tpath, err := qt_file.MakeTestFolder(name, withContent)\n\tif err != nil {\n\t\tctl.Log().Error(\"Unable to create test folder\", es_log.Error(err))\n\t\tapp_exit.Abort(app_exit.FailureGeneral)\n\t}\n\treturn path\n}\n\nfunc NewTestFileSystemFolderPath(c app_control.Control, name string) mo_path2.FileSystemPath {\n\treturn mo_path2.NewFileSystemPath(MustMakeTestFolder(c, name, true))\n}\n\nfunc NewTestExistingFileSystemFolderPath(c app_control.Control, name string) mo_path2.ExistingFileSystemPath {\n\treturn mo_path2.NewExistingFileSystemPath(MustMakeTestFolder(c, name, true))\n}\n\nfunc resBundle() es_resource.Bundle {\n\t_, err := rice.FindBox(\"..\/..\/..\/resources\/messages\")\n\tif err == nil {\n\t\treturn es_resource.New(\n\t\t\trice.MustFindBox(\"..\/..\/..\/resources\/templates\"),\n\t\t\trice.MustFindBox(\"..\/..\/..\/resources\/messages\"),\n\t\t\trice.MustFindBox(\"..\/..\/..\/resources\/web\"),\n\t\t\trice.MustFindBox(\"..\/..\/..\/resources\/keys\"),\n\t\t\trice.MustFindBox(\"..\/..\/..\/resources\/images\"),\n\t\t\trice.MustFindBox(\"..\/..\/..\/resources\/data\"),\n\t\t)\n\t} else {\n\t\t\/\/ In case the test run from the project root\n\t\treturn es_resource.New(\n\t\t\trice.MustFindBox(\"resources\/templates\"),\n\t\t\trice.MustFindBox(\"resources\/messages\"),\n\t\t\trice.MustFindBox(\"resources\/web\"),\n\t\t\trice.MustFindBox(\"resources\/keys\"),\n\t\t\trice.MustFindBox(\"resources\/images\"),\n\t\t\trice.MustFindBox(\"resources\/data\"),\n\t\t)\n\t}\n}\n\nfunc findTestFolder() string {\n\tl := es_log.Default()\n\n\troot, err := es_project.DetectRepositoryRoot()\n\tif err != nil {\n\t\tl.Error(\"Test path not found\")\n\t\tpanic(err)\n\t}\n\treturn filepath.Join(root, \"test\")\n}\n\nfunc loadReplay(name string) (rr []nw_replay.Response, err error) {\n\tl := es_log.Default().With(es_log.String(\"name\", name))\n\ttp := findTestFolder()\n\trp := filepath.Join(tp, \"replay\", name)\n\n\tl.Debug(\"Loading replay\", es_log.String(\"path\", rp))\n\tb, err := ioutil.ReadFile(rp)\n\tif err != nil {\n\t\tl.Debug(\"Unable to load\", es_log.Error(err))\n\t\treturn nil, err\n\t}\n\n\tif err := json.Unmarshal(b, &rr); err != nil {\n\t\tl.Debug(\"Unable to unmarshal\", es_log.Error(err))\n\t\treturn nil, err\n\t}\n\n\tl.Debug(\"Replay loaded\", es_log.Int(\"numRecords\", len(rr)))\n\treturn rr, nil\n}\n\nfunc Resources() (ui app_ui.UI) {\n\tbundle := resBundle()\n\tlg := es_log.Default()\n\tlog.SetOutput(lgw_golog.NewLogWrapper(lg))\n\tapp_resource.SetBundle(bundle)\n\n\tmc := app_msg_container_impl.NewContainer()\n\tif qt_secure.IsSecureEndToEndTest() || app.IsProduction() {\n\t\treturn app_ui.NewDiscard(mc, lg)\n\t} else {\n\t\treturn app_ui.NewConsole(mc, lg, es_stdout.NewDefaultOut(true), es_dialogue.DenyAll())\n\t}\n}\n\nfunc TestWithDbxContext(t *testing.T, twc func(ctx dbx_context.Context)) {\n\tTestWithControl(t, func(ctl app_control.Control) {\n\t\tctx := dbx_context_impl.NewMock(ctl)\n\t\ttwc(ctx)\n\t})\n}\n\nfunc TestWithReplayDbxContext(t *testing.T, name string, twc func(ctx dbx_context.Context)) {\n\tTestWithControl(t, func(ctl app_control.Control) {\n\t\trm, err := loadReplay(name)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tctx := dbx_context_impl.NewReplayMock(ctl, rm)\n\t\ttwc(ctx)\n\t})\n}\n\nfunc TestWithControl(t *testing.T, twc func(ctl app_control.Control)) {\n\tnw_ratelimit.SetTestMode(true)\n\tui := Resources()\n\twb, err := app_workspace.NewBundle(\"\", app_budget.BudgetUnlimited, es_log.ConsoleDefaultLevel())\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tcom := app_opt.Default()\n\tnop := rc_spec.New(&rc_recipe.Nop{})\n\tjl := app_job_impl.NewLauncher(ui, wb, com, nop)\n\tctl, err := jl.Up()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\ttwc(ctl.WithFeature(ctl.Feature().AsTest(false)))\n\n\tjl.Down(nil, ctl)\n}\n\nfunc ForkWithName(t *testing.T, name string, c app_control.Control, f func(c app_control.Control) error) {\n\terr := app_workspace.WithFork(c.WorkBundle(), name, func(fwb app_workspace.Bundle) error {\n\t\tcf := c.WithBundle(fwb)\n\t\tl := cf.Log()\n\t\tl.Info(\"Execute\", es_log.String(\"name\", name))\n\t\treturn f(cf)\n\t})\n\tif re, c := qt_errors.ErrorsForTest(c.Log(), err); !c {\n\t\tt.Error(re)\n\t}\n}\n\nfunc TestRecipe(t *testing.T, re rc_recipe.Recipe) {\n\tDoTestRecipe(t, re, false)\n}\n\nfunc DoTestRecipe(t *testing.T, re rc_recipe.Recipe, useMock bool) {\n\ttype Stopper interface {\n\t\tStop()\n\t}\n\tnw_ratelimit.SetTestMode(true)\n\tTestWithControl(t, func(ctl app_control.Control) {\n\t\tl := ctl.Log()\n\t\tl.Debug(\"Start testing\")\n\n\t\tvar pr Stopper\n\t\tif !testing.Short() {\n\t\t\tpr = profile.Start(\n\t\t\t\tprofile.ProfilePath(ctl.Workspace().Log()),\n\t\t\t\tprofile.MemProfile,\n\t\t\t)\n\t\t}\n\t\tvar err error\n\t\tif useMock {\n\t\t\terr = re.Test(ctl.WithFeature(ctl.Feature().AsTest(true)))\n\t\t} else {\n\t\t\terr = re.Test(ctl.WithFeature(ctl.Feature().AsTest(false)))\n\t\t}\n\n\t\tif pr != nil {\n\t\t\tpr.Stop()\n\t\t}\n\t\tes_memory.DumpMemStats(l)\n\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\n\t\tif re, _ := qt_errors.ErrorsForTest(l, err); re != nil {\n\t\t\tt.Error(re)\n\t\t}\n\t})\n}\n\ntype RowTester func(cols map[string]string) error\n\nfunc TestRows(ctl app_control.Control, reportName string, tester RowTester) error {\n\tl := ctl.Log().With(es_log.String(\"reportName\", reportName))\n\tcsvFile := filepath.Join(ctl.Workspace().Report(), reportName+\".csv\")\n\n\tl.Debug(\"Start loading report\", es_log.String(\"csvFile\", csvFile))\n\n\tcf, err := os.Open(csvFile)\n\tif err != nil {\n\t\tl.Warn(\"Unable to open report CSV\", es_log.Error(err))\n\t\treturn err\n\t}\n\tdefer cf.Close()\n\tcsf := csv.NewReader(cf)\n\tvar header []string\n\tisFirstLine := true\n\n\tfor {\n\t\tcols, err := csf.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tl.Warn(\"An error occurred during read report file\", es_log.Error(err))\n\t\t\treturn err\n\t\t}\n\t\tif isFirstLine {\n\t\t\theader = cols\n\t\t\tisFirstLine = false\n\t\t} else {\n\t\t\tcolMap := make(map[string]string)\n\t\t\tfor i, h := range header {\n\t\t\t\tcolMap[h] = cols[i]\n\t\t\t}\n\t\t\tif err := tester(colMap); err != nil {\n\t\t\t\tl.Warn(\"Tester returned an error\", es_log.Error(err), es_log.Any(\"cols\", colMap))\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>#358 : mock test fails on mock error<commit_after>package qt_recipe\n\nimport (\n\t\"encoding\/csv\"\n\t\"encoding\/json\"\n\trice \"github.com\/GeertJohan\/go.rice\"\n\t\"github.com\/pkg\/profile\"\n\tmo_path2 \"github.com\/watermint\/toolbox\/domain\/common\/model\/mo_path\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/api\/dbx_context\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/api\/dbx_context_impl\"\n\t\"github.com\/watermint\/toolbox\/domain\/dropbox\/model\/mo_path\"\n\t\"github.com\/watermint\/toolbox\/essentials\/go\/es_project\"\n\t\"github.com\/watermint\/toolbox\/essentials\/go\/es_resource\"\n\t\"github.com\/watermint\/toolbox\/essentials\/io\/es_stdout\"\n\t\"github.com\/watermint\/toolbox\/essentials\/log\/es_log\"\n\t\"github.com\/watermint\/toolbox\/essentials\/log\/stats\/es_memory\"\n\t\"github.com\/watermint\/toolbox\/essentials\/log\/wrapper\/lgw_golog\"\n\t\"github.com\/watermint\/toolbox\/essentials\/terminal\/es_dialogue\"\n\t\"github.com\/watermint\/toolbox\/infra\/app\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_budget\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_control\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_exit\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_job_impl\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_opt\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_resource\"\n\t\"github.com\/watermint\/toolbox\/infra\/control\/app_workspace\"\n\t\"github.com\/watermint\/toolbox\/infra\/network\/nw_ratelimit\"\n\t\"github.com\/watermint\/toolbox\/infra\/network\/nw_replay\"\n\t\"github.com\/watermint\/toolbox\/infra\/recipe\/rc_recipe\"\n\t\"github.com\/watermint\/toolbox\/infra\/recipe\/rc_spec\"\n\t\"github.com\/watermint\/toolbox\/infra\/ui\/app_msg_container_impl\"\n\t\"github.com\/watermint\/toolbox\/infra\/ui\/app_ui\"\n\t\"github.com\/watermint\/toolbox\/quality\/infra\/qt_errors\"\n\t\"github.com\/watermint\/toolbox\/quality\/infra\/qt_file\"\n\t\"github.com\/watermint\/toolbox\/quality\/infra\/qt_secure\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"testing\"\n)\n\nconst (\n\tTestTeamFolderName = \"watermint-toolbox-test\"\n)\n\nfunc NewTestDropboxFolderPath(rel ...string) mo_path.DropboxPath {\n\treturn mo_path.NewDropboxPath(\"\/\" + TestTeamFolderName).ChildPath(rel...)\n}\n\nfunc MustMakeTestFolder(ctl app_control.Control, name string, withContent bool) (path string) {\n\tpath, err := qt_file.MakeTestFolder(name, withContent)\n\tif err != nil {\n\t\tctl.Log().Error(\"Unable to create test folder\", es_log.Error(err))\n\t\tapp_exit.Abort(app_exit.FailureGeneral)\n\t}\n\treturn path\n}\n\nfunc NewTestFileSystemFolderPath(c app_control.Control, name string) mo_path2.FileSystemPath {\n\treturn mo_path2.NewFileSystemPath(MustMakeTestFolder(c, name, true))\n}\n\nfunc NewTestExistingFileSystemFolderPath(c app_control.Control, name string) mo_path2.ExistingFileSystemPath {\n\treturn mo_path2.NewExistingFileSystemPath(MustMakeTestFolder(c, name, true))\n}\n\nfunc resBundle() es_resource.Bundle {\n\t_, err := rice.FindBox(\"..\/..\/..\/resources\/messages\")\n\tif err == nil {\n\t\treturn es_resource.New(\n\t\t\trice.MustFindBox(\"..\/..\/..\/resources\/templates\"),\n\t\t\trice.MustFindBox(\"..\/..\/..\/resources\/messages\"),\n\t\t\trice.MustFindBox(\"..\/..\/..\/resources\/web\"),\n\t\t\trice.MustFindBox(\"..\/..\/..\/resources\/keys\"),\n\t\t\trice.MustFindBox(\"..\/..\/..\/resources\/images\"),\n\t\t\trice.MustFindBox(\"..\/..\/..\/resources\/data\"),\n\t\t)\n\t} else {\n\t\t\/\/ In case the test run from the project root\n\t\treturn es_resource.New(\n\t\t\trice.MustFindBox(\"resources\/templates\"),\n\t\t\trice.MustFindBox(\"resources\/messages\"),\n\t\t\trice.MustFindBox(\"resources\/web\"),\n\t\t\trice.MustFindBox(\"resources\/keys\"),\n\t\t\trice.MustFindBox(\"resources\/images\"),\n\t\t\trice.MustFindBox(\"resources\/data\"),\n\t\t)\n\t}\n}\n\nfunc findTestFolder() string {\n\tl := es_log.Default()\n\n\troot, err := es_project.DetectRepositoryRoot()\n\tif err != nil {\n\t\tl.Error(\"Test path not found\")\n\t\tpanic(err)\n\t}\n\treturn filepath.Join(root, \"test\")\n}\n\nfunc loadReplay(name string) (rr []nw_replay.Response, err error) {\n\tl := es_log.Default().With(es_log.String(\"name\", name))\n\ttp := findTestFolder()\n\trp := filepath.Join(tp, \"replay\", name)\n\n\tl.Debug(\"Loading replay\", es_log.String(\"path\", rp))\n\tb, err := ioutil.ReadFile(rp)\n\tif err != nil {\n\t\tl.Debug(\"Unable to load\", es_log.Error(err))\n\t\treturn nil, err\n\t}\n\n\tif err := json.Unmarshal(b, &rr); err != nil {\n\t\tl.Debug(\"Unable to unmarshal\", es_log.Error(err))\n\t\treturn nil, err\n\t}\n\n\tl.Debug(\"Replay loaded\", es_log.Int(\"numRecords\", len(rr)))\n\treturn rr, nil\n}\n\nfunc Resources() (ui app_ui.UI) {\n\tbundle := resBundle()\n\tlg := es_log.Default()\n\tlog.SetOutput(lgw_golog.NewLogWrapper(lg))\n\tapp_resource.SetBundle(bundle)\n\n\tmc := app_msg_container_impl.NewContainer()\n\tif qt_secure.IsSecureEndToEndTest() || app.IsProduction() {\n\t\treturn app_ui.NewDiscard(mc, lg)\n\t} else {\n\t\treturn app_ui.NewConsole(mc, lg, es_stdout.NewDefaultOut(true), es_dialogue.DenyAll())\n\t}\n}\n\nfunc TestWithDbxContext(t *testing.T, twc func(ctx dbx_context.Context)) {\n\tTestWithControl(t, func(ctl app_control.Control) {\n\t\tctx := dbx_context_impl.NewMock(ctl)\n\t\ttwc(ctx)\n\t})\n}\n\nfunc TestWithReplayDbxContext(t *testing.T, name string, twc func(ctx dbx_context.Context)) {\n\tTestWithControl(t, func(ctl app_control.Control) {\n\t\trm, err := loadReplay(name)\n\t\tif err != nil {\n\t\t\tt.Error(err)\n\t\t\treturn\n\t\t}\n\t\tctx := dbx_context_impl.NewReplayMock(ctl, rm)\n\t\ttwc(ctx)\n\t})\n}\n\nfunc TestWithControl(t *testing.T, twc func(ctl app_control.Control)) {\n\tnw_ratelimit.SetTestMode(true)\n\tui := Resources()\n\twb, err := app_workspace.NewBundle(\"\", app_budget.BudgetUnlimited, es_log.ConsoleDefaultLevel())\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tcom := app_opt.Default()\n\tnop := rc_spec.New(&rc_recipe.Nop{})\n\tjl := app_job_impl.NewLauncher(ui, wb, com, nop)\n\tctl, err := jl.Up()\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\ttwc(ctl.WithFeature(ctl.Feature().AsTest(false)))\n\n\tjl.Down(nil, ctl)\n}\n\nfunc ForkWithName(t *testing.T, name string, c app_control.Control, f func(c app_control.Control) error) {\n\terr := app_workspace.WithFork(c.WorkBundle(), name, func(fwb app_workspace.Bundle) error {\n\t\tcf := c.WithBundle(fwb)\n\t\tl := cf.Log()\n\t\tl.Info(\"Execute\", es_log.String(\"name\", name))\n\t\treturn f(cf)\n\t})\n\tif re, c := qt_errors.ErrorsForTest(c.Log(), err); !c && re != nil {\n\t\tt.Error(re)\n\t}\n}\n\nfunc TestRecipe(t *testing.T, re rc_recipe.Recipe) {\n\tDoTestRecipe(t, re, false)\n}\n\nfunc DoTestRecipe(t *testing.T, re rc_recipe.Recipe, useMock bool) {\n\ttype Stopper interface {\n\t\tStop()\n\t}\n\tnw_ratelimit.SetTestMode(true)\n\tTestWithControl(t, func(ctl app_control.Control) {\n\t\tl := ctl.Log()\n\t\tl.Debug(\"Start testing\")\n\n\t\tvar pr Stopper\n\t\tif !testing.Short() {\n\t\t\tpr = profile.Start(\n\t\t\t\tprofile.ProfilePath(ctl.Workspace().Log()),\n\t\t\t\tprofile.MemProfile,\n\t\t\t)\n\t\t}\n\t\tvar err error\n\t\tif useMock {\n\t\t\terr = re.Test(ctl.WithFeature(ctl.Feature().AsTest(true)))\n\t\t} else {\n\t\t\terr = re.Test(ctl.WithFeature(ctl.Feature().AsTest(false)))\n\t\t}\n\n\t\tif pr != nil {\n\t\t\tpr.Stop()\n\t\t}\n\t\tes_memory.DumpMemStats(l)\n\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\n\t\tif re, _ := qt_errors.ErrorsForTest(l, err); re != nil {\n\t\t\tt.Error(re)\n\t\t}\n\t})\n}\n\ntype RowTester func(cols map[string]string) error\n\nfunc TestRows(ctl app_control.Control, reportName string, tester RowTester) error {\n\tl := ctl.Log().With(es_log.String(\"reportName\", reportName))\n\tcsvFile := filepath.Join(ctl.Workspace().Report(), reportName+\".csv\")\n\n\tl.Debug(\"Start loading report\", es_log.String(\"csvFile\", csvFile))\n\n\tcf, err := os.Open(csvFile)\n\tif err != nil {\n\t\tl.Warn(\"Unable to open report CSV\", es_log.Error(err))\n\t\treturn err\n\t}\n\tdefer cf.Close()\n\tcsf := csv.NewReader(cf)\n\tvar header []string\n\tisFirstLine := true\n\n\tfor {\n\t\tcols, err := csf.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tl.Warn(\"An error occurred during read report file\", es_log.Error(err))\n\t\t\treturn err\n\t\t}\n\t\tif isFirstLine {\n\t\t\theader = cols\n\t\t\tisFirstLine = false\n\t\t} else {\n\t\t\tcolMap := make(map[string]string)\n\t\t\tfor i, h := range header {\n\t\t\t\tcolMap[h] = cols[i]\n\t\t\t}\n\t\t\tif err := tester(colMap); err != nil {\n\t\t\t\tl.Warn(\"Tester returned an error\", es_log.Error(err), es_log.Any(\"cols\", colMap))\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package mock\n\nimport (\n\t\"restic\"\n\t\"restic\/crypto\"\n)\n\n\/\/ Repository implements a mock Repository.\ntype Repository struct {\n\tBackendFn func() Backend\n\n\tKeyFn func() *crypto.Key\n\n\tSetIndexFn func(restic.Index)\n\n\tIndexFn         func() restic.Index\n\tSaveFullIndexFn func() error\n\tSaveIndexFn     func() error\n\tLoadIndexFn     func() error\n\n\tConfigFn func() restic.Config\n\n\tLookupBlobSizeFn func(restic.ID, restic.BlobType) (uint, error)\n\n\tListFn     func(restic.FileType, <-chan struct{}) <-chan restic.ID\n\tListPackFn func(restic.ID) ([]restic.Blob, int64, error)\n\n\tFlushFn func() error\n\n\tSaveUnpackedFn     func(restic.FileType, []byte) (restic.ID, error)\n\tSaveJSONUnpackedFn func(restic.FileType, interface{}) (restic.ID, error)\n\n\tLoadJSONUnpackedFn func(restic.FileType, restic.ID, interface{}) error\n\tLoadAndDecryptFn   func(restic.FileType, restic.ID) ([]byte, error)\n\n\tLoadBlobFn func(restic.BlobType, restic.ID, []byte) (int, error)\n\tSaveBlobFn func(restic.BlobType, []byte, restic.ID) (restic.ID, error)\n\n\tLoadTreeFn func(restic.ID) (*restic.Tree, error)\n\tSaveTreeFn func(t *restic.Tree) (restic.ID, error)\n}\n\n\/\/ Backend is a stub method.\nfunc (repo *Repository) Backend() Backend {\n\treturn repo.BackendFn()\n}\n\n\/\/ Key is a stub method.\nfunc (repo *Repository) Key() *crypto.Key {\n\treturn repo.KeyFn()\n}\n\n\/\/ SetIndex is a stub method.\nfunc (repo *Repository) SetIndex(idx restic.Index) {\n\trepo.SetIndexFn(idx)\n}\n\n\/\/ Index is a stub method.\nfunc (repo *Repository) Index() restic.Index {\n\treturn repo.IndexFn()\n}\n\n\/\/ SaveFullIndex is a stub method.\nfunc (repo *Repository) SaveFullIndex() error {\n\treturn repo.SaveFullIndexFn()\n}\n\n\/\/ SaveIndex is a stub method.\nfunc (repo *Repository) SaveIndex() error {\n\treturn repo.SaveIndexFn()\n}\n\n\/\/ LoadIndex is a stub method.\nfunc (repo *Repository) LoadIndex() error {\n\treturn repo.LoadIndexFn()\n}\n\n\/\/ Config is a stub method.\nfunc (repo *Repository) Config() restic.Config {\n\treturn repo.ConfigFn()\n}\n\n\/\/ LookupBlobSize is a stub method.\nfunc (repo *Repository) LookupBlobSize(id restic.ID, t restic.BlobType) (uint, error) {\n\treturn repo.LookupBlobSizeFn(id, t)\n}\n\n\/\/ List is a stub method.\nfunc (repo *Repository) List(t restic.FileType, done <-chan struct{}) <-chan restic.ID {\n\treturn repo.ListFn(t, done)\n}\n\n\/\/ ListPack is a stub method.\nfunc (repo *Repository) ListPack(id restic.ID) ([]restic.Blob, int64, error) {\n\treturn repo.ListPackFn(id)\n}\n\n\/\/ Flush is a stub method.\nfunc (repo *Repository) Flush() error {\n\treturn repo.FlushFn()\n}\n\n\/\/ SaveUnpacked is a stub method.\nfunc (repo *Repository) SaveUnpacked(t restic.FileType, buf []byte) (restic.ID, error) {\n\treturn repo.SaveUnpackedFn(t, buf)\n}\n\n\/\/ SaveJSONUnpacked is a stub method.\nfunc (repo *Repository) SaveJSONUnpacked(t restic.FileType, item interface{}) (restic.ID, error) {\n\treturn repo.SaveJSONUnpackedFn(t, item)\n}\n\n\/\/ LoadJSONUnpacked is a stub method.\nfunc (repo *Repository) LoadJSONUnpacked(t restic.FileType, id restic.ID, item interface{}) error {\n\treturn repo.LoadJSONUnpackedFn(t, id, item)\n}\n\n\/\/ LoadAndDecrypt is a stub method.\nfunc (repo *Repository) LoadAndDecrypt(t restic.FileType, id restic.ID) ([]byte, error) {\n\treturn repo.LoadAndDecryptFn(t, id)\n}\n\n\/\/ LoadBlob is a stub method.\nfunc (repo *Repository) LoadBlob(t restic.BlobType, id restic.ID, buf []byte) (int, error) {\n\treturn repo.LoadBlobFn(t, id, buf)\n}\n\n\/\/ SaveBlob is a stub method.\nfunc (repo *Repository) SaveBlob(t restic.BlobType, buf []byte, id restic.ID) (restic.ID, error) {\n\treturn repo.SaveBlobFn(t, buf, id)\n}\n\n\/\/ LoadTree is a stub method.\nfunc (repo *Repository) LoadTree(id restic.ID) (*restic.Tree, error) {\n\treturn repo.LoadTreeFn(id)\n}\n\n\/\/ SaveTree is a stub method.\nfunc (repo *Repository) SaveTree(t *restic.Tree) (restic.ID, error) {\n\treturn repo.SaveTreeFn(t)\n}\n<commit_msg>Fix mock.Repository<commit_after>package mock\n\nimport (\n\t\"restic\"\n\t\"restic\/crypto\"\n)\n\n\/\/ Repository implements a mock Repository.\ntype Repository struct {\n\tBackendFn func() restic.Backend\n\n\tKeyFn func() *crypto.Key\n\n\tSetIndexFn func(restic.Index)\n\n\tIndexFn         func() restic.Index\n\tSaveFullIndexFn func() error\n\tSaveIndexFn     func() error\n\tLoadIndexFn     func() error\n\n\tConfigFn func() restic.Config\n\n\tLookupBlobSizeFn func(restic.ID, restic.BlobType) (uint, error)\n\n\tListFn     func(restic.FileType, <-chan struct{}) <-chan restic.ID\n\tListPackFn func(restic.ID) ([]restic.Blob, int64, error)\n\n\tFlushFn func() error\n\n\tSaveUnpackedFn     func(restic.FileType, []byte) (restic.ID, error)\n\tSaveJSONUnpackedFn func(restic.FileType, interface{}) (restic.ID, error)\n\n\tLoadJSONUnpackedFn func(restic.FileType, restic.ID, interface{}) error\n\tLoadAndDecryptFn   func(restic.FileType, restic.ID) ([]byte, error)\n\n\tLoadBlobFn func(restic.BlobType, restic.ID, []byte) (int, error)\n\tSaveBlobFn func(restic.BlobType, []byte, restic.ID) (restic.ID, error)\n\n\tLoadTreeFn func(restic.ID) (*restic.Tree, error)\n\tSaveTreeFn func(t *restic.Tree) (restic.ID, error)\n}\n\n\/\/ Backend is a stub method.\nfunc (repo Repository) Backend() restic.Backend {\n\treturn repo.BackendFn()\n}\n\n\/\/ Key is a stub method.\nfunc (repo Repository) Key() *crypto.Key {\n\treturn repo.KeyFn()\n}\n\n\/\/ SetIndex is a stub method.\nfunc (repo Repository) SetIndex(idx restic.Index) {\n\trepo.SetIndexFn(idx)\n}\n\n\/\/ Index is a stub method.\nfunc (repo Repository) Index() restic.Index {\n\treturn repo.IndexFn()\n}\n\n\/\/ SaveFullIndex is a stub method.\nfunc (repo Repository) SaveFullIndex() error {\n\treturn repo.SaveFullIndexFn()\n}\n\n\/\/ SaveIndex is a stub method.\nfunc (repo Repository) SaveIndex() error {\n\treturn repo.SaveIndexFn()\n}\n\n\/\/ LoadIndex is a stub method.\nfunc (repo Repository) LoadIndex() error {\n\treturn repo.LoadIndexFn()\n}\n\n\/\/ Config is a stub method.\nfunc (repo Repository) Config() restic.Config {\n\treturn repo.ConfigFn()\n}\n\n\/\/ LookupBlobSize is a stub method.\nfunc (repo Repository) LookupBlobSize(id restic.ID, t restic.BlobType) (uint, error) {\n\treturn repo.LookupBlobSizeFn(id, t)\n}\n\n\/\/ List is a stub method.\nfunc (repo Repository) List(t restic.FileType, done <-chan struct{}) <-chan restic.ID {\n\treturn repo.ListFn(t, done)\n}\n\n\/\/ ListPack is a stub method.\nfunc (repo Repository) ListPack(id restic.ID) ([]restic.Blob, int64, error) {\n\treturn repo.ListPackFn(id)\n}\n\n\/\/ Flush is a stub method.\nfunc (repo Repository) Flush() error {\n\treturn repo.FlushFn()\n}\n\n\/\/ SaveUnpacked is a stub method.\nfunc (repo Repository) SaveUnpacked(t restic.FileType, buf []byte) (restic.ID, error) {\n\treturn repo.SaveUnpackedFn(t, buf)\n}\n\n\/\/ SaveJSONUnpacked is a stub method.\nfunc (repo Repository) SaveJSONUnpacked(t restic.FileType, item interface{}) (restic.ID, error) {\n\treturn repo.SaveJSONUnpackedFn(t, item)\n}\n\n\/\/ LoadJSONUnpacked is a stub method.\nfunc (repo Repository) LoadJSONUnpacked(t restic.FileType, id restic.ID, item interface{}) error {\n\treturn repo.LoadJSONUnpackedFn(t, id, item)\n}\n\n\/\/ LoadAndDecrypt is a stub method.\nfunc (repo Repository) LoadAndDecrypt(t restic.FileType, id restic.ID) ([]byte, error) {\n\treturn repo.LoadAndDecryptFn(t, id)\n}\n\n\/\/ LoadBlob is a stub method.\nfunc (repo Repository) LoadBlob(t restic.BlobType, id restic.ID, buf []byte) (int, error) {\n\treturn repo.LoadBlobFn(t, id, buf)\n}\n\n\/\/ SaveBlob is a stub method.\nfunc (repo Repository) SaveBlob(t restic.BlobType, buf []byte, id restic.ID) (restic.ID, error) {\n\treturn repo.SaveBlobFn(t, buf, id)\n}\n\n\/\/ LoadTree is a stub method.\nfunc (repo Repository) LoadTree(id restic.ID) (*restic.Tree, error) {\n\treturn repo.LoadTreeFn(id)\n}\n\n\/\/ SaveTree is a stub method.\nfunc (repo Repository) SaveTree(t *restic.Tree) (restic.ID, error) {\n\treturn repo.SaveTreeFn(t)\n}\n<|endoftext|>"}
{"text":"<commit_before>package collector\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/bcicen\/ctop\/models\"\n\tapi \"github.com\/fsouza\/go-dockerclient\"\n)\n\ntype DockerLogs struct {\n\tid     string\n\tclient *api.Client\n\tdone   chan bool\n}\n\nfunc NewDockerLogs(id string, client *api.Client) *DockerLogs {\n\treturn &DockerLogs{\n\t\tid:     id,\n\t\tclient: client,\n\t\tdone:   make(chan bool),\n\t}\n}\n\nfunc (l *DockerLogs) Stream() chan models.Log {\n\tr, w := io.Pipe()\n\tlogCh := make(chan models.Log)\n\tctx, cancel := context.WithCancel(context.Background())\n\n\topts := api.LogsOptions{\n\t\tContext:      ctx,\n\t\tContainer:    l.id,\n\t\tOutputStream: w,\n\t\tErrorStream:  w,\n\t\tStdout:       true,\n\t\tStderr:       true,\n\t\tTail:         \"10\",\n\t\tFollow:       true,\n\t\tTimestamps:   true,\n\t}\n\n\t\/\/ read io pipe into channel\n\tgo func() {\n\t\tscanner := bufio.NewScanner(r)\n\t\tfor scanner.Scan() {\n\t\t\tparts := strings.Split(scanner.Text(), \" \")\n\t\t\tts := l.parseTime(parts[0])\n\t\t\tlogCh <- models.Log{ts, strings.Join(parts[1:], \" \")}\n\t\t}\n\t}()\n\n\t\/\/ connect to container log stream\n\tgo func() {\n\t\terr := l.client.Logs(opts)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"error reading container logs: %s\", err)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tselect {\n\t\tcase <-l.done:\n\t\t\tcancel()\n\t\t}\n\t}()\n\n\treturn logCh\n}\n\nfunc (l *DockerLogs) Stop() { l.done <- true }\n\nfunc (l *DockerLogs) parseTime(s string) time.Time {\n\tts, err := time.Parse(\"2006-01-02T15:04:05.000000000Z\", s)\n\tif err != nil {\n\t\tlog.Errorf(\"failed to parse container log: %s\", err)\n\t\tts = time.Now()\n\t}\n\treturn ts\n}\n<commit_msg>add logging for log reader start\/stop<commit_after>package collector\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/bcicen\/ctop\/models\"\n\tapi \"github.com\/fsouza\/go-dockerclient\"\n)\n\ntype DockerLogs struct {\n\tid     string\n\tclient *api.Client\n\tdone   chan bool\n}\n\nfunc NewDockerLogs(id string, client *api.Client) *DockerLogs {\n\treturn &DockerLogs{\n\t\tid:     id,\n\t\tclient: client,\n\t\tdone:   make(chan bool),\n\t}\n}\n\nfunc (l *DockerLogs) Stream() chan models.Log {\n\tr, w := io.Pipe()\n\tlogCh := make(chan models.Log)\n\tctx, cancel := context.WithCancel(context.Background())\n\n\topts := api.LogsOptions{\n\t\tContext:      ctx,\n\t\tContainer:    l.id,\n\t\tOutputStream: w,\n\t\tErrorStream:  w,\n\t\tStdout:       true,\n\t\tStderr:       true,\n\t\tTail:         \"10\",\n\t\tFollow:       true,\n\t\tTimestamps:   true,\n\t}\n\n\t\/\/ read io pipe into channel\n\tgo func() {\n\t\tscanner := bufio.NewScanner(r)\n\t\tfor scanner.Scan() {\n\t\t\tparts := strings.Split(scanner.Text(), \" \")\n\t\t\tts := l.parseTime(parts[0])\n\t\t\tlogCh <- models.Log{ts, strings.Join(parts[1:], \" \")}\n\t\t}\n\t}()\n\n\t\/\/ connect to container log stream\n\tgo func() {\n\t\terr := l.client.Logs(opts)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"error reading container logs: %s\", err)\n\t\t}\n\t\tlog.Infof(\"log reader stopped for container: %s\", l.id)\n\t}()\n\n\tgo func() {\n\t\tselect {\n\t\tcase <-l.done:\n\t\t\tcancel()\n\t\t}\n\t}()\n\n\tlog.Infof(\"log reader started for container: %s\", l.id)\n\treturn logCh\n}\n\nfunc (l *DockerLogs) Stop() { l.done <- true }\n\nfunc (l *DockerLogs) parseTime(s string) time.Time {\n\tts, err := time.Parse(\"2006-01-02T15:04:05.000000000Z\", s)\n\tif err != nil {\n\t\tlog.Errorf(\"failed to parse container log: %s\", err)\n\t\tts = time.Now()\n\t}\n\treturn ts\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Project Gonder.\n\/\/ Author Supme\n\/\/ Copyright Supme 2016\n\/\/ License http:\/\/opensource.org\/licenses\/MIT MIT License\n\/\/\n\/\/  THE SOFTWARE AND DOCUMENTATION ARE PROVIDED \"AS IS\" WITHOUT WARRANTY OF\n\/\/  ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n\/\/  IMPLIED WARRANTIES OF MERCHANTABILITY AND\/OR FITNESS FOR A PARTICULAR\n\/\/  PURPOSE.\n\/\/\n\/\/ Please see the License.txt file for more information.\n\/\/\npackage models\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"text\/template\"\n\t\"log\"\n)\n\ntype (\n\tMessage struct {\n\t\tRecipientId      string\n\t\tRecipientEmail   string\n\t\tRecipientName    string\n\t\tRecipientParam   map[string]string\n\t\tCampaignId       string\n\t\tCampaignSubject  string\n\t\tCampaignTemplate string\n\t}\n\n\tJsonData struct {\n\t\tId    string `json:\"id\"`\n\t\tEmail string `json:\"email\"`\n\t\tData  string `json:\"data\"`\n\t}\n)\n\nfunc (m *Message) New(recipientId string) error {\n\tm.RecipientId = recipientId\n\terr := Db.QueryRow(\"SELECT `campaign_id`,`email`,`name` FROM `recipient` WHERE `id`=?\", m.RecipientId).Scan(&m.CampaignId, &m.RecipientEmail, &m.RecipientName)\n\tif err == sql.ErrNoRows {\n\t\treturn errors.New(\"The recipient does not exist\")\n\t}\n\treturn nil\n}\n\nfunc DecodeData(base64data string) (message Message, data string, err error) {\n\tvar param JsonData\n\n\tdecode, err := base64.URLEncoding.DecodeString(base64data)\n\tif err != nil {\n\t\treturn message, data, err\n\t}\n\terr = json.Unmarshal([]byte(decode), &param)\n\tif err != nil {\n\t\treturn message, data, err\n\t}\n\tdata = param.Data\n\terr = message.New(param.Id)\n\tif err != nil {\n\t\treturn message, data, err\n\t}\n\tif param.Email != message.RecipientEmail {\n\t\treturn message, data, errors.New(\"Not valid recipient\")\n\t}\n\treturn message, data, nil\n}\n\nfunc (m *Message) Unsubscribe(extra map[string]string) error {\n\tr, err := Db.Exec(\"INSERT INTO unsubscribe (`group_id`, `campaign_id`, `email`) VALUE ((SELECT group_id FROM campaign WHERE id=?), ?, ?)\", m.CampaignId, m.CampaignId, m.RecipientEmail)\n\tid, e := r.LastInsertId();\n\tif e != nil {\n\t\tlog.Print(err)\n\t}\n\tfor name, value := range extra {\n\t\tDb.Exec(\"INSERT INTO unsubscribe_extra (`unsubscribe_id`, `name`, `value`) VALUE (?, ?, ?)\", id, name, value)\n\t}\n\treturn err\n}\n\nfunc (m *Message) UnsubscribeTemplateDir() (name string) {\n\tDb.QueryRow(\"SELECT `group`.`template` FROM `campaign` INNER JOIN `group` ON `campaign`.`group_id`=`group`.`id` WHERE `group`.`template` IS NOT NULL AND `campaign`.`id`=?\", m.CampaignId).Scan(&name)\n\tif name == \"\" {\n\t\tname = \"default\"\n\t} else {\n\t\tif _, err := os.Stat(FromRootDir(\"templates\/\" + name + \"\/accept.html\")); err != nil {\n\t\t\tname = \"default\"\n\t\t}\n\t\tif _, err := os.Stat(FromRootDir(\"templates\/\" + name + \"\/success.html\")); err != nil {\n\t\t\tname = \"default\"\n\t\t}\n\t}\n\tname = FromRootDir(\"templates\/\" + name)\n\treturn\n}\n\nfunc (m *Message) makeLink(cmd, data string) string {\n\tj, _ := json.Marshal(\n\t\tJsonData{\n\t\t\tId:    m.RecipientId,\n\t\t\tEmail: m.RecipientEmail,\n\t\t\tData:  data,\n\t\t})\n\treturn Config.Url + \"\/\" + cmd + \"\/\" + base64.URLEncoding.EncodeToString(j)\n}\n\nfunc (m *Message) UnsubscribeWebLink() string {\n\treturn m.makeLink(\"unsubscribe\", \"web\")\n}\n\nfunc (m *Message) UnsubscribeMailLink() string {\n\treturn m.makeLink(\"unsubscribe\", \"mail\")\n}\n\nfunc (m *Message) RedirectLink(url string) string {\n\treturn m.makeLink(\"redirect\", url)\n}\n\nfunc (m *Message) WebLink() string {\n\treturn m.makeLink(\"web\", \"\")\n}\n\nfunc (m *Message) StatPngLink() string {\n\treturn m.makeLink(\"open\", \"\")\n}\n\nfunc (m *Message) RenderMessage() (string, error) {\n\n\tvar err error\n\tvar web bool\n\n\tif m.CampaignSubject == \"\" && m.CampaignTemplate == \"\" {\n\t\terr := Db.QueryRow(\"SELECT `subject`,`body` FROM `campaign` WHERE `id`=?\", m.CampaignId).Scan(&m.CampaignSubject, &m.CampaignTemplate)\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn \"\", err\n\t\t}\n\t\tweb = true\n\t} else {\n\t\tweb = false\n\t}\n\n\tm.RecipientParam = map[string]string{}\n\tvar paramKey, paramValue string\n\tq, err := Db.Query(\"SELECT `key`, `value` FROM parameter WHERE recipient_id=?\", m.RecipientId)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer q.Close()\n\tfor q.Next() {\n\t\terr = q.Scan(&paramKey, &paramValue)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tm.RecipientParam[paramKey] = paramValue\n\t}\n\n\tm.RecipientParam[\"UnsubscribeUrl\"] = m.UnsubscribeWebLink()\n\tm.RecipientParam[\"StatPng\"] = m.StatPngLink()\n\tm.RecipientParam[\"RecipientEmail\"] = m.RecipientEmail\n\tm.RecipientParam[\"RecipientName\"] = m.RecipientName\n\tm.RecipientParam[\"CampaignId\"] = m.CampaignId\n\n\tif !web {\n\t\tm.RecipientParam[\"WebUrl\"] = m.WebLink()\n\n\t\t\/\/ add statistic png\n\t\tif strings.Index(m.CampaignTemplate, \"{{.StatPng}}\") == -1 {\n\t\t\tif strings.Index(m.CampaignTemplate, \"<\/body>\") == -1 {\n\t\t\t\tm.CampaignTemplate = m.CampaignTemplate + \"<img src='{{.StatPng}}' border='0px' width='10px' height='10px'\/>\"\n\t\t\t} else {\n\t\t\t\tm.CampaignTemplate = strings.Replace(m.CampaignTemplate, \"<\/body>\", \"\\n<img src='{{.StatPng}}' border='0px' width='10px' height='10px'\/>\\n<\/body>\", -1)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Replace links for statistic\n\tre := regexp.MustCompile(`[hH][rR][eE][fF]\\s*?=\\s*?[\"']\\s*?(\\[.*?\\])?\\s*?(\\b[hH][tT]{2}[pP][sS]?\\b:\\\/\\\/\\b)(.*?)[\"']`)\n\tm.CampaignTemplate = re.ReplaceAllStringFunc(m.CampaignTemplate, func(str string) string {\n\t\t\/\/ get only url\n\t\ts := strings.Replace(str, `'`, \"\", -1)\n\t\ts = strings.Replace(s, `\"`, \"\", -1)\n\t\ts = strings.Replace(s, \"href=\", \"\", 1)\n\n\t\tswitch s {\n\t\tcase \"{{.WebUrl}}\":\n\t\t\treturn `href=\"` + m.RecipientParam[\"WebUrl\"] + `\"`\n\t\tcase \"{{.UnsubscribeUrl}}\":\n\t\t\treturn `href=\"` + m.RecipientParam[\"UnsubscribeUrl\"] + `\"`\n\t\tdefault:\n\t\t\t\/\/ template parameter in url\n\t\t\turlt := template.New(\"url\" + m.RecipientId)\n\t\t\turlt, err = urlt.Parse(s)\n\t\t\tif err != nil {\n\t\t\t\ts = fmt.Sprintf(\"Error parse url params: %v\", err)\n\t\t\t}\n\t\t\tu := bytes.NewBufferString(\"\")\n\t\t\turlt.Execute(u, m.RecipientParam)\n\t\t\ts = u.String()\n\n\t\t\treturn `href=\"` + m.RedirectLink(s) + `\"`\n\t\t}\n\t})\n\n\t\/\/replace static url to absolute\n\tm.CampaignTemplate = strings.Replace(m.CampaignTemplate, \"\\\"\/files\/\", \"\\\"\"+Config.Url+\"\/files\/\", -1)\n\tm.CampaignTemplate = strings.Replace(m.CampaignTemplate, \"'\/files\/\", \"'\"+Config.Url+\"'\/files\/\", -1)\n\n\ttmpl := template.New(\"mail\" + m.RecipientId)\n\n\ttmpl, err = tmpl.Parse(m.CampaignTemplate)\n\tif err != nil {\n\t\te := fmt.Sprintf(\"Error parse template: %v\", err)\n\t\treturn e, err\n\t}\n\n\tt := bytes.NewBufferString(\"\")\n\ttmpl.Execute(t, m.RecipientParam)\n\treturn t.String(), nil\n}\n<commit_msg>template mail subject<commit_after>\/\/ Project Gonder.\n\/\/ Author Supme\n\/\/ Copyright Supme 2016\n\/\/ License http:\/\/opensource.org\/licenses\/MIT MIT License\n\/\/\n\/\/  THE SOFTWARE AND DOCUMENTATION ARE PROVIDED \"AS IS\" WITHOUT WARRANTY OF\n\/\/  ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n\/\/  IMPLIED WARRANTIES OF MERCHANTABILITY AND\/OR FITNESS FOR A PARTICULAR\n\/\/  PURPOSE.\n\/\/\n\/\/ Please see the License.txt file for more information.\n\/\/\npackage models\n\nimport (\n\t\"bytes\"\n\t\"database\/sql\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"text\/template\"\n\t\"log\"\n)\n\ntype (\n\tMessage struct {\n\t\tRecipientId      string\n\t\tRecipientEmail   string\n\t\tRecipientName    string\n\t\tRecipientParam   map[string]string\n\t\tCampaignId       string\n\t\tCampaignSubject  string\n\t\tCampaignTemplate string\n\t}\n\n\tJsonData struct {\n\t\tId    string `json:\"id\"`\n\t\tEmail string `json:\"email\"`\n\t\tData  string `json:\"data\"`\n\t}\n)\n\nfunc (m *Message) New(recipientId string) error {\n\tm.RecipientId = recipientId\n\terr := Db.QueryRow(\"SELECT `campaign_id`,`email`,`name` FROM `recipient` WHERE `id`=?\", m.RecipientId).Scan(&m.CampaignId, &m.RecipientEmail, &m.RecipientName)\n\tif err == sql.ErrNoRows {\n\t\treturn errors.New(\"The recipient does not exist\")\n\t}\n\treturn nil\n}\n\nfunc DecodeData(base64data string) (message Message, data string, err error) {\n\tvar param JsonData\n\n\tdecode, err := base64.URLEncoding.DecodeString(base64data)\n\tif err != nil {\n\t\treturn message, data, err\n\t}\n\terr = json.Unmarshal([]byte(decode), &param)\n\tif err != nil {\n\t\treturn message, data, err\n\t}\n\tdata = param.Data\n\terr = message.New(param.Id)\n\tif err != nil {\n\t\treturn message, data, err\n\t}\n\tif param.Email != message.RecipientEmail {\n\t\treturn message, data, errors.New(\"Not valid recipient\")\n\t}\n\treturn message, data, nil\n}\n\nfunc (m *Message) Unsubscribe(extra map[string]string) error {\n\tr, err := Db.Exec(\"INSERT INTO unsubscribe (`group_id`, `campaign_id`, `email`) VALUE ((SELECT group_id FROM campaign WHERE id=?), ?, ?)\", m.CampaignId, m.CampaignId, m.RecipientEmail)\n\tid, e := r.LastInsertId();\n\tif e != nil {\n\t\tlog.Print(err)\n\t}\n\tfor name, value := range extra {\n\t\tDb.Exec(\"INSERT INTO unsubscribe_extra (`unsubscribe_id`, `name`, `value`) VALUE (?, ?, ?)\", id, name, value)\n\t}\n\treturn err\n}\n\nfunc (m *Message) UnsubscribeTemplateDir() (name string) {\n\tDb.QueryRow(\"SELECT `group`.`template` FROM `campaign` INNER JOIN `group` ON `campaign`.`group_id`=`group`.`id` WHERE `group`.`template` IS NOT NULL AND `campaign`.`id`=?\", m.CampaignId).Scan(&name)\n\tif name == \"\" {\n\t\tname = \"default\"\n\t} else {\n\t\tif _, err := os.Stat(FromRootDir(\"templates\/\" + name + \"\/accept.html\")); err != nil {\n\t\t\tname = \"default\"\n\t\t}\n\t\tif _, err := os.Stat(FromRootDir(\"templates\/\" + name + \"\/success.html\")); err != nil {\n\t\t\tname = \"default\"\n\t\t}\n\t}\n\tname = FromRootDir(\"templates\/\" + name)\n\treturn\n}\n\nfunc (m *Message) makeLink(cmd, data string) string {\n\tj, _ := json.Marshal(\n\t\tJsonData{\n\t\t\tId:    m.RecipientId,\n\t\t\tEmail: m.RecipientEmail,\n\t\t\tData:  data,\n\t\t})\n\treturn Config.Url + \"\/\" + cmd + \"\/\" + base64.URLEncoding.EncodeToString(j)\n}\n\nfunc (m *Message) UnsubscribeWebLink() string {\n\treturn m.makeLink(\"unsubscribe\", \"web\")\n}\n\nfunc (m *Message) UnsubscribeMailLink() string {\n\treturn m.makeLink(\"unsubscribe\", \"mail\")\n}\n\nfunc (m *Message) RedirectLink(url string) string {\n\treturn m.makeLink(\"redirect\", url)\n}\n\nfunc (m *Message) WebLink() string {\n\treturn m.makeLink(\"web\", \"\")\n}\n\nfunc (m *Message) StatPngLink() string {\n\treturn m.makeLink(\"open\", \"\")\n}\n\nfunc (m *Message) RenderMessage() (string, error) {\n\n\tvar err error\n\tvar web bool\n\n\tif m.CampaignSubject == \"\" && m.CampaignTemplate == \"\" {\n\t\terr := Db.QueryRow(\"SELECT `subject`,`body` FROM `campaign` WHERE `id`=?\", m.CampaignId).Scan(&m.CampaignSubject, &m.CampaignTemplate)\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn \"\", err\n\t\t}\n\t\tweb = true\n\t} else {\n\t\tweb = false\n\t}\n\n\tm.RecipientParam = map[string]string{}\n\tvar paramKey, paramValue string\n\tq, err := Db.Query(\"SELECT `key`, `value` FROM parameter WHERE recipient_id=?\", m.RecipientId)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer q.Close()\n\tfor q.Next() {\n\t\terr = q.Scan(&paramKey, &paramValue)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tm.RecipientParam[paramKey] = paramValue\n\t}\n\n\tm.RecipientParam[\"UnsubscribeUrl\"] = m.UnsubscribeWebLink()\n\tm.RecipientParam[\"StatPng\"] = m.StatPngLink()\n\tm.RecipientParam[\"RecipientEmail\"] = m.RecipientEmail\n\tm.RecipientParam[\"RecipientName\"] = m.RecipientName\n\tm.RecipientParam[\"CampaignId\"] = m.CampaignId\n\n\t\/\/ render subject\n\tsubj := template.New(\"subject\" + m.RecipientId)\n\tsubj, err = subj.Parse(m.CampaignSubject)\n\tif err != nil {\n\t\te := fmt.Sprintf(\"Error parse subject: %v\", err)\n\t\treturn e, err\n\t}\n\ttSubj := bytes.NewBufferString(\"\")\n\tsubj.Execute(tSubj, m.RecipientParam)\n\tm.CampaignSubject = tSubj.String()\n\n\tif !web {\n\t\tm.RecipientParam[\"WebUrl\"] = m.WebLink()\n\n\t\t\/\/ add statistic png\n\t\tif strings.Index(m.CampaignTemplate, \"{{.StatPng}}\") == -1 {\n\t\t\tif strings.Index(m.CampaignTemplate, \"<\/body>\") == -1 {\n\t\t\t\tm.CampaignTemplate = m.CampaignTemplate + \"<img src='{{.StatPng}}' border='0px' width='10px' height='10px'\/>\"\n\t\t\t} else {\n\t\t\t\tm.CampaignTemplate = strings.Replace(m.CampaignTemplate, \"<\/body>\", \"\\n<img src='{{.StatPng}}' border='0px' width='10px' height='10px'\/>\\n<\/body>\", -1)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Replace links for statistic\n\tre := regexp.MustCompile(`[hH][rR][eE][fF]\\s*?=\\s*?[\"']\\s*?(\\[.*?\\])?\\s*?(\\b[hH][tT]{2}[pP][sS]?\\b:\\\/\\\/\\b)(.*?)[\"']`)\n\tm.CampaignTemplate = re.ReplaceAllStringFunc(m.CampaignTemplate, func(str string) string {\n\t\t\/\/ get only url\n\t\ts := strings.Replace(str, `'`, \"\", -1)\n\t\ts = strings.Replace(s, `\"`, \"\", -1)\n\t\ts = strings.Replace(s, \"href=\", \"\", 1)\n\n\t\tswitch s {\n\t\tcase \"{{.WebUrl}}\":\n\t\t\treturn `href=\"` + m.RecipientParam[\"WebUrl\"] + `\"`\n\t\tcase \"{{.UnsubscribeUrl}}\":\n\t\t\treturn `href=\"` + m.RecipientParam[\"UnsubscribeUrl\"] + `\"`\n\t\tdefault:\n\t\t\t\/\/ template parameter in url\n\t\t\turlt := template.New(\"url\" + m.RecipientId)\n\t\t\turlt, err = urlt.Parse(s)\n\t\t\tif err != nil {\n\t\t\t\ts = fmt.Sprintf(\"Error parse url params: %v\", err)\n\t\t\t}\n\t\t\tu := bytes.NewBufferString(\"\")\n\t\t\turlt.Execute(u, m.RecipientParam)\n\t\t\ts = u.String()\n\n\t\t\treturn `href=\"` + m.RedirectLink(s) + `\"`\n\t\t}\n\t})\n\n\t\/\/replace static url to absolute\n\tm.CampaignTemplate = strings.Replace(m.CampaignTemplate, \"\\\"\/files\/\", \"\\\"\"+Config.Url+\"\/files\/\", -1)\n\tm.CampaignTemplate = strings.Replace(m.CampaignTemplate, \"'\/files\/\", \"'\"+Config.Url+\"'\/files\/\", -1)\n\n\t\/\/ render template\n\ttmpl := template.New(\"mail\" + m.RecipientId)\n\ttmpl, err = tmpl.Parse(m.CampaignTemplate)\n\tif err != nil {\n\t\te := fmt.Sprintf(\"Error parse template: %v\", err)\n\t\treturn e, err\n\t}\n\ttTempl := bytes.NewBufferString(\"\")\n\ttmpl.Execute(tTempl, m.RecipientParam)\n\treturn tTempl.String(), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package provisioning\n\nimport \"testing\"\nimport \"github.com\/wingedpig\/loom\"\n\ntype Config struct {\n\tloom.Config\n}\n\nfunc TestRun(t *testing.T) {\n\tc := &Config{loom.Config{User: \"ubuntu\", Host: \"TESTSERVER\",\n\t\tDisplayOutput: true, AbortOnError: true}}\n\t_, err := c.Run(\"ls -la\")\n\tif err != nil {\n\t\tt.Errorf(\"Run cmd error, %s\", err)\n\t}\n}\n\nfunc TestSudo(t *testing.T) {\n\tc := &Config{loom.Config{User: \"ubuntu\", Host: \"TESTSERVER\",\n\t\tDisplayOutput: true, AbortOnError: true}}\n\t_, err := c.Sudo(\"ls -la\")\n\tif err != nil {\n\t\tt.Errorf(\"Run sudo error, %s\", err)\n\t}\n}\n\nfunc TestPutString(t *testing.T) {\n\tc := &Config{loom.Config{User: \"ubuntu\", Host: \"TESTSERVER\",\n\t\tDisplayOutput: true, AbortOnError: true}}\n\terr := c.PutString(\"TestPutString\\nTestPutString\", \"~\/testputstring\")\n\tif err != nil {\n\t\tt.Errorf(\"Run putstring error, %s\", err)\n\t} else {\n\t\tc.Run(\"cat ~\/testputstring\")\n\t}\n}\n\nfunc TestPut(t *testing.T) {\n\tc := &Config{loom.Config{User: \"ubuntu\", Host: \"TESTSERVER\",\n\t\tDisplayOutput: true, AbortOnError: true}}\n\terr := c.Put(\".\/remote.iml\", \"~\/remote.iml\")\n\tif err != nil {\n\t\tt.Errorf(\"Run put error, %s\", err)\n\t} else {\n\t\tc.Run(\"cat ~\/remote.iml\")\n\t}\n}\n\n\/\/ Local support linux only\nfunc TestLocal(t *testing.T) {\n\tc := &Config{loom.Config{User: \"ubuntu\", Host: \"TESTSERVER\",\n\t\tDisplayOutput: true, AbortOnError: true}}\n\t_, err := c.Local(\"echo testlocal\")\n\tif err != nil {\n\t\tt.Errorf(\"Run local error, %s\", err)\n\t}\n}\n\nfunc TestGet(t *testing.T) {\n\tc := &Config{loom.Config{User: \"ubuntu\", Host: \"TESTSERVER\",\n\t\tDisplayOutput: true, AbortOnError: true}}\n\terr := c.Get(\"~\/remote.iml\", \".\/remote.iml1\")\n\tif err != nil {\n\t\tt.Errorf(\"Run get error, %s\", err)\n\t}\n}\n\nfunc TestDeploy(t *testing.T) {\n\tc, err := MakeConfig(\"ubuntu\", \"TESTSERVER\", true, true)\n\tif err != nil {\n\t\tt.Errorf(\"Make config error, %s\", err)\n\t}\n\tcmd := Cmd{AptCache: true, UseSudo: true, CmdLine: \"ls -la\"}\n\n\tvar i Provisioning\n\ti = c\n\ti.Execute(cmd)\n}\n<commit_msg>Add TODO<commit_after>package provisioning\n\nimport \"testing\"\nimport \"github.com\/wingedpig\/loom\"\n\ntype Config struct {\n\tloom.Config\n}\n\/\/ TODO: Refactor testing. the host: \"TESTSERVER\"\" is unreachable. Could not used for Travis-CI.\nfunc TestRun(t *testing.T) {\n\tc := &Config{loom.Config{User: \"ubuntu\", Host: \"TESTSERVER\",\n\t\tDisplayOutput: true, AbortOnError: true}}\n\t_, err := c.Run(\"ls -la\")\n\tif err != nil {\n\t\tt.Errorf(\"Run cmd error, %s\", err)\n\t}\n}\n\nfunc TestSudo(t *testing.T) {\n\tc := &Config{loom.Config{User: \"ubuntu\", Host: \"TESTSERVER\",\n\t\tDisplayOutput: true, AbortOnError: true}}\n\t_, err := c.Sudo(\"ls -la\")\n\tif err != nil {\n\t\tt.Errorf(\"Run sudo error, %s\", err)\n\t}\n}\n\nfunc TestPutString(t *testing.T) {\n\tc := &Config{loom.Config{User: \"ubuntu\", Host: \"TESTSERVER\",\n\t\tDisplayOutput: true, AbortOnError: true}}\n\terr := c.PutString(\"TestPutString\\nTestPutString\", \"~\/testputstring\")\n\tif err != nil {\n\t\tt.Errorf(\"Run putstring error, %s\", err)\n\t} else {\n\t\tc.Run(\"cat ~\/testputstring\")\n\t}\n}\n\nfunc TestPut(t *testing.T) {\n\tc := &Config{loom.Config{User: \"ubuntu\", Host: \"TESTSERVER\",\n\t\tDisplayOutput: true, AbortOnError: true}}\n\terr := c.Put(\".\/remote.iml\", \"~\/remote.iml\")\n\tif err != nil {\n\t\tt.Errorf(\"Run put error, %s\", err)\n\t} else {\n\t\tc.Run(\"cat ~\/remote.iml\")\n\t}\n}\n\n\/\/ Local support linux only\nfunc TestLocal(t *testing.T) {\n\tc := &Config{loom.Config{User: \"ubuntu\", Host: \"TESTSERVER\",\n\t\tDisplayOutput: true, AbortOnError: true}}\n\t_, err := c.Local(\"echo testlocal\")\n\tif err != nil {\n\t\tt.Errorf(\"Run local error, %s\", err)\n\t}\n}\n\nfunc TestGet(t *testing.T) {\n\tc := &Config{loom.Config{User: \"ubuntu\", Host: \"TESTSERVER\",\n\t\tDisplayOutput: true, AbortOnError: true}}\n\terr := c.Get(\"~\/remote.iml\", \".\/remote.iml1\")\n\tif err != nil {\n\t\tt.Errorf(\"Run get error, %s\", err)\n\t}\n}\n\nfunc TestDeploy(t *testing.T) {\n\tc, err := MakeConfig(\"ubuntu\", \"TESTSERVER\", true, true)\n\tif err != nil {\n\t\tt.Errorf(\"Make config error, %s\", err)\n\t}\n\tcmd := Cmd{AptCache: true, UseSudo: true, CmdLine: \"ls -la\"}\n\n\tvar i Provisioning\n\ti = c\n\ti.Execute(cmd)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Cockroach Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License. See the AUTHORS file\n\/\/ for names of contributors.\n\/\/\n\/\/ Author: Marc Berhault (marc@cockroachlabs.com)\n\n\/\/ This is a slight modification of: https:\/\/github.com\/docker\/machine\/blob\/master\/drivers\/google\/auth_util.go\n\/\/ The main difference is that we have a single path for tokens, whereas docker-machine\n\/\/ has --google-auth-token and a default store-path.\n\/\/ Original license follows:\n\n\/\/ Copyright 2014 Docker, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License. See the AUTHORS file\n\/\/ for names of contributors.\n\npackage google\n\nimport (\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"code.google.com\/p\/goauth2\/oauth\"\n\t\"github.com\/cockroachdb\/cockroach\/util\/log\"\n\tcompute \"google.golang.org\/api\/compute\/v1\"\n)\n\n\/\/ OAuth logic. This initializes a GCE Service with a OAuth token.\n\/\/ If the token (in Gob format) exists at 'authTokenPath', load it.\n\/\/ Otherwise, redirect to the Google consent screen to get a code,\n\/\/ generate a token from it, and save it in 'authTokenPath'.\n\/\/\n\/\/ The token file format must be the same as that used by docker-machine.\nconst (\n\tauthURL  = \"https:\/\/accounts.google.com\/o\/oauth2\/auth\"\n\ttokenURL = \"https:\/\/accounts.google.com\/o\/oauth2\/token\"\n\t\/\/ Cockroach client ID and secret.\n\t\/\/ TODO(marc): details show my personal email for now. We should have a more\n\t\/\/ generic user-facing one.\n\tclientID     = \"962032490974-5avmqm15uklkgus98c7f862dk23u5mdk.apps.googleusercontent.com\"\n\tclientSecret = \"SSytmGLypTUPnj6a3PeV8LiR\"\n\tredirectURI  = \"urn:ietf:wg:oauth:2.0:oob\"\n)\n\n\/\/ gobCache implements oauth.Cache.\n\/\/ Its value is the full path name to the cache file.\n\/\/ This is pretty much oauth.CacheFile, but with gob encoding.\ntype gobCache string\n\n\/\/ Token returns the cached token value, or an error if none is found.\nfunc (f gobCache) Token() (*oauth.Token, error) {\n\tfile, err := os.Open(string(f))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\ttok := &oauth.Token{}\n\tif err = gob.NewDecoder(file).Decode(tok); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tok, nil\n}\n\n\/\/ PutToken stores the given token in the cache.\n\/\/ TODO(marc): we should write to a tmp file and rename in case we error out.\nfunc (f gobCache) PutToken(tok *oauth.Token) error {\n\tfilename := string(f)\n\t\/\/ Create the parent directory if necessary.\n\tparent := filepath.Dir(filename)\n\terr := os.MkdirAll(parent, 0700)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := gob.NewEncoder(file).Encode(tok); err != nil {\n\t\tfile.Close()\n\t\treturn err\n\t}\n\tif err := file.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc newOauthClient(authTokenPath string) (*http.Client, error) {\n\tconfig := &oauth.Config{\n\t\tClientId:     clientID,\n\t\tClientSecret: clientSecret,\n\t\tScope:        compute.ComputeScope,\n\t\tAuthURL:      authURL,\n\t\tTokenURL:     tokenURL,\n\t\tRedirectURL:  redirectURI,\n\t\tTokenCache:   gobCache(authTokenPath),\n\t\t\/\/ Needed for refresh tokens:\n\t\tAccessType:     \"offline\",\n\t\tApprovalPrompt: \"force\",\n\t}\n\n\ttransport := &oauth.Transport{\n\t\tConfig:    config,\n\t\tTransport: http.DefaultTransport,\n\t}\n\n\terr := initTransport(transport)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn transport.Client(), nil\n}\n\nfunc initTransport(transport *oauth.Transport) error {\n\t\/\/ First: check the cache.\n\tif token, err := transport.Config.TokenCache.Token(); err == nil {\n\t\t\/\/ We have a token.\n\t\ttransport.Token = token\n\t\tif !token.Expired() {\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ Token is expired, attempt a refresh.\n\t\t\/\/ TODO(marc): we should check whether it expires soon (eg: 5 minutes).\n\t\terr := transport.Refresh()\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t\tlog.Infof(\"token expired and refresh failed, requesting new one\")\n\t}\n\n\t\/\/ Get a new token. Pops up a browser window (hopefully).\n\trandState := fmt.Sprintf(\"st%d\", time.Now().UnixNano())\n\tauthURL := transport.Config.AuthCodeURL(randState)\n\tlog.Infof(\"Opening auth URL in browser: %s\", authURL)\n\tlog.Infof(\"If the URL doesn't open please open it manually and copy the code here.\")\n\topenURL(authURL)\n\tcode := getCodeFromStdin()\n\n\t_, err := transport.Exchange(code)\n\tif err != nil {\n\t\tlog.Infof(\"problem exchanging code: %v\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc getCodeFromStdin() string {\n\tfmt.Print(\"Enter code: \")\n\tvar code string\n\tfmt.Scanln(&code)\n\treturn strings.Trim(code, \"\\n\")\n}\n\nfunc openURL(url string) {\n\ttry := []string{\"xdg-open\", \"google-chrome\", \"open\"}\n\tfor _, bin := range try {\n\t\terr := exec.Command(bin, url).Run()\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t}\n}\n<commit_msg>Always refresh OAuth token<commit_after>\/\/ Copyright 2015 The Cockroach Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License. See the AUTHORS file\n\/\/ for names of contributors.\n\/\/\n\/\/ Author: Marc Berhault (marc@cockroachlabs.com)\n\n\/\/ This is a slight modification of: https:\/\/github.com\/docker\/machine\/blob\/master\/drivers\/google\/auth_util.go\n\/\/ The main difference is that we have a single path for tokens, whereas docker-machine\n\/\/ has --google-auth-token and a default store-path.\n\/\/ Original license follows:\n\n\/\/ Copyright 2014 Docker, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\/\/ implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License. See the AUTHORS file\n\/\/ for names of contributors.\n\npackage google\n\nimport (\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"code.google.com\/p\/goauth2\/oauth\"\n\t\"github.com\/cockroachdb\/cockroach\/util\/log\"\n\tcompute \"google.golang.org\/api\/compute\/v1\"\n)\n\n\/\/ OAuth logic. This initializes a GCE Service with a OAuth token.\n\/\/ If the token (in Gob format) exists at 'authTokenPath', load it.\n\/\/ Otherwise, redirect to the Google consent screen to get a code,\n\/\/ generate a token from it, and save it in 'authTokenPath'.\n\/\/\n\/\/ The token file format must be the same as that used by docker-machine.\nconst (\n\tauthURL  = \"https:\/\/accounts.google.com\/o\/oauth2\/auth\"\n\ttokenURL = \"https:\/\/accounts.google.com\/o\/oauth2\/token\"\n\t\/\/ Cockroach client ID and secret.\n\t\/\/ TODO(marc): details show my personal email for now. We should have a more\n\t\/\/ generic user-facing one.\n\tclientID     = \"962032490974-5avmqm15uklkgus98c7f862dk23u5mdk.apps.googleusercontent.com\"\n\tclientSecret = \"SSytmGLypTUPnj6a3PeV8LiR\"\n\tredirectURI  = \"urn:ietf:wg:oauth:2.0:oob\"\n)\n\n\/\/ gobCache implements oauth.Cache.\n\/\/ Its value is the full path name to the cache file.\n\/\/ This is pretty much oauth.CacheFile, but with gob encoding.\ntype gobCache string\n\n\/\/ Token returns the cached token value, or an error if none is found.\nfunc (f gobCache) Token() (*oauth.Token, error) {\n\tfile, err := os.Open(string(f))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer file.Close()\n\ttok := &oauth.Token{}\n\tif err = gob.NewDecoder(file).Decode(tok); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tok, nil\n}\n\n\/\/ PutToken stores the given token in the cache.\n\/\/ TODO(marc): we should write to a tmp file and rename in case we error out.\nfunc (f gobCache) PutToken(tok *oauth.Token) error {\n\tfilename := string(f)\n\t\/\/ Create the parent directory if necessary.\n\tparent := filepath.Dir(filename)\n\terr := os.MkdirAll(parent, 0700)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := gob.NewEncoder(file).Encode(tok); err != nil {\n\t\tfile.Close()\n\t\treturn err\n\t}\n\tif err := file.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc newOauthClient(authTokenPath string) (*http.Client, error) {\n\tconfig := &oauth.Config{\n\t\tClientId:     clientID,\n\t\tClientSecret: clientSecret,\n\t\tScope:        compute.ComputeScope,\n\t\tAuthURL:      authURL,\n\t\tTokenURL:     tokenURL,\n\t\tRedirectURL:  redirectURI,\n\t\tTokenCache:   gobCache(authTokenPath),\n\t\t\/\/ Needed for refresh tokens:\n\t\tAccessType:     \"offline\",\n\t\tApprovalPrompt: \"force\",\n\t}\n\n\ttransport := &oauth.Transport{\n\t\tConfig:    config,\n\t\tTransport: http.DefaultTransport,\n\t}\n\n\terr := initTransport(transport)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn transport.Client(), nil\n}\n\nfunc initTransport(transport *oauth.Transport) error {\n\t\/\/ First: check the cache.\n\tif token, err := transport.Config.TokenCache.Token(); err == nil {\n\t\t\/\/ We have a token, refresh it. The lifetime is 1h, so we always\n\t\t\/\/ refresh to ensure lengthy commands do not time out.\n\t\ttransport.Token = token\n\t\terr := transport.Refresh()\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\t\tlog.Infof(\"token refresh failed, requesting new one\")\n\t}\n\n\t\/\/ Get a new token. Pops up a browser window (hopefully).\n\trandState := fmt.Sprintf(\"st%d\", time.Now().UnixNano())\n\tauthURL := transport.Config.AuthCodeURL(randState)\n\tlog.Infof(\"Opening auth URL in browser: %s\", authURL)\n\tlog.Infof(\"If the URL doesn't open please open it manually and copy the code here.\")\n\topenURL(authURL)\n\tcode := getCodeFromStdin()\n\n\t_, err := transport.Exchange(code)\n\tif err != nil {\n\t\tlog.Infof(\"problem exchanging code: %v\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc getCodeFromStdin() string {\n\tfmt.Print(\"Enter code: \")\n\tvar code string\n\tfmt.Scanln(&code)\n\treturn strings.Trim(code, \"\\n\")\n}\n\nfunc openURL(url string) {\n\ttry := []string{\"xdg-open\", \"google-chrome\", \"open\"}\n\tfor _, bin := range try {\n\t\terr := exec.Command(bin, url).Run()\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package shell\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/master_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/needle\"\n)\n\nfunc init() {\n\tcommands = append(commands, &commandVolumeBalance{})\n}\n\ntype commandVolumeBalance struct {\n}\n\nfunc (c *commandVolumeBalance) Name() string {\n\treturn \"volume.balance\"\n}\n\nfunc (c *commandVolumeBalance) Help() string {\n\treturn `balance all volumes among volume servers\n\n\tvolume.balance [-c collectionName] [-f]\n\n\tAlgorithm:\n\tFor each type of volume server (different max volume count limit){\n\t\tfor each collection {\n\t\t\tbalanceWritableVolumes()\n\t\t\tbalanceReadOnlyVolumes()\n\t\t}\n\t\tfor all volumes {\n\t\t\tbalanceWritableVolumes()\n\t\t\tbalanceReadOnlyVolumes()\n\t\t}\n\t}\n\n\tfunc balanceWritableVolumes(){\n\t\tidealWritableVolumes = totalWritableVolumes \/ numVolumeServers\n\t\tfor {\n\t\t\tsort all volume servers ordered by the number of local writable volumes\n\t\t\tpick the volume server A with the lowest number of writable volumes x\n\t\t\tpick the volume server B with the highest number of writable volumes y\n\t\t\tif y > idealWritableVolumes and x +1 <= idealWritableVolumes {\n\t\t\t\tif B has a writable volume id v that A does not have {\n\t\t\t\t\tmove writable volume v from A to B\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfunc balanceReadOnlyVolumes(){\n\t\t\/\/similar to balanceWritableVolumes\n\t}\n\n`\n}\n\nfunc (c *commandVolumeBalance) Do(args []string, commandEnv *commandEnv, writer io.Writer) (err error) {\n\n\tbalanceCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)\n\tcollection := balanceCommand.String(\"c\", \"EACH_COLLECTION\", \"collection name, or use \\\"ALL_COLLECTIONS\\\" across collections, \\\"EACH_COLLECTION\\\" for each collection\")\n\tdc := balanceCommand.String(\"dataCenter\", \"\", \"only apply the balancing for this dataCenter\")\n\tapplyBalancing := balanceCommand.Bool(\"f\", false, \"apply the balancing plan.\")\n\tif err = balanceCommand.Parse(args); err != nil {\n\t\treturn nil\n\t}\n\n\tvar resp *master_pb.VolumeListResponse\n\tctx := context.Background()\n\terr = commandEnv.masterClient.WithClient(ctx, func(client master_pb.SeaweedClient) error {\n\t\tresp, err = client.VolumeList(ctx, &master_pb.VolumeListRequest{})\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttypeToNodes := collectVolumeServersByType(resp.TopologyInfo, *dc)\n\tfor _, volumeServers := range typeToNodes {\n\t\tif len(volumeServers) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif *collection == \"EACH_COLLECTION\" {\n\t\t\tcollections, err := ListCollectionNames(commandEnv)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, c := range collections {\n\t\t\t\tif err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, c, *applyBalancing); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t} else if *collection == \"ALL\" {\n\t\t\tif err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, \"ALL\", *applyBalancing); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, *collection, *applyBalancing); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\treturn nil\n}\n\nfunc balanceVolumeServers(commandEnv *commandEnv, dataNodeInfos []*master_pb.DataNodeInfo, volumeSizeLimit uint64, collection string, applyBalancing bool) error {\n\tvar nodes []*Node\n\tfor _, dn := range dataNodeInfos {\n\t\tnodes = append(nodes, &Node{\n\t\t\tinfo: dn,\n\t\t})\n\t}\n\n\t\/\/ balance writable volumes\n\tfor _, n := range nodes {\n\t\tn.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {\n\t\t\tif collection != \"ALL\" {\n\t\t\t\tif v.Collection != collection {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn !v.ReadOnly && v.Size < volumeSizeLimit\n\t\t})\n\t}\n\tif err := balanceSelectedVolume(commandEnv, nodes, sortWritableVolumes, applyBalancing); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ balance readable volumes\n\tfor _, n := range nodes {\n\t\tn.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {\n\t\t\tif collection != \"ALL\" {\n\t\t\t\tif v.Collection != collection {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn v.ReadOnly || v.Size >= volumeSizeLimit\n\t\t})\n\t}\n\tif err := balanceSelectedVolume(commandEnv, nodes, sortReadOnlyVolumes, applyBalancing); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc collectVolumeServersByType(t *master_pb.TopologyInfo, selectedDataCenter string) (typeToNodes map[uint64][]*master_pb.DataNodeInfo) {\n\ttypeToNodes = make(map[uint64][]*master_pb.DataNodeInfo)\n\tfor _, dc := range t.DataCenterInfos {\n\t\tif selectedDataCenter != \"\" && dc.Id != selectedDataCenter {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, r := range dc.RackInfos {\n\t\t\tfor _, dn := range r.DataNodeInfos {\n\t\t\t\ttypeToNodes[dn.MaxVolumeCount] = append(typeToNodes[dn.MaxVolumeCount], dn)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\ntype Node struct {\n\tinfo            *master_pb.DataNodeInfo\n\tselectedVolumes map[uint32]*master_pb.VolumeInformationMessage\n}\n\nfunc sortWritableVolumes(volumes []*master_pb.VolumeInformationMessage) {\n\tsort.Slice(volumes, func(i, j int) bool {\n\t\treturn volumes[i].Size < volumes[j].Size\n\t})\n}\n\nfunc sortReadOnlyVolumes(volumes []*master_pb.VolumeInformationMessage) {\n\tsort.Slice(volumes, func(i, j int) bool {\n\t\treturn volumes[i].Id < volumes[j].Id\n\t})\n}\n\nfunc balanceSelectedVolume(commandEnv *commandEnv, nodes []*Node, sortCandidatesFn func(volumes []*master_pb.VolumeInformationMessage), applyBalancing bool) error {\n\tselectedVolumeCount := 0\n\tfor _, dn := range nodes {\n\t\tselectedVolumeCount += len(dn.selectedVolumes)\n\t}\n\n\tidealSelectedVolumes := selectedVolumeCount \/ len(nodes)\n\n\thasMove := true\n\n\tfor hasMove {\n\t\thasMove = false\n\t\tsort.Slice(nodes, func(i, j int) bool {\n\t\t\treturn len(nodes[i].selectedVolumes) < len(nodes[j].selectedVolumes)\n\t\t})\n\t\temptyNode, fullNode := nodes[0], nodes[len(nodes)-1]\n\t\tif len(fullNode.selectedVolumes) > idealSelectedVolumes && len(emptyNode.selectedVolumes)+1 <= idealSelectedVolumes {\n\n\t\t\t\/\/ sort the volumes to move\n\t\t\tvar candidateVolumes []*master_pb.VolumeInformationMessage\n\t\t\tfor _, v := range fullNode.selectedVolumes {\n\t\t\t\tcandidateVolumes = append(candidateVolumes, v)\n\t\t\t}\n\t\t\tsortCandidatesFn(candidateVolumes)\n\n\t\t\tfor _, v := range candidateVolumes {\n\t\t\t\tif _, found := emptyNode.selectedVolumes[v.Id]; !found {\n\t\t\t\t\tif err := moveVolume(commandEnv, v, fullNode, emptyNode, applyBalancing); err == nil {\n\t\t\t\t\t\tdelete(fullNode.selectedVolumes, v.Id)\n\t\t\t\t\t\temptyNode.selectedVolumes[v.Id] = v\n\t\t\t\t\t\thasMove = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc moveVolume(commandEnv *commandEnv, v *master_pb.VolumeInformationMessage, fullNode *Node, emptyNode *Node, applyBalancing bool) error {\n\tcollectionPrefix := v.Collection + \"_\"\n\tif v.Collection == \"\" {\n\t\tcollectionPrefix = \"\"\n\t}\n\tfmt.Fprintf(os.Stdout, \"moving volume %s%d %s => %s\\n\", collectionPrefix, v.Id, fullNode.info.Id, emptyNode.info.Id)\n\tif applyBalancing {\n\t\tctx := context.Background()\n\t\treturn LiveMoveVolume(ctx, commandEnv.option.GrpcDialOption, needle.VolumeId(v.Id), fullNode.info.Id, emptyNode.info.Id, 5*time.Second)\n\t}\n\treturn nil\n}\n\nfunc (node *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {\n\tnode.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)\n\tfor _, v := range node.info.VolumeInfos {\n\t\tif fn(v) {\n\t\t\tnode.selectedVolumes[v.Id] = v\n\t\t}\n\t}\n}\n<commit_msg>adjust help message<commit_after>package shell\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/master_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/needle\"\n)\n\nfunc init() {\n\tcommands = append(commands, &commandVolumeBalance{})\n}\n\ntype commandVolumeBalance struct {\n}\n\nfunc (c *commandVolumeBalance) Name() string {\n\treturn \"volume.balance\"\n}\n\nfunc (c *commandVolumeBalance) Help() string {\n\treturn `balance all volumes among volume servers\n\n\tvolume.balance [-c ALL|EACH_COLLECTION|<collection_name>] [-f] [-dataCenter=<data_center_name>]\n\n\tAlgorithm:\n\n\tFor each type of volume server (different max volume count limit){\n\t\tfor each collection {\n\t\t\tbalanceWritableVolumes()\n\t\t\tbalanceReadOnlyVolumes()\n\t\t}\n\t}\n\n\tfunc balanceWritableVolumes(){\n\t\tidealWritableVolumes = totalWritableVolumes \/ numVolumeServers\n\t\tfor {\n\t\t\tsort all volume servers ordered by the number of local writable volumes\n\t\t\tpick the volume server A with the lowest number of writable volumes x\n\t\t\tpick the volume server B with the highest number of writable volumes y\n\t\t\tif y > idealWritableVolumes and x +1 <= idealWritableVolumes {\n\t\t\t\tif B has a writable volume id v that A does not have {\n\t\t\t\t\tmove writable volume v from A to B\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfunc balanceReadOnlyVolumes(){\n\t\t\/\/similar to balanceWritableVolumes\n\t}\n\n`\n}\n\nfunc (c *commandVolumeBalance) Do(args []string, commandEnv *commandEnv, writer io.Writer) (err error) {\n\n\tbalanceCommand := flag.NewFlagSet(c.Name(), flag.ContinueOnError)\n\tcollection := balanceCommand.String(\"c\", \"EACH_COLLECTION\", \"collection name, or use \\\"ALL_COLLECTIONS\\\" across collections, \\\"EACH_COLLECTION\\\" for each collection\")\n\tdc := balanceCommand.String(\"dataCenter\", \"\", \"only apply the balancing for this dataCenter\")\n\tapplyBalancing := balanceCommand.Bool(\"f\", false, \"apply the balancing plan.\")\n\tif err = balanceCommand.Parse(args); err != nil {\n\t\treturn nil\n\t}\n\n\tvar resp *master_pb.VolumeListResponse\n\tctx := context.Background()\n\terr = commandEnv.masterClient.WithClient(ctx, func(client master_pb.SeaweedClient) error {\n\t\tresp, err = client.VolumeList(ctx, &master_pb.VolumeListRequest{})\n\t\treturn err\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttypeToNodes := collectVolumeServersByType(resp.TopologyInfo, *dc)\n\tfor _, volumeServers := range typeToNodes {\n\t\tif len(volumeServers) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif *collection == \"EACH_COLLECTION\" {\n\t\t\tcollections, err := ListCollectionNames(commandEnv)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfor _, c := range collections {\n\t\t\t\tif err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, c, *applyBalancing); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t} else if *collection == \"ALL\" {\n\t\t\tif err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, \"ALL\", *applyBalancing); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif err = balanceVolumeServers(commandEnv, volumeServers, resp.VolumeSizeLimitMb*1024*1024, *collection, *applyBalancing); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t}\n\treturn nil\n}\n\nfunc balanceVolumeServers(commandEnv *commandEnv, dataNodeInfos []*master_pb.DataNodeInfo, volumeSizeLimit uint64, collection string, applyBalancing bool) error {\n\tvar nodes []*Node\n\tfor _, dn := range dataNodeInfos {\n\t\tnodes = append(nodes, &Node{\n\t\t\tinfo: dn,\n\t\t})\n\t}\n\n\t\/\/ balance writable volumes\n\tfor _, n := range nodes {\n\t\tn.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {\n\t\t\tif collection != \"ALL\" {\n\t\t\t\tif v.Collection != collection {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn !v.ReadOnly && v.Size < volumeSizeLimit\n\t\t})\n\t}\n\tif err := balanceSelectedVolume(commandEnv, nodes, sortWritableVolumes, applyBalancing); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ balance readable volumes\n\tfor _, n := range nodes {\n\t\tn.selectVolumes(func(v *master_pb.VolumeInformationMessage) bool {\n\t\t\tif collection != \"ALL\" {\n\t\t\t\tif v.Collection != collection {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn v.ReadOnly || v.Size >= volumeSizeLimit\n\t\t})\n\t}\n\tif err := balanceSelectedVolume(commandEnv, nodes, sortReadOnlyVolumes, applyBalancing); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc collectVolumeServersByType(t *master_pb.TopologyInfo, selectedDataCenter string) (typeToNodes map[uint64][]*master_pb.DataNodeInfo) {\n\ttypeToNodes = make(map[uint64][]*master_pb.DataNodeInfo)\n\tfor _, dc := range t.DataCenterInfos {\n\t\tif selectedDataCenter != \"\" && dc.Id != selectedDataCenter {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, r := range dc.RackInfos {\n\t\t\tfor _, dn := range r.DataNodeInfos {\n\t\t\t\ttypeToNodes[dn.MaxVolumeCount] = append(typeToNodes[dn.MaxVolumeCount], dn)\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\ntype Node struct {\n\tinfo            *master_pb.DataNodeInfo\n\tselectedVolumes map[uint32]*master_pb.VolumeInformationMessage\n}\n\nfunc sortWritableVolumes(volumes []*master_pb.VolumeInformationMessage) {\n\tsort.Slice(volumes, func(i, j int) bool {\n\t\treturn volumes[i].Size < volumes[j].Size\n\t})\n}\n\nfunc sortReadOnlyVolumes(volumes []*master_pb.VolumeInformationMessage) {\n\tsort.Slice(volumes, func(i, j int) bool {\n\t\treturn volumes[i].Id < volumes[j].Id\n\t})\n}\n\nfunc balanceSelectedVolume(commandEnv *commandEnv, nodes []*Node, sortCandidatesFn func(volumes []*master_pb.VolumeInformationMessage), applyBalancing bool) error {\n\tselectedVolumeCount := 0\n\tfor _, dn := range nodes {\n\t\tselectedVolumeCount += len(dn.selectedVolumes)\n\t}\n\n\tidealSelectedVolumes := selectedVolumeCount \/ len(nodes)\n\n\thasMove := true\n\n\tfor hasMove {\n\t\thasMove = false\n\t\tsort.Slice(nodes, func(i, j int) bool {\n\t\t\treturn len(nodes[i].selectedVolumes) < len(nodes[j].selectedVolumes)\n\t\t})\n\t\temptyNode, fullNode := nodes[0], nodes[len(nodes)-1]\n\t\tif len(fullNode.selectedVolumes) > idealSelectedVolumes && len(emptyNode.selectedVolumes)+1 <= idealSelectedVolumes {\n\n\t\t\t\/\/ sort the volumes to move\n\t\t\tvar candidateVolumes []*master_pb.VolumeInformationMessage\n\t\t\tfor _, v := range fullNode.selectedVolumes {\n\t\t\t\tcandidateVolumes = append(candidateVolumes, v)\n\t\t\t}\n\t\t\tsortCandidatesFn(candidateVolumes)\n\n\t\t\tfor _, v := range candidateVolumes {\n\t\t\t\tif _, found := emptyNode.selectedVolumes[v.Id]; !found {\n\t\t\t\t\tif err := moveVolume(commandEnv, v, fullNode, emptyNode, applyBalancing); err == nil {\n\t\t\t\t\t\tdelete(fullNode.selectedVolumes, v.Id)\n\t\t\t\t\t\temptyNode.selectedVolumes[v.Id] = v\n\t\t\t\t\t\thasMove = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc moveVolume(commandEnv *commandEnv, v *master_pb.VolumeInformationMessage, fullNode *Node, emptyNode *Node, applyBalancing bool) error {\n\tcollectionPrefix := v.Collection + \"_\"\n\tif v.Collection == \"\" {\n\t\tcollectionPrefix = \"\"\n\t}\n\tfmt.Fprintf(os.Stdout, \"moving volume %s%d %s => %s\\n\", collectionPrefix, v.Id, fullNode.info.Id, emptyNode.info.Id)\n\tif applyBalancing {\n\t\tctx := context.Background()\n\t\treturn LiveMoveVolume(ctx, commandEnv.option.GrpcDialOption, needle.VolumeId(v.Id), fullNode.info.Id, emptyNode.info.Id, 5*time.Second)\n\t}\n\treturn nil\n}\n\nfunc (node *Node) selectVolumes(fn func(v *master_pb.VolumeInformationMessage) bool) {\n\tnode.selectedVolumes = make(map[uint32]*master_pb.VolumeInformationMessage)\n\tfor _, v := range node.info.VolumeInfos {\n\t\tif fn(v) {\n\t\t\tnode.selectedVolumes[v.Id] = v\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gardenhealth_test\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/executor\/gardenhealth\"\n\t\"github.com\/cloudfoundry\/dropsonde\/metric_sender\/fake\"\n\t\"github.com\/cloudfoundry\/dropsonde\/metrics\"\n\t\"github.com\/tedsuo\/ifrit\"\n\t\"github.com\/tedsuo\/ifrit\/ginkgomon\"\n\n\t\"code.cloudfoundry.org\/clock\/fakeclock\"\n\tfakeexecutor \"code.cloudfoundry.org\/executor\/fakes\"\n\t\"code.cloudfoundry.org\/executor\/gardenhealth\/fakegardenhealth\"\n\t\"code.cloudfoundry.org\/lager\"\n\t\"code.cloudfoundry.org\/lager\/lagertest\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n)\n\nvar _ = Describe(\"Runner\", func() {\n\tvar (\n\t\trunner                          *gardenhealth.Runner\n\t\tprocess                         ifrit.Process\n\t\tlogger                          *lagertest.TestLogger\n\t\tchecker                         *fakegardenhealth.FakeChecker\n\t\texecutorClient                  *fakeexecutor.FakeClient\n\t\tsender                          *fake.FakeMetricSender\n\t\tfakeClock                       *fakeclock.FakeClock\n\t\tcheckInterval, emissionInterval time.Duration\n\t\ttimeoutDuration                 time.Duration\n\t)\n\n\tBeforeEach(func() {\n\t\tlogger = lagertest.NewTestLogger(\"test\")\n\t\tchecker = &fakegardenhealth.FakeChecker{}\n\t\texecutorClient = &fakeexecutor.FakeClient{}\n\t\tfakeClock = fakeclock.NewFakeClock(time.Now())\n\t\tcheckInterval = 2 * time.Minute\n\t\ttimeoutDuration = 1 * time.Minute\n\t\temissionInterval = 30 * time.Second\n\n\t\tsender = fake.NewFakeMetricSender()\n\t\tmetrics.Initialize(sender, nil)\n\t})\n\n\tJustBeforeEach(func() {\n\t\trunner = gardenhealth.NewRunner(checkInterval, emissionInterval, timeoutDuration, logger, checker, executorClient, fakeClock)\n\t\tprocess = ifrit.Background(runner)\n\t})\n\n\tAfterEach(func() {\n\t\tginkgomon.Interrupt(process)\n\t})\n\n\tDescribe(\"Run\", func() {\n\t\tContext(\"When garden is immediately unhealthy\", func() {\n\t\t\tContext(\"because the health check fails\", func() {\n\t\t\t\tvar checkErr = gardenhealth.UnrecoverableError(\"nope\")\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tchecker.HealthcheckReturns(checkErr)\n\t\t\t\t\texecutorClient.HealthyReturns(false)\n\t\t\t\t})\n\n\t\t\t\tIt(\"fails without becoming ready\", func() {\n\t\t\t\t\tEventually(process.Wait()).Should(Receive(Equal(checkErr)))\n\t\t\t\t\tConsistently(process.Ready()).ShouldNot(BeClosed())\n\t\t\t\t})\n\n\t\t\t\tIt(\"emits a metric for unhealthy cell\", func() {\n\t\t\t\t\tEventually(process.Wait()).Should(Receive(Equal(checkErr)))\n\t\t\t\t\tEventually(func() float64 {\n\t\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t\t}).Should(Equal(float64(1)))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"because the health check timed out\", func() {\n\t\t\t\tvar blockHealthcheck chan struct{}\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tblockHealthcheck = make(chan struct{})\n\t\t\t\t\tchecker.HealthcheckStub = func(lager.Logger) error {\n\t\t\t\t\t\t<-blockHealthcheck\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t})\n\n\t\t\t\tJustBeforeEach(func() {\n\t\t\t\t\tfakeClock.WaitForWatcherAndIncrement(timeoutDuration)\n\t\t\t\t})\n\n\t\t\t\tAfterEach(func() {\n\t\t\t\t\t\/\/ Send to the channel to eliminate the race\n\t\t\t\t\tblockHealthcheck <- struct{}{}\n\t\t\t\t\tclose(blockHealthcheck)\n\t\t\t\t\tblockHealthcheck = nil\n\t\t\t\t})\n\n\t\t\t\tIt(\"fails without becoming ready\", func() {\n\t\t\t\t\tEventually(process.Wait()).Should(Receive(Equal(gardenhealth.HealthcheckTimeoutError{})))\n\t\t\t\t\tConsistently(process.Ready()).ShouldNot(BeClosed())\n\t\t\t\t})\n\n\t\t\t\tIt(\"emits a metric for unhealthy cell\", func() {\n\t\t\t\t\tEventually(process.Wait()).Should(Receive(Equal(gardenhealth.HealthcheckTimeoutError{})))\n\t\t\t\t\tEventually(func() float64 {\n\t\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t\t}).Should(Equal(float64(1)))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tContext(\"When garden is healthy\", func() {\n\t\t\tIt(\"sets healthy to true only once\", func() {\n\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(1))\n\t\t\t\t_, healthy := executorClient.SetHealthyArgsForCall(0)\n\t\t\t\tExpect(healthy).Should(Equal(true))\n\t\t\t\tExpect(executorClient.SetHealthyCallCount()).To(Equal(1))\n\t\t\t})\n\n\t\t\tIt(\"continues to check at the correct interval\", func() {\n\t\t\t\tEventually(checker.HealthcheckCallCount).Should(Equal(1))\n\t\t\t\tEventually(process.Ready()).Should(BeClosed())\n\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(checkInterval)\n\t\t\t\tEventually(checker.HealthcheckCallCount).Should(Equal(2))\n\t\t\t\tEventually(logger).Should(gbytes.Say(\"check-complete\"))\n\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(checkInterval)\n\t\t\t\tEventually(checker.HealthcheckCallCount).Should(Equal(3))\n\t\t\t\tEventually(logger).Should(gbytes.Say(\"check-complete\"))\n\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(checkInterval)\n\t\t\t\tEventually(checker.HealthcheckCallCount).Should(Equal(4))\n\t\t\t\tEventually(logger).Should(gbytes.Say(\"check-complete\"))\n\t\t\t})\n\n\t\t\tIt(\"emits a metric for healthy cell\", func() {\n\t\t\t\tEventually(func () float64 {\n\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t}).Should(Equal(float64(0)))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when garden is intermittently healthy\", func() {\n\t\t\tvar checkErr = errors.New(\"nope\")\n\n\t\t\tBeforeEach(func() {\n\t\t\t\texecutorClient.HealthyReturns(true)\n\t\t\t})\n\n\t\t\tIt(\"Sets healthy to false after it fails, then to true after success and emits respective metrics\", func() {\n\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(1))\n\t\t\t\t_, healthy := executorClient.SetHealthyArgsForCall(0)\n\t\t\t\tExpect(healthy).Should(Equal(true))\n\t\t\t\tExpect(sender.GetValue(\"UnhealthyCell\").Value).To(Equal(float64(0)))\n\n\t\t\t\tchecker.HealthcheckReturns(checkErr)\n\t\t\t\texecutorClient.HealthyReturns(false)\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(checkInterval)\n\n\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(2))\n\t\t\t\t_, healthy = executorClient.SetHealthyArgsForCall(1)\n\t\t\t\tExpect(healthy).Should(Equal(false))\n\t\t\t\tExpect(sender.GetValue(\"UnhealthyCell\").Value).To(Equal(float64(1)))\n\n\t\t\t\tchecker.HealthcheckReturns(nil)\n\t\t\t\texecutorClient.HealthyReturns(true)\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(checkInterval)\n\n\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(3))\n\t\t\t\t_, healthy = executorClient.SetHealthyArgsForCall(2)\n\t\t\t\tExpect(healthy).Should(Equal(true))\n\t\t\t\tExpect(sender.GetValue(\"UnhealthyCell\").Value).To(Equal(float64(0)))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"When the healthcheck times out\", func() {\n\t\t\tvar blockHealthcheck chan struct{}\n\n\t\t\tBeforeEach(func() {\n\t\t\t\tblockHealthcheck = make(chan struct{})\n\t\t\t\tchecker.HealthcheckStub = func(lager.Logger) error {\n\t\t\t\t\tlogger.Info(\"blocking\")\n\t\t\t\t\t<-blockHealthcheck\n\t\t\t\t\tlogger.Info(\"unblocking\")\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tAfterEach(func() {\n\t\t\t\tclose(blockHealthcheck)\n\t\t\t})\n\n\t\t\tIt(\"sets the executor to unhealthy and emits the unhealthy metric\", func() {\n\t\t\t\tEventually(blockHealthcheck).Should(BeSent(struct{}{}))\n\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(1))\n\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(checkInterval)\n\t\t\t\tEventually(checker.HealthcheckCallCount).Should(Equal(2))\n\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(timeoutDuration)\n\n\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(2))\n\t\t\t\t_, healthy := executorClient.SetHealthyArgsForCall(1)\n\t\t\t\tExpect(healthy).Should(Equal(false))\n\t\t\t\tEventually(func() float64 {\n\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t}).Should(Equal(float64(1)))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"When the runner is signaled\", func() {\n\t\t\tContext(\"during the initial health check\", func() {\n\t\t\t\tvar blockHealthcheck chan struct{}\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tblockHealthcheck = make(chan struct{})\n\t\t\t\t\tchecker.HealthcheckStub = func(lager.Logger) error {\n\t\t\t\t\t\t<-blockHealthcheck\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t})\n\n\t\t\t\tJustBeforeEach(func() {\n\t\t\t\t\tprocess.Signal(os.Interrupt)\n\t\t\t\t})\n\n\t\t\t\tIt(\"exits with no error\", func() {\n\t\t\t\t\tEventually(process.Wait()).Should(Receive(BeNil()))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"After the initial health check\", func() {\n\t\t\t\tIt(\"exits imediately with no error\", func() {\n\t\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(1))\n\n\t\t\t\t\tprocess.Signal(os.Interrupt)\n\t\t\t\t\tEventually(process.Wait()).Should(Receive(BeNil()))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tContext(\"UnhealthyCell metric emission\", func() {\n\t\t\tIt(\"emits the UnhealthyCell every emitInterval\", func() {\n\t\t\t\tEventually(executorClient.HealthyCallCount).Should(Equal(1))\n\t\t\t\tEventually(func() float64 {\n\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t}).Should(Equal(float64(1)))\n\n\t\t\t\texecutorClient.HealthyReturns(true)\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(emissionInterval)\n\n\t\t\t\tEventually(executorClient.HealthyCallCount).Should(Equal(2))\n\t\t\t\tEventually(func() float64 {\n\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t}).Should(Equal(float64(0)))\n\n\t\t\t\texecutorClient.HealthyReturns(false)\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(emissionInterval)\n\n\t\t\t\tEventually(executorClient.HealthyCallCount).Should(Equal(3))\n\t\t\t\tEventually(func() float64 {\n\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t}).Should(Equal(float64(1)))\n\t\t\t})\n\t\t})\n\t})\n})\n<commit_msg>Fix flaky test<commit_after>package gardenhealth_test\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/executor\/gardenhealth\"\n\t\"github.com\/cloudfoundry\/dropsonde\/metric_sender\/fake\"\n\t\"github.com\/cloudfoundry\/dropsonde\/metrics\"\n\t\"github.com\/tedsuo\/ifrit\"\n\t\"github.com\/tedsuo\/ifrit\/ginkgomon\"\n\n\t\"code.cloudfoundry.org\/clock\/fakeclock\"\n\tfakeexecutor \"code.cloudfoundry.org\/executor\/fakes\"\n\t\"code.cloudfoundry.org\/executor\/gardenhealth\/fakegardenhealth\"\n\t\"code.cloudfoundry.org\/lager\"\n\t\"code.cloudfoundry.org\/lager\/lagertest\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gbytes\"\n)\n\nvar _ = Describe(\"Runner\", func() {\n\tvar (\n\t\trunner                          *gardenhealth.Runner\n\t\tprocess                         ifrit.Process\n\t\tlogger                          *lagertest.TestLogger\n\t\tchecker                         *fakegardenhealth.FakeChecker\n\t\texecutorClient                  *fakeexecutor.FakeClient\n\t\tsender                          *fake.FakeMetricSender\n\t\tfakeClock                       *fakeclock.FakeClock\n\t\tcheckInterval, emissionInterval time.Duration\n\t\ttimeoutDuration                 time.Duration\n\t)\n\n\tBeforeEach(func() {\n\t\tlogger = lagertest.NewTestLogger(\"test\")\n\t\tchecker = &fakegardenhealth.FakeChecker{}\n\t\texecutorClient = &fakeexecutor.FakeClient{}\n\t\tfakeClock = fakeclock.NewFakeClock(time.Now())\n\t\tcheckInterval = 2 * time.Minute\n\t\ttimeoutDuration = 1 * time.Minute\n\t\temissionInterval = 30 * time.Second\n\n\t\tsender = fake.NewFakeMetricSender()\n\t\tmetrics.Initialize(sender, nil)\n\t})\n\n\tJustBeforeEach(func() {\n\t\trunner = gardenhealth.NewRunner(checkInterval, emissionInterval, timeoutDuration, logger, checker, executorClient, fakeClock)\n\t\tprocess = ifrit.Background(runner)\n\t})\n\n\tAfterEach(func() {\n\t\tginkgomon.Interrupt(process)\n\t})\n\n\tDescribe(\"Run\", func() {\n\t\tContext(\"When garden is immediately unhealthy\", func() {\n\t\t\tContext(\"because the health check fails\", func() {\n\t\t\t\tvar checkErr = gardenhealth.UnrecoverableError(\"nope\")\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tchecker.HealthcheckReturns(checkErr)\n\t\t\t\t\texecutorClient.HealthyReturns(false)\n\t\t\t\t})\n\n\t\t\t\tIt(\"fails without becoming ready\", func() {\n\t\t\t\t\tEventually(process.Wait()).Should(Receive(Equal(checkErr)))\n\t\t\t\t\tConsistently(process.Ready()).ShouldNot(BeClosed())\n\t\t\t\t})\n\n\t\t\t\tIt(\"emits a metric for unhealthy cell\", func() {\n\t\t\t\t\tEventually(process.Wait()).Should(Receive(Equal(checkErr)))\n\t\t\t\t\tEventually(func() float64 {\n\t\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t\t}).Should(Equal(float64(1)))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"because the health check timed out\", func() {\n\t\t\t\tvar blockHealthcheck chan struct{}\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tblockHealthcheck = make(chan struct{})\n\t\t\t\t\tchecker.HealthcheckStub = func(lager.Logger) error {\n\t\t\t\t\t\t<-blockHealthcheck\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t})\n\n\t\t\t\tJustBeforeEach(func() {\n\t\t\t\t\tfakeClock.WaitForWatcherAndIncrement(timeoutDuration)\n\t\t\t\t})\n\n\t\t\t\tAfterEach(func() {\n\t\t\t\t\t\/\/ Send to the channel to eliminate the race\n\t\t\t\t\tblockHealthcheck <- struct{}{}\n\t\t\t\t\tclose(blockHealthcheck)\n\t\t\t\t\tblockHealthcheck = nil\n\t\t\t\t})\n\n\t\t\t\tIt(\"fails without becoming ready\", func() {\n\t\t\t\t\tEventually(process.Wait()).Should(Receive(Equal(gardenhealth.HealthcheckTimeoutError{})))\n\t\t\t\t\tConsistently(process.Ready()).ShouldNot(BeClosed())\n\t\t\t\t})\n\n\t\t\t\tIt(\"emits a metric for unhealthy cell\", func() {\n\t\t\t\t\tEventually(process.Wait()).Should(Receive(Equal(gardenhealth.HealthcheckTimeoutError{})))\n\t\t\t\t\tEventually(func() float64 {\n\t\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t\t}).Should(Equal(float64(1)))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tContext(\"When garden is healthy\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\texecutorClient.HealthyReturns(true)\n\t\t\t})\n\n\t\t\tIt(\"sets healthy to true only once\", func() {\n\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(1))\n\t\t\t\t_, healthy := executorClient.SetHealthyArgsForCall(0)\n\t\t\t\tExpect(healthy).Should(Equal(true))\n\t\t\t\tExpect(executorClient.SetHealthyCallCount()).To(Equal(1))\n\t\t\t})\n\n\t\t\tIt(\"continues to check at the correct interval\", func() {\n\t\t\t\tEventually(checker.HealthcheckCallCount).Should(Equal(1))\n\t\t\t\tEventually(process.Ready()).Should(BeClosed())\n\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(checkInterval)\n\t\t\t\tEventually(checker.HealthcheckCallCount).Should(Equal(2))\n\t\t\t\tEventually(logger).Should(gbytes.Say(\"check-complete\"))\n\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(checkInterval)\n\t\t\t\tEventually(checker.HealthcheckCallCount).Should(Equal(3))\n\t\t\t\tEventually(logger).Should(gbytes.Say(\"check-complete\"))\n\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(checkInterval)\n\t\t\t\tEventually(checker.HealthcheckCallCount).Should(Equal(4))\n\t\t\t\tEventually(logger).Should(gbytes.Say(\"check-complete\"))\n\t\t\t})\n\n\t\t\tIt(\"emits a metric for healthy cell\", func() {\n\t\t\t\tEventually(func() float64 {\n\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t}).Should(Equal(float64(0)))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when garden is intermittently healthy\", func() {\n\t\t\tvar checkErr = errors.New(\"nope\")\n\n\t\t\tBeforeEach(func() {\n\t\t\t\texecutorClient.HealthyReturns(true)\n\t\t\t})\n\n\t\t\tIt(\"Sets healthy to false after it fails, then to true after success and emits respective metrics\", func() {\n\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(1))\n\t\t\t\t_, healthy := executorClient.SetHealthyArgsForCall(0)\n\t\t\t\tExpect(healthy).Should(Equal(true))\n\t\t\t\tExpect(sender.GetValue(\"UnhealthyCell\").Value).To(Equal(float64(0)))\n\n\t\t\t\tchecker.HealthcheckReturns(checkErr)\n\t\t\t\texecutorClient.HealthyReturns(false)\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(checkInterval)\n\n\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(2))\n\t\t\t\t_, healthy = executorClient.SetHealthyArgsForCall(1)\n\t\t\t\tExpect(healthy).Should(Equal(false))\n\t\t\t\tExpect(sender.GetValue(\"UnhealthyCell\").Value).To(Equal(float64(1)))\n\n\t\t\t\tchecker.HealthcheckReturns(nil)\n\t\t\t\texecutorClient.HealthyReturns(true)\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(checkInterval)\n\n\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(3))\n\t\t\t\t_, healthy = executorClient.SetHealthyArgsForCall(2)\n\t\t\t\tExpect(healthy).Should(Equal(true))\n\t\t\t\tExpect(sender.GetValue(\"UnhealthyCell\").Value).To(Equal(float64(0)))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"When the healthcheck times out\", func() {\n\t\t\tvar blockHealthcheck chan struct{}\n\n\t\t\tBeforeEach(func() {\n\t\t\t\tblockHealthcheck = make(chan struct{})\n\t\t\t\tchecker.HealthcheckStub = func(lager.Logger) error {\n\t\t\t\t\tlogger.Info(\"blocking\")\n\t\t\t\t\t<-blockHealthcheck\n\t\t\t\t\tlogger.Info(\"unblocking\")\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tAfterEach(func() {\n\t\t\t\tclose(blockHealthcheck)\n\t\t\t})\n\n\t\t\tIt(\"sets the executor to unhealthy and emits the unhealthy metric\", func() {\n\t\t\t\tEventually(blockHealthcheck).Should(BeSent(struct{}{}))\n\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(1))\n\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(checkInterval)\n\t\t\t\tEventually(checker.HealthcheckCallCount).Should(Equal(2))\n\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(timeoutDuration)\n\n\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(2))\n\t\t\t\t_, healthy := executorClient.SetHealthyArgsForCall(1)\n\t\t\t\tExpect(healthy).Should(Equal(false))\n\t\t\t\tEventually(func() float64 {\n\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t}).Should(Equal(float64(1)))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"When the runner is signaled\", func() {\n\t\t\tContext(\"during the initial health check\", func() {\n\t\t\t\tvar blockHealthcheck chan struct{}\n\n\t\t\t\tBeforeEach(func() {\n\t\t\t\t\tblockHealthcheck = make(chan struct{})\n\t\t\t\t\tchecker.HealthcheckStub = func(lager.Logger) error {\n\t\t\t\t\t\t<-blockHealthcheck\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t})\n\n\t\t\t\tJustBeforeEach(func() {\n\t\t\t\t\tprocess.Signal(os.Interrupt)\n\t\t\t\t})\n\n\t\t\t\tIt(\"exits with no error\", func() {\n\t\t\t\t\tEventually(process.Wait()).Should(Receive(BeNil()))\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"After the initial health check\", func() {\n\t\t\t\tIt(\"exits imediately with no error\", func() {\n\t\t\t\t\tEventually(executorClient.SetHealthyCallCount).Should(Equal(1))\n\n\t\t\t\t\tprocess.Signal(os.Interrupt)\n\t\t\t\t\tEventually(process.Wait()).Should(Receive(BeNil()))\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tContext(\"UnhealthyCell metric emission\", func() {\n\t\t\tIt(\"emits the UnhealthyCell every emitInterval\", func() {\n\t\t\t\tEventually(executorClient.HealthyCallCount).Should(Equal(1))\n\t\t\t\tEventually(func() float64 {\n\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t}).Should(Equal(float64(1)))\n\n\t\t\t\texecutorClient.HealthyReturns(true)\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(emissionInterval)\n\n\t\t\t\tEventually(executorClient.HealthyCallCount).Should(Equal(2))\n\t\t\t\tEventually(func() float64 {\n\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t}).Should(Equal(float64(0)))\n\n\t\t\t\texecutorClient.HealthyReturns(false)\n\t\t\t\tfakeClock.WaitForWatcherAndIncrement(emissionInterval)\n\n\t\t\t\tEventually(executorClient.HealthyCallCount).Should(Equal(3))\n\t\t\t\tEventually(func() float64 {\n\t\t\t\t\treturn sender.GetValue(\"UnhealthyCell\").Value\n\t\t\t\t}).Should(Equal(float64(1)))\n\t\t\t})\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage componentconfig\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\tutilnet \"k8s.io\/kubernetes\/pkg\/util\/net\"\n)\n\n\/\/ used for validating command line opts\n\/\/ TODO(mikedanese): remove these when we remove command line flags\n\ntype IPVar struct {\n\tVal *string\n}\n\nfunc (v IPVar) Set(s string) error {\n\tif net.ParseIP(s) == nil {\n\t\treturn fmt.Errorf(\"%q is not a valid IP address\", s)\n\t}\n\tif v.Val == nil {\n\t\t\/\/ it's okay to panic here since this is programmer error\n\t\tpanic(\"the string pointer passed into IPVar should not be nil\")\n\t}\n\t*v.Val = s\n\treturn nil\n}\n\nfunc (v IPVar) String() string {\n\tif v.Val == nil {\n\t\treturn \"\"\n\t}\n\treturn *v.Val\n}\n\nfunc (v IPVar) Type() string {\n\treturn \"ip\"\n}\n\nfunc (m *ProxyMode) Set(s string) error {\n\tnm := ProxyMode(s)\n\tm = &nm\n\treturn nil\n}\n\nfunc (m *ProxyMode) String() string {\n\tif m != nil {\n\t\treturn string(*m)\n\t}\n\treturn \"\"\n}\n\nfunc (m *ProxyMode) Type() string {\n\treturn \"ProxyMode\"\n}\n\ntype PortRangeVar struct {\n\tVal *string\n}\n\nfunc (v PortRangeVar) Set(s string) error {\n\tif _, err := utilnet.ParsePortRange(s); err != nil {\n\t\treturn fmt.Errorf(\"%q is not a valid port range: %v\", s, err)\n\t}\n\tif v.Val == nil {\n\t\t\/\/ it's okay to panic here since this is programmer error\n\t\tpanic(\"the string pointer passed into PortRangeVar should not be nil\")\n\t}\n\t*v.Val = s\n\treturn nil\n}\n\nfunc (v PortRangeVar) String() string {\n\tif v.Val == nil {\n\t\treturn \"\"\n\t}\n\treturn *v.Val\n}\n\nfunc (v PortRangeVar) Type() string {\n\treturn \"port-range\"\n}\n<commit_msg>componentconfig: fix proxy mode set func<commit_after>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage componentconfig\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\tutilnet \"k8s.io\/kubernetes\/pkg\/util\/net\"\n)\n\n\/\/ used for validating command line opts\n\/\/ TODO(mikedanese): remove these when we remove command line flags\n\ntype IPVar struct {\n\tVal *string\n}\n\nfunc (v IPVar) Set(s string) error {\n\tif net.ParseIP(s) == nil {\n\t\treturn fmt.Errorf(\"%q is not a valid IP address\", s)\n\t}\n\tif v.Val == nil {\n\t\t\/\/ it's okay to panic here since this is programmer error\n\t\tpanic(\"the string pointer passed into IPVar should not be nil\")\n\t}\n\t*v.Val = s\n\treturn nil\n}\n\nfunc (v IPVar) String() string {\n\tif v.Val == nil {\n\t\treturn \"\"\n\t}\n\treturn *v.Val\n}\n\nfunc (v IPVar) Type() string {\n\treturn \"ip\"\n}\n\nfunc (m *ProxyMode) Set(s string) error {\n\t*m = ProxyMode(s)\n\treturn nil\n}\n\nfunc (m *ProxyMode) String() string {\n\tif m != nil {\n\t\treturn string(*m)\n\t}\n\treturn \"\"\n}\n\nfunc (m *ProxyMode) Type() string {\n\treturn \"ProxyMode\"\n}\n\ntype PortRangeVar struct {\n\tVal *string\n}\n\nfunc (v PortRangeVar) Set(s string) error {\n\tif _, err := utilnet.ParsePortRange(s); err != nil {\n\t\treturn fmt.Errorf(\"%q is not a valid port range: %v\", s, err)\n\t}\n\tif v.Val == nil {\n\t\t\/\/ it's okay to panic here since this is programmer error\n\t\tpanic(\"the string pointer passed into PortRangeVar should not be nil\")\n\t}\n\t*v.Val = s\n\treturn nil\n}\n\nfunc (v PortRangeVar) String() string {\n\tif v.Val == nil {\n\t\treturn \"\"\n\t}\n\treturn *v.Val\n}\n\nfunc (v PortRangeVar) Type() string {\n\treturn \"port-range\"\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage diskmanagers\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/vmware\/govmomi\/object\"\n\t\"github.com\/vmware\/govmomi\/vim25\/types\"\n\t\"golang.org\/x\/net\/context\"\n\t\"k8s.io\/kubernetes\/pkg\/cloudprovider\/providers\/vsphere\/vclib\"\n)\n\n\/\/ vmDiskManager implements VirtualDiskProvider interface for creating volume using Virtual Machine Reconfigure approach\ntype vmDiskManager struct {\n\tdiskPath      string\n\tvolumeOptions *vclib.VolumeOptions\n\tvmOptions     *vclib.VMOptions\n}\n\n\/\/ Create implements Disk's Create interface\n\/\/ Contains implementation of VM based Provisioning to provision disk with SPBM Policy or VSANStorageProfileData\nfunc (vmdisk vmDiskManager) Create(ctx context.Context, datastore *vclib.Datastore) (err error) {\n\tif vmdisk.volumeOptions.SCSIControllerType == \"\" {\n\t\tvmdisk.volumeOptions.SCSIControllerType = vclib.PVSCSIControllerType\n\t}\n\tpbmClient, err := vclib.NewPbmClient(ctx, datastore.Client())\n\tif err != nil {\n\t\tglog.Errorf(\"Error occurred while creating new pbmClient, err: %+v\", err)\n\t\treturn err\n\t}\n\n\tif vmdisk.volumeOptions.StoragePolicyID == \"\" && vmdisk.volumeOptions.StoragePolicyName != \"\" {\n\t\tvmdisk.volumeOptions.StoragePolicyID, err = pbmClient.ProfileIDByName(ctx, vmdisk.volumeOptions.StoragePolicyName)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Error occurred while getting Profile Id from Profile Name: %s, err: %+v\", vmdisk.volumeOptions.StoragePolicyName, err)\n\t\t\treturn err\n\t\t}\n\t}\n\tif vmdisk.volumeOptions.StoragePolicyID != \"\" {\n\t\tcompatible, faultMessage, err := datastore.IsCompatibleWithStoragePolicy(ctx, vmdisk.volumeOptions.StoragePolicyID)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Error occurred while checking datastore compatibility with storage policy id: %s, err: %+v\", vmdisk.volumeOptions.StoragePolicyID, err)\n\t\t\treturn err\n\t\t}\n\n\t\tif !compatible {\n\t\t\tglog.Errorf(\"Datastore: %s is not compatible with Policy: %s\", datastore.Name(), vmdisk.volumeOptions.StoragePolicyName)\n\t\t\treturn fmt.Errorf(\"User specified datastore is not compatible with the storagePolicy: %q. Failed with faults: %+q\", vmdisk.volumeOptions.StoragePolicyName, faultMessage)\n\t\t}\n\t}\n\n\tstorageProfileSpec := &types.VirtualMachineDefinedProfileSpec{}\n\t\/\/ Is PBM storage policy ID is present, set the storage spec profile ID,\n\t\/\/ else, set raw the VSAN policy string.\n\tif vmdisk.volumeOptions.StoragePolicyID != \"\" {\n\t\tstorageProfileSpec.ProfileId = vmdisk.volumeOptions.StoragePolicyID\n\t} else if vmdisk.volumeOptions.VSANStorageProfileData != \"\" {\n\t\t\/\/ Check Datastore type - VSANStorageProfileData is only applicable to vSAN Datastore\n\t\tdsType, err := datastore.GetType(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif dsType != vclib.VSANDatastoreType {\n\t\t\tglog.Errorf(\"The specified datastore: %q is not a VSAN datastore\", datastore.Name())\n\t\t\treturn fmt.Errorf(\"The specified datastore: %q is not a VSAN datastore.\"+\n\t\t\t\t\" The policy parameters will work only with VSAN Datastore.\"+\n\t\t\t\t\" So, please specify a valid VSAN datastore in Storage class definition.\", datastore.Name())\n\t\t}\n\t\tstorageProfileSpec.ProfileId = \"\"\n\t\tstorageProfileSpec.ProfileData = &types.VirtualMachineProfileRawData{\n\t\t\tExtensionKey: \"com.vmware.vim.sps\",\n\t\t\tObjectData:   vmdisk.volumeOptions.VSANStorageProfileData,\n\t\t}\n\t} else {\n\t\tglog.Errorf(\"Both volumeOptions.StoragePolicyID and volumeOptions.VSANStorageProfileData are not set. One of them should be set\")\n\t\treturn fmt.Errorf(\"Both volumeOptions.StoragePolicyID and volumeOptions.VSANStorageProfileData are not set. One of them should be set\")\n\t}\n\tvar dummyVM *vclib.VirtualMachine\n\t\/\/ Check if VM already exist in the folder.\n\t\/\/ If VM is already present, use it, else create a new dummy VM.\n\tdummyVMFullName := vclib.DummyVMPrefixName + \"-\" + vmdisk.volumeOptions.Name\n\tdummyVM, err = datastore.Datacenter.GetVMByPath(ctx, vmdisk.vmOptions.VMFolder.InventoryPath+\"\/\"+dummyVMFullName)\n\tif err != nil {\n\t\t\/\/ Create a dummy VM\n\t\tglog.V(1).Info(\"Creating Dummy VM: %q\", dummyVMFullName)\n\t\tdummyVM, err = vmdisk.createDummyVM(ctx, datastore.Datacenter, dummyVMFullName)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to create Dummy VM. err: %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Reconfigure the VM to attach the disk with the VSAN policy configured\n\tvirtualMachineConfigSpec := types.VirtualMachineConfigSpec{}\n\tdisk, _, err := dummyVM.CreateDiskSpec(ctx, vmdisk.diskPath, datastore, vmdisk.volumeOptions)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to create Disk Spec. err: %v\", err)\n\t\treturn err\n\t}\n\tdeviceConfigSpec := &types.VirtualDeviceConfigSpec{\n\t\tDevice:        disk,\n\t\tOperation:     types.VirtualDeviceConfigSpecOperationAdd,\n\t\tFileOperation: types.VirtualDeviceConfigSpecFileOperationCreate,\n\t}\n\n\tdeviceConfigSpec.Profile = append(deviceConfigSpec.Profile, storageProfileSpec)\n\tvirtualMachineConfigSpec.DeviceChange = append(virtualMachineConfigSpec.DeviceChange, deviceConfigSpec)\n\tfileAlreadyExist := false\n\ttask, err := dummyVM.Reconfigure(ctx, virtualMachineConfigSpec)\n\terr = task.Wait(ctx)\n\tif err != nil {\n\t\tfileAlreadyExist = isAlreadyExists(vmdisk.diskPath, err)\n\t\tif fileAlreadyExist {\n\t\t\t\/\/Skip error and continue to detach the disk as the disk was already created on the datastore.\n\t\t\tglog.V(vclib.LogLevel).Info(\"File: %v already exists\", vmdisk.diskPath)\n\t\t} else {\n\t\t\tglog.Errorf(\"Failed to attach the disk to VM: %q with err: %+v\", dummyVMFullName, err)\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ Detach the disk from the dummy VM.\n\terr = dummyVM.DetachDisk(ctx, vmdisk.diskPath)\n\tif err != nil {\n\t\tif vclib.DiskNotFoundErrMsg == err.Error() && fileAlreadyExist {\n\t\t\t\/\/ Skip error if disk was already detached from the dummy VM but still present on the datastore.\n\t\t\tglog.V(vclib.LogLevel).Info(\"File: %v is already detached\", vmdisk.diskPath)\n\t\t} else {\n\t\t\tglog.Errorf(\"Failed to detach the disk: %q from VM: %q with err: %+v\", vmdisk.diskPath, dummyVMFullName, err)\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/  Delete the dummy VM\n\terr = dummyVM.DeleteVM(ctx)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to destroy the vm: %q with err: %+v\", dummyVMFullName, err)\n\t}\n\treturn nil\n}\n\nfunc (vmdisk vmDiskManager) Delete(ctx context.Context, datastore *vclib.Datastore) error {\n\treturn fmt.Errorf(\"vmDiskManager.Delete is not supported\")\n}\n\n\/\/ CreateDummyVM create a Dummy VM at specified location with given name.\nfunc (vmdisk vmDiskManager) createDummyVM(ctx context.Context, datacenter *vclib.Datacenter, vmName string) (*vclib.VirtualMachine, error) {\n\t\/\/ Create a virtual machine config spec with 1 SCSI adapter.\n\tvirtualMachineConfigSpec := types.VirtualMachineConfigSpec{\n\t\tName: vmName,\n\t\tFiles: &types.VirtualMachineFileInfo{\n\t\t\tVmPathName: \"[\" + vmdisk.volumeOptions.Datastore + \"]\",\n\t\t},\n\t\tNumCPUs:  1,\n\t\tMemoryMB: 4,\n\t\tDeviceChange: []types.BaseVirtualDeviceConfigSpec{\n\t\t\t&types.VirtualDeviceConfigSpec{\n\t\t\t\tOperation: types.VirtualDeviceConfigSpecOperationAdd,\n\t\t\t\tDevice: &types.ParaVirtualSCSIController{\n\t\t\t\t\tVirtualSCSIController: types.VirtualSCSIController{\n\t\t\t\t\t\tSharedBus: types.VirtualSCSISharingNoSharing,\n\t\t\t\t\t\tVirtualController: types.VirtualController{\n\t\t\t\t\t\t\tBusNumber: 0,\n\t\t\t\t\t\t\tVirtualDevice: types.VirtualDevice{\n\t\t\t\t\t\t\t\tKey: 1000,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\ttask, err := vmdisk.vmOptions.VMFolder.CreateVM(ctx, virtualMachineConfigSpec, vmdisk.vmOptions.VMResourcePool, nil)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to create VM. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\n\tdummyVMTaskInfo, err := task.WaitForResult(ctx, nil)\n\tif err != nil {\n\t\tglog.Errorf(\"Error occurred while waiting for create VM task result. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\n\tvmRef := dummyVMTaskInfo.Result.(object.Reference)\n\tdummyVM := object.NewVirtualMachine(datacenter.Client(), vmRef.Reference())\n\treturn &vclib.VirtualMachine{VirtualMachine: dummyVM, Datacenter: datacenter}, nil\n}\n\n\/\/ CleanUpDummyVMs deletes stale dummyVM's\nfunc CleanUpDummyVMs(ctx context.Context, folder *vclib.Folder, dc *vclib.Datacenter) error {\n\tvmList, err := folder.GetVirtualMachines(ctx)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Failed to get virtual machines in the kubernetes cluster: %s, err: %+v\", folder.InventoryPath, err)\n\t\treturn err\n\t}\n\tif vmList == nil || len(vmList) == 0 {\n\t\tglog.Errorf(\"No virtual machines found in the kubernetes cluster: %s\", folder.InventoryPath)\n\t\treturn fmt.Errorf(\"No virtual machines found in the kubernetes cluster: %s\", folder.InventoryPath)\n\t}\n\tvar dummyVMList []*vclib.VirtualMachine\n\t\/\/ Loop through VM's in the Kubernetes cluster to find dummy VM's\n\tfor _, vm := range vmList {\n\t\tvmName, err := vm.ObjectName(ctx)\n\t\tif err != nil {\n\t\t\tglog.V(4).Infof(\"Unable to get name from VM with err: %+v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(vmName, vclib.DummyVMPrefixName) {\n\t\t\tvmObj := vclib.VirtualMachine{VirtualMachine: object.NewVirtualMachine(dc.Client(), vm.Reference()), Datacenter: dc}\n\t\t\tdummyVMList = append(dummyVMList, &vmObj)\n\t\t}\n\t}\n\tfor _, vm := range dummyVMList {\n\t\terr = vm.DeleteVM(ctx)\n\t\tif err != nil {\n\t\t\tglog.V(4).Infof(\"Unable to delete dummy VM with err: %+v\", err)\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc isAlreadyExists(path string, err error) bool {\n\terrorMessage := fmt.Sprintf(\"Cannot complete the operation because the file or folder %s already exists\", path)\n\tif errorMessage == err.Error() {\n\t\treturn true\n\t}\n\treturn false\n}\n<commit_msg>Using hash\/fnv to generate the vmName<commit_after>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage diskmanagers\n\nimport (\n\t\"fmt\"\n\t\"hash\/fnv\"\n\t\"strings\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/vmware\/govmomi\/object\"\n\t\"github.com\/vmware\/govmomi\/vim25\/types\"\n\t\"golang.org\/x\/net\/context\"\n\t\"k8s.io\/kubernetes\/pkg\/cloudprovider\/providers\/vsphere\/vclib\"\n)\n\n\/\/ vmDiskManager implements VirtualDiskProvider interface for creating volume using Virtual Machine Reconfigure approach\ntype vmDiskManager struct {\n\tdiskPath      string\n\tvolumeOptions *vclib.VolumeOptions\n\tvmOptions     *vclib.VMOptions\n}\n\n\/\/ Create implements Disk's Create interface\n\/\/ Contains implementation of VM based Provisioning to provision disk with SPBM Policy or VSANStorageProfileData\nfunc (vmdisk vmDiskManager) Create(ctx context.Context, datastore *vclib.Datastore) (err error) {\n\tif vmdisk.volumeOptions.SCSIControllerType == \"\" {\n\t\tvmdisk.volumeOptions.SCSIControllerType = vclib.PVSCSIControllerType\n\t}\n\tpbmClient, err := vclib.NewPbmClient(ctx, datastore.Client())\n\tif err != nil {\n\t\tglog.Errorf(\"Error occurred while creating new pbmClient, err: %+v\", err)\n\t\treturn err\n\t}\n\n\tif vmdisk.volumeOptions.StoragePolicyID == \"\" && vmdisk.volumeOptions.StoragePolicyName != \"\" {\n\t\tvmdisk.volumeOptions.StoragePolicyID, err = pbmClient.ProfileIDByName(ctx, vmdisk.volumeOptions.StoragePolicyName)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Error occurred while getting Profile Id from Profile Name: %s, err: %+v\", vmdisk.volumeOptions.StoragePolicyName, err)\n\t\t\treturn err\n\t\t}\n\t}\n\tif vmdisk.volumeOptions.StoragePolicyID != \"\" {\n\t\tcompatible, faultMessage, err := datastore.IsCompatibleWithStoragePolicy(ctx, vmdisk.volumeOptions.StoragePolicyID)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Error occurred while checking datastore compatibility with storage policy id: %s, err: %+v\", vmdisk.volumeOptions.StoragePolicyID, err)\n\t\t\treturn err\n\t\t}\n\n\t\tif !compatible {\n\t\t\tglog.Errorf(\"Datastore: %s is not compatible with Policy: %s\", datastore.Name(), vmdisk.volumeOptions.StoragePolicyName)\n\t\t\treturn fmt.Errorf(\"User specified datastore is not compatible with the storagePolicy: %q. Failed with faults: %+q\", vmdisk.volumeOptions.StoragePolicyName, faultMessage)\n\t\t}\n\t}\n\n\tstorageProfileSpec := &types.VirtualMachineDefinedProfileSpec{}\n\t\/\/ Is PBM storage policy ID is present, set the storage spec profile ID,\n\t\/\/ else, set raw the VSAN policy string.\n\tif vmdisk.volumeOptions.StoragePolicyID != \"\" {\n\t\tstorageProfileSpec.ProfileId = vmdisk.volumeOptions.StoragePolicyID\n\t} else if vmdisk.volumeOptions.VSANStorageProfileData != \"\" {\n\t\t\/\/ Check Datastore type - VSANStorageProfileData is only applicable to vSAN Datastore\n\t\tdsType, err := datastore.GetType(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif dsType != vclib.VSANDatastoreType {\n\t\t\tglog.Errorf(\"The specified datastore: %q is not a VSAN datastore\", datastore.Name())\n\t\t\treturn fmt.Errorf(\"The specified datastore: %q is not a VSAN datastore.\"+\n\t\t\t\t\" The policy parameters will work only with VSAN Datastore.\"+\n\t\t\t\t\" So, please specify a valid VSAN datastore in Storage class definition.\", datastore.Name())\n\t\t}\n\t\tstorageProfileSpec.ProfileId = \"\"\n\t\tstorageProfileSpec.ProfileData = &types.VirtualMachineProfileRawData{\n\t\t\tExtensionKey: \"com.vmware.vim.sps\",\n\t\t\tObjectData:   vmdisk.volumeOptions.VSANStorageProfileData,\n\t\t}\n\t} else {\n\t\tglog.Errorf(\"Both volumeOptions.StoragePolicyID and volumeOptions.VSANStorageProfileData are not set. One of them should be set\")\n\t\treturn fmt.Errorf(\"Both volumeOptions.StoragePolicyID and volumeOptions.VSANStorageProfileData are not set. One of them should be set\")\n\t}\n\tvar dummyVM *vclib.VirtualMachine\n\t\/\/ Check if VM already exist in the folder.\n\t\/\/ If VM is already present, use it, else create a new dummy VM.\n\tfnvHash := fnv.New32a()\n\tfnvHash.Write([]byte(vmdisk.volumeOptions.Name))\n\tdummyVMFullName := vclib.DummyVMPrefixName + \"-\" + fmt.Sprint(fnvHash.Sum32())\n\tdummyVM, err = datastore.Datacenter.GetVMByPath(ctx, vmdisk.vmOptions.VMFolder.InventoryPath+\"\/\"+dummyVMFullName)\n\tif err != nil {\n\t\t\/\/ Create a dummy VM\n\t\tglog.V(1).Info(\"Creating Dummy VM: %q\", dummyVMFullName)\n\t\tdummyVM, err = vmdisk.createDummyVM(ctx, datastore.Datacenter, dummyVMFullName)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to create Dummy VM. err: %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Reconfigure the VM to attach the disk with the VSAN policy configured\n\tvirtualMachineConfigSpec := types.VirtualMachineConfigSpec{}\n\tdisk, _, err := dummyVM.CreateDiskSpec(ctx, vmdisk.diskPath, datastore, vmdisk.volumeOptions)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to create Disk Spec. err: %v\", err)\n\t\treturn err\n\t}\n\tdeviceConfigSpec := &types.VirtualDeviceConfigSpec{\n\t\tDevice:        disk,\n\t\tOperation:     types.VirtualDeviceConfigSpecOperationAdd,\n\t\tFileOperation: types.VirtualDeviceConfigSpecFileOperationCreate,\n\t}\n\n\tdeviceConfigSpec.Profile = append(deviceConfigSpec.Profile, storageProfileSpec)\n\tvirtualMachineConfigSpec.DeviceChange = append(virtualMachineConfigSpec.DeviceChange, deviceConfigSpec)\n\tfileAlreadyExist := false\n\ttask, err := dummyVM.Reconfigure(ctx, virtualMachineConfigSpec)\n\terr = task.Wait(ctx)\n\tif err != nil {\n\t\tfileAlreadyExist = isAlreadyExists(vmdisk.diskPath, err)\n\t\tif fileAlreadyExist {\n\t\t\t\/\/Skip error and continue to detach the disk as the disk was already created on the datastore.\n\t\t\tglog.V(vclib.LogLevel).Info(\"File: %v already exists\", vmdisk.diskPath)\n\t\t} else {\n\t\t\tglog.Errorf(\"Failed to attach the disk to VM: %q with err: %+v\", dummyVMFullName, err)\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ Detach the disk from the dummy VM.\n\terr = dummyVM.DetachDisk(ctx, vmdisk.diskPath)\n\tif err != nil {\n\t\tif vclib.DiskNotFoundErrMsg == err.Error() && fileAlreadyExist {\n\t\t\t\/\/ Skip error if disk was already detached from the dummy VM but still present on the datastore.\n\t\t\tglog.V(vclib.LogLevel).Info(\"File: %v is already detached\", vmdisk.diskPath)\n\t\t} else {\n\t\t\tglog.Errorf(\"Failed to detach the disk: %q from VM: %q with err: %+v\", vmdisk.diskPath, dummyVMFullName, err)\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/  Delete the dummy VM\n\terr = dummyVM.DeleteVM(ctx)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to destroy the vm: %q with err: %+v\", dummyVMFullName, err)\n\t}\n\treturn nil\n}\n\nfunc (vmdisk vmDiskManager) Delete(ctx context.Context, datastore *vclib.Datastore) error {\n\treturn fmt.Errorf(\"vmDiskManager.Delete is not supported\")\n}\n\n\/\/ CreateDummyVM create a Dummy VM at specified location with given name.\nfunc (vmdisk vmDiskManager) createDummyVM(ctx context.Context, datacenter *vclib.Datacenter, vmName string) (*vclib.VirtualMachine, error) {\n\t\/\/ Create a virtual machine config spec with 1 SCSI adapter.\n\tvirtualMachineConfigSpec := types.VirtualMachineConfigSpec{\n\t\tName: vmName,\n\t\tFiles: &types.VirtualMachineFileInfo{\n\t\t\tVmPathName: \"[\" + vmdisk.volumeOptions.Datastore + \"]\",\n\t\t},\n\t\tNumCPUs:  1,\n\t\tMemoryMB: 4,\n\t\tDeviceChange: []types.BaseVirtualDeviceConfigSpec{\n\t\t\t&types.VirtualDeviceConfigSpec{\n\t\t\t\tOperation: types.VirtualDeviceConfigSpecOperationAdd,\n\t\t\t\tDevice: &types.ParaVirtualSCSIController{\n\t\t\t\t\tVirtualSCSIController: types.VirtualSCSIController{\n\t\t\t\t\t\tSharedBus: types.VirtualSCSISharingNoSharing,\n\t\t\t\t\t\tVirtualController: types.VirtualController{\n\t\t\t\t\t\t\tBusNumber: 0,\n\t\t\t\t\t\t\tVirtualDevice: types.VirtualDevice{\n\t\t\t\t\t\t\t\tKey: 1000,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\ttask, err := vmdisk.vmOptions.VMFolder.CreateVM(ctx, virtualMachineConfigSpec, vmdisk.vmOptions.VMResourcePool, nil)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to create VM. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\n\tdummyVMTaskInfo, err := task.WaitForResult(ctx, nil)\n\tif err != nil {\n\t\tglog.Errorf(\"Error occurred while waiting for create VM task result. err: %+v\", err)\n\t\treturn nil, err\n\t}\n\n\tvmRef := dummyVMTaskInfo.Result.(object.Reference)\n\tdummyVM := object.NewVirtualMachine(datacenter.Client(), vmRef.Reference())\n\treturn &vclib.VirtualMachine{VirtualMachine: dummyVM, Datacenter: datacenter}, nil\n}\n\n\/\/ CleanUpDummyVMs deletes stale dummyVM's\nfunc CleanUpDummyVMs(ctx context.Context, folder *vclib.Folder, dc *vclib.Datacenter) error {\n\tvmList, err := folder.GetVirtualMachines(ctx)\n\tif err != nil {\n\t\tglog.V(4).Infof(\"Failed to get virtual machines in the kubernetes cluster: %s, err: %+v\", folder.InventoryPath, err)\n\t\treturn err\n\t}\n\tif vmList == nil || len(vmList) == 0 {\n\t\tglog.Errorf(\"No virtual machines found in the kubernetes cluster: %s\", folder.InventoryPath)\n\t\treturn fmt.Errorf(\"No virtual machines found in the kubernetes cluster: %s\", folder.InventoryPath)\n\t}\n\tvar dummyVMList []*vclib.VirtualMachine\n\t\/\/ Loop through VM's in the Kubernetes cluster to find dummy VM's\n\tfor _, vm := range vmList {\n\t\tvmName, err := vm.ObjectName(ctx)\n\t\tif err != nil {\n\t\t\tglog.V(4).Infof(\"Unable to get name from VM with err: %+v\", err)\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasPrefix(vmName, vclib.DummyVMPrefixName) {\n\t\t\tvmObj := vclib.VirtualMachine{VirtualMachine: object.NewVirtualMachine(dc.Client(), vm.Reference()), Datacenter: dc}\n\t\t\tdummyVMList = append(dummyVMList, &vmObj)\n\t\t}\n\t}\n\tfor _, vm := range dummyVMList {\n\t\terr = vm.DeleteVM(ctx)\n\t\tif err != nil {\n\t\t\tglog.V(4).Infof(\"Unable to delete dummy VM with err: %+v\", err)\n\t\t\tcontinue\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc isAlreadyExists(path string, err error) bool {\n\terrorMessage := fmt.Sprintf(\"Cannot complete the operation because the file or folder %s already exists\", path)\n\tif errorMessage == err.Error() {\n\t\treturn true\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Licensed to the Apache Software Foundation (ASF) under one or more\n\/\/ contributor license agreements.  See the NOTICE file distributed with\n\/\/ this work for additional information regarding copyright ownership.\n\/\/ The ASF licenses this file to You under the Apache License, Version 2.0\n\/\/ (the \"License\"); you may not use this file except in compliance with\n\/\/ the License.  You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage runtime\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"sync\"\n\n\t\"github.com\/apache\/beam\/sdks\/go\/pkg\/beam\/core\/util\/reflectx\"\n\t\"github.com\/apache\/beam\/sdks\/go\/pkg\/beam\/core\/util\/symtab\"\n)\n\nvar (\n\t\/\/ Resolver is the accessible symbol resolver the runtime uses to find functions.\n\tResolver SymbolResolver\n\tcache    = make(map[string]interface{})\n\tmu       sync.Mutex\n)\n\nfunc init() {\n\t\/\/ defer initialization of the default resolver. This way\n\t\/\/ the symbol table isn't read in unless strictly necessary.\n\tResolver = &deferedResolver{initFn: initResolver}\n}\n\ntype deferedResolver struct {\n\tinitFn func() SymbolResolver\n\tr      SymbolResolver\n\tinit   sync.Once\n}\n\nfunc (d *deferedResolver) Sym2Addr(name string) (uintptr, error) {\n\td.init.Do(func() {\n\t\td.r = d.initFn()\n\t})\n\treturn d.r.Sym2Addr(name)\n}\n\nfunc initResolver() SymbolResolver {\n\t\/\/ First try the Linux location, since it's the most reliable.\n\tif r, err := symtab.New(\"\/proc\/self\/exe\"); err == nil {\n\t\treturn r\n\t}\n\t\/\/ For other OS's this works in most cases we need.\n\tif r, err := symtab.New(os.Args[0]); err == nil {\n\t\treturn r\n\t}\n\treturn failResolver(false)\n}\n\n\/\/ SymbolResolver resolves a symbol to an unsafe address.\ntype SymbolResolver interface {\n\t\/\/ Sym2Addr returns the address pointer for a given symbol.\n\tSym2Addr(string) (uintptr, error)\n}\n\n\/\/ RegisterFunction allows function registration. It is beneficial for performance\n\/\/ and is needed for functions -- such as custom coders -- serialized during unit\n\/\/ tests, where the underlying symbol table is not available. It should be called\n\/\/ in init() only. Returns the external key for the function.\nfunc RegisterFunction(fn interface{}) {\n\tif initialized {\n\t\tpanic(\"Init hooks have already run. Register function during init() instead.\")\n\t}\n\n\tkey := reflectx.FunctionName(fn)\n\tif _, exists := cache[key]; exists {\n\t\tpanic(fmt.Sprintf(\"Function %v already registred\", key))\n\t}\n\tcache[key] = fn\n}\n\n\/\/ ResolveFunction resolves the runtime value of a given function by symbol name\n\/\/ and type.\nfunc ResolveFunction(name string, t reflect.Type) (interface{}, error) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\n\tif val, exists := cache[name]; exists {\n\t\treturn val, nil\n\t}\n\n\tptr, err := Resolver.Sym2Addr(name)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tval := reflectx.LoadFunction(ptr, t)\n\tcache[name] = val\n\treturn val, nil\n}\n\ntype failResolver bool\n\nfunc (p failResolver) Sym2Addr(name string) (uintptr, error) {\n\treturn 0, fmt.Errorf(\"%v not found. Use runtime.RegisterFunction in unit tests\", name)\n}\n<commit_msg>[BEAM-3612] Make function registration idempotent<commit_after>\/\/ Licensed to the Apache Software Foundation (ASF) under one or more\n\/\/ contributor license agreements.  See the NOTICE file distributed with\n\/\/ this work for additional information regarding copyright ownership.\n\/\/ The ASF licenses this file to You under the Apache License, Version 2.0\n\/\/ (the \"License\"); you may not use this file except in compliance with\n\/\/ the License.  You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage runtime\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"sync\"\n\n\t\"github.com\/apache\/beam\/sdks\/go\/pkg\/beam\/core\/util\/reflectx\"\n\t\"github.com\/apache\/beam\/sdks\/go\/pkg\/beam\/core\/util\/symtab\"\n)\n\nvar (\n\t\/\/ Resolver is the accessible symbol resolver the runtime uses to find functions.\n\tResolver SymbolResolver\n\tcache    = make(map[string]interface{})\n\tmu       sync.Mutex\n)\n\nfunc init() {\n\t\/\/ defer initialization of the default resolver. This way\n\t\/\/ the symbol table isn't read in unless strictly necessary.\n\tResolver = &deferedResolver{initFn: initResolver}\n}\n\ntype deferedResolver struct {\n\tinitFn func() SymbolResolver\n\tr      SymbolResolver\n\tinit   sync.Once\n}\n\nfunc (d *deferedResolver) Sym2Addr(name string) (uintptr, error) {\n\td.init.Do(func() {\n\t\td.r = d.initFn()\n\t})\n\treturn d.r.Sym2Addr(name)\n}\n\nfunc initResolver() SymbolResolver {\n\t\/\/ First try the Linux location, since it's the most reliable.\n\tif r, err := symtab.New(\"\/proc\/self\/exe\"); err == nil {\n\t\treturn r\n\t}\n\t\/\/ For other OS's this works in most cases we need.\n\tif r, err := symtab.New(os.Args[0]); err == nil {\n\t\treturn r\n\t}\n\treturn failResolver(false)\n}\n\n\/\/ SymbolResolver resolves a symbol to an unsafe address.\ntype SymbolResolver interface {\n\t\/\/ Sym2Addr returns the address pointer for a given symbol.\n\tSym2Addr(string) (uintptr, error)\n}\n\n\/\/ RegisterFunction allows function registration. It is beneficial for performance\n\/\/ and is needed for functions -- such as custom coders -- serialized during unit\n\/\/ tests, where the underlying symbol table is not available. It should be called\n\/\/ in init() only. Returns the external key for the function.\nfunc RegisterFunction(fn interface{}) {\n\tif initialized {\n\t\tpanic(\"Init hooks have already run. Register function during init() instead.\")\n\t}\n\n\tkey := reflectx.FunctionName(fn)\n\t\/\/ If the function was registered already, the key and value will be the same anyway.\n\tcache[key] = fn\n}\n\n\/\/ ResolveFunction resolves the runtime value of a given function by symbol name\n\/\/ and type.\nfunc ResolveFunction(name string, t reflect.Type) (interface{}, error) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\n\tif val, exists := cache[name]; exists {\n\t\treturn val, nil\n\t}\n\n\tptr, err := Resolver.Sym2Addr(name)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tval := reflectx.LoadFunction(ptr, t)\n\tcache[name] = val\n\treturn val, nil\n}\n\ntype failResolver bool\n\nfunc (p failResolver) Sym2Addr(name string) (uintptr, error) {\n\treturn 0, fmt.Errorf(\"%v not found. Use runtime.RegisterFunction in unit tests\", name)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Nging is a toolbox for webmasters\n   Copyright (C) 2018-present Wenhui Shen <swh@admpub.com>\n\n   This program is free software: you can redistribute it and\/or modify\n   it under the terms of the GNU Affero General Public License as published\n   by the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with this program.  If not, see <https:\/\/www.gnu.org\/licenses\/>.\n*\/\n\npackage cmd\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/webx-top\/echo\"\n\t\"github.com\/webx-top\/echo\/defaults\"\n\t\"github.com\/webx-top\/echo\/middleware\/language\"\n\n\t\"github.com\/admpub\/log\"\n\t\"github.com\/admpub\/nging\/v4\/application\/cmd\/bootconfig\"\n\t\"github.com\/admpub\/nging\/v4\/application\/handler\/setup\"\n\t\"github.com\/admpub\/nging\/v4\/application\/library\/config\"\n\t\"github.com\/admpub\/nging\/v4\/application\/library\/config\/subconfig\/sdb\"\n\t\"github.com\/admpub\/once\"\n)\n\n\/\/ 静默安装\nvar InitDBConfig = &sdb.DB{\n\tType:     `mysql`, \/\/ mysql \/ sqlite\n\tUser:     `root`,\n\tDatabase: `nging`,\n\tHost:     `127.0.0.1:3306`,\n}\n\nvar InitInstallConfig = &struct {\n\tCharset    string\n\tAdminUser  string\n\tAdminPass  string\n\tAdminEmail string\n\tLanguage   string \/\/ en \/ zh-cn\n}{\n\tCharset:   sdb.MySQLDefaultCharset,\n\tAdminUser: `admin`,\n\tLanguage:  `zh-cn`,\n}\n\nvar initCmd = &cobra.Command{\n\tUse:     \"init\",\n\tShort:   \"Silent install\",\n\tExample: filepath.Base(os.Args[0]) + \" init [options]\",\n\tRunE:    initRunE,\n}\n\nvar translate *language.Translate\nvar translock once.Once\n\nfunc initTranslate() {\n\ttranslate = BuildTranslator(config.DefaultConfig.Language)\n}\n\nfunc GetTranslator() *language.Translate {\n\ttranslock.Do(initTranslate)\n\treturn translate\n}\n\nfunc ResetTranslator() {\n\ttranslock.Reset()\n}\n\nfunc BuildTranslator(c language.Config) *language.Translate {\n\tc.SetFSFunc(bootconfig.LangFSFunc)\n\ti18n := language.NewI18n(&c)\n\ttr := &language.Translate{}\n\ttr.Reset(InitInstallConfig.Language, i18n)\n\treturn tr\n}\n\nfunc initRunE(cmd *cobra.Command, args []string) error {\n\tconf, err := config.InitConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tconf.AsDefault()\n\tctx := defaults.NewMockContext()\n\tctx.SetAuto(true)\n\n\t\/\/ 启用多语言支持\n\tctx.SetTranslator(GetTranslator())\n\n\tctx.Request().Header().Set(echo.HeaderAccept, echo.MIMETextPlain)\n\tctx.Request().SetMethod(echo.POST)\n\tctx.Request().Form().Set(`type`, InitDBConfig.Type)\n\tctx.Request().Form().Set(`user`, InitDBConfig.User)\n\tctx.Request().Form().Set(`host`, InitDBConfig.Host)\n\tctx.Request().Form().Set(`password`, InitDBConfig.Password)\n\tctx.Request().Form().Set(`database`, InitDBConfig.Database)\n\tctx.Request().Form().Set(`prefix`, InitDBConfig.Prefix)\n\tctx.Request().Form().Set(`charset`, InitInstallConfig.Charset)\n\tctx.Request().Form().Set(`adminUser`, InitInstallConfig.AdminUser)\n\tctx.Request().Form().Set(`adminPass`, InitInstallConfig.AdminPass)\n\tctx.Request().Form().Set(`adminEmail`, InitInstallConfig.AdminEmail)\n\t\/\/return ctx.Render(`index`, nil)\n\terr = setup.Setup(ctx)\n\tif err == nil {\n\t\tlog.Okay(`Congratulations, this program has been installed successfully`)\n\t}\n\treturn err\n}\n\nfunc init() {\n\trootCmd.AddCommand(initCmd)\n\n\tinitCmd.Flags().StringVar(&InitDBConfig.Type, \"type\", InitDBConfig.Type, \"database type\")\n\tinitCmd.Flags().StringVar(&InitDBConfig.User, \"user\", InitDBConfig.User, \"database user\")\n\tinitCmd.Flags().StringVar(&InitDBConfig.Host, \"host\", InitDBConfig.Host, \"database host\")\n\tinitCmd.Flags().StringVar(&InitDBConfig.Password, \"password\", InitDBConfig.Password, \"database password\")\n\tinitCmd.Flags().StringVar(&InitDBConfig.Database, \"database\", InitDBConfig.Database, \"database name\")\n\tinitCmd.Flags().StringVar(&InitDBConfig.Prefix, \"prefix\", InitDBConfig.Prefix, \"database table prefix\")\n\tinitCmd.Flags().StringVar(&InitInstallConfig.Charset, \"charset\", InitInstallConfig.Charset, \"database table charset\")\n\tinitCmd.Flags().StringVar(&InitInstallConfig.AdminUser, \"adminUser\", InitInstallConfig.AdminUser, \"administrator name\")\n\tinitCmd.Flags().StringVar(&InitInstallConfig.AdminPass, \"adminPass\", InitInstallConfig.AdminPass, \"administrator password\")\n\tinitCmd.Flags().StringVar(&InitInstallConfig.AdminEmail, \"adminEmail\", InitInstallConfig.AdminEmail, \"administrator e-mail\")\n}\n<commit_msg>update<commit_after>\/*\n   Nging is a toolbox for webmasters\n   Copyright (C) 2018-present Wenhui Shen <swh@admpub.com>\n\n   This program is free software: you can redistribute it and\/or modify\n   it under the terms of the GNU Affero General Public License as published\n   by the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with this program.  If not, see <https:\/\/www.gnu.org\/licenses\/>.\n*\/\n\npackage cmd\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/webx-top\/echo\"\n\t\"github.com\/webx-top\/echo\/defaults\"\n\t\"github.com\/webx-top\/echo\/middleware\/language\"\n\n\t\"github.com\/admpub\/log\"\n\t\"github.com\/admpub\/nging\/v4\/application\/cmd\/bootconfig\"\n\t\"github.com\/admpub\/nging\/v4\/application\/handler\/setup\"\n\t\"github.com\/admpub\/nging\/v4\/application\/library\/config\"\n\t\"github.com\/admpub\/nging\/v4\/application\/library\/config\/subconfig\/sdb\"\n\t\"github.com\/admpub\/once\"\n)\n\n\/\/ 静默安装\nvar InitDBConfig = &sdb.DB{\n\tType:     `mysql`, \/\/ mysql \/ sqlite\n\tUser:     `root`,\n\tDatabase: `nging`,\n\tHost:     `127.0.0.1:3306`,\n}\n\nvar InitInstallConfig = &struct {\n\tCharset    string\n\tAdminUser  string\n\tAdminPass  string\n\tAdminEmail string\n\tLanguage   string \/\/ en \/ zh-cn\n}{\n\tCharset:   sdb.MySQLDefaultCharset,\n\tAdminUser: `admin`,\n\tLanguage:  `zh-cn`,\n}\n\nvar initCmd = &cobra.Command{\n\tUse:     \"init\",\n\tShort:   \"Silent install\",\n\tExample: filepath.Base(os.Args[0]) + \" init [options]\",\n\tRunE:    initRunE,\n}\n\nvar translate *language.Translate\nvar translock once.Once\n\nfunc initTranslate() {\n\ttranslate = BuildTranslator(config.DefaultConfig.Language)\n}\n\nfunc GetTranslator() *language.Translate {\n\ttranslock.Do(initTranslate)\n\treturn translate\n}\n\nfunc ResetTranslator() {\n\ttranslock.Reset()\n}\n\nfunc BuildTranslator(c language.Config) *language.Translate {\n\tc.SetFSFunc(bootconfig.LangFSFunc)\n\ti18n := language.NewI18n(&c)\n\ttr := &language.Translate{}\n\ttr.Reset(InitInstallConfig.Language, i18n)\n\treturn tr\n}\n\nfunc initRunE(cmd *cobra.Command, args []string) error {\n\tconf, err := config.InitConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\tconf.AsDefault()\n\tctx := defaults.NewMockContext()\n\tctx.SetAuto(true)\n\n\t\/\/ 启用多语言支持\n\tctx.SetTranslator(GetTranslator())\n\n\tctx.Request().Header().Set(echo.HeaderAccept, echo.MIMETextPlain)\n\tctx.Request().SetMethod(echo.POST)\n\tctx.Request().Form().Set(`type`, InitDBConfig.Type)\n\tctx.Request().Form().Set(`user`, InitDBConfig.User)\n\tctx.Request().Form().Set(`host`, InitDBConfig.Host)\n\tctx.Request().Form().Set(`password`, InitDBConfig.Password)\n\tctx.Request().Form().Set(`database`, InitDBConfig.Database)\n\tctx.Request().Form().Set(`prefix`, InitDBConfig.Prefix)\n\tctx.Request().Form().Set(`charset`, InitInstallConfig.Charset)\n\tctx.Request().Form().Set(`adminUser`, InitInstallConfig.AdminUser)\n\tctx.Request().Form().Set(`adminPass`, InitInstallConfig.AdminPass)\n\tctx.Request().Form().Set(`adminEmail`, InitInstallConfig.AdminEmail)\n\t\/\/return ctx.Render(`index`, nil)\n\terr = setup.Setup(ctx)\n\tif err == nil {\n\t\tlog.Okay(ctx.T(`Congratulations, this program has been installed successfully`))\n\t}\n\treturn err\n}\n\nfunc init() {\n\trootCmd.AddCommand(initCmd)\n\n\tinitCmd.Flags().StringVar(&InitDBConfig.Type, \"type\", InitDBConfig.Type, \"database type\")\n\tinitCmd.Flags().StringVar(&InitDBConfig.User, \"user\", InitDBConfig.User, \"database user\")\n\tinitCmd.Flags().StringVar(&InitDBConfig.Host, \"host\", InitDBConfig.Host, \"database host\")\n\tinitCmd.Flags().StringVar(&InitDBConfig.Password, \"password\", InitDBConfig.Password, \"database password\")\n\tinitCmd.Flags().StringVar(&InitDBConfig.Database, \"database\", InitDBConfig.Database, \"database name\")\n\tinitCmd.Flags().StringVar(&InitDBConfig.Prefix, \"prefix\", InitDBConfig.Prefix, \"database table prefix\")\n\tinitCmd.Flags().StringVar(&InitInstallConfig.Charset, \"charset\", InitInstallConfig.Charset, \"database table charset\")\n\tinitCmd.Flags().StringVar(&InitInstallConfig.AdminUser, \"adminUser\", InitInstallConfig.AdminUser, \"administrator name\")\n\tinitCmd.Flags().StringVar(&InitInstallConfig.AdminPass, \"adminPass\", InitInstallConfig.AdminPass, \"administrator password\")\n\tinitCmd.Flags().StringVar(&InitInstallConfig.AdminEmail, \"adminEmail\", InitInstallConfig.AdminEmail, \"administrator e-mail\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package base\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"time\"\n)\n\nvar ErrMustSetContains = errors.New(\"must set Contains or ContainsRe\")\nvar ErrCallbackAlreadyTriggered = errors.New(\"callback set to 'OnlyOnce', but already triggered\")\nvar ErrCallbackTimeout = errors.New(\"callback timeout\")\n\ntype ReadCallbackOption func(callback *ReadCallback) error\n\nfunc WithCallbackContains(contains string) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.Contains = contains\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackContainsRe(contains string) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.ContainsRe = contains\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackCaseInsensitive(i bool) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.CaseInsensitive = i\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackMultiline(m bool) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.MultiLine = m\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackResetOutput(reset bool) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.ResetOutput = reset\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackOnlyOnce(o bool) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.OnlyOnce = o\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackNextTimeout(t time.Duration) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.NextTimeout = t\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackNextReadDelay(t time.Duration) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.NextReadDelay = t\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackComplete(complete bool) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.Complete = complete\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackName(name string) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.Name = name\n\n\t\treturn nil\n\t}\n}\n\nfunc NewReadCallback(\n\tcallback func(*Driver, string) error,\n\toptions ...ReadCallbackOption,\n) (*ReadCallback, error) {\n\trc := &ReadCallback{\n\t\tCallback:           callback,\n\t\tContains:           \"\",\n\t\tcontainsBytes:      nil,\n\t\tContainsRe:         \"\",\n\t\tcontainsReCompiled: nil,\n\t\tCaseInsensitive:    true,\n\t\tMultiLine:          true,\n\t\tResetOutput:        true,\n\t\tOnlyOnce:           false,\n\t\tNextTimeout:        0,\n\t\tNextReadDelay:      0,\n\t\ttriggered:          false,\n\t\tComplete:           false,\n\t\tName:               \"\",\n\t}\n\n\tfor _, option := range options {\n\t\terr := option(rc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif rc.Contains == \"\" && rc.ContainsRe == \"\" {\n\t\treturn nil, ErrMustSetContains\n\t}\n\n\treturn rc, nil\n}\n\ntype ReadCallback struct {\n\tCallback           func(*Driver, string) error\n\tContains           string\n\tcontainsBytes      []byte\n\tContainsRe         string\n\tcontainsReCompiled *regexp.Regexp\n\tCaseInsensitive    bool\n\tMultiLine          bool\n\t\/\/ ResetOutput bool indicating if the output should be reset or not after callback execution.\n\tResetOutput bool\n\t\/\/ OnlyOnce bool indicating if this callback should be executed only one time.\n\tOnlyOnce bool\n\t\/\/ NextTimout timeout value to use for the subsequent read loop - ignored if Complete is true.\n\tNextTimeout time.Duration\n\t\/\/ NextReadDelay is time to use for sleeps between reads for hte subsequent read loop.\n\tNextReadDelay time.Duration\n\ttriggered     bool\n\tComplete      bool\n\tName          string\n}\n\nfunc (r *ReadCallback) contains() []byte {\n\tif len(r.containsBytes) == 0 {\n\t\tr.containsBytes = []byte(r.Contains)\n\n\t\tif r.CaseInsensitive {\n\t\t\tr.containsBytes = bytes.ToLower(r.containsBytes)\n\t\t}\n\t}\n\n\treturn r.containsBytes\n}\n\nfunc (r *ReadCallback) containsRe() *regexp.Regexp {\n\tif r.containsReCompiled == nil {\n\t\tflags := \"\"\n\n\t\tif r.CaseInsensitive && r.MultiLine {\n\t\t\tflags = \"(?im)\"\n\t\t} else if r.CaseInsensitive {\n\t\t\tflags = \"(?i)\"\n\t\t} else if r.MultiLine {\n\t\t\tflags = \"(?m)\"\n\t\t}\n\n\t\tr.containsReCompiled = regexp.MustCompile(fmt.Sprintf(`%s%s`, flags, r.ContainsRe))\n\t}\n\n\treturn r.containsReCompiled\n}\n\ntype readCallbackResult struct {\n\ti         int\n\tcallbacks []*ReadCallback\n\toutput    []byte\n\terr       error\n}\n\nfunc (d *Driver) executeCallback(\n\ti int,\n\tcallbacks []*ReadCallback,\n\toutput []byte,\n\ttimeout,\n\treadDelay time.Duration) error {\n\tcallback := callbacks[i]\n\n\tif callback.OnlyOnce {\n\t\tif callback.triggered {\n\t\t\treturn ErrCallbackAlreadyTriggered\n\t\t}\n\n\t\tcallback.triggered = true\n\t}\n\n\terr := callback.Callback(d, string(output))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif callback.Complete {\n\t\treturn nil\n\t}\n\n\tif callback.ResetOutput {\n\t\toutput = []byte{}\n\t}\n\n\tnextTimeout := timeout\n\tif callback.NextTimeout != 0 {\n\t\tnextTimeout = callback.NextTimeout\n\t}\n\n\tnextReadDelay := readDelay\n\tif callback.NextReadDelay != 0 {\n\t\tnextReadDelay = callback.NextReadDelay\n\t}\n\n\treturn d.readWithCallbacks(callbacks, output, nextTimeout, nextReadDelay)\n}\n\nfunc (d *Driver) readWithCallbacks(\n\tcallbacks []*ReadCallback,\n\toutput []byte,\n\ttimeout,\n\treadDelay time.Duration,\n) error {\n\tc := make(chan *readCallbackResult)\n\n\tgo func() {\n\t\tdefer close(c)\n\n\t\tfor {\n\t\t\tnewOutput, err := d.Channel.Read()\n\t\t\tif err != nil {\n\t\t\t\tc <- &readCallbackResult{\n\t\t\t\t\terr: err,\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\toutput = append(output, newOutput...)\n\n\t\t\tfor i, callback := range callbacks {\n\t\t\t\to := output\n\t\t\t\tif callback.CaseInsensitive {\n\t\t\t\t\to = bytes.ToLower(output)\n\t\t\t\t}\n\n\t\t\t\tif (callback.Contains != \"\" && bytes.Contains(o, callback.contains())) ||\n\t\t\t\t\t(callback.ContainsRe != \"\" && callback.containsRe().Match(o)) {\n\t\t\t\t\tc <- &readCallbackResult{\n\t\t\t\t\t\ti:         i,\n\t\t\t\t\t\tcallbacks: callbacks,\n\t\t\t\t\t\toutput:    output,\n\t\t\t\t\t\terr:       nil,\n\t\t\t\t\t}\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttime.Sleep(readDelay)\n\t\t}\n\t}()\n\n\ttimer := time.NewTimer(timeout)\n\n\tselect {\n\tcase r := <-c:\n\t\tif r.err != nil {\n\t\t\treturn r.err\n\t\t}\n\n\t\treturn d.executeCallback(r.i, r.callbacks, r.output, timeout, readDelay)\n\tcase <-timer.C:\n\t\treturn ErrCallbackTimeout\n\t}\n}\n\nfunc (d *Driver) ReadWithCallbacks(\n\tcallbacks []*ReadCallback,\n\tinput string,\n\ttimeout,\n\treadDelay time.Duration,\n) error {\n\tif input != \"\" {\n\t\terr := d.Channel.WriteAndReturn([]byte(input), false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\torigTransportTimeout := d.Transport.BaseTransportArgs.TimeoutTransport\n\td.Transport.BaseTransportArgs.TimeoutTransport = 0\n\n\tr := d.readWithCallbacks(callbacks, []byte{}, timeout, readDelay)\n\n\td.Transport.BaseTransportArgs.TimeoutTransport = origTransportTimeout\n\n\treturn r\n}\n<commit_msg>callback improvements<commit_after>package base\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"time\"\n)\n\nvar ErrMustSetContains = errors.New(\"must set Contains or ContainsRe\")\nvar ErrCallbackAlreadyTriggered = errors.New(\"callback set to 'OnlyOnce', but already triggered\")\nvar ErrCallbackTimeout = errors.New(\"callback timeout\")\n\ntype ReadCallbackOption func(callback *ReadCallback) error\n\nfunc WithCallbackContains(contains string) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.Contains = contains\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackNotContains(notContains string) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.NotContains = notContains\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackContainsRe(contains string) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.ContainsRe = contains\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackCaseInsensitive(i bool) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.CaseInsensitive = i\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackMultiline(m bool) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.MultiLine = m\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackResetOutput(reset bool) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.ResetOutput = reset\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackOnlyOnce(o bool) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.OnlyOnce = o\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackNextTimeout(t time.Duration) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.NextTimeout = t\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackNextReadDelay(t time.Duration) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.NextReadDelay = t\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackComplete(complete bool) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.Complete = complete\n\n\t\treturn nil\n\t}\n}\n\nfunc WithCallbackName(name string) ReadCallbackOption {\n\treturn func(r *ReadCallback) error {\n\t\tr.Name = name\n\n\t\treturn nil\n\t}\n}\n\nfunc NewReadCallback(\n\tcallback func(*Driver, string) error,\n\toptions ...ReadCallbackOption,\n) (*ReadCallback, error) {\n\trc := &ReadCallback{\n\t\tCallback:           callback,\n\t\tContains:           \"\",\n\t\tcontainsBytes:      nil,\n\t\tContainsRe:         \"\",\n\t\tcontainsReCompiled: nil,\n\t\tCaseInsensitive:    true,\n\t\tMultiLine:          true,\n\t\tResetOutput:        true,\n\t\tOnlyOnce:           false,\n\t\tNextTimeout:        0,\n\t\tNextReadDelay:      0,\n\t\ttriggered:          false,\n\t\tComplete:           false,\n\t\tName:               \"\",\n\t}\n\n\tfor _, option := range options {\n\t\terr := option(rc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif rc.Contains == \"\" && rc.ContainsRe == \"\" {\n\t\treturn nil, ErrMustSetContains\n\t}\n\n\treturn rc, nil\n}\n\ntype ReadCallback struct {\n\tCallback           func(*Driver, string) error\n\tContains           string\n\tcontainsBytes      []byte\n\tNotContains        string\n\tnotContainsBytes   []byte\n\tContainsRe         string\n\tcontainsReCompiled *regexp.Regexp\n\tCaseInsensitive    bool\n\tMultiLine          bool\n\t\/\/ ResetOutput bool indicating if the output should be reset or not after callback execution.\n\tResetOutput bool\n\t\/\/ OnlyOnce bool indicating if this callback should be executed only one time.\n\tOnlyOnce bool\n\t\/\/ NextTimout timeout value to use for the subsequent read loop - ignored if Complete is true.\n\tNextTimeout time.Duration\n\t\/\/ NextReadDelay is time to use for sleeps between reads for hte subsequent read loop.\n\tNextReadDelay time.Duration\n\ttriggered     bool\n\tComplete      bool\n\tName          string\n}\n\nfunc (r *ReadCallback) contains() []byte {\n\tif len(r.containsBytes) == 0 {\n\t\tr.containsBytes = []byte(r.Contains)\n\n\t\tif r.CaseInsensitive {\n\t\t\tr.containsBytes = bytes.ToLower(r.containsBytes)\n\t\t}\n\t}\n\n\treturn r.containsBytes\n}\n\nfunc (r *ReadCallback) notContains() []byte {\n\tif len(r.notContainsBytes) == 0 {\n\t\tr.notContainsBytes = []byte(r.NotContains)\n\n\t\tif r.CaseInsensitive {\n\t\t\tr.notContainsBytes = bytes.ToLower(r.notContainsBytes)\n\t\t}\n\t}\n\n\treturn r.notContainsBytes\n}\n\nfunc (r *ReadCallback) containsRe() *regexp.Regexp {\n\tif r.containsReCompiled == nil {\n\t\tflags := \"\"\n\n\t\tif r.CaseInsensitive && r.MultiLine {\n\t\t\tflags = \"(?im)\"\n\t\t} else if r.CaseInsensitive {\n\t\t\tflags = \"(?i)\"\n\t\t} else if r.MultiLine {\n\t\t\tflags = \"(?m)\"\n\t\t}\n\n\t\tr.containsReCompiled = regexp.MustCompile(fmt.Sprintf(`%s%s`, flags, r.ContainsRe))\n\t}\n\n\treturn r.containsReCompiled\n}\n\nfunc (r *ReadCallback) check(o []byte) bool {\n\tif r.CaseInsensitive {\n\t\to = bytes.ToLower(o)\n\t}\n\n\tif (r.Contains != \"\" && bytes.Contains(o, r.contains())) &&\n\t\t!(r.NotContains != \"\" && !bytes.Contains(o, r.notContains())) {\n\t\treturn true\n\t}\n\n\tif (r.ContainsRe != \"\" && r.containsRe().Match(o)) &&\n\t\t!(r.NotContains != \"\" && !bytes.Contains(o, r.notContains())) {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\ntype readCallbackResult struct {\n\ti         int\n\tcallbacks []*ReadCallback\n\toutput    []byte\n\terr       error\n}\n\nfunc (d *Driver) executeCallback(\n\ti int,\n\tcallbacks []*ReadCallback,\n\toutput []byte,\n\ttimeout,\n\treadDelay time.Duration) error {\n\tcallback := callbacks[i]\n\n\tif callback.OnlyOnce {\n\t\tif callback.triggered {\n\t\t\treturn ErrCallbackAlreadyTriggered\n\t\t}\n\n\t\tcallback.triggered = true\n\t}\n\n\terr := callback.Callback(d, string(output))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif callback.Complete {\n\t\treturn nil\n\t}\n\n\tif callback.ResetOutput {\n\t\toutput = []byte{}\n\t}\n\n\tnextTimeout := timeout\n\tif callback.NextTimeout != 0 {\n\t\tnextTimeout = callback.NextTimeout\n\t}\n\n\tnextReadDelay := readDelay\n\tif callback.NextReadDelay != 0 {\n\t\tnextReadDelay = callback.NextReadDelay\n\t}\n\n\treturn d.readWithCallbacks(callbacks, output, nextTimeout, nextReadDelay)\n}\n\nfunc (d *Driver) readWithCallbacks(\n\tcallbacks []*ReadCallback,\n\toutput []byte,\n\ttimeout,\n\treadDelay time.Duration,\n) error {\n\tc := make(chan *readCallbackResult)\n\n\tgo func() {\n\t\tdefer close(c)\n\n\t\tfor {\n\t\t\tnewOutput, err := d.Channel.Read()\n\t\t\tif err != nil {\n\t\t\t\tc <- &readCallbackResult{\n\t\t\t\t\terr: err,\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\toutput = append(output, newOutput...)\n\n\t\t\tfor i, callback := range callbacks {\n\t\t\t\tif callback.check(output) {\n\t\t\t\t\tc <- &readCallbackResult{\n\t\t\t\t\t\ti:         i,\n\t\t\t\t\t\tcallbacks: callbacks,\n\t\t\t\t\t\toutput:    output,\n\t\t\t\t\t\terr:       nil,\n\t\t\t\t\t}\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t\ttime.Sleep(readDelay)\n\t\t}\n\t}()\n\n\ttimer := time.NewTimer(timeout)\n\n\tselect {\n\tcase r := <-c:\n\t\tif r.err != nil {\n\t\t\treturn r.err\n\t\t}\n\n\t\treturn d.executeCallback(r.i, r.callbacks, r.output, timeout, readDelay)\n\tcase <-timer.C:\n\t\treturn ErrCallbackTimeout\n\t}\n}\n\nfunc (d *Driver) ReadWithCallbacks(\n\tcallbacks []*ReadCallback,\n\tinput string,\n\ttimeout,\n\treadDelay time.Duration,\n) error {\n\tif input != \"\" {\n\t\terr := d.Channel.WriteAndReturn([]byte(input), false)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\torigTransportTimeout := d.Transport.BaseTransportArgs.TimeoutTransport\n\td.Transport.BaseTransportArgs.TimeoutTransport = 0\n\n\tr := d.readWithCallbacks(callbacks, []byte{}, timeout, readDelay)\n\n\td.Transport.BaseTransportArgs.TimeoutTransport = origTransportTimeout\n\n\treturn r\n}\n<|endoftext|>"}
{"text":"<commit_before>package couch\n\nimport (\n    \"strings\"\n    \"fmt\"\n    \"os\"\n    \"json\"\n    \"bytes\"\n    \"http\"\n    \"net\"\n    \"io\/ioutil\"\n)\n\nvar (\n    CouchDBHost = \"localhost\"\n    CouchDBPort = \"5984\"\n    CouchDBName = \"exampledb\"\n)\n\n\/\/\n\/\/ Helper and utility functions (private)\n\/\/\n\n\/\/ Replaces all instances of from with to in s (quite inefficient right now)\nfunc replace(s, from, to string) string {\n    toks := strings.SplitAfter(s, from, 0)\n    newstr := \"\"\n    for i, tok := range toks {\n        if i < len(toks)-1 {\n            if !strings.HasSuffix(tok, from) {\n                panic(\"problem in replace\")\n            }\n            newtok := tok[0 : len(tok)-len(from)]\n            newstr = newstr + newtok + to\n        } else {\n            newstr = newstr + tok\n        }\n    }\n    return newstr\n}\n\n\/\/ Converts given URL to string containing the body of the response.\nfunc url_to_string(url string) string {\n    if r, _, err := http.Get(url); err == nil {\n        b, err := ioutil.ReadAll(r.Body)\n        r.Body.Close()\n        if err == nil {\n            return string(b)\n        }\n    }\n    return \"\"\n}\n\n\/\/ Marshal given interface to JSON string\nfunc to_JSON(p interface{}) (string, os.Error) {\n    buf := new(bytes.Buffer)\n    if err := json.Marshal(buf, p); err != nil {\n        return \"\", err\n    }\n    return buf.String(), nil\n}\n\n\/\/ Unmarshal JSON string to given interface\nfunc from_JSON(s string, p interface{}) os.Error {\n    if ok, errtok := json.Unmarshal(s, p); !ok {\n        return os.NewError(fmt.Sprintf(\"error unmarshaling: %s\", errtok))\n    }\n    return nil\n}\n\n\/\/ Since the json pkg doesn't handle fields beginning with _, we need to\n\/\/ convert \"_id\" and \"_rev\" to \"Id\" and \"Rev\" to extract that data.\nfunc temp_hack_go_to_json(json_str string) string {\n    json_str = replace(json_str, `\"Id\"`, `\"_id\"`)\n    json_str = replace(json_str, `\"Rev\"`, `\"_rev\"`)\n    return json_str\n}\n\nfunc temp_hack_json_to_go(json_str string) string {\n    json_str = replace(json_str, `\"_id\"`, `\"Id\"`)\n    json_str = replace(json_str, `\"_rev\"`, `\"Rev\"`)\n    return json_str\n}\n\ntype IdAndRev struct {\n    Id  string\n    Rev string\n}\n\n\/\/ Simply extract id and rev from a given JSON string (typically a document)\nfunc extract_id_and_rev(json_str string) (string, string, os.Error) {\n    \/\/ this assumes the temp replacement hack has already been applied\n    id_rev := new(IdAndRev)\n    if err := from_JSON(json_str, id_rev); err != nil {\n        return \"\", \"\", err\n    }\n    return id_rev.Id, id_rev.Rev, nil\n}\n\n\n\/\/\n\/\/ Interface functions (public)\n\/\/\n\n\nfunc CouchDBURL() string {\n    return fmt.Sprintf(\"http:\/\/%s:%s\/%s\/\", CouchDBHost, CouchDBPort, CouchDBName)\n}\n\ntype InsertResponse struct {\n    Ok  bool\n    Id  string\n    Rev string\n}\n\n\/\/ Inserts document to CouchDB, returning id and rev on success. The document\n\/\/ interface may optionally specify an \"Id\" field.\nfunc Insert(p interface{}) (string, string, os.Error) {\n    body_type := \"application\/json\"\n    json_str, err := to_JSON(p)\n    if err != nil {\n        return \"\", \"\", err\n    }\n    json_str = temp_hack_go_to_json(json_str)\n\n    r, err := http.Post(CouchDBURL(), body_type, bytes.NewBufferString(json_str))\n    if err != nil {\n        return \"\", \"\", err\n    }\n\n    b, err := ioutil.ReadAll(r.Body)\n    r.Body.Close()\n    if err != nil {\n        return \"\", \"\", err\n    }\n\n    ir := new(InsertResponse)\n    if err := from_JSON(string(b), ir); err != nil {\n        return \"\", \"\", err\n    }\n\n    if !ir.Ok {\n        return \"\", \"\", os.NewError(fmt.Sprintf(\"CouchDB returned not-OK: %v\", ir))\n    }\n\n    return ir.Id, ir.Rev, nil\n}\n\n\/\/ Unmarshals the document matching id to the given interface, returning rev.\nfunc Retrieve(id string, p interface{}) (string, os.Error) {\n    if len(id) <= 0 {\n        return \"\", os.NewError(\"no id specified\")\n    }\n\n    json_str := url_to_string(fmt.Sprintf(\"%s%s\", CouchDBURL(), id))\n    json_str = temp_hack_json_to_go(json_str)\n    _, rev, err := extract_id_and_rev(json_str)\n    if err != nil {\n        return \"\", err\n    }\n\n    return rev, from_JSON(json_str, p)\n}\n\n\/\/ Edits the given document, which must specify both id and rev fields (as \"Id\"\n\/\/ and \"Rev\"), and returns the new rev.\nfunc Edit(p interface{}) (string, os.Error) {\n    _, rev, err := Insert(p)\n    return rev, err\n}\n\n\/\/ Deletes document given by id and rev.\nfunc Delete(id, rev string) os.Error {\n    \/\/ Set up request\n    var req http.Request\n    req.Method = \"DELETE\"\n    req.ProtoMajor = 1\n    req.ProtoMinor = 1\n    req.Close = true\n    req.Header = map[string]string {\n        \"Content-Type\": \"application\/json\",\n        \"If-Match\": rev,\n    }\n    req.TransferEncoding = []string{\"chunked\"}\n    req.URL, _ = http.ParseURL(CouchDBURL() + id)\n    \n    \/\/ Make connection\n    conn, err := net.Dial(\"tcp\", \"\", CouchDBHost + \":\" + CouchDBPort)\n    if err != nil {\n        return err\n    }\n    http_conn := http.NewClientConn(conn, nil)\n    defer http_conn.Close()\n    if err := http_conn.Write(&req); err != nil {\n        return err\n    }\n    \n    \/\/ Read response\n    r, err := http_conn.Read()\n    if r == nil {\n        return os.NewError(\"no response\")\n    }\n    if err != nil {\n        return err\n    }\n    data, _ := ioutil.ReadAll(r.Body)\n    r.Body.Close()\n    ir := new(InsertResponse)\n    if ok, _ := json.Unmarshal(string(data), ir); !ok {\n        return os.NewError(\"error unmarshaling response\")\n    }\n    if !ir.Ok {\n        return os.NewError(\"CouchDB returned not-OK\")\n    }\n    \n    return nil\n}\n\ntype Row struct {\n    Id  string\n    Key string\n}\n\ntype KeyedViewResponse struct {\n    Total_rows uint64\n    Offset     uint64\n    Rows       []Row\n}\n\n\/\/ Return array of document ids as returned by the given view, by given key.\nfunc RetrieveIds(view, key string) []string {\n    \/\/ view should be eg. \"_design\/my_foo\/_view\/my_bar\"\n    if len(view) <= 0 || len(key) <= 0 {\n        return make([]string, 0)\n    }\n    \n    full_url := fmt.Sprintf(`%s%s?key=\"%s\"`, CouchDBURL(), view, key)\n    json_str := url_to_string(full_url)\n    kvr := new(KeyedViewResponse)\n    if err := from_JSON(json_str, kvr); err != nil {\n        return make([]string, 0)\n    }\n    \n    ids := make([]string, len(kvr.Rows))\n    for i, row := range kvr.Rows {\n        ids[i] = row.Id\n    }\n    return ids    \n}\n<commit_msg>Properly encode key=\"xyz\" in RetrieveIds<commit_after>package couch\n\nimport (\n    \"strings\"\n    \"fmt\"\n    \"os\"\n    \"json\"\n    \"bytes\"\n    \"http\"\n    \"net\"\n    \"io\/ioutil\"\n)\n\nvar (\n    CouchDBHost = \"localhost\"\n    CouchDBPort = \"5984\"\n    CouchDBName = \"exampledb\"\n)\n\n\/\/\n\/\/ Helper and utility functions (private)\n\/\/\n\n\/\/ Replaces all instances of from with to in s (quite inefficient right now)\nfunc replace(s, from, to string) string {\n    toks := strings.SplitAfter(s, from, 0)\n    newstr := \"\"\n    for i, tok := range toks {\n        if i < len(toks)-1 {\n            if !strings.HasSuffix(tok, from) {\n                panic(\"problem in replace\")\n            }\n            newtok := tok[0 : len(tok)-len(from)]\n            newstr = newstr + newtok + to\n        } else {\n            newstr = newstr + tok\n        }\n    }\n    return newstr\n}\n\n\/\/ Converts given URL to string containing the body of the response.\nfunc url_to_string(url string) string {\n    if r, _, err := http.Get(url); err == nil {\n        b, err := ioutil.ReadAll(r.Body)\n        r.Body.Close()\n        if err == nil {\n            return string(b)\n        }\n    }\n    return \"\"\n}\n\n\/\/ Marshal given interface to JSON string\nfunc to_JSON(p interface{}) (string, os.Error) {\n    buf := new(bytes.Buffer)\n    if err := json.Marshal(buf, p); err != nil {\n        return \"\", err\n    }\n    return buf.String(), nil\n}\n\n\/\/ Unmarshal JSON string to given interface\nfunc from_JSON(s string, p interface{}) os.Error {\n    if ok, errtok := json.Unmarshal(s, p); !ok {\n        return os.NewError(fmt.Sprintf(\"error unmarshaling: %s\", errtok))\n    }\n    return nil\n}\n\n\/\/ Since the json pkg doesn't handle fields beginning with _, we need to\n\/\/ convert \"_id\" and \"_rev\" to \"Id\" and \"Rev\" to extract that data.\nfunc temp_hack_go_to_json(json_str string) string {\n    json_str = replace(json_str, `\"Id\"`, `\"_id\"`)\n    json_str = replace(json_str, `\"Rev\"`, `\"_rev\"`)\n    return json_str\n}\n\nfunc temp_hack_json_to_go(json_str string) string {\n    json_str = replace(json_str, `\"_id\"`, `\"Id\"`)\n    json_str = replace(json_str, `\"_rev\"`, `\"Rev\"`)\n    return json_str\n}\n\ntype IdAndRev struct {\n    Id  string\n    Rev string\n}\n\n\/\/ Simply extract id and rev from a given JSON string (typically a document)\nfunc extract_id_and_rev(json_str string) (string, string, os.Error) {\n    \/\/ this assumes the temp replacement hack has already been applied\n    id_rev := new(IdAndRev)\n    if err := from_JSON(json_str, id_rev); err != nil {\n        return \"\", \"\", err\n    }\n    return id_rev.Id, id_rev.Rev, nil\n}\n\n\n\/\/\n\/\/ Interface functions (public)\n\/\/\n\n\nfunc CouchDBURL() string {\n    return fmt.Sprintf(\"http:\/\/%s:%s\/%s\/\", CouchDBHost, CouchDBPort, CouchDBName)\n}\n\ntype InsertResponse struct {\n    Ok  bool\n    Id  string\n    Rev string\n}\n\n\/\/ Inserts document to CouchDB, returning id and rev on success. The document\n\/\/ interface may optionally specify an \"Id\" field.\nfunc Insert(p interface{}) (string, string, os.Error) {\n    body_type := \"application\/json\"\n    json_str, err := to_JSON(p)\n    if err != nil {\n        return \"\", \"\", err\n    }\n    json_str = temp_hack_go_to_json(json_str)\n\n    r, err := http.Post(CouchDBURL(), body_type, bytes.NewBufferString(json_str))\n    if err != nil {\n        return \"\", \"\", err\n    }\n\n    b, err := ioutil.ReadAll(r.Body)\n    r.Body.Close()\n    if err != nil {\n        return \"\", \"\", err\n    }\n\n    ir := new(InsertResponse)\n    if err := from_JSON(string(b), ir); err != nil {\n        return \"\", \"\", err\n    }\n\n    if !ir.Ok {\n        return \"\", \"\", os.NewError(fmt.Sprintf(\"CouchDB returned not-OK: %v\", ir))\n    }\n\n    return ir.Id, ir.Rev, nil\n}\n\n\/\/ Unmarshals the document matching id to the given interface, returning rev.\nfunc Retrieve(id string, p interface{}) (string, os.Error) {\n    if len(id) <= 0 {\n        return \"\", os.NewError(\"no id specified\")\n    }\n\n    json_str := url_to_string(fmt.Sprintf(\"%s%s\", CouchDBURL(), id))\n    json_str = temp_hack_json_to_go(json_str)\n    _, rev, err := extract_id_and_rev(json_str)\n    if err != nil {\n        return \"\", err\n    }\n\n    return rev, from_JSON(json_str, p)\n}\n\n\/\/ Edits the given document, which must specify both id and rev fields (as \"Id\"\n\/\/ and \"Rev\"), and returns the new rev.\nfunc Edit(p interface{}) (string, os.Error) {\n    _, rev, err := Insert(p)\n    return rev, err\n}\n\n\/\/ Deletes document given by id and rev.\nfunc Delete(id, rev string) os.Error {\n    \/\/ Set up request\n    var req http.Request\n    req.Method = \"DELETE\"\n    req.ProtoMajor = 1\n    req.ProtoMinor = 1\n    req.Close = true\n    req.Header = map[string]string {\n        \"Content-Type\": \"application\/json\",\n        \"If-Match\": rev,\n    }\n    req.TransferEncoding = []string{\"chunked\"}\n    req.URL, _ = http.ParseURL(CouchDBURL() + id)\n    \n    \/\/ Make connection\n    conn, err := net.Dial(\"tcp\", \"\", CouchDBHost + \":\" + CouchDBPort)\n    if err != nil {\n        return err\n    }\n    http_conn := http.NewClientConn(conn, nil)\n    defer http_conn.Close()\n    if err := http_conn.Write(&req); err != nil {\n        return err\n    }\n    \n    \/\/ Read response\n    r, err := http_conn.Read()\n    if r == nil {\n        return os.NewError(\"no response\")\n    }\n    if err != nil {\n        return err\n    }\n    data, _ := ioutil.ReadAll(r.Body)\n    r.Body.Close()\n    ir := new(InsertResponse)\n    if ok, _ := json.Unmarshal(string(data), ir); !ok {\n        return os.NewError(\"error unmarshaling response\")\n    }\n    if !ir.Ok {\n        return os.NewError(\"CouchDB returned not-OK\")\n    }\n    \n    return nil\n}\n\ntype Row struct {\n    Id  string\n    Key string\n}\n\ntype KeyedViewResponse struct {\n    Total_rows uint64\n    Offset     uint64\n    Rows       []Row\n}\n\n\/\/ Return array of document ids as returned by the given view, by given key.\nfunc RetrieveIds(view, key string) []string {\n    \/\/ view should be eg. \"_design\/my_foo\/_view\/my_bar\"\n    if len(view) <= 0 || len(key) <= 0 {\n        return make([]string, 0)\n    }\n    \n    parameters = http.URLEncode(fmt.Sprintf(`key=\"%s\"`, key))\n    full_url := fmt.Sprintf(\"%s%s?%s\", CouchDBURL(), view, parameters)\n    json_str := url_to_string(full_url)\n    kvr := new(KeyedViewResponse)\n    if err := from_JSON(json_str, kvr); err != nil {\n        return make([]string, 0)\n    }\n    \n    ids := make([]string, len(kvr.Rows))\n    for i, row := range kvr.Rows {\n        ids[i] = row.Id\n    }\n    return ids    \n}\n<|endoftext|>"}
{"text":"<commit_before>package formats\n\nimport (\n\t\"io\"\n\t\"sort\"\n\n\t\"github.com\/alecthomas\/template\"\n\t\"github.com\/yarbelk\/refasta\/sequence\"\n)\n\n\/\/ TNT formatter\ntype TNT struct {\n\tTitle        string\n\tSequences    map[string]map[string]sequence.Sequence\n\tMetaData     sequence.GMDSlice\n\tspeciesNames []string\n}\n\nconst tntNonInterleavedTemplateString = `xread\n'{{ .Title }}'\n{{ .Length }} {{ .NTaxa }}\n{{ range $i, $taxon := .Taxa }}{{ $taxon.SpeciesName }} {{ $taxon.Sequence }}\n{{ end }};`\n\nvar tntNonInterleavedTemplate = template.Must(template.New(\"TNT\").Parse(tntNonInterleavedTemplateString))\n\ntype templateContext struct {\n\tTitle         string\n\tLength, NTaxa int\n\tTaxa          []taxonData\n}\n\ntype taxonData struct {\n\tSpeciesName string\n\tSequence    sequence.SequenceData\n}\n\nconst TNT_FORMAT = \"tnt\"\n\n\/\/ Construct a species using a GMDSlice to order the gene sequences\nfunc (t *TNT) PrintableTaxa() []taxonData {\n\tt.MetaData.Sort()\n\tvar allSpecies []taxonData = make([]taxonData, 0, len(t.speciesNames))\n\n\tfor _, n := range t.speciesNames {\n\t\tcombinedSequences := make([]byte, 0, t.getTotalLength())\n\t\tfor _, gmd := range t.MetaData {\n\t\t\tcombinedSequences = append(combinedSequences, t.Sequences[gmd.Gene][n].Seq...)\n\t\t}\n\t\tallSpecies = append(allSpecies, taxonData{\n\t\t\tSpeciesName: sequence.Safe(n),\n\t\t\tSequence:    combinedSequences,\n\t\t})\n\t}\n\treturn allSpecies\n}\n\n\/\/ insertString into the place that would keep it uniquely and ordered ascending\nfunc insertString(slice []string, s string) []string {\n\ti := sort.SearchStrings(slice, s)\n\t\/\/ Inserstion sort of the species names: builds up the list as a sorted list\n\tif i < len(slice) && slice[i] != s {\n\t\t\/\/ Species Name not in the list; insert it at i\n\t\tslice = append(slice[:i], append([]string{s}, slice[i:]...)...)\n\t} else if i == len(slice) {\n\t\tslice = append(slice, s)\n\t}\n\treturn slice\n}\n\n\/\/ AddSequence (or multiple) to the internal sequence store.\nfunc (t *TNT) AddSequence(seqs ...sequence.Sequence) {\n\tfor _, seq := range seqs {\n\t\tif t.Sequences == nil {\n\t\t\tt.Sequences = make(map[string]map[string]sequence.Sequence)\n\t\t}\n\t\tif m, ok := t.Sequences[seq.Gene]; !ok || m == nil {\n\t\t\tt.Sequences[seq.Gene] = make(map[string]sequence.Sequence)\n\t\t}\n\t\tt.Sequences[seq.Gene][seq.Species] = seq\n\t\tt.speciesNames = insertString(t.speciesNames, seq.Species)\n\t}\n}\n\n\/\/ WriteSequences will collect up the sequences, verify their validity,\n\/\/ and output a formated TNT file to the supplied writer\nfunc (t *TNT) WriteSequences(writer io.Writer) error {\n\tgmd, err := t.GenerateMetaData()\n\tif err != nil {\n\t\treturn err\n\t}\n\tgmd.Sort()\n\tt.MetaData = gmd\n\tallSpecies := t.PrintableTaxa()\n\tcontext := templateContext{\n\t\tTitle:  t.Title,\n\t\tLength: t.getTotalLength(),\n\t\tNTaxa:  len(t.speciesNames),\n\t\tTaxa:   allSpecies,\n\t}\n\treturn tntNonInterleavedTemplate.Execute(writer, context)\n}\n\n\/\/ GenerateMetaData will make sure that the sequences for the same\n\/\/ gene sequence (or whatever sequence) are all the same length.\n\/\/ Returns types of InvalidSequence with ErrNo\n\/\/ MISSMATCHED_SEQUENCE_LENGTHS if they are no correct\n\/\/ If they are correct, it will return a slice of the gene meta data\n\/\/ GeneMetaData, sequence.GMDSlice\nfunc (t *TNT) GenerateMetaData() (sequence.GMDSlice, error) {\n\tvar expectedLen int\n\tgeneMetaData := make(sequence.GMDSlice, 0, len(t.Sequences))\n\n\tfor gene, _ := range t.Sequences {\n\t\tfor i, name := range t.speciesNames {\n\t\t\tseq := t.Sequences[gene][name]\n\t\t\tif i == 0 {\n\t\t\t\texpectedLen = seq.Length\n\t\t\t} else if seq.Length != expectedLen {\n\t\t\t\treturn nil, sequence.InvalidSequence{\n\t\t\t\t\tMessage: \"Sequences are not the Same length\",\n\t\t\t\t\tDetails: \"None so far\",\n\t\t\t\t\tErrno:   sequence.MISSMATCHED_SEQUENCE_LENGTHS,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgeneMetaData = append(geneMetaData, sequence.GeneMetaData{\n\t\t\tGene:          gene,\n\t\t\tLength:        expectedLen,\n\t\t\tNumberSpecies: len(t.Sequences[gene]),\n\t\t})\n\t}\n\treturn geneMetaData, nil\n}\n\n\/\/ getTotalLength will return the combined length of all genes.  This should\n\/\/ be the same for each species.\nfunc (t *TNT) getTotalLength() (length int) {\n\tfor _, gmd := range t.MetaData {\n\t\tlength = length + gmd.Length\n\t}\n\treturn\n}\n<commit_msg>Pull the xread tnt block into helper method<commit_after>package formats\n\nimport (\n\t\"io\"\n\t\"sort\"\n\n\t\"github.com\/alecthomas\/template\"\n\t\"github.com\/yarbelk\/refasta\/sequence\"\n)\n\n\/\/ TNT formatter\ntype TNT struct {\n\tTitle        string\n\tSequences    map[string]map[string]sequence.Sequence\n\tMetaData     sequence.GMDSlice\n\tspeciesNames []string\n}\n\nconst tntNonInterleavedTemplateString = `xread\n'{{ .Title }}'\n{{ .Length }} {{ .NTaxa }}\n{{ range $i, $taxon := .Taxa }}{{ $taxon.SpeciesName }} {{ $taxon.Sequence }}\n{{ end }};`\n\nvar tntNonInterleavedTemplate = template.Must(template.New(\"TNT\").Parse(tntNonInterleavedTemplateString))\n\ntype templateContext struct {\n\tTitle         string\n\tLength, NTaxa int\n\tTaxa          []taxonData\n}\n\ntype taxonData struct {\n\tSpeciesName string\n\tSequence    sequence.SequenceData\n}\n\nconst TNT_FORMAT = \"tnt\"\n\n\/\/ Construct a species using a GMDSlice to order the gene sequences\nfunc (t *TNT) PrintableTaxa() []taxonData {\n\tt.MetaData.Sort()\n\tvar allSpecies []taxonData = make([]taxonData, 0, len(t.speciesNames))\n\n\tfor _, n := range t.speciesNames {\n\t\tcombinedSequences := make([]byte, 0, t.getTotalLength())\n\t\tfor _, gmd := range t.MetaData {\n\t\t\tcombinedSequences = append(combinedSequences, t.Sequences[gmd.Gene][n].Seq...)\n\t\t}\n\t\tallSpecies = append(allSpecies, taxonData{\n\t\t\tSpeciesName: sequence.Safe(n),\n\t\t\tSequence:    combinedSequences,\n\t\t})\n\t}\n\treturn allSpecies\n}\n\n\/\/ insertString into the place that would keep it uniquely and ordered ascending\nfunc insertString(slice []string, s string) []string {\n\ti := sort.SearchStrings(slice, s)\n\t\/\/ Inserstion sort of the species names: builds up the list as a sorted list\n\tif i < len(slice) && slice[i] != s {\n\t\t\/\/ Species Name not in the list; insert it at i\n\t\tslice = append(slice[:i], append([]string{s}, slice[i:]...)...)\n\t} else if i == len(slice) {\n\t\tslice = append(slice, s)\n\t}\n\treturn slice\n}\n\n\/\/ AddSequence (or multiple) to the internal sequence store.\nfunc (t *TNT) AddSequence(seqs ...sequence.Sequence) {\n\tfor _, seq := range seqs {\n\t\tif t.Sequences == nil {\n\t\t\tt.Sequences = make(map[string]map[string]sequence.Sequence)\n\t\t}\n\t\tif m, ok := t.Sequences[seq.Gene]; !ok || m == nil {\n\t\t\tt.Sequences[seq.Gene] = make(map[string]sequence.Sequence)\n\t\t}\n\t\tt.Sequences[seq.Gene][seq.Species] = seq\n\t\tt.speciesNames = insertString(t.speciesNames, seq.Species)\n\t}\n}\n\n\/*\nWriteXRead writes out the xread block; which contains the sequence\nand taxa data\n\n\txread\n\ttaxa_1 CTAGC...\n\ttaxa_2 TAGCA...\n\t;\n\n*\/\nfunc (t *TNT) WriteXRead(writer io.Writer) error {\n\tallSpecies := t.PrintableTaxa()\n\tcontext := templateContext{\n\t\tTitle:  t.Title,\n\t\tLength: t.getTotalLength(),\n\t\tNTaxa:  len(t.speciesNames),\n\t\tTaxa:   allSpecies,\n\t}\n\treturn tntNonInterleavedTemplate.Execute(writer, context)\n}\n\n\/\/ WriteSequences will collect up the sequences, verify their validity,\n\/\/ and output a formated TNT file to the supplied writer\nfunc (t *TNT) WriteSequences(writer io.Writer) error {\n\tgmd, err := t.GenerateMetaData()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\tgmd.Sort()\n\tt.MetaData = gmd\n\n\tif err := t.WriteXRead(writer); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ GenerateMetaData will make sure that the sequences for the same\n\/\/ gene sequence (or whatever sequence) are all the same length.\n\/\/ Returns types of InvalidSequence with ErrNo\n\/\/ MISSMATCHED_SEQUENCE_LENGTHS if they are no correct\n\/\/ If they are correct, it will return a slice of the gene meta data\n\/\/ GeneMetaData, sequence.GMDSlice\nfunc (t *TNT) GenerateMetaData() (sequence.GMDSlice, error) {\n\tvar expectedLen int\n\tgeneMetaData := make(sequence.GMDSlice, 0, len(t.Sequences))\n\n\tfor gene, _ := range t.Sequences {\n\t\tfor i, name := range t.speciesNames {\n\t\t\tseq := t.Sequences[gene][name]\n\t\t\tif i == 0 {\n\t\t\t\texpectedLen = seq.Length\n\t\t\t} else if seq.Length != expectedLen {\n\t\t\t\treturn nil, sequence.InvalidSequence{\n\t\t\t\t\tMessage: \"Sequences are not the Same length\",\n\t\t\t\t\tDetails: \"None so far\",\n\t\t\t\t\tErrno:   sequence.MISSMATCHED_SEQUENCE_LENGTHS,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tgeneMetaData = append(geneMetaData, sequence.GeneMetaData{\n\t\t\tGene:          gene,\n\t\t\tLength:        expectedLen,\n\t\t\tNumberSpecies: len(t.Sequences[gene]),\n\t\t})\n\t}\n\treturn geneMetaData, nil\n}\n\n\/\/ getTotalLength will return the combined length of all genes.  This should\n\/\/ be the same for each species.\nfunc (t *TNT) getTotalLength() (length int) {\n\tfor _, gmd := range t.MetaData {\n\t\tlength = length + gmd.Length\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"time\"\n)\n\n\/\/ ProjectStatus is a type alias which will be used to create an enum of acceptable project status states.\ntype ProjectStatus string\n\n\/\/ ProjectStatus pseudo-enum values\nconst (\n\tStatusPublished ProjectStatus = \"published\"\n\n\tStatuses = []ProjectStatus{StatusPublished}\n)\n\n\/\/ Errors pertaining to the data in a Project or operations on Projects.\nvar (\n\tErrInvalidProjectStatus = fmt.Errorf(\"Project status must be one of the following: %s\\n\", strings.Join([]string(Statuses), \", \"))\n)\n\n\/\/ Project contains information about a scanlation project, which has a human-readable name, a unique shorthand name,\n\/\/ and a publishing status amongst other things.\ntype Project struct {\n\tId          string        `json:\"id\"`\n\tName        string        `json:\"name\"`\n\tShorthand   string        `json:\"projectName\"`\n\tDescription string        `json:\"description\"`\n\tStatus      ProjectStatus `json:\"status\"`\n\tCreatedAt   time.Time     `json:\"createdAt\"`\n}\n\n\/\/ Validate checks that the \"status\" of the project is one of the accepted ProjectStatus values.\nfunc (p Project) Validate() error {\n\tfor _, status := range Statuses {\n\t\tif p.Status == status {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn ErrInvalidProjectStatus\n}\n<commit_msg>Rename some things to avoid name conflicts<commit_after>package models\n\nimport (\n\t\"time\"\n)\n\n\/\/ ProjectStatus is a type alias which will be used to create an enum of acceptable project status states.\ntype ProjectStatus string\n\n\/\/ ProjectStatus pseudo-enum values\nconst (\n\tPStatusPublished ProjectStatus = \"published\"\n\n\tPStatuses = []ProjectStatus{StatusPublished}\n)\n\n\/\/ Errors pertaining to the data in a Project or operations on Projects.\nvar (\n\tErrInvalidProjectStatus = fmt.Errorf(\"Project status must be one of the following: %s\\n\", strings.Join([]string(PStatuses), \", \"))\n)\n\n\/\/ Project contains information about a scanlation project, which has a human-readable name, a unique shorthand name,\n\/\/ and a publishing status amongst other things.\ntype Project struct {\n\tId          string        `json:\"id\"`\n\tName        string        `json:\"name\"`\n\tShorthand   string        `json:\"projectName\"`\n\tDescription string        `json:\"description\"`\n\tStatus      ProjectStatus `json:\"status\"`\n\tCreatedAt   time.Time     `json:\"createdAt\"`\n}\n\n\/\/ Validate checks that the \"status\" of the project is one of the accepted ProjectStatus values.\nfunc (p Project) Validate() error {\n\tfor _, status := range PStatuses {\n\t\tif p.Status == status {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn ErrInvalidProjectStatus\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2015 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cache\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\nfunc testIndexFunc(obj interface{}) ([]string, error) {\n\tpod := obj.(*v1.Pod)\n\treturn []string{pod.Labels[\"foo\"]}, nil\n}\n\nfunc TestGetIndexFuncValues(t *testing.T) {\n\tindex := NewIndexer(MetaNamespaceKeyFunc, Indexers{\"testmodes\": testIndexFunc})\n\n\tpod1 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"one\", Labels: map[string]string{\"foo\": \"bar\"}}}\n\tpod2 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"two\", Labels: map[string]string{\"foo\": \"bar\"}}}\n\tpod3 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"tre\", Labels: map[string]string{\"foo\": \"biz\"}}}\n\n\tindex.Add(pod1)\n\tindex.Add(pod2)\n\tindex.Add(pod3)\n\n\tkeys := index.ListIndexFuncValues(\"testmodes\")\n\tif len(keys) != 2 {\n\t\tt.Errorf(\"Expected 2 keys but got %v\", len(keys))\n\t}\n\n\tfor _, key := range keys {\n\t\tif key != \"bar\" && key != \"biz\" {\n\t\t\tt.Errorf(\"Expected only 'bar' or 'biz' but got %s\", key)\n\t\t}\n\t}\n}\n\nfunc testUsersIndexFunc(obj interface{}) ([]string, error) {\n\tpod := obj.(*v1.Pod)\n\tusersString := pod.Annotations[\"users\"]\n\n\treturn strings.Split(usersString, \",\"), nil\n}\n\nfunc TestMultiIndexKeys(t *testing.T) {\n\tindex := NewIndexer(MetaNamespaceKeyFunc, Indexers{\"byUser\": testUsersIndexFunc})\n\n\tpod1 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"one\", Annotations: map[string]string{\"users\": \"ernie,bert\"}}}\n\tpod2 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"two\", Annotations: map[string]string{\"users\": \"bert,oscar\"}}}\n\tpod3 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"tre\", Annotations: map[string]string{\"users\": \"ernie,elmo\"}}}\n\n\tindex.Add(pod1)\n\tindex.Add(pod2)\n\tindex.Add(pod3)\n\n\terniePods, err := index.ByIndex(\"byUser\", \"ernie\")\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %v\", err)\n\t}\n\tif len(erniePods) != 2 {\n\t\tt.Errorf(\"Expected 2 pods but got %v\", len(erniePods))\n\t}\n\tfor _, erniePod := range erniePods {\n\t\tif erniePod.(*v1.Pod).Name != \"one\" && erniePod.(*v1.Pod).Name != \"tre\" {\n\t\t\tt.Errorf(\"Expected only 'one' or 'tre' but got %s\", erniePod.(*v1.Pod).Name)\n\t\t}\n\t}\n\n\tbertPods, err := index.ByIndex(\"byUser\", \"bert\")\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %v\", err)\n\t}\n\tif len(bertPods) != 2 {\n\t\tt.Errorf(\"Expected 2 pods but got %v\", len(bertPods))\n\t}\n\tfor _, bertPod := range bertPods {\n\t\tif bertPod.(*v1.Pod).Name != \"one\" && bertPod.(*v1.Pod).Name != \"two\" {\n\t\t\tt.Errorf(\"Expected only 'one' or 'two' but got %s\", bertPod.(*v1.Pod).Name)\n\t\t}\n\t}\n\n\toscarPods, err := index.ByIndex(\"byUser\", \"oscar\")\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %v\", err)\n\t}\n\tif len(oscarPods) != 1 {\n\t\tt.Errorf(\"Expected 1 pods but got %v\", len(erniePods))\n\t}\n\tfor _, oscarPod := range oscarPods {\n\t\tif oscarPod.(*v1.Pod).Name != \"two\" {\n\t\t\tt.Errorf(\"Expected only 'two' but got %s\", oscarPod.(*v1.Pod).Name)\n\t\t}\n\t}\n\n\ternieAndBertKeys, err := index.Index(\"byUser\", pod1)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %v\", err)\n\t}\n\tif len(ernieAndBertKeys) != 3 {\n\t\tt.Errorf(\"Expected 3 pods but got %v\", len(ernieAndBertKeys))\n\t}\n\tfor _, ernieAndBertKey := range ernieAndBertKeys {\n\t\tif ernieAndBertKey.(*v1.Pod).Name != \"one\" && ernieAndBertKey.(*v1.Pod).Name != \"two\" && ernieAndBertKey.(*v1.Pod).Name != \"tre\" {\n\t\t\tt.Errorf(\"Expected only 'one', 'two' or 'tre' but got %s\", ernieAndBertKey.(*v1.Pod).Name)\n\t\t}\n\t}\n\n\tindex.Delete(pod3)\n\terniePods, err = index.ByIndex(\"byUser\", \"ernie\")\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %v\", err)\n\t}\n\tif len(erniePods) != 1 {\n\t\tt.Errorf(\"Expected 1 pods but got %v\", len(erniePods))\n\t}\n\tfor _, erniePod := range erniePods {\n\t\tif erniePod.(*v1.Pod).Name != \"one\" {\n\t\t\tt.Errorf(\"Expected only 'one' but got %s\", erniePod.(*v1.Pod).Name)\n\t\t}\n\t}\n\n\telmoPods, err := index.ByIndex(\"byUser\", \"elmo\")\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %v\", err)\n\t}\n\tif len(elmoPods) != 0 {\n\t\tt.Errorf(\"Expected 0 pods but got %v\", len(elmoPods))\n\t}\n\n\tcopyOfPod2 := pod2.DeepCopy()\n\tcopyOfPod2.Annotations[\"users\"] = \"oscar\"\n\tindex.Update(copyOfPod2)\n\tbertPods, err = index.ByIndex(\"byUser\", \"bert\")\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %v\", err)\n\t}\n\tif len(bertPods) != 1 {\n\t\tt.Errorf(\"Expected 1 pods but got %v\", len(bertPods))\n\t}\n\tfor _, bertPod := range bertPods {\n\t\tif bertPod.(*v1.Pod).Name != \"one\" {\n\t\t\tt.Errorf(\"Expected only 'one' but got %s\", bertPod.(*v1.Pod).Name)\n\t\t}\n\t}\n\n}\n<commit_msg>refactor index_test to compress the basic expected assertions<commit_after>\/*\nCopyright 2015 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cache\n\nimport (\n\t\"k8s.io\/apimachinery\/pkg\/util\/sets\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n)\n\nfunc testIndexFunc(obj interface{}) ([]string, error) {\n\tpod := obj.(*v1.Pod)\n\treturn []string{pod.Labels[\"foo\"]}, nil\n}\n\nfunc TestGetIndexFuncValues(t *testing.T) {\n\tindex := NewIndexer(MetaNamespaceKeyFunc, Indexers{\"testmodes\": testIndexFunc})\n\n\tpod1 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"one\", Labels: map[string]string{\"foo\": \"bar\"}}}\n\tpod2 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"two\", Labels: map[string]string{\"foo\": \"bar\"}}}\n\tpod3 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"tre\", Labels: map[string]string{\"foo\": \"biz\"}}}\n\n\tindex.Add(pod1)\n\tindex.Add(pod2)\n\tindex.Add(pod3)\n\n\tkeys := index.ListIndexFuncValues(\"testmodes\")\n\tif len(keys) != 2 {\n\t\tt.Errorf(\"Expected 2 keys but got %v\", len(keys))\n\t}\n\n\tfor _, key := range keys {\n\t\tif key != \"bar\" && key != \"biz\" {\n\t\t\tt.Errorf(\"Expected only 'bar' or 'biz' but got %s\", key)\n\t\t}\n\t}\n}\n\nfunc testUsersIndexFunc(obj interface{}) ([]string, error) {\n\tpod := obj.(*v1.Pod)\n\tusersString := pod.Annotations[\"users\"]\n\n\treturn strings.Split(usersString, \",\"), nil\n}\n\nfunc TestMultiIndexKeys(t *testing.T) {\n\tindex := NewIndexer(MetaNamespaceKeyFunc, Indexers{\"byUser\": testUsersIndexFunc})\n\n\tpod1 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"one\", Annotations: map[string]string{\"users\": \"ernie,bert\"}}}\n\tpod2 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"two\", Annotations: map[string]string{\"users\": \"bert,oscar\"}}}\n\tpod3 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: \"tre\", Annotations: map[string]string{\"users\": \"ernie,elmo\"}}}\n\n\tindex.Add(pod1)\n\tindex.Add(pod2)\n\tindex.Add(pod3)\n\n\texpected := map[string]sets.String{}\n\texpected[\"ernie\"] = sets.NewString(\"one\", \"tre\")\n\texpected[\"bert\"] = sets.NewString(\"one\", \"two\")\n\texpected[\"elmo\"] = sets.NewString(\"tre\")\n\texpected[\"oscar\"] = sets.NewString(\"two\")\n\texpected[\"elmo\"] = sets.NewString() \/\/ let's just make sure we don't get anything back in this case\n\t{\n\t\tfor k, v := range expected {\n\t\t\tfound := sets.String{}\n\t\t\tindexResults, err := index.ByIndex(\"byUser\", k)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Unexpected error %v\", err)\n\t\t\t}\n\t\t\tfor _, item := range indexResults {\n\t\t\t\tfound.Insert(item.(*v1.Pod).Name)\n\t\t\t}\n\t\t\titems := v.List()\n\t\t\tif !found.HasAll(items...) {\n\t\t\t\tt.Errorf(\"missing items, index %s, expected %v but found %v\", k, items, found.List())\n\t\t\t}\n\t\t}\n\t}\n\n\tindex.Delete(pod3)\n\terniePods, err := index.ByIndex(\"byUser\", \"ernie\")\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %v\", err)\n\t}\n\tif len(erniePods) != 1 {\n\t\tt.Errorf(\"Expected 1 pods but got %v\", len(erniePods))\n\t}\n\tfor _, erniePod := range erniePods {\n\t\tif erniePod.(*v1.Pod).Name != \"one\" {\n\t\t\tt.Errorf(\"Expected only 'one' but got %s\", erniePod.(*v1.Pod).Name)\n\t\t}\n\t}\n\n\telmoPods, err := index.ByIndex(\"byUser\", \"elmo\")\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %v\", err)\n\t}\n\tif len(elmoPods) != 0 {\n\t\tt.Errorf(\"Expected 0 pods but got %v\", len(elmoPods))\n\t}\n\n\tcopyOfPod2 := pod2.DeepCopy()\n\tcopyOfPod2.Annotations[\"users\"] = \"oscar\"\n\tindex.Update(copyOfPod2)\n\tbertPods, err := index.ByIndex(\"byUser\", \"bert\")\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error: %v\", err)\n\t}\n\tif len(bertPods) != 1 {\n\t\tt.Errorf(\"Expected 1 pods but got %v\", len(bertPods))\n\t}\n\tfor _, bertPod := range bertPods {\n\t\tif bertPod.(*v1.Pod).Name != \"one\" {\n\t\t\tt.Errorf(\"Expected only 'one' but got %s\", bertPod.(*v1.Pod).Name)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage componentconfig\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\tutilnet \"k8s.io\/kubernetes\/pkg\/util\/net\"\n)\n\n\/\/ used for validating command line opts\n\/\/ TODO(mikedanese): remove these when we remove command line flags\n\ntype IPVar struct {\n\tVal *string\n}\n\nfunc (v IPVar) Set(s string) error {\n\tif net.ParseIP(s) == nil {\n\t\treturn fmt.Errorf(\"%q is not a valid IP address\", s)\n\t}\n\tif v.Val == nil {\n\t\t\/\/ it's okay to panic here since this is programmer error\n\t\tpanic(\"the string pointer passed into IPVar should not be nil\")\n\t}\n\t*v.Val = s\n\treturn nil\n}\n\nfunc (v IPVar) String() string {\n\tif v.Val == nil {\n\t\treturn \"\"\n\t}\n\treturn *v.Val\n}\n\nfunc (v IPVar) Type() string {\n\treturn \"ip\"\n}\n\nfunc (m *ProxyMode) Set(s string) error {\n\tnm := ProxyMode(s)\n\tm = &nm\n\treturn nil\n}\n\nfunc (m *ProxyMode) String() string {\n\tif m != nil {\n\t\treturn string(*m)\n\t}\n\treturn \"\"\n}\n\nfunc (m *ProxyMode) Type() string {\n\treturn \"ProxyMode\"\n}\n\ntype PortRangeVar struct {\n\tVal *string\n}\n\nfunc (v PortRangeVar) Set(s string) error {\n\tif _, err := utilnet.ParsePortRange(s); err != nil {\n\t\treturn fmt.Errorf(\"%q is not a valid port range: %v\", s, err)\n\t}\n\tif v.Val == nil {\n\t\t\/\/ it's okay to panic here since this is programmer error\n\t\tpanic(\"the string pointer passed into PortRangeVar should not be nil\")\n\t}\n\t*v.Val = s\n\treturn nil\n}\n\nfunc (v PortRangeVar) String() string {\n\tif v.Val == nil {\n\t\treturn \"\"\n\t}\n\treturn *v.Val\n}\n\nfunc (v PortRangeVar) Type() string {\n\treturn \"port-range\"\n}\n<commit_msg>componentconfig: fix proxy mode set func<commit_after>\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage componentconfig\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\tutilnet \"k8s.io\/kubernetes\/pkg\/util\/net\"\n)\n\n\/\/ used for validating command line opts\n\/\/ TODO(mikedanese): remove these when we remove command line flags\n\ntype IPVar struct {\n\tVal *string\n}\n\nfunc (v IPVar) Set(s string) error {\n\tif net.ParseIP(s) == nil {\n\t\treturn fmt.Errorf(\"%q is not a valid IP address\", s)\n\t}\n\tif v.Val == nil {\n\t\t\/\/ it's okay to panic here since this is programmer error\n\t\tpanic(\"the string pointer passed into IPVar should not be nil\")\n\t}\n\t*v.Val = s\n\treturn nil\n}\n\nfunc (v IPVar) String() string {\n\tif v.Val == nil {\n\t\treturn \"\"\n\t}\n\treturn *v.Val\n}\n\nfunc (v IPVar) Type() string {\n\treturn \"ip\"\n}\n\nfunc (m *ProxyMode) Set(s string) error {\n\t*m = ProxyMode(s)\n\treturn nil\n}\n\nfunc (m *ProxyMode) String() string {\n\tif m != nil {\n\t\treturn string(*m)\n\t}\n\treturn \"\"\n}\n\nfunc (m *ProxyMode) Type() string {\n\treturn \"ProxyMode\"\n}\n\ntype PortRangeVar struct {\n\tVal *string\n}\n\nfunc (v PortRangeVar) Set(s string) error {\n\tif _, err := utilnet.ParsePortRange(s); err != nil {\n\t\treturn fmt.Errorf(\"%q is not a valid port range: %v\", s, err)\n\t}\n\tif v.Val == nil {\n\t\t\/\/ it's okay to panic here since this is programmer error\n\t\tpanic(\"the string pointer passed into PortRangeVar should not be nil\")\n\t}\n\t*v.Val = s\n\treturn nil\n}\n\nfunc (v PortRangeVar) String() string {\n\tif v.Val == nil {\n\t\treturn \"\"\n\t}\n\treturn *v.Val\n}\n\nfunc (v PortRangeVar) Type() string {\n\treturn \"port-range\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package runcexecutor\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/containerd\/containerd\/contrib\/seccomp\"\n\t\"github.com\/containerd\/containerd\/mount\"\n\tcontainerdoci \"github.com\/containerd\/containerd\/oci\"\n\t\"github.com\/containerd\/continuity\/fs\"\n\trunc \"github.com\/containerd\/go-runc\"\n\t\"github.com\/moby\/buildkit\/cache\"\n\t\"github.com\/moby\/buildkit\/executor\"\n\t\"github.com\/moby\/buildkit\/executor\/oci\"\n\t\"github.com\/moby\/buildkit\/identity\"\n\t\"github.com\/moby\/buildkit\/solver\/pb\"\n\t\"github.com\/moby\/buildkit\/util\/network\"\n\trootlessspecconv \"github.com\/moby\/buildkit\/util\/rootless\/specconv\"\n\t\"github.com\/moby\/buildkit\/util\/system\"\n\tspecs \"github.com\/opencontainers\/runtime-spec\/specs-go\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\ntype Opt struct {\n\t\/\/ root directory\n\tRoot              string\n\tCommandCandidates []string\n\t\/\/ without root privileges (has nothing to do with Opt.Root directory)\n\tRootless bool\n\t\/\/ DefaultCgroupParent is the cgroup-parent name for executor\n\tDefaultCgroupParent string\n}\n\nvar defaultCommandCandidates = []string{\"buildkit-runc\", \"runc\"}\n\ntype runcExecutor struct {\n\trunc             *runc.Runc\n\troot             string\n\tcmd              string\n\tcgroupParent     string\n\trootless         bool\n\tnetworkProviders map[pb.NetMode]network.Provider\n}\n\nfunc New(opt Opt, networkProviders map[pb.NetMode]network.Provider) (executor.Executor, error) {\n\tcmds := opt.CommandCandidates\n\tif cmds == nil {\n\t\tcmds = defaultCommandCandidates\n\t}\n\n\tvar cmd string\n\tvar found bool\n\tfor _, cmd = range cmds {\n\t\tif _, err := exec.LookPath(cmd); err == nil {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn nil, errors.Errorf(\"failed to find %s binary\", cmd)\n\t}\n\n\troot := opt.Root\n\n\tif err := os.MkdirAll(root, 0700); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create %s\", root)\n\t}\n\n\troot, err := filepath.Abs(root)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\troot, err = filepath.EvalSymlinks(root)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\truntime := &runc.Runc{\n\t\tCommand:      cmd,\n\t\tLog:          filepath.Join(root, \"runc-log.json\"),\n\t\tLogFormat:    runc.JSON,\n\t\tPdeathSignal: syscall.SIGKILL,\n\t\tSetpgid:      true,\n\t\t\/\/ we don't execute runc with --rootless=(true|false) explicitly,\n\t\t\/\/ so as to support non-runc runtimes\n\t}\n\n\tw := &runcExecutor{\n\t\trunc:             runtime,\n\t\troot:             root,\n\t\tcgroupParent:     opt.DefaultCgroupParent,\n\t\trootless:         opt.Rootless,\n\t\tnetworkProviders: networkProviders,\n\t}\n\treturn w, nil\n}\n\nfunc (w *runcExecutor) Exec(ctx context.Context, meta executor.Meta, root cache.Mountable, mounts []executor.Mount, stdin io.ReadCloser, stdout, stderr io.WriteCloser) error {\n\tprovider, ok := w.networkProviders[meta.NetMode]\n\tif !ok {\n\t\treturn errors.Errorf(\"unknown network mode %s\", meta.NetMode)\n\t}\n\tnamespace, err := provider.New()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer namespace.Close()\n\n\tif meta.NetMode == pb.NetMode_HOST {\n\t\tlogrus.Info(\"enabling HostNetworking\")\n\t}\n\n\tresolvConf, err := oci.GetResolvConf(ctx, w.root)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thostsFile, clean, err := oci.GetHostsFile(ctx, w.root, meta.ExtraHosts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif clean != nil {\n\t\tdefer clean()\n\t}\n\n\tmountable, err := root.Mount(ctx, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trootMount, err := mountable.Mount()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer mountable.Release()\n\n\tid := identity.NewID()\n\tbundle := filepath.Join(w.root, id)\n\n\tif err := os.Mkdir(bundle, 0700); err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(bundle)\n\trootFSPath := filepath.Join(bundle, \"rootfs\")\n\tif err := os.Mkdir(rootFSPath, 0700); err != nil {\n\t\treturn err\n\t}\n\tif err := mount.All(rootMount, rootFSPath); err != nil {\n\t\treturn err\n\t}\n\tdefer mount.Unmount(rootFSPath, 0)\n\n\tuid, gid, sgids, err := oci.GetUser(ctx, rootFSPath, meta.User)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(filepath.Join(bundle, \"config.json\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\topts := []containerdoci.SpecOpts{oci.WithUIDGID(uid, gid, sgids)}\n\tif system.SeccompSupported() {\n\t\topts = append(opts, seccomp.WithDefaultProfile())\n\t}\n\tif meta.ReadonlyRootFS {\n\t\topts = append(opts, containerdoci.WithRootFSReadonly())\n\t}\n\n\tif w.cgroupParent != \"\" {\n\t\tvar cgroupsPath string\n\t\tlastSeparator := w.cgroupParent[len(w.cgroupParent)-1:]\n\t\tif strings.Contains(w.cgroupParent, \".slice\") && lastSeparator == \":\" {\n\t\t\tcgroupsPath = w.cgroupParent + id\n\t\t} else {\n\t\t\tcgroupsPath = filepath.Join(\"\/\", w.cgroupParent, \"buildkit\", id)\n\t\t}\n\t\topts = append(opts, containerdoci.WithCgroup(cgroupsPath))\n\t}\n\tspec, cleanup, err := oci.GenerateSpec(ctx, meta, mounts, id, resolvConf, hostsFile, namespace, opts...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cleanup()\n\n\tspec.Root.Path = rootFSPath\n\tif _, ok := root.(cache.ImmutableRef); ok { \/\/ TODO: pass in with mount, not ref type\n\t\tspec.Root.Readonly = true\n\t}\n\n\tnewp, err := fs.RootPath(rootFSPath, meta.Cwd)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"working dir %s points to invalid target\", newp)\n\t}\n\tif err := os.MkdirAll(newp, 0755); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create working directory %s\", newp)\n\t}\n\n\tif err := setOOMScoreAdj(spec); err != nil {\n\t\treturn err\n\t}\n\tif w.rootless {\n\t\tif err := rootlessspecconv.ToRootless(spec); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := json.NewEncoder(f).Encode(spec); err != nil {\n\t\treturn err\n\t}\n\n\tforwardIO, err := newForwardIO(stdin, stdout, stderr)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"creating new forwarding IO\")\n\t}\n\tdefer forwardIO.Close()\n\n\tlogrus.Debugf(\"> creating %s %v\", id, meta.Args)\n\tstatus, err := w.runc.Run(ctx, id, bundle, &runc.CreateOpts{\n\t\tIO: forwardIO,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif status != 0 {\n\t\treturn errors.Errorf(\"exit code: %d\", status)\n\t}\n\n\treturn nil\n}\n\ntype forwardIO struct {\n\tstdin, stdout, stderr *os.File\n\ttoRelease             []io.Closer\n\ttoClose               []io.Closer\n}\n\nfunc newForwardIO(stdin io.ReadCloser, stdout, stderr io.WriteCloser) (f *forwardIO, err error) {\n\tfio := &forwardIO{}\n\tdefer func() {\n\t\tif err != nil {\n\t\t\tfio.Close()\n\t\t}\n\t}()\n\tif stdin != nil {\n\t\tfio.stdin, err = fio.readCloserToFile(stdin)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif stdout != nil {\n\t\tfio.stdout, err = fio.writeCloserToFile(stdout)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif stderr != nil {\n\t\tfio.stderr, err = fio.writeCloserToFile(stderr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn fio, nil\n}\n\nfunc (s *forwardIO) Close() error {\n\ts.CloseAfterStart()\n\tvar err error\n\tfor _, cl := range s.toClose {\n\t\tif err1 := cl.Close(); err == nil {\n\t\t\terr = err1\n\t\t}\n\t}\n\ts.toClose = nil\n\treturn err\n}\n\n\/\/ release releases active FDs if the process doesn't need them any more\nfunc (s *forwardIO) CloseAfterStart() error {\n\tfor _, cl := range s.toRelease {\n\t\tcl.Close()\n\t}\n\ts.toRelease = nil\n\treturn nil\n}\n\nfunc (s *forwardIO) Set(cmd *exec.Cmd) {\n\tcmd.Stdin = s.stdin\n\tcmd.Stdout = s.stdout\n\tcmd.Stderr = s.stderr\n}\n\nfunc (s *forwardIO) readCloserToFile(rc io.ReadCloser) (*os.File, error) {\n\tif f, ok := rc.(*os.File); ok {\n\t\treturn f, nil\n\t}\n\tpr, pw, err := os.Pipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.toClose = append(s.toClose, pw)\n\ts.toRelease = append(s.toRelease, pr)\n\tgo func() {\n\t\t_, err := io.Copy(pw, rc)\n\t\tif err1 := pw.Close(); err == nil {\n\t\t\terr = err1\n\t\t}\n\t\t_ = err\n\t}()\n\treturn pr, nil\n}\n\nfunc (s *forwardIO) writeCloserToFile(wc io.WriteCloser) (*os.File, error) {\n\tif f, ok := wc.(*os.File); ok {\n\t\treturn f, nil\n\t}\n\tpr, pw, err := os.Pipe()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.toClose = append(s.toClose, pr)\n\ts.toRelease = append(s.toRelease, pw)\n\tgo func() {\n\t\t_, err := io.Copy(wc, pr)\n\t\tif err1 := pw.Close(); err == nil {\n\t\t\terr = err1\n\t\t}\n\t\t_ = err\n\t}()\n\treturn pw, nil\n}\n\nfunc (s *forwardIO) Stdin() io.WriteCloser {\n\treturn nil\n}\n\nfunc (s *forwardIO) Stdout() io.ReadCloser {\n\treturn nil\n}\n\nfunc (s *forwardIO) Stderr() io.ReadCloser {\n\treturn nil\n}\n\n\/\/ setOOMScoreAdj comes from https:\/\/github.com\/genuinetools\/img\/blob\/2fabe60b7dc4623aa392b515e013bbc69ad510ab\/executor\/runc\/executor.go#L182-L192\nfunc setOOMScoreAdj(spec *specs.Spec) error {\n\t\/\/ Set the oom_score_adj of our children containers to that of the current process.\n\tb, err := ioutil.ReadFile(\"\/proc\/self\/oom_score_adj\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to read \/proc\/self\/oom_score_adj\")\n\t}\n\ts := strings.TrimSpace(string(b))\n\toom, err := strconv.Atoi(s)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to parse %s as int\", s)\n\t}\n\tspec.Process.OOMScoreAdj = &oom\n\treturn nil\n}\n<commit_msg>runcexecutor: revert forwardio<commit_after>package runcexecutor\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/containerd\/containerd\/contrib\/seccomp\"\n\t\"github.com\/containerd\/containerd\/mount\"\n\tcontainerdoci \"github.com\/containerd\/containerd\/oci\"\n\t\"github.com\/containerd\/continuity\/fs\"\n\trunc \"github.com\/containerd\/go-runc\"\n\t\"github.com\/moby\/buildkit\/cache\"\n\t\"github.com\/moby\/buildkit\/executor\"\n\t\"github.com\/moby\/buildkit\/executor\/oci\"\n\t\"github.com\/moby\/buildkit\/identity\"\n\t\"github.com\/moby\/buildkit\/solver\/pb\"\n\t\"github.com\/moby\/buildkit\/util\/network\"\n\trootlessspecconv \"github.com\/moby\/buildkit\/util\/rootless\/specconv\"\n\t\"github.com\/moby\/buildkit\/util\/system\"\n\tspecs \"github.com\/opencontainers\/runtime-spec\/specs-go\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\ntype Opt struct {\n\t\/\/ root directory\n\tRoot              string\n\tCommandCandidates []string\n\t\/\/ without root privileges (has nothing to do with Opt.Root directory)\n\tRootless bool\n\t\/\/ DefaultCgroupParent is the cgroup-parent name for executor\n\tDefaultCgroupParent string\n}\n\nvar defaultCommandCandidates = []string{\"buildkit-runc\", \"runc\"}\n\ntype runcExecutor struct {\n\trunc             *runc.Runc\n\troot             string\n\tcmd              string\n\tcgroupParent     string\n\trootless         bool\n\tnetworkProviders map[pb.NetMode]network.Provider\n}\n\nfunc New(opt Opt, networkProviders map[pb.NetMode]network.Provider) (executor.Executor, error) {\n\tcmds := opt.CommandCandidates\n\tif cmds == nil {\n\t\tcmds = defaultCommandCandidates\n\t}\n\n\tvar cmd string\n\tvar found bool\n\tfor _, cmd = range cmds {\n\t\tif _, err := exec.LookPath(cmd); err == nil {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn nil, errors.Errorf(\"failed to find %s binary\", cmd)\n\t}\n\n\troot := opt.Root\n\n\tif err := os.MkdirAll(root, 0700); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create %s\", root)\n\t}\n\n\troot, err := filepath.Abs(root)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\troot, err = filepath.EvalSymlinks(root)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\truntime := &runc.Runc{\n\t\tCommand:      cmd,\n\t\tLog:          filepath.Join(root, \"runc-log.json\"),\n\t\tLogFormat:    runc.JSON,\n\t\tPdeathSignal: syscall.SIGKILL,\n\t\tSetpgid:      true,\n\t\t\/\/ we don't execute runc with --rootless=(true|false) explicitly,\n\t\t\/\/ so as to support non-runc runtimes\n\t}\n\n\tw := &runcExecutor{\n\t\trunc:             runtime,\n\t\troot:             root,\n\t\tcgroupParent:     opt.DefaultCgroupParent,\n\t\trootless:         opt.Rootless,\n\t\tnetworkProviders: networkProviders,\n\t}\n\treturn w, nil\n}\n\nfunc (w *runcExecutor) Exec(ctx context.Context, meta executor.Meta, root cache.Mountable, mounts []executor.Mount, stdin io.ReadCloser, stdout, stderr io.WriteCloser) error {\n\tprovider, ok := w.networkProviders[meta.NetMode]\n\tif !ok {\n\t\treturn errors.Errorf(\"unknown network mode %s\", meta.NetMode)\n\t}\n\tnamespace, err := provider.New()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer namespace.Close()\n\n\tif meta.NetMode == pb.NetMode_HOST {\n\t\tlogrus.Info(\"enabling HostNetworking\")\n\t}\n\n\tresolvConf, err := oci.GetResolvConf(ctx, w.root)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thostsFile, clean, err := oci.GetHostsFile(ctx, w.root, meta.ExtraHosts)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif clean != nil {\n\t\tdefer clean()\n\t}\n\n\tmountable, err := root.Mount(ctx, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trootMount, err := mountable.Mount()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer mountable.Release()\n\n\tid := identity.NewID()\n\tbundle := filepath.Join(w.root, id)\n\n\tif err := os.Mkdir(bundle, 0700); err != nil {\n\t\treturn err\n\t}\n\tdefer os.RemoveAll(bundle)\n\trootFSPath := filepath.Join(bundle, \"rootfs\")\n\tif err := os.Mkdir(rootFSPath, 0700); err != nil {\n\t\treturn err\n\t}\n\tif err := mount.All(rootMount, rootFSPath); err != nil {\n\t\treturn err\n\t}\n\tdefer mount.Unmount(rootFSPath, 0)\n\n\tuid, gid, sgids, err := oci.GetUser(ctx, rootFSPath, meta.User)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.Create(filepath.Join(bundle, \"config.json\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\topts := []containerdoci.SpecOpts{oci.WithUIDGID(uid, gid, sgids)}\n\tif system.SeccompSupported() {\n\t\topts = append(opts, seccomp.WithDefaultProfile())\n\t}\n\tif meta.ReadonlyRootFS {\n\t\topts = append(opts, containerdoci.WithRootFSReadonly())\n\t}\n\n\tif w.cgroupParent != \"\" {\n\t\tvar cgroupsPath string\n\t\tlastSeparator := w.cgroupParent[len(w.cgroupParent)-1:]\n\t\tif strings.Contains(w.cgroupParent, \".slice\") && lastSeparator == \":\" {\n\t\t\tcgroupsPath = w.cgroupParent + id\n\t\t} else {\n\t\t\tcgroupsPath = filepath.Join(\"\/\", w.cgroupParent, \"buildkit\", id)\n\t\t}\n\t\topts = append(opts, containerdoci.WithCgroup(cgroupsPath))\n\t}\n\tspec, cleanup, err := oci.GenerateSpec(ctx, meta, mounts, id, resolvConf, hostsFile, namespace, opts...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer cleanup()\n\n\tspec.Root.Path = rootFSPath\n\tif _, ok := root.(cache.ImmutableRef); ok { \/\/ TODO: pass in with mount, not ref type\n\t\tspec.Root.Readonly = true\n\t}\n\n\tnewp, err := fs.RootPath(rootFSPath, meta.Cwd)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"working dir %s points to invalid target\", newp)\n\t}\n\tif err := os.MkdirAll(newp, 0755); err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create working directory %s\", newp)\n\t}\n\n\tif err := setOOMScoreAdj(spec); err != nil {\n\t\treturn err\n\t}\n\tif w.rootless {\n\t\tif err := rootlessspecconv.ToRootless(spec); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := json.NewEncoder(f).Encode(spec); err != nil {\n\t\treturn err\n\t}\n\n\tlogrus.Debugf(\"> creating %s %v\", id, meta.Args)\n\tstatus, err := w.runc.Run(ctx, id, bundle, &runc.CreateOpts{\n\t\tIO: &forwardIO{stdin: stdin, stdout: stdout, stderr: stderr},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif status != 0 {\n\t\treturn errors.Errorf(\"exit code: %d\", status)\n\t}\n\n\treturn nil\n}\n\ntype forwardIO struct {\n\tstdin          io.ReadCloser\n\tstdout, stderr io.WriteCloser\n}\n\nfunc (s *forwardIO) Close() error {\n\treturn nil\n}\n\nfunc (s *forwardIO) Set(cmd *exec.Cmd) {\n\tcmd.Stdin = s.stdin\n\tcmd.Stdout = s.stdout\n\tcmd.Stderr = s.stderr\n}\n\nfunc (s *forwardIO) Stdin() io.WriteCloser {\n\treturn nil\n}\n\nfunc (s *forwardIO) Stdout() io.ReadCloser {\n\treturn nil\n}\n\nfunc (s *forwardIO) Stderr() io.ReadCloser {\n\treturn nil\n}\n\n\/\/ setOOMScoreAdj comes from https:\/\/github.com\/genuinetools\/img\/blob\/2fabe60b7dc4623aa392b515e013bbc69ad510ab\/executor\/runc\/executor.go#L182-L192\nfunc setOOMScoreAdj(spec *specs.Spec) error {\n\t\/\/ Set the oom_score_adj of our children containers to that of the current process.\n\tb, err := ioutil.ReadFile(\"\/proc\/self\/oom_score_adj\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to read \/proc\/self\/oom_score_adj\")\n\t}\n\ts := strings.TrimSpace(string(b))\n\toom, err := strconv.Atoi(s)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to parse %s as int\", s)\n\t}\n\tspec.Process.OOMScoreAdj = &oom\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package gaurun\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\ntype globalsStore struct {\n\tConfGaurun        ConfToml\n\tQueueNotification chan RequestGaurunNotification\n}\n\nvar (\n\tstore globalsStore\n)\n\nfunc (store globalsStore) save() {\n\tstore.QueueNotification = QueueNotification\n\tstore.ConfGaurun = ConfGaurun\n}\n\nfunc (store globalsStore) restore() {\n\tQueueNotification = store.QueueNotification\n\tConfGaurun = store.ConfGaurun\n}\n\nfunc TestEnqueueNotifications(t *testing.T) {\n\tstore.save()\n\tdefer store.restore()\n\n\tpositiveCases := []struct {\n\t\tN []RequestGaurunNotification\n\t\tC ConfToml\n\t}{\n\t\t{\n\t\t\t[]RequestGaurunNotification{\n\t\t\t\t{\n\t\t\t\t\tTokens:   []string{\"test token\"},\n\t\t\t\t\tPlatform: 1,\n\t\t\t\t\tMessage:  \"test message\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTokens:   []string{\"test token\"},\n\t\t\t\t\tPlatform: 2,\n\t\t\t\t\tMessage:  \"test message\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tConfToml{Ios: SectionIos{Enabled: true}, Android: SectionAndroid{Enabled: true}},\n\t\t},\n\t}\n\n\tnegativeCases := []struct {\n\t\tN []RequestGaurunNotification\n\t\tC ConfToml\n\t}{\n\t\t\/\/ push is disabled\n\t\t{\n\t\t\t[]RequestGaurunNotification{\n\t\t\t\t{\n\t\t\t\t\tTokens:   []string{\"test token\"},\n\t\t\t\t\tPlatform: 1,\n\t\t\t\t\tMessage:  \"test message\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tTokens:   []string{\"test token\"},\n\t\t\t\t\tPlatform: 2,\n\t\t\t\t\tMessage:  \"test message\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tConfToml{Ios: SectionIos{Enabled: false}, Android: SectionAndroid{Enabled: false}},\n\t\t},\n\n\t\t\/\/ config is invalid\n\t\t{\n\t\t\t[]RequestGaurunNotification{\n\t\t\t\t{\n\t\t\t\t\tTokens: []string{\"\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\tConfToml{Ios: SectionIos{Enabled: true}, Android: SectionAndroid{Enabled: true}},\n\t\t},\n\t\t{\n\t\t\t[]RequestGaurunNotification{\n\t\t\t\t{\n\t\t\t\t\tTokens:   []string{\"test token\"},\n\t\t\t\t\tPlatform: 100, \/* neither iOS nor Android *\/\n\t\t\t\t\tMessage:  \"test message\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tConfToml{Ios: SectionIos{Enabled: true}, Android: SectionAndroid{Enabled: true}},\n\t\t},\n\t}\n\n\tfor _, c := range positiveCases {\n\t\tQueueNotification = make(chan RequestGaurunNotification, len(c.N))\n\t\tConfGaurun = c.C\n\n\t\tenqueueNotifications(c.N)\n\n\t\tassert.Equal(t, len(QueueNotification), len(c.N))\n\t}\n\n\tfor _, c := range negativeCases {\n\t\tQueueNotification = make(chan RequestGaurunNotification, len(c.N))\n\t\tConfGaurun = c.C\n\n\t\tenqueueNotifications(c.N)\n\n\t\tassert.Equal(t, len(QueueNotification), 0)\n\t}\n}\n\nfunc TestValidateNotification(t *testing.T) {\n\tcases := []struct {\n\t\tNotification RequestGaurunNotification\n\t\tExpected     error\n\t}{\n\t\t\/\/ positive cases\n\t\t{\n\t\t\tRequestGaurunNotification{\n\t\t\t\tTokens:   []string{\"test token\"},\n\t\t\t\tPlatform: 1,\n\t\t\t\tMessage:  \"test message\",\n\t\t\t},\n\t\t\tnil,\n\t\t},\n\t\t{\n\t\t\tRequestGaurunNotification{\n\t\t\t\tTokens:   []string{\"test token\"},\n\t\t\t\tPlatform: 2,\n\t\t\t\tMessage:  \"test message\",\n\t\t\t},\n\t\t\tnil,\n\t\t},\n\n\t\t\/\/ negative cases\n\t\t{\n\t\t\tRequestGaurunNotification{\n\t\t\t\tTokens: []string{\"\"},\n\t\t\t},\n\t\t\terrors.New(\"empty token\"),\n\t\t},\n\t\t{\n\t\t\tRequestGaurunNotification{\n\t\t\t\tTokens:   []string{\"test token\"},\n\t\t\t\tPlatform: 100, \/* neither iOS nor Android *\/\n\t\t\t},\n\t\t\terrors.New(\"invalid platform\"),\n\t\t},\n\t\t{\n\t\t\tRequestGaurunNotification{\n\t\t\t\tTokens:   []string{\"test token\"},\n\t\t\t\tPlatform: 1,\n\t\t\t\tMessage:  \"\",\n\t\t\t},\n\t\t\terrors.New(\"empty message\"),\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tactual := validateNotification(&c.Notification)\n\t\tassert.Equal(t, actual, c.Expected)\n\t}\n}\n\nfunc TestSendResponse(t *testing.T) {\n\ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tsendResponse(w, \"valid message\", http.StatusOK)\n\t\treturn\n\t}))\n\tdefer s.Close()\n\n\tres, err := http.Get(s.URL)\n\tassert.Nil(t, err)\n\tassert.Equal(t, res.StatusCode, http.StatusOK)\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tassert.Nil(t, err)\n\tassert.Equal(t, string(body), \"{\\\"message\\\":\\\"valid message\\\"}\\n\")\n}\n\nfunc TestPushNotificationHandler(t *testing.T) {\n\tstore.save()\n\tdefer store.restore()\n\n\tcases := []struct {\n\t\tMethod       string\n\t\tRequestBody  string\n\t\tConf         ConfToml\n\t\tExpectedBody string\n\t\tExpectedCode int\n\t}{\n\t\t{\n\t\t\t\"GET\",\n\t\t\t\"\",\n\t\t\tConfToml{},\n\t\t\t\"{\\\"message\\\":\\\"method must be POST\\\"}\\n\",\n\t\t\thttp.StatusBadRequest,\n\t\t},\n\t\t{\n\t\t\t\"POST\",\n\t\t\t\"\",\n\t\t\tConfToml{},\n\t\t\t\"{\\\"message\\\":\\\"request body is empty\\\"}\\n\",\n\t\t\thttp.StatusBadRequest,\n\t\t},\n\t\t{\n\t\t\t\"POST\",\n\t\t\t\"invalid json\",\n\t\t\tConfToml{},\n\t\t\t\"{\\\"message\\\":\\\"Request-body is malformed\\\"}\\n\",\n\t\t\thttp.StatusBadRequest,\n\t\t},\n\t\t\/* NOTE It gets \"empty notification\" actually ...\n\t\t   {\n\t\t     \"POST\",\n\t\t     \"invalid json\",\n\t\t     ConfToml{Log: SectionLog{Level: \"debug\"}},\n\t\t     \"{\\\"message\\\":\\\"Request-body is malformed\\\"}\\n\",\n\t\t     http.StatusBadRequest,\n\t\t   },\n\t\t*\/\n\t\t{\n\t\t\t\"POST\",\n\t\t\t\"{\\\"notifications\\\":[]}\",\n\t\t\tConfToml{},\n\t\t\t\"{\\\"message\\\":\\\"empty notification\\\"}\\n\",\n\t\t\thttp.StatusBadRequest,\n\t\t},\n\t\t{\n\t\t\t\"POST\",\n\t\t\t\"{\\\"notifications\\\":[{}]}\",\n\t\t\tConfToml{Core: SectionCore{NotificationMax: 0}},\n\t\t\t\"{\\\"message\\\":\\\"number of notifications(1) over limit(0)\\\"}\\n\",\n\t\t\thttp.StatusBadRequest,\n\t\t},\n\t\t\/\/ NOTE It will cause goroutine leak ...\n\t\t{\n\t\t\t\"POST\",\n\t\t\t\"{\\\"notifications\\\":[{}]}\",\n\t\t\tConfToml{Core: SectionCore{NotificationMax: 10}},\n\t\t\t\"{\\\"message\\\":\\\"ok\\\"}\\n\",\n\t\t\thttp.StatusOK,\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\ts := httptest.NewServer(http.HandlerFunc(PushNotificationHandler))\n\t\tdefer s.Close()\n\n\t\tConfGaurun = c.Conf\n\n\t\tclient := http.Client{}\n\t\treq, _ := http.NewRequest(c.Method, s.URL, bytes.NewBufferString(c.RequestBody))\n\t\tres, err := client.Do(req)\n\n\t\tassert.Nil(t, err)\n\t\tassert.Equal(t, res.StatusCode, c.ExpectedCode)\n\n\t\tbody, err := ioutil.ReadAll(res.Body)\n\t\tassert.Nil(t, err)\n\t\tassert.Equal(t, string(body), c.ExpectedBody)\n\t}\n}\n<commit_msg>Remove test codes modify global variables<commit_after>package gaurun\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestValidateNotification(t *testing.T) {\n\tcases := []struct {\n\t\tNotification RequestGaurunNotification\n\t\tExpected     error\n\t}{\n\t\t\/\/ positive cases\n\t\t{\n\t\t\tRequestGaurunNotification{\n\t\t\t\tTokens:   []string{\"test token\"},\n\t\t\t\tPlatform: 1,\n\t\t\t\tMessage:  \"test message\",\n\t\t\t},\n\t\t\tnil,\n\t\t},\n\t\t{\n\t\t\tRequestGaurunNotification{\n\t\t\t\tTokens:   []string{\"test token\"},\n\t\t\t\tPlatform: 2,\n\t\t\t\tMessage:  \"test message\",\n\t\t\t},\n\t\t\tnil,\n\t\t},\n\n\t\t\/\/ negative cases\n\t\t{\n\t\t\tRequestGaurunNotification{\n\t\t\t\tTokens: []string{\"\"},\n\t\t\t},\n\t\t\terrors.New(\"empty token\"),\n\t\t},\n\t\t{\n\t\t\tRequestGaurunNotification{\n\t\t\t\tTokens:   []string{\"test token\"},\n\t\t\t\tPlatform: 100, \/* neither iOS nor Android *\/\n\t\t\t},\n\t\t\terrors.New(\"invalid platform\"),\n\t\t},\n\t\t{\n\t\t\tRequestGaurunNotification{\n\t\t\t\tTokens:   []string{\"test token\"},\n\t\t\t\tPlatform: 1,\n\t\t\t\tMessage:  \"\",\n\t\t\t},\n\t\t\terrors.New(\"empty message\"),\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tactual := validateNotification(&c.Notification)\n\t\tassert.Equal(t, actual, c.Expected)\n\t}\n}\n\nfunc TestSendResponse(t *testing.T) {\n\ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tsendResponse(w, \"valid message\", http.StatusOK)\n\t\treturn\n\t}))\n\tdefer s.Close()\n\n\tres, err := http.Get(s.URL)\n\tassert.Nil(t, err)\n\tassert.Equal(t, res.StatusCode, http.StatusOK)\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tassert.Nil(t, err)\n\tassert.Equal(t, string(body), \"{\\\"message\\\":\\\"valid message\\\"}\\n\")\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2020 Docker Compose CLI authors\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage e2e\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gotest.tools\/v3\/assert\"\n\t\"gotest.tools\/v3\/icmd\"\n)\n\nfunc TestEnvPriority(t *testing.T) {\n\tc := NewParallelCLI(t)\n\n\tprojectDir := \".\/fixtures\/environment\/env-priority\"\n\n\tt.Run(\"up\", func(t *testing.T) {\n\t\tc.RunDockerOrExitError(t, \"rmi\", \"env-compose-priority\")\n\t\tc.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose-with-env.yaml\",\n\t\t\t\"--project-directory\", projectDir, \"up\", \"-d\", \"--build\")\n\t})\n\n\t\/\/ Full options activated\n\t\/\/ 1. Compose file <-- Result expected\n\t\/\/ 2. Shell environment variables\n\t\/\/ 3. Environment file\n\t\/\/ 4. Dockerfile\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"compose file priority\", func(t *testing.T) {\n\t\tcmd := c.NewDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose-with-env.yaml\",\n\t\t\t\"--project-directory\", projectDir, \"--env-file\", \".\/fixtures\/environment\/env-priority\/.env.override\", \"run\",\n\t\t\t\"--rm\", \"-e\", \"WHEREAMI\", \"env-compose-priority\")\n\t\tres := icmd.RunCmd(cmd, icmd.WithEnv(\"WHEREAMI=shell\"))\n\t\tassert.Equal(t, strings.TrimSpace(res.Stdout()), \"Compose File\")\n\t})\n\n\t\/\/ No Compose file, all other options\n\t\/\/ 1. Compose file\n\t\/\/ 2. Shell environment variables <-- Result expected\n\t\/\/ 3. Environment file\n\t\/\/ 4. Dockerfile\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"shell priority\", func(t *testing.T) {\n\t\tcmd := c.NewDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose.yaml\", \"--project-directory\",\n\t\t\tprojectDir, \"--env-file\", \".\/fixtures\/environment\/env-priority\/.env.override\", \"run\", \"--rm\", \"-e\",\n\t\t\t\"WHEREAMI\", \"env-compose-priority\")\n\t\tres := icmd.RunCmd(cmd, icmd.WithEnv(\"WHEREAMI=shell\"))\n\t\tassert.Equal(t, strings.TrimSpace(res.Stdout()), \"shell\")\n\t})\n\n\t\/\/  No Compose file and env variable pass to the run command\n\t\/\/ 1. Compose file\n\t\/\/ 2. Shell environment variables <-- Result expected\n\t\/\/ 3. Environment file\n\t\/\/ 4. Dockerfile\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"shell priority from run command\", func(t *testing.T) {\n\t\tres := c.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose.yaml\", \"--project-directory\",\n\t\t\tprojectDir, \"--env-file\", \".\/fixtures\/environment\/env-priority\/.env.override\", \"run\", \"--rm\", \"-e\",\n\t\t\t\"WHEREAMI=shell-run\", \"env-compose-priority\")\n\t\tassert.Equal(t, strings.TrimSpace(res.Stdout()), \"shell-run\")\n\t})\n\n\t\/\/  No Compose file & no env variable but override env file\n\t\/\/ 1. Compose file\n\t\/\/ 2. Shell environment variables\n\t\/\/ 3. Environment file <-- Result expected\n\t\/\/ 4. Dockerfile\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"override env file\", func(t *testing.T) {\n\t\tres := c.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose.yaml\", \"--project-directory\",\n\t\t\tprojectDir, \"--env-file\", \".\/fixtures\/environment\/env-priority\/.env.override\", \"run\", \"--rm\", \"-e\",\n\t\t\t\"WHEREAMI\", \"env-compose-priority\")\n\t\tassert.Equal(t, strings.TrimSpace(res.Stdout()), \"override\")\n\t})\n\n\t\/\/  No Compose file & no env variable but override env file\n\t\/\/ 1. Compose file\n\t\/\/ 2. Shell environment variables\n\t\/\/ 3. Environment file <-- Result expected\n\t\/\/ 4. Dockerfile\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"env file\", func(t *testing.T) {\n\t\tres := c.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose.yaml\", \"--project-directory\",\n\t\t\tprojectDir, \"run\", \"--rm\", \"-e\", \"WHEREAMI\", \"env-compose-priority\")\n\t\tassert.Equal(t, strings.TrimSpace(res.Stdout()), \"Env File\")\n\t})\n\n\t\/\/  No Compose file & no env variable, using an empty override env file\n\t\/\/ 1. Compose file\n\t\/\/ 2. Shell environment variables\n\t\/\/ 3. Environment file\n\t\/\/ 4. Dockerfile   <-- Result expected\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"use Dockerfile\", func(t *testing.T) {\n\t\tres := c.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose.yaml\", \"--project-directory\",\n\t\t\tprojectDir, \"--env-file\", \".\/fixtures\/environment\/env-priority\/.env.empty\", \"run\", \"--rm\", \"-e\", \"WHEREAMI\",\n\t\t\t\"env-compose-priority\")\n\t\tassert.Equal(t, strings.TrimSpace(res.Stdout()), \"Dockerfile\")\n\t})\n\n\tt.Run(\"down\", func(t *testing.T) {\n\t\tc.RunDockerComposeCmd(t, \"--project-directory\", projectDir, \"down\")\n\t})\n}\n\nfunc TestEnvInterpolation(t *testing.T) {\n\tc := NewParallelCLI(t)\n\n\tprojectDir := \".\/fixtures\/environment\/env-interpolation\"\n\n\t\/\/  No variable defined in the Compose file and env variable pass to the run command\n\t\/\/ 1. Compose file\n\t\/\/ 2. Shell environment variables <-- Result expected\n\t\/\/ 3. Environment file\n\t\/\/ 4. Dockerfile\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"shell priority from run command\", func(t *testing.T) {\n\t\tcmd := c.NewDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-interpolation\/compose.yaml\",\n\t\t\t\"--project-directory\", projectDir, \"config\")\n\t\tres := icmd.RunCmd(cmd, icmd.WithEnv(\"WHEREAMI=shell\"))\n\t\tres.Assert(t, icmd.Expected{Out: `IMAGE: default_env:shell`})\n\t})\n}\n\nfunc TestCommentsInEnvFile(t *testing.T) {\n\tc := NewParallelCLI(t)\n\n\tprojectDir := \".\/fixtures\/environment\/env-file-comments\"\n\n\tt.Run(\"comments in env files\", func(t *testing.T) {\n\t\tc.RunDockerOrExitError(t, \"rmi\", \"env-file-comments\")\n\n\t\tc.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-file-comments\/compose.yaml\", \"--project-directory\",\n\t\t\tprojectDir, \"up\", \"-d\", \"--build\")\n\n\t\tres := c.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-file-comments\/compose.yaml\",\n\t\t\t\"--project-directory\", projectDir, \"run\", \"--rm\", \"-e\", \"COMMENT\", \"-e\", \"NO_COMMENT\", \"env-file-comments\")\n\n\t\tres.Assert(t, icmd.Expected{Out: `COMMENT=1234`})\n\t\tres.Assert(t, icmd.Expected{Out: `NO_COMMENT=1234#5`})\n\n\t\tc.RunDockerComposeCmd(t, \"--project-directory\", projectDir, \"down\", \"--rmi\", \"all\")\n\t})\n}\n<commit_msg>e2e: fix per-command env overrides<commit_after>\/*\n   Copyright 2020 Docker Compose CLI authors\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage e2e\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"gotest.tools\/v3\/assert\"\n\t\"gotest.tools\/v3\/icmd\"\n)\n\nfunc TestEnvPriority(t *testing.T) {\n\tc := NewParallelCLI(t)\n\n\tprojectDir := \".\/fixtures\/environment\/env-priority\"\n\n\tt.Run(\"up\", func(t *testing.T) {\n\t\tc.RunDockerOrExitError(t, \"rmi\", \"env-compose-priority\")\n\t\tc.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose-with-env.yaml\",\n\t\t\t\"--project-directory\", projectDir, \"up\", \"-d\", \"--build\")\n\t})\n\n\t\/\/ Full options activated\n\t\/\/ 1. Compose file <-- Result expected\n\t\/\/ 2. Shell environment variables\n\t\/\/ 3. Environment file\n\t\/\/ 4. Dockerfile\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"compose file priority\", func(t *testing.T) {\n\t\tcmd := c.NewDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose-with-env.yaml\",\n\t\t\t\"--project-directory\", projectDir, \"--env-file\", \".\/fixtures\/environment\/env-priority\/.env.override\", \"run\",\n\t\t\t\"--rm\", \"-e\", \"WHEREAMI\", \"env-compose-priority\")\n\t\tcmd.Env = append(cmd.Env, \"WHEREAMI=shell\")\n\t\tres := icmd.RunCmd(cmd)\n\t\tassert.Equal(t, strings.TrimSpace(res.Stdout()), \"Compose File\")\n\t})\n\n\t\/\/ No Compose file, all other options\n\t\/\/ 1. Compose file\n\t\/\/ 2. Shell environment variables <-- Result expected\n\t\/\/ 3. Environment file\n\t\/\/ 4. Dockerfile\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"shell priority\", func(t *testing.T) {\n\t\tcmd := c.NewDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose.yaml\", \"--project-directory\",\n\t\t\tprojectDir, \"--env-file\", \".\/fixtures\/environment\/env-priority\/.env.override\", \"run\", \"--rm\", \"-e\",\n\t\t\t\"WHEREAMI\", \"env-compose-priority\")\n\t\tcmd.Env = append(cmd.Env, \"WHEREAMI=shell\")\n\t\tres := icmd.RunCmd(cmd)\n\t\tassert.Equal(t, strings.TrimSpace(res.Stdout()), \"shell\")\n\t})\n\n\t\/\/  No Compose file and env variable pass to the run command\n\t\/\/ 1. Compose file\n\t\/\/ 2. Shell environment variables <-- Result expected\n\t\/\/ 3. Environment file\n\t\/\/ 4. Dockerfile\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"shell priority from run command\", func(t *testing.T) {\n\t\tres := c.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose.yaml\", \"--project-directory\",\n\t\t\tprojectDir, \"--env-file\", \".\/fixtures\/environment\/env-priority\/.env.override\", \"run\", \"--rm\", \"-e\",\n\t\t\t\"WHEREAMI=shell-run\", \"env-compose-priority\")\n\t\tassert.Equal(t, strings.TrimSpace(res.Stdout()), \"shell-run\")\n\t})\n\n\t\/\/  No Compose file & no env variable but override env file\n\t\/\/ 1. Compose file\n\t\/\/ 2. Shell environment variables\n\t\/\/ 3. Environment file <-- Result expected\n\t\/\/ 4. Dockerfile\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"override env file\", func(t *testing.T) {\n\t\tres := c.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose.yaml\", \"--project-directory\",\n\t\t\tprojectDir, \"--env-file\", \".\/fixtures\/environment\/env-priority\/.env.override\", \"run\", \"--rm\", \"-e\",\n\t\t\t\"WHEREAMI\", \"env-compose-priority\")\n\t\tassert.Equal(t, strings.TrimSpace(res.Stdout()), \"override\")\n\t})\n\n\t\/\/  No Compose file & no env variable but override env file\n\t\/\/ 1. Compose file\n\t\/\/ 2. Shell environment variables\n\t\/\/ 3. Environment file <-- Result expected\n\t\/\/ 4. Dockerfile\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"env file\", func(t *testing.T) {\n\t\tres := c.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose.yaml\", \"--project-directory\",\n\t\t\tprojectDir, \"run\", \"--rm\", \"-e\", \"WHEREAMI\", \"env-compose-priority\")\n\t\tassert.Equal(t, strings.TrimSpace(res.Stdout()), \"Env File\")\n\t})\n\n\t\/\/  No Compose file & no env variable, using an empty override env file\n\t\/\/ 1. Compose file\n\t\/\/ 2. Shell environment variables\n\t\/\/ 3. Environment file\n\t\/\/ 4. Dockerfile   <-- Result expected\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"use Dockerfile\", func(t *testing.T) {\n\t\tres := c.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-priority\/compose.yaml\", \"--project-directory\",\n\t\t\tprojectDir, \"--env-file\", \".\/fixtures\/environment\/env-priority\/.env.empty\", \"run\", \"--rm\", \"-e\", \"WHEREAMI\",\n\t\t\t\"env-compose-priority\")\n\t\tassert.Equal(t, strings.TrimSpace(res.Stdout()), \"Dockerfile\")\n\t})\n\n\tt.Run(\"down\", func(t *testing.T) {\n\t\tc.RunDockerComposeCmd(t, \"--project-directory\", projectDir, \"down\")\n\t})\n}\n\nfunc TestEnvInterpolation(t *testing.T) {\n\tc := NewParallelCLI(t)\n\n\tprojectDir := \".\/fixtures\/environment\/env-interpolation\"\n\n\t\/\/  No variable defined in the Compose file and env variable pass to the run command\n\t\/\/ 1. Compose file\n\t\/\/ 2. Shell environment variables <-- Result expected\n\t\/\/ 3. Environment file\n\t\/\/ 4. Dockerfile\n\t\/\/ 5. Variable is not defined\n\tt.Run(\"shell priority from run command\", func(t *testing.T) {\n\t\tcmd := c.NewDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-interpolation\/compose.yaml\",\n\t\t\t\"--project-directory\", projectDir, \"config\")\n\t\tcmd.Env = append(cmd.Env, \"WHEREAMI=shell\")\n\t\tres := icmd.RunCmd(cmd)\n\t\tres.Assert(t, icmd.Expected{Out: `IMAGE: default_env:shell`})\n\t})\n}\n\nfunc TestCommentsInEnvFile(t *testing.T) {\n\tc := NewParallelCLI(t)\n\n\tprojectDir := \".\/fixtures\/environment\/env-file-comments\"\n\n\tt.Run(\"comments in env files\", func(t *testing.T) {\n\t\tc.RunDockerOrExitError(t, \"rmi\", \"env-file-comments\")\n\n\t\tc.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-file-comments\/compose.yaml\", \"--project-directory\",\n\t\t\tprojectDir, \"up\", \"-d\", \"--build\")\n\n\t\tres := c.RunDockerComposeCmd(t, \"-f\", \".\/fixtures\/environment\/env-file-comments\/compose.yaml\",\n\t\t\t\"--project-directory\", projectDir, \"run\", \"--rm\", \"-e\", \"COMMENT\", \"-e\", \"NO_COMMENT\", \"env-file-comments\")\n\n\t\tres.Assert(t, icmd.Expected{Out: `COMMENT=1234`})\n\t\tres.Assert(t, icmd.Expected{Out: `NO_COMMENT=1234#5`})\n\n\t\tc.RunDockerComposeCmd(t, \"--project-directory\", projectDir, \"down\", \"--rmi\", \"all\")\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package resolve\n\nimport (\n\t\"github.com\/Aptomi\/aptomi\/pkg\/lang\"\n\t\"strings\"\n)\n\n\/\/ componentInstanceKeySeparator is a separator between strings in ComponentInstanceKey\nconst componentInstanceKeySeparator = \"#\"\n\n\/\/ componentUnresolvedName is placeholder for unresolved entries\nconst componentUnresolvedName = \"unknown\"\n\n\/\/ componentRootName is a name of component for service entry (which in turn consists of components)\nconst componentRootName = \"root\"\n\n\/\/ ComponentInstanceKey is a key for component instance. During policy resolution every component instance gets\n\/\/ assigned a unique string key. It's important to form those keys correctly, so that we can make actual comparison\n\/\/ of actual state (components with their keys) and desired state (components with their keys).\n\/\/\n\/\/ Currently, component keys are formed from multiple parameters as follows.\n\/\/ Cluster gets included as a part of the key (components running on different clusters must have different keys).\n\/\/ Namespace gets included as a part of the key (components from different namespaces must have different keys).\n\/\/ Contract, Context (with allocation keys), Service get included as a part of the key (Service must be within the same namespace as Contract).\n\/\/ ComponentName gets included as a part of the key. For service-level component instances, ComponentName is\n\/\/ set to componentRootName, while for all component instances within a service an actual Component.Name is used.\ntype ComponentInstanceKey struct {\n\t\/\/ cached version of component key\n\tkey string\n\n\t\/\/ required fields\n\tClusterName         string \/\/ mandatory\n\tNamespace           string \/\/ determined from the contract\n\tContractName        string \/\/ mandatory\n\tContextName         string \/\/ mandatory\n\tKeysResolved        string \/\/ mandatory\n\tContextNameWithKeys string \/\/ calculated\n\tServiceName         string \/\/ determined from the context (included into key for readability)\n\tComponentName       string \/\/ component name\n}\n\n\/\/ NewComponentInstanceKey creates a new ComponentInstanceKey\nfunc NewComponentInstanceKey(cluster *lang.Cluster, contract *lang.Contract, context *lang.Context, allocationKeysResolved []string, service *lang.Service, component *lang.ServiceComponent) *ComponentInstanceKey {\n\tcontextName := getContextNameUnsafe(context)\n\tkeysResolved := strings.Join(allocationKeysResolved, componentInstanceKeySeparator)\n\tcontextNameWithKeys := strings.Join([]string{contextName, keysResolved}, componentInstanceKeySeparator)\n\treturn &ComponentInstanceKey{\n\t\tClusterName:         getClusterNameUnsafe(cluster),\n\t\tNamespace:           getContractNamespaceUnsafe(contract),\n\t\tContractName:        getContractNameUnsafe(contract),\n\t\tContextName:         contextName,\n\t\tKeysResolved:        keysResolved,\n\t\tContextNameWithKeys: contextNameWithKeys,\n\t\tServiceName:         getServiceNameUnsafe(service),\n\t\tComponentName:       getComponentNameUnsafe(component),\n\t}\n}\n\n\/\/ MakeCopy creates a copy of ComponentInstanceKey\nfunc (cik *ComponentInstanceKey) MakeCopy() *ComponentInstanceKey {\n\treturn &ComponentInstanceKey{\n\t\tClusterName:         cik.ClusterName,\n\t\tNamespace:           cik.Namespace,\n\t\tContractName:        cik.ContractName,\n\t\tContextName:         cik.ContextName,\n\t\tKeysResolved:        cik.KeysResolved,\n\t\tContextNameWithKeys: cik.ContextNameWithKeys,\n\t\tComponentName:       cik.ComponentName,\n\t}\n}\n\n\/\/ IsService returns 'true' if it's a contract instance key and we can't go up anymore. And it will return 'false' if it's a component instance key\nfunc (cik *ComponentInstanceKey) IsService() bool {\n\treturn cik.ComponentName == componentRootName\n}\n\n\/\/ IsComponent returns 'true' if it's a component instance key and we can go up to the corresponding service. And it will return 'false' if it's a service instance key\nfunc (cik *ComponentInstanceKey) IsComponent() bool {\n\treturn cik.ComponentName != componentRootName\n}\n\n\/\/ GetParentServiceKey returns a key for the parent service, replacing componentName with componentRootName\nfunc (cik *ComponentInstanceKey) GetParentServiceKey() *ComponentInstanceKey {\n\tif cik.ComponentName == componentRootName {\n\t\treturn cik\n\t}\n\tserviceCik := cik.MakeCopy()\n\tserviceCik.ComponentName = componentRootName\n\treturn serviceCik\n}\n\n\/\/ GetKey returns a string key\nfunc (cik ComponentInstanceKey) GetKey() string {\n\tif cik.key == \"\" {\n\t\tcik.key = strings.Join(\n\t\t\t[]string{\n\t\t\t\tcik.ClusterName,\n\t\t\t\tcik.Namespace,\n\t\t\t\tcik.ContractName,\n\t\t\t\tcik.ContextNameWithKeys,\n\t\t\t\tcik.ComponentName,\n\t\t\t}, componentInstanceKeySeparator)\n\t}\n\treturn cik.key\n}\n\n\/\/ GetDeployName returns a string that could be used as name for deployment inside the cluster\nfunc (cik ComponentInstanceKey) GetDeployName() string {\n\treturn strings.Join(\n\t\t[]string{\n\t\t\tcik.Namespace,\n\t\t\tcik.ContractName,\n\t\t\tcik.ContextNameWithKeys,\n\t\t\tcik.ComponentName,\n\t\t}, componentInstanceKeySeparator)\n}\n\n\/\/ If cluster has not been resolved yet and we need a key, generate one\n\/\/ Otherwise use cluster name\nfunc getClusterNameUnsafe(cluster *lang.Cluster) string {\n\tif cluster == nil {\n\t\treturn componentUnresolvedName\n\t}\n\treturn cluster.Name\n}\n\n\/\/ If contract has not been resolved yet and we need a key, generate one\n\/\/ Otherwise use contract name\nfunc getContractNameUnsafe(contract *lang.Contract) string {\n\tif contract == nil {\n\t\treturn componentUnresolvedName\n\t}\n\treturn contract.Name\n}\n\n\/\/ If contract has not been resolved yet and we need a key, generate one\n\/\/ Otherwise use contract namespace\nfunc getContractNamespaceUnsafe(contract *lang.Contract) string {\n\tif contract == nil {\n\t\treturn componentUnresolvedName\n\t}\n\treturn contract.Namespace\n}\n\n\/\/ If context has not been resolved yet and we need a key, generate one\n\/\/ Otherwise use context name\nfunc getContextNameUnsafe(context *lang.Context) string {\n\tif context == nil {\n\t\treturn componentUnresolvedName\n\t}\n\treturn context.Name\n}\n\n\/\/ If service has not been resolved yet and we need a key, generate one\n\/\/ Otherwise use service name\nfunc getServiceNameUnsafe(service *lang.Service) string {\n\tif service == nil {\n\t\treturn componentUnresolvedName\n\t}\n\treturn service.Name\n}\n\n\/\/ If component has not been resolved yet and we need a key, generate one\n\/\/ Otherwise use component name\nfunc getComponentNameUnsafe(component *lang.ServiceComponent) string {\n\tif component == nil {\n\t\treturn componentRootName\n\t}\n\treturn component.Name\n}\n<commit_msg>fixed component key generation (do not add revolved keys if they are empty)<commit_after>package resolve\n\nimport (\n\t\"github.com\/Aptomi\/aptomi\/pkg\/lang\"\n\t\"strings\"\n)\n\n\/\/ componentInstanceKeySeparator is a separator between strings in ComponentInstanceKey\nconst componentInstanceKeySeparator = \"#\"\n\n\/\/ componentUnresolvedName is placeholder for unresolved entries\nconst componentUnresolvedName = \"unknown\"\n\n\/\/ componentRootName is a name of component for service entry (which in turn consists of components)\nconst componentRootName = \"root\"\n\n\/\/ ComponentInstanceKey is a key for component instance. During policy resolution every component instance gets\n\/\/ assigned a unique string key. It's important to form those keys correctly, so that we can make actual comparison\n\/\/ of actual state (components with their keys) and desired state (components with their keys).\n\/\/\n\/\/ Currently, component keys are formed from multiple parameters as follows.\n\/\/ Cluster gets included as a part of the key (components running on different clusters must have different keys).\n\/\/ Namespace gets included as a part of the key (components from different namespaces must have different keys).\n\/\/ Contract, Context (with allocation keys), Service get included as a part of the key (Service must be within the same namespace as Contract).\n\/\/ ComponentName gets included as a part of the key. For service-level component instances, ComponentName is\n\/\/ set to componentRootName, while for all component instances within a service an actual Component.Name is used.\ntype ComponentInstanceKey struct {\n\t\/\/ cached version of component key\n\tkey string\n\n\t\/\/ required fields\n\tClusterName         string \/\/ mandatory\n\tNamespace           string \/\/ determined from the contract\n\tContractName        string \/\/ mandatory\n\tContextName         string \/\/ mandatory\n\tKeysResolved        string \/\/ mandatory\n\tContextNameWithKeys string \/\/ calculated\n\tServiceName         string \/\/ determined from the context (included into key for readability)\n\tComponentName       string \/\/ component name\n}\n\n\/\/ NewComponentInstanceKey creates a new ComponentInstanceKey\nfunc NewComponentInstanceKey(cluster *lang.Cluster, contract *lang.Contract, context *lang.Context, allocationKeysResolved []string, service *lang.Service, component *lang.ServiceComponent) *ComponentInstanceKey {\n\tcontextName := getContextNameUnsafe(context)\n\tkeysResolved := strings.Join(allocationKeysResolved, componentInstanceKeySeparator)\n\tcontextNameWithKeys := contextName\n\tif len(keysResolved) > 0 {\n\t\tcontextNameWithKeys = strings.Join([]string{contextNameWithKeys, keysResolved}, componentInstanceKeySeparator)\n\t}\n\treturn &ComponentInstanceKey{\n\t\tClusterName:         getClusterNameUnsafe(cluster),\n\t\tNamespace:           getContractNamespaceUnsafe(contract),\n\t\tContractName:        getContractNameUnsafe(contract),\n\t\tContextName:         contextName,\n\t\tKeysResolved:        keysResolved,\n\t\tContextNameWithKeys: contextNameWithKeys,\n\t\tServiceName:         getServiceNameUnsafe(service),\n\t\tComponentName:       getComponentNameUnsafe(component),\n\t}\n}\n\n\/\/ MakeCopy creates a copy of ComponentInstanceKey\nfunc (cik *ComponentInstanceKey) MakeCopy() *ComponentInstanceKey {\n\treturn &ComponentInstanceKey{\n\t\tClusterName:         cik.ClusterName,\n\t\tNamespace:           cik.Namespace,\n\t\tContractName:        cik.ContractName,\n\t\tContextName:         cik.ContextName,\n\t\tKeysResolved:        cik.KeysResolved,\n\t\tContextNameWithKeys: cik.ContextNameWithKeys,\n\t\tComponentName:       cik.ComponentName,\n\t}\n}\n\n\/\/ IsService returns 'true' if it's a contract instance key and we can't go up anymore. And it will return 'false' if it's a component instance key\nfunc (cik *ComponentInstanceKey) IsService() bool {\n\treturn cik.ComponentName == componentRootName\n}\n\n\/\/ IsComponent returns 'true' if it's a component instance key and we can go up to the corresponding service. And it will return 'false' if it's a service instance key\nfunc (cik *ComponentInstanceKey) IsComponent() bool {\n\treturn cik.ComponentName != componentRootName\n}\n\n\/\/ GetParentServiceKey returns a key for the parent service, replacing componentName with componentRootName\nfunc (cik *ComponentInstanceKey) GetParentServiceKey() *ComponentInstanceKey {\n\tif cik.ComponentName == componentRootName {\n\t\treturn cik\n\t}\n\tserviceCik := cik.MakeCopy()\n\tserviceCik.ComponentName = componentRootName\n\treturn serviceCik\n}\n\n\/\/ GetKey returns a string key\nfunc (cik ComponentInstanceKey) GetKey() string {\n\tif cik.key == \"\" {\n\t\tcik.key = strings.Join(\n\t\t\t[]string{\n\t\t\t\tcik.ClusterName,\n\t\t\t\tcik.Namespace,\n\t\t\t\tcik.ContractName,\n\t\t\t\tcik.ContextNameWithKeys,\n\t\t\t\tcik.ComponentName,\n\t\t\t}, componentInstanceKeySeparator)\n\t}\n\treturn cik.key\n}\n\n\/\/ GetDeployName returns a string that could be used as name for deployment inside the cluster\nfunc (cik ComponentInstanceKey) GetDeployName() string {\n\treturn strings.Join(\n\t\t[]string{\n\t\t\tcik.Namespace,\n\t\t\tcik.ContractName,\n\t\t\tcik.ContextNameWithKeys,\n\t\t\tcik.ComponentName,\n\t\t}, componentInstanceKeySeparator)\n}\n\n\/\/ If cluster has not been resolved yet and we need a key, generate one\n\/\/ Otherwise use cluster name\nfunc getClusterNameUnsafe(cluster *lang.Cluster) string {\n\tif cluster == nil {\n\t\treturn componentUnresolvedName\n\t}\n\treturn cluster.Name\n}\n\n\/\/ If contract has not been resolved yet and we need a key, generate one\n\/\/ Otherwise use contract name\nfunc getContractNameUnsafe(contract *lang.Contract) string {\n\tif contract == nil {\n\t\treturn componentUnresolvedName\n\t}\n\treturn contract.Name\n}\n\n\/\/ If contract has not been resolved yet and we need a key, generate one\n\/\/ Otherwise use contract namespace\nfunc getContractNamespaceUnsafe(contract *lang.Contract) string {\n\tif contract == nil {\n\t\treturn componentUnresolvedName\n\t}\n\treturn contract.Namespace\n}\n\n\/\/ If context has not been resolved yet and we need a key, generate one\n\/\/ Otherwise use context name\nfunc getContextNameUnsafe(context *lang.Context) string {\n\tif context == nil {\n\t\treturn componentUnresolvedName\n\t}\n\treturn context.Name\n}\n\n\/\/ If service has not been resolved yet and we need a key, generate one\n\/\/ Otherwise use service name\nfunc getServiceNameUnsafe(service *lang.Service) string {\n\tif service == nil {\n\t\treturn componentUnresolvedName\n\t}\n\treturn service.Name\n}\n\n\/\/ If component has not been resolved yet and we need a key, generate one\n\/\/ Otherwise use component name\nfunc getComponentNameUnsafe(component *lang.ServiceComponent) string {\n\tif component == nil {\n\t\treturn componentRootName\n\t}\n\treturn component.Name\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2015 Juniper Networks, Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage opencontrail\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/golang\/glog\"\n\n\t\"github.com\/Juniper\/contrail-go-api\"\n\t\"github.com\/Juniper\/contrail-go-api\/config\"\n\t\"github.com\/Juniper\/contrail-go-api\/types\"\n)\n\ntype NetworkManager interface {\n\tLocateFloatingIpPool(network *types.VirtualNetwork, subnet string) (*types.FloatingIpPool, error)\n\tDeleteFloatingIpPool(network *types.VirtualNetwork, cascade bool) error\n\tLookupNetwork(projectName, networkName string) (*types.VirtualNetwork, error)\n\tLocateNetwork(project, name, subnet string) (*types.VirtualNetwork, error)\n\tDeleteNetwork(*types.VirtualNetwork) error\n\tReleaseNetworkIfEmpty(namespace, name string) error\n\tLocateFloatingIp(network *types.VirtualNetwork, resourceName, address string) (*types.FloatingIp, error)\n\tGetPublicNetwork() *types.VirtualNetwork\n\tGetServiceNetwork() *types.VirtualNetwork\n\tGetGatewayAddress(network *types.VirtualNetwork) (string, error)\n}\n\ntype NetworkManagerImpl struct {\n\tclient        contrail.ApiClient\n\tconfig        *Config\n\tpublicNetwork *types.VirtualNetwork\n\tserviceNetwork *types.VirtualNetwork\n}\n\nfunc NewNetworkManager(client contrail.ApiClient, config *Config) NetworkManager {\n\tmanager := new(NetworkManagerImpl)\n\tmanager.client = client\n\tmanager.config = config\n\tmanager.initializePublicNetwork()\n\tmanager.initializeServiceNetwork()\n\treturn manager\n}\n\nfunc (m *NetworkManagerImpl) GetServiceNetwork() *types.VirtualNetwork {\n\treturn m.serviceNetwork\n}\n\nfunc (m *NetworkManagerImpl) GetPublicNetwork() *types.VirtualNetwork {\n\treturn m.publicNetwork\n}\n\nfunc makePoolName(network *types.VirtualNetwork) string {\n\tfqn := make([]string, len(network.GetFQName()), len(network.GetFQName())+1)\n\tcopy(fqn, network.GetFQName())\n\tfqn = append(fqn, fqn[len(fqn)-1])\n\treturn strings.Join(fqn, \":\")\n}\n\nfunc (m *NetworkManagerImpl) LocateFloatingIpPool(\n\tnetwork *types.VirtualNetwork, subnet string) (*types.FloatingIpPool, error) {\n\tobj, err := m.client.FindByName(\n\t\t\"floating-ip-pool\", makePoolName(network))\n\tif err == nil {\n\t\treturn obj.(*types.FloatingIpPool), nil\n\t}\n\n\taddress, prefixlen := PrefixToAddressLen(subnet)\n\n\tpool := new(types.FloatingIpPool)\n\tpool.SetName(network.GetName())\n\tpool.SetParent(network)\n\tpool.SetFloatingIpPoolPrefixes(\n\t\t&types.FloatingIpPoolType{\n\t\t\tSubnet: []types.SubnetType{types.SubnetType{address, prefixlen}}})\n\terr = m.client.Create(pool)\n\tif err != nil {\n\t\tglog.Errorf(\"Create floating-ip-pool %s: %v\", network.GetName(), err)\n\t\treturn nil, err\n\t}\n\treturn pool, nil\n}\n\nfunc (m *NetworkManagerImpl) floatingIpPoolDeleteChildren(pool *types.FloatingIpPool) error {\n\tfips, err := pool.GetFloatingIps()\n\tif err != nil {\n\t\tglog.Errorf(\"Get floating-ip-pool %s: %v\", pool.GetName(), err)\n\t\treturn err\n\t}\n\tfor _, fip := range fips {\n\t\terr := m.client.DeleteByUuid(\"floating-ip\", fip.Uuid)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Delete floating-ip %s: %v\", fip.Uuid, err)\n\t\t}\n\t}\n\treturn nil\n}\nfunc (m *NetworkManagerImpl) DeleteFloatingIpPool(network *types.VirtualNetwork, cascade bool) error {\n\tobj, err := m.client.FindByName(\"floating-ip-pool\", makePoolName(network))\n\tif err != nil {\n\t\tglog.Errorf(\"Get floating-ip-pool %s: %v\", network.GetName(), err)\n\t\treturn err\n\t}\n\tif cascade {\n\t\tpool := obj.(*types.FloatingIpPool)\n\t\tm.floatingIpPoolDeleteChildren(pool)\n\t}\n\tm.client.Delete(obj)\n\treturn nil\n}\n\nfunc (m *NetworkManagerImpl) initializeServiceNetwork() {\n\tvar network *types.VirtualNetwork\n\tobj, err := m.client.FindByName(\"virtual-network\", m.config.ServiceNetwork)\n\tif err != nil {\n\t\tfqn := strings.Split(m.config.ServiceNetwork, \":\")\n\t\tparent := strings.Join(fqn[0:len(fqn)-1], \":\")\n\t\tprojectId, err := m.client.UuidByName(\"project\", parent)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"%s: %v\", parent, err)\n\t\t}\n\t\tvar networkId string\n\t\tnetworkName := fqn[len(fqn)-1]\n\t\tif len(m.config.ServiceSubnet) > 0 {\n\t\t\tnetworkId, err = config.CreateNetworkWithSubnet(\n\t\t\t\tm.client, projectId, networkName, m.config.ServiceSubnet)\n\t\t} else {\n\t\t\tnetworkId, err = config.CreateNetwork(m.client, projectId, networkName)\n\t\t}\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"%s: %v\", parent, err)\n\t\t}\n\n\t\tglog.Infof(\"Created network %s\", m.config.ServiceNetwork)\n\n\t\tobj, err := m.client.FindByUuid(\"virtual-network\", networkId)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"GET %s %v\", networkId, err)\n\t\t}\n\t\tnetwork = obj.(*types.VirtualNetwork)\n\t} else {\n\t\tnetwork = obj.(*types.VirtualNetwork)\n\t}\n\n\tm.serviceNetwork = network\n\n\t\/\/ TODO(prm): Ensure that the subnet is as specified.\n\tif len(m.config.ServiceSubnet) > 0 {\n\t\tm.LocateFloatingIpPool(network, m.config.ServiceSubnet)\n\t}\n}\n\nfunc (m *NetworkManagerImpl) initializePublicNetwork() {\n\tvar network *types.VirtualNetwork\n\tobj, err := m.client.FindByName(\"virtual-network\", m.config.PublicNetwork)\n\tif err != nil {\n\t\tfqn := strings.Split(m.config.PublicNetwork, \":\")\n\t\tparent := strings.Join(fqn[0:len(fqn)-1], \":\")\n\t\tprojectId, err := m.client.UuidByName(\"project\", parent)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"%s: %v\", parent, err)\n\t\t}\n\t\tvar networkId string\n\t\tnetworkName := fqn[len(fqn)-1]\n\t\tif len(m.config.PublicSubnet) > 0 {\n\t\t\tnetworkId, err = config.CreateNetworkWithSubnet(\n\t\t\t\tm.client, projectId, networkName, m.config.PublicSubnet)\n\t\t} else {\n\t\t\tnetworkId, err = config.CreateNetwork(m.client, projectId, networkName)\n\t\t}\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"%s: %v\", parent, err)\n\t\t}\n\n\t\tglog.Infof(\"Created network %s\", m.config.PublicNetwork)\n\n\t\tobj, err := m.client.FindByUuid(\"virtual-network\", networkId)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"GET %s %v\", networkId, err)\n\t\t}\n\t\tnetwork = obj.(*types.VirtualNetwork)\n\t} else {\n\t\tnetwork = obj.(*types.VirtualNetwork)\n\t}\n\n\tm.publicNetwork = network\n\n\t\/\/ TODO(prm): Ensure that the subnet is as specified.\n\tif len(m.config.PublicSubnet) > 0 {\n\t\tm.LocateFloatingIpPool(network, m.config.PublicSubnet)\n\t}\n}\n\nfunc (m *NetworkManagerImpl) LookupNetwork(projectName, networkName string) (*types.VirtualNetwork, error) {\n\tfqn := []string{DefaultDomain, projectName, networkName}\n\tobj, err := m.client.FindByName(\"virtual-network\", strings.Join(fqn, \":\"))\n\tif err != nil {\n\t\tglog.Errorf(\"GET virtual-network %s: %v\", networkName, err)\n\t\treturn nil, err\n\t}\n\treturn obj.(*types.VirtualNetwork), nil\n}\n\nfunc (m *NetworkManagerImpl) LocateNetwork(project, name, subnet string) (*types.VirtualNetwork, error) {\n\tfqn := []string{DefaultDomain, project, name}\n\tfqname := strings.Join(fqn, \":\")\n\n\tobj, err := m.client.FindByName(\"virtual-network\", fqname)\n\tif err == nil {\n\t\treturn obj.(*types.VirtualNetwork), nil\n\t}\n\n\tprojectId, err := m.client.UuidByName(\"project\", fmt.Sprintf(\"%s:%s\", DefaultDomain, project))\n\tif err != nil {\n\t\tglog.Infof(\"GET %s: %v\", project, err)\n\t\treturn nil, err\n\t}\n\tuid, err := config.CreateNetworkWithSubnet(\n\t\tm.client, projectId, name, subnet)\n\tif err != nil {\n\t\tglog.Infof(\"Create %s: %v\", name, err)\n\t\treturn nil, err\n\t}\n\tobj, err = m.client.FindByUuid(\"virtual-network\", uid)\n\tif err != nil {\n\t\tglog.Infof(\"GET %s: %v\", name, err)\n\t\treturn nil, err\n\t}\n\tglog.Infof(\"Create network %s\", fqname)\n\treturn obj.(*types.VirtualNetwork), nil\n}\n\nfunc (m *NetworkManagerImpl) ReleaseNetworkIfEmpty(namespace, name string) error {\n\tfqn := []string{DefaultDomain, namespace, name}\n\tobj, err := m.client.FindByName(\"virtual-network\", strings.Join(fqn, \":\"))\n\tif err != nil {\n\t\tglog.Errorf(\"Get virtual-network %s: %v\", name, err)\n\t\treturn err\n\t}\n\tnetwork := obj.(*types.VirtualNetwork)\n\trefs, err := network.GetVirtualMachineInterfaceBackRefs()\n\tif err != nil {\n\t\tglog.Errorf(\"Get network vmi references %s: %v\", name, err)\n\t\treturn err\n\t}\n\tif len(refs) == 0 {\n\t\terr = m.client.Delete(network)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Delete virtual-network %s: %v\", name, err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *NetworkManagerImpl) LocateFloatingIp(network *types.VirtualNetwork, resourceName, address string) (*types.FloatingIp, error) {\n\tobj, err := m.client.FindByName(\"floating-ip-pool\", makePoolName(network))\n\tif err != nil {\n\t\tglog.Errorf(\"Get floating-ip-pool %s: %v\", network.GetName(), err)\n\t\treturn nil, err\n\t}\n\tpool := obj.(*types.FloatingIpPool)\n\n\tfqn := AppendConst(pool.GetFQName(), resourceName)\n\tobj, err = m.client.FindByName(\"floating-ip\", strings.Join(fqn, \":\"))\n\tif err == nil {\n\t\tfip := obj.(*types.FloatingIp)\n\t\tif fip.GetFloatingIpAddress() != address {\n\t\t\tfip.SetFloatingIpAddress(address)\n\t\t\terr = m.client.Update(fip)\n\t\t\tif err != nil {\n\t\t\t\tglog.Errorf(\"Update floating-ip %s: %v\", resourceName, err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn fip, nil\n\t}\n\n\tprojectFQN := network.GetFQName()[0 : len(network.GetFQName())-1]\n\tobj, err = m.client.FindByName(\"project\", strings.Join(projectFQN, \":\"))\n\tif err != nil {\n\t\tglog.Errorf(\"Get project %s: %v\", projectFQN[len(projectFQN)-1], err)\n\t\treturn nil, err\n\t}\n\tproject := obj.(*types.Project)\n\n\tfip := new(types.FloatingIp)\n\tfip.SetParent(pool)\n\tfip.SetName(resourceName)\n\tfip.SetFloatingIpAddress(address)\n\tfip.AddProject(project)\n\terr = m.client.Create(fip)\n\tif err != nil {\n\t\tglog.Errorf(\"Create floating-ip %s: %v\", resourceName, err)\n\t\treturn nil, err\n\t}\n\treturn fip, nil\n}\n\nfunc (m *NetworkManagerImpl) GetGatewayAddress(network *types.VirtualNetwork) (string, error) {\n\trefs, err := network.GetNetworkIpamRefs()\n\tif err != nil {\n\t\tglog.Errorf(\"Get network %s network-ipam refs: %v\", network.GetName(), err)\n\t\treturn \"\", err\n\t}\n\n\tattr := refs[0].Attr.(types.VnSubnetsType)\n\tif len(attr.IpamSubnets) == 0 {\n\t\tglog.Errorf(\"Network %s has no subnets configured\", network.GetName())\n\t\treturn \"\", fmt.Errorf(\"Network %s: empty subnet list\", network.GetName())\n\t}\n\n\tgateway := attr.IpamSubnets[0].DefaultGateway\n\tif gateway == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Gateway is empty: %+v\", attr.IpamSubnets)\n\t}\n\n\treturn gateway, nil\n}\n\nfunc (m *NetworkManagerImpl) DeleteNetwork(network *types.VirtualNetwork) error {\n\trefs, err := network.GetNetworkPolicyRefs()\n\tif err != nil {\n\t\tglog.Errorf(\"Get %s policy refs: %v\", network.GetName(), err)\n\t}\n\tm.client.Delete(network)\n\n\tfor _, ref := range refs {\n\t\tobj, err := m.client.FindByUuid(\"network-policy\", ref.Uuid)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Get policy %s: %v\", ref.Uuid, err)\n\t\t}\n\t\tpolicy := obj.(*types.NetworkPolicy)\n\t\tnpRefs, err := policy.GetVirtualNetworkBackRefs()\n\t\tif len(npRefs) == 0 {\n\t\t\tm.client.Delete(policy)\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>add some debugs<commit_after>\/*\nCopyright 2015 Juniper Networks, Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage opencontrail\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/golang\/glog\"\n\n\t\"github.com\/Juniper\/contrail-go-api\"\n\t\"github.com\/Juniper\/contrail-go-api\/config\"\n\t\"github.com\/Juniper\/contrail-go-api\/types\"\n)\n\ntype NetworkManager interface {\n\tLocateFloatingIpPool(network *types.VirtualNetwork, subnet string) (*types.FloatingIpPool, error)\n\tDeleteFloatingIpPool(network *types.VirtualNetwork, cascade bool) error\n\tLookupNetwork(projectName, networkName string) (*types.VirtualNetwork, error)\n\tLocateNetwork(project, name, subnet string) (*types.VirtualNetwork, error)\n\tDeleteNetwork(*types.VirtualNetwork) error\n\tReleaseNetworkIfEmpty(namespace, name string) error\n\tLocateFloatingIp(network *types.VirtualNetwork, resourceName, address string) (*types.FloatingIp, error)\n\tGetPublicNetwork() *types.VirtualNetwork\n\tGetServiceNetwork() *types.VirtualNetwork\n\tGetGatewayAddress(network *types.VirtualNetwork) (string, error)\n}\n\ntype NetworkManagerImpl struct {\n\tclient        contrail.ApiClient\n\tconfig        *Config\n\tpublicNetwork *types.VirtualNetwork\n\tserviceNetwork *types.VirtualNetwork\n}\n\nfunc NewNetworkManager(client contrail.ApiClient, config *Config) NetworkManager {\n\tmanager := new(NetworkManagerImpl)\n\tmanager.client = client\n\tmanager.config = config\n\tmanager.initializePublicNetwork()\n\tmanager.initializeServiceNetwork()\n\treturn manager\n}\n\nfunc (m *NetworkManagerImpl) GetServiceNetwork() *types.VirtualNetwork {\n\treturn m.serviceNetwork\n}\n\nfunc (m *NetworkManagerImpl) GetPublicNetwork() *types.VirtualNetwork {\n\treturn m.publicNetwork\n}\n\nfunc makePoolName(network *types.VirtualNetwork) string {\n\tfqn := make([]string, len(network.GetFQName()), len(network.GetFQName())+1)\n\tcopy(fqn, network.GetFQName())\n\tfqn = append(fqn, fqn[len(fqn)-1])\n\treturn strings.Join(fqn, \":\")\n}\n\nfunc (m *NetworkManagerImpl) LocateFloatingIpPool(\n\tnetwork *types.VirtualNetwork, subnet string) (*types.FloatingIpPool, error) {\n\tobj, err := m.client.FindByName(\n\t\t\"floating-ip-pool\", makePoolName(network))\n\tif err == nil {\n\t\treturn obj.(*types.FloatingIpPool), nil\n\t}\n\n\taddress, prefixlen := PrefixToAddressLen(subnet)\n\n\tpool := new(types.FloatingIpPool)\n\tpool.SetName(network.GetName())\n\tpool.SetParent(network)\n\tpool.SetFloatingIpPoolPrefixes(\n\t\t&types.FloatingIpPoolType{\n\t\t\tSubnet: []types.SubnetType{types.SubnetType{address, prefixlen}}})\n\terr = m.client.Create(pool)\n\tif err != nil {\n\t\tglog.Errorf(\"Create floating-ip-pool %s: %v\", network.GetName(), err)\n\t\treturn nil, err\n\t}\n\treturn pool, nil\n}\n\nfunc (m *NetworkManagerImpl) floatingIpPoolDeleteChildren(pool *types.FloatingIpPool) error {\n\tfips, err := pool.GetFloatingIps()\n\tif err != nil {\n\t\tglog.Errorf(\"Get floating-ip-pool %s: %v\", pool.GetName(), err)\n\t\treturn err\n\t}\n\tfor _, fip := range fips {\n\t\terr := m.client.DeleteByUuid(\"floating-ip\", fip.Uuid)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Delete floating-ip %s: %v\", fip.Uuid, err)\n\t\t}\n\t}\n\treturn nil\n}\nfunc (m *NetworkManagerImpl) DeleteFloatingIpPool(network *types.VirtualNetwork, cascade bool) error {\n\tobj, err := m.client.FindByName(\"floating-ip-pool\", makePoolName(network))\n\tif err != nil {\n\t\tglog.Errorf(\"Get floating-ip-pool %s: %v\", network.GetName(), err)\n\t\treturn err\n\t}\n\tif cascade {\n\t\tpool := obj.(*types.FloatingIpPool)\n\t\tm.floatingIpPoolDeleteChildren(pool)\n\t}\n\tm.client.Delete(obj)\n\treturn nil\n}\n\nfunc (m *NetworkManagerImpl) initializeServiceNetwork() {\n\tvar network *types.VirtualNetwork\n\tobj, err := m.client.FindByName(\"virtual-network\", m.config.ServiceNetwork)\n\tif err != nil {\n\t\tfqn := strings.Split(m.config.ServiceNetwork, \":\")\n\t\tparent := strings.Join(fqn[0:len(fqn)-1], \":\")\n\t\tprojectId, err := m.client.UuidByName(\"project\", parent)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"%s: %v\", parent, err)\n\t\t}\n\t\tvar networkId string\n\t\tnetworkName := fqn[len(fqn)-1]\n\t\tif len(m.config.ServiceSubnet) > 0 {\n\t\t\tnetworkId, err = config.CreateNetworkWithSubnet(\n\t\t\t\tm.client, projectId, networkName, m.config.ServiceSubnet)\n\t\t} else {\n\t\t\tnetworkId, err = config.CreateNetwork(m.client, projectId, networkName)\n\t\t}\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"%s: %v\", parent, err)\n\t\t}\n\n\t\tglog.Infof(\"Created network %s\", m.config.ServiceNetwork)\n\n\t\tobj, err := m.client.FindByUuid(\"virtual-network\", networkId)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"GET %s %v\", networkId, err)\n\t\t}\n\t\tnetwork = obj.(*types.VirtualNetwork)\n\t} else {\n\t\tnetwork = obj.(*types.VirtualNetwork)\n\t}\n\n\tm.serviceNetwork = network\n\n\t\/\/ TODO(prm): Ensure that the subnet is as specified.\n\tif len(m.config.ServiceSubnet) > 0 {\n\t\tm.LocateFloatingIpPool(network, m.config.ServiceSubnet)\n\t}\n}\n\nfunc (m *NetworkManagerImpl) initializePublicNetwork() {\n\tvar network *types.VirtualNetwork\n\tobj, err := m.client.FindByName(\"virtual-network\", m.config.PublicNetwork)\n\tif err != nil {\n\t\tfqn := strings.Split(m.config.PublicNetwork, \":\")\n\t\tparent := strings.Join(fqn[0:len(fqn)-1], \":\")\n\t\tprojectId, err := m.client.UuidByName(\"project\", parent)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"%s: %v\", parent, err)\n\t\t}\n\t\tvar networkId string\n\t\tnetworkName := fqn[len(fqn)-1]\n\t\tif len(m.config.PublicSubnet) > 0 {\n\t\t\tnetworkId, err = config.CreateNetworkWithSubnet(\n\t\t\t\tm.client, projectId, networkName, m.config.PublicSubnet)\n\t\t} else {\n\t\t\tnetworkId, err = config.CreateNetwork(m.client, projectId, networkName)\n\t\t}\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"%s: %v\", parent, err)\n\t\t}\n\n\t\tglog.Infof(\"Created network %s\", m.config.PublicNetwork)\n\n\t\tobj, err := m.client.FindByUuid(\"virtual-network\", networkId)\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"GET %s %v\", networkId, err)\n\t\t}\n\t\tnetwork = obj.(*types.VirtualNetwork)\n\t} else {\n\t\tnetwork = obj.(*types.VirtualNetwork)\n\t}\n\n\tm.publicNetwork = network\n\n\t\/\/ TODO(prm): Ensure that the subnet is as specified.\n\tif len(m.config.PublicSubnet) > 0 {\n\t\tm.LocateFloatingIpPool(network, m.config.PublicSubnet)\n\t}\n}\n\nfunc (m *NetworkManagerImpl) LookupNetwork(projectName, networkName string) (*types.VirtualNetwork, error) {\n\tfqn := []string{DefaultDomain, projectName, networkName}\n\tobj, err := m.client.FindByName(\"virtual-network\", strings.Join(fqn, \":\"))\n\tif err != nil {\n\t\tglog.Errorf(\"GET virtual-network %s: %v\", networkName, err)\n\t\treturn nil, err\n\t}\n\treturn obj.(*types.VirtualNetwork), nil\n}\n\nfunc (m *NetworkManagerImpl) LocateNetwork(project, name, subnet string) (*types.VirtualNetwork, error) {\n\tfqn := []string{DefaultDomain, project, name}\n\tfqname := strings.Join(fqn, \":\")\n\n\tobj, err := m.client.FindByName(\"virtual-network\", fqname)\n\tif err == nil {\n\t\treturn obj.(*types.VirtualNetwork), nil\n\t}\n\n\tprojectId, err := m.client.UuidByName(\"project\", fmt.Sprintf(\"%s:%s\", DefaultDomain, project))\n\tif err != nil {\n\t\tglog.Infof(\"GET %s: %v\", project, err)\n\t\treturn nil, err\n\t}\n\tuid, err := config.CreateNetworkWithSubnet(\n\t\tm.client, projectId, name, subnet)\n\tif err != nil {\n\t\tglog.Infof(\"Create %s: %v\", name, err)\n\t\treturn nil, err\n\t}\n\tobj, err = m.client.FindByUuid(\"virtual-network\", uid)\n\tif err != nil {\n\t\tglog.Infof(\"GET %s: %v\", name, err)\n\t\treturn nil, err\n\t}\n\tglog.Infof(\"Create network %s\", fqname)\n\treturn obj.(*types.VirtualNetwork), nil\n}\n\nfunc (m *NetworkManagerImpl) ReleaseNetworkIfEmpty(namespace, name string) error {\n\tfqn := []string{DefaultDomain, namespace, name}\n\tobj, err := m.client.FindByName(\"virtual-network\", strings.Join(fqn, \":\"))\n\tif err != nil {\n\t\tglog.Errorf(\"Get virtual-network %s: %v\", name, err)\n\t\treturn err\n\t}\n\tnetwork := obj.(*types.VirtualNetwork)\n\trefs, err := network.GetVirtualMachineInterfaceBackRefs()\n\tif err != nil {\n\t\tglog.Errorf(\"Get network vmi references %s: %v\", name, err)\n\t\treturn err\n\t}\n\tif len(refs) == 0 {\n\t\terr = m.client.Delete(network)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Delete virtual-network %s: %v\", name, err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *NetworkManagerImpl) LocateFloatingIp(network *types.VirtualNetwork, resourceName, address string) (*types.FloatingIp, error) {\n\tglog.Infof(\"LocateFloatingIp: %s in resource: %s\", address, resourceName)\n\tobj, err := m.client.FindByName(\"floating-ip-pool\", makePoolName(network))\n\tif err != nil {\n\t\tglog.Errorf(\"Get floating-ip-pool %s: %v\", network.GetName(), err)\n\t\treturn nil, err\n\t}\n\tpool := obj.(*types.FloatingIpPool)\n\n\tfqn := AppendConst(pool.GetFQName(), resourceName)\n\tobj, err = m.client.FindByName(\"floating-ip\", strings.Join(fqn, \":\"))\n\tif err == nil {\n\t\tfip := obj.(*types.FloatingIp)\n\t\tif fip.GetFloatingIpAddress() != address {\n\t\t\tfip.SetFloatingIpAddress(address)\n\t\t\terr = m.client.Update(fip)\n\t\t\tif err != nil {\n\t\t\t\tglog.Errorf(\"Update floating-ip %s: %v\", resourceName, err)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn fip, nil\n\t}\n\n\tprojectFQN := network.GetFQName()[0 : len(network.GetFQName())-1]\n\tobj, err = m.client.FindByName(\"project\", strings.Join(projectFQN, \":\"))\n\tif err != nil {\n\t\tglog.Errorf(\"Get project %s: %v\", projectFQN[len(projectFQN)-1], err)\n\t\treturn nil, err\n\t}\n\tproject := obj.(*types.Project)\n\n\tfip := new(types.FloatingIp)\n\tfip.SetParent(pool)\n\tfip.SetName(resourceName)\n\tfip.SetFloatingIpAddress(address)\n\tfip.AddProject(project)\n\terr = m.client.Create(fip)\n\tif err != nil {\n\t\tglog.Errorf(\"Create floating-ip %s: %v\", resourceName, err)\n\t\treturn nil, err\n\t}\n\treturn fip, nil\n}\n\nfunc (m *NetworkManagerImpl) GetGatewayAddress(network *types.VirtualNetwork) (string, error) {\n\trefs, err := network.GetNetworkIpamRefs()\n\tif err != nil {\n\t\tglog.Errorf(\"Get network %s network-ipam refs: %v\", network.GetName(), err)\n\t\treturn \"\", err\n\t}\n\n\tattr := refs[0].Attr.(types.VnSubnetsType)\n\tif len(attr.IpamSubnets) == 0 {\n\t\tglog.Errorf(\"Network %s has no subnets configured\", network.GetName())\n\t\treturn \"\", fmt.Errorf(\"Network %s: empty subnet list\", network.GetName())\n\t}\n\n\tgateway := attr.IpamSubnets[0].DefaultGateway\n\tif gateway == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Gateway is empty: %+v\", attr.IpamSubnets)\n\t}\n\n\treturn gateway, nil\n}\n\nfunc (m *NetworkManagerImpl) DeleteNetwork(network *types.VirtualNetwork) error {\n\trefs, err := network.GetNetworkPolicyRefs()\n\tif err != nil {\n\t\tglog.Errorf(\"Get %s policy refs: %v\", network.GetName(), err)\n\t}\n\tm.client.Delete(network)\n\n\tfor _, ref := range refs {\n\t\tobj, err := m.client.FindByUuid(\"network-policy\", ref.Uuid)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Get policy %s: %v\", ref.Uuid, err)\n\t\t}\n\t\tpolicy := obj.(*types.NetworkPolicy)\n\t\tnpRefs, err := policy.GetVirtualNetworkBackRefs()\n\t\tif len(npRefs) == 0 {\n\t\t\tm.client.Delete(policy)\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package globalsettings\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gopkg.in\/adsi.v0\"\n\t\"gopkg.in\/dfsr.v0\/config\/membercache\"\n\t\"gopkg.in\/dfsr.v0\/core\"\n)\n\n\/\/ GlobalSettings provides a means of querying DFSR global settings.\ntype GlobalSettings struct {\n\tclient   *adsi.Client\n\tdomainDN string\n\tmc       *membercache.Cache \/\/ Maps distinguished names to MemberInfo\n}\n\n\/\/ New returns a new DFSR global settings configuration manager for the given\n\/\/ domain.\n\/\/\n\/\/ The provided ADSI client is retained by the global settings and will be used\n\/\/ internally to peform the necessary LDAP queries. It is the caller's\n\/\/ responsibility to explicitly close the ADSI client at an appropriate time\n\/\/ when finished with the global settings.\nfunc New(client *adsi.Client, domain string) *GlobalSettings {\n\treturn &GlobalSettings{\n\t\tclient:   client,\n\t\tdomainDN: domainDN(domain),\n\t\tmc:       membercache.New(),\n\t}\n}\n\n\/\/ Domain will fetch DFSR configuration data from the domain.\nfunc (gs *GlobalSettings) Domain() (domain core.Domain, err error) {\n\tstart := time.Now()\n\n\tnc, err := gs.NamingContext()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgroups, err := gs.Groups()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn core.Domain{\n\t\tNamingContext:  nc,\n\t\tGroups:         groups,\n\t\tConfigDuration: time.Now().Sub(start),\n\t}, nil\n}\n\n\/\/ NamingContext returns information about the default naming context for the\n\/\/ domain.\nfunc (gs *GlobalSettings) NamingContext() (nc core.NamingContext, err error) {\n\tdomain, err := gs.client.Open(ldap(gs.domainDN))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer domain.Close()\n\n\tnc.ID, err = domain.GUID()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tnc.Path, err = domain.Path()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tnc.DN = strings.TrimPrefix(nc.Path, \"LDAP:\/\/\")\n\n\tnc.Description, err = domain.AttrString(\"description\")\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/ Groups retreives the DFSR group configuration for all groups contained in the\n\/\/ domain.\nfunc (gs *GlobalSettings) Groups() (groups []core.Group, err error) {\n\tcontainer, err := gs.openContainer(makeDN(\"cn\", \"DFSR-GlobalSettings\", \"System\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer container.Close()\n\n\titer, err := container.Children()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer iter.Close()\n\n\tvar results []chan groupResult\n\n\tfor g, gerr := iter.Next(); gerr == nil; g, gerr = iter.Next() {\n\t\tch := make(chan groupResult, 1)\n\t\tresults = append(results, ch)\n\n\t\tgo func(ch chan groupResult, g *adsi.Object) {\n\t\t\tdefer g.Close()\n\t\t\tdefer close(ch)\n\t\t\tgroup, werr := gs.group(g)\n\t\t\tch <- groupResult{Group: group, Err: werr}\n\t\t}(ch, g)\n\n\t\ttime.Sleep(groupQueryDelay) \/\/ Try to avoid rate-limiting\n\t}\n\n\tfor i := 0; i < len(results); i++ {\n\t\tresult := <-results[i]\n\t\tif err != nil {\n\t\t\tcontinue \/\/ Already hit an error, just drain the channels\n\t\t}\n\n\t\tif result.Err != nil {\n\t\t\terr = fmt.Errorf(\"Error retrieving configuration for replication group %v: %v\", i, result.Err.Error())\n\t\t\tgroups = nil\n\t\t} else {\n\t\t\tgroups = append(groups, result.Group)\n\t\t}\n\t}\n\n\treturn\n}\n\n\/*\nfunc (gs *GlobalSettings) groups() (groups []core.Group, err error) {\n\tcontainer, err := gs.openContainer(makeDN(\"cn\", \"DFSR-GlobalSettings\", \"System\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer container.Close()\n\n\titer, err := container.Children()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer iter.Close()\n\n\tfor g, err := iter.Next(); err == nil; g, err = iter.Next() {\n\t\tdefer g.Close()\n\n\t\tgroup, err := gs.group(g)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tgroups = append(groups, group)\n\t}\n\n\treturn\n}\n*\/\n\n\/\/ GroupByName retreives the DFSR group configuration for the given name.\nfunc (gs *GlobalSettings) GroupByName(groupName string) (group core.Group, err error) {\n\tgroupName = strings.ToLower(groupName)\n\n\tcontainer, err := gs.openContainer(makeDN(\"cn\", \"DFSR-GlobalSettings\", \"System\"))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer container.Close()\n\n\titer, err := container.Children()\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer iter.Close()\n\n\tfor g, gerr := iter.Next(); gerr == nil; g, gerr = iter.Next() {\n\t\tdefer g.Close()\n\n\t\tcandidate, cerr := g.Name()\n\t\tif err != nil {\n\t\t\terr = cerr\n\t\t\treturn\n\t\t}\n\t\tcandidate = strings.ToLower(candidate)\n\n\t\tif candidate == groupName || strings.TrimPrefix(candidate, \"cn=\") == groupName {\n\t\t\treturn gs.group(g)\n\t\t}\n\t}\n\n\terr = errors.New(\"Replication Group not found.\")\n\treturn\n}\n\n\/\/ Group retreives the DFSR group configuration for the given distinguished\n\/\/ name.\nfunc (gs *GlobalSettings) Group(groupDN string) (group core.Group, err error) {\n\tg, err := gs.client.Open(ldap(groupDN))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer g.Close()\n\n\treturn gs.group(g)\n}\n\nfunc (gs *GlobalSettings) group(g *adsi.Object) (group core.Group, err error) {\n\tstart := time.Now()\n\n\tgroup.Name, err = g.Name()\n\tif err != nil {\n\t\treturn\n\t}\n\tgroup.Name = strings.TrimPrefix(group.Name, \"CN=\")\n\n\tgroup.ID, err = g.GUID()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgc, err := g.ToContainer()\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer gc.Close()\n\n\tcontent, err := gc.Container(\"msDFSR-Content\", \"cn=Content\")\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer content.Close()\n\n\tgroup.Folders, err = gs.folders(content)\n\tif err != nil {\n\t\treturn\n\t}\n\n\ttopology, err := gc.Object(\"msDFSR-Topology\", \"cn=Topology\")\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer topology.Close()\n\n\tgroup.Members, err = gs.members(topology)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgroup.ConfigDuration = time.Now().Sub(start)\n\n\treturn\n}\n\nfunc (gs *GlobalSettings) folders(content *adsi.Container) (folders []core.Folder, err error) {\n\titer, err := content.Children()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer iter.Close()\n\n\tfor f, err := iter.Next(); err == nil; f, err = iter.Next() {\n\t\tdefer f.Close()\n\n\t\tfolder, err := gs.folder(f)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfolders = append(folders, folder)\n\t}\n\n\treturn\n}\n\nfunc (gs *GlobalSettings) folder(f *adsi.Object) (folder core.Folder, err error) {\n\tfolder.Name, err = f.Name()\n\tif err != nil {\n\t\treturn\n\t}\n\tfolder.Name = strings.TrimPrefix(folder.Name, \"CN=\")\n\n\tfolder.ID, err = f.GUID()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (gs *GlobalSettings) members(topology *adsi.Object) (members []core.Member, err error) {\n\ttc, err := topology.ToContainer()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer tc.Close()\n\n\titer, err := tc.Children()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer iter.Close()\n\n\tfor m, err := iter.Next(); err == nil; m, err = iter.Next() {\n\t\tdefer m.Close()\n\n\t\tmember, err := gs.member(m, \"\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmembers = append(members, member)\n\t}\n\n\treturn\n}\n\n\/\/ Member retreives the DFSR member configuration for the given distinguished\n\/\/ name. The member's connection list is included in the returned data.\nfunc (gs *GlobalSettings) Member(memberDN string) (member core.Member, err error) {\n\tm, err := gs.client.Open(ldap(memberDN))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer m.Close()\n\n\treturn gs.member(m, memberDN)\n}\n\nfunc (gs *GlobalSettings) member(m *adsi.Object, dn string) (member core.Member, err error) {\n\tmember.MemberInfo, err = gs.memberInfo(m, dn)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tmember.Connections, err = gs.connections(m)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ MemberInfo retreives the DFSR member configuration for the given\n\/\/ distinguished name. The member's connection list is not included in the\n\/\/ returned data.\nfunc (gs *GlobalSettings) MemberInfo(memberDN string) (member core.MemberInfo, err error) {\n\tmember, ok := gs.mc.Retrieve(memberDN)\n\tif ok {\n\t\treturn\n\t}\n\n\tm, err := gs.client.Open(ldap(memberDN))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer m.Close()\n\n\treturn gs.memberInfo(m, memberDN)\n}\n\nfunc (gs *GlobalSettings) memberInfo(m *adsi.Object, dn string) (member core.MemberInfo, err error) {\n\tif dn == \"\" {\n\t\tpath, perr := m.Path()\n\t\tif err != nil {\n\t\t\terr = perr\n\t\t\treturn\n\t\t}\n\t\tmember.DN = strings.TrimPrefix(path, \"LDAP:\/\/\")\n\t} else {\n\t\tmember.DN = dn\n\t}\n\n\tmember.Name, err = m.Name()\n\tif err != nil {\n\t\treturn\n\t}\n\tmember.Name = strings.TrimPrefix(member.Name, \"CN=\")\n\n\tmember.ID, err = m.GUID()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcompref, err := m.AttrString(\"msDFSR-ComputerReference\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tmember.Computer, err = gs.Computer(compref)\n\n\tgs.mc.Set(member) \/\/ Add member info to the cache\n\treturn\n}\n\nfunc (gs *GlobalSettings) connections(member *adsi.Object) (connections []core.Connection, err error) {\n\tmc, err := member.ToContainer()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer mc.Close()\n\n\titer, err := mc.Children()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer iter.Close()\n\n\tfor c, err := iter.Next(); err == nil; c, err = iter.Next() {\n\t\tdefer c.Close()\n\n\t\tconn, err := gs.connection(c)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tconnections = append(connections, conn)\n\t}\n\n\treturn\n}\n\nfunc (gs *GlobalSettings) connection(c *adsi.Object) (conn core.Connection, err error) {\n\tconn.Name, err = c.Name()\n\tif err != nil {\n\t\treturn\n\t}\n\tconn.Name = strings.TrimPrefix(conn.Name, \"CN=\")\n\n\tconn.ID, err = c.GUID()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn.MemberDN, err = c.AttrString(\"fromServer\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn.Enabled, err = c.AttrBool(\"msDFSR-Enabled\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tmi, err := gs.MemberInfo(conn.MemberDN)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn.Computer = mi.Computer\n\n\treturn\n}\n\n\/\/ Computer retrieves the DNS host name for the given distinguished name.\nfunc (gs *GlobalSettings) Computer(dn string) (computer core.Computer, err error) {\n\tc, err := gs.client.Open(ldap(dn))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer c.Close()\n\n\treturn gs.computer(c)\n}\n\nfunc (gs *GlobalSettings) computer(c *adsi.Object) (computer core.Computer, err error) {\n\tcomputer.DN, err = c.Path()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tcomputer.Host, err = c.AttrString(\"dNSHostName\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (gs *GlobalSettings) openContainer(partialDN string) (*adsi.Container, error) {\n\tpath := ldap(combineDN(partialDN, gs.domainDN))\n\treturn gs.client.OpenContainer(path)\n}\n<commit_msg>Added basic domain system volume support to globalsettings<commit_after>package globalsettings\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"gopkg.in\/adsi.v0\"\n\t\"gopkg.in\/dfsr.v0\/config\/membercache\"\n\t\"gopkg.in\/dfsr.v0\/core\"\n)\n\n\/\/ GlobalSettings provides a means of querying DFSR global settings.\ntype GlobalSettings struct {\n\tclient   *adsi.Client\n\tdomainDN string\n\tmc       *membercache.Cache \/\/ Maps distinguished names to MemberInfo\n}\n\n\/\/ New returns a new DFSR global settings configuration manager for the given\n\/\/ domain.\n\/\/\n\/\/ The provided ADSI client is retained by the global settings and will be used\n\/\/ internally to peform the necessary LDAP queries. It is the caller's\n\/\/ responsibility to explicitly close the ADSI client at an appropriate time\n\/\/ when finished with the global settings.\nfunc New(client *adsi.Client, domain string) *GlobalSettings {\n\treturn &GlobalSettings{\n\t\tclient:   client,\n\t\tdomainDN: domainDN(domain),\n\t\tmc:       membercache.New(),\n\t}\n}\n\n\/\/ Domain will fetch DFSR configuration data from the domain.\nfunc (gs *GlobalSettings) Domain() (domain core.Domain, err error) {\n\tstart := time.Now()\n\n\tnc, err := gs.NamingContext()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgroups, err := gs.Groups()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn core.Domain{\n\t\tNamingContext:  nc,\n\t\tGroups:         groups,\n\t\tConfigDuration: time.Now().Sub(start),\n\t}, nil\n}\n\n\/\/ NamingContext returns information about the default naming context for the\n\/\/ domain.\nfunc (gs *GlobalSettings) NamingContext() (nc core.NamingContext, err error) {\n\tdomain, err := gs.client.Open(ldap(gs.domainDN))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer domain.Close()\n\n\tnc.ID, err = domain.GUID()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tnc.Path, err = domain.Path()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tnc.DN = strings.TrimPrefix(nc.Path, \"LDAP:\/\/\")\n\n\tnc.Description, err = domain.AttrString(\"description\")\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}\n\n\/\/ Groups retreives the DFSR group configuration for all groups contained in the\n\/\/ domain.\nfunc (gs *GlobalSettings) Groups() (groups []core.Group, err error) {\n\tcontainer, err := gs.openContainer(makeDN(\"cn\", \"DFSR-GlobalSettings\", \"System\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer container.Close()\n\n\titer, err := container.Children()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer iter.Close()\n\n\tvar results []chan groupResult\n\n\tfor g, gerr := iter.Next(); gerr == nil; g, gerr = iter.Next() {\n\t\tch := make(chan groupResult, 1)\n\t\tresults = append(results, ch)\n\n\t\tgo func(ch chan groupResult, g *adsi.Object) {\n\t\t\tdefer g.Close()\n\t\t\tdefer close(ch)\n\t\t\tgroup, werr := gs.group(g)\n\t\t\tch <- groupResult{Group: group, Err: werr}\n\t\t}(ch, g)\n\n\t\ttime.Sleep(groupQueryDelay) \/\/ Try to avoid rate-limiting\n\t}\n\n\tfor i := 0; i < len(results); i++ {\n\t\tresult := <-results[i]\n\t\tif err != nil {\n\t\t\tcontinue \/\/ Already hit an error, just drain the channels\n\t\t}\n\n\t\tif result.Err != nil {\n\t\t\terr = fmt.Errorf(\"Error retrieving configuration for replication group %v: %v\", i, result.Err.Error())\n\t\t\tgroups = nil\n\t\t} else {\n\t\t\tgroups = append(groups, result.Group)\n\t\t}\n\t}\n\n\treturn\n}\n\n\/*\nfunc (gs *GlobalSettings) groups() (groups []core.Group, err error) {\n\tcontainer, err := gs.openContainer(makeDN(\"cn\", \"DFSR-GlobalSettings\", \"System\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer container.Close()\n\n\titer, err := container.Children()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer iter.Close()\n\n\tfor g, err := iter.Next(); err == nil; g, err = iter.Next() {\n\t\tdefer g.Close()\n\n\t\tgroup, err := gs.group(g)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tgroups = append(groups, group)\n\t}\n\n\treturn\n}\n*\/\n\n\/\/ GroupByName retreives the DFSR group configuration for the given name.\nfunc (gs *GlobalSettings) GroupByName(groupName string) (group core.Group, err error) {\n\tgroupName = strings.ToLower(groupName)\n\n\tcontainer, err := gs.openContainer(makeDN(\"cn\", \"DFSR-GlobalSettings\", \"System\"))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer container.Close()\n\n\titer, err := container.Children()\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer iter.Close()\n\n\tfor g, gerr := iter.Next(); gerr == nil; g, gerr = iter.Next() {\n\t\tdefer g.Close()\n\n\t\tcandidate, cerr := g.Name()\n\t\tif err != nil {\n\t\t\terr = cerr\n\t\t\treturn\n\t\t}\n\t\tcandidate = strings.ToLower(candidate)\n\n\t\tif candidate == groupName || strings.TrimPrefix(candidate, \"cn=\") == groupName {\n\t\t\treturn gs.group(g)\n\t\t}\n\t}\n\n\terr = errors.New(\"Replication Group not found.\")\n\treturn\n}\n\n\/\/ Group retreives the DFSR group configuration for the given distinguished\n\/\/ name.\nfunc (gs *GlobalSettings) Group(groupDN string) (group core.Group, err error) {\n\tg, err := gs.client.Open(ldap(groupDN))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer g.Close()\n\n\treturn gs.group(g)\n}\n\nfunc (gs *GlobalSettings) group(g *adsi.Object) (group core.Group, err error) {\n\tstart := time.Now()\n\n\tgroup.Name, err = g.Name()\n\tif err != nil {\n\t\treturn\n\t}\n\tgroup.Name = strings.TrimPrefix(group.Name, \"CN=\")\n\n\tgroup.ID, err = g.GUID()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgc, err := g.ToContainer()\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer gc.Close()\n\n\tcontent, err := gc.Container(\"msDFSR-Content\", \"cn=Content\")\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer content.Close()\n\n\tgroup.Folders, err = gs.folders(content)\n\tif err != nil {\n\t\treturn\n\t}\n\n\ttopology, err := gc.Object(\"msDFSR-Topology\", \"cn=Topology\")\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer topology.Close()\n\n\tgroup.Members, err = gs.members(topology)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tgroup.ConfigDuration = time.Now().Sub(start)\n\n\treturn\n}\n\nfunc (gs *GlobalSettings) folders(content *adsi.Container) (folders []core.Folder, err error) {\n\titer, err := content.Children()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer iter.Close()\n\n\tfor f, err := iter.Next(); err == nil; f, err = iter.Next() {\n\t\tdefer f.Close()\n\n\t\tfolder, err := gs.folder(f)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfolders = append(folders, folder)\n\t}\n\n\treturn\n}\n\nfunc (gs *GlobalSettings) folder(f *adsi.Object) (folder core.Folder, err error) {\n\tfolder.Name, err = f.Name()\n\tif err != nil {\n\t\treturn\n\t}\n\tfolder.Name = strings.TrimPrefix(folder.Name, \"CN=\")\n\n\tfolder.ID, err = f.GUID()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (gs *GlobalSettings) members(topology *adsi.Object) (members []core.Member, err error) {\n\ttc, err := topology.ToContainer()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer tc.Close()\n\n\titer, err := tc.Children()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer iter.Close()\n\n\tfor m, err := iter.Next(); err == nil; m, err = iter.Next() {\n\t\tdefer m.Close()\n\n\t\tmember, err := gs.member(m, \"\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmembers = append(members, member)\n\t}\n\n\treturn\n}\n\n\/\/ Member retreives the DFSR member configuration for the given distinguished\n\/\/ name. The member's connection list is included in the returned data.\nfunc (gs *GlobalSettings) Member(memberDN string) (member core.Member, err error) {\n\tm, err := gs.client.Open(ldap(memberDN))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer m.Close()\n\n\treturn gs.member(m, memberDN)\n}\n\nfunc (gs *GlobalSettings) member(m *adsi.Object, dn string) (member core.Member, err error) {\n\tmember.MemberInfo, err = gs.memberInfo(m, dn)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tserverref, _ := m.AttrString(\"serverReference\")\n\tif serverref == \"\" {\n\t\t\/\/ Standard DFSR membership\n\t\tmember.Connections, err = gs.connections(m)\n\t\treturn\n\t}\n\n\t\/\/ Domain System Volume membership\n\tserver, err := gs.client.Open(ldap(serverref))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tmember.Connections, err = gs.connections(server)\n\treturn\n}\n\n\/\/ MemberInfo retreives the DFSR member configuration for the given\n\/\/ distinguished name. The member's connection list is not included in the\n\/\/ returned data.\nfunc (gs *GlobalSettings) MemberInfo(memberDN string) (member core.MemberInfo, err error) {\n\tmember, ok := gs.mc.Retrieve(memberDN)\n\tif ok {\n\t\treturn\n\t}\n\n\tm, err := gs.client.Open(ldap(memberDN))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer m.Close()\n\n\treturn gs.memberInfo(m, memberDN)\n}\n\nfunc (gs *GlobalSettings) memberInfo(m *adsi.Object, dn string) (member core.MemberInfo, err error) {\n\tif dn == \"\" {\n\t\tpath, perr := m.Path()\n\t\tif err != nil {\n\t\t\terr = perr\n\t\t\treturn\n\t\t}\n\t\tmember.DN = strings.TrimPrefix(path, \"LDAP:\/\/\")\n\t} else {\n\t\tmember.DN = dn\n\t}\n\n\tclass, err := m.Class()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar compref string\n\tswitch class {\n\tcase \"nTDSDSA\":\n\t\tm, err = gs.openParent(m)\n\t\tdefer m.Close()\n\t\tfallthrough\n\tcase \"server\":\n\t\tcompref, err = m.AttrString(\"serverReference\")\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\tcase \"msDFSR-Member\":\n\t\tcompref, err = m.AttrString(\"msDFSR-ComputerReference\")\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\terr = errors.New(\"Unknown Active Directory membership class\")\n\t\treturn\n\t}\n\n\tmember.Name, err = m.Name()\n\tif err != nil {\n\t\treturn\n\t}\n\tmember.Name = strings.TrimPrefix(member.Name, \"CN=\")\n\n\tmember.ID, err = m.GUID()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tmember.Computer, err = gs.Computer(compref)\n\n\tgs.mc.Set(member) \/\/ Add member info to the cache\n\treturn\n}\n\nfunc (gs *GlobalSettings) connections(member *adsi.Object) (connections []core.Connection, err error) {\n\tmc, err := member.ToContainer()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer mc.Close()\n\n\titer, err := mc.Children()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer iter.Close()\n\n\tfor c, err := iter.Next(); err == nil; c, err = iter.Next() {\n\t\tdefer c.Close()\n\n\t\tconn, err := gs.connection(c)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tconnections = append(connections, conn)\n\t}\n\n\treturn\n}\n\nfunc (gs *GlobalSettings) connection(c *adsi.Object) (conn core.Connection, err error) {\n\tclass, err := c.Class()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn.Name, err = c.Name()\n\tif err != nil {\n\t\treturn\n\t}\n\tconn.Name = strings.TrimPrefix(conn.Name, \"CN=\")\n\n\tconn.ID, err = c.GUID()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn.MemberDN, err = c.AttrString(\"fromServer\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif class == \"msDFSR-Member\" {\n\t\t\/\/ Standard DFSR connection\n\t\tconn.Enabled, err = c.AttrBool(\"msDFSR-Enabled\")\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t} else if class == \"nTDSConnection\" {\n\t\t\/\/ Domain System Volume membership\n\t\tconn.Enabled = true \/\/ These members are always enabled\n\t}\n\n\tmi, err := gs.MemberInfo(conn.MemberDN)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn.Computer = mi.Computer\n\n\treturn\n}\n\n\/\/ Computer retrieves the DNS host name for the given distinguished name.\nfunc (gs *GlobalSettings) Computer(dn string) (computer core.Computer, err error) {\n\tc, err := gs.client.Open(ldap(dn))\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer c.Close()\n\n\treturn gs.computer(c)\n}\n\nfunc (gs *GlobalSettings) computer(c *adsi.Object) (computer core.Computer, err error) {\n\tcomputer.DN, err = c.Path()\n\tif err != nil {\n\t\treturn\n\t}\n\tcomputer.DN = strings.TrimPrefix(computer.DN, \"LDAP:\/\/\")\n\n\tcomputer.Host, err = c.AttrString(\"dNSHostName\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (gs *GlobalSettings) openParent(o *adsi.Object) (parent *adsi.Object, err error) {\n\tpath, err := o.Parent()\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn gs.client.Open(path)\n}\n\nfunc (gs *GlobalSettings) openContainer(partialDN string) (*adsi.Container, error) {\n\tpath := ldap(combineDN(partialDN, gs.domainDN))\n\treturn gs.client.OpenContainer(path)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2021 The LUCI Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\n\t\"github.com\/bazelbuild\/remote-apis-sdks\/go\/pkg\/fakes\"\n\tregrpc \"github.com\/bazelbuild\/remote-apis\/build\/bazel\/remote\/execution\/v2\"\n\tbsgrpc \"google.golang.org\/genproto\/googleapis\/bytestream\"\n\t\"google.golang.org\/grpc\"\n\n\t\"go.chromium.org\/luci\/common\/system\/signals\"\n)\n\nfunc main() {\n\tport := flag.Int(\"port\", 9000, \"local port number used by fake server\")\n\taddrFile := flag.String(\"addr-file\", \"\", \"dump listening address in this file\")\n\tflag.Parse()\n\n\ts := grpc.NewServer()\n\tcas := fakes.NewCAS()\n\tex := &fakes.Exec{}\n\tbsgrpc.RegisterByteStreamServer(s, cas)\n\tregrpc.RegisterContentAddressableStorageServer(s, cas)\n\tregrpc.RegisterCapabilitiesServer(s, ex)\n\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\"localhost:%d\", *port))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\\n\", err)\n\t}\n\tlog.Printf(\"listening address: %s\\n\", lis.Addr())\n\n\tif *addrFile != \"\" {\n\t\tif err := os.WriteFile(*addrFile, []byte(lis.Addr().String()), 0600); err != nil {\n\t\t\tlog.Fatalf(\"failed to write addrFile: %v\", err)\n\t\t}\n\t}\n\n\tdefer signals.HandleInterrupt(func() {\n\t\tlog.Println(\"shutting down fake CAS gRPC server...\")\n\t\ts.GracefulStop()\n\t})()\n\n\tlog.Println(\"starting CAS fake server...\")\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve fake CAS gRPC server: %v\\n\", err)\n\t}\n}\n<commit_msg>[fakecas] Change fakecase to use dynamic port by default<commit_after>\/\/ Copyright 2021 The LUCI Authors.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\n\t\"github.com\/bazelbuild\/remote-apis-sdks\/go\/pkg\/fakes\"\n\tregrpc \"github.com\/bazelbuild\/remote-apis\/build\/bazel\/remote\/execution\/v2\"\n\tbsgrpc \"google.golang.org\/genproto\/googleapis\/bytestream\"\n\t\"google.golang.org\/grpc\"\n\n\t\"go.chromium.org\/luci\/common\/system\/signals\"\n)\n\nfunc main() {\n\tport := flag.Int(\"port\", 0, \"local port number used by fake server\")\n\taddrFile := flag.String(\"addr-file\", \"\", \"dump listening address in this file\")\n\tflag.Parse()\n\n\ts := grpc.NewServer()\n\tcas := fakes.NewCAS()\n\tex := &fakes.Exec{}\n\tbsgrpc.RegisterByteStreamServer(s, cas)\n\tregrpc.RegisterContentAddressableStorageServer(s, cas)\n\tregrpc.RegisterCapabilitiesServer(s, ex)\n\n\tlis, err := net.Listen(\"tcp\", fmt.Sprintf(\"localhost:%d\", *port))\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to listen: %v\\n\", err)\n\t}\n\tlog.Printf(\"listening address: %s\\n\", lis.Addr())\n\n\tif *addrFile != \"\" {\n\t\tif err := os.WriteFile(*addrFile, []byte(lis.Addr().String()), 0600); err != nil {\n\t\t\tlog.Fatalf(\"failed to write addrFile: %v\", err)\n\t\t}\n\t}\n\n\tdefer signals.HandleInterrupt(func() {\n\t\tlog.Println(\"shutting down fake CAS gRPC server...\")\n\t\ts.GracefulStop()\n\t})()\n\n\tlog.Println(\"starting CAS fake server...\")\n\tif err := s.Serve(lis); err != nil {\n\t\tlog.Fatalf(\"failed to serve fake CAS gRPC server: %v\\n\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package acr\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\tcr \"github.com\/Azure\/azure-sdk-for-go\/services\/containerregistry\/mgmt\/2018-09-01\/containerregistry\"\n\t\"github.com\/Azure\/go-autorest\/autorest\/azure\/auth\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\/tag\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/docker\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/schema\/latest\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/util\"\n\t\"github.com\/pkg\/errors\"\n\t\"io\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"time\"\n)\n\nconst BUILD_STATUS_HEADER = \"x-ms-meta-Complete\"\n\nfunc (b *Builder) Build(ctx context.Context, out io.Writer, tagger tag.Tagger, artifacts []*latest.Artifact) ([]build.Artifact, error) {\n\treturn build.InParallel(ctx, out, tagger, artifacts, b.buildArtifact)\n}\n\nfunc (b *Builder) buildArtifact(ctx context.Context, out io.Writer, tagger tag.Tagger, artifact *latest.Artifact) (string, error) {\n\tclient := cr.NewRegistriesClient(b.Credentials.SubscriptionId)\n\tauthorizer, err := auth.NewClientCredentialsConfig(b.Credentials.ClientId, b.Credentials.ClientSecret, b.Credentials.TenantId).Authorizer()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"authorizing client\")\n\t}\n\tclient.Authorizer = authorizer\n\n\tresult, err := client.GetBuildSourceUploadURL(ctx, b.ResourceGroup, b.ContainerRegistry)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"build source upload url\")\n\t}\n\tblob := NewBlobStorage(*result.UploadURL)\n\n\terr = docker.CreateDockerTarGzContext(blob.Writer(), artifact.Workspace, artifact.DockerArtifact)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"create context tar.gz\")\n\t}\n\n\terr = blob.UploadFileToBlob()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"upload file to blob\")\n\t}\n\n\timageTag, err := tagger.GenerateFullyQualifiedImageName(artifact.Workspace, &tag.Options{\n\t\tDigest:    util.RandomID(),\n\t\tImageName: artifact.ImageName,\n\t})\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"create fully qualified image name\")\n\t}\n\n\timageTag, err = getImageTagWithoutFQDN(imageTag)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get azure image tag\")\n\t}\n\n\tbuildRequest := cr.DockerBuildRequest{\n\t\tImageNames:     &[]string{imageTag},\n\t\tIsPushEnabled:  &[]bool{true}[0], \/\/who invented bool pointers\n\t\tSourceLocation: result.RelativePath,\n\t\tPlatform: &cr.PlatformProperties{\n\t\t\tVariant:      cr.V8,\n\t\t\tOs:           cr.Linux,\n\t\t\tArchitecture: cr.Amd64,\n\t\t},\n\t\tDockerFilePath: &artifact.DockerArtifact.DockerfilePath,\n\t\tType:           cr.TypeDockerBuildRequest,\n\t}\n\tfuture, err := client.ScheduleRun(ctx, b.ResourceGroup, b.ContainerRegistry, buildRequest)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"schedule build request\")\n\t}\n\n\trun, err := future.Result(client)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get run id\")\n\t}\n\trunId := *run.RunID\n\n\trunsClient := cr.NewRunsClient(b.Credentials.SubscriptionId)\n\trunsClient.Authorizer = client.Authorizer\n\tlogUrl, err := runsClient.GetLogSasURL(ctx, b.ResourceGroup, b.ContainerRegistry, runId)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get log url\")\n\t}\n\n\terr = pollBuildStatus(*logUrl.LogLink, out)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"polling build status\")\n\t}\n\n\treturn imageTag, nil\n}\n\nfunc pollBuildStatus(logUrl string, out io.Writer) error {\n\toffset := int32(0)\n\tfor {\n\t\tresp, err := http.Get(logUrl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif resp.StatusCode == http.StatusNotFound {\n\t\t\t\/\/if blob is not available yet, try again\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\tscanner := bufio.NewScanner(resp.Body)\n\t\tline := int32(0)\n\t\tfor scanner.Scan() {\n\t\t\tif line > offset {\n\t\t\t\tout.Write(scanner.Bytes())\n\t\t\t\tline++\n\t\t\t\toffset++\n\t\t\t}\n\t\t}\n\t\tresp.Body.Close()\n\n\t\tif offset > 0 {\n\t\t\tswitch resp.Header.Get(BUILD_STATUS_HEADER) {\n\t\t\tcase \"\": \/\/run succeeded when there is no status header\n\t\t\t\treturn nil\n\t\t\tcase \"internalerror\":\n\t\t\tcase \"failed\":\n\t\t\t\treturn errors.New(\"run failed\")\n\t\t\tcase \"timedout\":\n\t\t\t\treturn errors.New(\"run timed out\")\n\t\t\tcase \"canceled\":\n\t\t\t\treturn errors.New(\"run was canceled\")\n\t\t\t}\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\t}\n}\n\n\/\/ ACR needs the image tag in the following format\n\/\/ <registryName>\/<repository>:<tag>\nfunc getImageTagWithoutFQDN(imageTag string) (string, error) {\n\tr, err := regexp.Compile(\"(.*)\\\\..*\\\\..*(\/.*)\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"create regexp\")\n\t}\n\n\tmatches := r.FindStringSubmatch(imageTag)\n\tif len(matches) < 3 {\n\t\treturn \"\", errors.New(\"invalid image tag\")\n\t}\n\n\treturn matches[1] + matches[2], nil\n}\n<commit_msg>always increment log lines<commit_after>package acr\n\nimport (\n\t\"bufio\"\n\t\"context\"\n\tcr \"github.com\/Azure\/azure-sdk-for-go\/services\/containerregistry\/mgmt\/2018-09-01\/containerregistry\"\n\t\"github.com\/Azure\/go-autorest\/autorest\/azure\/auth\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\/tag\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/docker\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/schema\/latest\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/util\"\n\t\"github.com\/pkg\/errors\"\n\t\"io\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"time\"\n)\n\nconst BUILD_STATUS_HEADER = \"x-ms-meta-Complete\"\n\nfunc (b *Builder) Build(ctx context.Context, out io.Writer, tagger tag.Tagger, artifacts []*latest.Artifact) ([]build.Artifact, error) {\n\treturn build.InParallel(ctx, out, tagger, artifacts, b.buildArtifact)\n}\n\nfunc (b *Builder) buildArtifact(ctx context.Context, out io.Writer, tagger tag.Tagger, artifact *latest.Artifact) (string, error) {\n\tclient := cr.NewRegistriesClient(b.Credentials.SubscriptionId)\n\tauthorizer, err := auth.NewClientCredentialsConfig(b.Credentials.ClientId, b.Credentials.ClientSecret, b.Credentials.TenantId).Authorizer()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"authorizing client\")\n\t}\n\tclient.Authorizer = authorizer\n\n\tresult, err := client.GetBuildSourceUploadURL(ctx, b.ResourceGroup, b.ContainerRegistry)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"build source upload url\")\n\t}\n\tblob := NewBlobStorage(*result.UploadURL)\n\n\terr = docker.CreateDockerTarGzContext(blob.Writer(), artifact.Workspace, artifact.DockerArtifact)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"create context tar.gz\")\n\t}\n\n\terr = blob.UploadFileToBlob()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"upload file to blob\")\n\t}\n\n\timageTag, err := tagger.GenerateFullyQualifiedImageName(artifact.Workspace, &tag.Options{\n\t\tDigest:    util.RandomID(),\n\t\tImageName: artifact.ImageName,\n\t})\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"create fully qualified image name\")\n\t}\n\n\timageTag, err = getImageTagWithoutFQDN(imageTag)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get azure image tag\")\n\t}\n\n\tbuildRequest := cr.DockerBuildRequest{\n\t\tImageNames:     &[]string{imageTag},\n\t\tIsPushEnabled:  &[]bool{true}[0], \/\/who invented bool pointers\n\t\tSourceLocation: result.RelativePath,\n\t\tPlatform: &cr.PlatformProperties{\n\t\t\tVariant:      cr.V8,\n\t\t\tOs:           cr.Linux,\n\t\t\tArchitecture: cr.Amd64,\n\t\t},\n\t\tDockerFilePath: &artifact.DockerArtifact.DockerfilePath,\n\t\tType:           cr.TypeDockerBuildRequest,\n\t}\n\tfuture, err := client.ScheduleRun(ctx, b.ResourceGroup, b.ContainerRegistry, buildRequest)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"schedule build request\")\n\t}\n\n\trun, err := future.Result(client)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get run id\")\n\t}\n\trunId := *run.RunID\n\n\trunsClient := cr.NewRunsClient(b.Credentials.SubscriptionId)\n\trunsClient.Authorizer = client.Authorizer\n\tlogUrl, err := runsClient.GetLogSasURL(ctx, b.ResourceGroup, b.ContainerRegistry, runId)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"get log url\")\n\t}\n\n\terr = pollBuildStatus(*logUrl.LogLink, out)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"polling build status\")\n\t}\n\n\treturn imageTag, nil\n}\n\nfunc pollBuildStatus(logUrl string, out io.Writer) error {\n\toffset := int32(0)\n\tfor {\n\t\tresp, err := http.Get(logUrl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif resp.StatusCode == http.StatusNotFound {\n\t\t\t\/\/if blob is not available yet, try again\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t\tcontinue\n\t\t}\n\n\t\tscanner := bufio.NewScanner(resp.Body)\n\t\tline := int32(0)\n\t\tfor scanner.Scan() {\n\t\t\tif line > offset {\n\t\t\t\tout.Write(scanner.Bytes())\n\t\t\t\toffset++\n\t\t\t}\n\t\t\tline++\n\t\t}\n\t\tresp.Body.Close()\n\n\t\tif offset > 0 {\n\t\t\tswitch resp.Header.Get(BUILD_STATUS_HEADER) {\n\t\t\tcase \"\": \/\/run succeeded when there is no status header\n\t\t\t\treturn nil\n\t\t\tcase \"internalerror\":\n\t\t\tcase \"failed\":\n\t\t\t\treturn errors.New(\"run failed\")\n\t\t\tcase \"timedout\":\n\t\t\t\treturn errors.New(\"run timed out\")\n\t\t\tcase \"canceled\":\n\t\t\t\treturn errors.New(\"run was canceled\")\n\t\t\t}\n\t\t}\n\n\t\ttime.Sleep(2 * time.Second)\n\t}\n}\n\n\/\/ ACR needs the image tag in the following format\n\/\/ <registryName>\/<repository>:<tag>\nfunc getImageTagWithoutFQDN(imageTag string) (string, error) {\n\tr, err := regexp.Compile(\"(.*)\\\\..*\\\\..*(\/.*)\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"create regexp\")\n\t}\n\n\tmatches := r.FindStringSubmatch(imageTag)\n\tif len(matches) < 3 {\n\t\treturn \"\", errors.New(\"invalid image tag\")\n\t}\n\n\treturn matches[1] + matches[2], nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage constants\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nconst (\n\t\/\/ DefaultLogLevel is the default global verbosity\n\tDefaultLogLevel = logrus.WarnLevel\n\n\t\/\/ DefaultDockerfilePath is the dockerfile path is given relative to the\n\t\/\/ context directory\n\tDefaultDockerfilePath = \"Dockerfile\"\n\n\tDefaultDevTagStrategy = TagStrategySha256\n\tDefaultRunTagStrategy = TagStrategyGitCommit\n\n\t\/\/ TagStrategySha256 uses the checksum of the built artifact as the tag\n\tTagStrategySha256    = \"sha256\"\n\tTagStrategyGitCommit = \"gitCommit\"\n\n\tDefaultMinikubeContext         = \"minikube\"\n\tDefaultDockerForDesktopContext = \"docker-for-desktop\"\n\tGCSBucketSuffix                = \"_cloudbuild\"\n\n\tHelmOverridesFilename = \"skaffold-overrides.yaml\"\n\n\tDefaultKustomizationPath = \".\"\n\n\tDefaultKanikoImage             = \"gcr.io\/kaniko-project\/executor@sha256:434bbb1d998ba1bd8ebc04c90d93afa859fd5c7ff93326bca9f6e7da0d6277ff\"\n\tDefaultKanikoSecretName        = \"kaniko-secret\"\n\tDefaultKanikoTimeout           = \"20m\"\n\tDefaultKanikoContainerName     = \"kaniko\"\n\tDefaultKanikoEmptyDirName      = \"kaniko-emptydir\"\n\tDefaultKanikoEmptyDirMountPath = \"\/kaniko\/buildcontext\"\n\n\tDefaultAlpineImage = \"alpine\"\n\n\tUpdateCheckEnvironmentVariable = \"SKAFFOLD_UPDATE_CHECK\"\n\n\tDefaultCloudBuildDockerImage = \"gcr.io\/cloud-builders\/docker\"\n\n\t\/\/ A regex matching valid repository names (https:\/\/github.com\/docker\/distribution\/blob\/master\/reference\/reference.go)\n\tRepositoryComponentRegex string = `^[a-z\\d]+(?:(?:[_.]|__|-+)[a-z\\d]+)*$`\n)\n\nvar DefaultKubectlManifests = []string{\"k8s\/*.yaml\"}\n\nvar LatestDownloadURL = fmt.Sprintf(\"https:\/\/storage.googleapis.com\/skaffold\/releases\/latest\/skaffold-%s-%s\", runtime.GOOS, runtime.GOARCH)\n\nvar Labels = struct {\n\tTagPolicy        string\n\tDeployer         string\n\tBuilder          string\n\tDockerAPIVersion string\n\tDefaultLabels    map[string]string\n}{\n\tDefaultLabels: map[string]string{\n\t\t\"deployed-with\": \"skaffold\",\n\t},\n\tTagPolicy:        \"skaffold-tag-policy\",\n\tDeployer:         \"skaffold-deployer\",\n\tBuilder:          \"skaffold-builder\",\n\tDockerAPIVersion: \"docker-api-version\",\n}\n<commit_msg>Update kaniko image to latest version<commit_after>\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage constants\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nconst (\n\t\/\/ DefaultLogLevel is the default global verbosity\n\tDefaultLogLevel = logrus.WarnLevel\n\n\t\/\/ DefaultDockerfilePath is the dockerfile path is given relative to the\n\t\/\/ context directory\n\tDefaultDockerfilePath = \"Dockerfile\"\n\n\tDefaultDevTagStrategy = TagStrategySha256\n\tDefaultRunTagStrategy = TagStrategyGitCommit\n\n\t\/\/ TagStrategySha256 uses the checksum of the built artifact as the tag\n\tTagStrategySha256    = \"sha256\"\n\tTagStrategyGitCommit = \"gitCommit\"\n\n\tDefaultMinikubeContext         = \"minikube\"\n\tDefaultDockerForDesktopContext = \"docker-for-desktop\"\n\tGCSBucketSuffix                = \"_cloudbuild\"\n\n\tHelmOverridesFilename = \"skaffold-overrides.yaml\"\n\n\tDefaultKustomizationPath = \".\"\n\n\tDefaultKanikoImage             = \"gcr.io\/kaniko-project\/executor:v0.7.0@sha256:0b4e0812aa17c54a9b8d8c8d7cb35559a892a341650acf7cb428c3e8cb4a3919\"\n\tDefaultKanikoSecretName        = \"kaniko-secret\"\n\tDefaultKanikoTimeout           = \"20m\"\n\tDefaultKanikoContainerName     = \"kaniko\"\n\tDefaultKanikoEmptyDirName      = \"kaniko-emptydir\"\n\tDefaultKanikoEmptyDirMountPath = \"\/kaniko\/buildcontext\"\n\n\tDefaultAlpineImage = \"alpine\"\n\n\tUpdateCheckEnvironmentVariable = \"SKAFFOLD_UPDATE_CHECK\"\n\n\tDefaultCloudBuildDockerImage = \"gcr.io\/cloud-builders\/docker\"\n\n\t\/\/ A regex matching valid repository names (https:\/\/github.com\/docker\/distribution\/blob\/master\/reference\/reference.go)\n\tRepositoryComponentRegex string = `^[a-z\\d]+(?:(?:[_.]|__|-+)[a-z\\d]+)*$`\n)\n\nvar DefaultKubectlManifests = []string{\"k8s\/*.yaml\"}\n\nvar LatestDownloadURL = fmt.Sprintf(\"https:\/\/storage.googleapis.com\/skaffold\/releases\/latest\/skaffold-%s-%s\", runtime.GOOS, runtime.GOARCH)\n\nvar Labels = struct {\n\tTagPolicy        string\n\tDeployer         string\n\tBuilder          string\n\tDockerAPIVersion string\n\tDefaultLabels    map[string]string\n}{\n\tDefaultLabels: map[string]string{\n\t\t\"deployed-with\": \"skaffold\",\n\t},\n\tTagPolicy:        \"skaffold-tag-policy\",\n\tDeployer:         \"skaffold-deployer\",\n\tBuilder:          \"skaffold-builder\",\n\tDockerAPIVersion: \"docker-api-version\",\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage deploy\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/GoogleCloudPlatform\/skaffold\/pkg\/skaffold\/build\"\n\t\"github.com\/GoogleCloudPlatform\/skaffold\/pkg\/skaffold\/config\"\n\t\"github.com\/GoogleCloudPlatform\/skaffold\/pkg\/skaffold\/util\"\n\t\"github.com\/GoogleCloudPlatform\/skaffold\/testutil\"\n\t\"github.com\/spf13\/afero\"\n)\n\nconst testKubeContext = \"kubecontext\"\n\nconst deploymentYAML = `apiVersion: apps\/v1\nkind: Deployment\nmetadata:\n  name: leeroy-web\n  labels:\n    app: leeroy-web\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: leeroy-web\n  template:\n    metadata:\n      labels:\n        app: leeroy-web\n    spec:\n      containers:\n      - name: leeroy-web\n        image: IMAGE_NAME\n        ports:\n\t\t- containerPort: 8080\n`\n\nfunc TestKubectlRun(t *testing.T) {\n\tvar tests = []struct {\n\t\tdescription string\n\t\tcfg         *config.DeployConfig\n\t\tb           *build.BuildResult\n\t\tcommand     util.Command\n\n\t\texpected  *Result\n\t\tshouldErr bool\n\t}{\n\t\t{\n\t\t\tdescription: \"parameter mismatch\",\n\t\t\tshouldErr:   true,\n\t\t\tcfg: &config.DeployConfig{\n\t\t\t\tDeployType: config.DeployType{\n\t\t\t\t\tKubectlDeploy: &config.KubectlDeploy{\n\t\t\t\t\t\tManifests: []config.Manifest{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tPaths: []string{\"test\/deployment.yaml\"},\n\t\t\t\t\t\t\t\tParameters: map[string]string{\n\t\t\t\t\t\t\t\t\t\"IMAGE_NAME\": \"abc\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tb: &build.BuildResult{\n\t\t\t\tBuilds: []build.Build{\n\t\t\t\t\t{\n\t\t\t\t\t\tImageName: \"not_abc\",\n\t\t\t\t\t\tTag:       \"not_abc:123\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescription: \"missing manifest file\",\n\t\t\tshouldErr:   true,\n\t\t\tcfg: &config.DeployConfig{\n\t\t\t\tDeployType: config.DeployType{\n\t\t\t\t\tKubectlDeploy: &config.KubectlDeploy{\n\t\t\t\t\t\tManifests: []config.Manifest{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tPaths: []string{\"test\/not_deployment.yaml\"},\n\t\t\t\t\t\t\t\tParameters: map[string]string{\n\t\t\t\t\t\t\t\t\t\"IMAGE_NAME\": \"abc\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tb: &build.BuildResult{\n\t\t\t\tBuilds: []build.Build{\n\t\t\t\t\t{\n\t\t\t\t\t\tImageName: \"abc\",\n\t\t\t\t\t\tTag:       \"abc:123\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescription: \"deploy success\",\n\t\t\tcfg: &config.DeployConfig{\n\t\t\t\tDeployType: config.DeployType{\n\t\t\t\t\tKubectlDeploy: &config.KubectlDeploy{\n\t\t\t\t\t\tManifests: []config.Manifest{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tPaths: []string{\"test\/deployment.yaml\"},\n\t\t\t\t\t\t\t\tParameters: map[string]string{\n\t\t\t\t\t\t\t\t\t\"IMAGE_NAME\": \"abc\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tcommand: testutil.NewFakeRunCommand(\"\", \"\", nil),\n\t\t\tb: &build.BuildResult{\n\t\t\t\tBuilds: []build.Build{\n\t\t\t\t\t{\n\t\t\t\t\t\tImageName: \"abc\",\n\t\t\t\t\t\tTag:       \"abc:123\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: &Result{},\n\t\t},\n\t\t{\n\t\t\tdescription: \"deploy command error\",\n\t\t\tshouldErr:   true,\n\t\t\tcfg: &config.DeployConfig{\n\t\t\t\tDeployType: config.DeployType{\n\t\t\t\t\tKubectlDeploy: &config.KubectlDeploy{\n\t\t\t\t\t\tManifests: []config.Manifest{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tPaths: []string{\"test\/not_deployment.yaml\"},\n\t\t\t\t\t\t\t\tParameters: map[string]string{\n\t\t\t\t\t\t\t\t\t\"IMAGE_NAME\": \"abc\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tcommand: testutil.NewFakeRunCommand(\"\", \"\", fmt.Errorf(\"\")),\n\t\t\tb: &build.BuildResult{\n\t\t\t\tBuilds: []build.Build{\n\t\t\t\t\t{\n\t\t\t\t\t\tImageName: \"abc\",\n\t\t\t\t\t\tTag:       \"abc:123\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tutil.Fs = afero.NewMemMapFs()\n\tdefer util.ResetFs()\n\tutil.Fs.MkdirAll(\"test\", 0750)\n\tfiles := map[string]string{\n\t\t\"test\/deployment.yaml\": deploymentYAML,\n\t}\n\tfor path, contents := range files {\n\t\tafero.WriteFile(util.Fs, path, []byte(contents), 0644)\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tif test.command != nil {\n\t\t\t\tutil.DefaultExecCommand = test.command\n\t\t\t\tdefer util.ResetDefaultExecCommand()\n\t\t\t}\n\n\t\t\tk := NewKubectlDeployer(test.cfg, testKubeContext)\n\t\t\tres, err := k.Deploy(context.Background(), &bytes.Buffer{}, test.b)\n\n\t\t\ttestutil.CheckErrorAndDeepEqual(t, test.shouldErr, err, test.expected, res)\n\t\t})\n\n\t}\n}\n\nfunc TestReplaceParameters(t *testing.T) {\n\tmanifest := \"[IMAGE_NAME][IMAGE_NAME_OTHER][OTHER]\"\n\texpectedManifest := \"[image:v1][image_other:v1][other:v1]\"\n\n\tmanifest = replaceParameters(manifest, map[string]build.Build{\n\t\t\"IMAGE_NAME\":       {Tag: \"image:v1\"},\n\t\t\"IMAGE_NAME_OTHER\": {Tag: \"image_other:v1\"},\n\t\t\"OTHER\":            {Tag: \"other:v1\"},\n\t})\n\n\tif manifest != expectedManifest {\n\t\tt.Errorf(\"Expected: '%s'. Got: '%s'\", expectedManifest, manifest)\n\t}\n}\n<commit_msg>kubectl: fix tests<commit_after>\/*\nCopyright 2018 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage deploy\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/GoogleCloudPlatform\/skaffold\/pkg\/skaffold\/build\"\n\t\"github.com\/GoogleCloudPlatform\/skaffold\/pkg\/skaffold\/config\"\n\t\"github.com\/GoogleCloudPlatform\/skaffold\/pkg\/skaffold\/util\"\n\t\"github.com\/GoogleCloudPlatform\/skaffold\/testutil\"\n\t\"github.com\/spf13\/afero\"\n)\n\nconst testKubeContext = \"kubecontext\"\n\nconst deploymentYAML = `apiVersion: apps\/v1\nkind: Deployment\nmetadata:\n  name: leeroy-web\n  labels:\n    app: leeroy-web\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: leeroy-web\n  template:\n    metadata:\n      labels:\n        app: leeroy-web\n    spec:\n      containers:\n      - name: leeroy-web\n        image: leeroy-web-image\n        ports:\n\t\t- containerPort: 8080\n`\n\nfunc TestKubectlRun(t *testing.T) {\n\tvar tests = []struct {\n\t\tdescription string\n\t\tcfg         *config.DeployConfig\n\t\tb           *build.BuildResult\n\t\tcommand     util.Command\n\n\t\texpected  *Result\n\t\tshouldErr bool\n\t}{\n\t\t{\n\t\t\tdescription: \"parameter mismatch\",\n\t\t\tshouldErr:   true,\n\t\t\tcfg: &config.DeployConfig{\n\t\t\t\tDeployType: config.DeployType{\n\t\t\t\t\tKubectlDeploy: &config.KubectlDeploy{\n\t\t\t\t\t\tManifests: []config.Manifest{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tPaths:  []string{\"test\/deployment.yaml\"},\n\t\t\t\t\t\t\t\tImages: []string{\"leeroy-web-image\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tb: &build.BuildResult{\n\t\t\t\tBuilds: []build.Build{\n\t\t\t\t\t{\n\t\t\t\t\t\tImageName: \"leeroy-web-image\",\n\t\t\t\t\t\tTag:       \"leeroy-web-image:v1\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescription: \"missing manifest file\",\n\t\t\tshouldErr:   true,\n\t\t\tcfg: &config.DeployConfig{\n\t\t\t\tDeployType: config.DeployType{\n\t\t\t\t\tKubectlDeploy: &config.KubectlDeploy{\n\t\t\t\t\t\tManifests: []config.Manifest{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tPaths:  []string{\"test\/not_deployment.yaml\"},\n\t\t\t\t\t\t\t\tImages: []string{\"leeroy-web-image\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tb: &build.BuildResult{\n\t\t\t\tBuilds: []build.Build{\n\t\t\t\t\t{\n\t\t\t\t\t\tImageName: \"leeroy-web-image\",\n\t\t\t\t\t\tTag:       \"leeroy-web-image:123\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdescription: \"deploy success\",\n\t\t\tcfg: &config.DeployConfig{\n\t\t\t\tDeployType: config.DeployType{\n\t\t\t\t\tKubectlDeploy: &config.KubectlDeploy{\n\t\t\t\t\t\tManifests: []config.Manifest{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tPaths:  []string{\"test\/deployment.yaml\"},\n\t\t\t\t\t\t\t\tImages: []string{\"leeroy-web-image\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tcommand: testutil.NewFakeRunCommand(\"\", \"\", nil),\n\t\t\tb: &build.BuildResult{\n\t\t\t\tBuilds: []build.Build{\n\t\t\t\t\t{\n\t\t\t\t\t\tImageName: \"leeroy-web-image\",\n\t\t\t\t\t\tTag:       \"leeroy-web-image:123\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: &Result{},\n\t\t},\n\t\t{\n\t\t\tdescription: \"deploy command error\",\n\t\t\tshouldErr:   true,\n\t\t\tcfg: &config.DeployConfig{\n\t\t\t\tDeployType: config.DeployType{\n\t\t\t\t\tKubectlDeploy: &config.KubectlDeploy{\n\t\t\t\t\t\tManifests: []config.Manifest{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tPaths:  []string{\"test\/not_deployment.yaml\"},\n\t\t\t\t\t\t\t\tImages: []string{\"leeroy-web-image\"},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tcommand: testutil.NewFakeRunCommand(\"\", \"\", fmt.Errorf(\"\")),\n\t\t\tb: &build.BuildResult{\n\t\t\t\tBuilds: []build.Build{\n\t\t\t\t\t{\n\t\t\t\t\t\tImageName: \"leeroy-web-image\",\n\t\t\t\t\t\tTag:       \"leeroy-web-image:123\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tutil.Fs = afero.NewMemMapFs()\n\tdefer util.ResetFs()\n\tutil.Fs.MkdirAll(\"test\", 0750)\n\tfiles := map[string]string{\n\t\t\"test\/deployment.yaml\": deploymentYAML,\n\t}\n\tfor path, contents := range files {\n\t\tafero.WriteFile(util.Fs, path, []byte(contents), 0644)\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.description, func(t *testing.T) {\n\t\t\tif test.command != nil {\n\t\t\t\tutil.DefaultExecCommand = test.command\n\t\t\t\tdefer util.ResetDefaultExecCommand()\n\t\t\t}\n\n\t\t\tk := NewKubectlDeployer(test.cfg, testKubeContext)\n\t\t\tres, err := k.Deploy(context.Background(), &bytes.Buffer{}, test.b)\n\n\t\t\ttestutil.CheckErrorAndDeepEqual(t, test.shouldErr, err, test.expected, res)\n\t\t})\n\n\t}\n}\n\nfunc TestReplaceParameters(t *testing.T) {\n\tmanifest := \"[IMAGE_NAME][IMAGE_NAME_OTHER][OTHER]\"\n\texpectedManifest := \"[image:v1][image_other:v1][other:v1]\"\n\n\tmanifest = replaceParameters(manifest, map[string]build.Build{\n\t\t\"IMAGE_NAME\":       {Tag: \"image:v1\"},\n\t\t\"IMAGE_NAME_OTHER\": {Tag: \"image_other:v1\"},\n\t\t\"OTHER\":            {Tag: \"other:v1\"},\n\t})\n\n\tif manifest != expectedManifest {\n\t\tt.Errorf(\"Expected: '%s'. Got: '%s'\", expectedManifest, manifest)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build !nounit\n\npackage smokescreen\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"net\/url\"\n\t\"sync\/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\tlogrustest \"github.com\/sirupsen\/logrus\/hooks\/test\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\t\"github.com\/stripe\/smokescreen\/pkg\/smokescreen\/conntrack\"\n)\n\nvar allowRanges = []string{\n\t\"8.8.9.0\/24\",\n\t\"10.0.1.0\/24\",\n\t\"172.16.1.0\/24\",\n\t\"192.168.1.0\/24\",\n\t\"127.0.1.0\/24\",\n}\nvar allowAddresses = []string{\n\t\"10.0.0.1:321\",\n}\nvar denyRanges = []string{\n\t\"1.1.1.1\/32\",\n}\nvar denyAddresses = []string{\n\t\"8.8.8.8:321\",\n}\n\ntype testCase struct {\n\tip       string\n\tport     int\n\texpected ipType\n}\n\nfunc TestClassifyAddr(t *testing.T) {\n\ta := assert.New(t)\n\n\tconf := NewConfig()\n\ta.NoError(conf.SetDenyRanges(denyRanges))\n\ta.NoError(conf.SetDenyAddresses(denyAddresses))\n\ta.NoError(conf.SetAllowRanges(allowRanges))\n\ta.NoError(conf.SetAllowAddresses(allowAddresses))\n\tconf.ConnectTimeout = 10 * time.Second\n\tconf.ExitTimeout = 10 * time.Second\n\tconf.AdditionalErrorMessageOnDeny = \"Proxy denied\"\n\n\ttestIPs := []testCase{\n\t\ttestCase{\"8.8.8.8\", 1, ipAllowDefault},\n\t\ttestCase{\"8.8.9.8\", 1, ipAllowUserConfigured},\n\n\t\t\/\/ Specific blocked networks\n\t\ttestCase{\"10.0.0.1\", 1, ipDenyPrivateRange},\n\t\ttestCase{\"10.0.0.1\", 321, ipAllowUserConfigured},\n\t\ttestCase{\"10.0.1.1\", 1, ipAllowUserConfigured},\n\t\ttestCase{\"172.16.0.1\", 1, ipDenyPrivateRange},\n\t\ttestCase{\"172.16.1.1\", 1, ipAllowUserConfigured},\n\t\ttestCase{\"192.168.0.1\", 1, ipDenyPrivateRange},\n\t\ttestCase{\"192.168.1.1\", 1, ipAllowUserConfigured},\n\t\ttestCase{\"8.8.8.8\", 321, ipDenyUserConfigured},\n\t\ttestCase{\"1.1.1.1\", 1, ipDenyUserConfigured},\n\n\t\t\/\/ localhost\n\t\ttestCase{\"127.0.0.1\", 1, ipDenyNotGlobalUnicast},\n\t\ttestCase{\"127.255.255.255\", 1, ipDenyNotGlobalUnicast},\n\t\ttestCase{\"::1\", 1, ipDenyNotGlobalUnicast},\n\t\ttestCase{\"127.0.1.1\", 1, ipAllowUserConfigured},\n\n\t\t\/\/ ec2 metadata endpoint\n\t\ttestCase{\"169.254.169.254\", 1, ipDenyNotGlobalUnicast},\n\n\t\t\/\/ Broadcast addresses\n\t\ttestCase{\"255.255.255.255\", 1, ipDenyNotGlobalUnicast},\n\t\ttestCase{\"ff02:0:0:0:0:0:0:2\", 1, ipDenyNotGlobalUnicast},\n\t}\n\n\tfor _, test := range testIPs {\n\t\tlocalIP := net.ParseIP(test.ip)\n\t\tif localIP == nil {\n\t\t\tt.Errorf(\"Could not parse IP from string: %s\", test.ip)\n\t\t\tcontinue\n\t\t}\n\t\tlocalAddr := net.TCPAddr{\n\t\t\tIP:   localIP,\n\t\t\tPort: test.port,\n\t\t}\n\n\t\tgot := classifyAddr(conf, &localAddr)\n\t\tif got != test.expected {\n\t\t\tt.Errorf(\"Misclassified IP (%s): should be %s, but is instead %s.\", localIP, test.expected, got)\n\t\t}\n\t}\n}\n\nfunc TestClearsErrorHeader(t *testing.T) {\n\tr := require.New(t)\n\n\tlog.SetFlags(log.LstdFlags | log.Lshortfile)\n\n\tproxySrv, _, err := proxyServer()\n\tr.NoError(err)\n\tdefer proxySrv.Close()\n\n\t\/\/ Create a http.Client that uses our proxy\n\tclient, err := proxyClient(proxySrv.URL)\n\tr.NoError(err)\n\n\t\/\/ Talk \"through\" the proxy to our malicious upstream that sets the\n\t\/\/ error header.\n\tresp, err := client.Get(\"http:\/\/httpbin.org\/response-headers?X-Smokescreen-Error=foobar&X-Smokescreen-Test=yes\")\n\tr.NoError(err)\n\n\t\/\/ Should succeed\n\tif resp.StatusCode != 200 {\n\t\tt.Errorf(\"response had bad status: expected 200, got %d\", resp.StatusCode)\n\t}\n\n\t\/\/ Verify the error header is not set.\n\tif h := resp.Header.Get(errorHeader); h != \"\" {\n\t\tt.Errorf(\"proxy did not strip %q header: %q\", errorHeader, h)\n\t}\n\n\t\/\/ Verify we did get the other header, to confirm we're talking to the right thing\n\tif h := resp.Header.Get(\"X-Smokescreen-Test\"); h != \"yes\" {\n\t\tt.Errorf(\"did not get expected header X-Smokescreen-Test: expected \\\"yes\\\", got %q\", h)\n\t}\n}\n\nfunc TestConsistentHostHeader(t *testing.T) {\n\tr := require.New(t)\n\ta := assert.New(t)\n\n\thostCh := make(chan string)\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"OK\"))\n\t\thostCh <- r.Host\n\t}))\n\tdefer ts.Close()\n\n\t\/\/ Custom proxy config for the \"remote\" httptest.NewServer\n\tconf := NewConfig()\n\tconf.ConnTracker = conntrack.NewTracker(conf.IdleThreshold, nil, conf.Log, atomic.Value{})\n\terr := conf.SetAllowAddresses([]string{\"127.0.0.1\"})\n\tr.NoError(err)\n\n\tproxy := BuildProxy(conf)\n\tproxySrv := httptest.NewServer(proxy)\n\n\tclient, err := proxyClient(proxySrv.URL)\n\tr.NoError(err)\n\n\treq, err := http.NewRequest(\"GET\", ts.URL, nil)\n\tr.NoError(err)\n\n\texpectedHostHeader := req.Host\n\tgo client.Do(req)\n\n\tselect {\n\tcase receivedHostHeader := <-hostCh:\n\t\ta.Equal(expectedHostHeader, receivedHostHeader)\n\tcase <-time.After(3 * time.Second):\n\t\tt.Fatal(\"timed out waiting for client request\")\n\t}\n}\n\nfunc TestClearsTraceIDHeader(t *testing.T) {\n\tr := require.New(t)\n\ta := assert.New(t)\n\n\theaderCh := make(chan string)\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"OK\"))\n\t\theaderCh <- r.Header.Get(\"X-Smokescreen-Trace-ID\")\n\t}))\n\tdefer ts.Close()\n\n\t\/\/ Custom proxy config for the \"remote\" httptest.NewServer\n\tconf := NewConfig()\n\tconf.ConnTracker = conntrack.NewTracker(conf.IdleThreshold, nil, conf.Log, atomic.Value{})\n\terr := conf.SetAllowAddresses([]string{\"127.0.0.1\"})\n\tr.NoError(err)\n\n\tproxy := BuildProxy(conf)\n\tproxySrv := httptest.NewServer(proxy)\n\n\tclient, err := proxyClient(proxySrv.URL)\n\tr.NoError(err)\n\n\treq, err := http.NewRequest(\"GET\", ts.URL, nil)\n\tr.NoError(err)\n\treq.Header.Set(\"X-Smokescreen-Trace-ID\", \"7fa4587f-7362-4515-ba44-e44490241af0\")\n\n\tgo client.Do(req)\n\n\tselect {\n\tcase receivedTraceIDCh := <-headerCh:\n\t\ta.Empty(receivedTraceIDCh)\n\tcase <-time.After(3 * time.Second):\n\t\tt.Fatal(\"timed out waiting for client request\")\n\t}\n}\n\nfunc TestShuttingDownValue(t *testing.T) {\n\ta := assert.New(t)\n\n\tconf := NewConfig()\n\tconf.Port = 39381\n\n\tquit := make(chan interface{})\n\tgo StartWithConfig(conf, quit)\n\n\t\/\/ These sleeps are not ideal, but there is a race with checking the\n\t\/\/ ShuttingDown value from these tests. The server has to bootstrap\n\t\/\/ itself with an initial value before it returns false, and has to\n\t\/\/ set the value to true after we send on the quit channel.\n\ttime.Sleep(500 * time.Millisecond)\n\ta.Equal(false, conf.ShuttingDown.Load())\n\n\tquit <- true\n\n\ttime.Sleep(500 * time.Millisecond)\n\ta.Equal(true, conf.ShuttingDown.Load())\n\n}\n\nfunc TestHealthcheck(t *testing.T) {\n\tr := require.New(t)\n\ta := assert.New(t)\n\n\thealthcheckCh := make(chan string)\n\n\ttestHealthcheck := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"OK\"))\n\t\thealthcheckCh <- \"OK\"\n\t})\n\n\tconf := NewConfig()\n\n\t\/\/ We set this here so that we can deterministically test the Healthcheck\n\t\/\/ handler. Otherwise we would have to call StartWithConfig() in a goroutine,\n\t\/\/ which creates a race between the test and the listener accepting\n\t\/\/ connections.\n\thandler := HealthcheckMiddleware{\n\t\tProxy:       BuildProxy(conf),\n\t\tHealthcheck: testHealthcheck,\n\t}\n\n\tserver := httptest.NewServer(handler)\n\n\tgo func() {\n\t\tselect {\n\t\tcase healthy := <-healthcheckCh:\n\t\t\ta.Equal(\"OK\", healthy)\n\t\tcase <-time.After(5 * time.Second):\n\t\t\tt.Fatal(\"timed out waiting for client request\")\n\t\t}\n\t}()\n\n\tresp, err := http.Get(fmt.Sprintf(\"%s\/healthcheck\", server.URL))\n\tr.NoError(err)\n\ta.Equal(http.StatusOK, resp.StatusCode)\n}\n\nvar invalidHostCases = []struct {\n\tscheme    string\n\texpectErr bool\n\tproxyType string\n}{\n\t{\"http\", false, \"http\"},\n\t{\"https\", true, \"connect\"},\n}\n\nfunc TestInvalidHost(t *testing.T) {\n\tfor _, testCase := range invalidHostCases {\n\t\tt.Run(testCase.scheme, func(t *testing.T) {\n\t\t\ta := assert.New(t)\n\t\t\tr := require.New(t)\n\n\t\t\tproxySrv, logHook, err := proxyServer()\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer proxySrv.Close()\n\n\t\t\t\/\/ Create a http.Client that uses our proxy\n\t\t\tclient, err := proxyClient(proxySrv.URL)\n\t\t\tr.NoError(err)\n\n\t\t\tresp, err := client.Get(fmt.Sprintf(\"%s:\/\/neversaynever.stripe.com\", testCase.scheme))\n\t\t\tif testCase.expectErr {\n\t\t\t\tr.EqualError(err, \"Get https:\/\/neversaynever.stripe.com: Request Rejected by Proxy\")\n\t\t\t} else {\n\t\t\t\tr.NoError(err)\n\t\t\t\tr.Equal(http.StatusProxyAuthRequired, resp.StatusCode)\n\t\t\t}\n\n\t\t\tentry := findCanonicalProxyDecision(logHook.AllEntries())\n\t\t\tr.NotNil(entry)\n\n\t\t\tif a.Contains(entry.Data, \"allow\") {\n\t\t\t\ta.Equal(true, entry.Data[\"allow\"])\n\t\t\t}\n\t\t\tif a.Contains(entry.Data, \"error\") {\n\t\t\t\ta.Contains(entry.Data[\"error\"], \"no such host\")\n\t\t\t}\n\t\t\tif a.Contains(entry.Data, \"proxy_type\") {\n\t\t\t\ta.Contains(entry.Data[\"proxy_type\"], testCase.proxyType)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc findCanonicalProxyDecision(logs []*logrus.Entry) *logrus.Entry {\n\tfor _, entry := range logs {\n\t\tif entry.Message == LOGLINE_CANONICAL_PROXY_DECISION {\n\t\t\treturn entry\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc proxyServer() (*httptest.Server, *logrustest.Hook, error) {\n\tvar logHook logrustest.Hook\n\n\tconf := NewConfig()\n\tconf.Port = 39381\n\tif err := conf.SetAllowRanges(allowRanges); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tconf.ConnectTimeout = 10 * time.Second\n\tconf.ExitTimeout = 10 * time.Second\n\tconf.AdditionalErrorMessageOnDeny = \"Proxy denied\"\n\tconf.Resolver = &net.Resolver{}\n\tconf.Log.AddHook(&logHook)\n\tconf.ConnTracker = conntrack.NewTracker(conf.IdleThreshold, nil, conf.Log, atomic.Value{})\n\n\tproxy := BuildProxy(conf)\n\treturn httptest.NewServer(proxy), &logHook, nil\n}\n\nfunc proxyClient(proxy string) (*http.Client, error) {\n\tproxyUrl, err := url.Parse(proxy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tProxy:                 http.ProxyURL(proxyUrl),\n\t\t\tTLSHandshakeTimeout:   10 * time.Second,\n\t\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t},\n\t}, nil\n}\n<commit_msg>Update test to check logs<commit_after>\/\/ +build !nounit\n\npackage smokescreen\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"net\/url\"\n\t\"sync\/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/sirupsen\/logrus\"\n\tlogrustest \"github.com\/sirupsen\/logrus\/hooks\/test\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\t\"github.com\/stripe\/smokescreen\/pkg\/smokescreen\/conntrack\"\n)\n\nvar allowRanges = []string{\n\t\"8.8.9.0\/24\",\n\t\"10.0.1.0\/24\",\n\t\"172.16.1.0\/24\",\n\t\"192.168.1.0\/24\",\n\t\"127.0.1.0\/24\",\n}\nvar allowAddresses = []string{\n\t\"10.0.0.1:321\",\n}\nvar denyRanges = []string{\n\t\"1.1.1.1\/32\",\n}\nvar denyAddresses = []string{\n\t\"8.8.8.8:321\",\n}\n\ntype testCase struct {\n\tip       string\n\tport     int\n\texpected ipType\n}\n\nfunc TestClassifyAddr(t *testing.T) {\n\ta := assert.New(t)\n\n\tconf := NewConfig()\n\ta.NoError(conf.SetDenyRanges(denyRanges))\n\ta.NoError(conf.SetDenyAddresses(denyAddresses))\n\ta.NoError(conf.SetAllowRanges(allowRanges))\n\ta.NoError(conf.SetAllowAddresses(allowAddresses))\n\tconf.ConnectTimeout = 10 * time.Second\n\tconf.ExitTimeout = 10 * time.Second\n\tconf.AdditionalErrorMessageOnDeny = \"Proxy denied\"\n\n\ttestIPs := []testCase{\n\t\ttestCase{\"8.8.8.8\", 1, ipAllowDefault},\n\t\ttestCase{\"8.8.9.8\", 1, ipAllowUserConfigured},\n\n\t\t\/\/ Specific blocked networks\n\t\ttestCase{\"10.0.0.1\", 1, ipDenyPrivateRange},\n\t\ttestCase{\"10.0.0.1\", 321, ipAllowUserConfigured},\n\t\ttestCase{\"10.0.1.1\", 1, ipAllowUserConfigured},\n\t\ttestCase{\"172.16.0.1\", 1, ipDenyPrivateRange},\n\t\ttestCase{\"172.16.1.1\", 1, ipAllowUserConfigured},\n\t\ttestCase{\"192.168.0.1\", 1, ipDenyPrivateRange},\n\t\ttestCase{\"192.168.1.1\", 1, ipAllowUserConfigured},\n\t\ttestCase{\"8.8.8.8\", 321, ipDenyUserConfigured},\n\t\ttestCase{\"1.1.1.1\", 1, ipDenyUserConfigured},\n\n\t\t\/\/ localhost\n\t\ttestCase{\"127.0.0.1\", 1, ipDenyNotGlobalUnicast},\n\t\ttestCase{\"127.255.255.255\", 1, ipDenyNotGlobalUnicast},\n\t\ttestCase{\"::1\", 1, ipDenyNotGlobalUnicast},\n\t\ttestCase{\"127.0.1.1\", 1, ipAllowUserConfigured},\n\n\t\t\/\/ ec2 metadata endpoint\n\t\ttestCase{\"169.254.169.254\", 1, ipDenyNotGlobalUnicast},\n\n\t\t\/\/ Broadcast addresses\n\t\ttestCase{\"255.255.255.255\", 1, ipDenyNotGlobalUnicast},\n\t\ttestCase{\"ff02:0:0:0:0:0:0:2\", 1, ipDenyNotGlobalUnicast},\n\t}\n\n\tfor _, test := range testIPs {\n\t\tlocalIP := net.ParseIP(test.ip)\n\t\tif localIP == nil {\n\t\t\tt.Errorf(\"Could not parse IP from string: %s\", test.ip)\n\t\t\tcontinue\n\t\t}\n\t\tlocalAddr := net.TCPAddr{\n\t\t\tIP:   localIP,\n\t\t\tPort: test.port,\n\t\t}\n\n\t\tgot := classifyAddr(conf, &localAddr)\n\t\tif got != test.expected {\n\t\t\tt.Errorf(\"Misclassified IP (%s): should be %s, but is instead %s.\", localIP, test.expected, got)\n\t\t}\n\t}\n}\n\nfunc TestClearsErrorHeader(t *testing.T) {\n\tr := require.New(t)\n\n\tlog.SetFlags(log.LstdFlags | log.Lshortfile)\n\n\tproxySrv, _, err := proxyServer()\n\tr.NoError(err)\n\tdefer proxySrv.Close()\n\n\t\/\/ Create a http.Client that uses our proxy\n\tclient, err := proxyClient(proxySrv.URL)\n\tr.NoError(err)\n\n\t\/\/ Talk \"through\" the proxy to our malicious upstream that sets the\n\t\/\/ error header.\n\tresp, err := client.Get(\"http:\/\/httpbin.org\/response-headers?X-Smokescreen-Error=foobar&X-Smokescreen-Test=yes\")\n\tr.NoError(err)\n\n\t\/\/ Should succeed\n\tif resp.StatusCode != 200 {\n\t\tt.Errorf(\"response had bad status: expected 200, got %d\", resp.StatusCode)\n\t}\n\n\t\/\/ Verify the error header is not set.\n\tif h := resp.Header.Get(errorHeader); h != \"\" {\n\t\tt.Errorf(\"proxy did not strip %q header: %q\", errorHeader, h)\n\t}\n\n\t\/\/ Verify we did get the other header, to confirm we're talking to the right thing\n\tif h := resp.Header.Get(\"X-Smokescreen-Test\"); h != \"yes\" {\n\t\tt.Errorf(\"did not get expected header X-Smokescreen-Test: expected \\\"yes\\\", got %q\", h)\n\t}\n}\n\nfunc TestConsistentHostHeader(t *testing.T) {\n\tr := require.New(t)\n\ta := assert.New(t)\n\n\thostCh := make(chan string)\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"OK\"))\n\t\thostCh <- r.Host\n\t}))\n\tdefer ts.Close()\n\n\t\/\/ Custom proxy config for the \"remote\" httptest.NewServer\n\tconf := NewConfig()\n\tconf.ConnTracker = conntrack.NewTracker(conf.IdleThreshold, nil, conf.Log, atomic.Value{})\n\terr := conf.SetAllowAddresses([]string{\"127.0.0.1\"})\n\tr.NoError(err)\n\n\tproxy := BuildProxy(conf)\n\tproxySrv := httptest.NewServer(proxy)\n\n\tclient, err := proxyClient(proxySrv.URL)\n\tr.NoError(err)\n\n\treq, err := http.NewRequest(\"GET\", ts.URL, nil)\n\tr.NoError(err)\n\n\texpectedHostHeader := req.Host\n\tgo client.Do(req)\n\n\tselect {\n\tcase receivedHostHeader := <-hostCh:\n\t\ta.Equal(expectedHostHeader, receivedHostHeader)\n\tcase <-time.After(3 * time.Second):\n\t\tt.Fatal(\"timed out waiting for client request\")\n\t}\n}\n\nfunc TestClearsTraceIDHeader(t *testing.T) {\n\tr := require.New(t)\n\ta := assert.New(t)\n\n\theaderCh := make(chan string)\n\trespCh := make(chan bool)\n\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"OK\"))\n\t\theaderCh <- r.Header.Get(\"X-Smokescreen-Trace-ID\")\n\t}))\n\tdefer ts.Close()\n\n\t\/\/ Custom proxy config for the \"remote\" httptest.NewServer\n\tvar logHook logrustest.Hook\n\tconf := NewConfig()\n\tconf.Log.AddHook(&logHook)\n\tconf.ConnTracker = conntrack.NewTracker(conf.IdleThreshold, nil, conf.Log, atomic.Value{})\n\terr := conf.SetAllowAddresses([]string{\"127.0.0.1\"})\n\tr.NoError(err)\n\n\tproxy := BuildProxy(conf)\n\tproxySrv := httptest.NewServer(proxy)\n\n\tclient, err := proxyClient(proxySrv.URL)\n\tr.NoError(err)\n\n\treq, err := http.NewRequest(\"GET\", ts.URL, nil)\n\tr.NoError(err)\n\treq.Header.Set(\"X-Smokescreen-Trace-ID\", \"7fa4587f-7362-4515-ba44-e44490241af0\")\n\n\tgo func() {\n\t\tclient.Do(req)\n\t\trespCh <- true\n\t}()\n\n\tfor i := 0; i < 2; i++ {\n\t\tselect {\n\t\tcase receivedTraceIDCh := <-headerCh:\n\t\t\ta.Empty(receivedTraceIDCh)\n\t\tcase <-time.After(3 * time.Second):\n\t\t\tt.Fatal(\"timed out waiting for client request\")\n\t\tcase <-respCh:\n\t\t\tentry := findCanonicalProxyDecision(logHook.AllEntries())\n\t\t\tr.NotNil(entry)\n\t\t\ta.NotEmpty(entry.Data[\"smokescreen_trace_id\"])\n\t\t}\n\t}\n}\n\nfunc TestShuttingDownValue(t *testing.T) {\n\ta := assert.New(t)\n\n\tconf := NewConfig()\n\tconf.Port = 39381\n\n\tquit := make(chan interface{})\n\tgo StartWithConfig(conf, quit)\n\n\t\/\/ These sleeps are not ideal, but there is a race with checking the\n\t\/\/ ShuttingDown value from these tests. The server has to bootstrap\n\t\/\/ itself with an initial value before it returns false, and has to\n\t\/\/ set the value to true after we send on the quit channel.\n\ttime.Sleep(500 * time.Millisecond)\n\ta.Equal(false, conf.ShuttingDown.Load())\n\n\tquit <- true\n\n\ttime.Sleep(500 * time.Millisecond)\n\ta.Equal(true, conf.ShuttingDown.Load())\n\n}\n\nfunc TestHealthcheck(t *testing.T) {\n\tr := require.New(t)\n\ta := assert.New(t)\n\n\thealthcheckCh := make(chan string)\n\n\ttestHealthcheck := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(\"OK\"))\n\t\thealthcheckCh <- \"OK\"\n\t})\n\n\tconf := NewConfig()\n\n\t\/\/ We set this here so that we can deterministically test the Healthcheck\n\t\/\/ handler. Otherwise we would have to call StartWithConfig() in a goroutine,\n\t\/\/ which creates a race between the test and the listener accepting\n\t\/\/ connections.\n\thandler := HealthcheckMiddleware{\n\t\tProxy:       BuildProxy(conf),\n\t\tHealthcheck: testHealthcheck,\n\t}\n\n\tserver := httptest.NewServer(handler)\n\n\tgo func() {\n\t\tselect {\n\t\tcase healthy := <-healthcheckCh:\n\t\t\ta.Equal(\"OK\", healthy)\n\t\tcase <-time.After(5 * time.Second):\n\t\t\tt.Fatal(\"timed out waiting for client request\")\n\t\t}\n\t}()\n\n\tresp, err := http.Get(fmt.Sprintf(\"%s\/healthcheck\", server.URL))\n\tr.NoError(err)\n\ta.Equal(http.StatusOK, resp.StatusCode)\n}\n\nvar invalidHostCases = []struct {\n\tscheme    string\n\texpectErr bool\n\tproxyType string\n}{\n\t{\"http\", false, \"http\"},\n\t{\"https\", true, \"connect\"},\n}\n\nfunc TestInvalidHost(t *testing.T) {\n\tfor _, testCase := range invalidHostCases {\n\t\tt.Run(testCase.scheme, func(t *testing.T) {\n\t\t\ta := assert.New(t)\n\t\t\tr := require.New(t)\n\n\t\t\tproxySrv, logHook, err := proxyServer()\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer proxySrv.Close()\n\n\t\t\t\/\/ Create a http.Client that uses our proxy\n\t\t\tclient, err := proxyClient(proxySrv.URL)\n\t\t\tr.NoError(err)\n\n\t\t\tresp, err := client.Get(fmt.Sprintf(\"%s:\/\/neversaynever.stripe.com\", testCase.scheme))\n\t\t\tif testCase.expectErr {\n\t\t\t\tr.EqualError(err, \"Get https:\/\/neversaynever.stripe.com: Request Rejected by Proxy\")\n\t\t\t} else {\n\t\t\t\tr.NoError(err)\n\t\t\t\tr.Equal(http.StatusProxyAuthRequired, resp.StatusCode)\n\t\t\t}\n\n\t\t\tentry := findCanonicalProxyDecision(logHook.AllEntries())\n\t\t\tr.NotNil(entry)\n\n\t\t\tif a.Contains(entry.Data, \"allow\") {\n\t\t\t\ta.Equal(true, entry.Data[\"allow\"])\n\t\t\t}\n\t\t\tif a.Contains(entry.Data, \"error\") {\n\t\t\t\ta.Contains(entry.Data[\"error\"], \"no such host\")\n\t\t\t}\n\t\t\tif a.Contains(entry.Data, \"proxy_type\") {\n\t\t\t\ta.Contains(entry.Data[\"proxy_type\"], testCase.proxyType)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc findCanonicalProxyDecision(logs []*logrus.Entry) *logrus.Entry {\n\tfor _, entry := range logs {\n\t\tif entry.Message == LOGLINE_CANONICAL_PROXY_DECISION {\n\t\t\treturn entry\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc proxyServer() (*httptest.Server, *logrustest.Hook, error) {\n\tvar logHook logrustest.Hook\n\n\tconf := NewConfig()\n\tconf.Port = 39381\n\tif err := conf.SetAllowRanges(allowRanges); err != nil {\n\t\treturn nil, nil, err\n\t}\n\tconf.ConnectTimeout = 10 * time.Second\n\tconf.ExitTimeout = 10 * time.Second\n\tconf.AdditionalErrorMessageOnDeny = \"Proxy denied\"\n\tconf.Resolver = &net.Resolver{}\n\tconf.Log.AddHook(&logHook)\n\tconf.ConnTracker = conntrack.NewTracker(conf.IdleThreshold, nil, conf.Log, atomic.Value{})\n\n\tproxy := BuildProxy(conf)\n\treturn httptest.NewServer(proxy), &logHook, nil\n}\n\nfunc proxyClient(proxy string) (*http.Client, error) {\n\tproxyUrl, err := url.Parse(proxy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tProxy:                 http.ProxyURL(proxyUrl),\n\t\t\tTLSHandshakeTimeout:   10 * time.Second,\n\t\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t},\n\t}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package dishes\n\nimport \"math\/rand\"\n\n\/\/ randNumMorsels returns a random number of morsels between 5 and 10\nfunc randNumMorsels() int {\n\treturn 5 + rand.Intn(5)\n}\n\n\/\/ Manager is an actor that manages the internal list of dishes and number of morsels left in each.\ntype Manager struct {\n\t\/\/ The slice of shared dishes. This is the shared state that the Manager actor is managing.\n\tdishes []dish\n\t\/\/ This is the message passing channel.\n\t\/\/\n\t\/\/ The manager receive loop only reads from it (in a 'range Ch') and writes to the 'chan *string' channel values.\n\t\/\/\n\t\/\/ The message sender must only write to Ch and then read from the channel values. Simply close this channel to terminate the receive loop.\n\t\/\/\n\t\/\/ The manager will write a valid dish name back on the 'chan *string' if there are any left, or nil if there are none left.\n\tCh chan chan *string\n}\n\n\/\/ NewManager creates a new Manager actor and starts the receive loop in a background goroutine.\n\/\/\n\/\/ Example usage:\n\/\/\n\/\/  mgr := NewManager()\n\/\/  \/\/ get a dish that has morsels left\n\/\/  dishNameCh := make(chan *string)\n\/\/  mgr.Ch <- dishNameCh\n\/\/  dishName := <-dishNameCh\n\/\/  if dishName == nil {\n\/\/    \/\/ there are no more morsels left of any dish!\n\/\/  } else {\n\/\/    fmt.Println(\"got a morsel of %s!\", *dishName)\n\/\/  }\nfunc NewManager() *Manager {\n\tch := make(chan chan *string)\n\tmgr := &Manager{\n\t\t\/\/ this is the shared state that we're managing\n\t\tdishes: []dish{\n\t\t\t{name: \"chorizo\", numMorsels: randNumMorsels()},\n\t\t\t{name: \"chopitos\", numMorsels: randNumMorsels()},\n\t\t\t{name: \"pimientos de padrón\", numMorsels: randNumMorsels()},\n\t\t\t{name: \"croquetas\", numMorsels: randNumMorsels()},\n\t\t\t{name: \"patatas bravas\", numMorsels: randNumMorsels()},\n\t\t},\n\t\tCh: ch,\n\t}\n\n\tgo func() {\n\t\tfor retCh := range mgr.Ch {\n\t\t\tif len(mgr.dishes) == 0 {\n\t\t\t\tretCh <- nil\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tidx := rand.Intn(len(mgr.dishes))\n\t\t\tdish := &mgr.dishes[idx]\n\t\t\tdish.numMorsels--\n\t\t\tif dish.numMorsels == 0 {\n\t\t\t\t\/\/ remove the dish from the list\n\t\t\t\tmgr.dishes = append(mgr.dishes[0:idx], mgr.dishes[idx+1:]...)\n\t\t\t}\n\t\t\tretCh <- &dish.name\n\t\t}\n\t}()\n\treturn mgr\n}\n\n\/\/ randDishIdx returns a random index into the dishes slice, or -1 if the slice\n\/\/ is empty\nfunc (m *Manager) randDishIdx() int {\n\tif len(m.dishes) == 0 {\n\t\treturn -1\n\t}\n\treturn rand.Intn(len(m.dishes))\n}\n<commit_msg>moving un-exported code to bottom<commit_after>package dishes\n\nimport \"math\/rand\"\n\n\/\/ Manager is an actor that manages the internal list of dishes and number of morsels left in each.\ntype Manager struct {\n\t\/\/ The slice of shared dishes. This is the shared state that the Manager actor is managing.\n\tdishes []dish\n\t\/\/ This is the message passing channel.\n\t\/\/\n\t\/\/ The manager receive loop only reads from it (in a 'range Ch') and writes to the 'chan *string' channel values.\n\t\/\/\n\t\/\/ The message sender must only write to Ch and then read from the channel values. Simply close this channel to terminate the receive loop.\n\t\/\/\n\t\/\/ The manager will write a valid dish name back on the 'chan *string' if there are any left, or nil if there are none left.\n\tCh chan chan *string\n}\n\n\/\/ NewManager creates a new Manager actor and starts the receive loop in a background goroutine.\n\/\/\n\/\/ Example usage:\n\/\/\n\/\/  mgr := NewManager()\n\/\/  \/\/ get a dish that has morsels left\n\/\/  dishNameCh := make(chan *string)\n\/\/  mgr.Ch <- dishNameCh\n\/\/  dishName := <-dishNameCh\n\/\/  if dishName == nil {\n\/\/    \/\/ there are no more morsels left of any dish!\n\/\/  } else {\n\/\/    fmt.Println(\"got a morsel of %s!\", *dishName)\n\/\/  }\nfunc NewManager() *Manager {\n\tch := make(chan chan *string)\n\tmgr := &Manager{\n\t\t\/\/ this is the shared state that we're managing\n\t\tdishes: []dish{\n\t\t\t{name: \"chorizo\", numMorsels: randNumMorsels()},\n\t\t\t{name: \"chopitos\", numMorsels: randNumMorsels()},\n\t\t\t{name: \"pimientos de padrón\", numMorsels: randNumMorsels()},\n\t\t\t{name: \"croquetas\", numMorsels: randNumMorsels()},\n\t\t\t{name: \"patatas bravas\", numMorsels: randNumMorsels()},\n\t\t},\n\t\tCh: ch,\n\t}\n\n\tgo func() {\n\t\tfor retCh := range mgr.Ch {\n\t\t\tif len(mgr.dishes) == 0 {\n\t\t\t\tretCh <- nil\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tidx := rand.Intn(len(mgr.dishes))\n\t\t\tdish := &mgr.dishes[idx]\n\t\t\tdish.numMorsels--\n\t\t\tif dish.numMorsels == 0 {\n\t\t\t\t\/\/ remove the dish from the list\n\t\t\t\tmgr.dishes = append(mgr.dishes[0:idx], mgr.dishes[idx+1:]...)\n\t\t\t}\n\t\t\tretCh <- &dish.name\n\t\t}\n\t}()\n\treturn mgr\n}\n\n\/\/ randDishIdx returns a random index into the dishes slice, or -1 if the slice\n\/\/ is empty\nfunc (m *Manager) randDishIdx() int {\n\tif len(m.dishes) == 0 {\n\t\treturn -1\n\t}\n\treturn rand.Intn(len(m.dishes))\n}\n\ntype dish struct {\n\tname       string\n\tnumMorsels int\n}\n\n\/\/ randNumMorsels returns a random number of morsels between 5 and 10\nfunc randNumMorsels() int {\n\treturn 5 + rand.Intn(5)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nLicensed to the Apache Software Foundation (ASF) under one\nor more contributor license agreements.  See the NOTICE file\ndistributed with this work for additional information\nregarding copyright ownership.  The ASF licenses this file\nto you under the Apache License, Version 2.0 (the\n\"License\"); you may not use this file except in compliance\nwith the License.  You may obtain a copy of the License at\n\n  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the License is distributed on an\n\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, either express or implied.  See the License for the\nspecific language governing permissions and limitations\nunder the License.\n*\/\n\npackage electron\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc testAuthClientServer(t *testing.T, copts []ConnectionOption, sopts []ConnectionOption) (got connectionSettings, err error) {\n\tclient, server := newClientServerOpts(t, copts, sopts)\n\tdefer closeClientServer(client, server)\n\n\tgo func() {\n\t\tfor in := range server.Incoming() {\n\t\t\tswitch in := in.(type) {\n\t\t\tcase *IncomingConnection:\n\t\t\t\tgot = connectionSettings{user: in.User(), virtualHost: in.VirtualHost()}\n\t\t\t}\n\t\t\tin.Accept()\n\t\t}\n\t}()\n\n\terr = client.Sync()\n\treturn\n}\n\nfunc TestAuthAnonymous(t *testing.T) {\n\tfatalIf(t, configureSASL())\n\tgot, err := testAuthClientServer(t,\n\t\t[]ConnectionOption{User(\"fred\"), VirtualHost(\"vhost\"), SASLAllowInsecure(true)},\n\t\t[]ConnectionOption{SASLAllowedMechs(\"ANONYMOUS\"), SASLAllowInsecure(true)})\n\tfatalIf(t, err)\n\terrorIf(t, checkEqual(connectionSettings{user: \"anonymous\", virtualHost: \"vhost\"}, got))\n}\n\nfunc TestAuthPlain(t *testing.T) {\n\tif !SASLExtended() {\n\t\tt.Skip()\n\t}\n\tfatalIf(t, configureSASL())\n\tgot, err := testAuthClientServer(t,\n\t\t[]ConnectionOption{SASLAllowInsecure(true), SASLAllowedMechs(\"PLAIN\"), User(\"fred@proton\"), Password([]byte(\"xxx\"))},\n\t\t[]ConnectionOption{SASLAllowInsecure(true), SASLAllowedMechs(\"PLAIN\")})\n\tfatalIf(t, err)\n\terrorIf(t, checkEqual(connectionSettings{user: \"fred@proton\"}, got))\n}\n\nfunc TestAuthBadPass(t *testing.T) {\n\tif !SASLExtended() {\n\t\tt.Skip()\n\t}\n\tfatalIf(t, configureSASL())\n\t_, err := testAuthClientServer(t,\n\t\t[]ConnectionOption{SASLAllowInsecure(true), SASLAllowedMechs(\"PLAIN\"), User(\"fred@proton\"), Password([]byte(\"yyy\"))},\n\t\t[]ConnectionOption{SASLAllowInsecure(true), SASLAllowedMechs(\"PLAIN\")})\n\tif err == nil {\n\t\tt.Error(\"Expected auth failure for bad pass\")\n\t}\n}\n\nfunc TestAuthBadUser(t *testing.T) {\n\tif !SASLExtended() {\n\t\tt.Skip()\n\t}\n\tfatalIf(t, configureSASL())\n\t_, err := testAuthClientServer(t,\n\t\t[]ConnectionOption{SASLAllowInsecure(true), SASLAllowedMechs(\"PLAIN\"), User(\"foo@bar\"), Password([]byte(\"yyy\"))},\n\t\t[]ConnectionOption{SASLAllowInsecure(true), SASLAllowedMechs(\"PLAIN\")})\n\tif err == nil {\n\t\tt.Error(\"Expected auth failure for bad user\")\n\t}\n}\n\nvar confDir string\nvar confErr error\n\nfunc configureSASL() error {\n\tif confDir != \"\" || confErr != nil {\n\t\treturn confErr\n\t}\n\tconfDir, confErr = ioutil.TempDir(\"\", \"\")\n\tif confErr != nil {\n\t\treturn confErr\n\t}\n\n\tGlobalSASLConfigDir(confDir)\n\tGlobalSASLConfigName(\"test\")\n\tconf := filepath.Join(confDir, \"test.conf\")\n\n\tdb := filepath.Join(confDir, \"proton.sasldb\")\n\tcmd := exec.Command(\"saslpasswd2\", \"-c\", \"-p\", \"-f\", db, \"-u\", \"proton\", \"fred\")\n\tcmd.Stdin = strings.NewReader(\"xxx\") \/\/ Password\n\tif out, err := cmd.CombinedOutput(); err != nil {\n\t\tconfErr = fmt.Errorf(\"saslpasswd2 failed: %s\\n%s\", err, out)\n\t\treturn confErr\n\t}\n\tconfStr := \"sasldb_path: \" + db + \"\\nmech_list: EXTERNAL DIGEST-MD5 SCRAM-SHA-1 CRAM-MD5 PLAIN ANONYMOUS\\n\"\n\tif err := ioutil.WriteFile(conf, []byte(confStr), os.ModePerm); err != nil {\n\t\tconfErr = fmt.Errorf(\"write conf file %s failed: %s\", conf, err)\n\t}\n\treturn confErr\n}\n\nfunc TestMain(m *testing.M) {\n\tstatus := m.Run()\n\tif confDir != \"\" {\n\t\t_ = os.RemoveAll(confDir)\n\t}\n\tos.Exit(status)\n}\n<commit_msg>PROTON-1696\/PROTON-522: Go Anonymous SASL test should work even without Cyrus SASL installed - It was relying on saslpasswd2 even when it didn't need to<commit_after>\/*\nLicensed to the Apache Software Foundation (ASF) under one\nor more contributor license agreements.  See the NOTICE file\ndistributed with this work for additional information\nregarding copyright ownership.  The ASF licenses this file\nto you under the Apache License, Version 2.0 (the\n\"License\"); you may not use this file except in compliance\nwith the License.  You may obtain a copy of the License at\n\n  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the License is distributed on an\n\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, either express or implied.  See the License for the\nspecific language governing permissions and limitations\nunder the License.\n*\/\n\npackage electron\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc testAuthClientServer(t *testing.T, copts []ConnectionOption, sopts []ConnectionOption) (got connectionSettings, err error) {\n\tclient, server := newClientServerOpts(t, copts, sopts)\n\tdefer closeClientServer(client, server)\n\n\tgo func() {\n\t\tfor in := range server.Incoming() {\n\t\t\tswitch in := in.(type) {\n\t\t\tcase *IncomingConnection:\n\t\t\t\tgot = connectionSettings{user: in.User(), virtualHost: in.VirtualHost()}\n\t\t\t}\n\t\t\tin.Accept()\n\t\t}\n\t}()\n\n\terr = client.Sync()\n\treturn\n}\n\nfunc TestAuthAnonymous(t *testing.T) {\n\tconfigureSASL()\n\tgot, err := testAuthClientServer(t,\n\t\t[]ConnectionOption{User(\"fred\"), VirtualHost(\"vhost\"), SASLAllowInsecure(true)},\n\t\t[]ConnectionOption{SASLAllowedMechs(\"ANONYMOUS\"), SASLAllowInsecure(true)})\n\tfatalIf(t, err)\n\terrorIf(t, checkEqual(connectionSettings{user: \"anonymous\", virtualHost: \"vhost\"}, got))\n}\n\nfunc TestAuthPlain(t *testing.T) {\n\tif !SASLExtended() {\n\t\tt.Skip()\n\t}\n\tfatalIf(t, configureSASL())\n\tgot, err := testAuthClientServer(t,\n\t\t[]ConnectionOption{SASLAllowInsecure(true), SASLAllowedMechs(\"PLAIN\"), User(\"fred@proton\"), Password([]byte(\"xxx\"))},\n\t\t[]ConnectionOption{SASLAllowInsecure(true), SASLAllowedMechs(\"PLAIN\")})\n\tfatalIf(t, err)\n\terrorIf(t, checkEqual(connectionSettings{user: \"fred@proton\"}, got))\n}\n\nfunc TestAuthBadPass(t *testing.T) {\n\tif !SASLExtended() {\n\t\tt.Skip()\n\t}\n\tfatalIf(t, configureSASL())\n\t_, err := testAuthClientServer(t,\n\t\t[]ConnectionOption{SASLAllowInsecure(true), SASLAllowedMechs(\"PLAIN\"), User(\"fred@proton\"), Password([]byte(\"yyy\"))},\n\t\t[]ConnectionOption{SASLAllowInsecure(true), SASLAllowedMechs(\"PLAIN\")})\n\tif err == nil {\n\t\tt.Error(\"Expected auth failure for bad pass\")\n\t}\n}\n\nfunc TestAuthBadUser(t *testing.T) {\n\tif !SASLExtended() {\n\t\tt.Skip()\n\t}\n\tfatalIf(t, configureSASL())\n\t_, err := testAuthClientServer(t,\n\t\t[]ConnectionOption{SASLAllowInsecure(true), SASLAllowedMechs(\"PLAIN\"), User(\"foo@bar\"), Password([]byte(\"yyy\"))},\n\t\t[]ConnectionOption{SASLAllowInsecure(true), SASLAllowedMechs(\"PLAIN\")})\n\tif err == nil {\n\t\tt.Error(\"Expected auth failure for bad user\")\n\t}\n}\n\nvar confDir string\nvar confErr error\n\nfunc configureSASL() error {\n\tif confDir != \"\" || confErr != nil {\n\t\treturn confErr\n\t}\n\tconfDir, confErr = ioutil.TempDir(\"\", \"\")\n\tif confErr != nil {\n\t\treturn confErr\n\t}\n\n\tGlobalSASLConfigDir(confDir)\n\tGlobalSASLConfigName(\"test\")\n\tconf := filepath.Join(confDir, \"test.conf\")\n\n\tdb := filepath.Join(confDir, \"proton.sasldb\")\n\tcmd := exec.Command(\"saslpasswd2\", \"-c\", \"-p\", \"-f\", db, \"-u\", \"proton\", \"fred\")\n\tcmd.Stdin = strings.NewReader(\"xxx\") \/\/ Password\n\tif out, err := cmd.CombinedOutput(); err != nil {\n\t\tconfErr = fmt.Errorf(\"saslpasswd2 failed: %s\\n%s\", err, out)\n\t\treturn confErr\n\t}\n\tconfStr := \"sasldb_path: \" + db + \"\\nmech_list: EXTERNAL DIGEST-MD5 SCRAM-SHA-1 CRAM-MD5 PLAIN ANONYMOUS\\n\"\n\tif err := ioutil.WriteFile(conf, []byte(confStr), os.ModePerm); err != nil {\n\t\tconfErr = fmt.Errorf(\"write conf file %s failed: %s\", conf, err)\n\t}\n\treturn confErr\n}\n\nfunc TestMain(m *testing.M) {\n\tstatus := m.Run()\n\tif confDir != \"\" {\n\t\t_ = os.RemoveAll(confDir)\n\t}\n\tos.Exit(status)\n}\n<|endoftext|>"}
{"text":"<commit_before>package etcdhttp\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tcrand \"crypto\/rand\"\n\t\"math\/rand\"\n\n\t\"github.com\/coreos\/etcd\/elog\"\n\tetcdErr \"github.com\/coreos\/etcd\/error\"\n\t\"github.com\/coreos\/etcd\/etcdserver\"\n\t\"github.com\/coreos\/etcd\/etcdserver\/etcdserverpb\"\n\t\"github.com\/coreos\/etcd\/raft\/raftpb\"\n\t\"github.com\/coreos\/etcd\/store\"\n\t\"github.com\/coreos\/etcd\/third_party\/code.google.com\/p\/go.net\/context\"\n)\n\nconst (\n\tkeysPrefix     = \"\/v2\/keys\"\n\tmachinesPrefix = \"\/v2\/machines\"\n)\n\ntype Peers map[int64][]string\n\nfunc (ps Peers) Pick(id int64) string {\n\taddrs := ps[id]\n\tif len(addrs) == 0 {\n\t\treturn \"\"\n\t}\n\treturn addScheme(addrs[rand.Intn(len(addrs))])\n}\n\n\/\/ TODO: improve this when implementing TLS\nfunc addScheme(addr string) string {\n\treturn fmt.Sprintf(\"http:\/\/%s\", addr)\n}\n\n\/\/ Set parses command line sets of names to ips formatted like:\n\/\/ a=1.1.1.1&a=1.1.1.2&b=2.2.2.2\nfunc (ps *Peers) Set(s string) error {\n\tm := make(map[int64][]string)\n\tv, err := url.ParseQuery(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range v {\n\t\tid, err := strconv.ParseInt(k, 0, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tm[id] = v\n\t}\n\t*ps = m\n\treturn nil\n}\n\nfunc (ps *Peers) String() string {\n\tv := url.Values{}\n\tfor k, vv := range *ps {\n\t\tfor i := range vv {\n\t\t\tv.Add(strconv.FormatInt(k, 16), vv[i])\n\t\t}\n\t}\n\treturn v.Encode()\n}\n\nfunc (ps Peers) Ids() []int64 {\n\tvar ids []int64\n\tfor id := range ps {\n\t\tids = append(ids, id)\n\t}\n\treturn ids\n}\n\nvar errClosed = errors.New(\"etcdhttp: client closed connection\")\n\nconst DefaultTimeout = 500 * time.Millisecond\n\nfunc Sender(p Peers) func(msgs []raftpb.Message) {\n\treturn func(msgs []raftpb.Message) {\n\t\tfor _, m := range msgs {\n\t\t\t\/\/ TODO: reuse go routines\n\t\t\t\/\/ limit the number of outgoing connections for the same receiver\n\t\t\tgo send(p, m)\n\t\t}\n\t}\n}\n\nfunc send(p Peers, m raftpb.Message) {\n\t\/\/ TODO (xiangli): reasonable retry logic\n\tfor i := 0; i < 3; i++ {\n\t\turl := p.Pick(m.To)\n\t\tif url == \"\" {\n\t\t\t\/\/ TODO: unknown peer id.. what do we do? I\n\t\t\t\/\/ don't think his should ever happen, need to\n\t\t\t\/\/ look into this further.\n\t\t\tlog.Println(\"etcdhttp: no addr for %d\", m.To)\n\t\t\treturn\n\t\t}\n\n\t\turl += \"\/raft\"\n\n\t\t\/\/ TODO: don't block. we should be able to have 1000s\n\t\t\/\/ of messages out at a time.\n\t\tdata, err := m.Marshal()\n\t\tif err != nil {\n\t\t\tlog.Println(\"etcdhttp: dropping message:\", err)\n\t\t\treturn \/\/ drop bad message\n\t\t}\n\t\tif httpPost(url, data) {\n\t\t\treturn \/\/ success\n\t\t}\n\t\t\/\/ TODO: backoff\n\t}\n}\n\nfunc httpPost(url string, data []byte) bool {\n\t\/\/ TODO: set timeouts\n\tresp, err := http.Post(url, \"application\/protobuf\", bytes.NewBuffer(data))\n\tif err != nil {\n\t\telog.TODO()\n\t\treturn false\n\t}\n\tresp.Body.Close()\n\tif resp.StatusCode != 200 {\n\t\telog.TODO()\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ Handler implements the http.Handler interface and serves etcd client and\n\/\/ raft communication.\ntype Handler struct {\n\tTimeout time.Duration\n\tServer  *etcdserver.Server\n\t\/\/ TODO: dynamic configuration may make this outdated. take care of it.\n\t\/\/ TODO: dynamic configuration may introduce race also.\n\tPeers Peers\n}\n\nfunc (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\t\/\/ TODO: set read\/write timeout?\n\n\ttimeout := h.Timeout\n\tif timeout == 0 {\n\t\ttimeout = DefaultTimeout\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\tswitch {\n\tcase strings.HasPrefix(r.URL.Path, \"\/raft\"):\n\t\th.serveRaft(ctx, w, r)\n\tcase strings.HasPrefix(r.URL.Path, keysPrefix):\n\t\th.serveKeys(ctx, w, r)\n\tcase strings.HasPrefix(r.URL.Path, machinesPrefix):\n\t\th.serveMachines(w, r)\n\tdefault:\n\t\thttp.NotFound(w, r)\n\t}\n}\n\nfunc (h Handler) serveKeys(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\trr, err := parseRequest(r, genId())\n\tif err != nil {\n\t\twriteError(w, err)\n\t\treturn\n\t}\n\n\tresp, err := h.Server.Do(ctx, rr)\n\tif err != nil {\n\t\twriteError(w, err)\n\t\treturn\n\t}\n\n\tvar ev *store.Event\n\tswitch {\n\tcase resp.Event != nil:\n\t\tev = resp.Event\n\tcase resp.Watcher != nil:\n\t\tif ev, err = waitForEvent(ctx, w, resp.Watcher); err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusGatewayTimeout)\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\twriteError(w, errors.New(\"received response with no Event\/Watcher!\"))\n\t\treturn\n\t}\n\n\tif err = writeEvent(w, ev); err != nil {\n\t\t\/\/ Should never be reached\n\t\tlog.Println(\"error writing event: %v\", err)\n\t}\n}\n\n\/\/ serveMachines responds address list in the format '0.0.0.0, 1.1.1.1'.\n\/\/ TODO: rethink the format of machine list because it is not json format.\nfunc (h Handler) serveMachines(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"GET\" && r.Method != \"HEAD\" {\n\t\tallow(w, \"GET\", \"HEAD\")\n\t\treturn\n\t}\n\turls := make([]string, 0)\n\tfor _, addrs := range h.Peers {\n\t\tfor _, addr := range addrs {\n\t\t\turls = append(urls, addScheme(addr))\n\t\t}\n\t}\n\tsort.Strings(urls)\n\tw.Write([]byte(strings.Join(urls, \", \")))\n}\n\nfunc (h Handler) serveRaft(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Println(\"etcdhttp: error reading raft message:\", err)\n\t}\n\tvar m raftpb.Message\n\tif err := m.Unmarshal(b); err != nil {\n\t\tlog.Println(\"etcdhttp: error unmarshaling raft message:\", err)\n\t}\n\tlog.Printf(\"etcdhttp: raft recv message from %#x: %+v\", m.From, m)\n\tif err := h.Server.Node.Step(ctx, m); err != nil {\n\t\tlog.Println(\"etcdhttp: error stepping raft messages:\", err)\n\t}\n}\n\n\/\/ genId generates a random id that is: n < 0 < n.\nfunc genId() int64 {\n\tfor {\n\t\tb := make([]byte, 8)\n\t\tif _, err := io.ReadFull(crand.Reader, b); err != nil {\n\t\t\tpanic(err) \/\/ really bad stuff happened\n\t\t}\n\t\tn := int64(binary.BigEndian.Uint64(b))\n\t\tif n != 0 {\n\t\t\treturn n\n\t\t}\n\t}\n}\n\n\/\/ parseRequest converts a received http.Request to a server Request,\n\/\/ performing validation of supplied fields as appropriate.\n\/\/ If any validation fails, an empty Request and non-nil error is returned.\nfunc parseRequest(r *http.Request, id int64) (etcdserverpb.Request, error) {\n\temptyReq := etcdserverpb.Request{}\n\n\terr := r.ParseForm()\n\tif err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeInvalidForm,\n\t\t\terr.Error(),\n\t\t)\n\t}\n\n\tif !strings.HasPrefix(r.URL.Path, keysPrefix) {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeInvalidForm,\n\t\t\t\"incorrect key prefix\",\n\t\t)\n\t}\n\tp := r.URL.Path[len(keysPrefix):]\n\n\tvar pIdx, wIdx, ttl uint64\n\tif pIdx, err = getUint64(r.Form, \"prevIndex\"); err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeIndexNaN,\n\t\t\tfmt.Sprintf(\"invalid value for prevIndex\"),\n\t\t)\n\t}\n\tif wIdx, err = getUint64(r.Form, \"waitIndex\"); err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeIndexNaN,\n\t\t\tfmt.Sprintf(\"invalid value for waitIndex\"),\n\t\t)\n\t}\n\tif ttl, err = getUint64(r.Form, \"ttl\"); err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeTTLNaN,\n\t\t\t`invalid value for \"ttl\"`,\n\t\t)\n\t}\n\n\tvar rec, sort, wait bool\n\tif rec, err = getBool(r.Form, \"recursive\"); err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeInvalidField,\n\t\t\t`invalid value for \"recursive\"`,\n\t\t)\n\t}\n\tif sort, err = getBool(r.Form, \"sorted\"); err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeInvalidField,\n\t\t\t`invalid value for \"sorted\"`,\n\t\t)\n\t}\n\tif wait, err = getBool(r.Form, \"wait\"); err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeInvalidField,\n\t\t\t`invalid value for \"wait\"`,\n\t\t)\n\t}\n\n\t\/\/ prevExists is nullable, so leave it null if not specified\n\tvar pe *bool\n\tif _, ok := r.Form[\"prevExists\"]; ok {\n\t\tbv, err := getBool(r.Form, \"prevExists\")\n\t\tif err != nil {\n\t\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\t\tetcdErr.EcodeInvalidField,\n\t\t\t\t\"invalid value for prevExists\",\n\t\t\t)\n\t\t}\n\t\tpe = &bv\n\t}\n\n\trr := etcdserverpb.Request{\n\t\tId:         id,\n\t\tMethod:     r.Method,\n\t\tPath:       p,\n\t\tVal:        r.FormValue(\"value\"),\n\t\tPrevValue:  r.FormValue(\"prevValue\"),\n\t\tPrevIndex:  pIdx,\n\t\tPrevExists: pe,\n\t\tRecursive:  rec,\n\t\tSince:      wIdx,\n\t\tSorted:     sort,\n\t\tWait:       wait,\n\t}\n\n\tif pe != nil {\n\t\trr.PrevExists = pe\n\t}\n\n\tif ttl > 0 {\n\t\texpr := time.Duration(ttl) * time.Second\n\t\t\/\/ TODO(jonboulle): use fake clock instead of time module\n\t\t\/\/ https:\/\/github.com\/coreos\/etcd\/issues\/1021\n\t\trr.Expiration = time.Now().Add(expr).UnixNano()\n\t}\n\n\treturn rr, nil\n}\n\n\/\/ getUint64 extracts a uint64 by the given key from a Form. If the key does\n\/\/ not exist in the form, 0 is returned. If the key exists but the value is\n\/\/ badly formed, an error is returned. If multiple values are present only the\n\/\/ first is considered.\nfunc getUint64(form url.Values, key string) (i uint64, err error) {\n\tif vals, ok := form[key]; ok {\n\t\ti, err = strconv.ParseUint(vals[0], 10, 64)\n\t}\n\treturn\n}\n\n\/\/ getBool extracts a bool by the given key from a Form. If the key does not\n\/\/ exist in the form, false is returned. If the key exists but the value is\n\/\/ badly formed, an error is returned. If multiple values are present only the\n\/\/ first is considered.\nfunc getBool(form url.Values, key string) (b bool, err error) {\n\tif vals, ok := form[key]; ok {\n\t\tb, err = strconv.ParseBool(vals[0])\n\t}\n\treturn\n}\n\n\/\/ writeError logs and writes the given Error to the ResponseWriter\n\/\/ If Error is an etcdErr, it is rendered to the ResponseWriter\n\/\/ Otherwise, it is assumed to be an InternalServerError\nfunc writeError(w http.ResponseWriter, err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\tlog.Println(err)\n\tif e, ok := err.(*etcdErr.Error); ok {\n\t\te.Write(w)\n\t} else {\n\t\thttp.Error(w, \"Internal Server Error\", http.StatusInternalServerError)\n\t}\n}\n\n\/\/ writeEvent serializes the given Event and writes the resulting JSON to the\n\/\/ given ResponseWriter\nfunc writeEvent(w http.ResponseWriter, ev *store.Event) error {\n\tif ev == nil {\n\t\treturn errors.New(\"cannot write empty Event!\")\n\t}\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Header().Add(\"X-Etcd-Index\", fmt.Sprint(ev.Index()))\n\n\tif ev.IsCreated() {\n\t\tw.WriteHeader(http.StatusCreated)\n\t}\n\n\treturn json.NewEncoder(w).Encode(ev)\n}\n\n\/\/ waitForEvent waits for a given Watcher to return its associated\n\/\/ event. It returns a non-nil error if the given Context times out\n\/\/ or the given ResponseWriter triggers a CloseNotify.\nfunc waitForEvent(ctx context.Context, w http.ResponseWriter, wa store.Watcher) (*store.Event, error) {\n\t\/\/ TODO(bmizerany): support streaming?\n\tdefer wa.Remove()\n\tvar nch <-chan bool\n\tif x, ok := w.(http.CloseNotifier); ok {\n\t\tnch = x.CloseNotify()\n\t}\n\tselect {\n\tcase ev := <-wa.EventChan():\n\t\treturn ev, nil\n\tcase <-nch:\n\t\telog.TODO()\n\t\treturn nil, errClosed\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\t}\n}\n\n\/\/ allow writes response for the case that Method Not Allowed\nfunc allow(w http.ResponseWriter, m ...string) {\n\tw.Header().Set(\"Allow\", strings.Join(m, \",\"))\n\thttp.Error(w, \"Method Not Allowed\", http.StatusMethodNotAllowed)\n}\n<commit_msg>simplify<commit_after>package etcdhttp\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tcrand \"crypto\/rand\"\n\t\"math\/rand\"\n\n\t\"github.com\/coreos\/etcd\/elog\"\n\tetcdErr \"github.com\/coreos\/etcd\/error\"\n\t\"github.com\/coreos\/etcd\/etcdserver\"\n\t\"github.com\/coreos\/etcd\/etcdserver\/etcdserverpb\"\n\t\"github.com\/coreos\/etcd\/raft\/raftpb\"\n\t\"github.com\/coreos\/etcd\/store\"\n\t\"github.com\/coreos\/etcd\/third_party\/code.google.com\/p\/go.net\/context\"\n)\n\nconst (\n\tkeysPrefix     = \"\/v2\/keys\"\n\tmachinesPrefix = \"\/v2\/machines\"\n)\n\ntype Peers map[int64][]string\n\nfunc (ps Peers) Pick(id int64) string {\n\taddrs := ps[id]\n\tif len(addrs) == 0 {\n\t\treturn \"\"\n\t}\n\treturn addScheme(addrs[rand.Intn(len(addrs))])\n}\n\n\/\/ TODO: improve this when implementing TLS\nfunc addScheme(addr string) string {\n\treturn fmt.Sprintf(\"http:\/\/%s\", addr)\n}\n\n\/\/ Set parses command line sets of names to ips formatted like:\n\/\/ a=1.1.1.1&a=1.1.1.2&b=2.2.2.2\nfunc (ps *Peers) Set(s string) error {\n\tm := make(map[int64][]string)\n\tv, err := url.ParseQuery(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range v {\n\t\tid, err := strconv.ParseInt(k, 0, 64)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tm[id] = v\n\t}\n\t*ps = m\n\treturn nil\n}\n\nfunc (ps *Peers) String() string {\n\tv := url.Values{}\n\tfor k, vv := range *ps {\n\t\tfor i := range vv {\n\t\t\tv.Add(strconv.FormatInt(k, 16), vv[i])\n\t\t}\n\t}\n\treturn v.Encode()\n}\n\nfunc (ps Peers) Ids() []int64 {\n\tvar ids []int64\n\tfor id := range ps {\n\t\tids = append(ids, id)\n\t}\n\treturn ids\n}\n\nvar errClosed = errors.New(\"etcdhttp: client closed connection\")\n\nconst DefaultTimeout = 500 * time.Millisecond\n\nfunc Sender(p Peers) func(msgs []raftpb.Message) {\n\treturn func(msgs []raftpb.Message) {\n\t\tfor _, m := range msgs {\n\t\t\t\/\/ TODO: reuse go routines\n\t\t\t\/\/ limit the number of outgoing connections for the same receiver\n\t\t\tgo send(p, m)\n\t\t}\n\t}\n}\n\nfunc send(p Peers, m raftpb.Message) {\n\t\/\/ TODO (xiangli): reasonable retry logic\n\tfor i := 0; i < 3; i++ {\n\t\turl := p.Pick(m.To)\n\t\tif url == \"\" {\n\t\t\t\/\/ TODO: unknown peer id.. what do we do? I\n\t\t\t\/\/ don't think his should ever happen, need to\n\t\t\t\/\/ look into this further.\n\t\t\tlog.Println(\"etcdhttp: no addr for %d\", m.To)\n\t\t\treturn\n\t\t}\n\n\t\turl += \"\/raft\"\n\n\t\t\/\/ TODO: don't block. we should be able to have 1000s\n\t\t\/\/ of messages out at a time.\n\t\tdata, err := m.Marshal()\n\t\tif err != nil {\n\t\t\tlog.Println(\"etcdhttp: dropping message:\", err)\n\t\t\treturn \/\/ drop bad message\n\t\t}\n\t\tif httpPost(url, data) {\n\t\t\treturn \/\/ success\n\t\t}\n\t\t\/\/ TODO: backoff\n\t}\n}\n\nfunc httpPost(url string, data []byte) bool {\n\t\/\/ TODO: set timeouts\n\tresp, err := http.Post(url, \"application\/protobuf\", bytes.NewBuffer(data))\n\tif err != nil {\n\t\telog.TODO()\n\t\treturn false\n\t}\n\tresp.Body.Close()\n\tif resp.StatusCode != 200 {\n\t\telog.TODO()\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ Handler implements the http.Handler interface and serves etcd client and\n\/\/ raft communication.\ntype Handler struct {\n\tTimeout time.Duration\n\tServer  *etcdserver.Server\n\t\/\/ TODO: dynamic configuration may make this outdated. take care of it.\n\t\/\/ TODO: dynamic configuration may introduce race also.\n\tPeers Peers\n}\n\nfunc (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\t\/\/ TODO: set read\/write timeout?\n\n\ttimeout := h.Timeout\n\tif timeout == 0 {\n\t\ttimeout = DefaultTimeout\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), timeout)\n\tdefer cancel()\n\n\tswitch {\n\tcase strings.HasPrefix(r.URL.Path, \"\/raft\"):\n\t\th.serveRaft(ctx, w, r)\n\tcase strings.HasPrefix(r.URL.Path, keysPrefix):\n\t\th.serveKeys(ctx, w, r)\n\tcase strings.HasPrefix(r.URL.Path, machinesPrefix):\n\t\th.serveMachines(w, r)\n\tdefault:\n\t\thttp.NotFound(w, r)\n\t}\n}\n\nfunc (h Handler) serveKeys(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\trr, err := parseRequest(r, genId())\n\tif err != nil {\n\t\twriteError(w, err)\n\t\treturn\n\t}\n\n\tresp, err := h.Server.Do(ctx, rr)\n\tif err != nil {\n\t\twriteError(w, err)\n\t\treturn\n\t}\n\n\tvar ev *store.Event\n\tswitch {\n\tcase resp.Event != nil:\n\t\tev = resp.Event\n\tcase resp.Watcher != nil:\n\t\tif ev, err = waitForEvent(ctx, w, resp.Watcher); err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusGatewayTimeout)\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\twriteError(w, errors.New(\"received response with no Event\/Watcher!\"))\n\t\treturn\n\t}\n\n\tif err = writeEvent(w, ev); err != nil {\n\t\t\/\/ Should never be reached\n\t\tlog.Println(\"error writing event: %v\", err)\n\t}\n}\n\n\/\/ serveMachines responds address list in the format '0.0.0.0, 1.1.1.1'.\n\/\/ TODO: rethink the format of machine list because it is not json format.\nfunc (h Handler) serveMachines(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"GET\" && r.Method != \"HEAD\" {\n\t\tallow(w, \"GET\", \"HEAD\")\n\t\treturn\n\t}\n\turls := make([]string, 0)\n\tfor _, addrs := range h.Peers {\n\t\tfor _, addr := range addrs {\n\t\t\turls = append(urls, addScheme(addr))\n\t\t}\n\t}\n\tsort.Strings(urls)\n\tw.Write([]byte(strings.Join(urls, \", \")))\n}\n\nfunc (h Handler) serveRaft(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\tb, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Println(\"etcdhttp: error reading raft message:\", err)\n\t}\n\tvar m raftpb.Message\n\tif err := m.Unmarshal(b); err != nil {\n\t\tlog.Println(\"etcdhttp: error unmarshaling raft message:\", err)\n\t}\n\tlog.Printf(\"etcdhttp: raft recv message from %#x: %+v\", m.From, m)\n\tif err := h.Server.Node.Step(ctx, m); err != nil {\n\t\tlog.Println(\"etcdhttp: error stepping raft messages:\", err)\n\t}\n}\n\n\/\/ genId generates a random id that is: n < 0 < n.\nfunc genId() int64 {\n\tfor {\n\t\tb := make([]byte, 8)\n\t\tif _, err := io.ReadFull(crand.Reader, b); err != nil {\n\t\t\tpanic(err) \/\/ really bad stuff happened\n\t\t}\n\t\tn := int64(binary.BigEndian.Uint64(b))\n\t\tif n != 0 {\n\t\t\treturn n\n\t\t}\n\t}\n}\n\n\/\/ parseRequest converts a received http.Request to a server Request,\n\/\/ performing validation of supplied fields as appropriate.\n\/\/ If any validation fails, an empty Request and non-nil error is returned.\nfunc parseRequest(r *http.Request, id int64) (etcdserverpb.Request, error) {\n\temptyReq := etcdserverpb.Request{}\n\n\terr := r.ParseForm()\n\tif err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeInvalidForm,\n\t\t\terr.Error(),\n\t\t)\n\t}\n\n\tif !strings.HasPrefix(r.URL.Path, keysPrefix) {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeInvalidForm,\n\t\t\t\"incorrect key prefix\",\n\t\t)\n\t}\n\tp := r.URL.Path[len(keysPrefix):]\n\n\tvar pIdx, wIdx, ttl uint64\n\tif pIdx, err = getUint64(r.Form, \"prevIndex\"); err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeIndexNaN,\n\t\t\t`invalid value for \"prevIndex\"`,\n\t\t)\n\t}\n\tif wIdx, err = getUint64(r.Form, \"waitIndex\"); err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeIndexNaN,\n\t\t\t`invalid value for \"waitIndex\"`,\n\t\t)\n\t}\n\tif ttl, err = getUint64(r.Form, \"ttl\"); err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeTTLNaN,\n\t\t\t`invalid value for \"ttl\"`,\n\t\t)\n\t}\n\n\tvar rec, sort, wait bool\n\tif rec, err = getBool(r.Form, \"recursive\"); err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeInvalidField,\n\t\t\t`invalid value for \"recursive\"`,\n\t\t)\n\t}\n\tif sort, err = getBool(r.Form, \"sorted\"); err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeInvalidField,\n\t\t\t`invalid value for \"sorted\"`,\n\t\t)\n\t}\n\tif wait, err = getBool(r.Form, \"wait\"); err != nil {\n\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\tetcdErr.EcodeInvalidField,\n\t\t\t`invalid value for \"wait\"`,\n\t\t)\n\t}\n\n\t\/\/ prevExists is nullable, so leave it null if not specified\n\tvar pe *bool\n\tif _, ok := r.Form[\"prevExists\"]; ok {\n\t\tbv, err := getBool(r.Form, \"prevExists\")\n\t\tif err != nil {\n\t\t\treturn emptyReq, etcdErr.NewRequestError(\n\t\t\t\tetcdErr.EcodeInvalidField,\n\t\t\t\t\"invalid value for prevExists\",\n\t\t\t)\n\t\t}\n\t\tpe = &bv\n\t}\n\n\trr := etcdserverpb.Request{\n\t\tId:         id,\n\t\tMethod:     r.Method,\n\t\tPath:       p,\n\t\tVal:        r.FormValue(\"value\"),\n\t\tPrevValue:  r.FormValue(\"prevValue\"),\n\t\tPrevIndex:  pIdx,\n\t\tPrevExists: pe,\n\t\tRecursive:  rec,\n\t\tSince:      wIdx,\n\t\tSorted:     sort,\n\t\tWait:       wait,\n\t}\n\n\tif pe != nil {\n\t\trr.PrevExists = pe\n\t}\n\n\tif ttl > 0 {\n\t\texpr := time.Duration(ttl) * time.Second\n\t\t\/\/ TODO(jonboulle): use fake clock instead of time module\n\t\t\/\/ https:\/\/github.com\/coreos\/etcd\/issues\/1021\n\t\trr.Expiration = time.Now().Add(expr).UnixNano()\n\t}\n\n\treturn rr, nil\n}\n\n\/\/ getUint64 extracts a uint64 by the given key from a Form. If the key does\n\/\/ not exist in the form, 0 is returned. If the key exists but the value is\n\/\/ badly formed, an error is returned. If multiple values are present only the\n\/\/ first is considered.\nfunc getUint64(form url.Values, key string) (i uint64, err error) {\n\tif vals, ok := form[key]; ok {\n\t\ti, err = strconv.ParseUint(vals[0], 10, 64)\n\t}\n\treturn\n}\n\n\/\/ getBool extracts a bool by the given key from a Form. If the key does not\n\/\/ exist in the form, false is returned. If the key exists but the value is\n\/\/ badly formed, an error is returned. If multiple values are present only the\n\/\/ first is considered.\nfunc getBool(form url.Values, key string) (b bool, err error) {\n\tif vals, ok := form[key]; ok {\n\t\tb, err = strconv.ParseBool(vals[0])\n\t}\n\treturn\n}\n\n\/\/ writeError logs and writes the given Error to the ResponseWriter\n\/\/ If Error is an etcdErr, it is rendered to the ResponseWriter\n\/\/ Otherwise, it is assumed to be an InternalServerError\nfunc writeError(w http.ResponseWriter, err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\tlog.Println(err)\n\tif e, ok := err.(*etcdErr.Error); ok {\n\t\te.Write(w)\n\t} else {\n\t\thttp.Error(w, \"Internal Server Error\", http.StatusInternalServerError)\n\t}\n}\n\n\/\/ writeEvent serializes the given Event and writes the resulting JSON to the\n\/\/ given ResponseWriter\nfunc writeEvent(w http.ResponseWriter, ev *store.Event) error {\n\tif ev == nil {\n\t\treturn errors.New(\"cannot write empty Event!\")\n\t}\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Header().Add(\"X-Etcd-Index\", fmt.Sprint(ev.Index()))\n\n\tif ev.IsCreated() {\n\t\tw.WriteHeader(http.StatusCreated)\n\t}\n\n\treturn json.NewEncoder(w).Encode(ev)\n}\n\n\/\/ waitForEvent waits for a given Watcher to return its associated\n\/\/ event. It returns a non-nil error if the given Context times out\n\/\/ or the given ResponseWriter triggers a CloseNotify.\nfunc waitForEvent(ctx context.Context, w http.ResponseWriter, wa store.Watcher) (*store.Event, error) {\n\t\/\/ TODO(bmizerany): support streaming?\n\tdefer wa.Remove()\n\tvar nch <-chan bool\n\tif x, ok := w.(http.CloseNotifier); ok {\n\t\tnch = x.CloseNotify()\n\t}\n\tselect {\n\tcase ev := <-wa.EventChan():\n\t\treturn ev, nil\n\tcase <-nch:\n\t\telog.TODO()\n\t\treturn nil, errClosed\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\t}\n}\n\n\/\/ allow writes response for the case that Method Not Allowed\nfunc allow(w http.ResponseWriter, m ...string) {\n\tw.Header().Set(\"Allow\", strings.Join(m, \",\"))\n\thttp.Error(w, \"Method Not Allowed\", http.StatusMethodNotAllowed)\n}\n<|endoftext|>"}
{"text":"<commit_before>package dalga\n\n\/\/ TODO list\n\/\/ write basic integration tests\n\/\/ handle mysql disconnect\n\/\/ handle rabbitmq disconnect\n\nimport (\n\t\"database\/sql\"\n\t\"flag\"\n\t\"fmt\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"github.com\/streadway\/amqp\"\n\t\"log\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar debugging = flag.Bool(\"d\", false, \"turn on debug messages\")\n\nfunc debug(args ...interface{}) {\n\tif *debugging {\n\t\tlog.Println(args...)\n\t}\n}\n\ntype Dalga struct {\n\tC            *Config\n\tdb           *sql.DB\n\trabbit       *amqp.Connection\n\tchannel      *amqp.Channel\n\tlistener     net.Listener\n\tnewJobs      chan *Job\n\tcanceledJobs chan *Job\n\tquit         chan bool\n}\n\nfunc NewDalga(config *Config) *Dalga {\n\treturn &Dalga{\n\t\tC:            config,\n\t\tnewJobs:      make(chan *Job),\n\t\tcanceledJobs: make(chan *Job),\n\t\tquit:         make(chan bool, 1),\n\t}\n}\n\nfunc (d *Dalga) Run() error {\n\terr := d.connectDB()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = d.connectMQ()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tserver, err := d.makeServer()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo d.publisher()\n\tgo server()\n\n\tdebug(\"Waiting a message from quit channel\")\n\t<-d.quit\n\tdebug(\"Got quit message\")\n\treturn nil\n}\n\nfunc (d *Dalga) Shutdown() error {\n\treturn d.listener.Close()\n}\n\nfunc (d *Dalga) connectDB() error {\n\tvar err error\n\tmy := d.C.MySQL\n\tdsn := my.User + \":\" + my.Password + \"@\" + \"tcp(\" + my.Host + \":\" + my.Port + \")\/\" + my.Db + \"?parseTime=true\"\n\td.db, err = sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"Connected to MySQL\")\n\treturn d.db.Ping()\n}\n\nfunc (d *Dalga) connectMQ() error {\n\tvar err error\n\trabbit := d.C.RabbitMQ\n\turi := \"amqp:\/\/\" + rabbit.User + \":\" + rabbit.Password + \"@\" + rabbit.Host + \":\" + rabbit.Port + rabbit.VHost\n\td.rabbit, err = amqp.Dial(uri)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.channel, err = d.rabbit.Channel()\n\tfmt.Println(\"Connected to RabbitMQ\")\n\treturn err\n}\n\n\/\/ front returns the first job to be run in the queue.\nfunc (d *Dalga) front() (*Job, error) {\n\tvar interval uint\n\tj := Job{}\n\trow := d.db.QueryRow(\"SELECT routing_key, body, `interval`, next_run \" +\n\t\t\"FROM \" + d.C.MySQL.Table + \" \" +\n\t\t\"ORDER BY next_run ASC LIMIT 1\")\n\terr := row.Scan(&j.RoutingKey, &j.Body, &interval, &j.NextRun)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tj.Interval = time.Duration(interval) * time.Second\n\treturn &j, nil\n}\n\n\/\/ publish sends a message to exchange defined in the config and\n\/\/ updates the Job's next run time on the database.\nfunc (d *Dalga) publish(j *Job) error {\n\tdebug(\"publish\", *j)\n\n\t\/\/ Update next run time\n\t_, err := d.db.Exec(\"UPDATE \"+d.C.MySQL.Table+\" \"+\n\t\t\"SET next_run=? \"+\n\t\t\"WHERE routing_key=? AND body=?\",\n\t\ttime.Now().UTC().Add(j.Interval), j.RoutingKey, j.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Send a message to RabbitMQ\n\terr = d.channel.Publish(d.C.RabbitMQ.Exchange, j.RoutingKey, false, false, amqp.Publishing{\n\t\tHeaders: amqp.Table{\n\t\t\t\"interval\":     j.Interval.Seconds(),\n\t\t\t\"published_at\": time.Now().UTC().String(),\n\t\t},\n\t\tContentType:     \"text\/plain\",\n\t\tContentEncoding: \"UTF-8\",\n\t\tBody:            []byte(j.Body),\n\t\tDeliveryMode:    amqp.Persistent,\n\t\tPriority:        0,\n\t\tExpiration:      strconv.FormatUint(uint64(j.Interval.Seconds()), 10) + \"000\",\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ enter puts the job to the waiting queue.\nfunc (d *Dalga) enter(j *Job) error {\n\tinterval := j.Interval.Seconds()\n\t_, err := d.db.Exec(\"INSERT INTO \"+d.C.MySQL.Table+\" \"+\n\t\t\"(routing_key, body, `interval`, next_run) \"+\n\t\t\"VALUES(?, ?, ?, ?) \"+\n\t\t\"ON DUPLICATE KEY UPDATE \"+\n\t\t\"next_run=DATE_ADD(next_run, INTERVAL (? - `interval`) SECOND), \"+\n\t\t\"`interval`=?\",\n\t\tj.RoutingKey, j.Body, interval, j.NextRun, interval, interval)\n\treturn err\n}\n\n\/\/ cancel removes the job from the waiting queue.\nfunc (d *Dalga) cancel(routingKey, body string) error {\n\t_, err := d.db.Exec(\"DELETE FROM \"+d.C.MySQL.Table+\" \"+\n\t\t\"WHERE routing_key=? AND body=?\", routingKey, body)\n\treturn err\n}\n\n\/\/ publisher runs a loop that reads the next Job from the queue and publishes it.\nfunc (d *Dalga) publisher() {\n\tpublish := func(j *Job) {\n\t\terr := d.publish(j)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n\n\tfor {\n\t\tdebug(\"\")\n\n\t\tjob, err := d.front()\n\t\tif err != nil {\n\t\t\tif strings.Contains(err.Error(), \"no rows in result set\") {\n\t\t\t\tdebug(\"No waiting jobs in the queue\")\n\t\t\t\tdebug(\"Waiting wakeup signal\")\n\t\t\t\tjob = <-d.newJobs\n\t\t\t\tdebug(\"Got wakeup signal\")\n\t\t\t} else {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\tCheckNextRun:\n\t\tremaining := job.Remaining()\n\t\tdebug(\"Next job:\", job, \"Remaining:\", remaining)\n\n\t\tnow := time.Now().UTC()\n\t\tif job.NextRun.After(now) {\n\t\t\t\/\/ Wait until the next Job time or\n\t\t\t\/\/ the webserver's \/schedule handler wakes us up\n\t\t\tdebug(\"Sleeping for job:\", remaining)\n\t\t\tselect {\n\t\t\tcase <-time.After(remaining):\n\t\t\t\tdebug(\"Job sleep time finished\")\n\t\t\t\tpublish(job)\n\t\t\tcase newJob := <-d.newJobs:\n\t\t\t\tdebug(\"A new job has been scheduled\")\n\t\t\t\tif newJob.NextRun.Before(job.NextRun) {\n\t\t\t\t\tdebug(\"The new job comes before out current job\")\n\t\t\t\t\tjob = newJob \/\/ Process the new job next\n\t\t\t\t}\n\t\t\t\t\/\/ Continue processing the current job without fetching from database\n\t\t\t\tgoto CheckNextRun\n\t\t\tcase canceledJob := <-d.canceledJobs:\n\t\t\t\tdebug(\"A job has been cancelled\")\n\t\t\t\tif (job.RoutingKey == canceledJob.RoutingKey) && (job.Body == canceledJob.Body) {\n\t\t\t\t\t\/\/ The job we are waiting for has been canceled.\n\t\t\t\t\t\/\/ We need to fetch the next job in the queue.\n\t\t\t\t\tdebug(\"The cancelled job is our current job\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t\/\/ Continue to process our current job\n\t\t\t\tgoto CheckNextRun\n\t\t\t}\n\t\t} else {\n\t\t\tpublish(job)\n\t\t}\n\n\t}\n}\n<commit_msg>new todos<commit_after>package dalga\n\n\/\/ TODO list\n\/\/ use bytes\n\/\/ option for creating table\n\/\/ write basic integration tests\n\/\/ handle mysql disconnect\n\/\/ handle rabbitmq disconnect\n\nimport (\n\t\"database\/sql\"\n\t\"flag\"\n\t\"fmt\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"github.com\/streadway\/amqp\"\n\t\"log\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar debugging = flag.Bool(\"d\", false, \"turn on debug messages\")\n\nfunc debug(args ...interface{}) {\n\tif *debugging {\n\t\tlog.Println(args...)\n\t}\n}\n\ntype Dalga struct {\n\tC            *Config\n\tdb           *sql.DB\n\trabbit       *amqp.Connection\n\tchannel      *amqp.Channel\n\tlistener     net.Listener\n\tnewJobs      chan *Job\n\tcanceledJobs chan *Job\n\tquit         chan bool\n}\n\nfunc NewDalga(config *Config) *Dalga {\n\treturn &Dalga{\n\t\tC:            config,\n\t\tnewJobs:      make(chan *Job),\n\t\tcanceledJobs: make(chan *Job),\n\t\tquit:         make(chan bool, 1),\n\t}\n}\n\nfunc (d *Dalga) Run() error {\n\terr := d.connectDB()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = d.connectMQ()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tserver, err := d.makeServer()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgo d.publisher()\n\tgo server()\n\n\tdebug(\"Waiting a message from quit channel\")\n\t<-d.quit\n\tdebug(\"Got quit message\")\n\treturn nil\n}\n\nfunc (d *Dalga) Shutdown() error {\n\treturn d.listener.Close()\n}\n\nfunc (d *Dalga) connectDB() error {\n\tvar err error\n\tmy := d.C.MySQL\n\tdsn := my.User + \":\" + my.Password + \"@\" + \"tcp(\" + my.Host + \":\" + my.Port + \")\/\" + my.Db + \"?parseTime=true\"\n\td.db, err = sql.Open(\"mysql\", dsn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"Connected to MySQL\")\n\treturn d.db.Ping()\n}\n\nfunc (d *Dalga) connectMQ() error {\n\tvar err error\n\trabbit := d.C.RabbitMQ\n\turi := \"amqp:\/\/\" + rabbit.User + \":\" + rabbit.Password + \"@\" + rabbit.Host + \":\" + rabbit.Port + rabbit.VHost\n\td.rabbit, err = amqp.Dial(uri)\n\tif err != nil {\n\t\treturn err\n\t}\n\td.channel, err = d.rabbit.Channel()\n\tfmt.Println(\"Connected to RabbitMQ\")\n\treturn err\n}\n\n\/\/ front returns the first job to be run in the queue.\nfunc (d *Dalga) front() (*Job, error) {\n\tvar interval uint\n\tj := Job{}\n\trow := d.db.QueryRow(\"SELECT routing_key, body, `interval`, next_run \" +\n\t\t\"FROM \" + d.C.MySQL.Table + \" \" +\n\t\t\"ORDER BY next_run ASC LIMIT 1\")\n\terr := row.Scan(&j.RoutingKey, &j.Body, &interval, &j.NextRun)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tj.Interval = time.Duration(interval) * time.Second\n\treturn &j, nil\n}\n\n\/\/ publish sends a message to exchange defined in the config and\n\/\/ updates the Job's next run time on the database.\nfunc (d *Dalga) publish(j *Job) error {\n\tdebug(\"publish\", *j)\n\n\t\/\/ Update next run time\n\t_, err := d.db.Exec(\"UPDATE \"+d.C.MySQL.Table+\" \"+\n\t\t\"SET next_run=? \"+\n\t\t\"WHERE routing_key=? AND body=?\",\n\t\ttime.Now().UTC().Add(j.Interval), j.RoutingKey, j.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Send a message to RabbitMQ\n\terr = d.channel.Publish(d.C.RabbitMQ.Exchange, j.RoutingKey, false, false, amqp.Publishing{\n\t\tHeaders: amqp.Table{\n\t\t\t\"interval\":     j.Interval.Seconds(),\n\t\t\t\"published_at\": time.Now().UTC().String(),\n\t\t},\n\t\tContentType:     \"text\/plain\",\n\t\tContentEncoding: \"UTF-8\",\n\t\tBody:            []byte(j.Body),\n\t\tDeliveryMode:    amqp.Persistent,\n\t\tPriority:        0,\n\t\tExpiration:      strconv.FormatUint(uint64(j.Interval.Seconds()), 10) + \"000\",\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ enter puts the job to the waiting queue.\nfunc (d *Dalga) enter(j *Job) error {\n\tinterval := j.Interval.Seconds()\n\t_, err := d.db.Exec(\"INSERT INTO \"+d.C.MySQL.Table+\" \"+\n\t\t\"(routing_key, body, `interval`, next_run) \"+\n\t\t\"VALUES(?, ?, ?, ?) \"+\n\t\t\"ON DUPLICATE KEY UPDATE \"+\n\t\t\"next_run=DATE_ADD(next_run, INTERVAL (? - `interval`) SECOND), \"+\n\t\t\"`interval`=?\",\n\t\tj.RoutingKey, j.Body, interval, j.NextRun, interval, interval)\n\treturn err\n}\n\n\/\/ cancel removes the job from the waiting queue.\nfunc (d *Dalga) cancel(routingKey, body string) error {\n\t_, err := d.db.Exec(\"DELETE FROM \"+d.C.MySQL.Table+\" \"+\n\t\t\"WHERE routing_key=? AND body=?\", routingKey, body)\n\treturn err\n}\n\n\/\/ publisher runs a loop that reads the next Job from the queue and publishes it.\nfunc (d *Dalga) publisher() {\n\tpublish := func(j *Job) {\n\t\terr := d.publish(j)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n\n\tfor {\n\t\tdebug(\"\")\n\n\t\tjob, err := d.front()\n\t\tif err != nil {\n\t\t\tif strings.Contains(err.Error(), \"no rows in result set\") {\n\t\t\t\tdebug(\"No waiting jobs in the queue\")\n\t\t\t\tdebug(\"Waiting wakeup signal\")\n\t\t\t\tjob = <-d.newJobs\n\t\t\t\tdebug(\"Got wakeup signal\")\n\t\t\t} else {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\tCheckNextRun:\n\t\tremaining := job.Remaining()\n\t\tdebug(\"Next job:\", job, \"Remaining:\", remaining)\n\n\t\tnow := time.Now().UTC()\n\t\tif job.NextRun.After(now) {\n\t\t\t\/\/ Wait until the next Job time or\n\t\t\t\/\/ the webserver's \/schedule handler wakes us up\n\t\t\tdebug(\"Sleeping for job:\", remaining)\n\t\t\tselect {\n\t\t\tcase <-time.After(remaining):\n\t\t\t\tdebug(\"Job sleep time finished\")\n\t\t\t\tpublish(job)\n\t\t\tcase newJob := <-d.newJobs:\n\t\t\t\tdebug(\"A new job has been scheduled\")\n\t\t\t\tif newJob.NextRun.Before(job.NextRun) {\n\t\t\t\t\tdebug(\"The new job comes before out current job\")\n\t\t\t\t\tjob = newJob \/\/ Process the new job next\n\t\t\t\t}\n\t\t\t\t\/\/ Continue processing the current job without fetching from database\n\t\t\t\tgoto CheckNextRun\n\t\t\tcase canceledJob := <-d.canceledJobs:\n\t\t\t\tdebug(\"A job has been cancelled\")\n\t\t\t\tif (job.RoutingKey == canceledJob.RoutingKey) && (job.Body == canceledJob.Body) {\n\t\t\t\t\t\/\/ The job we are waiting for has been canceled.\n\t\t\t\t\t\/\/ We need to fetch the next job in the queue.\n\t\t\t\t\tdebug(\"The cancelled job is our current job\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t\/\/ Continue to process our current job\n\t\t\t\tgoto CheckNextRun\n\t\t\t}\n\t\t} else {\n\t\t\tpublish(job)\n\t\t}\n\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"code.google.com\/p\/gcfg\"\n\t\"database\/sql\"\n\t\"fmt\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"github.com\/streadway\/amqp\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar (\n\tcfg struct {\n\t\tDB struct {\n\t\t\tDriver string\n\t\t\tDsn    string\n\t\t\tTable  string\n\t\t}\n\t\tRabbitMQ struct {\n\t\t\tUri      string\n\t\t\tExchange string\n\t\t}\n\t\tHTTP struct {\n\t\t\tHost string\n\t\t\tPort string\n\t\t}\n\t}\n\n\tdb     *sql.DB\n\tbroker *amqp.Connection\n)\n\nfunc handleSchedule(w http.ResponseWriter, r *http.Request) {\n\troutingKey, body, interval_s := r.FormValue(\"routing_key\"), r.FormValue(\"body\"), r.FormValue(\"interval\")\n\tlog.Println(\"\/schedule\", routingKey, body)\n\tinterval, err := strconv.ParseInt(interval_s, 10, 64)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tnext_run := time.Now().Add(time.Duration(interval) * time.Second)\n\t_, err = db.Exec(\"INSERT IGNORE INTO \"+cfg.DB.Table+\" \"+\n\t\t\"(routing_key, body, `interval`, next_run, state) \"+\n\t\t\"VALUES(?, ?, ?, ?, 'WAITING')\",\n\t\troutingKey, body, interval, next_run)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc handleCancel(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"\/cancel\")\n}\n\nfunc main() {\n\t\/\/ Read config\n\terr := gcfg.ReadFileInto(&cfg, \"dalga.ini\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Read config: \", cfg)\n\n\t\/\/ Connect to database\n\tdb, err = sql.Open(cfg.DB.Driver, cfg.DB.Dsn)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Connected to DB\")\n\n\t\/\/ Connect to RabbitMQ\n\t_, err = amqp.Dial(cfg.RabbitMQ.Uri)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Connected to RabbitMQ\")\n\n\t\/\/ Start HTTP server\n\taddr := cfg.HTTP.Host + \":\" + cfg.HTTP.Port\n\thttp.HandleFunc(\"\/schedule\", handleSchedule)\n\thttp.HandleFunc(\"\/cancel\", handleSchedule)\n\thttp.ListenAndServe(addr, nil)\n}\n<commit_msg>cancel<commit_after>package main\n\nimport (\n\t\"code.google.com\/p\/gcfg\"\n\t\"database\/sql\"\n\t\"fmt\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"github.com\/streadway\/amqp\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\nvar (\n\tcfg struct {\n\t\tDB struct {\n\t\t\tDriver string\n\t\t\tDsn    string\n\t\t\tTable  string\n\t\t}\n\t\tRabbitMQ struct {\n\t\t\tUri      string\n\t\t\tExchange string\n\t\t}\n\t\tHTTP struct {\n\t\t\tHost string\n\t\t\tPort string\n\t\t}\n\t}\n\n\tdb     *sql.DB\n\tbroker *amqp.Connection\n)\n\nfunc handleSchedule(w http.ResponseWriter, r *http.Request) {\n\troutingKey, body, interval_s := r.FormValue(\"routing_key\"), r.FormValue(\"body\"), r.FormValue(\"interval\")\n\tlog.Println(\"\/schedule\", routingKey, body)\n\n\tinterval, err := strconv.ParseInt(interval_s, 10, 64)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tnext_run := time.Now().Add(time.Duration(interval) * time.Second)\n\t_, err = db.Exec(\"INSERT IGNORE INTO \"+cfg.DB.Table+\" \"+\n\t\t\"(routing_key, body, `interval`, next_run, state) \"+\n\t\t\"VALUES(?, ?, ?, ?, 'WAITING')\",\n\t\troutingKey, body, interval, next_run)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc handleCancel(w http.ResponseWriter, r *http.Request) {\n\troutingKey, body := r.FormValue(\"routing_key\"), r.FormValue(\"body\")\n\tfmt.Println(\"\/cancel\", routingKey, body)\n\n\t_, err := db.Exec(\"DELETE FROM \"+cfg.DB.Table+\" \"+\n\t\t\"WHERE routing_key=? AND body=?\", routingKey, body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc main() {\n\t\/\/ Read config\n\terr := gcfg.ReadFileInto(&cfg, \"dalga.ini\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Read config: \", cfg)\n\n\t\/\/ Connect to database\n\tdb, err = sql.Open(cfg.DB.Driver, cfg.DB.Dsn)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\terr = db.Ping()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Connected to DB\")\n\n\t\/\/ Connect to RabbitMQ\n\t_, err = amqp.Dial(cfg.RabbitMQ.Uri)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Connected to RabbitMQ\")\n\n\t\/\/ Start HTTP server\n\taddr := cfg.HTTP.Host + \":\" + cfg.HTTP.Port\n\thttp.HandleFunc(\"\/schedule\", handleSchedule)\n\thttp.HandleFunc(\"\/cancel\", handleCancel)\n\thttp.ListenAndServe(addr, nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package finalize\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry\/libbuildpack\"\n\t\"github.com\/kr\/text\"\n)\n\ntype Stager interface {\n\tBuildDir() string\n\tDepsIdx() string\n\tDepDir() string\n}\n\ntype Finalizer struct {\n\tStager           Stager\n\tVersions         Versions\n\tLog              *libbuildpack.Logger\n\tGem12Factor      bool\n\tGemStaticAssets  bool\n\tGemStdoutLogging bool\n\tRailsVersion     int\n}\n\nfunc Run(f *Finalizer) error {\n\tf.Log.BeginStep(\"Finalizing Ruby\")\n\n\tif err := f.Setup(); err != nil {\n\t\tf.Log.Error(\"Error determining versions: %v\", err)\n\t\treturn err\n\t}\n\n\tif err := f.RestoreGemfileLock(); err != nil {\n\t\tf.Log.Error(\"Error copying Gemfile.lock to app: %v\", err)\n\t\treturn err\n\t}\n\n\tif err := f.InstallPlugins(); err != nil {\n\t\tf.Log.Error(\"Error installing plugins: %v\", err)\n\t\treturn err\n\t}\n\n\tif err := f.WriteDatabaseYml(); err != nil {\n\t\tf.Log.Error(\"Error writing database.yml: %v\", err)\n\t\treturn err\n\t}\n\n\tif err := f.PrecompileAssets(); err != nil {\n\t\tf.Log.Error(\"Error precompiling assets: %v\", err)\n\t\treturn err\n\t}\n\n\tf.BestPracticeWarnings()\n\n\tif err := f.DeleteVendorBundle(); err != nil {\n\t\tf.Log.Error(\"Error deleting vendor\/bundle: %v\", err)\n\t\treturn err\n\t}\n\n\tif err := f.CopyToAppBin(); err != nil {\n\t\tf.Log.Error(\"Error creating files in bin: %v\", err)\n\t\treturn err\n\t}\n\n\tdata, err := f.GenerateReleaseYaml()\n\tif err != nil {\n\t\tf.Log.Error(\"Error generating release YAML: %v\", err)\n\t\treturn err\n\t}\n\treleasePath := filepath.Join(f.Stager.BuildDir(), \"tmp\", \"ruby-buildpack-release-step.yml\")\n\tlibbuildpack.NewYAML().Write(releasePath, data)\n\n\treturn nil\n}\n\nfunc (f *Finalizer) Setup() error {\n\tvar err error\n\n\tf.Gem12Factor, err = f.Versions.HasGem(\"rails_12factor\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.GemStdoutLogging, err = f.Versions.HasGem(\"rails_stdout_logging\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.GemStaticAssets, err = f.Versions.HasGem(\"rails_serve_static_assets\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.RailsVersion, err = f.Versions.GemMajorVersion(\"rails\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (f *Finalizer) RestoreGemfileLock() error {\n\tsource := filepath.Join(f.Stager.DepDir(), \"Gemfile.lock\")\n\tf.Log.Debug(\"RestoreGemfileLock; %s\", source)\n\tif exists, err := libbuildpack.FileExists(source); err != nil {\n\t\treturn err\n\t} else if exists {\n\t\tgemfile := \"Gemfile\"\n\t\tif os.Getenv(\"BUNDLE_GEMFILE\") != \"\" {\n\t\t\tgemfile = os.Getenv(\"BUNDLE_GEMFILE\")\n\t\t}\n\t\ttarget := filepath.Join(f.Stager.BuildDir(), gemfile) + \".lock\"\n\t\tf.Log.Debug(\"RestoreGemfileLock; exists, copy to %s\", target)\n\t\treturn os.Rename(source, target)\n\t}\n\treturn nil\n}\n\nfunc (f *Finalizer) WriteDatabaseYml() error {\n\tif exists, err := libbuildpack.FileExists(filepath.Join(f.Stager.BuildDir(), \"config\")); err != nil {\n\t\treturn err\n\t} else if !exists {\n\t\treturn nil\n\t}\n\tif rails41Plus, err := f.Versions.HasGemVersion(\"activerecord\", \">=4.1.0.beta\"); err != nil {\n\t\treturn err\n\t} else if rails41Plus {\n\t\treturn nil\n\t}\n\n\tf.Log.BeginStep(\"Writing config\/database.yml to read from DATABASE_URL\")\n\tif err := ioutil.WriteFile(filepath.Join(f.Stager.BuildDir(), \"config\", \"database.yml\"), []byte(config_database_yml), 0644); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (f *Finalizer) PrecompileAssets() error {\n\tcmd := exec.Command(\"bundle\", \"exec\", \"rake\", \"-n\", \"assets:precompile\")\n\tcmd.Dir = f.Stager.BuildDir()\n\tif err := cmd.Run(); err != nil {\n\t\treturn nil\n\t}\n\n\tf.Log.BeginStep(\"Precompiling assets\")\n\tstartTime := time.Now()\n\tcmd = exec.Command(\"bundle\", \"exec\", \"rake\", \"assets:precompile\")\n\tcmd.Dir = f.Stager.BuildDir()\n\tcmd.Stdout = text.NewIndentWriter(os.Stdout, []byte(\"       \"))\n\tcmd.Stderr = text.NewIndentWriter(os.Stderr, []byte(\"       \"))\n\terr := cmd.Run()\n\n\tf.Log.Info(\"Asset precompilation completed (%v)\", time.Since(startTime))\n\n\tif f.RailsVersion >= 4 && err == nil {\n\t\tf.Log.Info(\"Cleaning assets\")\n\t\tcmd = exec.Command(\"bundle\", \"exec\", \"rake\", \"assets:clean\")\n\t\tcmd.Dir = f.Stager.BuildDir()\n\t\tcmd.Stdout = text.NewIndentWriter(os.Stdout, []byte(\"       \"))\n\t\tcmd.Stderr = text.NewIndentWriter(os.Stderr, []byte(\"       \"))\n\t\terr = cmd.Run()\n\t}\n\n\treturn err\n}\n\nfunc (f *Finalizer) InstallPlugins() error {\n\tif f.Gem12Factor {\n\t\treturn nil\n\t}\n\n\tif f.RailsVersion == 4 {\n\t\tif !(f.GemStdoutLogging && f.GemStaticAssets) {\n\t\t\tf.Log.Protip(\"Include 'rails_12factor' gem to enable all platform features\", \"https:\/\/devcenter.heroku.com\/articles\/rails-integration-gems\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tif f.RailsVersion == 2 || f.RailsVersion == 3 {\n\t\tif err := f.installPluginStdoutLogger(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := f.installPluginServeStaticAssets(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (f *Finalizer) installPluginStdoutLogger() error {\n\tif f.GemStdoutLogging {\n\t\treturn nil\n\t}\n\n\tf.Log.BeginStep(\"Injecting plugin 'rails_log_stdout'\")\n\n\tcode := `\nbegin\n  STDOUT.sync = true\n  def Rails.cloudfoundry_stdout_logger\n    logger = Logger.new(STDOUT)\n    logger = ActiveSupport::TaggedLogging.new(logger) if defined?(ActiveSupport::TaggedLogging)\n    level = ENV['LOG_LEVEL'].to_s.upcase\n    level = 'INFO' unless %w[DEBUG INFO WARN ERROR FATAL UNKNOWN].include?(level)\n    logger.level = Logger.const_get(level)\n    logger\n  end\n  Rails.logger = Rails.application.config.logger = Rails.cloudfoundry_stdout_logger\nrescue Exception => ex\n  puts %Q{WARNING: Exception during rails_log_stdout init: #{ex.message}}\nend\n`\n\n\tif err := os.MkdirAll(filepath.Join(f.Stager.BuildDir(), \"vendor\", \"plugins\", \"rails_log_stdout\"), 0755); err != nil {\n\t\treturn fmt.Errorf(\"Error creating rails_log_stdout plugin directory: %v\", err)\n\t}\n\tif err := ioutil.WriteFile(filepath.Join(f.Stager.BuildDir(), \"vendor\", \"plugins\", \"rails_log_stdout\", \"init.rb\"), []byte(code), 0644); err != nil {\n\t\treturn fmt.Errorf(\"Error writing rails_log_stdout plugin file: %v\", err)\n\t}\n\treturn nil\n}\n\nfunc (f *Finalizer) installPluginServeStaticAssets() error {\n\tif f.GemStaticAssets {\n\t\treturn nil\n\t}\n\n\tf.Log.BeginStep(\"Injecting plugin 'rails3_serve_static_assets'\")\n\n\tcode := \"Rails.application.class.config.serve_static_assets = true\\n\"\n\n\tif err := os.MkdirAll(filepath.Join(f.Stager.BuildDir(), \"vendor\", \"plugins\", \"rails3_serve_static_assets\"), 0755); err != nil {\n\t\treturn fmt.Errorf(\"Error creating rails3_serve_static_assets plugin directory: %v\", err)\n\t}\n\tif err := ioutil.WriteFile(filepath.Join(f.Stager.BuildDir(), \"vendor\", \"plugins\", \"rails3_serve_static_assets\", \"init.rb\"), []byte(code), 0644); err != nil {\n\t\treturn fmt.Errorf(\"Error writing rails3_serve_static_assets plugin file: %v\", err)\n\t}\n\treturn nil\n}\n\nfunc (f *Finalizer) BestPracticeWarnings() {\n\tif os.Getenv(\"RAILS_ENV\") != \"production\" {\n\t\tf.Log.Warning(\"You are deploying to a non-production environment: %s\", os.Getenv(\"RAILS_ENV\"))\n\t}\n}\n\nfunc (f *Finalizer) DeleteVendorBundle() error {\n\tif exists, err := libbuildpack.FileExists(filepath.Join(f.Stager.BuildDir(), \"vendor\", \"bundle\")); err != nil {\n\t\treturn err\n\t} else if exists {\n\t\tf.Log.Warning(\"Removing `vendor\/bundle`.\\nChecking in `vendor\/bundle` is not supported. Please remove this directory and add it to your .gitignore. To vendor your gems with Bundler, use `bundle pack` instead.\")\n\t\treturn os.RemoveAll(filepath.Join(f.Stager.BuildDir(), \"vendor\", \"bundle\"))\n\t}\n\n\treturn nil\n}\n\nfunc (f *Finalizer) CopyToAppBin() error {\n\tf.Log.BeginStep(\"Copy binaries to app\/bin directory\")\n\n\tbinDir := filepath.Join(f.Stager.BuildDir(), \"bin\")\n\tif err := os.MkdirAll(binDir, 0755); err != nil {\n\t\treturn fmt.Errorf(\"Could not create \/app\/bin directory: %v\", err)\n\t}\n\n\tfiles, err := ioutil.ReadDir(filepath.Join(f.Stager.DepDir(), \"binstubs\"))\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"Could not read dep\/binstubs directory: %v\", err)\n\t\t}\n\t\tfiles = []os.FileInfo{}\n\t}\n\tfor _, file := range files {\n\t\tsource := filepath.Join(f.Stager.DepDir(), \"binstubs\", file.Name())\n\t\ttarget := filepath.Join(binDir, file.Name())\n\t\tif exists, err := libbuildpack.FileExists(target); err != nil {\n\t\t\treturn fmt.Errorf(\"Checking existence: %v\", err)\n\t\t} else if !exists {\n\t\t\tif err := libbuildpack.CopyFile(source, target); err != nil {\n\t\t\t\treturn fmt.Errorf(\"CopyFile: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tfiles, err = ioutil.ReadDir(filepath.Join(f.Stager.DepDir(), \"bin\"))\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"Could not read dep\/bin directory: %v\", err)\n\t\t}\n\t\tfiles = []os.FileInfo{}\n\t}\n\tfor _, file := range files {\n\t\ttarget := filepath.Join(binDir, file.Name())\n\t\tif exists, err := libbuildpack.FileExists(target); err != nil {\n\t\t\treturn fmt.Errorf(\"Checking existence: %v\", err)\n\t\t} else if !exists {\n\t\t\tcontents := fmt.Sprintf(\"#!\/bin\/bash\\nexec $DEPS_DIR\/%s\/bin\/%s \\\"$@\\\"\\n\", f.Stager.DepsIdx(), file.Name())\n\t\t\tif err := ioutil.WriteFile(target, []byte(contents), 0755); err != nil {\n\t\t\t\treturn fmt.Errorf(\"WriteFile: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Limit environment for assets:precompile [#149435225]<commit_after>package finalize\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/cloudfoundry\/libbuildpack\"\n\t\"github.com\/kr\/text\"\n)\n\ntype Stager interface {\n\tBuildDir() string\n\tDepsIdx() string\n\tDepDir() string\n}\n\ntype Finalizer struct {\n\tStager           Stager\n\tVersions         Versions\n\tLog              *libbuildpack.Logger\n\tGem12Factor      bool\n\tGemStaticAssets  bool\n\tGemStdoutLogging bool\n\tRailsVersion     int\n}\n\nfunc Run(f *Finalizer) error {\n\tf.Log.BeginStep(\"Finalizing Ruby\")\n\n\tif err := f.Setup(); err != nil {\n\t\tf.Log.Error(\"Error determining versions: %v\", err)\n\t\treturn err\n\t}\n\n\tif err := f.RestoreGemfileLock(); err != nil {\n\t\tf.Log.Error(\"Error copying Gemfile.lock to app: %v\", err)\n\t\treturn err\n\t}\n\n\tif err := f.InstallPlugins(); err != nil {\n\t\tf.Log.Error(\"Error installing plugins: %v\", err)\n\t\treturn err\n\t}\n\n\tif err := f.WriteDatabaseYml(); err != nil {\n\t\tf.Log.Error(\"Error writing database.yml: %v\", err)\n\t\treturn err\n\t}\n\n\tif err := f.PrecompileAssets(); err != nil {\n\t\tf.Log.Error(\"Error precompiling assets: %v\", err)\n\t\treturn err\n\t}\n\n\tf.BestPracticeWarnings()\n\n\tif err := f.DeleteVendorBundle(); err != nil {\n\t\tf.Log.Error(\"Error deleting vendor\/bundle: %v\", err)\n\t\treturn err\n\t}\n\n\tif err := f.CopyToAppBin(); err != nil {\n\t\tf.Log.Error(\"Error creating files in bin: %v\", err)\n\t\treturn err\n\t}\n\n\tdata, err := f.GenerateReleaseYaml()\n\tif err != nil {\n\t\tf.Log.Error(\"Error generating release YAML: %v\", err)\n\t\treturn err\n\t}\n\treleasePath := filepath.Join(f.Stager.BuildDir(), \"tmp\", \"ruby-buildpack-release-step.yml\")\n\tlibbuildpack.NewYAML().Write(releasePath, data)\n\n\treturn nil\n}\n\nfunc (f *Finalizer) Setup() error {\n\tvar err error\n\n\tf.Gem12Factor, err = f.Versions.HasGem(\"rails_12factor\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.GemStdoutLogging, err = f.Versions.HasGem(\"rails_stdout_logging\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.GemStaticAssets, err = f.Versions.HasGem(\"rails_serve_static_assets\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.RailsVersion, err = f.Versions.GemMajorVersion(\"rails\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (f *Finalizer) RestoreGemfileLock() error {\n\tsource := filepath.Join(f.Stager.DepDir(), \"Gemfile.lock\")\n\tf.Log.Debug(\"RestoreGemfileLock; %s\", source)\n\tif exists, err := libbuildpack.FileExists(source); err != nil {\n\t\treturn err\n\t} else if exists {\n\t\tgemfile := \"Gemfile\"\n\t\tif os.Getenv(\"BUNDLE_GEMFILE\") != \"\" {\n\t\t\tgemfile = os.Getenv(\"BUNDLE_GEMFILE\")\n\t\t}\n\t\ttarget := filepath.Join(f.Stager.BuildDir(), gemfile) + \".lock\"\n\t\tf.Log.Debug(\"RestoreGemfileLock; exists, copy to %s\", target)\n\t\treturn os.Rename(source, target)\n\t}\n\treturn nil\n}\n\nfunc (f *Finalizer) WriteDatabaseYml() error {\n\tif exists, err := libbuildpack.FileExists(filepath.Join(f.Stager.BuildDir(), \"config\")); err != nil {\n\t\treturn err\n\t} else if !exists {\n\t\treturn nil\n\t}\n\tif rails41Plus, err := f.Versions.HasGemVersion(\"activerecord\", \">=4.1.0.beta\"); err != nil {\n\t\treturn err\n\t} else if rails41Plus {\n\t\treturn nil\n\t}\n\n\tf.Log.BeginStep(\"Writing config\/database.yml to read from DATABASE_URL\")\n\tif err := ioutil.WriteFile(filepath.Join(f.Stager.BuildDir(), \"config\", \"database.yml\"), []byte(config_database_yml), 0644); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (f *Finalizer) PrecompileAssets() error {\n\tcmd := exec.Command(\"bundle\", \"exec\", \"rake\", \"-n\", \"assets:precompile\")\n\tcmd.Dir = f.Stager.BuildDir()\n\tif err := cmd.Run(); err != nil {\n\t\treturn nil\n\t}\n\n\tenv := []string{\n\t\tfmt.Sprintf(\"BUNDLE_BIN=%s\", os.Getenv(\"BUNDLE_BIN\")),\n\t\tfmt.Sprintf(\"BUNDLE_CONFIG=%s\", os.Getenv(\"BUNDLE_CONFIG\")),\n\t\tfmt.Sprintf(\"BUNDLE_PATH=%s\", os.Getenv(\"BUNDLE_PATH\")),\n\t\tfmt.Sprintf(\"BUNDLE_WITHOUT=%s\", os.Getenv(\"BUNDLE_WITHOUT\")),\n\t\tfmt.Sprintf(\"GEM_HOME=%s\", os.Getenv(\"GEM_HOME\")),\n\t\tfmt.Sprintf(\"GEM_PATH=%s\", os.Getenv(\"GEM_PATH\")),\n\t\tfmt.Sprintf(\"PATH=%s\", os.Getenv(\"PATH\")),\n\t}\n\n\tf.Log.BeginStep(\"Precompiling assets\")\n\tstartTime := time.Now()\n\tcmd = exec.Command(\"bundle\", \"exec\", \"rake\", \"assets:precompile\")\n\tcmd.Dir = f.Stager.BuildDir()\n\tcmd.Stdout = text.NewIndentWriter(os.Stdout, []byte(\"       \"))\n\tcmd.Stderr = text.NewIndentWriter(os.Stderr, []byte(\"       \"))\n\tcmd.Env = env\n\terr := cmd.Run()\n\n\tf.Log.Info(\"Asset precompilation completed (%v)\", time.Since(startTime))\n\n\tif f.RailsVersion >= 4 && err == nil {\n\t\tf.Log.Info(\"Cleaning assets\")\n\t\tcmd = exec.Command(\"bundle\", \"exec\", \"rake\", \"assets:clean\")\n\t\tcmd.Dir = f.Stager.BuildDir()\n\t\tcmd.Stdout = text.NewIndentWriter(os.Stdout, []byte(\"       \"))\n\t\tcmd.Stderr = text.NewIndentWriter(os.Stderr, []byte(\"       \"))\n\t\tcmd.Env = env\n\t\terr = cmd.Run()\n\t}\n\n\treturn err\n}\n\nfunc (f *Finalizer) InstallPlugins() error {\n\tif f.Gem12Factor {\n\t\treturn nil\n\t}\n\n\tif f.RailsVersion == 4 {\n\t\tif !(f.GemStdoutLogging && f.GemStaticAssets) {\n\t\t\tf.Log.Protip(\"Include 'rails_12factor' gem to enable all platform features\", \"https:\/\/devcenter.heroku.com\/articles\/rails-integration-gems\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tif f.RailsVersion == 2 || f.RailsVersion == 3 {\n\t\tif err := f.installPluginStdoutLogger(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := f.installPluginServeStaticAssets(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (f *Finalizer) installPluginStdoutLogger() error {\n\tif f.GemStdoutLogging {\n\t\treturn nil\n\t}\n\n\tf.Log.BeginStep(\"Injecting plugin 'rails_log_stdout'\")\n\n\tcode := `\nbegin\n  STDOUT.sync = true\n  def Rails.cloudfoundry_stdout_logger\n    logger = Logger.new(STDOUT)\n    logger = ActiveSupport::TaggedLogging.new(logger) if defined?(ActiveSupport::TaggedLogging)\n    level = ENV['LOG_LEVEL'].to_s.upcase\n    level = 'INFO' unless %w[DEBUG INFO WARN ERROR FATAL UNKNOWN].include?(level)\n    logger.level = Logger.const_get(level)\n    logger\n  end\n  Rails.logger = Rails.application.config.logger = Rails.cloudfoundry_stdout_logger\nrescue Exception => ex\n  puts %Q{WARNING: Exception during rails_log_stdout init: #{ex.message}}\nend\n`\n\n\tif err := os.MkdirAll(filepath.Join(f.Stager.BuildDir(), \"vendor\", \"plugins\", \"rails_log_stdout\"), 0755); err != nil {\n\t\treturn fmt.Errorf(\"Error creating rails_log_stdout plugin directory: %v\", err)\n\t}\n\tif err := ioutil.WriteFile(filepath.Join(f.Stager.BuildDir(), \"vendor\", \"plugins\", \"rails_log_stdout\", \"init.rb\"), []byte(code), 0644); err != nil {\n\t\treturn fmt.Errorf(\"Error writing rails_log_stdout plugin file: %v\", err)\n\t}\n\treturn nil\n}\n\nfunc (f *Finalizer) installPluginServeStaticAssets() error {\n\tif f.GemStaticAssets {\n\t\treturn nil\n\t}\n\n\tf.Log.BeginStep(\"Injecting plugin 'rails3_serve_static_assets'\")\n\n\tcode := \"Rails.application.class.config.serve_static_assets = true\\n\"\n\n\tif err := os.MkdirAll(filepath.Join(f.Stager.BuildDir(), \"vendor\", \"plugins\", \"rails3_serve_static_assets\"), 0755); err != nil {\n\t\treturn fmt.Errorf(\"Error creating rails3_serve_static_assets plugin directory: %v\", err)\n\t}\n\tif err := ioutil.WriteFile(filepath.Join(f.Stager.BuildDir(), \"vendor\", \"plugins\", \"rails3_serve_static_assets\", \"init.rb\"), []byte(code), 0644); err != nil {\n\t\treturn fmt.Errorf(\"Error writing rails3_serve_static_assets plugin file: %v\", err)\n\t}\n\treturn nil\n}\n\nfunc (f *Finalizer) BestPracticeWarnings() {\n\tif os.Getenv(\"RAILS_ENV\") != \"production\" {\n\t\tf.Log.Warning(\"You are deploying to a non-production environment: %s\", os.Getenv(\"RAILS_ENV\"))\n\t}\n}\n\nfunc (f *Finalizer) DeleteVendorBundle() error {\n\tif exists, err := libbuildpack.FileExists(filepath.Join(f.Stager.BuildDir(), \"vendor\", \"bundle\")); err != nil {\n\t\treturn err\n\t} else if exists {\n\t\tf.Log.Warning(\"Removing `vendor\/bundle`.\\nChecking in `vendor\/bundle` is not supported. Please remove this directory and add it to your .gitignore. To vendor your gems with Bundler, use `bundle pack` instead.\")\n\t\treturn os.RemoveAll(filepath.Join(f.Stager.BuildDir(), \"vendor\", \"bundle\"))\n\t}\n\n\treturn nil\n}\n\nfunc (f *Finalizer) CopyToAppBin() error {\n\tf.Log.BeginStep(\"Copy binaries to app\/bin directory\")\n\n\tbinDir := filepath.Join(f.Stager.BuildDir(), \"bin\")\n\tif err := os.MkdirAll(binDir, 0755); err != nil {\n\t\treturn fmt.Errorf(\"Could not create \/app\/bin directory: %v\", err)\n\t}\n\n\tfiles, err := ioutil.ReadDir(filepath.Join(f.Stager.DepDir(), \"binstubs\"))\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"Could not read dep\/binstubs directory: %v\", err)\n\t\t}\n\t\tfiles = []os.FileInfo{}\n\t}\n\tfor _, file := range files {\n\t\tsource := filepath.Join(f.Stager.DepDir(), \"binstubs\", file.Name())\n\t\ttarget := filepath.Join(binDir, file.Name())\n\t\tif exists, err := libbuildpack.FileExists(target); err != nil {\n\t\t\treturn fmt.Errorf(\"Checking existence: %v\", err)\n\t\t} else if !exists {\n\t\t\tif err := libbuildpack.CopyFile(source, target); err != nil {\n\t\t\t\treturn fmt.Errorf(\"CopyFile: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tfiles, err = ioutil.ReadDir(filepath.Join(f.Stager.DepDir(), \"bin\"))\n\tif err != nil {\n\t\tif !os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"Could not read dep\/bin directory: %v\", err)\n\t\t}\n\t\tfiles = []os.FileInfo{}\n\t}\n\tfor _, file := range files {\n\t\ttarget := filepath.Join(binDir, file.Name())\n\t\tif exists, err := libbuildpack.FileExists(target); err != nil {\n\t\t\treturn fmt.Errorf(\"Checking existence: %v\", err)\n\t\t} else if !exists {\n\t\t\tcontents := fmt.Sprintf(\"#!\/bin\/bash\\nexec $DEPS_DIR\/%s\/bin\/%s \\\"$@\\\"\\n\", f.Stager.DepsIdx(), file.Name())\n\t\t\tif err := ioutil.WriteFile(target, []byte(contents), 0755); err != nil {\n\t\t\t\treturn fmt.Errorf(\"WriteFile: %v\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2015 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\npackage components\n\nimport (\n\t\"sync\"\n\n\t\"github.com\/TheThingsNetwork\/ttn\/core\"\n\t\"github.com\/brocaar\/lorawan\"\n)\n\ntype handlerStorage interface {\n\tstore(lorawan.DevAddr, handlerEntry) error\n\tpartition([]core.Packet) ([]handlerPartition, error)\n}\n\ntype handlerPartition struct {\n\thandlerEntry\n\tPackets []core.Packet\n}\n\ntype handlerEntry struct {\n\tAppEUI  lorawan.EUI64\n\tNwkSKey lorawan.AES128Key\n\tAppSKey lorawan.AES128Key\n\tDevAddr lorawan.DevAddr\n}\n\ntype handlerDB struct {\n\tsync.RWMutex \/\/ Guards entries\n\tentries      map[lorawan.DevAddr][]handlerEntry\n}\n\n\/\/ newHandlerDB construct a new local handlerStorage\nfunc newHandlerDB() handlerStorage {\n\treturn &handlerDB{entries: make(map[lorawan.DevAddr][]handlerEntry)}\n}\n\n\/\/ store implements the handlerStorage interface\nfunc (db *handlerDB) store(devAddr lorawan.DevAddr, entry handlerEntry) error {\n\tdb.Lock()\n\tdb.entries[devAddr] = append(db.entries[devAddr], entry)\n\tdb.Unlock()\n\treturn nil\n}\n\n\/\/ partition implements the handlerStorage interface\nfunc (db *handlerDB) partition(packets []core.Packet) ([]handlerPartition, error) {\n\t\/\/ Create a map in order to do the partition\n\tpartitions := make(map[lorawan.EUI64]handlerPartition)\n\n\tdb.RLock() \/\/ We require lock on the whole block because we don't want the entries to change while building the partition.\n\tfor _, packet := range packets {\n\t\t\/\/ First, determine devAddr and get the macPayload. Those are mandatory.\n\t\tdevAddr, err := packet.DevAddr()\n\t\tif err != nil {\n\t\t\treturn nil, ErrInvalidPacket\n\t\t}\n\t\tmacPayload, ok := packet.Payload.MACPayload.(*lorawan.MACPayload)\n\t\tif !ok {\n\t\t\treturn nil, ErrInvalidPacket\n\t\t}\n\n\t\t\/\/ Now, get all tuples associated to that device address, and choose the right one\n\t\tfor _, entry := range db.entries[devAddr] {\n\t\t\t\/\/ Try to decrypt the frame payload with those keys\n\t\t\tkey := entry.AppSKey\n\t\t\tif macPayload.FPort == 0 {\n\t\t\t\tkey = entry.NwkSKey\n\t\t\t}\n\t\t\terr := macPayload.DecryptFRMPayload(key)\n\t\t\tif err != nil { \/\/ Weren't the good keys\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ #Easy\n\t\t\tpacket.Payload.MACPayload = macPayload\n\t\t\tpartitions[entry.AppEUI] = handlerPartition{\n\t\t\t\thandlerEntry: entry,\n\t\t\t\tPackets:      append(partitions[entry.AppEUI].Packets, packet),\n\t\t\t}\n\t\t\tbreak \/\/ We don't need to look for other entries, we've found the right one\n\t\t}\n\t}\n\tdb.RUnlock()\n\n\t\/\/ Transform the map in a slice\n\tres := make([]handlerPartition, 0, len(partitions))\n\tfor _, p := range partitions {\n\t\tres = append(res, p)\n\t}\n\n\treturn res, nil\n}\n<commit_msg>[handler] Make tests pass.<commit_after>\/\/ Copyright © 2015 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\npackage components\n\nimport (\n\t\"sync\"\n\n\t\"github.com\/TheThingsNetwork\/ttn\/core\"\n\t\"github.com\/brocaar\/lorawan\"\n)\n\ntype handlerStorage interface {\n\tstore(lorawan.DevAddr, handlerEntry) error\n\tpartition([]core.Packet) ([]handlerPartition, error)\n}\n\ntype handlerPartition struct {\n\thandlerEntry\n\tPackets []core.Packet\n}\n\ntype handlerEntry struct {\n\tAppEUI  lorawan.EUI64\n\tNwkSKey lorawan.AES128Key\n\tAppSKey lorawan.AES128Key\n\tDevAddr lorawan.DevAddr\n}\n\ntype handlerDB struct {\n\tsync.RWMutex \/\/ Guards entries\n\tentries      map[lorawan.DevAddr][]handlerEntry\n}\n\n\/\/ newHandlerDB construct a new local handlerStorage\nfunc newHandlerDB() handlerStorage {\n\treturn &handlerDB{entries: make(map[lorawan.DevAddr][]handlerEntry)}\n}\n\n\/\/ store implements the handlerStorage interface\nfunc (db *handlerDB) store(devAddr lorawan.DevAddr, entry handlerEntry) error {\n\tdb.Lock()\n\tdb.entries[devAddr] = append(db.entries[devAddr], entry)\n\tdb.Unlock()\n\treturn nil\n}\n\n\/\/ partition implements the handlerStorage interface\nfunc (db *handlerDB) partition(packets []core.Packet) ([]handlerPartition, error) {\n\t\/\/ Create a map in order to do the partition\n\tpartitions := make(map[[20]byte]handlerPartition)\n\n\tdb.RLock() \/\/ We require lock on the whole block because we don't want the entries to change while building the partition.\n\tfor _, packet := range packets {\n\t\t\/\/ First, determine devAddr and get the macPayload. Those are mandatory.\n\t\tdevAddr, err := packet.DevAddr()\n\t\tif err != nil {\n\t\t\treturn nil, ErrInvalidPacket\n\t\t}\n\n\t\t\/\/ Now, get all tuples associated to that device address, and choose the right one\n\t\tfor _, entry := range db.entries[devAddr] {\n\t\t\t\/\/ Compute MIC check to find the right keys\n\t\t\tok, err := packet.Payload.ValidateMIC(entry.NwkSKey)\n\t\t\tif err != nil || !ok {\n\t\t\t\tcontinue \/\/ These aren't the droid you're looking for\n\t\t\t}\n\n\t\t\t\/\/ #Easy\n\t\t\tvar id [20]byte\n\t\t\tcopy(id[:16], entry.AppEUI[:])\n\t\t\tcopy(id[16:], entry.DevAddr[:])\n\t\t\tpartitions[id] = handlerPartition{\n\t\t\t\thandlerEntry: entry,\n\t\t\t\tPackets:      append(partitions[id].Packets, packet),\n\t\t\t}\n\t\t\tbreak \/\/ We shouldn't look for other entries, we've found the right one\n\t\t}\n\t}\n\tdb.RUnlock()\n\n\t\/\/ Transform the map in a slice\n\tres := make([]handlerPartition, 0, len(partitions))\n\tfor _, p := range partitions {\n\t\tres = append(res, p)\n\t}\n\n\tif len(res) == 0 {\n\t\treturn nil, ErrNotFound\n\t}\n\treturn res, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cc_messages\n\nimport \"encoding\/json\"\n\ntype DesireAppRequestFromCC struct {\n\tProcessGuid     string      `json:\"process_guid\"`\n\tDropletUri      string      `json:\"droplet_uri\"`\n\tDockerImageUrl  string      `json:\"docker_image\"`\n\tStack           string      `json:\"stack\"`\n\tStartCommand    string      `json:\"start_command\"`\n\tEnvironment     Environment `json:\"environment\"`\n\tMemoryMB        int         `json:\"memory_mb\"`\n\tDiskMB          int         `json:\"disk_mb\"`\n\tFileDescriptors uint64      `json:\"file_descriptors\"`\n\tNumInstances    int         `json:\"num_instances\"`\n\tRoutes          []string    `json:\"routes\"`\n\tLogGuid         string      `json:\"log_guid\"`\n}\n\nfunc (d DesireAppRequestFromCC) ToJSON() []byte {\n\tencoded, _ := json.Marshal(d)\n\treturn encoded\n}\n\ntype CCDesiredStateServerResponse struct {\n\tApps        []DesireAppRequestFromCC `json:\"apps\"`\n\tCCBulkToken *json.RawMessage         `json:\"token\"`\n}\n\ntype CCBulkToken struct {\n\tId int `json:\"id\"`\n}\n<commit_msg>Add staging_metadata to DesireAppMessage<commit_after>package cc_messages\n\nimport \"encoding\/json\"\n\ntype DesireAppRequestFromCC struct {\n\tProcessGuid     string      `json:\"process_guid\"`\n\tDropletUri      string      `json:\"droplet_uri\"`\n\tDockerImageUrl  string      `json:\"docker_image\"`\n\tStack           string      `json:\"stack\"`\n\tStartCommand    string      `json:\"start_command\"`\n\tStagingMetadata string      `json:\"staging_metadata\"`\n\tEnvironment     Environment `json:\"environment\"`\n\tMemoryMB        int         `json:\"memory_mb\"`\n\tDiskMB          int         `json:\"disk_mb\"`\n\tFileDescriptors uint64      `json:\"file_descriptors\"`\n\tNumInstances    int         `json:\"num_instances\"`\n\tRoutes          []string    `json:\"routes\"`\n\tLogGuid         string      `json:\"log_guid\"`\n}\n\nfunc (d DesireAppRequestFromCC) ToJSON() []byte {\n\tencoded, _ := json.Marshal(d)\n\treturn encoded\n}\n\ntype CCDesiredStateServerResponse struct {\n\tApps        []DesireAppRequestFromCC `json:\"apps\"`\n\tCCBulkToken *json.RawMessage         `json:\"token\"`\n}\n\ntype CCBulkToken struct {\n\tId int `json:\"id\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package dsl_test\n<commit_msg>a few more tests<commit_after>package dsl_test\n\nimport (\n\t\"github.com\/bketelsen\/gorma\"\n\tgdsl \"github.com\/bketelsen\/gorma\/dsl\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t. \"github.com\/raphael\/goa\/design\"\n\t. \"github.com\/raphael\/goa\/design\/dsl\"\n)\n\nvar _ = Describe(\"RelationalStore\", func() {\n\tvar sgname, name string\n\tvar dsl func()\n\n\tBeforeEach(func() {\n\t\tDesign = nil\n\t\tErrors = nil\n\t\tsgname = \"production\"\n\t\tdsl = nil\n\t\tname = \"\"\n\t\tgorma.GormaConstructs = nil\n\n\t})\n\n\tJustBeforeEach(func() {\n\n\t\tgdsl.StorageGroup(sgname, func() {\n\t\t\tgdsl.RelationalStore(name, gorma.MySQL, dsl)\n\t\t})\n\n\t\tRunDSL()\n\n\t})\n\n\tContext(\"with no DSL\", func() {\n\t\tBeforeEach(func() {\n\t\t\tname = \"mysql\"\n\t\t})\n\n\t\tIt(\"produces a valid Relational Store definition\", func() {\n\t\t\tΩ(Design.Validate()).ShouldNot(HaveOccurred())\n\t\t\tsg := gorma.GormaConstructs[gorma.StorageGroup].(*gorma.StorageGroupDefinition)\n\t\t\tΩ(sg.RelationalStores[name].Name).Should(Equal(name))\n\t\t})\n\t})\n\n\tContext(\"with an already defined Relational Store with the same name\", func() {\n\t\tBeforeEach(func() {\n\t\t\tname = \"mysql\"\n\t\t})\n\n\t\tIt(\"produces an error\", func() {\n\t\t\tgdsl.StorageGroup(sgname, func() {\n\t\t\t\tgdsl.RelationalStore(name, gorma.MySQL, dsl)\n\t\t\t})\n\t\t\tΩ(Errors).Should(HaveOccurred())\n\t\t})\n\t})\n\n\tContext(\"with an already defined Relational Store with a different name\", func() {\n\t\tBeforeEach(func() {\n\t\t\tsgname = \"mysql\"\n\t\t})\n\n\t\tIt(\"returns an error\", func() {\n\t\t\tgdsl.StorageGroup(\"news\", dsl)\n\t\t\tΩ(Errors).Should(HaveOccurred())\n\t\t})\n\t})\n\n\tContext(\"with valid DSL\", func() {\n\t\tJustBeforeEach(func() {\n\t\t\tΩ(Errors).ShouldNot(HaveOccurred())\n\t\t\tΩ(Design.Validate()).ShouldNot(HaveOccurred())\n\t\t})\n\n\t\tContext(\"with a description\", func() {\n\t\t\tconst description = \"description\"\n\n\t\t\tBeforeEach(func() {\n\t\t\t\tname = \"mysql\"\n\t\t\t\tdsl = func() {\n\t\t\t\t\tgdsl.Description(description)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tIt(\"sets the relational store description\", func() {\n\t\t\t\tsg := gorma.GormaConstructs[gorma.StorageGroup].(*gorma.StorageGroupDefinition)\n\t\t\t\tΩ(sg.RelationalStores[name].Description).Should(Equal(description))\n\t\t\t})\n\t\t})\n\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tgoselenium \"github.com\/bunsenapp\/go-selenium\"\n)\n\nfunc main() {\n\t\/\/ Create capabilities, driver etc.\n\tcapabilities := goselenium.Capabilities{}\n\tcapabilities.SetBrowser(goselenium.FirefoxBrowser())\n\n\tdriver, err := goselenium.NewSeleniumWebDriver(\"http:\/\/localhost:4444\/wd\/hub\", capabilities)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t_, err = driver.CreateSession()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t\/\/ Delete the session once this function is completed.\n\tdefer driver.DeleteSession()\n\n\t\/\/ Navigate to the HackerNews website.\n\t_, err = driver.Go(\"https:\/\/news.ycombinator.com\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t\/\/ Click the 'new' link at the top\n\tel, err := driver.FindElement(goselenium.ByCSSSelector(\"a[href='newest']\"))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t\/\/ Click the link.\n\t_, err = el.Click()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t\/\/ Wait until the URL has changed with a timeout of 1 second and a check\n\t\/\/ interval of 10ms..\n\tnewLink := \"https:\/\/news.ycombinator.com\/newest\"\n\tok := driver.Wait(goselenium.UntilURLIs(newLink), 10*time.Second, 10*time.Millisecond)\n\tif !ok {\n\t\tfmt.Println(\"Wait timed out :<\")\n\t\treturn\n\t}\n\n\t\/\/ Woohoo! We have successfully navigated to a page.\n\tfmt.Println(\"Successfully navigated to URL \" + newLink)\n}\n<commit_msg>Change time back to 1 second<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tgoselenium \"github.com\/bunsenapp\/go-selenium\"\n)\n\nfunc main() {\n\t\/\/ Create capabilities, driver etc.\n\tcapabilities := goselenium.Capabilities{}\n\tcapabilities.SetBrowser(goselenium.FirefoxBrowser())\n\n\tdriver, err := goselenium.NewSeleniumWebDriver(\"http:\/\/localhost:4444\/wd\/hub\", capabilities)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t_, err = driver.CreateSession()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t\/\/ Delete the session once this function is completed.\n\tdefer driver.DeleteSession()\n\n\t\/\/ Navigate to the HackerNews website.\n\t_, err = driver.Go(\"https:\/\/news.ycombinator.com\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t\/\/ Click the 'new' link at the top\n\tel, err := driver.FindElement(goselenium.ByCSSSelector(\"a[href='newest']\"))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t\/\/ Click the link.\n\t_, err = el.Click()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\t\/\/ Wait until the URL has changed with a timeout of 1 second and a check\n\t\/\/ interval of 10ms..\n\tnewLink := \"https:\/\/news.ycombinator.com\/newest\"\n\tok := driver.Wait(goselenium.UntilURLIs(newLink), 1*time.Second, 10*time.Millisecond)\n\tif !ok {\n\t\tfmt.Println(\"Wait timed out :<\")\n\t\treturn\n\t}\n\n\t\/\/ Woohoo! We have successfully navigated to a page.\n\tfmt.Println(\"Successfully navigated to URL \" + newLink)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/jacobsa\/aws\/exp\/sdb\"\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/ogletest\"\n\t\"math\/rand\"\n\t\"sync\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype integrationTest struct {\n\tdb sdb.SimpleDB\n}\n\nfunc (t *integrationTest) SetUp(i *TestInfo) {\n\tvar err error\n\n\t\/\/ Open a connection.\n\tt.db, err = sdb.NewSimpleDB(g_region, g_accessKey)\n\tAssertEq(nil, err)\n}\n\n\/\/ Generate an item name likely to be unique.\nfunc (t *integrationTest) makeItemName() sdb.ItemName {\n\treturn sdb.ItemName(fmt.Sprintf(\"item.%16x\", uint64(rand.Int63())))\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Domains\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvar g_domainsTestDb sdb.SimpleDB\nvar g_domainsTestDomain0 sdb.Domain\nvar g_domainsTestDomain1 sdb.Domain\n\ntype DomainsTest struct {\n\tintegrationTest\n\n\tmutex           sync.Mutex\n\tdomainsToDelete []sdb.Domain  \/\/ Protected by mutex\n}\n\nfunc init() { RegisterTestSuite(&DomainsTest{}) }\n\nfunc (t *DomainsTest) SetUpTestSuite() {\n\tvar err error\n\n\t\/\/ Open a connection.\n\tg_domainsTestDb, err = sdb.NewSimpleDB(g_region, g_accessKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Create domain 0.\n\tg_domainsTestDomain0, err = g_domainsTestDb.OpenDomain(\"DomainsTest.domain0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Create domain 1.\n\tg_domainsTestDomain1, err = g_domainsTestDb.OpenDomain(\"DomainsTest.domain1\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc (t *DomainsTest) TearDownTestSuite() {\n\t\/\/ Delete both domains.\n\tif err := g_domainsTestDb.DeleteDomain(g_domainsTestDomain0); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := g_domainsTestDb.DeleteDomain(g_domainsTestDomain1); err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Clear variables.\n\tg_domainsTestDb = nil\n\tg_domainsTestDomain0 = nil\n\tg_domainsTestDomain1 = nil\n}\n\nfunc (t *DomainsTest) TearDown() {\n\tt.mutex.Lock()\n\tdefer t.mutex.Unlock()\n\n\t\/\/ Delete each of the domains created during the test.\n\tfor _, d := range t.domainsToDelete {\n\t\tExpectEq(nil, t.db.DeleteDomain(d), \"Domain: %s\", d.Name())\n\t}\n}\n\nfunc (t *DomainsTest) InvalidAccessKey() {\n\t\/\/ Open a connection with an unknown key ID.\n\twrongKey := g_accessKey\n\twrongKey.Id += \"taco\"\n\n\tdb, err := sdb.NewSimpleDB(g_region, wrongKey)\n\tAssertEq(nil, err)\n\n\t\/\/ Attempt to create a domain.\n\t_, err = db.OpenDomain(\"some_domain\")\n\n\tExpectThat(err, Error(HasSubstr(\"403\")))\n\tExpectThat(err, Error(HasSubstr(\"Key Id\")))\n\tExpectThat(err, Error(HasSubstr(\"exist\")))\n}\n\nfunc (t *DomainsTest) SeparatelyNamedDomainsHaveIndependentItems() {\n\tvar err error\n\n\t\/\/ Set up an item in the first domain.\n\titemName := t.makeItemName()\n\terr = g_domainsTestDomain0.PutAttributes(\n\t\titemName,\n\t\t[]sdb.PutUpdate{\n\t\t\tsdb.PutUpdate{Name: \"enchilada\", Value: \"queso\"},\n\t\t},\n\t\t[]sdb.Precondition{},\n\t)\n\n\tAssertEq(nil, err)\n\n\t\/\/ Get attributes for the same name in the other domain. There should be\n\t\/\/ none.\n\tattrs, err := g_domainsTestDomain1.GetAttributes(itemName, true, []string{})\n\tAssertEq(nil, err)\n\n\tExpectThat(attrs, ElementsAre())\n}\n\nfunc (t *DomainsTest) IdenticallyNamedDomainsHaveIdenticalItems() {\n\tvar err error\n\n\t\/\/ Set up an item in the first domain.\n\titemName := t.makeItemName()\n\terr = g_domainsTestDomain0.PutAttributes(\n\t\titemName,\n\t\t[]sdb.PutUpdate{\n\t\t\tsdb.PutUpdate{Name: \"enchilada\", Value: \"queso\"},\n\t\t},\n\t\t[]sdb.Precondition{},\n\t)\n\n\tAssertEq(nil, err)\n\n\t\/\/ Get attributes for the same name in another domain object opened with the\n\t\/\/ same name.\n\tdomain1, err := t.db.OpenDomain(g_domainsTestDomain0.Name())\n\tAssertEq(nil, err)\n\n\tattrs, err := domain1.GetAttributes(itemName, true, []string{})\n\tAssertEq(nil, err)\n\n\tExpectThat(\n\t\tattrs,\n\t\tElementsAre(\n\t\t\tDeepEquals(sdb.Attribute{Name: \"enchilada\", Value: \"queso\"}),\n\t\t),\n\t)\n}\n\nfunc (t *DomainsTest) Delete() {\n\tvar err error\n\tdomainName := \"DomainsTest.Delete\"\n\n\t\/\/ Create a domain, then delete it.\n\tdomain, err := t.db.OpenDomain(domainName)\n\tAssertEq(nil, err)\n\n\terr = t.db.DeleteDomain(domain)\n\tAssertEq(nil, err)\n\n\t\/\/ Delete again; nothing should go wrong.\n\terr = t.db.DeleteDomain(domain)\n\tAssertEq(nil, err)\n\n\t\/\/ Attempt to write to the domain.\n\terr = domain.PutAttributes(\n\t\t\"some_item\",\n\t\t[]sdb.PutUpdate{\n\t\t\tsdb.PutUpdate{Name: \"foo\", Value: \"bar\"},\n\t\t},\n\t\t[]sdb.Precondition{},\n\t)\n\n\tExpectThat(err, Error(HasSubstr(\"NoSuchDomain\")))\n\tExpectThat(err, Error(HasSubstr(\"domain\")))\n\tExpectThat(err, Error(HasSubstr(\"exist\")))\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Items\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvar g_itemsTestDb     sdb.SimpleDB\nvar g_itemsTestDomain sdb.Domain\n\ntype ItemsTest struct {\n\tintegrationTest\n}\n\nfunc init() { RegisterTestSuite(&ItemsTest{}) }\n\nfunc (t *ItemsTest) SetUpTestSuite() {\n\tvar err error\n\n\t\/\/ Open a connection.\n\tg_itemsTestDb, err = sdb.NewSimpleDB(g_region, g_accessKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Create a domain.\n\tg_itemsTestDomain, err = g_itemsTestDb.OpenDomain(\"ItemsTest.domain\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc (t *ItemsTest) TearDownTestSuite() {\n\t\/\/ Delete the domain.\n\tif err := g_itemsTestDb.DeleteDomain(g_itemsTestDomain); err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Clear variables.\n\tg_itemsTestDb = nil\n\tg_itemsTestDomain = nil\n}\n\nfunc (t *ItemsTest) WrongAccessKeySecret() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) InvalidUtf8ItemName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) InvalidUtf8AttributeName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) InvalidUtf8AttributeValue() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) LongItemName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) LongAttributeName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) LongAttributeValue() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) PutThenGet() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) BatchPutThenGet() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) BatchPutThenBatchGet() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) GetForNonExistentItem() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) GetParticularAttributes() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) BatchGetParticularAttributes() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) BatchGetForNonExistentItems() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) GetNonExistentAttributeName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) BatchGetNonExistentAttributeName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) FailedValuePrecondition() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) FailedExistencePrecondition() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) FailedNonExistencePrecondition() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SuccessfulPreconditions() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) DeleteParticularAttributes() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) DeleteAllAttributes() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) BatchDelete() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) InvalidSelectQuery() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectAll() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectItemName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectCount() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectWithPredicates() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectWithSortOrder() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectWithLimit() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectEmptyResultSet() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectLargeResultSet() {\n\tExpectEq(\"TODO\", \"\")\n}\n<commit_msg>Deleted a redundant test.<commit_after>\/\/ Copyright 2012 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/jacobsa\/aws\/exp\/sdb\"\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/ogletest\"\n\t\"math\/rand\"\n\t\"sync\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype integrationTest struct {\n\tdb sdb.SimpleDB\n}\n\nfunc (t *integrationTest) SetUp(i *TestInfo) {\n\tvar err error\n\n\t\/\/ Open a connection.\n\tt.db, err = sdb.NewSimpleDB(g_region, g_accessKey)\n\tAssertEq(nil, err)\n}\n\n\/\/ Generate an item name likely to be unique.\nfunc (t *integrationTest) makeItemName() sdb.ItemName {\n\treturn sdb.ItemName(fmt.Sprintf(\"item.%16x\", uint64(rand.Int63())))\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Domains\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvar g_domainsTestDb sdb.SimpleDB\nvar g_domainsTestDomain0 sdb.Domain\nvar g_domainsTestDomain1 sdb.Domain\n\ntype DomainsTest struct {\n\tintegrationTest\n\n\tmutex           sync.Mutex\n\tdomainsToDelete []sdb.Domain  \/\/ Protected by mutex\n}\n\nfunc init() { RegisterTestSuite(&DomainsTest{}) }\n\nfunc (t *DomainsTest) SetUpTestSuite() {\n\tvar err error\n\n\t\/\/ Open a connection.\n\tg_domainsTestDb, err = sdb.NewSimpleDB(g_region, g_accessKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Create domain 0.\n\tg_domainsTestDomain0, err = g_domainsTestDb.OpenDomain(\"DomainsTest.domain0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Create domain 1.\n\tg_domainsTestDomain1, err = g_domainsTestDb.OpenDomain(\"DomainsTest.domain1\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc (t *DomainsTest) TearDownTestSuite() {\n\t\/\/ Delete both domains.\n\tif err := g_domainsTestDb.DeleteDomain(g_domainsTestDomain0); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := g_domainsTestDb.DeleteDomain(g_domainsTestDomain1); err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Clear variables.\n\tg_domainsTestDb = nil\n\tg_domainsTestDomain0 = nil\n\tg_domainsTestDomain1 = nil\n}\n\nfunc (t *DomainsTest) TearDown() {\n\tt.mutex.Lock()\n\tdefer t.mutex.Unlock()\n\n\t\/\/ Delete each of the domains created during the test.\n\tfor _, d := range t.domainsToDelete {\n\t\tExpectEq(nil, t.db.DeleteDomain(d), \"Domain: %s\", d.Name())\n\t}\n}\n\nfunc (t *DomainsTest) InvalidAccessKey() {\n\t\/\/ Open a connection with an unknown key ID.\n\twrongKey := g_accessKey\n\twrongKey.Id += \"taco\"\n\n\tdb, err := sdb.NewSimpleDB(g_region, wrongKey)\n\tAssertEq(nil, err)\n\n\t\/\/ Attempt to create a domain.\n\t_, err = db.OpenDomain(\"some_domain\")\n\n\tExpectThat(err, Error(HasSubstr(\"403\")))\n\tExpectThat(err, Error(HasSubstr(\"Key Id\")))\n\tExpectThat(err, Error(HasSubstr(\"exist\")))\n}\n\nfunc (t *DomainsTest) SeparatelyNamedDomainsHaveIndependentItems() {\n\tvar err error\n\n\t\/\/ Set up an item in the first domain.\n\titemName := t.makeItemName()\n\terr = g_domainsTestDomain0.PutAttributes(\n\t\titemName,\n\t\t[]sdb.PutUpdate{\n\t\t\tsdb.PutUpdate{Name: \"enchilada\", Value: \"queso\"},\n\t\t},\n\t\t[]sdb.Precondition{},\n\t)\n\n\tAssertEq(nil, err)\n\n\t\/\/ Get attributes for the same name in the other domain. There should be\n\t\/\/ none.\n\tattrs, err := g_domainsTestDomain1.GetAttributes(itemName, true, []string{})\n\tAssertEq(nil, err)\n\n\tExpectThat(attrs, ElementsAre())\n}\n\nfunc (t *DomainsTest) IdenticallyNamedDomainsHaveIdenticalItems() {\n\tvar err error\n\n\t\/\/ Set up an item in the first domain.\n\titemName := t.makeItemName()\n\terr = g_domainsTestDomain0.PutAttributes(\n\t\titemName,\n\t\t[]sdb.PutUpdate{\n\t\t\tsdb.PutUpdate{Name: \"enchilada\", Value: \"queso\"},\n\t\t},\n\t\t[]sdb.Precondition{},\n\t)\n\n\tAssertEq(nil, err)\n\n\t\/\/ Get attributes for the same name in another domain object opened with the\n\t\/\/ same name.\n\tdomain1, err := t.db.OpenDomain(g_domainsTestDomain0.Name())\n\tAssertEq(nil, err)\n\n\tattrs, err := domain1.GetAttributes(itemName, true, []string{})\n\tAssertEq(nil, err)\n\n\tExpectThat(\n\t\tattrs,\n\t\tElementsAre(\n\t\t\tDeepEquals(sdb.Attribute{Name: \"enchilada\", Value: \"queso\"}),\n\t\t),\n\t)\n}\n\nfunc (t *DomainsTest) Delete() {\n\tvar err error\n\tdomainName := \"DomainsTest.Delete\"\n\n\t\/\/ Create a domain, then delete it.\n\tdomain, err := t.db.OpenDomain(domainName)\n\tAssertEq(nil, err)\n\n\terr = t.db.DeleteDomain(domain)\n\tAssertEq(nil, err)\n\n\t\/\/ Delete again; nothing should go wrong.\n\terr = t.db.DeleteDomain(domain)\n\tAssertEq(nil, err)\n\n\t\/\/ Attempt to write to the domain.\n\terr = domain.PutAttributes(\n\t\t\"some_item\",\n\t\t[]sdb.PutUpdate{\n\t\t\tsdb.PutUpdate{Name: \"foo\", Value: \"bar\"},\n\t\t},\n\t\t[]sdb.Precondition{},\n\t)\n\n\tExpectThat(err, Error(HasSubstr(\"NoSuchDomain\")))\n\tExpectThat(err, Error(HasSubstr(\"domain\")))\n\tExpectThat(err, Error(HasSubstr(\"exist\")))\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Items\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvar g_itemsTestDb     sdb.SimpleDB\nvar g_itemsTestDomain sdb.Domain\n\ntype ItemsTest struct {\n\tintegrationTest\n}\n\nfunc init() { RegisterTestSuite(&ItemsTest{}) }\n\nfunc (t *ItemsTest) SetUpTestSuite() {\n\tvar err error\n\n\t\/\/ Open a connection.\n\tg_itemsTestDb, err = sdb.NewSimpleDB(g_region, g_accessKey)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Create a domain.\n\tg_itemsTestDomain, err = g_itemsTestDb.OpenDomain(\"ItemsTest.domain\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc (t *ItemsTest) TearDownTestSuite() {\n\t\/\/ Delete the domain.\n\tif err := g_itemsTestDb.DeleteDomain(g_itemsTestDomain); err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Clear variables.\n\tg_itemsTestDb = nil\n\tg_itemsTestDomain = nil\n}\n\nfunc (t *ItemsTest) InvalidUtf8ItemName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) InvalidUtf8AttributeName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) InvalidUtf8AttributeValue() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) LongItemName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) LongAttributeName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) LongAttributeValue() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) PutThenGet() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) BatchPutThenGet() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) BatchPutThenBatchGet() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) GetForNonExistentItem() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) GetParticularAttributes() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) BatchGetParticularAttributes() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) BatchGetForNonExistentItems() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) GetNonExistentAttributeName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) BatchGetNonExistentAttributeName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) FailedValuePrecondition() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) FailedExistencePrecondition() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) FailedNonExistencePrecondition() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SuccessfulPreconditions() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) DeleteParticularAttributes() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) DeleteAllAttributes() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) BatchDelete() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) InvalidSelectQuery() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectAll() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectItemName() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectCount() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectWithPredicates() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectWithSortOrder() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectWithLimit() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectEmptyResultSet() {\n\tExpectEq(\"TODO\", \"\")\n}\n\nfunc (t *ItemsTest) SelectLargeResultSet() {\n\tExpectEq(\"TODO\", \"\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package maimok\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\n\tlibvirt \"github.com\/libvirt\/libvirt-go\"\n\t\"github.com\/satori\/go.uuid\"\n)\n\n\/\/ VM data model\ntype VM struct {\n\tID     uint    `json:\"id\"`\n\tName   string  `json:\"name\"`\n\tMemory uint64  `json:\"memory\"`\n\tState  VMState `json:\"state\"`\n}\n\n\/\/ VMState is the state of the vm\ntype VMState int\n\nconst (\n\t\/\/ Running vm\n\tRunning VMState = iota + 1\n\t\/\/ Stopped vm\n\tStopped\n)\n\n\/\/ CreateVMStruct struct for the CreateVM call\ntype CreateVMStruct struct {\n\t\/\/ Generated\n\tID         string\n\tMACAddress string\n\t\/\/ Provided by API\n\tName        string\n\tHostname    string\n\tRAMMB       uint\n\tDiskSpaceGB uint\n\tImage       string\n\tIPAddress   string\n\t\/\/ Set in config file\n\tSSHKey  string\n\tGateway string\n\tNetmask string\n}\n\nfunc generateMACAddress() (string, error) {\n\tbuf := make(net.HardwareAddr, 6)\n\t_, err := rand.Read(buf)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf[0] = (buf[0] | 2) & 0xfe \/\/ Set local bit, ensure unicast address\n\treturn buf.String(), nil\n}\n\n\/\/ CreateVM createds a virtual machine\nfunc CreateVM(state *globalState, createVM CreateVMStruct) error {\n\tcreateVM.ID = uuid.NewV4().String()\n\tcreateVM.SSHKey = state.config.SSHKey\n\tcreateVM.Gateway = state.config.Gateway\n\tcreateVM.Netmask = state.config.Netmask\n\n\tmacAddress, err := generateMACAddress()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot generate MAC Address, %s\", err)\n\t}\n\tcreateVM.MACAddress = macAddress\n\n\t\/\/ create config iso\n\tdir, err := ioutil.TempDir(\"\", \"maimok\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot create temp directory, %s\", err)\n\t}\n\tdefer os.RemoveAll(dir)\n\n\tmetaDataFile, err := os.OpenFile(filepath.Join(dir, \"meta-data\"), os.O_WRONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer metaDataFile.Close()\n\tif err := state.tpl.ExecuteTemplate(metaDataFile, \"meta-data.yml\", createVM); err != nil {\n\t\treturn err\n\t}\n\n\tuserDataFile, err := os.OpenFile(filepath.Join(dir, \"user-data\"), os.O_WRONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer userDataFile.Close()\n\tif err := state.tpl.ExecuteTemplate(userDataFile, \"user-data.yml\", createVM); err != nil {\n\t\treturn err\n\t}\n\n\tnetworkConfigFile, err := os.OpenFile(filepath.Join(dir, \"network-config\"), os.O_WRONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer networkConfigFile.Close()\n\tif err := state.tpl.ExecuteTemplate(networkConfigFile, \"network-config.yml\", createVM); err != nil {\n\t\treturn err\n\t}\n\n\tcmd := exec.Command(\"genisoimage\", \"-volid\", \"cidata\", \"-joliet\", \"-rock\",\n\t\tmetaDataFile.Name(), userDataFile.Name(), networkConfigFile.Name())\n\tvar isoFile bytes.Buffer\n\tcmd.Stdout = &isoFile\n\terr = cmd.Run()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Generation of iso image failed: %s\", err)\n\t}\n\n\tstoragePool, err := state.conn.LookupStoragePoolByName(\"default\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ create iso volume\n\tbuf := new(bytes.Buffer)\n\tif err := state.tpl.ExecuteTemplate(buf, \"iso-volume.xml\", createVM); err != nil {\n\t\treturn err\n\t}\n\tvolume, err := storagePool.StorageVolCreateXML(buf.String(), 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstream, err := state.conn.NewStream(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvolume.Upload(stream, 0, 0, 0)\n\tlen, err := stream.Send(isoFile.Bytes())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not send config iso image to storage pool: %s\", err)\n\t}\n\tif len < buf.Len() {\n\t\treturn fmt.Errorf(\"Could not send all iso image data to storage pool\")\n\t}\n\tif err := stream.Finish(); err != nil {\n\t\treturn fmt.Errorf(\"Could not send config iso image to storage pool: %s\", err)\n\t}\n\n\t\/\/ create harddisk volume\n\tbuf = new(bytes.Buffer)\n\tif err := state.tpl.ExecuteTemplate(buf, \"volume.xml\", createVM); err != nil {\n\t\treturn err\n\t}\n\tif _, err = storagePool.StorageVolCreateXML(buf.String(), 0); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ define domain\n\tbuf = new(bytes.Buffer)\n\tif err = state.tpl.ExecuteTemplate(buf, \"domain.xml\", createVM); err != nil {\n\t\treturn err\n\t}\n\tdomain, err := state.conn.DomainDefineXML(buf.String())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to define domain: %s\", err)\n\t}\n\n\t\/\/ start domain\n\tif err = domain.Create(); err != nil {\n\t\treturn fmt.Errorf(\"Failed to start domain: %s\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ ListVMs returns a list of all virtual machines\nfunc ListVMs(state *globalState) []*VM {\n\tdomains, err := state.conn.ListAllDomains(0)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tvms := []*VM{}\n\tfor _, domain := range domains {\n\t\tname, _ := domain.GetName()\n\t\tmemory, _ := domain.GetMaxMemory()\n\t\tid, _ := domain.GetID()\n\t\tstate, _, _ := domain.GetState()\n\n\t\tvar vmState VMState\n\t\tif state == libvirt.DOMAIN_RUNNING {\n\t\t\tvmState = Running\n\t\t} else {\n\t\t\tvmState = Stopped\n\t\t}\n\n\t\tvms = append(vms, &VM{ID: id, Name: name, Memory: memory, State: vmState})\n\t}\n\treturn vms\n}\n<commit_msg>backend: show running state as boolean<commit_after>package maimok\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\n\tlibvirt \"github.com\/libvirt\/libvirt-go\"\n\tuuid \"github.com\/satori\/go.uuid\"\n)\n\n\/\/ VM data model\ntype VM struct {\n\tID      uint   `json:\"id\"`\n\tName    string `json:\"name\"`\n\tMemory  uint64 `json:\"memory\"`\n\tRunning bool   `json:\"running\"`\n}\n\n\/\/ CreateVMStruct struct for the CreateVM call\ntype CreateVMStruct struct {\n\t\/\/ Generated\n\tID         string\n\tMACAddress string\n\t\/\/ Provided by API\n\tName        string\n\tHostname    string\n\tRAMMB       uint\n\tDiskSpaceGB uint\n\tImage       string\n\tIPAddress   string\n\t\/\/ Set in config file\n\tSSHKey  string\n\tGateway string\n\tNetmask string\n}\n\nfunc generateMACAddress() (string, error) {\n\tbuf := make(net.HardwareAddr, 6)\n\t_, err := rand.Read(buf)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbuf[0] = (buf[0] | 2) & 0xfe \/\/ Set local bit, ensure unicast address\n\treturn buf.String(), nil\n}\n\n\/\/ CreateVM createds a virtual machine\nfunc CreateVM(state *globalState, createVM CreateVMStruct) error {\n\tcreateVM.ID = uuid.NewV4().String()\n\tcreateVM.SSHKey = state.config.SSHKey\n\tcreateVM.Gateway = state.config.Gateway\n\tcreateVM.Netmask = state.config.Netmask\n\n\tmacAddress, err := generateMACAddress()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot generate MAC Address, %s\", err)\n\t}\n\tcreateVM.MACAddress = macAddress\n\n\t\/\/ create config iso\n\tdir, err := ioutil.TempDir(\"\", \"maimok\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Cannot create temp directory, %s\", err)\n\t}\n\tdefer os.RemoveAll(dir)\n\n\tmetaDataFile, err := os.OpenFile(filepath.Join(dir, \"meta-data\"), os.O_WRONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer metaDataFile.Close()\n\tif err := state.tpl.ExecuteTemplate(metaDataFile, \"meta-data.yml\", createVM); err != nil {\n\t\treturn err\n\t}\n\n\tuserDataFile, err := os.OpenFile(filepath.Join(dir, \"user-data\"), os.O_WRONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer userDataFile.Close()\n\tif err := state.tpl.ExecuteTemplate(userDataFile, \"user-data.yml\", createVM); err != nil {\n\t\treturn err\n\t}\n\n\tnetworkConfigFile, err := os.OpenFile(filepath.Join(dir, \"network-config\"), os.O_WRONLY|os.O_CREATE, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer networkConfigFile.Close()\n\tif err := state.tpl.ExecuteTemplate(networkConfigFile, \"network-config.yml\", createVM); err != nil {\n\t\treturn err\n\t}\n\n\tcmd := exec.Command(\"genisoimage\", \"-volid\", \"cidata\", \"-joliet\", \"-rock\",\n\t\tmetaDataFile.Name(), userDataFile.Name(), networkConfigFile.Name())\n\tvar isoFile bytes.Buffer\n\tcmd.Stdout = &isoFile\n\terr = cmd.Run()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Generation of iso image failed: %s\", err)\n\t}\n\n\tstoragePool, err := state.conn.LookupStoragePoolByName(\"default\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ create iso volume\n\tbuf := new(bytes.Buffer)\n\tif err := state.tpl.ExecuteTemplate(buf, \"iso-volume.xml\", createVM); err != nil {\n\t\treturn err\n\t}\n\tvolume, err := storagePool.StorageVolCreateXML(buf.String(), 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstream, err := state.conn.NewStream(0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvolume.Upload(stream, 0, 0, 0)\n\tlen, err := stream.Send(isoFile.Bytes())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Could not send config iso image to storage pool: %s\", err)\n\t}\n\tif len < buf.Len() {\n\t\treturn fmt.Errorf(\"Could not send all iso image data to storage pool\")\n\t}\n\tif err := stream.Finish(); err != nil {\n\t\treturn fmt.Errorf(\"Could not send config iso image to storage pool: %s\", err)\n\t}\n\n\t\/\/ create harddisk volume\n\tbuf = new(bytes.Buffer)\n\tif err := state.tpl.ExecuteTemplate(buf, \"volume.xml\", createVM); err != nil {\n\t\treturn err\n\t}\n\tif _, err = storagePool.StorageVolCreateXML(buf.String(), 0); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ define domain\n\tbuf = new(bytes.Buffer)\n\tif err = state.tpl.ExecuteTemplate(buf, \"domain.xml\", createVM); err != nil {\n\t\treturn err\n\t}\n\tdomain, err := state.conn.DomainDefineXML(buf.String())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to define domain: %s\", err)\n\t}\n\n\t\/\/ start domain\n\tif err = domain.Create(); err != nil {\n\t\treturn fmt.Errorf(\"Failed to start domain: %s\", err)\n\t}\n\n\treturn nil\n}\n\n\/\/ ListVMs returns a list of all virtual machines\nfunc ListVMs(state *globalState) []*VM {\n\tdomains, err := state.conn.ListAllDomains(0)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tvms := []*VM{}\n\tfor _, domain := range domains {\n\t\tname, _ := domain.GetName()\n\t\tmemory, _ := domain.GetMaxMemory()\n\t\tid, _ := domain.GetID()\n\t\tstate, _, _ := domain.GetState()\n\n\t\tvar running bool\n\t\tif state == libvirt.DOMAIN_RUNNING {\n\t\t\trunning = true\n\t\t} else {\n\t\t\trunning = false\n\t\t}\n\n\t\tvms = append(vms, &VM{ID: id, Name: name, Memory: memory, Running: running})\n\t}\n\treturn vms\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/*\n\n#define _GNU_SOURCE\n#include <asm\/types.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <linux\/netlink.h>\n#include <linux\/rtnetlink.h>\n#include <sched.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/ioctl.h>\n#include <sys\/socket.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <time.h>\n#include <unistd.h>\n\n#include \"..\/shared\/netutils\/network.c\"\n#include \"include\/memory_utils.h\"\n\n#ifndef UEVENT_SEND\n#define UEVENT_SEND 16\n#endif\n\nextern char *advance_arg(bool required);\nextern void attach_userns(int pid);\nextern int dosetns(int pid, char *nstype);\n\nstruct nlmsg {\n\tstruct nlmsghdr *nlmsghdr;\n\tssize_t cap;\n};\n\nstatic struct nlmsg *nlmsg_alloc(size_t size)\n{\n\t__do_free struct nlmsg *nlmsg = NULL;\n\tsize_t len = NLMSG_HDRLEN + NLMSG_ALIGN(size);\n\n\tnlmsg = (struct nlmsg *)malloc(sizeof(struct nlmsg));\n\tif (!nlmsg)\n\t\treturn NULL;\n\n\tnlmsg->nlmsghdr = (struct nlmsghdr *)malloc(len);\n\tif (!nlmsg->nlmsghdr)\n\t\treturn NULL;\n\n\tmemset(nlmsg->nlmsghdr, 0, len);\n\tnlmsg->cap = len;\n\tnlmsg->nlmsghdr->nlmsg_len = NLMSG_HDRLEN;\n\n\treturn move_ptr(nlmsg);\n}\n\nstatic void *nlmsg_reserve_unaligned(struct nlmsg *nlmsg, size_t len)\n{\n\tchar *buf;\n\tsize_t nlmsg_len = nlmsg->nlmsghdr->nlmsg_len;\n\tsize_t tlen = len;\n\n\tif ((ssize_t)(nlmsg_len + tlen) > nlmsg->cap)\n\t\treturn NULL;\n\n\tbuf = ((char *)(nlmsg->nlmsghdr)) + nlmsg_len;\n\tnlmsg->nlmsghdr->nlmsg_len += tlen;\n\n\tif (tlen > len)\n\t\tmemset(buf + len, 0, tlen - len);\n\n\treturn buf;\n}\n\nint can_inject_uevent(const char *uevent, size_t len)\n{\n\t__do_close_prot_errno int sock_fd = -EBADF;\n\t__do_free struct nlmsg *nlmsg = NULL;\n\tint ret;\n\tchar *umsg = NULL;\n\n\tsock_fd = netlink_open(NETLINK_KOBJECT_UEVENT);\n\tif (sock_fd < 0) {\n\t\treturn -1;\n\t}\n\n\tnlmsg = nlmsg_alloc(len);\n\tif (!nlmsg)\n\t\treturn -1;\n\n\tnlmsg->nlmsghdr->nlmsg_flags = NLM_F_REQUEST;\n\tnlmsg->nlmsghdr->nlmsg_type = UEVENT_SEND;\n\tnlmsg->nlmsghdr->nlmsg_pid = 0;\n\n\tumsg = nlmsg_reserve_unaligned(nlmsg, len);\n\tif (!umsg)\n\t\treturn -1;\n\n\tmemcpy(umsg, uevent, len);\n\n\tret = __netlink_send(sock_fd, nlmsg->nlmsghdr);\n\tif (ret < 0)\n\t\treturn -1;\n\n\treturn 0;\n}\n\nstatic int inject_uevent(const char *uevent, size_t len)\n{\n\t__do_close_prot_errno int sock_fd = -EBADF;\n\t__do_free struct nlmsg *nlmsg = NULL;\n\tint ret;\n\tchar *umsg = NULL;\n\n\tsock_fd = netlink_open(NETLINK_KOBJECT_UEVENT);\n\tif (sock_fd < 0)\n\t\treturn -1;\n\n\tnlmsg = nlmsg_alloc(len);\n\tif (!nlmsg)\n\t\treturn -1;\n\n\tnlmsg->nlmsghdr->nlmsg_flags = NLM_F_ACK | NLM_F_REQUEST;\n\tnlmsg->nlmsghdr->nlmsg_type = UEVENT_SEND;\n\tnlmsg->nlmsghdr->nlmsg_pid = 0;\n\n\tumsg = nlmsg_reserve_unaligned(nlmsg, len);\n\tif (!umsg)\n\t\treturn -1;\n\n\tmemcpy(umsg, uevent, len);\n\n\tret = netlink_transaction(sock_fd, nlmsg->nlmsghdr, nlmsg->nlmsghdr);\n\tif (ret < 0)\n\t\treturn -1;\n\n\treturn 0;\n}\n\nvoid forkuevent() {\n\tchar *uevent = NULL;\n\tchar *cur = NULL;\n\tpid_t pid = 0;\n\tsize_t len = 0;\n\n\tcur = advance_arg(false);\n\tif (cur == NULL || (strcmp(cur, \"--help\") == 0 || strcmp(cur, \"--version\") == 0 || strcmp(cur, \"-h\") == 0)) {\n\t\tfprintf(stderr, \"Error: Missing PID\\n\");\n\t\t_exit(1);\n\t}\n\n\t\/\/ Get the pid\n\tcur = advance_arg(false);\n\tif (cur == NULL || (strcmp(cur, \"--help\") == 0 || strcmp(cur, \"--version\") == 0 || strcmp(cur, \"-h\") == 0)) {\n\t\tfprintf(stderr, \"Error: Missing PID\\n\");\n\t\t_exit(1);\n\t}\n\tpid = atoi(cur);\n\n\t\/\/ Get the size\n\tcur = advance_arg(false);\n\tif (cur == NULL || (strcmp(cur, \"--help\") == 0 || strcmp(cur, \"--version\") == 0 || strcmp(cur, \"-h\") == 0)) {\n\t\tfprintf(stderr, \"Error: Missing uevent length\\n\");\n\t\t_exit(1);\n\t}\n\tlen = atoi(cur);\n\n\t\/\/ Get the uevent\n\tcur = advance_arg(false);\n\tif (cur == NULL || (strcmp(cur, \"--help\") == 0 || strcmp(cur, \"--version\") == 0 || strcmp(cur, \"-h\") == 0)) {\n\t\tfprintf(stderr, \"Error: Missing uevent\\n\");\n\t\t_exit(1);\n\t}\n\tuevent = cur;\n\n\t\/\/ Check that we're root\n\tif (geteuid() != 0) {\n\t\tfprintf(stderr, \"Error: forkuevent requires root privileges\\n\");\n\t\t_exit(1);\n\t}\n\n\tattach_userns(pid);\n\n\tif (dosetns(pid, \"net\") < 0) {\n\t\tfprintf(stderr, \"Failed to setns to container network namespace: %s\\n\", strerror(errno));\n\t\t_exit(1);\n\t}\n\n\tif (inject_uevent(uevent, len) < 0) {\n\t\tfprintf(stderr, \"Failed to inject uevent\\n\");\n\t\t_exit(1);\n\t}\n}\n*\/\n\/\/ #cgo CFLAGS: -std=gnu11 -Wvla\nimport \"C\"\n\ntype cmdForkuevent struct {\n\tglobal *cmdGlobal\n}\n\nfunc (c *cmdForkuevent) Command() *cobra.Command {\n\t\/\/ Main subcommand\n\tcmd := &cobra.Command{}\n\tcmd.Use = \"forkuevent\"\n\tcmd.Short = \"Inject uevents into container's network namespace\"\n\tcmd.Long = `Description:\n  Inject uevent into a container's network namespace\n\n  This internal command is used to inject uevents into unprivileged container's\n  network namespaces.\n`\n\tcmd.Hidden = true\n\n\t\/\/ pull\n\tcmdInject := &cobra.Command{}\n\tcmdInject.Use = \"inject <PID> <len> <uevent>\"\n\tcmdInject.Args = cobra.ExactArgs(3)\n\tcmdInject.RunE = c.Run\n\tcmd.AddCommand(cmdInject)\n\n\treturn cmd\n}\n\nfunc (c *cmdForkuevent) Run(cmd *cobra.Command, args []string) error {\n\treturn nil\n}\n<commit_msg>main\/forkuevent: Fixes error when >3 arguments used (normal case)<commit_after>package main\n\nimport (\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/*\n\n#define _GNU_SOURCE\n#include <asm\/types.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <linux\/netlink.h>\n#include <linux\/rtnetlink.h>\n#include <sched.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys\/ioctl.h>\n#include <sys\/socket.h>\n#include <sys\/stat.h>\n#include <sys\/types.h>\n#include <sys\/wait.h>\n#include <time.h>\n#include <unistd.h>\n\n#include \"..\/shared\/netutils\/network.c\"\n#include \"include\/memory_utils.h\"\n\n#ifndef UEVENT_SEND\n#define UEVENT_SEND 16\n#endif\n\nextern char *advance_arg(bool required);\nextern void attach_userns(int pid);\nextern int dosetns(int pid, char *nstype);\n\nstruct nlmsg {\n\tstruct nlmsghdr *nlmsghdr;\n\tssize_t cap;\n};\n\nstatic struct nlmsg *nlmsg_alloc(size_t size)\n{\n\t__do_free struct nlmsg *nlmsg = NULL;\n\tsize_t len = NLMSG_HDRLEN + NLMSG_ALIGN(size);\n\n\tnlmsg = (struct nlmsg *)malloc(sizeof(struct nlmsg));\n\tif (!nlmsg)\n\t\treturn NULL;\n\n\tnlmsg->nlmsghdr = (struct nlmsghdr *)malloc(len);\n\tif (!nlmsg->nlmsghdr)\n\t\treturn NULL;\n\n\tmemset(nlmsg->nlmsghdr, 0, len);\n\tnlmsg->cap = len;\n\tnlmsg->nlmsghdr->nlmsg_len = NLMSG_HDRLEN;\n\n\treturn move_ptr(nlmsg);\n}\n\nstatic void *nlmsg_reserve_unaligned(struct nlmsg *nlmsg, size_t len)\n{\n\tchar *buf;\n\tsize_t nlmsg_len = nlmsg->nlmsghdr->nlmsg_len;\n\tsize_t tlen = len;\n\n\tif ((ssize_t)(nlmsg_len + tlen) > nlmsg->cap)\n\t\treturn NULL;\n\n\tbuf = ((char *)(nlmsg->nlmsghdr)) + nlmsg_len;\n\tnlmsg->nlmsghdr->nlmsg_len += tlen;\n\n\tif (tlen > len)\n\t\tmemset(buf + len, 0, tlen - len);\n\n\treturn buf;\n}\n\nint can_inject_uevent(const char *uevent, size_t len)\n{\n\t__do_close_prot_errno int sock_fd = -EBADF;\n\t__do_free struct nlmsg *nlmsg = NULL;\n\tint ret;\n\tchar *umsg = NULL;\n\n\tsock_fd = netlink_open(NETLINK_KOBJECT_UEVENT);\n\tif (sock_fd < 0) {\n\t\treturn -1;\n\t}\n\n\tnlmsg = nlmsg_alloc(len);\n\tif (!nlmsg)\n\t\treturn -1;\n\n\tnlmsg->nlmsghdr->nlmsg_flags = NLM_F_REQUEST;\n\tnlmsg->nlmsghdr->nlmsg_type = UEVENT_SEND;\n\tnlmsg->nlmsghdr->nlmsg_pid = 0;\n\n\tumsg = nlmsg_reserve_unaligned(nlmsg, len);\n\tif (!umsg)\n\t\treturn -1;\n\n\tmemcpy(umsg, uevent, len);\n\n\tret = __netlink_send(sock_fd, nlmsg->nlmsghdr);\n\tif (ret < 0)\n\t\treturn -1;\n\n\treturn 0;\n}\n\nstatic int inject_uevent(const char *uevent, size_t len)\n{\n\t__do_close_prot_errno int sock_fd = -EBADF;\n\t__do_free struct nlmsg *nlmsg = NULL;\n\tint ret;\n\tchar *umsg = NULL;\n\n\tsock_fd = netlink_open(NETLINK_KOBJECT_UEVENT);\n\tif (sock_fd < 0)\n\t\treturn -1;\n\n\tnlmsg = nlmsg_alloc(len);\n\tif (!nlmsg)\n\t\treturn -1;\n\n\tnlmsg->nlmsghdr->nlmsg_flags = NLM_F_ACK | NLM_F_REQUEST;\n\tnlmsg->nlmsghdr->nlmsg_type = UEVENT_SEND;\n\tnlmsg->nlmsghdr->nlmsg_pid = 0;\n\n\tumsg = nlmsg_reserve_unaligned(nlmsg, len);\n\tif (!umsg)\n\t\treturn -1;\n\n\tmemcpy(umsg, uevent, len);\n\n\tret = netlink_transaction(sock_fd, nlmsg->nlmsghdr, nlmsg->nlmsghdr);\n\tif (ret < 0)\n\t\treturn -1;\n\n\treturn 0;\n}\n\nvoid forkuevent() {\n\tchar *uevent = NULL;\n\tchar *cur = NULL;\n\tpid_t pid = 0;\n\tsize_t len = 0;\n\n\tcur = advance_arg(false);\n\tif (cur == NULL || (strcmp(cur, \"--help\") == 0 || strcmp(cur, \"--version\") == 0 || strcmp(cur, \"-h\") == 0)) {\n\t\tfprintf(stderr, \"Error: Missing PID\\n\");\n\t\t_exit(1);\n\t}\n\n\t\/\/ Get the pid\n\tcur = advance_arg(false);\n\tif (cur == NULL || (strcmp(cur, \"--help\") == 0 || strcmp(cur, \"--version\") == 0 || strcmp(cur, \"-h\") == 0)) {\n\t\tfprintf(stderr, \"Error: Missing PID\\n\");\n\t\t_exit(1);\n\t}\n\tpid = atoi(cur);\n\n\t\/\/ Get the size\n\tcur = advance_arg(false);\n\tif (cur == NULL || (strcmp(cur, \"--help\") == 0 || strcmp(cur, \"--version\") == 0 || strcmp(cur, \"-h\") == 0)) {\n\t\tfprintf(stderr, \"Error: Missing uevent length\\n\");\n\t\t_exit(1);\n\t}\n\tlen = atoi(cur);\n\n\t\/\/ Get the uevent\n\tcur = advance_arg(false);\n\tif (cur == NULL || (strcmp(cur, \"--help\") == 0 || strcmp(cur, \"--version\") == 0 || strcmp(cur, \"-h\") == 0)) {\n\t\tfprintf(stderr, \"Error: Missing uevent\\n\");\n\t\t_exit(1);\n\t}\n\tuevent = cur;\n\n\t\/\/ Check that we're root\n\tif (geteuid() != 0) {\n\t\tfprintf(stderr, \"Error: forkuevent requires root privileges\\n\");\n\t\t_exit(1);\n\t}\n\n\tattach_userns(pid);\n\n\tif (dosetns(pid, \"net\") < 0) {\n\t\tfprintf(stderr, \"Failed to setns to container network namespace: %s\\n\", strerror(errno));\n\t\t_exit(1);\n\t}\n\n\tif (inject_uevent(uevent, len) < 0) {\n\t\tfprintf(stderr, \"Failed to inject uevent\\n\");\n\t\t_exit(1);\n\t}\n}\n*\/\n\/\/ #cgo CFLAGS: -std=gnu11 -Wvla\nimport \"C\"\n\ntype cmdForkuevent struct {\n\tglobal *cmdGlobal\n}\n\nfunc (c *cmdForkuevent) Command() *cobra.Command {\n\t\/\/ Main subcommand\n\tcmd := &cobra.Command{}\n\tcmd.Use = \"forkuevent\"\n\tcmd.Short = \"Inject uevents into container's network namespace\"\n\tcmd.Long = `Description:\n  Inject uevent into a container's network namespace\n\n  This internal command is used to inject uevents into unprivileged container's\n  network namespaces.\n`\n\tcmd.Hidden = true\n\n\t\/\/ pull\n\tcmdInject := &cobra.Command{}\n\tcmdInject.Use = \"inject <PID> <len> <uevent parts>...\"\n\tcmdInject.Args = cobra.MinimumNArgs(3)\n\tcmdInject.RunE = c.Run\n\tcmd.AddCommand(cmdInject)\n\n\treturn cmd\n}\n\nfunc (c *cmdForkuevent) Run(cmd *cobra.Command, args []string) error {\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package ifname\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/influxdata\/telegraf\"\n\t\"github.com\/influxdata\/telegraf\/config\"\n\t\"github.com\/influxdata\/telegraf\/internal\"\n\t\"github.com\/influxdata\/telegraf\/internal\/snmp\"\n\t\"github.com\/influxdata\/telegraf\/plugins\/common\/parallel\"\n\tsi \"github.com\/influxdata\/telegraf\/plugins\/inputs\/snmp\"\n\t\"github.com\/influxdata\/telegraf\/plugins\/processors\"\n)\n\nvar sampleConfig = `\n  ## Name of tag holding the interface number\n  # tag = \"ifIndex\"\n\n  ## Name of output tag where service name will be added\n  # dest = \"ifName\"\n\n  ## Name of tag of the SNMP agent to request the interface name from\n  # agent = \"agent\"\n\n  ## Timeout for each request.\n  # timeout = \"5s\"\n\n  ## SNMP version; can be 1, 2, or 3.\n  # version = 2\n\n  ## SNMP community string.\n  # community = \"public\"\n\n  ## Number of retries to attempt.\n  # retries = 3\n\n  ## The GETBULK max-repetitions parameter.\n  # max_repetitions = 10\n\n  ## SNMPv3 authentication and encryption options.\n  ##\n  ## Security Name.\n  # sec_name = \"myuser\"\n  ## Authentication protocol; one of \"MD5\", \"SHA\", or \"\".\n  # auth_protocol = \"MD5\"\n  ## Authentication password.\n  # auth_password = \"pass\"\n  ## Security Level; one of \"noAuthNoPriv\", \"authNoPriv\", or \"authPriv\".\n  # sec_level = \"authNoPriv\"\n  ## Context Name.\n  # context_name = \"\"\n  ## Privacy protocol used for encrypted messages; one of \"DES\", \"AES\" or \"\".\n  # priv_protocol = \"\"\n  ## Privacy password used for encrypted messages.\n  # priv_password = \"\"\n\n  ## max_parallel_lookups is the maximum number of SNMP requests to\n  ## make at the same time.\n  # max_parallel_lookups = 100\n\n  ## ordered controls whether or not the metrics need to stay in the\n  ## same order this plugin received them in. If false, this plugin\n  ## may change the order when data is cached.  If you need metrics to\n  ## stay in order set this to true.  keeping the metrics ordered may\n  ## be slightly slower\n  # ordered = false\n\n  ## cache_ttl is the amount of time interface names are cached for a\n  ## given agent.  After this period elapses if names are needed they\n  ## will be retrieved again.\n  # cache_ttl = \"8h\"\n`\n\ntype nameMap map[uint64]string\ntype keyType = string\ntype valType = nameMap\n\ntype mapFunc func(agent string) (nameMap, error)\ntype makeTableFunc func(string) (*si.Table, error)\n\ntype sigMap map[string](chan struct{})\n\ntype IfName struct {\n\tSourceTag string `toml:\"tag\"`\n\tDestTag   string `toml:\"dest\"`\n\tAgentTag  string `toml:\"agent\"`\n\n\tsnmp.ClientConfig\n\n\tCacheSize          uint            `toml:\"max_cache_entries\"`\n\tMaxParallelLookups int             `toml:\"max_parallel_lookups\"`\n\tOrdered            bool            `toml:\"ordered\"`\n\tCacheTTL           config.Duration `toml:\"cache_ttl\"`\n\n\tLog telegraf.Logger `toml:\"-\"`\n\n\tifTable  *si.Table `toml:\"-\"`\n\tifXTable *si.Table `toml:\"-\"`\n\n\trwLock sync.RWMutex `toml:\"-\"`\n\tcache  *TTLCache    `toml:\"-\"`\n\n\tparallel parallel.Parallel    `toml:\"-\"`\n\tacc      telegraf.Accumulator `toml:\"-\"`\n\n\tgetMapRemote mapFunc       `toml:\"-\"`\n\tmakeTable    makeTableFunc `toml:\"-\"`\n\n\tgsBase snmp.GosnmpWrapper `toml:\"-\"`\n\n\tsigs sigMap `toml:\"-\"`\n}\n\nconst minRetry time.Duration = 5 * time.Minute\n\nfunc (d *IfName) SampleConfig() string {\n\treturn sampleConfig\n}\n\nfunc (d *IfName) Description() string {\n\treturn \"Add a tag of the network interface name looked up over SNMP by interface number\"\n}\n\nfunc (d *IfName) Init() error {\n\td.getMapRemote = d.getMapRemoteNoMock\n\td.makeTable = makeTableNoMock\n\n\tc := NewTTLCache(time.Duration(d.CacheTTL), d.CacheSize)\n\td.cache = &c\n\n\td.sigs = make(sigMap)\n\n\treturn nil\n}\n\nfunc (d *IfName) addTag(metric telegraf.Metric) error {\n\tagent, ok := metric.GetTag(d.AgentTag)\n\tif !ok {\n\t\td.Log.Warn(\"Agent tag missing.\")\n\t\treturn nil\n\t}\n\n\tnum_s, ok := metric.GetTag(d.SourceTag)\n\tif !ok {\n\t\td.Log.Warn(\"Source tag missing.\")\n\t\treturn nil\n\t}\n\n\tnum, err := strconv.ParseUint(num_s, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't parse source tag as uint\")\n\t}\n\n\tfirstTime := true\n\tfor {\n\t\tm, age, err := d.getMap(agent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't retrieve the table of interface names: %w\", err)\n\t\t}\n\n\t\tname, found := m[num]\n\t\tif found {\n\t\t\t\/\/ success\n\t\t\tmetric.AddTag(d.DestTag, name)\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ We have the agent's interface map but it doesn't contain\n\t\t\/\/ the interface we're interested in.  If the entry is old\n\t\t\/\/ enough, retrieve it from the agent once more.\n\t\tif age < minRetry {\n\t\t\treturn fmt.Errorf(\"interface number %d isn't in the table of interface names\", num)\n\t\t}\n\n\t\tif firstTime {\n\t\t\td.invalidate(agent)\n\t\t\tfirstTime = false\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ not found, cache hit, retrying\n\t\treturn fmt.Errorf(\"missing interface but couldn't retrieve table\")\n\t}\n}\n\nfunc (d *IfName) invalidate(agent string) {\n\td.rwLock.RLock()\n\td.cache.Delete(agent)\n\td.rwLock.RUnlock()\n}\n\nfunc (d *IfName) Start(acc telegraf.Accumulator) error {\n\td.acc = acc\n\n\tvar err error\n\td.gsBase, err = snmp.NewWrapper(d.ClientConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing SNMP client config: %w\", err)\n\t}\n\n\td.ifTable, err = d.makeTable(\"IF-MIB::ifTable\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"looking up ifTable in local MIB: %w\", err)\n\t}\n\td.ifXTable, err = d.makeTable(\"IF-MIB::ifXTable\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"looking up ifXTable in local MIB: %w\", err)\n\t}\n\n\tfn := func(m telegraf.Metric) []telegraf.Metric {\n\t\terr := d.addTag(m)\n\t\tif err != nil {\n\t\t\td.Log.Debugf(\"Error adding tag %v\", err)\n\t\t}\n\t\treturn []telegraf.Metric{m}\n\t}\n\n\tif d.Ordered {\n\t\td.parallel = parallel.NewOrdered(acc, fn, 10000, d.MaxParallelLookups)\n\t} else {\n\t\td.parallel = parallel.NewUnordered(acc, fn, d.MaxParallelLookups)\n\t}\n\treturn nil\n}\n\nfunc (d *IfName) Add(metric telegraf.Metric, acc telegraf.Accumulator) error {\n\td.parallel.Enqueue(metric)\n\treturn nil\n}\n\nfunc (d *IfName) Stop() error {\n\td.parallel.Stop()\n\treturn nil\n}\n\n\/\/ getMap gets the interface names map either from cache or from the SNMP\n\/\/ agent\nfunc (d *IfName) getMap(agent string) (entry nameMap, age time.Duration, err error) {\n\tvar sig chan struct{}\n\n\t\/\/ Check cache\n\td.rwLock.RLock()\n\tm, ok, age := d.cache.Get(agent)\n\td.rwLock.RUnlock()\n\tif ok {\n\t\treturn m, age, nil\n\t}\n\n\t\/\/ Is this the first request for this agent?\n\td.rwLock.Lock()\n\tsig, found := d.sigs[agent]\n\tif !found {\n\t\ts := make(chan struct{})\n\t\td.sigs[agent] = s\n\t\tsig = s\n\t}\n\td.rwLock.Unlock()\n\n\tif found {\n\t\t\/\/ This is not the first request.  Wait for first to finish.\n\t\t<-sig\n\t\t\/\/ Check cache again\n\t\td.rwLock.RLock()\n\t\tm, ok, age := d.cache.Get(agent)\n\t\td.rwLock.RUnlock()\n\t\tif ok {\n\t\t\treturn m, age, nil\n\t\t}\n\t\treturn nil, 0, fmt.Errorf(\"getting remote table from cache\")\n\t}\n\n\t\/\/ The cache missed and this is the first request for this\n\t\/\/ agent.\n\n\t\/\/ Make the SNMP request\n\tm, err = d.getMapRemote(agent)\n\tif err != nil {\n\t\t\/\/failure.  signal without saving to cache\n\t\td.rwLock.Lock()\n\t\tclose(sig)\n\t\tdelete(d.sigs, agent)\n\t\td.rwLock.Unlock()\n\n\t\treturn nil, 0, fmt.Errorf(\"getting remote table: %w\", err)\n\t}\n\n\t\/\/ Cache it, then signal any other waiting requests for this agent\n\t\/\/ and clean up\n\td.rwLock.Lock()\n\td.cache.Put(agent, m)\n\tclose(sig)\n\tdelete(d.sigs, agent)\n\td.rwLock.Unlock()\n\n\treturn m, 0, nil\n}\n\nfunc (d *IfName) getMapRemoteNoMock(agent string) (nameMap, error) {\n\tgs := d.gsBase\n\terr := gs.SetAgent(agent)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing agent tag: %w\", err)\n\t}\n\n\terr = gs.Connect()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"connecting when fetching interface names: %w\", err)\n\t}\n\n\t\/\/try ifXtable and ifName first.  if that fails, fall back to\n\t\/\/ifTable and ifDescr\n\tvar m nameMap\n\tm, err = buildMap(gs, d.ifXTable, \"ifName\")\n\tif err == nil {\n\t\treturn m, nil\n\t}\n\n\tm, err = buildMap(gs, d.ifTable, \"ifDescr\")\n\tif err == nil {\n\t\treturn m, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"fetching interface names: %w\", err)\n}\n\nfunc init() {\n\tprocessors.AddStreaming(\"ifname\", func() telegraf.StreamingProcessor {\n\t\treturn &IfName{\n\t\t\tSourceTag:          \"ifIndex\",\n\t\t\tDestTag:            \"ifName\",\n\t\t\tAgentTag:           \"agent\",\n\t\t\tCacheSize:          100,\n\t\t\tMaxParallelLookups: 100,\n\t\t\tClientConfig: snmp.ClientConfig{\n\t\t\t\tRetries:        3,\n\t\t\t\tMaxRepetitions: 10,\n\t\t\t\tTimeout:        internal.Duration{Duration: 5 * time.Second},\n\t\t\t\tVersion:        2,\n\t\t\t\tCommunity:      \"public\",\n\t\t\t},\n\t\t\tCacheTTL: config.Duration(8 * time.Hour),\n\t\t}\n\t})\n}\n\nfunc makeTableNoMock(tableName string) (*si.Table, error) {\n\tvar err error\n\ttab := si.Table{\n\t\tOid:        tableName,\n\t\tIndexAsTag: true,\n\t}\n\n\terr = tab.Init()\n\tif err != nil {\n\t\t\/\/Init already wraps\n\t\treturn nil, err\n\t}\n\n\treturn &tab, nil\n}\n\nfunc buildMap(gs snmp.GosnmpWrapper, tab *si.Table, column string) (nameMap, error) {\n\tvar err error\n\n\trtab, err := tab.Build(gs, true)\n\tif err != nil {\n\t\t\/\/Build already wraps\n\t\treturn nil, err\n\t}\n\n\tif len(rtab.Rows) == 0 {\n\t\treturn nil, fmt.Errorf(\"empty table\")\n\t}\n\n\tt := make(nameMap)\n\tfor _, v := range rtab.Rows {\n\t\ti_str, ok := v.Tags[\"index\"]\n\t\tif !ok {\n\t\t\t\/\/should always have an index tag because the table should\n\t\t\t\/\/always have IndexAsTag true\n\t\t\treturn nil, fmt.Errorf(\"no index tag\")\n\t\t}\n\t\ti, err := strconv.ParseUint(i_str, 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"index tag isn't a uint\")\n\t\t}\n\t\tname_if, ok := v.Fields[column]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"field %s is missing\", column)\n\t\t}\n\t\tname, ok := name_if.(string)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"field %s isn't a string\", column)\n\t\t}\n\n\t\tt[i] = name\n\t}\n\treturn t, nil\n}\n<commit_msg>Fix mutex locking around ifname cache  (#8873)<commit_after>package ifname\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/influxdata\/telegraf\"\n\t\"github.com\/influxdata\/telegraf\/config\"\n\t\"github.com\/influxdata\/telegraf\/internal\"\n\t\"github.com\/influxdata\/telegraf\/internal\/snmp\"\n\t\"github.com\/influxdata\/telegraf\/plugins\/common\/parallel\"\n\tsi \"github.com\/influxdata\/telegraf\/plugins\/inputs\/snmp\"\n\t\"github.com\/influxdata\/telegraf\/plugins\/processors\"\n)\n\nvar sampleConfig = `\n  ## Name of tag holding the interface number\n  # tag = \"ifIndex\"\n\n  ## Name of output tag where service name will be added\n  # dest = \"ifName\"\n\n  ## Name of tag of the SNMP agent to request the interface name from\n  # agent = \"agent\"\n\n  ## Timeout for each request.\n  # timeout = \"5s\"\n\n  ## SNMP version; can be 1, 2, or 3.\n  # version = 2\n\n  ## SNMP community string.\n  # community = \"public\"\n\n  ## Number of retries to attempt.\n  # retries = 3\n\n  ## The GETBULK max-repetitions parameter.\n  # max_repetitions = 10\n\n  ## SNMPv3 authentication and encryption options.\n  ##\n  ## Security Name.\n  # sec_name = \"myuser\"\n  ## Authentication protocol; one of \"MD5\", \"SHA\", or \"\".\n  # auth_protocol = \"MD5\"\n  ## Authentication password.\n  # auth_password = \"pass\"\n  ## Security Level; one of \"noAuthNoPriv\", \"authNoPriv\", or \"authPriv\".\n  # sec_level = \"authNoPriv\"\n  ## Context Name.\n  # context_name = \"\"\n  ## Privacy protocol used for encrypted messages; one of \"DES\", \"AES\" or \"\".\n  # priv_protocol = \"\"\n  ## Privacy password used for encrypted messages.\n  # priv_password = \"\"\n\n  ## max_parallel_lookups is the maximum number of SNMP requests to\n  ## make at the same time.\n  # max_parallel_lookups = 100\n\n  ## ordered controls whether or not the metrics need to stay in the\n  ## same order this plugin received them in. If false, this plugin\n  ## may change the order when data is cached.  If you need metrics to\n  ## stay in order set this to true.  keeping the metrics ordered may\n  ## be slightly slower\n  # ordered = false\n\n  ## cache_ttl is the amount of time interface names are cached for a\n  ## given agent.  After this period elapses if names are needed they\n  ## will be retrieved again.\n  # cache_ttl = \"8h\"\n`\n\ntype nameMap map[uint64]string\ntype keyType = string\ntype valType = nameMap\n\ntype mapFunc func(agent string) (nameMap, error)\ntype makeTableFunc func(string) (*si.Table, error)\n\ntype sigMap map[string](chan struct{})\n\ntype IfName struct {\n\tSourceTag string `toml:\"tag\"`\n\tDestTag   string `toml:\"dest\"`\n\tAgentTag  string `toml:\"agent\"`\n\n\tsnmp.ClientConfig\n\n\tCacheSize          uint            `toml:\"max_cache_entries\"`\n\tMaxParallelLookups int             `toml:\"max_parallel_lookups\"`\n\tOrdered            bool            `toml:\"ordered\"`\n\tCacheTTL           config.Duration `toml:\"cache_ttl\"`\n\n\tLog telegraf.Logger `toml:\"-\"`\n\n\tifTable  *si.Table `toml:\"-\"`\n\tifXTable *si.Table `toml:\"-\"`\n\n\tlock  sync.Mutex `toml:\"-\"`\n\tcache *TTLCache  `toml:\"-\"`\n\n\tparallel parallel.Parallel    `toml:\"-\"`\n\tacc      telegraf.Accumulator `toml:\"-\"`\n\n\tgetMapRemote mapFunc       `toml:\"-\"`\n\tmakeTable    makeTableFunc `toml:\"-\"`\n\n\tgsBase snmp.GosnmpWrapper `toml:\"-\"`\n\n\tsigs sigMap `toml:\"-\"`\n}\n\nconst minRetry time.Duration = 5 * time.Minute\n\nfunc (d *IfName) SampleConfig() string {\n\treturn sampleConfig\n}\n\nfunc (d *IfName) Description() string {\n\treturn \"Add a tag of the network interface name looked up over SNMP by interface number\"\n}\n\nfunc (d *IfName) Init() error {\n\td.getMapRemote = d.getMapRemoteNoMock\n\td.makeTable = makeTableNoMock\n\n\tc := NewTTLCache(time.Duration(d.CacheTTL), d.CacheSize)\n\td.cache = &c\n\n\td.sigs = make(sigMap)\n\n\treturn nil\n}\n\nfunc (d *IfName) addTag(metric telegraf.Metric) error {\n\tagent, ok := metric.GetTag(d.AgentTag)\n\tif !ok {\n\t\td.Log.Warn(\"Agent tag missing.\")\n\t\treturn nil\n\t}\n\n\tnum_s, ok := metric.GetTag(d.SourceTag)\n\tif !ok {\n\t\td.Log.Warn(\"Source tag missing.\")\n\t\treturn nil\n\t}\n\n\tnum, err := strconv.ParseUint(num_s, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"couldn't parse source tag as uint\")\n\t}\n\n\tfirstTime := true\n\tfor {\n\t\tm, age, err := d.getMap(agent)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't retrieve the table of interface names: %w\", err)\n\t\t}\n\n\t\tname, found := m[num]\n\t\tif found {\n\t\t\t\/\/ success\n\t\t\tmetric.AddTag(d.DestTag, name)\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ We have the agent's interface map but it doesn't contain\n\t\t\/\/ the interface we're interested in.  If the entry is old\n\t\t\/\/ enough, retrieve it from the agent once more.\n\t\tif age < minRetry {\n\t\t\treturn fmt.Errorf(\"interface number %d isn't in the table of interface names\", num)\n\t\t}\n\n\t\tif firstTime {\n\t\t\td.invalidate(agent)\n\t\t\tfirstTime = false\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ not found, cache hit, retrying\n\t\treturn fmt.Errorf(\"missing interface but couldn't retrieve table\")\n\t}\n}\n\nfunc (d *IfName) invalidate(agent string) {\n\td.lock.Lock()\n\td.cache.Delete(agent)\n\td.lock.Unlock()\n}\n\nfunc (d *IfName) Start(acc telegraf.Accumulator) error {\n\td.acc = acc\n\n\tvar err error\n\td.gsBase, err = snmp.NewWrapper(d.ClientConfig)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"parsing SNMP client config: %w\", err)\n\t}\n\n\td.ifTable, err = d.makeTable(\"IF-MIB::ifTable\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"looking up ifTable in local MIB: %w\", err)\n\t}\n\td.ifXTable, err = d.makeTable(\"IF-MIB::ifXTable\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"looking up ifXTable in local MIB: %w\", err)\n\t}\n\n\tfn := func(m telegraf.Metric) []telegraf.Metric {\n\t\terr := d.addTag(m)\n\t\tif err != nil {\n\t\t\td.Log.Debugf(\"Error adding tag %v\", err)\n\t\t}\n\t\treturn []telegraf.Metric{m}\n\t}\n\n\tif d.Ordered {\n\t\td.parallel = parallel.NewOrdered(acc, fn, 10000, d.MaxParallelLookups)\n\t} else {\n\t\td.parallel = parallel.NewUnordered(acc, fn, d.MaxParallelLookups)\n\t}\n\treturn nil\n}\n\nfunc (d *IfName) Add(metric telegraf.Metric, acc telegraf.Accumulator) error {\n\td.parallel.Enqueue(metric)\n\treturn nil\n}\n\nfunc (d *IfName) Stop() error {\n\td.parallel.Stop()\n\treturn nil\n}\n\n\/\/ getMap gets the interface names map either from cache or from the SNMP\n\/\/ agent\nfunc (d *IfName) getMap(agent string) (entry nameMap, age time.Duration, err error) {\n\tvar sig chan struct{}\n\n\td.lock.Lock()\n\n\t\/\/ Check cache\n\tm, ok, age := d.cache.Get(agent)\n\tif ok {\n\t\td.lock.Unlock()\n\t\treturn m, age, nil\n\t}\n\n\t\/\/ cache miss.  Is this the first request for this agent?\n\tsig, found := d.sigs[agent]\n\tif !found {\n\t\t\/\/ This is the first request.  Make signal for subsequent requests to wait on\n\t\ts := make(chan struct{})\n\t\td.sigs[agent] = s\n\t\tsig = s\n\t}\n\n\td.lock.Unlock()\n\n\tif found {\n\t\t\/\/ This is not the first request.  Wait for first to finish.\n\t\t<-sig\n\n\t\t\/\/ Check cache again\n\t\td.lock.Lock()\n\t\tm, ok, age := d.cache.Get(agent)\n\t\td.lock.Unlock()\n\t\tif ok {\n\t\t\treturn m, age, nil\n\t\t}\n\t\treturn nil, 0, fmt.Errorf(\"getting remote table from cache\")\n\t}\n\n\t\/\/ The cache missed and this is the first request for this\n\t\/\/ agent. Make the SNMP request\n\tm, err = d.getMapRemote(agent)\n\n\td.lock.Lock()\n\tif err != nil {\n\t\t\/\/snmp failure.  signal without saving to cache\n\t\tclose(sig)\n\t\tdelete(d.sigs, agent)\n\n\t\td.lock.Unlock()\n\t\treturn nil, 0, fmt.Errorf(\"getting remote table: %w\", err)\n\t}\n\n\t\/\/ snmp success.  Cache response, then signal any other waiting\n\t\/\/ requests for this agent and clean up\n\td.cache.Put(agent, m)\n\tclose(sig)\n\tdelete(d.sigs, agent)\n\n\td.lock.Unlock()\n\treturn m, 0, nil\n}\n\nfunc (d *IfName) getMapRemoteNoMock(agent string) (nameMap, error) {\n\tgs := d.gsBase\n\terr := gs.SetAgent(agent)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing agent tag: %w\", err)\n\t}\n\n\terr = gs.Connect()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"connecting when fetching interface names: %w\", err)\n\t}\n\n\t\/\/try ifXtable and ifName first.  if that fails, fall back to\n\t\/\/ifTable and ifDescr\n\tvar m nameMap\n\tm, err = buildMap(gs, d.ifXTable, \"ifName\")\n\tif err == nil {\n\t\treturn m, nil\n\t}\n\n\tm, err = buildMap(gs, d.ifTable, \"ifDescr\")\n\tif err == nil {\n\t\treturn m, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"fetching interface names: %w\", err)\n}\n\nfunc init() {\n\tprocessors.AddStreaming(\"ifname\", func() telegraf.StreamingProcessor {\n\t\treturn &IfName{\n\t\t\tSourceTag:          \"ifIndex\",\n\t\t\tDestTag:            \"ifName\",\n\t\t\tAgentTag:           \"agent\",\n\t\t\tCacheSize:          100,\n\t\t\tMaxParallelLookups: 100,\n\t\t\tClientConfig: snmp.ClientConfig{\n\t\t\t\tRetries:        3,\n\t\t\t\tMaxRepetitions: 10,\n\t\t\t\tTimeout:        internal.Duration{Duration: 5 * time.Second},\n\t\t\t\tVersion:        2,\n\t\t\t\tCommunity:      \"public\",\n\t\t\t},\n\t\t\tCacheTTL: config.Duration(8 * time.Hour),\n\t\t}\n\t})\n}\n\nfunc makeTableNoMock(tableName string) (*si.Table, error) {\n\tvar err error\n\ttab := si.Table{\n\t\tOid:        tableName,\n\t\tIndexAsTag: true,\n\t}\n\n\terr = tab.Init()\n\tif err != nil {\n\t\t\/\/Init already wraps\n\t\treturn nil, err\n\t}\n\n\treturn &tab, nil\n}\n\nfunc buildMap(gs snmp.GosnmpWrapper, tab *si.Table, column string) (nameMap, error) {\n\tvar err error\n\n\trtab, err := tab.Build(gs, true)\n\tif err != nil {\n\t\t\/\/Build already wraps\n\t\treturn nil, err\n\t}\n\n\tif len(rtab.Rows) == 0 {\n\t\treturn nil, fmt.Errorf(\"empty table\")\n\t}\n\n\tt := make(nameMap)\n\tfor _, v := range rtab.Rows {\n\t\ti_str, ok := v.Tags[\"index\"]\n\t\tif !ok {\n\t\t\t\/\/should always have an index tag because the table should\n\t\t\t\/\/always have IndexAsTag true\n\t\t\treturn nil, fmt.Errorf(\"no index tag\")\n\t\t}\n\t\ti, err := strconv.ParseUint(i_str, 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"index tag isn't a uint\")\n\t\t}\n\t\tname_if, ok := v.Fields[column]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"field %s is missing\", column)\n\t\t}\n\t\tname, ok := name_if.(string)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"field %s isn't a string\", column)\n\t\t}\n\n\t\tt[i] = name\n\t}\n\treturn t, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package pxemgr\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/gorilla\/mux\"\n\t\"crypto\/x509\"\n\t\"crypto\/tls\"\n)\n\ntype EtcdNode struct {\n\tKey   string      `json:\"key\"`\n\tValue string      `json:\"value,omitempty\"`\n\tNodes []*EtcdNode `json:\"nodes,omitempty\"`\n\tDir   bool        `json:\"dir,omitempty\"`\n}\n\ntype EtcdResponse struct {\n\tAction string    `json:\"action\"`\n\tNode   *EtcdNode `json:\"node,omitempty\"`\n}\n\ntype EtcdResponseError struct {\n\tErrorCode int    `json:\"errorCode\"`\n\tMessage   string `json:\"message\"`\n\tCause     string `json:\"cause\"`\n}\n\nfunc (mgr *pxeManagerT) defineEtcdDiscoveryRoutes(etcdRouter *mux.Router) {\n\tetcdRouter.PathPrefix(\"\/new\").Methods(\"PUT\").HandlerFunc(mgr.etcdDiscoveryNewCluster)\n\n\ttokenRouter := etcdRouter.PathPrefix(\"\/{token:[a-f0-9]{32}}\").Subrouter()\n\ttokenRouter.PathPrefix(\"\/_config\/size\").Methods(\"GET\").HandlerFunc(mgr.etcdDiscoveryProxyHandler)\n\ttokenRouter.PathPrefix(\"\/_config\/size\").Methods(\"PUT\").HandlerFunc(mgr.etcdDiscoveryProxyHandler)\n\ttokenRouter.PathPrefix(\"\/{machine}\").Methods(\"PUT\").HandlerFunc(mgr.etcdDiscoveryProxyHandler)\n\ttokenRouter.PathPrefix(\"\/{machine}\").Methods(\"GET\").HandlerFunc(mgr.etcdDiscoveryProxyHandler)\n\ttokenRouter.PathPrefix(\"\/{machine}\").Methods(\"DELETE\").HandlerFunc(mgr.etcdDiscoveryProxyHandler)\n\ttokenRouter.Methods(\"GET\").HandlerFunc(mgr.etcdDiscoveryProxyHandler)\n\n\tetcdRouter.Methods(\"GET\").HandlerFunc(mgr.etcdDiscoveryHandler)\n}\n\nfunc (mgr *pxeManagerT) etcdDiscoveryHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(w, r,\n\t\t\"https:\/\/github.com\/giantswarm\/mayu\/blob\/master\/docs\/etcd-discovery.md\",\n\t\thttp.StatusMovedPermanently,\n\t)\n}\n\nfunc (mgr *pxeManagerT) etcdDiscoveryNewCluster(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\tsize := mgr.defaultEtcdQuorumSize\n\ts := r.FormValue(\"size\")\n\tif s != \"\" {\n\t\tsize, err = strconv.Atoi(s)\n\t\tif err != nil {\n\t\t\thttpError(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t}\n\n\ttoken, err := mgr.cluster.GenerateEtcdDiscoveryToken()\n\tif err != nil {\n\t\thttpError(w, fmt.Sprintf(\"Unable to generate token '%v'\", err), 400)\n\t\treturn\n\t}\n\n\terr = mgr.cluster.StoreEtcdDiscoveryToken(mgr.etcdEndpoint, mgr.etcdCAFile, token, size)\n\tif err != nil {\n\t\thttpError(w, fmt.Sprintf(\"Unable to store token in etcd '%v'\", err), 400)\n\t\treturn\n\t}\n\n\tglog.V(2).Infof(\"New cluster created '%s'\", token)\n\n\tfmt.Fprintf(w, \"%s\/%s\", mgr.etcdDiscoveryBaseURL(), token)\n}\n\nfunc (mgr *pxeManagerT) etcdDiscoveryBaseURL() string {\n\treturn fmt.Sprintf(\"%s\/etcd\", mgr.thisHost())\n}\n\nfunc (mgr *pxeManagerT) etcdDiscoveryProxyHandler(w http.ResponseWriter, r *http.Request) {\n\tresp, err := mgr.etcdDiscoveryProxyRequest(r)\n\tif err != nil {\n\t\thttpError(w, fmt.Sprintf(\"Error proxying request to etcd '%v'\", err), 500)\n\t}\n\n\tcopyHeader(w.Header(), resp.Header)\n\tw.WriteHeader(resp.StatusCode)\n\tio.Copy(w, resp.Body)\n}\n\nfunc (mgr *pxeManagerT) etcdDiscoveryProxyRequest(r *http.Request) (*http.Response, error) {\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar transport = http.DefaultTransport\n\n\tif strings.HasPrefix(mgr.etcdEndpoint, \"https\") && mgr.etcdCAFile != \"\" {\n\t\tcustomCA := x509.NewCertPool()\n\n\t\tpemData, err := ioutil.ReadFile(mgr.etcdCAFile)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"Unable to read custom CA file: \"+err.Error())\n\t\t}\n\t\tcustomCA.AppendCertsFromPEM(pemData)\n\t\ttransport = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{RootCAs:customCA},\n\t\t}\n\t}\n\n\tscheme := strings.Split(mgr.etcdEndpoint,\":\")[0]\n\thost := strings.Split(mgr.etcdEndpoint,\"\/\")[2]\n\n\tfor i := 0; i <= 10; i++ {\n\t\tu := url.URL{\n\t\t\tScheme:   scheme,\n\t\t\tHost:     host,\n\t\t\tPath:     path.Join(\"v2\", \"keys\", \"_etcd\", \"registry\", strings.TrimPrefix(r.URL.Path, \"\/etcd\")),\n\t\t\tRawQuery: r.URL.RawQuery,\n\t\t}\n\n\t\tbuf := bytes.NewBuffer(body)\n\t\tglog.V(2).Infof(\"Body '%s'\", body)\n\n\t\toutreq, err := http.NewRequest(r.Method, u.String(), buf)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcopyHeader(outreq.Header, r.Header)\n\n\t\tclient := http.Client{Transport:transport}\n\t\tresp, err := client.Do(outreq)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn resp, nil\n\t}\n\n\treturn nil, errors.New(\"All attempts at proxying to etcd failed\")\n}\n\n\/\/ copyHeader copies all of the headers from dst to src.\nfunc copyHeader(dst, src http.Header) {\n\tfor k, v := range src {\n\t\tfor _, q := range v {\n\t\t\tdst.Add(k, q)\n\t\t}\n\t}\n}\n<commit_msg>url parse<commit_after>package pxemgr\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/gorilla\/mux\"\n\t\"crypto\/x509\"\n\t\"crypto\/tls\"\n)\n\ntype EtcdNode struct {\n\tKey   string      `json:\"key\"`\n\tValue string      `json:\"value,omitempty\"`\n\tNodes []*EtcdNode `json:\"nodes,omitempty\"`\n\tDir   bool        `json:\"dir,omitempty\"`\n}\n\ntype EtcdResponse struct {\n\tAction string    `json:\"action\"`\n\tNode   *EtcdNode `json:\"node,omitempty\"`\n}\n\ntype EtcdResponseError struct {\n\tErrorCode int    `json:\"errorCode\"`\n\tMessage   string `json:\"message\"`\n\tCause     string `json:\"cause\"`\n}\n\nfunc (mgr *pxeManagerT) defineEtcdDiscoveryRoutes(etcdRouter *mux.Router) {\n\tetcdRouter.PathPrefix(\"\/new\").Methods(\"PUT\").HandlerFunc(mgr.etcdDiscoveryNewCluster)\n\n\ttokenRouter := etcdRouter.PathPrefix(\"\/{token:[a-f0-9]{32}}\").Subrouter()\n\ttokenRouter.PathPrefix(\"\/_config\/size\").Methods(\"GET\").HandlerFunc(mgr.etcdDiscoveryProxyHandler)\n\ttokenRouter.PathPrefix(\"\/_config\/size\").Methods(\"PUT\").HandlerFunc(mgr.etcdDiscoveryProxyHandler)\n\ttokenRouter.PathPrefix(\"\/{machine}\").Methods(\"PUT\").HandlerFunc(mgr.etcdDiscoveryProxyHandler)\n\ttokenRouter.PathPrefix(\"\/{machine}\").Methods(\"GET\").HandlerFunc(mgr.etcdDiscoveryProxyHandler)\n\ttokenRouter.PathPrefix(\"\/{machine}\").Methods(\"DELETE\").HandlerFunc(mgr.etcdDiscoveryProxyHandler)\n\ttokenRouter.Methods(\"GET\").HandlerFunc(mgr.etcdDiscoveryProxyHandler)\n\n\tetcdRouter.Methods(\"GET\").HandlerFunc(mgr.etcdDiscoveryHandler)\n}\n\nfunc (mgr *pxeManagerT) etcdDiscoveryHandler(w http.ResponseWriter, r *http.Request) {\n\thttp.Redirect(w, r,\n\t\t\"https:\/\/github.com\/giantswarm\/mayu\/blob\/master\/docs\/etcd-discovery.md\",\n\t\thttp.StatusMovedPermanently,\n\t)\n}\n\nfunc (mgr *pxeManagerT) etcdDiscoveryNewCluster(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\tsize := mgr.defaultEtcdQuorumSize\n\ts := r.FormValue(\"size\")\n\tif s != \"\" {\n\t\tsize, err = strconv.Atoi(s)\n\t\tif err != nil {\n\t\t\thttpError(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t}\n\n\ttoken, err := mgr.cluster.GenerateEtcdDiscoveryToken()\n\tif err != nil {\n\t\thttpError(w, fmt.Sprintf(\"Unable to generate token '%v'\", err), 400)\n\t\treturn\n\t}\n\n\terr = mgr.cluster.StoreEtcdDiscoveryToken(mgr.etcdEndpoint, mgr.etcdCAFile, token, size)\n\tif err != nil {\n\t\thttpError(w, fmt.Sprintf(\"Unable to store token in etcd '%v'\", err), 400)\n\t\treturn\n\t}\n\n\tglog.V(2).Infof(\"New cluster created '%s'\", token)\n\n\tfmt.Fprintf(w, \"%s\/%s\", mgr.etcdDiscoveryBaseURL(), token)\n}\n\nfunc (mgr *pxeManagerT) etcdDiscoveryBaseURL() string {\n\treturn fmt.Sprintf(\"%s\/etcd\", mgr.thisHost())\n}\n\nfunc (mgr *pxeManagerT) etcdDiscoveryProxyHandler(w http.ResponseWriter, r *http.Request) {\n\tresp, err := mgr.etcdDiscoveryProxyRequest(r)\n\tif err != nil {\n\t\thttpError(w, fmt.Sprintf(\"Error proxying request to etcd '%v'\", err), 500)\n\t}\n\n\tcopyHeader(w.Header(), resp.Header)\n\tw.WriteHeader(resp.StatusCode)\n\tio.Copy(w, resp.Body)\n}\n\nfunc (mgr *pxeManagerT) etcdDiscoveryProxyRequest(r *http.Request) (*http.Response, error) {\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar transport = http.DefaultTransport\n\n\tif strings.HasPrefix(mgr.etcdEndpoint, \"https\") && mgr.etcdCAFile != \"\" {\n\t\tcustomCA := x509.NewCertPool()\n\n\t\tpemData, err := ioutil.ReadFile(mgr.etcdCAFile)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"unable to read custom CA file: \"+err.Error())\n\t\t}\n\t\tcustomCA.AppendCertsFromPEM(pemData)\n\t\ttransport = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{RootCAs:customCA},\n\t\t}\n\t}\n\n\tu, err := url.Parse(mgr.etcdEndpoint)\n\tif err != nil {\n\t\tnil, errors.New(\"invalid etcd-endpoint: \"+err.Error())\n\t}\n\tu.Path = path.Join(\"v2\", \"keys\", \"_etcd\", \"registry\", strings.TrimPrefix(r.URL.Path, \"\/etcd\"))\n\tu.RawQuery = r.URL.RawQuery\n\n\tfor i := 0; i <= 10; i++ {\n\n\t\tbuf := bytes.NewBuffer(body)\n\t\tglog.V(2).Infof(\"Body '%s'\", body)\n\n\t\toutreq, err := http.NewRequest(r.Method, u.String(), buf)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tcopyHeader(outreq.Header, r.Header)\n\n\t\tclient := http.Client{Transport:transport}\n\t\tresp, err := client.Do(outreq)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn resp, nil\n\t}\n\n\treturn nil, errors.New(\"All attempts at proxying to etcd failed\")\n}\n\n\/\/ copyHeader copies all of the headers from dst to src.\nfunc copyHeader(dst, src http.Header) {\n\tfor k, v := range src {\n\t\tfor _, q := range v {\n\t\t\tdst.Add(k, q)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package bdiscord\n\nimport (\n\t\"bytes\"\n\t\"github.com\/42wim\/matterbridge\/bridge\/config\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/bwmarrin\/discordgo\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype bdiscord struct {\n\tc              *discordgo.Session\n\tConfig         *config.Protocol\n\tRemote         chan config.Message\n\tAccount        string\n\tChannels       []*discordgo.Channel\n\tNick           string\n\tUseChannelID   bool\n\tuserMemberMap  map[string]*discordgo.Member\n\tguildID        string\n\twebhookID      string\n\twebhookToken   string\n\tchannelInfoMap map[string]*config.ChannelInfo\n\tsync.RWMutex\n}\n\nvar flog *log.Entry\nvar protocol = \"discord\"\n\nfunc init() {\n\tflog = log.WithFields(log.Fields{\"module\": protocol})\n}\n\nfunc New(cfg config.Protocol, account string, c chan config.Message) *bdiscord {\n\tb := &bdiscord{}\n\tb.Config = &cfg\n\tb.Remote = c\n\tb.Account = account\n\tb.userMemberMap = make(map[string]*discordgo.Member)\n\tb.channelInfoMap = make(map[string]*config.ChannelInfo)\n\tif b.Config.WebhookURL != \"\" {\n\t\tflog.Debug(\"Configuring Discord Incoming Webhook\")\n\t\tb.webhookID, b.webhookToken = b.splitURL(b.Config.WebhookURL)\n\t}\n\treturn b\n}\n\nfunc (b *bdiscord) Connect() error {\n\tvar err error\n\tflog.Info(\"Connecting\")\n\tif b.Config.WebhookURL == \"\" {\n\t\tflog.Info(\"Connecting using token\")\n\t} else {\n\t\tflog.Info(\"Connecting using webhookurl (for posting) and token\")\n\t}\n\tif !strings.HasPrefix(b.Config.Token, \"Bot \") {\n\t\tb.Config.Token = \"Bot \" + b.Config.Token\n\t}\n\tb.c, err = discordgo.New(b.Config.Token)\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tflog.Info(\"Connection succeeded\")\n\tb.c.AddHandler(b.messageCreate)\n\tb.c.AddHandler(b.memberUpdate)\n\tb.c.AddHandler(b.messageUpdate)\n\tb.c.AddHandler(b.messageDelete)\n\terr = b.c.Open()\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tguilds, err := b.c.UserGuilds(100, \"\", \"\")\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tuserinfo, err := b.c.User(\"@me\")\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tb.Nick = userinfo.Username\n\tfor _, guild := range guilds {\n\t\tif guild.Name == b.Config.Server {\n\t\t\tb.Channels, err = b.c.GuildChannels(guild.ID)\n\t\t\tb.guildID = guild.ID\n\t\t\tif err != nil {\n\t\t\t\tflog.Debugf(\"%#v\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (b *bdiscord) Disconnect() error {\n\treturn nil\n}\n\nfunc (b *bdiscord) JoinChannel(channel config.ChannelInfo) error {\n\tb.channelInfoMap[channel.ID] = &channel\n\tidcheck := strings.Split(channel.Name, \"ID:\")\n\tif len(idcheck) > 1 {\n\t\tb.UseChannelID = true\n\t}\n\treturn nil\n}\n\nfunc (b *bdiscord) Send(msg config.Message) (string, error) {\n\tflog.Debugf(\"Receiving %#v\", msg)\n\tchannelID := b.getChannelID(msg.Channel)\n\tif channelID == \"\" {\n\t\tflog.Errorf(\"Could not find channelID for %v\", msg.Channel)\n\t\treturn \"\", nil\n\t}\n\tif msg.Event == config.EVENT_USER_ACTION {\n\t\tmsg.Text = \"_\" + msg.Text + \"_\"\n\t}\n\n\twID := b.webhookID\n\twToken := b.webhookToken\n\tif ci, ok := b.channelInfoMap[msg.Channel+b.Account]; ok {\n\t\tif ci.Options.WebhookURL != \"\" {\n\t\t\twID, wToken = b.splitURL(ci.Options.WebhookURL)\n\t\t}\n\t}\n\n\tif wID == \"\" {\n\t\tflog.Debugf(\"Broadcasting using token (API)\")\n\t\tif msg.Event == config.EVENT_MSG_DELETE {\n\t\t\tif msg.ID == \"\" {\n\t\t\t\treturn \"\", nil\n\t\t\t}\n\t\t\terr := b.c.ChannelMessageDelete(channelID, msg.ID)\n\t\t\treturn \"\", err\n\t\t}\n\t\tif msg.ID != \"\" {\n\t\t\t_, err := b.c.ChannelMessageEdit(channelID, msg.ID, msg.Username+msg.Text)\n\t\t\treturn msg.ID, err\n\t\t}\n\n\t\tif msg.Extra != nil {\n\t\t\t\/\/ check if we have files to upload (from slack, telegram or mattermost)\n\t\t\tif len(msg.Extra[\"file\"]) > 0 {\n\t\t\t\tvar err error\n\t\t\t\tvar res *discordgo.Message\n\t\t\t\tfor _, f := range msg.Extra[\"file\"] {\n\t\t\t\t\tfi := f.(config.FileInfo)\n\t\t\t\t\tfiles := []*discordgo.File{}\n\t\t\t\t\tfiles = append(files, &discordgo.File{fi.Name, \"\", bytes.NewReader(*fi.Data)})\n\t\t\t\t\tres, err = b.c.ChannelMessageSendComplex(channelID, &discordgo.MessageSend{Content: msg.Text, Files: files})\n\t\t\t\t}\n\t\t\t\treturn res.ID, err\n\t\t\t}\n\t\t}\n\t\tres, err := b.c.ChannelMessageSend(channelID, msg.Username+msg.Text)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn res.ID, err\n\t}\n\tflog.Debugf(\"Broadcasting using Webhook\")\n\terr := b.c.WebhookExecute(\n\t\twID,\n\t\twToken,\n\t\ttrue,\n\t\t&discordgo.WebhookParams{\n\t\t\tContent:   msg.Text,\n\t\t\tUsername:  msg.Username,\n\t\t\tAvatarURL: msg.Avatar,\n\t\t})\n\treturn \"\", err\n}\n\nfunc (b *bdiscord) messageDelete(s *discordgo.Session, m *discordgo.MessageDelete) {\n\trmsg := config.Message{Account: b.Account, ID: m.ID, Event: config.EVENT_MSG_DELETE, Text: config.EVENT_MSG_DELETE}\n\trmsg.Channel = b.getChannelName(m.ChannelID)\n\tif b.UseChannelID {\n\t\trmsg.Channel = \"ID:\" + m.ChannelID\n\t}\n\tflog.Debugf(\"Sending message from %s to gateway\", b.Account)\n\tflog.Debugf(\"Message is %#v\", rmsg)\n\tb.Remote <- rmsg\n}\n\nfunc (b *bdiscord) messageUpdate(s *discordgo.Session, m *discordgo.MessageUpdate) {\n\tif b.Config.EditDisable {\n\t\treturn\n\t}\n\t\/\/ only when message is actually edited\n\tif m.Message.EditedTimestamp != \"\" {\n\t\tflog.Debugf(\"Sending edit message\")\n\t\tm.Content = m.Content + b.Config.EditSuffix\n\t\tb.messageCreate(s, (*discordgo.MessageCreate)(m))\n\t}\n}\n\nfunc (b *bdiscord) messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {\n\t\/\/ not relay our own messages\n\tif m.Author.Username == b.Nick {\n\t\treturn\n\t}\n\t\/\/ if using webhooks, do not relay if it's ours\n\tif b.useWebhook() && m.Author.Bot && b.isWebhookID(m.Author.ID) {\n\t\treturn\n\t}\n\n\tif len(m.Attachments) > 0 {\n\t\tfor _, attach := range m.Attachments {\n\t\t\tm.Content = m.Content + \"\\n\" + attach.URL\n\t\t}\n\t}\n\n\tvar text string\n\tif m.Content != \"\" {\n\t\tflog.Debugf(\"Receiving message %#v\", m.Message)\n\t\tif len(m.MentionRoles) > 0 {\n\t\t\tm.Message.Content = b.replaceRoleMentions(m.Message.Content)\n\t\t}\n\t\tm.Message.Content = b.stripCustomoji(m.Message.Content)\n\t\tm.Message.Content = b.replaceChannelMentions(m.Message.Content)\n\t\ttext = m.ContentWithMentionsReplaced()\n\t}\n\n\trmsg := config.Message{Account: b.Account, Avatar: \"https:\/\/cdn.discordapp.com\/avatars\/\" + m.Author.ID + \"\/\" + m.Author.Avatar + \".jpg\",\n\t\tUserID: m.Author.ID, ID: m.ID}\n\n\trmsg.Channel = b.getChannelName(m.ChannelID)\n\tif b.UseChannelID {\n\t\trmsg.Channel = \"ID:\" + m.ChannelID\n\t}\n\n\tif !b.Config.UseUserName {\n\t\trmsg.Username = b.getNick(m.Author)\n\t} else {\n\t\trmsg.Username = m.Author.Username\n\t}\n\n\tif b.Config.ShowEmbeds && m.Message.Embeds != nil {\n\t\tfor _, embed := range m.Message.Embeds {\n\t\t\ttext = text + \"embed: \" + embed.Title + \" - \" + embed.Description + \" - \" + embed.URL + \"\\n\"\n\t\t}\n\t}\n\n\t\/\/ no empty messages\n\tif text == \"\" {\n\t\treturn\n\t}\n\n\ttext, ok := b.replaceAction(text)\n\tif ok {\n\t\trmsg.Event = config.EVENT_USER_ACTION\n\t}\n\n\trmsg.Text = text\n\tflog.Debugf(\"Sending message from %s on %s to gateway\", m.Author.Username, b.Account)\n\tflog.Debugf(\"Message is %#v\", rmsg)\n\tb.Remote <- rmsg\n}\n\nfunc (b *bdiscord) memberUpdate(s *discordgo.Session, m *discordgo.GuildMemberUpdate) {\n\tb.Lock()\n\tif _, ok := b.userMemberMap[m.Member.User.ID]; ok {\n\t\tflog.Debugf(\"%s: memberupdate: user %s (nick %s) changes nick to %s\", b.Account, m.Member.User.Username, b.userMemberMap[m.Member.User.ID].Nick, m.Member.Nick)\n\t}\n\tb.userMemberMap[m.Member.User.ID] = m.Member\n\tb.Unlock()\n}\n\nfunc (b *bdiscord) getNick(user *discordgo.User) string {\n\tvar err error\n\tb.Lock()\n\tdefer b.Unlock()\n\tif _, ok := b.userMemberMap[user.ID]; ok {\n\t\tif b.userMemberMap[user.ID] != nil {\n\t\t\tif b.userMemberMap[user.ID].Nick != \"\" {\n\t\t\t\t\/\/ only return if nick is set\n\t\t\t\treturn b.userMemberMap[user.ID].Nick\n\t\t\t}\n\t\t\t\/\/ otherwise return username\n\t\t\treturn user.Username\n\t\t}\n\t}\n\t\/\/ if we didn't find nick, search for it\n\tmember, err := b.c.GuildMember(b.guildID, user.ID)\n\tif err != nil {\n\t\treturn user.Username\n\t}\n\tb.userMemberMap[user.ID] = member\n\t\/\/ only return if nick is set\n\tif b.userMemberMap[user.ID].Nick != \"\" {\n\t\treturn b.userMemberMap[user.ID].Nick\n\t}\n\treturn user.Username\n}\n\nfunc (b *bdiscord) getChannelID(name string) string {\n\tidcheck := strings.Split(name, \"ID:\")\n\tif len(idcheck) > 1 {\n\t\treturn idcheck[1]\n\t}\n\tfor _, channel := range b.Channels {\n\t\tif channel.Name == name {\n\t\t\treturn channel.ID\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (b *bdiscord) getChannelName(id string) string {\n\tfor _, channel := range b.Channels {\n\t\tif channel.ID == id {\n\t\t\treturn channel.Name\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (b *bdiscord) replaceRoleMentions(text string) string {\n\troles, err := b.c.GuildRoles(b.guildID)\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", string(err.(*discordgo.RESTError).ResponseBody))\n\t\treturn text\n\t}\n\tfor _, role := range roles {\n\t\ttext = strings.Replace(text, \"<@&\"+role.ID+\">\", \"@\"+role.Name, -1)\n\t}\n\treturn text\n}\n\nfunc (b *bdiscord) replaceChannelMentions(text string) string {\n\tvar err error\n\tre := regexp.MustCompile(\"<#[0-9]+>\")\n\ttext = re.ReplaceAllStringFunc(text, func(m string) string {\n\t\tchannel := b.getChannelName(m[2 : len(m)-1])\n\t\t\/\/ if at first don't succeed, try again\n\t\tif channel == \"\" {\n\t\t\tb.Channels, err = b.c.GuildChannels(b.guildID)\n\t\t\tif err != nil {\n\t\t\t\treturn \"#unknownchannel\"\n\t\t\t}\n\t\t\tchannel = b.getChannelName(m[2 : len(m)-1])\n\t\t\treturn \"#\" + channel\n\t\t}\n\t\treturn \"#\" + channel\n\t})\n\treturn text\n}\n\nfunc (b *bdiscord) replaceAction(text string) (string, bool) {\n\tif strings.HasPrefix(text, \"_\") && strings.HasSuffix(text, \"_\") {\n\t\treturn strings.Replace(text, \"_\", \"\", -1), true\n\t}\n\treturn text, false\n}\n\nfunc (b *bdiscord) stripCustomoji(text string) string {\n\t\/\/ <:doge:302803592035958784>\n\tre := regexp.MustCompile(\"<(:.*?:)[0-9]+>\")\n\treturn re.ReplaceAllString(text, `$1`)\n}\n\n\/\/ splitURL splits a webhookURL and returns the id and token\nfunc (b *bdiscord) splitURL(url string) (string, string) {\n\twebhookURLSplit := strings.Split(url, \"\/\")\n\treturn webhookURLSplit[len(webhookURLSplit)-2], webhookURLSplit[len(webhookURLSplit)-1]\n}\n\n\/\/ useWebhook returns true if we have a webhook defined somewhere\nfunc (b *bdiscord) useWebhook() bool {\n\tif b.Config.WebhookURL != \"\" {\n\t\treturn true\n\t}\n\tfor _, channel := range b.channelInfoMap {\n\t\tif channel.Options.WebhookURL != \"\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ isWebhookID returns true if the specified id is used in a defined webhook\nfunc (b *bdiscord) isWebhookID(id string) bool {\n\tif b.Config.WebhookURL != \"\" {\n\t\twID, _ := b.splitURL(b.Config.WebhookURL)\n\t\tif wID == id {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, channel := range b.channelInfoMap {\n\t\tif channel.Options.WebhookURL != \"\" {\n\t\t\twID, _ := b.splitURL(channel.Options.WebhookURL)\n\t\t\tif wID == id {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>Show error message when file upload fails (discord)<commit_after>package bdiscord\n\nimport (\n\t\"bytes\"\n\t\"github.com\/42wim\/matterbridge\/bridge\/config\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/bwmarrin\/discordgo\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype bdiscord struct {\n\tc              *discordgo.Session\n\tConfig         *config.Protocol\n\tRemote         chan config.Message\n\tAccount        string\n\tChannels       []*discordgo.Channel\n\tNick           string\n\tUseChannelID   bool\n\tuserMemberMap  map[string]*discordgo.Member\n\tguildID        string\n\twebhookID      string\n\twebhookToken   string\n\tchannelInfoMap map[string]*config.ChannelInfo\n\tsync.RWMutex\n}\n\nvar flog *log.Entry\nvar protocol = \"discord\"\n\nfunc init() {\n\tflog = log.WithFields(log.Fields{\"module\": protocol})\n}\n\nfunc New(cfg config.Protocol, account string, c chan config.Message) *bdiscord {\n\tb := &bdiscord{}\n\tb.Config = &cfg\n\tb.Remote = c\n\tb.Account = account\n\tb.userMemberMap = make(map[string]*discordgo.Member)\n\tb.channelInfoMap = make(map[string]*config.ChannelInfo)\n\tif b.Config.WebhookURL != \"\" {\n\t\tflog.Debug(\"Configuring Discord Incoming Webhook\")\n\t\tb.webhookID, b.webhookToken = b.splitURL(b.Config.WebhookURL)\n\t}\n\treturn b\n}\n\nfunc (b *bdiscord) Connect() error {\n\tvar err error\n\tflog.Info(\"Connecting\")\n\tif b.Config.WebhookURL == \"\" {\n\t\tflog.Info(\"Connecting using token\")\n\t} else {\n\t\tflog.Info(\"Connecting using webhookurl (for posting) and token\")\n\t}\n\tif !strings.HasPrefix(b.Config.Token, \"Bot \") {\n\t\tb.Config.Token = \"Bot \" + b.Config.Token\n\t}\n\tb.c, err = discordgo.New(b.Config.Token)\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tflog.Info(\"Connection succeeded\")\n\tb.c.AddHandler(b.messageCreate)\n\tb.c.AddHandler(b.memberUpdate)\n\tb.c.AddHandler(b.messageUpdate)\n\tb.c.AddHandler(b.messageDelete)\n\terr = b.c.Open()\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tguilds, err := b.c.UserGuilds(100, \"\", \"\")\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tuserinfo, err := b.c.User(\"@me\")\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", err)\n\t\treturn err\n\t}\n\tb.Nick = userinfo.Username\n\tfor _, guild := range guilds {\n\t\tif guild.Name == b.Config.Server {\n\t\t\tb.Channels, err = b.c.GuildChannels(guild.ID)\n\t\t\tb.guildID = guild.ID\n\t\t\tif err != nil {\n\t\t\t\tflog.Debugf(\"%#v\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (b *bdiscord) Disconnect() error {\n\treturn nil\n}\n\nfunc (b *bdiscord) JoinChannel(channel config.ChannelInfo) error {\n\tb.channelInfoMap[channel.ID] = &channel\n\tidcheck := strings.Split(channel.Name, \"ID:\")\n\tif len(idcheck) > 1 {\n\t\tb.UseChannelID = true\n\t}\n\treturn nil\n}\n\nfunc (b *bdiscord) Send(msg config.Message) (string, error) {\n\tflog.Debugf(\"Receiving %#v\", msg)\n\tchannelID := b.getChannelID(msg.Channel)\n\tif channelID == \"\" {\n\t\tflog.Errorf(\"Could not find channelID for %v\", msg.Channel)\n\t\treturn \"\", nil\n\t}\n\tif msg.Event == config.EVENT_USER_ACTION {\n\t\tmsg.Text = \"_\" + msg.Text + \"_\"\n\t}\n\n\twID := b.webhookID\n\twToken := b.webhookToken\n\tif ci, ok := b.channelInfoMap[msg.Channel+b.Account]; ok {\n\t\tif ci.Options.WebhookURL != \"\" {\n\t\t\twID, wToken = b.splitURL(ci.Options.WebhookURL)\n\t\t}\n\t}\n\n\tif wID == \"\" {\n\t\tflog.Debugf(\"Broadcasting using token (API)\")\n\t\tif msg.Event == config.EVENT_MSG_DELETE {\n\t\t\tif msg.ID == \"\" {\n\t\t\t\treturn \"\", nil\n\t\t\t}\n\t\t\terr := b.c.ChannelMessageDelete(channelID, msg.ID)\n\t\t\treturn \"\", err\n\t\t}\n\t\tif msg.ID != \"\" {\n\t\t\t_, err := b.c.ChannelMessageEdit(channelID, msg.ID, msg.Username+msg.Text)\n\t\t\treturn msg.ID, err\n\t\t}\n\n\t\tif msg.Extra != nil {\n\t\t\t\/\/ check if we have files to upload (from slack, telegram or mattermost)\n\t\t\tif len(msg.Extra[\"file\"]) > 0 {\n\t\t\t\tvar err error\n\t\t\t\tfor _, f := range msg.Extra[\"file\"] {\n\t\t\t\t\tfi := f.(config.FileInfo)\n\t\t\t\t\tfiles := []*discordgo.File{}\n\t\t\t\t\tfiles = append(files, &discordgo.File{fi.Name, \"\", bytes.NewReader(*fi.Data)})\n\t\t\t\t\t_, err = b.c.ChannelMessageSendComplex(channelID, &discordgo.MessageSend{Content: msg.Text, Files: files})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tflog.Errorf(\"file upload failed: %#v\", err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tres, err := b.c.ChannelMessageSend(channelID, msg.Username+msg.Text)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn res.ID, err\n\t}\n\tflog.Debugf(\"Broadcasting using Webhook\")\n\terr := b.c.WebhookExecute(\n\t\twID,\n\t\twToken,\n\t\ttrue,\n\t\t&discordgo.WebhookParams{\n\t\t\tContent:   msg.Text,\n\t\t\tUsername:  msg.Username,\n\t\t\tAvatarURL: msg.Avatar,\n\t\t})\n\treturn \"\", err\n}\n\nfunc (b *bdiscord) messageDelete(s *discordgo.Session, m *discordgo.MessageDelete) {\n\trmsg := config.Message{Account: b.Account, ID: m.ID, Event: config.EVENT_MSG_DELETE, Text: config.EVENT_MSG_DELETE}\n\trmsg.Channel = b.getChannelName(m.ChannelID)\n\tif b.UseChannelID {\n\t\trmsg.Channel = \"ID:\" + m.ChannelID\n\t}\n\tflog.Debugf(\"Sending message from %s to gateway\", b.Account)\n\tflog.Debugf(\"Message is %#v\", rmsg)\n\tb.Remote <- rmsg\n}\n\nfunc (b *bdiscord) messageUpdate(s *discordgo.Session, m *discordgo.MessageUpdate) {\n\tif b.Config.EditDisable {\n\t\treturn\n\t}\n\t\/\/ only when message is actually edited\n\tif m.Message.EditedTimestamp != \"\" {\n\t\tflog.Debugf(\"Sending edit message\")\n\t\tm.Content = m.Content + b.Config.EditSuffix\n\t\tb.messageCreate(s, (*discordgo.MessageCreate)(m))\n\t}\n}\n\nfunc (b *bdiscord) messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {\n\t\/\/ not relay our own messages\n\tif m.Author.Username == b.Nick {\n\t\treturn\n\t}\n\t\/\/ if using webhooks, do not relay if it's ours\n\tif b.useWebhook() && m.Author.Bot && b.isWebhookID(m.Author.ID) {\n\t\treturn\n\t}\n\n\tif len(m.Attachments) > 0 {\n\t\tfor _, attach := range m.Attachments {\n\t\t\tm.Content = m.Content + \"\\n\" + attach.URL\n\t\t}\n\t}\n\n\tvar text string\n\tif m.Content != \"\" {\n\t\tflog.Debugf(\"Receiving message %#v\", m.Message)\n\t\tif len(m.MentionRoles) > 0 {\n\t\t\tm.Message.Content = b.replaceRoleMentions(m.Message.Content)\n\t\t}\n\t\tm.Message.Content = b.stripCustomoji(m.Message.Content)\n\t\tm.Message.Content = b.replaceChannelMentions(m.Message.Content)\n\t\ttext = m.ContentWithMentionsReplaced()\n\t}\n\n\trmsg := config.Message{Account: b.Account, Avatar: \"https:\/\/cdn.discordapp.com\/avatars\/\" + m.Author.ID + \"\/\" + m.Author.Avatar + \".jpg\",\n\t\tUserID: m.Author.ID, ID: m.ID}\n\n\trmsg.Channel = b.getChannelName(m.ChannelID)\n\tif b.UseChannelID {\n\t\trmsg.Channel = \"ID:\" + m.ChannelID\n\t}\n\n\tif !b.Config.UseUserName {\n\t\trmsg.Username = b.getNick(m.Author)\n\t} else {\n\t\trmsg.Username = m.Author.Username\n\t}\n\n\tif b.Config.ShowEmbeds && m.Message.Embeds != nil {\n\t\tfor _, embed := range m.Message.Embeds {\n\t\t\ttext = text + \"embed: \" + embed.Title + \" - \" + embed.Description + \" - \" + embed.URL + \"\\n\"\n\t\t}\n\t}\n\n\t\/\/ no empty messages\n\tif text == \"\" {\n\t\treturn\n\t}\n\n\ttext, ok := b.replaceAction(text)\n\tif ok {\n\t\trmsg.Event = config.EVENT_USER_ACTION\n\t}\n\n\trmsg.Text = text\n\tflog.Debugf(\"Sending message from %s on %s to gateway\", m.Author.Username, b.Account)\n\tflog.Debugf(\"Message is %#v\", rmsg)\n\tb.Remote <- rmsg\n}\n\nfunc (b *bdiscord) memberUpdate(s *discordgo.Session, m *discordgo.GuildMemberUpdate) {\n\tb.Lock()\n\tif _, ok := b.userMemberMap[m.Member.User.ID]; ok {\n\t\tflog.Debugf(\"%s: memberupdate: user %s (nick %s) changes nick to %s\", b.Account, m.Member.User.Username, b.userMemberMap[m.Member.User.ID].Nick, m.Member.Nick)\n\t}\n\tb.userMemberMap[m.Member.User.ID] = m.Member\n\tb.Unlock()\n}\n\nfunc (b *bdiscord) getNick(user *discordgo.User) string {\n\tvar err error\n\tb.Lock()\n\tdefer b.Unlock()\n\tif _, ok := b.userMemberMap[user.ID]; ok {\n\t\tif b.userMemberMap[user.ID] != nil {\n\t\t\tif b.userMemberMap[user.ID].Nick != \"\" {\n\t\t\t\t\/\/ only return if nick is set\n\t\t\t\treturn b.userMemberMap[user.ID].Nick\n\t\t\t}\n\t\t\t\/\/ otherwise return username\n\t\t\treturn user.Username\n\t\t}\n\t}\n\t\/\/ if we didn't find nick, search for it\n\tmember, err := b.c.GuildMember(b.guildID, user.ID)\n\tif err != nil {\n\t\treturn user.Username\n\t}\n\tb.userMemberMap[user.ID] = member\n\t\/\/ only return if nick is set\n\tif b.userMemberMap[user.ID].Nick != \"\" {\n\t\treturn b.userMemberMap[user.ID].Nick\n\t}\n\treturn user.Username\n}\n\nfunc (b *bdiscord) getChannelID(name string) string {\n\tidcheck := strings.Split(name, \"ID:\")\n\tif len(idcheck) > 1 {\n\t\treturn idcheck[1]\n\t}\n\tfor _, channel := range b.Channels {\n\t\tif channel.Name == name {\n\t\t\treturn channel.ID\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (b *bdiscord) getChannelName(id string) string {\n\tfor _, channel := range b.Channels {\n\t\tif channel.ID == id {\n\t\t\treturn channel.Name\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (b *bdiscord) replaceRoleMentions(text string) string {\n\troles, err := b.c.GuildRoles(b.guildID)\n\tif err != nil {\n\t\tflog.Debugf(\"%#v\", string(err.(*discordgo.RESTError).ResponseBody))\n\t\treturn text\n\t}\n\tfor _, role := range roles {\n\t\ttext = strings.Replace(text, \"<@&\"+role.ID+\">\", \"@\"+role.Name, -1)\n\t}\n\treturn text\n}\n\nfunc (b *bdiscord) replaceChannelMentions(text string) string {\n\tvar err error\n\tre := regexp.MustCompile(\"<#[0-9]+>\")\n\ttext = re.ReplaceAllStringFunc(text, func(m string) string {\n\t\tchannel := b.getChannelName(m[2 : len(m)-1])\n\t\t\/\/ if at first don't succeed, try again\n\t\tif channel == \"\" {\n\t\t\tb.Channels, err = b.c.GuildChannels(b.guildID)\n\t\t\tif err != nil {\n\t\t\t\treturn \"#unknownchannel\"\n\t\t\t}\n\t\t\tchannel = b.getChannelName(m[2 : len(m)-1])\n\t\t\treturn \"#\" + channel\n\t\t}\n\t\treturn \"#\" + channel\n\t})\n\treturn text\n}\n\nfunc (b *bdiscord) replaceAction(text string) (string, bool) {\n\tif strings.HasPrefix(text, \"_\") && strings.HasSuffix(text, \"_\") {\n\t\treturn strings.Replace(text, \"_\", \"\", -1), true\n\t}\n\treturn text, false\n}\n\nfunc (b *bdiscord) stripCustomoji(text string) string {\n\t\/\/ <:doge:302803592035958784>\n\tre := regexp.MustCompile(\"<(:.*?:)[0-9]+>\")\n\treturn re.ReplaceAllString(text, `$1`)\n}\n\n\/\/ splitURL splits a webhookURL and returns the id and token\nfunc (b *bdiscord) splitURL(url string) (string, string) {\n\twebhookURLSplit := strings.Split(url, \"\/\")\n\treturn webhookURLSplit[len(webhookURLSplit)-2], webhookURLSplit[len(webhookURLSplit)-1]\n}\n\n\/\/ useWebhook returns true if we have a webhook defined somewhere\nfunc (b *bdiscord) useWebhook() bool {\n\tif b.Config.WebhookURL != \"\" {\n\t\treturn true\n\t}\n\tfor _, channel := range b.channelInfoMap {\n\t\tif channel.Options.WebhookURL != \"\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ isWebhookID returns true if the specified id is used in a defined webhook\nfunc (b *bdiscord) isWebhookID(id string) bool {\n\tif b.Config.WebhookURL != \"\" {\n\t\twID, _ := b.splitURL(b.Config.WebhookURL)\n\t\tif wID == id {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, channel := range b.channelInfoMap {\n\t\tif channel.Options.WebhookURL != \"\" {\n\t\t\twID, _ := b.splitURL(channel.Options.WebhookURL)\n\t\t\tif wID == id {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package xSql\n\nimport (\n\t\"fmt\"\n\t\"github.com\/iostrovok\/go-iutils\/iutils\"\n\t\"log\"\n\t\"strings\"\n)\n\nvar MarkList = map[string]bool{\n\t\"&&\":    true,\n\t\"<\":     true,\n\t\"<=\":    true,\n\t\"<>\":    true,\n\t\"<@\":    true,\n\t\"=\":     true,\n\t\">\":     true,\n\t\">=\":    true,\n\t\"@>\":    true,\n\t\"ILIKE\": true,\n\t\"IN\":    true,\n\t\"IS\":    true,\n\t\"LIKE\":  true,\n\t\"RET\":   true,\n\t\"SQL\":   true,\n\t\"||\":    true,\n}\n\nvar LogicList = map[string]bool{\n\t\"AND\":    true,\n\t\"OR\":     true,\n\t\"INSERT\": true,\n\t\"UPDATE\": true,\n}\n\ntype One struct {\n\tData     []interface{}\n\tTable    string\n\tField    string\n\tMark     string\n\tAddParam string\n\tType     string \/\/ NoVals Array Where JSON\n}\n\nfunc Update(table string) *One {\n\tone := One{}\n\tone.Mark = \"UPDATE\"\n\tone.Table = table\n\treturn &one\n}\n\nfunc Insert(table string) *One {\n\tone := One{}\n\tone.Mark = \"INSERT\"\n\tone.Table = table\n\treturn &one\n}\n\nfunc IN(field string, data []interface{}) *One {\n\tone := One{}\n\tone.Data = data\n\tone.Mark = \"IN\"\n\tone.Field = field\n\n\treturn &one\n}\n\nfunc (one *One) CompUpdate() (string, []interface{}) {\n\tsUp := []string{}\n\tsRet := []string{}\n\n\tvalues := []interface{}{}\n\tsql_where := \"\"\n\n\tfor _, v := range one.Data {\n\t\tswitch v.(type) {\n\t\tcase *One:\n\t\t\tif v.(*One).Type == \"Where\" {\n\t\t\t\tsql, vals := v.(*One).Comp()\n\t\t\t\tif sql != \"\" {\n\t\t\t\t\tsql_where = \" WHERE \" + sql\n\t\t\t\t\tvalues = append(values, vals...)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tPoint := 1 + len(values)\n\n\tfor _, v := range one.Data {\n\t\tswitch v.(type) {\n\t\tcase *One:\n\t\t\tlog.Println(\"CompUpdate. v.(*One).Type: \" + v.(*One).Type)\n\n\t\t\tif v.(*One).Type == \"Where\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttp := v.(*One).Mark\n\n\t\t\tif tp == \"RET\" {\n\t\t\t\tsRet = append(sRet, v.(*One).Field)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif tp != \"=\" {\n\t\t\t\tlog.Fatalf(\"Comp. For update only \\\"=\\\" defined %v\\n\", v)\n\t\t\t}\n\n\t\t\tsql, vals := v.(*One).Comp(Point)\n\t\t\tPoint += len(vals)\n\t\t\tsUp = append(sUp, sql)\n\t\t\tvalues = append(values, vals...)\n\n\t\tdefault:\n\t\t\tlog.Printf(\"Comp. Not defined %T\\n\", v)\n\t\t\tlog.Fatalf(\"Comp. Not defined %v\\n\", v)\n\t\t}\n\t}\n\tret := \"\"\n\tif len(sRet) > 0 {\n\t\tret = \" RETURNING \" + strings.Join(sRet, \", \")\n\t}\n\tsql := strings.Join(sUp, \", \")\n\treturn \" UPDATE \" + one.Table + \" SET \" + sql + sql_where + ret, values\n}\n\nfunc (one *One) CompInsert() (string, []interface{}) {\n\tsIn := []string{}\n\tsVals := []string{}\n\tsRet := []string{}\n\tPoint := 1\n\tvalues := []interface{}{}\n\tfor _, v := range one.Data {\n\t\tswitch v.(type) {\n\t\tcase *One:\n\t\t\tlog.Println(\"CompInsert. v.(*One).Type: \" + v.(*One).Type)\n\n\t\t\ttp := v.(*One).Mark\n\n\t\t\tif tp == \"RET\" {\n\t\t\t\tsRet = append(sRet, v.(*One).Field)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsIn = append(sIn, v.(*One).Field)\n\t\t\tvals := v.(*One).Data\n\n\t\t\tif v.(*One).Type == \"Array\" {\n\t\t\t\ts, v := PrepareArray(v.(*One).AddParam, vals, Point)\n\t\t\t\tsVals = append(sVals, s)\n\t\t\t\tvalues = append(values, v...)\n\t\t\t\tPoint += len(v)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif len(vals) > 1 {\n\t\t\t\tlog.Fatalf(\"Comp. You can't INSERT multivalue params %T, %v\\n\", v, v)\n\t\t\t}\n\n\t\t\tif v.(*One).Type == \"JSON\" {\n\t\t\t\tvals = PrepareJsonVals(vals)\n\t\t\t}\n\n\t\t\tif tp == \"SQL\" {\n\t\t\t\tsVals = append(sVals, iutils.AnyToString(vals[0]))\n\t\t\t} else {\n\t\t\t\tsVals = append(sVals, fmt.Sprintf(\"$%d \", Point))\n\t\t\t\tPoint++\n\t\t\t\tvalues = append(values, vals...)\n\t\t\t}\n\n\t\tdefault:\n\t\t\tlog.Printf(\"Comp. Not defined %T\\n\", v)\n\t\t\tlog.Fatalf(\"Comp. Not defined %v\\n\", v)\n\t\t}\n\t}\n\tret := \"\"\n\tif len(sRet) > 0 {\n\t\tret = \" RETURNING \" + strings.Join(sRet, \", \")\n\t}\n\tsql := \"  ( \" + strings.Join(sIn, \", \") + \") VALUES (\" + strings.Join(sVals, \", \") + \")\"\n\treturn \" INSERT INTO \" + one.Table + sql + ret, values\n}\n\nfunc (one *One) Comp(PointIn ...int) (string, []interface{}) {\n\n\tPoint := 1\n\tif len(PointIn) > 0 {\n\t\tPoint = PointIn[0]\n\t}\n\tlog.Println(\"Comp. v.(*One).Type: \" + one.Type)\n\n\tsqlLine := \"\"\n\tvalues := []interface{}{}\n\n\tif one.Mark == \"INSERT\" {\n\t\tif Point > 1 {\n\t\t\tlog.Fatalf(\"Comp. You can't combination INSERT into other request\\n\")\n\t\t}\n\t\treturn one.CompInsert()\n\t}\n\n\tif one.Mark == \"UPDATE\" {\n\t\tif Point > 1 {\n\t\t\tlog.Fatalf(\"Comp. You can't combination INSERT into other request\\n\")\n\t\t}\n\t\treturn one.CompUpdate()\n\t}\n\n\tswitch one.Type {\n\tcase \"NoVals\":\n\t\treturn one.Field, values\n\tcase \"Array\":\n\t\treturn one.CompArray(Point)\n\tcase \"JSON\":\n\t\tone.Data = PrepareJsonVals(one.Data)\n\t}\n\n\tswitch one.Mark {\n\tcase \"AND\", \"OR\":\n\t\ts := []string{}\n\t\tfor _, v := range one.Data {\n\t\t\tswitch v.(type) {\n\t\t\tcase *One:\n\t\t\t\tsql, vals := v.(*One).Comp(Point)\n\t\t\t\ts = append(s, sql)\n\t\t\t\tif len(vals) > 0 {\n\t\t\t\t\tPoint += len(vals)\n\t\t\t\t\tvalues = append(values, vals...)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"Comp. Not defined %T\\n\", v)\n\t\t\t\tlog.Fatalf(\"Comp. Not defined %v\\n\", v)\n\t\t\t}\n\t\t}\n\t\tsqlLine = \"( \" + strings.Join(s, \" \"+one.Mark+\" \") + \") \"\n\tcase \"IN\":\n\t\ts := []string{}\n\t\ti := len(one.Data)\n\t\tfor {\n\t\t\ts = append(s, fmt.Sprintf(\" $%d \", Point))\n\t\t\tPoint++\n\t\t\ti--\n\t\t\tif i < 1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tsqlLine = fmt.Sprintf(\" %s IN ( %s ) \", one.Field, strings.Join(s, \", \"))\n\t\tvalues = one.Data\n\tcase \"IS\":\n\t\tsqlLine = one.Field + \" IS \" + iutils.AnyToString(one.Data[0])\n\tdefault:\n\t\tsqlLine = fmt.Sprintf(\" %s %s $%d \", one.Field, one.Mark, Point)\n\t\tPoint++\n\t\tvalues = append(values, one.Data[0])\n\t}\n\n\treturn sqlLine, values\n}\n\nfunc (one *One) Append(Nexters ...*One) *One {\n\tif _, find := LogicList[one.Mark]; !find {\n\t\tlog.Fatalf(\"Append. Bad type for append %s\\n\", one.Mark)\n\t}\n\tfor _, v := range Nexters {\n\t\tone.Data = append(one.Data, v)\n\t}\n\treturn one\n}\n\nfunc NLogic(mark string, Nexters ...*One) *One {\n\tone := One{}\n\tone.Logic(mark, Nexters...)\n\treturn &one\n}\n\nfunc (one *One) Logic(mark string, Nexters ...*One) {\n\n\tif _, find := LogicList[mark]; !find {\n\t\tlog.Fatalf(\"Logic. Not defined %s\\n\", mark)\n\t}\n\n\tone.Data = []interface{}{}\n\tfor _, v := range Nexters {\n\t\tone.Data = append(one.Data, v)\n\t}\n\tone.Mark = mark\n}\n\nfunc (one *One) Where(v *One) *One {\n\tv.Type = \"Where\"\n\tone.Data = append(one.Data, v)\n\treturn one\n}\n\n\/*\n\texample: where start_date > now()\n\tFunc(\"start_date\", \">\", \"now()\")\n*\/\nfunc Func(field string) *One {\n\tIn := One{}\n\n\tIn.Type = \"NoVals\"\n\tIn.Field = field\n\n\treturn &In\n}\n\nfunc Mark(field string, mark string, data ...interface{}) *One {\n\tIn := One{}\n\n\tif _, find := MarkList[mark]; find {\n\t\tIn.Mark = mark\n\t} else {\n\t\tlog.Fatalf(\"Mark. Not defined %s\\n\", mark)\n\t}\n\n\tIn.Data = data\n\tIn.Field = field\n\tIn.Type = \"\"\n\n\tif mark == \"IS\" {\n\t\tif iutils.AnyToString(In.Data[0]) == \"NULL\" {\n\t\t\tIn.Type = \"NoVals\"\n\t\t\tIn.Field = field + \" IS NULL \"\n\t\t} else if iutils.AnyToString(In.Data[0]) == \"NOT NULL\" {\n\t\t\tIn.Type = \"NoVals\"\n\t\t\tIn.Field = field + \" IS NOT NULL \"\n\t\t} else {\n\t\t\tlog.Fatalf(\"Mark. Not defined %s. You have to use 'IS', 'NULL' or 'IS', 'NOT NULL' \\n\", mark)\n\t\t}\n\t}\n\n\treturn &In\n}\n<commit_msg>Remove unnecessary log messages.<commit_after>package xSql\n\nimport (\n\t\"fmt\"\n\t\"github.com\/iostrovok\/go-iutils\/iutils\"\n\t\"log\"\n\t\"strings\"\n)\n\nvar MarkList = map[string]bool{\n\t\"&&\":    true,\n\t\"<\":     true,\n\t\"<=\":    true,\n\t\"<>\":    true,\n\t\"<@\":    true,\n\t\"=\":     true,\n\t\">\":     true,\n\t\">=\":    true,\n\t\"@>\":    true,\n\t\"ILIKE\": true,\n\t\"IN\":    true,\n\t\"IS\":    true,\n\t\"LIKE\":  true,\n\t\"RET\":   true,\n\t\"SQL\":   true,\n\t\"||\":    true,\n}\n\nvar LogicList = map[string]bool{\n\t\"AND\":    true,\n\t\"OR\":     true,\n\t\"INSERT\": true,\n\t\"UPDATE\": true,\n}\n\ntype One struct {\n\tData     []interface{}\n\tTable    string\n\tField    string\n\tMark     string\n\tAddParam string\n\tType     string \/\/ NoVals Array Where JSON\n}\n\nfunc Update(table string) *One {\n\tone := One{}\n\tone.Mark = \"UPDATE\"\n\tone.Table = table\n\treturn &one\n}\n\nfunc Insert(table string) *One {\n\tone := One{}\n\tone.Mark = \"INSERT\"\n\tone.Table = table\n\treturn &one\n}\n\nfunc IN(field string, data []interface{}) *One {\n\tone := One{}\n\tone.Data = data\n\tone.Mark = \"IN\"\n\tone.Field = field\n\n\treturn &one\n}\n\nfunc (one *One) CompUpdate() (string, []interface{}) {\n\tsUp := []string{}\n\tsRet := []string{}\n\n\tvalues := []interface{}{}\n\tsql_where := \"\"\n\n\tfor _, v := range one.Data {\n\t\tswitch v.(type) {\n\t\tcase *One:\n\t\t\tif v.(*One).Type == \"Where\" {\n\t\t\t\tsql, vals := v.(*One).Comp()\n\t\t\t\tif sql != \"\" {\n\t\t\t\t\tsql_where = \" WHERE \" + sql\n\t\t\t\t\tvalues = append(values, vals...)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tPoint := 1 + len(values)\n\n\tfor _, v := range one.Data {\n\t\tswitch v.(type) {\n\t\tcase *One:\n\t\t\tif v.(*One).Type == \"Where\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\ttp := v.(*One).Mark\n\n\t\t\tif tp == \"RET\" {\n\t\t\t\tsRet = append(sRet, v.(*One).Field)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif tp != \"=\" {\n\t\t\t\tlog.Fatalf(\"Comp. For update only \\\"=\\\" defined %v\\n\", v)\n\t\t\t}\n\n\t\t\tsql, vals := v.(*One).Comp(Point)\n\t\t\tPoint += len(vals)\n\t\t\tsUp = append(sUp, sql)\n\t\t\tvalues = append(values, vals...)\n\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Comp. Not defined %T, %v\\n\", v, v)\n\t\t}\n\t}\n\tret := \"\"\n\tif len(sRet) > 0 {\n\t\tret = \" RETURNING \" + strings.Join(sRet, \", \")\n\t}\n\tsql := strings.Join(sUp, \", \")\n\treturn \" UPDATE \" + one.Table + \" SET \" + sql + sql_where + ret, values\n}\n\nfunc (one *One) CompInsert() (string, []interface{}) {\n\tsIn := []string{}\n\tsVals := []string{}\n\tsRet := []string{}\n\tPoint := 1\n\tvalues := []interface{}{}\n\tfor _, v := range one.Data {\n\t\tswitch v.(type) {\n\t\tcase *One:\n\n\t\t\ttp := v.(*One).Mark\n\n\t\t\tif tp == \"RET\" {\n\t\t\t\tsRet = append(sRet, v.(*One).Field)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tsIn = append(sIn, v.(*One).Field)\n\t\t\tvals := v.(*One).Data\n\n\t\t\tif v.(*One).Type == \"Array\" {\n\t\t\t\ts, v := PrepareArray(v.(*One).AddParam, vals, Point)\n\t\t\t\tsVals = append(sVals, s)\n\t\t\t\tvalues = append(values, v...)\n\t\t\t\tPoint += len(v)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif len(vals) > 1 {\n\t\t\t\tlog.Fatalf(\"Comp. You can't INSERT multivalue params %T, %v\\n\", v, v)\n\t\t\t}\n\n\t\t\tif v.(*One).Type == \"JSON\" {\n\t\t\t\tvals = PrepareJsonVals(vals)\n\t\t\t}\n\n\t\t\tif tp == \"SQL\" {\n\t\t\t\tsVals = append(sVals, iutils.AnyToString(vals[0]))\n\t\t\t} else {\n\t\t\t\tsVals = append(sVals, fmt.Sprintf(\"$%d \", Point))\n\t\t\t\tPoint++\n\t\t\t\tvalues = append(values, vals...)\n\t\t\t}\n\n\t\tdefault:\n\t\t\tlog.Fatalf(\"Comp. Not defined %T, %v\\n\", v, v)\n\t\t}\n\t}\n\tret := \"\"\n\tif len(sRet) > 0 {\n\t\tret = \" RETURNING \" + strings.Join(sRet, \", \")\n\t}\n\tsql := \"  ( \" + strings.Join(sIn, \", \") + \") VALUES (\" + strings.Join(sVals, \", \") + \")\"\n\treturn \" INSERT INTO \" + one.Table + sql + ret, values\n}\n\nfunc (one *One) Comp(PointIn ...int) (string, []interface{}) {\n\n\tPoint := 1\n\tif len(PointIn) > 0 {\n\t\tPoint = PointIn[0]\n\t}\n\n\tsqlLine := \"\"\n\tvalues := []interface{}{}\n\n\tif one.Mark == \"INSERT\" {\n\t\tif Point > 1 {\n\t\t\tlog.Fatalf(\"Comp. You can't combination INSERT into other request\\n\")\n\t\t}\n\t\treturn one.CompInsert()\n\t}\n\n\tif one.Mark == \"UPDATE\" {\n\t\tif Point > 1 {\n\t\t\tlog.Fatalf(\"Comp. You can't combination INSERT into other request\\n\")\n\t\t}\n\t\treturn one.CompUpdate()\n\t}\n\n\tswitch one.Type {\n\tcase \"NoVals\":\n\t\treturn one.Field, values\n\tcase \"Array\":\n\t\treturn one.CompArray(Point)\n\tcase \"JSON\":\n\t\tone.Data = PrepareJsonVals(one.Data)\n\t}\n\n\tswitch one.Mark {\n\tcase \"AND\", \"OR\":\n\t\ts := []string{}\n\t\tfor _, v := range one.Data {\n\t\t\tswitch v.(type) {\n\t\t\tcase *One:\n\t\t\t\tsql, vals := v.(*One).Comp(Point)\n\t\t\t\ts = append(s, sql)\n\t\t\t\tif len(vals) > 0 {\n\t\t\t\t\tPoint += len(vals)\n\t\t\t\t\tvalues = append(values, vals...)\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlog.Fatalf(\"Comp. Not defined %T, %v\\n\", v, v)\n\t\t\t}\n\t\t}\n\t\tsqlLine = \"( \" + strings.Join(s, \" \"+one.Mark+\" \") + \") \"\n\tcase \"IN\":\n\t\ts := []string{}\n\t\ti := len(one.Data)\n\t\tfor {\n\t\t\ts = append(s, fmt.Sprintf(\" $%d \", Point))\n\t\t\tPoint++\n\t\t\ti--\n\t\t\tif i < 1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tsqlLine = fmt.Sprintf(\" %s IN ( %s ) \", one.Field, strings.Join(s, \", \"))\n\t\tvalues = one.Data\n\tcase \"IS\":\n\t\tsqlLine = one.Field + \" IS \" + iutils.AnyToString(one.Data[0])\n\tdefault:\n\t\tsqlLine = fmt.Sprintf(\" %s %s $%d \", one.Field, one.Mark, Point)\n\t\tPoint++\n\t\tvalues = append(values, one.Data[0])\n\t}\n\n\treturn sqlLine, values\n}\n\nfunc (one *One) Append(Nexters ...*One) *One {\n\tif _, find := LogicList[one.Mark]; !find {\n\t\tlog.Fatalf(\"Append. Bad type for append %s\\n\", one.Mark)\n\t}\n\tfor _, v := range Nexters {\n\t\tone.Data = append(one.Data, v)\n\t}\n\treturn one\n}\n\nfunc NLogic(mark string, Nexters ...*One) *One {\n\tone := One{}\n\tone.Logic(mark, Nexters...)\n\treturn &one\n}\n\nfunc (one *One) Logic(mark string, Nexters ...*One) {\n\n\tif _, find := LogicList[mark]; !find {\n\t\tlog.Fatalf(\"Logic. Not defined %s\\n\", mark)\n\t}\n\n\tone.Data = []interface{}{}\n\tfor _, v := range Nexters {\n\t\tone.Data = append(one.Data, v)\n\t}\n\tone.Mark = mark\n}\n\nfunc (one *One) Where(v *One) *One {\n\tv.Type = \"Where\"\n\tone.Data = append(one.Data, v)\n\treturn one\n}\n\n\/*\n\texample: where start_date > now()\n\tFunc(\"start_date\", \">\", \"now()\")\n*\/\nfunc Func(field string) *One {\n\tIn := One{}\n\n\tIn.Type = \"NoVals\"\n\tIn.Field = field\n\n\treturn &In\n}\n\nfunc Mark(field string, mark string, data ...interface{}) *One {\n\tIn := One{}\n\n\tif _, find := MarkList[mark]; find {\n\t\tIn.Mark = mark\n\t} else {\n\t\tlog.Fatalf(\"Mark. Not defined %s\\n\", mark)\n\t}\n\n\tIn.Data = data\n\tIn.Field = field\n\tIn.Type = \"\"\n\n\tif mark == \"IS\" {\n\t\tif iutils.AnyToString(In.Data[0]) == \"NULL\" {\n\t\t\tIn.Type = \"NoVals\"\n\t\t\tIn.Field = field + \" IS NULL \"\n\t\t} else if iutils.AnyToString(In.Data[0]) == \"NOT NULL\" {\n\t\t\tIn.Type = \"NoVals\"\n\t\t\tIn.Field = field + \" IS NOT NULL \"\n\t\t} else {\n\t\t\tlog.Fatalf(\"Mark. Not defined %s. You have to use 'IS', 'NULL' or 'IS', 'NOT NULL' \\n\", mark)\n\t\t}\n\t}\n\n\treturn &In\n}\n<|endoftext|>"}
{"text":"<commit_before>package bdiscord\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/42wim\/matterbridge\/bridge\"\n\t\"github.com\/42wim\/matterbridge\/bridge\/config\"\n\t\"github.com\/42wim\/matterbridge\/bridge\/helper\"\n\t\"github.com\/bwmarrin\/discordgo\"\n)\n\ntype Bdiscord struct {\n\tc              *discordgo.Session\n\tChannels       []*discordgo.Channel\n\tNick           string\n\tUseChannelID   bool\n\tuserMemberMap  map[string]*discordgo.Member\n\tguildID        string\n\twebhookID      string\n\twebhookToken   string\n\tchannelInfoMap map[string]*config.ChannelInfo\n\tsync.RWMutex\n\t*bridge.Config\n}\n\nfunc New(cfg *bridge.Config) bridge.Bridger {\n\tb := &Bdiscord{Config: cfg}\n\tb.userMemberMap = make(map[string]*discordgo.Member)\n\tb.channelInfoMap = make(map[string]*config.ChannelInfo)\n\tif b.GetString(\"WebhookURL\") != \"\" {\n\t\tb.Log.Debug(\"Configuring Discord Incoming Webhook\")\n\t\tb.webhookID, b.webhookToken = b.splitURL(b.GetString(\"WebhookURL\"))\n\t}\n\treturn b\n}\n\nfunc (b *Bdiscord) Connect() error {\n\tvar err error\n\tvar token string\n\tb.Log.Info(\"Connecting\")\n\tif b.GetString(\"WebhookURL\") == \"\" {\n\t\tb.Log.Info(\"Connecting using token\")\n\t} else {\n\t\tb.Log.Info(\"Connecting using webhookurl (for posting) and token\")\n\t}\n\tif !strings.HasPrefix(b.GetString(\"Token\"), \"Bot \") {\n\t\ttoken = \"Bot \" + b.GetString(\"Token\")\n\t}\n\tb.c, err = discordgo.New(token)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.Log.Info(\"Connection succeeded\")\n\tb.c.AddHandler(b.messageCreate)\n\tb.c.AddHandler(b.memberUpdate)\n\tb.c.AddHandler(b.messageUpdate)\n\tb.c.AddHandler(b.messageDelete)\n\terr = b.c.Open()\n\tif err != nil {\n\t\treturn err\n\t}\n\tguilds, err := b.c.UserGuilds(100, \"\", \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tuserinfo, err := b.c.User(\"@me\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.Nick = userinfo.Username\n\tfor _, guild := range guilds {\n\t\tif guild.Name == b.GetString(\"Server\") {\n\t\t\tb.Channels, err = b.c.GuildChannels(guild.ID)\n\t\t\tb.guildID = guild.ID\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tfor _, channel := range b.Channels {\n\t\tb.Log.Debugf(\"found channel %#v\", channel)\n\t}\n\treturn nil\n}\n\nfunc (b *Bdiscord) Disconnect() error {\n\treturn b.c.Close()\n}\n\nfunc (b *Bdiscord) JoinChannel(channel config.ChannelInfo) error {\n\tb.channelInfoMap[channel.ID] = &channel\n\tidcheck := strings.Split(channel.Name, \"ID:\")\n\tif len(idcheck) > 1 {\n\t\tb.UseChannelID = true\n\t}\n\treturn nil\n}\n\nfunc (b *Bdiscord) Send(msg config.Message) (string, error) {\n\tb.Log.Debugf(\"=> Receiving %#v\", msg)\n\n\tchannelID := b.getChannelID(msg.Channel)\n\tif channelID == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Could not find channelID for %v\", msg.Channel)\n\t}\n\n\t\/\/ Make a action \/me of the message\n\tif msg.Event == config.EVENT_USER_ACTION {\n\t\tmsg.Text = \"_\" + msg.Text + \"_\"\n\t}\n\n\t\/\/ use initial webhook\n\twID := b.webhookID\n\twToken := b.webhookToken\n\n\t\/\/ check if have a channel specific webhook\n\tif ci, ok := b.channelInfoMap[msg.Channel+b.Account]; ok {\n\t\tif ci.Options.WebhookURL != \"\" {\n\t\t\twID, wToken = b.splitURL(ci.Options.WebhookURL)\n\t\t}\n\t}\n\n\t\/\/ Use webhook to send the message\n\tif wID != \"\" {\n\t\t\/\/ skip events\n\t\tif msg.Event != \"\" && msg.Event != config.EVENT_JOIN_LEAVE && msg.Event != config.EVENT_TOPIC_CHANGE {\n\t\t\treturn \"\", nil\n\t\t}\n\t\tb.Log.Debugf(\"Broadcasting using Webhook\")\n\t\tfor _, f := range msg.Extra[\"file\"] {\n\t\t\tfi := f.(config.FileInfo)\n\t\t\tif fi.URL != \"\" {\n\t\t\t\tmsg.Text += fi.URL + \" \"\n\t\t\t}\n\t\t}\n\t\terr := b.c.WebhookExecute(\n\t\t\twID,\n\t\t\twToken,\n\t\t\ttrue,\n\t\t\t&discordgo.WebhookParams{\n\t\t\t\tContent:   msg.Text,\n\t\t\t\tUsername:  msg.Username,\n\t\t\t\tAvatarURL: msg.Avatar,\n\t\t\t})\n\t\treturn \"\", err\n\t}\n\n\tb.Log.Debugf(\"Broadcasting using token (API)\")\n\n\t\/\/ Delete message\n\tif msg.Event == config.EVENT_MSG_DELETE {\n\t\tif msg.ID == \"\" {\n\t\t\treturn \"\", nil\n\t\t}\n\t\terr := b.c.ChannelMessageDelete(channelID, msg.ID)\n\t\treturn \"\", err\n\t}\n\n\t\/\/ Upload a file if it exists\n\tif msg.Extra != nil {\n\t\tfor _, rmsg := range helper.HandleExtra(&msg, b.General) {\n\t\t\tb.c.ChannelMessageSend(channelID, rmsg.Username+rmsg.Text)\n\t\t}\n\t\t\/\/ check if we have files to upload (from slack, telegram or mattermost)\n\t\tif len(msg.Extra[\"file\"]) > 0 {\n\t\t\treturn b.handleUploadFile(&msg, channelID)\n\t\t}\n\t}\n\n\t\/\/ Edit message\n\tif msg.ID != \"\" {\n\t\t_, err := b.c.ChannelMessageEdit(channelID, msg.ID, msg.Username+msg.Text)\n\t\treturn msg.ID, err\n\t}\n\n\t\/\/ Post normal message\n\tres, err := b.c.ChannelMessageSend(channelID, msg.Username+msg.Text)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn res.ID, err\n}\n\nfunc (b *Bdiscord) messageDelete(s *discordgo.Session, m *discordgo.MessageDelete) {\n\trmsg := config.Message{Account: b.Account, ID: m.ID, Event: config.EVENT_MSG_DELETE, Text: config.EVENT_MSG_DELETE}\n\trmsg.Channel = b.getChannelName(m.ChannelID)\n\tif b.UseChannelID {\n\t\trmsg.Channel = \"ID:\" + m.ChannelID\n\t}\n\tb.Log.Debugf(\"<= Sending message from %s to gateway\", b.Account)\n\tb.Log.Debugf(\"<= Message is %#v\", rmsg)\n\tb.Remote <- rmsg\n}\n\nfunc (b *Bdiscord) messageUpdate(s *discordgo.Session, m *discordgo.MessageUpdate) {\n\tif b.GetBool(\"EditDisable\") {\n\t\treturn\n\t}\n\t\/\/ only when message is actually edited\n\tif m.Message.EditedTimestamp != \"\" {\n\t\tb.Log.Debugf(\"Sending edit message\")\n\t\tm.Content = m.Content + b.GetString(\"EditSuffix\")\n\t\tb.messageCreate(s, (*discordgo.MessageCreate)(m))\n\t}\n}\n\nfunc (b *Bdiscord) messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {\n\tvar err error\n\n\t\/\/ not relay our own messages\n\tif m.Author.Username == b.Nick {\n\t\treturn\n\t}\n\t\/\/ if using webhooks, do not relay if it's ours\n\tif b.useWebhook() && m.Author.Bot && b.isWebhookID(m.Author.ID) {\n\t\treturn\n\t}\n\n\t\/\/ add the url of the attachments to content\n\tif len(m.Attachments) > 0 {\n\t\tfor _, attach := range m.Attachments {\n\t\t\tm.Content = m.Content + \"\\n\" + attach.URL\n\t\t}\n\t}\n\n\trmsg := config.Message{Account: b.Account, Avatar: \"https:\/\/cdn.discordapp.com\/avatars\/\" + m.Author.ID + \"\/\" + m.Author.Avatar + \".jpg\", UserID: m.Author.ID, ID: m.ID}\n\n\tif m.Content != \"\" {\n\t\tb.Log.Debugf(\"== Receiving event %#v\", m.Message)\n\t\tm.Message.Content = b.stripCustomoji(m.Message.Content)\n\t\tm.Message.Content = b.replaceChannelMentions(m.Message.Content)\n\t\trmsg.Text, err = m.ContentWithMoreMentionsReplaced(b.c)\n\t\tif err != nil {\n\t\t\tb.Log.Errorf(\"ContentWithMoreMentionsReplaced failed: %s\", err)\n\t\t\trmsg.Text = m.ContentWithMentionsReplaced()\n\t\t}\n\t}\n\n\t\/\/ set channel name\n\trmsg.Channel = b.getChannelName(m.ChannelID)\n\tif b.UseChannelID {\n\t\trmsg.Channel = \"ID:\" + m.ChannelID\n\t}\n\n\t\/\/ set username\n\tif !b.GetBool(\"UseUserName\") {\n\t\trmsg.Username = b.getNick(m.Author)\n\t} else {\n\t\trmsg.Username = m.Author.Username\n\t}\n\n\t\/\/ if we have embedded content add it to text\n\tif b.GetBool(\"ShowEmbeds\") && m.Message.Embeds != nil {\n\t\tfor _, embed := range m.Message.Embeds {\n\t\t\trmsg.Text = rmsg.Text + \"embed: \" + embed.Title + \" - \" + embed.Description + \" - \" + embed.URL + \"\\n\"\n\t\t}\n\t}\n\n\t\/\/ no empty messages\n\tif rmsg.Text == \"\" {\n\t\treturn\n\t}\n\n\t\/\/ do we have a \/me action\n\tvar ok bool\n\trmsg.Text, ok = b.replaceAction(rmsg.Text)\n\tif ok {\n\t\trmsg.Event = config.EVENT_USER_ACTION\n\t}\n\n\tb.Log.Debugf(\"<= Sending message from %s on %s to gateway\", m.Author.Username, b.Account)\n\tb.Log.Debugf(\"<= Message is %#v\", rmsg)\n\tb.Remote <- rmsg\n}\n\nfunc (b *Bdiscord) memberUpdate(s *discordgo.Session, m *discordgo.GuildMemberUpdate) {\n\tb.Lock()\n\tif _, ok := b.userMemberMap[m.Member.User.ID]; ok {\n\t\tb.Log.Debugf(\"%s: memberupdate: user %s (nick %s) changes nick to %s\", b.Account, m.Member.User.Username, b.userMemberMap[m.Member.User.ID].Nick, m.Member.Nick)\n\t}\n\tb.userMemberMap[m.Member.User.ID] = m.Member\n\tb.Unlock()\n}\n\nfunc (b *Bdiscord) getNick(user *discordgo.User) string {\n\tvar err error\n\tb.Lock()\n\tdefer b.Unlock()\n\tif _, ok := b.userMemberMap[user.ID]; ok {\n\t\tif b.userMemberMap[user.ID] != nil {\n\t\t\tif b.userMemberMap[user.ID].Nick != \"\" {\n\t\t\t\t\/\/ only return if nick is set\n\t\t\t\treturn b.userMemberMap[user.ID].Nick\n\t\t\t}\n\t\t\t\/\/ otherwise return username\n\t\t\treturn user.Username\n\t\t}\n\t}\n\t\/\/ if we didn't find nick, search for it\n\tmember, err := b.c.GuildMember(b.guildID, user.ID)\n\tif err != nil {\n\t\treturn user.Username\n\t}\n\tb.userMemberMap[user.ID] = member\n\t\/\/ only return if nick is set\n\tif b.userMemberMap[user.ID].Nick != \"\" {\n\t\treturn b.userMemberMap[user.ID].Nick\n\t}\n\treturn user.Username\n}\n\nfunc (b *Bdiscord) getChannelID(name string) string {\n\tidcheck := strings.Split(name, \"ID:\")\n\tif len(idcheck) > 1 {\n\t\treturn idcheck[1]\n\t}\n\tfor _, channel := range b.Channels {\n\t\tif channel.Name == name {\n\t\t\treturn channel.ID\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (b *Bdiscord) getChannelName(id string) string {\n\tfor _, channel := range b.Channels {\n\t\tif channel.ID == id {\n\t\t\treturn channel.Name\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (b *Bdiscord) replaceChannelMentions(text string) string {\n\tvar err error\n\tre := regexp.MustCompile(\"<#[0-9]+>\")\n\ttext = re.ReplaceAllStringFunc(text, func(m string) string {\n\t\tchannel := b.getChannelName(m[2 : len(m)-1])\n\t\t\/\/ if at first don't succeed, try again\n\t\tif channel == \"\" {\n\t\t\tb.Channels, err = b.c.GuildChannels(b.guildID)\n\t\t\tif err != nil {\n\t\t\t\treturn \"#unknownchannel\"\n\t\t\t}\n\t\t\tchannel = b.getChannelName(m[2 : len(m)-1])\n\t\t\treturn \"#\" + channel\n\t\t}\n\t\treturn \"#\" + channel\n\t})\n\treturn text\n}\n\nfunc (b *Bdiscord) replaceAction(text string) (string, bool) {\n\tif strings.HasPrefix(text, \"_\") && strings.HasSuffix(text, \"_\") {\n\t\treturn strings.Replace(text, \"_\", \"\", -1), true\n\t}\n\treturn text, false\n}\n\nfunc (b *Bdiscord) stripCustomoji(text string) string {\n\t\/\/ <:doge:302803592035958784>\n\tre := regexp.MustCompile(\"<(:.*?:)[0-9]+>\")\n\treturn re.ReplaceAllString(text, `$1`)\n}\n\n\/\/ splitURL splits a webhookURL and returns the id and token\nfunc (b *Bdiscord) splitURL(url string) (string, string) {\n\twebhookURLSplit := strings.Split(url, \"\/\")\n\tif len(webhookURLSplit) != 7 {\n\t\tb.Log.Fatalf(\"%s is no correct discord WebhookURL\", url)\n\t}\n\treturn webhookURLSplit[len(webhookURLSplit)-2], webhookURLSplit[len(webhookURLSplit)-1]\n}\n\n\/\/ useWebhook returns true if we have a webhook defined somewhere\nfunc (b *Bdiscord) useWebhook() bool {\n\tif b.GetString(\"WebhookURL\") != \"\" {\n\t\treturn true\n\t}\n\tfor _, channel := range b.channelInfoMap {\n\t\tif channel.Options.WebhookURL != \"\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ isWebhookID returns true if the specified id is used in a defined webhook\nfunc (b *Bdiscord) isWebhookID(id string) bool {\n\tif b.GetString(\"WebhookURL\") != \"\" {\n\t\twID, _ := b.splitURL(b.GetString(\"WebhookURL\"))\n\t\tif wID == id {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, channel := range b.channelInfoMap {\n\t\tif channel.Options.WebhookURL != \"\" {\n\t\t\twID, _ := b.splitURL(channel.Options.WebhookURL)\n\t\t\tif wID == id {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ handleUploadFile handles native upload of files\nfunc (b *Bdiscord) handleUploadFile(msg *config.Message, channelID string) (string, error) {\n\tvar err error\n\tfor _, f := range msg.Extra[\"file\"] {\n\t\tfi := f.(config.FileInfo)\n\t\tfiles := []*discordgo.File{}\n\t\tfiles = append(files, &discordgo.File{fi.Name, \"\", bytes.NewReader(*fi.Data)})\n\t\t_, err = b.c.ChannelMessageSendComplex(channelID, &discordgo.MessageSend{Content: msg.Username + fi.Comment, Files: files})\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"file upload failed: %#v\", err)\n\t\t}\n\t}\n\treturn \"\", nil\n}\n<commit_msg>Add a space before url in file uploads (discord). Closes #461<commit_after>package bdiscord\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/42wim\/matterbridge\/bridge\"\n\t\"github.com\/42wim\/matterbridge\/bridge\/config\"\n\t\"github.com\/42wim\/matterbridge\/bridge\/helper\"\n\t\"github.com\/bwmarrin\/discordgo\"\n)\n\ntype Bdiscord struct {\n\tc              *discordgo.Session\n\tChannels       []*discordgo.Channel\n\tNick           string\n\tUseChannelID   bool\n\tuserMemberMap  map[string]*discordgo.Member\n\tguildID        string\n\twebhookID      string\n\twebhookToken   string\n\tchannelInfoMap map[string]*config.ChannelInfo\n\tsync.RWMutex\n\t*bridge.Config\n}\n\nfunc New(cfg *bridge.Config) bridge.Bridger {\n\tb := &Bdiscord{Config: cfg}\n\tb.userMemberMap = make(map[string]*discordgo.Member)\n\tb.channelInfoMap = make(map[string]*config.ChannelInfo)\n\tif b.GetString(\"WebhookURL\") != \"\" {\n\t\tb.Log.Debug(\"Configuring Discord Incoming Webhook\")\n\t\tb.webhookID, b.webhookToken = b.splitURL(b.GetString(\"WebhookURL\"))\n\t}\n\treturn b\n}\n\nfunc (b *Bdiscord) Connect() error {\n\tvar err error\n\tvar token string\n\tb.Log.Info(\"Connecting\")\n\tif b.GetString(\"WebhookURL\") == \"\" {\n\t\tb.Log.Info(\"Connecting using token\")\n\t} else {\n\t\tb.Log.Info(\"Connecting using webhookurl (for posting) and token\")\n\t}\n\tif !strings.HasPrefix(b.GetString(\"Token\"), \"Bot \") {\n\t\ttoken = \"Bot \" + b.GetString(\"Token\")\n\t}\n\tb.c, err = discordgo.New(token)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.Log.Info(\"Connection succeeded\")\n\tb.c.AddHandler(b.messageCreate)\n\tb.c.AddHandler(b.memberUpdate)\n\tb.c.AddHandler(b.messageUpdate)\n\tb.c.AddHandler(b.messageDelete)\n\terr = b.c.Open()\n\tif err != nil {\n\t\treturn err\n\t}\n\tguilds, err := b.c.UserGuilds(100, \"\", \"\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tuserinfo, err := b.c.User(\"@me\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.Nick = userinfo.Username\n\tfor _, guild := range guilds {\n\t\tif guild.Name == b.GetString(\"Server\") {\n\t\t\tb.Channels, err = b.c.GuildChannels(guild.ID)\n\t\t\tb.guildID = guild.ID\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tfor _, channel := range b.Channels {\n\t\tb.Log.Debugf(\"found channel %#v\", channel)\n\t}\n\treturn nil\n}\n\nfunc (b *Bdiscord) Disconnect() error {\n\treturn b.c.Close()\n}\n\nfunc (b *Bdiscord) JoinChannel(channel config.ChannelInfo) error {\n\tb.channelInfoMap[channel.ID] = &channel\n\tidcheck := strings.Split(channel.Name, \"ID:\")\n\tif len(idcheck) > 1 {\n\t\tb.UseChannelID = true\n\t}\n\treturn nil\n}\n\nfunc (b *Bdiscord) Send(msg config.Message) (string, error) {\n\tb.Log.Debugf(\"=> Receiving %#v\", msg)\n\n\tchannelID := b.getChannelID(msg.Channel)\n\tif channelID == \"\" {\n\t\treturn \"\", fmt.Errorf(\"Could not find channelID for %v\", msg.Channel)\n\t}\n\n\t\/\/ Make a action \/me of the message\n\tif msg.Event == config.EVENT_USER_ACTION {\n\t\tmsg.Text = \"_\" + msg.Text + \"_\"\n\t}\n\n\t\/\/ use initial webhook\n\twID := b.webhookID\n\twToken := b.webhookToken\n\n\t\/\/ check if have a channel specific webhook\n\tif ci, ok := b.channelInfoMap[msg.Channel+b.Account]; ok {\n\t\tif ci.Options.WebhookURL != \"\" {\n\t\t\twID, wToken = b.splitURL(ci.Options.WebhookURL)\n\t\t}\n\t}\n\n\t\/\/ Use webhook to send the message\n\tif wID != \"\" {\n\t\t\/\/ skip events\n\t\tif msg.Event != \"\" && msg.Event != config.EVENT_JOIN_LEAVE && msg.Event != config.EVENT_TOPIC_CHANGE {\n\t\t\treturn \"\", nil\n\t\t}\n\t\tb.Log.Debugf(\"Broadcasting using Webhook\")\n\t\tfor _, f := range msg.Extra[\"file\"] {\n\t\t\tfi := f.(config.FileInfo)\n\t\t\tif fi.URL != \"\" {\n\t\t\t\tmsg.Text += \" \" + fi.URL\n\t\t\t}\n\t\t}\n\t\terr := b.c.WebhookExecute(\n\t\t\twID,\n\t\t\twToken,\n\t\t\ttrue,\n\t\t\t&discordgo.WebhookParams{\n\t\t\t\tContent:   msg.Text,\n\t\t\t\tUsername:  msg.Username,\n\t\t\t\tAvatarURL: msg.Avatar,\n\t\t\t})\n\t\treturn \"\", err\n\t}\n\n\tb.Log.Debugf(\"Broadcasting using token (API)\")\n\n\t\/\/ Delete message\n\tif msg.Event == config.EVENT_MSG_DELETE {\n\t\tif msg.ID == \"\" {\n\t\t\treturn \"\", nil\n\t\t}\n\t\terr := b.c.ChannelMessageDelete(channelID, msg.ID)\n\t\treturn \"\", err\n\t}\n\n\t\/\/ Upload a file if it exists\n\tif msg.Extra != nil {\n\t\tfor _, rmsg := range helper.HandleExtra(&msg, b.General) {\n\t\t\tb.c.ChannelMessageSend(channelID, rmsg.Username+rmsg.Text)\n\t\t}\n\t\t\/\/ check if we have files to upload (from slack, telegram or mattermost)\n\t\tif len(msg.Extra[\"file\"]) > 0 {\n\t\t\treturn b.handleUploadFile(&msg, channelID)\n\t\t}\n\t}\n\n\t\/\/ Edit message\n\tif msg.ID != \"\" {\n\t\t_, err := b.c.ChannelMessageEdit(channelID, msg.ID, msg.Username+msg.Text)\n\t\treturn msg.ID, err\n\t}\n\n\t\/\/ Post normal message\n\tres, err := b.c.ChannelMessageSend(channelID, msg.Username+msg.Text)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn res.ID, err\n}\n\nfunc (b *Bdiscord) messageDelete(s *discordgo.Session, m *discordgo.MessageDelete) {\n\trmsg := config.Message{Account: b.Account, ID: m.ID, Event: config.EVENT_MSG_DELETE, Text: config.EVENT_MSG_DELETE}\n\trmsg.Channel = b.getChannelName(m.ChannelID)\n\tif b.UseChannelID {\n\t\trmsg.Channel = \"ID:\" + m.ChannelID\n\t}\n\tb.Log.Debugf(\"<= Sending message from %s to gateway\", b.Account)\n\tb.Log.Debugf(\"<= Message is %#v\", rmsg)\n\tb.Remote <- rmsg\n}\n\nfunc (b *Bdiscord) messageUpdate(s *discordgo.Session, m *discordgo.MessageUpdate) {\n\tif b.GetBool(\"EditDisable\") {\n\t\treturn\n\t}\n\t\/\/ only when message is actually edited\n\tif m.Message.EditedTimestamp != \"\" {\n\t\tb.Log.Debugf(\"Sending edit message\")\n\t\tm.Content = m.Content + b.GetString(\"EditSuffix\")\n\t\tb.messageCreate(s, (*discordgo.MessageCreate)(m))\n\t}\n}\n\nfunc (b *Bdiscord) messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {\n\tvar err error\n\n\t\/\/ not relay our own messages\n\tif m.Author.Username == b.Nick {\n\t\treturn\n\t}\n\t\/\/ if using webhooks, do not relay if it's ours\n\tif b.useWebhook() && m.Author.Bot && b.isWebhookID(m.Author.ID) {\n\t\treturn\n\t}\n\n\t\/\/ add the url of the attachments to content\n\tif len(m.Attachments) > 0 {\n\t\tfor _, attach := range m.Attachments {\n\t\t\tm.Content = m.Content + \"\\n\" + attach.URL\n\t\t}\n\t}\n\n\trmsg := config.Message{Account: b.Account, Avatar: \"https:\/\/cdn.discordapp.com\/avatars\/\" + m.Author.ID + \"\/\" + m.Author.Avatar + \".jpg\", UserID: m.Author.ID, ID: m.ID}\n\n\tif m.Content != \"\" {\n\t\tb.Log.Debugf(\"== Receiving event %#v\", m.Message)\n\t\tm.Message.Content = b.stripCustomoji(m.Message.Content)\n\t\tm.Message.Content = b.replaceChannelMentions(m.Message.Content)\n\t\trmsg.Text, err = m.ContentWithMoreMentionsReplaced(b.c)\n\t\tif err != nil {\n\t\t\tb.Log.Errorf(\"ContentWithMoreMentionsReplaced failed: %s\", err)\n\t\t\trmsg.Text = m.ContentWithMentionsReplaced()\n\t\t}\n\t}\n\n\t\/\/ set channel name\n\trmsg.Channel = b.getChannelName(m.ChannelID)\n\tif b.UseChannelID {\n\t\trmsg.Channel = \"ID:\" + m.ChannelID\n\t}\n\n\t\/\/ set username\n\tif !b.GetBool(\"UseUserName\") {\n\t\trmsg.Username = b.getNick(m.Author)\n\t} else {\n\t\trmsg.Username = m.Author.Username\n\t}\n\n\t\/\/ if we have embedded content add it to text\n\tif b.GetBool(\"ShowEmbeds\") && m.Message.Embeds != nil {\n\t\tfor _, embed := range m.Message.Embeds {\n\t\t\trmsg.Text = rmsg.Text + \"embed: \" + embed.Title + \" - \" + embed.Description + \" - \" + embed.URL + \"\\n\"\n\t\t}\n\t}\n\n\t\/\/ no empty messages\n\tif rmsg.Text == \"\" {\n\t\treturn\n\t}\n\n\t\/\/ do we have a \/me action\n\tvar ok bool\n\trmsg.Text, ok = b.replaceAction(rmsg.Text)\n\tif ok {\n\t\trmsg.Event = config.EVENT_USER_ACTION\n\t}\n\n\tb.Log.Debugf(\"<= Sending message from %s on %s to gateway\", m.Author.Username, b.Account)\n\tb.Log.Debugf(\"<= Message is %#v\", rmsg)\n\tb.Remote <- rmsg\n}\n\nfunc (b *Bdiscord) memberUpdate(s *discordgo.Session, m *discordgo.GuildMemberUpdate) {\n\tb.Lock()\n\tif _, ok := b.userMemberMap[m.Member.User.ID]; ok {\n\t\tb.Log.Debugf(\"%s: memberupdate: user %s (nick %s) changes nick to %s\", b.Account, m.Member.User.Username, b.userMemberMap[m.Member.User.ID].Nick, m.Member.Nick)\n\t}\n\tb.userMemberMap[m.Member.User.ID] = m.Member\n\tb.Unlock()\n}\n\nfunc (b *Bdiscord) getNick(user *discordgo.User) string {\n\tvar err error\n\tb.Lock()\n\tdefer b.Unlock()\n\tif _, ok := b.userMemberMap[user.ID]; ok {\n\t\tif b.userMemberMap[user.ID] != nil {\n\t\t\tif b.userMemberMap[user.ID].Nick != \"\" {\n\t\t\t\t\/\/ only return if nick is set\n\t\t\t\treturn b.userMemberMap[user.ID].Nick\n\t\t\t}\n\t\t\t\/\/ otherwise return username\n\t\t\treturn user.Username\n\t\t}\n\t}\n\t\/\/ if we didn't find nick, search for it\n\tmember, err := b.c.GuildMember(b.guildID, user.ID)\n\tif err != nil {\n\t\treturn user.Username\n\t}\n\tb.userMemberMap[user.ID] = member\n\t\/\/ only return if nick is set\n\tif b.userMemberMap[user.ID].Nick != \"\" {\n\t\treturn b.userMemberMap[user.ID].Nick\n\t}\n\treturn user.Username\n}\n\nfunc (b *Bdiscord) getChannelID(name string) string {\n\tidcheck := strings.Split(name, \"ID:\")\n\tif len(idcheck) > 1 {\n\t\treturn idcheck[1]\n\t}\n\tfor _, channel := range b.Channels {\n\t\tif channel.Name == name {\n\t\t\treturn channel.ID\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (b *Bdiscord) getChannelName(id string) string {\n\tfor _, channel := range b.Channels {\n\t\tif channel.ID == id {\n\t\t\treturn channel.Name\n\t\t}\n\t}\n\treturn \"\"\n}\n\nfunc (b *Bdiscord) replaceChannelMentions(text string) string {\n\tvar err error\n\tre := regexp.MustCompile(\"<#[0-9]+>\")\n\ttext = re.ReplaceAllStringFunc(text, func(m string) string {\n\t\tchannel := b.getChannelName(m[2 : len(m)-1])\n\t\t\/\/ if at first don't succeed, try again\n\t\tif channel == \"\" {\n\t\t\tb.Channels, err = b.c.GuildChannels(b.guildID)\n\t\t\tif err != nil {\n\t\t\t\treturn \"#unknownchannel\"\n\t\t\t}\n\t\t\tchannel = b.getChannelName(m[2 : len(m)-1])\n\t\t\treturn \"#\" + channel\n\t\t}\n\t\treturn \"#\" + channel\n\t})\n\treturn text\n}\n\nfunc (b *Bdiscord) replaceAction(text string) (string, bool) {\n\tif strings.HasPrefix(text, \"_\") && strings.HasSuffix(text, \"_\") {\n\t\treturn strings.Replace(text, \"_\", \"\", -1), true\n\t}\n\treturn text, false\n}\n\nfunc (b *Bdiscord) stripCustomoji(text string) string {\n\t\/\/ <:doge:302803592035958784>\n\tre := regexp.MustCompile(\"<(:.*?:)[0-9]+>\")\n\treturn re.ReplaceAllString(text, `$1`)\n}\n\n\/\/ splitURL splits a webhookURL and returns the id and token\nfunc (b *Bdiscord) splitURL(url string) (string, string) {\n\twebhookURLSplit := strings.Split(url, \"\/\")\n\tif len(webhookURLSplit) != 7 {\n\t\tb.Log.Fatalf(\"%s is no correct discord WebhookURL\", url)\n\t}\n\treturn webhookURLSplit[len(webhookURLSplit)-2], webhookURLSplit[len(webhookURLSplit)-1]\n}\n\n\/\/ useWebhook returns true if we have a webhook defined somewhere\nfunc (b *Bdiscord) useWebhook() bool {\n\tif b.GetString(\"WebhookURL\") != \"\" {\n\t\treturn true\n\t}\n\tfor _, channel := range b.channelInfoMap {\n\t\tif channel.Options.WebhookURL != \"\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ isWebhookID returns true if the specified id is used in a defined webhook\nfunc (b *Bdiscord) isWebhookID(id string) bool {\n\tif b.GetString(\"WebhookURL\") != \"\" {\n\t\twID, _ := b.splitURL(b.GetString(\"WebhookURL\"))\n\t\tif wID == id {\n\t\t\treturn true\n\t\t}\n\t}\n\tfor _, channel := range b.channelInfoMap {\n\t\tif channel.Options.WebhookURL != \"\" {\n\t\t\twID, _ := b.splitURL(channel.Options.WebhookURL)\n\t\t\tif wID == id {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ handleUploadFile handles native upload of files\nfunc (b *Bdiscord) handleUploadFile(msg *config.Message, channelID string) (string, error) {\n\tvar err error\n\tfor _, f := range msg.Extra[\"file\"] {\n\t\tfi := f.(config.FileInfo)\n\t\tfiles := []*discordgo.File{}\n\t\tfiles = append(files, &discordgo.File{fi.Name, \"\", bytes.NewReader(*fi.Data)})\n\t\t_, err = b.c.ChannelMessageSendComplex(channelID, &discordgo.MessageSend{Content: msg.Username + fi.Comment, Files: files})\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"file upload failed: %#v\", err)\n\t\t}\n\t}\n\treturn \"\", nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package buildkite\n\nimport (\n\t\"github.com\/buildkite\/agent\/buildkite\/logger\"\n\t\"github.com\/goinggo\/work\"\n\t\"time\"\n)\n\ntype LogStreamer struct {\n\t\/\/ The client we should use to stream the logs\n\tClient Client\n\n\t\/\/ How many log streamer workers are running at any one time\n\tConcurrency int\n\n\t\/\/ The streaming work queue\n\tQueue *work.Work\n\n\t\/\/ Total size in bytes of the log\n\tbytes int\n\n\t\/\/ The chunks of the log\n\tchunks []*LogStreamerChunk\n\n\t\/\/ Each chunk is assigned an order\n\torder int\n}\n\nfunc workLoggingFunction(message string) {\n\t\/\/ logger.Debug(\"Worker: %s\", message)\n}\n\nfunc NewLogStreamer(client *Client) (*LogStreamer, error) {\n\t\/\/ Create a new log streamer and default the concurrency to 5, seems\n\t\/\/ like a good number?\n\tstreamer := new(LogStreamer)\n\tstreamer.Concurrency = 5\n\n\treturn streamer, nil\n}\n\nfunc (streamer *LogStreamer) Start() error {\n\t\/\/ Create a new work queue\n\tw, err := work.New(streamer.Concurrency, time.Second, workLoggingFunction)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstreamer.Queue = w\n\n\treturn nil\n}\n\n\/\/ Takes the full process output, grabs the portion we don't have, and adds it\n\/\/ to the stream queue\nfunc (streamer *LogStreamer) Process(output string) error {\n\tbytes := len(output)\n\n\tif streamer.bytes != bytes {\n\t\t\/\/ Grab the part of the log that we haven't seen yet\n\t\tblob := output[streamer.bytes:bytes]\n\n\t\t\/\/ Increment the order\n\t\tstreamer.order += 1\n\n\t\t\/\/ Create the chunk and append it to our list\n\t\tchunk := LogStreamerChunk{\n\t\t\tOrder: streamer.order,\n\t\t\tBlob:  blob,\n\t\t\tBytes: len(blob),\n\t\t}\n\n\t\t\/\/ Append the chunk to our list\n\t\tstreamer.chunks = append(streamer.chunks, &chunk)\n\n\t\t\/\/ Create the worker and run it\n\t\tworker := LogStreamerWorker{Chunk: &chunk}\n\t\tgo func() {\n\t\t\t\/\/ Add the chunk worker to the queue. Run will block until it\n\t\t\t\/\/ is successfully added to the queue.\n\t\t\tstreamer.Queue.Run(&worker)\n\t\t}()\n\n\t\t\/\/ Save the new amount of bytes\n\t\tstreamer.bytes = bytes\n\t}\n\n\treturn nil\n}\n\nfunc (streamer *LogStreamer) Stop() error {\n\tlogger.Debug(\"Waiting for the log streaming workers to finish\")\n\n\tstreamer.Queue.Shutdown()\n\n\treturn nil\n}\n<commit_msg>Split the blobs into 100kb chunks.<commit_after>package buildkite\n\nimport (\n\t\"github.com\/buildkite\/agent\/buildkite\/logger\"\n\t\"github.com\/goinggo\/work\"\n\t\"math\"\n\t\"time\"\n)\n\ntype LogStreamer struct {\n\t\/\/ The client we should use to stream the logs\n\tClient Client\n\n\t\/\/ How many log streamer workers are running at any one time\n\tConcurrency int\n\n\t\/\/ The streaming work queue\n\tQueue *work.Work\n\n\t\/\/ Total size in bytes of the log\n\tbytes int\n\n\t\/\/ The chunks of the log\n\tchunks []*LogStreamerChunk\n\n\t\/\/ Each chunk is assigned an order\n\torder int\n}\n\nfunc workLoggingFunction(message string) {\n\t\/\/ logger.Debug(\"Worker: %s\", message)\n}\n\nfunc NewLogStreamer(client *Client) (*LogStreamer, error) {\n\t\/\/ Create a new log streamer and default the concurrency to 5, seems\n\t\/\/ like a good number?\n\tstreamer := new(LogStreamer)\n\tstreamer.Concurrency = 5\n\n\treturn streamer, nil\n}\n\nfunc (streamer *LogStreamer) Start() error {\n\t\/\/ Create a new work queue\n\tw, err := work.New(streamer.Concurrency, time.Second, workLoggingFunction)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstreamer.Queue = w\n\n\treturn nil\n}\n\n\/\/ Takes the full process output, grabs the portion we don't have, and adds it\n\/\/ to the stream queue\nfunc (streamer *LogStreamer) Process(output string) error {\n\tbytes := len(output)\n\n\tif streamer.bytes != bytes {\n\t\tmaximumBlobSize := 100000\n\n\t\t\/\/ Grab the part of the log that we haven't seen yet\n\t\tblob := output[streamer.bytes:bytes]\n\n\t\t\/\/ How many 100kb chunks are in the blob?\n\t\tnumberOfChunks := int(math.Ceil(float64(len(blob)) \/ float64(maximumBlobSize)))\n\n\t\tfor i := 0; i < numberOfChunks; i++ {\n\t\t\t\/\/ Find the upper limit of the blob\n\t\t\tupperLimit := (i + 1) * maximumBlobSize\n\t\t\tif upperLimit > len(blob) {\n\t\t\t\tupperLimit = len(blob)\n\t\t\t}\n\n\t\t\t\/\/ Grab the 100kb section of the blob\n\t\t\tpartialBlob := blob[i*maximumBlobSize : upperLimit]\n\n\t\t\t\/\/ Increment the order\n\t\t\tstreamer.order += 1\n\n\t\t\tlogger.Debug(\"Creating %d byte chunk\", len(partialBlob))\n\n\t\t\t\/\/ Create the chunk and append it to our list\n\t\t\tchunk := LogStreamerChunk{\n\t\t\t\tOrder: streamer.order,\n\t\t\t\tBlob:  partialBlob,\n\t\t\t\tBytes: len(partialBlob),\n\t\t\t}\n\n\t\t\t\/\/ Append the chunk to our list\n\t\t\tstreamer.chunks = append(streamer.chunks, &chunk)\n\n\t\t\t\/\/ Create the worker and run it\n\t\t\tworker := LogStreamerWorker{Chunk: &chunk}\n\t\t\tgo func() {\n\t\t\t\t\/\/ Add the chunk worker to the queue. Run will block until it\n\t\t\t\t\/\/ is successfully added to the queue.\n\t\t\t\tstreamer.Queue.Run(&worker)\n\t\t\t}()\n\t\t}\n\n\t\t\/\/ Save the new amount of bytes\n\t\tstreamer.bytes = bytes\n\t}\n\n\treturn nil\n}\n\nfunc (streamer *LogStreamer) Stop() error {\n\tlogger.Debug(\"Waiting for the log streaming workers to finish\")\n\n\tstreamer.Queue.Shutdown()\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Copyright 2015 @ z3q.net.\n * name : account\n * author : jarryliu\n * date : 2015-07-24 08:48\n * description :\n * history :\n *\/\npackage member\n\nconst (\n\t\/\/ 余额账户\n\tAccountBalance = 1\n\t\/\/ 积分账户\n\tAccountIntegral = 2\n\t\/\/ 赠送账户\n\tAccountPresent = 3\n\t\/\/ 流通金账户\n\tAccountFlow = 4\n)\n\nconst (\n\t\/\/ 用户充值\n\tChargeByUser = 1\n\t\/\/ 系统自动充值\n\tChargeBySystem = 2\n\t\/\/ 客服充值\n\tChargeByService = 3\n\t\/\/ 退款充值\n\tChargeByRefund = 4\n)\n\nconst (\n\t\/\/ 会员充值\n\tKindBalanceCharge = 1\n\t\/\/ 系统充值\n\tKindBalanceSystemCharge = 2\n\t\/\/ 客服充值\n\tKindBalanceServiceCharge = 3\n\t\/\/ 购物消费\n\tKindBalanceShopping = 4\n\t\/\/ 支付抵扣\n\tKindBalanceDiscount = 5\n\t\/\/ 客服扣件\n\tKindBalanceServiceDiscount = 6\n\t\/\/ 退款\n\tKindBalanceRefund = 7\n\t\/\/ 冻结\n\tKindBalanceFreeze = 8\n\t\/\/ 解冻\n\tKindBalanceUnfreeze = 9\n)\n\nconst (\n\t\/\/ 赠送金额\n\tKindPresentAdd = 1\n\t\/\/ 抵扣奖金\n\tKindPresentDiscount = 2\n\t\/\/ 客服赠送\n\tKindPresentServiceAdd = 3\n\t\/\/ 客服扣减\n\tKindPresentServiceDiscount = 4\n\t\/\/ 其他账户转入\n\tKindPresentTransferIn = 5\n\t\/\/ 提现\n\tKindPresentTakeOut = 6\n\t\/\/ 冻结\n\tKindPresentFreeze = 8\n\t\/\/ 解冻\n\tKindPresentUnfreeze = 9\n)\n\nconst (\n\tKindGrow = 7 \/\/ 增利\n\n\t\/\/KindCommission = 9 \/\/ 手续费\n\n\t\/\/ 赠送\n\t\/\/KindBalancePresent = 3\n\n\t\/\/ 流通账户\n\tKindBalanceFlow = 4 \/\/ 账户流通\n\n\t\/\/ 提现\n\tKindBalanceApplyCash = 11\n\t\/\/ 转账\n\tKindBalanceTransfer = 12\n\n\t\/\/ 提现并充值到余额\n\tTypeApplyCashToCharge = 1\n\t\/\/ 提现到银行卡\n\tTypeApplyCashToBank = 2\n\t\/\/ 提现到第三方服务提供商（如：Paypal,支付宝等)\n\tTypeApplyCashToServiceProvider = 3\n\n\t\/\/ 退款到银行卡\n\tTypeBackToBank = 1\n\t\/\/ 退款到第三方\n\tTypeBackToServiceProvider = 2\n\n\t\/\/ 提现请求已提交\n\tStateApplySubmitted = 0\n\t\/\/ 提现已经确认\n\tStateApplyConfirmed = 1\n\t\/\/ 提现未通过\n\tStateApplyNotPass = 2\n\t\/\/ 提现完成\n\tStateApplyOver = 3\n\n\tStatusNormal = 0\n\tStatusOK     = 1\n)\n\nconst (\n\t\/\/ 赠送\n\tTypeIntegralPresent = 1\n\t\/\/ 积分抵扣\n\tTypeIntegralDiscount = 2\n\t\/\/ 积分冻结\n\tTypeIntegralFreeze = 3\n\t\/\/ 积分解冻\n\tTypeIntegralUnfreeze = 4\n\t\/\/ 购物赠送\n\tTypeIntegralShoppingPresent = 5\n\t\/\/ 支付抵扣\n\tTypeIntegralPaymentDiscount = 6\n)\n\ntype (\n\tIAccount interface {\n\t\t\/\/ 获取领域对象编号\n\t\tGetDomainId() int\n\n\t\t\/\/ 获取账户值\n\t\tGetValue() *Account\n\n\t\t\/\/ 保存\n\t\tSave() (int, error)\n\n\t\t\/\/ 设置优先(默认)支付方式, account 为账户类型\n\t\tSetPriorityPay(account int, enabled bool) error\n\n\t\t\/\/ 根据编号获取余额变动信息\n\t\tGetBalanceInfo(id int) *BalanceInfo\n\n\t\t\/\/ 根据号码获取余额变动信息\n\t\t\/\/ GetBalanceInfoByNo(no string) *BalanceInfo\n\n\t\t\/\/ 保存余额变动信息\n\t\tSaveBalanceInfo(*BalanceInfo) (int, error)\n\n\t\t\/\/ 充值,客服操作时,需提供操作人(relateUser)\n\t\tChargeForBalance(chargeType int, title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 扣减余额\n\t\tDiscountBalance(title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 冻结余额\n\t\tFreeze(title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 解冻金额\n\t\tUnfreeze(title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 赠送金额,客服操作时,需提供操作人(relateUser)\n\t\tChargeForPresent(title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 赠送金额(指定业务类型)\n\t\tChargePresentByKind(kind int, title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 扣减奖金,mustLargeZero是否必须大于0, 赠送金额存在扣为负数的情况\n\t\tDiscountPresent(title string, outerNo string, amount float32,\n\t\t\trelateUser int, mustLargeZero bool) error\n\n\t\t\/\/ 冻结赠送金额\n\t\tFreezePresent(title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 解冻赠送金额\n\t\tUnfreezePresent(title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 流通账户余额变动，如扣除,amount传入负数金额\n\t\tChargeFlowBalance(title string, tradeNo string, amount float32) error\n\n\t\t\/\/ 支付单抵扣消费,tradeNo为支付单单号\n\t\tPaymentDiscount(tradeNo string, amount float32, remark string) error\n\n\t\t\/\/　增加积分\n\t\tAddIntegral(iType int, outerNo string, value int, remark string) error\n\n\t\t\/\/ 积分抵扣\n\t\tIntegralDiscount(logType int, outerNo string, value int, remark string) error\n\n\t\t\/\/ 冻结积分,当new为true不扣除积分,反之扣除积分\n\t\tFreezesIntegral(value int, new bool, remark string) error\n\n\t\t\/\/ 解冻积分\n\t\tUnfreezesIntegral(value int, remark string) error\n\n\t\t\/\/ 退款\n\t\tRequestBackBalance(backType int, title string, amount float32) error\n\n\t\t\/\/ 完成退款\n\t\tFinishBackBalance(id int, tradeNo string) error\n\n\t\t\/\/ 请求提现,applyType：提现方式,返回info_id,交易号 及错误\n\t\tRequestApplyCash(applyType int, title string, amount float32, commission float32) (int, string, error)\n\n\t\t\/\/ 确认提现\n\t\tConfirmApplyCash(id int, pass bool, remark string) error\n\n\t\t\/\/ 完成提现\n\t\tFinishApplyCash(id int, tradeNo string) error\n\n\t\t\/\/ 转账余额到其他账户\n\t\tTransferBalance(kind int, amount float32, tradeNo string, toTitle, fromTitle string) error\n\n\t\t\/\/ 转账返利账户,kind为转账类型，如 KindBalanceTransfer等\n\t\t\/\/ commission手续费\n\t\tTransferPresent(kind int, amount float32, commission float32, tradeNo string,\n\t\t\ttoTitle string, fromTitle string) error\n\n\t\t\/\/ 转账活动账户,kind为转账类型，如 KindBalanceTransfer等\n\t\t\/\/ commission手续费\n\t\tTransferFlow(kind int, amount float32, commission float32, tradeNo string,\n\t\t\ttoTitle string, fromTitle string) error\n\n\t\t\/\/ 将活动金转给其他人\n\t\tTransferFlowTo(memberId int, kind int, amount float32, commission float32,\n\t\t\ttradeNo string, toTitle string, fromTitle string) error\n\t}\n\n\t\/\/ 余额变动信息\n\tBalanceInfo struct {\n\t\tId       int    `db:\"id\" auto:\"yes\" pk:\"yes\"`\n\t\tMemberId int    `db:\"member_id\"`\n\t\tTradeNo  string `db:\"trade_no\"`\n\t\tKind     int    `db:\"kind\"`\n\t\tType     int    `db:\"type\"`\n\t\tTitle    string `db:\"title\"`\n\t\t\/\/ 金额\n\t\tAmount float32 `db:\"amount\"`\n\t\t\/\/ 手续费\n\t\tCsnAmount float32 `db:\"csn_amount\"`\n\t\t\/\/ 引用编号\n\t\tRefId      int   `db:\"ref_id\"`\n\t\tState      int   `db:\"state\"`\n\t\tCreateTime int64 `db:\"create_time\"`\n\t\tUpdateTime int64 `db:\"update_time\"`\n\t}\n\n\t\/\/ 余额日志\n\tBalanceLog struct {\n\t\tId       int    `db:\"id\" auto:\"yes\" pk:\"yes\"`\n\t\tMemberId int    `db:\"member_id\"`\n\t\tOuterNo  string `db:\"outer_no\"`\n\t\t\/\/ 业务类型\n\t\tBusinessKind int    `db:\"kind\"`\n\t\tTitle        string `db:\"title\"`\n\t\t\/\/ 金额\n\t\tAmount float32 `db:\"amount\"`\n\t\t\/\/ 手续费\n\t\tCsnFee float32 `db:\"csn_fee\"`\n\t\t\/\/ 关联操作人,仅在客服操作时,记录操作人\n\t\tRelateUser int   `db:\"rel_user\"`\n\t\tState      int   `db:\"state\"`\n\t\tCreateTime int64 `db:\"create_time\"`\n\t\tUpdateTime int64 `db:\"update_time\"`\n\t}\n\n\t\/\/ 赠送账户日志\n\tPresentLog struct {\n\t\tId       int    `db:\"id\" auto:\"yes\" pk:\"yes\"`\n\t\tMemberId int    `db:\"member_id\"`\n\t\tOuterNo  string `db:\"outer_no\"`\n\t\t\/\/ 业务类型\n\t\tBusinessKind int    `db:\"kind\"`\n\t\tTitle        string `db:\"title\"`\n\t\t\/\/ 金额\n\t\tAmount float32 `db:\"amount\"`\n\t\t\/\/ 手续费\n\t\tCsnFee float32 `db:\"csn_fee\"`\n\t\t\/\/ 关联操作人,仅在客服操作时,记录操作人\n\t\tRelateUser int   `db:\"rel_user\"`\n\t\tState      int   `db:\"state\"`\n\t\tCreateTime int64 `db:\"create_time\"`\n\t\tUpdateTime int64 `db:\"update_time\"`\n\t}\n\n\t\/\/ 账户值对象\n\tAccount struct {\n\t\t\/\/ 会员编号\n\t\tMemberId int `db:\"member_id\" pk:\"yes\" json:\"memberId\"`\n\t\t\/\/ 积分\n\t\tIntegral int `db:\"integral\"`\n\t\t\/\/ 不可用积分\n\t\tFreezeIntegral int `db:\"freeze_integral\"`\n\t\t\/\/ 余额\n\t\tBalance float32 `db:\"balance\" json:\"balance\"`\n\t\t\/\/ 不可用余额\n\t\tFreezeBalance float32 `db:\"freeze_balance\" json:\"freezesFee\"`\n\t\t\/\/ 失效的账户余额\n\t\tOutOfBalance float32 `db:\"out_balance\"`\n\t\t\/\/奖金账户余额\n\t\tPresentBalance float32 `db:\"present_balance\" json:\"presentBalance\"`\n\t\t\/\/冻结赠送金额\n\t\tFreezePresent float32 `db:\"freeze_present\" json:\"FreezePresent\"`\n\t\t\/\/失效的赠送金额\n\t\tOutOfPresent float32 `db:\"out_present\"`\n\t\t\/\/总赠送金额\n\t\tTotalPresentFee float32 `db:\"total_present_fee\" json:\"totalPresentFee\"`\n\t\t\/\/流动账户余额\n\t\tFlowBalance float32 `db:\"flow_balance\" json:\"flowBalance\"`\n\t\t\/\/当前理财账户余额\n\t\tGrowBalance float32 `db:\"grow_balance\" json:\"growBalance\"`\n\t\t\/\/理财总投资金额,不含收益\n\t\tGrowAmount float32 `db:\"grow_amount\" json:\"growAmount\"`\n\t\t\/\/当前收益金额\n\t\tGrowEarnings float32 `db:\"grow_earnings\" json:\"growEarnings\"`\n\t\t\/\/累积收益金额\n\t\tGrowTotalEarnings float32 `db:\"grow_total_earnings\" json:\"growTotalEarnings\"`\n\t\t\/\/总消费金额\n\t\tTotalConsumption float32 `db:\"total_consumption\" json:\"totalFee\"`\n\t\t\/\/总充值金额\n\t\tTotalCharge float32 `db:\"total_charge\" json:\"totalCharge\"`\n\t\t\/\/总支付额\n\t\tTotalPay float32 `db:\"total_pay\" json:\"totalPay\"`\n\t\t\/\/ 优先(默认)支付选项\n\t\tPriorityPay int `db:\"priority_pay\"`\n\t\t\/\/更新时间\n\t\tUpdateTime int64 `db:\"update_time\" json:\"updateTime\"`\n\t}\n\n\t\/\/ 积分记录\n\tIntegralLog struct {\n\t\t\/\/ 编号\n\t\tId int `db:\"id\" pk:\"yes\" auto:\"yes\"`\n\t\t\/\/ 会员编号\n\t\tMemberId int `db:\"member_id\"`\n\t\t\/\/ 类型\n\t\tType int `db:\"type\"`\n\t\t\/\/ 关联的编号\n\t\tOuterNo string `db:\"outer_no\"`\n\t\t\/\/ 积分值\n\t\tValue int `db:\"value\"`\n\t\t\/\/ 备注\n\t\tRemark string `db:\"remark\"`\n\t\t\/\/ 创建时间\n\t\tCreateTime int64 `db:\"create_time\"`\n\t}\n)\n<commit_msg>account<commit_after>\/**\n * Copyright 2015 @ z3q.net.\n * name : account\n * author : jarryliu\n * date : 2015-07-24 08:48\n * description :\n * history :\n *\/\npackage member\n\nconst (\n\t\/\/ 余额账户\n\tAccountBalance = 1\n\t\/\/ 积分账户\n\tAccountIntegral = 2\n\t\/\/ 赠送账户\n\tAccountPresent = 3\n\t\/\/ 流通金账户\n\tAccountFlow = 4\n)\n\nconst (\n\t\/\/ 用户充值\n\tChargeByUser = 1\n\t\/\/ 系统自动充值\n\tChargeBySystem = 2\n\t\/\/ 客服充值\n\tChargeByService = 3\n\t\/\/ 退款充值\n\tChargeByRefund = 4\n)\n\nconst (\n\t\/\/ 会员充值\n\tKindBalanceCharge = 1\n\t\/\/ 系统充值\n\tKindBalanceSystemCharge = 2\n\t\/\/ 客服充值\n\tKindBalanceServiceCharge = 3\n\t\/\/ 购物消费\n\tKindBalanceShopping = 4\n\t\/\/ 支付抵扣\n\tKindBalanceDiscount = 5\n\t\/\/ 客服扣件\n\tKindBalanceServiceDiscount = 6\n\t\/\/ 退款\n\tKindBalanceRefund = 7\n\t\/\/ 冻结\n\tKindBalanceFreeze = 8\n\t\/\/ 解冻\n\tKindBalanceUnfreeze = 9\n)\n\nconst (\n\t\/\/ 赠送金额\n\tKindPresentAdd = 1\n\t\/\/ 抵扣奖金\n\tKindPresentDiscount = 2\n\t\/\/ 客服赠送\n\tKindPresentServiceAdd = 3\n\t\/\/ 客服扣减\n\tKindPresentServiceDiscount = 4\n\t\/\/ 转入\n\tKindPresentTransferIn = 5\n\t\/\/ 转出\n\tKindPresentTransferOut = 6\n\t\/\/ 提现\n\tKindPresentTakeOut = 7\n\t\/\/ 冻结\n\tKindPresentFreeze = 8\n\t\/\/ 解冻\n\tKindPresentUnfreeze = 9\n)\n\nconst (\n\tKindGrow = 7 \/\/ 增利\n\n\t\/\/KindCommission = 9 \/\/ 手续费\n\n\t\/\/ 赠送\n\t\/\/KindBalancePresent = 3\n\n\t\/\/ 流通账户\n\tKindBalanceFlow = 4 \/\/ 账户流通\n\n\t\/\/ 提现\n\tKindBalanceApplyCash = 11\n\t\/\/ 转账\n\tKindBalanceTransfer = 12\n\n\t\/\/ 提现并充值到余额\n\tTypeApplyCashToCharge = 1\n\t\/\/ 提现到银行卡\n\tTypeApplyCashToBank = 2\n\t\/\/ 提现到第三方服务提供商（如：Paypal,支付宝等)\n\tTypeApplyCashToServiceProvider = 3\n\n\t\/\/ 退款到银行卡\n\tTypeBackToBank = 1\n\t\/\/ 退款到第三方\n\tTypeBackToServiceProvider = 2\n\n\t\/\/ 提现请求已提交\n\tStateApplySubmitted = 0\n\t\/\/ 提现已经确认\n\tStateApplyConfirmed = 1\n\t\/\/ 提现未通过\n\tStateApplyNotPass = 2\n\t\/\/ 提现完成\n\tStateApplyOver = 3\n\n\tStatusNormal = 0\n\tStatusOK     = 1\n)\n\nconst (\n\t\/\/ 赠送\n\tTypeIntegralPresent = 1\n\t\/\/ 积分抵扣\n\tTypeIntegralDiscount = 2\n\t\/\/ 积分冻结\n\tTypeIntegralFreeze = 3\n\t\/\/ 积分解冻\n\tTypeIntegralUnfreeze = 4\n\t\/\/ 购物赠送\n\tTypeIntegralShoppingPresent = 5\n\t\/\/ 支付抵扣\n\tTypeIntegralPaymentDiscount = 6\n)\n\ntype (\n\tIAccount interface {\n\t\t\/\/ 获取领域对象编号\n\t\tGetDomainId() int\n\n\t\t\/\/ 获取账户值\n\t\tGetValue() *Account\n\n\t\t\/\/ 保存\n\t\tSave() (int, error)\n\n\t\t\/\/ 设置优先(默认)支付方式, account 为账户类型\n\t\tSetPriorityPay(account int, enabled bool) error\n\n\t\t\/\/ 根据编号获取余额变动信息\n\t\tGetBalanceInfo(id int) *BalanceInfo\n\n\t\t\/\/ 根据号码获取余额变动信息\n\t\t\/\/ GetBalanceInfoByNo(no string) *BalanceInfo\n\n\t\t\/\/ 保存余额变动信息\n\t\tSaveBalanceInfo(*BalanceInfo) (int, error)\n\n\t\t\/\/ 充值,客服操作时,需提供操作人(relateUser)\n\t\tChargeForBalance(chargeType int, title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 扣减余额\n\t\tDiscountBalance(title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 冻结余额\n\t\tFreeze(title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 解冻金额\n\t\tUnfreeze(title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 赠送金额,客服操作时,需提供操作人(relateUser)\n\t\tChargeForPresent(title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 赠送金额(指定业务类型)\n\t\tChargePresentByKind(kind int, title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 扣减奖金,mustLargeZero是否必须大于0, 赠送金额存在扣为负数的情况\n\t\tDiscountPresent(title string, outerNo string, amount float32,\n\t\t\trelateUser int, mustLargeZero bool) error\n\n\t\t\/\/ 冻结赠送金额\n\t\tFreezePresent(title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 解冻赠送金额\n\t\tUnfreezePresent(title string, outerNo string, amount float32, relateUser int) error\n\n\t\t\/\/ 流通账户余额变动，如扣除,amount传入负数金额\n\t\tChargeFlowBalance(title string, tradeNo string, amount float32) error\n\n\t\t\/\/ 支付单抵扣消费,tradeNo为支付单单号\n\t\tPaymentDiscount(tradeNo string, amount float32, remark string) error\n\n\t\t\/\/　增加积分\n\t\tAddIntegral(iType int, outerNo string, value int, remark string) error\n\n\t\t\/\/ 积分抵扣\n\t\tIntegralDiscount(logType int, outerNo string, value int, remark string) error\n\n\t\t\/\/ 冻结积分,当new为true不扣除积分,反之扣除积分\n\t\tFreezesIntegral(value int, new bool, remark string) error\n\n\t\t\/\/ 解冻积分\n\t\tUnfreezesIntegral(value int, remark string) error\n\n\t\t\/\/ 退款\n\t\tRequestBackBalance(backType int, title string, amount float32) error\n\n\t\t\/\/ 完成退款\n\t\tFinishBackBalance(id int, tradeNo string) error\n\n\t\t\/\/ 请求提现,applyType：提现方式,返回info_id,交易号 及错误\n\t\tRequestApplyCash(applyType int, title string, amount float32, commission float32) (int, string, error)\n\n\t\t\/\/ 确认提现\n\t\tConfirmApplyCash(id int, pass bool, remark string) error\n\n\t\t\/\/ 完成提现\n\t\tFinishApplyCash(id int, tradeNo string) error\n\n\t\t\/\/ 转账余额到其他账户\n\t\tTransferBalance(kind int, amount float32, tradeNo string, toTitle, fromTitle string) error\n\n\t\t\/\/ 转账返利账户,kind为转账类型，如 KindBalanceTransfer等\n\t\t\/\/ commission手续费\n\t\tTransferPresent(kind int, amount float32, commission float32, tradeNo string,\n\t\t\ttoTitle string, fromTitle string) error\n\n\t\t\/\/ 转账活动账户,kind为转账类型，如 KindBalanceTransfer等\n\t\t\/\/ commission手续费\n\t\tTransferFlow(kind int, amount float32, commission float32, tradeNo string,\n\t\t\ttoTitle string, fromTitle string) error\n\n\t\t\/\/ 将活动金转给其他人\n\t\tTransferFlowTo(memberId int, kind int, amount float32, commission float32,\n\t\t\ttradeNo string, toTitle string, fromTitle string) error\n\t}\n\n\t\/\/ 余额变动信息\n\tBalanceInfo struct {\n\t\tId       int    `db:\"id\" auto:\"yes\" pk:\"yes\"`\n\t\tMemberId int    `db:\"member_id\"`\n\t\tTradeNo  string `db:\"trade_no\"`\n\t\tKind     int    `db:\"kind\"`\n\t\tType     int    `db:\"type\"`\n\t\tTitle    string `db:\"title\"`\n\t\t\/\/ 金额\n\t\tAmount float32 `db:\"amount\"`\n\t\t\/\/ 手续费\n\t\tCsnAmount float32 `db:\"csn_amount\"`\n\t\t\/\/ 引用编号\n\t\tRefId      int   `db:\"ref_id\"`\n\t\tState      int   `db:\"state\"`\n\t\tCreateTime int64 `db:\"create_time\"`\n\t\tUpdateTime int64 `db:\"update_time\"`\n\t}\n\n\t\/\/ 余额日志\n\tBalanceLog struct {\n\t\tId       int    `db:\"id\" auto:\"yes\" pk:\"yes\"`\n\t\tMemberId int    `db:\"member_id\"`\n\t\tOuterNo  string `db:\"outer_no\"`\n\t\t\/\/ 业务类型\n\t\tBusinessKind int    `db:\"kind\"`\n\t\tTitle        string `db:\"title\"`\n\t\t\/\/ 金额\n\t\tAmount float32 `db:\"amount\"`\n\t\t\/\/ 手续费\n\t\tCsnFee float32 `db:\"csn_fee\"`\n\t\t\/\/ 关联操作人,仅在客服操作时,记录操作人\n\t\tRelateUser int   `db:\"rel_user\"`\n\t\tState      int   `db:\"state\"`\n\t\tCreateTime int64 `db:\"create_time\"`\n\t\tUpdateTime int64 `db:\"update_time\"`\n\t}\n\n\t\/\/ 赠送账户日志\n\tPresentLog struct {\n\t\tId       int    `db:\"id\" auto:\"yes\" pk:\"yes\"`\n\t\tMemberId int    `db:\"member_id\"`\n\t\tOuterNo  string `db:\"outer_no\"`\n\t\t\/\/ 业务类型\n\t\tBusinessKind int    `db:\"kind\"`\n\t\tTitle        string `db:\"title\"`\n\t\t\/\/ 金额\n\t\tAmount float32 `db:\"amount\"`\n\t\t\/\/ 手续费\n\t\tCsnFee float32 `db:\"csn_fee\"`\n\t\t\/\/ 关联操作人,仅在客服操作时,记录操作人\n\t\tRelateUser int   `db:\"rel_user\"`\n\t\tState      int   `db:\"state\"`\n\t\tCreateTime int64 `db:\"create_time\"`\n\t\tUpdateTime int64 `db:\"update_time\"`\n\t}\n\n\t\/\/ 账户值对象\n\tAccount struct {\n\t\t\/\/ 会员编号\n\t\tMemberId int `db:\"member_id\" pk:\"yes\" json:\"memberId\"`\n\t\t\/\/ 积分\n\t\tIntegral int `db:\"integral\"`\n\t\t\/\/ 不可用积分\n\t\tFreezeIntegral int `db:\"freeze_integral\"`\n\t\t\/\/ 余额\n\t\tBalance float32 `db:\"balance\" json:\"balance\"`\n\t\t\/\/ 不可用余额\n\t\tFreezeBalance float32 `db:\"freeze_balance\" json:\"freezesFee\"`\n\t\t\/\/ 失效的账户余额\n\t\tOutOfBalance float32 `db:\"out_balance\"`\n\t\t\/\/奖金账户余额\n\t\tPresentBalance float32 `db:\"present_balance\" json:\"presentBalance\"`\n\t\t\/\/冻结赠送金额\n\t\tFreezePresent float32 `db:\"freeze_present\" json:\"FreezePresent\"`\n\t\t\/\/失效的赠送金额\n\t\tOutOfPresent float32 `db:\"out_present\"`\n\t\t\/\/总赠送金额\n\t\tTotalPresentFee float32 `db:\"total_present_fee\" json:\"totalPresentFee\"`\n\t\t\/\/流动账户余额\n\t\tFlowBalance float32 `db:\"flow_balance\" json:\"flowBalance\"`\n\t\t\/\/当前理财账户余额\n\t\tGrowBalance float32 `db:\"grow_balance\" json:\"growBalance\"`\n\t\t\/\/理财总投资金额,不含收益\n\t\tGrowAmount float32 `db:\"grow_amount\" json:\"growAmount\"`\n\t\t\/\/当前收益金额\n\t\tGrowEarnings float32 `db:\"grow_earnings\" json:\"growEarnings\"`\n\t\t\/\/累积收益金额\n\t\tGrowTotalEarnings float32 `db:\"grow_total_earnings\" json:\"growTotalEarnings\"`\n\t\t\/\/总消费金额\n\t\tTotalConsumption float32 `db:\"total_consumption\" json:\"totalFee\"`\n\t\t\/\/总充值金额\n\t\tTotalCharge float32 `db:\"total_charge\" json:\"totalCharge\"`\n\t\t\/\/总支付额\n\t\tTotalPay float32 `db:\"total_pay\" json:\"totalPay\"`\n\t\t\/\/ 优先(默认)支付选项\n\t\tPriorityPay int `db:\"priority_pay\"`\n\t\t\/\/更新时间\n\t\tUpdateTime int64 `db:\"update_time\" json:\"updateTime\"`\n\t}\n\n\t\/\/ 积分记录\n\tIntegralLog struct {\n\t\t\/\/ 编号\n\t\tId int `db:\"id\" pk:\"yes\" auto:\"yes\"`\n\t\t\/\/ 会员编号\n\t\tMemberId int `db:\"member_id\"`\n\t\t\/\/ 类型\n\t\tType int `db:\"type\"`\n\t\t\/\/ 关联的编号\n\t\tOuterNo string `db:\"outer_no\"`\n\t\t\/\/ 积分值\n\t\tValue int `db:\"value\"`\n\t\t\/\/ 备注\n\t\tRemark string `db:\"remark\"`\n\t\t\/\/ 创建时间\n\t\tCreateTime int64 `db:\"create_time\"`\n\t}\n)\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Matthew Baird\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage elastigo\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ Max buffer size in bytes before flushing to elasticsearch\n\tBulkMaxBuffer = 16384\n\t\/\/ Max number of Docs to hold in buffer before forcing flush\n\tBulkMaxDocs = 100\n\t\/\/ Max delay before forcing a flush to Elasticearch\n\tBulkDelaySeconds = 5\n\t\/\/ maximum wait shutdown seconds\n\tMAX_SHUTDOWN_SECS = 5\n)\n\ntype ErrorBuffer struct {\n\tErr error\n\tBuf *bytes.Buffer\n}\n\n\/\/ A bulk indexer creates goroutines, and channels for connecting and sending data\n\/\/ to elasticsearch in bulk, using buffers.\ntype BulkIndexer struct {\n\tconn *Conn\n\n\t\/\/ We are creating a variable defining the func responsible for sending\n\t\/\/ to allow a mock sendor for test purposes\n\tSender func(*bytes.Buffer) error\n\n\t\/\/ If we encounter an error in sending, we are going to retry for this long\n\t\/\/ before returning an error\n\t\/\/ if 0 it will not retry\n\tRetryForSeconds int\n\n\t\/\/ channel for getting errors\n\tErrorChannel chan *ErrorBuffer\n\n\t\/\/ channel for sending to background indexer\n\tbulkChannel chan []byte\n\n\t\/\/ numErrors is a running total of errors seen\n\tnumErrors uint64\n\n\t\/\/ shutdown channel\n\tshutdownChan chan chan struct{}\n\t\/\/ channel to shutdown timer\n\ttimerDoneChan chan struct{}\n\n\t\/\/ Channel to send a complete byte.Buffer to the http sendor\n\tsendBuf chan *bytes.Buffer\n\t\/\/ byte buffer for docs that have been converted to bytes, but not yet sent\n\tbuf *bytes.Buffer\n\t\/\/ Buffer for Max number of time before forcing flush\n\tBufferDelayMax time.Duration\n\t\/\/ Max buffer size in bytes before flushing to elasticsearch\n\tBulkMaxBuffer int \/\/ 1048576\n\t\/\/ Max number of Docs to hold in buffer before forcing flush\n\tBulkMaxDocs int \/\/ 100\n\n\t\/\/ Number of documents we have send through so far on this session\n\tdocCt int\n\t\/\/ Max number of http conns in flight at one time\n\tmaxConns int\n\t\/\/ If we are indexing enough docs per bufferdelaymax, we won't need to do time\n\t\/\/ based eviction, else we do.\n\tneedsTimeBasedFlush bool\n\t\/\/ Lock for document writes\/operations\n\tmu sync.Mutex\n\t\/\/ Wait Group for the http sends\n\tsendWg *sync.WaitGroup\n}\n\nfunc (b *BulkIndexer) NumErrors() uint64 {\n\treturn b.numErrors\n}\n\nfunc (c *Conn) NewBulkIndexer(maxConns int) *BulkIndexer {\n\tb := BulkIndexer{conn: c, sendBuf: make(chan *bytes.Buffer, maxConns)}\n\tb.needsTimeBasedFlush = true\n\tb.buf = new(bytes.Buffer)\n\tb.maxConns = maxConns\n\tb.BulkMaxBuffer = BulkMaxBuffer\n\tb.BulkMaxDocs = BulkMaxDocs\n\tb.BufferDelayMax = time.Duration(BulkDelaySeconds) * time.Second\n\tb.bulkChannel = make(chan []byte, 100)\n\tb.sendWg = new(sync.WaitGroup)\n\tb.timerDoneChan = make(chan struct{})\n\treturn &b\n}\n\n\/\/ A bulk indexer with more control over error handling\n\/\/    @maxConns is the max number of in flight http requests\n\/\/    @retrySeconds is # of seconds to wait before retrying falied requests\n\/\/\n\/\/   done := make(chan bool)\n\/\/   BulkIndexerGlobalRun(100, done)\nfunc (c *Conn) NewBulkIndexerErrors(maxConns, retrySeconds int) *BulkIndexer {\n\tb := c.NewBulkIndexer(maxConns)\n\tb.RetryForSeconds = retrySeconds\n\tb.ErrorChannel = make(chan *ErrorBuffer, 20)\n\treturn b\n}\n\n\/\/ Starts this bulk Indexer running, this Run opens a go routine so is\n\/\/ Non blocking\nfunc (b *BulkIndexer) Start() {\n\tb.shutdownChan = make(chan chan struct{})\n\n\tgo func() {\n\t\t\/\/ XXX(j): Refactor this stuff to use an interface.\n\t\tif b.Sender == nil {\n\t\t\tb.Sender = b.Send\n\t\t}\n\t\t\/\/ Backwards compatibility\n\t\tb.startHttpSender()\n\t\tb.startDocChannel()\n\t\tb.startTimer()\n\t\tch := <-b.shutdownChan\n\t\tb.Flush()\n\t\tb.shutdown()\n\t\tch <- struct{}{}\n\t}()\n}\n\n\/\/ Stop stops the bulk indexer, blocking the caller until it is complete.\nfunc (b *BulkIndexer) Stop() {\n\tch := make(chan struct{})\n\tb.shutdownChan <- ch\n\tselect {\n\tcase <-ch:\n\t\t\/\/ done\n\tcase <-time.After(time.Second * time.Duration(MAX_SHUTDOWN_SECS)):\n\t\t\/\/ timeout!\n\t}\n}\n\n\/\/ Make a channel that will close when the given WaitGroup is done.\nfunc wgChan(wg *sync.WaitGroup) <-chan interface{} {\n\tch := make(chan interface{})\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(ch)\n\t}()\n\treturn ch\n}\n\nfunc (b *BulkIndexer) PendingDocuments() int {\n\treturn b.docCt\n}\n\n\/\/ Flush all current documents to ElasticSearch\nfunc (b *BulkIndexer) Flush() {\n\tb.mu.Lock()\n\tif b.docCt > 0 {\n\t\tb.send(b.buf)\n\t}\n\tb.mu.Unlock()\n}\n\nfunc (b *BulkIndexer) startHttpSender() {\n\n\t\/\/ this sends http requests to elasticsearch it uses maxConns to open up that\n\t\/\/ many goroutines, each of which will synchronously call ElasticSearch\n\t\/\/ in theory, the whole set will cause a backup all the way to IndexBulk if\n\t\/\/ we have consumed all maxConns\n\tfor i := 0; i < b.maxConns; i++ {\n\t\tgo func() {\n\t\t\tfor buf := range b.sendBuf {\n\t\t\t\tb.sendWg.Add(1)\n\t\t\t\t\/\/ Copy for the potential re-send.\n\t\t\t\tbufCopy := bytes.NewBuffer(buf.Bytes())\n\t\t\t\terr := b.Sender(buf)\n\n\t\t\t\t\/\/ Perhaps a b.FailureStrategy(err)  ??  with different types of strategies\n\t\t\t\t\/\/  1.  Retry, then panic\n\t\t\t\t\/\/  2.  Retry then return error and let runner decide\n\t\t\t\t\/\/  3.  Retry, then log to disk?   retry later?\n\t\t\t\tif err != nil {\n\t\t\t\t\tif b.RetryForSeconds > 0 {\n\t\t\t\t\t\ttime.Sleep(time.Second * time.Duration(b.RetryForSeconds))\n\t\t\t\t\t\terr = b.Sender(bufCopy)\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t\/\/ Successfully re-sent with no error\n\t\t\t\t\t\t\tb.sendWg.Done()\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif b.ErrorChannel != nil {\n\t\t\t\t\t\tb.ErrorChannel <- &ErrorBuffer{err, buf}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tb.sendWg.Done()\n\t\t\t}\n\t\t}()\n\t}\n}\n\n\/\/ start a timer for checking back and forcing flush ever BulkDelaySeconds seconds\n\/\/ even if we haven't hit max messages\/size\nfunc (b *BulkIndexer) startTimer() {\n\tticker := time.NewTicker(b.BufferDelayMax)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tb.mu.Lock()\n\t\t\t\t\/\/ don't send unless last sendor was the time,\n\t\t\t\t\/\/ otherwise an indication of other thresholds being hit\n\t\t\t\t\/\/ where time isn't needed\n\t\t\t\tif b.buf.Len() > 0 && b.needsTimeBasedFlush {\n\t\t\t\t\tb.needsTimeBasedFlush = true\n\t\t\t\t\tb.send(b.buf)\n\t\t\t\t} else if b.buf.Len() > 0 {\n\t\t\t\t\tb.needsTimeBasedFlush = true\n\t\t\t\t}\n\t\t\t\tb.mu.Unlock()\n\t\t\tcase <-b.timerDoneChan:\n\t\t\t\t\/\/ shutdown this go routine\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n}\n\nfunc (b *BulkIndexer) startDocChannel() {\n\t\/\/ This goroutine accepts incoming byte arrays from the IndexBulk function and\n\t\/\/ writes to buffer\n\tgo func() {\n\t\tfor docBytes := range b.bulkChannel {\n\t\t\tb.mu.Lock()\n\t\t\tb.docCt += 1\n\t\t\tb.buf.Write(docBytes)\n\t\t\tif b.buf.Len() >= b.BulkMaxBuffer || b.docCt >= b.BulkMaxDocs {\n\t\t\t\tb.needsTimeBasedFlush = false\n\t\t\t\t\/\/log.Printf(\"Send due to size:  docs=%d  bufsize=%d\", b.docCt, b.buf.Len())\n\t\t\t\tb.send(b.buf)\n\t\t\t}\n\t\t\tb.mu.Unlock()\n\t\t}\n\t}()\n}\n\nfunc (b *BulkIndexer) send(buf *bytes.Buffer) {\n\t\/\/b2 := *b.buf\n\tb.sendBuf <- buf\n\tb.buf = new(bytes.Buffer)\n\t\/\/\tb.buf.Reset()\n\tb.docCt = 0\n}\n\nfunc (b *BulkIndexer) shutdown() {\n\t\/\/ This must be called after Flush()\n\tclose(b.timerDoneChan)\n\tclose(b.sendBuf)\n\tclose(b.bulkChannel)\n\t<-wgChan(b.sendWg)\n}\n\n\/\/ The index bulk API adds or updates a typed JSON document to a specific index, making it searchable.\n\/\/ it operates by buffering requests, and ocassionally flushing to elasticsearch\n\/\/ http:\/\/www.elasticsearch.org\/guide\/reference\/api\/bulk.html\nfunc (b *BulkIndexer) Index(index string, _type string, id, ttl string, date *time.Time, data interface{}, refresh bool) error {\n\t\/\/{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n\tby, err := WriteBulkBytes(\"index\", index, _type, id, ttl, date, data, refresh)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.bulkChannel <- by\n\treturn nil\n}\n\nfunc (b *BulkIndexer) Update(index string, _type string, id, ttl string, date *time.Time, data interface{}, refresh bool) error {\n\t\/\/{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n\tby, err := WriteBulkBytes(\"update\", index, _type, id, ttl, date, data, refresh)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.bulkChannel <- by\n\treturn nil\n}\n\nfunc (b *BulkIndexer) Delete(index, _type, id string, refresh bool) {\n\tqueryLine := fmt.Sprintf(\"{\\\"delete\\\":{\\\"_index\\\":%q,\\\"_type\\\":%q,\\\"_id\\\":%q,\\\"refresh\\\":%t}}\\n\", index, _type, id, refresh)\n\tb.bulkChannel <- []byte(queryLine)\n\treturn\n}\n\nfunc (b *BulkIndexer) UpdateWithWithScript(index string, _type string, id, ttl string, date *time.Time, script string, refresh bool) error {\n\n\tvar data map[string]interface{} = make(map[string]interface{})\n\tdata[\"script\"] = script\n\treturn b.Update(index, _type, id, ttl, date, data, refresh)\n}\n\nfunc (b *BulkIndexer) UpdateWithPartialDoc(index string, _type string, id, ttl string, date *time.Time, partialDoc interface{}, upsert bool, refresh bool) error {\n\n\tvar data map[string]interface{} = make(map[string]interface{})\n\n\tdata[\"doc\"] = partialDoc\n\tif upsert {\n\t\tdata[\"doc_as_upsert\"] = true\n\t}\n\treturn b.Update(index, _type, id, ttl, date, data, refresh)\n}\n\n\/\/ This does the actual send of a buffer, which has already been formatted\n\/\/ into bytes of ES formatted bulk data\nfunc (b *BulkIndexer) Send(buf *bytes.Buffer) error {\n\ttype responseStruct struct {\n\t\tTook   int64                    `json:\"took\"`\n\t\tErrors bool                     `json:\"errors\"`\n\t\tItems  []map[string]interface{} `json:\"items\"`\n\t}\n\n\tresponse := responseStruct{}\n\n\tbody, err := b.conn.DoCommand(\"POST\", \"\/_bulk\", nil, buf)\n\n\tif err != nil {\n\t\tb.numErrors += 1\n\t\treturn err\n\t}\n\t\/\/ check for response errors, bulk insert will give 200 OK but then include errors in response\n\tjsonErr := json.Unmarshal(body, &response)\n\tif jsonErr == nil {\n\t\tif response.Errors {\n\t\t\tb.numErrors += uint64(len(response.Items))\n\t\t\treturn fmt.Errorf(\"Bulk Insertion Error. Failed item count [%d]\", len(response.Items))\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Given a set of arguments for index, type, id, data create a set of bytes that is formatted for bulkd index\n\/\/ http:\/\/www.elasticsearch.org\/guide\/reference\/api\/bulk.html\nfunc WriteBulkBytes(op string, index string, _type string, id, ttl string, date *time.Time, data interface{}, refresh bool) ([]byte, error) {\n\t\/\/ only index and update are currently supported\n\tif op != \"index\" && op != \"update\" {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Operation '%s' is not yet supported\", op))\n\t}\n\n\t\/\/ First line\n\tbuf := bytes.Buffer{}\n\tbuf.WriteString(fmt.Sprintf(`{\"%s\":{\"_index\":\"`, op))\n\tbuf.WriteString(index)\n\tbuf.WriteString(`\",\"_type\":\"`)\n\tbuf.WriteString(_type)\n\tbuf.WriteString(`\"`)\n\tif len(id) > 0 {\n\t\tbuf.WriteString(`,\"_id\":\"`)\n\t\tbuf.WriteString(id)\n\t\tbuf.WriteString(`\"`)\n\t}\n\n\tif op == \"update\" {\n\t\tbuf.WriteString(`,\"retry_on_conflict\":3`)\n\t}\n\n\tif len(ttl) > 0 {\n\t\tbuf.WriteString(`,\"ttl\":\"`)\n\t\tbuf.WriteString(ttl)\n\t\tbuf.WriteString(`\"`)\n\t}\n\tif date != nil {\n\t\tbuf.WriteString(`,\"_timestamp\":\"`)\n\t\tbuf.WriteString(strconv.FormatInt(date.UnixNano()\/1e6, 10))\n\t\tbuf.WriteString(`\"`)\n\t}\n\tif refresh {\n\t\tbuf.WriteString(`,\"refresh\":true`)\n\t}\n\tbuf.WriteString(`}}`)\n\tbuf.WriteRune('\\n')\n\t\/\/buf.WriteByte('\\n')\n\tswitch v := data.(type) {\n\tcase *bytes.Buffer:\n\t\tio.Copy(&buf, v)\n\tcase []byte:\n\t\tbuf.Write(v)\n\tcase string:\n\t\tbuf.WriteString(v)\n\tdefault:\n\t\tbody, jsonErr := json.Marshal(data)\n\t\tif jsonErr != nil {\n\t\t\treturn nil, jsonErr\n\t\t}\n\t\tbuf.Write(body)\n\t}\n\tbuf.WriteRune('\\n')\n\treturn buf.Bytes(), nil\n}\n<commit_msg>Insert a milli-sleep after Stop() has been called to let other goros set the buffer before flushing. Without this, a quick, small bulk write will never actually be sent.<commit_after>\/\/ Copyright 2013 Matthew Baird\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage elastigo\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ Max buffer size in bytes before flushing to elasticsearch\n\tBulkMaxBuffer = 16384\n\t\/\/ Max number of Docs to hold in buffer before forcing flush\n\tBulkMaxDocs = 100\n\t\/\/ Max delay before forcing a flush to Elasticearch\n\tBulkDelaySeconds = 5\n\t\/\/ maximum wait shutdown seconds\n\tMAX_SHUTDOWN_SECS = 5\n)\n\ntype ErrorBuffer struct {\n\tErr error\n\tBuf *bytes.Buffer\n}\n\n\/\/ A bulk indexer creates goroutines, and channels for connecting and sending data\n\/\/ to elasticsearch in bulk, using buffers.\ntype BulkIndexer struct {\n\tconn *Conn\n\n\t\/\/ We are creating a variable defining the func responsible for sending\n\t\/\/ to allow a mock sendor for test purposes\n\tSender func(*bytes.Buffer) error\n\n\t\/\/ If we encounter an error in sending, we are going to retry for this long\n\t\/\/ before returning an error\n\t\/\/ if 0 it will not retry\n\tRetryForSeconds int\n\n\t\/\/ channel for getting errors\n\tErrorChannel chan *ErrorBuffer\n\n\t\/\/ channel for sending to background indexer\n\tbulkChannel chan []byte\n\n\t\/\/ numErrors is a running total of errors seen\n\tnumErrors uint64\n\n\t\/\/ shutdown channel\n\tshutdownChan chan chan struct{}\n\t\/\/ channel to shutdown timer\n\ttimerDoneChan chan struct{}\n\n\t\/\/ Channel to send a complete byte.Buffer to the http sendor\n\tsendBuf chan *bytes.Buffer\n\t\/\/ byte buffer for docs that have been converted to bytes, but not yet sent\n\tbuf *bytes.Buffer\n\t\/\/ Buffer for Max number of time before forcing flush\n\tBufferDelayMax time.Duration\n\t\/\/ Max buffer size in bytes before flushing to elasticsearch\n\tBulkMaxBuffer int \/\/ 1048576\n\t\/\/ Max number of Docs to hold in buffer before forcing flush\n\tBulkMaxDocs int \/\/ 100\n\n\t\/\/ Number of documents we have send through so far on this session\n\tdocCt int\n\t\/\/ Max number of http conns in flight at one time\n\tmaxConns int\n\t\/\/ If we are indexing enough docs per bufferdelaymax, we won't need to do time\n\t\/\/ based eviction, else we do.\n\tneedsTimeBasedFlush bool\n\t\/\/ Lock for document writes\/operations\n\tmu sync.Mutex\n\t\/\/ Wait Group for the http sends\n\tsendWg *sync.WaitGroup\n}\n\nfunc (b *BulkIndexer) NumErrors() uint64 {\n\treturn b.numErrors\n}\n\nfunc (c *Conn) NewBulkIndexer(maxConns int) *BulkIndexer {\n\tb := BulkIndexer{conn: c, sendBuf: make(chan *bytes.Buffer, maxConns)}\n\tb.needsTimeBasedFlush = true\n\tb.buf = new(bytes.Buffer)\n\tb.maxConns = maxConns\n\tb.BulkMaxBuffer = BulkMaxBuffer\n\tb.BulkMaxDocs = BulkMaxDocs\n\tb.BufferDelayMax = time.Duration(BulkDelaySeconds) * time.Second\n\tb.bulkChannel = make(chan []byte, 100)\n\tb.sendWg = new(sync.WaitGroup)\n\tb.timerDoneChan = make(chan struct{})\n\treturn &b\n}\n\n\/\/ A bulk indexer with more control over error handling\n\/\/    @maxConns is the max number of in flight http requests\n\/\/    @retrySeconds is # of seconds to wait before retrying falied requests\n\/\/\n\/\/   done := make(chan bool)\n\/\/   BulkIndexerGlobalRun(100, done)\nfunc (c *Conn) NewBulkIndexerErrors(maxConns, retrySeconds int) *BulkIndexer {\n\tb := c.NewBulkIndexer(maxConns)\n\tb.RetryForSeconds = retrySeconds\n\tb.ErrorChannel = make(chan *ErrorBuffer, 20)\n\treturn b\n}\n\n\/\/ Starts this bulk Indexer running, this Run opens a go routine so is\n\/\/ Non blocking\nfunc (b *BulkIndexer) Start() {\n\tb.shutdownChan = make(chan chan struct{})\n\n\tgo func() {\n\t\t\/\/ XXX(j): Refactor this stuff to use an interface.\n\t\tif b.Sender == nil {\n\t\t\tb.Sender = b.Send\n\t\t}\n\t\t\/\/ Backwards compatibility\n\t\tb.startHttpSender()\n\t\tb.startDocChannel()\n\t\tb.startTimer()\n\t\tch := <-b.shutdownChan\n\t\ttime.Sleep(2 * time.Millisecond)\n\t\tb.Flush()\n\t\tb.shutdown()\n\t\tch <- struct{}{}\n\t}()\n}\n\n\/\/ Stop stops the bulk indexer, blocking the caller until it is complete.\nfunc (b *BulkIndexer) Stop() {\n\tch := make(chan struct{})\n\tb.shutdownChan <- ch\n\tselect {\n\tcase <-ch:\n\t\t\/\/ done\n\tcase <-time.After(time.Second * time.Duration(MAX_SHUTDOWN_SECS)):\n\t\t\/\/ timeout!\n\t}\n}\n\n\/\/ Make a channel that will close when the given WaitGroup is done.\nfunc wgChan(wg *sync.WaitGroup) <-chan interface{} {\n\tch := make(chan interface{})\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(ch)\n\t}()\n\treturn ch\n}\n\nfunc (b *BulkIndexer) PendingDocuments() int {\n\treturn b.docCt\n}\n\n\/\/ Flush all current documents to ElasticSearch\nfunc (b *BulkIndexer) Flush() {\n\tb.mu.Lock()\n\tif b.docCt > 0 {\n\t\tb.send(b.buf)\n\t}\n\tb.mu.Unlock()\n}\n\nfunc (b *BulkIndexer) startHttpSender() {\n\n\t\/\/ this sends http requests to elasticsearch it uses maxConns to open up that\n\t\/\/ many goroutines, each of which will synchronously call ElasticSearch\n\t\/\/ in theory, the whole set will cause a backup all the way to IndexBulk if\n\t\/\/ we have consumed all maxConns\n\tfor i := 0; i < b.maxConns; i++ {\n\t\tgo func() {\n\t\t\tfor buf := range b.sendBuf {\n\t\t\t\tb.sendWg.Add(1)\n\t\t\t\t\/\/ Copy for the potential re-send.\n\t\t\t\tbufCopy := bytes.NewBuffer(buf.Bytes())\n\t\t\t\terr := b.Sender(buf)\n\n\t\t\t\t\/\/ Perhaps a b.FailureStrategy(err)  ??  with different types of strategies\n\t\t\t\t\/\/  1.  Retry, then panic\n\t\t\t\t\/\/  2.  Retry then return error and let runner decide\n\t\t\t\t\/\/  3.  Retry, then log to disk?   retry later?\n\t\t\t\tif err != nil {\n\t\t\t\t\tif b.RetryForSeconds > 0 {\n\t\t\t\t\t\ttime.Sleep(time.Second * time.Duration(b.RetryForSeconds))\n\t\t\t\t\t\terr = b.Sender(bufCopy)\n\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t\/\/ Successfully re-sent with no error\n\t\t\t\t\t\t\tb.sendWg.Done()\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif b.ErrorChannel != nil {\n\t\t\t\t\t\tb.ErrorChannel <- &ErrorBuffer{err, buf}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tb.sendWg.Done()\n\t\t\t}\n\t\t}()\n\t}\n}\n\n\/\/ start a timer for checking back and forcing flush ever BulkDelaySeconds seconds\n\/\/ even if we haven't hit max messages\/size\nfunc (b *BulkIndexer) startTimer() {\n\tticker := time.NewTicker(b.BufferDelayMax)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tb.mu.Lock()\n\t\t\t\t\/\/ don't send unless last sendor was the time,\n\t\t\t\t\/\/ otherwise an indication of other thresholds being hit\n\t\t\t\t\/\/ where time isn't needed\n\t\t\t\tif b.buf.Len() > 0 && b.needsTimeBasedFlush {\n\t\t\t\t\tb.needsTimeBasedFlush = true\n\t\t\t\t\tb.send(b.buf)\n\t\t\t\t} else if b.buf.Len() > 0 {\n\t\t\t\t\tb.needsTimeBasedFlush = true\n\t\t\t\t}\n\t\t\t\tb.mu.Unlock()\n\t\t\tcase <-b.timerDoneChan:\n\t\t\t\t\/\/ shutdown this go routine\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n}\n\nfunc (b *BulkIndexer) startDocChannel() {\n\t\/\/ This goroutine accepts incoming byte arrays from the IndexBulk function and\n\t\/\/ writes to buffer\n\tgo func() {\n\t\tfor docBytes := range b.bulkChannel {\n\t\t\tb.mu.Lock()\n\t\t\tb.docCt += 1\n\t\t\tb.buf.Write(docBytes)\n\t\t\tif b.buf.Len() >= b.BulkMaxBuffer || b.docCt >= b.BulkMaxDocs {\n\t\t\t\tb.needsTimeBasedFlush = false\n\t\t\t\t\/\/log.Printf(\"Send due to size:  docs=%d  bufsize=%d\", b.docCt, b.buf.Len())\n\t\t\t\tb.send(b.buf)\n\t\t\t}\n\t\t\tb.mu.Unlock()\n\t\t}\n\t}()\n}\n\nfunc (b *BulkIndexer) send(buf *bytes.Buffer) {\n\t\/\/b2 := *b.buf\n\tb.sendBuf <- buf\n\tb.buf = new(bytes.Buffer)\n\t\/\/\tb.buf.Reset()\n\tb.docCt = 0\n}\n\nfunc (b *BulkIndexer) shutdown() {\n\t\/\/ This must be called after Flush()\n\tclose(b.timerDoneChan)\n\tclose(b.sendBuf)\n\tclose(b.bulkChannel)\n\t<-wgChan(b.sendWg)\n}\n\n\/\/ The index bulk API adds or updates a typed JSON document to a specific index, making it searchable.\n\/\/ it operates by buffering requests, and ocassionally flushing to elasticsearch\n\/\/ http:\/\/www.elasticsearch.org\/guide\/reference\/api\/bulk.html\nfunc (b *BulkIndexer) Index(index string, _type string, id, ttl string, date *time.Time, data interface{}, refresh bool) error {\n\t\/\/{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n\tby, err := WriteBulkBytes(\"index\", index, _type, id, ttl, date, data, refresh)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.bulkChannel <- by\n\treturn nil\n}\n\nfunc (b *BulkIndexer) Update(index string, _type string, id, ttl string, date *time.Time, data interface{}, refresh bool) error {\n\t\/\/{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n\tby, err := WriteBulkBytes(\"update\", index, _type, id, ttl, date, data, refresh)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.bulkChannel <- by\n\treturn nil\n}\n\nfunc (b *BulkIndexer) Delete(index, _type, id string, refresh bool) {\n\tqueryLine := fmt.Sprintf(\"{\\\"delete\\\":{\\\"_index\\\":%q,\\\"_type\\\":%q,\\\"_id\\\":%q,\\\"refresh\\\":%t}}\\n\", index, _type, id, refresh)\n\tb.bulkChannel <- []byte(queryLine)\n\treturn\n}\n\nfunc (b *BulkIndexer) UpdateWithWithScript(index string, _type string, id, ttl string, date *time.Time, script string, refresh bool) error {\n\n\tvar data map[string]interface{} = make(map[string]interface{})\n\tdata[\"script\"] = script\n\treturn b.Update(index, _type, id, ttl, date, data, refresh)\n}\n\nfunc (b *BulkIndexer) UpdateWithPartialDoc(index string, _type string, id, ttl string, date *time.Time, partialDoc interface{}, upsert bool, refresh bool) error {\n\n\tvar data map[string]interface{} = make(map[string]interface{})\n\n\tdata[\"doc\"] = partialDoc\n\tif upsert {\n\t\tdata[\"doc_as_upsert\"] = true\n\t}\n\treturn b.Update(index, _type, id, ttl, date, data, refresh)\n}\n\n\/\/ This does the actual send of a buffer, which has already been formatted\n\/\/ into bytes of ES formatted bulk data\nfunc (b *BulkIndexer) Send(buf *bytes.Buffer) error {\n\ttype responseStruct struct {\n\t\tTook   int64                    `json:\"took\"`\n\t\tErrors bool                     `json:\"errors\"`\n\t\tItems  []map[string]interface{} `json:\"items\"`\n\t}\n\n\tresponse := responseStruct{}\n\n\tbody, err := b.conn.DoCommand(\"POST\", \"\/_bulk\", nil, buf)\n\n\tif err != nil {\n\t\tb.numErrors += 1\n\t\treturn err\n\t}\n\t\/\/ check for response errors, bulk insert will give 200 OK but then include errors in response\n\tjsonErr := json.Unmarshal(body, &response)\n\tif jsonErr == nil {\n\t\tif response.Errors {\n\t\t\tb.numErrors += uint64(len(response.Items))\n\t\t\treturn fmt.Errorf(\"Bulk Insertion Error. Failed item count [%d]\", len(response.Items))\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Given a set of arguments for index, type, id, data create a set of bytes that is formatted for bulkd index\n\/\/ http:\/\/www.elasticsearch.org\/guide\/reference\/api\/bulk.html\nfunc WriteBulkBytes(op string, index string, _type string, id, ttl string, date *time.Time, data interface{}, refresh bool) ([]byte, error) {\n\t\/\/ only index and update are currently supported\n\tif op != \"index\" && op != \"update\" {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Operation '%s' is not yet supported\", op))\n\t}\n\n\t\/\/ First line\n\tbuf := bytes.Buffer{}\n\tbuf.WriteString(fmt.Sprintf(`{\"%s\":{\"_index\":\"`, op))\n\tbuf.WriteString(index)\n\tbuf.WriteString(`\",\"_type\":\"`)\n\tbuf.WriteString(_type)\n\tbuf.WriteString(`\"`)\n\tif len(id) > 0 {\n\t\tbuf.WriteString(`,\"_id\":\"`)\n\t\tbuf.WriteString(id)\n\t\tbuf.WriteString(`\"`)\n\t}\n\n\tif op == \"update\" {\n\t\tbuf.WriteString(`,\"retry_on_conflict\":3`)\n\t}\n\n\tif len(ttl) > 0 {\n\t\tbuf.WriteString(`,\"ttl\":\"`)\n\t\tbuf.WriteString(ttl)\n\t\tbuf.WriteString(`\"`)\n\t}\n\tif date != nil {\n\t\tbuf.WriteString(`,\"_timestamp\":\"`)\n\t\tbuf.WriteString(strconv.FormatInt(date.UnixNano()\/1e6, 10))\n\t\tbuf.WriteString(`\"`)\n\t}\n\tif refresh {\n\t\tbuf.WriteString(`,\"refresh\":true`)\n\t}\n\tbuf.WriteString(`}}`)\n\tbuf.WriteRune('\\n')\n\t\/\/buf.WriteByte('\\n')\n\tswitch v := data.(type) {\n\tcase *bytes.Buffer:\n\t\tio.Copy(&buf, v)\n\tcase []byte:\n\t\tbuf.Write(v)\n\tcase string:\n\t\tbuf.WriteString(v)\n\tdefault:\n\t\tbody, jsonErr := json.Marshal(data)\n\t\tif jsonErr != nil {\n\t\t\treturn nil, jsonErr\n\t\t}\n\t\tbuf.Write(body)\n\t}\n\tbuf.WriteRune('\\n')\n\treturn buf.Bytes(), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Matthew Baird\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage elastigo\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ Max buffer size in bytes before flushing to elasticsearch\n\tBulkMaxBuffer = 16384\n\t\/\/ Max number of Docs to hold in buffer before forcing flush\n\tBulkMaxDocs = 100\n\t\/\/ Max delay before forcing a flush to Elasticearch\n\tBulkDelaySeconds = 5\n\t\/\/ maximum wait shutdown seconds\n\tMAX_SHUTDOWN_SECS = 5\n)\n\ntype ErrorBuffer struct {\n\tErr error\n\tBuf *bytes.Buffer\n}\n\n\/\/ A bulk indexer creates goroutines, and channels for connecting and sending data\n\/\/ to elasticsearch in bulk, using buffers.\ntype BulkIndexer struct {\n\tconn *Conn\n\n\t\/\/ We are creating a variable defining the func responsible for sending\n\t\/\/ to allow a mock sendor for test purposes\n\tSender func(*bytes.Buffer) error\n\n\t\/\/ If we encounter an error in sending, we are going to retry for this long\n\t\/\/ before returning an error\n\t\/\/ if 0 it will not retry\n\tRetryForSeconds int\n\n\t\/\/ channel for getting errors\n\tErrorChannel chan *ErrorBuffer\n\n\t\/\/ channel for sending to background indexer\n\tbulkChannel chan []byte\n\n\t\/\/ numErrors is a running total of errors seen\n\tnumErrors uint64\n\n\t\/\/ shutdown channel\n\tshutdownChan chan chan struct{}\n\t\/\/ Channel to shutdown http send go-routines\n\thttpDoneChan chan bool\n\t\/\/ channel to shutdown timer\n\ttimerDoneChan chan bool\n\t\/\/ channel to shutdown doc go-routines\n\tdocDoneChan chan bool\n\n\t\/\/ Channel to send a complete byte.Buffer to the http sendor\n\tsendBuf chan *bytes.Buffer\n\t\/\/ byte buffer for docs that have been converted to bytes, but not yet sent\n\tbuf *bytes.Buffer\n\t\/\/ Buffer for Max number of time before forcing flush\n\tBufferDelayMax time.Duration\n\t\/\/ Max buffer size in bytes before flushing to elasticsearch\n\tBulkMaxBuffer int \/\/ 1048576\n\t\/\/ Max number of Docs to hold in buffer before forcing flush\n\tBulkMaxDocs int \/\/ 100\n\n\t\/\/ Number of documents we have send through so far on this session\n\tdocCt int\n\t\/\/ Max number of http conns in flight at one time\n\tmaxConns int\n\t\/\/ If we are indexing enough docs per bufferdelaymax, we won't need to do time\n\t\/\/ based eviction, else we do.\n\tneedsTimeBasedFlush bool\n\t\/\/ Lock for document writes\/operations\n\tmu sync.Mutex\n\t\/\/ Wait Group for the http sends\n\tsendWg *sync.WaitGroup\n}\n\nfunc (b *BulkIndexer) NumErrors() uint64 {\n\treturn b.numErrors\n}\n\nfunc (c *Conn) NewBulkIndexer(maxConns int) *BulkIndexer {\n\tb := BulkIndexer{conn: c, sendBuf: make(chan *bytes.Buffer, maxConns)}\n\tb.needsTimeBasedFlush = true\n\tb.buf = new(bytes.Buffer)\n\tb.maxConns = maxConns\n\tb.BulkMaxBuffer = BulkMaxBuffer\n\tb.BulkMaxDocs = BulkMaxDocs\n\tb.BufferDelayMax = time.Duration(BulkDelaySeconds) * time.Second\n\tb.bulkChannel = make(chan []byte, 100)\n\tb.sendWg = new(sync.WaitGroup)\n\tb.docDoneChan = make(chan bool)\n\tb.timerDoneChan = make(chan bool)\n\tb.httpDoneChan = make(chan bool)\n\treturn &b\n}\n\n\/\/ A bulk indexer with more control over error handling\n\/\/    @maxConns is the max number of in flight http requests\n\/\/    @retrySeconds is # of seconds to wait before retrying falied requests\n\/\/\n\/\/   done := make(chan bool)\n\/\/   BulkIndexerGlobalRun(100, done)\nfunc (c *Conn) NewBulkIndexerErrors(maxConns, retrySeconds int) *BulkIndexer {\n\tb := c.NewBulkIndexer(maxConns)\n\tb.RetryForSeconds = retrySeconds\n\tb.ErrorChannel = make(chan *ErrorBuffer, 20)\n\treturn b\n}\n\n\/\/ Starts this bulk Indexer running, this Run opens a go routine so is\n\/\/ Non blocking\nfunc (b *BulkIndexer) Start() {\n\tb.shutdownChan = make(chan chan struct{})\n\n\tgo func() {\n\t\t\/\/ XXX(j): Refactor this stuff to use an interface.\n\t\tif b.Sender == nil {\n\t\t\tb.Sender = b.Send\n\t\t}\n\t\t\/\/ Backwards compatibility\n\t\tb.startHttpSender()\n\t\tb.startDocChannel()\n\t\tb.startTimer()\n\t\tch := <-b.shutdownChan\n\t\tb.Flush()\n\t\tb.shutdown()\n\t\tch <- struct{}{}\n\t\tclose(ch)\n\t}()\n}\n\n\/\/ Stop stops the bulk indexer, blocking the caller until it is complete.\nfunc (b *BulkIndexer) Stop() {\n\tch := make(chan struct{})\n\tb.shutdownChan <- ch\n\t<-ch\n\tclose(b.shutdownChan)\n}\n\n\/\/ Make a channel that will close when the given WaitGroup is done.\nfunc wgChan(wg *sync.WaitGroup) <-chan interface{} {\n\tch := make(chan interface{})\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(ch)\n\t}()\n\treturn ch\n}\n\nfunc (b *BulkIndexer) PendingDocuments() int {\n\treturn b.docCt\n}\n\n\/\/ Flush all current documents to ElasticSearch\nfunc (b *BulkIndexer) Flush() {\n\tb.mu.Lock()\n\tif b.docCt > 0 {\n\t\tb.send(b.buf)\n\t}\n\tb.mu.Unlock()\n\tfor {\n\t\tselect {\n\t\tcase <-wgChan(b.sendWg):\n\t\t\t\/\/ done\n\t\t\treturn\n\t\tcase <-time.After(time.Second * time.Duration(MAX_SHUTDOWN_SECS)):\n\t\t\t\/\/ timeout!\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (b *BulkIndexer) startHttpSender() {\n\n\t\/\/ this sends http requests to elasticsearch it uses maxConns to open up that\n\t\/\/ many goroutines, each of which will synchronously call ElasticSearch\n\t\/\/ in theory, the whole set will cause a backup all the way to IndexBulk if\n\t\/\/ we have consumed all maxConns\n\tfor i := 0; i < b.maxConns; i++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase buf := <-b.sendBuf:\n\t\t\t\t\tb.sendWg.Add(1)\n\t\t\t\t\t\/\/ Copy for the potential re-send.\n\t\t\t\t\tbufCopy := bytes.NewBuffer(buf.Bytes())\n\t\t\t\t\terr := b.Sender(buf)\n\n\t\t\t\t\t\/\/ Perhaps a b.FailureStrategy(err)  ??  with different types of strategies\n\t\t\t\t\t\/\/  1.  Retry, then panic\n\t\t\t\t\t\/\/  2.  Retry then return error and let runner decide\n\t\t\t\t\t\/\/  3.  Retry, then log to disk?   retry later?\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif b.RetryForSeconds > 0 {\n\t\t\t\t\t\t\ttime.Sleep(time.Second * time.Duration(b.RetryForSeconds))\n\t\t\t\t\t\t\terr = b.Sender(bufCopy)\n\t\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t\t\/\/ Successfully re-sent with no error\n\t\t\t\t\t\t\t\tb.sendWg.Done()\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif b.ErrorChannel != nil {\n\t\t\t\t\t\t\tb.ErrorChannel <- &ErrorBuffer{err, buf}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tb.sendWg.Done()\n\t\t\t\tcase <-b.httpDoneChan:\n\t\t\t\t\t\/\/ shutdown this go routine\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t}\n\t\t}()\n\t}\n}\n\n\/\/ start a timer for checking back and forcing flush ever BulkDelaySeconds seconds\n\/\/ even if we haven't hit max messages\/size\nfunc (b *BulkIndexer) startTimer() {\n\tticker := time.NewTicker(b.BufferDelayMax)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tb.mu.Lock()\n\t\t\t\t\/\/ don't send unless last sendor was the time,\n\t\t\t\t\/\/ otherwise an indication of other thresholds being hit\n\t\t\t\t\/\/ where time isn't needed\n\t\t\t\tif b.buf.Len() > 0 && b.needsTimeBasedFlush {\n\t\t\t\t\tb.needsTimeBasedFlush = true\n\t\t\t\t\tb.send(b.buf)\n\t\t\t\t} else if b.buf.Len() > 0 {\n\t\t\t\t\tb.needsTimeBasedFlush = true\n\t\t\t\t}\n\t\t\t\tb.mu.Unlock()\n\t\t\tcase <-b.timerDoneChan:\n\t\t\t\t\/\/ shutdown this go routine\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n}\n\nfunc (b *BulkIndexer) startDocChannel() {\n\t\/\/ This goroutine accepts incoming byte arrays from the IndexBulk function and\n\t\/\/ writes to buffer\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase docBytes := <-b.bulkChannel:\n\t\t\t\tb.mu.Lock()\n\t\t\t\tb.docCt += 1\n\t\t\t\tb.buf.Write(docBytes)\n\t\t\t\tif b.buf.Len() >= b.BulkMaxBuffer || b.docCt >= b.BulkMaxDocs {\n\t\t\t\t\tb.needsTimeBasedFlush = false\n\t\t\t\t\t\/\/log.Printf(\"Send due to size:  docs=%d  bufsize=%d\", b.docCt, b.buf.Len())\n\t\t\t\t\tb.send(b.buf)\n\t\t\t\t}\n\t\t\t\tb.mu.Unlock()\n\t\t\tcase <-b.docDoneChan:\n\t\t\t\t\/\/ shutdown this go routine\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (b *BulkIndexer) send(buf *bytes.Buffer) {\n\t\/\/b2 := *b.buf\n\tb.sendBuf <- buf\n\tb.buf = new(bytes.Buffer)\n\t\/\/\tb.buf.Reset()\n\tb.docCt = 0\n}\n\nfunc (b *BulkIndexer) shutdown() {\n\t\/\/ This must be called After flush\n\tb.docDoneChan <- true\n\tb.timerDoneChan <- true\n\tfor i := 0; i < b.maxConns; i++ {\n\t\tb.httpDoneChan <- true\n\t}\n}\n\n\/\/ The index bulk API adds or updates a typed JSON document to a specific index, making it searchable.\n\/\/ it operates by buffering requests, and ocassionally flushing to elasticsearch\n\/\/ http:\/\/www.elasticsearch.org\/guide\/reference\/api\/bulk.html\nfunc (b *BulkIndexer) Index(index string, _type string, id, ttl string, date *time.Time, data interface{}, refresh bool) error {\n\t\/\/{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n\tby, err := WriteBulkBytes(\"index\", index, _type, id, ttl, date, data, refresh)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.bulkChannel <- by\n\treturn nil\n}\n\nfunc (b *BulkIndexer) Update(index string, _type string, id, ttl string, date *time.Time, data interface{}, refresh bool) error {\n\t\/\/{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n\tby, err := WriteBulkBytes(\"update\", index, _type, id, ttl, date, data, refresh)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.bulkChannel <- by\n\treturn nil\n}\n\nfunc (b *BulkIndexer) Delete(index, _type, id string, refresh bool) {\n\tqueryLine := fmt.Sprintf(\"{\\\"delete\\\":{\\\"_index\\\":%q,\\\"_type\\\":%q,\\\"_id\\\":%q,\\\"refresh\\\":%t}}\\n\", index, _type, id, refresh)\n\tb.bulkChannel <- []byte(queryLine)\n\treturn\n}\n\nfunc (b *BulkIndexer) UpdateWithPartialDoc(index string, _type string, id, ttl string, date *time.Time, partialDoc interface{}, upsert bool, refresh bool) error {\n\n\tvar data map[string]interface{} = make(map[string]interface{})\n\n\tdata[\"doc\"] = partialDoc\n\tif upsert {\n\t\tdata[\"doc_as_upsert\"] = true\n\t}\n\treturn b.Update(index, _type, id, ttl, date, data, refresh)\n}\n\n\/\/ This does the actual send of a buffer, which has already been formatted\n\/\/ into bytes of ES formatted bulk data\nfunc (b *BulkIndexer) Send(buf *bytes.Buffer) error {\n\ttype responseStruct struct {\n\t\tTook   int64                    `json:\"took\"`\n\t\tErrors bool                     `json:\"errors\"`\n\t\tItems  []map[string]interface{} `json:\"items\"`\n\t}\n\n\tresponse := responseStruct{}\n\n\tbody, err := b.conn.DoCommand(\"POST\", \"\/_bulk\", nil, buf)\n\n\tif err != nil {\n\t\tb.numErrors += 1\n\t\treturn err\n\t}\n\t\/\/ check for response errors, bulk insert will give 200 OK but then include errors in response\n\tjsonErr := json.Unmarshal(body, &response)\n\tif jsonErr == nil {\n\t\tif response.Errors {\n\t\t\tb.numErrors += uint64(len(response.Items))\n\t\t\treturn fmt.Errorf(\"Bulk Insertion Error. Failed item count [%d]\", len(response.Items))\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Given a set of arguments for index, type, id, data create a set of bytes that is formatted for bulkd index\n\/\/ http:\/\/www.elasticsearch.org\/guide\/reference\/api\/bulk.html\nfunc WriteBulkBytes(op string, index string, _type string, id, ttl string, date *time.Time, data interface{}, refresh bool) ([]byte, error) {\n\t\/\/ only index and update are currently supported\n\tif op != \"index\" && op != \"update\" {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Operation '%s' is not yet supported\", op))\n\t}\n\n\t\/\/ First line\n\tbuf := bytes.Buffer{}\n\tbuf.WriteString(fmt.Sprintf(`{\"%s\":{\"_index\":\"`, op))\n\tbuf.WriteString(index)\n\tbuf.WriteString(`\",\"_type\":\"`)\n\tbuf.WriteString(_type)\n\tbuf.WriteString(`\"`)\n\tif len(id) > 0 {\n\t\tbuf.WriteString(`,\"_id\":\"`)\n\t\tbuf.WriteString(id)\n\t\tbuf.WriteString(`\"`)\n\t}\n\n\tif op == \"update\" {\n\t\tbuf.WriteString(`,\"retry_on_conflict\":3`)\n\t}\n\n\tif len(ttl) > 0 {\n\t\tbuf.WriteString(`,\"ttl\":\"`)\n\t\tbuf.WriteString(ttl)\n\t\tbuf.WriteString(`\"`)\n\t}\n\tif date != nil {\n\t\tbuf.WriteString(`,\"_timestamp\":\"`)\n\t\tbuf.WriteString(strconv.FormatInt(date.UnixNano()\/1e6, 10))\n\t\tbuf.WriteString(`\"`)\n\t}\n\tif refresh {\n\t\tbuf.WriteString(`,\"refresh\":true`)\n\t}\n\tbuf.WriteString(`}}`)\n\tbuf.WriteRune('\\n')\n\t\/\/buf.WriteByte('\\n')\n\tswitch v := data.(type) {\n\tcase *bytes.Buffer:\n\t\tio.Copy(&buf, v)\n\tcase []byte:\n\t\tbuf.Write(v)\n\tcase string:\n\t\tbuf.WriteString(v)\n\tdefault:\n\t\tbody, jsonErr := json.Marshal(data)\n\t\tif jsonErr != nil {\n\t\t\treturn nil, jsonErr\n\t\t}\n\t\tbuf.Write(body)\n\t}\n\tbuf.WriteRune('\\n')\n\treturn buf.Bytes(), nil\n}\n<commit_msg>adding helper for bulk update with script<commit_after>\/\/ Copyright 2013 Matthew Baird\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage elastigo\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ Max buffer size in bytes before flushing to elasticsearch\n\tBulkMaxBuffer = 16384\n\t\/\/ Max number of Docs to hold in buffer before forcing flush\n\tBulkMaxDocs = 100\n\t\/\/ Max delay before forcing a flush to Elasticearch\n\tBulkDelaySeconds = 5\n\t\/\/ maximum wait shutdown seconds\n\tMAX_SHUTDOWN_SECS = 5\n)\n\ntype ErrorBuffer struct {\n\tErr error\n\tBuf *bytes.Buffer\n}\n\n\/\/ A bulk indexer creates goroutines, and channels for connecting and sending data\n\/\/ to elasticsearch in bulk, using buffers.\ntype BulkIndexer struct {\n\tconn *Conn\n\n\t\/\/ We are creating a variable defining the func responsible for sending\n\t\/\/ to allow a mock sendor for test purposes\n\tSender func(*bytes.Buffer) error\n\n\t\/\/ If we encounter an error in sending, we are going to retry for this long\n\t\/\/ before returning an error\n\t\/\/ if 0 it will not retry\n\tRetryForSeconds int\n\n\t\/\/ channel for getting errors\n\tErrorChannel chan *ErrorBuffer\n\n\t\/\/ channel for sending to background indexer\n\tbulkChannel chan []byte\n\n\t\/\/ numErrors is a running total of errors seen\n\tnumErrors uint64\n\n\t\/\/ shutdown channel\n\tshutdownChan chan chan struct{}\n\t\/\/ Channel to shutdown http send go-routines\n\thttpDoneChan chan bool\n\t\/\/ channel to shutdown timer\n\ttimerDoneChan chan bool\n\t\/\/ channel to shutdown doc go-routines\n\tdocDoneChan chan bool\n\n\t\/\/ Channel to send a complete byte.Buffer to the http sendor\n\tsendBuf chan *bytes.Buffer\n\t\/\/ byte buffer for docs that have been converted to bytes, but not yet sent\n\tbuf *bytes.Buffer\n\t\/\/ Buffer for Max number of time before forcing flush\n\tBufferDelayMax time.Duration\n\t\/\/ Max buffer size in bytes before flushing to elasticsearch\n\tBulkMaxBuffer int \/\/ 1048576\n\t\/\/ Max number of Docs to hold in buffer before forcing flush\n\tBulkMaxDocs int \/\/ 100\n\n\t\/\/ Number of documents we have send through so far on this session\n\tdocCt int\n\t\/\/ Max number of http conns in flight at one time\n\tmaxConns int\n\t\/\/ If we are indexing enough docs per bufferdelaymax, we won't need to do time\n\t\/\/ based eviction, else we do.\n\tneedsTimeBasedFlush bool\n\t\/\/ Lock for document writes\/operations\n\tmu sync.Mutex\n\t\/\/ Wait Group for the http sends\n\tsendWg *sync.WaitGroup\n}\n\nfunc (b *BulkIndexer) NumErrors() uint64 {\n\treturn b.numErrors\n}\n\nfunc (c *Conn) NewBulkIndexer(maxConns int) *BulkIndexer {\n\tb := BulkIndexer{conn: c, sendBuf: make(chan *bytes.Buffer, maxConns)}\n\tb.needsTimeBasedFlush = true\n\tb.buf = new(bytes.Buffer)\n\tb.maxConns = maxConns\n\tb.BulkMaxBuffer = BulkMaxBuffer\n\tb.BulkMaxDocs = BulkMaxDocs\n\tb.BufferDelayMax = time.Duration(BulkDelaySeconds) * time.Second\n\tb.bulkChannel = make(chan []byte, 100)\n\tb.sendWg = new(sync.WaitGroup)\n\tb.docDoneChan = make(chan bool)\n\tb.timerDoneChan = make(chan bool)\n\tb.httpDoneChan = make(chan bool)\n\treturn &b\n}\n\n\/\/ A bulk indexer with more control over error handling\n\/\/    @maxConns is the max number of in flight http requests\n\/\/    @retrySeconds is # of seconds to wait before retrying falied requests\n\/\/\n\/\/   done := make(chan bool)\n\/\/   BulkIndexerGlobalRun(100, done)\nfunc (c *Conn) NewBulkIndexerErrors(maxConns, retrySeconds int) *BulkIndexer {\n\tb := c.NewBulkIndexer(maxConns)\n\tb.RetryForSeconds = retrySeconds\n\tb.ErrorChannel = make(chan *ErrorBuffer, 20)\n\treturn b\n}\n\n\/\/ Starts this bulk Indexer running, this Run opens a go routine so is\n\/\/ Non blocking\nfunc (b *BulkIndexer) Start() {\n\tb.shutdownChan = make(chan chan struct{})\n\n\tgo func() {\n\t\t\/\/ XXX(j): Refactor this stuff to use an interface.\n\t\tif b.Sender == nil {\n\t\t\tb.Sender = b.Send\n\t\t}\n\t\t\/\/ Backwards compatibility\n\t\tb.startHttpSender()\n\t\tb.startDocChannel()\n\t\tb.startTimer()\n\t\tch := <-b.shutdownChan\n\t\tb.Flush()\n\t\tb.shutdown()\n\t\tch <- struct{}{}\n\t\tclose(ch)\n\t}()\n}\n\n\/\/ Stop stops the bulk indexer, blocking the caller until it is complete.\nfunc (b *BulkIndexer) Stop() {\n\tch := make(chan struct{})\n\tb.shutdownChan <- ch\n\t<-ch\n\tclose(b.shutdownChan)\n}\n\n\/\/ Make a channel that will close when the given WaitGroup is done.\nfunc wgChan(wg *sync.WaitGroup) <-chan interface{} {\n\tch := make(chan interface{})\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(ch)\n\t}()\n\treturn ch\n}\n\nfunc (b *BulkIndexer) PendingDocuments() int {\n\treturn b.docCt\n}\n\n\/\/ Flush all current documents to ElasticSearch\nfunc (b *BulkIndexer) Flush() {\n\tb.mu.Lock()\n\tif b.docCt > 0 {\n\t\tb.send(b.buf)\n\t}\n\tb.mu.Unlock()\n\tfor {\n\t\tselect {\n\t\tcase <-wgChan(b.sendWg):\n\t\t\t\/\/ done\n\t\t\treturn\n\t\tcase <-time.After(time.Second * time.Duration(MAX_SHUTDOWN_SECS)):\n\t\t\t\/\/ timeout!\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (b *BulkIndexer) startHttpSender() {\n\n\t\/\/ this sends http requests to elasticsearch it uses maxConns to open up that\n\t\/\/ many goroutines, each of which will synchronously call ElasticSearch\n\t\/\/ in theory, the whole set will cause a backup all the way to IndexBulk if\n\t\/\/ we have consumed all maxConns\n\tfor i := 0; i < b.maxConns; i++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase buf := <-b.sendBuf:\n\t\t\t\t\tb.sendWg.Add(1)\n\t\t\t\t\t\/\/ Copy for the potential re-send.\n\t\t\t\t\tbufCopy := bytes.NewBuffer(buf.Bytes())\n\t\t\t\t\terr := b.Sender(buf)\n\n\t\t\t\t\t\/\/ Perhaps a b.FailureStrategy(err)  ??  with different types of strategies\n\t\t\t\t\t\/\/  1.  Retry, then panic\n\t\t\t\t\t\/\/  2.  Retry then return error and let runner decide\n\t\t\t\t\t\/\/  3.  Retry, then log to disk?   retry later?\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif b.RetryForSeconds > 0 {\n\t\t\t\t\t\t\ttime.Sleep(time.Second * time.Duration(b.RetryForSeconds))\n\t\t\t\t\t\t\terr = b.Sender(bufCopy)\n\t\t\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\t\t\/\/ Successfully re-sent with no error\n\t\t\t\t\t\t\t\tb.sendWg.Done()\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif b.ErrorChannel != nil {\n\t\t\t\t\t\t\tb.ErrorChannel <- &ErrorBuffer{err, buf}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tb.sendWg.Done()\n\t\t\t\tcase <-b.httpDoneChan:\n\t\t\t\t\t\/\/ shutdown this go routine\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t}\n\t\t}()\n\t}\n}\n\n\/\/ start a timer for checking back and forcing flush ever BulkDelaySeconds seconds\n\/\/ even if we haven't hit max messages\/size\nfunc (b *BulkIndexer) startTimer() {\n\tticker := time.NewTicker(b.BufferDelayMax)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tb.mu.Lock()\n\t\t\t\t\/\/ don't send unless last sendor was the time,\n\t\t\t\t\/\/ otherwise an indication of other thresholds being hit\n\t\t\t\t\/\/ where time isn't needed\n\t\t\t\tif b.buf.Len() > 0 && b.needsTimeBasedFlush {\n\t\t\t\t\tb.needsTimeBasedFlush = true\n\t\t\t\t\tb.send(b.buf)\n\t\t\t\t} else if b.buf.Len() > 0 {\n\t\t\t\t\tb.needsTimeBasedFlush = true\n\t\t\t\t}\n\t\t\t\tb.mu.Unlock()\n\t\t\tcase <-b.timerDoneChan:\n\t\t\t\t\/\/ shutdown this go routine\n\t\t\t\treturn\n\t\t\t}\n\n\t\t}\n\t}()\n}\n\nfunc (b *BulkIndexer) startDocChannel() {\n\t\/\/ This goroutine accepts incoming byte arrays from the IndexBulk function and\n\t\/\/ writes to buffer\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase docBytes := <-b.bulkChannel:\n\t\t\t\tb.mu.Lock()\n\t\t\t\tb.docCt += 1\n\t\t\t\tb.buf.Write(docBytes)\n\t\t\t\tif b.buf.Len() >= b.BulkMaxBuffer || b.docCt >= b.BulkMaxDocs {\n\t\t\t\t\tb.needsTimeBasedFlush = false\n\t\t\t\t\t\/\/log.Printf(\"Send due to size:  docs=%d  bufsize=%d\", b.docCt, b.buf.Len())\n\t\t\t\t\tb.send(b.buf)\n\t\t\t\t}\n\t\t\t\tb.mu.Unlock()\n\t\t\tcase <-b.docDoneChan:\n\t\t\t\t\/\/ shutdown this go routine\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (b *BulkIndexer) send(buf *bytes.Buffer) {\n\t\/\/b2 := *b.buf\n\tb.sendBuf <- buf\n\tb.buf = new(bytes.Buffer)\n\t\/\/\tb.buf.Reset()\n\tb.docCt = 0\n}\n\nfunc (b *BulkIndexer) shutdown() {\n\t\/\/ This must be called After flush\n\tb.docDoneChan <- true\n\tb.timerDoneChan <- true\n\tfor i := 0; i < b.maxConns; i++ {\n\t\tb.httpDoneChan <- true\n\t}\n}\n\n\/\/ The index bulk API adds or updates a typed JSON document to a specific index, making it searchable.\n\/\/ it operates by buffering requests, and ocassionally flushing to elasticsearch\n\/\/ http:\/\/www.elasticsearch.org\/guide\/reference\/api\/bulk.html\nfunc (b *BulkIndexer) Index(index string, _type string, id, ttl string, date *time.Time, data interface{}, refresh bool) error {\n\t\/\/{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n\tby, err := WriteBulkBytes(\"index\", index, _type, id, ttl, date, data, refresh)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.bulkChannel <- by\n\treturn nil\n}\n\nfunc (b *BulkIndexer) Update(index string, _type string, id, ttl string, date *time.Time, data interface{}, refresh bool) error {\n\t\/\/{ \"index\" : { \"_index\" : \"test\", \"_type\" : \"type1\", \"_id\" : \"1\" } }\n\tby, err := WriteBulkBytes(\"update\", index, _type, id, ttl, date, data, refresh)\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.bulkChannel <- by\n\treturn nil\n}\n\nfunc (b *BulkIndexer) Delete(index, _type, id string, refresh bool) {\n\tqueryLine := fmt.Sprintf(\"{\\\"delete\\\":{\\\"_index\\\":%q,\\\"_type\\\":%q,\\\"_id\\\":%q,\\\"refresh\\\":%t}}\\n\", index, _type, id, refresh)\n\tb.bulkChannel <- []byte(queryLine)\n\treturn\n}\n\nfunc (b *BulkIndexer) UpdateWithWithScript(index string, _type string, id, ttl string, date *time.Time, script string, refresh bool) error {\n\n\tvar data map[string]interface{} = make(map[string]interface{})\n\tdata[\"script\"] = script\n\treturn b.Update(index, _type, id, ttl, date, data, refresh)\n}\n\nfunc (b *BulkIndexer) UpdateWithPartialDoc(index string, _type string, id, ttl string, date *time.Time, partialDoc interface{}, upsert bool, refresh bool) error {\n\n\tvar data map[string]interface{} = make(map[string]interface{})\n\n\tdata[\"doc\"] = partialDoc\n\tif upsert {\n\t\tdata[\"doc_as_upsert\"] = true\n\t}\n\treturn b.Update(index, _type, id, ttl, date, data, refresh)\n}\n\n\/\/ This does the actual send of a buffer, which has already been formatted\n\/\/ into bytes of ES formatted bulk data\nfunc (b *BulkIndexer) Send(buf *bytes.Buffer) error {\n\ttype responseStruct struct {\n\t\tTook   int64                    `json:\"took\"`\n\t\tErrors bool                     `json:\"errors\"`\n\t\tItems  []map[string]interface{} `json:\"items\"`\n\t}\n\n\tresponse := responseStruct{}\n\n\tbody, err := b.conn.DoCommand(\"POST\", \"\/_bulk\", nil, buf)\n\n\tif err != nil {\n\t\tb.numErrors += 1\n\t\treturn err\n\t}\n\t\/\/ check for response errors, bulk insert will give 200 OK but then include errors in response\n\tjsonErr := json.Unmarshal(body, &response)\n\tif jsonErr == nil {\n\t\tif response.Errors {\n\t\t\tb.numErrors += uint64(len(response.Items))\n\t\t\treturn fmt.Errorf(\"Bulk Insertion Error. Failed item count [%d]\", len(response.Items))\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Given a set of arguments for index, type, id, data create a set of bytes that is formatted for bulkd index\n\/\/ http:\/\/www.elasticsearch.org\/guide\/reference\/api\/bulk.html\nfunc WriteBulkBytes(op string, index string, _type string, id, ttl string, date *time.Time, data interface{}, refresh bool) ([]byte, error) {\n\t\/\/ only index and update are currently supported\n\tif op != \"index\" && op != \"update\" {\n\t\treturn nil, errors.New(fmt.Sprintf(\"Operation '%s' is not yet supported\", op))\n\t}\n\n\t\/\/ First line\n\tbuf := bytes.Buffer{}\n\tbuf.WriteString(fmt.Sprintf(`{\"%s\":{\"_index\":\"`, op))\n\tbuf.WriteString(index)\n\tbuf.WriteString(`\",\"_type\":\"`)\n\tbuf.WriteString(_type)\n\tbuf.WriteString(`\"`)\n\tif len(id) > 0 {\n\t\tbuf.WriteString(`,\"_id\":\"`)\n\t\tbuf.WriteString(id)\n\t\tbuf.WriteString(`\"`)\n\t}\n\n\tif op == \"update\" {\n\t\tbuf.WriteString(`,\"retry_on_conflict\":3`)\n\t}\n\n\tif len(ttl) > 0 {\n\t\tbuf.WriteString(`,\"ttl\":\"`)\n\t\tbuf.WriteString(ttl)\n\t\tbuf.WriteString(`\"`)\n\t}\n\tif date != nil {\n\t\tbuf.WriteString(`,\"_timestamp\":\"`)\n\t\tbuf.WriteString(strconv.FormatInt(date.UnixNano()\/1e6, 10))\n\t\tbuf.WriteString(`\"`)\n\t}\n\tif refresh {\n\t\tbuf.WriteString(`,\"refresh\":true`)\n\t}\n\tbuf.WriteString(`}}`)\n\tbuf.WriteRune('\\n')\n\t\/\/buf.WriteByte('\\n')\n\tswitch v := data.(type) {\n\tcase *bytes.Buffer:\n\t\tio.Copy(&buf, v)\n\tcase []byte:\n\t\tbuf.Write(v)\n\tcase string:\n\t\tbuf.WriteString(v)\n\tdefault:\n\t\tbody, jsonErr := json.Marshal(data)\n\t\tif jsonErr != nil {\n\t\t\treturn nil, jsonErr\n\t\t}\n\t\tbuf.Write(body)\n\t}\n\tbuf.WriteRune('\\n')\n\treturn buf.Bytes(), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Keybase, Inc. All rights reserved. Use of\n\/\/ this source code is governed by the included BSD license.\n\npackage client\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/keybase\/cli\"\n\t\"github.com\/keybase\/client\/go\/libcmdline\"\n\t\"github.com\/keybase\/client\/go\/libkb\"\n\t\"github.com\/keybase\/go-framed-msgpack-rpc\/rpc\"\n)\n\n\/\/ CmdDeviceAdd is the 'device add' command.  It is used for\n\/\/ device provisioning on the provisioner\/device X\/C1.\ntype CmdDeviceAdd struct {\n\tlibkb.Contextified\n}\n\nconst cmdDevAddDesc = `When you are adding a new device to your account and you have an\nexisting device, you will be prompted to use this command on your\nexisting device to authorize the new device.`\n\n\/\/ NewCmdDeviceAdd creates a new cli.Command.\nfunc NewCmdDeviceAdd(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {\n\treturn cli.Command{\n\t\tName:        \"add\",\n\t\tUsage:       \"Authorize a new device\",\n\t\tDescription: cmdDevAddDesc,\n\t\tAction: func(c *cli.Context) {\n\t\t\tcl.ChooseCommand(&CmdDeviceAdd{Contextified: libkb.NewContextified(g)}, \"add\", c)\n\t\t},\n\t}\n}\n\n\/\/ RunClient runs the command in client\/server mode.\nfunc (c *CmdDeviceAdd) Run() error {\n\tdui := c.G().UI.GetDumbOutputUI()\n\tdui.Printf(\"Starting `device add`...\\n\\n\")\n\tdui.Printf(\"(Please note that you should run `device add` on a computer that is\\n\")\n\tdui.Printf(\"already registered with Keybase)\\n\")\n\n\tcli, err := GetDeviceClient(c.G())\n\tif err != nil {\n\t\treturn err\n\t}\n\tprotocols := []rpc.Protocol{\n\t\tNewProvisionUIProtocol(c.G(), libkb.KexRoleProvisioner),\n\t\tNewSecretUIProtocol(c.G()),\n\t}\n\tif err := RegisterProtocols(protocols); err != nil {\n\t\treturn err\n\t}\n\n\tif err := cli.DeviceAdd(context.TODO(), 0); err != nil {\n\t\tif lsErr, ok := err.(libkb.LoginStateTimeoutError); ok {\n\t\t\tc.G().Log.Debug(\"caught a LoginStateTimeoutError in `device add` command: %s\", lsErr)\n\t\t\tc.G().Log.Debug(\"providing hopefully helpful terminal output...\")\n\n\t\t\tdui.Printf(\"\\n\\nSorry, but it looks like there is another login or device provisioning\\n\")\n\t\t\tdui.Printf(\"task currently running.\\n\\n\")\n\t\t\tdui.Printf(\"We only run one at a time to ensure the device is provisioned correctly.\\n\\n\")\n\t\t\tdui.Printf(\"(Note that this often happens when you run `device add` on a new\\n\")\n\t\t\tdui.Printf(\"computer while it is being provisioned. You need to run it on an\\n\")\n\t\t\tdui.Printf(\"existing computer that is already reqistered with Keybase.)\\n\")\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ ParseArgv gets the secret phrase from the command args.\nfunc (c *CmdDeviceAdd) ParseArgv(ctx *cli.Context) error {\n\tif len(ctx.Args()) != 0 {\n\t\treturn fmt.Errorf(\"device add takes zero arguments\")\n\t}\n\treturn nil\n}\n\n\/\/ GetUsage says what this command needs to operate.\nfunc (c *CmdDeviceAdd) GetUsage() libkb.Usage {\n\treturn libkb.Usage{\n\t\tConfig:    true,\n\t\tKbKeyring: true,\n\t\tAPI:       true,\n\t}\n}\n<commit_msg>Fix typo<commit_after>\/\/ Copyright 2015 Keybase, Inc. All rights reserved. Use of\n\/\/ this source code is governed by the included BSD license.\n\npackage client\n\nimport (\n\t\"fmt\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/keybase\/cli\"\n\t\"github.com\/keybase\/client\/go\/libcmdline\"\n\t\"github.com\/keybase\/client\/go\/libkb\"\n\t\"github.com\/keybase\/go-framed-msgpack-rpc\/rpc\"\n)\n\n\/\/ CmdDeviceAdd is the 'device add' command.  It is used for\n\/\/ device provisioning on the provisioner\/device X\/C1.\ntype CmdDeviceAdd struct {\n\tlibkb.Contextified\n}\n\nconst cmdDevAddDesc = `When you are adding a new device to your account and you have an\nexisting device, you will be prompted to use this command on your\nexisting device to authorize the new device.`\n\n\/\/ NewCmdDeviceAdd creates a new cli.Command.\nfunc NewCmdDeviceAdd(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {\n\treturn cli.Command{\n\t\tName:        \"add\",\n\t\tUsage:       \"Authorize a new device\",\n\t\tDescription: cmdDevAddDesc,\n\t\tAction: func(c *cli.Context) {\n\t\t\tcl.ChooseCommand(&CmdDeviceAdd{Contextified: libkb.NewContextified(g)}, \"add\", c)\n\t\t},\n\t}\n}\n\n\/\/ RunClient runs the command in client\/server mode.\nfunc (c *CmdDeviceAdd) Run() error {\n\tdui := c.G().UI.GetDumbOutputUI()\n\tdui.Printf(\"Starting `device add`...\\n\\n\")\n\tdui.Printf(\"(Please note that you should run `device add` on a computer that is\\n\")\n\tdui.Printf(\"already registered with Keybase)\\n\")\n\n\tcli, err := GetDeviceClient(c.G())\n\tif err != nil {\n\t\treturn err\n\t}\n\tprotocols := []rpc.Protocol{\n\t\tNewProvisionUIProtocol(c.G(), libkb.KexRoleProvisioner),\n\t\tNewSecretUIProtocol(c.G()),\n\t}\n\tif err := RegisterProtocols(protocols); err != nil {\n\t\treturn err\n\t}\n\n\tif err := cli.DeviceAdd(context.TODO(), 0); err != nil {\n\t\tif lsErr, ok := err.(libkb.LoginStateTimeoutError); ok {\n\t\t\tc.G().Log.Debug(\"caught a LoginStateTimeoutError in `device add` command: %s\", lsErr)\n\t\t\tc.G().Log.Debug(\"providing hopefully helpful terminal output...\")\n\n\t\t\tdui.Printf(\"\\n\\nSorry, but it looks like there is another login or device provisioning\\n\")\n\t\t\tdui.Printf(\"task currently running.\\n\\n\")\n\t\t\tdui.Printf(\"We only run one at a time to ensure the device is provisioned correctly.\\n\\n\")\n\t\t\tdui.Printf(\"(Note that this often happens when you run `device add` on a new\\n\")\n\t\t\tdui.Printf(\"computer while it is being provisioned. You need to run it on an\\n\")\n\t\t\tdui.Printf(\"existing computer that is already registered with Keybase.)\\n\")\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ ParseArgv gets the secret phrase from the command args.\nfunc (c *CmdDeviceAdd) ParseArgv(ctx *cli.Context) error {\n\tif len(ctx.Args()) != 0 {\n\t\treturn fmt.Errorf(\"device add takes zero arguments\")\n\t}\n\treturn nil\n}\n\n\/\/ GetUsage says what this command needs to operate.\nfunc (c *CmdDeviceAdd) GetUsage() libkb.Usage {\n\treturn libkb.Usage{\n\t\tConfig:    true,\n\t\tKbKeyring: true,\n\t\tAPI:       true,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Keybase, Inc. All rights reserved. Use of\n\/\/ this source code is governed by the included BSD license.\n\npackage client\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/keybase\/cli\"\n\t\"github.com\/keybase\/client\/go\/libcmdline\"\n\t\"github.com\/keybase\/client\/go\/libkb\"\n\tkeybase1 \"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n\t\"github.com\/keybase\/go-framed-msgpack-rpc\/rpc\"\n)\n\nfunc NewCmdPGPExport(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {\n\treturn cli.Command{\n\t\tName:  \"export\",\n\t\tUsage: \"Export a PGP key from keybase\",\n\t\tAction: func(c *cli.Context) {\n\t\t\tcl.ChooseCommand(&CmdPGPExport{Contextified: libkb.NewContextified(g)}, \"export\", c)\n\t\t},\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"o, outfile\",\n\t\t\t\tUsage: \"Specify an outfile (stdout by default).\",\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"s, secret\",\n\t\t\t\tUsage: \"Export secret key.\",\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"q, query\",\n\t\t\t\tUsage: \"Only export keys matching that query.\",\n\t\t\t},\n\t\t},\n\t\tDescription: `\"keybase pgp export\" exports public (and optionally private) PGP keys\n   from Keybase, and into a file or to standard output. It doesn't access\n   the GnuPG keychain at all.`,\n\t}\n}\n\ntype CmdPGPExport struct {\n\tUnixFilter\n\targ     keybase1.PGPExportArg\n\toutfile string\n\tlibkb.Contextified\n}\n\nfunc (s *CmdPGPExport) ParseArgv(ctx *cli.Context) error {\n\tnargs := len(ctx.Args())\n\tvar err error\n\n\ts.arg.Options.Secret = ctx.Bool(\"secret\")\n\ts.arg.Options.Query = ctx.String(\"query\")\n\ts.outfile = ctx.String(\"outfile\")\n\n\tif nargs > 0 {\n\t\terr = fmt.Errorf(\"export doesn't take args\")\n\t}\n\n\treturn err\n}\n\nfunc (s *CmdPGPExport) Run() (err error) {\n\tprotocols := []rpc.Protocol{\n\t\tNewSecretUIProtocol(s.G()),\n\t}\n\n\tcli, err := GetPGPClient(s.G())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = RegisterProtocolsWithContext(protocols, s.G()); err != nil {\n\t\treturn err\n\t}\n\treturn s.finish(cli.PGPExport(context.TODO(), s.arg))\n}\n\nfunc (s *CmdPGPExport) finish(res []keybase1.KeyInfo, inErr error) error {\n\tif inErr != nil {\n\t\treturn inErr\n\t}\n\tif len(res) > 1 {\n\t\ts.G().Log.Warning(\"Found several matches:\")\n\t\tfor _, k := range res {\n\t\t\t\/\/ XXX os.Stderr?  why not Log?\n\t\t\tos.Stderr.Write([]byte(k.Desc + \"\\n\\n\"))\n\t\t}\n\t\treturn fmt.Errorf(\"Specify a key to export\")\n\t}\n\tif len(res) == 0 {\n\t\treturn fmt.Errorf(\"No matching keys found\")\n\t}\n\n\tsnk := initSink(s.outfile)\n\tif err := snk.Open(); err != nil {\n\t\treturn err\n\t}\n\tsnk.Write([]byte(res[0].Key))\n\treturn snk.Close()\n}\n\nfunc (s *CmdPGPExport) GetUsage() libkb.Usage {\n\treturn libkb.Usage{\n\t\tConfig:    true,\n\t\tAPI:       true,\n\t\tKbKeyring: true,\n\t}\n}\n<commit_msg>Ensure newline in 'pgp export'<commit_after>\/\/ Copyright 2015 Keybase, Inc. All rights reserved. Use of\n\/\/ this source code is governed by the included BSD license.\n\npackage client\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/keybase\/cli\"\n\t\"github.com\/keybase\/client\/go\/libcmdline\"\n\t\"github.com\/keybase\/client\/go\/libkb\"\n\tkeybase1 \"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n\t\"github.com\/keybase\/go-framed-msgpack-rpc\/rpc\"\n)\n\nfunc NewCmdPGPExport(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {\n\treturn cli.Command{\n\t\tName:  \"export\",\n\t\tUsage: \"Export a PGP key from keybase\",\n\t\tAction: func(c *cli.Context) {\n\t\t\tcl.ChooseCommand(&CmdPGPExport{Contextified: libkb.NewContextified(g)}, \"export\", c)\n\t\t},\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"o, outfile\",\n\t\t\t\tUsage: \"Specify an outfile (stdout by default).\",\n\t\t\t},\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"s, secret\",\n\t\t\t\tUsage: \"Export secret key.\",\n\t\t\t},\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"q, query\",\n\t\t\t\tUsage: \"Only export keys matching that query.\",\n\t\t\t},\n\t\t},\n\t\tDescription: `\"keybase pgp export\" exports public (and optionally private) PGP keys\n   from Keybase, and into a file or to standard output. It doesn't access\n   the GnuPG keychain at all.`,\n\t}\n}\n\ntype CmdPGPExport struct {\n\tUnixFilter\n\targ     keybase1.PGPExportArg\n\toutfile string\n\tlibkb.Contextified\n}\n\nfunc (s *CmdPGPExport) ParseArgv(ctx *cli.Context) error {\n\tnargs := len(ctx.Args())\n\tvar err error\n\n\ts.arg.Options.Secret = ctx.Bool(\"secret\")\n\ts.arg.Options.Query = ctx.String(\"query\")\n\ts.outfile = ctx.String(\"outfile\")\n\n\tif nargs > 0 {\n\t\terr = fmt.Errorf(\"export doesn't take args\")\n\t}\n\n\treturn err\n}\n\nfunc (s *CmdPGPExport) Run() (err error) {\n\tprotocols := []rpc.Protocol{\n\t\tNewSecretUIProtocol(s.G()),\n\t}\n\n\tcli, err := GetPGPClient(s.G())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = RegisterProtocolsWithContext(protocols, s.G()); err != nil {\n\t\treturn err\n\t}\n\treturn s.finish(cli.PGPExport(context.TODO(), s.arg))\n}\n\nfunc (s *CmdPGPExport) finish(res []keybase1.KeyInfo, inErr error) error {\n\tif inErr != nil {\n\t\treturn inErr\n\t}\n\tif len(res) > 1 {\n\t\ts.G().Log.Warning(\"Found several matches:\")\n\t\tfor _, k := range res {\n\t\t\t\/\/ XXX os.Stderr?  why not Log?\n\t\t\tos.Stderr.Write([]byte(k.Desc + \"\\n\\n\"))\n\t\t}\n\t\treturn fmt.Errorf(\"Specify a key to export\")\n\t}\n\tif len(res) == 0 {\n\t\treturn fmt.Errorf(\"No matching keys found\")\n\t}\n\n\tsnk := initSink(s.outfile)\n\tif err := snk.Open(); err != nil {\n\t\treturn err\n\t}\n\tsnk.Write([]byte(strings.TrimSpace(res[0].Key) + \"\\n\"))\n\treturn snk.Close()\n}\n\nfunc (s *CmdPGPExport) GetUsage() libkb.Usage {\n\treturn libkb.Usage{\n\t\tConfig:    true,\n\t\tAPI:       true,\n\t\tKbKeyring: true,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package chat1\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\/\/ Eq compares two TLFIDs\nfunc (id TLFID) Eq(other TLFID) bool {\n\treturn bytes.Equal([]byte(id), []byte(other))\n}\n\n\/\/ EqString is like EqualsTo, except that it accepts a fmt.Stringer. This\n\/\/ can be useful for comparing keybase1.TLFID and chat1.TLFID.\nfunc (id TLFID) EqString(other fmt.Stringer) bool {\n\treturn hex.EncodeToString(id) == other.String()\n}\n\nfunc (id TLFID) String() string {\n\treturn hex.EncodeToString(id)\n}\n\nfunc MakeConvID(val string) (ConversationID, error) {\n\treturn hex.DecodeString(val)\n}\n\nfunc (cid ConversationID) Bytes() []byte {\n\treturn []byte(cid)\n}\n\nfunc (cid ConversationID) String() string {\n\treturn hex.EncodeToString(cid)\n}\n\nfunc (cid ConversationID) IsNil() bool {\n\treturn len(cid) == 0\n}\n\nfunc (cid ConversationID) Eq(c ConversationID) bool {\n\treturn bytes.Equal(cid, c)\n}\n\nfunc (cid ConversationID) Less(c ConversationID) bool {\n\treturn bytes.Compare(cid, c) < 0\n}\n\nfunc MakeTLFID(val string) (TLFID, error) {\n\treturn hex.DecodeString(val)\n}\n\nfunc MakeTopicID(val string) (TopicID, error) {\n\treturn hex.DecodeString(val)\n}\n\nfunc MakeTopicType(val int64) TopicType {\n\treturn TopicType(val)\n}\n\nfunc (mid MessageID) String() string {\n\treturn strconv.FormatUint(uint64(mid), 10)\n}\n\nfunc (t MessageType) String() string {\n\tswitch t {\n\tcase MessageType_NONE:\n\t\treturn \"NONE\"\n\tcase MessageType_TEXT:\n\t\treturn \"TEXT\"\n\tcase MessageType_ATTACHMENT:\n\t\treturn \"ATTACHMENT\"\n\tcase MessageType_EDIT:\n\t\treturn \"EDIT\"\n\tcase MessageType_DELETE:\n\t\treturn \"DELETE\"\n\tcase MessageType_METADATA:\n\t\treturn \"METADATA\"\n\tdefault:\n\t\treturn \"UNKNOWN\"\n\t}\n}\n\nfunc (t TopicType) String() string {\n\tswitch t {\n\tcase TopicType_NONE:\n\t\treturn \"NONE\"\n\tcase TopicType_CHAT:\n\t\treturn \"CHAT\"\n\tcase TopicType_DEV:\n\t\treturn \"DEV\"\n\tdefault:\n\t\treturn \"UNKNOWN\"\n\t}\n}\n\nfunc (t TopicID) String() string {\n\treturn hex.EncodeToString(t)\n}\n\nfunc (me ConversationIDTriple) Eq(other ConversationIDTriple) bool {\n\treturn me.Tlfid.Eq(other.Tlfid) &&\n\t\tbytes.Equal([]byte(me.TopicID), []byte(other.TopicID)) &&\n\t\tme.TopicType == other.TopicType\n}\n\nfunc (hash Hash) String() string {\n\treturn hex.EncodeToString(hash)\n}\n\nfunc (hash Hash) Eq(other Hash) bool {\n\treturn bytes.Equal(hash, other)\n}\n\nfunc (m MessageUnboxed) GetMessageID() MessageID {\n\tif state, err := m.State(); err == nil {\n\t\tif state == MessageUnboxedState_VALID {\n\t\t\treturn m.Valid().ServerHeader.MessageID\n\t\t}\n\t\tif state == MessageUnboxedState_ERROR {\n\t\t\treturn m.Error().MessageID\n\t\t}\n\t}\n\treturn 0\n}\n\nfunc (m MessageUnboxed) GetMessageType() MessageType {\n\tif state, err := m.State(); err == nil {\n\t\tif state == MessageUnboxedState_VALID {\n\t\t\treturn m.Valid().ClientHeader.MessageType\n\t\t}\n\t\tif state == MessageUnboxedState_ERROR {\n\t\t\treturn m.Error().MessageType\n\t\t}\n\t}\n\treturn MessageType_NONE\n}\n\nfunc (m MessageUnboxed) IsValid() bool {\n\tif state, err := m.State(); err == nil {\n\t\treturn state == MessageUnboxedState_VALID\n\t}\n\treturn false\n}\n\nfunc (m MessageBoxed) GetMessageID() MessageID {\n\treturn m.ServerHeader.MessageID\n}\n\nfunc (m MessageBoxed) GetMessageType() MessageType {\n\treturn m.ClientHeader.MessageType\n}\n\nvar ConversationStatusGregorMap = map[ConversationStatus]string{\n\tConversationStatus_UNFILED:  \"unfiled\",\n\tConversationStatus_FAVORITE: \"favorite\",\n\tConversationStatus_IGNORED:  \"ignored\",\n\tConversationStatus_BLOCKED:  \"blocked\",\n}\n\nvar ConversationStatusGregorRevMap = map[string]ConversationStatus{\n\t\"unfiled\":  ConversationStatus_UNFILED,\n\t\"favorite\": ConversationStatus_FAVORITE,\n\t\"ignored\":  ConversationStatus_IGNORED,\n\t\"blocked\":  ConversationStatus_BLOCKED,\n}\n\nfunc (t ConversationIDTriple) Hash10B() []byte {\n\th := sha256.New()\n\th.Write(t.Tlfid)\n\th.Write(t.TopicID)\n\th.Write([]byte(strconv.Itoa(int(t.TopicType))))\n\thash := h.Sum(nil)\n\n\treturn hash[:10]\n}\n\nfunc (t ConversationIDTriple) ToConversationID(shardID [2]byte) ConversationID {\n\th := t.Hash10B()\n\th[0], h[1] = shardID[0], shardID[1]\n\treturn ConversationID(h)\n}\n\nfunc (t ConversationIDTriple) Derivable(cid ConversationID) bool {\n\tif len(cid) != 10 {\n\t\treturn false\n\t}\n\th10 := t.Hash10B()\n\treturn bytes.Equal(h10[2:], []byte(cid[2:]))\n}\n\nfunc (o OutboxID) Eq(r OutboxID) bool {\n\treturn bytes.Equal(o, r)\n}\n<commit_msg>use full hash for conv ID CORE-4111 (#4918)<commit_after>package chat1\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\/\/ Eq compares two TLFIDs\nfunc (id TLFID) Eq(other TLFID) bool {\n\treturn bytes.Equal([]byte(id), []byte(other))\n}\n\n\/\/ EqString is like EqualsTo, except that it accepts a fmt.Stringer. This\n\/\/ can be useful for comparing keybase1.TLFID and chat1.TLFID.\nfunc (id TLFID) EqString(other fmt.Stringer) bool {\n\treturn hex.EncodeToString(id) == other.String()\n}\n\nfunc (id TLFID) String() string {\n\treturn hex.EncodeToString(id)\n}\n\nfunc MakeConvID(val string) (ConversationID, error) {\n\treturn hex.DecodeString(val)\n}\n\nfunc (cid ConversationID) String() string {\n\treturn hex.EncodeToString(cid)\n}\n\nfunc (cid ConversationID) IsNil() bool {\n\treturn len(cid) == 0\n}\n\nfunc (cid ConversationID) Eq(c ConversationID) bool {\n\treturn bytes.Equal(cid, c)\n}\n\nfunc (cid ConversationID) Less(c ConversationID) bool {\n\treturn bytes.Compare(cid, c) < 0\n}\n\n\/\/ DbShortForm should only be used when interacting with the database, and should\n\/\/ never leave Gregor\nfunc (cid ConversationID) DbShortForm() []byte {\n\treturn cid[:10]\n}\n\nfunc MakeTLFID(val string) (TLFID, error) {\n\treturn hex.DecodeString(val)\n}\n\nfunc MakeTopicID(val string) (TopicID, error) {\n\treturn hex.DecodeString(val)\n}\n\nfunc MakeTopicType(val int64) TopicType {\n\treturn TopicType(val)\n}\n\nfunc (mid MessageID) String() string {\n\treturn strconv.FormatUint(uint64(mid), 10)\n}\n\nfunc (t MessageType) String() string {\n\tswitch t {\n\tcase MessageType_NONE:\n\t\treturn \"NONE\"\n\tcase MessageType_TEXT:\n\t\treturn \"TEXT\"\n\tcase MessageType_ATTACHMENT:\n\t\treturn \"ATTACHMENT\"\n\tcase MessageType_EDIT:\n\t\treturn \"EDIT\"\n\tcase MessageType_DELETE:\n\t\treturn \"DELETE\"\n\tcase MessageType_METADATA:\n\t\treturn \"METADATA\"\n\tdefault:\n\t\treturn \"UNKNOWN\"\n\t}\n}\n\nfunc (t TopicType) String() string {\n\tswitch t {\n\tcase TopicType_NONE:\n\t\treturn \"NONE\"\n\tcase TopicType_CHAT:\n\t\treturn \"CHAT\"\n\tcase TopicType_DEV:\n\t\treturn \"DEV\"\n\tdefault:\n\t\treturn \"UNKNOWN\"\n\t}\n}\n\nfunc (t TopicID) String() string {\n\treturn hex.EncodeToString(t)\n}\n\nfunc (me ConversationIDTriple) Eq(other ConversationIDTriple) bool {\n\treturn me.Tlfid.Eq(other.Tlfid) &&\n\t\tbytes.Equal([]byte(me.TopicID), []byte(other.TopicID)) &&\n\t\tme.TopicType == other.TopicType\n}\n\nfunc (hash Hash) String() string {\n\treturn hex.EncodeToString(hash)\n}\n\nfunc (hash Hash) Eq(other Hash) bool {\n\treturn bytes.Equal(hash, other)\n}\n\nfunc (m MessageUnboxed) GetMessageID() MessageID {\n\tif state, err := m.State(); err == nil {\n\t\tif state == MessageUnboxedState_VALID {\n\t\t\treturn m.Valid().ServerHeader.MessageID\n\t\t}\n\t\tif state == MessageUnboxedState_ERROR {\n\t\t\treturn m.Error().MessageID\n\t\t}\n\t}\n\treturn 0\n}\n\nfunc (m MessageUnboxed) GetMessageType() MessageType {\n\tif state, err := m.State(); err == nil {\n\t\tif state == MessageUnboxedState_VALID {\n\t\t\treturn m.Valid().ClientHeader.MessageType\n\t\t}\n\t\tif state == MessageUnboxedState_ERROR {\n\t\t\treturn m.Error().MessageType\n\t\t}\n\t}\n\treturn MessageType_NONE\n}\n\nfunc (m MessageUnboxed) IsValid() bool {\n\tif state, err := m.State(); err == nil {\n\t\treturn state == MessageUnboxedState_VALID\n\t}\n\treturn false\n}\n\nfunc (m MessageBoxed) GetMessageID() MessageID {\n\treturn m.ServerHeader.MessageID\n}\n\nfunc (m MessageBoxed) GetMessageType() MessageType {\n\treturn m.ClientHeader.MessageType\n}\n\nvar ConversationStatusGregorMap = map[ConversationStatus]string{\n\tConversationStatus_UNFILED:  \"unfiled\",\n\tConversationStatus_FAVORITE: \"favorite\",\n\tConversationStatus_IGNORED:  \"ignored\",\n\tConversationStatus_BLOCKED:  \"blocked\",\n}\n\nvar ConversationStatusGregorRevMap = map[string]ConversationStatus{\n\t\"unfiled\":  ConversationStatus_UNFILED,\n\t\"favorite\": ConversationStatus_FAVORITE,\n\t\"ignored\":  ConversationStatus_IGNORED,\n\t\"blocked\":  ConversationStatus_BLOCKED,\n}\n\nfunc (t ConversationIDTriple) Hash() []byte {\n\th := sha256.New()\n\th.Write(t.Tlfid)\n\th.Write(t.TopicID)\n\th.Write([]byte(strconv.Itoa(int(t.TopicType))))\n\thash := h.Sum(nil)\n\n\treturn hash\n}\n\nfunc (t ConversationIDTriple) ToConversationID(shardID [2]byte) ConversationID {\n\th := t.Hash()\n\th[0], h[1] = shardID[0], shardID[1]\n\treturn ConversationID(h)\n}\n\nfunc (t ConversationIDTriple) Derivable(cid ConversationID) bool {\n\th := t.Hash()\n\treturn bytes.Equal(h[2:], []byte(cid[2:]))\n}\n\nfunc (o OutboxID) Eq(r OutboxID) bool {\n\treturn bytes.Equal(o, r)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\/\/ \"os\"\n\t\"summa\"\n)\n\nvar configFile string\n\nfunc init() {\n\tflag.StringVar(&configFile, \"f\", \"server.conf\", \"The server configuration file\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\terr := summa.Init(configFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not initialize Summa: %s\", err)\n\t}\n\n\tsumma.SetAuthProvider(auth)\n\tsumma.StartHttp()\n}\n\nfunc auth(username, password string) (*summa.User, error) {\n\tvar u summa.User\n\n\tu.Username = \"anonymous\"\n\tu.DisplayName = \"Anonymous\"\n\tu.Email = \"anon@anonymous.com\"\n\n\treturn &u, nil\n}\n<commit_msg>Remove commented code in summa-server\/main.go<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"summa\"\n)\n\nvar configFile string\n\nfunc init() {\n\tflag.StringVar(&configFile, \"f\", \"server.conf\", \"The server configuration file\")\n}\n\nfunc main() {\n\tflag.Parse()\n\n\terr := summa.Init(configFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not initialize Summa: %s\", err)\n\t}\n\n\tsumma.SetAuthProvider(auth)\n\tsumma.StartHttp()\n}\n\nfunc auth(username, password string) (*summa.User, error) {\n\tvar u summa.User\n\n\tu.Username = \"anonymous\"\n\tu.DisplayName = \"Anonymous\"\n\tu.Email = \"anon@anonymous.com\"\n\n\treturn &u, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package google\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n\tsqladmin \"google.golang.org\/api\/sqladmin\/v1beta4\"\n)\n\nfunc resourceSqlUser() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceSqlUserCreate,\n\t\tRead:   resourceSqlUserRead,\n\t\tUpdate: resourceSqlUserUpdate,\n\t\tDelete: resourceSqlUserDelete,\n\t\tImporter: &schema.ResourceImporter{\n\t\t\tState: resourceSqlUserImporter,\n\t\t},\n\n\t\tSchemaVersion: 1,\n\t\tMigrateState:  resourceSqlUserMigrateState,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"host\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"instance\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"password\": {\n\t\t\t\tType:      schema.TypeString,\n\t\t\t\tOptional:  true,\n\t\t\t\tSensitive: true,\n\t\t\t},\n\n\t\t\t\"project\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceSqlUserCreate(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tproject, err := getProject(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tname := d.Get(\"name\").(string)\n\tinstance := d.Get(\"instance\").(string)\n\tpassword := d.Get(\"password\").(string)\n\thost := d.Get(\"host\").(string)\n\n\tuser := &sqladmin.User{\n\t\tName:     name,\n\t\tInstance: instance,\n\t\tPassword: password,\n\t\tHost:     host,\n\t}\n\n\tmutexKV.Lock(instanceMutexKey(project, instance))\n\tdefer mutexKV.Unlock(instanceMutexKey(project, instance))\n\top, err := config.clientSqlAdmin.Users.Insert(project, instance,\n\t\tuser).Do()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error, failed to insert \"+\n\t\t\t\"user %s into instance %s: %s\", name, instance, err)\n\t}\n\n\t\/\/ This will include a double-slash (\/\/) for postgres instances,\n\t\/\/ for which user.Host is an empty string.  That's okay.\n\td.SetId(fmt.Sprintf(\"%s\/%s\/%s\", user.Name, user.Host, user.Instance))\n\n\terr = sqlAdminOperationWait(config, op, project, \"Insert User\")\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error, failure waiting for insertion of %s \"+\n\t\t\t\"into %s: %s\", name, instance, err)\n\t}\n\n\treturn resourceSqlUserRead(d, meta)\n}\n\nfunc resourceSqlUserRead(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tproject, err := getProject(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinstance := d.Get(\"instance\").(string)\n\tname := d.Get(\"name\").(string)\n\thost := d.Get(\"host\").(string)\n\n\tvar users *sqladmin.UsersListResponse\n\terr = nil\n\terr = retryTime(func() error {\n\t\tusers, err = config.clientSqlAdmin.Users.List(project, instance).Do()\n\t\treturn err\n\t}, 5)\n\tif err != nil {\n\t\treturn handleNotFoundError(err, d, fmt.Sprintf(\"SQL User %q in instance %q\", name, instance))\n\t}\n\n\tvar user *sqladmin.User\n\tfor _, currentUser := range users.Items {\n\t\tif currentUser.Name == name {\n\t\t\t\/\/ Host can only be empty for postgres instances,\n\t\t\t\/\/ so don't compare the host if the API host is empty.\n\t\t\tif currentUser.Host == \"\" || currentUser.Host == host {\n\t\t\t\tuser = currentUser\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif user == nil {\n\t\tlog.Printf(\"[WARN] Removing SQL User %q because it's gone\", d.Get(\"name\").(string))\n\t\td.SetId(\"\")\n\n\t\treturn nil\n\t}\n\n\td.Set(\"host\", user.Host)\n\td.Set(\"instance\", user.Instance)\n\td.Set(\"name\", user.Name)\n\td.Set(\"project\", project)\n\td.SetId(fmt.Sprintf(\"%s\/%s\/%s\", user.Name, user.Host, user.Instance))\n\treturn nil\n}\n\nfunc resourceSqlUserUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tif d.HasChange(\"password\") {\n\t\tproject, err := getProject(d, config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tname := d.Get(\"name\").(string)\n\t\tinstance := d.Get(\"instance\").(string)\n\t\tpassword := d.Get(\"password\").(string)\n\t\thost := d.Get(\"host\").(string)\n\n\t\tuser := &sqladmin.User{\n\t\t\tName:     name,\n\t\t\tInstance: instance,\n\t\t\tPassword: password,\n\t\t}\n\n\t\tmutexKV.Lock(instanceMutexKey(project, instance))\n\t\tdefer mutexKV.Unlock(instanceMutexKey(project, instance))\n\t\top, err := config.clientSqlAdmin.Users.Update(project, instance, name,\n\t\t\tuser).Host(host).Do()\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error, failed to update\"+\n\t\t\t\t\"user %s into user %s: %s\", name, instance, err)\n\t\t}\n\n\t\terr = sqlAdminOperationWait(config, op, project, \"Insert User\")\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error, failure waiting for update of %s \"+\n\t\t\t\t\"in %s: %s\", name, instance, err)\n\t\t}\n\n\t\treturn resourceSqlUserRead(d, meta)\n\t}\n\n\treturn nil\n}\n\nfunc resourceSqlUserDelete(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tproject, err := getProject(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tname := d.Get(\"name\").(string)\n\tinstance := d.Get(\"instance\").(string)\n\thost := d.Get(\"host\").(string)\n\n\tmutexKV.Lock(instanceMutexKey(project, instance))\n\tdefer mutexKV.Unlock(instanceMutexKey(project, instance))\n\n\tvar op *sqladmin.Operation\n\terr = retryTimeDuration(func() error {\n\t\top, err = config.clientSqlAdmin.Users.Delete(project, instance, host, name).Do()\n\t\treturn err\n\t}, d.Timeout(schema.TimeoutDelete))\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error, failed to delete\"+\n\t\t\t\"user %s in instance %s: %s\", name,\n\t\t\tinstance, err)\n\t}\n\n\terr = sqlAdminOperationWait(config, op, project, \"Delete User\")\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error, failure waiting for deletion of %s \"+\n\t\t\t\"in %s: %s\", name, instance, err)\n\t}\n\n\treturn nil\n}\n\nfunc resourceSqlUserImporter(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {\n\tparts := strings.Split(d.Id(), \"\/\")\n\n\tif len(parts) == 3 {\n\t\td.Set(\"project\", parts[0])\n\t\td.Set(\"instance\", parts[1])\n\t\td.Set(\"name\", parts[2])\n\t} else if len(parts) == 4 {\n\t\td.Set(\"project\", parts[0])\n\t\td.Set(\"instance\", parts[1])\n\t\td.Set(\"host\", parts[2])\n\t\td.Set(\"name\", parts[3])\n\t} else {\n\t\treturn nil, fmt.Errorf(\"Invalid specifier. Expecting {project}\/{instance}\/{name} for postgres instance and {project}\/{instance}\/{host}\/{name} for MySQL instance\")\n\t}\n\n\treturn []*schema.ResourceData{d}, nil\n}\n<commit_msg>Add retries to SQL user insert and update operations. (#4860)<commit_after>package google\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n\tsqladmin \"google.golang.org\/api\/sqladmin\/v1beta4\"\n)\n\nfunc resourceSqlUser() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceSqlUserCreate,\n\t\tRead:   resourceSqlUserRead,\n\t\tUpdate: resourceSqlUserUpdate,\n\t\tDelete: resourceSqlUserDelete,\n\t\tImporter: &schema.ResourceImporter{\n\t\t\tState: resourceSqlUserImporter,\n\t\t},\n\n\t\tSchemaVersion: 1,\n\t\tMigrateState:  resourceSqlUserMigrateState,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"host\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"instance\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"name\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\n\t\t\t\"password\": {\n\t\t\t\tType:      schema.TypeString,\n\t\t\t\tOptional:  true,\n\t\t\t\tSensitive: true,\n\t\t\t},\n\n\t\t\t\"project\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceSqlUserCreate(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tproject, err := getProject(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tname := d.Get(\"name\").(string)\n\tinstance := d.Get(\"instance\").(string)\n\tpassword := d.Get(\"password\").(string)\n\thost := d.Get(\"host\").(string)\n\n\tuser := &sqladmin.User{\n\t\tName:     name,\n\t\tInstance: instance,\n\t\tPassword: password,\n\t\tHost:     host,\n\t}\n\n\tmutexKV.Lock(instanceMutexKey(project, instance))\n\tdefer mutexKV.Unlock(instanceMutexKey(project, instance))\n\tvar op *sqladmin.Operation\n\tinsertFunc := func() error {\n\t\top, err = config.clientSqlAdmin.Users.Insert(project, instance,\n\t\t\tuser).Do()\n\t\treturn err\n\t}\n\terr = retryTimeDuration(insertFunc, d.Timeout(schema.TimeoutCreate))\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error, failed to insert \"+\n\t\t\t\"user %s into instance %s: %s\", name, instance, err)\n\t}\n\n\t\/\/ This will include a double-slash (\/\/) for postgres instances,\n\t\/\/ for which user.Host is an empty string.  That's okay.\n\td.SetId(fmt.Sprintf(\"%s\/%s\/%s\", user.Name, user.Host, user.Instance))\n\n\terr = sqlAdminOperationWait(config, op, project, \"Insert User\")\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error, failure waiting for insertion of %s \"+\n\t\t\t\"into %s: %s\", name, instance, err)\n\t}\n\n\treturn resourceSqlUserRead(d, meta)\n}\n\nfunc resourceSqlUserRead(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tproject, err := getProject(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tinstance := d.Get(\"instance\").(string)\n\tname := d.Get(\"name\").(string)\n\thost := d.Get(\"host\").(string)\n\n\tvar users *sqladmin.UsersListResponse\n\terr = nil\n\terr = retryTime(func() error {\n\t\tusers, err = config.clientSqlAdmin.Users.List(project, instance).Do()\n\t\treturn err\n\t}, 5)\n\tif err != nil {\n\t\treturn handleNotFoundError(err, d, fmt.Sprintf(\"SQL User %q in instance %q\", name, instance))\n\t}\n\n\tvar user *sqladmin.User\n\tfor _, currentUser := range users.Items {\n\t\tif currentUser.Name == name {\n\t\t\t\/\/ Host can only be empty for postgres instances,\n\t\t\t\/\/ so don't compare the host if the API host is empty.\n\t\t\tif currentUser.Host == \"\" || currentUser.Host == host {\n\t\t\t\tuser = currentUser\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif user == nil {\n\t\tlog.Printf(\"[WARN] Removing SQL User %q because it's gone\", d.Get(\"name\").(string))\n\t\td.SetId(\"\")\n\n\t\treturn nil\n\t}\n\n\td.Set(\"host\", user.Host)\n\td.Set(\"instance\", user.Instance)\n\td.Set(\"name\", user.Name)\n\td.Set(\"project\", project)\n\td.SetId(fmt.Sprintf(\"%s\/%s\/%s\", user.Name, user.Host, user.Instance))\n\treturn nil\n}\n\nfunc resourceSqlUserUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tif d.HasChange(\"password\") {\n\t\tproject, err := getProject(d, config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tname := d.Get(\"name\").(string)\n\t\tinstance := d.Get(\"instance\").(string)\n\t\tpassword := d.Get(\"password\").(string)\n\t\thost := d.Get(\"host\").(string)\n\n\t\tuser := &sqladmin.User{\n\t\t\tName:     name,\n\t\t\tInstance: instance,\n\t\t\tPassword: password,\n\t\t}\n\n\t\tmutexKV.Lock(instanceMutexKey(project, instance))\n\t\tdefer mutexKV.Unlock(instanceMutexKey(project, instance))\n\t\tvar op *sqladmin.Operation\n\t\tretryFunc := func() error {\n\t\t\top, err = config.clientSqlAdmin.Users.Update(project, instance, name,\n\t\t\t\tuser).Host(host).Do()\n\t\t\treturn err\n\t\t}\n\t\terr = retryTimeDuration(retryFunc, d.Timeout(schema.TimeoutUpdate))\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error, failed to update\"+\n\t\t\t\t\"user %s into user %s: %s\", name, instance, err)\n\t\t}\n\n\t\terr = sqlAdminOperationWait(config, op, project, \"Insert User\")\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error, failure waiting for update of %s \"+\n\t\t\t\t\"in %s: %s\", name, instance, err)\n\t\t}\n\n\t\treturn resourceSqlUserRead(d, meta)\n\t}\n\n\treturn nil\n}\n\nfunc resourceSqlUserDelete(d *schema.ResourceData, meta interface{}) error {\n\tconfig := meta.(*Config)\n\n\tproject, err := getProject(d, config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tname := d.Get(\"name\").(string)\n\tinstance := d.Get(\"instance\").(string)\n\thost := d.Get(\"host\").(string)\n\n\tmutexKV.Lock(instanceMutexKey(project, instance))\n\tdefer mutexKV.Unlock(instanceMutexKey(project, instance))\n\n\tvar op *sqladmin.Operation\n\terr = retryTimeDuration(func() error {\n\t\top, err = config.clientSqlAdmin.Users.Delete(project, instance, host, name).Do()\n\t\treturn err\n\t}, d.Timeout(schema.TimeoutDelete))\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error, failed to delete\"+\n\t\t\t\"user %s in instance %s: %s\", name,\n\t\t\tinstance, err)\n\t}\n\n\terr = sqlAdminOperationWait(config, op, project, \"Delete User\")\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error, failure waiting for deletion of %s \"+\n\t\t\t\"in %s: %s\", name, instance, err)\n\t}\n\n\treturn nil\n}\n\nfunc resourceSqlUserImporter(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {\n\tparts := strings.Split(d.Id(), \"\/\")\n\n\tif len(parts) == 3 {\n\t\td.Set(\"project\", parts[0])\n\t\td.Set(\"instance\", parts[1])\n\t\td.Set(\"name\", parts[2])\n\t} else if len(parts) == 4 {\n\t\td.Set(\"project\", parts[0])\n\t\td.Set(\"instance\", parts[1])\n\t\td.Set(\"host\", parts[2])\n\t\td.Set(\"name\", parts[3])\n\t} else {\n\t\treturn nil, fmt.Errorf(\"Invalid specifier. Expecting {project}\/{instance}\/{name} for postgres instance and {project}\/{instance}\/{host}\/{name} for MySQL instance\")\n\t}\n\n\treturn []*schema.ResourceData{d}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package db\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t_ \"github.com\/lib\/pq\"\n\t\"github.com\/orc\/utils\"\n\t\"os\"\n\t\/\/\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc HandleErr(message string, err error) {\n\tif err != nil {\n\t\tfmt.Printf(message+\"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nconst user string = \"admin\"\nconst dbname string = \"orc\"\nconst password string = \"admin\"\n\nvar DB, _ = sql.Open(\n\t\"postgres\",\n\t\"host=localhost\"+\n\t\t\" user=\"+user+\n\t\t\" dbname=\"+dbname+\n\t\t\" password=\"+password+\n\t\t\" sslmode=disable\")\n\nvar Tables = []string{\n\t\"events\",\n\t\"event_types\",\n\t\"events_types\",\n\t\"teams\",\n\t\"persons\",\n\t\"persons_events\",\n\t\"users\",\n\t\"teams_persons\",\n\t\"forms\",\n\t\"params\",\n\t\"forms_types\",\n\t\"param_values\",\n}\n\nvar TableNames = []string{\n\t\"Мероприятия\",\n\t\"Типы мероприятий\",\n\t\"Мероприятия-Типы\",\n\t\"Команды\",\n\t\"Персоны\",\n\t\"Персоны-Мероприятия\",\n\t\"Пользователи\",\n\t\"Команды-Персоны\",\n\t\"Формы\",\n\t\"Параметры\",\n\t\"Формы-Типы мероприятий\",\n\t\"Значения параметров\",\n}\n\nfunc Exec(query string, params []interface{}) sql.Result {\n\tfmt.Println(query)\n\n\tstmt, err := DB.Prepare(query)\n\tutils.HandleErr(\"[db.Exec] Prepare: \", err, nil)\n\n\tresult, err := stmt.Exec(params...)\n\tutils.HandleErr(\"[db.Exec] Exec: \", err, nil)\n\treturn result\n}\n\nfunc Query(query string, params []interface{}) *sql.Rows {\n\tfmt.Println(query)\n\n\tstmt, err := DB.Prepare(query)\n\tutils.HandleErr(\"[db.Query] Prepare: \", err, nil)\n\n\tresult, err := stmt.Query(params...)\n\tutils.HandleErr(\"[db.Query] Query: \", err, nil)\n\treturn result\n}\n\nfunc QueryRow(query string, params []interface{}) *sql.Row {\n\tfmt.Println(query)\n\n\tstmt, err := DB.Prepare(query)\n\tutils.HandleErr(\"[db.QueryRow] Prepare: \", err, nil)\n\n\tresult := stmt.QueryRow(params...)\n\tutils.HandleErr(\"[db.QueryRow] Query: \", err, nil)\n\treturn result\n}\n\nfunc QuerySelect(tableName, where string, fields []string) string {\n\tquery := \"SELECT %s FROM %s\"\n\tf := strings.Join(fields, \", \")\n\tif where != \"\" {\n\t\tquery += \" WHERE %s;\"\n\t\treturn fmt.Sprintf(query, f, tableName, where)\n\t} else {\n\t\treturn fmt.Sprintf(query, f, tableName)\n\t}\n}\n\nfunc QueryInsert(tableName string, fields []string) string {\n\tquery := \"INSERT INTO %s (%s) VALUES (%s);\"\n\tf := strings.Join(fields, \", \")\n\tp := strings.Join(MakeParams(len(fields)), \", \")\n\treturn fmt.Sprintf(query, tableName, f, p)\n}\n\nfunc QueryUpdate(tableName, where string, fields []string) string {\n\tquery := \"UPDATE %s SET %s WHERE %s;\"\n\tp := strings.Join(MakePairs(fields), \", \")\n\treturn fmt.Sprintf(query, tableName, p, where)\n}\n\nfunc QueryDelete(tableName, fieldName string, countParams int) string {\n\tquery := \"DELETE FROM %s WHERE %s IN (%s)\"\n\tparams := strings.Join(MakeParams(countParams), \", \")\n\treturn fmt.Sprintf(query, tableName, fieldName, params)\n}\n\nfunc IsExists(tableName, fieldName string, value string) bool {\n\tvar result string\n\tquery := QuerySelect(tableName, fieldName+\"=$1\", []string{fieldName})\n\trow := QueryRow(query, []interface{}{value})\n\terr := row.Scan(&result)\n\treturn err != sql.ErrNoRows\n}\n\nfunc MakeParams(n int) []string {\n\tvar result = make([]string, n)\n\tfor i := 0; i < n; i++ {\n\t\tresult[i] = \"$\" + strconv.Itoa(i+1)\n\t}\n\treturn result\n}\n\nfunc MakePairs(fields []string) []string {\n\tvar result = make([]string, len(fields))\n\tfor i := 0; i < len(fields); i++ {\n\t\tresult[i] = fields[i] + \"=$\" + strconv.Itoa(i+1)\n\t}\n\treturn result\n}\n\nfunc Select(tableName string, where []string, condition string, fields []string) []interface{} {\n\tvar key []string\n\tvar val []interface{}\n\tvar i, j = 0, 1\n\tif len(where) != 0 {\n\t\tfor i = 0; i < len(where)-1; i += 2 {\n\t\t\tkey = append(key, where[i]+\"=$\"+strconv.Itoa(j))\n\t\t\tval = append(val, where[i+1])\n\t\t\tj++\n\t\t}\n\t}\n\tquery := QuerySelect(tableName, strings.Join(key, \" \"+condition+\" \"), fields)\n\trows := Query(query, val)\n\trowsInf := Exec(query, val)\n\n\tcolumns, _ := rows.Columns()\n\trow := make([]interface{}, len(columns))\n\tvalues := make([]interface{}, len(columns))\n\tfor i, _ := range row {\n\t\trow[i] = &values[i]\n\t}\n\n\tl, err := rowsInf.RowsAffected()\n\tutils.HandleErr(\"[Entity.Select] RowsAffected: \", err, nil)\n\treturn ConvertData(columns, l, rows)\n}\n\nfunc ConvertData(columns []string, l int64, rows *sql.Rows) []interface{} {\n\tj := 0\n\trow := make([]interface{}, len(columns))\n\tvalues := make([]interface{}, len(columns))\n\tfor i, _ := range row {\n\t\trow[i] = &values[i]\n\t}\n\n\tanswer := make([]interface{}, l)\n\n\tfor rows.Next() {\n\t\trows.Scan(row...)\n\t\tanswer[j] = make(map[string]interface{}, len(values))\n\t\trecord := make(map[string]interface{}, len(values))\n\t\tfor i, col := range values {\n\t\t\tif col != nil {\n\t\t\t\t\/\/fmt.Printf(\"\\n%s: type= %s\\n\", columns[i], reflect.TypeOf(col))\n\t\t\t\tswitch col.(type) {\n\t\t\t\tdefault:\n\t\t\t\t\tutils.HandleErr(\"Entity.Select: Unexpected type.\", nil, nil)\n\t\t\t\tcase bool:\n\t\t\t\t\trecord[columns[i]] = col.(bool)\n\t\t\t\tcase int:\n\t\t\t\t\trecord[columns[i]] = col.(int)\n\t\t\t\tcase int64:\n\t\t\t\t\trecord[columns[i]] = col.(int64)\n\t\t\t\tcase float64:\n\t\t\t\t\trecord[columns[i]] = col.(float64)\n\t\t\t\tcase string:\n\t\t\t\t\trecord[columns[i]] = col.(string)\n\t\t\t\tcase []byte:\n\t\t\t\t\trecord[columns[i]] = string(col.([]byte))\n\t\t\t\tcase []int8:\n\t\t\t\t\trecord[columns[i]] = col.([]string)\n\t\t\t\tcase time.Time:\n\t\t\t\t\trecord[columns[i]] = col\n\t\t\t\t}\n\t\t\t}\n\t\t\tanswer[j] = record\n\t\t}\n\t\tj++\n\t}\n\treturn answer\n}\n\nfunc InnerJoin(\n\tselectFields []string,\n\tselectRef string,\n\n\tfromTable string,\n\tfromTableRef string,\n\tfromField []string,\n\n\tjoinTables []string,\n\tjoinRef []string,\n\tjoinField []string,\n\n\twhere string) string {\n\n\tquery := \"SELECT \"\n\tfor i := 0; i < len(selectFields); i++ {\n\t\tquery += selectRef + \".\" + selectFields[i] + \", \"\n\t}\n\tquery = query[0 : len(query)-2]\n\tquery += \" FROM \" + fromTable + \" \" + fromTableRef\n\tfor i := 0; i < len(joinTables); i++ {\n\t\tquery += \" INNER JOIN \" + joinTables[i] + \" \" + joinRef[i]\n\t\tquery += \" ON \" + joinRef[i] + \".\" + joinField[i] + \" = \" + fromTableRef + \".\" + fromField[i]\n\t}\n\tquery += \" \" + where\n\treturn query\n}\n<commit_msg>Remove unused function HandleErr<commit_after>package db\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t_ \"github.com\/lib\/pq\"\n\t\"github.com\/orc\/utils\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst user string = \"admin\"\nconst dbname string = \"orc\"\nconst password string = \"admin\"\n\nvar DB, _ = sql.Open(\n\t\"postgres\",\n\t\"host=localhost\"+\n\t\t\" user=\"+user+\n\t\t\" dbname=\"+dbname+\n\t\t\" password=\"+password+\n\t\t\" sslmode=disable\")\n\nvar Tables = []string{\n\t\"events\",\n\t\"event_types\",\n\t\"events_types\",\n\t\"teams\",\n\t\"persons\",\n\t\"persons_events\",\n\t\"users\",\n\t\"teams_persons\",\n\t\"forms\",\n\t\"params\",\n\t\"forms_types\",\n\t\"param_values\",\n}\n\nvar TableNames = []string{\n\t\"Мероприятия\",\n\t\"Типы мероприятий\",\n\t\"Мероприятия-Типы\",\n\t\"Команды\",\n\t\"Персоны\",\n\t\"Персоны-Мероприятия\",\n\t\"Пользователи\",\n\t\"Команды-Персоны\",\n\t\"Формы\",\n\t\"Параметры\",\n\t\"Формы-Типы мероприятий\",\n\t\"Значения параметров\",\n}\n\nfunc Exec(query string, params []interface{}) sql.Result {\n\tfmt.Println(query)\n\n\tstmt, err := DB.Prepare(query)\n\tutils.HandleErr(\"[db.Exec] Prepare: \", err, nil)\n\n\tresult, err := stmt.Exec(params...)\n\tutils.HandleErr(\"[db.Exec] Exec: \", err, nil)\n\treturn result\n}\n\nfunc Query(query string, params []interface{}) *sql.Rows {\n\tfmt.Println(query)\n\n\tstmt, err := DB.Prepare(query)\n\tutils.HandleErr(\"[db.Query] Prepare: \", err, nil)\n\n\tresult, err := stmt.Query(params...)\n\tutils.HandleErr(\"[db.Query] Query: \", err, nil)\n\treturn result\n}\n\nfunc QueryRow(query string, params []interface{}) *sql.Row {\n\tfmt.Println(query)\n\n\tstmt, err := DB.Prepare(query)\n\tutils.HandleErr(\"[db.QueryRow] Prepare: \", err, nil)\n\n\tresult := stmt.QueryRow(params...)\n\tutils.HandleErr(\"[db.QueryRow] Query: \", err, nil)\n\treturn result\n}\n\nfunc QuerySelect(tableName, where string, fields []string) string {\n\tquery := \"SELECT %s FROM %s\"\n\tf := strings.Join(fields, \", \")\n\tif where != \"\" {\n\t\tquery += \" WHERE %s;\"\n\t\treturn fmt.Sprintf(query, f, tableName, where)\n\t} else {\n\t\treturn fmt.Sprintf(query, f, tableName)\n\t}\n}\n\nfunc QueryInsert(tableName string, fields []string) string {\n\tquery := \"INSERT INTO %s (%s) VALUES (%s);\"\n\tf := strings.Join(fields, \", \")\n\tp := strings.Join(MakeParams(len(fields)), \", \")\n\treturn fmt.Sprintf(query, tableName, f, p)\n}\n\nfunc QueryUpdate(tableName, where string, fields []string) string {\n\tquery := \"UPDATE %s SET %s WHERE %s;\"\n\tp := strings.Join(MakePairs(fields), \", \")\n\treturn fmt.Sprintf(query, tableName, p, where)\n}\n\nfunc QueryDelete(tableName, fieldName string, countParams int) string {\n\tquery := \"DELETE FROM %s WHERE %s IN (%s)\"\n\tparams := strings.Join(MakeParams(countParams), \", \")\n\treturn fmt.Sprintf(query, tableName, fieldName, params)\n}\n\nfunc IsExists(tableName, fieldName string, value string) bool {\n\tvar result string\n\tquery := QuerySelect(tableName, fieldName+\"=$1\", []string{fieldName})\n\trow := QueryRow(query, []interface{}{value})\n\terr := row.Scan(&result)\n\treturn err != sql.ErrNoRows\n}\n\nfunc MakeParams(n int) []string {\n\tvar result = make([]string, n)\n\tfor i := 0; i < n; i++ {\n\t\tresult[i] = \"$\" + strconv.Itoa(i+1)\n\t}\n\treturn result\n}\n\nfunc MakePairs(fields []string) []string {\n\tvar result = make([]string, len(fields))\n\tfor i := 0; i < len(fields); i++ {\n\t\tresult[i] = fields[i] + \"=$\" + strconv.Itoa(i+1)\n\t}\n\treturn result\n}\n\nfunc Select(tableName string, where []string, condition string, fields []string) []interface{} {\n\tvar key []string\n\tvar val []interface{}\n\tvar i, j = 0, 1\n\tif len(where) != 0 {\n\t\tfor i = 0; i < len(where)-1; i += 2 {\n\t\t\tkey = append(key, where[i]+\"=$\"+strconv.Itoa(j))\n\t\t\tval = append(val, where[i+1])\n\t\t\tj++\n\t\t}\n\t}\n\tquery := QuerySelect(tableName, strings.Join(key, \" \"+condition+\" \"), fields)\n\trows := Query(query, val)\n\trowsInf := Exec(query, val)\n\n\tcolumns, _ := rows.Columns()\n\trow := make([]interface{}, len(columns))\n\tvalues := make([]interface{}, len(columns))\n\tfor i, _ := range row {\n\t\trow[i] = &values[i]\n\t}\n\n\tl, err := rowsInf.RowsAffected()\n\tutils.HandleErr(\"[Entity.Select] RowsAffected: \", err, nil)\n\treturn ConvertData(columns, l, rows)\n}\n\nfunc ConvertData(columns []string, l int64, rows *sql.Rows) []interface{} {\n\tj := 0\n\trow := make([]interface{}, len(columns))\n\tvalues := make([]interface{}, len(columns))\n\tfor i, _ := range row {\n\t\trow[i] = &values[i]\n\t}\n\n\tanswer := make([]interface{}, l)\n\n\tfor rows.Next() {\n\t\trows.Scan(row...)\n\t\tanswer[j] = make(map[string]interface{}, len(values))\n\t\trecord := make(map[string]interface{}, len(values))\n\t\tfor i, col := range values {\n\t\t\tif col != nil {\n\t\t\t\t\/\/fmt.Printf(\"\\n%s: type= %s\\n\", columns[i], reflect.TypeOf(col))\n\t\t\t\tswitch col.(type) {\n\t\t\t\tdefault:\n\t\t\t\t\tutils.HandleErr(\"Entity.Select: Unexpected type.\", nil, nil)\n\t\t\t\tcase bool:\n\t\t\t\t\trecord[columns[i]] = col.(bool)\n\t\t\t\tcase int:\n\t\t\t\t\trecord[columns[i]] = col.(int)\n\t\t\t\tcase int64:\n\t\t\t\t\trecord[columns[i]] = col.(int64)\n\t\t\t\tcase float64:\n\t\t\t\t\trecord[columns[i]] = col.(float64)\n\t\t\t\tcase string:\n\t\t\t\t\trecord[columns[i]] = col.(string)\n\t\t\t\tcase []byte:\n\t\t\t\t\trecord[columns[i]] = string(col.([]byte))\n\t\t\t\tcase []int8:\n\t\t\t\t\trecord[columns[i]] = col.([]string)\n\t\t\t\tcase time.Time:\n\t\t\t\t\trecord[columns[i]] = col\n\t\t\t\t}\n\t\t\t}\n\t\t\tanswer[j] = record\n\t\t}\n\t\tj++\n\t}\n\treturn answer\n}\n\nfunc InnerJoin(\n\tselectFields []string,\n\tselectRef string,\n\n\tfromTable string,\n\tfromTableRef string,\n\tfromField []string,\n\n\tjoinTables []string,\n\tjoinRef []string,\n\tjoinField []string,\n\n\twhere string) string {\n\n\tquery := \"SELECT \"\n\tfor i := 0; i < len(selectFields); i++ {\n\t\tquery += selectRef + \".\" + selectFields[i] + \", \"\n\t}\n\tquery = query[0 : len(query)-2]\n\tquery += \" FROM \" + fromTable + \" \" + fromTableRef\n\tfor i := 0; i < len(joinTables); i++ {\n\t\tquery += \" INNER JOIN \" + joinTables[i] + \" \" + joinRef[i]\n\t\tquery += \" ON \" + joinRef[i] + \".\" + joinField[i] + \" = \" + fromTableRef + \".\" + fromField[i]\n\t}\n\tquery += \" \" + where\n\treturn query\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\/pprof\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar ModDebugCore = PISCModule{\n\tAuthor:    \"Andrew Owen\",\n\tName:      \"IOCore\",\n\tLicense:   \"MIT\",\n\tDocString: \"The debug words used in PISC\",\n\tLoad:      loadDebugCore,\n}\n\nfunc loadDebugCore(m *machine) error {\n\t\/\/ ( -- )\n\tm.predefinedWords[\"show-prefix-words\"] = NilWord(func(m *machine) {\n\t\tfor name := range m.prefixWords {\n\t\t\tfmt.Println(name)\n\t\t}\n\t})\n\t\/\/ ( quot -- .. time )\n\tm.addGoWord(\"time\", \"( quot -- .. time )\", GoWord(func(m *machine) error {\n\t\twords := &codeQuotation{\n\t\t\tidx:   0,\n\t\t\twords: []*word{&word{str: \"call\"}},\n\t\t}\n\t\tstart := time.Now()\n\t\terr := m.execute(words)\n\t\telapsed := time.Since(start)\n\t\tm.pushValue(String(fmt.Sprint(\"Code took \", elapsed)))\n\t\treturn err\n\t}))\n\n\tm.addGoWord(\"print-debug-trace\", \"( -- )\", func(m *machine) error {\n\t\tfmt.Println(m.debugTrace)\n\t\treturn nil\n\t})\n\n\tm.addGoWord(\"clear-debug-trace\", \"( -- )\", func(m *machine) error {\n\t\tm.debugTrace = \"\"\n\t\treturn nil\n\t})\n\n\t\/\/ ( filepath quotation -- )\n\tm.predefinedWords[\"cpu-pprof\"] = GoWord(func(m *machine) error {\n\t\tm.executeString(\"swap\", codePosition{source: \"cpu-pprof GoWord\"})\n\t\tpath := m.popValue().String()\n\t\tf, err := os.Create(path)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Unable to create profiling file\")\n\t\t\treturn err\n\t\t}\n\t\tif err := pprof.StartCPUProfile(f); err != nil {\n\t\t\tlog.Fatal(\"Unable to start CPU profile\")\n\t\t\treturn err\n\t\t}\n\t\tm.executeQuotation()\n\t\tpprof.StopCPUProfile()\n\t\treturn nil\n\t})\n\n\t\/\/ ( -- )\n\tm.predefinedWords[\"dump-defined-words\"] = GoWord(func(m *machine) error {\n\t\t\/\/ var words = make(Array, 0)\n\t\tfor name, seq := range m.prefixWords {\n\t\t\tfmt.Println(\":PRE\", name, m.definedStackComments[name], DumpToString(seq), \";\")\n\t\t}\n\t\tfor name, seq := range m.definedWords {\n\t\t\tfmt.Println(\":DOC\", name, m.definedStackComments[name], m.helpDocs[name], \";\")\n\t\t\tfmt.Println(\":\", name, m.definedStackComments[name], DumpToString(seq), \";\")\n\t\t}\n\t\treturn nil\n\t})\n\treturn m.importPISCAsset(\"stdlib\/debug.pisc\")\n}\n\n\/\/ TODO: See about this...\nfunc DumpToString(c codeSequence) string {\n\tc = c.cloneCode()\n\twords := make([]string, 0)\n\tfor {\n\t\tw, err := c.nextWord()\n\t\tif err == io.EOF {\n\t\t\treturn strings.Join(words, \" \")\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(\"Unexpected error!!!\")\n\t\t}\n\t\twords = append(words, w.str)\n\t}\n}\n<commit_msg>Fix the name for DebugCore<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\/pprof\"\n\t\"strings\"\n\t\"time\"\n)\n\nvar ModDebugCore = PISCModule{\n\tAuthor:    \"Andrew Owen\",\n\tName:      \"DebugCore\",\n\tLicense:   \"MIT\",\n\tDocString: \"The debug words used in PISC\",\n\tLoad:      loadDebugCore,\n}\n\nfunc loadDebugCore(m *machine) error {\n\t\/\/ ( -- )\n\tm.predefinedWords[\"show-prefix-words\"] = NilWord(func(m *machine) {\n\t\tfor name := range m.prefixWords {\n\t\t\tfmt.Println(name)\n\t\t}\n\t})\n\t\/\/ ( quot -- .. time )\n\tm.addGoWord(\"time\", \"( quot -- .. time )\", GoWord(func(m *machine) error {\n\t\twords := &codeQuotation{\n\t\t\tidx:   0,\n\t\t\twords: []*word{&word{str: \"call\"}},\n\t\t}\n\t\tstart := time.Now()\n\t\terr := m.execute(words)\n\t\telapsed := time.Since(start)\n\t\tm.pushValue(String(fmt.Sprint(\"Code took \", elapsed)))\n\t\treturn err\n\t}))\n\n\tm.addGoWord(\"print-debug-trace\", \"( -- )\", func(m *machine) error {\n\t\tfmt.Println(m.debugTrace)\n\t\treturn nil\n\t})\n\n\tm.addGoWord(\"clear-debug-trace\", \"( -- )\", func(m *machine) error {\n\t\tm.debugTrace = \"\"\n\t\treturn nil\n\t})\n\n\t\/\/ ( filepath quotation -- )\n\tm.predefinedWords[\"cpu-pprof\"] = GoWord(func(m *machine) error {\n\t\tm.executeString(\"swap\", codePosition{source: \"cpu-pprof GoWord\"})\n\t\tpath := m.popValue().String()\n\t\tf, err := os.Create(path)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Unable to create profiling file\")\n\t\t\treturn err\n\t\t}\n\t\tif err := pprof.StartCPUProfile(f); err != nil {\n\t\t\tlog.Fatal(\"Unable to start CPU profile\")\n\t\t\treturn err\n\t\t}\n\t\tm.executeQuotation()\n\t\tpprof.StopCPUProfile()\n\t\treturn nil\n\t})\n\n\t\/\/ ( -- )\n\tm.predefinedWords[\"dump-defined-words\"] = GoWord(func(m *machine) error {\n\t\t\/\/ var words = make(Array, 0)\n\t\tfor name, seq := range m.prefixWords {\n\t\t\tfmt.Println(\":PRE\", name, m.definedStackComments[name], DumpToString(seq), \";\")\n\t\t}\n\t\tfor name, seq := range m.definedWords {\n\t\t\tfmt.Println(\":DOC\", name, m.definedStackComments[name], m.helpDocs[name], \";\")\n\t\t\tfmt.Println(\":\", name, m.definedStackComments[name], DumpToString(seq), \";\")\n\t\t}\n\t\treturn nil\n\t})\n\treturn m.importPISCAsset(\"stdlib\/debug.pisc\")\n}\n\n\/\/ TODO: See about this...\nfunc DumpToString(c codeSequence) string {\n\tc = c.cloneCode()\n\twords := make([]string, 0)\n\tfor {\n\t\tw, err := c.nextWord()\n\t\tif err == io.EOF {\n\t\t\treturn strings.Join(words, \" \")\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(\"Unexpected error!!!\")\n\t\t}\n\t\twords = append(words, w.str)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package auth\n\nimport (\n\t\"crypto\/md5\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\ttestSignTime = time.Unix(1541064730, 0)\n\ttestPrivKey  = \"12345678\"\n)\n\nfunc assertEqual(t *testing.T, x, y interface{}) {\n\tif !reflect.DeepEqual(x, y) {\n\t\tt.Errorf(\"%s: Not equal! Expected='%v', Actual='%v'\\n\", t.Name(), x, y)\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAtypeAuth(t *testing.T) {\n\tr, _ := url.Parse(\"https:\/\/example.com\/a?foo=bar\")\n\turl := aTypeTest(r, testPrivKey, testSignTime)\n\tassertEqual(t, \"https:\/\/example.com\/a?foo=bar&auth_key=1541064730-0-0-f9dd5ed1e274ab4b1d5f5745344bf28b\", url)\n}\n\nfunc TestBtypeAuth(t *testing.T) {\n\tsigner := newURLSigner(\"b\", testPrivKey)\n\turl, _ := signer.Sign(\"https:\/\/example.com\/a?foo=bar\", testSignTime)\n\tassertEqual(t, \"https:\/\/example.com\/201811011732\/3a19d83a89ccb00a73212420791b0123\/a?foo=bar\", url)\n}\n\nfunc TestCtypeAuth(t *testing.T) {\n\tsigner := newURLSigner(\"c\", testPrivKey)\n\turl, _ := signer.Sign(\"https:\/\/example.com\/a?foo=bar\", testSignTime)\n\tassertEqual(t, \"https:\/\/example.com\/7d6b308ce87beb16d9dba32d741220f6\/5bdac81a\/a?foo=bar\", url)\n}\n\nfunc aTypeTest(r *url.URL, privateKey string, expires time.Time) string {\n\t\/\/rand equals \"0\" in test case\n\trand := \"0\"\n\tuid := \"0\"\n\tsecret := fmt.Sprintf(\"%s-%d-%s-%s-%s\", r.Path, expires.Unix(), rand, uid, privateKey)\n\thashValue := md5.Sum([]byte(secret))\n\tauthKey := fmt.Sprintf(\"%d-%s-%s-%x\", expires.Unix(), rand, uid, hashValue)\n\tif r.RawQuery == \"\" {\n\t\treturn fmt.Sprintf(\"%s?auth_key=%s\", r.String(), authKey)\n\t} else {\n\t\treturn fmt.Sprintf(\"%s&auth_key=%s\", r.String(), authKey)\n\t}\n}\n<commit_msg>fix newsignurl<commit_after>package auth\n\nimport (\n\t\"crypto\/md5\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\ttestSignTime = time.Unix(1541064730, 0)\n\ttestPrivKey  = \"12345678\"\n)\n\nfunc assertEqual(t *testing.T, x, y interface{}) {\n\tif !reflect.DeepEqual(x, y) {\n\t\tt.Errorf(\"%s: Not equal! Expected='%v', Actual='%v'\\n\", t.Name(), x, y)\n\t\tt.FailNow()\n\t}\n}\n\nfunc TestAtypeAuth(t *testing.T) {\n\tr, _ := url.Parse(\"https:\/\/example.com\/a?foo=bar\")\n\turl := aTypeTest(r, testPrivKey, testSignTime)\n\tassertEqual(t, \"https:\/\/example.com\/a?foo=bar&auth_key=1541064730-0-0-f9dd5ed1e274ab4b1d5f5745344bf28b\", url)\n}\n\nfunc TestBtypeAuth(t *testing.T) {\n\tsigner := NewURLSigner(\"b\", testPrivKey)\n\turl, _ := signer.Sign(\"https:\/\/example.com\/a?foo=bar\", testSignTime)\n\tassertEqual(t, \"https:\/\/example.com\/201811011732\/3a19d83a89ccb00a73212420791b0123\/a?foo=bar\", url)\n}\n\nfunc TestCtypeAuth(t *testing.T) {\n\tsigner := NewURLSigner(\"c\", testPrivKey)\n\turl, _ := signer.Sign(\"https:\/\/example.com\/a?foo=bar\", testSignTime)\n\tassertEqual(t, \"https:\/\/example.com\/7d6b308ce87beb16d9dba32d741220f6\/5bdac81a\/a?foo=bar\", url)\n}\n\nfunc aTypeTest(r *url.URL, privateKey string, expires time.Time) string {\n\t\/\/rand equals \"0\" in test case\n\trand := \"0\"\n\tuid := \"0\"\n\tsecret := fmt.Sprintf(\"%s-%d-%s-%s-%s\", r.Path, expires.Unix(), rand, uid, privateKey)\n\thashValue := md5.Sum([]byte(secret))\n\tauthKey := fmt.Sprintf(\"%d-%s-%s-%x\", expires.Unix(), rand, uid, hashValue)\n\tif r.RawQuery == \"\" {\n\t\treturn fmt.Sprintf(\"%s?auth_key=%s\", r.String(), authKey)\n\t} else {\n\t\treturn fmt.Sprintf(\"%s&auth_key=%s\", r.String(), authKey)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved.\n\/\/ Copyright (c) 2006-2014 Sippy Software, Inc. All rights reserved.\n\/\/ Copyright (c) 2016 Andriy Pylypenko. All rights reserved.\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation and\/or\n\/\/ other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n\/\/ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n\/\/ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\npackage sippy\n\nimport (\n    \"bufio\"\n    \"net\"\n    \"strconv\"\n    \"strings\"\n\n    \"sippy\/net\"\n    \"sippy\/types\"\n)\n\nfunc NewRtpProxyClient(opts *rtpProxyClientOpts) sippy_types.RtpProxyClient {\n    return NewRtp_proxy_client_base(nil, opts)\n}\n\ntype Rtp_proxy_client_base struct {\n    heir            sippy_types.RtpProxyClient\n    opts            *rtpProxyClientOpts\n    transport       rtp_proxy_transport\n    online          bool\n    sbind_supported bool\n    tnot_supported  bool\n    copy_supported  bool\n    stat_supported  bool\n    wdnt_supported  bool\n    caps_done       bool\n    shut_down       bool\n    active_sessions int64\n    sessions_created int64\n    active_streams  int64\n    preceived       int64\n    ptransmitted    int64\n}\n\ntype rtp_proxy_transport interface {\n    address() net.Addr\n    get_rtpc_delay() float64\n    is_local() bool\n    send_command(string, func(string))\n    shutdown()\n    reconnect(net.Addr, *sippy_net.HostPort)\n}\n\nfunc (self *Rtp_proxy_client_base) IsLocal() bool {\n    return self.transport.is_local()\n}\n\nfunc (self *Rtp_proxy_client_base) IsOnline() bool {\n    return self.online\n}\n\nfunc (self *Rtp_proxy_client_base) WdntSupported() bool {\n    return self.wdnt_supported\n}\n\nfunc (self *Rtp_proxy_client_base) SBindSupported() bool {\n    return self.sbind_supported\n}\n\nfunc (self *Rtp_proxy_client_base) TNotSupported() bool {\n    return self.tnot_supported\n}\n\nfunc (self *Rtp_proxy_client_base) GetProxyAddress() string {\n    return self.opts.proxy_address\n}\n\nfunc (self *Rtp_proxy_client_base) me() sippy_types.RtpProxyClient {\n    if self.heir != nil {\n        return self.heir\n    }\n    return self\n}\n\nfunc (self *Rtp_proxy_client_base) Address() net.Addr {\n    return self.transport.address()\n}\n\nfunc NewRtp_proxy_client_base(heir sippy_types.RtpProxyClient, opts *rtpProxyClientOpts) *Rtp_proxy_client_base {\n    return &Rtp_proxy_client_base{\n        heir            : heir,\n        caps_done       : false,\n        shut_down       : false,\n        opts            : opts,\n    }\n}\n\nfunc (self *Rtp_proxy_client_base) Start() error {\n    var err error\n\n    self.transport, err = self.opts.rtpp_class(self.me(), self.opts.config, self.opts.rtppaddr, self.opts.bind_address)\n    if err != nil {\n        return err\n    }\n    if ! self.opts.no_version_check {\n        self.version_check()\n    } else {\n        self.caps_done = true\n        self.online = true\n    }\n    return nil\n}\n\nfunc (self *Rtp_proxy_client_base) SendCommand(cmd string, cb func(string)) {\n    self.transport.send_command(cmd, cb)\n}\n\nfunc (self *Rtp_proxy_client_base) Reconnect(addr net.Addr, bind_addr *sippy_net.HostPort) {\n    self.transport.reconnect(addr, bind_addr)\n}\n\nfunc (self *Rtp_proxy_client_base) version_check() {\n    if self.shut_down {\n        return\n    }\n    self.transport.send_command(\"V\", self.version_check_reply)\n}\n\nfunc (self *Rtp_proxy_client_base) version_check_reply(version string) {\n    if self.shut_down {\n        return\n    }\n    if version == \"20040107\" {\n        self.me().GoOnline()\n    } else if self.online {\n        self.me().GoOffline()\n    } else {\n        StartTimeoutWithSpread(self.version_check, nil, self.opts.hrtb_retr_ival, 1, self.opts.logger, 0.1)\n    }\n}\n\nfunc (self *Rtp_proxy_client_base) heartbeat() {\n    \/\/print \"heartbeat\", self, self.address\n    if self.shut_down {\n        return\n    }\n    self.transport.send_command(\"Ib\", self.heartbeat_reply)\n}\n\nfunc (self *Rtp_proxy_client_base) heartbeat_reply(stats string) {\n    \/\/print \"heartbeat_reply\", self.address, stats, self.online\n    if self.shut_down || ! self.online {\n        return\n    }\n    if stats == \"\" {\n        self.active_sessions = 0\n        self.me().GoOffline()\n    } else {\n        sessions_created := int64(0)\n        active_sessions := int64(0)\n        active_streams := int64(0)\n        preceived := int64(0)\n        ptransmitted := int64(0)\n        scanner := bufio.NewScanner(strings.NewReader(stats))\n        for scanner.Scan() {\n            line_parts := strings.SplitN(scanner.Text(), \":\", 2)\n            if len(line_parts) != 2 { continue }\n            switch line_parts[0] {\n            case \"sessions created\":\n                sessions_created, _ = strconv.ParseInt(line_parts[1], 10, 64)\n            case \"active sessions\":\n                active_sessions, _ = strconv.ParseInt(line_parts[1], 10, 64)\n            case \"active streams\":\n                active_streams, _ = strconv.ParseInt(line_parts[1], 10, 64)\n            case \"packets received\":\n                preceived, _ = strconv.ParseInt(line_parts[1], 10, 64)\n            case \"packets transmitted\":\n                ptransmitted, _ = strconv.ParseInt(line_parts[1], 10, 64)\n            }\n        }\n        self.UpdateActive(active_sessions, sessions_created, active_streams, preceived, ptransmitted)\n    }\n    StartTimeoutWithSpread(self.heartbeat, nil, self.opts.hrtb_ival, 1, self.opts.logger, 0.1)\n}\n\nfunc (self *Rtp_proxy_client_base) GoOnline() {\n    if self.shut_down {\n        return\n    }\n    if ! self.online {\n        if ! self.caps_done {\n            newRtppCapsChecker(self)\n            return\n        }\n        self.online = true\n        self.heartbeat()\n    }\n}\n\nfunc (self *Rtp_proxy_client_base) GoOffline() {\n    if self.shut_down {\n        return\n    }\n    \/\/print \"go_offline\", self.address, self.online\n    if self.online {\n        self.online = false\n        StartTimeoutWithSpread(self.version_check, nil, self.opts.hrtb_retr_ival, 1, self.opts.logger, 0.1)\n    }\n}\n\nfunc (self *Rtp_proxy_client_base) UpdateActive(active_sessions, sessions_created, active_streams, preceived, ptransmitted int64) {\n    self.sessions_created = sessions_created\n    self.active_sessions = active_sessions\n    self.active_streams = active_streams\n    self.preceived = preceived\n    self.ptransmitted = ptransmitted\n}\n\nfunc (self *Rtp_proxy_client_base) GetActiveSessions() int64 {\n    return self.active_sessions\n}\n\nfunc (self *Rtp_proxy_client_base) GetActiveStreams() int64 {\n    return self.active_streams\n}\n\nfunc (self *Rtp_proxy_client_base) GetPReceived() int64 {\n    return self.preceived\n}\n\nfunc (self *Rtp_proxy_client_base) GetSessionsCreated() int64 {\n    return self.sessions_created\n}\n\nfunc (self *Rtp_proxy_client_base) GetPTransmitted() int64 {\n    return self.ptransmitted\n}\n\nfunc (self *Rtp_proxy_client_base) Shutdown() {\n    if self.shut_down { \/\/ do not crash when shutdown() called twice\n        return\n    }\n    self.shut_down = true\n    self.transport.shutdown()\n    self.transport = nil\n}\n\nfunc (self *Rtp_proxy_client_base) IsShutDown() bool {\n    return self.shut_down\n}\n\nfunc (self *Rtp_proxy_client_base) GetOpts() sippy_types.RtpProxyClientOpts {\n    return self.opts\n}\n\nfunc (self *Rtp_proxy_client_base) GetRtpcDelay() float64 {\n    return self.transport.get_rtpc_delay()\n}\n\ntype rtppCapsChecker struct {\n    caps_requested  int\n    caps_received   int\n    rtpc            *Rtp_proxy_client_base\n}\n\nfunc newRtppCapsChecker(rtpc *Rtp_proxy_client_base) *rtppCapsChecker {\n    self := &rtppCapsChecker{\n        rtpc    : rtpc,\n    }\n    rtpc.caps_done = false\n    CAPSTABLE := []struct{ vers string; attr *bool }{\n        { \"20071218\", &self.rtpc.copy_supported },\n        { \"20080403\", &self.rtpc.stat_supported },\n        { \"20081224\", &self.rtpc.tnot_supported },\n        { \"20090810\", &self.rtpc.sbind_supported },\n        { \"20150617\", &self.rtpc.wdnt_supported },\n    }\n    self.caps_requested = len(CAPSTABLE)\n    for _, it := range CAPSTABLE {\n        attr := it.attr \/\/ For some reason the it.attr cannot be passed into the following\n                        \/\/ function directly - the resulting value is always that of the\n                        \/\/ last 'it.attr' value.\n        rtpc.transport.send_command(\"VF \" + it.vers, func(res string) { self.caps_query_done(res, attr) })\n    }\n    return self\n}\n\nfunc (self *rtppCapsChecker) caps_query_done(result string, attr *bool) {\n    self.caps_received += 1\n    if result == \"1\" {\n        *attr = true\n    } else {\n        *attr = false\n    }\n    if self.caps_received == self.caps_requested {\n        self.rtpc.caps_done = true\n        self.rtpc.GoOnline()\n        self.rtpc = nil\n    }\n}\n<commit_msg>The GoOnline() function is virtual.<commit_after>\/\/ Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved.\n\/\/ Copyright (c) 2006-2014 Sippy Software, Inc. All rights reserved.\n\/\/ Copyright (c) 2016 Andriy Pylypenko. All rights reserved.\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without modification,\n\/\/ are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation and\/or\n\/\/ other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n\/\/ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n\/\/ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n\/\/ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n\/\/ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n\/\/ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\npackage sippy\n\nimport (\n    \"bufio\"\n    \"net\"\n    \"strconv\"\n    \"strings\"\n\n    \"sippy\/net\"\n    \"sippy\/types\"\n)\n\nfunc NewRtpProxyClient(opts *rtpProxyClientOpts) sippy_types.RtpProxyClient {\n    return NewRtp_proxy_client_base(nil, opts)\n}\n\ntype Rtp_proxy_client_base struct {\n    heir            sippy_types.RtpProxyClient\n    opts            *rtpProxyClientOpts\n    transport       rtp_proxy_transport\n    online          bool\n    sbind_supported bool\n    tnot_supported  bool\n    copy_supported  bool\n    stat_supported  bool\n    wdnt_supported  bool\n    caps_done       bool\n    shut_down       bool\n    active_sessions int64\n    sessions_created int64\n    active_streams  int64\n    preceived       int64\n    ptransmitted    int64\n}\n\ntype rtp_proxy_transport interface {\n    address() net.Addr\n    get_rtpc_delay() float64\n    is_local() bool\n    send_command(string, func(string))\n    shutdown()\n    reconnect(net.Addr, *sippy_net.HostPort)\n}\n\nfunc (self *Rtp_proxy_client_base) IsLocal() bool {\n    return self.transport.is_local()\n}\n\nfunc (self *Rtp_proxy_client_base) IsOnline() bool {\n    return self.online\n}\n\nfunc (self *Rtp_proxy_client_base) WdntSupported() bool {\n    return self.wdnt_supported\n}\n\nfunc (self *Rtp_proxy_client_base) SBindSupported() bool {\n    return self.sbind_supported\n}\n\nfunc (self *Rtp_proxy_client_base) TNotSupported() bool {\n    return self.tnot_supported\n}\n\nfunc (self *Rtp_proxy_client_base) GetProxyAddress() string {\n    return self.opts.proxy_address\n}\n\nfunc (self *Rtp_proxy_client_base) me() sippy_types.RtpProxyClient {\n    if self.heir != nil {\n        return self.heir\n    }\n    return self\n}\n\nfunc (self *Rtp_proxy_client_base) Address() net.Addr {\n    return self.transport.address()\n}\n\nfunc NewRtp_proxy_client_base(heir sippy_types.RtpProxyClient, opts *rtpProxyClientOpts) *Rtp_proxy_client_base {\n    return &Rtp_proxy_client_base{\n        heir            : heir,\n        caps_done       : false,\n        shut_down       : false,\n        opts            : opts,\n    }\n}\n\nfunc (self *Rtp_proxy_client_base) Start() error {\n    var err error\n\n    self.transport, err = self.opts.rtpp_class(self.me(), self.opts.config, self.opts.rtppaddr, self.opts.bind_address)\n    if err != nil {\n        return err\n    }\n    if ! self.opts.no_version_check {\n        self.version_check()\n    } else {\n        self.caps_done = true\n        self.online = true\n    }\n    return nil\n}\n\nfunc (self *Rtp_proxy_client_base) SendCommand(cmd string, cb func(string)) {\n    self.transport.send_command(cmd, cb)\n}\n\nfunc (self *Rtp_proxy_client_base) Reconnect(addr net.Addr, bind_addr *sippy_net.HostPort) {\n    self.transport.reconnect(addr, bind_addr)\n}\n\nfunc (self *Rtp_proxy_client_base) version_check() {\n    if self.shut_down {\n        return\n    }\n    self.transport.send_command(\"V\", self.version_check_reply)\n}\n\nfunc (self *Rtp_proxy_client_base) version_check_reply(version string) {\n    if self.shut_down {\n        return\n    }\n    if version == \"20040107\" {\n        self.me().GoOnline()\n    } else if self.online {\n        self.me().GoOffline()\n    } else {\n        StartTimeoutWithSpread(self.version_check, nil, self.opts.hrtb_retr_ival, 1, self.opts.logger, 0.1)\n    }\n}\n\nfunc (self *Rtp_proxy_client_base) heartbeat() {\n    \/\/print \"heartbeat\", self, self.address\n    if self.shut_down {\n        return\n    }\n    self.transport.send_command(\"Ib\", self.heartbeat_reply)\n}\n\nfunc (self *Rtp_proxy_client_base) heartbeat_reply(stats string) {\n    \/\/print \"heartbeat_reply\", self.address, stats, self.online\n    if self.shut_down || ! self.online {\n        return\n    }\n    if stats == \"\" {\n        self.active_sessions = 0\n        self.me().GoOffline()\n    } else {\n        sessions_created := int64(0)\n        active_sessions := int64(0)\n        active_streams := int64(0)\n        preceived := int64(0)\n        ptransmitted := int64(0)\n        scanner := bufio.NewScanner(strings.NewReader(stats))\n        for scanner.Scan() {\n            line_parts := strings.SplitN(scanner.Text(), \":\", 2)\n            if len(line_parts) != 2 { continue }\n            switch line_parts[0] {\n            case \"sessions created\":\n                sessions_created, _ = strconv.ParseInt(line_parts[1], 10, 64)\n            case \"active sessions\":\n                active_sessions, _ = strconv.ParseInt(line_parts[1], 10, 64)\n            case \"active streams\":\n                active_streams, _ = strconv.ParseInt(line_parts[1], 10, 64)\n            case \"packets received\":\n                preceived, _ = strconv.ParseInt(line_parts[1], 10, 64)\n            case \"packets transmitted\":\n                ptransmitted, _ = strconv.ParseInt(line_parts[1], 10, 64)\n            }\n        }\n        self.UpdateActive(active_sessions, sessions_created, active_streams, preceived, ptransmitted)\n    }\n    StartTimeoutWithSpread(self.heartbeat, nil, self.opts.hrtb_ival, 1, self.opts.logger, 0.1)\n}\n\nfunc (self *Rtp_proxy_client_base) GoOnline() {\n    if self.shut_down {\n        return\n    }\n    if ! self.online {\n        if ! self.caps_done {\n            newRtppCapsChecker(self)\n            return\n        }\n        self.online = true\n        self.heartbeat()\n    }\n}\n\nfunc (self *Rtp_proxy_client_base) GoOffline() {\n    if self.shut_down {\n        return\n    }\n    \/\/print \"go_offline\", self.address, self.online\n    if self.online {\n        self.online = false\n        StartTimeoutWithSpread(self.version_check, nil, self.opts.hrtb_retr_ival, 1, self.opts.logger, 0.1)\n    }\n}\n\nfunc (self *Rtp_proxy_client_base) UpdateActive(active_sessions, sessions_created, active_streams, preceived, ptransmitted int64) {\n    self.sessions_created = sessions_created\n    self.active_sessions = active_sessions\n    self.active_streams = active_streams\n    self.preceived = preceived\n    self.ptransmitted = ptransmitted\n}\n\nfunc (self *Rtp_proxy_client_base) GetActiveSessions() int64 {\n    return self.active_sessions\n}\n\nfunc (self *Rtp_proxy_client_base) GetActiveStreams() int64 {\n    return self.active_streams\n}\n\nfunc (self *Rtp_proxy_client_base) GetPReceived() int64 {\n    return self.preceived\n}\n\nfunc (self *Rtp_proxy_client_base) GetSessionsCreated() int64 {\n    return self.sessions_created\n}\n\nfunc (self *Rtp_proxy_client_base) GetPTransmitted() int64 {\n    return self.ptransmitted\n}\n\nfunc (self *Rtp_proxy_client_base) Shutdown() {\n    if self.shut_down { \/\/ do not crash when shutdown() called twice\n        return\n    }\n    self.shut_down = true\n    self.transport.shutdown()\n    self.transport = nil\n}\n\nfunc (self *Rtp_proxy_client_base) IsShutDown() bool {\n    return self.shut_down\n}\n\nfunc (self *Rtp_proxy_client_base) GetOpts() sippy_types.RtpProxyClientOpts {\n    return self.opts\n}\n\nfunc (self *Rtp_proxy_client_base) GetRtpcDelay() float64 {\n    return self.transport.get_rtpc_delay()\n}\n\ntype rtppCapsChecker struct {\n    caps_requested  int\n    caps_received   int\n    rtpc            *Rtp_proxy_client_base\n}\n\nfunc newRtppCapsChecker(rtpc *Rtp_proxy_client_base) *rtppCapsChecker {\n    self := &rtppCapsChecker{\n        rtpc    : rtpc,\n    }\n    rtpc.caps_done = false\n    CAPSTABLE := []struct{ vers string; attr *bool }{\n        { \"20071218\", &self.rtpc.copy_supported },\n        { \"20080403\", &self.rtpc.stat_supported },\n        { \"20081224\", &self.rtpc.tnot_supported },\n        { \"20090810\", &self.rtpc.sbind_supported },\n        { \"20150617\", &self.rtpc.wdnt_supported },\n    }\n    self.caps_requested = len(CAPSTABLE)\n    for _, it := range CAPSTABLE {\n        attr := it.attr \/\/ For some reason the it.attr cannot be passed into the following\n                        \/\/ function directly - the resulting value is always that of the\n                        \/\/ last 'it.attr' value.\n        rtpc.transport.send_command(\"VF \" + it.vers, func(res string) { self.caps_query_done(res, attr) })\n    }\n    return self\n}\n\nfunc (self *rtppCapsChecker) caps_query_done(result string, attr *bool) {\n    self.caps_received += 1\n    if result == \"1\" {\n        *attr = true\n    } else {\n        *attr = false\n    }\n    if self.caps_received == self.caps_requested {\n        self.rtpc.caps_done = true\n        self.rtpc.me().GoOnline()\n        self.rtpc = nil\n    }\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2015 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage remotecommand\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"k8s.io\/klog\/v2\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/httpstream\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/remotecommand\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/runtime\"\n\trestclient \"k8s.io\/client-go\/rest\"\n\tspdy \"k8s.io\/client-go\/transport\/spdy\"\n)\n\n\/\/ StreamOptions holds information pertaining to the current streaming session:\n\/\/ input\/output streams, if the client is requesting a TTY, and a terminal size queue to\n\/\/ support terminal resizing.\ntype StreamOptions struct {\n\tStdin             io.Reader\n\tStdout            io.Writer\n\tStderr            io.Writer\n\tTty               bool\n\tTerminalSizeQueue TerminalSizeQueue\n}\n\n\/\/ Executor is an interface for transporting shell-style streams.\ntype Executor interface {\n\t\/\/ Deprecated: use StreamWithContext instead to avoid possible resource leaks.\n\t\/\/ See https:\/\/github.com\/kubernetes\/kubernetes\/pull\/103177 for details.\n\tStream(options StreamOptions) error\n\n\t\/\/ StreamWithContext initiates the transport of the standard shell streams. It will\n\t\/\/ transport any non-nil stream to a remote system, and return an error if a problem\n\t\/\/ occurs. If tty is set, the stderr stream is not used (raw TTY manages stdout and\n\t\/\/ stderr over the stdout stream).\n\t\/\/ The context controls the entire lifetime of stream execution.\n\tStreamWithContext(ctx context.Context, options StreamOptions) error\n}\n\ntype streamCreator interface {\n\tCreateStream(headers http.Header) (httpstream.Stream, error)\n}\n\ntype streamProtocolHandler interface {\n\tstream(conn streamCreator) error\n}\n\n\/\/ streamExecutor handles transporting standard shell streams over an httpstream connection.\ntype streamExecutor struct {\n\tupgrader  spdy.Upgrader\n\ttransport http.RoundTripper\n\n\tmethod    string\n\turl       *url.URL\n\tprotocols []string\n}\n\n\/\/ NewSPDYExecutor connects to the provided server and upgrades the connection to\n\/\/ multiplexed bidirectional streams.\nfunc NewSPDYExecutor(config *restclient.Config, method string, url *url.URL) (Executor, error) {\n\twrapper, upgradeRoundTripper, err := spdy.RoundTripperFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewSPDYExecutorForTransports(wrapper, upgradeRoundTripper, method, url)\n}\n\n\/\/ NewSPDYExecutorForTransports connects to the provided server using the given transport,\n\/\/ upgrades the response using the given upgrader to multiplexed bidirectional streams.\nfunc NewSPDYExecutorForTransports(transport http.RoundTripper, upgrader spdy.Upgrader, method string, url *url.URL) (Executor, error) {\n\treturn NewSPDYExecutorForProtocols(\n\t\ttransport, upgrader, method, url,\n\t\tremotecommand.StreamProtocolV4Name,\n\t\tremotecommand.StreamProtocolV3Name,\n\t\tremotecommand.StreamProtocolV2Name,\n\t\tremotecommand.StreamProtocolV1Name,\n\t)\n}\n\n\/\/ NewSPDYExecutorForProtocols connects to the provided server and upgrades the connection to\n\/\/ multiplexed bidirectional streams using only the provided protocols. Exposed for testing, most\n\/\/ callers should use NewSPDYExecutor or NewSPDYExecutorForTransports.\nfunc NewSPDYExecutorForProtocols(transport http.RoundTripper, upgrader spdy.Upgrader, method string, url *url.URL, protocols ...string) (Executor, error) {\n\treturn &streamExecutor{\n\t\tupgrader:  upgrader,\n\t\ttransport: transport,\n\t\tmethod:    method,\n\t\turl:       url,\n\t\tprotocols: protocols,\n\t}, nil\n}\n\n\/\/ Stream opens a protocol streamer to the server and streams until a client closes\n\/\/ the connection or the server disconnects.\nfunc (e *streamExecutor) Stream(options StreamOptions) error {\n\treturn e.StreamWithContext(context.Background(), options)\n}\n\n\/\/ newConnectionAndStream creates a new SPDY connection and a stream protocol handler upon it.\nfunc (e *streamExecutor) newConnectionAndStream(ctx context.Context, options StreamOptions) (httpstream.Connection, streamProtocolHandler, error) {\n\treq, err := http.NewRequestWithContext(ctx, e.method, e.url.String(), nil)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error creating request: %v\", err)\n\t}\n\n\tconn, protocol, err := spdy.Negotiate(\n\t\te.upgrader,\n\t\t&http.Client{Transport: e.transport},\n\t\treq,\n\t\te.protocols...,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar streamer streamProtocolHandler\n\n\tswitch protocol {\n\tcase remotecommand.StreamProtocolV4Name:\n\t\tstreamer = newStreamProtocolV4(options)\n\tcase remotecommand.StreamProtocolV3Name:\n\t\tstreamer = newStreamProtocolV3(options)\n\tcase remotecommand.StreamProtocolV2Name:\n\t\tstreamer = newStreamProtocolV2(options)\n\tcase \"\":\n\t\tklog.V(4).Infof(\"The server did not negotiate a streaming protocol version. Falling back to %s\", remotecommand.StreamProtocolV1Name)\n\t\tfallthrough\n\tcase remotecommand.StreamProtocolV1Name:\n\t\tstreamer = newStreamProtocolV1(options)\n\t}\n\n\treturn conn, streamer, nil\n}\n\n\/\/ StreamWithContext opens a protocol streamer to the server and streams until a client closes\n\/\/ the connection or the server disconnects or the context is done.\nfunc (e *streamExecutor) StreamWithContext(ctx context.Context, options StreamOptions) error {\n\tconn, streamer, err := e.newConnectionAndStream(ctx, options)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\terrorChan := make(chan error, 1)\n\tgo func() {\n\t\tdefer runtime.HandleCrash()\n\t\tdefer close(errorChan)\n\t\terrorChan <- streamer.stream(conn)\n\t}()\n\n\tselect {\n\tcase err := <-errorChan:\n\t\treturn err\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}\n<commit_msg>Propagate the panic with a channel<commit_after>\/*\nCopyright 2015 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage remotecommand\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n\n\t\"k8s.io\/klog\/v2\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/httpstream\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/remotecommand\"\n\trestclient \"k8s.io\/client-go\/rest\"\n\t\"k8s.io\/client-go\/transport\/spdy\"\n)\n\n\/\/ StreamOptions holds information pertaining to the current streaming session:\n\/\/ input\/output streams, if the client is requesting a TTY, and a terminal size queue to\n\/\/ support terminal resizing.\ntype StreamOptions struct {\n\tStdin             io.Reader\n\tStdout            io.Writer\n\tStderr            io.Writer\n\tTty               bool\n\tTerminalSizeQueue TerminalSizeQueue\n}\n\n\/\/ Executor is an interface for transporting shell-style streams.\ntype Executor interface {\n\t\/\/ Deprecated: use StreamWithContext instead to avoid possible resource leaks.\n\t\/\/ See https:\/\/github.com\/kubernetes\/kubernetes\/pull\/103177 for details.\n\tStream(options StreamOptions) error\n\n\t\/\/ StreamWithContext initiates the transport of the standard shell streams. It will\n\t\/\/ transport any non-nil stream to a remote system, and return an error if a problem\n\t\/\/ occurs. If tty is set, the stderr stream is not used (raw TTY manages stdout and\n\t\/\/ stderr over the stdout stream).\n\t\/\/ The context controls the entire lifetime of stream execution.\n\tStreamWithContext(ctx context.Context, options StreamOptions) error\n}\n\ntype streamCreator interface {\n\tCreateStream(headers http.Header) (httpstream.Stream, error)\n}\n\ntype streamProtocolHandler interface {\n\tstream(conn streamCreator) error\n}\n\n\/\/ streamExecutor handles transporting standard shell streams over an httpstream connection.\ntype streamExecutor struct {\n\tupgrader  spdy.Upgrader\n\ttransport http.RoundTripper\n\n\tmethod    string\n\turl       *url.URL\n\tprotocols []string\n}\n\n\/\/ NewSPDYExecutor connects to the provided server and upgrades the connection to\n\/\/ multiplexed bidirectional streams.\nfunc NewSPDYExecutor(config *restclient.Config, method string, url *url.URL) (Executor, error) {\n\twrapper, upgradeRoundTripper, err := spdy.RoundTripperFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewSPDYExecutorForTransports(wrapper, upgradeRoundTripper, method, url)\n}\n\n\/\/ NewSPDYExecutorForTransports connects to the provided server using the given transport,\n\/\/ upgrades the response using the given upgrader to multiplexed bidirectional streams.\nfunc NewSPDYExecutorForTransports(transport http.RoundTripper, upgrader spdy.Upgrader, method string, url *url.URL) (Executor, error) {\n\treturn NewSPDYExecutorForProtocols(\n\t\ttransport, upgrader, method, url,\n\t\tremotecommand.StreamProtocolV4Name,\n\t\tremotecommand.StreamProtocolV3Name,\n\t\tremotecommand.StreamProtocolV2Name,\n\t\tremotecommand.StreamProtocolV1Name,\n\t)\n}\n\n\/\/ NewSPDYExecutorForProtocols connects to the provided server and upgrades the connection to\n\/\/ multiplexed bidirectional streams using only the provided protocols. Exposed for testing, most\n\/\/ callers should use NewSPDYExecutor or NewSPDYExecutorForTransports.\nfunc NewSPDYExecutorForProtocols(transport http.RoundTripper, upgrader spdy.Upgrader, method string, url *url.URL, protocols ...string) (Executor, error) {\n\treturn &streamExecutor{\n\t\tupgrader:  upgrader,\n\t\ttransport: transport,\n\t\tmethod:    method,\n\t\turl:       url,\n\t\tprotocols: protocols,\n\t}, nil\n}\n\n\/\/ Stream opens a protocol streamer to the server and streams until a client closes\n\/\/ the connection or the server disconnects.\nfunc (e *streamExecutor) Stream(options StreamOptions) error {\n\treturn e.StreamWithContext(context.Background(), options)\n}\n\n\/\/ newConnectionAndStream creates a new SPDY connection and a stream protocol handler upon it.\nfunc (e *streamExecutor) newConnectionAndStream(ctx context.Context, options StreamOptions) (httpstream.Connection, streamProtocolHandler, error) {\n\treq, err := http.NewRequestWithContext(ctx, e.method, e.url.String(), nil)\n\tif err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"error creating request: %v\", err)\n\t}\n\n\tconn, protocol, err := spdy.Negotiate(\n\t\te.upgrader,\n\t\t&http.Client{Transport: e.transport},\n\t\treq,\n\t\te.protocols...,\n\t)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tvar streamer streamProtocolHandler\n\n\tswitch protocol {\n\tcase remotecommand.StreamProtocolV4Name:\n\t\tstreamer = newStreamProtocolV4(options)\n\tcase remotecommand.StreamProtocolV3Name:\n\t\tstreamer = newStreamProtocolV3(options)\n\tcase remotecommand.StreamProtocolV2Name:\n\t\tstreamer = newStreamProtocolV2(options)\n\tcase \"\":\n\t\tklog.V(4).Infof(\"The server did not negotiate a streaming protocol version. Falling back to %s\", remotecommand.StreamProtocolV1Name)\n\t\tfallthrough\n\tcase remotecommand.StreamProtocolV1Name:\n\t\tstreamer = newStreamProtocolV1(options)\n\t}\n\n\treturn conn, streamer, nil\n}\n\n\/\/ StreamWithContext opens a protocol streamer to the server and streams until a client closes\n\/\/ the connection or the server disconnects or the context is done.\nfunc (e *streamExecutor) StreamWithContext(ctx context.Context, options StreamOptions) error {\n\tconn, streamer, err := e.newConnectionAndStream(ctx, options)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tpanicChan := make(chan any, 1)\n\terrorChan := make(chan error, 1)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif p := recover(); p != nil {\n\t\t\t\tpanicChan <- p\n\t\t\t}\n\t\t}()\n\t\terrorChan <- streamer.stream(conn)\n\t}()\n\n\tselect {\n\tcase p := <-panicChan:\n\t\tpanic(p)\n\tcase err := <-errorChan:\n\t\treturn err\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package errcheck is the library used to implement the errcheck command-line tool.\n\/\/\n\/\/ Note: The API of this package has not been finalized and may change at any point.\npackage errcheck\n\nimport (\n\t\"bytes\"\n\t\"code.google.com\/p\/go.tools\/go\/types\"\n\t\"errors\"\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"honnef.co\/go\/importer\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"regexp\"\n)\n\nvar (\n\t\/\/ ErrNoGoFiles is returned when CheckPackage is run on a package with no Go source files\n\tErrNoGoFiles = errors.New(\"package contains no go source files\")\n)\n\n\/\/ UncheckedErrors is returned from the CheckPackage function if the package contains\n\/\/ any unchecked errors.\ntype UncheckedErrors struct {\n\t\/\/ Errors is a list of all the unchecked errors in the package.\n\t\/\/ Printing an error reports its position within the file and the contents of the line.\n\tErrors []error\n}\n\nfunc (e UncheckedErrors) Error() string {\n\treturn fmt.Sprintln(len(e.Errors), \"unchecked errors\")\n}\n\nfunc CheckPackage(pkgPath string, ignore map[string]*regexp.Regexp, blank bool) error {\n\tpkg, err := newPackage(pkgPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn checkPackage(pkg, ignore, blank)\n}\n\n\/\/ package_ represents a single Go package\ntype package_ struct {\n\tpath     string\n\tfset     *token.FileSet\n\tastFiles []*ast.File\n\tfiles    map[string]file\n}\n\n\/\/ newPackage creates a package_ from the Go files in path\nfunc newPackage(path string) (package_, error) {\n\tp := package_{path: path, fset: token.NewFileSet()}\n\tpkg, err := findPackage(path)\n\tif err != nil {\n\t\treturn p, fmt.Errorf(\"could not find package: %s\", err)\n\t}\n\tfileNames := getFiles(pkg)\n\n\tif len(fileNames) == 0 {\n\t\treturn p, ErrNoGoFiles\n\t}\n\n\tp.astFiles = make([]*ast.File, len(fileNames))\n\tp.files = make(map[string]file, len(fileNames))\n\n\tfor i, fileName := range fileNames {\n\t\tf, err := parseFile(p.fset, fileName)\n\t\tif err != nil {\n\t\t\treturn p, fmt.Errorf(\"could not parse %s: %s\", fileName, err)\n\t\t}\n\t\tp.files[fileName] = f\n\t\tp.astFiles[i] = f.ast\n\t}\n\n\treturn p, nil\n}\n\n\/\/ typedPackage is like package_ but with type information\ntype typedPackage struct {\n\tpackage_\n\tcallTypes map[ast.Expr]types.Type\n\tidentObjs map[*ast.Ident]types.Object\n}\n\n\/\/ typeCheck creates a typedPackage from a package_\nfunc typeCheck(p package_) (typedPackage, error) {\n\ttp := typedPackage{\n\t\tpackage_:  p,\n\t\tcallTypes: make(map[ast.Expr]types.Type),\n\t\tidentObjs: make(map[*ast.Ident]types.Object),\n\t}\n\n\tinfo := types.Info{\n\t\tTypes:   tp.callTypes,\n\t\tObjects: tp.identObjs,\n\t}\n\tcontext := types.Config{Import: importer.NewImporter().Import}\n\n\t_, err := context.Check(p.path, p.fset, p.astFiles, &info)\n\treturn tp, err\n}\n\n\/\/ file represents a single Go source file\ntype file struct {\n\tfset  *token.FileSet\n\tname  string\n\tast   *ast.File\n\tlines [][]byte\n}\n\nfunc parseFile(fset *token.FileSet, fileName string) (f file, err error) {\n\trd, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn f, err\n\t}\n\tdefer rd.Close()\n\n\tdata, err := ioutil.ReadAll(rd)\n\tif err != nil {\n\t\treturn f, err\n\t}\n\n\tastFile, err := parser.ParseFile(fset, fileName, bytes.NewReader(data), parser.ParseComments)\n\tif err != nil {\n\t\treturn f, fmt.Errorf(\"could not parse: %s\", err)\n\t}\n\n\tlines := bytes.Split(data, []byte(\"\\n\"))\n\tf = file{fset: fset, name: fileName, ast: astFile, lines: lines}\n\treturn f, nil\n}\n\n\/\/ checker implements the errcheck algorithm\ntype checker struct {\n\tpkg    typedPackage\n\tignore map[string]*regexp.Regexp\n\tblank  bool\n\n\terrors []error\n}\n\ntype uncheckedError struct {\n\tpos  token.Position\n\tline []byte\n}\n\nfunc (e uncheckedError) Error() string {\n\treturn fmt.Sprintf(\"%s\\t%s\", e.pos, e.line)\n}\n\nfunc (c *checker) ignoreCall(call *ast.CallExpr) bool {\n\t\/\/ Try to get an identifier.\n\t\/\/ Currently only supports simple expressions:\n\t\/\/     1. f()\n\t\/\/     2. x.y.f()\n\tvar id *ast.Ident\n\tswitch exp := call.Fun.(type) {\n\tcase (*ast.Ident):\n\t\tid = exp\n\tcase (*ast.SelectorExpr):\n\t\tid = exp.Sel\n\tdefault:\n\t\t\/\/ eg: *ast.SliceExpr, *ast.IndexExpr\n\t}\n\n\tif id == nil {\n\t\treturn false\n\t}\n\n\t\/\/ If we got an identifier for the function, see if it is ignored\n\n\tif re, ok := c.ignore[\"\"]; ok && re.MatchString(id.Name) {\n\t\treturn true\n\t}\n\n\tif obj := c.pkg.identObjs[id]; obj != nil {\n\t\tif pkg := obj.Pkg(); pkg != nil {\n\t\t\tif re, ok := c.ignore[pkg.Path()]; ok {\n\t\t\t\treturn re.MatchString(id.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ errorsByArg returns a slice s such that\n\/\/ len(s) == number of return types of call\n\/\/ s[i] == true iff return type at position i from left is an error type\nfunc (c *checker) errorsByArg(call *ast.CallExpr) []bool {\n\tswitch t := c.pkg.callTypes[call].(type) {\n\tcase *types.Named:\n\t\t\/\/ Single return\n\t\treturn []bool{isErrorType(t.Obj())}\n\tcase *types.Tuple:\n\t\t\/\/ Multiple returns\n\t\ts := make([]bool, t.Len())\n\t\tfor i := 0; i < t.Len(); i++ {\n\t\t\tnt, ok := t.At(i).Type().(*types.Named)\n\t\t\ts[i] = ok && isErrorType(nt.Obj())\n\t\t}\n\t\treturn s\n\t}\n\treturn nil\n}\n\nfunc (c *checker) callReturnsError(call *ast.CallExpr) bool {\n\tfor _, isError := range c.errorsByArg(call) {\n\t\tif isError {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (c *checker) addErrorAtPosition(position token.Pos) {\n\tpos := c.pkg.fset.Position(position)\n\tline := bytes.TrimSpace(c.pkg.files[pos.Filename].lines[pos.Line-1])\n\tc.errors = append(c.errors, uncheckedError{pos, line})\n}\n\nfunc (c *checker) Visit(node ast.Node) ast.Visitor {\n\tswitch stmt := node.(type) {\n\tcase *ast.ExprStmt:\n\t\tif call, ok := stmt.X.(*ast.CallExpr); ok {\n\t\t\tif !c.ignoreCall(call) && c.callReturnsError(call) {\n\t\t\t\tc.addErrorAtPosition(call.Lparen)\n\t\t\t}\n\t\t}\n\tcase *ast.GoStmt:\n\t\t\/\/BUG(kisielk) This won't work till\n\t\t\/\/ http:\/\/code.google.com\/p\/go\/issues\/detail?id=6413 is fixed.\n\t\tif !c.ignoreCall(stmt.Call) && c.callReturnsError(stmt.Call) {\n\t\t\tfmt.Println(\"added error\")\n\t\t\tc.addErrorAtPosition(stmt.Call.Lparen)\n\t\t}\n\tcase *ast.DeferStmt:\n\t\t\/\/BUG(kisielk) This won't work till\n\t\t\/\/ http:\/\/code.google.com\/p\/go\/issues\/detail?id=6413 is fixed.\n\t\tif !c.ignoreCall(stmt.Call) && c.callReturnsError(stmt.Call) {\n\t\t\tfmt.Println(\"added error\")\n\t\t\tc.addErrorAtPosition(stmt.Call.Lparen)\n\t\t}\n\tcase *ast.AssignStmt:\n\t\tif !c.blank {\n\t\t\tbreak\n\t\t}\n\t\tif len(stmt.Rhs) == 1 {\n\t\t\t\/\/ single value on rhs; check against lhs identifiers\n\t\t\tif call, ok := stmt.Rhs[0].(*ast.CallExpr); ok {\n\t\t\t\tif c.ignoreCall(call) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tisError := c.errorsByArg(call)\n\t\t\t\tfor i := 0; i < len(stmt.Lhs); i++ {\n\t\t\t\t\tif id, ok := stmt.Lhs[i].(*ast.Ident); ok {\n\t\t\t\t\t\tif id.Name == \"_\" && isError[i] {\n\t\t\t\t\t\t\tc.addErrorAtPosition(id.NamePos)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ multiple value on rhs; in this case a call can't return\n\t\t\t\/\/ multiple values. Assume len(stmt.Lhs) == len(stmt.Rhs)\n\t\t\tfor i := 0; i < len(stmt.Lhs); i++ {\n\t\t\t\tif id, ok := stmt.Lhs[i].(*ast.Ident); ok {\n\t\t\t\t\tif call, ok := stmt.Rhs[i].(*ast.CallExpr); ok {\n\t\t\t\t\t\tif c.ignoreCall(call) {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif id.Name == \"_\" && c.callReturnsError(call) {\n\t\t\t\t\t\t\tc.addErrorAtPosition(id.NamePos)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tdefault:\n\t}\n\treturn c\n}\n\nfunc checkPackage(pkg package_, ignore map[string]*regexp.Regexp, blank bool) error {\n\ttp, err := typeCheck(pkg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not type check: %s\", err)\n\t}\n\n\tvisitor := &checker{tp, ignore, blank, []error{}}\n\tfor _, astFile := range pkg.astFiles {\n\t\tast.Walk(visitor, astFile)\n\t}\n\n\tif len(visitor.errors) > 0 {\n\t\treturn UncheckedErrors{visitor.errors}\n\t}\n\treturn nil\n}\n\ntype obj interface {\n\tPkg() *types.Package\n\tName() string\n}\n\nfunc isErrorType(v obj) bool {\n\treturn v.Pkg() == nil && v.Name() == \"error\"\n}\n<commit_msg>Don't use Println to print error strings, silly.<commit_after>\/\/ Package errcheck is the library used to implement the errcheck command-line tool.\n\/\/\n\/\/ Note: The API of this package has not been finalized and may change at any point.\npackage errcheck\n\nimport (\n\t\"bytes\"\n\t\"code.google.com\/p\/go.tools\/go\/types\"\n\t\"errors\"\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"honnef.co\/go\/importer\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"regexp\"\n)\n\nvar (\n\t\/\/ ErrNoGoFiles is returned when CheckPackage is run on a package with no Go source files\n\tErrNoGoFiles = errors.New(\"package contains no go source files\")\n)\n\n\/\/ UncheckedErrors is returned from the CheckPackage function if the package contains\n\/\/ any unchecked errors.\ntype UncheckedErrors struct {\n\t\/\/ Errors is a list of all the unchecked errors in the package.\n\t\/\/ Printing an error reports its position within the file and the contents of the line.\n\tErrors []error\n}\n\nfunc (e UncheckedErrors) Error() string {\n\treturn fmt.Sprintf(\"%d unchecked errors\", len(e.Errors))\n}\n\nfunc CheckPackage(pkgPath string, ignore map[string]*regexp.Regexp, blank bool) error {\n\tpkg, err := newPackage(pkgPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn checkPackage(pkg, ignore, blank)\n}\n\n\/\/ package_ represents a single Go package\ntype package_ struct {\n\tpath     string\n\tfset     *token.FileSet\n\tastFiles []*ast.File\n\tfiles    map[string]file\n}\n\n\/\/ newPackage creates a package_ from the Go files in path\nfunc newPackage(path string) (package_, error) {\n\tp := package_{path: path, fset: token.NewFileSet()}\n\tpkg, err := findPackage(path)\n\tif err != nil {\n\t\treturn p, fmt.Errorf(\"could not find package: %s\", err)\n\t}\n\tfileNames := getFiles(pkg)\n\n\tif len(fileNames) == 0 {\n\t\treturn p, ErrNoGoFiles\n\t}\n\n\tp.astFiles = make([]*ast.File, len(fileNames))\n\tp.files = make(map[string]file, len(fileNames))\n\n\tfor i, fileName := range fileNames {\n\t\tf, err := parseFile(p.fset, fileName)\n\t\tif err != nil {\n\t\t\treturn p, fmt.Errorf(\"could not parse %s: %s\", fileName, err)\n\t\t}\n\t\tp.files[fileName] = f\n\t\tp.astFiles[i] = f.ast\n\t}\n\n\treturn p, nil\n}\n\n\/\/ typedPackage is like package_ but with type information\ntype typedPackage struct {\n\tpackage_\n\tcallTypes map[ast.Expr]types.Type\n\tidentObjs map[*ast.Ident]types.Object\n}\n\n\/\/ typeCheck creates a typedPackage from a package_\nfunc typeCheck(p package_) (typedPackage, error) {\n\ttp := typedPackage{\n\t\tpackage_:  p,\n\t\tcallTypes: make(map[ast.Expr]types.Type),\n\t\tidentObjs: make(map[*ast.Ident]types.Object),\n\t}\n\n\tinfo := types.Info{\n\t\tTypes:   tp.callTypes,\n\t\tObjects: tp.identObjs,\n\t}\n\tcontext := types.Config{Import: importer.NewImporter().Import}\n\n\t_, err := context.Check(p.path, p.fset, p.astFiles, &info)\n\treturn tp, err\n}\n\n\/\/ file represents a single Go source file\ntype file struct {\n\tfset  *token.FileSet\n\tname  string\n\tast   *ast.File\n\tlines [][]byte\n}\n\nfunc parseFile(fset *token.FileSet, fileName string) (f file, err error) {\n\trd, err := os.Open(fileName)\n\tif err != nil {\n\t\treturn f, err\n\t}\n\tdefer rd.Close()\n\n\tdata, err := ioutil.ReadAll(rd)\n\tif err != nil {\n\t\treturn f, err\n\t}\n\n\tastFile, err := parser.ParseFile(fset, fileName, bytes.NewReader(data), parser.ParseComments)\n\tif err != nil {\n\t\treturn f, fmt.Errorf(\"could not parse: %s\", err)\n\t}\n\n\tlines := bytes.Split(data, []byte(\"\\n\"))\n\tf = file{fset: fset, name: fileName, ast: astFile, lines: lines}\n\treturn f, nil\n}\n\n\/\/ checker implements the errcheck algorithm\ntype checker struct {\n\tpkg    typedPackage\n\tignore map[string]*regexp.Regexp\n\tblank  bool\n\n\terrors []error\n}\n\ntype uncheckedError struct {\n\tpos  token.Position\n\tline []byte\n}\n\nfunc (e uncheckedError) Error() string {\n\treturn fmt.Sprintf(\"%s\\t%s\", e.pos, e.line)\n}\n\nfunc (c *checker) ignoreCall(call *ast.CallExpr) bool {\n\t\/\/ Try to get an identifier.\n\t\/\/ Currently only supports simple expressions:\n\t\/\/     1. f()\n\t\/\/     2. x.y.f()\n\tvar id *ast.Ident\n\tswitch exp := call.Fun.(type) {\n\tcase (*ast.Ident):\n\t\tid = exp\n\tcase (*ast.SelectorExpr):\n\t\tid = exp.Sel\n\tdefault:\n\t\t\/\/ eg: *ast.SliceExpr, *ast.IndexExpr\n\t}\n\n\tif id == nil {\n\t\treturn false\n\t}\n\n\t\/\/ If we got an identifier for the function, see if it is ignored\n\n\tif re, ok := c.ignore[\"\"]; ok && re.MatchString(id.Name) {\n\t\treturn true\n\t}\n\n\tif obj := c.pkg.identObjs[id]; obj != nil {\n\t\tif pkg := obj.Pkg(); pkg != nil {\n\t\t\tif re, ok := c.ignore[pkg.Path()]; ok {\n\t\t\t\treturn re.MatchString(id.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ errorsByArg returns a slice s such that\n\/\/ len(s) == number of return types of call\n\/\/ s[i] == true iff return type at position i from left is an error type\nfunc (c *checker) errorsByArg(call *ast.CallExpr) []bool {\n\tswitch t := c.pkg.callTypes[call].(type) {\n\tcase *types.Named:\n\t\t\/\/ Single return\n\t\treturn []bool{isErrorType(t.Obj())}\n\tcase *types.Tuple:\n\t\t\/\/ Multiple returns\n\t\ts := make([]bool, t.Len())\n\t\tfor i := 0; i < t.Len(); i++ {\n\t\t\tnt, ok := t.At(i).Type().(*types.Named)\n\t\t\ts[i] = ok && isErrorType(nt.Obj())\n\t\t}\n\t\treturn s\n\t}\n\treturn nil\n}\n\nfunc (c *checker) callReturnsError(call *ast.CallExpr) bool {\n\tfor _, isError := range c.errorsByArg(call) {\n\t\tif isError {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (c *checker) addErrorAtPosition(position token.Pos) {\n\tpos := c.pkg.fset.Position(position)\n\tline := bytes.TrimSpace(c.pkg.files[pos.Filename].lines[pos.Line-1])\n\tc.errors = append(c.errors, uncheckedError{pos, line})\n}\n\nfunc (c *checker) Visit(node ast.Node) ast.Visitor {\n\tswitch stmt := node.(type) {\n\tcase *ast.ExprStmt:\n\t\tif call, ok := stmt.X.(*ast.CallExpr); ok {\n\t\t\tif !c.ignoreCall(call) && c.callReturnsError(call) {\n\t\t\t\tc.addErrorAtPosition(call.Lparen)\n\t\t\t}\n\t\t}\n\tcase *ast.GoStmt:\n\t\t\/\/BUG(kisielk) This won't work till\n\t\t\/\/ http:\/\/code.google.com\/p\/go\/issues\/detail?id=6413 is fixed.\n\t\tif !c.ignoreCall(stmt.Call) && c.callReturnsError(stmt.Call) {\n\t\t\tfmt.Println(\"added error\")\n\t\t\tc.addErrorAtPosition(stmt.Call.Lparen)\n\t\t}\n\tcase *ast.DeferStmt:\n\t\t\/\/BUG(kisielk) This won't work till\n\t\t\/\/ http:\/\/code.google.com\/p\/go\/issues\/detail?id=6413 is fixed.\n\t\tif !c.ignoreCall(stmt.Call) && c.callReturnsError(stmt.Call) {\n\t\t\tfmt.Println(\"added error\")\n\t\t\tc.addErrorAtPosition(stmt.Call.Lparen)\n\t\t}\n\tcase *ast.AssignStmt:\n\t\tif !c.blank {\n\t\t\tbreak\n\t\t}\n\t\tif len(stmt.Rhs) == 1 {\n\t\t\t\/\/ single value on rhs; check against lhs identifiers\n\t\t\tif call, ok := stmt.Rhs[0].(*ast.CallExpr); ok {\n\t\t\t\tif c.ignoreCall(call) {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tisError := c.errorsByArg(call)\n\t\t\t\tfor i := 0; i < len(stmt.Lhs); i++ {\n\t\t\t\t\tif id, ok := stmt.Lhs[i].(*ast.Ident); ok {\n\t\t\t\t\t\tif id.Name == \"_\" && isError[i] {\n\t\t\t\t\t\t\tc.addErrorAtPosition(id.NamePos)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ multiple value on rhs; in this case a call can't return\n\t\t\t\/\/ multiple values. Assume len(stmt.Lhs) == len(stmt.Rhs)\n\t\t\tfor i := 0; i < len(stmt.Lhs); i++ {\n\t\t\t\tif id, ok := stmt.Lhs[i].(*ast.Ident); ok {\n\t\t\t\t\tif call, ok := stmt.Rhs[i].(*ast.CallExpr); ok {\n\t\t\t\t\t\tif c.ignoreCall(call) {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif id.Name == \"_\" && c.callReturnsError(call) {\n\t\t\t\t\t\t\tc.addErrorAtPosition(id.NamePos)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tdefault:\n\t}\n\treturn c\n}\n\nfunc checkPackage(pkg package_, ignore map[string]*regexp.Regexp, blank bool) error {\n\ttp, err := typeCheck(pkg)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not type check: %s\", err)\n\t}\n\n\tvisitor := &checker{tp, ignore, blank, []error{}}\n\tfor _, astFile := range pkg.astFiles {\n\t\tast.Walk(visitor, astFile)\n\t}\n\n\tif len(visitor.errors) > 0 {\n\t\treturn UncheckedErrors{visitor.errors}\n\t}\n\treturn nil\n}\n\ntype obj interface {\n\tPkg() *types.Package\n\tName() string\n}\n\nfunc isErrorType(v obj) bool {\n\treturn v.Pkg() == nil && v.Name() == \"error\"\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 CoreOS, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/coreos\/rkt\/Godeps\/_workspace\/src\/github.com\/ThomasRooney\/gexpect\"\n)\n\nvar envTests = []struct {\n\trunCmd    string\n\trunExpect string\n\tsleepCmd  string\n\tenterCmd  string\n}{\n\t{\n\t\t`^RKT_BIN^ --debug --insecure-skip-verify run .\/rkt-inspect-print-var-from-manifest.aci`,\n\t\t\"VAR_FROM_MANIFEST=manifest\",\n\t\t`^RKT_BIN^ --debug --insecure-skip-verify run .\/rkt-inspect-sleep.aci`,\n\t\t`\/bin\/sh -c \"^RKT_BIN^ --debug enter $(^RKT_BIN^ list --full|grep running|awk '{print $1}') \/inspect --print-env=VAR_FROM_MANIFEST\"`,\n\t},\n\t{\n\t\t`^RKT_BIN^ --debug --insecure-skip-verify run --set-env=VAR_OTHER=setenv .\/rkt-inspect-print-var-other.aci`,\n\t\t\"VAR_OTHER=setenv\",\n\t\t`^RKT_BIN^ --debug --insecure-skip-verify run --set-env=VAR_OTHER=setenv .\/rkt-inspect-sleep.aci`,\n\t\t`\/bin\/sh -c \"^RKT_BIN^ --debug enter $(^RKT_BIN^ list --full|grep running|awk '{print $1}') \/inspect --print-env=VAR_OTHER\"`,\n\t},\n\t{\n\t\t`^RKT_BIN^ --debug --insecure-skip-verify run --set-env=VAR_FROM_MANIFEST=setenv .\/rkt-inspect-print-var-from-manifest.aci`,\n\t\t\"VAR_FROM_MANIFEST=setenv\",\n\t\t`^RKT_BIN^ --debug --insecure-skip-verify run --set-env=VAR_FROM_MANIFEST=setenv .\/rkt-inspect-sleep.aci`,\n\t\t`\/bin\/sh -c \"^RKT_BIN^ --debug enter $(^RKT_BIN^ list --full|grep running|awk '{print $1}') \/inspect --print-env=VAR_FROM_MANIFEST\"`,\n\t},\n\t{\n\t\t`\/bin\/sh -c \"export VAR_OTHER=host ; ^RKT_BIN^ --debug --insecure-skip-verify run --inherit-env=true .\/rkt-inspect-print-var-other.aci\"`,\n\t\t\"VAR_OTHER=host\",\n\t\t`\/bin\/sh -c \"export VAR_OTHER=host ; ^RKT_BIN^ --debug --insecure-skip-verify run --inherit-env=true .\/rkt-inspect-sleep.aci\"`,\n\t\t`\/bin\/sh -c \"export VAR_OTHER=host ; ^RKT_BIN^ --debug enter $(^RKT_BIN^ list --full|grep running|awk '{print $1}') \/inspect --print-env=VAR_OTHER\"`,\n\t},\n\t{\n\t\t`\/bin\/sh -c \"export VAR_FROM_MANIFEST=host ; ^RKT_BIN^ --debug --insecure-skip-verify run --inherit-env=true .\/rkt-inspect-print-var-from-manifest.aci\"`,\n\t\t\"VAR_FROM_MANIFEST=manifest\",\n\t\t`\/bin\/sh -c \"export VAR_FROM_MANIFEST=host ; ^RKT_BIN^ --debug --insecure-skip-verify run --inherit-env=true .\/rkt-inspect-sleep.aci\"`,\n\t\t`\/bin\/sh -c \"export VAR_FROM_MANIFEST=host ; ^RKT_BIN^ --debug enter $(^RKT_BIN^ list --full|grep running|awk '{print $1}') \/inspect --print-env=VAR_FROM_MANIFEST\"`,\n\t},\n\t{\n\t\t`\/bin\/sh -c \"export VAR_OTHER=host ; ^RKT_BIN^ --debug --insecure-skip-verify run --inherit-env=true --set-env=VAR_OTHER=setenv .\/rkt-inspect-print-var-other.aci\"`,\n\t\t\"VAR_OTHER=setenv\",\n\t\t`\/bin\/sh -c \"export VAR_OTHER=host ; ^RKT_BIN^ --debug --insecure-skip-verify run --inherit-env=true --set-env=VAR_OTHER=setenv .\/rkt-inspect-sleep.aci\"`,\n\t\t`\/bin\/sh -c \"export VAR_OTHER=host ; ^RKT_BIN^ --debug enter $(^RKT_BIN^ list --full|grep running|awk '{print $1}') \/inspect --print-env=VAR_OTHER\"`,\n\t},\n}\n\nfunc TestEnv(t *testing.T) {\n\tpatchTestACI(\"rkt-inspect-print-var-from-manifest.aci\", \"--exec=\/inspect --print-env=VAR_FROM_MANIFEST\")\n\tdefer os.Remove(\"rkt-inspect-print-var-from-manifest.aci\")\n\tpatchTestACI(\"rkt-inspect-print-var-other.aci\", \"--exec=\/inspect --print-env=VAR_OTHER\")\n\tdefer os.Remove(\"rkt-inspect-print-var-other.aci\")\n\tpatchTestACI(\"rkt-inspect-sleep.aci\", \"--exec=\/inspect --print-msg=Hello --sleep=84000\")\n\tdefer os.Remove(\"rkt-inspect-sleep.aci\")\n\tctx := newRktRunCtx()\n\tdefer ctx.cleanup()\n\n\tfor i, tt := range envTests {\n\t\t\/\/ 'run' tests\n\t\trunCmd := strings.Replace(tt.runCmd, \"^RKT_BIN^\", ctx.cmd(), -1)\n\t\tt.Logf(\"Running 'run' test #%v: %v\", i, runCmd)\n\t\tchild, err := gexpect.Spawn(runCmd)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Cannot exec rkt #%v: %v\", i, err)\n\t\t}\n\n\t\terr = child.Expect(tt.runExpect)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected %q but not found\", tt.runExpect)\n\t\t}\n\n\t\terr = child.Wait()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"rkt didn't terminate correctly: %v\", err)\n\t\t}\n\n\t\t\/\/ 'enter' tests\n\t\tsleepCmd := strings.Replace(tt.sleepCmd, \"^RKT_BIN^\", ctx.cmd(), -1)\n\t\tt.Logf(\"Running 'enter' test #%v: sleep: %v\", i, sleepCmd)\n\t\tchild, err = gexpect.Spawn(sleepCmd)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Cannot exec rkt #%v: %v\", i, err)\n\t\t}\n\n\t\terr = child.Expect(\"Hello\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected %q but not found\", tt.runExpect)\n\t\t}\n\n\t\tenterCmd := strings.Replace(tt.enterCmd, \"^RKT_BIN^\", ctx.cmd(), -1)\n\t\tt.Logf(\"Running 'enter' test #%v: enter: %v\", i, enterCmd)\n\t\tenterChild, err := gexpect.Spawn(enterCmd)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Cannot exec rkt #%v: %v\", i, err)\n\t\t}\n\n\t\terr = enterChild.Expect(tt.runExpect)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected %q but not found\", tt.runExpect)\n\t\t}\n\n\t\terr = enterChild.Wait()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"rkt didn't terminate correctly: %v\", err)\n\t\t}\n\t\terr = child.Close()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"rkt didn't terminate correctly: %v\", err)\n\t\t}\n\t\tctx.reset()\n\t}\n}\n<commit_msg>functional tests: environment: fix a race between child.Close() and ctx.reset()<commit_after>\/\/ Copyright 2015 CoreOS, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/coreos\/rkt\/Godeps\/_workspace\/src\/github.com\/ThomasRooney\/gexpect\"\n)\n\nvar envTests = []struct {\n\trunCmd    string\n\trunExpect string\n\tsleepCmd  string\n\tenterCmd  string\n}{\n\t{\n\t\t`^RKT_BIN^ --debug --insecure-skip-verify run .\/rkt-inspect-print-var-from-manifest.aci`,\n\t\t\"VAR_FROM_MANIFEST=manifest\",\n\t\t`^RKT_BIN^ --debug --insecure-skip-verify run --interactive .\/rkt-inspect-sleep.aci`,\n\t\t`\/bin\/sh -c \"^RKT_BIN^ --debug enter $(^RKT_BIN^ list --full|grep running|awk '{print $1}') \/inspect --print-env=VAR_FROM_MANIFEST\"`,\n\t},\n\t{\n\t\t`^RKT_BIN^ --debug --insecure-skip-verify run --set-env=VAR_OTHER=setenv .\/rkt-inspect-print-var-other.aci`,\n\t\t\"VAR_OTHER=setenv\",\n\t\t`^RKT_BIN^ --debug --insecure-skip-verify run --interactive --set-env=VAR_OTHER=setenv .\/rkt-inspect-sleep.aci`,\n\t\t`\/bin\/sh -c \"^RKT_BIN^ --debug enter $(^RKT_BIN^ list --full|grep running|awk '{print $1}') \/inspect --print-env=VAR_OTHER\"`,\n\t},\n\t{\n\t\t`^RKT_BIN^ --debug --insecure-skip-verify run --set-env=VAR_FROM_MANIFEST=setenv .\/rkt-inspect-print-var-from-manifest.aci`,\n\t\t\"VAR_FROM_MANIFEST=setenv\",\n\t\t`^RKT_BIN^ --debug --insecure-skip-verify run --interactive --set-env=VAR_FROM_MANIFEST=setenv .\/rkt-inspect-sleep.aci`,\n\t\t`\/bin\/sh -c \"^RKT_BIN^ --debug enter $(^RKT_BIN^ list --full|grep running|awk '{print $1}') \/inspect --print-env=VAR_FROM_MANIFEST\"`,\n\t},\n\t{\n\t\t`\/bin\/sh -c \"export VAR_OTHER=host ; ^RKT_BIN^ --debug --insecure-skip-verify run --inherit-env=true .\/rkt-inspect-print-var-other.aci\"`,\n\t\t\"VAR_OTHER=host\",\n\t\t`\/bin\/sh -c \"export VAR_OTHER=host ; ^RKT_BIN^ --debug --insecure-skip-verify run --interactive --inherit-env=true .\/rkt-inspect-sleep.aci\"`,\n\t\t`\/bin\/sh -c \"export VAR_OTHER=host ; ^RKT_BIN^ --debug enter $(^RKT_BIN^ list --full|grep running|awk '{print $1}') \/inspect --print-env=VAR_OTHER\"`,\n\t},\n\t{\n\t\t`\/bin\/sh -c \"export VAR_FROM_MANIFEST=host ; ^RKT_BIN^ --debug --insecure-skip-verify run --inherit-env=true .\/rkt-inspect-print-var-from-manifest.aci\"`,\n\t\t\"VAR_FROM_MANIFEST=manifest\",\n\t\t`\/bin\/sh -c \"export VAR_FROM_MANIFEST=host ; ^RKT_BIN^ --debug --insecure-skip-verify run --interactive --inherit-env=true .\/rkt-inspect-sleep.aci\"`,\n\t\t`\/bin\/sh -c \"export VAR_FROM_MANIFEST=host ; ^RKT_BIN^ --debug enter $(^RKT_BIN^ list --full|grep running|awk '{print $1}') \/inspect --print-env=VAR_FROM_MANIFEST\"`,\n\t},\n\t{\n\t\t`\/bin\/sh -c \"export VAR_OTHER=host ; ^RKT_BIN^ --debug --insecure-skip-verify run --inherit-env=true --set-env=VAR_OTHER=setenv .\/rkt-inspect-print-var-other.aci\"`,\n\t\t\"VAR_OTHER=setenv\",\n\t\t`\/bin\/sh -c \"export VAR_OTHER=host ; ^RKT_BIN^ --debug --insecure-skip-verify run --interactive --inherit-env=true --set-env=VAR_OTHER=setenv .\/rkt-inspect-sleep.aci\"`,\n\t\t`\/bin\/sh -c \"export VAR_OTHER=host ; ^RKT_BIN^ --debug enter $(^RKT_BIN^ list --full|grep running|awk '{print $1}') \/inspect --print-env=VAR_OTHER\"`,\n\t},\n}\n\nfunc TestEnv(t *testing.T) {\n\tpatchTestACI(\"rkt-inspect-print-var-from-manifest.aci\", \"--exec=\/inspect --print-env=VAR_FROM_MANIFEST\")\n\tdefer os.Remove(\"rkt-inspect-print-var-from-manifest.aci\")\n\tpatchTestACI(\"rkt-inspect-print-var-other.aci\", \"--exec=\/inspect --print-env=VAR_OTHER\")\n\tdefer os.Remove(\"rkt-inspect-print-var-other.aci\")\n\tpatchTestACI(\"rkt-inspect-sleep.aci\", \"--exec=\/inspect --read-stdin\")\n\tdefer os.Remove(\"rkt-inspect-sleep.aci\")\n\tctx := newRktRunCtx()\n\tdefer ctx.cleanup()\n\n\tfor i, tt := range envTests {\n\t\t\/\/ 'run' tests\n\t\trunCmd := strings.Replace(tt.runCmd, \"^RKT_BIN^\", ctx.cmd(), -1)\n\t\tt.Logf(\"Running 'run' test #%v: %v\", i, runCmd)\n\t\tchild, err := gexpect.Spawn(runCmd)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Cannot exec rkt #%v: %v\", i, err)\n\t\t}\n\n\t\terr = child.Expect(tt.runExpect)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected %q but not found\", tt.runExpect)\n\t\t}\n\n\t\terr = child.Wait()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"rkt didn't terminate correctly: %v\", err)\n\t\t}\n\n\t\t\/\/ 'enter' tests\n\t\tsleepCmd := strings.Replace(tt.sleepCmd, \"^RKT_BIN^\", ctx.cmd(), -1)\n\t\tt.Logf(\"Running 'enter' test #%v: sleep: %v\", i, sleepCmd)\n\t\tchild, err = gexpect.Spawn(sleepCmd)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Cannot exec rkt #%v: %v\", i, err)\n\t\t}\n\n\t\terr = child.Expect(\"Enter text:\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Waited for the prompt but not found #%v\", i)\n\t\t}\n\n\t\tenterCmd := strings.Replace(tt.enterCmd, \"^RKT_BIN^\", ctx.cmd(), -1)\n\t\tt.Logf(\"Running 'enter' test #%v: enter: %v\", i, enterCmd)\n\t\tenterChild, err := gexpect.Spawn(enterCmd)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Cannot exec rkt #%v: %v\", i, err)\n\t\t}\n\n\t\terr = enterChild.Expect(tt.runExpect)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected %q but not found\", tt.runExpect)\n\t\t}\n\n\t\terr = enterChild.Wait()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"rkt didn't terminate correctly: %v\", err)\n\t\t}\n\t\terr = child.SendLine(\"Bye\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"rkt couldn't write to the container: %v\", err)\n\t\t}\n\t\terr = child.Expect(\"Received text: Bye\")\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Expected Bye but not found #%v\", i)\n\t\t}\n\n\t\terr = child.Wait()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"rkt didn't terminate correctly: %v\", err)\n\t\t}\n\t\tctx.reset()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n\nmulti is a server that loads up multiple games on one server to demonstrate\nhow that works. It is also possible to have a server with only one game.\n\n*\/\npackage main\n\nimport (\n\t\"github.com\/jkomoros\/boardgame\/examples\/blackjack\"\n\t\"github.com\/jkomoros\/boardgame\/examples\/debuganimations\"\n\t\"github.com\/jkomoros\/boardgame\/examples\/memory\"\n\t\"github.com\/jkomoros\/boardgame\/examples\/tictactoe\"\n\t\"github.com\/jkomoros\/boardgame\/server\/api\"\n)\n\nfunc main() {\n\tstorage := api.NewDefaultStorageManager()\n\tdefer storage.Close()\n\tapi.NewServer(storage, blackjack.NewManager(storage), tictactoe.NewManager(storage), memory.NewManager(storage), debuganimations.NewManager(storage)).Start()\n}\n<commit_msg>Wire pig example into server. Part of #372.<commit_after>\/*\n\nmulti is a server that loads up multiple games on one server to demonstrate\nhow that works. It is also possible to have a server with only one game.\n\n*\/\npackage main\n\nimport (\n\t\"github.com\/jkomoros\/boardgame\/examples\/blackjack\"\n\t\"github.com\/jkomoros\/boardgame\/examples\/debuganimations\"\n\t\"github.com\/jkomoros\/boardgame\/examples\/memory\"\n\t\"github.com\/jkomoros\/boardgame\/examples\/pig\"\n\t\"github.com\/jkomoros\/boardgame\/examples\/tictactoe\"\n\t\"github.com\/jkomoros\/boardgame\/server\/api\"\n)\n\nfunc main() {\n\tstorage := api.NewDefaultStorageManager()\n\tdefer storage.Close()\n\tapi.NewServer(storage,\n\t\tblackjack.NewManager(storage),\n\t\ttictactoe.NewManager(storage),\n\t\tmemory.NewManager(storage),\n\t\tdebuganimations.NewManager(storage),\n\t\tpig.NewManager(storage),\n\t).Start()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/ChristopherRabotin\/gokalman\"\n\t\"github.com\/ChristopherRabotin\/smd\"\n\t\"github.com\/gonum\/matrix\/mat64\"\n)\n\nconst (\n\tekfTrigger    = 15    \/\/ Number of measurements prior to switching to EKF mode.\n\tsncEnabled    = true  \/\/ Set to false to disable SNC.\n\ttimeBasedPlot = false \/\/ Set to true to plot time, or false to plot on measurements.\n)\n\nvar (\n\twg sync.WaitGroup\n)\n\nfunc main() {\n\t\/\/ Define the times\n\tstartDT := time.Now()\n\tendDT := startDT.Add(time.Duration(24) * time.Hour)\n\t\/\/ Define the orbits\n\tleo := smd.NewOrbitFromOE(7000, 0.001, 30, 80, 40, 0, smd.Earth)\n\n\t\/\/ Define the stations\n\tσρ := 1e-3    \/\/ m , but all measurements in km.\n\tσρDot := 1e-6 \/\/ mm\/s , but all measurements in km\/s.\n\tst1 := NewStation(\"st1\", 0, -35.398333, 148.981944, σρ, σρDot)\n\tst2 := NewStation(\"st2\", 0, 40.427222, 355.749444, σρ, σρDot)\n\tst3 := NewStation(\"st3\", 0, 35.247164, 243.205, σρ, σρDot)\n\tstations := []Station{st1, st2, st3}\n\n\t\/\/ Vector of measurements\n\tmeasurements := []Measurement{}\n\n\t\/\/ Define the special export functions\n\texport := smd.ExportConfig{Filename: \"LEO\", Cosmo: false, AsCSV: true, Timestamp: false}\n\texport.CSVAppendHdr = func() string {\n\t\thdr := \"secondsSinceEpoch,\"\n\t\tfor _, st := range stations {\n\t\t\thdr += fmt.Sprintf(\"%sRange,%sRangeRate,%sNoisyRange,%sNoisyRangeRate,\", st.name, st.name, st.name, st.name)\n\t\t}\n\t\treturn hdr[:len(hdr)-1] \/\/ Remove trailing comma\n\t}\n\texport.CSVAppend = func(state smd.MissionState) string {\n\t\tΔt := state.DT.Sub(startDT).Seconds()\n\t\tstr := fmt.Sprintf(\"%f,\", Δt)\n\t\tθgst := Δt * smd.EarthRotationRate\n\t\t\/\/ Compute visibility for each station.\n\t\tfor _, st := range stations {\n\t\t\t_, measurement := st.PerformMeasurement(θgst, state)\n\t\t\tif measurement.Visible {\n\t\t\t\tmeasurements = append(measurements, measurement)\n\t\t\t\tstr += measurement.CSV()\n\t\t\t} else {\n\t\t\t\tstr += \",,,,\"\n\t\t\t}\n\t\t}\n\t\treturn str[:len(str)-1] \/\/ Remove trailing comma\n\t}\n\n\t\/\/ Generate the perturbed orbit\n\tscName := \"LEO\"\n\tsmd.NewPreciseMission(smd.NewEmptySC(scName, 0), leo, startDT, endDT, smd.Cartesian, smd.Perturbations{Jn: 3}, 2*time.Second, export).Propagate()\n\n\t\/\/ Take care of the measurements:\n\tfmt.Printf(\"\\n[INFO] Generated %d measurements\\n\", len(measurements))\n\t\/\/ Let's mark those as the truth so we can plot that.\n\tstateTruth := make([]*mat64.Vector, len(measurements))\n\ttruthMeas := make([]*mat64.Vector, len(measurements))\n\tresiduals := make([]*mat64.Vector, len(measurements))\n\tfor measNo, measurement := range measurements {\n\t\torbit := make([]float64, 6)\n\t\tR, V := measurement.State.Orbit.RV()\n\t\tfor i := 0; i < 3; i++ {\n\t\t\torbit[i] = R[i]\n\t\t\torbit[i+3] = V[i]\n\t\t}\n\t\tstateTruth[measNo] = mat64.NewVector(6, orbit)\n\t\ttruthMeas[measNo] = measurement.StateVector()\n\t}\n\ttruth := gokalman.NewBatchGroundTruth(stateTruth, truthMeas)\n\n\t\/\/ Perturbations in the estimate\n\testPerts := smd.Perturbations{Jn: 3}\n\n\t\/\/ Initialize the KF noise\n\tσx := math.Pow(1e-6, 2)\n\tσy := math.Pow(1e-6, 2)\n\tσz := math.Pow(1e-6, 2)\n\tQ := mat64.NewSymDense(3, []float64{σx, 0, 0, 0, σy, 0, 0, 0, σz})\n\tR := mat64.NewSymDense(2, []float64{σρ, 0, 0, σρDot})\n\tnoiseKF := gokalman.NewNoiseless(Q, R)\n\n\t\/\/ Take care of measurements.\n\testChan := make(chan (gokalman.Estimate), 1)\n\tgo processEst(\"hybridkf\", estChan)\n\n\tprevXHat := mat64.NewVector(6, nil)\n\tprevP := mat64.NewSymDense(6, nil)\n\tvar covarDistance float64 = 50\n\tvar covarVelocity float64 = 1\n\tfor i := 0; i < 3; i++ {\n\t\tprevP.SetSym(i, i, covarDistance)\n\t\tprevP.SetSym(i+3, i+3, covarVelocity)\n\t}\n\n\tvisibilityErrors := 0\n\tvar orbitEstimate *smd.OrbitEstimate\n\n\tif ekfTrigger < 0 {\n\t\tfmt.Println(\"[WARNING] EKF disabled\")\n\t} else if ekfTrigger < 10 {\n\t\tfmt.Println(\"[WARNING] EKF may be turned on too early\")\n\t} else {\n\t\tfmt.Printf(\"[INFO] EKF will turn on after %d measurements\\n\", ekfTrigger)\n\t}\n\n\tvar kf *gokalman.HybridKF\n\tvar prevStationName = \"\"\n\tvar prevDT time.Time\n\tfor measNo, measurement := range measurements {\n\t\tif !measurement.Visible {\n\t\t\tpanic(\"why is there a non visible measurement?!\")\n\t\t}\n\t\tif measNo == 0 {\n\t\t\tprevDT = measurement.State.DT\n\t\t\torbitEstimate = smd.NewOrbitEstimate(\"estimator\", measurement.State.Orbit, estPerts, measurement.State.DT, time.Second)\n\t\t\tvar err error\n\t\t\tkf, _, err = gokalman.NewHybridKF(prevXHat, prevP, noiseKF, 2)\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Errorf(\"%s\", err))\n\t\t\t}\n\t\t} else if measNo == ekfTrigger {\n\t\t\t\/\/ Switch KF to EKF mode\n\t\t\tkf.EnableEKF()\n\t\t\tfmt.Printf(\"[INFO] #%04d EKF now enabled\\n\", measNo)\n\t\t}\n\t\tif timeBasedPlot {\n\t\t\t\/\/ Propagate and predict for each time step until next measurement.\n\t\t\tfor prevDT.Before(measurement.State.DT) {\n\t\t\t\tnextDT := prevDT.Add(10 * time.Second)\n\t\t\t\torbitEstimate.PropagateUntil(nextDT) \/\/ This leads to Φ(ti+1, ti)\n\t\t\t\t\/\/ Only do a prediction.\n\t\t\t\tkf.Prepare(orbitEstimate.Φ, nil)\n\t\t\t\test, perr := kf.Predict()\n\t\t\t\tif perr != nil {\n\t\t\t\t\tpanic(fmt.Errorf(\"[error] (#%04d)\\n%s\", measNo, perr))\n\t\t\t\t}\n\t\t\t\tstateEst := mat64.NewVector(6, nil)\n\t\t\t\tR, V := orbitEstimate.State().Orbit.RV()\n\t\t\t\tfor i := 0; i < 3; i++ {\n\t\t\t\t\tstateEst.SetVec(i, R[i])\n\t\t\t\t\tstateEst.SetVec(i+3, V[i])\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"%s\\n\\n\", est)\n\t\t\t\t\/\/fmt.Printf(\"%+v\\n\", mat64.Formatted(stateEst.T()))\n\t\t\t\testChan <- truth.ErrorWithOffset(measNo, est, stateEst)\n\t\t\t\tprevDT = nextDT\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tΔtDuration := measurement.State.DT.Sub(prevDT)\n\t\tΔt := ΔtDuration.Seconds() \/\/ Everything is in seconds.\n\t\tif Δt > 60 {\n\t\t\tfmt.Printf(\"[INFO] #%04d occurred %s after #%04d\\n\", measNo, ΔtDuration, measNo-1)\n\t\t}\n\t\t\/\/ Propagate the reference trajectory until the next measurement time.\n\t\torbitEstimate.PropagateUntil(measurement.State.DT) \/\/ This leads to Φ(ti+1, ti)\n\n\t\tif measurement.Station.name != prevStationName {\n\t\t\tfmt.Printf(\"[INFO] #%04d %s in visibility of %s (T+%s)\\n\", measNo, scName, measurement.Station.name, measurement.State.DT.Sub(startDT))\n\t\t\tprevStationName = measurement.Station.name\n\t\t}\n\n\t\t\/\/ Compute \"real\" measurement\n\t\tvis, computedObservation := measurement.Station.PerformMeasurement(measurement.θgst, orbitEstimate.State())\n\t\tif !vis {\n\t\t\tfmt.Printf(\"[WARNING] station %s should see the SC but does not\\n\", measurement.Station.name)\n\t\t\tvisibilityErrors++\n\t\t}\n\t\tHtilde := measurement.HTilde(orbitEstimate.State(), measurement.θgst)\n\t\tkf.Prepare(orbitEstimate.Φ, Htilde)\n\t\tif sncEnabled {\n\t\t\tif Δt < 60*38 {\n\t\t\t\t\/\/ Only enable SNC for small time differences between measurements.\n\t\t\t\tΓtop := gokalman.ScaledDenseIdentity(3, math.Pow(Δt, 2)\/2)\n\t\t\t\tΓbot := gokalman.ScaledDenseIdentity(3, Δt)\n\t\t\t\tΓ := mat64.NewDense(6, 3, nil)\n\t\t\t\tΓ.Stack(Γtop, Γbot)\n\t\t\t\tkf.PreparePNT(Γ)\n\t\t\t}\n\t\t}\n\t\test, err := kf.Update(measurement.StateVector(), computedObservation.StateVector())\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"[error] %s\", err))\n\t\t}\n\t\tprevXHat = est.State()\n\t\tprevP = est.Covariance().(*mat64.SymDense)\n\t\tstateEst := mat64.NewVector(6, nil)\n\t\tR, V := orbitEstimate.State().Orbit.RV()\n\t\tfor i := 0; i < 3; i++ {\n\t\t\tstateEst.SetVec(i, R[i])\n\t\t\tstateEst.SetVec(i+3, V[i])\n\t\t}\n\t\tstateEst.AddVec(stateEst, est.State())\n\t\t\/\/ Compute residual\n\t\tresidual := mat64.NewVector(2, nil)\n\t\tresidual.MulVec(Htilde, est.State())\n\t\tresidual.AddScaledVec(residual, -1, est.ObservationDev())\n\t\tresidual.ScaleVec(-1, residual)\n\t\tresiduals[measNo] = residual\n\n\t\t\/\/ Stream to CSV file\n\t\testChan <- truth.ErrorWithOffset(measNo, est, stateEst)\n\t\tprevDT = measurement.State.DT\n\n\t\t\/\/ If in EKF, update the reference trajectory.\n\t\tif kf.EKFEnabled() {\n\t\t\t\/\/ Update the state from the error.\n\t\t\tstate := est.State()\n\t\t\tR, V := orbitEstimate.Orbit.RV()\n\t\t\tfor i := 0; i < 3; i++ {\n\t\t\t\tR[i] += state.At(i, 0)\n\t\t\t\tV[i] += state.At(i+3, 0)\n\t\t\t}\n\t\t\torbitEstimate = smd.NewOrbitEstimate(\"estimator\", *smd.NewOrbitFromRV(R, V, smd.Earth), estPerts, measurement.State.DT, time.Second)\n\t\t}\n\n\t}\n\tclose(estChan)\n\twg.Wait()\n\n\tseverity := \"INFO\"\n\tif visibilityErrors > 0 {\n\t\tseverity = \"WARNING\"\n\t}\n\tfmt.Printf(\"[%s] %d visibility errors\\n\", severity, visibilityErrors)\n\t\/\/ Write the residuals to a CSV file\n\tfname := \"hkf\"\n\tf, err := os.Create(fmt.Sprintf(\".\/%s-residuals.csv\", fname))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\tf.WriteString(\"rho,rhoDot\\n\")\n\tfor _, residual := range residuals {\n\t\tcsv := fmt.Sprintf(\"%f,%f\\n\", residual.At(0, 0), residual.At(1, 0))\n\t\tif _, err := f.WriteString(csv); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\nfunc processEst(fn string, estChan chan (gokalman.Estimate)) {\n\twg.Add(1)\n\tce, _ := gokalman.NewCustomCSVExporter([]string{\"x\", \"y\", \"z\", \"xDot\", \"yDot\", \"zDot\"}, \".\", fn+\".csv\", 3)\n\tfor {\n\t\test, more := <-estChan\n\t\tif !more {\n\t\t\tce.Close()\n\t\t\twg.Done()\n\t\t\tbreak\n\t\t}\n\t\tce.Write(est)\n\t}\n}\n<commit_msg>All Q elements are now from one variable<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/ChristopherRabotin\/gokalman\"\n\t\"github.com\/ChristopherRabotin\/smd\"\n\t\"github.com\/gonum\/matrix\/mat64\"\n)\n\nconst (\n\tekfTrigger    = 15    \/\/ Number of measurements prior to switching to EKF mode.\n\tsncEnabled    = true  \/\/ Set to false to disable SNC.\n\ttimeBasedPlot = false \/\/ Set to true to plot time, or false to plot on measurements.\n)\n\nvar (\n\twg sync.WaitGroup\n)\n\nfunc main() {\n\t\/\/ Define the times\n\tstartDT := time.Now()\n\tendDT := startDT.Add(time.Duration(24) * time.Hour)\n\t\/\/ Define the orbits\n\tleo := smd.NewOrbitFromOE(7000, 0.001, 30, 80, 40, 0, smd.Earth)\n\n\t\/\/ Define the stations\n\tσρ := 1e-3    \/\/ m , but all measurements in km.\n\tσρDot := 1e-6 \/\/ mm\/s , but all measurements in km\/s.\n\tst1 := NewStation(\"st1\", 0, -35.398333, 148.981944, σρ, σρDot)\n\tst2 := NewStation(\"st2\", 0, 40.427222, 355.749444, σρ, σρDot)\n\tst3 := NewStation(\"st3\", 0, 35.247164, 243.205, σρ, σρDot)\n\tstations := []Station{st1, st2, st3}\n\n\t\/\/ Vector of measurements\n\tmeasurements := []Measurement{}\n\n\t\/\/ Define the special export functions\n\texport := smd.ExportConfig{Filename: \"LEO\", Cosmo: false, AsCSV: true, Timestamp: false}\n\texport.CSVAppendHdr = func() string {\n\t\thdr := \"secondsSinceEpoch,\"\n\t\tfor _, st := range stations {\n\t\t\thdr += fmt.Sprintf(\"%sRange,%sRangeRate,%sNoisyRange,%sNoisyRangeRate,\", st.name, st.name, st.name, st.name)\n\t\t}\n\t\treturn hdr[:len(hdr)-1] \/\/ Remove trailing comma\n\t}\n\texport.CSVAppend = func(state smd.MissionState) string {\n\t\tΔt := state.DT.Sub(startDT).Seconds()\n\t\tstr := fmt.Sprintf(\"%f,\", Δt)\n\t\tθgst := Δt * smd.EarthRotationRate\n\t\t\/\/ Compute visibility for each station.\n\t\tfor _, st := range stations {\n\t\t\t_, measurement := st.PerformMeasurement(θgst, state)\n\t\t\tif measurement.Visible {\n\t\t\t\tmeasurements = append(measurements, measurement)\n\t\t\t\tstr += measurement.CSV()\n\t\t\t} else {\n\t\t\t\tstr += \",,,,\"\n\t\t\t}\n\t\t}\n\t\treturn str[:len(str)-1] \/\/ Remove trailing comma\n\t}\n\n\t\/\/ Generate the perturbed orbit\n\tscName := \"LEO\"\n\tsmd.NewPreciseMission(smd.NewEmptySC(scName, 0), leo, startDT, endDT, smd.Cartesian, smd.Perturbations{Jn: 3}, 2*time.Second, export).Propagate()\n\n\t\/\/ Take care of the measurements:\n\tfmt.Printf(\"\\n[INFO] Generated %d measurements\\n\", len(measurements))\n\t\/\/ Let's mark those as the truth so we can plot that.\n\tstateTruth := make([]*mat64.Vector, len(measurements))\n\ttruthMeas := make([]*mat64.Vector, len(measurements))\n\tresiduals := make([]*mat64.Vector, len(measurements))\n\tfor measNo, measurement := range measurements {\n\t\torbit := make([]float64, 6)\n\t\tR, V := measurement.State.Orbit.RV()\n\t\tfor i := 0; i < 3; i++ {\n\t\t\torbit[i] = R[i]\n\t\t\torbit[i+3] = V[i]\n\t\t}\n\t\tstateTruth[measNo] = mat64.NewVector(6, orbit)\n\t\ttruthMeas[measNo] = measurement.StateVector()\n\t}\n\ttruth := gokalman.NewBatchGroundTruth(stateTruth, truthMeas)\n\n\t\/\/ Perturbations in the estimate\n\testPerts := smd.Perturbations{Jn: 3}\n\n\t\/\/ Initialize the KF noise\n\tσQ := math.Pow(1e-6, 2)\n\tQ := mat64.NewSymDense(3, []float64{σQ, 0, 0, 0, σQ, 0, 0, 0, σQ})\n\tR := mat64.NewSymDense(2, []float64{σρ, 0, 0, σρDot})\n\tnoiseKF := gokalman.NewNoiseless(Q, R)\n\n\t\/\/ Take care of measurements.\n\testChan := make(chan (gokalman.Estimate), 1)\n\tgo processEst(\"hybridkf\", estChan)\n\n\tprevXHat := mat64.NewVector(6, nil)\n\tprevP := mat64.NewSymDense(6, nil)\n\tvar covarDistance float64 = 50\n\tvar covarVelocity float64 = 1\n\tfor i := 0; i < 3; i++ {\n\t\tprevP.SetSym(i, i, covarDistance)\n\t\tprevP.SetSym(i+3, i+3, covarVelocity)\n\t}\n\n\tvisibilityErrors := 0\n\tvar orbitEstimate *smd.OrbitEstimate\n\n\tif ekfTrigger < 0 {\n\t\tfmt.Println(\"[WARNING] EKF disabled\")\n\t} else if ekfTrigger < 10 {\n\t\tfmt.Println(\"[WARNING] EKF may be turned on too early\")\n\t} else {\n\t\tfmt.Printf(\"[INFO] EKF will turn on after %d measurements\\n\", ekfTrigger)\n\t}\n\n\tvar kf *gokalman.HybridKF\n\tvar prevStationName = \"\"\n\tvar prevDT time.Time\n\tfor measNo, measurement := range measurements {\n\t\tif !measurement.Visible {\n\t\t\tpanic(\"why is there a non visible measurement?!\")\n\t\t}\n\t\tif measNo == 0 {\n\t\t\tprevDT = measurement.State.DT\n\t\t\torbitEstimate = smd.NewOrbitEstimate(\"estimator\", measurement.State.Orbit, estPerts, measurement.State.DT, time.Second)\n\t\t\tvar err error\n\t\t\tkf, _, err = gokalman.NewHybridKF(prevXHat, prevP, noiseKF, 2)\n\t\t\tif err != nil {\n\t\t\t\tpanic(fmt.Errorf(\"%s\", err))\n\t\t\t}\n\t\t} else if measNo == ekfTrigger {\n\t\t\t\/\/ Switch KF to EKF mode\n\t\t\tkf.EnableEKF()\n\t\t\tfmt.Printf(\"[INFO] #%04d EKF now enabled\\n\", measNo)\n\t\t}\n\t\tif timeBasedPlot {\n\t\t\t\/\/ Propagate and predict for each time step until next measurement.\n\t\t\tfor prevDT.Before(measurement.State.DT) {\n\t\t\t\tnextDT := prevDT.Add(10 * time.Second)\n\t\t\t\torbitEstimate.PropagateUntil(nextDT) \/\/ This leads to Φ(ti+1, ti)\n\t\t\t\t\/\/ Only do a prediction.\n\t\t\t\tkf.Prepare(orbitEstimate.Φ, nil)\n\t\t\t\test, perr := kf.Predict()\n\t\t\t\tif perr != nil {\n\t\t\t\t\tpanic(fmt.Errorf(\"[error] (#%04d)\\n%s\", measNo, perr))\n\t\t\t\t}\n\t\t\t\tstateEst := mat64.NewVector(6, nil)\n\t\t\t\tR, V := orbitEstimate.State().Orbit.RV()\n\t\t\t\tfor i := 0; i < 3; i++ {\n\t\t\t\t\tstateEst.SetVec(i, R[i])\n\t\t\t\t\tstateEst.SetVec(i+3, V[i])\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"%s\\n\\n\", est)\n\t\t\t\t\/\/fmt.Printf(\"%+v\\n\", mat64.Formatted(stateEst.T()))\n\t\t\t\testChan <- truth.ErrorWithOffset(measNo, est, stateEst)\n\t\t\t\tprevDT = nextDT\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tΔtDuration := measurement.State.DT.Sub(prevDT)\n\t\tΔt := ΔtDuration.Seconds() \/\/ Everything is in seconds.\n\t\tif Δt > 60 {\n\t\t\tfmt.Printf(\"[INFO] #%04d occurred %s after #%04d\\n\", measNo, ΔtDuration, measNo-1)\n\t\t}\n\t\t\/\/ Propagate the reference trajectory until the next measurement time.\n\t\torbitEstimate.PropagateUntil(measurement.State.DT) \/\/ This leads to Φ(ti+1, ti)\n\n\t\tif measurement.Station.name != prevStationName {\n\t\t\tfmt.Printf(\"[INFO] #%04d %s in visibility of %s (T+%s)\\n\", measNo, scName, measurement.Station.name, measurement.State.DT.Sub(startDT))\n\t\t\tprevStationName = measurement.Station.name\n\t\t}\n\n\t\t\/\/ Compute \"real\" measurement\n\t\tvis, computedObservation := measurement.Station.PerformMeasurement(measurement.θgst, orbitEstimate.State())\n\t\tif !vis {\n\t\t\tfmt.Printf(\"[WARNING] station %s should see the SC but does not\\n\", measurement.Station.name)\n\t\t\tvisibilityErrors++\n\t\t}\n\t\tHtilde := measurement.HTilde(orbitEstimate.State(), measurement.θgst)\n\t\tkf.Prepare(orbitEstimate.Φ, Htilde)\n\t\tif sncEnabled {\n\t\t\tif Δt < 60*38 {\n\t\t\t\t\/\/ Only enable SNC for small time differences between measurements.\n\t\t\t\tΓtop := gokalman.ScaledDenseIdentity(3, math.Pow(Δt, 2)\/2)\n\t\t\t\tΓbot := gokalman.ScaledDenseIdentity(3, Δt)\n\t\t\t\tΓ := mat64.NewDense(6, 3, nil)\n\t\t\t\tΓ.Stack(Γtop, Γbot)\n\t\t\t\tkf.PreparePNT(Γ)\n\t\t\t}\n\t\t}\n\t\test, err := kf.Update(measurement.StateVector(), computedObservation.StateVector())\n\t\tif err != nil {\n\t\t\tpanic(fmt.Errorf(\"[error] %s\", err))\n\t\t}\n\t\tprevXHat = est.State()\n\t\tprevP = est.Covariance().(*mat64.SymDense)\n\t\tstateEst := mat64.NewVector(6, nil)\n\t\tR, V := orbitEstimate.State().Orbit.RV()\n\t\tfor i := 0; i < 3; i++ {\n\t\t\tstateEst.SetVec(i, R[i])\n\t\t\tstateEst.SetVec(i+3, V[i])\n\t\t}\n\t\tstateEst.AddVec(stateEst, est.State())\n\t\t\/\/ Compute residual\n\t\tresidual := mat64.NewVector(2, nil)\n\t\tresidual.MulVec(Htilde, est.State())\n\t\tresidual.AddScaledVec(residual, -1, est.ObservationDev())\n\t\tresidual.ScaleVec(-1, residual)\n\t\tresiduals[measNo] = residual\n\n\t\t\/\/ Stream to CSV file\n\t\testChan <- truth.ErrorWithOffset(measNo, est, stateEst)\n\t\tprevDT = measurement.State.DT\n\n\t\t\/\/ If in EKF, update the reference trajectory.\n\t\tif kf.EKFEnabled() {\n\t\t\t\/\/ Update the state from the error.\n\t\t\tstate := est.State()\n\t\t\tR, V := orbitEstimate.Orbit.RV()\n\t\t\tfor i := 0; i < 3; i++ {\n\t\t\t\tR[i] += state.At(i, 0)\n\t\t\t\tV[i] += state.At(i+3, 0)\n\t\t\t}\n\t\t\torbitEstimate = smd.NewOrbitEstimate(\"estimator\", *smd.NewOrbitFromRV(R, V, smd.Earth), estPerts, measurement.State.DT, time.Second)\n\t\t}\n\n\t}\n\tclose(estChan)\n\twg.Wait()\n\n\tseverity := \"INFO\"\n\tif visibilityErrors > 0 {\n\t\tseverity = \"WARNING\"\n\t}\n\tfmt.Printf(\"[%s] %d visibility errors\\n\", severity, visibilityErrors)\n\t\/\/ Write the residuals to a CSV file\n\tfname := \"hkf\"\n\tf, err := os.Create(fmt.Sprintf(\".\/%s-residuals.csv\", fname))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer f.Close()\n\tf.WriteString(\"rho,rhoDot\\n\")\n\tfor _, residual := range residuals {\n\t\tcsv := fmt.Sprintf(\"%f,%f\\n\", residual.At(0, 0), residual.At(1, 0))\n\t\tif _, err := f.WriteString(csv); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\nfunc processEst(fn string, estChan chan (gokalman.Estimate)) {\n\twg.Add(1)\n\tce, _ := gokalman.NewCustomCSVExporter([]string{\"x\", \"y\", \"z\", \"xDot\", \"yDot\", \"zDot\"}, \".\", fn+\".csv\", 3)\n\tfor {\n\t\test, more := <-estChan\n\t\tif !more {\n\t\t\tce.Close()\n\t\t\twg.Done()\n\t\t\tbreak\n\t\t}\n\t\tce.Write(est)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package tictactoe\n\nimport (\n\t\"errors\"\n\t\"github.com\/jkomoros\/boardgame\"\n)\n\ntype MovePlaceToken struct {\n\t\/\/Which token to place the token\n\tSlot int\n\t\/\/Which player we THINK is making the move.\n\tTargetPlayerIndex int\n}\n\nfunc (m *MovePlaceToken) Legal(payload boardgame.StatePayload) error {\n\tp := payload.(*statePayload)\n\n\tif p.game.CurrentPlayer != m.TargetPlayerIndex {\n\t\treturn errors.New(\"The specified player is not the current player.\")\n\t}\n\n\tif p.users[m.TargetPlayerIndex].UnusedTokens.Len() < 1 {\n\t\treturn errors.New(\"There aren't any remaining tokens for the current player to place.\")\n\t}\n\n\tif p.game.Slots.ComponentAt(m.Slot) != nil {\n\t\treturn errors.New(\"The specified slot is already taken.\")\n\t}\n\n\treturn nil\n\n}\n\nfunc (m *MovePlaceToken) Apply(payload boardgame.StatePayload) boardgame.StatePayload {\n\n\tresult := payload.Copy()\n\n\tp := result.(*statePayload)\n\n\tc := p.users[m.TargetPlayerIndex].UnusedTokens.RemoveFirst()\n\n\tp.game.Slots.InsertAtSlot(c, m.Slot)\n\n\treturn result\n\n}\n\nfunc (m *MovePlaceToken) Name() string {\n\treturn \"Place Token\"\n}\n\nfunc (m *MovePlaceToken) Description() string {\n\treturn \"Place a player's token in a specific space.\"\n}\n\nfunc (m *MovePlaceToken) Copy() boardgame.Move {\n\tvar result MovePlaceToken\n\tresult = *m\n\treturn &result\n}\n\nfunc (m *MovePlaceToken) Props() []string {\n\treturn boardgame.PropertyReaderPropsImpl(m)\n}\n\nfunc (m *MovePlaceToken) Prop(name string) interface{} {\n\treturn boardgame.PropertyReaderPropImpl(m, name)\n}\n\nfunc (m *MovePlaceToken) SetProp(name string, val interface{}) error {\n\treturn boardgame.PropertySetImpl(m, name, val)\n}\n\nfunc (m *MovePlaceToken) JSON() boardgame.JSONObject {\n\treturn m\n}\n\ntype MoveAdvancePlayer struct{}\n\nfunc (m *MoveAdvancePlayer) Legal(payload boardgame.StatePayload) error {\n\tp := payload.(*statePayload)\n\n\tuser := p.users[p.game.CurrentPlayer]\n\n\tif user.TokensToPlaceThisTurn > 0 {\n\t\treturn errors.New(\"The current player still has tokens left to place this turn.\")\n\t}\n\n\treturn nil\n}\n\nfunc (m *MoveAdvancePlayer) Apply(payload boardgame.StatePayload) boardgame.StatePayload {\n\tresult := payload.Copy()\n\n\tp := result.(*statePayload)\n\n\tp.game.CurrentPlayer++\n\n\tif p.game.CurrentPlayer >= len(p.users) {\n\t\tp.game.CurrentPlayer = 0\n\t}\n\n\tnewUser := p.users[p.game.CurrentPlayer]\n\n\tnewUser.TokensToPlaceThisTurn = 1\n\n\treturn result\n\n}\n\nfunc (m *MoveAdvancePlayer) Name() string {\n\treturn \"Advance Player\"\n}\n\nfunc (m *MoveAdvancePlayer) Description() string {\n\treturn \"After the current player has made all of their moves, this fix-up move advances to the next player.\"\n}\n\nfunc (m *MoveAdvancePlayer) Copy() boardgame.Move {\n\tvar result MoveAdvancePlayer\n\tresult = *m\n\treturn &result\n}\n\nfunc (m *MoveAdvancePlayer) JSON() boardgame.JSONObject {\n\treturn m\n}\n\nfunc (m *MoveAdvancePlayer) Prop(name string) interface{} {\n\treturn boardgame.PropertyReaderPropImpl(m, name)\n}\n\nfunc (m *MoveAdvancePlayer) Props() []string {\n\treturn boardgame.PropertyReaderPropsImpl(m)\n}\n\nfunc (m *MoveAdvancePlayer) SetProp(name string, val interface{}) error {\n\treturn boardgame.PropertySetImpl(m, name, val)\n}\n<commit_msg>Placing a token decrements the MovesLeftThisTurn count. Still doesn't advance to next player because no ProposeFixUp exists. Part of #14.<commit_after>package tictactoe\n\nimport (\n\t\"errors\"\n\t\"github.com\/jkomoros\/boardgame\"\n)\n\ntype MovePlaceToken struct {\n\t\/\/Which token to place the token\n\tSlot int\n\t\/\/Which player we THINK is making the move.\n\tTargetPlayerIndex int\n}\n\nfunc (m *MovePlaceToken) Legal(payload boardgame.StatePayload) error {\n\tp := payload.(*statePayload)\n\n\tif p.game.CurrentPlayer != m.TargetPlayerIndex {\n\t\treturn errors.New(\"The specified player is not the current player.\")\n\t}\n\n\tif p.users[m.TargetPlayerIndex].UnusedTokens.Len() < 1 {\n\t\treturn errors.New(\"There aren't any remaining tokens for the current player to place.\")\n\t}\n\n\tif p.game.Slots.ComponentAt(m.Slot) != nil {\n\t\treturn errors.New(\"The specified slot is already taken.\")\n\t}\n\n\treturn nil\n\n}\n\nfunc (m *MovePlaceToken) Apply(payload boardgame.StatePayload) boardgame.StatePayload {\n\n\tresult := payload.Copy()\n\n\tp := result.(*statePayload)\n\n\tu := p.users[m.TargetPlayerIndex]\n\n\tc := u.UnusedTokens.RemoveFirst()\n\n\tp.game.Slots.InsertAtSlot(c, m.Slot)\n\n\tu.TokensToPlaceThisTurn--\n\n\treturn result\n\n}\n\nfunc (m *MovePlaceToken) Name() string {\n\treturn \"Place Token\"\n}\n\nfunc (m *MovePlaceToken) Description() string {\n\treturn \"Place a player's token in a specific space.\"\n}\n\nfunc (m *MovePlaceToken) Copy() boardgame.Move {\n\tvar result MovePlaceToken\n\tresult = *m\n\treturn &result\n}\n\nfunc (m *MovePlaceToken) Props() []string {\n\treturn boardgame.PropertyReaderPropsImpl(m)\n}\n\nfunc (m *MovePlaceToken) Prop(name string) interface{} {\n\treturn boardgame.PropertyReaderPropImpl(m, name)\n}\n\nfunc (m *MovePlaceToken) SetProp(name string, val interface{}) error {\n\treturn boardgame.PropertySetImpl(m, name, val)\n}\n\nfunc (m *MovePlaceToken) JSON() boardgame.JSONObject {\n\treturn m\n}\n\ntype MoveAdvancePlayer struct{}\n\nfunc (m *MoveAdvancePlayer) Legal(payload boardgame.StatePayload) error {\n\tp := payload.(*statePayload)\n\n\tuser := p.users[p.game.CurrentPlayer]\n\n\tif user.TokensToPlaceThisTurn > 0 {\n\t\treturn errors.New(\"The current player still has tokens left to place this turn.\")\n\t}\n\n\treturn nil\n}\n\nfunc (m *MoveAdvancePlayer) Apply(payload boardgame.StatePayload) boardgame.StatePayload {\n\tresult := payload.Copy()\n\n\tp := result.(*statePayload)\n\n\tp.game.CurrentPlayer++\n\n\tif p.game.CurrentPlayer >= len(p.users) {\n\t\tp.game.CurrentPlayer = 0\n\t}\n\n\tnewUser := p.users[p.game.CurrentPlayer]\n\n\tnewUser.TokensToPlaceThisTurn = 1\n\n\treturn result\n\n}\n\nfunc (m *MoveAdvancePlayer) Name() string {\n\treturn \"Advance Player\"\n}\n\nfunc (m *MoveAdvancePlayer) Description() string {\n\treturn \"After the current player has made all of their moves, this fix-up move advances to the next player.\"\n}\n\nfunc (m *MoveAdvancePlayer) Copy() boardgame.Move {\n\tvar result MoveAdvancePlayer\n\tresult = *m\n\treturn &result\n}\n\nfunc (m *MoveAdvancePlayer) JSON() boardgame.JSONObject {\n\treturn m\n}\n\nfunc (m *MoveAdvancePlayer) Prop(name string) interface{} {\n\treturn boardgame.PropertyReaderPropImpl(m, name)\n}\n\nfunc (m *MoveAdvancePlayer) Props() []string {\n\treturn boardgame.PropertyReaderPropsImpl(m)\n}\n\nfunc (m *MoveAdvancePlayer) SetProp(name string, val interface{}) error {\n\treturn boardgame.PropertySetImpl(m, name, val)\n}\n<|endoftext|>"}
{"text":"<commit_before>package command\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"gotest.tools\/v3\/assert\"\n)\n\nfunc contentTrustEnabled(t *testing.T) bool {\n\tvar cli DockerCli\n\tassert.NilError(t, WithContentTrustFromEnv()(&cli))\n\treturn cli.contentTrust\n}\n\n\/\/ NB: Do not t.Parallel() this test -- it messes with the process environment.\nfunc TestWithContentTrustFromEnv(t *testing.T) {\n\tenvvar := \"DOCKER_CONTENT_TRUST\"\n\tif orig, ok := os.LookupEnv(envvar); ok {\n\t\tdefer func() {\n\t\t\tos.Setenv(envvar, orig)\n\t\t}()\n\t} else {\n\t\tdefer func() {\n\t\t\tos.Unsetenv(envvar)\n\t\t}()\n\t}\n\n\tos.Setenv(envvar, \"true\")\n\tassert.Assert(t, contentTrustEnabled(t))\n\tos.Setenv(envvar, \"false\")\n\tassert.Assert(t, !contentTrustEnabled(t))\n\tos.Setenv(envvar, \"invalid\")\n\tassert.Assert(t, contentTrustEnabled(t))\n\tos.Unsetenv(envvar)\n\tassert.Assert(t, !contentTrustEnabled(t))\n}\n<commit_msg>linting: os.Setenv() can be replaced by `t.Setenv()` (tenv)<commit_after>package command\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"gotest.tools\/v3\/assert\"\n)\n\nfunc contentTrustEnabled(t *testing.T) bool {\n\tvar cli DockerCli\n\tassert.NilError(t, WithContentTrustFromEnv()(&cli))\n\treturn cli.contentTrust\n}\n\n\/\/ NB: Do not t.Parallel() this test -- it messes with the process environment.\nfunc TestWithContentTrustFromEnv(t *testing.T) {\n\tconst envvar = \"DOCKER_CONTENT_TRUST\"\n\tt.Setenv(envvar, \"true\")\n\tassert.Check(t, contentTrustEnabled(t))\n\tt.Setenv(envvar, \"false\")\n\tassert.Check(t, !contentTrustEnabled(t))\n\tt.Setenv(envvar, \"invalid\")\n\tassert.Check(t, contentTrustEnabled(t))\n\tos.Unsetenv(envvar)\n\tassert.Check(t, !contentTrustEnabled(t))\n}\n<|endoftext|>"}
{"text":"<commit_before>package image\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"sort\"\n\t\"syscall\"\n\t\"testing\"\n\n\t\"github.com\/docker\/cli\/cli\/command\"\n\t\"github.com\/docker\/cli\/internal\/test\"\n\t\"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/pkg\/archive\"\n\t\"github.com\/gotestyourself\/gotestyourself\/assert\"\n\tis \"github.com\/gotestyourself\/gotestyourself\/assert\/cmp\"\n\t\"github.com\/gotestyourself\/gotestyourself\/fs\"\n\t\"github.com\/gotestyourself\/gotestyourself\/skip\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nfunc TestRunBuildResetsUidAndGidInContext(t *testing.T) {\n\tskip.IfCondition(t, runtime.GOOS == \"windows\", \"uid and gid not relevant on windows\")\n\tdest := fs.NewDir(t, \"test-build-context-dest\")\n\tdefer dest.Remove()\n\n\tfakeImageBuild := func(_ context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) {\n\t\tassert.Check(t, archive.Untar(context, dest.Path(), nil))\n\n\t\tbody := new(bytes.Buffer)\n\t\treturn types.ImageBuildResponse{Body: ioutil.NopCloser(body)}, nil\n\t}\n\tcli := test.NewFakeCli(&fakeClient{imageBuildFunc: fakeImageBuild})\n\n\tdir := fs.NewDir(t, \"test-build-context\",\n\t\tfs.WithFile(\"foo\", \"some content\", fs.AsUser(65534, 65534)),\n\t\tfs.WithFile(\"Dockerfile\", `\n\t\t\tFROM alpine:3.6\n\t\t\tCOPY foo bar \/\n\t\t`),\n\t)\n\tdefer dir.Remove()\n\n\toptions := newBuildOptions()\n\toptions.context = dir.Path()\n\n\terr := runBuild(cli, options)\n\tassert.NilError(t, err)\n\n\tfiles, err := ioutil.ReadDir(dest.Path())\n\tassert.NilError(t, err)\n\tfor _, fileInfo := range files {\n\t\tassert.Check(t, is.Equal(uint32(0), fileInfo.Sys().(*syscall.Stat_t).Uid))\n\t\tassert.Check(t, is.Equal(uint32(0), fileInfo.Sys().(*syscall.Stat_t).Gid))\n\t}\n}\nfunc TestRunBuildDockerfileFromStdinWithCompress(t *testing.T) {\n\tdest, err := ioutil.TempDir(\"\", \"test-build-compress-dest\")\n\tassert.NilError(t, err)\n\tdefer os.RemoveAll(dest)\n\n\tvar dockerfileName string\n\tfakeImageBuild := func(_ context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) {\n\t\tbuffer := new(bytes.Buffer)\n\t\ttee := io.TeeReader(context, buffer)\n\n\t\tassert.Check(t, archive.Untar(tee, dest, nil))\n\t\tdockerfileName = options.Dockerfile\n\n\t\theader := buffer.Bytes()[:10]\n\t\tassert.Check(t, is.Equal(archive.Gzip, archive.DetectCompression(header)))\n\n\t\tbody := new(bytes.Buffer)\n\t\treturn types.ImageBuildResponse{Body: ioutil.NopCloser(body)}, nil\n\t}\n\n\tcli := test.NewFakeCli(&fakeClient{imageBuildFunc: fakeImageBuild})\n\tdockerfile := bytes.NewBufferString(`\n\t\tFROM alpine:3.6\n\t\tCOPY foo \/\n\t`)\n\tcli.SetIn(command.NewInStream(ioutil.NopCloser(dockerfile)))\n\n\tdir, err := ioutil.TempDir(\"\", \"test-build-compress\")\n\tassert.NilError(t, err)\n\tdefer os.RemoveAll(dir)\n\n\tioutil.WriteFile(filepath.Join(dir, \"foo\"), []byte(\"some content\"), 0644)\n\n\toptions := newBuildOptions()\n\toptions.compress = true\n\toptions.dockerfileName = \"-\"\n\toptions.context = dir\n\n\terr = runBuild(cli, options)\n\tassert.NilError(t, err)\n\n\tfiles, err := ioutil.ReadDir(dest)\n\tassert.NilError(t, err)\n\tactual := []string{}\n\tfor _, fileInfo := range files {\n\t\tactual = append(actual, fileInfo.Name())\n\t}\n\tsort.Strings(actual)\n\tassert.Check(t, is.DeepEqual([]string{dockerfileName, \".dockerignore\", \"foo\"}, actual))\n}\n\nfunc TestRunBuildDockerfileOutsideContext(t *testing.T) {\n\tdir := fs.NewDir(t, t.Name(),\n\t\tfs.WithFile(\"data\", \"data file\"),\n\t)\n\tdefer dir.Remove()\n\n\t\/\/ Dockerfile outside of build-context\n\tdf := fs.NewFile(t, t.Name(),\n\t\tfs.WithContent(`\nFROM FOOBAR\nCOPY data \/data\n\t\t`),\n\t)\n\tdefer df.Remove()\n\n\tdest, err := ioutil.TempDir(\"\", t.Name())\n\tassert.NilError(t, err)\n\tdefer os.RemoveAll(dest)\n\n\tvar dockerfileName string\n\tfakeImageBuild := func(_ context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) {\n\t\tbuffer := new(bytes.Buffer)\n\t\ttee := io.TeeReader(context, buffer)\n\n\t\tassert.Check(t, archive.Untar(tee, dest, nil))\n\t\tdockerfileName = options.Dockerfile\n\n\t\tbody := new(bytes.Buffer)\n\t\treturn types.ImageBuildResponse{Body: ioutil.NopCloser(body)}, nil\n\t}\n\n\tcli := test.NewFakeCli(&fakeClient{imageBuildFunc: fakeImageBuild})\n\n\toptions := newBuildOptions()\n\toptions.context = dir.Path()\n\toptions.dockerfileName = df.Path()\n\n\terr = runBuild(cli, options)\n\tassert.NilError(t, err)\n\n\tfiles, err := ioutil.ReadDir(dest)\n\tassert.NilError(t, err)\n\tvar actual []string\n\tfor _, fileInfo := range files {\n\t\tactual = append(actual, fileInfo.Name())\n\t}\n\tsort.Strings(actual)\n\tassert.Check(t, is.DeepEqual([]string{dockerfileName, \".dockerignore\", \"data\"}, actual))\n}\n\n\/\/ TestRunBuildFromLocalGitHubDirNonExistingRepo tests that build contexts\n\/\/ starting with `github.com\/` are special-cased, and the build command attempts\n\/\/ to clone the remote repo.\nfunc TestRunBuildFromGitHubSpecialCase(t *testing.T) {\n\tcmd := NewBuildCommand(test.NewFakeCli(nil))\n\tcmd.SetArgs([]string{\"github.com\/docker\/no-such-repository\"})\n\tcmd.SetOutput(ioutil.Discard)\n\terr := cmd.Execute()\n\tassert.ErrorContains(t, err, \"unable to prepare context: unable to 'git clone'\")\n}\n\n\/\/ TestRunBuildFromLocalGitHubDirNonExistingRepo tests that a local directory\n\/\/ starting with `github.com` takes precedence over the `github.com` special\n\/\/ case.\nfunc TestRunBuildFromLocalGitHubDir(t *testing.T) {\n\ttmpDir, err := ioutil.TempDir(\"\", \"docker-build-from-local-dir-\")\n\tassert.NilError(t, err)\n\tdefer os.RemoveAll(tmpDir)\n\n\tbuildDir := filepath.Join(tmpDir, \"github.com\", \"docker\", \"no-such-repository\")\n\terr = os.MkdirAll(buildDir, 0777)\n\tassert.NilError(t, err)\n\terr = ioutil.WriteFile(filepath.Join(buildDir, \"Dockerfile\"), []byte(\"FROM busybox\\n\"), 0644)\n\tassert.NilError(t, err)\n\n\tclient := test.NewFakeCli(&fakeClient{})\n\tcmd := NewBuildCommand(client)\n\tcmd.SetArgs([]string{buildDir})\n\tcmd.SetOutput(ioutil.Discard)\n\terr = cmd.Execute()\n\tassert.NilError(t, err)\n}\n<commit_msg>dont prompt for github creds in unit test<commit_after>package image\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"sort\"\n\t\"syscall\"\n\t\"testing\"\n\n\t\"github.com\/docker\/cli\/cli\/command\"\n\t\"github.com\/docker\/cli\/internal\/test\"\n\t\"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/pkg\/archive\"\n\t\"github.com\/gotestyourself\/gotestyourself\/assert\"\n\tis \"github.com\/gotestyourself\/gotestyourself\/assert\/cmp\"\n\t\"github.com\/gotestyourself\/gotestyourself\/fs\"\n\t\"github.com\/gotestyourself\/gotestyourself\/skip\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nfunc TestRunBuildResetsUidAndGidInContext(t *testing.T) {\n\tskip.IfCondition(t, runtime.GOOS == \"windows\", \"uid and gid not relevant on windows\")\n\tdest := fs.NewDir(t, \"test-build-context-dest\")\n\tdefer dest.Remove()\n\n\tfakeImageBuild := func(_ context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) {\n\t\tassert.Check(t, archive.Untar(context, dest.Path(), nil))\n\n\t\tbody := new(bytes.Buffer)\n\t\treturn types.ImageBuildResponse{Body: ioutil.NopCloser(body)}, nil\n\t}\n\tcli := test.NewFakeCli(&fakeClient{imageBuildFunc: fakeImageBuild})\n\n\tdir := fs.NewDir(t, \"test-build-context\",\n\t\tfs.WithFile(\"foo\", \"some content\", fs.AsUser(65534, 65534)),\n\t\tfs.WithFile(\"Dockerfile\", `\n\t\t\tFROM alpine:3.6\n\t\t\tCOPY foo bar \/\n\t\t`),\n\t)\n\tdefer dir.Remove()\n\n\toptions := newBuildOptions()\n\toptions.context = dir.Path()\n\n\terr := runBuild(cli, options)\n\tassert.NilError(t, err)\n\n\tfiles, err := ioutil.ReadDir(dest.Path())\n\tassert.NilError(t, err)\n\tfor _, fileInfo := range files {\n\t\tassert.Check(t, is.Equal(uint32(0), fileInfo.Sys().(*syscall.Stat_t).Uid))\n\t\tassert.Check(t, is.Equal(uint32(0), fileInfo.Sys().(*syscall.Stat_t).Gid))\n\t}\n}\nfunc TestRunBuildDockerfileFromStdinWithCompress(t *testing.T) {\n\tdest, err := ioutil.TempDir(\"\", \"test-build-compress-dest\")\n\tassert.NilError(t, err)\n\tdefer os.RemoveAll(dest)\n\n\tvar dockerfileName string\n\tfakeImageBuild := func(_ context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) {\n\t\tbuffer := new(bytes.Buffer)\n\t\ttee := io.TeeReader(context, buffer)\n\n\t\tassert.Check(t, archive.Untar(tee, dest, nil))\n\t\tdockerfileName = options.Dockerfile\n\n\t\theader := buffer.Bytes()[:10]\n\t\tassert.Check(t, is.Equal(archive.Gzip, archive.DetectCompression(header)))\n\n\t\tbody := new(bytes.Buffer)\n\t\treturn types.ImageBuildResponse{Body: ioutil.NopCloser(body)}, nil\n\t}\n\n\tcli := test.NewFakeCli(&fakeClient{imageBuildFunc: fakeImageBuild})\n\tdockerfile := bytes.NewBufferString(`\n\t\tFROM alpine:3.6\n\t\tCOPY foo \/\n\t`)\n\tcli.SetIn(command.NewInStream(ioutil.NopCloser(dockerfile)))\n\n\tdir, err := ioutil.TempDir(\"\", \"test-build-compress\")\n\tassert.NilError(t, err)\n\tdefer os.RemoveAll(dir)\n\n\tioutil.WriteFile(filepath.Join(dir, \"foo\"), []byte(\"some content\"), 0644)\n\n\toptions := newBuildOptions()\n\toptions.compress = true\n\toptions.dockerfileName = \"-\"\n\toptions.context = dir\n\n\terr = runBuild(cli, options)\n\tassert.NilError(t, err)\n\n\tfiles, err := ioutil.ReadDir(dest)\n\tassert.NilError(t, err)\n\tactual := []string{}\n\tfor _, fileInfo := range files {\n\t\tactual = append(actual, fileInfo.Name())\n\t}\n\tsort.Strings(actual)\n\tassert.Check(t, is.DeepEqual([]string{dockerfileName, \".dockerignore\", \"foo\"}, actual))\n}\n\nfunc TestRunBuildDockerfileOutsideContext(t *testing.T) {\n\tdir := fs.NewDir(t, t.Name(),\n\t\tfs.WithFile(\"data\", \"data file\"),\n\t)\n\tdefer dir.Remove()\n\n\t\/\/ Dockerfile outside of build-context\n\tdf := fs.NewFile(t, t.Name(),\n\t\tfs.WithContent(`\nFROM FOOBAR\nCOPY data \/data\n\t\t`),\n\t)\n\tdefer df.Remove()\n\n\tdest, err := ioutil.TempDir(\"\", t.Name())\n\tassert.NilError(t, err)\n\tdefer os.RemoveAll(dest)\n\n\tvar dockerfileName string\n\tfakeImageBuild := func(_ context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) {\n\t\tbuffer := new(bytes.Buffer)\n\t\ttee := io.TeeReader(context, buffer)\n\n\t\tassert.Check(t, archive.Untar(tee, dest, nil))\n\t\tdockerfileName = options.Dockerfile\n\n\t\tbody := new(bytes.Buffer)\n\t\treturn types.ImageBuildResponse{Body: ioutil.NopCloser(body)}, nil\n\t}\n\n\tcli := test.NewFakeCli(&fakeClient{imageBuildFunc: fakeImageBuild})\n\n\toptions := newBuildOptions()\n\toptions.context = dir.Path()\n\toptions.dockerfileName = df.Path()\n\n\terr = runBuild(cli, options)\n\tassert.NilError(t, err)\n\n\tfiles, err := ioutil.ReadDir(dest)\n\tassert.NilError(t, err)\n\tvar actual []string\n\tfor _, fileInfo := range files {\n\t\tactual = append(actual, fileInfo.Name())\n\t}\n\tsort.Strings(actual)\n\tassert.Check(t, is.DeepEqual([]string{dockerfileName, \".dockerignore\", \"data\"}, actual))\n}\n\n\/\/ TestRunBuildFromLocalGitHubDirNonExistingRepo tests that build contexts\n\/\/ starting with `github.com\/` are special-cased, and the build command attempts\n\/\/ to clone the remote repo.\n\/\/ TODO: test \"context selection\" logic directly when runBuild is refactored\n\/\/ to support testing (ex: docker\/cli#294)\nfunc TestRunBuildFromGitHubSpecialCase(t *testing.T) {\n\tcmd := NewBuildCommand(test.NewFakeCli(nil))\n\t\/\/ Clone a small repo that exists so git doesn't prompt for credentials\n\tcmd.SetArgs([]string{\"github.com\/docker\/for-win\"})\n\tcmd.SetOutput(ioutil.Discard)\n\terr := cmd.Execute()\n\tassert.ErrorContains(t, err, \"unable to prepare context\")\n\tassert.ErrorContains(t, err, \"docker-build-git\")\n}\n\n\/\/ TestRunBuildFromLocalGitHubDirNonExistingRepo tests that a local directory\n\/\/ starting with `github.com` takes precedence over the `github.com` special\n\/\/ case.\nfunc TestRunBuildFromLocalGitHubDir(t *testing.T) {\n\ttmpDir, err := ioutil.TempDir(\"\", \"docker-build-from-local-dir-\")\n\tassert.NilError(t, err)\n\tdefer os.RemoveAll(tmpDir)\n\n\tbuildDir := filepath.Join(tmpDir, \"github.com\", \"docker\", \"no-such-repository\")\n\terr = os.MkdirAll(buildDir, 0777)\n\tassert.NilError(t, err)\n\terr = ioutil.WriteFile(filepath.Join(buildDir, \"Dockerfile\"), []byte(\"FROM busybox\\n\"), 0644)\n\tassert.NilError(t, err)\n\n\tclient := test.NewFakeCli(&fakeClient{})\n\tcmd := NewBuildCommand(client)\n\tcmd.SetArgs([]string{buildDir})\n\tcmd.SetOutput(ioutil.Discard)\n\terr = cmd.Execute()\n\tassert.NilError(t, err)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2016 Uber Technologies, Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\npackage http\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"io\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"go.uber.org\/yarpc\/internal\/errors\"\n\t\"go.uber.org\/yarpc\/internal\/request\"\n\t\"go.uber.org\/yarpc\/transport\"\n\t\"go.uber.org\/yarpc\/transport\/internal\"\n\n\t\"github.com\/opentracing\/opentracing-go\"\n\t\"github.com\/opentracing\/opentracing-go\/ext\"\n)\n\nfunc popHeader(h http.Header, n string) string {\n\tv := h.Get(n)\n\th.Del(n)\n\treturn v\n}\n\n\/\/ handler adapts a transport.Handler into a handler for net\/http.\ntype handler struct {\n\tRegistry transport.Registry\n\tDeps     transport.Deps\n}\n\nfunc (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tstart := time.Now()\n\n\tdefer req.Body.Close()\n\tif req.Method != \"POST\" {\n\t\thttp.NotFound(w, req)\n\t\treturn\n\t}\n\n\tservice := req.Header.Get(ServiceHeader)\n\tprocedure := req.Header.Get(ProcedureHeader)\n\n\terr := h.callHandler(w, req, start)\n\tif err == nil {\n\t\treturn\n\t}\n\n\terr = errors.AsHandlerError(service, procedure, err)\n\tstatus := http.StatusInternalServerError\n\tif transport.IsBadRequestError(err) {\n\t\tstatus = http.StatusBadRequest\n\t} else if transport.IsTimeoutError(err) {\n\t\tstatus = http.StatusGatewayTimeout\n\t}\n\thttp.Error(w, err.Error(), status)\n}\n\nfunc (h handler) callHandler(w http.ResponseWriter, req *http.Request, start time.Time) error {\n\ttreq := &transport.Request{\n\t\tCaller:    popHeader(req.Header, CallerHeader),\n\t\tService:   popHeader(req.Header, ServiceHeader),\n\t\tProcedure: popHeader(req.Header, ProcedureHeader),\n\t\tEncoding:  transport.Encoding(popHeader(req.Header, EncodingHeader)),\n\t\tHeaders:   applicationHeaders.FromHTTPHeaders(req.Header, transport.Headers{}),\n\t\tBody:      req.Body,\n\t}\n\n\tctx := req.Context()\n\n\tv := request.Validator{Request: treq}\n\tctx, cancel := v.ParseTTL(ctx, popHeader(req.Header, TTLMSHeader))\n\tdefer cancel()\n\n\tctx, span := h.createSpan(ctx, req, treq, start)\n\n\ttreq, err := v.Validate(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspec, err := h.Registry.Choose(ctx, treq)\n\tif err != nil {\n\t\treturn updateSpanWithErr(span, err)\n\t}\n\n\tswitch spec.Type() {\n\tcase transport.Unary:\n\t\tdefer span.Finish()\n\n\t\tctx, cancel := v.ParseTTL(ctx, popHeader(req.Header, TTLMSHeader))\n\t\tdefer cancel()\n\n\t\ttreq, err = v.ValidateUnary(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = internal.SafelyCallUnaryHandler(ctx, spec.Unary(), start, treq, newResponseWriter(w))\n\n\tcase transport.Oneway:\n\t\ttreq, err = v.ValidateOneway(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = handleOnewayRequest(ctx, span, treq, spec.Oneway())\n\n\tdefault:\n\t\terr = errors.UnsupportedTypeError{Transport: \"HTTP\", Type: string(spec.Type())}\n\t}\n\n\treturn updateSpanWithErr(span, err)\n}\n\nfunc handleOnewayRequest(\n\tctx context.Context,\n\tspan opentracing.Span,\n\ttreq *transport.Request,\n\tonewayHandler transport.OnewayHandler,\n) error {\n\t\/\/ we will lose access to the body unless we read all the bytes before\n\t\/\/ returning from the request\n\tvar buff bytes.Buffer\n\tif _, err := io.Copy(&buff, treq.Body); err != nil {\n\t\treturn err\n\t}\n\ttreq.Body = &buff\n\n\tgo func() {\n\t\t\/\/ ensure the span lasts for length of the request in case of errors\n\t\tdefer span.Finish()\n\n\t\terr := internal.SafelyCallOnewayHandler(ctx, onewayHandler, treq)\n\t\tupdateSpanWithErr(span, err)\n\t}()\n\treturn nil\n}\n\nfunc updateSpanWithErr(span opentracing.Span, err error) error {\n\tif err != nil {\n\t\tspan.SetTag(\"error\", true)\n\t\tspan.LogEvent(err.Error())\n\t}\n\n\treturn err\n}\n\nfunc (h handler) createSpan(ctx context.Context, req *http.Request, treq *transport.Request, start time.Time) (context.Context, opentracing.Span) {\n\t\/\/ Extract opentracing etc baggage from headers\n\t\/\/ Annotate the inbound context with a trace span\n\ttracer := h.Deps.Tracer()\n\tcarrier := opentracing.HTTPHeadersCarrier(req.Header)\n\tparentSpanCtx, _ := tracer.Extract(opentracing.HTTPHeaders, carrier)\n\t\/\/ parentSpanCtx may be nil, ext.RPCServerOption handles a nil parent\n\t\/\/ gracefully.\n\tspan := tracer.StartSpan(\n\t\ttreq.Procedure,\n\t\topentracing.StartTime(start),\n\t\topentracing.Tags{\n\t\t\t\"rpc.caller\":    treq.Caller,\n\t\t\t\"rpc.service\":   treq.Service,\n\t\t\t\"rpc.encoding\":  treq.Encoding,\n\t\t\t\"rpc.transport\": \"http\",\n\t\t},\n\t\text.RPCServerOption(parentSpanCtx), \/\/ implies ChildOf\n\t)\n\text.PeerService.Set(span, treq.Caller)\n\tctx = opentracing.ContextWithSpan(ctx, span)\n\treturn ctx, span\n}\n\n\/\/ responseWriter adapts a http.ResponseWriter into a transport.ResponseWriter.\ntype responseWriter struct {\n\tw http.ResponseWriter\n}\n\nfunc newResponseWriter(w http.ResponseWriter) responseWriter {\n\treturn responseWriter{w: w}\n}\n\nfunc (rw responseWriter) Write(s []byte) (int, error) {\n\treturn rw.w.Write(s)\n}\n\nfunc (rw responseWriter) AddHeaders(h transport.Headers) {\n\tapplicationHeaders.ToHTTPHeaders(h, rw.w.Header())\n}\n\nfunc (responseWriter) SetApplicationError() {\n\t\/\/ Nothing to do.\n}\n<commit_msg>create new context for HTTP oneway inbound requests<commit_after>\/\/ Copyright (c) 2016 Uber Technologies, Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\npackage http\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"io\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"go.uber.org\/yarpc\/internal\/errors\"\n\t\"go.uber.org\/yarpc\/internal\/request\"\n\t\"go.uber.org\/yarpc\/transport\"\n\t\"go.uber.org\/yarpc\/transport\/internal\"\n\n\t\"github.com\/opentracing\/opentracing-go\"\n\t\"github.com\/opentracing\/opentracing-go\/ext\"\n)\n\nfunc popHeader(h http.Header, n string) string {\n\tv := h.Get(n)\n\th.Del(n)\n\treturn v\n}\n\n\/\/ handler adapts a transport.Handler into a handler for net\/http.\ntype handler struct {\n\tRegistry transport.Registry\n\tDeps     transport.Deps\n}\n\nfunc (h handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tstart := time.Now()\n\n\tdefer req.Body.Close()\n\tif req.Method != \"POST\" {\n\t\thttp.NotFound(w, req)\n\t\treturn\n\t}\n\n\tservice := req.Header.Get(ServiceHeader)\n\tprocedure := req.Header.Get(ProcedureHeader)\n\n\terr := h.callHandler(w, req, start)\n\tif err == nil {\n\t\treturn\n\t}\n\n\terr = errors.AsHandlerError(service, procedure, err)\n\tstatus := http.StatusInternalServerError\n\tif transport.IsBadRequestError(err) {\n\t\tstatus = http.StatusBadRequest\n\t} else if transport.IsTimeoutError(err) {\n\t\tstatus = http.StatusGatewayTimeout\n\t}\n\thttp.Error(w, err.Error(), status)\n}\n\nfunc (h handler) callHandler(w http.ResponseWriter, req *http.Request, start time.Time) error {\n\ttreq := &transport.Request{\n\t\tCaller:    popHeader(req.Header, CallerHeader),\n\t\tService:   popHeader(req.Header, ServiceHeader),\n\t\tProcedure: popHeader(req.Header, ProcedureHeader),\n\t\tEncoding:  transport.Encoding(popHeader(req.Header, EncodingHeader)),\n\t\tHeaders:   applicationHeaders.FromHTTPHeaders(req.Header, transport.Headers{}),\n\t\tBody:      req.Body,\n\t}\n\n\tctx := req.Context()\n\n\tv := request.Validator{Request: treq}\n\tctx, cancel := v.ParseTTL(ctx, popHeader(req.Header, TTLMSHeader))\n\tdefer cancel()\n\n\tctx, span := h.createSpan(ctx, req, treq, start)\n\n\ttreq, err := v.Validate(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspec, err := h.Registry.Choose(ctx, treq)\n\tif err != nil {\n\t\treturn updateSpanWithErr(span, err)\n\t}\n\n\tswitch spec.Type() {\n\tcase transport.Unary:\n\t\tdefer span.Finish()\n\n\t\tctx, cancel := v.ParseTTL(ctx, popHeader(req.Header, TTLMSHeader))\n\t\tdefer cancel()\n\n\t\ttreq, err = v.ValidateUnary(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = internal.SafelyCallUnaryHandler(ctx, spec.Unary(), start, treq, newResponseWriter(w))\n\n\tcase transport.Oneway:\n\t\ttreq, err = v.ValidateOneway(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = handleOnewayRequest(span, treq, spec.Oneway())\n\n\tdefault:\n\t\terr = errors.UnsupportedTypeError{Transport: \"HTTP\", Type: string(spec.Type())}\n\t}\n\n\treturn updateSpanWithErr(span, err)\n}\n\nfunc handleOnewayRequest(\n\tspan opentracing.Span,\n\ttreq *transport.Request,\n\tonewayHandler transport.OnewayHandler,\n) error {\n\t\/\/ we will lose access to the body unless we read all the bytes before\n\t\/\/ returning from the request\n\tvar buff bytes.Buffer\n\tif _, err := io.Copy(&buff, treq.Body); err != nil {\n\t\treturn err\n\t}\n\ttreq.Body = &buff\n\n\t\/\/ create a new context for oneway requests since the HTTP handler cancels\n\t\/\/ http.Request's context when ServeHTTP returns\n\tctx := opentracing.ContextWithSpan(context.Background(), span)\n\n\tgo func() {\n\t\t\/\/ ensure the span lasts for length of the handler in case of errors\n\t\tdefer span.Finish()\n\n\t\terr := internal.SafelyCallOnewayHandler(ctx, onewayHandler, treq)\n\t\tupdateSpanWithErr(span, err)\n\t}()\n\treturn nil\n}\n\nfunc updateSpanWithErr(span opentracing.Span, err error) error {\n\tif err != nil {\n\t\tspan.SetTag(\"error\", true)\n\t\tspan.LogEvent(err.Error())\n\t}\n\n\treturn err\n}\n\nfunc (h handler) createSpan(ctx context.Context, req *http.Request, treq *transport.Request, start time.Time) (context.Context, opentracing.Span) {\n\t\/\/ Extract opentracing etc baggage from headers\n\t\/\/ Annotate the inbound context with a trace span\n\ttracer := h.Deps.Tracer()\n\tcarrier := opentracing.HTTPHeadersCarrier(req.Header)\n\tparentSpanCtx, _ := tracer.Extract(opentracing.HTTPHeaders, carrier)\n\t\/\/ parentSpanCtx may be nil, ext.RPCServerOption handles a nil parent\n\t\/\/ gracefully.\n\tspan := tracer.StartSpan(\n\t\ttreq.Procedure,\n\t\topentracing.StartTime(start),\n\t\topentracing.Tags{\n\t\t\t\"rpc.caller\":    treq.Caller,\n\t\t\t\"rpc.service\":   treq.Service,\n\t\t\t\"rpc.encoding\":  treq.Encoding,\n\t\t\t\"rpc.transport\": \"http\",\n\t\t},\n\t\text.RPCServerOption(parentSpanCtx), \/\/ implies ChildOf\n\t)\n\text.PeerService.Set(span, treq.Caller)\n\tctx = opentracing.ContextWithSpan(ctx, span)\n\treturn ctx, span\n}\n\n\/\/ responseWriter adapts a http.ResponseWriter into a transport.ResponseWriter.\ntype responseWriter struct {\n\tw http.ResponseWriter\n}\n\nfunc newResponseWriter(w http.ResponseWriter) responseWriter {\n\treturn responseWriter{w: w}\n}\n\nfunc (rw responseWriter) Write(s []byte) (int, error) {\n\treturn rw.w.Write(s)\n}\n\nfunc (rw responseWriter) AddHeaders(h transport.Headers) {\n\tapplicationHeaders.ToHTTPHeaders(h, rw.w.Header())\n}\n\nfunc (responseWriter) SetApplicationError() {\n\t\/\/ Nothing to do.\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nfunc main() {\n\n}\n<commit_msg>途中だけどコミット<commit_after>package main\n\nimport (\n\t\"github.com\/pkg\/errors\"\n\t\"io\/ioutil\"\n\t\"fmt\"\n)\n\nfunc main() {\n\n\t\/\/ TODO 途中.\n\n\t\/*\n\n\t\tpkg\/errors のサンプル実装\n\n\t\t# 参照\n\t\t\thttps:\/\/github.com\/pkg\/errors\n\n\t\t# インストール\n\t\t\tgo get -u github.com\/pkg\/errors\n\t*\/\n\n\terr := a()\n\tif err != nil {\n\t\tfmt.Printf(\"エラーだよ. %v\\n\", err)\n\t\tfmt.Println(\"------------\")\n\t} else {\n\t\tfmt.Println(\"無事に処理できました！\")\n\t}\n\n}\n\nfunc a() error {\n\terr := b()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"〇〇しようと思ったけどエラー.\")\n\t}\n\treturn nil\n}\n\nfunc b() error {\n\tfpath := \"notfound.txt\"\n\t_, err := ioutil.ReadFile(fpath)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"「%s」を読み込めませんでした\", fpath)\n\t}\n\treturn nil\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/ninjasphere\/go-ninja\/channels\"\n\t\"github.com\/ninjasphere\/go-zigbee\/gateway\"\n)\n\ntype OnOffChannel struct {\n\tChannel\n\tchannel *channels.OnOffChannel\n}\n\n\/\/ -------- On\/Off Protocol --------\n\nfunc (c *OnOffChannel) TurnOn() error {\n\treturn c.setState(gateway.GwOnOffStateT_ON_STATE.Enum())\n}\n\nfunc (c *OnOffChannel) TurnOff() error {\n\treturn c.setState(gateway.GwOnOffStateT_OFF_STATE.Enum())\n}\n\nfunc (c *OnOffChannel) ToggleOnOff() error {\n\treturn c.setState(gateway.GwOnOffStateT_TOGGLE_STATE.Enum())\n}\n\nfunc (c *OnOffChannel) SetOnOff(state bool) error {\n\tif state {\n\t\treturn c.TurnOn()\n\t}\n\n\treturn c.TurnOff()\n}\n\nfunc (c *OnOffChannel) init() error {\n\tlog.Debugf(\"Initialising on\/off channel of device %d\", *c.device.deviceInfo.IeeeAddress)\n\n\t\/\/clusterID := uint32(0x06)\n\n\t\/*attributeID := uint32(0)\n\tminReportInterval := uint32(1)\n\tmaxReportInterval := uint32(120)\n\n\trequest := &gateway.GwSetAttributeReportingReq{\n\t\tDstAddress: &gateway.GwAddressStructT{\n\t\t\tAddressType: gateway.GwAddressTypeT_UNICAST.Enum(),\n\t\t\tIeeeAddr:    c.device.deviceInfo.IeeeAddress,\n\t\t},\n\t\tClusterId: &clusterID,\n\t\tAttributeReportList: []*gateway.GwAttributeReportT{{\n\t\t\tAttributeId:       &attributeID,\n\t\t\tAttributeType:     gateway.GwZclAttributeDataTypesT_ZCL_DATATYPE_BOOLEAN.Enum(),\n\t\t\tMinReportInterval: &minReportInterval,\n\t\t\tMaxReportInterval: &maxReportInterval,\n\t\t}},\n\t}\n\n\tresponse := &gateway.GwSetAttributeReportingRspInd{}\n\n\terr := c.device.driver.gatewayConn.SendAsyncCommand(request, response, 20*time.Second)\n\tif err != nil {\n\t\tlog.Errorf(\"Error enabling on\/off reporting: %s\", err)\n\t} else if response.Status.String() != \"STATUS_SUCCESS\" {\n\t\tlog.Errorf(\"Failed to enable on\/off reporting. status: %s\", response.Status.String())\n\t}*\/\n\n\tc.channel = channels.NewOnOffChannel(c)\n\terr = c.device.driver.Conn.ExportChannel(c.device, c.channel, c.ID)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to announce on\/off channel: %s\", err)\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tlog.Debugf(\"Polling for on\/off\")\n\t\t\terr := c.fetchState()\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed to poll for on\/off state %s\", err)\n\t\t\t}\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\t}()\n\n\treturn nil\n\n}\n\nfunc (c *OnOffChannel) setState(state *gateway.GwOnOffStateT) error {\n\trequest := &gateway.DevSetOnOffStateReq{\n\t\tDstAddress: &gateway.GwAddressStructT{\n\t\t\tAddressType: gateway.GwAddressTypeT_UNICAST.Enum(),\n\t\t\tIeeeAddr:    c.device.deviceInfo.IeeeAddress,\n\t\t},\n\t\tState: state,\n\t}\n\n\tresponse := &gateway.GwZigbeeGenericRspInd{}\n\terr := c.device.driver.gatewayConn.SendAsyncCommand(request, response, 2*time.Second)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error setting on\/off state : %s\", err)\n\t}\n\tif response.Status.String() != \"STATUS_SUCCESS\" {\n\t\treturn fmt.Errorf(\"Failed to set on\/off state. status: %s\", response.Status.String())\n\t}\n\n\treturn c.fetchState()\n}\n\nfunc (c *OnOffChannel) fetchState() error {\n\trequest := &gateway.DevGetOnOffStateReq{\n\t\tDstAddress: &gateway.GwAddressStructT{\n\t\t\tAddressType: gateway.GwAddressTypeT_UNICAST.Enum(),\n\t\t\tIeeeAddr:    c.device.deviceInfo.IeeeAddress,\n\t\t},\n\t}\n\n\tresponse := &gateway.DevGetOnOffStateRspInd{}\n\tif c.device.driver == nil {\n\t\tlog.Fatalf(\"assertion failed: c.device.driver != nil\")\n\t}\n\tif c.device.driver.gatewayConn == nil {\n\t\tlog.Fatalf(\"assertion failed: c.device.driver.gatewayConn != nil\")\n\t}\n\terr := c.device.driver.gatewayConn.SendAsyncCommand(request, response, 10*time.Second)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting on\/off state : %s\", err)\n\t}\n\tif response.Status.String() != \"STATUS_SUCCESS\" {\n\t\treturn fmt.Errorf(\"Failed to get on\/off state. status: %s\", response.Status.String())\n\t}\n\n\tc.channel.SendState(*response.StateValue == gateway.GwOnOffStateValueT_ON)\n\n\treturn nil\n}\n<commit_msg>Only send on-off state when it changes, or when a command has been sent<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/ninjasphere\/go-ninja\/channels\"\n\t\"github.com\/ninjasphere\/go-zigbee\/gateway\"\n)\n\ntype OnOffChannel struct {\n\tChannel\n\tlastState *bool\n\tchannel   *channels.OnOffChannel\n}\n\n\/\/ -------- On\/Off Protocol --------\n\nfunc (c *OnOffChannel) TurnOn() error {\n\treturn c.setState(gateway.GwOnOffStateT_ON_STATE.Enum())\n}\n\nfunc (c *OnOffChannel) TurnOff() error {\n\treturn c.setState(gateway.GwOnOffStateT_OFF_STATE.Enum())\n}\n\nfunc (c *OnOffChannel) ToggleOnOff() error {\n\treturn c.setState(gateway.GwOnOffStateT_TOGGLE_STATE.Enum())\n}\n\nfunc (c *OnOffChannel) SetOnOff(state bool) error {\n\tif state {\n\t\treturn c.TurnOn()\n\t}\n\n\treturn c.TurnOff()\n}\n\nfunc (c *OnOffChannel) init() error {\n\tlog.Debugf(\"Initialising on\/off channel of device %d\", *c.device.deviceInfo.IeeeAddress)\n\n\t\/\/clusterID := uint32(0x06)\n\n\t\/*attributeID := uint32(0)\n\tminReportInterval := uint32(1)\n\tmaxReportInterval := uint32(120)\n\n\trequest := &gateway.GwSetAttributeReportingReq{\n\t\tDstAddress: &gateway.GwAddressStructT{\n\t\t\tAddressType: gateway.GwAddressTypeT_UNICAST.Enum(),\n\t\t\tIeeeAddr:    c.device.deviceInfo.IeeeAddress,\n\t\t},\n\t\tClusterId: &clusterID,\n\t\tAttributeReportList: []*gateway.GwAttributeReportT{{\n\t\t\tAttributeId:       &attributeID,\n\t\t\tAttributeType:     gateway.GwZclAttributeDataTypesT_ZCL_DATATYPE_BOOLEAN.Enum(),\n\t\t\tMinReportInterval: &minReportInterval,\n\t\t\tMaxReportInterval: &maxReportInterval,\n\t\t}},\n\t}\n\n\tresponse := &gateway.GwSetAttributeReportingRspInd{}\n\n\terr := c.device.driver.gatewayConn.SendAsyncCommand(request, response, 20*time.Second)\n\tif err != nil {\n\t\tlog.Errorf(\"Error enabling on\/off reporting: %s\", err)\n\t} else if response.Status.String() != \"STATUS_SUCCESS\" {\n\t\tlog.Errorf(\"Failed to enable on\/off reporting. status: %s\", response.Status.String())\n\t}*\/\n\n\tc.channel = channels.NewOnOffChannel(c)\n\terr = c.device.driver.Conn.ExportChannel(c.device, c.channel, c.ID)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to announce on\/off channel: %s\", err)\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tlog.Debugf(\"Polling for on\/off\")\n\t\t\terr := c.fetchState()\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed to poll for on\/off state %s\", err)\n\t\t\t}\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t}\n\t}()\n\n\treturn nil\n\n}\n\nfunc (c *OnOffChannel) setState(state *gateway.GwOnOffStateT) error {\n\n\trequest := &gateway.DevSetOnOffStateReq{\n\t\tDstAddress: &gateway.GwAddressStructT{\n\t\t\tAddressType: gateway.GwAddressTypeT_UNICAST.Enum(),\n\t\t\tIeeeAddr:    c.device.deviceInfo.IeeeAddress,\n\t\t},\n\t\tState: state,\n\t}\n\n\tresponse := &gateway.GwZigbeeGenericRspInd{}\n\terr := c.device.driver.gatewayConn.SendAsyncCommand(request, response, 2*time.Second)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error setting on\/off state : %s\", err)\n\t}\n\tif response.Status.String() != \"STATUS_SUCCESS\" {\n\t\treturn fmt.Errorf(\"Failed to set on\/off state. status: %s\", response.Status.String())\n\t}\n\n\tc.lastState = nil\n\n\treturn c.fetchState()\n}\n\nfunc (c *OnOffChannel) fetchState() error {\n\trequest := &gateway.DevGetOnOffStateReq{\n\t\tDstAddress: &gateway.GwAddressStructT{\n\t\t\tAddressType: gateway.GwAddressTypeT_UNICAST.Enum(),\n\t\t\tIeeeAddr:    c.device.deviceInfo.IeeeAddress,\n\t\t},\n\t}\n\n\tresponse := &gateway.DevGetOnOffStateRspInd{}\n\tif c.device.driver == nil {\n\t\tlog.Fatalf(\"assertion failed: c.device.driver != nil\")\n\t}\n\tif c.device.driver.gatewayConn == nil {\n\t\tlog.Fatalf(\"assertion failed: c.device.driver.gatewayConn != nil\")\n\t}\n\terr := c.device.driver.gatewayConn.SendAsyncCommand(request, response, 10*time.Second)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting on\/off state : %s\", err)\n\t}\n\tif response.Status.String() != \"STATUS_SUCCESS\" {\n\t\treturn fmt.Errorf(\"Failed to get on\/off state. status: %s\", response.Status.String())\n\t}\n\n\tstate := *response.StateValue == gateway.GwOnOffStateValueT_ON\n\n\tif c.lastState == nil || *c.lastState != state {\n\t\tc.lastState = &state\n\t\tc.channel.SendState(state)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package fingerprint\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\tcleanhttp \"github.com\/hashicorp\/go-cleanhttp\"\n\tlog \"github.com\/hashicorp\/go-hclog\"\n\n\t\"github.com\/hashicorp\/nomad\/helper\/useragent\"\n\t\"github.com\/hashicorp\/nomad\/nomad\/structs\"\n)\n\nconst (\n\t\/\/ AzureMetadataURL is where the Azure metadata server normally resides. We hardcode the\n\t\/\/ \"instance\" path as well since it's the only one we access here.\n\tAzureMetadataURL = \"http:\/\/169.254.169.254\/metadata\/instance\/\"\n\n\t\/\/ AzureMetadataAPIVersion is the version used when contacting the Azure metadata\n\t\/\/ services.\n\tAzureMetadataAPIVersion = \"2019-06-04\"\n\n\t\/\/ AzureMetadataTimeout is the timeout used when contacting the Azure metadata\n\t\/\/ services.\n\tAzureMetadataTimeout = 2 * time.Second\n)\n\ntype AzureMetadataTag struct {\n\tName  string\n\tValue string\n}\n\ntype AzureMetadataPair struct {\n\tpath   string\n\tunique bool\n}\n\n\/\/ EnvAzureFingerprint is used to fingerprint Azure metadata\ntype EnvAzureFingerprint struct {\n\tStaticFingerprinter\n\tclient      *http.Client\n\tlogger      log.Logger\n\tmetadataURL string\n}\n\n\/\/ NewEnvAzureFingerprint is used to create a fingerprint from Azure metadata\nfunc NewEnvAzureFingerprint(logger log.Logger) Fingerprint {\n\t\/\/ Read the internal metadata URL from the environment, allowing test files to\n\t\/\/ provide their own\n\tmetadataURL := os.Getenv(\"AZURE_ENV_URL\")\n\tif metadataURL == \"\" {\n\t\tmetadataURL = AzureMetadataURL\n\t}\n\n\t\/\/ assume 2 seconds is enough time for inside Azure network\n\tclient := &http.Client{\n\t\tTimeout:   AzureMetadataTimeout,\n\t\tTransport: cleanhttp.DefaultTransport(),\n\t}\n\n\treturn &EnvAzureFingerprint{\n\t\tclient:      client,\n\t\tlogger:      logger.Named(\"env_azure\"),\n\t\tmetadataURL: metadataURL,\n\t}\n}\n\nfunc (f *EnvAzureFingerprint) Get(attribute string, format string) (string, error) {\n\treqURL := f.metadataURL + attribute + fmt.Sprintf(\"?api-version=%s&format=%s\", AzureMetadataAPIVersion, format)\n\tparsedURL, err := url.Parse(reqURL)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq := &http.Request{\n\t\tMethod: \"GET\",\n\t\tURL:    parsedURL,\n\t\tHeader: http.Header{\n\t\t\t\"Metadata\":   []string{\"true\"},\n\t\t\t\"User-Agent\": []string{useragent.String()},\n\t\t},\n\t}\n\n\tres, err := f.client.Do(req)\n\tif err != nil {\n\t\tf.logger.Debug(\"could not read value for attribute\", \"attribute\", attribute, \"error\", err)\n\t\treturn \"\", err\n\t} else if res.StatusCode != http.StatusOK {\n\t\tf.logger.Debug(\"could not read value for attribute\", \"attribute\", attribute, \"resp_code\", res.StatusCode)\n\t\treturn \"\", err\n\t}\n\n\tresp, err := ioutil.ReadAll(res.Body)\n\tres.Body.Close()\n\tif err != nil {\n\t\tf.logger.Error(\"error reading response body for Azure attribute\", \"attribute\", attribute, \"error\", err)\n\t\treturn \"\", err\n\t}\n\n\tif res.StatusCode >= 400 {\n\t\treturn \"\", ReqError{res.StatusCode}\n\t}\n\n\treturn string(resp), nil\n}\n\nfunc checkAzureError(err error, logger log.Logger, desc string) error {\n\t\/\/ If it's a URL error, assume we're not actually in an Azure environment.\n\t\/\/ To the outer layers, this isn't an error so return nil.\n\tif _, ok := err.(*url.Error); ok {\n\t\tlogger.Debug(\"error querying Azure attribute; skipping\", \"attribute\", desc)\n\t\treturn nil\n\t}\n\t\/\/ Otherwise pass the error through.\n\treturn err\n}\n\nfunc (f *EnvAzureFingerprint) Fingerprint(request *FingerprintRequest, response *FingerprintResponse) error {\n\tcfg := request.Config\n\n\t\/\/ Check if we should tighten the timeout\n\tif cfg.ReadBoolDefault(TightenNetworkTimeoutsConfig, false) {\n\t\tf.client.Timeout = 1 * time.Millisecond\n\t}\n\n\tif !f.isAzure() {\n\t\treturn nil\n\t}\n\n\t\/\/ Keys and whether they should be namespaced as unique. Any key whose value\n\t\/\/ uniquely identifies a node, such as ip, should be marked as unique. When\n\t\/\/ marked as unique, the key isn't included in the computed node class.\n\tkeys := map[string]AzureMetadataPair{\n\t\t\"id\":             {unique: true, path: \"compute\/vmId\"},\n\t\t\"name\":           {unique: true, path: \"compute\/name\"}, \/\/ name might not be the same as hostname\n\t\t\"location\":       {unique: false, path: \"compute\/location\"},\n\t\t\"resource-group\": {unique: false, path: \"compute\/resourceGroupName\"},\n\t\t\"scale-set\":      {unique: false, path: \"compute\/vmScaleSetName\"},\n\t\t\"vm-size\":        {unique: false, path: \"compute\/vmSize\"},\n\t\t\"local-ipv4\":     {unique: true, path: \"network\/interface\/0\/ipv4\/ipAddress\/0\/privateIpAddress\"},\n\t\t\"public-ipv4\":    {unique: true, path: \"network\/interface\/0\/ipv4\/ipAddress\/0\/publicIpAddress\"},\n\t\t\"local-ipv6\":     {unique: true, path: \"network\/interface\/0\/ipv6\/ipAddress\/0\/privateIpAddress\"},\n\t\t\"public-ipv6\":    {unique: true, path: \"network\/interface\/0\/ipv6\/ipAddress\/0\/publicIpAddress\"},\n\t\t\"mac\":            {unique: true, path: \"network\/interface\/0\/macAddress\"},\n\t}\n\n\tfor k, attr := range keys {\n\t\tresp, err := f.Get(attr.path, \"text\")\n\t\tv := strings.TrimSpace(resp)\n\t\tif err != nil {\n\t\t\treturn checkAzureError(err, f.logger, k)\n\t\t} else if v == \"\" {\n\t\t\tf.logger.Debug(\"read an empty value\", \"attribute\", k)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ assume we want blank entries\n\t\tkey := \"platform.azure.\" + strings.Replace(k, \"\/\", \".\", -1)\n\t\tif attr.unique {\n\t\t\tkey = structs.UniqueNamespace(key)\n\t\t}\n\t\tresponse.AddAttribute(key, v)\n\t}\n\n\t\/\/ copy over network specific information\n\tif val, ok := response.Attributes[\"unique.platform.azure.local-ipv4\"]; ok && val != \"\" {\n\t\tresponse.AddAttribute(\"unique.network.ip-address\", val)\n\t}\n\n\tvar tagList []AzureMetadataTag\n\tvalue, err := f.Get(\"compute\/tagsList\", \"json\")\n\tif err != nil {\n\t\treturn checkAzureError(err, f.logger, \"tags\")\n\t}\n\tif err := json.Unmarshal([]byte(value), &tagList); err != nil {\n\t\tf.logger.Warn(\"error decoding instance tags\", \"error\", err)\n\t}\n\tfor _, tag := range tagList {\n\t\tattr := \"platform.azure.tag.\"\n\t\tvar key string\n\n\t\t\/\/ If the tag is namespaced as unique, we strip it from the tag and\n\t\t\/\/ prepend to the whole attribute.\n\t\tif structs.IsUniqueNamespace(tag.Name) {\n\t\t\ttag.Name = strings.TrimPrefix(tag.Name, structs.NodeUniqueNamespace)\n\t\t\tkey = fmt.Sprintf(\"%s%s%s\", structs.NodeUniqueNamespace, attr, tag.Name)\n\t\t} else {\n\t\t\tkey = fmt.Sprintf(\"%s%s\", attr, tag.Name)\n\t\t}\n\n\t\tresponse.AddAttribute(key, tag.Value)\n\t}\n\n\t\/\/ populate Links\n\tif id, ok := response.Attributes[\"unique.platform.azure.id\"]; ok {\n\t\tresponse.AddLink(\"azure\", id)\n\t}\n\n\tresponse.Detected = true\n\treturn nil\n}\n\nfunc (f *EnvAzureFingerprint) isAzure() bool {\n\tv, err := f.Get(\"compute\/azEnvironment\", \"text\")\n\tv = strings.TrimSpace(v)\n\treturn err == nil && v != \"\"\n}\n<commit_msg>Add compute\/zone to Azure fingerprinting<commit_after>package fingerprint\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\tcleanhttp \"github.com\/hashicorp\/go-cleanhttp\"\n\tlog \"github.com\/hashicorp\/go-hclog\"\n\n\t\"github.com\/hashicorp\/nomad\/helper\/useragent\"\n\t\"github.com\/hashicorp\/nomad\/nomad\/structs\"\n)\n\nconst (\n\t\/\/ AzureMetadataURL is where the Azure metadata server normally resides. We hardcode the\n\t\/\/ \"instance\" path as well since it's the only one we access here.\n\tAzureMetadataURL = \"http:\/\/169.254.169.254\/metadata\/instance\/\"\n\n\t\/\/ AzureMetadataAPIVersion is the version used when contacting the Azure metadata\n\t\/\/ services.\n\tAzureMetadataAPIVersion = \"2019-06-04\"\n\n\t\/\/ AzureMetadataTimeout is the timeout used when contacting the Azure metadata\n\t\/\/ services.\n\tAzureMetadataTimeout = 2 * time.Second\n)\n\ntype AzureMetadataTag struct {\n\tName  string\n\tValue string\n}\n\ntype AzureMetadataPair struct {\n\tpath   string\n\tunique bool\n}\n\n\/\/ EnvAzureFingerprint is used to fingerprint Azure metadata\ntype EnvAzureFingerprint struct {\n\tStaticFingerprinter\n\tclient      *http.Client\n\tlogger      log.Logger\n\tmetadataURL string\n}\n\n\/\/ NewEnvAzureFingerprint is used to create a fingerprint from Azure metadata\nfunc NewEnvAzureFingerprint(logger log.Logger) Fingerprint {\n\t\/\/ Read the internal metadata URL from the environment, allowing test files to\n\t\/\/ provide their own\n\tmetadataURL := os.Getenv(\"AZURE_ENV_URL\")\n\tif metadataURL == \"\" {\n\t\tmetadataURL = AzureMetadataURL\n\t}\n\n\t\/\/ assume 2 seconds is enough time for inside Azure network\n\tclient := &http.Client{\n\t\tTimeout:   AzureMetadataTimeout,\n\t\tTransport: cleanhttp.DefaultTransport(),\n\t}\n\n\treturn &EnvAzureFingerprint{\n\t\tclient:      client,\n\t\tlogger:      logger.Named(\"env_azure\"),\n\t\tmetadataURL: metadataURL,\n\t}\n}\n\nfunc (f *EnvAzureFingerprint) Get(attribute string, format string) (string, error) {\n\treqURL := f.metadataURL + attribute + fmt.Sprintf(\"?api-version=%s&format=%s\", AzureMetadataAPIVersion, format)\n\tparsedURL, err := url.Parse(reqURL)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq := &http.Request{\n\t\tMethod: \"GET\",\n\t\tURL:    parsedURL,\n\t\tHeader: http.Header{\n\t\t\t\"Metadata\":   []string{\"true\"},\n\t\t\t\"User-Agent\": []string{useragent.String()},\n\t\t},\n\t}\n\n\tres, err := f.client.Do(req)\n\tif err != nil {\n\t\tf.logger.Debug(\"could not read value for attribute\", \"attribute\", attribute, \"error\", err)\n\t\treturn \"\", err\n\t} else if res.StatusCode != http.StatusOK {\n\t\tf.logger.Debug(\"could not read value for attribute\", \"attribute\", attribute, \"resp_code\", res.StatusCode)\n\t\treturn \"\", err\n\t}\n\n\tresp, err := ioutil.ReadAll(res.Body)\n\tres.Body.Close()\n\tif err != nil {\n\t\tf.logger.Error(\"error reading response body for Azure attribute\", \"attribute\", attribute, \"error\", err)\n\t\treturn \"\", err\n\t}\n\n\tif res.StatusCode >= 400 {\n\t\treturn \"\", ReqError{res.StatusCode}\n\t}\n\n\treturn string(resp), nil\n}\n\nfunc checkAzureError(err error, logger log.Logger, desc string) error {\n\t\/\/ If it's a URL error, assume we're not actually in an Azure environment.\n\t\/\/ To the outer layers, this isn't an error so return nil.\n\tif _, ok := err.(*url.Error); ok {\n\t\tlogger.Debug(\"error querying Azure attribute; skipping\", \"attribute\", desc)\n\t\treturn nil\n\t}\n\t\/\/ Otherwise pass the error through.\n\treturn err\n}\n\nfunc (f *EnvAzureFingerprint) Fingerprint(request *FingerprintRequest, response *FingerprintResponse) error {\n\tcfg := request.Config\n\n\t\/\/ Check if we should tighten the timeout\n\tif cfg.ReadBoolDefault(TightenNetworkTimeoutsConfig, false) {\n\t\tf.client.Timeout = 1 * time.Millisecond\n\t}\n\n\tif !f.isAzure() {\n\t\treturn nil\n\t}\n\n\t\/\/ Keys and whether they should be namespaced as unique. Any key whose value\n\t\/\/ uniquely identifies a node, such as ip, should be marked as unique. When\n\t\/\/ marked as unique, the key isn't included in the computed node class.\n\tkeys := map[string]AzureMetadataPair{\n\t\t\"id\":             {unique: true, path: \"compute\/vmId\"},\n\t\t\"name\":           {unique: true, path: \"compute\/name\"}, \/\/ name might not be the same as hostname\n\t\t\"location\":       {unique: false, path: \"compute\/location\"},\n\t\t\"resource-group\": {unique: false, path: \"compute\/resourceGroupName\"},\n\t\t\"scale-set\":      {unique: false, path: \"compute\/vmScaleSetName\"},\n\t\t\"vm-size\":        {unique: false, path: \"compute\/vmSize\"},\n\t\t\"zone\":           {unique: false, path: \"compute\/zone\"},\n\t\t\"local-ipv4\":     {unique: true, path: \"network\/interface\/0\/ipv4\/ipAddress\/0\/privateIpAddress\"},\n\t\t\"public-ipv4\":    {unique: true, path: \"network\/interface\/0\/ipv4\/ipAddress\/0\/publicIpAddress\"},\n\t\t\"local-ipv6\":     {unique: true, path: \"network\/interface\/0\/ipv6\/ipAddress\/0\/privateIpAddress\"},\n\t\t\"public-ipv6\":    {unique: true, path: \"network\/interface\/0\/ipv6\/ipAddress\/0\/publicIpAddress\"},\n\t\t\"mac\":            {unique: true, path: \"network\/interface\/0\/macAddress\"},\n\t}\n\n\tfor k, attr := range keys {\n\t\tresp, err := f.Get(attr.path, \"text\")\n\t\tv := strings.TrimSpace(resp)\n\t\tif err != nil {\n\t\t\treturn checkAzureError(err, f.logger, k)\n\t\t} else if v == \"\" {\n\t\t\tf.logger.Debug(\"read an empty value\", \"attribute\", k)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ assume we want blank entries\n\t\tkey := \"platform.azure.\" + strings.Replace(k, \"\/\", \".\", -1)\n\t\tif attr.unique {\n\t\t\tkey = structs.UniqueNamespace(key)\n\t\t}\n\t\tresponse.AddAttribute(key, v)\n\t}\n\n\t\/\/ copy over network specific information\n\tif val, ok := response.Attributes[\"unique.platform.azure.local-ipv4\"]; ok && val != \"\" {\n\t\tresponse.AddAttribute(\"unique.network.ip-address\", val)\n\t}\n\n\tvar tagList []AzureMetadataTag\n\tvalue, err := f.Get(\"compute\/tagsList\", \"json\")\n\tif err != nil {\n\t\treturn checkAzureError(err, f.logger, \"tags\")\n\t}\n\tif err := json.Unmarshal([]byte(value), &tagList); err != nil {\n\t\tf.logger.Warn(\"error decoding instance tags\", \"error\", err)\n\t}\n\tfor _, tag := range tagList {\n\t\tattr := \"platform.azure.tag.\"\n\t\tvar key string\n\n\t\t\/\/ If the tag is namespaced as unique, we strip it from the tag and\n\t\t\/\/ prepend to the whole attribute.\n\t\tif structs.IsUniqueNamespace(tag.Name) {\n\t\t\ttag.Name = strings.TrimPrefix(tag.Name, structs.NodeUniqueNamespace)\n\t\t\tkey = fmt.Sprintf(\"%s%s%s\", structs.NodeUniqueNamespace, attr, tag.Name)\n\t\t} else {\n\t\t\tkey = fmt.Sprintf(\"%s%s\", attr, tag.Name)\n\t\t}\n\n\t\tresponse.AddAttribute(key, tag.Value)\n\t}\n\n\t\/\/ populate Links\n\tif id, ok := response.Attributes[\"unique.platform.azure.id\"]; ok {\n\t\tresponse.AddLink(\"azure\", id)\n\t}\n\n\tresponse.Detected = true\n\treturn nil\n}\n\nfunc (f *EnvAzureFingerprint) isAzure() bool {\n\tv, err := f.Get(\"compute\/azEnvironment\", \"text\")\n\tv = strings.TrimSpace(v)\n\treturn err == nil && v != \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright ©2012 The bíogo.cluster Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package meanshift provides mean shift clustering for ℝⁿ data.\npackage meanshift\n\nimport (\n\t\"code.google.com\/p\/biogo.cluster\"\n\t\"fmt\"\n)\n\ntype pnt []float64\n\nfunc (p pnt) V() []float64 { return p }\n\ntype value struct {\n\tpnt\n\tw       float64\n\tcluster int\n}\n\nfunc (v *value) Weight() float64 { return v.w }\nfunc (v *value) Cluster() int    { return v.cluster }\n\ntype center struct {\n\tpnt\n\tw       float64\n\tindices cluster.Indices\n}\n\nfunc (c *center) Members() cluster.Indices { return c.indices }\n\n\/\/ Shifter implements a single step of the mean shift algorithm.\ntype Shifter interface {\n\t\/\/ Init initialises the Shifter with the provided data.\n\tInit(cluster.Interface)\n\n\t\/\/ Shift performs a single iteration of the mean shift algorithm and\n\t\/\/ returns the sum of squares differences between the initial state\n\t\/\/ and the final state.\n\tShift() float64\n\n\t\/\/ Bandwidth returns the bandwidth parameter of the Shifter.\n\tBandwidth() float64\n\n\t\/\/ Centers returns the cluster centers of the clustered data.\n\tCenters() []cluster.Center\n}\n\n\/\/ MeanShift implements data clustering using the mean shift algorithm.\ntype MeanShift struct {\n\tk       Shifter\n\ttol     float64\n\tmaxIter int\n\tvalues  []value\n\tcenters []center\n\tci      []cluster.Indices\n}\n\n\/\/ New creates a new mean shift Clusterer object populated with data from an Interface value, data\n\/\/ and using the Shifter k.\nfunc New(data cluster.Interface, k Shifter, tol float64, maxIter int) *MeanShift {\n\tk.Init(data)\n\treturn &MeanShift{\n\t\tk:       k,\n\t\ttol:     tol,\n\t\tmaxIter: maxIter,\n\t\tvalues:  convert(data),\n\t}\n}\n\n\/\/ convert renders data to the internal float64 representation for a MeanShift.\nfunc convert(data cluster.Interface) []value {\n\tva := make([]value, data.Len())\n\tfor i := 0; i < data.Len(); i++ {\n\t\tva[i] = value{pnt: append(pnt(nil), data.Values(i)...)}\n\t}\n\tif w, ok := data.(cluster.Weighter); ok {\n\t\tfor i := 0; i < data.Len(); i++ {\n\t\t\tva[i].w = w.Weight(i)\n\t\t}\n\t} else {\n\t\tfor i := 0; i < data.Len(); i++ {\n\t\t\tva[i].w = 1\n\t\t}\n\t}\n\n\treturn va\n}\n\n\/\/ Cluster runs a clustering of the data using the mean shift algorithm.\nfunc (ms *MeanShift) Cluster() error {\n\tfor i := 0; ; i++ {\n\t\tdelta := ms.k.Shift()\n\t\tif delta <= ms.tol {\n\t\t\tbreak\n\t\t}\n\t\tif i > ms.maxIter {\n\t\t\treturn fmt.Errorf(\"meanshift: exceeded maximum iterations: delta=%f\", delta)\n\t\t}\n\t}\n\n\tvar cen []cluster.Center\n\tcen = ms.k.Centers()\n\tms.ci = make([]cluster.Indices, len(cen))\n\tms.centers = make([]center, len(cen))\n\tfor i, c := range cen {\n\t\tms.ci[i] = c.Members()\n\t\tms.centers[i] = center{pnt: c.V(), indices: ms.ci[i]}\n\t\tfor _, j := range ms.ci[i] {\n\t\t\tms.values[j].cluster = i\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Total calculates the total sum of squares for the data relative to the data mean.\nfunc (ms *MeanShift) Total() float64 {\n\tp := make([]float64, len(ms.values[0].pnt))\n\n\tfor _, v := range ms.values {\n\t\tfor i := range p {\n\t\t\tp[i] += v.pnt[i]\n\t\t}\n\t}\n\tinv := 1 \/ float64(len(ms.values))\n\tfor i := range p {\n\t\tp[i] *= inv\n\t}\n\n\tvar ss float64\n\tfor _, v := range ms.values {\n\t\tfor i := range p {\n\t\t\td := p[i] - v.pnt[i]\n\t\t\tss += d * d\n\t\t}\n\t}\n\n\treturn ss\n}\n\n\/\/ Within calculates the sum of squares within each cluster. It returns nil if Cluster\n\/\/ has not been called.\nfunc (ms *MeanShift) Within() []float64 {\n\tif ms.centers == nil {\n\t\treturn nil\n\t}\n\tss := make([]float64, len(ms.centers))\n\n\tfor _, v := range ms.values {\n\t\tfor i := range ms.centers[0].pnt {\n\t\t\td := ms.centers[v.cluster].pnt[i] - v.pnt[i]\n\t\t\tss[v.cluster] += d * d\n\t\t}\n\t}\n\n\treturn ss\n}\n\n\/\/ Centers returns the centers determined by a previous call to Cluster.\nfunc (ms *MeanShift) Centers() []cluster.Center {\n\tcs := make([]cluster.Center, len(ms.centers))\n\tfor i := range ms.centers {\n\t\tcs[i] = &ms.centers[i]\n\t}\n\treturn cs\n}\n\n\/\/ Values returns a slice of the values in the MeanShift.\nfunc (ms *MeanShift) Values() []cluster.Value {\n\tvs := make([]cluster.Value, len(ms.values))\n\tfor i := range ms.values {\n\t\tvs[i] = &ms.values[i]\n\t}\n\treturn vs\n}\n<commit_msg>meanshift: allow failed clustering to return best effort<commit_after>\/\/ Copyright ©2012 The bíogo.cluster Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package meanshift provides mean shift clustering for ℝⁿ data.\npackage meanshift\n\nimport (\n\t\"code.google.com\/p\/biogo.cluster\"\n\t\"fmt\"\n)\n\ntype pnt []float64\n\nfunc (p pnt) V() []float64 { return p }\n\ntype value struct {\n\tpnt\n\tw       float64\n\tcluster int\n}\n\nfunc (v *value) Weight() float64 { return v.w }\nfunc (v *value) Cluster() int    { return v.cluster }\n\ntype center struct {\n\tpnt\n\tw       float64\n\tindices cluster.Indices\n}\n\nfunc (c *center) Members() cluster.Indices { return c.indices }\n\n\/\/ Shifter implements a single step of the mean shift algorithm.\ntype Shifter interface {\n\t\/\/ Init initialises the Shifter with the provided data.\n\tInit(cluster.Interface)\n\n\t\/\/ Shift performs a single iteration of the mean shift algorithm and\n\t\/\/ returns the sum of squares differences between the initial state\n\t\/\/ and the final state.\n\tShift() float64\n\n\t\/\/ Bandwidth returns the bandwidth parameter of the Shifter.\n\tBandwidth() float64\n\n\t\/\/ Centers returns the cluster centers of the clustered data.\n\tCenters() []cluster.Center\n}\n\n\/\/ MeanShift implements data clustering using the mean shift algorithm.\ntype MeanShift struct {\n\tk       Shifter\n\ttol     float64\n\tmaxIter int\n\tvalues  []value\n\tcenters []center\n\tci      []cluster.Indices\n}\n\n\/\/ New creates a new mean shift Clusterer object populated with data from an Interface value, data\n\/\/ and using the Shifter k.\nfunc New(data cluster.Interface, k Shifter, tol float64, maxIter int) *MeanShift {\n\tk.Init(data)\n\treturn &MeanShift{\n\t\tk:       k,\n\t\ttol:     tol,\n\t\tmaxIter: maxIter,\n\t\tvalues:  convert(data),\n\t}\n}\n\n\/\/ convert renders data to the internal float64 representation for a MeanShift.\nfunc convert(data cluster.Interface) []value {\n\tva := make([]value, data.Len())\n\tfor i := 0; i < data.Len(); i++ {\n\t\tva[i] = value{pnt: append(pnt(nil), data.Values(i)...)}\n\t}\n\tif w, ok := data.(cluster.Weighter); ok {\n\t\tfor i := 0; i < data.Len(); i++ {\n\t\t\tva[i].w = w.Weight(i)\n\t\t}\n\t} else {\n\t\tfor i := 0; i < data.Len(); i++ {\n\t\t\tva[i].w = 1\n\t\t}\n\t}\n\n\treturn va\n}\n\n\/\/ Cluster runs a clustering of the data using the mean shift algorithm.\nfunc (ms *MeanShift) Cluster() error {\n\tvar err error\n\tfor i := 0; ; i++ {\n\t\tdelta := ms.k.Shift()\n\t\tif delta <= ms.tol {\n\t\t\tbreak\n\t\t}\n\t\tif i > ms.maxIter {\n\t\t\terr = fmt.Errorf(\"meanshift: exceeded maximum iterations: delta=%f\", delta)\n\t\t}\n\t}\n\n\tvar cen []cluster.Center\n\tcen = ms.k.Centers()\n\tms.ci = make([]cluster.Indices, len(cen))\n\tms.centers = make([]center, len(cen))\n\tfor i, c := range cen {\n\t\tms.ci[i] = c.Members()\n\t\tms.centers[i] = center{pnt: c.V(), indices: ms.ci[i]}\n\t\tfor _, j := range ms.ci[i] {\n\t\t\tms.values[j].cluster = i\n\t\t}\n\t}\n\n\treturn err\n}\n\n\/\/ Total calculates the total sum of squares for the data relative to the data mean.\nfunc (ms *MeanShift) Total() float64 {\n\tp := make([]float64, len(ms.values[0].pnt))\n\n\tfor _, v := range ms.values {\n\t\tfor i := range p {\n\t\t\tp[i] += v.pnt[i]\n\t\t}\n\t}\n\tinv := 1 \/ float64(len(ms.values))\n\tfor i := range p {\n\t\tp[i] *= inv\n\t}\n\n\tvar ss float64\n\tfor _, v := range ms.values {\n\t\tfor i := range p {\n\t\t\td := p[i] - v.pnt[i]\n\t\t\tss += d * d\n\t\t}\n\t}\n\n\treturn ss\n}\n\n\/\/ Within calculates the sum of squares within each cluster. It returns nil if Cluster\n\/\/ has not been called.\nfunc (ms *MeanShift) Within() []float64 {\n\tif ms.centers == nil {\n\t\treturn nil\n\t}\n\tss := make([]float64, len(ms.centers))\n\n\tfor _, v := range ms.values {\n\t\tfor i := range ms.centers[0].pnt {\n\t\t\td := ms.centers[v.cluster].pnt[i] - v.pnt[i]\n\t\t\tss[v.cluster] += d * d\n\t\t}\n\t}\n\n\treturn ss\n}\n\n\/\/ Centers returns the centers determined by a previous call to Cluster.\nfunc (ms *MeanShift) Centers() []cluster.Center {\n\tcs := make([]cluster.Center, len(ms.centers))\n\tfor i := range ms.centers {\n\t\tcs[i] = &ms.centers[i]\n\t}\n\treturn cs\n}\n\n\/\/ Values returns a slice of the values in the MeanShift.\nfunc (ms *MeanShift) Values() []cluster.Value {\n\tvs := make([]cluster.Value, len(ms.values))\n\tfor i := range ms.values {\n\t\tvs[i] = &ms.values[i]\n\t}\n\treturn vs\n}\n<|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/docker\/distribution\/reference\"\n\t\"github.com\/docker\/distribution\/registry\/client\/auth\"\n\t\"github.com\/docker\/distribution\/registry\/client\/transport\"\n\tauthtypes \"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/registry\"\n\t\"github.com\/pkg\/errors\"\n)\n\ntype repositoryEndpoint struct {\n\tinfo     *registry.RepositoryInfo\n\tendpoint registry.APIEndpoint\n}\n\n\/\/ Name returns the repository name\nfunc (r repositoryEndpoint) Name() string {\n\trepoName := r.info.Name.Name()\n\t\/\/ If endpoint does not support CanonicalName, use the RemoteName instead\n\tif r.endpoint.TrimHostname {\n\t\trepoName = reference.Path(r.info.Name)\n\t}\n\treturn repoName\n}\n\n\/\/ BaseURL returns the endpoint url\nfunc (r repositoryEndpoint) BaseURL() string {\n\treturn r.endpoint.URL.String()\n}\n\nfunc newDefaultRepositoryEndpoint(ref reference.Named, insecure bool) (repositoryEndpoint, error) {\n\trepoInfo, err := registry.ParseRepositoryInfo(ref)\n\tif err != nil {\n\t\treturn repositoryEndpoint{}, err\n\t}\n\tendpoint, err := getDefaultEndpointFromRepoInfo(repoInfo)\n\tif err != nil {\n\t\treturn repositoryEndpoint{}, err\n\t}\n\tif insecure {\n\t\tendpoint.TLSConfig.InsecureSkipVerify = true\n\t}\n\treturn repositoryEndpoint{info: repoInfo, endpoint: endpoint}, nil\n}\n\nfunc getDefaultEndpointFromRepoInfo(repoInfo *registry.RepositoryInfo) (registry.APIEndpoint, error) {\n\tvar err error\n\n\toptions := registry.ServiceOptions{}\n\tregistryService, err := registry.NewService(options)\n\tif err != nil {\n\t\treturn registry.APIEndpoint{}, err\n\t}\n\tendpoints, err := registryService.LookupPushEndpoints(reference.Domain(repoInfo.Name))\n\tif err != nil {\n\t\treturn registry.APIEndpoint{}, err\n\t}\n\t\/\/ Default to the highest priority endpoint to return\n\tendpoint := endpoints[0]\n\tif !repoInfo.Index.Secure {\n\t\tfor _, ep := range endpoints {\n\t\t\tif ep.URL.Scheme == \"http\" {\n\t\t\t\tendpoint = ep\n\t\t\t}\n\t\t}\n\t}\n\treturn endpoint, nil\n}\n\n\/\/ getHTTPTransport builds a transport for use in communicating with a registry\nfunc getHTTPTransport(authConfig authtypes.AuthConfig, endpoint registry.APIEndpoint, repoName string, userAgent string) (http.RoundTripper, error) {\n\t\/\/ get the http transport, this will be used in a client to upload manifest\n\tbase := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout:   30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t\tDualStack: true,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tTLSClientConfig:     endpoint.TLSConfig,\n\t\tDisableKeepAlives:   true,\n\t}\n\n\tmodifiers := registry.Headers(userAgent, http.Header{})\n\tauthTransport := transport.NewTransport(base, modifiers...)\n\tchallengeManager, confirmedV2, err := registry.PingV2Registry(endpoint.URL, authTransport)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error pinging v2 registry\")\n\t}\n\tif !confirmedV2 {\n\t\treturn nil, fmt.Errorf(\"unsupported registry version\")\n\t}\n\tif authConfig.RegistryToken != \"\" {\n\t\tpassThruTokenHandler := &existingTokenHandler{token: authConfig.RegistryToken}\n\t\tmodifiers = append(modifiers, auth.NewAuthorizer(challengeManager, passThruTokenHandler))\n\t} else {\n\t\tcreds := registry.NewStaticCredentialStore(&authConfig)\n\t\ttokenHandler := auth.NewTokenHandler(authTransport, creds, repoName, \"*\")\n\t\tbasicHandler := auth.NewBasicHandler(creds)\n\t\tmodifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler))\n\t}\n\treturn transport.NewTransport(base, modifiers...), nil\n}\n\n\/\/ RepoNameForReference returns the repository name from a reference\nfunc RepoNameForReference(ref reference.Named) (string, error) {\n\t\/\/ insecure is fine since this only returns the name\n\trepo, err := newDefaultRepositoryEndpoint(ref, false)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn repo.Name(), nil\n}\n\ntype existingTokenHandler struct {\n\ttoken string\n}\n\nfunc (th *existingTokenHandler) AuthorizeRequest(req *http.Request, params map[string]string) error {\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", th.token))\n\treturn nil\n}\n\nfunc (th *existingTokenHandler) Scheme() string {\n\treturn \"bearer\"\n}\n<commit_msg>specify specific permissions<commit_after>package client\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/docker\/distribution\/reference\"\n\t\"github.com\/docker\/distribution\/registry\/client\/auth\"\n\t\"github.com\/docker\/distribution\/registry\/client\/transport\"\n\tauthtypes \"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/registry\"\n\t\"github.com\/pkg\/errors\"\n)\n\ntype repositoryEndpoint struct {\n\tinfo     *registry.RepositoryInfo\n\tendpoint registry.APIEndpoint\n}\n\n\/\/ Name returns the repository name\nfunc (r repositoryEndpoint) Name() string {\n\trepoName := r.info.Name.Name()\n\t\/\/ If endpoint does not support CanonicalName, use the RemoteName instead\n\tif r.endpoint.TrimHostname {\n\t\trepoName = reference.Path(r.info.Name)\n\t}\n\treturn repoName\n}\n\n\/\/ BaseURL returns the endpoint url\nfunc (r repositoryEndpoint) BaseURL() string {\n\treturn r.endpoint.URL.String()\n}\n\nfunc newDefaultRepositoryEndpoint(ref reference.Named, insecure bool) (repositoryEndpoint, error) {\n\trepoInfo, err := registry.ParseRepositoryInfo(ref)\n\tif err != nil {\n\t\treturn repositoryEndpoint{}, err\n\t}\n\tendpoint, err := getDefaultEndpointFromRepoInfo(repoInfo)\n\tif err != nil {\n\t\treturn repositoryEndpoint{}, err\n\t}\n\tif insecure {\n\t\tendpoint.TLSConfig.InsecureSkipVerify = true\n\t}\n\treturn repositoryEndpoint{info: repoInfo, endpoint: endpoint}, nil\n}\n\nfunc getDefaultEndpointFromRepoInfo(repoInfo *registry.RepositoryInfo) (registry.APIEndpoint, error) {\n\tvar err error\n\n\toptions := registry.ServiceOptions{}\n\tregistryService, err := registry.NewService(options)\n\tif err != nil {\n\t\treturn registry.APIEndpoint{}, err\n\t}\n\tendpoints, err := registryService.LookupPushEndpoints(reference.Domain(repoInfo.Name))\n\tif err != nil {\n\t\treturn registry.APIEndpoint{}, err\n\t}\n\t\/\/ Default to the highest priority endpoint to return\n\tendpoint := endpoints[0]\n\tif !repoInfo.Index.Secure {\n\t\tfor _, ep := range endpoints {\n\t\t\tif ep.URL.Scheme == \"http\" {\n\t\t\t\tendpoint = ep\n\t\t\t}\n\t\t}\n\t}\n\treturn endpoint, nil\n}\n\n\/\/ getHTTPTransport builds a transport for use in communicating with a registry\nfunc getHTTPTransport(authConfig authtypes.AuthConfig, endpoint registry.APIEndpoint, repoName string, userAgent string) (http.RoundTripper, error) {\n\t\/\/ get the http transport, this will be used in a client to upload manifest\n\tbase := &http.Transport{\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout:   30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t\tDualStack: true,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\tTLSClientConfig:     endpoint.TLSConfig,\n\t\tDisableKeepAlives:   true,\n\t}\n\n\tmodifiers := registry.Headers(userAgent, http.Header{})\n\tauthTransport := transport.NewTransport(base, modifiers...)\n\tchallengeManager, confirmedV2, err := registry.PingV2Registry(endpoint.URL, authTransport)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error pinging v2 registry\")\n\t}\n\tif !confirmedV2 {\n\t\treturn nil, fmt.Errorf(\"unsupported registry version\")\n\t}\n\tif authConfig.RegistryToken != \"\" {\n\t\tpassThruTokenHandler := &existingTokenHandler{token: authConfig.RegistryToken}\n\t\tmodifiers = append(modifiers, auth.NewAuthorizer(challengeManager, passThruTokenHandler))\n\t} else {\n\t\tcreds := registry.NewStaticCredentialStore(&authConfig)\n\t\ttokenHandler := auth.NewTokenHandler(authTransport, creds, repoName, \"push\", \"pull\")\n\t\tbasicHandler := auth.NewBasicHandler(creds)\n\t\tmodifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler))\n\t}\n\treturn transport.NewTransport(base, modifiers...), nil\n}\n\n\/\/ RepoNameForReference returns the repository name from a reference\nfunc RepoNameForReference(ref reference.Named) (string, error) {\n\t\/\/ insecure is fine since this only returns the name\n\trepo, err := newDefaultRepositoryEndpoint(ref, false)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn repo.Name(), nil\n}\n\ntype existingTokenHandler struct {\n\ttoken string\n}\n\nfunc (th *existingTokenHandler) AuthorizeRequest(req *http.Request, params map[string]string) error {\n\treq.Header.Set(\"Authorization\", fmt.Sprintf(\"Bearer %s\", th.token))\n\treturn nil\n}\n\nfunc (th *existingTokenHandler) Scheme() string {\n\treturn \"bearer\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package igc\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com\/d4l3k\/messagediff\"\n\t\"github.com\/twpayne\/go-geom\"\n)\n\nfunc TestDecode(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\ts string\n\t\tt *T\n\t}{\n\t\t{\n\t\t\ts: \"AXTR20C38FF2C110\\r\\n\" +\n\t\t\t\t\"HFDTE151115\\r\\n\" +\n\t\t\t\t\"B1316284654230N00839078EA0147801630\\r\\n\",\n\t\t\tt: &T{\n\t\t\t\tHeaders: []Header{\n\t\t\t\t\t{Source: \"F\", Key: \"DTE\", KeyExtra: \"\", Value: \"151115\"},\n\t\t\t\t},\n\t\t\t\tLineString: geom.NewLineString(geom.Layout(5)).MustSetCoords([]geom.Coord{\n\t\t\t\t\t{8.6513, 46.90383333333333, 1630, 1447593388, 1478},\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\ts: \"ACPP274CPILOT - s\/n:11002274\\r\\n\" +\n\t\t\t\t\"HFDTE020613\\r\\n\" +\n\t\t\t\t\"I033638FXA3940SIU4141TDS\\r\\n\" +\n\t\t\t\t\"B1053525151892N00203986WA0017900275000108\\r\\n\",\n\t\t\tt: &T{\n\t\t\t\tHeaders: []Header{\n\t\t\t\t\t{Source: \"F\", Key: \"DTE\", KeyExtra: \"\", Value: \"020613\"},\n\t\t\t\t},\n\t\t\t\tLineString: geom.NewLineString(geom.Layout(5)).MustSetCoords([]geom.Coord{\n\t\t\t\t\t{-2.0664333333333333, 51.864866666666664, 275, 1370170432.8, 179},\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\ts: \"AXCC64BCompCheck-3.2\\r\\n\" +\n\t\t\t\t\"HFDTE100810\\r\\n\" +\n\t\t\t\t\"I033637LAD3839LOD4040TDS\\r\\n\" +\n\t\t\t\t\"B1146174031985N00726775WA010040114912340\",\n\t\t\tt: &T{\n\t\t\t\tHeaders: []Header{\n\t\t\t\t\t{Source: \"F\", Key: \"DTE\", KeyExtra: \"\", Value: \"100810\"},\n\t\t\t\t},\n\t\t\t\tLineString: geom.NewLineString(geom.Layout(5)).MustSetCoords([]geom.Coord{\n\t\t\t\t\t{-7.446255666666667, 40.53308533333333, 1149, 1281440777, 1004},\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\ts: \"AXGD Flymaster LiveSD  SN03142  SW1.07b\\r\\n\" +\n\t\t\t\t\"HFDTEDATE:220418,01\\r\\n\" +\n\t\t\t\t\"B1316284654230N00839078EA0147801630\\r\\n\",\n\t\t\tt: &T{\n\t\t\t\tHeaders: []Header{\n\t\t\t\t\t{Source: \"F\", Key: \"DTE\", KeyExtra: \"DATE\", Value: \"220418,01\"},\n\t\t\t\t},\n\t\t\t\tLineString: geom.NewLineString(geom.Layout(5)).MustSetCoords([]geom.Coord{\n\t\t\t\t\t{8.6513, 46.90383333333333, 1630, 1524402988, 1478},\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t} {\n\t\tgot, err := Read(bytes.NewBufferString(tc.s))\n\t\tdiff, equal := messagediff.PrettyDiff(tc.t, got)\n\t\tif err != nil || !equal {\n\t\t\tt.Errorf(\"Read(...(%#v)) == %#v, %v, want nil, %#v\\n%s\", tc.s, got, err, tc.t, diff)\n\t\t}\n\t}\n}\n\nfunc TestDecodeHeaders(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\ts string\n\t\tt *T\n\t}{\n\t\t{\n\t\t\ts: \"AFLY05094\\r\\n\" +\n\t\t\t\t\"HFDTE210407\\r\\n\" +\n\t\t\t\t\"HFFXA100\\r\\n\" +\n\t\t\t\t\"HFPLTPILOT:Tom Payne\\r\\n\" +\n\t\t\t\t\"HFGTYGLIDERTYPE:Gradient Aspen\\r\\n\" +\n\t\t\t\t\"HFGIDGLIDERID:G12242505057\\r\\n\" +\n\t\t\t\t\"HFDTM100GPSDATUM:WGS84\\r\\n\" +\n\t\t\t\t\"HFGPSGPS:FURUNO GH-80\\r\\n\" +\n\t\t\t\t\"HFRFWFIRMWAREVERSION:1.16\\r\\n\" +\n\t\t\t\t\"HFRHWHARDWAREVERSION:1.00\\r\\n\" +\n\t\t\t\t\"HFFTYFRTYPE:FLYTEC,5020\\r\\n\",\n\t\t\tt: &T{\n\t\t\t\tHeaders: []Header{\n\t\t\t\t\t{Source: \"F\", Key: \"DTE\", KeyExtra: \"\", Value: \"210407\"},\n\t\t\t\t\t{Source: \"F\", Key: \"FXA\", KeyExtra: \"\", Value: \"100\"},\n\t\t\t\t\t{Source: \"F\", Key: \"PLT\", KeyExtra: \"PILOT\", Value: \"Tom Payne\"},\n\t\t\t\t\t{Source: \"F\", Key: \"GTY\", KeyExtra: \"GLIDERTYPE\", Value: \"Gradient Aspen\"},\n\t\t\t\t\t{Source: \"F\", Key: \"GID\", KeyExtra: \"GLIDERID\", Value: \"G12242505057\"},\n\t\t\t\t\t{Source: \"F\", Key: \"DTM\", KeyExtra: \"100GPSDATUM\", Value: \"WGS84\"},\n\t\t\t\t\t{Source: \"F\", Key: \"GPS\", KeyExtra: \"GPS\", Value: \"FURUNO GH-80\"},\n\t\t\t\t\t{Source: \"F\", Key: \"RFW\", KeyExtra: \"FIRMWAREVERSION\", Value: \"1.16\"},\n\t\t\t\t\t{Source: \"F\", Key: \"RHW\", KeyExtra: \"HARDWAREVERSION\", Value: \"1.00\"},\n\t\t\t\t\t{Source: \"F\", Key: \"FTY\", KeyExtra: \"FRTYPE\", Value: \"FLYTEC,5020\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t} {\n\t\tgot, err := Read(bytes.NewBufferString(tc.s))\n\t\tdiff, equal := messagediff.PrettyDiff(got.Headers, tc.t.Headers)\n\t\tif err != nil || !equal {\n\t\t\tt.Errorf(\"Read(...(%#v)) == %#v, %v, want nil, %#v\\n%s\", tc.s, got, err, tc.t, diff)\n\t\t}\n\t}\n}\n<commit_msg>Print diffs in tests<commit_after>package igc\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com\/d4l3k\/messagediff\"\n\t\"github.com\/twpayne\/go-geom\"\n)\n\nfunc TestDecode(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\ts string\n\t\tt *T\n\t}{\n\t\t{\n\t\t\ts: \"AXTR20C38FF2C110\\r\\n\" +\n\t\t\t\t\"HFDTE151115\\r\\n\" +\n\t\t\t\t\"B1316284654230N00839078EA0147801630\\r\\n\",\n\t\t\tt: &T{\n\t\t\t\tHeaders: []Header{\n\t\t\t\t\t{Source: \"F\", Key: \"DTE\", KeyExtra: \"\", Value: \"151115\"},\n\t\t\t\t},\n\t\t\t\tLineString: geom.NewLineString(geom.Layout(5)).MustSetCoords([]geom.Coord{\n\t\t\t\t\t{8.6513, 46.90383333333333, 1630, 1447593388, 1478},\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\ts: \"ACPP274CPILOT - s\/n:11002274\\r\\n\" +\n\t\t\t\t\"HFDTE020613\\r\\n\" +\n\t\t\t\t\"I033638FXA3940SIU4141TDS\\r\\n\" +\n\t\t\t\t\"B1053525151892N00203986WA0017900275000108\\r\\n\",\n\t\t\tt: &T{\n\t\t\t\tHeaders: []Header{\n\t\t\t\t\t{Source: \"F\", Key: \"DTE\", KeyExtra: \"\", Value: \"020613\"},\n\t\t\t\t},\n\t\t\t\tLineString: geom.NewLineString(geom.Layout(5)).MustSetCoords([]geom.Coord{\n\t\t\t\t\t{-2.0664333333333333, 51.864866666666664, 275, 1370170432.8, 179},\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\ts: \"AXCC64BCompCheck-3.2\\r\\n\" +\n\t\t\t\t\"HFDTE100810\\r\\n\" +\n\t\t\t\t\"I033637LAD3839LOD4040TDS\\r\\n\" +\n\t\t\t\t\"B1146174031985N00726775WA010040114912340\",\n\t\t\tt: &T{\n\t\t\t\tHeaders: []Header{\n\t\t\t\t\t{Source: \"F\", Key: \"DTE\", KeyExtra: \"\", Value: \"100810\"},\n\t\t\t\t},\n\t\t\t\tLineString: geom.NewLineString(geom.Layout(5)).MustSetCoords([]geom.Coord{\n\t\t\t\t\t{-7.446255666666667, 40.53308533333333, 1149, 1281440777, 1004},\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\ts: \"AXGD Flymaster LiveSD  SN03142  SW1.07b\\r\\n\" +\n\t\t\t\t\"HFDTEDATE:220418,01\\r\\n\" +\n\t\t\t\t\"B1316284654230N00839078EA0147801630\\r\\n\",\n\t\t\tt: &T{\n\t\t\t\tHeaders: []Header{\n\t\t\t\t\t{Source: \"F\", Key: \"DTE\", KeyExtra: \"DATE\", Value: \"220418,01\"},\n\t\t\t\t},\n\t\t\t\tLineString: geom.NewLineString(geom.Layout(5)).MustSetCoords([]geom.Coord{\n\t\t\t\t\t{8.6513, 46.90383333333333, 1630, 1524402988, 1478},\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t} {\n\t\tgot, err := Read(bytes.NewBufferString(tc.s))\n\t\tdiff, equal := \"\", true\n\t\tif err == nil {\n\t\t\tdiff, equal = messagediff.PrettyDiff(tc.t, got)\n\t\t}\n\t\tif err != nil || !equal {\n\t\t\tt.Errorf(\"Read(...(%#v)) == %#v, %v, want nil, %#v\\n%s\", tc.s, got, err, tc.t, diff)\n\t\t}\n\t}\n}\n\nfunc TestDecodeHeaders(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\ts string\n\t\tt *T\n\t}{\n\t\t{\n\t\t\ts: \"AFLY05094\\r\\n\" +\n\t\t\t\t\"HFDTE210407\\r\\n\" +\n\t\t\t\t\"HFFXA100\\r\\n\" +\n\t\t\t\t\"HFPLTPILOT:Tom Payne\\r\\n\" +\n\t\t\t\t\"HFGTYGLIDERTYPE:Gradient Aspen\\r\\n\" +\n\t\t\t\t\"HFGIDGLIDERID:G12242505057\\r\\n\" +\n\t\t\t\t\"HFDTM100GPSDATUM:WGS84\\r\\n\" +\n\t\t\t\t\"HFGPSGPS:FURUNO GH-80\\r\\n\" +\n\t\t\t\t\"HFRFWFIRMWAREVERSION:1.16\\r\\n\" +\n\t\t\t\t\"HFRHWHARDWAREVERSION:1.00\\r\\n\" +\n\t\t\t\t\"HFFTYFRTYPE:FLYTEC,5020\\r\\n\",\n\t\t\tt: &T{\n\t\t\t\tHeaders: []Header{\n\t\t\t\t\t{Source: \"F\", Key: \"DTE\", KeyExtra: \"\", Value: \"210407\"},\n\t\t\t\t\t{Source: \"F\", Key: \"FXA\", KeyExtra: \"\", Value: \"100\"},\n\t\t\t\t\t{Source: \"F\", Key: \"PLT\", KeyExtra: \"PILOT\", Value: \"Tom Payne\"},\n\t\t\t\t\t{Source: \"F\", Key: \"GTY\", KeyExtra: \"GLIDERTYPE\", Value: \"Gradient Aspen\"},\n\t\t\t\t\t{Source: \"F\", Key: \"GID\", KeyExtra: \"GLIDERID\", Value: \"G12242505057\"},\n\t\t\t\t\t{Source: \"F\", Key: \"DTM\", KeyExtra: \"100GPSDATUM\", Value: \"WGS84\"},\n\t\t\t\t\t{Source: \"F\", Key: \"GPS\", KeyExtra: \"GPS\", Value: \"FURUNO GH-80\"},\n\t\t\t\t\t{Source: \"F\", Key: \"RFW\", KeyExtra: \"FIRMWAREVERSION\", Value: \"1.16\"},\n\t\t\t\t\t{Source: \"F\", Key: \"RHW\", KeyExtra: \"HARDWAREVERSION\", Value: \"1.00\"},\n\t\t\t\t\t{Source: \"F\", Key: \"FTY\", KeyExtra: \"FRTYPE\", Value: \"FLYTEC,5020\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t} {\n\t\tgot, err := Read(bytes.NewBufferString(tc.s))\n\t\tdiff, equal := \"\", true\n\t\tif err == nil {\n\t\t\tdiff, equal = messagediff.PrettyDiff(tc.t.Headers, got.Headers)\n\t\t}\n\t\tif err != nil || !equal {\n\t\t\tt.Errorf(\"Read(...(%#v)) == %#v, %v, want nil, %#v\\n%s\", tc.s, got, err, tc.t, diff)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Made local runs also output log data.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ +build !linux\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfmt.Println(\n\t\t\"this driver was built on a non-linux machine, so it is \" +\n\t\t\t\"unavailable. Please re-build minikube on a linux machine to enable \" +\n\t\t\t\"it.\",\n\t)\n\tos.Exit(1)\n}\n<commit_msg>Adding proper boilerplate<commit_after>\/\/ +build !linux\n\n\/*\nCopyright 2016 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfmt.Println(\n\t\t\"this driver was built on a non-linux machine, so it is \" +\n\t\t\t\"unavailable. Please re-build minikube on a linux machine to enable \" +\n\t\t\t\"it.\",\n\t)\n\tos.Exit(1)\n}\n<|endoftext|>"}
{"text":"<commit_before>package mirror\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/funkygao\/gafka\"\n\t\"github.com\/funkygao\/gafka\/ctx\"\n\t\"github.com\/funkygao\/gafka\/zk\"\n\t\"github.com\/funkygao\/golib\/gofmt\"\n\t\"github.com\/funkygao\/golib\/ratelimiter\"\n\t\"github.com\/funkygao\/golib\/signal\"\n\tlog \"github.com\/funkygao\/log4go\"\n)\n\n\/\/ target kafka auto.create.topics.enable=true\ntype Mirror struct {\n\tConfig\n\n\tquit chan struct{}\n\tonce sync.Once\n\n\ttransferN     int64\n\ttransferBytes int64\n\n\tbandwidthRateLimiter *ratelimiter.LeakyBucket\n}\n\nfunc New(cf *Config) *Mirror {\n\treturn &Mirror{Config: *cf}\n}\n\nfunc (this *Mirror) Main() (exitCode int) {\n\tthis.quit = make(chan struct{})\n\tsignal.RegisterHandler(func(sig os.Signal) {\n\t\tlog.Info(\"received signal: %s\", strings.ToUpper(sig.String()))\n\t\tlog.Info(\"quiting...\")\n\n\t\tthis.once.Do(func() {\n\t\t\tclose(this.quit)\n\t\t})\n\t}, syscall.SIGINT, syscall.SIGTERM)\n\n\tlimit := (1 << 20) * this.BandwidthLimit \/ 8\n\tif this.BandwidthLimit > 0 {\n\t\tthis.bandwidthRateLimiter = ratelimiter.NewLeakyBucket(limit*10, time.Second*10)\n\t}\n\n\tlog.Info(\"starting mirror@%s\", gafka.BuildId)\n\n\t\/\/ pprof\n\tdebugAddr := \":10009\"\n\tgo http.ListenAndServe(debugAddr, nil)\n\tlog.Info(\"pprof ready on %s\", debugAddr)\n\n\tz1 := zk.NewZkZone(zk.DefaultConfig(this.Z1, ctx.ZoneZkAddrs(this.Z1)))\n\tz2 := zk.NewZkZone(zk.DefaultConfig(this.Z2, ctx.ZoneZkAddrs(this.Z2)))\n\tc1 := z1.NewCluster(this.C1)\n\tc2 := z2.NewCluster(this.C2)\n\n\tthis.runMirror(c1, c2, limit)\n\n\tlog.Info(\"bye mirror@%s\", gafka.BuildId)\n\tlog.Close()\n\n\treturn\n}\n\nfunc (this *Mirror) runMirror(c1, c2 *zk.ZkCluster, limit int64) {\n\tlog.Info(\"start [%s\/%s] -> [%s\/%s] with bandwidth %sbps\",\n\t\tc1.ZkZone().Name(), c1.Name(),\n\t\tc2.ZkZone().Name(), c2.Name(),\n\t\tgofmt.Comma(limit*8))\n\n\tpub, err := this.makePub(c2)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Trace(\"pub[%s\/%s] made\", c2.ZkZone().Name(), c2.Name())\n\n\tgo func(pub sarama.AsyncProducer, c *zk.ZkCluster) {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-this.quit:\n\t\t\t\treturn\n\n\t\t\tcase err := <-pub.Errors():\n\t\t\t\t\/\/ TODO\n\t\t\t\tlog.Error(\"pub[%s\/%s] %v\", c.ZkZone().Name(), c.Name(), err)\n\t\t\t}\n\t\t}\n\t}(pub, c2)\n\n\tgroup := this.groupName(c1, c2)\n\tever := true\n\tfor ever {\n\t\ttopics, topicsChanges, err := c1.WatchTopics()\n\t\tif err != nil {\n\t\t\tlog.Error(\"[%s\/%s]watch topics: %v\", c1.ZkZone().Name(), c1.Name(), err)\n\t\t\ttime.Sleep(time.Second * 10)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ TODO remove '__consumer_offsets' from topics\n\t\tsub, err := this.makeSub(c1, group, topics)\n\t\tif err != nil {\n\t\t\t\/\/ TODO how to handle this err?\n\t\t\tlog.Error(err)\n\t\t\ttime.Sleep(time.Second * 10)\n\t\t}\n\n\t\tlog.Info(\"starting pump [%s\/%s] -> [%s\/%s] with group %s\",\n\t\t\tc1.ZkZone().Name(), c1.Name(),\n\t\t\tc2.ZkZone().Name(), c2.Name(), group)\n\n\t\tpumpStopper := make(chan struct{})\n\t\tpumpStopped := make(chan struct{})\n\t\tgo this.pump(sub, pub, pumpStopper, pumpStopped)\n\n\t\tselect {\n\t\tcase <-topicsChanges:\n\t\t\t\/\/ TODO log the diff the topics\n\t\t\tlog.Warn(\"[%s\/%s] topics changed, stopping pump...\", c1.Name(), c2.Name())\n\t\t\tpumpStopper <- struct{}{} \/\/ stop pump\n\t\t\t<-pumpStopped             \/\/ await pump cleanup\n\n\t\t\t\/\/ refresh c1 topics\n\t\t\ttopics, err = c1.Topics()\n\t\t\tif err != nil {\n\t\t\t\t\/\/ TODO how to handle this err?\n\t\t\t\tlog.Error(err)\n\t\t\t\ttime.Sleep(time.Second * 10)\n\t\t\t}\n\n\t\t\tlog.Info(\"[%s\/%s] topics: %+v\", c1.ZkZone().Name(), c1.Name(), topics)\n\n\t\tcase <-this.quit:\n\t\t\tlog.Info(\"awaiting pump cleanup...\")\n\t\t\t<-pumpStopped\n\n\t\t\tever = false\n\n\t\tcase <-pumpStopped:\n\t\t\t\/\/ pump encounters problems, just retry\n\t\t\tlog.Warn(\"pump stopped for ?\")\n\t\t}\n\t}\n\n\tlog.Info(\"total transferred: %s %smsgs\",\n\t\tgofmt.ByteSize(this.transferBytes),\n\t\tgofmt.Comma(this.transferN))\n\n\tlog.Info(\"closing pub...\")\n\tpub.Close()\n}\n\nfunc (this *Mirror) groupName(c1, c2 *zk.ZkCluster) string {\n\treturn fmt.Sprintf(\"_mirror_.%s.%s.%s.%s\", c1.ZkZone().Name(), c1.Name(), c2.ZkZone().Name(), c2.Name())\n}\n<commit_msg>record life span of mirror<commit_after>package mirror\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/funkygao\/gafka\"\n\t\"github.com\/funkygao\/gafka\/ctx\"\n\t\"github.com\/funkygao\/gafka\/zk\"\n\t\"github.com\/funkygao\/golib\/gofmt\"\n\t\"github.com\/funkygao\/golib\/ratelimiter\"\n\t\"github.com\/funkygao\/golib\/signal\"\n\tlog \"github.com\/funkygao\/log4go\"\n)\n\n\/\/ target kafka auto.create.topics.enable=true\ntype Mirror struct {\n\tConfig\n\n\tstartedAt time.Time\n\tquit      chan struct{}\n\tonce      sync.Once\n\n\ttransferN     int64\n\ttransferBytes int64\n\n\tbandwidthRateLimiter *ratelimiter.LeakyBucket\n}\n\nfunc New(cf *Config) *Mirror {\n\treturn &Mirror{Config: *cf}\n}\n\nfunc (this *Mirror) Main() (exitCode int) {\n\tthis.quit = make(chan struct{})\n\tsignal.RegisterHandler(func(sig os.Signal) {\n\t\tlog.Info(\"received signal: %s\", strings.ToUpper(sig.String()))\n\t\tlog.Info(\"quiting...\")\n\n\t\tthis.once.Do(func() {\n\t\t\tclose(this.quit)\n\t\t})\n\t}, syscall.SIGINT, syscall.SIGTERM)\n\n\tlimit := (1 << 20) * this.BandwidthLimit \/ 8\n\tif this.BandwidthLimit > 0 {\n\t\tthis.bandwidthRateLimiter = ratelimiter.NewLeakyBucket(limit*10, time.Second*10)\n\t}\n\n\tlog.Info(\"starting mirror@%s\", gafka.BuildId)\n\n\t\/\/ pprof\n\tdebugAddr := \":10009\"\n\tgo http.ListenAndServe(debugAddr, nil)\n\tlog.Info(\"pprof ready on %s\", debugAddr)\n\n\tz1 := zk.NewZkZone(zk.DefaultConfig(this.Z1, ctx.ZoneZkAddrs(this.Z1)))\n\tz2 := zk.NewZkZone(zk.DefaultConfig(this.Z2, ctx.ZoneZkAddrs(this.Z2)))\n\tc1 := z1.NewCluster(this.C1)\n\tc2 := z2.NewCluster(this.C2)\n\n\tthis.runMirror(c1, c2, limit)\n\n\tlog.Info(\"bye mirror@%s, %s\", gafka.BuildId, time.Since(this.startedAt))\n\tlog.Close()\n\n\treturn\n}\n\nfunc (this *Mirror) runMirror(c1, c2 *zk.ZkCluster, limit int64) {\n\tthis.startedAt = time.Now()\n\n\tlog.Info(\"start [%s\/%s] -> [%s\/%s] with bandwidth %sbps\",\n\t\tc1.ZkZone().Name(), c1.Name(),\n\t\tc2.ZkZone().Name(), c2.Name(),\n\t\tgofmt.Comma(limit*8))\n\n\tpub, err := this.makePub(c2)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Trace(\"pub[%s\/%s] made\", c2.ZkZone().Name(), c2.Name())\n\n\tgo func(pub sarama.AsyncProducer, c *zk.ZkCluster) {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-this.quit:\n\t\t\t\treturn\n\n\t\t\tcase err := <-pub.Errors():\n\t\t\t\t\/\/ TODO\n\t\t\t\tlog.Error(\"pub[%s\/%s] %v\", c.ZkZone().Name(), c.Name(), err)\n\t\t\t}\n\t\t}\n\t}(pub, c2)\n\n\tgroup := this.groupName(c1, c2)\n\tever := true\n\tfor ever {\n\t\ttopics, topicsChanges, err := c1.WatchTopics()\n\t\tif err != nil {\n\t\t\tlog.Error(\"[%s\/%s]watch topics: %v\", c1.ZkZone().Name(), c1.Name(), err)\n\t\t\ttime.Sleep(time.Second * 10)\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ TODO remove '__consumer_offsets' from topics\n\t\tsub, err := this.makeSub(c1, group, topics)\n\t\tif err != nil {\n\t\t\t\/\/ TODO how to handle this err?\n\t\t\tlog.Error(err)\n\t\t\ttime.Sleep(time.Second * 10)\n\t\t}\n\n\t\tlog.Info(\"starting pump [%s\/%s] -> [%s\/%s] with group %s\",\n\t\t\tc1.ZkZone().Name(), c1.Name(),\n\t\t\tc2.ZkZone().Name(), c2.Name(), group)\n\n\t\tpumpStopper := make(chan struct{})\n\t\tpumpStopped := make(chan struct{})\n\t\tgo this.pump(sub, pub, pumpStopper, pumpStopped)\n\n\t\tselect {\n\t\tcase <-topicsChanges:\n\t\t\t\/\/ TODO log the diff the topics\n\t\t\tlog.Warn(\"[%s\/%s] topics changed, stopping pump...\", c1.Name(), c2.Name())\n\t\t\tpumpStopper <- struct{}{} \/\/ stop pump\n\t\t\t<-pumpStopped             \/\/ await pump cleanup\n\n\t\t\t\/\/ refresh c1 topics\n\t\t\ttopics, err = c1.Topics()\n\t\t\tif err != nil {\n\t\t\t\t\/\/ TODO how to handle this err?\n\t\t\t\tlog.Error(err)\n\t\t\t\ttime.Sleep(time.Second * 10)\n\t\t\t}\n\n\t\t\tlog.Info(\"[%s\/%s] topics: %+v\", c1.ZkZone().Name(), c1.Name(), topics)\n\n\t\tcase <-this.quit:\n\t\t\tlog.Info(\"awaiting pump cleanup...\")\n\t\t\t<-pumpStopped\n\n\t\t\tever = false\n\n\t\tcase <-pumpStopped:\n\t\t\t\/\/ pump encounters problems, just retry\n\t\t\tlog.Warn(\"pump stopped for ?\")\n\t\t}\n\t}\n\n\tlog.Info(\"total transferred: %s %smsgs\",\n\t\tgofmt.ByteSize(this.transferBytes),\n\t\tgofmt.Comma(this.transferN))\n\n\tlog.Info(\"closing pub...\")\n\tpub.Close()\n}\n\nfunc (this *Mirror) groupName(c1, c2 *zk.ZkCluster) string {\n\treturn fmt.Sprintf(\"_mirror_.%s.%s.%s.%s\", c1.ZkZone().Name(), c1.Name(), c2.ZkZone().Name(), c2.Name())\n}\n<|endoftext|>"}
{"text":"<commit_before>package swarm\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\tspipe \"github.com\/jbenet\/go-ipfs\/crypto\/spipe\"\n\tconn \"github.com\/jbenet\/go-ipfs\/net\/conn\"\n\tmsg \"github.com\/jbenet\/go-ipfs\/net\/message\"\n\tversion \"github.com\/jbenet\/go-ipfs\/net\/version\"\n\n\tproto \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/goprotobuf\/proto\"\n\tma \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr\"\n\tmanet \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr\/net\"\n)\n\n\/\/ Open listeners for each network the swarm should listen on\nfunc (s *Swarm) listen() error {\n\thasErr := false\n\tretErr := &ListenErr{\n\t\tErrors: make([]error, len(s.local.Addresses)),\n\t}\n\n\t\/\/ listen on every address\n\tfor i, addr := range s.local.Addresses {\n\t\terr := s.connListen(addr)\n\t\tif err != nil {\n\t\t\thasErr = true\n\t\t\tretErr.Errors[i] = err\n\t\t\tlog.Error(\"Failed to listen on: %s - %s\", addr, err)\n\t\t}\n\t}\n\n\tif hasErr {\n\t\treturn retErr\n\t}\n\treturn nil\n}\n\n\/\/ Listen for new connections on the given multiaddr\nfunc (s *Swarm) connListen(maddr ma.Multiaddr) error {\n\tlist, err := manet.Listen(maddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ NOTE: this may require a lock around it later. currently, only run on setup\n\ts.listeners = append(s.listeners, list)\n\n\t\/\/ Accept and handle new connections on this listener until it errors\n\tgo func() {\n\t\tfor {\n\t\t\tnconn, err := list.Accept()\n\t\t\tif err != nil {\n\t\t\t\te := fmt.Errorf(\"Failed to accept connection: %s - %s\", maddr, err)\n\t\t\t\ts.errChan <- e\n\n\t\t\t\t\/\/ if cancel is nil, we're closed.\n\t\t\t\tif s.cancel == nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgo s.handleIncomingConn(nconn)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil\n}\n\n\/\/ Handle getting ID from this peer, handshake, and adding it into the map\nfunc (s *Swarm) handleIncomingConn(nconn manet.Conn) {\n\n\taddr := nconn.RemoteMultiaddr()\n\n\t\/\/ Construct conn with nil peer for now, because we don't know its ID yet.\n\t\/\/ connSetup will figure this out, and pull out \/ construct the peer.\n\tc, err := conn.NewConn(nil, addr, nconn)\n\tif err != nil {\n\t\ts.errChan <- err\n\t\treturn\n\t}\n\n\t\/\/ Setup the new connection\n\terr = s.connSetup(c)\n\tif err != nil && err != ErrAlreadyOpen {\n\t\ts.errChan <- err\n\t\tc.Close()\n\t}\n}\n\n\/\/ connSetup adds the passed in connection to its peerMap and starts\n\/\/ the fanIn routine for that connection\nfunc (s *Swarm) connSetup(c *conn.Conn) error {\n\tif c == nil {\n\t\treturn errors.New(\"Tried to start nil connection.\")\n\t}\n\n\tif c.Peer != nil {\n\t\tlog.Debug(\"Starting connection: %s\", c.Peer)\n\t} else {\n\t\tlog.Debug(\"Starting connection: [unknown peer]\")\n\t}\n\n\tif err := s.connSecure(c); err != nil {\n\t\treturn fmt.Errorf(\"Conn securing error: %v\", err)\n\t}\n\n\tlog.Debug(\"Secured connection: %s\", c.Peer)\n\n\t\/\/ add address of connection to Peer. Maybe it should happen in connSecure.\n\tc.Peer.AddAddress(c.Addr)\n\n\tif err := s.connVersionExchange(c); err != nil {\n\t\treturn fmt.Errorf(\"Conn version exchange error: %v\", err)\n\t}\n\n\t\/\/ add to conns\n\ts.connsLock.Lock()\n\tif _, ok := s.conns[c.Peer.Key()]; ok {\n\t\tlog.Debug(\"Conn already open!\")\n\t\ts.connsLock.Unlock()\n\t\treturn ErrAlreadyOpen\n\t}\n\ts.conns[c.Peer.Key()] = c\n\tlog.Debug(\"Added conn to map!\")\n\ts.connsLock.Unlock()\n\n\t\/\/ kick off reader goroutine\n\tgo s.fanIn(c)\n\treturn nil\n}\n\n\/\/ connSecure setups a secure remote connection.\nfunc (s *Swarm) connSecure(c *conn.Conn) error {\n\n\tsp, err := spipe.NewSecurePipe(s.ctx, 10, s.local, s.peers)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = sp.Wrap(s.ctx, spipe.Duplex{\n\t\tIn:  c.Incoming.MsgChan,\n\t\tOut: c.Outgoing.MsgChan,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.Peer == nil {\n\t\tc.Peer = sp.RemotePeer()\n\n\t} else if c.Peer != sp.RemotePeer() {\n\t\tpanic(\"peers not being constructed correctly.\")\n\t}\n\n\tc.Secure = sp\n\treturn nil\n}\n\n\/\/ connVersionExchange exchanges local and remote versions and compares them\n\/\/ closes remote and returns an error in case of major difference\nfunc (s *Swarm) connVersionExchange(remote *conn.Conn) error {\n\tvar remoteVersion, myVersion *version.SemVer\n\tmyVersion = version.Current()\n\n\tmyVersionMsg, err := msg.FromObject(s.local, myVersion)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"connVersionExchange: could not prepare local version: %q\", err)\n\t}\n\n\tvar gotTheirs, sendMine bool\n\tfor {\n\t\tif gotTheirs && sendMine {\n\t\t\tbreak\n\t\t}\n\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\t\/\/ close Conn.\n\t\t\tremote.Close()\n\t\t\treturn nil \/\/ BUG(cryptix): should this be an error?\n\n\t\tcase <-remote.Closed:\n\t\t\treturn errors.New(\"remote closed connection during version exchange\")\n\n\t\tcase remote.Secure.Out <- myVersionMsg.Data():\n\t\t\tlog.Debug(\"[peer: %s] Send my version(%s) to %s\", s.local, myVersion, remote.Peer)\n\t\t\tsendMine = true\n\n\t\tcase data, ok := <-remote.Secure.In:\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"Error retrieving from conn: %v\", remote.Peer)\n\t\t\t}\n\n\t\t\tlog.Debug(\"[peer: %s] Received message [from = %s]\", s.local, remote.Peer)\n\n\t\t\tremoteVersion = new(version.SemVer)\n\t\t\terr = proto.Unmarshal(data, remoteVersion)\n\t\t\tif err != nil {\n\t\t\t\ts.Close()\n\t\t\t\treturn fmt.Errorf(\"connSetup: could not decode remote version: %q\", err)\n\t\t\t}\n\t\t\tgotTheirs = true\n\t\t}\n\t}\n\n\treturn errors.New(\"not yet\")\n}\n\n\/\/ Handles the unwrapping + sending of messages to the right connection.\nfunc (s *Swarm) fanOut() {\n\tfor {\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\treturn \/\/ told to close.\n\n\t\tcase msg, ok := <-s.Outgoing:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ts.connsLock.RLock()\n\t\t\tconn, found := s.conns[msg.Peer().Key()]\n\t\t\ts.connsLock.RUnlock()\n\n\t\t\tif !found {\n\t\t\t\te := fmt.Errorf(\"Sent msg to peer without open conn: %v\",\n\t\t\t\t\tmsg.Peer)\n\t\t\t\ts.errChan <- e\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ log.Debug(\"[peer: %s] Sent message [to = %s]\", s.local, msg.Peer())\n\n\t\t\t\/\/ queue it in the connection's buffer\n\t\t\tconn.Secure.Out <- msg.Data()\n\t\t}\n\t}\n}\n\n\/\/ Handles the receiving + wrapping of messages, per conn.\n\/\/ Consider using reflect.Select with one goroutine instead of n.\nfunc (s *Swarm) fanIn(c *conn.Conn) {\n\tfor {\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\t\/\/ close Conn.\n\t\t\tc.Close()\n\t\t\tgoto out\n\n\t\tcase <-c.Closed:\n\t\t\tgoto out\n\n\t\tcase data, ok := <-c.Secure.In:\n\t\t\tif !ok {\n\t\t\t\te := fmt.Errorf(\"Error retrieving from conn: %v\", c.Peer)\n\t\t\t\ts.errChan <- e\n\t\t\t\tgoto out\n\t\t\t}\n\n\t\t\t\/\/ log.Debug(\"[peer: %s] Received message [from = %s]\", s.local, c.Peer)\n\n\t\t\tmsg := msg.New(c.Peer, data)\n\t\t\ts.Incoming <- msg\n\t\t}\n\t}\n\nout:\n\ts.connsLock.Lock()\n\tdelete(s.conns, c.Peer.Key())\n\ts.connsLock.Unlock()\n}\n<commit_msg>only send local version once<commit_after>package swarm\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\tspipe \"github.com\/jbenet\/go-ipfs\/crypto\/spipe\"\n\tconn \"github.com\/jbenet\/go-ipfs\/net\/conn\"\n\tmsg \"github.com\/jbenet\/go-ipfs\/net\/message\"\n\tversion \"github.com\/jbenet\/go-ipfs\/net\/version\"\n\n\tproto \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/goprotobuf\/proto\"\n\tma \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr\"\n\tmanet \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr\/net\"\n)\n\n\/\/ Open listeners for each network the swarm should listen on\nfunc (s *Swarm) listen() error {\n\thasErr := false\n\tretErr := &ListenErr{\n\t\tErrors: make([]error, len(s.local.Addresses)),\n\t}\n\n\t\/\/ listen on every address\n\tfor i, addr := range s.local.Addresses {\n\t\terr := s.connListen(addr)\n\t\tif err != nil {\n\t\t\thasErr = true\n\t\t\tretErr.Errors[i] = err\n\t\t\tlog.Error(\"Failed to listen on: %s - %s\", addr, err)\n\t\t}\n\t}\n\n\tif hasErr {\n\t\treturn retErr\n\t}\n\treturn nil\n}\n\n\/\/ Listen for new connections on the given multiaddr\nfunc (s *Swarm) connListen(maddr ma.Multiaddr) error {\n\tlist, err := manet.Listen(maddr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ NOTE: this may require a lock around it later. currently, only run on setup\n\ts.listeners = append(s.listeners, list)\n\n\t\/\/ Accept and handle new connections on this listener until it errors\n\tgo func() {\n\t\tfor {\n\t\t\tnconn, err := list.Accept()\n\t\t\tif err != nil {\n\t\t\t\te := fmt.Errorf(\"Failed to accept connection: %s - %s\", maddr, err)\n\t\t\t\ts.errChan <- e\n\n\t\t\t\t\/\/ if cancel is nil, we're closed.\n\t\t\t\tif s.cancel == nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgo s.handleIncomingConn(nconn)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil\n}\n\n\/\/ Handle getting ID from this peer, handshake, and adding it into the map\nfunc (s *Swarm) handleIncomingConn(nconn manet.Conn) {\n\n\taddr := nconn.RemoteMultiaddr()\n\n\t\/\/ Construct conn with nil peer for now, because we don't know its ID yet.\n\t\/\/ connSetup will figure this out, and pull out \/ construct the peer.\n\tc, err := conn.NewConn(nil, addr, nconn)\n\tif err != nil {\n\t\ts.errChan <- err\n\t\treturn\n\t}\n\n\t\/\/ Setup the new connection\n\terr = s.connSetup(c)\n\tif err != nil && err != ErrAlreadyOpen {\n\t\ts.errChan <- err\n\t\tc.Close()\n\t}\n}\n\n\/\/ connSetup adds the passed in connection to its peerMap and starts\n\/\/ the fanIn routine for that connection\nfunc (s *Swarm) connSetup(c *conn.Conn) error {\n\tif c == nil {\n\t\treturn errors.New(\"Tried to start nil connection.\")\n\t}\n\n\tif c.Peer != nil {\n\t\tlog.Debug(\"Starting connection: %s\", c.Peer)\n\t} else {\n\t\tlog.Debug(\"Starting connection: [unknown peer]\")\n\t}\n\n\tif err := s.connSecure(c); err != nil {\n\t\treturn fmt.Errorf(\"Conn securing error: %v\", err)\n\t}\n\n\tlog.Debug(\"Secured connection: %s\", c.Peer)\n\n\t\/\/ add address of connection to Peer. Maybe it should happen in connSecure.\n\tc.Peer.AddAddress(c.Addr)\n\n\tif err := s.connVersionExchange(c); err != nil {\n\t\treturn fmt.Errorf(\"Conn version exchange error: %v\", err)\n\t}\n\n\t\/\/ add to conns\n\ts.connsLock.Lock()\n\tif _, ok := s.conns[c.Peer.Key()]; ok {\n\t\tlog.Debug(\"Conn already open!\")\n\t\ts.connsLock.Unlock()\n\t\treturn ErrAlreadyOpen\n\t}\n\ts.conns[c.Peer.Key()] = c\n\tlog.Debug(\"Added conn to map!\")\n\ts.connsLock.Unlock()\n\n\t\/\/ kick off reader goroutine\n\tgo s.fanIn(c)\n\treturn nil\n}\n\n\/\/ connSecure setups a secure remote connection.\nfunc (s *Swarm) connSecure(c *conn.Conn) error {\n\n\tsp, err := spipe.NewSecurePipe(s.ctx, 10, s.local, s.peers)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = sp.Wrap(s.ctx, spipe.Duplex{\n\t\tIn:  c.Incoming.MsgChan,\n\t\tOut: c.Outgoing.MsgChan,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.Peer == nil {\n\t\tc.Peer = sp.RemotePeer()\n\n\t} else if c.Peer != sp.RemotePeer() {\n\t\tpanic(\"peers not being constructed correctly.\")\n\t}\n\n\tc.Secure = sp\n\treturn nil\n}\n\n\/\/ connVersionExchange exchanges local and remote versions and compares them\n\/\/ closes remote and returns an error in case of major difference\nfunc (s *Swarm) connVersionExchange(remote *conn.Conn) error {\n\tvar remoteVersion, myVersion *version.SemVer\n\tmyVersion = version.Current()\n\n\tmyVersionMsg, err := msg.FromObject(s.local, myVersion)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"connVersionExchange: could not prepare local version: %q\", err)\n\t}\n\n\t\/\/ buffered channel to send our version just once\n\toutBuf := make(chan []byte, 1)\n\toutBuf <- myVersionMsg.Data()\n\n\tvar gotTheirs, sendMine bool\n\tfor {\n\t\tif gotTheirs && sendMine {\n\t\t\tbreak\n\t\t}\n\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\t\/\/ close Conn.\n\t\t\tremote.Close()\n\t\t\treturn nil \/\/ BUG(cryptix): should this be an error?\n\n\t\tcase <-remote.Closed:\n\t\t\treturn errors.New(\"remote closed connection during version exchange\")\n\n\t\tcase our, ok := <-outBuf:\n\t\t\tif ok {\n\t\t\t\tremote.Secure.Out <- our\n\t\t\t\tsendMine = true\n\t\t\t\tclose(outBuf) \/\/ only send local version once\n\t\t\t\tlog.Debug(\"[peer: %s] Send my version(%s) to %s\", s.local, myVersion, remote.Peer)\n\t\t\t}\n\n\t\tcase data, ok := <-remote.Secure.In:\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"Error retrieving from conn: %v\", remote.Peer)\n\t\t\t}\n\n\t\t\tlog.Debug(\"[peer: %s] Received message [from = %s]\", s.local, remote.Peer)\n\n\t\t\tremoteVersion = new(version.SemVer)\n\t\t\terr = proto.Unmarshal(data, remoteVersion)\n\t\t\tif err != nil {\n\t\t\t\ts.Close()\n\t\t\t\treturn fmt.Errorf(\"connSetup: could not decode remote version: %q\", err)\n\t\t\t}\n\t\t\tgotTheirs = true\n\n\t\t\t\/\/ BUG(cryptix): could add another case here to trigger resending our version\n\t\t}\n\t}\n\n\treturn errors.New(\"not yet\")\n}\n\n\/\/ Handles the unwrapping + sending of messages to the right connection.\nfunc (s *Swarm) fanOut() {\n\tfor {\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\treturn \/\/ told to close.\n\n\t\tcase msg, ok := <-s.Outgoing:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ts.connsLock.RLock()\n\t\t\tconn, found := s.conns[msg.Peer().Key()]\n\t\t\ts.connsLock.RUnlock()\n\n\t\t\tif !found {\n\t\t\t\te := fmt.Errorf(\"Sent msg to peer without open conn: %v\",\n\t\t\t\t\tmsg.Peer)\n\t\t\t\ts.errChan <- e\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ log.Debug(\"[peer: %s] Sent message [to = %s]\", s.local, msg.Peer())\n\n\t\t\t\/\/ queue it in the connection's buffer\n\t\t\tconn.Secure.Out <- msg.Data()\n\t\t}\n\t}\n}\n\n\/\/ Handles the receiving + wrapping of messages, per conn.\n\/\/ Consider using reflect.Select with one goroutine instead of n.\nfunc (s *Swarm) fanIn(c *conn.Conn) {\n\tfor {\n\t\tselect {\n\t\tcase <-s.ctx.Done():\n\t\t\t\/\/ close Conn.\n\t\t\tc.Close()\n\t\t\tgoto out\n\n\t\tcase <-c.Closed:\n\t\t\tgoto out\n\n\t\tcase data, ok := <-c.Secure.In:\n\t\t\tif !ok {\n\t\t\t\te := fmt.Errorf(\"Error retrieving from conn: %v\", c.Peer)\n\t\t\t\ts.errChan <- e\n\t\t\t\tgoto out\n\t\t\t}\n\n\t\t\t\/\/ log.Debug(\"[peer: %s] Received message [from = %s]\", s.local, c.Peer)\n\n\t\t\tmsg := msg.New(c.Peer, data)\n\t\t\ts.Incoming <- msg\n\t\t}\n\t}\n\nout:\n\ts.connsLock.Lock()\n\tdelete(s.conns, c.Peer.Key())\n\ts.connsLock.Unlock()\n}\n<|endoftext|>"}
{"text":"<commit_before>package fingerprint\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/hashicorp\/nomad\/client\/config\"\n\t\"github.com\/hashicorp\/nomad\/nomad\/structs\"\n\t\"github.com\/shirou\/gopsutil\/cpu\"\n)\n\n\/\/ CPUFingerprint is used to fingerprint the CPU\ntype CPUFingerprint struct {\n\tStaticFingerprinter\n\tlogger *log.Logger\n}\n\n\/\/ NewCPUFingerprint is used to create a CPU fingerprint\nfunc NewCPUFingerprint(logger *log.Logger) Fingerprint {\n\tf := &CPUFingerprint{logger: logger}\n\treturn f\n}\n\nfunc (f *CPUFingerprint) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {\n\tcpuInfo, err := cpu.CPUInfo()\n\tif err != nil {\n\t\tf.logger.Println(\"[WARN] Error reading CPU information:\", err)\n\t\treturn false, err\n\t}\n\n\tvar numCores int32\n\tvar mhz float64\n\tvar modelName string\n\n\t\/\/ Assume all CPUs found have same Model. Log if not.\n\t\/\/ If CPUInfo() returns nil above, this loop is still safe\n\tfor _, c := range cpuInfo {\n\t\tnumCores += c.Cores\n\t\tmhz += c.Mhz\n\n\t\tif modelName != \"\" && modelName != c.ModelName {\n\t\t\tf.logger.Println(\"[WARN] Found different model names in the same CPU information. Recording last found\")\n\t\t}\n\t\tmodelName = c.ModelName\n\t}\n\t\/\/ Get average CPU frequency\n\tmhz \/= float64(len(cpuInfo))\n\n\tif mhz > 0 {\n\t\tnode.Attributes[\"cpu.frequency\"] = fmt.Sprintf(\"%.6f\", mhz)\n\t\tf.logger.Printf(\"[DEBUG] fingerprint.cpu: frequency: %02.1fMHz\", mhz)\n\t}\n\n\tif numCores > 0 {\n\t\tnode.Attributes[\"cpu.numcores\"] = fmt.Sprintf(\"%d\", numCores)\n\t\tf.logger.Printf(\"[DEBUG] fingerprint.cpu: core count: %d\", numCores)\n\t}\n\n\tif mhz > 0 && numCores > 0 {\n\t\ttc := float64(numCores) * mhz\n\t\tnode.Attributes[\"cpu.totalcompute\"] = fmt.Sprintf(\"%.6f\", tc)\n\n\t\tif node.Resources == nil {\n\t\t\tnode.Resources = &structs.Resources{}\n\t\t}\n\n\t\tnode.Resources.CPU = int(tc)\n\t}\n\n\tif modelName != \"\" {\n\t\tnode.Attributes[\"cpu.modelname\"] = modelName\n\t}\n\n\treturn true, nil\n}\n<commit_msg>Establish a floor of one core for the number of cores.<commit_after>package fingerprint\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/hashicorp\/nomad\/client\/config\"\n\t\"github.com\/hashicorp\/nomad\/nomad\/structs\"\n\t\"github.com\/shirou\/gopsutil\/cpu\"\n)\n\n\/\/ CPUFingerprint is used to fingerprint the CPU\ntype CPUFingerprint struct {\n\tStaticFingerprinter\n\tlogger *log.Logger\n}\n\n\/\/ NewCPUFingerprint is used to create a CPU fingerprint\nfunc NewCPUFingerprint(logger *log.Logger) Fingerprint {\n\tf := &CPUFingerprint{logger: logger}\n\treturn f\n}\n\nfunc (f *CPUFingerprint) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {\n\tcpuInfo, err := cpu.CPUInfo()\n\tif err != nil {\n\t\tf.logger.Println(\"[WARN] Error reading CPU information:\", err)\n\t\treturn false, err\n\t}\n\n\tvar numCores int32\n\tvar mhz float64\n\tvar modelName string\n\n\t\/\/ Assume all CPUs found have same Model. Log if not.\n\t\/\/ If CPUInfo() returns nil above, this loop is still safe\n\tfor _, c := range cpuInfo {\n\t\tnumCores += c.Cores\n\t\tmhz += c.Mhz\n\n\t\tif modelName != \"\" && modelName != c.ModelName {\n\t\t\tf.logger.Println(\"[WARN] Found different model names in the same CPU information. Recording last found\")\n\t\t}\n\t\tmodelName = c.ModelName\n\t}\n\t\/\/ Get average CPU frequency\n\tmhz \/= float64(len(cpuInfo))\n\n\tif mhz > 0 {\n\t\tnode.Attributes[\"cpu.frequency\"] = fmt.Sprintf(\"%.6f\", mhz)\n\t\tf.logger.Printf(\"[DEBUG] fingerprint.cpu: frequency: %02.1fMHz\", mhz)\n\t}\n\n\tif numCores <= 0 {\n\t\tconst defaultCPUCoreCount = 1\n\t\tf.logger.Printf(\"[DEBUG] fingerprint.cpu: unable to find core count, defaulting to %d\", defaultCPUCoreCount)\n\t\tnumCores = defaultCPUCoreCount\n\t}\n\n\tif numCores > 0 {\n\t\tnode.Attributes[\"cpu.numcores\"] = fmt.Sprintf(\"%d\", numCores)\n\t\tf.logger.Printf(\"[DEBUG] fingerprint.cpu: core count: %d\", numCores)\n\t}\n\n\tif mhz > 0 && numCores > 0 {\n\t\ttc := float64(numCores) * mhz\n\t\tnode.Attributes[\"cpu.totalcompute\"] = fmt.Sprintf(\"%.6f\", tc)\n\n\t\tif node.Resources == nil {\n\t\t\tnode.Resources = &structs.Resources{}\n\t\t}\n\n\t\tnode.Resources.CPU = int(tc)\n\t}\n\n\tif modelName != \"\" {\n\t\tnode.Attributes[\"cpu.modelname\"] = modelName\n\t}\n\n\treturn true, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package commands\n\nimport (\n\t\"os\"\n\n\t\"github.com\/git-lfs\/git-lfs\/git\"\n\t\"github.com\/git-lfs\/git-lfs\/locking\"\n\t\"github.com\/rubyist\/tracerx\"\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ postCommitCommand is run through Git's post-commit hook. The hook passes\n\/\/ no arguments.\n\/\/ This hook checks that files which are lockable and not locked are made read-only,\n\/\/ optimising that based on what was added \/ modified in the commit.\nfunc postCommitCommand(cmd *cobra.Command, args []string) {\n\trequireGitVersion()\n\n\tlockClient, err := locking.NewClient(cfg)\n\tif err != nil {\n\t\tExit(\"Unable to create lock system: %v\", err)\n\t}\n\n\t\/\/ Skip this hook if no lockable patterns have been configured\n\tif len(lockClient.GetLockablePatterns()) == 0 ||\n\t\t!cfg.Os.Bool(\"GIT_LFS_SET_LOCKABLE_READONLY\", true) {\n\t\tos.Exit(0)\n\t}\n\n\ttracerx.Printf(\"post-commit: checking file write flags at HEAD\")\n\t\/\/ We can speed things up by looking at what changed in\n\t\/\/ HEAD, and only checking those lockable files\n\tfiles, err := git.GetFilesChanged(\"HEAD\", \"\")\n\n\tif err != nil {\n\t\tLoggedError(err, \"Warning: post-commit failed: %v\", err)\n\t\tos.Exit(1)\n\t}\n\ttracerx.Printf(\"post-commit: checking write flags on %v\", files)\n\terr = lockClient.FixLockableFileWriteFlags(files)\n\tif err != nil {\n\t\tLoggedError(err, \"Warning: post-commit locked file check failed: %v\", err)\n\t}\n\n}\n\nfunc init() {\n\tRegisterCommand(\"post-commit\", postCommitCommand, nil)\n}\n<commit_msg>Explain the need for the post-commit hook (added files)<commit_after>package commands\n\nimport (\n\t\"os\"\n\n\t\"github.com\/git-lfs\/git-lfs\/git\"\n\t\"github.com\/git-lfs\/git-lfs\/locking\"\n\t\"github.com\/rubyist\/tracerx\"\n\t\"github.com\/spf13\/cobra\"\n)\n\n\/\/ postCommitCommand is run through Git's post-commit hook. The hook passes\n\/\/ no arguments.\n\/\/ This hook checks that files which are lockable and not locked are made read-only,\n\/\/ optimising that based on what was added \/ modified in the commit.\n\/\/ This is mainly to catch added files, since modified files should already be\n\/\/ locked. If we didn't do this, any added files would remain read\/write on disk\n\/\/ even without a lock unless something else checked.\nfunc postCommitCommand(cmd *cobra.Command, args []string) {\n\trequireGitVersion()\n\n\tlockClient, err := locking.NewClient(cfg)\n\tif err != nil {\n\t\tExit(\"Unable to create lock system: %v\", err)\n\t}\n\n\t\/\/ Skip this hook if no lockable patterns have been configured\n\tif len(lockClient.GetLockablePatterns()) == 0 ||\n\t\t!cfg.Os.Bool(\"GIT_LFS_SET_LOCKABLE_READONLY\", true) {\n\t\tos.Exit(0)\n\t}\n\n\ttracerx.Printf(\"post-commit: checking file write flags at HEAD\")\n\t\/\/ We can speed things up by looking at what changed in\n\t\/\/ HEAD, and only checking those lockable files\n\tfiles, err := git.GetFilesChanged(\"HEAD\", \"\")\n\n\tif err != nil {\n\t\tLoggedError(err, \"Warning: post-commit failed: %v\", err)\n\t\tos.Exit(1)\n\t}\n\ttracerx.Printf(\"post-commit: checking write flags on %v\", files)\n\terr = lockClient.FixLockableFileWriteFlags(files)\n\tif err != nil {\n\t\tLoggedError(err, \"Warning: post-commit locked file check failed: %v\", err)\n\t}\n\n}\n\nfunc init() {\n\tRegisterCommand(\"post-commit\", postCommitCommand, nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Simple example of ReturnAddress in Go\n\npackage ReturnAddress\n\nimport \"fmt\"\n\ntype Request struct {\n    data        []int\n    resultChan  chan int\n}\n\nfunc sum(a []int) (s int) {\n  for _, v := range a {\n    s += v\n  }\n  return\n}\n\nfunc handle(queue chan *Request) {\n  for req := range queue {\n    req.resultChan <- sum(req.data)\n  }\n}\n\nfunc main() {\n  reqChannel := make(chan *Request, 10)\n  go handle(reqChannel)\n  request1 := &Request{[]int{3, 4, 5}, make(chan int)}\n  request2 := &Request{[]int{1, 2, 3}, make(chan int)}\n  reqChannel <- request1\n  reqChannel <- request2\n  fmt.Printf(\"answer: %d %d\\n\", <-request1.resultChan, <-request2.resultChan)\n}\n<commit_msg>added comments<commit_after>\/\/ Example implementations for Enterprise Integration Patterns\n\/\/ www.EnterpriseIntegrationPatterns.com\n\/\/\n\/\/ Simple example of ReturnAddress in Go\n\npackage ReturnAddress\n\nimport \"fmt\"\n\ntype Request struct {\n    data        []int\n    resultChan  chan int\n}\n\nfunc sum(a []int) (s int) {\n  for _, v := range a {\n    s += v\n  }\n  return\n}\n\nfunc handle(queue chan *Request) {\n  for req := range queue {\n    req.resultChan <- sum(req.data)\n  }\n}\n\nfunc main() {\n  reqChannel := make(chan *Request, 10)\n  go handle(reqChannel)\n  \/\/ Make two requests with separate return channels\n  request1 := &Request{[]int{3, 4, 5}, make(chan int)}\n  request2 := &Request{[]int{1, 2, 3}, make(chan int)}\n  \/\/ Receive both results\n  reqChannel <- request1\n  reqChannel <- request2\n  fmt.Printf(\"answer: %d %d\\n\", <-request1.resultChan, <-request2.resultChan)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nThe Ginkgo CLI\n\nThe Ginkgo CLI is fully documented [here](http:\/\/onsi.github.io\/ginkgo\/#the_ginkgo_cli)\n\nTo install:\n\n\tgo install github.com\/onsi\/ginkgo\/ginkgo\n\nTo run tests:\n\n\tginkgo\n\nTo run tests in all subdirectories:\n\n\tginkgo -r\n\nTo run tests in particular packages:\n\n\tginkgo <flags> \/path\/to\/package \/path\/to\/another\/package\n\nBy default, when running multiple tests (with -r or a list of packages) Ginkgo will abort when a test fails.  To have Ginkgo run subsequent test suites instead you can:\n\n\tginkgo -keep-going\n\nTo monitor packages and rerun tests when changes occur:\n\n\tginkgo -watch <-r> <\/path\/to\/package>\n\npassing `ginkgo -watch` the `-r` flag will recursively detect all test suites under the current directory and monitor them.\n`-watch` does not detect *new* packages. Moreover, changes in package X only rerun the tests for package X, tests for packages\nthat depend on X are not rerun.\n\n[OSX only] To receive (desktop) notifications when a test run completes:\n\n\tginkgo -notify\n\nthis is particularly useful with `ginkgo -watch`.  Notifications are currently only supported on OS X and require that you `brew install terminal-notifier`\n\nTo run tests in parallel\n\n\tginkgo -nodes=N\n\nwhere N is the number of nodes.  By default the Ginkgo CLI will spin up a server that the individual\ntest processes stream test output to.  The CLI then aggregates these streams into one coherent stream of output.\nAn alternative is to have the parallel nodes run and then present the resulting, final, output in one monolithic chunk - you can opt into this if streaming is giving you trouble:\n\n\tginkgo -nodes=N -stream=false\n\nOn windows, the default value for stream is false.\n\nTo bootstrap a test suite:\n\n\tginkgo bootstrap\n\nTo generate a test file:\n\n\tginkgo generate <test_file_name>\n\nTo unfocus tests:\n\n\tginkgo unfocus\n\nTo print out Ginkgo's version:\n\n\tginkgo version\n\nTo get more help:\n\n\tginkgo help\n*\/\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/onsi\/ginkgo\/config\"\n\t\"github.com\/onsi\/ginkgo\/ginkgo\/testsuite\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"time\"\n)\n\nvar numCPU int\nvar parallelStream bool\nvar recurse bool\nvar runMagicI bool\nvar race bool\nvar cover bool\nvar watch bool\nvar notify bool\nvar keepGoing bool\n\nfunc init() {\n\tonWindows := (runtime.GOOS == \"windows\")\n\tonOSX := (runtime.GOOS == \"darwin\")\n\n\tconfig.Flags(\"\", false)\n\n\tflag.IntVar(&(numCPU), \"nodes\", 1, \"The number of parallel test nodes to run\")\n\tflag.BoolVar(&(parallelStream), \"stream\", !onWindows, \"Aggregate parallel test output into one coherent stream (default: true)\")\n\tflag.BoolVar(&(recurse), \"r\", false, \"Find and run test suites under the current directory recursively\")\n\tflag.BoolVar(&(runMagicI), \"i\", false, \"Run go test -i first, then run the test suite\")\n\tflag.BoolVar(&(race), \"race\", false, \"Run tests with race detection enabled\")\n\tflag.BoolVar(&(cover), \"cover\", false, \"Run tests with coverage analysis, will generate coverage profiles with the package name in the current directory\")\n\tflag.BoolVar(&(watch), \"watch\", false, \"Monitor the target packages for changes, then run tests when changes are detected\")\n\tflag.BoolVar(&(keepGoing), \"keep-going\", false, \"When true, failures from earlier test suites do not prevent later test suites from running\")\n\tif onOSX {\n\t\tflag.BoolVar(&(notify), \"notify\", false, \"Send desktop notifications when a test run completes\")\n\t}\n\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of ginkgo:\\n\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"ginkgo <FLAGS> <DIRECTORY> ...\\n  Run the tests in the passed in <DIRECTORY> (or the current directory if left blank).\\n  ginkgo accepts the following flags:\\n\")\n\t\tflag.PrintDefaults()\n\t\tfmt.Fprintf(os.Stderr, \"\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"ginkgo bootstrap\\n  Bootstrap a test suite for the current package.\\n\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"ginkgo generate <SUBJECT>\\n  Generate a test file for SUBJECT, the file will be named SUBJECT_test.go\\n  If omitted, a file named after the package will be created.\\n\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"ginkgo unfocus\\n  Unfocuses any focused tests.\\n\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"ginkgo version\\n  Print ginkgo's version.\\n\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"ginkgo help\\n  Print this usage information.\\n\")\n\t}\n\n\tflag.Parse()\n}\n\nfunc main() {\n\tif flag.NArg() > 0 {\n\t\targs := flag.Args()\n\t\thandled := handleSubcommands(args)\n\t\tif handled {\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tif notify {\n\t\tverifyNotificationsAreAvailable()\n\t}\n\n\trunner := newTestRunner(numCPU, parallelStream, runMagicI, race, cover)\n\n\tregisterSignalHandler(runner)\n\n\tif watch {\n\t\twatchTests(runner)\n\t} else {\n\t\trunTests(runner)\n\t}\n}\n\nfunc handleSubcommands(args []string) bool {\n\tswitch args[0] {\n\tcase \"bootstrap\":\n\t\tgenerateBootstrap()\n\tcase \"generate\":\n\t\tsubject := \"\"\n\t\tif len(args) > 1 {\n\t\t\tsubject = args[1]\n\t\t}\n\t\tgenerateSpec(subject)\n\tcase \"unfocus\", \"blur\":\n\t\tunfocusSpecs()\n\tcase \"help\":\n\t\tflag.Usage()\n\tcase \"version\":\n\t\tfmt.Printf(\"Ginkgo V%s\\n\", config.VERSION)\n\tdefault:\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc findSuites() []*testsuite.TestSuite {\n\tsuites := []*testsuite.TestSuite{}\n\n\tif flag.NArg() > 0 {\n\t\tfor _, dir := range flag.Args() {\n\t\t\tsuites = append(suites, testsuite.SuitesInDir(dir, recurse)...)\n\t\t}\n\t} else {\n\t\tsuites = testsuite.SuitesInDir(\".\", recurse)\n\t}\n\n\tif len(suites) == 0 {\n\t\tfmt.Printf(\"Found no test suites.\\nFor usage instructions:\\n\\tginkgo help\\n\")\n\t\tos.Exit(1)\n\t}\n\n\treturn suites\n}\n\nfunc runTests(runner *testRunner) {\n\tt := time.Now()\n\n\tsuites := findSuites()\n\tsuitesThatFailed := []*testsuite.TestSuite{}\n\n\tpassed := true\n\tfor _, suite := range suites {\n\t\tsuitePassed := runner.runSuite(suite)\n\t\tsendSuiteCompletionNotification(suite, suitePassed)\n\n\t\tif !suitePassed {\n\t\t\tpassed = false\n\t\t\tsuitesThatFailed = append(suitesThatFailed, suite)\n\t\t\tif !keepGoing {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif keepGoing && !passed {\n\t\tfmt.Println(\"\\nThere were failures detected in the following suites:\")\n\t\tfor _, suite := range suitesThatFailed {\n\t\t\tfmt.Printf(\"\\t%s\\n\", suite.PackageName)\n\t\t}\n\t}\n\n\tfmt.Printf(\"\\nGinkgo ran in %s\\n\", time.Since(t))\n\n\tif passed {\n\t\tfmt.Printf(\"Test Suite Passed\\n\")\n\t\tos.Exit(0)\n\t} else {\n\t\tfmt.Printf(\"Test Suite Failed\\n\")\n\t\tos.Exit(1)\n\t}\n}\n\nfunc watchTests(runner *testRunner) {\n\tsuites := findSuites()\n\n\tmodifiedSuite := make(chan *testsuite.TestSuite)\n\tfor _, suite := range suites {\n\t\tgo suite.Watch(modifiedSuite)\n\t}\n\n\tif !recurse {\n\t\tsuitePassed := runner.runSuite(suites[0])\n\t\tsendSuiteCompletionNotification(suites[0], suitePassed)\n\t}\n\n\tfor {\n\t\tsuite := <-modifiedSuite\n\t\tsendNotification(\"Ginkgo\", fmt.Sprintf(`Detected change in \"%s\"...`, suite.PackageName))\n\n\t\tfmt.Printf(\"\\n\\nDetected change in %s\\n\\n\", suite.PackageName)\n\t\tsuitePassed := runner.runSuite(suite)\n\n\t\tsendSuiteCompletionNotification(suite, suitePassed)\n\t}\n}\n\nfunc registerSignalHandler(runner *testRunner) {\n\tgo func() {\n\t\tc := make(chan os.Signal, 1)\n\t\tsignal.Notify(c, os.Interrupt, os.Kill)\n\n\t\tselect {\n\t\tcase sig := <-c:\n\t\t\trunner.abort(sig)\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n}\n<commit_msg>keep-going => keepGoing<commit_after>\/*\nThe Ginkgo CLI\n\nThe Ginkgo CLI is fully documented [here](http:\/\/onsi.github.io\/ginkgo\/#the_ginkgo_cli)\n\nTo install:\n\n\tgo install github.com\/onsi\/ginkgo\/ginkgo\n\nTo run tests:\n\n\tginkgo\n\nTo run tests in all subdirectories:\n\n\tginkgo -r\n\nTo run tests in particular packages:\n\n\tginkgo <flags> \/path\/to\/package \/path\/to\/another\/package\n\nBy default, when running multiple tests (with -r or a list of packages) Ginkgo will abort when a test fails.  To have Ginkgo run subsequent test suites instead you can:\n\n\tginkgo -keepGoing\n\nTo monitor packages and rerun tests when changes occur:\n\n\tginkgo -watch <-r> <\/path\/to\/package>\n\npassing `ginkgo -watch` the `-r` flag will recursively detect all test suites under the current directory and monitor them.\n`-watch` does not detect *new* packages. Moreover, changes in package X only rerun the tests for package X, tests for packages\nthat depend on X are not rerun.\n\n[OSX only] To receive (desktop) notifications when a test run completes:\n\n\tginkgo -notify\n\nthis is particularly useful with `ginkgo -watch`.  Notifications are currently only supported on OS X and require that you `brew install terminal-notifier`\n\nTo run tests in parallel\n\n\tginkgo -nodes=N\n\nwhere N is the number of nodes.  By default the Ginkgo CLI will spin up a server that the individual\ntest processes stream test output to.  The CLI then aggregates these streams into one coherent stream of output.\nAn alternative is to have the parallel nodes run and then present the resulting, final, output in one monolithic chunk - you can opt into this if streaming is giving you trouble:\n\n\tginkgo -nodes=N -stream=false\n\nOn windows, the default value for stream is false.\n\nTo bootstrap a test suite:\n\n\tginkgo bootstrap\n\nTo generate a test file:\n\n\tginkgo generate <test_file_name>\n\nTo unfocus tests:\n\n\tginkgo unfocus\n\nTo print out Ginkgo's version:\n\n\tginkgo version\n\nTo get more help:\n\n\tginkgo help\n*\/\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/onsi\/ginkgo\/config\"\n\t\"github.com\/onsi\/ginkgo\/ginkgo\/testsuite\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"time\"\n)\n\nvar numCPU int\nvar parallelStream bool\nvar recurse bool\nvar runMagicI bool\nvar race bool\nvar cover bool\nvar watch bool\nvar notify bool\nvar keepGoing bool\n\nfunc init() {\n\tonWindows := (runtime.GOOS == \"windows\")\n\tonOSX := (runtime.GOOS == \"darwin\")\n\n\tconfig.Flags(\"\", false)\n\n\tflag.IntVar(&(numCPU), \"nodes\", 1, \"The number of parallel test nodes to run\")\n\tflag.BoolVar(&(parallelStream), \"stream\", !onWindows, \"Aggregate parallel test output into one coherent stream (default: true)\")\n\tflag.BoolVar(&(recurse), \"r\", false, \"Find and run test suites under the current directory recursively\")\n\tflag.BoolVar(&(runMagicI), \"i\", false, \"Run go test -i first, then run the test suite\")\n\tflag.BoolVar(&(race), \"race\", false, \"Run tests with race detection enabled\")\n\tflag.BoolVar(&(cover), \"cover\", false, \"Run tests with coverage analysis, will generate coverage profiles with the package name in the current directory\")\n\tflag.BoolVar(&(watch), \"watch\", false, \"Monitor the target packages for changes, then run tests when changes are detected\")\n\tflag.BoolVar(&(keepGoing), \"keepGoing\", false, \"When true, failures from earlier test suites do not prevent later test suites from running\")\n\tif onOSX {\n\t\tflag.BoolVar(&(notify), \"notify\", false, \"Send desktop notifications when a test run completes\")\n\t}\n\n\tflag.Usage = func() {\n\t\tfmt.Fprintf(os.Stderr, \"Usage of ginkgo:\\n\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"ginkgo <FLAGS> <DIRECTORY> ...\\n  Run the tests in the passed in <DIRECTORY> (or the current directory if left blank).\\n  ginkgo accepts the following flags:\\n\")\n\t\tflag.PrintDefaults()\n\t\tfmt.Fprintf(os.Stderr, \"\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"ginkgo bootstrap\\n  Bootstrap a test suite for the current package.\\n\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"ginkgo generate <SUBJECT>\\n  Generate a test file for SUBJECT, the file will be named SUBJECT_test.go\\n  If omitted, a file named after the package will be created.\\n\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"ginkgo unfocus\\n  Unfocuses any focused tests.\\n\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"ginkgo version\\n  Print ginkgo's version.\\n\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"ginkgo help\\n  Print this usage information.\\n\")\n\t}\n\n\tflag.Parse()\n}\n\nfunc main() {\n\tif flag.NArg() > 0 {\n\t\targs := flag.Args()\n\t\thandled := handleSubcommands(args)\n\t\tif handled {\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n\n\tif notify {\n\t\tverifyNotificationsAreAvailable()\n\t}\n\n\trunner := newTestRunner(numCPU, parallelStream, runMagicI, race, cover)\n\n\tregisterSignalHandler(runner)\n\n\tif watch {\n\t\twatchTests(runner)\n\t} else {\n\t\trunTests(runner)\n\t}\n}\n\nfunc handleSubcommands(args []string) bool {\n\tswitch args[0] {\n\tcase \"bootstrap\":\n\t\tgenerateBootstrap()\n\tcase \"generate\":\n\t\tsubject := \"\"\n\t\tif len(args) > 1 {\n\t\t\tsubject = args[1]\n\t\t}\n\t\tgenerateSpec(subject)\n\tcase \"unfocus\", \"blur\":\n\t\tunfocusSpecs()\n\tcase \"help\":\n\t\tflag.Usage()\n\tcase \"version\":\n\t\tfmt.Printf(\"Ginkgo V%s\\n\", config.VERSION)\n\tdefault:\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc findSuites() []*testsuite.TestSuite {\n\tsuites := []*testsuite.TestSuite{}\n\n\tif flag.NArg() > 0 {\n\t\tfor _, dir := range flag.Args() {\n\t\t\tsuites = append(suites, testsuite.SuitesInDir(dir, recurse)...)\n\t\t}\n\t} else {\n\t\tsuites = testsuite.SuitesInDir(\".\", recurse)\n\t}\n\n\tif len(suites) == 0 {\n\t\tfmt.Printf(\"Found no test suites.\\nFor usage instructions:\\n\\tginkgo help\\n\")\n\t\tos.Exit(1)\n\t}\n\n\treturn suites\n}\n\nfunc runTests(runner *testRunner) {\n\tt := time.Now()\n\n\tsuites := findSuites()\n\tsuitesThatFailed := []*testsuite.TestSuite{}\n\n\tpassed := true\n\tfor _, suite := range suites {\n\t\tsuitePassed := runner.runSuite(suite)\n\t\tsendSuiteCompletionNotification(suite, suitePassed)\n\n\t\tif !suitePassed {\n\t\t\tpassed = false\n\t\t\tsuitesThatFailed = append(suitesThatFailed, suite)\n\t\t\tif !keepGoing {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif keepGoing && !passed {\n\t\tfmt.Println(\"\\nThere were failures detected in the following suites:\")\n\t\tfor _, suite := range suitesThatFailed {\n\t\t\tfmt.Printf(\"\\t%s\\n\", suite.PackageName)\n\t\t}\n\t}\n\n\tfmt.Printf(\"\\nGinkgo ran in %s\\n\", time.Since(t))\n\n\tif passed {\n\t\tfmt.Printf(\"Test Suite Passed\\n\")\n\t\tos.Exit(0)\n\t} else {\n\t\tfmt.Printf(\"Test Suite Failed\\n\")\n\t\tos.Exit(1)\n\t}\n}\n\nfunc watchTests(runner *testRunner) {\n\tsuites := findSuites()\n\n\tmodifiedSuite := make(chan *testsuite.TestSuite)\n\tfor _, suite := range suites {\n\t\tgo suite.Watch(modifiedSuite)\n\t}\n\n\tif !recurse {\n\t\tsuitePassed := runner.runSuite(suites[0])\n\t\tsendSuiteCompletionNotification(suites[0], suitePassed)\n\t}\n\n\tfor {\n\t\tsuite := <-modifiedSuite\n\t\tsendNotification(\"Ginkgo\", fmt.Sprintf(`Detected change in \"%s\"...`, suite.PackageName))\n\n\t\tfmt.Printf(\"\\n\\nDetected change in %s\\n\\n\", suite.PackageName)\n\t\tsuitePassed := runner.runSuite(suite)\n\n\t\tsendSuiteCompletionNotification(suite, suitePassed)\n\t}\n}\n\nfunc registerSignalHandler(runner *testRunner) {\n\tgo func() {\n\t\tc := make(chan os.Signal, 1)\n\t\tsignal.Notify(c, os.Interrupt, os.Kill)\n\n\t\tselect {\n\t\tcase sig := <-c:\n\t\t\trunner.abort(sig)\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2013 Matt Jibson <matt.jibson@gmail.com>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\npackage goapp\n\nimport (\n\t\"encoding\/base64\"\n\t\"net\/url\"\n\t\"time\"\n\n\t\"appengine\"\n\t\"appengine\/datastore\"\n\t\"appengine\/taskqueue\"\n)\n\ntype User struct {\n\t_kind    string    `goon:\"kind,U\"`\n\tId       string    `datastore:\"-\" goon:\"id\"`\n\tEmail    string    `datastore:\"e,noindex\"`\n\tMessages []string  `datastore:\"m,noindex\"`\n\tRead     time.Time `datastore:\"r,noindex\"`\n\tOptions  string    `datastore:\"o,noindex\"`\n}\n\nfunc (u *User) String() string {\n\treturn u.Email\n}\n\n\/\/ parent: User, key: \"data\"\ntype UserData struct {\n\t_kind  string         `goon:\"kind,UD\"`\n\tId     string         `datastore:\"-\" goon:\"id\"`\n\tParent *datastore.Key `datastore:\"-\" goon:\"parent\"`\n\tOpml   []byte         `datastore:\"o,noindex\"`\n\tRead   []byte         `datastore:\"r,noindex\"`\n}\n\ntype Read map[string][]string\n\ntype Feed struct {\n\t_kind      string    `goon:\"kind,F\"`\n\tUrl        string    `datastore:\"-\" goon:\"id\"`\n\tTitle      string    `datastore:\"t,noindex\"`\n\tUpdated    time.Time `datastore:\"u,noindex\"`\n\tDate       time.Time `datastore:\"d,noindex\"`\n\tChecked    time.Time `datastore:\"c,noindex\"`\n\tNextUpdate time.Time `datastore:\"n\"`\n\tLink       string    `datastore:\"l,noindex\"`\n\tErrors     int       `datastore:\"e,noindex\"`\n\tImage      string    `datastore:\"i,noindex\"`\n\tSubscribed time.Time `datastore:\"s,noindex\"`\n}\n\nfunc (f Feed) Subscribe(c appengine.Context) {\n\tif !f.IsSubscribed() {\n\t\tt := taskqueue.NewPOSTTask(routeUrl(\"subscribe-feed\"), url.Values{\n\t\t\t\"feed\": {f.Url},\n\t\t})\n\t\tif _, err := taskqueue.Add(c, t, \"update-manual\"); err != nil {\n\t\t\tc.Errorf(\"taskqueue error: %v\", err.Error())\n\t\t} else {\n\t\t\tc.Warningf(\"subscribe feed: %v\", f.Url)\n\t\t}\n\t}\n}\n\nfunc (f Feed) IsSubscribed() bool {\n\treturn !ENABLE_PUBSUBHUBBUB || time.Now().Before(f.Subscribed)\n}\n\nfunc (f Feed) PubSubURL() string {\n\tb := base64.URLEncoding.EncodeToString([]byte(f.Url))\n\tru, _ := router.Get(\"subscribe-callback\").URL(\"feed\", b)\n\tru.Scheme = \"http\"\n\tru.Host = PUBSUBHUBBUB_HOST\n\treturn ru.String()\n}\n\n\/\/ parent: Feed, key: story ID\ntype Story struct {\n\t_kind     string         `goon:\"kind,S\"`\n\tId        string         `datastore:\"-\" goon:\"id\"`\n\tParent    *datastore.Key `datastore:\"-\" goon:\"parent\" json:\"-\"`\n\tTitle     string         `datastore:\"t,noindex\"`\n\tLink      string         `datastore:\"l,noindex\"`\n\tCreated   time.Time      `datastore:\"c\" json:\"-\"`\n\tPublished time.Time      `datastore:\"p\" json:\"-\"`\n\tUpdated   time.Time      `datastore:\"u,noindex\" json:\"-\"`\n\tDate      int64          `datastore:\"e,noindex\"`\n\tAuthor    string         `datastore:\"a,noindex\"`\n\tSummary   string         `datastore:\"s,noindex\"`\n\n\tcontent string\n}\n\nconst IDX_COL = \"p\"\n\n\/\/ parent: Story, key: 1\ntype StoryContent struct {\n\t_kind   string         `goon:\"kind,SC\"`\n\tId      int64          `datastore:\"-\" goon:\"id\"`\n\tParent  *datastore.Key `datastore:\"-\" goon:\"parent\"`\n\tContent string         `datastore:\"c,noindex\"`\n}\n\ntype OpmlOutline struct {\n\tOutline []*OpmlOutline `xml:\"outline\" json:\",omitempty\"`\n\tTitle   string         `xml:\"title,attr,omitempty\" json:\",omitempty\"`\n\tXmlUrl  string         `xml:\"xmlUrl,attr\" json:\",omitempty\"`\n\tType    string         `xml:\"type,attr,omitempty\" json:\",omitempty\"`\n\tText    string         `xml:\"text,attr,omitempty\" json:\",omitempty\"`\n\tHtmlUrl string         `xml:\"htmlUrl,attr,omitempty\" json:\",omitempty\"`\n}\n\ntype Opml struct {\n\tXMLName string         `xml:\"opml\"`\n\tVersion string         `xml:\"version,attr\"`\n\tOutline []*OpmlOutline `xml:\"body>outline\"`\n}\n\ntype DateFormat struct {\n\tId     string         `datastore:\"-\" goon:\"id\"`\n\t_kind  string         `goon:\"kind,DF\"`\n\tParent *datastore.Key `datastore:\"-\" goon:\"parent\"`\n}\n\ntype Image struct {\n\tId   string            `datastore:\"-\" goon:\"id\"`\n\tBlob appengine.BlobKey `datastore:\"b,noindex\"`\n\tUrl  string            `datastore:\"u,noindex\"`\n}\n<commit_msg>Omit empty<commit_after>\/*\n * Copyright (c) 2013 Matt Jibson <matt.jibson@gmail.com>\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\npackage goapp\n\nimport (\n\t\"encoding\/base64\"\n\t\"net\/url\"\n\t\"time\"\n\n\t\"appengine\"\n\t\"appengine\/datastore\"\n\t\"appengine\/taskqueue\"\n)\n\ntype User struct {\n\t_kind    string    `goon:\"kind,U\"`\n\tId       string    `datastore:\"-\" goon:\"id\"`\n\tEmail    string    `datastore:\"e,noindex\"`\n\tMessages []string  `datastore:\"m,noindex\"`\n\tRead     time.Time `datastore:\"r,noindex\"`\n\tOptions  string    `datastore:\"o,noindex\"`\n}\n\nfunc (u *User) String() string {\n\treturn u.Email\n}\n\n\/\/ parent: User, key: \"data\"\ntype UserData struct {\n\t_kind  string         `goon:\"kind,UD\"`\n\tId     string         `datastore:\"-\" goon:\"id\"`\n\tParent *datastore.Key `datastore:\"-\" goon:\"parent\"`\n\tOpml   []byte         `datastore:\"o,noindex\"`\n\tRead   []byte         `datastore:\"r,noindex\"`\n}\n\ntype Read map[string][]string\n\ntype Feed struct {\n\t_kind      string    `goon:\"kind,F\"`\n\tUrl        string    `datastore:\"-\" goon:\"id\"`\n\tTitle      string    `datastore:\"t,noindex\"`\n\tUpdated    time.Time `datastore:\"u,noindex\"`\n\tDate       time.Time `datastore:\"d,noindex\"`\n\tChecked    time.Time `datastore:\"c,noindex\"`\n\tNextUpdate time.Time `datastore:\"n\"`\n\tLink       string    `datastore:\"l,noindex\"`\n\tErrors     int       `datastore:\"e,noindex\"`\n\tImage      string    `datastore:\"i,noindex\"`\n\tSubscribed time.Time `datastore:\"s,noindex\"`\n}\n\nfunc (f Feed) Subscribe(c appengine.Context) {\n\tif !f.IsSubscribed() {\n\t\tt := taskqueue.NewPOSTTask(routeUrl(\"subscribe-feed\"), url.Values{\n\t\t\t\"feed\": {f.Url},\n\t\t})\n\t\tif _, err := taskqueue.Add(c, t, \"update-manual\"); err != nil {\n\t\t\tc.Errorf(\"taskqueue error: %v\", err.Error())\n\t\t} else {\n\t\t\tc.Warningf(\"subscribe feed: %v\", f.Url)\n\t\t}\n\t}\n}\n\nfunc (f Feed) IsSubscribed() bool {\n\treturn !ENABLE_PUBSUBHUBBUB || time.Now().Before(f.Subscribed)\n}\n\nfunc (f Feed) PubSubURL() string {\n\tb := base64.URLEncoding.EncodeToString([]byte(f.Url))\n\tru, _ := router.Get(\"subscribe-callback\").URL(\"feed\", b)\n\tru.Scheme = \"http\"\n\tru.Host = PUBSUBHUBBUB_HOST\n\treturn ru.String()\n}\n\n\/\/ parent: Feed, key: story ID\ntype Story struct {\n\t_kind     string         `goon:\"kind,S\"`\n\tId        string         `datastore:\"-\" goon:\"id\"`\n\tParent    *datastore.Key `datastore:\"-\" goon:\"parent\" json:\"-\"`\n\tTitle     string         `datastore:\"t,noindex\"`\n\tLink      string         `datastore:\"l,noindex\"`\n\tCreated   time.Time      `datastore:\"c\" json:\"-\"`\n\tPublished time.Time      `datastore:\"p\" json:\"-\"`\n\tUpdated   time.Time      `datastore:\"u,noindex\" json:\"-\"`\n\tDate      int64          `datastore:\"e,noindex\"`\n\tAuthor    string         `datastore:\"a,noindex\" json:\",omitempty\"`\n\tSummary   string         `datastore:\"s,noindex\"`\n\n\tcontent string\n}\n\nconst IDX_COL = \"p\"\n\n\/\/ parent: Story, key: 1\ntype StoryContent struct {\n\t_kind   string         `goon:\"kind,SC\"`\n\tId      int64          `datastore:\"-\" goon:\"id\"`\n\tParent  *datastore.Key `datastore:\"-\" goon:\"parent\"`\n\tContent string         `datastore:\"c,noindex\"`\n}\n\ntype OpmlOutline struct {\n\tOutline []*OpmlOutline `xml:\"outline\" json:\",omitempty\"`\n\tTitle   string         `xml:\"title,attr,omitempty\" json:\",omitempty\"`\n\tXmlUrl  string         `xml:\"xmlUrl,attr\" json:\",omitempty\"`\n\tType    string         `xml:\"type,attr,omitempty\" json:\",omitempty\"`\n\tText    string         `xml:\"text,attr,omitempty\" json:\",omitempty\"`\n\tHtmlUrl string         `xml:\"htmlUrl,attr,omitempty\" json:\",omitempty\"`\n}\n\ntype Opml struct {\n\tXMLName string         `xml:\"opml\"`\n\tVersion string         `xml:\"version,attr\"`\n\tOutline []*OpmlOutline `xml:\"body>outline\"`\n}\n\ntype DateFormat struct {\n\tId     string         `datastore:\"-\" goon:\"id\"`\n\t_kind  string         `goon:\"kind,DF\"`\n\tParent *datastore.Key `datastore:\"-\" goon:\"parent\"`\n}\n\ntype Image struct {\n\tId   string            `datastore:\"-\" goon:\"id\"`\n\tBlob appengine.BlobKey `datastore:\"b,noindex\"`\n\tUrl  string            `datastore:\"u,noindex\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package goenv\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/crgimenes\/goconfig\/structtag\"\n)\n\nvar (\n\t\/\/ Prefix is a string that would be placed at the beginning of the generated tags.\n\tPrefix string\n\n\t\/\/ Usage is the function that is called when an error occurs.\n\tUsage func()\n\n\t\/\/ PrintDefaultsOutput changes the default output help string\n\tPrintDefaultsOutput string\n)\n\n\/\/ Setup maps and variables\nfunc Setup(tag string, tagDefault string) {\n\tUsage = DefaultUsage\n\n\tstructtag.Setup()\n\tstructtag.Prefix = Prefix\n\tSetTag(tag)\n\tSetTagDefault(tagDefault)\n\n\tstructtag.ParseMap[reflect.Int64] = reflectInt\n\tstructtag.ParseMap[reflect.Int] = reflectInt\n\tstructtag.ParseMap[reflect.Float64] = reflectFloat\n\tstructtag.ParseMap[reflect.String] = reflectString\n\tstructtag.ParseMap[reflect.Bool] = reflectBool\n}\n\n\/\/ SetTag set a new tag\nfunc SetTag(tag string) {\n\tstructtag.Tag = tag\n}\n\n\/\/ SetTagDefault set a new TagDefault to retorn default values\nfunc SetTagDefault(tag string) {\n\tstructtag.TagDefault = tag\n}\n\n\/\/ Parse configuration\nfunc Parse(config interface{}) (err error) {\n\terr = structtag.Parse(config, \"\")\n\treturn\n}\n\nfunc parseValue(datatype string, value *reflect.Value) (ret string, ok bool) {\n\tswitch datatype {\n\tcase \"bool\":\n\t\tif value.Bool() {\n\t\t\tret = \"true\"\n\t\t\tok = true\n\t\t}\n\tcase \"string\":\n\t\tret = value.String()\n\t\tok = ret != \"\"\n\tcase \"int\":\n\t\tret = strconv.FormatInt(value.Int(), 10)\n\t\tok = ret != \"0\"\n\tcase \"float64\":\n\t\tret = strconv.FormatFloat(value.Float(), 'f', -1, 64)\n\t\tok = ret != \"0\"\n\t}\n\treturn\n}\n\nfunc getNewValue(field *reflect.StructField, value *reflect.Value, tag string, datatype string) (ret string) {\n\tdefaultValue := field.Tag.Get(structtag.TagDefault)\n\n\t\/\/ create PrintDefaults output\n\ttag = strings.ToUpper(tag)\n\tsysvar := `$` + tag\n\tif runtime.GOOS == \"windows\" {\n\t\tsysvar = `%` + tag + `%`\n\t}\n\n\toutput := fmt.Sprintf(\"  %v %v\\n\\n\", sysvar, datatype)\n\tif defaultValue != \"\" {\n\t\toutput = fmt.Sprintf(\"  %v %v\\n\\t(default %q)\\n\", sysvar, datatype, defaultValue)\n\t}\n\tPrintDefaultsOutput += output\n\n\t\/\/ get value from environment variable\n\tret = os.Getenv(tag)\n\tif ret != \"\" {\n\t\treturn\n\t}\n\n\tret, ok := parseValue(datatype, value)\n\tif ok {\n\t\treturn\n\t}\n\n\t\/\/ get value from default settings\n\tret = defaultValue\n\treturn\n}\n\nfunc reflectInt(field *reflect.StructField, value *reflect.Value, tag string) (err error) {\n\tnewValue := getNewValue(field, value, tag, \"int\")\n\tif newValue == \"\" {\n\t\treturn\n\t}\n\tvar intNewValue int64\n\tintNewValue, err = strconv.ParseInt(newValue, 10, 64)\n\tif err != nil {\n\t\treturn\n\t}\n\tvalue.SetInt(intNewValue)\n\treturn\n}\n\nfunc reflectFloat(field *reflect.StructField, value *reflect.Value, tag string) (err error) {\n\tnewValue := getNewValue(field, value, tag, \"float64\")\n\tif newValue == \"\" {\n\t\treturn\n\t}\n\tvar floatNewValue float64\n\tfloatNewValue, err = strconv.ParseFloat(newValue, 64)\n\tif err != nil {\n\t\treturn\n\t}\n\tvalue.SetFloat(floatNewValue)\n\treturn\n}\n\nfunc reflectString(field *reflect.StructField, value *reflect.Value, tag string) (err error) {\n\tnewValue := getNewValue(field, value, tag, \"string\")\n\tif newValue == \"\" {\n\t\treturn\n\t}\n\tvalue.SetString(newValue)\n\treturn\n}\n\nfunc reflectBool(field *reflect.StructField, value *reflect.Value, tag string) (err error) {\n\tnewValue := getNewValue(field, value, tag, \"bool\")\n\tif newValue == \"\" {\n\t\treturn\n\t}\n\tnewBoolValue := newValue == \"true\" || newValue == \"t\"\n\tvalue.SetBool(newBoolValue)\n\treturn\n}\n\n\/\/ PrintDefaults print the default help\nfunc PrintDefaults() {\n\tfmt.Println(\"Environment variables:\")\n\tfmt.Println(PrintDefaultsOutput)\n}\n\n\/\/ DefaultUsage is assigned for Usage function by default\nfunc DefaultUsage() {\n\tfmt.Println(\"Usage\")\n\tPrintDefaults()\n}\n<commit_msg>replace GetEnv by the LookupEnv function (#42)<commit_after>package goenv\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/crgimenes\/goconfig\/structtag\"\n)\n\nvar (\n\t\/\/ Prefix is a string that would be placed at the beginning of the generated tags.\n\tPrefix string\n\n\t\/\/ Usage is the function that is called when an error occurs.\n\tUsage func()\n\n\t\/\/ PrintDefaultsOutput changes the default output help string\n\tPrintDefaultsOutput string\n)\n\n\/\/ Setup maps and variables\nfunc Setup(tag string, tagDefault string) {\n\tUsage = DefaultUsage\n\n\tstructtag.Setup()\n\tstructtag.Prefix = Prefix\n\tSetTag(tag)\n\tSetTagDefault(tagDefault)\n\n\tstructtag.ParseMap[reflect.Int64] = reflectInt\n\tstructtag.ParseMap[reflect.Int] = reflectInt\n\tstructtag.ParseMap[reflect.Float64] = reflectFloat\n\tstructtag.ParseMap[reflect.String] = reflectString\n\tstructtag.ParseMap[reflect.Bool] = reflectBool\n}\n\n\/\/ SetTag set a new tag\nfunc SetTag(tag string) {\n\tstructtag.Tag = tag\n}\n\n\/\/ SetTagDefault set a new TagDefault to retorn default values\nfunc SetTagDefault(tag string) {\n\tstructtag.TagDefault = tag\n}\n\n\/\/ Parse configuration\nfunc Parse(config interface{}) (err error) {\n\terr = structtag.Parse(config, \"\")\n\treturn\n}\n\nfunc parseValue(datatype string, value *reflect.Value) (ret string, ok bool) {\n\tswitch datatype {\n\tcase \"bool\":\n\t\tif value.Bool() {\n\t\t\tret = \"true\"\n\t\t\tok = true\n\t\t}\n\tcase \"string\":\n\t\tret = value.String()\n\t\tok = ret != \"\"\n\tcase \"int\":\n\t\tret = strconv.FormatInt(value.Int(), 10)\n\t\tok = ret != \"0\"\n\tcase \"float64\":\n\t\tret = strconv.FormatFloat(value.Float(), 'f', -1, 64)\n\t\tok = ret != \"0\"\n\t}\n\treturn\n}\n\nfunc getNewValue(field *reflect.StructField, value *reflect.Value, tag string, datatype string) (ret string) {\n\tdefaultValue := field.Tag.Get(structtag.TagDefault)\n\n\t\/\/ create PrintDefaults output\n\ttag = strings.ToUpper(tag)\n\tsysvar := `$` + tag\n\tif runtime.GOOS == \"windows\" {\n\t\tsysvar = `%` + tag + `%`\n\t}\n\n\toutput := fmt.Sprintf(\"  %v %v\\n\\n\", sysvar, datatype)\n\tif defaultValue != \"\" {\n\t\toutput = fmt.Sprintf(\"  %v %v\\n\\t(default %q)\\n\", sysvar, datatype, defaultValue)\n\t}\n\tPrintDefaultsOutput += output\n\n\t\/\/ get value from environment variable\n\tret, ok := os.LookupEnv(tag)\n\tif ok {\n\t\treturn\n\t}\n\n\tret, ok = parseValue(datatype, value)\n\tif ok {\n\t\treturn\n\t}\n\n\t\/\/ get value from default settings\n\tret = defaultValue\n\treturn\n}\n\nfunc reflectInt(field *reflect.StructField, value *reflect.Value, tag string) (err error) {\n\tnewValue := getNewValue(field, value, tag, \"int\")\n\tif newValue == \"\" {\n\t\treturn\n\t}\n\tvar intNewValue int64\n\tintNewValue, err = strconv.ParseInt(newValue, 10, 64)\n\tif err != nil {\n\t\treturn\n\t}\n\tvalue.SetInt(intNewValue)\n\treturn\n}\n\nfunc reflectFloat(field *reflect.StructField, value *reflect.Value, tag string) (err error) {\n\tnewValue := getNewValue(field, value, tag, \"float64\")\n\tif newValue == \"\" {\n\t\treturn\n\t}\n\tvar floatNewValue float64\n\tfloatNewValue, err = strconv.ParseFloat(newValue, 64)\n\tif err != nil {\n\t\treturn\n\t}\n\tvalue.SetFloat(floatNewValue)\n\treturn\n}\n\nfunc reflectString(field *reflect.StructField, value *reflect.Value, tag string) (err error) {\n\tnewValue := getNewValue(field, value, tag, \"string\")\n\tif newValue == \"\" {\n\t\treturn\n\t}\n\tvalue.SetString(newValue)\n\treturn\n}\n\nfunc reflectBool(field *reflect.StructField, value *reflect.Value, tag string) (err error) {\n\tnewValue := getNewValue(field, value, tag, \"bool\")\n\tif newValue == \"\" {\n\t\treturn\n\t}\n\tnewBoolValue := newValue == \"true\" || newValue == \"t\"\n\tvalue.SetBool(newBoolValue)\n\treturn\n}\n\n\/\/ PrintDefaults print the default help\nfunc PrintDefaults() {\n\tfmt.Println(\"Environment variables:\")\n\tfmt.Println(PrintDefaultsOutput)\n}\n\n\/\/ DefaultUsage is assigned for Usage function by default\nfunc DefaultUsage() {\n\tfmt.Println(\"Usage\")\n\tPrintDefaults()\n}\n<|endoftext|>"}
{"text":"<commit_before>package gopikacloud\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n)\n\nconst (\n\tdefaultBaseURL = \"https:\/\/pikacloud.com\/api\/\"\n\tapiVersion     = \"v1\"\n)\n\n\/\/ Client manages communication with Pikacloud API.\ntype Client struct {\n\t\/\/ API Token for authenticating\n\tAPIToken string\n\t\/\/ HTTP client used to communicate with the Pikacloud API.\n\tHTTPClient *http.Client\n\t\/\/ Base URL for API requests.\n\tBaseURL string\n}\n\n\/\/ NewClient users\nfunc NewClient(apiToken string) *Client {\n\treturn &Client{APIToken: apiToken, HTTPClient: &http.Client{}, BaseURL: defaultBaseURL}\n}\n\nfunc (client *Client) makeRequest(method, path string, body io.Reader) (*http.Request, error) {\n\turl := client.BaseURL + fmt.Sprintf(\"%s\/%s\", apiVersion, path)\n\treq, err := http.NewRequest(method, url, body)\n\treq.Header.Add(\"Authorization: Token\", fmt.Sprintf(\"%s\", client.APIToken))\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\treq.Header.Add(\"Accept\", \"application\/json\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}\n\nfunc (client *Client) get(path string, val interface{}) error {\n\tbody, _, err := client.sendRequest(\"GET\", path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = json.Unmarshal([]byte(body), &val); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (client *Client) delete(path string, val interface{}) error {\n\t_, _, err := client.sendRequest(\"DELETE\", path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (client *Client) sendRequest(method, path string, body io.Reader) (string, int, error) {\n\treq, err := client.makeRequest(method, path, body)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\n\tresp, err := client.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\tresponseBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\n\treturn string(responseBytes), resp.StatusCode, nil\n}\n<commit_msg>fix auth header key<commit_after>package gopikacloud\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n)\n\nconst (\n\tdefaultBaseURL = \"https:\/\/pikacloud.com\/api\/\"\n\tapiVersion     = \"v1\"\n)\n\n\/\/ Client manages communication with Pikacloud API.\ntype Client struct {\n\t\/\/ API Token for authenticating\n\tAPIToken string\n\t\/\/ HTTP client used to communicate with the Pikacloud API.\n\tHTTPClient *http.Client\n\t\/\/ Base URL for API requests.\n\tBaseURL string\n}\n\n\/\/ NewClient users\nfunc NewClient(apiToken string) *Client {\n\treturn &Client{APIToken: apiToken, HTTPClient: &http.Client{}, BaseURL: defaultBaseURL}\n}\n\nfunc (client *Client) makeRequest(method, path string, body io.Reader) (*http.Request, error) {\n\turl := client.BaseURL + fmt.Sprintf(\"%s\/%s\", apiVersion, path)\n\treq, err := http.NewRequest(method, url, body)\n\treq.Header.Add(\"Authorization\", fmt.Sprintf(\"Token: %s\", client.APIToken))\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\treq.Header.Add(\"Accept\", \"application\/json\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}\n\nfunc (client *Client) get(path string, val interface{}) error {\n\tbody, _, err := client.sendRequest(\"GET\", path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = json.Unmarshal([]byte(body), &val); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (client *Client) delete(path string, val interface{}) error {\n\t_, _, err := client.sendRequest(\"DELETE\", path, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (client *Client) sendRequest(method, path string, body io.Reader) (string, int, error) {\n\treq, err := client.makeRequest(method, path, body)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\n\tresp, err := client.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\tdefer resp.Body.Close()\n\n\tresponseBytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", 0, err\n\t}\n\n\treturn string(responseBytes), resp.StatusCode, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package gorobokassa\n\nimport (\n\t\"crypto\/md5\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tQUERY_OUT_SUMM    = \"OutSum\"\n\tQUERY_INV_ID      = \"InvId\"\n\tQUERY_CRC         = \"SignatureValue\"\n\tQUERY_DESCRIPTION = \"Desc\"\n\tQUERY_LOGIN       = \"MrchLogin\"\n\tROBOKASSA_HOST    = \"auth.robokassa.ru\"\n\tROBOKASSA_PATH    = \"Merchant\/Index.aspx\"\n\tSCHEME            = \"https\"\n\tDELIMETER         = \":\"\n)\n\nvar (\n\tErrIncorrectValue = errors.New(\"incorrect value\")\n)\n\ntype Client struct {\n\tlogin          string\n\tfirstPassword  string\n\tsecondPassword string\n}\n\n\/\/ формирование URL переадресации пользователя на оплату\nfunc (client *Client) Url(invoice, value int, description string) string {\n\treturn buildRedirectUrl(client.login, client.firstPassword, invoice, value, description)\n}\n\n\/\/ получение уведомления об исполнении операции (ResultURL)\nfunc (client *Client) CheckResult(r *http.Request) bool {\n\treturn verifyRequest(client.secondPassword, r)\n}\n\n\/\/ проверка параметров в скрипте завершения операции (SuccessURL)\nfunc (client *Client) CheckSuccess(r *http.Request) bool {\n\treturn verifyRequest(client.firstPassword, r)\n}\n\nfunc New(login, password1, password2 string) *Client {\n\treturn &Client{login, password1, password2}\n}\n\n\/\/ join values with delimeter and return hex of md5\nfunc CRC(v ...interface{}) string {\n\ts := make([]string, len(v))\n\tfor key, value := range v {\n\t\ts[key] = fmt.Sprintf(\"%v\", value)\n\t}\n\th := md5.New()\n\tio.WriteString(h, strings.Join(s, DELIMETER))\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}\n\nfunc buildRedirectUrl(login, password string, invoice, value int, description string) string {\n\tq := url.URL{}\n\tq.Host = ROBOKASSA_HOST\n\tq.Scheme = SCHEME\n\tq.Path = ROBOKASSA_PATH\n\n\tparams := url.Values{}\n\tparams.Add(QUERY_LOGIN, login)\n\tparams.Add(QUERY_OUT_SUMM, strconv.Itoa(value))\n\tparams.Add(QUERY_INV_ID, strconv.Itoa(invoice))\n\tparams.Add(QUERY_DESCRIPTION, description)\n\tparams.Add(QUERY_CRC, CRC(login, value, invoice, password))\n\n\tq.RawQuery = params.Encode()\n\treturn q.String()\n}\n\nfunc verifyResult(password string, invoice, value int, crc string) bool {\n\treturn strings.ToUpper(crc) == strings.ToUpper(CRC(value, invoice, password))\n}\n\nfunc verifyRequest(password string, r *http.Request) bool {\n\tq := r.URL.Query()\n\tvalue, err := strconv.Atoi(q.Get(QUERY_OUT_SUMM))\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn false\n\t}\n\tinvoice, err := strconv.Atoi(q.Get(QUERY_INV_ID))\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn false\n\t}\n\tcrc := q.Get(QUERY_CRC)\n\treturn verifyResult(password, invoice, value, crc)\n}\n<commit_msg>removed errors<commit_after>package gorobokassa\n\nimport (\n\t\"crypto\/md5\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\tQUERY_OUT_SUMM    = \"OutSum\"\n\tQUERY_INV_ID      = \"InvId\"\n\tQUERY_CRC         = \"SignatureValue\"\n\tQUERY_DESCRIPTION = \"Desc\"\n\tQUERY_LOGIN       = \"MrchLogin\"\n\tROBOKASSA_HOST    = \"auth.robokassa.ru\"\n\tROBOKASSA_PATH    = \"Merchant\/Index.aspx\"\n\tSCHEME            = \"https\"\n\tDELIMETER         = \":\"\n)\n\ntype Client struct {\n\tlogin          string\n\tfirstPassword  string\n\tsecondPassword string\n}\n\n\/\/ формирование URL переадресации пользователя на оплату\nfunc (client *Client) Url(invoice, value int, description string) string {\n\treturn buildRedirectUrl(client.login, client.firstPassword, invoice, value, description)\n}\n\n\/\/ получение уведомления об исполнении операции (ResultURL)\nfunc (client *Client) CheckResult(r *http.Request) bool {\n\treturn verifyRequest(client.secondPassword, r)\n}\n\n\/\/ проверка параметров в скрипте завершения операции (SuccessURL)\nfunc (client *Client) CheckSuccess(r *http.Request) bool {\n\treturn verifyRequest(client.firstPassword, r)\n}\n\nfunc New(login, password1, password2 string) *Client {\n\treturn &Client{login, password1, password2}\n}\n\n\/\/ join values with delimeter and return hex of md5\nfunc CRC(v ...interface{}) string {\n\ts := make([]string, len(v))\n\tfor key, value := range v {\n\t\ts[key] = fmt.Sprintf(\"%v\", value)\n\t}\n\th := md5.New()\n\tio.WriteString(h, strings.Join(s, DELIMETER))\n\treturn fmt.Sprintf(\"%x\", h.Sum(nil))\n}\n\nfunc buildRedirectUrl(login, password string, invoice, value int, description string) string {\n\tq := url.URL{}\n\tq.Host = ROBOKASSA_HOST\n\tq.Scheme = SCHEME\n\tq.Path = ROBOKASSA_PATH\n\n\tparams := url.Values{}\n\tparams.Add(QUERY_LOGIN, login)\n\tparams.Add(QUERY_OUT_SUMM, strconv.Itoa(value))\n\tparams.Add(QUERY_INV_ID, strconv.Itoa(invoice))\n\tparams.Add(QUERY_DESCRIPTION, description)\n\tparams.Add(QUERY_CRC, CRC(login, value, invoice, password))\n\n\tq.RawQuery = params.Encode()\n\treturn q.String()\n}\n\nfunc verifyResult(password string, invoice, value int, crc string) bool {\n\treturn strings.ToUpper(crc) == strings.ToUpper(CRC(value, invoice, password))\n}\n\nfunc verifyRequest(password string, r *http.Request) bool {\n\tq := r.URL.Query()\n\tvalue, err := strconv.Atoi(q.Get(QUERY_OUT_SUMM))\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn false\n\t}\n\tinvoice, err := strconv.Atoi(q.Get(QUERY_INV_ID))\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn false\n\t}\n\tcrc := q.Get(QUERY_CRC)\n\treturn verifyResult(password, invoice, value, crc)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Riemann middleware for martini framework\n\/\/\n\/\/ Copyright (C) 2014 by Christopher Gilbert <christopher.john.gilbert@gmail.com>\npackage gorymartini\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/bigdatadev\/goryman\"\n\t\"github.com\/go-martini\/martini\"\n)\n\n\/\/ NewGoryMartini - Factory\nfunc NewGoryMartini(host string) (*goryman.GorymanClient, martini.Handler) {\n\triemann := goryman.NewGorymanClient(host)\n\terr := riemann.Connect()\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\treturn riemann, func(res http.ResponseWriter, req *http.Request, c martini.Context, log *log.Logger) {\n\t\tstart := time.Now()\n\n\t\trw := res.(martini.ResponseWriter)\n\t\tc.Next()\n\n\t\tmetric := float64(time.Since(start))\n\n\t\terr := riemann.SendEvent(&goryman.Event{\n\t\t\tService:     \"http req\",\n\t\t\tMetric:      metric,\n\t\t\tDescription: fmt.Sprintf(\"Request took %f seconds.\", metric),\n\t\t\tTags: []string{\n\t\t\t\t\"http\",\n\t\t\t},\n\t\t\tAttributes: map[string]string{\n\t\t\t\t\"path\":   req.URL.Path,\n\t\t\t\t\"status\": strconv.Itoa(rw.Status()),\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Riemann client SendEvent failed!\")\n\t\t}\n\t}\n}\n<commit_msg>Fixed time conversion<commit_after>\/\/ Riemann middleware for martini framework\n\/\/\n\/\/ Copyright (C) 2014 by Christopher Gilbert <christopher.john.gilbert@gmail.com>\npackage gorymartini\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/bigdatadev\/goryman\"\n\t\"github.com\/go-martini\/martini\"\n)\n\n\/\/ NewGoryMartini - Factory\nfunc NewGoryMartini(host string) (*goryman.GorymanClient, martini.Handler) {\n\triemann := goryman.NewGorymanClient(host)\n\terr := riemann.Connect()\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\treturn riemann, func(res http.ResponseWriter, req *http.Request, c martini.Context, log *log.Logger) {\n\t\tstart := time.Now()\n\n\t\trw := res.(martini.ResponseWriter)\n\t\tc.Next()\n\n\t\tmetric := float64(time.Since(start)) \/ float64(time.Millisecond)\n\n\t\terr := riemann.SendEvent(&goryman.Event{\n\t\t\tService:     \"http req\",\n\t\t\tMetric:      metric,\n\t\t\tDescription: fmt.Sprintf(\"Request took %f seconds.\", metric),\n\t\t\tTags: []string{\n\t\t\t\t\"http\",\n\t\t\t},\n\t\t\tAttributes: map[string]string{\n\t\t\t\t\"path\":   req.URL.Path,\n\t\t\t\t\"status\": strconv.Itoa(rw.Status()),\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"Riemann client SendEvent failed!\")\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package gowebsocket is a websocket library.\n\/\/ Currently functional api - will improve and add OO alternative.\npackage gowebsocket\n\nimport (\n\t\"fmt\"\n\t\"golang.org\/x\/net\/websocket\"\n\t\"io\"\n\t\"math\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/ WebscketServer is the main struct representing the server.\ntype WebsocketServer struct{}\n\n\/\/ SocketHandler is an alias.\ntype SocketHandler func(*websocket.Conn)\n\n\/\/ CustomHandler is an alias.\ntype CustomHandler func([]byte, func(string))\n\n\/\/ NewWensocketServer returns a new WebsocketServer.\nfunc NewWebsocketServer() *WebsocketServer {\n\treturn &WebsocketServer{}\n}\n\n\/\/ Add adds a route and an associated handler function.\nfunc (s *WebsocketServer) Add(route string, handlerFn CustomHandler) {\n\thttp.Handle(route, websocket.Handler(getSocketHandler(handlerFn)))\n}\n\n\/\/ Start starts the server listening for the specified routes.\nfunc (s *WebsocketServer) Start() {\n\tfmt.Println(\"Starting websocket server...\")\n\t\/\/ Server an example client html page.\n\ts.serveExampleClientPage()\n\t\/\/ Add builtin fixed routes - will probably remove.\n\ts.addBuiltinRoutes()\n\terr := http.ListenAndServe(\":8080\", nil)\n\tif err != nil {\n\t\tpanic(\"ListenAndServe: \" + err.Error())\n\t}\n}\n\n\/\/ getSocketHandler returns a handler to be asscociated with a route.\n\/\/ The handler wraps the client-provided handler, receives request data\n\/\/ from the websocket, passes it on to the wrapped handler, along with a\n\/\/ send function for the wrapped handler to use to send the response.\nfunc getSocketHandler(myCustHandler CustomHandler) SocketHandler {\n\treturn func(ws *websocket.Conn) {\n\t\tvar in []byte\n\t\tif err := websocket.Message.Receive(ws, &in); err != nil {\n\t\t\tfmt.Println(\"Err,\", err)\n\t\t}\n\t\toutFn := func(msg string) {\n\t\t\twebsocket.Message.Send(ws, msg)\n\t\t}\n\t\tmyCustHandler(in, outFn)\n\t}\n}\n\n\/*\n * The below is non-essential and will be (re)moved at some point.\n *\/\n\n\/\/ serveExampleClientPage serves a html page which will communicate with the websocket server.\nfunc (s *WebsocketServer) serveExampleClientPage() {\n\thandler := func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"socketbasic.html\")\n\t}\n\thttp.HandleFunc(\"\/\", handler)\n}\n\n\/\/ addBuiltinRoutes adds some routes that might be useful, eg for debugging.\nfunc (s *WebsocketServer) addBuiltinRoutes() {\n\t\/\/ Http handlers - http:\/\/\n\t\/\/http.HandleFunc(\"\/\", reqDump)\n\t\/\/fs := http.FileServer(http.Dir(\".\"))\n\t\/\/http.Handle(\"\/builtin\/\", http.StripPrefix(\"\/builtin\/\", fs))\n\n\t\/\/http.Handle(\"\/\", http.FileServer(http.Dir(\".\")))\n\n\t\/\/ Websocket handlers - ws:\/\/\n\t\/\/http.Handle(\"\/echo\", websocket.Handler(webHandler))\n\t\/\/http.Handle(\"\/\", websocket.Handler(webHandler))\n}\n\n\/\/ reqDump might be useful for debugging.\nfunc reqDump(c http.ResponseWriter, req *http.Request) {\n\tfmt.Println(\"Received request for url:\", req.URL)\n\tc.Write([]byte(\"Nice.\"))\n}\n\n\/\/ echoHandler might be useful for debugging.\nfunc echoHandler(ws *websocket.Conn) {\n\tfmt.Println(\"Echoing.\")\n\tio.Copy(ws, ws)\n}\n\n\/\/ webHandler is a sample fake data feed.\nfunc webHandler(ws *websocket.Conn) {\n\tfmt.Println(\"rx\")\n\tvar in []byte\n\tif err := websocket.Message.Receive(ws, &in); err != nil {\n\t\tfmt.Println(\"Err,\", err)\n\t\treturn\n\t}\n\n\tfor i := 0; i < 100; i++ {\n\t\tfor j := 0; j < 10; j++ {\n\t\t\trad := (math.Pi * 2) \/ 10 * float64(j)\n\t\t\tresponse := strconv.FormatFloat(rad, 'f', 6, 64)\n\t\t\twebsocket.Message.Send(ws, response)\n\t\t\ttime.Sleep(time.Millisecond * 100)\n\t\t}\n\t}\n}\n<commit_msg>Moved socket client route to a separate object.<commit_after>\/\/ Package gowebsocket is a websocket library.\n\/\/ Currently functional api - will improve and add OO alternative.\npackage gowebsocket\n\nimport (\n\t\"fmt\"\n\t\"golang.org\/x\/net\/websocket\"\n\t\"io\"\n\t\"math\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/ WebsocketServer is the main struct representing the websocket server.\ntype WebsocketServer struct{}\n\n\/\/ WebServer is a simple html server, useful for serving a websocket client.\ntype WebServer struct{}\n\n\/\/ SocketHandler is an alias.\ntype SocketHandler func(*websocket.Conn)\n\n\/\/ CustomHandler is an alias.\ntype CustomHandler func([]byte, func(string))\n\n\/\/ NewWebsocketServer returns a new WebsocketServer.\nfunc NewWebsocketServer() *WebsocketServer {\n\treturn &WebsocketServer{}\n}\n\n\/\/ NewWebServer returns a new WebServer.\nfunc NewWebServer() *WebServer {\n\treturn &WebServer{}\n}\n\n\/\/ Add adds a route and an associated handler function.\nfunc (s *WebsocketServer) Add(route string, handlerFn CustomHandler) {\n\thttp.Handle(route, websocket.Handler(getSocketHandler(handlerFn)))\n}\n\n\/\/ Start starts the server listening for the specified routes.\nfunc (s *WebsocketServer) Start() {\n\tfmt.Println(\"Starting websocket server...\")\n\t\/\/ Serve an example client html page.\n\tw := NewWebServer()\n\tw.serveExampleClientPage()\n\t\/\/ Add builtin fixed routes - will probably remove.\n\ts.addBuiltinRoutes()\n\terr := http.ListenAndServe(\":8080\", nil)\n\tif err != nil {\n\t\tpanic(\"ListenAndServe: \" + err.Error())\n\t}\n}\n\n\/\/ getSocketHandler returns a handler to be asscociated with a route.\n\/\/ The handler wraps the client-provided handler, receives request data\n\/\/ from the websocket, passes it on to the wrapped handler, along with a\n\/\/ send function for the wrapped handler to use to send the response.\nfunc getSocketHandler(myCustHandler CustomHandler) SocketHandler {\n\treturn func(ws *websocket.Conn) {\n\t\tvar in []byte\n\t\tif err := websocket.Message.Receive(ws, &in); err != nil {\n\t\t\tfmt.Println(\"Err,\", err)\n\t\t}\n\t\toutFn := func(msg string) {\n\t\t\twebsocket.Message.Send(ws, msg)\n\t\t}\n\t\tmyCustHandler(in, outFn)\n\t}\n}\n\n\/*\n * The below is non-essential and will be (re)moved at some point.\n *\/\n\n\/\/ serveExampleClientPage serves a html page which will communicate with the websocket server.\nfunc (s *WebServer) serveExampleClientPage() {\n\thandler := func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.ServeFile(w, r, \"socketbasic.html\")\n\t}\n\thttp.HandleFunc(\"\/\", handler)\n\t\/\/ Putting this here for possible later use.\n\t\/\/err := http.ListenAndServe(\":8081\", nil)\n\t\/\/if err != nil {\n\t\/\/\tpanic(\"ListenAndServe: \" + err.Error())\n\t\/\/}\n\n}\n\n\/\/ addBuiltinRoutes adds some routes that might be useful, eg for debugging.\nfunc (s *WebsocketServer) addBuiltinRoutes() {\n\t\/\/ Http handlers - http:\/\/\n\t\/\/http.HandleFunc(\"\/\", reqDump)\n\t\/\/fs := http.FileServer(http.Dir(\".\"))\n\t\/\/http.Handle(\"\/builtin\/\", http.StripPrefix(\"\/builtin\/\", fs))\n\n\t\/\/http.Handle(\"\/\", http.FileServer(http.Dir(\".\")))\n\n\t\/\/ Websocket handlers - ws:\/\/\n\t\/\/http.Handle(\"\/echo\", websocket.Handler(webHandler))\n\t\/\/http.Handle(\"\/\", websocket.Handler(webHandler))\n}\n\n\/\/ reqDump might be useful for debugging.\nfunc reqDump(c http.ResponseWriter, req *http.Request) {\n\tfmt.Println(\"Received request for url:\", req.URL)\n\tc.Write([]byte(\"Nice.\"))\n}\n\n\/\/ echoHandler might be useful for debugging.\nfunc echoHandler(ws *websocket.Conn) {\n\tfmt.Println(\"Echoing.\")\n\tio.Copy(ws, ws)\n}\n\n\/\/ webHandler is a sample fake data feed.\nfunc webHandler(ws *websocket.Conn) {\n\tfmt.Println(\"rx\")\n\tvar in []byte\n\tif err := websocket.Message.Receive(ws, &in); err != nil {\n\t\tfmt.Println(\"Err,\", err)\n\t\treturn\n\t}\n\n\tfor i := 0; i < 100; i++ {\n\t\tfor j := 0; j < 10; j++ {\n\t\t\trad := (math.Pi * 2) \/ 10 * float64(j)\n\t\t\tresponse := strconv.FormatFloat(rad, 'f', 6, 64)\n\t\t\twebsocket.Message.Send(ws, response)\n\t\t\ttime.Sleep(time.Millisecond * 100)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>2bb474b4-2e55-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>1f37a642-2e56-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>edcf5fce-2e54-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"}
{"text":"<commit_before>package parser\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/elpinal\/coco3\/extra\/ast\"\n)\n\nfunc TestParse(t *testing.T) {\n\ttests := []struct {\n\t\tsrc  string\n\t\tname string\n\t\targs []ast.Expr\n\t}{\n\t\t{\n\t\t\tsrc:  \"aa 'b'\",\n\t\t\tname: \"aa\",\n\t\t\targs: []ast.Expr{&ast.String{Lit: \"b\"}},\n\t\t},\n\t\t{\n\t\t\tsrc:  \"a 'u' : 'v' : []\",\n\t\t\tname: \"a\",\n\t\t\targs: []ast.Expr{\n\t\t\t\t&ast.Cons{\n\t\t\t\t\tHead: \"u\",\n\t\t\t\t\tTail: &ast.Cons{\n\t\t\t\t\t\tHead: \"v\",\n\t\t\t\t\t\tTail: &ast.Empty{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tsrc:  \"a-b ['u', 'v']\",\n\t\t\tname: \"a-b\",\n\t\t\targs: []ast.Expr{\n\t\t\t\t&ast.Cons{\n\t\t\t\t\tHead: \"u\",\n\t\t\t\t\tTail: &ast.Cons{\n\t\t\t\t\t\tHead: \"v\",\n\t\t\t\t\t\tTail: &ast.Empty{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tsrc:  \"a-b1-2190 [''] 8\",\n\t\t\tname: \"a-b1-2190\",\n\t\t\targs: []ast.Expr{\n\t\t\t\t&ast.Cons{\n\t\t\t\t\tHead: \"\",\n\t\t\t\t\tTail: &ast.Empty{},\n\t\t\t\t},\n\t\t\t\t&ast.Int{\n\t\t\t\t\tLit: \"8\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tsrc:  `a '{{range .Imports}}{{. | printf \"%s\\\\n\"}}{{end}}'`,\n\t\t\tname: \"a\",\n\t\t\targs: []ast.Expr{\n\t\t\t\t&ast.String{\n\t\t\t\t\tLit: `{{range .Imports}}{{. | printf \"%s\\n\"}}{{end}}`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tsrc:  \"!cmd\",\n\t\t\tname: \"exec\",\n\t\t\targs: []ast.Expr{&ast.String{Lit: \"cmd\"}},\n\t\t},\n\t\t{\n\t\t\tsrc:  \"!cmd []\",\n\t\t\tname: \"exec\",\n\t\t\targs: []ast.Expr{&ast.String{Lit: \"cmd\"}, &ast.Empty{}},\n\t\t},\n\t\t{\n\t\t\tsrc:  \"! cmd ['arg']\",\n\t\t\tname: \"exec\",\n\t\t\targs: []ast.Expr{&ast.String{Lit: \"cmd\"}, &ast.Cons{&ast.String{\"arg\"}, &ast.Empty{}}},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tx, err := Parse([]byte(test.src))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Parse(%q): %v\", test.src, err)\n\t\t}\n\t\tif x.Name.Lit != test.name {\n\t\t\tt.Fatalf(\"Parse(%q).Lit != %s; got %s\", test.src, test.name, x.Name.Lit)\n\t\t}\n\t\tif !reflect.DeepEqual(x.Args, test.args) {\n\t\t\tt.Errorf(\"Parse(%q).Args != %v; got %v\", test.src, test.args, x.Args)\n\t\t}\n\t}\n}\n\nfunc TestParseFail(t *testing.T) {\n\ttests := []string{\n\t\t\"aa '\",\n\t\t\"'a'\",\n\t\t\"12\",\n\t\t\"a :\",\n\t\t\"a [\",\n\t\t\"a ?--#b\",\n\t\t`a \"bc\\3df\"`,\n\t\t\"a ['\",\n\t}\n\tfor _, src := range tests {\n\t\tgot, err := Parse([]byte(src))\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Parse(%q): unexpectedly succeeded\", src)\n\t\t\tt.Fatalf(\"got: %v\", got)\n\t\t}\n\t}\n}\n\nfunc match(s, q string) bool {\n\treturn strings.Contains(s, q)\n}\n\nfunc TestInvalidEscapeSequence(t *testing.T) {\n\t_, err := Parse([]byte(`a '\\Z'`))\n\tif err == nil {\n\t\tt.Fatalf(\"Parse: unexpectedly succeeded\")\n\t}\n\tp := `unknown escape sequence: \\Z`\n\tif !match(err.(*ParseError).Msg, p) {\n\t\tt.Log(\"missing message about escape sequence in error message\")\n\t\tt.Logf(\"pattern %q not found\", p)\n\t\tt.FailNow()\n\t}\n}\n<commit_msg>Fix test<commit_after>package parser\n\nimport (\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/elpinal\/coco3\/extra\/ast\"\n)\n\nfunc TestParse(t *testing.T) {\n\ttests := []struct {\n\t\tsrc  string\n\t\tname string\n\t\targs []ast.Expr\n\t}{\n\t\t{\n\t\t\tsrc:  \"aa 'b'\",\n\t\t\tname: \"aa\",\n\t\t\targs: []ast.Expr{&ast.String{Lit: \"b\"}},\n\t\t},\n\t\t{\n\t\t\tsrc:  \"a 'u' : 'v' : []\",\n\t\t\tname: \"a\",\n\t\t\targs: []ast.Expr{\n\t\t\t\t&ast.Cons{\n\t\t\t\t\tHead: \"u\",\n\t\t\t\t\tTail: &ast.Cons{\n\t\t\t\t\t\tHead: \"v\",\n\t\t\t\t\t\tTail: &ast.Empty{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tsrc:  \"a-b ['u', 'v']\",\n\t\t\tname: \"a-b\",\n\t\t\targs: []ast.Expr{\n\t\t\t\t&ast.Cons{\n\t\t\t\t\tHead: \"u\",\n\t\t\t\t\tTail: &ast.Cons{\n\t\t\t\t\t\tHead: \"v\",\n\t\t\t\t\t\tTail: &ast.Empty{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tsrc:  \"a-b1-2190 [''] 8\",\n\t\t\tname: \"a-b1-2190\",\n\t\t\targs: []ast.Expr{\n\t\t\t\t&ast.Cons{\n\t\t\t\t\tHead: \"\",\n\t\t\t\t\tTail: &ast.Empty{},\n\t\t\t\t},\n\t\t\t\t&ast.Int{\n\t\t\t\t\tLit: \"8\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tsrc:  `a '{{range .Imports}}{{. | printf \"%s\\\\n\"}}{{end}}'`,\n\t\t\tname: \"a\",\n\t\t\targs: []ast.Expr{\n\t\t\t\t&ast.String{\n\t\t\t\t\tLit: `{{range .Imports}}{{. | printf \"%s\\n\"}}{{end}}`,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tsrc:  \"!cmd\",\n\t\t\tname: \"exec\",\n\t\t\targs: []ast.Expr{&ast.String{Lit: \"cmd\"}},\n\t\t},\n\t\t{\n\t\t\tsrc:  \"!cmd []\",\n\t\t\tname: \"exec\",\n\t\t\targs: []ast.Expr{&ast.String{Lit: \"cmd\"}, &ast.Empty{}},\n\t\t},\n\t\t{\n\t\t\tsrc:  \"! cmd ['arg']\",\n\t\t\tname: \"exec\",\n\t\t\targs: []ast.Expr{&ast.String{Lit: \"cmd\"}, &ast.Cons{\"arg\", &ast.Empty{}}},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tx, err := Parse([]byte(test.src))\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Parse(%q): %v\", test.src, err)\n\t\t}\n\t\tif x.Name.Lit != test.name {\n\t\t\tt.Fatalf(\"Parse(%q).Lit != %s; got %s\", test.src, test.name, x.Name.Lit)\n\t\t}\n\t\tif !reflect.DeepEqual(x.Args, test.args) {\n\t\t\tt.Errorf(\"Parse(%q).Args != %v; got %v\", test.src, test.args, x.Args)\n\t\t}\n\t}\n}\n\nfunc TestParseFail(t *testing.T) {\n\ttests := []string{\n\t\t\"aa '\",\n\t\t\"'a'\",\n\t\t\"12\",\n\t\t\"a :\",\n\t\t\"a [\",\n\t\t\"a ?--#b\",\n\t\t`a \"bc\\3df\"`,\n\t\t\"a ['\",\n\t}\n\tfor _, src := range tests {\n\t\tgot, err := Parse([]byte(src))\n\t\tif err == nil {\n\t\t\tt.Errorf(\"Parse(%q): unexpectedly succeeded\", src)\n\t\t\tt.Fatalf(\"got: %v\", got)\n\t\t}\n\t}\n}\n\nfunc match(s, q string) bool {\n\treturn strings.Contains(s, q)\n}\n\nfunc TestInvalidEscapeSequence(t *testing.T) {\n\t_, err := Parse([]byte(`a '\\Z'`))\n\tif err == nil {\n\t\tt.Fatalf(\"Parse: unexpectedly succeeded\")\n\t}\n\tp := `unknown escape sequence: \\Z`\n\tif !match(err.(*ParseError).Msg, p) {\n\t\tt.Log(\"missing message about escape sequence in error message\")\n\t\tt.Logf(\"pattern %q not found\", p)\n\t\tt.FailNow()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package message\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\n\/\/ Errors used by implementers of the MessageSet interface.\nvar (\n\tErrMultipleCodecs = errors.New(\"multiple codecs found\")\n\tErrNoMessages     = errors.New(\"no messages provided\")\n\tErrNilMessages    = errors.New(\"nil messages provided\")\n)\n\n\/\/ Constants used by implementers of the MessageSet interface.\nconst (\n\tOffsetLength  = 8\n\tMsgSizeLength = 4\n\tMsgOverhead   = MsgSizeLength + OffsetLength\n)\n\n\/\/ MessageSet is an in-memory sequential Message container with a fixed\n\/\/ serialization format.\n\/\/\n\/\/ With no compression enabled, each Message is laid out sequentially\n\/\/ and preceded by a header containing its offset and size.\n\/\/\n\/\/  -----------------------------------------------------------------\n\/\/  | offset | size | message | ... | offset+N | size N | message N |\n\/\/  -----------------------------------------------------------------\n\/\/\n\/\/ With compression enabled, the previous byte slice is compressed and set as\n\/\/ the value of a single Message within the MessageSet.\n\/\/\n\/\/  -----------------------------\n\/\/  | offset+N | size | message |\n\/\/  -----------------------------\n\/\/\ntype MessageSet struct{ buf []byte }\n\n\/\/ NewMessageSet returns a MessageSet containing the provided Messages.\n\/\/ The first offset is set to the provided one and increments from there for\n\/\/ each Message.\n\/\/\n\/\/ The compression Codec is found by iterating over all passed Messages and\n\/\/ verifying that they all have the same Codec, or an error is returned.\n\/\/ In case the Codec is valid, the resulting MessageSet will have a single\n\/\/ Message with its value set to the compressed original MessageSet.\n\/\/ If the compression fails an error will be returned.\nfunc NewMessageSet(offset uint64, msgs ...Message) (*MessageSet, error) {\n\tif len(msgs) == 0 {\n\t\treturn nil, ErrNoMessages\n\t} else if msgs[0] == nil {\n\t\treturn nil, ErrNilMessages\n\t}\n\tcodec, size := msgs[0].Codec(), MsgOverhead+msgs[0].Size()\n\n\tfor i := 1; i < len(msgs); i++ {\n\t\tif msgs[i] == nil {\n\t\t\treturn nil, ErrNilMessages\n\t\t} else if msgs[i].Codec() != codec {\n\t\t\treturn nil, ErrMultipleCodecs\n\t\t}\n\t\tsize += MsgOverhead + msgs[i].Size()\n\t}\n\n\tms := &MessageSet{make([]byte, size)}\n\tms.set(offset, msgs...)\n\tif err := ms.compress(offset, codec); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ms, nil\n}\n\n\/\/ Iterate calls fn for each Message in the MessageSet.\n\/\/ TODO: Support decompression.\nfunc (ms *MessageSet) Iterate(fn func(offset uint64, msg Message) bool) bool {\n\tvar (\n\t\toffset uint64\n\t\tsize   uint32\n\t)\n\tfor i := 0; i < ms.Size(); i += int(MsgOverhead + size) {\n\t\toffset = binary.BigEndian.Uint64(ms.buf[i : i+OffsetLength])\n\t\tsize = binary.BigEndian.Uint32(ms.buf[i+OffsetLength : i+MsgOverhead])\n\t\tif fn(offset, Message(ms.buf[i+MsgOverhead:i+int(MsgOverhead+size)])) {\n\t\t\treturn true \/\/ Halt iteration\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Size returns the byte size of the MessageSet.\nfunc (ms *MessageSet) Size() int {\n\treturn len(ms.buf)\n}\n\n\/\/ Equal returns whether other MessageSet is equal to ms.\nfunc (ms *MessageSet) Equal(other MessageSet) bool {\n\treturn bytes.Equal(ms.buf, other.buf)\n}\n\n\/\/ WriteTo implements the io.WriterTo interface.\nfunc (ms *MessageSet) WriteTo(w io.Writer) (int64, error) {\n\tn, err := w.Write(ms.buf)\n\treturn int64(n), err\n}\n\n\/\/ String implements the fmt.Stringer interface.\nfunc (ms *MessageSet) String() string {\n\tvar (\n\t\tstr bytes.Buffer\n\t\tlim = 100\n\t)\n\n\tfmt.Fprintln(&str, \"MessageSet{\")\n\thalted := ms.Iterate(func(_ uint64, msg Message) bool {\n\t\tif lim -= 1; lim == 0 {\n\t\t\treturn true\n\t\t}\n\t\tfmt.Fprintln(&str, \"  \", msg, \",\")\n\t\treturn false\n\t})\n\n\tif halted {\n\t\tfmt.Fprintln(&str, \"  ...\")\n\t}\n\n\tfmt.Fprint(&str, \"}\")\n\n\treturn str.String()\n}\n\n\/\/ set writes the provided Messages to the MessageSet\n\/\/ starting with the provided offset.\nfunc (ms *MessageSet) set(offset uint64, msgs ...Message) {\n\tvar n uint32\n\tfor i, msg := range msgs {\n\t\tbinary.BigEndian.PutUint64(ms.buf[n:], offset+uint64(i))\n\t\tbinary.BigEndian.PutUint32(ms.buf[n+OffsetLength:], msg.Size())\n\t\tn += uint32(MsgOverhead + copy(ms.buf[n+MsgOverhead:], msg))\n\t}\n\tms.buf = ms.buf[:n]\n}\n\n\/\/ compress reduces the MessageSet to a single Message which holds the\n\/\/ compressed payload in its value.\n\/\/ It returns an error when the Codec fails to compress.\nfunc (ms *MessageSet) compress(offset uint64, codec Codec) error {\n\tif codec == NoCodec {\n\t\treturn nil\n\t}\n\n\tvalue, err := codec.Compress(ms.buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.set(offset-1, NewMessage(nil, value, codec))\n\n\treturn nil\n}\n<commit_msg>message: MessageOffset<commit_after>package message\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\n\/\/ Errors used by implementers of the MessageSet interface.\nvar (\n\tErrMultipleCodecs = errors.New(\"multiple codecs found\")\n\tErrNoMessages     = errors.New(\"no messages provided\")\n\tErrNilMessages    = errors.New(\"nil messages provided\")\n)\n\n\/\/ Constants used by implementers of the MessageSet interface.\nconst (\n\tOffsetLength  = 8\n\tMsgSizeLength = 4\n\tMsgOverhead   = MsgSizeLength + OffsetLength\n)\n\n\/\/ MessageOffset is an utility type wrapping a Message and its offset within a\n\/\/ MessageSet.\ntype MessageOffset struct {\n\tOffset uint64\n\tMessage\n}\n\n\/\/ MessageSet is an in-memory sequential Message container with a fixed\n\/\/ serialization format.\n\/\/\n\/\/ With no compression enabled, each Message is laid out sequentially\n\/\/ and preceded by a header containing its offset and size.\n\/\/\n\/\/  -----------------------------------------------------------------\n\/\/  | offset | size | message | ... | offset+N | size N | message N |\n\/\/  -----------------------------------------------------------------\n\/\/\n\/\/ With compression enabled, the previous byte slice is compressed and set as\n\/\/ the value of a single Message within the MessageSet.\n\/\/\n\/\/  -----------------------------\n\/\/  | offset+N | size | message |\n\/\/  -----------------------------\n\/\/\ntype MessageSet struct{ buf []byte }\n\n\/\/ NewMessageSet returns a MessageSet containing the provided Messages.\n\/\/ The first offset is set to the provided one and increments from there for\n\/\/ each Message.\n\/\/\n\/\/ The compression Codec is found by iterating over all passed Messages and\n\/\/ verifying that they all have the same Codec, or an error is returned.\n\/\/ In case the Codec is valid, the resulting MessageSet will have a single\n\/\/ Message with its value set to the compressed original MessageSet.\n\/\/ If the compression fails an error will be returned.\nfunc NewMessageSet(offset uint64, msgs ...Message) (*MessageSet, error) {\n\tif len(msgs) == 0 {\n\t\treturn nil, ErrNoMessages\n\t} else if msgs[0] == nil {\n\t\treturn nil, ErrNilMessages\n\t}\n\tcodec, size := msgs[0].Codec(), MsgOverhead+msgs[0].Size()\n\n\tfor i := 1; i < len(msgs); i++ {\n\t\tif msgs[i] == nil {\n\t\t\treturn nil, ErrNilMessages\n\t\t} else if msgs[i].Codec() != codec {\n\t\t\treturn nil, ErrMultipleCodecs\n\t\t}\n\t\tsize += MsgOverhead + msgs[i].Size()\n\t}\n\n\tms := &MessageSet{make([]byte, size)}\n\tms.set(offset, msgs...)\n\tif err := ms.compress(offset, codec); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ms, nil\n}\n\n\/\/ Iterate calls fn for each Message in the MessageSet.\n\/\/ TODO: Support decompression.\nfunc (ms *MessageSet) Iterate(fn func(m MessageOffset) bool) bool {\n\tvar (\n\t\toffset uint64\n\t\tsize   uint32\n\t\tmsg    Message\n\t)\n\tfor i := 0; i < ms.Size(); i += int(MsgOverhead + size) {\n\t\toffset = binary.BigEndian.Uint64(ms.buf[i : i+OffsetLength])\n\t\tsize = binary.BigEndian.Uint32(ms.buf[i+OffsetLength : i+MsgOverhead])\n\t\tmsg = Message(ms.buf[i+MsgOverhead : i+int(MsgOverhead+size)])\n\t\tif fn(MessageOffset{Offset: offset, Message: msg}) {\n\t\t\treturn true \/\/ Halt iteration\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Size returns the byte size of the MessageSet.\nfunc (ms *MessageSet) Size() int {\n\treturn len(ms.buf)\n}\n\n\/\/ Equal returns whether other MessageSet is equal to ms.\nfunc (ms *MessageSet) Equal(other MessageSet) bool {\n\treturn bytes.Equal(ms.buf, other.buf)\n}\n\n\/\/ WriteTo implements the io.WriterTo interface.\nfunc (ms *MessageSet) WriteTo(w io.Writer) (int64, error) {\n\tn, err := w.Write(ms.buf)\n\treturn int64(n), err\n}\n\n\/\/ String implements the fmt.Stringer interface.\nfunc (ms *MessageSet) String() string {\n\tvar (\n\t\tstr bytes.Buffer\n\t\tlim = 100\n\t)\n\n\tfmt.Fprintln(&str, \"MessageSet{\")\n\thalted := ms.Iterate(func(m MessageOffset) bool {\n\t\tif lim -= 1; lim == 0 {\n\t\t\treturn true\n\t\t}\n\t\tfmt.Fprintf(&str, \"  %d: %s,\\n\", m.Offset, m)\n\t\treturn false\n\t})\n\n\tif halted {\n\t\tfmt.Fprintln(&str, \"  ...\")\n\t}\n\n\tfmt.Fprint(&str, \"}\")\n\n\treturn str.String()\n}\n\n\/\/ set writes the provided Messages to the MessageSet\n\/\/ starting with the provided offset.\nfunc (ms *MessageSet) set(offset uint64, msgs ...Message) {\n\tvar n uint32\n\tfor i, msg := range msgs {\n\t\tbinary.BigEndian.PutUint64(ms.buf[n:], offset+uint64(i))\n\t\tbinary.BigEndian.PutUint32(ms.buf[n+OffsetLength:], msg.Size())\n\t\tn += uint32(MsgOverhead + copy(ms.buf[n+MsgOverhead:], msg))\n\t}\n\tms.buf = ms.buf[:n]\n}\n\n\/\/ compress reduces the MessageSet to a single Message which holds the\n\/\/ compressed payload in its value.\n\/\/ It returns an error when the Codec fails to compress.\nfunc (ms *MessageSet) compress(offset uint64, codec Codec) error {\n\tif codec == NoCodec {\n\t\treturn nil\n\t}\n\n\tvalue, err := codec.Compress(ms.buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.set(offset-1, NewMessage(nil, value, codec))\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package framework\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/vault\/logical\"\n)\n\n\/\/ LeaseExtend returns an OperationFunc that can be used to simply extend the\n\/\/ lease of the auth\/secret for the duration that was requested.\n\/\/\n\/\/ backendIncrement is the backend's requested increment -- perhaps from a user\n\/\/ request, perhaps from a role\/config value. If not set, uses the mount\/system\n\/\/ value.\n\/\/\n\/\/ backendMax is the backend's requested increment -- this can be more\n\/\/ restrictive than the mount\/system value but not less.\n\/\/\n\/\/ systemView is the system view from the calling backend, used to determine\n\/\/ and\/or correct default\/max times.\nfunc LeaseExtend(backendIncrement, backendMax time.Duration, systemView logical.SystemView) OperationFunc {\n\treturn func(req *logical.Request, data *FieldData) (*logical.Response, error) {\n\t\tvar leaseOpts *logical.LeaseOptions\n\t\tswitch {\n\t\tcase req.Auth != nil:\n\t\t\tleaseOpts = &req.Auth.LeaseOptions\n\t\tcase req.Secret != nil:\n\t\t\tleaseOpts = &req.Secret.LeaseOptions\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"no lease options for request\")\n\t\t}\n\n\t\t\/\/ Use the mount's configured max unless the backend specifies\n\t\t\/\/ something more restrictive (perhaps from a role configuration\n\t\t\/\/ parameter)\n\t\tmax := systemView.MaxLeaseTTL()\n\t\tif backendMax > 0 && backendMax < max {\n\t\t\tmax = backendMax\n\t\t}\n\n\t\t\/\/ Should never happen, but guard anyways\n\t\tif max < 0 {\n\t\t\treturn nil, fmt.Errorf(\"max TTL is negative\")\n\t\t}\n\n\t\t\/\/ We cannot go past this time\n\t\tmaxValidTime := leaseOpts.IssueTime.UTC().Add(max)\n\n\t\t\/\/ Get the current time\n\t\tnow := time.Now().UTC()\n\n\t\t\/\/ If we are past the max TTL, we shouldn't be in this function...but\n\t\t\/\/ fast path out if we are\n\t\tif maxValidTime.Before(now) {\n\t\t\treturn nil, fmt.Errorf(\"past the max TTL, cannot renew\")\n\t\t}\n\n\t\t\/\/ Basic max safety checks have passed, now let's figure out our\n\t\t\/\/ increment. We'll use the backend-provided value if possible, or the\n\t\t\/\/ mount\/system default if not. We won't change the LeaseOpts value,\n\t\t\/\/ just adjust accordingly.\n\t\tincrement := leaseOpts.Increment\n\t\tif backendIncrement > 0 {\n\t\t\tincrement = backendIncrement\n\t\t}\n\t\tif increment <= 0 {\n\t\t\tincrement = systemView.DefaultLeaseTTL()\n\t\t}\n\n\t\tproposedExpiration := leaseOpts.IssueTime.UTC().Add(increment)\n\n\t\t\/\/ If the proposed expiration is after the maximum TTL of the lease,\n\t\t\/\/ cap the increment to whatever is left\n\t\tif maxValidTime.Before(proposedExpiration) {\n\t\t\tincrement = maxValidTime.Sub(now)\n\t\t}\n\n\t\t\/\/ Set the lease\n\t\tleaseOpts.TTL = increment\n\n\t\treturn &logical.Response{Auth: req.Auth, Secret: req.Secret}, nil\n\t}\n}\n<commit_msg>Update proposed time<commit_after>package framework\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/vault\/logical\"\n)\n\n\/\/ LeaseExtend returns an OperationFunc that can be used to simply extend the\n\/\/ lease of the auth\/secret for the duration that was requested.\n\/\/\n\/\/ backendIncrement is the backend's requested increment -- perhaps from a user\n\/\/ request, perhaps from a role\/config value. If not set, uses the mount\/system\n\/\/ value.\n\/\/\n\/\/ backendMax is the backend's requested increment -- this can be more\n\/\/ restrictive than the mount\/system value but not less.\n\/\/\n\/\/ systemView is the system view from the calling backend, used to determine\n\/\/ and\/or correct default\/max times.\nfunc LeaseExtend(backendIncrement, backendMax time.Duration, systemView logical.SystemView) OperationFunc {\n\treturn func(req *logical.Request, data *FieldData) (*logical.Response, error) {\n\t\tvar leaseOpts *logical.LeaseOptions\n\t\tswitch {\n\t\tcase req.Auth != nil:\n\t\t\tleaseOpts = &req.Auth.LeaseOptions\n\t\tcase req.Secret != nil:\n\t\t\tleaseOpts = &req.Secret.LeaseOptions\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"no lease options for request\")\n\t\t}\n\n\t\t\/\/ Use the mount's configured max unless the backend specifies\n\t\t\/\/ something more restrictive (perhaps from a role configuration\n\t\t\/\/ parameter)\n\t\tmax := systemView.MaxLeaseTTL()\n\t\tif backendMax > 0 && backendMax < max {\n\t\t\tmax = backendMax\n\t\t}\n\n\t\t\/\/ Should never happen, but guard anyways\n\t\tif max < 0 {\n\t\t\treturn nil, fmt.Errorf(\"max TTL is negative\")\n\t\t}\n\n\t\t\/\/ We cannot go past this time\n\t\tmaxValidTime := leaseOpts.IssueTime.UTC().Add(max)\n\n\t\t\/\/ Get the current time\n\t\tnow := time.Now().UTC()\n\n\t\t\/\/ If we are past the max TTL, we shouldn't be in this function...but\n\t\t\/\/ fast path out if we are\n\t\tif maxValidTime.Before(now) {\n\t\t\treturn nil, fmt.Errorf(\"past the max TTL, cannot renew\")\n\t\t}\n\n\t\t\/\/ Basic max safety checks have passed, now let's figure out our\n\t\t\/\/ increment. We'll use the backend-provided value if possible, or the\n\t\t\/\/ mount\/system default if not. We won't change the LeaseOpts value,\n\t\t\/\/ just adjust accordingly.\n\t\tincrement := leaseOpts.Increment\n\t\tif backendIncrement > 0 {\n\t\t\tincrement = backendIncrement\n\t\t}\n\t\tif increment <= 0 {\n\t\t\tincrement = systemView.DefaultLeaseTTL()\n\t\t}\n\n\t\t\/\/ We are proposing a time of the current time plus the increment\n\t\tproposedExpiration := now.Add(increment)\n\n\t\t\/\/ If the proposed expiration is after the maximum TTL of the lease,\n\t\t\/\/ cap the increment to whatever is left\n\t\tif maxValidTime.Before(proposedExpiration) {\n\t\t\tincrement = maxValidTime.Sub(now)\n\t\t}\n\n\t\t\/\/ Set the lease\n\t\tleaseOpts.TTL = increment\n\n\t\treturn &logical.Response{Auth: req.Auth, Secret: req.Secret}, nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2015 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n\/\/ Package semtech provides useful methods and types to handle communications with a gateway.\n\/\/\n\/\/ This package relies on the SemTech Protocol 1.2 accessible on github: https:\/\/github.com\/TheThingsNetwork\/packet_forwarder\/blob\/master\/PROTOCOL.TXT\npackage semtech\n\nimport (\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype DeviceAddress [4]byte\n\n\/\/ RXPK represents an uplink json message format sent by the gateway\ntype RXPK struct {\n\tChan    *uint          `json:\"chan,omitempty\"` \/\/ Concentrator \"IF\" channel used for RX (unsigned integer)\n\tCodr    *string        `json:\"codr,omitempty\"` \/\/ LoRa ECC coding rate identifier\n\tData    *string        `json:\"data,omitempty\"` \/\/ Base64 encoded RF packet payload, padded\n\tDatr    *string        `json:\"-\"`              \/\/ FSK datarate (unsigned in bit per second) || LoRa datarate identifier\n\tFreq    *float64       `json:\"freq,omitempty\"` \/\/ RX Central frequency in MHx (unsigned float, Hz precision)\n\tLsnr    *float64       `json:\"lsnr,omitempty\"` \/\/ LoRa SNR ratio in dB (signed float, 0.1 dB precision)\n\tModu    *string        `json:\"modu,omitempty\"` \/\/ Modulation identifier \"LORA\" or \"FSK\"\n\tRfch    *uint          `json:\"rfch,omitempty\"` \/\/ Concentrator \"RF chain\" used for RX (unsigned integer)\n\tRssi    *int           `json:\"rssi,omitempty\"` \/\/ RSSI in dBm (signed integer, 1 dB precision)\n\tSize    *uint          `json:\"size,omitempty\"` \/\/ RF packet payload size in bytes (unsigned integer)\n\tStat    *int           `json:\"stat,omitempty\"` \/\/ CRC status: 1 - OK, -1 = fail, 0 = no CRC\n\tTime    *time.Time     `json:\"-\"`              \/\/ UTC time of pkt RX, us precision, ISO 8601 'compact' format\n\tTmst    *uint          `json:\"tmst,omitempty\"` \/\/ Internal timestamp of \"RX finished\" event (32b unsigned)\n\tdevAddr *DeviceAddress \/\/ End-Device address, according to the Data. Memoized here.\n}\n\n\/\/ DevAddr returns the end-device address described in the payload\nfunc (rxpk *RXPK) DevAddr() *DeviceAddress {\n\tif rxpk.devAddr != nil {\n\t\treturn rxpk.devAddr\n\t}\n\n\tif rxpk.Data == nil {\n\t\treturn nil\n\t}\n\n\tbuf, err := base64.StdEncoding.DecodeString(*rxpk.Data)\n\tif err != nil || len(buf) < 5 {\n\t\treturn nil\n\t}\n\n\trxpk.devAddr = new(DeviceAddress)\n\tcopy((*rxpk.devAddr)[:], buf[1:5]) \/\/ Device Address corresponds to the first 4 bytes of the Frame Header, after one byte of MAC_HEADER\n\treturn rxpk.devAddr\n}\n\n\/\/ TXPK represents a downlink j,omitemptyson message format received by the gateway.\n\/\/ Most field are optional.\ntype TXPK struct {\n\tCodr    *string        `json:\"codr,omitempty\"`  \/\/ LoRa ECC coding rate identifier\n\tData    *string        `json:\"data,omirtmepty\"` \/\/ Base64 encoded RF packet payload, padding optional\n\tDatr    *string        `json:\"-\"`               \/\/ LoRa datarate identifier (eg. SF12BW500) || FSK Datarate (unsigned, in bits per second)\n\tFdev    *uint          `json:\"fdev,omitempty\"`  \/\/ FSK frequency deviation (unsigned integer, in Hz)\n\tFreq    *float64       `json:\"freq,omitempty\"`  \/\/ TX central frequency in MHz (unsigned float, Hz precision)\n\tImme    *bool          `json:\"imme,omitempty\"`  \/\/ Send packet immediately (will ignore tmst & time)\n\tIpol    *bool          `json:\"ipol,omitempty\"`  \/\/ Lora modulation polarization inversion\n\tModu    *string        `json:\"modu,omitempty\"`  \/\/ Modulation identifier \"LORA\" or \"FSK\"\n\tNcrc    *bool          `json:\"ncrc,omitempty\"`  \/\/ If true, disable the CRC of the physical layer (optional)\n\tPowe    *uint          `json:\"powe,omitempty\"`  \/\/ TX output power in dBm (unsigned integer, dBm precision)\n\tPrea    *uint          `json:\"prea,omitempty\"`  \/\/ RF preamble size (unsigned integer)\n\tRfch    *uint          `json:\"rfch,omitempty\"`  \/\/ Concentrator \"RF chain\" used for TX (unsigned integer)\n\tSize    *uint          `json:\"size,omitempty\"`  \/\/ RF packet payload size in bytes (unsigned integer)\n\tTime    *time.Time     `json:\"-\"`               \/\/ Send packet at a certain time (GPS synchronization required)\n\tTmst    *uint          `json:\"tmst,omitempty\"`  \/\/ Send packet on a certain timestamp value (will ignore time)\n\tdevAddr *DeviceAddress \/\/ End-Device address, according to the Data. Memoized here.\n}\n\n\/\/ DevAddr returns the end-device address described in the payload\nfunc (txpk *TXPK) DevAddr() *DeviceAddress {\n\tif txpk.devAddr != nil {\n\t\treturn txpk.devAddr\n\t}\n\n\tif txpk.Data == nil {\n\t\treturn nil\n\t}\n\n\tbuf, err := base64.StdEncoding.DecodeString(*txpk.Data)\n\tif err != nil || len(buf) < 5 {\n\t\treturn nil\n\t}\n\n\ttxpk.devAddr = new(DeviceAddress)\n\tcopy((*txpk.devAddr)[:], buf[1:5]) \/\/ Device Address corresponds to the first 4 bytes of the Frame Header, after one byte of MAC_HEADER\n\treturn txpk.devAddr\n}\n\n\/\/ Stat represents a status json message format sent by the gateway\ntype Stat struct {\n\tAckr *float64   `json:\"ackr,omitempty\"` \/\/ Percentage of upstream datagrams that were acknowledged\n\tAlti *int       `json:\"alti,omitempty\"` \/\/ GPS altitude of the gateway in meter RX (integer)\n\tDwnb *uint      `json:\"dwnb,omitempty\"` \/\/ Number of downlink datagrams received (unsigned integer)\n\tLati *float64   `json:\"lati,omitempty\"` \/\/ GPS latitude of the gateway in degree (float, N is +)\n\tLong *float64   `json:\"long,omitempty\"` \/\/ GPS latitude of the gateway in dgree (float, E is +)\n\tRxfw *uint      `json:\"rxfw,omitempty\"` \/\/ Number of radio packets forwarded (unsigned integer)\n\tRxnb *uint      `json:\"rxnb,omitempty\"` \/\/ Number of radio packets received (unsigned integer)\n\tRxok *uint      `json:\"rxok,omitempty\"` \/\/ Number of radio packets received with a valid PHY CRC\n\tTime *time.Time `json:\"-\"`              \/\/ UTC 'system' time of the gateway, ISO 8601 'expanded' format\n\tTxnb *uint      `json:\"txnb,omitempty\"` \/\/ Number of packets emitted (unsigned integer)\n}\n\n\/\/ Packet as seen by the gateway.\ntype Packet struct {\n\tVersion    byte     \/\/ Protocol version, should always be 1 here\n\tToken      []byte   \/\/ Random number generated by the gateway on some request. 2-bytes long.\n\tIdentifier byte     \/\/ Packet's command identifier\n\tGatewayId  []byte   \/\/ Source gateway's identifier (Only PULL_DATA and PUSH_DATA)\n\tPayload    *Payload \/\/ JSON payload transmitted if any, nil otherwise\n}\n\n\/\/ Payload refers to the JSON payload sent by a gateway or a server.\ntype Payload struct {\n\tRaw  []byte `json:\"-\"`              \/\/ The raw unparsed response\n\tRXPK []RXPK `json:\"rxpk,omitempty\"` \/\/ A list of RXPK messages transmitted if any\n\tStat *Stat  `json:\"stat,omitempty\"` \/\/ A Stat message transmitted if any\n\tTXPK *TXPK  `json:\"txpk,omitempty\"` \/\/ A TXPK message transmitted if any\n}\n\n\/\/ UniformDevAddr tries to extract a device address from the different part of a payload. If the\n\/\/ payload is composed of messages coming from several end-device, the method will fail.\nfunc (p Payload) UniformDevAddr() (*DeviceAddress, error) {\n\tvar devAddr *DeviceAddress\n\n\t\/\/ Determine the devAddress associated to that payload\n\tif p.RXPK == nil || len(p.RXPK) == 0 { \/\/ NOTE are those conditions significantly different ?\n\t\tif p.TXPK == nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to determine device address. No RXPK neither TXPK messages\")\n\t\t}\n\t\tif devAddr = p.TXPK.DevAddr(); devAddr == nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to determine device address from TXPK\")\n\t\t}\n\n\t} else {\n\t\t\/\/ We check them all to be sure, but all RXPK should refer to the same End-Device\n\t\tfor _, rxpk := range p.RXPK {\n\t\t\taddr := rxpk.DevAddr()\n\t\t\tif addr == nil || (devAddr != nil && *devAddr != *addr) {\n\t\t\t\treturn nil, fmt.Errorf(\"Payload is composed of messages from several end-devices\")\n\t\t\t}\n\t\t\tdevAddr = addr\n\t\t}\n\t}\n\treturn devAddr, nil\n}\n\n\/\/ Available packet commands\nconst (\n\tPUSH_DATA byte = iota \/\/ Sent by the gateway for an uplink message with data\n\tPUSH_ACK              \/\/ Sent by the gateway's recipient in response to a PUSH_DATA\n\tPULL_DATA             \/\/ Sent periodically by the gateway to keep a connection open\n\tPULL_RESP             \/\/ Sent by the gateway's recipient to transmit back data to the Gateway\n\tPULL_ACK              \/\/ Sent by the gateway's recipient in response to PULL_DATA\n)\n\n\/\/ Protocol version in use\nconst VERSION = 0x01\n<commit_msg>[router] Remove NOTE. Conditions were actually different.<commit_after>\/\/ Copyright © 2015 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n\/\/ Package semtech provides useful methods and types to handle communications with a gateway.\n\/\/\n\/\/ This package relies on the SemTech Protocol 1.2 accessible on github: https:\/\/github.com\/TheThingsNetwork\/packet_forwarder\/blob\/master\/PROTOCOL.TXT\npackage semtech\n\nimport (\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"time\"\n)\n\ntype DeviceAddress [4]byte\n\n\/\/ RXPK represents an uplink json message format sent by the gateway\ntype RXPK struct {\n\tChan    *uint          `json:\"chan,omitempty\"` \/\/ Concentrator \"IF\" channel used for RX (unsigned integer)\n\tCodr    *string        `json:\"codr,omitempty\"` \/\/ LoRa ECC coding rate identifier\n\tData    *string        `json:\"data,omitempty\"` \/\/ Base64 encoded RF packet payload, padded\n\tDatr    *string        `json:\"-\"`              \/\/ FSK datarate (unsigned in bit per second) || LoRa datarate identifier\n\tFreq    *float64       `json:\"freq,omitempty\"` \/\/ RX Central frequency in MHx (unsigned float, Hz precision)\n\tLsnr    *float64       `json:\"lsnr,omitempty\"` \/\/ LoRa SNR ratio in dB (signed float, 0.1 dB precision)\n\tModu    *string        `json:\"modu,omitempty\"` \/\/ Modulation identifier \"LORA\" or \"FSK\"\n\tRfch    *uint          `json:\"rfch,omitempty\"` \/\/ Concentrator \"RF chain\" used for RX (unsigned integer)\n\tRssi    *int           `json:\"rssi,omitempty\"` \/\/ RSSI in dBm (signed integer, 1 dB precision)\n\tSize    *uint          `json:\"size,omitempty\"` \/\/ RF packet payload size in bytes (unsigned integer)\n\tStat    *int           `json:\"stat,omitempty\"` \/\/ CRC status: 1 - OK, -1 = fail, 0 = no CRC\n\tTime    *time.Time     `json:\"-\"`              \/\/ UTC time of pkt RX, us precision, ISO 8601 'compact' format\n\tTmst    *uint          `json:\"tmst,omitempty\"` \/\/ Internal timestamp of \"RX finished\" event (32b unsigned)\n\tdevAddr *DeviceAddress \/\/ End-Device address, according to the Data. Memoized here.\n}\n\n\/\/ DevAddr returns the end-device address described in the payload\nfunc (rxpk *RXPK) DevAddr() *DeviceAddress {\n\tif rxpk.devAddr != nil {\n\t\treturn rxpk.devAddr\n\t}\n\n\tif rxpk.Data == nil {\n\t\treturn nil\n\t}\n\n\tbuf, err := base64.StdEncoding.DecodeString(*rxpk.Data)\n\tif err != nil || len(buf) < 5 {\n\t\treturn nil\n\t}\n\n\trxpk.devAddr = new(DeviceAddress)\n\tcopy((*rxpk.devAddr)[:], buf[1:5]) \/\/ Device Address corresponds to the first 4 bytes of the Frame Header, after one byte of MAC_HEADER\n\treturn rxpk.devAddr\n}\n\n\/\/ TXPK represents a downlink j,omitemptyson message format received by the gateway.\n\/\/ Most field are optional.\ntype TXPK struct {\n\tCodr    *string        `json:\"codr,omitempty\"`  \/\/ LoRa ECC coding rate identifier\n\tData    *string        `json:\"data,omirtmepty\"` \/\/ Base64 encoded RF packet payload, padding optional\n\tDatr    *string        `json:\"-\"`               \/\/ LoRa datarate identifier (eg. SF12BW500) || FSK Datarate (unsigned, in bits per second)\n\tFdev    *uint          `json:\"fdev,omitempty\"`  \/\/ FSK frequency deviation (unsigned integer, in Hz)\n\tFreq    *float64       `json:\"freq,omitempty\"`  \/\/ TX central frequency in MHz (unsigned float, Hz precision)\n\tImme    *bool          `json:\"imme,omitempty\"`  \/\/ Send packet immediately (will ignore tmst & time)\n\tIpol    *bool          `json:\"ipol,omitempty\"`  \/\/ Lora modulation polarization inversion\n\tModu    *string        `json:\"modu,omitempty\"`  \/\/ Modulation identifier \"LORA\" or \"FSK\"\n\tNcrc    *bool          `json:\"ncrc,omitempty\"`  \/\/ If true, disable the CRC of the physical layer (optional)\n\tPowe    *uint          `json:\"powe,omitempty\"`  \/\/ TX output power in dBm (unsigned integer, dBm precision)\n\tPrea    *uint          `json:\"prea,omitempty\"`  \/\/ RF preamble size (unsigned integer)\n\tRfch    *uint          `json:\"rfch,omitempty\"`  \/\/ Concentrator \"RF chain\" used for TX (unsigned integer)\n\tSize    *uint          `json:\"size,omitempty\"`  \/\/ RF packet payload size in bytes (unsigned integer)\n\tTime    *time.Time     `json:\"-\"`               \/\/ Send packet at a certain time (GPS synchronization required)\n\tTmst    *uint          `json:\"tmst,omitempty\"`  \/\/ Send packet on a certain timestamp value (will ignore time)\n\tdevAddr *DeviceAddress \/\/ End-Device address, according to the Data. Memoized here.\n}\n\n\/\/ DevAddr returns the end-device address described in the payload\nfunc (txpk *TXPK) DevAddr() *DeviceAddress {\n\tif txpk.devAddr != nil {\n\t\treturn txpk.devAddr\n\t}\n\n\tif txpk.Data == nil {\n\t\treturn nil\n\t}\n\n\tbuf, err := base64.StdEncoding.DecodeString(*txpk.Data)\n\tif err != nil || len(buf) < 5 {\n\t\treturn nil\n\t}\n\n\ttxpk.devAddr = new(DeviceAddress)\n\tcopy((*txpk.devAddr)[:], buf[1:5]) \/\/ Device Address corresponds to the first 4 bytes of the Frame Header, after one byte of MAC_HEADER\n\treturn txpk.devAddr\n}\n\n\/\/ Stat represents a status json message format sent by the gateway\ntype Stat struct {\n\tAckr *float64   `json:\"ackr,omitempty\"` \/\/ Percentage of upstream datagrams that were acknowledged\n\tAlti *int       `json:\"alti,omitempty\"` \/\/ GPS altitude of the gateway in meter RX (integer)\n\tDwnb *uint      `json:\"dwnb,omitempty\"` \/\/ Number of downlink datagrams received (unsigned integer)\n\tLati *float64   `json:\"lati,omitempty\"` \/\/ GPS latitude of the gateway in degree (float, N is +)\n\tLong *float64   `json:\"long,omitempty\"` \/\/ GPS latitude of the gateway in dgree (float, E is +)\n\tRxfw *uint      `json:\"rxfw,omitempty\"` \/\/ Number of radio packets forwarded (unsigned integer)\n\tRxnb *uint      `json:\"rxnb,omitempty\"` \/\/ Number of radio packets received (unsigned integer)\n\tRxok *uint      `json:\"rxok,omitempty\"` \/\/ Number of radio packets received with a valid PHY CRC\n\tTime *time.Time `json:\"-\"`              \/\/ UTC 'system' time of the gateway, ISO 8601 'expanded' format\n\tTxnb *uint      `json:\"txnb,omitempty\"` \/\/ Number of packets emitted (unsigned integer)\n}\n\n\/\/ Packet as seen by the gateway.\ntype Packet struct {\n\tVersion    byte     \/\/ Protocol version, should always be 1 here\n\tToken      []byte   \/\/ Random number generated by the gateway on some request. 2-bytes long.\n\tIdentifier byte     \/\/ Packet's command identifier\n\tGatewayId  []byte   \/\/ Source gateway's identifier (Only PULL_DATA and PUSH_DATA)\n\tPayload    *Payload \/\/ JSON payload transmitted if any, nil otherwise\n}\n\n\/\/ Payload refers to the JSON payload sent by a gateway or a server.\ntype Payload struct {\n\tRaw  []byte `json:\"-\"`              \/\/ The raw unparsed response\n\tRXPK []RXPK `json:\"rxpk,omitempty\"` \/\/ A list of RXPK messages transmitted if any\n\tStat *Stat  `json:\"stat,omitempty\"` \/\/ A Stat message transmitted if any\n\tTXPK *TXPK  `json:\"txpk,omitempty\"` \/\/ A TXPK message transmitted if any\n}\n\n\/\/ UniformDevAddr tries to extract a device address from the different part of a payload. If the\n\/\/ payload is composed of messages coming from several end-device, the method will fail.\nfunc (p Payload) UniformDevAddr() (*DeviceAddress, error) {\n\tvar devAddr *DeviceAddress\n\n\t\/\/ Determine the devAddress associated to that payload\n\tif p.RXPK == nil || len(p.RXPK) == 0 {\n\t\tif p.TXPK == nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to determine device address. No RXPK neither TXPK messages\")\n\t\t}\n\t\tif devAddr = p.TXPK.DevAddr(); devAddr == nil {\n\t\t\treturn nil, fmt.Errorf(\"Unable to determine device address from TXPK\")\n\t\t}\n\n\t} else {\n\t\t\/\/ We check them all to be sure, but all RXPK should refer to the same End-Device\n\t\tfor _, rxpk := range p.RXPK {\n\t\t\taddr := rxpk.DevAddr()\n\t\t\tif addr == nil || (devAddr != nil && *devAddr != *addr) {\n\t\t\t\treturn nil, fmt.Errorf(\"Payload is composed of messages from several end-devices\")\n\t\t\t}\n\t\t\tdevAddr = addr\n\t\t}\n\t}\n\treturn devAddr, nil\n}\n\n\/\/ Available packet commands\nconst (\n\tPUSH_DATA byte = iota \/\/ Sent by the gateway for an uplink message with data\n\tPUSH_ACK              \/\/ Sent by the gateway's recipient in response to a PUSH_DATA\n\tPULL_DATA             \/\/ Sent periodically by the gateway to keep a connection open\n\tPULL_RESP             \/\/ Sent by the gateway's recipient to transmit back data to the Gateway\n\tPULL_ACK              \/\/ Sent by the gateway's recipient in response to PULL_DATA\n)\n\n\/\/ Protocol version in use\nconst VERSION = 0x01\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>log\/syslog: document if network==\"\" for Dial, it will connect to local syslog server. Fixes issue 7828.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>please vet<commit_after><|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/dynamodb\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nfunc TestAccAWSDynamoDbTable(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSDynamoDbTableDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSDynamoDbConfigInitialState,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckInitialAWSDynamoDbTableExists(\"aws_dynamodb_table.basic-dynamodb-table\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSDynamoDbConfigAddSecondaryGSI,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDynamoDbTableWasUpdated(\"aws_dynamodb_table.basic-dynamodb-table\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckAWSDynamoDbTableDestroy(s *terraform.State) error {\n\tconn := testAccProvider.Meta().(*AWSClient).dynamodbconn\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_dynamodb_table\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Printf(\"[DEBUG] Checking if DynamoDB table %s exists\", rs.Primary.ID)\n\t\t\/\/ Check if queue exists by checking for its attributes\n\t\tparams := &dynamodb.DescribeTableInput{\n\t\t\tTableName: aws.String(rs.Primary.ID),\n\t\t}\n\t\t_, err := conn.DescribeTable(params)\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"DynamoDB table %s still exists. Failing!\", rs.Primary.ID)\n\t\t}\n\n\t\t\/\/ Verify the error is what we want\n\t\t_, ok := err.(awserr.Error)\n\t\tif !ok {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc testAccCheckInitialAWSDynamoDbTableExists(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tfmt.Printf(\"[DEBUG] Trying to create initial table state!\")\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No DynamoDB table name specified!\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).dynamodbconn\n\n\t\tparams := &dynamodb.DescribeTableInput{\n\t\t\tTableName: aws.String(rs.Primary.ID),\n\t\t}\n\n\t\tresp, err := conn.DescribeTable(params)\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"[ERROR] Problem describing table '%s': %s\", rs.Primary.ID, err)\n\t\t\treturn err\n\t\t}\n\n\t\ttable := resp.Table\n\n\t\tfmt.Printf(\"[DEBUG] Checking on table %s\", rs.Primary.ID)\n\n\t\tif *table.ProvisionedThroughput.WriteCapacityUnits != 20 {\n\t\t\treturn fmt.Errorf(\"Provisioned write capacity was %d, not 20!\", table.ProvisionedThroughput.WriteCapacityUnits)\n\t\t}\n\n\t\tif *table.ProvisionedThroughput.ReadCapacityUnits != 10 {\n\t\t\treturn fmt.Errorf(\"Provisioned read capacity was %d, not 10!\", table.ProvisionedThroughput.ReadCapacityUnits)\n\t\t}\n\n\t\tattrCount := len(table.AttributeDefinitions)\n\t\tgsiCount := len(table.GlobalSecondaryIndexes)\n\t\tlsiCount := len(table.LocalSecondaryIndexes)\n\n\t\tif attrCount != 4 {\n\t\t\treturn fmt.Errorf(\"There were %d attributes, not 4 like there should have been!\", attrCount)\n\t\t}\n\n\t\tif gsiCount != 1 {\n\t\t\treturn fmt.Errorf(\"There were %d GSIs, not 1 like there should have been!\", gsiCount)\n\t\t}\n\n\t\tif lsiCount != 1 {\n\t\t\treturn fmt.Errorf(\"There were %d LSIs, not 1 like there should have been!\", lsiCount)\n\t\t}\n\n\t\tattrmap := dynamoDbAttributesToMap(&table.AttributeDefinitions)\n\t\tif attrmap[\"TestTableHashKey\"] != \"S\" {\n\t\t\treturn fmt.Errorf(\"Test table hash key was of type %s instead of S!\", attrmap[\"TestTableHashKey\"])\n\t\t}\n\t\tif attrmap[\"TestTableRangeKey\"] != \"S\" {\n\t\t\treturn fmt.Errorf(\"Test table range key was of type %s instead of S!\", attrmap[\"TestTableRangeKey\"])\n\t\t}\n\t\tif attrmap[\"TestLSIRangeKey\"] != \"N\" {\n\t\t\treturn fmt.Errorf(\"Test table LSI range key was of type %s instead of N!\", attrmap[\"TestLSIRangeKey\"])\n\t\t}\n\t\tif attrmap[\"TestGSIRangeKey\"] != \"S\" {\n\t\t\treturn fmt.Errorf(\"Test table GSI range key was of type %s instead of S!\", attrmap[\"TestGSIRangeKey\"])\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckDynamoDbTableWasUpdated(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No DynamoDB table name specified!\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).dynamodbconn\n\n\t\tparams := &dynamodb.DescribeTableInput{\n\t\t\tTableName: aws.String(rs.Primary.ID),\n\t\t}\n\t\tresp, err := conn.DescribeTable(params)\n\t\ttable := resp.Table\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tattrCount := len(table.AttributeDefinitions)\n\t\tgsiCount := len(table.GlobalSecondaryIndexes)\n\t\tlsiCount := len(table.LocalSecondaryIndexes)\n\n\t\tif attrCount != 4 {\n\t\t\treturn fmt.Errorf(\"There were %d attributes, not 4 like there should have been!\", attrCount)\n\t\t}\n\n\t\tif gsiCount != 1 {\n\t\t\treturn fmt.Errorf(\"There were %d GSIs, not 1 like there should have been!\", gsiCount)\n\t\t}\n\n\t\tif lsiCount != 1 {\n\t\t\treturn fmt.Errorf(\"There were %d LSIs, not 1 like there should have been!\", lsiCount)\n\t\t}\n\n\t\tif dynamoDbGetGSIIndex(&table.GlobalSecondaryIndexes, \"ReplacementTestTableGSI\") == -1 {\n\t\t\treturn fmt.Errorf(\"Could not find GSI named 'ReplacementTestTableGSI' in the table!\")\n\t\t}\n\n\t\tif dynamoDbGetGSIIndex(&table.GlobalSecondaryIndexes, \"InitialTestTableGSI\") != -1 {\n\t\t\treturn fmt.Errorf(\"Should have removed 'InitialTestTableGSI' but it still exists!\")\n\t\t}\n\n\t\tattrmap := dynamoDbAttributesToMap(&table.AttributeDefinitions)\n\t\tif attrmap[\"TestTableHashKey\"] != \"S\" {\n\t\t\treturn fmt.Errorf(\"Test table hash key was of type %s instead of S!\", attrmap[\"TestTableHashKey\"])\n\t\t}\n\t\tif attrmap[\"TestTableRangeKey\"] != \"S\" {\n\t\t\treturn fmt.Errorf(\"Test table range key was of type %s instead of S!\", attrmap[\"TestTableRangeKey\"])\n\t\t}\n\t\tif attrmap[\"TestLSIRangeKey\"] != \"N\" {\n\t\t\treturn fmt.Errorf(\"Test table LSI range key was of type %s instead of N!\", attrmap[\"TestLSIRangeKey\"])\n\t\t}\n\t\tif attrmap[\"ReplacementGSIRangeKey\"] != \"N\" {\n\t\t\treturn fmt.Errorf(\"Test table replacement GSI range key was of type %s instead of N!\", attrmap[\"ReplacementGSIRangeKey\"])\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc dynamoDbGetGSIIndex(gsiList *[]*dynamodb.GlobalSecondaryIndexDescription, target string) int {\n\tfor idx, gsiObject := range *gsiList {\n\t\tif *gsiObject.IndexName == target {\n\t\t\treturn idx\n\t\t}\n\t}\n\n\treturn -1\n}\n\nfunc dynamoDbAttributesToMap(attributes *[]*dynamodb.AttributeDefinition) map[string]string {\n\tattrmap := make(map[string]string)\n\n\tfor _, attrdef := range *attributes {\n\t\tattrmap[*(attrdef.AttributeName)] = *(attrdef.AttributeType)\n\t}\n\n\treturn attrmap\n}\n\nconst testAccAWSDynamoDbConfigInitialState = `\nresource \"aws_dynamodb_table\" \"basic-dynamodb-table\" {\n    name = \"TerraformTestTable\"\n\t\tread_capacity = 10\n\t\twrite_capacity = 20\n\t\thash_key = \"TestTableHashKey\"\n\t\trange_key = \"TestTableRangeKey\"\n\t\tattribute {\n\t\t\tname = \"TestTableHashKey\"\n\t\t\ttype = \"S\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"TestTableRangeKey\"\n\t\t\ttype = \"S\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"TestLSIRangeKey\"\n\t\t\ttype = \"N\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"TestGSIRangeKey\"\n\t\t\ttype = \"S\"\n\t\t}\n\t\tlocal_secondary_index {\n\t\t\tname = \"TestTableLSI\"\n\t\t\trange_key = \"TestLSIRangeKey\"\n\t\t\tprojection_type = \"ALL\"\n\t\t}\n\t\tglobal_secondary_index {\n\t\t\tname = \"InitialTestTableGSI\"\n\t\t\thash_key = \"TestTableHashKey\"\n\t\t\trange_key = \"TestGSIRangeKey\"\n\t\t\twrite_capacity = 10\n\t\t\tread_capacity = 10\n\t\t\tprojection_type = \"ALL\"\n\t\t}\n}\n`\n\nconst testAccAWSDynamoDbConfigAddSecondaryGSI = `\nresource \"aws_dynamodb_table\" \"basic-dynamodb-table\" {\n    name = \"TerraformTestTable\"\n\t\tread_capacity = 20\n\t\twrite_capacity = 20\n\t\thash_key = \"TestTableHashKey\"\n\t\trange_key = \"TestTableRangeKey\"\n\t\tattribute {\n\t\t\tname = \"TestTableHashKey\"\n\t\t\ttype = \"S\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"TestTableRangeKey\"\n\t\t\ttype = \"S\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"TestLSIRangeKey\"\n\t\t\ttype = \"N\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"ReplacementGSIRangeKey\"\n\t\t\ttype = \"N\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"TestNonKeyAttribute\"\n\t\t\ttype = \"S\"\n\t\t}\n\t\tlocal_secondary_index {\n\t\t\tname = \"TestTableLSI\"\n\t\t\trange_key = \"TestLSIRangeKey\"\n\t\t\tprojection_type = \"ALL\"\n\t\t}\n\t\tglobal_secondary_index {\n\t\t\tname = \"ReplacementTestTableGSI\"\n\t\t\thash_key = \"TestTableHashKey\"\n\t\t\trange_key = \"ReplacementGSIRangeKey\"\n\t\t\twrite_capacity = 5\n\t\t\tread_capacity = 5\n\t\t\tprojection_type = \"INCLUDE\"\n\t\t\tnon_key_attributes = [\"TestNonKeyAttribute\"]\n\t\t}\n}\n`\n<commit_msg>include keys only projection type<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/dynamodb\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nfunc TestAccAWSDynamoDbTable(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSDynamoDbTableDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSDynamoDbConfigInitialState,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckInitialAWSDynamoDbTableExists(\"aws_dynamodb_table.basic-dynamodb-table\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAWSDynamoDbConfigAddSecondaryGSI,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDynamoDbTableWasUpdated(\"aws_dynamodb_table.basic-dynamodb-table\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckAWSDynamoDbTableDestroy(s *terraform.State) error {\n\tconn := testAccProvider.Meta().(*AWSClient).dynamodbconn\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_dynamodb_table\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Printf(\"[DEBUG] Checking if DynamoDB table %s exists\", rs.Primary.ID)\n\t\t\/\/ Check if queue exists by checking for its attributes\n\t\tparams := &dynamodb.DescribeTableInput{\n\t\t\tTableName: aws.String(rs.Primary.ID),\n\t\t}\n\t\t_, err := conn.DescribeTable(params)\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"DynamoDB table %s still exists. Failing!\", rs.Primary.ID)\n\t\t}\n\n\t\t\/\/ Verify the error is what we want\n\t\t_, ok := err.(awserr.Error)\n\t\tif !ok {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc testAccCheckInitialAWSDynamoDbTableExists(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tfmt.Printf(\"[DEBUG] Trying to create initial table state!\")\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No DynamoDB table name specified!\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).dynamodbconn\n\n\t\tparams := &dynamodb.DescribeTableInput{\n\t\t\tTableName: aws.String(rs.Primary.ID),\n\t\t}\n\n\t\tresp, err := conn.DescribeTable(params)\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"[ERROR] Problem describing table '%s': %s\", rs.Primary.ID, err)\n\t\t\treturn err\n\t\t}\n\n\t\ttable := resp.Table\n\n\t\tfmt.Printf(\"[DEBUG] Checking on table %s\", rs.Primary.ID)\n\n\t\tif *table.ProvisionedThroughput.WriteCapacityUnits != 20 {\n\t\t\treturn fmt.Errorf(\"Provisioned write capacity was %d, not 20!\", table.ProvisionedThroughput.WriteCapacityUnits)\n\t\t}\n\n\t\tif *table.ProvisionedThroughput.ReadCapacityUnits != 10 {\n\t\t\treturn fmt.Errorf(\"Provisioned read capacity was %d, not 10!\", table.ProvisionedThroughput.ReadCapacityUnits)\n\t\t}\n\n\t\tattrCount := len(table.AttributeDefinitions)\n\t\tgsiCount := len(table.GlobalSecondaryIndexes)\n\t\tlsiCount := len(table.LocalSecondaryIndexes)\n\n\t\tif attrCount != 4 {\n\t\t\treturn fmt.Errorf(\"There were %d attributes, not 4 like there should have been!\", attrCount)\n\t\t}\n\n\t\tif gsiCount != 1 {\n\t\t\treturn fmt.Errorf(\"There were %d GSIs, not 1 like there should have been!\", gsiCount)\n\t\t}\n\n\t\tif lsiCount != 1 {\n\t\t\treturn fmt.Errorf(\"There were %d LSIs, not 1 like there should have been!\", lsiCount)\n\t\t}\n\n\t\tattrmap := dynamoDbAttributesToMap(&table.AttributeDefinitions)\n\t\tif attrmap[\"TestTableHashKey\"] != \"S\" {\n\t\t\treturn fmt.Errorf(\"Test table hash key was of type %s instead of S!\", attrmap[\"TestTableHashKey\"])\n\t\t}\n\t\tif attrmap[\"TestTableRangeKey\"] != \"S\" {\n\t\t\treturn fmt.Errorf(\"Test table range key was of type %s instead of S!\", attrmap[\"TestTableRangeKey\"])\n\t\t}\n\t\tif attrmap[\"TestLSIRangeKey\"] != \"N\" {\n\t\t\treturn fmt.Errorf(\"Test table LSI range key was of type %s instead of N!\", attrmap[\"TestLSIRangeKey\"])\n\t\t}\n\t\tif attrmap[\"TestGSIRangeKey\"] != \"S\" {\n\t\t\treturn fmt.Errorf(\"Test table GSI range key was of type %s instead of S!\", attrmap[\"TestGSIRangeKey\"])\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckDynamoDbTableWasUpdated(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No DynamoDB table name specified!\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).dynamodbconn\n\n\t\tparams := &dynamodb.DescribeTableInput{\n\t\t\tTableName: aws.String(rs.Primary.ID),\n\t\t}\n\t\tresp, err := conn.DescribeTable(params)\n\t\ttable := resp.Table\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tattrCount := len(table.AttributeDefinitions)\n\t\tgsiCount := len(table.GlobalSecondaryIndexes)\n\t\tlsiCount := len(table.LocalSecondaryIndexes)\n\n\t\tif attrCount != 4 {\n\t\t\treturn fmt.Errorf(\"There were %d attributes, not 4 like there should have been!\", attrCount)\n\t\t}\n\n\t\tif gsiCount != 1 {\n\t\t\treturn fmt.Errorf(\"There were %d GSIs, not 1 like there should have been!\", gsiCount)\n\t\t}\n\n\t\tif lsiCount != 1 {\n\t\t\treturn fmt.Errorf(\"There were %d LSIs, not 1 like there should have been!\", lsiCount)\n\t\t}\n\n\t\tif dynamoDbGetGSIIndex(&table.GlobalSecondaryIndexes, \"ReplacementTestTableGSI\") == -1 {\n\t\t\treturn fmt.Errorf(\"Could not find GSI named 'ReplacementTestTableGSI' in the table!\")\n\t\t}\n\n\t\tif dynamoDbGetGSIIndex(&table.GlobalSecondaryIndexes, \"InitialTestTableGSI\") != -1 {\n\t\t\treturn fmt.Errorf(\"Should have removed 'InitialTestTableGSI' but it still exists!\")\n\t\t}\n\n\t\tattrmap := dynamoDbAttributesToMap(&table.AttributeDefinitions)\n\t\tif attrmap[\"TestTableHashKey\"] != \"S\" {\n\t\t\treturn fmt.Errorf(\"Test table hash key was of type %s instead of S!\", attrmap[\"TestTableHashKey\"])\n\t\t}\n\t\tif attrmap[\"TestTableRangeKey\"] != \"S\" {\n\t\t\treturn fmt.Errorf(\"Test table range key was of type %s instead of S!\", attrmap[\"TestTableRangeKey\"])\n\t\t}\n\t\tif attrmap[\"TestLSIRangeKey\"] != \"N\" {\n\t\t\treturn fmt.Errorf(\"Test table LSI range key was of type %s instead of N!\", attrmap[\"TestLSIRangeKey\"])\n\t\t}\n\t\tif attrmap[\"ReplacementGSIRangeKey\"] != \"N\" {\n\t\t\treturn fmt.Errorf(\"Test table replacement GSI range key was of type %s instead of N!\", attrmap[\"ReplacementGSIRangeKey\"])\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc dynamoDbGetGSIIndex(gsiList *[]*dynamodb.GlobalSecondaryIndexDescription, target string) int {\n\tfor idx, gsiObject := range *gsiList {\n\t\tif *gsiObject.IndexName == target {\n\t\t\treturn idx\n\t\t}\n\t}\n\n\treturn -1\n}\n\nfunc dynamoDbAttributesToMap(attributes *[]*dynamodb.AttributeDefinition) map[string]string {\n\tattrmap := make(map[string]string)\n\n\tfor _, attrdef := range *attributes {\n\t\tattrmap[*(attrdef.AttributeName)] = *(attrdef.AttributeType)\n\t}\n\n\treturn attrmap\n}\n\nconst testAccAWSDynamoDbConfigInitialState = `\nresource \"aws_dynamodb_table\" \"basic-dynamodb-table\" {\n    name = \"TerraformTestTable\"\n\t\tread_capacity = 10\n\t\twrite_capacity = 20\n\t\thash_key = \"TestTableHashKey\"\n\t\trange_key = \"TestTableRangeKey\"\n\t\tattribute {\n\t\t\tname = \"TestTableHashKey\"\n\t\t\ttype = \"S\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"TestTableRangeKey\"\n\t\t\ttype = \"S\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"TestLSIRangeKey\"\n\t\t\ttype = \"N\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"TestGSIRangeKey\"\n\t\t\ttype = \"S\"\n\t\t}\n\t\tlocal_secondary_index {\n\t\t\tname = \"TestTableLSI\"\n\t\t\trange_key = \"TestLSIRangeKey\"\n\t\t\tprojection_type = \"ALL\"\n\t\t}\n\t\tglobal_secondary_index {\n\t\t\tname = \"InitialTestTableGSI\"\n\t\t\thash_key = \"TestTableHashKey\"\n\t\t\trange_key = \"TestGSIRangeKey\"\n\t\t\twrite_capacity = 10\n\t\t\tread_capacity = 10\n\t\t\tprojection_type = \"KEYS_ONLY\"\n\t\t}\n}\n`\n\nconst testAccAWSDynamoDbConfigAddSecondaryGSI = `\nresource \"aws_dynamodb_table\" \"basic-dynamodb-table\" {\n    name = \"TerraformTestTable\"\n\t\tread_capacity = 20\n\t\twrite_capacity = 20\n\t\thash_key = \"TestTableHashKey\"\n\t\trange_key = \"TestTableRangeKey\"\n\t\tattribute {\n\t\t\tname = \"TestTableHashKey\"\n\t\t\ttype = \"S\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"TestTableRangeKey\"\n\t\t\ttype = \"S\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"TestLSIRangeKey\"\n\t\t\ttype = \"N\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"ReplacementGSIRangeKey\"\n\t\t\ttype = \"N\"\n\t\t}\n\t\tattribute {\n\t\t\tname = \"TestNonKeyAttribute\"\n\t\t\ttype = \"S\"\n\t\t}\n\t\tlocal_secondary_index {\n\t\t\tname = \"TestTableLSI\"\n\t\t\trange_key = \"TestLSIRangeKey\"\n\t\t\tprojection_type = \"ALL\"\n\t\t}\n\t\tglobal_secondary_index {\n\t\t\tname = \"ReplacementTestTableGSI\"\n\t\t\thash_key = \"TestTableHashKey\"\n\t\t\trange_key = \"ReplacementGSIRangeKey\"\n\t\t\twrite_capacity = 5\n\t\t\tread_capacity = 5\n\t\t\tprojection_type = \"INCLUDE\"\n\t\t\tnon_key_attributes = [\"TestNonKeyAttribute\"]\n\t\t}\n}\n`\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/awslabs\/aws-sdk-go\/aws\"\n\t\"github.com\/awslabs\/aws-sdk-go\/service\/elasticache\"\n\t\"github.com\/awslabs\/aws-sdk-go\/service\/iam\"\n\t\"github.com\/hashicorp\/terraform\/helper\/hashcode\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n)\n\nfunc resourceAwsElasticacheCluster() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsElasticacheClusterCreate,\n\t\tRead:   resourceAwsElasticacheClusterRead,\n\t\tUpdate: resourceAwsElasticacheClusterUpdate,\n\t\tDelete: resourceAwsElasticacheClusterDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"cluster_id\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"engine\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"node_type\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"num_cache_nodes\": &schema.Schema{\n\t\t\t\tType:     schema.TypeInt,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"parameter_group_name\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"port\": &schema.Schema{\n\t\t\t\tType:     schema.TypeInt,\n\t\t\t\tDefault:  11211,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"engine_version\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"subnet_group_name\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"security_group_names\": &schema.Schema{\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t\tSet: func(v interface{}) int {\n\t\t\t\t\treturn hashcode.String(v.(string))\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"security_group_ids\": &schema.Schema{\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t\tSet: func(v interface{}) int {\n\t\t\t\t\treturn hashcode.String(v.(string))\n\t\t\t\t},\n\t\t\t},\n\t\t\t\/\/ Exported Attributes\n\t\t\t\"cache_nodes\": &schema.Schema{\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tComputed: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"id\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"address\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"port\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeInt,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsElasticacheClusterCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).elasticacheconn\n\n\tclusterId := d.Get(\"cluster_id\").(string)\n\tnodeType := d.Get(\"node_type\").(string)           \/\/ e.g) cache.m1.small\n\tnumNodes := int64(d.Get(\"num_cache_nodes\").(int)) \/\/ 2\n\tengine := d.Get(\"engine\").(string)                \/\/ memcached\n\tengineVersion := d.Get(\"engine_version\").(string) \/\/ 1.4.14\n\tport := int64(d.Get(\"port\").(int))                \/\/ 11211\n\tsubnetGroupName := d.Get(\"subnet_group_name\").(string)\n\tsecurityNameSet := d.Get(\"security_group_names\").(*schema.Set)\n\tsecurityIdSet := d.Get(\"security_group_ids\").(*schema.Set)\n\n\tsecurityNames := expandStringList(securityNameSet.List())\n\tsecurityIds := expandStringList(securityIdSet.List())\n\n\ttags := tagsFromMapEC(d.Get(\"tags\").(map[string]interface{}))\n\treq := &elasticache.CreateCacheClusterInput{\n\t\tCacheClusterID:          aws.String(clusterId),\n\t\tCacheNodeType:           aws.String(nodeType),\n\t\tNumCacheNodes:           aws.Long(numNodes),\n\t\tEngine:                  aws.String(engine),\n\t\tEngineVersion:           aws.String(engineVersion),\n\t\tPort:                    aws.Long(port),\n\t\tCacheSubnetGroupName:    aws.String(subnetGroupName),\n\t\tCacheSecurityGroupNames: securityNames,\n\t\tSecurityGroupIDs:        securityIds,\n\t\tTags:                    tags,\n\t}\n\n\t\/\/ parameter groups are optional and can be defaulted by AWS\n\tif v, ok := d.GetOk(\"parameter_group_name\"); ok {\n\t\treq.CacheParameterGroupName = aws.String(v.(string))\n\t}\n\n\t_, err := conn.CreateCacheCluster(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating Elasticache: %s\", err)\n\t}\n\n\tpending := []string{\"creating\"}\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:    pending,\n\t\tTarget:     \"available\",\n\t\tRefresh:    CacheClusterStateRefreshFunc(conn, d.Id(), \"available\", pending),\n\t\tTimeout:    10 * time.Minute,\n\t\tDelay:      10 * time.Second,\n\t\tMinTimeout: 3 * time.Second,\n\t}\n\n\tlog.Printf(\"[DEBUG] Waiting for state to become available: %v\", d.Id())\n\t_, sterr := stateConf.WaitForState()\n\tif sterr != nil {\n\t\treturn fmt.Errorf(\"Error waiting for elasticache (%s) to be created: %s\", d.Id(), sterr)\n\t}\n\n\td.SetId(clusterId)\n\n\treturn resourceAwsElasticacheClusterRead(d, meta)\n}\n\nfunc resourceAwsElasticacheClusterRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).elasticacheconn\n\treq := &elasticache.DescribeCacheClustersInput{\n\t\tCacheClusterID:    aws.String(d.Id()),\n\t\tShowCacheNodeInfo: aws.Boolean(true),\n\t}\n\n\tres, err := conn.DescribeCacheClusters(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(res.CacheClusters) == 1 {\n\t\tc := res.CacheClusters[0]\n\t\td.Set(\"cluster_id\", c.CacheClusterID)\n\t\td.Set(\"node_type\", c.CacheNodeType)\n\t\td.Set(\"num_cache_nodes\", c.NumCacheNodes)\n\t\td.Set(\"engine\", c.Engine)\n\t\td.Set(\"engine_version\", c.EngineVersion)\n\t\tif c.ConfigurationEndpoint != nil {\n\t\t\td.Set(\"port\", c.ConfigurationEndpoint.Port)\n\t\t}\n\t\td.Set(\"subnet_group_name\", c.CacheSubnetGroupName)\n\t\td.Set(\"security_group_names\", c.CacheSecurityGroups)\n\t\td.Set(\"security_group_ids\", c.SecurityGroups)\n\t\td.Set(\"parameter_group_name\", c.CacheParameterGroup)\n\n\t\tif err := setCacheNodeData(d, c); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ list tags for resource\n\t\t\/\/ set tags\n\t\tarn, err := buildECARN(d, meta)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[DEBUG] Error building ARN for ElastiCache Cluster, not setting Tags for cluster %s\", *c.CacheClusterID)\n\t\t} else {\n\t\t\tresp, err := conn.ListTagsForResource(&elasticache.ListTagsForResourceInput{\n\t\t\t\tResourceName: aws.String(arn),\n\t\t\t})\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[DEBUG] Error retreiving tags for ARN: %s\", arn)\n\t\t\t}\n\n\t\t\tvar et []*elasticache.Tag\n\t\t\tif len(resp.TagList) > 0 {\n\t\t\t\tet = resp.TagList\n\t\t\t}\n\t\t\td.Set(\"tags\", tagsToMapEC(et))\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsElasticacheClusterUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).elasticacheconn\n\tarn, err := buildECARN(d, meta)\n\tif err != nil {\n\t\tlog.Printf(\"[DEBUG] Error building ARN for ElastiCache Cluster, not updating Tags for cluster %s\", *c.CacheClusterID)\n\t} else {\n\t\tif err := setTagsEC(conn, d, arn); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn resourceAwsElasticacheClusterRead(d, meta)\n}\n\nfunc setCacheNodeData(d *schema.ResourceData, c *elasticache.CacheCluster) error {\n\tsortedCacheNodes := make([]*elasticache.CacheNode, len(c.CacheNodes))\n\tcopy(sortedCacheNodes, c.CacheNodes)\n\tsort.Sort(byCacheNodeId(sortedCacheNodes))\n\n\tcacheNodeData := make([]map[string]interface{}, 0, len(sortedCacheNodes))\n\n\tfor _, node := range sortedCacheNodes {\n\t\tif node.CacheNodeID == nil || node.Endpoint == nil || node.Endpoint.Address == nil || node.Endpoint.Port == nil {\n\t\t\treturn fmt.Errorf(\"Unexpected nil pointer in: %#v\", node)\n\t\t}\n\t\tcacheNodeData = append(cacheNodeData, map[string]interface{}{\n\t\t\t\"id\":      *node.CacheNodeID,\n\t\t\t\"address\": *node.Endpoint.Address,\n\t\t\t\"port\":    int(*node.Endpoint.Port),\n\t\t})\n\t}\n\n\treturn d.Set(\"cache_nodes\", cacheNodeData)\n}\n\ntype byCacheNodeId []*elasticache.CacheNode\n\nfunc (b byCacheNodeId) Len() int      { return len(b) }\nfunc (b byCacheNodeId) Swap(i, j int) { b[i], b[j] = b[j], b[i] }\nfunc (b byCacheNodeId) Less(i, j int) bool {\n\treturn b[i].CacheNodeID != nil && b[j].CacheNodeID != nil &&\n\t\t*b[i].CacheNodeID < *b[j].CacheNodeID\n}\n\nfunc resourceAwsElasticacheClusterDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).elasticacheconn\n\n\treq := &elasticache.DeleteCacheClusterInput{\n\t\tCacheClusterID: aws.String(d.Id()),\n\t}\n\t_, err := conn.DeleteCacheCluster(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[DEBUG] Waiting for deletion: %v\", d.Id())\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:    []string{\"creating\", \"available\", \"deleting\", \"incompatible-parameters\", \"incompatible-network\", \"restore-failed\"},\n\t\tTarget:     \"\",\n\t\tRefresh:    CacheClusterStateRefreshFunc(conn, d.Id(), \"\", []string{}),\n\t\tTimeout:    10 * time.Minute,\n\t\tDelay:      10 * time.Second,\n\t\tMinTimeout: 3 * time.Second,\n\t}\n\n\t_, sterr := stateConf.WaitForState()\n\tif sterr != nil {\n\t\treturn fmt.Errorf(\"Error waiting for elasticache (%s) to delete: %s\", d.Id(), sterr)\n\t}\n\n\td.SetId(\"\")\n\n\treturn nil\n}\n\nfunc CacheClusterStateRefreshFunc(conn *elasticache.ElastiCache, clusterID, givenState string, pending []string) resource.StateRefreshFunc {\n\treturn func() (interface{}, string, error) {\n\t\tresp, err := conn.DescribeCacheClusters(&elasticache.DescribeCacheClustersInput{\n\t\t\tCacheClusterID: aws.String(clusterID),\n\t\t})\n\t\tif err != nil {\n\t\t\tapierr := err.(aws.APIError)\n\t\t\tlog.Printf(\"[DEBUG] message: %v, code: %v\", apierr.Message, apierr.Code)\n\t\t\tif apierr.Message == fmt.Sprintf(\"CacheCluster not found: %v\", clusterID) {\n\t\t\t\tlog.Printf(\"[DEBUG] Detect deletion\")\n\t\t\t\treturn nil, \"\", nil\n\t\t\t}\n\n\t\t\tlog.Printf(\"[ERROR] CacheClusterStateRefreshFunc: %s\", err)\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\tc := resp.CacheClusters[0]\n\t\tlog.Printf(\"[DEBUG] status: %v\", *c.CacheClusterStatus)\n\n\t\t\/\/ return the current state if it's in the pending array\n\t\tfor _, p := range pending {\n\t\t\ts := *c.CacheClusterStatus\n\t\t\tif p == s {\n\t\t\t\tlog.Printf(\"[DEBUG] Return with status: %v\", *c.CacheClusterStatus)\n\t\t\t\treturn c, p, nil\n\t\t\t}\n\t\t}\n\n\t\t\/\/ return given state if it's not in pending\n\t\tif givenState != \"\" {\n\t\t\treturn c, givenState, nil\n\t\t}\n\t\tlog.Printf(\"[DEBUG] current status: %v\", *c.CacheClusterStatus)\n\t\treturn c, *c.CacheClusterStatus, nil\n\t}\n}\n\nfunc buildECARN(d *schema.ResourceData, meta interface{}) (string, error) {\n\tiamconn := meta.(*AWSClient).iamconn\n\tregion := meta.(*AWSClient).region\n\t\/\/ An zero value GetUserInput{} defers to the currently logged in user\n\tresp, err := iamconn.GetUser(&iam.GetUserInput{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tuserARN := *resp.User.ARN\n\taccountID := strings.Split(userARN, \":\")[4]\n\tarn := fmt.Sprintf(\"arn:aws:elasticache:%s:%s:cluster:%s\", region, accountID, d.Id())\n\treturn arn, nil\n}\n<commit_msg>cleanup<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/awslabs\/aws-sdk-go\/aws\"\n\t\"github.com\/awslabs\/aws-sdk-go\/service\/elasticache\"\n\t\"github.com\/awslabs\/aws-sdk-go\/service\/iam\"\n\t\"github.com\/hashicorp\/terraform\/helper\/hashcode\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n)\n\nfunc resourceAwsElasticacheCluster() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsElasticacheClusterCreate,\n\t\tRead:   resourceAwsElasticacheClusterRead,\n\t\tUpdate: resourceAwsElasticacheClusterUpdate,\n\t\tDelete: resourceAwsElasticacheClusterDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"cluster_id\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"engine\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"node_type\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"num_cache_nodes\": &schema.Schema{\n\t\t\t\tType:     schema.TypeInt,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"parameter_group_name\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"port\": &schema.Schema{\n\t\t\t\tType:     schema.TypeInt,\n\t\t\t\tDefault:  11211,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"engine_version\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"subnet_group_name\": &schema.Schema{\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t},\n\t\t\t\"security_group_names\": &schema.Schema{\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t\tSet: func(v interface{}) int {\n\t\t\t\t\treturn hashcode.String(v.(string))\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"security_group_ids\": &schema.Schema{\n\t\t\t\tType:     schema.TypeSet,\n\t\t\t\tOptional: true,\n\t\t\t\tComputed: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem:     &schema.Schema{Type: schema.TypeString},\n\t\t\t\tSet: func(v interface{}) int {\n\t\t\t\t\treturn hashcode.String(v.(string))\n\t\t\t\t},\n\t\t\t},\n\t\t\t\/\/ Exported Attributes\n\t\t\t\"cache_nodes\": &schema.Schema{\n\t\t\t\tType:     schema.TypeList,\n\t\t\t\tComputed: true,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"id\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"address\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeString,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"port\": &schema.Schema{\n\t\t\t\t\t\t\tType:     schema.TypeInt,\n\t\t\t\t\t\t\tComputed: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsElasticacheClusterCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).elasticacheconn\n\n\tclusterId := d.Get(\"cluster_id\").(string)\n\tnodeType := d.Get(\"node_type\").(string)           \/\/ e.g) cache.m1.small\n\tnumNodes := int64(d.Get(\"num_cache_nodes\").(int)) \/\/ 2\n\tengine := d.Get(\"engine\").(string)                \/\/ memcached\n\tengineVersion := d.Get(\"engine_version\").(string) \/\/ 1.4.14\n\tport := int64(d.Get(\"port\").(int))                \/\/ 11211\n\tsubnetGroupName := d.Get(\"subnet_group_name\").(string)\n\tsecurityNameSet := d.Get(\"security_group_names\").(*schema.Set)\n\tsecurityIdSet := d.Get(\"security_group_ids\").(*schema.Set)\n\n\tsecurityNames := expandStringList(securityNameSet.List())\n\tsecurityIds := expandStringList(securityIdSet.List())\n\n\ttags := tagsFromMapEC(d.Get(\"tags\").(map[string]interface{}))\n\treq := &elasticache.CreateCacheClusterInput{\n\t\tCacheClusterID:          aws.String(clusterId),\n\t\tCacheNodeType:           aws.String(nodeType),\n\t\tNumCacheNodes:           aws.Long(numNodes),\n\t\tEngine:                  aws.String(engine),\n\t\tEngineVersion:           aws.String(engineVersion),\n\t\tPort:                    aws.Long(port),\n\t\tCacheSubnetGroupName:    aws.String(subnetGroupName),\n\t\tCacheSecurityGroupNames: securityNames,\n\t\tSecurityGroupIDs:        securityIds,\n\t\tTags:                    tags,\n\t}\n\n\t\/\/ parameter groups are optional and can be defaulted by AWS\n\tif v, ok := d.GetOk(\"parameter_group_name\"); ok {\n\t\treq.CacheParameterGroupName = aws.String(v.(string))\n\t}\n\n\t_, err := conn.CreateCacheCluster(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating Elasticache: %s\", err)\n\t}\n\n\tpending := []string{\"creating\"}\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:    pending,\n\t\tTarget:     \"available\",\n\t\tRefresh:    CacheClusterStateRefreshFunc(conn, d.Id(), \"available\", pending),\n\t\tTimeout:    10 * time.Minute,\n\t\tDelay:      10 * time.Second,\n\t\tMinTimeout: 3 * time.Second,\n\t}\n\n\tlog.Printf(\"[DEBUG] Waiting for state to become available: %v\", d.Id())\n\t_, sterr := stateConf.WaitForState()\n\tif sterr != nil {\n\t\treturn fmt.Errorf(\"Error waiting for elasticache (%s) to be created: %s\", d.Id(), sterr)\n\t}\n\n\td.SetId(clusterId)\n\n\treturn resourceAwsElasticacheClusterRead(d, meta)\n}\n\nfunc resourceAwsElasticacheClusterRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).elasticacheconn\n\treq := &elasticache.DescribeCacheClustersInput{\n\t\tCacheClusterID:    aws.String(d.Id()),\n\t\tShowCacheNodeInfo: aws.Boolean(true),\n\t}\n\n\tres, err := conn.DescribeCacheClusters(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(res.CacheClusters) == 1 {\n\t\tc := res.CacheClusters[0]\n\t\td.Set(\"cluster_id\", c.CacheClusterID)\n\t\td.Set(\"node_type\", c.CacheNodeType)\n\t\td.Set(\"num_cache_nodes\", c.NumCacheNodes)\n\t\td.Set(\"engine\", c.Engine)\n\t\td.Set(\"engine_version\", c.EngineVersion)\n\t\tif c.ConfigurationEndpoint != nil {\n\t\t\td.Set(\"port\", c.ConfigurationEndpoint.Port)\n\t\t}\n\t\td.Set(\"subnet_group_name\", c.CacheSubnetGroupName)\n\t\td.Set(\"security_group_names\", c.CacheSecurityGroups)\n\t\td.Set(\"security_group_ids\", c.SecurityGroups)\n\t\td.Set(\"parameter_group_name\", c.CacheParameterGroup)\n\n\t\tif err := setCacheNodeData(d, c); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ list tags for resource\n\t\t\/\/ set tags\n\t\tarn, err := buildECARN(d, meta)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"[DEBUG] Error building ARN for ElastiCache Cluster, not setting Tags for cluster %s\", *c.CacheClusterID)\n\t\t} else {\n\t\t\tresp, err := conn.ListTagsForResource(&elasticache.ListTagsForResourceInput{\n\t\t\t\tResourceName: aws.String(arn),\n\t\t\t})\n\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[DEBUG] Error retreiving tags for ARN: %s\", arn)\n\t\t\t}\n\n\t\t\tvar et []*elasticache.Tag\n\t\t\tif len(resp.TagList) > 0 {\n\t\t\t\tet = resp.TagList\n\t\t\t}\n\t\t\td.Set(\"tags\", tagsToMapEC(et))\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsElasticacheClusterUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).elasticacheconn\n\tarn, err := buildECARN(d, meta)\n\tif err != nil {\n\t\tlog.Printf(\"[DEBUG] Error building ARN for ElastiCache Cluster, not updating Tags for cluster %s\", d.Id())\n\t} else {\n\t\tif err := setTagsEC(conn, d, arn); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn resourceAwsElasticacheClusterRead(d, meta)\n}\n\nfunc setCacheNodeData(d *schema.ResourceData, c *elasticache.CacheCluster) error {\n\tsortedCacheNodes := make([]*elasticache.CacheNode, len(c.CacheNodes))\n\tcopy(sortedCacheNodes, c.CacheNodes)\n\tsort.Sort(byCacheNodeId(sortedCacheNodes))\n\n\tcacheNodeData := make([]map[string]interface{}, 0, len(sortedCacheNodes))\n\n\tfor _, node := range sortedCacheNodes {\n\t\tif node.CacheNodeID == nil || node.Endpoint == nil || node.Endpoint.Address == nil || node.Endpoint.Port == nil {\n\t\t\treturn fmt.Errorf(\"Unexpected nil pointer in: %#v\", node)\n\t\t}\n\t\tcacheNodeData = append(cacheNodeData, map[string]interface{}{\n\t\t\t\"id\":      *node.CacheNodeID,\n\t\t\t\"address\": *node.Endpoint.Address,\n\t\t\t\"port\":    int(*node.Endpoint.Port),\n\t\t})\n\t}\n\n\treturn d.Set(\"cache_nodes\", cacheNodeData)\n}\n\ntype byCacheNodeId []*elasticache.CacheNode\n\nfunc (b byCacheNodeId) Len() int      { return len(b) }\nfunc (b byCacheNodeId) Swap(i, j int) { b[i], b[j] = b[j], b[i] }\nfunc (b byCacheNodeId) Less(i, j int) bool {\n\treturn b[i].CacheNodeID != nil && b[j].CacheNodeID != nil &&\n\t\t*b[i].CacheNodeID < *b[j].CacheNodeID\n}\n\nfunc resourceAwsElasticacheClusterDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).elasticacheconn\n\n\treq := &elasticache.DeleteCacheClusterInput{\n\t\tCacheClusterID: aws.String(d.Id()),\n\t}\n\t_, err := conn.DeleteCacheCluster(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"[DEBUG] Waiting for deletion: %v\", d.Id())\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:    []string{\"creating\", \"available\", \"deleting\", \"incompatible-parameters\", \"incompatible-network\", \"restore-failed\"},\n\t\tTarget:     \"\",\n\t\tRefresh:    CacheClusterStateRefreshFunc(conn, d.Id(), \"\", []string{}),\n\t\tTimeout:    10 * time.Minute,\n\t\tDelay:      10 * time.Second,\n\t\tMinTimeout: 3 * time.Second,\n\t}\n\n\t_, sterr := stateConf.WaitForState()\n\tif sterr != nil {\n\t\treturn fmt.Errorf(\"Error waiting for elasticache (%s) to delete: %s\", d.Id(), sterr)\n\t}\n\n\td.SetId(\"\")\n\n\treturn nil\n}\n\nfunc CacheClusterStateRefreshFunc(conn *elasticache.ElastiCache, clusterID, givenState string, pending []string) resource.StateRefreshFunc {\n\treturn func() (interface{}, string, error) {\n\t\tresp, err := conn.DescribeCacheClusters(&elasticache.DescribeCacheClustersInput{\n\t\t\tCacheClusterID: aws.String(clusterID),\n\t\t})\n\t\tif err != nil {\n\t\t\tapierr := err.(aws.APIError)\n\t\t\tlog.Printf(\"[DEBUG] message: %v, code: %v\", apierr.Message, apierr.Code)\n\t\t\tif apierr.Message == fmt.Sprintf(\"CacheCluster not found: %v\", clusterID) {\n\t\t\t\tlog.Printf(\"[DEBUG] Detect deletion\")\n\t\t\t\treturn nil, \"\", nil\n\t\t\t}\n\n\t\t\tlog.Printf(\"[ERROR] CacheClusterStateRefreshFunc: %s\", err)\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\tc := resp.CacheClusters[0]\n\t\tlog.Printf(\"[DEBUG] status: %v\", *c.CacheClusterStatus)\n\n\t\t\/\/ return the current state if it's in the pending array\n\t\tfor _, p := range pending {\n\t\t\ts := *c.CacheClusterStatus\n\t\t\tif p == s {\n\t\t\t\tlog.Printf(\"[DEBUG] Return with status: %v\", *c.CacheClusterStatus)\n\t\t\t\treturn c, p, nil\n\t\t\t}\n\t\t}\n\n\t\t\/\/ return given state if it's not in pending\n\t\tif givenState != \"\" {\n\t\t\treturn c, givenState, nil\n\t\t}\n\t\tlog.Printf(\"[DEBUG] current status: %v\", *c.CacheClusterStatus)\n\t\treturn c, *c.CacheClusterStatus, nil\n\t}\n}\n\nfunc buildECARN(d *schema.ResourceData, meta interface{}) (string, error) {\n\tiamconn := meta.(*AWSClient).iamconn\n\tregion := meta.(*AWSClient).region\n\t\/\/ An zero value GetUserInput{} defers to the currently logged in user\n\tresp, err := iamconn.GetUser(&iam.GetUserInput{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tuserARN := *resp.User.ARN\n\taccountID := strings.Split(userARN, \":\")[4]\n\tarn := fmt.Sprintf(\"arn:aws:elasticache:%s:%s:cluster:%s\", region, accountID, d.Id())\n\treturn arn, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"github.com\/norisatir\/go-gtk3\/gtk3\"\n\n\nfunc CreateBBox(orientation int, title string, spacing int, layout int) *gtk3.Frame {\n\n\tframe := gtk3.NewFrame(title)\n\n\tbbox := gtk3.NewButtonBox(orientation)\t\n\tbbox.SetLayout(layout)\n\n\tbutton := gtk3.NewButtonFromStock(gtk3.GtkStock.OK)\n\tbbox.Add(button)\n\n\tbutton = gtk3.NewButtonFromStock(gtk3.GtkStock.CANCEL)\n\tbbox.Add(button)\n\n\tbutton = gtk3.NewButtonFromStock(gtk3.GtkStock.HELP)\n\tbbox.Add(button)\n\n\tframe.Add(bbox)\n\n\treturn frame\n}\n\n\nfunc DoButtonBox() *gtk3.Window {\n\twindow := gtk3.NewWindow(gtk3.GtkWindowType.TOPLEVEL, nil)\n\twindow.SetTitle(\"Button Boxes\")\n\twindow.Connect(\"destroy\", gtk3.MainQuit)\n\n\tmain_vbox := gtk3.NewVBox(0)\n\twindow.Add(main_vbox)\n\n\tframe_horz := gtk3.NewFrame(\"Horizontal Button Boxes\")\n\tmain_vbox.PackStart(frame_horz, true, true, 10)\n\n\tvbox := gtk3.NewVBox(0)\n\tframe_horz.Add(vbox)\n\n\tvbox.PackStart(CreateBBox(gtk3.GtkOrientation.HORIZONTAL, \"Spread\", 40, gtk3.GtkButtonBoxStyle.SPREAD), true, true, 0)\n\tvbox.PackStart(CreateBBox(gtk3.GtkOrientation.HORIZONTAL, \"Edge\", 40, gtk3.GtkButtonBoxStyle.EDGE), true, true, 5)\n\tvbox.PackStart(CreateBBox(gtk3.GtkOrientation.HORIZONTAL, \"Start\", 40, gtk3.GtkButtonBoxStyle.START), true, true, 5)\n\tvbox.PackStart(CreateBBox(gtk3.GtkOrientation.HORIZONTAL, \"End\", 40, gtk3.GtkButtonBoxStyle.END), true, true, 5)\n\n\n\tframe_vert := gtk3.NewFrame(\"Vertical Button Boxes\")\n\tmain_vbox.PackStart(frame_vert, true, true, 10)\n\n\n\thbox := gtk3.NewHBox(0)\n\tframe_vert.Add(hbox)\n\n\n\tvbox.PackStart(CreateBBox(gtk3.GtkOrientation.VERTICAL, \"Spread\", 30, gtk3.GtkButtonBoxStyle.SPREAD), true, true, 0)\n\tvbox.PackStart(CreateBBox(gtk3.GtkOrientation.VERTICAL, \"Edge\", 30, gtk3.GtkButtonBoxStyle.EDGE), true, true, 5)\n\tvbox.PackStart(CreateBBox(gtk3.GtkOrientation.VERTICAL, \"Start\", 30, gtk3.GtkButtonBoxStyle.START), true, true, 5)\n\tvbox.PackStart(CreateBBox(gtk3.GtkOrientation.VERTICAL, \"End\", 30, gtk3.GtkButtonBoxStyle.END), true, true, 5)\n\n\treturn window\n}\n\nfunc main() {\n\tgtk3.Init()\n\n\tw := DoButtonBox()\n\tw.ShowAll()\n\n\tgtk3.Main()\n}\n<commit_msg>Fixed buttonbox demo app.<commit_after>package main\n\nimport \"github.com\/norisatir\/go-gtk3\/gtk3\"\n\n\nfunc CreateBBox(orientation int, title string, spacing int, layout int) *gtk3.Frame {\n\n\tframe := gtk3.NewFrame(title)\n\n\tbbox := gtk3.NewButtonBox(orientation)\t\n\tbbox.SetLayout(layout)\n\n\tbutton := gtk3.NewButtonFromStock(gtk3.GtkStock.OK)\n\tbbox.Add(button)\n\n\tbutton = gtk3.NewButtonFromStock(gtk3.GtkStock.CANCEL)\n\tbbox.Add(button)\n\n\tbutton = gtk3.NewButtonFromStock(gtk3.GtkStock.HELP)\n\tbbox.Add(button)\n\n\tframe.Add(bbox)\n\n\treturn frame\n}\n\n\nfunc DoButtonBox() *gtk3.Window {\n\twindow := gtk3.NewWindow(gtk3.GtkWindowType.TOPLEVEL, nil)\n\twindow.SetTitle(\"Button Boxes\")\n\twindow.Connect(\"destroy\", gtk3.MainQuit)\n\n\tmain_vbox := gtk3.NewVBox(0)\n\twindow.Add(main_vbox)\n\n\tframe_horz := gtk3.NewFrame(\"Horizontal Button Boxes\")\n\tmain_vbox.PackStart(frame_horz, true, true, 10)\n\n\tvbox := gtk3.NewVBox(0)\n\tframe_horz.Add(vbox)\n\n\tvbox.PackStart(CreateBBox(gtk3.GtkOrientation.HORIZONTAL, \"Spread\", 40, gtk3.GtkButtonBoxStyle.SPREAD), true, true, 0)\n\tvbox.PackStart(CreateBBox(gtk3.GtkOrientation.HORIZONTAL, \"Edge\", 40, gtk3.GtkButtonBoxStyle.EDGE), true, true, 5)\n\tvbox.PackStart(CreateBBox(gtk3.GtkOrientation.HORIZONTAL, \"Start\", 40, gtk3.GtkButtonBoxStyle.START), true, true, 5)\n\tvbox.PackStart(CreateBBox(gtk3.GtkOrientation.HORIZONTAL, \"End\", 40, gtk3.GtkButtonBoxStyle.END), true, true, 5)\n\n\n\tframe_vert := gtk3.NewFrame(\"Vertical Button Boxes\")\n\tmain_vbox.PackStart(frame_vert, true, true, 10)\n\n\n\thbox := gtk3.NewHBox(0)\n\tframe_vert.Add(hbox)\n\n\n\thbox.PackStart(CreateBBox(gtk3.GtkOrientation.VERTICAL, \"Spread\", 30, gtk3.GtkButtonBoxStyle.SPREAD), true, true, 0)\n\thbox.PackStart(CreateBBox(gtk3.GtkOrientation.VERTICAL, \"Edge\", 30, gtk3.GtkButtonBoxStyle.EDGE), true, true, 5)\n\thbox.PackStart(CreateBBox(gtk3.GtkOrientation.VERTICAL, \"Start\", 30, gtk3.GtkButtonBoxStyle.START), true, true, 5)\n\thbox.PackStart(CreateBBox(gtk3.GtkOrientation.VERTICAL, \"End\", 30, gtk3.GtkButtonBoxStyle.END), true, true, 5)\n\n\treturn window\n}\n\nfunc main() {\n\tgtk3.Init()\n\n\tw := DoButtonBox()\n\tw.ShowAll()\n\n\tgtk3.Main()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage huaweicloud\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\tapiv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/resource\"\n\t\"k8s.io\/autoscaler\/cluster-autoscaler\/cloudprovider\"\n\t\"k8s.io\/autoscaler\/cluster-autoscaler\/config\"\n\t\"k8s.io\/autoscaler\/cluster-autoscaler\/utils\/errors\"\n\tklog \"k8s.io\/klog\/v2\"\n)\n\nconst (\n\t\/\/ GPULabel is the label added to nodes with GPU resource.\n\tGPULabel = \"cloud.google.com\/gke-accelerator\"\n)\n\nvar (\n\tavailableGPUTypes = map[string]struct{}{\n\t\t\"nvidia-tesla-k80\":  {},\n\t\t\"nvidia-tesla-p100\": {},\n\t\t\"nvidia-tesla-v100\": {},\n\t}\n)\n\n\/\/ huaweicloudCloudProvider implements CloudProvider interface defined in autoscaler\/cluster-autoscaler\/cloudprovider\/cloud_provider.go\ntype huaweicloudCloudProvider struct {\n\tcloudServiceManager CloudServiceManager\n\tresourceLimiter     *cloudprovider.ResourceLimiter\n\tautoScalingGroup    []AutoScalingGroup\n\tlock                sync.RWMutex\n\n\t\/\/ Following to be refactored\n\thuaweiCloudManager *huaweicloudCloudManager\n\tnodeGroups         []NodeGroup\n}\n\nfunc newCloudProvider(opts config.AutoscalingOptions, do cloudprovider.NodeGroupDiscoveryOptions, rl *cloudprovider.ResourceLimiter) *huaweicloudCloudProvider {\n\tcloudConfig, err := readConf(opts.CloudConfig)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to read cloud configuration. error: %v\", err)\n\t\treturn nil\n\t}\n\tif err = cloudConfig.validate(); err != nil {\n\t\tklog.Errorf(\"cloud configuration is invalid. error: %v\", err)\n\t\treturn nil\n\t}\n\n\tcsm := newCloudServiceManager(cloudConfig)\n\tsgs, err := csm.ListScalingGroups()\n\tif err != nil {\n\t\tklog.Errorf(\"failed to list scaling groups. error: %v\", err)\n\t\treturn nil\n\t}\n\n\treturn &huaweicloudCloudProvider{\n\t\tcloudServiceManager: csm,\n\t\tresourceLimiter:     rl,\n\t\tautoScalingGroup:    sgs,\n\t}\n}\n\n\/\/ Name returns the name of the cloud provider.\nfunc (hcp *huaweicloudCloudProvider) Name() string {\n\treturn cloudprovider.HuaweicloudProviderName\n}\n\n\/\/ NodeGroups returns all node groups managed by this cloud provider.\nfunc (hcp *huaweicloudCloudProvider) NodeGroups() []cloudprovider.NodeGroup {\n\thcp.lock.RLock()\n\tdefer hcp.lock.RUnlock()\n\n\tgroups := make([]cloudprovider.NodeGroup, 0, len(hcp.autoScalingGroup))\n\tfor i := range hcp.autoScalingGroup {\n\t\tpinedGroup := hcp.autoScalingGroup[i]\n\t\tgroups = append(groups, &pinedGroup)\n\t}\n\n\treturn groups\n}\n\n\/\/ NodeGroupForNode returns the node group for the given node, nil if the node\n\/\/ should not be processed by cluster autoscaler, or non-nil error if such\n\/\/ occurred. Must be implemented.\nfunc (hcp *huaweicloudCloudProvider) NodeGroupForNode(node *apiv1.Node) (cloudprovider.NodeGroup, error) {\n\tif _, found := node.ObjectMeta.Labels[\"node-role.kubernetes.io\/master\"]; found {\n\t\treturn nil, nil\n\t}\n\n\tinstanceID := node.Spec.ProviderID\n\tif len(instanceID) == 0 {\n\t\tklog.Warningf(\"Node %v has no providerId\", node.Name)\n\t\treturn nil, fmt.Errorf(\"provider id missing from node: %s\", node.Name)\n\t}\n\n\thcp.lock.RLock()\n\tdefer hcp.lock.RUnlock()\n\n\tfor i := range hcp.autoScalingGroup {\n\t\tinstances, err := hcp.autoScalingGroup[i].Nodes()\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"failed to list instances from scaling group: %s, error: %v\", hcp.autoScalingGroup[i].groupName, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor i := range instances {\n\t\t\tif instanceID == instances[i].Id {\n\t\t\t\tpinnedGroup := hcp.autoScalingGroup[i]\n\t\t\t\treturn &pinnedGroup, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"no node group found\")\n}\n\n\/\/ Pricing returns pricing model for this cloud provider or error if not available. Not implemented.\nfunc (hcp *huaweicloudCloudProvider) Pricing() (cloudprovider.PricingModel, errors.AutoscalerError) {\n\treturn nil, cloudprovider.ErrNotImplemented\n}\n\n\/\/ GetAvailableMachineTypes get all machine types that can be requested from the cloud provider. Not implemented.\nfunc (hcp *huaweicloudCloudProvider) GetAvailableMachineTypes() ([]string, error) {\n\treturn []string{}, nil\n}\n\n\/\/ NewNodeGroup builds a theoretical node group based on the node definition provided. The node group is not automatically\n\/\/ created on the cloud provider side. The node group is not returned by NodeGroups() until it is created. Not implemented.\nfunc (hcp *huaweicloudCloudProvider) NewNodeGroup(machineType string, labels map[string]string, systemLabels map[string]string,\n\ttaints []apiv1.Taint, extraResources map[string]resource.Quantity) (cloudprovider.NodeGroup, error) {\n\treturn nil, cloudprovider.ErrNotImplemented\n}\n\n\/\/ GetResourceLimiter returns struct containing limits (max, min) for resources (cores, memory etc.).\nfunc (hcp *huaweicloudCloudProvider) GetResourceLimiter() (*cloudprovider.ResourceLimiter, error) {\n\treturn hcp.resourceLimiter, nil\n}\n\n\/\/ GPULabel returns the label added to nodes with GPU resource.\nfunc (hcp *huaweicloudCloudProvider) GPULabel() string {\n\treturn GPULabel\n}\n\n\/\/ GetAvailableGPUTypes returns all available GPU types cloud provider supports.\nfunc (hcp *huaweicloudCloudProvider) GetAvailableGPUTypes() map[string]struct{} {\n\treturn availableGPUTypes\n}\n\n\/\/ Cleanup currently does nothing.\nfunc (hcp *huaweicloudCloudProvider) Cleanup() error {\n\treturn nil\n}\n\n\/\/ Refresh is called before every main loop and can be used to dynamically update cloud provider state.\n\/\/ In particular the list of node groups returned by NodeGroups can change as a result of CloudProvider.Refresh().\n\/\/ Currently does nothing.\nfunc (hcp *huaweicloudCloudProvider) Refresh() error {\n\treturn nil\n}\n\n\/\/ BuildHuaweiCloud is called by the autoscaler\/cluster-autoscaler\/builder to build a huaweicloud cloud provider.\nfunc BuildHuaweiCloud(opts config.AutoscalingOptions, do cloudprovider.NodeGroupDiscoveryOptions, rl *cloudprovider.ResourceLimiter) cloudprovider.CloudProvider {\n\tif len(opts.CloudConfig) == 0 {\n\t\tklog.Fatalf(\"cloud config is missing.\")\n\t}\n\n\treturn newCloudProvider(opts, do, rl)\n}\n<commit_msg>Fix find node from scaling groups would cause panic issue<commit_after>\/*\nCopyright 2020 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage huaweicloud\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\tapiv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/resource\"\n\t\"k8s.io\/autoscaler\/cluster-autoscaler\/cloudprovider\"\n\t\"k8s.io\/autoscaler\/cluster-autoscaler\/config\"\n\t\"k8s.io\/autoscaler\/cluster-autoscaler\/utils\/errors\"\n\tklog \"k8s.io\/klog\/v2\"\n)\n\nconst (\n\t\/\/ GPULabel is the label added to nodes with GPU resource.\n\tGPULabel = \"cloud.google.com\/gke-accelerator\"\n)\n\nvar (\n\tavailableGPUTypes = map[string]struct{}{\n\t\t\"nvidia-tesla-k80\":  {},\n\t\t\"nvidia-tesla-p100\": {},\n\t\t\"nvidia-tesla-v100\": {},\n\t}\n)\n\n\/\/ huaweicloudCloudProvider implements CloudProvider interface defined in autoscaler\/cluster-autoscaler\/cloudprovider\/cloud_provider.go\ntype huaweicloudCloudProvider struct {\n\tcloudServiceManager CloudServiceManager\n\tresourceLimiter     *cloudprovider.ResourceLimiter\n\tautoScalingGroup    []AutoScalingGroup\n\tlock                sync.RWMutex\n\n\t\/\/ Following to be refactored\n\thuaweiCloudManager *huaweicloudCloudManager\n\tnodeGroups         []NodeGroup\n}\n\nfunc newCloudProvider(opts config.AutoscalingOptions, do cloudprovider.NodeGroupDiscoveryOptions, rl *cloudprovider.ResourceLimiter) *huaweicloudCloudProvider {\n\tcloudConfig, err := readConf(opts.CloudConfig)\n\tif err != nil {\n\t\tklog.Errorf(\"failed to read cloud configuration. error: %v\", err)\n\t\treturn nil\n\t}\n\tif err = cloudConfig.validate(); err != nil {\n\t\tklog.Errorf(\"cloud configuration is invalid. error: %v\", err)\n\t\treturn nil\n\t}\n\n\tcsm := newCloudServiceManager(cloudConfig)\n\tsgs, err := csm.ListScalingGroups()\n\tif err != nil {\n\t\tklog.Errorf(\"failed to list scaling groups. error: %v\", err)\n\t\treturn nil\n\t}\n\n\treturn &huaweicloudCloudProvider{\n\t\tcloudServiceManager: csm,\n\t\tresourceLimiter:     rl,\n\t\tautoScalingGroup:    sgs,\n\t}\n}\n\n\/\/ Name returns the name of the cloud provider.\nfunc (hcp *huaweicloudCloudProvider) Name() string {\n\treturn cloudprovider.HuaweicloudProviderName\n}\n\n\/\/ NodeGroups returns all node groups managed by this cloud provider.\nfunc (hcp *huaweicloudCloudProvider) NodeGroups() []cloudprovider.NodeGroup {\n\thcp.lock.RLock()\n\tdefer hcp.lock.RUnlock()\n\n\tgroups := make([]cloudprovider.NodeGroup, 0, len(hcp.autoScalingGroup))\n\tfor i := range hcp.autoScalingGroup {\n\t\tpinedGroup := hcp.autoScalingGroup[i]\n\t\tgroups = append(groups, &pinedGroup)\n\t}\n\n\treturn groups\n}\n\n\/\/ NodeGroupForNode returns the node group for the given node, nil if the node\n\/\/ should not be processed by cluster autoscaler, or non-nil error if such\n\/\/ occurred. Must be implemented.\nfunc (hcp *huaweicloudCloudProvider) NodeGroupForNode(node *apiv1.Node) (cloudprovider.NodeGroup, error) {\n\tif _, found := node.ObjectMeta.Labels[\"node-role.kubernetes.io\/master\"]; found {\n\t\treturn nil, nil\n\t}\n\n\tinstanceID := node.Spec.ProviderID\n\tif len(instanceID) == 0 {\n\t\tklog.Warningf(\"Node %v has no providerId\", node.Name)\n\t\treturn nil, fmt.Errorf(\"provider id missing from node: %s\", node.Name)\n\t}\n\n\thcp.lock.RLock()\n\tdefer hcp.lock.RUnlock()\n\n\tfor i := range hcp.autoScalingGroup {\n\t\tinstances, err := hcp.autoScalingGroup[i].Nodes()\n\t\tif err != nil {\n\t\t\tklog.Warningf(\"failed to list instances from scaling group: %s, error: %v\", hcp.autoScalingGroup[i].groupName, err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor j := range instances {\n\t\t\tif instanceID == instances[j].Id {\n\t\t\t\tpinnedGroup := hcp.autoScalingGroup[i]\n\t\t\t\treturn &pinnedGroup, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"no node group found\")\n}\n\n\/\/ Pricing returns pricing model for this cloud provider or error if not available. Not implemented.\nfunc (hcp *huaweicloudCloudProvider) Pricing() (cloudprovider.PricingModel, errors.AutoscalerError) {\n\treturn nil, cloudprovider.ErrNotImplemented\n}\n\n\/\/ GetAvailableMachineTypes get all machine types that can be requested from the cloud provider. Not implemented.\nfunc (hcp *huaweicloudCloudProvider) GetAvailableMachineTypes() ([]string, error) {\n\treturn []string{}, nil\n}\n\n\/\/ NewNodeGroup builds a theoretical node group based on the node definition provided. The node group is not automatically\n\/\/ created on the cloud provider side. The node group is not returned by NodeGroups() until it is created. Not implemented.\nfunc (hcp *huaweicloudCloudProvider) NewNodeGroup(machineType string, labels map[string]string, systemLabels map[string]string,\n\ttaints []apiv1.Taint, extraResources map[string]resource.Quantity) (cloudprovider.NodeGroup, error) {\n\treturn nil, cloudprovider.ErrNotImplemented\n}\n\n\/\/ GetResourceLimiter returns struct containing limits (max, min) for resources (cores, memory etc.).\nfunc (hcp *huaweicloudCloudProvider) GetResourceLimiter() (*cloudprovider.ResourceLimiter, error) {\n\treturn hcp.resourceLimiter, nil\n}\n\n\/\/ GPULabel returns the label added to nodes with GPU resource.\nfunc (hcp *huaweicloudCloudProvider) GPULabel() string {\n\treturn GPULabel\n}\n\n\/\/ GetAvailableGPUTypes returns all available GPU types cloud provider supports.\nfunc (hcp *huaweicloudCloudProvider) GetAvailableGPUTypes() map[string]struct{} {\n\treturn availableGPUTypes\n}\n\n\/\/ Cleanup currently does nothing.\nfunc (hcp *huaweicloudCloudProvider) Cleanup() error {\n\treturn nil\n}\n\n\/\/ Refresh is called before every main loop and can be used to dynamically update cloud provider state.\n\/\/ In particular the list of node groups returned by NodeGroups can change as a result of CloudProvider.Refresh().\n\/\/ Currently does nothing.\nfunc (hcp *huaweicloudCloudProvider) Refresh() error {\n\treturn nil\n}\n\n\/\/ BuildHuaweiCloud is called by the autoscaler\/cluster-autoscaler\/builder to build a huaweicloud cloud provider.\nfunc BuildHuaweiCloud(opts config.AutoscalingOptions, do cloudprovider.NodeGroupDiscoveryOptions, rl *cloudprovider.ResourceLimiter) cloudprovider.CloudProvider {\n\tif len(opts.CloudConfig) == 0 {\n\t\tklog.Fatalf(\"cloud config is missing.\")\n\t}\n\n\treturn newCloudProvider(opts, do, rl)\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Made channel ownership cleaner<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>return after 404 json output<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Exposed File to lua<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Fixed example of valid config in --help option<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Extend example<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>better logging and error handling<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>added comments<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix notebook alias.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Remove the YAML bit of the CLI app<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Handle blocks asynchronously.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>using port 80<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>formatting for join<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Update help for x509 issue to explain defaults<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Initial application setup<commit_after><|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\".\/schemas\"\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/companieshouse\/chs.go\/avro\"\n\t\"github.com\/companieshouse\/chs.go\/avro\/schema\"\n\t\"github.com\/companieshouse\/chs.go\/kafka\/producer\"\n)\n\n\/\/ Assigns all flags to variables\nvar (\n\tbrokerPtr         = flag.String(\"broker\", \"\", \"Broker\")\n\ttopicPtr          = flag.String(\"topic\", \"\", \"Topic name\")\n\tschemaPtr         = flag.String(\"schema\", \"\", \"Schema\")\n\tschemaRegistryPtr = flag.String(\"schema-registry\", \"\", \"Schema Registry\")\n\tpartitionPtr      = flag.Int64(\"partition\", 0, \"Partition\")\n\tzookeeperPtr      = flag.String(\"zookeeper\", \"\", \"Zookeeper\")\n\toffsetPtr         = flag.String(\"offset\", \"-1\", \"Offset number\")\n\tjsonOutPtr        = flag.Int(\"json-out\", -1, \"Does deserialized JSON get printed to terminal?\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tfmt.Println(\"broker:\", *brokerPtr)\n\tfmt.Println(\"topic:\", *topicPtr)\n\tfmt.Println(\"schema:\", *schemaPtr)\n\tfmt.Println(\"schema-registry:\", *schemaRegistryPtr)\n\tfmt.Println(\"partition:\", *partitionPtr)\n\tfmt.Println(\"zookeeper-registry:\", *zookeeperPtr)\n\tfmt.Println(\"offset:\", *offsetPtr)\n\tfmt.Println(\"json-out:\", *jsonOutPtr)\n\n\t\/\/ create offset array\n\toffsetArray := createOffsetArray(*offsetPtr)\n\n\t\/\/ create default config for sarama\n\tconfig := sarama.NewConfig()\n\n\t\/\/create consumer\n\tconsumer, err := sarama.NewConsumer([]string{*brokerPtr}, config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ create messages chan\n\tmessages := make(chan *sarama.ConsumerMessage)\n\tgo consumePartition(consumer, *topicPtr, int32(*partitionPtr), messages, offsetArray)\n\n\t\/\/ create signals chan\n\tsignals := make(chan os.Signal, 1)\n\tsignal.Notify(signals, os.Interrupt)\n\n\tconsumed := 0\nConsumerLoop:\n\tfor {\n\t\tselect {\n\t\tcase msg := <-messages:\n\n\t\t\tschemaStruct := schemas.IdentifySchema(*topicPtr)\n\t\t\tvar err error\n\n\t\t\t\/\/ Get schema from schema registry and use it to create avro consumer\n\t\t\tschema, err := schema.Get(*schemaRegistryPtr, *topicPtr)\n\t\t\tconsumerAvro := &avro.Schema{\n\t\t\t\tDefinition: schema,\n\t\t\t}\n\n\t\t\t\/\/ Unmarshal message value and assign it to schemaStruct\n\t\t\tif err = consumerAvro.Unmarshal(msg.Value, schemaStruct); err != nil {\n\t\t\t\tfmt.Println(\"Error unmarshalling avro:\")\n\t\t\t}\n\n\t\t\t\/\/ create avro producer\n\t\t\tproducerAvro := &avro.Schema{\n\t\t\t\tDefinition: schema,\n\t\t\t}\n\n\t\t\t\/\/ Marshall schemaStruct that contains message value ready for republishing\n\t\t\tmessageBytes, err := producerAvro.Marshal(schemaStruct)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error Marshalling avro:\")\n\t\t\t}\n\n\t\t\t\/\/ create producer message\n\t\t\tproducerMessage := &producer.Message{\n\t\t\t\tValue: messageBytes,\n\t\t\t\tTopic: *topicPtr,\n\t\t\t}\n\n\t\t\t\/\/create new producer\n\t\t\tp, err := producer.New(&producer.Config{Acks: &producer.WaitForAll, BrokerAddrs: []string{*brokerPtr}})\n\t\t\tif err != nil {\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\t\/\/ republish message\n\t\t\tpartition, offset, err := p.Send(producerMessage)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error republishing message:\")\n\t\t\t}\n\t\t\tfmt.Println(\"Message republished!\", partition, offset)\n\n\t\t\tconsumed++\n\t\tcase <-signals:\n\t\t\tfmt.Println(\"break\")\n\t\t\tbreak ConsumerLoop\n\t\t}\n\t}\n}\n\n\/\/ The offset slice is passed into method and is iterated over and each message\n\/\/ related to the offset in the topic\/partition is outputted into the 'out' chan\nfunc consumePartition(consumer sarama.Consumer, topic string, partition int32, out chan *sarama.ConsumerMessage, offsetArray []int64) {\n\tfor offset := range offsetArray {\n\t\tpartitionConsumer, err := consumer.ConsumePartition(topic, partition, int64(offset))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tselect {\n\t\tcase msg := <-partitionConsumer.Messages():\n\t\t\tpartitionConsumer.Close()\n\t\t\tout <- msg\n\t\t}\n\t}\n}\n\n\/\/ This creates the offset array depending on whether a range or a single value\n\/\/ is entered as an argument to the tool\nfunc createOffsetArray(offset string) []int64 {\n\tarraySize := make([]int64, 0)\n\tif strings.ContainsAny(offset, \"-\") {\n\t\tslice := strings.Split(offset, \"-\")\n\t\tminRange, err := strconv.ParseInt(slice[0], 10, 64)\n\t\tmaxRange, err := strconv.ParseInt(slice[1], 10, 64)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tindex := 0\n\t\tfor value := minRange; value <= maxRange; value++ {\n\t\t\tarraySize = append(arraySize, value)\n\t\t\tindex++\n\t\t}\n\t} else {\n\t\tvalue, err := strconv.ParseInt(offset, 10, 64)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tarraySize = append(arraySize, value)\n\t}\n\treturn arraySize\n}\n<commit_msg>Improved description for flag fields<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\".\/schemas\"\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/companieshouse\/chs.go\/avro\"\n\t\"github.com\/companieshouse\/chs.go\/avro\/schema\"\n\t\"github.com\/companieshouse\/chs.go\/kafka\/producer\"\n)\n\n\/\/ Assigns all flags to variables\nvar (\n\tbrokerPtr         = flag.String(\"broker\", \"\", \"Broker address\")\n\ttopicPtr          = flag.String(\"topic\", \"\", \"Topic name\")\n\tschemaPtr         = flag.String(\"schema\", \"\", \"Schema name\")\n\tschemaRegistryPtr = flag.String(\"schema-registry\", \"\", \"Schema Registry\")\n\tpartitionPtr      = flag.Int64(\"partition\", 0, \"Partition\")\n\tzookeeperPtr      = flag.String(\"zookeeper\", \"\", \"Zookeeper address\")\n\toffsetPtr         = flag.String(\"offset\", \"-1\", \"Offset number\")\n\tjsonOutPtr        = flag.Int(\"json-out\", -1, \"Print deserialized JSON message\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tfmt.Println(\"broker:\", *brokerPtr)\n\tfmt.Println(\"topic:\", *topicPtr)\n\tfmt.Println(\"schema:\", *schemaPtr)\n\tfmt.Println(\"schema-registry:\", *schemaRegistryPtr)\n\tfmt.Println(\"partition:\", *partitionPtr)\n\tfmt.Println(\"zookeeper-registry:\", *zookeeperPtr)\n\tfmt.Println(\"offset:\", *offsetPtr)\n\tfmt.Println(\"json-out:\", *jsonOutPtr)\n\n\t\/\/ create offset array\n\toffsetArray := createOffsetArray(*offsetPtr)\n\n\t\/\/ create default config for sarama\n\tconfig := sarama.NewConfig()\n\n\t\/\/create consumer\n\tconsumer, err := sarama.NewConsumer([]string{*brokerPtr}, config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ create messages chan\n\tmessages := make(chan *sarama.ConsumerMessage)\n\tgo consumePartition(consumer, *topicPtr, int32(*partitionPtr), messages, offsetArray)\n\n\t\/\/ create signals chan\n\tsignals := make(chan os.Signal, 1)\n\tsignal.Notify(signals, os.Interrupt)\n\n\tconsumed := 0\nConsumerLoop:\n\tfor {\n\t\tselect {\n\t\tcase msg := <-messages:\n\n\t\t\tschemaStruct := schemas.IdentifySchema(*topicPtr)\n\t\t\tvar err error\n\n\t\t\t\/\/ Get schema from schema registry and use it to create avro consumer\n\t\t\tschema, err := schema.Get(*schemaRegistryPtr, *topicPtr)\n\t\t\tconsumerAvro := &avro.Schema{\n\t\t\t\tDefinition: schema,\n\t\t\t}\n\n\t\t\t\/\/ Unmarshal message value and assign it to schemaStruct\n\t\t\tif err = consumerAvro.Unmarshal(msg.Value, schemaStruct); err != nil {\n\t\t\t\tfmt.Println(\"Error unmarshalling avro:\")\n\t\t\t}\n\n\t\t\t\/\/ create avro producer\n\t\t\tproducerAvro := &avro.Schema{\n\t\t\t\tDefinition: schema,\n\t\t\t}\n\n\t\t\t\/\/ Marshall schemaStruct that contains message value ready for republishing\n\t\t\tmessageBytes, err := producerAvro.Marshal(schemaStruct)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error Marshalling avro:\")\n\t\t\t}\n\n\t\t\t\/\/ create producer message\n\t\t\tproducerMessage := &producer.Message{\n\t\t\t\tValue: messageBytes,\n\t\t\t\tTopic: *topicPtr,\n\t\t\t}\n\n\t\t\t\/\/create new producer\n\t\t\tp, err := producer.New(&producer.Config{Acks: &producer.WaitForAll, BrokerAddrs: []string{*brokerPtr}})\n\t\t\tif err != nil {\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\n\t\t\t\/\/ republish message\n\t\t\tpartition, offset, err := p.Send(producerMessage)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error republishing message:\")\n\t\t\t}\n\t\t\tfmt.Println(\"Message republished!\", partition, offset)\n\n\t\t\tconsumed++\n\t\tcase <-signals:\n\t\t\tfmt.Println(\"break\")\n\t\t\tbreak ConsumerLoop\n\t\t}\n\t}\n}\n\n\/\/ The offset slice is passed into method and is iterated over and each message\n\/\/ related to the offset in the topic\/partition is outputted into the 'out' chan\nfunc consumePartition(consumer sarama.Consumer, topic string, partition int32, out chan *sarama.ConsumerMessage, offsetArray []int64) {\n\tfor offset := range offsetArray {\n\t\tpartitionConsumer, err := consumer.ConsumePartition(topic, partition, int64(offset))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tselect {\n\t\tcase msg := <-partitionConsumer.Messages():\n\t\t\tpartitionConsumer.Close()\n\t\t\tout <- msg\n\t\t}\n\t}\n}\n\n\/\/ This creates the offset array depending on whether a range or a single value\n\/\/ is entered as an argument to the tool\nfunc createOffsetArray(offset string) []int64 {\n\tarraySize := make([]int64, 0)\n\tif strings.ContainsAny(offset, \"-\") {\n\t\tslice := strings.Split(offset, \"-\")\n\t\tminRange, err := strconv.ParseInt(slice[0], 10, 64)\n\t\tmaxRange, err := strconv.ParseInt(slice[1], 10, 64)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tindex := 0\n\t\tfor value := minRange; value <= maxRange; value++ {\n\t\t\tarraySize = append(arraySize, value)\n\t\t\tindex++\n\t\t}\n\t} else {\n\t\tvalue, err := strconv.ParseInt(offset, 10, 64)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tarraySize = append(arraySize, value)\n\t}\n\treturn arraySize\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>manual merge<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>travis: remove unnecessary convert to int64. (#220)<commit_after><|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"context\"\n\tstdlog \"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/alecthomas\/kingpin\"\n\t\"github.com\/estafette\/estafette-ci-api\/auth\"\n\t\"github.com\/estafette\/estafette-ci-api\/bitbucket\"\n\t\"github.com\/estafette\/estafette-ci-api\/cockroach\"\n\t\"github.com\/estafette\/estafette-ci-api\/config\"\n\t\"github.com\/estafette\/estafette-ci-api\/estafette\"\n\t\"github.com\/estafette\/estafette-ci-api\/github\"\n\t\"github.com\/estafette\/estafette-ci-api\/slack\"\n\tcrypt \"github.com\/estafette\/estafette-ci-crypt\"\n\t\"github.com\/gin-contrib\/gzip\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\/promhttp\"\n\t\"github.com\/rs\/zerolog\"\n\t\"github.com\/rs\/zerolog\/log\"\n)\n\nvar (\n\tversion   string\n\tbranch    string\n\trevision  string\n\tbuildDate string\n\tgoVersion = runtime.Version()\n)\n\nvar (\n\t\/\/ flags\n\tprometheusMetricsAddress     = kingpin.Flag(\"metrics-listen-address\", \"The address to listen on for Prometheus metrics requests.\").Default(\":9001\").String()\n\tprometheusMetricsPath        = kingpin.Flag(\"metrics-path\", \"The path to listen for Prometheus metrics requests.\").Default(\"\/metrics\").String()\n\tapiAddress                   = kingpin.Flag(\"api-listen-address\", \"The address to listen on for api HTTP requests.\").Default(\":5000\").String()\n\tconfigFilePath               = kingpin.Flag(\"config-file-path\", \"The path to yaml config file configuring this application.\").Default(\"\/configs\/config.yaml\").String()\n\tsecretDecryptionKey          = kingpin.Flag(\"secret-decryption-key\", \"The AES-256 key used to decrypt secrets that have been encrypted with it.\").Envar(\"SECRET_DECRYPTION_KEY\").String()\n\tgracefulShutdownDelaySeconds = kingpin.Flag(\"graceful-shutdown-delay-seconds\", \"The number of seconds to wait with graceful shutdown in order to let endpoints update propagation finish.\").Default(\"15\").OverrideDefaultFromEnvar(\"GRACEFUL_SHUTDOWN_DELAY_SECONDS\").Int()\n\n\t\/\/ prometheusInboundEventTotals is the prometheus timeline serie that keeps track of inbound events\n\tprometheusInboundEventTotals = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tName: \"estafette_ci_api_inbound_event_totals\",\n\t\t\tHelp: \"Total of inbound events.\",\n\t\t},\n\t\t[]string{\"event\", \"source\"},\n\t)\n\n\t\/\/ prometheusOutboundAPICallTotals is the prometheus timeline serie that keeps track of outbound api calls\n\tprometheusOutboundAPICallTotals = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tName: \"estafette_ci_api_outbound_api_call_totals\",\n\t\t\tHelp: \"Total of outgoing api calls.\",\n\t\t},\n\t\t[]string{\"target\"},\n\t)\n)\n\nfunc init() {\n\t\/\/ Metrics have to be registered to be exposed:\n\tprometheus.MustRegister(prometheusInboundEventTotals)\n\tprometheus.MustRegister(prometheusOutboundAPICallTotals)\n}\n\nfunc main() {\n\n\t\/\/ parse command line parameters\n\tkingpin.Parse()\n\n\t\/\/ configure json logging\n\tinitLogging()\n\n\t\/\/ define channels and waitgroup to gracefully shutdown the application\n\tsigs := make(chan os.Signal, 1)                                    \/\/ Create channel to receive OS signals\n\tstop := make(chan struct{})                                        \/\/ Create channel to receive stop signal\n\tsignal.Notify(sigs, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) \/\/ Register the sigs channel to receieve SIGTERM\n\twg := &sync.WaitGroup{}                                            \/\/ Goroutines can add themselves to this to be waited on so that they finish\n\n\t\/\/ start prometheus\n\tgo startPrometheus()\n\n\t\/\/ handle api requests\n\tsrv := handleRequests(stop, wg)\n\n\t\/\/ wait for graceful shutdown to finish\n\t<-sigs \/\/ Wait for signals (this hangs until a signal arrives)\n\tlog.Info().Msgf(\"Shutting down in %v seconds...\", *gracefulShutdownDelaySeconds)\n\ttime.Sleep(time.Duration(*gracefulShutdownDelaySeconds) * 1000 * time.Millisecond)\n\n\t\/\/ shut down gracefully\n\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\tdefer cancel()\n\tif err := srv.Shutdown(ctx); err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Graceful server shutdown failed\")\n\t}\n\n\tlog.Debug().Msg(\"Stopping goroutines...\")\n\tclose(stop) \/\/ Tell goroutines to stop themselves\n\n\tlog.Debug().Msg(\"Awaiting waitgroup...\")\n\twg.Wait() \/\/ Wait for all to be stopped\n\n\tlog.Info().Msg(\"Server gracefully stopped\")\n}\n\nfunc startPrometheus() {\n\thttp.Handle(*prometheusMetricsPath, promhttp.Handler())\n\n\tif err := http.ListenAndServe(*prometheusMetricsAddress, nil); err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Starting Prometheus listener failed\")\n\t}\n}\n\nfunc initLogging() {\n\n\t\/\/ log as severity for stackdriver logging to recognize the level\n\tzerolog.LevelFieldName = \"severity\"\n\n\t\/\/ set some default fields added to all logs\n\tlog.Logger = zerolog.New(os.Stdout).With().\n\t\tTimestamp().\n\t\tStr(\"app\", \"estafette-ci-api\").\n\t\tStr(\"version\", version).\n\t\tLogger()\n\n\t\/\/ use zerolog for any logs sent via standard log library\n\tstdlog.SetFlags(0)\n\tstdlog.SetOutput(log.Logger)\n\n\t\/\/ log startup message\n\tlog.Info().\n\t\tStr(\"branch\", branch).\n\t\tStr(\"revision\", revision).\n\t\tStr(\"buildDate\", buildDate).\n\t\tStr(\"goVersion\", goVersion).\n\t\tMsg(\"Starting estafette-ci-api...\")\n}\n\nfunc createRouter() *gin.Engine {\n\n\t\/\/ run gin in release mode and other defaults\n\tgin.SetMode(gin.ReleaseMode)\n\tgin.DefaultWriter = log.Logger\n\tgin.DisableConsoleColor()\n\n\t\/\/ Creates a router without any middleware by default\n\trouter := gin.New()\n\n\t\/\/ Recovery middleware recovers from any panics and writes a 500 if there was one.\n\trouter.Use(gin.Recovery())\n\n\t\/\/ access logs with zerolog\n\trouter.Use(ZeroLogMiddleware())\n\n\t\/\/ liveness and readiness\n\trouter.GET(\"\/liveness\", func(c *gin.Context) {\n\t\tc.String(200, \"I'm alive!\")\n\t})\n\trouter.GET(\"\/readiness\", func(c *gin.Context) {\n\t\tc.String(200, \"I'm ready!\")\n\t})\n\n\treturn router\n}\n\nfunc handleRequests(stopChannel <-chan struct{}, waitGroup *sync.WaitGroup) *http.Server {\n\n\tsecretHelper := crypt.NewSecretHelper(*secretDecryptionKey)\n\tconfigReader := config.NewConfigReader(secretHelper)\n\n\tconfig, err := configReader.ReadConfigFromFile(*configFilePath, true)\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Failed reading configuration\")\n\t}\n\n\tencryptedConfig, err := configReader.ReadConfigFromFile(*configFilePath, false)\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Failed reading configuration without decrypting\")\n\t}\n\n\tgithubAPIClient := github.NewGithubAPIClient(*config.Integrations.Github, prometheusOutboundAPICallTotals)\n\tbitbucketAPIClient := bitbucket.NewBitbucketAPIClient(*config.Integrations.Bitbucket, prometheusOutboundAPICallTotals)\n\tslackAPIClient := slack.NewSlackAPIClient(*config.Integrations.Slack, prometheusOutboundAPICallTotals)\n\tcockroachDBClient := cockroach.NewCockroachDBClient(*config.Database, prometheusOutboundAPICallTotals)\n\tciBuilderClient, err := estafette.NewCiBuilderClient(*config, *encryptedConfig, *secretDecryptionKey, prometheusOutboundAPICallTotals)\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Creating new CiBuilderClient has failed\")\n\t}\n\n\t\/\/ set up database\n\terr = cockroachDBClient.Connect()\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Failed connecting to CockroachDB\")\n\t}\n\n\t\/\/ create and init router\n\trouter := createRouter()\n\n\t\/\/ Gzip and logging middleware\n\tgzippedRoutes := router.Group(\"\/\", gzip.Gzip(gzip.DefaultCompression))\n\n\t\/\/ middleware to handle auth for different endpoints\n\tauthMiddleware := auth.NewAuthMiddleware(*config.Auth)\n\n\testafetteBuildService := estafette.NewBuildService(cockroachDBClient, ciBuilderClient, githubAPIClient.JobVarsFunc(), bitbucketAPIClient.JobVarsFunc())\n\n\tgithubEventHandler := github.NewGithubEventHandler(githubAPIClient, estafetteBuildService, *config.Integrations.Github, prometheusInboundEventTotals)\n\tgzippedRoutes.POST(\"\/api\/integrations\/github\/events\", githubEventHandler.Handle)\n\n\tbitbucketEventHandler := bitbucket.NewBitbucketEventHandler(bitbucketAPIClient, estafetteBuildService, prometheusInboundEventTotals)\n\tgzippedRoutes.POST(\"\/api\/integrations\/bitbucket\/events\", bitbucketEventHandler.Handle)\n\n\tslackEventHandler := slack.NewSlackEventHandler(secretHelper, *config.Integrations.Slack, slackAPIClient, cockroachDBClient, *config.APIServer, estafetteBuildService, githubAPIClient.JobVarsFunc(), bitbucketAPIClient.JobVarsFunc(), prometheusInboundEventTotals)\n\tgzippedRoutes.POST(\"\/api\/integrations\/slack\/slash\", slackEventHandler.Handle)\n\n\testafetteEventHandler := estafette.NewEstafetteEventHandler(*config.APIServer, ciBuilderClient, cockroachDBClient, prometheusInboundEventTotals)\n\twarningHelper := estafette.NewWarningHelper()\n\n\testafetteAPIHandler := estafette.NewAPIHandler(*configFilePath, *config.APIServer, *config.Auth, *encryptedConfig, cockroachDBClient, ciBuilderClient, estafetteBuildService, warningHelper, secretHelper, githubAPIClient.JobVarsFunc(), bitbucketAPIClient.JobVarsFunc())\n\tgzippedRoutes.GET(\"\/api\/pipelines\", estafetteAPIHandler.GetPipelines)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\", estafetteAPIHandler.GetPipeline)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\", estafetteAPIHandler.GetPipelineBuilds)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\/:revisionOrId\", estafetteAPIHandler.GetPipelineBuild)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\/:revisionOrId\/logs\", estafetteAPIHandler.GetPipelineBuildLogs)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\/:revisionOrId\/warnings\", estafetteAPIHandler.GetPipelineBuildWarnings)\n\trouter.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\/:revisionOrId\/logs\/tail\", estafetteAPIHandler.TailPipelineBuildLogs)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\", estafetteAPIHandler.GetPipelineReleases)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\/:id\", estafetteAPIHandler.GetPipelineRelease)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\/:id\/logs\", estafetteAPIHandler.GetPipelineReleaseLogs)\n\trouter.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\/:id\/logs\/tail\", estafetteAPIHandler.TailPipelineReleaseLogs)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/stats\/buildsdurations\", estafetteAPIHandler.GetPipelineStatsBuildsDurations)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/stats\/releasesdurations\", estafetteAPIHandler.GetPipelineStatsReleasesDurations)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/warnings\", estafetteAPIHandler.GetPipelineWarnings)\n\tgzippedRoutes.GET(\"\/api\/stats\/pipelinescount\", estafetteAPIHandler.GetStatsPipelinesCount)\n\tgzippedRoutes.GET(\"\/api\/stats\/buildscount\", estafetteAPIHandler.GetStatsBuildsCount)\n\tgzippedRoutes.GET(\"\/api\/stats\/releasescount\", estafetteAPIHandler.GetStatsReleasesCount)\n\tgzippedRoutes.GET(\"\/api\/stats\/buildsduration\", estafetteAPIHandler.GetStatsBuildsDuration)\n\tgzippedRoutes.GET(\"\/api\/stats\/buildsadoption\", estafetteAPIHandler.GetStatsBuildsAdoption)\n\tgzippedRoutes.GET(\"\/api\/stats\/releasesadoption\", estafetteAPIHandler.GetStatsReleasesAdoption)\n\tgzippedRoutes.GET(\"\/api\/stats\/mostbuilds\", estafetteAPIHandler.GetStatsMostBuilds)\n\tgzippedRoutes.GET(\"\/api\/stats\/mostreleases\", estafetteAPIHandler.GetStatsMostReleases)\n\tgzippedRoutes.GET(\"\/api\/manifest\/templates\", estafetteAPIHandler.GetManifestTemplates)\n\tgzippedRoutes.POST(\"\/api\/manifest\/generate\", estafetteAPIHandler.GenerateManifest)\n\tgzippedRoutes.POST(\"\/api\/manifest\/validate\", estafetteAPIHandler.ValidateManifest)\n\tgzippedRoutes.POST(\"\/api\/manifest\/encrypt\", estafetteAPIHandler.EncryptSecret)\n\tgzippedRoutes.POST(\"\/api\/labels\/frequent\", estafetteAPIHandler.GetFrequentLabels)\n\n\t\/\/ api key protected endpoints\n\tapiKeyAuthorizedRoutes := gzippedRoutes.Group(\"\/\", authMiddleware.APIKeyMiddlewareFunc())\n\t{\n\t\tapiKeyAuthorizedRoutes.POST(\"\/api\/commands\", estafetteEventHandler.Handle)\n\t\tapiKeyAuthorizedRoutes.POST(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\/:revisionOrId\/logs\", estafetteAPIHandler.PostPipelineBuildLogs)\n\t\tapiKeyAuthorizedRoutes.POST(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\/:id\/logs\", estafetteAPIHandler.PostPipelineReleaseLogs)\n\t}\n\n\t\/\/ iap protected endpoints\n\tiapAuthorizedRoutes := gzippedRoutes.Group(\"\/\", authMiddleware.MiddlewareFunc())\n\t{\n\t\tiapAuthorizedRoutes.POST(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\", estafetteAPIHandler.CreatePipelineBuild)\n\t\tiapAuthorizedRoutes.POST(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\", estafetteAPIHandler.CreatePipelineRelease)\n\t\tiapAuthorizedRoutes.DELETE(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\/:revisionOrId\", estafetteAPIHandler.CancelPipelineBuild)\n\t\tiapAuthorizedRoutes.DELETE(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\/:id\", estafetteAPIHandler.CancelPipelineRelease)\n\t\tiapAuthorizedRoutes.GET(\"\/api\/users\/me\", estafetteAPIHandler.GetLoggedInUser)\n\t\tiapAuthorizedRoutes.GET(\"\/api\/config\", estafetteAPIHandler.GetConfig)\n\t\tiapAuthorizedRoutes.GET(\"\/api\/config\/credentials\", estafetteAPIHandler.GetConfigCredentials)\n\t\tiapAuthorizedRoutes.GET(\"\/api\/config\/trustedimages\", estafetteAPIHandler.GetConfigTrustedImages)\n\t\tiapAuthorizedRoutes.GET(\"\/api\/update-computed-tables\", estafetteAPIHandler.UpdateComputedTables)\n\t}\n\n\trouter.NoRoute(func(c *gin.Context) {\n\t\tc.AbortWithStatusJSON(http.StatusNotFound, gin.H{\"code\": http.StatusText(http.StatusNotFound), \"message\": \"Page not found\"})\n\t})\n\n\t\/\/ instantiate servers instead of using router.Run in order to handle graceful shutdown\n\tsrv := &http.Server{\n\t\tAddr:        *apiAddress,\n\t\tHandler:     router,\n\t\tReadTimeout: 30 * time.Second,\n\t\t\/\/WriteTimeout:   30 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\n\tgo func() {\n\t\tif err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\tlog.Fatal().Err(err).Msg(\"Starting gin router failed\")\n\t\t}\n\t}()\n\n\treturn srv\n}\n<commit_msg>use GET for \/api\/labels\/frequent<commit_after>package main\n\nimport (\n\t\"context\"\n\tstdlog \"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/alecthomas\/kingpin\"\n\t\"github.com\/estafette\/estafette-ci-api\/auth\"\n\t\"github.com\/estafette\/estafette-ci-api\/bitbucket\"\n\t\"github.com\/estafette\/estafette-ci-api\/cockroach\"\n\t\"github.com\/estafette\/estafette-ci-api\/config\"\n\t\"github.com\/estafette\/estafette-ci-api\/estafette\"\n\t\"github.com\/estafette\/estafette-ci-api\/github\"\n\t\"github.com\/estafette\/estafette-ci-api\/slack\"\n\tcrypt \"github.com\/estafette\/estafette-ci-crypt\"\n\t\"github.com\/gin-contrib\/gzip\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\/promhttp\"\n\t\"github.com\/rs\/zerolog\"\n\t\"github.com\/rs\/zerolog\/log\"\n)\n\nvar (\n\tversion   string\n\tbranch    string\n\trevision  string\n\tbuildDate string\n\tgoVersion = runtime.Version()\n)\n\nvar (\n\t\/\/ flags\n\tprometheusMetricsAddress     = kingpin.Flag(\"metrics-listen-address\", \"The address to listen on for Prometheus metrics requests.\").Default(\":9001\").String()\n\tprometheusMetricsPath        = kingpin.Flag(\"metrics-path\", \"The path to listen for Prometheus metrics requests.\").Default(\"\/metrics\").String()\n\tapiAddress                   = kingpin.Flag(\"api-listen-address\", \"The address to listen on for api HTTP requests.\").Default(\":5000\").String()\n\tconfigFilePath               = kingpin.Flag(\"config-file-path\", \"The path to yaml config file configuring this application.\").Default(\"\/configs\/config.yaml\").String()\n\tsecretDecryptionKey          = kingpin.Flag(\"secret-decryption-key\", \"The AES-256 key used to decrypt secrets that have been encrypted with it.\").Envar(\"SECRET_DECRYPTION_KEY\").String()\n\tgracefulShutdownDelaySeconds = kingpin.Flag(\"graceful-shutdown-delay-seconds\", \"The number of seconds to wait with graceful shutdown in order to let endpoints update propagation finish.\").Default(\"15\").OverrideDefaultFromEnvar(\"GRACEFUL_SHUTDOWN_DELAY_SECONDS\").Int()\n\n\t\/\/ prometheusInboundEventTotals is the prometheus timeline serie that keeps track of inbound events\n\tprometheusInboundEventTotals = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tName: \"estafette_ci_api_inbound_event_totals\",\n\t\t\tHelp: \"Total of inbound events.\",\n\t\t},\n\t\t[]string{\"event\", \"source\"},\n\t)\n\n\t\/\/ prometheusOutboundAPICallTotals is the prometheus timeline serie that keeps track of outbound api calls\n\tprometheusOutboundAPICallTotals = prometheus.NewCounterVec(\n\t\tprometheus.CounterOpts{\n\t\t\tName: \"estafette_ci_api_outbound_api_call_totals\",\n\t\t\tHelp: \"Total of outgoing api calls.\",\n\t\t},\n\t\t[]string{\"target\"},\n\t)\n)\n\nfunc init() {\n\t\/\/ Metrics have to be registered to be exposed:\n\tprometheus.MustRegister(prometheusInboundEventTotals)\n\tprometheus.MustRegister(prometheusOutboundAPICallTotals)\n}\n\nfunc main() {\n\n\t\/\/ parse command line parameters\n\tkingpin.Parse()\n\n\t\/\/ configure json logging\n\tinitLogging()\n\n\t\/\/ define channels and waitgroup to gracefully shutdown the application\n\tsigs := make(chan os.Signal, 1)                                    \/\/ Create channel to receive OS signals\n\tstop := make(chan struct{})                                        \/\/ Create channel to receive stop signal\n\tsignal.Notify(sigs, os.Interrupt, syscall.SIGTERM, syscall.SIGINT) \/\/ Register the sigs channel to receieve SIGTERM\n\twg := &sync.WaitGroup{}                                            \/\/ Goroutines can add themselves to this to be waited on so that they finish\n\n\t\/\/ start prometheus\n\tgo startPrometheus()\n\n\t\/\/ handle api requests\n\tsrv := handleRequests(stop, wg)\n\n\t\/\/ wait for graceful shutdown to finish\n\t<-sigs \/\/ Wait for signals (this hangs until a signal arrives)\n\tlog.Info().Msgf(\"Shutting down in %v seconds...\", *gracefulShutdownDelaySeconds)\n\ttime.Sleep(time.Duration(*gracefulShutdownDelaySeconds) * 1000 * time.Millisecond)\n\n\t\/\/ shut down gracefully\n\tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n\tdefer cancel()\n\tif err := srv.Shutdown(ctx); err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Graceful server shutdown failed\")\n\t}\n\n\tlog.Debug().Msg(\"Stopping goroutines...\")\n\tclose(stop) \/\/ Tell goroutines to stop themselves\n\n\tlog.Debug().Msg(\"Awaiting waitgroup...\")\n\twg.Wait() \/\/ Wait for all to be stopped\n\n\tlog.Info().Msg(\"Server gracefully stopped\")\n}\n\nfunc startPrometheus() {\n\thttp.Handle(*prometheusMetricsPath, promhttp.Handler())\n\n\tif err := http.ListenAndServe(*prometheusMetricsAddress, nil); err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Starting Prometheus listener failed\")\n\t}\n}\n\nfunc initLogging() {\n\n\t\/\/ log as severity for stackdriver logging to recognize the level\n\tzerolog.LevelFieldName = \"severity\"\n\n\t\/\/ set some default fields added to all logs\n\tlog.Logger = zerolog.New(os.Stdout).With().\n\t\tTimestamp().\n\t\tStr(\"app\", \"estafette-ci-api\").\n\t\tStr(\"version\", version).\n\t\tLogger()\n\n\t\/\/ use zerolog for any logs sent via standard log library\n\tstdlog.SetFlags(0)\n\tstdlog.SetOutput(log.Logger)\n\n\t\/\/ log startup message\n\tlog.Info().\n\t\tStr(\"branch\", branch).\n\t\tStr(\"revision\", revision).\n\t\tStr(\"buildDate\", buildDate).\n\t\tStr(\"goVersion\", goVersion).\n\t\tMsg(\"Starting estafette-ci-api...\")\n}\n\nfunc createRouter() *gin.Engine {\n\n\t\/\/ run gin in release mode and other defaults\n\tgin.SetMode(gin.ReleaseMode)\n\tgin.DefaultWriter = log.Logger\n\tgin.DisableConsoleColor()\n\n\t\/\/ Creates a router without any middleware by default\n\trouter := gin.New()\n\n\t\/\/ Recovery middleware recovers from any panics and writes a 500 if there was one.\n\trouter.Use(gin.Recovery())\n\n\t\/\/ access logs with zerolog\n\trouter.Use(ZeroLogMiddleware())\n\n\t\/\/ liveness and readiness\n\trouter.GET(\"\/liveness\", func(c *gin.Context) {\n\t\tc.String(200, \"I'm alive!\")\n\t})\n\trouter.GET(\"\/readiness\", func(c *gin.Context) {\n\t\tc.String(200, \"I'm ready!\")\n\t})\n\n\treturn router\n}\n\nfunc handleRequests(stopChannel <-chan struct{}, waitGroup *sync.WaitGroup) *http.Server {\n\n\tsecretHelper := crypt.NewSecretHelper(*secretDecryptionKey)\n\tconfigReader := config.NewConfigReader(secretHelper)\n\n\tconfig, err := configReader.ReadConfigFromFile(*configFilePath, true)\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Failed reading configuration\")\n\t}\n\n\tencryptedConfig, err := configReader.ReadConfigFromFile(*configFilePath, false)\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Failed reading configuration without decrypting\")\n\t}\n\n\tgithubAPIClient := github.NewGithubAPIClient(*config.Integrations.Github, prometheusOutboundAPICallTotals)\n\tbitbucketAPIClient := bitbucket.NewBitbucketAPIClient(*config.Integrations.Bitbucket, prometheusOutboundAPICallTotals)\n\tslackAPIClient := slack.NewSlackAPIClient(*config.Integrations.Slack, prometheusOutboundAPICallTotals)\n\tcockroachDBClient := cockroach.NewCockroachDBClient(*config.Database, prometheusOutboundAPICallTotals)\n\tciBuilderClient, err := estafette.NewCiBuilderClient(*config, *encryptedConfig, *secretDecryptionKey, prometheusOutboundAPICallTotals)\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Creating new CiBuilderClient has failed\")\n\t}\n\n\t\/\/ set up database\n\terr = cockroachDBClient.Connect()\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(\"Failed connecting to CockroachDB\")\n\t}\n\n\t\/\/ create and init router\n\trouter := createRouter()\n\n\t\/\/ Gzip and logging middleware\n\tgzippedRoutes := router.Group(\"\/\", gzip.Gzip(gzip.DefaultCompression))\n\n\t\/\/ middleware to handle auth for different endpoints\n\tauthMiddleware := auth.NewAuthMiddleware(*config.Auth)\n\n\testafetteBuildService := estafette.NewBuildService(cockroachDBClient, ciBuilderClient, githubAPIClient.JobVarsFunc(), bitbucketAPIClient.JobVarsFunc())\n\n\tgithubEventHandler := github.NewGithubEventHandler(githubAPIClient, estafetteBuildService, *config.Integrations.Github, prometheusInboundEventTotals)\n\tgzippedRoutes.POST(\"\/api\/integrations\/github\/events\", githubEventHandler.Handle)\n\n\tbitbucketEventHandler := bitbucket.NewBitbucketEventHandler(bitbucketAPIClient, estafetteBuildService, prometheusInboundEventTotals)\n\tgzippedRoutes.POST(\"\/api\/integrations\/bitbucket\/events\", bitbucketEventHandler.Handle)\n\n\tslackEventHandler := slack.NewSlackEventHandler(secretHelper, *config.Integrations.Slack, slackAPIClient, cockroachDBClient, *config.APIServer, estafetteBuildService, githubAPIClient.JobVarsFunc(), bitbucketAPIClient.JobVarsFunc(), prometheusInboundEventTotals)\n\tgzippedRoutes.POST(\"\/api\/integrations\/slack\/slash\", slackEventHandler.Handle)\n\n\testafetteEventHandler := estafette.NewEstafetteEventHandler(*config.APIServer, ciBuilderClient, cockroachDBClient, prometheusInboundEventTotals)\n\twarningHelper := estafette.NewWarningHelper()\n\n\testafetteAPIHandler := estafette.NewAPIHandler(*configFilePath, *config.APIServer, *config.Auth, *encryptedConfig, cockroachDBClient, ciBuilderClient, estafetteBuildService, warningHelper, secretHelper, githubAPIClient.JobVarsFunc(), bitbucketAPIClient.JobVarsFunc())\n\tgzippedRoutes.GET(\"\/api\/pipelines\", estafetteAPIHandler.GetPipelines)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\", estafetteAPIHandler.GetPipeline)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\", estafetteAPIHandler.GetPipelineBuilds)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\/:revisionOrId\", estafetteAPIHandler.GetPipelineBuild)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\/:revisionOrId\/logs\", estafetteAPIHandler.GetPipelineBuildLogs)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\/:revisionOrId\/warnings\", estafetteAPIHandler.GetPipelineBuildWarnings)\n\trouter.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\/:revisionOrId\/logs\/tail\", estafetteAPIHandler.TailPipelineBuildLogs)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\", estafetteAPIHandler.GetPipelineReleases)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\/:id\", estafetteAPIHandler.GetPipelineRelease)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\/:id\/logs\", estafetteAPIHandler.GetPipelineReleaseLogs)\n\trouter.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\/:id\/logs\/tail\", estafetteAPIHandler.TailPipelineReleaseLogs)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/stats\/buildsdurations\", estafetteAPIHandler.GetPipelineStatsBuildsDurations)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/stats\/releasesdurations\", estafetteAPIHandler.GetPipelineStatsReleasesDurations)\n\tgzippedRoutes.GET(\"\/api\/pipelines\/:source\/:owner\/:repo\/warnings\", estafetteAPIHandler.GetPipelineWarnings)\n\tgzippedRoutes.GET(\"\/api\/stats\/pipelinescount\", estafetteAPIHandler.GetStatsPipelinesCount)\n\tgzippedRoutes.GET(\"\/api\/stats\/buildscount\", estafetteAPIHandler.GetStatsBuildsCount)\n\tgzippedRoutes.GET(\"\/api\/stats\/releasescount\", estafetteAPIHandler.GetStatsReleasesCount)\n\tgzippedRoutes.GET(\"\/api\/stats\/buildsduration\", estafetteAPIHandler.GetStatsBuildsDuration)\n\tgzippedRoutes.GET(\"\/api\/stats\/buildsadoption\", estafetteAPIHandler.GetStatsBuildsAdoption)\n\tgzippedRoutes.GET(\"\/api\/stats\/releasesadoption\", estafetteAPIHandler.GetStatsReleasesAdoption)\n\tgzippedRoutes.GET(\"\/api\/stats\/mostbuilds\", estafetteAPIHandler.GetStatsMostBuilds)\n\tgzippedRoutes.GET(\"\/api\/stats\/mostreleases\", estafetteAPIHandler.GetStatsMostReleases)\n\tgzippedRoutes.GET(\"\/api\/manifest\/templates\", estafetteAPIHandler.GetManifestTemplates)\n\tgzippedRoutes.POST(\"\/api\/manifest\/generate\", estafetteAPIHandler.GenerateManifest)\n\tgzippedRoutes.POST(\"\/api\/manifest\/validate\", estafetteAPIHandler.ValidateManifest)\n\tgzippedRoutes.POST(\"\/api\/manifest\/encrypt\", estafetteAPIHandler.EncryptSecret)\n\tgzippedRoutes.GET(\"\/api\/labels\/frequent\", estafetteAPIHandler.GetFrequentLabels)\n\n\t\/\/ api key protected endpoints\n\tapiKeyAuthorizedRoutes := gzippedRoutes.Group(\"\/\", authMiddleware.APIKeyMiddlewareFunc())\n\t{\n\t\tapiKeyAuthorizedRoutes.POST(\"\/api\/commands\", estafetteEventHandler.Handle)\n\t\tapiKeyAuthorizedRoutes.POST(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\/:revisionOrId\/logs\", estafetteAPIHandler.PostPipelineBuildLogs)\n\t\tapiKeyAuthorizedRoutes.POST(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\/:id\/logs\", estafetteAPIHandler.PostPipelineReleaseLogs)\n\t}\n\n\t\/\/ iap protected endpoints\n\tiapAuthorizedRoutes := gzippedRoutes.Group(\"\/\", authMiddleware.MiddlewareFunc())\n\t{\n\t\tiapAuthorizedRoutes.POST(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\", estafetteAPIHandler.CreatePipelineBuild)\n\t\tiapAuthorizedRoutes.POST(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\", estafetteAPIHandler.CreatePipelineRelease)\n\t\tiapAuthorizedRoutes.DELETE(\"\/api\/pipelines\/:source\/:owner\/:repo\/builds\/:revisionOrId\", estafetteAPIHandler.CancelPipelineBuild)\n\t\tiapAuthorizedRoutes.DELETE(\"\/api\/pipelines\/:source\/:owner\/:repo\/releases\/:id\", estafetteAPIHandler.CancelPipelineRelease)\n\t\tiapAuthorizedRoutes.GET(\"\/api\/users\/me\", estafetteAPIHandler.GetLoggedInUser)\n\t\tiapAuthorizedRoutes.GET(\"\/api\/config\", estafetteAPIHandler.GetConfig)\n\t\tiapAuthorizedRoutes.GET(\"\/api\/config\/credentials\", estafetteAPIHandler.GetConfigCredentials)\n\t\tiapAuthorizedRoutes.GET(\"\/api\/config\/trustedimages\", estafetteAPIHandler.GetConfigTrustedImages)\n\t\tiapAuthorizedRoutes.GET(\"\/api\/update-computed-tables\", estafetteAPIHandler.UpdateComputedTables)\n\t}\n\n\trouter.NoRoute(func(c *gin.Context) {\n\t\tc.AbortWithStatusJSON(http.StatusNotFound, gin.H{\"code\": http.StatusText(http.StatusNotFound), \"message\": \"Page not found\"})\n\t})\n\n\t\/\/ instantiate servers instead of using router.Run in order to handle graceful shutdown\n\tsrv := &http.Server{\n\t\tAddr:        *apiAddress,\n\t\tHandler:     router,\n\t\tReadTimeout: 30 * time.Second,\n\t\t\/\/WriteTimeout:   30 * time.Second,\n\t\tMaxHeaderBytes: 1 << 20,\n\t}\n\n\tgo func() {\n\t\tif err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n\t\t\tlog.Fatal().Err(err).Msg(\"Starting gin router failed\")\n\t\t}\n\t}()\n\n\treturn srv\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/m4rw3r\/uuid\"\n\t\"net\/http\"\n\t\/\/\"fmt\"\n\n\t\"github.com\/zenazn\/goji\"\n\t\"github.com\/zenazn\/goji\/web\"\n\n\t\"github.com\/ckpt\/backend-services\/players\"\n)\n\ntype appError struct {\n\tError   error\n\tMessage string\n\tCode    int\n}\n\ntype appHandler func(web.C, http.ResponseWriter, *http.Request) *appError\n\nvar currentuser string\n\nfunc (fn appHandler) ServeHTTPC(c web.C, w http.ResponseWriter, r *http.Request) {\n\tif e := fn(c, w, r); e != nil {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\t\tw.WriteHeader(e.Code)\n\t\tencoder := json.NewEncoder(w)\n\t\tencoder.Encode(map[string]string{\"error\": e.Error.Error() +\n\t\t\t\" (\" + e.Message + \")\"})\n\t}\n}\n\nfunc listAllPlayers(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tplayerlist, err := players.AllPlayers()\n\tif err != nil {\n\t\treturn &appError{err, \"Cant load players\", 500}\n\t}\n\tencoder := json.NewEncoder(w)\n\tencoder.Encode(playerlist)\n\treturn nil\n}\n\nfunc getAllPlayerQuotes(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tplayerlist, err := players.AllPlayers()\n\tif err != nil {\n\t\treturn &appError{err, \"Cant load players\", 500}\n\t}\n\tquotes := make(map[string][]string)\n\tfor _, player := range playerlist {\n\t\tpq := player.Quotes\n\t\tif len(pq) > 0 {\n\t\t\tquotes[player.UUID.String()] = append(quotes[player.UUID.String()], pq...)\n\t\t}\n\t}\n\tencoder := json.NewEncoder(w)\n\tencoder.Encode(quotes)\n\treturn nil\n}\n\nfunc getPlayer(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tuuid, err := uuid.FromString(c.URLParams[\"uuid\"])\n\tplayer, err := players.PlayerByUUID(uuid)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find player\", 404}\n\t}\n\tencoder := json.NewEncoder(w)\n\tencoder.Encode(player)\n\treturn nil\n}\n\nfunc getPlayerProfile(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tuuid, err := uuid.FromString(c.URLParams[\"uuid\"])\n\tplayer, err := players.PlayerByUUID(uuid)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find player\", 404}\n\t}\n\tencoder := json.NewEncoder(w)\n\tencoder.Encode(player.Profile)\n\treturn nil\n}\n\nfunc updatePlayer(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tuuid, err := uuid.FromString(c.URLParams[\"uuid\"])\n\tplayer, err := players.PlayerByUUID(uuid)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find player\", 404}\n\t}\n\ttempPlayer := new(players.Player)\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(tempPlayer); err != nil {\n\t\treturn &appError{err, \"Invalid JSON\", 400}\n\t}\n\n\tif err := player.SetActive(tempPlayer.Active); err != nil {\n\t\treturn &appError{err, \"Failed to set active status\", 500}\n\t}\n\tif err := player.SetNick(tempPlayer.Nick); err != nil {\n\t\treturn &appError{err, \"Failed to set nick\", 500}\n\t}\n\tif err := player.SetProfile(tempPlayer.Profile); err != nil {\n\t\treturn &appError{err, \"Failed to set player profile\", 500}\n\t}\n\tw.WriteHeader(204)\n\treturn nil\n}\n\nfunc updatePlayerProfile(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tuuid, err := uuid.FromString(c.URLParams[\"uuid\"])\n\tplayer, err := players.PlayerByUUID(uuid)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find player\", 404}\n\t}\n\ttempProfile := new(players.Profile)\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(tempProfile); err != nil {\n\t\treturn &appError{err, \"Invalid JSON\", 400}\n\t}\n\n\tif err := player.SetProfile(*tempProfile); err != nil {\n\t\treturn &appError{err, \"Failed to set player profile\", 500}\n\t}\n\tw.WriteHeader(204)\n\treturn nil\n}\n\nfunc createNewPlayer(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tnPlayer := new(players.Player)\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(nPlayer); err != nil {\n\t\treturn &appError{err, \"Invalid JSON\", 400}\n\t}\n\tnPlayer, err := players.NewPlayer(nPlayer.Nick, nPlayer.Profile)\n\tif err != nil {\n\t\treturn &appError{err, \"Failed to create new player\", 500}\n\t}\n\tw.Header().Set(\"Location\", \"\/players\/\"+nPlayer.UUID.String())\n\tw.WriteHeader(201)\n\treturn nil\n}\n\nfunc createNewUser(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\ttype newUser struct {\n\t\tPlayer uuid.UUID `json:\"player\"`\n\t\tplayers.User\n\t}\n\tnUser := new(newUser)\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(nUser); err != nil {\n\t\treturn &appError{err, \"Invalid JSON\", 400}\n\t}\n\t_, err := players.NewUser(nUser.Player, &nUser.User)\n\tif err != nil {\n\t\treturn &appError{err, \"Failed to create new user\", 500}\n\t}\n\tw.Header().Set(\"Location\", \"\/players\/\"+nUser.Player.String()+\"\/user\")\n\tw.WriteHeader(201)\n\treturn nil\n}\n\nfunc getUserForPlayer(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tuuid, err := uuid.FromString(c.URLParams[\"uuid\"])\n\tplayer, err := players.PlayerByUUID(uuid)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find player\", 404}\n\t}\n\tencoder := json.NewEncoder(w)\n\tencoder.Encode(player.User)\n\treturn nil\n}\n\nfunc setUserForPlayer(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tuuid, err := uuid.FromString(c.URLParams[\"uuid\"])\n\tplayer, err := players.PlayerByUUID(uuid)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find player\", 404}\n\t}\n\ttempUser := new(players.User)\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(tempUser); err != nil {\n\t\treturn &appError{err, \"Invalid JSON\", 400}\n\t}\n\tuser, err := players.UserByName(tempUser.Username)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find user\", 400}\n\t}\n\n\tif err := player.SetUser(*user); err != nil {\n\t\treturn &appError{err, \"Failed to set user for player\", 500}\n\t}\n\tw.WriteHeader(204)\n\treturn nil\n}\n\nfunc main() {\n\t\/\/fmt.Printf(\"%+v\\n\", getMembers())\n\tcurrentuser = \"mortenk\"\n\tgoji.Get(\"\/players\", appHandler(listAllPlayers))\n\tgoji.Post(\"\/players\", appHandler(createNewPlayer))\n\tgoji.Get(\"\/players\/quotes\", appHandler(getAllPlayerQuotes))\n\tgoji.Get(\"\/players\/:uuid\", appHandler(getPlayer))\n\tgoji.Put(\"\/players\/:uuid\", appHandler(updatePlayer))\n\tgoji.Get(\"\/players\/:uuid\/profile\", appHandler(getPlayerProfile))\n\tgoji.Put(\"\/players\/:uuid\/profile\", appHandler(updatePlayerProfile))\n\tgoji.Get(\"\/players\/:uuid\/user\", appHandler(getUserForPlayer))\n\tgoji.Put(\"\/players\/:uuid\/user\", appHandler(setUserForPlayer))\n\n\tgoji.Post(\"\/users\", appHandler(createNewUser))\n\tgoji.Serve()\n}\n<commit_msg>Add login endpoint and proper cors support.<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/m4rw3r\/uuid\"\n\t\"net\/http\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/rs\/cors\"\n\t\"github.com\/zenazn\/goji\"\n\t\"github.com\/zenazn\/goji\/web\"\n\n\t\"github.com\/ckpt\/backend-services\/players\"\n)\n\ntype appError struct {\n\tError   error\n\tMessage string\n\tCode    int\n}\n\ntype appHandler func(web.C, http.ResponseWriter, *http.Request) *appError\n\nvar currentuser string\n\nfunc (fn appHandler) ServeHTTPC(c web.C, w http.ResponseWriter, r *http.Request) {\n\tif e := fn(c, w, r); e != nil {\n\t\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\t\tw.WriteHeader(e.Code)\n\t\tencoder := json.NewEncoder(w)\n\t\tencoder.Encode(map[string]string{\"error\": e.Error.Error() +\n\t\t\t\" (\" + e.Message + \")\"})\n\t}\n}\n\nfunc listAllPlayers(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tplayerlist, err := players.AllPlayers()\n\tif err != nil {\n\t\treturn &appError{err, \"Cant load players\", 500}\n\t}\n\tencoder := json.NewEncoder(w)\n\tencoder.Encode(playerlist)\n\treturn nil\n}\n\nfunc getAllPlayerQuotes(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tplayerlist, err := players.AllPlayers()\n\tif err != nil {\n\t\treturn &appError{err, \"Cant load players\", 500}\n\t}\n\tquotes := make(map[string][]string)\n\tfor _, player := range playerlist {\n\t\tpq := player.Quotes\n\t\tif len(pq) > 0 {\n\t\t\tquotes[player.UUID.String()] = append(quotes[player.UUID.String()], pq...)\n\t\t}\n\t}\n\tencoder := json.NewEncoder(w)\n\tencoder.Encode(quotes)\n\treturn nil\n}\n\nfunc getPlayer(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tuuid, err := uuid.FromString(c.URLParams[\"uuid\"])\n\tplayer, err := players.PlayerByUUID(uuid)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find player\", 404}\n\t}\n\tencoder := json.NewEncoder(w)\n\tencoder.Encode(player)\n\treturn nil\n}\n\nfunc getPlayerProfile(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tuuid, err := uuid.FromString(c.URLParams[\"uuid\"])\n\tplayer, err := players.PlayerByUUID(uuid)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find player\", 404}\n\t}\n\tencoder := json.NewEncoder(w)\n\tencoder.Encode(player.Profile)\n\treturn nil\n}\n\nfunc updatePlayer(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tuuid, err := uuid.FromString(c.URLParams[\"uuid\"])\n\tplayer, err := players.PlayerByUUID(uuid)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find player\", 404}\n\t}\n\ttempPlayer := new(players.Player)\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(tempPlayer); err != nil {\n\t\treturn &appError{err, \"Invalid JSON\", 400}\n\t}\n\n\tif err := player.SetActive(tempPlayer.Active); err != nil {\n\t\treturn &appError{err, \"Failed to set active status\", 500}\n\t}\n\tif err := player.SetNick(tempPlayer.Nick); err != nil {\n\t\treturn &appError{err, \"Failed to set nick\", 500}\n\t}\n\tif err := player.SetProfile(tempPlayer.Profile); err != nil {\n\t\treturn &appError{err, \"Failed to set player profile\", 500}\n\t}\n\tw.WriteHeader(204)\n\treturn nil\n}\n\nfunc updatePlayerProfile(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tuuid, err := uuid.FromString(c.URLParams[\"uuid\"])\n\tplayer, err := players.PlayerByUUID(uuid)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find player\", 404}\n\t}\n\ttempProfile := new(players.Profile)\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(tempProfile); err != nil {\n\t\treturn &appError{err, \"Invalid JSON\", 400}\n\t}\n\n\tif err := player.SetProfile(*tempProfile); err != nil {\n\t\treturn &appError{err, \"Failed to set player profile\", 500}\n\t}\n\tw.WriteHeader(204)\n\treturn nil\n}\n\nfunc createNewPlayer(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tnPlayer := new(players.Player)\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(nPlayer); err != nil {\n\t\treturn &appError{err, \"Invalid JSON\", 400}\n\t}\n\tnPlayer, err := players.NewPlayer(nPlayer.Nick, nPlayer.Profile)\n\tif err != nil {\n\t\treturn &appError{err, \"Failed to create new player\", 500}\n\t}\n\tw.Header().Set(\"Location\", \"\/players\/\"+nPlayer.UUID.String())\n\tw.WriteHeader(201)\n\treturn nil\n}\n\nfunc createNewUser(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\ttype newUser struct {\n\t\tPlayer uuid.UUID `json:\"player\"`\n\t\tplayers.User\n\t}\n\tnUser := new(newUser)\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(nUser); err != nil {\n\t\treturn &appError{err, \"Invalid JSON\", 400}\n\t}\n\t_, err := players.NewUser(nUser.Player, &nUser.User)\n\tif err != nil {\n\t\treturn &appError{err, \"Failed to create new user\", 500}\n\t}\n\tw.Header().Set(\"Location\", \"\/players\/\"+nUser.Player.String()+\"\/user\")\n\tw.WriteHeader(201)\n\treturn nil\n}\n\nfunc getUserForPlayer(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tuuid, err := uuid.FromString(c.URLParams[\"uuid\"])\n\tplayer, err := players.PlayerByUUID(uuid)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find player\", 404}\n\t}\n\tencoder := json.NewEncoder(w)\n\tencoder.Encode(player.User)\n\treturn nil\n}\n\nfunc setUserForPlayer(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tuuid, err := uuid.FromString(c.URLParams[\"uuid\"])\n\tplayer, err := players.PlayerByUUID(uuid)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find player\", 404}\n\t}\n\ttempUser := new(players.User)\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(tempUser); err != nil {\n\t\treturn &appError{err, \"Invalid JSON\", 400}\n\t}\n\tuser, err := players.UserByName(tempUser.Username)\n\tif err != nil {\n\t\treturn &appError{err, \"Cant find user\", 400}\n\t}\n\n\tif err := player.SetUser(*user); err != nil {\n\t\treturn &appError{err, \"Failed to set user for player\", 500}\n\t}\n\tw.WriteHeader(204)\n\treturn nil\n}\n\nfunc login(c web.C, w http.ResponseWriter, r *http.Request) *appError {\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\n\ttype LoginRequest struct {\n\t\tUsername string\n\t\tPassword string\n\t}\n\n\tloginReq := new(LoginRequest)\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(loginReq); err != nil {\n\t\treturn &appError{err, \"Invalid JSON\", 400}\n\t}\n\t\/\/ Hard code for now\n\tfmt.Printf(\"%+v\\n\", loginReq)\n\tif (loginReq.Username == \"mortenk\" &&\n\t\tloginReq.Password == \"testing123\") {\n\t\tauthUser, err := players.UserByName(loginReq.Username)\n\t\tif err != nil {\n\t\t\treturn &appError{err, \"Failed to fetch user data\", 500}\n\t\t}\n\t\tif authUser.Locked {\n\t\t\treturn &appError{errors.New(\"Locked\"), \"User locked\", 403}\n\t\t}\n\t\tencoder := json.NewEncoder(w)\n\t\tencoder.Encode(authUser)\n\t\treturn nil\n\t}\n\n\t\/\/ Else, forbidden\n\tw.WriteHeader(403)\n\treturn nil\n}\n\nfunc main() {\n\t\/\/fmt.Printf(\"%+v\\n\", getMembers())\n\tc := cors.New(cors.Options{\n\t\tAllowedOrigins: []string{\"*\"},\n\t})\n\tgoji.Use(c.Handler)\n\n\tgoji.Get(\"\/players\", appHandler(listAllPlayers))\n\tgoji.Post(\"\/players\", appHandler(createNewPlayer))\n\tgoji.Get(\"\/players\/quotes\", appHandler(getAllPlayerQuotes))\n\tgoji.Get(\"\/players\/:uuid\", appHandler(getPlayer))\n\tgoji.Put(\"\/players\/:uuid\", appHandler(updatePlayer))\n\tgoji.Get(\"\/players\/:uuid\/profile\", appHandler(getPlayerProfile))\n\tgoji.Put(\"\/players\/:uuid\/profile\", appHandler(updatePlayerProfile))\n\tgoji.Get(\"\/players\/:uuid\/user\", appHandler(getUserForPlayer))\n\tgoji.Put(\"\/players\/:uuid\/user\", appHandler(setUserForPlayer))\n\n\tgoji.Post(\"\/users\", appHandler(createNewUser))\n\n\tgoji.Post(\"\/login\", appHandler(login))\n\tgoji.Serve()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"github.com\/codeskyblue\/proxylocal\/pxlocal\"\n\t\"github.com\/qiniu\/log\"\n)\n\nfunc main() {\n\tvar serverMode bool\n\tvar serverAddr string\n\tvar proxyPort int\n\tvar proxyAddr string\n\tvar subDomain string\n\tvar domain string\n\tvar debug bool\n\n\tvar defaultServerAddr = os.Getenv(\"PXL_SERVER_ADDR\")\n\tif defaultServerAddr == \"\" {\n\t\tdefaultServerAddr = \"proxylocal.xyz\"\n\t}\n\tflag.BoolVar(&serverMode, \"server\", false, \"run in server mode\")\n\tflag.StringVar(&serverAddr, \"server-addr\", defaultServerAddr, \"server address\")\n\tflag.StringVar(&domain, \"server-domain\", \"\", \"proxy server domain name, optional\")\n\tflag.StringVar(&subDomain, \"subdomain\", \"\", \"proxy subdomain, used for http\")\n\tflag.BoolVar(&debug, \"debug\", false, \"open debug mode\")\n\tflag.IntVar(&proxyPort, \"port\", 0, \"proxy server listen port, used for tcp\")\n\n\tflag.Usage = func() {\n\t\tfmt.Printf(\"Usage: %s [OPTIONS] <port | host:port>\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\tflag.Parse()\n\tif !serverMode && len(flag.Args()) != 1 {\n\t\tflag.Usage()\n\t\treturn\n\t}\n\tif !debug {\n\t\tlog.SetOutputLevel(log.Linfo)\n\t} else {\n\t\tlog.SetOutputLevel(log.Ldebug)\n\t}\n\n\tif serverMode {\n\t\t_, port, _ := net.SplitHostPort(serverAddr)\n\t\tif port == \"\" {\n\t\t\tport = \"80\"\n\t\t}\n\t\taddr := net.JoinHostPort(\"0.0.0.0\", port)\n\t\tif domain == \"\" {\n\t\t\tdomain = serverAddr\n\t\t}\n\t\tfmt.Println(\"proxylocal: server listen on\", addr)\n\t\tps := pxlocal.NewProxyServer(domain)\n\t\tlog.Fatal(http.ListenAndServe(addr, ps))\n\t}\n\n\tproxyAddr = flag.Arg(0)\n\tif !regexp.MustCompile(\"^(http|https|tcp):\/\/\").MatchString(proxyAddr) {\n\t\tif _, err := strconv.Atoi(proxyAddr); err == nil { \/\/ only contain port\n\t\t\tproxyAddr = \"localhost:\" + proxyAddr\n\t\t} else {\n\t\t\t\/\/proxyAddr += \":80\"\n\t\t}\n\t\tproxyAddr = \"http:\/\/\" + proxyAddr\n\t}\n\tpURL, err := url.Parse(proxyAddr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(\"proxy URL:\", pURL)\n\tpxlocal.StartAgent(pURL, subDomain, serverAddr, proxyPort)\n}\n<commit_msg>show version<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"github.com\/codeskyblue\/proxylocal\/pxlocal\"\n\t\"github.com\/qiniu\/log\"\n)\n\nconst (\n\tVERSION = \"0.1\"\n)\n\nfunc main() {\n\tvar serverMode bool\n\tvar serverAddr string\n\tvar proxyPort int\n\tvar proxyAddr string\n\tvar subDomain string\n\tvar domain string\n\tvar debug bool\n\n\tvar defaultServerAddr = os.Getenv(\"PXL_SERVER_ADDR\")\n\tif defaultServerAddr == \"\" {\n\t\tdefaultServerAddr = \"proxylocal.xyz\"\n\t}\n\tflag.BoolVar(&serverMode, \"server\", false, \"run in server mode\")\n\tflag.StringVar(&serverAddr, \"server-addr\", defaultServerAddr, \"server address\")\n\tflag.StringVar(&domain, \"server-domain\", \"\", \"proxy server domain name, optional\")\n\tflag.StringVar(&subDomain, \"subdomain\", \"\", \"proxy subdomain, used for http\")\n\tflag.BoolVar(&debug, \"debug\", false, \"open debug mode\")\n\tflag.IntVar(&proxyPort, \"port\", 0, \"proxy server listen port, used for tcp\")\n\n\tflag.Usage = func() {\n\t\tfmt.Printf(\"proxylocal version: %v\\nUsage: %s [OPTIONS] <port | host:port>\\n\", VERSION, os.Args[0])\n\t\tflag.PrintDefaults()\n\t}\n\tflag.Parse()\n\tif !serverMode && len(flag.Args()) != 1 {\n\t\tflag.Usage()\n\t\treturn\n\t}\n\tif !debug {\n\t\tlog.SetOutputLevel(log.Linfo)\n\t} else {\n\t\tlog.SetOutputLevel(log.Ldebug)\n\t}\n\n\tif serverMode {\n\t\t_, port, _ := net.SplitHostPort(serverAddr)\n\t\tif port == \"\" {\n\t\t\tport = \"80\"\n\t\t}\n\t\taddr := net.JoinHostPort(\"0.0.0.0\", port)\n\t\tif domain == \"\" {\n\t\t\tdomain = serverAddr\n\t\t}\n\t\tfmt.Println(\"proxylocal: server listen on\", addr)\n\t\tps := pxlocal.NewProxyServer(domain)\n\t\tlog.Fatal(http.ListenAndServe(addr, ps))\n\t}\n\n\tproxyAddr = flag.Arg(0)\n\tif !regexp.MustCompile(\"^(http|https|tcp):\/\/\").MatchString(proxyAddr) {\n\t\tif _, err := strconv.Atoi(proxyAddr); err == nil { \/\/ only contain port\n\t\t\tproxyAddr = \"localhost:\" + proxyAddr\n\t\t} else {\n\t\t\t\/\/proxyAddr += \":80\"\n\t\t}\n\t\tproxyAddr = \"http:\/\/\" + proxyAddr\n\t}\n\tpURL, err := url.Parse(proxyAddr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Println(\"proxy URL:\", pURL)\n\tpxlocal.StartAgent(pURL, subDomain, serverAddr, proxyPort)\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Command line interface<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Change the exit codes to something sensible<commit_after><|endoftext|>"}
{"text":"<commit_before>package shell\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"pfi\/sensorbee\/sensorbee\/client\"\n\t\"strings\"\n)\n\nconst (\n\ttopologiesHeader = \"\/topologies\"\n)\n\ntype currentTopologyState struct {\n\tname string\n}\n\nvar (\n\tcurrentTopology currentTopologyState\n)\n\n\/\/ NewBQLCommands return command list to execute BQL statement.\nfunc NewTopologiesCommands() []Command {\n\treturn []Command{\n\t\t&changeTopologyCmd{},\n\t\t&bqlCmd{},\n\t}\n}\n\ntype changeTopologyCmd struct {\n\tname string\n}\n\nfunc (ct *changeTopologyCmd) Init() error {\n\treturn nil\n}\n\nfunc (ct *changeTopologyCmd) Name() []string {\n\treturn []string{\"use\"}\n}\n\nfunc (ct *changeTopologyCmd) Input(input string) (cmdInputStatusType, error) {\n\tinput = strings.Trim(input, \" \")\n\tinputs := strings.Split(input, \" \")\n\tif len(inputs) == 1 {\n\t\treturn invalidCMD, fmt.Errorf(\"empty name is not supported\")\n\t}\n\tif len(inputs) >= 3 {\n\t\treturn invalidCMD, fmt.Errorf(\"name included spaces is not supported: %v\",\n\t\t\tstrings.Join(inputs[1:], \" \"))\n\t}\n\n\tct.name = inputs[1]\n\treturn preparedCMD, nil\n}\n\nfunc (ct *changeTopologyCmd) Eval(requester *client.Requester) {\n\tcurrentTopology.name = ct.name\n}\n\ntype bqlCmd struct {\n\tbuffer string\n}\n\n\/\/ Init BQL state.\nfunc (b *bqlCmd) Init() error {\n\treturn nil\n}\n\n\/\/ Name returns BQL start words.\nfunc (b *bqlCmd) Name() []string {\n\treturn []string{\"select\", \"create\", \"update\", \"insert\", \"pause\", \"resume\",\n\t\t\"rewind\", \"drop\", \"save\", \"load\"}\n}\n\nfunc (b *bqlCmd) Input(input string) (cmdInputStatusType, error) {\n\tif b.buffer == \"\" {\n\t\tb.buffer = input\n\t} else {\n\t\tb.buffer += \"\\n\" + input\n\t}\n\tif !strings.HasSuffix(input, \";\") {\n\t\treturn continuousCMD, nil\n\t}\n\n\treturn preparedCMD, nil\n}\n\n\/\/ Eval resolves input command to BQL statement\nfunc (b *bqlCmd) Eval(requester *client.Requester) {\n\t\/\/ flush buffer and get complete statement\n\tqueries := b.buffer\n\tb.buffer = \"\"\n\n\tfmt.Printf(\"BQL: %s\\n\", queries) \/\/ for debug, delete later\n\tsendBQLQueries(requester, queries)\n}\n\nfunc sendBQLQueries(requester *client.Requester, queries string) {\n\turi := topologiesHeader + \"\/\" + currentTopology.name + \"\/queries\"\n\tres, err := requester.Do(client.Post, uri, map[string]interface{}{\n\t\t\"queries\": queries,\n\t})\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"request failed: %v\\n\", err)\n\t\treturn\n\t}\n\tdefer res.Close()\n\n\tif res.IsError() {\n\t\t\/\/ TODO: provide error reporting utility\n\t\terrRes, err := res.Error()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ TODO: enhance error message\n\t\tfmt.Fprintf(os.Stderr, \"request failed: %v: %v: %v\\n\", errRes.Code, errRes.Message, errRes.Meta)\n\t\treturn\n\t}\n\n\tif res.IsStream() {\n\t\tshowStreamResponses(res)\n\t\treturn\n\t}\n\t\/\/ TODO: there isn't much information to show right now. Improve the server's response.\n}\n\nfunc showStreamResponses(res *client.Response) {\n\tch, err := res.ReadStreamJSON()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\treturn\n\t}\n\n\tsig := make(chan os.Signal)\n\tsignal.Notify(sig, os.Interrupt)\n\tdefer signal.Stop(sig)\n\n\tfor {\n\t\tselect {\n\t\tcase js, ok := <-ch:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdata, err := json.Marshal(js)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"cannot marshal a JSON: %v\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Printf(\"%s\\n\", data)\n\n\t\tcase <-sig:\n\t\t\treturn \/\/ The response is closed by the caller\n\t\t}\n\t}\n}\n<commit_msg>adapt client to work with EVAL statement and print result<commit_after>package shell\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"pfi\/sensorbee\/sensorbee\/client\"\n\t\"strings\"\n)\n\nconst (\n\ttopologiesHeader = \"\/topologies\"\n)\n\ntype currentTopologyState struct {\n\tname string\n}\n\nvar (\n\tcurrentTopology currentTopologyState\n)\n\n\/\/ NewBQLCommands return command list to execute BQL statement.\nfunc NewTopologiesCommands() []Command {\n\treturn []Command{\n\t\t&changeTopologyCmd{},\n\t\t&bqlCmd{},\n\t}\n}\n\ntype changeTopologyCmd struct {\n\tname string\n}\n\nfunc (ct *changeTopologyCmd) Init() error {\n\treturn nil\n}\n\nfunc (ct *changeTopologyCmd) Name() []string {\n\treturn []string{\"use\"}\n}\n\nfunc (ct *changeTopologyCmd) Input(input string) (cmdInputStatusType, error) {\n\tinput = strings.Trim(input, \" \")\n\tinputs := strings.Split(input, \" \")\n\tif len(inputs) == 1 {\n\t\treturn invalidCMD, fmt.Errorf(\"empty name is not supported\")\n\t}\n\tif len(inputs) >= 3 {\n\t\treturn invalidCMD, fmt.Errorf(\"name included spaces is not supported: %v\",\n\t\t\tstrings.Join(inputs[1:], \" \"))\n\t}\n\n\tct.name = inputs[1]\n\treturn preparedCMD, nil\n}\n\nfunc (ct *changeTopologyCmd) Eval(requester *client.Requester) {\n\tcurrentTopology.name = ct.name\n}\n\ntype bqlCmd struct {\n\tbuffer string\n}\n\n\/\/ Init BQL state.\nfunc (b *bqlCmd) Init() error {\n\treturn nil\n}\n\n\/\/ Name returns BQL start words.\nfunc (b *bqlCmd) Name() []string {\n\treturn []string{\"select\", \"create\", \"update\", \"insert\", \"pause\", \"resume\",\n\t\t\"rewind\", \"drop\", \"save\", \"load\", \"eval\"}\n}\n\nfunc (b *bqlCmd) Input(input string) (cmdInputStatusType, error) {\n\tif b.buffer == \"\" {\n\t\tb.buffer = input\n\t} else {\n\t\tb.buffer += \"\\n\" + input\n\t}\n\tif !strings.HasSuffix(input, \";\") {\n\t\treturn continuousCMD, nil\n\t}\n\n\treturn preparedCMD, nil\n}\n\n\/\/ Eval resolves input command to BQL statement\nfunc (b *bqlCmd) Eval(requester *client.Requester) {\n\t\/\/ flush buffer and get complete statement\n\tqueries := b.buffer\n\tb.buffer = \"\"\n\n\tfmt.Printf(\"BQL: %s\\n\", queries) \/\/ for debug, delete later\n\tsendBQLQueries(requester, queries)\n}\n\nfunc sendBQLQueries(requester *client.Requester, queries string) {\n\turi := topologiesHeader + \"\/\" + currentTopology.name + \"\/queries\"\n\tres, err := requester.Do(client.Post, uri, map[string]interface{}{\n\t\t\"queries\": queries,\n\t})\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"request failed: %v\\n\", err)\n\t\treturn\n\t}\n\tdefer res.Close()\n\n\tif res.IsError() {\n\t\t\/\/ TODO: provide error reporting utility\n\t\terrRes, err := res.Error()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ TODO: enhance error message\n\t\tfmt.Fprintf(os.Stderr, \"request failed: %v: %v: %v\\n\", errRes.Code, errRes.Message, errRes.Meta)\n\t\treturn\n\t}\n\n\tif res.IsStream() {\n\t\tshowStreamResponses(res)\n\t\treturn\n\t} else {\n\t\t\/\/ check if we have a JSON body that contains a \"result\" field;\n\t\t\/\/ if so, print it.\n\t\t\/\/ NB. We should also display some more status information that\n\t\t\/\/ is reported by most statements.\n\t\tvar data map[string]interface{}\n\t\terr := res.ReadJSON(&data)\n\t\tif err == nil {\n\t\t\tresult, ok := data[\"result\"]\n\t\t\tif ok {\n\t\t\t\tfmt.Println(result)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc showStreamResponses(res *client.Response) {\n\tch, err := res.ReadStreamJSON()\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\treturn\n\t}\n\n\tsig := make(chan os.Signal)\n\tsignal.Notify(sig, os.Interrupt)\n\tdefer signal.Stop(sig)\n\n\tfor {\n\t\tselect {\n\t\tcase js, ok := <-ch:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdata, err := json.Marshal(js)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(os.Stderr, \"cannot marshal a JSON: %v\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfmt.Printf(\"%s\\n\", data)\n\n\t\tcase <-sig:\n\t\t\treturn \/\/ The response is closed by the caller\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package diskv\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n)\n\nconst (\n\tdefaultFilePerm os.FileMode = 0666\n\tdefaultPathPerm os.FileMode = 0777\n)\n\n\/\/ A TransformFunc transforms a key into a slice of strings, with each\n\/\/ element in the slice representing a directory in the file path\n\/\/ where the key's entry will eventually be stored.\n\/\/\n\/\/ For example, if TransformFunc transforms \"abcdef\" to [\"ab\", \"cde\", \"f\"],\n\/\/ the final location of the data file will be <basedir>\/ab\/cde\/f\/abcdef\ntype TransformFunction func(s string) []string\n\n\/\/ TODO\ntype Index interface {\n\tInitialize(less LessFunction, keys <-chan string)\n\tInsert(key string)\n\tDelete(key string)\n\tKeys(from string, n int) <-chan string\n}\n\n\/\/ TODO\ntype LessFunction func(string, string) bool\n\n\/\/ TODO\ntype Options struct {\n\tBasePath     string\n\tTransform    TransformFunction\n\tCacheSizeMax uint64 \/\/ bytes\n\tPathPerm     os.FileMode\n\tFilePerm     os.FileMode\n\n\tIndex       Index\n\tIndexLess   LessFunction\n\tCompression io.ReadWriteCloser\n}\n\ntype Diskv struct {\n\tsync.RWMutex\n\tOptions\n\tcache     map[string][]byte\n\tcacheSize uint64\n}\n\n\/\/ New returns an initialized Diskv structure, ready to use.\n\/\/ If the path identified by baseDir already contains data,\n\/\/ it will be accessible, but not yet cached.\nfunc New(options Options) *Diskv {\n\tif options.PathPerm == 0 {\n\t\toptions.PathPerm = defaultPathPerm\n\t}\n\tif options.FilePerm == 0 {\n\t\toptions.FilePerm = defaultFilePerm\n\t}\n\n\td := &Diskv{\n\t\tOptions:   options,\n\t\tcache:     map[string][]byte{},\n\t\tcacheSize: 0,\n\t}\n\n\tif d.Index != nil && d.IndexLess != nil {\n\t\td.Index.Initialize(d.IndexLess, d.Keys())\n\t}\n\n\treturn d\n}\n\n\/\/ Write synchronously writes the key-value pair to disk,\n\/\/ making it immediately available for reads.\nfunc (d *Diskv) Write(key string, val []byte) error {\n\tif len(key) <= 0 {\n\t\treturn fmt.Errorf(\"empty key\")\n\t}\n\n\td.Lock()\n\tdefer d.Unlock()\n\tif err := d.ensurePath(key); err != nil {\n\t\treturn err\n\t}\n\n\tcompressedVal, err := d.compress(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC \/\/ overwrite if exists\n\tf, err := os.OpenFile(d.completeFilename(key), mode, d.FilePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tif _, err = f.Write(compressedVal); err != nil {\n\t\treturn err\n\t}\n\n\tif d.Index != nil {\n\t\td.Index.Insert(key)\n\t}\n\n\tdelete(d.cache, key) \/\/ cache only on read\n\treturn nil\n}\n\n\/\/ Read reads the key and returns the value.\n\/\/ If the key is available in the cache, Read won't touch the disk.\n\/\/ If the key is not in the cache, Read will have the side-effect of\n\/\/ lazily caching the value.\nfunc (d *Diskv) Read(key string) ([]byte, error) {\n\td.RLock()\n\tdefer d.RUnlock()\n\n\t\/\/ check cache first\n\tif val, ok := d.cache[key]; ok {\n\t\treturn d.decompress(val)\n\t}\n\n\t\/\/ read from disk\n\tval, err := ioutil.ReadFile(d.completeFilename(key))\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\t\/\/ cache lazily\n\tgo d.cacheWithoutLock(key, val)\n\n\t\/\/ return\n\treturn d.decompress(val)\n}\n\n\/\/ Erase synchronously erases the given key from the disk and the cache.\nfunc (d *Diskv) Erase(key string) error {\n\td.Lock()\n\tdefer d.Unlock()\n\n\t\/\/ erase from cache\n\tif val, ok := d.cache[key]; ok {\n\t\td.cacheSize -= uint64(len(val))\n\t\tdelete(d.cache, key)\n\t}\n\n\t\/\/ erase from index\n\tif d.Index != nil {\n\t\td.Index.Delete(key)\n\t}\n\n\t\/\/ erase from disk\n\tfilename := d.completeFilename(key)\n\tif s, err := os.Stat(filename); err == nil {\n\t\tif !!s.IsDir() {\n\t\t\treturn fmt.Errorf(\"bad key\")\n\t\t}\n\t\tif err = os.Remove(filename); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\treturn err\n\t}\n\n\t\/\/ clean up and return\n\td.pruneDirs(key)\n\treturn nil\n}\n\n\/\/ Flush will delete all of the data from the store, both\n\/\/ in the cache and on the disk. Note that Flush doesn't\n\/\/ distinguish diskv-related data from non-diskv-related data.\n\/\/ Care should be taken to always specify a diskv base directory\n\/\/ that is exclusively for diskv data.\nfunc (d *Diskv) Flush() error {\n\td.Lock()\n\tdefer d.Unlock()\n\td.cache = make(map[string][]byte)\n\td.cacheSize = 0\n\treturn os.RemoveAll(d.BasePath)\n}\n\n\/\/ Keys returns a channel that will yield every key\n\/\/ accessible by the store in undefined order.\nfunc (d *Diskv) Keys() <-chan string {\n\tc := make(chan string)\n\tgo func() {\n\t\tfilepath.Walk(d.BasePath, walker(c))\n\t\tclose(c)\n\t}()\n\treturn c\n}\n\n\/\/\n\/\/\n\/\/\n\nfunc (d *Diskv) compress(val []byte) ([]byte, error) {\n\tif d.Compression != nil {\n\t\treturn val, nil \/\/ TODO\n\t}\n\treturn val, nil\n}\n\nfunc (d *Diskv) decompress(val []byte) ([]byte, error) {\n\tif d.Compression != nil {\n\t\treturn val, nil \/\/ TODO\n\t}\n\treturn val, nil\n}\n\n\/\/ walker returns a function which satisfies the filepath.WalkFunc interface.\n\/\/ It sends every non-directory file entry down the channel c.\nfunc walker(c chan string) func(path string, info os.FileInfo, err error) error {\n\treturn func(path string, info os.FileInfo, err error) error {\n\t\tif err == nil && !info.IsDir() {\n\t\t\tc <- info.Name()\n\t\t}\n\t\treturn nil \/\/ \"pass\"\n\t}\n}\n\n\/\/ pathFor returns the absolute path for location on the filesystem\n\/\/ where the data for the given key will be stored.\nfunc (d *Diskv) pathFor(key string) string {\n\treturn fmt.Sprintf(\n\t\t\"%s%c%s\",\n\t\td.BasePath,\n\t\tos.PathSeparator,\n\t\tstrings.Join(d.Transform(key), string(os.PathSeparator)),\n\t)\n}\n\n\/\/ ensureDir is a helper function that generates all necessary\n\/\/ directories on the filesystem for the given key.\nfunc (d *Diskv) ensurePath(key string) error {\n\treturn os.MkdirAll(d.pathFor(key), d.PathPerm)\n}\n\n\/\/ completeFilename returns the absolute path to the file for the given key.\nfunc (d *Diskv) completeFilename(key string) string {\n\treturn fmt.Sprintf(\"%s%c%s\", d.pathFor(key), os.PathSeparator, key)\n}\n\n\/\/ cacheWithLock attempts to cache the given key-value pair in the\n\/\/ store's cache. It can fail if the value is larger than the cache's\n\/\/ maximum size.\nfunc (d *Diskv) cacheWithLock(key string, val []byte) error {\n\tvalueSize := uint64(len(val))\n\tif err := d.ensureCacheSpaceFor(valueSize); err != nil {\n\t\treturn fmt.Errorf(\"%s; not caching\", err)\n\t}\n\n\tif (d.cacheSize + valueSize) > d.CacheSizeMax {\n\t\tpanic(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"failed to make room for value (%d\/%d)\",\n\t\t\t\tvalueSize,\n\t\t\t\td.CacheSizeMax,\n\t\t\t),\n\t\t)\n\t}\n\n\td.cache[key] = val\n\td.cacheSize += valueSize\n\treturn nil\n}\n\n\/\/ cacheWithoutLock acquires the store's (write) mutex\n\/\/ and calls cacheWithLock.\nfunc (d *Diskv) cacheWithoutLock(key string, val []byte) error {\n\td.Lock()\n\tdefer d.Unlock()\n\treturn d.cacheWithLock(key, val)\n}\n\n\/\/ pruneDirs deletes empty directories in the path walk leading to the key k.\n\/\/ Typically this function is called after an Erase is made.\nfunc (d *Diskv) pruneDirs(key string) error {\n\tpathlist := d.Transform(key)\n\tfor i := range pathlist {\n\t\tpslice := pathlist[:len(pathlist)-i]\n\t\tdir := fmt.Sprintf(\n\t\t\t\"%s%c%s\",\n\t\t\td.BasePath,\n\t\t\tos.PathSeparator,\n\t\t\tstrings.Join(pslice, string(os.PathSeparator)),\n\t\t)\n\n\t\t\/\/ thanks to Steven Blenkinsop for this snippet\n\t\tswitch fi, err := os.Stat(dir); true {\n\t\tcase err != nil:\n\t\t\treturn err\n\t\tcase !fi.IsDir():\n\t\t\tpanic(fmt.Sprintf(\"corrupt dirstate at %s\", dir))\n\t\t}\n\n\t\tnlinks, err := filepath.Glob(fmt.Sprintf(\"%s%c*\", dir, os.PathSeparator))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if len(nlinks) > 0 {\n\t\t\treturn nil \/\/ has subdirs -- do not prune\n\t\t}\n\t\tif err = os.Remove(dir); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ ensureCacheSpaceFor deletes entries from the cache in arbitrary order\n\/\/ until the cache has at least valueSize bytes available.\nfunc (d *Diskv) ensureCacheSpaceFor(valueSize uint64) error {\n\tif valueSize > d.CacheSizeMax {\n\t\treturn fmt.Errorf(\n\t\t\t\"value size (%d bytes) too large for cache (%d bytes)\",\n\t\t\tvalueSize,\n\t\t\td.CacheSizeMax,\n\t\t)\n\t}\n\n\tsafe := func() bool { return (d.cacheSize + valueSize) <= d.CacheSizeMax }\n\tfor key, val := range d.cache {\n\t\tif safe() {\n\t\t\tbreak\n\t\t}\n\t\tdelete(d.cache, key)            \/\/ delete is safe, per spec\n\t\td.cacheSize -= uint64(len(val)) \/\/ len should return uint :|\n\t}\n\tif !safe() {\n\t\tpanic(fmt.Sprintf(\n\t\t\t\"%d bytes still won't fit in the cache! (max %d bytes)\",\n\t\t\tvalueSize,\n\t\t\td.CacheSizeMax,\n\t\t))\n\t}\n\n\treturn nil\n}\n<commit_msg>Small commentary + cleanup<commit_after>package diskv\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n)\n\nconst (\n\tdefaultBasePath             = \"diskv\"\n\tdefaultFilePerm os.FileMode = 0666\n\tdefaultPathPerm os.FileMode = 0777\n)\n\nvar (\n\tdefaultTransform = func(s string) []string { return []string{\"\"} }\n)\n\n\/\/ A TransformFunc transforms a key into a slice of strings, with each\n\/\/ element in the slice representing a directory in the file path\n\/\/ where the key's entry will eventually be stored.\n\/\/\n\/\/ For example, if TransformFunc transforms \"abcdef\" to [\"ab\", \"cde\", \"f\"],\n\/\/ the final location of the data file will be <basedir>\/ab\/cde\/f\/abcdef\ntype TransformFunction func(s string) []string\n\n\/\/ Index is a generic interface for things that can\n\/\/ provide an ordered list of keys.\ntype Index interface {\n\tInitialize(less LessFunction, keys <-chan string)\n\tInsert(key string)\n\tDelete(key string)\n\tKeys(from string, n int) <-chan string\n}\n\n\/\/ LessFunction is used to initialize an Index of keys in a specific order.\ntype LessFunction func(string, string) bool\n\n\/\/ Options define a set of properties that dictate Diskv behavior.\n\/\/ All values are optional.\ntype Options struct {\n\tBasePath     string\n\tTransform    TransformFunction\n\tCacheSizeMax uint64 \/\/ bytes\n\tPathPerm     os.FileMode\n\tFilePerm     os.FileMode\n\n\tIndex     Index\n\tIndexLess LessFunction\n\n\tCompression io.ReadWriteCloser\n}\n\n\/\/ Diskv implements the Diskv interface. You shouldn't construct Diskv\n\/\/ structures directly; instead, use the New constructor.\ntype Diskv struct {\n\tsync.RWMutex\n\tOptions\n\tcache     map[string][]byte\n\tcacheSize uint64\n}\n\n\/\/ New returns an initialized Diskv structure, ready to use.\n\/\/ If the path identified by baseDir already contains data,\n\/\/ it will be accessible, but not yet cached.\nfunc New(options Options) *Diskv {\n\tif options.BasePath == \"\" {\n\t\toptions.BasePath = defaultBasePath\n\t}\n\tif options.Transform == nil {\n\t\toptions.Transform = defaultTransform\n\t}\n\tif options.PathPerm == 0 {\n\t\toptions.PathPerm = defaultPathPerm\n\t}\n\tif options.FilePerm == 0 {\n\t\toptions.FilePerm = defaultFilePerm\n\t}\n\n\td := &Diskv{\n\t\tOptions:   options,\n\t\tcache:     map[string][]byte{},\n\t\tcacheSize: 0,\n\t}\n\n\tif d.Index != nil && d.IndexLess != nil {\n\t\td.Index.Initialize(d.IndexLess, d.Keys())\n\t}\n\n\treturn d\n}\n\n\/\/ Write synchronously writes the key-value pair to disk,\n\/\/ making it immediately available for reads.\nfunc (d *Diskv) Write(key string, val []byte) error {\n\tif len(key) <= 0 {\n\t\treturn fmt.Errorf(\"empty key\")\n\t}\n\n\td.Lock()\n\tdefer d.Unlock()\n\tif err := d.ensurePath(key); err != nil {\n\t\treturn err\n\t}\n\n\tcompressedVal, err := d.compress(val)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC \/\/ overwrite if exists\n\tf, err := os.OpenFile(d.completeFilename(key), mode, d.FilePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tif _, err = f.Write(compressedVal); err != nil {\n\t\treturn err\n\t}\n\n\tif d.Index != nil {\n\t\td.Index.Insert(key)\n\t}\n\n\tdelete(d.cache, key) \/\/ cache only on read\n\treturn nil\n}\n\n\/\/ Read reads the key and returns the value.\n\/\/ If the key is available in the cache, Read won't touch the disk.\n\/\/ If the key is not in the cache, Read will have the side-effect of\n\/\/ lazily caching the value.\nfunc (d *Diskv) Read(key string) ([]byte, error) {\n\td.RLock()\n\tdefer d.RUnlock()\n\n\t\/\/ check cache first\n\tif val, ok := d.cache[key]; ok {\n\t\treturn d.decompress(val)\n\t}\n\n\t\/\/ read from disk\n\tval, err := ioutil.ReadFile(d.completeFilename(key))\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\n\t\/\/ cache lazily\n\tgo d.cacheWithoutLock(key, val)\n\n\t\/\/ return\n\treturn d.decompress(val)\n}\n\n\/\/ Erase synchronously erases the given key from the disk and the cache.\nfunc (d *Diskv) Erase(key string) error {\n\td.Lock()\n\tdefer d.Unlock()\n\n\t\/\/ erase from cache\n\tif val, ok := d.cache[key]; ok {\n\t\td.cacheSize -= uint64(len(val))\n\t\tdelete(d.cache, key)\n\t}\n\n\t\/\/ erase from index\n\tif d.Index != nil {\n\t\td.Index.Delete(key)\n\t}\n\n\t\/\/ erase from disk\n\tfilename := d.completeFilename(key)\n\tif s, err := os.Stat(filename); err == nil {\n\t\tif !!s.IsDir() {\n\t\t\treturn fmt.Errorf(\"bad key\")\n\t\t}\n\t\tif err = os.Remove(filename); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\treturn err\n\t}\n\n\t\/\/ clean up and return\n\td.pruneDirs(key)\n\treturn nil\n}\n\n\/\/ Flush will delete all of the data from the store, both\n\/\/ in the cache and on the disk. Note that Flush doesn't\n\/\/ distinguish diskv-related data from non-diskv-related data.\n\/\/ Care should be taken to always specify a diskv base directory\n\/\/ that is exclusively for diskv data.\nfunc (d *Diskv) Flush() error {\n\td.Lock()\n\tdefer d.Unlock()\n\td.cache = make(map[string][]byte)\n\td.cacheSize = 0\n\treturn os.RemoveAll(d.BasePath)\n}\n\n\/\/ Keys returns a channel that will yield every key\n\/\/ accessible by the store in undefined order.\nfunc (d *Diskv) Keys() <-chan string {\n\tc := make(chan string)\n\tgo func() {\n\t\tfilepath.Walk(d.BasePath, walker(c))\n\t\tclose(c)\n\t}()\n\treturn c\n}\n\n\/\/\n\/\/\n\/\/\n\nfunc (d *Diskv) compress(val []byte) ([]byte, error) {\n\tif d.Compression != nil {\n\t\treturn val, nil \/\/ TODO\n\t}\n\treturn val, nil\n}\n\nfunc (d *Diskv) decompress(val []byte) ([]byte, error) {\n\tif d.Compression != nil {\n\t\treturn val, nil \/\/ TODO\n\t}\n\treturn val, nil\n}\n\n\/\/ walker returns a function which satisfies the filepath.WalkFunc interface.\n\/\/ It sends every non-directory file entry down the channel c.\nfunc walker(c chan string) func(path string, info os.FileInfo, err error) error {\n\treturn func(path string, info os.FileInfo, err error) error {\n\t\tif err == nil && !info.IsDir() {\n\t\t\tc <- info.Name()\n\t\t}\n\t\treturn nil \/\/ \"pass\"\n\t}\n}\n\n\/\/ pathFor returns the absolute path for location on the filesystem\n\/\/ where the data for the given key will be stored.\nfunc (d *Diskv) pathFor(key string) string {\n\treturn fmt.Sprintf(\n\t\t\"%s%c%s\",\n\t\td.BasePath,\n\t\tos.PathSeparator,\n\t\tstrings.Join(d.Transform(key), string(os.PathSeparator)),\n\t)\n}\n\n\/\/ ensureDir is a helper function that generates all necessary\n\/\/ directories on the filesystem for the given key.\nfunc (d *Diskv) ensurePath(key string) error {\n\treturn os.MkdirAll(d.pathFor(key), d.PathPerm)\n}\n\n\/\/ completeFilename returns the absolute path to the file for the given key.\nfunc (d *Diskv) completeFilename(key string) string {\n\treturn fmt.Sprintf(\"%s%c%s\", d.pathFor(key), os.PathSeparator, key)\n}\n\n\/\/ cacheWithLock attempts to cache the given key-value pair in the\n\/\/ store's cache. It can fail if the value is larger than the cache's\n\/\/ maximum size.\nfunc (d *Diskv) cacheWithLock(key string, val []byte) error {\n\tvalueSize := uint64(len(val))\n\tif err := d.ensureCacheSpaceFor(valueSize); err != nil {\n\t\treturn fmt.Errorf(\"%s; not caching\", err)\n\t}\n\n\tif (d.cacheSize + valueSize) > d.CacheSizeMax {\n\t\tpanic(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"failed to make room for value (%d\/%d)\",\n\t\t\t\tvalueSize,\n\t\t\t\td.CacheSizeMax,\n\t\t\t),\n\t\t)\n\t}\n\n\td.cache[key] = val\n\td.cacheSize += valueSize\n\treturn nil\n}\n\n\/\/ cacheWithoutLock acquires the store's (write) mutex\n\/\/ and calls cacheWithLock.\nfunc (d *Diskv) cacheWithoutLock(key string, val []byte) error {\n\td.Lock()\n\tdefer d.Unlock()\n\treturn d.cacheWithLock(key, val)\n}\n\n\/\/ pruneDirs deletes empty directories in the path walk leading to the key k.\n\/\/ Typically this function is called after an Erase is made.\nfunc (d *Diskv) pruneDirs(key string) error {\n\tpathlist := d.Transform(key)\n\tfor i := range pathlist {\n\t\tpslice := pathlist[:len(pathlist)-i]\n\t\tdir := fmt.Sprintf(\n\t\t\t\"%s%c%s\",\n\t\t\td.BasePath,\n\t\t\tos.PathSeparator,\n\t\t\tstrings.Join(pslice, string(os.PathSeparator)),\n\t\t)\n\n\t\t\/\/ thanks to Steven Blenkinsop for this snippet\n\t\tswitch fi, err := os.Stat(dir); true {\n\t\tcase err != nil:\n\t\t\treturn err\n\t\tcase !fi.IsDir():\n\t\t\tpanic(fmt.Sprintf(\"corrupt dirstate at %s\", dir))\n\t\t}\n\n\t\tnlinks, err := filepath.Glob(fmt.Sprintf(\"%s%c*\", dir, os.PathSeparator))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if len(nlinks) > 0 {\n\t\t\treturn nil \/\/ has subdirs -- do not prune\n\t\t}\n\t\tif err = os.Remove(dir); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ ensureCacheSpaceFor deletes entries from the cache in arbitrary order\n\/\/ until the cache has at least valueSize bytes available.\nfunc (d *Diskv) ensureCacheSpaceFor(valueSize uint64) error {\n\tif valueSize > d.CacheSizeMax {\n\t\treturn fmt.Errorf(\n\t\t\t\"value size (%d bytes) too large for cache (%d bytes)\",\n\t\t\tvalueSize,\n\t\t\td.CacheSizeMax,\n\t\t)\n\t}\n\n\tsafe := func() bool { return (d.cacheSize + valueSize) <= d.CacheSizeMax }\n\tfor key, val := range d.cache {\n\t\tif safe() {\n\t\t\tbreak\n\t\t}\n\t\tdelete(d.cache, key)            \/\/ delete is safe, per spec\n\t\td.cacheSize -= uint64(len(val)) \/\/ len should return uint :|\n\t}\n\tif !safe() {\n\t\tpanic(fmt.Sprintf(\n\t\t\t\"%d bytes still won't fit in the cache! (max %d bytes)\",\n\t\t\tvalueSize,\n\t\t\td.CacheSizeMax,\n\t\t))\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package grift\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar CommandName = \"grift\"\nvar griftList = map[string]Grift{}\nvar descriptions = map[string]string{}\nvar lock = &sync.Mutex{}\nvar namespace string\n\ntype Grift func(c *Context) error\n\n\/\/ Namespace will place all tasks within the given prefix.\nfunc Namespace(name string, s func()) error {\n\tdefer func() {\n\t\tnamespace = \"\"\n\t}()\n\n\tnamespace = applyNamespace(name)\n\ts()\n\treturn nil\n}\n\nfunc applyNamespace(name string) string {\n\tif namespace != \"\" {\n\t\tif strings.HasPrefix(name, \":\") {\n\t\t\treturn name[1:]\n\t\t}\n\t\tif name == \"default\" {\n\t\t\treturn name\n\t\t}\n\t\treturn fmt.Sprintf(\"%s:%s\", namespace, name)\n\t}\n\n\treturn name\n}\n\n\/\/ Add a grift. If there is already a grift\n\/\/ with the given name the two grifts will\n\/\/ be bundled together.\nfunc Add(name string, grift Grift) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tname = applyNamespace(name)\n\n\tif griftList[name] != nil {\n\t\tfn := griftList[name]\n\t\tgriftList[name] = func(c *Context) error {\n\t\t\terr := fn(c)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn grift(c)\n\t\t}\n\t} else {\n\t\tgriftList[name] = grift\n\t}\n\treturn nil\n}\n\n\/\/ Set a grift. This is similar to `Add` but it will\n\/\/ overwrite an existing grift with the same name.\nfunc Set(name string, grift Grift) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tname = applyNamespace(name)\n\tgriftList[name] = grift\n\treturn nil\n}\n\n\/\/ Rename a grift. Useful if you want to re-define\n\/\/ an existing grift, but don't want to write over\n\/\/ the original.\nfunc Rename(oldName string, newName string) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\toldName = applyNamespace(oldName)\n\tnewName = applyNamespace(newName)\n\n\tif griftList[oldName] == nil {\n\t\treturn fmt.Errorf(\"No task named %s defined!\", oldName)\n\t}\n\tgriftList[newName] = griftList[oldName]\n\tdelete(griftList, oldName)\n\treturn nil\n}\n\n\/\/ Remove a grift. Not incredibly useful, but here for\n\/\/ completeness.\nfunc Remove(name string) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tname = applyNamespace(name)\n\n\tdelete(griftList, name)\n\tdelete(descriptions, name)\n\treturn nil\n}\n\n\/\/ Desc sets a helpful descriptive text for a grift.\n\/\/ This description will be shown when `grift list`\n\/\/ is run.\nfunc Desc(name string, description string) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tname = applyNamespace(name)\n\n\tdescriptions[name] = description\n\treturn nil\n}\n\n\/\/ Run a grift. This allows for the chaining for grifts.\n\/\/ One grift can Run another grift and so on.\nfunc Run(name string, c *Context) error {\n\tname = applyNamespace(name)\n\n\tif griftList[name] == nil {\n\t\tif name == \"list\" {\n\t\t\tPrintGrifts(os.Stdout)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"No task named '%s' defined!\", name)\n\t}\n\tif c.Verbose {\n\t\tdefer func(start time.Time) {\n\t\t\tlog.Printf(\"Completed task %s in %s\\n\", name, time.Now().Sub(start))\n\t\t}(time.Now())\n\t\tlog.Printf(\"Starting task %s\\n\", name)\n\t}\n\treturn griftList[name](c)\n}\n\n\/\/ List of the names of the defined grifts.\nfunc List() []string {\n\tkeys := []string{}\n\tfor k := range griftList {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}\n\n\/\/ Exec the grift stack. This is the main \"entry point\" to\n\/\/ the grift system.\nfunc Exec(args []string, verbose bool) error {\n\tname := \"list\"\n\tif len(args) >= 1 {\n\t\tname = args[0]\n\t}\n\tswitch name {\n\tcase \"list\":\n\t\tPrintGrifts(os.Stdout)\n\tdefault:\n\t\tc := NewContext(name)\n\t\tc.Verbose = verbose\n\t\tif len(args) >= 1 {\n\t\t\tc.Args = args[1:]\n\t\t}\n\t\treturn Run(name, c)\n\t}\n\treturn nil\n}\n\n\/\/ PrintGrifts to the screen, nice, sorted, and with descriptions,\n\/\/ should they exist.\nfunc PrintGrifts(w io.Writer) {\n\tfmt.Fprint(w, \"Available grifts\\n================\\n\")\n\n\tcnLen := len(CommandName)\n\tmaxLen := cnLen\n\tl := List()\n\n\tfor _, k := range l {\n\t\tif (len(k) + cnLen) > maxLen {\n\t\t\tmaxLen = len(k) + cnLen\n\t\t}\n\t}\n\n\tfor _, k := range l {\n\t\tm := strings.Join([]string{CommandName, k}, \" \")\n\t\tsuffix := strings.Repeat(\" \", (maxLen+3)-len(m)) + \" #\"\n\n\t\tfmt.Fprintln(w, strings.Join([]string{m, suffix, descriptions[k]}, \" \"))\n\t}\n}\n<commit_msg>Add RunSource<commit_after>package grift\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nvar CommandName = \"grift\"\nvar griftList = map[string]Grift{}\nvar descriptions = map[string]string{}\nvar lock = &sync.Mutex{}\nvar namespace string\n\ntype Grift func(c *Context) error\n\n\/\/ Namespace will place all tasks within the given prefix.\nfunc Namespace(name string, s func()) error {\n\tdefer func() {\n\t\tnamespace = \"\"\n\t}()\n\n\tnamespace = applyNamespace(name)\n\ts()\n\treturn nil\n}\n\nfunc applyNamespace(name string) string {\n\tif namespace != \"\" {\n\t\tif strings.HasPrefix(name, \":\") {\n\t\t\treturn name[1:]\n\t\t}\n\t\tif name == \"default\" {\n\t\t\treturn name\n\t\t}\n\t\treturn fmt.Sprintf(\"%s:%s\", namespace, name)\n\t}\n\n\treturn name\n}\n\n\/\/ Add a grift. If there is already a grift\n\/\/ with the given name the two grifts will\n\/\/ be bundled together.\nfunc Add(name string, grift Grift) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tname = applyNamespace(name)\n\n\tif griftList[name] != nil {\n\t\tfn := griftList[name]\n\t\tgriftList[name] = func(c *Context) error {\n\t\t\terr := fn(c)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn grift(c)\n\t\t}\n\t} else {\n\t\tgriftList[name] = grift\n\t}\n\treturn nil\n}\n\n\/\/ Set a grift. This is similar to `Add` but it will\n\/\/ overwrite an existing grift with the same name.\nfunc Set(name string, grift Grift) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\tname = applyNamespace(name)\n\tgriftList[name] = grift\n\treturn nil\n}\n\n\/\/ Rename a grift. Useful if you want to re-define\n\/\/ an existing grift, but don't want to write over\n\/\/ the original.\nfunc Rename(oldName string, newName string) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\toldName = applyNamespace(oldName)\n\tnewName = applyNamespace(newName)\n\n\tif griftList[oldName] == nil {\n\t\treturn fmt.Errorf(\"No task named %s defined!\", oldName)\n\t}\n\tgriftList[newName] = griftList[oldName]\n\tdelete(griftList, oldName)\n\treturn nil\n}\n\n\/\/ Remove a grift. Not incredibly useful, but here for\n\/\/ completeness.\nfunc Remove(name string) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tname = applyNamespace(name)\n\n\tdelete(griftList, name)\n\tdelete(descriptions, name)\n\treturn nil\n}\n\n\/\/ Desc sets a helpful descriptive text for a grift.\n\/\/ This description will be shown when `grift list`\n\/\/ is run.\nfunc Desc(name string, description string) error {\n\tlock.Lock()\n\tdefer lock.Unlock()\n\n\tname = applyNamespace(name)\n\n\tdescriptions[name] = description\n\treturn nil\n}\n\n\/\/ Run a grift. This allows for the chaining for grifts.\n\/\/ One grift can Run another grift and so on.\nfunc Run(name string, c *Context) error {\n\tname = applyNamespace(name)\n\n\tif griftList[name] == nil {\n\t\tif name == \"list\" {\n\t\t\tPrintGrifts(os.Stdout)\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"No task named '%s' defined!\", name)\n\t}\n\tif c.Verbose {\n\t\tdefer func(start time.Time) {\n\t\t\tlog.Printf(\"Completed task %s in %s\\n\", name, time.Now().Sub(start))\n\t\t}(time.Now())\n\t\tlog.Printf(\"Starting task %s\\n\", name)\n\t}\n\treturn griftList[name](c)\n}\n\n\/\/ List of the names of the defined grifts.\nfunc List() []string {\n\tkeys := []string{}\n\tfor k := range griftList {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\treturn keys\n}\n\n\/\/ Exec the grift stack. This is the main \"entry point\" to\n\/\/ the grift system.\nfunc Exec(args []string, verbose bool) error {\n\tname := \"list\"\n\tif len(args) >= 1 {\n\t\tname = args[0]\n\t}\n\tswitch name {\n\tcase \"list\":\n\t\tPrintGrifts(os.Stdout)\n\tdefault:\n\t\tc := NewContext(name)\n\t\tc.Verbose = verbose\n\t\tif len(args) >= 1 {\n\t\t\tc.Args = args[1:]\n\t\t}\n\t\treturn Run(name, c)\n\t}\n\treturn nil\n}\n\n\/\/ PrintGrifts to the screen, nice, sorted, and with descriptions,\n\/\/ should they exist.\nfunc PrintGrifts(w io.Writer) {\n\tfmt.Fprint(w, \"Available grifts\\n================\\n\")\n\n\tcnLen := len(CommandName)\n\tmaxLen := cnLen\n\tl := List()\n\n\tfor _, k := range l {\n\t\tif (len(k) + cnLen) > maxLen {\n\t\t\tmaxLen = len(k) + cnLen\n\t\t}\n\t}\n\n\tfor _, k := range l {\n\t\tm := strings.Join([]string{CommandName, k}, \" \")\n\t\tsuffix := strings.Repeat(\" \", (maxLen+3)-len(m)) + \" #\"\n\n\t\tfmt.Fprintln(w, strings.Join([]string{m, suffix, descriptions[k]}, \" \"))\n\t}\n}\n\/\/ RunSource executes the command passed as argument,\n\/\/ in the current shell\/context\nfunc RunSource(cmd exec.Command) error{\n\tcmd.Stdin = os.Stdin\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdout = os.Stdout\n\treturn cmd.Run()\n}<|endoftext|>"}
{"text":"<commit_before>package mocks\n\nimport \"github.com\/stretchr\/testify\/mock\"\n\nimport \"github.com\/control-center\/serviced\/domain\/applicationendpoint\"\nimport \"github.com\/control-center\/serviced\/domain\/host\"\nimport \"github.com\/control-center\/serviced\/domain\/pool\"\nimport \"github.com\/control-center\/serviced\/facade\"\nimport \"github.com\/control-center\/serviced\/volume\"\n\ntype ClientInterface struct {\n\tmock.Mock\n}\n\nfunc (_m *ClientInterface) Close() error {\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) GetHost(hostID string) (*host.Host, error) {\n\tret := _m.Called(hostID)\n\n\tvar r0 *host.Host\n\tif rf, ok := ret.Get(0).(func(string) *host.Host); ok {\n\t\tr0 = rf(hostID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*host.Host)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(hostID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) GetHosts() ([]host.Host, error) {\n\tret := _m.Called()\n\n\tvar r0 []host.Host\n\tif rf, ok := ret.Get(0).(func() []host.Host); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]host.Host)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) GetActiveHostIDs() ([]string, error) {\n\tret := _m.Called()\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func() []string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) AddHost(targetHost host.Host) error {\n\tret := _m.Called(targetHost)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(host.Host) error); ok {\n\t\tr0 = rf(targetHost)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) UpdateHost(targetHost host.Host) error {\n\tret := _m.Called(targetHost)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(host.Host) error); ok {\n\t\tr0 = rf(targetHost)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) RemoveHost(hostID string) error {\n\tret := _m.Called(hostID)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(hostID)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) FindHostsInPool(poolID string) ([]host.Host, error) {\n\tret := _m.Called(poolID)\n\n\tvar r0 []host.Host\n\tif rf, ok := ret.Get(0).(func(string) []host.Host); ok {\n\t\tr0 = rf(poolID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]host.Host)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(poolID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) GetResourcePool(poolID string) (*pool.ResourcePool, error) {\n\tret := _m.Called(poolID)\n\n\tvar r0 *pool.ResourcePool\n\tif rf, ok := ret.Get(0).(func(string) *pool.ResourcePool); ok {\n\t\tr0 = rf(poolID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*pool.ResourcePool)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(poolID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) GetResourcePools() ([]pool.ResourcePool, error) {\n\tret := _m.Called()\n\n\tvar r0 []pool.ResourcePool\n\tif rf, ok := ret.Get(0).(func() []pool.ResourcePool); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]pool.ResourcePool)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) AddResourcePool(pool pool.ResourcePool) error {\n\tret := _m.Called(pool)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(pool.ResourcePool) error); ok {\n\t\tr0 = rf(pool)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) UpdateResourcePool(pool pool.ResourcePool) error {\n\tret := _m.Called(pool)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(pool.ResourcePool) error); ok {\n\t\tr0 = rf(pool)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) RemoveResourcePool(poolID string) error {\n\tret := _m.Called(poolID)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(poolID)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) GetPoolIPs(poolID string) (*facade.PoolIPs, error) {\n\tret := _m.Called(poolID)\n\n\tvar r0 *facade.PoolIPs\n\tif rf, ok := ret.Get(0).(func(string) *facade.PoolIPs); ok {\n\t\tr0 = rf(poolID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*facade.PoolIPs)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(poolID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) AddVirtualIP(requestVirtualIP pool.VirtualIP) error {\n\tret := _m.Called(requestVirtualIP)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(pool.VirtualIP) error); ok {\n\t\tr0 = rf(requestVirtualIP)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) RemoveVirtualIP(requestVirtualIP pool.VirtualIP) error {\n\tret := _m.Called(requestVirtualIP)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(pool.VirtualIP) error); ok {\n\t\tr0 = rf(requestVirtualIP)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) ServiceUse(serviceID string, imageID string, registry string, replaceImgs []string, noOp bool) (string, error) {\n\tret := _m.Called(serviceID, imageID, registry, replaceImgs, noOp)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string, string, string, []string, bool) string); ok {\n\t\tr0 = rf(serviceID, imageID, registry, replaceImgs, noOp)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, string, string, []string, bool) error); ok {\n\t\tr1 = rf(serviceID, imageID, registry, replaceImgs, noOp)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) GetVolumeStatus() (*volume.Statuses, error) {\n\tret := _m.Called()\n\n\tvar r0 *volume.Statuses\n\tif rf, ok := ret.Get(0).(func() *volume.Statuses); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*volume.Statuses)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) GetServiceEndpoints(serviceIDs []string, reportImports bool, reportExports bool, validate bool) ([]applicationendpoint.EndpointReport, error) {\n\tret := _m.Called(serviceIDs, reportImports, reportExports, validate)\n\n\tvar r0 []applicationendpoint.EndpointReport\n\tif rf, ok := ret.Get(0).(func([]string, bool, bool, bool) []applicationendpoint.EndpointReport); ok {\n\t\tr0 = rf(serviceIDs, reportImports, reportExports, validate)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]applicationendpoint.EndpointReport)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func([]string, bool, bool, bool) error); ok {\n\t\tr1 = rf(serviceIDs, reportImports, reportExports, validate)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) ResetRegistry() error {\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) SyncRegistry() error {\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) UpgradeRegistry(endpoint string, override bool) error {\n\tret := _m.Called(endpoint, override)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, bool) error); ok {\n\t\tr0 = rf(endpoint, override)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\n<commit_msg>fixed pool name collision<commit_after>package mocks\n\nimport \"github.com\/stretchr\/testify\/mock\"\n\nimport \"github.com\/control-center\/serviced\/domain\/applicationendpoint\"\nimport \"github.com\/control-center\/serviced\/domain\/host\"\nimport \"github.com\/control-center\/serviced\/domain\/pool\"\nimport \"github.com\/control-center\/serviced\/facade\"\nimport \"github.com\/control-center\/serviced\/volume\"\n\ntype ClientInterface struct {\n\tmock.Mock\n}\n\nfunc (_m *ClientInterface) Close() error {\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) GetHost(hostID string) (*host.Host, error) {\n\tret := _m.Called(hostID)\n\n\tvar r0 *host.Host\n\tif rf, ok := ret.Get(0).(func(string) *host.Host); ok {\n\t\tr0 = rf(hostID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*host.Host)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(hostID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) GetHosts() ([]host.Host, error) {\n\tret := _m.Called()\n\n\tvar r0 []host.Host\n\tif rf, ok := ret.Get(0).(func() []host.Host); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]host.Host)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) GetActiveHostIDs() ([]string, error) {\n\tret := _m.Called()\n\n\tvar r0 []string\n\tif rf, ok := ret.Get(0).(func() []string); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]string)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) AddHost(targetHost host.Host) error {\n\tret := _m.Called(targetHost)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(host.Host) error); ok {\n\t\tr0 = rf(targetHost)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) UpdateHost(targetHost host.Host) error {\n\tret := _m.Called(targetHost)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(host.Host) error); ok {\n\t\tr0 = rf(targetHost)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) RemoveHost(hostID string) error {\n\tret := _m.Called(hostID)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(hostID)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) FindHostsInPool(poolID string) ([]host.Host, error) {\n\tret := _m.Called(poolID)\n\n\tvar r0 []host.Host\n\tif rf, ok := ret.Get(0).(func(string) []host.Host); ok {\n\t\tr0 = rf(poolID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]host.Host)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(poolID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) GetResourcePool(poolID string) (*pool.ResourcePool, error) {\n\tret := _m.Called(poolID)\n\n\tvar r0 *pool.ResourcePool\n\tif rf, ok := ret.Get(0).(func(string) *pool.ResourcePool); ok {\n\t\tr0 = rf(poolID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*pool.ResourcePool)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(poolID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) GetResourcePools() ([]pool.ResourcePool, error) {\n\tret := _m.Called()\n\n\tvar r0 []pool.ResourcePool\n\tif rf, ok := ret.Get(0).(func() []pool.ResourcePool); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]pool.ResourcePool)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) AddResourcePool(targetPool pool.ResourcePool) error {\n\tret := _m.Called(targetPool)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(pool.ResourcePool) error); ok {\n\t\tr0 = rf(targetPool)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) UpdateResourcePool(targetPool pool.ResourcePool) error {\n\tret := _m.Called(targetPool)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(pool.ResourcePool) error); ok {\n\t\tr0 = rf(targetPool)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) RemoveResourcePool(poolID string) error {\n\tret := _m.Called(poolID)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string) error); ok {\n\t\tr0 = rf(poolID)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) GetPoolIPs(poolID string) (*facade.PoolIPs, error) {\n\tret := _m.Called(poolID)\n\n\tvar r0 *facade.PoolIPs\n\tif rf, ok := ret.Get(0).(func(string) *facade.PoolIPs); ok {\n\t\tr0 = rf(poolID)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*facade.PoolIPs)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string) error); ok {\n\t\tr1 = rf(poolID)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) AddVirtualIP(requestVirtualIP pool.VirtualIP) error {\n\tret := _m.Called(requestVirtualIP)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(pool.VirtualIP) error); ok {\n\t\tr0 = rf(requestVirtualIP)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) RemoveVirtualIP(requestVirtualIP pool.VirtualIP) error {\n\tret := _m.Called(requestVirtualIP)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(pool.VirtualIP) error); ok {\n\t\tr0 = rf(requestVirtualIP)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) ServiceUse(serviceID string, imageID string, registry string, replaceImgs []string, noOp bool) (string, error) {\n\tret := _m.Called(serviceID, imageID, registry, replaceImgs, noOp)\n\n\tvar r0 string\n\tif rf, ok := ret.Get(0).(func(string, string, string, []string, bool) string); ok {\n\t\tr0 = rf(serviceID, imageID, registry, replaceImgs, noOp)\n\t} else {\n\t\tr0 = ret.Get(0).(string)\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(string, string, string, []string, bool) error); ok {\n\t\tr1 = rf(serviceID, imageID, registry, replaceImgs, noOp)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) GetVolumeStatus() (*volume.Statuses, error) {\n\tret := _m.Called()\n\n\tvar r0 *volume.Statuses\n\tif rf, ok := ret.Get(0).(func() *volume.Statuses); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*volume.Statuses)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func() error); ok {\n\t\tr1 = rf()\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) GetServiceEndpoints(serviceIDs []string, reportImports bool, reportExports bool, validate bool) ([]applicationendpoint.EndpointReport, error) {\n\tret := _m.Called(serviceIDs, reportImports, reportExports, validate)\n\n\tvar r0 []applicationendpoint.EndpointReport\n\tif rf, ok := ret.Get(0).(func([]string, bool, bool, bool) []applicationendpoint.EndpointReport); ok {\n\t\tr0 = rf(serviceIDs, reportImports, reportExports, validate)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).([]applicationendpoint.EndpointReport)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func([]string, bool, bool, bool) error); ok {\n\t\tr1 = rf(serviceIDs, reportImports, reportExports, validate)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}\nfunc (_m *ClientInterface) ResetRegistry() error {\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) SyncRegistry() error {\n\tret := _m.Called()\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func() error); ok {\n\t\tr0 = rf()\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\nfunc (_m *ClientInterface) UpgradeRegistry(endpoint string, override bool) error {\n\tret := _m.Called(endpoint, override)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, bool) error); ok {\n\t\tr0 = rf(endpoint, override)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"gopkg.in\/yaml.v2\"\n)\n\n\/\/ yaml special keys\nconst (\n\tDEFAULT_KEY = \"default\"\n\tSOURCE_KEY  = \"source\"\n\tTARGET_KEY  = \"target\"\n)\n\n\/\/ environment variable names\nconst (\n\tHOME_DIRECTORY = \"HOME\"\n)\n\n\/\/ temporary definitions for dev\nconst (\n\tSETTINGS_FILE_NAME = \"dotorrc.sample.yml\"\n\tSOURCE_PATH        = \"\/Users\/janus\/work\/dev\/github\/dotfiles\"\n)\n\nfunc main() {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Fprintln(os.Stderr, r)\n\t\t}\n\t}()\n\n\tsettings, err := ReadSettings(SETTINGS_FILE_NAME)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\trules, err := BuildRules(settings)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = CreateSymbolicLinks(rules, SOURCE_PATH)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc ReadSettings(filepath string) (map[interface{}]interface{}, error) {\n\tfile, err := ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsettings := make(map[interface{}]interface{})\n\tif err := yaml.Unmarshal(file, &settings); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn settings, nil\n}\n\nfunc BuildRules(settings map[interface{}]interface{}) (map[string]string, error) {\n\tdefaultRules, err := BuildSpecificOsRules(DEFAULT_KEY, settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tosRules, err := BuildSpecificOsRules(runtime.GOOS, settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trules := Extend(defaultRules, osRules)\n\treturn rules, err\n}\n\nfunc BuildSpecificOsRules(os string, settings map[interface{}]interface{}) (map[string]string, error) {\n\trules := make(map[string]string)\n\tif _, hasKey := settings[os]; !hasKey {\n\t\treturn rules, nil\n\t}\n\n\tfor _, value := range settings[os].([]interface{}) {\n\t\tswitch value.(type) {\n\t\tcase string:\n\t\t\trules[value.(string)] = value.(string)\n\t\tcase map[interface{}]interface{}:\n\t\t\tsetting := value.(map[interface{}]interface{})\n\t\t\t_, hasSource := setting[SOURCE_KEY]\n\t\t\t_, hasTarget := setting[TARGET_KEY]\n\t\t\tif !(hasSource && hasTarget) {\n\t\t\t\treturn nil, fmt.Errorf(\"specify key-values in format of \\\"%s:<source file name>\\\" and \\\"%s:<target file name>\\\" to change sysmbolic link names\", SOURCE_KEY, TARGET_KEY)\n\t\t\t}\n\t\t\tsource := setting[SOURCE_KEY].(string)\n\t\t\ttarget := setting[TARGET_KEY].(string)\n\t\t\trules[source] = target\n\t\t}\n\t}\n\n\treturn rules, nil\n}\n\nfunc Extend(m1, m2 map[string]string) map[string]string {\n\tresult := map[string]string{}\n\n\tfor v, k := range m1 {\n\t\tresult[k] = v\n\t}\n\tfor v, k := range m2 {\n\t\tresult[k] = v\n\t}\n\treturn (result)\n}\n\nfunc CreateSymbolicLinks(rules map[string]string, sourceDirectoryPath string) error {\n\ttargetDirectoryAbsolutePath, err := GetHomeDirectory()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsourceDirectoryAbsolutePath, err := filepath.Abs(sourceDirectoryPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"%s => %s\\n\", sourceDirectoryAbsolutePath, targetDirectoryAbsolutePath)\n\n\tfor source, target := range rules {\n\t\tsourceAbsolutePath := filepath.Join(sourceDirectoryAbsolutePath, source)\n\t\ttargetAbsolutePath := filepath.Join(targetDirectoryAbsolutePath, target)\n\t\tif !ExistsPath(sourceAbsolutePath) {\n\t\t\tfmt.Printf(\"source file \\\"%s\\\" is not exists. skipping.\\n\", targetAbsolutePath)\n\t\t\tcontinue\n\t\t}\n\t\tif ExistsPath(targetAbsolutePath) {\n\t\t\tfmt.Printf(\"target file \\\"%s\\\" is already exists. skipping.\\n\", targetAbsolutePath)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"creating symbolic link: %s => %s\\n\", sourceAbsolutePath, targetAbsolutePath)\n\t\t\/\/ TODO: use os.Symlink()\n\t}\n\n\treturn nil\n}\n\nfunc GetHomeDirectory() (dir string, err error) {\n\tenvironmentVariables := GetEnvironmentVariables()\n\tif _, ok := environmentVariables[HOME_DIRECTORY]; !ok {\n\t\treturn \"\", fmt.Errorf(\"Define the environment variable \\\"%s\\\"\", HOME_DIRECTORY)\n\t}\n\treturn environmentVariables[HOME_DIRECTORY], nil\n}\n\nfunc GetEnvironmentVariables() map[string]string {\n\tenvironmentVariables := make(map[string]string)\n\tfor _, item := range os.Environ() {\n\t\tsplited := strings.Split(item, \"=\")\n\t\tenvironmentVariables[splited[0]] = splited[1]\n\t}\n\treturn environmentVariables\n}\n\nfunc ExistsPath(path string) bool {\n\t_, err := os.Stat(path)\n\treturn !os.IsNotExist(err)\n}\n<commit_msg>[WIP] fix comments<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"gopkg.in\/yaml.v2\"\n)\n\n\/\/ special keys in settings\nconst (\n\tDEFAULT_KEY = \"default\"\n\tSOURCE_KEY  = \"source\"\n\tTARGET_KEY  = \"target\"\n)\n\n\/\/ environment variable names\nconst (\n\tHOME_DIRECTORY = \"HOME\"\n)\n\n\/\/ temporary definitions for dev\nconst (\n\tSETTINGS_FILE_NAME = \"dotorrc.sample.yml\"\n\tSOURCE_PATH        = \"\/Users\/janus\/work\/dev\/github\/dotfiles\"\n)\n\nfunc main() {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Fprintln(os.Stderr, r)\n\t\t}\n\t}()\n\n\tsettings, err := ReadSettings(SETTINGS_FILE_NAME)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\trules, err := BuildRules(settings)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\terr = CreateSymbolicLinks(rules, SOURCE_PATH)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc ReadSettings(filepath string) (map[interface{}]interface{}, error) {\n\tfile, err := ioutil.ReadFile(filepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsettings := make(map[interface{}]interface{})\n\tif err := yaml.Unmarshal(file, &settings); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn settings, nil\n}\n\nfunc BuildRules(settings map[interface{}]interface{}) (map[string]string, error) {\n\tdefaultRules, err := BuildSpecificOsRules(DEFAULT_KEY, settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tosRules, err := BuildSpecificOsRules(runtime.GOOS, settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trules := Extend(defaultRules, osRules)\n\treturn rules, err\n}\n\nfunc BuildSpecificOsRules(os string, settings map[interface{}]interface{}) (map[string]string, error) {\n\trules := make(map[string]string)\n\tif _, hasKey := settings[os]; !hasKey {\n\t\treturn rules, nil\n\t}\n\n\tfor _, value := range settings[os].([]interface{}) {\n\t\tswitch value.(type) {\n\t\tcase string:\n\t\t\trules[value.(string)] = value.(string)\n\t\tcase map[interface{}]interface{}:\n\t\t\tsetting := value.(map[interface{}]interface{})\n\t\t\t_, hasSource := setting[SOURCE_KEY]\n\t\t\t_, hasTarget := setting[TARGET_KEY]\n\t\t\tif !(hasSource && hasTarget) {\n\t\t\t\treturn nil, fmt.Errorf(\"specify key-values in format of \\\"%s:<source file name>\\\" and \\\"%s:<target file name>\\\" to change sysmbolic link names\", SOURCE_KEY, TARGET_KEY)\n\t\t\t}\n\t\t\tsource := setting[SOURCE_KEY].(string)\n\t\t\ttarget := setting[TARGET_KEY].(string)\n\t\t\trules[source] = target\n\t\t}\n\t}\n\n\treturn rules, nil\n}\n\nfunc Extend(m1, m2 map[string]string) map[string]string {\n\tresult := map[string]string{}\n\n\tfor v, k := range m1 {\n\t\tresult[k] = v\n\t}\n\tfor v, k := range m2 {\n\t\tresult[k] = v\n\t}\n\treturn (result)\n}\n\nfunc CreateSymbolicLinks(rules map[string]string, sourceDirectoryPath string) error {\n\ttargetDirectoryAbsolutePath, err := GetHomeDirectory()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsourceDirectoryAbsolutePath, err := filepath.Abs(sourceDirectoryPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"%s => %s\\n\", sourceDirectoryAbsolutePath, targetDirectoryAbsolutePath)\n\n\tfor source, target := range rules {\n\t\tsourceAbsolutePath := filepath.Join(sourceDirectoryAbsolutePath, source)\n\t\ttargetAbsolutePath := filepath.Join(targetDirectoryAbsolutePath, target)\n\t\tif !ExistsPath(sourceAbsolutePath) {\n\t\t\tfmt.Printf(\"source file \\\"%s\\\" is not exists. skipping.\\n\", targetAbsolutePath)\n\t\t\tcontinue\n\t\t}\n\t\tif ExistsPath(targetAbsolutePath) {\n\t\t\tfmt.Printf(\"target file \\\"%s\\\" is already exists. skipping.\\n\", targetAbsolutePath)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"creating symbolic link: %s => %s\\n\", sourceAbsolutePath, targetAbsolutePath)\n\t\t\/\/ TODO: use os.Symlink()\n\t}\n\n\treturn nil\n}\n\nfunc GetHomeDirectory() (dir string, err error) {\n\tenvironmentVariables := GetEnvironmentVariables()\n\tif _, ok := environmentVariables[HOME_DIRECTORY]; !ok {\n\t\treturn \"\", fmt.Errorf(\"Define the environment variable \\\"%s\\\"\", HOME_DIRECTORY)\n\t}\n\treturn environmentVariables[HOME_DIRECTORY], nil\n}\n\nfunc GetEnvironmentVariables() map[string]string {\n\tenvironmentVariables := make(map[string]string)\n\tfor _, item := range os.Environ() {\n\t\tsplited := strings.Split(item, \"=\")\n\t\tenvironmentVariables[splited[0]] = splited[1]\n\t}\n\treturn environmentVariables\n}\n\nfunc ExistsPath(path string) bool {\n\t_, err := os.Stat(path)\n\treturn !os.IsNotExist(err)\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/organizations\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/validation\"\n\t\"github.com\/terraform-providers\/terraform-provider-aws\/aws\/internal\/keyvaluetags\"\n)\n\nfunc resourceAwsOrganizationsAccount() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsOrganizationsAccountCreate,\n\t\tRead:   resourceAwsOrganizationsAccountRead,\n\t\tUpdate: resourceAwsOrganizationsAccountUpdate,\n\t\tDelete: resourceAwsOrganizationsAccountDelete,\n\t\tImporter: &schema.ResourceImporter{\n\t\t\tState: schema.ImportStatePassthrough,\n\t\t},\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"arn\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"joined_method\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"joined_timestamp\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"parent_id\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tComputed:     true,\n\t\t\t\tOptional:     true,\n\t\t\t\tValidateFunc: validation.StringMatch(regexp.MustCompile(\"^(r-[0-9a-z]{4,32})|(ou-[0-9a-z]{4,32}-[a-z0-9]{8,32})$\"), \"see https:\/\/docs.aws.amazon.com\/organizations\/latest\/APIReference\/API_MoveAccount.html#organizations-MoveAccount-request-DestinationParentId\"),\n\t\t\t},\n\t\t\t\"status\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"name\": {\n\t\t\t\tForceNew:     true,\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tRequired:     true,\n\t\t\t\tValidateFunc: validation.StringLenBetween(1, 50),\n\t\t\t},\n\t\t\t\"email\": {\n\t\t\t\tForceNew:     true,\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tRequired:     true,\n\t\t\t\tValidateFunc: validateAwsOrganizationsAccountEmail,\n\t\t\t},\n\t\t\t\"iam_user_access_to_billing\": {\n\t\t\t\tForceNew:     true,\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tOptional:     true,\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{organizations.IAMUserAccessToBillingAllow, organizations.IAMUserAccessToBillingDeny}, true),\n\t\t\t},\n\t\t\t\"role_name\": {\n\t\t\t\tForceNew:     true,\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tOptional:     true,\n\t\t\t\tValidateFunc: validateAwsOrganizationsAccountRoleName,\n\t\t\t},\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsOrganizationsAccountCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).organizationsconn\n\n\t\/\/ Create the account\n\tcreateOpts := &organizations.CreateAccountInput{\n\t\tAccountName: aws.String(d.Get(\"name\").(string)),\n\t\tEmail:       aws.String(d.Get(\"email\").(string)),\n\t}\n\tif role, ok := d.GetOk(\"role_name\"); ok {\n\t\tcreateOpts.RoleName = aws.String(role.(string))\n\t}\n\n\tif iam_user, ok := d.GetOk(\"iam_user_access_to_billing\"); ok {\n\t\tcreateOpts.IamUserAccessToBilling = aws.String(iam_user.(string))\n\t}\n\n\tlog.Printf(\"[DEBUG] Creating AWS Organizations Account: %s\", createOpts)\n\n\tvar resp *organizations.CreateAccountOutput\n\terr := resource.Retry(4*time.Minute, func() *resource.RetryError {\n\t\tvar err error\n\n\t\tresp, err = conn.CreateAccount(createOpts)\n\n\t\tif isAWSErr(err, organizations.ErrCodeFinalizingOrganizationException, \"\") {\n\t\t\treturn resource.RetryableError(err)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn resource.NonRetryableError(err)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif isResourceTimeoutError(err) {\n\t\tresp, err = conn.CreateAccount(createOpts)\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating account: %s\", err)\n\t}\n\n\trequestId := *resp.CreateAccountStatus.Id\n\n\t\/\/ Wait for the account to become available\n\tlog.Printf(\"[DEBUG] Waiting for account request (%s) to succeed\", requestId)\n\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:      []string{organizations.CreateAccountStateInProgress},\n\t\tTarget:       []string{organizations.CreateAccountStateSucceeded},\n\t\tRefresh:      resourceAwsOrganizationsAccountStateRefreshFunc(conn, requestId),\n\t\tPollInterval: 10 * time.Second,\n\t\tTimeout:      5 * time.Minute,\n\t}\n\tstateResp, stateErr := stateConf.WaitForState()\n\tif stateErr != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"Error waiting for account request (%s) to become available: %s\",\n\t\t\trequestId, stateErr)\n\t}\n\n\t\/\/ Store the ID\n\taccountId := stateResp.(*organizations.CreateAccountStatus).AccountId\n\td.SetId(*accountId)\n\n\tif v, ok := d.GetOk(\"parent_id\"); ok {\n\t\tnewParentID := v.(string)\n\n\t\texistingParentID, err := resourceAwsOrganizationsAccountGetParentId(conn, d.Id())\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error getting AWS Organizations Account (%s) parent: %s\", d.Id(), err)\n\t\t}\n\n\t\tif newParentID != existingParentID {\n\t\t\tinput := &organizations.MoveAccountInput{\n\t\t\t\tAccountId:           accountId,\n\t\t\t\tSourceParentId:      aws.String(existingParentID),\n\t\t\t\tDestinationParentId: aws.String(newParentID),\n\t\t\t}\n\n\t\t\tif _, err := conn.MoveAccount(input); err != nil {\n\t\t\t\treturn fmt.Errorf(\"error moving AWS Organizations Account (%s): %s\", d.Id(), err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif v := d.Get(\"tags\").(map[string]interface{}); len(v) > 0 {\n\t\tif err := keyvaluetags.OrganizationsUpdateTags(conn, d.Id(), nil, v); err != nil {\n\t\t\treturn fmt.Errorf(\"error adding AWS Organizations Account (%s) tags: %s\", d.Id(), err)\n\t\t}\n\t}\n\n\treturn resourceAwsOrganizationsAccountRead(d, meta)\n}\n\nfunc resourceAwsOrganizationsAccountRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).organizationsconn\n\tdescribeOpts := &organizations.DescribeAccountInput{\n\t\tAccountId: aws.String(d.Id()),\n\t}\n\tresp, err := conn.DescribeAccount(describeOpts)\n\n\tif isAWSErr(err, organizations.ErrCodeAccountNotFoundException, \"\") {\n\t\tlog.Printf(\"[WARN] Account does not exist, removing from state: %s\", d.Id())\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error describing AWS Organizations Account (%s): %s\", d.Id(), err)\n\t}\n\n\taccount := resp.Account\n\tif account == nil {\n\t\tlog.Printf(\"[WARN] Account does not exist, removing from state: %s\", d.Id())\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\n\tparentId, err := resourceAwsOrganizationsAccountGetParentId(conn, d.Id())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting AWS Organizations Account (%s) parent: %s\", d.Id(), err)\n\t}\n\n\td.Set(\"arn\", account.Arn)\n\td.Set(\"email\", account.Email)\n\td.Set(\"joined_method\", account.JoinedMethod)\n\td.Set(\"joined_timestamp\", aws.TimeValue(account.JoinedTimestamp).Format(time.RFC3339))\n\td.Set(\"name\", account.Name)\n\td.Set(\"parent_id\", parentId)\n\td.Set(\"status\", account.Status)\n\n\ttags, err := keyvaluetags.OrganizationsListTags(conn, d.Id())\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error listing tags for AWS Organizations Account (%s): %s\", d.Id(), err)\n\t}\n\n\tif err := d.Set(\"tags\", tags.IgnoreAws().Map()); err != nil {\n\t\treturn fmt.Errorf(\"error setting tags: %s\", err)\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsOrganizationsAccountUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).organizationsconn\n\n\tif d.HasChange(\"parent_id\") {\n\t\to, n := d.GetChange(\"parent_id\")\n\n\t\tinput := &organizations.MoveAccountInput{\n\t\t\tAccountId:           aws.String(d.Id()),\n\t\t\tSourceParentId:      aws.String(o.(string)),\n\t\t\tDestinationParentId: aws.String(n.(string)),\n\t\t}\n\n\t\tif _, err := conn.MoveAccount(input); err != nil {\n\t\t\treturn fmt.Errorf(\"error moving AWS Organizations Account (%s): %s\", d.Id(), err)\n\t\t}\n\t}\n\n\tif d.HasChange(\"tags\") {\n\t\to, n := d.GetChange(\"tags\")\n\n\t\tif err := keyvaluetags.OrganizationsUpdateTags(conn, d.Id(), o, n); err != nil {\n\t\t\treturn fmt.Errorf(\"error updating AWS Organizations Account (%s) tags: %s\", d.Id(), err)\n\t\t}\n\t}\n\n\treturn resourceAwsOrganizationsAccountRead(d, meta)\n}\n\nfunc resourceAwsOrganizationsAccountDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).organizationsconn\n\n\tinput := &organizations.RemoveAccountFromOrganizationInput{\n\t\tAccountId: aws.String(d.Id()),\n\t}\n\tlog.Printf(\"[DEBUG] Removing AWS account from organization: %s\", input)\n\t_, err := conn.RemoveAccountFromOrganization(input)\n\tif err != nil {\n\t\tif isAWSErr(err, organizations.ErrCodeAccountNotFoundException, \"\") {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ resourceAwsOrganizationsAccountStateRefreshFunc returns a resource.StateRefreshFunc\n\/\/ that is used to watch a CreateAccount request\nfunc resourceAwsOrganizationsAccountStateRefreshFunc(conn *organizations.Organizations, id string) resource.StateRefreshFunc {\n\treturn func() (interface{}, string, error) {\n\t\topts := &organizations.DescribeCreateAccountStatusInput{\n\t\t\tCreateAccountRequestId: aws.String(id),\n\t\t}\n\t\tresp, err := conn.DescribeCreateAccountStatus(opts)\n\t\tif err != nil {\n\t\t\tif isAWSErr(err, organizations.ErrCodeCreateAccountStatusNotFoundException, \"\") {\n\t\t\t\tresp = nil\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Error on OrganizationAccountStateRefresh: %s\", err)\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\t\t}\n\n\t\tif resp == nil {\n\t\t\t\/\/ Sometimes AWS just has consistency issues and doesn't see\n\t\t\t\/\/ our account yet. Return an empty state.\n\t\t\treturn nil, \"\", nil\n\t\t}\n\n\t\taccountStatus := resp.CreateAccountStatus\n\t\tif *accountStatus.State == organizations.CreateAccountStateFailed {\n\t\t\treturn nil, *accountStatus.State, fmt.Errorf(*accountStatus.FailureReason)\n\t\t}\n\t\treturn accountStatus, *accountStatus.State, nil\n\t}\n}\n\nfunc validateAwsOrganizationsAccountEmail(v interface{}, k string) (ws []string, errors []error) {\n\tvalue := v.(string)\n\tif !regexp.MustCompile(`^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$`).MatchString(value) {\n\t\terrors = append(errors, fmt.Errorf(\n\t\t\t\"%q must be a valid email address\", value))\n\t}\n\n\tif len(value) < 6 {\n\t\terrors = append(errors, fmt.Errorf(\n\t\t\t\"%q cannot be less than 6 characters\", value))\n\t}\n\n\tif len(value) > 64 {\n\t\terrors = append(errors, fmt.Errorf(\n\t\t\t\"%q cannot be greater than 64 characters\", value))\n\t}\n\n\treturn\n}\n\nfunc validateAwsOrganizationsAccountRoleName(v interface{}, k string) (ws []string, errors []error) {\n\tvalue := v.(string)\n\tif !regexp.MustCompile(`^[\\w+=,.@-]{1,64}$`).MatchString(value) {\n\t\terrors = append(errors, fmt.Errorf(\n\t\t\t\"%q must consist of uppercase letters, lowercase letters, digits with no spaces, and any of the following characters: =,.@-\", value))\n\t}\n\n\treturn\n}\n\nfunc resourceAwsOrganizationsAccountGetParentId(conn *organizations.Organizations, childId string) (string, error) {\n\tinput := &organizations.ListParentsInput{\n\t\tChildId: aws.String(childId),\n\t}\n\tvar parents []*organizations.Parent\n\n\terr := conn.ListParentsPages(input, func(page *organizations.ListParentsOutput, lastPage bool) bool {\n\t\tparents = append(parents, page.Parents...)\n\n\t\treturn !lastPage\n\t})\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(parents) == 0 {\n\t\treturn \"\", nil\n\t}\n\n\t\/\/ assume there is only a single parent\n\t\/\/ https:\/\/docs.aws.amazon.com\/organizations\/latest\/APIReference\/API_ListParents.html\n\tparent := parents[0]\n\treturn aws.StringValue(parent.Id), nil\n}\n<commit_msg>r\/organizations_account: tech debt: replace custom validation funcs<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/organizations\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/helper\/validation\"\n\t\"github.com\/terraform-providers\/terraform-provider-aws\/aws\/internal\/keyvaluetags\"\n)\n\nfunc resourceAwsOrganizationsAccount() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsOrganizationsAccountCreate,\n\t\tRead:   resourceAwsOrganizationsAccountRead,\n\t\tUpdate: resourceAwsOrganizationsAccountUpdate,\n\t\tDelete: resourceAwsOrganizationsAccountDelete,\n\t\tImporter: &schema.ResourceImporter{\n\t\t\tState: schema.ImportStatePassthrough,\n\t\t},\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"arn\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"joined_method\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"joined_timestamp\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"parent_id\": {\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tComputed:     true,\n\t\t\t\tOptional:     true,\n\t\t\t\tValidateFunc: validation.StringMatch(regexp.MustCompile(\"^(r-[0-9a-z]{4,32})|(ou-[0-9a-z]{4,32}-[a-z0-9]{8,32})$\"), \"see https:\/\/docs.aws.amazon.com\/organizations\/latest\/APIReference\/API_MoveAccount.html#organizations-MoveAccount-request-DestinationParentId\"),\n\t\t\t},\n\t\t\t\"status\": {\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"name\": {\n\t\t\t\tForceNew:     true,\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tRequired:     true,\n\t\t\t\tValidateFunc: validation.StringLenBetween(1, 50),\n\t\t\t},\n\t\t\t\"email\": {\n\t\t\t\tForceNew: true,\n\t\t\t\tType:     schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tValidateFunc: validation.All(\n\t\t\t\t\tvalidation.StringLenBetween(6, 64),\n\t\t\t\t\tvalidation.StringMatch(regexp.MustCompile(`^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$`), \"must be a valid email address\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t\"iam_user_access_to_billing\": {\n\t\t\t\tForceNew:     true,\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tOptional:     true,\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{organizations.IAMUserAccessToBillingAllow, organizations.IAMUserAccessToBillingDeny}, true),\n\t\t\t},\n\t\t\t\"role_name\": {\n\t\t\t\tForceNew:     true,\n\t\t\t\tType:         schema.TypeString,\n\t\t\t\tOptional:     true,\n\t\t\t\tValidateFunc: validation.StringMatch(regexp.MustCompile(`^[\\w+=,.@-]{1,64}$`), \"must consist of uppercase letters, lowercase letters, digits with no spaces, and any of the following characters\"),\n\t\t\t},\n\t\t\t\"tags\": tagsSchema(),\n\t\t},\n\t}\n}\n\nfunc resourceAwsOrganizationsAccountCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).organizationsconn\n\n\t\/\/ Create the account\n\tcreateOpts := &organizations.CreateAccountInput{\n\t\tAccountName: aws.String(d.Get(\"name\").(string)),\n\t\tEmail:       aws.String(d.Get(\"email\").(string)),\n\t}\n\tif role, ok := d.GetOk(\"role_name\"); ok {\n\t\tcreateOpts.RoleName = aws.String(role.(string))\n\t}\n\n\tif iam_user, ok := d.GetOk(\"iam_user_access_to_billing\"); ok {\n\t\tcreateOpts.IamUserAccessToBilling = aws.String(iam_user.(string))\n\t}\n\n\tlog.Printf(\"[DEBUG] Creating AWS Organizations Account: %s\", createOpts)\n\n\tvar resp *organizations.CreateAccountOutput\n\terr := resource.Retry(4*time.Minute, func() *resource.RetryError {\n\t\tvar err error\n\n\t\tresp, err = conn.CreateAccount(createOpts)\n\n\t\tif isAWSErr(err, organizations.ErrCodeFinalizingOrganizationException, \"\") {\n\t\t\treturn resource.RetryableError(err)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn resource.NonRetryableError(err)\n\t\t}\n\n\t\treturn nil\n\t})\n\n\tif isResourceTimeoutError(err) {\n\t\tresp, err = conn.CreateAccount(createOpts)\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating account: %s\", err)\n\t}\n\n\trequestId := *resp.CreateAccountStatus.Id\n\n\t\/\/ Wait for the account to become available\n\tlog.Printf(\"[DEBUG] Waiting for account request (%s) to succeed\", requestId)\n\n\tstateConf := &resource.StateChangeConf{\n\t\tPending:      []string{organizations.CreateAccountStateInProgress},\n\t\tTarget:       []string{organizations.CreateAccountStateSucceeded},\n\t\tRefresh:      resourceAwsOrganizationsAccountStateRefreshFunc(conn, requestId),\n\t\tPollInterval: 10 * time.Second,\n\t\tTimeout:      5 * time.Minute,\n\t}\n\tstateResp, stateErr := stateConf.WaitForState()\n\tif stateErr != nil {\n\t\treturn fmt.Errorf(\n\t\t\t\"Error waiting for account request (%s) to become available: %s\",\n\t\t\trequestId, stateErr)\n\t}\n\n\t\/\/ Store the ID\n\taccountId := stateResp.(*organizations.CreateAccountStatus).AccountId\n\td.SetId(*accountId)\n\n\tif v, ok := d.GetOk(\"parent_id\"); ok {\n\t\tnewParentID := v.(string)\n\n\t\texistingParentID, err := resourceAwsOrganizationsAccountGetParentId(conn, d.Id())\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error getting AWS Organizations Account (%s) parent: %s\", d.Id(), err)\n\t\t}\n\n\t\tif newParentID != existingParentID {\n\t\t\tinput := &organizations.MoveAccountInput{\n\t\t\t\tAccountId:           accountId,\n\t\t\t\tSourceParentId:      aws.String(existingParentID),\n\t\t\t\tDestinationParentId: aws.String(newParentID),\n\t\t\t}\n\n\t\t\tif _, err := conn.MoveAccount(input); err != nil {\n\t\t\t\treturn fmt.Errorf(\"error moving AWS Organizations Account (%s): %s\", d.Id(), err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif v := d.Get(\"tags\").(map[string]interface{}); len(v) > 0 {\n\t\tif err := keyvaluetags.OrganizationsUpdateTags(conn, d.Id(), nil, v); err != nil {\n\t\t\treturn fmt.Errorf(\"error adding AWS Organizations Account (%s) tags: %s\", d.Id(), err)\n\t\t}\n\t}\n\n\treturn resourceAwsOrganizationsAccountRead(d, meta)\n}\n\nfunc resourceAwsOrganizationsAccountRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).organizationsconn\n\tdescribeOpts := &organizations.DescribeAccountInput{\n\t\tAccountId: aws.String(d.Id()),\n\t}\n\tresp, err := conn.DescribeAccount(describeOpts)\n\n\tif isAWSErr(err, organizations.ErrCodeAccountNotFoundException, \"\") {\n\t\tlog.Printf(\"[WARN] Account does not exist, removing from state: %s\", d.Id())\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error describing AWS Organizations Account (%s): %s\", d.Id(), err)\n\t}\n\n\taccount := resp.Account\n\tif account == nil {\n\t\tlog.Printf(\"[WARN] Account does not exist, removing from state: %s\", d.Id())\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\n\tparentId, err := resourceAwsOrganizationsAccountGetParentId(conn, d.Id())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting AWS Organizations Account (%s) parent: %s\", d.Id(), err)\n\t}\n\n\td.Set(\"arn\", account.Arn)\n\td.Set(\"email\", account.Email)\n\td.Set(\"joined_method\", account.JoinedMethod)\n\td.Set(\"joined_timestamp\", aws.TimeValue(account.JoinedTimestamp).Format(time.RFC3339))\n\td.Set(\"name\", account.Name)\n\td.Set(\"parent_id\", parentId)\n\td.Set(\"status\", account.Status)\n\n\ttags, err := keyvaluetags.OrganizationsListTags(conn, d.Id())\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error listing tags for AWS Organizations Account (%s): %s\", d.Id(), err)\n\t}\n\n\tif err := d.Set(\"tags\", tags.IgnoreAws().Map()); err != nil {\n\t\treturn fmt.Errorf(\"error setting tags: %s\", err)\n\t}\n\n\treturn nil\n}\n\nfunc resourceAwsOrganizationsAccountUpdate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).organizationsconn\n\n\tif d.HasChange(\"parent_id\") {\n\t\to, n := d.GetChange(\"parent_id\")\n\n\t\tinput := &organizations.MoveAccountInput{\n\t\t\tAccountId:           aws.String(d.Id()),\n\t\t\tSourceParentId:      aws.String(o.(string)),\n\t\t\tDestinationParentId: aws.String(n.(string)),\n\t\t}\n\n\t\tif _, err := conn.MoveAccount(input); err != nil {\n\t\t\treturn fmt.Errorf(\"error moving AWS Organizations Account (%s): %s\", d.Id(), err)\n\t\t}\n\t}\n\n\tif d.HasChange(\"tags\") {\n\t\to, n := d.GetChange(\"tags\")\n\n\t\tif err := keyvaluetags.OrganizationsUpdateTags(conn, d.Id(), o, n); err != nil {\n\t\t\treturn fmt.Errorf(\"error updating AWS Organizations Account (%s) tags: %s\", d.Id(), err)\n\t\t}\n\t}\n\n\treturn resourceAwsOrganizationsAccountRead(d, meta)\n}\n\nfunc resourceAwsOrganizationsAccountDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).organizationsconn\n\n\tinput := &organizations.RemoveAccountFromOrganizationInput{\n\t\tAccountId: aws.String(d.Id()),\n\t}\n\tlog.Printf(\"[DEBUG] Removing AWS account from organization: %s\", input)\n\t_, err := conn.RemoveAccountFromOrganization(input)\n\tif err != nil {\n\t\tif isAWSErr(err, organizations.ErrCodeAccountNotFoundException, \"\") {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ resourceAwsOrganizationsAccountStateRefreshFunc returns a resource.StateRefreshFunc\n\/\/ that is used to watch a CreateAccount request\nfunc resourceAwsOrganizationsAccountStateRefreshFunc(conn *organizations.Organizations, id string) resource.StateRefreshFunc {\n\treturn func() (interface{}, string, error) {\n\t\topts := &organizations.DescribeCreateAccountStatusInput{\n\t\t\tCreateAccountRequestId: aws.String(id),\n\t\t}\n\t\tresp, err := conn.DescribeCreateAccountStatus(opts)\n\t\tif err != nil {\n\t\t\tif isAWSErr(err, organizations.ErrCodeCreateAccountStatusNotFoundException, \"\") {\n\t\t\t\tresp = nil\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Error on OrganizationAccountStateRefresh: %s\", err)\n\t\t\t\treturn nil, \"\", err\n\t\t\t}\n\t\t}\n\n\t\tif resp == nil {\n\t\t\t\/\/ Sometimes AWS just has consistency issues and doesn't see\n\t\t\t\/\/ our account yet. Return an empty state.\n\t\t\treturn nil, \"\", nil\n\t\t}\n\n\t\taccountStatus := resp.CreateAccountStatus\n\t\tif *accountStatus.State == organizations.CreateAccountStateFailed {\n\t\t\treturn nil, *accountStatus.State, fmt.Errorf(*accountStatus.FailureReason)\n\t\t}\n\t\treturn accountStatus, *accountStatus.State, nil\n\t}\n}\n\nfunc resourceAwsOrganizationsAccountGetParentId(conn *organizations.Organizations, childId string) (string, error) {\n\tinput := &organizations.ListParentsInput{\n\t\tChildId: aws.String(childId),\n\t}\n\tvar parents []*organizations.Parent\n\n\terr := conn.ListParentsPages(input, func(page *organizations.ListParentsOutput, lastPage bool) bool {\n\t\tparents = append(parents, page.Parents...)\n\n\t\treturn !lastPage\n\t})\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(parents) == 0 {\n\t\treturn \"\", nil\n\t}\n\n\t\/\/ assume there is only a single parent\n\t\/\/ https:\/\/docs.aws.amazon.com\/organizations\/latest\/APIReference\/API_ListParents.html\n\tparent := parents[0]\n\treturn aws.StringValue(parent.Id), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package command\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/funkygao\/gafka\/ctx\"\n\t\"github.com\/funkygao\/gafka\/zk\"\n\t\"github.com\/funkygao\/gocli\"\n\t\"github.com\/funkygao\/golib\/color\"\n\t\"github.com\/funkygao\/golib\/gofmt\"\n\t\"github.com\/funkygao\/golib\/pipestream\"\n\t\"github.com\/ryanuber\/columnize\"\n)\n\ntype Brokers struct {\n\tUi  cli.Ui\n\tCmd string\n\n\tstaleOnly    bool\n\tshowVersions bool\n\tipInNumber   bool\n\tcluster      string\n}\n\nfunc (this *Brokers) Run(args []string) (exitCode int) {\n\tvar (\n\t\tzone  string\n\t\tdebug bool\n\t)\n\tcmdFlags := flag.NewFlagSet(\"brokers\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { this.Ui.Output(this.Help()) }\n\tcmdFlags.StringVar(&zone, \"z\", \"\", \"\")\n\tcmdFlags.StringVar(&this.cluster, \"c\", \"\", \"\")\n\tcmdFlags.BoolVar(&debug, \"debug\", false, \"\")\n\tcmdFlags.BoolVar(&this.ipInNumber, \"n\", false, \"\")\n\tcmdFlags.BoolVar(&this.staleOnly, \"stale\", false, \"\")\n\tcmdFlags.BoolVar(&this.showVersions, \"versions\", false, \"\")\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tif this.showVersions {\n\t\tthis.doShowVersions()\n\t\treturn\n\t}\n\n\tif debug {\n\t\tsarama.Logger = log.New(os.Stderr, color.Magenta(\"[sarama]\"), log.LstdFlags)\n\t}\n\n\tif zone != \"\" {\n\t\tensureZoneValid(zone)\n\n\t\tzkzone := zk.NewZkZone(zk.DefaultConfig(zone, ctx.ZoneZkAddrs(zone)))\n\t\tthis.displayZoneBrokers(zkzone)\n\n\t\treturn\n\t}\n\n\t\/\/ print all brokers on all zones by default\n\tforSortedZones(func(zkzone *zk.ZkZone) {\n\t\tthis.displayZoneBrokers(zkzone)\n\t})\n\n\treturn\n}\n\nfunc (this *Brokers) maxBrokerId(zkzone *zk.ZkZone, clusterName string) int {\n\tvar maxBrokerId int\n\tzkzone.ForSortedBrokers(func(cluster string, liveBrokers map[string]*zk.BrokerZnode) {\n\t\tif cluster == clusterName {\n\t\t\tfor _, b := range liveBrokers {\n\t\t\t\tid, _ := strconv.Atoi(b.Id)\n\t\t\t\tif id > maxBrokerId {\n\t\t\t\t\tmaxBrokerId = id\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n\treturn maxBrokerId\n}\n\nfunc (this *Brokers) displayZoneBrokers(zkzone *zk.ZkZone) {\n\tlines := make([]string, 0)\n\theader := \"Zone|Cluster|Id|Broker|Uptime\"\n\tlines = append(lines, header)\n\n\tn := 0\n\tzkzone.ForSortedBrokers(func(cluster string, liveBrokers map[string]*zk.BrokerZnode) {\n\t\toutputs := this.clusterBrokers(zkzone.Name(), cluster, liveBrokers)\n\t\tn += len(outputs)\n\t\tlines = append(lines, outputs...)\n\t})\n\tif this.staleOnly {\n\t\tthis.Ui.Info(fmt.Sprintf(\"%d problematic brokers in zone[%s]\", n, zkzone.Name()))\n\t} else {\n\t\tthis.Ui.Info(fmt.Sprintf(\"%d brokers in zone[%s]\", n, zkzone.Name()))\n\t}\n\tif len(lines) > 1 {\n\t\t\/\/ lines has header\n\t\tthis.Ui.Output(columnize.SimpleFormat(lines))\n\t}\n}\n\nfunc (this *Brokers) clusterBrokers(zone, cluster string, brokers map[string]*zk.BrokerZnode) []string {\n\tif !patternMatched(cluster, this.cluster) {\n\t\treturn nil\n\t}\n\n\tif brokers == nil || len(brokers) == 0 {\n\t\treturn []string{fmt.Sprintf(\"%s|%s|%s|%s|%s\",\n\t\t\tzone, cluster, \" \", color.Red(\"empty brokers\"), \" \")}\n\t}\n\n\tlines := make([]string, 0, len(brokers))\n\tif this.staleOnly {\n\t\t\/\/ try each broker's aliveness\n\t\tfor brokerId, broker := range brokers {\n\t\t\tcf := sarama.NewConfig()\n\t\t\tcf.Net.ReadTimeout = time.Second * 4\n\t\t\tcf.Net.WriteTimeout = time.Second * 4\n\t\t\tkfk, err := sarama.NewClient([]string{broker.Addr()}, cf)\n\t\t\tif err != nil {\n\t\t\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s|%s|%s\",\n\t\t\t\t\tzone, cluster,\n\t\t\t\t\tbrokerId, broker.Addr(),\n\t\t\t\t\tgofmt.PrettySince(broker.Uptime())))\n\t\t\t} else {\n\t\t\t\tkfk.Close()\n\t\t\t}\n\t\t}\n\n\t\treturn lines\n\t}\n\n\t\/\/ sort by broker id\n\tsortedBrokerIds := make([]string, 0, len(brokers))\n\tfor brokerId, _ := range brokers {\n\t\tsortedBrokerIds = append(sortedBrokerIds, brokerId)\n\t}\n\tsort.Strings(sortedBrokerIds)\n\n\tfor _, brokerId := range sortedBrokerIds {\n\t\tb := brokers[brokerId]\n\t\tuptime := gofmt.PrettySince(b.Uptime())\n\t\tif time.Since(b.Uptime()) < time.Hour*24*7 {\n\t\t\tuptime = color.Green(uptime)\n\t\t}\n\t\tif this.ipInNumber {\n\t\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s|%s|%s\",\n\t\t\t\tzone, cluster,\n\t\t\t\tbrokerId, b.Addr(),\n\t\t\t\tgofmt.PrettySince(b.Uptime())))\n\t\t} else {\n\t\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s|%s|%s\",\n\t\t\t\tzone, cluster,\n\t\t\t\tbrokerId, b.NamedAddr(),\n\t\t\t\tgofmt.PrettySince(b.Uptime())))\n\t\t}\n\n\t}\n\treturn lines\n}\n\nfunc (this *Brokers) doShowVersions() {\n\tkafkaVerExp := regexp.MustCompile(`\/kafka_(?P<ver>[-\\d.]*)\\.jar`)\n\tprocessExp := regexp.MustCompile(`kfk_(?P<process>\\S*)\/config\/server.properties`)\n\n\tcmd := pipestream.New(\"\/usr\/bin\/consul\", \"exec\",\n\t\t\"pgrep\", \"-lf\", \"java\",\n\t\t\"|\", \"grep\", \"-w\", \"kafka\",\n\t\t\"|\", \"grep\", \"-vw\", \"grep\")\n\terr := cmd.Open()\n\tswallow(err)\n\tdefer cmd.Close()\n\n\tscanner := bufio.NewScanner(cmd.Reader())\n\tscanner.Split(bufio.ScanLines)\n\n\tvar (\n\t\tline     string\n\t\tlastLine string\n\t)\n\thosts := make(map[string]struct{})\n\tlines := make([]string, 0)\n\theader := \"Process|Host|Version\"\n\tlines = append(lines, header)\n\trecords := make(map[string]map[string]string) \/\/ {process: {host: ver}}\n\tfor scanner.Scan() {\n\t\tline = scanner.Text()\n\t\tif strings.Contains(line, \"finished with exit code\") {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.Contains(line, \"node(s) completed\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tfields := strings.Fields(line)\n\t\tif len(fields) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, err := strconv.Atoi(fields[1]); err != nil {\n\t\t\t\/\/ field 1 should be pid\n\t\t\t\/\/ if not pid, it continues with last line\n\t\t\tline = lastLine + strings.Join(fields[1:], \" \")\n\n\t\t\t\/\/ redo fields\n\t\t\tfields := strings.Fields(line)\n\t\t\tif len(fields) < 2 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tlastLine = line\n\n\t\t\/\/ version\n\t\tmatched := kafkaVerExp.FindStringSubmatch(line)\n\t\tif len(matched) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tver := matched[1]\n\n\t\t\/\/ process name\n\t\tmatched = processExp.FindStringSubmatch(line)\n\t\tif len(matched) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tprocess := matched[1]\n\n\t\t\/\/ got a valid process record\n\t\tif _, present := records[process]; !present {\n\t\t\trecords[process] = make(map[string]string)\n\t\t}\n\t\thost := fields[0][0 : len(fields[0])-1] \/\/ discard the ending ':'\n\t\thosts[host] = struct{}{}\n\t\trecords[process][host] = ver\n\t}\n\tswallow(scanner.Err())\n\n\tsortedProceses := make([]string, 0, len(records))\n\tfor proc, _ := range records {\n\t\tsortedProceses = append(sortedProceses, proc)\n\t}\n\tsort.Strings(sortedProceses)\n\n\tprocsWithSingleInstance := make([]string, 0)\n\tfor _, proc := range sortedProceses {\n\t\tsortedHosts := make([]string, 0, len(records[proc]))\n\t\tfor host, _ := range records[proc] {\n\t\t\tsortedHosts = append(sortedHosts, host)\n\t\t}\n\t\tsort.Strings(sortedHosts)\n\n\t\tif len(sortedHosts) < 2 {\n\t\t\tprocsWithSingleInstance = append(procsWithSingleInstance, proc)\n\t\t}\n\n\t\tfor _, host := range sortedHosts {\n\t\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s\", proc, host, records[proc][host]))\n\t\t}\n\t}\n\n\tthis.Ui.Output(columnize.SimpleFormat(lines))\n\tthis.Ui.Output(\"\")\n\tthis.Ui.Output(fmt.Sprintf(\"TOTAL %d processes running on %d hosts\",\n\t\tlen(lines)-1, len(hosts)))\n\tif len(procsWithSingleInstance) > 0 {\n\t\tthis.Ui.Output(fmt.Sprintf(\"\\nProcess with 1 SPOF: \"))\n\t\tthis.Ui.Warn(fmt.Sprintf(\"%v\", procsWithSingleInstance))\n\t}\n}\n\nfunc (*Brokers) Synopsis() string {\n\treturn \"Print online brokers from Zookeeper\"\n}\n\nfunc (this *Brokers) Help() string {\n\thelp := fmt.Sprintf(`\nUsage: %s brokers [options]\n\n    Print online brokers from Zookeeper\n\nOptions:\n\n    -z zone\n      Only print brokers within a zone\n\n    -c cluster name\n      Only print brokers of this cluster\n\n    -versions\n      Display kafka instances versions by host\n      Precondition: you MUST install consul on each broker host\n\n    -debug\n\n    -n\n      Show network addresses as numbers\n\n    -stale\n      Only print stale brokers: found in zk but not connectable\n\n`, this.Cmd)\n\treturn strings.TrimSpace(help)\n}\n<commit_msg>display stale broker err info<commit_after>package command\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/funkygao\/gafka\/ctx\"\n\t\"github.com\/funkygao\/gafka\/zk\"\n\t\"github.com\/funkygao\/gocli\"\n\t\"github.com\/funkygao\/golib\/color\"\n\t\"github.com\/funkygao\/golib\/gofmt\"\n\t\"github.com\/funkygao\/golib\/pipestream\"\n\t\"github.com\/ryanuber\/columnize\"\n)\n\ntype Brokers struct {\n\tUi  cli.Ui\n\tCmd string\n\n\tstaleOnly    bool\n\tshowVersions bool\n\tipInNumber   bool\n\tcluster      string\n}\n\nfunc (this *Brokers) Run(args []string) (exitCode int) {\n\tvar (\n\t\tzone  string\n\t\tdebug bool\n\t)\n\tcmdFlags := flag.NewFlagSet(\"brokers\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { this.Ui.Output(this.Help()) }\n\tcmdFlags.StringVar(&zone, \"z\", \"\", \"\")\n\tcmdFlags.StringVar(&this.cluster, \"c\", \"\", \"\")\n\tcmdFlags.BoolVar(&debug, \"debug\", false, \"\")\n\tcmdFlags.BoolVar(&this.ipInNumber, \"n\", false, \"\")\n\tcmdFlags.BoolVar(&this.staleOnly, \"stale\", false, \"\")\n\tcmdFlags.BoolVar(&this.showVersions, \"versions\", false, \"\")\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tif this.showVersions {\n\t\tthis.doShowVersions()\n\t\treturn\n\t}\n\n\tif debug {\n\t\tsarama.Logger = log.New(os.Stderr, color.Magenta(\"[sarama]\"), log.LstdFlags)\n\t}\n\n\tif zone != \"\" {\n\t\tensureZoneValid(zone)\n\n\t\tzkzone := zk.NewZkZone(zk.DefaultConfig(zone, ctx.ZoneZkAddrs(zone)))\n\t\tthis.displayZoneBrokers(zkzone)\n\n\t\treturn\n\t}\n\n\t\/\/ print all brokers on all zones by default\n\tforSortedZones(func(zkzone *zk.ZkZone) {\n\t\tthis.displayZoneBrokers(zkzone)\n\t})\n\n\treturn\n}\n\nfunc (this *Brokers) maxBrokerId(zkzone *zk.ZkZone, clusterName string) int {\n\tvar maxBrokerId int\n\tzkzone.ForSortedBrokers(func(cluster string, liveBrokers map[string]*zk.BrokerZnode) {\n\t\tif cluster == clusterName {\n\t\t\tfor _, b := range liveBrokers {\n\t\t\t\tid, _ := strconv.Atoi(b.Id)\n\t\t\t\tif id > maxBrokerId {\n\t\t\t\t\tmaxBrokerId = id\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n\n\treturn maxBrokerId\n}\n\nfunc (this *Brokers) displayZoneBrokers(zkzone *zk.ZkZone) {\n\tlines := make([]string, 0)\n\theader := \"Zone|Cluster|Id|Broker|Uptime\"\n\tlines = append(lines, header)\n\n\tn := 0\n\tzkzone.ForSortedBrokers(func(cluster string, liveBrokers map[string]*zk.BrokerZnode) {\n\t\toutputs := this.clusterBrokers(zkzone.Name(), cluster, liveBrokers)\n\t\tn += len(outputs)\n\t\tlines = append(lines, outputs...)\n\t})\n\tif this.staleOnly {\n\t\tthis.Ui.Info(fmt.Sprintf(\"%d problematic brokers in zone[%s]\", n, zkzone.Name()))\n\t} else {\n\t\tthis.Ui.Info(fmt.Sprintf(\"%d brokers in zone[%s]\", n, zkzone.Name()))\n\t}\n\tif len(lines) > 1 {\n\t\t\/\/ lines has header\n\t\tthis.Ui.Output(columnize.SimpleFormat(lines))\n\t}\n}\n\nfunc (this *Brokers) clusterBrokers(zone, cluster string, brokers map[string]*zk.BrokerZnode) []string {\n\tif !patternMatched(cluster, this.cluster) {\n\t\treturn nil\n\t}\n\n\tif brokers == nil || len(brokers) == 0 {\n\t\treturn []string{fmt.Sprintf(\"%s|%s|%s|%s|%s\",\n\t\t\tzone, cluster, \" \", color.Red(\"empty brokers\"), \" \")}\n\t}\n\n\tlines := make([]string, 0, len(brokers))\n\tif this.staleOnly {\n\t\t\/\/ try each broker's aliveness\n\t\tfor brokerId, broker := range brokers {\n\t\t\tcf := sarama.NewConfig()\n\t\t\tcf.Net.ReadTimeout = time.Second * 4\n\t\t\tcf.Net.WriteTimeout = time.Second * 4\n\t\t\tkfk, err := sarama.NewClient([]string{broker.Addr()}, cf)\n\t\t\tif err != nil {\n\t\t\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s|%s|%s\",\n\t\t\t\t\tzone, cluster,\n\t\t\t\t\tbrokerId, broker.Addr(),\n\t\t\t\t\tfmt.Sprintf(\"%s: %v\", gofmt.PrettySince(broker.Uptime()), err)))\n\t\t\t} else {\n\t\t\t\tkfk.Close()\n\t\t\t}\n\t\t}\n\n\t\treturn lines\n\t}\n\n\t\/\/ sort by broker id\n\tsortedBrokerIds := make([]string, 0, len(brokers))\n\tfor brokerId, _ := range brokers {\n\t\tsortedBrokerIds = append(sortedBrokerIds, brokerId)\n\t}\n\tsort.Strings(sortedBrokerIds)\n\n\tfor _, brokerId := range sortedBrokerIds {\n\t\tb := brokers[brokerId]\n\t\tuptime := gofmt.PrettySince(b.Uptime())\n\t\tif time.Since(b.Uptime()) < time.Hour*24*7 {\n\t\t\tuptime = color.Green(uptime)\n\t\t}\n\t\tif this.ipInNumber {\n\t\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s|%s|%s\",\n\t\t\t\tzone, cluster,\n\t\t\t\tbrokerId, b.Addr(),\n\t\t\t\tgofmt.PrettySince(b.Uptime())))\n\t\t} else {\n\t\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s|%s|%s\",\n\t\t\t\tzone, cluster,\n\t\t\t\tbrokerId, b.NamedAddr(),\n\t\t\t\tgofmt.PrettySince(b.Uptime())))\n\t\t}\n\n\t}\n\treturn lines\n}\n\nfunc (this *Brokers) doShowVersions() {\n\tkafkaVerExp := regexp.MustCompile(`\/kafka_(?P<ver>[-\\d.]*)\\.jar`)\n\tprocessExp := regexp.MustCompile(`kfk_(?P<process>\\S*)\/config\/server.properties`)\n\n\tcmd := pipestream.New(\"\/usr\/bin\/consul\", \"exec\",\n\t\t\"pgrep\", \"-lf\", \"java\",\n\t\t\"|\", \"grep\", \"-w\", \"kafka\",\n\t\t\"|\", \"grep\", \"-vw\", \"grep\")\n\terr := cmd.Open()\n\tswallow(err)\n\tdefer cmd.Close()\n\n\tscanner := bufio.NewScanner(cmd.Reader())\n\tscanner.Split(bufio.ScanLines)\n\n\tvar (\n\t\tline     string\n\t\tlastLine string\n\t)\n\thosts := make(map[string]struct{})\n\tlines := make([]string, 0)\n\theader := \"Process|Host|Version\"\n\tlines = append(lines, header)\n\trecords := make(map[string]map[string]string) \/\/ {process: {host: ver}}\n\tfor scanner.Scan() {\n\t\tline = scanner.Text()\n\t\tif strings.Contains(line, \"finished with exit code\") {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.Contains(line, \"node(s) completed\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tfields := strings.Fields(line)\n\t\tif len(fields) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif _, err := strconv.Atoi(fields[1]); err != nil {\n\t\t\t\/\/ field 1 should be pid\n\t\t\t\/\/ if not pid, it continues with last line\n\t\t\tline = lastLine + strings.Join(fields[1:], \" \")\n\n\t\t\t\/\/ redo fields\n\t\t\tfields := strings.Fields(line)\n\t\t\tif len(fields) < 2 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tlastLine = line\n\n\t\t\/\/ version\n\t\tmatched := kafkaVerExp.FindStringSubmatch(line)\n\t\tif len(matched) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tver := matched[1]\n\n\t\t\/\/ process name\n\t\tmatched = processExp.FindStringSubmatch(line)\n\t\tif len(matched) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tprocess := matched[1]\n\n\t\t\/\/ got a valid process record\n\t\tif _, present := records[process]; !present {\n\t\t\trecords[process] = make(map[string]string)\n\t\t}\n\t\thost := fields[0][0 : len(fields[0])-1] \/\/ discard the ending ':'\n\t\thosts[host] = struct{}{}\n\t\trecords[process][host] = ver\n\t}\n\tswallow(scanner.Err())\n\n\tsortedProceses := make([]string, 0, len(records))\n\tfor proc, _ := range records {\n\t\tsortedProceses = append(sortedProceses, proc)\n\t}\n\tsort.Strings(sortedProceses)\n\n\tprocsWithSingleInstance := make([]string, 0)\n\tfor _, proc := range sortedProceses {\n\t\tsortedHosts := make([]string, 0, len(records[proc]))\n\t\tfor host, _ := range records[proc] {\n\t\t\tsortedHosts = append(sortedHosts, host)\n\t\t}\n\t\tsort.Strings(sortedHosts)\n\n\t\tif len(sortedHosts) < 2 {\n\t\t\tprocsWithSingleInstance = append(procsWithSingleInstance, proc)\n\t\t}\n\n\t\tfor _, host := range sortedHosts {\n\t\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s\", proc, host, records[proc][host]))\n\t\t}\n\t}\n\n\tthis.Ui.Output(columnize.SimpleFormat(lines))\n\tthis.Ui.Output(\"\")\n\tthis.Ui.Output(fmt.Sprintf(\"TOTAL %d processes running on %d hosts\",\n\t\tlen(lines)-1, len(hosts)))\n\tif len(procsWithSingleInstance) > 0 {\n\t\tthis.Ui.Output(fmt.Sprintf(\"\\nProcess with 1 SPOF: \"))\n\t\tthis.Ui.Warn(fmt.Sprintf(\"%v\", procsWithSingleInstance))\n\t}\n}\n\nfunc (*Brokers) Synopsis() string {\n\treturn \"Print online brokers from Zookeeper\"\n}\n\nfunc (this *Brokers) Help() string {\n\thelp := fmt.Sprintf(`\nUsage: %s brokers [options]\n\n    Print online brokers from Zookeeper\n\nOptions:\n\n    -z zone\n      Only print brokers within a zone\n\n    -c cluster name\n      Only print brokers of this cluster\n\n    -versions\n      Display kafka instances versions by host\n      Precondition: you MUST install consul on each broker host\n\n    -debug\n\n    -n\n      Show network addresses as numbers\n\n    -stale\n      Only print stale brokers: found in zk but not connectable\n\n`, this.Cmd)\n\treturn strings.TrimSpace(help)\n}\n<|endoftext|>"}
{"text":"<commit_before>package command\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\n\t\"github.com\/funkygao\/gafka\/ctx\"\n\t\"github.com\/funkygao\/gafka\/zk\"\n\t\"github.com\/funkygao\/gocli\"\n\t\"github.com\/funkygao\/golib\/color\"\n\t\"github.com\/funkygao\/golib\/pipestream\"\n\t\"github.com\/ryanuber\/columnize\"\n)\n\n\/\/ consul members will include:\n\/\/ - zk cluster as server\n\/\/ - agents\n\/\/   - brokers\n\/\/   - kateway\ntype Members struct {\n\tUi  cli.Ui\n\tCmd string\n\n\tbrokerHosts, zkHosts, katewayHosts map[string]struct{}\n\tnodeHostMap                        map[string]string \/\/ consul members node->ip\n}\n\nfunc (this *Members) Run(args []string) (exitCode int) {\n\tvar (\n\t\tzone        string\n\t\tshowLoadAvg bool\n\t)\n\tcmdFlags := flag.NewFlagSet(\"members\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { this.Ui.Output(this.Help()) }\n\tcmdFlags.StringVar(&zone, \"z\", ctx.ZkDefaultZone(), \"\")\n\tcmdFlags.BoolVar(&showLoadAvg, \"l\", false, \"\")\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tzkzone := zk.NewZkZone(zk.DefaultConfig(zone, ctx.ZoneZkAddrs(zone)))\n\tthis.fillTheHosts(zkzone)\n\n\tconsulLiveNode, consulDeadNodes := this.consulMembers()\n\tfor _, node := range consulDeadNodes {\n\t\tthis.Ui.Error(fmt.Sprintf(\"%s consul dead\", node))\n\t}\n\n\tconsulLiveMap := make(map[string]struct{})\n\tbrokerN, zkN, katewayN, unknownN := 0, 0, 0, 0\n\tfor _, node := range consulLiveNode {\n\t\t_, presentInBroker := this.brokerHosts[node]\n\t\t_, presentInZk := this.zkHosts[node]\n\t\t_, presentInKateway := this.katewayHosts[node]\n\t\tif presentInBroker {\n\t\t\tbrokerN++\n\t\t}\n\t\tif presentInZk {\n\t\t\tzkN++\n\t\t}\n\t\tif presentInKateway {\n\t\t\tkatewayN++\n\t\t}\n\n\t\tif !presentInBroker && !presentInZk && !presentInKateway {\n\t\t\tunknownN++\n\n\t\t\tthis.Ui.Info(fmt.Sprintf(\"? %s\", node))\n\t\t}\n\n\t\tconsulLiveMap[node] = struct{}{}\n\t}\n\n\t\/\/ all brokers should run consul\n\tfor broker, _ := range this.brokerHosts {\n\t\tif _, present := consulLiveMap[broker]; !present {\n\t\t\tthis.Ui.Warn(fmt.Sprintf(\"- %s\", broker))\n\t\t}\n\t}\n\n\tif showLoadAvg {\n\t\tthis.displayLoadAvg()\n\t}\n\n\tthis.Ui.Output(fmt.Sprintf(\"zk:%s broker:%s kateway:%s ?:%s\",\n\t\tcolor.Magenta(\"%d\", zkN),\n\t\tcolor.Magenta(\"%d\", brokerN),\n\t\tcolor.Magenta(\"%d\", katewayN),\n\t\tcolor.Green(\"%d\", unknownN)))\n\n\treturn\n}\n\nfunc (this *Members) fillTheHosts(zkzone *zk.ZkZone) {\n\tthis.brokerHosts = make(map[string]struct{})\n\tzkzone.ForSortedBrokers(func(cluster string, brokers map[string]*zk.BrokerZnode) {\n\t\tfor _, brokerInfo := range brokers {\n\t\t\tthis.brokerHosts[brokerInfo.Host] = struct{}{}\n\t\t}\n\t})\n\n\tthis.zkHosts = make(map[string]struct{})\n\tfor _, addr := range zkzone.ZkAddrList() {\n\t\tzkNode, _, err := net.SplitHostPort(addr)\n\t\tswallow(err)\n\t\tthis.zkHosts[zkNode] = struct{}{}\n\t}\n\n\tthis.katewayHosts = make(map[string]struct{})\n\tkws, err := zkzone.KatewayInfos()\n\tswallow(err)\n\tfor _, kw := range kws {\n\t\thost, _, err := net.SplitHostPort(kw.PubAddr)\n\t\tswallow(err)\n\t\tthis.katewayHosts[host] = struct{}{}\n\t}\n}\n\nfunc (this *Members) displayLoadAvg() {\n\tcmd := pipestream.New(\"consul\", \"exec\",\n\t\t\"uptime\", \"|\", \"grep\", \"load\")\n\terr := cmd.Open()\n\tswallow(err)\n\tdefer cmd.Close()\n\n\tlines := make([]string, 0)\n\theader := \"Node|Host|Role|Load Avg\"\n\tlines = append(lines, header)\n\n\tscanner := bufio.NewScanner(cmd.Reader())\n\tscanner.Split(bufio.ScanLines)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tfields := strings.Fields(line)\n\t\tnode := fields[0]\n\t\tparts := strings.Split(line, \"load average:\")\n\t\tif len(parts) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasSuffix(node, \":\") {\n\t\t\tnode = strings.TrimRight(node, \":\")\n\t\t}\n\n\t\thost := this.nodeHostMap[node]\n\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s|%s\", node, host, this.roleOfHost(host), parts[1]))\n\t}\n\n\tif len(lines) > 1 {\n\t\tthis.Ui.Output(columnize.SimpleFormat(lines))\n\t}\n}\n\nfunc (this *Members) roleOfHost(host string) string {\n\tif _, present := this.brokerHosts[host]; present {\n\t\treturn \"B\"\n\t}\n\tif _, present := this.zkHosts[host]; present {\n\t\treturn \"Z\"\n\t}\n\tif _, present := this.katewayHosts[host]; present {\n\t\treturn \"K\"\n\t}\n\treturn \"?\"\n}\n\nfunc (this *Members) consulMembers() ([]string, []string) {\n\tcmd := pipestream.New(\"consul\", \"members\")\n\terr := cmd.Open()\n\tswallow(err)\n\tdefer cmd.Close()\n\n\tliveHosts, deadHosts := []string{}, []string{}\n\tscanner := bufio.NewScanner(cmd.Reader())\n\tscanner.Split(bufio.ScanLines)\n\tthis.nodeHostMap = make(map[string]string)\n\tfor scanner.Scan() {\n\t\tif strings.Contains(scanner.Text(), \"Protocol\") {\n\t\t\t\/\/ the header\n\t\t\tcontinue\n\t\t}\n\n\t\tfields := strings.Fields(scanner.Text())\n\t\tnode, addr, alive := fields[0], fields[1], fields[2]\n\t\thost, _, err := net.SplitHostPort(addr)\n\t\tswallow(err)\n\n\t\tthis.nodeHostMap[node] = host\n\n\t\tif alive == \"alive\" {\n\t\t\tliveHosts = append(liveHosts, host)\n\t\t} else {\n\t\t\tdeadHosts = append(deadHosts, host)\n\t\t}\n\t}\n\n\treturn liveHosts, deadHosts\n}\n\nfunc (*Members) Synopsis() string {\n\treturn \"Verify consul members match kafka zone\"\n}\n\nfunc (this *Members) Help() string {\n\thelp := fmt.Sprintf(`\nUsage: %s members [options]\n\n    Verify consul members match kafka zone\n\n    -z zone\n\n    -l\n      Display each member load average\n\n`, this.Cmd)\n\treturn strings.TrimSpace(help)\n}\n<commit_msg>member load avg sort by node name<commit_after>package command\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/funkygao\/gafka\/ctx\"\n\t\"github.com\/funkygao\/gafka\/zk\"\n\t\"github.com\/funkygao\/gocli\"\n\t\"github.com\/funkygao\/golib\/color\"\n\t\"github.com\/funkygao\/golib\/pipestream\"\n\t\"github.com\/ryanuber\/columnize\"\n)\n\n\/\/ consul members will include:\n\/\/ - zk cluster as server\n\/\/ - agents\n\/\/   - brokers\n\/\/   - kateway\ntype Members struct {\n\tUi  cli.Ui\n\tCmd string\n\n\tbrokerHosts, zkHosts, katewayHosts map[string]struct{}\n\tnodeHostMap                        map[string]string \/\/ consul members node->ip\n}\n\nfunc (this *Members) Run(args []string) (exitCode int) {\n\tvar (\n\t\tzone        string\n\t\tshowLoadAvg bool\n\t)\n\tcmdFlags := flag.NewFlagSet(\"members\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { this.Ui.Output(this.Help()) }\n\tcmdFlags.StringVar(&zone, \"z\", ctx.ZkDefaultZone(), \"\")\n\tcmdFlags.BoolVar(&showLoadAvg, \"l\", false, \"\")\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tzkzone := zk.NewZkZone(zk.DefaultConfig(zone, ctx.ZoneZkAddrs(zone)))\n\tthis.fillTheHosts(zkzone)\n\n\tconsulLiveNode, consulDeadNodes := this.consulMembers()\n\tfor _, node := range consulDeadNodes {\n\t\tthis.Ui.Error(fmt.Sprintf(\"%s consul dead\", node))\n\t}\n\n\tconsulLiveMap := make(map[string]struct{})\n\tbrokerN, zkN, katewayN, unknownN := 0, 0, 0, 0\n\tfor _, node := range consulLiveNode {\n\t\t_, presentInBroker := this.brokerHosts[node]\n\t\t_, presentInZk := this.zkHosts[node]\n\t\t_, presentInKateway := this.katewayHosts[node]\n\t\tif presentInBroker {\n\t\t\tbrokerN++\n\t\t}\n\t\tif presentInZk {\n\t\t\tzkN++\n\t\t}\n\t\tif presentInKateway {\n\t\t\tkatewayN++\n\t\t}\n\n\t\tif !presentInBroker && !presentInZk && !presentInKateway {\n\t\t\tunknownN++\n\t\t}\n\n\t\tconsulLiveMap[node] = struct{}{}\n\t}\n\n\t\/\/ all brokers should run consul\n\tfor broker, _ := range this.brokerHosts {\n\t\tif _, present := consulLiveMap[broker]; !present {\n\t\t\tthis.Ui.Warn(fmt.Sprintf(\"- %s\", broker))\n\t\t}\n\t}\n\n\tif showLoadAvg {\n\t\tthis.displayLoadAvg()\n\t}\n\n\tthis.Ui.Output(fmt.Sprintf(\"zk:%s broker:%s kateway:%s ?:%s\",\n\t\tcolor.Magenta(\"%d\", zkN),\n\t\tcolor.Magenta(\"%d\", brokerN),\n\t\tcolor.Magenta(\"%d\", katewayN),\n\t\tcolor.Green(\"%d\", unknownN)))\n\n\treturn\n}\n\nfunc (this *Members) fillTheHosts(zkzone *zk.ZkZone) {\n\tthis.brokerHosts = make(map[string]struct{})\n\tzkzone.ForSortedBrokers(func(cluster string, brokers map[string]*zk.BrokerZnode) {\n\t\tfor _, brokerInfo := range brokers {\n\t\t\tthis.brokerHosts[brokerInfo.Host] = struct{}{}\n\t\t}\n\t})\n\n\tthis.zkHosts = make(map[string]struct{})\n\tfor _, addr := range zkzone.ZkAddrList() {\n\t\tzkNode, _, err := net.SplitHostPort(addr)\n\t\tswallow(err)\n\t\tthis.zkHosts[zkNode] = struct{}{}\n\t}\n\n\tthis.katewayHosts = make(map[string]struct{})\n\tkws, err := zkzone.KatewayInfos()\n\tswallow(err)\n\tfor _, kw := range kws {\n\t\thost, _, err := net.SplitHostPort(kw.PubAddr)\n\t\tswallow(err)\n\t\tthis.katewayHosts[host] = struct{}{}\n\t}\n}\n\nfunc (this *Members) displayLoadAvg() {\n\tcmd := pipestream.New(\"consul\", \"exec\",\n\t\t\"uptime\", \"|\", \"grep\", \"load\")\n\terr := cmd.Open()\n\tswallow(err)\n\tdefer cmd.Close()\n\n\tlines := make([]string, 0)\n\theader := \"Node|Host|Role|Load Avg\"\n\tlines = append(lines, header)\n\n\tscanner := bufio.NewScanner(cmd.Reader())\n\tscanner.Split(bufio.ScanLines)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tfields := strings.Fields(line)\n\t\tnode := fields[0]\n\t\tparts := strings.Split(line, \"load average:\")\n\t\tif len(parts) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasSuffix(node, \":\") {\n\t\t\tnode = strings.TrimRight(node, \":\")\n\t\t}\n\n\t\thost := this.nodeHostMap[node]\n\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s|%s\", node, host, this.roleOfHost(host), parts[1]))\n\t}\n\n\tif len(lines) > 1 {\n\t\tsort.Strings(lines[1:])\n\t\tthis.Ui.Output(columnize.SimpleFormat(lines))\n\t}\n}\n\nfunc (this *Members) roleOfHost(host string) string {\n\tif _, present := this.brokerHosts[host]; present {\n\t\treturn \"B\"\n\t}\n\tif _, present := this.zkHosts[host]; present {\n\t\treturn \"Z\"\n\t}\n\tif _, present := this.katewayHosts[host]; present {\n\t\treturn \"K\"\n\t}\n\treturn \"?\"\n}\n\nfunc (this *Members) consulMembers() ([]string, []string) {\n\tcmd := pipestream.New(\"consul\", \"members\")\n\terr := cmd.Open()\n\tswallow(err)\n\tdefer cmd.Close()\n\n\tliveHosts, deadHosts := []string{}, []string{}\n\tscanner := bufio.NewScanner(cmd.Reader())\n\tscanner.Split(bufio.ScanLines)\n\tthis.nodeHostMap = make(map[string]string)\n\tfor scanner.Scan() {\n\t\tif strings.Contains(scanner.Text(), \"Protocol\") {\n\t\t\t\/\/ the header\n\t\t\tcontinue\n\t\t}\n\n\t\tfields := strings.Fields(scanner.Text())\n\t\tnode, addr, alive := fields[0], fields[1], fields[2]\n\t\thost, _, err := net.SplitHostPort(addr)\n\t\tswallow(err)\n\n\t\tthis.nodeHostMap[node] = host\n\n\t\tif alive == \"alive\" {\n\t\t\tliveHosts = append(liveHosts, host)\n\t\t} else {\n\t\t\tdeadHosts = append(deadHosts, host)\n\t\t}\n\t}\n\n\treturn liveHosts, deadHosts\n}\n\nfunc (*Members) Synopsis() string {\n\treturn \"Verify consul members match kafka zone\"\n}\n\nfunc (this *Members) Help() string {\n\thelp := fmt.Sprintf(`\nUsage: %s members [options]\n\n    Verify consul members match kafka zone\n\n    -z zone\n\n    -l\n      Display each member load average\n\n`, this.Cmd)\n\treturn strings.TrimSpace(help)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/binary\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\t\"time\"\n\n\t\"github.com\/golang\/snappy\"\n\t\"github.com\/influxdb\/influxdb\/tsdb\"\n\t\"github.com\/influxdb\/influxdb\/tsdb\/engine\/tsm1\"\n)\n\ntype tsdmDumpOpts struct {\n\tdumpIndex  bool\n\tdumpBlocks bool\n\tfilterKey  string\n\tpath       string\n}\n\ntype tsmIndex struct {\n\tseries  int\n\toffset  int64\n\tminTime time.Time\n\tmaxTime time.Time\n\tblocks  []*block\n}\n\ntype block struct {\n\tid     uint64\n\toffset int64\n}\n\ntype blockStats struct {\n\tmin, max int\n\tcounts   [][]int\n}\n\nfunc (b *blockStats) inc(typ int, enc byte) {\n\tfor len(b.counts) <= typ {\n\t\tb.counts = append(b.counts, []int{})\n\t}\n\tfor len(b.counts[typ]) <= int(enc) {\n\t\tb.counts[typ] = append(b.counts[typ], 0)\n\t}\n\tb.counts[typ][enc]++\n}\n\nfunc (b *blockStats) size(sz int) {\n\tif b.min == 0 || sz < b.min {\n\t\tb.min = sz\n\t}\n\tif b.min == 0 || sz > b.max {\n\t\tb.max = sz\n\t}\n}\n\nvar (\n\tfieldType = []string{\n\t\t\"timestamp\", \"float\", \"int\", \"bool\", \"string\",\n\t}\n\tblockTypes = []string{\n\t\t\"float64\", \"int64\", \"bool\", \"string\",\n\t}\n\ttimeEnc = []string{\n\t\t\"none\", \"s8b\", \"rle\",\n\t}\n\tfloatEnc = []string{\n\t\t\"none\", \"gor\",\n\t}\n\tintEnc = []string{\n\t\t\"none\", \"s8b\", \"rle\",\n\t}\n\tboolEnc = []string{\n\t\t\"none\", \"bp\",\n\t}\n\tstringEnc = []string{\n\t\t\"none\", \"snpy\",\n\t}\n\tencDescs = [][]string{\n\t\ttimeEnc, floatEnc, intEnc, boolEnc, stringEnc,\n\t}\n)\n\nfunc readFields(path string) (map[string]*tsdb.MeasurementFields, error) {\n\tfields := make(map[string]*tsdb.MeasurementFields)\n\n\tf, err := os.OpenFile(filepath.Join(path, tsm1.FieldsFileExtension), os.O_RDONLY, 0666)\n\tif os.IsNotExist(err) {\n\t\treturn fields, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata, err := snappy.Decode(nil, b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := json.Unmarshal(data, &fields); err != nil {\n\t\treturn nil, err\n\t}\n\treturn fields, nil\n}\n\nfunc readSeries(path string) (map[string]*tsdb.Series, error) {\n\tseries := make(map[string]*tsdb.Series)\n\n\tf, err := os.OpenFile(filepath.Join(path, tsm1.SeriesFileExtension), os.O_RDONLY, 0666)\n\tif os.IsNotExist(err) {\n\t\treturn series, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata, err := snappy.Decode(nil, b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := json.Unmarshal(data, &series); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn series, nil\n}\n\nfunc readIds(path string) (map[string]uint64, error) {\n\tf, err := os.OpenFile(filepath.Join(path, tsm1.IDsFileExtension), os.O_RDONLY, 0666)\n\tif os.IsNotExist(err) {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb, err = snappy.Decode(nil, b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tids := make(map[string]uint64)\n\tif b != nil {\n\t\tif err := json.Unmarshal(b, &ids); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn ids, err\n}\nfunc readIndex(f *os.File) (*tsmIndex, error) {\n\t\/\/ Get the file size\n\tstat, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Seek to the series count\n\tf.Seek(-4, os.SEEK_END)\n\tb := make([]byte, 8)\n\t_, err = f.Read(b[:4])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tseriesCount := binary.BigEndian.Uint32(b)\n\n\t\/\/ Get the min time\n\tf.Seek(-20, os.SEEK_END)\n\tf.Read(b)\n\tminTime := time.Unix(0, int64(btou64(b)))\n\n\t\/\/ Get max time\n\tf.Seek(-12, os.SEEK_END)\n\tf.Read(b)\n\tmaxTime := time.Unix(0, int64(btou64(b)))\n\n\t\/\/ Figure out where the index starts\n\tindexStart := stat.Size() - int64(seriesCount*12+20)\n\n\t\/\/ Seek to the start of the index\n\tf.Seek(indexStart, os.SEEK_SET)\n\tcount := int(seriesCount)\n\tindex := &tsmIndex{\n\t\toffset:  indexStart,\n\t\tminTime: minTime,\n\t\tmaxTime: maxTime,\n\t\tseries:  count,\n\t}\n\n\tif indexStart < 0 {\n\t\treturn nil, fmt.Errorf(\"index corrupt: offset=%d\", indexStart)\n\t}\n\n\t\/\/ Read the index entries\n\tfor i := 0; i < count; i++ {\n\t\tf.Read(b)\n\t\tid := binary.BigEndian.Uint64(b)\n\t\tf.Read(b[:4])\n\t\tpos := binary.BigEndian.Uint32(b[:4])\n\t\tindex.blocks = append(index.blocks, &block{id: id, offset: int64(pos)})\n\t}\n\n\treturn index, nil\n}\n\nfunc cmdDumpTsm1(opts *tsdmDumpOpts) {\n\tvar errors []error\n\n\tf, err := os.Open(opts.path)\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Get the file size\n\tstat, err := f.Stat()\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tb := make([]byte, 8)\n\tf.Read(b[:4])\n\n\t\/\/ Verify magic number\n\tif binary.BigEndian.Uint32(b[:4]) != 0x16D116D1 {\n\t\tprintln(\"Not a tsm1 file.\")\n\t\tos.Exit(1)\n\t}\n\n\tids, err := readIds(filepath.Dir(opts.path))\n\tif err != nil {\n\t\tprintln(\"Failed to read series:\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tinvIds := map[uint64]string{}\n\tfor k, v := range ids {\n\t\tinvIds[v] = k\n\t}\n\n\tindex, err := readIndex(f)\n\tif err != nil {\n\t\tprintln(\"Failed to readIndex:\", err.Error())\n\n\t\t\/\/ Create a stubbed out index so we can still try and read the block data directly\n\t\t\/\/ w\/o panicing ourselves.\n\t\tindex = &tsmIndex{\n\t\t\tminTime: time.Unix(0, 0),\n\t\t\tmaxTime: time.Unix(0, 0),\n\t\t\toffset:  stat.Size(),\n\t\t}\n\t}\n\n\tblockStats := &blockStats{}\n\n\tprintln(\"Summary:\")\n\tfmt.Printf(\"  File: %s\\n\", opts.path)\n\tfmt.Printf(\"  Time Range: %s - %s\\n\",\n\t\tindex.minTime.UTC().Format(time.RFC3339Nano),\n\t\tindex.maxTime.UTC().Format(time.RFC3339Nano),\n\t)\n\tfmt.Printf(\"  Duration: %s \", index.maxTime.Sub(index.minTime))\n\tfmt.Printf(\"  Series: %d \", index.series)\n\tfmt.Printf(\"  File Size: %d\\n\", stat.Size())\n\tprintln()\n\n\ttw := tabwriter.NewWriter(os.Stdout, 8, 8, 1, '\\t', 0)\n\tfmt.Fprintln(tw, \"  \"+strings.Join([]string{\"Pos\", \"ID\", \"Ofs\", \"Key\", \"Field\"}, \"\\t\"))\n\tfor i, block := range index.blocks {\n\t\tkey := invIds[block.id]\n\t\tsplit := strings.Split(key, \"#!~#\")\n\n\t\t\/\/ We dont' know know if we have fields so use an informative default\n\t\tvar measurement, field string = \"UNKNOWN\", \"UNKNOWN\"\n\n\t\t\/\/ We read some IDs from the ids file\n\t\tif len(invIds) > 0 {\n\t\t\t\/\/ Change the default to error until we know we have a valid key\n\t\t\tmeasurement = \"ERR\"\n\t\t\tfield = \"ERR\"\n\n\t\t\t\/\/ Possible corruption? Try to read as much as we can and point to the problem.\n\t\t\tif key == \"\" {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"index pos %d, field id: %d, missing key for id\", i, block.id))\n\t\t\t} else if len(split) < 2 {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"index pos %d, field id: %d, key corrupt: got '%v'\", i, block.id, key))\n\t\t\t} else {\n\t\t\t\tmeasurement = split[0]\n\t\t\t\tfield = split[1]\n\t\t\t}\n\t\t}\n\n\t\tif opts.filterKey != \"\" && !strings.Contains(key, opts.filterKey) {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Fprintln(tw, \"  \"+strings.Join([]string{\n\t\t\tstrconv.FormatInt(int64(i), 10),\n\t\t\tstrconv.FormatUint(block.id, 10),\n\t\t\tstrconv.FormatInt(int64(block.offset), 10),\n\t\t\tmeasurement,\n\t\t\tfield,\n\t\t}, \"\\t\"))\n\t}\n\n\tif opts.dumpIndex {\n\t\tprintln(\"Index:\")\n\t\ttw.Flush()\n\t\tprintln()\n\t}\n\n\ttw = tabwriter.NewWriter(os.Stdout, 8, 8, 1, '\\t', 0)\n\tfmt.Fprintln(tw, \"  \"+strings.Join([]string{\"Blk\", \"Ofs\", \"Len\", \"ID\", \"Type\", \"Min Time\", \"Points\", \"Enc [T\/V]\", \"Len [T\/V]\"}, \"\\t\"))\n\n\t\/\/ Staring at 4 because the magic number is 4 bytes\n\ti := int64(4)\n\tvar blockCount, pointCount, blockSize int64\n\tindexSize := stat.Size() - index.offset\n\n\t\/\/ Start at the beginning and read every block\n\tfor i < index.offset {\n\t\tf.Seek(int64(i), 0)\n\n\t\tf.Read(b)\n\t\tid := btou64(b)\n\t\tf.Read(b[:4])\n\t\tlength := binary.BigEndian.Uint32(b[:4])\n\t\tbuf := make([]byte, length)\n\t\tf.Read(buf)\n\n\t\tblockSize += int64(len(buf)) + 12\n\n\t\tstartTime := time.Unix(0, int64(btou64(buf[:8])))\n\t\tblockType := buf[8]\n\n\t\tencoded := buf[9:]\n\n\t\tvar v []tsm1.Value\n\t\terr := tsm1.DecodeBlock(buf, &v)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error: %v\\n\", err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tpointCount += int64(len(v))\n\n\t\t\/\/ Length of the timestamp block\n\t\ttsLen, j := binary.Uvarint(encoded)\n\n\t\t\/\/ Unpack the timestamp bytes\n\t\tts := encoded[int(j) : int(j)+int(tsLen)]\n\n\t\t\/\/ Unpack the value bytes\n\t\tvalues := encoded[int(j)+int(tsLen):]\n\n\t\ttsEncoding := timeEnc[int(ts[0]>>4)]\n\t\tvEncoding := encDescs[int(blockType+1)][values[0]>>4]\n\n\t\ttypeDesc := blockTypes[blockType]\n\n\t\tblockStats.inc(0, ts[0]>>4)\n\t\tblockStats.inc(int(blockType+1), values[0]>>4)\n\t\tblockStats.size(len(buf))\n\n\t\tif opts.filterKey != \"\" && !strings.Contains(invIds[id], opts.filterKey) {\n\t\t\ti += (12 + int64(length))\n\t\t\tblockCount++\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Fprintln(tw, \"  \"+strings.Join([]string{\n\t\t\tstrconv.FormatInt(blockCount, 10),\n\t\t\tstrconv.FormatInt(i, 10),\n\t\t\tstrconv.FormatInt(int64(len(buf)), 10),\n\t\t\tstrconv.FormatUint(id, 10),\n\t\t\ttypeDesc,\n\t\t\tstartTime.UTC().Format(time.RFC3339Nano),\n\t\t\tstrconv.FormatInt(int64(len(v)), 10),\n\t\t\tfmt.Sprintf(\"%s\/%s\", tsEncoding, vEncoding),\n\t\t\tfmt.Sprintf(\"%d\/%d\", len(ts), len(values)),\n\t\t}, \"\\t\"))\n\n\t\ti += (12 + int64(length))\n\t\tblockCount++\n\t}\n\tif opts.dumpBlocks {\n\t\tprintln(\"Blocks:\")\n\t\ttw.Flush()\n\t\tprintln()\n\t}\n\n\tfmt.Printf(\"Statistics\\n\")\n\tfmt.Printf(\"  Blocks:\\n\")\n\tfmt.Printf(\"    Total: %d Size: %d Min: %d Max: %d Avg: %d\\n\",\n\t\tblockCount, blockSize, blockStats.min, blockStats.max, blockSize\/blockCount)\n\tfmt.Printf(\"  Index:\\n\")\n\tfmt.Printf(\"    Total: %d Size: %d\\n\", len(index.blocks), indexSize)\n\tfmt.Printf(\"  Points:\\n\")\n\tfmt.Printf(\"    Total: %d\", pointCount)\n\tprintln()\n\n\tprintln(\"  Encoding:\")\n\tfor i, counts := range blockStats.counts {\n\t\tif len(counts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"    %s: \", strings.Title(fieldType[i]))\n\t\tfor j, v := range counts {\n\t\t\tfmt.Printf(\"\\t%s: %d (%d%%) \", encDescs[i][j], v, int(float64(v)\/float64(blockCount)*100))\n\t\t}\n\t\tprintln()\n\t}\n\tfmt.Printf(\"  Compression:\\n\")\n\tfmt.Printf(\"    Per block: %0.2f bytes\/point\\n\", float64(blockSize)\/float64(pointCount))\n\tfmt.Printf(\"    Total: %0.2f bytes\/point\\n\", float64(stat.Size())\/float64(pointCount))\n\n\tif len(errors) > 0 {\n\t\tprintln()\n\t\tfmt.Printf(\"Errors (%d):\\n\", len(errors))\n\t\tfor _, err := range errors {\n\t\t\tfmt.Printf(\"  * %v\\n\", err)\n\t\t}\n\t\tprintln()\n\t}\n}\n<commit_msg>Update influx_inspect to use new DecodeBlock interface<commit_after>package main\n\nimport (\n\t\"encoding\/binary\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text\/tabwriter\"\n\t\"time\"\n\n\t\"github.com\/golang\/snappy\"\n\t\"github.com\/influxdb\/influxdb\/tsdb\"\n\t\"github.com\/influxdb\/influxdb\/tsdb\/engine\/tsm1\"\n)\n\ntype tsdmDumpOpts struct {\n\tdumpIndex  bool\n\tdumpBlocks bool\n\tfilterKey  string\n\tpath       string\n}\n\ntype tsmIndex struct {\n\tseries  int\n\toffset  int64\n\tminTime time.Time\n\tmaxTime time.Time\n\tblocks  []*block\n}\n\ntype block struct {\n\tid     uint64\n\toffset int64\n}\n\ntype blockStats struct {\n\tmin, max int\n\tcounts   [][]int\n}\n\nfunc (b *blockStats) inc(typ int, enc byte) {\n\tfor len(b.counts) <= typ {\n\t\tb.counts = append(b.counts, []int{})\n\t}\n\tfor len(b.counts[typ]) <= int(enc) {\n\t\tb.counts[typ] = append(b.counts[typ], 0)\n\t}\n\tb.counts[typ][enc]++\n}\n\nfunc (b *blockStats) size(sz int) {\n\tif b.min == 0 || sz < b.min {\n\t\tb.min = sz\n\t}\n\tif b.min == 0 || sz > b.max {\n\t\tb.max = sz\n\t}\n}\n\nvar (\n\tfieldType = []string{\n\t\t\"timestamp\", \"float\", \"int\", \"bool\", \"string\",\n\t}\n\tblockTypes = []string{\n\t\t\"float64\", \"int64\", \"bool\", \"string\",\n\t}\n\ttimeEnc = []string{\n\t\t\"none\", \"s8b\", \"rle\",\n\t}\n\tfloatEnc = []string{\n\t\t\"none\", \"gor\",\n\t}\n\tintEnc = []string{\n\t\t\"none\", \"s8b\", \"rle\",\n\t}\n\tboolEnc = []string{\n\t\t\"none\", \"bp\",\n\t}\n\tstringEnc = []string{\n\t\t\"none\", \"snpy\",\n\t}\n\tencDescs = [][]string{\n\t\ttimeEnc, floatEnc, intEnc, boolEnc, stringEnc,\n\t}\n)\n\nfunc readFields(path string) (map[string]*tsdb.MeasurementFields, error) {\n\tfields := make(map[string]*tsdb.MeasurementFields)\n\n\tf, err := os.OpenFile(filepath.Join(path, tsm1.FieldsFileExtension), os.O_RDONLY, 0666)\n\tif os.IsNotExist(err) {\n\t\treturn fields, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata, err := snappy.Decode(nil, b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := json.Unmarshal(data, &fields); err != nil {\n\t\treturn nil, err\n\t}\n\treturn fields, nil\n}\n\nfunc readSeries(path string) (map[string]*tsdb.Series, error) {\n\tseries := make(map[string]*tsdb.Series)\n\n\tf, err := os.OpenFile(filepath.Join(path, tsm1.SeriesFileExtension), os.O_RDONLY, 0666)\n\tif os.IsNotExist(err) {\n\t\treturn series, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata, err := snappy.Decode(nil, b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := json.Unmarshal(data, &series); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn series, nil\n}\n\nfunc readIds(path string) (map[string]uint64, error) {\n\tf, err := os.OpenFile(filepath.Join(path, tsm1.IDsFileExtension), os.O_RDONLY, 0666)\n\tif os.IsNotExist(err) {\n\t\treturn nil, nil\n\t} else if err != nil {\n\t\treturn nil, err\n\t}\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb, err = snappy.Decode(nil, b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tids := make(map[string]uint64)\n\tif b != nil {\n\t\tif err := json.Unmarshal(b, &ids); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn ids, err\n}\nfunc readIndex(f *os.File) (*tsmIndex, error) {\n\t\/\/ Get the file size\n\tstat, err := f.Stat()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Seek to the series count\n\tf.Seek(-4, os.SEEK_END)\n\tb := make([]byte, 8)\n\t_, err = f.Read(b[:4])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tseriesCount := binary.BigEndian.Uint32(b)\n\n\t\/\/ Get the min time\n\tf.Seek(-20, os.SEEK_END)\n\tf.Read(b)\n\tminTime := time.Unix(0, int64(btou64(b)))\n\n\t\/\/ Get max time\n\tf.Seek(-12, os.SEEK_END)\n\tf.Read(b)\n\tmaxTime := time.Unix(0, int64(btou64(b)))\n\n\t\/\/ Figure out where the index starts\n\tindexStart := stat.Size() - int64(seriesCount*12+20)\n\n\t\/\/ Seek to the start of the index\n\tf.Seek(indexStart, os.SEEK_SET)\n\tcount := int(seriesCount)\n\tindex := &tsmIndex{\n\t\toffset:  indexStart,\n\t\tminTime: minTime,\n\t\tmaxTime: maxTime,\n\t\tseries:  count,\n\t}\n\n\tif indexStart < 0 {\n\t\treturn nil, fmt.Errorf(\"index corrupt: offset=%d\", indexStart)\n\t}\n\n\t\/\/ Read the index entries\n\tfor i := 0; i < count; i++ {\n\t\tf.Read(b)\n\t\tid := binary.BigEndian.Uint64(b)\n\t\tf.Read(b[:4])\n\t\tpos := binary.BigEndian.Uint32(b[:4])\n\t\tindex.blocks = append(index.blocks, &block{id: id, offset: int64(pos)})\n\t}\n\n\treturn index, nil\n}\n\nfunc cmdDumpTsm1(opts *tsdmDumpOpts) {\n\tvar errors []error\n\n\tf, err := os.Open(opts.path)\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Get the file size\n\tstat, err := f.Stat()\n\tif err != nil {\n\t\tprintln(err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tb := make([]byte, 8)\n\tf.Read(b[:4])\n\n\t\/\/ Verify magic number\n\tif binary.BigEndian.Uint32(b[:4]) != 0x16D116D1 {\n\t\tprintln(\"Not a tsm1 file.\")\n\t\tos.Exit(1)\n\t}\n\n\tids, err := readIds(filepath.Dir(opts.path))\n\tif err != nil {\n\t\tprintln(\"Failed to read series:\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tinvIds := map[uint64]string{}\n\tfor k, v := range ids {\n\t\tinvIds[v] = k\n\t}\n\n\tindex, err := readIndex(f)\n\tif err != nil {\n\t\tprintln(\"Failed to readIndex:\", err.Error())\n\n\t\t\/\/ Create a stubbed out index so we can still try and read the block data directly\n\t\t\/\/ w\/o panicing ourselves.\n\t\tindex = &tsmIndex{\n\t\t\tminTime: time.Unix(0, 0),\n\t\t\tmaxTime: time.Unix(0, 0),\n\t\t\toffset:  stat.Size(),\n\t\t}\n\t}\n\n\tblockStats := &blockStats{}\n\n\tprintln(\"Summary:\")\n\tfmt.Printf(\"  File: %s\\n\", opts.path)\n\tfmt.Printf(\"  Time Range: %s - %s\\n\",\n\t\tindex.minTime.UTC().Format(time.RFC3339Nano),\n\t\tindex.maxTime.UTC().Format(time.RFC3339Nano),\n\t)\n\tfmt.Printf(\"  Duration: %s \", index.maxTime.Sub(index.minTime))\n\tfmt.Printf(\"  Series: %d \", index.series)\n\tfmt.Printf(\"  File Size: %d\\n\", stat.Size())\n\tprintln()\n\n\ttw := tabwriter.NewWriter(os.Stdout, 8, 8, 1, '\\t', 0)\n\tfmt.Fprintln(tw, \"  \"+strings.Join([]string{\"Pos\", \"ID\", \"Ofs\", \"Key\", \"Field\"}, \"\\t\"))\n\tfor i, block := range index.blocks {\n\t\tkey := invIds[block.id]\n\t\tsplit := strings.Split(key, \"#!~#\")\n\n\t\t\/\/ We dont' know know if we have fields so use an informative default\n\t\tvar measurement, field string = \"UNKNOWN\", \"UNKNOWN\"\n\n\t\t\/\/ We read some IDs from the ids file\n\t\tif len(invIds) > 0 {\n\t\t\t\/\/ Change the default to error until we know we have a valid key\n\t\t\tmeasurement = \"ERR\"\n\t\t\tfield = \"ERR\"\n\n\t\t\t\/\/ Possible corruption? Try to read as much as we can and point to the problem.\n\t\t\tif key == \"\" {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"index pos %d, field id: %d, missing key for id\", i, block.id))\n\t\t\t} else if len(split) < 2 {\n\t\t\t\terrors = append(errors, fmt.Errorf(\"index pos %d, field id: %d, key corrupt: got '%v'\", i, block.id, key))\n\t\t\t} else {\n\t\t\t\tmeasurement = split[0]\n\t\t\t\tfield = split[1]\n\t\t\t}\n\t\t}\n\n\t\tif opts.filterKey != \"\" && !strings.Contains(key, opts.filterKey) {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Fprintln(tw, \"  \"+strings.Join([]string{\n\t\t\tstrconv.FormatInt(int64(i), 10),\n\t\t\tstrconv.FormatUint(block.id, 10),\n\t\t\tstrconv.FormatInt(int64(block.offset), 10),\n\t\t\tmeasurement,\n\t\t\tfield,\n\t\t}, \"\\t\"))\n\t}\n\n\tif opts.dumpIndex {\n\t\tprintln(\"Index:\")\n\t\ttw.Flush()\n\t\tprintln()\n\t}\n\n\ttw = tabwriter.NewWriter(os.Stdout, 8, 8, 1, '\\t', 0)\n\tfmt.Fprintln(tw, \"  \"+strings.Join([]string{\"Blk\", \"Ofs\", \"Len\", \"ID\", \"Type\", \"Min Time\", \"Points\", \"Enc [T\/V]\", \"Len [T\/V]\"}, \"\\t\"))\n\n\t\/\/ Staring at 4 because the magic number is 4 bytes\n\ti := int64(4)\n\tvar blockCount, pointCount, blockSize int64\n\tindexSize := stat.Size() - index.offset\n\n\t\/\/ Start at the beginning and read every block\n\tfor i < index.offset {\n\t\tf.Seek(int64(i), 0)\n\n\t\tf.Read(b)\n\t\tid := btou64(b)\n\t\tf.Read(b[:4])\n\t\tlength := binary.BigEndian.Uint32(b[:4])\n\t\tbuf := make([]byte, length)\n\t\tf.Read(buf)\n\n\t\tblockSize += int64(len(buf)) + 12\n\n\t\tstartTime := time.Unix(0, int64(btou64(buf[:8])))\n\t\tblockType := buf[8]\n\n\t\tencoded := buf[9:]\n\n\t\tvar v []tsm1.Value\n\t\tv, err := tsm1.DecodeBlock(buf, v)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error: %v\\n\", err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tpointCount += int64(len(v))\n\n\t\t\/\/ Length of the timestamp block\n\t\ttsLen, j := binary.Uvarint(encoded)\n\n\t\t\/\/ Unpack the timestamp bytes\n\t\tts := encoded[int(j) : int(j)+int(tsLen)]\n\n\t\t\/\/ Unpack the value bytes\n\t\tvalues := encoded[int(j)+int(tsLen):]\n\n\t\ttsEncoding := timeEnc[int(ts[0]>>4)]\n\t\tvEncoding := encDescs[int(blockType+1)][values[0]>>4]\n\n\t\ttypeDesc := blockTypes[blockType]\n\n\t\tblockStats.inc(0, ts[0]>>4)\n\t\tblockStats.inc(int(blockType+1), values[0]>>4)\n\t\tblockStats.size(len(buf))\n\n\t\tif opts.filterKey != \"\" && !strings.Contains(invIds[id], opts.filterKey) {\n\t\t\ti += (12 + int64(length))\n\t\t\tblockCount++\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Fprintln(tw, \"  \"+strings.Join([]string{\n\t\t\tstrconv.FormatInt(blockCount, 10),\n\t\t\tstrconv.FormatInt(i, 10),\n\t\t\tstrconv.FormatInt(int64(len(buf)), 10),\n\t\t\tstrconv.FormatUint(id, 10),\n\t\t\ttypeDesc,\n\t\t\tstartTime.UTC().Format(time.RFC3339Nano),\n\t\t\tstrconv.FormatInt(int64(len(v)), 10),\n\t\t\tfmt.Sprintf(\"%s\/%s\", tsEncoding, vEncoding),\n\t\t\tfmt.Sprintf(\"%d\/%d\", len(ts), len(values)),\n\t\t}, \"\\t\"))\n\n\t\ti += (12 + int64(length))\n\t\tblockCount++\n\t}\n\tif opts.dumpBlocks {\n\t\tprintln(\"Blocks:\")\n\t\ttw.Flush()\n\t\tprintln()\n\t}\n\n\tfmt.Printf(\"Statistics\\n\")\n\tfmt.Printf(\"  Blocks:\\n\")\n\tfmt.Printf(\"    Total: %d Size: %d Min: %d Max: %d Avg: %d\\n\",\n\t\tblockCount, blockSize, blockStats.min, blockStats.max, blockSize\/blockCount)\n\tfmt.Printf(\"  Index:\\n\")\n\tfmt.Printf(\"    Total: %d Size: %d\\n\", len(index.blocks), indexSize)\n\tfmt.Printf(\"  Points:\\n\")\n\tfmt.Printf(\"    Total: %d\", pointCount)\n\tprintln()\n\n\tprintln(\"  Encoding:\")\n\tfor i, counts := range blockStats.counts {\n\t\tif len(counts) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"    %s: \", strings.Title(fieldType[i]))\n\t\tfor j, v := range counts {\n\t\t\tfmt.Printf(\"\\t%s: %d (%d%%) \", encDescs[i][j], v, int(float64(v)\/float64(blockCount)*100))\n\t\t}\n\t\tprintln()\n\t}\n\tfmt.Printf(\"  Compression:\\n\")\n\tfmt.Printf(\"    Per block: %0.2f bytes\/point\\n\", float64(blockSize)\/float64(pointCount))\n\tfmt.Printf(\"    Total: %0.2f bytes\/point\\n\", float64(stat.Size())\/float64(pointCount))\n\n\tif len(errors) > 0 {\n\t\tprintln()\n\t\tfmt.Printf(\"Errors (%d):\\n\", len(errors))\n\t\tfor _, err := range errors {\n\t\t\tfmt.Printf(\"  * %v\\n\", err)\n\t\t}\n\t\tprintln()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t. \"launchpad.net\/gocheck\"\n\t\"launchpad.net\/juju-core\/environs\"\n\t\"launchpad.net\/juju-core\/environs\/config\"\n\t\"launchpad.net\/juju-core\/juju\/testing\"\n\t\"launchpad.net\/juju-core\/state\"\n\tcoretesting \"launchpad.net\/juju-core\/testing\"\n\t\"launchpad.net\/juju-core\/version\"\n\t\"launchpad.net\/tomb\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\nvar _ = Suite(&upgraderSuite{})\n\ntype upgraderSuite struct {\n\ttesting.JujuConnSuite\n\toldVarDir string\n}\n\nfunc (s *upgraderSuite) SetUpTest(c *C) {\n\ts.JujuConnSuite.SetUpTest(c)\n\ts.oldVarDir = environs.VarDir\n\tenvirons.VarDir = c.MkDir()\n}\n\nfunc (s *upgraderSuite) TearDownTest(c *C) {\n\tenvirons.VarDir = s.oldVarDir\n\tinvalidVersion = func() {}\n\tsameVersion = func() {}\n\ts.JujuConnSuite.TearDownTest(c)\n}\n\nfunc (s *upgraderSuite) TestUpgraderError(c *C) {\n\tst, err := state.Open(s.StateInfo(c))\n\tc.Assert(err, IsNil)\n\t_, as, upgraderDone := startUpgrader(st)\n\t\/\/ We have no installed tools, so the logic should set the agent\n\t\/\/ tools anyway, but with no URL.\n\tassertEvent(c, as.event, fmt.Sprintf(\"SetAgentTools %s \", version.Current))\n\n\t\/\/ Close the state under the watcher and check that the upgrader dies.\n\tst.Close()\n\tselect {\n\tcase err := <-upgraderDone:\n\t\tc.Assert(err, Not(FitsTypeOf), &UpgradedError{})\n\t\tc.Assert(err, NotNil)\n\tcase <-time.After(500 * time.Millisecond):\n\t\tc.Fatalf(\"upgrader did not stop as expected\")\n\t}\n}\n\nfunc (s *upgraderSuite) TestUpgraderStop(c *C) {\n\tu, as, upgraderDone := startUpgrader(s.State)\n\tassertEvent(c, as.event, fmt.Sprintf(\"SetAgentTools %s \", version.Current))\n\n\terr := u.Stop()\n\tc.Assert(err, IsNil)\n\n\tselect {\n\tcase err := <-upgraderDone:\n\t\tc.Assert(err, IsNil)\n\tcase <-time.After(500 * time.Millisecond):\n\t\tc.Fatalf(\"upgrader did not stop as expected\")\n\t}\n}\n\n\/\/ startUpgrader starts the upgrader using the given machine\n\/\/ for observing and changing agent tools.\nfunc startUpgrader(st *state.State) (u *Upgrader, as *testAgentState, upgraderDone <-chan error) {\n\tas = newTestAgentState()\n\tu = NewUpgrader(st, \"testagent\", as)\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- u.Wait()\n\t}()\n\tupgraderDone = done\n\treturn\n}\n\nfunc (s *upgraderSuite) proposeVersion(c *C, vers version.Number) {\n\tcfg, err := s.State.EnvironConfig()\n\tc.Assert(err, IsNil)\n\tattrs := cfg.AllAttrs()\n\tattrs[\"agent-version\"] = vers.String()\n\tnewCfg, err := config.New(attrs)\n\tc.Assert(err, IsNil)\n\terr = s.State.SetEnvironConfig(newCfg)\n\tc.Assert(err, IsNil)\n}\n\nfunc (s *upgraderSuite) uploadTools(c *C, vers version.Binary) (path string, tools *state.Tools) {\n\ttgz := coretesting.TarGz(\n\t\tcoretesting.NewTarFile(\"juju\", 0777, \"juju contents \"+vers.String()),\n\t\tcoretesting.NewTarFile(\"jujuc\", 0777, \"jujuc contents \"+vers.String()),\n\t\tcoretesting.NewTarFile(\"jujud\", 0777, \"jujud contents \"+vers.String()),\n\t)\n\tstorage := s.Conn.Environ.Storage()\n\terr := storage.Put(environs.ToolsStoragePath(vers), bytes.NewReader(tgz), int64(len(tgz)))\n\tc.Assert(err, IsNil)\n\tpath = environs.ToolsStoragePath(vers)\n\turl, err := s.Conn.Environ.Storage().URL(path)\n\tc.Assert(err, IsNil)\n\treturn path, &state.Tools{URL: url, Binary: vers}\n}\n\nfunc (s *upgraderSuite) TestUpgrader(c *C) {\n\t\/\/ Set up the test hooks.\n\tsameVersionEvent := make(chan struct{}, 10)\n\tsameVersion = func() {\n\t\tsameVersionEvent <- struct{}{}\n\t}\n\tinvalidVersionEvent := make(chan struct{}, 10)\n\tinvalidVersion = func() {\n\t\tinvalidVersionEvent <- struct{}{}\n\t}\n\n\t\/\/ Set up the current version and tools.\n\tversion.Current = version.MustParseBinary(\"1.0.1-foo-bar\")\n\tv1path, v1tools := s.uploadTools(c, version.Current)\n\n\t\/\/ Unpack the \"current\" version of the tools, and delete them from\n\t\/\/ the storage so that we're sure that the uploader isn't trying\n\t\/\/ to fetch them.\n\tresp, err := http.Get(v1tools.URL)\n\tc.Assert(err, IsNil)\n\terr = environs.UnpackTools(v1tools, resp.Body)\n\tc.Assert(err, IsNil)\n\terr = s.Conn.Environ.Storage().Remove(v1path)\n\tc.Assert(err, IsNil)\n\n\t\/\/ Start the upgrader going and check that the tools are those\n\t\/\/ that we set up.\n\t_, as, upgraderDone := startUpgrader(s.State)\n\tassertEvent(c, as.event, \"SetAgentTools 1.0.1-foo-bar \"+v1tools.URL)\n\n\t\/\/ Propose some tools that are not there, and check that it saw\n\t\/\/ the change.\n\ts.proposeVersion(c, version.MustParse(\"1.0.2\"))\n\t<-invalidVersionEvent\n\n\t\/\/ Upload the current tools again, and check that it saw the change.\n\tv1path, v1tools = s.uploadTools(c, version.Current)\n\ts.proposeVersion(c, version.MustParse(\"1.0.3\"))\n\t<-sameVersionEvent\n\n\t\/\/ Upload a two new versions of the tools. We'll test upgrading to these tools.\n\t_, v5tools := s.uploadTools(c, version.MustParseBinary(\"1.0.5-foo-bar\"))\n\t_, v6tools := s.uploadTools(c, version.MustParseBinary(\"1.0.6-foo-bar\"))\n\n\t\/\/ Check that it won't choose tools with a greater version number.\n\ts.proposeVersion(c, version.MustParse(\"1.0.4\"))\n\t<-sameVersionEvent\n\n\ts.proposeVersion(c, v6tools.Number)\n\tselect {\n\tcase err := <-upgraderDone:\n\t\tc.Assert(err, DeepEquals, &UpgradedError{v6tools})\n\tcase <-time.After(500 * time.Millisecond):\n\t\tc.Fatalf(\"upgrader did not stop as expected\")\n\t}\n\n\t\/\/ Check that the upgraded version was really downloaded.\n\tdata, err := ioutil.ReadFile(filepath.Join(environs.ToolsDir(v6tools.Binary), \"jujud\"))\n\tc.Assert(err, IsNil)\n\tc.Assert(string(data), Equals, \"jujud contents 1.0.6-foo-bar\")\n\n\tversion.Current = v6tools.Binary\n\t\/\/ Check that we can start again.\n\t_, as, upgraderDone = startUpgrader(s.State)\n\tassertEvent(c, as.event, \"SetAgentTools 1.0.6-foo-bar \"+v6tools.URL)\n\n\t\/\/ Check that we can downgrade.\n\ts.proposeVersion(c, v5tools.Number)\n\n\tselect {\n\tcase tools := <-upgraderDone:\n\t\tc.Assert(tools, DeepEquals, &UpgradedError{v5tools})\n\tcase <-time.After(500 * time.Millisecond):\n\t\tc.Fatalf(\"upgrader did not stop as expected\")\n\t}\n}\n\nfunc assertEvent(c *C, event <-chan string, want string) {\n\tselect {\n\tcase got := <-event:\n\t\tc.Assert(got, Equals, want)\n\tcase <-time.After(500 * time.Millisecond):\n\t\tc.Fatalf(\"no event received; expected %q\", want)\n\t}\n}\n\ntype testAgentState struct {\n\ttomb.Tomb\n\tevent chan string\n}\n\nfunc newTestAgentState() *testAgentState {\n\treturn &testAgentState{\n\t\tevent: make(chan string),\n\t}\n}\n\nfunc (t *testAgentState) SetAgentTools(tools *state.Tools) error {\n\tt.event <- fmt.Sprintf(\"SetAgentTools %v %s\", tools.Binary, tools.URL)\n\treturn nil\n}\n<commit_msg>cmd\/jujud: fix comment<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t. \"launchpad.net\/gocheck\"\n\t\"launchpad.net\/juju-core\/environs\"\n\t\"launchpad.net\/juju-core\/environs\/config\"\n\t\"launchpad.net\/juju-core\/juju\/testing\"\n\t\"launchpad.net\/juju-core\/state\"\n\tcoretesting \"launchpad.net\/juju-core\/testing\"\n\t\"launchpad.net\/juju-core\/version\"\n\t\"launchpad.net\/tomb\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\nvar _ = Suite(&upgraderSuite{})\n\ntype upgraderSuite struct {\n\ttesting.JujuConnSuite\n\toldVarDir string\n}\n\nfunc (s *upgraderSuite) SetUpTest(c *C) {\n\ts.JujuConnSuite.SetUpTest(c)\n\ts.oldVarDir = environs.VarDir\n\tenvirons.VarDir = c.MkDir()\n}\n\nfunc (s *upgraderSuite) TearDownTest(c *C) {\n\tenvirons.VarDir = s.oldVarDir\n\tinvalidVersion = func() {}\n\tsameVersion = func() {}\n\ts.JujuConnSuite.TearDownTest(c)\n}\n\nfunc (s *upgraderSuite) TestUpgraderError(c *C) {\n\tst, err := state.Open(s.StateInfo(c))\n\tc.Assert(err, IsNil)\n\t_, as, upgraderDone := startUpgrader(st)\n\t\/\/ We have no installed tools, so the logic should set the agent\n\t\/\/ tools anyway, but with no URL.\n\tassertEvent(c, as.event, fmt.Sprintf(\"SetAgentTools %s \", version.Current))\n\n\t\/\/ Close the state under the watcher and check that the upgrader dies.\n\tst.Close()\n\tselect {\n\tcase err := <-upgraderDone:\n\t\tc.Assert(err, Not(FitsTypeOf), &UpgradedError{})\n\t\tc.Assert(err, NotNil)\n\tcase <-time.After(500 * time.Millisecond):\n\t\tc.Fatalf(\"upgrader did not stop as expected\")\n\t}\n}\n\nfunc (s *upgraderSuite) TestUpgraderStop(c *C) {\n\tu, as, upgraderDone := startUpgrader(s.State)\n\tassertEvent(c, as.event, fmt.Sprintf(\"SetAgentTools %s \", version.Current))\n\n\terr := u.Stop()\n\tc.Assert(err, IsNil)\n\n\tselect {\n\tcase err := <-upgraderDone:\n\t\tc.Assert(err, IsNil)\n\tcase <-time.After(500 * time.Millisecond):\n\t\tc.Fatalf(\"upgrader did not stop as expected\")\n\t}\n}\n\n\/\/ startUpgrader starts the upgrader using the given machine\n\/\/ for observing and changing agent tools.\nfunc startUpgrader(st *state.State) (u *Upgrader, as *testAgentState, upgraderDone <-chan error) {\n\tas = newTestAgentState()\n\tu = NewUpgrader(st, \"testagent\", as)\n\tdone := make(chan error, 1)\n\tgo func() {\n\t\tdone <- u.Wait()\n\t}()\n\tupgraderDone = done\n\treturn\n}\n\nfunc (s *upgraderSuite) proposeVersion(c *C, vers version.Number) {\n\tcfg, err := s.State.EnvironConfig()\n\tc.Assert(err, IsNil)\n\tattrs := cfg.AllAttrs()\n\tattrs[\"agent-version\"] = vers.String()\n\tnewCfg, err := config.New(attrs)\n\tc.Assert(err, IsNil)\n\terr = s.State.SetEnvironConfig(newCfg)\n\tc.Assert(err, IsNil)\n}\n\nfunc (s *upgraderSuite) uploadTools(c *C, vers version.Binary) (path string, tools *state.Tools) {\n\ttgz := coretesting.TarGz(\n\t\tcoretesting.NewTarFile(\"juju\", 0777, \"juju contents \"+vers.String()),\n\t\tcoretesting.NewTarFile(\"jujuc\", 0777, \"jujuc contents \"+vers.String()),\n\t\tcoretesting.NewTarFile(\"jujud\", 0777, \"jujud contents \"+vers.String()),\n\t)\n\tstorage := s.Conn.Environ.Storage()\n\terr := storage.Put(environs.ToolsStoragePath(vers), bytes.NewReader(tgz), int64(len(tgz)))\n\tc.Assert(err, IsNil)\n\tpath = environs.ToolsStoragePath(vers)\n\turl, err := s.Conn.Environ.Storage().URL(path)\n\tc.Assert(err, IsNil)\n\treturn path, &state.Tools{URL: url, Binary: vers}\n}\n\nfunc (s *upgraderSuite) TestUpgrader(c *C) {\n\t\/\/ Set up the test hooks.\n\tsameVersionEvent := make(chan struct{}, 10)\n\tsameVersion = func() {\n\t\tsameVersionEvent <- struct{}{}\n\t}\n\tinvalidVersionEvent := make(chan struct{}, 10)\n\tinvalidVersion = func() {\n\t\tinvalidVersionEvent <- struct{}{}\n\t}\n\n\t\/\/ Set up the current version and tools.\n\tversion.Current = version.MustParseBinary(\"1.0.1-foo-bar\")\n\tv1path, v1tools := s.uploadTools(c, version.Current)\n\n\t\/\/ Unpack the \"current\" version of the tools, and delete them from\n\t\/\/ the storage so that we're sure that the uploader isn't trying\n\t\/\/ to fetch them.\n\tresp, err := http.Get(v1tools.URL)\n\tc.Assert(err, IsNil)\n\terr = environs.UnpackTools(v1tools, resp.Body)\n\tc.Assert(err, IsNil)\n\terr = s.Conn.Environ.Storage().Remove(v1path)\n\tc.Assert(err, IsNil)\n\n\t\/\/ Start the upgrader going and check that the tools are those\n\t\/\/ that we set up.\n\t_, as, upgraderDone := startUpgrader(s.State)\n\tassertEvent(c, as.event, \"SetAgentTools 1.0.1-foo-bar \"+v1tools.URL)\n\n\t\/\/ Propose some tools that are not there, and check that it saw\n\t\/\/ the change.\n\ts.proposeVersion(c, version.MustParse(\"1.0.2\"))\n\t<-invalidVersionEvent\n\n\t\/\/ Upload the current tools again, and check that it saw the change.\n\tv1path, v1tools = s.uploadTools(c, version.Current)\n\ts.proposeVersion(c, version.MustParse(\"1.0.3\"))\n\t<-sameVersionEvent\n\n\t\/\/ Upload two new versions of the tools. We'll test upgrading to these tools.\n\t_, v5tools := s.uploadTools(c, version.MustParseBinary(\"1.0.5-foo-bar\"))\n\t_, v6tools := s.uploadTools(c, version.MustParseBinary(\"1.0.6-foo-bar\"))\n\n\t\/\/ Check that it won't choose tools with a greater version number.\n\ts.proposeVersion(c, version.MustParse(\"1.0.4\"))\n\t<-sameVersionEvent\n\n\ts.proposeVersion(c, v6tools.Number)\n\tselect {\n\tcase err := <-upgraderDone:\n\t\tc.Assert(err, DeepEquals, &UpgradedError{v6tools})\n\tcase <-time.After(500 * time.Millisecond):\n\t\tc.Fatalf(\"upgrader did not stop as expected\")\n\t}\n\n\t\/\/ Check that the upgraded version was really downloaded.\n\tdata, err := ioutil.ReadFile(filepath.Join(environs.ToolsDir(v6tools.Binary), \"jujud\"))\n\tc.Assert(err, IsNil)\n\tc.Assert(string(data), Equals, \"jujud contents 1.0.6-foo-bar\")\n\n\tversion.Current = v6tools.Binary\n\t\/\/ Check that we can start again.\n\t_, as, upgraderDone = startUpgrader(s.State)\n\tassertEvent(c, as.event, \"SetAgentTools 1.0.6-foo-bar \"+v6tools.URL)\n\n\t\/\/ Check that we can downgrade.\n\ts.proposeVersion(c, v5tools.Number)\n\n\tselect {\n\tcase tools := <-upgraderDone:\n\t\tc.Assert(tools, DeepEquals, &UpgradedError{v5tools})\n\tcase <-time.After(500 * time.Millisecond):\n\t\tc.Fatalf(\"upgrader did not stop as expected\")\n\t}\n}\n\nfunc assertEvent(c *C, event <-chan string, want string) {\n\tselect {\n\tcase got := <-event:\n\t\tc.Assert(got, Equals, want)\n\tcase <-time.After(500 * time.Millisecond):\n\t\tc.Fatalf(\"no event received; expected %q\", want)\n\t}\n}\n\ntype testAgentState struct {\n\ttomb.Tomb\n\tevent chan string\n}\n\nfunc newTestAgentState() *testAgentState {\n\treturn &testAgentState{\n\t\tevent: make(chan string),\n\t}\n}\n\nfunc (t *testAgentState) SetAgentTools(tools *state.Tools) error {\n\tt.event <- fmt.Sprintf(\"SetAgentTools %v %s\", tools.Binary, tools.URL)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n *  Copyright 2014 Paul Querna\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *\/\n\npackage ff\n\ntype SweetInterface interface {\n\tCats() int\n}\n\ntype Cats struct {\n\tFieldOnCats int\n}\n\nfunc (c *Cats) Cats() int {\n\treturn 42\n}\n\ntype Embed struct {\n\tSuperBool bool\n}\n\ntype Everything struct {\n\tEmbed\n\tBool             bool\n\tInt              int\n\tInt8             int8\n\tInt16            int16\n\tInt32            int32\n\tInt64            int64\n\tUint             uint\n\tUint8            uint8\n\tUint16           uint16\n\tUint32           uint32\n\tUint64           uint64\n\tUintptr          uintptr\n\tFloat32          float32\n\tFloat64          float64\n\tArray            []int\n\tMap              map[string]int\n\tString           string\n\tStringPointer    *string\n\tInt64Pointer     *int64\n\tFooStruct        *Foo\n\tMySweetInterface SweetInterface\n\tnonexported\n}\n\ntype nonexported struct {\n\tSomething int8\n}\n\ntype Foo struct {\n\tBar int\n}\n\nfunc NewEverything(e *Everything) {\n\te.SuperBool = true\n\te.Bool = true\n\te.Int = 1\n\te.Int8 = 2\n\te.Int16 = 3\n\te.Int32 = -4\n\te.Int64 = 2 ^ 59\n\te.Uint = 100\n\te.Uint8 = 101\n\te.Uint16 = 102\n\te.Uint64 = 103\n\te.Uintptr = 104\n\te.Float32 = 3.14\n\te.Float64 = 3.15\n\te.Array = []int{1, 2, 3}\n\te.Map = map[string]int{\n\t\t\"foo\": 1,\n\t\t\"bar\": 2,\n\t}\n\te.String = \"snowman->☃\"\n\te.FooStruct = &Foo{Bar: 1}\n\te.Something = 99\n\te.MySweetInterface = &Cats{}\n}\n<commit_msg>Add array case to \"everything\" test<commit_after>\/**\n *  Copyright 2014 Paul Querna\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *\/\n\npackage ff\n\ntype SweetInterface interface {\n\tCats() int\n}\n\ntype Cats struct {\n\tFieldOnCats int\n}\n\nfunc (c *Cats) Cats() int {\n\treturn 42\n}\n\ntype Embed struct {\n\tSuperBool bool\n}\n\ntype Everything struct {\n\tEmbed\n\tBool             bool\n\tInt              int\n\tInt8             int8\n\tInt16            int16\n\tInt32            int32\n\tInt64            int64\n\tUint             uint\n\tUint8            uint8\n\tUint16           uint16\n\tUint32           uint32\n\tUint64           uint64\n\tUintptr          uintptr\n\tFloat32          float32\n\tFloat64          float64\n\tArray            [2]int\n\tSlice            []int\n\tMap              map[string]int\n\tString           string\n\tStringPointer    *string\n\tInt64Pointer     *int64\n\tFooStruct        *Foo\n\tMySweetInterface SweetInterface\n\tnonexported\n}\n\ntype nonexported struct {\n\tSomething int8\n}\n\ntype Foo struct {\n\tBar int\n}\n\nfunc NewEverything(e *Everything) {\n\te.SuperBool = true\n\te.Bool = true\n\te.Int = 1\n\te.Int8 = 2\n\te.Int16 = 3\n\te.Int32 = -4\n\te.Int64 = 2 ^ 59\n\te.Uint = 100\n\te.Uint8 = 101\n\te.Uint16 = 102\n\te.Uint64 = 103\n\te.Uintptr = 104\n\te.Float32 = 3.14\n\te.Float64 = 3.15\n\te.Array = [2]int{11, 12}\n\te.Slice = []int{1, 2, 3}\n\te.Map = map[string]int{\n\t\t\"foo\": 1,\n\t\t\"bar\": 2,\n\t}\n\te.String = \"snowman->☃\"\n\te.FooStruct = &Foo{Bar: 1}\n\te.Something = 99\n\te.MySweetInterface = &Cats{}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build !windows\n\npackage libcrypto\n\n\/\/ #include <openssl\/evp.h>\n\/\/ #include <openssl\/dh.h>\n\/\/ #include <openssl\/ec.h>\n\/\/ #include <openssl\/obj_mac.h>\nimport \"C\"\nimport (\n\t\"errors\"\n\t\"github.com\/mkobetic\/okapi\"\n\t\"unsafe\"\n)\n\nfunc init() {\n\tokapi.DH = DH.constructor()\n}\n\ntype dhParameters struct {\n\tecc bool\n}\n\nvar (\n\tDH         = dhParameters{ecc: false}\n\tECDH       = dhParameters{ecc: true}\n\tsize2curve = map[int]C.int{224: C.NID_secp224r1, 384: C.NID_secp384r1, 521: C.NID_secp521r1}\n)\n\nfunc (p dhParameters) constructor() okapi.KeyConstructor {\n\treturn func(keyParameters interface{}) (okapi.PrivateKey, error) {\n\t\treturn NewPKey(keyParameters, p)\n\t}\n}\n\nfunc (p dhParameters) configure(key *PKey) {\n\tkey.parameters = p\n\tif !key.public {\n\t\tcheck1(C.EVP_PKEY_derive_init(key.ctx))\n\t}\n}\n\nfunc (p dhParameters) isForEncryption() bool   { return false }\nfunc (p dhParameters) isForSigning() bool      { return false }\nfunc (p dhParameters) isForKeyAgreement() bool { return true }\n\nfunc (p dhParameters) toPublic(pri *PKey) (pub *PKey, err error) {\n\tif p.ecc {\n\t\treturn nil, errors.New(\"TODO\")\n\t}\n\t\/\/ This is butt ugly, but it seems that the only way to create\n\t\/\/ a public EVP_PKEY for DH is to create a key from the parameters\n\t\/\/ and then manually copy the pub_key member of the internal DH key over.\n\tdh1 := (*C.DH)(C.EVP_PKEY_get1_DH(pri.pkey))\n\tif dh1 == nil {\n\t\treturn nil, errors.New(libcryptoError())\n\t}\n\tsize := C.i2d_DHparams(dh1, nil)\n\tbytes := make([]byte, int(size))\n\tbytesp := (*C.uchar)(&bytes[0])\n\tsize = C.i2d_DHparams(dh1, &bytesp)\n\tbytesp = (*C.uchar)(&bytes[0])\n\tdh2 := C.d2i_DHparams(nil, &bytesp, (C.long)(size))\n\tif dh2 == nil {\n\t\treturn nil, errors.New(libcryptoError())\n\t}\n\tdh2.pub_key = C.BN_dup(dh1.pub_key)\n\tpkey := C.EVP_PKEY_new()\n\t\/\/ err := error1(C.EVP_PKEY_assign_DH(pkey, dh2))\n\terr = error1(C.EVP_PKEY_assign(pkey, C.EVP_PKEY_DH, unsafe.Pointer(dh2)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpub = &PKey{pkey: pkey, public: true, parameters: pri.parameters}\n\tctx := C.EVP_PKEY_CTX_new(pkey, nil)\n\tif ctx == nil {\n\t\tC.EVP_PKEY_free(pkey)\n\t\treturn nil, errors.New(libcryptoError())\n\t}\n\tpub.ctx = ctx\n\tpri.parameters.configure(pub)\n\treturn pub, nil\n}\n\nfunc (p dhParameters) keyType() C.int {\n\tif p.ecc {\n\t\treturn C.EVP_PKEY_EC\n\t} else {\n\t\treturn C.EVP_PKEY_DH\n\t}\n}\n\nfunc (p dhParameters) generate(size int) (*PKey, error) {\n\tpkey, err := newDHParams(size, p.keyType())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newPKeyFromParams(pkey)\n}\n\nfunc newDHParams(size int, keyType C.int) (*C.EVP_PKEY, error) {\n\tctx := C.EVP_PKEY_CTX_new_id(keyType, nil)\n\tif ctx == nil {\n\t\treturn nil, errors.New(\"Failed EVP_PKEY_CTX_new_id\")\n\t}\n\tdefer C.EVP_PKEY_CTX_free(ctx)\n\terr := error1(C.EVP_PKEY_paramgen_init(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif keyType == C.EVP_PKEY_EC {\n\t\t\/\/ Following macro didn't work:\n\t\t\/\/ err = error1(C.EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, size2curve[size]))\n\t\terr = error1(C.EVP_PKEY_CTX_ctrl(ctx, C.EVP_PKEY_EC, C.EVP_PKEY_OP_PARAMGEN, C.EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, size2curve[size], nil))\n\t} else {\n\t\t\/\/ Following macro didn't work:\n\t\t\/\/ err = error1(C.EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, size))\n\t\terr = error1(C.EVP_PKEY_CTX_ctrl(ctx, C.EVP_PKEY_DH, C.EVP_PKEY_OP_PARAMGEN, C.EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN, C.int(size), nil))\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar pkey *C.EVP_PKEY\n\terr = error1(C.EVP_PKEY_paramgen(ctx, &pkey))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pkey, nil\n}\n<commit_msg>minor fix<commit_after>\/\/ +build !windows\n\npackage libcrypto\n\n\/\/ #include <openssl\/evp.h>\n\/\/ #include <openssl\/dh.h>\n\/\/ #include <openssl\/ec.h>\n\/\/ #include <openssl\/obj_mac.h>\nimport \"C\"\nimport (\n\t\"errors\"\n\t\"github.com\/mkobetic\/okapi\"\n\t\"unsafe\"\n)\n\nfunc init() {\n\tokapi.DH = DH.constructor()\n}\n\ntype dhParameters struct {\n\tecc bool\n}\n\nvar (\n\tDH   = dhParameters{ecc: false}\n\tECDH = dhParameters{ecc: true}\n\t\/\/ size2curve = map[int]C.int{224: C.NID_secp224r1, 384: C.NID_secp384r1, 521: C.NID_secp521r1}\n)\n\nfunc (p dhParameters) constructor() okapi.KeyConstructor {\n\treturn func(keyParameters interface{}) (okapi.PrivateKey, error) {\n\t\treturn NewPKey(keyParameters, p)\n\t}\n}\n\nfunc (p dhParameters) configure(key *PKey) {\n\tkey.parameters = p\n\tif !key.public {\n\t\tcheck1(C.EVP_PKEY_derive_init(key.ctx))\n\t}\n}\n\nfunc (p dhParameters) isForEncryption() bool   { return false }\nfunc (p dhParameters) isForSigning() bool      { return false }\nfunc (p dhParameters) isForKeyAgreement() bool { return true }\n\nfunc (p dhParameters) toPublic(pri *PKey) (pub *PKey, err error) {\n\tif p.ecc {\n\t\treturn nil, errors.New(\"TODO\")\n\t}\n\t\/\/ This is butt ugly, but it seems that the only way to create\n\t\/\/ a public EVP_PKEY for DH is to create a key from the parameters\n\t\/\/ and then manually copy the pub_key member of the internal DH key over.\n\tdh1 := (*C.DH)(C.EVP_PKEY_get1_DH(pri.pkey))\n\tif dh1 == nil {\n\t\treturn nil, errors.New(libcryptoError())\n\t}\n\tsize := C.i2d_DHparams(dh1, nil)\n\tbytes := make([]byte, int(size))\n\tbytesp := (*C.uchar)(&bytes[0])\n\tsize = C.i2d_DHparams(dh1, &bytesp)\n\tbytesp = (*C.uchar)(&bytes[0])\n\tdh2 := C.d2i_DHparams(nil, &bytesp, (C.long)(size))\n\tif dh2 == nil {\n\t\treturn nil, errors.New(libcryptoError())\n\t}\n\tdh2.pub_key = C.BN_dup(dh1.pub_key)\n\tpkey := C.EVP_PKEY_new()\n\t\/\/ err := error1(C.EVP_PKEY_assign_DH(pkey, dh2))\n\terr = error1(C.EVP_PKEY_assign(pkey, C.EVP_PKEY_DH, unsafe.Pointer(dh2)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpub = &PKey{pkey: pkey, public: true, parameters: pri.parameters}\n\tctx := C.EVP_PKEY_CTX_new(pkey, nil)\n\tif ctx == nil {\n\t\tC.EVP_PKEY_free(pkey)\n\t\treturn nil, errors.New(libcryptoError())\n\t}\n\tpub.ctx = ctx\n\tpri.parameters.configure(pub)\n\treturn pub, nil\n}\n\nfunc (p dhParameters) keyType() C.int {\n\tif p.ecc {\n\t\treturn C.EVP_PKEY_EC\n\t} else {\n\t\treturn C.EVP_PKEY_DH\n\t}\n}\n\nfunc (p dhParameters) generate(size int) (*PKey, error) {\n\tpkey, err := newDHParams(size, p.keyType())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newPKeyFromParams(pkey)\n}\n\nfunc newDHParams(size int, keyType C.int) (*C.EVP_PKEY, error) {\n\tctx := C.EVP_PKEY_CTX_new_id(keyType, nil)\n\tif ctx == nil {\n\t\treturn nil, errors.New(\"Failed EVP_PKEY_CTX_new_id\")\n\t}\n\tdefer C.EVP_PKEY_CTX_free(ctx)\n\terr := error1(C.EVP_PKEY_paramgen_init(ctx))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif keyType == C.EVP_PKEY_EC {\n\t\t\/\/ Following macro didn't work:\n\t\t\/\/ err = error1(C.EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, size2curve[size]))\n\t\terr = error1(C.EVP_PKEY_CTX_ctrl(ctx, C.EVP_PKEY_EC, C.EVP_PKEY_OP_PARAMGEN, C.EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID, size2curve[size], nil))\n\t} else {\n\t\t\/\/ Following macro didn't work:\n\t\t\/\/ err = error1(C.EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, size))\n\t\terr = error1(C.EVP_PKEY_CTX_ctrl(ctx, C.EVP_PKEY_DH, C.EVP_PKEY_OP_PARAMGEN, C.EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN, C.int(size), nil))\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar pkey *C.EVP_PKEY\n\terr = error1(C.EVP_PKEY_paramgen(ctx, &pkey))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pkey, nil\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Resolve escaped newline<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2020 Docker, Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage convert\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"github.com\/compose-spec\/compose-go\/types\"\n\n\t\"github.com\/docker\/api\/errdefs\"\n)\n\n\/\/ GetRunVolumes return volume configurations for a project and a single service\n\/\/ this is meant to be used as a compose project of a single service\nfunc GetRunVolumes(volumes []string) (map[string]types.VolumeConfig, []types.ServiceVolumeConfig, error) {\n\tvar serviceConfigVolumes []types.ServiceVolumeConfig\n\tprojectVolumes := make(map[string]types.VolumeConfig, len(volumes))\n\tfor i, v := range volumes {\n\t\tvar vi volumeInput\n\t\terr := vi.parse(fmt.Sprintf(\"volume-%d\", i), v)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tprojectVolumes[vi.name] = types.VolumeConfig{\n\t\t\tName:   vi.name,\n\t\t\tDriver: azureFileDriverName,\n\t\t\tDriverOpts: map[string]string{\n\t\t\t\tvolumeDriveroptsAccountNameKey: vi.username,\n\t\t\t\tvolumeDriveroptsAccountKeyKey:  vi.key,\n\t\t\t\tvolumeDriveroptsShareNameKey:   vi.share,\n\t\t\t},\n\t\t}\n\t\tsv := types.ServiceVolumeConfig{\n\t\t\tType:   azureFileDriverName,\n\t\t\tSource: vi.name,\n\t\t\tTarget: vi.target,\n\t\t}\n\t\tserviceConfigVolumes = append(serviceConfigVolumes, sv)\n\t}\n\n\treturn projectVolumes, serviceConfigVolumes, nil\n}\n\ntype volumeInput struct {\n\tname     string\n\tusername string\n\tkey      string\n\tshare    string\n\ttarget   string\n}\n\nfunc escapeKeySlashes(rawURL string) (string, error) {\n\turlSplit := strings.Split(rawURL, \"@\")\n\tif len(urlSplit) < 1 {\n\t\treturn \"\", errors.Wrap(errdefs.ErrParsingFailed, \"invalid url format \"+rawURL)\n\t}\n\tuserPasswd := strings.ReplaceAll(urlSplit[0], \"\/\", \"_\")\n\n\tatIndex := strings.Index(rawURL, \"@\")\n\tif atIndex < 0 {\n\t\treturn \"\", errors.Wrap(errdefs.ErrParsingFailed, \"no share specified in \"+rawURL)\n\t}\n\n\tscaped := userPasswd + rawURL[atIndex:]\n\n\treturn scaped, nil\n}\n\nfunc unescapeKey(key string) string {\n\treturn strings.ReplaceAll(key, \"_\", \"\/\")\n}\n\n\/\/ Removes the second ':' that separates the source from target\nfunc volumeURL(pathURL string) (*url.URL, error) {\n\tscapedURL, err := escapeKeySlashes(pathURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpathURL = \"\/\/\" + scapedURL\n\n\tcount := strings.Count(pathURL, \":\")\n\tif count > 2 {\n\t\treturn nil, errors.Wrap(errdefs.ErrParsingFailed, fmt.Sprintf(\"unable to parse volume mount %q\", pathURL))\n\t}\n\tif count == 2 {\n\t\ttokens := strings.Split(pathURL, \":\")\n\t\tpathURL = fmt.Sprintf(\"%s:%s%s\", tokens[0], tokens[1], tokens[2])\n\t}\n\treturn url.Parse(pathURL)\n}\n\nfunc (v *volumeInput) parse(name string, s string) error {\n\tvolumeURL, err := volumeURL(s)\n\tif err != nil {\n\t\treturn errors.Wrap(errdefs.ErrParsingFailed, fmt.Sprintf(\"volume specification %q could not be parsed %q\", s, err))\n\t}\n\tv.username = volumeURL.User.Username()\n\tif v.username == \"\" {\n\t\treturn errors.Wrap(errdefs.ErrParsingFailed, fmt.Sprintf(\"volume specification %q does not include a storage username\", v))\n\t}\n\tkey, ok := volumeURL.User.Password()\n\tif !ok || key == \"\" {\n\t\treturn errors.Wrap(errdefs.ErrParsingFailed, fmt.Sprintf(\"volume specification %q does not include a storage key\", v))\n\t}\n\tv.key = unescapeKey(key)\n\tv.share = volumeURL.Host\n\tif v.share == \"\" {\n\t\treturn errors.Wrap(errdefs.ErrParsingFailed, fmt.Sprintf(\"volume specification %q does not include a storage file share\", v))\n\t}\n\tv.name = name\n\tv.target = volumeURL.Path\n\tif v.target == \"\" {\n\t\t\/\/ Do not use filepath.Join, on Windows it will replace \/ by \\\n\t\tv.target = \"\/run\/volumes\/\" + v.share\n\t}\n\treturn nil\n}\n<commit_msg>azure: Clean up volume parsing functions<commit_after>\/*\n   Copyright 2020 Docker, Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage convert\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"github.com\/compose-spec\/compose-go\/types\"\n\n\t\"github.com\/docker\/api\/errdefs\"\n)\n\n\/\/ GetRunVolumes return volume configurations for a project and a single service\n\/\/ this is meant to be used as a compose project of a single service\nfunc GetRunVolumes(volumes []string) (map[string]types.VolumeConfig, []types.ServiceVolumeConfig, error) {\n\tvar serviceConfigVolumes []types.ServiceVolumeConfig\n\tprojectVolumes := make(map[string]types.VolumeConfig, len(volumes))\n\tfor i, v := range volumes {\n\t\tvar vi volumeInput\n\t\terr := vi.parse(fmt.Sprintf(\"volume-%d\", i), v)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tprojectVolumes[vi.name] = types.VolumeConfig{\n\t\t\tName:   vi.name,\n\t\t\tDriver: azureFileDriverName,\n\t\t\tDriverOpts: map[string]string{\n\t\t\t\tvolumeDriveroptsAccountNameKey: vi.username,\n\t\t\t\tvolumeDriveroptsAccountKeyKey:  vi.key,\n\t\t\t\tvolumeDriveroptsShareNameKey:   vi.share,\n\t\t\t},\n\t\t}\n\t\tsv := types.ServiceVolumeConfig{\n\t\t\tType:   azureFileDriverName,\n\t\t\tSource: vi.name,\n\t\t\tTarget: vi.target,\n\t\t}\n\t\tserviceConfigVolumes = append(serviceConfigVolumes, sv)\n\t}\n\n\treturn projectVolumes, serviceConfigVolumes, nil\n}\n\ntype volumeInput struct {\n\tname     string\n\tusername string\n\tkey      string\n\tshare    string\n\ttarget   string\n}\n\nfunc escapeKeySlashes(rawURL string) (string, error) {\n\turlSplit := strings.Split(rawURL, \"@\")\n\tif len(urlSplit) < 1 {\n\t\treturn \"\", fmt.Errorf(\"invalid URL format: %s\", rawURL)\n\t}\n\tuserPasswd := strings.ReplaceAll(urlSplit[0], \"\/\", \"_\")\n\n\tatIndex := strings.Index(rawURL, \"@\")\n\tif atIndex < 0 {\n\t\treturn \"\", fmt.Errorf(\"no share specified in: %s\", rawURL)\n\t}\n\n\tscaped := userPasswd + rawURL[atIndex:]\n\n\treturn scaped, nil\n}\n\nfunc unescapeKey(key string) string {\n\treturn strings.ReplaceAll(key, \"_\", \"\/\")\n}\n\n\/\/ Removes the second ':' that separates the source from target\nfunc volumeURL(pathURL string) (*url.URL, error) {\n\tscapedURL, err := escapeKeySlashes(pathURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpathURL = \"\/\/\" + scapedURL\n\n\tcount := strings.Count(pathURL, \":\")\n\tif count > 2 {\n\t\treturn nil, fmt.Errorf(\"invalid path URL: %s\", pathURL)\n\t}\n\tif count == 2 {\n\t\ttokens := strings.Split(pathURL, \":\")\n\t\tpathURL = fmt.Sprintf(\"%s:%s%s\", tokens[0], tokens[1], tokens[2])\n\t}\n\treturn url.Parse(pathURL)\n}\n\nfunc (v *volumeInput) parse(name string, s string) error {\n\tvolumeURL, err := volumeURL(s)\n\tif err != nil {\n\t\treturn errors.Wrapf(errdefs.ErrParsingFailed, \"unable to parse volume specification: %s\", err.Error())\n\t}\n\tv.username = volumeURL.User.Username()\n\tif v.username == \"\" {\n\t\treturn errors.Wrapf(errdefs.ErrParsingFailed, \"volume specification %q does not include a storage username\", v)\n\t}\n\tkey, ok := volumeURL.User.Password()\n\tif !ok || key == \"\" {\n\t\treturn errors.Wrapf(errdefs.ErrParsingFailed, \"volume specification %q does not include a storage key\", v)\n\t}\n\tv.key = unescapeKey(key)\n\tv.share = volumeURL.Host\n\tif v.share == \"\" {\n\t\treturn errors.Wrapf(errdefs.ErrParsingFailed, \"volume specification %q does not include a storage file share\", v)\n\t}\n\tv.name = name\n\tv.target = volumeURL.Path\n\tif v.target == \"\" {\n\t\t\/\/ Do not use filepath.Join, on Windows it will replace \/ by \\\n\t\tv.target = \"\/run\/volumes\/\" + v.share\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package endpoint_test\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\n\t\"github.com\/BlueOwlOpenSource\/endpoint\"\n\t\"github.com\/gorilla\/mux\"\n)\n\n\/\/ The endpoint framework distinguishes parameters based on their types.\n\/\/ All parameters of type \"string\" look the same, but a type that is\n\/\/ defined as another type (like exampleType) is a different type.\ntype exampleType string\ntype fooParam string\ntype fromMiddleware string\n\n\/\/ exampleStaticInjector will not be called until the service.Start()\n\/\/ call in Example_PreRegisterServiceWithMux.  It will be called only\n\/\/ once per endpoint registered.  Since it has a return value, it will\n\/\/ only run if a downstream handler consumes the value it returns.\n\/\/\n\/\/ The values returned by injectors and available as input parameters\n\/\/ to any downstream handler.\nfunc exampleStaticInjector() exampleType {\n\treturn \"example static value\"\n}\n\n\/\/ exampleInjector will be called for each request.  We know that\n\/\/ exampleInjector is a regular injector because it takes a parameter\n\/\/ that is specific to the request (*http.Request).\nfunc exampleInjector(r *http.Request) fooParam {\n\treturn fooParam(r.FormValue(\"foo\"))\n}\n\ntype returnValue interface{}\n\n\/\/ jsonifyResult wraps all handlers downstream of it in the call chain.\n\/\/ We know that jsonifyResult is a middleware handler because its first\n\/\/ argument is an function with an anonymous type (inner).   Calling inner\n\/\/ invokes all handlers downstream from jsonifyResult.  The value returned\n\/\/ by inner can come from the return values of the final endpoint handler\n\/\/ or from values returned by any downstream middleware.  The parameters\n\/\/ to inner are available as inputs to any downstream handler.\n\/\/\n\/\/ Parameters are matched by their types.  Since inner returns a returnValue,\n\/\/ it can come from any downstream middleware or endpoint that returns something\n\/\/ of type returnValue.\nfunc jsonifyResult(inner func(fromMiddleware) returnValue, w http.ResponseWriter) {\n\tv := inner(\"jsonify!\")\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tencoded, _ := json.Marshal(v)\n\tw.Write(encoded)\n\tw.WriteHeader(200)\n}\n\n\/\/ Endpoints are grouped and started by services.  Handlers that are\n\/\/ common to all endpoints are attached to the service.\nvar service = endpoint.PreRegisterServiceWithMux(\"example-service\",\n\texampleStaticInjector,\n\tjsonifyResult)\n\nfunc init() {\n\t\/\/ The \/example endpoint is bound to a handler chain\n\t\/\/ that combines the functions included at the service\n\t\/\/ level and the functions included here.  The final chain is:\n\t\/\/\texampleStaticInjector, jsonifyResult, exampleInjector, exampleEndpoint.\n\t\/\/ ExampleStaticInjector and jsonifyResult come from the service\n\t\/\/ definition.  ExampleInjector and exampleEndpoint are attached when\n\t\/\/ the endpoint is registered.\n\t\/\/\n\t\/\/ Handlers will execute in the order of the chain: exampleStaticInjector\n\t\/\/ then jsonifyResult.  When jsonifyResult calls inner(), exampleInjector\n\t\/\/ runs, then exampleEndpoint.   When exampleEndpoint returns, inner() returns\n\t\/\/ so jsonifyResult continues its work.  When jsonifyResult returns, the\n\t\/\/ handler chain is complete and the http server can form a reply from the\n\t\/\/ ResponseWriter.\n\t\/\/\n\t\/\/ Since service is WithMux, we can use gorilla mux modifiers when\n\t\/\/ we register endpoints.  This allows us to trivially indicate that our\n\t\/\/ example endpoint supports the GET method only.\n\tservice.RegisterEndpoint(\"\/example\", exampleInjector, exampleEndpoint).Methods(\"GET\")\n}\n\n\/\/ This is the final endpoint handler.  The parameters it takes can\n\/\/ be provided by any handler upstream from it.  It can also take the two\n\/\/ values that are included by the http handler signature: http.ResponseWriter\n\/\/ and *http.Request.\n\/\/\n\/\/ Any values that the final endpoint handler returns must be consumed by an\n\/\/ upstream middleware handler.  In this example, a \"returnValue\" is returned\n\/\/ here and consumed by jsonifyResult.\nfunc exampleEndpoint(sv exampleType, foo fooParam, mid fromMiddleware) returnValue {\n\treturn map[string]string{\n\t\t\"value\": fmt.Sprintf(\"%s-%s-%s\", sv, foo, mid),\n\t}\n}\n\n\/\/ The code below puts up a test http server, hits the \/example\n\/\/ endpoint, decodes the response, prints it, and exits.  This\n\/\/ is just to excercise the endpoint defined above.  The interesting\n\/\/ stuff happens above.\nfunc Example() {\n\tmuxRouter := mux.NewRouter()\n\tservice.Start(muxRouter)\n\tlocalServer := httptest.NewServer(muxRouter)\n\tdefer localServer.Close()\n\tr, err := http.Get(localServer.URL + \"\/example?foo=bar\")\n\tif err != nil {\n\t\tfmt.Println(\"get error\", err)\n\t\treturn\n\t}\n\tbuf, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfmt.Println(\"read error\", err)\n\t\treturn\n\t}\n\tvar res map[string]string\n\terr = json.Unmarshal(buf, &res)\n\tif err != nil {\n\t\tfmt.Println(\"unmarshal error\", err)\n\t\treturn\n\t}\n\tfmt.Println(\"Value:\", res[\"value\"])\n\t\/\/ Output: Value: example static value-bar-jsonify!\n}\n<commit_msg>doc changes<commit_after>package endpoint_test\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\n\t\"github.com\/BlueOwlOpenSource\/endpoint\"\n\t\"github.com\/gorilla\/mux\"\n)\n\n\/\/ The endpoint framework distinguishes parameters based on their types.\n\/\/ All parameters of type \"string\" look the same, but a type that is\n\/\/ defined as another type (like exampleType) is a different type.\ntype exampleType string\ntype fooParam string\ntype fromMiddleware string\n\n\/\/ exampleStaticInjector will not be called until the service.Start()\n\/\/ call in Example_PreRegisterServiceWithMux.  It will be called only\n\/\/ once per endpoint registered.  Since it has a return value, it will\n\/\/ only run if a downstream handler consumes the value it returns.\n\/\/\n\/\/ The values returned by injectors and available as input parameters\n\/\/ to any downstream handler.\nfunc exampleStaticInjector() exampleType {\n\treturn \"example static value\"\n}\n\n\/\/ exampleInjector will be called for each request.  We know that\n\/\/ exampleInjector is a regular injector because it takes a parameter\n\/\/ that is specific to the request (*http.Request).\nfunc exampleInjector(r *http.Request) fooParam {\n\treturn fooParam(r.FormValue(\"foo\"))\n}\n\ntype returnValue interface{}\n\n\/\/ jsonifyResult wraps all handlers downstream of it in the call chain.\n\/\/ We know that jsonifyResult is a middleware handler because its first\n\/\/ argument is an function with an anonymous type (inner).   Calling inner\n\/\/ invokes all handlers downstream from jsonifyResult.  The value returned\n\/\/ by inner can come from the return values of the final endpoint handler\n\/\/ or from values returned by any downstream middleware.  The parameters\n\/\/ to inner are available as inputs to any downstream handler.\n\/\/\n\/\/ Parameters are matched by their types.  Since inner returns a returnValue,\n\/\/ it can come from any downstream middleware or endpoint that returns something\n\/\/ of type returnValue.\nfunc jsonifyResult(inner func(fromMiddleware) returnValue, w http.ResponseWriter) {\n\tv := inner(\"jsonify!\")\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tencoded, _ := json.Marshal(v)\n\tw.Write(encoded)\n\tw.WriteHeader(200)\n}\n\n\/\/ Endpoints are grouped and started by services.  Handlers that are\n\/\/ common to all endpoints are attached to the service.\nvar service = endpoint.PreRegisterServiceWithMux(\"example-service\",\n\texampleStaticInjector,\n\tjsonifyResult)\n\nfunc init() {\n\t\/\/ The \/example endpoint is bound to a handler chain\n\t\/\/ that combines the functions included at the service\n\t\/\/ level and the functions included here.  The final chain is:\n\t\/\/\texampleStaticInjector, jsonifyResult, exampleInjector, exampleEndpoint.\n\t\/\/ ExampleStaticInjector and jsonifyResult come from the service\n\t\/\/ definition.  ExampleInjector and exampleEndpoint are attached when\n\t\/\/ the endpoint is registered.\n\t\/\/\n\t\/\/ Handlers will execute in the order of the chain: exampleStaticInjector\n\t\/\/ then jsonifyResult.  When jsonifyResult calls inner(), exampleInjector\n\t\/\/ runs, then exampleEndpoint.   When exampleEndpoint returns, inner() returns\n\t\/\/ so jsonifyResult continues its work.  When jsonifyResult returns, the\n\t\/\/ handler chain is complete and the http server can form a reply from the\n\t\/\/ ResponseWriter.\n\t\/\/\n\t\/\/ Since service is WithMux, we can use gorilla mux modifiers when\n\t\/\/ we register endpoints.  This allows us to trivially indicate that our\n\t\/\/ example endpoint supports the GET method only.\n\tservice.RegisterEndpoint(\n\t\t\"\/example\", exampleInjector, exampleEndpoint).Methods(\"GET\")\n}\n\n\/\/ This is the final endpoint handler.  The parameters it takes can\n\/\/ be provided by any handler upstream from it.  It can also take the two\n\/\/ values that are included by the http handler signature: http.ResponseWriter\n\/\/ and *http.Request.\n\/\/\n\/\/ Any values that the final endpoint handler returns must be consumed by an\n\/\/ upstream middleware handler.  In this example, a \"returnValue\" is returned\n\/\/ here and consumed by jsonifyResult.\nfunc exampleEndpoint(sv exampleType, foo fooParam, mid fromMiddleware) returnValue {\n\treturn map[string]string{\n\t\t\"value\": fmt.Sprintf(\"%s-%s-%s\", sv, foo, mid),\n\t}\n}\n\n\/\/ The code below puts up a test http server, hits the \/example\n\/\/ endpoint, decodes the response, prints it, and exits.  This\n\/\/ is just to excercise the endpoint defined above.  The interesting\n\/\/ stuff happens above.\nfunc Example() {\n\tmuxRouter := mux.NewRouter()\n\tservice.Start(muxRouter)\n\tlocalServer := httptest.NewServer(muxRouter)\n\tdefer localServer.Close()\n\tr, err := http.Get(localServer.URL + \"\/example?foo=bar\")\n\tif err != nil {\n\t\tfmt.Println(\"get error\", err)\n\t\treturn\n\t}\n\tbuf, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfmt.Println(\"read error\", err)\n\t\treturn\n\t}\n\tvar res map[string]string\n\terr = json.Unmarshal(buf, &res)\n\tif err != nil {\n\t\tfmt.Println(\"unmarshal error\", err)\n\t\treturn\n\t}\n\tfmt.Println(\"Value:\", res[\"value\"])\n\t\/\/ Output: Value: example static value-bar-jsonify!\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 The Prometheus Authors\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build !nobcache\n\npackage collector\n\nimport (\n\t\"fmt\"\n\n\t\/\/ https:\/\/godoc.org\/github.com\/prometheus\/client_golang\/prometheus\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/prometheus\/procfs\/bcache\"\n)\n\nfunc init() {\n\tregisterCollector(\"bcache\", defaultEnabled, NewBcacheCollector)\n}\n\n\/\/ A bcacheCollector is a Collector which gathers metrics from Linux bcache.\ntype bcacheCollector struct {\n\tfs bcache.FS\n}\n\n\/\/ NewBcacheCollector returns a newly allocated bcacheCollector.\n\/\/ It exposes a number of Linux bcache statistics.\nfunc NewBcacheCollector() (Collector, error) {\n\tfs, err := bcache.NewFS(*sysPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open sysfs: %v\", err)\n\t}\n\n\treturn &bcacheCollector{\n\t\tfs: fs,\n\t}, nil\n}\n\n\/\/ Update reads and exposes bcache stats.\n\/\/ It implements the Collector interface.\nfunc (c *bcacheCollector) Update(ch chan<- prometheus.Metric) error {\n\tstats, err := c.fs.Stats()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to retrieve bcache stats: %v\", err)\n\t}\n\n\tfor _, s := range stats {\n\t\tc.updateBcacheStats(ch, s)\n\t}\n\treturn nil\n}\n\ntype bcacheMetric struct {\n\tname            string\n\tdesc            string\n\tvalue           float64\n\tmetricType      prometheus.ValueType\n\textraLabel      []string\n\textraLabelValue string\n}\n\nfunc bcachePeriodStatsToMetric(ps *bcache.PeriodStats, labelValue string) []bcacheMetric {\n\tlabel := []string{\"backing_device\"}\n\n\tmetrics := []bcacheMetric{\n\t\t{\n\t\t\tname:            \"bypassed_bytes_total\",\n\t\t\tdesc:            \"Amount of IO (both reads and writes) that has bypassed the cache.\",\n\t\t\tvalue:           float64(ps.Bypassed),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t\t{\n\t\t\tname:            \"cache_hits_total\",\n\t\t\tdesc:            \"Hits counted per individual IO as bcache sees them.\",\n\t\t\tvalue:           float64(ps.CacheHits),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t\t{\n\t\t\tname:            \"cache_misses_total\",\n\t\t\tdesc:            \"Misses counted per individual IO as bcache sees them.\",\n\t\t\tvalue:           float64(ps.CacheMisses),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t\t{\n\t\t\tname:            \"cache_bypass_hits_total\",\n\t\t\tdesc:            \"Hits for IO intended to skip the cache.\",\n\t\t\tvalue:           float64(ps.CacheBypassHits),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t\t{\n\t\t\tname:            \"cache_bypass_misses_total\",\n\t\t\tdesc:            \"Misses for IO intended to skip the cache.\",\n\t\t\tvalue:           float64(ps.CacheBypassMisses),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t\t{\n\t\t\tname:            \"cache_miss_collisions_total\",\n\t\t\tdesc:            \"Instances where data insertion from cache miss raced with write (data already present).\",\n\t\t\tvalue:           float64(ps.CacheMissCollisions),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t\t{\n\t\t\tname:            \"cache_readaheads_total\",\n\t\t\tdesc:            \"Count of times readahead occurred.\",\n\t\t\tvalue:           float64(ps.CacheReadaheads),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t}\n\treturn metrics\n}\n\n\/\/ UpdateBcacheStats collects statistics for one bcache ID.\nfunc (c *bcacheCollector) updateBcacheStats(ch chan<- prometheus.Metric, s *bcache.Stats) {\n\n\tconst (\n\t\tsubsystem = \"bcache\"\n\t)\n\n\tvar (\n\t\tdevLabel   = []string{\"uuid\"}\n\t\tallMetrics []bcacheMetric\n\t\tmetrics    []bcacheMetric\n\t)\n\n\tallMetrics = []bcacheMetric{\n\t\t\/\/ metrics in \/sys\/fs\/bcache\/<uuid>\/\n\t\t{\n\t\t\tname:       \"average_key_size_sectors\",\n\t\t\tdesc:       \"Average data per key in the btree (sectors).\",\n\t\t\tvalue:      float64(s.Bcache.AverageKeySize),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"btree_cache_size_bytes\",\n\t\t\tdesc:       \"Amount of memory currently used by the btree cache.\",\n\t\t\tvalue:      float64(s.Bcache.BtreeCacheSize),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"cache_available_percent\",\n\t\t\tdesc:       \"Percentage of cache device without dirty data, usable for writeback (may contain clean cached data).\",\n\t\t\tvalue:      float64(s.Bcache.CacheAvailablePercent),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"congested\",\n\t\t\tdesc:       \"Congestion.\",\n\t\t\tvalue:      float64(s.Bcache.Congested),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"root_usage_percent\",\n\t\t\tdesc:       \"Percentage of the root btree node in use (tree depth increases if too high).\",\n\t\t\tvalue:      float64(s.Bcache.RootUsagePercent),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"tree_depth\",\n\t\t\tdesc:       \"Depth of the btree.\",\n\t\t\tvalue:      float64(s.Bcache.TreeDepth),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t\/\/ metrics in \/sys\/fs\/bcache\/<uuid>\/internal\/\n\t\t{\n\t\t\tname:       \"active_journal_entries\",\n\t\t\tdesc:       \"Number of journal entries that are newer than the index.\",\n\t\t\tvalue:      float64(s.Bcache.Internal.ActiveJournalEntries),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"btree_nodes\",\n\t\t\tdesc:       \"Total nodes in the btree.\",\n\t\t\tvalue:      float64(s.Bcache.Internal.BtreeNodes),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"btree_read_average_duration_seconds\",\n\t\t\tdesc:       \"Average btree read duration.\",\n\t\t\tvalue:      float64(s.Bcache.Internal.BtreeReadAverageDurationNanoSeconds) * 1e-9,\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"cache_read_races_total\",\n\t\t\tdesc:       \"Counts instances where while data was being read from the cache, the bucket was reused and invalidated - i.e. where the pointer was stale after the read completed.\",\n\t\t\tvalue:      float64(s.Bcache.Internal.CacheReadRaces),\n\t\t\tmetricType: prometheus.CounterValue,\n\t\t},\n\t}\n\n\tfor _, bdev := range s.Bdevs {\n\t\t\/\/ metrics in \/sys\/fs\/bcache\/<uuid>\/<bdev>\/\n\t\tmetrics = []bcacheMetric{\n\t\t\t{\n\t\t\t\tname:            \"dirty_data_bytes\",\n\t\t\t\tdesc:            \"Amount of dirty data for this backing device in the cache.\",\n\t\t\t\tvalue:           float64(bdev.DirtyData),\n\t\t\t\tmetricType:      prometheus.GaugeValue,\n\t\t\t\textraLabel:      []string{\"backing_device\"},\n\t\t\t\textraLabelValue: bdev.Name,\n\t\t\t},\n\t\t}\n\t\tallMetrics = append(allMetrics, metrics...)\n\n\t\t\/\/ metrics in \/sys\/fs\/bcache\/<uuid>\/<bdev>\/stats_total\n\t\tmetrics := bcachePeriodStatsToMetric(&bdev.Total, bdev.Name)\n\t\tallMetrics = append(allMetrics, metrics...)\n\n\t}\n\n\tfor _, cache := range s.Caches {\n\t\tmetrics = []bcacheMetric{\n\t\t\t\/\/ metrics in \/sys\/fs\/bcache\/<uuid>\/<cache>\/\n\t\t\t{\n\t\t\t\tname:            \"io_errors\",\n\t\t\t\tdesc:            \"Number of errors that have occurred, decayed by io_error_halflife.\",\n\t\t\t\tvalue:           float64(cache.IOErrors),\n\t\t\t\tmetricType:      prometheus.GaugeValue,\n\t\t\t\textraLabel:      []string{\"cache_device\"},\n\t\t\t\textraLabelValue: cache.Name,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:            \"metadata_written_bytes_total\",\n\t\t\t\tdesc:            \"Sum of all non data writes (btree writes and all other metadata).\",\n\t\t\t\tvalue:           float64(cache.MetadataWritten),\n\t\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\t\textraLabel:      []string{\"cache_device\"},\n\t\t\t\textraLabelValue: cache.Name,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:            \"written_bytes_total\",\n\t\t\t\tdesc:            \"Sum of all data that has been written to the cache.\",\n\t\t\t\tvalue:           float64(cache.Written),\n\t\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\t\textraLabel:      []string{\"cache_device\"},\n\t\t\t\textraLabelValue: cache.Name,\n\t\t\t},\n\t\t\t\/\/ metrics in \/sys\/fs\/bcache\/<uuid>\/<cache>\/priority_stats\n\t\t\t{\n\t\t\t\tname:            \"priority_stats_unused_percent\",\n\t\t\t\tdesc:            \"The percentage of the cache that doesn't contain any data.\",\n\t\t\t\tvalue:           float64(cache.Priority.UnusedPercent),\n\t\t\t\tmetricType:      prometheus.GaugeValue,\n\t\t\t\textraLabel:      []string{\"cache_device\"},\n\t\t\t\textraLabelValue: cache.Name,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:            \"priority_stats_metadata_percent\",\n\t\t\t\tdesc:            \"Bcache's metadata overhead.\",\n\t\t\t\tvalue:           float64(cache.Priority.MetadataPercent),\n\t\t\t\tmetricType:      prometheus.GaugeValue,\n\t\t\t\textraLabel:      []string{\"cache_device\"},\n\t\t\t\textraLabelValue: cache.Name,\n\t\t\t},\n\t\t}\n\t\tallMetrics = append(allMetrics, metrics...)\n\t}\n\n\tfor _, m := range allMetrics {\n\t\tlabels := append(devLabel, m.extraLabel...)\n\n\t\tdesc := prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, subsystem, m.name),\n\t\t\tm.desc,\n\t\t\tlabels,\n\t\t\tnil,\n\t\t)\n\n\t\tlabelValues := []string{s.Name}\n\t\tif m.extraLabelValue != \"\" {\n\t\t\tlabelValues = append(labelValues, m.extraLabelValue)\n\t\t}\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tdesc,\n\t\t\tm.metricType,\n\t\t\tm.value,\n\t\t\tlabelValues...,\n\t\t)\n\t}\n}\n<commit_msg>collector: remove commented-out import from bcache collector<commit_after>\/\/ Copyright 2017 The Prometheus Authors\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build !nobcache\n\npackage collector\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/prometheus\/procfs\/bcache\"\n)\n\nfunc init() {\n\tregisterCollector(\"bcache\", defaultEnabled, NewBcacheCollector)\n}\n\n\/\/ A bcacheCollector is a Collector which gathers metrics from Linux bcache.\ntype bcacheCollector struct {\n\tfs bcache.FS\n}\n\n\/\/ NewBcacheCollector returns a newly allocated bcacheCollector.\n\/\/ It exposes a number of Linux bcache statistics.\nfunc NewBcacheCollector() (Collector, error) {\n\tfs, err := bcache.NewFS(*sysPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to open sysfs: %v\", err)\n\t}\n\n\treturn &bcacheCollector{\n\t\tfs: fs,\n\t}, nil\n}\n\n\/\/ Update reads and exposes bcache stats.\n\/\/ It implements the Collector interface.\nfunc (c *bcacheCollector) Update(ch chan<- prometheus.Metric) error {\n\tstats, err := c.fs.Stats()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to retrieve bcache stats: %v\", err)\n\t}\n\n\tfor _, s := range stats {\n\t\tc.updateBcacheStats(ch, s)\n\t}\n\treturn nil\n}\n\ntype bcacheMetric struct {\n\tname            string\n\tdesc            string\n\tvalue           float64\n\tmetricType      prometheus.ValueType\n\textraLabel      []string\n\textraLabelValue string\n}\n\nfunc bcachePeriodStatsToMetric(ps *bcache.PeriodStats, labelValue string) []bcacheMetric {\n\tlabel := []string{\"backing_device\"}\n\n\tmetrics := []bcacheMetric{\n\t\t{\n\t\t\tname:            \"bypassed_bytes_total\",\n\t\t\tdesc:            \"Amount of IO (both reads and writes) that has bypassed the cache.\",\n\t\t\tvalue:           float64(ps.Bypassed),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t\t{\n\t\t\tname:            \"cache_hits_total\",\n\t\t\tdesc:            \"Hits counted per individual IO as bcache sees them.\",\n\t\t\tvalue:           float64(ps.CacheHits),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t\t{\n\t\t\tname:            \"cache_misses_total\",\n\t\t\tdesc:            \"Misses counted per individual IO as bcache sees them.\",\n\t\t\tvalue:           float64(ps.CacheMisses),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t\t{\n\t\t\tname:            \"cache_bypass_hits_total\",\n\t\t\tdesc:            \"Hits for IO intended to skip the cache.\",\n\t\t\tvalue:           float64(ps.CacheBypassHits),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t\t{\n\t\t\tname:            \"cache_bypass_misses_total\",\n\t\t\tdesc:            \"Misses for IO intended to skip the cache.\",\n\t\t\tvalue:           float64(ps.CacheBypassMisses),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t\t{\n\t\t\tname:            \"cache_miss_collisions_total\",\n\t\t\tdesc:            \"Instances where data insertion from cache miss raced with write (data already present).\",\n\t\t\tvalue:           float64(ps.CacheMissCollisions),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t\t{\n\t\t\tname:            \"cache_readaheads_total\",\n\t\t\tdesc:            \"Count of times readahead occurred.\",\n\t\t\tvalue:           float64(ps.CacheReadaheads),\n\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\textraLabel:      label,\n\t\t\textraLabelValue: labelValue,\n\t\t},\n\t}\n\treturn metrics\n}\n\n\/\/ UpdateBcacheStats collects statistics for one bcache ID.\nfunc (c *bcacheCollector) updateBcacheStats(ch chan<- prometheus.Metric, s *bcache.Stats) {\n\n\tconst (\n\t\tsubsystem = \"bcache\"\n\t)\n\n\tvar (\n\t\tdevLabel   = []string{\"uuid\"}\n\t\tallMetrics []bcacheMetric\n\t\tmetrics    []bcacheMetric\n\t)\n\n\tallMetrics = []bcacheMetric{\n\t\t\/\/ metrics in \/sys\/fs\/bcache\/<uuid>\/\n\t\t{\n\t\t\tname:       \"average_key_size_sectors\",\n\t\t\tdesc:       \"Average data per key in the btree (sectors).\",\n\t\t\tvalue:      float64(s.Bcache.AverageKeySize),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"btree_cache_size_bytes\",\n\t\t\tdesc:       \"Amount of memory currently used by the btree cache.\",\n\t\t\tvalue:      float64(s.Bcache.BtreeCacheSize),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"cache_available_percent\",\n\t\t\tdesc:       \"Percentage of cache device without dirty data, usable for writeback (may contain clean cached data).\",\n\t\t\tvalue:      float64(s.Bcache.CacheAvailablePercent),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"congested\",\n\t\t\tdesc:       \"Congestion.\",\n\t\t\tvalue:      float64(s.Bcache.Congested),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"root_usage_percent\",\n\t\t\tdesc:       \"Percentage of the root btree node in use (tree depth increases if too high).\",\n\t\t\tvalue:      float64(s.Bcache.RootUsagePercent),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"tree_depth\",\n\t\t\tdesc:       \"Depth of the btree.\",\n\t\t\tvalue:      float64(s.Bcache.TreeDepth),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t\/\/ metrics in \/sys\/fs\/bcache\/<uuid>\/internal\/\n\t\t{\n\t\t\tname:       \"active_journal_entries\",\n\t\t\tdesc:       \"Number of journal entries that are newer than the index.\",\n\t\t\tvalue:      float64(s.Bcache.Internal.ActiveJournalEntries),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"btree_nodes\",\n\t\t\tdesc:       \"Total nodes in the btree.\",\n\t\t\tvalue:      float64(s.Bcache.Internal.BtreeNodes),\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"btree_read_average_duration_seconds\",\n\t\t\tdesc:       \"Average btree read duration.\",\n\t\t\tvalue:      float64(s.Bcache.Internal.BtreeReadAverageDurationNanoSeconds) * 1e-9,\n\t\t\tmetricType: prometheus.GaugeValue,\n\t\t},\n\t\t{\n\t\t\tname:       \"cache_read_races_total\",\n\t\t\tdesc:       \"Counts instances where while data was being read from the cache, the bucket was reused and invalidated - i.e. where the pointer was stale after the read completed.\",\n\t\t\tvalue:      float64(s.Bcache.Internal.CacheReadRaces),\n\t\t\tmetricType: prometheus.CounterValue,\n\t\t},\n\t}\n\n\tfor _, bdev := range s.Bdevs {\n\t\t\/\/ metrics in \/sys\/fs\/bcache\/<uuid>\/<bdev>\/\n\t\tmetrics = []bcacheMetric{\n\t\t\t{\n\t\t\t\tname:            \"dirty_data_bytes\",\n\t\t\t\tdesc:            \"Amount of dirty data for this backing device in the cache.\",\n\t\t\t\tvalue:           float64(bdev.DirtyData),\n\t\t\t\tmetricType:      prometheus.GaugeValue,\n\t\t\t\textraLabel:      []string{\"backing_device\"},\n\t\t\t\textraLabelValue: bdev.Name,\n\t\t\t},\n\t\t}\n\t\tallMetrics = append(allMetrics, metrics...)\n\n\t\t\/\/ metrics in \/sys\/fs\/bcache\/<uuid>\/<bdev>\/stats_total\n\t\tmetrics := bcachePeriodStatsToMetric(&bdev.Total, bdev.Name)\n\t\tallMetrics = append(allMetrics, metrics...)\n\n\t}\n\n\tfor _, cache := range s.Caches {\n\t\tmetrics = []bcacheMetric{\n\t\t\t\/\/ metrics in \/sys\/fs\/bcache\/<uuid>\/<cache>\/\n\t\t\t{\n\t\t\t\tname:            \"io_errors\",\n\t\t\t\tdesc:            \"Number of errors that have occurred, decayed by io_error_halflife.\",\n\t\t\t\tvalue:           float64(cache.IOErrors),\n\t\t\t\tmetricType:      prometheus.GaugeValue,\n\t\t\t\textraLabel:      []string{\"cache_device\"},\n\t\t\t\textraLabelValue: cache.Name,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:            \"metadata_written_bytes_total\",\n\t\t\t\tdesc:            \"Sum of all non data writes (btree writes and all other metadata).\",\n\t\t\t\tvalue:           float64(cache.MetadataWritten),\n\t\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\t\textraLabel:      []string{\"cache_device\"},\n\t\t\t\textraLabelValue: cache.Name,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:            \"written_bytes_total\",\n\t\t\t\tdesc:            \"Sum of all data that has been written to the cache.\",\n\t\t\t\tvalue:           float64(cache.Written),\n\t\t\t\tmetricType:      prometheus.CounterValue,\n\t\t\t\textraLabel:      []string{\"cache_device\"},\n\t\t\t\textraLabelValue: cache.Name,\n\t\t\t},\n\t\t\t\/\/ metrics in \/sys\/fs\/bcache\/<uuid>\/<cache>\/priority_stats\n\t\t\t{\n\t\t\t\tname:            \"priority_stats_unused_percent\",\n\t\t\t\tdesc:            \"The percentage of the cache that doesn't contain any data.\",\n\t\t\t\tvalue:           float64(cache.Priority.UnusedPercent),\n\t\t\t\tmetricType:      prometheus.GaugeValue,\n\t\t\t\textraLabel:      []string{\"cache_device\"},\n\t\t\t\textraLabelValue: cache.Name,\n\t\t\t},\n\t\t\t{\n\t\t\t\tname:            \"priority_stats_metadata_percent\",\n\t\t\t\tdesc:            \"Bcache's metadata overhead.\",\n\t\t\t\tvalue:           float64(cache.Priority.MetadataPercent),\n\t\t\t\tmetricType:      prometheus.GaugeValue,\n\t\t\t\textraLabel:      []string{\"cache_device\"},\n\t\t\t\textraLabelValue: cache.Name,\n\t\t\t},\n\t\t}\n\t\tallMetrics = append(allMetrics, metrics...)\n\t}\n\n\tfor _, m := range allMetrics {\n\t\tlabels := append(devLabel, m.extraLabel...)\n\n\t\tdesc := prometheus.NewDesc(\n\t\t\tprometheus.BuildFQName(namespace, subsystem, m.name),\n\t\t\tm.desc,\n\t\t\tlabels,\n\t\t\tnil,\n\t\t)\n\n\t\tlabelValues := []string{s.Name}\n\t\tif m.extraLabelValue != \"\" {\n\t\t\tlabelValues = append(labelValues, m.extraLabelValue)\n\t\t}\n\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tdesc,\n\t\t\tm.metricType,\n\t\t\tm.value,\n\t\t\tlabelValues...,\n\t\t)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package collector\n\nimport (\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\nvar (\n\toplogStatusCount = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace:\tNamespace,\n\t\tSubsystem:\t\"replset_oplog\",\n\t\tName:\t\t\"items_total\",\n\t\tHelp:\t\t\"The total number of changes in the oplog\",\n\t})\n\toplogStatusHeadTimestamp = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace:\tNamespace,\n\t\tSubsystem:\t\"replset_oplog\",\n\t\tName:\t\t\"head_timestamp\",\n\t\tHelp:\t\t\"The timestamp of the newest change in the oplog\",\n\t})\n\toplogStatusTailTimestamp = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace:\tNamespace,\n\t\tSubsystem:\t\"replset_oplog\",\n\t\tName:\t\t\"tail_timestamp\",\n\t\tHelp:\t\t\"The timestamp of the oldest change in the oplog\",\n\t})\n\toplogStatusSizeBytes = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace:\tNamespace,\n\t\tSubsystem:\t\"replset_oplog\",\n\t\tName:\t\t\"size_bytes\",\n\t\tHelp:\t\t\"Size of oplog in bytes\",\n\t}, []string{\"type\"})\n)\n\ntype OplogCollectionStats struct {\n\tCount\t\tfloat64\t`bson:\"count\"`\n\tSize\t\tfloat64\t`bson:\"size\"`\n\tStorageSize\tfloat64 `bson:\"storageSize\"`\n}\n\ntype OplogStatus struct {\n\tTailTimestamp\tfloat64\n\tHeadTimestamp\tfloat64\n\tCollectionStats\t*OplogCollectionStats\n}\n\n\/\/ there's gotta be a better way to do this, but it works for now :\/\nfunc BsonMongoTimestampToUnix(timestamp bson.MongoTimestamp) float64 {\n\treturn float64(timestamp >> 32)\n}\n\nfunc GetOplogTimestamp(session *mgo.Session, returnHead bool) (float64, error) {\n\tvar sortBy string = \"$natural\"\n\tif returnHead {\n\t\tsortBy = \"-$natural\"\n\t}\n\n\tvar err error\n\tvar tries int    = 0\n\tvar maxTries int = 2\n\tvar result struct { Timestamp bson.MongoTimestamp `bson:\"ts\"` }\n\tfor tries < maxTries {\n\t\terr = session.DB(\"local\").C(\"oplog.rs\").Find(nil).Sort(sortBy).Limit(1).One(&result)\n\t\tif err != nil {\n\t\t\ttries += 1\n\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t} else {\n\t\t\treturn BsonMongoTimestampToUnix(result.Timestamp), err\n\t\t}\n\t}\n\n\treturn nil, err\n}\n\nfunc GetOplogCollectionStats(session *mgo.Session) (*OplogCollectionStats, error) {\n\tresults := &OplogCollectionStats{}\n\terr := session.DB(\"local\").Run(bson.M{ \"collStats\" : \"oplog.rs\" }, &results)\n\treturn results, err\n}\n\nfunc (status *OplogStatus) Export(ch chan<- prometheus.Metric) {\n\toplogStatusSizeBytes.WithLabelValues(\"current\").Set(0)\n\toplogStatusSizeBytes.WithLabelValues(\"storage\").Set(0)\n\tif status.CollectionStats != nil {\n\t\toplogStatusCount.Set(status.CollectionStats.Count)\n\t\toplogStatusSizeBytes.WithLabelValues(\"current\").Set(status.CollectionStats.Size)\n\t\toplogStatusSizeBytes.WithLabelValues(\"storage\").Set(status.CollectionStats.StorageSize)\n\t}\n\tif status.HeadTimestamp != nil && status.TailTimestamp != nil {\n\t\toplogStatusHeadTimestamp.Set(status.HeadTimestamp)\n\t\toplogStatusTailTimestamp.Set(status.TailTimestamp)\n\t}\n\n\toplogStatusCount.Collect(ch)\n\toplogStatusHeadTimestamp.Collect(ch)\n\toplogStatusTailTimestamp.Collect(ch)\n\toplogStatusSizeBytes.Collect(ch)\n}\n\nfunc (status *OplogStatus) Describe(ch chan<- *prometheus.Desc) {\n\toplogStatusCount.Describe(ch)\n\toplogStatusHeadTimestamp.Describe(ch)\n\toplogStatusTailTimestamp.Describe(ch)\n\toplogStatusSizeBytes.Describe(ch)\n}\n\nfunc GetOplogStatus(session *mgo.Session) *OplogStatus {\n\toplogStatus := &OplogStatus{}\n\tcollectionStats, err := GetOplogCollectionStats(session)\n\tif err != nil {\n\t\tglog.Error(\"Failed to get local.oplog_rs collection stats.\")\n\t\treturn nil\n\t}\n\n\ttailTimestamp, err := GetOplogTimestamp(session, false)\n\theadTimestamp, err := GetOplogTimestamp(session, true)\n\tif err != nil {\n\t\tglog.Error(\"Failed to get oplog head or tail timestamps.\")\n\t\treturn nil\n\t}\n\n\toplogStatus.CollectionStats = collectionStats\n\toplogStatus.TailTimestamp   = tailTimestamp\n\toplogStatus.HeadTimestamp   = headTimestamp\n\n\treturn oplogStatus\n}\n<commit_msg>missing time import<commit_after>package collector\n\nimport (\n\t\"time\"\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n)\n\nvar (\n\toplogStatusCount = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace:\tNamespace,\n\t\tSubsystem:\t\"replset_oplog\",\n\t\tName:\t\t\"items_total\",\n\t\tHelp:\t\t\"The total number of changes in the oplog\",\n\t})\n\toplogStatusHeadTimestamp = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace:\tNamespace,\n\t\tSubsystem:\t\"replset_oplog\",\n\t\tName:\t\t\"head_timestamp\",\n\t\tHelp:\t\t\"The timestamp of the newest change in the oplog\",\n\t})\n\toplogStatusTailTimestamp = prometheus.NewGauge(prometheus.GaugeOpts{\n\t\tNamespace:\tNamespace,\n\t\tSubsystem:\t\"replset_oplog\",\n\t\tName:\t\t\"tail_timestamp\",\n\t\tHelp:\t\t\"The timestamp of the oldest change in the oplog\",\n\t})\n\toplogStatusSizeBytes = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tNamespace:\tNamespace,\n\t\tSubsystem:\t\"replset_oplog\",\n\t\tName:\t\t\"size_bytes\",\n\t\tHelp:\t\t\"Size of oplog in bytes\",\n\t}, []string{\"type\"})\n)\n\ntype OplogCollectionStats struct {\n\tCount\t\tfloat64\t`bson:\"count\"`\n\tSize\t\tfloat64\t`bson:\"size\"`\n\tStorageSize\tfloat64 `bson:\"storageSize\"`\n}\n\ntype OplogStatus struct {\n\tTailTimestamp\tfloat64\n\tHeadTimestamp\tfloat64\n\tCollectionStats\t*OplogCollectionStats\n}\n\n\/\/ there's gotta be a better way to do this, but it works for now :\/\nfunc BsonMongoTimestampToUnix(timestamp bson.MongoTimestamp) float64 {\n\treturn float64(timestamp >> 32)\n}\n\nfunc GetOplogTimestamp(session *mgo.Session, returnHead bool) (float64, error) {\n\tvar sortBy string = \"$natural\"\n\tif returnHead {\n\t\tsortBy = \"-$natural\"\n\t}\n\n\tvar err error\n\tvar tries int    = 0\n\tvar maxTries int = 2\n\tvar result struct { Timestamp bson.MongoTimestamp `bson:\"ts\"` }\n\tfor tries < maxTries {\n\t\terr = session.DB(\"local\").C(\"oplog.rs\").Find(nil).Sort(sortBy).Limit(1).One(&result)\n\t\tif err != nil {\n\t\t\ttries += 1\n\t\t\ttime.Sleep(500 * time.Millisecond)\n\t\t} else {\n\t\t\treturn BsonMongoTimestampToUnix(result.Timestamp), err\n\t\t}\n\t}\n\n\treturn nil, err\n}\n\nfunc GetOplogCollectionStats(session *mgo.Session) (*OplogCollectionStats, error) {\n\tresults := &OplogCollectionStats{}\n\terr := session.DB(\"local\").Run(bson.M{ \"collStats\" : \"oplog.rs\" }, &results)\n\treturn results, err\n}\n\nfunc (status *OplogStatus) Export(ch chan<- prometheus.Metric) {\n\toplogStatusSizeBytes.WithLabelValues(\"current\").Set(0)\n\toplogStatusSizeBytes.WithLabelValues(\"storage\").Set(0)\n\tif status.CollectionStats != nil {\n\t\toplogStatusCount.Set(status.CollectionStats.Count)\n\t\toplogStatusSizeBytes.WithLabelValues(\"current\").Set(status.CollectionStats.Size)\n\t\toplogStatusSizeBytes.WithLabelValues(\"storage\").Set(status.CollectionStats.StorageSize)\n\t}\n\tif status.HeadTimestamp != nil && status.TailTimestamp != nil {\n\t\toplogStatusHeadTimestamp.Set(status.HeadTimestamp)\n\t\toplogStatusTailTimestamp.Set(status.TailTimestamp)\n\t}\n\n\toplogStatusCount.Collect(ch)\n\toplogStatusHeadTimestamp.Collect(ch)\n\toplogStatusTailTimestamp.Collect(ch)\n\toplogStatusSizeBytes.Collect(ch)\n}\n\nfunc (status *OplogStatus) Describe(ch chan<- *prometheus.Desc) {\n\toplogStatusCount.Describe(ch)\n\toplogStatusHeadTimestamp.Describe(ch)\n\toplogStatusTailTimestamp.Describe(ch)\n\toplogStatusSizeBytes.Describe(ch)\n}\n\nfunc GetOplogStatus(session *mgo.Session) *OplogStatus {\n\toplogStatus := &OplogStatus{}\n\tcollectionStats, err := GetOplogCollectionStats(session)\n\tif err != nil {\n\t\tglog.Error(\"Failed to get local.oplog_rs collection stats.\")\n\t\treturn nil\n\t}\n\n\ttailTimestamp, err := GetOplogTimestamp(session, false)\n\theadTimestamp, err := GetOplogTimestamp(session, true)\n\tif err != nil {\n\t\tglog.Error(\"Failed to get oplog head or tail timestamps.\")\n\t\treturn nil\n\t}\n\n\toplogStatus.CollectionStats = collectionStats\n\toplogStatus.TailTimestamp   = tailTimestamp\n\toplogStatus.HeadTimestamp   = headTimestamp\n\n\treturn oplogStatus\n}\n<|endoftext|>"}
{"text":"<commit_before>package commands\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sync\/atomic\"\n\n\t\"github.com\/git-lfs\/git-lfs\/config\"\n\t\"github.com\/git-lfs\/git-lfs\/errors\"\n\t\"github.com\/git-lfs\/git-lfs\/git\"\n\t\"github.com\/git-lfs\/git-lfs\/lfs\"\n\t\"github.com\/git-lfs\/git-lfs\/tools\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tdedupFlags = struct {\n\t\ttest bool\n\t}{}\n\tdedupStats = &struct {\n\t\ttotalProcessedCount int64\n\t\ttotalProcessedSize  int64\n\t}{}\n)\n\nfunc dedupTestCommand(*cobra.Command, []string) {\n\trequireInRepo()\n\n\tif supported, err := tools.CheckCloneFileSupported(cfg.TempDir()); err != nil || !supported {\n\t\tif err == nil {\n\t\t\terr = errors.New(\"Unknown reason.\")\n\t\t}\n\t\tExit(\"This system does not support deduplication. %s\", err)\n\t}\n\n\tPrint(\"OK: This platform and repository support file de-duplication.\")\n}\n\nfunc dedupCommand(cmd *cobra.Command, args []string) {\n\tif dedupFlags.test {\n\t\tdedupTestCommand(cmd, args)\n\t\treturn\n\t}\n\n\trequireInRepo()\n\tif gitDir, err := git.GitDir(); err != nil {\n\t\tExitWithError(err)\n\t} else if supported, err := tools.CheckCloneFileSupported(gitDir); err != nil || !supported {\n\t\tExit(\"This system does not support deduplication.\")\n\t}\n\n\tif dirty, err := git.IsWorkingCopyDirty(); err != nil {\n\t\tExitWithError(err)\n\t} else if dirty {\n\t\tExit(\"Working tree is dirty. Please commit or reset your change.\")\n\t}\n\n\t\/\/ We assume working tree is clean.\n\tgitScanner := lfs.NewGitScanner(config.New(), func(p *lfs.WrappedPointer, err error) {\n\t\tif err != nil {\n\t\t\tExit(\"Could not scan for Git LFS tree: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif success, err := dedup(p); err != nil {\n\t\t\tError(\"Skipped: %s (Size: %d)\\n          %s\", p.Name, p.Size, err)\n\t\t} else if !success {\n\t\t\tError(\"Skipped: %s (Size: %d)\", p.Name, p.Size)\n\t\t} else if success {\n\t\t\tPrint(\"Success: %s (Size: %d)\", p.Name, p.Size)\n\n\t\t\tatomic.AddInt64(&dedupStats.totalProcessedCount, 1)\n\t\t\tatomic.AddInt64(&dedupStats.totalProcessedSize, p.Size)\n\t\t}\n\t})\n\tdefer gitScanner.Close()\n\n\tif err := gitScanner.ScanTree(\"HEAD\"); err != nil {\n\t\tExitWithError(err)\n\t}\n\n\tPrint(\"\\n\\nSuccessfully finished.\\n\"+\n\t\t\"  De-duplicated  size: %d bytes\\n\"+\n\t\t\"                count: %d\",\n\t\tdedupStats.totalProcessedSize,\n\t\tdedupStats.totalProcessedCount)\n}\n\n\/\/ dedup executes\n\/\/ Precondition: working tree MUST clean. We can replace working tree files from mediafile safely.\nfunc dedup(p *lfs.WrappedPointer) (success bool, err error) {\n\t\/\/ PRECONDITION, check ofs object exists or skip this file.\n\tif !cfg.LFSObjectExists(p.Oid, p.Size) { \/\/ Not exists,\n\t\t\/\/ Basically, this is not happens because executing 'git status' in `git.IsWorkingCopyDirty()` recover it.\n\t\treturn false, errors.New(\"mediafile is not exist\")\n\t}\n\n\t\/\/ DO de-dup\n\t\/\/ Gather original state\n\toriginalStat, err := os.Stat(p.Name)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ Do clone\n\tsrcFile := cfg.Filesystem().ObjectPathname(p.Oid)\n\tdstFile := filepath.Join(cfg.LocalWorkingDir(), p.Name)\n\n\t\/\/ Clone the file. This overwrites the destination if it exists.\n\tif ok, err := tools.CloneFileByPath(dstFile, srcFile); err != nil {\n\t\treturn false, err\n\t} else if !ok {\n\t\treturn false, errors.Errorf(\"unknown clone file error\")\n\t}\n\n\t\/\/ Recover original state\n\tif err := os.Chmod(dstFile, originalStat.Mode()); err != nil {\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}\n\nfunc init() {\n\tRegisterCommand(\"dedup\", dedupCommand, func(cmd *cobra.Command) {\n\t\tcmd.Flags().BoolVarP(&dedupFlags.test, \"test\", \"t\", false, \"test\")\n\t})\n}\n<commit_msg>command\/command_dedup.go: exit if extentions exist<commit_after>package commands\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sync\/atomic\"\n\n\t\"github.com\/git-lfs\/git-lfs\/config\"\n\t\"github.com\/git-lfs\/git-lfs\/errors\"\n\t\"github.com\/git-lfs\/git-lfs\/git\"\n\t\"github.com\/git-lfs\/git-lfs\/lfs\"\n\t\"github.com\/git-lfs\/git-lfs\/tools\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tdedupFlags = struct {\n\t\ttest bool\n\t}{}\n\tdedupStats = &struct {\n\t\ttotalProcessedCount int64\n\t\ttotalProcessedSize  int64\n\t}{}\n)\n\nfunc dedupTestCommand(*cobra.Command, []string) {\n\trequireInRepo()\n\n\tif supported, err := tools.CheckCloneFileSupported(cfg.TempDir()); err != nil || !supported {\n\t\tif err == nil {\n\t\t\terr = errors.New(\"Unknown reason.\")\n\t\t}\n\t\tExit(\"This system does not support deduplication. %s\", err)\n\t}\n\n\tif len(cfg.Extensions()) > 0 {\n\t\tExit(\"This platform supports file de-duplication, however, Git LFS extensions are configured and therefore de-duplication can not be used.\")\n\t}\n\n\tPrint(\"OK: This platform and repository support file de-duplication.\")\n}\n\nfunc dedupCommand(cmd *cobra.Command, args []string) {\n\tif dedupFlags.test {\n\t\tdedupTestCommand(cmd, args)\n\t\treturn\n\t}\n\n\trequireInRepo()\n\tif gitDir, err := git.GitDir(); err != nil {\n\t\tExitWithError(err)\n\t} else if supported, err := tools.CheckCloneFileSupported(gitDir); err != nil || !supported {\n\t\tExit(\"This system does not support deduplication.\")\n\t}\n\n\tif len(cfg.Extensions()) > 0 {\n\t\tExit(\"This platform supports file de-duplication, however, Git LFS extensions are configured and therefore de-duplication can not be used.\")\n\t}\n\n\tif dirty, err := git.IsWorkingCopyDirty(); err != nil {\n\t\tExitWithError(err)\n\t} else if dirty {\n\t\tExit(\"Working tree is dirty. Please commit or reset your change.\")\n\t}\n\n\t\/\/ We assume working tree is clean.\n\tgitScanner := lfs.NewGitScanner(config.New(), func(p *lfs.WrappedPointer, err error) {\n\t\tif err != nil {\n\t\t\tExit(\"Could not scan for Git LFS tree: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif success, err := dedup(p); err != nil {\n\t\t\tError(\"Skipped: %s (Size: %d)\\n          %s\", p.Name, p.Size, err)\n\t\t} else if !success {\n\t\t\tError(\"Skipped: %s (Size: %d)\", p.Name, p.Size)\n\t\t} else if success {\n\t\t\tPrint(\"Success: %s (Size: %d)\", p.Name, p.Size)\n\n\t\t\tatomic.AddInt64(&dedupStats.totalProcessedCount, 1)\n\t\t\tatomic.AddInt64(&dedupStats.totalProcessedSize, p.Size)\n\t\t}\n\t})\n\tdefer gitScanner.Close()\n\n\tif err := gitScanner.ScanTree(\"HEAD\"); err != nil {\n\t\tExitWithError(err)\n\t}\n\n\tPrint(\"\\n\\nSuccessfully finished.\\n\"+\n\t\t\"  De-duplicated  size: %d bytes\\n\"+\n\t\t\"                count: %d\",\n\t\tdedupStats.totalProcessedSize,\n\t\tdedupStats.totalProcessedCount)\n}\n\n\/\/ dedup executes\n\/\/ Precondition: working tree MUST clean. We can replace working tree files from mediafile safely.\nfunc dedup(p *lfs.WrappedPointer) (success bool, err error) {\n\t\/\/ PRECONDITION, check ofs object exists or skip this file.\n\tif !cfg.LFSObjectExists(p.Oid, p.Size) { \/\/ Not exists,\n\t\t\/\/ Basically, this is not happens because executing 'git status' in `git.IsWorkingCopyDirty()` recover it.\n\t\treturn false, errors.New(\"mediafile is not exist\")\n\t}\n\n\t\/\/ DO de-dup\n\t\/\/ Gather original state\n\toriginalStat, err := os.Stat(p.Name)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ Do clone\n\tsrcFile := cfg.Filesystem().ObjectPathname(p.Oid)\n\tdstFile := filepath.Join(cfg.LocalWorkingDir(), p.Name)\n\n\t\/\/ Clone the file. This overwrites the destination if it exists.\n\tif ok, err := tools.CloneFileByPath(dstFile, srcFile); err != nil {\n\t\treturn false, err\n\t} else if !ok {\n\t\treturn false, errors.Errorf(\"unknown clone file error\")\n\t}\n\n\t\/\/ Recover original state\n\tif err := os.Chmod(dstFile, originalStat.Mode()); err != nil {\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}\n\nfunc init() {\n\tRegisterCommand(\"dedup\", dedupCommand, func(cmd *cobra.Command) {\n\t\tcmd.Flags().BoolVarP(&dedupFlags.test, \"test\", \"t\", false, \"test\")\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"io\"\n\t\"os\/exec\"\n\t\"github.com\/dotcloud\/docker\/pkg\/beam\"\n\t\"github.com\/dotcloud\/docker\/pkg\/beam\/data\"\n\t\"github.com\/dotcloud\/docker\/pkg\/term\"\n\t\"text\/template\"\n\t\"fmt\"\n\t\"sync\"\n\t\"os\"\n\t\"strings\"\n\t\"path\"\n\t\"bufio\"\n\t\"net\"\n\t\"net\/url\"\n)\n\n\nfunc CmdLogger(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif err := os.MkdirAll(\"logs\", 0700); err != nil {\n\t\tfmt.Fprintf(stderr, \"%v\\n\", err)\n\t\treturn\n\t}\n\tvar tasks sync.WaitGroup\n\tdefer tasks.Wait()\n\tvar n int = 1\n\tr := beam.NewRouter(out)\n\tr.NewRoute().HasAttachment().KeyStartsWith(\"cmd\", \"log\").Handler(func (payload []byte, attachment *os.File) error {\n\t\ttasks.Add(1)\n\t\tgo func(n int) {\n\t\t\tdefer tasks.Done()\n\t\t\tdefer attachment.Close()\n\t\t\tvar streamname string\n\t\t\tif cmd := data.Message(payload).Get(\"cmd\"); len(cmd) == 1 || cmd[1] == \"stdout\" {\n\t\t\t\tstreamname = \"stdout\"\n\t\t\t} else {\n\t\t\t\tstreamname = cmd[1]\n\t\t\t}\n\t\t\tif fromcmd := data.Message(payload).Get(\"fromcmd\"); len(fromcmd) != 0 {\n\t\t\t\tstreamname = fmt.Sprintf(\"%s-%s\", strings.Replace(strings.Join(fromcmd, \"_\"), \"\/\", \"_\", -1), streamname)\n\t\t\t}\n\t\t\tlogfile, err := os.OpenFile(path.Join(\"logs\", fmt.Sprintf(\"%d-%s\", n, streamname)), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0700)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(stderr, \"%v\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer logfile.Close()\n\t\t\tio.Copy(logfile, attachment)\n\t\t\tlogfile.Sync()\n\t\t}(n)\n\t\tn++\n\t\treturn nil\n\t}).Tee(out)\n\tif _, err := beam.Copy(r, in); err != nil {\n\t\tfmt.Fprintf(stderr, \"%v\\n\", err)\n\t\treturn\n\t}\n}\n\nfunc CmdRender(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif len(args) != 2 {\n\t\tfmt.Fprintf(stderr, \"Usage: %s FORMAT\\n\", args[0])\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Bytes(), nil)\n\t\treturn\n\t}\n\ttxt := args[1]\n\tif !strings.HasSuffix(txt, \"\\n\") {\n\t\ttxt += \"\\n\"\n\t}\n\tt := template.Must(template.New(\"render\").Parse(txt))\n\tfor {\n\t\tpayload, attachment, err := in.Receive()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tmsg, err := data.Decode(string(payload))\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(stderr, \"decode error: %v\\n\")\n\t\t}\n\t\tif err := t.Execute(stdout, msg); err != nil {\n\t\t\tfmt.Fprintf(stderr, \"rendering error: %v\\n\", err)\n\t\t\tout.Send(data.Empty().Set(\"status\", \"1\").Bytes(), nil)\n\t\t\treturn\n\t\t}\n\t\tif err := out.Send(payload, attachment); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc CmdDevnull(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tfor {\n\t\t_, attachment, err := in.Receive()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif attachment != nil {\n\t\t\tattachment.Close()\n\t\t}\n\t}\n}\n\nfunc CmdPrompt(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif len(args) < 2 {\n\t\tfmt.Fprintf(stderr, \"usage: %s PROMPT...\\n\", args[0])\n\t\treturn\n\t}\n\tif !term.IsTerminal(0) {\n\t\tfmt.Fprintf(stderr, \"can't prompt: no tty available...\\n\")\n\t\treturn\n\t}\n\tfmt.Printf(\"%s: \", strings.Join(args[1:], \" \"))\n\toldState, _ := term.SaveState(0)\n\tterm.DisableEcho(0, oldState)\n\tline, _, err := bufio.NewReader(os.Stdin).ReadLine()\n\tif err != nil {\n\t\tfmt.Fprintln(stderr, err.Error())\n\t\treturn\n\t}\n\tval := string(line)\n\tfmt.Printf(\"\\n\")\n\tterm.RestoreTerminal(0, oldState)\n\tout.Send(data.Empty().Set(\"fromcmd\", args...).Set(\"value\", val).Bytes(), nil)\n}\n\nfunc CmdStdio(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tvar tasks sync.WaitGroup\n\tdefer tasks.Wait()\n\n\tr := beam.NewRouter(out)\n\tr.NewRoute().HasAttachment().KeyStartsWith(\"cmd\", \"log\").Handler(func(payload []byte, attachment *os.File) error {\n\t\ttasks.Add(1)\n\t\tgo func() {\n\t\t\tdefer tasks.Done()\n\t\t\tdefer attachment.Close()\n\t\t\tio.Copy(os.Stdout, attachment)\n\t\t\tattachment.Close()\n\t\t}()\n\t\treturn nil\n\t}).Tee(out)\n\n\tif _, err := beam.Copy(r, in); err != nil {\n\t\tFatal(err)\n\t\tfmt.Fprintf(stderr, \"%v\\n\", err)\n\t\treturn\n\t}\n}\n\nfunc CmdEcho(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tfmt.Fprintln(stdout, strings.Join(args[1:], \" \"))\n}\n\nfunc CmdPass(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tfor {\n\t\tpayload, attachment, err := in.Receive()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif err := out.Send(payload, attachment); err != nil {\n\t\t\tif attachment != nil {\n\t\t\t\tattachment.Close()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc CmdIn(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tos.Chdir(args[1])\n\tGetHandler(\"pass\")([]string{\"pass\"}, stdout, stderr, in, out)\n}\n\nfunc CmdExec(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tcmd := exec.Command(args[1], args[2:]...)\n\tcmd.Stdout = stdout\n\tcmd.Stderr = stderr\n\tcmd.Stdin = os.Stdin\n\texecErr := cmd.Run()\n\tvar status string\n\tif execErr != nil {\n\t\tstatus = execErr.Error()\n\t} else {\n\t\tstatus = \"ok\"\n\t}\n\tout.Send(data.Empty().Set(\"status\", status).Set(\"cmd\", args...).Bytes(), nil)\n}\n\nfunc CmdTrace(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tfor {\n\t\tp, a, err := in.Receive()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tvar msg string\n\t\tif pretty := data.Message(string(p)).Pretty(); pretty != \"\" {\n\t\t\tmsg = pretty\n\t\t} else {\n\t\t\tmsg = string(p)\n\t\t}\n\t\tif a != nil {\n\t\t\tmsg = fmt.Sprintf(\"%s [%d]\", msg, a.Fd())\n\t\t}\n\t\tfmt.Printf(\"===> %s\\n\", msg)\n\t\tout.Send(p, a)\n\t}\n}\n\nfunc CmdEmit(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tout.Send(data.Parse(args[1:]).Bytes(), nil)\n}\n\nfunc CmdPrint(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tfor {\n\t\tpayload, a, err := in.Receive()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t\/\/ Skip commands\n\t\tif a != nil && data.Message(payload).Get(\"cmd\") == nil {\n\t\t\tdup, err := beam.SendPipe(out, payload)\n\t\t\tif err != nil {\n\t\t\t\ta.Close()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tio.Copy(io.MultiWriter(os.Stdout, dup), a)\n\t\t\tdup.Close()\n\t\t} else {\n\t\t\tif err := out.Send(payload, a); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc CmdMultiprint(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tvar tasks sync.WaitGroup\n\tfor {\n\t\tpayload, a, err := in.Receive()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif a != nil {\n\t\t\ttasks.Add(1)\n\t\t\tgo func(payload []byte, attachment *os.File) {\n\t\t\t\tdefer tasks.Done()\n\t\t\t\tmsg := data.Message(string(payload))\n\t\t\t\tinput := bufio.NewScanner(attachment)\n\t\t\t\tfor input.Scan() {\n\t\t\t\t\tfmt.Printf(\"[%s] %s\\n\", msg.Pretty(), input.Text())\n\t\t\t\t}\n\t\t\t}(payload, a)\n\t\t}\n\t}\n\ttasks.Wait()\n}\n\nfunc CmdListen(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif len(args) != 2 {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", \"wrong number of arguments\").Bytes(), nil)\n\t\treturn\n\t}\n\tu, err := url.Parse(args[1])\n\tif err != nil {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", err.Error()).Bytes(), nil)\n\t\treturn\n\t}\n\tl, err := net.Listen(u.Scheme, u.Host)\n\tif err != nil {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", err.Error()).Bytes(), nil)\n\t\treturn\n\t}\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", err.Error()).Bytes(), nil)\n\t\t\treturn\n\t\t}\n\t\tf, err := connToFile(conn)\n\t\tif err != nil {\n\t\t\tconn.Close()\n\t\t\tcontinue\n\t\t}\n\t\tout.Send(data.Empty().Set(\"type\", \"socket\").Set(\"remoteaddr\", conn.RemoteAddr().String()).Bytes(), f)\n\t}\n}\n\nfunc CmdBeamsend(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif len(args) < 2 {\n\t\tif err := out.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", \"wrong number of arguments\").Bytes(), nil); err != nil {\n\t\t\tFatal(err)\n\t\t}\n\t\treturn\n\t}\n\tvar connector func(string) (chan net.Conn, error)\n\tconnector = dialer\n\tconnections, err := connector(args[1])\n\tif err != nil {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", err.Error()).Bytes(), nil)\n\t\treturn\n\t}\n\t\/\/ Copy in to conn\n\tSendToConn(connections, in)\n}\n\nfunc CmdBeamreceive(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif len(args) != 2 {\n\t\tif err := out.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", \"wrong number of arguments\").Bytes(), nil); err != nil {\n\t\t\tFatal(err)\n\t\t}\n\t\treturn\n\t}\n\tvar connector func(string) (chan net.Conn, error)\n\tconnector = listener\n\tconnections, err := connector(args[1])\n\tif err != nil {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", err.Error()).Bytes(), nil)\n\t\treturn\n\t}\n\t\/\/ Copy in to conn\n\tReceiveFromConn(connections, out)\n}\n\nfunc CmdConnect(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif len(args) != 2 {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", \"wrong number of arguments\").Bytes(), nil)\n\t\treturn\n\t}\n\tu, err := url.Parse(args[1])\n\tif err != nil {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", err.Error()).Bytes(), nil)\n\t\treturn\n\t}\n\tvar tasks sync.WaitGroup\n\tfor {\n\t\t_, attachment, err := in.Receive()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif attachment == nil {\n\t\t\tcontinue\n\t\t}\n\t\tLogf(\"connecting to %s\/%s\\n\", u.Scheme, u.Host)\n\t\tconn, err := net.Dial(u.Scheme, u.Host)\n\t\tif err != nil {\n\t\t\tout.Send(data.Empty().Set(\"cmd\", \"msg\", \"connect error: \" + err.Error()).Bytes(), nil)\n\t\t\treturn\n\t\t}\n\t\tout.Send(data.Empty().Set(\"cmd\", \"msg\", \"connection established\").Bytes(), nil)\n\t\ttasks.Add(1)\n\t\tgo func(attachment *os.File, conn net.Conn) {\n\t\t\tdefer tasks.Done()\n\t\t\t\/\/ even when successful, conn.File() returns a duplicate,\n\t\t\t\/\/ so we must close the original\n\t\t\tvar iotasks sync.WaitGroup\n\t\t\tiotasks.Add(2)\n\t\t\tgo func(attachment *os.File, conn net.Conn) {\n\t\t\t\tdefer iotasks.Done()\n\t\t\t\tio.Copy(attachment, conn)\n\t\t\t}(attachment, conn)\n\t\t\tgo func(attachment *os.File, conn net.Conn) {\n\t\t\t\tdefer iotasks.Done()\n\t\t\t\tio.Copy(conn, attachment)\n\t\t\t}(attachment, conn)\n\t\t\tiotasks.Wait()\n\t\t\tconn.Close()\n\t\t\tattachment.Close()\n\t\t}(attachment, conn)\n\t}\n\ttasks.Wait()\n}\n\nfunc CmdOpenfile(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tfor _, name := range args {\n\t\tf, err := os.Open(name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := out.Send(data.Empty().Set(\"path\", name).Set(\"type\", \"file\").Bytes(), f); err != nil {\n\t\t\tf.Close()\n\t\t}\n\t}\n}\n<commit_msg>beam\/examples\/beamsh: use beam.Router to simplify 'trace'<commit_after>package main\n\nimport (\n\t\"io\"\n\t\"os\/exec\"\n\t\"github.com\/dotcloud\/docker\/pkg\/beam\"\n\t\"github.com\/dotcloud\/docker\/pkg\/beam\/data\"\n\t\"github.com\/dotcloud\/docker\/pkg\/term\"\n\t\"text\/template\"\n\t\"fmt\"\n\t\"sync\"\n\t\"os\"\n\t\"strings\"\n\t\"path\"\n\t\"bufio\"\n\t\"net\"\n\t\"net\/url\"\n)\n\n\nfunc CmdLogger(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif err := os.MkdirAll(\"logs\", 0700); err != nil {\n\t\tfmt.Fprintf(stderr, \"%v\\n\", err)\n\t\treturn\n\t}\n\tvar tasks sync.WaitGroup\n\tdefer tasks.Wait()\n\tvar n int = 1\n\tr := beam.NewRouter(out)\n\tr.NewRoute().HasAttachment().KeyStartsWith(\"cmd\", \"log\").Handler(func (payload []byte, attachment *os.File) error {\n\t\ttasks.Add(1)\n\t\tgo func(n int) {\n\t\t\tdefer tasks.Done()\n\t\t\tdefer attachment.Close()\n\t\t\tvar streamname string\n\t\t\tif cmd := data.Message(payload).Get(\"cmd\"); len(cmd) == 1 || cmd[1] == \"stdout\" {\n\t\t\t\tstreamname = \"stdout\"\n\t\t\t} else {\n\t\t\t\tstreamname = cmd[1]\n\t\t\t}\n\t\t\tif fromcmd := data.Message(payload).Get(\"fromcmd\"); len(fromcmd) != 0 {\n\t\t\t\tstreamname = fmt.Sprintf(\"%s-%s\", strings.Replace(strings.Join(fromcmd, \"_\"), \"\/\", \"_\", -1), streamname)\n\t\t\t}\n\t\t\tlogfile, err := os.OpenFile(path.Join(\"logs\", fmt.Sprintf(\"%d-%s\", n, streamname)), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0700)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(stderr, \"%v\\n\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer logfile.Close()\n\t\t\tio.Copy(logfile, attachment)\n\t\t\tlogfile.Sync()\n\t\t}(n)\n\t\tn++\n\t\treturn nil\n\t}).Tee(out)\n\tif _, err := beam.Copy(r, in); err != nil {\n\t\tfmt.Fprintf(stderr, \"%v\\n\", err)\n\t\treturn\n\t}\n}\n\nfunc CmdRender(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif len(args) != 2 {\n\t\tfmt.Fprintf(stderr, \"Usage: %s FORMAT\\n\", args[0])\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Bytes(), nil)\n\t\treturn\n\t}\n\ttxt := args[1]\n\tif !strings.HasSuffix(txt, \"\\n\") {\n\t\ttxt += \"\\n\"\n\t}\n\tt := template.Must(template.New(\"render\").Parse(txt))\n\tfor {\n\t\tpayload, attachment, err := in.Receive()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tmsg, err := data.Decode(string(payload))\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(stderr, \"decode error: %v\\n\")\n\t\t}\n\t\tif err := t.Execute(stdout, msg); err != nil {\n\t\t\tfmt.Fprintf(stderr, \"rendering error: %v\\n\", err)\n\t\t\tout.Send(data.Empty().Set(\"status\", \"1\").Bytes(), nil)\n\t\t\treturn\n\t\t}\n\t\tif err := out.Send(payload, attachment); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc CmdDevnull(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tfor {\n\t\t_, attachment, err := in.Receive()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif attachment != nil {\n\t\t\tattachment.Close()\n\t\t}\n\t}\n}\n\nfunc CmdPrompt(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif len(args) < 2 {\n\t\tfmt.Fprintf(stderr, \"usage: %s PROMPT...\\n\", args[0])\n\t\treturn\n\t}\n\tif !term.IsTerminal(0) {\n\t\tfmt.Fprintf(stderr, \"can't prompt: no tty available...\\n\")\n\t\treturn\n\t}\n\tfmt.Printf(\"%s: \", strings.Join(args[1:], \" \"))\n\toldState, _ := term.SaveState(0)\n\tterm.DisableEcho(0, oldState)\n\tline, _, err := bufio.NewReader(os.Stdin).ReadLine()\n\tif err != nil {\n\t\tfmt.Fprintln(stderr, err.Error())\n\t\treturn\n\t}\n\tval := string(line)\n\tfmt.Printf(\"\\n\")\n\tterm.RestoreTerminal(0, oldState)\n\tout.Send(data.Empty().Set(\"fromcmd\", args...).Set(\"value\", val).Bytes(), nil)\n}\n\nfunc CmdStdio(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tvar tasks sync.WaitGroup\n\tdefer tasks.Wait()\n\n\tr := beam.NewRouter(out)\n\tr.NewRoute().HasAttachment().KeyStartsWith(\"cmd\", \"log\").Handler(func(payload []byte, attachment *os.File) error {\n\t\ttasks.Add(1)\n\t\tgo func() {\n\t\t\tdefer tasks.Done()\n\t\t\tdefer attachment.Close()\n\t\t\tio.Copy(os.Stdout, attachment)\n\t\t\tattachment.Close()\n\t\t}()\n\t\treturn nil\n\t}).Tee(out)\n\n\tif _, err := beam.Copy(r, in); err != nil {\n\t\tFatal(err)\n\t\tfmt.Fprintf(stderr, \"%v\\n\", err)\n\t\treturn\n\t}\n}\n\nfunc CmdEcho(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tfmt.Fprintln(stdout, strings.Join(args[1:], \" \"))\n}\n\nfunc CmdPass(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tfor {\n\t\tpayload, attachment, err := in.Receive()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif err := out.Send(payload, attachment); err != nil {\n\t\t\tif attachment != nil {\n\t\t\t\tattachment.Close()\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc CmdIn(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tos.Chdir(args[1])\n\tGetHandler(\"pass\")([]string{\"pass\"}, stdout, stderr, in, out)\n}\n\nfunc CmdExec(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tcmd := exec.Command(args[1], args[2:]...)\n\tcmd.Stdout = stdout\n\tcmd.Stderr = stderr\n\tcmd.Stdin = os.Stdin\n\texecErr := cmd.Run()\n\tvar status string\n\tif execErr != nil {\n\t\tstatus = execErr.Error()\n\t} else {\n\t\tstatus = \"ok\"\n\t}\n\tout.Send(data.Empty().Set(\"status\", status).Set(\"cmd\", args...).Bytes(), nil)\n}\n\nfunc CmdTrace(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tr := beam.NewRouter(out)\n\tr.NewRoute().All().Handler(func(payload []byte, attachment *os.File) error {\n\t\tfmt.Printf(\"===> %s\\n\", beam.MsgDesc(payload, attachment))\n\t\tout.Send(payload, attachment)\n\t\treturn nil\n\t})\n\tbeam.Copy(r, in)\n}\n\nfunc CmdEmit(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tout.Send(data.Parse(args[1:]).Bytes(), nil)\n}\n\nfunc CmdPrint(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tfor {\n\t\tpayload, a, err := in.Receive()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\t\/\/ Skip commands\n\t\tif a != nil && data.Message(payload).Get(\"cmd\") == nil {\n\t\t\tdup, err := beam.SendPipe(out, payload)\n\t\t\tif err != nil {\n\t\t\t\ta.Close()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tio.Copy(io.MultiWriter(os.Stdout, dup), a)\n\t\t\tdup.Close()\n\t\t} else {\n\t\t\tif err := out.Send(payload, a); err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc CmdMultiprint(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tvar tasks sync.WaitGroup\n\tfor {\n\t\tpayload, a, err := in.Receive()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif a != nil {\n\t\t\ttasks.Add(1)\n\t\t\tgo func(payload []byte, attachment *os.File) {\n\t\t\t\tdefer tasks.Done()\n\t\t\t\tmsg := data.Message(string(payload))\n\t\t\t\tinput := bufio.NewScanner(attachment)\n\t\t\t\tfor input.Scan() {\n\t\t\t\t\tfmt.Printf(\"[%s] %s\\n\", msg.Pretty(), input.Text())\n\t\t\t\t}\n\t\t\t}(payload, a)\n\t\t}\n\t}\n\ttasks.Wait()\n}\n\nfunc CmdListen(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif len(args) != 2 {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", \"wrong number of arguments\").Bytes(), nil)\n\t\treturn\n\t}\n\tu, err := url.Parse(args[1])\n\tif err != nil {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", err.Error()).Bytes(), nil)\n\t\treturn\n\t}\n\tl, err := net.Listen(u.Scheme, u.Host)\n\tif err != nil {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", err.Error()).Bytes(), nil)\n\t\treturn\n\t}\n\tfor {\n\t\tconn, err := l.Accept()\n\t\tif err != nil {\n\t\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", err.Error()).Bytes(), nil)\n\t\t\treturn\n\t\t}\n\t\tf, err := connToFile(conn)\n\t\tif err != nil {\n\t\t\tconn.Close()\n\t\t\tcontinue\n\t\t}\n\t\tout.Send(data.Empty().Set(\"type\", \"socket\").Set(\"remoteaddr\", conn.RemoteAddr().String()).Bytes(), f)\n\t}\n}\n\nfunc CmdBeamsend(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif len(args) < 2 {\n\t\tif err := out.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", \"wrong number of arguments\").Bytes(), nil); err != nil {\n\t\t\tFatal(err)\n\t\t}\n\t\treturn\n\t}\n\tvar connector func(string) (chan net.Conn, error)\n\tconnector = dialer\n\tconnections, err := connector(args[1])\n\tif err != nil {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", err.Error()).Bytes(), nil)\n\t\treturn\n\t}\n\t\/\/ Copy in to conn\n\tSendToConn(connections, in)\n}\n\nfunc CmdBeamreceive(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif len(args) != 2 {\n\t\tif err := out.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", \"wrong number of arguments\").Bytes(), nil); err != nil {\n\t\t\tFatal(err)\n\t\t}\n\t\treturn\n\t}\n\tvar connector func(string) (chan net.Conn, error)\n\tconnector = listener\n\tconnections, err := connector(args[1])\n\tif err != nil {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", err.Error()).Bytes(), nil)\n\t\treturn\n\t}\n\t\/\/ Copy in to conn\n\tReceiveFromConn(connections, out)\n}\n\nfunc CmdConnect(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tif len(args) != 2 {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", \"wrong number of arguments\").Bytes(), nil)\n\t\treturn\n\t}\n\tu, err := url.Parse(args[1])\n\tif err != nil {\n\t\tout.Send(data.Empty().Set(\"status\", \"1\").Set(\"message\", err.Error()).Bytes(), nil)\n\t\treturn\n\t}\n\tvar tasks sync.WaitGroup\n\tfor {\n\t\t_, attachment, err := in.Receive()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif attachment == nil {\n\t\t\tcontinue\n\t\t}\n\t\tLogf(\"connecting to %s\/%s\\n\", u.Scheme, u.Host)\n\t\tconn, err := net.Dial(u.Scheme, u.Host)\n\t\tif err != nil {\n\t\t\tout.Send(data.Empty().Set(\"cmd\", \"msg\", \"connect error: \" + err.Error()).Bytes(), nil)\n\t\t\treturn\n\t\t}\n\t\tout.Send(data.Empty().Set(\"cmd\", \"msg\", \"connection established\").Bytes(), nil)\n\t\ttasks.Add(1)\n\t\tgo func(attachment *os.File, conn net.Conn) {\n\t\t\tdefer tasks.Done()\n\t\t\t\/\/ even when successful, conn.File() returns a duplicate,\n\t\t\t\/\/ so we must close the original\n\t\t\tvar iotasks sync.WaitGroup\n\t\t\tiotasks.Add(2)\n\t\t\tgo func(attachment *os.File, conn net.Conn) {\n\t\t\t\tdefer iotasks.Done()\n\t\t\t\tio.Copy(attachment, conn)\n\t\t\t}(attachment, conn)\n\t\t\tgo func(attachment *os.File, conn net.Conn) {\n\t\t\t\tdefer iotasks.Done()\n\t\t\t\tio.Copy(conn, attachment)\n\t\t\t}(attachment, conn)\n\t\t\tiotasks.Wait()\n\t\t\tconn.Close()\n\t\t\tattachment.Close()\n\t\t}(attachment, conn)\n\t}\n\ttasks.Wait()\n}\n\nfunc CmdOpenfile(args []string, stdout, stderr io.Writer, in beam.Receiver, out beam.Sender) {\n\tfor _, name := range args {\n\t\tf, err := os.Open(name)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := out.Send(data.Empty().Set(\"path\", name).Set(\"type\", \"file\").Bytes(), f); err != nil {\n\t\t\tf.Close()\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package commands\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/github\/git-lfs\/lfs\"\n\t\"github.com\/github\/git-lfs\/vendor\/_nuts\/github.com\/spf13\/cobra\"\n)\n\nvar (\n\ttrackCmd = &cobra.Command{\n\t\tUse:   \"track\",\n\t\tShort: \"Manipulate .gitattributes\",\n\t\tRun:   trackCommand,\n\t}\n)\n\nfunc trackCommand(cmd *cobra.Command, args []string) {\n\tif lfs.LocalGitDir == \"\" {\n\t\tPrint(\"Not a git repository.\")\n\t\tos.Exit(128)\n\t}\n\n\tlfs.InstallHooks(false)\n\tknownPaths := findPaths()\n\n\tif len(args) == 0 {\n\t\tPrint(\"Listing tracked paths\")\n\t\tfor _, t := range knownPaths {\n\t\t\tPrint(\"    %s (%s)\", t.Path, t.Source)\n\t\t}\n\t\treturn\n\t}\n\n\taddTrailingLinebreak := needsTrailingLinebreak(\".gitattributes\")\n\tattributesFile, err := os.OpenFile(\".gitattributes\", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660)\n\tif err != nil {\n\t\tPrint(\"Error opening .gitattributes file\")\n\t\treturn\n\t}\n\tdefer attributesFile.Close()\n\n\tif addTrailingLinebreak {\n\t\tif _, err := attributesFile.WriteString(\"\\n\"); err != nil {\n\t\t\tPrint(\"Error writing to .gitattributes\")\n\t\t}\n\t}\n\nArgsLoop:\n\tfor _, t := range args {\n\t\tfor _, k := range knownPaths {\n\t\t\tif t == k.Path {\n\t\t\t\tPrint(\"%s already supported\", t)\n\t\t\t\tcontinue ArgsLoop\n\t\t\t}\n\t\t}\n\n\t\tencodedArg := strings.Replace(t, \" \", \"[[:space:]]\", -1)\n\t\t_, err := attributesFile.WriteString(fmt.Sprintf(\"%s filter=lfs diff=lfs merge=lfs -crlf\\n\", encodedArg))\n\t\tif err != nil {\n\t\t\tPrint(\"Error adding path %s\", t)\n\t\t\tcontinue\n\t\t}\n\t\tPrint(\"Tracking %s\", t)\n\t}\n}\n\ntype mediaPath struct {\n\tPath   string\n\tSource string\n}\n\nfunc findPaths() []mediaPath {\n\tpaths := make([]mediaPath, 0)\n\twd, _ := os.Getwd()\n\n\tfor _, path := range findAttributeFiles() {\n\t\tattributes, err := os.Open(path)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tscanner := bufio.NewScanner(attributes)\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif strings.Contains(line, \"filter=lfs\") {\n\t\t\t\tfields := strings.Fields(line)\n\t\t\t\trelPath, _ := filepath.Rel(wd, path)\n\t\t\t\tpaths = append(paths, mediaPath{Path: fields[0], Source: relPath})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn paths\n}\n\nfunc findAttributeFiles() []string {\n\tpaths := make([]string, 0)\n\n\trepoAttributes := filepath.Join(lfs.LocalGitDir, \"info\", \"attributes\")\n\tif info, err := os.Stat(repoAttributes); err == nil && !info.IsDir() {\n\t\tpaths = append(paths, repoAttributes)\n\t}\n\n\tfilepath.Walk(lfs.LocalWorkingDir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !info.IsDir() && (filepath.Base(path) == \".gitattributes\") {\n\t\t\tpaths = append(paths, path)\n\t\t}\n\t\treturn nil\n\t})\n\n\treturn paths\n}\n\nfunc needsTrailingLinebreak(filename string) bool {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer file.Close()\n\n\tbuf := make([]byte, 16384)\n\tbytesRead := 0\n\tfor {\n\t\tn, err := file.Read(buf)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn false\n\t\t}\n\t\tbytesRead = n\n\t}\n\n\treturn !strings.HasSuffix(string(buf[0:bytesRead]), \"\\n\")\n}\n\nfunc init() {\n\tRootCmd.AddCommand(trackCmd)\n}\n<commit_msg>アアー アアアア アーアア<commit_after>package commands\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/github\/git-lfs\/lfs\"\n\t\"github.com\/github\/git-lfs\/vendor\/_nuts\/github.com\/spf13\/cobra\"\n)\n\nvar (\n\ttrackCmd = &cobra.Command{\n\t\tUse:   \"track\",\n\t\tShort: \"Manipulate .gitattributes\",\n\t\tRun:   trackCommand,\n\t}\n)\n\nfunc trackCommand(cmd *cobra.Command, args []string) {\n\tif lfs.LocalGitDir == \"\" {\n\t\tPrint(\"Not a git repository.\")\n\t\tos.Exit(128)\n\t}\n\n\tlfs.InstallHooks(false)\n\tknownPaths := findPaths()\n\n\tif len(args) == 0 {\n\t\tPrint(\"Listing tracked paths\")\n\t\tfor _, t := range knownPaths {\n\t\t\tPrint(\"    %s (%s)\", t.Path, t.Source)\n\t\t}\n\t\treturn\n\t}\n\n\taddTrailingLinebreak := needsTrailingLinebreak(\".gitattributes\")\n\tattributesFile, err := os.OpenFile(\".gitattributes\", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660)\n\tif err != nil {\n\t\tPrint(\"Error opening .gitattributes file\")\n\t\treturn\n\t}\n\tdefer attributesFile.Close()\n\n\tif addTrailingLinebreak {\n\t\tif _, err := attributesFile.WriteString(\"\\n\"); err != nil {\n\t\t\tPrint(\"Error writing to .gitattributes\")\n\t\t}\n\t}\n\n\twd, _ := os.Getwd()\n\nArgsLoop:\n\tfor _, t := range args {\n\t\tabsT, _ := absRelPath(t, wd)\n\t\tfor _, k := range knownPaths {\n\t\t\tabsK, _ := absRelPath(k.Path, filepath.Join(wd, filepath.Dir(k.Source)))\n\t\t\tif absT == absK {\n\t\t\t\tPrint(\"%s already supported\", t)\n\t\t\t\tcontinue ArgsLoop\n\t\t\t}\n\t\t}\n\n\t\tencodedArg := strings.Replace(t, \" \", \"[[:space:]]\", -1)\n\t\t_, err := attributesFile.WriteString(fmt.Sprintf(\"%s filter=lfs diff=lfs merge=lfs -crlf\\n\", encodedArg))\n\t\tif err != nil {\n\t\t\tPrint(\"Error adding path %s\", t)\n\t\t\tcontinue\n\t\t}\n\t\tPrint(\"Tracking %s\", t)\n\t}\n}\n\ntype mediaPath struct {\n\tPath   string\n\tSource string\n}\n\nfunc findPaths() []mediaPath {\n\tpaths := make([]mediaPath, 0)\n\twd, _ := os.Getwd()\n\n\tfor _, path := range findAttributeFiles() {\n\t\tattributes, err := os.Open(path)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tscanner := bufio.NewScanner(attributes)\n\t\tfor scanner.Scan() {\n\t\t\tline := scanner.Text()\n\t\t\tif strings.Contains(line, \"filter=lfs\") {\n\t\t\t\tfields := strings.Fields(line)\n\t\t\t\trelPath, _ := filepath.Rel(wd, path)\n\t\t\t\tpaths = append(paths, mediaPath{Path: fields[0], Source: relPath})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn paths\n}\n\nfunc findAttributeFiles() []string {\n\tpaths := make([]string, 0)\n\n\trepoAttributes := filepath.Join(lfs.LocalGitDir, \"info\", \"attributes\")\n\tif info, err := os.Stat(repoAttributes); err == nil && !info.IsDir() {\n\t\tpaths = append(paths, repoAttributes)\n\t}\n\n\tfilepath.Walk(lfs.LocalWorkingDir, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !info.IsDir() && (filepath.Base(path) == \".gitattributes\") {\n\t\t\tpaths = append(paths, path)\n\t\t}\n\t\treturn nil\n\t})\n\n\treturn paths\n}\n\nfunc needsTrailingLinebreak(filename string) bool {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn false\n\t}\n\tdefer file.Close()\n\n\tbuf := make([]byte, 16384)\n\tbytesRead := 0\n\tfor {\n\t\tn, err := file.Read(buf)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\treturn false\n\t\t}\n\t\tbytesRead = n\n\t}\n\n\treturn !strings.HasSuffix(string(buf[0:bytesRead]), \"\\n\")\n}\n\n\/\/ absRelPath takes a path and a working directory and\n\/\/ returns an absolute and a relative representation of path based on the working directory\nfunc absRelPath(path, wd string) (string, string) {\n\tif filepath.IsAbs(path) {\n\t\trelPath, _ := filepath.Rel(wd, path)\n\t\treturn path, relPath\n\t}\n\n\tabsPath := filepath.Join(wd, path)\n\treturn absPath, path\n}\n\nfunc init() {\n\tRootCmd.AddCommand(trackCmd)\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Also parse elements at script tag level<commit_after><|endoftext|>"}
{"text":"<commit_before>package dht\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/consul\/api\"\n\t\"github.com\/stvp\/rendezvous\"\n)\n\nconst (\n\tcheckInterval = 5 * time.Second\n\tpollWait      = time.Second\n)\n\nfunc newCheckListenerAndServer() (listener net.Listener, server *http.Server, err error) {\n\tlistener, err = net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\treturn listener, nil, err\n\t}\n\n\tserver = &http.Server{\n\t\tReadTimeout:  time.Second,\n\t\tWriteTimeout: time.Second,\n\t\tHandler: http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {\n\t\t\tfmt.Fprintf(resp, \"OK\")\n\t\t}),\n\t}\n\n\t\/\/ When the listener is closed, this goroutine returns.\n\tgo server.Serve(listener)\n\n\treturn listener, server, err\n}\n\n\/\/ Node is a single node in a distributed hash table, coordinated using\n\/\/ services registered in Consul. Key membership is determined using rendezvous\n\/\/ hashing to ensure even distribution of keys and minimal key membership\n\/\/ changes when a Node fails or otherwise leaves the hash table.\n\/\/\n\/\/ Errors encountered when making blocking GET requests to the Consul agent API\n\/\/ are logged using the log package.\ntype Node struct {\n\t\/\/ Consul\n\tserviceName string\n\tserviceID   string\n\tconsul      *api.Client\n\n\t\/\/ HTTP health check server\n\tcheckURL      string\n\tcheckListener net.Listener\n\tcheckServer   *http.Server\n\n\t\/\/ Hash table\n\thashTable *rendezvous.Table\n\twaitIndex uint64\n\n\t\/\/ Graceful shutdown\n\tstop chan bool\n}\n\n\/\/ Join creates a new Node and adds it to the distributed hash table specified\n\/\/ by the given name. The given id should be unique among all Nodes in the hash\n\/\/ table.\nfunc Join(name, id string) (node *Node, err error) {\n\tnode = &Node{\n\t\tserviceName: name,\n\t\tserviceID:   id,\n\t\tstop:        make(chan bool),\n\t}\n\n\tnode.consul, err = api.NewClient(api.DefaultConfig())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"dht: can't create Consul API client: %s\", err)\n\t}\n\n\tnode.checkListener, node.checkServer, err = newCheckListenerAndServer()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"dht: can't start HTTP server: %s\", err)\n\t}\n\n\terr = node.register()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"dht: can't register %s service: %s\", node.serviceName, err)\n\t}\n\n\terr = node.update()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"dht: can't fetch %s services list: %s\", node.serviceName, err)\n\t}\n\n\tgo node.poll()\n\n\treturn node, nil\n}\n\nfunc (n *Node) register() (err error) {\n\terr = n.consul.Agent().ServiceRegister(&api.AgentServiceRegistration{\n\t\tName: n.serviceName,\n\t\tID:   n.serviceID,\n\t\tCheck: &api.AgentServiceCheck{\n\t\t\tHTTP:     fmt.Sprintf(\"http:\/\/%s\", n.checkListener.Addr().String()),\n\t\t\tInterval: checkInterval.String(),\n\t\t},\n\t})\n\treturn err\n}\n\nfunc (n *Node) poll() {\n\tvar err error\n\n\tfor {\n\t\tselect {\n\t\tcase <-n.stop:\n\t\t\treturn\n\t\tcase <-time.After(pollWait):\n\t\t\terr = n.update()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[dht %s %s] error: %s\", n.serviceName, n.serviceID, err)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ update blocks until the service list changes or until the Consul agent's\n\/\/ timeout is reached.\nfunc (n *Node) update() (err error) {\n\topts := &api.QueryOptions{WaitIndex: n.waitIndex}\n\tservices, meta, err := n.consul.Catalog().Service(n.serviceName, \"\", opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tids := make([]string, len(services))\n\tfor i, service := range services {\n\t\tids[i] = service.ServiceID\n\t}\n\n\tn.hashTable = rendezvous.New(ids)\n\tn.waitIndex = meta.LastIndex\n\n\treturn nil\n}\n\n\/\/ Member returns true if the given key belongs to this Node in the distributed\n\/\/ hash table.\nfunc (n *Node) Member(key string) bool {\n\treturn n.hashTable.Get(key) == n.serviceID\n}\n\n\/\/ Leave removes the Node from the distributed hash table by de-registering it\n\/\/ from Consul. Once Leave is called, the Node should be discarded. An error is\n\/\/ returned if the Node is unable to successfully deregister itself from\n\/\/ Consul. In that case, Consul's health check for the Node will fail and\n\/\/ require manual cleanup.\nfunc (n *Node) Leave() (err error) {\n\tclose(n.stop) \/\/ stop polling for state\n\terr = n.consul.Agent().ServiceDeregister(n.serviceID)\n\tn.checkListener.Close() \/\/ stop the health check http server\n\treturn err\n}\n<commit_msg>Add a note about the default client timeout.<commit_after>package dht\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/hashicorp\/consul\/api\"\n\t\"github.com\/stvp\/rendezvous\"\n)\n\nconst (\n\tcheckInterval = 5 * time.Second\n\tpollWait      = time.Second\n)\n\nfunc newCheckListenerAndServer() (listener net.Listener, server *http.Server, err error) {\n\tlistener, err = net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\treturn listener, nil, err\n\t}\n\n\tserver = &http.Server{\n\t\tReadTimeout:  time.Second,\n\t\tWriteTimeout: time.Second,\n\t\tHandler: http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {\n\t\t\tfmt.Fprintf(resp, \"OK\")\n\t\t}),\n\t}\n\n\t\/\/ When the listener is closed, this goroutine returns.\n\tgo server.Serve(listener)\n\n\treturn listener, server, err\n}\n\n\/\/ Node is a single node in a distributed hash table, coordinated using\n\/\/ services registered in Consul. Key membership is determined using rendezvous\n\/\/ hashing to ensure even distribution of keys and minimal key membership\n\/\/ changes when a Node fails or otherwise leaves the hash table.\n\/\/\n\/\/ Errors encountered when making blocking GET requests to the Consul agent API\n\/\/ are logged using the log package.\ntype Node struct {\n\t\/\/ Consul\n\tserviceName string\n\tserviceID   string\n\tconsul      *api.Client\n\n\t\/\/ HTTP health check server\n\tcheckURL      string\n\tcheckListener net.Listener\n\tcheckServer   *http.Server\n\n\t\/\/ Hash table\n\thashTable *rendezvous.Table\n\twaitIndex uint64\n\n\t\/\/ Graceful shutdown\n\tstop chan bool\n}\n\n\/\/ Join creates a new Node and adds it to the distributed hash table specified\n\/\/ by the given name. The given id should be unique among all Nodes in the hash\n\/\/ table.\nfunc Join(name, id string) (node *Node, err error) {\n\tnode = &Node{\n\t\tserviceName: name,\n\t\tserviceID:   id,\n\t\tstop:        make(chan bool),\n\t}\n\n\tnode.consul, err = api.NewClient(api.DefaultConfig())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"dht: can't create Consul API client: %s\", err)\n\t}\n\n\tnode.checkListener, node.checkServer, err = newCheckListenerAndServer()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"dht: can't start HTTP server: %s\", err)\n\t}\n\n\terr = node.register()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"dht: can't register %s service: %s\", node.serviceName, err)\n\t}\n\n\terr = node.update()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"dht: can't fetch %s services list: %s\", node.serviceName, err)\n\t}\n\n\tgo node.poll()\n\n\treturn node, nil\n}\n\nfunc (n *Node) register() (err error) {\n\terr = n.consul.Agent().ServiceRegister(&api.AgentServiceRegistration{\n\t\tName: n.serviceName,\n\t\tID:   n.serviceID,\n\t\tCheck: &api.AgentServiceCheck{\n\t\t\tHTTP:     fmt.Sprintf(\"http:\/\/%s\", n.checkListener.Addr().String()),\n\t\t\tInterval: checkInterval.String(),\n\t\t},\n\t})\n\treturn err\n}\n\nfunc (n *Node) poll() {\n\tvar err error\n\n\tfor {\n\t\tselect {\n\t\tcase <-n.stop:\n\t\t\treturn\n\t\tcase <-time.After(pollWait):\n\t\t\terr = n.update()\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"[dht %s %s] error: %s\", n.serviceName, n.serviceID, err)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ update blocks until the service list changes or until the Consul agent's\n\/\/ timeout is reached (10 minutes by default).\nfunc (n *Node) update() (err error) {\n\topts := &api.QueryOptions{WaitIndex: n.waitIndex}\n\tservices, meta, err := n.consul.Catalog().Service(n.serviceName, \"\", opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tids := make([]string, len(services))\n\tfor i, service := range services {\n\t\tids[i] = service.ServiceID\n\t}\n\n\tn.hashTable = rendezvous.New(ids)\n\tn.waitIndex = meta.LastIndex\n\n\treturn nil\n}\n\n\/\/ Member returns true if the given key belongs to this Node in the distributed\n\/\/ hash table.\nfunc (n *Node) Member(key string) bool {\n\treturn n.hashTable.Get(key) == n.serviceID\n}\n\n\/\/ Leave removes the Node from the distributed hash table by de-registering it\n\/\/ from Consul. Once Leave is called, the Node should be discarded. An error is\n\/\/ returned if the Node is unable to successfully deregister itself from\n\/\/ Consul. In that case, Consul's health check for the Node will fail and\n\/\/ require manual cleanup.\nfunc (n *Node) Leave() (err error) {\n\tclose(n.stop) \/\/ stop polling for state\n\terr = n.consul.Agent().ServiceDeregister(n.serviceID)\n\tn.checkListener.Close() \/\/ stop the health check http server\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package libxml2\n\n\/*\n#cgo pkg-config: libxml-2.0\n#include <stdbool.h>\n#include \"libxml\/tree.h\"\n#include \"libxml\/parser.h\"\n#include \"libxml\/xpath.h\"\n\nstatic inline bool MY_xmlXPathNodeSetIsEmpty(xmlNodeSetPtr ptr) {\n\treturn ptr == NULL ||\n\t\tptr->nodeNr == 0 ||\n\t\tptr->nodeTab == NULL;\n}\n\nstatic inline xmlNodePtr MY_xmlNodeSetTabAt(xmlNodePtr *nodes, int i) {\n\treturn nodes[i];\n}\n\nstatic inline int MY_setXmlIndentTreeOutput(int i) {\n\tint old = xmlIndentTreeOutput;\n\txmlIndentTreeOutput = i;\n\treturn old;\n}\n*\/\nimport \"C\"\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"unsafe\"\n)\n\ntype XmlNodeType int\n\nconst (\n\tElementNode XmlNodeType = iota + 1\n\tAttributeNode\n\tTextNode\n\tCDataSectionNode\n\tEntityRefNode\n\tEntityNode\n\tPiNode\n\tCommentNode\n\tDocumentNode\n\tDocumentTypeNode\n\tDocumentFragNode\n\tNotationNode\n\tHTMLDocumentNode\n\tDTDNode\n\tElementDecl\n\tAttributeDecl\n\tEntityDecl\n\tNamespaceDecl\n\tXIncludeStart\n\tXIncludeEnd\n\tDocbDocumentNode\n)\n\nvar _XmlNodeType_index = [...]uint8{0, 11, 24, 32, 48, 61, 71, 77, 88, 100, 116, 132, 144, 160, 167, 178, 191, 201, 214, 227, 238, 254}\n\nconst _XmlNodeType_name = `ElementNodeAttributeNodeTextNodeCDataSectionNodeEntityRefNodeEntityNodePiNodeCommentNodeDocumentNodeDocumentTypeNodeDocumentFragNodeNotationNodeHTMLDocumentNodeDTDNodeElementDeclAttributeDeclEntityDeclNamespaceDeclXIncludeStartXIncludeEndDocbDocumentNode`\n\nfunc (i XmlNodeType) String() string {\n\ti -= 1\n\tif i < 0 || i+1 >= XmlNodeType(len(_XmlNodeType_index)) {\n\t\treturn fmt.Sprintf(\"XmlNodeType(%d)\", i+1)\n\t}\n\treturn _XmlNodeType_name[_XmlNodeType_index[i]:_XmlNodeType_index[i+1]]\n}\n\nvar ErrNodeNotFound = errors.New(\"node not found\")\nvar ErrInvalidArgument = errors.New(\"invalid argument\")\n\n\/\/ Node defines the basic DOM interface\ntype Node interface {\n\t\/\/ pointer() returns the underlying C pointer. Only we are allowed to\n\t\/\/ slice it, dice it, do whatever the heck with it.\n\tpointer() unsafe.Pointer\n\n\tChildNodes() []Node\n\tOwnerDocument() *XmlDoc\n\tFindNodes(string) ([]Node, error)\n\tIsSameNode(Node) bool\n\tLastChild() Node\n\tNodeName() string\n\tNextSibling() Node\n\tParetNode() Node\n\tPreviousSibling() Node\n\tSetNodeName(string)\n\tString() string\n\tTextContent() string\n\tToString(int, bool) string\n\tType() XmlNodeType\n\tWalk(func(Node) error)\n}\n\ntype xmlNode struct {\n\tptr *C.xmlNode\n}\n\ntype XmlNode struct {\n\t*xmlNode\n}\n\ntype XmlElement struct {\n\t*XmlNode\n}\n\ntype XmlDoc struct {\n\tptr  *C.xmlDoc\n\troot *C.xmlNode\n}\n\ntype XmlText struct {\n\t*XmlNode\n}\n\nfunc wrapXmlElement(n *C.xmlElement) *XmlElement {\n\treturn &XmlElement{wrapXmlNode((*C.xmlNode)(unsafe.Pointer(n)))}\n}\n\nfunc wrapXmlNode(n *C.xmlNode) *XmlNode {\n\treturn &XmlNode{\n\t\t&xmlNode{\n\t\t\tptr: (*C.xmlNode)(unsafe.Pointer(n)),\n\t\t},\n\t}\n}\n\nfunc wrapToNode(n *C.xmlNode) Node {\n\tswitch XmlNodeType(n._type) {\n\tcase ElementNode:\n\t\treturn wrapXmlElement((*C.xmlElement)(unsafe.Pointer(n)))\n\tcase TextNode:\n\t\treturn &XmlText{&XmlNode{&xmlNode{ptr: n}}}\n\tdefault:\n\t\treturn &XmlNode{&xmlNode{ptr: n}}\n\t}\n}\n\nfunc findNodes(n Node, xpath string) ([]Node, error) {\n\tctx := C.xmlXPathNewContext((*C.xmlNode)(n.pointer()).doc)\n\tdefer C.xmlXPathFreeContext(ctx)\n\n\tres := C.xmlXPathEvalExpression(stringToXmlChar(xpath), ctx)\n\tdefer C.xmlXPathFreeObject(res)\n\tif C.MY_xmlXPathNodeSetIsEmpty(res.nodesetval) {\n\t\treturn []Node(nil), nil\n\t}\n\n\tret := make([]Node, res.nodesetval.nodeNr)\n\tfor i := 0; i < int(res.nodesetval.nodeNr); i++ {\n\t\tret[i] = wrapToNode(C.MY_xmlNodeSetTabAt(res.nodesetval.nodeTab, C.int(i)))\n\t}\n\treturn ret, nil\n}\n\nfunc (n *xmlNode) pointer() unsafe.Pointer {\n\treturn unsafe.Pointer(n.ptr)\n}\n\nfunc (n *xmlNode) ChildNodes() []Node {\n\treturn childNodes(n)\n}\n\nfunc wrapXmlDoc(n *C.xmlDoc) *XmlDoc {\n\tr := C.xmlDocGetRootElement(n) \/\/ XXX Should check for n == nil\n\treturn &XmlDoc{ptr: n, root: r}\n}\n\nfunc (n *xmlNode) OwnerDocument() *XmlDoc {\n\treturn wrapXmlDoc(n.ptr.doc)\n}\n\nfunc (n *xmlNode) FindNodes(xpath string) ([]Node, error) {\n\treturn findNodes(n, xpath)\n}\n\nfunc (n *xmlNode) IsSameNode(other Node) bool {\n\treturn n.pointer() == other.pointer()\n}\n\nfunc (n *xmlNode) LastChild() Node {\n\treturn wrapToNode(n.ptr.last)\n}\n\nfunc (n *xmlNode) NodeName() string {\n\treturn xmlCharToString(n.ptr.name)\n}\n\nfunc (n *xmlNode) NextSibling() Node {\n\treturn wrapToNode(n.ptr.next)\n}\n\nfunc (n *xmlNode) ParetNode() Node {\n\treturn wrapToNode(n.ptr.parent)\n}\n\nfunc (n *xmlNode) PreviousSibling() Node {\n\treturn wrapToNode(n.ptr.prev)\n}\n\nfunc (n *xmlNode) SetNodeName(name string) {\n\tC.xmlNodeSetName(n.ptr, stringToXmlChar(name))\n}\n\nfunc (n *xmlNode) String() string {\n\treturn n.ToString(0, false)\n}\n\nfunc (n *xmlNode) TextContent() string {\n\treturn xmlCharToString(C.xmlXPathCastNodeToString(n.ptr))\n}\n\nfunc (n *xmlNode) ToString(format int, docencoding bool) string {\n\tbuffer := C.xmlBufferCreate()\n\tdefer C.xmlBufferFree(buffer)\n\tif format <= 0 {\n\t\tC.xmlNodeDump(buffer, n.ptr.doc, n.ptr, 0, 0)\n\t} else {\n\t\toIndentTreeOutput := C.MY_setXmlIndentTreeOutput(1)\n\t\tC.xmlNodeDump(buffer, n.ptr.doc, n.ptr, 0, C.int(format))\n\t\tC.MY_setXmlIndentTreeOutput(oIndentTreeOutput)\n\t}\n\treturn xmlCharToString(C.xmlBufferContent(buffer))\n}\n\nfunc (n *xmlNode) Type() XmlNodeType {\n\treturn XmlNodeType(n.ptr._type)\n}\n\nfunc (n *xmlNode) Walk(fn func(Node) error) {\n\tpanic(\"should not call walk on internal struct\")\n}\n\nfunc (n *XmlNode) Walk(fn func(Node) error) {\n\twalk(n, fn)\n}\n\nfunc walk(n Node, fn func(Node) error) {\n\tif err := fn(n); err != nil {\n\t\treturn\n\t}\n\tfor _, c := range n.ChildNodes() {\n\t\twalk(c, fn)\n\t}\n}\n\nfunc childNodes(n Node) []Node {\n\tret := []Node(nil)\n\tfor chld := ((*C.xmlNode)(n.pointer())).children; chld != nil; chld = chld.next {\n\t\tret = append(ret, wrapToNode(chld))\n\t}\n\treturn ret\n}\n\nfunc (d *XmlDoc) pointer() unsafe.Pointer {\n\treturn unsafe.Pointer(d.ptr)\n}\n\nfunc (d *XmlDoc) DocumentElement() Node {\n\tif d.ptr == nil || d.root == nil {\n\t\treturn nil\n\t}\n\n\treturn wrapToNode(d.root)\n}\n\nfunc (d *XmlDoc) FindNodes(xpath string) ([]Node, error) {\n\troot := d.DocumentElement()\n\tif root == nil {\n\t\treturn nil, ErrNodeNotFound\n\t}\n\treturn root.FindNodes(xpath)\n}\n\nfunc (d *XmlDoc) Encoding() string {\n\treturn xmlCharToString(d.ptr.encoding)\n}\n\nfunc (d *XmlDoc) Free() {\n\tC.xmlFreeDoc(d.ptr)\n\td.ptr = nil\n\td.root = nil\n}\n\nfunc (d *XmlDoc) String() string {\n\tvar xc *C.xmlChar\n\ti := C.int(0)\n\tC.xmlDocDumpMemory(d.ptr, &xc, &i)\n\treturn xmlCharToString(xc)\n}\n\nfunc (d *XmlDoc) Type() XmlNodeType {\n\treturn XmlNodeType(d.ptr._type)\n}\n\nfunc (n *XmlDoc) Walk(fn func(Node) error) {\n\twalk(wrapXmlNode(n.root), fn)\n}\n\nfunc (n *XmlText) Data() string {\n\treturn xmlCharToString(n.ptr.content)\n}\n\nfunc (n *XmlText) Walk(fn func(Node) error) {\n\twalk(n, fn)\n}\n<commit_msg>Change Type to NodeType<commit_after>package libxml2\n\n\/*\n#cgo pkg-config: libxml-2.0\n#include <stdbool.h>\n#include \"libxml\/tree.h\"\n#include \"libxml\/parser.h\"\n#include \"libxml\/xpath.h\"\n\nstatic inline bool MY_xmlXPathNodeSetIsEmpty(xmlNodeSetPtr ptr) {\n\treturn ptr == NULL ||\n\t\tptr->nodeNr == 0 ||\n\t\tptr->nodeTab == NULL;\n}\n\nstatic inline xmlNodePtr MY_xmlNodeSetTabAt(xmlNodePtr *nodes, int i) {\n\treturn nodes[i];\n}\n\nstatic inline int MY_setXmlIndentTreeOutput(int i) {\n\tint old = xmlIndentTreeOutput;\n\txmlIndentTreeOutput = i;\n\treturn old;\n}\n*\/\nimport \"C\"\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"unsafe\"\n)\n\ntype XmlNodeType int\n\nconst (\n\tElementNode XmlNodeType = iota + 1\n\tAttributeNode\n\tTextNode\n\tCDataSectionNode\n\tEntityRefNode\n\tEntityNode\n\tPiNode\n\tCommentNode\n\tDocumentNode\n\tDocumentTypeNode\n\tDocumentFragNode\n\tNotationNode\n\tHTMLDocumentNode\n\tDTDNode\n\tElementDecl\n\tAttributeDecl\n\tEntityDecl\n\tNamespaceDecl\n\tXIncludeStart\n\tXIncludeEnd\n\tDocbDocumentNode\n)\n\nvar _XmlNodeType_index = [...]uint8{0, 11, 24, 32, 48, 61, 71, 77, 88, 100, 116, 132, 144, 160, 167, 178, 191, 201, 214, 227, 238, 254}\n\nconst _XmlNodeType_name = `ElementNodeAttributeNodeTextNodeCDataSectionNodeEntityRefNodeEntityNodePiNodeCommentNodeDocumentNodeDocumentTypeNodeDocumentFragNodeNotationNodeHTMLDocumentNodeDTDNodeElementDeclAttributeDeclEntityDeclNamespaceDeclXIncludeStartXIncludeEndDocbDocumentNode`\n\nfunc (i XmlNodeType) String() string {\n\ti -= 1\n\tif i < 0 || i+1 >= XmlNodeType(len(_XmlNodeType_index)) {\n\t\treturn fmt.Sprintf(\"XmlNodeType(%d)\", i+1)\n\t}\n\treturn _XmlNodeType_name[_XmlNodeType_index[i]:_XmlNodeType_index[i+1]]\n}\n\nvar ErrNodeNotFound = errors.New(\"node not found\")\nvar ErrInvalidArgument = errors.New(\"invalid argument\")\n\n\/\/ Node defines the basic DOM interface\ntype Node interface {\n\t\/\/ pointer() returns the underlying C pointer. Only we are allowed to\n\t\/\/ slice it, dice it, do whatever the heck with it.\n\tpointer() unsafe.Pointer\n\n\tChildNodes() []Node\n\tOwnerDocument() *XmlDoc\n\tFindNodes(string) ([]Node, error)\n\tIsSameNode(Node) bool\n\tLastChild() Node\n\tNextSibling() Node\n\tNodeName() string\n\tNodeType() XmlNodeType\n\tParetNode() Node\n\tPreviousSibling() Node\n\tSetNodeName(string)\n\tString() string\n\tTextContent() string\n\tToString(int, bool) string\n\tWalk(func(Node) error)\n}\n\ntype xmlNode struct {\n\tptr *C.xmlNode\n}\n\ntype XmlNode struct {\n\t*xmlNode\n}\n\ntype XmlElement struct {\n\t*XmlNode\n}\n\ntype XmlDoc struct {\n\tptr  *C.xmlDoc\n\troot *C.xmlNode\n}\n\ntype XmlText struct {\n\t*XmlNode\n}\n\nfunc wrapXmlElement(n *C.xmlElement) *XmlElement {\n\treturn &XmlElement{wrapXmlNode((*C.xmlNode)(unsafe.Pointer(n)))}\n}\n\nfunc wrapXmlNode(n *C.xmlNode) *XmlNode {\n\treturn &XmlNode{\n\t\t&xmlNode{\n\t\t\tptr: (*C.xmlNode)(unsafe.Pointer(n)),\n\t\t},\n\t}\n}\n\nfunc wrapToNode(n *C.xmlNode) Node {\n\tswitch XmlNodeType(n._type) {\n\tcase ElementNode:\n\t\treturn wrapXmlElement((*C.xmlElement)(unsafe.Pointer(n)))\n\tcase TextNode:\n\t\treturn &XmlText{&XmlNode{&xmlNode{ptr: n}}}\n\tdefault:\n\t\treturn &XmlNode{&xmlNode{ptr: n}}\n\t}\n}\n\nfunc findNodes(n Node, xpath string) ([]Node, error) {\n\tctx := C.xmlXPathNewContext((*C.xmlNode)(n.pointer()).doc)\n\tdefer C.xmlXPathFreeContext(ctx)\n\n\tres := C.xmlXPathEvalExpression(stringToXmlChar(xpath), ctx)\n\tdefer C.xmlXPathFreeObject(res)\n\tif C.MY_xmlXPathNodeSetIsEmpty(res.nodesetval) {\n\t\treturn []Node(nil), nil\n\t}\n\n\tret := make([]Node, res.nodesetval.nodeNr)\n\tfor i := 0; i < int(res.nodesetval.nodeNr); i++ {\n\t\tret[i] = wrapToNode(C.MY_xmlNodeSetTabAt(res.nodesetval.nodeTab, C.int(i)))\n\t}\n\treturn ret, nil\n}\n\nfunc (n *xmlNode) pointer() unsafe.Pointer {\n\treturn unsafe.Pointer(n.ptr)\n}\n\nfunc (n *xmlNode) ChildNodes() []Node {\n\treturn childNodes(n)\n}\n\nfunc wrapXmlDoc(n *C.xmlDoc) *XmlDoc {\n\tr := C.xmlDocGetRootElement(n) \/\/ XXX Should check for n == nil\n\treturn &XmlDoc{ptr: n, root: r}\n}\n\nfunc (n *xmlNode) OwnerDocument() *XmlDoc {\n\treturn wrapXmlDoc(n.ptr.doc)\n}\n\nfunc (n *xmlNode) FindNodes(xpath string) ([]Node, error) {\n\treturn findNodes(n, xpath)\n}\n\nfunc (n *xmlNode) IsSameNode(other Node) bool {\n\treturn n.pointer() == other.pointer()\n}\n\nfunc (n *xmlNode) LastChild() Node {\n\treturn wrapToNode(n.ptr.last)\n}\n\nfunc (n *xmlNode) NodeName() string {\n\treturn xmlCharToString(n.ptr.name)\n}\n\nfunc (n *xmlNode) NextSibling() Node {\n\treturn wrapToNode(n.ptr.next)\n}\n\nfunc (n *xmlNode) ParetNode() Node {\n\treturn wrapToNode(n.ptr.parent)\n}\n\nfunc (n *xmlNode) PreviousSibling() Node {\n\treturn wrapToNode(n.ptr.prev)\n}\n\nfunc (n *xmlNode) SetNodeName(name string) {\n\tC.xmlNodeSetName(n.ptr, stringToXmlChar(name))\n}\n\nfunc (n *xmlNode) String() string {\n\treturn n.ToString(0, false)\n}\n\nfunc (n *xmlNode) TextContent() string {\n\treturn xmlCharToString(C.xmlXPathCastNodeToString(n.ptr))\n}\n\nfunc (n *xmlNode) ToString(format int, docencoding bool) string {\n\tbuffer := C.xmlBufferCreate()\n\tdefer C.xmlBufferFree(buffer)\n\tif format <= 0 {\n\t\tC.xmlNodeDump(buffer, n.ptr.doc, n.ptr, 0, 0)\n\t} else {\n\t\toIndentTreeOutput := C.MY_setXmlIndentTreeOutput(1)\n\t\tC.xmlNodeDump(buffer, n.ptr.doc, n.ptr, 0, C.int(format))\n\t\tC.MY_setXmlIndentTreeOutput(oIndentTreeOutput)\n\t}\n\treturn xmlCharToString(C.xmlBufferContent(buffer))\n}\n\nfunc (n *xmlNode) NodeType() XmlNodeType {\n\treturn XmlNodeType(n.ptr._type)\n}\n\nfunc (n *xmlNode) Walk(fn func(Node) error) {\n\tpanic(\"should not call walk on internal struct\")\n}\n\nfunc (n *XmlNode) Walk(fn func(Node) error) {\n\twalk(n, fn)\n}\n\nfunc walk(n Node, fn func(Node) error) {\n\tif err := fn(n); err != nil {\n\t\treturn\n\t}\n\tfor _, c := range n.ChildNodes() {\n\t\twalk(c, fn)\n\t}\n}\n\nfunc childNodes(n Node) []Node {\n\tret := []Node(nil)\n\tfor chld := ((*C.xmlNode)(n.pointer())).children; chld != nil; chld = chld.next {\n\t\tret = append(ret, wrapToNode(chld))\n\t}\n\treturn ret\n}\n\nfunc (d *XmlDoc) pointer() unsafe.Pointer {\n\treturn unsafe.Pointer(d.ptr)\n}\n\nfunc (d *XmlDoc) DocumentElement() Node {\n\tif d.ptr == nil || d.root == nil {\n\t\treturn nil\n\t}\n\n\treturn wrapToNode(d.root)\n}\n\nfunc (d *XmlDoc) FindNodes(xpath string) ([]Node, error) {\n\troot := d.DocumentElement()\n\tif root == nil {\n\t\treturn nil, ErrNodeNotFound\n\t}\n\treturn root.FindNodes(xpath)\n}\n\nfunc (d *XmlDoc) Encoding() string {\n\treturn xmlCharToString(d.ptr.encoding)\n}\n\nfunc (d *XmlDoc) Free() {\n\tC.xmlFreeDoc(d.ptr)\n\td.ptr = nil\n\td.root = nil\n}\n\nfunc (d *XmlDoc) String() string {\n\tvar xc *C.xmlChar\n\ti := C.int(0)\n\tC.xmlDocDumpMemory(d.ptr, &xc, &i)\n\treturn xmlCharToString(xc)\n}\n\nfunc (d *XmlDoc) NodeType() XmlNodeType {\n\treturn XmlNodeType(d.ptr._type)\n}\n\nfunc (n *XmlDoc) Walk(fn func(Node) error) {\n\twalk(wrapXmlNode(n.root), fn)\n}\n\nfunc (n *XmlText) Data() string {\n\treturn xmlCharToString(n.ptr.content)\n}\n\nfunc (n *XmlText) Walk(fn func(Node) error) {\n\twalk(n, fn)\n}\n<|endoftext|>"}
{"text":"<commit_before>package flowgraph\n\nimport (\n\t\"github.com\/vectaport\/fgbase\"\n)\n\n\/\/ Node interface for flowgraph nodes that are connected by flowgraph edges\ntype Node interface {\n\t\/\/ Tracef for debug trace printing.  Use atomic log mechanism.\n\tTracef(format string, v ...interface{})\n\n\t\/\/ LogError for logging of error messages.  Use atomic log mechanism.\n\tLogError(format string, v ...interface{})\n\n\t\/\/ Name returns the node name\n\tName() string\n\n\t\/\/ Source returns upstream edge by index\n\tSource(n int) Edge\n\n\t\/\/ Destination returns downstream edge by index\n\tDestination(n int) Edge\n\n\t\/\/ FindSource returns upstream edge by name\n\tFindSource(name string) Edge\n\n\t\/\/ FindDestination returns downstream edge by name\n\tFindDestination(name string) Edge\n\n\t\/\/ AddSource adds a list of source edges\n\tAddSource(e ...Edge)\n\n\t\/\/ AddDestination adds a list of destination edges\n\tAddDestination(e ...Edge)\n\n\t\/\/ NumSource returns the number of upstream edges\n\tNumSource() int\n\n\t\/\/ NumDestination returns the number of downstream edges\n\tNumDestination() int\n\n\t\/\/ SetSourceNames names the sources\n\tSetSourceNames(nm ...string)\n\n\t\/\/ SetDestinationNames names the destinations\n\tSetDestinationNames(nm ...string)\n\n\t\/\/ SourceNames returns the names of the sources\n\tSourceNames() []string\n\n\t\/\/ DestinationNames returns the names of the destinations\n\tDestinationNames() []string\n\n\t\/\/ Auxiliary returns auxiliary storage used by\n\t\/\/ underlying implementation for storing state\n\tAuxiliary() interface{}\n\n\t\/\/ Base returns the value that implements this node\n\t\/\/ The type of this value identifies the implementation.\n\tBase() interface{}\n}\n\n\/\/ implementation of Node\ntype node struct {\n\tbase *fgbase.Node\n}\n\n\/\/ Tracef for debug trace printing.  Uses atomic log mechanism.\nfunc (n node) Tracef(format string, v ...interface{}) {\n\tn.base.Tracef(format, v)\n}\n\n\/\/ LogError for logging of error messages.  Uses atomic log mechanism.\nfunc (n node) LogError(format string, v ...interface{}) {\n\tn.base.LogError(format, v)\n}\n\n\/\/ Name returns the node name\nfunc (n node) Name() string {\n\treturn n.base.Name\n}\n\n\/\/ Source returns upstream edge by index\nfunc (n node) Source(i int) Edge {\n\treturn edge{n.base.Srcs[i]}\n}\n\n\/\/ Destination returns downstream edge by index\nfunc (n node) Destination(i int) Edge {\n\treturn edge{n.base.Dsts[i]}\n}\n\n\/\/ FindSource returns upstream edge by name\nfunc (n node) FindSource(name string) Edge {\n\treturn edge{n.base.FindSrc(name)}\n}\n\n\/\/ FindDestination returns downstream edge by name\nfunc (n node) FindDestination(name string) Edge {\n\treturn edge{n.base.FindDst(name)}\n}\n\n\/\/ AddSource adds a list of source edges\nfunc (n node) AddSource(e ...Edge) {\n\tfor _, ev := range e {\n\t\tn.base.Srcs = append(n.base.Srcs, ev.Base().(*fgbase.Edge))\n\t}\n}\n\n\/\/ AddDestination adds a list of destination edges\nfunc (n node) AddDestination(e ...Edge) {\n\tfor _, ev := range e {\n\t\tn.base.Dsts = append(n.base.Dsts, ev.Base().(*fgbase.Edge))\n\t}\n}\n\n\/\/ NumSource returns the number of upstream edges\nfunc (n node) NumSource() int {\n\treturn len(n.base.Srcs)\n}\n\n\/\/ NumDestination returns the number of downstream edges\nfunc (n node) NumDestination() int {\n\treturn len(n.base.Dsts)\n}\n\n\/\/ SetSourceNames names the sources\nfunc (n node) SetSourceNames(nm ...string) {\n\tfor _, v := range nm {\n\t\tn.base.SrcNames = append(n.base.SrcNames, v)\n\t}\n}\n\n\/\/ SetDestinationNames names the destinations\nfunc (n node) SetDestinationNames(nm ...string) {\n\tfor _, v := range nm {\n\t\tn.base.DstNames = append(n.base.DstNames, v)\n\t}\n}\n\n\/\/ SourceNames returns the names of the sources\nfunc (n node) SourceNames() []string {\n\treturn n.base.SrcNames\n}\n\n\/\/ DestinationNames returns the names of the destinatiopns\nfunc (n node) DestinationNames() []string {\n\treturn n.base.DstNames\n}\n\n\/\/ Auxiliary returns auxiliary storage for this node used by\n\/\/ the underlying implementation for storing state\nfunc (n node) Auxiliary() interface{} {\n\treturn n.base.Aux\n}\n\n\/\/ Base returns the value that implements this edge\n\/\/ The type of this value identifies the implementation.\nfunc (n node) Base() interface{} {\n\treturn n.base\n}\n<commit_msg>working on naming sources and destinations of a node<commit_after>package flowgraph\n\nimport (\n\t\"github.com\/vectaport\/fgbase\"\n)\n\n\/\/ Node interface for flowgraph nodes that are connected by flowgraph edges\ntype Node interface {\n\t\/\/ Tracef for debug trace printing.  Use atomic log mechanism.\n\tTracef(format string, v ...interface{})\n\n\t\/\/ LogError for logging of error messages.  Use atomic log mechanism.\n\tLogError(format string, v ...interface{})\n\n\t\/\/ Name returns the node name\n\tName() string\n\n\t\/\/ Source returns upstream edge by index\n\tSource(n int) Edge\n\n\t\/\/ Destination returns downstream edge by index\n\tDestination(n int) Edge\n\n\t\/\/ FindSource returns upstream edge by name\n\tFindSource(name string) Edge\n\n\t\/\/ FindDestination returns downstream edge by name\n\tFindDestination(name string) Edge\n\n\t\/\/ AddSource adds a list of source edges\n\tAddSource(e ...Edge)\n\n\t\/\/ AddDestination adds a list of destination edges\n\tAddDestination(e ...Edge)\n\n\t\/\/ NumSource returns the number of upstream edges\n\tNumSource() int\n\n\t\/\/ NumDestination returns the number of downstream edges\n\tNumDestination() int\n\n\t\/\/ SetSourceNames names the sources\n\tSetSourceNames(nm ...string)\n\n\t\/\/ SetDestinationNames names the destinations\n\tSetDestinationNames(nm ...string)\n\n\t\/\/ SourceNames returns the names of the sources\n\tSourceNames() []string\n\n\t\/\/ DestinationNames returns the names of the destinations\n\tDestinationNames() []string\n\n\t\/\/ Auxiliary returns auxiliary storage used by\n\t\/\/ underlying implementation for storing state\n\tAuxiliary() interface{}\n\n\t\/\/ Base returns the value that implements this node\n\t\/\/ The type of this value identifies the implementation.\n\tBase() interface{}\n}\n\n\/\/ implementation of Node\ntype node struct {\n\tbase *fgbase.Node\n}\n\n\/\/ Tracef for debug trace printing.  Uses atomic log mechanism.\nfunc (n node) Tracef(format string, v ...interface{}) {\n\tn.base.Tracef(format, v)\n}\n\n\/\/ LogError for logging of error messages.  Uses atomic log mechanism.\nfunc (n node) LogError(format string, v ...interface{}) {\n\tn.base.LogError(format, v)\n}\n\n\/\/ Name returns the node name\nfunc (n node) Name() string {\n\treturn n.base.Name\n}\n\n\/\/ Source returns upstream edge by index\nfunc (n node) Source(i int) Edge {\n\treturn edge{n.base.Srcs[i]}\n}\n\n\/\/ Destination returns downstream edge by index\nfunc (n node) Destination(i int) Edge {\n\treturn edge{n.base.Dsts[i]}\n}\n\n\/\/ FindSource returns upstream edge by name\nfunc (n node) FindSource(name string) Edge {\n\treturn edge{n.base.FindSrc(name)}\n}\n\n\/\/ FindDestination returns downstream edge by name\nfunc (n node) FindDestination(name string) Edge {\n\treturn edge{n.base.FindDst(name)}\n}\n\n\/\/ AddSource adds a list of source edges\nfunc (n node) AddSource(e ...Edge) {\n\tfor _, ev := range e {\n\t\tn.base.Srcs = append(n.base.Srcs, ev.Base().(*fgbase.Edge))\n\t}\n}\n\n\/\/ AddDestination adds a list of destination edges\nfunc (n node) AddDestination(e ...Edge) {\n\tfor _, ev := range e {\n\t\tn.base.Dsts = append(n.base.Dsts, ev.Base().(*fgbase.Edge))\n\t}\n}\n\n\/\/ NumSource returns the number of upstream edges\nfunc (n node) NumSource() int {\n\treturn len(n.base.Srcs)\n}\n\n\/\/ NumDestination returns the number of downstream edges\nfunc (n node) NumDestination() int {\n\treturn len(n.base.Dsts)\n}\n\n\/\/ SetSourceNames names the sources\nfunc (n node) SetSourceNames(nm ...string) {\n\tn.base.SetSrcNames(nm...)\n}\n\n\/\/ SetDestinationNames names the destination\nfunc (n node) SetDestinationNames(nm ...string) {\n\tn.base.SetDstNames(nm...)\n}\n\n\/\/ SourceNames returns the names of the sources\nfunc (n node) SourceNames() []string {\n\treturn n.base.SrcNames()\n}\n\n\/\/ DestinationNames returns the names of the destinatiopns\nfunc (n node) DestinationNames() []string {\n\treturn n.base.DstNames()\n}\n\n\/\/ Auxiliary returns auxiliary storage for this node used by\n\/\/ the underlying implementation for storing state\nfunc (n node) Auxiliary() interface{} {\n\treturn n.base.Aux\n}\n\n\/\/ Base returns the value that implements this edge\n\/\/ The type of this value identifies the implementation.\nfunc (n node) Base() interface{} {\n\treturn n.base\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2013 Kelsey Hightower. All rights reserved.\n\/\/ Use of this source code is governed by the Apache License, Version 2.0\n\/\/ that can be found in the LICENSE file.\npackage etcd\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\tgoetcd \"github.com\/coreos\/go-etcd\/etcd\"\n)\n\n\/\/ Client is a wrapper around the etcd client\ntype Client struct {\n\tclient *goetcd.Client\n}\n\n\/\/ NewEtcdClient returns an *etcd.Client with a connection to named machines.\n\/\/ It returns an error if a connection to the cluster cannot be made.\nfunc NewEtcdClient(machines []string, cert, key string, caCert string) (*Client, error) {\n\tvar c *goetcd.Client\n\tif cert != \"\" && key != \"\" {\n\t\tc, err := goetcd.NewTLSClient(machines, cert, key, caCert)\n\t\tif err != nil {\n\t\t\treturn &Client{c}, err\n\t\t}\n\t} else {\n\t\tc = goetcd.NewClient(machines)\n\t}\n\tsuccess := c.SetCluster(machines)\n\tif !success {\n\t\treturn &Client{c}, errors.New(\"cannot connect to etcd cluster: \" + strings.Join(machines, \",\"))\n\t}\n\treturn &Client{c}, nil\n}\n\n\/\/ GetValues queries etcd for keys prefixed by prefix.\n\/\/ Etcd paths (keys) are translated into names more suitable for use in\n\/\/ templates. For example if prefix were set to '\/production' and one of the\n\/\/ keys were '\/nginx\/port'; the prefixed '\/production\/nginx\/port' key would\n\/\/ be queried for. If the value for the prefixed key where 80, the returned map\n\/\/ would contain the entry vars[\"nginx_port\"] = \"80\".\nfunc (c *Client) GetValues(keys []string) (map[string]string, error) {\n\tvars := make(map[string]string)\n\tfor _, key := range keys {\n\t\tresp, err := c.client.Get(key, false, true)\n\t\tif err != nil {\n\t\t\treturn vars, err\n\t\t}\n\t\terr = nodeWalk(resp.Node, vars)\n\t\tif err != nil {\n\t\t\treturn vars, err\n\t\t}\n\t}\n\treturn vars, nil\n}\n\n\/\/ nodeWalk recursively descends nodes, updating vars.\nfunc nodeWalk(node *goetcd.Node, vars map[string]string) error {\n\tif node != nil {\n\t\tkey := node.Key\n\t\tif !node.Dir {\n\t\t\tvars[key] = node.Value\n\t\t} else {\n\t\t\tfor _, node := range node.Nodes {\n\t\t\t\tnodeWalk(node, vars)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>update comment<commit_after>\/\/ Copyright (c) 2013 Kelsey Hightower. All rights reserved.\n\/\/ Use of this source code is governed by the Apache License, Version 2.0\n\/\/ that can be found in the LICENSE file.\npackage etcd\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\tgoetcd \"github.com\/coreos\/go-etcd\/etcd\"\n)\n\n\/\/ Client is a wrapper around the etcd client\ntype Client struct {\n\tclient *goetcd.Client\n}\n\n\/\/ NewEtcdClient returns an *etcd.Client with a connection to named machines.\n\/\/ It returns an error if a connection to the cluster cannot be made.\nfunc NewEtcdClient(machines []string, cert, key string, caCert string) (*Client, error) {\n\tvar c *goetcd.Client\n\tif cert != \"\" && key != \"\" {\n\t\tc, err := goetcd.NewTLSClient(machines, cert, key, caCert)\n\t\tif err != nil {\n\t\t\treturn &Client{c}, err\n\t\t}\n\t} else {\n\t\tc = goetcd.NewClient(machines)\n\t}\n\tsuccess := c.SetCluster(machines)\n\tif !success {\n\t\treturn &Client{c}, errors.New(\"cannot connect to etcd cluster: \" + strings.Join(machines, \",\"))\n\t}\n\treturn &Client{c}, nil\n}\n\n\/\/ GetValues queries etcd for keys prefixed by prefix.\nfunc (c *Client) GetValues(keys []string) (map[string]string, error) {\n\tvars := make(map[string]string)\n\tfor _, key := range keys {\n\t\tresp, err := c.client.Get(key, false, true)\n\t\tif err != nil {\n\t\t\treturn vars, err\n\t\t}\n\t\terr = nodeWalk(resp.Node, vars)\n\t\tif err != nil {\n\t\t\treturn vars, err\n\t\t}\n\t}\n\treturn vars, nil\n}\n\n\/\/ nodeWalk recursively descends nodes, updating vars.\nfunc nodeWalk(node *goetcd.Node, vars map[string]string) error {\n\tif node != nil {\n\t\tkey := node.Key\n\t\tif !node.Dir {\n\t\t\tvars[key] = node.Value\n\t\t} else {\n\t\t\tfor _, node := range node.Nodes {\n\t\t\t\tnodeWalk(node, vars)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2021 Timo Savola. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build gateexecdir\n\npackage container\n\nimport (\n\t\"os\"\n\t\"path\"\n)\n\nfunc init() {\n\tif ExecDir != \"\" {\n\t\tif filename, err := os.Executable(); err == nil {\n\t\t\tExecDir = path.Dir(filename)\n\t\t}\n\t}\n}\n<commit_msg>runtime\/container: fix ExecDir configuration via linker<commit_after>\/\/ Copyright (c) 2021 Timo Savola. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build gateexecdir\n\npackage container\n\nimport (\n\t\"os\"\n\t\"path\"\n)\n\nfunc init() {\n\tif ExecDir == \"\" {\n\t\tif filename, err := os.Executable(); err == nil {\n\t\t\tExecDir = path.Dir(filename)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nPackage hamt32 implements a functional Hash Array Mapped Trie (HAMT).\nIt is called hamt32 because this package is using 32 nodes for each level of\nthe Trie. The term functional is used to imply immutable and persistent.\n\nThe 30bits of hash are separated into six 5bit values that constitue the hash\npath of any Key in this Trie. However, not all six levels of the Trie are used.\nAs many levels (six or less) are used to find a unique location\nfor the leaf to be placed within the Trie.\n\nIf all six levels of the Trie are used for two or more key\/val pairs then a\nspecial collision leaf will be used to store those key\/val pairs,  at the sixth\nlevel of the Trie.\n*\/\npackage hamt32\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/lleo\/go-hamt\/key\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ Nbits constant is the number of bits(5) a 30bit hash value is split into,\n\/\/ to provied the indexes of a HAMT.\nconst Nbits uint = 5\n\n\/\/ MaxDepth constant is the maximum depth(5) of Nbits values that constitute\n\/\/ the path in a HAMT, from [0..MaxDepth]for a total of MaxDepth+1(6) levels.\n\/\/ Nbits*(MaxDepth+1) == HASHBITS (ie 5*(5+1) == 30).\nconst MaxDepth uint = 5\n\n\/\/ TableCapacity constant is the number of table entries in a each node of\n\/\/ a HAMT datastructure; its value is 1<<Nbits (ie 2^5 == 32).\nconst TableCapacity uint = 1 << Nbits\n\nfunc hashPathMask(depth uint) uint32 {\n\treturn uint32(1<<(depth*Nbits)) - 1\n}\n\n\/\/ Create a string of the form \"\/%02d\/%02d...\" to describe a hashPath of\n\/\/ a given depth.\n\/\/\n\/\/ If you want hashPathString() to include the current idx, you Must\n\/\/ add one to depth. You may need to do this because you are creating\n\/\/ a table to be put at the idx'th slot of the current table.\nfunc hashPathString(hashPath uint32, depth uint) string {\n\tif depth == 0 {\n\t\treturn \"\/\"\n\t}\n\tvar strs = make([]string, depth)\n\n\tfor d := uint(0); d < depth; d++ {\n\t\tvar idx = index(hashPath, d)\n\t\tstrs[d] = fmt.Sprintf(\"%02d\", idx)\n\t}\n\n\treturn \"\/\" + strings.Join(strs, \"\/\")\n}\n\nfunc h30ToString(h30 uint32) string {\n\treturn hashPathString(h30, MaxDepth)\n}\n\nfunc StringToH30(s string) uint32 {\n\tif !strings.HasPrefix(s, \"\/\") {\n\t\tpanic(errors.New(\"does not start with '\/'\"))\n\t}\n\tvar s0 = s[1:]\n\tvar as = strings.Split(s0, \"\/\")\n\n\tvar h30 uint32 = 0\n\tfor i, s1 := range as {\n\t\tvar ui, err = strconv.ParseUint(s1, 10, int(Nbits))\n\t\tif err != nil {\n\t\t\tpanic(errors.Wrap(err, fmt.Sprintf(\"strconv.ParseUint(%q, %d, %d) failed\", s1, 10, Nbits)))\n\t\t}\n\t\th30 |= uint32(ui << (uint(i) * Nbits))\n\t\t\/\/fmt.Printf(\"%d: h30 = %q %2d %#02x %05b\\n\", i, s1, ui, ui, ui)\n\t}\n\n\treturn h30\n}\n\n\/\/ h30ToBitStr is for printf debugging use\nfunc h30ToBitStr(h30 uint32) string {\n\tvar strs = make([]string, MaxDepth+1)\n\n\tfor depth := uint(0); depth <= MaxDepth; depth++ {\n\t\tvar idx = index(h30, depth)\n\t\tstrs[MaxDepth-depth] = fmt.Sprintf(\"%05b\", idx)\n\t}\n\n\treturn strings.Join(strs, \" \")\n}\n\n\/\/indexMask() generates a Nbits(5-bit) mask for a given depth\nfunc indexMask(depth uint) uint32 {\n\treturn uint32((1<<Nbits)-1) << (depth * Nbits)\n}\n\n\/\/index() calculates a Nbits(5-bit) integer based on the hash and depth\nfunc index(h30 uint32, depth uint) uint {\n\tvar idxMask = indexMask(depth)\n\tvar idx = uint((h30 & idxMask) >> (depth * Nbits))\n\treturn idx\n}\n\n\/\/buildHashPath(hashPath, idx, depth)\n\/\/hashPath will be depth Nbits long\nfunc buildHashPath(hashPath uint32, idx, depth uint) uint32 {\n\tvar mask uint32 = (1 << ((depth - 1) * Nbits)) - 1\n\thashPath = hashPath & mask\n\n\treturn hashPath | uint32(idx<<((depth-1)*Nbits))\n}\n\ntype keyVal struct {\n\tkey key.Key\n\tval interface{}\n}\n\n\/\/ GradeTables variable controls whether Hamt structures will upgrade\/\n\/\/ downgrade compressed\/full tables. This variable and FullTableInit\n\/\/ should not be changed during the lifetime of any Hamt structure.\n\/\/ Default: true\nvar GradeTables = true\n\n\/\/ FullTableInit variable controls whether the initial new table type is\n\/\/ fullTable, else the initial new table type is compressedTable.\n\/\/ Default: false\nvar FullTableInit = false\n\n\/\/ UpgradeThreshold is a variable that defines when a compressedTable meats\n\/\/ or exceeds that number of entries, then that table will be upgraded to\n\/\/ a fullTable. This only applies when HybridTables option is chosen.\n\/\/ The current value is TableCapacity\/2.\nvar UpgradeThreshold = TableCapacity * 2 \/ 3\n\n\/\/ DowngradeThreshold is a variable that defines when a fullTable becomes\n\/\/ lower than that number of entries, then that table will be downgraded to\n\/\/ a compressedTable. This only applies when HybridTables option is chosen.\n\/\/ The current value is TableCapacity\/4.\nvar DowngradeThreshold = TableCapacity \/ 4\n\ntype Hamt struct {\n\troot     tableI\n\tnentries uint\n}\n\nfunc (h Hamt) IsEmpty() bool {\n\t\/\/return h.root == nil\n\t\/\/return h.nentries == 0\n\t\/\/return h.root == nil && h.nentries == 0\n\treturn h == Hamt{}\n}\n\nfunc (h Hamt) Root() tableI {\n\treturn h.root\n}\n\nfunc (h Hamt) Nentries() uint {\n\treturn h.nentries\n}\n\nfunc createRootTable(leaf leafI) tableI {\n\tif FullTableInit {\n\t\treturn createRootFullTable(leaf)\n\t}\n\treturn createRootCompressedTable(leaf)\n}\n\n\/\/func createTable(depth uint, leaf1 leafI, k key.Key, v interface{}) tableI {\nfunc createTable(depth uint, leaf1 leafI, leaf2 flatLeaf) tableI {\n\t\/\/var hashPath = k.Hash30() & hashPathMask(depth)\n\t\/\/var leaf2 = *newFlatLeaf(k, v)\n\n\tif FullTableInit {\n\t\treturn createFullTable(depth, leaf1, leaf2)\n\t}\n\treturn createCompressedTable(depth, leaf1, leaf2)\n}\n\n\/\/ copyUp is ONLY called on a fresh copy of the current Hamt. Hence, modifying\n\/\/ it is allowed.\nfunc (nh *Hamt) persist(oldTable, newTable tableI, path tableStack) {\n\tif path.isEmpty() {\n\t\tnh.root = newTable\n\t\treturn\n\t}\n\n\tvar depth = uint(path.len())\n\tvar parentDepth = depth - 1\n\n\tvar parentIdx = index(oldTable.Hash30(), parentDepth)\n\n\tvar oldParent = path.pop()\n\tvar newParent tableI\n\n\tif newTable == nil {\n\t\tnewParent = oldParent.remove(parentIdx)\n\t} else {\n\t\tnewParent = oldParent.replace(parentIdx, newTable)\n\t}\n\n\tnh.persist(oldParent, newParent, path) \/\/recurses at most MaxDepth-1 times\n\n\treturn\n}\n\nfunc (h Hamt) find(k key.Key) (path tableStack, leaf leafI, idx uint) {\n\tif h.IsEmpty() {\n\t\treturn nil, nil, 0\n\t}\n\n\tpath = newTableStack()\n\tvar curTable = h.root\n\n\tvar h30 = k.Hash30()\n\tvar depth uint\n\tvar curNode nodeI\n\n\tfor depth = 0; depth < MaxDepth; depth++ {\n\t\tpath.push(curTable)\n\t\tidx = index(h30, depth)\n\t\tcurNode = curTable.Get(idx)\n\n\t\tswitch n := curNode.(type) {\n\t\tcase nil:\n\t\t\treturn path, nil, idx\n\t\tcase leafI:\n\t\t\treturn path, n, idx\n\t\tcase tableI:\n\t\t\tcurTable = n\n\t\t\t\/\/ exit switch then loop for\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"switch default case: depth=%d; idx=%d; curNode unknown type = %T; value = %v; path=%s\", depth, idx, n, n, path))\n\t\t}\n\t}\n\tif depth == MaxDepth {\n\t\tpath.push(curTable)\n\t\tidx = index(h30, depth)\n\t\tcurNode = curTable.Get(idx)\n\n\t\tif curNode == nil {\n\t\t\treturn path, nil, idx\n\t\t} else if leaf, isLeaf := curNode.(leafI); isLeaf {\n\t\t\treturn path, leaf, idx\n\t\t} else {\n\t\t\tpanic(fmt.Sprintf(\"depth,%d == MaxDepth: %d; idx=%d; unknown type = %T; value = %v; path=%s\", depth, MaxDepth, idx, curNode, curNode, path))\n\t\t}\n\t}\n\n\tpanic(\"SHOULD NEVER GET HERE!\")\n}\n\n\/\/ Get(k) retrieves the value for a given key from the Hamt. The bool\n\/\/ represents whether the key was found.\nfunc (h Hamt) Get(k key.Key) (interface{}, bool) {\n\tvar _, leaf, _ = h.find(k)\n\n\t\/\/var depth = path.len()\n\t\/\/var curTable = path.pop()\n\n\tif leaf == nil {\n\t\treturn nil, false\n\t}\n\n\tvar val, found = leaf.get(k)\n\tif !found {\n\t\treturn nil, false\n\t}\n\n\treturn val, true\n}\n\n\/\/ Put new key\/val pair into Hamt, returning a new persistant Hamt and a bool\n\/\/ indicating if the key\/val pair was added(true) or mearly updated(false).\nfunc (h Hamt) Put(k key.Key, v interface{}) (Hamt, bool) {\n\tvar nh Hamt = h \/\/copy by value\n\n\tvar path, leaf, idx = h.find(k)\n\n\tif path == nil { \/\/ h.IsEmpty()\n\t\tnh.root = createRootTable(newFlatLeaf(k, v))\n\t\tnh.nentries++\n\t\treturn nh, true\n\t}\n\n\tvar curTable = path.pop()\n\tvar depth = uint(path.len())\n\n\tvar newTable tableI\n\tvar added bool\n\n\tif leaf == nil {\n\t\tnewTable = curTable.insert(idx, newFlatLeaf(k, v))\n\t\tadded = true\n\t} else {\n\t\tif leaf.Hash30() == k.Hash30() {\n\t\t\tvar newLeaf leafI\n\t\t\tnewLeaf, added = leaf.put(k, v)\n\t\t\tnewTable = curTable.replace(idx, newLeaf)\n\t\t} else {\n\t\t\tvar tmpTable = createTable(depth+1, leaf, *newFlatLeaf(k, v))\n\t\t\tnewTable = curTable.replace(idx, tmpTable)\n\t\t\tadded = true\n\t\t}\n\t}\n\n\tif added {\n\t\tnh.nentries++\n\t}\n\n\tnh.persist(curTable, newTable, path)\n\n\treturn nh, added\n}\n\n\/\/ Hamt.Del(k) returns a new Hamt, the value deleted, and a boolean that\n\/\/ specifies whether or not the key was deleted (eg it didn't exist to start\n\/\/ with). Therefor you must always test deleted before using the new *Hamt\n\/\/ value.\nfunc (h Hamt) Del(k key.Key) (Hamt, interface{}, bool) {\n\tvar nh Hamt = h \/\/ copy by value\n\n\tvar path, leaf, idx = h.find(k)\n\n\tif path == nil { \/\/ h.IsEmpty()\n\t\treturn nh, nil, false\n\t}\n\n\tvar curTable = path.pop()\n\t\/\/var depth = uint(path.len())\n\n\tvar newTable tableI\n\tvar val interface{}\n\tvar deleted bool\n\n\tif leaf == nil {\n\t\t\/\/return nh, val, deleted\n\t\treturn h, nil, false\n\t} else {\n\t\tvar newLeaf leafI\n\t\tnewLeaf, val, deleted = leaf.del(k)\n\n\t\tif !deleted {\n\t\t\t\/\/return nh, val, deleted\n\t\t\treturn h, nil, false\n\t\t}\n\n\t\tif newLeaf == nil {\n\t\t\tnewTable = curTable.remove(idx)\n\t\t} else {\n\t\t\tnewTable = curTable.replace(idx, newLeaf)\n\t\t}\n\t}\n\n\tif deleted {\n\t\tnh.nentries--\n\t}\n\n\tnh.persist(curTable, newTable, path)\n\n\treturn nh, val, deleted\n}\n\nfunc (h Hamt) String() string {\n\treturn fmt.Sprintf(\"Hamt{ nentries: %d, root: %s }\", h.nentries, h.root)\n}\n\nconst halfIndent = \"  \"\nconst fullIndent = \"    \"\n\nfunc (h Hamt) LongString(indent string) string {\n\tvar str string\n\tif h.root != nil {\n\t\tstr = indent + fmt.Sprintf(\"Hamt{ nentries: %d, root:\\n\", h.nentries)\n\t\tstr += indent + h.root.LongString(indent+fullIndent, true)\n\t\tstr += indent + \"}end\\n\"\n\t\treturn str\n\t} else {\n\t\tstr = indent + fmt.Sprintf(\"Hamt{ nentries: %d, root: nil }\", h.nentries)\n\t}\n\treturn str\n}\n<commit_msg>commented out a random printf debugging func<commit_after>\/*\nPackage hamt32 implements a functional Hash Array Mapped Trie (HAMT).\nIt is called hamt32 because this package is using 32 nodes for each level of\nthe Trie. The term functional is used to imply immutable and persistent.\n\nThe 30bits of hash are separated into six 5bit values that constitue the hash\npath of any Key in this Trie. However, not all six levels of the Trie are used.\nAs many levels (six or less) are used to find a unique location\nfor the leaf to be placed within the Trie.\n\nIf all six levels of the Trie are used for two or more key\/val pairs then a\nspecial collision leaf will be used to store those key\/val pairs,  at the sixth\nlevel of the Trie.\n*\/\npackage hamt32\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/lleo\/go-hamt\/key\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ Nbits constant is the number of bits(5) a 30bit hash value is split into,\n\/\/ to provied the indexes of a HAMT.\nconst Nbits uint = 5\n\n\/\/ MaxDepth constant is the maximum depth(5) of Nbits values that constitute\n\/\/ the path in a HAMT, from [0..MaxDepth]for a total of MaxDepth+1(6) levels.\n\/\/ Nbits*(MaxDepth+1) == HASHBITS (ie 5*(5+1) == 30).\nconst MaxDepth uint = 5\n\n\/\/ TableCapacity constant is the number of table entries in a each node of\n\/\/ a HAMT datastructure; its value is 1<<Nbits (ie 2^5 == 32).\nconst TableCapacity uint = 1 << Nbits\n\nfunc hashPathMask(depth uint) uint32 {\n\treturn uint32(1<<(depth*Nbits)) - 1\n}\n\n\/\/ Create a string of the form \"\/%02d\/%02d...\" to describe a hashPath of\n\/\/ a given depth.\n\/\/\n\/\/ If you want hashPathString() to include the current idx, you Must\n\/\/ add one to depth. You may need to do this because you are creating\n\/\/ a table to be put at the idx'th slot of the current table.\nfunc hashPathString(hashPath uint32, depth uint) string {\n\tif depth == 0 {\n\t\treturn \"\/\"\n\t}\n\tvar strs = make([]string, depth)\n\n\tfor d := uint(0); d < depth; d++ {\n\t\tvar idx = index(hashPath, d)\n\t\tstrs[d] = fmt.Sprintf(\"%02d\", idx)\n\t}\n\n\treturn \"\/\" + strings.Join(strs, \"\/\")\n}\n\nfunc h30ToString(h30 uint32) string {\n\treturn hashPathString(h30, MaxDepth)\n}\n\nfunc StringToH30(s string) uint32 {\n\tif !strings.HasPrefix(s, \"\/\") {\n\t\tpanic(errors.New(\"does not start with '\/'\"))\n\t}\n\tvar s0 = s[1:]\n\tvar as = strings.Split(s0, \"\/\")\n\n\tvar h30 uint32 = 0\n\tfor i, s1 := range as {\n\t\tvar ui, err = strconv.ParseUint(s1, 10, int(Nbits))\n\t\tif err != nil {\n\t\t\tpanic(errors.Wrap(err, fmt.Sprintf(\"strconv.ParseUint(%q, %d, %d) failed\", s1, 10, Nbits)))\n\t\t}\n\t\th30 |= uint32(ui << (uint(i) * Nbits))\n\t\t\/\/fmt.Printf(\"%d: h30 = %q %2d %#02x %05b\\n\", i, s1, ui, ui, ui)\n\t}\n\n\treturn h30\n}\n\n\/\/\/\/ h30ToBitStr is for printf debugging use\n\/\/func h30ToBitStr(h30 uint32) string {\n\/\/\tvar strs = make([]string, MaxDepth+1)\n\/\/\n\/\/\tfor depth := uint(0); depth <= MaxDepth; depth++ {\n\/\/\t\tvar idx = index(h30, depth)\n\/\/\t\tstrs[MaxDepth-depth] = fmt.Sprintf(\"%05b\", idx)\n\/\/\t}\n\/\/\n\/\/\treturn strings.Join(strs, \" \")\n\/\/}\n\n\/\/indexMask() generates a Nbits(5-bit) mask for a given depth\nfunc indexMask(depth uint) uint32 {\n\treturn uint32((1<<Nbits)-1) << (depth * Nbits)\n}\n\n\/\/index() calculates a Nbits(5-bit) integer based on the hash and depth\nfunc index(h30 uint32, depth uint) uint {\n\tvar idxMask = indexMask(depth)\n\tvar idx = uint((h30 & idxMask) >> (depth * Nbits))\n\treturn idx\n}\n\n\/\/buildHashPath(hashPath, idx, depth)\n\/\/hashPath will be depth Nbits long\nfunc buildHashPath(hashPath uint32, idx, depth uint) uint32 {\n\tvar mask uint32 = (1 << ((depth - 1) * Nbits)) - 1\n\thashPath = hashPath & mask\n\n\treturn hashPath | uint32(idx<<((depth-1)*Nbits))\n}\n\ntype keyVal struct {\n\tkey key.Key\n\tval interface{}\n}\n\n\/\/ GradeTables variable controls whether Hamt structures will upgrade\/\n\/\/ downgrade compressed\/full tables. This variable and FullTableInit\n\/\/ should not be changed during the lifetime of any Hamt structure.\n\/\/ Default: true\nvar GradeTables = true\n\n\/\/ FullTableInit variable controls whether the initial new table type is\n\/\/ fullTable, else the initial new table type is compressedTable.\n\/\/ Default: false\nvar FullTableInit = false\n\n\/\/ UpgradeThreshold is a variable that defines when a compressedTable meats\n\/\/ or exceeds that number of entries, then that table will be upgraded to\n\/\/ a fullTable. This only applies when HybridTables option is chosen.\n\/\/ The current value is TableCapacity\/2.\nvar UpgradeThreshold = TableCapacity * 2 \/ 3\n\n\/\/ DowngradeThreshold is a variable that defines when a fullTable becomes\n\/\/ lower than that number of entries, then that table will be downgraded to\n\/\/ a compressedTable. This only applies when HybridTables option is chosen.\n\/\/ The current value is TableCapacity\/4.\nvar DowngradeThreshold = TableCapacity \/ 4\n\ntype Hamt struct {\n\troot     tableI\n\tnentries uint\n}\n\nfunc (h Hamt) IsEmpty() bool {\n\t\/\/return h.root == nil\n\t\/\/return h.nentries == 0\n\t\/\/return h.root == nil && h.nentries == 0\n\treturn h == Hamt{}\n}\n\nfunc (h Hamt) Root() tableI {\n\treturn h.root\n}\n\nfunc (h Hamt) Nentries() uint {\n\treturn h.nentries\n}\n\nfunc createRootTable(leaf leafI) tableI {\n\tif FullTableInit {\n\t\treturn createRootFullTable(leaf)\n\t}\n\treturn createRootCompressedTable(leaf)\n}\n\n\/\/func createTable(depth uint, leaf1 leafI, k key.Key, v interface{}) tableI {\nfunc createTable(depth uint, leaf1 leafI, leaf2 flatLeaf) tableI {\n\t\/\/var hashPath = k.Hash30() & hashPathMask(depth)\n\t\/\/var leaf2 = *newFlatLeaf(k, v)\n\n\tif FullTableInit {\n\t\treturn createFullTable(depth, leaf1, leaf2)\n\t}\n\treturn createCompressedTable(depth, leaf1, leaf2)\n}\n\n\/\/ copyUp is ONLY called on a fresh copy of the current Hamt. Hence, modifying\n\/\/ it is allowed.\nfunc (nh *Hamt) persist(oldTable, newTable tableI, path tableStack) {\n\tif path.isEmpty() {\n\t\tnh.root = newTable\n\t\treturn\n\t}\n\n\tvar depth = uint(path.len())\n\tvar parentDepth = depth - 1\n\n\tvar parentIdx = index(oldTable.Hash30(), parentDepth)\n\n\tvar oldParent = path.pop()\n\tvar newParent tableI\n\n\tif newTable == nil {\n\t\tnewParent = oldParent.remove(parentIdx)\n\t} else {\n\t\tnewParent = oldParent.replace(parentIdx, newTable)\n\t}\n\n\tnh.persist(oldParent, newParent, path) \/\/recurses at most MaxDepth-1 times\n\n\treturn\n}\n\nfunc (h Hamt) find(k key.Key) (path tableStack, leaf leafI, idx uint) {\n\tif h.IsEmpty() {\n\t\treturn nil, nil, 0\n\t}\n\n\tpath = newTableStack()\n\tvar curTable = h.root\n\n\tvar h30 = k.Hash30()\n\tvar depth uint\n\tvar curNode nodeI\n\n\tfor depth = 0; depth < MaxDepth; depth++ {\n\t\tpath.push(curTable)\n\t\tidx = index(h30, depth)\n\t\tcurNode = curTable.Get(idx)\n\n\t\tswitch n := curNode.(type) {\n\t\tcase nil:\n\t\t\treturn path, nil, idx\n\t\tcase leafI:\n\t\t\treturn path, n, idx\n\t\tcase tableI:\n\t\t\tcurTable = n\n\t\t\t\/\/ exit switch then loop for\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"switch default case: depth=%d; idx=%d; curNode unknown type = %T; value = %v; path=%s\", depth, idx, n, n, path))\n\t\t}\n\t}\n\tif depth == MaxDepth {\n\t\tpath.push(curTable)\n\t\tidx = index(h30, depth)\n\t\tcurNode = curTable.Get(idx)\n\n\t\tif curNode == nil {\n\t\t\treturn path, nil, idx\n\t\t} else if leaf, isLeaf := curNode.(leafI); isLeaf {\n\t\t\treturn path, leaf, idx\n\t\t} else {\n\t\t\tpanic(fmt.Sprintf(\"depth,%d == MaxDepth: %d; idx=%d; unknown type = %T; value = %v; path=%s\", depth, MaxDepth, idx, curNode, curNode, path))\n\t\t}\n\t}\n\n\tpanic(\"SHOULD NEVER GET HERE!\")\n}\n\n\/\/ Get(k) retrieves the value for a given key from the Hamt. The bool\n\/\/ represents whether the key was found.\nfunc (h Hamt) Get(k key.Key) (interface{}, bool) {\n\tvar _, leaf, _ = h.find(k)\n\n\t\/\/var depth = path.len()\n\t\/\/var curTable = path.pop()\n\n\tif leaf == nil {\n\t\treturn nil, false\n\t}\n\n\tvar val, found = leaf.get(k)\n\tif !found {\n\t\treturn nil, false\n\t}\n\n\treturn val, true\n}\n\n\/\/ Put new key\/val pair into Hamt, returning a new persistant Hamt and a bool\n\/\/ indicating if the key\/val pair was added(true) or mearly updated(false).\nfunc (h Hamt) Put(k key.Key, v interface{}) (Hamt, bool) {\n\tvar nh Hamt = h \/\/copy by value\n\n\tvar path, leaf, idx = h.find(k)\n\n\tif path == nil { \/\/ h.IsEmpty()\n\t\tnh.root = createRootTable(newFlatLeaf(k, v))\n\t\tnh.nentries++\n\t\treturn nh, true\n\t}\n\n\tvar curTable = path.pop()\n\tvar depth = uint(path.len())\n\n\tvar newTable tableI\n\tvar added bool\n\n\tif leaf == nil {\n\t\tnewTable = curTable.insert(idx, newFlatLeaf(k, v))\n\t\tadded = true\n\t} else {\n\t\tif leaf.Hash30() == k.Hash30() {\n\t\t\tvar newLeaf leafI\n\t\t\tnewLeaf, added = leaf.put(k, v)\n\t\t\tnewTable = curTable.replace(idx, newLeaf)\n\t\t} else {\n\t\t\tvar tmpTable = createTable(depth+1, leaf, *newFlatLeaf(k, v))\n\t\t\tnewTable = curTable.replace(idx, tmpTable)\n\t\t\tadded = true\n\t\t}\n\t}\n\n\tif added {\n\t\tnh.nentries++\n\t}\n\n\tnh.persist(curTable, newTable, path)\n\n\treturn nh, added\n}\n\n\/\/ Hamt.Del(k) returns a new Hamt, the value deleted, and a boolean that\n\/\/ specifies whether or not the key was deleted (eg it didn't exist to start\n\/\/ with). Therefor you must always test deleted before using the new *Hamt\n\/\/ value.\nfunc (h Hamt) Del(k key.Key) (Hamt, interface{}, bool) {\n\tvar nh Hamt = h \/\/ copy by value\n\n\tvar path, leaf, idx = h.find(k)\n\n\tif path == nil { \/\/ h.IsEmpty()\n\t\treturn nh, nil, false\n\t}\n\n\tvar curTable = path.pop()\n\t\/\/var depth = uint(path.len())\n\n\tvar newTable tableI\n\tvar val interface{}\n\tvar deleted bool\n\n\tif leaf == nil {\n\t\t\/\/return nh, val, deleted\n\t\treturn h, nil, false\n\t} else {\n\t\tvar newLeaf leafI\n\t\tnewLeaf, val, deleted = leaf.del(k)\n\n\t\tif !deleted {\n\t\t\t\/\/return nh, val, deleted\n\t\t\treturn h, nil, false\n\t\t}\n\n\t\tif newLeaf == nil {\n\t\t\tnewTable = curTable.remove(idx)\n\t\t} else {\n\t\t\tnewTable = curTable.replace(idx, newLeaf)\n\t\t}\n\t}\n\n\tif deleted {\n\t\tnh.nentries--\n\t}\n\n\tnh.persist(curTable, newTable, path)\n\n\treturn nh, val, deleted\n}\n\nfunc (h Hamt) String() string {\n\treturn fmt.Sprintf(\"Hamt{ nentries: %d, root: %s }\", h.nentries, h.root)\n}\n\nconst halfIndent = \"  \"\nconst fullIndent = \"    \"\n\nfunc (h Hamt) LongString(indent string) string {\n\tvar str string\n\tif h.root != nil {\n\t\tstr = indent + fmt.Sprintf(\"Hamt{ nentries: %d, root:\\n\", h.nentries)\n\t\tstr += indent + h.root.LongString(indent+fullIndent, true)\n\t\tstr += indent + \"}end\\n\"\n\t\treturn str\n\t} else {\n\t\tstr = indent + fmt.Sprintf(\"Hamt{ nentries: %d, root: nil }\", h.nentries)\n\t}\n\treturn str\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/nsf\/termbox-go\"\n)\n\nconst (\n\tpauseAfterKeypress = (1500 * time.Millisecond)\n\tredrawPause        = 15 * time.Millisecond\n)\n\nvar (\n\tglobal_lastkeypress int64\n)\n\nfunc getRoot() string {\n\tif len(flag.Args()) == 0 {\n\t\treturn \".\"\n\t} else {\n\t\treturn flag.Arg(0)\n\t}\n}\n\n\/\/ hf --cmd=emacs ~\/go\/src\/github.com\/hugows\/ happy\nvar cmd = flag.String(\"cmd\", \"vim\", \"command to run\")\n\n\/\/ var termkey *TermboxEventWrapper\n\n\/\/ strings.Replace(tw.Text, \" \", \"+\", -1)\n\nfunc main() {\n\tflag.Parse()\n\n\tvar rview ResultsView\n\n\troot := getRoot()\n\tfi, err := os.Stat(root)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tif !fi.IsDir() {\n\t\tfmt.Println(root, \"is NOT a folder\")\n\t\treturn\n\t}\n\n\terr = termbox.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttermbox.SetInputMode(termbox.InputEsc)\n\n\tresultset := new(ResultSet)\n\n\tw, h := termbox.Size()\n\tmodeline := NewModeline(0, h-1, w)\n\tcmdline := new(CommandLine)\n\n\tidleTimer := time.NewTimer(1 * time.Hour)\n\n\tfileCh := walkFiles(getRoot())\n\ttermboxEventCh := make(chan termbox.Event)\n\n\tforceDrawCh := make(chan bool, 100)\n\tforceSortCh := make(chan bool, 100)\n\n\ttimeLastUser := time.Now().Add(-1 * time.Hour)\n\ttimeLastFilter := time.Now()\n\n\tgo func() {\n\t\tfor {\n\t\t\tev := termbox.PollEvent()\n\t\t\tif ev.Type == termbox.EventKey {\n\t\t\t\ttimeLastUser = time.Now()\n\t\t\t\tglobal_lastkeypress = timeLastUser.UnixNano()\n\t\t\t}\n\t\t\ttermboxEventCh <- ev\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\t<-forceSortCh\n\t\t\tfiltered := resultset.Filter(global_lastkeypress, modeline.Contents())\n\t\t\trview.Update(filtered.results)\n\t\t\tcmdline.Update(rview.GetSelected())\n\t\t\tforceDrawCh <- true\n\t\t}\n\t}()\n\n\t\/\/ Command name is:\n\t\/\/ os.Args[0]\n\n\tmodeline.Draw(&rview)\n\tcmdline.Draw(0, h-2, w)\n\trview.SetSize(0, 0, w, h-2)\n\ttermbox.Flush()\n\n\tfor {\n\t\tselect {\n\t\tcase <-forceDrawCh:\n\t\t\t\/* redraw *\/\n\n\t\tcase <-idleTimer.C:\n\t\t\tidleTimer = time.NewTimer(1 * time.Hour)\n\t\t\tif !modeline.paused {\n\t\t\t\tmodeline.LastFile()\n\t\t\t\tfileCh = nil\n\t\t\t}\n\n\t\tcase filename, ok := <-fileCh:\n\t\t\tif time.Since(timeLastUser) > pauseAfterKeypress {\n\t\t\t\tmodeline.Unpause()\n\t\t\t} else {\n\t\t\t\tmodeline.Pause()\n\t\t\t}\n\n\t\t\tif ok {\n\t\t\t\tresultset.Insert(filename)\n\t\t\t}\n\n\t\t\tif !modeline.paused && time.Since(timeLastFilter) > (15*time.Millisecond) {\n\t\t\t\tforceSortCh <- true\n\t\t\t\ttimeLastFilter = time.Now()\n\n\t\t\t\tif !ok {\n\t\t\t\t\tmodeline.LastFile()\n\t\t\t\t\tfileCh = nil\n\t\t\t\t}\n\t\t\t} else if !ok {\n\t\t\t\tidleTimer.Reset(redrawPause)\n\t\t\t\tfileCh = nil\n\t\t\t}\n\n\t\tcase ev := <-termboxEventCh:\n\t\t\tif fileCh != nil {\n\t\t\t\tidleTimer.Reset(pauseAfterKeypress)\n\t\t\t} else {\n\t\t\t\tmodeline.Unpause()\n\t\t\t}\n\n\t\t\tswitch ev.Type {\n\t\t\tcase termbox.EventKey:\n\t\t\t\tswitch ev.Key {\n\t\t\t\tcase termbox.KeyEsc, termbox.KeyCtrlC:\n\t\t\t\t\ttermbox.Close()\n\t\t\t\t\treturn\n\t\t\t\tcase termbox.KeyEnter:\n\t\t\t\t\ttermbox.Close()\n\t\t\t\t\t\/\/ runCmdWithArgs(rview.FormatSelected())\n\t\t\t\t\treturn\n\t\t\t\tcase termbox.KeyCtrlT:\n\t\t\t\t\trview.ToggleMarkAll()\n\t\t\t\tcase termbox.KeyArrowUp, termbox.KeyCtrlP:\n\t\t\t\t\tcmdline.Update(rview.SelectPrevious())\n\t\t\t\tcase termbox.KeyArrowDown, termbox.KeyCtrlN:\n\t\t\t\t\tcmdline.Update(rview.SelectNext())\n\t\t\t\tcase termbox.KeyArrowLeft, termbox.KeyCtrlB:\n\t\t\t\t\tmodeline.input.MoveCursorOneRuneBackward()\n\t\t\t\tcase termbox.KeyArrowRight, termbox.KeyCtrlF:\n\t\t\t\t\tmodeline.input.MoveCursorOneRuneForward()\n\t\t\t\tcase termbox.KeyBackspace, termbox.KeyBackspace2:\n\t\t\t\t\tmodeline.input.DeleteRuneBackward()\n\t\t\t\t\tforceSortCh <- true\n\t\t\t\tcase termbox.KeyDelete, termbox.KeyCtrlD:\n\t\t\t\t\tmodeline.input.DeleteRuneForward()\n\t\t\t\t\tforceSortCh <- true\n\t\t\t\tcase termbox.KeySpace:\n\t\t\t\t\trview.ToggleMark()\n\t\t\t\tcase termbox.KeyCtrlK:\n\t\t\t\t\tmodeline.input.DeleteTheRestOfTheLine()\n\t\t\t\t\tforceSortCh <- true\n\t\t\t\tcase termbox.KeyHome, termbox.KeyCtrlA:\n\t\t\t\t\tmodeline.input.MoveCursorToBeginningOfTheLine()\n\t\t\t\tcase termbox.KeyEnd, termbox.KeyCtrlE:\n\t\t\t\t\tmodeline.input.MoveCursorToEndOfTheLine()\n\t\t\t\tdefault:\n\t\t\t\t\tif ev.Ch != 0 {\n\t\t\t\t\t\tmodeline.input.InsertRune(ev.Ch)\n\t\t\t\t\t\tforceSortCh <- true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase termbox.EventError:\n\t\t\t\tpanic(ev.Err)\n\t\t\t}\n\n\t\t\t\/\/ fmt.Println(modeline.Contents())\n\t\t}\n\n\t\tmodeline.Draw(&rview)\n\t\tcmdline.Draw(0, h-2, w)\n\t\trview.Draw()\n\t\ttermbox.Flush()\n\t}\n\n}\n<commit_msg>missing forceSort<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/nsf\/termbox-go\"\n)\n\nconst (\n\tpauseAfterKeypress = (1500 * time.Millisecond)\n\tredrawPause        = 30 * time.Millisecond\n)\n\nvar (\n\tglobal_lastkeypress int64\n)\n\nfunc getRoot() string {\n\tif len(flag.Args()) == 0 {\n\t\treturn \".\"\n\t} else {\n\t\treturn flag.Arg(0)\n\t}\n}\n\n\/\/ hf --cmd=emacs ~\/go\/src\/github.com\/hugows\/ happy\nvar cmd = flag.String(\"cmd\", \"vim\", \"command to run\")\n\nfunc main() {\n\tflag.Parse()\n\n\tvar rview ResultsView\n\n\troot := getRoot()\n\tfi, err := os.Stat(root)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tif !fi.IsDir() {\n\t\tfmt.Println(root, \"is NOT a folder\")\n\t\treturn\n\t}\n\n\terr = termbox.Init()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttermbox.SetInputMode(termbox.InputEsc)\n\n\tresultset := new(ResultSet)\n\n\tw, h := termbox.Size()\n\tmodeline := NewModeline(0, h-1, w)\n\tcmdline := new(CommandLine)\n\n\tidleTimer := time.NewTimer(1 * time.Hour)\n\n\tfileCh := walkFiles(getRoot())\n\ttermboxEventCh := make(chan termbox.Event)\n\n\tforceDrawCh := make(chan bool, 100)\n\tforceSortCh := make(chan bool, 100)\n\n\ttimeLastUser := time.Now().Add(-1 * time.Hour)\n\ttimeLastFilter := time.Now()\n\n\tgo func() {\n\t\tfor {\n\t\t\tev := termbox.PollEvent()\n\t\t\tif ev.Type == termbox.EventKey {\n\t\t\t\ttimeLastUser = time.Now()\n\t\t\t\tglobal_lastkeypress = timeLastUser.UnixNano()\n\t\t\t}\n\t\t\ttermboxEventCh <- ev\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tfor {\n\t\t\t<-forceSortCh\n\t\t\tfiltered := resultset.Filter(global_lastkeypress, modeline.Contents())\n\t\t\trview.Update(filtered.results)\n\t\t\tcmdline.Update(rview.GetSelected())\n\t\t\tforceDrawCh <- true\n\t\t}\n\t}()\n\n\t\/\/ Command name is:\n\t\/\/ os.Args[0]\n\n\tmodeline.Draw(&rview)\n\tcmdline.Draw(0, h-2, w)\n\trview.SetSize(0, 0, w, h-2)\n\ttermbox.Flush()\n\n\tfor {\n\t\tselect {\n\t\tcase <-forceDrawCh:\n\t\t\t\/* redraw *\/\n\n\t\tcase <-idleTimer.C:\n\t\t\tidleTimer = time.NewTimer(1 * time.Hour)\n\t\t\tif !modeline.paused {\n\t\t\t\tmodeline.LastFile()\n\t\t\t\tfileCh = nil\n\t\t\t\tforceSortCh <- true\n\t\t\t}\n\n\t\tcase filename, ok := <-fileCh:\n\t\t\tif time.Since(timeLastUser) > pauseAfterKeypress {\n\t\t\t\tmodeline.Unpause()\n\t\t\t} else {\n\t\t\t\tmodeline.Pause()\n\t\t\t}\n\n\t\t\tif ok {\n\t\t\t\tresultset.Insert(filename)\n\t\t\t}\n\n\t\t\tif !modeline.paused && time.Since(timeLastFilter) > redrawPause {\n\t\t\t\tforceSortCh <- true\n\t\t\t\ttimeLastFilter = time.Now()\n\n\t\t\t\tif !ok {\n\t\t\t\t\tmodeline.LastFile()\n\t\t\t\t\tfileCh = nil\n\t\t\t\t}\n\t\t\t} else if !ok {\n\t\t\t\tidleTimer.Reset(redrawPause)\n\t\t\t\tfileCh = nil\n\t\t\t}\n\n\t\tcase ev := <-termboxEventCh:\n\t\t\tif fileCh != nil {\n\t\t\t\tidleTimer.Reset(pauseAfterKeypress)\n\t\t\t} else {\n\t\t\t\tmodeline.Unpause()\n\t\t\t}\n\n\t\t\tswitch ev.Type {\n\t\t\tcase termbox.EventKey:\n\t\t\t\tswitch ev.Key {\n\t\t\t\tcase termbox.KeyEsc, termbox.KeyCtrlC:\n\t\t\t\t\ttermbox.Close()\n\t\t\t\t\treturn\n\t\t\t\tcase termbox.KeyEnter:\n\t\t\t\t\ttermbox.Close()\n\t\t\t\t\t\/\/ runCmdWithArgs(rview.FormatSelected())\n\t\t\t\t\treturn\n\t\t\t\tcase termbox.KeyCtrlT:\n\t\t\t\t\trview.ToggleMarkAll()\n\t\t\t\tcase termbox.KeyArrowUp, termbox.KeyCtrlP:\n\t\t\t\t\tcmdline.Update(rview.SelectPrevious())\n\t\t\t\tcase termbox.KeyArrowDown, termbox.KeyCtrlN:\n\t\t\t\t\tcmdline.Update(rview.SelectNext())\n\t\t\t\tcase termbox.KeyArrowLeft, termbox.KeyCtrlB:\n\t\t\t\t\tmodeline.input.MoveCursorOneRuneBackward()\n\t\t\t\tcase termbox.KeyArrowRight, termbox.KeyCtrlF:\n\t\t\t\t\tmodeline.input.MoveCursorOneRuneForward()\n\t\t\t\tcase termbox.KeyBackspace, termbox.KeyBackspace2:\n\t\t\t\t\tmodeline.input.DeleteRuneBackward()\n\t\t\t\t\tforceSortCh <- true\n\t\t\t\tcase termbox.KeyDelete, termbox.KeyCtrlD:\n\t\t\t\t\tmodeline.input.DeleteRuneForward()\n\t\t\t\t\tforceSortCh <- true\n\t\t\t\tcase termbox.KeySpace:\n\t\t\t\t\trview.ToggleMark()\n\t\t\t\tcase termbox.KeyCtrlK:\n\t\t\t\t\tmodeline.input.DeleteTheRestOfTheLine()\n\t\t\t\t\tforceSortCh <- true\n\t\t\t\tcase termbox.KeyHome, termbox.KeyCtrlA:\n\t\t\t\t\tmodeline.input.MoveCursorToBeginningOfTheLine()\n\t\t\t\tcase termbox.KeyEnd, termbox.KeyCtrlE:\n\t\t\t\t\tmodeline.input.MoveCursorToEndOfTheLine()\n\t\t\t\tdefault:\n\t\t\t\t\tif ev.Ch != 0 {\n\t\t\t\t\t\tmodeline.input.InsertRune(ev.Ch)\n\t\t\t\t\t\tforceSortCh <- true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase termbox.EventError:\n\t\t\t\tpanic(ev.Err)\n\t\t\t}\n\n\t\t\t\/\/ fmt.Println(modeline.Contents())\n\t\t}\n\n\t\tmodeline.Draw(&rview)\n\t\tcmdline.Draw(0, h-2, w)\n\t\trview.Draw()\n\t\ttermbox.Flush()\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package pop3\n\nimport (\n\t\"bds\/lib\/maildir\"\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"io\"\n\t\"net\"\n\t\"net\/textproto\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype MailDirGetter interface {\n\t\/\/ get a user's maildir\n\tGetUserMaildir(user string) (maildir.MailDir, error)\n}\n\ntype mailDirGetter string\n\nfunc (md mailDirGetter) GetUserMaildir(user string) (m maildir.MailDir, err error) {\n\tm = maildir.MailDir(md)\n\treturn\n}\n\n\/\/ a maildir getter that always uses 1 directory\nfunc NewMailDirGetter(path string) MailDirGetter {\n\treturn mailDirGetter(path)\n}\n\n\/\/ pop3 server\ntype Server struct {\n\t\/\/ function that obtains a maildir given a user\n\tGetMailDir MailDirGetter\n\t\/\/ server name\n\tname string\n}\n\nfunc New() *Server {\n\thost, _ := os.Hostname()\n\treturn &Server{\n\t\tname: host,\n\t}\n}\n\n\/\/ get all messages in maildir\nfunc (s *Server) getMessages(user string) (msgs []maildir.Message, err error) {\n\t\/\/ get user's maildir\n\tvar md maildir.MailDir\n\tif s.GetMailDir == nil {\n\t\terr = errors.New(\"could't find maildir\")\n\t\treturn\n\t}\n\tmd, err = s.GetMailDir.GetUserMaildir(user)\n\tif err != nil {\n\t\treturn\n\t}\n\t\/\/ move new mail into cur\n\tvar ms []maildir.Message\n\tms, err = md.ListNew()\n\tif err == nil {\n\t\tfor _, m := range ms {\n\t\t\terr = md.ProcessNew(m)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"error processing maildir: %s\", err.Error())\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ get all current files\n\tmsgs, err = md.ListCur()\n\treturn\n}\n\nfunc (s *Server) checkUser(user, passwd string) (allowed bool) {\n\t\/\/ TODO: implement\n\tallowed = true\n\treturn\n}\n\nfunc (s *Server) checkDigest(user, digest string) (allowed bool) {\n\t\/\/ TODO: implement\n\tallowed = true\n\treturn\n}\n\n\/\/ get all messages and octet count\nfunc (s *Server) obtainMessages(user string) (msgs []maildir.Message, o int64, err error) {\n\tmsgs, err = s.getMessages(user)\n\tif err == nil {\n\t\tfor _, msg := range msgs {\n\t\t\tvar info os.FileInfo\n\t\t\tinfo, err = os.Stat(msg.Filepath())\n\t\t\tif err == nil && !info.IsDir() {\n\t\t\t\to += info.Size()\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ pop3 session handler\ntype pop3Session struct {\n\t\/\/ network connection\n\tc *textproto.Conn\n\t\/\/ parent server\n\ts *Server\n\t\/\/ are we in transaction state?\n\ttransaction bool\n\t\/\/ current user\n\tuser string\n\t\/\/ messages we have in this transaction\n\tmsgs []maildir.Message\n\t\/\/ how many octets we have for all messages\n\tocts int64\n\t\/\/ messages to delete\n\tdels []maildir.Message\n}\n\n\/\/ run pop3 session mainloop\nfunc (p *pop3Session) Run() {\n\t\/\/ send banner\n\terr := p.c.PrintfLine(\"+OK POP3 Server Ready <%d.%d@%s>\", os.Getpid(), time.Now().Unix(), p.s.name)\n\tfor err == nil {\n\t\tvar line string\n\t\tline, err = p.c.ReadLine()\n\t\tif err == nil {\n\t\t\tif strings.ToUpper(line) == \"QUIT\" {\n\t\t\t\t\/\/ check for quit command\n\t\t\t\terr = p.OK(\"k bai\")\n\t\t\t\tbreak\n\t\t\t} else if p.transaction {\n\t\t\t\terr = p.handleTransactionLine(line)\n\t\t\t} else {\n\t\t\t\terr = p.handleLine(line)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil && err != io.EOF {\n\t\tlog.Errorf(\"error in pop3 session: %s\", err.Error())\n\t}\n\t\/\/ close connection\n\tp.c.Close()\n\t\/\/ delete old messages\n\tfor _, msg := range p.dels {\n\t\tos.Remove(msg.Filepath())\n\t}\n}\n\n\/\/ handle line when in transaction mode\nfunc (p *pop3Session) handleTransactionLine(line string) (err error) {\n\tvar info os.FileInfo\n\tvar idx int\n\tparts := strings.Split(line, \" \")\n\tcmd := strings.ToUpper(parts[0])\n\tswitch cmd {\n\tcase \"DELE\":\n\t\tif len(parts) == 2 {\n\t\t\tidx, err = strconv.Atoi(parts[1])\n\t\t\tif err == nil && (idx > 0 && idx <= len(p.msgs)) {\n\t\t\t\t\/\/ valid, add it to delete\n\t\t\t\tp.dels = append(p.dels, p.msgs[idx-1])\n\t\t\t} else {\n\t\t\t\t\/\/ invalid\n\t\t\t\terr = p.Error(err.Error())\n\t\t\t}\n\t\t}\n\tcase \"RETR\":\n\t\tif len(parts) == 2 {\n\t\t\tidx, err = strconv.Atoi(parts[1])\n\t\t\tif err == nil && (idx > 0 && idx <= len(p.msgs)) {\n\t\t\t\t\/\/ valid\n\t\t\t\tmsg := p.msgs[idx-1].Filepath()\n\t\t\t\tvar f *os.File\n\t\t\t\tf, err = os.Open(msg)\n\t\t\t\tif err == nil {\n\t\t\t\t\tr := bufio.NewReader(f)\n\t\t\t\t\tinfo, err = f.Stat()\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\terr = p.c.PrintfLine(\"+OK %d octets\", info.Size())\n\t\t\t\t\t\tfor err == nil {\n\t\t\t\t\t\t\t\/\/ send line\n\t\t\t\t\t\t\tline, err = r.ReadString(10)\n\t\t\t\t\t\t\tif err == io.EOF {\n\t\t\t\t\t\t\t\terr = nil\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t} else if err == nil {\n\t\t\t\t\t\t\t\tline = strings.Trim(line, \"\\r\")\n\t\t\t\t\t\t\t\tline = strings.Trim(line, \"\\n\")\n\t\t\t\t\t\t\t\tif line == \".\" {\n\t\t\t\t\t\t\t\t\tline = \" .\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\/\/ send line\n\t\t\t\t\t\t\t\terr = p.c.PrintfLine(line)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\/\/ error\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tf.Close()\n\t\t\t\t\t\/\/ end\n\t\t\t\t\terr = p.c.PrintfLine(\".\")\n\t\t\t\t} else {\n\t\t\t\t\terr = p.Error(err.Error())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ invalid\n\t\t\t\terr = p.Error(\"bad message\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = p.Error(\"invalid syntax\")\n\t\t}\n\t\tbreak\n\tcase \"UIDL\":\n\t\tif len(parts) == 2 {\n\t\t\t\/\/ 1 message\n\t\t\tidx, err = strconv.Atoi(parts[1])\n\t\t\tif err == nil && (idx > 0 && idx <= len(p.msgs)) {\n\t\t\t\t\/\/ valid\n\t\t\t\terr = p.OK(parts[1] + \" \" + p.msgs[idx-1].Filename())\n\t\t\t} else {\n\t\t\t\t\/\/ invalid\n\t\t\t\terr = p.Error(\"bad message\")\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ all messages\n\t\t\tp.OK(\"\")\n\t\t\tdw := p.c.DotWriter()\n\t\t\tfor idx, msg := range p.msgs {\n\t\t\t\tfmt.Fprintf(dw, \"%d %s\\r\\n\", idx, msg.Filename())\n\t\t\t}\n\t\t\t\/\/ FLUSH :D\n\t\t\terr = dw.Close()\n\t\t}\n\t\t\/\/ begin\n\t\tbreak\n\tcase \"STAT\":\n\t\t\/\/ begin\n\t\t_, err = p.c.W.WriteString(\"+OK \")\n\t\tif err == nil {\n\t\t\t\/\/ write list\n\t\t\tfor idx, _ := range p.msgs {\n\t\t\t\t_, err = fmt.Fprintf(p.c.W, \"%d \", 1+idx)\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err == nil {\n\t\t\t\/\/ done writing list\n\t\t\terr = p.c.PrintfLine(\"\")\n\t\t} else {\n\t\t\terr = p.Error(err.Error())\n\t\t}\n\t\tbreak\n\tcase \"LIST\":\n\t\tif len(parts) == 2 {\n\t\t\t\/\/ 1 message\n\t\t\tidx, err = strconv.Atoi(parts[1])\n\t\t\tif err == nil {\n\t\t\t\tif idx > 0 && idx <= len(p.msgs) {\n\t\t\t\t\tinfo, err = os.Stat(p.msgs[idx-1].Filepath())\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\terr = p.c.PrintfLine(\"+OK %d %d\", idx, info.Size())\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ no existing message\n\t\t\t\t\terr = p.Error(\"no such message\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ all messages\n\t\t\terr = p.c.PrintfLine(\"+OK %d messages (%d octets)\", len(p.msgs), p.octs)\n\t\t\tif err == nil {\n\t\t\t\tdw := p.c.DotWriter()\n\t\t\t\tfor i, msg := range p.msgs {\n\t\t\t\t\tinfo, err = os.Stat(msg.Filepath())\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\/\/ write out entry\n\t\t\t\t\t\tfmt.Fprintf(dw, \"%d %d\\r\\n\", i+1, info.Size())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Errorf(\"error in pop3, stat(): %s\", err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ FLUSH IT !!! :-DDDDD\n\t\t\t\terr = dw.Close()\n\t\t\t}\n\t\t}\n\t\tbreak\n\tdefault:\n\t\terr = p.Error(\"bad command\")\n\t}\n\treturn\n}\n\n\/\/ handle 1 line of input when not in transaction mode\nfunc (p *pop3Session) handleLine(line string) (err error) {\n\tparts := strings.Split(line, \" \")\n\tcmd := strings.ToUpper(parts[0])\n\tswitch cmd {\n\tcase \"NOOP\":\n\t\terr = p.OK(\"\")\n\t\tbreak\n\tcase \"APOP\":\n\t\tif len(parts) == 3 {\n\t\t\tif p.s.checkDigest(parts[1], parts[2]) {\n\t\t\t\t\/\/ load messages\n\t\t\t\tp.msgs, p.octs, err = p.s.obtainMessages(p.user)\n\t\t\t\tif err == nil {\n\t\t\t\t\terr = p.OK(\"maildrop is go for access\")\n\t\t\t\t\tp.transaction = err == nil\n\t\t\t\t} else {\n\t\t\t\t\terr = p.Error(err.Error())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = p.Error(\"permission denied\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = p.Error(\"Bad APOP\")\n\t\t}\n\t\tbreak\n\tcase \"PASS\":\n\t\tif p.s.checkUser(p.user, line[5:]) {\n\t\t\tp.msgs, p.octs, err = p.s.obtainMessages(p.user)\n\t\t\tif err == nil {\n\t\t\t\terr = p.c.PrintfLine(\"+OK %s maildrop logged in, you have %d messages (%d octets)\", p.user, len(p.msgs), p.octs)\n\t\t\t\tp.transaction = err == nil\n\t\t\t} else {\n\t\t\t\terr = p.Error(err.Error())\n\t\t\t}\n\t\t} else {\n\t\t\terr = p.Error(\"bad login\")\n\t\t}\n\t\tbreak\n\tcase \"USER\":\n\t\tif len(parts) > 1 {\n\t\t\tp.user = line[5:]\n\t\t}\n\t\terr = p.OK(\"anonymous access enabled\")\n\t\tbreak\n\tdefault:\n\t\terr = p.Error(\"bad command\")\n\t}\n\treturn\n}\n\nfunc (p *pop3Session) OK(msg string) (err error) {\n\tif len(msg) == 0 {\n\t\terr = p.c.PrintfLine(\"+OK\")\n\t} else {\n\t\terr = p.c.PrintfLine(\"+OK %s\", msg)\n\t}\n\treturn\n}\n\n\/\/ send error\nfunc (p *pop3Session) Error(msg string) (err error) {\n\terr = p.c.PrintfLine(\"-ERR %s\", msg)\n\treturn\n}\n\n\/\/ serve sessions with connections accepted from a net.Listener\nfunc (s *Server) Serve(l net.Listener) (err error) {\n\tfor err == nil {\n\t\tvar c net.Conn\n\t\tc, err = l.Accept()\n\t\tif err == nil {\n\t\t\tp := &pop3Session{\n\t\t\t\tc: textproto.NewConn(c),\n\t\t\t\ts: s,\n\t\t\t}\n\t\t\tgo p.Run()\n\t\t}\n\t}\n\treturn\n}\n<commit_msg>fix DELE command, have it send a reply<commit_after>package pop3\n\nimport (\n\t\"bds\/lib\/maildir\"\n\t\"bufio\"\n\t\"errors\"\n\t\"fmt\"\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"io\"\n\t\"net\"\n\t\"net\/textproto\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype MailDirGetter interface {\n\t\/\/ get a user's maildir\n\tGetUserMaildir(user string) (maildir.MailDir, error)\n}\n\ntype mailDirGetter string\n\nfunc (md mailDirGetter) GetUserMaildir(user string) (m maildir.MailDir, err error) {\n\tm = maildir.MailDir(md)\n\treturn\n}\n\n\/\/ a maildir getter that always uses 1 directory\nfunc NewMailDirGetter(path string) MailDirGetter {\n\treturn mailDirGetter(path)\n}\n\n\/\/ pop3 server\ntype Server struct {\n\t\/\/ function that obtains a maildir given a user\n\tGetMailDir MailDirGetter\n\t\/\/ server name\n\tname string\n}\n\nfunc New() *Server {\n\thost, _ := os.Hostname()\n\treturn &Server{\n\t\tname: host,\n\t}\n}\n\n\/\/ get all messages in maildir\nfunc (s *Server) getMessages(user string) (msgs []maildir.Message, err error) {\n\t\/\/ get user's maildir\n\tvar md maildir.MailDir\n\tif s.GetMailDir == nil {\n\t\terr = errors.New(\"could't find maildir\")\n\t\treturn\n\t}\n\tmd, err = s.GetMailDir.GetUserMaildir(user)\n\tif err != nil {\n\t\treturn\n\t}\n\t\/\/ move new mail into cur\n\tvar ms []maildir.Message\n\tms, err = md.ListNew()\n\tif err == nil {\n\t\tfor _, m := range ms {\n\t\t\terr = md.ProcessNew(m)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"error processing maildir: %s\", err.Error())\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ get all current files\n\tmsgs, err = md.ListCur()\n\treturn\n}\n\nfunc (s *Server) checkUser(user, passwd string) (allowed bool) {\n\t\/\/ TODO: implement\n\tallowed = true\n\treturn\n}\n\nfunc (s *Server) checkDigest(user, digest string) (allowed bool) {\n\t\/\/ TODO: implement\n\tallowed = true\n\treturn\n}\n\n\/\/ get all messages and octet count\nfunc (s *Server) obtainMessages(user string) (msgs []maildir.Message, o int64, err error) {\n\tmsgs, err = s.getMessages(user)\n\tif err == nil {\n\t\tfor _, msg := range msgs {\n\t\t\tvar info os.FileInfo\n\t\t\tinfo, err = os.Stat(msg.Filepath())\n\t\t\tif err == nil && !info.IsDir() {\n\t\t\t\to += info.Size()\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ pop3 session handler\ntype pop3Session struct {\n\t\/\/ network connection\n\tc *textproto.Conn\n\t\/\/ parent server\n\ts *Server\n\t\/\/ are we in transaction state?\n\ttransaction bool\n\t\/\/ current user\n\tuser string\n\t\/\/ messages we have in this transaction\n\tmsgs []maildir.Message\n\t\/\/ how many octets we have for all messages\n\tocts int64\n\t\/\/ messages to delete\n\tdels []maildir.Message\n}\n\n\/\/ run pop3 session mainloop\nfunc (p *pop3Session) Run() {\n\t\/\/ send banner\n\terr := p.c.PrintfLine(\"+OK POP3 Server Ready <%d.%d@%s>\", os.Getpid(), time.Now().Unix(), p.s.name)\n\tfor err == nil {\n\t\tvar line string\n\t\tline, err = p.c.ReadLine()\n\t\tif err == nil {\n\t\t\tif strings.ToUpper(line) == \"QUIT\" {\n\t\t\t\t\/\/ check for quit command\n\t\t\t\terr = p.OK(\"k bai\")\n\t\t\t\tbreak\n\t\t\t} else if p.transaction {\n\t\t\t\terr = p.handleTransactionLine(line)\n\t\t\t} else {\n\t\t\t\terr = p.handleLine(line)\n\t\t\t}\n\t\t}\n\t}\n\tif err != nil && err != io.EOF {\n\t\tlog.Errorf(\"error in pop3 session: %s\", err.Error())\n\t}\n\t\/\/ close connection\n\tp.c.Close()\n\t\/\/ delete old messages\n\tfor _, msg := range p.dels {\n\t\tos.Remove(msg.Filepath())\n\t}\n}\n\n\/\/ handle line when in transaction mode\nfunc (p *pop3Session) handleTransactionLine(line string) (err error) {\n\tvar info os.FileInfo\n\tvar idx int\n\tparts := strings.Split(line, \" \")\n\tcmd := strings.ToUpper(parts[0])\n\tswitch cmd {\n\tcase \"DELE\":\n\t\tif len(parts) == 2 {\n\t\t\tidx, err = strconv.Atoi(parts[1])\n\t\t\tif err == nil && (idx > 0 && idx <= len(p.msgs)) {\n\t\t\t\t\/\/ valid, add it to delete\n\t\t\t\tp.dels = append(p.dels, p.msgs[idx-1])\n\t\t\t\tp.OK(\"\")\n\t\t\t} else {\n\t\t\t\t\/\/ invalid\n\t\t\t\terr = p.Error(err.Error())\n\t\t\t}\n\t\t}\n\tcase \"RETR\":\n\t\tif len(parts) == 2 {\n\t\t\tidx, err = strconv.Atoi(parts[1])\n\t\t\tif err == nil && (idx > 0 && idx <= len(p.msgs)) {\n\t\t\t\t\/\/ valid\n\t\t\t\tmsg := p.msgs[idx-1].Filepath()\n\t\t\t\tvar f *os.File\n\t\t\t\tf, err = os.Open(msg)\n\t\t\t\tif err == nil {\n\t\t\t\t\tr := bufio.NewReader(f)\n\t\t\t\t\tinfo, err = f.Stat()\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\terr = p.c.PrintfLine(\"+OK %d octets\", info.Size())\n\t\t\t\t\t\tfor err == nil {\n\t\t\t\t\t\t\t\/\/ send line\n\t\t\t\t\t\t\tline, err = r.ReadString(10)\n\t\t\t\t\t\t\tif err == io.EOF {\n\t\t\t\t\t\t\t\terr = nil\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t} else if err == nil {\n\t\t\t\t\t\t\t\tline = strings.Trim(line, \"\\r\")\n\t\t\t\t\t\t\t\tline = strings.Trim(line, \"\\n\")\n\t\t\t\t\t\t\t\tif line == \".\" {\n\t\t\t\t\t\t\t\t\tline = \" .\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\/\/ send line\n\t\t\t\t\t\t\t\terr = p.c.PrintfLine(line)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\/\/ error\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tf.Close()\n\t\t\t\t\t\/\/ end\n\t\t\t\t\terr = p.c.PrintfLine(\".\")\n\t\t\t\t} else {\n\t\t\t\t\terr = p.Error(err.Error())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ invalid\n\t\t\t\terr = p.Error(\"bad message\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = p.Error(\"invalid syntax\")\n\t\t}\n\t\tbreak\n\tcase \"UIDL\":\n\t\tif len(parts) == 2 {\n\t\t\t\/\/ 1 message\n\t\t\tidx, err = strconv.Atoi(parts[1])\n\t\t\tif err == nil && (idx > 0 && idx <= len(p.msgs)) {\n\t\t\t\t\/\/ valid\n\t\t\t\terr = p.OK(parts[1] + \" \" + p.msgs[idx-1].Filename())\n\t\t\t} else {\n\t\t\t\t\/\/ invalid\n\t\t\t\terr = p.Error(\"bad message\")\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ all messages\n\t\t\tp.OK(\"\")\n\t\t\tdw := p.c.DotWriter()\n\t\t\tfor idx, msg := range p.msgs {\n\t\t\t\tfmt.Fprintf(dw, \"%d %s\\r\\n\", idx, msg.Filename())\n\t\t\t}\n\t\t\t\/\/ FLUSH :D\n\t\t\terr = dw.Close()\n\t\t}\n\t\t\/\/ begin\n\t\tbreak\n\tcase \"STAT\":\n\t\t\/\/ begin\n\t\t_, err = p.c.W.WriteString(\"+OK \")\n\t\tif err == nil {\n\t\t\t\/\/ write list\n\t\t\tfor idx, _ := range p.msgs {\n\t\t\t\t_, err = fmt.Fprintf(p.c.W, \"%d \", 1+idx)\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif err == nil {\n\t\t\t\/\/ done writing list\n\t\t\terr = p.c.PrintfLine(\"\")\n\t\t} else {\n\t\t\terr = p.Error(err.Error())\n\t\t}\n\t\tbreak\n\tcase \"LIST\":\n\t\tif len(parts) == 2 {\n\t\t\t\/\/ 1 message\n\t\t\tidx, err = strconv.Atoi(parts[1])\n\t\t\tif err == nil {\n\t\t\t\tif idx > 0 && idx <= len(p.msgs) {\n\t\t\t\t\tinfo, err = os.Stat(p.msgs[idx-1].Filepath())\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\terr = p.c.PrintfLine(\"+OK %d %d\", idx, info.Size())\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ no existing message\n\t\t\t\t\terr = p.Error(\"no such message\")\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ all messages\n\t\t\terr = p.c.PrintfLine(\"+OK %d messages (%d octets)\", len(p.msgs), p.octs)\n\t\t\tif err == nil {\n\t\t\t\tdw := p.c.DotWriter()\n\t\t\t\tfor i, msg := range p.msgs {\n\t\t\t\t\tinfo, err = os.Stat(msg.Filepath())\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\t\/\/ write out entry\n\t\t\t\t\t\tfmt.Fprintf(dw, \"%d %d\\r\\n\", i+1, info.Size())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Errorf(\"error in pop3, stat(): %s\", err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ FLUSH IT !!! :-DDDDD\n\t\t\t\terr = dw.Close()\n\t\t\t}\n\t\t}\n\t\tbreak\n\tdefault:\n\t\terr = p.Error(\"bad command\")\n\t}\n\treturn\n}\n\n\/\/ handle 1 line of input when not in transaction mode\nfunc (p *pop3Session) handleLine(line string) (err error) {\n\tparts := strings.Split(line, \" \")\n\tcmd := strings.ToUpper(parts[0])\n\tswitch cmd {\n\tcase \"NOOP\":\n\t\terr = p.OK(\"\")\n\t\tbreak\n\tcase \"APOP\":\n\t\tif len(parts) == 3 {\n\t\t\tif p.s.checkDigest(parts[1], parts[2]) {\n\t\t\t\t\/\/ load messages\n\t\t\t\tp.msgs, p.octs, err = p.s.obtainMessages(p.user)\n\t\t\t\tif err == nil {\n\t\t\t\t\terr = p.OK(\"maildrop is go for access\")\n\t\t\t\t\tp.transaction = err == nil\n\t\t\t\t} else {\n\t\t\t\t\terr = p.Error(err.Error())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr = p.Error(\"permission denied\")\n\t\t\t}\n\t\t} else {\n\t\t\terr = p.Error(\"Bad APOP\")\n\t\t}\n\t\tbreak\n\tcase \"PASS\":\n\t\tif p.s.checkUser(p.user, line[5:]) {\n\t\t\tp.msgs, p.octs, err = p.s.obtainMessages(p.user)\n\t\t\tif err == nil {\n\t\t\t\terr = p.c.PrintfLine(\"+OK %s maildrop logged in, you have %d messages (%d octets)\", p.user, len(p.msgs), p.octs)\n\t\t\t\tp.transaction = err == nil\n\t\t\t} else {\n\t\t\t\terr = p.Error(err.Error())\n\t\t\t}\n\t\t} else {\n\t\t\terr = p.Error(\"bad login\")\n\t\t}\n\t\tbreak\n\tcase \"USER\":\n\t\tif len(parts) > 1 {\n\t\t\tp.user = line[5:]\n\t\t}\n\t\terr = p.OK(\"anonymous access enabled\")\n\t\tbreak\n\tdefault:\n\t\terr = p.Error(\"bad command\")\n\t}\n\treturn\n}\n\nfunc (p *pop3Session) OK(msg string) (err error) {\n\tif len(msg) == 0 {\n\t\terr = p.c.PrintfLine(\"+OK\")\n\t} else {\n\t\terr = p.c.PrintfLine(\"+OK %s\", msg)\n\t}\n\treturn\n}\n\n\/\/ send error\nfunc (p *pop3Session) Error(msg string) (err error) {\n\terr = p.c.PrintfLine(\"-ERR %s\", msg)\n\treturn\n}\n\n\/\/ serve sessions with connections accepted from a net.Listener\nfunc (s *Server) Serve(l net.Listener) (err error) {\n\tfor err == nil {\n\t\tvar c net.Conn\n\t\tc, err = l.Accept()\n\t\tif err == nil {\n\t\t\tp := &pop3Session{\n\t\t\t\tc: textproto.NewConn(c),\n\t\t\t\ts: s,\n\t\t\t}\n\t\t\tgo p.Run()\n\t\t}\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package edict implements a parser for the EDICT2 Japanese\/English dictionary.\npackage edict\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ Gloss encodes an English definition for a Japanese word.\ntype Gloss struct {\n\tDefinition  string   \/\/ English translation.\n\tInformation []Detail \/\/ Information about this particular definition.\n\tXref        []string \/\/ Xref to related entries (to the Kanji key), \"see also\".\n}\n\n\/\/ Entry encodes a line of edict2 input.\ntype Entry struct {\n\tKanji              []string \/\/ Kanji key.\n\tKana               []string \/\/ Kana transcription of keys.\n\tInformation        []Detail \/\/ Information about the word; part of speech, conjugation type, etc.\n\tGloss              []Gloss  \/\/ The \"glosses\", English definitions, ordered by frequency.\n\tSequence           string   \/\/ The entry's unique identifier.\n\tRecordingAvailable bool     \/\/ True if an audio clip of the entry reading is available from the JapanesePod101.com site.\n}\n\n\/\/ String formats an Entry as a single line; not in the edict2 format, but familiar enough.\nfunc (e Entry) String() string {\n\trecording := \"\"\n\tif e.RecordingAvailable {\n\t\trecording = \"X\"\n\t}\n\n\treturn fmt.Sprintf(\"%v %v \/%v %v\/%s%s\/\", e.Kanji, e.Kana, e.Information, e.Gloss, e.Sequence, recording)\n}\n\n\/\/ These lines contain the record separator as part of the entry, making the whole thing\n\/\/ signficantly more difficult to parse.  We'll skip these for now, and I'll patch the dictionary to\n\/\/ not do this :)\nvar blacklist = []int{31179, 104168, 104171}\n\nfunc Parse(in io.Reader) ([]Entry, error) {\n\tresult := []Entry{}\n\tscanner := bufio.NewScanner(in)\n\tline := 0\nlines:\n\tfor scanner.Scan() {\n\t\tline++\n\t\tentry, err := parseLine(scanner.Text())\n\t\tif err != nil {\n\t\t\tfor _, knownBadLine := range blacklist {\n\t\t\t\tif knownBadLine == line {\n\t\t\t\t\tcontinue lines\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result, fmt.Errorf(\"parse: line %d: %s\", line, err)\n\t\t}\n\t\tresult = append(result, entry)\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn result, fmt.Errorf(\"parse: past EOF (line %d): %s\", line, err)\n\t}\n\n\treturn result, nil\n}\n\n\/\/ Regular expressions for parsing entry lines.\nvar (\n\t\/\/ TODO(jrockway): kanji field is optional, according to the docs.  Key part looks like\n\t\/\/ \"key1;key2;... [reading1;reading2;...] \" (note the space at the end)\n\tparseKeys = regexp.MustCompile(`^([^[:space:]]+) \\[([^\\]]+)\\] `)\n)\n\ntype parseGlossState int\n\nconst (\n\tstart parseGlossState = iota\n\tcapture\n\tclosed\n\tdefinition\n)\n\nfunc parseIdentifier(s string) (*Detail, *string, *string) {\n\tif _, err := strconv.Atoi(s); err == nil {\n\t\treturn nil, nil, nil\n\t} else if strings.HasPrefix(s, \"See \") {\n\t\tword := strings.TrimPrefix(s, \"See \")\n\t\treturn nil, &word, nil\n\t} else if detail, ok := DetailFor[s]; ok {\n\t\treturn &detail, nil, nil\n\t} else {\n\t\treturn nil, nil, &s\n\t}\n}\n\nfunc parseGloss(gloss string) (def string, details []Detail, xrefs []string, err error) {\n\tgloss = strings.TrimSpace(gloss)\n\n\t\/\/ This is the state machine for parsing the gloss.  We start in the start state, looking\n\t\/\/ for a ( starting an identifier, or the start of a definition (anything other than an\n\t\/\/ opening paren).  Upon seeing a ( we transition to capture, capturing everything that's\n\t\/\/ not a ).  Upon reaching the ), we then transition to closed.  In the closed state, we\n\t\/\/ look for a space, and finding it, transition to start.  At the end of the loop, we must\n\t\/\/ be in the definition-capture state.  If not, we raise an error.\n\tstate := start\n\tcaptured := []rune{}\n\tdefcapture := []rune{}\n\n\tfor idx, c := range gloss {\n\t\tswitch state {\n\t\tcase start:\n\t\t\tif c == '(' {\n\t\t\t\tstate = capture\n\t\t\t} else {\n\t\t\t\tstate = definition\n\t\t\t\tdefcapture = append(defcapture, c)\n\t\t\t}\n\t\tcase definition:\n\t\t\tdefcapture = append(defcapture, c)\n\t\tcase capture:\n\t\t\tif c == ')' {\n\t\t\t\tstate = closed\n\t\t\t\td, x, u := parseIdentifier(string(captured))\n\n\t\t\t\tif d != nil {\n\t\t\t\t\tdetails = append(details, *d)\n\t\t\t\t} else if x != nil {\n\t\t\t\t\txrefs = append(xrefs, *x)\n\t\t\t\t} else if u != nil {\n\t\t\t\t\tdefcapture = append(defcapture, '(')\n\t\t\t\t\tfor _, c := range captured {\n\t\t\t\t\t\tdefcapture = append(defcapture, c)\n\t\t\t\t\t}\n\t\t\t\t\tdefcapture = append(defcapture, ')')\n\t\t\t\t\tstate = definition\n\t\t\t\t}\n\t\t\t\tcaptured = []rune{}\n\t\t\t} else {\n\t\t\t\tcaptured = append(captured, c)\n\t\t\t}\n\t\tcase closed:\n\t\t\tif c == ' ' {\n\t\t\t\tstate = start\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"unexpected '%c' while in closed state (expecting space)\", c)\n\t\t\t}\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"in unexpected state %v at byte %d '%c'\", state, idx, c)\n\t\t}\n\t}\n\n\tif state != definition {\n\t\terr = fmt.Errorf(\"not in definition state after parsing:\\ndetails=%v, xref=%v, def=%s\", details, xrefs, def)\n\t\treturn\n\t}\n\n\tdef = string(defcapture)\n\n\treturn\n}\n\nfunc parseLine(line string) (Entry, error) {\n\tresult := Entry{}\n\tparts := strings.Split(line, \"\/\")\n\tlast := parts[len(parts)-1]\n\tif last != \"\" {\n\t\treturn result, fmt.Errorf(\"parseLine: last component should be blank, but is %s\", last)\n\t}\n\n\t\/\/ Parse the sequence number part, since having this in the result makes misparsing lines\n\t\/\/ easier to grep for.\n\tresult.Sequence = parts[len(parts)-2]\n\tif strings.HasSuffix(result.Sequence, \"X\") {\n\t\tresult.RecordingAvailable = true\n\t\tresult.Sequence = strings.TrimSuffix(result.Sequence, \"X\")\n\t}\n\tresult.Sequence = seqParts[1]\n\n\t\/\/ Parse the first part into Kanji\/Kana fields.\n\tkey := parts[0]\n\tkeyParts := parseKeys.FindStringSubmatch(key)\n\tif len(keyParts) == 0 {\n\t\tresult.Kanji = strings.Split(key, \";\")\n\t} else if keyParts[0] != key || len(keyParts) != 3 {\n\t\treturn result, fmt.Errorf(\"incomplete match on key '%s':\\n got '%v'\", key, keyParts)\n\t} else {\n\t\tresult.Kanji = strings.Split(keyParts[1], \";\")\n\t\tresult.Kana = strings.Split(keyParts[2], \";\")\n\t}\n\n\t\/\/ Next we get some details from the first gloss.\n\tglosses := []string{parts[1]}\n\n\tif len(parts) > 4 {\n\t\t\/\/ If there's more than one gloss, the entry-wide details come before the (1)\n\t\t\/\/ marker.\n\t\tfirstGlossParts := strings.Split(parts[1], \"(1)\")\n\t\tif len(firstGlossParts) == 2 {\n\t\t\t_, detail, xref, err := parseGloss(firstGlossParts[0] + \"fake definition\")\n\t\t\tif err != nil {\n\t\t\t\treturn result, fmt.Errorf(\"parsing entry details: %s\", err)\n\t\t\t}\n\t\t\tif len(xref) != 0 {\n\t\t\t\treturn result, fmt.Errorf(\"unexpected xref in global details section\")\n\t\t\t}\n\t\t\tresult.Information = detail\n\t\t\tglosses[0] = firstGlossParts[1]\n\t\t}\n\t}\n\n\t\/\/ We already have the first gloss in glosses, add the rest here.\n\tif len(parts) > 4 {\n\t\tfor _, gloss := range parts[2 : len(parts)-2] {\n\t\t\tglosses = append(glosses, gloss)\n\t\t}\n\t}\n\n\tresult.Gloss = []Gloss{}\n\tfor _, gloss := range glosses {\n\t\tif gloss == \"(P)\" { \/\/ what a terrible file format\n\t\t\tresult.Information = append(result.Information, Common)\n\t\t\tcontinue\n\t\t}\n\n\t\tdef, detail, xref, err := parseGloss(gloss)\n\t\tif err != nil {\n\t\t\treturn result, fmt.Errorf(\"parsing gloss %s got err %s\", gloss, err)\n\t\t}\n\t\tresult.Gloss = append(result.Gloss, Gloss{def, detail, xref})\n\t}\n\n\t\/\/ In the event that there's only one gloss, transfer the details to the entry.\n\tif len(parts) <= 4 {\n\t\tresult.Information = result.Gloss[0].Information\n\t\tresult.Gloss[0].Information = []Detail{}\n\t}\n\n\treturn result, nil\n}\n<commit_msg>factor out parseKey, for possible future speedups<commit_after>\/\/ Package edict implements a parser for the EDICT2 Japanese\/English dictionary.\npackage edict\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ Gloss encodes an English definition for a Japanese word.\ntype Gloss struct {\n\tDefinition  string   \/\/ English translation.\n\tInformation []Detail \/\/ Information about this particular definition.\n\tXref        []string \/\/ Xref to related entries (to the Kanji key), \"see also\".\n}\n\n\/\/ Entry encodes a line of edict2 input.\ntype Entry struct {\n\tKanji              []string \/\/ Kanji key.\n\tKana               []string \/\/ Kana transcription of keys.\n\tInformation        []Detail \/\/ Information about the word; part of speech, conjugation type, etc.\n\tGloss              []Gloss  \/\/ The \"glosses\", English definitions, ordered by frequency.\n\tSequence           string   \/\/ The entry's unique identifier.\n\tRecordingAvailable bool     \/\/ True if an audio clip of the entry reading is available from the JapanesePod101.com site.\n}\n\n\/\/ String formats an Entry as a single line; not in the edict2 format, but familiar enough.\nfunc (e Entry) String() string {\n\trecording := \"\"\n\tif e.RecordingAvailable {\n\t\trecording = \"X\"\n\t}\n\n\treturn fmt.Sprintf(\"%v %v \/%v %v\/%s%s\/\", e.Kanji, e.Kana, e.Information, e.Gloss, e.Sequence, recording)\n}\n\n\/\/ These lines contain the record separator as part of the entry, making the whole thing\n\/\/ signficantly more difficult to parse.  We'll skip these for now, and I'll patch the dictionary to\n\/\/ not do this :)\nvar blacklist = []int{31179, 104168, 104171}\n\nfunc Parse(in io.Reader) ([]Entry, error) {\n\tresult := []Entry{}\n\tscanner := bufio.NewScanner(in)\n\tline := 0\nlines:\n\tfor scanner.Scan() {\n\t\tline++\n\t\tentry, err := parseLine(scanner.Text())\n\t\tif err != nil {\n\t\t\tfor _, knownBadLine := range blacklist {\n\t\t\t\tif knownBadLine == line {\n\t\t\t\t\tcontinue lines\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result, fmt.Errorf(\"parse: line %d: %s\", line, err)\n\t\t}\n\t\tresult = append(result, entry)\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn result, fmt.Errorf(\"parse: past EOF (line %d): %s\", line, err)\n\t}\n\n\treturn result, nil\n}\n\n\/\/ Regular expressions for parsing entry lines.\nvar (\n\t\/\/ TODO(jrockway): kanji field is optional, according to the docs.  Key part looks like\n\t\/\/ \"key1;key2;... [reading1;reading2;...] \" (note the space at the end)\n\tparseKeys = regexp.MustCompile(`^([^[:space:]]+) \\[([^\\]]+)\\] `)\n)\n\ntype parseGlossState int\n\nconst (\n\tstart parseGlossState = iota\n\tcapture\n\tclosed\n\tdefinition\n)\n\nfunc parseIdentifier(s string) (*Detail, *string, *string) {\n\tif _, err := strconv.Atoi(s); err == nil {\n\t\treturn nil, nil, nil\n\t} else if strings.HasPrefix(s, \"See \") {\n\t\tword := strings.TrimPrefix(s, \"See \")\n\t\treturn nil, &word, nil\n\t} else if detail, ok := DetailFor[s]; ok {\n\t\treturn &detail, nil, nil\n\t} else {\n\t\treturn nil, nil, &s\n\t}\n}\n\nfunc parseGloss(gloss string) (def string, details []Detail, xrefs []string, err error) {\n\tgloss = strings.TrimSpace(gloss)\n\n\t\/\/ This is the state machine for parsing the gloss.  We start in the start state, looking\n\t\/\/ for a ( starting an identifier, or the start of a definition (anything other than an\n\t\/\/ opening paren).  Upon seeing a ( we transition to capture, capturing everything that's\n\t\/\/ not a ).  Upon reaching the ), we then transition to closed.  In the closed state, we\n\t\/\/ look for a space, and finding it, transition to start.  At the end of the loop, we must\n\t\/\/ be in the definition-capture state.  If not, we raise an error.\n\tstate := start\n\tcaptured := []rune{}\n\tdefcapture := []rune{}\n\n\tfor idx, c := range gloss {\n\t\tswitch state {\n\t\tcase start:\n\t\t\tif c == '(' {\n\t\t\t\tstate = capture\n\t\t\t} else {\n\t\t\t\tstate = definition\n\t\t\t\tdefcapture = append(defcapture, c)\n\t\t\t}\n\t\tcase definition:\n\t\t\tdefcapture = append(defcapture, c)\n\t\tcase capture:\n\t\t\tif c == ')' {\n\t\t\t\tstate = closed\n\t\t\t\td, x, u := parseIdentifier(string(captured))\n\n\t\t\t\tif d != nil {\n\t\t\t\t\tdetails = append(details, *d)\n\t\t\t\t} else if x != nil {\n\t\t\t\t\txrefs = append(xrefs, *x)\n\t\t\t\t} else if u != nil {\n\t\t\t\t\tdefcapture = append(defcapture, '(')\n\t\t\t\t\tfor _, c := range captured {\n\t\t\t\t\t\tdefcapture = append(defcapture, c)\n\t\t\t\t\t}\n\t\t\t\t\tdefcapture = append(defcapture, ')')\n\t\t\t\t\tstate = definition\n\t\t\t\t}\n\t\t\t\tcaptured = []rune{}\n\t\t\t} else {\n\t\t\t\tcaptured = append(captured, c)\n\t\t\t}\n\t\tcase closed:\n\t\t\tif c == ' ' {\n\t\t\t\tstate = start\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"unexpected '%c' while in closed state (expecting space)\", c)\n\t\t\t}\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"in unexpected state %v at byte %d '%c'\", state, idx, c)\n\t\t}\n\t}\n\n\tif state != definition {\n\t\terr = fmt.Errorf(\"not in definition state after parsing:\\ndetails=%v, xref=%v, def=%s\", details, xrefs, def)\n\t\treturn\n\t}\n\n\tdef = string(defcapture)\n\n\treturn\n}\n\nfunc parseKey(key string) (kanji []string, kana []string, err error) {\n\t\/\/ Parse the first part into Kanji\/Kana fields.\n\tkeyParts := parseKeys.FindStringSubmatch(key)\n\tif len(keyParts) == 0 {\n\t\tkanji = strings.Split(key, \";\")\n\t} else if keyParts[0] != key || len(keyParts) != 3 {\n\t\terr = fmt.Errorf(\"incomplete match on key '%s':\\n got '%v'\", key, keyParts)\n\t\treturn\n\t} else {\n\t\tkanji = strings.Split(keyParts[1], \";\")\n\t\tkana = strings.Split(keyParts[2], \";\")\n\t}\n\treturn\n}\n\nfunc parseLine(line string) (Entry, error) {\n\tresult := Entry{}\n\tparts := strings.Split(line, \"\/\")\n\tlast := parts[len(parts)-1]\n\tif last != \"\" {\n\t\treturn result, fmt.Errorf(\"parseLine: last component should be blank, but is %s\", last)\n\t}\n\n\t\/\/ Parse the sequence number part, since having this in the result makes misparsing lines\n\t\/\/ easier to grep for.\n\tresult.Sequence = parts[len(parts)-2]\n\tif strings.HasSuffix(result.Sequence, \"X\") {\n\t\tresult.RecordingAvailable = true\n\t\tresult.Sequence = strings.TrimSuffix(result.Sequence, \"X\")\n\t}\n\n\tvar err error;\n\tresult.Kanji, result.Kana, err = parseKey(parts[0])\n\tif err != nil {\n\t\treturn result, err\n\t}\n\n\t\/\/ Next we get some details from the first gloss.\n\tglosses := []string{parts[1]}\n\n\tif len(parts) > 4 {\n\t\t\/\/ If there's more than one gloss, the entry-wide details come before the (1)\n\t\t\/\/ marker.\n\t\tfirstGlossParts := strings.Split(parts[1], \"(1)\")\n\t\tif len(firstGlossParts) == 2 {\n\t\t\t_, detail, xref, err := parseGloss(firstGlossParts[0] + \"fake definition\")\n\t\t\tif err != nil {\n\t\t\t\treturn result, fmt.Errorf(\"parsing entry details: %s\", err)\n\t\t\t}\n\t\t\tif len(xref) != 0 {\n\t\t\t\treturn result, fmt.Errorf(\"unexpected xref in global details section\")\n\t\t\t}\n\t\t\tresult.Information = detail\n\t\t\tglosses[0] = firstGlossParts[1]\n\t\t}\n\t}\n\n\t\/\/ We already have the first gloss in glosses, add the rest here.\n\tif len(parts) > 4 {\n\t\tfor _, gloss := range parts[2 : len(parts)-2] {\n\t\t\tglosses = append(glosses, gloss)\n\t\t}\n\t}\n\n\tresult.Gloss = []Gloss{}\n\tfor _, gloss := range glosses {\n\t\tif gloss == \"(P)\" { \/\/ what a terrible file format\n\t\t\tresult.Information = append(result.Information, Common)\n\t\t\tcontinue\n\t\t}\n\n\t\tdef, detail, xref, err := parseGloss(gloss)\n\t\tif err != nil {\n\t\t\treturn result, fmt.Errorf(\"parsing gloss %s got err %s\", gloss, err)\n\t\t}\n\t\tresult.Gloss = append(result.Gloss, Gloss{def, detail, xref})\n\t}\n\n\t\/\/ In the event that there's only one gloss, transfer the details to the entry.\n\tif len(parts) <= 4 {\n\t\tresult.Information = result.Gloss[0].Information\n\t\tresult.Gloss[0].Information = []Detail{}\n\t}\n\n\treturn result, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Hello is a trivial example of a main package.\npackage main\n\nimport (\n\t\"fmt\"\n\n\t\"code.google.com\/p\/go.example\/newmath\"\n)\n\nfunc main() {\n\tfmt.Printf(\"Hello, world.  Sqrt(2) = %v\\n\", newmath.Sqrt(2))\n}\n<commit_msg>Update hello.go<commit_after>\/\/ Copyright 2011 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Hello is a trivial example of a main package.\npackage main\n\nimport (\n\t\"fmt\"\n\n\t\/\/\"code.google.com\/p\/go.example\/newmath\"\n\t\n\t\"newmath\"\n)\n\nfunc main() {\n\tfmt.Printf(\"Hello, world.  Sqrt(2) = %v\\n\", newmath.Sqrt(2))\n}\n<|endoftext|>"}
{"text":"<commit_before>package helpers\n\nimport (\n\t\"github.com\/globalsign\/mgo\"\n\t\"github.com\/globalsign\/mgo\/bson\"\n\n\t\"reflect\"\n\n\t\"strings\"\n\n\t\"crypto\/tls\"\n\n\t\"net\"\n\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/Seklfreak\/Robyul2\/cache\"\n\t\"github.com\/Seklfreak\/Robyul2\/models\"\n\t\"github.com\/pkg\/errors\"\n)\n\nvar (\n\tmDbSession  *mgo.Session\n\tmDbDatabase string\n)\n\ntype mgoLogger struct {\n}\n\nfunc (mgol mgoLogger) Output(calldepth int, s string) error {\n\tcache.GetLogger().WithField(\"module\", \"mdb\").Info(s)\n\treturn nil\n}\n\n\/\/ ConnectDB connects to mongodb and stores the session\nfunc ConnectMDB(url string, database string) {\n\tvar err error\n\n\tlog := cache.GetLogger()\n\tlog.WithField(\"module\", \"mdb\").Info(\"Connecting to \" + url)\n\n\tmgoL := new(mgoLogger)\n\tmgo.SetLogger(mgoL)\n\n\tcache.GetLogger()\n\n\tnewUrl := strings.TrimSuffix(url, \"?ssl=true\")\n\tnewUrl = strings.Replace(newUrl, \"ssl=true&\", \"\", -1)\n\n\tdialInfo, err := mgo.ParseURL(newUrl)\n\tif err != nil {\n\t\tlog.WithField(\"module\", \"mdb\").Error(err.Error())\n\t\tpanic(err)\n\t}\n\n\t\/\/ setup TLS if we use SSL\n\tif newUrl != url {\n\t\ttlsConfig := &tls.Config{}\n\t\ttlsConfig.InsecureSkipVerify = true\n\n\t\tdialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {\n\t\t\tconn, err := tls.Dial(\"tcp\", addr.String(), tlsConfig)\n\t\t\treturn conn, err\n\t\t}\n\t}\n\n\tmDbSession, err = mgo.DialWithInfo(dialInfo)\n\tif err != nil {\n\t\tlog.WithField(\"module\", \"mdb\").Error(err.Error())\n\t\tpanic(err)\n\t}\n\n\tmDbSession.SetMode(mgo.Monotonic, true)\n\tmDbSession.SetSafe(&mgo.Safe{WMode: \"majority\"})\n\n\tmDbDatabase = database\n\n\tlog.WithField(\"module\", \"mdb\").Info(\"Connected!\")\n}\n\n\/\/ GetDB is a simple getter for the mongodb database.\nfunc GetMDb() *mgo.Database {\n\treturn mDbSession.DB(mDbDatabase)\n}\n\n\/\/ GetDB is a simple getter for the mongodb session.\nfunc GetMDbSession() *mgo.Session {\n\treturn mDbSession\n}\n\nfunc MDbInsert(collection models.MongoDbCollection, data interface{}) (rid bson.ObjectId, err error) {\n\tptr := reflect.New(reflect.TypeOf(data))\n\ttemp := ptr.Elem()\n\ttemp.Set(reflect.ValueOf(data))\n\n\tv := temp.FieldByName(\"ID\")\n\n\tif !v.IsValid() {\n\t\treturn bson.ObjectId(\"\"), errors.New(\"invalid data\")\n\t}\n\n\tnewID := v.String()\n\tif newID == \"\" {\n\t\tnewID = string(bson.NewObjectId())\n\t\tv.SetString(newID)\n\t}\n\n\tstart := time.Now()\n\terr = GetMDb().C(collection.String()).Insert(temp.Interface())\n\ttook := time.Since(start)\n\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"insert\",\n\t\t\t\tMethod:     \"MDbInsert()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(collection.String()),\n\t\t\t\tData:       fmt.Sprintf(\"%+v\", data),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\n\tif err != nil {\n\t\treturn bson.ObjectId(\"\"), err\n\t}\n\n\treturn bson.ObjectId(newID), nil\n}\n\nfunc MDbInsertWithoutLogging(collection models.MongoDbCollection, data interface{}) (rid bson.ObjectId, err error) {\n\tptr := reflect.New(reflect.TypeOf(data))\n\ttemp := ptr.Elem()\n\ttemp.Set(reflect.ValueOf(data))\n\n\tv := temp.FieldByName(\"ID\")\n\n\tif !v.IsValid() {\n\t\treturn bson.ObjectId(\"\"), errors.New(\"invalid data\")\n\t}\n\n\tnewID := v.String()\n\tif newID == \"\" {\n\t\tnewID = string(bson.NewObjectId())\n\t\tv.SetString(newID)\n\t}\n\n\terr = GetMDb().C(collection.String()).Insert(temp.Interface())\n\n\tif err != nil {\n\t\treturn bson.ObjectId(\"\"), err\n\t}\n\n\treturn bson.ObjectId(newID), nil\n}\n\nfunc MDbUpdate(collection models.MongoDbCollection, id bson.ObjectId, data interface{}) (rid bson.ObjectId, err error) {\n\tif !id.Valid() {\n\t\treturn bson.ObjectId(\"\"), errors.New(\"invalid id\")\n\t}\n\n\tstart := time.Now()\n\terr = GetMDb().C(collection.String()).UpdateId(id, data)\n\ttook := time.Since(start)\n\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"update\",\n\t\t\t\tMethod:     \"MDbUpdate()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(collection.String()),\n\t\t\t\tId:         id.String(),\n\t\t\t\tData:       fmt.Sprintf(\"%+v\", data),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\n\tif err != nil {\n\t\treturn bson.ObjectId(\"\"), err\n\t}\n\n\treturn id, nil\n}\n\nfunc MDbUpdateWithoutLogging(collection models.MongoDbCollection, id bson.ObjectId, data interface{}) (rid bson.ObjectId, err error) {\n\tif !id.Valid() {\n\t\treturn bson.ObjectId(\"\"), errors.New(\"invalid id\")\n\t}\n\n\terr = GetMDb().C(collection.String()).UpdateId(id, data)\n\n\tif err != nil {\n\t\treturn bson.ObjectId(\"\"), err\n\t}\n\n\treturn id, nil\n}\n\nfunc MDbUpsertID(collection models.MongoDbCollection, id bson.ObjectId, data interface{}) (err error) {\n\tif !id.Valid() {\n\t\treturn errors.New(\"invalid id\")\n\t}\n\n\tstart := time.Now()\n\t_, err = GetMDb().C(collection.String()).UpsertId(id, data)\n\ttook := time.Since(start)\n\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"upsert\",\n\t\t\t\tMethod:     \"MDbUpsertID()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(collection.String()),\n\t\t\t\tId:         id.String(),\n\t\t\t\tData:       fmt.Sprintf(\"%+v\", data),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc MDbUpsert(collection models.MongoDbCollection, selector interface{}, data interface{}) (err error) {\n\tstart := time.Now()\n\t_, err = GetMDb().C(collection.String()).Upsert(selector, data)\n\ttook := time.Since(start)\n\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"upsert\",\n\t\t\t\tMethod:     \"MDbUpsert()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(collection.String()),\n\t\t\t\tQuery:      fmt.Sprintf(\"%+v\", selector),\n\t\t\t\tData:       fmt.Sprintf(\"%+v\", data),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn err\n}\n\nfunc MDbDelete(collection models.MongoDbCollection, id bson.ObjectId) (err error) {\n\tif !id.Valid() {\n\t\treturn errors.New(\"invalid id\")\n\t}\n\n\tstart := time.Now()\n\terr = GetMDb().C(collection.String()).RemoveId(id)\n\ttook := time.Since(start)\n\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"remove\",\n\t\t\t\tMethod:     \"MDbDelete()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(collection.String()),\n\t\t\t\tId:         id.String(),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc MdbCollection(collection models.MongoDbCollection) (query *mgo.Collection) {\n\treturn GetMDb().C(collection.String())\n}\n\nfunc MDbIter(query *mgo.Query) (iter *mgo.Iter) {\n\tstart := time.Now()\n\titer = query.Iter()\n\ttook := time.Since(start)\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\tqueryValue := reflect.ValueOf(*query)\n\t\t\tqueryOp := queryValue.FieldByName(\"query\").FieldByName(\"op\")\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"query\",\n\t\t\t\tMethod:     \"MdbIter()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(queryOp.FieldByName(\"collection\").String()),\n\t\t\t\tQuery:      fmt.Sprintf(\"%+v\", reflect.ValueOf(queryOp.FieldByName(\"query\")).Interface()),\n\t\t\t\tSkip:       queryOp.FieldByName(\"skip\").Int(),\n\t\t\t\tLimit:      queryOp.FieldByName(\"limit\").Int(),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\treturn\n}\n\nfunc MdbOne(query *mgo.Query, object interface{}) (err error) {\n\tstart := time.Now()\n\terr = query.One(object)\n\ttook := time.Since(start)\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\tqueryValue := reflect.ValueOf(*query)\n\t\t\tqueryOp := queryValue.FieldByName(\"query\").FieldByName(\"op\")\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"query\",\n\t\t\t\tMethod:     \"MdbOne()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(queryOp.FieldByName(\"collection\").String()),\n\t\t\t\tQuery:      fmt.Sprintf(\"%+v\", reflect.ValueOf(queryOp.FieldByName(\"query\")).Interface()),\n\t\t\t\tSkip:       queryOp.FieldByName(\"skip\").Int(),\n\t\t\t\tLimit:      queryOp.FieldByName(\"limit\").Int(),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\treturn\n}\n\nfunc MdbOneWithoutLogging(query *mgo.Query, object interface{}) (err error) {\n\terr = query.One(object)\n\treturn\n}\n\n\/\/ Returns a human readable ID version of a ObjectID\n\/\/ id\t: the ObjectID to convert\nfunc MdbIdToHuman(id bson.ObjectId) (text string) {\n\treturn fmt.Sprintf(`%x`, string(id))\n}\n\n\/\/ Returns an ObjectID from a human readable ID\n\/\/ text\t: the human readable ID\nfunc HumanToMdbId(text string) (id bson.ObjectId) {\n\treturn bson.ObjectIdHex(text)\n}\n\nfunc stripRobyulDatabaseFromCollection(input string) (output string) {\n\treturn strings.TrimPrefix(input, mDbDatabase+\".\")\n}\n\ntype KeenMongoDbEvent struct {\n\tSeconds    float64\n\tCollection string\n\tType       string\n\tMethod     string\n\tQuery      string `json:\",omitempty\"`\n\tSkip       int64  `json:\",omitempty\"`\n\tLimit      int64  `json:\",omitempty\"`\n\tId         string `json:\",omitempty\"`\n\tData       string `json:\",omitempty\"`\n}\n<commit_msg>[mdb] improves keen logging 👀<commit_after>package helpers\n\nimport (\n\t\"github.com\/globalsign\/mgo\"\n\t\"github.com\/globalsign\/mgo\/bson\"\n\n\t\"reflect\"\n\n\t\"strings\"\n\n\t\"crypto\/tls\"\n\n\t\"net\"\n\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/Seklfreak\/Robyul2\/cache\"\n\t\"github.com\/Seklfreak\/Robyul2\/models\"\n\t\"github.com\/pkg\/errors\"\n)\n\nvar (\n\tmDbSession  *mgo.Session\n\tmDbDatabase string\n)\n\ntype mgoLogger struct {\n}\n\nfunc (mgol mgoLogger) Output(calldepth int, s string) error {\n\tcache.GetLogger().WithField(\"module\", \"mdb\").Info(s)\n\treturn nil\n}\n\n\/\/ ConnectDB connects to mongodb and stores the session\nfunc ConnectMDB(url string, database string) {\n\tvar err error\n\n\tlog := cache.GetLogger()\n\tlog.WithField(\"module\", \"mdb\").Info(\"Connecting to \" + url)\n\n\tmgoL := new(mgoLogger)\n\tmgo.SetLogger(mgoL)\n\n\tcache.GetLogger()\n\n\tnewUrl := strings.TrimSuffix(url, \"?ssl=true\")\n\tnewUrl = strings.Replace(newUrl, \"ssl=true&\", \"\", -1)\n\n\tdialInfo, err := mgo.ParseURL(newUrl)\n\tif err != nil {\n\t\tlog.WithField(\"module\", \"mdb\").Error(err.Error())\n\t\tpanic(err)\n\t}\n\n\t\/\/ setup TLS if we use SSL\n\tif newUrl != url {\n\t\ttlsConfig := &tls.Config{}\n\t\ttlsConfig.InsecureSkipVerify = true\n\n\t\tdialInfo.DialServer = func(addr *mgo.ServerAddr) (net.Conn, error) {\n\t\t\tconn, err := tls.Dial(\"tcp\", addr.String(), tlsConfig)\n\t\t\treturn conn, err\n\t\t}\n\t}\n\n\tmDbSession, err = mgo.DialWithInfo(dialInfo)\n\tif err != nil {\n\t\tlog.WithField(\"module\", \"mdb\").Error(err.Error())\n\t\tpanic(err)\n\t}\n\n\tmDbSession.SetMode(mgo.Monotonic, true)\n\tmDbSession.SetSafe(&mgo.Safe{WMode: \"majority\"})\n\n\tmDbDatabase = database\n\n\tlog.WithField(\"module\", \"mdb\").Info(\"Connected!\")\n}\n\n\/\/ GetDB is a simple getter for the mongodb database.\nfunc GetMDb() *mgo.Database {\n\treturn mDbSession.DB(mDbDatabase)\n}\n\n\/\/ GetDB is a simple getter for the mongodb session.\nfunc GetMDbSession() *mgo.Session {\n\treturn mDbSession\n}\n\nfunc MDbInsert(collection models.MongoDbCollection, data interface{}) (rid bson.ObjectId, err error) {\n\tptr := reflect.New(reflect.TypeOf(data))\n\ttemp := ptr.Elem()\n\ttemp.Set(reflect.ValueOf(data))\n\n\tv := temp.FieldByName(\"ID\")\n\n\tif !v.IsValid() {\n\t\treturn bson.ObjectId(\"\"), errors.New(\"invalid data\")\n\t}\n\n\tnewID := v.String()\n\tif newID == \"\" {\n\t\tnewID = string(bson.NewObjectId())\n\t\tv.SetString(newID)\n\t}\n\n\tstart := time.Now()\n\terr = GetMDb().C(collection.String()).Insert(temp.Interface())\n\ttook := time.Since(start)\n\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"insert\",\n\t\t\t\tMethod:     \"MDbInsert()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(collection.String()),\n\t\t\t\tData:       fmt.Sprintf(\"%+v\", data),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\n\tif err != nil {\n\t\treturn bson.ObjectId(\"\"), err\n\t}\n\n\treturn bson.ObjectId(newID), nil\n}\n\nfunc MDbInsertWithoutLogging(collection models.MongoDbCollection, data interface{}) (rid bson.ObjectId, err error) {\n\tptr := reflect.New(reflect.TypeOf(data))\n\ttemp := ptr.Elem()\n\ttemp.Set(reflect.ValueOf(data))\n\n\tv := temp.FieldByName(\"ID\")\n\n\tif !v.IsValid() {\n\t\treturn bson.ObjectId(\"\"), errors.New(\"invalid data\")\n\t}\n\n\tnewID := v.String()\n\tif newID == \"\" {\n\t\tnewID = string(bson.NewObjectId())\n\t\tv.SetString(newID)\n\t}\n\n\terr = GetMDb().C(collection.String()).Insert(temp.Interface())\n\n\tif err != nil {\n\t\treturn bson.ObjectId(\"\"), err\n\t}\n\n\treturn bson.ObjectId(newID), nil\n}\n\nfunc MDbUpdate(collection models.MongoDbCollection, id bson.ObjectId, data interface{}) (rid bson.ObjectId, err error) {\n\tif !id.Valid() {\n\t\treturn bson.ObjectId(\"\"), errors.New(\"invalid id\")\n\t}\n\n\tstart := time.Now()\n\terr = GetMDb().C(collection.String()).UpdateId(id, data)\n\ttook := time.Since(start)\n\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"update\",\n\t\t\t\tMethod:     \"MDbUpdate()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(collection.String()),\n\t\t\t\tId:         MdbIdToHuman(id),\n\t\t\t\tData:       fmt.Sprintf(\"%+v\", data),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\n\tif err != nil {\n\t\treturn bson.ObjectId(\"\"), err\n\t}\n\n\treturn id, nil\n}\n\nfunc MDbUpdateWithoutLogging(collection models.MongoDbCollection, id bson.ObjectId, data interface{}) (rid bson.ObjectId, err error) {\n\tif !id.Valid() {\n\t\treturn bson.ObjectId(\"\"), errors.New(\"invalid id\")\n\t}\n\n\terr = GetMDb().C(collection.String()).UpdateId(id, data)\n\n\tif err != nil {\n\t\treturn bson.ObjectId(\"\"), err\n\t}\n\n\treturn id, nil\n}\n\nfunc MDbUpsertID(collection models.MongoDbCollection, id bson.ObjectId, data interface{}) (err error) {\n\tif !id.Valid() {\n\t\treturn errors.New(\"invalid id\")\n\t}\n\n\tstart := time.Now()\n\t_, err = GetMDb().C(collection.String()).UpsertId(id, data)\n\ttook := time.Since(start)\n\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"upsert\",\n\t\t\t\tMethod:     \"MDbUpsertID()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(collection.String()),\n\t\t\t\tId:         MdbIdToHuman(id),\n\t\t\t\tData:       fmt.Sprintf(\"%+v\", data),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc MDbUpsert(collection models.MongoDbCollection, selector interface{}, data interface{}) (err error) {\n\tstart := time.Now()\n\t_, err = GetMDb().C(collection.String()).Upsert(selector, data)\n\ttook := time.Since(start)\n\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"upsert\",\n\t\t\t\tMethod:     \"MDbUpsert()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(collection.String()),\n\t\t\t\tQuery:      fmt.Sprintf(\"%+v\", selector),\n\t\t\t\tData:       fmt.Sprintf(\"%+v\", data),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\n\treturn err\n}\n\nfunc MDbDelete(collection models.MongoDbCollection, id bson.ObjectId) (err error) {\n\tif !id.Valid() {\n\t\treturn errors.New(\"invalid id\")\n\t}\n\n\tstart := time.Now()\n\terr = GetMDb().C(collection.String()).RemoveId(id)\n\ttook := time.Since(start)\n\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"remove\",\n\t\t\t\tMethod:     \"MDbDelete()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(collection.String()),\n\t\t\t\tId:         MdbIdToHuman(id),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc MdbCollection(collection models.MongoDbCollection) (query *mgo.Collection) {\n\treturn GetMDb().C(collection.String())\n}\n\nfunc MDbIter(query *mgo.Query) (iter *mgo.Iter) {\n\tstart := time.Now()\n\titer = query.Iter()\n\ttook := time.Since(start)\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\tqueryValue := reflect.ValueOf(*query)\n\t\t\tqueryOp := queryValue.FieldByName(\"query\").FieldByName(\"op\")\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"query\",\n\t\t\t\tMethod:     \"MdbIter()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(queryOp.FieldByName(\"collection\").String()),\n\t\t\t\tQuery:      fmt.Sprintf(\"%+v\", reflect.ValueOf(queryOp.FieldByName(\"query\")).Interface()),\n\t\t\t\tSkip:       queryOp.FieldByName(\"skip\").Int(),\n\t\t\t\tLimit:      queryOp.FieldByName(\"limit\").Int(),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\treturn\n}\n\nfunc MdbOne(query *mgo.Query, object interface{}) (err error) {\n\tstart := time.Now()\n\terr = query.One(object)\n\ttook := time.Since(start)\n\tif cache.HasKeen() {\n\t\tgo func() {\n\t\t\tdefer Recover()\n\n\t\t\tqueryValue := reflect.ValueOf(*query)\n\t\t\tqueryOp := queryValue.FieldByName(\"query\").FieldByName(\"op\")\n\n\t\t\terr := cache.GetKeen().AddEvent(\"Robyul_MongoDB\", &KeenMongoDbEvent{\n\t\t\t\tSeconds:    took.Seconds(),\n\t\t\t\tType:       \"query\",\n\t\t\t\tMethod:     \"MdbOne()\",\n\t\t\t\tCollection: stripRobyulDatabaseFromCollection(queryOp.FieldByName(\"collection\").String()),\n\t\t\t\tQuery:      fmt.Sprintf(\"%+v\", reflect.ValueOf(queryOp.FieldByName(\"query\")).Interface()),\n\t\t\t\tSkip:       queryOp.FieldByName(\"skip\").Int(),\n\t\t\t\tLimit:      queryOp.FieldByName(\"limit\").Int(),\n\t\t\t})\n\t\t\tif err != nil {\n\t\t\t\tcache.GetLogger().WithField(\"module\", \"mdb\").Error(\"Error logging MongoDB request to keen: \", err.Error())\n\t\t\t}\n\t\t}()\n\t}\n\treturn\n}\n\nfunc MdbOneWithoutLogging(query *mgo.Query, object interface{}) (err error) {\n\terr = query.One(object)\n\treturn\n}\n\n\/\/ Returns a human readable ID version of a ObjectID\n\/\/ id\t: the ObjectID to convert\nfunc MdbIdToHuman(id bson.ObjectId) (text string) {\n\treturn fmt.Sprintf(`%x`, string(id))\n}\n\n\/\/ Returns an ObjectID from a human readable ID\n\/\/ text\t: the human readable ID\nfunc HumanToMdbId(text string) (id bson.ObjectId) {\n\treturn bson.ObjectIdHex(text)\n}\n\nfunc stripRobyulDatabaseFromCollection(input string) (output string) {\n\treturn strings.TrimPrefix(input, mDbDatabase+\".\")\n}\n\ntype KeenMongoDbEvent struct {\n\tSeconds    float64\n\tCollection string\n\tType       string\n\tMethod     string\n\tQuery      string `json:\",omitempty\"`\n\tSkip       int64  `json:\",omitempty\"`\n\tLimit      int64  `json:\",omitempty\"`\n\tId         string `json:\",omitempty\"`\n\tData       string `json:\",omitempty\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package gocql\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype nodeState int32\n\nfunc (n nodeState) String() string {\n\tif n == NodeUp {\n\t\treturn \"UP\"\n\t} else if n == NodeDown {\n\t\treturn \"DOWN\"\n\t}\n\treturn fmt.Sprintf(\"UNKNOWN_%d\", n)\n}\n\nconst (\n\tNodeUp nodeState = iota\n\tNodeDown\n)\n\ntype cassVersion struct {\n\tMajor, Minor, Patch int\n}\n\nfunc (c *cassVersion) UnmarshalCQL(info TypeInfo, data []byte) error {\n\tv := strings.Split(string(data), \".\")\n\tif len(v) != 3 {\n\t\treturn fmt.Errorf(\"invalid schema_version: %v\", string(data))\n\t}\n\n\tvar err error\n\tc.Major, err = strconv.Atoi(v[0])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid major version %v: %v\", v[0], err)\n\t}\n\n\tc.Minor, err = strconv.Atoi(v[1])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid minor version %v: %v\", v[1], err)\n\t}\n\n\tc.Patch, err = strconv.Atoi(v[2])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid patch version %v: %v\", v[2], err)\n\t}\n\n\treturn nil\n}\n\nfunc (c cassVersion) String() string {\n\treturn fmt.Sprintf(\"v%d.%d.%d\", c.Major, c.Minor, c.Patch)\n}\n\nfunc (c cassVersion) nodeUpDelay() time.Duration {\n\tif c.Major >= 2 && c.Minor >= 2 {\n\t\t\/\/ CASSANDRA-8236\n\t\treturn 0\n\t}\n\n\treturn 10 * time.Second\n}\n\ntype HostInfo struct {\n\t\/\/ TODO(zariel): reduce locking maybe, not all values will change, but to ensure\n\t\/\/ that we are thread safe use a mutex to access all fields.\n\tmu         sync.RWMutex\n\tpeer       string\n\tport       int\n\tdataCenter string\n\track       string\n\thostId     string\n\tversion    cassVersion\n\tstate      nodeState\n\ttokens     []string\n}\n\nfunc (h *HostInfo) Equal(host *HostInfo) bool {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\thost.mu.RLock()\n\tdefer host.mu.RUnlock()\n\n\treturn h.peer == host.peer && h.hostId == host.hostId\n}\n\nfunc (h *HostInfo) Peer() string {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.peer\n}\n\nfunc (h *HostInfo) setPeer(peer string) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.peer = peer\n\treturn h\n}\n\nfunc (h *HostInfo) DataCenter() string {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.dataCenter\n}\n\nfunc (h *HostInfo) setDataCenter(dataCenter string) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.dataCenter = dataCenter\n\treturn h\n}\n\nfunc (h *HostInfo) Rack() string {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.rack\n}\n\nfunc (h *HostInfo) setRack(rack string) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.rack = rack\n\treturn h\n}\n\nfunc (h *HostInfo) HostID() string {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.hostId\n}\n\nfunc (h *HostInfo) setHostID(hostID string) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.hostId = hostID\n\treturn h\n}\n\nfunc (h *HostInfo) Version() cassVersion {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.version\n}\n\nfunc (h *HostInfo) setVersion(major, minor, patch int) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.version = cassVersion{major, minor, patch}\n\treturn h\n}\n\nfunc (h *HostInfo) State() nodeState {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.state\n}\n\nfunc (h *HostInfo) setState(state nodeState) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.state = state\n\treturn h\n}\n\nfunc (h *HostInfo) Tokens() []string {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.tokens\n}\n\nfunc (h *HostInfo) setTokens(tokens []string) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.tokens = tokens\n\treturn h\n}\n\nfunc (h *HostInfo) Port() int {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.port\n}\n\nfunc (h *HostInfo) setPort(port int) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.port = port\n\treturn h\n}\n\nfunc (h *HostInfo) update(from *HostInfo) {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\th.tokens = from.tokens\n\th.version = from.version\n\th.hostId = from.hostId\n\th.dataCenter = from.dataCenter\n}\n\nfunc (h *HostInfo) IsUp() bool {\n\treturn h.State() == NodeUp\n}\n\nfunc (h *HostInfo) String() string {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn fmt.Sprintf(\"[hostinfo peer=%q port=%d data_centre=%q rack=%q host_id=%q version=%q state=%s num_tokens=%d]\", h.peer, h.port, h.dataCenter, h.rack, h.hostId, h.version, h.state, len(h.tokens))\n}\n\n\/\/ Polls system.peers at a specific interval to find new hosts\ntype ringDescriber struct {\n\tdcFilter   string\n\trackFilter string\n\tsession    *Session\n\tcloseChan  chan bool\n\t\/\/ indicates that we can use system.local to get the connections remote address\n\tlocalHasRpcAddr bool\n\n\tmu              sync.Mutex\n\tprevHosts       []*HostInfo\n\tprevPartitioner string\n}\n\nfunc checkSystemLocal(control *controlConn) (bool, error) {\n\titer := control.query(\"SELECT broadcast_address FROM system.local\")\n\tif err := iter.err; err != nil {\n\t\tif errf, ok := err.(*errorFrame); ok {\n\t\t\tif errf.code == errSyntax {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}\n\nfunc (r *ringDescriber) GetHosts() (hosts []*HostInfo, partitioner string, err error) {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\t\/\/ we need conn to be the same because we need to query system.peers and system.local\n\t\/\/ on the same node to get the whole cluster\n\n\tconst (\n\t\tlegacyLocalQuery = \"SELECT data_center, rack, host_id, tokens, partitioner, release_version FROM system.local\"\n\t\t\/\/ only supported in 2.2.0, 2.1.6, 2.0.16\n\t\tlocalQuery = \"SELECT broadcast_address, data_center, rack, host_id, tokens, partitioner, release_version FROM system.local\"\n\t)\n\n\tlocalHost := &HostInfo{}\n\tif r.localHasRpcAddr {\n\t\titer := r.session.control.query(localQuery)\n\t\tif iter == nil {\n\t\t\treturn r.prevHosts, r.prevPartitioner, nil\n\t\t}\n\n\t\titer.Scan(&localHost.peer, &localHost.dataCenter, &localHost.rack,\n\t\t\t&localHost.hostId, &localHost.tokens, &partitioner, &localHost.version)\n\n\t\tif err = iter.Close(); err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t} else {\n\t\titer := r.session.control.query(legacyLocalQuery)\n\t\tif iter == nil {\n\t\t\treturn r.prevHosts, r.prevPartitioner, nil\n\t\t}\n\n\t\titer.Scan(&localHost.dataCenter, &localHost.rack, &localHost.hostId, &localHost.tokens, &partitioner, &localHost.version)\n\n\t\tif err = iter.Close(); err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\taddr, _, err := net.SplitHostPort(r.session.control.addr())\n\t\tif err != nil {\n\t\t\t\/\/ this should not happen, ever, as this is the address that was dialed by conn, here\n\t\t\t\/\/ a panic makes sense, please report a bug if it occurs.\n\t\t\tpanic(err)\n\t\t}\n\n\t\tlocalHost.peer = addr\n\t}\n\n\tlocalHost.port = r.session.cfg.Port\n\n\thosts = []*HostInfo{localHost}\n\n\titer := r.session.control.query(\"SELECT rpc_address, data_center, rack, host_id, tokens, release_version FROM system.peers\")\n\tif iter == nil {\n\t\treturn r.prevHosts, r.prevPartitioner, nil\n\t}\n\n\thost := &HostInfo{port: r.session.cfg.Port}\n\tfor iter.Scan(&host.peer, &host.dataCenter, &host.rack, &host.hostId, &host.tokens, &host.version) {\n\t\tif r.matchFilter(host) {\n\t\t\thosts = append(hosts, host)\n\t\t}\n\t\thost = &HostInfo{\n\t\t\tport: r.session.cfg.Port,\n\t\t}\n\t}\n\n\tif err = iter.Close(); err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tr.prevHosts = hosts\n\tr.prevPartitioner = partitioner\n\n\treturn hosts, partitioner, nil\n}\n\nfunc (r *ringDescriber) matchFilter(host *HostInfo) bool {\n\tif r.dcFilter != \"\" && r.dcFilter != host.DataCenter() {\n\t\treturn false\n\t}\n\n\tif r.rackFilter != \"\" && r.rackFilter != host.Rack() {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (r *ringDescriber) refreshRing() error {\n\t\/\/ if we have 0 hosts this will return the previous list of hosts to\n\t\/\/ attempt to reconnect to the cluster otherwise we would never find\n\t\/\/ downed hosts again, could possibly have an optimisation to only\n\t\/\/ try to add new hosts if GetHosts didnt error and the hosts didnt change.\n\thosts, partitioner, err := r.GetHosts()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ TODO: move this to session\n\t\/\/ TODO: handle removing hosts here\n\tfor _, h := range hosts {\n\t\tif host, ok := r.session.ring.addHostIfMissing(h); !ok {\n\t\t\tr.session.pool.addHost(h)\n\t\t} else {\n\t\t\thost.update(h)\n\t\t}\n\t}\n\n\tr.session.pool.SetPartitioner(partitioner)\n\treturn nil\n}\n<commit_msg>handle snapshot versions<commit_after>package gocql\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype nodeState int32\n\nfunc (n nodeState) String() string {\n\tif n == NodeUp {\n\t\treturn \"UP\"\n\t} else if n == NodeDown {\n\t\treturn \"DOWN\"\n\t}\n\treturn fmt.Sprintf(\"UNKNOWN_%d\", n)\n}\n\nconst (\n\tNodeUp nodeState = iota\n\tNodeDown\n)\n\ntype cassVersion struct {\n\tMajor, Minor, Patch int\n}\n\nfunc (c *cassVersion) UnmarshalCQL(info TypeInfo, data []byte) error {\n\tversion := strings.TrimSuffix(string(data), \"-SNAPSHOT\")\n\tv := strings.Split(version, \".\")\n\tif len(v) != 3 {\n\t\treturn fmt.Errorf(\"invalid schema_version: %v\", string(data))\n\t}\n\n\tvar err error\n\tc.Major, err = strconv.Atoi(v[0])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid major version %v: %v\", v[0], err)\n\t}\n\n\tc.Minor, err = strconv.Atoi(v[1])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid minor version %v: %v\", v[1], err)\n\t}\n\n\tc.Patch, err = strconv.Atoi(v[2])\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid patch version %v: %v\", v[2], err)\n\t}\n\n\treturn nil\n}\n\nfunc (c cassVersion) String() string {\n\treturn fmt.Sprintf(\"v%d.%d.%d\", c.Major, c.Minor, c.Patch)\n}\n\nfunc (c cassVersion) nodeUpDelay() time.Duration {\n\tif c.Major >= 2 && c.Minor >= 2 {\n\t\t\/\/ CASSANDRA-8236\n\t\treturn 0\n\t}\n\n\treturn 10 * time.Second\n}\n\ntype HostInfo struct {\n\t\/\/ TODO(zariel): reduce locking maybe, not all values will change, but to ensure\n\t\/\/ that we are thread safe use a mutex to access all fields.\n\tmu         sync.RWMutex\n\tpeer       string\n\tport       int\n\tdataCenter string\n\track       string\n\thostId     string\n\tversion    cassVersion\n\tstate      nodeState\n\ttokens     []string\n}\n\nfunc (h *HostInfo) Equal(host *HostInfo) bool {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\thost.mu.RLock()\n\tdefer host.mu.RUnlock()\n\n\treturn h.peer == host.peer && h.hostId == host.hostId\n}\n\nfunc (h *HostInfo) Peer() string {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.peer\n}\n\nfunc (h *HostInfo) setPeer(peer string) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.peer = peer\n\treturn h\n}\n\nfunc (h *HostInfo) DataCenter() string {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.dataCenter\n}\n\nfunc (h *HostInfo) setDataCenter(dataCenter string) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.dataCenter = dataCenter\n\treturn h\n}\n\nfunc (h *HostInfo) Rack() string {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.rack\n}\n\nfunc (h *HostInfo) setRack(rack string) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.rack = rack\n\treturn h\n}\n\nfunc (h *HostInfo) HostID() string {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.hostId\n}\n\nfunc (h *HostInfo) setHostID(hostID string) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.hostId = hostID\n\treturn h\n}\n\nfunc (h *HostInfo) Version() cassVersion {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.version\n}\n\nfunc (h *HostInfo) setVersion(major, minor, patch int) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.version = cassVersion{major, minor, patch}\n\treturn h\n}\n\nfunc (h *HostInfo) State() nodeState {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.state\n}\n\nfunc (h *HostInfo) setState(state nodeState) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.state = state\n\treturn h\n}\n\nfunc (h *HostInfo) Tokens() []string {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.tokens\n}\n\nfunc (h *HostInfo) setTokens(tokens []string) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.tokens = tokens\n\treturn h\n}\n\nfunc (h *HostInfo) Port() int {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn h.port\n}\n\nfunc (h *HostInfo) setPort(port int) *HostInfo {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\th.port = port\n\treturn h\n}\n\nfunc (h *HostInfo) update(from *HostInfo) {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\th.tokens = from.tokens\n\th.version = from.version\n\th.hostId = from.hostId\n\th.dataCenter = from.dataCenter\n}\n\nfunc (h *HostInfo) IsUp() bool {\n\treturn h.State() == NodeUp\n}\n\nfunc (h *HostInfo) String() string {\n\th.mu.RLock()\n\tdefer h.mu.RUnlock()\n\treturn fmt.Sprintf(\"[hostinfo peer=%q port=%d data_centre=%q rack=%q host_id=%q version=%q state=%s num_tokens=%d]\", h.peer, h.port, h.dataCenter, h.rack, h.hostId, h.version, h.state, len(h.tokens))\n}\n\n\/\/ Polls system.peers at a specific interval to find new hosts\ntype ringDescriber struct {\n\tdcFilter   string\n\trackFilter string\n\tsession    *Session\n\tcloseChan  chan bool\n\t\/\/ indicates that we can use system.local to get the connections remote address\n\tlocalHasRpcAddr bool\n\n\tmu              sync.Mutex\n\tprevHosts       []*HostInfo\n\tprevPartitioner string\n}\n\nfunc checkSystemLocal(control *controlConn) (bool, error) {\n\titer := control.query(\"SELECT broadcast_address FROM system.local\")\n\tif err := iter.err; err != nil {\n\t\tif errf, ok := err.(*errorFrame); ok {\n\t\t\tif errf.code == errSyntax {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t}\n\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}\n\nfunc (r *ringDescriber) GetHosts() (hosts []*HostInfo, partitioner string, err error) {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\t\/\/ we need conn to be the same because we need to query system.peers and system.local\n\t\/\/ on the same node to get the whole cluster\n\n\tconst (\n\t\tlegacyLocalQuery = \"SELECT data_center, rack, host_id, tokens, partitioner, release_version FROM system.local\"\n\t\t\/\/ only supported in 2.2.0, 2.1.6, 2.0.16\n\t\tlocalQuery = \"SELECT broadcast_address, data_center, rack, host_id, tokens, partitioner, release_version FROM system.local\"\n\t)\n\n\tlocalHost := &HostInfo{}\n\tif r.localHasRpcAddr {\n\t\titer := r.session.control.query(localQuery)\n\t\tif iter == nil {\n\t\t\treturn r.prevHosts, r.prevPartitioner, nil\n\t\t}\n\n\t\titer.Scan(&localHost.peer, &localHost.dataCenter, &localHost.rack,\n\t\t\t&localHost.hostId, &localHost.tokens, &partitioner, &localHost.version)\n\n\t\tif err = iter.Close(); err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t} else {\n\t\titer := r.session.control.query(legacyLocalQuery)\n\t\tif iter == nil {\n\t\t\treturn r.prevHosts, r.prevPartitioner, nil\n\t\t}\n\n\t\titer.Scan(&localHost.dataCenter, &localHost.rack, &localHost.hostId, &localHost.tokens, &partitioner, &localHost.version)\n\n\t\tif err = iter.Close(); err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\taddr, _, err := net.SplitHostPort(r.session.control.addr())\n\t\tif err != nil {\n\t\t\t\/\/ this should not happen, ever, as this is the address that was dialed by conn, here\n\t\t\t\/\/ a panic makes sense, please report a bug if it occurs.\n\t\t\tpanic(err)\n\t\t}\n\n\t\tlocalHost.peer = addr\n\t}\n\n\tlocalHost.port = r.session.cfg.Port\n\n\thosts = []*HostInfo{localHost}\n\n\titer := r.session.control.query(\"SELECT rpc_address, data_center, rack, host_id, tokens, release_version FROM system.peers\")\n\tif iter == nil {\n\t\treturn r.prevHosts, r.prevPartitioner, nil\n\t}\n\n\thost := &HostInfo{port: r.session.cfg.Port}\n\tfor iter.Scan(&host.peer, &host.dataCenter, &host.rack, &host.hostId, &host.tokens, &host.version) {\n\t\tif r.matchFilter(host) {\n\t\t\thosts = append(hosts, host)\n\t\t}\n\t\thost = &HostInfo{\n\t\t\tport: r.session.cfg.Port,\n\t\t}\n\t}\n\n\tif err = iter.Close(); err != nil {\n\t\treturn nil, \"\", err\n\t}\n\n\tr.prevHosts = hosts\n\tr.prevPartitioner = partitioner\n\n\treturn hosts, partitioner, nil\n}\n\nfunc (r *ringDescriber) matchFilter(host *HostInfo) bool {\n\tif r.dcFilter != \"\" && r.dcFilter != host.DataCenter() {\n\t\treturn false\n\t}\n\n\tif r.rackFilter != \"\" && r.rackFilter != host.Rack() {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (r *ringDescriber) refreshRing() error {\n\t\/\/ if we have 0 hosts this will return the previous list of hosts to\n\t\/\/ attempt to reconnect to the cluster otherwise we would never find\n\t\/\/ downed hosts again, could possibly have an optimisation to only\n\t\/\/ try to add new hosts if GetHosts didnt error and the hosts didnt change.\n\thosts, partitioner, err := r.GetHosts()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ TODO: move this to session\n\t\/\/ TODO: handle removing hosts here\n\tfor _, h := range hosts {\n\t\tif host, ok := r.session.ring.addHostIfMissing(h); !ok {\n\t\t\tr.session.pool.addHost(h)\n\t\t} else {\n\t\t\thost.update(h)\n\t\t}\n\t}\n\n\tr.session.pool.SetPartitioner(partitioner)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n    database.go\n\n    Manages router data persistence.\n*\/\npackage main\n\nimport(\n    \"redis-go\"\n    \"encoding\/json\"\n    \"strconv\"\n    \"strings\"\n    \"errors\"\n    \"fmt\"\n    \"log\"\n)\n\ntype SessionID struct {\n    instance string\n    id       int\n}\n\nfunc (s SessionID) Key() string {\n    return fmt.Sprintf(\"session:%s:%d\", s.instance, s.id)\n}\n\nfunc (s SessionID) ObjectsKey() string {\n    return fmt.Sprintf(\"session_objs:%s:%d\", s.instance, s.id)\n}\n\ntype SessionObjectID struct {\n    objectType string\n    sessionID  SessionID\n    subject    string\n}\n\nfunc (s SessionObjectID) Key() string {\n    return fmt.Sprintf(\"%s:%s:%d:%s\", s.objectType, s.sessionID.instance, s.sessionID.id, s.subject)\n}\n\ntype Database struct {\n    client *redis.Client\n}\n\nfunc NewDatabase(redisHost string, redisDB int) (database *Database) {\n    database = &Database{\n        client: &redis.Client{Addr: redisHost, Db: redisDB},\n    }\n    return database\n}\n\n\/* Getting\/Setting Session Stuff *\/\n\nfunc (db *Database) SessionIDs() ([]SessionID, error) {\n    sessionsData, err := db.client.Smembers(\"sessions\")\n    if err != nil {\n        return nil, err\n    }\n\n    ids := make([]SessionID, len(sessionsData))\n\n    for i, bytes := range sessionsData {\n        components := strings.Split(string(bytes), \":\")\n\n        instance := components[1]\n        id, err := strconv.Atoi(components[2])\n        if err != nil {\n            return ids, err\n        }\n\n        ids[i] = SessionID{\n            instance: instance,\n            id:       id,\n        }\n    }\n    return ids, err\n}\n\nfunc (db *Database) SessionObjectIDs(sessionID SessionID) ([]SessionObjectID, error) {\n    key := sessionID.ObjectsKey()\n    sessionObjects, err := db.client.Smembers(key)\n    if err != nil {\n        return nil, err\n    }\n\n    ids := make([]SessionObjectID, len(sessionObjects))\n\n    for i, bytes := range sessionObjects {\n        components := strings.Split(string(bytes), \":\")\n\n        objectType := components[0]\n        instance := components[1]\n        id, err := strconv.Atoi(components[2])\n        if err != nil {\n            return ids, err\n        }\n        if instance != sessionID.instance || id != sessionID.id {\n            return ids, errors.New(\"session_objs has object with different instance\/id\")\n        }\n        subject := components[3]\n\n        ids[i] = SessionObjectID{\n            objectType: objectType,\n            sessionID:  SessionID{\n                            instance: instance,\n                            id:       id,\n                        },\n            subject:    subject,\n        }\n    }\n    return ids, err\n}\n\nfunc (db *Database) DeleteSession(sessionID SessionID) (error) {\n    _, err := db.client.Del(sessionID.Key())\n    if err != nil {\n        return err\n    }\n    _, err = db.client.Srem(\"sessions\", []byte(sessionID.Key()))\n    if err != nil {\n        return err\n    }\n    return db.DeleteSessionObjects(sessionID)\n}\n\n\/* Getting and Setting Session Objects *\/\n\nfunc (db *Database) getIntData(key string) (int, error) {\n    bytes, err := db.client.Get(key)\n    if err != nil {\n        return 0, err\n    }\n    return strconv.Atoi(string(bytes))\n}\n\nfunc (db *Database) Period(objectID SessionObjectID) (int, error) {\n    return db.getIntData(objectID.Key())\n}\n\nfunc (db *Database) Group(objectID SessionObjectID) (int, error) {\n    return db.getIntData(objectID.Key())\n}\n\nfunc (db *Database) Config(objectID SessionObjectID) (*Msg, error) {\n    bytes, err := db.client.Get(objectID.Key())\n    if err != nil {\n        return nil, err\n    }\n\n    var config Msg\n    err = json.Unmarshal(bytes, &config)\n    return &config, err\n}\n\nfunc (db *Database) SetSessionObject(objectID SessionObjectID, data []byte) (error) {\n    keyBytes := []byte(objectID.Key())\n\n    var err error\n    if err = db.client.Set(objectID.Key(), data); err != nil {\n        return err\n    }\n    if _, err = db.client.Sadd(objectID.sessionID.ObjectsKey(), keyBytes); err != nil {\n        return err\n    }\n    return nil\n}\n\nfunc (db *Database) DeleteSessionObjects(sessionID SessionID) (error) {\n    objectKeys, err := db.client.Smembers(sessionID.Key())\n    if err != nil {\n        return err\n    }\n    for i := range objectKeys {\n        _, err := db.client.Del(string(objectKeys[i]))\n        if err != nil {\n            return err\n        }\n    }\n    _, err = db.client.Del(sessionID.ObjectsKey())\n    return err\n}\n\n\/* Getting Messages *\/\n\nfunc (db *Database) Messages(sessionID SessionID) (chan *Msg, error) {\n    \/\/ retrive messages in smaller blocks to keep peak memory usage\n    \/\/ under control when the message digest gets too large\n    blockSize := 1000\n    messageCount, err := db.client.Llen(sessionID.Key())\n    if err != nil {\n        return nil, err\n    }\n\n    messages := make(chan *Msg, blockSize)\n\n    log.Printf(\"Fetching %d messages from Redis into %p\", messageCount, messages)\n    go func() {\n        for i := 0; i < messageCount; i += blockSize {\n            limit := i + blockSize\n            if limit >= messageCount {\n                limit = messageCount\n            }\n            log.Printf(\"Fetching messages %d-%d into %p\", i, limit - 1, messages)\n            msgData, err := db.client.Lrange(sessionID.Key(), i, limit - 1)\n            if err != nil {\n                close(messages)\n                return\n            }\n            for _, bytes := range msgData {\n                var msg Msg\n                if err = json.Unmarshal(bytes, &msg); err != nil {\n                    close(messages)\n                    return\n                }\n                messages <- &msg\n            }\n        }\n        close(messages)\n    }()\n\n    return messages, nil\n}\n\n\/* Saving Messages *\/\n\nfunc (db *Database) SaveMessage(msg *Msg) (error) {\n    key := fmt.Sprintf(\"session:%s:%d\", msg.Instance, msg.Session)\n    db.client.Sadd(\"sessions\", []byte(key))\n    if b, err := json.Marshal(msg); err == nil {\n        err := db.client.Rpush(key, b)\n        return err\n    }\n    return nil\n}<commit_msg>Consolidated some channel closing<commit_after>\/*\n    database.go\n\n    Manages router data persistence.\n*\/\npackage main\n\nimport(\n    \"redis-go\"\n    \"encoding\/json\"\n    \"strconv\"\n    \"strings\"\n    \"errors\"\n    \"fmt\"\n    \"log\"\n)\n\ntype SessionID struct {\n    instance string\n    id       int\n}\n\nfunc (s SessionID) Key() string {\n    return fmt.Sprintf(\"session:%s:%d\", s.instance, s.id)\n}\n\nfunc (s SessionID) ObjectsKey() string {\n    return fmt.Sprintf(\"session_objs:%s:%d\", s.instance, s.id)\n}\n\ntype SessionObjectID struct {\n    objectType string\n    sessionID  SessionID\n    subject    string\n}\n\nfunc (s SessionObjectID) Key() string {\n    return fmt.Sprintf(\"%s:%s:%d:%s\", s.objectType, s.sessionID.instance, s.sessionID.id, s.subject)\n}\n\ntype Database struct {\n    client *redis.Client\n}\n\nfunc NewDatabase(redisHost string, redisDB int) (database *Database) {\n    database = &Database{\n        client: &redis.Client{Addr: redisHost, Db: redisDB},\n    }\n    return database\n}\n\n\/* Getting\/Setting Session Stuff *\/\n\nfunc (db *Database) SessionIDs() ([]SessionID, error) {\n    sessionsData, err := db.client.Smembers(\"sessions\")\n    if err != nil {\n        return nil, err\n    }\n\n    ids := make([]SessionID, len(sessionsData))\n\n    for i, bytes := range sessionsData {\n        components := strings.Split(string(bytes), \":\")\n\n        instance := components[1]\n        id, err := strconv.Atoi(components[2])\n        if err != nil {\n            return ids, err\n        }\n\n        ids[i] = SessionID{\n            instance: instance,\n            id:       id,\n        }\n    }\n    return ids, err\n}\n\nfunc (db *Database) SessionObjectIDs(sessionID SessionID) ([]SessionObjectID, error) {\n    key := sessionID.ObjectsKey()\n    sessionObjects, err := db.client.Smembers(key)\n    if err != nil {\n        return nil, err\n    }\n\n    ids := make([]SessionObjectID, len(sessionObjects))\n\n    for i, bytes := range sessionObjects {\n        components := strings.Split(string(bytes), \":\")\n\n        objectType := components[0]\n        instance := components[1]\n        id, err := strconv.Atoi(components[2])\n        if err != nil {\n            return ids, err\n        }\n        if instance != sessionID.instance || id != sessionID.id {\n            return ids, errors.New(\"session_objs has object with different instance\/id\")\n        }\n        subject := components[3]\n\n        ids[i] = SessionObjectID{\n            objectType: objectType,\n            sessionID:  SessionID{\n                            instance: instance,\n                            id:       id,\n                        },\n            subject:    subject,\n        }\n    }\n    return ids, err\n}\n\nfunc (db *Database) DeleteSession(sessionID SessionID) (error) {\n    _, err := db.client.Del(sessionID.Key())\n    if err != nil {\n        return err\n    }\n    _, err = db.client.Srem(\"sessions\", []byte(sessionID.Key()))\n    if err != nil {\n        return err\n    }\n    return db.DeleteSessionObjects(sessionID)\n}\n\n\/* Getting and Setting Session Objects *\/\n\nfunc (db *Database) getIntData(key string) (int, error) {\n    bytes, err := db.client.Get(key)\n    if err != nil {\n        return 0, err\n    }\n    return strconv.Atoi(string(bytes))\n}\n\nfunc (db *Database) Period(objectID SessionObjectID) (int, error) {\n    return db.getIntData(objectID.Key())\n}\n\nfunc (db *Database) Group(objectID SessionObjectID) (int, error) {\n    return db.getIntData(objectID.Key())\n}\n\nfunc (db *Database) Config(objectID SessionObjectID) (*Msg, error) {\n    bytes, err := db.client.Get(objectID.Key())\n    if err != nil {\n        return nil, err\n    }\n\n    var config Msg\n    err = json.Unmarshal(bytes, &config)\n    return &config, err\n}\n\nfunc (db *Database) SetSessionObject(objectID SessionObjectID, data []byte) (error) {\n    keyBytes := []byte(objectID.Key())\n\n    var err error\n    if err = db.client.Set(objectID.Key(), data); err != nil {\n        return err\n    }\n    if _, err = db.client.Sadd(objectID.sessionID.ObjectsKey(), keyBytes); err != nil {\n        return err\n    }\n    return nil\n}\n\nfunc (db *Database) DeleteSessionObjects(sessionID SessionID) (error) {\n    objectKeys, err := db.client.Smembers(sessionID.Key())\n    if err != nil {\n        return err\n    }\n    for i := range objectKeys {\n        _, err := db.client.Del(string(objectKeys[i]))\n        if err != nil {\n            return err\n        }\n    }\n    _, err = db.client.Del(sessionID.ObjectsKey())\n    return err\n}\n\n\/* Getting Messages *\/\n\nfunc (db *Database) Messages(sessionID SessionID) (chan *Msg, error) {\n    \/\/ retrive messages in smaller blocks to keep peak memory usage\n    \/\/ under control when the message digest gets too large\n    blockSize := 1000\n    messageCount, err := db.client.Llen(sessionID.Key())\n    if err != nil {\n        return nil, err\n    }\n\n    messages := make(chan *Msg, blockSize)\n\n    log.Printf(\"Fetching %d messages from Redis into %p\", messageCount, messages)\n    go func() {\n        defer close(messages)\n        for i := 0; i < messageCount; i += blockSize {\n            limit := i + blockSize\n            if limit >= messageCount {\n                limit = messageCount\n            }\n            msgData, err := db.client.Lrange(sessionID.Key(), i, limit - 1)\n            if err != nil {\n                return\n            }\n            for _, bytes := range msgData {\n                var msg Msg\n                if err = json.Unmarshal(bytes, &msg); err != nil {\n                    return\n                }\n                messages <- &msg\n            }\n        }\n    }()\n\n    return messages, nil\n}\n\n\/* Saving Messages *\/\n\nfunc (db *Database) SaveMessage(msg *Msg) (error) {\n    key := fmt.Sprintf(\"session:%s:%d\", msg.Instance, msg.Session)\n    db.client.Sadd(\"sessions\", []byte(key))\n    if b, err := json.Marshal(msg); err == nil {\n        err := db.client.Rpush(key, b)\n        return err\n    }\n    return nil\n}<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t_ \"expvar\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"net\/url\"\n\t\"os\"\n\t\"time\"\n\n\t\"koding\/artifact\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"koding\/kites\/kloud\/contexthelper\/publickeys\"\n\t\"koding\/kites\/kloud\/dnsstorage\"\n\t\"koding\/kites\/kloud\/pkg\/dnsclient\"\n\t\"koding\/kites\/kloud\/pkg\/multiec2\"\n\t\"koding\/kites\/kloud\/plans\"\n\t\"koding\/kites\/kloud\/provider\/koding\"\n\t\"koding\/kites\/kloud\/userdata\"\n\n\t\"koding\/kites\/kloud\/keycreator\"\n\t\"koding\/kites\/kloud\/kloud\"\n\t\"koding\/kites\/kloud\/kloudctl\/command\"\n\n\t\"github.com\/koding\/kite\"\n\tkiteconfig \"github.com\/koding\/kite\/config\"\n\t\"github.com\/koding\/logging\"\n\t\"github.com\/koding\/metrics\"\n\t\"github.com\/koding\/multiconfig\"\n\t\"github.com\/mitchellh\/goamz\/aws\"\n)\n\nvar Name = \"kloud\"\n\n\/\/ Config defines the configuration that Kloud needs to operate.\ntype Config struct {\n\t\/\/ ---  KLOUD SPECIFIC ---\n\tIP          string\n\tPort        int\n\tRegion      string\n\tEnvironment string\n\n\t\/\/ Connect to Koding mongodb\n\tMongoURL string `required:\"true\"`\n\n\t\/\/ Endpoint for fetching plans\n\tPlanEndpoint string `required:\"true\"`\n\n\t\/\/ Endpoint for fetching user machine network usage\n\tNetworkUsageEndpoint string `required:\"true\"`\n\n\t\/\/ --- DEVELOPMENT CONFIG ---\n\t\/\/ Show version and exit if enabled\n\tVersion bool\n\n\t\/\/ Enable debug log mode\n\tDebugMode bool\n\n\t\/\/ Enable production mode, operates on production channel\n\tProdMode bool\n\n\t\/\/ Enable test mode, disabled some authentication checks\n\tTestMode bool\n\n\t\/\/ Defines the base domain for domain creation\n\tHostedZone string `required:\"true\"`\n\n\t\/\/ Defines the default AMI Tag to use for koding provider\n\tAMITag string\n\n\t\/\/ --- KLIENT DEVELOPMENT ---\n\t\/\/ KontrolURL to connect and to de deployed with klient\n\tKontrolURL string `required:\"true\"`\n\n\t\/\/ Private key to create kite.key\n\tPrivateKey string `required:\"true\"`\n\n\t\/\/ Public key to create kite.key\n\tPublicKey string `required:\"true\"`\n\n\t\/\/ --- KONTROL CONFIGURATION ---\n\tPublic      bool   \/\/ Try to register with a public ip\n\tRegisterURL string \/\/ Explicitly register with this given url\n}\n\nfunc main() {\n\tconf := new(Config)\n\n\t\/\/ Load the config, it's reads environment variables or from flags\n\tmulticonfig.New().MustLoad(conf)\n\n\tif conf.Version {\n\t\tfmt.Println(kloud.VERSION)\n\t\tos.Exit(0)\n\t}\n\n\tk := newKite(conf)\n\n\tif conf.DebugMode {\n\t\tk.Log.Info(\"Debug mode enabled\")\n\t}\n\n\tif conf.TestMode {\n\t\tk.Log.Info(\"Test mode enabled\")\n\t}\n\n\tregisterURL := k.RegisterURL(!conf.Public)\n\tif conf.RegisterURL != \"\" {\n\t\tu, err := url.Parse(conf.RegisterURL)\n\t\tif err != nil {\n\t\t\tk.Log.Fatal(\"Couldn't parse register url: %s\", err)\n\t\t}\n\n\t\tregisterURL = u\n\t}\n\n\tif err := k.RegisterForever(registerURL); err != nil {\n\t\tk.Log.Fatal(err.Error())\n\t}\n\n\t\/\/ DataDog listens to it\n\tgo func() {\n\t\terr := http.ListenAndServe(\"0.0.0.0:6060\", nil)\n\t\tk.Log.Error(err.Error())\n\t}()\n\n\tk.Run()\n}\n\nfunc newKite(conf *Config) *kite.Kite {\n\tk := kite.New(kloud.NAME, kloud.VERSION)\n\tk.Config = kiteconfig.MustGet()\n\tk.Config.Port = conf.Port\n\n\tif conf.Region != \"\" {\n\t\tk.Config.Region = conf.Region\n\t}\n\n\tif conf.Environment != \"\" {\n\t\tk.Config.Environment = conf.Environment\n\t}\n\n\tif conf.AMITag != \"\" {\n\t\tk.Log.Warning(\"Default AMI Tag changed from %s to %s\", koding.DefaultCustomAMITag, conf.AMITag)\n\t\tkoding.DefaultCustomAMITag = conf.AMITag\n\t}\n\n\tklientFolder := \"development\/latest\"\n\tk.Log.Info(\"Klient distribution channel is: %s\", klientFolder)\n\n\tmodelhelper.Initialize(conf.MongoURL)\n\tdb := modelhelper.Mongo\n\n\tkontrolPrivateKey, kontrolPublicKey := kontrolKeys(conf)\n\n\t\/\/ Credential belongs to the `koding-kloud` user in AWS IAM's\n\tauth := aws.Auth{\n\t\tAccessKey: \"AKIAJFKDHRJ7Q5G4MOUQ\",\n\t\tSecretKey: \"iSNZFtHwNFT8OpZ8Gsmj\/Bp0tU1vqNw6DfgvIUsn\",\n\t}\n\n\tdnsInstance := dnsclient.NewRoute53Client(conf.HostedZone, auth)\n\tdnsStorage := dnsstorage.NewMongodbStorage(db)\n\n\tkodingProvider := &koding.Provider{\n\t\tDB:         db,\n\t\tLog:        newLogger(\"kloud\", conf.DebugMode),\n\t\tDNSClient:  dnsInstance,\n\t\tDNSStorage: dnsStorage,\n\t\tKite:       k,\n\t\tEC2Clients: multiec2.New(auth, []string{\n\t\t\t\"us-east-1\",\n\t\t\t\"ap-southeast-1\",\n\t\t\t\"us-west-2\",\n\t\t\t\"eu-west-1\",\n\t\t}),\n\t\tUserdata: &userdata.Userdata{\n\t\t\tKeycreator: &keycreator.Key{\n\t\t\t\tKontrolURL:        getKontrolURL(conf.KontrolURL),\n\t\t\t\tKontrolPrivateKey: kontrolPrivateKey,\n\t\t\t\tKontrolPublicKey:  kontrolPublicKey,\n\t\t\t},\n\t\t\tBucket: userdata.NewBucket(\"koding-klient\", klientFolder, auth),\n\t\t},\n\t\tPaymentFetcher: &plans.Payment{\n\t\t\tPaymentEndpoint: conf.PlanEndpoint,\n\t\t},\n\t\tCheckerFetcher: &plans.KodingChecker{\n\t\t\tNetworkUsageEndpoint: conf.NetworkUsageEndpoint,\n\t\t},\n\t}\n\n\tcheckInterval := time.Second * 5\n\tif conf.ProdMode {\n\t\tk.Log.Info(\"Prod mode enabled\")\n\t\tklientFolder = \"production\/latest\"\n\t\tcheckInterval = time.Millisecond * 500\n\t}\n\n\tgo kodingProvider.RunChecker(checkInterval)\n\tgo kodingProvider.RunCleaners(time.Minute * 60)\n\n\tstats, err := metrics.NewDogStatsD(\"kloud\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tkld := kloud.New()\n\tkld.Metrics = stats\n\tkld.PublicKeys = publickeys.NewKeys()\n\tkld.DomainStorage = dnsStorage\n\tkld.Domainer = dnsInstance\n\tkld.Locker = kodingProvider\n\tkld.Log = newLogger(Name, conf.DebugMode)\n\n\terr = kld.AddProvider(\"koding\", kodingProvider)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Machine handling methods\n\tk.HandleFunc(\"build\", kld.Build)\n\tk.HandleFunc(\"destroy\", kld.Destroy)\n\tk.HandleFunc(\"stop\", kld.Stop)\n\tk.HandleFunc(\"start\", kld.Start)\n\tk.HandleFunc(\"reinit\", kld.Reinit)\n\tk.HandleFunc(\"restart\", kld.Restart)\n\tk.HandleFunc(\"info\", kld.Info)\n\tk.HandleFunc(\"event\", kld.Event)\n\tk.HandleFunc(\"resize\", kld.Resize)\n\n\t\/\/ Snapshot functionality\n\tk.HandleFunc(\"createSnapshot\", kld.CreateSnapshot)\n\tk.HandleFunc(\"deleteSnapshot\", kld.DeleteSnapshot)\n\n\t\/\/ Domain records handling methods\n\tk.HandleFunc(\"domain.set\", kld.DomainSet)\n\tk.HandleFunc(\"domain.unset\", kld.DomainUnset)\n\tk.HandleFunc(\"domain.add\", kld.DomainAdd)\n\tk.HandleFunc(\"domain.remove\", kld.DomainRemove)\n\n\tk.HandleHTTPFunc(\"\/healthCheck\", artifact.HealthCheckHandler(Name))\n\tk.HandleHTTPFunc(\"\/version\", artifact.VersionHandler())\n\n\t\/\/ This is a custom authenticator just for kloudctl\n\tk.Authenticators[\"kloudctl\"] = func(r *kite.Request) error {\n\t\tif r.Auth.Key != command.KloudSecretKey {\n\t\t\treturn errors.New(\"wrong secret key passed, you are not authenticated\")\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn k\n}\n\nfunc newLogger(name string, debug bool) logging.Logger {\n\tlog := logging.NewLogger(name)\n\tlogHandler := logging.NewWriterHandler(os.Stderr)\n\tlogHandler.Colorize = true\n\tlog.SetHandler(logHandler)\n\n\tif debug {\n\t\tlog.SetLevel(logging.DEBUG)\n\t\tlogHandler.SetLevel(logging.DEBUG)\n\t}\n\n\treturn log\n}\n\nfunc kontrolKeys(conf *Config) (string, string) {\n\tpubKey, err := ioutil.ReadFile(conf.PublicKey)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tpublicKey := string(pubKey)\n\n\tprivKey, err := ioutil.ReadFile(conf.PrivateKey)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tprivateKey := string(privKey)\n\n\treturn privateKey, publicKey\n}\n\nfunc getKontrolURL(ownURL string) string {\n\t\/\/ read kontrolURL from kite.key if it doesn't exist.\n\tkontrolURL := kiteconfig.MustGet().KontrolURL\n\n\tif ownURL != \"\" {\n\t\tu, err := url.Parse(ownURL)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t\tkontrolURL = u.String()\n\t}\n\n\treturn kontrolURL\n}\n<commit_msg>kloud\/main: change channel earlier<commit_after>package main\n\nimport (\n\t\"errors\"\n\t_ \"expvar\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t_ \"net\/http\/pprof\"\n\t\"net\/url\"\n\t\"os\"\n\t\"time\"\n\n\t\"koding\/artifact\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"koding\/kites\/kloud\/contexthelper\/publickeys\"\n\t\"koding\/kites\/kloud\/dnsstorage\"\n\t\"koding\/kites\/kloud\/pkg\/dnsclient\"\n\t\"koding\/kites\/kloud\/pkg\/multiec2\"\n\t\"koding\/kites\/kloud\/plans\"\n\t\"koding\/kites\/kloud\/provider\/koding\"\n\t\"koding\/kites\/kloud\/userdata\"\n\n\t\"koding\/kites\/kloud\/keycreator\"\n\t\"koding\/kites\/kloud\/kloud\"\n\t\"koding\/kites\/kloud\/kloudctl\/command\"\n\n\t\"github.com\/koding\/kite\"\n\tkiteconfig \"github.com\/koding\/kite\/config\"\n\t\"github.com\/koding\/logging\"\n\t\"github.com\/koding\/metrics\"\n\t\"github.com\/koding\/multiconfig\"\n\t\"github.com\/mitchellh\/goamz\/aws\"\n)\n\nvar Name = \"kloud\"\n\n\/\/ Config defines the configuration that Kloud needs to operate.\ntype Config struct {\n\t\/\/ ---  KLOUD SPECIFIC ---\n\tIP          string\n\tPort        int\n\tRegion      string\n\tEnvironment string\n\n\t\/\/ Connect to Koding mongodb\n\tMongoURL string `required:\"true\"`\n\n\t\/\/ Endpoint for fetching plans\n\tPlanEndpoint string `required:\"true\"`\n\n\t\/\/ Endpoint for fetching user machine network usage\n\tNetworkUsageEndpoint string `required:\"true\"`\n\n\t\/\/ --- DEVELOPMENT CONFIG ---\n\t\/\/ Show version and exit if enabled\n\tVersion bool\n\n\t\/\/ Enable debug log mode\n\tDebugMode bool\n\n\t\/\/ Enable production mode, operates on production channel\n\tProdMode bool\n\n\t\/\/ Enable test mode, disabled some authentication checks\n\tTestMode bool\n\n\t\/\/ Defines the base domain for domain creation\n\tHostedZone string `required:\"true\"`\n\n\t\/\/ Defines the default AMI Tag to use for koding provider\n\tAMITag string\n\n\t\/\/ --- KLIENT DEVELOPMENT ---\n\t\/\/ KontrolURL to connect and to de deployed with klient\n\tKontrolURL string `required:\"true\"`\n\n\t\/\/ Private key to create kite.key\n\tPrivateKey string `required:\"true\"`\n\n\t\/\/ Public key to create kite.key\n\tPublicKey string `required:\"true\"`\n\n\t\/\/ --- KONTROL CONFIGURATION ---\n\tPublic      bool   \/\/ Try to register with a public ip\n\tRegisterURL string \/\/ Explicitly register with this given url\n}\n\nfunc main() {\n\tconf := new(Config)\n\n\t\/\/ Load the config, it's reads environment variables or from flags\n\tmulticonfig.New().MustLoad(conf)\n\n\tif conf.Version {\n\t\tfmt.Println(kloud.VERSION)\n\t\tos.Exit(0)\n\t}\n\n\tk := newKite(conf)\n\n\tif conf.DebugMode {\n\t\tk.Log.Info(\"Debug mode enabled\")\n\t}\n\n\tif conf.TestMode {\n\t\tk.Log.Info(\"Test mode enabled\")\n\t}\n\n\tregisterURL := k.RegisterURL(!conf.Public)\n\tif conf.RegisterURL != \"\" {\n\t\tu, err := url.Parse(conf.RegisterURL)\n\t\tif err != nil {\n\t\t\tk.Log.Fatal(\"Couldn't parse register url: %s\", err)\n\t\t}\n\n\t\tregisterURL = u\n\t}\n\n\tif err := k.RegisterForever(registerURL); err != nil {\n\t\tk.Log.Fatal(err.Error())\n\t}\n\n\t\/\/ DataDog listens to it\n\tgo func() {\n\t\terr := http.ListenAndServe(\"0.0.0.0:6060\", nil)\n\t\tk.Log.Error(err.Error())\n\t}()\n\n\tk.Run()\n}\n\nfunc newKite(conf *Config) *kite.Kite {\n\tk := kite.New(kloud.NAME, kloud.VERSION)\n\tk.Config = kiteconfig.MustGet()\n\tk.Config.Port = conf.Port\n\n\tif conf.Region != \"\" {\n\t\tk.Config.Region = conf.Region\n\t}\n\n\tif conf.Environment != \"\" {\n\t\tk.Config.Environment = conf.Environment\n\t}\n\n\tif conf.AMITag != \"\" {\n\t\tk.Log.Warning(\"Default AMI Tag changed from %s to %s\", koding.DefaultCustomAMITag, conf.AMITag)\n\t\tkoding.DefaultCustomAMITag = conf.AMITag\n\t}\n\n\tklientFolder := \"development\/latest\"\n\tcheckInterval := time.Second * 5\n\tif conf.ProdMode {\n\t\tk.Log.Info(\"Prod mode enabled\")\n\t\tklientFolder = \"production\/latest\"\n\t\tcheckInterval = time.Millisecond * 500\n\t}\n\tk.Log.Info(\"Klient distribution channel is: %s\", klientFolder)\n\n\tmodelhelper.Initialize(conf.MongoURL)\n\tdb := modelhelper.Mongo\n\n\tkontrolPrivateKey, kontrolPublicKey := kontrolKeys(conf)\n\n\t\/\/ Credential belongs to the `koding-kloud` user in AWS IAM's\n\tauth := aws.Auth{\n\t\tAccessKey: \"AKIAJFKDHRJ7Q5G4MOUQ\",\n\t\tSecretKey: \"iSNZFtHwNFT8OpZ8Gsmj\/Bp0tU1vqNw6DfgvIUsn\",\n\t}\n\n\tdnsInstance := dnsclient.NewRoute53Client(conf.HostedZone, auth)\n\tdnsStorage := dnsstorage.NewMongodbStorage(db)\n\n\tkodingProvider := &koding.Provider{\n\t\tDB:         db,\n\t\tLog:        newLogger(\"kloud\", conf.DebugMode),\n\t\tDNSClient:  dnsInstance,\n\t\tDNSStorage: dnsStorage,\n\t\tKite:       k,\n\t\tEC2Clients: multiec2.New(auth, []string{\n\t\t\t\"us-east-1\",\n\t\t\t\"ap-southeast-1\",\n\t\t\t\"us-west-2\",\n\t\t\t\"eu-west-1\",\n\t\t}),\n\t\tUserdata: &userdata.Userdata{\n\t\t\tKeycreator: &keycreator.Key{\n\t\t\t\tKontrolURL:        getKontrolURL(conf.KontrolURL),\n\t\t\t\tKontrolPrivateKey: kontrolPrivateKey,\n\t\t\t\tKontrolPublicKey:  kontrolPublicKey,\n\t\t\t},\n\t\t\tBucket: userdata.NewBucket(\"koding-klient\", klientFolder, auth),\n\t\t},\n\t\tPaymentFetcher: &plans.Payment{\n\t\t\tPaymentEndpoint: conf.PlanEndpoint,\n\t\t},\n\t\tCheckerFetcher: &plans.KodingChecker{\n\t\t\tNetworkUsageEndpoint: conf.NetworkUsageEndpoint,\n\t\t},\n\t}\n\n\tgo kodingProvider.RunChecker(checkInterval)\n\tgo kodingProvider.RunCleaners(time.Minute * 60)\n\n\tstats, err := metrics.NewDogStatsD(\"kloud\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tkld := kloud.New()\n\tkld.Metrics = stats\n\tkld.PublicKeys = publickeys.NewKeys()\n\tkld.DomainStorage = dnsStorage\n\tkld.Domainer = dnsInstance\n\tkld.Locker = kodingProvider\n\tkld.Log = newLogger(Name, conf.DebugMode)\n\n\terr = kld.AddProvider(\"koding\", kodingProvider)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t\/\/ Machine handling methods\n\tk.HandleFunc(\"build\", kld.Build)\n\tk.HandleFunc(\"destroy\", kld.Destroy)\n\tk.HandleFunc(\"stop\", kld.Stop)\n\tk.HandleFunc(\"start\", kld.Start)\n\tk.HandleFunc(\"reinit\", kld.Reinit)\n\tk.HandleFunc(\"restart\", kld.Restart)\n\tk.HandleFunc(\"info\", kld.Info)\n\tk.HandleFunc(\"event\", kld.Event)\n\tk.HandleFunc(\"resize\", kld.Resize)\n\n\t\/\/ Snapshot functionality\n\tk.HandleFunc(\"createSnapshot\", kld.CreateSnapshot)\n\tk.HandleFunc(\"deleteSnapshot\", kld.DeleteSnapshot)\n\n\t\/\/ Domain records handling methods\n\tk.HandleFunc(\"domain.set\", kld.DomainSet)\n\tk.HandleFunc(\"domain.unset\", kld.DomainUnset)\n\tk.HandleFunc(\"domain.add\", kld.DomainAdd)\n\tk.HandleFunc(\"domain.remove\", kld.DomainRemove)\n\n\tk.HandleHTTPFunc(\"\/healthCheck\", artifact.HealthCheckHandler(Name))\n\tk.HandleHTTPFunc(\"\/version\", artifact.VersionHandler())\n\n\t\/\/ This is a custom authenticator just for kloudctl\n\tk.Authenticators[\"kloudctl\"] = func(r *kite.Request) error {\n\t\tif r.Auth.Key != command.KloudSecretKey {\n\t\t\treturn errors.New(\"wrong secret key passed, you are not authenticated\")\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn k\n}\n\nfunc newLogger(name string, debug bool) logging.Logger {\n\tlog := logging.NewLogger(name)\n\tlogHandler := logging.NewWriterHandler(os.Stderr)\n\tlogHandler.Colorize = true\n\tlog.SetHandler(logHandler)\n\n\tif debug {\n\t\tlog.SetLevel(logging.DEBUG)\n\t\tlogHandler.SetLevel(logging.DEBUG)\n\t}\n\n\treturn log\n}\n\nfunc kontrolKeys(conf *Config) (string, string) {\n\tpubKey, err := ioutil.ReadFile(conf.PublicKey)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tpublicKey := string(pubKey)\n\n\tprivKey, err := ioutil.ReadFile(conf.PrivateKey)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tprivateKey := string(privKey)\n\n\treturn privateKey, publicKey\n}\n\nfunc getKontrolURL(ownURL string) string {\n\t\/\/ read kontrolURL from kite.key if it doesn't exist.\n\tkontrolURL := kiteconfig.MustGet().KontrolURL\n\n\tif ownURL != \"\" {\n\t\tu, err := url.Parse(ownURL)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\n\t\tkontrolURL = u.String()\n\t}\n\n\treturn kontrolURL\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar (\n\tErrMessageAlreadyInTheChannel = errors.New(\"message is already in the channel\")\n\tErrIdIsNotSet                 = errors.New(\"Id is not set\")\n\tErrAccountIdIsNotSet          = errors.New(\"account id is not set\")\n\tErrOldIdIsNotSet              = errors.New(\"old id is not set\")\n\tErrNickIsNotSet               = errors.New(\"nick is not set\")\n\tErrGuestsAreNotAllowed        = errors.New(\"guests are not allowed\")\n\n\tErrMessageIdIsNotSet       = errors.New(\"message id is not set\")\n\tErrMessageIsNotSet         = errors.New(\"message is not set\")\n\tErrParentMessageIsNotSet   = errors.New(\"parent message is not set\")\n\tErrParentMessageIdIsNotSet = errors.New(\"parent message id is not set\")\n\tErrCreatorIdIsNotSet       = errors.New(\"creator id is not set\")\n\n\tErrChannelIsNotSet                = errors.New(\"channel is not set\")\n\tErrChannelIdIsNotSet              = errors.New(\"channel id is not set\")\n\tErrChannelContainerIsNotSet       = errors.New(\"channel container is not set\")\n\tErCouldntFindAccountIdFromContent = errors.New(\"couldnt find account id from content\")\n\tErrAccountIsAlreadyInTheChannel   = errors.New(\"account is already in the channel\")\n\n\tErrChannelParticipantIsNotSet             = errors.New(\"channel participant is not set\")\n\tErrCannotAddNewParticipantToPinnedChannel = errors.New(\"you can not add any participants to pinned activity channel\")\n\n\tErrChannelMessageIdIsNotSet        = errors.New(\"channel message id is not set\")\n\tErrChannelMessageUpdatedNotAllowed = errors.New(\"join\/leave message update is not allowed\")\n\n\tErrNameIsNotSet       = errors.New(\"name is not set\")\n\tErrGroupNameIsNotSet  = errors.New(\"group name is not set\")\n\tErrLastSeenAtIsNotSet = errors.New(\"lastSeenAt is not set\")\n\tErrAddedAtIsNotSet    = errors.New(\"addedAt is not set\")\n\n\tErrRecipientsNotDefined = errors.New(\"recipients are not defined\")\n\tErrCannotOpenChannel    = errors.New(\"you can not open the channel\")\n\tErrSlugIsNotSet         = errors.New(\"slug is not set\")\n\n\tErrChannelOrMessageIdIsNotSet = errors.New(\"channelId\/messageId is not set\")\n\n\tErrNotLoggedIn = errors.New(\"not logged in\")\n\n\tErrAccessDenied = errors.New(\"access denied\")\n\n\tErrRoleNotSet          = errors.New(\"role not set\")\n\tErrAccountNotFound     = errors.New(\"account not found\")\n\tErrChannelNotFound     = errors.New(\"channel not found\")\n\tErrParticipantNotFound = errors.New(\"participant not found\")\n\tErrParticipantBlocked  = errors.New(\"participant is blocked\")\n\n\t\/\/ moderation\n\tErrLeafIsNotSet     = errors.New(\"leaf channel is not set\")\n\tErrRootIsNotSet     = errors.New(\"root channel is not set\")\n\tErrChannelHasLeaves = errors.New(\"channel has leaves\")\n\tErrGroupsAreNotSame = errors.New(\"groups are not same\")\n\tErrLeafIsRootToo    = errors.New(\"leaf channel is root of another channel\")\n)\n\ntype ChannelIsLeafError error\n\nfunc ErrChannelIsLeafFunc(rootName, typeConstant string) error {\n\treturn ChannelIsLeafError(\n\t\tfmt.Errorf(\n\t\t\t\/\/ poor man's json encoding - not to handle error case of\n\t\t\t\/\/ json.MarshalJSON, if we add new properties into this string, we\n\t\t\t\/\/ should use std package\n\t\t\t\"{\\\"rootName\\\":\\\"%s\\\", \\\"typeConstant\\\":\\\"%s\\\"}\",\n\t\t\trootName,\n\t\t\ttypeConstant,\n\t\t))\n}\n\nfunc IsChannelLeafErr(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\t_, ok := err.(ChannelIsLeafError)\n\treturn ok\n}\n<commit_msg>socialapi: error is added<commit_after>package models\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar (\n\tErrMessageAlreadyInTheChannel = errors.New(\"message is already in the channel\")\n\tErrIdIsNotSet                 = errors.New(\"Id is not set\")\n\tErrAccountIdIsNotSet          = errors.New(\"account id is not set\")\n\tErrOldIdIsNotSet              = errors.New(\"old id is not set\")\n\tErrNickIsNotSet               = errors.New(\"nick is not set\")\n\tErrGuestsAreNotAllowed        = errors.New(\"guests are not allowed\")\n\n\tErrMessageIdIsNotSet       = errors.New(\"message id is not set\")\n\tErrMessageIsNotSet         = errors.New(\"message is not set\")\n\tErrParentMessageIsNotSet   = errors.New(\"parent message is not set\")\n\tErrParentMessageIdIsNotSet = errors.New(\"parent message id is not set\")\n\tErrCreatorIdIsNotSet       = errors.New(\"creator id is not set\")\n\n\tErrChannelIsNotSet                = errors.New(\"channel is not set\")\n\tErrChannelIdIsNotSet              = errors.New(\"channel id is not set\")\n\tErrChannelContainerIsNotSet       = errors.New(\"channel container is not set\")\n\tErCouldntFindAccountIdFromContent = errors.New(\"couldnt find account id from content\")\n\tErrAccountIsAlreadyInTheChannel   = errors.New(\"account is already in the channel\")\n\n\tErrChannelParticipantIsNotSet             = errors.New(\"channel participant is not set\")\n\tErrCannotAddNewParticipantToPinnedChannel = errors.New(\"you can not add any participants to pinned activity channel\")\n\n\tErrChannelMessageIdIsNotSet        = errors.New(\"channel message id is not set\")\n\tErrChannelMessageUpdatedNotAllowed = errors.New(\"join\/leave message update is not allowed\")\n\n\tErrNameIsNotSet       = errors.New(\"name is not set\")\n\tErrGroupNameIsNotSet  = errors.New(\"group name is not set\")\n\tErrGroupNotFound \t  = errors.New(\"group is not found\")\n\tErrLastSeenAtIsNotSet = errors.New(\"lastSeenAt is not set\")\n\tErrAddedAtIsNotSet    = errors.New(\"addedAt is not set\")\n\n\tErrRecipientsNotDefined = errors.New(\"recipients are not defined\")\n\tErrCannotOpenChannel    = errors.New(\"you can not open the channel\")\n\tErrSlugIsNotSet         = errors.New(\"slug is not set\")\n\n\tErrChannelOrMessageIdIsNotSet = errors.New(\"channelId\/messageId is not set\")\n\n\tErrNotLoggedIn = errors.New(\"not logged in\")\n\n\tErrAccessDenied = errors.New(\"access denied\")\n\n\tErrRoleNotSet          = errors.New(\"role not set\")\n\tErrAccountNotFound     = errors.New(\"account not found\")\n\tErrChannelNotFound     = errors.New(\"channel not found\")\n\tErrParticipantNotFound = errors.New(\"participant not found\")\n\tErrParticipantBlocked  = errors.New(\"participant is blocked\")\n\n\t\/\/ moderation\n\tErrLeafIsNotSet     = errors.New(\"leaf channel is not set\")\n\tErrRootIsNotSet     = errors.New(\"root channel is not set\")\n\tErrChannelHasLeaves = errors.New(\"channel has leaves\")\n\tErrGroupsAreNotSame = errors.New(\"groups are not same\")\n\tErrLeafIsRootToo    = errors.New(\"leaf channel is root of another channel\")\n)\n\ntype ChannelIsLeafError error\n\nfunc ErrChannelIsLeafFunc(rootName, typeConstant string) error {\n\treturn ChannelIsLeafError(\n\t\tfmt.Errorf(\n\t\t\t\/\/ poor man's json encoding - not to handle error case of\n\t\t\t\/\/ json.MarshalJSON, if we add new properties into this string, we\n\t\t\t\/\/ should use std package\n\t\t\t\"{\\\"rootName\\\":\\\"%s\\\", \\\"typeConstant\\\":\\\"%s\\\"}\",\n\t\t\trootName,\n\t\t\ttypeConstant,\n\t\t))\n}\n\nfunc IsChannelLeafErr(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\t_, ok := err.(ChannelIsLeafError)\n\treturn ok\n}\n<|endoftext|>"}
{"text":"<commit_before>package https\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"golang.org\/x\/crypto\/acme\/autocert\"\n)\n\nfunc ListenAndServeAutocert(httpsAddr, cachePath string, hosts []string, appHandlers http.Handler) error {\n\tvar m autocert.Manager\n\tm.Prompt = autocert.AcceptTOS\n\tif cachePath != \"\" {\n\t\tif err := os.MkdirAll(cachePath, 0700); err != nil {\n\t\t\treturn fmt.Errorf(\"could not create or read Let's Encrypt cache directory: %v\", err)\n\t\t}\n\t\tm.Cache = autocert.DirCache(cachePath)\n\t}\n\tif len(hosts) > 0 {\n\t\tm.HostPolicy = autocert.HostWhitelist(hosts...)\n\t}\n\ttlsConfig := &tls.Config{GetCertificate: m.GetCertificate}\n\n\tserver := newServer(tlsConfig, appHandlers)\n\n\tln, err := net.Listen(\"tcp\", httpsAddr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: %v\", err)\n\t}\n\tln = tls.NewListener(ln, tlsConfig)\n\terr = server.Serve(ln)\n\treturn fmt.Errorf(\"https: %v\", err)\n}\n\nfunc ListenAndServeTLS(addr, certFile, keyFile string, handler http.Handler) error {\n\ttlsConfig, err := newDefaultTLSConfig(certFile, keyFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: setting up TLS config: %v\", err)\n\t}\n\n\tserver := newServer(tlsConfig, handler)\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: %v\", err)\n\t}\n\tln = tls.NewListener(ln, tlsConfig)\n\terr = server.Serve(ln)\n\treturn fmt.Errorf(\"https: %v\", err)\n}\n\nfunc newServer(config *tls.Config, handler http.Handler) *http.Server {\n\treturn &http.Server{\n\t\tReadHeaderTimeout: 5 * time.Second,\n\t\tReadTimeout:       15 * time.Second,\n\t\tWriteTimeout:      10 * time.Second,\n\t\tIdleTimeout:       60 * time.Second,\n\t\tTLSConfig:         config,\n\t\tHandler:           handler,\n\t}\n}\n\nfunc newDefaultTLSConfig(certFile, keyFile string) (*tls.Config, error) {\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"loading certificate key pair failed: %v\", err)\n\t}\n\t\/\/ TLS configuration meant to be used by a Go server that is going to be\n\t\/\/ exposed on the internet directly (Valsorda 2016):\n\t\/\/ https:\/\/blog.cloudflare.com\/exposing-go-on-the-internet\/\n\ttlsConfig := &tls.Config{\n\t\t\/\/ Causes servers to use Go's default ciphersuite preferences,\n\t\t\/\/ which are tuned to avoid attacks. Does nothing on clients.\n\t\tPreferServerCipherSuites: true,\n\t\tCurvePreferences:         []tls.CurveID{tls.CurveP256, tls.X25519},\n\t\tMinVersion:               tls.VersionTLS12,\n\t\tCertificates:             []tls.Certificate{cert},\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,\n\n\t\t\t\/\/ Vulnerable to the Lucky13 attack.\n\t\t\t\/\/ tls.TLS_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\t\/\/ tls.TLS_RSA_WITH_AES_128_GCM_SHA256,\n\t\t},\n\t}\n\ttlsConfig.BuildNameToCertificate()\n\treturn tlsConfig, nil\n}\n<commit_msg>Document https package<commit_after>\/\/ Package https provides helpers for starting an HTTPS server and serving an\n\/\/ application's handlers.\npackage https\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n\n\t\"golang.org\/x\/crypto\/acme\/autocert\"\n)\n\n\/\/ ListenAndServeAutocert automatically gets Let's Encrypt certificates for the\n\/\/ provided hosts and launches an HTTPS server to serve the application's\n\/\/ handlers.\nfunc ListenAndServeAutocert(httpsAddr, cachePath string, hosts []string, appHandlers http.Handler) error {\n\tvar m autocert.Manager\n\tm.Prompt = autocert.AcceptTOS\n\tif cachePath != \"\" {\n\t\tif err := os.MkdirAll(cachePath, 0700); err != nil {\n\t\t\treturn fmt.Errorf(\"could not create or read Let's Encrypt cache directory: %v\", err)\n\t\t}\n\t\tm.Cache = autocert.DirCache(cachePath)\n\t}\n\tif len(hosts) > 0 {\n\t\tm.HostPolicy = autocert.HostWhitelist(hosts...)\n\t}\n\ttlsConfig := &tls.Config{GetCertificate: m.GetCertificate}\n\n\tserver := newServer(tlsConfig, appHandlers)\n\n\tln, err := net.Listen(\"tcp\", httpsAddr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: %v\", err)\n\t}\n\tln = tls.NewListener(ln, tlsConfig)\n\terr = server.Serve(ln)\n\treturn fmt.Errorf(\"https: %v\", err)\n}\n\n\/\/ ListenAndServeTLS launches an HTTPS server to serve the application's\n\/\/ handlers using the provided TLS certificaces.\nfunc ListenAndServeTLS(addr, certFile, keyFile string, handler http.Handler) error {\n\ttlsConfig, err := newDefaultTLSConfig(certFile, keyFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: setting up TLS config: %v\", err)\n\t}\n\n\tserver := newServer(tlsConfig, handler)\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"https: %v\", err)\n\t}\n\tln = tls.NewListener(ln, tlsConfig)\n\terr = server.Serve(ln)\n\treturn fmt.Errorf(\"https: %v\", err)\n}\n\nfunc newServer(config *tls.Config, handler http.Handler) *http.Server {\n\treturn &http.Server{\n\t\tReadHeaderTimeout: 5 * time.Second,\n\t\tReadTimeout:       15 * time.Second,\n\t\tWriteTimeout:      10 * time.Second,\n\t\tIdleTimeout:       60 * time.Second,\n\t\tTLSConfig:         config,\n\t\tHandler:           handler,\n\t}\n}\n\nfunc newDefaultTLSConfig(certFile, keyFile string) (*tls.Config, error) {\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"loading certificate key pair failed: %v\", err)\n\t}\n\t\/\/ TLS configuration meant to be used by a Go server that is going to be\n\t\/\/ exposed on the internet directly (Valsorda 2016):\n\t\/\/ https:\/\/blog.cloudflare.com\/exposing-go-on-the-internet\/\n\ttlsConfig := &tls.Config{\n\t\t\/\/ Causes servers to use Go's default ciphersuite preferences,\n\t\t\/\/ which are tuned to avoid attacks. Does nothing on clients.\n\t\tPreferServerCipherSuites: true,\n\t\tCurvePreferences:         []tls.CurveID{tls.CurveP256, tls.X25519},\n\t\tMinVersion:               tls.VersionTLS12,\n\t\tCertificates:             []tls.Certificate{cert},\n\t\tCipherSuites: []uint16{\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n\t\t\ttls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,\n\n\t\t\t\/\/ Vulnerable to the Lucky13 attack.\n\t\t\t\/\/ tls.TLS_RSA_WITH_AES_256_GCM_SHA384,\n\t\t\t\/\/ tls.TLS_RSA_WITH_AES_128_GCM_SHA256,\n\t\t},\n\t}\n\ttlsConfig.BuildNameToCertificate()\n\treturn tlsConfig, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Qiang Xue. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage validation\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype (\n\t\/\/ Errors represents the validation errors that are indexed by struct field names, map or slice keys.\n\tErrors map[string]error\n\n\t\/\/ InternalError represents an error that should NOT be treated as a validation error.\n\tInternalError interface {\n\t\terror\n\t\tInternalError() error\n\t}\n\n\tinternalError struct {\n\t\terror\n\t}\n)\n\n\/\/ NewInternalError wraps a given error into an InternalError.\nfunc NewInternalError(err error) InternalError {\n\treturn internalError{error: err}\n}\n\n\/\/ InternalError returns the actual error that it wraps around.\nfunc (e internalError) InternalError() error {\n\treturn e.error\n}\n\n\/\/ Error returns the error string of Errors.\nfunc (es Errors) Error() string {\n\tif len(es) == 0 {\n\t\treturn \"\"\n\t}\n\n\tkeys := []string{}\n\tfor key := range es {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Strings(keys)\n\n\ts := \"\"\n\tfor i, key := range keys {\n\t\tif i > 0 {\n\t\t\ts += \"; \"\n\t\t}\n\t\tif errs, ok := es[key].(Errors); ok {\n\t\t\ts += fmt.Sprintf(\"%v: (%v)\", key, errs)\n\t\t} else {\n\t\t\ts += fmt.Sprintf(\"%v: %v\", key, es[key].Error())\n\t\t}\n\t}\n\treturn s + \".\"\n}\n\n\/\/ MarshalJSON converts the Errors into a valid JSON.\nfunc (es Errors) MarshalJSON() ([]byte, error) {\n\terrs := map[string]interface{}{}\n\tfor key, err := range es {\n\t\tif ms, ok := err.(json.Marshaler); ok {\n\t\t\terrs[key] = ms\n\t\t} else {\n\t\t\terrs[key] = err.Error()\n\t\t}\n\t}\n\treturn json.Marshal(errs)\n}\n\n\/\/ Filter removes all nils from Errors and returns back the updated Errors as an error.\n\/\/ If the length of Errors becomes 0, it will return nil.\nfunc (es Errors) Filter() error {\n\tfor key, value := range es {\n\t\tif value == nil {\n\t\t\tdelete(es, key)\n\t\t}\n\t}\n\tif len(es) == 0 {\n\t\treturn nil\n\t}\n\treturn es\n}\n<commit_msg>optimized error string generation in Errors.Error()<commit_after>\/\/ Copyright 2016 Qiang Xue. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\n\npackage validation\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n)\n\ntype (\n\t\/\/ Errors represents the validation errors that are indexed by struct field names, map or slice keys.\n\tErrors map[string]error\n\n\t\/\/ InternalError represents an error that should NOT be treated as a validation error.\n\tInternalError interface {\n\t\terror\n\t\tInternalError() error\n\t}\n\n\tinternalError struct {\n\t\terror\n\t}\n)\n\n\/\/ NewInternalError wraps a given error into an InternalError.\nfunc NewInternalError(err error) InternalError {\n\treturn internalError{error: err}\n}\n\n\/\/ InternalError returns the actual error that it wraps around.\nfunc (e internalError) InternalError() error {\n\treturn e.error\n}\n\n\/\/ Error returns the error string of Errors.\nfunc (es Errors) Error() string {\n\tif len(es) == 0 {\n\t\treturn \"\"\n\t}\n\n\tkeys := []string{}\n\tfor key := range es {\n\t\tkeys = append(keys, key)\n\t}\n\tsort.Strings(keys)\n\n\tvar s strings.Builder\n\tfor i, key := range keys {\n\t\tif i > 0 {\n\t\t\ts.WriteString(\"; \")\n\t\t}\n\t\tif errs, ok := es[key].(Errors); ok {\n\t\t\tfmt.Fprintf(&s, \"%v: (%v)\", key, errs)\n\t\t} else {\n\t\t\tfmt.Fprintf(&s, \"%v: %v\", key, es[key].Error())\n\t\t}\n\t}\n\ts.WriteString(\".\")\n\treturn s.String()\n}\n\n\/\/ MarshalJSON converts the Errors into a valid JSON.\nfunc (es Errors) MarshalJSON() ([]byte, error) {\n\terrs := map[string]interface{}{}\n\tfor key, err := range es {\n\t\tif ms, ok := err.(json.Marshaler); ok {\n\t\t\terrs[key] = ms\n\t\t} else {\n\t\t\terrs[key] = err.Error()\n\t\t}\n\t}\n\treturn json.Marshal(errs)\n}\n\n\/\/ Filter removes all nils from Errors and returns back the updated Errors as an error.\n\/\/ If the length of Errors becomes 0, it will return nil.\nfunc (es Errors) Filter() error {\n\tfor key, value := range es {\n\t\tif value == nil {\n\t\t\tdelete(es, key)\n\t\t}\n\t}\n\tif len(es) == 0 {\n\t\treturn nil\n\t}\n\treturn es\n}\n<|endoftext|>"}
{"text":"<commit_before>package api2go\n\nimport \"strconv\"\n\ntype httpError struct {\n\terr    error\n\tmsg    string\n\tstatus int\n\terrors []APIError\n}\n\n\/\/APIError can be used for\ntype APIError struct {\n\tID     string\n\tHref   string\n\tStatus string\n\tCode   string\n\tTitle  string\n\tDetail string\n\tPath   string\n}\n\n\/\/ NewHTTPError creates a new error with message and status code.\n\/\/ `err` will be logged (but never sent to a client), `msg` will be sent and `status` is the http status code.\n\/\/ `err` can be nil.\nfunc NewHTTPError(err error, msg string, status int) error {\n\tvar errors []APIError\n\treturn httpError{err, msg, status, errors}\n}\n\n\/\/AddAPIError adds an additional json api error\nfunc (e *httpError) AddAPIError(err APIError) {\n\te.errors = append(e.errors, err)\n}\n\n\/\/Error returns a nice string represenation including the status\nfunc (e httpError) Error() string {\n\tmsg := \"http error (\" + strconv.Itoa(e.status) + \"): \" + e.msg\n\tif e.err != nil {\n\t\tmsg += \", \" + e.err.Error()\n\t}\n\treturn msg\n}\n<commit_msg>Label struct params in order to remove empty init<commit_after>package api2go\n\nimport \"strconv\"\n\ntype httpError struct {\n\terr    error\n\tmsg    string\n\tstatus int\n\terrors []APIError\n}\n\n\/\/APIError can be used for\ntype APIError struct {\n\tID     string\n\tHref   string\n\tStatus string\n\tCode   string\n\tTitle  string\n\tDetail string\n\tPath   string\n}\n\n\/\/ NewHTTPError creates a new error with message and status code.\n\/\/ `err` will be logged (but never sent to a client), `msg` will be sent and `status` is the http status code.\n\/\/ `err` can be nil.\nfunc NewHTTPError(err error, msg string, status int) error {\n\treturn httpError{err: err, msg: msg, status: status}\n}\n\n\/\/AddAPIError adds an additional json api error\nfunc (e *httpError) AddAPIError(err APIError) {\n\te.errors = append(e.errors, err)\n}\n\n\/\/Error returns a nice string represenation including the status\nfunc (e httpError) Error() string {\n\tmsg := \"http error (\" + strconv.Itoa(e.status) + \"): \" + e.msg\n\tif e.err != nil {\n\t\tmsg += \", \" + e.err.Error()\n\t}\n\treturn msg\n}\n<|endoftext|>"}
{"text":"<commit_before>package yext\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype ErrorType string\n\nconst (\n\tErrorTypeFatal    = \"FATAL_ERROR\"\n\tErrorTypeNonFatal = \"NON_FATAL_ERROR\"\n\tErrorTypeWarning  = \"WARNING\"\n)\n\ntype Error struct {\n\tMessage     string `json:\"message\"`\n\tCode        int    `json:\"code\"`\n\tType        string `json:\"type\"`\n\tRequestUUID string `json:\"request_uuid\"`\n}\n\nfunc (e Error) Error() string {\n\treturn fmt.Sprintf(\"type: %s code: %d message: %s, request uuid: %s\", e.Type, e.Code, e.Message, e.RequestUUID)\n}\n\nfunc (e Error) ErrorWithoutUUID() string {\n\treturn fmt.Sprintf(\"type: %s code: %d message: %s\", e.Type, e.Code, e.Message)\n}\n\nfunc (e Error) IsError() bool {\n\treturn e.Type == ErrorTypeFatal || e.Type == ErrorTypeNonFatal\n}\n\nfunc (e Error) IsWarning() bool {\n\treturn e.Type == ErrorTypeWarning\n}\n\ntype Errors []*Error\n\nfunc (e Errors) Error() string {\n\tvar (\n\t\terrs = make([]string, len(e))\n\t\tuuid = \"\"\n\t)\n\n\tfor i, err := range e {\n\t\terrs[i] = err.ErrorWithoutUUID()\n\t\tuuid = err.RequestUUID\n\t}\n\n\treturn fmt.Sprintf(\"%s; request uuid: %s\", strings.Join(errs, \"; \"), uuid)\n}\n\nfunc (e Errors) Errors() []Error {\n\tvar errors []Error\n\tfor _, err := range e {\n\t\tif err.IsError() {\n\t\t\terrors = append(errors, *err)\n\t\t}\n\t}\n\treturn errors\n}\n\nfunc (e Errors) Warnings() []Error {\n\tvar warnings []Error\n\tfor _, err := range e {\n\t\tif err.IsWarning() {\n\t\t\twarnings = append(warnings, *err)\n\t\t}\n\t}\n\treturn warnings\n}\n\nfunc IsNotFoundError(err error) bool {\n\tif e, ok := err.(Errors); ok {\n\t\tfor _, innerError := range e {\n\t\t\tif IsNotFoundError(innerError) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t} else if e, ok := err.(*Error); ok {\n\t\tif e.Code == 2000 || e.Code == 6004 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>update the Errors type Errors() and Warnings() methods to match the type itself, a slice of pointers to Error structs<commit_after>package yext\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype ErrorType string\n\nconst (\n\tErrorTypeFatal    = \"FATAL_ERROR\"\n\tErrorTypeNonFatal = \"NON_FATAL_ERROR\"\n\tErrorTypeWarning  = \"WARNING\"\n)\n\ntype Error struct {\n\tMessage     string `json:\"message\"`\n\tCode        int    `json:\"code\"`\n\tType        string `json:\"type\"`\n\tRequestUUID string `json:\"request_uuid\"`\n}\n\nfunc (e Error) Error() string {\n\treturn fmt.Sprintf(\"type: %s code: %d message: %s, request uuid: %s\", e.Type, e.Code, e.Message, e.RequestUUID)\n}\n\nfunc (e Error) ErrorWithoutUUID() string {\n\treturn fmt.Sprintf(\"type: %s code: %d message: %s\", e.Type, e.Code, e.Message)\n}\n\nfunc (e Error) IsError() bool {\n\treturn e.Type == ErrorTypeFatal || e.Type == ErrorTypeNonFatal\n}\n\nfunc (e Error) IsWarning() bool {\n\treturn e.Type == ErrorTypeWarning\n}\n\ntype Errors []*Error\n\nfunc (e Errors) Error() string {\n\tvar (\n\t\terrs = make([]string, len(e))\n\t\tuuid = \"\"\n\t)\n\n\tfor i, err := range e {\n\t\terrs[i] = err.ErrorWithoutUUID()\n\t\tuuid = err.RequestUUID\n\t}\n\n\treturn fmt.Sprintf(\"%s; request uuid: %s\", strings.Join(errs, \"; \"), uuid)\n}\n\nfunc (e Errors) Errors() []*Error {\n\tvar errors []*Error\n\tfor _, err := range e {\n\t\tif err.IsError() {\n\t\t\terrors = append(errors, err)\n\t\t}\n\t}\n\treturn errors\n}\n\nfunc (e Errors) Warnings() []*Error {\n\tvar warnings []*Error\n\tfor _, err := range e {\n\t\tif err.IsWarning() {\n\t\t\twarnings = append(warnings, err)\n\t\t}\n\t}\n\treturn warnings\n}\n\nfunc IsNotFoundError(err error) bool {\n\tif e, ok := err.(Errors); ok {\n\t\tfor _, innerError := range e {\n\t\t\tif IsNotFoundError(innerError) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t} else if e, ok := err.(*Error); ok {\n\t\tif e.Code == 2000 || e.Code == 6004 {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package octokit\n\nimport (\n\t\"github.com\/jingweno\/go-sawyer\/hypermedia\"\n)\n\nvar (\n\tCodeSearchURL       = Hyperlink(\"\/search\/code?q={query}{&page,per_page,sort,order}\")\n\tIssueSearchURL      = Hyperlink(\"\/search\/issues?q={query}{&page,per_page,sort,order}\")\n\tRepositorySearchURL = Hyperlink(\"\/search\/repositories?q={query}{&page,per_page,sort,order}\")\n\tUserSearchURL       = Hyperlink(\"\/search\/users?q={query}{&page,per_page,sort,order}\")\n)\n\nvar SearchURITemplate = \"search{\/type}?q={query}{&page,per_page,sort,order}\"\n\nfunc (c *Client) Search() *SearchService {\n\treturn &SearchService{client: c}\n}\n\n\/\/ A service to return search records\ntype SearchService struct {\n\tclient *Client\n}\n\n\/\/ Get the user search results based on SearchService#URL\nfunc (g *SearchService) Users(uri *Hyperlink, params M) (\n\tuserSearchResults UserSearchResults, result *Result) {\n\tif uri == nil {\n\t\turi = &UserSearchURL\n\t}\n\turl, e := uri.Expand(params)\n\tif e != nil {\n\t\treturn UserSearchResults{}, &Result{Err: e}\n\t}\n\tresult = g.client.get(url, &userSearchResults)\n\treturn\n}\n\n\/\/ Get the issue search results based on SearchService#URL\nfunc (g *SearchService) Issues(uri *Hyperlink, params M) (\n\tissueSearchResults IssueSearchResults, result *Result) {\n\tif uri == nil {\n\t\turi = &IssueSearchURL\n\t}\n\turl, e := uri.Expand(params)\n\tif e != nil {\n\t\treturn IssueSearchResults{}, &Result{Err: e}\n\t}\n\tresult = g.client.get(url, &issueSearchResults)\n\treturn\n}\n\n\/\/ Get the repository search results based on SearchService#URL\nfunc (g *SearchService) Repositories(uri *Hyperlink, params M) (\n\trepositorySearchResults RepositorySearchResults, result *Result) {\n\tif uri == nil {\n\t\turi = &RepositorySearchURL\n\t}\n\turl, e := uri.Expand(params)\n\tif e != nil {\n\t\treturn RepositorySearchResults{}, &Result{Err: e}\n\t}\n\tresult = g.client.get(url, &repositorySearchResults)\n\treturn\n}\n\n\/\/ Get the code search results based on SearchService#URL\nfunc (g *SearchService) Code(uri *Hyperlink, params M) (\n\tcodeSearchResults CodeSearchResults, result *Result) {\n\tif uri == nil {\n\t\turi = &CodeSearchURL\n\t}\n\turl, e := uri.Expand(params)\n\tif e != nil {\n\t\treturn CodeSearchResults{}, &Result{Err: e}\n\t}\n\tresult = g.client.get(url, &codeSearchResults)\n\treturn\n}\n\ntype UserSearchResults struct {\n\t*hypermedia.HALResource\n\n\tTotalCount        int    `json:\"total_count,omitempty\"`\n\tIncompleteResults bool   `json:\"incomplete_results,omitempty\"`\n\tItems             []User `json:\"items,omitempty\"`\n}\n\ntype IssueSearchResults struct {\n\t*hypermedia.HALResource\n\n\tTotalCount        int     `json:\"total_count,omitempty\"`\n\tIncompleteResults bool    `json:\"incomplete_results,omitempty\"`\n\tItems             []Issue `json:\"items,omitempty\"`\n}\n\ntype RepositorySearchResults struct {\n\t*hypermedia.HALResource\n\n\tTotalCount        int          `json:\"total_count,omitempty\"`\n\tIncompleteResults bool         `json:\"incomplete_results,omitempty\"`\n\tItems             []Repository `json:\"items,omitempty\"`\n}\n\ntype CodeSearchResults struct {\n\t*hypermedia.HALResource\n\n\tTotalCount        int        `json:\"total_count,omitempty\"`\n\tIncompleteResults bool       `json:\"incomplete_results,omitempty\"`\n\tItems             []CodeFile `json:\"items,omitempty\"`\n}\n\ntype CodeFile struct {\n\t*hypermedia.HALResource\n\n\tName       string     `json:\"name,omitempty\"`\n\tPath       string     `json:\"path,omitempty\"`\n\tSHA        string     `json:\"sha,omitempty\"`\n\tURL        Hyperlink  `json:\"url,omitempty\"`\n\tGitURL     Hyperlink  `json:\"git_url,omitempty\"`\n\tHTMLURL    Hyperlink  `json:\"html_url,omitempty\"`\n\tRepository Repository `json:\"repository,omitempty\"`\n}\n<commit_msg>Renamed e to err<commit_after>package octokit\n\nimport (\n\t\"github.com\/jingweno\/go-sawyer\/hypermedia\"\n)\n\nvar (\n\tCodeSearchURL       = Hyperlink(\"\/search\/code?q={query}{&page,per_page,sort,order}\")\n\tIssueSearchURL      = Hyperlink(\"\/search\/issues?q={query}{&page,per_page,sort,order}\")\n\tRepositorySearchURL = Hyperlink(\"\/search\/repositories?q={query}{&page,per_page,sort,order}\")\n\tUserSearchURL       = Hyperlink(\"\/search\/users?q={query}{&page,per_page,sort,order}\")\n)\n\nvar SearchURITemplate = \"search{\/type}?q={query}{&page,per_page,sort,order}\"\n\nfunc (c *Client) Search() *SearchService {\n\treturn &SearchService{client: c}\n}\n\n\/\/ A service to return search records\ntype SearchService struct {\n\tclient *Client\n}\n\n\/\/ Get the user search results based on SearchService#URL\nfunc (g *SearchService) Users(uri *Hyperlink, params M) (\n\tuserSearchResults UserSearchResults, result *Result) {\n\tif uri == nil {\n\t\turi = &UserSearchURL\n\t}\n\turl, err := uri.Expand(params)\n\tif e != nil {\n\t\treturn UserSearchResults{}, &Result{Err: err}\n\t}\n\tresult = g.client.get(url, &userSearchResults)\n\treturn\n}\n\n\/\/ Get the issue search results based on SearchService#URL\nfunc (g *SearchService) Issues(uri *Hyperlink, params M) (\n\tissueSearchResults IssueSearchResults, result *Result) {\n\tif uri == nil {\n\t\turi = &IssueSearchURL\n\t}\n\turl, err := uri.Expand(params)\n\tif e != nil {\n\t\treturn IssueSearchResults{}, &Result{Err: err}\n\t}\n\tresult = g.client.get(url, &issueSearchResults)\n\treturn\n}\n\n\/\/ Get the repository search results based on SearchService#URL\nfunc (g *SearchService) Repositories(uri *Hyperlink, params M) (\n\trepositorySearchResults RepositorySearchResults, result *Result) {\n\tif uri == nil {\n\t\turi = &RepositorySearchURL\n\t}\n\turl, err := uri.Expand(params)\n\tif e != nil {\n\t\treturn RepositorySearchResults{}, &Result{Err: err}\n\t}\n\tresult = g.client.get(url, &repositorySearchResults)\n\treturn\n}\n\n\/\/ Get the code search results based on SearchService#URL\nfunc (g *SearchService) Code(uri *Hyperlink, params M) (\n\tcodeSearchResults CodeSearchResults, result *Result) {\n\tif uri == nil {\n\t\turi = &CodeSearchURL\n\t}\n\turl, err := uri.Expand(params)\n\tif e != nil {\n\t\treturn CodeSearchResults{}, &Result{Err: err}\n\t}\n\tresult = g.client.get(url, &codeSearchResults)\n\treturn\n}\n\ntype UserSearchResults struct {\n\t*hypermedia.HALResource\n\n\tTotalCount        int    `json:\"total_count,omitempty\"`\n\tIncompleteResults bool   `json:\"incomplete_results,omitempty\"`\n\tItems             []User `json:\"items,omitempty\"`\n}\n\ntype IssueSearchResults struct {\n\t*hypermedia.HALResource\n\n\tTotalCount        int     `json:\"total_count,omitempty\"`\n\tIncompleteResults bool    `json:\"incomplete_results,omitempty\"`\n\tItems             []Issue `json:\"items,omitempty\"`\n}\n\ntype RepositorySearchResults struct {\n\t*hypermedia.HALResource\n\n\tTotalCount        int          `json:\"total_count,omitempty\"`\n\tIncompleteResults bool         `json:\"incomplete_results,omitempty\"`\n\tItems             []Repository `json:\"items,omitempty\"`\n}\n\ntype CodeSearchResults struct {\n\t*hypermedia.HALResource\n\n\tTotalCount        int        `json:\"total_count,omitempty\"`\n\tIncompleteResults bool       `json:\"incomplete_results,omitempty\"`\n\tItems             []CodeFile `json:\"items,omitempty\"`\n}\n\ntype CodeFile struct {\n\t*hypermedia.HALResource\n\n\tName       string     `json:\"name,omitempty\"`\n\tPath       string     `json:\"path,omitempty\"`\n\tSHA        string     `json:\"sha,omitempty\"`\n\tURL        Hyperlink  `json:\"url,omitempty\"`\n\tGitURL     Hyperlink  `json:\"git_url,omitempty\"`\n\tHTMLURL    Hyperlink  `json:\"html_url,omitempty\"`\n\tRepository Repository `json:\"repository,omitempty\"`\n}\n<|endoftext|>"}
{"text":"<commit_before>package mapquest\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n\t\"strings\"\n)\n\nvar _ = log.Print\n\nconst (\n\t\/\/ NominatimPathPrefix is the default path prefix for the Nominatim API.\n\tNominatimPathPrefix = \"\/nominatim\/v1\"\n)\n\n\/\/ NominatimAPI is a geographic search service that relies solely on the\n\/\/ data contributed to OpenStreetMap.\n\/\/ See http:\/\/open.mapquestapi.com\/nominatim\/ for details.\ntype NominatimAPI struct {\n\tc *Client\n}\n\n\/\/ Search searches for details given an address.\nfunc (api *NominatimAPI) Search(req *NominatimSearchRequest) (*NominatimSearchResponse, error) {\n\tu, err := api.buildSearchURL(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := new(NominatimSearchResponse)\n\tres.Results = make([]*NominatimSearchResult, 0)\n\n\tif err := api.c.getJSON(u, &res.Results); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}\n\n\/\/ buildSearchURL returns the complete URL for the request,\n\/\/ including the key to query the MapQuest API.\nfunc (api *NominatimAPI) buildSearchURL(req *NominatimSearchRequest) (string, error) {\n\turls := fmt.Sprintf(\"%s%s\/search.php\", api.c.BaseURL(), NominatimPathPrefix)\n\tu, err := url.Parse(urls)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t\/\/ Add key and other parameters to the query string\n\tq := u.Query()\n\tq.Set(\"format\", \"json\")\n\tq.Set(\"q\", req.Query)\n\tq.Set(\"addressdetails\", \"1\")\n\tif req.Limit > 0 {\n\t\tq.Set(\"limit\", fmt.Sprintf(\"%d\", req.Limit))\n\t}\n\tif len(req.CountryCodes) > 0 {\n\t\tq.Set(\"countrycodes\", strings.Join(req.CountryCodes, \",\"))\n\t}\n\tif len(req.ViewBox) == 4 {\n\t\tq.Set(\"viewbox\", fmt.Sprintf(\"%f,%f,%f,%f\", req.ViewBox[0], req.ViewBox[1], req.ViewBox[2], req.ViewBox[3]))\n\t}\n\tif len(req.ExcludePlaceIds) > 0 {\n\t\tq.Set(\"exclude_place_ids\", strings.Join(req.ExcludePlaceIds, \",\"))\n\t}\n\tif req.Bounded != nil {\n\t\tif *req.Bounded {\n\t\t\tq.Set(\"bounded\", \"1\")\n\t\t} else {\n\t\t\tq.Set(\"bounded\", \"0\")\n\t\t}\n\t}\n\t\/\/ TODO(oe): routewidth\n\tif req.RouteWidth != nil {\n\t\tq.Set(\"routewidth\", fmt.Sprintf(\"%f\", *req.RouteWidth))\n\t}\n\tif req.OSMType != \"\" {\n\t\tq.Set(\"osm_type\", req.OSMType)\n\t}\n\tif req.OSMId != \"\" {\n\t\tq.Set(\"osm_id\", req.OSMId)\n\t}\n\n\t\/\/ No key here!\n\tu.RawQuery = q.Encode()\n\treturn u.String(), nil\n}\n\ntype NominatimSearchRequest struct {\n\tQuery           string\n\tLimit           int\n\tCountryCodes    []string\n\tViewBox         []float64\n\tExcludePlaceIds []string\n\tBounded         *bool\n\tRouteWidth      *float64\n\tOSMType         string\n\tOSMId           string\n}\n\ntype NominatimSearchResponse struct {\n\tResults []*NominatimSearchResult\n}\n\ntype NominatimSearchResult struct {\n\tAddress *struct {\n\t\tCity          string `json:\"city,omitempty\"`\n\t\tCityDistrict  string `json:\"city_district,omitempty\"`\n\t\tContinent     string `json:\"continent,omitempty\"`\n\t\tCountry       string `json:\"country,omitempty\"`\n\t\tCountryCode   string `json:\"country_code,omitempty\"`\n\t\tCounty        string `json:\"county,omitempty\"`\n\t\tHamlet        string `json:\"hamlet,omitempty\"`\n\t\tHouseNumber   string `json:\"house_number,omitempty\"`\n\t\tPedestrian    string `json:\"pedestrian,omitempty\"`\n\t\tNeighbourhood string `json:\"neighbourhood,omitempty\"`\n\t\tPostCode      string `json:\"postcode,omitempty\"`\n\t\tRoad          string `json:\"road,omitempty\"`\n\t\tState         string `json:\"state,omitempty\"`\n\t\tStateDistrict string `json:\"state_district,omitempty\"`\n\t\tSuburb        string `json:\"suburb,omitempty\"`\n\t} `json:\"address,omitempty\"`\n\tBoundingBox []string `json:\"boundingbox,omitempty\"`\n\tClass       string   `json:\"class,omitempty\"`\n\tDisplayName string   `json:\"display_name,omitempty\"`\n\tImportance  float64  `json:\"importance,omitempty\"`\n\tLatitude    float64  `json:\"lat,string,omitempty\"`\n\tLongitude   float64  `json:\"lon,string,omitempty\"`\n\tOSMId       string   `json:\"osm_id,omitempty\"`\n\tOSMType     string   `json:\"osm_type,omitempty\"`\n\tPlaceId     string   `json:\"place_id,omitempty\"`\n\tType        string   `json:\"type,omitempty\"`\n\tLicense     string   `json:\"licence,omitempty\"` \/\/ typo in API?\n}\n<commit_msg>nominatim: boundingbox is unreliable<commit_after>package mapquest\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n\t\"strings\"\n)\n\nvar _ = log.Print\n\nconst (\n\t\/\/ NominatimPathPrefix is the default path prefix for the Nominatim API.\n\tNominatimPathPrefix = \"\/nominatim\/v1\"\n)\n\n\/\/ NominatimAPI is a geographic search service that relies solely on the\n\/\/ data contributed to OpenStreetMap.\n\/\/ See http:\/\/open.mapquestapi.com\/nominatim\/ for details.\ntype NominatimAPI struct {\n\tc *Client\n}\n\n\/\/ Search searches for details given an address.\nfunc (api *NominatimAPI) Search(req *NominatimSearchRequest) (*NominatimSearchResponse, error) {\n\tu, err := api.buildSearchURL(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := new(NominatimSearchResponse)\n\tres.Results = make([]*NominatimSearchResult, 0)\n\n\tif err := api.c.getJSON(u, &res.Results); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}\n\n\/\/ buildSearchURL returns the complete URL for the request,\n\/\/ including the key to query the MapQuest API.\nfunc (api *NominatimAPI) buildSearchURL(req *NominatimSearchRequest) (string, error) {\n\turls := fmt.Sprintf(\"%s%s\/search.php\", api.c.BaseURL(), NominatimPathPrefix)\n\tu, err := url.Parse(urls)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t\/\/ Add key and other parameters to the query string\n\tq := u.Query()\n\tq.Set(\"format\", \"json\")\n\tq.Set(\"q\", req.Query)\n\tq.Set(\"addressdetails\", \"1\")\n\tif req.Limit > 0 {\n\t\tq.Set(\"limit\", fmt.Sprintf(\"%d\", req.Limit))\n\t}\n\tif len(req.CountryCodes) > 0 {\n\t\tq.Set(\"countrycodes\", strings.Join(req.CountryCodes, \",\"))\n\t}\n\tif len(req.ViewBox) == 4 {\n\t\tq.Set(\"viewbox\", fmt.Sprintf(\"%f,%f,%f,%f\", req.ViewBox[0], req.ViewBox[1], req.ViewBox[2], req.ViewBox[3]))\n\t}\n\tif len(req.ExcludePlaceIds) > 0 {\n\t\tq.Set(\"exclude_place_ids\", strings.Join(req.ExcludePlaceIds, \",\"))\n\t}\n\tif req.Bounded != nil {\n\t\tif *req.Bounded {\n\t\t\tq.Set(\"bounded\", \"1\")\n\t\t} else {\n\t\t\tq.Set(\"bounded\", \"0\")\n\t\t}\n\t}\n\t\/\/ TODO(oe): routewidth\n\tif req.RouteWidth != nil {\n\t\tq.Set(\"routewidth\", fmt.Sprintf(\"%f\", *req.RouteWidth))\n\t}\n\tif req.OSMType != \"\" {\n\t\tq.Set(\"osm_type\", req.OSMType)\n\t}\n\tif req.OSMId != \"\" {\n\t\tq.Set(\"osm_id\", req.OSMId)\n\t}\n\n\t\/\/ No key here!\n\tu.RawQuery = q.Encode()\n\treturn u.String(), nil\n}\n\ntype NominatimSearchRequest struct {\n\tQuery           string\n\tLimit           int\n\tCountryCodes    []string\n\tViewBox         []float64\n\tExcludePlaceIds []string\n\tBounded         *bool\n\tRouteWidth      *float64\n\tOSMType         string\n\tOSMId           string\n}\n\ntype NominatimSearchResponse struct {\n\tResults []*NominatimSearchResult\n}\n\ntype NominatimSearchResult struct {\n\tAddress *struct {\n\t\tCity          string `json:\"city,omitempty\"`\n\t\tCityDistrict  string `json:\"city_district,omitempty\"`\n\t\tContinent     string `json:\"continent,omitempty\"`\n\t\tCountry       string `json:\"country,omitempty\"`\n\t\tCountryCode   string `json:\"country_code,omitempty\"`\n\t\tCounty        string `json:\"county,omitempty\"`\n\t\tHamlet        string `json:\"hamlet,omitempty\"`\n\t\tHouseNumber   string `json:\"house_number,omitempty\"`\n\t\tPedestrian    string `json:\"pedestrian,omitempty\"`\n\t\tNeighbourhood string `json:\"neighbourhood,omitempty\"`\n\t\tPostCode      string `json:\"postcode,omitempty\"`\n\t\tRoad          string `json:\"road,omitempty\"`\n\t\tState         string `json:\"state,omitempty\"`\n\t\tStateDistrict string `json:\"state_district,omitempty\"`\n\t\tSuburb        string `json:\"suburb,omitempty\"`\n\t} `json:\"address,omitempty\"`\n\t\/\/BoundingBox []float64 `json:\"boundingbox,omitempty\"`\n\tClass       string  `json:\"class,omitempty\"`\n\tDisplayName string  `json:\"display_name,omitempty\"`\n\tImportance  float64 `json:\"importance,omitempty\"`\n\tLatitude    float64 `json:\"lat,string,omitempty\"`\n\tLongitude   float64 `json:\"lon,string,omitempty\"`\n\tOSMId       string  `json:\"osm_id,omitempty\"`\n\tOSMType     string  `json:\"osm_type,omitempty\"`\n\tPlaceId     string  `json:\"place_id,omitempty\"`\n\tType        string  `json:\"type,omitempty\"`\n\tLicense     string  `json:\"licence,omitempty\"` \/\/ typo in API?\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\n\/\/ Handles notifications from Jenkins and queues a message in RabbitMQ with the\n\/\/ details of the notification.\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"github.com\/streadway\/amqp\"\n)\n\nvar (\n\tamqpURI      = flag.String(\"uri\", \"amqp:\/\/guest:guest@localhost:5672\/\", \"AMQP URI\")\n\texchangeName = flag.String(\"exchange\", \"amqp.fanout\", \"Durable AMQP exchange name\")\n\tport         = flag.String(\"post\", \":8080\", \"Listen on port\")\n\tchanSize     = flag.Int(\"queue\", 5, \"Size of channel for notifications\")\n\tkey          = flag.String(\"key\", \"notifications.jenkins.build\", \"Routing key\")\n)\n\ntype Notification struct {\n\tBuild struct {\n\t\tNumber float64 `json:\"number\"`\n\t\tPhase  string  `json:\"phase\"`\n\t\tUrl    string  `json:\"url\"`\n\t} `json:\"build\"`\n\tName string `json:\"name\"`\n\tUrl  string `json:\"url\"`\n}\n\nfunc init() {\n\tflag.Parse()\n}\n\ntype NotificationsHandler struct {\n\tnotifications chan Notification\n}\n\nfunc (n NotificationsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tdecoder := json.NewDecoder(r.Body)\n\tvar not Notification\n\terr := decoder.Decode(&not)\n\tif err != nil {\n\t\tfmt.Printf(\"%s\\n\", err)\n\t} else {\n\t\tn.notifications <- not\n\t}\n}\n\nfunc main() {\n\tnotifications := make(chan Notification, *chanSize)\n\thttp.Handle(\"\/notifications\", NotificationsHandler{notifications})\n\tgo sendNotifications(notifications)\n\thttp.ListenAndServe(*port, nil)\n}\n\nfunc sendNotifications(notifications chan Notification) {\n\tconnection, err := amqp.Dial(*amqpURI)\n\tif err != nil {\n\t\tlog.Fatalf(\"Dial: %s\", err)\n\t}\n\tdefer connection.Close()\n\tchannel, err := connection.Channel()\n\tif err != nil {\n\t\tlog.Fatalf(\"Channel: %s\", err)\n\t}\n\terr = channel.ExchangeDeclare(\n\t\t*exchangeName, \/\/ name\n\t\t\"fanout\",      \/\/ type\n\t\ttrue,          \/\/ durable\n\t\tfalse,         \/\/ auto-deleted\n\t\tfalse,         \/\/ internal\n\t\tfalse,         \/\/ noWait\n\t\tnil,           \/\/ arguments\n\t)\n\tif err != nil {\n\t\tlog.Fatalf(\"Exchange Declare: %s\", err)\n\t}\n\n\tfor {\n\t\tselect {\n\t\tcase n := <-notifications:\n\t\t\tbody, err := json.Marshal(n)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tchannel.Publish(\n\t\t\t\t*exchangeName,\n\t\t\t\t*key,\n\t\t\t\tfalse, \/\/ mandatory\n\t\t\t\tfalse, \/\/ immediate\n\t\t\t\tamqp.Publishing{\n\t\t\t\t\tHeaders:         amqp.Table{},\n\t\t\t\t\tContentType:     \"application\/json\",\n\t\t\t\t\tContentEncoding: \"\",\n\t\t\t\t\tBody:            body,\n\t\t\t\t\tDeliveryMode:    amqp.Transient,\n\t\t\t\t\tPriority:        0,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t}\n}\n<commit_msg>Don't Fatal parsing errors, we can continue from these.<commit_after>package main\n\n\/\/ Handles notifications from Jenkins and queues a message in RabbitMQ with the\n\/\/ details of the notification.\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"github.com\/streadway\/amqp\"\n)\n\nvar (\n\tamqpURI      = flag.String(\"uri\", \"amqp:\/\/guest:guest@localhost:5672\/\", \"AMQP URI\")\n\texchangeName = flag.String(\"exchange\", \"amqp.fanout\", \"Durable AMQP exchange name\")\n\tport         = flag.String(\"post\", \":8080\", \"Listen on port\")\n\tchanSize     = flag.Int(\"queue\", 5, \"Size of channel for notifications\")\n\tkey          = flag.String(\"key\", \"notifications.jenkins.build\", \"Routing key\")\n)\n\ntype Notification struct {\n\tBuild struct {\n\t\tNumber float64 `json:\"number\"`\n\t\tPhase  string  `json:\"phase\"`\n\t\tUrl    string  `json:\"url\"`\n\t} `json:\"build\"`\n\tName string `json:\"name\"`\n\tUrl  string `json:\"url\"`\n}\n\nfunc init() {\n\tflag.Parse()\n}\n\ntype NotificationsHandler struct {\n\tnotifications chan Notification\n}\n\nfunc (n NotificationsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tdecoder := json.NewDecoder(r.Body)\n\tvar not Notification\n\terr := decoder.Decode(&not)\n\tif err != nil {\n\t\tlog.Println(err)\n\t} else {\n\t\tn.notifications <- not\n\t}\n}\n\nfunc main() {\n\tnotifications := make(chan Notification, *chanSize)\n\thttp.Handle(\"\/notifications\", NotificationsHandler{notifications})\n\tgo sendNotifications(notifications)\n\n    log.Printf(\"Listening on %s\\n\", *port)\n\thttp.ListenAndServe(*port, nil)\n}\n\nfunc sendNotifications(notifications chan Notification) {\n\tconnection, err := amqp.Dial(*amqpURI)\n\tif err != nil {\n\t\tlog.Fatalf(\"Dial: %s\", err)\n\t}\n\tdefer connection.Close()\n\tchannel, err := connection.Channel()\n\tif err != nil {\n\t\tlog.Fatalf(\"Channel: %s\", err)\n\t}\n\terr = channel.ExchangeDeclare(\n\t\t*exchangeName, \/\/ name\n\t\t\"fanout\",      \/\/ type\n\t\ttrue,          \/\/ durable\n\t\tfalse,         \/\/ auto-deleted\n\t\tfalse,         \/\/ internal\n\t\tfalse,         \/\/ noWait\n\t\tnil,           \/\/ arguments\n\t)\n\tif err != nil {\n\t\tlog.Fatalf(\"Exchange Declare: %s\", err)\n\t}\n\n    log.Printf(\"Connected to %s\\n\", *amqpURI)\n\tfor {\n\t\tselect {\n\t\tcase n := <-notifications:\n\t\t\tbody, err := json.Marshal(n)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tchannel.Publish(\n\t\t\t\t*exchangeName,\n\t\t\t\t*key,\n\t\t\t\tfalse, \/\/ mandatory\n\t\t\t\tfalse, \/\/ immediate\n\t\t\t\tamqp.Publishing{\n\t\t\t\t\tHeaders:         amqp.Table{},\n\t\t\t\t\tContentType:     \"application\/json\",\n\t\t\t\t\tContentEncoding: \"\",\n\t\t\t\t\tBody:            body,\n\t\t\t\t\tDeliveryMode:    amqp.Transient,\n\t\t\t\t\tPriority:        0,\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package amiando\n\nimport \"fmt\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Event\n\ntype BasicEventData struct {\n\tHostID                 ID      `json:\"hostId\"`\n\tTitle                  string  `json:\"title\"`\n\tCountry                string  `json:\"country\"`\n\tLanguage               string  `json:\"language\"`\n\tStartDate              string  `json:\"selectedDate\"`\n\tEndDate                string  `json:\"selectedEndDate\"`\n\tTimezone               string  `json:\"timezone\"`\n\tVisibility             string  `json:\"visibility\"`\n\tIdentifier             string  `json:\"identifier\"`\n\tDescription            string  `json:\"description\"`\n\tShortDescription       string  `json:\"shortDescription\"`\n\tEventType              string  `json:\"eventType\"`\n\tOrganisatorDisplayName string  `json:\"organisatorDisplayName\"`\n\tPartnerEventUrl        string  `json:\"partnerEventUrl\"`\n\tLocation               string  `json:\"location\"`\n\tLocationDescription    string  `json:\"locationDescription\"`\n\tStreet                 string  `json:\"street2\"`\n\tZipCode                string  `json:\"zipCode\"`\n\tCity                   string  `json:\"city\"`\n\tState                  string  `json:\"state\"`\n\tCreationTime           string  `json:\"creationTime\"`\n\tLastModified           string  `json:\"lastModified\"`\n\tLongitude              float64 `json:\"longitude\"`\n\tLatitude               float64 `json:\"latitude\"`\n}\n\ntype Event struct {\n\tResultBase\n\tBasicEventData `json:\"event\"`\n\tApi            *Api\n\tIdentifier     string\n\tInternalID     ID\n}\n\nfunc NewEvent(api *Api, identifier string) (event *Event, err error) {\n\tevent = &Event{\n\t\tApi:        api,\n\t\tIdentifier: identifier,\n\t}\n\n\t\/\/ Search for event with identifier\n\ttype Result struct {\n\t\tResultBase\n\t\tIds []ID `json:\"ids\"`\n\t}\n\tvar result Result\n\terr = event.Api.Call(\"event\/find?identifier=%s\", identifier, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(result.Ids) == 0 {\n\t\treturn nil, fmt.Errorf(\"No event found for identifier '%s'\", identifier)\n\t}\n\t\/\/ Find event with exact match of identifier\n\t\/\/ because API find returns all events whose identifiers include the searched one\n\tfor _, id := range result.Ids {\n\t\ttype Result struct {\n\t\t\tResultBase\n\t\t\tEvent BasicEventData `json:\"event\"`\n\t\t}\n\t\tvar result Result\n\t\terr = event.Api.Call(\"event\/%v\", id, &result)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif result.Event.Identifier == identifier {\n\t\t\tevent.InternalID = id\n\t\t\tbreak\n\t\t}\n\t}\n\tif event.InternalID == 0 {\n\t\treturn nil, fmt.Errorf(\"No exact match found for identifier '%s'\", identifier)\n\t}\n\n\terr = event.Read(event)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn event, nil\n}\n\nfunc (self *Event) Read(out ErrorReporter) (err error) {\n\treturn self.Api.Call(\"event\/%v\", self.InternalID, out)\n}\n\nfunc (self *Event) PaymentIDs() (ids []ID, err error) {\n\ttype Result struct {\n\t\tResultBase\n\t\tPayments []ID `json:\"payments\"`\n\t}\n\tvar result Result\n\terr = self.Api.Call(\"event\/%v\/payments\", self.InternalID, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.Payments, nil\n}\n\nfunc (self *Event) TicketIDs() (ids []ID, err error) {\n\ttype Result struct {\n\t\tResultBase\n\t\tIds []ID `json:\"ids\"`\n\t}\n\tvar result Result\n\terr = self.Api.Call(\"ticket\/find?eventId=%v\", self.InternalID, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.Ids, nil\n}\n\nfunc (self *Event) Participants() (participants []*Participant, err error) {\n\tparticipants = []*Participant{}\n\n\tpaymentIDs, err := self.PaymentIDs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, paymentID := range paymentIDs {\n\t\tticketIDs, err := self.Api.TicketIDsOfPayment(paymentID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor i, ticketID := range ticketIDs {\n\t\t\tparticipant := &Participant{\n\t\t\t\tEvent:     self,\n\t\t\t\tPaymentID: paymentID,\n\t\t\t\tTicketID:  ticketID,\n\t\t\t}\n\n\t\t\terr = self.Api.Payment(paymentID, participant)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t\/\/ Save payment UserData because it will be overwritten by the ticket UserData \n\t\t\tuserData := participant.UserData\n\n\t\t\terr = self.Api.Ticket(ticketID, participant)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t\/\/ If there is no ticket UserData use payment UserData for the first ticket\n\t\t\tif i == 0 && len(participant.UserData) == 0 {\n\t\t\t\tparticipant.UserData = userData\n\t\t\t}\n\n\t\t\tparticipants = append(participants, participant)\n\t\t}\n\t}\n\n\treturn participants, nil\n}\n\nfunc (self *Event) EnumParticipants() (<-chan *Participant, <-chan error) {\n\tp := make(chan *Participant, 32)\n\te := make(chan error, 1)\n\n\tgo func() {\n\t\tdefer close(p)\n\t\tdefer close(e)\n\n\t\tpaymentIDs, err := self.PaymentIDs()\n\t\tif err != nil {\n\t\t\te <- err\n\t\t\treturn\n\t\t}\n\t\tfor _, paymentID := range paymentIDs {\n\t\t\tticketIDs, err := self.Api.TicketIDsOfPayment(paymentID)\n\t\t\tif err != nil {\n\t\t\t\te <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor i, ticketID := range ticketIDs {\n\t\t\t\tparticipant := &Participant{\n\t\t\t\t\tEvent:     self,\n\t\t\t\t\tPaymentID: paymentID,\n\t\t\t\t\tTicketID:  ticketID,\n\t\t\t\t}\n\n\t\t\t\terr = self.Api.Payment(paymentID, participant)\n\t\t\t\tif err != nil {\n\t\t\t\t\te <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t\/\/ Save payment UserData because it will be overwritten by the ticket UserData \n\t\t\t\tuserData := participant.UserData\n\n\t\t\t\terr = self.Api.Ticket(ticketID, participant)\n\t\t\t\tif err != nil {\n\t\t\t\t\te <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t\/\/ If there is no ticket UserData use payment UserData for the first ticket\n\t\t\t\tif i == 0 && len(participant.UserData) == 0 {\n\t\t\t\t\tparticipant.UserData = userData\n\t\t\t\t}\n\n\t\t\t\tp <- participant\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn p, e\n}\n<commit_msg>made BasicEventData Event.Event field for correct unmarshalling<commit_after>package amiando\n\nimport \"fmt\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Event\n\ntype BasicEventData struct {\n\tHostID                 ID      `json:\"hostId\"`\n\tTitle                  string  `json:\"title\"`\n\tCountry                string  `json:\"country\"`\n\tLanguage               string  `json:\"language\"`\n\tStartDate              string  `json:\"selectedDate\"`\n\tEndDate                string  `json:\"selectedEndDate\"`\n\tTimezone               string  `json:\"timezone\"`\n\tVisibility             string  `json:\"visibility\"`\n\tIdentifier             string  `json:\"identifier\"`\n\tDescription            string  `json:\"description\"`\n\tShortDescription       string  `json:\"shortDescription\"`\n\tEventType              string  `json:\"eventType\"`\n\tOrganisatorDisplayName string  `json:\"organisatorDisplayName\"`\n\tPartnerEventUrl        string  `json:\"partnerEventUrl\"`\n\tLocation               string  `json:\"location\"`\n\tLocationDescription    string  `json:\"locationDescription\"`\n\tStreet                 string  `json:\"street2\"`\n\tZipCode                string  `json:\"zipCode\"`\n\tCity                   string  `json:\"city\"`\n\tState                  string  `json:\"state\"`\n\tCreationTime           string  `json:\"creationTime\"`\n\tLastModified           string  `json:\"lastModified\"`\n\tLongitude              float64 `json:\"longitude\"`\n\tLatitude               float64 `json:\"latitude\"`\n}\n\ntype Event struct {\n\tResultBase\n\tEvent      BasicEventData `json:\"event\"`\n\tApi        *Api           `json:\"-\"`\n\tIdentifier string         `json:\"-\"`\n\tInternalID ID             `json:\"-\"`\n}\n\nfunc NewEvent(api *Api, identifier string) (event *Event, err error) {\n\tevent = &Event{\n\t\tApi:        api,\n\t\tIdentifier: identifier,\n\t}\n\n\t\/\/ Search for event with identifier\n\ttype Result struct {\n\t\tResultBase\n\t\tIds []ID `json:\"ids\"`\n\t}\n\tvar result Result\n\terr = event.Api.Call(\"event\/find?identifier=%s\", identifier, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(result.Ids) == 0 {\n\t\treturn nil, fmt.Errorf(\"No event found for identifier '%s'\", identifier)\n\t}\n\t\/\/ Find event with exact match of identifier\n\t\/\/ because API find returns all events whose identifiers include the searched one\n\tfor _, id := range result.Ids {\n\t\ttype Result struct {\n\t\t\tResultBase\n\t\t\tEvent BasicEventData `json:\"event\"`\n\t\t}\n\t\tvar result Result\n\t\terr = event.Api.Call(\"event\/%v\", id, &result)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif result.Event.Identifier == identifier {\n\t\t\tevent.InternalID = id\n\t\t\tbreak\n\t\t}\n\t}\n\tif event.InternalID == 0 {\n\t\treturn nil, fmt.Errorf(\"No exact match found for identifier '%s'\", identifier)\n\t}\n\n\terr = event.Read(event)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn event, nil\n}\n\nfunc (self *Event) Read(out ErrorReporter) (err error) {\n\treturn self.Api.Call(\"event\/%v\", self.InternalID, out)\n}\n\nfunc (self *Event) PaymentIDs() (ids []ID, err error) {\n\ttype Result struct {\n\t\tResultBase\n\t\tPayments []ID `json:\"payments\"`\n\t}\n\tvar result Result\n\terr = self.Api.Call(\"event\/%v\/payments\", self.InternalID, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.Payments, nil\n}\n\nfunc (self *Event) TicketIDs() (ids []ID, err error) {\n\ttype Result struct {\n\t\tResultBase\n\t\tIds []ID `json:\"ids\"`\n\t}\n\tvar result Result\n\terr = self.Api.Call(\"ticket\/find?eventId=%v\", self.InternalID, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.Ids, nil\n}\n\nfunc (self *Event) Participants() (participants []*Participant, err error) {\n\tparticipants = []*Participant{}\n\n\tpaymentIDs, err := self.PaymentIDs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, paymentID := range paymentIDs {\n\t\tticketIDs, err := self.Api.TicketIDsOfPayment(paymentID)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfor i, ticketID := range ticketIDs {\n\t\t\tparticipant := &Participant{\n\t\t\t\tEvent:     self,\n\t\t\t\tPaymentID: paymentID,\n\t\t\t\tTicketID:  ticketID,\n\t\t\t}\n\n\t\t\terr = self.Api.Payment(paymentID, participant)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t\/\/ Save payment UserData because it will be overwritten by the ticket UserData \n\t\t\tuserData := participant.UserData\n\n\t\t\terr = self.Api.Ticket(ticketID, participant)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t\/\/ If there is no ticket UserData use payment UserData for the first ticket\n\t\t\tif i == 0 && len(participant.UserData) == 0 {\n\t\t\t\tparticipant.UserData = userData\n\t\t\t}\n\n\t\t\tparticipants = append(participants, participant)\n\t\t}\n\t}\n\n\treturn participants, nil\n}\n\nfunc (self *Event) EnumParticipants() (<-chan *Participant, <-chan error) {\n\tp := make(chan *Participant, 32)\n\te := make(chan error, 1)\n\n\tgo func() {\n\t\tdefer close(p)\n\t\tdefer close(e)\n\n\t\tpaymentIDs, err := self.PaymentIDs()\n\t\tif err != nil {\n\t\t\te <- err\n\t\t\treturn\n\t\t}\n\t\tfor _, paymentID := range paymentIDs {\n\t\t\tticketIDs, err := self.Api.TicketIDsOfPayment(paymentID)\n\t\t\tif err != nil {\n\t\t\t\te <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor i, ticketID := range ticketIDs {\n\t\t\t\tparticipant := &Participant{\n\t\t\t\t\tEvent:     self,\n\t\t\t\t\tPaymentID: paymentID,\n\t\t\t\t\tTicketID:  ticketID,\n\t\t\t\t}\n\n\t\t\t\terr = self.Api.Payment(paymentID, participant)\n\t\t\t\tif err != nil {\n\t\t\t\t\te <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t\/\/ Save payment UserData because it will be overwritten by the ticket UserData \n\t\t\t\tuserData := participant.UserData\n\n\t\t\t\terr = self.Api.Ticket(ticketID, participant)\n\t\t\t\tif err != nil {\n\t\t\t\t\te <- err\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t\/\/ If there is no ticket UserData use payment UserData for the first ticket\n\t\t\t\tif i == 0 && len(participant.UserData) == 0 {\n\t\t\t\t\tparticipant.UserData = userData\n\t\t\t\t}\n\n\t\t\t\tp <- participant\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn p, e\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) Liam Stanley <me@liamstanley.io>. All rights reserved. Use\n\/\/ of this source code is governed by the MIT license that can be found in\n\/\/ the LICENSE file.\n\npackage girc\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\teventSpace byte = 0x20 \/\/ Separator.\n\tmaxLength       = 510  \/\/ Maximum length is 510 (2 for line endings).\n)\n\n\/\/ cutCRFunc is used to trim CR characters from prefixes\/messages.\nfunc cutCRFunc(r rune) bool {\n\treturn r == '\\r' || r == '\\n'\n}\n\n\/\/ Event represents an IRC protocol message, see RFC1459 section 2.3.1\n\/\/\n\/\/    <message>  :: [':' <prefix> <SPACE>] <command> <params> <crlf>\n\/\/    <prefix>   :: <servername> | <nick> ['!' <user>] ['@' <host>]\n\/\/    <command>  :: <letter>{<letter>} | <number> <number> <number>\n\/\/    <SPACE>    :: ' '{' '}\n\/\/    <params>   :: <SPACE> [':' <trailing> | <middle> <params>]\n\/\/    <middle>   :: <Any *non-empty* sequence of octets not including SPACE or NUL\n\/\/                   or CR or LF, the first of which may not be ':'>\n\/\/    <trailing> :: <Any, possibly empty, sequence of octets not including NUL or\n\/\/                   CR or LF>\n\/\/    <crlf>     :: CR LF\ntype Event struct {\n\tSource        *Source  \/\/ The source of the event.\n\tTags          Tags     \/\/ IRCv3 style message tags. Only use if network supported.\n\tCommand       string   \/\/ the IRC command, e.g. JOIN, PRIVMSG, KILL.\n\tParams        []string \/\/ parameters to the command. Commonly nickname, channel, etc.\n\tTrailing      string   \/\/ any trailing data. e.g. with a PRIVMSG, this is the message text.\n\tEmptyTrailing bool     \/\/ if true, trailing prefix (:) will be added even if Event.Trailing is empty.\n\tSensitive     bool     \/\/ if the message is sensitive (e.g. and should not be logged).\n}\n\n\/\/ ParseEvent takes a string and attempts to create a Event struct.\n\/\/\n\/\/ Returns nil if the Event is invalid.\nfunc ParseEvent(raw string) (e *Event) {\n\t\/\/ Ignore empty events.\n\tif raw = strings.TrimFunc(raw, cutCRFunc); len(raw) < 2 {\n\t\treturn nil\n\t}\n\n\ti, j := 0, 0\n\te = &Event{}\n\n\tif raw[0] == prefixTag {\n\t\t\/\/ Tags end with a space.\n\t\ti = strings.IndexByte(raw, eventSpace)\n\n\t\tif i < 2 {\n\t\t\treturn nil\n\t\t}\n\n\t\te.Tags = ParseTags(raw[1:i])\n\t\traw = raw[i+1:]\n\t}\n\n\tif raw[0] == messagePrefix {\n\t\t\/\/ Prefix ends with a space.\n\t\ti = strings.IndexByte(raw, eventSpace)\n\n\t\t\/\/ Prefix string must not be empty if the indicator is present.\n\t\tif i < 2 {\n\t\t\treturn nil\n\t\t}\n\n\t\te.Source = ParseSource(raw[1:i])\n\n\t\t\/\/ Skip space at the end of the prefix.\n\t\ti++\n\t}\n\n\t\/\/ Find end of command.\n\tj = i + strings.IndexByte(raw[i:], eventSpace)\n\n\t\/\/ Extract command.\n\tif j < i {\n\t\te.Command = strings.ToUpper(raw[i:])\n\t\treturn e\n\t}\n\n\te.Command = strings.ToUpper(raw[i:j])\n\t\/\/ Skip space after command.\n\tj++\n\n\t\/\/ Find prefix for trailer.\n\ti = bytes.Index([]byte(raw[j:]), []byte{eventSpace, messagePrefix})\n\tif i != -1 {\n\t\ti += 1\n\t}\n\n\tif i < 0 || raw[j+i-1] != eventSpace {\n\t\t\/\/ No trailing argument.\n\t\te.Params = strings.Split(raw[j:], string(eventSpace))\n\t\treturn e\n\t}\n\n\t\/\/ Compensate for index on substring.\n\ti = i + j\n\n\t\/\/ Check if we need to parse arguments.\n\tif i > j {\n\t\te.Params = strings.Split(raw[j:i-1], string(eventSpace))\n\t}\n\n\te.Trailing = raw[i+1:]\n\n\t\/\/ We need to re-encode the trailing argument even if it was empty.\n\tif len(e.Trailing) <= 0 {\n\t\te.EmptyTrailing = true\n\t}\n\n\treturn e\n}\n\n\/\/ Len calculates the length of the string representation of event.\nfunc (e *Event) Len() (length int) {\n\tif e.Tags != nil {\n\t\t\/\/ Include tags and trailing space.\n\t\tlength = e.Tags.Len() + 1\n\t}\n\tif e.Source != nil {\n\t\t\/\/ Include prefix and trailing space.\n\t\tlength += e.Source.Len() + 2\n\t}\n\n\tlength += len(e.Command)\n\n\tif len(e.Params) > 0 {\n\t\tlength += len(e.Params)\n\n\t\tfor i := 0; i < len(e.Params); i++ {\n\t\t\tlength += len(e.Params[i])\n\t\t}\n\t}\n\n\tif len(e.Trailing) > 0 || e.EmptyTrailing {\n\t\t\/\/ Include prefix and space.\n\t\tlength += len(e.Trailing) + 2\n\t}\n\n\treturn\n}\n\n\/\/ Bytes returns a []byte representation of event. Strips all newlines and\n\/\/ carriage returns.\n\/\/\n\/\/ Per RFC2812 section 2.3, messages should not exceed 512 characters in\n\/\/ length. This method forces that limit by discarding any characters\n\/\/ exceeding the length limit.\nfunc (e *Event) Bytes() []byte {\n\tbuffer := new(bytes.Buffer)\n\n\t\/\/ Tags.\n\tif e.Tags != nil {\n\t\te.Tags.writeTo(buffer)\n\t}\n\n\t\/\/ Event prefix.\n\tif e.Source != nil {\n\t\tbuffer.WriteByte(messagePrefix)\n\t\te.Source.writeTo(buffer)\n\t\tbuffer.WriteByte(eventSpace)\n\t}\n\n\t\/\/ Command is required.\n\tbuffer.WriteString(e.Command)\n\n\t\/\/ Space separated list of arguments.\n\tif len(e.Params) > 0 {\n\t\tbuffer.WriteByte(eventSpace)\n\t\tbuffer.WriteString(strings.Join(e.Params, string(eventSpace)))\n\t}\n\n\tif len(e.Trailing) > 0 || e.EmptyTrailing {\n\t\tbuffer.WriteByte(eventSpace)\n\t\tbuffer.WriteByte(messagePrefix)\n\t\tbuffer.WriteString(e.Trailing)\n\t}\n\n\t\/\/ We need the limit the buffer length.\n\tif buffer.Len() > (maxLength) {\n\t\tif e.Tags != nil {\n\t\t\t\/\/ regular message, max tag length, and the splitting space.\n\t\t\tbuffer.Truncate(maxLength + maxTagLength + 1)\n\t\t} else {\n\t\t\tbuffer.Truncate(maxLength)\n\t\t}\n\t}\n\n\tout := buffer.Bytes()\n\n\t\/\/ Strip newlines and carriage returns.\n\tfor i := 0; i < len(out); i++ {\n\t\tif out[i] == 0x0A || out[i] == 0x0D {\n\t\t\tout = append(out[:i], out[i+1:]...)\n\t\t\ti-- \/\/ Decrease the index so we can pick up where we left off.\n\t\t}\n\t}\n\n\treturn out\n}\n\n\/\/ String returns a string representation of this event. Strips all newlines\n\/\/ and carriage returns.\nfunc (e *Event) String() string {\n\treturn string(e.Bytes())\n}\n\n\/\/ Pretty returns a prettified string of the event. If the event doesn't\n\/\/ support prettification, ok is false. Pretty is not just useful to make\n\/\/ an event prettier, but also to filter out events that most don't visually\n\/\/ see in normal IRC clients. e.g. most clients don't show WHO queries.\nfunc (e *Event) Pretty() (out string, ok bool) {\n\tif e.Command == INITIALIZED {\n\t\treturn fmt.Sprintf(\"[*] connection to %s initialized\", e.Trailing), true\n\t}\n\n\tif e.Command == CONNECTED {\n\t\treturn fmt.Sprintf(\"[*] successfully connected to %s\", e.Trailing), true\n\t}\n\n\tif (e.Command == PRIVMSG || e.Command == NOTICE) && len(e.Params) > 0 {\n\t\treturn fmt.Sprintf(\"[%s] (%s) %s\", strings.Join(e.Params, \",\"), e.Source.Name, e.Trailing), true\n\t}\n\n\tif e.Command == RPL_MOTD || e.Command == RPL_MOTDSTART ||\n\t\te.Command == RPL_WELCOME || e.Command == RPL_YOURHOST ||\n\t\te.Command == RPL_CREATED || e.Command == RPL_LUSERCLIENT {\n\t\treturn fmt.Sprintf(\"[*] \" + e.Trailing), true\n\t}\n\n\tif e.Command == JOIN && len(e.Params) > 0 {\n\t\treturn fmt.Sprintf(\"[*] %s has joined %s\", e.Source.Name, e.Params[0]), true\n\t}\n\n\tif e.Command == PART && len(e.Params) > 0 {\n\t\treturn fmt.Sprintf(\"[*] %s has left %s (%s)\", e.Source.Name, e.Params[0], e.Trailing), true\n\t}\n\n\tif e.Command == ERROR {\n\t\treturn fmt.Sprintf(\"[*] an error occurred: %s\", e.Trailing), true\n\t}\n\n\tif e.Command == QUIT {\n\t\treturn fmt.Sprintf(\"[*] %s has quit (%s)\", e.Source.Name, e.Trailing), true\n\t}\n\n\tif e.Command == KICK && len(e.Params) == 2 {\n\t\treturn fmt.Sprintf(\"[%s] *** %s has kicked %s: %s\", e.Params[0], e.Source.Name, e.Params[1], e.Trailing), true\n\t}\n\n\tif e.Command == NICK && len(e.Params) == 1 {\n\t\treturn fmt.Sprintf(\"[*] %s is now known as %s\", e.Source.Name, e.Params[0]), true\n\t}\n\n\tif e.Command == TOPIC && len(e.Params) > 0 {\n\t\treturn fmt.Sprintf(\"[%s] *** %s has set the topic to: %s\", e.Params[len(e.Params)-1], e.Source.Name, e.Trailing), true\n\t}\n\n\tif e.Command == MODE && len(e.Params) > 2 {\n\t\treturn fmt.Sprintf(\"[%s] %s set modes: %s\", e.Params[0], e.Source.Name, strings.Join(e.Params[1:], \" \")), true\n\t}\n\n\tif e.Command == CAP_AWAY {\n\t\tif len(e.Trailing) > 0 {\n\t\t\treturn fmt.Sprintf(\"[*] %s is now away: %s\", e.Source.Name, e.Trailing), true\n\t\t}\n\n\t\treturn fmt.Sprintf(\"[*] %s is no longer away\", e.Source.Name), true\n\t}\n\n\tif e.Command == CAP_CHGHOST && len(e.Params) == 2 {\n\t\treturn fmt.Sprintf(\"[*] %s has changed their host to %s (was %s)\", e.Source.Name, e.Params[1], e.Source.Host), true\n\t}\n\n\tif e.Command == CAP_ACCOUNT && len(e.Params) == 1 {\n\t\tif e.Params[0] == \"*\" {\n\t\t\treturn fmt.Sprintf(\"[*] %s has become un-authenticated\", e.Source.Name), true\n\t\t}\n\n\t\treturn fmt.Sprintf(\"[*] %s has authenticated for account: %s\", e.Source.Name, e.Params[0]), true\n\t}\n\n\treturn \"\", false\n}\n\n\/\/ IsAction checks to see if the event is a PRIVMSG, and is an ACTION (\/me).\nfunc (e *Event) IsAction() bool {\n\tif len(e.Trailing) <= 0 || e.Command != PRIVMSG {\n\t\treturn false\n\t}\n\n\tif !strings.HasPrefix(e.Trailing, \"\\001ACTION\") || e.Trailing[len(e.Trailing)-1] != ctcpDelim {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ IsFromChannel checks to see if a message was from a channel (rather than\n\/\/ a private message).\nfunc (e *Event) IsFromChannel() bool {\n\tif len(e.Params) != 1 {\n\t\treturn false\n\t}\n\n\tif e.Command != \"PRIVMSG\" || !IsValidChannel(e.Params[0]) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ IsFromUser checks to see if a message was from a user (rather than a\n\/\/ channel).\nfunc (e *Event) IsFromUser() bool {\n\tif len(e.Params) != 1 {\n\t\treturn false\n\t}\n\n\tif e.Command != \"PRIVMSG\" || !IsValidNick(e.Params[0]) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ StripAction returns the stripped version of the action encoding from a\n\/\/ PRIVMSG ACTION (\/me).\nfunc (e *Event) StripAction() string {\n\tif !e.IsAction() || len(e.Trailing) < 9 {\n\t\treturn e.Trailing\n\t}\n\n\treturn e.Trailing[8 : len(e.Trailing)-1]\n}\n\n\/\/ EventLimiter is a custom ticker which lets you rate limit sending events\n\/\/ to a function (e.g. Client.Send()), with optional burst support. See\n\/\/ NewEventLimiter() for more information.\ntype EventLimiter struct {\n\ttick     *time.Ticker\n\tthrottle chan time.Time\n\tfn       func(*Event) error\n}\n\n\/\/ loop is used to read events from the internal time.Ticker.\nfunc (el *EventLimiter) loop() {\n\t\/\/ This should exit itself once el.Stop() is called.\n\tfor t := range el.tick.C {\n\t\tel.throttle <- t\n\t}\n}\n\n\/\/ Stop closes the ticker, and prevents re-use of the EventLimiter. Use this\n\/\/ to prevent EventLimiter from keeping unnecessary pointers in memory.\nfunc (el *EventLimiter) Stop() {\n\tel.tick.Stop()\n\tel.fn = nil\n}\n\n\/\/ Send is the subtitute function used to send the event the the previously\n\/\/ specified send function.\n\/\/\n\/\/ This WILL panic if Stop() was already called on the EventLimiter.\nfunc (el *EventLimiter) Send(event *Event) error {\n\t\/\/ Ensure nobody is sending to it once it's closed.\n\tif el.fn == nil {\n\t\tpanic(\"attempted send on closed EventLimiter\")\n\t}\n\n\t<-el.throttle\n\treturn el.fn(event)\n}\n\n\/\/ SendAll sends a list of events to Send(). SendAll will return the first\n\/\/ error it gets when attempting to Send() to the predefined Send function.\n\/\/ It will not attempt to continue processing the list of events.\nfunc (el *EventLimiter) SendAll(events ...*Event) error {\n\tfor i := 0; i < len(events); i++ {\n\t\tif err := el.Send(events[i]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ NewEventLimiter returns a NewEventLimiter which can be used to rate limit\n\/\/ events being sent to a Send function. This does support bursting a\n\/\/ certain amount of messages if there are less than burstCount.\n\/\/\n\/\/ Ensure that Stop() is called on the returned EventLimiter, otherwise\n\/\/ the limiter may keep unwanted pointers to data in memory.\nfunc NewEventLimiter(burstCount int, rate time.Duration, eventFunc func(event *Event) error) *EventLimiter {\n\tlimiter := &EventLimiter{\n\t\ttick:     time.NewTicker(rate),\n\t\tthrottle: make(chan time.Time, burstCount),\n\t\tfn:       eventFunc,\n\t}\n\n\t\/\/ Push the ticket into the background. If you want to stop this, simply\n\t\/\/ use EventLimiter.Stop().\n\tgo limiter.loop()\n\n\treturn limiter\n}\n<commit_msg>add prettification for RPL_TOPIC<commit_after>\/\/ Copyright (c) Liam Stanley <me@liamstanley.io>. All rights reserved. Use\n\/\/ of this source code is governed by the MIT license that can be found in\n\/\/ the LICENSE file.\n\npackage girc\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\teventSpace byte = 0x20 \/\/ Separator.\n\tmaxLength       = 510  \/\/ Maximum length is 510 (2 for line endings).\n)\n\n\/\/ cutCRFunc is used to trim CR characters from prefixes\/messages.\nfunc cutCRFunc(r rune) bool {\n\treturn r == '\\r' || r == '\\n'\n}\n\n\/\/ Event represents an IRC protocol message, see RFC1459 section 2.3.1\n\/\/\n\/\/    <message>  :: [':' <prefix> <SPACE>] <command> <params> <crlf>\n\/\/    <prefix>   :: <servername> | <nick> ['!' <user>] ['@' <host>]\n\/\/    <command>  :: <letter>{<letter>} | <number> <number> <number>\n\/\/    <SPACE>    :: ' '{' '}\n\/\/    <params>   :: <SPACE> [':' <trailing> | <middle> <params>]\n\/\/    <middle>   :: <Any *non-empty* sequence of octets not including SPACE or NUL\n\/\/                   or CR or LF, the first of which may not be ':'>\n\/\/    <trailing> :: <Any, possibly empty, sequence of octets not including NUL or\n\/\/                   CR or LF>\n\/\/    <crlf>     :: CR LF\ntype Event struct {\n\tSource        *Source  \/\/ The source of the event.\n\tTags          Tags     \/\/ IRCv3 style message tags. Only use if network supported.\n\tCommand       string   \/\/ the IRC command, e.g. JOIN, PRIVMSG, KILL.\n\tParams        []string \/\/ parameters to the command. Commonly nickname, channel, etc.\n\tTrailing      string   \/\/ any trailing data. e.g. with a PRIVMSG, this is the message text.\n\tEmptyTrailing bool     \/\/ if true, trailing prefix (:) will be added even if Event.Trailing is empty.\n\tSensitive     bool     \/\/ if the message is sensitive (e.g. and should not be logged).\n}\n\n\/\/ ParseEvent takes a string and attempts to create a Event struct.\n\/\/\n\/\/ Returns nil if the Event is invalid.\nfunc ParseEvent(raw string) (e *Event) {\n\t\/\/ Ignore empty events.\n\tif raw = strings.TrimFunc(raw, cutCRFunc); len(raw) < 2 {\n\t\treturn nil\n\t}\n\n\ti, j := 0, 0\n\te = &Event{}\n\n\tif raw[0] == prefixTag {\n\t\t\/\/ Tags end with a space.\n\t\ti = strings.IndexByte(raw, eventSpace)\n\n\t\tif i < 2 {\n\t\t\treturn nil\n\t\t}\n\n\t\te.Tags = ParseTags(raw[1:i])\n\t\traw = raw[i+1:]\n\t}\n\n\tif raw[0] == messagePrefix {\n\t\t\/\/ Prefix ends with a space.\n\t\ti = strings.IndexByte(raw, eventSpace)\n\n\t\t\/\/ Prefix string must not be empty if the indicator is present.\n\t\tif i < 2 {\n\t\t\treturn nil\n\t\t}\n\n\t\te.Source = ParseSource(raw[1:i])\n\n\t\t\/\/ Skip space at the end of the prefix.\n\t\ti++\n\t}\n\n\t\/\/ Find end of command.\n\tj = i + strings.IndexByte(raw[i:], eventSpace)\n\n\t\/\/ Extract command.\n\tif j < i {\n\t\te.Command = strings.ToUpper(raw[i:])\n\t\treturn e\n\t}\n\n\te.Command = strings.ToUpper(raw[i:j])\n\t\/\/ Skip space after command.\n\tj++\n\n\t\/\/ Find prefix for trailer.\n\ti = bytes.Index([]byte(raw[j:]), []byte{eventSpace, messagePrefix})\n\tif i != -1 {\n\t\ti += 1\n\t}\n\n\tif i < 0 || raw[j+i-1] != eventSpace {\n\t\t\/\/ No trailing argument.\n\t\te.Params = strings.Split(raw[j:], string(eventSpace))\n\t\treturn e\n\t}\n\n\t\/\/ Compensate for index on substring.\n\ti = i + j\n\n\t\/\/ Check if we need to parse arguments.\n\tif i > j {\n\t\te.Params = strings.Split(raw[j:i-1], string(eventSpace))\n\t}\n\n\te.Trailing = raw[i+1:]\n\n\t\/\/ We need to re-encode the trailing argument even if it was empty.\n\tif len(e.Trailing) <= 0 {\n\t\te.EmptyTrailing = true\n\t}\n\n\treturn e\n}\n\n\/\/ Len calculates the length of the string representation of event.\nfunc (e *Event) Len() (length int) {\n\tif e.Tags != nil {\n\t\t\/\/ Include tags and trailing space.\n\t\tlength = e.Tags.Len() + 1\n\t}\n\tif e.Source != nil {\n\t\t\/\/ Include prefix and trailing space.\n\t\tlength += e.Source.Len() + 2\n\t}\n\n\tlength += len(e.Command)\n\n\tif len(e.Params) > 0 {\n\t\tlength += len(e.Params)\n\n\t\tfor i := 0; i < len(e.Params); i++ {\n\t\t\tlength += len(e.Params[i])\n\t\t}\n\t}\n\n\tif len(e.Trailing) > 0 || e.EmptyTrailing {\n\t\t\/\/ Include prefix and space.\n\t\tlength += len(e.Trailing) + 2\n\t}\n\n\treturn\n}\n\n\/\/ Bytes returns a []byte representation of event. Strips all newlines and\n\/\/ carriage returns.\n\/\/\n\/\/ Per RFC2812 section 2.3, messages should not exceed 512 characters in\n\/\/ length. This method forces that limit by discarding any characters\n\/\/ exceeding the length limit.\nfunc (e *Event) Bytes() []byte {\n\tbuffer := new(bytes.Buffer)\n\n\t\/\/ Tags.\n\tif e.Tags != nil {\n\t\te.Tags.writeTo(buffer)\n\t}\n\n\t\/\/ Event prefix.\n\tif e.Source != nil {\n\t\tbuffer.WriteByte(messagePrefix)\n\t\te.Source.writeTo(buffer)\n\t\tbuffer.WriteByte(eventSpace)\n\t}\n\n\t\/\/ Command is required.\n\tbuffer.WriteString(e.Command)\n\n\t\/\/ Space separated list of arguments.\n\tif len(e.Params) > 0 {\n\t\tbuffer.WriteByte(eventSpace)\n\t\tbuffer.WriteString(strings.Join(e.Params, string(eventSpace)))\n\t}\n\n\tif len(e.Trailing) > 0 || e.EmptyTrailing {\n\t\tbuffer.WriteByte(eventSpace)\n\t\tbuffer.WriteByte(messagePrefix)\n\t\tbuffer.WriteString(e.Trailing)\n\t}\n\n\t\/\/ We need the limit the buffer length.\n\tif buffer.Len() > (maxLength) {\n\t\tif e.Tags != nil {\n\t\t\t\/\/ regular message, max tag length, and the splitting space.\n\t\t\tbuffer.Truncate(maxLength + maxTagLength + 1)\n\t\t} else {\n\t\t\tbuffer.Truncate(maxLength)\n\t\t}\n\t}\n\n\tout := buffer.Bytes()\n\n\t\/\/ Strip newlines and carriage returns.\n\tfor i := 0; i < len(out); i++ {\n\t\tif out[i] == 0x0A || out[i] == 0x0D {\n\t\t\tout = append(out[:i], out[i+1:]...)\n\t\t\ti-- \/\/ Decrease the index so we can pick up where we left off.\n\t\t}\n\t}\n\n\treturn out\n}\n\n\/\/ String returns a string representation of this event. Strips all newlines\n\/\/ and carriage returns.\nfunc (e *Event) String() string {\n\treturn string(e.Bytes())\n}\n\n\/\/ Pretty returns a prettified string of the event. If the event doesn't\n\/\/ support prettification, ok is false. Pretty is not just useful to make\n\/\/ an event prettier, but also to filter out events that most don't visually\n\/\/ see in normal IRC clients. e.g. most clients don't show WHO queries.\nfunc (e *Event) Pretty() (out string, ok bool) {\n\tif e.Command == INITIALIZED {\n\t\treturn fmt.Sprintf(\"[*] connection to %s initialized\", e.Trailing), true\n\t}\n\n\tif e.Command == CONNECTED {\n\t\treturn fmt.Sprintf(\"[*] successfully connected to %s\", e.Trailing), true\n\t}\n\n\tif (e.Command == PRIVMSG || e.Command == NOTICE) && len(e.Params) > 0 {\n\t\treturn fmt.Sprintf(\"[%s] (%s) %s\", strings.Join(e.Params, \",\"), e.Source.Name, e.Trailing), true\n\t}\n\n\tif e.Command == RPL_MOTD || e.Command == RPL_MOTDSTART ||\n\t\te.Command == RPL_WELCOME || e.Command == RPL_YOURHOST ||\n\t\te.Command == RPL_CREATED || e.Command == RPL_LUSERCLIENT {\n\t\treturn fmt.Sprintf(\"[*] \" + e.Trailing), true\n\t}\n\n\tif e.Command == JOIN && len(e.Params) > 0 {\n\t\treturn fmt.Sprintf(\"[*] %s has joined %s\", e.Source.Name, e.Params[0]), true\n\t}\n\n\tif e.Command == PART && len(e.Params) > 0 {\n\t\treturn fmt.Sprintf(\"[*] %s has left %s (%s)\", e.Source.Name, e.Params[0], e.Trailing), true\n\t}\n\n\tif e.Command == ERROR {\n\t\treturn fmt.Sprintf(\"[*] an error occurred: %s\", e.Trailing), true\n\t}\n\n\tif e.Command == QUIT {\n\t\treturn fmt.Sprintf(\"[*] %s has quit (%s)\", e.Source.Name, e.Trailing), true\n\t}\n\n\tif e.Command == KICK && len(e.Params) == 2 {\n\t\treturn fmt.Sprintf(\"[%s] *** %s has kicked %s: %s\", e.Params[0], e.Source.Name, e.Params[1], e.Trailing), true\n\t}\n\n\tif e.Command == NICK && len(e.Params) == 1 {\n\t\treturn fmt.Sprintf(\"[*] %s is now known as %s\", e.Source.Name, e.Params[0]), true\n\t}\n\n\tif e.Command == TOPIC && len(e.Params) > 0 {\n\t\treturn fmt.Sprintf(\"[%s] *** %s has set the topic to: %s\", e.Params[len(e.Params)-1], e.Source.Name, e.Trailing), true\n\t}\n\n\tif e.Command == MODE && len(e.Params) > 2 {\n\t\treturn fmt.Sprintf(\"[%s] *** %s set modes: %s\", e.Params[0], e.Source.Name, strings.Join(e.Params[1:], \" \")), true\n\t}\n\n\tif e.Command == CAP_AWAY {\n\t\tif len(e.Trailing) > 0 {\n\t\t\treturn fmt.Sprintf(\"[*] %s is now away: %s\", e.Source.Name, e.Trailing), true\n\t\t}\n\n\t\treturn fmt.Sprintf(\"[*] %s is no longer away\", e.Source.Name), true\n\t}\n\n\tif e.Command == CAP_CHGHOST && len(e.Params) == 2 {\n\t\treturn fmt.Sprintf(\"[*] %s has changed their host to %s (was %s)\", e.Source.Name, e.Params[1], e.Source.Host), true\n\t}\n\n\tif e.Command == CAP_ACCOUNT && len(e.Params) == 1 {\n\t\tif e.Params[0] == \"*\" {\n\t\t\treturn fmt.Sprintf(\"[*] %s has become un-authenticated\", e.Source.Name), true\n\t\t}\n\n\t\treturn fmt.Sprintf(\"[*] %s has authenticated for account: %s\", e.Source.Name, e.Params[0]), true\n\t}\n\n\tif e.Command == RPL_TOPIC && len(e.Params) > 0 && len(e.Trailing) > 0 {\n\t\treturn fmt.Sprintf(\"[*] topic for %s is: %s\", e.Params[len(e.Params)-1], e.Trailing), true\n\t}\n\n\treturn \"\", false\n}\n\n\/\/ IsAction checks to see if the event is a PRIVMSG, and is an ACTION (\/me).\nfunc (e *Event) IsAction() bool {\n\tif len(e.Trailing) <= 0 || e.Command != PRIVMSG {\n\t\treturn false\n\t}\n\n\tif !strings.HasPrefix(e.Trailing, \"\\001ACTION\") || e.Trailing[len(e.Trailing)-1] != ctcpDelim {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ IsFromChannel checks to see if a message was from a channel (rather than\n\/\/ a private message).\nfunc (e *Event) IsFromChannel() bool {\n\tif len(e.Params) != 1 {\n\t\treturn false\n\t}\n\n\tif e.Command != \"PRIVMSG\" || !IsValidChannel(e.Params[0]) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ IsFromUser checks to see if a message was from a user (rather than a\n\/\/ channel).\nfunc (e *Event) IsFromUser() bool {\n\tif len(e.Params) != 1 {\n\t\treturn false\n\t}\n\n\tif e.Command != \"PRIVMSG\" || !IsValidNick(e.Params[0]) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ StripAction returns the stripped version of the action encoding from a\n\/\/ PRIVMSG ACTION (\/me).\nfunc (e *Event) StripAction() string {\n\tif !e.IsAction() || len(e.Trailing) < 9 {\n\t\treturn e.Trailing\n\t}\n\n\treturn e.Trailing[8 : len(e.Trailing)-1]\n}\n\n\/\/ EventLimiter is a custom ticker which lets you rate limit sending events\n\/\/ to a function (e.g. Client.Send()), with optional burst support. See\n\/\/ NewEventLimiter() for more information.\ntype EventLimiter struct {\n\ttick     *time.Ticker\n\tthrottle chan time.Time\n\tfn       func(*Event) error\n}\n\n\/\/ loop is used to read events from the internal time.Ticker.\nfunc (el *EventLimiter) loop() {\n\t\/\/ This should exit itself once el.Stop() is called.\n\tfor t := range el.tick.C {\n\t\tel.throttle <- t\n\t}\n}\n\n\/\/ Stop closes the ticker, and prevents re-use of the EventLimiter. Use this\n\/\/ to prevent EventLimiter from keeping unnecessary pointers in memory.\nfunc (el *EventLimiter) Stop() {\n\tel.tick.Stop()\n\tel.fn = nil\n}\n\n\/\/ Send is the subtitute function used to send the event the the previously\n\/\/ specified send function.\n\/\/\n\/\/ This WILL panic if Stop() was already called on the EventLimiter.\nfunc (el *EventLimiter) Send(event *Event) error {\n\t\/\/ Ensure nobody is sending to it once it's closed.\n\tif el.fn == nil {\n\t\tpanic(\"attempted send on closed EventLimiter\")\n\t}\n\n\t<-el.throttle\n\treturn el.fn(event)\n}\n\n\/\/ SendAll sends a list of events to Send(). SendAll will return the first\n\/\/ error it gets when attempting to Send() to the predefined Send function.\n\/\/ It will not attempt to continue processing the list of events.\nfunc (el *EventLimiter) SendAll(events ...*Event) error {\n\tfor i := 0; i < len(events); i++ {\n\t\tif err := el.Send(events[i]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ NewEventLimiter returns a NewEventLimiter which can be used to rate limit\n\/\/ events being sent to a Send function. This does support bursting a\n\/\/ certain amount of messages if there are less than burstCount.\n\/\/\n\/\/ Ensure that Stop() is called on the returned EventLimiter, otherwise\n\/\/ the limiter may keep unwanted pointers to data in memory.\nfunc NewEventLimiter(burstCount int, rate time.Duration, eventFunc func(event *Event) error) *EventLimiter {\n\tlimiter := &EventLimiter{\n\t\ttick:     time.NewTicker(rate),\n\t\tthrottle: make(chan time.Time, burstCount),\n\t\tfn:       eventFunc,\n\t}\n\n\t\/\/ Push the ticket into the background. If you want to stop this, simply\n\t\/\/ use EventLimiter.Stop().\n\tgo limiter.loop()\n\n\treturn limiter\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The Upspin Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package proto contains the protocol buffer definitions shared between RPC\n\/\/ servers and clients, mirroring the interfaces and types in the upspin\n\/\/ package itself.\n\/\/\n\/\/ These protocol buffers are used in the networking API to talk to Upspin\n\/\/ servers. The wire protocol is described by package upspin.io\/rpc.\n\/\/\n\/\/ Unlike in some other systems, the protocol buffer types themselves are not\n\/\/ used within the rest of the Upspin implementation. Instead, native Go types\n\/\/ are used internally and they are converted to the protocol buffer types\n\/\/ across the boundary. Helper routines in this package assist in the\n\/\/ translation.\n\/\/\n\/\/ Within the protocol buffers, some of the types are stored as uninterpreted\n\/\/ bytes that are transcoded with custom code. For instance, the\n\/\/ upspin.io\/errors.Error type is transmitted as a byte slice that is marshaled\n\/\/ and unmarshaled using the MarshalError and UnmarshalError routines in the\n\/\/ errors package. This technique preserves the properties of the Go type across\n\/\/ the network.\npackage proto \/\/ import \"upspin.io\/upspin\/proto\"\n\nimport (\n\t\"time\"\n\n\t\"upspin.io\/errors\"\n\t\"upspin.io\/upspin\"\n)\n\n\/\/ To regenerate the protocol buffer output for this package, run\n\/\/\tgo generate\n\n\/\/go:generate protoc upspin.proto --go_out=.\n\n\/\/ All these converters are an unfortunate side-effect of not letting protobufs rule our types.\n\n\/\/ UpspinLocation converts a proto Location struct to upspin.Location.\nfunc UpspinLocation(loc *Location) upspin.Location {\n\tif loc == nil {\n\t\treturn upspin.Location{}\n\t}\n\treturn upspin.Location{\n\t\tEndpoint: upspin.Endpoint{\n\t\t\tTransport: upspin.Transport(loc.Endpoint.Transport),\n\t\t\tNetAddr:   upspin.NetAddr(loc.Endpoint.NetAddr),\n\t\t},\n\t\tReference: upspin.Reference(loc.Reference),\n\t}\n}\n\n\/\/ UpspinLocations converts from slices of proto's Location struct to upspin's.\nfunc UpspinLocations(l []*Location) []upspin.Location {\n\tif len(l) == 0 {\n\t\treturn nil\n\t}\n\tulocs := make([]upspin.Location, len(l))\n\tfor i := range ulocs {\n\t\tulocs[i] = UpspinLocation(l[i])\n\t}\n\treturn ulocs\n}\n\n\/\/ UpspinDirEntry converts a slice of bytes struct to *upspin.DirEntry.\n\/\/ If the slice is nil or empty, it returns nil.\nfunc UpspinDirEntry(b []byte) (*upspin.DirEntry, error) {\n\tconst op = \"proto.UpspinDirEntry\"\n\tif len(b) == 0 {\n\t\treturn nil, nil\n\t}\n\tvar d upspin.DirEntry\n\tb, err := d.Unmarshal(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(b) != 0 {\n\t\treturn nil, errors.E(op, errors.Invalid, errors.Str(\"extra data\"))\n\t}\n\treturn &d, nil\n}\n\n\/\/ Locations converts from slices of upspin's Location struct to proto's.\nfunc Locations(ul []upspin.Location) []*Location {\n\tif len(ul) == 0 {\n\t\treturn nil\n\t}\n\tlocs := make([]*Location, len(ul))\n\tfor i := range locs {\n\t\tloc := ul[i]\n\t\tlocs[i] = &Location{\n\t\t\tEndpoint: &Endpoint{\n\t\t\t\tTransport: int32(loc.Endpoint.Transport),\n\t\t\t\tNetAddr:   string(loc.Endpoint.NetAddr),\n\t\t\t},\n\t\t\tReference: string(loc.Reference),\n\t\t}\n\t}\n\treturn locs\n}\n\n\/\/ UpspinEndpoints converts from slices of proto's Endpoint struct to upspin's.\nfunc UpspinEndpoints(e []*Endpoint) []upspin.Endpoint {\n\tif len(e) == 0 {\n\t\treturn nil\n\t}\n\tueps := make([]upspin.Endpoint, len(e))\n\tfor i := range ueps {\n\t\tep := e[i]\n\t\tueps[i] = upspin.Endpoint{\n\t\t\tTransport: upspin.Transport(ep.Transport),\n\t\t\tNetAddr:   upspin.NetAddr(ep.NetAddr),\n\t\t}\n\t}\n\treturn ueps\n}\n\n\/\/ Endpoints converts from slices of upspin's Endpoint struct to proto's.\nfunc Endpoints(ue []upspin.Endpoint) []*Endpoint {\n\tif len(ue) == 0 {\n\t\treturn nil\n\t}\n\teps := make([]*Endpoint, len(ue))\n\tfor i := range eps {\n\t\tep := ue[i]\n\t\teps[i] = &Endpoint{\n\t\t\tTransport: int32(ep.Transport),\n\t\t\tNetAddr:   string(ep.NetAddr),\n\t\t}\n\t}\n\treturn eps\n}\n\n\/\/ UpspinPublicKeys converts from slices of strings to upspin's PublicKeys.\nfunc UpspinPublicKeys(s []string) []upspin.PublicKey {\n\tif len(s) == 0 {\n\t\treturn nil\n\t}\n\tupk := make([]upspin.PublicKey, len(s))\n\tfor i := range upk {\n\t\tupk[i] = upspin.PublicKey(s[i])\n\t}\n\treturn upk\n}\n\n\/\/ PublicKeys converts from slices of upspin's PublicKey to string.\nfunc PublicKeys(upk []upspin.PublicKey) []string {\n\tif len(upk) == 0 {\n\t\treturn nil\n\t}\n\ts := make([]string, len(upk))\n\tfor i := range s {\n\t\ts[i] = string(upk[i])\n\t}\n\treturn s\n}\n\n\/\/ UpspinUser converts a proto.User to upspin.User.\nfunc UpspinUser(user *User) *upspin.User {\n\treturn &upspin.User{\n\t\tName:      upspin.UserName(user.Name),\n\t\tDirs:      UpspinEndpoints(user.Dirs),\n\t\tStores:    UpspinEndpoints(user.Stores),\n\t\tPublicKey: upspin.PublicKey(user.PublicKey),\n\t}\n}\n\n\/\/ UserProto converts an upspin.User to a proto.User.\nfunc UserProto(user *upspin.User) *User {\n\treturn &User{\n\t\tName:      string(user.Name),\n\t\tDirs:      Endpoints(user.Dirs),\n\t\tStores:    Endpoints(user.Stores),\n\t\tPublicKey: string(user.PublicKey),\n\t}\n}\n\n\/\/ RefdataProto converts an upspin.Refdata to a proto.Refdata.\nfunc RefdataProto(refdata *upspin.Refdata) *Refdata {\n\tif refdata == nil {\n\t\treturn nil\n\t}\n\treturn &Refdata{\n\t\tReference: string(refdata.Reference),\n\t\tVolatile:  refdata.Volatile,\n\t\tDuration:  int64(refdata.Duration),\n\t}\n}\n\n\/\/ UpspinRefdata converts a proto.Refdata to upspin.Refdata.\nfunc UpspinRefdata(refdata *Refdata) *upspin.Refdata {\n\tif refdata == nil {\n\t\treturn nil\n\t}\n\treturn &upspin.Refdata{\n\t\tReference: upspin.Reference(refdata.Reference),\n\t\tVolatile:  refdata.Volatile,\n\t\tDuration:  time.Duration(refdata.Duration),\n\t}\n}\n\n\/\/ UpspinDirEntries converts from slices of bytes to upspin's *DirEntries.\nfunc UpspinDirEntries(b [][]byte) ([]*upspin.DirEntry, error) {\n\tif len(b) == 0 {\n\t\treturn nil, nil\n\t}\n\tude := make([]*upspin.DirEntry, len(b))\n\tfor i := range ude {\n\t\tvar err error\n\t\tude[i], err = UpspinDirEntry(b[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn ude, nil\n}\n\n\/\/ DirEntryBytes converts from slices of upspin's *DirEntries to bytes.\nfunc DirEntryBytes(ude []*upspin.DirEntry) ([][]byte, error) {\n\tif len(ude) == 0 {\n\t\treturn nil, nil\n\t}\n\tb := make([][]byte, len(ude))\n\tfor i := range b {\n\t\tvar err error\n\t\tb[i], err = ude[i].Marshal()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn b, nil\n}\n\n\/\/ UpspinEvent converts a proto.DirWatchResponse to upspin.Event.\nfunc UpspinEvent(event *Event) (*upspin.Event, error) {\n\tentry, err := UpspinDirEntry(event.Entry)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &upspin.Event{\n\t\tEntry:  entry, \/\/ may be nil.\n\t\tOrder:  event.Order,\n\t\tDelete: event.Delete,\n\t\tError:  errors.UnmarshalError(event.Error),\n\t}, nil\n}\n\n\/\/ EventProto converts an upspin.Event to proto.Event.\nfunc EventProto(event *upspin.Event) (*Event, error) {\n\tif event == nil {\n\t\t\/\/ A nil proto is likely to cause GRPC to crash, according to\n\t\t\/\/ https:\/\/github.com\/grpc\/grpc-go\/issues\/532.\n\t\treturn &Event{}, nil\n\t}\n\tvar b []byte\n\tif event.Entry != nil {\n\t\tvar mErr error\n\t\tb, mErr = event.Entry.Marshal()\n\t\tif mErr != nil {\n\t\t\treturn nil, mErr\n\t\t}\n\t}\n\tvar err []byte\n\tif event.Error != nil {\n\t\terr = errors.MarshalError(event.Error)\n\t}\n\treturn &Event{\n\t\tEntry:  b,\n\t\tOrder:  event.Order,\n\t\tDelete: event.Delete,\n\t\tError:  err,\n\t}, nil\n}\n<commit_msg>upspin\/proto: update comment regarding GRPC<commit_after>\/\/ Copyright 2016 The Upspin Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package proto contains the protocol buffer definitions shared between RPC\n\/\/ servers and clients, mirroring the interfaces and types in the upspin\n\/\/ package itself.\n\/\/\n\/\/ These protocol buffers are used in the networking API to talk to Upspin\n\/\/ servers. The wire protocol is described by package upspin.io\/rpc.\n\/\/\n\/\/ Unlike in some other systems, the protocol buffer types themselves are not\n\/\/ used within the rest of the Upspin implementation. Instead, native Go types\n\/\/ are used internally and they are converted to the protocol buffer types\n\/\/ across the boundary. Helper routines in this package assist in the\n\/\/ translation.\n\/\/\n\/\/ Within the protocol buffers, some of the types are stored as uninterpreted\n\/\/ bytes that are transcoded with custom code. For instance, the\n\/\/ upspin.io\/errors.Error type is transmitted as a byte slice that is marshaled\n\/\/ and unmarshaled using the MarshalError and UnmarshalError routines in the\n\/\/ errors package. This technique preserves the properties of the Go type across\n\/\/ the network.\npackage proto \/\/ import \"upspin.io\/upspin\/proto\"\n\nimport (\n\t\"time\"\n\n\t\"upspin.io\/errors\"\n\t\"upspin.io\/upspin\"\n)\n\n\/\/ To regenerate the protocol buffer output for this package, run\n\/\/\tgo generate\n\n\/\/go:generate protoc upspin.proto --go_out=.\n\n\/\/ All these converters are an unfortunate side-effect of not letting protobufs rule our types.\n\n\/\/ UpspinLocation converts a proto Location struct to upspin.Location.\nfunc UpspinLocation(loc *Location) upspin.Location {\n\tif loc == nil {\n\t\treturn upspin.Location{}\n\t}\n\treturn upspin.Location{\n\t\tEndpoint: upspin.Endpoint{\n\t\t\tTransport: upspin.Transport(loc.Endpoint.Transport),\n\t\t\tNetAddr:   upspin.NetAddr(loc.Endpoint.NetAddr),\n\t\t},\n\t\tReference: upspin.Reference(loc.Reference),\n\t}\n}\n\n\/\/ UpspinLocations converts from slices of proto's Location struct to upspin's.\nfunc UpspinLocations(l []*Location) []upspin.Location {\n\tif len(l) == 0 {\n\t\treturn nil\n\t}\n\tulocs := make([]upspin.Location, len(l))\n\tfor i := range ulocs {\n\t\tulocs[i] = UpspinLocation(l[i])\n\t}\n\treturn ulocs\n}\n\n\/\/ UpspinDirEntry converts a slice of bytes struct to *upspin.DirEntry.\n\/\/ If the slice is nil or empty, it returns nil.\nfunc UpspinDirEntry(b []byte) (*upspin.DirEntry, error) {\n\tconst op = \"proto.UpspinDirEntry\"\n\tif len(b) == 0 {\n\t\treturn nil, nil\n\t}\n\tvar d upspin.DirEntry\n\tb, err := d.Unmarshal(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(b) != 0 {\n\t\treturn nil, errors.E(op, errors.Invalid, errors.Str(\"extra data\"))\n\t}\n\treturn &d, nil\n}\n\n\/\/ Locations converts from slices of upspin's Location struct to proto's.\nfunc Locations(ul []upspin.Location) []*Location {\n\tif len(ul) == 0 {\n\t\treturn nil\n\t}\n\tlocs := make([]*Location, len(ul))\n\tfor i := range locs {\n\t\tloc := ul[i]\n\t\tlocs[i] = &Location{\n\t\t\tEndpoint: &Endpoint{\n\t\t\t\tTransport: int32(loc.Endpoint.Transport),\n\t\t\t\tNetAddr:   string(loc.Endpoint.NetAddr),\n\t\t\t},\n\t\t\tReference: string(loc.Reference),\n\t\t}\n\t}\n\treturn locs\n}\n\n\/\/ UpspinEndpoints converts from slices of proto's Endpoint struct to upspin's.\nfunc UpspinEndpoints(e []*Endpoint) []upspin.Endpoint {\n\tif len(e) == 0 {\n\t\treturn nil\n\t}\n\tueps := make([]upspin.Endpoint, len(e))\n\tfor i := range ueps {\n\t\tep := e[i]\n\t\tueps[i] = upspin.Endpoint{\n\t\t\tTransport: upspin.Transport(ep.Transport),\n\t\t\tNetAddr:   upspin.NetAddr(ep.NetAddr),\n\t\t}\n\t}\n\treturn ueps\n}\n\n\/\/ Endpoints converts from slices of upspin's Endpoint struct to proto's.\nfunc Endpoints(ue []upspin.Endpoint) []*Endpoint {\n\tif len(ue) == 0 {\n\t\treturn nil\n\t}\n\teps := make([]*Endpoint, len(ue))\n\tfor i := range eps {\n\t\tep := ue[i]\n\t\teps[i] = &Endpoint{\n\t\t\tTransport: int32(ep.Transport),\n\t\t\tNetAddr:   string(ep.NetAddr),\n\t\t}\n\t}\n\treturn eps\n}\n\n\/\/ UpspinPublicKeys converts from slices of strings to upspin's PublicKeys.\nfunc UpspinPublicKeys(s []string) []upspin.PublicKey {\n\tif len(s) == 0 {\n\t\treturn nil\n\t}\n\tupk := make([]upspin.PublicKey, len(s))\n\tfor i := range upk {\n\t\tupk[i] = upspin.PublicKey(s[i])\n\t}\n\treturn upk\n}\n\n\/\/ PublicKeys converts from slices of upspin's PublicKey to string.\nfunc PublicKeys(upk []upspin.PublicKey) []string {\n\tif len(upk) == 0 {\n\t\treturn nil\n\t}\n\ts := make([]string, len(upk))\n\tfor i := range s {\n\t\ts[i] = string(upk[i])\n\t}\n\treturn s\n}\n\n\/\/ UpspinUser converts a proto.User to upspin.User.\nfunc UpspinUser(user *User) *upspin.User {\n\treturn &upspin.User{\n\t\tName:      upspin.UserName(user.Name),\n\t\tDirs:      UpspinEndpoints(user.Dirs),\n\t\tStores:    UpspinEndpoints(user.Stores),\n\t\tPublicKey: upspin.PublicKey(user.PublicKey),\n\t}\n}\n\n\/\/ UserProto converts an upspin.User to a proto.User.\nfunc UserProto(user *upspin.User) *User {\n\treturn &User{\n\t\tName:      string(user.Name),\n\t\tDirs:      Endpoints(user.Dirs),\n\t\tStores:    Endpoints(user.Stores),\n\t\tPublicKey: string(user.PublicKey),\n\t}\n}\n\n\/\/ RefdataProto converts an upspin.Refdata to a proto.Refdata.\nfunc RefdataProto(refdata *upspin.Refdata) *Refdata {\n\tif refdata == nil {\n\t\treturn nil\n\t}\n\treturn &Refdata{\n\t\tReference: string(refdata.Reference),\n\t\tVolatile:  refdata.Volatile,\n\t\tDuration:  int64(refdata.Duration),\n\t}\n}\n\n\/\/ UpspinRefdata converts a proto.Refdata to upspin.Refdata.\nfunc UpspinRefdata(refdata *Refdata) *upspin.Refdata {\n\tif refdata == nil {\n\t\treturn nil\n\t}\n\treturn &upspin.Refdata{\n\t\tReference: upspin.Reference(refdata.Reference),\n\t\tVolatile:  refdata.Volatile,\n\t\tDuration:  time.Duration(refdata.Duration),\n\t}\n}\n\n\/\/ UpspinDirEntries converts from slices of bytes to upspin's *DirEntries.\nfunc UpspinDirEntries(b [][]byte) ([]*upspin.DirEntry, error) {\n\tif len(b) == 0 {\n\t\treturn nil, nil\n\t}\n\tude := make([]*upspin.DirEntry, len(b))\n\tfor i := range ude {\n\t\tvar err error\n\t\tude[i], err = UpspinDirEntry(b[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn ude, nil\n}\n\n\/\/ DirEntryBytes converts from slices of upspin's *DirEntries to bytes.\nfunc DirEntryBytes(ude []*upspin.DirEntry) ([][]byte, error) {\n\tif len(ude) == 0 {\n\t\treturn nil, nil\n\t}\n\tb := make([][]byte, len(ude))\n\tfor i := range b {\n\t\tvar err error\n\t\tb[i], err = ude[i].Marshal()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn b, nil\n}\n\n\/\/ UpspinEvent converts a proto.DirWatchResponse to upspin.Event.\nfunc UpspinEvent(event *Event) (*upspin.Event, error) {\n\tentry, err := UpspinDirEntry(event.Entry)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &upspin.Event{\n\t\tEntry:  entry, \/\/ may be nil.\n\t\tOrder:  event.Order,\n\t\tDelete: event.Delete,\n\t\tError:  errors.UnmarshalError(event.Error),\n\t}, nil\n}\n\n\/\/ EventProto converts an upspin.Event to proto.Event.\nfunc EventProto(event *upspin.Event) (*Event, error) {\n\tif event == nil {\n\t\t\/\/ A nil proto is likely to cause GRPC to crash, according to\n\t\t\/\/ https:\/\/github.com\/grpc\/grpc-go\/issues\/532.\n\t\t\/\/ We don't use GRPC now for this protocol but we might again,\n\t\t\/\/ so play it safe.\n\t\treturn &Event{}, nil\n\t}\n\tvar b []byte\n\tif event.Entry != nil {\n\t\tvar mErr error\n\t\tb, mErr = event.Entry.Marshal()\n\t\tif mErr != nil {\n\t\t\treturn nil, mErr\n\t\t}\n\t}\n\tvar err []byte\n\tif event.Error != nil {\n\t\terr = errors.MarshalError(event.Error)\n\t}\n\treturn &Event{\n\t\tEntry:  b,\n\t\tOrder:  event.Order,\n\t\tDelete: event.Delete,\n\t\tError:  err,\n\t}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 The ql Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSES\/QL-LICENSE file.\n\n\/\/ Copyright 2015 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage types\n\nimport (\n\t\"github.com\/juju\/errors\"\n\tmysql \"github.com\/pingcap\/tidb\/mysqldef\"\n)\n\n\/\/ CompareInt64 returns an integer comparing the int64 x to y.\nfunc CompareInt64(x, y int64) int {\n\tif x < y {\n\t\treturn -1\n\t} else if x == y {\n\t\treturn 0\n\t}\n\n\treturn 1\n}\n\n\/\/ CompareUint64 returns an integer comparing the uint64 x to y.\nfunc CompareUint64(x, y uint64) int {\n\tif x < y {\n\t\treturn -1\n\t} else if x == y {\n\t\treturn 0\n\t}\n\n\treturn 1\n}\n\n\/\/ CompareFloat64 returns an integer comparing the float64 x to y.\nfunc CompareFloat64(x, y float64) int {\n\tif x < y {\n\t\treturn -1\n\t} else if x == y {\n\t\treturn 0\n\t}\n\n\treturn 1\n}\n\n\/\/ CompareInteger returns an integer comparing the int64 x to the uint64 y.\nfunc CompareInteger(x int64, y uint64) int {\n\tif x < 0 {\n\t\treturn -1\n\t}\n\treturn CompareUint64(uint64(x), y)\n}\n\n\/\/ CompareString returns an integer comparing the string x to y.\nfunc CompareString(x, y string) int {\n\tif x < y {\n\t\treturn -1\n\t} else if x == y {\n\t\treturn 0\n\t}\n\n\treturn 1\n}\n\n\/\/ compareFloatString compares float a with string s.\n\/\/ compareFloatString first parses s to a float value, if failed, returns error.\nfunc compareFloatString(a float64, s string) (int, error) {\n\t\/\/ MySQL will convert string to a float point value.\n\t\/\/ MySQL uses a very loose conversation, e.g, 123.abc -> 123\n\t\/\/ We should do a trade off whether supporting this feature or using a strict mode.\n\t\/\/ Now we use a strict mode.\n\tb, err := StrToFloat(s)\n\tif err != nil {\n\t\treturn 0, errors.Trace(err)\n\t}\n\treturn CompareFloat64(a, b), nil\n}\n\n\/\/ compareStringFloat compares string s with float a.\nfunc compareStringFloat(s string, a float64) (int, error) {\n\tn, err := compareFloatString(a, s)\n\treturn -n, errors.Trace(err)\n}\n\nfunc coerceCompare(a, b interface{}) (x interface{}, y interface{}, err error) {\n\trowTypeNum := 0\n\tx, y = Coerce(a, b)\n\t\/\/ change []byte to string for later compare\n\tswitch v := a.(type) {\n\tcase []byte:\n\t\tx = string(v)\n\tcase []interface{}:\n\t\trowTypeNum++\n\tcase *DataItem:\n\t\tx = v.Data\n\t}\n\n\tswitch v := b.(type) {\n\tcase []byte:\n\t\ty = string(v)\n\tcase []interface{}:\n\t\trowTypeNum++\n\tcase *DataItem:\n\t\ty = v.Data\n\t}\n\n\tif rowTypeNum == 1 {\n\t\t\/\/ a and b must be all row type or not\n\t\terr = errors.Errorf(\"invalid comapre type %T cmp %T\", a, b)\n\t}\n\n\treturn x, y, errors.Trace(err)\n}\n\nfunc compareRow(a, b []interface{}) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.Errorf(\"mismatch columns for row %v cmp %v\", a, b)\n\t}\n\n\tfor i := range a {\n\t\tn, err := Compare(a[i], b[i])\n\t\tif err != nil {\n\t\t\treturn 0, errors.Trace(err)\n\t\t} else if n != 0 {\n\t\t\treturn n, nil\n\t\t}\n\t}\n\treturn 0, nil\n}\n\n\/\/ Compare returns an integer comparing the interface a with b.\n\/\/ a > b -> 1\n\/\/ a = b -> 0\n\/\/ a < b -> -1\nfunc Compare(a, b interface{}) (int, error) {\n\tvar coerceErr error\n\ta, b, coerceErr = coerceCompare(a, b)\n\tif coerceErr != nil {\n\t\treturn 0, errors.Trace(coerceErr)\n\t}\n\n\tif va, ok := a.([]interface{}); ok {\n\t\t\/\/ we guarantee in coerceCompare that a and b are both []interface{}\n\t\tvb := b.([]interface{})\n\t\treturn compareRow(va, vb)\n\t}\n\n\tif a == nil || b == nil {\n\t\t\/\/ Check ni first, nil is always less than none nil value.\n\t\tif a == nil && b != nil {\n\t\t\treturn -1, nil\n\t\t} else if a != nil && b == nil {\n\t\t\treturn 1, nil\n\t\t} else {\n\t\t\t\/\/ here a and b are all nil\n\t\t\treturn 0, nil\n\t\t}\n\t}\n\n\t\/\/ TODO: support compare time type with other int, float, decimal types.\n\tswitch x := a.(type) {\n\tcase float64:\n\t\tswitch y := b.(type) {\n\t\tcase float64:\n\t\t\treturn CompareFloat64(x, y), nil\n\t\tcase string:\n\t\t\treturn compareFloatString(x, y)\n\t\t}\n\tcase int64:\n\t\tswitch y := b.(type) {\n\t\tcase int64:\n\t\t\treturn CompareInt64(x, y), nil\n\t\tcase uint64:\n\t\t\treturn CompareInteger(x, y), nil\n\t\tcase string:\n\t\t\treturn compareFloatString(float64(x), y)\n\t\tcase mysql.Hex:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\t}\n\tcase uint64:\n\t\tswitch y := b.(type) {\n\t\tcase uint64:\n\t\t\treturn CompareUint64(x, y), nil\n\t\tcase int64:\n\t\t\treturn -CompareInteger(y, x), nil\n\t\tcase string:\n\t\t\treturn compareFloatString(float64(x), y)\n\t\tcase mysql.Hex:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\t}\n\tcase mysql.Decimal:\n\t\tswitch y := b.(type) {\n\t\tcase mysql.Decimal:\n\t\t\treturn x.Cmp(y), nil\n\t\tcase string:\n\t\t\tf, err := mysql.ConvertToDecimal(y)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, errors.Trace(err)\n\t\t\t}\n\t\t\treturn x.Cmp(f), nil\n\t\t}\n\tcase string:\n\t\tswitch y := b.(type) {\n\t\tcase string:\n\t\t\treturn CompareString(x, y), nil\n\t\tcase int64:\n\t\t\treturn compareStringFloat(x, float64(y))\n\t\tcase uint64:\n\t\t\treturn compareStringFloat(x, float64(y))\n\t\tcase float64:\n\t\t\treturn compareStringFloat(x, y)\n\t\tcase mysql.Decimal:\n\t\t\tf, err := mysql.ConvertToDecimal(x)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, errors.Trace(err)\n\t\t\t}\n\t\t\treturn f.Cmp(y), nil\n\t\tcase mysql.Time:\n\t\t\tn, err := y.CompareString(x)\n\t\t\treturn -n, errors.Trace(err)\n\t\tcase mysql.Duration:\n\t\t\tn, err := y.CompareString(x)\n\t\t\treturn -n, errors.Trace(err)\n\t\tcase mysql.Hex:\n\t\t\treturn CompareString(x, y.ToString()), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareString(x, y.ToString()), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareString(x, y.String()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareString(x, y.String()), nil\n\t\t}\n\tcase mysql.Time:\n\t\tswitch y := b.(type) {\n\t\tcase mysql.Time:\n\t\t\treturn x.Compare(y), nil\n\t\tcase string:\n\t\t\treturn x.CompareString(y)\n\t\t}\n\tcase mysql.Duration:\n\t\tswitch y := b.(type) {\n\t\tcase mysql.Duration:\n\t\t\treturn x.Compare(y), nil\n\t\tcase string:\n\t\t\treturn x.CompareString(y)\n\t\t}\n\tcase mysql.Hex:\n\t\tswitch y := b.(type) {\n\t\tcase int64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase uint64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase string:\n\t\t\treturn CompareString(x.ToString(), y), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Hex:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\t}\n\tcase mysql.Bit:\n\t\tswitch y := b.(type) {\n\t\tcase int64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase uint64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase mysql.Hex:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase string:\n\t\t\treturn CompareString(x.ToString(), y), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\t}\n\tcase mysql.Enum:\n\t\tswitch y := b.(type) {\n\t\tcase int64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase uint64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase mysql.Hex:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase string:\n\t\t\treturn CompareString(x.String(), y), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\t}\n\tcase mysql.Set:\n\t\tswitch y := b.(type) {\n\t\tcase int64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase uint64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase mysql.Hex:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase string:\n\t\t\treturn CompareString(x.String(), y), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\t}\n\t}\n\n\treturn 0, errors.Errorf(\"invalid comapre type %T cmp %T\", a, b)\n}\n<commit_msg>types: Improve compare for DataItem<commit_after>\/\/ Copyright 2014 The ql Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSES\/QL-LICENSE file.\n\n\/\/ Copyright 2015 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage types\n\nimport (\n\t\"github.com\/juju\/errors\"\n\tmysql \"github.com\/pingcap\/tidb\/mysqldef\"\n)\n\n\/\/ CompareInt64 returns an integer comparing the int64 x to y.\nfunc CompareInt64(x, y int64) int {\n\tif x < y {\n\t\treturn -1\n\t} else if x == y {\n\t\treturn 0\n\t}\n\n\treturn 1\n}\n\n\/\/ CompareUint64 returns an integer comparing the uint64 x to y.\nfunc CompareUint64(x, y uint64) int {\n\tif x < y {\n\t\treturn -1\n\t} else if x == y {\n\t\treturn 0\n\t}\n\n\treturn 1\n}\n\n\/\/ CompareFloat64 returns an integer comparing the float64 x to y.\nfunc CompareFloat64(x, y float64) int {\n\tif x < y {\n\t\treturn -1\n\t} else if x == y {\n\t\treturn 0\n\t}\n\n\treturn 1\n}\n\n\/\/ CompareInteger returns an integer comparing the int64 x to the uint64 y.\nfunc CompareInteger(x int64, y uint64) int {\n\tif x < 0 {\n\t\treturn -1\n\t}\n\treturn CompareUint64(uint64(x), y)\n}\n\n\/\/ CompareString returns an integer comparing the string x to y.\nfunc CompareString(x, y string) int {\n\tif x < y {\n\t\treturn -1\n\t} else if x == y {\n\t\treturn 0\n\t}\n\n\treturn 1\n}\n\n\/\/ compareFloatString compares float a with string s.\n\/\/ compareFloatString first parses s to a float value, if failed, returns error.\nfunc compareFloatString(a float64, s string) (int, error) {\n\t\/\/ MySQL will convert string to a float point value.\n\t\/\/ MySQL uses a very loose conversation, e.g, 123.abc -> 123\n\t\/\/ We should do a trade off whether supporting this feature or using a strict mode.\n\t\/\/ Now we use a strict mode.\n\tb, err := StrToFloat(s)\n\tif err != nil {\n\t\treturn 0, errors.Trace(err)\n\t}\n\treturn CompareFloat64(a, b), nil\n}\n\n\/\/ compareStringFloat compares string s with float a.\nfunc compareStringFloat(s string, a float64) (int, error) {\n\tn, err := compareFloatString(a, s)\n\treturn -n, errors.Trace(err)\n}\n\nfunc coerceCompare(a, b interface{}) (x interface{}, y interface{}, err error) {\n\trowTypeNum := 0\n\tx, y = Coerce(a, b)\n\t\/\/ change []byte to string for later compare\n\tswitch v := a.(type) {\n\tcase []byte:\n\t\tx = string(v)\n\tcase []interface{}:\n\t\trowTypeNum++\n\tcase *DataItem:\n\t\treturn coerceCompare(v.Data, b)\n\t}\n\n\tswitch v := b.(type) {\n\tcase []byte:\n\t\ty = string(v)\n\tcase []interface{}:\n\t\trowTypeNum++\n\tcase *DataItem:\n\t\treturn coerceCompare(a, v.Data)\n\t}\n\n\tif rowTypeNum == 1 {\n\t\t\/\/ a and b must be all row type or not\n\t\terr = errors.Errorf(\"invalid comapre type %T cmp %T\", a, b)\n\t}\n\n\treturn x, y, errors.Trace(err)\n}\n\nfunc compareRow(a, b []interface{}) (int, error) {\n\tif len(a) != len(b) {\n\t\treturn 0, errors.Errorf(\"mismatch columns for row %v cmp %v\", a, b)\n\t}\n\n\tfor i := range a {\n\t\tn, err := Compare(a[i], b[i])\n\t\tif err != nil {\n\t\t\treturn 0, errors.Trace(err)\n\t\t} else if n != 0 {\n\t\t\treturn n, nil\n\t\t}\n\t}\n\treturn 0, nil\n}\n\n\/\/ Compare returns an integer comparing the interface a with b.\n\/\/ a > b -> 1\n\/\/ a = b -> 0\n\/\/ a < b -> -1\nfunc Compare(a, b interface{}) (int, error) {\n\tvar coerceErr error\n\ta, b, coerceErr = coerceCompare(a, b)\n\tif coerceErr != nil {\n\t\treturn 0, errors.Trace(coerceErr)\n\t}\n\n\tif va, ok := a.([]interface{}); ok {\n\t\t\/\/ we guarantee in coerceCompare that a and b are both []interface{}\n\t\tvb := b.([]interface{})\n\t\treturn compareRow(va, vb)\n\t}\n\n\tif a == nil || b == nil {\n\t\t\/\/ Check ni first, nil is always less than none nil value.\n\t\tif a == nil && b != nil {\n\t\t\treturn -1, nil\n\t\t} else if a != nil && b == nil {\n\t\t\treturn 1, nil\n\t\t} else {\n\t\t\t\/\/ here a and b are all nil\n\t\t\treturn 0, nil\n\t\t}\n\t}\n\n\t\/\/ TODO: support compare time type with other int, float, decimal types.\n\tswitch x := a.(type) {\n\tcase float64:\n\t\tswitch y := b.(type) {\n\t\tcase float64:\n\t\t\treturn CompareFloat64(x, y), nil\n\t\tcase string:\n\t\t\treturn compareFloatString(x, y)\n\t\t}\n\tcase int64:\n\t\tswitch y := b.(type) {\n\t\tcase int64:\n\t\t\treturn CompareInt64(x, y), nil\n\t\tcase uint64:\n\t\t\treturn CompareInteger(x, y), nil\n\t\tcase string:\n\t\t\treturn compareFloatString(float64(x), y)\n\t\tcase mysql.Hex:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\t}\n\tcase uint64:\n\t\tswitch y := b.(type) {\n\t\tcase uint64:\n\t\t\treturn CompareUint64(x, y), nil\n\t\tcase int64:\n\t\t\treturn -CompareInteger(y, x), nil\n\t\tcase string:\n\t\t\treturn compareFloatString(float64(x), y)\n\t\tcase mysql.Hex:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareFloat64(float64(x), y.ToNumber()), nil\n\t\t}\n\tcase mysql.Decimal:\n\t\tswitch y := b.(type) {\n\t\tcase mysql.Decimal:\n\t\t\treturn x.Cmp(y), nil\n\t\tcase string:\n\t\t\tf, err := mysql.ConvertToDecimal(y)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, errors.Trace(err)\n\t\t\t}\n\t\t\treturn x.Cmp(f), nil\n\t\t}\n\tcase string:\n\t\tswitch y := b.(type) {\n\t\tcase string:\n\t\t\treturn CompareString(x, y), nil\n\t\tcase int64:\n\t\t\treturn compareStringFloat(x, float64(y))\n\t\tcase uint64:\n\t\t\treturn compareStringFloat(x, float64(y))\n\t\tcase float64:\n\t\t\treturn compareStringFloat(x, y)\n\t\tcase mysql.Decimal:\n\t\t\tf, err := mysql.ConvertToDecimal(x)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, errors.Trace(err)\n\t\t\t}\n\t\t\treturn f.Cmp(y), nil\n\t\tcase mysql.Time:\n\t\t\tn, err := y.CompareString(x)\n\t\t\treturn -n, errors.Trace(err)\n\t\tcase mysql.Duration:\n\t\t\tn, err := y.CompareString(x)\n\t\t\treturn -n, errors.Trace(err)\n\t\tcase mysql.Hex:\n\t\t\treturn CompareString(x, y.ToString()), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareString(x, y.ToString()), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareString(x, y.String()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareString(x, y.String()), nil\n\t\t}\n\tcase mysql.Time:\n\t\tswitch y := b.(type) {\n\t\tcase mysql.Time:\n\t\t\treturn x.Compare(y), nil\n\t\tcase string:\n\t\t\treturn x.CompareString(y)\n\t\t}\n\tcase mysql.Duration:\n\t\tswitch y := b.(type) {\n\t\tcase mysql.Duration:\n\t\t\treturn x.Compare(y), nil\n\t\tcase string:\n\t\t\treturn x.CompareString(y)\n\t\t}\n\tcase mysql.Hex:\n\t\tswitch y := b.(type) {\n\t\tcase int64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase uint64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase string:\n\t\t\treturn CompareString(x.ToString(), y), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Hex:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\t}\n\tcase mysql.Bit:\n\t\tswitch y := b.(type) {\n\t\tcase int64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase uint64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase mysql.Hex:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase string:\n\t\t\treturn CompareString(x.ToString(), y), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\t}\n\tcase mysql.Enum:\n\t\tswitch y := b.(type) {\n\t\tcase int64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase uint64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase mysql.Hex:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase string:\n\t\t\treturn CompareString(x.String(), y), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\t}\n\tcase mysql.Set:\n\t\tswitch y := b.(type) {\n\t\tcase int64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase uint64:\n\t\t\treturn CompareFloat64(x.ToNumber(), float64(y)), nil\n\t\tcase mysql.Hex:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase string:\n\t\t\treturn CompareString(x.String(), y), nil\n\t\tcase mysql.Bit:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Enum:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\tcase mysql.Set:\n\t\t\treturn CompareFloat64(x.ToNumber(), y.ToNumber()), nil\n\t\t}\n\t}\n\n\treturn 0, errors.Errorf(\"invalid comapre type %T cmp %T\", a, b)\n}\n<|endoftext|>"}
{"text":"<commit_before>package instana\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\n\/\/ Trace IDs (and Span IDs) are based on Java Signed Long datatype\nconst MinUint64 = uint64(0)\nconst MaxUint64 = uint64(18446744073709551615)\nconst MinInt64 = int64(-9223372036854775808)\nconst MaxInt64 = int64(9223372036854775807)\n\nfunc TestGeneratedIDRange(t *testing.T) {\n\tvar count = 10000\n\tfor index := 0; index < count; index++ {\n\t\tid := randomID()\n\t\tassert.True(t, id <= 9223372036854775807, \"Generated ID is out of bounds (+)\")\n\t\tassert.True(t, id >= -9223372036854775808, \"Generated ID is out of bounds (-)\")\n\t}\n}\n\nfunc TestIDConversionBackForth(t *testing.T) {\n\tmaxID := int64(9223372036854775807)\n\tminID := int64(-9223372036854775808)\n\tmaxHex := \"7fffffffffffffff\"\n\tminHex := \"8000000000000000\"\n\n\t\/\/ Place holders\n\tvar header string\n\tvar id int64\n\n\t\/\/ maxID (int64) -> header -> int64\n\theader, _ = ID2Header(maxID)\n\tid, _ = Header2ID(header)\n\tassert.Equal(t, maxHex, header, \"ID2Header incorrect result.\")\n\tassert.Equal(t, maxID, id, \"Convert back into original is wrong\")\n\n\t\/\/ minHex (unsigned 64bit hex string) -> signed 64bit int -> unsigned 64bit hex string\n\tid, _ = Header2ID(minHex)\n\theader, _ = ID2Header(id)\n\tassert.Equal(t, minID, id, \"Header2ID incorrect result\")\n\tassert.Equal(t, minHex, header, \"Convert back into original is wrong\")\n}\n\nfunc TestIDConversion(t *testing.T) {\n\t\/\/ Place holders\n\tvar header string\n\tvar id int64\n\n\theader, _ = ID2Header(-7815363404733516491)\n\tassert.Equal(t, \"938a406416457535\", header, \"ID2Header incorrect result.\")\n\tid, _ = Header2ID(\"938a406416457535\")\n\tassert.Equal(t, int64(-7815363404733516491), id, \"Header2ID incorrect result\")\n\n\theader, _ = ID2Header(307170163380978816)\n\tassert.Equal(t, \"44349a2d9ec0480\", header, \"ID2Header incorrect result.\")\n\tid, _ = Header2ID(\"44349a2d9ec0480\") \/\/ Without a leading zero\n\tassert.Equal(t, int64(307170163380978816), id, \"Header2ID incorrect result\")\n\tid, _ = Header2ID(\"044349a2d9ec0480\") \/\/ Try with a leading zero\n\tassert.Equal(t, int64(307170163380978816), id, \"Header2ID incorrect result\")\n\n\theader, _ = ID2Header(2920004540187184976)\n\tassert.Equal(t, \"2885f0a890628f50\", header, \"ID2Header incorrect result.\")\n\tid, _ = Header2ID(\"2885f0a890628f50\")\n\tassert.Equal(t, int64(2920004540187184976), id, \"Header2ID incorrect result\")\n\n\theader, _ = ID2Header(16)\n\tassert.Equal(t, \"10\", header, \"ID2Header should drop leading zeros\")\n\tid, _ = Header2ID(\"0000000000000010\")\n\tassert.Equal(t, int64(16), id, \"Header2ID should stll work with leading zeros\")\n\tid, _ = Header2ID(\"10\")\n\tassert.Equal(t, int64(16), id, \"Header2ID should convert <16 char strings\")\n\n\tcount := 10000\n\tfor index := 0; index < count; index++ {\n\t\tgeneratedID := randomID()\n\t\theader, _ := ID2Header(generatedID)\n\t\tid, _ := Header2ID(header)\n\t\tassert.Equal(t, generatedID, id, \"Original ID does not match converted back ID\")\n\t}\n}\n\nfunc TestBogusValues(t *testing.T) {\n\tvar id int64\n\n\t\/\/ Header2ID with random strings should return 0\n\tid, err := Header2ID(\"this shouldnt work\")\n\tassert.Equal(t, int64(0), id, \"Bad input should return 0\")\n\tassert.NotNil(t, err, \"An error should be returned\")\n}\n\nfunc TestHexGatewayToAddr(t *testing.T) {\n\ttests := []struct {\n\t\tin          string\n\t\texpected    string\n\t\texpectedErr error\n\t}{\n\t\t{\n\t\t\tin:          \"0101FEA9\",\n\t\t\texpected:    \"169.254.1.1\",\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tin:          \"0101FEAC\",\n\t\t\texpected:    \"172.254.1.1\",\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tin:          \"0101FEA\",\n\t\t\texpected:    \"\",\n\t\t\texpectedErr: errors.New(\"invalid gateway length\"),\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tgatewayHex := []rune(test.in)\n\t\tgateway, err := hexGatewayToAddr(gatewayHex)\n\t\tassert.Equal(t, test.expectedErr, err)\n\t\tassert.Equal(t, test.expected, gateway)\n\t}\n}\n\nfunc TestGetDefaultGateway(t *testing.T) {\n\n\ttests := []struct {\n\t\tin       string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tin: `Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n\neth0\t00000000\t0101FEA9\t0003\t0\t0\t0\t00000000\t0\t0\t0\n\neth0\t0101FEA9\t00000000\t0005\t0\t0\t0\tFFFFFFFF\t0\t0\t0\n\n`,\n\t\t\texpected: \"169.254.1.1\",\n\t\t},\n\t\t{\n\t\t\tin: `Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n\t\t\t\t\t\t\t\t\t\t \neth0\t000011AC\t00000000\t0001\t0\t0\t0\t0000FFFF\t0\t0\t0\n\neth0\t00000000\t010011AC\t0003\t0\t0\t0\t00000000\t0\t0\t0\n                                                                               \n`,\n\t\t\texpected: \"172.17.0.1\",\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tfunc() {\n\t\t\ttmpFile, err := ioutil.TempFile(\"\", \"getdefaultgateway\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tdefer os.Remove(tmpFile.Name())\n\n\t\t\t_, err = tmpFile.WriteString(test.in)\n\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tgateway := getDefaultGateway(tmpFile.Name())\n\n\t\t\tassert.Equal(t, test.expected, gateway)\n\t\t}()\n\t}\n}\n<commit_msg>Use instana.{Min,Max}Int64 constants in tests instead of raw values<commit_after>package instana\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\n\/\/ Trace IDs (and Span IDs) are based on Java Signed Long datatype\nconst (\n\tMinInt64 int64 = -9223372036854775808\n\tMaxInt64 int64 = 9223372036854775807\n)\n\nfunc TestGeneratedIDRange(t *testing.T) {\n\tvar count = 10000\n\tfor index := 0; index < count; index++ {\n\t\tid := randomID()\n\t\tassert.True(t, id <= MaxInt64, \"Generated ID is out of bounds (+)\")\n\t\tassert.True(t, id >= MinInt64, \"Generated ID is out of bounds (-)\")\n\t}\n}\n\nfunc TestIDConversionBackForth(t *testing.T) {\n\tmaxID := int64(MaxInt64)\n\tminID := int64(MinInt64)\n\tmaxHex := \"7fffffffffffffff\"\n\tminHex := \"8000000000000000\"\n\n\t\/\/ Place holders\n\tvar header string\n\tvar id int64\n\n\t\/\/ maxID (int64) -> header -> int64\n\theader, _ = ID2Header(maxID)\n\tid, _ = Header2ID(header)\n\tassert.Equal(t, maxHex, header, \"ID2Header incorrect result.\")\n\tassert.Equal(t, maxID, id, \"Convert back into original is wrong\")\n\n\t\/\/ minHex (unsigned 64bit hex string) -> signed 64bit int -> unsigned 64bit hex string\n\tid, _ = Header2ID(minHex)\n\theader, _ = ID2Header(id)\n\tassert.Equal(t, minID, id, \"Header2ID incorrect result\")\n\tassert.Equal(t, minHex, header, \"Convert back into original is wrong\")\n}\n\nfunc TestIDConversion(t *testing.T) {\n\t\/\/ Place holders\n\tvar header string\n\tvar id int64\n\n\theader, _ = ID2Header(-7815363404733516491)\n\tassert.Equal(t, \"938a406416457535\", header, \"ID2Header incorrect result.\")\n\tid, _ = Header2ID(\"938a406416457535\")\n\tassert.Equal(t, int64(-7815363404733516491), id, \"Header2ID incorrect result\")\n\n\theader, _ = ID2Header(307170163380978816)\n\tassert.Equal(t, \"44349a2d9ec0480\", header, \"ID2Header incorrect result.\")\n\tid, _ = Header2ID(\"44349a2d9ec0480\") \/\/ Without a leading zero\n\tassert.Equal(t, int64(307170163380978816), id, \"Header2ID incorrect result\")\n\tid, _ = Header2ID(\"044349a2d9ec0480\") \/\/ Try with a leading zero\n\tassert.Equal(t, int64(307170163380978816), id, \"Header2ID incorrect result\")\n\n\theader, _ = ID2Header(2920004540187184976)\n\tassert.Equal(t, \"2885f0a890628f50\", header, \"ID2Header incorrect result.\")\n\tid, _ = Header2ID(\"2885f0a890628f50\")\n\tassert.Equal(t, int64(2920004540187184976), id, \"Header2ID incorrect result\")\n\n\theader, _ = ID2Header(16)\n\tassert.Equal(t, \"10\", header, \"ID2Header should drop leading zeros\")\n\tid, _ = Header2ID(\"0000000000000010\")\n\tassert.Equal(t, int64(16), id, \"Header2ID should stll work with leading zeros\")\n\tid, _ = Header2ID(\"10\")\n\tassert.Equal(t, int64(16), id, \"Header2ID should convert <16 char strings\")\n\n\tcount := 10000\n\tfor index := 0; index < count; index++ {\n\t\tgeneratedID := randomID()\n\t\theader, _ := ID2Header(generatedID)\n\t\tid, _ := Header2ID(header)\n\t\tassert.Equal(t, generatedID, id, \"Original ID does not match converted back ID\")\n\t}\n}\n\nfunc TestBogusValues(t *testing.T) {\n\tvar id int64\n\n\t\/\/ Header2ID with random strings should return 0\n\tid, err := Header2ID(\"this shouldnt work\")\n\tassert.Equal(t, int64(0), id, \"Bad input should return 0\")\n\tassert.NotNil(t, err, \"An error should be returned\")\n}\n\nfunc TestHexGatewayToAddr(t *testing.T) {\n\ttests := []struct {\n\t\tin          string\n\t\texpected    string\n\t\texpectedErr error\n\t}{\n\t\t{\n\t\t\tin:          \"0101FEA9\",\n\t\t\texpected:    \"169.254.1.1\",\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tin:          \"0101FEAC\",\n\t\t\texpected:    \"172.254.1.1\",\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tin:          \"0101FEA\",\n\t\t\texpected:    \"\",\n\t\t\texpectedErr: errors.New(\"invalid gateway length\"),\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tgatewayHex := []rune(test.in)\n\t\tgateway, err := hexGatewayToAddr(gatewayHex)\n\t\tassert.Equal(t, test.expectedErr, err)\n\t\tassert.Equal(t, test.expected, gateway)\n\t}\n}\n\nfunc TestGetDefaultGateway(t *testing.T) {\n\n\ttests := []struct {\n\t\tin       string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tin: `Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n\neth0\t00000000\t0101FEA9\t0003\t0\t0\t0\t00000000\t0\t0\t0\n\neth0\t0101FEA9\t00000000\t0005\t0\t0\t0\tFFFFFFFF\t0\t0\t0\n\n`,\n\t\t\texpected: \"169.254.1.1\",\n\t\t},\n\t\t{\n\t\t\tin: `Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n\t\t\t\t\t\t\t\t\t\t \neth0\t000011AC\t00000000\t0001\t0\t0\t0\t0000FFFF\t0\t0\t0\n\neth0\t00000000\t010011AC\t0003\t0\t0\t0\t00000000\t0\t0\t0\n                                                                               \n`,\n\t\t\texpected: \"172.17.0.1\",\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tfunc() {\n\t\t\ttmpFile, err := ioutil.TempFile(\"\", \"getdefaultgateway\")\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tdefer os.Remove(tmpFile.Name())\n\n\t\t\t_, err = tmpFile.WriteString(test.in)\n\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tgateway := getDefaultGateway(tmpFile.Name())\n\n\t\t\tassert.Equal(t, test.expected, gateway)\n\t\t}()\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package server\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"strings\"\n\t\"terrigenesis\/fileserver\/handlers\"\n\t\"terrigenesis\/fileserver\/utils\"\n\t\"time\"\n)\n\nvar sessions []utils.Session\n\n\/*\nStartServer Entry point for fileserver\n*\/\nfunc StartServer() {\n\thandleInterrupt()\n\n\t\/\/ initialize session list\n\tsessions := make([]utils.Session, 0)\n\n\t\/\/ port number\n\tportNum := 3000\n\n\tfmt.Println(\"Listening on port \" + strconv.Itoa(portNum))\n\tfmt.Printf(\"Current sessions %v\\n\", sessions)\n\thttp.HandleFunc(\"\/\", handler)\n\thttp.ListenAndServe(\":\"+strconv.Itoa(portNum), nil)\n}\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"\\n\", r)\n\n\tsplited := strings.Split(r.URL.Path[1:], \"\/\")\n\n\tif r.Method == \"GET\" {\n\t\tswitch request := splited[0]; request {\n\t\t\/\/ Close Connection\n\t\tcase \"closecon\":\n\t\t\tfmt.Println(\">>> Closing Connection\")\n\t\t\tsessions = handlers.CloseConnection(w, r, sessions)\n\t\t\tfmt.Printf(\"Current sessions: %v\\n\\n\", sessions)\n\n\t\tdefault:\n\t\t\tsessions = handleGet(w, r, request, sessions)\n\t\t}\n\t} else if r.Method == \"POST\" {\n\t\tswitch request := splited[0]; request {\n\t\t\/\/ Establish Connection\n\t\tcase \"estabcon\":\n\t\t\tfmt.Println(\">>> Establish Connection\")\n\t\t\tif token, ok := handlers.EstablishConnection(w, r); ok {\n\t\t\t\tsessions = append(sessions, utils.Session{Token: token, CWD: \".\/db\", LastUsed: time.Now()})\n\t\t\t}\n\t\t\tfmt.Printf(\"Current sessions: %v\\n\\n\", sessions)\n\n\t\tdefault:\n\t\t\tsessions = handlePost(w, r, request, sessions)\n\t\t}\n\t}\n}\n\nfunc handleGet(w http.ResponseWriter, r *http.Request, request string, sessions []utils.Session) []utils.Session {\n\tif r.URL.Query()[\"Token\"] == nil {\n\t\thandlers.IllegalArgumentsError(w)\n\t\treturn sessions\n\t}\n\tvar session utils.Session\n\tvar exists bool\n\tif session, exists = utils.SessionExist(sessions, strings.Join(r.URL.Query()[\"Token\"], \"\")); !exists {\n\t\thandlers.SessionNotFoundError(w)\n\t\treturn sessions\n\t}\n\n\t\/\/ now session is available for use\n\tswitch request {\n\t\/\/ Print Working Directory\n\tcase \"pwd\":\n\t\tfmt.Println(\">>> Print Working Directory\")\n\t\thandlers.PrintWorkingDirectory(w, r, session)\n\n\t\/\/ Download File\n\tcase \"downfile\":\n\t\tfmt.Println(\">>> Download File\")\n\n\tdefault:\n\t\t\/\/ TODO: render a snake game\n\t}\n\n\t\/\/ TODO: replace original session with current one\n\n\treturn sessions\n}\n\nfunc handlePost(w http.ResponseWriter, r *http.Request, request string, sessions []utils.Session) []utils.Session {\n\tdefer r.Body.Close()\n\n\tvar body utils.PostBody\n\terr := json.NewDecoder(r.Body).Decode(&body)\n\tif err != nil {\n\t\thandlers.IllegalArgumentsError(w)\n\t\treturn sessions\n\t}\n\tvar session utils.Session\n\tvar exists bool\n\tif session, exists = utils.SessionExist(sessions, body.Token); !exists {\n\t\thandlers.SessionNotFoundError(w)\n\t\treturn sessions\n\t}\n\n\tswitch request {\n\t\/\/ Change Directory\n\tcase \"chdir\":\n\t\tfmt.Println(\">>> Change Directory\")\n\n\t\/\/ Make Directory\n\tcase \"mkdir\":\n\t\tfmt.Println(\">>> Create Directory\")\n\n\t\/\/ Remove Directory\n\tcase \"rmdir\":\n\t\tfmt.Println(\">>> Remove Directory\")\n\n\t\/\/ Upload File\n\tcase \"upfile\":\n\t\tfmt.Println(\">>> Upload File\")\n\t\thandlers.UploadFile(w, r, session)\n\n\t\/\/ Remove File\n\tcase \"rmfile\":\n\t\tfmt.Println(\">>> Remove File\")\n\n\t\/\/ Move File (does not support rename)\n\tcase \"mvfile\":\n\t\tfmt.Println(\">>> Move File\")\n\n\tdefault:\n\t\t\/\/ TODO: render a snake game\n\t}\n\n\t\/\/ TODO: replace original session with current one\n\n\treturn sessions\n}\n\nfunc handleInterrupt() {\n\t\/\/ handle keyboard interrupt\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\tfor sig := range c {\n\t\t\tif sig != nil {\n\t\t\t\tfmt.Println(\"\\rShutting down server...\")\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n<commit_msg>Added snake game for root and exception pages<commit_after>package server\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"strings\"\n\t\"terrigenesis\/fileserver\/handlers\"\n\t\"terrigenesis\/fileserver\/utils\"\n\t\"time\"\n)\n\nvar sessions []utils.Session\n\n\/*\nStartServer Entry point for fileserver\n*\/\nfunc StartServer() {\n\thandleInterrupt()\n\n\t\/\/ initialize session list\n\tsessions := make([]utils.Session, 0)\n\n\t\/\/ port number\n\tportNum := 3000\n\n\tfmt.Println(\"Listening on port \" + strconv.Itoa(portNum))\n\tfmt.Printf(\"Current sessions %v\\n\", sessions)\n\thttp.HandleFunc(\"\/\", handler)\n\thttp.ListenAndServe(\":\"+strconv.Itoa(portNum), nil)\n}\n\nfunc handler(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"\\n\", r)\n\n\t\/\/ root page, render snakey\n\tif len(r.URL.Path) <= 1 {\n\t\trenderSnake(w)\n\t\treturn\n\t}\n\n\tsplited := strings.Split(r.URL.Path[1:], \"\/\")\n\n\tif r.Method == \"GET\" {\n\t\tswitch request := splited[0]; request {\n\t\t\/\/ Close Connection\n\t\tcase \"closecon\":\n\t\t\tfmt.Println(\">>> Closing Connection\")\n\t\t\tsessions = handlers.CloseConnection(w, r, sessions)\n\t\t\tfmt.Printf(\"Current sessions: %v\\n\\n\", sessions)\n\n\t\tdefault:\n\t\t\tsessions = handleGet(w, r, request, sessions)\n\t\t}\n\t} else if r.Method == \"POST\" {\n\t\tswitch request := splited[0]; request {\n\t\t\/\/ Establish Connection\n\t\tcase \"estabcon\":\n\t\t\tfmt.Println(\">>> Establish Connection\")\n\t\t\tif token, ok := handlers.EstablishConnection(w, r); ok {\n\t\t\t\tsessions = append(sessions, utils.Session{Token: token, CWD: \".\/db\", LastUsed: time.Now()})\n\t\t\t}\n\t\t\tfmt.Printf(\"Current sessions: %v\\n\\n\", sessions)\n\n\t\tdefault:\n\t\t\tsessions = handlePost(w, r, request, sessions)\n\t\t}\n\t}\n}\n\nfunc handleGet(w http.ResponseWriter, r *http.Request, request string, sessions []utils.Session) []utils.Session {\n\tdefer r.Body.Close()\n\n\tif r.URL.Query()[\"Token\"] == nil {\n\t\thandlers.IllegalArgumentsError(w)\n\t\treturn sessions\n\t}\n\tvar session utils.Session\n\tvar exists bool\n\tif session, exists = utils.SessionExist(sessions, strings.Join(r.URL.Query()[\"Token\"], \"\")); !exists {\n\t\thandlers.SessionNotFoundError(w)\n\t\treturn sessions\n\t}\n\n\t\/\/ now session is available for use\n\tswitch request {\n\t\/\/ Print Working Directory\n\tcase \"pwd\":\n\t\tfmt.Println(\">>> Print Working Directory\")\n\t\thandlers.PrintWorkingDirectory(w, r, session)\n\n\t\/\/ Download File\n\tcase \"downfile\":\n\t\tfmt.Println(\">>> Download File\")\n\n\tdefault:\n\t\trenderSnake(w)\n\t}\n\n\t\/\/ TODO: replace original session with current one\n\n\treturn sessions\n}\n\nfunc handlePost(w http.ResponseWriter, r *http.Request, request string, sessions []utils.Session) []utils.Session {\n\tdefer r.Body.Close()\n\n\tvar body utils.PostBody\n\terr := json.NewDecoder(r.Body).Decode(&body)\n\tif err != nil {\n\t\thandlers.IllegalArgumentsError(w)\n\t\treturn sessions\n\t}\n\tvar session utils.Session\n\tvar exists bool\n\tif session, exists = utils.SessionExist(sessions, body.Token); !exists {\n\t\thandlers.SessionNotFoundError(w)\n\t\treturn sessions\n\t}\n\n\tswitch request {\n\t\/\/ Change Directory\n\tcase \"chdir\":\n\t\tfmt.Println(\">>> Change Directory\")\n\n\t\/\/ Make Directory\n\tcase \"mkdir\":\n\t\tfmt.Println(\">>> Create Directory\")\n\n\t\/\/ Remove Directory\n\tcase \"rmdir\":\n\t\tfmt.Println(\">>> Remove Directory\")\n\n\t\/\/ Upload File\n\tcase \"upfile\":\n\t\tfmt.Println(\">>> Upload File\")\n\t\thandlers.UploadFile(w, r, session)\n\n\t\/\/ Remove File\n\tcase \"rmfile\":\n\t\tfmt.Println(\">>> Remove File\")\n\n\t\/\/ Move File (does not support rename)\n\tcase \"mvfile\":\n\t\tfmt.Println(\">>> Move File\")\n\n\tdefault:\n\t\trenderSnake(w)\n\t}\n\n\t\/\/ TODO: replace original session with current one\n\n\treturn sessions\n}\n\n\/\/ render a snake game\nfunc renderSnake(w http.ResponseWriter) {\n\tw.Header().Set(\"Content-Type\", \"text\/html; charset=utf-8\")\n\tfmt.Fprint(w, \"<!DOCTYPE html><html lang=\\\"en\\\"><head><meta charset=\\\"UTF-8\\\"><title>Snakey!!!<\/title><canvas id=\\\"canvas\\\" width=\\\"400\\\" height=\\\"400\\\"><\/canvas><\/head><body><script>window.onkeydown=((ctx,snake,food,direction,move,draw)=>((loop,newFood,timer)=>Array.from({length:400}).forEach((_e,i)=>draw(ctx,i,\\\"black\\\"))||(timer=setInterval(()=>loop(newFood)||clearInterval(timer)||console.log(timer)||alert('Game Over'),200))&&(e=>direction=snake[1]-snake[0]==(move=[-1,-20,1,20][(e||event).keyCode-37]||direction)?direction:move))((newFood)=>snake.unshift(move=snake[0]+direction)&&snake.indexOf(move,1)>0||move<0||move>399||direction==1&&move%20==0||direction==-1&&move%20==19?false:(draw(ctx,move,\\\"green\\\")||move==food?newFood()&draw(ctx,food,\\\"red\\\"):draw(ctx,snake.pop(),\\\"Black\\\"))!==[],()=>Array.from({length:8000}).some(e=>snake.indexOf(food=~~(Math.random()*400))===-1)))(document.getElementById('canvas').getContext('2d'),[42,41],43,1,null,(ctx,node,color)=>(ctx.fillStyle=color)&ctx.fillRect(node%20*20+1,~~(node\/20)*20+1,18,18));<\/script><\/body><\/html>\")\n}\n\nfunc handleInterrupt() {\n\t\/\/ handle keyboard interrupt\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt)\n\tgo func() {\n\t\tfor sig := range c {\n\t\t\tif sig != nil {\n\t\t\t\tfmt.Println(\"\\rShutting down server...\")\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc check(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package zmqOutput_test\n\nimport (\n\t. \"github.com\/CapillarySoftware\/goiostat\/diskStat\"\n\t. \"github.com\/CapillarySoftware\/goiostat\/zmqOutput\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t\/\/ . \"github.com\/CapillarySoftware\/goiostat\/protoStat\"\n\t\"fmt\"\n\t. \"github.com\/onsi\/gomega\"\n\tzmq \"github.com\/pebbe\/zmq3\"\n)\n\nfunc sendStats(output ZmqOutput, eStat *ExtendedIoStats, sendCount int) {\n\tfor i := 0; i <= sendCount; i++ {\n\t\toutput.SendStats(eStat)\n\t}\n}\n\nvar _ = Describe(\"ZmqOutput\", func() {\n\teStat := ExtendedIoStats{\n\t\t\"Device\",\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t}\n\n\turl := \"ipc:\/\/\/tmp\/testOutput.ipc\"\n\n\tIt(\"Testing basic send stats\", func() {\n\t\toutput := ZmqOutput{}\n\t\toutput.Connect(url)\n\t\tdefer output.Close()\n\n\t\terr := output.SendStats(&eStat)\n\t\tExpect(err).Should(BeNil())\n\t})\n\n\tIt(\"Call sendStats without initializing socket\", func() {\n\t\toutput := ZmqOutput{}\n\t\tdefer output.Close()\n\t\terr := output.SendStats(&eStat)\n\t\tExpect(err).ShouldNot(BeNil())\n\t})\n\n\t\/\/this test validates zmq works but also sucks for an integration test\n\t\/\/ It(\"Send to recv socket and validate we get what we expect\", func() {\n\t\/\/ \toutput := ZmqOutput{}\n\t\/\/ \tdefer output.Close()\n\t\/\/ \toutput.Connect(url)\n\n\t\/\/ \trecv, err := zmq.NewSocket(zmq.PULL)\n\t\/\/ \tExpect(err).Should(BeNil())\n\t\/\/ \tdefer recv.Close()\n\n\t\/\/ \trecv.Bind(url)\n\t\/\/ \tgo sendStats(output, &eStat, 1)\n\n\t\/\/ \tfor i := 0; i <= 12; i++ {\n\t\/\/ \t\ts, err := recv.RecvBytes(0)\n\t\/\/ \t\tfmt.Println(\"bytes: \", s)\n\t\/\/ \t\tExpect(err).Should(BeNil())\n\t\/\/ \t}\n\t\/\/ })\n})\n<commit_msg>fix build<commit_after>package zmqOutput_test\n\nimport (\n\t. \"github.com\/CapillarySoftware\/goiostat\/diskStat\"\n\t. \"github.com\/CapillarySoftware\/goiostat\/zmqOutput\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t\/\/ . \"github.com\/CapillarySoftware\/goiostat\/protoStat\"\n\t\/\/ \"fmt\"\n\t. \"github.com\/onsi\/gomega\"\n\t\/\/ zmq \"github.com\/pebbe\/zmq3\"\n)\n\nfunc sendStats(output ZmqOutput, eStat *ExtendedIoStats, sendCount int) {\n\tfor i := 0; i <= sendCount; i++ {\n\t\toutput.SendStats(eStat)\n\t}\n}\n\nvar _ = Describe(\"ZmqOutput\", func() {\n\teStat := ExtendedIoStats{\n\t\t\"Device\",\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t}\n\n\turl := \"ipc:\/\/\/tmp\/testOutput1.ipc\"\n\n\tIt(\"Testing basic send stats\", func() {\n\t\toutput := ZmqOutput{}\n\t\toutput.Connect(url)\n\t\tdefer output.Close()\n\n\t\terr := output.SendStats(&eStat)\n\t\tExpect(err).Should(BeNil())\n\t})\n\n\tIt(\"Call sendStats without initializing socket\", func() {\n\t\toutput := ZmqOutput{}\n\t\tdefer output.Close()\n\t\terr := output.SendStats(&eStat)\n\t\tExpect(err).ShouldNot(BeNil())\n\t})\n\n\t\/\/this test validates zmq works but also sucks for an integration test\n\t\/\/ It(\"Send to recv socket and validate we get what we expect\", func() {\n\t\/\/ \toutput := ZmqOutput{}\n\t\/\/ \tdefer output.Close()\n\t\/\/ \toutput.Connect(url)\n\n\t\/\/ \trecv, err := zmq.NewSocket(zmq.PULL)\n\t\/\/ \tExpect(err).Should(BeNil())\n\t\/\/ \tdefer recv.Close()\n\n\t\/\/ \trecv.Bind(url)\n\t\/\/ \tgo sendStats(output, &eStat, 1)\n\n\t\/\/ \tfor i := 0; i <= 12; i++ {\n\t\/\/ \t\ts, err := recv.RecvBytes(0)\n\t\/\/ \t\tfmt.Println(\"bytes: \", s)\n\t\/\/ \t\tExpect(err).Should(BeNil())\n\t\/\/ \t}\n\t\/\/ })\n})\n<|endoftext|>"}
{"text":"<commit_before>\/*\ninet package handles connecting to an irc server and reading and writing to\nthe connection\n*\/\npackage inet\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"log\"\n\t\"math\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ bufferSize is the size of the buffer to be allocated for writes\n\tbufferSize = 16348\n\t\/\/ nBufferedWrites is how many writes can succeed before blocking\n\tnBufferedWrites = 25\n\t\/\/ resetTicks is the number of timePerTick between messages required\n\t\/\/ to bypass queueing.\n\tresetTicks = 3\n\t\/\/ defaultTimePerTick is the default scale of the sleeps and timeouts.\n\tdefaultTimePerTick = time.Second\n)\n\nvar (\n\t\/\/ pong allows replies from pong to write directly without waiting on sleeps\n\tpong = []byte(\"PONG\")\n)\n\n\/\/ Format strings for errors and logging output\nconst (\n\tfmtDiscarded          = \"(%v) <- (DISCARDED) %s\\n\"\n\tfmtWrite              = \"(%v) <- %s\\n\"\n\tfmtWriteErr           = \"(%v) <- (%v) %s\\n\"\n\tfmtRead               = \"(%v) -> %s\\n\"\n\tfmtErrSiphonReadError = \"inet: (%v) read socket error (%s)\\n\"\n\tfmtErrPumpReadError   = \"inet: (%v) write socket error (%s)\\n\"\n\tfmtErrSiphonClosed    = \"inet: (%v) siphon closed (%s)\\n\"\n\tfmtErrPumpClosed      = \"inet: (%v) pump closed (%s)\\n\"\n\terrMsgShutdown        = \"Shut Down\"\n)\n\n\/\/ IrcClient represents a connection to an irc server. It uses a queueing system\n\/\/ to throttle writes to the server. And it implements ReadWriteCloser interface\ntype IrcClient struct {\n\tisShutdown        bool\n\tisShutdownProtect sync.RWMutex\n\n\tconn        net.Conn\n\tsiphonchan  chan []byte\n\tpumpchan    chan []byte\n\tpumpservice chan chan []byte\n\tkillpump    chan int\n\tkillsiphon  chan int\n\tqueue       Queue\n\n\t\/\/ The name of the connection for logging\n\tname string\n\n\t\/\/ write throttling\n\tnThrottled  int\n\tlastwrite   time.Time\n\ttimePerTick time.Duration\n\n\t\/\/ buffering for io.Reader interface\n\treadbuf []byte\n\tpos     int\n}\n\n\/\/ CreateIrcClient initializes the required fields in the IrcClient\nfunc CreateIrcClient(conn net.Conn, name string) *IrcClient {\n\treturn &IrcClient{\n\t\tname:        name,\n\t\tconn:        conn,\n\t\tsiphonchan:  make(chan []byte),\n\t\tpumpchan:    make(chan []byte),\n\t\tpumpservice: make(chan chan []byte),\n\t\ttimePerTick: defaultTimePerTick,\n\t\tlastwrite:   time.Now().Truncate(resetTicks * defaultTimePerTick),\n\t}\n}\n\n\/\/ SpawnWorkers creates two goroutines, one that is constantly reading using\n\/\/ Siphon, and one that is constantly working on eliminating the write queue by\n\/\/ writing. Also sets up the instances kill channels.\nfunc (c *IrcClient) SpawnWorkers(pump, siphon bool) {\n\tif pump {\n\t\tc.killpump = make(chan int)\n\t\tgo c.pump()\n\t}\n\tif siphon {\n\t\tc.killsiphon = make(chan int)\n\t\tgo c.siphon()\n\t}\n}\n\n\/\/ calcSleepTime checks to ensure that if we've been writing in quick succession\n\/\/ we get some sleep time in between writes.\nfunc (c *IrcClient) calcSleepTime(t time.Time) time.Duration {\n\tdur := t.Sub(c.lastwrite)\n\tif dur < 0 {\n\t\tdur = 0\n\t}\n\n\tif dur > (resetTicks * c.timePerTick) {\n\t\tc.nThrottled = 0\n\t\treturn time.Duration(0)\n\t} else {\n\t\tsleep := c.timePerTick * time.Duration(\n\t\t\t0.5+math.Max(0, math.Log2(float64(c.nThrottled)-3.0)),\n\t\t)\n\t\tc.nThrottled += 1\n\t\treturn sleep\n\t}\n}\n\n\/\/ pump enqueues the messages given to Write and writes them to the connection.\n\/\/ It also sleeps a don't-get-glined amount of time between writes.\nfunc (c *IrcClient) pump() {\n\tvar err error\n\tvar sleeper <-chan time.Time\n\tdefer close(c.pumpservice)\n\n\tfor err == nil {\n\t\tselect {\n\t\tcase c.pumpservice <- c.pumpchan:\n\t\t\tmessage := <-c.pumpchan\n\t\t\tif len(message) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif bytes.HasPrefix(message, pong) {\n\t\t\t\tif err = c.writeMessage(message); err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} else if sleeper == nil {\n\t\t\t\tsleepTime := c.calcSleepTime(time.Now())\n\t\t\t\tif sleepTime == 0 {\n\t\t\t\t\tif err = c.writeMessage(message); err != nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tc.queue.Enqueue(message)\n\t\t\t\t\tsleeper = time.After(sleepTime)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tc.queue.Enqueue(message)\n\t\t\t}\n\t\tcase <-sleeper:\n\t\t\tif err = c.writeMessage(c.queue.Dequeue()); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif c.queue.length > 0 {\n\t\t\t\tsleepTime := c.calcSleepTime(time.Now())\n\t\t\t\tsleeper = time.After(sleepTime)\n\t\t\t} else {\n\t\t\t\tsleeper = nil\n\t\t\t}\n\t\tcase <-c.killpump:\n\t\t\tlog.Printf(fmtErrPumpClosed, c.name, errMsgShutdown)\n\t\t\treturn\n\t\t}\n\t}\n\n\t<-c.killpump\n}\n\n\/\/ writeMessage writes a byte array out to the socket, sets the last write time.\nfunc (c *IrcClient) writeMessage(msg []byte) error {\n\tvar n int\n\tvar err error\n\tfor written := 0; written < len(msg); written += n {\n\t\tn, err = c.conn.Write(msg[written:])\n\t\twrote := msg[written : len(msg)-2]\n\t\tif err != nil {\n\t\t\tlog.Printf(fmtWriteErr, c.name, err, wrote)\n\t\t\treturn err\n\t\t}\n\t\tlog.Printf(fmtWrite, c.name, wrote)\n\t\tc.lastwrite = time.Now()\n\t}\n\treturn nil\n}\n\n\/\/ Siphon takes messages from the connection given to the IrcClient and then\n\/\/ uses extractMessages to send them to the readchan.\nfunc (c *IrcClient) siphon() {\n\tbuf := make([]byte, bufferSize)\n\n\tvar err error = nil\n\tvar shutdown bool\n\tvar position, n = 0, 0\n\n\tfor err == nil {\n\t\tn, err = c.conn.Read(buf[position:])\n\n\t\tif n > 0 && (err == nil || err == io.EOF) {\n\t\t\tposition, shutdown = c.extractMessages(buf[:n+position])\n\t\t\tif shutdown {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Printf(fmtErrSiphonReadError, c.name, err)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tclose(c.siphonchan)\n\t<-c.killsiphon\n}\n\n\/\/ extractMessages takes the information in a buffer and splits on \\r\\n pairs.\n\/\/ When it encounters a pair, it creates a copy of the data from start to the\n\/\/ pair and passes it into the readchan from the IrcClient. If no \\r\\n is found\n\/\/ but data is still present in the buffer, it moves this data to the front of\n\/\/ the buffer and returns an index from which the next read should be started at\n\/\/\n\/\/ Note:\n\/\/ the reason for the copy is because of the threadedness, the buffer pointed to\n\/\/ by the slice can be immediately filled with new information once this\n\/\/ function returns and therefore a copy must be made for thread safety.\nfunc (c *IrcClient) extractMessages(buf []byte) (int, bool) {\n\n\tsend := func(chunk []byte) bool {\n\t\tcpy := make([]byte, len(chunk)-2)\n\t\tcopy(cpy, chunk[:len(chunk)-2])\n\t\tselect {\n\t\tcase c.siphonchan <- cpy:\n\t\t\tlog.Printf(fmtRead, c.name, cpy)\n\t\t\treturn false\n\t\tcase <-c.killsiphon:\n\t\t\treturn true\n\t\t}\n\t}\n\n\tstart, remaining, abort := findChunks(buf, send)\n\tif abort {\n\t\treturn 0, true\n\t} else if remaining {\n\t\tcopy(buf[:len(buf)-start], buf[start:])\n\t\treturn len(buf) - start, false\n\t}\n\n\treturn 0, false\n}\n\n\/\/ Close closes the socket, sets an all-consuming dequeuer routine to\n\/\/ eat all the waiting-to-write goroutines, and then waits to acquire a mutex\n\/\/ that will allow it to safely close the writer channel and set a shutdown var.\nfunc (c *IrcClient) Close() error {\n\tif c.IsClosed() {\n\t\treturn nil\n\t}\n\n\terr := c.conn.Close()\n\n\tc.isShutdownProtect.Lock()\n\tc.isShutdown = true\n\tc.isShutdownProtect.Unlock()\n\n\tif c.killpump != nil {\n\t\tc.killpump <- 0\n\t}\n\tif c.killsiphon != nil {\n\t\tc.killsiphon <- 0\n\t}\n\n\treturn err\n}\n\n\/\/ IsClosed returns true if the IrcClient has been closed.\nfunc (c *IrcClient) IsClosed() bool {\n\tc.isShutdownProtect.RLock()\n\tb := c.isShutdown\n\tc.isShutdownProtect.RUnlock()\n\treturn b\n}\n\n\/\/ Reads a message from the read channel in it's entirety. More efficient than\n\/\/ read because read requires you to allocate your own buffer, but since we're\n\/\/ dealing in routines and splitting the buffer the reality is another buffer\n\/\/ has been already allocated to copy the bytes recieved anyways.\nfunc (c *IrcClient) ReadMessage() ([]byte, bool) {\n\tret, ok := <-c.siphonchan\n\tif !ok {\n\t\treturn nil, ok\n\t}\n\treturn ret, ok\n}\n\n\/\/ Retrieves the channel that's used to read.\nfunc (c *IrcClient) ReadChannel() <-chan []byte {\n\treturn c.siphonchan\n}\n\n\/\/ Read implements the io.Reader interface, but this method is just here for\n\/\/ convenience. It is not efficient and should probably not even be used.\n\/\/ Instead use ReadMessage as it it has already allocated a buffer and copied\n\/\/ the contents into it. Using this method requires an extra buffer allocation\n\/\/ and extra copying.\nfunc (c *IrcClient) Read(buf []byte) (int, error) {\n\tif c.pos == 0 {\n\t\tvar ok bool\n\t\tc.readbuf, ok = c.ReadMessage()\n\t\tif !ok {\n\t\t\treturn 0, io.EOF\n\t\t}\n\t}\n\n\tn := copy(buf, c.readbuf[c.pos:])\n\tc.pos += n\n\tif c.pos == len(c.readbuf) {\n\t\tc.readbuf = nil\n\t\tc.pos = 0\n\t}\n\n\treturn n, nil\n}\n\n\/\/ Write implements the io.Writer interface and is the preferred way to write\n\/\/ to the socket. Returns EOF if the client has been closed. The buffer\n\/\/ is split based on \\r\\n and each message is queued, then the Pump is signaled\n\/\/ through the channel with the number of messages queued. A read lock on a\n\/\/ mutex is required to write to the channel to ensure any other thread\n\/\/ cannot close the channel while someone is attempting to write to it.\nfunc (c *IrcClient) Write(buf []byte) (int, error) {\n\tn := len(buf)\n\tif n == 0 {\n\t\treturn 0, nil\n\t}\n\n\twrite := func(msg []byte) bool {\n\t\tservice, ok := <-c.pumpservice\n\t\tif !ok {\n\t\t\treturn true\n\t\t}\n\t\tservice <- msg\n\t\treturn false\n\t}\n\n\tstart, remaining, abort := findChunks(buf, write)\n\tif abort {\n\t\treturn 0, io.EOF\n\t} else if remaining {\n\t\tif write(append(buf[start:], []byte{'\\r', '\\n'}...)) {\n\t\t\treturn start, io.EOF\n\t\t}\n\t}\n\n\treturn n, nil\n}\n\n\/\/ findChunks calls a callback for each \\r\\n encountered.\n\/\/ if there is still a remaining chunk to be dealt with that did not end with\n\/\/ \\r\\n the bool return value will be true.\nfunc findChunks(buf []byte, block func([]byte) bool) (int, bool, bool) {\n\tvar start, i int\n\tfor start, i = 0, 1; i < len(buf); i++ {\n\t\tif buf[i-1] == '\\r' && buf[i] == '\\n' {\n\t\t\ti++\n\t\t\tif block(buf[start:i]) {\n\t\t\t\treturn start, false, true\n\t\t\t}\n\t\t\tif i == len(buf) {\n\t\t\t\treturn start, false, false\n\t\t\t}\n\t\t\tstart = i\n\t\t}\n\t}\n\n\treturn start, true, false\n}\n<commit_msg>Fix useless temp var.<commit_after>\/*\ninet package handles connecting to an irc server and reading and writing to\nthe connection\n*\/\npackage inet\n\nimport (\n\t\"bytes\"\n\t\"io\"\n\t\"log\"\n\t\"math\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ bufferSize is the size of the buffer to be allocated for writes\n\tbufferSize = 16348\n\t\/\/ nBufferedWrites is how many writes can succeed before blocking\n\tnBufferedWrites = 25\n\t\/\/ resetTicks is the number of timePerTick between messages required\n\t\/\/ to bypass queueing.\n\tresetTicks = 3\n\t\/\/ defaultTimePerTick is the default scale of the sleeps and timeouts.\n\tdefaultTimePerTick = time.Second\n)\n\nvar (\n\t\/\/ pong allows replies from pong to write directly without waiting on sleeps\n\tpong = []byte(\"PONG\")\n)\n\n\/\/ Format strings for errors and logging output\nconst (\n\tfmtDiscarded          = \"(%v) <- (DISCARDED) %s\\n\"\n\tfmtWrite              = \"(%v) <- %s\\n\"\n\tfmtWriteErr           = \"(%v) <- (%v) %s\\n\"\n\tfmtRead               = \"(%v) -> %s\\n\"\n\tfmtErrSiphonReadError = \"inet: (%v) read socket error (%s)\\n\"\n\tfmtErrPumpReadError   = \"inet: (%v) write socket error (%s)\\n\"\n\tfmtErrSiphonClosed    = \"inet: (%v) siphon closed (%s)\\n\"\n\tfmtErrPumpClosed      = \"inet: (%v) pump closed (%s)\\n\"\n\terrMsgShutdown        = \"Shut Down\"\n)\n\n\/\/ IrcClient represents a connection to an irc server. It uses a queueing system\n\/\/ to throttle writes to the server. And it implements ReadWriteCloser interface\ntype IrcClient struct {\n\tisShutdown        bool\n\tisShutdownProtect sync.RWMutex\n\n\tconn        net.Conn\n\tsiphonchan  chan []byte\n\tpumpchan    chan []byte\n\tpumpservice chan chan []byte\n\tkillpump    chan int\n\tkillsiphon  chan int\n\tqueue       Queue\n\n\t\/\/ The name of the connection for logging\n\tname string\n\n\t\/\/ write throttling\n\tnThrottled  int\n\tlastwrite   time.Time\n\ttimePerTick time.Duration\n\n\t\/\/ buffering for io.Reader interface\n\treadbuf []byte\n\tpos     int\n}\n\n\/\/ CreateIrcClient initializes the required fields in the IrcClient\nfunc CreateIrcClient(conn net.Conn, name string) *IrcClient {\n\treturn &IrcClient{\n\t\tname:        name,\n\t\tconn:        conn,\n\t\tsiphonchan:  make(chan []byte),\n\t\tpumpchan:    make(chan []byte),\n\t\tpumpservice: make(chan chan []byte),\n\t\ttimePerTick: defaultTimePerTick,\n\t\tlastwrite:   time.Now().Truncate(resetTicks * defaultTimePerTick),\n\t}\n}\n\n\/\/ SpawnWorkers creates two goroutines, one that is constantly reading using\n\/\/ Siphon, and one that is constantly working on eliminating the write queue by\n\/\/ writing. Also sets up the instances kill channels.\nfunc (c *IrcClient) SpawnWorkers(pump, siphon bool) {\n\tif pump {\n\t\tc.killpump = make(chan int)\n\t\tgo c.pump()\n\t}\n\tif siphon {\n\t\tc.killsiphon = make(chan int)\n\t\tgo c.siphon()\n\t}\n}\n\n\/\/ calcSleepTime checks to ensure that if we've been writing in quick succession\n\/\/ we get some sleep time in between writes.\nfunc (c *IrcClient) calcSleepTime(t time.Time) time.Duration {\n\tdur := t.Sub(c.lastwrite)\n\tif dur < 0 {\n\t\tdur = 0\n\t}\n\n\tif dur > (resetTicks * c.timePerTick) {\n\t\tc.nThrottled = 0\n\t\treturn time.Duration(0)\n\t} else {\n\t\tsleep := c.timePerTick * time.Duration(\n\t\t\t0.5+math.Max(0, math.Log2(float64(c.nThrottled)-3.0)),\n\t\t)\n\t\tc.nThrottled += 1\n\t\treturn sleep\n\t}\n}\n\n\/\/ pump enqueues the messages given to Write and writes them to the connection.\n\/\/ It also sleeps a don't-get-glined amount of time between writes.\nfunc (c *IrcClient) pump() {\n\tvar err error\n\tvar sleeper <-chan time.Time\n\tdefer close(c.pumpservice)\n\n\tfor err == nil {\n\t\tselect {\n\t\tcase c.pumpservice <- c.pumpchan:\n\t\t\tmessage := <-c.pumpchan\n\t\t\tif len(message) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif bytes.HasPrefix(message, pong) {\n\t\t\t\tif err = c.writeMessage(message); err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t} else if sleeper == nil {\n\t\t\t\tsleepTime := c.calcSleepTime(time.Now())\n\t\t\t\tif sleepTime == 0 {\n\t\t\t\t\tif err = c.writeMessage(message); err != nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tc.queue.Enqueue(message)\n\t\t\t\t\tsleeper = time.After(sleepTime)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tc.queue.Enqueue(message)\n\t\t\t}\n\t\tcase <-sleeper:\n\t\t\tif err = c.writeMessage(c.queue.Dequeue()); err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif c.queue.length > 0 {\n\t\t\t\tsleepTime := c.calcSleepTime(time.Now())\n\t\t\t\tsleeper = time.After(sleepTime)\n\t\t\t} else {\n\t\t\t\tsleeper = nil\n\t\t\t}\n\t\tcase <-c.killpump:\n\t\t\tlog.Printf(fmtErrPumpClosed, c.name, errMsgShutdown)\n\t\t\treturn\n\t\t}\n\t}\n\n\t<-c.killpump\n}\n\n\/\/ writeMessage writes a byte array out to the socket, sets the last write time.\nfunc (c *IrcClient) writeMessage(msg []byte) error {\n\tvar n int\n\tvar err error\n\tfor written := 0; written < len(msg); written += n {\n\t\tn, err = c.conn.Write(msg[written:])\n\t\twrote := msg[written : len(msg)-2]\n\t\tif err != nil {\n\t\t\tlog.Printf(fmtWriteErr, c.name, err, wrote)\n\t\t\treturn err\n\t\t}\n\t\tlog.Printf(fmtWrite, c.name, wrote)\n\t\tc.lastwrite = time.Now()\n\t}\n\treturn nil\n}\n\n\/\/ Siphon takes messages from the connection given to the IrcClient and then\n\/\/ uses extractMessages to send them to the readchan.\nfunc (c *IrcClient) siphon() {\n\tbuf := make([]byte, bufferSize)\n\n\tvar err error = nil\n\tvar shutdown bool\n\tvar position, n = 0, 0\n\n\tfor err == nil {\n\t\tn, err = c.conn.Read(buf[position:])\n\n\t\tif n > 0 && (err == nil || err == io.EOF) {\n\t\t\tposition, shutdown = c.extractMessages(buf[:n+position])\n\t\t\tif shutdown {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Printf(fmtErrSiphonReadError, c.name, err)\n\t\t\tbreak\n\t\t}\n\t}\n\n\tclose(c.siphonchan)\n\t<-c.killsiphon\n}\n\n\/\/ extractMessages takes the information in a buffer and splits on \\r\\n pairs.\n\/\/ When it encounters a pair, it creates a copy of the data from start to the\n\/\/ pair and passes it into the readchan from the IrcClient. If no \\r\\n is found\n\/\/ but data is still present in the buffer, it moves this data to the front of\n\/\/ the buffer and returns an index from which the next read should be started at\n\/\/\n\/\/ Note:\n\/\/ the reason for the copy is because of the threadedness, the buffer pointed to\n\/\/ by the slice can be immediately filled with new information once this\n\/\/ function returns and therefore a copy must be made for thread safety.\nfunc (c *IrcClient) extractMessages(buf []byte) (int, bool) {\n\n\tsend := func(chunk []byte) bool {\n\t\tcpy := make([]byte, len(chunk)-2)\n\t\tcopy(cpy, chunk[:len(chunk)-2])\n\t\tselect {\n\t\tcase c.siphonchan <- cpy:\n\t\t\tlog.Printf(fmtRead, c.name, cpy)\n\t\t\treturn false\n\t\tcase <-c.killsiphon:\n\t\t\treturn true\n\t\t}\n\t}\n\n\tstart, remaining, abort := findChunks(buf, send)\n\tif abort {\n\t\treturn 0, true\n\t} else if remaining {\n\t\tcopy(buf[:len(buf)-start], buf[start:])\n\t\treturn len(buf) - start, false\n\t}\n\n\treturn 0, false\n}\n\n\/\/ Close closes the socket, sets an all-consuming dequeuer routine to\n\/\/ eat all the waiting-to-write goroutines, and then waits to acquire a mutex\n\/\/ that will allow it to safely close the writer channel and set a shutdown var.\nfunc (c *IrcClient) Close() error {\n\tif c.IsClosed() {\n\t\treturn nil\n\t}\n\n\terr := c.conn.Close()\n\n\tc.isShutdownProtect.Lock()\n\tc.isShutdown = true\n\tc.isShutdownProtect.Unlock()\n\n\tif c.killpump != nil {\n\t\tc.killpump <- 0\n\t}\n\tif c.killsiphon != nil {\n\t\tc.killsiphon <- 0\n\t}\n\n\treturn err\n}\n\n\/\/ IsClosed returns true if the IrcClient has been closed.\nfunc (c *IrcClient) IsClosed() bool {\n\tc.isShutdownProtect.RLock()\n\tdefer c.isShutdownProtect.RUnlock()\n\treturn c.isShutdown\n}\n\n\/\/ Reads a message from the read channel in it's entirety. More efficient than\n\/\/ read because read requires you to allocate your own buffer, but since we're\n\/\/ dealing in routines and splitting the buffer the reality is another buffer\n\/\/ has been already allocated to copy the bytes recieved anyways.\nfunc (c *IrcClient) ReadMessage() ([]byte, bool) {\n\tret, ok := <-c.siphonchan\n\tif !ok {\n\t\treturn nil, ok\n\t}\n\treturn ret, ok\n}\n\n\/\/ Retrieves the channel that's used to read.\nfunc (c *IrcClient) ReadChannel() <-chan []byte {\n\treturn c.siphonchan\n}\n\n\/\/ Read implements the io.Reader interface, but this method is just here for\n\/\/ convenience. It is not efficient and should probably not even be used.\n\/\/ Instead use ReadMessage as it it has already allocated a buffer and copied\n\/\/ the contents into it. Using this method requires an extra buffer allocation\n\/\/ and extra copying.\nfunc (c *IrcClient) Read(buf []byte) (int, error) {\n\tif c.pos == 0 {\n\t\tvar ok bool\n\t\tc.readbuf, ok = c.ReadMessage()\n\t\tif !ok {\n\t\t\treturn 0, io.EOF\n\t\t}\n\t}\n\n\tn := copy(buf, c.readbuf[c.pos:])\n\tc.pos += n\n\tif c.pos == len(c.readbuf) {\n\t\tc.readbuf = nil\n\t\tc.pos = 0\n\t}\n\n\treturn n, nil\n}\n\n\/\/ Write implements the io.Writer interface and is the preferred way to write\n\/\/ to the socket. Returns EOF if the client has been closed. The buffer\n\/\/ is split based on \\r\\n and each message is queued, then the Pump is signaled\n\/\/ through the channel with the number of messages queued. A read lock on a\n\/\/ mutex is required to write to the channel to ensure any other thread\n\/\/ cannot close the channel while someone is attempting to write to it.\nfunc (c *IrcClient) Write(buf []byte) (int, error) {\n\tn := len(buf)\n\tif n == 0 {\n\t\treturn 0, nil\n\t}\n\n\twrite := func(msg []byte) bool {\n\t\tservice, ok := <-c.pumpservice\n\t\tif !ok {\n\t\t\treturn true\n\t\t}\n\t\tservice <- msg\n\t\treturn false\n\t}\n\n\tstart, remaining, abort := findChunks(buf, write)\n\tif abort {\n\t\treturn 0, io.EOF\n\t} else if remaining {\n\t\tif write(append(buf[start:], []byte{'\\r', '\\n'}...)) {\n\t\t\treturn start, io.EOF\n\t\t}\n\t}\n\n\treturn n, nil\n}\n\n\/\/ findChunks calls a callback for each \\r\\n encountered.\n\/\/ if there is still a remaining chunk to be dealt with that did not end with\n\/\/ \\r\\n the bool return value will be true.\nfunc findChunks(buf []byte, block func([]byte) bool) (int, bool, bool) {\n\tvar start, i int\n\tfor start, i = 0, 1; i < len(buf); i++ {\n\t\tif buf[i-1] == '\\r' && buf[i] == '\\n' {\n\t\t\ti++\n\t\t\tif block(buf[start:i]) {\n\t\t\t\treturn start, false, true\n\t\t\t}\n\t\t\tif i == len(buf) {\n\t\t\t\treturn start, false, false\n\t\t\t}\n\t\t\tstart = i\n\t\t}\n\t}\n\n\treturn start, true, false\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package bench contains benchmarks for gathering system information.\n\/\/ These packages are not directly comparable because of the differences\n\/\/ in what they gather, but I wanted to see some numbers.\n\/\/\n\/\/ This will only work on linux systems due to limitations of\n\/\/ github.com\/mohae\/joefriday.\npackage bench\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/DataDog\/gohai\/memory\"\n\t\"github.com\/EricLagergren\/go-gnulib\/sysinfo\"\n\t\"github.com\/cloudfoundry\/gosigar\"\n\tgopsutilmem \"github.com\/shirou\/gopsutil\/mem\"\n)\n\nfunc BenchmarkOSExecCatMemInfo(b *testing.B) {\n\tvar inf *MemInfo\n\tfor i := 0; i < b.N; i++ {\n\t\tinf, _ = GetMemInfoCat()\n\t}\n\t_ = inf\n}\n\nfunc BenchmarkOSExecCatMemInfoToJSON(b *testing.B) {\n\tvar inf []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tinf, _ = GetMemInfoCatToJSON()\n\t}\n\t_ = inf\n}\n\nfunc BenchmarkOSExecCatMemInfoToFlatbuffers(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemDataCat()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkOSExecCatMemInfoToFlatbuffersReuseBuilder(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemDataCatReuseBldr()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkReadMemInfo(b *testing.B) {\n\tvar inf *MemInfo\n\tfor i := 0; i < b.N; i++ {\n\t\tinf, _ = GetMemInfoRead()\n\t}\n\t_ = inf\n}\n\nfunc BenchmarkReadMemInfoToJSON(b *testing.B) {\n\tvar inf []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tinf, _ = GetMemInfoReadToJSON()\n\t}\n\t_ = inf\n}\n\nfunc BenchmarkReadMemInfoToFlatbuffers(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemDataRead()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkReadMemInfoToFlatbuffersReuseBuilder(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemDataReadReuseBldr()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkReadMemInfoReuseBufio(b *testing.B) {\n\tvar inf *MemInfo\n\tfor i := 0; i < b.N; i++ {\n\t\tinf, _ = GetMemInfoReadReuseR()\n\t}\n\t_ = inf\n}\n\nfunc BenchmarkReadMemInfoToJSONReuseBufio(b *testing.B) {\n\tvar inf []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tinf, _ = GetMemInfoReadReuseRToJSON()\n\t}\n\t_ = inf\n}\n\nfunc BenchmarkReadMemInfoToFlatbuffersReuseBufio(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemDataReadReuseR()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkReadMemDataToFlatbuffersReuseBufioReuseBuilder(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemDataReuseRReuseBldr()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkReadMemInfoToFlatbuffersReuseBufioReuseBuilder(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemInfoToFlatbuffersReuseBldr()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkReadMemInfoToFlatbuffersMinAllocs(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemInfoToFlatbuffersMinAllocs()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkGohaiMem(b *testing.B) {\n\ttype Collector interface {\n\t\tName() string\n\t\tCollect() (interface{}, error)\n\t}\n\tvar collector = &memory.Memory{}\n\tvar c interface{}\n\tfor i := 0; i < b.N; i++ {\n\t\tc, _ = collector.Collect()\n\t}\n\t_ = c\n}\n\nfunc BenchmarkGoSigarMem(b *testing.B) {\n\tvar mem sigar.Mem\n\tfor i := 0; i < b.N; i++ {\n\t\tmem.Get()\n\t}\n\t_ = mem\n}\n\nfunc BenchmarkGopsutilMem(b *testing.B) {\n\tvar mem *gopsutilmem.VirtualMemoryStat\n\tfor i := 0; i < b.N; i++ {\n\t\tmem, _ = gopsutilmem.VirtualMemory()\n\t}\n\t_ = mem\n}\n\nfunc BenchmarkGnulibSysinfo(b *testing.B) {\n\tvar memA, memT int64\n\tfor i := 0; i < b.N; i++ {\n\t\tmemA = sysinfo.PhysmemAvailable()\n\t\tmemT = sysinfo.PhysmemTotal()\n\t}\n\t_ = memA\n\t_ = memT\n}\n<commit_msg>rename 3rd party benchmarks; add the owner's name<commit_after>\/\/ Package bench contains benchmarks for gathering system information.\n\/\/ These packages are not directly comparable because of the differences\n\/\/ in what they gather, but I wanted to see some numbers.\n\/\/\n\/\/ This will only work on linux systems due to limitations of\n\/\/ github.com\/mohae\/joefriday.\npackage bench\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/DataDog\/gohai\/memory\"\n\t\"github.com\/EricLagergren\/go-gnulib\/sysinfo\"\n\t\"github.com\/cloudfoundry\/gosigar\"\n\tgopsutilmem \"github.com\/shirou\/gopsutil\/mem\"\n)\n\nfunc BenchmarkOSExecCatMemInfo(b *testing.B) {\n\tvar inf *MemInfo\n\tfor i := 0; i < b.N; i++ {\n\t\tinf, _ = GetMemInfoCat()\n\t}\n\t_ = inf\n}\n\nfunc BenchmarkOSExecCatMemInfoToJSON(b *testing.B) {\n\tvar inf []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tinf, _ = GetMemInfoCatToJSON()\n\t}\n\t_ = inf\n}\n\nfunc BenchmarkOSExecCatMemInfoToFlatbuffers(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemDataCat()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkOSExecCatMemInfoToFlatbuffersReuseBuilder(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemDataCatReuseBldr()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkReadMemInfo(b *testing.B) {\n\tvar inf *MemInfo\n\tfor i := 0; i < b.N; i++ {\n\t\tinf, _ = GetMemInfoRead()\n\t}\n\t_ = inf\n}\n\nfunc BenchmarkReadMemInfoToJSON(b *testing.B) {\n\tvar inf []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tinf, _ = GetMemInfoReadToJSON()\n\t}\n\t_ = inf\n}\n\nfunc BenchmarkReadMemInfoToFlatbuffers(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemDataRead()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkReadMemInfoToFlatbuffersReuseBuilder(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemDataReadReuseBldr()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkReadMemInfoReuseBufio(b *testing.B) {\n\tvar inf *MemInfo\n\tfor i := 0; i < b.N; i++ {\n\t\tinf, _ = GetMemInfoReadReuseR()\n\t}\n\t_ = inf\n}\n\nfunc BenchmarkReadMemInfoToJSONReuseBufio(b *testing.B) {\n\tvar inf []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tinf, _ = GetMemInfoReadReuseRToJSON()\n\t}\n\t_ = inf\n}\n\nfunc BenchmarkReadMemInfoToFlatbuffersReuseBufio(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemDataReadReuseR()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkReadMemDataToFlatbuffersReuseBufioReuseBuilder(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemDataReuseRReuseBldr()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkReadMemInfoToFlatbuffersReuseBufioReuseBuilder(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemInfoToFlatbuffersReuseBldr()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkReadMemInfoToFlatbuffersMinAllocs(b *testing.B) {\n\tvar data []byte\n\tfor i := 0; i < b.N; i++ {\n\t\tdata, _ = GetMemInfoToFlatbuffersMinAllocs()\n\t}\n\t_ = data\n}\n\nfunc BenchmarkDataDogGohaiMem(b *testing.B) {\n\ttype Collector interface {\n\t\tName() string\n\t\tCollect() (interface{}, error)\n\t}\n\tvar collector = &memory.Memory{}\n\tvar c interface{}\n\tfor i := 0; i < b.N; i++ {\n\t\tc, _ = collector.Collect()\n\t}\n\t_ = c\n}\n\nfunc BenchmarkCloudFoundryGoSigarMem(b *testing.B) {\n\tvar mem sigar.Mem\n\tfor i := 0; i < b.N; i++ {\n\t\tmem.Get()\n\t}\n\t_ = mem\n}\n\nfunc BenchmarkShirouGopsutilMem(b *testing.B) {\n\tvar mem *gopsutilmem.VirtualMemoryStat\n\tfor i := 0; i < b.N; i++ {\n\t\tmem, _ = gopsutilmem.VirtualMemory()\n\t}\n\t_ = mem\n}\n\nfunc BenchmarkEricLagergrenGnulibSysinfo(b *testing.B) {\n\tvar memA, memT int64\n\tfor i := 0; i < b.N; i++ {\n\t\tmemA = sysinfo.PhysmemAvailable()\n\t\tmemT = sysinfo.PhysmemTotal()\n\t}\n\t_ = memA\n\t_ = memT\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com\/catatsuy\/isucon6-final\/bench\/fails\"\n\t\"github.com\/catatsuy\/isucon6-final\/bench\/scenario\"\n\t\"github.com\/catatsuy\/isucon6-final\/bench\/score\"\n\t\"github.com\/catatsuy\/isucon6-final\/bench\/session\"\n)\n\nvar BenchmarkTimeout = 30 * time.Second\n\nfunc main() {\n\n\thost := \"\"\n\n\tflag.StringVar(&host, \"host\", \"\", \"ベンチマーク対象のIPアドレス\")\n\n\tflag.Parse()\n\n\tif !regexp.MustCompile(`\\A[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}\\z`).MatchString(host) {\n\t\tlog.Fatal(\"hostの指定が間違っています（例: 127.0.0.1）\")\n\t}\n\tbaseURL := \"https:\/\/\" + host\n\n\t\/\/ 初期チェックで失敗したらそこで終了\n\tinitialCheck(baseURL)\n\tif len(fails.Get()) > 0 {\n\t\toutput()\n\t\treturn\n\t}\n\n\tbenchmark(baseURL)\n\toutput()\n}\n\nfunc initialCheck(baseURL string) {\n\tscenario.CheckCSRFTokenRefreshed(session.New(baseURL))\n}\n\nfunc benchmark(baseURL string) {\n\tloadIndexPageCh := makeChan(2)\n\tcheckCSRFTokenRefreshedCh := makeChan(1)\n\n\ttimeoutCh := time.After(BenchmarkTimeout)\n\nL:\n\tfor {\n\t\tselect {\n\t\tcase <-loadIndexPageCh:\n\t\t\tgo func() {\n\t\t\t\tscenario.LoadIndexPage(session.New(baseURL))\n\t\t\t\tloadIndexPageCh <- struct{}{}\n\t\t\t}()\n\t\tcase <-checkCSRFTokenRefreshedCh:\n\t\t\tgo func() {\n\t\t\t\tscenario.CheckCSRFTokenRefreshed(session.New(baseURL))\n\t\t\t\tcheckCSRFTokenRefreshedCh <- struct{}{}\n\t\t\t}()\n\t\tcase <-timeoutCh:\n\t\t\tbreak L\n\t\t}\n\t}\n}\n\nfunc output() {\n\tb, _ := json.Marshal(struct {\n\t\tScore    int64    `json:\"score\"`\n\t\tMessages []string `json:\"messages\"`\n\t}{Score: score.Get(), Messages: fails.GetUnique()})\n\n\tfmt.Println(string(b))\n}\n\nfunc makeChan(len int) chan struct{} {\n\tch := make(chan struct{}, len)\n\tfor i := 0; i < len; i++ {\n\t\tch <- struct{}{}\n\t}\n\treturn ch\n}\n<commit_msg>正規表現のミスとconstに<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"regexp\"\n\t\"time\"\n\n\t\"github.com\/catatsuy\/isucon6-final\/bench\/fails\"\n\t\"github.com\/catatsuy\/isucon6-final\/bench\/scenario\"\n\t\"github.com\/catatsuy\/isucon6-final\/bench\/score\"\n\t\"github.com\/catatsuy\/isucon6-final\/bench\/session\"\n)\n\nconst BenchmarkTimeout = 30 * time.Second\n\nfunc main() {\n\n\thost := \"\"\n\n\tflag.StringVar(&host, \"host\", \"\", \"ベンチマーク対象のIPアドレス\")\n\n\tflag.Parse()\n\n\tif !regexp.MustCompile(`\\A[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\z`).MatchString(host) {\n\t\tlog.Fatal(\"hostの指定が間違っています（例: 127.0.0.1）\")\n\t}\n\tbaseURL := \"https:\/\/\" + host\n\n\t\/\/ 初期チェックで失敗したらそこで終了\n\tinitialCheck(baseURL)\n\tif len(fails.Get()) > 0 {\n\t\toutput()\n\t\treturn\n\t}\n\n\tbenchmark(baseURL)\n\toutput()\n}\n\nfunc initialCheck(baseURL string) {\n\tscenario.CheckCSRFTokenRefreshed(session.New(baseURL))\n}\n\nfunc benchmark(baseURL string) {\n\tloadIndexPageCh := makeChan(2)\n\tcheckCSRFTokenRefreshedCh := makeChan(1)\n\n\ttimeoutCh := time.After(BenchmarkTimeout)\n\nL:\n\tfor {\n\t\tselect {\n\t\tcase <-loadIndexPageCh:\n\t\t\tgo func() {\n\t\t\t\tscenario.LoadIndexPage(session.New(baseURL))\n\t\t\t\tloadIndexPageCh <- struct{}{}\n\t\t\t}()\n\t\tcase <-checkCSRFTokenRefreshedCh:\n\t\t\tgo func() {\n\t\t\t\tscenario.CheckCSRFTokenRefreshed(session.New(baseURL))\n\t\t\t\tcheckCSRFTokenRefreshedCh <- struct{}{}\n\t\t\t}()\n\t\tcase <-timeoutCh:\n\t\t\tbreak L\n\t\t}\n\t}\n}\n\nfunc output() {\n\tb, _ := json.Marshal(struct {\n\t\tScore    int64    `json:\"score\"`\n\t\tMessages []string `json:\"messages\"`\n\t}{Score: score.Get(), Messages: fails.GetUnique()})\n\n\tfmt.Println(string(b))\n}\n\nfunc makeChan(len int) chan struct{} {\n\tch := make(chan struct{}, len)\n\tfor i := 0; i < len; i++ {\n\t\tch <- struct{}{}\n\t}\n\treturn ch\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build example jsgo\n\npackage main\n\nimport (\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com\/hajimehoshi\/ebiten\"\n\t\"github.com\/hajimehoshi\/ebiten\/ebitenutil\"\n)\n\nvar (\n\ttext          = \"Type on the keyboard:\\n\"\n\tcounter       = 0\n\tbsPrevPressed = false\n)\n\nfunc update(screen *ebiten.Image) error {\n\t\/\/ Add a string from InputChars, that returns string input by users.\n\t\/\/ Note that InputChars result changes every frame, so you need to call this\n\t\/\/ every frame.\n\ttext += string(ebiten.InputChars())\n\n\t\/\/ Adjust the string to be at most 10 lines.\n\tss := strings.Split(text, \"\\n\")\n\tif len(ss) > 10 {\n\t\ttext = strings.Join(ss[len(ss)-10:], \"\\n\")\n\t}\n\n\t\/\/ If the enter key is pressed, add a line break.\n\tif ebiten.IsKeyPressed(ebiten.KeyEnter) && !strings.HasSuffix(text, \"\\n\") {\n\t\ttext += \"\\n\"\n\t}\n\n\t\/\/ If the backspace key is pressed, remove one character.\n\tbsPressed := ebiten.IsKeyPressed(ebiten.KeyBackspace)\n\tif !bsPrevPressed && bsPressed {\n\t\tif len(text) >= 1 {\n\t\t\ttext = text[:len(text)-1]\n\t\t}\n\t}\n\tbsPrevPressed = bsPressed\n\n\tcounter++\n\n\tif ebiten.IsRunningSlowly() {\n\t\treturn nil\n\t}\n\n\t\/\/ Blink the cursor.\n\tt := text\n\tif counter%60 < 30 {\n\t\tt += \"_\"\n\t}\n\tebitenutil.DebugPrint(screen, t)\n\treturn nil\n}\n\nfunc main() {\n\tif err := ebiten.Run(update, 320, 240, 2.0, \"Typewriter (Ebiten Demo)\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>examples\/typewriter: Refactoring: Use inpututil<commit_after>\/\/ Copyright 2017 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build example jsgo\n\npackage main\n\nimport (\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com\/hajimehoshi\/ebiten\"\n\t\"github.com\/hajimehoshi\/ebiten\/ebitenutil\"\n\t\"github.com\/hajimehoshi\/ebiten\/inpututil\"\n)\n\nvar (\n\ttext    = \"Type on the keyboard:\\n\"\n\tcounter = 0\n)\n\nfunc update(screen *ebiten.Image) error {\n\t\/\/ Add a string from InputChars, that returns string input by users.\n\t\/\/ Note that InputChars result changes every frame, so you need to call this\n\t\/\/ every frame.\n\ttext += string(ebiten.InputChars())\n\n\t\/\/ Adjust the string to be at most 10 lines.\n\tss := strings.Split(text, \"\\n\")\n\tif len(ss) > 10 {\n\t\ttext = strings.Join(ss[len(ss)-10:], \"\\n\")\n\t}\n\n\t\/\/ If the enter key is pressed, add a line break.\n\tif inpututil.IsKeyJustPressed(ebiten.KeyEnter) || inpututil.IsKeyJustPressed(ebiten.KeyKPEnter) {\n\t\ttext += \"\\n\"\n\t}\n\n\t\/\/ If the backspace key is pressed, remove one character.\n\tif inpututil.IsKeyJustPressed(ebiten.KeyBackspace) {\n\t\tif len(text) >= 1 {\n\t\t\ttext = text[:len(text)-1]\n\t\t}\n\t}\n\n\tcounter++\n\n\tif ebiten.IsRunningSlowly() {\n\t\treturn nil\n\t}\n\n\t\/\/ Blink the cursor.\n\tt := text\n\tif counter%60 < 30 {\n\t\tt += \"_\"\n\t}\n\tebitenutil.DebugPrint(screen, t)\n\treturn nil\n}\n\nfunc main() {\n\tif err := ebiten.Run(update, 320, 240, 2.0, \"Typewriter (Ebiten Demo)\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package topology\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/raft\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/master_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/sequence\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/needle\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/super_block\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/util\"\n)\n\ntype Topology struct {\n\tvacuumLockCounter int64\n\tNodeImpl\n\n\tcollectionMap  *util.ConcurrentReadMap\n\tecShardMap     map[needle.VolumeId]*EcShardLocations\n\tecShardMapLock sync.RWMutex\n\n\tpulse int64\n\n\tvolumeSizeLimit  uint64\n\treplicationAsMin bool\n\n\tSequence sequence.Sequencer\n\n\tchanFullVolumes chan storage.VolumeInfo\n\n\tConfiguration *Configuration\n\n\tRaftServer raft.Server\n}\n\nfunc NewTopology(id string, seq sequence.Sequencer, volumeSizeLimit uint64, pulse int, replicationAsMin bool) *Topology {\n\tt := &Topology{}\n\tt.id = NodeId(id)\n\tt.nodeType = \"Topology\"\n\tt.NodeImpl.value = t\n\tt.children = make(map[NodeId]Node)\n\tt.collectionMap = util.NewConcurrentReadMap()\n\tt.ecShardMap = make(map[needle.VolumeId]*EcShardLocations)\n\tt.pulse = int64(pulse)\n\tt.volumeSizeLimit = volumeSizeLimit\n\tt.replicationAsMin = replicationAsMin\n\n\tt.Sequence = seq\n\n\tt.chanFullVolumes = make(chan storage.VolumeInfo)\n\n\tt.Configuration = &Configuration{}\n\n\treturn t\n}\n\nfunc (t *Topology) IsLeader() bool {\n\tif t.RaftServer != nil {\n\t\tif t.RaftServer.State() == raft.Leader {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (t *Topology) Leader() (string, error) {\n\tl := \"\"\n\tcount := 3\n\tfor count > 0 {\n\t\tif t.RaftServer != nil {\n\t\t\tl = t.RaftServer.Leader()\n\t\t} else {\n\t\t\treturn \"\", errors.New(\"Raft Server not ready yet!\")\n\t\t}\n\t\tif l != \"\" {\n\t\t\tbreak\n\t\t} else {\n\t\t\ttime.Sleep(time.Duration(5-count) * time.Second)\n\t\t}\n\t\tcount -= 1\n\t}\n\treturn l, nil\n}\n\nfunc (t *Topology) Lookup(collection string, vid needle.VolumeId) (dataNodes []*DataNode) {\n\t\/\/maybe an issue if lots of collections?\n\tif collection == \"\" {\n\t\tfor _, c := range t.collectionMap.Items() {\n\t\t\tif list := c.(*Collection).Lookup(vid); list != nil {\n\t\t\t\treturn list\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif c, ok := t.collectionMap.Find(collection); ok {\n\t\t\treturn c.(*Collection).Lookup(vid)\n\t\t}\n\t}\n\n\tif locations, found := t.LookupEcShards(vid); found {\n\t\tfor _, loc := range locations.Locations {\n\t\t\tdataNodes = append(dataNodes, loc...)\n\t\t}\n\t\treturn dataNodes\n\t}\n\n\treturn nil\n}\n\nfunc (t *Topology) NextVolumeId() (needle.VolumeId, error) {\n\tvid := t.GetMaxVolumeId()\n\tnext := vid.Next()\n\tif _, err := t.RaftServer.Do(NewMaxVolumeIdCommand(next)); err != nil {\n\t\treturn 0, err\n\t}\n\treturn next, nil\n}\n\nfunc (t *Topology) HasWritableVolume(option *VolumeGrowOption) bool {\n\tvl := t.GetVolumeLayout(option.Collection, option.ReplicaPlacement, option.Ttl)\n\treturn vl.GetActiveVolumeCount(option) > 0\n}\n\nfunc (t *Topology) PickForWrite(count uint64, option *VolumeGrowOption) (string, uint64, *DataNode, error) {\n\tvid, count, datanodes, err := t.GetVolumeLayout(option.Collection, option.ReplicaPlacement, option.Ttl).PickForWrite(count, option)\n\tif err != nil {\n\t\treturn \"\", 0, nil, fmt.Errorf(\"failed to find writable volumes for collection:%s replication:%s ttl:%s error: %v\", option.Collection, option.ReplicaPlacement.String(), option.Ttl.String(), err)\n\t}\n\tif datanodes.Length() == 0 {\n\t\treturn \"\", 0, nil, fmt.Errorf(\"no writable volumes available for collection:%s replication:%s ttl:%s\", option.Collection, option.ReplicaPlacement.String(), option.Ttl.String())\n\t}\n\tfileId := t.Sequence.NextFileId(count)\n\treturn needle.NewFileId(*vid, fileId, rand.Uint32()).String(), count, datanodes.Head(), nil\n}\n\nfunc (t *Topology) GetVolumeLayout(collectionName string, rp *super_block.ReplicaPlacement, ttl *needle.TTL) *VolumeLayout {\n\treturn t.collectionMap.Get(collectionName, func() interface{} {\n\t\treturn NewCollection(collectionName, t.volumeSizeLimit, t.replicationAsMin)\n\t}).(*Collection).GetOrCreateVolumeLayout(rp, ttl)\n}\n\nfunc (t *Topology) ListCollections(includeNormalVolumes, includeEcVolumes bool) (ret []string) {\n\n\tmapOfCollections := make(map[string]bool)\n\tfor _, c := range t.collectionMap.Items() {\n\t\tmapOfCollections[c.(*Collection).Name] = true\n\t}\n\n\tif includeEcVolumes {\n\t\tt.ecShardMapLock.RLock()\n\t\tfor _, ecVolumeLocation := range t.ecShardMap {\n\t\t\tmapOfCollections[ecVolumeLocation.Collection] = true\n\t\t}\n\t\tt.ecShardMapLock.RUnlock()\n\t}\n\n\tfor k := range mapOfCollections {\n\t\tret = append(ret, k)\n\t}\n\treturn ret\n}\n\nfunc (t *Topology) FindCollection(collectionName string) (*Collection, bool) {\n\tc, hasCollection := t.collectionMap.Find(collectionName)\n\tif !hasCollection {\n\t\treturn nil, false\n\t}\n\treturn c.(*Collection), hasCollection\n}\n\nfunc (t *Topology) DeleteCollection(collectionName string) {\n\tt.collectionMap.Delete(collectionName)\n}\n\nfunc (t *Topology) RegisterVolumeLayout(v storage.VolumeInfo, dn *DataNode) {\n\tt.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl).RegisterVolume(&v, dn)\n}\nfunc (t *Topology) UnRegisterVolumeLayout(v storage.VolumeInfo, dn *DataNode) {\n\tglog.Infof(\"removing volume info:%+v\", v)\n\tvolumeLayout := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl)\n\tvolumeLayout.UnRegisterVolume(&v, dn)\n\tif volumeLayout.isEmpty() {\n\t\tt.DeleteCollection(v.Collection)\n\t}\n}\n\nfunc (t *Topology) GetOrCreateDataCenter(dcName string) *DataCenter {\n\tfor _, c := range t.Children() {\n\t\tdc := c.(*DataCenter)\n\t\tif string(dc.Id()) == dcName {\n\t\t\treturn dc\n\t\t}\n\t}\n\tdc := NewDataCenter(dcName)\n\tt.LinkChildNode(dc)\n\treturn dc\n}\n\nfunc (t *Topology) SyncDataNodeRegistration(volumes []*master_pb.VolumeInformationMessage, dn *DataNode) (newVolumes, deletedVolumes []storage.VolumeInfo) {\n\t\/\/ convert into in memory struct storage.VolumeInfo\n\tvar volumeInfos []storage.VolumeInfo\n\tfor _, v := range volumes {\n\t\tif vi, err := storage.NewVolumeInfo(v); err == nil {\n\t\t\tvolumeInfos = append(volumeInfos, vi)\n\t\t} else {\n\t\t\tglog.V(0).Infof(\"Fail to convert joined volume information: %v\", err)\n\t\t}\n\t}\n\t\/\/ find out the delta volumes\n\tvar changedVolumes []storage.VolumeInfo\n\tnewVolumes, deletedVolumes, changedVolumes = dn.UpdateVolumes(volumeInfos)\n\tfor _, v := range newVolumes {\n\t\tt.RegisterVolumeLayout(v, dn)\n\t}\n\tfor _, v := range deletedVolumes {\n\t\tt.UnRegisterVolumeLayout(v, dn)\n\t}\n\tfor _, v := range changedVolumes {\n\t\tvl := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl)\n\t\tvl.ensureCorrectWritables(&v)\n\t}\n\treturn\n}\n\nfunc (t *Topology) IncrementalSyncDataNodeRegistration(newVolumes, deletedVolumes []*master_pb.VolumeShortInformationMessage, dn *DataNode) {\n\tvar newVis, oldVis []storage.VolumeInfo\n\tfor _, v := range newVolumes {\n\t\tvi, err := storage.NewVolumeInfoFromShort(v)\n\t\tif err != nil {\n\t\t\tglog.V(0).Infof(\"NewVolumeInfoFromShort %v: %v\", v, err)\n\t\t\tcontinue\n\t\t}\n\t\tnewVis = append(newVis, vi)\n\t}\n\tfor _, v := range deletedVolumes {\n\t\tvi, err := storage.NewVolumeInfoFromShort(v)\n\t\tif err != nil {\n\t\t\tglog.V(0).Infof(\"NewVolumeInfoFromShort %v: %v\", v, err)\n\t\t\tcontinue\n\t\t}\n\t\toldVis = append(oldVis, vi)\n\t}\n\tdn.DeltaUpdateVolumes(newVis, oldVis)\n\n\tfor _, vi := range newVis {\n\t\tt.RegisterVolumeLayout(vi, dn)\n\t}\n\tfor _, vi := range oldVis {\n\t\tt.UnRegisterVolumeLayout(vi, dn)\n\t}\n\n\treturn\n}\n<commit_msg>minor adjustments<commit_after>package topology\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/chrislusf\/raft\"\n\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/glog\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/pb\/master_pb\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/sequence\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/needle\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/storage\/super_block\"\n\t\"github.com\/chrislusf\/seaweedfs\/weed\/util\"\n)\n\ntype Topology struct {\n\tvacuumLockCounter int64\n\tNodeImpl\n\n\tcollectionMap  *util.ConcurrentReadMap\n\tecShardMap     map[needle.VolumeId]*EcShardLocations\n\tecShardMapLock sync.RWMutex\n\n\tpulse int64\n\n\tvolumeSizeLimit  uint64\n\treplicationAsMin bool\n\n\tSequence sequence.Sequencer\n\n\tchanFullVolumes chan storage.VolumeInfo\n\n\tConfiguration *Configuration\n\n\tRaftServer raft.Server\n}\n\nfunc NewTopology(id string, seq sequence.Sequencer, volumeSizeLimit uint64, pulse int, replicationAsMin bool) *Topology {\n\tt := &Topology{}\n\tt.id = NodeId(id)\n\tt.nodeType = \"Topology\"\n\tt.NodeImpl.value = t\n\tt.children = make(map[NodeId]Node)\n\tt.collectionMap = util.NewConcurrentReadMap()\n\tt.ecShardMap = make(map[needle.VolumeId]*EcShardLocations)\n\tt.pulse = int64(pulse)\n\tt.volumeSizeLimit = volumeSizeLimit\n\tt.replicationAsMin = replicationAsMin\n\n\tt.Sequence = seq\n\n\tt.chanFullVolumes = make(chan storage.VolumeInfo)\n\n\tt.Configuration = &Configuration{}\n\n\treturn t\n}\n\nfunc (t *Topology) IsLeader() bool {\n\tif t.RaftServer != nil {\n\t\tif t.RaftServer.State() == raft.Leader {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (t *Topology) Leader() (string, error) {\n\tl := \"\"\n\tfor count := 0; count < 3; count++ {\n\t\tif t.RaftServer != nil {\n\t\t\tl = t.RaftServer.Leader()\n\t\t} else {\n\t\t\treturn \"\", errors.New(\"Raft Server not ready yet!\")\n\t\t}\n\t\tif l != \"\" {\n\t\t\tbreak\n\t\t} else {\n\t\t\ttime.Sleep(time.Duration(5+count) * time.Second)\n\t\t}\n\t}\n\treturn l, nil\n}\n\nfunc (t *Topology) Lookup(collection string, vid needle.VolumeId) (dataNodes []*DataNode) {\n\t\/\/ maybe an issue if lots of collections?\n\tif collection == \"\" {\n\t\tfor _, c := range t.collectionMap.Items() {\n\t\t\tif list := c.(*Collection).Lookup(vid); list != nil {\n\t\t\t\treturn list\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif c, ok := t.collectionMap.Find(collection); ok {\n\t\t\treturn c.(*Collection).Lookup(vid)\n\t\t}\n\t}\n\n\tif locations, found := t.LookupEcShards(vid); found {\n\t\tfor _, loc := range locations.Locations {\n\t\t\tdataNodes = append(dataNodes, loc...)\n\t\t}\n\t\treturn dataNodes\n\t}\n\n\treturn nil\n}\n\nfunc (t *Topology) NextVolumeId() (needle.VolumeId, error) {\n\tvid := t.GetMaxVolumeId()\n\tnext := vid.Next()\n\tif _, err := t.RaftServer.Do(NewMaxVolumeIdCommand(next)); err != nil {\n\t\treturn 0, err\n\t}\n\treturn next, nil\n}\n\nfunc (t *Topology) HasWritableVolume(option *VolumeGrowOption) bool {\n\tvl := t.GetVolumeLayout(option.Collection, option.ReplicaPlacement, option.Ttl)\n\treturn vl.GetActiveVolumeCount(option) > 0\n}\n\nfunc (t *Topology) PickForWrite(count uint64, option *VolumeGrowOption) (string, uint64, *DataNode, error) {\n\tvid, count, datanodes, err := t.GetVolumeLayout(option.Collection, option.ReplicaPlacement, option.Ttl).PickForWrite(count, option)\n\tif err != nil {\n\t\treturn \"\", 0, nil, fmt.Errorf(\"failed to find writable volumes for collection:%s replication:%s ttl:%s error: %v\", option.Collection, option.ReplicaPlacement.String(), option.Ttl.String(), err)\n\t}\n\tif datanodes.Length() == 0 {\n\t\treturn \"\", 0, nil, fmt.Errorf(\"no writable volumes available for collection:%s replication:%s ttl:%s\", option.Collection, option.ReplicaPlacement.String(), option.Ttl.String())\n\t}\n\tfileId := t.Sequence.NextFileId(count)\n\treturn needle.NewFileId(*vid, fileId, rand.Uint32()).String(), count, datanodes.Head(), nil\n}\n\nfunc (t *Topology) GetVolumeLayout(collectionName string, rp *super_block.ReplicaPlacement, ttl *needle.TTL) *VolumeLayout {\n\treturn t.collectionMap.Get(collectionName, func() interface{} {\n\t\treturn NewCollection(collectionName, t.volumeSizeLimit, t.replicationAsMin)\n\t}).(*Collection).GetOrCreateVolumeLayout(rp, ttl)\n}\n\nfunc (t *Topology) ListCollections(includeNormalVolumes, includeEcVolumes bool) (ret []string) {\n\n\tmapOfCollections := make(map[string]bool)\n\tfor _, c := range t.collectionMap.Items() {\n\t\tmapOfCollections[c.(*Collection).Name] = true\n\t}\n\n\tif includeEcVolumes {\n\t\tt.ecShardMapLock.RLock()\n\t\tfor _, ecVolumeLocation := range t.ecShardMap {\n\t\t\tmapOfCollections[ecVolumeLocation.Collection] = true\n\t\t}\n\t\tt.ecShardMapLock.RUnlock()\n\t}\n\n\tfor k := range mapOfCollections {\n\t\tret = append(ret, k)\n\t}\n\treturn ret\n}\n\nfunc (t *Topology) FindCollection(collectionName string) (*Collection, bool) {\n\tc, hasCollection := t.collectionMap.Find(collectionName)\n\tif !hasCollection {\n\t\treturn nil, false\n\t}\n\treturn c.(*Collection), hasCollection\n}\n\nfunc (t *Topology) DeleteCollection(collectionName string) {\n\tt.collectionMap.Delete(collectionName)\n}\n\nfunc (t *Topology) RegisterVolumeLayout(v storage.VolumeInfo, dn *DataNode) {\n\tt.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl).RegisterVolume(&v, dn)\n}\nfunc (t *Topology) UnRegisterVolumeLayout(v storage.VolumeInfo, dn *DataNode) {\n\tglog.Infof(\"removing volume info:%+v\", v)\n\tvolumeLayout := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl)\n\tvolumeLayout.UnRegisterVolume(&v, dn)\n\tif volumeLayout.isEmpty() {\n\t\tt.DeleteCollection(v.Collection)\n\t}\n}\n\nfunc (t *Topology) GetOrCreateDataCenter(dcName string) *DataCenter {\n\tfor _, c := range t.Children() {\n\t\tdc := c.(*DataCenter)\n\t\tif string(dc.Id()) == dcName {\n\t\t\treturn dc\n\t\t}\n\t}\n\tdc := NewDataCenter(dcName)\n\tt.LinkChildNode(dc)\n\treturn dc\n}\n\nfunc (t *Topology) SyncDataNodeRegistration(volumes []*master_pb.VolumeInformationMessage, dn *DataNode) (newVolumes, deletedVolumes []storage.VolumeInfo) {\n\t\/\/ convert into in memory struct storage.VolumeInfo\n\tvar volumeInfos []storage.VolumeInfo\n\tfor _, v := range volumes {\n\t\tif vi, err := storage.NewVolumeInfo(v); err == nil {\n\t\t\tvolumeInfos = append(volumeInfos, vi)\n\t\t} else {\n\t\t\tglog.V(0).Infof(\"Fail to convert joined volume information: %v\", err)\n\t\t}\n\t}\n\t\/\/ find out the delta volumes\n\tvar changedVolumes []storage.VolumeInfo\n\tnewVolumes, deletedVolumes, changedVolumes = dn.UpdateVolumes(volumeInfos)\n\tfor _, v := range newVolumes {\n\t\tt.RegisterVolumeLayout(v, dn)\n\t}\n\tfor _, v := range deletedVolumes {\n\t\tt.UnRegisterVolumeLayout(v, dn)\n\t}\n\tfor _, v := range changedVolumes {\n\t\tvl := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl)\n\t\tvl.ensureCorrectWritables(&v)\n\t}\n\treturn\n}\n\nfunc (t *Topology) IncrementalSyncDataNodeRegistration(newVolumes, deletedVolumes []*master_pb.VolumeShortInformationMessage, dn *DataNode) {\n\tvar newVis, oldVis []storage.VolumeInfo\n\tfor _, v := range newVolumes {\n\t\tvi, err := storage.NewVolumeInfoFromShort(v)\n\t\tif err != nil {\n\t\t\tglog.V(0).Infof(\"NewVolumeInfoFromShort %v: %v\", v, err)\n\t\t\tcontinue\n\t\t}\n\t\tnewVis = append(newVis, vi)\n\t}\n\tfor _, v := range deletedVolumes {\n\t\tvi, err := storage.NewVolumeInfoFromShort(v)\n\t\tif err != nil {\n\t\t\tglog.V(0).Infof(\"NewVolumeInfoFromShort %v: %v\", v, err)\n\t\t\tcontinue\n\t\t}\n\t\toldVis = append(oldVis, vi)\n\t}\n\tdn.DeltaUpdateVolumes(newVis, oldVis)\n\n\tfor _, vi := range newVis {\n\t\tt.RegisterVolumeLayout(vi, dn)\n\t}\n\tfor _, vi := range oldVis {\n\t\tt.UnRegisterVolumeLayout(vi, dn)\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package interactive\n\nimport (\n\t\"os\"\n\t\"fmt\"\n\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"go\/parser\"\n\n\trl \"code.google.com\/p\/go-gnureadline\"\n)\n\nfunc Run(env *Env) {\n\tvar line string\n\tterm := os.ExpandEnv(\"TERM\")\n\n\tnames := completions(env)\n\n\trl.SetAttemptedCompletionFunction(func(text string, start, end int) []string {\n\t\tif text == \"\" {\n\t\t\treturn nil\n\t\t}\n\n\t\tn := len(names)\n\t\ttop := sort.Search(n, func(i int) bool { return text <= names[i] })\n\t\tbot := sort.Search(n, func(i int) bool { return i >= top && !strings.HasPrefix(names[i], text) })\n\n\t\tif bot == top {\n\t\t\treturn nil\n\t\t} else if bot - top == 1 {\n\t\t\treturn names[top:bot]\n\t\t} else {\n\t\t\tntop := names[top]\n\t\t\tnbot := names[bot-1]\n\t\t\tn := len(ntop)\n\t\t\tif len(nbot) < n {\n\t\t\t\tn = len(nbot)\n\t\t\t}\n\t\t\tvar i int\n\t\t\tfor i = 0; i < n && ntop[i] == nbot[i]; i += 1 {}\n\n\t\t\treturn append([]string{ntop[0:i]}, names[top:bot]...)\n\t\t}\n\t})\n\n\tline, rlerr := rl.Readline(\"go> \")\n\tfor rlerr == nil && line != \"quit\" {\n\n\t\t\/\/line = \"func() {\" + line + \"}\"\n\t\tif expr, err := parser.ParseExpr(line); err != nil {\n\t\t\tfmt.Printf(\"%s\\n\", err)\n\t\t} else if vals, _, err := evalExpr(expr, env); err != nil {\n\t\t\tfmt.Printf(\"%s\\n\", err)\n\t\t} else if len(vals) == 0 {\n\t\t\tfmt.Printf(\"void\")\n\t\t} else if len(vals) == 1 {\n\t\t\tfmt.Printf(\"%v\\n\", vals[0].Interface())\n\t\t} else {\n\t\t\tsep := \"(\"\n\t\t\tfor _, v := range vals {\n\t\t\t\tfmt.Printf(\"%s%v\", sep, v.Interface())\n\t\t\t}\n\t\t\tfmt.Printf(\")\\n\")\n\t\t}\n\n\t\tline, rlerr = rl.Readline(\"go> \")\n\n\t}\n\t\/\/WriteHistory(\"data\/deleteme.history\")\n\trl.Rl_reset_terminal(term)\n}\n\nfunc completions (env *Env) (names []string) {\n\tprefix := env.Name\n\tif env.Name == \".\" {\n\t\tfor k := range builtinTypes {\n\t\t\tnames = append(names, k)\n\t\t}\n\t\tfor k := range builtinFuncs {\n\t\t\tnames = append(names, k)\n\t\t}\n\t\tfor _, v := range env.Pkgs {\n\t\t\tnames = append(names, completions(v)...)\n\t\t}\n\t\tprefix = \"\"\n\t} else {\n\t\tprefix += \".\"\n\t}\n\n\tfor k := range env.Vars {\n\t\tnames = append(names, prefix + k)\n\t}\n\n\tfor k := range env.Consts {\n\t\tnames = append(names, prefix + k)\n\t}\n\n\tfor k := range env.Funcs {\n\t\tnames = append(names, k)\n\t}\n\n\tfor k, v := range env.Types {\n\t\tnames = append(names, prefix + k)\n\t\tif v.Kind() == reflect.Struct {\n\t\t\tfor i := 0; i < v.NumField(); i += 1 {\n\t\t\t\tnames = append(names, v.Field(i).Name)\n\t\t\t}\n\t\t}\n\t\tif v.Kind() == reflect.Struct || v.Kind() == reflect.Interface {\n\t\t\tfor i := 0; i < v.NumMethod(); i += 1 {\n\t\t\t\tnames = append(names, v.Method(i).Name)\n\t\t\t}\n\t\t}\n\t}\n\tsort.Strings(names)\n\treturn names\n}\n<commit_msg>Correctly add function names to namespace.<commit_after>package interactive\n\nimport (\n\t\"os\"\n\t\"fmt\"\n\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"go\/parser\"\n\n\trl \"code.google.com\/p\/go-gnureadline\"\n)\n\nfunc Run(env *Env) {\n\tvar line string\n\tterm := os.ExpandEnv(\"TERM\")\n\n\tnames := completions(env)\n\n\trl.SetAttemptedCompletionFunction(func(text string, start, end int) []string {\n\t\tif text == \"\" {\n\t\t\treturn nil\n\t\t}\n\n\t\tn := len(names)\n\t\ttop := sort.Search(n, func(i int) bool { return text <= names[i] })\n\t\tbot := sort.Search(n, func(i int) bool { return i >= top && !strings.HasPrefix(names[i], text) })\n\n\t\tif bot == top {\n\t\t\treturn nil\n\t\t} else if bot - top == 1 {\n\t\t\treturn names[top:bot]\n\t\t} else {\n\t\t\tntop := names[top]\n\t\t\tnbot := names[bot-1]\n\t\t\tn := len(ntop)\n\t\t\tif len(nbot) < n {\n\t\t\t\tn = len(nbot)\n\t\t\t}\n\t\t\tvar i int\n\t\t\tfor i = 0; i < n && ntop[i] == nbot[i]; i += 1 {}\n\n\t\t\treturn append([]string{ntop[0:i]}, names[top:bot]...)\n\t\t}\n\t})\n\n\tline, rlerr := rl.Readline(\"go> \")\n\tfor rlerr == nil && line != \"quit\" {\n\n\t\t\/\/line = \"func() {\" + line + \"}\"\n\t\tif expr, err := parser.ParseExpr(line); err != nil {\n\t\t\tfmt.Printf(\"%s\\n\", err)\n\t\t} else if vals, _, err := evalExpr(expr, env); err != nil {\n\t\t\tfmt.Printf(\"%s\\n\", err)\n\t\t} else if len(vals) == 0 {\n\t\t\tfmt.Printf(\"void\")\n\t\t} else if len(vals) == 1 {\n\t\t\tfmt.Printf(\"%v\\n\", vals[0].Interface())\n\t\t} else {\n\t\t\tsep := \"(\"\n\t\t\tfor _, v := range vals {\n\t\t\t\tfmt.Printf(\"%s%v\", sep, v.Interface())\n\t\t\t}\n\t\t\tfmt.Printf(\")\\n\")\n\t\t}\n\n\t\tline, rlerr = rl.Readline(\"go> \")\n\n\t}\n\t\/\/WriteHistory(\"data\/deleteme.history\")\n\trl.Rl_reset_terminal(term)\n}\n\nfunc completions (env *Env) (names []string) {\n\tprefix := env.Name\n\tif env.Name == \".\" {\n\t\tfor k := range builtinTypes {\n\t\t\tnames = append(names, k)\n\t\t}\n\t\tfor k := range builtinFuncs {\n\t\t\tnames = append(names, k)\n\t\t}\n\t\tfor _, v := range env.Pkgs {\n\t\t\tnames = append(names, completions(v)...)\n\t\t}\n\t\tprefix = \"\"\n\t} else {\n\t\tprefix += \".\"\n\t}\n\n\tfor k := range env.Vars {\n\t\tnames = append(names, prefix + k)\n\t}\n\n\tfor k := range env.Consts {\n\t\tnames = append(names, prefix + k)\n\t}\n\n\tfor k := range env.Funcs {\n\t\tnames = append(names, prefix + k)\n\t}\n\n\tfor k, v := range env.Types {\n\t\tnames = append(names, prefix + k)\n\t\tif v.Kind() == reflect.Struct {\n\t\t\tfor i := 0; i < v.NumField(); i += 1 {\n\t\t\t\tnames = append(names, v.Field(i).Name)\n\t\t\t}\n\t\t}\n\t\tif v.Kind() == reflect.Struct || v.Kind() == reflect.Interface {\n\t\t\tfor i := 0; i < v.NumMethod(); i += 1 {\n\t\t\t\tnames = append(names, v.Method(i).Name)\n\t\t\t}\n\t\t}\n\t}\n\tsort.Strings(names)\n\treturn names\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage network\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/onsi\/ginkgo\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/intstr\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/kubernetes\/test\/e2e\/framework\"\n\te2enode \"k8s.io\/kubernetes\/test\/e2e\/framework\/node\"\n\te2epod \"k8s.io\/kubernetes\/test\/e2e\/framework\/pod\"\n\te2eservice \"k8s.io\/kubernetes\/test\/e2e\/framework\/service\"\n\te2eskipper \"k8s.io\/kubernetes\/test\/e2e\/framework\/skipper\"\n)\n\nconst (\n\tserviceName = \"svc-udp\"\n\tpodClient   = \"pod-client\"\n\tpodBackend1 = \"pod-server-1\"\n\tpodBackend2 = \"pod-server-2\"\n\tsrcPort     = 12345\n)\n\n\/\/ Linux NAT uses conntrack to perform NAT, everytime a new\n\/\/ flow is seen, a connection is created in the conntrack table, and it\n\/\/ is being used by the NAT module.\n\/\/ Each entry in the conntrack table has associated a timeout, that removes\n\/\/ the connection once it expires.\n\/\/ UDP is a connectionless protocol, so the conntrack module tracking functions\n\/\/ are not very advanced.\n\/\/ It uses a short timeout (30 sec by default) that is renewed if there are new flows\n\/\/ matching the connection. Otherwise it expires the entry.\n\/\/ This behaviour can cause issues in Kubernetes when one entry on the conntrack table\n\/\/ is never expired because the sender does not stop sending traffic, but the pods or\n\/\/ endpoints were deleted, blackholing the traffic\n\/\/ In order to mitigate this problem, Kubernetes delete the stale entries:\n\/\/ - when an endpoint is removed\n\/\/ - when a service goes from no endpoints to new endpoint\n\n\/\/ Ref: https:\/\/api.semanticscholar.org\/CorpusID:198903401\n\/\/ Boye, Magnus. “Netfilter Connection Tracking and NAT Implementation.” (2012).\n\nvar _ = SIGDescribe(\"Conntrack\", func() {\n\n\tfr := framework.NewDefaultFramework(\"conntrack\")\n\n\ttype nodeInfo struct {\n\t\tname   string\n\t\tnodeIP string\n\t}\n\n\tvar (\n\t\tcs                             clientset.Interface\n\t\tns                             string\n\t\tclientNodeInfo, serverNodeInfo nodeInfo\n\t)\n\n\tlogContainsFn := func(text string) wait.ConditionFunc {\n\t\treturn func() (bool, error) {\n\t\t\tlogs, err := e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Retry the error next time.\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tif !strings.Contains(string(logs), text) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\tginkgo.BeforeEach(func() {\n\t\tcs = fr.ClientSet\n\t\tns = fr.Namespace.Name\n\n\t\tnodes, err := e2enode.GetBoundedReadySchedulableNodes(cs, 2)\n\t\tframework.ExpectNoError(err)\n\t\tif len(nodes.Items) < 2 {\n\t\t\te2eskipper.Skipf(\n\t\t\t\t\"Test requires >= 2 Ready nodes, but there are only %v nodes\",\n\t\t\t\tlen(nodes.Items))\n\t\t}\n\n\t\tips := e2enode.CollectAddresses(nodes, v1.NodeInternalIP)\n\n\t\tclientNodeInfo = nodeInfo{\n\t\t\tname:   nodes.Items[0].Name,\n\t\t\tnodeIP: ips[0],\n\t\t}\n\n\t\tserverNodeInfo = nodeInfo{\n\t\t\tname:   nodes.Items[1].Name,\n\t\t\tnodeIP: ips[1],\n\t\t}\n\t})\n\n\tginkgo.It(\"should be able to preserve UDP traffic when server pod cycles for a NodePort service\", func() {\n\t\t\/\/ TODO(#91236): Remove once the test is debugged and fixed.\n\t\t\/\/ dump conntrack table for debugging\n\t\tdefer dumpConntrack(cs)\n\n\t\t\/\/ Create a NodePort service\n\t\tudpJig := e2eservice.NewTestJig(cs, ns, serviceName)\n\t\tginkgo.By(\"creating a UDP service \" + serviceName + \" with type=NodePort in \" + ns)\n\t\tudpService, err := udpJig.CreateUDPService(func(svc *v1.Service) {\n\t\t\tsvc.Spec.Type = v1.ServiceTypeNodePort\n\t\t\tsvc.Spec.Ports = []v1.ServicePort{\n\t\t\t\t{Port: 80, Name: \"udp\", Protocol: v1.ProtocolUDP, TargetPort: intstr.FromInt(80)},\n\t\t\t}\n\t\t})\n\t\tframework.ExpectNoError(err)\n\n\t\t\/\/ Create a pod in one node to create the UDP traffic against the NodePort service every 5 seconds\n\t\tginkgo.By(\"creating a client pod for probing the service \" + serviceName)\n\t\tclientPod := newAgnhostPod(podClient, \"\")\n\t\tclientPod.Spec.NodeName = clientNodeInfo.name\n\t\tcmd := fmt.Sprintf(`date; for i in $(seq 1 3000); do echo \"$(date) Try: ${i}\"; echo hostname | nc -u -w 5 -p %d %s %d; echo; done`, srcPort, serverNodeInfo.nodeIP, udpService.Spec.Ports[0].NodePort)\n\t\tclientPod.Spec.Containers[0].Command = []string{\"\/bin\/sh\", \"-c\", cmd}\n\t\tclientPod.Spec.Containers[0].Name = podClient\n\t\tfr.PodClient().CreateSync(clientPod)\n\n\t\t\/\/ Read the client pod logs\n\t\tlogs, err := e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\tframework.ExpectNoError(err)\n\t\tframework.Logf(\"Pod client logs: %s\", logs)\n\n\t\t\/\/ Add a backend pod to the service in the other node\n\t\tginkgo.By(\"creating a backend pod \" + podBackend1 + \" for the service \" + serviceName)\n\t\tserverPod1 := newAgnhostPod(podBackend1, \"netexec\", fmt.Sprintf(\"--udp-port=%d\", 80))\n\t\tserverPod1.Labels = udpJig.Labels\n\t\tserverPod1.Spec.NodeName = serverNodeInfo.name\n\t\tfr.PodClient().CreateSync(serverPod1)\n\n\t\t\/\/ Waiting for service to expose endpoint.\n\t\terr = validateEndpointsPorts(cs, ns, serviceName, portsByPodName{podBackend1: {80}})\n\t\tframework.ExpectNoError(err, \"failed to validate endpoints for service %s in namespace: %s\", serviceName, ns)\n\n\t\t\/\/ Note that the fact that Endpoints object already exists, does NOT mean\n\t\t\/\/ that iptables (or whatever else is used) was already programmed.\n\t\t\/\/ Additionally take into account that UDP conntract entries timeout is\n\t\t\/\/ 30 seconds by default.\n\t\t\/\/ Based on the above check if the pod receives the traffic.\n\t\tginkgo.By(\"checking client pod connected to the backend 1 on Node IP \" + serverNodeInfo.nodeIP)\n\t\tif err := wait.PollImmediate(5*time.Second, time.Minute, logContainsFn(podBackend1)); err != nil {\n\t\t\tlogs, err = e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\t\tframework.ExpectNoError(err)\n\t\t\tframework.Logf(\"Pod client logs: %s\", logs)\n\t\t\tframework.Failf(\"Failed to connect to backend 1\")\n\t\t}\n\n\t\t\/\/ Create a second pod\n\t\tginkgo.By(\"creating a second backend pod \" + podBackend2 + \" for the service \" + serviceName)\n\t\tserverPod2 := newAgnhostPod(podBackend2, \"netexec\", fmt.Sprintf(\"--udp-port=%d\", 80))\n\t\tserverPod2.Labels = udpJig.Labels\n\t\tserverPod2.Spec.NodeName = serverNodeInfo.name\n\t\tfr.PodClient().CreateSync(serverPod2)\n\n\t\t\/\/ and delete the first pod\n\t\tframework.Logf(\"Cleaning up %s pod\", podBackend1)\n\t\tfr.PodClient().DeleteSync(podBackend1, metav1.DeleteOptions{}, framework.DefaultPodDeletionTimeout)\n\n\t\t\/\/ Waiting for service to expose endpoint.\n\t\terr = validateEndpointsPorts(cs, ns, serviceName, portsByPodName{podBackend2: {80}})\n\t\tframework.ExpectNoError(err, \"failed to validate endpoints for service %s in namespace: %s\", serviceName, ns)\n\n\t\t\/\/ Check that the second pod keeps receiving traffic\n\t\t\/\/ UDP conntrack entries timeout is 30 sec by default\n\t\tginkgo.By(\"checking client pod connected to the backend 2 on Node IP \" + serverNodeInfo.nodeIP)\n\t\tif err := wait.PollImmediate(5*time.Second, time.Minute, logContainsFn(podBackend2)); err != nil {\n\t\t\tlogs, err = e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\t\tframework.ExpectNoError(err)\n\t\t\tframework.Logf(\"Pod client logs: %s\", logs)\n\t\t\tframework.Failf(\"Failed to connect to backend 2\")\n\t\t}\n\t})\n\n\tginkgo.It(\"should be able to preserve UDP traffic when server pod cycles for a ClusterIP service\", func() {\n\t\t\/\/ TODO(#91236): Remove once the test is debugged and fixed.\n\t\t\/\/ dump conntrack table for debugging\n\t\tdefer dumpConntrack(cs)\n\n\t\t\/\/ Create a ClusterIP service\n\t\tudpJig := e2eservice.NewTestJig(cs, ns, serviceName)\n\t\tginkgo.By(\"creating a UDP service \" + serviceName + \" with type=ClusterIP in \" + ns)\n\t\tudpService, err := udpJig.CreateUDPService(func(svc *v1.Service) {\n\t\t\tsvc.Spec.Type = v1.ServiceTypeClusterIP\n\t\t\tsvc.Spec.Ports = []v1.ServicePort{\n\t\t\t\t{Port: 80, Name: \"udp\", Protocol: v1.ProtocolUDP, TargetPort: intstr.FromInt(80)},\n\t\t\t}\n\t\t})\n\t\tframework.ExpectNoError(err)\n\n\t\t\/\/ Create a pod in one node to create the UDP traffic against the ClusterIP service every 5 seconds\n\t\tginkgo.By(\"creating a client pod for probing the service \" + serviceName)\n\t\tclientPod := newAgnhostPod(podClient, \"\")\n\t\tclientPod.Spec.NodeName = clientNodeInfo.name\n\t\tcmd := fmt.Sprintf(`date; for i in $(seq 1 3000); do echo \"$(date) Try: ${i}\"; echo hostname | nc -u -w 5 -p %d %s %d; echo; done`, srcPort, udpService.Spec.ClusterIP, udpService.Spec.Ports[0].Port)\n\t\tclientPod.Spec.Containers[0].Command = []string{\"\/bin\/sh\", \"-c\", cmd}\n\t\tclientPod.Spec.Containers[0].Name = podClient\n\t\tfr.PodClient().CreateSync(clientPod)\n\n\t\t\/\/ Read the client pod logs\n\t\tlogs, err := e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\tframework.ExpectNoError(err)\n\t\tframework.Logf(\"Pod client logs: %s\", logs)\n\n\t\t\/\/ Add a backend pod to the service in the other node\n\t\tginkgo.By(\"creating a backend pod \" + podBackend1 + \" for the service \" + serviceName)\n\t\tserverPod1 := newAgnhostPod(podBackend1, \"netexec\", fmt.Sprintf(\"--udp-port=%d\", 80))\n\t\tserverPod1.Labels = udpJig.Labels\n\t\tserverPod1.Spec.NodeName = serverNodeInfo.name\n\t\tfr.PodClient().CreateSync(serverPod1)\n\n\t\t\/\/ Waiting for service to expose endpoint.\n\t\terr = validateEndpointsPorts(cs, ns, serviceName, portsByPodName{podBackend1: {80}})\n\t\tframework.ExpectNoError(err, \"failed to validate endpoints for service %s in namespace: %s\", serviceName, ns)\n\n\t\t\/\/ Note that the fact that Endpoints object already exists, does NOT mean\n\t\t\/\/ that iptables (or whatever else is used) was already programmed.\n\t\t\/\/ Additionally take into account that UDP conntract entries timeout is\n\t\t\/\/ 30 seconds by default.\n\t\t\/\/ Based on the above check if the pod receives the traffic.\n\t\tginkgo.By(\"checking client pod connected to the backend 1 on Node IP \" + serverNodeInfo.nodeIP)\n\t\tif err := wait.PollImmediate(5*time.Second, time.Minute, logContainsFn(podBackend1)); err != nil {\n\t\t\tlogs, err = e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\t\tframework.ExpectNoError(err)\n\t\t\tframework.Logf(\"Pod client logs: %s\", logs)\n\t\t\tframework.Failf(\"Failed to connect to backend 1\")\n\t\t}\n\n\t\t\/\/ Create a second pod\n\t\tginkgo.By(\"creating a second backend pod \" + podBackend2 + \" for the service \" + serviceName)\n\t\tserverPod2 := newAgnhostPod(podBackend2, \"netexec\", fmt.Sprintf(\"--udp-port=%d\", 80))\n\t\tserverPod2.Labels = udpJig.Labels\n\t\tserverPod2.Spec.NodeName = serverNodeInfo.name\n\t\tfr.PodClient().CreateSync(serverPod2)\n\n\t\t\/\/ and delete the first pod\n\t\tframework.Logf(\"Cleaning up %s pod\", podBackend1)\n\t\tfr.PodClient().DeleteSync(podBackend1, metav1.DeleteOptions{}, framework.DefaultPodDeletionTimeout)\n\n\t\t\/\/ Waiting for service to expose endpoint.\n\t\terr = validateEndpointsPorts(cs, ns, serviceName, portsByPodName{podBackend2: {80}})\n\t\tframework.ExpectNoError(err, \"failed to validate endpoints for service %s in namespace: %s\", serviceName, ns)\n\n\t\t\/\/ Check that the second pod keeps receiving traffic\n\t\t\/\/ UDP conntrack entries timeout is 30 sec by default\n\t\tginkgo.By(\"checking client pod connected to the backend 2 on Node IP \" + serverNodeInfo.nodeIP)\n\t\tif err := wait.PollImmediate(5*time.Second, time.Minute, logContainsFn(podBackend2)); err != nil {\n\t\t\tlogs, err = e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\t\tframework.ExpectNoError(err)\n\t\t\tframework.Logf(\"Pod client logs: %s\", logs)\n\t\t\tframework.Failf(\"Failed to connect to backend 2\")\n\t\t}\n\t})\n})\n\nfunc dumpConntrack(cs clientset.Interface) {\n\t\/\/ Dump conntrack table of each node for troubleshooting using the kube-proxy pods\n\tnamespace := \"kube-system\"\n\tpods, err := cs.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{})\n\tif err != nil || len(pods.Items) == 0 {\n\t\tframework.Logf(\"failed to list kube-proxy pods in namespace: %s\", namespace)\n\t\treturn\n\t}\n\tcmd := \"conntrack -L\"\n\tfor _, pod := range pods.Items {\n\t\tif strings.Contains(pod.Name, \"kube-proxy\") {\n\t\t\tstdout, err := framework.RunHostCmd(namespace, pod.Name, cmd)\n\t\t\tif err != nil {\n\t\t\t\tframework.Logf(\"Failed to dump conntrack table of node %s: %v\", pod.Spec.NodeName, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tframework.Logf(\"conntrack table of node %s: %s\", pod.Spec.NodeName, stdout)\n\t\t}\n\t}\n}\n<commit_msg>Replace non-ascii string under test\/<commit_after>\/*\nCopyright 2020 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage network\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/onsi\/ginkgo\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/intstr\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n\tclientset \"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/kubernetes\/test\/e2e\/framework\"\n\te2enode \"k8s.io\/kubernetes\/test\/e2e\/framework\/node\"\n\te2epod \"k8s.io\/kubernetes\/test\/e2e\/framework\/pod\"\n\te2eservice \"k8s.io\/kubernetes\/test\/e2e\/framework\/service\"\n\te2eskipper \"k8s.io\/kubernetes\/test\/e2e\/framework\/skipper\"\n)\n\nconst (\n\tserviceName = \"svc-udp\"\n\tpodClient   = \"pod-client\"\n\tpodBackend1 = \"pod-server-1\"\n\tpodBackend2 = \"pod-server-2\"\n\tsrcPort     = 12345\n)\n\n\/\/ Linux NAT uses conntrack to perform NAT, everytime a new\n\/\/ flow is seen, a connection is created in the conntrack table, and it\n\/\/ is being used by the NAT module.\n\/\/ Each entry in the conntrack table has associated a timeout, that removes\n\/\/ the connection once it expires.\n\/\/ UDP is a connectionless protocol, so the conntrack module tracking functions\n\/\/ are not very advanced.\n\/\/ It uses a short timeout (30 sec by default) that is renewed if there are new flows\n\/\/ matching the connection. Otherwise it expires the entry.\n\/\/ This behaviour can cause issues in Kubernetes when one entry on the conntrack table\n\/\/ is never expired because the sender does not stop sending traffic, but the pods or\n\/\/ endpoints were deleted, blackholing the traffic\n\/\/ In order to mitigate this problem, Kubernetes delete the stale entries:\n\/\/ - when an endpoint is removed\n\/\/ - when a service goes from no endpoints to new endpoint\n\n\/\/ Ref: https:\/\/api.semanticscholar.org\/CorpusID:198903401\n\/\/ Boye, Magnus. \"Netfilter Connection Tracking and NAT Implementation.\" (2012).\n\nvar _ = SIGDescribe(\"Conntrack\", func() {\n\n\tfr := framework.NewDefaultFramework(\"conntrack\")\n\n\ttype nodeInfo struct {\n\t\tname   string\n\t\tnodeIP string\n\t}\n\n\tvar (\n\t\tcs                             clientset.Interface\n\t\tns                             string\n\t\tclientNodeInfo, serverNodeInfo nodeInfo\n\t)\n\n\tlogContainsFn := func(text string) wait.ConditionFunc {\n\t\treturn func() (bool, error) {\n\t\t\tlogs, err := e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Retry the error next time.\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tif !strings.Contains(string(logs), text) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\tginkgo.BeforeEach(func() {\n\t\tcs = fr.ClientSet\n\t\tns = fr.Namespace.Name\n\n\t\tnodes, err := e2enode.GetBoundedReadySchedulableNodes(cs, 2)\n\t\tframework.ExpectNoError(err)\n\t\tif len(nodes.Items) < 2 {\n\t\t\te2eskipper.Skipf(\n\t\t\t\t\"Test requires >= 2 Ready nodes, but there are only %v nodes\",\n\t\t\t\tlen(nodes.Items))\n\t\t}\n\n\t\tips := e2enode.CollectAddresses(nodes, v1.NodeInternalIP)\n\n\t\tclientNodeInfo = nodeInfo{\n\t\t\tname:   nodes.Items[0].Name,\n\t\t\tnodeIP: ips[0],\n\t\t}\n\n\t\tserverNodeInfo = nodeInfo{\n\t\t\tname:   nodes.Items[1].Name,\n\t\t\tnodeIP: ips[1],\n\t\t}\n\t})\n\n\tginkgo.It(\"should be able to preserve UDP traffic when server pod cycles for a NodePort service\", func() {\n\t\t\/\/ TODO(#91236): Remove once the test is debugged and fixed.\n\t\t\/\/ dump conntrack table for debugging\n\t\tdefer dumpConntrack(cs)\n\n\t\t\/\/ Create a NodePort service\n\t\tudpJig := e2eservice.NewTestJig(cs, ns, serviceName)\n\t\tginkgo.By(\"creating a UDP service \" + serviceName + \" with type=NodePort in \" + ns)\n\t\tudpService, err := udpJig.CreateUDPService(func(svc *v1.Service) {\n\t\t\tsvc.Spec.Type = v1.ServiceTypeNodePort\n\t\t\tsvc.Spec.Ports = []v1.ServicePort{\n\t\t\t\t{Port: 80, Name: \"udp\", Protocol: v1.ProtocolUDP, TargetPort: intstr.FromInt(80)},\n\t\t\t}\n\t\t})\n\t\tframework.ExpectNoError(err)\n\n\t\t\/\/ Create a pod in one node to create the UDP traffic against the NodePort service every 5 seconds\n\t\tginkgo.By(\"creating a client pod for probing the service \" + serviceName)\n\t\tclientPod := newAgnhostPod(podClient, \"\")\n\t\tclientPod.Spec.NodeName = clientNodeInfo.name\n\t\tcmd := fmt.Sprintf(`date; for i in $(seq 1 3000); do echo \"$(date) Try: ${i}\"; echo hostname | nc -u -w 5 -p %d %s %d; echo; done`, srcPort, serverNodeInfo.nodeIP, udpService.Spec.Ports[0].NodePort)\n\t\tclientPod.Spec.Containers[0].Command = []string{\"\/bin\/sh\", \"-c\", cmd}\n\t\tclientPod.Spec.Containers[0].Name = podClient\n\t\tfr.PodClient().CreateSync(clientPod)\n\n\t\t\/\/ Read the client pod logs\n\t\tlogs, err := e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\tframework.ExpectNoError(err)\n\t\tframework.Logf(\"Pod client logs: %s\", logs)\n\n\t\t\/\/ Add a backend pod to the service in the other node\n\t\tginkgo.By(\"creating a backend pod \" + podBackend1 + \" for the service \" + serviceName)\n\t\tserverPod1 := newAgnhostPod(podBackend1, \"netexec\", fmt.Sprintf(\"--udp-port=%d\", 80))\n\t\tserverPod1.Labels = udpJig.Labels\n\t\tserverPod1.Spec.NodeName = serverNodeInfo.name\n\t\tfr.PodClient().CreateSync(serverPod1)\n\n\t\t\/\/ Waiting for service to expose endpoint.\n\t\terr = validateEndpointsPorts(cs, ns, serviceName, portsByPodName{podBackend1: {80}})\n\t\tframework.ExpectNoError(err, \"failed to validate endpoints for service %s in namespace: %s\", serviceName, ns)\n\n\t\t\/\/ Note that the fact that Endpoints object already exists, does NOT mean\n\t\t\/\/ that iptables (or whatever else is used) was already programmed.\n\t\t\/\/ Additionally take into account that UDP conntract entries timeout is\n\t\t\/\/ 30 seconds by default.\n\t\t\/\/ Based on the above check if the pod receives the traffic.\n\t\tginkgo.By(\"checking client pod connected to the backend 1 on Node IP \" + serverNodeInfo.nodeIP)\n\t\tif err := wait.PollImmediate(5*time.Second, time.Minute, logContainsFn(podBackend1)); err != nil {\n\t\t\tlogs, err = e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\t\tframework.ExpectNoError(err)\n\t\t\tframework.Logf(\"Pod client logs: %s\", logs)\n\t\t\tframework.Failf(\"Failed to connect to backend 1\")\n\t\t}\n\n\t\t\/\/ Create a second pod\n\t\tginkgo.By(\"creating a second backend pod \" + podBackend2 + \" for the service \" + serviceName)\n\t\tserverPod2 := newAgnhostPod(podBackend2, \"netexec\", fmt.Sprintf(\"--udp-port=%d\", 80))\n\t\tserverPod2.Labels = udpJig.Labels\n\t\tserverPod2.Spec.NodeName = serverNodeInfo.name\n\t\tfr.PodClient().CreateSync(serverPod2)\n\n\t\t\/\/ and delete the first pod\n\t\tframework.Logf(\"Cleaning up %s pod\", podBackend1)\n\t\tfr.PodClient().DeleteSync(podBackend1, metav1.DeleteOptions{}, framework.DefaultPodDeletionTimeout)\n\n\t\t\/\/ Waiting for service to expose endpoint.\n\t\terr = validateEndpointsPorts(cs, ns, serviceName, portsByPodName{podBackend2: {80}})\n\t\tframework.ExpectNoError(err, \"failed to validate endpoints for service %s in namespace: %s\", serviceName, ns)\n\n\t\t\/\/ Check that the second pod keeps receiving traffic\n\t\t\/\/ UDP conntrack entries timeout is 30 sec by default\n\t\tginkgo.By(\"checking client pod connected to the backend 2 on Node IP \" + serverNodeInfo.nodeIP)\n\t\tif err := wait.PollImmediate(5*time.Second, time.Minute, logContainsFn(podBackend2)); err != nil {\n\t\t\tlogs, err = e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\t\tframework.ExpectNoError(err)\n\t\t\tframework.Logf(\"Pod client logs: %s\", logs)\n\t\t\tframework.Failf(\"Failed to connect to backend 2\")\n\t\t}\n\t})\n\n\tginkgo.It(\"should be able to preserve UDP traffic when server pod cycles for a ClusterIP service\", func() {\n\t\t\/\/ TODO(#91236): Remove once the test is debugged and fixed.\n\t\t\/\/ dump conntrack table for debugging\n\t\tdefer dumpConntrack(cs)\n\n\t\t\/\/ Create a ClusterIP service\n\t\tudpJig := e2eservice.NewTestJig(cs, ns, serviceName)\n\t\tginkgo.By(\"creating a UDP service \" + serviceName + \" with type=ClusterIP in \" + ns)\n\t\tudpService, err := udpJig.CreateUDPService(func(svc *v1.Service) {\n\t\t\tsvc.Spec.Type = v1.ServiceTypeClusterIP\n\t\t\tsvc.Spec.Ports = []v1.ServicePort{\n\t\t\t\t{Port: 80, Name: \"udp\", Protocol: v1.ProtocolUDP, TargetPort: intstr.FromInt(80)},\n\t\t\t}\n\t\t})\n\t\tframework.ExpectNoError(err)\n\n\t\t\/\/ Create a pod in one node to create the UDP traffic against the ClusterIP service every 5 seconds\n\t\tginkgo.By(\"creating a client pod for probing the service \" + serviceName)\n\t\tclientPod := newAgnhostPod(podClient, \"\")\n\t\tclientPod.Spec.NodeName = clientNodeInfo.name\n\t\tcmd := fmt.Sprintf(`date; for i in $(seq 1 3000); do echo \"$(date) Try: ${i}\"; echo hostname | nc -u -w 5 -p %d %s %d; echo; done`, srcPort, udpService.Spec.ClusterIP, udpService.Spec.Ports[0].Port)\n\t\tclientPod.Spec.Containers[0].Command = []string{\"\/bin\/sh\", \"-c\", cmd}\n\t\tclientPod.Spec.Containers[0].Name = podClient\n\t\tfr.PodClient().CreateSync(clientPod)\n\n\t\t\/\/ Read the client pod logs\n\t\tlogs, err := e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\tframework.ExpectNoError(err)\n\t\tframework.Logf(\"Pod client logs: %s\", logs)\n\n\t\t\/\/ Add a backend pod to the service in the other node\n\t\tginkgo.By(\"creating a backend pod \" + podBackend1 + \" for the service \" + serviceName)\n\t\tserverPod1 := newAgnhostPod(podBackend1, \"netexec\", fmt.Sprintf(\"--udp-port=%d\", 80))\n\t\tserverPod1.Labels = udpJig.Labels\n\t\tserverPod1.Spec.NodeName = serverNodeInfo.name\n\t\tfr.PodClient().CreateSync(serverPod1)\n\n\t\t\/\/ Waiting for service to expose endpoint.\n\t\terr = validateEndpointsPorts(cs, ns, serviceName, portsByPodName{podBackend1: {80}})\n\t\tframework.ExpectNoError(err, \"failed to validate endpoints for service %s in namespace: %s\", serviceName, ns)\n\n\t\t\/\/ Note that the fact that Endpoints object already exists, does NOT mean\n\t\t\/\/ that iptables (or whatever else is used) was already programmed.\n\t\t\/\/ Additionally take into account that UDP conntract entries timeout is\n\t\t\/\/ 30 seconds by default.\n\t\t\/\/ Based on the above check if the pod receives the traffic.\n\t\tginkgo.By(\"checking client pod connected to the backend 1 on Node IP \" + serverNodeInfo.nodeIP)\n\t\tif err := wait.PollImmediate(5*time.Second, time.Minute, logContainsFn(podBackend1)); err != nil {\n\t\t\tlogs, err = e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\t\tframework.ExpectNoError(err)\n\t\t\tframework.Logf(\"Pod client logs: %s\", logs)\n\t\t\tframework.Failf(\"Failed to connect to backend 1\")\n\t\t}\n\n\t\t\/\/ Create a second pod\n\t\tginkgo.By(\"creating a second backend pod \" + podBackend2 + \" for the service \" + serviceName)\n\t\tserverPod2 := newAgnhostPod(podBackend2, \"netexec\", fmt.Sprintf(\"--udp-port=%d\", 80))\n\t\tserverPod2.Labels = udpJig.Labels\n\t\tserverPod2.Spec.NodeName = serverNodeInfo.name\n\t\tfr.PodClient().CreateSync(serverPod2)\n\n\t\t\/\/ and delete the first pod\n\t\tframework.Logf(\"Cleaning up %s pod\", podBackend1)\n\t\tfr.PodClient().DeleteSync(podBackend1, metav1.DeleteOptions{}, framework.DefaultPodDeletionTimeout)\n\n\t\t\/\/ Waiting for service to expose endpoint.\n\t\terr = validateEndpointsPorts(cs, ns, serviceName, portsByPodName{podBackend2: {80}})\n\t\tframework.ExpectNoError(err, \"failed to validate endpoints for service %s in namespace: %s\", serviceName, ns)\n\n\t\t\/\/ Check that the second pod keeps receiving traffic\n\t\t\/\/ UDP conntrack entries timeout is 30 sec by default\n\t\tginkgo.By(\"checking client pod connected to the backend 2 on Node IP \" + serverNodeInfo.nodeIP)\n\t\tif err := wait.PollImmediate(5*time.Second, time.Minute, logContainsFn(podBackend2)); err != nil {\n\t\t\tlogs, err = e2epod.GetPodLogs(cs, ns, podClient, podClient)\n\t\t\tframework.ExpectNoError(err)\n\t\t\tframework.Logf(\"Pod client logs: %s\", logs)\n\t\t\tframework.Failf(\"Failed to connect to backend 2\")\n\t\t}\n\t})\n})\n\nfunc dumpConntrack(cs clientset.Interface) {\n\t\/\/ Dump conntrack table of each node for troubleshooting using the kube-proxy pods\n\tnamespace := \"kube-system\"\n\tpods, err := cs.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{})\n\tif err != nil || len(pods.Items) == 0 {\n\t\tframework.Logf(\"failed to list kube-proxy pods in namespace: %s\", namespace)\n\t\treturn\n\t}\n\tcmd := \"conntrack -L\"\n\tfor _, pod := range pods.Items {\n\t\tif strings.Contains(pod.Name, \"kube-proxy\") {\n\t\t\tstdout, err := framework.RunHostCmd(namespace, pod.Name, cmd)\n\t\t\tif err != nil {\n\t\t\t\tframework.Logf(\"Failed to dump conntrack table of node %s: %v\", pod.Spec.NodeName, err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tframework.Logf(\"conntrack table of node %s: %s\", pod.Spec.NodeName, stdout)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018-2020 Authors of Cilium\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage k8sTest\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/cilium\/cilium\/test\/config\"\n\t. \"github.com\/cilium\/cilium\/test\/ginkgo-ext\"\n\t\"github.com\/cilium\/cilium\/test\/helpers\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar longTimeout = 10 * time.Minute\n\n\/\/ ExpectKubeDNSReady is a wrapper around helpers\/WaitKubeDNS. It asserts that\n\/\/ the error returned by that function is nil.\nfunc ExpectKubeDNSReady(vm *helpers.Kubectl) {\n\tBy(\"Waiting for kube-dns to be ready\")\n\terr := vm.WaitKubeDNS()\n\tExpectWithOffset(1, err).Should(BeNil(), \"kube-dns was not able to get into ready state\")\n\n\tBy(\"Running kube-dns preflight check\")\n\terr = vm.KubeDNSPreFlightCheck()\n\tExpectWithOffset(1, err).Should(BeNil(), \"kube-dns service not ready\")\n}\n\n\/\/ ExpectCiliumReady is a wrapper around helpers\/WaitForPods. It asserts that\n\/\/ the error returned by that function is nil.\nfunc ExpectCiliumReady(vm *helpers.Kubectl) {\n\terr := vm.WaitForCiliumReadiness()\n\tExpect(err).To(BeNil(), \"Timeout while waiting for Cilium to become ready\")\n\n\terr = vm.CiliumPreFlightCheck()\n\tExpectWithOffset(1, err).Should(BeNil(), \"cilium pre-flight checks failed\")\n}\n\n\/\/ ExpectCiliumOperatorReady is a wrapper around helpers\/WaitForPods. It asserts that\n\/\/ the error returned by that function is nil.\nfunc ExpectCiliumOperatorReady(vm *helpers.Kubectl) {\n\tBy(\"Waiting for cilium-operator to be ready\")\n\terr := vm.WaitforPods(helpers.CiliumNamespace, \"-l name=cilium-operator\", longTimeout)\n\tExpectWithOffset(1, err).Should(BeNil(), \"Cilium operator was not able to get into ready state\")\n}\n\n\/\/ ExpectAllPodsTerminated is a wrapper around helpers\/WaitCleanAllTerminatingPods.\n\/\/ It asserts that the error returned by that function is nil.\nfunc ExpectAllPodsTerminated(vm *helpers.Kubectl) {\n\terr := vm.WaitCleanAllTerminatingPods(helpers.HelperTimeout)\n\tExpectWithOffset(1, err).To(BeNil(), \"terminating containers are not deleted after timeout\")\n}\n\n\/\/ ExpectCiliumPreFlightInstallReady is a wrapper around helpers\/WaitForNPods.\n\/\/ It asserts the error returned by that function is nil.\nfunc ExpectCiliumPreFlightInstallReady(vm *helpers.Kubectl) {\n\tBy(\"Waiting for all cilium pre-flight pods to be ready\")\n\n\terr := vm.WaitforPods(helpers.CiliumNamespace, \"-l k8s-app=cilium-pre-flight-check\", longTimeout)\n\twarningMessage := \"\"\n\tif err != nil {\n\t\tres := vm.Exec(fmt.Sprintf(\n\t\t\t\"%s -n %s get pods -l k8s-app=cilium-pre-flight-check\",\n\t\t\thelpers.KubectlCmd, helpers.CiliumNamespace))\n\t\twarningMessage = res.Output().String()\n\t}\n\tExpect(err).To(BeNil(), \"cilium pre-flight check is not ready after timeout, pods status:\\n %s\", warningMessage)\n}\n\n\/\/ DeployCiliumAndDNS deploys DNS and cilium into the kubernetes cluster\nfunc DeployCiliumAndDNS(vm *helpers.Kubectl, ciliumFilename string) {\n\tDeployCiliumOptionsAndDNS(vm, ciliumFilename, map[string]string{\"global.debug.verbose\": \"flow\"})\n}\n\nfunc redeployCilium(vm *helpers.Kubectl, ciliumFilename string, options map[string]string) {\n\tBy(\"Installing Cilium\")\n\terr := vm.CiliumInstall(ciliumFilename, options)\n\tExpect(err).To(BeNil(), \"Cilium cannot be installed\")\n\n\terr = vm.WaitForCiliumReadiness()\n\tExpect(err).To(BeNil(), \"Timeout while waiting for Cilium to become ready\")\n}\n\n\/\/ RedeployCilium reinstantiates the Cilium DS and ensures it is running.\n\/\/\n\/\/ This helper is only appropriate for reconfiguring Cilium in the middle of\n\/\/ an existing testsuite that calls DeployCiliumAndDNS(...).\nfunc RedeployCilium(vm *helpers.Kubectl, ciliumFilename string, options map[string]string) {\n\tredeployCilium(vm, ciliumFilename, options)\n\terr := vm.CiliumPreFlightCheck()\n\tExpectWithOffset(1, err).Should(BeNil(), \"cilium pre-flight checks failed\")\n\tExpectCiliumOperatorReady(vm)\n}\n\n\/\/ DeployCiliumOptionsAndDNS deploys DNS and cilium with options into the kubernetes cluster\nfunc DeployCiliumOptionsAndDNS(vm *helpers.Kubectl, ciliumFilename string, options map[string]string) {\n\tredeployCilium(vm, ciliumFilename, options)\n\n\tBy(\"Installing DNS Deployment\")\n\tswitch helpers.GetCurrentIntegration() {\n\tcase helpers.CIIntegrationMicrok8s:\n\t\tBy(fmt.Sprintf(\"%s (hint: %s)\",\n\t\t\t\"Assuming that microk8s already has DNS deployed...\",\n\t\t\t\"Use 'microk8s.enable dns' to create deployment\"))\n\tcase helpers.CIIntegrationGKE:\n\t\tBy(\"Restarting all kube-system pods\")\n\t\tif res := vm.DeleteResource(\"pod\", fmt.Sprintf(\"-n %s --all\", helpers.KubeSystemNamespace)); !res.WasSuccessful() {\n\t\t\tlog.Warningf(\"Unable to delete kube-system pods: %s\", res.OutputPrettyPrint())\n\t\t}\n\tdefault:\n\t\tvm.ApplyDefault(helpers.DNSDeployment(vm.BasePath()))\n\t\tBy(\"Restarting DNS Pods\")\n\t\tif res := vm.DeleteResource(\"pod\", fmt.Sprintf(\"-n %s -l k8s-app=kube-dns\", helpers.KubeSystemNamespace)); !res.WasSuccessful() {\n\t\t\tlog.Warningf(\"Unable to delete DNS pods: %s\", res.OutputPrettyPrint())\n\t\t}\n\t}\n\n\tswitch helpers.GetCurrentIntegration() {\n\tcase helpers.CIIntegrationFlannel:\n\t\tBy(\"Installing Flannel\")\n\t\tvm.ApplyDefault(vm.GetFilePath(\"..\/examples\/kubernetes\/addons\/flannel\/flannel.yaml\"))\n\tdefault:\n\t}\n\n\terr := vm.CiliumPreFlightCheck()\n\tExpectWithOffset(1, err).Should(BeNil(), \"cilium pre-flight checks failed\")\n\tExpectCiliumOperatorReady(vm)\n\tExpectKubeDNSReady(vm)\n\n\tswitch helpers.GetCurrentIntegration() {\n\tcase helpers.CIIntegrationGKE:\n\t\terr := vm.WaitforPods(helpers.KubeSystemNamespace, \"\", longTimeout)\n\t\tExpectWithOffset(1, err).Should(BeNil(), \"kube-system pods were not able to get into ready state after restart\")\n\t}\n}\n\n\/\/ SkipIfBenchmark will skip the test if benchmark is not specified\nfunc SkipIfBenchmark() {\n\tif !config.CiliumTestConfig.Benchmarks {\n\t\tSkip(\"Benchmarks are skipped, specify -cilium.Benchmarks\")\n\t}\n}\n\n\/\/ SkipIfIntegration will skip a test if it's running with any of the specified\n\/\/ integration.\nfunc SkipIfIntegration(integration string) {\n\tif helpers.IsIntegration(integration) {\n\t\tSkip(fmt.Sprintf(\n\t\t\t\"This feature is not supported in Cilium %q mode. Skipping test.\",\n\t\t\tintegration))\n\t}\n}\n\n\/\/ SkipItIfNoKubeProxy will skip It if kube-proxy is disabled (= NodePort BPF is\n\/\/ enabled)\nfunc SkipItIfNoKubeProxy() {\n\tif !helpers.RunsWithKubeProxy() {\n\t\tSkip(\"kube-proxy is disabled (NodePort BPF is enabled). Skipping test.\")\n\t}\n}\n<commit_msg>test\/k8sT: add assertion helpers for hubble-cli and hubble-relay<commit_after>\/\/ Copyright 2018-2020 Authors of Cilium\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage k8sTest\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/cilium\/cilium\/test\/config\"\n\t. \"github.com\/cilium\/cilium\/test\/ginkgo-ext\"\n\t\"github.com\/cilium\/cilium\/test\/helpers\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar longTimeout = 10 * time.Minute\n\n\/\/ ExpectKubeDNSReady is a wrapper around helpers\/WaitKubeDNS. It asserts that\n\/\/ the error returned by that function is nil.\nfunc ExpectKubeDNSReady(vm *helpers.Kubectl) {\n\tBy(\"Waiting for kube-dns to be ready\")\n\terr := vm.WaitKubeDNS()\n\tExpectWithOffset(1, err).Should(BeNil(), \"kube-dns was not able to get into ready state\")\n\n\tBy(\"Running kube-dns preflight check\")\n\terr = vm.KubeDNSPreFlightCheck()\n\tExpectWithOffset(1, err).Should(BeNil(), \"kube-dns service not ready\")\n}\n\n\/\/ ExpectCiliumReady is a wrapper around helpers\/WaitForPods. It asserts that\n\/\/ the error returned by that function is nil.\nfunc ExpectCiliumReady(vm *helpers.Kubectl) {\n\terr := vm.WaitForCiliumReadiness()\n\tExpect(err).To(BeNil(), \"Timeout while waiting for Cilium to become ready\")\n\n\terr = vm.CiliumPreFlightCheck()\n\tExpectWithOffset(1, err).Should(BeNil(), \"cilium pre-flight checks failed\")\n}\n\n\/\/ ExpectCiliumOperatorReady is a wrapper around helpers\/WaitForPods. It asserts that\n\/\/ the error returned by that function is nil.\nfunc ExpectCiliumOperatorReady(vm *helpers.Kubectl) {\n\tBy(\"Waiting for cilium-operator to be ready\")\n\terr := vm.WaitforPods(helpers.CiliumNamespace, \"-l name=cilium-operator\", longTimeout)\n\tExpectWithOffset(1, err).Should(BeNil(), \"Cilium operator was not able to get into ready state\")\n}\n\n\/\/ ExpectHubbleCLIReady is a wrapper around helpers\/WaitForPods. It asserts\n\/\/ that the error returned by that function is nil.\nfunc ExpectHubbleCLIReady(vm *helpers.Kubectl, ns string) {\n\tBy(\"Waiting for hubble-cli to be ready\")\n\terr := vm.WaitforPods(ns, \"-l k8s-app=hubble-cli\", longTimeout)\n\tExpectWithOffset(1, err).Should(BeNil(), \"hubble-cli was not able to get into ready state\")\n}\n\n\/\/ ExpectHubbleRelayReady is a wrapper around helpers\/WaitForPods. It asserts\n\/\/ that the error returned by that function is nil.\nfunc ExpectHubbleRelayReady(vm *helpers.Kubectl, ns string) {\n\tBy(\"Waiting for hubble-relay to be ready\")\n\terr := vm.WaitforPods(ns, \"-l k8s-app=hubble-relay\", longTimeout)\n\tExpectWithOffset(1, err).Should(BeNil(), \"hubble-relay was not able to get into ready state\")\n}\n\n\/\/ ExpectAllPodsTerminated is a wrapper around helpers\/WaitCleanAllTerminatingPods.\n\/\/ It asserts that the error returned by that function is nil.\nfunc ExpectAllPodsTerminated(vm *helpers.Kubectl) {\n\terr := vm.WaitCleanAllTerminatingPods(helpers.HelperTimeout)\n\tExpectWithOffset(1, err).To(BeNil(), \"terminating containers are not deleted after timeout\")\n}\n\n\/\/ ExpectCiliumPreFlightInstallReady is a wrapper around helpers\/WaitForNPods.\n\/\/ It asserts the error returned by that function is nil.\nfunc ExpectCiliumPreFlightInstallReady(vm *helpers.Kubectl) {\n\tBy(\"Waiting for all cilium pre-flight pods to be ready\")\n\n\terr := vm.WaitforPods(helpers.CiliumNamespace, \"-l k8s-app=cilium-pre-flight-check\", longTimeout)\n\twarningMessage := \"\"\n\tif err != nil {\n\t\tres := vm.Exec(fmt.Sprintf(\n\t\t\t\"%s -n %s get pods -l k8s-app=cilium-pre-flight-check\",\n\t\t\thelpers.KubectlCmd, helpers.CiliumNamespace))\n\t\twarningMessage = res.Output().String()\n\t}\n\tExpect(err).To(BeNil(), \"cilium pre-flight check is not ready after timeout, pods status:\\n %s\", warningMessage)\n}\n\n\/\/ DeployCiliumAndDNS deploys DNS and cilium into the kubernetes cluster\nfunc DeployCiliumAndDNS(vm *helpers.Kubectl, ciliumFilename string) {\n\tDeployCiliumOptionsAndDNS(vm, ciliumFilename, map[string]string{\"global.debug.verbose\": \"flow\"})\n}\n\nfunc redeployCilium(vm *helpers.Kubectl, ciliumFilename string, options map[string]string) {\n\tBy(\"Installing Cilium\")\n\terr := vm.CiliumInstall(ciliumFilename, options)\n\tExpect(err).To(BeNil(), \"Cilium cannot be installed\")\n\n\terr = vm.WaitForCiliumReadiness()\n\tExpect(err).To(BeNil(), \"Timeout while waiting for Cilium to become ready\")\n}\n\n\/\/ RedeployCilium reinstantiates the Cilium DS and ensures it is running.\n\/\/\n\/\/ This helper is only appropriate for reconfiguring Cilium in the middle of\n\/\/ an existing testsuite that calls DeployCiliumAndDNS(...).\nfunc RedeployCilium(vm *helpers.Kubectl, ciliumFilename string, options map[string]string) {\n\tredeployCilium(vm, ciliumFilename, options)\n\terr := vm.CiliumPreFlightCheck()\n\tExpectWithOffset(1, err).Should(BeNil(), \"cilium pre-flight checks failed\")\n\tExpectCiliumOperatorReady(vm)\n}\n\n\/\/ DeployCiliumOptionsAndDNS deploys DNS and cilium with options into the kubernetes cluster\nfunc DeployCiliumOptionsAndDNS(vm *helpers.Kubectl, ciliumFilename string, options map[string]string) {\n\tredeployCilium(vm, ciliumFilename, options)\n\n\tBy(\"Installing DNS Deployment\")\n\tswitch helpers.GetCurrentIntegration() {\n\tcase helpers.CIIntegrationMicrok8s:\n\t\tBy(fmt.Sprintf(\"%s (hint: %s)\",\n\t\t\t\"Assuming that microk8s already has DNS deployed...\",\n\t\t\t\"Use 'microk8s.enable dns' to create deployment\"))\n\tcase helpers.CIIntegrationGKE:\n\t\tBy(\"Restarting all kube-system pods\")\n\t\tif res := vm.DeleteResource(\"pod\", fmt.Sprintf(\"-n %s --all\", helpers.KubeSystemNamespace)); !res.WasSuccessful() {\n\t\t\tlog.Warningf(\"Unable to delete kube-system pods: %s\", res.OutputPrettyPrint())\n\t\t}\n\tdefault:\n\t\tvm.ApplyDefault(helpers.DNSDeployment(vm.BasePath()))\n\t\tBy(\"Restarting DNS Pods\")\n\t\tif res := vm.DeleteResource(\"pod\", fmt.Sprintf(\"-n %s -l k8s-app=kube-dns\", helpers.KubeSystemNamespace)); !res.WasSuccessful() {\n\t\t\tlog.Warningf(\"Unable to delete DNS pods: %s\", res.OutputPrettyPrint())\n\t\t}\n\t}\n\n\tswitch helpers.GetCurrentIntegration() {\n\tcase helpers.CIIntegrationFlannel:\n\t\tBy(\"Installing Flannel\")\n\t\tvm.ApplyDefault(vm.GetFilePath(\"..\/examples\/kubernetes\/addons\/flannel\/flannel.yaml\"))\n\tdefault:\n\t}\n\n\terr := vm.CiliumPreFlightCheck()\n\tExpectWithOffset(1, err).Should(BeNil(), \"cilium pre-flight checks failed\")\n\tExpectCiliumOperatorReady(vm)\n\tExpectKubeDNSReady(vm)\n\n\tswitch helpers.GetCurrentIntegration() {\n\tcase helpers.CIIntegrationGKE:\n\t\terr := vm.WaitforPods(helpers.KubeSystemNamespace, \"\", longTimeout)\n\t\tExpectWithOffset(1, err).Should(BeNil(), \"kube-system pods were not able to get into ready state after restart\")\n\t}\n}\n\n\/\/ SkipIfBenchmark will skip the test if benchmark is not specified\nfunc SkipIfBenchmark() {\n\tif !config.CiliumTestConfig.Benchmarks {\n\t\tSkip(\"Benchmarks are skipped, specify -cilium.Benchmarks\")\n\t}\n}\n\n\/\/ SkipIfIntegration will skip a test if it's running with any of the specified\n\/\/ integration.\nfunc SkipIfIntegration(integration string) {\n\tif helpers.IsIntegration(integration) {\n\t\tSkip(fmt.Sprintf(\n\t\t\t\"This feature is not supported in Cilium %q mode. Skipping test.\",\n\t\t\tintegration))\n\t}\n}\n\n\/\/ SkipItIfNoKubeProxy will skip It if kube-proxy is disabled (= NodePort BPF is\n\/\/ enabled)\nfunc SkipItIfNoKubeProxy() {\n\tif !helpers.RunsWithKubeProxy() {\n\t\tSkip(\"kube-proxy is disabled (NodePort BPF is enabled). Skipping test.\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This file is subject to a 1-clause BSD license.\n\/\/ Its contents can be found in the enclosed LICENSE file.\n\npackage irc\n\n\/\/ Channel represents a single channel.\ntype Channel struct {\n\tName             string \/\/ Channel name.\n\tKey              string \/\/ Channel key. Might be needed to join when channel is protected.\n\tChanservPassword string \/\/ Chanserv password.\n}\n<commit_msg>irc: Adds Channel.IsLocal method. Determines if the given channel is local to the current server.<commit_after>\/\/ This file is subject to a 1-clause BSD license.\n\/\/ Its contents can be found in the enclosed LICENSE file.\n\npackage irc\n\n\/\/ Channel represents a single channel.\ntype Channel struct {\n\tName             string \/\/ Channel name.\n\tKey              string \/\/ Channel key. Might be needed to join when channel is protected.\n\tChanservPassword string \/\/ Chanserv password.\n}\n\n\/\/ Returns true if the channel is local to the current server.\n\/\/ This is the case when its name starts with '&'.\nfunc (c *Channel) IsLocal() bool {\n\treturn len(c.Name) > 0 && c.Name[0] == '&'\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2020 Shivaram Lingamneni\n\/\/ Released under the MIT license\n\npackage irc\n\nimport \"fmt\"\n\nconst (\n\t\/\/ SemVer is the semantic version of Oragono.\n\tSemVer = \"2.4.0-unreleased\"\n)\n\nvar (\n\t\/\/ Ver is the full version of Oragono, used in responses to clients.\n\tVer = fmt.Sprintf(\"oragono-%s\", SemVer)\n\t\/\/ Commit is the full git hash, if available\n\tCommit string\n)\n\n\/\/ initialize version strings (these are set in package main via linker flags)\nfunc SetVersionString(version, commit string) {\n\tCommit = commit\n\tif version != \"\" {\n\t\tVer = fmt.Sprintf(\"oragono-%s\", version)\n\t} else if len(Commit) == 40 {\n\t\tVer = fmt.Sprintf(\"oragono-%s-%s\", SemVer, Commit[:16])\n\t}\n}\n<commit_msg>bump version to 2.4.0-rc1<commit_after>\/\/ Copyright (c) 2020 Shivaram Lingamneni\n\/\/ Released under the MIT license\n\npackage irc\n\nimport \"fmt\"\n\nconst (\n\t\/\/ SemVer is the semantic version of Oragono.\n\tSemVer = \"2.4.0-rc1\"\n)\n\nvar (\n\t\/\/ Ver is the full version of Oragono, used in responses to clients.\n\tVer = fmt.Sprintf(\"oragono-%s\", SemVer)\n\t\/\/ Commit is the full git hash, if available\n\tCommit string\n)\n\n\/\/ initialize version strings (these are set in package main via linker flags)\nfunc SetVersionString(version, commit string) {\n\tCommit = commit\n\tif version != \"\" {\n\t\tVer = fmt.Sprintf(\"oragono-%s\", version)\n\t} else if len(Commit) == 40 {\n\t\tVer = fmt.Sprintf(\"oragono-%s-%s\", SemVer, Commit[:16])\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"eaciit\/gdrj\/model\"\n\t\"eaciit\/gdrj\/modules\"\n\t\"os\"\n\n\t\"github.com\/eaciit\/dbox\"\n\t\"github.com\/eaciit\/orm\/v1\"\n\t\"github.com\/eaciit\/toolkit\"\n\t\/\/ \"strings\"\n\t\"time\"\n)\n\nvar conn dbox.IConnection\nvar count int\n\nvar (\n\tt0                          time.Time\n\tfiscalyear, iscount, scount int\n\tdata                        map[string]float64\n\tmasters                     = toolkit.M{}\n\n\talloc = map[string]float64{\n\t\t\"I1\": 0.21,\n\t\t\"I3\": 0.49,\n\t\t\"I2\": 0.30,\n\t}\n)\n\nfunc setinitialconnection() {\n\tvar err error\n\tconn, err = modules.GetDboxIConnection(\"db_godrej\")\n\n\tif err != nil {\n\t\ttoolkit.Println(\"Initial connection found : \", err)\n\t\tos.Exit(1)\n\t}\n\n\terr = gdrj.SetDb(conn)\n\tif err != nil {\n\t\ttoolkit.Println(\"Initial connection found : \", err)\n\t\tos.Exit(1)\n\t}\n}\n\ntype sgaalloc struct {\n\tChannelID                                    string\n\tTotalNow, TotalExpect, RatioNow, RatioExpect float64\n\tTotalSales                                   float64\n}\n\nfunc (s *sgaalloc) Multiplier() float64 {\n\tif s.RatioNow == 0 {\n\t\treturn 0\n\t}\n\treturn s.RatioExpect \/ s.RatioNow\n}\n\nfunc calcDiff(tablename string) (m map[string]map[string]*sgaalloc, err error) {\n\tdiffConn, _ := modules.GetDboxIConnection(\"db_godrej\")\n\tdefer diffConn.Close()\n\n\tm = map[string]map[string]*sgaalloc{}\n\ttotals := map[string]float64{}\n\tsumnow, _ := diffConn.NewQuery().From(tablename).\n\t\tCursor(nil)\n\tfor {\n\t\tmnow := toolkit.M{}\n\t\tefetch := sumnow.Fetch(&mnow, 1, false)\n\t\tif efetch != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tkey := mnow.Get(\"key\", toolkit.M{}).(toolkit.M)\n\t\tfiscal := key.GetString(\"date_fiscal\")\n\t\tsgaf, sgafExist := m[fiscal]\n\t\ttotal := totals[fiscal]\n\t\tif !sgafExist {\n\t\t\tsgaf = map[string]*sgaalloc{}\n\t\t\tm[fiscal] = sgaf\n\t\t}\n\n\t\tchannelid := key.GetString(\"customer_channelid\")\n\t\tsga, sgaExist := sgaf[channelid]\n\t\tif !sgaExist {\n\t\t\tsga = new(sgaalloc)\n\t\t\tsgaf[channelid] = sga\n\t\t}\n\t\tsga.ChannelID = channelid\n\t\tsgavalue := mnow.GetFloat64(\"PL94A\")\n\t\tsga.TotalNow += sgavalue\n\t\tsga.TotalSales += mnow.GetFloat64(\"PL8A\")\n\t\ttotal += sgavalue\n\t\ttotals[fiscal] = total\n\t}\n\n\tfor fid, fallocs := range m {\n\t\ttotal := totals[fid]\n\t\tfor cid, calloc := range fallocs {\n\t\t\tcalloc.RatioNow = calloc.TotalNow \/ total\n\t\t\tratioexpect := alloc[cid]\n\t\t\tcalloc.RatioExpect = ratioexpect\n\t\t\tcalloc.TotalExpect = ratioexpect * total\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc main() {\n\tt0 = time.Now()\n\n\tsetinitialconnection()\n\tdefer gdrj.CloseDb()\n\tprepmastercalc()\n\n\ttoolkit.Println(\"Start data query...\")\n\ttablenames := []string{\n\t\t\"pl_customer_channelid_customer_channelname_date_fiscal\"}\n\n\tfor _, tn := range tablenames {\n\t\tdiff, e := calcDiff(tn)\n\t\tif e != nil {\n\t\t\ttoolkit.Printfn(\"Calc diff error: %s - %s\", tn, e.Error())\n\t\t\treturn\n\t\t}\n\n\t\te = processTable(tn, diff)\n\t\tif e != nil {\n\t\t\ttoolkit.Printfn(\"Process table error: %s - %s\", tn, e.Error())\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc processTable(tn string, ratio map[string]map[string]*sgaalloc) error {\n\ttoolkit.Printfn(\"Processing with alloc as follow: %s\", toolkit.JsonString(ratio))\n\n\tcursor, _ := conn.NewQuery().From(tn).Select().Cursor(nil)\n\tdefer cursor.Close()\n\n\tcount := cursor.Count()\n\ti := 0\n\tfor {\n\t\tmr := toolkit.M{}\n\t\tef := cursor.Fetch(&mr, 1, false)\n\t\tif ef != nil {\n\t\t\tbreak\n\t\t}\n\n\t\ti++\n\t\ttoolkit.Printfn(\"Processing %s, %d of %d\", tn, i, count)\n\n\t\tkey := mr.Get(\"key\", toolkit.M{}).(toolkit.M)\n\t\tfiscal := key.GetString(\"date_fiscal\")\n\t\tchannelid := key.GetString(\"customer_channelid\")\n\t\tfratio := ratio[fiscal]\n\t\tif fratio == nil {\n\t\t\tcontinue\n\t\t}\n\t\tsratio := fratio[channelid]\n\t\tif sratio == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tsalesRatio := mr.GetFloat64(\"PL8A\") \/ sratio.TotalSales\n\t\tfor k, v := range mr {\n\t\t\tif toolkit.HasMember([]string{\"PL33\", \"PL34\", \"PL35\", \"PL94\", \"PL94A\"}, k) {\n\t\t\t\tnewv := v.(float64) + salesRatio*(sratio.TotalExpect-sratio.TotalNow)\n\t\t\t\tmr.Set(k, newv)\n\t\t\t}\n\t\t}\n\n\t\tmr = CalcSum(mr)\n\t\tesave := conn.NewQuery().From(tn).Save().Exec(toolkit.M{}.Set(\"data\", mr))\n\t\tif esave != nil {\n\t\t\treturn esave\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc CalcSum(tkm toolkit.M) toolkit.M {\n\tvar netsales, cogs, grossmargin, sellingexpense,\n\t\tsga, opincome, directexpense, indirectexpense,\n\t\troyaltiestrademark, advtpromoexpense, operatingexpense,\n\t\tfreightexpense, nonoprincome, ebt, taxexpense,\n\t\tpercentpbt, eat, totdepreexp, damagegoods, ebitda, ebitdaroyalties, ebitsga,\n\t\tgrosssales, discount, advexp, promoexp, spgexp float64\n\n\texclude := []string{\"PL8A\", \"PL14A\", \"PL74A\", \"PL26A\", \"PL32A\", \"PL39A\", \"PL41A\", \"PL44A\",\n\t\t\"PL74B\", \"PL74C\", \"PL32B\", \"PL94B\", \"PL94C\", \"PL39B\", \"PL41B\", \"PL41C\", \"PL44B\", \"PL44C\", \"PL44D\", \"PL44E\",\n\t\t\"PL44F\", \"PL6A\", \"PL0\", \"PL28\", \"PL29A\", \"PL31\"}\n\t\/\/\"PL94A\",\n\tplmodels := masters.Get(\"plmodel\").(map[string]*gdrj.PLModel)\n\n\tinexclude := func(f string) bool {\n\t\tfor _, v := range exclude {\n\t\t\tif v == f {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\tfor k, v := range tkm {\n\t\tif k == \"_id\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif inexclude(k) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ arrk := strings.Split(k, \"_\")\n\n\t\tplmodel, exist := plmodels[k]\n\t\tif !exist {\n\t\t\t\/\/toolkit.Println(k)\n\t\t\tcontinue\n\t\t}\n\t\tAmount := toolkit.ToFloat64(v, 6, toolkit.RoundingAuto)\n\t\t\/\/ PLHeader1\n\t\t\/\/ PLHeader2\n\t\t\/\/ PLHeader3\n\t\t\/\/ switch v.Group1 {\n\t\tswitch plmodel.PLHeader1 {\n\t\tcase \"Net Sales\":\n\t\t\tnetsales += Amount\n\t\tcase \"Direct Expense\":\n\t\t\tdirectexpense += Amount\n\t\tcase \"Indirect Expense\":\n\t\t\tindirectexpense += Amount\n\t\tcase \"Freight Expense\":\n\t\t\tfreightexpense += Amount\n\t\tcase \"Royalties & Trademark Exp\":\n\t\t\troyaltiestrademark += Amount\n\t\tcase \"Advt & Promo Expenses\":\n\t\t\tadvtpromoexpense += Amount\n\t\tcase \"G&A Expenses\":\n\t\t\tsga += Amount\n\t\tcase \"Non Operating (Income) \/ Exp\":\n\t\t\tnonoprincome += Amount\n\t\tcase \"Tax Expense\":\n\t\t\ttaxexpense += Amount\n\t\tcase \"Total Depreciation Exp\":\n\t\t\tif plmodel.PLHeader2 == \"Damaged Goods\" {\n\t\t\t\tdamagegoods += Amount\n\t\t\t} else {\n\t\t\t\ttotdepreexp += Amount\n\t\t\t}\n\t\t}\n\n\t\t\/\/ switch v.Group2 {\n\t\tswitch plmodel.PLHeader2 {\n\t\tcase \"Gross Sales\":\n\t\t\tgrosssales += Amount\n\t\tcase \"Discount\":\n\t\t\tdiscount += Amount\n\t\tcase \"Advertising Expenses\":\n\t\t\tadvexp += Amount\n\t\tcase \"Promotions Expenses\":\n\t\t\tpromoexp += Amount\n\t\tcase \"SPG Exp \/ Export Cost\":\n\t\t\tspgexp += Amount\n\t\t}\n\t}\n\n\tcogs = directexpense + indirectexpense\n\tgrossmargin = netsales + cogs\n\tsellingexpense = freightexpense + royaltiestrademark + advtpromoexpense\n\toperatingexpense = sellingexpense + sga\n\topincome = grossmargin + operatingexpense\n\tebt = opincome + nonoprincome \/\/asume nonopriceincome already minus\n\tpercentpbt = 0\n\tif ebt != 0 {\n\t\tpercentpbt = taxexpense \/ ebt * 100\n\t}\n\teat = ebt + taxexpense\n\tebitda = totdepreexp + damagegoods + opincome\n\tebitdaroyalties = ebitda - royaltiestrademark\n\tebitsga = opincome - sga\n\tebitsgaroyalty := ebitsga - royaltiestrademark\n\n\ttkm.Set(\"PL0\", grosssales)\n\ttkm.Set(\"PL6A\", discount)\n\ttkm.Set(\"PL8A\", netsales)\n\ttkm.Set(\"PL14A\", directexpense)\n\ttkm.Set(\"PL74A\", indirectexpense)\n\ttkm.Set(\"PL26A\", royaltiestrademark)\n\ttkm.Set(\"PL32A\", advtpromoexpense)\n\ttkm.Set(\"PL94A\", sga)\n\ttkm.Set(\"PL39A\", nonoprincome)\n\ttkm.Set(\"PL41A\", taxexpense)\n\ttkm.Set(\"PL44A\", totdepreexp)\n\n\ttkm.Set(\"PL28\", advexp)\n\ttkm.Set(\"PL29A\", promoexp)\n\ttkm.Set(\"PL31\", spgexp)\n\ttkm.Set(\"PL74B\", cogs)\n\ttkm.Set(\"PL74C\", grossmargin)\n\ttkm.Set(\"PL32B\", sellingexpense)\n\ttkm.Set(\"PL94B\", operatingexpense)\n\ttkm.Set(\"PL94C\", opincome)\n\ttkm.Set(\"PL39B\", ebt)\n\ttkm.Set(\"PL41B\", percentpbt)\n\ttkm.Set(\"PL41C\", eat)\n\ttkm.Set(\"PL44B\", opincome)\n\ttkm.Set(\"PL44C\", ebitda)\n\ttkm.Set(\"PL44D\", ebitdaroyalties)\n\ttkm.Set(\"PL44E\", ebitsga)\n\ttkm.Set(\"PL44F\", ebitsgaroyalty)\n\n\treturn tkm\n}\n\nfunc buildmap(holder interface{},\n\tfnModel func() orm.IModel,\n\tfilter *dbox.Filter,\n\tfnIter func(holder interface{}, obj interface{})) interface{} {\n\tcrx, ecrx := gdrj.Find(fnModel(), filter, nil)\n\tif ecrx != nil {\n\t\ttoolkit.Printfn(\"Cursor Error: %s\", ecrx.Error())\n\t\tos.Exit(100)\n\t}\n\tdefer crx.Close()\n\tfor {\n\t\ts := fnModel()\n\t\te := crx.Fetch(s, 1, false)\n\t\tif e != nil {\n\t\t\tbreak\n\t\t}\n\t\tfnIter(holder, s)\n\t}\n\treturn holder\n}\n\nfunc prepmastercalc() {\n\ttoolkit.Println(\"--> PL MODEL\")\n\tmasters.Set(\"plmodel\", buildmap(map[string]*gdrj.PLModel{},\n\t\tfunc() orm.IModel {\n\t\t\treturn new(gdrj.PLModel)\n\t\t},\n\t\tnil,\n\t\tfunc(holder, obj interface{}) {\n\t\t\th := holder.(map[string]*gdrj.PLModel)\n\t\t\to := obj.(*gdrj.PLModel)\n\t\t\th[o.ID] = o\n\t\t}).(map[string]*gdrj.PLModel))\n}\n<commit_msg>sga update<commit_after>package main\n\nimport (\n\t\"eaciit\/gdrj\/model\"\n\t\"eaciit\/gdrj\/modules\"\n\t\"os\"\n\n\t\"github.com\/eaciit\/dbox\"\n\t\"github.com\/eaciit\/orm\/v1\"\n\t\"github.com\/eaciit\/toolkit\"\n\t\/\/ \"strings\"\n\t\"time\"\n)\n\nvar conn dbox.IConnection\nvar count int\n\nvar (\n\tt0                          time.Time\n\tfiscalyear, iscount, scount int\n\tdata                        map[string]float64\n\tmasters                     = toolkit.M{}\n\n\talloc = map[string]float64{\n\t\t\"I1\": 0.21,\n\t\t\"I3\": 0.49,\n\t\t\"I2\": 0.30,\n\t}\n)\n\nfunc setinitialconnection() {\n\tvar err error\n\tconn, err = modules.GetDboxIConnection(\"db_godrej\")\n\n\tif err != nil {\n\t\ttoolkit.Println(\"Initial connection found : \", err)\n\t\tos.Exit(1)\n\t}\n\n\terr = gdrj.SetDb(conn)\n\tif err != nil {\n\t\ttoolkit.Println(\"Initial connection found : \", err)\n\t\tos.Exit(1)\n\t}\n}\n\ntype sgaalloc struct {\n\tChannelID                                    string\n\tTotalNow, TotalExpect, RatioNow, RatioExpect float64\n\tTotalSales                                   float64\n}\n\nfunc (s *sgaalloc) Multiplier() float64 {\n\tif s.RatioNow == 0 {\n\t\treturn 0\n\t}\n\treturn s.RatioExpect \/ s.RatioNow\n}\n\nfunc calcDiff(tablename string) (m map[string]map[string]*sgaalloc, err error) {\n\tdiffConn, _ := modules.GetDboxIConnection(\"db_godrej\")\n\tdefer diffConn.Close()\n\n\tm = map[string]map[string]*sgaalloc{}\n\ttotals := map[string]float64{}\n\tsumnow, _ := diffConn.NewQuery().From(tablename).\n\t\tCursor(nil)\n\tcount := sumnow.Count()\n\ti := 0\n\tfor {\n\t\tmnow := toolkit.M{}\n\t\tefetch := sumnow.Fetch(&mnow, 1, false)\n\t\tif efetch != nil {\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t\ttoolkit.Printfn(\"Calculating diff. %d of %d in %s\",\n\t\t\ti, count, time.Since(t0).String())\n\n\t\tkey := mnow.Get(\"key\", toolkit.M{}).(toolkit.M)\n\t\tfiscal := key.GetString(\"date_fiscal\")\n\t\tsgaf, sgafExist := m[fiscal]\n\t\ttotal := totals[fiscal]\n\t\tif !sgafExist {\n\t\t\tsgaf = map[string]*sgaalloc{}\n\t\t\tm[fiscal] = sgaf\n\t\t}\n\n\t\tchannelid := key.GetString(\"customer_channelid\")\n\t\tsga, sgaExist := sgaf[channelid]\n\t\tif !sgaExist {\n\t\t\tsga = new(sgaalloc)\n\t\t\tsgaf[channelid] = sga\n\t\t}\n\t\tsga.ChannelID = channelid\n\t\tsgavalue := mnow.GetFloat64(\"PL94A\")\n\t\tsga.TotalNow += sgavalue\n\t\tsga.TotalSales += mnow.GetFloat64(\"PL8A\")\n\t\ttotal += sgavalue\n\t\ttotals[fiscal] = total\n\t}\n\n\tfor fid, fallocs := range m {\n\t\ttotal := totals[fid]\n\t\tfor cid, calloc := range fallocs {\n\t\t\tcalloc.RatioNow = calloc.TotalNow \/ total\n\t\t\tratioexpect := alloc[cid]\n\t\t\tcalloc.RatioExpect = ratioexpect\n\t\t\tcalloc.TotalExpect = ratioexpect * total\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc main() {\n\tt0 = time.Now()\n\n\tsetinitialconnection()\n\tdefer gdrj.CloseDb()\n\tprepmastercalc()\n\n\ttoolkit.Println(\"Start data query...\")\n\ttablenames := []string{\n\t\t\"salespls-summary\"}\n\n\tfor _, tn := range tablenames {\n\t\tdiff, e := calcDiff(tn)\n\t\tif e != nil {\n\t\t\ttoolkit.Printfn(\"Calc diff error: %s - %s\", tn, e.Error())\n\t\t\treturn\n\t\t}\n\n\t\te = processTable(tn, diff)\n\t\tif e != nil {\n\t\t\ttoolkit.Printfn(\"Process table error: %s - %s\", tn, e.Error())\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc processTable(tn string, ratio map[string]map[string]*sgaalloc) error {\n\ttoolkit.Printfn(\"Processing with alloc as follow: %s\", toolkit.JsonString(ratio))\n\n\tcursor, _ := conn.NewQuery().From(tn).Select().Cursor(nil)\n\tdefer cursor.Close()\n\n\tcount := cursor.Count()\n\ti := 0\n\tfor {\n\t\tmr := toolkit.M{}\n\t\tef := cursor.Fetch(&mr, 1, false)\n\t\tif ef != nil {\n\t\t\tbreak\n\t\t}\n\n\t\ti++\n\t\ttoolkit.Printfn(\"Processing %s, %d of %d in %s\",\n\t\t\ttn, i, count, time.Since(t0).String())\n\n\t\tkey := mr.Get(\"key\", toolkit.M{}).(toolkit.M)\n\t\tfiscal := key.GetString(\"date_fiscal\")\n\t\tchannelid := key.GetString(\"customer_channelid\")\n\t\tfratio := ratio[fiscal]\n\t\tif fratio == nil {\n\t\t\tcontinue\n\t\t}\n\t\tsratio := fratio[channelid]\n\t\tif sratio == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tsalesRatio := mr.GetFloat64(\"PL8A\") \/ sratio.TotalSales\n\t\tfor k, v := range mr {\n\t\t\tif toolkit.HasMember([]string{\"PL33\", \"PL34\", \"PL35\", \"PL94\", \"PL94A\"}, k) {\n\t\t\t\tnewv := v.(float64) + salesRatio*(sratio.TotalExpect-sratio.TotalNow)\n\t\t\t\tmr.Set(k, newv)\n\t\t\t}\n\t\t}\n\n\t\tmr = CalcSum(mr)\n\t\tesave := conn.NewQuery().From(tn).Save().Exec(toolkit.M{}.Set(\"data\", mr))\n\t\tif esave != nil {\n\t\t\treturn esave\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc CalcSum(tkm toolkit.M) toolkit.M {\n\tvar netsales, cogs, grossmargin, sellingexpense,\n\t\tsga, opincome, directexpense, indirectexpense,\n\t\troyaltiestrademark, advtpromoexpense, operatingexpense,\n\t\tfreightexpense, nonoprincome, ebt, taxexpense,\n\t\tpercentpbt, eat, totdepreexp, damagegoods, ebitda, ebitdaroyalties, ebitsga,\n\t\tgrosssales, discount, advexp, promoexp, spgexp float64\n\n\texclude := []string{\"PL8A\", \"PL14A\", \"PL74A\", \"PL26A\", \"PL32A\", \"PL39A\", \"PL41A\", \"PL44A\",\n\t\t\"PL74B\", \"PL74C\", \"PL32B\", \"PL94B\", \"PL94C\", \"PL39B\", \"PL41B\", \"PL41C\", \"PL44B\", \"PL44C\", \"PL44D\", \"PL44E\",\n\t\t\"PL44F\", \"PL6A\", \"PL0\", \"PL28\", \"PL29A\", \"PL31\"}\n\t\/\/\"PL94A\",\n\tplmodels := masters.Get(\"plmodel\").(map[string]*gdrj.PLModel)\n\n\tinexclude := func(f string) bool {\n\t\tfor _, v := range exclude {\n\t\t\tif v == f {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\n\t\treturn false\n\t}\n\n\tfor k, v := range tkm {\n\t\tif k == \"_id\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tif inexclude(k) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ arrk := strings.Split(k, \"_\")\n\n\t\tplmodel, exist := plmodels[k]\n\t\tif !exist {\n\t\t\t\/\/toolkit.Println(k)\n\t\t\tcontinue\n\t\t}\n\t\tAmount := toolkit.ToFloat64(v, 6, toolkit.RoundingAuto)\n\t\t\/\/ PLHeader1\n\t\t\/\/ PLHeader2\n\t\t\/\/ PLHeader3\n\t\t\/\/ switch v.Group1 {\n\t\tswitch plmodel.PLHeader1 {\n\t\tcase \"Net Sales\":\n\t\t\tnetsales += Amount\n\t\tcase \"Direct Expense\":\n\t\t\tdirectexpense += Amount\n\t\tcase \"Indirect Expense\":\n\t\t\tindirectexpense += Amount\n\t\tcase \"Freight Expense\":\n\t\t\tfreightexpense += Amount\n\t\tcase \"Royalties & Trademark Exp\":\n\t\t\troyaltiestrademark += Amount\n\t\tcase \"Advt & Promo Expenses\":\n\t\t\tadvtpromoexpense += Amount\n\t\tcase \"G&A Expenses\":\n\t\t\tsga += Amount\n\t\tcase \"Non Operating (Income) \/ Exp\":\n\t\t\tnonoprincome += Amount\n\t\tcase \"Tax Expense\":\n\t\t\ttaxexpense += Amount\n\t\tcase \"Total Depreciation Exp\":\n\t\t\tif plmodel.PLHeader2 == \"Damaged Goods\" {\n\t\t\t\tdamagegoods += Amount\n\t\t\t} else {\n\t\t\t\ttotdepreexp += Amount\n\t\t\t}\n\t\t}\n\n\t\t\/\/ switch v.Group2 {\n\t\tswitch plmodel.PLHeader2 {\n\t\tcase \"Gross Sales\":\n\t\t\tgrosssales += Amount\n\t\tcase \"Discount\":\n\t\t\tdiscount += Amount\n\t\tcase \"Advertising Expenses\":\n\t\t\tadvexp += Amount\n\t\tcase \"Promotions Expenses\":\n\t\t\tpromoexp += Amount\n\t\tcase \"SPG Exp \/ Export Cost\":\n\t\t\tspgexp += Amount\n\t\t}\n\t}\n\n\tcogs = directexpense + indirectexpense\n\tgrossmargin = netsales + cogs\n\tsellingexpense = freightexpense + royaltiestrademark + advtpromoexpense\n\toperatingexpense = sellingexpense + sga\n\topincome = grossmargin + operatingexpense\n\tebt = opincome + nonoprincome \/\/asume nonopriceincome already minus\n\tpercentpbt = 0\n\tif ebt != 0 {\n\t\tpercentpbt = taxexpense \/ ebt * 100\n\t}\n\teat = ebt + taxexpense\n\tebitda = totdepreexp + damagegoods + opincome\n\tebitdaroyalties = ebitda - royaltiestrademark\n\tebitsga = opincome - sga\n\tebitsgaroyalty := ebitsga - royaltiestrademark\n\n\ttkm.Set(\"PL0\", grosssales)\n\ttkm.Set(\"PL6A\", discount)\n\ttkm.Set(\"PL8A\", netsales)\n\ttkm.Set(\"PL14A\", directexpense)\n\ttkm.Set(\"PL74A\", indirectexpense)\n\ttkm.Set(\"PL26A\", royaltiestrademark)\n\ttkm.Set(\"PL32A\", advtpromoexpense)\n\ttkm.Set(\"PL94A\", sga)\n\ttkm.Set(\"PL39A\", nonoprincome)\n\ttkm.Set(\"PL41A\", taxexpense)\n\ttkm.Set(\"PL44A\", totdepreexp)\n\n\ttkm.Set(\"PL28\", advexp)\n\ttkm.Set(\"PL29A\", promoexp)\n\ttkm.Set(\"PL31\", spgexp)\n\ttkm.Set(\"PL74B\", cogs)\n\ttkm.Set(\"PL74C\", grossmargin)\n\ttkm.Set(\"PL32B\", sellingexpense)\n\ttkm.Set(\"PL94B\", operatingexpense)\n\ttkm.Set(\"PL94C\", opincome)\n\ttkm.Set(\"PL39B\", ebt)\n\ttkm.Set(\"PL41B\", percentpbt)\n\ttkm.Set(\"PL41C\", eat)\n\ttkm.Set(\"PL44B\", opincome)\n\ttkm.Set(\"PL44C\", ebitda)\n\ttkm.Set(\"PL44D\", ebitdaroyalties)\n\ttkm.Set(\"PL44E\", ebitsga)\n\ttkm.Set(\"PL44F\", ebitsgaroyalty)\n\n\treturn tkm\n}\n\nfunc buildmap(holder interface{},\n\tfnModel func() orm.IModel,\n\tfilter *dbox.Filter,\n\tfnIter func(holder interface{}, obj interface{})) interface{} {\n\tcrx, ecrx := gdrj.Find(fnModel(), filter, nil)\n\tif ecrx != nil {\n\t\ttoolkit.Printfn(\"Cursor Error: %s\", ecrx.Error())\n\t\tos.Exit(100)\n\t}\n\tdefer crx.Close()\n\tfor {\n\t\ts := fnModel()\n\t\te := crx.Fetch(s, 1, false)\n\t\tif e != nil {\n\t\t\tbreak\n\t\t}\n\t\tfnIter(holder, s)\n\t}\n\treturn holder\n}\n\nfunc prepmastercalc() {\n\ttoolkit.Println(\"--> PL MODEL\")\n\tmasters.Set(\"plmodel\", buildmap(map[string]*gdrj.PLModel{},\n\t\tfunc() orm.IModel {\n\t\t\treturn new(gdrj.PLModel)\n\t\t},\n\t\tnil,\n\t\tfunc(holder, obj interface{}) {\n\t\t\th := holder.(map[string]*gdrj.PLModel)\n\t\t\to := obj.(*gdrj.PLModel)\n\t\t\th[o.ID] = o\n\t\t}).(map[string]*gdrj.PLModel))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage wordlist\n\nvar DefaultWordlist = `\n.git\n.htaccess\n.htpasswd\nAdmin\nAdministration\nCVS\nLog\nLogs\nPages\nServlet\nServlets\nSiteServer\nSources\nStatistics\nStats\nW3SVC\nW3SVC1\nW3SVC2\nW3SVC3\nWEB-INF\na\naa\naaa\nabc\nabout\nacademic\naccess\naccessgranted\naccount\naccounting\naction\nactions\nactive\nadm\nadmin\nadmin_login\nadmin_logon\nadministration\nadministrator\nadminlogin\nadminlogon\nadminsql\nadsl\nagent\nagents\nalias\naliases\nall\nalpha\nanalog\nanalyse\nannouncements\nanswer\nany\napache\napi\napp\napplet\napplets\nappliance\napplication\napplications\napps\narchive\narchives\narrow\nasp\naspadmin\nassets\nattach\nattachments\naudit\nauth\nauto\nautomatic\nb\nback\nback-up\nbackdoor\nbackend\nbackoffice\nbackup\nbackups\nbak\nbak-up\nbakup\nbank\nbanks\nbanner\nbanners\nbase\nbasic\nbass\nbatch\nbd\nbdata\nbea\nbean\nbeans\nbeta\nbill\nbilling\nbin\nbinaries\nbiz\nblog\nblow\nboard\nboards\nbody\nboot\nbot\nbots\nbox\nboxes\nbroken\nbsd\nbug\nbugs\nbuild\nbuilder\nbulk\nbuttons\nc\ncache\ncachemgr\ncad\ncan\ncaptcha\ncar\ncard\ncardinal\ncards\ncarpet\ncart\ncas\ncat\ncatalog\ncatalogs\ncatch\ncc\nccs\ncd\ncdrom\ncert\ncertenroll\ncertificate\ncertificates\ncerts\ncfdocs\ncfg\ncgi\ncgi-bin\/\ncgi-win\ncgibin\nchan\nchange\nchangepw\nchannel\nchart\nchat\nclass\nclasses\nclassic\nclassified\nclassifieds\nclient\nclients\ncluster\ncm\ncmd\ncode\ncoffee\ncommand\ncommerce\ncommercial\ncommon\ncomponent\ncompose\ncomposer\ncompressed\ncomunicator\ncon\nconfig\nconfigs\nconfiguration\nconfigure\nconnect\nconnections\nconsole\nconstant\nconstants\ncontact\ncontacts\ncontent\ncontents\ncontrol\ncontroller\ncontrolpanel\ncontrols\ncorba\ncore\ncorporate\ncount\ncounter\ncpanel\ncreate\ncreation\ncredit\ncreditcards\ncron\ncrs\ncss\ncustomer\ncustomers\ncv\ncvs\nd\ndaemon\ndat\ndata\ndatabase\ndatabases\ndav\ndb\ndba\ndbase\ndbm\ndbms\ndebug\ndefault\ndelete\ndeletion\ndemo\ndemos\ndeny\ndeploy\ndeployment\ndesign\ndetails\ndev\ndev60cgi\ndevel\ndevelop\ndevelopement\ndevelopers\ndevelopment\ndevice\ndevices\ndevs\ndiag\ndial\ndig\ndir\ndirectory\ndiscovery\ndisk\ndispatch\ndispatcher\ndms\ndns\ndoc\ndocs\ndocument\ndocuments\ndown\ndownload\ndownloads\ndraft\ndragon\ndratfs\ndriver\ndump\ndumpenv\ne\neasy\nebriefs\nechannel\necommerce\nedit\neditor\nelement\nelements\nemail\nemployees\nen\neng\nengine\nenglish\nenterprise\nenv\nenviron\nenvironment\nerror\nerrors\nes\nesales\nesp\nestablished\nesupport\netc\nevent\nevents\nexample\nexamples\nexchange\nexe\nexec\nexecutable\nexecutables\nexplorer\nexport\nexternal\nextra\nExtranet\nextranet\nfail\nfailed\nfcgi-bin\nfeedback\nfield\nfile\nfiles\nfilter\nfirewall\nfirst\nflash\nfolder\nfoo\nforget\nforgot\nforgotten\nform\nformat\nformhandler\nformsend\nformupdate\nfortune\nforum\nforums\nframe\nframework\nftp\nfun\nfunction\nfunctions\ngames\ngate\ngeneric\ngest\nget\nglobal\nglobalnav\nglobals\ngone\ngp\ngpapp\ngranted\ngraphics\ngroup\ngroups\nguest\nguestbook\nguests\nhack\nhacker\nhandler\nhanlder\nhappening\nhead\nheader\nheaders\nhello\nhelloworld\nhelp\nhidden\nhide\nhistory\nhits\nhome\nhomepage\nhomes\nhomework\nhost\nhosts\nhtdocs\nhtm\nhtml\nhtmls\nibm\nicons\nidbc\niis\nimages\nimg\nimport\ninbox\ninc\ninclude\nincludes\nincoming\nincs\nindex\nindex2\nindex_adm\nindex_admin\nindexes\ninfo\ninformation\ningres\ningress\nini\ninit\ninput\ninstall\ninstallation\ninteractive\ninternal\ninternet\nintranet\nintro\ninventory\ninvitation\ninvite\nipp\nips\nj\njava\njava-sys\njavascript\njdbc\njob\njoin\njrun\njs\njsp\njsps\njsr\nkeep\nkept\nkernel\nkey\nlab\nlabs\nlaunch\nlaunchpage\nldap\nleft\nlevel\nlib\nlibraries\nlibrary\nlibs\nlink\nlinks\nlinux\nlist\nload\nloader\nlock\nlockout\nlog\nlogfile\nlogfiles\nlogger\nlogging\nlogin\nlogo\nlogon\nlogout\nlogs\nlost%2Bfound\nls\nmagic\nmail\nmailbox\nmaillist\nmain\nmaint\nmakefile\nman\nmanage\nmanagement\nmanager\nmanual\nmap\nmarket\nmarketing\nmaster\nmbo\nmdb\nme\nmember\nmembers\nmemory\nmenu\nmessage\nmessages\nmessaging\nmeta\nmetabase\nmgr\nmine\nminimum\nmirror\nmirrors\nmisc\nmkstats\nmodel\nmodem\nmodule\nmodules\nmonitor\nmount\nmp3\nmp3s\nmqseries\nmrtg\nms\nms-sql\nmsql\nmssql\nmusic\nmy\nmy-sql\nmysql\nnames\nnavigation\nne\nnet\nnetscape\nnetstat\nnetwork\nnew\nnews\nnext\nnl\nnobody\nnotes\nnovell\nnul\nnull\nnumber\nobject\nobjects\nodbc\nof\noff\noffice\nogl\nold\non\nonline\nopen\nopenapp\nopenfile\noperator\noracle\noradata\norder\norders\noutgoing\noutput\npad\npage\npages\npam\npanel\npaper\npapers\npass\npasses\npassw\npasswd\npasswor\npassword\npasswords\npath\npdf\nperl\nperl5\npersonal\npersonals\npgsql\nphone\nphp\nphpMyAdmin\nphpmyadmin\npics\nping\npix\npl\npls\nplx\npol\npolicy\npoll\npop\nportal\nportlet\nportlets\npost\npostgres\npower\npress\npreview\nprint\nprintenv\npriv\nprivate\nprivs\nprocess\nprocessform\nprod\nproduction\nproducts\nprofessor\nprofile\nprogram\nproject\nproof\nproperties\nprotect\nprotected\nproxy\nps\npub\npublic\npublish\npublisher\npurchase\npurchases\nput\npw\npwd\npython\nquery\nqueue\nquote\nramon\nrandom\nrank\nrcs\nreadme\nredir\nredirect\nreference\nreferences\nreg\nreginternal\nregional\nregister\nregistered\nrelease\nremind\nreminder\nremote\nremoved\nreport\nreports\nrequisite\nresearch\nreseller\nresource\nresources\nresponder\nrestricted\nretail\nright\nrobot\nrobots.txt\nrobotics\nroot\nroute\nrouter\nrpc\nrss\nrules\nrun\nsales\nsample\nsamples\nsave\nsaved\nschema\nscr\nscratc\nscript\nscripts\nsdk\nsearch\nsecret\nsecrets\nsection\nsections\nsecure\nsecured\nsecurity\nselect\nsell\nsend\nsendmail\nsensepost\nsensor\nsent\nserver\nserver_stats\nservers\nservice\nservices\nservlet\nservlets\nsession\nsessions\nset\nsetting\nsettings\nsetup\nshare\nshared\nshell\nshit\nshop\nshopper\nshow\nshowcode\nshtml\nsign\nsignature\nsignin\nsimple\nsingle\nsite\nsitemap\nsites\nsmall\nsnoop\nsoap\nsoapdocs\nsoftware\nsolaris\nsolutions\nsomebody\nsource\nsources\nspain\nspanish\nsql\nsqladmin\nsrc\nsrchad\nsrv\nssi\nssl\nstaff\nstart\nstartpage\nstat\nstatic\nstatistic\nstatistics\nstats\nstatus\nstop\nstore\nstory\nstring\nstudent\nstuff\nstyle\nstylesheet\nstylesheets\nsubmit\nsubmitter\nsun\nsuper\nsupport\nsupported\nsurvey\nsvc\nsvn\nsvr\nsys\nsysadmin\nsystem\ntable\ntag\ntape\ntar\ntarget\ntech\ntemp\ntemplate\ntemplates\ntemporal\ntemps\nterminal\ntest\ntesting\ntests\ntext\ntexts\nticket\ntmp\ntoday\ntool\ntoolbar\ntools\ntop\ntopics\ntour\ntrace\ntraffic\ntransactions\ntransfer\ntransport\ntrap\ntrash\ntree\ntrees\ntsql\ntutorial\nuddi\nuninstall\nunix\nup\nupdate\nupdates\nupload\nuploader\nuploads\nusage\nuser\nusers\nusr\nustats\nutil\nutilities\nutility\nutils\nvalidation\nvalidatior\nvap\nvar\nvb\nvbs\nvbscript\nvbscripts\nvfs\nview\nviewer\nviews\nvirtual\nvisitor\nvpn\nw\nw3\nw3c\nwarez\nwdav\nweb\nwebaccess\nwebadmin\nwebapp\nwebboard\nwebcart\nwebdata\nwebdav\nwebdist\nwebhits\nweblog\nweblogic\nweblogs\nwebmail\nwebmaster\nwebsearch\nwebsite\nwebstat\nwebstats\nwebvpn\nwelcome\nwellcome\nwhatever\nwhatnot\nwhois\nwill\nwin\nwindows\nword\nwork\nworkplace\nworkshop\nwstats\nwusage\nwww\nwwwboard\nwwwjoin\nwwwlog\nwwwstats\nxcache\nxfer\nxml\nxmlrpc\nxsl\nxyz\nzip\nzipfiles\nzips\n`\n<commit_msg>Fix wordlist for lost+found.<commit_after>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage wordlist\n\nvar DefaultWordlist = `\n.git\n.htaccess\n.htpasswd\nAdmin\nAdministration\nCVS\nLog\nLogs\nPages\nServlet\nServlets\nSiteServer\nSources\nStatistics\nStats\nW3SVC\nW3SVC1\nW3SVC2\nW3SVC3\nWEB-INF\na\naa\naaa\nabc\nabout\nacademic\naccess\naccessgranted\naccount\naccounting\naction\nactions\nactive\nadm\nadmin\nadmin_login\nadmin_logon\nadministration\nadministrator\nadminlogin\nadminlogon\nadminsql\nadsl\nagent\nagents\nalias\naliases\nall\nalpha\nanalog\nanalyse\nannouncements\nanswer\nany\napache\napi\napp\napplet\napplets\nappliance\napplication\napplications\napps\narchive\narchives\narrow\nasp\naspadmin\nassets\nattach\nattachments\naudit\nauth\nauto\nautomatic\nb\nback\nback-up\nbackdoor\nbackend\nbackoffice\nbackup\nbackups\nbak\nbak-up\nbakup\nbank\nbanks\nbanner\nbanners\nbase\nbasic\nbass\nbatch\nbd\nbdata\nbea\nbean\nbeans\nbeta\nbill\nbilling\nbin\nbinaries\nbiz\nblog\nblow\nboard\nboards\nbody\nboot\nbot\nbots\nbox\nboxes\nbroken\nbsd\nbug\nbugs\nbuild\nbuilder\nbulk\nbuttons\nc\ncache\ncachemgr\ncad\ncan\ncaptcha\ncar\ncard\ncardinal\ncards\ncarpet\ncart\ncas\ncat\ncatalog\ncatalogs\ncatch\ncc\nccs\ncd\ncdrom\ncert\ncertenroll\ncertificate\ncertificates\ncerts\ncfdocs\ncfg\ncgi\ncgi-bin\/\ncgi-win\ncgibin\nchan\nchange\nchangepw\nchannel\nchart\nchat\nclass\nclasses\nclassic\nclassified\nclassifieds\nclient\nclients\ncluster\ncm\ncmd\ncode\ncoffee\ncommand\ncommerce\ncommercial\ncommon\ncomponent\ncompose\ncomposer\ncompressed\ncomunicator\ncon\nconfig\nconfigs\nconfiguration\nconfigure\nconnect\nconnections\nconsole\nconstant\nconstants\ncontact\ncontacts\ncontent\ncontents\ncontrol\ncontroller\ncontrolpanel\ncontrols\ncorba\ncore\ncorporate\ncount\ncounter\ncpanel\ncreate\ncreation\ncredit\ncreditcards\ncron\ncrs\ncss\ncustomer\ncustomers\ncv\ncvs\nd\ndaemon\ndat\ndata\ndatabase\ndatabases\ndav\ndb\ndba\ndbase\ndbm\ndbms\ndebug\ndefault\ndelete\ndeletion\ndemo\ndemos\ndeny\ndeploy\ndeployment\ndesign\ndetails\ndev\ndev60cgi\ndevel\ndevelop\ndevelopement\ndevelopers\ndevelopment\ndevice\ndevices\ndevs\ndiag\ndial\ndig\ndir\ndirectory\ndiscovery\ndisk\ndispatch\ndispatcher\ndms\ndns\ndoc\ndocs\ndocument\ndocuments\ndown\ndownload\ndownloads\ndraft\ndragon\ndratfs\ndriver\ndump\ndumpenv\ne\neasy\nebriefs\nechannel\necommerce\nedit\neditor\nelement\nelements\nemail\nemployees\nen\neng\nengine\nenglish\nenterprise\nenv\nenviron\nenvironment\nerror\nerrors\nes\nesales\nesp\nestablished\nesupport\netc\nevent\nevents\nexample\nexamples\nexchange\nexe\nexec\nexecutable\nexecutables\nexplorer\nexport\nexternal\nextra\nExtranet\nextranet\nfail\nfailed\nfcgi-bin\nfeedback\nfield\nfile\nfiles\nfilter\nfirewall\nfirst\nflash\nfolder\nfoo\nforget\nforgot\nforgotten\nform\nformat\nformhandler\nformsend\nformupdate\nfortune\nforum\nforums\nframe\nframework\nftp\nfun\nfunction\nfunctions\ngames\ngate\ngeneric\ngest\nget\nglobal\nglobalnav\nglobals\ngone\ngp\ngpapp\ngranted\ngraphics\ngroup\ngroups\nguest\nguestbook\nguests\nhack\nhacker\nhandler\nhanlder\nhappening\nhead\nheader\nheaders\nhello\nhelloworld\nhelp\nhidden\nhide\nhistory\nhits\nhome\nhomepage\nhomes\nhomework\nhost\nhosts\nhtdocs\nhtm\nhtml\nhtmls\nibm\nicons\nidbc\niis\nimages\nimg\nimport\ninbox\ninc\ninclude\nincludes\nincoming\nincs\nindex\nindex2\nindex_adm\nindex_admin\nindexes\ninfo\ninformation\ningres\ningress\nini\ninit\ninput\ninstall\ninstallation\ninteractive\ninternal\ninternet\nintranet\nintro\ninventory\ninvitation\ninvite\nipp\nips\nj\njava\njava-sys\njavascript\njdbc\njob\njoin\njrun\njs\njsp\njsps\njsr\nkeep\nkept\nkernel\nkey\nlab\nlabs\nlaunch\nlaunchpage\nldap\nleft\nlevel\nlib\nlibraries\nlibrary\nlibs\nlink\nlinks\nlinux\nlist\nload\nloader\nlock\nlockout\nlog\nlogfile\nlogfiles\nlogger\nlogging\nlogin\nlogo\nlogon\nlogout\nlogs\nlost+found\nls\nmagic\nmail\nmailbox\nmaillist\nmain\nmaint\nmakefile\nman\nmanage\nmanagement\nmanager\nmanual\nmap\nmarket\nmarketing\nmaster\nmbo\nmdb\nme\nmember\nmembers\nmemory\nmenu\nmessage\nmessages\nmessaging\nmeta\nmetabase\nmgr\nmine\nminimum\nmirror\nmirrors\nmisc\nmkstats\nmodel\nmodem\nmodule\nmodules\nmonitor\nmount\nmp3\nmp3s\nmqseries\nmrtg\nms\nms-sql\nmsql\nmssql\nmusic\nmy\nmy-sql\nmysql\nnames\nnavigation\nne\nnet\nnetscape\nnetstat\nnetwork\nnew\nnews\nnext\nnl\nnobody\nnotes\nnovell\nnul\nnull\nnumber\nobject\nobjects\nodbc\nof\noff\noffice\nogl\nold\non\nonline\nopen\nopenapp\nopenfile\noperator\noracle\noradata\norder\norders\noutgoing\noutput\npad\npage\npages\npam\npanel\npaper\npapers\npass\npasses\npassw\npasswd\npasswor\npassword\npasswords\npath\npdf\nperl\nperl5\npersonal\npersonals\npgsql\nphone\nphp\nphpMyAdmin\nphpmyadmin\npics\nping\npix\npl\npls\nplx\npol\npolicy\npoll\npop\nportal\nportlet\nportlets\npost\npostgres\npower\npress\npreview\nprint\nprintenv\npriv\nprivate\nprivs\nprocess\nprocessform\nprod\nproduction\nproducts\nprofessor\nprofile\nprogram\nproject\nproof\nproperties\nprotect\nprotected\nproxy\nps\npub\npublic\npublish\npublisher\npurchase\npurchases\nput\npw\npwd\npython\nquery\nqueue\nquote\nramon\nrandom\nrank\nrcs\nreadme\nredir\nredirect\nreference\nreferences\nreg\nreginternal\nregional\nregister\nregistered\nrelease\nremind\nreminder\nremote\nremoved\nreport\nreports\nrequisite\nresearch\nreseller\nresource\nresources\nresponder\nrestricted\nretail\nright\nrobot\nrobots.txt\nrobotics\nroot\nroute\nrouter\nrpc\nrss\nrules\nrun\nsales\nsample\nsamples\nsave\nsaved\nschema\nscr\nscratc\nscript\nscripts\nsdk\nsearch\nsecret\nsecrets\nsection\nsections\nsecure\nsecured\nsecurity\nselect\nsell\nsend\nsendmail\nsensepost\nsensor\nsent\nserver\nserver_stats\nservers\nservice\nservices\nservlet\nservlets\nsession\nsessions\nset\nsetting\nsettings\nsetup\nshare\nshared\nshell\nshit\nshop\nshopper\nshow\nshowcode\nshtml\nsign\nsignature\nsignin\nsimple\nsingle\nsite\nsitemap\nsites\nsmall\nsnoop\nsoap\nsoapdocs\nsoftware\nsolaris\nsolutions\nsomebody\nsource\nsources\nspain\nspanish\nsql\nsqladmin\nsrc\nsrchad\nsrv\nssi\nssl\nstaff\nstart\nstartpage\nstat\nstatic\nstatistic\nstatistics\nstats\nstatus\nstop\nstore\nstory\nstring\nstudent\nstuff\nstyle\nstylesheet\nstylesheets\nsubmit\nsubmitter\nsun\nsuper\nsupport\nsupported\nsurvey\nsvc\nsvn\nsvr\nsys\nsysadmin\nsystem\ntable\ntag\ntape\ntar\ntarget\ntech\ntemp\ntemplate\ntemplates\ntemporal\ntemps\nterminal\ntest\ntesting\ntests\ntext\ntexts\nticket\ntmp\ntoday\ntool\ntoolbar\ntools\ntop\ntopics\ntour\ntrace\ntraffic\ntransactions\ntransfer\ntransport\ntrap\ntrash\ntree\ntrees\ntsql\ntutorial\nuddi\nuninstall\nunix\nup\nupdate\nupdates\nupload\nuploader\nuploads\nusage\nuser\nusers\nusr\nustats\nutil\nutilities\nutility\nutils\nvalidation\nvalidatior\nvap\nvar\nvb\nvbs\nvbscript\nvbscripts\nvfs\nview\nviewer\nviews\nvirtual\nvisitor\nvpn\nw\nw3\nw3c\nwarez\nwdav\nweb\nwebaccess\nwebadmin\nwebapp\nwebboard\nwebcart\nwebdata\nwebdav\nwebdist\nwebhits\nweblog\nweblogic\nweblogs\nwebmail\nwebmaster\nwebsearch\nwebsite\nwebstat\nwebstats\nwebvpn\nwelcome\nwellcome\nwhatever\nwhatnot\nwhois\nwill\nwin\nwindows\nword\nwork\nworkplace\nworkshop\nwstats\nwusage\nwww\nwwwboard\nwwwjoin\nwwwlog\nwwwstats\nxcache\nxfer\nxml\nxmlrpc\nxsl\nxyz\nzip\nzipfiles\nzips\n`\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012, 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage deployer\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\n\t\"github.com\/juju\/names\"\n\n\t\"github.com\/juju\/juju\/agent\"\n\t\"github.com\/juju\/juju\/agent\/tools\"\n\t\"github.com\/juju\/juju\/apiserver\/params\"\n\t\"github.com\/juju\/juju\/service\"\n\t\"github.com\/juju\/juju\/service\/common\"\n\t\"github.com\/juju\/juju\/version\"\n)\n\n\/\/ TODO(ericsnow) Eliminate InitDir.\n\n\/\/ InitDir is the default upstart init directory.\n\/\/ This is a var so it can be overridden by tests.\nvar InitDir = \"\/etc\/init\"\n\n\/\/ APICalls defines the interface to the API that the simple context needs.\ntype APICalls interface {\n\tConnectionInfo() (params.DeployerConnectionValues, error)\n}\n\n\/\/ SimpleContext is a Context that manages unit deployments on the local system.\ntype SimpleContext struct {\n\n\t\/\/ api is used to get the current state server addresses at the time the\n\t\/\/ given unit is deployed.\n\tapi APICalls\n\n\t\/\/ agentConfig returns the agent config for the machine agent that is\n\t\/\/ running the deployer.\n\tagentConfig agent.Config\n\n\t\/\/ initDir specifies the directory used by init on the local system.\n\t\/\/ For upstart, it is typically set to \"\/etc\/init\".\n\tinitDir string\n\n\t\/\/ discoverService is a surrogate for service.DiscoverService.\n\tdiscoverService func(string, common.Conf) deployerService\n\n\t\/\/ listServices is a surrogate for service.ListServices.\n\tlistServices func(string) ([]string, error)\n}\n\nvar _ Context = (*SimpleContext)(nil)\n\n\/\/ recursiveChmod will change the permissions on all files and\n\/\/ folders inside path\nfunc recursiveChmod(path string, mode os.FileMode) error {\n\twalker := func(p string, fi os.FileInfo, err error) error {\n\t\tif _, err := os.Stat(p); err == nil {\n\t\t\terrPerm := os.Chmod(p, mode)\n\t\t\tif errPerm != nil {\n\t\t\t\treturn errPerm\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tif err := filepath.Walk(path, walker); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ NewSimpleContext returns a new SimpleContext, acting on behalf of\n\/\/ the specified deployer, that deploys unit agents.\n\/\/ Paths to which agents and tools are installed are relative to dataDir.\nfunc NewSimpleContext(agentConfig agent.Config, api APICalls) *SimpleContext {\n\treturn &SimpleContext{\n\t\tapi:         api,\n\t\tagentConfig: agentConfig,\n\t\tinitDir:     InitDir,\n\t\tdiscoverService: func(name string, conf common.Conf) deployerService {\n\t\t\tsvc, _ := service.DiscoverService(name, conf)\n\t\t\treturn svc\n\t\t},\n\t\tlistServices: func(initDir string) ([]string, error) {\n\t\t\treturn service.ListServices(initDir)\n\t\t},\n\t}\n}\n\nfunc (ctx *SimpleContext) AgentConfig() agent.Config {\n\treturn ctx.agentConfig\n}\n\nfunc (ctx *SimpleContext) DeployUnit(unitName, initialPassword string) (err error) {\n\t\/\/ Check sanity.\n\tsvc := ctx.service(unitName)\n\tif svc.Installed() {\n\t\treturn fmt.Errorf(\"unit %q is already deployed\", unitName)\n\t}\n\n\t\/\/ Link the current tools for use by the new agent.\n\ttag := names.NewUnitTag(unitName)\n\tdataDir := ctx.agentConfig.DataDir()\n\tlogDir := ctx.agentConfig.LogDir()\n\t\/\/ TODO(dfc)\n\t_, err = tools.ChangeAgentTools(dataDir, tag.String(), version.Current)\n\t\/\/ TODO(dfc)\n\ttoolsDir := tools.ToolsDir(dataDir, tag.String())\n\tdefer removeOnErr(&err, toolsDir)\n\n\tresult, err := ctx.api.ConnectionInfo()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.Debugf(\"state addresses: %q\", result.StateAddresses)\n\tlogger.Debugf(\"API addresses: %q\", result.APIAddresses)\n\tcontainerType := ctx.agentConfig.Value(agent.ContainerType)\n\tnamespace := ctx.agentConfig.Value(agent.Namespace)\n\tconf, err := agent.NewAgentConfig(\n\t\tagent.AgentConfigParams{\n\t\t\tDataDir:           dataDir,\n\t\t\tLogDir:            logDir,\n\t\t\tUpgradedToVersion: version.Current.Number,\n\t\t\tTag:               tag,\n\t\t\tPassword:          initialPassword,\n\t\t\tNonce:             \"unused\",\n\t\t\tEnvironment:       ctx.agentConfig.Environment(),\n\t\t\t\/\/ TODO: remove the state addresses here and test when api only.\n\t\t\tStateAddresses: result.StateAddresses,\n\t\t\tAPIAddresses:   result.APIAddresses,\n\t\t\tCACert:         ctx.agentConfig.CACert(),\n\t\t\tValues: map[string]string{\n\t\t\t\tagent.ContainerType: containerType,\n\t\t\t\tagent.Namespace:     namespace,\n\t\t\t},\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := conf.Write(); err != nil {\n\t\treturn err\n\t}\n\tdefer removeOnErr(&err, conf.Dir())\n\n\t\/\/ Install an init service that runs the unit agent.\n\tsconf, _ := service.UnitAgentConf(\n\t\tunitName,\n\t\tdataDir,\n\t\tlogDir,\n\t\t\"\",\n\t\tcontainerType,\n\t)\n\tsconf.InitDir = ctx.initDir\n\tsvc.UpdateConfig(sconf)\n\treturn svc.Install()\n}\n\ntype deployerService interface {\n\tUpdateConfig(common.Conf)\n\tInstalled() bool\n\tInstall() error\n\tStopAndRemove() error\n}\n\n\/\/ findUpstartJob tries to find an init system job matching the\n\/\/ given unit name in one of these formats:\n\/\/   jujud-<deployer-tag>:<unit-tag>.conf (for compatibility)\n\/\/   jujud-<unit-tag>.conf (default)\nfunc (ctx *SimpleContext) findInitSystemJob(unitName string) deployerService {\n\tunitsAndJobs, err := ctx.deployedUnitsInitSystemJobs()\n\tif err != nil {\n\t\treturn nil\n\t}\n\tif job, ok := unitsAndJobs[unitName]; ok {\n\t\treturn ctx.discoverService(job, common.Conf{InitDir: ctx.initDir})\n\t}\n\treturn nil\n}\n\nfunc (ctx *SimpleContext) RecallUnit(unitName string) error {\n\tsvc := ctx.findInitSystemJob(unitName)\n\tif svc == nil || !svc.Installed() {\n\t\treturn fmt.Errorf(\"unit %q is not deployed\", unitName)\n\t}\n\tif err := svc.StopAndRemove(); err != nil {\n\t\treturn err\n\t}\n\ttag := names.NewUnitTag(unitName)\n\tdataDir := ctx.agentConfig.DataDir()\n\tagentDir := agent.Dir(dataDir, tag)\n\t\/\/ Recursivley change mode to 777 on windows to avoid\n\t\/\/ Operation not permitted errors when deleting the agentDir\n\terr := recursiveChmod(agentDir, os.FileMode(0777))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := os.RemoveAll(agentDir); err != nil {\n\t\treturn err\n\t}\n\t\/\/ TODO(dfc) should take a Tag\n\ttoolsDir := tools.ToolsDir(dataDir, tag.String())\n\treturn os.Remove(toolsDir)\n}\n\nvar deployedRe = regexp.MustCompile(\"^(jujud-.*unit-([a-z0-9-]+)-([0-9]+))$\")\n\nfunc (ctx *SimpleContext) deployedUnitsInitSystemJobs() (map[string]string, error) {\n\tfis, err := ctx.listServices(ctx.initDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinstalled := make(map[string]string)\n\tfor _, fi := range fis {\n\t\tif groups := deployedRe.FindStringSubmatch(fi); len(groups) > 0 {\n\t\t\tunitName := groups[2] + \"\/\" + groups[3]\n\t\t\tif !names.IsValidUnit(unitName) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tinstalled[unitName] = groups[1]\n\t\t}\n\t}\n\treturn installed, nil\n}\n\nfunc (ctx *SimpleContext) DeployedUnits() ([]string, error) {\n\tunitsAndJobs, err := ctx.deployedUnitsInitSystemJobs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar installed []string\n\tfor unitName := range unitsAndJobs {\n\t\tinstalled = append(installed, unitName)\n\t}\n\treturn installed, nil\n}\n\n\/\/ service returns a service.Service corresponding to the specified\n\/\/ unit.\nfunc (ctx *SimpleContext) service(unitName string) deployerService {\n\ttag := names.NewUnitTag(unitName).String()\n\tsvcName := \"jujud-\" + tag\n\treturn ctx.discoverService(svcName, common.Conf{InitDir: ctx.initDir})\n}\n\nfunc removeOnErr(err *error, path string) {\n\tif *err != nil {\n\t\tif err := os.Remove(path); err != nil {\n\t\t\tlogger.Warningf(\"installer: cannot remove %q: %v\", path, err)\n\t\t}\n\t}\n}\n<commit_msg>Add some TODO comments.<commit_after>\/\/ Copyright 2012, 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage deployer\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\n\t\"github.com\/juju\/names\"\n\n\t\"github.com\/juju\/juju\/agent\"\n\t\"github.com\/juju\/juju\/agent\/tools\"\n\t\"github.com\/juju\/juju\/apiserver\/params\"\n\t\"github.com\/juju\/juju\/service\"\n\t\"github.com\/juju\/juju\/service\/common\"\n\t\"github.com\/juju\/juju\/version\"\n)\n\n\/\/ TODO(ericsnow) Use errors.Trace, etc. in this file.\n\n\/\/ TODO(ericsnow) Eliminate InitDir.\n\n\/\/ InitDir is the default upstart init directory.\n\/\/ This is a var so it can be overridden by tests.\nvar InitDir = \"\/etc\/init\"\n\n\/\/ APICalls defines the interface to the API that the simple context needs.\ntype APICalls interface {\n\tConnectionInfo() (params.DeployerConnectionValues, error)\n}\n\n\/\/ SimpleContext is a Context that manages unit deployments on the local system.\ntype SimpleContext struct {\n\n\t\/\/ api is used to get the current state server addresses at the time the\n\t\/\/ given unit is deployed.\n\tapi APICalls\n\n\t\/\/ agentConfig returns the agent config for the machine agent that is\n\t\/\/ running the deployer.\n\tagentConfig agent.Config\n\n\t\/\/ initDir specifies the directory used by init on the local system.\n\t\/\/ For upstart, it is typically set to \"\/etc\/init\".\n\tinitDir string\n\n\t\/\/ discoverService is a surrogate for service.DiscoverService.\n\tdiscoverService func(string, common.Conf) deployerService\n\n\t\/\/ listServices is a surrogate for service.ListServices.\n\tlistServices func(string) ([]string, error)\n}\n\nvar _ Context = (*SimpleContext)(nil)\n\n\/\/ recursiveChmod will change the permissions on all files and\n\/\/ folders inside path\nfunc recursiveChmod(path string, mode os.FileMode) error {\n\twalker := func(p string, fi os.FileInfo, err error) error {\n\t\tif _, err := os.Stat(p); err == nil {\n\t\t\terrPerm := os.Chmod(p, mode)\n\t\t\tif errPerm != nil {\n\t\t\t\treturn errPerm\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tif err := filepath.Walk(path, walker); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ NewSimpleContext returns a new SimpleContext, acting on behalf of\n\/\/ the specified deployer, that deploys unit agents.\n\/\/ Paths to which agents and tools are installed are relative to dataDir.\nfunc NewSimpleContext(agentConfig agent.Config, api APICalls) *SimpleContext {\n\treturn &SimpleContext{\n\t\tapi:         api,\n\t\tagentConfig: agentConfig,\n\t\tinitDir:     InitDir,\n\t\tdiscoverService: func(name string, conf common.Conf) deployerService {\n\t\t\tsvc, _ := service.DiscoverService(name, conf)\n\t\t\treturn svc\n\t\t},\n\t\tlistServices: func(initDir string) ([]string, error) {\n\t\t\treturn service.ListServices(initDir)\n\t\t},\n\t}\n}\n\nfunc (ctx *SimpleContext) AgentConfig() agent.Config {\n\treturn ctx.agentConfig\n}\n\nfunc (ctx *SimpleContext) DeployUnit(unitName, initialPassword string) (err error) {\n\t\/\/ Check sanity.\n\tsvc := ctx.service(unitName)\n\tif svc.Installed() {\n\t\treturn fmt.Errorf(\"unit %q is already deployed\", unitName)\n\t}\n\n\t\/\/ Link the current tools for use by the new agent.\n\ttag := names.NewUnitTag(unitName)\n\tdataDir := ctx.agentConfig.DataDir()\n\tlogDir := ctx.agentConfig.LogDir()\n\t\/\/ TODO(dfc)\n\t_, err = tools.ChangeAgentTools(dataDir, tag.String(), version.Current)\n\t\/\/ TODO(dfc)\n\ttoolsDir := tools.ToolsDir(dataDir, tag.String())\n\tdefer removeOnErr(&err, toolsDir)\n\n\tresult, err := ctx.api.ConnectionInfo()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.Debugf(\"state addresses: %q\", result.StateAddresses)\n\tlogger.Debugf(\"API addresses: %q\", result.APIAddresses)\n\tcontainerType := ctx.agentConfig.Value(agent.ContainerType)\n\tnamespace := ctx.agentConfig.Value(agent.Namespace)\n\tconf, err := agent.NewAgentConfig(\n\t\tagent.AgentConfigParams{\n\t\t\tDataDir:           dataDir,\n\t\t\tLogDir:            logDir,\n\t\t\tUpgradedToVersion: version.Current.Number,\n\t\t\tTag:               tag,\n\t\t\tPassword:          initialPassword,\n\t\t\tNonce:             \"unused\",\n\t\t\tEnvironment:       ctx.agentConfig.Environment(),\n\t\t\t\/\/ TODO: remove the state addresses here and test when api only.\n\t\t\tStateAddresses: result.StateAddresses,\n\t\t\tAPIAddresses:   result.APIAddresses,\n\t\t\tCACert:         ctx.agentConfig.CACert(),\n\t\t\tValues: map[string]string{\n\t\t\t\tagent.ContainerType: containerType,\n\t\t\t\tagent.Namespace:     namespace,\n\t\t\t},\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := conf.Write(); err != nil {\n\t\treturn err\n\t}\n\tdefer removeOnErr(&err, conf.Dir())\n\n\t\/\/ Install an init service that runs the unit agent.\n\tsconf, _ := service.UnitAgentConf(\n\t\tunitName,\n\t\tdataDir,\n\t\tlogDir,\n\t\t\"\",\n\t\tcontainerType,\n\t)\n\tsconf.InitDir = ctx.initDir\n\tsvc.UpdateConfig(sconf)\n\treturn svc.Install()\n}\n\ntype deployerService interface {\n\tUpdateConfig(common.Conf)\n\tInstalled() bool\n\tInstall() error\n\tStopAndRemove() error\n}\n\n\/\/ findUpstartJob tries to find an init system job matching the\n\/\/ given unit name in one of these formats:\n\/\/   jujud-<deployer-tag>:<unit-tag>.conf (for compatibility)\n\/\/   jujud-<unit-tag>.conf (default)\nfunc (ctx *SimpleContext) findInitSystemJob(unitName string) deployerService {\n\tunitsAndJobs, err := ctx.deployedUnitsInitSystemJobs()\n\tif err != nil {\n\t\t\/\/ TODO(ericsnow) Is there a good reason to discard the error\n\t\t\/\/ like this?\n\t\treturn nil\n\t}\n\tif job, ok := unitsAndJobs[unitName]; ok {\n\t\treturn ctx.discoverService(job, common.Conf{InitDir: ctx.initDir})\n\t}\n\treturn nil\n}\n\nfunc (ctx *SimpleContext) RecallUnit(unitName string) error {\n\tsvc := ctx.findInitSystemJob(unitName)\n\tif svc == nil || !svc.Installed() {\n\t\treturn fmt.Errorf(\"unit %q is not deployed\", unitName)\n\t}\n\tif err := svc.StopAndRemove(); err != nil {\n\t\treturn err\n\t}\n\ttag := names.NewUnitTag(unitName)\n\tdataDir := ctx.agentConfig.DataDir()\n\tagentDir := agent.Dir(dataDir, tag)\n\t\/\/ Recursivley change mode to 777 on windows to avoid\n\t\/\/ Operation not permitted errors when deleting the agentDir\n\terr := recursiveChmod(agentDir, os.FileMode(0777))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := os.RemoveAll(agentDir); err != nil {\n\t\treturn err\n\t}\n\t\/\/ TODO(dfc) should take a Tag\n\ttoolsDir := tools.ToolsDir(dataDir, tag.String())\n\treturn os.Remove(toolsDir)\n}\n\nvar deployedRe = regexp.MustCompile(\"^(jujud-.*unit-([a-z0-9-]+)-([0-9]+))$\")\n\nfunc (ctx *SimpleContext) deployedUnitsInitSystemJobs() (map[string]string, error) {\n\tfis, err := ctx.listServices(ctx.initDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinstalled := make(map[string]string)\n\tfor _, fi := range fis {\n\t\tif groups := deployedRe.FindStringSubmatch(fi); len(groups) > 0 {\n\t\t\tunitName := groups[2] + \"\/\" + groups[3]\n\t\t\tif !names.IsValidUnit(unitName) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tinstalled[unitName] = groups[1]\n\t\t}\n\t}\n\treturn installed, nil\n}\n\nfunc (ctx *SimpleContext) DeployedUnits() ([]string, error) {\n\tunitsAndJobs, err := ctx.deployedUnitsInitSystemJobs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar installed []string\n\tfor unitName := range unitsAndJobs {\n\t\tinstalled = append(installed, unitName)\n\t}\n\treturn installed, nil\n}\n\n\/\/ service returns a service.Service corresponding to the specified\n\/\/ unit.\nfunc (ctx *SimpleContext) service(unitName string) deployerService {\n\ttag := names.NewUnitTag(unitName).String()\n\tsvcName := \"jujud-\" + tag\n\treturn ctx.discoverService(svcName, common.Conf{InitDir: ctx.initDir})\n}\n\nfunc removeOnErr(err *error, path string) {\n\tif *err != nil {\n\t\tif err := os.Remove(path); err != nil {\n\t\t\tlogger.Warningf(\"installer: cannot remove %q: %v\", path, err)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package catalog defines collections of translated format strings.\n\/\/\n\/\/ This package mostly defines types for populating catalogs with messages. The\n\/\/ catmsg package contains further definitions for creating custom message and\n\/\/ dictionary types as well as packages that use Catalogs.\n\/\/\n\/\/ Package catalog defines various interfaces: Dictionary, Loader, and Message.\n\/\/ A Dictionary maintains a set of translations of format strings for a single\n\/\/ language. The Loader interface defines a source of dictionaries. A\n\/\/ translation of a format string is represented by a Message.\n\/\/\n\/\/\n\/\/ Catalogs\n\/\/\n\/\/ A Catalog defines a programmatic interface for setting message translations.\n\/\/ It maintains a set of per-language dictionaries with translations for a set\n\/\/ of keys. For message translation to function properly, a translation should\n\/\/ be defined for each key for each supported language. A dictionary may be\n\/\/ underspecified, though, if there is a parent language that already defines\n\/\/ the key. For example, a Dictionary for \"en-GB\" could leave out entries that\n\/\/ are identical to those in a dictionary for \"en\".\n\/\/\n\/\/\n\/\/ Messages\n\/\/\n\/\/ A Message is a format string which varies on the value of substitution\n\/\/ variables. For instance, to indicate the number of results one could want \"no\n\/\/ results\" if there are none, \"1 result\" if there is 1, and \"%d results\" for\n\/\/ any other number. Catalog is agnostic to the kind of format strings that are\n\/\/ used: for instance, messages can follow either the printf-style substitution\n\/\/ from package fmt or use templates.\n\/\/\n\/\/ A Message does not substitute arguments in the format string. This job is\n\/\/ reserved for packages that render strings, such as message, that use Catalogs\n\/\/ to selected string. This separation of concerns allows Catalog to be used to\n\/\/ store any kind of formatting strings.\n\/\/\n\/\/\n\/\/ Selecting messages based on linguistic features of substitution arguments\n\/\/\n\/\/ Messages may vary based on any linguistic features of the argument values.\n\/\/ The most common one is plural form, but others exist.\n\/\/\n\/\/ Selection messages are provided in packages that provide support for a\n\/\/ specific linguistic feature. The following snippet uses plural.Select:\n\/\/\n\/\/   catalog.Set(language.English, \"You are %d minute(s) late.\",\n\/\/       plural.Select(1,\n\/\/           \"one\", \"You are 1 minute late.\",\n\/\/           \"other\", \"You are %d minutes late.\"))\n\/\/\n\/\/ In this example, a message is stored in the Catalog where one of two messages\n\/\/ is selected based on the first argument, a number. The first message is\n\/\/ selected if the argument is singular (identified by the selector \"one\") and\n\/\/ the second message is selected in all other cases. The selectors are defined\n\/\/ by the plural rules defined in CLDR. The selector \"other\" is special and will\n\/\/ always match. Each language always defines one of the linguistic categories\n\/\/ to be \"other.\" For English, singular is \"one\" and plural is \"other\".\n\/\/\n\/\/ Selects can be nested. This allows selecting sentences based on features of\n\/\/ multiple arguments or multiple linguistic properties of a single argument.\n\/\/\n\/\/\n\/\/ String interpolation\n\/\/\n\/\/ There is often a lot of commonality between the possible variants of a\n\/\/ message. For instance, in the example above the word \"minute\" varies based on\n\/\/ the plural catogory of the argument, but the rest of the sentence is\n\/\/ identical. Using interpolation the above message can be rewritten as:\n\/\/\n\/\/   catalog.Set(language.English, \"You are %d minute(s) late.\",\n\/\/       catalog.Var(\"minutes\",\n\/\/           plural.Select(1, \"one\", \"minute\", \"other\", \"minutes\")),\n\/\/       catalog.String(\"You are %[1]d ${minutes} late.\"))\n\/\/\n\/\/ Var is defined to return the variable name if the message does not yield a\n\/\/ match. This allows us to further simplify this snippet to\n\/\/\n\/\/   catalog.Set(language.English, \"You are %d minute(s) late.\",\n\/\/       catalog.Var(\"minutes\", plural.Select(1, \"one\", \"minute\")),\n\/\/       catalog.String(\"You are %d ${minutes} late.\"))\n\/\/\n\/\/ Overall this is still only a minor improvement, but things can get a lot more\n\/\/ unwieldy if more than one linguistic feature is used to determine a message\n\/\/ variant. Consider the following example:\n\/\/\n\/\/   \/\/ argument 1: list of hosts, argument 2: list of guests\n\/\/   catalog.Set(language.English, \"%[1]v invite(s) %[2]v to their party.\",\n\/\/     catalog.Var(\"their\",\n\/\/         plural.Select(1,\n\/\/             \"one\", gender.Select(1, \"female\", \"her\", \"other\", \"his\"))),\n\/\/     catalog.Var(\"invites\", plural.Select(1, \"one\", \"invite\"))\n\/\/     catalog.String(\"%[1]v ${invites} %[2]v to ${their} party.\")),\n\/\/\n\/\/ Without variable substitution, this would have to be written as\n\/\/\n\/\/   \/\/ argument 1: list of hosts, argument 2: list of guests\n\/\/   catalog.Set(language.English, \"%[1]v invite(s) %[2]v to their party.\",\n\/\/     plural.Select(1,\n\/\/         \"one\", gender.Select(1,\n\/\/             \"female\", \"%[1]v invites %[2]v to her party.\"\n\/\/             \"other\", \"%[1]v invites %[2]v to his party.\"),\n\/\/         \"other\", \"%[1]v invites %[2]v to their party.\")\n\/\/\n\/\/ Not necessarily shorter, but using variables there is less duplication and\n\/\/ the messages are more maintenance friendly. Moreover, languages may have up\n\/\/ to six plural forms. This makes the use of variables more welcome.\n\/\/\n\/\/ Different messages using the same inflections can reuse variables by moving\n\/\/ them to macros. Using macros we can rewrite the message as:\n\/\/\n\/\/   \/\/ argument 1: list of hosts, argument 2: list of guests\n\/\/   catalog.SetString(language.English, \"%[1]v invite(s) %[2]v to their party.\",\n\/\/       \"%[1]v ${invites(1)} %[2]v to ${their(1)} party.\")\n\/\/\n\/\/ Where the following macros were defined separately.\n\/\/\n\/\/   catalog.SetMacro(language.English, \"invites\", plural.Select(1, \"one\", \"invite\"))\n\/\/   catalog.SetMacro(language.English, \"their\", plural.Select(1,\n\/\/      \"one\", gender.Select(1, \"female\", \"her\", \"other\", \"his\"))),\n\/\/\n\/\/ Placeholders use parentheses and the arguments to invoke a macro.\n\/\/\n\/\/\n\/\/ Looking up messages\n\/\/\n\/\/ Message lookup using Catalogs is typically only done by specialized packages\n\/\/ and is not something the user should be concerned with. For instance, to\n\/\/ express the tardiness of a user using the related message we defined earlier,\n\/\/ the user may use the package message like so:\n\/\/\n\/\/   p := message.NewPrinter(language.English)\n\/\/   p.Printf(\"You are %d minute(s) late.\", 5)\n\/\/\n\/\/ Which would print:\n\/\/   You are 5 minutes late.\n\/\/\n\/\/\n\/\/ This package is UNDER CONSTRUCTION and its API may change.\npackage catalog \/\/ import \"golang.org\/x\/text\/message\/catalog\"\n\n\/\/ TODO:\n\/\/ Some way to freeze a catalog.\n\/\/ - Locking on each lockup turns out to be about 50% of the total running time\n\/\/   for some of the benchmarks in the message package.\n\/\/ Consider these:\n\/\/ - Sequence type to support sequences in user-defined messages.\n\/\/ - Garbage collection: Remove dictionaries that can no longer be reached\n\/\/   as other dictionaries have been added that cover all possible keys.\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"golang.org\/x\/text\/internal\"\n\n\t\"golang.org\/x\/text\/internal\/catmsg\"\n\t\"golang.org\/x\/text\/language\"\n)\n\n\/\/ A Catalog allows lookup of translated messages.\ntype Catalog interface {\n\t\/\/ Languages returns all languages for which the Catalog contains variants.\n\tLanguages() []language.Tag\n\n\t\/\/ Matcher returns a Matcher for languages from this Catalog.\n\tMatcher() language.Matcher\n\n\t\/\/ A Context is used for evaluating Messages.\n\tContext(tag language.Tag, r catmsg.Renderer) *Context\n\n\t\/\/ This method also makes Catalog a private interface.\n\tlookup(tag language.Tag, key string) (data string, ok bool)\n}\n\n\/\/ NewFromMap creates a Catalog from the given map. If a Dictionary is\n\/\/ underspecified the entry is retrieved from a parent language.\nfunc NewFromMap(dictionaries map[string]Dictionary, opts ...Option) (Catalog, error) {\n\toptions := options{}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\tc := &catalog{\n\t\tdicts: map[language.Tag]Dictionary{},\n\t}\n\t_, hasFallback := dictionaries[options.fallback.String()]\n\tif hasFallback {\n\t\t\/\/ TODO: Should it be okay to not have a fallback language?\n\t\t\/\/ Catalog generators could enforce there is always a fallback.\n\t\tc.langs = append(c.langs, options.fallback)\n\t}\n\tfor lang, dict := range dictionaries {\n\t\ttag, err := language.Parse(lang)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"catalog: invalid language tag %q\", lang)\n\t\t}\n\t\tif _, ok := c.dicts[tag]; ok {\n\t\t\treturn nil, fmt.Errorf(\"catalog: duplicate entry for tag %q after normalization\", tag)\n\t\t}\n\t\tc.dicts[tag] = dict\n\t\tif !hasFallback || tag != options.fallback {\n\t\t\tc.langs = append(c.langs, tag)\n\t\t}\n\t}\n\tif hasFallback {\n\t\tinternal.SortTags(c.langs[1:])\n\t} else {\n\t\tinternal.SortTags(c.langs)\n\t}\n\tc.matcher = language.NewMatcher(c.langs)\n\treturn c, nil\n}\n\n\/\/ A Dictionary is a source of translations for a single language.\ntype Dictionary interface {\n\t\/\/ Lookup returns a message compiled with catmsg.Compile for the given key.\n\t\/\/ It returns false for ok if such a message could not be found.\n\tLookup(key string) (data string, ok bool)\n}\n\ntype catalog struct {\n\tlangs   []language.Tag\n\tdicts   map[language.Tag]Dictionary\n\tmacros  store\n\tmatcher language.Matcher\n}\n\nfunc (c *catalog) Languages() []language.Tag { return c.langs }\nfunc (c *catalog) Matcher() language.Matcher { return c.matcher }\n\nfunc (c *catalog) lookup(tag language.Tag, key string) (data string, ok bool) {\n\tfor ; ; tag = tag.Parent() {\n\t\tif dict, ok := c.dicts[tag]; ok {\n\t\t\tif data, ok := dict.Lookup(key); ok {\n\t\t\t\treturn data, true\n\t\t\t}\n\t\t}\n\t\tif tag == language.Und {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn \"\", false\n}\n\n\/\/ Context returns a Context for formatting messages.\n\/\/ Only one Message may be formatted per context at any given time.\nfunc (c *catalog) Context(tag language.Tag, r catmsg.Renderer) *Context {\n\treturn &Context{\n\t\tcat: c,\n\t\ttag: tag,\n\t\tdec: catmsg.NewDecoder(tag, r, &dict{&c.macros, tag}),\n\t}\n}\n\n\/\/ A Builder allows building a Catalog programmatically.\ntype Builder struct {\n\toptions\n\tmatcher language.Matcher\n\n\tindex  store\n\tmacros store\n}\n\ntype options struct {\n\tfallback language.Tag\n}\n\n\/\/ An Option configures Catalog behavior.\ntype Option func(*options)\n\n\/\/ Fallback specifies the default fallback language. The default is Und.\nfunc Fallback(tag language.Tag) Option {\n\treturn func(o *options) { o.fallback = tag }\n}\n\n\/\/ TODO:\n\/\/ \/\/ Catalogs specifies one or more sources for a Catalog.\n\/\/ \/\/ Lookups are in order.\n\/\/ \/\/ This can be changed inserting a Catalog used for setting, which implements\n\/\/ \/\/ Loader, used for setting in the chain.\n\/\/ func Catalogs(d ...Loader) Option {\n\/\/ \treturn nil\n\/\/ }\n\/\/\n\/\/ func Delims(start, end string) Option {}\n\/\/\n\/\/ func Dict(tag language.Tag, d ...Dictionary) Option\n\n\/\/ NewBuilder returns an empty mutable Catalog.\nfunc NewBuilder(opts ...Option) *Builder {\n\tc := &Builder{}\n\tfor _, o := range opts {\n\t\to(&c.options)\n\t}\n\treturn c\n}\n\n\/\/ SetString is shorthand for Set(tag, key, String(msg)).\nfunc (c *Builder) SetString(tag language.Tag, key string, msg string) error {\n\treturn c.set(tag, key, &c.index, String(msg))\n}\n\n\/\/ Set sets the translation for the given language and key.\n\/\/\n\/\/ When evaluation this message, the first Message in the sequence to msgs to\n\/\/ evaluate to a string will be the message returned.\nfunc (c *Builder) Set(tag language.Tag, key string, msg ...Message) error {\n\treturn c.set(tag, key, &c.index, msg...)\n}\n\n\/\/ SetMacro defines a Message that may be substituted in another message.\n\/\/ The arguments to a macro Message are passed as arguments in the\n\/\/ placeholder the form \"${foo(arg1, arg2)}\".\nfunc (c *Builder) SetMacro(tag language.Tag, name string, msg ...Message) error {\n\treturn c.set(tag, name, &c.macros, msg...)\n}\n\n\/\/ ErrNotFound indicates there was no message for the given key.\nvar ErrNotFound = errors.New(\"catalog: message not found\")\n\n\/\/ String specifies a plain message string. It can be used as fallback if no\n\/\/ other strings match or as a simple standalone message.\n\/\/\n\/\/ It is an error to pass more than one String in a message sequence.\nfunc String(name string) Message {\n\treturn catmsg.String(name)\n}\n\n\/\/ Var sets a variable that may be substituted in formatting patterns using\n\/\/ named substitution of the form \"${name}\". The name argument is used as a\n\/\/ fallback if the statements do not produce a match. The statement sequence may\n\/\/ not contain any Var calls.\n\/\/\n\/\/ The name passed to a Var must be unique within message sequence.\nfunc Var(name string, msg ...Message) Message {\n\treturn &catmsg.Var{Name: name, Message: firstInSequence(msg)}\n}\n\n\/\/ Context returns a Context for formatting messages.\n\/\/ Only one Message may be formatted per context at any given time.\nfunc (b *Builder) Context(tag language.Tag, r catmsg.Renderer) *Context {\n\treturn &Context{\n\t\tcat: b,\n\t\ttag: tag,\n\t\tdec: catmsg.NewDecoder(tag, r, &dict{&b.macros, tag}),\n\t}\n}\n\n\/\/ A Context is used for evaluating Messages.\n\/\/ Only one Message may be formatted per context at any given time.\ntype Context struct {\n\tcat Catalog\n\ttag language.Tag \/\/ TODO: use compact index.\n\tdec *catmsg.Decoder\n}\n\n\/\/ Execute looks up and executes the message with the given key.\n\/\/ It returns ErrNotFound if no message could be found in the index.\nfunc (c *Context) Execute(key string) error {\n\tdata, ok := c.cat.lookup(c.tag, key)\n\tif !ok {\n\t\treturn ErrNotFound\n\t}\n\treturn c.dec.Execute(data)\n}\n<commit_msg>message\/catalog: fix usage of plural in docs<commit_after>\/\/ Copyright 2017 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package catalog defines collections of translated format strings.\n\/\/\n\/\/ This package mostly defines types for populating catalogs with messages. The\n\/\/ catmsg package contains further definitions for creating custom message and\n\/\/ dictionary types as well as packages that use Catalogs.\n\/\/\n\/\/ Package catalog defines various interfaces: Dictionary, Loader, and Message.\n\/\/ A Dictionary maintains a set of translations of format strings for a single\n\/\/ language. The Loader interface defines a source of dictionaries. A\n\/\/ translation of a format string is represented by a Message.\n\/\/\n\/\/\n\/\/ Catalogs\n\/\/\n\/\/ A Catalog defines a programmatic interface for setting message translations.\n\/\/ It maintains a set of per-language dictionaries with translations for a set\n\/\/ of keys. For message translation to function properly, a translation should\n\/\/ be defined for each key for each supported language. A dictionary may be\n\/\/ underspecified, though, if there is a parent language that already defines\n\/\/ the key. For example, a Dictionary for \"en-GB\" could leave out entries that\n\/\/ are identical to those in a dictionary for \"en\".\n\/\/\n\/\/\n\/\/ Messages\n\/\/\n\/\/ A Message is a format string which varies on the value of substitution\n\/\/ variables. For instance, to indicate the number of results one could want \"no\n\/\/ results\" if there are none, \"1 result\" if there is 1, and \"%d results\" for\n\/\/ any other number. Catalog is agnostic to the kind of format strings that are\n\/\/ used: for instance, messages can follow either the printf-style substitution\n\/\/ from package fmt or use templates.\n\/\/\n\/\/ A Message does not substitute arguments in the format string. This job is\n\/\/ reserved for packages that render strings, such as message, that use Catalogs\n\/\/ to selected string. This separation of concerns allows Catalog to be used to\n\/\/ store any kind of formatting strings.\n\/\/\n\/\/\n\/\/ Selecting messages based on linguistic features of substitution arguments\n\/\/\n\/\/ Messages may vary based on any linguistic features of the argument values.\n\/\/ The most common one is plural form, but others exist.\n\/\/\n\/\/ Selection messages are provided in packages that provide support for a\n\/\/ specific linguistic feature. The following snippet uses plural.Selectf:\n\/\/\n\/\/   catalog.Set(language.English, \"You are %d minute(s) late.\",\n\/\/       plural.Selectf(1, \"\",\n\/\/           plural.One, \"You are 1 minute late.\",\n\/\/           plural.Other, \"You are %d minutes late.\"))\n\/\/\n\/\/ In this example, a message is stored in the Catalog where one of two messages\n\/\/ is selected based on the first argument, a number. The first message is\n\/\/ selected if the argument is singular (identified by the selector \"one\") and\n\/\/ the second message is selected in all other cases. The selectors are defined\n\/\/ by the plural rules defined in CLDR. The selector \"other\" is special and will\n\/\/ always match. Each language always defines one of the linguistic categories\n\/\/ to be \"other.\" For English, singular is \"one\" and plural is \"other\".\n\/\/\n\/\/ Selects can be nested. This allows selecting sentences based on features of\n\/\/ multiple arguments or multiple linguistic properties of a single argument.\n\/\/\n\/\/\n\/\/ String interpolation\n\/\/\n\/\/ There is often a lot of commonality between the possible variants of a\n\/\/ message. For instance, in the example above the word \"minute\" varies based on\n\/\/ the plural catogory of the argument, but the rest of the sentence is\n\/\/ identical. Using interpolation the above message can be rewritten as:\n\/\/\n\/\/   catalog.Set(language.English, \"You are %d minute(s) late.\",\n\/\/       catalog.Var(\"minutes\",\n\/\/           plural.Selectf(1, \"\", plural.One, \"minute\", plural.Other, \"minutes\")),\n\/\/       catalog.String(\"You are %[1]d ${minutes} late.\"))\n\/\/\n\/\/ Var is defined to return the variable name if the message does not yield a\n\/\/ match. This allows us to further simplify this snippet to\n\/\/\n\/\/   catalog.Set(language.English, \"You are %d minute(s) late.\",\n\/\/       catalog.Var(\"minutes\", plural.Selectf(1, \"\", plural.One, \"minute\")),\n\/\/       catalog.String(\"You are %d ${minutes} late.\"))\n\/\/\n\/\/ Overall this is still only a minor improvement, but things can get a lot more\n\/\/ unwieldy if more than one linguistic feature is used to determine a message\n\/\/ variant. Consider the following example:\n\/\/\n\/\/   \/\/ argument 1: list of hosts, argument 2: list of guests\n\/\/   catalog.Set(language.English, \"%[1]v invite(s) %[2]v to their party.\",\n\/\/     catalog.Var(\"their\",\n\/\/         plural.Selectf(1, \"\"\n\/\/             plural.One, gender.Select(1, \"female\", \"her\", \"other\", \"his\"))),\n\/\/     catalog.Var(\"invites\", plural.Selectf(1, \"\", plural.One, \"invite\"))\n\/\/     catalog.String(\"%[1]v ${invites} %[2]v to ${their} party.\")),\n\/\/\n\/\/ Without variable substitution, this would have to be written as\n\/\/\n\/\/   \/\/ argument 1: list of hosts, argument 2: list of guests\n\/\/   catalog.Set(language.English, \"%[1]v invite(s) %[2]v to their party.\",\n\/\/     plural.Selectf(1, \"\",\n\/\/         plural.One, gender.Select(1,\n\/\/             \"female\", \"%[1]v invites %[2]v to her party.\"\n\/\/             \"other\", \"%[1]v invites %[2]v to his party.\"),\n\/\/         plural.Other, \"%[1]v invites %[2]v to their party.\")\n\/\/\n\/\/ Not necessarily shorter, but using variables there is less duplication and\n\/\/ the messages are more maintenance friendly. Moreover, languages may have up\n\/\/ to six plural forms. This makes the use of variables more welcome.\n\/\/\n\/\/ Different messages using the same inflections can reuse variables by moving\n\/\/ them to macros. Using macros we can rewrite the message as:\n\/\/\n\/\/   \/\/ argument 1: list of hosts, argument 2: list of guests\n\/\/   catalog.SetString(language.English, \"%[1]v invite(s) %[2]v to their party.\",\n\/\/       \"%[1]v ${invites(1)} %[2]v to ${their(1)} party.\")\n\/\/\n\/\/ Where the following macros were defined separately.\n\/\/\n\/\/   catalog.SetMacro(language.English, \"invites\", plural.Selectf(1, \"\",\n\/\/      plural.One, \"invite\"))\n\/\/   catalog.SetMacro(language.English, \"their\", plural.Selectf(1, \"\",\n\/\/      plural.One, gender.Select(1, \"female\", \"her\", \"other\", \"his\"))),\n\/\/\n\/\/ Placeholders use parentheses and the arguments to invoke a macro.\n\/\/\n\/\/\n\/\/ Looking up messages\n\/\/\n\/\/ Message lookup using Catalogs is typically only done by specialized packages\n\/\/ and is not something the user should be concerned with. For instance, to\n\/\/ express the tardiness of a user using the related message we defined earlier,\n\/\/ the user may use the package message like so:\n\/\/\n\/\/   p := message.NewPrinter(language.English)\n\/\/   p.Printf(\"You are %d minute(s) late.\", 5)\n\/\/\n\/\/ Which would print:\n\/\/   You are 5 minutes late.\n\/\/\n\/\/\n\/\/ This package is UNDER CONSTRUCTION and its API may change.\npackage catalog \/\/ import \"golang.org\/x\/text\/message\/catalog\"\n\n\/\/ TODO:\n\/\/ Some way to freeze a catalog.\n\/\/ - Locking on each lockup turns out to be about 50% of the total running time\n\/\/   for some of the benchmarks in the message package.\n\/\/ Consider these:\n\/\/ - Sequence type to support sequences in user-defined messages.\n\/\/ - Garbage collection: Remove dictionaries that can no longer be reached\n\/\/   as other dictionaries have been added that cover all possible keys.\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"golang.org\/x\/text\/internal\"\n\n\t\"golang.org\/x\/text\/internal\/catmsg\"\n\t\"golang.org\/x\/text\/language\"\n)\n\n\/\/ A Catalog allows lookup of translated messages.\ntype Catalog interface {\n\t\/\/ Languages returns all languages for which the Catalog contains variants.\n\tLanguages() []language.Tag\n\n\t\/\/ Matcher returns a Matcher for languages from this Catalog.\n\tMatcher() language.Matcher\n\n\t\/\/ A Context is used for evaluating Messages.\n\tContext(tag language.Tag, r catmsg.Renderer) *Context\n\n\t\/\/ This method also makes Catalog a private interface.\n\tlookup(tag language.Tag, key string) (data string, ok bool)\n}\n\n\/\/ NewFromMap creates a Catalog from the given map. If a Dictionary is\n\/\/ underspecified the entry is retrieved from a parent language.\nfunc NewFromMap(dictionaries map[string]Dictionary, opts ...Option) (Catalog, error) {\n\toptions := options{}\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\tc := &catalog{\n\t\tdicts: map[language.Tag]Dictionary{},\n\t}\n\t_, hasFallback := dictionaries[options.fallback.String()]\n\tif hasFallback {\n\t\t\/\/ TODO: Should it be okay to not have a fallback language?\n\t\t\/\/ Catalog generators could enforce there is always a fallback.\n\t\tc.langs = append(c.langs, options.fallback)\n\t}\n\tfor lang, dict := range dictionaries {\n\t\ttag, err := language.Parse(lang)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"catalog: invalid language tag %q\", lang)\n\t\t}\n\t\tif _, ok := c.dicts[tag]; ok {\n\t\t\treturn nil, fmt.Errorf(\"catalog: duplicate entry for tag %q after normalization\", tag)\n\t\t}\n\t\tc.dicts[tag] = dict\n\t\tif !hasFallback || tag != options.fallback {\n\t\t\tc.langs = append(c.langs, tag)\n\t\t}\n\t}\n\tif hasFallback {\n\t\tinternal.SortTags(c.langs[1:])\n\t} else {\n\t\tinternal.SortTags(c.langs)\n\t}\n\tc.matcher = language.NewMatcher(c.langs)\n\treturn c, nil\n}\n\n\/\/ A Dictionary is a source of translations for a single language.\ntype Dictionary interface {\n\t\/\/ Lookup returns a message compiled with catmsg.Compile for the given key.\n\t\/\/ It returns false for ok if such a message could not be found.\n\tLookup(key string) (data string, ok bool)\n}\n\ntype catalog struct {\n\tlangs   []language.Tag\n\tdicts   map[language.Tag]Dictionary\n\tmacros  store\n\tmatcher language.Matcher\n}\n\nfunc (c *catalog) Languages() []language.Tag { return c.langs }\nfunc (c *catalog) Matcher() language.Matcher { return c.matcher }\n\nfunc (c *catalog) lookup(tag language.Tag, key string) (data string, ok bool) {\n\tfor ; ; tag = tag.Parent() {\n\t\tif dict, ok := c.dicts[tag]; ok {\n\t\t\tif data, ok := dict.Lookup(key); ok {\n\t\t\t\treturn data, true\n\t\t\t}\n\t\t}\n\t\tif tag == language.Und {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn \"\", false\n}\n\n\/\/ Context returns a Context for formatting messages.\n\/\/ Only one Message may be formatted per context at any given time.\nfunc (c *catalog) Context(tag language.Tag, r catmsg.Renderer) *Context {\n\treturn &Context{\n\t\tcat: c,\n\t\ttag: tag,\n\t\tdec: catmsg.NewDecoder(tag, r, &dict{&c.macros, tag}),\n\t}\n}\n\n\/\/ A Builder allows building a Catalog programmatically.\ntype Builder struct {\n\toptions\n\tmatcher language.Matcher\n\n\tindex  store\n\tmacros store\n}\n\ntype options struct {\n\tfallback language.Tag\n}\n\n\/\/ An Option configures Catalog behavior.\ntype Option func(*options)\n\n\/\/ Fallback specifies the default fallback language. The default is Und.\nfunc Fallback(tag language.Tag) Option {\n\treturn func(o *options) { o.fallback = tag }\n}\n\n\/\/ TODO:\n\/\/ \/\/ Catalogs specifies one or more sources for a Catalog.\n\/\/ \/\/ Lookups are in order.\n\/\/ \/\/ This can be changed inserting a Catalog used for setting, which implements\n\/\/ \/\/ Loader, used for setting in the chain.\n\/\/ func Catalogs(d ...Loader) Option {\n\/\/ \treturn nil\n\/\/ }\n\/\/\n\/\/ func Delims(start, end string) Option {}\n\/\/\n\/\/ func Dict(tag language.Tag, d ...Dictionary) Option\n\n\/\/ NewBuilder returns an empty mutable Catalog.\nfunc NewBuilder(opts ...Option) *Builder {\n\tc := &Builder{}\n\tfor _, o := range opts {\n\t\to(&c.options)\n\t}\n\treturn c\n}\n\n\/\/ SetString is shorthand for Set(tag, key, String(msg)).\nfunc (c *Builder) SetString(tag language.Tag, key string, msg string) error {\n\treturn c.set(tag, key, &c.index, String(msg))\n}\n\n\/\/ Set sets the translation for the given language and key.\n\/\/\n\/\/ When evaluation this message, the first Message in the sequence to msgs to\n\/\/ evaluate to a string will be the message returned.\nfunc (c *Builder) Set(tag language.Tag, key string, msg ...Message) error {\n\treturn c.set(tag, key, &c.index, msg...)\n}\n\n\/\/ SetMacro defines a Message that may be substituted in another message.\n\/\/ The arguments to a macro Message are passed as arguments in the\n\/\/ placeholder the form \"${foo(arg1, arg2)}\".\nfunc (c *Builder) SetMacro(tag language.Tag, name string, msg ...Message) error {\n\treturn c.set(tag, name, &c.macros, msg...)\n}\n\n\/\/ ErrNotFound indicates there was no message for the given key.\nvar ErrNotFound = errors.New(\"catalog: message not found\")\n\n\/\/ String specifies a plain message string. It can be used as fallback if no\n\/\/ other strings match or as a simple standalone message.\n\/\/\n\/\/ It is an error to pass more than one String in a message sequence.\nfunc String(name string) Message {\n\treturn catmsg.String(name)\n}\n\n\/\/ Var sets a variable that may be substituted in formatting patterns using\n\/\/ named substitution of the form \"${name}\". The name argument is used as a\n\/\/ fallback if the statements do not produce a match. The statement sequence may\n\/\/ not contain any Var calls.\n\/\/\n\/\/ The name passed to a Var must be unique within message sequence.\nfunc Var(name string, msg ...Message) Message {\n\treturn &catmsg.Var{Name: name, Message: firstInSequence(msg)}\n}\n\n\/\/ Context returns a Context for formatting messages.\n\/\/ Only one Message may be formatted per context at any given time.\nfunc (b *Builder) Context(tag language.Tag, r catmsg.Renderer) *Context {\n\treturn &Context{\n\t\tcat: b,\n\t\ttag: tag,\n\t\tdec: catmsg.NewDecoder(tag, r, &dict{&b.macros, tag}),\n\t}\n}\n\n\/\/ A Context is used for evaluating Messages.\n\/\/ Only one Message may be formatted per context at any given time.\ntype Context struct {\n\tcat Catalog\n\ttag language.Tag \/\/ TODO: use compact index.\n\tdec *catmsg.Decoder\n}\n\n\/\/ Execute looks up and executes the message with the given key.\n\/\/ It returns ErrNotFound if no message could be found in the index.\nfunc (c *Context) Execute(key string) error {\n\tdata, ok := c.cat.lookup(c.tag, key)\n\tif !ok {\n\t\treturn ErrNotFound\n\t}\n\treturn c.dec.Execute(data)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build OMIT\n\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar z []int\n\tfmt.Println(z, len(z), cap(z))\n\tif z == nil {\n\t\tfmt.Println(\"nil!\")\n\t}\n}\n<commit_msg>content: rename variable in nil slices example<commit_after>\/\/ +build OMIT\n\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar s []int\n\tfmt.Println(s, len(s), cap(s))\n\tif s == nil {\n\t\tfmt.Println(\"nil!\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* Copyright (c) 2016 Thomas Findelkind\n#\n# This program is free software: you can redistribute it and\/or modify it under\n# the terms of the GNU General Public License as published by the Free Software\n# Foundation, either version 3 of the License, or (at your option) any later\n# version.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more\n# details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n#\n# MORE ABOUT THIS SCRIPT AVAILABLE IN THE README AND AT:\n#\n# http:\/\/tfindelkind.com\n#\n# ----------------------------------------------------------------------------\n*\/\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\tntnxAPI \"github.com\/Tfindelkind\/acropolis-sdk-go\"\n)\n\nconst appVersion = \"0.9 beta\"\n\nvar (\n\thost       *string\n\tusername   *string\n\tpassword   *string\n\tcontainer  *string\n\tmountpoint *string\n\twhitelist  *string\n\tdebug      *bool\n\thelp       *bool\n\tversion    *bool\n)\n\nfunc init() {\n\thost = flag.String(\"host\", \"\", \"a string\")\n\tusername = flag.String(\"username\", \"\", \"a string\")\n\tpassword = flag.String(\"password\", \"\", \"a string\")\n\tcontainer = flag.String(\"container\", \"\", \"a string\")\n\tmountpoint = flag.String(\"mountpoint\", \"\", \"a string\")\n\twhitelist = flag.String(\"whitelist\", \"\", \"a string\")\n\tdebug = flag.Bool(\"debug\", false, \"a bool\")\n\thelp = flag.Bool(\"help\", false, \"a bool\")\n\tversion = flag.Bool(\"version\", false, \"a bool\")\n}\n\nfunc printHelp() {\n\n\tfmt.Println(\"Usage: mount_nfs [OPTIONS]\")\n\tfmt.Println(\"mount_nfs [ --help | --version ]\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"FOR NUTANIX AHV ONLY- exports an AHV VM\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"Options:\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"--host             Specify CVM host or Cluster IP\")\n\tfmt.Println(\"--username         Specify username for connect to host\")\n\tfmt.Println(\"--password         Specify password for user\")\n\tfmt.Println(\"--container        Specify the container to mount - Default mount all\")\n\tfmt.Println(\"--mountpoint       (Optional) the mount point like ´\/mount\/´ WITH tailing \/\")\n\tfmt.Println(\"--whitelist\t\t    (Optional) nnn.nnn.nnn.nnn\/xxx.xxx.xxx.xxx\")\n\tfmt.Println(\"           \t\t    where nnn is the IP address, and xxx is the subnet mask.\")\n\tfmt.Println(\"--debug            Enables debug mode\")\n\tfmt.Println(\"--help             List this help\")\n\tfmt.Println(\"--version          Show the deploy_cloud_vm version\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"Example:\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"mount_nfs --host=NTNX-CVM --username=admin --password=nutanix\/4u\")\n\tfmt.Println(\"\")\n}\n\nfunc evaluateFlags() ntnxAPI.NTNXConnection {\n\n\t\/\/help\n\tif *help {\n\t\tprintHelp()\n\t\tos.Exit(0)\n\t}\n\n\t\/\/version\n\tif *version {\n\t\tfmt.Println(\"Version: \" + appVersion)\n\t\tos.Exit(0)\n\t}\n\n\t\/\/debug\n\tif *debug {\n\t\tlog.SetLevel(log.DebugLevel)\n\t} else {\n\t\tlog.SetLevel(log.InfoLevel)\n\t}\n\n\t\/\/host\n\tif *host == \"\" {\n\t\tlog.Warn(\"mandatory option '--host=' is not set\")\n\t\tos.Exit(0)\n\t}\n\n\t\/\/username\n\tif *username == \"\" {\n\t\tlog.Warn(\"option '--username=' is not set  Default: admin is used\")\n\t\t*username = \"admin\"\n\t}\n\n\t\/\/password\n\tif *password == \"\" {\n\t\tlog.Warn(\"option '--password=' is not set  Default: nutanix\/4u is used\")\n\t\t*password = \"nutanix\/4u\"\n\t}\n\n\t\/\/container\n\tif *container == \"\" {\n\t\tlog.Warn(\"option '--container=' is not set  Default: mounting all\")\n\t\t*container = \"MOUNT-ALL\"\n\t}\n\n\t\/\/mountpoint\n\tif *mountpoint == \"\" {\n\t\tlog.Warn(\"option '--mountpoint=' is not set  Default: \/mnt\/<containername>\")\n\t}\n\n\tvar n ntnxAPI.NTNXConnection\n\n\tn.NutanixHost = *host\n\tn.Username = *username\n\tn.Password = *password\n\n\tntnxAPI.EncodeCredentials(&n)\n\tntnxAPI.CreateHTTPClient(&n)\n\n\tntnxAPI.NutanixCheckCredentials(&n)\n\n\treturn n\n\n}\n\nfunc mkDIR(path string) {\n\n\tcmd := exec.Command(\"\/bin\/bash\", \"-c\", \"sudo mkdir -p \"+path)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Error(\"Could not create mountpoint: \" + path)\n\t}\n}\n\nfunc mount(hostname string, share string, path string) {\n\tcmd := exec.Command(\"\/bin\/bash\", \"-c\", \"sudo mount -t nfs \"+hostname+\":\/\"+share+\" \"+path)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Error(\"Could not mount share: \" + share + \" from host: \" + hostname + \" to path: \" + path)\n\t}\n}\n\nfunc main() {\n\n\tflag.Usage = printHelp\n\tflag.Parse()\n\n\tcustomFormatter := new(log.TextFormatter)\n\tcustomFormatter.TimestampFormat = \"2006-01-02 15:04:05\"\n\tlog.SetFormatter(customFormatter)\n\tcustomFormatter.FullTimestamp = true\n\n\tvar n ntnxAPI.NTNXConnection\n\n\tn = evaluateFlags()\n\n\tif *whitelist != \"\" {\n\t\tntnxAPI.AddWhiteList(&n, *whitelist)\n\t\ttime.Sleep(5000) \/\/ Wait so Whitelist will be active\n\t}\n\n\tif *container != \"MOUNT-ALL\" {\n\t\t_, err := ntnxAPI.GetContainerIDbyName(&n, *container)\n\t\tif err != nil {\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tif *mountpoint != \"\" {\n\t\t\tmkDIR(*mountpoint + *container)\n\t\t\tmount(*host, *container, *mountpoint+*container)\n\n\t\t} else {\n\t\t\tmkDIR(\"\/mnt\/\" + *container)\n\t\t\tmount(*host, *container, \"\/mnt\/\"+*container)\n\n\t\t}\n\t\tos.Exit(0)\n\t}\n\n\tlist, _ := ntnxAPI.GetContainerNames(&n)\n\tfor _, elem := range list {\n\n\t\tmkDIR(\"\/mnt\/\" + elem)\n\t\tmount(*host, elem, \"\/mnt\/\"+elem)\n\n\t}\n\n}\n<commit_msg>mount_nfs whitelist fix<commit_after>\/* Copyright (c) 2016 Thomas Findelkind\n#\n# This program is free software: you can redistribute it and\/or modify it under\n# the terms of the GNU General Public License as published by the Free Software\n# Foundation, either version 3 of the License, or (at your option) any later\n# version.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more\n# details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n#\n# MORE ABOUT THIS SCRIPT AVAILABLE IN THE README AND AT:\n#\n# http:\/\/tfindelkind.com\n#\n# ----------------------------------------------------------------------------\n*\/\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\tntnxAPI \"github.com\/Tfindelkind\/acropolis-sdk-go\"\n)\n\nconst appVersion = \"0.9 beta\"\n\nvar (\n\thost       *string\n\tusername   *string\n\tpassword   *string\n\tcontainer  *string\n\tmountpoint *string\n\twhitelist  *string\n\tunmount    *bool\n\tdebug      *bool\n\thelp       *bool\n\tversion    *bool\n)\n\nfunc init() {\n\thost = flag.String(\"host\", \"\", \"a string\")\n\tusername = flag.String(\"username\", \"\", \"a string\")\n\tpassword = flag.String(\"password\", \"\", \"a string\")\n\tcontainer = flag.String(\"container\", \"\", \"a string\")\n\tmountpoint = flag.String(\"mountpoint\", \"\", \"a string\")\n\twhitelist = flag.String(\"whitelist\", \"\", \"a string\")\n\tunmount = flag.Bool(\"unmount\", false, \"a bool\")\n\tdebug = flag.Bool(\"debug\", false, \"a bool\")\n\thelp = flag.Bool(\"help\", false, \"a bool\")\n\tversion = flag.Bool(\"version\", false, \"a bool\")\n}\n\nfunc printHelp() {\n\n\tfmt.Println(\"Usage: mount_nfs [OPTIONS]\")\n\tfmt.Println(\"mount_nfs [ --help | --version ]\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"FOR NUTANIX AHV ONLY- exports an AHV VM\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"Options:\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"--host             Specify CVM host or Cluster IP\")\n\tfmt.Println(\"--username         Specify username for connect to host\")\n\tfmt.Println(\"--password         Specify password for user\")\n\tfmt.Println(\"--container        Specify the container to mount - Default mount all\")\n\tfmt.Println(\"--mountpoint       (Optional) the mount point like '\/mount\/' WITH tailing \/\")\n\tfmt.Println(\"--whitelist\t\t    (Optional) nnn.nnn.nnn.nnn\/xxx.xxx.xxx.xxx\")\n\tfmt.Println(\"           \t\t    where nnn is the IP address, and xxx is the subnet mask.\")\n\tfmt.Println(\"--unmount\t\t      will unmount in 'mount all' mode\")\n\tfmt.Println(\"--debug            Enables debug mode\")\n\tfmt.Println(\"--help             List this help\")\n\tfmt.Println(\"--version          Show the deploy_cloud_vm version\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"Example:\")\n\tfmt.Println(\"\")\n\tfmt.Println(\"mount_nfs --host=NTNX-CVM --username=admin --password=nutanix\/4u\")\n\tfmt.Println(\"\")\n}\n\nfunc evaluateFlags() ntnxAPI.NTNXConnection {\n\n\t\/\/help\n\tif *help {\n\t\tprintHelp()\n\t\tos.Exit(0)\n\t}\n\n\t\/\/version\n\tif *version {\n\t\tfmt.Println(\"Version: \" + appVersion)\n\t\tos.Exit(0)\n\t}\n\n\t\/\/debug\n\tif *debug {\n\t\tlog.SetLevel(log.DebugLevel)\n\t} else {\n\t\tlog.SetLevel(log.InfoLevel)\n\t}\n\n\t\/\/host\n\tif *host == \"\" {\n\t\tlog.Warn(\"mandatory option '--host=' is not set\")\n\t\tos.Exit(0)\n\t}\n\n\t\/\/username\n\tif *username == \"\" {\n\t\tlog.Warn(\"option '--username=' is not set  Default: admin is used\")\n\t\t*username = \"admin\"\n\t}\n\n\t\/\/password\n\tif *password == \"\" {\n\t\tlog.Warn(\"option '--password=' is not set  Default: nutanix\/4u is used\")\n\t\t*password = \"nutanix\/4u\"\n\t}\n\n\t\/\/container\n\tif *container == \"\" {\n\t\tlog.Warn(\"option '--container=' is not set  Default: mounting all\")\n\t\t*container = \"MOUNT-ALL\"\n\t}\n\n\t\/\/mountpoint\n\tif *mountpoint == \"\" {\n\t\tlog.Warn(\"option '--mountpoint=' is not set  Default: \/mnt\/<containername>\")\n\t}\n\n\tvar n ntnxAPI.NTNXConnection\n\n\tn.NutanixHost = *host\n\tn.Username = *username\n\tn.Password = *password\n\n\tntnxAPI.EncodeCredentials(&n)\n\tntnxAPI.CreateHTTPClient(&n)\n\n\tntnxAPI.NutanixCheckCredentials(&n)\n\n\treturn n\n\n}\n\nfunc mkDIR(path string) {\n\n\tcmd := exec.Command(\"\/bin\/bash\", \"-c\", \"sudo mkdir -p \"+path)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Error(\"Could not create mountpoint: \" + path)\n\t}\n}\n\nfunc mount(hostname string, share string, path string) {\n\tcmd := exec.Command(\"\/bin\/bash\", \"-c\", \"sudo mount -t nfs \"+hostname+\":\/\"+share+\" \"+path)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Error(\"Could not mount share: \" + share + \" from host: \" + hostname + \" to path: \" + path)\n\t}\n}\n\nfunc umount(path string) {\n\tcmd := exec.Command(\"\/bin\/bash\", \"-c\", \"sudo umount \"+path)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Error(\"Could not unmount path: \" + path)\n\t}\n}\n\nfunc main() {\n\n\tflag.Usage = printHelp\n\tflag.Parse()\n\n\tcustomFormatter := new(log.TextFormatter)\n\tcustomFormatter.TimestampFormat = \"2006-01-02 15:04:05\"\n\tlog.SetFormatter(customFormatter)\n\tcustomFormatter.FullTimestamp = true\n\n\tvar n ntnxAPI.NTNXConnection\n\n\tn = evaluateFlags()\n\n\tif *whitelist != \"\" {\n\t\tntnxAPI.AddWhiteList(&n, *whitelist)\n\t\ttime.Sleep(5000) \/\/ Wait so Whitelist will be active\n\t}\n\n\tif *container != \"MOUNT-ALL\" {\n\n\t\t_, err := ntnxAPI.GetContainerIDbyName(&n, *container)\n\t\tif err != nil {\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tif *mountpoint != \"\" {\n\t\t\tmkDIR(*mountpoint + *container)\n\t\t\tmount(*host, *container, *mountpoint+*container)\n\n\t\t} else {\n\t\t\tmkDIR(\"\/mnt\/\" + *container)\n\t\t\tmount(*host, *container, \"\/mnt\/\"+*container)\n\n\t\t}\n\t\tos.Exit(0)\n\t}\n\n\tlist, _ := ntnxAPI.GetContainerNames(&n)\n\tfor _, elem := range list {\n\t\tif *unmount {\n\t\t\tumount(\"\/mnt\/\" + elem)\n\t\t} else {\n\t\t\tmkDIR(\"\/mnt\/\" + elem)\n\t\t\tmount(*host, elem, \"\/mnt\/\"+elem)\n\t\t}\n\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package mtgplugin\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/iopred\/bruxism\"\n\t\"github.com\/scaleway\/scaleway-cli\/vendor\/github.com\/renstrom\/fuzzysearch\/fuzzy\"\n)\n\ntype MTGSet struct {\n\tCards []*MTGCard `json:\"cards\"`\n}\n\ntype MTGCard struct {\n\tName      string  `json:\"name\"`\n\tManaCost  string  `json:\"manaCost\"`\n\tType      string  `json:\"type\"`\n\tText      string  `json:\"text\"`\n\tID        *int    `json:\"multiverseid\"`\n\tPower     *string `json:\"power\"`\n\tToughness *string `json:\"toughness\"`\n\tLoyalty   *int    `json:\"loyalty\"`\n}\n\nvar MTGCardMap map[string]*MTGCard = map[string]*MTGCard{}\nvar MTGCardNames []string\n\nvar MTGTextReplacer *strings.Replacer = strings.NewReplacer(\"(\", \"*(\", \")\", \")*\")\nvar MTGCostReplacer *strings.Replacer = strings.NewReplacer(\"{\", \"\", \"}\", \"\")\nvar MTGRestReplacer *strings.Replacer = strings.NewReplacer(\"*\", \"\\\\*\")\n\nfunc init() {\n\tfile, err := os.Open(\"mtg\/AllSets-x.json\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\tMTGSets := map[string]*MTGSet{}\n\n\td := json.NewDecoder(bufio.NewReader(file))\n\terr = d.Decode(&MTGSets)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfor _, s := range MTGSets {\n\t\tfor _, c := range s.Cards {\n\t\t\tc.ManaCost = MTGCostReplacer.Replace(c.ManaCost)\n\t\t\tc.Text = MTGCostReplacer.Replace(c.Text)\n\t\t\tMTGCardMap[c.Name] = c\n\t\t\tMTGCardNames = append(MTGCardNames, c.Name)\n\t\t}\n\t}\n}\n\n\/\/ MTGCommand is a command for getting information about MTG cards..\nfunc MTGCommand(bot *bruxism.Bot, service bruxism.Service, message bruxism.Message, command string, parts []string) {\n\tcardNames := fuzzy.RankFindFold(command, MTGCardNames)\n\tif len(cardNames) == 0 {\n\t\tservice.SendMessage(message.Channel(), \"Could not find a card with that name, sorry.\")\n\t\treturn\n\t}\n\n\tsort.Sort(cardNames)\n\n\tcard := MTGCardMap[cardNames[0].Target]\n\n\trest := \"\"\n\tif card.Text != \"\" {\n\t\trest += \"\\n\"\n\t}\n\tif card.Power != nil {\n\t\trest += MTGRestReplacer.Replace(fmt.Sprintf(\"%s\/%s\", *card.Power, *card.Toughness))\n\t}\n\tif card.Loyalty != nil {\n\t\trest += MTGRestReplacer.Replace(fmt.Sprintf(\"%d\", *card.Loyalty))\n\t}\n\tif card.ID != nil {\n\t\tif rest != \"\" && rest != \"\\n\" {\n\t\t\trest += \"\\n\"\n\t\t}\n\t\trest += fmt.Sprintf(\"(http:\/\/gatherer.wizards.com\/Handlers\/Image.ashx?multiverseid=%d&type=card)\", *card.ID)\n\t}\n\n\tif service.Name() == bruxism.DiscordServiceName {\n\t\tservice.SendMessage(message.Channel(), fmt.Sprintf(\"**%s** %s\\n*%s*\\n%s%s\", card.Name, card.ManaCost, card.Type, MTGTextReplacer.Replace(card.Text), rest))\n\t} else {\n\t\tservice.SendMessage(message.Channel(), strings.Replace(fmt.Sprintf(\"%s. %s. %s. %s%s\", card.Name, card.Type, card.ManaCost, card.Text, rest), \"\\n\", \" \", -1))\n\t}\n}\n<commit_msg>Fix mtg plugin for go 1.6<commit_after>package mtgplugin\n\nimport (\n\t\"bufio\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/iopred\/bruxism\"\n\t\"github.com\/renstrom\/fuzzysearch\/fuzzy\"\n)\n\ntype MTGSet struct {\n\tCards []*MTGCard `json:\"cards\"`\n}\n\ntype MTGCard struct {\n\tName      string  `json:\"name\"`\n\tManaCost  string  `json:\"manaCost\"`\n\tType      string  `json:\"type\"`\n\tText      string  `json:\"text\"`\n\tID        *int    `json:\"multiverseid\"`\n\tPower     *string `json:\"power\"`\n\tToughness *string `json:\"toughness\"`\n\tLoyalty   *int    `json:\"loyalty\"`\n}\n\nvar MTGCardMap map[string]*MTGCard = map[string]*MTGCard{}\nvar MTGCardNames []string\n\nvar MTGTextReplacer *strings.Replacer = strings.NewReplacer(\"(\", \"*(\", \")\", \")*\")\nvar MTGCostReplacer *strings.Replacer = strings.NewReplacer(\"{\", \"\", \"}\", \"\")\nvar MTGRestReplacer *strings.Replacer = strings.NewReplacer(\"*\", \"\\\\*\")\n\nfunc init() {\n\tfile, err := os.Open(\"mtg\/AllSets-x.json\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\tMTGSets := map[string]*MTGSet{}\n\n\td := json.NewDecoder(bufio.NewReader(file))\n\terr = d.Decode(&MTGSets)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfor _, s := range MTGSets {\n\t\tfor _, c := range s.Cards {\n\t\t\tc.ManaCost = MTGCostReplacer.Replace(c.ManaCost)\n\t\t\tc.Text = MTGCostReplacer.Replace(c.Text)\n\t\t\tMTGCardMap[c.Name] = c\n\t\t\tMTGCardNames = append(MTGCardNames, c.Name)\n\t\t}\n\t}\n}\n\n\/\/ MTGCommand is a command for getting information about MTG cards..\nfunc MTGCommand(bot *bruxism.Bot, service bruxism.Service, message bruxism.Message, command string, parts []string) {\n\tcardNames := fuzzy.RankFindFold(command, MTGCardNames)\n\tif len(cardNames) == 0 {\n\t\tservice.SendMessage(message.Channel(), \"Could not find a card with that name, sorry.\")\n\t\treturn\n\t}\n\n\tsort.Sort(cardNames)\n\n\tcard := MTGCardMap[cardNames[0].Target]\n\n\trest := \"\"\n\tif card.Text != \"\" {\n\t\trest += \"\\n\"\n\t}\n\tif card.Power != nil {\n\t\trest += MTGRestReplacer.Replace(fmt.Sprintf(\"%s\/%s\", *card.Power, *card.Toughness))\n\t}\n\tif card.Loyalty != nil {\n\t\trest += MTGRestReplacer.Replace(fmt.Sprintf(\"%d\", *card.Loyalty))\n\t}\n\tif card.ID != nil {\n\t\tif rest != \"\" && rest != \"\\n\" {\n\t\t\trest += \"\\n\"\n\t\t}\n\t\trest += fmt.Sprintf(\"(http:\/\/gatherer.wizards.com\/Handlers\/Image.ashx?multiverseid=%d&type=card)\", *card.ID)\n\t}\n\n\tif service.Name() == bruxism.DiscordServiceName {\n\t\tservice.SendMessage(message.Channel(), fmt.Sprintf(\"**%s** %s\\n*%s*\\n%s%s\", card.Name, card.ManaCost, card.Type, MTGTextReplacer.Replace(card.Text), rest))\n\t} else {\n\t\tservice.SendMessage(message.Channel(), strings.Replace(fmt.Sprintf(\"%s. %s. %s. %s%s\", card.Name, card.Type, card.ManaCost, card.Text, rest), \"\\n\", \" \", -1))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 The Kubernetes Authors.\n\/\/ SPDX-License-Identifier: Apache-2.0\n\npackage builtinpluginconsts\n\nconst (\n\tnameReferenceFieldSpecs = `\nnameReference:\n- kind: Deployment\n  fieldSpecs:\n  - path: spec\/scaleTargetRef\/name\n    kind: HorizontalPodAutoscaler\n\n- kind: ReplicationController\n  fieldSpecs:\n  - path: spec\/scaleTargetRef\/name\n    kind: HorizontalPodAutoscaler\n\n- kind: ReplicaSet\n  fieldSpecs:\n  - path: spec\/scaleTargetRef\/name\n    kind: HorizontalPodAutoscaler\n\n- kind: StatefulSet\n  fieldSpecs:\n  - path: spec\/scaleTargetRef\/name\n    kind: HorizontalPodAutoscaler\n\n- kind: ConfigMap\n  version: v1\n  fieldSpecs:\n  - path: spec\/volumes\/configMap\/name\n    version: v1\n    kind: Pod\n  - path: spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/containers\/envFrom\/configMapRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/initContainers\/envFrom\/configMapRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/volumes\/projected\/sources\/configMap\/name\n    version: v1\n    kind: Pod\n  - path: spec\/template\/spec\/volumes\/configMap\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/containers\/envFrom\/configMapRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/initContainers\/envFrom\/configMapRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/configMap\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/volumes\/configMap\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/containers\/envFrom\/configMapRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/initContainers\/envFrom\/configMapRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/configMap\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/volumes\/configMap\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/containers\/envFrom\/configMapRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/initContainers\/envFrom\/configMapRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/configMap\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/volumes\/configMap\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/containers\/envFrom\/configMapRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/initContainers\/envFrom\/configMapRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/configMap\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/volumes\/configMap\/name\n    kind: Job\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/containers\/envFrom\/configMapRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/initContainers\/envFrom\/configMapRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/configMap\/name\n    kind: Job\n  - path: spec\/jobTemplate\/spec\/template\/spec\/volumes\/configMap\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/volumes\/projected\/sources\/configMap\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/containers\/envFrom\/configMapRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/initContainers\/envFrom\/configMapRef\/name\n    kind: CronJob\n  - path: spec\/configSource\/configMap\n    kind: Node\n\n- kind: Secret\n  version: v1\n  fieldSpecs:\n  - path: spec\/volumes\/secret\/secretName\n    version: v1\n    kind: Pod\n  - path: spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/containers\/envFrom\/secretRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/initContainers\/envFrom\/secretRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/imagePullSecrets\/name\n    version: v1\n    kind: Pod\n  - path: spec\/volumes\/projected\/sources\/secret\/name\n    version: v1\n    kind: Pod\n  - path: spec\/template\/spec\/volumes\/secret\/secretName\n    kind: Deployment\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/containers\/envFrom\/secretRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/initContainers\/envFrom\/secretRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/imagePullSecrets\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/secret\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/volumes\/secret\/secretName\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/containers\/envFrom\/secretRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/initContainers\/envFrom\/secretRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/imagePullSecrets\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/secret\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/volumes\/secret\/secretName\n    kind: DaemonSet\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/containers\/envFrom\/secretRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/initContainers\/envFrom\/secretRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/imagePullSecrets\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/secret\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/volumes\/secret\/secretName\n    kind: StatefulSet\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/containers\/envFrom\/secretRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/initContainers\/envFrom\/secretRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/imagePullSecrets\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/secret\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/volumes\/secret\/secretName\n    kind: Job\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/containers\/envFrom\/secretRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/initContainers\/envFrom\/secretRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/imagePullSecrets\/name\n    kind: Job\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/secret\/name\n    kind: Job\n  - path: spec\/jobTemplate\/spec\/template\/spec\/volumes\/secret\/secretName\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/volumes\/projected\/sources\/secret\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/containers\/envFrom\/secretRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/initContainers\/envFrom\/secretRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/imagePullSecrets\/name\n    kind: CronJob\n  - path: spec\/tls\/secretName\n    kind: Ingress\n  - path: metadata\/annotations\/ingress.kubernetes.io\\\/auth-secret\n    kind: Ingress\n  - path: metadata\/annotations\/nginx.ingress.kubernetes.io\\\/auth-secret\n    kind: Ingress\n  - path: metadata\/annotations\/nginx.ingress.kubernetes.io\\\/auth-tls-secret\n    kind: Ingress\n  - path: imagePullSecrets\/name\n    kind: ServiceAccount\n  - path: parameters\/secretName\n    kind: StorageClass\n  - path: parameters\/adminSecretName\n    kind: StorageClass\n  - path: parameters\/userSecretName\n    kind: StorageClass\n  - path: parameters\/secretRef\n    kind: StorageClass\n  - path: rules\/resourceNames\n    kind: Role\n  - path: rules\/resourceNames\n    kind: ClusterRole\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: Service\n    group: serving.knative.dev\n    version: v1\n\n- kind: Service\n  version: v1\n  fieldSpecs:\n  - path: spec\/serviceName\n    kind: StatefulSet\n    group: apps\n  - path: spec\/rules\/http\/paths\/backend\/serviceName\n    kind: Ingress\n  - path: spec\/backend\/serviceName\n    kind: Ingress\n  - path: spec\/rules\/http\/paths\/backend\/service\/name\n    kind: Ingress\n  - path: spec\/defaultBackend\/service\/name\n    kind: Ingress\n  - path: spec\/service\/name\n    kind: APIService\n    group: apiregistration.k8s.io\n  - path: webhooks\/clientConfig\/service\n    kind: ValidatingWebhookConfiguration\n    group: admissionregistration.k8s.io\n  - path: webhooks\/clientConfig\/service\n    kind: MutatingWebhookConfiguration\n    group: admissionregistration.k8s.io\n\n- kind: Role\n  group: rbac.authorization.k8s.io\n  fieldSpecs:\n  - path: roleRef\/name\n    kind: RoleBinding\n    group: rbac.authorization.k8s.io\n\n- kind: ClusterRole\n  group: rbac.authorization.k8s.io\n  fieldSpecs:\n  - path: roleRef\/name\n    kind: RoleBinding\n    group: rbac.authorization.k8s.io\n  - path: roleRef\/name\n    kind: ClusterRoleBinding\n    group: rbac.authorization.k8s.io\n\n- kind: ServiceAccount\n  version: v1\n  fieldSpecs:\n  - path: subjects\n    kind: RoleBinding\n    group: rbac.authorization.k8s.io\n  - path: subjects\n    kind: ClusterRoleBinding\n    group: rbac.authorization.k8s.io\n  - path: spec\/serviceAccountName\n    kind: Pod\n  - path: spec\/template\/spec\/serviceAccountName\n    kind: StatefulSet\n  - path: spec\/template\/spec\/serviceAccountName\n    kind: Deployment\n  - path: spec\/template\/spec\/serviceAccountName\n    kind: ReplicationController\n  - path: spec\/jobTemplate\/spec\/template\/spec\/serviceAccountName\n    kind: CronJob\n  - path: spec\/template\/spec\/serviceAccountName\n    kind: Job\n  - path: spec\/template\/spec\/serviceAccountName\n    kind: DaemonSet\n\n- kind: PersistentVolumeClaim\n  version: v1\n  fieldSpecs:\n  - path: spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: Pod\n  - path: spec\/template\/spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: StatefulSet\n  - path: spec\/template\/spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: Deployment\n  - path: spec\/template\/spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: ReplicationController\n  - path: spec\/jobTemplate\/spec\/template\/spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: CronJob\n  - path: spec\/template\/spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: Job\n  - path: spec\/template\/spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: DaemonSet\n\n- kind: PersistentVolume\n  version: v1\n  fieldSpecs:\n  - path: spec\/volumeName\n    kind: PersistentVolumeClaim\n  - path: rules\/resourceNames\n    kind: ClusterRole\n\n- kind: StorageClass\n  version: v1\n  group: storage.k8s.io\n  fieldSpecs:\n  - path: spec\/storageClassName\n    kind: PersistentVolume\n  - path: spec\/storageClassName\n    kind: PersistentVolumeClaim\n  - path: spec\/volumeClaimTemplates\/spec\/storageClassName\n    kind: StatefulSet\n\n- kind: PriorityClass\n  version: v1\n  group: scheduling.k8s.io\n  fieldSpecs:\n  - path: spec\/priorityClassName\n    kind: Pod\n  - path: spec\/template\/spec\/priorityClassName\n    kind: StatefulSet\n  - path: spec\/template\/spec\/priorityClassName\n    kind: Deployment\n  - path: spec\/template\/spec\/priorityClassName\n    kind: ReplicationController\n  - path: spec\/jobTemplate\/spec\/template\/spec\/priorityClassName\n    kind: CronJob\n  - path: spec\/template\/spec\/priorityClassName\n    kind: Job\n  - path: spec\/template\/spec\/priorityClassName\n    kind: DaemonSet\n`\n)\n<commit_msg>Add IngressClass kind<commit_after>\/\/ Copyright 2019 The Kubernetes Authors.\n\/\/ SPDX-License-Identifier: Apache-2.0\n\npackage builtinpluginconsts\n\nconst (\n\tnameReferenceFieldSpecs = `\nnameReference:\n- kind: Deployment\n  fieldSpecs:\n  - path: spec\/scaleTargetRef\/name\n    kind: HorizontalPodAutoscaler\n\n- kind: ReplicationController\n  fieldSpecs:\n  - path: spec\/scaleTargetRef\/name\n    kind: HorizontalPodAutoscaler\n\n- kind: ReplicaSet\n  fieldSpecs:\n  - path: spec\/scaleTargetRef\/name\n    kind: HorizontalPodAutoscaler\n\n- kind: StatefulSet\n  fieldSpecs:\n  - path: spec\/scaleTargetRef\/name\n    kind: HorizontalPodAutoscaler\n\n- kind: ConfigMap\n  version: v1\n  fieldSpecs:\n  - path: spec\/volumes\/configMap\/name\n    version: v1\n    kind: Pod\n  - path: spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/containers\/envFrom\/configMapRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/initContainers\/envFrom\/configMapRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/volumes\/projected\/sources\/configMap\/name\n    version: v1\n    kind: Pod\n  - path: spec\/template\/spec\/volumes\/configMap\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/containers\/envFrom\/configMapRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/initContainers\/envFrom\/configMapRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/configMap\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/volumes\/configMap\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/containers\/envFrom\/configMapRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/initContainers\/envFrom\/configMapRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/configMap\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/volumes\/configMap\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/containers\/envFrom\/configMapRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/initContainers\/envFrom\/configMapRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/configMap\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/volumes\/configMap\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/containers\/envFrom\/configMapRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/initContainers\/envFrom\/configMapRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/configMap\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/volumes\/configMap\/name\n    kind: Job\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/containers\/envFrom\/configMapRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/initContainers\/envFrom\/configMapRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/configMap\/name\n    kind: Job\n  - path: spec\/jobTemplate\/spec\/template\/spec\/volumes\/configMap\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/volumes\/projected\/sources\/configMap\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/containers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/initContainers\/env\/valueFrom\/configMapKeyRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/containers\/envFrom\/configMapRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/initContainers\/envFrom\/configMapRef\/name\n    kind: CronJob\n  - path: spec\/configSource\/configMap\n    kind: Node\n\n- kind: Secret\n  version: v1\n  fieldSpecs:\n  - path: spec\/volumes\/secret\/secretName\n    version: v1\n    kind: Pod\n  - path: spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/containers\/envFrom\/secretRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/initContainers\/envFrom\/secretRef\/name\n    version: v1\n    kind: Pod\n  - path: spec\/imagePullSecrets\/name\n    version: v1\n    kind: Pod\n  - path: spec\/volumes\/projected\/sources\/secret\/name\n    version: v1\n    kind: Pod\n  - path: spec\/template\/spec\/volumes\/secret\/secretName\n    kind: Deployment\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/containers\/envFrom\/secretRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/initContainers\/envFrom\/secretRef\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/imagePullSecrets\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/secret\/name\n    kind: Deployment\n  - path: spec\/template\/spec\/volumes\/secret\/secretName\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/containers\/envFrom\/secretRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/initContainers\/envFrom\/secretRef\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/imagePullSecrets\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/secret\/name\n    kind: ReplicaSet\n  - path: spec\/template\/spec\/volumes\/secret\/secretName\n    kind: DaemonSet\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/containers\/envFrom\/secretRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/initContainers\/envFrom\/secretRef\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/imagePullSecrets\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/secret\/name\n    kind: DaemonSet\n  - path: spec\/template\/spec\/volumes\/secret\/secretName\n    kind: StatefulSet\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/containers\/envFrom\/secretRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/initContainers\/envFrom\/secretRef\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/imagePullSecrets\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/secret\/name\n    kind: StatefulSet\n  - path: spec\/template\/spec\/volumes\/secret\/secretName\n    kind: Job\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/containers\/envFrom\/secretRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/initContainers\/envFrom\/secretRef\/name\n    kind: Job\n  - path: spec\/template\/spec\/imagePullSecrets\/name\n    kind: Job\n  - path: spec\/template\/spec\/volumes\/projected\/sources\/secret\/name\n    kind: Job\n  - path: spec\/jobTemplate\/spec\/template\/spec\/volumes\/secret\/secretName\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/volumes\/projected\/sources\/secret\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/initContainers\/env\/valueFrom\/secretKeyRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/containers\/envFrom\/secretRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/initContainers\/envFrom\/secretRef\/name\n    kind: CronJob\n  - path: spec\/jobTemplate\/spec\/template\/spec\/imagePullSecrets\/name\n    kind: CronJob\n  - path: spec\/tls\/secretName\n    kind: Ingress\n  - path: metadata\/annotations\/ingress.kubernetes.io\\\/auth-secret\n    kind: Ingress\n  - path: metadata\/annotations\/nginx.ingress.kubernetes.io\\\/auth-secret\n    kind: Ingress\n  - path: metadata\/annotations\/nginx.ingress.kubernetes.io\\\/auth-tls-secret\n    kind: Ingress\n  - path: imagePullSecrets\/name\n    kind: ServiceAccount\n  - path: parameters\/secretName\n    kind: StorageClass\n  - path: parameters\/adminSecretName\n    kind: StorageClass\n  - path: parameters\/userSecretName\n    kind: StorageClass\n  - path: parameters\/secretRef\n    kind: StorageClass\n  - path: rules\/resourceNames\n    kind: Role\n  - path: rules\/resourceNames\n    kind: ClusterRole\n  - path: spec\/template\/spec\/containers\/env\/valueFrom\/secretKeyRef\/name\n    kind: Service\n    group: serving.knative.dev\n    version: v1\n\n- kind: Service\n  version: v1\n  fieldSpecs:\n  - path: spec\/serviceName\n    kind: StatefulSet\n    group: apps\n  - path: spec\/rules\/http\/paths\/backend\/serviceName\n    kind: Ingress\n  - path: spec\/backend\/serviceName\n    kind: Ingress\n  - path: spec\/rules\/http\/paths\/backend\/service\/name\n    kind: Ingress\n  - path: spec\/defaultBackend\/service\/name\n    kind: Ingress\n  - path: spec\/service\/name\n    kind: APIService\n    group: apiregistration.k8s.io\n  - path: webhooks\/clientConfig\/service\n    kind: ValidatingWebhookConfiguration\n    group: admissionregistration.k8s.io\n  - path: webhooks\/clientConfig\/service\n    kind: MutatingWebhookConfiguration\n    group: admissionregistration.k8s.io\n\n- kind: Role\n  group: rbac.authorization.k8s.io\n  fieldSpecs:\n  - path: roleRef\/name\n    kind: RoleBinding\n    group: rbac.authorization.k8s.io\n\n- kind: ClusterRole\n  group: rbac.authorization.k8s.io\n  fieldSpecs:\n  - path: roleRef\/name\n    kind: RoleBinding\n    group: rbac.authorization.k8s.io\n  - path: roleRef\/name\n    kind: ClusterRoleBinding\n    group: rbac.authorization.k8s.io\n\n- kind: ServiceAccount\n  version: v1\n  fieldSpecs:\n  - path: subjects\n    kind: RoleBinding\n    group: rbac.authorization.k8s.io\n  - path: subjects\n    kind: ClusterRoleBinding\n    group: rbac.authorization.k8s.io\n  - path: spec\/serviceAccountName\n    kind: Pod\n  - path: spec\/template\/spec\/serviceAccountName\n    kind: StatefulSet\n  - path: spec\/template\/spec\/serviceAccountName\n    kind: Deployment\n  - path: spec\/template\/spec\/serviceAccountName\n    kind: ReplicationController\n  - path: spec\/jobTemplate\/spec\/template\/spec\/serviceAccountName\n    kind: CronJob\n  - path: spec\/template\/spec\/serviceAccountName\n    kind: Job\n  - path: spec\/template\/spec\/serviceAccountName\n    kind: DaemonSet\n\n- kind: PersistentVolumeClaim\n  version: v1\n  fieldSpecs:\n  - path: spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: Pod\n  - path: spec\/template\/spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: StatefulSet\n  - path: spec\/template\/spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: Deployment\n  - path: spec\/template\/spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: ReplicationController\n  - path: spec\/jobTemplate\/spec\/template\/spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: CronJob\n  - path: spec\/template\/spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: Job\n  - path: spec\/template\/spec\/volumes\/persistentVolumeClaim\/claimName\n    kind: DaemonSet\n\n- kind: PersistentVolume\n  version: v1\n  fieldSpecs:\n  - path: spec\/volumeName\n    kind: PersistentVolumeClaim\n  - path: rules\/resourceNames\n    kind: ClusterRole\n\n- kind: StorageClass\n  version: v1\n  group: storage.k8s.io\n  fieldSpecs:\n  - path: spec\/storageClassName\n    kind: PersistentVolume\n  - path: spec\/storageClassName\n    kind: PersistentVolumeClaim\n  - path: spec\/volumeClaimTemplates\/spec\/storageClassName\n    kind: StatefulSet\n\n- kind: PriorityClass\n  version: v1\n  group: scheduling.k8s.io\n  fieldSpecs:\n  - path: spec\/priorityClassName\n    kind: Pod\n  - path: spec\/template\/spec\/priorityClassName\n    kind: StatefulSet\n  - path: spec\/template\/spec\/priorityClassName\n    kind: Deployment\n  - path: spec\/template\/spec\/priorityClassName\n    kind: ReplicationController\n  - path: spec\/jobTemplate\/spec\/template\/spec\/priorityClassName\n    kind: CronJob\n  - path: spec\/template\/spec\/priorityClassName\n    kind: Job\n  - path: spec\/template\/spec\/priorityClassName\n    kind: DaemonSet\n\n- kind: IngressClass\n  version: v1\n  group: networking.k8s.io\/v1\n  fieldSpecs:\n  - path: spec\/ingressClassName\n    kind: Ingress\n`\n)\n<|endoftext|>"}
{"text":"<commit_before>package addrutil\n\nimport (\n\t\"fmt\"\n\n\teventlog \"github.com\/jbenet\/go-ipfs\/thirdparty\/eventlog\"\n\n\tcontext \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/go.net\/context\"\n\tma \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr\"\n\tmanet \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr-net\"\n)\n\nvar log = eventlog.Logger(\"p2p\/net\/swarm\/addr\")\n\n\/\/ SupportedTransportStrings is the list of supported transports for the swarm.\n\/\/ These are strings of encapsulated multiaddr protocols. E.g.:\n\/\/   \/ip4\/tcp\nvar SupportedTransportStrings = []string{\n\t\"\/ip4\/tcp\",\n\t\"\/ip6\/tcp\",\n\t\/\/ \"\/ip4\/udp\/utp\", disabled because the lib is broken\n\t\/\/ \"\/ip6\/udp\/utp\", disabled because the lib is broken\n\t\/\/ \"\/ip4\/udp\/udt\", disabled because the lib doesnt work on arm\n\t\/\/ \"\/ip6\/udp\/udt\", disabled because the lib doesnt work on arm\n}\n\n\/\/ SupportedTransportProtocols is the list of supported transports for the swarm.\n\/\/ These are []ma.Protocol lists. Populated at runtime from SupportedTransportStrings\nvar SupportedTransportProtocols = [][]ma.Protocol{}\n\nfunc init() {\n\t\/\/ initialize SupportedTransportProtocols\n\ttransports := make([][]ma.Protocol, len(SupportedTransportStrings))\n\tfor _, s := range SupportedTransportStrings {\n\t\tt, err := ma.ProtocolsWithString(s)\n\t\tif err != nil {\n\t\t\tpanic(err) \/\/ important to fix this in the codebase\n\t\t}\n\t\ttransports = append(transports, t)\n\t}\n\tSupportedTransportProtocols = transports\n}\n\n\/\/ FilterAddrs is a filter that removes certain addresses, according to filter.\n\/\/ if filter returns true, the address is kept.\nfunc FilterAddrs(a []ma.Multiaddr, filter func(ma.Multiaddr) bool) []ma.Multiaddr {\n\tb := make([]ma.Multiaddr, 0, len(a))\n\tfor _, addr := range a {\n\t\tif filter(addr) {\n\t\t\tb = append(b, addr)\n\t\t}\n\t}\n\treturn b\n}\n\n\/\/ FilterUsableAddrs removes certain addresses\n\/\/ from a list. the addresses removed are those known NOT\n\/\/ to work with our network. Namely, addresses with UTP.\nfunc FilterUsableAddrs(a []ma.Multiaddr) []ma.Multiaddr {\n\treturn FilterAddrs(a, func(m ma.Multiaddr) bool {\n\t\treturn AddrUsable(m, false)\n\t})\n}\n\n\/\/ AddrOverNonLocalIP returns whether the addr uses a non-local ip link\nfunc AddrOverNonLocalIP(a ma.Multiaddr) bool {\n\tsplit := ma.Split(a)\n\tif len(split) < 1 {\n\t\treturn false\n\t}\n\tif manet.IsIP6LinkLocal(split[0]) {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ AddrUsable returns whether our network can use this addr.\n\/\/ We only use the transports in SupportedTransportStrings,\n\/\/ and we do not link local addresses. Loopback is ok\n\/\/ as we need to be able to connect to multiple ipfs nodes\n\/\/ in the same machine.\nfunc AddrUsable(a ma.Multiaddr, partial bool) bool {\n\n\tif !AddrOverNonLocalIP(a) {\n\t\treturn false\n\t}\n\n\t\/\/ test the address protocol list is in SupportedTransportProtocols\n\tmatches := func(supported, test []ma.Protocol) bool {\n\t\tif len(test) > len(supported) {\n\t\t\treturn false\n\t\t}\n\n\t\t\/\/ when partial, it's ok if test < supported.\n\t\tif !partial && len(supported) != len(test) {\n\t\t\treturn false\n\t\t}\n\n\t\tfor i := range test {\n\t\t\tif supported[i].Code != test[i].Code {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\ttransport := a.Protocols()\n\tfor _, supported := range SupportedTransportProtocols {\n\t\tif matches(supported, transport) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ ResolveUnspecifiedAddress expands an unspecified ip addresses (\/ip4\/0.0.0.0, \/ip6\/::) to\n\/\/ use the known local interfaces. If ifaceAddr is nil, we request interface addresses\n\/\/ from the network stack. (this is so you can provide a cached value if resolving many addrs)\nfunc ResolveUnspecifiedAddress(resolve ma.Multiaddr, ifaceAddrs []ma.Multiaddr) ([]ma.Multiaddr, error) {\n\t\/\/ split address into its components\n\tsplit := ma.Split(resolve)\n\n\t\/\/ if first component (ip) is not unspecified, use it as is.\n\tif !manet.IsIPUnspecified(split[0]) {\n\t\treturn []ma.Multiaddr{resolve}, nil\n\t}\n\n\tout := make([]ma.Multiaddr, 0, len(ifaceAddrs))\n\tfor _, ia := range ifaceAddrs {\n\t\t\/\/ must match the first protocol to be resolve.\n\t\tif ia.Protocols()[0].Code != resolve.Protocols()[0].Code {\n\t\t\tcontinue\n\t\t}\n\n\t\tsplit[0] = ia\n\t\tjoined := ma.Join(split...)\n\t\tout = append(out, joined)\n\t\tlog.Debug(\"adding resolved addr:\", resolve, joined, out)\n\t}\n\tif len(out) < 1 {\n\t\treturn nil, fmt.Errorf(\"failed to resolve: %s\", resolve)\n\t}\n\treturn out, nil\n}\n\n\/\/ ResolveUnspecifiedAddresses expands unspecified ip addresses (\/ip4\/0.0.0.0, \/ip6\/::) to\n\/\/ use the known local interfaces.\nfunc ResolveUnspecifiedAddresses(unspecAddrs, ifaceAddrs []ma.Multiaddr) ([]ma.Multiaddr, error) {\n\n\t\/\/ todo optimize: only fetch these if we have a \"any\" addr.\n\tif len(ifaceAddrs) < 1 {\n\t\tvar err error\n\t\tifaceAddrs, err = InterfaceAddresses()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ log.Debug(\"InterfaceAddresses:\", ifaceAddrs)\n\t}\n\n\tvar outputAddrs []ma.Multiaddr\n\tfor _, a := range unspecAddrs {\n\t\t\/\/ unspecified?\n\t\tresolved, err := ResolveUnspecifiedAddress(a, ifaceAddrs)\n\t\tif err != nil {\n\t\t\tcontinue \/\/ optimistic. if we cant resolve anything, we'll know at the bottom.\n\t\t}\n\t\t\/\/ log.Debug(\"resolved:\", a, resolved)\n\t\toutputAddrs = append(outputAddrs, resolved...)\n\t}\n\n\tif len(outputAddrs) < 1 {\n\t\treturn nil, fmt.Errorf(\"failed to specify addrs: %s\", unspecAddrs)\n\t}\n\n\tlog.Event(context.TODO(), \"interfaceListenAddresses\", func() eventlog.Loggable {\n\t\tvar addrs []string\n\t\tfor _, addr := range outputAddrs {\n\t\t\taddrs = append(addrs, addr.String())\n\t\t}\n\t\treturn eventlog.Metadata{\"addresses\": addrs}\n\t}())\n\n\tlog.Debug(\"ResolveUnspecifiedAddresses:\", unspecAddrs, ifaceAddrs, outputAddrs)\n\treturn outputAddrs, nil\n}\n\n\/\/ InterfaceAddresses returns a list of addresses associated with local machine\n\/\/ Note: we do not return link local addresses. IP loopback is ok, because we\n\/\/ may be connecting to other nodes in the same machine.\nfunc InterfaceAddresses() ([]ma.Multiaddr, error) {\n\tmaddrs, err := manet.InterfaceMultiaddrs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debug(\"InterfaceAddresses: from manet:\", maddrs)\n\n\tvar out []ma.Multiaddr\n\tfor _, a := range maddrs {\n\t\tif !AddrUsable(a, true) { \/\/ partial\n\t\t\t\/\/ log.Debug(\"InterfaceAddresses: skipping unusable:\", a)\n\t\t\tcontinue\n\t\t}\n\n\t\tout = append(out, a)\n\t}\n\n\tlog.Debug(\"InterfaceAddresses: usable:\", out)\n\treturn out, nil\n}\n\n\/\/ AddrInList returns whether or not an address is part of a list.\n\/\/ this is useful to check if NAT is happening (or other bugs?)\nfunc AddrInList(addr ma.Multiaddr, list []ma.Multiaddr) bool {\n\tfor _, addr2 := range list {\n\t\tif addr.Equal(addr2) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ AddrIsShareableOnWAN returns whether the given address should be shareable on the\n\/\/ wide area network (wide internet).\nfunc AddrIsShareableOnWAN(addr ma.Multiaddr) bool {\n\ts := ma.Split(addr)\n\tif len(s) < 1 {\n\t\treturn false\n\t}\n\ta := s[0]\n\tif manet.IsIPLoopback(a) || manet.IsIP6LinkLocal(a) || manet.IsIPUnspecified(a) {\n\t\treturn false\n\t}\n\treturn manet.IsThinWaist(a)\n}\n\n\/\/ WANShareableAddrs filters addresses based on whether they're shareable on WAN\nfunc WANShareableAddrs(inp []ma.Multiaddr) []ma.Multiaddr {\n\treturn FilterAddrs(inp, AddrIsShareableOnWAN)\n}\n\n\/\/ Subtract filters out all addrs in b from a\nfunc Subtract(a, b []ma.Multiaddr) []ma.Multiaddr {\n\treturn FilterAddrs(a, func(m ma.Multiaddr) bool {\n\t\tfor _, bb := range b {\n\t\t\tif m.Equal(bb) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n}\n\n\/\/ CheckNATWarning checks if our observed addresses differ. if so,\n\/\/ informs the user that certain things might not work yet\nfunc CheckNATWarning(observed, expected ma.Multiaddr, listen []ma.Multiaddr) {\n\tif observed.Equal(expected) {\n\t\treturn\n\t}\n\n\tif !AddrInList(observed, listen) { \/\/ probably a nat\n\t\tlog.Warningf(natWarning, observed, listen)\n\t}\n}\n\nconst natWarning = `Remote peer observed our address to be: %s\nThe local addresses are: %s\nThus, connection is going through NAT, and other connections may fail.\n\nIPFS NAT traversal is still under development. Please bug us on github or irc to fix this.\nBaby steps: http:\/\/jbenet.static.s3.amazonaws.com\/271dfcf\/baby-steps.gif\n`\n<commit_msg>p2p\/net\/swarm\/addr: check for nil addr<commit_after>package addrutil\n\nimport (\n\t\"fmt\"\n\n\teventlog \"github.com\/jbenet\/go-ipfs\/thirdparty\/eventlog\"\n\n\tcontext \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/go.net\/context\"\n\tma \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr\"\n\tmanet \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multiaddr-net\"\n)\n\nvar log = eventlog.Logger(\"p2p\/net\/swarm\/addr\")\n\n\/\/ SupportedTransportStrings is the list of supported transports for the swarm.\n\/\/ These are strings of encapsulated multiaddr protocols. E.g.:\n\/\/   \/ip4\/tcp\nvar SupportedTransportStrings = []string{\n\t\"\/ip4\/tcp\",\n\t\"\/ip6\/tcp\",\n\t\/\/ \"\/ip4\/udp\/utp\", disabled because the lib is broken\n\t\/\/ \"\/ip6\/udp\/utp\", disabled because the lib is broken\n\t\/\/ \"\/ip4\/udp\/udt\", disabled because the lib doesnt work on arm\n\t\/\/ \"\/ip6\/udp\/udt\", disabled because the lib doesnt work on arm\n}\n\n\/\/ SupportedTransportProtocols is the list of supported transports for the swarm.\n\/\/ These are []ma.Protocol lists. Populated at runtime from SupportedTransportStrings\nvar SupportedTransportProtocols = [][]ma.Protocol{}\n\nfunc init() {\n\t\/\/ initialize SupportedTransportProtocols\n\ttransports := make([][]ma.Protocol, len(SupportedTransportStrings))\n\tfor _, s := range SupportedTransportStrings {\n\t\tt, err := ma.ProtocolsWithString(s)\n\t\tif err != nil {\n\t\t\tpanic(err) \/\/ important to fix this in the codebase\n\t\t}\n\t\ttransports = append(transports, t)\n\t}\n\tSupportedTransportProtocols = transports\n}\n\n\/\/ FilterAddrs is a filter that removes certain addresses, according to filter.\n\/\/ if filter returns true, the address is kept.\nfunc FilterAddrs(a []ma.Multiaddr, filter func(ma.Multiaddr) bool) []ma.Multiaddr {\n\tb := make([]ma.Multiaddr, 0, len(a))\n\tfor _, addr := range a {\n\t\tif filter(addr) {\n\t\t\tb = append(b, addr)\n\t\t}\n\t}\n\treturn b\n}\n\n\/\/ FilterUsableAddrs removes certain addresses\n\/\/ from a list. the addresses removed are those known NOT\n\/\/ to work with our network. Namely, addresses with UTP.\nfunc FilterUsableAddrs(a []ma.Multiaddr) []ma.Multiaddr {\n\treturn FilterAddrs(a, func(m ma.Multiaddr) bool {\n\t\treturn AddrUsable(m, false)\n\t})\n}\n\n\/\/ AddrOverNonLocalIP returns whether the addr uses a non-local ip link\nfunc AddrOverNonLocalIP(a ma.Multiaddr) bool {\n\tsplit := ma.Split(a)\n\tif len(split) < 1 {\n\t\treturn false\n\t}\n\tif manet.IsIP6LinkLocal(split[0]) {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ AddrUsable returns whether our network can use this addr.\n\/\/ We only use the transports in SupportedTransportStrings,\n\/\/ and we do not link local addresses. Loopback is ok\n\/\/ as we need to be able to connect to multiple ipfs nodes\n\/\/ in the same machine.\nfunc AddrUsable(a ma.Multiaddr, partial bool) bool {\n\tif a == nil {\n\t\treturn false\n\t}\n\n\tif !AddrOverNonLocalIP(a) {\n\t\treturn false\n\t}\n\n\t\/\/ test the address protocol list is in SupportedTransportProtocols\n\tmatches := func(supported, test []ma.Protocol) bool {\n\t\tif len(test) > len(supported) {\n\t\t\treturn false\n\t\t}\n\n\t\t\/\/ when partial, it's ok if test < supported.\n\t\tif !partial && len(supported) != len(test) {\n\t\t\treturn false\n\t\t}\n\n\t\tfor i := range test {\n\t\t\tif supported[i].Code != test[i].Code {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\ttransport := a.Protocols()\n\tfor _, supported := range SupportedTransportProtocols {\n\t\tif matches(supported, transport) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ ResolveUnspecifiedAddress expands an unspecified ip addresses (\/ip4\/0.0.0.0, \/ip6\/::) to\n\/\/ use the known local interfaces. If ifaceAddr is nil, we request interface addresses\n\/\/ from the network stack. (this is so you can provide a cached value if resolving many addrs)\nfunc ResolveUnspecifiedAddress(resolve ma.Multiaddr, ifaceAddrs []ma.Multiaddr) ([]ma.Multiaddr, error) {\n\t\/\/ split address into its components\n\tsplit := ma.Split(resolve)\n\n\t\/\/ if first component (ip) is not unspecified, use it as is.\n\tif !manet.IsIPUnspecified(split[0]) {\n\t\treturn []ma.Multiaddr{resolve}, nil\n\t}\n\n\tout := make([]ma.Multiaddr, 0, len(ifaceAddrs))\n\tfor _, ia := range ifaceAddrs {\n\t\t\/\/ must match the first protocol to be resolve.\n\t\tif ia.Protocols()[0].Code != resolve.Protocols()[0].Code {\n\t\t\tcontinue\n\t\t}\n\n\t\tsplit[0] = ia\n\t\tjoined := ma.Join(split...)\n\t\tout = append(out, joined)\n\t\tlog.Debug(\"adding resolved addr:\", resolve, joined, out)\n\t}\n\tif len(out) < 1 {\n\t\treturn nil, fmt.Errorf(\"failed to resolve: %s\", resolve)\n\t}\n\treturn out, nil\n}\n\n\/\/ ResolveUnspecifiedAddresses expands unspecified ip addresses (\/ip4\/0.0.0.0, \/ip6\/::) to\n\/\/ use the known local interfaces.\nfunc ResolveUnspecifiedAddresses(unspecAddrs, ifaceAddrs []ma.Multiaddr) ([]ma.Multiaddr, error) {\n\n\t\/\/ todo optimize: only fetch these if we have a \"any\" addr.\n\tif len(ifaceAddrs) < 1 {\n\t\tvar err error\n\t\tifaceAddrs, err = InterfaceAddresses()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ log.Debug(\"InterfaceAddresses:\", ifaceAddrs)\n\t}\n\n\tvar outputAddrs []ma.Multiaddr\n\tfor _, a := range unspecAddrs {\n\t\t\/\/ unspecified?\n\t\tresolved, err := ResolveUnspecifiedAddress(a, ifaceAddrs)\n\t\tif err != nil {\n\t\t\tcontinue \/\/ optimistic. if we cant resolve anything, we'll know at the bottom.\n\t\t}\n\t\t\/\/ log.Debug(\"resolved:\", a, resolved)\n\t\toutputAddrs = append(outputAddrs, resolved...)\n\t}\n\n\tif len(outputAddrs) < 1 {\n\t\treturn nil, fmt.Errorf(\"failed to specify addrs: %s\", unspecAddrs)\n\t}\n\n\tlog.Event(context.TODO(), \"interfaceListenAddresses\", func() eventlog.Loggable {\n\t\tvar addrs []string\n\t\tfor _, addr := range outputAddrs {\n\t\t\taddrs = append(addrs, addr.String())\n\t\t}\n\t\treturn eventlog.Metadata{\"addresses\": addrs}\n\t}())\n\n\tlog.Debug(\"ResolveUnspecifiedAddresses:\", unspecAddrs, ifaceAddrs, outputAddrs)\n\treturn outputAddrs, nil\n}\n\n\/\/ InterfaceAddresses returns a list of addresses associated with local machine\n\/\/ Note: we do not return link local addresses. IP loopback is ok, because we\n\/\/ may be connecting to other nodes in the same machine.\nfunc InterfaceAddresses() ([]ma.Multiaddr, error) {\n\tmaddrs, err := manet.InterfaceMultiaddrs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Debug(\"InterfaceAddresses: from manet:\", maddrs)\n\n\tvar out []ma.Multiaddr\n\tfor _, a := range maddrs {\n\t\tif !AddrUsable(a, true) { \/\/ partial\n\t\t\t\/\/ log.Debug(\"InterfaceAddresses: skipping unusable:\", a)\n\t\t\tcontinue\n\t\t}\n\n\t\tout = append(out, a)\n\t}\n\n\tlog.Debug(\"InterfaceAddresses: usable:\", out)\n\treturn out, nil\n}\n\n\/\/ AddrInList returns whether or not an address is part of a list.\n\/\/ this is useful to check if NAT is happening (or other bugs?)\nfunc AddrInList(addr ma.Multiaddr, list []ma.Multiaddr) bool {\n\tfor _, addr2 := range list {\n\t\tif addr.Equal(addr2) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ AddrIsShareableOnWAN returns whether the given address should be shareable on the\n\/\/ wide area network (wide internet).\nfunc AddrIsShareableOnWAN(addr ma.Multiaddr) bool {\n\ts := ma.Split(addr)\n\tif len(s) < 1 {\n\t\treturn false\n\t}\n\ta := s[0]\n\tif manet.IsIPLoopback(a) || manet.IsIP6LinkLocal(a) || manet.IsIPUnspecified(a) {\n\t\treturn false\n\t}\n\treturn manet.IsThinWaist(a)\n}\n\n\/\/ WANShareableAddrs filters addresses based on whether they're shareable on WAN\nfunc WANShareableAddrs(inp []ma.Multiaddr) []ma.Multiaddr {\n\treturn FilterAddrs(inp, AddrIsShareableOnWAN)\n}\n\n\/\/ Subtract filters out all addrs in b from a\nfunc Subtract(a, b []ma.Multiaddr) []ma.Multiaddr {\n\treturn FilterAddrs(a, func(m ma.Multiaddr) bool {\n\t\tfor _, bb := range b {\n\t\t\tif m.Equal(bb) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n}\n\n\/\/ CheckNATWarning checks if our observed addresses differ. if so,\n\/\/ informs the user that certain things might not work yet\nfunc CheckNATWarning(observed, expected ma.Multiaddr, listen []ma.Multiaddr) {\n\tif observed.Equal(expected) {\n\t\treturn\n\t}\n\n\tif !AddrInList(observed, listen) { \/\/ probably a nat\n\t\tlog.Warningf(natWarning, observed, listen)\n\t}\n}\n\nconst natWarning = `Remote peer observed our address to be: %s\nThe local addresses are: %s\nThus, connection is going through NAT, and other connections may fail.\n\nIPFS NAT traversal is still under development. Please bug us on github or irc to fix this.\nBaby steps: http:\/\/jbenet.static.s3.amazonaws.com\/271dfcf\/baby-steps.gif\n`\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package output contains reaction and visualization data related functionality\n\/\/\n\/\/ Copyright 2015 Markus Dittrich\n\/\/ Licensed under BSD license, see LICENSE file for details\npackage output\n\nimport (\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/haskelladdict\/mcellLite\/mol\"\n)\n\n\/\/ WriteCB writes the current molecule position to a CellBlender compatible\n\/\/ input format\n\/\/ NOTE: This function does a lot of type casting mostly due to the way\n\/\/ CellBlender format was designed. E.g., while positions are internally stored\n\/\/ as 64bit doubles, CellBlender format writes them as 32bit floats. Eventually,\n\/\/ the CellBlender format should probably be overhauled or completele redesigned.\nfunc WriteCB(molMap mol.MolMap, outPath, fileName string, iter int64) error {\n\t\/\/ if output dir does not exist we create it\n\tif err := os.MkdirAll(outPath, 0700); err != nil {\n\t\treturn fmt.Errorf(\"in writeCB: %s\", err)\n\t}\n\n\tp := fmt.Sprintf(\"%s.cellbin.%04d.dat\", fileName, iter)\n\tp = path.Join(outPath, p)\n\tfile, err := os.Create(p)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"in writeCB: %s\", err)\n\t}\n\tdefer file.Close()\n\n\t\/\/ write version info\n\tvar version uint32 = 1\n\tif err := writeUint32(file, version); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ write molecules\n\tfor sp, mols := range molMap {\n\t\t\/\/ write species info\n\t\tif err := writeUint8(file, uint8(len(sp))); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif n, err := file.Write([]byte(sp)); err != nil || len(sp) != n {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ write mol type (0 = volume molecule)\n\t\tif err := writeUint8(file, 0); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ write number of molecules and then molecule info\n\t\tif err := writeUint32(file, 3*uint32(len(mols))); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, mol := range mols {\n\t\t\tif err := writeUint32(file, math.Float32bits(float32(mol.R.X))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := writeUint32(file, math.Float32bits(float32(mol.R.Y))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := writeUint32(file, math.Float32bits(float32(mol.R.Z))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ writeUint8 write an uint8 to the provided Writer in little endian format\nfunc writeUint8(w io.Writer, i uint8) error {\n\tbuf := []byte{i}\n\tif n, err := w.Write(buf); err != nil || n != 1 {\n\t\treturn fmt.Errorf(\"in WriteUint8: %s\", err)\n\t}\n\treturn nil\n}\n\n\/\/ writeUint16 write an uint16 to the provided Writer in little endian format\nfunc writeUint16(w io.Writer, i uint16) error {\n\tbuf := make([]byte, 2)\n\tbinary.LittleEndian.PutUint16(buf, i)\n\tif n, err := w.Write(buf); err != nil || n != 2 {\n\t\treturn fmt.Errorf(\"in WriteUint16: %s\", err)\n\t}\n\treturn nil\n}\n\n\/\/ writeUint32 write an uint32 to the provided Writer in little endian format\nfunc writeUint32(w io.Writer, i uint32) error {\n\tbuf := make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(buf, i)\n\tif n, err := w.Write(buf); err != nil || n != 4 {\n\t\treturn fmt.Errorf(\"in WriteUint32: %s\", err)\n\t}\n\treturn nil\n}\n\n\/\/ writeUint64 write an uint64 to the provided Writer in little endian format\nfunc writeUint64(w io.Writer, i uint64) error {\n\tbuf := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(buf, i)\n\tif n, err := w.Write(buf); err != nil || n != 8 {\n\t\treturn fmt.Errorf(\"in WriteUint64: %s\", err)\n\t}\n\treturn nil\n}\n<commit_msg>Switch to buffered IO for CellBlender output.<commit_after>\/\/ Package output contains reaction and visualization data related functionality\n\/\/\n\/\/ Copyright 2015 Markus Dittrich\n\/\/ Licensed under BSD license, see LICENSE file for details\npackage output\n\nimport (\n\t\"bufio\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/haskelladdict\/mcellLite\/mol\"\n)\n\n\/\/ WriteCB writes the current molecule position to a CellBlender compatible\n\/\/ input format\n\/\/ NOTE: This function does a lot of type casting mostly due to the way\n\/\/ CellBlender format was designed. E.g., while positions are internally stored\n\/\/ as 64bit doubles, CellBlender format writes them as 32bit floats. Eventually,\n\/\/ the CellBlender format should probably be overhauled or completele redesigned.\nfunc WriteCB(molMap mol.MolMap, outPath, fileName string, iter int64) error {\n\t\/\/ if output dir does not exist we create it\n\tif err := os.MkdirAll(outPath, 0700); err != nil {\n\t\treturn fmt.Errorf(\"in writeCB: %s\", err)\n\t}\n\n\tp := fmt.Sprintf(\"%s.cellbin.%04d.dat\", fileName, iter)\n\tp = path.Join(outPath, p)\n\tfile, err := os.Create(p)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"in writeCB: %s\", err)\n\t}\n\tdefer file.Close()\n\n\tw := bufio.NewWriter(file)\n\n\t\/\/ write version info\n\tvar version uint32 = 1\n\tif err := writeUint32(w, version); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ write molecules\n\tfor sp, mols := range molMap {\n\t\t\/\/ write species info\n\t\tif err := writeUint8(w, uint8(len(sp))); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif n, err := w.Write([]byte(sp)); err != nil || len(sp) != n {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ write mol type (0 = volume molecule)\n\t\tif err := writeUint8(w, 0); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ write number of molecules and then molecule info\n\t\tif err := writeUint32(w, 3*uint32(len(mols))); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, mol := range mols {\n\t\t\tif err := writeUint32(w, math.Float32bits(float32(mol.R.X))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := writeUint32(w, math.Float32bits(float32(mol.R.Y))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := writeUint32(w, math.Float32bits(float32(mol.R.Z))); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ writeUint8 write an uint8 to the provided Writer in little endian format\nfunc writeUint8(w io.Writer, i uint8) error {\n\tbuf := []byte{i}\n\tif n, err := w.Write(buf); err != nil || n != 1 {\n\t\treturn fmt.Errorf(\"in WriteUint8: %s\", err)\n\t}\n\treturn nil\n}\n\n\/\/ writeUint16 write an uint16 to the provided Writer in little endian format\nfunc writeUint16(w io.Writer, i uint16) error {\n\tbuf := make([]byte, 2)\n\tbinary.LittleEndian.PutUint16(buf, i)\n\tif n, err := w.Write(buf); err != nil || n != 2 {\n\t\treturn fmt.Errorf(\"in WriteUint16: %s\", err)\n\t}\n\treturn nil\n}\n\n\/\/ writeUint32 write an uint32 to the provided Writer in little endian format\nfunc writeUint32(w io.Writer, i uint32) error {\n\tbuf := make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(buf, i)\n\tif n, err := w.Write(buf); err != nil || n != 4 {\n\t\treturn fmt.Errorf(\"in WriteUint32: %s\", err)\n\t}\n\treturn nil\n}\n\n\/\/ writeUint64 write an uint64 to the provided Writer in little endian format\nfunc writeUint64(w io.Writer, i uint64) error {\n\tbuf := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(buf, i)\n\tif n, err := w.Write(buf); err != nil || n != 8 {\n\t\treturn fmt.Errorf(\"in WriteUint64: %s\", err)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package rpc\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\/rpc\"\n\n\t\"github.com\/hashicorp\/packer\/packer\"\n)\n\n\/\/ An implementation of packer.Ui where the Ui is actually executed\n\/\/ over an RPC connection.\ntype Ui struct {\n\tclient   *rpc.Client\n\tendpoint string\n}\n\nvar _ packer.Ui = new(Ui)\n\n\/\/ UiServer wraps a packer.Ui implementation and makes it exportable\n\/\/ as part of a Golang RPC server.\ntype UiServer struct {\n\tui       packer.Ui\n\tregister func(name string, rcvr interface{}) error\n}\n\n\/\/ The arguments sent to Ui.Machine\ntype UiMachineArgs struct {\n\tCategory string\n\tArgs     []string\n}\n\nfunc (u *Ui) Ask(query string) (result string, err error) {\n\terr = u.client.Call(\"Ui.Ask\", query, &result)\n\treturn\n}\n\nfunc (u *Ui) Error(message string) {\n\tif err := u.client.Call(\"Ui.Error\", message, new(interface{})); err != nil {\n\t\tlog.Printf(\"Error in Ui RPC call: %s\", err)\n\t}\n}\n\nfunc (u *Ui) Machine(t string, args ...string) {\n\trpcArgs := &UiMachineArgs{\n\t\tCategory: t,\n\t\tArgs:     args,\n\t}\n\n\tif err := u.client.Call(\"Ui.Machine\", rpcArgs, new(interface{})); err != nil {\n\t\tlog.Printf(\"Error in Ui RPC call: %s\", err)\n\t}\n}\n\nfunc (u *Ui) Message(message string) {\n\tif err := u.client.Call(\"Ui.Message\", message, new(interface{})); err != nil {\n\t\tlog.Printf(\"Error in Ui RPC call: %s\", err)\n\t}\n}\n\nfunc (u *Ui) Say(message string) {\n\tif err := u.client.Call(\"Ui.Say\", message, new(interface{})); err != nil {\n\t\tlog.Printf(\"Error in Ui RPC call: %s\", err)\n\t}\n}\n\nfunc (u *Ui) ProgressBar() packer.ProgressBar {\n\tvar callMeMaybe string\n\tif err := u.client.Call(\"Ui.ProgressBar\", nil, &callMeMaybe); err != nil {\n\t\tlog.Printf(\"Error in Ui RPC call: %s\", err)\n\t\treturn new(packer.NoopProgressBar)\n\t}\n\n\treturn &RemoteProgressBarClient{\n\t\tid:     callMeMaybe,\n\t\tclient: u.client,\n\t}\n}\n\ntype RemoteProgressBarClient struct {\n\tid     string \/\/ TODO(azr): don't need an id any more since bar is a singleton\n\tclient *rpc.Client\n}\n\nvar _ packer.ProgressBar = new(RemoteProgressBarClient)\n\nfunc (pb *RemoteProgressBarClient) Start(total uint64) {\n\tpb.client.Call(pb.id+\".Start\", total, new(interface{}))\n}\n\nfunc (pb *RemoteProgressBarClient) Add(current uint64) {\n\tpb.client.Call(pb.id+\".Add\", current, new(interface{}))\n}\n\nfunc (pb *RemoteProgressBarClient) Finish() {\n\tpb.client.Call(pb.id+\".Finish\", nil, new(interface{}))\n}\n\nfunc (pb *RemoteProgressBarClient) NewProxyReader(r io.Reader) io.Reader {\n\treturn &packer.ProxyReader{Reader: r, ProgressBar: pb}\n}\n\nfunc (u *UiServer) Ask(query string, reply *string) (err error) {\n\t*reply, err = u.ui.Ask(query)\n\treturn\n}\n\nfunc (u *UiServer) Error(message *string, reply *interface{}) error {\n\tu.ui.Error(*message)\n\n\t*reply = nil\n\treturn nil\n}\n\nfunc (u *UiServer) Machine(args *UiMachineArgs, reply *interface{}) error {\n\tu.ui.Machine(args.Category, args.Args...)\n\n\t*reply = nil\n\treturn nil\n}\n\nfunc (u *UiServer) Message(message *string, reply *interface{}) error {\n\tu.ui.Message(*message)\n\t*reply = nil\n\treturn nil\n}\n\nfunc (u *UiServer) Say(message *string, reply *interface{}) error {\n\tu.ui.Say(*message)\n\n\t*reply = nil\n\treturn nil\n}\n\nfunc RandStringBytes(n int) string { \/\/ TODO(azr): remove before merging\n\tconst letterBytes = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\n\tb := make([]byte, n)\n\tfor i := range b {\n\t\tb[i] = letterBytes[rand.Intn(len(letterBytes))]\n\t}\n\treturn string(b)\n}\n\nfunc (u *UiServer) ProgressBar(_ *string, reply *interface{}) error {\n\tbar := u.ui.ProgressBar()\n\n\tcallbackName := RandStringBytes(6)\n\n\tlog.Printf(\"registering progressbar %s\", callbackName)\n\terr := u.register(callbackName, &RemoteProgressBarServer{bar})\n\tif err != nil {\n\t\tlog.Printf(\"failed to register a new progress bar rpc server, %s\", err)\n\t\treturn err\n\t}\n\t*reply = callbackName\n\treturn nil\n}\n\ntype RemoteProgressBarServer struct {\n\tpb packer.ProgressBar\n}\n\nfunc (pb *RemoteProgressBarServer) Finish(_ string, _ *interface{}) error {\n\tpb.pb.Finish()\n\treturn nil\n}\n\nfunc (pb *RemoteProgressBarServer) Start(total uint64, _ *interface{}) error {\n\tpb.pb.Start(total)\n\treturn nil\n}\n\nfunc (pb *RemoteProgressBarServer) Add(current uint64, _ *interface{}) error {\n\tpb.pb.Add(current)\n\treturn nil\n}\n<commit_msg>use freshly merged random.AlphaNum instead of our own random<commit_after>package rpc\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"net\/rpc\"\n\n\t\"github.com\/hashicorp\/packer\/common\/random\"\n\n\t\"github.com\/hashicorp\/packer\/packer\"\n)\n\n\/\/ An implementation of packer.Ui where the Ui is actually executed\n\/\/ over an RPC connection.\ntype Ui struct {\n\tclient   *rpc.Client\n\tendpoint string\n}\n\nvar _ packer.Ui = new(Ui)\n\n\/\/ UiServer wraps a packer.Ui implementation and makes it exportable\n\/\/ as part of a Golang RPC server.\ntype UiServer struct {\n\tui       packer.Ui\n\tregister func(name string, rcvr interface{}) error\n}\n\n\/\/ The arguments sent to Ui.Machine\ntype UiMachineArgs struct {\n\tCategory string\n\tArgs     []string\n}\n\nfunc (u *Ui) Ask(query string) (result string, err error) {\n\terr = u.client.Call(\"Ui.Ask\", query, &result)\n\treturn\n}\n\nfunc (u *Ui) Error(message string) {\n\tif err := u.client.Call(\"Ui.Error\", message, new(interface{})); err != nil {\n\t\tlog.Printf(\"Error in Ui RPC call: %s\", err)\n\t}\n}\n\nfunc (u *Ui) Machine(t string, args ...string) {\n\trpcArgs := &UiMachineArgs{\n\t\tCategory: t,\n\t\tArgs:     args,\n\t}\n\n\tif err := u.client.Call(\"Ui.Machine\", rpcArgs, new(interface{})); err != nil {\n\t\tlog.Printf(\"Error in Ui RPC call: %s\", err)\n\t}\n}\n\nfunc (u *Ui) Message(message string) {\n\tif err := u.client.Call(\"Ui.Message\", message, new(interface{})); err != nil {\n\t\tlog.Printf(\"Error in Ui RPC call: %s\", err)\n\t}\n}\n\nfunc (u *Ui) Say(message string) {\n\tif err := u.client.Call(\"Ui.Say\", message, new(interface{})); err != nil {\n\t\tlog.Printf(\"Error in Ui RPC call: %s\", err)\n\t}\n}\n\nfunc (u *Ui) ProgressBar() packer.ProgressBar {\n\tvar callMeMaybe string\n\tif err := u.client.Call(\"Ui.ProgressBar\", nil, &callMeMaybe); err != nil {\n\t\tlog.Printf(\"Error in Ui RPC call: %s\", err)\n\t\treturn new(packer.NoopProgressBar)\n\t}\n\n\treturn &RemoteProgressBarClient{\n\t\tid:     callMeMaybe,\n\t\tclient: u.client,\n\t}\n}\n\ntype RemoteProgressBarClient struct {\n\tid     string \/\/ TODO(azr): don't need an id any more since bar is a singleton\n\tclient *rpc.Client\n}\n\nvar _ packer.ProgressBar = new(RemoteProgressBarClient)\n\nfunc (pb *RemoteProgressBarClient) Start(total uint64) {\n\tpb.client.Call(pb.id+\".Start\", total, new(interface{}))\n}\n\nfunc (pb *RemoteProgressBarClient) Add(current uint64) {\n\tpb.client.Call(pb.id+\".Add\", current, new(interface{}))\n}\n\nfunc (pb *RemoteProgressBarClient) Finish() {\n\tpb.client.Call(pb.id+\".Finish\", nil, new(interface{}))\n}\n\nfunc (pb *RemoteProgressBarClient) NewProxyReader(r io.Reader) io.Reader {\n\treturn &packer.ProxyReader{Reader: r, ProgressBar: pb}\n}\n\nfunc (u *UiServer) Ask(query string, reply *string) (err error) {\n\t*reply, err = u.ui.Ask(query)\n\treturn\n}\n\nfunc (u *UiServer) Error(message *string, reply *interface{}) error {\n\tu.ui.Error(*message)\n\n\t*reply = nil\n\treturn nil\n}\n\nfunc (u *UiServer) Machine(args *UiMachineArgs, reply *interface{}) error {\n\tu.ui.Machine(args.Category, args.Args...)\n\n\t*reply = nil\n\treturn nil\n}\n\nfunc (u *UiServer) Message(message *string, reply *interface{}) error {\n\tu.ui.Message(*message)\n\t*reply = nil\n\treturn nil\n}\n\nfunc (u *UiServer) Say(message *string, reply *interface{}) error {\n\tu.ui.Say(*message)\n\n\t*reply = nil\n\treturn nil\n}\n\nfunc (u *UiServer) ProgressBar(_ *string, reply *interface{}) error {\n\tbar := u.ui.ProgressBar()\n\n\tcallbackName := random.AlphaNum(6)\n\n\tlog.Printf(\"registering progressbar %s\", callbackName)\n\terr := u.register(callbackName, &RemoteProgressBarServer{bar})\n\tif err != nil {\n\t\tlog.Printf(\"failed to register a new progress bar rpc server, %s\", err)\n\t\treturn err\n\t}\n\t*reply = callbackName\n\treturn nil\n}\n\ntype RemoteProgressBarServer struct {\n\tpb packer.ProgressBar\n}\n\nfunc (pb *RemoteProgressBarServer) Finish(_ string, _ *interface{}) error {\n\tpb.pb.Finish()\n\treturn nil\n}\n\nfunc (pb *RemoteProgressBarServer) Start(total uint64, _ *interface{}) error {\n\tpb.pb.Start(total)\n\treturn nil\n}\n\nfunc (pb *RemoteProgressBarServer) Add(current uint64, _ *interface{}) error {\n\tpb.pb.Add(current)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\npackage toolchain\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"mynewt.apache.org\/newt\/util\"\n)\n\ntype DepTracker struct {\n\t\/\/ Most recent .o modification time.\n\tMostRecent time.Time\n\n\tcompiler *Compiler\n}\n\nfunc NewDepTracker(c *Compiler) DepTracker {\n\ttracker := DepTracker{\n\t\tMostRecent: time.Unix(0, 0),\n\t\tcompiler:   c,\n\t}\n\n\treturn tracker\n}\n\n\/\/ @return string               The name of the dependent file (i.e., the first\n\/\/                                  .o file encountered).\n\/\/ @return []string             Populated with the dependencies' filenames.\nfunc parseDepsLine(line string) (string, []string, error) {\n\ttokens := strings.Fields(line)\n\tif len(tokens) == 0 {\n\t\treturn \"\", nil, nil\n\t}\n\n\tdFileTok := tokens[0]\n\tif dFileTok[len(dFileTok)-1:] != \":\" {\n\t\treturn \"\", nil, util.NewNewtError(\"Invalid Makefile dependency file; \" +\n\t\t\t\"line missing ':'\")\n\t}\n\n\tdFileName := dFileTok[:len(dFileTok)-1]\n\treturn dFileName, tokens[1:], nil\n\n}\n\n\/\/ Parses a dependency (.d) file generated by gcc.  On success, the returned\n\/\/ string array is populated with the dependency filenames.  This function\n\/\/ expects each line of a dependency file to have the following format:\n\/\/\n\/\/ <file>.o: <file>.c a.h b.h c.h \\\n\/\/  d.h e.h f.h\n\/\/\n\/\/ Only the first dependent object(<file>.o) is considered.\n\/\/\n\/\/ @return []string             Populated with the dependencies' filenames.\nfunc ParseDepsFile(filename string) ([]string, error) {\n\tlines, err := util.ReadLines(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(lines) == 0 {\n\t\treturn []string{}, nil\n\t}\n\n\tvar dFile string\n\tallDeps := []string{}\n\tfor _, line := range lines {\n\t\tsrc, deps, err := parseDepsLine(line)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif dFile == \"\" {\n\t\t\tdFile = src\n\t\t}\n\n\t\tif src == dFile {\n\t\t\tallDeps = append(allDeps, deps...)\n\t\t}\n\t}\n\n\treturn allDeps, nil\n}\n\n\/\/ Updates the dependency tracker's most recent timestamp according to the\n\/\/ modification time of the specified file.  If the specified file is older\n\/\/ than the tracker's currently most-recent time, this function has no effect.\nfunc (tracker *DepTracker) ProcessFileTime(file string) error {\n\tmodTime, err := util.FileModificationTime(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif modTime.After(tracker.MostRecent) {\n\t\ttracker.MostRecent = modTime\n\t}\n\n\treturn nil\n}\n\n\/\/ Determines if a file was previously built with a command line invocation\n\/\/ different from the one specified.\n\/\/\n\/\/ @param dstFile               The output file whose build invocation is being\n\/\/                                  tested.\n\/\/ @param cmd                   The command that would be used to generate the\n\/\/                                  specified destination file.\n\/\/\n\/\/ @return                      true if the command has changed or if the\n\/\/                                  destination file was never built;\n\/\/                              false otherwise.\nfunc commandHasChanged(dstFile string, cmd string) bool {\n\tcmdFile := dstFile + \".cmd\"\n\tprevCmd, err := ioutil.ReadFile(cmdFile)\n\tif err != nil {\n\t\treturn true\n\t}\n\n\treturn bytes.Compare(prevCmd, []byte(cmd)) != 0\n}\n\n\/\/ Determines if the specified C or assembly file needs to be built.  A compile\n\/\/ is required if any of the following is true:\n\/\/     * The destination object file does not exist.\n\/\/     * The existing object file was built with a different compiler\n\/\/       invocation.\n\/\/     * The source file has a newer modification time than the object file.\n\/\/     * One or more included header files has a newer modification time than\n\/\/       the object file.\nfunc (tracker *DepTracker) CompileRequired(srcFile string,\n\tcompilerType int) (bool, error) {\n\n\tobjFile := tracker.compiler.DstDir() + \"\/\" +\n\t\tstrings.TrimSuffix(srcFile, filepath.Ext(srcFile)) + \".o\"\n\tdepFile := tracker.compiler.DstDir() + \"\/\" +\n\t\tstrings.TrimSuffix(srcFile, filepath.Ext(srcFile)) + \".d\"\n\n\t\/\/ If the object was previously built with a different set of options, a\n\t\/\/ rebuild is necessary.\n\tcmd, err := tracker.compiler.CompileFileCmd(srcFile, compilerType)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif commandHasChanged(objFile, cmd) {\n\t\tutil.StatusMessage(util.VERBOSITY_VERBOSE, \"%s - rebuild required; \"+\n\t\t\t\"different command\\n\", srcFile)\n\t\terr := tracker.compiler.GenDepsForFile(srcFile)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn true, nil\n\t}\n\n\tsrcModTime, err := util.FileModificationTime(srcFile)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tobjModTime, err := util.FileModificationTime(objFile)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ If the object doesn't exist or is older than the source file, a build is\n\t\/\/ required; no need to check dependencies.\n\tif srcModTime.After(objModTime) {\n\t\tutil.StatusMessage(util.VERBOSITY_VERBOSE, \"%s - rebuild required; \"+\n\t\t\t\"source newer than obj\\n\", srcFile)\n\t\treturn true, nil\n\t}\n\n\t\/\/ Determine if the dependency (.d) file needs to be generated.  If it\n\t\/\/ doesn't exist or is older than the source file, it is out of date and\n\t\/\/ needs to be created.\n\tdepModTime, err := util.FileModificationTime(depFile)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif srcModTime.After(depModTime) {\n\t\terr := tracker.compiler.GenDepsForFile(srcFile)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\t\/\/ Extract the dependency filenames from the dependency file.\n\tdeps, err := ParseDepsFile(depFile)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ Check if any dependencies are newer than the destination object file.\n\tfor _, dep := range deps {\n\t\tif util.NodeNotExist(dep) {\n\t\t\t\/\/ The dependency has been deleted; the .d file is out of date.\n\t\t\t\/\/ Recreate the dependency file and repeat this entire function.\n\t\t\terr := tracker.compiler.GenDepsForFile(srcFile)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\treturn tracker.CompileRequired(srcFile, compilerType)\n\t\t} else {\n\t\t\tdepModTime, err = util.FileModificationTime(dep)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\n\t\tif depModTime.After(objModTime) {\n\t\t\tutil.StatusMessage(util.VERBOSITY_VERBOSE, \"%s - rebuild required; obj older than dependency (%s)\\n\", srcFile, dep)\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n\n\/\/ Determines if the specified static library needs to be rearchived.  The\n\/\/ library needs to be archived if any of the following is true:\n\/\/     * The destination library file does not exist.\n\/\/     * The existing library file was built with a different compiler\n\/\/       invocation.\n\/\/     * One or more source object files has a newer modification time than the\n\/\/       library file.\nfunc (tracker *DepTracker) ArchiveRequired(archiveFile string,\n\tobjFiles []string) (bool, error) {\n\n\t\/\/ If the archive was previously built with a different set of options, a\n\t\/\/ rebuild is required.\n\tcmd := tracker.compiler.CompileArchiveCmd(archiveFile, objFiles)\n\tif commandHasChanged(archiveFile, cmd) {\n\t\treturn true, nil\n\t}\n\n\t\/\/ If the archive doesn't exist or is older than any object file, a rebuild\n\t\/\/ is required.\n\taModTime, err := util.FileModificationTime(archiveFile)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif tracker.MostRecent.After(aModTime) {\n\t\treturn true, nil\n\t}\n\n\t\/\/ The library is up to date.\n\treturn false, nil\n}\n\n\/\/ Determines if the specified elf file needs to be linked.  Linking is\n\/\/ necessary if the elf file does not exist or has an older modification time\n\/\/ than any source object or library file.\n\/\/ Determines if the specified static library needs to be rearchived.  The\n\/\/ library needs to be archived if any of the following is true:\n\/\/     * The destination library file does not exist.\n\/\/     * The existing library file was built with a different compiler\n\/\/       invocation.\n\/\/     * One or more source object files has a newer modification time than the\n\/\/       library file.\nfunc (tracker *DepTracker) LinkRequired(dstFile string,\n\toptions map[string]bool, objFiles []string) (bool, error) {\n\n\t\/\/ If the elf file was previously built with a different set of options, a\n\t\/\/ rebuild is required.\n\tcmd := tracker.compiler.CompileBinaryCmd(dstFile, options, objFiles)\n\tif commandHasChanged(dstFile, cmd) {\n\t\treturn true, nil\n\t}\n\n\t\/\/ If the elf file doesn't exist or is older than any input file, a rebuild\n\t\/\/ is required.\n\tdstModTime, err := util.FileModificationTime(dstFile)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ Check timestamp of each .o file in the project.\n\tif tracker.MostRecent.After(dstModTime) {\n\t\treturn true, nil\n\t}\n\n\t\/\/ Check timestamp of the linker script and all input libraries.\n\tif tracker.compiler.LinkerScript != \"\" {\n\t\tobjFiles = append(objFiles, tracker.compiler.LinkerScript)\n\t}\n\tfor _, obj := range objFiles {\n\t\tobjModTime, err := util.FileModificationTime(obj)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif objModTime.After(dstModTime) {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n<commit_msg>newt tool - Fix deadlock due to deleted header<commit_after>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\npackage toolchain\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"mynewt.apache.org\/newt\/util\"\n)\n\ntype DepTracker struct {\n\t\/\/ Most recent .o modification time.\n\tMostRecent time.Time\n\n\tcompiler *Compiler\n}\n\nfunc NewDepTracker(c *Compiler) DepTracker {\n\ttracker := DepTracker{\n\t\tMostRecent: time.Unix(0, 0),\n\t\tcompiler:   c,\n\t}\n\n\treturn tracker\n}\n\n\/\/ @return string               The name of the dependent file (i.e., the first\n\/\/                                  .o file encountered).\n\/\/ @return []string             Populated with the dependencies' filenames.\nfunc parseDepsLine(line string) (string, []string, error) {\n\ttokens := strings.Fields(line)\n\tif len(tokens) == 0 {\n\t\treturn \"\", nil, nil\n\t}\n\n\tdFileTok := tokens[0]\n\tif dFileTok[len(dFileTok)-1:] != \":\" {\n\t\treturn \"\", nil, util.NewNewtError(\"Invalid Makefile dependency file; \" +\n\t\t\t\"line missing ':'\")\n\t}\n\n\tdFileName := dFileTok[:len(dFileTok)-1]\n\treturn dFileName, tokens[1:], nil\n\n}\n\n\/\/ Parses a dependency (.d) file generated by gcc.  On success, the returned\n\/\/ string array is populated with the dependency filenames.  This function\n\/\/ expects each line of a dependency file to have the following format:\n\/\/\n\/\/ <file>.o: <file>.c a.h b.h c.h \\\n\/\/  d.h e.h f.h\n\/\/\n\/\/ Only the first dependent object(<file>.o) is considered.\n\/\/\n\/\/ @return []string             Populated with the dependencies' filenames.\nfunc ParseDepsFile(filename string) ([]string, error) {\n\tlines, err := util.ReadLines(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(lines) == 0 {\n\t\treturn []string{}, nil\n\t}\n\n\tvar dFile string\n\tallDeps := []string{}\n\tfor _, line := range lines {\n\t\tsrc, deps, err := parseDepsLine(line)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif dFile == \"\" {\n\t\t\tdFile = src\n\t\t}\n\n\t\tif src == dFile {\n\t\t\tallDeps = append(allDeps, deps...)\n\t\t}\n\t}\n\n\treturn allDeps, nil\n}\n\n\/\/ Updates the dependency tracker's most recent timestamp according to the\n\/\/ modification time of the specified file.  If the specified file is older\n\/\/ than the tracker's currently most-recent time, this function has no effect.\nfunc (tracker *DepTracker) ProcessFileTime(file string) error {\n\tmodTime, err := util.FileModificationTime(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif modTime.After(tracker.MostRecent) {\n\t\ttracker.MostRecent = modTime\n\t}\n\n\treturn nil\n}\n\n\/\/ Determines if a file was previously built with a command line invocation\n\/\/ different from the one specified.\n\/\/\n\/\/ @param dstFile               The output file whose build invocation is being\n\/\/                                  tested.\n\/\/ @param cmd                   The command that would be used to generate the\n\/\/                                  specified destination file.\n\/\/\n\/\/ @return                      true if the command has changed or if the\n\/\/                                  destination file was never built;\n\/\/                              false otherwise.\nfunc commandHasChanged(dstFile string, cmd string) bool {\n\tcmdFile := dstFile + \".cmd\"\n\tprevCmd, err := ioutil.ReadFile(cmdFile)\n\tif err != nil {\n\t\treturn true\n\t}\n\n\treturn bytes.Compare(prevCmd, []byte(cmd)) != 0\n}\n\n\/\/ Determines if the specified C or assembly file needs to be built.  A compile\n\/\/ is required if any of the following is true:\n\/\/     * The destination object file does not exist.\n\/\/     * The existing object file was built with a different compiler\n\/\/       invocation.\n\/\/     * The source file has a newer modification time than the object file.\n\/\/     * One or more included header files has a newer modification time than\n\/\/       the object file.\nfunc (tracker *DepTracker) CompileRequired(srcFile string,\n\tcompilerType int) (bool, error) {\n\n\tobjFile := tracker.compiler.DstDir() + \"\/\" +\n\t\tstrings.TrimSuffix(srcFile, filepath.Ext(srcFile)) + \".o\"\n\tdepFile := tracker.compiler.DstDir() + \"\/\" +\n\t\tstrings.TrimSuffix(srcFile, filepath.Ext(srcFile)) + \".d\"\n\n\t\/\/ If the object was previously built with a different set of options, a\n\t\/\/ rebuild is necessary.\n\tcmd, err := tracker.compiler.CompileFileCmd(srcFile, compilerType)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif commandHasChanged(objFile, cmd) {\n\t\tutil.StatusMessage(util.VERBOSITY_VERBOSE, \"%s - rebuild required; \"+\n\t\t\t\"different command\\n\", srcFile)\n\t\terr := tracker.compiler.GenDepsForFile(srcFile)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\treturn true, nil\n\t}\n\n\tsrcModTime, err := util.FileModificationTime(srcFile)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tobjModTime, err := util.FileModificationTime(objFile)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ If the object doesn't exist or is older than the source file, a build is\n\t\/\/ required; no need to check dependencies.\n\tif srcModTime.After(objModTime) {\n\t\tutil.StatusMessage(util.VERBOSITY_VERBOSE, \"%s - rebuild required; \"+\n\t\t\t\"source newer than obj\\n\", srcFile)\n\t\treturn true, nil\n\t}\n\n\t\/\/ Determine if the dependency (.d) file needs to be generated.  If it\n\t\/\/ doesn't exist or is older than the source file, it is out of date and\n\t\/\/ needs to be created.\n\tdepModTime, err := util.FileModificationTime(depFile)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif srcModTime.After(depModTime) {\n\t\terr := tracker.compiler.GenDepsForFile(srcFile)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t}\n\n\t\/\/ Extract the dependency filenames from the dependency file.\n\tdeps, err := ParseDepsFile(depFile)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ Check if any dependencies are newer than the destination object file.\n\tfor _, dep := range deps {\n\t\tif util.NodeNotExist(dep) {\n\t\t\t\/\/ The dependency has been deleted; a rebuild is required.\n\t\t\treturn true, nil\n\t\t} else {\n\t\t\tdepModTime, err = util.FileModificationTime(dep)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t}\n\n\t\tif depModTime.After(objModTime) {\n\t\t\tutil.StatusMessage(util.VERBOSITY_VERBOSE, \"%s - rebuild required; obj older than dependency (%s)\\n\", srcFile, dep)\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n\n\/\/ Determines if the specified static library needs to be rearchived.  The\n\/\/ library needs to be archived if any of the following is true:\n\/\/     * The destination library file does not exist.\n\/\/     * The existing library file was built with a different compiler\n\/\/       invocation.\n\/\/     * One or more source object files has a newer modification time than the\n\/\/       library file.\nfunc (tracker *DepTracker) ArchiveRequired(archiveFile string,\n\tobjFiles []string) (bool, error) {\n\n\t\/\/ If the archive was previously built with a different set of options, a\n\t\/\/ rebuild is required.\n\tcmd := tracker.compiler.CompileArchiveCmd(archiveFile, objFiles)\n\tif commandHasChanged(archiveFile, cmd) {\n\t\treturn true, nil\n\t}\n\n\t\/\/ If the archive doesn't exist or is older than any object file, a rebuild\n\t\/\/ is required.\n\taModTime, err := util.FileModificationTime(archiveFile)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif tracker.MostRecent.After(aModTime) {\n\t\treturn true, nil\n\t}\n\n\t\/\/ The library is up to date.\n\treturn false, nil\n}\n\n\/\/ Determines if the specified elf file needs to be linked.  Linking is\n\/\/ necessary if the elf file does not exist or has an older modification time\n\/\/ than any source object or library file.\n\/\/ Determines if the specified static library needs to be rearchived.  The\n\/\/ library needs to be archived if any of the following is true:\n\/\/     * The destination library file does not exist.\n\/\/     * The existing library file was built with a different compiler\n\/\/       invocation.\n\/\/     * One or more source object files has a newer modification time than the\n\/\/       library file.\nfunc (tracker *DepTracker) LinkRequired(dstFile string,\n\toptions map[string]bool, objFiles []string) (bool, error) {\n\n\t\/\/ If the elf file was previously built with a different set of options, a\n\t\/\/ rebuild is required.\n\tcmd := tracker.compiler.CompileBinaryCmd(dstFile, options, objFiles)\n\tif commandHasChanged(dstFile, cmd) {\n\t\treturn true, nil\n\t}\n\n\t\/\/ If the elf file doesn't exist or is older than any input file, a rebuild\n\t\/\/ is required.\n\tdstModTime, err := util.FileModificationTime(dstFile)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ Check timestamp of each .o file in the project.\n\tif tracker.MostRecent.After(dstModTime) {\n\t\treturn true, nil\n\t}\n\n\t\/\/ Check timestamp of the linker script and all input libraries.\n\tif tracker.compiler.LinkerScript != \"\" {\n\t\tobjFiles = append(objFiles, tracker.compiler.LinkerScript)\n\t}\n\tfor _, obj := range objFiles {\n\t\tobjModTime, err := util.FileModificationTime(obj)\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tif objModTime.After(dstModTime) {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Vanadium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage monitoring\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\n\t\"code.google.com\/p\/goauth2\/oauth\/jwt\"\n\t\"google.golang.org\/api\/cloudmonitoring\/v2beta2\"\n)\n\nconst (\n\tcustomMetricPrefix = \"custom.cloudmonitoring.googleapis.com\"\n)\n\n\/\/ CustomMetricDescriptors is a map from metric's short names to their\n\/\/ MetricDescriptor definitions.\nvar CustomMetricDescriptors = map[string]*cloudmonitoring.MetricDescriptor{\n\t\/\/ Custom metric for recording check latency of vanadium production services.\n\t\"service-latency\": createMetric(\"service\/latency\", \"The check latency (ms) of vanadium production services.\", \"double\"),\n\n\t\/\/ Custom metric for recording various counters of vanadium production services.\n\t\"service-counters\": createMetric(\"service\/counters\", \"Various counters of vanadium production services.\", \"double\"),\n\n\t\/\/ Custom metric for recording gce instance stats.\n\t\"gce-instance\": createMetric(\"gce-instance\/stats\", \"Various stats for GCE instances.\", \"double\"),\n\n\t\/\/ Custom metric for recording nginx stats.\n\t\"nginx\": createMetric(\"nginx\/stats\", \"Various stats for Nginx server.\", \"double\"),\n}\n\nfunc createMetric(metricType, description, valueType string) *cloudmonitoring.MetricDescriptor {\n\treturn &cloudmonitoring.MetricDescriptor{\n\t\tName:        fmt.Sprintf(\"%s\/v\/%s\", customMetricPrefix, metricType),\n\t\tDescription: description,\n\t\tTypeDescriptor: &cloudmonitoring.MetricDescriptorTypeDescriptor{\n\t\t\tMetricType: \"gauge\",\n\t\t\tValueType:  valueType,\n\t\t},\n\t\tLabels: []*cloudmonitoring.MetricDescriptorLabelDescriptor{\n\t\t\t&cloudmonitoring.MetricDescriptorLabelDescriptor{\n\t\t\t\tKey:         fmt.Sprintf(\"%s\/gce-instance\", customMetricPrefix),\n\t\t\t\tDescription: \"The name of the GCE instance associated with this metric.\",\n\t\t\t},\n\t\t\t&cloudmonitoring.MetricDescriptorLabelDescriptor{\n\t\t\t\tKey:         fmt.Sprintf(\"%s\/gce-zone\", customMetricPrefix),\n\t\t\t\tDescription: \"The zone of the GCE instance associated with this metric.\",\n\t\t\t},\n\t\t\t&cloudmonitoring.MetricDescriptorLabelDescriptor{\n\t\t\t\tKey:         fmt.Sprintf(\"%s\/metric-name\", customMetricPrefix),\n\t\t\t\tDescription: \"The name of the metric.\",\n\t\t\t},\n\t\t},\n\t}\n}\n\n\/\/ Authenticate authenticates the given service account's email with the given\n\/\/ key. If successful, it returns a service object that can be used in GCM API\n\/\/ calls.\nfunc Authenticate(serviceAccountEmail, keyFilePath string) (*cloudmonitoring.Service, error) {\n\tbytes, err := ioutil.ReadFile(keyFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ReadFile(%s) failed: %v\", keyFilePath, err)\n\t}\n\n\ttoken := jwt.NewToken(serviceAccountEmail, cloudmonitoring.MonitoringScope, bytes)\n\ttransport, err := jwt.NewTransport(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewTransport() failed: %v\", err)\n\t}\n\tc := transport.Client()\n\ts, err := cloudmonitoring.New(c)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"New() failed: %v\", err)\n\t}\n\treturn s, nil\n}\n<commit_msg>devtools\/vmon: send rpc-load results to GCM.<commit_after>\/\/ Copyright 2015 The Vanadium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage monitoring\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\n\t\"code.google.com\/p\/goauth2\/oauth\/jwt\"\n\t\"google.golang.org\/api\/cloudmonitoring\/v2beta2\"\n)\n\nconst (\n\tcustomMetricPrefix = \"custom.cloudmonitoring.googleapis.com\"\n)\n\n\/\/ CustomMetricDescriptors is a map from metric's short names to their\n\/\/ MetricDescriptor definitions.\nvar CustomMetricDescriptors = map[string]*cloudmonitoring.MetricDescriptor{\n\t\/\/ Custom metric for recording check latency of vanadium production services.\n\t\"service-latency\": createMetric(\"service\/latency\", \"The check latency (ms) of vanadium production services.\", \"double\", true),\n\n\t\/\/ Custom metric for recording various counters of vanadium production services.\n\t\"service-counters\": createMetric(\"service\/counters\", \"Various counters of vanadium production services.\", \"double\", true),\n\n\t\/\/ Custom metric for recording gce instance stats.\n\t\"gce-instance\": createMetric(\"gce-instance\/stats\", \"Various stats for GCE instances.\", \"double\", true),\n\n\t\/\/ Custom metric for recording nginx stats.\n\t\"nginx\": createMetric(\"nginx\/stats\", \"Various stats for Nginx server.\", \"double\", true),\n\n\t\/\/ Custom metric for rpc load tests.\n\t\"rpc-load-test\": createMetric(\"rpc-load-test\", \"Results of rpc load test\", \"double\", false),\n}\n\nfunc createMetric(metricType, description, valueType string, includeGCELabels bool) *cloudmonitoring.MetricDescriptor {\n\tlabels := []*cloudmonitoring.MetricDescriptorLabelDescriptor{\n\t\t&cloudmonitoring.MetricDescriptorLabelDescriptor{\n\t\t\tKey:         fmt.Sprintf(\"%s\/metric-name\", customMetricPrefix),\n\t\t\tDescription: \"The name of the metric.\",\n\t\t},\n\t}\n\tif includeGCELabels {\n\t\tlabels = append(labels, &cloudmonitoring.MetricDescriptorLabelDescriptor{\n\t\t\tKey:         fmt.Sprintf(\"%s\/gce-instance\", customMetricPrefix),\n\t\t\tDescription: \"The name of the GCE instance associated with this metric.\",\n\t\t}, &cloudmonitoring.MetricDescriptorLabelDescriptor{\n\t\t\tKey:         fmt.Sprintf(\"%s\/gce-zone\", customMetricPrefix),\n\t\t\tDescription: \"The zone of the GCE instance associated with this metric.\",\n\t\t})\n\t}\n\n\treturn &cloudmonitoring.MetricDescriptor{\n\t\tName:        fmt.Sprintf(\"%s\/v\/%s\", customMetricPrefix, metricType),\n\t\tDescription: description,\n\t\tTypeDescriptor: &cloudmonitoring.MetricDescriptorTypeDescriptor{\n\t\t\tMetricType: \"gauge\",\n\t\t\tValueType:  valueType,\n\t\t},\n\t\tLabels: labels,\n\t}\n}\n\n\/\/ Authenticate authenticates the given service account's email with the given\n\/\/ key. If successful, it returns a service object that can be used in GCM API\n\/\/ calls.\nfunc Authenticate(serviceAccountEmail, keyFilePath string) (*cloudmonitoring.Service, error) {\n\tbytes, err := ioutil.ReadFile(keyFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ReadFile(%s) failed: %v\", keyFilePath, err)\n\t}\n\n\ttoken := jwt.NewToken(serviceAccountEmail, cloudmonitoring.MonitoringScope, bytes)\n\ttransport, err := jwt.NewTransport(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"NewTransport() failed: %v\", err)\n\t}\n\tc := transport.Client()\n\ts, err := cloudmonitoring.New(c)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"New() failed: %v\", err)\n\t}\n\treturn s, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package event provides support for event based telemetry.\npackage event\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype eventType uint8\n\nconst (\n\tLogType = eventType(iota)\n\tStartSpanType\n\tEndSpanType\n\tLabelType\n\tDetachType\n\tRecordType\n)\n\ntype Event struct {\n\ttyp     eventType\n\tAt      time.Time\n\tMessage string\n\tError   error\n\n\ttags []Tag\n}\n\nfunc (e Event) IsLog() bool       { return e.typ == LogType }\nfunc (e Event) IsEndSpan() bool   { return e.typ == EndSpanType }\nfunc (e Event) IsStartSpan() bool { return e.typ == StartSpanType }\nfunc (e Event) IsLabel() bool     { return e.typ == LabelType }\nfunc (e Event) IsDetach() bool    { return e.typ == DetachType }\nfunc (e Event) IsRecord() bool    { return e.typ == RecordType }\n\nfunc (e Event) Format(f fmt.State, r rune) {\n\tif !e.At.IsZero() {\n\t\tfmt.Fprint(f, e.At.Format(\"2006\/01\/02 15:04:05 \"))\n\t}\n\tfmt.Fprint(f, e.Message)\n\tif e.Error != nil {\n\t\tif f.Flag('+') {\n\t\t\tfmt.Fprintf(f, \": %+v\", e.Error)\n\t\t} else {\n\t\t\tfmt.Fprintf(f, \": %v\", e.Error)\n\t\t}\n\t}\n\tfor it := e.Tags(); it.Valid(); it.Advance() {\n\t\ttag := it.Tag()\n\t\tfmt.Fprintf(f, \"\\n\\t%s = %v\", tag.Key.Name(), tag.Value)\n\t}\n}\n\nfunc (ev Event) Tags() TagIterator {\n\tif len(ev.tags) == 0 {\n\t\treturn TagIterator{}\n\t}\n\treturn NewTagIterator(ev.tags...)\n}\n\nfunc (ev Event) Map() TagMap {\n\treturn NewTagMap(ev.tags...)\n}\n<commit_msg>internal\/telemetry: normalize the event reciever names to all use ev<commit_after>\/\/ Copyright 2019 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Package event provides support for event based telemetry.\npackage event\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype eventType uint8\n\nconst (\n\tLogType = eventType(iota)\n\tStartSpanType\n\tEndSpanType\n\tLabelType\n\tDetachType\n\tRecordType\n)\n\ntype Event struct {\n\ttyp     eventType\n\tAt      time.Time\n\tMessage string\n\tError   error\n\n\ttags []Tag\n}\n\nfunc (ev Event) IsLog() bool       { return ev.typ == LogType }\nfunc (ev Event) IsEndSpan() bool   { return ev.typ == EndSpanType }\nfunc (ev Event) IsStartSpan() bool { return ev.typ == StartSpanType }\nfunc (ev Event) IsLabel() bool     { return ev.typ == LabelType }\nfunc (ev Event) IsDetach() bool    { return ev.typ == DetachType }\nfunc (ev Event) IsRecord() bool    { return ev.typ == RecordType }\n\nfunc (ev Event) Format(f fmt.State, r rune) {\n\tif !ev.At.IsZero() {\n\t\tfmt.Fprint(f, ev.At.Format(\"2006\/01\/02 15:04:05 \"))\n\t}\n\tfmt.Fprint(f, ev.Message)\n\tif ev.Error != nil {\n\t\tif f.Flag('+') {\n\t\t\tfmt.Fprintf(f, \": %+v\", ev.Error)\n\t\t} else {\n\t\t\tfmt.Fprintf(f, \": %v\", ev.Error)\n\t\t}\n\t}\n\tfor it := ev.Tags(); it.Valid(); it.Advance() {\n\t\ttag := it.Tag()\n\t\tfmt.Fprintf(f, \"\\n\\t%s = %v\", tag.Key.Name(), tag.Value)\n\t}\n}\n\nfunc (ev Event) Tags() TagIterator {\n\tif len(ev.tags) == 0 {\n\t\treturn TagIterator{}\n\t}\n\treturn NewTagIterator(ev.tags...)\n}\n\nfunc (ev Event) Map() TagMap {\n\treturn NewTagMap(ev.tags...)\n}\n<|endoftext|>"}
{"text":"<commit_before>package connections\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/websocket\"\n\t\"github.com\/pquerna\/ffjson\/ffjson\"\n\t\"github.com\/sirupsen\/logrus\"\n\n\t\"github.com\/ivan1993spb\/snake-server\/broadcast\"\n\t\"github.com\/ivan1993spb\/snake-server\/game\"\n)\n\nconst (\n\tchanBroadcastBuffer  = 128\n\tchanGameEventsBuffer = 8192\n\tchanBytesProxyBuffer = 8192\n\tchanBytesOutBuffer   = 8192\n\n\tchanEncodeGroupMessageBuffer = 8192\n\n\tsendPreparedMessageTimeout = time.Millisecond * 50\n\n\tbroadcastOutputMessageBufferMonitoringDelay = time.Second * 10\n\tgameOutputMessageBufferMonitoringDelay      = time.Second * 10\n\tencodeGroupMessageBufferMonitoringDelay     = time.Second * 10\n\tpreparedMessageBufferMonitoringDelay        = time.Second * 10\n)\n\ntype ConnectionGroup struct {\n\tlimit      int\n\tcounter    int\n\tcounterMux *sync.RWMutex\n\n\tlogger logrus.FieldLogger\n\n\tgame      *game.Game\n\tbroadcast *broadcast.GroupBroadcast\n\n\tchs    []chan *websocket.PreparedMessage\n\tchsMux *sync.RWMutex\n\n\tstop    chan struct{}\n\tstopper *sync.Once\n}\n\ntype errCreateConnectionGroup string\n\nfunc (e errCreateConnectionGroup) Error() string {\n\treturn \"cannot create connection group: \" + string(e)\n}\n\nfunc NewConnectionGroup(logger logrus.FieldLogger, connectionLimit int, width, height uint8) (*ConnectionGroup, error) {\n\tg, err := game.NewGame(logger, width, height)\n\tif err != nil {\n\t\treturn nil, errCreateConnectionGroup(err.Error())\n\t}\n\n\tif connectionLimit > 0 {\n\t\treturn &ConnectionGroup{\n\t\t\tlimit:      connectionLimit,\n\t\t\tcounterMux: &sync.RWMutex{},\n\t\t\tgame:       g,\n\t\t\tbroadcast:  broadcast.NewGroupBroadcast(),\n\t\t\tlogger:     logger,\n\t\t\tchs:        make([]chan *websocket.PreparedMessage, 0),\n\t\t\tchsMux:     &sync.RWMutex{},\n\t\t\tstop:       make(chan struct{}),\n\t\t\tstopper:    &sync.Once{},\n\t\t}, nil\n\t}\n\n\treturn nil, errCreateConnectionGroup(\"invalid connection limit\")\n}\n\nfunc (cg *ConnectionGroup) GetLimit() int {\n\tcg.counterMux.RLock()\n\tdefer cg.counterMux.RUnlock()\n\treturn cg.limit\n}\n\nfunc (cg *ConnectionGroup) SetLimit(limit int) {\n\tcg.counterMux.Lock()\n\tcg.limit = limit\n\tcg.counterMux.Unlock()\n}\n\nfunc (cg *ConnectionGroup) GetCount() int {\n\tcg.counterMux.RLock()\n\tdefer cg.counterMux.RUnlock()\n\treturn cg.counter\n}\n\n\/\/ unsafeIsFull returns true if group is full\nfunc (cg *ConnectionGroup) unsafeIsFull() bool {\n\treturn cg.counter == cg.limit\n}\n\nfunc (cg *ConnectionGroup) IsFull() bool {\n\tcg.counterMux.RLock()\n\tdefer cg.counterMux.RUnlock()\n\treturn cg.unsafeIsFull()\n}\n\n\/\/ unsafeIsEmpty returns true if group is empty\nfunc (cg *ConnectionGroup) unsafeIsEmpty() bool {\n\treturn cg.counter == 0\n}\n\nfunc (cg *ConnectionGroup) IsEmpty() bool {\n\tcg.counterMux.RLock()\n\tdefer cg.counterMux.RUnlock()\n\treturn cg.unsafeIsEmpty()\n}\n\ntype ErrHandleConnection struct {\n\tErr error\n}\n\nfunc (e *ErrHandleConnection) Error() string {\n\treturn \"handle connection error: \" + e.Err.Error()\n}\n\nvar ErrGroupIsFull = errors.New(\"group is full\")\n\nfunc (cg *ConnectionGroup) Handle(connectionWorker *ConnectionWorker) error {\n\tcg.counterMux.Lock()\n\tif cg.unsafeIsFull() {\n\t\tcg.counterMux.Unlock()\n\t\treturn &ErrHandleConnection{\n\t\t\tErr: ErrGroupIsFull,\n\t\t}\n\t}\n\tcg.counter += 1\n\tcg.counterMux.Unlock()\n\n\tdefer func() {\n\t\tcg.counterMux.Lock()\n\t\tcg.counter -= 1\n\t\tcg.counterMux.Unlock()\n\t}()\n\n\tchStopHandle := make(chan struct{})\n\tdefer close(chStopHandle)\n\n\tif err := connectionWorker.Start(cg.stop, cg.game, cg.broadcast, cg.proxyCh(chStopHandle, chanBytesOutBuffer)); err != nil {\n\t\treturn &ErrHandleConnection{\n\t\t\tErr: err,\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (cg *ConnectionGroup) Start() {\n\tcg.broadcast.Start(cg.stop)\n\tcg.game.Start(cg.stop)\n\n\tchMessagesGame := cg.listenGame(cg.stop, cg.game.ListenEvents(cg.stop, chanGameEventsBuffer))\n\tchMessagesBroadcast := cg.listenBroadcast(cg.stop, cg.broadcast.ListenMessages(cg.stop, chanBroadcastBuffer))\n\tchBytes := cg.encode(cg.stop, chMessagesGame, chMessagesBroadcast)\n\tchPreparedMessages := cg.prepare(cg.stop, chBytes)\n\tcg.broadcastPreparedMessages(chPreparedMessages)\n}\n\nfunc (cg *ConnectionGroup) broadcastPreparedMessages(chin <-chan *websocket.PreparedMessage) {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase pm, ok := <-chin:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tcg.doBroadcast(pm)\n\t\t\tcase <-cg.stop:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (cg *ConnectionGroup) doBroadcast(pm *websocket.PreparedMessage) {\n\tcg.chsMux.RLock()\n\tdefer cg.chsMux.RUnlock()\n\n\tfor _, ch := range cg.chs {\n\t\tselect {\n\t\tcase ch <- pm:\n\t\tcase <-cg.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (cg *ConnectionGroup) Stop() {\n\tcg.stopper.Do(func() {\n\t\tclose(cg.stop)\n\t})\n}\n\nfunc (cg *ConnectionGroup) GetWorldWidth() uint8 {\n\treturn cg.game.World().Width()\n}\n\nfunc (cg *ConnectionGroup) GetWorldHeight() uint8 {\n\treturn cg.game.World().Height()\n}\n\nfunc (cg *ConnectionGroup) GetObjects() []interface{} {\n\treturn cg.game.World().GetObjects()\n}\n\nfunc (cg *ConnectionGroup) createChan() chan *websocket.PreparedMessage {\n\tch := make(chan *websocket.PreparedMessage, chanBytesProxyBuffer)\n\n\tcg.chsMux.Lock()\n\tcg.chs = append(cg.chs, ch)\n\tcg.chsMux.Unlock()\n\n\treturn ch\n}\n\nfunc (cg *ConnectionGroup) deleteChan(ch chan *websocket.PreparedMessage) {\n\tgo func() {\n\t\tfor range ch {\n\t\t}\n\t}()\n\n\tcg.chsMux.Lock()\n\tfor i := range cg.chs {\n\t\tif cg.chs[i] == ch {\n\t\t\tcg.chs = append(cg.chs[:i], cg.chs[i+1:]...)\n\t\t\tclose(ch)\n\t\t\tbreak\n\t\t}\n\t}\n\tcg.chsMux.Unlock()\n}\n\nfunc (cg *ConnectionGroup) proxyCh(stop <-chan struct{}, buffer uint) <-chan *websocket.PreparedMessage {\n\tch := cg.createChan()\n\tchOut := make(chan *websocket.PreparedMessage, buffer)\n\n\tgo func() {\n\t\tdefer close(chOut)\n\t\tdefer cg.deleteChan(ch)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\tcase <-cg.stop:\n\t\t\t\treturn\n\t\t\tcase message, ok := <-ch:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcg.sendTimeout(chOut, message, stop, sendPreparedMessageTimeout)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn chOut\n}\n\nfunc (cg *ConnectionGroup) sendTimeout(ch chan *websocket.PreparedMessage, pm *websocket.PreparedMessage, stop <-chan struct{}, timeout time.Duration) {\n\tconst warnFormat = \"game group message was not send to connection: %s\"\n\tvar timer = time.NewTimer(timeout)\n\tdefer timer.Stop()\n\tselect {\n\tcase ch <- pm:\n\tcase <-cg.stop:\n\t\tcg.logger.Warnf(warnFormat, \"game group stopped\")\n\tcase <-stop:\n\t\tcg.logger.Warnf(warnFormat, \"connection handler stopped\")\n\tcase <-timer.C:\n\t\tcg.logger.Warnf(warnFormat, \"time is out\")\n\t\tif len(ch) == cap(ch) {\n\t\t\tcg.logger.Warn(\"connection group output channel buffer is overflow for connection\")\n\t\t}\n\t}\n}\n\nfunc (cg *ConnectionGroup) listenGame(stop <-chan struct{}, chin <-chan game.Event) <-chan OutputMessage {\n\tchout := make(chan OutputMessage, cap(chin))\n\n\tgo func() {\n\t\tdefer close(chout)\n\n\t\tticker := time.NewTicker(gameOutputMessageBufferMonitoringDelay)\n\t\tdefer ticker.Stop()\n\n\t\tvar count = 0\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-chin:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t\/\/ Do not send internal game errors to clients\n\t\t\t\tif event.Type == game.EventTypeError {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t\/\/ Do not send checked events to clients\n\t\t\t\tif event.Type == game.EventTypeObjectChecked {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\toutputMessage := OutputMessage{\n\t\t\t\t\tType:    OutputMessageTypeGame,\n\t\t\t\t\tPayload: event,\n\t\t\t\t}\n\n\t\t\t\tselect {\n\t\t\t\tcase chout <- outputMessage:\n\t\t\t\t\tcount++\n\t\t\t\tcase <-stop:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tcg.logger.WithFields(logrus.Fields{\n\t\t\t\t\t\"buffered_messages\": len(chout),\n\t\t\t\t\t\"buffer_size\":       cap(chout),\n\t\t\t\t\t\"time_frame\":        gameOutputMessageBufferMonitoringDelay,\n\t\t\t\t\t\"count\":             count,\n\t\t\t\t}).Debug(\"game output messages buffer monitoring\")\n\n\t\t\t\tcount = 0\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn chout\n}\n\nfunc (cg *ConnectionGroup) listenBroadcast(stop <-chan struct{}, chin <-chan broadcast.Message) <-chan OutputMessage {\n\tchout := make(chan OutputMessage, cap(chin))\n\n\tgo func() {\n\t\tdefer close(chout)\n\n\t\tticker := time.NewTicker(broadcastOutputMessageBufferMonitoringDelay)\n\t\tdefer ticker.Stop()\n\n\t\tvar count = 0\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase message, ok := <-chin:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\toutputMessage := OutputMessage{\n\t\t\t\t\tType:    OutputMessageTypeBroadcast,\n\t\t\t\t\tPayload: message,\n\t\t\t\t}\n\n\t\t\t\tselect {\n\t\t\t\tcase chout <- outputMessage:\n\t\t\t\t\tcount++\n\t\t\t\tcase <-stop:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tcg.logger.WithFields(logrus.Fields{\n\t\t\t\t\t\"buffered_messages\": len(chout),\n\t\t\t\t\t\"buffer_size\":       cap(chout),\n\t\t\t\t\t\"time_frame\":        broadcastOutputMessageBufferMonitoringDelay,\n\t\t\t\t\t\"count\":             count,\n\t\t\t\t}).Debug(\"broadcast output messages buffer monitoring\")\n\n\t\t\t\tcount = 0\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn chout\n}\n\nfunc (cg *ConnectionGroup) encode(stop <-chan struct{}, chins ...<-chan OutputMessage) <-chan []byte {\n\tchout := make(chan []byte, chanEncodeGroupMessageBuffer)\n\n\twg := sync.WaitGroup{}\n\twg.Add(len(chins))\n\n\tfor i, chin := range chins {\n\t\tgo func(i int, chin <-chan OutputMessage) {\n\t\t\tdefer wg.Done()\n\n\t\t\tticker := time.NewTicker(encodeGroupMessageBufferMonitoringDelay)\n\t\t\tdefer ticker.Stop()\n\n\t\t\tvar count = 0\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-stop:\n\t\t\t\t\treturn\n\t\t\t\tcase message, ok := <-chin:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tif data, err := ffjson.Marshal(message); err != nil {\n\t\t\t\t\t\tcg.logger.Errorln(\"encode output message error:\", err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase chout <- data:\n\t\t\t\t\t\t\tcount++\n\t\t\t\t\t\tcase <-stop:\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase <-ticker.C:\n\t\t\t\t\tcg.logger.WithFields(logrus.Fields{\n\t\t\t\t\t\t\"buffered_messages\": len(chout),\n\t\t\t\t\t\t\"buffer_size\":       chanEncodeGroupMessageBuffer,\n\t\t\t\t\t\t\"time_frame\":        encodeGroupMessageBufferMonitoringDelay,\n\t\t\t\t\t\t\"count\":             count,\n\t\t\t\t\t\t\"channel\":           i,\n\t\t\t\t\t}).Debug(\"encoded group messages buffer monitoring\")\n\n\t\t\t\t\tcount = 0\n\t\t\t\t}\n\t\t\t}\n\t\t}(i, chin)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(chout)\n\t}()\n\n\treturn chout\n}\n\nfunc (cg *ConnectionGroup) prepare(stop <-chan struct{}, chin <-chan []byte) <-chan *websocket.PreparedMessage {\n\tchout := make(chan *websocket.PreparedMessage, cap(chin))\n\n\tgo func() {\n\t\tdefer close(chout)\n\n\t\tticker := time.NewTicker(preparedMessageBufferMonitoringDelay)\n\t\tdefer ticker.Stop()\n\n\t\tvar count = 0\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase data, ok := <-chin:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif pm, err := websocket.NewPreparedMessage(websocket.TextMessage, data); err != nil {\n\t\t\t\t\tcg.logger.Errorln(\"prepare group output message error:\", err)\n\t\t\t\t} else {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase chout <- pm:\n\t\t\t\t\t\tcount++\n\t\t\t\t\tcase <-stop:\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tcg.logger.WithFields(logrus.Fields{\n\t\t\t\t\t\"buffered_messages\": len(chout),\n\t\t\t\t\t\"buffer_size\":       cap(chout),\n\t\t\t\t\t\"time_frame\":        preparedMessageBufferMonitoringDelay,\n\t\t\t\t\t\"count\":             count,\n\t\t\t\t}).Debug(\"prepared messages buffer monitoring\")\n\n\t\t\t\tcount = 0\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn chout\n}\n\nfunc (cg *ConnectionGroup) BroadcastMessageTimeout(message string, timeout time.Duration) bool {\n\treturn cg.broadcast.BroadcastMessageTimeout(broadcast.Message(message), timeout)\n}\n<commit_msg>Fix const names in ConnectionGroup<commit_after>package connections\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/websocket\"\n\t\"github.com\/pquerna\/ffjson\/ffjson\"\n\t\"github.com\/sirupsen\/logrus\"\n\n\t\"github.com\/ivan1993spb\/snake-server\/broadcast\"\n\t\"github.com\/ivan1993spb\/snake-server\/game\"\n)\n\nconst (\n\tchanBroadcastBuffer  = 128\n\tchanGameEventsBuffer = 8192\n\n\tchanPreparedMessageProxyBuffer = 8192\n\tchanPreparedMessageOutBuffer   = 8192\n\n\tchanEncodedOutputMessageBuffer = 8192\n\n\tsendPreparedMessageTimeout = time.Millisecond * 50\n\n\tbroadcastOutputMessageBufferMonitoringDelay = time.Second * 30\n\tgameOutputMessageBufferMonitoringDelay      = time.Second * 30\n\tencodedOutputMessageBufferMonitoringDelay   = time.Second * 30\n\tpreparedMessageBufferMonitoringDelay        = time.Second * 30\n\n\tminimalConnectionLimit = 1\n)\n\ntype ConnectionGroup struct {\n\tlimit      int\n\tcounter    int\n\tcounterMux *sync.RWMutex\n\n\tlogger logrus.FieldLogger\n\n\tgame      *game.Game\n\tbroadcast *broadcast.GroupBroadcast\n\n\tchs    []chan *websocket.PreparedMessage\n\tchsMux *sync.RWMutex\n\n\tstop    chan struct{}\n\tstopper *sync.Once\n}\n\ntype errCreateConnectionGroup string\n\nfunc (e errCreateConnectionGroup) Error() string {\n\treturn \"cannot create connection group: \" + string(e)\n}\n\nfunc NewConnectionGroup(logger logrus.FieldLogger, connectionLimit int, width, height uint8) (*ConnectionGroup, error) {\n\tg, err := game.NewGame(logger, width, height)\n\tif err != nil {\n\t\treturn nil, errCreateConnectionGroup(err.Error())\n\t}\n\n\tif connectionLimit < minimalConnectionLimit {\n\t\treturn nil, errCreateConnectionGroup(\"invalid connection limit\")\n\t}\n\n\treturn &ConnectionGroup{\n\t\tlimit:      connectionLimit,\n\t\tcounterMux: &sync.RWMutex{},\n\t\tgame:       g,\n\t\tbroadcast:  broadcast.NewGroupBroadcast(),\n\t\tlogger:     logger,\n\t\tchs:        make([]chan *websocket.PreparedMessage, 0),\n\t\tchsMux:     &sync.RWMutex{},\n\t\tstop:       make(chan struct{}),\n\t\tstopper:    &sync.Once{},\n\t}, nil\n}\n\nfunc (cg *ConnectionGroup) GetLimit() int {\n\tcg.counterMux.RLock()\n\tdefer cg.counterMux.RUnlock()\n\treturn cg.limit\n}\n\nfunc (cg *ConnectionGroup) SetLimit(limit int) {\n\tcg.counterMux.Lock()\n\tcg.limit = limit\n\tcg.counterMux.Unlock()\n}\n\nfunc (cg *ConnectionGroup) GetCount() int {\n\tcg.counterMux.RLock()\n\tdefer cg.counterMux.RUnlock()\n\treturn cg.counter\n}\n\n\/\/ unsafeIsFull returns true if group is full\nfunc (cg *ConnectionGroup) unsafeIsFull() bool {\n\treturn cg.counter == cg.limit\n}\n\nfunc (cg *ConnectionGroup) IsFull() bool {\n\tcg.counterMux.RLock()\n\tdefer cg.counterMux.RUnlock()\n\treturn cg.unsafeIsFull()\n}\n\n\/\/ unsafeIsEmpty returns true if group is empty\nfunc (cg *ConnectionGroup) unsafeIsEmpty() bool {\n\treturn cg.counter == 0\n}\n\nfunc (cg *ConnectionGroup) IsEmpty() bool {\n\tcg.counterMux.RLock()\n\tdefer cg.counterMux.RUnlock()\n\treturn cg.unsafeIsEmpty()\n}\n\ntype ErrHandleConnection struct {\n\tErr error\n}\n\nfunc (e *ErrHandleConnection) Error() string {\n\treturn \"handle connection error: \" + e.Err.Error()\n}\n\nvar ErrGroupIsFull = errors.New(\"group is full\")\n\nfunc (cg *ConnectionGroup) Handle(connectionWorker *ConnectionWorker) error {\n\tcg.counterMux.Lock()\n\tif cg.unsafeIsFull() {\n\t\tcg.counterMux.Unlock()\n\t\treturn &ErrHandleConnection{\n\t\t\tErr: ErrGroupIsFull,\n\t\t}\n\t}\n\tcg.counter += 1\n\tcg.counterMux.Unlock()\n\n\tdefer func() {\n\t\tcg.counterMux.Lock()\n\t\tcg.counter -= 1\n\t\tcg.counterMux.Unlock()\n\t}()\n\n\tchStopHandle := make(chan struct{})\n\tdefer close(chStopHandle)\n\n\tchout := cg.proxyCh(chStopHandle, chanPreparedMessageOutBuffer)\n\n\tif err := connectionWorker.Start(cg.stop, cg.game, cg.broadcast, chout); err != nil {\n\t\treturn &ErrHandleConnection{\n\t\t\tErr: err,\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (cg *ConnectionGroup) Start() {\n\tcg.broadcast.Start(cg.stop)\n\tcg.game.Start(cg.stop)\n\n\tchMessagesGame := cg.listenGame(cg.stop, cg.game.ListenEvents(cg.stop, chanGameEventsBuffer))\n\tchMessagesBroadcast := cg.listenBroadcast(cg.stop, cg.broadcast.ListenMessages(cg.stop, chanBroadcastBuffer))\n\tchBytes := cg.encode(cg.stop, chMessagesGame, chMessagesBroadcast)\n\tchPreparedMessages := cg.prepare(cg.stop, chBytes)\n\tcg.broadcastPreparedMessages(chPreparedMessages)\n}\n\nfunc (cg *ConnectionGroup) broadcastPreparedMessages(chin <-chan *websocket.PreparedMessage) {\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase pm, ok := <-chin:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tcg.doBroadcast(pm)\n\t\t\tcase <-cg.stop:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}\n\nfunc (cg *ConnectionGroup) doBroadcast(pm *websocket.PreparedMessage) {\n\tcg.chsMux.RLock()\n\tdefer cg.chsMux.RUnlock()\n\n\tfor _, ch := range cg.chs {\n\t\tselect {\n\t\tcase ch <- pm:\n\t\tcase <-cg.stop:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (cg *ConnectionGroup) Stop() {\n\tcg.stopper.Do(func() {\n\t\tclose(cg.stop)\n\t})\n}\n\nfunc (cg *ConnectionGroup) GetWorldWidth() uint8 {\n\treturn cg.game.World().Width()\n}\n\nfunc (cg *ConnectionGroup) GetWorldHeight() uint8 {\n\treturn cg.game.World().Height()\n}\n\nfunc (cg *ConnectionGroup) GetObjects() []interface{} {\n\treturn cg.game.World().GetObjects()\n}\n\nfunc (cg *ConnectionGroup) createChan() chan *websocket.PreparedMessage {\n\tch := make(chan *websocket.PreparedMessage, chanPreparedMessageProxyBuffer)\n\n\tcg.chsMux.Lock()\n\tcg.chs = append(cg.chs, ch)\n\tcg.chsMux.Unlock()\n\n\treturn ch\n}\n\nfunc (cg *ConnectionGroup) deleteChan(ch chan *websocket.PreparedMessage) {\n\tgo func() {\n\t\tfor range ch {\n\t\t}\n\t}()\n\n\tcg.chsMux.Lock()\n\tfor i := range cg.chs {\n\t\tif cg.chs[i] == ch {\n\t\t\tcg.chs = append(cg.chs[:i], cg.chs[i+1:]...)\n\t\t\tclose(ch)\n\t\t\tbreak\n\t\t}\n\t}\n\tcg.chsMux.Unlock()\n}\n\nfunc (cg *ConnectionGroup) proxyCh(stop <-chan struct{}, buffer uint) <-chan *websocket.PreparedMessage {\n\tch := cg.createChan()\n\tchOut := make(chan *websocket.PreparedMessage, buffer)\n\n\tgo func() {\n\t\tdefer close(chOut)\n\t\tdefer cg.deleteChan(ch)\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\tcase <-cg.stop:\n\t\t\t\treturn\n\t\t\tcase message, ok := <-ch:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcg.sendTimeout(chOut, message, stop, sendPreparedMessageTimeout)\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn chOut\n}\n\nfunc (cg *ConnectionGroup) sendTimeout(ch chan *websocket.PreparedMessage, pm *websocket.PreparedMessage, stop <-chan struct{}, timeout time.Duration) {\n\tconst warnFormat = \"game group message was not send to connection: %s\"\n\tvar timer = time.NewTimer(timeout)\n\tdefer timer.Stop()\n\tselect {\n\tcase ch <- pm:\n\tcase <-cg.stop:\n\t\tcg.logger.Warnf(warnFormat, \"game group stopped\")\n\tcase <-stop:\n\t\tcg.logger.Warnf(warnFormat, \"connection handler stopped\")\n\tcase <-timer.C:\n\t\tcg.logger.Warnf(warnFormat, \"time is out\")\n\t\tif len(ch) == cap(ch) {\n\t\t\tcg.logger.Warn(\"connection group output channel buffer is overflow for connection\")\n\t\t}\n\t}\n}\n\nfunc (cg *ConnectionGroup) listenGame(stop <-chan struct{}, chin <-chan game.Event) <-chan OutputMessage {\n\tchout := make(chan OutputMessage, cap(chin))\n\n\tgo func() {\n\t\tdefer close(chout)\n\n\t\tticker := time.NewTicker(gameOutputMessageBufferMonitoringDelay)\n\t\tdefer ticker.Stop()\n\n\t\tvar count = 0\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event, ok := <-chin:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t\/\/ Do not send internal game errors to clients\n\t\t\t\tif event.Type == game.EventTypeError {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t\/\/ Do not send checked events to clients\n\t\t\t\tif event.Type == game.EventTypeObjectChecked {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\toutputMessage := OutputMessage{\n\t\t\t\t\tType:    OutputMessageTypeGame,\n\t\t\t\t\tPayload: event,\n\t\t\t\t}\n\n\t\t\t\tselect {\n\t\t\t\tcase chout <- outputMessage:\n\t\t\t\t\tcount++\n\t\t\t\tcase <-stop:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tcg.logger.WithFields(logrus.Fields{\n\t\t\t\t\t\"buffered_messages\": len(chout),\n\t\t\t\t\t\"buffer_size\":       cap(chout),\n\t\t\t\t\t\"time_frame\":        gameOutputMessageBufferMonitoringDelay,\n\t\t\t\t\t\"count\":             count,\n\t\t\t\t}).Debug(\"game output messages buffer monitoring\")\n\n\t\t\t\tcount = 0\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn chout\n}\n\nfunc (cg *ConnectionGroup) listenBroadcast(stop <-chan struct{}, chin <-chan broadcast.Message) <-chan OutputMessage {\n\tchout := make(chan OutputMessage, cap(chin))\n\n\tgo func() {\n\t\tdefer close(chout)\n\n\t\tticker := time.NewTicker(broadcastOutputMessageBufferMonitoringDelay)\n\t\tdefer ticker.Stop()\n\n\t\tvar count = 0\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase message, ok := <-chin:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\toutputMessage := OutputMessage{\n\t\t\t\t\tType:    OutputMessageTypeBroadcast,\n\t\t\t\t\tPayload: message,\n\t\t\t\t}\n\n\t\t\t\tselect {\n\t\t\t\tcase chout <- outputMessage:\n\t\t\t\t\tcount++\n\t\t\t\tcase <-stop:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tcg.logger.WithFields(logrus.Fields{\n\t\t\t\t\t\"buffered_messages\": len(chout),\n\t\t\t\t\t\"buffer_size\":       cap(chout),\n\t\t\t\t\t\"time_frame\":        broadcastOutputMessageBufferMonitoringDelay,\n\t\t\t\t\t\"count\":             count,\n\t\t\t\t}).Debug(\"broadcast output messages buffer monitoring\")\n\n\t\t\t\tcount = 0\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn chout\n}\n\nfunc (cg *ConnectionGroup) encode(stop <-chan struct{}, chins ...<-chan OutputMessage) <-chan []byte {\n\tchout := make(chan []byte, chanEncodedOutputMessageBuffer)\n\n\twg := sync.WaitGroup{}\n\twg.Add(len(chins))\n\n\tfor i, chin := range chins {\n\t\tgo func(i int, chin <-chan OutputMessage) {\n\t\t\tdefer wg.Done()\n\n\t\t\tticker := time.NewTicker(encodedOutputMessageBufferMonitoringDelay)\n\t\t\tdefer ticker.Stop()\n\n\t\t\tvar count = 0\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-stop:\n\t\t\t\t\treturn\n\t\t\t\tcase message, ok := <-chin:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\n\t\t\t\t\tif data, err := ffjson.Marshal(message); err != nil {\n\t\t\t\t\t\tcg.logger.Errorln(\"encode output message error:\", err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tselect {\n\t\t\t\t\t\tcase chout <- data:\n\t\t\t\t\t\t\tcount++\n\t\t\t\t\t\tcase <-stop:\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase <-ticker.C:\n\t\t\t\t\tcg.logger.WithFields(logrus.Fields{\n\t\t\t\t\t\t\"buffered_messages\": len(chout),\n\t\t\t\t\t\t\"buffer_size\":       chanEncodedOutputMessageBuffer,\n\t\t\t\t\t\t\"time_frame\":        encodedOutputMessageBufferMonitoringDelay,\n\t\t\t\t\t\t\"count\":             count,\n\t\t\t\t\t\t\"channel\":           i,\n\t\t\t\t\t}).Debug(\"encoded group messages buffer monitoring\")\n\n\t\t\t\t\tcount = 0\n\t\t\t\t}\n\t\t\t}\n\t\t}(i, chin)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(chout)\n\t}()\n\n\treturn chout\n}\n\nfunc (cg *ConnectionGroup) prepare(stop <-chan struct{}, chin <-chan []byte) <-chan *websocket.PreparedMessage {\n\tchout := make(chan *websocket.PreparedMessage, cap(chin))\n\n\tgo func() {\n\t\tdefer close(chout)\n\n\t\tticker := time.NewTicker(preparedMessageBufferMonitoringDelay)\n\t\tdefer ticker.Stop()\n\n\t\tvar count = 0\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase data, ok := <-chin:\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tif pm, err := websocket.NewPreparedMessage(websocket.TextMessage, data); err != nil {\n\t\t\t\t\tcg.logger.Errorln(\"prepare group output message error:\", err)\n\t\t\t\t} else {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase chout <- pm:\n\t\t\t\t\t\tcount++\n\t\t\t\t\tcase <-stop:\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tcase <-stop:\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\tcg.logger.WithFields(logrus.Fields{\n\t\t\t\t\t\"buffered_messages\": len(chout),\n\t\t\t\t\t\"buffer_size\":       cap(chout),\n\t\t\t\t\t\"time_frame\":        preparedMessageBufferMonitoringDelay,\n\t\t\t\t\t\"count\":             count,\n\t\t\t\t}).Debug(\"prepared messages buffer monitoring\")\n\n\t\t\t\tcount = 0\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn chout\n}\n\nfunc (cg *ConnectionGroup) BroadcastMessageTimeout(message string, timeout time.Duration) bool {\n\treturn cg.broadcast.BroadcastMessageTimeout(broadcast.Message(message), timeout)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This program solves the (English) peg\n\/\/ solitaire board game.\n\/\/ http:\/\/en.wikipedia.org\/wiki\/Peg_solitaire\n\npackage main\n\nimport \"fmt\"\n\nconst N = 11 + 1 \/\/ length of a row (+1 for \\n)\n\n\/\/ The board must be surrounded by 2 illegal\n\/\/ fields in each direction so that move()\n\/\/ doesn't need to check the board boundaries.\n\/\/ Periods represent illegal fields,\n\/\/ ● are pegs, and ○ are holes.\n\nvar board = []int(\n\t`...........\n...........\n....●●●....\n....●●●....\n..●●●●●●●..\n..●●●○●●●..\n..●●●●●●●..\n....●●●....\n....●●●....\n...........\n...........\n`)\n\n\/\/ center is the position of the center hole if \n\/\/ there is a single one; otherwise it is -1.\nvar center int\n\nfunc init() {\n\tn := 0\n\tfor pos, field := range board {\n\t\tif field == '○' {\n\t\t\tcenter = pos\n\t\t\tn++\n\t\t}\n\t}\n\tif n != 1 {\n\t\tcenter = -1 \/\/ no single hole\n\t}\n}\n\nvar moves int \/\/ number of times move is called\n\n\/\/ move tests if there is a peg at position pos that \n\/\/ can jump over another peg in direction dir. If the\n\/\/ move is valid, it is executed and move returns true.\n\/\/ Otherwise, move returns false.\nfunc move(pos, dir int) bool {\n\tmoves++\n\tif board[pos] == '●' && board[pos+dir] == '●' && board[pos+2*dir] == '○' {\n\t\tboard[pos] = '○'\n\t\tboard[pos+dir] = '○'\n\t\tboard[pos+2*dir] = '●'\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ unmove reverts a previously executed valid move.\nfunc unmove(pos, dir int) {\n\tboard[pos] = '●'\n\tboard[pos+dir] = '●'\n\tboard[pos+2*dir] = '○'\n}\n\n\/\/ solve tries to find a sequence of moves such that \n\/\/ there is only one peg left at the end; if center is \n\/\/ >= 0, that last peg must be in the center position.\n\/\/ If a solution is found, solve prints the board after\n\/\/ each move in a backward fashion (i.e., the last \n\/\/ board position is printed first, all the way back to\n\/\/ the starting board position).\nfunc solve() bool {\n\tvar last, n int\n\tfor pos, field := range board {\n\t\t\/\/ try each board position\n\t\tif field == '●' {\n\t\t\t\/\/ found a peg\n\t\t\tfor _, dir := range [...]int{-1, -N, +1, +N} {\n\t\t\t\t\/\/ try each direction\n\t\t\t\tif move(pos, dir) {\n\t\t\t\t\t\/\/ a valid move was found and executed,\n\t\t\t\t\t\/\/ see if this new board has a solution\n\t\t\t\t\tif solve() {\n\t\t\t\t\t\tunmove(pos, dir)\n\t\t\t\t\t\tprintln(string(board))\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t\tunmove(pos, dir)\n\t\t\t\t}\n\t\t\t}\n\t\t\tlast = pos\n\t\t\tn++\n\t\t}\n\t}\n\t\/\/ tried each possible move\n\tif n == 1 && (center < 0 || last == center) {\n\t\t\/\/ there's only one peg left\n\t\tprintln(string(board))\n\t\treturn true\n\t}\n\t\/\/ no solution found for this board\n\treturn false\n}\n\nfunc main() {\n\tif !solve() {\n\t\tfmt.Println(\"no solution found\")\n\t}\n\tfmt.Println(moves, \"moves tried\")\n}\n<commit_msg>doc\/play: use []rune insetead of []int.<commit_after>\/\/ This program solves the (English) peg\n\/\/ solitaire board game.\n\/\/ http:\/\/en.wikipedia.org\/wiki\/Peg_solitaire\n\npackage main\n\nimport \"fmt\"\n\nconst N = 11 + 1 \/\/ length of a row (+1 for \\n)\n\n\/\/ The board must be surrounded by 2 illegal\n\/\/ fields in each direction so that move()\n\/\/ doesn't need to check the board boundaries.\n\/\/ Periods represent illegal fields,\n\/\/ ● are pegs, and ○ are holes.\n\nvar board = []rune(\n\t`...........\n...........\n....●●●....\n....●●●....\n..●●●●●●●..\n..●●●○●●●..\n..●●●●●●●..\n....●●●....\n....●●●....\n...........\n...........\n`)\n\n\/\/ center is the position of the center hole if \n\/\/ there is a single one; otherwise it is -1.\nvar center int\n\nfunc init() {\n\tn := 0\n\tfor pos, field := range board {\n\t\tif field == '○' {\n\t\t\tcenter = pos\n\t\t\tn++\n\t\t}\n\t}\n\tif n != 1 {\n\t\tcenter = -1 \/\/ no single hole\n\t}\n}\n\nvar moves int \/\/ number of times move is called\n\n\/\/ move tests if there is a peg at position pos that \n\/\/ can jump over another peg in direction dir. If the\n\/\/ move is valid, it is executed and move returns true.\n\/\/ Otherwise, move returns false.\nfunc move(pos, dir int) bool {\n\tmoves++\n\tif board[pos] == '●' && board[pos+dir] == '●' && board[pos+2*dir] == '○' {\n\t\tboard[pos] = '○'\n\t\tboard[pos+dir] = '○'\n\t\tboard[pos+2*dir] = '●'\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ unmove reverts a previously executed valid move.\nfunc unmove(pos, dir int) {\n\tboard[pos] = '●'\n\tboard[pos+dir] = '●'\n\tboard[pos+2*dir] = '○'\n}\n\n\/\/ solve tries to find a sequence of moves such that \n\/\/ there is only one peg left at the end; if center is \n\/\/ >= 0, that last peg must be in the center position.\n\/\/ If a solution is found, solve prints the board after\n\/\/ each move in a backward fashion (i.e., the last \n\/\/ board position is printed first, all the way back to\n\/\/ the starting board position).\nfunc solve() bool {\n\tvar last, n int\n\tfor pos, field := range board {\n\t\t\/\/ try each board position\n\t\tif field == '●' {\n\t\t\t\/\/ found a peg\n\t\t\tfor _, dir := range [...]int{-1, -N, +1, +N} {\n\t\t\t\t\/\/ try each direction\n\t\t\t\tif move(pos, dir) {\n\t\t\t\t\t\/\/ a valid move was found and executed,\n\t\t\t\t\t\/\/ see if this new board has a solution\n\t\t\t\t\tif solve() {\n\t\t\t\t\t\tunmove(pos, dir)\n\t\t\t\t\t\tprintln(string(board))\n\t\t\t\t\t\treturn true\n\t\t\t\t\t}\n\t\t\t\t\tunmove(pos, dir)\n\t\t\t\t}\n\t\t\t}\n\t\t\tlast = pos\n\t\t\tn++\n\t\t}\n\t}\n\t\/\/ tried each possible move\n\tif n == 1 && (center < 0 || last == center) {\n\t\t\/\/ there's only one peg left\n\t\tprintln(string(board))\n\t\treturn true\n\t}\n\t\/\/ no solution found for this board\n\treturn false\n}\n\nfunc main() {\n\tif !solve() {\n\t\tfmt.Println(\"no solution found\")\n\t}\n\tfmt.Println(moves, \"moves tried\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package params\n\nimport (\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n)\n\n\/\/ Type for http post body\ntype PostBody []byte \/\/ Byte array with request body\n\n\/\/ Get params stands for \"query params\"\ntype GetParams map[string]string\n\ntype Params struct {\n\tQuery      GetParams\n\tBody       PostBody\n\tPathParams PathParams\n}\n\nfunc NewParams(request *http.Request, pattern *regexp.Regexp, path string) (*Params, error) {\n\tbody, err := ioutil.ReadAll(request.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Params{\n\t\tQuery:      ValuesToGetParams(request.URL.Query()),\n\t\tBody:       body,\n\t\tPathParams: ExtractPathParams(pattern, path),\n\t}, nil\n}\n\nfunc ExtractParams(req *http.Request) *Params {\n\treturn req.Context().Value(\"params\").(*Params)\n}\n\n\/\/ Converts url.Url.Query() from \"Values\" (map[string][]string)\n\/\/ to \"getParams\" (map[string]string)\nfunc ValuesToGetParams(values url.Values) GetParams {\n\tvar params map[string]string\n\tfor key := range values {\n\t\tparams[key] = values.Get(key)\n\t}\n\treturn params\n}\n\n\/\/ Example: url \"\/api\/v1\/users\/599a49bacdf43b817eeea57b\" and pattern `\/api\/v1\/users\/:id`\n\/\/ path params = {\"id\": \"599a49bacdf43b817eeea57b\"}\ntype PathParams map[string]string\n\n\/\/ Extract path params from path\nfunc ExtractPathParams(pattern *regexp.Regexp, path string) PathParams {\n\tmatch := pattern.FindStringSubmatch(path)\n\tresult := make(PathParams)\n\n\tfor i, name := range pattern.SubexpNames() {\n\t\tif i != 0 {\n\t\t\tresult[name] = match[i]\n\t\t}\n\t}\n\n\treturn result\n}\n<commit_msg>fix get params from get query<commit_after>package params\n\nimport (\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n)\n\n\/\/ Type for http post body\ntype PostBody []byte \/\/ Byte array with request body\n\n\/\/ Get params stands for \"query params\"\ntype GetParams map[string]string\n\ntype Params struct {\n\tQuery      GetParams\n\tBody       PostBody\n\tPathParams PathParams\n}\n\nfunc NewParams(request *http.Request, pattern *regexp.Regexp, path string) (*Params, error) {\n\tbody, err := ioutil.ReadAll(request.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Params{\n\t\tQuery:      ValuesToGetParams(request.URL.Query()),\n\t\tBody:       body,\n\t\tPathParams: ExtractPathParams(pattern, path),\n\t}, nil\n}\n\nfunc ExtractParams(req *http.Request) *Params {\n\treturn req.Context().Value(\"params\").(*Params)\n}\n\n\/\/ Converts url.Url.Query() from \"Values\" (map[string][]string)\n\/\/ to \"getParams\" (map[string]string)\nfunc ValuesToGetParams(values url.Values) GetParams {\n\tparams := make(map[string]string)\n\tfor key := range values {\n\t\tparams[key] = values.Get(key)\n\t}\n\treturn params\n}\n\n\/\/ Example: url \"\/api\/v1\/users\/599a49bacdf43b817eeea57b\" and pattern `\/api\/v1\/users\/:id`\n\/\/ path params = {\"id\": \"599a49bacdf43b817eeea57b\"}\ntype PathParams map[string]string\n\n\/\/ Extract path params from path\nfunc ExtractPathParams(pattern *regexp.Regexp, path string) PathParams {\n\tmatch := pattern.FindStringSubmatch(path)\n\tresult := make(PathParams)\n\n\tfor i, name := range pattern.SubexpNames() {\n\t\tif i != 0 {\n\t\t\tresult[name] = match[i]\n\t\t}\n\t}\n\n\treturn result\n}\n<|endoftext|>"}
{"text":"<commit_before>package parser\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/Tamrin007\/monkey\/ast\"\n\t\"github.com\/Tamrin007\/monkey\/lexer\"\n\t\"github.com\/Tamrin007\/monkey\/token\"\n)\n\ntype Parser struct {\n\tl         *lexer.Lexer\n\terrors    []string\n\tcurToken  token.Token\n\tpeekToken token.Token\n}\n\nfunc New(l *lexer.Lexer) *Parser {\n\tp := &Parser{\n\t\tl:      l,\n\t\terrors: []string{},\n\t}\n\n\tp.nextToken()\n\tp.nextToken()\n\n\treturn p\n}\n\nfunc (p *Parser) Errors() []string {\n\treturn p.errors\n}\n\nfunc (p *Parser) peekError(t token.TokenType) {\n\tmsg := fmt.Sprintf(\"expected next token to be %s, got %s instead\", t, p.peekToken.Type)\n\tp.errors = append(p.errors, msg)\n}\n\nfunc (p *Parser) nextToken() {\n\tp.curToken = p.peekToken\n\tp.peekToken = p.l.NextToken()\n}\n\nfunc (p *Parser) ParseProgram() *ast.Program {\n\tprogram := &ast.Program{}\n\tprogram.Statements = []ast.Statement{}\n\n\tfor p.curToken.Type != token.EOF {\n\t\tstmt := p.parseStatement()\n\t\tif stmt != nil {\n\t\t\tprogram.Statements = append(program.Statements, stmt)\n\t\t}\n\t\tp.nextToken()\n\t}\n\treturn program\n}\n\nfunc (p *Parser) parseStatement() ast.Statement {\n\tswitch p.curToken.Type {\n\tcase token.LET:\n\t\treturn p.parseLetStatement()\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (p *Parser) parseLetStatement() *ast.LetStatement {\n\tstmt := &ast.LetStatement{Token: p.curToken}\n\n\tif !p.expectPeek(token.IDENT) {\n\t\treturn nil\n\t}\n\n\tstmt.Name = &ast.Identifier{Token: p.curToken, Value: p.curToken.Literal}\n\n\tif !p.expectPeek(token.ASSIGN) {\n\t\treturn nil\n\t}\n\n\t\/\/ TODO: We're skiping the expressions until we encounter a semicolon\n\tfor !p.curTokenIs(token.SEMICOLON) {\n\t\tp.nextToken()\n\t}\n\n\treturn stmt\n}\n\nfunc (p *Parser) curTokenIs(t token.TokenType) bool {\n\treturn p.curToken.Type == t\n}\n\nfunc (p *Parser) peekTokenIs(t token.TokenType) bool {\n\treturn p.peekToken.Type == t\n}\n\nfunc (p *Parser) expectPeek(t token.TokenType) bool {\n\tif p.peekTokenIs(t) {\n\t\tp.nextToken()\n\t\treturn true\n\t}\n\tp.peekError(t)\n\treturn false\n}\n<commit_msg>add function to parse return statement<commit_after>package parser\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/Tamrin007\/monkey\/ast\"\n\t\"github.com\/Tamrin007\/monkey\/lexer\"\n\t\"github.com\/Tamrin007\/monkey\/token\"\n)\n\ntype Parser struct {\n\tl         *lexer.Lexer\n\terrors    []string\n\tcurToken  token.Token\n\tpeekToken token.Token\n}\n\nfunc New(l *lexer.Lexer) *Parser {\n\tp := &Parser{\n\t\tl:      l,\n\t\terrors: []string{},\n\t}\n\n\tp.nextToken()\n\tp.nextToken()\n\n\treturn p\n}\n\nfunc (p *Parser) Errors() []string {\n\treturn p.errors\n}\n\nfunc (p *Parser) peekError(t token.TokenType) {\n\tmsg := fmt.Sprintf(\"expected next token to be %s, got %s instead\", t, p.peekToken.Type)\n\tp.errors = append(p.errors, msg)\n}\n\nfunc (p *Parser) nextToken() {\n\tp.curToken = p.peekToken\n\tp.peekToken = p.l.NextToken()\n}\n\nfunc (p *Parser) ParseProgram() *ast.Program {\n\tprogram := &ast.Program{}\n\tprogram.Statements = []ast.Statement{}\n\n\tfor p.curToken.Type != token.EOF {\n\t\tstmt := p.parseStatement()\n\t\tif stmt != nil {\n\t\t\tprogram.Statements = append(program.Statements, stmt)\n\t\t}\n\t\tp.nextToken()\n\t}\n\treturn program\n}\n\nfunc (p *Parser) parseStatement() ast.Statement {\n\tswitch p.curToken.Type {\n\tcase token.LET:\n\t\treturn p.parseLetStatement()\n\tcase token.RETURN:\n\t\treturn p.parseReturnStatement()\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (p *Parser) parseLetStatement() *ast.LetStatement {\n\tstmt := &ast.LetStatement{Token: p.curToken}\n\n\tif !p.expectPeek(token.IDENT) {\n\t\treturn nil\n\t}\n\n\tstmt.Name = &ast.Identifier{Token: p.curToken, Value: p.curToken.Literal}\n\n\tif !p.expectPeek(token.ASSIGN) {\n\t\treturn nil\n\t}\n\n\t\/\/ TODO: We're skiping the expressions until we encounter a semicolon\n\tfor !p.curTokenIs(token.SEMICOLON) {\n\t\tp.nextToken()\n\t}\n\n\treturn stmt\n}\n\nfunc (p *Parser) parseReturnStatement() *ast.ReturnStatement {\n\tstmt := &ast.ReturnStatement{Token: p.curToken}\n\n\tp.nextToken()\n\n\t\/\/ TODO: We're skipping the expressions until we encounter a semicolon\n\tfor !p.curTokenIs(token.SEMICOLON) {\n\t\tp.nextToken()\n\t}\n\n\treturn stmt\n}\n\nfunc (p *Parser) curTokenIs(t token.TokenType) bool {\n\treturn p.curToken.Type == t\n}\n\nfunc (p *Parser) peekTokenIs(t token.TokenType) bool {\n\treturn p.peekToken.Type == t\n}\n\nfunc (p *Parser) expectPeek(t token.TokenType) bool {\n\tif p.peekTokenIs(t) {\n\t\tp.nextToken()\n\t\treturn true\n\t}\n\tp.peekError(t)\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package path implements utilities for resolving paths within ipfs.\npackage path\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tmh \"github.com\/ipfs\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multihash\"\n\t\"github.com\/ipfs\/go-ipfs\/Godeps\/_workspace\/src\/golang.org\/x\/net\/context\"\n\n\tmerkledag \"github.com\/ipfs\/go-ipfs\/merkledag\"\n\tu \"github.com\/ipfs\/go-ipfs\/util\"\n)\n\nvar log = u.Logger(\"path\")\n\n\/\/ ErrNoLink is returned when a link is not found in a path\ntype ErrNoLink struct {\n\tname string\n\tnode mh.Multihash\n}\n\nfunc (e ErrNoLink) Error() string {\n\treturn fmt.Sprintf(\"no link named %q under %s\", e.name, e.node.B58String())\n}\n\n\/\/ Resolver provides path resolution to IPFS\n\/\/ It has a pointer to a DAGService, which is uses to resolve nodes.\ntype Resolver struct {\n\tDAG merkledag.DAGService\n}\n\n\/\/ SplitAbsPath clean up and split fpath. It extracts the first component (which\n\/\/ must be a Multihash) and return it separately.\nfunc SplitAbsPath(fpath Path) (mh.Multihash, []string, error) {\n\n\tlog.Debugf(\"Resolve: '%s'\", fpath)\n\n\tparts := fpath.Segments()\n\tif parts[0] == \"ipfs\" {\n\t\tparts = parts[1:]\n\t}\n\n\t\/\/ if nothing, bail.\n\tif len(parts) == 0 {\n\t\treturn nil, nil, fmt.Errorf(\"ipfs path must contain at least one component\")\n\t}\n\n\t\/\/ first element in the path is a b58 hash (for now)\n\th, err := mh.FromB58String(parts[0])\n\tif err != nil {\n\t\tlog.Debug(\"given path element is not a base58 string.\\n\")\n\t\treturn nil, nil, err\n\t}\n\n\treturn h, parts[1:], nil\n}\n\n\/\/ ResolvePath fetches the node for given path. It returns the last item\n\/\/ returned by ResolvePathComponents.\nfunc (s *Resolver) ResolvePath(ctx context.Context, fpath Path) (*merkledag.Node, error) {\n\tnodes, err := s.ResolvePathComponents(ctx, fpath)\n\tif err != nil || nodes == nil {\n\t\treturn nil, err\n\t}\n\treturn nodes[len(nodes)-1], err\n}\n\n\/\/ ResolvePathComponents fetches the nodes for each segment of the given path.\n\/\/ It uses the first path component as a hash (key) of the first node, then\n\/\/ resolves all other components walking the links, with ResolveLinks.\nfunc (s *Resolver) ResolvePathComponents(ctx context.Context, fpath Path) ([]*merkledag.Node, error) {\n\th, parts, err := SplitAbsPath(fpath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Debug(\"Resolve dag get.\")\n\tctx, cancel := context.WithTimeout(ctx, time.Minute)\n\tdefer cancel()\n\tnd, err := s.DAG.Get(ctx, u.Key(h))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.ResolveLinks(ctx, nd, parts)\n}\n\n\/\/ ResolveLinks iteratively resolves names by walking the link hierarchy.\n\/\/ Every node is fetched from the DAGService, resolving the next name.\n\/\/ Returns the list of nodes forming the path, starting with ndd. This list is\n\/\/ guaranteed never to be empty.\n\/\/\n\/\/ ResolveLinks(nd, []string{\"foo\", \"bar\", \"baz\"})\n\/\/ would retrieve \"baz\" in (\"bar\" in (\"foo\" in nd.Links).Links).Links\nfunc (s *Resolver) ResolveLinks(ctx context.Context, ndd *merkledag.Node, names []string) ([]*merkledag.Node, error) {\n\n\tresult := make([]*merkledag.Node, 0, len(names)+1)\n\tresult = append(result, ndd)\n\tnd := ndd \/\/ dup arg workaround\n\n\t\/\/ for each of the path components\n\tfor _, name := range names {\n\n\t\tvar next u.Key\n\t\tvar nlink *merkledag.Link\n\t\t\/\/ for each of the links in nd, the current object\n\t\tfor _, link := range nd.Links {\n\t\t\tif link.Name == name {\n\t\t\t\tnext = u.Key(link.Hash)\n\t\t\t\tnlink = link\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif next == \"\" {\n\t\t\tn, _ := nd.Multihash()\n\t\t\treturn result, ErrNoLink{name: name, node: n}\n\t\t}\n\n\t\tif nlink.Node == nil {\n\t\t\t\/\/ fetch object for link and assign to nd\n\t\t\tctx, cancel := context.WithTimeout(ctx, time.Minute)\n\t\t\tdefer cancel()\n\t\t\tnd, err := s.DAG.Get(ctx, next)\n\t\t\tif err != nil {\n\t\t\t\treturn append(result, nd), err\n\t\t\t}\n\t\t\tnlink.Node = nd\n\t\t} else {\n\t\t\tnd = nlink.Node\n\t\t}\n\n\t\tresult = append(result, nlink.Node)\n\t}\n\treturn result, nil\n}\n<commit_msg>path\/resolver: Fix recursive path resolution<commit_after>\/\/ Package path implements utilities for resolving paths within ipfs.\npackage path\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tmh \"github.com\/ipfs\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multihash\"\n\t\"github.com\/ipfs\/go-ipfs\/Godeps\/_workspace\/src\/golang.org\/x\/net\/context\"\n\n\tmerkledag \"github.com\/ipfs\/go-ipfs\/merkledag\"\n\tu \"github.com\/ipfs\/go-ipfs\/util\"\n)\n\nvar log = u.Logger(\"path\")\n\n\/\/ ErrNoLink is returned when a link is not found in a path\ntype ErrNoLink struct {\n\tname string\n\tnode mh.Multihash\n}\n\nfunc (e ErrNoLink) Error() string {\n\treturn fmt.Sprintf(\"no link named %q under %s\", e.name, e.node.B58String())\n}\n\n\/\/ Resolver provides path resolution to IPFS\n\/\/ It has a pointer to a DAGService, which is uses to resolve nodes.\ntype Resolver struct {\n\tDAG merkledag.DAGService\n}\n\n\/\/ SplitAbsPath clean up and split fpath. It extracts the first component (which\n\/\/ must be a Multihash) and return it separately.\nfunc SplitAbsPath(fpath Path) (mh.Multihash, []string, error) {\n\n\tlog.Debugf(\"Resolve: '%s'\", fpath)\n\n\tparts := fpath.Segments()\n\tif parts[0] == \"ipfs\" {\n\t\tparts = parts[1:]\n\t}\n\n\t\/\/ if nothing, bail.\n\tif len(parts) == 0 {\n\t\treturn nil, nil, fmt.Errorf(\"ipfs path must contain at least one component\")\n\t}\n\n\t\/\/ first element in the path is a b58 hash (for now)\n\th, err := mh.FromB58String(parts[0])\n\tif err != nil {\n\t\tlog.Debug(\"given path element is not a base58 string.\\n\")\n\t\treturn nil, nil, err\n\t}\n\n\treturn h, parts[1:], nil\n}\n\n\/\/ ResolvePath fetches the node for given path. It returns the last item\n\/\/ returned by ResolvePathComponents.\nfunc (s *Resolver) ResolvePath(ctx context.Context, fpath Path) (*merkledag.Node, error) {\n\tnodes, err := s.ResolvePathComponents(ctx, fpath)\n\tif err != nil || nodes == nil {\n\t\treturn nil, err\n\t}\n\treturn nodes[len(nodes)-1], err\n}\n\n\/\/ ResolvePathComponents fetches the nodes for each segment of the given path.\n\/\/ It uses the first path component as a hash (key) of the first node, then\n\/\/ resolves all other components walking the links, with ResolveLinks.\nfunc (s *Resolver) ResolvePathComponents(ctx context.Context, fpath Path) ([]*merkledag.Node, error) {\n\th, parts, err := SplitAbsPath(fpath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Debug(\"Resolve dag get.\")\n\tctx, cancel := context.WithTimeout(ctx, time.Minute)\n\tdefer cancel()\n\tnd, err := s.DAG.Get(ctx, u.Key(h))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn s.ResolveLinks(ctx, nd, parts)\n}\n\n\/\/ ResolveLinks iteratively resolves names by walking the link hierarchy.\n\/\/ Every node is fetched from the DAGService, resolving the next name.\n\/\/ Returns the list of nodes forming the path, starting with ndd. This list is\n\/\/ guaranteed never to be empty.\n\/\/\n\/\/ ResolveLinks(nd, []string{\"foo\", \"bar\", \"baz\"})\n\/\/ would retrieve \"baz\" in (\"bar\" in (\"foo\" in nd.Links).Links).Links\nfunc (s *Resolver) ResolveLinks(ctx context.Context, ndd *merkledag.Node, names []string) ([]*merkledag.Node, error) {\n\n\tresult := make([]*merkledag.Node, 0, len(names)+1)\n\tresult = append(result, ndd)\n\tnd := ndd \/\/ dup arg workaround\n\n\t\/\/ for each of the path components\n\tfor _, name := range names {\n\n\t\tvar next u.Key\n\t\tvar nlink *merkledag.Link\n\t\t\/\/ for each of the links in nd, the current object\n\t\tfor _, link := range nd.Links {\n\t\t\tif link.Name == name {\n\t\t\t\tnext = u.Key(link.Hash)\n\t\t\t\tnlink = link\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif next == \"\" {\n\t\t\tn, _ := nd.Multihash()\n\t\t\treturn result, ErrNoLink{name: name, node: n}\n\t\t}\n\n\t\tif nlink.Node == nil {\n\t\t\t\/\/ fetch object for link and assign to nd\n\t\t\tctx, cancel := context.WithTimeout(ctx, time.Minute)\n\t\t\tdefer cancel()\n\t\t\tvar err error\n\t\t\tnd, err = s.DAG.Get(ctx, next)\n\t\t\tif err != nil {\n\t\t\t\treturn append(result, nd), err\n\t\t\t}\n\t\t\tnlink.Node = nd\n\t\t} else {\n\t\t\tnd = nlink.Node\n\t\t}\n\n\t\tresult = append(result, nlink.Node)\n\t}\n\treturn result, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package smpp34\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n)\n\nvar (\n\t\/\/ Required SubmitSm Fields\n\treqSSMFields = []string{\n\t\tSERVICE_TYPE,\n\t\tSOURCE_ADDR_TON,\n\t\tSOURCE_ADDR_NPI,\n\t\tSOURCE_ADDR,\n\t\tDEST_ADDR_TON,\n\t\tDEST_ADDR_NPI,\n\t\tDESTINATION_ADDR,\n\t\tESM_CLASS,\n\t\tPROTOCOL_ID,\n\t\tPRIORITY_FLAG,\n\t\tSCHEDULE_DELIVERY_TIME,\n\t\tVALIDITY_PERIOD,\n\t\tREGISTERED_DELIVERY,\n\t\tREPLACE_IF_PRESENT_FLAG,\n\t\tDATA_CODING,\n\t\tSM_DEFAULT_MSG_ID,\n\t\tSM_LENGTH,\n\t\tSHORT_MESSAGE,\n\t}\n)\n\ntype SubmitSm struct {\n\t*Header\n\tmandatoryFields map[string]Field\n\ttlvFields       map[uint16]*TLVField\n}\n\nfunc NewSubmitSm(hdr *Header, b []byte) (*SubmitSm, error) {\n\tr := bytes.NewBuffer(b)\n\n\tfields, tlvs, err := create_pdu_fields(reqSSMFields, r)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := &SubmitSm{hdr, fields, tlvs}\n\n\treturn s, nil\n}\n\nfunc (s *SubmitSm) GetField(f string) Field {\n\treturn s.mandatoryFields[f]\n}\n\nfunc (s *SubmitSm) Fields() map[string]Field {\n\treturn s.mandatoryFields\n}\n\nfunc (s *SubmitSm) MandatoryFieldsList() []string {\n\treturn reqSSMFields\n}\n\nfunc (s *SubmitSm) GetHeader() *Header {\n\treturn s.Header\n}\n\nfunc (s *SubmitSm) SetField(f string, v interface{}) error {\n\tif s.validate_field(f, v) {\n\t\tfield := NewField(f, v)\n\n\t\tif field != nil {\n\t\t\ts.mandatoryFields[f] = field\n\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn errors.New(\"Invalid field value\")\n}\n\nfunc (s *SubmitSm) SetSeqNum(i uint32) {\n\ts.Header.Sequence = i\n}\n\nfunc (s *SubmitSm) SetTLVField(t, l int, v []byte) error {\n\tif l != len(v) {\n\t\treturn errors.New(\"Invalid TLV value lenght\")\n\t}\n\n\ts.tlvFields[uint16(t)] = &TLVField{uint16(t), uint16(l), v}\n\n\treturn nil\n}\n\nfunc (s *SubmitSm) validate_field(f string, v interface{}) bool {\n\tif included_check(s.MandatoryFieldsList(), f) && validate_pdu_field(f, v) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *SubmitSm) TLVFields() map[uint16]*TLVField {\n\treturn s.tlvFields\n}\n\nfunc (s *SubmitSm) writeFields() []byte {\n\tb := []byte{}\n\n\tfor _, i := range s.MandatoryFieldsList() {\n\t\tv := s.mandatoryFields[i].ByteArray()\n\t\tb = append(b, v...)\n\t}\n\n\treturn b\n}\n\nfunc (s *SubmitSm) writeTLVFields() []byte {\n\tb := []byte{}\n\n\tfor _, v := range s.tlvFields {\n\t\tb = append(b, v.Writer()...)\n\t}\n\n\treturn b\n}\n\nfunc (s *SubmitSm) Writer() []byte {\n\tb := append(s.writeFields(), s.writeTLVFields()...)\n\th := packUi32(uint32(len(b) + 16))\n\th = append(h, packUi32(SUBMIT_SM)...)\n\th = append(h, packUi32(s.Header.Status)...)\n\th = append(h, packUi32(s.Header.Sequence)...)\n\n\treturn append(h, b...)\n}\n<commit_msg>Proper SM length set for submit_sm<commit_after>package smpp34\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n)\n\nvar (\n\t\/\/ Required SubmitSm Fields\n\treqSSMFields = []string{\n\t\tSERVICE_TYPE,\n\t\tSOURCE_ADDR_TON,\n\t\tSOURCE_ADDR_NPI,\n\t\tSOURCE_ADDR,\n\t\tDEST_ADDR_TON,\n\t\tDEST_ADDR_NPI,\n\t\tDESTINATION_ADDR,\n\t\tESM_CLASS,\n\t\tPROTOCOL_ID,\n\t\tPRIORITY_FLAG,\n\t\tSCHEDULE_DELIVERY_TIME,\n\t\tVALIDITY_PERIOD,\n\t\tREGISTERED_DELIVERY,\n\t\tREPLACE_IF_PRESENT_FLAG,\n\t\tDATA_CODING,\n\t\tSM_DEFAULT_MSG_ID,\n\t\tSM_LENGTH,\n\t\tSHORT_MESSAGE,\n\t}\n)\n\ntype SubmitSm struct {\n\t*Header\n\tmandatoryFields map[string]Field\n\ttlvFields       map[uint16]*TLVField\n}\n\nfunc NewSubmitSm(hdr *Header, b []byte) (*SubmitSm, error) {\n\tr := bytes.NewBuffer(b)\n\n\tfields, tlvs, err := create_pdu_fields(reqSSMFields, r)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts := &SubmitSm{hdr, fields, tlvs}\n\n\treturn s, nil\n}\n\nfunc (s *SubmitSm) GetField(f string) Field {\n\treturn s.mandatoryFields[f]\n}\n\nfunc (s *SubmitSm) Fields() map[string]Field {\n\treturn s.mandatoryFields\n}\n\nfunc (s *SubmitSm) MandatoryFieldsList() []string {\n\treturn reqSSMFields\n}\n\nfunc (s *SubmitSm) GetHeader() *Header {\n\treturn s.Header\n}\n\nfunc (s *SubmitSm) SetField(f string, v interface{}) error {\n\tif s.validate_field(f, v) {\n\t\tfield := NewField(f, v)\n\n\t\tif field != nil {\n\t\t\ts.mandatoryFields[f] = field\n\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn errors.New(\"Invalid field value\")\n}\n\nfunc (s *SubmitSm) SetSeqNum(i uint32) {\n\ts.Header.Sequence = i\n}\n\nfunc (s *SubmitSm) SetTLVField(t, l int, v []byte) error {\n\tif l != len(v) {\n\t\treturn errors.New(\"Invalid TLV value lenght\")\n\t}\n\n\ts.tlvFields[uint16(t)] = &TLVField{uint16(t), uint16(l), v}\n\n\treturn nil\n}\n\nfunc (s *SubmitSm) validate_field(f string, v interface{}) bool {\n\tif included_check(s.MandatoryFieldsList(), f) && validate_pdu_field(f, v) {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (s *SubmitSm) TLVFields() map[uint16]*TLVField {\n\treturn s.tlvFields\n}\n\nfunc (s *SubmitSm) writeFields() []byte {\n\tb := []byte{}\n\n\tfor _, i := range s.MandatoryFieldsList() {\n\t\tv := s.mandatoryFields[i].ByteArray()\n\t\tb = append(b, v...)\n\t}\n\n\treturn b\n}\n\nfunc (s *SubmitSm) writeTLVFields() []byte {\n\tb := []byte{}\n\n\tfor _, v := range s.tlvFields {\n\t\tb = append(b, v.Writer()...)\n\t}\n\n\treturn b\n}\n\nfunc (s *SubmitSm) Writer() []byte {\n\t\/\/ Set SM_LENGTH\n\tsm := len(s.GetField(SHORT_MESSAGE).ByteArray())\n\ts.SetField(SM_LENGTH, sm)\n\n\tb := append(s.writeFields(), s.writeTLVFields()...)\n\th := packUi32(uint32(len(b) + 16))\n\th = append(h, packUi32(SUBMIT_SM)...)\n\th = append(h, packUi32(s.Header.Status)...)\n\th = append(h, packUi32(s.Header.Sequence)...)\n\n\treturn append(h, b...)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2015 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage testing\n\nimport (\n\t\"testing\"\n\n\t\"k8s.io\/apiserver\/pkg\/storage\/storagebackend\"\n\n\tclientv3 \"go.etcd.io\/etcd\/client\/v3\"\n\t\"go.etcd.io\/etcd\/tests\/v3\/integration\"\n)\n\n\/\/ EtcdTestServer encapsulates the datastructures needed to start local instance for testing\ntype EtcdTestServer struct {\n\tCertificatesDir string\n\tCertFile        string\n\tKeyFile         string\n\tCAFile          string\n\n\t\/\/ The following are lumped etcd3 test server params\n\tv3Cluster *integration.ClusterV3\n\tV3Client  *clientv3.Client\n}\n\n\/\/ Terminate will shutdown the running etcd server\nfunc (m *EtcdTestServer) Terminate(t *testing.T) {\n\tm.v3Cluster.Terminate(t)\n}\n\n\/\/ NewUnsecuredEtcd3TestClientServer creates a new client and server for testing\nfunc NewUnsecuredEtcd3TestClientServer(t *testing.T) (*EtcdTestServer, *storagebackend.Config) {\n\tintegration.BeforeTestExternal(t)\n\tserver := &EtcdTestServer{\n\t\tv3Cluster: integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1}),\n\t}\n\tserver.V3Client = server.v3Cluster.RandClient()\n\tconfig := &storagebackend.Config{\n\t\tType:   \"etcd3\",\n\t\tPrefix: PathPrefix(),\n\t\tTransport: storagebackend.TransportConfig{\n\t\t\tServerList: server.V3Client.Endpoints(),\n\t\t},\n\t\tPaging: true,\n\t}\n\treturn server, config\n}\n<commit_msg>Quiet embedded etcd logs<commit_after>\/*\nCopyright 2015 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage testing\n\nimport (\n\t\"io\/ioutil\"\n\t\"testing\"\n\n\t\"k8s.io\/apiserver\/pkg\/storage\/storagebackend\"\n\n\tgrpclogsettable \"github.com\/grpc-ecosystem\/go-grpc-middleware\/logging\/settable\"\n\tclientv3 \"go.etcd.io\/etcd\/client\/v3\"\n\t\"go.etcd.io\/etcd\/tests\/v3\/integration\"\n\t\"google.golang.org\/grpc\/grpclog\"\n)\n\nvar grpc_logger grpclogsettable.SettableLoggerV2\n\nfunc init() {\n\t\/\/ override logger set up by etcd integration test package\n\tgrpc_logger = grpclogsettable.ReplaceGrpcLoggerV2()\n}\n\n\/\/ EtcdTestServer encapsulates the datastructures needed to start local instance for testing\ntype EtcdTestServer struct {\n\tCertificatesDir string\n\tCertFile        string\n\tKeyFile         string\n\tCAFile          string\n\n\t\/\/ The following are lumped etcd3 test server params\n\tv3Cluster *integration.ClusterV3\n\tV3Client  *clientv3.Client\n}\n\n\/\/ Terminate will shutdown the running etcd server\nfunc (m *EtcdTestServer) Terminate(t *testing.T) {\n\tm.v3Cluster.Terminate(t)\n}\n\n\/\/ NewUnsecuredEtcd3TestClientServer creates a new client and server for testing\nfunc NewUnsecuredEtcd3TestClientServer(t *testing.T) (*EtcdTestServer, *storagebackend.Config) {\n\tintegration.BeforeTestExternal(t)\n\tgrpc_logger.Set(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, &testErrorWriter{t}))\n\tserver := &EtcdTestServer{\n\t\tv3Cluster: integration.NewClusterV3(&noLogT{t}, &integration.ClusterConfig{Size: 1}),\n\t}\n\tserver.V3Client = server.v3Cluster.RandClient()\n\tconfig := &storagebackend.Config{\n\t\tType:   \"etcd3\",\n\t\tPrefix: PathPrefix(),\n\t\tTransport: storagebackend.TransportConfig{\n\t\t\tServerList: server.V3Client.Endpoints(),\n\t\t},\n\t\tPaging: true,\n\t}\n\treturn server, config\n}\n\ntype noLogT struct {\n\ttesting.TB\n}\n\nfunc (q *noLogT) Log(s ...interface{}) {\n}\nfunc (q *noLogT) Logf(s string, params ...interface{}) {\n}\n\ntype testErrorWriter struct {\n\ttesting.TB\n}\n\nfunc (t *testErrorWriter) Write(b []byte) (int, error) {\n\tt.TB.Error(string(b))\n\treturn len(b), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package limiter\n\nimport (\n\t\"math\"\n\t\"math\/rand\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/garyburd\/redigo\/redis\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc init() {\n\trand.Seed(time.Now().UnixNano())\n}\n\nvar letterRunes = []rune(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n\nfunc RandStringRunes(n int) string {\n\tb := make([]rune, n)\n\tfor i := range b {\n\t\tb[i] = letterRunes[rand.Intn(len(letterRunes))]\n\t}\n\treturn string(b)\n}\n\n\/\/ TestLimiterMemory tests Limiter with memory store.\nfunc TestLimiterMemory(t *testing.T) {\n\trate, err := NewRateFromFormatted(\"3-M\")\n\tassert.Nil(t, err)\n\n\tstore := NewMemoryStoreWithOptions(StoreOptions{\n\t\tPrefix:          \"limitertests:memory\",\n\t\tCleanUpInterval: 30 * time.Second,\n\t})\n\n\ttestLimiter(t, store, rate)\n}\n\n\/\/ TestLimiterRedis tests Limiter with Redis store.\nfunc TestLimiterRedis(t *testing.T) {\n\trate, err := NewRateFromFormatted(\"3-M\")\n\tassert.Nil(t, err)\n\n\trandPrefix := RandStringRunes(10)\n\tstore, err := NewRedisStoreWithOptions(\n\t\tnewRedisPool(),\n\t\tStoreOptions{Prefix: \"limitertests:redis_\" + randPrefix, MaxRetry: 3})\n\n\tassert.Nil(t, err)\n\n\ttestLimiter(t, store, rate)\n}\n\nfunc testLimiter(t *testing.T, store Store, rate Rate) {\n\tlimiter := NewLimiter(store, rate)\n\n\ti := 1\n\tfor i <= 5 {\n\t\tif i <= 3 {\n\t\t\tctx, err := limiter.Peek(\"boo\")\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.Equal(t, int64(3-(i-1)), ctx.Remaining)\n\t\t}\n\n\t\tctx, err := limiter.Get(\"boo\")\n\t\tassert.NoError(t, err)\n\n\t\tif i <= 3 {\n\t\t\tassert.Equal(t, int64(3), ctx.Limit)\n\t\t\tassert.Equal(t, int64(3-i), ctx.Remaining)\n\t\t\tassert.True(t, math.Ceil(time.Since(time.Unix(ctx.Reset, 0)).Seconds()) <= 60)\n\t\t\tctx, err := limiter.Peek(\"boo\")\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.Equal(t, int64(3-i), ctx.Remaining)\n\t\t} else {\n\t\t\tassert.Equal(t, int64(3), ctx.Limit)\n\t\t\tassert.True(t, ctx.Remaining == 0)\n\t\t\tassert.True(t, math.Ceil(time.Since(time.Unix(ctx.Reset, 0)).Seconds()) <= 60)\n\t\t}\n\n\t\ti++\n\t}\n\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Helpers\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ newRedisPool returns\nfunc newRedisPool() *redis.Pool {\n\treturn redis.NewPool(func() (redis.Conn, error) {\n\t\tc, err := redis.Dial(\"tcp\", \":6379\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn c, err\n\t}, 100)\n}\n\n\/\/ newRedisLimiter returns an instance of limiter with redis backend.\nfunc newRedisLimiter(formattedQuota string, prefix string) *Limiter {\n\trate, err := NewRateFromFormatted(formattedQuota)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tstore, err := NewRedisStoreWithOptions(\n\t\tnewRedisPool(),\n\t\tStoreOptions{Prefix: prefix, MaxRetry: 3})\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn NewLimiter(store, rate)\n}\n<commit_msg>chore: delete store and middleware unit test<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\n * ZDNS Copyright 2016 Regents of the University of Michigan\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy\n * of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License.\n *\/\n\npackage alookup\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"net\"\n\t\"strings\"\n\n\t\"github.com\/zmap\/dns\"\n\t\"github.com\/zmap\/zdns\"\n\t\"github.com\/zmap\/zdns\/modules\/miekg\"\n)\n\ntype Result struct {\n\tIPv4Addresses []string `json:\"ipv4_addresses,omitempty\" groups:\"short,normal,long,trace\"`\n\tIPv6Addresses []string `json:\"ipv6_addresses,omitempty\" groups:\"short,normal,long,trace\"`\n}\n\n\/\/ Per Connection Lookup ======================================================\n\/\/\ntype Lookup struct {\n\tFactory *RoutineLookupFactory\n\tmiekg.Lookup\n}\n\nfunc (s *Lookup) DoLookup(name, nameServer string) (interface{}, zdns.Trace, zdns.Status, error) {\n\tif nameServer == \"\" {\n\t\tnameServer = s.Factory.Factory.RandomNameServer()\n\t}\n\treturn s.DoTargetedLookup(name, nameServer)\n}\n\n\/\/ Verify that A record is indeed IPv4 and AAAA is IPv6\nfunc verifyAddress(ansType string, ip string) bool {\n\tvar isIpv4, isIpv6 bool\n\tif net.ParseIP(ip) != nil {\n\t\tisIpv6 = strings.Contains(ip, \":\")\n\t\tisIpv4 = !isIpv6\n\t}\n\tif ansType == \"A\" {\n\t\treturn isIpv4\n\t} else if ansType == \"AAAA\" {\n\t\treturn isIpv6\n\t}\n\treturn !isIpv4 && !isIpv6\n}\n\nfunc populateResults(records []interface{}, dnsType uint16, candidateSet map[string][]miekg.Answer, cnameSet map[string][]miekg.Answer, garbage map[string][]miekg.Answer) {\n\tfor _, a := range records {\n\t\t\/\/ filter only valid answers of requested type or CNAME (#163)\n\t\tif ans, ok := a.(miekg.Answer); ok {\n\t\t\tlowerCaseName := strings.ToLower(ans.Name)\n\t\t\t\/\/ Verify that the answer type matches requested type\n\t\t\tif verifyAddress(ans.Type, ans.Answer) {\n\t\t\t\tansType := dns.StringToType[ans.Type]\n\t\t\t\tif dnsType == ansType {\n\t\t\t\t\tcandidateSet[lowerCaseName] = append(candidateSet[lowerCaseName], ans)\n\t\t\t\t} else if ok && dns.TypeCNAME == ansType {\n\t\t\t\t\tcnameSet[lowerCaseName] = append(cnameSet[lowerCaseName], ans)\n\t\t\t\t} else {\n\t\t\t\t\tgarbage[lowerCaseName] = append(garbage[lowerCaseName], ans)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgarbage[lowerCaseName] = append(garbage[lowerCaseName], ans)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (s *Lookup) doLookupProtocol(name, nameServer string, dnsType uint16, candidateSet map[string][]miekg.Answer, cnameSet map[string][]miekg.Answer, origName string, depth int) ([]string, []interface{}, zdns.Status, error) {\n\t\/\/ avoid infinite loops\n\tif name == origName && depth != 0 {\n\t\treturn nil, make([]interface{}, 0), zdns.STATUS_ERROR, errors.New(\"infinite redirection loop\")\n\t}\n\tif depth > 10 {\n\t\treturn nil, make([]interface{}, 0), zdns.STATUS_ERROR, errors.New(\"max recursion depth reached\")\n\t}\n\t\/\/ check if the record is already in our cache. if not, perform normal A lookup and\n\t\/\/ see what comes back. Then iterate over results and if needed, perform further lookups\n\tvar trace []interface{}\n\tgarbage := map[string][]miekg.Answer{}\n\tif _, ok := candidateSet[name]; !ok {\n\t\tvar miekgResult interface{}\n\t\tvar status zdns.Status\n\t\tvar err error\n\t\tmiekgResult, trace, status, err = s.DoMiekgLookup(miekg.Question{Name: name, Type: dnsType}, nameServer)\n\t\tif status != zdns.STATUS_NOERROR || err != nil {\n\t\t\treturn nil, trace, status, err\n\t\t}\n\n\t\tpopulateResults(miekgResult.(miekg.Result).Answers, dnsType, candidateSet, cnameSet, garbage)\n\t\tpopulateResults(miekgResult.(miekg.Result).Additional, dnsType, candidateSet, cnameSet, garbage)\n\t}\n\t\/\/ our cache should now have any data that exists about the current name\n\tif res, ok := candidateSet[name]; ok && len(res) > 0 {\n\t\t\/\/ we have IP addresses to hand back to the user. let's make an easy-to-use array of strings\n\t\tvar ips []string\n\t\tfor _, answer := range res {\n\t\t\tips = append(ips, answer.Answer)\n\t\t}\n\t\treturn ips, trace, zdns.STATUS_NOERROR, nil\n\t} else if res, ok = cnameSet[name]; ok && len(res) > 0 {\n\t\t\/\/ we have a CNAME and need to further recurse to find IPs\n\t\tshortName := strings.ToLower(res[0].Answer[0 : len(res[0].Answer)-1])\n\t\tres, secondTrace, status, err := s.doLookupProtocol(shortName, nameServer, dnsType, candidateSet, cnameSet, origName, depth+1)\n\t\ttrace = append(trace, secondTrace...)\n\t\treturn res, trace, status, err\n\t} else if res, ok = garbage[name]; ok && len(res) > 0 {\n\t\treturn nil, trace, zdns.STATUS_ERROR, errors.New(\"unexpected record type received\")\n\t} else {\n\t\t\/\/ we have no data whatsoever about this name. return an empty recordset to the user\n\t\tvar ips []string\n\t\treturn ips, trace, zdns.STATUS_NOERROR, nil\n\t}\n}\n\nfunc safeStatus(status zdns.Status) bool {\n\treturn status == zdns.STATUS_NOERROR\n}\n\nfunc (s *Lookup) DoTargetedLookup(name, nameServer string) (interface{}, []interface{}, zdns.Status, error) {\n\tres := Result{}\n\tcandidateSet := map[string][]miekg.Answer{}\n\tcnameSet := map[string][]miekg.Answer{}\n\tlookupIpv4 := s.Factory.Factory.IPv4Lookup || !s.Factory.Factory.IPv6Lookup\n\tlookupIpv6 := s.Factory.Factory.IPv6Lookup\n\tvar ipv4 []string\n\tvar ipv6 []string\n\tvar ipv4Trace []interface{}\n\tvar ipv6Trace []interface{}\n\tvar ipv4status zdns.Status\n\tvar ipv6status zdns.Status\n\tif lookupIpv4 {\n\t\tipv4, ipv4Trace, ipv4status, _ = s.doLookupProtocol(name, nameServer, dns.TypeA, candidateSet, cnameSet, name, 0)\n\t\tres.IPv4Addresses = make([]string, len(ipv4))\n\t\tcopy(res.IPv4Addresses, ipv4)\n\t}\n\tcandidateSet = map[string][]miekg.Answer{}\n\tcnameSet = map[string][]miekg.Answer{}\n\tif lookupIpv6 {\n\t\tipv6, ipv6Trace, ipv6status, _ = s.doLookupProtocol(name, nameServer, dns.TypeAAAA, candidateSet, cnameSet, name, 0)\n\t\tres.IPv6Addresses = make([]string, len(ipv6))\n\t\tcopy(res.IPv6Addresses, ipv6)\n\t}\n\n\tcombinedTrace := append(ipv4Trace, ipv6Trace...)\n\n\t\/\/ alookup is only expected to return IP addresses. Hence irrespective of the\n\t\/\/ status returned from miekgdns, we return NO_ANSWER in case of missing IPs\n\tif len(res.IPv4Addresses) == 0 && len(res.IPv6Addresses) == 0 {\n\t\tif lookupIpv4 && !safeStatus(ipv4status) {\n\t\t\treturn nil, combinedTrace, ipv4status, nil\n\t\t} else if lookupIpv6 && !safeStatus(ipv6status) {\n\t\t\treturn nil, combinedTrace, ipv6status, nil\n\t\t} else {\n\t\t\treturn nil, combinedTrace, zdns.STATUS_NOERROR, nil\n\t\t}\n\t}\n\treturn res, combinedTrace, zdns.STATUS_NOERROR, nil\n}\n\n\/\/ Per GoRoutine Factory ======================================================\n\/\/\ntype RoutineLookupFactory struct {\n\tmiekg.RoutineLookupFactory\n\tFactory *GlobalLookupFactory\n}\n\nfunc (s *RoutineLookupFactory) MakeLookup() (zdns.Lookup, error) {\n\ta := Lookup{Factory: s}\n\tnameServer := s.Factory.RandomNameServer()\n\ta.Initialize(nameServer, dns.TypeA, dns.ClassINET, &s.RoutineLookupFactory)\n\treturn &a, nil\n}\n\n\/\/ Global Factory =============================================================\n\/\/\ntype GlobalLookupFactory struct {\n\tmiekg.GlobalLookupFactory\n\tIPv4Lookup bool\n\tIPv6Lookup bool\n}\n\nfunc (s *GlobalLookupFactory) AddFlags(f *flag.FlagSet) {\n\tf.BoolVar(&s.IPv4Lookup, \"ipv4-lookup\", false, \"perform A lookups for each server\")\n\tf.BoolVar(&s.IPv6Lookup, \"ipv6-lookup\", false, \"perform AAAA record lookups for each server\")\n}\n\n\/\/ Command-line Help Documentation. This is the descriptive text what is\n\/\/ returned when you run zdns module --help\nfunc (s *GlobalLookupFactory) Help() string {\n\treturn \"\"\n}\n\nfunc (s *GlobalLookupFactory) MakeRoutineFactory(threadID int) (zdns.RoutineLookupFactory, error) {\n\tr := new(RoutineLookupFactory)\n\tr.Factory = s\n\tr.RoutineLookupFactory.Factory = &s.GlobalLookupFactory\n\tr.Initialize(s.GlobalConf)\n\tr.ThreadID = threadID\n\treturn r, nil\n}\n\n\/\/ Global Registration ========================================================\n\/\/\nfunc init() {\n\ts := new(GlobalLookupFactory)\n\tzdns.RegisterLookup(\"ALOOKUP\", s)\n}\n<commit_msg>Initialize bools to false<commit_after>\/*\n * ZDNS Copyright 2016 Regents of the University of Michigan\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy\n * of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License.\n *\/\n\npackage alookup\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"net\"\n\t\"strings\"\n\n\t\"github.com\/zmap\/dns\"\n\t\"github.com\/zmap\/zdns\"\n\t\"github.com\/zmap\/zdns\/modules\/miekg\"\n)\n\ntype Result struct {\n\tIPv4Addresses []string `json:\"ipv4_addresses,omitempty\" groups:\"short,normal,long,trace\"`\n\tIPv6Addresses []string `json:\"ipv6_addresses,omitempty\" groups:\"short,normal,long,trace\"`\n}\n\n\/\/ Per Connection Lookup ======================================================\n\/\/\ntype Lookup struct {\n\tFactory *RoutineLookupFactory\n\tmiekg.Lookup\n}\n\nfunc (s *Lookup) DoLookup(name, nameServer string) (interface{}, zdns.Trace, zdns.Status, error) {\n\tif nameServer == \"\" {\n\t\tnameServer = s.Factory.Factory.RandomNameServer()\n\t}\n\treturn s.DoTargetedLookup(name, nameServer)\n}\n\n\/\/ Verify that A record is indeed IPv4 and AAAA is IPv6\nfunc verifyAddress(ansType string, ip string) bool {\n\tisIpv4 := false\n\tisIpv6 := false\n\tif net.ParseIP(ip) != nil {\n\t\tisIpv6 = strings.Contains(ip, \":\")\n\t\tisIpv4 = !isIpv6\n\t}\n\tif ansType == \"A\" {\n\t\treturn isIpv4\n\t} else if ansType == \"AAAA\" {\n\t\treturn isIpv6\n\t}\n\treturn !isIpv4 && !isIpv6\n}\n\nfunc populateResults(records []interface{}, dnsType uint16, candidateSet map[string][]miekg.Answer, cnameSet map[string][]miekg.Answer, garbage map[string][]miekg.Answer) {\n\tfor _, a := range records {\n\t\t\/\/ filter only valid answers of requested type or CNAME (#163)\n\t\tif ans, ok := a.(miekg.Answer); ok {\n\t\t\tlowerCaseName := strings.ToLower(ans.Name)\n\t\t\t\/\/ Verify that the answer type matches requested type\n\t\t\tif verifyAddress(ans.Type, ans.Answer) {\n\t\t\t\tansType := dns.StringToType[ans.Type]\n\t\t\t\tif dnsType == ansType {\n\t\t\t\t\tcandidateSet[lowerCaseName] = append(candidateSet[lowerCaseName], ans)\n\t\t\t\t} else if ok && dns.TypeCNAME == ansType {\n\t\t\t\t\tcnameSet[lowerCaseName] = append(cnameSet[lowerCaseName], ans)\n\t\t\t\t} else {\n\t\t\t\t\tgarbage[lowerCaseName] = append(garbage[lowerCaseName], ans)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgarbage[lowerCaseName] = append(garbage[lowerCaseName], ans)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (s *Lookup) doLookupProtocol(name, nameServer string, dnsType uint16, candidateSet map[string][]miekg.Answer, cnameSet map[string][]miekg.Answer, origName string, depth int) ([]string, []interface{}, zdns.Status, error) {\n\t\/\/ avoid infinite loops\n\tif name == origName && depth != 0 {\n\t\treturn nil, make([]interface{}, 0), zdns.STATUS_ERROR, errors.New(\"infinite redirection loop\")\n\t}\n\tif depth > 10 {\n\t\treturn nil, make([]interface{}, 0), zdns.STATUS_ERROR, errors.New(\"max recursion depth reached\")\n\t}\n\t\/\/ check if the record is already in our cache. if not, perform normal A lookup and\n\t\/\/ see what comes back. Then iterate over results and if needed, perform further lookups\n\tvar trace []interface{}\n\tgarbage := map[string][]miekg.Answer{}\n\tif _, ok := candidateSet[name]; !ok {\n\t\tvar miekgResult interface{}\n\t\tvar status zdns.Status\n\t\tvar err error\n\t\tmiekgResult, trace, status, err = s.DoMiekgLookup(miekg.Question{Name: name, Type: dnsType}, nameServer)\n\t\tif status != zdns.STATUS_NOERROR || err != nil {\n\t\t\treturn nil, trace, status, err\n\t\t}\n\n\t\tpopulateResults(miekgResult.(miekg.Result).Answers, dnsType, candidateSet, cnameSet, garbage)\n\t\tpopulateResults(miekgResult.(miekg.Result).Additional, dnsType, candidateSet, cnameSet, garbage)\n\t}\n\t\/\/ our cache should now have any data that exists about the current name\n\tif res, ok := candidateSet[name]; ok && len(res) > 0 {\n\t\t\/\/ we have IP addresses to hand back to the user. let's make an easy-to-use array of strings\n\t\tvar ips []string\n\t\tfor _, answer := range res {\n\t\t\tips = append(ips, answer.Answer)\n\t\t}\n\t\treturn ips, trace, zdns.STATUS_NOERROR, nil\n\t} else if res, ok = cnameSet[name]; ok && len(res) > 0 {\n\t\t\/\/ we have a CNAME and need to further recurse to find IPs\n\t\tshortName := strings.ToLower(res[0].Answer[0 : len(res[0].Answer)-1])\n\t\tres, secondTrace, status, err := s.doLookupProtocol(shortName, nameServer, dnsType, candidateSet, cnameSet, origName, depth+1)\n\t\ttrace = append(trace, secondTrace...)\n\t\treturn res, trace, status, err\n\t} else if res, ok = garbage[name]; ok && len(res) > 0 {\n\t\treturn nil, trace, zdns.STATUS_ERROR, errors.New(\"unexpected record type received\")\n\t} else {\n\t\t\/\/ we have no data whatsoever about this name. return an empty recordset to the user\n\t\tvar ips []string\n\t\treturn ips, trace, zdns.STATUS_NOERROR, nil\n\t}\n}\n\nfunc safeStatus(status zdns.Status) bool {\n\treturn status == zdns.STATUS_NOERROR\n}\n\nfunc (s *Lookup) DoTargetedLookup(name, nameServer string) (interface{}, []interface{}, zdns.Status, error) {\n\tres := Result{}\n\tcandidateSet := map[string][]miekg.Answer{}\n\tcnameSet := map[string][]miekg.Answer{}\n\tlookupIpv4 := s.Factory.Factory.IPv4Lookup || !s.Factory.Factory.IPv6Lookup\n\tlookupIpv6 := s.Factory.Factory.IPv6Lookup\n\tvar ipv4 []string\n\tvar ipv6 []string\n\tvar ipv4Trace []interface{}\n\tvar ipv6Trace []interface{}\n\tvar ipv4status zdns.Status\n\tvar ipv6status zdns.Status\n\tif lookupIpv4 {\n\t\tipv4, ipv4Trace, ipv4status, _ = s.doLookupProtocol(name, nameServer, dns.TypeA, candidateSet, cnameSet, name, 0)\n\t\tres.IPv4Addresses = make([]string, len(ipv4))\n\t\tcopy(res.IPv4Addresses, ipv4)\n\t}\n\tcandidateSet = map[string][]miekg.Answer{}\n\tcnameSet = map[string][]miekg.Answer{}\n\tif lookupIpv6 {\n\t\tipv6, ipv6Trace, ipv6status, _ = s.doLookupProtocol(name, nameServer, dns.TypeAAAA, candidateSet, cnameSet, name, 0)\n\t\tres.IPv6Addresses = make([]string, len(ipv6))\n\t\tcopy(res.IPv6Addresses, ipv6)\n\t}\n\n\tcombinedTrace := append(ipv4Trace, ipv6Trace...)\n\n\t\/\/ alookup is only expected to return IP addresses. Hence irrespective of the\n\t\/\/ status returned from miekgdns, we return NO_ANSWER in case of missing IPs\n\tif len(res.IPv4Addresses) == 0 && len(res.IPv6Addresses) == 0 {\n\t\tif lookupIpv4 && !safeStatus(ipv4status) {\n\t\t\treturn nil, combinedTrace, ipv4status, nil\n\t\t} else if lookupIpv6 && !safeStatus(ipv6status) {\n\t\t\treturn nil, combinedTrace, ipv6status, nil\n\t\t} else {\n\t\t\treturn nil, combinedTrace, zdns.STATUS_NOERROR, nil\n\t\t}\n\t}\n\treturn res, combinedTrace, zdns.STATUS_NOERROR, nil\n}\n\n\/\/ Per GoRoutine Factory ======================================================\n\/\/\ntype RoutineLookupFactory struct {\n\tmiekg.RoutineLookupFactory\n\tFactory *GlobalLookupFactory\n}\n\nfunc (s *RoutineLookupFactory) MakeLookup() (zdns.Lookup, error) {\n\ta := Lookup{Factory: s}\n\tnameServer := s.Factory.RandomNameServer()\n\ta.Initialize(nameServer, dns.TypeA, dns.ClassINET, &s.RoutineLookupFactory)\n\treturn &a, nil\n}\n\n\/\/ Global Factory =============================================================\n\/\/\ntype GlobalLookupFactory struct {\n\tmiekg.GlobalLookupFactory\n\tIPv4Lookup bool\n\tIPv6Lookup bool\n}\n\nfunc (s *GlobalLookupFactory) AddFlags(f *flag.FlagSet) {\n\tf.BoolVar(&s.IPv4Lookup, \"ipv4-lookup\", false, \"perform A lookups for each server\")\n\tf.BoolVar(&s.IPv6Lookup, \"ipv6-lookup\", false, \"perform AAAA record lookups for each server\")\n}\n\n\/\/ Command-line Help Documentation. This is the descriptive text what is\n\/\/ returned when you run zdns module --help\nfunc (s *GlobalLookupFactory) Help() string {\n\treturn \"\"\n}\n\nfunc (s *GlobalLookupFactory) MakeRoutineFactory(threadID int) (zdns.RoutineLookupFactory, error) {\n\tr := new(RoutineLookupFactory)\n\tr.Factory = s\n\tr.RoutineLookupFactory.Factory = &s.GlobalLookupFactory\n\tr.Initialize(s.GlobalConf)\n\tr.ThreadID = threadID\n\treturn r, nil\n}\n\n\/\/ Global Registration ========================================================\n\/\/\nfunc init() {\n\ts := new(GlobalLookupFactory)\n\tzdns.RegisterLookup(\"ALOOKUP\", s)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage pkginit\n\nimport (\n\t\"cmd\/compile\/internal\/base\"\n\t\"cmd\/compile\/internal\/ir\"\n\t\"cmd\/compile\/internal\/noder\"\n\t\"cmd\/compile\/internal\/objw\"\n\t\"cmd\/compile\/internal\/staticinit\"\n\t\"cmd\/compile\/internal\/typecheck\"\n\t\"cmd\/compile\/internal\/types\"\n\t\"cmd\/internal\/obj\"\n\t\"cmd\/internal\/src\"\n)\n\n\/\/ MakeInit creates a synthetic init function to handle any\n\/\/ package-scope initialization statements.\n\/\/\n\/\/ TODO(mdempsky): Move into noder, so that the types2-based frontends\n\/\/ can use Info.InitOrder instead.\nfunc MakeInit() {\n\tnf := initOrder(typecheck.Target.Decls)\n\tif len(nf) == 0 {\n\t\treturn\n\t}\n\n\t\/\/ Make a function that contains all the initialization statements.\n\tbase.Pos = nf[0].Pos() \/\/ prolog\/epilog gets line number of first init stmt\n\tinitializers := typecheck.Lookup(\"init\")\n\tfn := typecheck.DeclFunc(initializers, nil, nil, nil)\n\tfor _, dcl := range typecheck.InitTodoFunc.Dcl {\n\t\tdcl.Curfn = fn\n\t}\n\tfn.Dcl = append(fn.Dcl, typecheck.InitTodoFunc.Dcl...)\n\ttypecheck.InitTodoFunc.Dcl = nil\n\n\t\/\/ Suppress useless \"can inline\" diagnostics.\n\t\/\/ Init functions are only called dynamically.\n\tfn.SetInlinabilityChecked(true)\n\n\tfn.Body = nf\n\ttypecheck.FinishFuncBody()\n\n\ttypecheck.Func(fn)\n\tir.WithFunc(fn, func() {\n\t\ttypecheck.Stmts(nf)\n\t})\n\ttypecheck.Target.Decls = append(typecheck.Target.Decls, fn)\n\n\t\/\/ Prepend to Inits, so it runs first, before any user-declared init\n\t\/\/ functions.\n\ttypecheck.Target.Inits = append([]*ir.Func{fn}, typecheck.Target.Inits...)\n\n\tif typecheck.InitTodoFunc.Dcl != nil {\n\t\t\/\/ We only generate temps using InitTodoFunc if there\n\t\t\/\/ are package-scope initialization statements, so\n\t\t\/\/ something's weird if we get here.\n\t\tbase.Fatalf(\"InitTodoFunc still has declarations\")\n\t}\n\ttypecheck.InitTodoFunc = nil\n}\n\n\/\/ Task makes and returns an initialization record for the package.\n\/\/ See runtime\/proc.go:initTask for its layout.\n\/\/ The 3 tasks for initialization are:\n\/\/  1. Initialize all of the packages the current package depends on.\n\/\/  2. Initialize all the variables that have initializers.\n\/\/  3. Run any init functions.\nfunc Task() *ir.Name {\n\tvar deps []*obj.LSym \/\/ initTask records for packages the current package depends on\n\tvar fns []*obj.LSym  \/\/ functions to call for package initialization\n\n\t\/\/ Find imported packages with init tasks.\n\tfor _, pkg := range typecheck.Target.Imports {\n\t\tn := typecheck.Resolve(ir.NewIdent(base.Pos, pkg.Lookup(\".inittask\")))\n\t\tif n.Op() == ir.ONONAME {\n\t\t\tcontinue\n\t\t}\n\t\tif n.Op() != ir.ONAME || n.(*ir.Name).Class != ir.PEXTERN {\n\t\t\tbase.Fatalf(\"bad inittask: %v\", n)\n\t\t}\n\t\tdeps = append(deps, n.(*ir.Name).Linksym())\n\t}\n\tif base.Flag.ASan {\n\t\t\/\/ Make an initialization function to call runtime.asanregisterglobals to register an\n\t\t\/\/ array of instrumented global variables when -asan is enabled. An instrumented global\n\t\t\/\/ variable is described by a structure.\n\t\t\/\/ See the _asan_global structure declared in src\/runtime\/asan\/asan.go.\n\t\t\/\/\n\t\t\/\/ func init {\n\t\t\/\/ \t\tvar globals []_asan_global {...}\n\t\t\/\/ \t\tasanregisterglobals(&globals[0], len(globals))\n\t\t\/\/ }\n\t\tfor _, n := range typecheck.Target.Externs {\n\t\t\tif canInstrumentGlobal(n) {\n\t\t\t\tname := n.Sym().Name\n\t\t\t\tInstrumentGlobalsMap[name] = n\n\t\t\t\tInstrumentGlobalsSlice = append(InstrumentGlobalsSlice, n)\n\t\t\t}\n\t\t}\n\t\tni := len(InstrumentGlobalsMap)\n\t\tif ni != 0 {\n\t\t\t\/\/ Make an init._ function.\n\t\t\tbase.Pos = base.AutogeneratedPos\n\t\t\ttypecheck.DeclContext = ir.PEXTERN\n\t\t\tname := noder.Renameinit()\n\t\t\tfnInit := typecheck.DeclFunc(name, ir.NewFuncType(base.Pos, nil, nil, nil))\n\n\t\t\t\/\/ Get an array of intrumented global variables.\n\t\t\tglobals := instrumentGlobals(fnInit)\n\n\t\t\t\/\/ Call runtime.asanregisterglobals function to poison redzones.\n\t\t\t\/\/ runtime.asanregisterglobals(unsafe.Pointer(&globals[0]), ni)\n\t\t\tasanf := typecheck.NewName(ir.Pkgs.Runtime.Lookup(\"asanregisterglobals\"))\n\t\t\tir.MarkFunc(asanf)\n\t\t\tasanf.SetType(types.NewSignature(types.NoPkg, nil, nil, []*types.Field{\n\t\t\t\ttypes.NewField(base.Pos, nil, types.Types[types.TUNSAFEPTR]),\n\t\t\t\ttypes.NewField(base.Pos, nil, types.Types[types.TUINTPTR]),\n\t\t\t}, nil))\n\t\t\tasancall := ir.NewCallExpr(base.Pos, ir.OCALL, asanf, nil)\n\t\t\tasancall.Args.Append(typecheck.ConvNop(typecheck.NodAddr(\n\t\t\t\tir.NewIndexExpr(base.Pos, globals, ir.NewInt(0))), types.Types[types.TUNSAFEPTR]))\n\t\t\tasancall.Args.Append(typecheck.ConvNop(ir.NewInt(int64(ni)), types.Types[types.TUINTPTR]))\n\n\t\t\tfnInit.Body.Append(asancall)\n\t\t\ttypecheck.FinishFuncBody()\n\t\t\ttypecheck.Func(fnInit)\n\t\t\tir.CurFunc = fnInit\n\t\t\ttypecheck.Stmts(fnInit.Body)\n\t\t\tir.CurFunc = nil\n\n\t\t\ttypecheck.Target.Decls = append(typecheck.Target.Decls, fnInit)\n\t\t\ttypecheck.Target.Inits = append(typecheck.Target.Inits, fnInit)\n\t\t}\n\t}\n\n\t\/\/ Record user init functions.\n\tfor _, fn := range typecheck.Target.Inits {\n\t\tif fn.Sym().Name == \"init\" {\n\t\t\t\/\/ Synthetic init function for initialization of package-scope\n\t\t\t\/\/ variables. We can use staticinit to optimize away static\n\t\t\t\/\/ assignments.\n\t\t\ts := staticinit.Schedule{\n\t\t\t\tPlans: make(map[ir.Node]*staticinit.Plan),\n\t\t\t\tTemps: make(map[ir.Node]*ir.Name),\n\t\t\t}\n\t\t\tfor _, n := range fn.Body {\n\t\t\t\ts.StaticInit(n)\n\t\t\t}\n\t\t\tfn.Body = s.Out\n\t\t\tir.WithFunc(fn, func() {\n\t\t\t\ttypecheck.Stmts(fn.Body)\n\t\t\t})\n\n\t\t\tif len(fn.Body) == 0 {\n\t\t\t\tfn.Body = []ir.Node{ir.NewBlockStmt(src.NoXPos, nil)}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Skip init functions with empty bodies.\n\t\tif len(fn.Body) == 1 {\n\t\t\tif stmt := fn.Body[0]; stmt.Op() == ir.OBLOCK && len(stmt.(*ir.BlockStmt).List) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tfns = append(fns, fn.Nname.Linksym())\n\t}\n\n\tif len(deps) == 0 && len(fns) == 0 && types.LocalPkg.Name != \"main\" && types.LocalPkg.Name != \"runtime\" {\n\t\treturn nil \/\/ nothing to initialize\n\t}\n\n\t\/\/ Make an .inittask structure.\n\tsym := typecheck.Lookup(\".inittask\")\n\ttask := typecheck.NewName(sym)\n\ttask.SetType(types.Types[types.TUINT8]) \/\/ fake type\n\ttask.Class = ir.PEXTERN\n\tsym.Def = task\n\tlsym := task.Linksym()\n\tot := 0\n\tot = objw.Uintptr(lsym, ot, 0) \/\/ state: not initialized yet\n\tot = objw.Uintptr(lsym, ot, uint64(len(deps)))\n\tot = objw.Uintptr(lsym, ot, uint64(len(fns)))\n\tfor _, d := range deps {\n\t\tot = objw.SymPtr(lsym, ot, d, 0)\n\t}\n\tfor _, f := range fns {\n\t\tot = objw.SymPtr(lsym, ot, f, 0)\n\t}\n\t\/\/ An initTask has pointers, but none into the Go heap.\n\t\/\/ It's not quite read only, the state field must be modifiable.\n\tobjw.Global(lsym, int32(ot), obj.NOPTR)\n\treturn task\n}\n<commit_msg>cmd\/compile\/internal\/pkginit: fix typecheck.DeclFunc call<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage pkginit\n\nimport (\n\t\"cmd\/compile\/internal\/base\"\n\t\"cmd\/compile\/internal\/ir\"\n\t\"cmd\/compile\/internal\/noder\"\n\t\"cmd\/compile\/internal\/objw\"\n\t\"cmd\/compile\/internal\/staticinit\"\n\t\"cmd\/compile\/internal\/typecheck\"\n\t\"cmd\/compile\/internal\/types\"\n\t\"cmd\/internal\/obj\"\n\t\"cmd\/internal\/src\"\n)\n\n\/\/ MakeInit creates a synthetic init function to handle any\n\/\/ package-scope initialization statements.\n\/\/\n\/\/ TODO(mdempsky): Move into noder, so that the types2-based frontends\n\/\/ can use Info.InitOrder instead.\nfunc MakeInit() {\n\tnf := initOrder(typecheck.Target.Decls)\n\tif len(nf) == 0 {\n\t\treturn\n\t}\n\n\t\/\/ Make a function that contains all the initialization statements.\n\tbase.Pos = nf[0].Pos() \/\/ prolog\/epilog gets line number of first init stmt\n\tinitializers := typecheck.Lookup(\"init\")\n\tfn := typecheck.DeclFunc(initializers, nil, nil, nil)\n\tfor _, dcl := range typecheck.InitTodoFunc.Dcl {\n\t\tdcl.Curfn = fn\n\t}\n\tfn.Dcl = append(fn.Dcl, typecheck.InitTodoFunc.Dcl...)\n\ttypecheck.InitTodoFunc.Dcl = nil\n\n\t\/\/ Suppress useless \"can inline\" diagnostics.\n\t\/\/ Init functions are only called dynamically.\n\tfn.SetInlinabilityChecked(true)\n\n\tfn.Body = nf\n\ttypecheck.FinishFuncBody()\n\n\ttypecheck.Func(fn)\n\tir.WithFunc(fn, func() {\n\t\ttypecheck.Stmts(nf)\n\t})\n\ttypecheck.Target.Decls = append(typecheck.Target.Decls, fn)\n\n\t\/\/ Prepend to Inits, so it runs first, before any user-declared init\n\t\/\/ functions.\n\ttypecheck.Target.Inits = append([]*ir.Func{fn}, typecheck.Target.Inits...)\n\n\tif typecheck.InitTodoFunc.Dcl != nil {\n\t\t\/\/ We only generate temps using InitTodoFunc if there\n\t\t\/\/ are package-scope initialization statements, so\n\t\t\/\/ something's weird if we get here.\n\t\tbase.Fatalf(\"InitTodoFunc still has declarations\")\n\t}\n\ttypecheck.InitTodoFunc = nil\n}\n\n\/\/ Task makes and returns an initialization record for the package.\n\/\/ See runtime\/proc.go:initTask for its layout.\n\/\/ The 3 tasks for initialization are:\n\/\/  1. Initialize all of the packages the current package depends on.\n\/\/  2. Initialize all the variables that have initializers.\n\/\/  3. Run any init functions.\nfunc Task() *ir.Name {\n\tvar deps []*obj.LSym \/\/ initTask records for packages the current package depends on\n\tvar fns []*obj.LSym  \/\/ functions to call for package initialization\n\n\t\/\/ Find imported packages with init tasks.\n\tfor _, pkg := range typecheck.Target.Imports {\n\t\tn := typecheck.Resolve(ir.NewIdent(base.Pos, pkg.Lookup(\".inittask\")))\n\t\tif n.Op() == ir.ONONAME {\n\t\t\tcontinue\n\t\t}\n\t\tif n.Op() != ir.ONAME || n.(*ir.Name).Class != ir.PEXTERN {\n\t\t\tbase.Fatalf(\"bad inittask: %v\", n)\n\t\t}\n\t\tdeps = append(deps, n.(*ir.Name).Linksym())\n\t}\n\tif base.Flag.ASan {\n\t\t\/\/ Make an initialization function to call runtime.asanregisterglobals to register an\n\t\t\/\/ array of instrumented global variables when -asan is enabled. An instrumented global\n\t\t\/\/ variable is described by a structure.\n\t\t\/\/ See the _asan_global structure declared in src\/runtime\/asan\/asan.go.\n\t\t\/\/\n\t\t\/\/ func init {\n\t\t\/\/ \t\tvar globals []_asan_global {...}\n\t\t\/\/ \t\tasanregisterglobals(&globals[0], len(globals))\n\t\t\/\/ }\n\t\tfor _, n := range typecheck.Target.Externs {\n\t\t\tif canInstrumentGlobal(n) {\n\t\t\t\tname := n.Sym().Name\n\t\t\t\tInstrumentGlobalsMap[name] = n\n\t\t\t\tInstrumentGlobalsSlice = append(InstrumentGlobalsSlice, n)\n\t\t\t}\n\t\t}\n\t\tni := len(InstrumentGlobalsMap)\n\t\tif ni != 0 {\n\t\t\t\/\/ Make an init._ function.\n\t\t\tbase.Pos = base.AutogeneratedPos\n\t\t\ttypecheck.DeclContext = ir.PEXTERN\n\t\t\tname := noder.Renameinit()\n\t\t\tfnInit := typecheck.DeclFunc(name, nil, nil, nil)\n\n\t\t\t\/\/ Get an array of intrumented global variables.\n\t\t\tglobals := instrumentGlobals(fnInit)\n\n\t\t\t\/\/ Call runtime.asanregisterglobals function to poison redzones.\n\t\t\t\/\/ runtime.asanregisterglobals(unsafe.Pointer(&globals[0]), ni)\n\t\t\tasanf := typecheck.NewName(ir.Pkgs.Runtime.Lookup(\"asanregisterglobals\"))\n\t\t\tir.MarkFunc(asanf)\n\t\t\tasanf.SetType(types.NewSignature(types.NoPkg, nil, nil, []*types.Field{\n\t\t\t\ttypes.NewField(base.Pos, nil, types.Types[types.TUNSAFEPTR]),\n\t\t\t\ttypes.NewField(base.Pos, nil, types.Types[types.TUINTPTR]),\n\t\t\t}, nil))\n\t\t\tasancall := ir.NewCallExpr(base.Pos, ir.OCALL, asanf, nil)\n\t\t\tasancall.Args.Append(typecheck.ConvNop(typecheck.NodAddr(\n\t\t\t\tir.NewIndexExpr(base.Pos, globals, ir.NewInt(0))), types.Types[types.TUNSAFEPTR]))\n\t\t\tasancall.Args.Append(typecheck.ConvNop(ir.NewInt(int64(ni)), types.Types[types.TUINTPTR]))\n\n\t\t\tfnInit.Body.Append(asancall)\n\t\t\ttypecheck.FinishFuncBody()\n\t\t\ttypecheck.Func(fnInit)\n\t\t\tir.CurFunc = fnInit\n\t\t\ttypecheck.Stmts(fnInit.Body)\n\t\t\tir.CurFunc = nil\n\n\t\t\ttypecheck.Target.Decls = append(typecheck.Target.Decls, fnInit)\n\t\t\ttypecheck.Target.Inits = append(typecheck.Target.Inits, fnInit)\n\t\t}\n\t}\n\n\t\/\/ Record user init functions.\n\tfor _, fn := range typecheck.Target.Inits {\n\t\tif fn.Sym().Name == \"init\" {\n\t\t\t\/\/ Synthetic init function for initialization of package-scope\n\t\t\t\/\/ variables. We can use staticinit to optimize away static\n\t\t\t\/\/ assignments.\n\t\t\ts := staticinit.Schedule{\n\t\t\t\tPlans: make(map[ir.Node]*staticinit.Plan),\n\t\t\t\tTemps: make(map[ir.Node]*ir.Name),\n\t\t\t}\n\t\t\tfor _, n := range fn.Body {\n\t\t\t\ts.StaticInit(n)\n\t\t\t}\n\t\t\tfn.Body = s.Out\n\t\t\tir.WithFunc(fn, func() {\n\t\t\t\ttypecheck.Stmts(fn.Body)\n\t\t\t})\n\n\t\t\tif len(fn.Body) == 0 {\n\t\t\t\tfn.Body = []ir.Node{ir.NewBlockStmt(src.NoXPos, nil)}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Skip init functions with empty bodies.\n\t\tif len(fn.Body) == 1 {\n\t\t\tif stmt := fn.Body[0]; stmt.Op() == ir.OBLOCK && len(stmt.(*ir.BlockStmt).List) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tfns = append(fns, fn.Nname.Linksym())\n\t}\n\n\tif len(deps) == 0 && len(fns) == 0 && types.LocalPkg.Name != \"main\" && types.LocalPkg.Name != \"runtime\" {\n\t\treturn nil \/\/ nothing to initialize\n\t}\n\n\t\/\/ Make an .inittask structure.\n\tsym := typecheck.Lookup(\".inittask\")\n\ttask := typecheck.NewName(sym)\n\ttask.SetType(types.Types[types.TUINT8]) \/\/ fake type\n\ttask.Class = ir.PEXTERN\n\tsym.Def = task\n\tlsym := task.Linksym()\n\tot := 0\n\tot = objw.Uintptr(lsym, ot, 0) \/\/ state: not initialized yet\n\tot = objw.Uintptr(lsym, ot, uint64(len(deps)))\n\tot = objw.Uintptr(lsym, ot, uint64(len(fns)))\n\tfor _, d := range deps {\n\t\tot = objw.SymPtr(lsym, ot, d, 0)\n\t}\n\tfor _, f := range fns {\n\t\tot = objw.SymPtr(lsym, ot, f, 0)\n\t}\n\t\/\/ An initTask has pointers, but none into the Go heap.\n\t\/\/ It's not quite read only, the state field must be modifiable.\n\tobjw.Global(lsym, int32(ot), obj.NOPTR)\n\treturn task\n}\n<|endoftext|>"}
{"text":"<commit_before>package pinnedpost\n\nimport (\n\t\"socialapi\/models\"\n\n\t\"github.com\/koding\/logging\"\n\t\"github.com\/streadway\/amqp\"\n)\n\ntype Controller struct{ log logging.Logger }\n\nfunc (t *Controller) DefaultErrHandler(delivery amqp.Delivery, err error) bool {\n\tif delivery.Redelivered {\n\t\tt.log.Error(\"Redelivered message gave error again, putting to maintenance queue\", err)\n\t\tdelivery.Ack(false)\n\t\treturn true\n\t}\n\n\tt.log.Error(\"an error occured putting message back to queue\", err)\n\tdelivery.Nack(false, true)\n\treturn false\n}\n\nfunc New(log logging.Logger) *Controller {\n\treturn &Controller{log: log}\n}\n\nfunc (c *Controller) ReplyCreated(messageReply *models.MessageReply) error {\n\t\/\/ parent message is needed for adding to pinned channel\n\tparentMessage := models.NewChannelMessage()\n\tif err := parentMessage.ById(messageReply.MessageId); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ only posts can be marked as pinned\n\tif parentMessage.TypeConstant != models.ChannelMessage_TYPE_POST {\n\t\treturn nil\n\t}\n\n\t\/\/ fetch reply itself for processsing\n\treply := models.NewChannelMessage()\n\tif err := reply.ById(messageReply.ReplyId); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ fetch the parent channel for gorup name\n\t\/\/ get it from cache\n\tchannel, err := models.ChannelById(reply.InitialChannelId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ get pinning channel for current user\n\tpinningChannel, err := models.EnsurePinnedActivityChannel(reply.AccountId, channel.GroupName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ add parent message into pinning channel\n\t_, err = pinningChannel.AddMessage(parentMessage.Id)\n\t\/\/ if message is already in the channel ignore the error, and mark process as successful\n\tif err == models.AlreadyInTheChannel {\n\t\treturn nil\n\t}\n\n\treturn err\n}\n<commit_msg>Social: add message created event into system for adding created messages to owner's pinned post<commit_after>package pinnedpost\n\nimport (\n\t\"socialapi\/models\"\n\n\t\"github.com\/koding\/logging\"\n\t\"github.com\/streadway\/amqp\"\n)\n\ntype Controller struct{ log logging.Logger }\n\nfunc (t *Controller) DefaultErrHandler(delivery amqp.Delivery, err error) bool {\n\tif delivery.Redelivered {\n\t\tt.log.Error(\"Redelivered message gave error again, putting to maintenance queue\", err)\n\t\tdelivery.Ack(false)\n\t\treturn true\n\t}\n\n\tt.log.Error(\"an error occured putting message back to queue\", err)\n\tdelivery.Nack(false, true)\n\treturn false\n}\n\nfunc New(log logging.Logger) *Controller {\n\treturn &Controller{log: log}\n}\n\n\/\/ MessageCreated handles the created messages\n\/\/ adds given message to the the author's pinned post channel\nfunc (c *Controller) MessageCreated(message *models.ChannelMessage) error {\n\t\/\/ only posts can be marked as pinned\n\tif message.TypeConstant != models.ChannelMessage_TYPE_POST {\n\t\treturn nil\n\t}\n\n\treturn c.addMessage(message.AccountId, message.Id, message.InitialChannelId)\n}\n\n\/\/ MessageReplyCreated handles the created replies\nfunc (c *Controller) MessageReplyCreated(messageReply *models.MessageReply) error {\n\tparent, err := messageReply.FetchParent()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ only posts can be marked as pinned\n\tif parent.TypeConstant != models.ChannelMessage_TYPE_POST {\n\t\treturn nil\n\t}\n\n\treply, err := messageReply.FetchReply()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.addMessage(reply.AccountId, parent.Id, parent.InitialChannelId)\n}\n\nfunc (c *Controller) addMessage(accountId, messageId, channelId int64) error {\n\t\/\/ fetch the parent channel for gorup name\n\t\/\/ get it from cache\n\tchannel, err := models.ChannelById(channelId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ get pinning channel for current user if it is created,, else create and get\n\tpinningChannel, err := models.EnsurePinnedActivityChannel(accountId, channel.GroupName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ add parent message into pinning channel\n\t_, err = pinningChannel.AddMessage(messageId)\n\t\/\/ if message is already in the channel ignore the error, and mark process as successful\n\tif err == models.AlreadyInTheChannel {\n\t\treturn nil\n\t}\n\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package realtime\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"socialapi\/models\"\n)\n\ntype channelUpdatedEventType string\n\nvar (\n\tchannelUpdatedEventMessageAddedToChannel     channelUpdatedEventType = \"MessageAddedToChannel\"\n\tchannelUpdatedEventMessageRemovedFromChannel channelUpdatedEventType = \"MessageRemovedFromChannel\"\n\tchannelUpdatedEventMessageUpdatedAtChannel   channelUpdatedEventType = \"MessageListUpdated\"\n\tchannelUpdatedEventReplyAdded                channelUpdatedEventType = \"ReplyAdded\"\n\tchannelUpdatedEventReplyRemoved              channelUpdatedEventType = \"ReplyRemoved\"\n\tchannelUpdatedEventChannelParticipantUpdated channelUpdatedEventType = \"ParticipantUpdated\"\n)\n\ntype channelUpdatedEvent struct {\n\tController           *Controller                `json:\"-\"`\n\tChannel              *models.Channel            `json:\"channel\"`\n\tParentChannelMessage *models.ChannelMessage     `json:\"channelMessage\"`\n\tReplyChannelMessage  *models.ChannelMessage     `json:\"-\"`\n\tEventType            channelUpdatedEventType    `json:\"event\"`\n\tChannelParticipant   *models.ChannelParticipant `json:\"-\"`\n\tUnreadCount          int                        `json:\"unreadCount\"`\n}\n\n\/\/ sendChannelUpdatedEvent sends channel updated events\nfunc (cue *channelUpdatedEvent) send() error {\n\tcue.Controller.log.Debug(\"sending channel update event %+v\", cue)\n\n\tif err := cue.validateChannelUpdatedEvents(); err != nil {\n\t\tcue.Controller.log.Error(err.Error())\n\t\t\/\/ this is not an error actually\n\t\treturn nil\n\t}\n\n\t\/\/ fetch all participants of related channel\n\t\/\/ if you ask why we are not sending those messaages to the channel's channel\n\t\/\/ instead of sending events as notifications?, because we are also sending\n\t\/\/ unread counts of the related channel's messages by the notifiee\n\tparticipants, err := cue.Channel.FetchParticipantIds()\n\tif err != nil {\n\t\tcue.Controller.log.Error(\"Error occured while fetching participants %s\", err.Error())\n\t\treturn err\n\t}\n\n\t\/\/ if\n\tif len(participants) == 0 {\n\t\tcue.Controller.log.Notice(\"This channel (%d) doesnt have any participant but we are trying to send an event to it, please investigate\", cue.Channel.Id)\n\t\treturn nil\n\t}\n\n\tfor _, accountId := range participants {\n\t\tif !cue.isEligibleForBroadcasting(accountId) {\n\t\t\tcue.Controller.log.Debug(\"not sending event to the creator of this operation %s\", cue.EventType)\n\t\t\tcontinue\n\t\t}\n\n\t\tcp := models.NewChannelParticipant()\n\t\tcp.ChannelId = cue.Channel.Id\n\t\tcp.AccountId = accountId\n\t\tif err := cp.FetchParticipant(); err != nil {\n\t\t\tcue.Controller.log.Error(\"Err: %s, skipping account %d\", err.Error(), accountId)\n\t\t\treturn nil\n\t\t}\n\t\tcue.ChannelParticipant = cp\n\n\t\terr := cue.sendForParticipant()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc (cue *channelUpdatedEvent) isEligibleForBroadcasting(accountId int64) bool {\n\t\/\/ if parent message is empty do send\n\t\/\/ realtime  updates to the client\n\tif cue.ParentChannelMessage == nil {\n\t\treturn true\n\t}\n\n\t\/\/ if we are gonna send this notification to topic channel\n\t\/\/ do not send to initiator\n\tif cue.Channel.TypeConstant == models.Channel_TYPE_TOPIC {\n\t\tif cue.ParentChannelMessage.AccountId == accountId {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t\/\/ if reply is not set do send this event\n\tif cue.ReplyChannelMessage == nil {\n\t\treturn true\n\t}\n\n\t\/\/ if parent message's crateor is account\n\t\/\/ dont send it\n\t\/\/ this has introduced some bugs to system, like if someone\n\t\/\/ comments to my post(i also pinned it)\n\t\/\/ i wasnt getting any notification\n\t\/\/ if cue.ParentChannelMessage.AccountId == accountId {\n\t\/\/ \treturn false\n\t\/\/ }\n\n\t\/\/ if reply message's crateor is account\n\t\/\/ dont send it\n\tif cue.ReplyChannelMessage.AccountId == accountId {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (cue *channelUpdatedEvent) validateChannelUpdatedEvents() error {\n\t\/\/ channel shouldnt be nil\n\tif cue.Channel == nil {\n\t\treturn fmt.Errorf(\"Channel is nil\")\n\t}\n\n\t\/\/ channel id should be set inorder to send event to the channel\n\tif cue.Channel.Id == 0 {\n\t\treturn fmt.Errorf(\"Channel id is not set\")\n\t}\n\n\t\/\/ filter group events\n\t\/\/ do not send any -updated- event to group channels\n\tif cue.Channel.TypeConstant == models.Channel_TYPE_GROUP {\n\t\treturn fmt.Errorf(\"Not sending group (%s) event\", cue.Channel.GroupName)\n\t}\n\n\t\/\/ do not send comment events to topic channels\n\t\/\/ other than topic channel, channels persist their messages as replies\n\tif cue.Channel.TypeConstant != models.Channel_TYPE_TOPIC {\n\t\treturn nil\n\t}\n\n\t\/\/ if we dont have a parent message it means this is a post addition\/creation\n\tif cue.ParentChannelMessage == nil {\n\t\treturn nil\n\t}\n\n\t\/\/ send only post operations the the client\n\tif cue.ParentChannelMessage.TypeConstant != models.ChannelMessage_TYPE_POST {\n\t\treturn fmt.Errorf(\"Not sending non-post (%s) event to topic channel\",\n\t\t\tcue.ParentChannelMessage.TypeConstant,\n\t\t)\n\t}\n\n\treturn nil\n}\n\nfunc (cue *channelUpdatedEvent) sendForParticipant() error {\n\tif cue.ChannelParticipant == nil {\n\t\treturn errors.New(\"Channel Participant is nil\")\n\t}\n\n\tcount, err := cue.calculateUnreadItemCount()\n\tif err != nil {\n\t\tcue.Controller.log.Notice(\"Error happened, setting unread count to 0 %s\", err.Error())\n\t\tcount = 0\n\t}\n\n\tcue.UnreadCount = count\n\n\terr = cue.Controller.sendNotification(cue.ChannelParticipant.AccountId, ChannelUpdateEventName, cue)\n\tif err != nil {\n\t\tcue.Controller.log.Error(err.Error())\n\t}\n\n\treturn nil\n}\n\nfunc (cue *channelUpdatedEvent) calculateUnreadItemCount() (int, error) {\n\tif cue.ParentChannelMessage == nil {\n\t\treturn models.NewChannelMessageList().UnreadCount(cue.ChannelParticipant)\n\t}\n\n\t\/\/ for topic channel unread count will be calculated from unread post count\n\tif cue.Channel.TypeConstant == models.Channel_TYPE_TOPIC {\n\t\treturn models.NewChannelMessageList().UnreadCount(cue.ChannelParticipant)\n\t}\n\n\t\/\/ for private messages calculate the unread reply count\n\tif cue.Channel.TypeConstant == models.Channel_TYPE_PRIVATE_MESSAGE {\n\t\tcount, err := models.NewMessageReply().UnreadCount(cue.ParentChannelMessage.Id, cue.ChannelParticipant.LastSeenAt)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\t\/\/ if unread count is 0\n\t\t\/\/ set it to 1 for now\n\t\t\/\/ because we want to show a notification with a sign\n\t\tif count == 0 {\n\t\t\tcount = 1\n\t\t}\n\n\t\treturn count, nil\n\t}\n\n\tcue.Controller.log.Critical(\"Calculating unread count shouldnt fall here\")\n\treturn 0, nil\n}\n<commit_msg>Social: for pinned posts calculate unread count from message's added at into that channel<commit_after>package realtime\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"socialapi\/models\"\n)\n\ntype channelUpdatedEventType string\n\nvar (\n\tchannelUpdatedEventMessageAddedToChannel     channelUpdatedEventType = \"MessageAddedToChannel\"\n\tchannelUpdatedEventMessageRemovedFromChannel channelUpdatedEventType = \"MessageRemovedFromChannel\"\n\tchannelUpdatedEventMessageUpdatedAtChannel   channelUpdatedEventType = \"MessageListUpdated\"\n\tchannelUpdatedEventReplyAdded                channelUpdatedEventType = \"ReplyAdded\"\n\tchannelUpdatedEventReplyRemoved              channelUpdatedEventType = \"ReplyRemoved\"\n\tchannelUpdatedEventChannelParticipantUpdated channelUpdatedEventType = \"ParticipantUpdated\"\n)\n\ntype channelUpdatedEvent struct {\n\tController           *Controller                `json:\"-\"`\n\tChannel              *models.Channel            `json:\"channel\"`\n\tParentChannelMessage *models.ChannelMessage     `json:\"channelMessage\"`\n\tReplyChannelMessage  *models.ChannelMessage     `json:\"-\"`\n\tEventType            channelUpdatedEventType    `json:\"event\"`\n\tChannelParticipant   *models.ChannelParticipant `json:\"-\"`\n\tUnreadCount          int                        `json:\"unreadCount\"`\n}\n\n\/\/ sendChannelUpdatedEvent sends channel updated events\nfunc (cue *channelUpdatedEvent) send() error {\n\tcue.Controller.log.Debug(\"sending channel update event %+v\", cue)\n\n\tif err := cue.validateChannelUpdatedEvents(); err != nil {\n\t\tcue.Controller.log.Error(err.Error())\n\t\t\/\/ this is not an error actually\n\t\treturn nil\n\t}\n\n\t\/\/ fetch all participants of related channel\n\t\/\/ if you ask why we are not sending those messaages to the channel's channel\n\t\/\/ instead of sending events as notifications?, because we are also sending\n\t\/\/ unread counts of the related channel's messages by the notifiee\n\tparticipants, err := cue.Channel.FetchParticipantIds()\n\tif err != nil {\n\t\tcue.Controller.log.Error(\"Error occured while fetching participants %s\", err.Error())\n\t\treturn err\n\t}\n\n\t\/\/ if\n\tif len(participants) == 0 {\n\t\tcue.Controller.log.Notice(\"This channel (%d) doesnt have any participant but we are trying to send an event to it, please investigate\", cue.Channel.Id)\n\t\treturn nil\n\t}\n\n\tfor _, accountId := range participants {\n\t\tif !cue.isEligibleForBroadcasting(accountId) {\n\t\t\tcue.Controller.log.Debug(\"not sending event to the creator of this operation %s\", cue.EventType)\n\t\t\tcontinue\n\t\t}\n\n\t\tcp := models.NewChannelParticipant()\n\t\tcp.ChannelId = cue.Channel.Id\n\t\tcp.AccountId = accountId\n\t\tif err := cp.FetchParticipant(); err != nil {\n\t\t\tcue.Controller.log.Error(\"Err: %s, skipping account %d\", err.Error(), accountId)\n\t\t\treturn nil\n\t\t}\n\t\tcue.ChannelParticipant = cp\n\n\t\terr := cue.sendForParticipant()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nfunc (cue *channelUpdatedEvent) isEligibleForBroadcasting(accountId int64) bool {\n\t\/\/ if parent message is empty do send\n\t\/\/ realtime  updates to the client\n\tif cue.ParentChannelMessage == nil {\n\t\treturn true\n\t}\n\n\t\/\/ if we are gonna send this notification to topic channel\n\t\/\/ do not send to initiator\n\tif cue.Channel.TypeConstant == models.Channel_TYPE_TOPIC {\n\t\tif cue.ParentChannelMessage.AccountId == accountId {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t\/\/ if reply is not set do send this event\n\tif cue.ReplyChannelMessage == nil {\n\t\treturn true\n\t}\n\n\t\/\/ if parent message's crateor is account\n\t\/\/ dont send it\n\t\/\/ this has introduced some bugs to system, like if someone\n\t\/\/ comments to my post(i also pinned it)\n\t\/\/ i wasnt getting any notification\n\t\/\/ if cue.ParentChannelMessage.AccountId == accountId {\n\t\/\/ \treturn false\n\t\/\/ }\n\n\t\/\/ if reply message's crateor is account\n\t\/\/ dont send it\n\tif cue.ReplyChannelMessage.AccountId == accountId {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (cue *channelUpdatedEvent) validateChannelUpdatedEvents() error {\n\t\/\/ channel shouldnt be nil\n\tif cue.Channel == nil {\n\t\treturn fmt.Errorf(\"Channel is nil\")\n\t}\n\n\t\/\/ channel id should be set inorder to send event to the channel\n\tif cue.Channel.Id == 0 {\n\t\treturn fmt.Errorf(\"Channel id is not set\")\n\t}\n\n\t\/\/ filter group events\n\t\/\/ do not send any -updated- event to group channels\n\tif cue.Channel.TypeConstant == models.Channel_TYPE_GROUP {\n\t\treturn fmt.Errorf(\"Not sending group (%s) event\", cue.Channel.GroupName)\n\t}\n\n\t\/\/ do not send comment events to topic channels\n\t\/\/ other than topic channel, channels persist their messages as replies\n\tif cue.Channel.TypeConstant != models.Channel_TYPE_TOPIC {\n\t\treturn nil\n\t}\n\n\t\/\/ if we dont have a parent message it means this is a post addition\/creation\n\tif cue.ParentChannelMessage == nil {\n\t\treturn nil\n\t}\n\n\t\/\/ send only post operations the the client\n\tif cue.ParentChannelMessage.TypeConstant != models.ChannelMessage_TYPE_POST {\n\t\treturn fmt.Errorf(\"Not sending non-post (%s) event to topic channel\",\n\t\t\tcue.ParentChannelMessage.TypeConstant,\n\t\t)\n\t}\n\n\treturn nil\n}\n\nfunc (cue *channelUpdatedEvent) sendForParticipant() error {\n\tif cue.ChannelParticipant == nil {\n\t\treturn errors.New(\"Channel Participant is nil\")\n\t}\n\n\tcount, err := cue.calculateUnreadItemCount()\n\tif err != nil {\n\t\tcue.Controller.log.Notice(\"Error happened, setting unread count to 0 %s\", err.Error())\n\t\tcount = 0\n\t}\n\n\tcue.UnreadCount = count\n\n\terr = cue.Controller.sendNotification(cue.ChannelParticipant.AccountId, ChannelUpdateEventName, cue)\n\tif err != nil {\n\t\tcue.Controller.log.Error(err.Error())\n\t}\n\n\treturn nil\n}\n\nfunc (cue *channelUpdatedEvent) calculateUnreadItemCount() (int, error) {\n\tif cue.ParentChannelMessage == nil {\n\t\treturn models.NewChannelMessageList().UnreadCount(cue.ChannelParticipant)\n\t}\n\n\t\/\/ for topic channel unread count will be calculated from unread post count\n\tif cue.Channel.TypeConstant == models.Channel_TYPE_TOPIC {\n\t\treturn models.NewChannelMessageList().UnreadCount(cue.ChannelParticipant)\n\t}\n\n\t\/\/ from this poin we need parent message\n\n\t\/\/ for pinned posts calculate unread count from message's added at into that channel\n\tif cue.Channel.TypeConstant == models.Channel_TYPE_PINNED_ACTIVITY {\n\t\tcml, err := cue.Channel.FetchMessageList(cue.ParentChannelMessage.Id)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\t\/\/ for pinned posts we are calculating unread count from reviseddAt of the\n\t\t\/\/ regarding channel message list, since only participant for the channel\n\t\t\/\/ is the owner and we cant use channel_participant for unread counts\n\t\t\/\/ on the other hand messages should have their own unread count\n\t\t\/\/ we are specialcasing the pinned posts here\n\t\treturn models.NewMessageReply().UnreadCount(cml.MessageId, cml.RevisedAt)\n\t}\n\n\t\/\/ for private messages calculate the unread reply count\n\tif cue.Channel.TypeConstant == models.Channel_TYPE_PRIVATE_MESSAGE {\n\t\tcount, err := models.NewMessageReply().UnreadCount(cue.ParentChannelMessage.Id, cue.ChannelParticipant.LastSeenAt)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\t\/\/ if unread count is 0\n\t\t\/\/ set it to 1 for now\n\t\t\/\/ because we want to show a notification with a sign\n\t\tif count == 0 {\n\t\t\tcount = 1\n\t\t}\n\n\t\treturn count, nil\n\t}\n\n\tcue.Controller.log.Critical(\"Calculating unread count shouldnt fall here\")\n\treturn 0, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package jpush\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"github.com\/wuyongzhi\/gopush\/utils\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t_ \"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\t\"crypto\/md5\"\n\t\"encoding\/hex\"\n)\n\nconst JPushServerUrl string = \"http:\/\/api.jpush.cn:8800\/v2\/push\"\nconst JPushServerUrlSsl string = \"https:\/\/api.jpush.cn:443\/v2\/push\"\n\ntype Request struct {\n\turl.Values\n}\n\ntype NotifyMessage struct {\n\tBuilderId int\t\t`json:\"n_builder_id\"`\n\tTitle string\t\t`json:\"n_title\"`\n\tContent string\t\t`json:\"n_content\"`\n\tExtras string\t\t`json:\"n_extras\"`\n}\n\ntype CustomMessage struct {\n\tMessage string\t\t`json:\"message\"`\n\tContentType int    \t`json:\"content_type\"`\n\tTitle string\t\t`json:\"title\"`\n\tExtras string\t\t`json:\"extras\"`\n}\n\ntype JPushMsgId interface {}\n\nvar InvalidMsgId JPushMsgId = nil\n\ntype Response struct {\n\tErrCode int    `json:\"errcode\"`\n\tErrMsg  string `json:\"errmsg\"`\n\tMsgId   JPushMsgId `json:\"msg_id\"`\n}\n\ntype Response2 struct {\n\tErrCode int    `json:\"errcode\"`\n\tErrMsg  string `json:\"errmsg\"`\n\n}\n\n\nfunc NewRequest() *Request {\n\tm := Request{}\n\tm.Values = make(map[string][]string, 8)\n\treturn &m\n}\n\nfunc (r *Response) IsOk() bool {\n\treturn r.ErrCode == 0\n}\n\nfunc (r *Response) IsFailed() bool {\n\treturn r.ErrCode != 0\n}\n\nfunc (m *Request) Set(key, value string){\n\tm.Values.Set(key, value)\n}\n\nfunc (m *Request) SetInt(key string, value int){\n\tm.Set(key, strconv.Itoa(value))\n}\n\nfunc (m *Request) SendNo(sendno int){\n\tm.SetInt(\"sendno\", sendno)\n}\n\nfunc (m *Request) AppKey(app_key string) {\n\tm.Set(\"app_key\", app_key)\n}\n\nconst (\n\tReceiverTypeTag            int = 2\n\tReceiverTypeAlias              = 3\n\tReceiverTypeBoardcast          = 4\n\tReceiverTypeRegistrationID     = 5\n)\n\nconst (\n\tMsgTypeNotify = 1\n\tMsgTypeCustom = 2\n)\n\n\/\/\t可以是以下值:\n\/\/\t\tReceiverTypeAlias\n\/\/ \t\tReceiverTypeTag\n\/\/ \t\tReceiverTypeBoardcast\n\/\/ \t\tReceiverTypeRegistrationID\nfunc (m *Request) ReceiverType(receiver_type int)  {\n\tm.SetInt(\"receiver_type\", receiver_type)\n}\n\nfunc (m *Request) ReceiverValue(receiver_values ...string) {\n\tm.Set(\"receiver_value\", strings.Join(receiver_values, \",\"))\n}\n\n\/\/允许传递认证码自行认证，也可以在调用Send 时，传递有效的 master_secret 参数来生成认证码\nfunc (m *Request) VerificationCode(verification_code string)  {\n\tm.Set(\"verification_code\", verification_code)\n}\n\n\/\/可以是以下值：\n\/\/\n\/\/ \tMsgTypeNotify\n\/\/ \tMsgTypeCustom\nfunc (m *Request) MsgType(msg_type int)  {\n\tm.SetInt(\"msg_type\", msg_type)\n}\n\nfunc (m *Request) MessageNotify(n_builder_id int, n_title, n_content, n_extras string) {\n\tmsg := NotifyMessage{n_builder_id, n_title, n_content, n_extras}\n\tbytes, _ := json.Marshal(msg)\n\tm.Set(\"msg_content\", string(bytes))\n\tm.SetInt(\"msg_type\", MsgTypeNotify)\n}\n\n\nfunc (m *Request) MessageCustom(message, title, extras string, contentType int) {\n\tmsg := CustomMessage{\n\t\tMessage: message,\n\t\tTitle: title,\n\t\tExtras: extras,\n\t\tContentType: contentType,\n\t}\n\tbytes, _ := json.Marshal(msg)\n\tm.Set(\"msg_content\", string(bytes))\n\tm.SetInt(\"msg_type\", MsgTypeCustom)\n}\n\n\n\nfunc (m *Request) SendDescription(send_description string)  {\n\tm.Set(\"send_description\", send_description)\n}\n\n\/\/按可变参数，挨个传递“平台”，方法会用逗号将它们拼起来\nfunc (m *Request) Platform(platforms ...string)  {\n\tm.Set(\"platform\", strings.Join(platforms, \",\"))\n}\n\n\/\/ 仅IOS  适用 0 开发环境；1 生产环境\nfunc (m *Request) APNSProduction(apns_production int)  {\n\tm.SetInt(\"apns_production\", apns_production)\n}\n\nfunc (m *Request) TimeToLive(time_to_live int)  {\n\tm.SetInt(\"time_to_live\", time_to_live)\n}\n\nfunc (m *Request) OverrideMsgId(override_msg_id string)  {\n\tm.Set(\"override_msg_id\", override_msg_id)\n}\n\nfunc (m *Request) Sign(master_secret string)  {\n\tsrc := m.Values.Get(\"sendno\") + m.Values.Get(\"receiver_type\") + m.Values.Get(\"receiver_value\") + master_secret\n\/\/\tfmt.Println(src)\n\tsum := md5.Sum([]byte(src))\n\tverification_code := hex.EncodeToString(sum[:])\n\tm.Values.Set(\"verification_code\", verification_code)\n\n}\n\nfunc (m *Request) send(url string) (*Response, error) {\n\n\n\tresp, err := defaultHttpClient.PostForm(url, m.Values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, errors.New(strconv.Itoa(resp.StatusCode) + resp.Status)\n\t}\n\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar jpushResponse Response\n\n\t\/\/\tresponseContent := string(bytes)\n\terr = json.Unmarshal(bytes, &jpushResponse)\n\tif err != nil {\n\t\treturn nil, errors.New(err.Error() + \" response: \\n\" + string(bytes))\n\t}\n\n\t\/\/ 如果失败，转换为 go 的 error\n\tif jpushResponse.IsFailed() {\n\t\treturn &jpushResponse, errors.New(strconv.Itoa(jpushResponse.ErrCode) + \", \" + jpushResponse.ErrMsg)\n\t}\n\n\treturn &jpushResponse, nil\n\n}\n\n\n\/\/ 使用 http 协议\nfunc (m *Request) Send() (*Response, error) {\n\treturn m.send(JPushServerUrl)\n}\n\n\/\/ 使用 https 协议\nfunc (m *Request) SendSecure() (*Response, error) {\n\treturn m.send(JPushServerUrlSsl)\n}\n\nvar defaultHttpClient *utils.HttpClient\n\nfunc init() {\n\ttimeout, _ := time.ParseDuration(\"10s\")\n\tdefaultHttpClient = utils.NewHttpClient(20, timeout, timeout, false)\n\t\/\/defaultHttpClient.\n}\n<commit_msg>默认60秒超时<commit_after>package jpush\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"github.com\/wuyongzhi\/gopush\/utils\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t_ \"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\t\"crypto\/md5\"\n\t\"encoding\/hex\"\n)\n\nconst JPushServerUrl string = \"http:\/\/api.jpush.cn:8800\/v2\/push\"\nconst JPushServerUrlSsl string = \"https:\/\/api.jpush.cn:443\/v2\/push\"\n\ntype Request struct {\n\turl.Values\n}\n\ntype NotifyMessage struct {\n\tBuilderId int\t\t`json:\"n_builder_id\"`\n\tTitle string\t\t`json:\"n_title\"`\n\tContent string\t\t`json:\"n_content\"`\n\tExtras string\t\t`json:\"n_extras\"`\n}\n\ntype CustomMessage struct {\n\tMessage string\t\t`json:\"message\"`\n\tContentType int    \t`json:\"content_type\"`\n\tTitle string\t\t`json:\"title\"`\n\tExtras string\t\t`json:\"extras\"`\n}\n\ntype JPushMsgId interface {}\n\nvar InvalidMsgId JPushMsgId = nil\n\ntype Response struct {\n\tErrCode int    `json:\"errcode\"`\n\tErrMsg  string `json:\"errmsg\"`\n\tMsgId   JPushMsgId `json:\"msg_id\"`\n}\n\ntype Response2 struct {\n\tErrCode int    `json:\"errcode\"`\n\tErrMsg  string `json:\"errmsg\"`\n\n}\n\n\nfunc NewRequest() *Request {\n\tm := Request{}\n\tm.Values = make(map[string][]string, 8)\n\treturn &m\n}\n\nfunc (r *Response) IsOk() bool {\n\treturn r.ErrCode == 0\n}\n\nfunc (r *Response) IsFailed() bool {\n\treturn r.ErrCode != 0\n}\n\nfunc (m *Request) Set(key, value string){\n\tm.Values.Set(key, value)\n}\n\nfunc (m *Request) SetInt(key string, value int){\n\tm.Set(key, strconv.Itoa(value))\n}\n\nfunc (m *Request) SendNo(sendno int){\n\tm.SetInt(\"sendno\", sendno)\n}\n\nfunc (m *Request) AppKey(app_key string) {\n\tm.Set(\"app_key\", app_key)\n}\n\nconst (\n\tReceiverTypeTag            int = 2\n\tReceiverTypeAlias              = 3\n\tReceiverTypeBoardcast          = 4\n\tReceiverTypeRegistrationID     = 5\n)\n\nconst (\n\tMsgTypeNotify = 1\n\tMsgTypeCustom = 2\n)\n\n\/\/\t可以是以下值:\n\/\/\t\tReceiverTypeAlias\n\/\/ \t\tReceiverTypeTag\n\/\/ \t\tReceiverTypeBoardcast\n\/\/ \t\tReceiverTypeRegistrationID\nfunc (m *Request) ReceiverType(receiver_type int)  {\n\tm.SetInt(\"receiver_type\", receiver_type)\n}\n\nfunc (m *Request) ReceiverValue(receiver_values ...string) {\n\tm.Set(\"receiver_value\", strings.Join(receiver_values, \",\"))\n}\n\n\/\/允许传递认证码自行认证，也可以在调用Send 时，传递有效的 master_secret 参数来生成认证码\nfunc (m *Request) VerificationCode(verification_code string)  {\n\tm.Set(\"verification_code\", verification_code)\n}\n\n\/\/可以是以下值：\n\/\/\n\/\/ \tMsgTypeNotify\n\/\/ \tMsgTypeCustom\nfunc (m *Request) MsgType(msg_type int)  {\n\tm.SetInt(\"msg_type\", msg_type)\n}\n\nfunc (m *Request) MessageNotify(n_builder_id int, n_title, n_content, n_extras string) {\n\tmsg := NotifyMessage{n_builder_id, n_title, n_content, n_extras}\n\tbytes, _ := json.Marshal(msg)\n\tm.Set(\"msg_content\", string(bytes))\n\tm.SetInt(\"msg_type\", MsgTypeNotify)\n}\n\n\nfunc (m *Request) MessageCustom(message, title, extras string, contentType int) {\n\tmsg := CustomMessage{\n\t\tMessage: message,\n\t\tTitle: title,\n\t\tExtras: extras,\n\t\tContentType: contentType,\n\t}\n\tbytes, _ := json.Marshal(msg)\n\tm.Set(\"msg_content\", string(bytes))\n\tm.SetInt(\"msg_type\", MsgTypeCustom)\n}\n\n\n\nfunc (m *Request) SendDescription(send_description string)  {\n\tm.Set(\"send_description\", send_description)\n}\n\n\/\/按可变参数，挨个传递“平台”，方法会用逗号将它们拼起来\nfunc (m *Request) Platform(platforms ...string)  {\n\tm.Set(\"platform\", strings.Join(platforms, \",\"))\n}\n\n\/\/ 仅IOS  适用 0 开发环境；1 生产环境\nfunc (m *Request) APNSProduction(apns_production int)  {\n\tm.SetInt(\"apns_production\", apns_production)\n}\n\nfunc (m *Request) TimeToLive(time_to_live int)  {\n\tm.SetInt(\"time_to_live\", time_to_live)\n}\n\nfunc (m *Request) OverrideMsgId(override_msg_id string)  {\n\tm.Set(\"override_msg_id\", override_msg_id)\n}\n\nfunc (m *Request) Sign(master_secret string)  {\n\tsrc := m.Values.Get(\"sendno\") + m.Values.Get(\"receiver_type\") + m.Values.Get(\"receiver_value\") + master_secret\n\/\/\tfmt.Println(src)\n\tsum := md5.Sum([]byte(src))\n\tverification_code := hex.EncodeToString(sum[:])\n\tm.Values.Set(\"verification_code\", verification_code)\n\n}\n\nfunc (m *Request) send(url string) (*Response, error) {\n\n\n\tresp, err := defaultHttpClient.PostForm(url, m.Values)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, errors.New(strconv.Itoa(resp.StatusCode) + resp.Status)\n\t}\n\n\tbytes, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar jpushResponse Response\n\n\t\/\/\tresponseContent := string(bytes)\n\terr = json.Unmarshal(bytes, &jpushResponse)\n\tif err != nil {\n\t\treturn nil, errors.New(err.Error() + \" response: \\n\" + string(bytes))\n\t}\n\n\t\/\/ 如果失败，转换为 go 的 error\n\tif jpushResponse.IsFailed() {\n\t\treturn &jpushResponse, errors.New(strconv.Itoa(jpushResponse.ErrCode) + \", \" + jpushResponse.ErrMsg)\n\t}\n\n\treturn &jpushResponse, nil\n\n}\n\n\n\/\/ 使用 http 协议\nfunc (m *Request) Send() (*Response, error) {\n\treturn m.send(JPushServerUrl)\n}\n\n\/\/ 使用 https 协议\nfunc (m *Request) SendSecure() (*Response, error) {\n\treturn m.send(JPushServerUrlSsl)\n}\n\nvar defaultHttpClient *utils.HttpClient\n\nfunc init() {\n\ttimeout, _ := time.ParseDuration(\"60s\")\n\tdefaultHttpClient = utils.NewHttpClient(20, timeout, timeout, false)\n\t\/\/defaultHttpClient.\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"go\/parser\"\n\t\"go\/types\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"golang.org\/x\/tools\/go\/loader\"\n)\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Fprintf(os.Stderr, \"%s .\/pkg\/foo > tests\/clone\/generated\/foo_test.go\\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\tinfos := extractInfos(os.Args[1:])\n\tgenerateTests(infos)\n}\n\nfunc extractInfos(pkgs []string) []info {\n\tinfos := make([]info, 0)\n\tdocIface := getDocIface()\n\n\tfor _, pkgPath := range pkgs {\n\t\tpkg, err := pkgInfoFromPath(pkgPath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tin := info{\n\t\t\tPkgName: pkg.Name(),\n\t\t\tPkgPath: pkg.Path(),\n\t\t\tStructs: make(map[string][]mutableField),\n\t\t}\n\t\tscope := pkg.Scope()\n\t\tfor _, name := range scope.Names() {\n\t\t\tobj := scope.Lookup(name)\n\t\t\ts, ok := obj.Type().Underlying().(*types.Struct)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tptr := types.NewPointer(obj.Type())\n\t\t\t\/\/ FIXME implements returns false for intents.Intent but it should\n\t\t\t\/\/ return true, find why!\n\t\t\t\/\/ implements := types.Implements(ptr.Underlying(), docIface)\n\t\t\tf, g := types.MissingMethod(ptr.Underlying(), docIface, true)\n\t\t\tif f != nil && !g {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfields := make([]mutableField, 0)\n\t\t\tfor i := 0; i < s.NumFields(); i++ {\n\t\t\t\tfield := s.Field(i)\n\t\t\t\t\/\/ fmt.Printf(\" - %d. %s - %s\\n\", i, field.Name(), field.Type())\n\t\t\t\tswitch t := field.Type().(type) {\n\t\t\t\tcase (*types.Slice):\n\t\t\t\t\tfields = append(fields, &sliceField{\n\t\t\t\t\t\tName:  field.Name(),\n\t\t\t\t\t\tValue: generatorForType(t.Elem()),\n\t\t\t\t\t})\n\t\t\t\tcase (*types.Map):\n\t\t\t\t\tfields = append(fields, &mapField{\n\t\t\t\t\t\tName:  field.Name(),\n\t\t\t\t\t\tKey:   generatorForType(t.Key()),\n\t\t\t\t\t\tValue: generatorForType(t.Elem()),\n\t\t\t\t\t})\n\t\t\t\tcase (*types.Named):\n\t\t\t\t\tnamed := fmt.Sprintf(\"%s.%s\", t.Obj().Pkg().Name(), t.Obj().Name())\n\t\t\t\t\tswitch named {\n\t\t\t\t\tcase \"time.Time\", \"time.Duration\":\n\t\t\t\t\t\t\/\/ These structs are known to be safe\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tpanic(fmt.Errorf(\"Unknown named type: %s\", named))\n\t\t\t\t\t}\n\t\t\t\tcase (*types.Interface):\n\t\t\t\t\tfmt.Fprintf(os.Stderr, \"Warning: cannot check interfaces: %s.%s -> %s\\n\",\n\t\t\t\t\t\tpkg.Name(), name, field)\n\t\t\t\tcase (*types.Basic):\n\t\t\t\t\t\/\/ Basic types are immutables\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(fmt.Errorf(\"Unknown type: %#v\", field.Type()))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(fields) > 0 {\n\t\t\t\tin.Structs[name] = fields\n\t\t\t}\n\t\t}\n\t\tif len(in.Structs) > 0 {\n\t\t\tinfos = append(infos, in)\n\t\t}\n\t}\n\treturn infos\n}\n\nfunc generateTests(infos []info) {\n\tfmt.Printf(`\/\/ Generated tests for Clone(). Do not manually edit!\npackage clone\n\nimport (\n\t\"testing\"\n`)\n\tfor _, info := range infos {\n\t\tfmt.Printf(\"\\t\\\"%s\\\"\\n\", info.PkgPath)\n\t}\n\tfmt.Printf(\")\\n\\n\")\n\n\tfor _, info := range infos {\n\t\tfmt.Printf(\"func Test%s(t *testing.T) {\\n\", strings.Title(info.PkgName))\n\t\tfor name, fields := range info.Structs {\n\t\t\tv := strings.ToLower(name)\n\t\t\tfmt.Printf(\"\\t%sA := &%s.%s{}\\n\", v, info.PkgName, name)\n\t\t\tfor _, field := range fields {\n\t\t\t\tfield.Initialize(v)\n\t\t\t}\n\t\t\tptr := \"*\"\n\t\t\tif name == \"JSONDoc\" {\n\t\t\t\tptr = \"\"\n\t\t\t}\n\t\t\tfmt.Printf(\"\\t%sB := %sA.Clone().(%s%s.%s)\\n\", v, v, ptr, info.PkgName, name)\n\t\t\tfor _, field := range fields {\n\t\t\t\tfield.Reassign(v)\n\t\t\t\tfield.Compare(v)\n\t\t\t\tfmt.Printf(\"\\t\\tt.Fatalf(\\\"Error for clone %s.%s -> %s\\\")\\n\\t}\\n\", info.PkgName, name, field)\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"}\\n\\n\")\n\t}\n}\n\ntype info struct {\n\tPkgName string\n\tPkgPath string\n\tStructs map[string][]mutableField\n}\n\ntype mutableField interface {\n\tString() string\n\tInitialize(v string)\n\tReassign(v string)\n\tCompare(v string)\n}\n\ntype sliceField struct {\n\tName  string\n\tValue generator\n}\n\nfunc (f *sliceField) String() string { return f.Name }\n\nfunc (f *sliceField) Initialize(v string) {\n\tif f.Value.Warning != \"\" {\n\t\tfmt.Printf(\"\\t\/\/ Warning: %s\", f.Value.Warning)\n\t}\n\tfmt.Printf(\"\\t%sA.%s = []%s{%s}\\n\", v, f.Name, f.Value.Type, f.Value.Initial)\n}\nfunc (f *sliceField) Reassign(v string) {\n\tfmt.Printf(\"\\t%sA.%s[0] = %s\\n\", v, f.Name, f.Value.Altered)\n}\nfunc (f *sliceField) Compare(v string) {\n\tfmt.Printf(\"\\tif %sB.%s[0] != %s {\\n\", v, f.Name, f.Value.Initial)\n}\n\ntype mapField struct {\n\tName  string\n\tKey   generator\n\tValue generator\n}\n\nfunc (f *mapField) String() string { return f.Name }\n\nfunc (f *mapField) Initialize(v string) {\n\tif f.Value.Warning != \"\" {\n\t\tfmt.Printf(\"\\t\/\/ Warning: %s\\n\", f.Value.Warning)\n\t}\n\tfmt.Printf(\"\\t%sA.%s = map[%s]%s{%s: %s}\\n\", v, f.Name, f.Key.Type, f.Value.Type, f.Key.Key, f.Value.Initial)\n}\nfunc (f *mapField) Reassign(v string) {\n\tfmt.Printf(\"\\t%sA.%s[%s] = %s\\n\", v, f.Name, f.Key.Key, f.Value.Altered)\n}\nfunc (f *mapField) Compare(v string) {\n\tfmt.Printf(\"\\tif %sB.%s[%s] != %s {\\n\", v, f.Name, f.Key.Key, f.Value.Initial)\n}\n\nfunc generatorForType(typ types.Type) generator {\n\tswitch t := typ.(type) {\n\tcase (*types.Basic):\n\t\tswitch t.Name() {\n\t\tcase \"string\":\n\t\t\treturn stringGenerator\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"Unknown basic type: %s\", t.Name()))\n\t\t}\n\tcase (*types.Interface):\n\t\tif t.Empty() {\n\t\t\treturn emptyInterfaceGenerator\n\t\t}\n\t}\n\t\/\/return stringGenerator\n\tpanic(fmt.Errorf(\"Unknown generator type: %#v\", typ))\n}\n\ntype generator struct {\n\tType    string\n\tKey     string\n\tInitial string\n\tAltered string\n\tWarning string\n}\n\nvar stringGenerator = generator{\n\tType:    \"string\",\n\tKey:     `\"foo\"`,\n\tInitial: `\"bar\"`,\n\tAltered: `\"baz\"`,\n}\n\nvar emptyInterfaceGenerator = generator{\n\tType:    \"interface{}\",\n\tKey:     \"0\",\n\tInitial: \"1\",\n\tAltered: \"2\",\n\tWarning: \"interface{} can contain nested data!\",\n}\n\n\/\/ getDocIface returns the couchdb.Doc interface\nfunc getDocIface() *types.Interface {\n\tcouchPkg := \"github.com\/cozy\/cozy-stack\/pkg\/couchdb\"\n\tconf := loader.Config{\n\t\tParserMode: parser.SpuriousErrors,\n\t}\n\tconf.Import(couchPkg)\n\tlprog, err := conf.Load()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tscope := lprog.Package(couchPkg).Pkg.Scope()\n\treturn scope.Lookup(\"Doc\").Type().Underlying().(*types.Interface)\n}\n\n\/\/ pkgInfoFromPath returns information about the package\n\/\/ Taken from https:\/\/github.com\/matryer\/moq\nfunc pkgInfoFromPath(src string) (*types.Package, error) {\n\tabs, err := filepath.Abs(src)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpkgFull := stripGopath(abs)\n\n\tconf := loader.Config{\n\t\tParserMode: parser.SpuriousErrors,\n\t}\n\tconf.Import(pkgFull)\n\tlprog, err := conf.Load()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpkgInfo := lprog.Package(pkgFull)\n\tif pkgInfo == nil {\n\t\treturn nil, errors.New(\"package was nil\")\n\t}\n\n\treturn pkgInfo.Pkg, nil\n}\n\n\/\/ stripGopath takes the directory to a package and remove the gopath to get the\n\/\/ canonical package name.\n\/\/ Taken from https:\/\/github.com\/ernesto-jimenez\/gogen\nfunc stripGopath(p string) string {\n\tfor _, gopath := range gopaths() {\n\t\tp = strings.TrimPrefix(p, path.Join(gopath, \"src\")+\"\/\")\n\t}\n\treturn p\n}\n\nfunc gopaths() []string {\n\treturn strings.Split(os.Getenv(\"GOPATH\"), string(filepath.ListSeparator))\n}\n<commit_msg>Add clone test for pointer to struct<commit_after>package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"go\/parser\"\n\t\"go\/types\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"golang.org\/x\/tools\/go\/loader\"\n)\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tfmt.Fprintf(os.Stderr, \"%s .\/pkg\/foo > tests\/clone\/generated\/foo_test.go\\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\tinfos := extractInfos(os.Args[1:])\n\tgenerateTests(infos)\n}\n\nfunc extractInfos(pkgs []string) []info {\n\tinfos := make([]info, 0)\n\tdocIface := getDocIface()\n\n\tfor _, pkgPath := range pkgs {\n\t\tpkg, err := pkgInfoFromPath(pkgPath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tin := info{\n\t\t\tPkgName: pkg.Name(),\n\t\t\tPkgPath: pkg.Path(),\n\t\t\tStructs: make(map[string][]mutableField),\n\t\t}\n\t\tscope := pkg.Scope()\n\t\tfor _, name := range scope.Names() {\n\t\t\tobj := scope.Lookup(name)\n\t\t\ts, ok := obj.Type().Underlying().(*types.Struct)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tptr := types.NewPointer(obj.Type())\n\t\t\t\/\/ FIXME implements returns false for intents.Intent but it should\n\t\t\t\/\/ return true, find why!\n\t\t\t\/\/ implements := types.Implements(ptr.Underlying(), docIface)\n\t\t\tf, g := types.MissingMethod(ptr.Underlying(), docIface, true)\n\t\t\tif f != nil && !g {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfields := make([]mutableField, 0)\n\t\t\tfor i := 0; i < s.NumFields(); i++ {\n\t\t\t\tfield := s.Field(i)\n\t\t\t\t\/\/ fmt.Printf(\" - %d. %s - %s\\n\", i, field.Name(), field.Type())\n\t\t\t\tswitch t := field.Type().(type) {\n\t\t\t\tcase (*types.Slice):\n\t\t\t\t\tfields = append(fields, &sliceField{\n\t\t\t\t\t\tName:  field.Name(),\n\t\t\t\t\t\tValue: generatorForType(t.Elem()),\n\t\t\t\t\t})\n\t\t\t\tcase (*types.Map):\n\t\t\t\t\tfields = append(fields, &mapField{\n\t\t\t\t\t\tName:  field.Name(),\n\t\t\t\t\t\tKey:   generatorForType(t.Key()),\n\t\t\t\t\t\tValue: generatorForType(t.Elem()),\n\t\t\t\t\t})\n\t\t\t\tcase (*types.Named):\n\t\t\t\t\tnamed := fmt.Sprintf(\"%s.%s\", t.Obj().Pkg().Name(), t.Obj().Name())\n\t\t\t\t\tswitch named {\n\t\t\t\t\tcase \"time.Time\", \"time.Duration\":\n\t\t\t\t\t\t\/\/ These structs are known to be safe\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tpanic(fmt.Errorf(\"Unknown named type: %s\", named))\n\t\t\t\t\t}\n\t\t\t\tcase (*types.Interface):\n\t\t\t\t\tfmt.Fprintf(os.Stderr, \"Warning: cannot check interfaces: %s.%s -> %s\\n\",\n\t\t\t\t\t\tpkg.Name(), name, field)\n\t\t\t\tcase (*types.Pointer):\n\t\t\t\t\tfields = append(fields, &ptrField{\n\t\t\t\t\t\tName:  field.Name(),\n\t\t\t\t\t\tValue: generatorForType(t.Elem()),\n\t\t\t\t\t})\n\t\t\t\tcase (*types.Basic):\n\t\t\t\t\t\/\/ Basic types are immutables\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(fmt.Errorf(\"Unknown type: %#v\", field.Type()))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(fields) > 0 {\n\t\t\t\tin.Structs[name] = fields\n\t\t\t}\n\t\t}\n\t\tif len(in.Structs) > 0 {\n\t\t\tinfos = append(infos, in)\n\t\t}\n\t}\n\treturn infos\n}\n\nfunc generateTests(infos []info) {\n\tfmt.Printf(`\/\/ Generated tests for Clone(). Do not manually edit!\npackage clone\n\nimport (\n\t\"testing\"\n`)\n\tfor _, info := range infos {\n\t\tfmt.Printf(\"\\t\\\"%s\\\"\\n\", info.PkgPath)\n\t}\n\tfmt.Printf(\")\\n\\n\")\n\n\tfor _, info := range infos {\n\t\tfmt.Printf(\"func Test%s(t *testing.T) {\\n\", strings.Title(info.PkgName))\n\t\tfor name, fields := range info.Structs {\n\t\t\tv := strings.ToLower(name)\n\t\t\tfmt.Printf(\"\\t%sA := &%s.%s{}\\n\", v, info.PkgName, name)\n\t\t\tfor _, field := range fields {\n\t\t\t\tfield.Initialize(v)\n\t\t\t}\n\t\t\tptr := \"*\"\n\t\t\tif name == \"JSONDoc\" {\n\t\t\t\tptr = \"\"\n\t\t\t}\n\t\t\tfmt.Printf(\"\\t%sB := %sA.Clone().(%s%s.%s)\\n\", v, v, ptr, info.PkgName, name)\n\t\t\tfor _, field := range fields {\n\t\t\t\tfield.Reassign(v)\n\t\t\t\tfield.Compare(v)\n\t\t\t\tfmt.Printf(\"\\t\\tt.Fatalf(\\\"Error for clone %s.%s -> %s\\\")\\n\\t}\\n\", info.PkgName, name, field)\n\t\t\t}\n\t\t}\n\t\tfmt.Printf(\"}\\n\\n\")\n\t}\n}\n\ntype info struct {\n\tPkgName string\n\tPkgPath string\n\tStructs map[string][]mutableField\n}\n\ntype mutableField interface {\n\tString() string\n\tInitialize(v string)\n\tReassign(v string)\n\tCompare(v string)\n}\n\ntype sliceField struct {\n\tName  string\n\tValue generator\n}\n\nfunc (f *sliceField) String() string { return f.Name }\n\nfunc (f *sliceField) Initialize(v string) {\n\tif f.Value.Warning != \"\" {\n\t\tfmt.Printf(\"\\t\/\/ Warning: %s\", f.Value.Warning)\n\t}\n\tfmt.Printf(\"\\t%sA.%s = []%s{%s}\\n\", v, f.Name, f.Value.Type, f.Value.Initial)\n}\nfunc (f *sliceField) Reassign(v string) {\n\tfmt.Printf(\"\\t%sA.%s[0]%s = %s\\n\", v, f.Name, f.Value.SubKey, f.Value.Altered)\n}\nfunc (f *sliceField) Compare(v string) {\n\tfmt.Printf(\"\\tif %sB.%s[0]%s != %s {\\n\", v, f.Name, f.Value.SubKey, f.Value.SubValue)\n}\n\ntype mapField struct {\n\tName  string\n\tKey   generator\n\tValue generator\n}\n\nfunc (f *mapField) String() string { return f.Name }\n\nfunc (f *mapField) Initialize(v string) {\n\tif f.Value.Warning != \"\" {\n\t\tfmt.Printf(\"\\t\/\/ Warning: %s\\n\", f.Value.Warning)\n\t}\n\tfmt.Printf(\"\\t%sA.%s = map[%s]%s{%s: %s}\\n\", v, f.Name, f.Key.Type, f.Value.Type, f.Key.Key, f.Value.Initial)\n}\nfunc (f *mapField) Reassign(v string) {\n\tfmt.Printf(\"\\t%sA.%s[%s]%s = %s\\n\", v, f.Name, f.Key.Key, f.Value.SubKey, f.Value.Altered)\n}\nfunc (f *mapField) Compare(v string) {\n\tfmt.Printf(\"\\tif %sB.%s[%s]%s != %s {\\n\", v, f.Name, f.Key.Key, f.Value.SubKey, f.Value.SubValue)\n}\n\ntype ptrField struct {\n\tName  string\n\tValue generator\n}\n\nfunc (f *ptrField) String() string { return f.Name }\n\nfunc (f *ptrField) Initialize(v string) {\n\tif f.Value.Warning != \"\" {\n\t\tfmt.Printf(\"\\t\/\/ Warning: %s\", f.Value.Warning)\n\t}\n\tfmt.Printf(\"\\t%sA.%s = &%s\\n\", v, f.Name, f.Value.Initial)\n}\nfunc (f *ptrField) Reassign(v string) {\n\tfmt.Printf(\"\\t%sA.%s%s = %s\\n\", v, f.Name, f.Value.SubKey, f.Value.Altered)\n}\nfunc (f *ptrField) Compare(v string) {\n\tfmt.Printf(\"\\tif %sB.%s%s != %s {\\n\", v, f.Name, f.Value.SubKey, f.Value.SubValue)\n}\n\nfunc generatorForType(typ types.Type) generator {\n\tswitch t := typ.(type) {\n\tcase (*types.Basic):\n\t\tswitch t.Name() {\n\t\tcase \"string\":\n\t\t\treturn stringGenerator\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"Unknown basic type: %s\", t.Name()))\n\t\t}\n\tcase (*types.Interface):\n\t\tif t.Empty() {\n\t\t\treturn emptyInterfaceGenerator\n\t\t}\n\tcase (*types.Named):\n\t\tif s, ok := t.Obj().Type().Underlying().(*types.Struct); ok {\n\t\t\tnamed := fmt.Sprintf(\"%s.%s\", t.Obj().Pkg().Name(), t.Obj().Name())\n\t\t\treturn structGenerator(named, s)\n\t\t}\n\t}\n\tpanic(fmt.Errorf(\"Unknown generator type: %#v\", typ))\n}\n\ntype generator struct {\n\tType     string\n\tKey      string\n\tInitial  string\n\tAltered  string\n\tWarning  string\n\tSubKey   string\n\tSubValue string\n}\n\nvar stringGenerator = generator{\n\tType:     \"string\",\n\tKey:      `\"foo\"`,\n\tInitial:  `\"bar\"`,\n\tAltered:  `\"baz\"`,\n\tSubValue: `\"bar\"`,\n}\n\nvar emptyInterfaceGenerator = generator{\n\tType:     \"interface{}\",\n\tKey:      \"0\",\n\tInitial:  \"1\",\n\tAltered:  \"2\",\n\tSubValue: \"1\",\n\tWarning:  \"interface{} can contain nested data!\",\n}\n\nfunc structGenerator(name string, s *types.Struct) generator {\n\tf := s.Field(0)\n\tg := generatorForType(f.Type())\n\treturn generator{\n\t\tType:     \"&ptr\",\n\t\tInitial:  fmt.Sprintf(\"%s{%s: %s}\", name, f.Name(), g.Initial),\n\t\tAltered:  g.Altered,\n\t\tSubKey:   \".\" + f.Name(),\n\t\tSubValue: g.SubValue,\n\t}\n}\n\n\/\/ getDocIface returns the couchdb.Doc interface\nfunc getDocIface() *types.Interface {\n\tcouchPkg := \"github.com\/cozy\/cozy-stack\/pkg\/couchdb\"\n\tconf := loader.Config{\n\t\tParserMode: parser.SpuriousErrors,\n\t}\n\tconf.Import(couchPkg)\n\tlprog, err := conf.Load()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tscope := lprog.Package(couchPkg).Pkg.Scope()\n\treturn scope.Lookup(\"Doc\").Type().Underlying().(*types.Interface)\n}\n\n\/\/ pkgInfoFromPath returns information about the package\n\/\/ Taken from https:\/\/github.com\/matryer\/moq\nfunc pkgInfoFromPath(src string) (*types.Package, error) {\n\tabs, err := filepath.Abs(src)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpkgFull := stripGopath(abs)\n\n\tconf := loader.Config{\n\t\tParserMode: parser.SpuriousErrors,\n\t}\n\tconf.Import(pkgFull)\n\tlprog, err := conf.Load()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpkgInfo := lprog.Package(pkgFull)\n\tif pkgInfo == nil {\n\t\treturn nil, errors.New(\"package was nil\")\n\t}\n\n\treturn pkgInfo.Pkg, nil\n}\n\n\/\/ stripGopath takes the directory to a package and remove the gopath to get the\n\/\/ canonical package name.\n\/\/ Taken from https:\/\/github.com\/ernesto-jimenez\/gogen\nfunc stripGopath(p string) string {\n\tfor _, gopath := range gopaths() {\n\t\tp = strings.TrimPrefix(p, path.Join(gopath, \"src\")+\"\/\")\n\t}\n\treturn p\n}\n\nfunc gopaths() []string {\n\treturn strings.Split(os.Getenv(\"GOPATH\"), string(filepath.ListSeparator))\n}\n<|endoftext|>"}
{"text":"<commit_before>package etw\r\n\r\n\/\/ Channel represents the ETW logging channel that is used. It can be used by\r\n\/\/ event consumers to give an event special treatment.\r\ntype Channel uint8\r\n\r\nconst (\r\n\t\/\/ ChannelTraceLogging is the default channel for TraceLogging events. It is\r\n\t\/\/ not required to be used for TraceLogging, but will prevent decoding\r\n\t\/\/ issues for these events on older operating systems.\r\n\tChannelTraceLogging Channel = 11\r\n)\r\n\r\n\/\/ Level represents the ETW logging level. There are several predefined levels\r\n\/\/ that are commonly used, but technically anything from 0-255 is allowed.\r\n\/\/ Lower levels indicate more important events, and 0 indicates an event that\r\n\/\/ will always be collected.\r\ntype Level uint8\r\n\r\n\/\/ Predefined ETW log levels.\r\nconst (\r\n\tLevelAlways Level = iota\r\n\tLevelCritical\r\n\tLevelError\r\n\tLevelWarning\r\n\tLevelInfo\r\n\tLevelVerbose\r\n)\r\n\r\n\/\/ Event represents a single ETW event. It can have field metadata and data\r\n\/\/ added to it, and then be logged via a provider to actually send it to ETW.\r\ntype Event struct {\r\n\tDescriptor *EventDescriptor\r\n\tMetadata   *EventMetadata\r\n\tData       *EventData\r\n}\r\n\r\n\/\/ NewEvent returns a new instance of an event object.\r\nfunc NewEvent(name string, descriptor *EventDescriptor) *Event {\r\n\treturn &Event{\r\n\t\tDescriptor: descriptor,\r\n\t\tMetadata:   NewEventMetadata(name),\r\n\t\tData:       &EventData{},\r\n\t}\r\n}\r\n\r\n\/\/ EventDescriptor represents various metadata for an ETW event.\r\ntype EventDescriptor struct {\r\n\tid      uint16\r\n\tversion uint8\r\n\tChannel Channel\r\n\tLevel   Level\r\n\tOpcode  uint8\r\n\tTask    uint16\r\n\tKeyword uint64\r\n}\r\n\r\n\/\/ NewEventDescriptor returns an EventDescriptor initialized for use with\r\n\/\/ TraceLogging.\r\nfunc NewEventDescriptor() *EventDescriptor {\r\n\t\/\/ Standard TraceLogging events default to the TraceLogging channel, and\r\n\t\/\/ verbose level.\r\n\treturn &EventDescriptor{\r\n\t\tid:      0,\r\n\t\tversion: 0,\r\n\t\tChannel: ChannelTraceLogging,\r\n\t\tLevel:   LevelVerbose,\r\n\t\tOpcode:  0,\r\n\t\tTask:    0,\r\n\t\tKeyword: 0,\r\n\t}\r\n}\r\n\r\n\/\/ Identity returns the identity of the event. If the identity is not 0, it\r\n\/\/ should uniquely identify the other event metadata (contained in\r\n\/\/ EventDescriptor, and field metadata). Only the lower 24 bits of this value\r\n\/\/ are relevant.\r\nfunc (ed *EventDescriptor) Identity() uint32 {\r\n\treturn (uint32(ed.version) << 16) & uint32(ed.id)\r\n}\r\n\r\n\/\/ SetIdentity sets the identity of the event. If the identity is not 0, it\r\n\/\/ should uniquely identify the other event metadata (contained in\r\n\/\/ EventDescriptor, and field metadata). Only the lower 24 bits of this value\r\n\/\/ are relevant.\r\nfunc (ed *EventDescriptor) SetIdentity(identity uint32) {\r\n\ted.id = uint16(identity)\r\n\ted.version = uint8(identity >> 16)\r\n}\r\n<commit_msg>Update pkg\/etw\/event.go<commit_after>package etw\r\n\r\n\/\/ Channel represents the ETW logging channel that is used. It can be used by\r\n\/\/ event consumers to give an event special treatment.\r\ntype Channel uint8\r\n\r\nconst (\r\n\t\/\/ ChannelTraceLogging is the default channel for TraceLogging events. It is\r\n\t\/\/ not required to be used for TraceLogging, but will prevent decoding\r\n\t\/\/ issues for these events on older operating systems.\r\n\tChannelTraceLogging Channel = 11\r\n)\r\n\r\n\/\/ Level represents the ETW logging level. There are several predefined levels\r\n\/\/ that are commonly used, but technically anything from 0-255 is allowed.\r\n\/\/ Lower levels indicate more important events, and 0 indicates an event that\r\n\/\/ will always be collected.\r\ntype Level uint8\r\n\r\n\/\/ Predefined ETW log levels.\r\nconst (\r\n\tLevelAlways Level = iota\r\n\tLevelCritical\r\n\tLevelError\r\n\tLevelWarning\r\n\tLevelInfo\r\n\tLevelVerbose\r\n)\r\n\r\n\/\/ Event represents a single ETW event. It can have field metadata and data\r\n\/\/ added to it, and then be logged via a provider to actually send it to ETW.\r\ntype Event struct {\r\n\tDescriptor *EventDescriptor\r\n\tMetadata   *EventMetadata\r\n\tData       *EventData\r\n}\r\n\r\n\/\/ NewEvent returns a new instance of an event object.\r\nfunc NewEvent(name string, descriptor *EventDescriptor) *Event {\r\n\treturn &Event{\r\n\t\tDescriptor: descriptor,\r\n\t\tMetadata:   NewEventMetadata(name),\r\n\t\tData:       &EventData{},\r\n\t}\r\n}\r\n\r\n\/\/ EventDescriptor represents various metadata for an ETW event.\r\ntype EventDescriptor struct {\r\n\tid      uint16\r\n\tversion uint8\r\n\tChannel Channel\r\n\tLevel   Level\r\n\tOpcode  uint8\r\n\tTask    uint16\r\n\tKeyword uint64\r\n}\r\n\r\n\/\/ NewEventDescriptor returns an EventDescriptor initialized for use with\r\n\/\/ TraceLogging.\r\nfunc NewEventDescriptor() *EventDescriptor {\r\n\t\/\/ Standard TraceLogging events default to the TraceLogging channel, and\r\n\t\/\/ verbose level.\r\n\treturn &EventDescriptor{\r\n\t\tid:      0,\r\n\t\tversion: 0,\r\n\t\tChannel: ChannelTraceLogging,\r\n\t\tLevel:   LevelVerbose,\r\n\t\tOpcode:  0,\r\n\t\tTask:    0,\r\n\t\tKeyword: 0,\r\n\t}\r\n}\r\n\r\n\/\/ Identity returns the identity of the event. If the identity is not 0, it\r\n\/\/ should uniquely identify the other event metadata (contained in\r\n\/\/ EventDescriptor, and field metadata). Only the lower 24 bits of this value\r\n\/\/ are relevant.\r\nfunc (ed *EventDescriptor) Identity() uint32 {\r\n\treturn (uint32(ed.version) << 16) | uint32(ed.id)\r\n}\r\n\r\n\/\/ SetIdentity sets the identity of the event. If the identity is not 0, it\r\n\/\/ should uniquely identify the other event metadata (contained in\r\n\/\/ EventDescriptor, and field metadata). Only the lower 24 bits of this value\r\n\/\/ are relevant.\r\nfunc (ed *EventDescriptor) SetIdentity(identity uint32) {\r\n\ted.id = uint16(identity)\r\n\ted.version = uint8(identity >> 16)\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2015 Google Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage util\n\nimport (\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"github.com\/golang\/glog\"\n)\n\nfunc GetHostname(hostnameOverride string) string {\n\thostname := []byte(hostnameOverride)\n\tif string(hostname) == \"\" {\n\t\t\/\/ Note: We use exec here instead of os.Hostname() because we\n\t\t\/\/ want the FQDN, and this is the easiest way to get it.\n\t\tfqdn, err := exec.Command(\"uname\", \"-n\").Output()\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"Couldn't determine hostname: %v\", err)\n\t\t}\n\t\thostname = fqdn\n\t}\n\treturn strings.ToLower(strings.TrimSpace(string(hostname)))\n}\n<commit_msg>Remove deprecated comment.<commit_after>\/*\nCopyright 2015 Google Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage util\n\nimport (\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"github.com\/golang\/glog\"\n)\n\nfunc GetHostname(hostnameOverride string) string {\n\thostname := []byte(hostnameOverride)\n\tif string(hostname) == \"\" {\n\t\tfqdn, err := exec.Command(\"uname\", \"-n\").Output()\n\t\tif err != nil {\n\t\t\tglog.Fatalf(\"Couldn't determine hostname: %v\", err)\n\t\t}\n\t\thostname = fqdn\n\t}\n\treturn strings.ToLower(strings.TrimSpace(string(hostname)))\n}\n<|endoftext|>"}
{"text":"<commit_before>package utils\n\nimport (\n\t\"capsulecd\/pkg\/errors\"\n\t\"capsulecd\/pkg\/pipeline\"\n\t\"fmt\"\n\tgit2go \"gopkg.in\/libgit2\/git2go.v25\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Clone a git repo into a local directory.\n\/\/ Credentials need to be specified by embedding in gitRemote url.\n\/\/ TODO: this pattern may not work on Bitbucket\/GitLab\nfunc GitClone(parentPath string, repositoryName string, gitRemote string) (string, error) {\n\tabsPath, _ := filepath.Abs(path.Join(parentPath, repositoryName))\n\n\tif !FileExists(absPath) {\n\t\tos.MkdirAll(absPath, os.ModePerm)\n\t} else {\n\t\treturn \"\", errors.ScmFilesystemError(fmt.Sprintf(\"The local repository path already exists, this should never happen. %s\", absPath))\n\t}\n\n\t_, err := git2go.Clone(gitRemote, absPath, new(git2go.CloneOptions))\n\treturn absPath, err\n}\n\nfunc GitFetch(repoPath string, remoteRef string, localBranchName string) error {\n\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn oerr\n\t}\n\n\tcheckoutOpts := &git2go.CheckoutOpts{\n\t\tStrategy: git2go.CheckoutSafe | git2go.CheckoutRecreateMissing | git2go.CheckoutAllowConflicts | git2go.CheckoutUseTheirs,\n\t}\n\n\tremote, lerr := repo.Remotes.Lookup(\"origin\")\n\tif lerr != nil {\n\t\treturn lerr\n\t}\n\ttime.Sleep(time.Second)\n\tferr := remote.Fetch([]string{fmt.Sprintf(\"%s:%s\", remoteRef, localBranchName)}, new(git2go.FetchOptions), \"\")\n\tif ferr != nil {\n\t\treturn ferr\n\t}\n\n\t\/\/should not raise an error when looking for branch (we just created it above)\n\tlocalBranch, berr := repo.LookupBranch(localBranchName, git2go.BranchLocal)\n\tif berr != nil {\n\t\treturn berr\n\t}\n\n\t\/\/ Getting the tree for the branch\n\tlocalCommit, err := repo.LookupCommit(localBranch.Target())\n\tif err != nil {\n\t\tlog.Print(\"Failed to lookup for commit in local branch \" + localBranchName)\n\t\treturn err\n\t}\n\t\/\/defer localCommit.Free()\n\n\ttree, err := repo.LookupTree(localCommit.TreeId())\n\tif err != nil {\n\t\tlog.Print(\"Failed to lookup for tree \" + localBranchName)\n\t\treturn err\n\t}\n\t\/\/defer tree.Free()\n\n\t\/\/ Checkout the tree\n\terr = repo.CheckoutTree(tree, checkoutOpts)\n\tif err != nil {\n\t\tlog.Print(\"Failed to checkout tree \" + localBranchName)\n\t\treturn err\n\t}\n\t\/\/ Setting the Head to point to our branch\n\treturn repo.SetHead(\"refs\/heads\/\" + localBranchName)\n}\n\nfunc GitCheckout(repoPath string, branchName string) error {\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn oerr\n\t}\n\n\tcheckoutOpts := &git2go.CheckoutOpts{\n\t\tStrategy: git2go.CheckoutSafe | git2go.CheckoutRecreateMissing | git2go.CheckoutAllowConflicts | git2go.CheckoutUseTheirs,\n\t}\n\t\/\/Getting the reference for the remote branch\n\t\/\/ remoteBranch, err := repo.References.Lookup(\"refs\/remotes\/origin\/\" + branchName)\n\tremoteBranch, err := repo.LookupBranch(\"origin\/\"+branchName, git2go.BranchRemote)\n\tif err != nil {\n\t\tlog.Print(\"Failed to find remote branch: \" + branchName)\n\t\treturn err\n\t}\n\t\/\/defer remoteBranch.Free()\n\n\t\/\/ Lookup for commit from remote branch\n\tcommit, err := repo.LookupCommit(remoteBranch.Target())\n\tif err != nil {\n\t\tlog.Print(\"Failed to find remote branch commit: \" + branchName)\n\t\treturn err\n\t}\n\t\/\/defer commit.Free()\n\n\tlocalBranch, err := repo.LookupBranch(branchName, git2go.BranchLocal)\n\t\/\/ No local branch, lets create one\n\tif localBranch == nil || err != nil {\n\t\t\/\/ Creating local branch\n\t\tlocalBranch, err = repo.CreateBranch(branchName, commit, false)\n\t\tif err != nil {\n\t\t\tlog.Print(\"Failed to create local branch: \" + branchName)\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Setting upstream to origin branch\n\t\terr = localBranch.SetUpstream(\"origin\/\" + branchName)\n\t\tif err != nil {\n\t\t\tlog.Print(\"Failed to create upstream to origin\/\" + branchName)\n\t\t\treturn err\n\t\t}\n\t}\n\tif localBranch == nil {\n\t\treturn errors.ScmFilesystemError(\"Error while locating\/creating local branch\")\n\t}\n\t\/\/defer localBranch.Free()\n\n\t\/\/ Getting the tree for the branch\n\tlocalCommit, err := repo.LookupCommit(localBranch.Target())\n\tif err != nil {\n\t\tlog.Print(\"Failed to lookup for commit in local branch \" + branchName)\n\t\treturn err\n\t}\n\t\/\/defer localCommit.Free()\n\n\ttree, err := repo.LookupTree(localCommit.TreeId())\n\tif err != nil {\n\t\tlog.Print(\"Failed to lookup for tree \" + branchName)\n\t\treturn err\n\t}\n\t\/\/defer tree.Free()\n\n\t\/\/ Checkout the tree\n\terr = repo.CheckoutTree(tree, checkoutOpts)\n\tif err != nil {\n\t\tlog.Print(\"Failed to checkout tree \" + branchName)\n\t\treturn err\n\t}\n\t\/\/ Setting the Head to point to our branch\n\treturn repo.SetHead(\"refs\/heads\/\" + branchName)\n}\n\n\/\/Add all modified files to index, and commit.\nfunc GitCommit(repoPath string, message string) error {\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn oerr\n\t}\n\n\tsignature := gitSignature()\n\n\t\/\/get repo index.\n\tidx, ierr := repo.Index()\n\tif ierr != nil {\n\t\treturn ierr\n\t}\n\taerr := idx.AddAll([]string{}, git2go.IndexAddDefault, nil)\n\tif aerr != nil {\n\t\treturn aerr\n\t}\n\ttreeId, wterr := idx.WriteTree()\n\tif wterr != nil {\n\t\treturn wterr\n\t}\n\twerr := idx.Write()\n\tif werr != nil {\n\t\treturn werr\n\t}\n\n\ttree, lerr := repo.LookupTree(treeId)\n\tif lerr != nil {\n\t\treturn lerr\n\t}\n\n\tcurrentBranch, berr := repo.Head()\n\tif berr != nil {\n\t\treturn berr\n\t}\n\n\tcommitTarget, terr := repo.LookupCommit(currentBranch.Target())\n\tif terr != nil {\n\t\treturn terr\n\t}\n\n\t_, cerr := repo.CreateCommit(\"HEAD\", signature, signature, message, tree, commitTarget)\n\t\/\/if(cerr != nil){return cerr}\n\n\treturn cerr\n}\n\nfunc GitTag(repoPath string, version string) (string, error) {\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn \"\", oerr\n\t}\n\tcommitHead, herr := repo.Head()\n\tif herr != nil {\n\t\treturn \"\", herr\n\t}\n\n\tcommit, lerr := repo.LookupCommit(commitHead.Target())\n\tif lerr != nil {\n\t\treturn \"\", lerr\n\t}\n\n\t\/\/TODO: this should be a annotated tag.\n\ttagId, terr := repo.Tags.CreateLightweight(version, commit, false) \/\/TODO: this should be an annotated tag.\n\treturn tagId.String(), terr\n}\n\nfunc GitPush(repoPath string, localBranch string, remoteBranch string) error {\n\t\/\/- https:\/\/gist.github.com\/danielfbm\/37b0ca88b745503557b2b3f16865d8c3\n\t\/\/- https:\/\/stackoverflow.com\/questions\/37026399\/git2go-after-createcommit-all-files-appear-like-being-added-for-deletion\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn oerr\n\t}\n\n\t\/\/ Push\n\tremote, lerr := repo.Remotes.Lookup(\"origin\")\n\tif lerr != nil {\n\t\treturn lerr\n\t}\n\t\/\/remote.ConnectPush(gitRemoteCallbacks(), &git.ProxyOptions{}, []string{})\n\n\t\/\/err = remote.Push([]string{\"refs\/heads\/master\"}, nil, signature, message)\n\treturn remote.Push([]string{fmt.Sprintf(\"refs\/heads\/%s:refs\/heads\/%s\", localBranch, remoteBranch)}, new(git2go.PushOptions))\n}\n\n\/\/ Get the nearest tag on branch.\n\/\/ tag must be nearest, ie. sorted by their distance from the HEAD of the branch, not the date or tagname.\n\/\/ basically `git describe --tags --abbrev=0`\nfunc GitFindNearestTagName(repoPath string) (string, error) {\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn \"\", oerr\n\t}\n\n\tdescOptions, derr := git2go.DefaultDescribeOptions()\n\tif derr != nil {\n\t\treturn \"\", derr\n\t}\n\tdescOptions.Strategy = git2go.DescribeTags\n\n\tformatOptions, ferr := git2go.DefaultDescribeFormatOptions()\n\tif ferr != nil {\n\t\treturn \"\", ferr\n\t}\n\tformatOptions.AbbreviatedSize = 0\n\n\tdescr, derr := repo.DescribeWorkdir(&descOptions)\n\tif derr != nil {\n\t\treturn \"\", derr\n\t}\n\n\tnearestTag, ferr := descr.Format(&formatOptions)\n\tif ferr != nil {\n\t\treturn \"\", ferr\n\t}\n\n\treturn nearestTag, nil\n}\n\nfunc GitGenerateChangelog(repoPath string, baseSha string, headSha string) (string, error) {\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn \"\", oerr\n\t}\n\n\tmarkdown := StripIndent(`Timestamp |  SHA | Message | Author\n\t------------- | ------------- | ------------- | -------------\n\t`)\n\n\trevWalk, werr := repo.Walk()\n\tif werr != nil {\n\t\treturn \"\", werr\n\t}\n\n\trerr := revWalk.PushRange(fmt.Sprintf(\"%s..%s\", baseSha, headSha))\n\tif rerr != nil {\n\t\treturn \"\", rerr\n\t}\n\n\trevWalk.Iterate(func(commit *git2go.Commit) bool {\n\t\tmarkdown += fmt.Sprintf(\"%s | %.8s | %s | %s\\n\", \/\/TODO: this should have a link for the SHA.\n\t\t\tcommit.Author().When.UTC().Format(\"2006-01-02T15:04Z\"),\n\t\t\tcommit.Id().String(),\n\t\t\tcleanCommitMessage(commit.Message()),\n\t\t\tcommit.Author().Name,\n\t\t)\n\t\treturn true\n\t})\n\t\/\/for {\n\t\/\/\terr := revWalk.Next()\n\t\/\/\tif err != nil {\n\t\/\/\t\tbreak\n\t\/\/\t}\n\t\/\/\n\t\/\/\tlog.Info(gi.String())\n\t\/\/}\n\n\treturn markdown, nil\n}\n\nfunc GitGenerateGitIgnore(repoPath string, ignoreType string) error {\n\t\/\/https:\/\/github.com\/GlenDC\/go-gitignore\/blob\/master\/gitignore\/provider\/github.go\n\n\tgitIgnoreBytes, err := getGitIgnore(ignoreType)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgitIgnorePath := filepath.Join(repoPath, \".gitignore\")\n\treturn ioutil.WriteFile(gitIgnorePath, gitIgnoreBytes, 0644)\n}\n\nfunc GitGetTagDetails(repoPath string, tagName string) (*pipeline.GitTagDetails, error) {\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn nil, oerr\n\t}\n\n\tid, aerr := repo.References.Dwim(tagName)\n\tif aerr != nil {\n\t\treturn nil, aerr\n\t}\n\ttag, lerr := repo.LookupTag(id.Target()) \/\/assume its an annotated tag.\n\n\tvar currentTag *pipeline.GitTagDetails\n\tif lerr != nil {\n\t\t\/\/this is a lightweight tag, not an annotated tag.\n\t\tcommitRef, rerr := repo.LookupCommit(id.Target())\n\t\tif rerr != nil {\n\t\t\treturn nil, rerr\n\t\t}\n\n\t\tauthor := commitRef.Author()\n\n\t\tlog.Printf(\"Light-weight tag (%s) Commit ID: %s, DATE: %s\", tagName, commitRef.Id().String(), author.When.String())\n\n\t\tcurrentTag = &pipeline.GitTagDetails{\n\t\t\tTagShortName: tagName,\n\t\t\tCommitSha:    commitRef.Id().String(),\n\t\t\tCommitDate:   author.When,\n\t\t}\n\n\t} else {\n\n\t\tlog.Printf(\"Annotated tag (%s) Tag ID: %s, Commit ID: %s, DATE: %s\", tagName, tag.Id().String(), tag.TargetId().String(), tag.Tagger().When.String())\n\n\t\tcurrentTag = &pipeline.GitTagDetails{\n\t\t\tTagShortName: tagName,\n\t\t\tCommitSha:    tag.TargetId().String(),\n\t\t\tCommitDate:   tag.Tagger().When,\n\t\t}\n\t}\n\treturn currentTag, nil\n\n}\n\n\/\/private methods\n\nfunc gitSignature() *git2go.Signature {\n\treturn &git2go.Signature{\n\t\tName:  \"CapsuleCD\",\n\t\tEmail: \"CapsuleCD@users.noreply.github.com\",\n\t\tWhen:  time.Now(),\n\t}\n}\n\nfunc cleanCommitMessage(commitMessage string) string {\n\tcommitMessage = strings.TrimSpace(commitMessage)\n\tif commitMessage == \"\" {\n\t\treturn \"--\"\n\t}\n\n\tcommitMessage = strings.Replace(commitMessage, \"|\", \"\/\", -1)\n\tcommitMessage = strings.Replace(commitMessage, \"\\n\", \" \", -1)\n\n\treturn commitMessage\n}\n\nfunc getGitIgnore(languageName string) ([]byte, error) {\n\tgitURL := fmt.Sprintf(\"https:\/\/raw.githubusercontent.com\/github\/gitignore\/master\/%s.gitignore\", languageName)\n\n\tresp, err := http.Get(gitURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn nil, errors.Custom(fmt.Sprintf(\"Could not find .gitignore for '%s'\", languageName))\n\t}\n\n\treturn ioutil.ReadAll(resp.Body)\n}\n\n\/\/func gitRemoteCallbacks() *git.RemoteCallbacks {\n\/\/\treturn  &git.RemoteCallbacks{\n\/\/\t\tCredentialsCallback: credentialsCallback,\n\/\/\t\tCertificateCheckCallback: certificateCheckCallback,\n\/\/\t}\n\/\/}\n\/\/\n\/\/func credentialsCallback(url string, username_from_url string, allowed_types git.CredType) (git.ErrorCode, *git.Cred) {\n\/\/\tlog.Printf(\"This is the CRED URL FOR PUSH: %s %s\",url, username_from_url)\n\/\/\tret, cred := git.NewCredUserpassPlaintext(\"placeholder\", \"\") \/\/TODO: remote cred.\n\/\/\n\/\/\tlog.Printf(\"THIS IS THE CRED RESPONS: %s %s\", ret, cred)\n\/\/\treturn git.ErrorCode(ret), &cred\n\/\/}\n\/\/\n\/\/func certificateCheckCallback(cert *git.Certificate, valid bool, hostname string) git.ErrorCode {\n\/\/\tif hostname != \"github.com\" {\n\/\/\t\treturn git.ErrUser\n\/\/\t}\n\/\/\treturn git.ErrOk\n\/\/}\n<commit_msg>add code to create annotated tags.<commit_after>package utils\n\nimport (\n\t\"capsulecd\/pkg\/errors\"\n\t\"capsulecd\/pkg\/pipeline\"\n\t\"fmt\"\n\tgit2go \"gopkg.in\/libgit2\/git2go.v25\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Clone a git repo into a local directory.\n\/\/ Credentials need to be specified by embedding in gitRemote url.\n\/\/ TODO: this pattern may not work on Bitbucket\/GitLab\nfunc GitClone(parentPath string, repositoryName string, gitRemote string) (string, error) {\n\tabsPath, _ := filepath.Abs(path.Join(parentPath, repositoryName))\n\n\tif !FileExists(absPath) {\n\t\tos.MkdirAll(absPath, os.ModePerm)\n\t} else {\n\t\treturn \"\", errors.ScmFilesystemError(fmt.Sprintf(\"The local repository path already exists, this should never happen. %s\", absPath))\n\t}\n\n\t_, err := git2go.Clone(gitRemote, absPath, new(git2go.CloneOptions))\n\treturn absPath, err\n}\n\nfunc GitFetch(repoPath string, remoteRef string, localBranchName string) error {\n\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn oerr\n\t}\n\n\tcheckoutOpts := &git2go.CheckoutOpts{\n\t\tStrategy: git2go.CheckoutSafe | git2go.CheckoutRecreateMissing | git2go.CheckoutAllowConflicts | git2go.CheckoutUseTheirs,\n\t}\n\n\tremote, lerr := repo.Remotes.Lookup(\"origin\")\n\tif lerr != nil {\n\t\treturn lerr\n\t}\n\ttime.Sleep(time.Second)\n\tferr := remote.Fetch([]string{fmt.Sprintf(\"%s:%s\", remoteRef, localBranchName)}, new(git2go.FetchOptions), \"\")\n\tif ferr != nil {\n\t\treturn ferr\n\t}\n\n\t\/\/should not raise an error when looking for branch (we just created it above)\n\tlocalBranch, berr := repo.LookupBranch(localBranchName, git2go.BranchLocal)\n\tif berr != nil {\n\t\treturn berr\n\t}\n\n\t\/\/ Getting the tree for the branch\n\tlocalCommit, err := repo.LookupCommit(localBranch.Target())\n\tif err != nil {\n\t\tlog.Print(\"Failed to lookup for commit in local branch \" + localBranchName)\n\t\treturn err\n\t}\n\t\/\/defer localCommit.Free()\n\n\ttree, err := repo.LookupTree(localCommit.TreeId())\n\tif err != nil {\n\t\tlog.Print(\"Failed to lookup for tree \" + localBranchName)\n\t\treturn err\n\t}\n\t\/\/defer tree.Free()\n\n\t\/\/ Checkout the tree\n\terr = repo.CheckoutTree(tree, checkoutOpts)\n\tif err != nil {\n\t\tlog.Print(\"Failed to checkout tree \" + localBranchName)\n\t\treturn err\n\t}\n\t\/\/ Setting the Head to point to our branch\n\treturn repo.SetHead(\"refs\/heads\/\" + localBranchName)\n}\n\nfunc GitCheckout(repoPath string, branchName string) error {\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn oerr\n\t}\n\n\tcheckoutOpts := &git2go.CheckoutOpts{\n\t\tStrategy: git2go.CheckoutSafe | git2go.CheckoutRecreateMissing | git2go.CheckoutAllowConflicts | git2go.CheckoutUseTheirs,\n\t}\n\t\/\/Getting the reference for the remote branch\n\t\/\/ remoteBranch, err := repo.References.Lookup(\"refs\/remotes\/origin\/\" + branchName)\n\tremoteBranch, err := repo.LookupBranch(\"origin\/\"+branchName, git2go.BranchRemote)\n\tif err != nil {\n\t\tlog.Print(\"Failed to find remote branch: \" + branchName)\n\t\treturn err\n\t}\n\t\/\/defer remoteBranch.Free()\n\n\t\/\/ Lookup for commit from remote branch\n\tcommit, err := repo.LookupCommit(remoteBranch.Target())\n\tif err != nil {\n\t\tlog.Print(\"Failed to find remote branch commit: \" + branchName)\n\t\treturn err\n\t}\n\t\/\/defer commit.Free()\n\n\tlocalBranch, err := repo.LookupBranch(branchName, git2go.BranchLocal)\n\t\/\/ No local branch, lets create one\n\tif localBranch == nil || err != nil {\n\t\t\/\/ Creating local branch\n\t\tlocalBranch, err = repo.CreateBranch(branchName, commit, false)\n\t\tif err != nil {\n\t\t\tlog.Print(\"Failed to create local branch: \" + branchName)\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Setting upstream to origin branch\n\t\terr = localBranch.SetUpstream(\"origin\/\" + branchName)\n\t\tif err != nil {\n\t\t\tlog.Print(\"Failed to create upstream to origin\/\" + branchName)\n\t\t\treturn err\n\t\t}\n\t}\n\tif localBranch == nil {\n\t\treturn errors.ScmFilesystemError(\"Error while locating\/creating local branch\")\n\t}\n\t\/\/defer localBranch.Free()\n\n\t\/\/ Getting the tree for the branch\n\tlocalCommit, err := repo.LookupCommit(localBranch.Target())\n\tif err != nil {\n\t\tlog.Print(\"Failed to lookup for commit in local branch \" + branchName)\n\t\treturn err\n\t}\n\t\/\/defer localCommit.Free()\n\n\ttree, err := repo.LookupTree(localCommit.TreeId())\n\tif err != nil {\n\t\tlog.Print(\"Failed to lookup for tree \" + branchName)\n\t\treturn err\n\t}\n\t\/\/defer tree.Free()\n\n\t\/\/ Checkout the tree\n\terr = repo.CheckoutTree(tree, checkoutOpts)\n\tif err != nil {\n\t\tlog.Print(\"Failed to checkout tree \" + branchName)\n\t\treturn err\n\t}\n\t\/\/ Setting the Head to point to our branch\n\treturn repo.SetHead(\"refs\/heads\/\" + branchName)\n}\n\n\/\/Add all modified files to index, and commit.\nfunc GitCommit(repoPath string, message string) error {\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn oerr\n\t}\n\n\tsignature := gitSignature()\n\n\t\/\/get repo index.\n\tidx, ierr := repo.Index()\n\tif ierr != nil {\n\t\treturn ierr\n\t}\n\taerr := idx.AddAll([]string{}, git2go.IndexAddDefault, nil)\n\tif aerr != nil {\n\t\treturn aerr\n\t}\n\ttreeId, wterr := idx.WriteTree()\n\tif wterr != nil {\n\t\treturn wterr\n\t}\n\twerr := idx.Write()\n\tif werr != nil {\n\t\treturn werr\n\t}\n\n\ttree, lerr := repo.LookupTree(treeId)\n\tif lerr != nil {\n\t\treturn lerr\n\t}\n\n\tcurrentBranch, berr := repo.Head()\n\tif berr != nil {\n\t\treturn berr\n\t}\n\n\tcommitTarget, terr := repo.LookupCommit(currentBranch.Target())\n\tif terr != nil {\n\t\treturn terr\n\t}\n\n\t_, cerr := repo.CreateCommit(\"HEAD\", signature, signature, message, tree, commitTarget)\n\t\/\/if(cerr != nil){return cerr}\n\n\treturn cerr\n}\n\nfunc GitTag(repoPath string, version string) (string, error) {\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn \"\", oerr\n\t}\n\tcommitHead, herr := repo.Head()\n\tif herr != nil {\n\t\treturn \"\", herr\n\t}\n\n\tcommit, lerr := repo.LookupCommit(commitHead.Target())\n\tif lerr != nil {\n\t\treturn \"\", lerr\n\t}\n\n\t\/\/TODO: this should be a annotated tag.\n\t\/\/tagId, terr := repo.Tags.CreateLightweight(version, commit, false) \/\/TODO: this should be an annotated tag.\n\n\ttagId, terr := repo.Tags.Create(version, commit, gitSignature(), fmt.Sprintf(\"(v%s) Automated packaging of release by CapsuleCD\", version))\n\treturn tagId.String(), terr\n}\n\nfunc GitPush(repoPath string, localBranch string, remoteBranch string) error {\n\t\/\/- https:\/\/gist.github.com\/danielfbm\/37b0ca88b745503557b2b3f16865d8c3\n\t\/\/- https:\/\/stackoverflow.com\/questions\/37026399\/git2go-after-createcommit-all-files-appear-like-being-added-for-deletion\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn oerr\n\t}\n\n\t\/\/ Push\n\tremote, lerr := repo.Remotes.Lookup(\"origin\")\n\tif lerr != nil {\n\t\treturn lerr\n\t}\n\t\/\/remote.ConnectPush(gitRemoteCallbacks(), &git.ProxyOptions{}, []string{})\n\n\t\/\/err = remote.Push([]string{\"refs\/heads\/master\"}, nil, signature, message)\n\treturn remote.Push([]string{fmt.Sprintf(\"refs\/heads\/%s:refs\/heads\/%s\", localBranch, remoteBranch)}, new(git2go.PushOptions))\n}\n\n\/\/ Get the nearest tag on branch.\n\/\/ tag must be nearest, ie. sorted by their distance from the HEAD of the branch, not the date or tagname.\n\/\/ basically `git describe --tags --abbrev=0`\nfunc GitFindNearestTagName(repoPath string) (string, error) {\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn \"\", oerr\n\t}\n\n\tdescOptions, derr := git2go.DefaultDescribeOptions()\n\tif derr != nil {\n\t\treturn \"\", derr\n\t}\n\tdescOptions.Strategy = git2go.DescribeTags\n\n\tformatOptions, ferr := git2go.DefaultDescribeFormatOptions()\n\tif ferr != nil {\n\t\treturn \"\", ferr\n\t}\n\tformatOptions.AbbreviatedSize = 0\n\n\tdescr, derr := repo.DescribeWorkdir(&descOptions)\n\tif derr != nil {\n\t\treturn \"\", derr\n\t}\n\n\tnearestTag, ferr := descr.Format(&formatOptions)\n\tif ferr != nil {\n\t\treturn \"\", ferr\n\t}\n\n\treturn nearestTag, nil\n}\n\nfunc GitGenerateChangelog(repoPath string, baseSha string, headSha string) (string, error) {\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn \"\", oerr\n\t}\n\n\tmarkdown := StripIndent(`Timestamp |  SHA | Message | Author\n\t------------- | ------------- | ------------- | -------------\n\t`)\n\n\trevWalk, werr := repo.Walk()\n\tif werr != nil {\n\t\treturn \"\", werr\n\t}\n\n\trerr := revWalk.PushRange(fmt.Sprintf(\"%s..%s\", baseSha, headSha))\n\tif rerr != nil {\n\t\treturn \"\", rerr\n\t}\n\n\trevWalk.Iterate(func(commit *git2go.Commit) bool {\n\t\tmarkdown += fmt.Sprintf(\"%s | %.8s | %s | %s\\n\", \/\/TODO: this should have a link for the SHA.\n\t\t\tcommit.Author().When.UTC().Format(\"2006-01-02T15:04Z\"),\n\t\t\tcommit.Id().String(),\n\t\t\tcleanCommitMessage(commit.Message()),\n\t\t\tcommit.Author().Name,\n\t\t)\n\t\treturn true\n\t})\n\t\/\/for {\n\t\/\/\terr := revWalk.Next()\n\t\/\/\tif err != nil {\n\t\/\/\t\tbreak\n\t\/\/\t}\n\t\/\/\n\t\/\/\tlog.Info(gi.String())\n\t\/\/}\n\n\treturn markdown, nil\n}\n\nfunc GitGenerateGitIgnore(repoPath string, ignoreType string) error {\n\t\/\/https:\/\/github.com\/GlenDC\/go-gitignore\/blob\/master\/gitignore\/provider\/github.go\n\n\tgitIgnoreBytes, err := getGitIgnore(ignoreType)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgitIgnorePath := filepath.Join(repoPath, \".gitignore\")\n\treturn ioutil.WriteFile(gitIgnorePath, gitIgnoreBytes, 0644)\n}\n\nfunc GitGetTagDetails(repoPath string, tagName string) (*pipeline.GitTagDetails, error) {\n\trepo, oerr := git2go.OpenRepository(repoPath)\n\tif oerr != nil {\n\t\treturn nil, oerr\n\t}\n\n\tid, aerr := repo.References.Dwim(tagName)\n\tif aerr != nil {\n\t\treturn nil, aerr\n\t}\n\ttag, lerr := repo.LookupTag(id.Target()) \/\/assume its an annotated tag.\n\n\tvar currentTag *pipeline.GitTagDetails\n\tif lerr != nil {\n\t\t\/\/this is a lightweight tag, not an annotated tag.\n\t\tcommitRef, rerr := repo.LookupCommit(id.Target())\n\t\tif rerr != nil {\n\t\t\treturn nil, rerr\n\t\t}\n\n\t\tauthor := commitRef.Author()\n\n\t\tlog.Printf(\"Light-weight tag (%s) Commit ID: %s, DATE: %s\", tagName, commitRef.Id().String(), author.When.String())\n\n\t\tcurrentTag = &pipeline.GitTagDetails{\n\t\t\tTagShortName: tagName,\n\t\t\tCommitSha:    commitRef.Id().String(),\n\t\t\tCommitDate:   author.When,\n\t\t}\n\n\t} else {\n\n\t\tlog.Printf(\"Annotated tag (%s) Tag ID: %s, Commit ID: %s, DATE: %s\", tagName, tag.Id().String(), tag.TargetId().String(), tag.Tagger().When.String())\n\n\t\tcurrentTag = &pipeline.GitTagDetails{\n\t\t\tTagShortName: tagName,\n\t\t\tCommitSha:    tag.TargetId().String(),\n\t\t\tCommitDate:   tag.Tagger().When,\n\t\t}\n\t}\n\treturn currentTag, nil\n\n}\n\n\/\/private methods\n\nfunc gitSignature() *git2go.Signature {\n\treturn &git2go.Signature{\n\t\tName:  \"CapsuleCD\",\n\t\tEmail: \"CapsuleCD@users.noreply.github.com\",\n\t\tWhen:  time.Now(),\n\t}\n}\n\nfunc cleanCommitMessage(commitMessage string) string {\n\tcommitMessage = strings.TrimSpace(commitMessage)\n\tif commitMessage == \"\" {\n\t\treturn \"--\"\n\t}\n\n\tcommitMessage = strings.Replace(commitMessage, \"|\", \"\/\", -1)\n\tcommitMessage = strings.Replace(commitMessage, \"\\n\", \" \", -1)\n\n\treturn commitMessage\n}\n\nfunc getGitIgnore(languageName string) ([]byte, error) {\n\tgitURL := fmt.Sprintf(\"https:\/\/raw.githubusercontent.com\/github\/gitignore\/master\/%s.gitignore\", languageName)\n\n\tresp, err := http.Get(gitURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn nil, errors.Custom(fmt.Sprintf(\"Could not find .gitignore for '%s'\", languageName))\n\t}\n\n\treturn ioutil.ReadAll(resp.Body)\n}\n\n\/\/func gitRemoteCallbacks() *git.RemoteCallbacks {\n\/\/\treturn  &git.RemoteCallbacks{\n\/\/\t\tCredentialsCallback: credentialsCallback,\n\/\/\t\tCertificateCheckCallback: certificateCheckCallback,\n\/\/\t}\n\/\/}\n\/\/\n\/\/func credentialsCallback(url string, username_from_url string, allowed_types git.CredType) (git.ErrorCode, *git.Cred) {\n\/\/\tlog.Printf(\"This is the CRED URL FOR PUSH: %s %s\",url, username_from_url)\n\/\/\tret, cred := git.NewCredUserpassPlaintext(\"placeholder\", \"\") \/\/TODO: remote cred.\n\/\/\n\/\/\tlog.Printf(\"THIS IS THE CRED RESPONS: %s %s\", ret, cred)\n\/\/\treturn git.ErrorCode(ret), &cred\n\/\/}\n\/\/\n\/\/func certificateCheckCallback(cert *git.Certificate, valid bool, hostname string) git.ErrorCode {\n\/\/\tif hostname != \"github.com\" {\n\/\/\t\treturn git.ErrUser\n\/\/\t}\n\/\/\treturn git.ErrOk\n\/\/}\n<|endoftext|>"}
{"text":"<commit_before>package graph\n\nimport (\n\t\"fmt\"\n\t\"geo\"\n\t\"mm\"\n\t\"path\"\n\t\"sort\"\n)\n\ntype OverlayGraphFile struct {\n\t*GraphFile\n\tCluster          []uint16      \/\/ cluster id -> vertex indices\n\tVertexIndices    []int         \/\/ vertex indices -> cluster id\n\tMatrices         [][][]float32 \/\/ transport mode -> metric -> (cluster id, i, j) -> weight\n\tClusterEdgeCount int           \/\/ combined boundary edge count of the clusters \n\tEdgeCounts       []int         \/\/ cluster id -> id of first edge inside the cluster\n}\n\n\/\/ I\/O\n\nfunc computeVertexIndices(g *OverlayGraphFile) {\n\tg.VertexIndices = make([]int, g.VertexCount())\n\tfor i := 0; i < g.ClusterCount(); i++ {\n\t\tfor j := g.Cluster[i]; j < g.Cluster[i+1]; j++ {\n\t\t\tg.VertexIndices[j] = i\n\t\t}\n\t}\n}\n\nfunc computeEdgeCounts(g *OverlayGraphFile) {\n\tg.EdgeCounts = make([]int, g.ClusterCount()+1)\n\tg.EdgeCounts[0] = g.GraphFile.EdgeCount()\n\tfor i := 0; i < g.ClusterCount(); i++ {\n\t\tg.EdgeCounts[i+1] = g.EdgeCounts[i] + g.ClusterSize(i)*g.ClusterSize(i)\n\t}\n}\n\nfunc loadAllMatrices(g *OverlayGraphFile, base string) error {\n\tg.Matrices = make([][][]float32, TransportMax)\n\tfor t := 0; t < int(TransportMax); t++ {\n\t\tg.Matrices[t] = make([][]float32, MetricMax)\n\t\tfor m := 0; m < int(MetricMax); m++ {\n\t\t\tvar matrixFile []float32\n\t\t\tfileName := fmt.Sprintf(\"matrices.trans%d.metric%d.ftf\", t+1, m+1)\n\t\t\terr := mm.Open(path.Join(base, fileName), &matrixFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tg.Matrices[t][m] = matrixFile\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc OpenOverlay(base string, loadMatrices, ignoreErrors bool) (*OverlayGraphFile, error) {\n\toverlayBaseDir := path.Join(base, \"\/overlay\")\n\tg, err := OpenGraphFile(overlayBaseDir, ignoreErrors)\n\tif err != nil && !ignoreErrors {\n\t\treturn nil, err\n\t}\n\n\toverlay := &OverlayGraphFile{GraphFile: g}\n\tfiles := []struct {\n\t\tname string\n\t\tp    interface{}\n\t}{\n\t\t{\"partitions.ftf\", &overlay.Cluster},\n\t}\n\n\tfor _, file := range files {\n\t\terr = mm.Open(path.Join(overlayBaseDir, file.name), file.p)\n\t\tif err != nil && !ignoreErrors {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcomputeVertexIndices(overlay)\n\tcomputeEdgeCounts(overlay)\n\tif loadMatrices {\n\t\terr = loadAllMatrices(overlay, base)\n\t\tif err != nil && !ignoreErrors {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tfor i := 0; i < overlay.ClusterCount(); i++ {\n\t\toverlay.ClusterEdgeCount += overlay.ClusterSize(i) * overlay.ClusterSize(i)\n\t}\n\n\treturn overlay, nil\n}\n\nfunc CloseOverlay(overlay *OverlayGraphFile) error {\n\terr := CloseGraphFile(overlay.GraphFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfiles := []interface{}{\n\t\t&overlay.Cluster,\n\t}\n\n\tfor _, p := range files {\n\t\terr = mm.Close(p)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Graph Interface\n\nfunc (g *OverlayGraphFile) EdgeCount() int {\n\t\/\/ Count edges and matrices...\n\treturn g.GraphFile.EdgeCount() + g.ClusterEdgeCount\n}\n\nfunc (g *OverlayGraphFile) VertexEdges(v Vertex, forward bool, t Transport, buf []Edge) []Edge {\n\t\/\/ Add the cut edges\n\tresult := g.GraphFile.VertexEdges(v, forward, t, buf)\n\t\/\/ Add the precomputed edges.\n\tcluster, indexInCluster := g.VertexCluster(v)\n\tclusterStart := g.EdgeCounts[cluster]\n\tclusterSize := g.ClusterSize(cluster)\n\tif forward {\n\t\t\/\/ out edges\n\t\toutEdgesStart := clusterStart + int(indexInCluster)*clusterSize\n\t\tfor i := 0; i < clusterSize; i++ {\n\t\t\tresult = append(result, Edge(outEdgesStart+i))\n\t\t}\n\t} else {\n\t\t\/\/ in edges\n\t\tfor i := 0; i < clusterSize; i++ {\n\t\t\tresult = append(result, Edge(i*clusterSize+int(indexInCluster)))\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (g *OverlayGraphFile) IsCutEdge(e Edge) bool {\n\treturn int(e) < g.GraphFile.EdgeCount()\n}\n\nfunc (g *OverlayGraphFile) EdgeOpposite(e Edge, v Vertex) Vertex {\n\tif g.IsCutEdge(e) {\n\t\treturn g.GraphFile.EdgeOpposite(e, v)\n\t}\n\t\/\/ binary search for cluster id\n\tcluster := sort.Search(g.ClusterCount(), func(i int) bool { return int(e) < g.EdgeCounts[i+1] })\n\n\te = e - Edge(g.EdgeCounts[cluster])\n\tvCheck := int(e) \/ g.ClusterSize(cluster)\n\tif int(v) != vCheck {\n\t\tpanic(\"index of v is not as expected\")\n\t}\n\tu := int(e) % g.ClusterSize(cluster)\n\treturn Vertex(u)\n}\n\nfunc (g *OverlayGraphFile) EdgeSteps(e Edge, from Vertex) []geo.Coordinate {\n\t\/\/ Return nil unless the edge is a cross partition edge.\n\t\/\/ In this case, defer to the normal Graph interface.\n\tif g.IsCutEdge(e) {\n\t\treturn g.GraphFile.EdgeSteps(e, from)\n\t}\n\treturn nil\n}\n\nfunc (g *OverlayGraphFile) EdgeWeight(e Edge, t Transport, m Metric) float64 {\n\t\/\/ Return the normal weight if e is a cross partition edge,\n\t\/\/ otherwise return the precomputed weight for t and m.\n\tif g.IsCutEdge(e) {\n\t\treturn g.GraphFile.EdgeWeight(e, t, m)\n\t}\n\tedgeIndex := int(e) - g.GraphFile.EdgeCount()\n\treturn float64(g.Matrices[t][m][edgeIndex])\n}\n\n\/\/ Overlay Interface\n\nfunc (g *OverlayGraphFile) ClusterCount() int {\n\treturn len(g.Cluster) - 1\n}\n\n\/\/ actually: boundary vertex count\nfunc (g *OverlayGraphFile) ClusterSize(i int) int {\n\t\/\/ cluster id -> number of vertices\n\treturn int(g.Cluster[i+1] - g.Cluster[i])\n}\n\nfunc (g *OverlayGraphFile) VertexCluster(v Vertex) (int, Vertex) {\n\t\/\/ overlay vertex id -> cluster id, cluster vertex id\n\ti := g.VertexIndices[v]\n\treturn i, v - Vertex(g.Cluster[i])\n}\n\nfunc (g *OverlayGraphFile) ClusterVertex(i int, v Vertex) Vertex {\n\t\/\/ cluster id, cluster vertex id -> overlay vertex id\n\treturn Vertex(g.Cluster[i]) + v\n}\n<commit_msg>added correct handling of in edges in EdgeOpposite<commit_after>package graph\n\nimport (\n\t\"fmt\"\n\t\"geo\"\n\t\"mm\"\n\t\"path\"\n\t\"sort\"\n)\n\ntype OverlayGraphFile struct {\n\t*GraphFile\n\tCluster          []uint16      \/\/ cluster id -> vertex indices\n\tVertexIndices    []int         \/\/ vertex indices -> cluster id\n\tMatrices         [][][]float32 \/\/ transport mode -> metric -> (cluster id, i, j) -> weight\n\tClusterEdgeCount int           \/\/ combined boundary edge count of the clusters \n\tEdgeCounts       []int         \/\/ cluster id -> id of first edge inside the cluster\n}\n\n\/\/ I\/O\n\nfunc computeVertexIndices(g *OverlayGraphFile) {\n\tg.VertexIndices = make([]int, g.VertexCount())\n\tfor i := 0; i < g.ClusterCount(); i++ {\n\t\tfor j := g.Cluster[i]; j < g.Cluster[i+1]; j++ {\n\t\t\tg.VertexIndices[j] = i\n\t\t}\n\t}\n}\n\nfunc computeEdgeCounts(g *OverlayGraphFile) {\n\tg.EdgeCounts = make([]int, g.ClusterCount()+1)\n\tg.EdgeCounts[0] = g.GraphFile.EdgeCount()\n\tfor i := 0; i < g.ClusterCount(); i++ {\n\t\tg.EdgeCounts[i+1] = g.EdgeCounts[i] + g.ClusterSize(i)*g.ClusterSize(i)\n\t}\n}\n\nfunc loadAllMatrices(g *OverlayGraphFile, base string) error {\n\tg.Matrices = make([][][]float32, TransportMax)\n\tfor t := 0; t < int(TransportMax); t++ {\n\t\tg.Matrices[t] = make([][]float32, MetricMax)\n\t\tfor m := 0; m < int(MetricMax); m++ {\n\t\t\tvar matrixFile []float32\n\t\t\tfileName := fmt.Sprintf(\"matrices.trans%d.metric%d.ftf\", t+1, m+1)\n\t\t\terr := mm.Open(path.Join(base, fileName), &matrixFile)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tg.Matrices[t][m] = matrixFile\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc OpenOverlay(base string, loadMatrices, ignoreErrors bool) (*OverlayGraphFile, error) {\n\toverlayBaseDir := path.Join(base, \"\/overlay\")\n\tg, err := OpenGraphFile(overlayBaseDir, ignoreErrors)\n\tif err != nil && !ignoreErrors {\n\t\treturn nil, err\n\t}\n\n\toverlay := &OverlayGraphFile{GraphFile: g}\n\tfiles := []struct {\n\t\tname string\n\t\tp    interface{}\n\t}{\n\t\t{\"partitions.ftf\", &overlay.Cluster},\n\t}\n\n\tfor _, file := range files {\n\t\terr = mm.Open(path.Join(overlayBaseDir, file.name), file.p)\n\t\tif err != nil && !ignoreErrors {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcomputeVertexIndices(overlay)\n\tcomputeEdgeCounts(overlay)\n\tif loadMatrices {\n\t\terr = loadAllMatrices(overlay, base)\n\t\tif err != nil && !ignoreErrors {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tfor i := 0; i < overlay.ClusterCount(); i++ {\n\t\toverlay.ClusterEdgeCount += overlay.ClusterSize(i) * overlay.ClusterSize(i)\n\t}\n\n\treturn overlay, nil\n}\n\nfunc CloseOverlay(overlay *OverlayGraphFile) error {\n\terr := CloseGraphFile(overlay.GraphFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfiles := []interface{}{\n\t\t&overlay.Cluster,\n\t}\n\n\tfor _, p := range files {\n\t\terr = mm.Close(p)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Graph Interface\n\nfunc (g *OverlayGraphFile) EdgeCount() int {\n\t\/\/ Count edges and matrices...\n\treturn g.GraphFile.EdgeCount() + g.ClusterEdgeCount\n}\n\nfunc (g *OverlayGraphFile) VertexEdges(v Vertex, forward bool, t Transport, buf []Edge) []Edge {\n\t\/\/ Add the cut edges\n\tresult := g.GraphFile.VertexEdges(v, forward, t, buf)\n\t\/\/ Add the precomputed edges.\n\tcluster, indexInCluster := g.VertexCluster(v)\n\tclusterStart := g.EdgeCounts[cluster]\n\tclusterSize := g.ClusterSize(cluster)\n\tif forward {\n\t\t\/\/ out edges\n\t\toutEdgesStart := clusterStart + int(indexInCluster)*clusterSize\n\t\tfor i := 0; i < clusterSize; i++ {\n\t\t\tresult = append(result, Edge(outEdgesStart+i))\n\t\t}\n\t} else {\n\t\t\/\/ in edges\n\t\tfor i := 0; i < clusterSize; i++ {\n\t\t\tresult = append(result, Edge(i*clusterSize+int(indexInCluster)))\n\t\t}\n\t}\n\treturn result\n}\n\nfunc (g *OverlayGraphFile) IsCutEdge(e Edge) bool {\n\treturn int(e) < g.GraphFile.EdgeCount()\n}\n\nfunc (g *OverlayGraphFile) EdgeOpposite(e Edge, v Vertex) Vertex {\n\tif g.IsCutEdge(e) {\n\t\treturn g.GraphFile.EdgeOpposite(e, v)\n\t}\n\t\/\/ binary search for cluster id\n\tcluster := sort.Search(g.ClusterCount(), func(i int) bool { return int(e) < g.EdgeCounts[i+1] })\n\tclusterSize := g.ClusterSize(cluster)\n\n\te = e - Edge(g.EdgeCounts[cluster])\n\tvCheck := int(e) \/ clusterSize\n\tif int(v) != vCheck {\n\t\t\/\/ in edge of v\n\t\tif int(e)%clusterSize != int(v) {\n\t\t\tpanic(\"index of v is not as expected\")\n\t\t}\n\t\treturn Vertex(vCheck)\n\t}\n\t\/\/ out edge of v\n\tu := int(e) % clusterSize\n\treturn Vertex(u)\n}\n\nfunc (g *OverlayGraphFile) EdgeSteps(e Edge, from Vertex) []geo.Coordinate {\n\t\/\/ Return nil unless the edge is a cross partition edge.\n\t\/\/ In this case, defer to the normal Graph interface.\n\tif g.IsCutEdge(e) {\n\t\treturn g.GraphFile.EdgeSteps(e, from)\n\t}\n\treturn nil\n}\n\nfunc (g *OverlayGraphFile) EdgeWeight(e Edge, t Transport, m Metric) float64 {\n\t\/\/ Return the normal weight if e is a cross partition edge,\n\t\/\/ otherwise return the precomputed weight for t and m.\n\tif g.IsCutEdge(e) {\n\t\treturn g.GraphFile.EdgeWeight(e, t, m)\n\t}\n\tedgeIndex := int(e) - g.GraphFile.EdgeCount()\n\treturn float64(g.Matrices[t][m][edgeIndex])\n}\n\n\/\/ Overlay Interface\n\nfunc (g *OverlayGraphFile) ClusterCount() int {\n\treturn len(g.Cluster) - 1\n}\n\n\/\/ actually: boundary vertex count\nfunc (g *OverlayGraphFile) ClusterSize(i int) int {\n\t\/\/ cluster id -> number of vertices\n\treturn int(g.Cluster[i+1] - g.Cluster[i])\n}\n\nfunc (g *OverlayGraphFile) VertexCluster(v Vertex) (int, Vertex) {\n\t\/\/ overlay vertex id -> cluster id, cluster vertex id\n\ti := g.VertexIndices[v]\n\treturn i, v - Vertex(g.Cluster[i])\n}\n\nfunc (g *OverlayGraphFile) ClusterVertex(i int, v Vertex) Vertex {\n\t\/\/ cluster id, cluster vertex id -> overlay vertex id\n\treturn Vertex(g.Cluster[i]) + v\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Google. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file or at\n\/\/ https:\/\/developers.google.com\/open-source\/licenses\/bsd\n\n\/\/ Package plugin implements a plugin for protoc-gen-go that generates\n\/\/ RPC stubs for use with the the net\/rpc package.\n\/\/\n\/\/ To register the plugin, import this package as follows:\n\/\/   import _ \"github.com\/bradhe\/go-rpcgen\/plugin\"\npackage plugin\n\nimport (\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/golang\/protobuf\/protoc-gen-go\/generator\"\n)\n\n\/\/ Fail to compile if Plugin doesn't implement the generator.Plugin interface\nvar _ generator.Plugin = &Plugin{}\n\ntype compileGen interface {\n\t\/\/ Output\n\tP(...interface{})\n\tIn()\n\tOut()\n\n\t\/\/ Errors\n\tFail(...string)\n\tError(error, ...string)\n\n\t\/\/ Object lookup\n\tObjectNamed(string) generator.Object\n\tTypeName(generator.Object) string\n}\n\n\/\/ Plugin implements the generator.Plugin interface.\ntype Plugin struct {\n\trpcImports bool\n\twebImports bool\n\tcompileGen\n\n\tstubs []string\n}\n\n\/\/ Name returns the name of the plugin.\nfunc (p *Plugin) Name() string { return \"go-rpcgen\" }\n\n\/\/ Init stores the given generator in the Plugin for use in the\n\/\/ Generate* class of functions.\nfunc (p *Plugin) Init(g *generator.Generator) {\n\tp.compileGen = g\n\n\tp.stubs = []string{\"rpc\", \"web\"}\n\n\tif stubs := os.Getenv(\"GO_STUBS\"); stubs != \"\" {\n\t\tp.stubs = strings.Split(stubs, \",\")\n\t}\n}\n\n\/\/ Generate generates the RPC stubs for all plugin in the given\n\/\/ FileDescriptorProto.\nfunc (p *Plugin) Generate(file *generator.FileDescriptor) {\n\tfor _, svc := range file.Service {\n\t\tp.GenerateCommonStubs(svc)\n\t\tfor _, stub := range p.stubs {\n\t\t\tswitch stub {\n\t\t\tcase \"rpc\":\n\t\t\t\tp.GenerateRPCStubs(svc)\n\t\t\tcase \"web\":\n\t\t\t\tp.GenerateWebStubs(svc)\n\t\t\tdefault:\n\t\t\t\tp.Fail(\"unknown go_stub\", stub)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ GenerateImports adds the required imports to the output file if the Generate\n\/\/ function generated any RPC stubs.\nfunc (p *Plugin) GenerateImports(file *generator.FileDescriptor) {\n\tif p.rpcImports {\n\t\tp.P(`import \"net\"`)\n\t\tp.P(`import \"net\/rpc\"`)\n\t\tp.P(`import \"github.com\/bradhe\/go-rpcgen\/client\"`)\n\t\tp.P(`import \"errors\"`)\n\t}\n\tif p.webImports {\n\t\tp.P(`import \"net\/url\"`)\n\t\tp.P(`import \"net\/http\"`)\n\t\tp.P(`import \"github.com\/bradhe\/go-rpcgen\/webrpc\"`)\n\t}\n}\n\nfunc init() {\n\tgenerator.RegisterPlugin(new(Plugin))\n}\n<commit_msg>Include codec, or course<commit_after>\/\/ Copyright 2013 Google. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file or at\n\/\/ https:\/\/developers.google.com\/open-source\/licenses\/bsd\n\n\/\/ Package plugin implements a plugin for protoc-gen-go that generates\n\/\/ RPC stubs for use with the the net\/rpc package.\n\/\/\n\/\/ To register the plugin, import this package as follows:\n\/\/   import _ \"github.com\/bradhe\/go-rpcgen\/plugin\"\npackage plugin\n\nimport (\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/golang\/protobuf\/protoc-gen-go\/generator\"\n)\n\n\/\/ Fail to compile if Plugin doesn't implement the generator.Plugin interface\nvar _ generator.Plugin = &Plugin{}\n\ntype compileGen interface {\n\t\/\/ Output\n\tP(...interface{})\n\tIn()\n\tOut()\n\n\t\/\/ Errors\n\tFail(...string)\n\tError(error, ...string)\n\n\t\/\/ Object lookup\n\tObjectNamed(string) generator.Object\n\tTypeName(generator.Object) string\n}\n\n\/\/ Plugin implements the generator.Plugin interface.\ntype Plugin struct {\n\trpcImports bool\n\twebImports bool\n\tcompileGen\n\n\tstubs []string\n}\n\n\/\/ Name returns the name of the plugin.\nfunc (p *Plugin) Name() string { return \"go-rpcgen\" }\n\n\/\/ Init stores the given generator in the Plugin for use in the\n\/\/ Generate* class of functions.\nfunc (p *Plugin) Init(g *generator.Generator) {\n\tp.compileGen = g\n\n\tp.stubs = []string{\"rpc\", \"web\"}\n\n\tif stubs := os.Getenv(\"GO_STUBS\"); stubs != \"\" {\n\t\tp.stubs = strings.Split(stubs, \",\")\n\t}\n}\n\n\/\/ Generate generates the RPC stubs for all plugin in the given\n\/\/ FileDescriptorProto.\nfunc (p *Plugin) Generate(file *generator.FileDescriptor) {\n\tfor _, svc := range file.Service {\n\t\tp.GenerateCommonStubs(svc)\n\t\tfor _, stub := range p.stubs {\n\t\t\tswitch stub {\n\t\t\tcase \"rpc\":\n\t\t\t\tp.GenerateRPCStubs(svc)\n\t\t\tcase \"web\":\n\t\t\t\tp.GenerateWebStubs(svc)\n\t\t\tdefault:\n\t\t\t\tp.Fail(\"unknown go_stub\", stub)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ GenerateImports adds the required imports to the output file if the Generate\n\/\/ function generated any RPC stubs.\nfunc (p *Plugin) GenerateImports(file *generator.FileDescriptor) {\n\tif p.rpcImports {\n\t\tp.P(`import \"net\"`)\n\t\tp.P(`import \"net\/rpc\"`)\n\t\tp.P(`import \"github.com\/bradhe\/go-rpcgen\/codec\"`)\n\t\tp.P(`import \"github.com\/bradhe\/go-rpcgen\/client\"`)\n\t}\n\tif p.webImports {\n\t\tp.P(`import \"net\/url\"`)\n\t\tp.P(`import \"net\/http\"`)\n\t\tp.P(`import \"github.com\/bradhe\/go-rpcgen\/webrpc\"`)\n\t}\n}\n\nfunc init() {\n\tgenerator.RegisterPlugin(new(Plugin))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Vanadium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ The following enables go generate to generate the doc.go file.\n\/\/go:generate go run $JIRI_ROOT\/release\/go\/src\/v.io\/x\/lib\/cmdline\/testdata\/gendoc.go . -help\n\npackage main\n\nimport (\n\t\"encoding\/base64\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\n\t\"v.io\/v23\"\n\t\"v.io\/v23\/context\"\n\t\"v.io\/v23\/security\"\n\t\"v.io\/v23\/vom\"\n\t\"v.io\/x\/lib\/cmdline\"\n\tlsecurity \"v.io\/x\/ref\/lib\/security\"\n\t\"v.io\/x\/ref\/lib\/signals\"\n\t\"v.io\/x\/ref\/lib\/v23cmd\"\n\t\"v.io\/x\/ref\/services\/agent\/internal\/ipc\"\n\t\"v.io\/x\/ref\/services\/agent\/internal\/server\"\n\t\"v.io\/x\/ref\/services\/cluster\"\n\n\t_ \"v.io\/x\/ref\/runtime\/factories\/roaming\"\n)\n\nvar (\n\tclusterAgent  string\n\tsocketPath    string\n\tsecretKeyFile string\n\trootBlessings string\n)\n\nfunc main() {\n\tcmdPodAgentD.Flags.StringVar(&clusterAgent, \"agent\", \"\", \"The address of the cluster agent.\")\n\tcmdPodAgentD.Flags.StringVar(&socketPath, \"socket-path\", \"\", \"The path of the unix socket to listen on.\")\n\tcmdPodAgentD.Flags.StringVar(&secretKeyFile, \"secret-key-file\", \"\", \"The name of the file that contains the secret key.\")\n\tcmdPodAgentD.Flags.StringVar(&rootBlessings, \"root-blessings\", \"\", \"A comma-separated list of the root blessings to trust, base64-encoded VOM-encoded.\")\n\n\tcmdline.HideGlobalFlagsExcept()\n\tcmdline.Main(cmdPodAgentD)\n}\n\nvar cmdPodAgentD = &cmdline.Command{\n\tRunner: v23cmd.RunnerFunc(runPodAgentD),\n\tName:   \"pod_agentd\",\n\tShort:  \"Holds the principal of a kubernetes pod\",\n\tLong: `\nCommand pod_agentd runs a security agent daemon, which holds a private key in\nmemory and makes it available to the kubernetes pod in which it is running.\n`,\n}\n\nfunc runPodAgentD(ctx *context.T, env *cmdline.Env, args []string) error {\n\tp, err := lsecurity.NewPrincipal()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ctx, err = v23.WithPrincipal(ctx, p); err != nil {\n\t\treturn err\n\t}\n\tif rootBlessings != \"\" {\n\t\taddRoot(ctx, rootBlessings)\n\t}\n\n\tsecret, err := ioutil.ReadFile(secretKeyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Fetch blessings from cluster agent.\n\tca := cluster.ClusterAgentClient(clusterAgent)\n\tblessings, err := ca.SeekBlessings(ctx, string(secret))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = p.BlessingStore().SetDefault(blessings); err != nil {\n\t\treturn err\n\t}\n\tif _, err = p.BlessingStore().Set(blessings, security.AllPrincipals); err != nil {\n\t\treturn err\n\t}\n\tif err = security.AddToRoots(p, blessings); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Run the server.\n\ti := ipc.NewIPC()\n\tdefer i.Close()\n\tif err = server.ServeAgent(i, lsecurity.NewImmutablePrincipal(p)); err != nil {\n\t\treturn err\n\t}\n\tif _, err := os.Stat(socketPath); err == nil {\n\t\tos.Remove(socketPath)\n\t}\n\tif err = i.Listen(socketPath); err != nil {\n\t\treturn err\n\t}\n\t<-signals.ShutdownOnSignals(ctx)\n\treturn nil\n}\n\nfunc addRoot(ctx *context.T, flagRoots string) {\n\tp := v23.GetPrincipal(ctx)\n\tfor _, b64 := range strings.Split(flagRoots, \",\") {\n\t\t\/\/ We use URLEncoding to be compatible with the principal\n\t\t\/\/ command.\n\t\tvomBlessings, err := base64.URLEncoding.DecodeString(b64)\n\t\tif err != nil {\n\t\t\tctx.Fatalf(\"unable to decode the base64 blessing roots: %v\", err)\n\t\t}\n\t\tvar blessings security.Blessings\n\t\tif err := vom.Decode(vomBlessings, &blessings); err != nil {\n\t\t\tctx.Fatalf(\"unable to decode the vom blessing roots: %v\", err)\n\t\t}\n\t\tif err := security.AddToRoots(p, blessings); err != nil {\n\t\t\tctx.Fatalf(\"unable to add blessing roots: %v\", err)\n\t\t}\n\t}\n}\n<commit_msg>services\/agent\/pod_agentd: Make socket 666<commit_after>\/\/ Copyright 2015 The Vanadium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ The following enables go generate to generate the doc.go file.\n\/\/go:generate go run $JIRI_ROOT\/release\/go\/src\/v.io\/x\/lib\/cmdline\/testdata\/gendoc.go . -help\n\npackage main\n\nimport (\n\t\"encoding\/base64\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\n\t\"v.io\/v23\"\n\t\"v.io\/v23\/context\"\n\t\"v.io\/v23\/security\"\n\t\"v.io\/v23\/vom\"\n\t\"v.io\/x\/lib\/cmdline\"\n\tlsecurity \"v.io\/x\/ref\/lib\/security\"\n\t\"v.io\/x\/ref\/lib\/signals\"\n\t\"v.io\/x\/ref\/lib\/v23cmd\"\n\t\"v.io\/x\/ref\/services\/agent\/internal\/ipc\"\n\t\"v.io\/x\/ref\/services\/agent\/internal\/server\"\n\t\"v.io\/x\/ref\/services\/cluster\"\n\n\t_ \"v.io\/x\/ref\/runtime\/factories\/roaming\"\n)\n\nvar (\n\tclusterAgent  string\n\tsocketPath    string\n\tsecretKeyFile string\n\trootBlessings string\n)\n\nfunc main() {\n\tcmdPodAgentD.Flags.StringVar(&clusterAgent, \"agent\", \"\", \"The address of the cluster agent.\")\n\tcmdPodAgentD.Flags.StringVar(&socketPath, \"socket-path\", \"\", \"The path of the unix socket to listen on.\")\n\tcmdPodAgentD.Flags.StringVar(&secretKeyFile, \"secret-key-file\", \"\", \"The name of the file that contains the secret key.\")\n\tcmdPodAgentD.Flags.StringVar(&rootBlessings, \"root-blessings\", \"\", \"A comma-separated list of the root blessings to trust, base64-encoded VOM-encoded.\")\n\n\tcmdline.HideGlobalFlagsExcept()\n\tcmdline.Main(cmdPodAgentD)\n}\n\nvar cmdPodAgentD = &cmdline.Command{\n\tRunner: v23cmd.RunnerFunc(runPodAgentD),\n\tName:   \"pod_agentd\",\n\tShort:  \"Holds the principal of a kubernetes pod\",\n\tLong: `\nCommand pod_agentd runs a security agent daemon, which holds a private key in\nmemory and makes it available to the kubernetes pod in which it is running.\n`,\n}\n\nfunc runPodAgentD(ctx *context.T, env *cmdline.Env, args []string) error {\n\tp, err := lsecurity.NewPrincipal()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif ctx, err = v23.WithPrincipal(ctx, p); err != nil {\n\t\treturn err\n\t}\n\tif rootBlessings != \"\" {\n\t\taddRoot(ctx, rootBlessings)\n\t}\n\n\tsecret, err := ioutil.ReadFile(secretKeyFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Fetch blessings from cluster agent.\n\tca := cluster.ClusterAgentClient(clusterAgent)\n\tblessings, err := ca.SeekBlessings(ctx, string(secret))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = p.BlessingStore().SetDefault(blessings); err != nil {\n\t\treturn err\n\t}\n\tif _, err = p.BlessingStore().Set(blessings, security.AllPrincipals); err != nil {\n\t\treturn err\n\t}\n\tif err = security.AddToRoots(p, blessings); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Run the server.\n\ti := ipc.NewIPC()\n\tdefer i.Close()\n\tif err = server.ServeAgent(i, lsecurity.NewImmutablePrincipal(p)); err != nil {\n\t\treturn err\n\t}\n\tif _, err := os.Stat(socketPath); err == nil {\n\t\tos.Remove(socketPath)\n\t}\n\tif err = i.Listen(socketPath); err != nil {\n\t\treturn err\n\t}\n\t\/\/ Make the socket available to all users so that the application can\n\t\/\/ run with a non-root UID.\n\t\/\/ The socket's parent directory is mounted only in the containers that\n\t\/\/ should have access to it. So, this doesn't change who has access to\n\t\/\/ the socket.\n\tif err = os.Chmod(socketPath, 0666); err != nil {\n\t\treturn err\n\t}\n\t<-signals.ShutdownOnSignals(ctx)\n\treturn nil\n}\n\nfunc addRoot(ctx *context.T, flagRoots string) {\n\tp := v23.GetPrincipal(ctx)\n\tfor _, b64 := range strings.Split(flagRoots, \",\") {\n\t\t\/\/ We use URLEncoding to be compatible with the principal\n\t\t\/\/ command.\n\t\tvomBlessings, err := base64.URLEncoding.DecodeString(b64)\n\t\tif err != nil {\n\t\t\tctx.Fatalf(\"unable to decode the base64 blessing roots: %v\", err)\n\t\t}\n\t\tvar blessings security.Blessings\n\t\tif err := vom.Decode(vomBlessings, &blessings); err != nil {\n\t\t\tctx.Fatalf(\"unable to decode the vom blessing roots: %v\", err)\n\t\t}\n\t\tif err := security.AddToRoots(p, blessings); err != nil {\n\t\t\tctx.Fatalf(\"unable to add blessing roots: %v\", err)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Andrew Morgan <andrew@amorgan.xyz>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\tlog \"github.com\/sirupsen\/logrus\"\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\ntype AppServiceAPI struct {\n\tMatrix  *Global  `yaml:\"-\"`\n\tDerived *Derived `yaml:\"-\"` \/\/ TODO: Nuke Derived from orbit\n\n\tInternalAPI InternalAPIOptions `yaml:\"internal_api\"`\n\n\tDatabase DatabaseOptions `yaml:\"database\"`\n\n\t\/\/ DisableTLSValidation disables the validation of X.509 TLS certs\n\t\/\/ on appservice endpoints. This is not recommended in production!\n\tDisableTLSValidation bool `yaml:\"disable_tls_validation\"`\n\n\tConfigFiles []string `yaml:\"config_files\"`\n}\n\nfunc (c *AppServiceAPI) Defaults(generate bool) {\n\tc.InternalAPI.Listen = \"http:\/\/localhost:7777\"\n\tc.InternalAPI.Connect = \"http:\/\/localhost:7777\"\n\tc.Database.Defaults(5)\n\tif generate {\n\t\tc.Database.ConnectionString = \"file:appservice.db\"\n\t}\n}\n\nfunc (c *AppServiceAPI) Verify(configErrs *ConfigErrors, isMonolith bool) {\n\tcheckURL(configErrs, \"app_service_api.internal_api.listen\", string(c.InternalAPI.Listen))\n\tcheckURL(configErrs, \"app_service_api.internal_api.bind\", string(c.InternalAPI.Connect))\n\tcheckNotEmpty(configErrs, \"app_service_api.database.connection_string\", string(c.Database.ConnectionString))\n}\n\n\/\/ ApplicationServiceNamespace is the namespace that a specific application\n\/\/ service has management over.\ntype ApplicationServiceNamespace struct {\n\t\/\/ Whether or not the namespace is managed solely by this application service\n\tExclusive bool `yaml:\"exclusive\"`\n\t\/\/ A regex pattern that represents the namespace\n\tRegex string `yaml:\"regex\"`\n\t\/\/ The ID of an existing group that all users of this application service will\n\t\/\/ be added to. This field is only relevant to the `users` namespace.\n\t\/\/ Note that users who are joined to this group through an application service\n\t\/\/ are not to be listed when querying for the group's members, however the\n\t\/\/ group should be listed when querying an application service user's groups.\n\t\/\/ This is to prevent making spamming all users of an application service\n\t\/\/ trivial.\n\tGroupID string `yaml:\"group_id\"`\n\t\/\/ Regex object representing our pattern. Saves having to recompile every time\n\tRegexpObject *regexp.Regexp\n}\n\n\/\/ ApplicationService represents a Matrix application service.\n\/\/ https:\/\/matrix.org\/docs\/spec\/application_service\/unstable.html\ntype ApplicationService struct {\n\t\/\/ User-defined, unique, persistent ID of the application service\n\tID string `yaml:\"id\"`\n\t\/\/ Base URL of the application service\n\tURL string `yaml:\"url\"`\n\t\/\/ Application service token provided in requests to a homeserver\n\tASToken string `yaml:\"as_token\"`\n\t\/\/ Homeserver token provided in requests to an application service\n\tHSToken string `yaml:\"hs_token\"`\n\t\/\/ Localpart of application service user\n\tSenderLocalpart string `yaml:\"sender_localpart\"`\n\t\/\/ Information about an application service's namespaces. Key is either\n\t\/\/ \"users\", \"aliases\" or \"rooms\"\n\tNamespaceMap map[string][]ApplicationServiceNamespace `yaml:\"namespaces\"`\n\t\/\/ Whether rate limiting is applied to each application service user\n\tRateLimited bool `yaml:\"rate_limited\"`\n\t\/\/ Any custom protocols that this application service provides (e.g. IRC)\n\tProtocols []string `yaml:\"protocols\"`\n}\n\n\/\/ IsInterestedInRoomID returns a bool on whether an application service's\n\/\/ namespace includes the given room ID\nfunc (a *ApplicationService) IsInterestedInRoomID(\n\troomID string,\n) bool {\n\tif namespaceSlice, ok := a.NamespaceMap[\"rooms\"]; ok {\n\t\tfor _, namespace := range namespaceSlice {\n\t\t\tif namespace.RegexpObject != nil && namespace.RegexpObject.MatchString(roomID) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ IsInterestedInUserID returns a bool on whether an application service's\n\/\/ namespace includes the given user ID\nfunc (a *ApplicationService) IsInterestedInUserID(\n\tuserID string,\n) bool {\n\tif namespaceSlice, ok := a.NamespaceMap[\"users\"]; ok {\n\t\tfor _, namespace := range namespaceSlice {\n\t\t\tif namespace.RegexpObject.MatchString(userID) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ OwnsNamespaceCoveringUserId returns a bool on whether an application service's\n\/\/ namespace is exclusive and includes the given user ID\nfunc (a *ApplicationService) OwnsNamespaceCoveringUserId(\n\tuserID string,\n) bool {\n\tif namespaceSlice, ok := a.NamespaceMap[\"users\"]; ok {\n\t\tfor _, namespace := range namespaceSlice {\n\t\t\tif namespace.Exclusive && namespace.RegexpObject.MatchString(userID) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ IsInterestedInRoomAlias returns a bool on whether an application service's\n\/\/ namespace includes the given room alias\nfunc (a *ApplicationService) IsInterestedInRoomAlias(\n\troomAlias string,\n) bool {\n\tif namespaceSlice, ok := a.NamespaceMap[\"aliases\"]; ok {\n\t\tfor _, namespace := range namespaceSlice {\n\t\t\tif namespace.RegexpObject.MatchString(roomAlias) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ loadAppServices iterates through all application service config files\n\/\/ and loads their data into the config object for later access.\nfunc loadAppServices(config *AppServiceAPI, derived *Derived) error {\n\tfor _, configPath := range config.ConfigFiles {\n\t\t\/\/ Create a new application service with default options\n\t\tappservice := ApplicationService{\n\t\t\tRateLimited: true,\n\t\t}\n\n\t\t\/\/ Create an absolute path from a potentially relative path\n\t\tabsPath, err := filepath.Abs(configPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Read the application service's config file\n\t\tconfigData, err := ioutil.ReadFile(absPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Load the config data into our struct\n\t\tif err = yaml.UnmarshalStrict(configData, &appservice); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Append the parsed application service to the global config\n\t\tderived.ApplicationServices = append(\n\t\t\tderived.ApplicationServices, appservice,\n\t\t)\n\t}\n\n\t\/\/ Check for any errors in the loaded application services\n\treturn checkErrors(config, derived)\n}\n\n\/\/ setupRegexps will create regex objects for exclusive and non-exclusive\n\/\/ usernames, aliases and rooms of all application services, so that other\n\/\/ methods can quickly check if a particular string matches any of them.\nfunc setupRegexps(asAPI *AppServiceAPI, derived *Derived) (err error) {\n\t\/\/ Combine all exclusive namespaces for later string checking\n\tvar exclusiveUsernameStrings, exclusiveAliasStrings []string\n\n\t\/\/ If an application service's regex is marked as exclusive, add\n\t\/\/ its contents to the overall exlusive regex string. Room regex\n\t\/\/ not necessary as we aren't denying exclusive room ID creation\n\tfor _, appservice := range derived.ApplicationServices {\n\t\t\/\/ The sender_localpart can be considered an exclusive regex for a single user, so let's do that\n\t\t\/\/ to simplify the code\n\t\tvar senderUserIDSlice = []string{fmt.Sprintf(\"@%s:%s\", appservice.SenderLocalpart, asAPI.Matrix.ServerName)}\n\t\tusersSlice, found := appservice.NamespaceMap[\"users\"]\n\t\tif !found {\n\t\t\tusersSlice = []ApplicationServiceNamespace{}\n\t\t\tappservice.NamespaceMap[\"users\"] = usersSlice\n\t\t}\n\t\tappendExclusiveNamespaceRegexs(&senderUserIDSlice, usersSlice)\n\n\t\tfor key, namespaceSlice := range appservice.NamespaceMap {\n\t\t\tswitch key {\n\t\t\tcase \"users\":\n\t\t\t\tappendExclusiveNamespaceRegexs(&exclusiveUsernameStrings, namespaceSlice)\n\t\t\tcase \"aliases\":\n\t\t\t\tappendExclusiveNamespaceRegexs(&exclusiveAliasStrings, namespaceSlice)\n\t\t\t}\n\n\t\t\tif err = compileNamespaceRegexes(namespaceSlice); err != nil {\n\t\t\t\treturn fmt.Errorf(\"invalid regex in appservice %q, namespace %q: %w\", appservice.ID, key, err)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Join the regexes together into one big regex.\n\t\/\/ i.e. \"app1.*\", \"app2.*\" -> \"(app1.*)|(app2.*)\"\n\t\/\/ Later we can check if a username or alias matches any exclusive regex and\n\t\/\/ deny access if it isn't from an application service\n\texclusiveUsernames := strings.Join(exclusiveUsernameStrings, \"|\")\n\texclusiveAliases := strings.Join(exclusiveAliasStrings, \"|\")\n\n\t\/\/ If there are no exclusive regexes, compile string so that it will not match\n\t\/\/ any valid usernames\/aliases\/roomIDs\n\tif exclusiveUsernames == \"\" {\n\t\texclusiveUsernames = \"^$\"\n\t}\n\tif exclusiveAliases == \"\" {\n\t\texclusiveAliases = \"^$\"\n\t}\n\n\t\/\/ Store compiled Regex\n\tif derived.ExclusiveApplicationServicesUsernameRegexp, err = regexp.Compile(exclusiveUsernames); err != nil {\n\t\treturn err\n\t}\n\tif derived.ExclusiveApplicationServicesAliasRegexp, err = regexp.Compile(exclusiveAliases); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ appendExclusiveNamespaceRegexs takes a slice of strings and a slice of\n\/\/ namespaces and will append the regexes of only the exclusive namespaces\n\/\/ into the string slice\nfunc appendExclusiveNamespaceRegexs(\n\texclusiveStrings *[]string, namespaces []ApplicationServiceNamespace,\n) {\n\tfor _, namespace := range namespaces {\n\t\tif namespace.Exclusive {\n\t\t\t\/\/ We append parenthesis to later separate each regex when we compile\n\t\t\t\/\/ i.e. \"app1.*\", \"app2.*\" -> \"(app1.*)|(app2.*)\"\n\t\t\t*exclusiveStrings = append(*exclusiveStrings, \"(\"+namespace.Regex+\")\")\n\t\t}\n\t}\n}\n\n\/\/ compileNamespaceRegexes turns strings into regex objects and complains\n\/\/ if some of there are bad\nfunc compileNamespaceRegexes(namespaces []ApplicationServiceNamespace) (err error) {\n\tfor index, namespace := range namespaces {\n\t\t\/\/ Compile this regex into a Regexp object for later use\n\t\tr, err := regexp.Compile(namespace.Regex)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"regex at namespace %d: %w\", index, err)\n\t\t}\n\n\t\tnamespaces[index].RegexpObject = r\n\t}\n\n\treturn nil\n}\n\n\/\/ checkErrors checks for any configuration errors amongst the loaded\n\/\/ application services according to the application service spec.\nfunc checkErrors(config *AppServiceAPI, derived *Derived) (err error) {\n\tvar idMap = make(map[string]bool)\n\tvar tokenMap = make(map[string]bool)\n\n\t\/\/ Compile regexp object for checking groupIDs\n\tgroupIDRegexp := regexp.MustCompile(`\\+.*:.*`)\n\n\t\/\/ Check each application service for any config errors\n\tfor _, appservice := range derived.ApplicationServices {\n\t\t\/\/ Namespace-related checks\n\t\tfor key, namespaceSlice := range appservice.NamespaceMap {\n\t\t\tfor _, namespace := range namespaceSlice {\n\t\t\t\tif err := validateNamespace(&appservice, key, &namespace, groupIDRegexp); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Check if the url has trailing \/'s. If so, remove them\n\t\tappservice.URL = strings.TrimRight(appservice.URL, \"\/\")\n\n\t\t\/\/ Check if we've already seen this ID. No two application services\n\t\t\/\/ can have the same ID or token.\n\t\tif idMap[appservice.ID] {\n\t\t\treturn ConfigErrors([]string{fmt.Sprintf(\n\t\t\t\t\"Application service ID %s must be unique\", appservice.ID,\n\t\t\t)})\n\t\t}\n\t\t\/\/ Check if we've already seen this token\n\t\tif tokenMap[appservice.ASToken] {\n\t\t\treturn ConfigErrors([]string{fmt.Sprintf(\n\t\t\t\t\"Application service Token %s must be unique\", appservice.ASToken,\n\t\t\t)})\n\t\t}\n\n\t\t\/\/ Add the id\/token to their respective maps if we haven't already\n\t\t\/\/ seen them.\n\t\tidMap[appservice.ID] = true\n\t\ttokenMap[appservice.ASToken] = true\n\n\t\t\/\/ TODO: Remove once rate_limited is implemented\n\t\tif appservice.RateLimited {\n\t\t\tlog.Warn(\"WARNING: Application service option rate_limited is currently unimplemented\")\n\t\t}\n\t\t\/\/ TODO: Remove once protocols is implemented\n\t\tif len(appservice.Protocols) > 0 {\n\t\t\tlog.Warn(\"WARNING: Application service option protocols is currently unimplemented\")\n\t\t}\n\t}\n\n\treturn setupRegexps(config, derived)\n}\n\n\/\/ validateNamespace returns nil or an error based on whether a given\n\/\/ application service namespace is valid. A namespace is valid if it has the\n\/\/ required fields, and its regex is correct.\nfunc validateNamespace(\n\tappservice *ApplicationService,\n\tkey string,\n\tnamespace *ApplicationServiceNamespace,\n\tgroupIDRegexp *regexp.Regexp,\n) error {\n\t\/\/ Check that namespace(s) are valid regex\n\tif !IsValidRegex(namespace.Regex) {\n\t\treturn ConfigErrors([]string{fmt.Sprintf(\n\t\t\t\"Invalid regex string for Application Service %s\", appservice.ID,\n\t\t)})\n\t}\n\n\t\/\/ Check if GroupID for the users namespace is in the correct format\n\tif key == \"users\" && namespace.GroupID != \"\" {\n\t\t\/\/ TODO: Remove once group_id is implemented\n\t\tlog.Warn(\"WARNING: Application service option group_id is currently unimplemented\")\n\n\t\tcorrectFormat := groupIDRegexp.MatchString(namespace.GroupID)\n\t\tif !correctFormat {\n\t\t\treturn ConfigErrors([]string{fmt.Sprintf(\n\t\t\t\t\"Invalid user group_id field for application service %s.\",\n\t\t\t\tappservice.ID,\n\t\t\t)})\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ IsValidRegex returns true or false based on whether the\n\/\/ given string is valid regex or not\nfunc IsValidRegex(regexString string) bool {\n\t_, err := regexp.Compile(regexString)\n\n\treturn err == nil\n}\n<commit_msg>fixup treat the sender_localpart as an exclusive namespace of one user (#2255)<commit_after>\/\/ Copyright 2017 Andrew Morgan <andrew@amorgan.xyz>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\tlog \"github.com\/sirupsen\/logrus\"\n\tyaml \"gopkg.in\/yaml.v2\"\n)\n\ntype AppServiceAPI struct {\n\tMatrix  *Global  `yaml:\"-\"`\n\tDerived *Derived `yaml:\"-\"` \/\/ TODO: Nuke Derived from orbit\n\n\tInternalAPI InternalAPIOptions `yaml:\"internal_api\"`\n\n\tDatabase DatabaseOptions `yaml:\"database\"`\n\n\t\/\/ DisableTLSValidation disables the validation of X.509 TLS certs\n\t\/\/ on appservice endpoints. This is not recommended in production!\n\tDisableTLSValidation bool `yaml:\"disable_tls_validation\"`\n\n\tConfigFiles []string `yaml:\"config_files\"`\n}\n\nfunc (c *AppServiceAPI) Defaults(generate bool) {\n\tc.InternalAPI.Listen = \"http:\/\/localhost:7777\"\n\tc.InternalAPI.Connect = \"http:\/\/localhost:7777\"\n\tc.Database.Defaults(5)\n\tif generate {\n\t\tc.Database.ConnectionString = \"file:appservice.db\"\n\t}\n}\n\nfunc (c *AppServiceAPI) Verify(configErrs *ConfigErrors, isMonolith bool) {\n\tcheckURL(configErrs, \"app_service_api.internal_api.listen\", string(c.InternalAPI.Listen))\n\tcheckURL(configErrs, \"app_service_api.internal_api.bind\", string(c.InternalAPI.Connect))\n\tcheckNotEmpty(configErrs, \"app_service_api.database.connection_string\", string(c.Database.ConnectionString))\n}\n\n\/\/ ApplicationServiceNamespace is the namespace that a specific application\n\/\/ service has management over.\ntype ApplicationServiceNamespace struct {\n\t\/\/ Whether or not the namespace is managed solely by this application service\n\tExclusive bool `yaml:\"exclusive\"`\n\t\/\/ A regex pattern that represents the namespace\n\tRegex string `yaml:\"regex\"`\n\t\/\/ The ID of an existing group that all users of this application service will\n\t\/\/ be added to. This field is only relevant to the `users` namespace.\n\t\/\/ Note that users who are joined to this group through an application service\n\t\/\/ are not to be listed when querying for the group's members, however the\n\t\/\/ group should be listed when querying an application service user's groups.\n\t\/\/ This is to prevent making spamming all users of an application service\n\t\/\/ trivial.\n\tGroupID string `yaml:\"group_id\"`\n\t\/\/ Regex object representing our pattern. Saves having to recompile every time\n\tRegexpObject *regexp.Regexp\n}\n\n\/\/ ApplicationService represents a Matrix application service.\n\/\/ https:\/\/matrix.org\/docs\/spec\/application_service\/unstable.html\ntype ApplicationService struct {\n\t\/\/ User-defined, unique, persistent ID of the application service\n\tID string `yaml:\"id\"`\n\t\/\/ Base URL of the application service\n\tURL string `yaml:\"url\"`\n\t\/\/ Application service token provided in requests to a homeserver\n\tASToken string `yaml:\"as_token\"`\n\t\/\/ Homeserver token provided in requests to an application service\n\tHSToken string `yaml:\"hs_token\"`\n\t\/\/ Localpart of application service user\n\tSenderLocalpart string `yaml:\"sender_localpart\"`\n\t\/\/ Information about an application service's namespaces. Key is either\n\t\/\/ \"users\", \"aliases\" or \"rooms\"\n\tNamespaceMap map[string][]ApplicationServiceNamespace `yaml:\"namespaces\"`\n\t\/\/ Whether rate limiting is applied to each application service user\n\tRateLimited bool `yaml:\"rate_limited\"`\n\t\/\/ Any custom protocols that this application service provides (e.g. IRC)\n\tProtocols []string `yaml:\"protocols\"`\n}\n\n\/\/ IsInterestedInRoomID returns a bool on whether an application service's\n\/\/ namespace includes the given room ID\nfunc (a *ApplicationService) IsInterestedInRoomID(\n\troomID string,\n) bool {\n\tif namespaceSlice, ok := a.NamespaceMap[\"rooms\"]; ok {\n\t\tfor _, namespace := range namespaceSlice {\n\t\t\tif namespace.RegexpObject != nil && namespace.RegexpObject.MatchString(roomID) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ IsInterestedInUserID returns a bool on whether an application service's\n\/\/ namespace includes the given user ID\nfunc (a *ApplicationService) IsInterestedInUserID(\n\tuserID string,\n) bool {\n\tif namespaceSlice, ok := a.NamespaceMap[\"users\"]; ok {\n\t\tfor _, namespace := range namespaceSlice {\n\t\t\tif namespace.RegexpObject.MatchString(userID) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ OwnsNamespaceCoveringUserId returns a bool on whether an application service's\n\/\/ namespace is exclusive and includes the given user ID\nfunc (a *ApplicationService) OwnsNamespaceCoveringUserId(\n\tuserID string,\n) bool {\n\tif namespaceSlice, ok := a.NamespaceMap[\"users\"]; ok {\n\t\tfor _, namespace := range namespaceSlice {\n\t\t\tif namespace.Exclusive && namespace.RegexpObject.MatchString(userID) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ IsInterestedInRoomAlias returns a bool on whether an application service's\n\/\/ namespace includes the given room alias\nfunc (a *ApplicationService) IsInterestedInRoomAlias(\n\troomAlias string,\n) bool {\n\tif namespaceSlice, ok := a.NamespaceMap[\"aliases\"]; ok {\n\t\tfor _, namespace := range namespaceSlice {\n\t\t\tif namespace.RegexpObject.MatchString(roomAlias) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ loadAppServices iterates through all application service config files\n\/\/ and loads their data into the config object for later access.\nfunc loadAppServices(config *AppServiceAPI, derived *Derived) error {\n\tfor _, configPath := range config.ConfigFiles {\n\t\t\/\/ Create a new application service with default options\n\t\tappservice := ApplicationService{\n\t\t\tRateLimited: true,\n\t\t}\n\n\t\t\/\/ Create an absolute path from a potentially relative path\n\t\tabsPath, err := filepath.Abs(configPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Read the application service's config file\n\t\tconfigData, err := ioutil.ReadFile(absPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Load the config data into our struct\n\t\tif err = yaml.UnmarshalStrict(configData, &appservice); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Append the parsed application service to the global config\n\t\tderived.ApplicationServices = append(\n\t\t\tderived.ApplicationServices, appservice,\n\t\t)\n\t}\n\n\t\/\/ Check for any errors in the loaded application services\n\treturn checkErrors(config, derived)\n}\n\n\/\/ setupRegexps will create regex objects for exclusive and non-exclusive\n\/\/ usernames, aliases and rooms of all application services, so that other\n\/\/ methods can quickly check if a particular string matches any of them.\nfunc setupRegexps(asAPI *AppServiceAPI, derived *Derived) (err error) {\n\t\/\/ Combine all exclusive namespaces for later string checking\n\tvar exclusiveUsernameStrings, exclusiveAliasStrings []string\n\n\t\/\/ If an application service's regex is marked as exclusive, add\n\t\/\/ its contents to the overall exlusive regex string. Room regex\n\t\/\/ not necessary as we aren't denying exclusive room ID creation\n\tfor _, appservice := range derived.ApplicationServices {\n\t\t\/\/ The sender_localpart can be considered an exclusive regex for a single user, so let's do that\n\t\t\/\/ to simplify the code\n\t\tusers, found := appservice.NamespaceMap[\"users\"]\n\t\tif !found {\n\t\t\tusers = []ApplicationServiceNamespace{}\n\t\t}\n\t\tappservice.NamespaceMap[\"users\"] = append(users, ApplicationServiceNamespace{\n\t\t\tExclusive: true,\n\t\t\tRegex:     regexp.QuoteMeta(fmt.Sprintf(\"@%s:%s\", appservice.SenderLocalpart, asAPI.Matrix.ServerName)),\n\t\t})\n\n\t\tfor key, namespaceSlice := range appservice.NamespaceMap {\n\t\t\tswitch key {\n\t\t\tcase \"users\":\n\t\t\t\tappendExclusiveNamespaceRegexs(&exclusiveUsernameStrings, namespaceSlice)\n\t\t\tcase \"aliases\":\n\t\t\t\tappendExclusiveNamespaceRegexs(&exclusiveAliasStrings, namespaceSlice)\n\t\t\t}\n\n\t\t\tif err = compileNamespaceRegexes(namespaceSlice); err != nil {\n\t\t\t\treturn fmt.Errorf(\"invalid regex in appservice %q, namespace %q: %w\", appservice.ID, key, err)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Join the regexes together into one big regex.\n\t\/\/ i.e. \"app1.*\", \"app2.*\" -> \"(app1.*)|(app2.*)\"\n\t\/\/ Later we can check if a username or alias matches any exclusive regex and\n\t\/\/ deny access if it isn't from an application service\n\texclusiveUsernames := strings.Join(exclusiveUsernameStrings, \"|\")\n\texclusiveAliases := strings.Join(exclusiveAliasStrings, \"|\")\n\n\t\/\/ If there are no exclusive regexes, compile string so that it will not match\n\t\/\/ any valid usernames\/aliases\/roomIDs\n\tif exclusiveUsernames == \"\" {\n\t\texclusiveUsernames = \"^$\"\n\t}\n\tif exclusiveAliases == \"\" {\n\t\texclusiveAliases = \"^$\"\n\t}\n\n\t\/\/ Store compiled Regex\n\tif derived.ExclusiveApplicationServicesUsernameRegexp, err = regexp.Compile(exclusiveUsernames); err != nil {\n\t\treturn err\n\t}\n\tif derived.ExclusiveApplicationServicesAliasRegexp, err = regexp.Compile(exclusiveAliases); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ appendExclusiveNamespaceRegexs takes a slice of strings and a slice of\n\/\/ namespaces and will append the regexes of only the exclusive namespaces\n\/\/ into the string slice\nfunc appendExclusiveNamespaceRegexs(\n\texclusiveStrings *[]string, namespaces []ApplicationServiceNamespace,\n) {\n\tfor _, namespace := range namespaces {\n\t\tif namespace.Exclusive {\n\t\t\t\/\/ We append parenthesis to later separate each regex when we compile\n\t\t\t\/\/ i.e. \"app1.*\", \"app2.*\" -> \"(app1.*)|(app2.*)\"\n\t\t\t*exclusiveStrings = append(*exclusiveStrings, \"(\"+namespace.Regex+\")\")\n\t\t}\n\t}\n}\n\n\/\/ compileNamespaceRegexes turns strings into regex objects and complains\n\/\/ if some of there are bad\nfunc compileNamespaceRegexes(namespaces []ApplicationServiceNamespace) (err error) {\n\tfor index, namespace := range namespaces {\n\t\t\/\/ Compile this regex into a Regexp object for later use\n\t\tr, err := regexp.Compile(namespace.Regex)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"regex at namespace %d: %w\", index, err)\n\t\t}\n\n\t\tnamespaces[index].RegexpObject = r\n\t}\n\n\treturn nil\n}\n\n\/\/ checkErrors checks for any configuration errors amongst the loaded\n\/\/ application services according to the application service spec.\nfunc checkErrors(config *AppServiceAPI, derived *Derived) (err error) {\n\tvar idMap = make(map[string]bool)\n\tvar tokenMap = make(map[string]bool)\n\n\t\/\/ Compile regexp object for checking groupIDs\n\tgroupIDRegexp := regexp.MustCompile(`\\+.*:.*`)\n\n\t\/\/ Check each application service for any config errors\n\tfor _, appservice := range derived.ApplicationServices {\n\t\t\/\/ Namespace-related checks\n\t\tfor key, namespaceSlice := range appservice.NamespaceMap {\n\t\t\tfor _, namespace := range namespaceSlice {\n\t\t\t\tif err := validateNamespace(&appservice, key, &namespace, groupIDRegexp); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Check if the url has trailing \/'s. If so, remove them\n\t\tappservice.URL = strings.TrimRight(appservice.URL, \"\/\")\n\n\t\t\/\/ Check if we've already seen this ID. No two application services\n\t\t\/\/ can have the same ID or token.\n\t\tif idMap[appservice.ID] {\n\t\t\treturn ConfigErrors([]string{fmt.Sprintf(\n\t\t\t\t\"Application service ID %s must be unique\", appservice.ID,\n\t\t\t)})\n\t\t}\n\t\t\/\/ Check if we've already seen this token\n\t\tif tokenMap[appservice.ASToken] {\n\t\t\treturn ConfigErrors([]string{fmt.Sprintf(\n\t\t\t\t\"Application service Token %s must be unique\", appservice.ASToken,\n\t\t\t)})\n\t\t}\n\n\t\t\/\/ Add the id\/token to their respective maps if we haven't already\n\t\t\/\/ seen them.\n\t\tidMap[appservice.ID] = true\n\t\ttokenMap[appservice.ASToken] = true\n\n\t\t\/\/ TODO: Remove once rate_limited is implemented\n\t\tif appservice.RateLimited {\n\t\t\tlog.Warn(\"WARNING: Application service option rate_limited is currently unimplemented\")\n\t\t}\n\t\t\/\/ TODO: Remove once protocols is implemented\n\t\tif len(appservice.Protocols) > 0 {\n\t\t\tlog.Warn(\"WARNING: Application service option protocols is currently unimplemented\")\n\t\t}\n\t}\n\n\treturn setupRegexps(config, derived)\n}\n\n\/\/ validateNamespace returns nil or an error based on whether a given\n\/\/ application service namespace is valid. A namespace is valid if it has the\n\/\/ required fields, and its regex is correct.\nfunc validateNamespace(\n\tappservice *ApplicationService,\n\tkey string,\n\tnamespace *ApplicationServiceNamespace,\n\tgroupIDRegexp *regexp.Regexp,\n) error {\n\t\/\/ Check that namespace(s) are valid regex\n\tif !IsValidRegex(namespace.Regex) {\n\t\treturn ConfigErrors([]string{fmt.Sprintf(\n\t\t\t\"Invalid regex string for Application Service %s\", appservice.ID,\n\t\t)})\n\t}\n\n\t\/\/ Check if GroupID for the users namespace is in the correct format\n\tif key == \"users\" && namespace.GroupID != \"\" {\n\t\t\/\/ TODO: Remove once group_id is implemented\n\t\tlog.Warn(\"WARNING: Application service option group_id is currently unimplemented\")\n\n\t\tcorrectFormat := groupIDRegexp.MatchString(namespace.GroupID)\n\t\tif !correctFormat {\n\t\t\treturn ConfigErrors([]string{fmt.Sprintf(\n\t\t\t\t\"Invalid user group_id field for application service %s.\",\n\t\t\t\tappservice.ID,\n\t\t\t)})\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ IsValidRegex returns true or false based on whether the\n\/\/ given string is valid regex or not\nfunc IsValidRegex(regexString string) bool {\n\t_, err := regexp.Compile(regexString)\n\n\treturn err == nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 CoreOS, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cli\n\nimport (\n\t\"os\"\n\n\t\"github.com\/coreos\/mantle\/Godeps\/_workspace\/src\/github.com\/coreos\/pkg\/capnslog\"\n\t\"github.com\/coreos\/mantle\/Godeps\/_workspace\/src\/github.com\/spf13\/cobra\"\n\n\t\"github.com\/coreos\/mantle\/system\/exec\"\n\t\"github.com\/coreos\/mantle\/version\"\n)\n\nvar (\n\tversionCmd = &cobra.Command{\n\t\tUse:   \"version\",\n\t\tShort: \"Print the version number and exit.\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmd.Printf(\"mantle\/%s version %s\\n\",\n\t\t\t\tcmd.Root().Name(), version.Version)\n\t\t},\n\t}\n\n\tlogDebug   bool\n\tlogVerbose bool\n\tlogLevel   capnslog.LogLevel = capnslog.NOTICE\n\n\tplog = capnslog.NewPackageLogger(\"github.com\/coreos\/mantle\", \"cli\")\n)\n\n\/\/ Execute sets up common features that all mantle commands should share\n\/\/ and then executes the command. It does not return.\nfunc Execute(main *cobra.Command) {\n\t\/\/ If we were invoked via a multicall entrypoint run it instead.\n\t\/\/ TODO(marineam): should we figure out a way to initialize logging?\n\texec.MaybeExec()\n\n\tmain.AddCommand(versionCmd)\n\n\t\/\/ TODO(marineam): pflags defines the Value interface differently,\n\t\/\/ update capnslog accordingly...\n\t\/\/main.PersistentFlags().Var(&level, \"log-level\",\n\t\/\/\t\"Set global log level. (default is NOTICE)\")\n\tmain.PersistentFlags().BoolVarP(&logVerbose, \"verbose\", \"v\", false,\n\t\t\"Alias for --log-level=INFO\")\n\tmain.PersistentFlags().BoolVarP(&logDebug, \"debug\", \"d\", false,\n\t\t\"Alias for --log-level=DEBUG\")\n\n\tvar preRun = main.PersistentPreRun\n\tmain.PersistentPreRun = func(cmd *cobra.Command, args []string) {\n\t\tstartLogging(cmd)\n\t\tif preRun != nil {\n\t\t\tpreRun(cmd, args)\n\t\t}\n\t}\n\n\tif err := main.Execute(); err != nil {\n\t\tplog.Fatal(err)\n\t}\n\tos.Exit(0)\n}\n\nfunc startLogging(cmd *cobra.Command) {\n\tswitch {\n\tcase logDebug:\n\t\tlogLevel = capnslog.DEBUG\n\tcase logVerbose:\n\t\tlogLevel = capnslog.INFO\n\t}\n\n\tcapnslog.SetFormatter(capnslog.NewStringFormatter(cmd.Out()))\n\tcapnslog.SetGlobalLogLevel(logLevel)\n\tplog.Infof(\"Started logging at level %s\", logLevel)\n}\n<commit_msg>cli: fix golint complaints<commit_after>\/\/ Copyright 2014 CoreOS, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cli\n\nimport (\n\t\"os\"\n\n\t\"github.com\/coreos\/mantle\/Godeps\/_workspace\/src\/github.com\/coreos\/pkg\/capnslog\"\n\t\"github.com\/coreos\/mantle\/Godeps\/_workspace\/src\/github.com\/spf13\/cobra\"\n\n\t\"github.com\/coreos\/mantle\/system\/exec\"\n\t\"github.com\/coreos\/mantle\/version\"\n)\n\nvar (\n\tversionCmd = &cobra.Command{\n\t\tUse:   \"version\",\n\t\tShort: \"Print the version number and exit.\",\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmd.Printf(\"mantle\/%s version %s\\n\",\n\t\t\t\tcmd.Root().Name(), version.Version)\n\t\t},\n\t}\n\n\tlogDebug   bool\n\tlogVerbose bool\n\tlogLevel   = capnslog.NOTICE\n\n\tplog = capnslog.NewPackageLogger(\"github.com\/coreos\/mantle\", \"cli\")\n)\n\n\/\/ Execute sets up common features that all mantle commands should share\n\/\/ and then executes the command. It does not return.\nfunc Execute(main *cobra.Command) {\n\t\/\/ If we were invoked via a multicall entrypoint run it instead.\n\t\/\/ TODO(marineam): should we figure out a way to initialize logging?\n\texec.MaybeExec()\n\n\tmain.AddCommand(versionCmd)\n\n\t\/\/ TODO(marineam): pflags defines the Value interface differently,\n\t\/\/ update capnslog accordingly...\n\t\/\/main.PersistentFlags().Var(&level, \"log-level\",\n\t\/\/\t\"Set global log level. (default is NOTICE)\")\n\tmain.PersistentFlags().BoolVarP(&logVerbose, \"verbose\", \"v\", false,\n\t\t\"Alias for --log-level=INFO\")\n\tmain.PersistentFlags().BoolVarP(&logDebug, \"debug\", \"d\", false,\n\t\t\"Alias for --log-level=DEBUG\")\n\n\tvar preRun = main.PersistentPreRun\n\tmain.PersistentPreRun = func(cmd *cobra.Command, args []string) {\n\t\tstartLogging(cmd)\n\t\tif preRun != nil {\n\t\t\tpreRun(cmd, args)\n\t\t}\n\t}\n\n\tif err := main.Execute(); err != nil {\n\t\tplog.Fatal(err)\n\t}\n\tos.Exit(0)\n}\n\nfunc startLogging(cmd *cobra.Command) {\n\tswitch {\n\tcase logDebug:\n\t\tlogLevel = capnslog.DEBUG\n\tcase logVerbose:\n\t\tlogLevel = capnslog.INFO\n\t}\n\n\tcapnslog.SetFormatter(capnslog.NewStringFormatter(cmd.Out()))\n\tcapnslog.SetGlobalLogLevel(logLevel)\n\tplog.Infof(\"Started logging at level %s\", logLevel)\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"code.google.com\/p\/google-api-go-client\/drive\/v2\"\n\t\"fmt\"\n\t\"github.com\/prasmussen\/gdrive\/gdrive\"\n\t\"github.com\/prasmussen\/gdrive\/util\"\n\t\"io\"\n\t\"mime\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nfunc List(d *gdrive.Drive, query, titleFilter string, maxResults int, sharedStatus bool, noHeader bool) error {\n\tcaller := d.Files.List()\n\n\tif maxResults > 0 {\n\t\tcaller.MaxResults(int64(maxResults))\n\t}\n\n\tif titleFilter != \"\" {\n\t\tq := fmt.Sprintf(\"title contains '%s'\", titleFilter)\n\t\tcaller.Q(q)\n\t}\n\n\tif query != \"\" {\n\t\tcaller.Q(query)\n\t}\n\n\tlist, err := caller.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titems := make([]map[string]string, 0, 0)\n\n\tfor _, f := range list.Items {\n\t\t\/\/ Skip files that dont have a download url (they are not stored on google drive)\n\t\tif f.DownloadUrl == \"\" {\n\t\t\tif f.MimeType != \"application\/vnd.google-apps.folder\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif f.Labels.Trashed {\n\t\t\tcontinue\n\t\t}\n\n\t\titems = append(items, map[string]string{\n\t\t\t\"Id\":      f.Id,\n\t\t\t\"Title\":   util.TruncateString(f.Title, 40),\n\t\t\t\"Size\":    util.FileSizeFormat(f.FileSize),\n\t\t\t\"Created\": util.ISODateToLocal(f.CreatedDate),\n\t\t})\n\t}\n\n\tcolumnOrder := []string{\"Id\", \"Title\", \"Size\", \"Created\"}\n\n\tif sharedStatus {\n\t\taddSharedStatus(d, items)\n\t\tcolumnOrder = append(columnOrder, \"Shared\")\n\t}\n\n\tutil.PrintColumns(items, columnOrder, 3, noHeader)\n\treturn nil\n}\n\n\/\/ Adds the key-value-pair 'Shared: True\/False' to the map\nfunc addSharedStatus(d *gdrive.Drive, items []map[string]string) {\n\t\/\/ Limit to 10 simultaneous requests\n\tactive := make(chan bool, 10)\n\tdone := make(chan bool)\n\n\t\/\/ Closure that performs the check\n\tcheckStatus := func(item map[string]string) {\n\t\t\/\/ Wait for an empty spot in the active queue\n\t\tactive <- true\n\n\t\t\/\/ Perform request\n\t\tshared := isShared(d, item[\"Id\"])\n\t\titem[\"Shared\"] = util.FormatBool(shared)\n\n\t\t\/\/ Decrement the active queue and notify that we are done\n\t\t<-active\n\t\tdone <- true\n\t}\n\n\t\/\/ Go, go, go!\n\tfor _, item := range items {\n\t\tgo checkStatus(item)\n\t}\n\n\t\/\/ Wait for all goroutines to finish\n\tfor i := 0; i < len(items); i++ {\n\t\t<-done\n\t}\n}\n\nfunc Info(d *gdrive.Drive, fileId string) error {\n\tinfo, err := d.Files.Get(fileId).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\tprintInfo(d, info)\n\treturn nil\n}\n\nfunc printInfo(d *gdrive.Drive, f *drive.File) {\n\tfields := map[string]string{\n\t\t\"Id\":          f.Id,\n\t\t\"Title\":       f.Title,\n\t\t\"Description\": f.Description,\n\t\t\"Size\":        util.FileSizeFormat(f.FileSize),\n\t\t\"Created\":     util.ISODateToLocal(f.CreatedDate),\n\t\t\"Modified\":    util.ISODateToLocal(f.ModifiedDate),\n\t\t\"Owner\":       strings.Join(f.OwnerNames, \", \"),\n\t\t\"Md5sum\":      f.Md5Checksum,\n\t\t\"Shared\":      util.FormatBool(isShared(d, f.Id)),\n\t\t\"Parents\":     util.ParentList(f.Parents),\n\t}\n\n\torder := []string{\n\t\t\"Id\",\n\t\t\"Title\",\n\t\t\"Description\",\n\t\t\"Size\",\n\t\t\"Created\",\n\t\t\"Modified\",\n\t\t\"Owner\",\n\t\t\"Md5sum\",\n\t\t\"Shared\",\n\t\t\"Parents\",\n\t}\n\tutil.Print(fields, order)\n}\n\n\/\/ Create folder in drive\nfunc Folder(d *gdrive.Drive, title string, parentId string, share bool) error {\n\tinfo, err := makeFolder(d, title, parentId, share)\n\tif err != nil {\n\t\treturn err\n\t}\n\tprintInfo(d, info)\n\tfmt.Printf(\"Folder '%s' created\\n\", info.Title)\n\treturn nil\n}\n\nfunc makeFolder(d *gdrive.Drive, title string, parentId string, share bool) (*drive.File, error) {\n\t\/\/ File instance\n\tf := &drive.File{Title: title, MimeType: \"application\/vnd.google-apps.folder\"}\n\t\/\/ Set parent (if provided)\n\tif parentId != \"\" {\n\t\tp := &drive.ParentReference{Id: parentId}\n\t\tf.Parents = []*drive.ParentReference{p}\n\t}\n\t\/\/ Create folder\n\tinfo, err := d.Files.Insert(f).Do()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"An error occurred creating the folder: %v\\n\", err)\n\t}\n\t\/\/ Share folder if the share flag was provided\n\tif share {\n\t\tShare(d, info.Id)\n\t}\n\treturn info, err\n}\n\n\/\/ Upload file to drive\nfunc Upload(d *gdrive.Drive, input io.ReadCloser, title string, parentId string, share bool, mimeType string, convert bool) error {\n\n\t\/\/ Use filename or 'untitled' as title if no title is specified\n\tif title == \"\" {\n\t\tif f, ok := input.(*os.File); ok && input != os.Stdin {\n\t\t\tfi, err := f.Stat()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif fi.Mode().IsDir() {\n\t\t\t\t\/\/ then upload the entire directory, calling Upload recursively\n\t\t\t\t\/\/ make dir first\n\t\t\t\tfolder, err := makeFolder(d, filepath.Base(f.Name()), parentId, share)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tcurrDir, err := os.Getwd()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tfiles, err := f.Readdir(0)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t\/\/ need to change dirs to get the files in the dir\n\t\t\t\terr = f.Chdir()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfor _, el := range files {\n\t\t\t\t\tif el.IsDir() {\n\t\t\t\t\t\t\/\/ todo: recursively do this, would need to keep track of parent ids for new directories\n\t\t\t\t\t} else {\n\t\t\t\t\t\tf2, err := os.Open(el.Name())\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tUpload(d, f2, filepath.Base(el.Name()), folder.Id, share, mimeType, convert)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ go back to previous dir\n\t\t\t\terr = os.Chdir(currDir)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t\/\/ normal file, not a directory\n\t\t\ttitle = filepath.Base(f.Name())\n\n\t\t} else {\n\t\t\ttitle = \"untitled\"\n\t\t}\n\t}\n\n\tif mimeType == \"\" {\n\t\tmimeType = mime.TypeByExtension(filepath.Ext(title))\n\t}\n\n\t\/\/ File instance\n\tf := &drive.File{Title: title, MimeType: mimeType}\n\t\/\/ Set parent (if provided)\n\tif parentId != \"\" {\n\t\tp := &drive.ParentReference{Id: parentId}\n\t\tf.Parents = []*drive.ParentReference{p}\n\t}\n\tgetRate := util.MeasureTransferRate()\n\n\tif convert {\n\t\tfmt.Printf(\"Converting to Google Docs format enabled\\n\")\n\t}\n\n\tinfo, err := d.Files.Insert(f).Convert(convert).Media(input).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred uploading the document: %v\\n\", err)\n\t}\n\n\t\/\/ Total bytes transferred\n\tbytes := info.FileSize\n\n\t\/\/ Print information about uploaded file\n\tprintInfo(d, info)\n\tfmt.Printf(\"MIME Type: %s\\n\", mimeType)\n\tfmt.Printf(\"Uploaded '%s' at %s, total %s\\n\", info.Title, getRate(bytes), util.FileSizeFormat(bytes))\n\n\t\/\/ Share file if the share flag was provided\n\tif share {\n\t\terr = Share(d, info.Id)\n\t}\n\treturn err\n}\n\nfunc DownloadLatest(d *gdrive.Drive, stdout bool) error {\n\tlist, err := d.Files.List().Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(list.Items) == 0 {\n\t\treturn fmt.Errorf(\"No files found\")\n\t}\n\n\tlatestId := list.Items[0].Id\n\treturn Download(d, latestId, stdout, true)\n}\n\n\/\/ Download file from drive\nfunc Download(d *gdrive.Drive, fileId string, stdout, deleteAfterDownload bool) error {\n\t\/\/ Get file info\n\tinfo, err := d.Files.Get(fileId).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\tif info.DownloadUrl == \"\" {\n\t\t\/\/ If there is no DownloadUrl, there is no body\n\t\treturn fmt.Errorf(\"An error occurred: File is not downloadable\")\n\t}\n\n\t\/\/ Measure transfer rate\n\tgetRate := util.MeasureTransferRate()\n\n\t\/\/ GET the download url\n\tres, err := d.Client().Get(info.DownloadUrl)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\t\/\/ Close body on function exit\n\tdefer res.Body.Close()\n\n\t\/\/ Write file content to stdout\n\tif stdout {\n\t\tio.Copy(os.Stdout, res.Body)\n\t\treturn nil\n\t}\n\n\t\/\/ Check if file exists\n\tif util.FileExists(info.Title) {\n\t\treturn fmt.Errorf(\"An error occurred: '%s' already exists\\n\", info.Title)\n\t}\n\n\t\/\/ Create a new file\n\toutFile, err := os.Create(info.Title)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\t\/\/ Close file on function exit\n\tdefer outFile.Close()\n\n\t\/\/ Save file to disk\n\tbytes, err := io.Copy(outFile, res.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %s\", err)\n\t}\n\n\tfmt.Printf(\"Downloaded '%s' at %s, total %s\\n\", info.Title, getRate(bytes), util.FileSizeFormat(bytes))\n\n\tif deleteAfterDownload {\n\t\terr = Delete(d, fileId)\n\t}\n\treturn err\n}\n\n\/\/ Delete file with given file id\nfunc Delete(d *gdrive.Drive, fileId string) error {\n\tinfo, err := d.Files.Get(fileId).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\tif err := d.Files.Delete(fileId).Do(); err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\n\t}\n\n\tfmt.Printf(\"Removed file '%s'\\n\", info.Title)\n\treturn nil\n}\n\n\/\/ Make given file id readable by anyone -- auth not required to view\/download file\nfunc Share(d *gdrive.Drive, fileId string) error {\n\tinfo, err := d.Files.Get(fileId).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\tperm := &drive.Permission{\n\t\tValue: \"me\",\n\t\tType:  \"anyone\",\n\t\tRole:  \"reader\",\n\t}\n\n\tif _, err := d.Permissions.Insert(fileId, perm).Do(); err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\tfmt.Printf(\"File '%s' is now readable by everyone @ %s\\n\", info.Title, util.PreviewUrl(fileId))\n\treturn nil\n}\n\n\/\/ Removes the 'anyone' permission -- auth will be required to view\/download file\nfunc Unshare(d *gdrive.Drive, fileId string) error {\n\tinfo, err := d.Files.Get(fileId).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\tif err := d.Permissions.Delete(fileId, \"anyone\").Do(); err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\tfmt.Printf(\"File '%s' is no longer shared to 'anyone'\\n\", info.Title)\n\treturn nil\n}\n\nfunc isShared(d *gdrive.Drive, fileId string) bool {\n\tr, err := d.Permissions.List(fileId).Do()\n\tif err != nil {\n\t\tfmt.Printf(\"An error occurred: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tfor _, perm := range r.Items {\n\t\tif perm.Type == \"anyone\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>Fix ups.<commit_after>package cli\n\nimport (\n\t\"code.google.com\/p\/google-api-go-client\/drive\/v2\"\n\t\"fmt\"\n\t\"github.com\/prasmussen\/gdrive\/gdrive\"\n\t\"github.com\/prasmussen\/gdrive\/util\"\n\t\"io\"\n\t\"mime\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nfunc List(d *gdrive.Drive, query, titleFilter string, maxResults int, sharedStatus bool, noHeader bool) error {\n\tcaller := d.Files.List()\n\n\tif maxResults > 0 {\n\t\tcaller.MaxResults(int64(maxResults))\n\t}\n\n\tif titleFilter != \"\" {\n\t\tq := fmt.Sprintf(\"title contains '%s'\", titleFilter)\n\t\tcaller.Q(q)\n\t}\n\n\tif query != \"\" {\n\t\tcaller.Q(query)\n\t}\n\n\tlist, err := caller.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titems := make([]map[string]string, 0, 0)\n\n\tfor _, f := range list.Items {\n\t\t\/\/ Skip files that dont have a download url (they are not stored on google drive)\n\t\tif f.DownloadUrl == \"\" {\n\t\t\tif f.MimeType != \"application\/vnd.google-apps.folder\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif f.Labels.Trashed {\n\t\t\tcontinue\n\t\t}\n\n\t\titems = append(items, map[string]string{\n\t\t\t\"Id\":      f.Id,\n\t\t\t\"Title\":   util.TruncateString(f.Title, 40),\n\t\t\t\"Size\":    util.FileSizeFormat(f.FileSize),\n\t\t\t\"Created\": util.ISODateToLocal(f.CreatedDate),\n\t\t})\n\t}\n\n\tcolumnOrder := []string{\"Id\", \"Title\", \"Size\", \"Created\"}\n\n\tif sharedStatus {\n\t\taddSharedStatus(d, items)\n\t\tcolumnOrder = append(columnOrder, \"Shared\")\n\t}\n\n\tutil.PrintColumns(items, columnOrder, 3, noHeader)\n\treturn nil\n}\n\n\/\/ Adds the key-value-pair 'Shared: True\/False' to the map\nfunc addSharedStatus(d *gdrive.Drive, items []map[string]string) {\n\t\/\/ Limit to 10 simultaneous requests\n\tactive := make(chan bool, 10)\n\tdone := make(chan bool)\n\n\t\/\/ Closure that performs the check\n\tcheckStatus := func(item map[string]string) {\n\t\t\/\/ Wait for an empty spot in the active queue\n\t\tactive <- true\n\n\t\t\/\/ Perform request\n\t\tshared := isShared(d, item[\"Id\"])\n\t\titem[\"Shared\"] = util.FormatBool(shared)\n\n\t\t\/\/ Decrement the active queue and notify that we are done\n\t\t<-active\n\t\tdone <- true\n\t}\n\n\t\/\/ Go, go, go!\n\tfor _, item := range items {\n\t\tgo checkStatus(item)\n\t}\n\n\t\/\/ Wait for all goroutines to finish\n\tfor i := 0; i < len(items); i++ {\n\t\t<-done\n\t}\n}\n\nfunc Info(d *gdrive.Drive, fileId string) error {\n\tinfo, err := d.Files.Get(fileId).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\tprintInfo(d, info)\n\treturn nil\n}\n\nfunc printInfo(d *gdrive.Drive, f *drive.File) {\n\tfields := map[string]string{\n\t\t\"Id\":          f.Id,\n\t\t\"Title\":       f.Title,\n\t\t\"Description\": f.Description,\n\t\t\"Size\":        util.FileSizeFormat(f.FileSize),\n\t\t\"Created\":     util.ISODateToLocal(f.CreatedDate),\n\t\t\"Modified\":    util.ISODateToLocal(f.ModifiedDate),\n\t\t\"Owner\":       strings.Join(f.OwnerNames, \", \"),\n\t\t\"Md5sum\":      f.Md5Checksum,\n\t\t\"Shared\":      util.FormatBool(isShared(d, f.Id)),\n\t\t\"Parents\":     util.ParentList(f.Parents),\n\t}\n\n\torder := []string{\n\t\t\"Id\",\n\t\t\"Title\",\n\t\t\"Description\",\n\t\t\"Size\",\n\t\t\"Created\",\n\t\t\"Modified\",\n\t\t\"Owner\",\n\t\t\"Md5sum\",\n\t\t\"Shared\",\n\t\t\"Parents\",\n\t}\n\tutil.Print(fields, order)\n}\n\n\/\/ Create folder in drive\nfunc Folder(d *gdrive.Drive, title string, parentId string, share bool) error {\n\tinfo, err := makeFolder(d, title, parentId, share)\n\tif err != nil {\n\t\treturn err\n\t}\n\tprintInfo(d, info)\n\tfmt.Printf(\"Folder '%s' created\\n\", info.Title)\n\treturn nil\n}\n\nfunc makeFolder(d *gdrive.Drive, title string, parentId string, share bool) (*drive.File, error) {\n\t\/\/ File instance\n\tf := &drive.File{Title: title, MimeType: \"application\/vnd.google-apps.folder\"}\n\t\/\/ Set parent (if provided)\n\tif parentId != \"\" {\n\t\tp := &drive.ParentReference{Id: parentId}\n\t\tf.Parents = []*drive.ParentReference{p}\n\t}\n\t\/\/ Create folder\n\tinfo, err := d.Files.Insert(f).Do()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"An error occurred creating the folder: %v\\n\", err)\n\t}\n\t\/\/ Share folder if the share flag was provided\n\tif share {\n\t\tShare(d, info.Id)\n\t}\n\treturn info, err\n}\n\n\/\/ Upload file to drive\nfunc Upload(d *gdrive.Drive, input io.ReadCloser, title string, parentId string, share bool, mimeType string, convert bool) error {\n\n\t\/\/ Use filename or 'untitled' as title if no title is specified\n\tf2, ok := input.(*os.File)\n\tif title == \"\" {\n\t\tif ok && input != os.Stdin {\n\t\t\t\/\/ then find title if it's a file or upload directory if it's a directory (directory can't have a title).\n\t\t\tfi, err := f2.Stat()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif fi.Mode().IsDir() {\n\t\t\t\t\/\/ then upload the entire directory, calling Upload recursively\n\t\t\t\t\/\/ make dir first\n\t\t\t\tfolder, err := makeFolder(d, filepath.Base(f2.Name()), parentId, share)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tcurrDir, err := os.Getwd()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tfiles, err := f2.Readdir(0)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t\/\/ need to change dirs to get the files in the dir\n\t\t\t\terr = f2.Chdir()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfor _, el := range files {\n\t\t\t\t\tif el.IsDir() {\n\t\t\t\t\t\t\/\/ todo: recursively do this, would need to keep track of parent ids for new directories\n\t\t\t\t\t} else {\n\t\t\t\t\t\tf2, err := os.Open(el.Name())\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tUpload(d, f2, filepath.Base(el.Name()), folder.Id, share, mimeType, convert)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/\/ go back to previous dir\n\t\t\t\terr = os.Chdir(currDir)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\t\/\/ normal file, not a directory\n\t\t\ttitle = filepath.Base(f2.Name())\n\n\t\t} else {\n\t\t\ttitle = \"untitled\"\n\t\t}\n\t}\n\n\tif mimeType == \"\" {\n\t\tmimeType = mime.TypeByExtension(filepath.Ext(title))\n\t}\n\n\t\/\/ File instance\n\tf := &drive.File{Title: title, MimeType: mimeType}\n\t\/\/ Set parent (if provided)\n\tif parentId != \"\" {\n\t\tp := &drive.ParentReference{Id: parentId}\n\t\tf.Parents = []*drive.ParentReference{p}\n\t}\n\tgetRate := util.MeasureTransferRate()\n\n\tif convert {\n\t\tfmt.Printf(\"Converting to Google Docs format enabled\\n\")\n\t}\n\n\tinfo, err := d.Files.Insert(f).Convert(convert).Media(input).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred uploading the document: %v\\n\", err)\n\t}\n\n\t\/\/ Total bytes transferred\n\tbytes := info.FileSize\n\n\t\/\/ Print information about uploaded file\n\tprintInfo(d, info)\n\tfmt.Printf(\"MIME Type: %s\\n\", mimeType)\n\tfmt.Printf(\"Uploaded '%s' at %s, total %s\\n\", info.Title, getRate(bytes), util.FileSizeFormat(bytes))\n\n\t\/\/ Share file if the share flag was provided\n\tif share {\n\t\terr = Share(d, info.Id)\n\t}\n\treturn err\n}\n\nfunc DownloadLatest(d *gdrive.Drive, stdout bool) error {\n\tlist, err := d.Files.List().Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(list.Items) == 0 {\n\t\treturn fmt.Errorf(\"No files found\")\n\t}\n\n\tlatestId := list.Items[0].Id\n\treturn Download(d, latestId, stdout, true)\n}\n\n\/\/ Download file from drive\nfunc Download(d *gdrive.Drive, fileId string, stdout, deleteAfterDownload bool) error {\n\t\/\/ Get file info\n\tinfo, err := d.Files.Get(fileId).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\tif info.DownloadUrl == \"\" {\n\t\t\/\/ If there is no DownloadUrl, there is no body\n\t\treturn fmt.Errorf(\"An error occurred: File is not downloadable\")\n\t}\n\n\t\/\/ Measure transfer rate\n\tgetRate := util.MeasureTransferRate()\n\n\t\/\/ GET the download url\n\tres, err := d.Client().Get(info.DownloadUrl)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\t\/\/ Close body on function exit\n\tdefer res.Body.Close()\n\n\t\/\/ Write file content to stdout\n\tif stdout {\n\t\tio.Copy(os.Stdout, res.Body)\n\t\treturn nil\n\t}\n\n\t\/\/ Check if file exists\n\tif util.FileExists(info.Title) {\n\t\treturn fmt.Errorf(\"An error occurred: '%s' already exists\\n\", info.Title)\n\t}\n\n\t\/\/ Create a new file\n\toutFile, err := os.Create(info.Title)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\t\/\/ Close file on function exit\n\tdefer outFile.Close()\n\n\t\/\/ Save file to disk\n\tbytes, err := io.Copy(outFile, res.Body)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %s\", err)\n\t}\n\n\tfmt.Printf(\"Downloaded '%s' at %s, total %s\\n\", info.Title, getRate(bytes), util.FileSizeFormat(bytes))\n\n\tif deleteAfterDownload {\n\t\terr = Delete(d, fileId)\n\t}\n\treturn err\n}\n\n\/\/ Delete file with given file id\nfunc Delete(d *gdrive.Drive, fileId string) error {\n\tinfo, err := d.Files.Get(fileId).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\tif err := d.Files.Delete(fileId).Do(); err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\n\t}\n\n\tfmt.Printf(\"Removed file '%s'\\n\", info.Title)\n\treturn nil\n}\n\n\/\/ Make given file id readable by anyone -- auth not required to view\/download file\nfunc Share(d *gdrive.Drive, fileId string) error {\n\tinfo, err := d.Files.Get(fileId).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\tperm := &drive.Permission{\n\t\tValue: \"me\",\n\t\tType:  \"anyone\",\n\t\tRole:  \"reader\",\n\t}\n\n\tif _, err := d.Permissions.Insert(fileId, perm).Do(); err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\tfmt.Printf(\"File '%s' is now readable by everyone @ %s\\n\", info.Title, util.PreviewUrl(fileId))\n\treturn nil\n}\n\n\/\/ Removes the 'anyone' permission -- auth will be required to view\/download file\nfunc Unshare(d *gdrive.Drive, fileId string) error {\n\tinfo, err := d.Files.Get(fileId).Do()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\tif err := d.Permissions.Delete(fileId, \"anyone\").Do(); err != nil {\n\t\treturn fmt.Errorf(\"An error occurred: %v\\n\", err)\n\t}\n\n\tfmt.Printf(\"File '%s' is no longer shared to 'anyone'\\n\", info.Title)\n\treturn nil\n}\n\nfunc isShared(d *gdrive.Drive, fileId string) bool {\n\tr, err := d.Permissions.List(fileId).Do()\n\tif err != nil {\n\t\tfmt.Printf(\"An error occurred: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tfor _, perm := range r.Items {\n\t\tif perm.Type == \"anyone\" {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/dcbishop\/gim\/globals\"\n\t\"github.com\/docopt\/docopt-go\"\n)\n\nvar usageMessage = `%[1]s\n\nUsage:\n  %[2]s [<file>...]\n  %[2]s -h | --help\n\nOptions:\n  -h --help     Show this screen.\n`\n\n\/\/ Options stores options parsed from the command line\ntype Options struct {\n\tFilesToOpen []string\n\tHelp        bool\n}\n\n\/\/ ParseArgs takes arguments and returns a cli.Options. Will return error if parsing failed.\nfunc ParseArgs(args []string) (Options, error) {\n\toptions := Options{}\n\n\tif len(args) < 2 {\n\t\treturn options, nil\n\t}\n\n\t\/\/ Docopt.go doesn't seem to have a way to stop it spamming the console.\n\tdisableStdout()\n\tdefer restoreStdout()\n\n\tversion := globals.Name() + \" \" + globals.VersionString()\n\n\targuments, err := docopt.Parse(Usage(), args[1:], false, version, false, false)\n\tif err != nil {\n\t\treturn options, err\n\t}\n\n\tif arguments[\"--help\"].(bool) {\n\t\toptions.Help = true\n\t\treturn options, nil\n\t}\n\n\toptions.FilesToOpen = arguments[\"<file>\"].([]string)\n\n\treturn options, nil\n}\n\n\/\/ Usage returns the usage message\nfunc Usage() string {\n\treturn fmt.Sprintf(usageMessage, globals.Name(), globals.Executable())\n}\n\nvar initialStdout = os.Stdout\n\nfunc disableStdout() {\n\t_, w, _ := os.Pipe()\n\tos.Stdout = w\n}\n\nfunc restoreStdout() {\n\tos.Stdout = initialStdout\n}\n<commit_msg>[Refactor]: Extract some functions.<commit_after>package cli\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/dcbishop\/gim\/globals\"\n\t\"github.com\/docopt\/docopt-go\"\n)\n\nvar usageMessage = `%[1]s\n\nUsage:\n  %[2]s [<file>...]\n  %[2]s -h | --help\n\nOptions:\n  -h --help     Show this screen.\n`\n\n\/\/ Options stores options parsed from the command line\ntype Options struct {\n\tFilesToOpen []string\n\tHelp        bool\n}\n\n\/\/ ParseArgs takes arguments and returns a cli.Options. Will return error if parsing failed.\nfunc ParseArgs(args []string) (Options, error) {\n\tif len(args) < 2 {\n\t\treturn Options{}, nil\n\t}\n\n\toptions, err := parseWithDocopt(args[1:])\n\treturn options, err\n}\n\n\/\/ parseWithDocopt takes a slice of args (without the program name) and returns an Options\nfunc parseWithDocopt(args []string) (Options, error) {\n\t\/\/ Docopt.go doesn't seem to have a way to stop it spamming the console.\n\tdisableStdout()\n\tdefer restoreStdout()\n\n\tversion := nameVersion()\n\targuments, err := docopt.Parse(Usage(), args, false, version, false, false)\n\tif err != nil {\n\t\treturn Options{}, err\n\t}\n\n\toptions := docoptArgsToOptions(arguments)\n\n\treturn options, nil\n}\n\n\/\/ Returns the name and version (ie \"Gim 0.1\")\nfunc nameVersion() string {\n\treturn globals.Name() + \" \" + globals.VersionString()\n}\n\n\/\/ Converts the result of docopt.Parse into an Options\nfunc docoptArgsToOptions(arguments map[string]interface{}) Options {\n\toptions := Options{}\n\tif arguments[\"--help\"].(bool) {\n\t\toptions.Help = true\n\t\treturn options\n\t}\n\n\toptions.FilesToOpen = arguments[\"<file>\"].([]string)\n\n\treturn options\n}\n\n\/\/ Usage returns the usage message\nfunc Usage() string {\n\treturn fmt.Sprintf(usageMessage, globals.Name(), globals.Executable())\n}\n\nvar initialStdout = os.Stdout\n\n\/\/ Replaces the stdout with a dummy pipe to stop console output.\nfunc disableStdout() {\n\t_, w, _ := os.Pipe()\n\tos.Stdout = w\n}\n\n\/\/ Restores the stdout to the writer it has at program start.\nfunc restoreStdout() {\n\tos.Stdout = initialStdout\n}\n<|endoftext|>"}
{"text":"<commit_before>package tumblr\n\n\/\/ Defines each subtype of Post (see consts below) and factory methods\n\nimport (\n\t\"encoding\/json\"\n)\n\n\/\/ Post Types\ntype PostType int\n\nconst (\n\tText = iota\n\tQuote\n\tLink\n\tAnswer\n\tVideo\n\tAudio\n\tPhoto\n\tChat\n)\n\n\/\/ Return the PostType of the type described in the JSON\nfunc TypeOfPost(t string) PostType {\n\tswitch t {\n\tcase \"text\":\n\t\treturn Text\n\tcase \"quote\":\n\t\treturn Quote\n\tcase \"link\":\n\t\treturn Link\n\tcase \"answer\":\n\t\treturn Answer\n\tcase \"video\":\n\t\treturn Video\n\tcase \"audio\":\n\t\treturn Audio\n\tcase \"photo\":\n\t\treturn Photo\n\tcase \"chat\":\n\t\treturn Chat\n\t}\n}\n\n\/\/ Stuff in the \"response\":\"posts\" field\ntype Post struct {\n\tBlogName    string\n\tId          int64\n\tPostURL     string\n\tType        string\n\tTimestamp   int64\n\tDate        string\n\tFormat      string\n\tReblogKey   string\n\tTags        []string\n\tBookmarklet bool\n\tMobile      bool\n\tSourceURL   string\n\tSourceTitle string\n\tLiked       bool\n\tState       string \/\/ published, ueued, draft, private\n\tTotalPosts  int64  \/\/ total posts in result set for pagination\n}\n\ntype TextPost struct {\n\tPost\n\tTitle string\n\tBody  string\n}\n\n\/\/ Photo post\ntype PhotoPost struct {\n\tPost\n\tPhotos  []PhotoData\n\tCaption string\n\tWidth   int64\n\tHeight  int64\n}\n\n\/\/ One photo in a PhotoPost\ntype PhotoData struct {\n\tCaption  string \/\/ photosets only\n\tAltSizes []AltSizeData\n}\n\n\/\/ One alternate size of a Photo\ntype AltSizeData struct {\n\tWidth  int\n\tHeight int\n\tURL    string\n}\n\n\/\/ Quote post\ntype QuotePost struct {\n\tPost\n\tText   string\n\tSource string\n}\n\n\/\/ Link post\ntype LinkPost struct {\n\tPost\n\tTitle       string\n\tURL         string\n\tDescription string\n}\n\n\/\/ Chat post\ntype ChatPost struct {\n\tPost\n\tTitle    string\n\tBody     string\n\tDialogue []DialogueData\n}\n\n\/\/ One component of a conversation in a Dialogue in a Chat\ntype DialogueData struct {\n\tName   string\n\tLabel  string\n\tPhrase string\n}\n\n\/\/ Audio post\ntype AudioPost struct {\n\tPost\n\tCaption     string\n\tPlayer      string\n\tPlays       int64\n\tAlbumArt    string\n\tArtist      string\n\tAlbum       string\n\tTrackName   string\n\tTrackNumber int64\n\tYear        int\n}\n\n\/\/ Video post - TODO Handle all the different sources - not documented :(\ntype VideoPost struct {\n\tPost\n\tCaption string\n\tPlayer  []EmbedObjectData\n}\n\n\/\/ One embedded video player in a VideoPost\ntype EmbedObjectData struct {\n\tWidth     int\n\tEmbedCode string\n}\n\n\/\/ Answer post\ntype AnswerPost struct {\n\tPost\n\tAskingName string\n\tAskingURL  string\n\tQuestion   string\n\tAnswer     string\n}\n<commit_msg>Trying this pattern for making new strongly typed posts<commit_after>package tumblr\n\n\/\/ Defines each subtype of Post (see consts below) and factory methods\n\nimport (\n\t\"encoding\/json\"\n)\n\n\/\/ Post Types\ntype PostType int\n\nconst (\n\tText = iota\n\tQuote\n\tLink\n\tAnswer\n\tVideo\n\tAudio\n\tPhoto\n\tChat\n)\n\n\/\/ Return the PostType of the type described in the JSON\nfunc TypeOfPost(t string) PostType {\n\tswitch t {\n\tcase \"text\":\n\t\treturn Text\n\tcase \"quote\":\n\t\treturn Quote\n\tcase \"link\":\n\t\treturn Link\n\tcase \"answer\":\n\t\treturn Answer\n\tcase \"video\":\n\t\treturn Video\n\tcase \"audio\":\n\t\treturn Audio\n\tcase \"photo\":\n\t\treturn Photo\n\tcase \"chat\":\n\t\treturn Chat\n\t}\n}\n\n\/\/ Stuff in the \"response\":\"posts\" field\ntype Post struct {\n\tBlogName    string\n\tId          int64\n\tPostURL     string\n\tType        string\n\tTimestamp   int64\n\tDate        string\n\tFormat      string\n\tReblogKey   string\n\tTags        []string\n\tBookmarklet bool\n\tMobile      bool\n\tSourceURL   string\n\tSourceTitle string\n\tLiked       bool\n\tState       string \/\/ published, ueued, draft, private\n\tTotalPosts  int64  \/\/ total posts in result set for pagination\n}\n\n\/\/ Text post\ntype TextPost struct {\n\tPost\n\tTitle string\n\tBody  string\n}\n\nfunc NewTextPost(r json.RawMessage) (*TextPost, error) {\n\tp := &TextPost{}\n\terr := json.Unmarshal(r, &p)\n\treturn p, err\n}\n\n\/\/ Photo post\ntype PhotoPost struct {\n\tPost\n\tPhotos  []PhotoData\n\tCaption string\n\tWidth   int64\n\tHeight  int64\n}\n\n\/\/ One photo in a PhotoPost\ntype PhotoData struct {\n\tCaption  string \/\/ photosets only\n\tAltSizes []AltSizeData\n}\n\n\/\/ One alternate size of a Photo\ntype AltSizeData struct {\n\tWidth  int\n\tHeight int\n\tURL    string\n}\n\n\/\/ Quote post\ntype QuotePost struct {\n\tPost\n\tText   string\n\tSource string\n}\n\n\/\/ Link post\ntype LinkPost struct {\n\tPost\n\tTitle       string\n\tURL         string\n\tDescription string\n}\n\n\/\/ Chat post\ntype ChatPost struct {\n\tPost\n\tTitle    string\n\tBody     string\n\tDialogue []DialogueData\n}\n\n\/\/ One component of a conversation in a Dialogue in a Chat\ntype DialogueData struct {\n\tName   string\n\tLabel  string\n\tPhrase string\n}\n\n\/\/ Audio post\ntype AudioPost struct {\n\tPost\n\tCaption     string\n\tPlayer      string\n\tPlays       int64\n\tAlbumArt    string\n\tArtist      string\n\tAlbum       string\n\tTrackName   string\n\tTrackNumber int64\n\tYear        int\n}\n\n\/\/ Video post - TODO Handle all the different sources - not documented :(\ntype VideoPost struct {\n\tPost\n\tCaption string\n\tPlayer  []EmbedObjectData\n}\n\n\/\/ One embedded video player in a VideoPost\ntype EmbedObjectData struct {\n\tWidth     int\n\tEmbedCode string\n}\n\n\/\/ Answer post\ntype AnswerPost struct {\n\tPost\n\tAskingName string\n\tAskingURL  string\n\tQuestion   string\n\tAnswer     string\n}\n<|endoftext|>"}
{"text":"<commit_before>package qb\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/suite\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype PostgresTestSuite struct {\n\tsuite.Suite\n\tsession *Session\n}\n\nfunc (suite *PostgresTestSuite) SetupTest() {\n\tbuilder := NewBuilder(\"postgres\")\n\tbuilder.SetEscaping(true)\n\n\tengine, err := NewEngine(\"postgres\", \"user=postgres dbname=qb_test sslmode=disable\")\n\n\tsuite.session = &Session{\n\t\tqueries:  []*Query{},\n\t\tmapper:   NewMapper(builder),\n\t\tmetadata: NewMetaData(engine, builder),\n\t\tbuilder:  builder,\n\t\tmutex:    &sync.Mutex{},\n\t}\n\n\tassert.Nil(suite.T(), err)\n\tassert.NotNil(suite.T(), suite.session)\n}\n\nfunc (suite *PostgresTestSuite) TestPostgres() {\n\ttype User struct {\n\t\tID          string         `qb:\"type:uuid; constraints:primary_key, auto_increment\"`\n\t\tEmail       string         `qb:\"constraints:unique, notnull\"`\n\t\tFullName    string         `qb:\"constraints:notnull\"`\n\t\tBio         sql.NullString `qb:\"type:text; constraints:null\"`\n\t\tOscars      int            `qb:\"constraints:default(0)\"`\n\t\tIgnoreField string         `qb:\"-\"`\n\t}\n\n\ttype Session struct {\n\t\tID             int64     `qb:\"type:bigserial; constraints:primary_key\"`\n\t\tUserID         string    `qb:\"type:uuid; constraints:ref(user.id)\"`\n\t\tAuthToken      string    `qb:\"type:uuid; constraints:notnull, unique; index\"`\n\t\tCreatedAt      time.Time `qb:\"constraints:notnull\"`\n\t\tExpiresAt      time.Time `qb:\"constraints:notnull\"`\n\t\tCompositeIndex `qb:\"index:created_at, expires_at\"`\n\t}\n\n\tvar err error\n\n\tsuite.session.Metadata().Add(User{})\n\tsuite.session.Metadata().Add(Session{})\n\n\terr = suite.session.Metadata().CreateAll()\n\tassert.Nil(suite.T(), err)\n\n\t\/\/ add sample user & session\n\tsuite.session.AddAll(\n\t\t&User{\n\t\t\tID:       \"b6f8bfe3-a830-441a-a097-1777e6bfae95\",\n\t\t\tEmail:    \"jack@nicholson.com\",\n\t\t\tFullName: \"Jack Nicholson\",\n\t\t\tBio:      sql.NullString{String: \"Jack Nicholson, an American actor, producer, screen-writer and director, is a three-time Academy Award winner and twelve-time nominee.\", Valid: true},\n\t\t}, &Session{\n\t\t\tUserID:    \"b6f8bfe3-a830-441a-a097-1777e6bfae95\",\n\t\t\tAuthToken: \"e4968197-6137-47a4-ba79-690d8c552248\",\n\t\t\tCreatedAt: time.Now(),\n\t\t\tExpiresAt: time.Now().Add(24 * time.Hour),\n\t\t},\n\t)\n\n\terr = suite.session.Commit()\n\tassert.Nil(suite.T(), err)\n\n\t\/\/ find user\n\tvar user User\n\n\tsuite.session.Find(&User{ID: \"b6f8bfe3-a830-441a-a097-1777e6bfae95\"}).One(&user)\n\n\tfmt.Printf(\"User: %+v\\n\", user)\n\n\tassert.Equal(suite.T(), user.Email, \"jack@nicholson.com\")\n\tassert.Equal(suite.T(), user.FullName, \"Jack Nicholson\")\n\tassert.Equal(suite.T(), user.Bio.String, \"Jack Nicholson, an American actor, producer, screen-writer and director, is a three-time Academy Award winner and twelve-time nominee.\")\n\n\t\/\/ select using join\n\tsessions := []Session{}\n\terr = suite.session.Select(\"s.user_id\", \"s.id\", \"s.auth_token\", \"s.created_at\", \"s.expires_at\").\n\t\tFrom(\"user u\").\n\t\tInnerJoin(\"session s\", \"u.id = s.user_id\").\n\t\tWhere(\"u.id = ?\", \"b6f8bfe3-a830-441a-a097-1777e6bfae95\").\n\t\tAll(&sessions)\n\n\tassert.Nil(suite.T(), err)\n\tassert.Equal(suite.T(), len(sessions), 1)\n\n\tassert.Equal(suite.T(), sessions[0].ID, int64(1))\n\tassert.Equal(suite.T(), sessions[0].UserID, \"b6f8bfe3-a830-441a-a097-1777e6bfae95\")\n\tassert.Equal(suite.T(), sessions[0].AuthToken, \"e4968197-6137-47a4-ba79-690d8c552248\")\n\n\t\/\/ update user\n\tupdate := suite.session.\n\t\tUpdate(\"user\").\n\t\tSet(map[string]interface{}{\n\t\t\t\"bio\": nil,\n\t\t}).\n\t\tWhere(suite.session.Eq(\"id\", \"b6f8bfe3-a830-441a-a097-1777e6bfae95\")).\n\t\tQuery()\n\n\tsuite.session.AddQuery(update)\n\terr = suite.session.Commit()\n\tassert.Nil(suite.T(), err)\n\n\tsuite.session.Find(&User{ID: \"b6f8bfe3-a830-441a-a097-1777e6bfae95\"}).One(&user)\n\tassert.Equal(suite.T(), user.Bio, sql.NullString{String: \"\", Valid: false})\n\n\t\/\/ delete session\n\tsuite.session.Delete(&Session{AuthToken: \"99e591f8-1025-41ef-a833-6904a0f89a38\"})\n\terr = suite.session.Commit()\n\tassert.Nil(suite.T(), err)\n\n\t\/\/ drop tables\n\tassert.Nil(suite.T(), suite.session.Metadata().DropAll())\n}\n\nfunc TestPostgresTestSuite(t *testing.T) {\n\tsuite.Run(t, new(PostgresTestSuite))\n}\n<commit_msg>improve test coverage to 100%<commit_after>package qb\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/suite\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n)\n\ntype PostgresTestSuite struct {\n\tsuite.Suite\n\tsession *Session\n}\n\nfunc (suite *PostgresTestSuite) SetupTest() {\n\tbuilder := NewBuilder(\"postgres\")\n\tbuilder.SetEscaping(true)\n\n\tengine, err := NewEngine(\"postgres\", \"user=postgres dbname=qb_test sslmode=disable\")\n\n\tsuite.session = &Session{\n\t\tqueries:  []*Query{},\n\t\tmapper:   NewMapper(builder),\n\t\tmetadata: NewMetaData(engine, builder),\n\t\tbuilder:  builder,\n\t\tmutex:    &sync.Mutex{},\n\t}\n\n\tassert.Nil(suite.T(), err)\n\tassert.NotNil(suite.T(), suite.session)\n}\n\nfunc (suite *PostgresTestSuite) TestPostgres() {\n\ttype User struct {\n\t\tID          string         `qb:\"type:uuid; constraints:primary_key, auto_increment\"`\n\t\tEmail       string         `qb:\"constraints:unique, notnull\"`\n\t\tFullName    string         `qb:\"constraints:notnull\"`\n\t\tBio         sql.NullString `qb:\"type:text; constraints:null\"`\n\t\tOscars      int            `qb:\"constraints:default(0)\"`\n\t\tIgnoreField string         `qb:\"-\"`\n\t}\n\n\ttype Session struct {\n\t\tID             int64     `qb:\"type:bigserial; constraints:primary_key\"`\n\t\tUserID         string    `qb:\"type:uuid; constraints:ref(user.id)\"`\n\t\tAuthToken      string    `qb:\"type:uuid; constraints:notnull, unique; index\"`\n\t\tCreatedAt      time.Time `qb:\"constraints:notnull\"`\n\t\tExpiresAt      time.Time `qb:\"constraints:notnull\"`\n\t\tCompositeIndex `qb:\"index:created_at, expires_at\"`\n\t}\n\n\tvar err error\n\n\tsuite.session.Metadata().Add(User{})\n\tsuite.session.Metadata().Add(Session{})\n\n\terr = suite.session.Metadata().CreateAll()\n\tassert.Nil(suite.T(), err)\n\n\t\/\/ add sample user & session\n\tsuite.session.AddAll(\n\t\t&User{\n\t\t\tID:       \"b6f8bfe3-a830-441a-a097-1777e6bfae95\",\n\t\t\tEmail:    \"jack@nicholson.com\",\n\t\t\tFullName: \"Jack Nicholson\",\n\t\t\tBio:      sql.NullString{String: \"Jack Nicholson, an American actor, producer, screen-writer and director, is a three-time Academy Award winner and twelve-time nominee.\", Valid: true},\n\t\t}, &Session{\n\t\t\tUserID:    \"b6f8bfe3-a830-441a-a097-1777e6bfae95\",\n\t\t\tAuthToken: \"e4968197-6137-47a4-ba79-690d8c552248\",\n\t\t\tCreatedAt: time.Now(),\n\t\t\tExpiresAt: time.Now().Add(24 * time.Hour),\n\t\t},\n\t)\n\n\terr = suite.session.Commit()\n\tassert.Nil(suite.T(), err)\n\n\tquery := suite.session.Builder().Insert(\"user\").Values(map[string]interface{}{\n\t\t\"id\":       \"b6f8bfe3-a830-441a-a097-1777e6bfae95\",\n\t\t\"email\":    \"jack@nicholson.com\",\n\t\t\"full_name\": \"Jack Nicholson\",\n\t\t\"bio\":      sql.NullString{},\n\t}).Query()\n\n\t_, err = suite.session.Engine().Exec(query)\n\tassert.NotNil(suite.T(), err)\n\tfmt.Println(\"Duplicate error; \", err)\n\n\tquery = suite.session.Builder().Insert(\"user\").Values(map[string]interface{}{\n\t\t\"id\":       \"cf28d117-a12d-4b75-acd8-73a7d3cbb15f\",\n\t\t\"email\":    \"jack@nicholson2.com\",\n\t\t\"full_name\": \"Jack Nicholson\",\n\t\t\"bio\":      sql.NullString{},\n\t}).Query()\n\n\t_, err = suite.session.Engine().Exec(query)\n\tassert.Nil(suite.T(), err)\n\n\terr = suite.session.Rollback()\n\tassert.NotNil(suite.T(), err)\n\n\t\/\/ find user using QueryRow()\n\tquery = suite.session.Find(&User{ID: \"cf28d117-a12d-4b75-acd8-73a7d3cbb15f\"}).Query()\n\trow := suite.session.Engine().QueryRow(query)\n\tassert.NotNil(suite.T(), row)\n\n\t\/\/ find user using Query()\n\tquery = suite.session.Find(&User{ID: \"cf28d117-a12d-4b75-acd8-73a7d3cbb15f\"}).Query()\n\trows, err := suite.session.Engine().Query(query)\n\tassert.Nil(suite.T(), err)\n\trowLength := 0\n\tfor rows.Next() {\n\t\trowLength++\n\t}\n\tassert.Equal(suite.T(), rowLength, 1)\n\n\t\/\/ find user using session api's Find()\n\tvar user User\n\n\tsuite.session.Find(&User{ID: \"b6f8bfe3-a830-441a-a097-1777e6bfae95\"}).One(&user)\n\n\tfmt.Printf(\"User: %+v\\n\", user)\n\n\tassert.Equal(suite.T(), user.Email, \"jack@nicholson.com\")\n\tassert.Equal(suite.T(), user.FullName, \"Jack Nicholson\")\n\tassert.Equal(suite.T(), user.Bio.String, \"Jack Nicholson, an American actor, producer, screen-writer and director, is a three-time Academy Award winner and twelve-time nominee.\")\n\n\t\/\/ select using join\n\tsessions := []Session{}\n\terr = suite.session.Select(\"s.user_id\", \"s.id\", \"s.auth_token\", \"s.created_at\", \"s.expires_at\").\n\t\tFrom(\"user u\").\n\t\tInnerJoin(\"session s\", \"u.id = s.user_id\").\n\t\tWhere(\"u.id = ?\", \"b6f8bfe3-a830-441a-a097-1777e6bfae95\").\n\t\tAll(&sessions)\n\n\tassert.Nil(suite.T(), err)\n\tassert.Equal(suite.T(), len(sessions), 1)\n\n\tassert.Equal(suite.T(), sessions[0].ID, int64(1))\n\tassert.Equal(suite.T(), sessions[0].UserID, \"b6f8bfe3-a830-441a-a097-1777e6bfae95\")\n\tassert.Equal(suite.T(), sessions[0].AuthToken, \"e4968197-6137-47a4-ba79-690d8c552248\")\n\n\t\/\/ update user\n\tupdate := suite.session.\n\t\tUpdate(\"user\").\n\t\tSet(map[string]interface{}{\n\t\t\t\"bio\": nil,\n\t\t}).\n\t\tWhere(suite.session.Eq(\"id\", \"b6f8bfe3-a830-441a-a097-1777e6bfae95\")).\n\t\tQuery()\n\n\tsuite.session.AddQuery(update)\n\terr = suite.session.Commit()\n\tassert.Nil(suite.T(), err)\n\n\tsuite.session.Find(&User{ID: \"b6f8bfe3-a830-441a-a097-1777e6bfae95\"}).One(&user)\n\tassert.Equal(suite.T(), user.Bio, sql.NullString{String: \"\", Valid: false})\n\n\t\/\/ delete session\n\tsuite.session.Delete(&Session{AuthToken: \"99e591f8-1025-41ef-a833-6904a0f89a38\"})\n\terr = suite.session.Commit()\n\tassert.Nil(suite.T(), err)\n\n\t\/\/ drop tables\n\tassert.Nil(suite.T(), suite.session.Metadata().DropAll())\n}\n\nfunc TestPostgresTestSuite(t *testing.T) {\n\tsuite.Run(t, new(PostgresTestSuite))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2020 Karim Radhouani <medkarimrdi@gmail.com>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/google\/gnxi\/utils\/xpath\"\n\t\"github.com\/openconfig\/gnmi\/proto\/gnmi\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n\t\"google.golang.org\/grpc\/metadata\"\n)\n\n\/\/ getCmd represents the get command\nvar getCmd = &cobra.Command{\n\tUse:   \"get\",\n\tShort: \"run gnmi get on targets\",\n\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tvar err error\n\t\taddresses := viper.GetStringSlice(\"address\")\n\t\tif len(addresses) == 0 {\n\t\t\tfmt.Println(\"no grpc server address specified\")\n\t\t\treturn nil\n\t\t}\n\t\tusername := viper.GetString(\"username\")\n\t\tif username == \"\" {\n\t\t\tif username, err = readUsername(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tpassword := viper.GetString(\"password\")\n\t\tif password == \"\" {\n\t\t\tif password, err = readPassword(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treq := &gnmi.GetRequest{\n\t\t\tUseModels: make([]*gnmi.ModelData, 0),\n\t\t\tPath:      make([]*gnmi.Path, 0),\n\t\t}\n\t\tmodel := viper.GetString(\"get-model\")\n\t\tif model != \"\" {\n\t\t\treq.UseModels = append(req.UseModels, &gnmi.ModelData{Name: model})\n\t\t}\n\t\tprefix := viper.GetString(\"get-prefix\")\n\t\tif prefix != \"\" {\n\t\t\tgnmiPrefix, err := xpath.ToGNMIPath(prefix)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"prefix parse error: %v\", err)\n\t\t\t}\n\t\t\treq.Prefix = gnmiPrefix\n\t\t}\n\t\tpaths := viper.GetStringSlice(\"get-path\")\n\t\tfor _, p := range paths {\n\t\t\tlog.Printf(\"parsing path '%s'\\n\", p)\n\t\t\tgnmiPath, err := xpath.ToGNMIPath(p)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"path parse error: %v\", err)\n\t\t\t}\n\t\t\treq.Path = append(req.Path, gnmiPath)\n\t\t}\n\t\tdataType := viper.GetString(\"get-type\")\n\t\tif dataType != \"\" {\n\t\t\tdti, ok := gnmi.GetRequest_DataType_value[dataType]\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"unknown data type %s\", dataType)\n\t\t\t}\n\t\t\treq.Type = gnmi.GetRequest_DataType(dti)\n\t\t}\n\t\tlog.Printf(\"get request: %s\", req)\n\t\twg := new(sync.WaitGroup)\n\t\twg.Add(len(addresses))\n\t\tfor _, addr := range addresses {\n\t\t\tgo func(address string) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tipa, _, err := net.SplitHostPort(address)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif strings.Contains(err.Error(), \"missing port in address\") {\n\t\t\t\t\t\taddress = net.JoinHostPort(ipa, defaultGrpcPort)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Printf(\"error parsing address '%s': %v\", address, err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconn, err := createGrpcConn(address)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"connection to %s failed: %v\", address, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tclient := gnmi.NewGNMIClient(conn)\n\t\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\t\tdefer cancel()\n\t\t\t\tctx = metadata.AppendToOutgoingContext(ctx, \"username\", username, \"password\", password)\n\n\t\t\t\tresponse, err := client.Get(ctx, req)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"error sending get request: %v\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tprintPrefix := fmt.Sprintf(\"[%s] \", address)\n\t\t\t\tfor _, notif := range response.Notification {\n\t\t\t\t\tfmt.Printf(\"%stimestamp: %d\\n\", printPrefix, notif.Timestamp)\n\t\t\t\t\tfmt.Printf(\"%sprefix: %s\\n\", printPrefix, gnmiPathToXPath(notif.Prefix))\n\t\t\t\t\tfmt.Printf(\"%salias: %s\\n\", printPrefix, notif.Alias)\n\t\t\t\t\tfor _, upd := range notif.Update {\n\t\t\t\t\t\tif upd.Val == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvar value interface{}\n\t\t\t\t\t\tvar jsondata []byte\n\t\t\t\t\t\tswitch val := upd.Val.Value.(type) {\n\t\t\t\t\t\tcase *gnmi.TypedValue_AsciiVal:\n\t\t\t\t\t\t\tvalue = val.AsciiVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_BoolVal:\n\t\t\t\t\t\t\tvalue = val.BoolVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_BytesVal:\n\t\t\t\t\t\t\tvalue = val.BytesVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_DecimalVal:\n\t\t\t\t\t\t\tvalue = val.DecimalVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_FloatVal:\n\t\t\t\t\t\t\tvalue = val.FloatVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_IntVal:\n\t\t\t\t\t\t\tvalue = val.IntVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_StringVal:\n\t\t\t\t\t\t\tvalue = val.StringVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_UintVal:\n\t\t\t\t\t\t\tvalue = val.UintVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_JsonIetfVal:\n\t\t\t\t\t\t\tjsondata = val.JsonIetfVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_JsonVal:\n\t\t\t\t\t\t\tjsondata = val.JsonVal\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif jsondata != nil {\n\t\t\t\t\t\t\terr = json.Unmarshal(jsondata, &value)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tlog.Printf(\"error unmarshling jsonVal '%s'\", string(jsondata))\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdata, err := json.MarshalIndent(value, printPrefix, \"  \")\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tlog.Printf(\"error marshling jsonVal '%s'\", value)\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfmt.Printf(\"%s%s: (%T) %s\\n\", printPrefix, gnmiPathToXPath(upd.Path), upd.Val.Value, data)\n\t\t\t\t\t\t} else if value != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"%s%s: (%T) %s\\n\", printPrefix, gnmiPathToXPath(upd.Path), upd.Val.Value, value)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfmt.Println()\n\t\t\t}(addr)\n\t\t}\n\t\twg.Wait()\n\t\treturn nil\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(getCmd)\n\n\tgetCmd.Flags().StringSliceP(\"path\", \"\", []string{\"\/\"}, \"get request paths\")\n\tgetCmd.Flags().StringP(\"prefix\", \"\", \"\", \"get request prefix\")\n\tgetCmd.Flags().StringP(\"model\", \"\", \"\", \"get request model\")\n\tgetCmd.Flags().StringP(\"type\", \"t\", \"ALL\", \"the type of data that is requested from the target. one of: ALL, CONFIG, STATE, OPERATIONAL\")\n\tviper.BindPFlag(\"get-path\", getCmd.Flags().Lookup(\"path\"))\n\tviper.BindPFlag(\"get-prefix\", getCmd.Flags().Lookup(\"prefix\"))\n\tviper.BindPFlag(\"get-model\", getCmd.Flags().Lookup(\"model\"))\n\tviper.BindPFlag(\"get-type\", getCmd.Flags().Lookup(\"type\"))\n}\n<commit_msg>remove extra logging<commit_after>\/\/ Copyright © 2020 Karim Radhouani <medkarimrdi@gmail.com>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/google\/gnxi\/utils\/xpath\"\n\t\"github.com\/openconfig\/gnmi\/proto\/gnmi\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n\t\"google.golang.org\/grpc\/metadata\"\n)\n\n\/\/ getCmd represents the get command\nvar getCmd = &cobra.Command{\n\tUse:   \"get\",\n\tShort: \"run gnmi get on targets\",\n\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tvar err error\n\t\taddresses := viper.GetStringSlice(\"address\")\n\t\tif len(addresses) == 0 {\n\t\t\tfmt.Println(\"no grpc server address specified\")\n\t\t\treturn nil\n\t\t}\n\t\tusername := viper.GetString(\"username\")\n\t\tif username == \"\" {\n\t\t\tif username, err = readUsername(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tpassword := viper.GetString(\"password\")\n\t\tif password == \"\" {\n\t\t\tif password, err = readPassword(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treq := &gnmi.GetRequest{\n\t\t\tUseModels: make([]*gnmi.ModelData, 0),\n\t\t\tPath:      make([]*gnmi.Path, 0),\n\t\t}\n\t\tmodel := viper.GetString(\"get-model\")\n\t\tif model != \"\" {\n\t\t\treq.UseModels = append(req.UseModels, &gnmi.ModelData{Name: model})\n\t\t}\n\t\tprefix := viper.GetString(\"get-prefix\")\n\t\tif prefix != \"\" {\n\t\t\tgnmiPrefix, err := xpath.ToGNMIPath(prefix)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"prefix parse error: %v\", err)\n\t\t\t}\n\t\t\treq.Prefix = gnmiPrefix\n\t\t}\n\t\tpaths := viper.GetStringSlice(\"get-path\")\n\t\tfor _, p := range paths {\n\t\t\tgnmiPath, err := xpath.ToGNMIPath(p)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"path parse error: %v\", err)\n\t\t\t}\n\t\t\treq.Path = append(req.Path, gnmiPath)\n\t\t}\n\t\tdataType := viper.GetString(\"get-type\")\n\t\tif dataType != \"\" {\n\t\t\tdti, ok := gnmi.GetRequest_DataType_value[dataType]\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"unknown data type %s\", dataType)\n\t\t\t}\n\t\t\treq.Type = gnmi.GetRequest_DataType(dti)\n\t\t}\n\t\twg := new(sync.WaitGroup)\n\t\twg.Add(len(addresses))\n\t\tfor _, addr := range addresses {\n\t\t\tgo func(address string) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tipa, _, err := net.SplitHostPort(address)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif strings.Contains(err.Error(), \"missing port in address\") {\n\t\t\t\t\t\taddress = net.JoinHostPort(ipa, defaultGrpcPort)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Printf(\"error parsing address '%s': %v\", address, err)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconn, err := createGrpcConn(address)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"connection to %s failed: %v\", address, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tclient := gnmi.NewGNMIClient(conn)\n\t\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\t\tdefer cancel()\n\t\t\t\tctx = metadata.AppendToOutgoingContext(ctx, \"username\", username, \"password\", password)\n\n\t\t\t\tresponse, err := client.Get(ctx, req)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"error sending get request: %v\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tprintPrefix := fmt.Sprintf(\"[%s] \", address)\n\t\t\t\tfor _, notif := range response.Notification {\n\t\t\t\t\tfmt.Printf(\"%stimestamp: %d\\n\", printPrefix, notif.Timestamp)\n\t\t\t\t\tfmt.Printf(\"%sprefix: %s\\n\", printPrefix, gnmiPathToXPath(notif.Prefix))\n\t\t\t\t\tfmt.Printf(\"%salias: %s\\n\", printPrefix, notif.Alias)\n\t\t\t\t\tfor _, upd := range notif.Update {\n\t\t\t\t\t\tif upd.Val == nil {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvar value interface{}\n\t\t\t\t\t\tvar jsondata []byte\n\t\t\t\t\t\tswitch val := upd.Val.Value.(type) {\n\t\t\t\t\t\tcase *gnmi.TypedValue_AsciiVal:\n\t\t\t\t\t\t\tvalue = val.AsciiVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_BoolVal:\n\t\t\t\t\t\t\tvalue = val.BoolVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_BytesVal:\n\t\t\t\t\t\t\tvalue = val.BytesVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_DecimalVal:\n\t\t\t\t\t\t\tvalue = val.DecimalVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_FloatVal:\n\t\t\t\t\t\t\tvalue = val.FloatVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_IntVal:\n\t\t\t\t\t\t\tvalue = val.IntVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_StringVal:\n\t\t\t\t\t\t\tvalue = val.StringVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_UintVal:\n\t\t\t\t\t\t\tvalue = val.UintVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_JsonIetfVal:\n\t\t\t\t\t\t\tjsondata = val.JsonIetfVal\n\t\t\t\t\t\tcase *gnmi.TypedValue_JsonVal:\n\t\t\t\t\t\t\tjsondata = val.JsonVal\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif jsondata != nil {\n\t\t\t\t\t\t\terr = json.Unmarshal(jsondata, &value)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tlog.Printf(\"error unmarshling jsonVal '%s'\", string(jsondata))\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdata, err := json.MarshalIndent(value, printPrefix, \"  \")\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tlog.Printf(\"error marshling jsonVal '%s'\", value)\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfmt.Printf(\"%s%s: (%T) %s\\n\", printPrefix, gnmiPathToXPath(upd.Path), upd.Val.Value, data)\n\t\t\t\t\t\t} else if value != nil {\n\t\t\t\t\t\t\tfmt.Printf(\"%s%s: (%T) %s\\n\", printPrefix, gnmiPathToXPath(upd.Path), upd.Val.Value, value)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfmt.Println()\n\t\t\t}(addr)\n\t\t}\n\t\twg.Wait()\n\t\treturn nil\n\t},\n}\n\nfunc init() {\n\trootCmd.AddCommand(getCmd)\n\n\tgetCmd.Flags().StringSliceP(\"path\", \"\", []string{\"\/\"}, \"get request paths\")\n\tgetCmd.Flags().StringP(\"prefix\", \"\", \"\", \"get request prefix\")\n\tgetCmd.Flags().StringP(\"model\", \"\", \"\", \"get request model\")\n\tgetCmd.Flags().StringP(\"type\", \"t\", \"ALL\", \"the type of data that is requested from the target. one of: ALL, CONFIG, STATE, OPERATIONAL\")\n\tviper.BindPFlag(\"get-path\", getCmd.Flags().Lookup(\"path\"))\n\tviper.BindPFlag(\"get-prefix\", getCmd.Flags().Lookup(\"prefix\"))\n\tviper.BindPFlag(\"get-model\", getCmd.Flags().Lookup(\"model\"))\n\tviper.BindPFlag(\"get-type\", getCmd.Flags().Lookup(\"type\"))\n}\n<|endoftext|>"}
{"text":"<commit_before>package kerberos\n\nimport (\n\t\"fmt\"\n\t\/\/\"strings\"\n\n\t\/\/\"github.com\/hashicorp\/vault\/helper\/policyutil\"\n\t\"github.com\/hashicorp\/vault\/logical\"\n\t\"github.com\/hashicorp\/vault\/logical\/framework\"\n)\n\nfunc pathLogin(b *backend) *framework.Path {\n\treturn &framework.Path{\n\t\tPattern: \"login\/*\", \/\/TODO: Need to figure out Pattern\n\t\tFields: map[string]*framework.FieldSchema{\n\t\t\t\"ticket\": &framework.FieldSchema{\n\t\t\t\tType:        framework.TypeString, \/\/TODO: Figure out if this is right\n\t\t\t\tDescription: \"Kerberos Ticket used to Authorize and Authenticate\",\n\t\t\t},\n\t\t},\n\n\t\tCallbacks: map[logical.Operation]framework.OperationFunc{\n\t\t\tlogical.UpdateOperation: b.pathLogin,\n\t\t},\n\n\t\tHelpSynopsis:    pathLoginSyn,\n\t\tHelpDescription: pathLoginDesc,\n\t}\n}\n\nfunc (b *backend) pathLogin(\n\treq *logical.Request, d *framework.FieldData) (*logical.Response, error) {\n\tfmt.Println(\"We Made it here\")\n\treturn logical.ErrorResponse(\"invalid Request\"), nil\n\n}\n\nfunc (b *backend) pathLoginRenew(\n\treq *logical.Request, d *framework.FieldData) (*logical.Response, error) {\n\treturn logical.ErrorResponse(\"invald Request\"), nil\n\n}\n\nconst pathLoginSyn = `\nPlaceholder\n`\n\nconst pathLoginDesc = `\nPlaceholder\n`\n<commit_msg>Initial pathLogin success<commit_after>package kerberos\n\nimport (\n\t\"fmt\"\n\t\/\/\"strings\"\n\n\t\/\/\"github.com\/hashicorp\/vault\/helper\/policyutil\"\n\t\"github.com\/hashicorp\/vault\/logical\"\n\t\"github.com\/hashicorp\/vault\/logical\/framework\"\n)\n\nfunc pathLogin(b *backend) *framework.Path {\n\treturn &framework.Path{\n\t\tPattern: \"login\/user\", \/\/TODO: Need to figure out Pattern\n\t\tFields: map[string]*framework.FieldSchema{\n\t\t\t\"ticket\": &framework.FieldSchema{\n\t\t\t\tType:        framework.TypeString, \/\/TODO: Figure out if this is right\n\t\t\t\tDescription: \"Kerberos Ticket used to Authorize and Authenticate\",\n\t\t\t},\n\t\t},\n\n\t\tCallbacks: map[logical.Operation]framework.OperationFunc{\n\t\t\tlogical.UpdateOperation: b.pathLogin,\n\t\t},\n\n\t\tHelpSynopsis:    pathLoginSyn,\n\t\tHelpDescription: pathLoginDesc,\n\t}\n}\n\nfunc (b *backend) pathLogin(\n\treq *logical.Request, d *framework.FieldData) (*logical.Response, error) {\n\tfmt.Println(\"We Made it here\")\n\treturn logical.ErrorResponse(\"invalid Request\"), nil\n\n}\n\nfunc (b *backend) pathLoginRenew(\n\treq *logical.Request, d *framework.FieldData) (*logical.Response, error) {\n\treturn logical.ErrorResponse(\"invald Request\"), nil\n\n}\n\nconst pathLoginSyn = `\nPlaceholder\n`\n\nconst pathLoginDesc = `\nPlaceholder\n`\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2014 CoreOS, Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage integration\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/coreos\/etcd\/client\"\n\t\"github.com\/coreos\/etcd\/etcdserver\"\n\t\"github.com\/coreos\/etcd\/etcdserver\/etcdhttp\"\n\t\"github.com\/coreos\/etcd\/etcdserver\/etcdhttp\/httptypes\"\n\t\"github.com\/coreos\/etcd\/pkg\/types\"\n\n\t\"github.com\/coreos\/etcd\/Godeps\/_workspace\/src\/code.google.com\/p\/go.net\/context\"\n)\n\nconst (\n\ttickDuration   = 10 * time.Millisecond\n\tclusterName    = \"etcd\"\n\trequestTimeout = 2 * time.Second\n)\n\nfunc init() {\n\t\/\/ open microsecond-level time log for integration test debugging\n\tlog.SetFlags(log.Ltime | log.Lmicroseconds | log.Lshortfile)\n}\n\nfunc TestClusterOf1(t *testing.T) { testCluster(t, 1) }\nfunc TestClusterOf3(t *testing.T) { testCluster(t, 3) }\n\nfunc testCluster(t *testing.T, size int) {\n\tdefer afterTest(t)\n\tc := NewCluster(t, size)\n\tc.Launch(t)\n\tdefer c.Terminate(t)\n\tfor i, u := range c.URLs() {\n\t\tcc := mustNewHTTPClient(t, []string{u})\n\t\tkapi := client.NewKeysAPI(cc)\n\t\tctx, cancel := context.WithTimeout(context.Background(), requestTimeout)\n\t\tif _, err := kapi.Create(ctx, fmt.Sprintf(\"\/%d\", i), \"bar\", -1); err != nil {\n\t\t\tt.Errorf(\"create on %s error: %v\", u, err)\n\t\t}\n\t\tcancel()\n\t}\n}\n\nfunc TestClusterOf1UsingDiscovery(t *testing.T) { testClusterUsingDiscovery(t, 1) }\nfunc TestClusterOf3UsingDiscovery(t *testing.T) { testClusterUsingDiscovery(t, 3) }\n\nfunc testClusterUsingDiscovery(t *testing.T, size int) {\n\tdefer afterTest(t)\n\tdc := NewCluster(t, 1)\n\tdc.Launch(t)\n\tdefer dc.Terminate(t)\n\t\/\/ init discovery token space\n\tdcc := mustNewHTTPClient(t, dc.URLs())\n\tdkapi := client.NewKeysAPI(dcc)\n\tctx, cancel := context.WithTimeout(context.Background(), requestTimeout)\n\tif _, err := dkapi.Create(ctx, \"\/_config\/size\", fmt.Sprintf(\"%d\", size), -1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcancel()\n\n\tc := NewClusterByDiscovery(t, size, dc.URL(0)+\"\/v2\/keys\")\n\tc.Launch(t)\n\tdefer c.Terminate(t)\n\n\tfor i, u := range c.URLs() {\n\t\tcc := mustNewHTTPClient(t, []string{u})\n\t\tkapi := client.NewKeysAPI(cc)\n\t\tctx, cancel := context.WithTimeout(context.Background(), requestTimeout)\n\t\tif _, err := kapi.Create(ctx, fmt.Sprintf(\"\/%d\", i), \"bar\", -1); err != nil {\n\t\t\tt.Errorf(\"create on %s error: %v\", u, err)\n\t\t}\n\t\tcancel()\n\t}\n}\n\n\/\/ TODO: support TLS\ntype cluster struct {\n\tMembers []*member\n}\n\n\/\/ NewCluster returns an unlaunched cluster of the given size which has been\n\/\/ set to use static bootstrap.\nfunc NewCluster(t *testing.T, size int) *cluster {\n\tc := &cluster{}\n\tms := make([]*member, size)\n\tfor i := 0; i < size; i++ {\n\t\tms[i] = newMember(t, c.name(i))\n\t}\n\tc.Members = ms\n\n\taddrs := make([]string, 0)\n\tfor _, m := range ms {\n\t\tfor _, l := range m.PeerListeners {\n\t\t\taddrs = append(addrs, fmt.Sprintf(\"%s=%s\", m.Name, \"http:\/\/\"+l.Addr().String()))\n\t\t}\n\t}\n\tclusterStr := strings.Join(addrs, \",\")\n\tvar err error\n\tfor _, m := range ms {\n\t\tm.Cluster, err = etcdserver.NewClusterFromString(clusterName, clusterStr)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\treturn c\n}\n\n\/\/ NewClusterUsingDiscovery returns an unlaunched cluster of the given size\n\/\/ which has been set to use the given url as discovery service to bootstrap.\nfunc NewClusterByDiscovery(t *testing.T, size int, url string) *cluster {\n\tc := &cluster{}\n\tms := make([]*member, size)\n\tfor i := 0; i < size; i++ {\n\t\tms[i] = newMember(t, c.name(i))\n\t\tms[i].DiscoveryURL = url\n\t}\n\tc.Members = ms\n\treturn c\n}\n\nfunc (c *cluster) Launch(t *testing.T) {\n\tvar wg sync.WaitGroup\n\tfor _, m := range c.Members {\n\t\twg.Add(1)\n\t\t\/\/ Members are launched in separate goroutines because if they boot\n\t\t\/\/ using discovery url, they have to wait for others to register to continue.\n\t\tgo func(m *member) {\n\t\t\tm.Launch(t)\n\t\t\twg.Done()\n\t\t}(m)\n\t}\n\twg.Wait()\n\t\/\/ wait cluster to be stable to receive future client requests\n\tc.waitClientURLsPublished(t)\n}\n\nfunc (c *cluster) URL(i int) string {\n\treturn c.Members[i].ClientURLs[0].String()\n}\n\nfunc (c *cluster) URLs() []string {\n\turls := make([]string, 0)\n\tfor _, m := range c.Members {\n\t\tfor _, u := range m.ClientURLs {\n\t\t\turls = append(urls, u.String())\n\t\t}\n\t}\n\treturn urls\n}\n\nfunc (c *cluster) Terminate(t *testing.T) {\n\tfor _, m := range c.Members {\n\t\tm.Terminate(t)\n\t}\n}\n\nfunc (c *cluster) waitClientURLsPublished(t *testing.T) {\n\ttimer := time.AfterFunc(10*time.Second, func() {\n\t\tt.Fatal(\"wait too long for client urls publish\")\n\t})\n\tcc := mustNewHTTPClient(t, []string{c.URL(0)})\n\tma := client.NewMembersAPI(cc)\n\tfor {\n\t\tctx, cancel := context.WithTimeout(context.Background(), requestTimeout)\n\t\tmembs, err := ma.List(ctx)\n\t\tcancel()\n\t\tif err == nil && c.checkClientURLsPublished(membs) {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(tickDuration)\n\t}\n\ttimer.Stop()\n\treturn\n}\n\nfunc (c *cluster) checkClientURLsPublished(membs []httptypes.Member) bool {\n\tif len(membs) != len(c.Members) {\n\t\treturn false\n\t}\n\tfor _, m := range membs {\n\t\tif len(m.ClientURLs) == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (c *cluster) name(i int) string {\n\treturn fmt.Sprint(\"node\", i)\n}\n\nfunc newLocalListener(t *testing.T) net.Listener {\n\tl, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn l\n}\n\ntype member struct {\n\tetcdserver.ServerConfig\n\tPeerListeners, ClientListeners []net.Listener\n\n\ts   *etcdserver.EtcdServer\n\thss []*httptest.Server\n}\n\nfunc newMember(t *testing.T, name string) *member {\n\tvar err error\n\tm := &member{}\n\tpln := newLocalListener(t)\n\tm.PeerListeners = []net.Listener{pln}\n\tcln := newLocalListener(t)\n\tm.ClientListeners = []net.Listener{cln}\n\tm.Name = name\n\tm.ClientURLs, err = types.NewURLs([]string{\"http:\/\/\" + cln.Addr().String()})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tm.DataDir, err = ioutil.TempDir(os.TempDir(), \"etcd\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclusterStr := fmt.Sprintf(\"%s=http:\/\/%s\", name, pln.Addr().String())\n\tm.Cluster, err = etcdserver.NewClusterFromString(clusterName, clusterStr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tm.NewCluster = true\n\tm.Transport = newTransport()\n\treturn m\n}\n\n\/\/ Launch starts a member based on ServerConfig, PeerListeners\n\/\/ and ClientListeners.\nfunc (m *member) Launch(t *testing.T) {\n\tvar err error\n\tif m.s, err = etcdserver.NewServer(&m.ServerConfig); err != nil {\n\t\tt.Fatalf(\"failed to initialize the etcd server: %v\", err)\n\t}\n\tm.s.Ticker = time.Tick(tickDuration)\n\tm.s.SyncTicker = time.Tick(10 * tickDuration)\n\tm.s.Start()\n\n\tfor _, ln := range m.PeerListeners {\n\t\ths := &httptest.Server{\n\t\t\tListener: ln,\n\t\t\tConfig:   &http.Server{Handler: etcdhttp.NewPeerHandler(m.s)},\n\t\t}\n\t\ths.Start()\n\t\tm.hss = append(m.hss, hs)\n\t}\n\tfor _, ln := range m.ClientListeners {\n\t\ths := &httptest.Server{\n\t\t\tListener: ln,\n\t\t\tConfig:   &http.Server{Handler: etcdhttp.NewClientHandler(m.s)},\n\t\t}\n\t\ths.Start()\n\t\tm.hss = append(m.hss, hs)\n\t}\n}\n\n\/\/ Stop stops the member, but the data dir of the member is preserved.\nfunc (m *member) Stop(t *testing.T) {\n\tpanic(\"unimplemented\")\n}\n\n\/\/ Start starts the member using the preserved data dir.\nfunc (m *member) Start(t *testing.T) {\n\tpanic(\"unimplemented\")\n}\n\n\/\/ Terminate stops the member and removes the data dir.\nfunc (m *member) Terminate(t *testing.T) {\n\tm.s.Stop()\n\tfor _, hs := range m.hss {\n\t\ths.CloseClientConnections()\n\t\ths.Close()\n\t}\n\tif err := os.RemoveAll(m.ServerConfig.DataDir); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc mustNewHTTPClient(t *testing.T, eps []string) client.HTTPClient {\n\tcc, err := client.NewHTTPClient(newTransport(), eps)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn cc\n}\n\nfunc newTransport() *http.Transport {\n\ttr := &http.Transport{}\n\t\/\/ TODO: need the support of graceful stop in Sender to remove this\n\ttr.DisableKeepAlives = true\n\ttr.Dial = (&net.Dialer{Timeout: 100 * time.Millisecond}).Dial\n\treturn tr\n}\n<commit_msg>integration: rewrite the way to check cluster make progress<commit_after>\/*\n   Copyright 2014 CoreOS, Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage integration\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/coreos\/etcd\/client\"\n\t\"github.com\/coreos\/etcd\/etcdserver\"\n\t\"github.com\/coreos\/etcd\/etcdserver\/etcdhttp\"\n\t\"github.com\/coreos\/etcd\/etcdserver\/etcdhttp\/httptypes\"\n\t\"github.com\/coreos\/etcd\/pkg\/types\"\n\n\t\"github.com\/coreos\/etcd\/Godeps\/_workspace\/src\/code.google.com\/p\/go.net\/context\"\n)\n\nconst (\n\ttickDuration   = 10 * time.Millisecond\n\tclusterName    = \"etcd\"\n\trequestTimeout = 2 * time.Second\n)\n\nfunc init() {\n\t\/\/ open microsecond-level time log for integration test debugging\n\tlog.SetFlags(log.Ltime | log.Lmicroseconds | log.Lshortfile)\n}\n\nfunc TestClusterOf1(t *testing.T) { testCluster(t, 1) }\nfunc TestClusterOf3(t *testing.T) { testCluster(t, 3) }\n\nfunc testCluster(t *testing.T, size int) {\n\tdefer afterTest(t)\n\tc := NewCluster(t, size)\n\tc.Launch(t)\n\tdefer c.Terminate(t)\n\tclusterMustProgress(t, c)\n}\n\nfunc TestClusterOf1UsingDiscovery(t *testing.T) { testClusterUsingDiscovery(t, 1) }\nfunc TestClusterOf3UsingDiscovery(t *testing.T) { testClusterUsingDiscovery(t, 3) }\n\nfunc testClusterUsingDiscovery(t *testing.T, size int) {\n\tdefer afterTest(t)\n\tdc := NewCluster(t, 1)\n\tdc.Launch(t)\n\tdefer dc.Terminate(t)\n\t\/\/ init discovery token space\n\tdcc := mustNewHTTPClient(t, dc.URLs())\n\tdkapi := client.NewKeysAPI(dcc)\n\tctx, cancel := context.WithTimeout(context.Background(), requestTimeout)\n\tif _, err := dkapi.Create(ctx, \"\/_config\/size\", fmt.Sprintf(\"%d\", size), -1); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcancel()\n\n\tc := NewClusterByDiscovery(t, size, dc.URL(0)+\"\/v2\/keys\")\n\tc.Launch(t)\n\tdefer c.Terminate(t)\n\tclusterMustProgress(t, c)\n}\n\n\/\/ clusterMustProgress ensures that cluster can make progress. It creates\n\/\/ a key first, and check the new key could be got from all client urls of\n\/\/ the cluster.\nfunc clusterMustProgress(t *testing.T, cl *cluster) {\n\tcc := mustNewHTTPClient(t, []string{cl.URL(0)})\n\tkapi := client.NewKeysAPI(cc)\n\tctx, cancel := context.WithTimeout(context.Background(), requestTimeout)\n\tresp, err := kapi.Create(ctx, \"\/foo\", \"bar\", -1)\n\tif err != nil {\n\t\tt.Fatalf(\"create on %s error: %v\", cl.URL(0), err)\n\t}\n\tcancel()\n\n\tfor i, u := range cl.URLs() {\n\t\tcc := mustNewHTTPClient(t, []string{u})\n\t\tkapi := client.NewKeysAPI(cc)\n\t\tctx, cancel := context.WithTimeout(context.Background(), requestTimeout)\n\t\tif _, err := kapi.Watch(\"foo\", resp.Node.ModifiedIndex).Next(ctx); err != nil {\n\t\t\tt.Fatalf(\"#%d: watch on %s error: %v\", i, u, err)\n\t\t}\n\t\tcancel()\n\t}\n}\n\n\/\/ TODO: support TLS\ntype cluster struct {\n\tMembers []*member\n}\n\n\/\/ NewCluster returns an unlaunched cluster of the given size which has been\n\/\/ set to use static bootstrap.\nfunc NewCluster(t *testing.T, size int) *cluster {\n\tc := &cluster{}\n\tms := make([]*member, size)\n\tfor i := 0; i < size; i++ {\n\t\tms[i] = newMember(t, c.name(i))\n\t}\n\tc.Members = ms\n\n\taddrs := make([]string, 0)\n\tfor _, m := range ms {\n\t\tfor _, l := range m.PeerListeners {\n\t\t\taddrs = append(addrs, fmt.Sprintf(\"%s=%s\", m.Name, \"http:\/\/\"+l.Addr().String()))\n\t\t}\n\t}\n\tclusterStr := strings.Join(addrs, \",\")\n\tvar err error\n\tfor _, m := range ms {\n\t\tm.Cluster, err = etcdserver.NewClusterFromString(clusterName, clusterStr)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t}\n\n\treturn c\n}\n\n\/\/ NewClusterUsingDiscovery returns an unlaunched cluster of the given size\n\/\/ which has been set to use the given url as discovery service to bootstrap.\nfunc NewClusterByDiscovery(t *testing.T, size int, url string) *cluster {\n\tc := &cluster{}\n\tms := make([]*member, size)\n\tfor i := 0; i < size; i++ {\n\t\tms[i] = newMember(t, c.name(i))\n\t\tms[i].DiscoveryURL = url\n\t}\n\tc.Members = ms\n\treturn c\n}\n\nfunc (c *cluster) Launch(t *testing.T) {\n\tvar wg sync.WaitGroup\n\tfor _, m := range c.Members {\n\t\twg.Add(1)\n\t\t\/\/ Members are launched in separate goroutines because if they boot\n\t\t\/\/ using discovery url, they have to wait for others to register to continue.\n\t\tgo func(m *member) {\n\t\t\tm.Launch(t)\n\t\t\twg.Done()\n\t\t}(m)\n\t}\n\twg.Wait()\n\t\/\/ wait cluster to be stable to receive future client requests\n\tc.waitClientURLsPublished(t)\n}\n\nfunc (c *cluster) URL(i int) string {\n\treturn c.Members[i].ClientURLs[0].String()\n}\n\nfunc (c *cluster) URLs() []string {\n\turls := make([]string, 0)\n\tfor _, m := range c.Members {\n\t\tfor _, u := range m.ClientURLs {\n\t\t\turls = append(urls, u.String())\n\t\t}\n\t}\n\treturn urls\n}\n\nfunc (c *cluster) Terminate(t *testing.T) {\n\tfor _, m := range c.Members {\n\t\tm.Terminate(t)\n\t}\n}\n\nfunc (c *cluster) waitClientURLsPublished(t *testing.T) {\n\ttimer := time.AfterFunc(10*time.Second, func() {\n\t\tt.Fatal(\"wait too long for client urls publish\")\n\t})\n\tcc := mustNewHTTPClient(t, []string{c.URL(0)})\n\tma := client.NewMembersAPI(cc)\n\tfor {\n\t\tctx, cancel := context.WithTimeout(context.Background(), requestTimeout)\n\t\tmembs, err := ma.List(ctx)\n\t\tcancel()\n\t\tif err == nil && c.checkClientURLsPublished(membs) {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(tickDuration)\n\t}\n\ttimer.Stop()\n\treturn\n}\n\nfunc (c *cluster) checkClientURLsPublished(membs []httptypes.Member) bool {\n\tif len(membs) != len(c.Members) {\n\t\treturn false\n\t}\n\tfor _, m := range membs {\n\t\tif len(m.ClientURLs) == 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (c *cluster) name(i int) string {\n\treturn fmt.Sprint(\"node\", i)\n}\n\nfunc newLocalListener(t *testing.T) net.Listener {\n\tl, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn l\n}\n\ntype member struct {\n\tetcdserver.ServerConfig\n\tPeerListeners, ClientListeners []net.Listener\n\n\ts   *etcdserver.EtcdServer\n\thss []*httptest.Server\n}\n\nfunc newMember(t *testing.T, name string) *member {\n\tvar err error\n\tm := &member{}\n\tpln := newLocalListener(t)\n\tm.PeerListeners = []net.Listener{pln}\n\tcln := newLocalListener(t)\n\tm.ClientListeners = []net.Listener{cln}\n\tm.Name = name\n\tm.ClientURLs, err = types.NewURLs([]string{\"http:\/\/\" + cln.Addr().String()})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tm.DataDir, err = ioutil.TempDir(os.TempDir(), \"etcd\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tclusterStr := fmt.Sprintf(\"%s=http:\/\/%s\", name, pln.Addr().String())\n\tm.Cluster, err = etcdserver.NewClusterFromString(clusterName, clusterStr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tm.NewCluster = true\n\tm.Transport = newTransport()\n\treturn m\n}\n\n\/\/ Launch starts a member based on ServerConfig, PeerListeners\n\/\/ and ClientListeners.\nfunc (m *member) Launch(t *testing.T) {\n\tvar err error\n\tif m.s, err = etcdserver.NewServer(&m.ServerConfig); err != nil {\n\t\tt.Fatalf(\"failed to initialize the etcd server: %v\", err)\n\t}\n\tm.s.Ticker = time.Tick(tickDuration)\n\tm.s.SyncTicker = time.Tick(10 * tickDuration)\n\tm.s.Start()\n\n\tfor _, ln := range m.PeerListeners {\n\t\ths := &httptest.Server{\n\t\t\tListener: ln,\n\t\t\tConfig:   &http.Server{Handler: etcdhttp.NewPeerHandler(m.s)},\n\t\t}\n\t\ths.Start()\n\t\tm.hss = append(m.hss, hs)\n\t}\n\tfor _, ln := range m.ClientListeners {\n\t\ths := &httptest.Server{\n\t\t\tListener: ln,\n\t\t\tConfig:   &http.Server{Handler: etcdhttp.NewClientHandler(m.s)},\n\t\t}\n\t\ths.Start()\n\t\tm.hss = append(m.hss, hs)\n\t}\n}\n\n\/\/ Stop stops the member, but the data dir of the member is preserved.\nfunc (m *member) Stop(t *testing.T) {\n\tpanic(\"unimplemented\")\n}\n\n\/\/ Start starts the member using the preserved data dir.\nfunc (m *member) Start(t *testing.T) {\n\tpanic(\"unimplemented\")\n}\n\n\/\/ Terminate stops the member and removes the data dir.\nfunc (m *member) Terminate(t *testing.T) {\n\tm.s.Stop()\n\tfor _, hs := range m.hss {\n\t\ths.CloseClientConnections()\n\t\ths.Close()\n\t}\n\tif err := os.RemoveAll(m.ServerConfig.DataDir); err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc mustNewHTTPClient(t *testing.T, eps []string) client.HTTPClient {\n\tcc, err := client.NewHTTPClient(newTransport(), eps)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn cc\n}\n\nfunc newTransport() *http.Transport {\n\ttr := &http.Transport{}\n\t\/\/ TODO: need the support of graceful stop in Sender to remove this\n\ttr.DisableKeepAlives = true\n\ttr.Dial = (&net.Dialer{Timeout: 100 * time.Millisecond}).Dial\n\treturn tr\n}\n<|endoftext|>"}
{"text":"<commit_before>package integration\n\nimport (\n\t\"os\"\n\t\"os\/exec\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"Upgrade\", func() {\n\tBeforeEach(func() {\n\t\tdir := setupTestWorkingDirWithVersion(\"v1.2.2\")\n\t\tos.Chdir(dir)\n\t})\n\tDescribe(\"Upgrading a cluster using offline mode\", func() {\n\t\tContext(\"Using a minikube layout\", func() {\n\t\t\tContext(\"Using Ubuntu 16.04\", func() {\n\t\t\t\tItOnAWS(\"should be upgraded [slow] [upgrade]\", func(aws infrastructureProvisioner) {\n\t\t\t\t\tWithMiniInfrastructure(Ubuntu1604LTS, aws, func(node NodeDeets, sshKey string) {\n\t\t\t\t\t\t\/\/ Install previous version cluster\n\t\t\t\t\t\terr := installKismaticMini(node, sshKey)\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\t\/\/ Extract current version of kismatic\n\t\t\t\t\t\tpwd, err := os.Getwd()\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\t\terr = extractCurrentKismatic(pwd)\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\t\/\/ Perform upgrade\n\t\t\t\t\t\tcmd := exec.Command(\".\/kismatic\", \"upgrade\", \"offline\", \"-f\", \"kismatic-testing.yaml\")\n\t\t\t\t\t\tcmd.Stderr = os.Stderr\n\t\t\t\t\t\tcmd.Stdout = os.Stdout\n\t\t\t\t\t\terr = cmd.Run()\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"Using CentOS 7\", func() {\n\t\t\t\tItOnAWS(\"should be upgraded [slow] [upgrade]\", func(aws infrastructureProvisioner) {\n\t\t\t\t\tWithMiniInfrastructure(CentOS7, aws, func(node NodeDeets, sshKey string) {\n\t\t\t\t\t\t\/\/ Install previous version cluster\n\t\t\t\t\t\terr := installKismaticMini(node, sshKey)\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\t\/\/ Extract new version of kismatic\n\t\t\t\t\t\tpwd, err := os.Getwd()\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\t\terr = extractCurrentKismatic(pwd)\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\t\/\/ Perform upgrade\n\t\t\t\t\t\tcmd := exec.Command(\".\/kismatic\", \"upgrade\", \"offline\", \"-f\", \"kismatic-testing.yaml\")\n\t\t\t\t\t\tcmd.Stderr = os.Stderr\n\t\t\t\t\t\tcmd.Stdout = os.Stdout\n\t\t\t\t\t\terr = cmd.Run()\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\t\/\/ This spec will be used for testing non-destructive kismatic features on\n\t\t\/\/ an upgraded cluster.\n\t\t\/\/ This spec is open to modification when new assertions have to be made.\n\t\tContext(\"Using a skunkworks cluster\", func() {\n\t\t\tItOnAWS(\"should result in an upgraded cluster [slow] [upgrade]\", func(aws infrastructureProvisioner) {\n\t\t\t\tWithInfrastructureAndDNS(NodeCount{Etcd: 3, Master: 2, Worker: 3, Ingress: 2, Storage: 2}, CentOS7, aws, func(nodes provisionedNodes, sshKey string) {\n\t\t\t\t\t\/\/ reserve one of the workers for the add-worker test\n\t\t\t\t\tallWorkers := nodes.worker\n\t\t\t\t\tnodes.worker = allWorkers[0 : len(nodes.worker)-1]\n\n\t\t\t\t\t\/\/ Standup cluster with previous version\n\t\t\t\t\topts := installOptions{allowPackageInstallation: true}\n\t\t\t\t\terr := installKismatic(nodes, opts, sshKey)\n\t\t\t\t\tFailIfError(err)\n\n\t\t\t\t\tpwd, err := os.Getwd()\n\t\t\t\t\tFailIfError(err)\n\t\t\t\t\terr = extractCurrentKismatic(pwd)\n\t\t\t\t\tFailIfError(err)\n\n\t\t\t\t\tcmd := exec.Command(\".\/kismatic\", \"upgrade\", \"offline\", \"-f\", \"kismatic-testing.yaml\")\n\t\t\t\t\tcmd.Stdout = os.Stdout\n\t\t\t\t\tcmd.Stderr = os.Stderr\n\t\t\t\t\terr = cmd.Run()\n\t\t\t\t\tFailIfError(err)\n\n\t\t\t\t\tassertClusterVersionIsCurrent()\n\n\t\t\t\t\tsub := SubDescribe(\"Using an upgraded cluster\")\n\t\t\t\t\tdefer sub.Check()\n\n\t\t\t\t\tsub.It(\"should allow adding a new storage volume\", func() error {\n\t\t\t\t\t\tplanFile, err := os.Open(\"kismatic-testing.yaml\")\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn createVolume(planFile, \"test-vol\", 1, 1, \"\")\n\t\t\t\t\t})\n\n\t\t\t\t\tsub.It(\"should allow adding a worker node\", func() error {\n\t\t\t\t\t\tnewWorker := allWorkers[len(allWorkers)-1]\n\t\t\t\t\t\treturn addWorkerToCluster(newWorker)\n\t\t\t\t\t})\n\n\t\t\t\t\tsub.It(\"should have an accessible dashboard\", func() error {\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t})\n\n\t\t\t\t\tsub.It(\"should be able to deploy a workload with ingress\", func() error {\n\t\t\t\t\t\treturn verifyIngressNodes(nodes.master[0], nodes.ingress, sshKey)\n\t\t\t\t\t})\n\n\t\t\t\t\tsub.It(\"should not have kube-apiserver systemd service\", func() error {\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n})\n<commit_msg>Add dashboard upgrade test<commit_after>package integration\n\nimport (\n\t\"os\"\n\t\"os\/exec\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"Upgrade\", func() {\n\tBeforeEach(func() {\n\t\tdir := setupTestWorkingDirWithVersion(\"v1.2.2\")\n\t\tos.Chdir(dir)\n\t})\n\tDescribe(\"Upgrading a cluster using offline mode\", func() {\n\t\tContext(\"Using a minikube layout\", func() {\n\t\t\tContext(\"Using Ubuntu 16.04\", func() {\n\t\t\t\tItOnAWS(\"should be upgraded [slow] [upgrade]\", func(aws infrastructureProvisioner) {\n\t\t\t\t\tWithMiniInfrastructure(Ubuntu1604LTS, aws, func(node NodeDeets, sshKey string) {\n\t\t\t\t\t\t\/\/ Install previous version cluster\n\t\t\t\t\t\terr := installKismaticMini(node, sshKey)\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\t\/\/ Extract current version of kismatic\n\t\t\t\t\t\tpwd, err := os.Getwd()\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\t\terr = extractCurrentKismatic(pwd)\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\t\/\/ Perform upgrade\n\t\t\t\t\t\tcmd := exec.Command(\".\/kismatic\", \"upgrade\", \"offline\", \"-f\", \"kismatic-testing.yaml\")\n\t\t\t\t\t\tcmd.Stderr = os.Stderr\n\t\t\t\t\t\tcmd.Stdout = os.Stdout\n\t\t\t\t\t\terr = cmd.Run()\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\n\t\t\tContext(\"Using CentOS 7\", func() {\n\t\t\t\tItOnAWS(\"should be upgraded [slow] [upgrade]\", func(aws infrastructureProvisioner) {\n\t\t\t\t\tWithMiniInfrastructure(CentOS7, aws, func(node NodeDeets, sshKey string) {\n\t\t\t\t\t\t\/\/ Install previous version cluster\n\t\t\t\t\t\terr := installKismaticMini(node, sshKey)\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\t\/\/ Extract new version of kismatic\n\t\t\t\t\t\tpwd, err := os.Getwd()\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\t\terr = extractCurrentKismatic(pwd)\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\t\t\t\t\/\/ Perform upgrade\n\t\t\t\t\t\tcmd := exec.Command(\".\/kismatic\", \"upgrade\", \"offline\", \"-f\", \"kismatic-testing.yaml\")\n\t\t\t\t\t\tcmd.Stderr = os.Stderr\n\t\t\t\t\t\tcmd.Stdout = os.Stdout\n\t\t\t\t\t\terr = cmd.Run()\n\t\t\t\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\t\/\/ This spec will be used for testing non-destructive kismatic features on\n\t\t\/\/ an upgraded cluster.\n\t\t\/\/ This spec is open to modification when new assertions have to be made.\n\t\tContext(\"Using a skunkworks cluster\", func() {\n\t\t\tItOnAWS(\"should result in an upgraded cluster [slow] [upgrade]\", func(aws infrastructureProvisioner) {\n\t\t\t\tWithInfrastructureAndDNS(NodeCount{Etcd: 3, Master: 2, Worker: 3, Ingress: 2, Storage: 2}, CentOS7, aws, func(nodes provisionedNodes, sshKey string) {\n\t\t\t\t\t\/\/ reserve one of the workers for the add-worker test\n\t\t\t\t\tallWorkers := nodes.worker\n\t\t\t\t\tnodes.worker = allWorkers[0 : len(nodes.worker)-1]\n\n\t\t\t\t\t\/\/ Standup cluster with previous version\n\t\t\t\t\topts := installOptions{allowPackageInstallation: true}\n\t\t\t\t\terr := installKismatic(nodes, opts, sshKey)\n\t\t\t\t\tFailIfError(err)\n\n\t\t\t\t\tpwd, err := os.Getwd()\n\t\t\t\t\tFailIfError(err)\n\t\t\t\t\terr = extractCurrentKismatic(pwd)\n\t\t\t\t\tFailIfError(err)\n\n\t\t\t\t\tcmd := exec.Command(\".\/kismatic\", \"upgrade\", \"offline\", \"-f\", \"kismatic-testing.yaml\")\n\t\t\t\t\tcmd.Stdout = os.Stdout\n\t\t\t\t\tcmd.Stderr = os.Stderr\n\t\t\t\t\terr = cmd.Run()\n\t\t\t\t\tFailIfError(err)\n\n\t\t\t\t\tassertClusterVersionIsCurrent()\n\n\t\t\t\t\tsub := SubDescribe(\"Using an upgraded cluster\")\n\t\t\t\t\tdefer sub.Check()\n\n\t\t\t\t\tsub.It(\"should allow adding a new storage volume\", func() error {\n\t\t\t\t\t\tplanFile, err := os.Open(\"kismatic-testing.yaml\")\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn createVolume(planFile, \"test-vol\", 1, 1, \"\")\n\t\t\t\t\t})\n\n\t\t\t\t\tsub.It(\"should allow adding a worker node\", func() error {\n\t\t\t\t\t\tnewWorker := allWorkers[len(allWorkers)-1]\n\t\t\t\t\t\treturn addWorkerToCluster(newWorker)\n\t\t\t\t\t})\n\n\t\t\t\t\tsub.It(\"should have an accessible dashboard\", func() error {\n\t\t\t\t\t\treturn canAccessDashboard()\n\t\t\t\t\t})\n\n\t\t\t\t\tsub.It(\"should be able to deploy a workload with ingress\", func() error {\n\t\t\t\t\t\treturn verifyIngressNodes(nodes.master[0], nodes.ingress, sshKey)\n\t\t\t\t\t})\n\n\t\t\t\t\tsub.It(\"should not have kube-apiserver systemd service\", func() error {\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t})\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build !windows\n\/\/ +build !go1.8\n\npackage fs\n\nimport (\n\t\"os\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\nfunc rename(src, dst string) error {\n\tfi, err := os.Stat(src)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"cannot stat %s\", src)\n\t}\n\n\tif dstfi, err := os.Stat(dst); fi.IsDir() && err == nil && dstfi.IsDir() {\n\t\treturn errors.Errorf(\"cannot rename directory %s to existing dst %s\", src, dst)\n\t}\n\n\treturn os.Rename(src, dst)\n}\n<commit_msg>internal\/fs: add renameFallback to rename_go1.7.go<commit_after>\/\/ Copyright 2016 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build !windows\n\/\/ +build !go1.8\n\npackage fs\n\nimport (\n\t\"os\"\n\n\t\"github.com\/pkg\/errors\"\n)\n\nfunc rename(src, dst string) error {\n\tfi, err := os.Stat(src)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"cannot stat %s\", src)\n\t}\n\n\tif dstfi, err := os.Stat(dst); fi.IsDir() && err == nil && dstfi.IsDir() {\n\t\treturn errors.Errorf(\"cannot rename directory %s to existing dst %s\", src, dst)\n\t}\n\n\treturn os.Rename(src, dst)\n}\n\n\/\/ renameFallback attempts to determine the appropriate fallback to failed rename\n\/\/ operation depending on the resulting error.\nfunc renameFallback(err error, src, dst string) error {\n\t\/\/ Rename may fail if src and dst are on different devices; fall back to\n\t\/\/ copy if we detect that case. syscall.EXDEV is the common name for the\n\t\/\/ cross device link error which has varying output text across different\n\t\/\/ operating systems.\n\tterr, ok := err.(*os.LinkError)\n\tif !ok {\n\t\treturn err\n\t} else if terr.Err != syscall.EXDEV {\n\t\treturn errors.Wrapf(terr, \"link error: cannot rename %s to %s\", src, dst)\n\t}\n\n\treturn renameByCopy(src, dst)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage cache\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/parser\"\n\t\"go\/scanner\"\n\t\"go\/token\"\n\n\t\"golang.org\/x\/tools\/internal\/lsp\/source\"\n\t\"golang.org\/x\/tools\/internal\/lsp\/telemetry\/trace\"\n\t\"golang.org\/x\/tools\/internal\/memoize\"\n)\n\n\/\/ Limits the number of parallel parser calls per process.\nvar parseLimit = make(chan bool, 20)\n\n\/\/ parseKey uniquely identifies a parsed Go file.\ntype parseKey struct {\n\tfile source.FileIdentity\n\tmode source.ParseMode\n}\n\ntype parseGoHandle struct {\n\thandle *memoize.Handle\n\tfile   source.FileHandle\n\tmode   source.ParseMode\n}\n\ntype parseGoData struct {\n\tmemoize.NoCopy\n\n\tast *ast.File\n\terr error\n}\n\nfunc (c *cache) ParseGoHandle(fh source.FileHandle, mode source.ParseMode) source.ParseGoHandle {\n\tkey := parseKey{\n\t\tfile: fh.Identity(),\n\t\tmode: mode,\n\t}\n\th := c.store.Bind(key, func(ctx context.Context) interface{} {\n\t\tdata := &parseGoData{}\n\t\tdata.ast, data.err = parseGo(ctx, c, fh, mode)\n\t\treturn data\n\t})\n\treturn &parseGoHandle{\n\t\thandle: h,\n\t\tfile:   fh,\n\t\tmode:   mode,\n\t}\n}\n\nfunc (h *parseGoHandle) File() source.FileHandle {\n\treturn h.file\n}\n\nfunc (h *parseGoHandle) Mode() source.ParseMode {\n\treturn h.mode\n}\n\nfunc (h *parseGoHandle) Parse(ctx context.Context) (*ast.File, error) {\n\tv := h.handle.Get(ctx)\n\tif v == nil {\n\t\treturn nil, ctx.Err()\n\t}\n\tdata := v.(*parseGoData)\n\treturn data.ast, data.err\n}\n\nfunc parseGo(ctx context.Context, c *cache, fh source.FileHandle, mode source.ParseMode) (*ast.File, error) {\n\tctx, done := trace.StartSpan(ctx, \"cache.parseGo\")\n\tdefer done()\n\tbuf, _, err := fh.Read(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tparseLimit <- true\n\tdefer func() { <-parseLimit }()\n\tparserMode := parser.AllErrors | parser.ParseComments\n\tif mode == source.ParseHeader {\n\t\tparserMode = parser.ImportsOnly\n\t}\n\tast, err := parser.ParseFile(c.fset, fh.Identity().URI.Filename(), buf, parserMode)\n\tif ast != nil {\n\t\tif mode == source.ParseExported {\n\t\t\ttrimAST(ast)\n\t\t}\n\t\t\/\/ Fix any badly parsed parts of the AST.\n\t\ttok := c.fset.File(ast.Pos())\n\t\tif err := fix(ctx, ast, tok, buf); err != nil {\n\t\t\t\/\/ TODO: Do something with the error (need access to a logger in here).\n\t\t}\n\t}\n\tif ast == nil {\n\t\treturn nil, err\n\t}\n\treturn ast, err\n}\n\n\/\/ trimAST clears any part of the AST not relevant to type checking\n\/\/ expressions at pos.\nfunc trimAST(file *ast.File) {\n\tast.Inspect(file, func(n ast.Node) bool {\n\t\tif n == nil {\n\t\t\treturn false\n\t\t}\n\t\tswitch n := n.(type) {\n\t\tcase *ast.FuncDecl:\n\t\t\tn.Body = nil\n\t\tcase *ast.BlockStmt:\n\t\t\tn.List = nil\n\t\tcase *ast.CaseClause:\n\t\t\tn.Body = nil\n\t\tcase *ast.CommClause:\n\t\t\tn.Body = nil\n\t\tcase *ast.CompositeLit:\n\t\t\t\/\/ Leave elts in place for [...]T\n\t\t\t\/\/ array literals, because they can\n\t\t\t\/\/ affect the expression's type.\n\t\t\tif !isEllipsisArray(n.Type) {\n\t\t\t\tn.Elts = nil\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n}\n\nfunc isEllipsisArray(n ast.Expr) bool {\n\tat, ok := n.(*ast.ArrayType)\n\tif !ok {\n\t\treturn false\n\t}\n\t_, ok = at.Len.(*ast.Ellipsis)\n\treturn ok\n}\n\n\/\/ fix inspects and potentially modifies any *ast.BadStmts or *ast.BadExprs in the AST.\n\/\/ We attempt to modify the AST such that we can type-check it more effectively.\nfunc fix(ctx context.Context, file *ast.File, tok *token.File, src []byte) error {\n\tvar parent ast.Node\n\tvar err error\n\tast.Inspect(file, func(n ast.Node) bool {\n\t\tif n == nil {\n\t\t\treturn false\n\t\t}\n\t\tswitch n := n.(type) {\n\t\tcase *ast.BadStmt:\n\t\t\terr = parseDeferOrGoStmt(n, parent, tok, src) \/\/ don't shadow err\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"unable to parse defer or go from *ast.BadStmt: %v\", err)\n\t\t\t}\n\t\t\treturn false\n\t\tdefault:\n\t\t\tparent = n\n\t\t\treturn true\n\t\t}\n\t})\n\treturn err\n}\n\n\/\/ parseDeferOrGoStmt tries to parse an *ast.BadStmt into a defer or a go statement.\n\/\/\n\/\/ go\/parser packages a statement of the form \"defer x.\" as an *ast.BadStmt because\n\/\/ it does not include a call expression. This means that go\/types skips type-checking\n\/\/ this statement entirely, and we can't use the type information when completing.\n\/\/ Here, we try to generate a fake *ast.DeferStmt or *ast.GoStmt to put into the AST,\n\/\/ instead of the *ast.BadStmt.\nfunc parseDeferOrGoStmt(bad *ast.BadStmt, parent ast.Node, tok *token.File, src []byte) error {\n\t\/\/ Check if we have a bad statement containing either a \"go\" or \"defer\".\n\ts := &scanner.Scanner{}\n\ts.Init(tok, src, nil, 0)\n\n\tvar pos token.Pos\n\tvar tkn token.Token\n\tvar lit string\n\tfor {\n\t\tif tkn == token.EOF {\n\t\t\treturn fmt.Errorf(\"reached the end of the file\")\n\t\t}\n\t\tif pos >= bad.From {\n\t\t\tbreak\n\t\t}\n\t\tpos, tkn, lit = s.Scan()\n\t}\n\tvar stmt ast.Stmt\n\tswitch lit {\n\tcase \"defer\":\n\t\tstmt = &ast.DeferStmt{\n\t\t\tDefer: pos,\n\t\t}\n\tcase \"go\":\n\t\tstmt = &ast.GoStmt{\n\t\t\tGo: pos,\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"no defer or go statement found\")\n\t}\n\n\t\/\/ The expression after the \"defer\" or \"go\" starts at this position.\n\tfrom, _, _ := s.Scan()\n\tvar to, curr token.Pos\nFindTo:\n\tfor {\n\t\tcurr, tkn, lit = s.Scan()\n\t\t\/\/ TODO(rstambler): This still needs more handling to work correctly.\n\t\t\/\/ We encounter a specific issue with code that looks like this:\n\t\t\/\/\n\t\t\/\/      defer x.<>\n\t\t\/\/      y := 1\n\t\t\/\/\n\t\t\/\/ In this scenario, we parse it as \"defer x.y\", which then fails to\n\t\t\/\/ type-check, and we don't get completions as expected.\n\t\tswitch tkn {\n\t\tcase token.COMMENT, token.EOF, token.SEMICOLON, token.DEFINE:\n\t\t\tbreak FindTo\n\t\t}\n\t\t\/\/ to is the end of expression that should become the Fun part of the call.\n\t\tto = curr\n\t}\n\tif !from.IsValid() || tok.Offset(from) >= len(src) {\n\t\treturn fmt.Errorf(\"invalid from position\")\n\t}\n\tif !to.IsValid() || tok.Offset(to)+1 >= len(src) {\n\t\treturn fmt.Errorf(\"invalid to position\")\n\t}\n\texprstr := string(src[tok.Offset(from) : tok.Offset(to)+1])\n\texpr, err := parser.ParseExpr(exprstr)\n\tif expr == nil {\n\t\treturn fmt.Errorf(\"no expr in %s: %v\", exprstr, err)\n\t}\n\t\/\/ parser.ParseExpr returns undefined positions.\n\t\/\/ Adjust them for the current file.\n\toffsetPositions(expr, from-1)\n\n\t\/\/ Package the expression into a fake *ast.CallExpr and re-insert into the function.\n\tcall := &ast.CallExpr{\n\t\tFun:    expr,\n\t\tLparen: to,\n\t\tRparen: to,\n\t}\n\tswitch stmt := stmt.(type) {\n\tcase *ast.DeferStmt:\n\t\tstmt.Call = call\n\tcase *ast.GoStmt:\n\t\tstmt.Call = call\n\t}\n\tswitch parent := parent.(type) {\n\tcase *ast.BlockStmt:\n\t\tfor i, s := range parent.List {\n\t\t\tif s == bad {\n\t\t\t\tparent.List[i] = stmt\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ offsetPositions applies an offset to the positions in an ast.Node.\n\/\/ TODO(rstambler): Add more cases here as they become necessary.\nfunc offsetPositions(expr ast.Expr, offset token.Pos) {\n\tast.Inspect(expr, func(n ast.Node) bool {\n\t\tswitch n := n.(type) {\n\t\tcase *ast.Ident:\n\t\t\tn.NamePos += offset\n\t\t\treturn false\n\t\tdefault:\n\t\t\treturn true\n\t\t}\n\t})\n}\n<commit_msg>internal\/lsp\/cache: clean up parse.go<commit_after>\/\/ Copyright 2019 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage cache\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"go\/ast\"\n\t\"go\/parser\"\n\t\"go\/scanner\"\n\t\"go\/token\"\n\n\t\"golang.org\/x\/tools\/internal\/lsp\/source\"\n\t\"golang.org\/x\/tools\/internal\/lsp\/telemetry\/trace\"\n\t\"golang.org\/x\/tools\/internal\/memoize\"\n)\n\n\/\/ Limits the number of parallel parser calls per process.\nvar parseLimit = make(chan struct{}, 20)\n\n\/\/ parseKey uniquely identifies a parsed Go file.\ntype parseKey struct {\n\tfile source.FileIdentity\n\tmode source.ParseMode\n}\n\ntype parseGoHandle struct {\n\thandle *memoize.Handle\n\tfile   source.FileHandle\n\tmode   source.ParseMode\n}\n\ntype parseGoData struct {\n\tmemoize.NoCopy\n\n\tast *ast.File\n\terr error\n}\n\nfunc (c *cache) ParseGoHandle(fh source.FileHandle, mode source.ParseMode) source.ParseGoHandle {\n\tkey := parseKey{\n\t\tfile: fh.Identity(),\n\t\tmode: mode,\n\t}\n\th := c.store.Bind(key, func(ctx context.Context) interface{} {\n\t\tdata := &parseGoData{}\n\t\tdata.ast, data.err = parseGo(ctx, c, fh, mode)\n\t\treturn data\n\t})\n\treturn &parseGoHandle{\n\t\thandle: h,\n\t\tfile:   fh,\n\t\tmode:   mode,\n\t}\n}\n\nfunc (h *parseGoHandle) File() source.FileHandle {\n\treturn h.file\n}\n\nfunc (h *parseGoHandle) Mode() source.ParseMode {\n\treturn h.mode\n}\n\nfunc (h *parseGoHandle) Parse(ctx context.Context) (*ast.File, error) {\n\tv := h.handle.Get(ctx)\n\tif v == nil {\n\t\treturn nil, ctx.Err()\n\t}\n\tdata := v.(*parseGoData)\n\treturn data.ast, data.err\n}\n\nfunc parseGo(ctx context.Context, c *cache, fh source.FileHandle, mode source.ParseMode) (*ast.File, error) {\n\tctx, done := trace.StartSpan(ctx, \"cache.parseGo\")\n\tdefer done()\n\tbuf, _, err := fh.Read(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tparseLimit <- struct{}{}\n\tdefer func() { <-parseLimit }()\n\tparserMode := parser.AllErrors | parser.ParseComments\n\tif mode == source.ParseHeader {\n\t\tparserMode = parser.ImportsOnly\n\t}\n\tast, err := parser.ParseFile(c.fset, fh.Identity().URI.Filename(), buf, parserMode)\n\tif ast != nil {\n\t\tif mode == source.ParseExported {\n\t\t\ttrimAST(ast)\n\t\t}\n\t\t\/\/ Fix any badly parsed parts of the AST.\n\t\ttok := c.fset.File(ast.Pos())\n\t\tif err := fix(ctx, ast, tok, buf); err != nil {\n\t\t\t\/\/ TODO: Do something with the error (need access to a logger in here).\n\t\t}\n\t}\n\tif ast == nil {\n\t\treturn nil, err\n\t}\n\treturn ast, err\n}\n\n\/\/ trimAST clears any part of the AST not relevant to type checking\n\/\/ expressions at pos.\nfunc trimAST(file *ast.File) {\n\tast.Inspect(file, func(n ast.Node) bool {\n\t\tif n == nil {\n\t\t\treturn false\n\t\t}\n\t\tswitch n := n.(type) {\n\t\tcase *ast.FuncDecl:\n\t\t\tn.Body = nil\n\t\tcase *ast.BlockStmt:\n\t\t\tn.List = nil\n\t\tcase *ast.CaseClause:\n\t\t\tn.Body = nil\n\t\tcase *ast.CommClause:\n\t\t\tn.Body = nil\n\t\tcase *ast.CompositeLit:\n\t\t\t\/\/ Leave elts in place for [...]T\n\t\t\t\/\/ array literals, because they can\n\t\t\t\/\/ affect the expression's type.\n\t\t\tif !isEllipsisArray(n.Type) {\n\t\t\t\tn.Elts = nil\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n}\n\nfunc isEllipsisArray(n ast.Expr) bool {\n\tat, ok := n.(*ast.ArrayType)\n\tif !ok {\n\t\treturn false\n\t}\n\t_, ok = at.Len.(*ast.Ellipsis)\n\treturn ok\n}\n\n\/\/ fix inspects the AST and potentially modifies any *ast.BadStmts so that it can be\n\/\/ type-checked more effectively.\nfunc fix(ctx context.Context, file *ast.File, tok *token.File, src []byte) error {\n\tvar parent ast.Node\n\tvar err error\n\tast.Inspect(file, func(n ast.Node) bool {\n\t\tif n == nil {\n\t\t\treturn false\n\t\t}\n\t\tswitch n := n.(type) {\n\t\tcase *ast.BadStmt:\n\t\t\terr = parseDeferOrGoStmt(n, parent, tok, src) \/\/ don't shadow err\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"unable to parse defer or go from *ast.BadStmt: %v\", err)\n\t\t\t}\n\t\t\treturn false\n\t\tdefault:\n\t\t\tparent = n\n\t\t\treturn true\n\t\t}\n\t})\n\treturn err\n}\n\n\/\/ parseDeferOrGoStmt tries to parse an *ast.BadStmt into a defer or a go statement.\n\/\/\n\/\/ go\/parser packages a statement of the form \"defer x.\" as an *ast.BadStmt because\n\/\/ it does not include a call expression. This means that go\/types skips type-checking\n\/\/ this statement entirely, and we can't use the type information when completing.\n\/\/ Here, we try to generate a fake *ast.DeferStmt or *ast.GoStmt to put into the AST,\n\/\/ instead of the *ast.BadStmt.\nfunc parseDeferOrGoStmt(bad *ast.BadStmt, parent ast.Node, tok *token.File, src []byte) error {\n\t\/\/ Check if we have a bad statement containing either a \"go\" or \"defer\".\n\ts := &scanner.Scanner{}\n\ts.Init(tok, src, nil, 0)\n\n\tvar pos token.Pos\n\tvar tkn token.Token\n\tvar lit string\n\tfor {\n\t\tif tkn == token.EOF {\n\t\t\treturn fmt.Errorf(\"reached the end of the file\")\n\t\t}\n\t\tif pos >= bad.From {\n\t\t\tbreak\n\t\t}\n\t\tpos, tkn, lit = s.Scan()\n\t}\n\tvar stmt ast.Stmt\n\tswitch lit {\n\tcase \"defer\":\n\t\tstmt = &ast.DeferStmt{\n\t\t\tDefer: pos,\n\t\t}\n\tcase \"go\":\n\t\tstmt = &ast.GoStmt{\n\t\t\tGo: pos,\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"no defer or go statement found\")\n\t}\n\n\t\/\/ The expression after the \"defer\" or \"go\" starts at this position.\n\tfrom, _, _ := s.Scan()\n\tvar to, curr token.Pos\nFindTo:\n\tfor {\n\t\tcurr, tkn, _ = s.Scan()\n\t\t\/\/ TODO(rstambler): This still needs more handling to work correctly.\n\t\t\/\/ We encounter a specific issue with code that looks like this:\n\t\t\/\/\n\t\t\/\/      defer x.<>\n\t\t\/\/      y := 1\n\t\t\/\/\n\t\t\/\/ In this scenario, we parse it as \"defer x.y\", which then fails to\n\t\t\/\/ type-check, and we don't get completions as expected.\n\t\tswitch tkn {\n\t\tcase token.COMMENT, token.EOF, token.SEMICOLON, token.DEFINE:\n\t\t\tbreak FindTo\n\t\t}\n\t\t\/\/ to is the end of expression that should become the Fun part of the call.\n\t\tto = curr\n\t}\n\tif !from.IsValid() || tok.Offset(from) >= len(src) {\n\t\treturn fmt.Errorf(\"invalid from position\")\n\t}\n\tif !to.IsValid() || tok.Offset(to)+1 >= len(src) {\n\t\treturn fmt.Errorf(\"invalid to position\")\n\t}\n\texprstr := string(src[tok.Offset(from) : tok.Offset(to)+1])\n\texpr, err := parser.ParseExpr(exprstr)\n\tif expr == nil {\n\t\treturn fmt.Errorf(\"no expr in %s: %v\", exprstr, err)\n\t}\n\t\/\/ parser.ParseExpr returns undefined positions.\n\t\/\/ Adjust them for the current file.\n\toffsetPositions(expr, from-1)\n\n\t\/\/ Package the expression into a fake *ast.CallExpr and re-insert into the function.\n\tcall := &ast.CallExpr{\n\t\tFun:    expr,\n\t\tLparen: to,\n\t\tRparen: to,\n\t}\n\tswitch stmt := stmt.(type) {\n\tcase *ast.DeferStmt:\n\t\tstmt.Call = call\n\tcase *ast.GoStmt:\n\t\tstmt.Call = call\n\t}\n\tswitch parent := parent.(type) {\n\tcase *ast.BlockStmt:\n\t\tfor i, s := range parent.List {\n\t\t\tif s == bad {\n\t\t\t\tparent.List[i] = stmt\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ offsetPositions applies an offset to the positions in an ast.Node.\n\/\/ TODO(rstambler): Add more cases here as they become necessary.\nfunc offsetPositions(expr ast.Expr, offset token.Pos) {\n\tast.Inspect(expr, func(n ast.Node) bool {\n\t\tswitch n := n.(type) {\n\t\tcase *ast.Ident:\n\t\t\tn.NamePos += offset\n\t\t\treturn false\n\t\tdefault:\n\t\t\treturn true\n\t\t}\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/montanaflynn\/stats\"\n)\n\n\/\/ global command line parameters\nvar runs *int\nvar cpus0 *string\nvar cpus1 *string\nvar threads *string\nvar hermitcore *bool\n\nfunc main() {\n\truns = flag.Int(\"arun\", 2, \"Number of times the applications are executed\")\n\tcommandFile := flag.String(\"cmd\", \"cmd.txt\", \"Text file containing the commands to execute\")\n\tcpus0 = flag.String(\"cpus0\", \"0-4\", \"List of CPUs to be used for the 1st command\")\n\tcpus1 = flag.String(\"cpus1\", \"5-9\", \"List of CPUs to be used for the 2nd command\")\n\tthreads = flag.String(\"threads\", \"5\", \"Number of threads to be used\")\n\thermitcore = flag.Bool(\"hermitcore\", false, \"Use if you are executing hermitcore binaries\")\n\t\/\/resctrlPath := flag.String(\"resctrl\", \"\/sys\/fs\/resctrl\/\", \"Root path of the resctrl file system\")\n\tflag.Parse()\n\n\tcommands, err := readCommands(*commandFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error reading command file %v: %v\", *commandFile, err)\n\t}\n\tif len(commands) < 2 {\n\t\tlog.Fatal(\"You must provide at least 2 commands\")\n\t}\n\n\tcommandPairs := generateCommandPairs(commands)\n\n\tfmt.Println(\"Executing the following command pairs:\")\n\tfor _, c := range commandPairs {\n\t\tfmt.Println(c)\n\t}\n\n\tfor i, c := range commandPairs {\n\t\tfmt.Printf(\"Running pair %v\\n\", i)\n\t\tfmt.Println(c)\n\t\t\/\/ TODO run for every combination of CAT setup\n\t\terr := runPair(c, i)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error while running pair %v (%v): %v\", i, c, err)\n\t\t}\n\t}\n}\n\nfunc runCmdMinTimes(cmd *exec.Cmd, min int, wg *sync.WaitGroup, measurement *string, done chan int, errs chan error) {\n\tdefer wg.Done()\n\n\tvar runtime []float64\n\n\tfor i := 1; ; i++ {\n\t\t\/\/ create a copy of the command\n\t\tcmd := *cmd\n\n\t\tstart := time.Now()\n\t\terr := cmd.Run()\n\t\telapsed := time.Since(start)\n\n\t\tif err != nil {\n\t\t\terrs <- fmt.Errorf(\"Error running %v: %v\", cmd.Args, err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ did the other cmd result in an error?\n\t\tif len(errs) != 0 {\n\t\t\treturn\n\t\t}\n\n\t\td := <-done\n\n\t\t\/\/ check if the other application was running the whole time\n\t\tif d == 2 {\n\t\t\t\/\/ no\n\t\t\t*measurement += \"# \"\n\t\t} else {\n\t\t\truntime = append(runtime, elapsed.Seconds())\n\t\t}\n\t\t*measurement += strconv.FormatInt(elapsed.Nanoseconds(), 10)\n\t\t*measurement += \"\\n\"\n\n\t\t\/\/ did we run min times?\n\t\tif i == min {\n\t\t\td++\n\t\t}\n\t\tdone <- d\n\n\t\t\/\/ both applications are done\n\t\tif d == 2 {\n\t\t\tmean, err := stats.Mean(runtime)\n\t\t\tif err != nil {\n\t\t\t\tmean = -23.23\n\t\t\t}\n\t\t\tstddev, err := stats.StandardDeviation(runtime)\n\t\t\tif err != nil {\n\t\t\t\tstddev = -23.23\n\t\t\t}\n\t\t\tvari, err := stats.Variance(runtime)\n\t\t\tif err != nil {\n\t\t\t\tvari = -23.23\n\t\t\t}\n\n\t\t\tfmt.Printf(\"%v \\t %9.2fs avg. runtime \\t %1.6f std. dev. \\t %1.6f variance \\t %v runs\\n\", cmd.Args, mean, stddev, vari, i)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc runPair(cPair [2]string, id int) error {\n\tvar cmd0 *exec.Cmd\n\tvar cmd1 *exec.Cmd\n\n\tenv := os.Environ()\n\tif *hermitcore {\n\t\tcmd0 = exec.Command(\"taskset\", \"-c\", *cpus0, \"\/bin\/sh\", \"-c\", cPair[0])\n\t\tcmd1 = exec.Command(\"taskset\", \"-c\", *cpus1, \"\/bin\/sh\", \"-c\", cPair[1])\n\t\tcmd0.Env = append(env, \"HERMIT_CPUS=\"+*threads, \"HERMIT_MEM=4G\", \"HERMIT_ISLE=uhyve\")\n\t\tcmd1.Env = append(env, \"HERMIT_CPUS=\"+*threads, \"HERMIT_MEM=4G\", \"HERMIT_ISLE=uhyve\")\n\t} else {\n\t\tcmd0 = exec.Command(\"\/bin\/sh\", \"-c\", cPair[0])\n\t\tcmd1 = exec.Command(\"\/bin\/sh\", \"-c\", cPair[1])\n\t\tcmd0.Env = append(env, \"GOMP_CPU_AFFINITY=\"+*cpus0, \"OMP_NUM_THREADS=\"+*threads)\n\t\tcmd1.Env = append(env, \"GOMP_CPU_AFFINITY=\"+*cpus1, \"OMP_NUM_THREADS=\"+*threads)\n\t}\n\n\toutfile0, err := os.Create(fmt.Sprintf(\"%v-0.log\", id))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error while creating file: %v\", err)\n\t}\n\tdefer outfile0.Close()\n\toutfile1, err := os.Create(fmt.Sprintf(\"%v-1.log\", id))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error while creating file: %v\", err)\n\t}\n\tdefer outfile1.Close()\n\n\tcmd0.Stdout = outfile0\n\tcmd1.Stdout = outfile1\n\n\tvar measurements [2]string\n\t\/\/ used to count how many apps have reached there min limit\n\tdone := make(chan int, 1)\n\tdone <- 0\n\n\t\/\/ used to return an error from the go-routines\n\terrs := make(chan error, 2)\n\n\t\/\/ used to wait for the following 2 goroutines\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\n\tgo runCmdMinTimes(cmd0, *runs, &wg, &measurements[0], done, errs)\n\tgo runCmdMinTimes(cmd1, *runs, &wg, &measurements[1], done, errs)\n\n\twg.Wait()\n\n\tif len(errs) != 0 {\n\t\treturn <-errs\n\t}\n\n\tfor i, s := range measurements {\n\t\tmeasurementsFile, err := os.Create(fmt.Sprintf(\"%v-%v.time\", id, i))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error while creating file: %v\", err)\n\t\t}\n\t\tdefer measurementsFile.Close()\n\n\t\t_, err = measurementsFile.WriteString(\"# runtime in nanoseconds of \\\"\" + cPair[i] + \"\\\" while \\\"\" + cPair[(i+1)%2] + \"\\\" is running\\n\" + s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error while writing measurements file: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc generateCommandPairs(commands []string) [][2]string {\n\tvar pairs [][2]string\n\tfor i, c0 := range commands {\n\t\tfor j, c1 := range commands {\n\t\t\tif i >= j {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpairs = append(pairs, [2]string{c0, c1})\n\t\t}\n\t}\n\treturn pairs\n}\n\nfunc readCommands(filename string) ([]string, error) {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error opening file \" + filename + \": \" + err.Error())\n\t}\n\tdefer file.Close()\n\n\tvar commands []string\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tcommands = append(commands, scanner.Text())\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, errors.New(\"Error scanning commands: \" + err.Error())\n\t}\n\n\treturn commands, nil\n}\n<commit_msg>Simplified stats computation.<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/montanaflynn\/stats\"\n)\n\n\/\/ global command line parameters\nvar runs *int\nvar cpus0 *string\nvar cpus1 *string\nvar threads *string\nvar hermitcore *bool\n\nfunc main() {\n\truns = flag.Int(\"arun\", 2, \"Number of times the applications are executed\")\n\tcommandFile := flag.String(\"cmd\", \"cmd.txt\", \"Text file containing the commands to execute\")\n\tcpus0 = flag.String(\"cpus0\", \"0-4\", \"List of CPUs to be used for the 1st command\")\n\tcpus1 = flag.String(\"cpus1\", \"5-9\", \"List of CPUs to be used for the 2nd command\")\n\tthreads = flag.String(\"threads\", \"5\", \"Number of threads to be used\")\n\thermitcore = flag.Bool(\"hermitcore\", false, \"Use if you are executing hermitcore binaries\")\n\t\/\/resctrlPath := flag.String(\"resctrl\", \"\/sys\/fs\/resctrl\/\", \"Root path of the resctrl file system\")\n\tflag.Parse()\n\n\tcommands, err := readCommands(*commandFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error reading command file %v: %v\", *commandFile, err)\n\t}\n\tif len(commands) < 2 {\n\t\tlog.Fatal(\"You must provide at least 2 commands\")\n\t}\n\n\tcommandPairs := generateCommandPairs(commands)\n\n\tfmt.Println(\"Executing the following command pairs:\")\n\tfor _, c := range commandPairs {\n\t\tfmt.Println(c)\n\t}\n\n\tfor i, c := range commandPairs {\n\t\tfmt.Printf(\"Running pair %v\\n\", i)\n\t\tfmt.Println(c)\n\t\t\/\/ TODO run for every combination of CAT setup\n\t\terr := runPair(c, i)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Error while running pair %v (%v): %v\", i, c, err)\n\t\t}\n\t}\n}\n\nfunc runCmdMinTimes(cmd *exec.Cmd, min int, wg *sync.WaitGroup, measurement *string, done chan int, errs chan error) {\n\tdefer wg.Done()\n\n\tvar runtime []float64\n\n\tfor i := 1; ; i++ {\n\t\t\/\/ create a copy of the command\n\t\tcmd := *cmd\n\n\t\tstart := time.Now()\n\t\terr := cmd.Run()\n\t\telapsed := time.Since(start)\n\n\t\tif err != nil {\n\t\t\terrs <- fmt.Errorf(\"Error running %v: %v\", cmd.Args, err)\n\t\t\treturn\n\t\t}\n\n\t\t\/\/ did the other cmd result in an error?\n\t\tif len(errs) != 0 {\n\t\t\treturn\n\t\t}\n\n\t\td := <-done\n\n\t\t\/\/ check if the other application was running the whole time\n\t\tif d == 2 {\n\t\t\t\/\/ no\n\t\t\t*measurement += \"# \"\n\t\t} else {\n\t\t\truntime = append(runtime, elapsed.Seconds())\n\t\t}\n\t\t*measurement += strconv.FormatInt(elapsed.Nanoseconds(), 10)\n\t\t*measurement += \"\\n\"\n\n\t\t\/\/ did we run min times?\n\t\tif i == min {\n\t\t\td++\n\t\t}\n\t\tdone <- d\n\n\t\t\/\/ both applications are done\n\t\tif d == 2 {\n\t\t\t\/\/ ignore error, stats returns NaN\n\t\t\tmean, _ := stats.Mean(runtime)\n\t\t\tstddev, _ := stats.StandardDeviation(runtime)\n\t\t\tvari, _ := stats.Variance(runtime)\n\n\t\t\tfmt.Printf(\"%v \\t %9.2fs avg. runtime \\t %1.6f std. dev. \\t %1.6f variance \\t %v runs\\n\", cmd.Args, mean, stddev, vari, i)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc runPair(cPair [2]string, id int) error {\n\tvar cmd0 *exec.Cmd\n\tvar cmd1 *exec.Cmd\n\n\tenv := os.Environ()\n\tif *hermitcore {\n\t\tcmd0 = exec.Command(\"taskset\", \"-c\", *cpus0, \"\/bin\/sh\", \"-c\", cPair[0])\n\t\tcmd1 = exec.Command(\"taskset\", \"-c\", *cpus1, \"\/bin\/sh\", \"-c\", cPair[1])\n\t\tcmd0.Env = append(env, \"HERMIT_CPUS=\"+*threads, \"HERMIT_MEM=4G\", \"HERMIT_ISLE=uhyve\")\n\t\tcmd1.Env = append(env, \"HERMIT_CPUS=\"+*threads, \"HERMIT_MEM=4G\", \"HERMIT_ISLE=uhyve\")\n\t} else {\n\t\tcmd0 = exec.Command(\"\/bin\/sh\", \"-c\", cPair[0])\n\t\tcmd1 = exec.Command(\"\/bin\/sh\", \"-c\", cPair[1])\n\t\tcmd0.Env = append(env, \"GOMP_CPU_AFFINITY=\"+*cpus0, \"OMP_NUM_THREADS=\"+*threads)\n\t\tcmd1.Env = append(env, \"GOMP_CPU_AFFINITY=\"+*cpus1, \"OMP_NUM_THREADS=\"+*threads)\n\t}\n\n\toutfile0, err := os.Create(fmt.Sprintf(\"%v-0.log\", id))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error while creating file: %v\", err)\n\t}\n\tdefer outfile0.Close()\n\toutfile1, err := os.Create(fmt.Sprintf(\"%v-1.log\", id))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error while creating file: %v\", err)\n\t}\n\tdefer outfile1.Close()\n\n\tcmd0.Stdout = outfile0\n\tcmd1.Stdout = outfile1\n\n\tvar measurements [2]string\n\t\/\/ used to count how many apps have reached there min limit\n\tdone := make(chan int, 1)\n\tdone <- 0\n\n\t\/\/ used to return an error from the go-routines\n\terrs := make(chan error, 2)\n\n\t\/\/ used to wait for the following 2 goroutines\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\n\tgo runCmdMinTimes(cmd0, *runs, &wg, &measurements[0], done, errs)\n\tgo runCmdMinTimes(cmd1, *runs, &wg, &measurements[1], done, errs)\n\n\twg.Wait()\n\n\tif len(errs) != 0 {\n\t\treturn <-errs\n\t}\n\n\tfor i, s := range measurements {\n\t\tmeasurementsFile, err := os.Create(fmt.Sprintf(\"%v-%v.time\", id, i))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error while creating file: %v\", err)\n\t\t}\n\t\tdefer measurementsFile.Close()\n\n\t\t_, err = measurementsFile.WriteString(\"# runtime in nanoseconds of \\\"\" + cPair[i] + \"\\\" while \\\"\" + cPair[(i+1)%2] + \"\\\" is running\\n\" + s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error while writing measurements file: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc generateCommandPairs(commands []string) [][2]string {\n\tvar pairs [][2]string\n\tfor i, c0 := range commands {\n\t\tfor j, c1 := range commands {\n\t\t\tif i >= j {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpairs = append(pairs, [2]string{c0, c1})\n\t\t}\n\t}\n\treturn pairs\n}\n\nfunc readCommands(filename string) ([]string, error) {\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn nil, errors.New(\"Error opening file \" + filename + \": \" + err.Error())\n\t}\n\tdefer file.Close()\n\n\tvar commands []string\n\n\tscanner := bufio.NewScanner(file)\n\tfor scanner.Scan() {\n\t\tcommands = append(commands, scanner.Text())\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, errors.New(\"Error scanning commands: \" + err.Error())\n\t}\n\n\treturn commands, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017, TCN Inc.\n\/\/ All rights reserved.\n\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/     * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/     * Neither the name of TCN Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\npackage generator\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"github.com\/xwb1989\/sqlparser\"\n\t\"github.com\/Sirupsen\/logrus\"\n)\n\ntype QueryArg struct {\n\tName         string      \/\/ name in the map,\n\tValue        interface{} \/\/ generic value of the argument. If is a field, this will be empty\n\tIsFieldValue bool        \/\/ Whether this refers to a field passed in\n\tField        TypeDesc    \/\/ if IsFieldValue is true, this will describe the Field\n}\n\ntype SpannerHelper struct {\n\tRawQuery string\n\tQuery string\n\tParsedQuery sqlparser.Statement\n\tTableName string\n\tOptionArguments []string\n\tIsSelect bool\n\tIsUpdate bool\n\tIsInsert bool\n\tIsDelete bool\n\tQueryArgs []QueryArg\n\tInsertCols []string \/\/ the column names for insert queries\n\tParent *Method\n\tProtoFieldDescs map[string]TypeDesc\n}\n\nfunc (sh *SpannerHelper) String() string {\n\tif sh != nil {\n\t\treturn fmt.Sprintf(\"SpannerHelper\\n\\tQuery: %s\\n\\tIsSelect: %t\\n\\tIsUpdate: %t\\n\\tIsInsert: %t\\n\\tIsDelete: %t\\n\\n\",\n\t\t\t\tsh.Query, sh.IsSelect, sh.IsUpdate, sh.IsInsert, sh.IsDelete)\n\t}\n\treturn \"<nil>\"\n}\n\nfunc NewSpannerHelper(p *Method) (*SpannerHelper, error) {\n\t\/\/ get the query, and parse it\n\topts := p.GetMethodOption()\n\tif opts == nil {\n\t\treturn nil, fmt.Errorf(\"no options found on proto method\")\n\t}\n\targs := opts.GetArguments()\n\tquery := opts.GetQuery()\n\tlogrus.Debugf(\"query: %#v\", query)\n\tpquery, err := sqlparser.Parse(query)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing error in spanner_helper: %s\", err)\n\t}\n\t\/\/ get the fields descriptions to construct query args\n\tinput := p.GetInputTypeStruct()\n\tfieldsMap := p.GetTypeDescForFieldsInStructSnakeCase(input)\n\n\n\tsh := &SpannerHelper{\n\t\tRawQuery: query,\n\t\tParsedQuery: pquery,\n\t\tOptionArguments: args,\n\t\tParent: p,\n\t\tProtoFieldDescs: fieldsMap,\n\t}\n\terr = sh.Parse()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sh, nil\n}\n\nfunc (sh *SpannerHelper) Parse() error {\n\t\/\/ parse our query\n\tswitch pq := sh.ParsedQuery.(type) {\n\tcase *sqlparser.Select:\n\t\tsh.IsSelect = true\n\t\tspl := strings.Split(sh.RawQuery, \"?\")\n\t\tvar updatedQuery string\n\n\t\tif len(sh.OptionArguments) != len(spl) - 1 {\n\t\t\terrStr := \"err parsing spanner query: not correct number of option arguments\"\n\t\t\terrStr += \" for method: %s of service: %s  want: %d have: %d\"\n\t\t\treturn fmt.Errorf(errStr, sh.Parent.GetName(), sh.Parent.Service.GetName(), len(spl) - 1, len(sh.OptionArguments))\n\t\t}\n\t\tfor i := 0; i < len(spl)-1; i++ {\n\t\t\tname := fmt.Sprintf(\"@%d\", i)\n\t\t\tfield := sh.ProtoFieldDescs[sh.OptionArguments[i]]\n\t\t\tqa := QueryArg{\n\t\t\t\tName: name,\n\t\t\t\tIsFieldValue: true,\n\t\t\t\tField: field,\n\t\t\t}\n\t\t\tsh.QueryArgs = append(sh.QueryArgs, qa)\n\t\t\tupdatedQuery += (spl[i] + name)\n\t\t}\n\t\tupdatedQuery += spl[len(spl)-1]\n\t\tsh.Query = updatedQuery\n\tcase *sqlparser.Insert:\n\t\tsh.IsInsert = true\n\t\tcols, err := extractInsertColumns(pq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttable, err := extractIUDTableName(pq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpas, err := prepareInsertValues(pq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, arg := range pas.args {\n\t\t\tvar qa QueryArg\n\t\t\tif ap, ok := arg.(PassedInArgPos); ok {\n\t\t\t\tindex := int(ap)\n\t\t\t\targName := sh.OptionArguments[index]\n\t\t\t\tqa = QueryArg{\n\t\t\t\t\tIsFieldValue: true,\n\t\t\t\t\tField: sh.ProtoFieldDescs[argName],\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tqa = QueryArg{\n\t\t\t\t\tValue: fmt.Sprintf(\"%#v\", arg),\n\t\t\t\t\tIsFieldValue: false,\n\t\t\t\t}\n\t\t\t}\n\t\t\tsh.QueryArgs = append(sh.QueryArgs, qa)\n\t\t}\n\t\tsh.InsertCols = cols\n\t\tsh.TableName = table\n\tcase *sqlparser.Delete:\n\t\tsh.IsUpdate = true\n\t\ttable, err := extractIUDTableName(pq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsh.TableName = table\n\tcase *sqlparser.Update:\n\t\tsh.IsDelete = true\n\t\ttable, err := extractIUDTableName(pq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsh.TableName = table\n\t}\n\treturn nil\n}\n\nfunc (sh *SpannerHelper) InsertColsAsString() string {\n\treturn fmt.Sprintf(\"%#v\", sh.InsertCols)\n}\n\n\nfunc (sh *SpannerHelper) GetDeleteKeyRange() string {\n\treturn \"\"\n}\n<commit_msg>added update query parsing<commit_after>\/\/ Copyright 2017, TCN Inc.\n\/\/ All rights reserved.\n\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\n\/\/     * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/     * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/     * Neither the name of TCN Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\npackage generator\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"github.com\/xwb1989\/sqlparser\"\n\t\"github.com\/Sirupsen\/logrus\"\n)\n\ntype QueryArg struct {\n\tName         string      \/\/ name in the map,\n\tValue        interface{} \/\/ generic value of the argument. If is a field, this will be empty\n\tIsFieldValue bool        \/\/ Whether this refers to a field passed in\n\tField        TypeDesc    \/\/ if IsFieldValue is true, this will describe the Field\n}\n\ntype SpannerHelper struct {\n\tRawQuery string\n\tQuery string\n\tParsedQuery sqlparser.Statement\n\tTableName string\n\tOptionArguments []string\n\tIsSelect bool\n\tIsUpdate bool\n\tIsInsert bool\n\tIsDelete bool\n\tQueryArgs []QueryArg\n\tInsertCols []string \/\/ the column names for insert queries\n\tParent *Method\n\tProtoFieldDescs map[string]TypeDesc\n}\n\nfunc (sh *SpannerHelper) String() string {\n\tif sh != nil {\n\t\treturn fmt.Sprintf(\"SpannerHelper\\n\\tQuery: %s\\n\\tIsSelect: %t\\n\\tIsUpdate: %t\\n\\tIsInsert: %t\\n\\tIsDelete: %t\\n\\n\",\n\t\t\t\tsh.Query, sh.IsSelect, sh.IsUpdate, sh.IsInsert, sh.IsDelete)\n\t}\n\treturn \"<nil>\"\n}\n\nfunc NewSpannerHelper(p *Method) (*SpannerHelper, error) {\n\t\/\/ get the query, and parse it\n\topts := p.GetMethodOption()\n\tif opts == nil {\n\t\treturn nil, fmt.Errorf(\"no options found on proto method\")\n\t}\n\targs := opts.GetArguments()\n\tquery := opts.GetQuery()\n\tlogrus.Debugf(\"query: %#v\", query)\n\tpquery, err := sqlparser.Parse(query)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"parsing error in spanner_helper: %s\", err)\n\t}\n\t\/\/ get the fields descriptions to construct query args\n\tinput := p.GetInputTypeStruct()\n\tfieldsMap := p.GetTypeDescForFieldsInStructSnakeCase(input)\n\n\n\tsh := &SpannerHelper{\n\t\tRawQuery: query,\n\t\tParsedQuery: pquery,\n\t\tOptionArguments: args,\n\t\tParent: p,\n\t\tProtoFieldDescs: fieldsMap,\n\t}\n\terr = sh.Parse()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sh, nil\n}\n\nfunc (sh *SpannerHelper) Parse() error {\n\t\/\/ parse our query\n\tswitch pq := sh.ParsedQuery.(type) {\n\tcase *sqlparser.Select:\n\t\tsh.IsSelect = true\n\t\tspl := strings.Split(sh.RawQuery, \"?\")\n\t\tvar updatedQuery string\n\n\t\tif len(sh.OptionArguments) != len(spl) - 1 {\n\t\t\terrStr := \"err parsing spanner query: not correct number of option arguments\"\n\t\t\terrStr += \" for method: %s of service: %s  want: %d have: %d\"\n\t\t\treturn fmt.Errorf(errStr, sh.Parent.GetName(), sh.Parent.Service.GetName(), len(spl) - 1, len(sh.OptionArguments))\n\t\t}\n\t\tfor i := 0; i < len(spl)-1; i++ {\n\t\t\tname := fmt.Sprintf(\"@%d\", i)\n\t\t\tfield := sh.ProtoFieldDescs[sh.OptionArguments[i]]\n\t\t\tqa := QueryArg{\n\t\t\t\tName: name,\n\t\t\t\tIsFieldValue: true,\n\t\t\t\tField: field,\n\t\t\t}\n\t\t\tsh.QueryArgs = append(sh.QueryArgs, qa)\n\t\t\tupdatedQuery += (spl[i] + name)\n\t\t}\n\t\tupdatedQuery += spl[len(spl)-1]\n\t\tsh.Query = updatedQuery\n\tcase *sqlparser.Insert:\n\t\tsh.IsInsert = true\n\t\tcols, err := extractInsertColumns(pq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\ttable, err := extractIUDTableName(pq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpas, err := prepareInsertValues(pq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, arg := range pas.args {\n\t\t\tvar qa QueryArg\n\t\t\tif ap, ok := arg.(PassedInArgPos); ok {\n\t\t\t\tindex := int(ap)\n\t\t\t\targName := sh.OptionArguments[index]\n\t\t\t\tqa = QueryArg{\n\t\t\t\t\tIsFieldValue: true,\n\t\t\t\t\tField: sh.ProtoFieldDescs[argName],\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tqa = QueryArg{\n\t\t\t\t\tValue: fmt.Sprintf(\"%#v\", arg),\n\t\t\t\t\tIsFieldValue: false,\n\t\t\t\t}\n\t\t\t}\n\t\t\tsh.QueryArgs = append(sh.QueryArgs, qa)\n\t\t}\n\t\tsh.InsertCols = cols\n\t\tsh.TableName = table\n\tcase *sqlparser.Delete:\n\t\tsh.IsDelete = true\n\t\ttable, err := extractIUDTableName(pq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsh.TableName = table\n\tcase *sqlparser.Update:\n\t\tsh.IsUpdate = true\n\t\ttable, err := extractIUDTableName(pq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tpam, err := extractUpdateClause(pq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor key, arg := range pam.args {\n\t\t\tvar qa QueryArg\n\t\t\tif ap, ok := arg.(PassedInArgPos); ok {\n\t\t\t\tindex := int(ap)\n\t\t\t\targName := sh.OptionArguments[index]\n\t\t\t\tqa = QueryArg{\n\t\t\t\t\tName: key,\n\t\t\t\t\tIsFieldValue: true,\n\t\t\t\t\tField: sh.ProtoFieldDescs[argName],\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tqa = QueryArg{\n\t\t\t\t\tName: key,\n\t\t\t\t\tValue: fmt.Sprintf(\"%#v\", arg),\n\t\t\t\t\tIsFieldValue: false,\n\t\t\t\t}\n\t\t\t}\n\t\t\tsh.QueryArgs = append(sh.QueryArgs, qa)\n\t\t}\n\t\tsh.TableName = table\n\t}\n\treturn nil\n}\n\nfunc (sh *SpannerHelper) InsertColsAsString() string {\n\treturn fmt.Sprintf(\"%#v\", sh.InsertCols)\n}\n\n\nfunc (sh *SpannerHelper) GetDeleteKeyRange() string {\n\treturn \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 The Periph Authors. All rights reserved.\n\/\/ Use of this source code is governed under the Apache License, Version 2.0\n\/\/ that can be found in the LICENSE file.\n\npackage pca9685\n\nimport (\n\t\"time\"\n\n\t\"periph.io\/x\/periph\/conn\/gpio\"\n\t\"periph.io\/x\/periph\/conn\/i2c\"\n\t\"periph.io\/x\/periph\/conn\/physic\"\n)\n\n\/\/ I2CAddr i2c default address.\nconst I2CAddr uint16 = 0x40\n\n\/\/ PCA9685 Commands\nconst (\n\tmode1      byte = 0x00\n\tmode2      byte = 0x01\n\tsubAdr1    byte = 0x02\n\tsubAdr2    byte = 0x03\n\tsubAdr3    byte = 0x04\n\tprescale   byte = 0xFE\n\tled0OnL    byte = 0x06\n\tled0OnH    byte = 0x07\n\tled0OffL   byte = 0x08\n\tled0OffH   byte = 0x09\n\tallLedOnL  byte = 0xFA\n\tallLedOnH  byte = 0xFB\n\tallLedOffL byte = 0xFC\n\tallLedOffH byte = 0xFD\n\n\t\/\/ Bits\n\trestart byte = 0x80\n\tsleep   byte = 0x10\n\tallCall byte = 0x01\n\tinvrt   byte = 0x10\n\toutDrv  byte = 0x04\n)\n\n\/\/ Dev is a handler to pca9685 controller\ntype Dev struct {\n\tdev *i2c.Dev\n}\n\n\/\/ NewI2C returns a Dev object that communicates over I2C.\n\/\/\n\/\/ To use on the default address, pca9685.I2CAddr must be passed as argument.\nfunc NewI2C(bus i2c.Bus, address uint16) (*Dev, error) {\n\tdev := &Dev{\n\t\tdev: &i2c.Dev{Bus: bus, Addr: address},\n\t}\n\terr := dev.init()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn dev, nil\n}\n\nfunc (d *Dev) init() error {\n\tif err := d.SetAllPwm(0, 0); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := d.dev.Write([]byte{mode2, outDrv}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.dev.Write([]byte{mode1, allCall}); err != nil {\n\t\treturn err\n\t}\n\n\ttime.Sleep(100 * time.Millisecond)\n\n\tmodeRead := [1]byte{}\n\tif err := d.dev.Tx([]byte{mode1}, modeRead[:]); err != nil {\n\t\treturn err\n\t}\n\n\tmode := modeRead[0] & ^sleep\n\tif _, err := d.dev.Write([]byte{mode1, mode}); err != nil {\n\t\treturn err\n\t}\n\n\ttime.Sleep(5 * time.Millisecond)\n\n\treturn d.SetPwmFreq(50 * physic.Hertz)\n}\n\n\/\/ SetPwmFreq set the pwm frequency\nfunc (d *Dev) SetPwmFreq(freqHz physic.Frequency) error {\n\tp := (25*physic.MegaHertz\/4096 + freqHz\/2) \/ freqHz\n\n\tmodeRead := [1]byte{}\n\tif err := d.dev.Tx([]byte{mode1}, modeRead[:]); err != nil {\n\t\treturn err\n\t}\n\n\toldmode := modeRead[0]\n\tif _, err := d.dev.Write([]byte{mode1, byte((oldmode & 0x7F) | 0x10)}); err != nil { \/\/ go to sleep;\n\t\treturn err\n\t}\n\tif _, err := d.dev.Write([]byte{prescale, byte(p)}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.dev.Write([]byte{mode1, oldmode}); err != nil {\n\t\treturn err\n\t}\n\n\ttime.Sleep(100 * time.Millisecond)\n\n\t_, err := d.dev.Write([]byte{mode1, (byte)(oldmode | 0x80)})\n\treturn err\n}\n\n\/\/ SetAllPwm set a pwm value for all outputs\nfunc (d *Dev) SetAllPwm(on, off gpio.Duty) error {\n\tif _, err := d.dev.Write([]byte{allLedOnL, byte(on)}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.dev.Write([]byte{allLedOnH, byte(on >> 8)}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.dev.Write([]byte{allLedOffL, byte(off)}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.dev.Write([]byte{allLedOffH, byte(off >> 8)}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/ SetPwm set a pwm value for given pca9685 channel\nfunc (d *Dev) SetPwm(channel int, on, off gpio.Duty) error {\n\tif _, err := d.dev.Write([]byte{led0OnL + byte(4*channel), byte(on)}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.dev.Write([]byte{led0OnH + byte(4*channel), byte(on >> 8)}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.dev.Write([]byte{led0OffL + byte(4*channel), byte(off)}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.dev.Write([]byte{led0OffH + byte(4*channel), byte(off >> 8)}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>pca9685: cleanup (#414)<commit_after>\/\/ Copyright 2018 The Periph Authors. All rights reserved.\n\/\/ Use of this source code is governed under the Apache License, Version 2.0\n\/\/ that can be found in the LICENSE file.\n\npackage pca9685\n\nimport (\n\t\"time\"\n\n\t\"periph.io\/x\/periph\/conn\/gpio\"\n\t\"periph.io\/x\/periph\/conn\/i2c\"\n\t\"periph.io\/x\/periph\/conn\/physic\"\n)\n\n\/\/ I2CAddr i2c default address.\nconst I2CAddr uint16 = 0x40\n\n\/\/ PCA9685 registers.\nconst (\n\tmode1    byte = 0x00\n\tmode2    byte = 0x01\n\tprescale byte = 0xFE\n\t\/\/ Each channel has two 12-bit registers (on & off time).\n\tled0OnL   byte = 0x06 \/\/ Start address for setting channel 0.\n\tallLedOnL byte = 0xFA \/\/ Start address for setting all channels.\n)\n\n\/\/ Mode register 1, mode1.\nconst (\n\trestart byte = 0x80\n\tai      byte = 0x20 \/\/ Auto-increment register after each read and write.\n\tsleep   byte = 0x10\n\tallCall byte = 0x01\n)\n\n\/\/ Mode register 2, mode2.\nconst (\n\tinvrt  byte = 0x10\n\toutDrv byte = 0x04\n)\n\n\/\/ Dev is a handler to pca9685 controller.\ntype Dev struct {\n\tdev *i2c.Dev\n}\n\n\/\/ NewI2C returns a Dev object that communicates over I2C.\n\/\/\n\/\/ To use on the default address, pca9685.I2CAddr must be passed as argument.\nfunc NewI2C(bus i2c.Bus, address uint16) (*Dev, error) {\n\tdev := &Dev{\n\t\tdev: &i2c.Dev{Bus: bus, Addr: address},\n\t}\n\terr := dev.init()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn dev, nil\n}\n\nfunc (d *Dev) init() error {\n\tif err := d.SetAllPwm(0, 0); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := d.dev.Write([]byte{mode2, outDrv}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.dev.Write([]byte{mode1, allCall}); err != nil {\n\t\treturn err\n\t}\n\n\ttime.Sleep(100 * time.Millisecond)\n\n\tmodeRead := [1]byte{}\n\tif err := d.dev.Tx([]byte{mode1}, modeRead[:]); err != nil {\n\t\treturn err\n\t}\n\n\tmode := (modeRead[0] & ^sleep) | ai\n\tif _, err := d.dev.Write([]byte{mode1, mode}); err != nil {\n\t\treturn err\n\t}\n\n\ttime.Sleep(5 * time.Millisecond)\n\n\treturn d.SetPwmFreq(50 * physic.Hertz)\n}\n\n\/\/ SetPwmFreq set the PWM frequency.\nfunc (d *Dev) SetPwmFreq(freqHz physic.Frequency) error {\n\tp := (25*physic.MegaHertz\/4096 + freqHz\/2) \/ freqHz\n\n\tmodeRead := [1]byte{}\n\tif err := d.dev.Tx([]byte{mode1}, modeRead[:]); err != nil {\n\t\treturn err\n\t}\n\n\toldmode := modeRead[0]\n\tif _, err := d.dev.Write([]byte{mode1, (oldmode & ^restart) | sleep}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.dev.Write([]byte{prescale, byte(p)}); err != nil {\n\t\treturn err\n\t}\n\tif _, err := d.dev.Write([]byte{mode1, oldmode}); err != nil {\n\t\treturn err\n\t}\n\n\ttime.Sleep(100 * time.Millisecond)\n\n\t_, err := d.dev.Write([]byte{mode1, oldmode | restart})\n\treturn err\n}\n\n\/\/ setPWM writes a PWM value in a specific register.\nfunc (d *Dev) setPWM(register uint8, on, off gpio.Duty) error {\n\t\/\/ Chained writes are possible due to auto-increment.\n\t_, err := d.dev.Write([]byte{\n\t\tregister,\n\t\tbyte(on),\n\t\tbyte(on >> 8),\n\t\tbyte(off),\n\t\tbyte(off >> 8),\n\t})\n\treturn err\n}\n\n\/\/ SetAllPwm set a PWM value for all outputs.\nfunc (d *Dev) SetAllPwm(on, off gpio.Duty) error {\n\treturn d.setPWM(allLedOnL, on, off)\n}\n\n\/\/ SetPwm set a PWM value for a given PCA9685 channel.\nfunc (d *Dev) SetPwm(channel int, on, off gpio.Duty) error {\n\treturn d.setPWM(led0OnL+byte(4*channel), on, off)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Factom Foundation\n\/\/ Use of this source code is governed by the MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage wallet\n\nimport (\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\n\t\"github.com\/FactomProject\/btcutil\/base58\"\n\t\"github.com\/FactomProject\/factom\"\n\t\"github.com\/FactomProject\/factomd\/common\/factoid\"\n\/\/\t\"github.com\/FactomProject\/factomd\/common\/interfaces\"\n\t\"github.com\/FactomProject\/factomd\/common\/primitives\"\n)\n\nvar (\n\tErrTXExists      = errors.New(\"wallet: Transaction name already exists\")\n\tErrTXNotExists   = errors.New(\"wallet: Transaction name was not found\")\n\tErrTXInvalidName = errors.New(\"wallet: Transaction name is not valid\")\n)\n\nfunc (w *Wallet) NewTransaction(name string) error {\n\tif _, exist := w.transactions[name]; exist {\n\t\treturn ErrTXExists\n\t}\n\n\t\/\/ check that the transaction name is valid\n\tif name == \"\" {\n\t\treturn ErrTXInvalidName\n\t}\n\tif len(name) > 32 {\n\t\treturn ErrTXInvalidName\n\t}\n\tif match, err := regexp.MatchString(\"[^a-zA-Z0-9_-]\", name); err != nil {\n\t\treturn err\n\t} else if match {\n\t\treturn ErrTXInvalidName\n\t}\n\n\tt := new(factoid.Transaction)\n\/\/\tt.SetTimestamp(*interfaces.NewTimestampNow())\n\tw.transactions[name] = t\n\treturn nil\n}\n\nfunc (w *Wallet) DeleteTransaction(name string) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\tdelete(w.transactions, name)\n\treturn nil\n}\n\nfunc (w *Wallet) AddInput(name, address string, amount uint64) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\ta, err := w.GetFCTAddress(address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tadr := factoid.NewAddress(a.RCDHash())\n\n\t\/\/ First look if this is really an update\n\tfor _, input := range trans.GetInputs() {\n\t\tif input.GetAddress().IsSameAs(adr) {\n\t\t\tinput.SetAmount(amount)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t\/\/ Add our new input\n\ttrans.AddInput(adr, amount)\n\ttrans.AddRCD(factoid.NewRCD_1(a.PubBytes()))\n\n\treturn nil\n}\n\nfunc (w *Wallet) AddOutput(name, address string, amount uint64) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\tif !factom.IsValidAddress(address) {\n\t\treturn errors.New(\"Invalid Address\")\n\t}\n\n\tadr := factoid.NewAddress(base58.Decode(address)[2:34])\n\n\ttrans.AddOutput(adr, amount)\n\n\treturn nil\n}\n\nfunc (w *Wallet) AddECOutput(name, address string, amount uint64) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\tif !factom.IsValidAddress(address) {\n\t\treturn errors.New(\"Invalid Address\")\n\t}\n\n\tadr := factoid.NewAddress(base58.Decode(address)[2:34])\n\n\ttrans.AddECOutput(adr, amount)\n\n\treturn nil\n}\n\nfunc (w *Wallet) AddFee(name, address string, rate uint64) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\t{\n\t\tins, err := trans.TotalInputs()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\touts, err := trans.TotalOutputs()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tecs, err := trans.TotalECs()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif ins != outs+ecs {\n\t\t\treturn fmt.Errorf(\"Inputs and outputs don't add up\")\n\t\t}\n\t}\n\n\ttransfee, err := trans.CalculateFee(rate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ta, err := w.GetFCTAddress(address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tadr := factoid.NewAddress(a.RCDHash())\n\n\tfor _, input := range trans.GetInputs() {\n\t\tif input.GetAddress().IsSameAs(adr) {\n\t\t\tamt, err := factoid.ValidateAmounts(input.GetAmount(), transfee)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tinput.SetAmount(amt)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"%s is not an input to the transaction.\", address)\n}\n\nfunc (w *Wallet) SubFee(name, address string, rate uint64) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\tif !factom.IsValidAddress(address) {\n\t\treturn errors.New(\"Invalid Address\")\n\t}\n\n\t{\n\t\tins, err := trans.TotalInputs()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\touts, err := trans.TotalOutputs()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tecs, err := trans.TotalECs()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif ins != outs+ecs {\n\t\t\treturn fmt.Errorf(\"Inputs and outputs don't add up\")\n\t\t}\n\t}\n\n\ttransfee, err := trans.CalculateFee(rate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tadr := factoid.NewAddress(base58.Decode(address)[2:34])\n\n\tfor _, output := range trans.GetOutputs() {\n\t\tif output.GetAddress().IsSameAs(adr) {\n\t\t\toutput.SetAmount(output.GetAmount() - transfee)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"%s is not an output to the transaction.\", address)\n}\n\nfunc (w *Wallet) SignTransaction(name string) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\tdata, err := trans.MarshalBinarySig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i, rcd := range trans.GetRCDs() {\n\t\ta, err := rcd.GetAddress()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tf, err := w.GetFCTAddress(primitives.ConvertFctAddressToUserStr(a))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsig := factoid.NewSingleSignatureBlock(f.SecBytes(), data)\n\t\ttrans.SetSignatureBlock(i, sig)\n\t}\n\n\treturn nil\n}\n\nfunc (w *Wallet) GetTransactions() map[string]*factoid.Transaction {\n\treturn w.transactions\n}\n\nfunc (w *Wallet) ComposeTransaction(name string) (*factom.JSON2Request, error) {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn nil, ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\ttype txreq struct {\n\t\tTransaction string `json:\"transaction\"`\n\t}\n\n\tparam := new(txreq)\n\tif p, err := trans.MarshalBinary(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tparam.Transaction = hex.EncodeToString(p)\n\t}\n\n\treq := factom.NewJSON2Request(\"factoid-submit\", apiCounter(), param)\n\n\treturn req, nil\n}\n<commit_msg>wallet now makes valid transactions<commit_after>\/\/ Copyright 2016 Factom Foundation\n\/\/ Use of this source code is governed by the MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage wallet\n\nimport (\n\t\"encoding\/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\n\t\"github.com\/FactomProject\/btcutil\/base58\"\n\t\"github.com\/FactomProject\/factom\"\n\t\"github.com\/FactomProject\/factomd\/common\/factoid\"\n\t\"github.com\/FactomProject\/factomd\/common\/interfaces\"\n\t\"github.com\/FactomProject\/factomd\/common\/primitives\"\n)\n\nvar (\n\tErrTXExists      = errors.New(\"wallet: Transaction name already exists\")\n\tErrTXNotExists   = errors.New(\"wallet: Transaction name was not found\")\n\tErrTXInvalidName = errors.New(\"wallet: Transaction name is not valid\")\n)\n\nfunc (w *Wallet) NewTransaction(name string) error {\n\tif _, exist := w.transactions[name]; exist {\n\t\treturn ErrTXExists\n\t}\n\n\t\/\/ check that the transaction name is valid\n\tif name == \"\" {\n\t\treturn ErrTXInvalidName\n\t}\n\tif len(name) > 32 {\n\t\treturn ErrTXInvalidName\n\t}\n\tif match, err := regexp.MatchString(\"[^a-zA-Z0-9_-]\", name); err != nil {\n\t\treturn err\n\t} else if match {\n\t\treturn ErrTXInvalidName\n\t}\n\n\tt := new(factoid.Transaction)\n\tt.SetTimestamp(*interfaces.NewTimestampNow())\n\tw.transactions[name] = t\n\treturn nil\n}\n\nfunc (w *Wallet) DeleteTransaction(name string) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\tdelete(w.transactions, name)\n\treturn nil\n}\n\nfunc (w *Wallet) AddInput(name, address string, amount uint64) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\ta, err := w.GetFCTAddress(address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tadr := factoid.NewAddress(a.RCDHash())\n\n\t\/\/ First look if this is really an update\n\tfor _, input := range trans.GetInputs() {\n\t\tif input.GetAddress().IsSameAs(adr) {\n\t\t\tinput.SetAmount(amount)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t\/\/ Add our new input\n\ttrans.AddInput(adr, amount)\n\ttrans.AddRCD(factoid.NewRCD_1(a.PubBytes()))\n\n\treturn nil\n}\n\nfunc (w *Wallet) AddOutput(name, address string, amount uint64) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\tif !factom.IsValidAddress(address) {\n\t\treturn errors.New(\"Invalid Address\")\n\t}\n\n\tadr := factoid.NewAddress(base58.Decode(address)[2:34])\n\n\ttrans.AddOutput(adr, amount)\n\n\treturn nil\n}\n\nfunc (w *Wallet) AddECOutput(name, address string, amount uint64) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\tif !factom.IsValidAddress(address) {\n\t\treturn errors.New(\"Invalid Address\")\n\t}\n\n\tadr := factoid.NewAddress(base58.Decode(address)[2:34])\n\n\ttrans.AddECOutput(adr, amount)\n\n\treturn nil\n}\n\nfunc (w *Wallet) AddFee(name, address string, rate uint64) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\t{\n\t\tins, err := trans.TotalInputs()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\touts, err := trans.TotalOutputs()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tecs, err := trans.TotalECs()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif ins != outs+ecs {\n\t\t\treturn fmt.Errorf(\"Inputs and outputs don't add up\")\n\t\t}\n\t}\n\n\ttransfee, err := trans.CalculateFee(rate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ta, err := w.GetFCTAddress(address)\n\tif err != nil {\n\t\treturn err\n\t}\n\tadr := factoid.NewAddress(a.RCDHash())\n\n\tfor _, input := range trans.GetInputs() {\n\t\tif input.GetAddress().IsSameAs(adr) {\n\t\t\tamt, err := factoid.ValidateAmounts(input.GetAmount(), transfee)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tinput.SetAmount(amt)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"%s is not an input to the transaction.\", address)\n}\n\nfunc (w *Wallet) SubFee(name, address string, rate uint64) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\tif !factom.IsValidAddress(address) {\n\t\treturn errors.New(\"Invalid Address\")\n\t}\n\n\t{\n\t\tins, err := trans.TotalInputs()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\touts, err := trans.TotalOutputs()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tecs, err := trans.TotalECs()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif ins != outs+ecs {\n\t\t\treturn fmt.Errorf(\"Inputs and outputs don't add up\")\n\t\t}\n\t}\n\n\ttransfee, err := trans.CalculateFee(rate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tadr := factoid.NewAddress(base58.Decode(address)[2:34])\n\n\tfor _, output := range trans.GetOutputs() {\n\t\tif output.GetAddress().IsSameAs(adr) {\n\t\t\toutput.SetAmount(output.GetAmount() - transfee)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"%s is not an output to the transaction.\", address)\n}\n\nfunc (w *Wallet) SignTransaction(name string) error {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\tdata, err := trans.MarshalBinarySig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i, rcd := range trans.GetRCDs() {\n\t\ta, err := rcd.GetAddress()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tf, err := w.GetFCTAddress(primitives.ConvertFctAddressToUserStr(a))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tsig := factoid.NewSingleSignatureBlock(f.SecBytes(), data)\n\t\ttrans.SetSignatureBlock(i, sig)\n\t}\n\n\treturn nil\n}\n\nfunc (w *Wallet) GetTransactions() map[string]*factoid.Transaction {\n\treturn w.transactions\n}\n\nfunc (w *Wallet) ComposeTransaction(name string) (*factom.JSON2Request, error) {\n\tif _, exists := w.transactions[name]; !exists {\n\t\treturn nil, ErrTXNotExists\n\t}\n\ttrans := w.transactions[name]\n\n\ttype txreq struct {\n\t\tTransaction string `json:\"transaction\"`\n\t}\n\n\tparam := new(txreq)\n\tif p, err := trans.MarshalBinary(); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tparam.Transaction = hex.EncodeToString(p)\n\t}\n\n\treq := factom.NewJSON2Request(\"factoid-submit\", apiCounter(), param)\n\n\treturn req, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build integration\n\n\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage tests\n\nimport (\n\t\"testing\"\n\t\"github.com\/apache\/incubator-openwhisk-wskdeploy\/tests\/src\/integration\/common\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"os\"\n\t\"fmt\"\n)\n\nvar projectPath = \"\/src\/github.com\/apache\/incubator-openwhisk-wskdeploy\/tests\/apps\/owbp-cloudant-trigger\/runtimes\/\"\n\nfunc TestCloudantTriggerNode(t *testing.T) {\n\tmanifestPath   := os.Getenv(\"GOPATH\") + projectPath + \"node\/manifest.yaml\"\n\tdeploymentPath := \"\"\n\tos.Setenv(\"CLOUDANT_DATABASE\", \"testdb\")\n\twskprops := common.GetWskpropsFromEnvVars(common.BLUEMIX_APIHOST, common.BLUEMIX_NAMESPACE, common.BLUEMIX_AUTH)\n\terr := common.ValidateWskprops(wskprops)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tfmt.Println(\"Wsk properties are not properly configured, so tests are skipped.\")\n\t} else {\n\t\twskdeploy := common.NewWskdeploy()\n\t\t_, err := wskdeploy.DeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to deploy the manifest file.\")\n\t\t_, err = wskdeploy.UndeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to undeploy the manifest file.\")\n\t}\n}\n\nfunc TestCloudantTriggerPhp(t *testing.T) {\n\tmanifestPath   := os.Getenv(\"GOPATH\") + projectPath + \"php\/manifest.yaml\"\n\tdeploymentPath := \"\"\n\tos.Setenv(\"CLOUDANT_DATABASE\", \"testdb\")\n\twskprops := common.GetWskpropsFromEnvVars(common.BLUEMIX_APIHOST, common.BLUEMIX_NAMESPACE, common.BLUEMIX_AUTH)\n\terr := common.ValidateWskprops(wskprops)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tfmt.Println(\"Wsk properties are not properly configured, so tests are skipped.\")\n\t} else {\n\t\twskdeploy := common.NewWskdeploy()\n\t\t_, err := wskdeploy.DeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to deploy the manifest file.\")\n\t\t_, err = wskdeploy.UndeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to undeploy the manifest file.\")\n\t}\n}\n\nfunc TestCloudantTriggerPython(t *testing.T) {\n\tmanifestPath   := os.Getenv(\"GOPATH\") + projectPath + \"python\/manifest.yaml\"\n\tdeploymentPath := \"\"\n\tos.Setenv(\"CLOUDANT_DATABASE\", \"testdb\")\n\twskprops := common.GetWskpropsFromEnvVars(common.BLUEMIX_APIHOST, common.BLUEMIX_NAMESPACE, common.BLUEMIX_AUTH)\n\terr := common.ValidateWskprops(wskprops)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tfmt.Println(\"Wsk properties are not properly configured, so tests are skipped.\")\n\t} else {\n\t\twskdeploy := common.NewWskdeploy()\n\t\t_, err := wskdeploy.DeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to deploy the manifest file.\")\n\t\t_, err = wskdeploy.UndeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to undeploy the manifest file.\")\n\t}\n}\n\nfunc TestCloudantTriggerSwift(t *testing.T) {\n\tmanifestPath   := os.Getenv(\"GOPATH\") + projectPath + \"swift\/manifest.yaml\"\n\tdeploymentPath := \"\"\n\tos.Setenv(\"CLOUDANT_DATABASE\", \"testdb\")\n\twskprops := common.GetWskpropsFromEnvVars(common.BLUEMIX_APIHOST, common.BLUEMIX_NAMESPACE, common.BLUEMIX_AUTH)\n\terr := common.ValidateWskprops(wskprops)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tfmt.Println(\"Wsk properties are not properly configured, so tests are skipped.\")\n\t} else {\n\t\twskdeploy := common.NewWskdeploy()\n\t\t_, err := wskdeploy.DeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to deploy the manifest file.\")\n\t\t_, err = wskdeploy.UndeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to undeploy the manifest file.\")\n\t}\n}\n\n<commit_msg>disable integration test (#600)<commit_after>\/\/ +build skip_integration\n\n\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements.  See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License.  You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage tests\n\nimport (\n\t\"testing\"\n\t\"github.com\/apache\/incubator-openwhisk-wskdeploy\/tests\/src\/integration\/common\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"os\"\n\t\"fmt\"\n)\n\nvar projectPath = \"\/src\/github.com\/apache\/incubator-openwhisk-wskdeploy\/tests\/apps\/owbp-cloudant-trigger\/runtimes\/\"\n\nfunc TestCloudantTriggerNode(t *testing.T) {\n\tmanifestPath   := os.Getenv(\"GOPATH\") + projectPath + \"node\/manifest.yaml\"\n\tdeploymentPath := \"\"\n\tos.Setenv(\"CLOUDANT_DATABASE\", \"testdb\")\n\twskprops := common.GetWskpropsFromEnvVars(common.BLUEMIX_APIHOST, common.BLUEMIX_NAMESPACE, common.BLUEMIX_AUTH)\n\terr := common.ValidateWskprops(wskprops)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tfmt.Println(\"Wsk properties are not properly configured, so tests are skipped.\")\n\t} else {\n\t\twskdeploy := common.NewWskdeploy()\n\t\t_, err := wskdeploy.DeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to deploy the manifest file.\")\n\t\t_, err = wskdeploy.UndeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to undeploy the manifest file.\")\n\t}\n}\n\nfunc TestCloudantTriggerPhp(t *testing.T) {\n\tmanifestPath   := os.Getenv(\"GOPATH\") + projectPath + \"php\/manifest.yaml\"\n\tdeploymentPath := \"\"\n\tos.Setenv(\"CLOUDANT_DATABASE\", \"testdb\")\n\twskprops := common.GetWskpropsFromEnvVars(common.BLUEMIX_APIHOST, common.BLUEMIX_NAMESPACE, common.BLUEMIX_AUTH)\n\terr := common.ValidateWskprops(wskprops)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tfmt.Println(\"Wsk properties are not properly configured, so tests are skipped.\")\n\t} else {\n\t\twskdeploy := common.NewWskdeploy()\n\t\t_, err := wskdeploy.DeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to deploy the manifest file.\")\n\t\t_, err = wskdeploy.UndeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to undeploy the manifest file.\")\n\t}\n}\n\nfunc TestCloudantTriggerPython(t *testing.T) {\n\tmanifestPath   := os.Getenv(\"GOPATH\") + projectPath + \"python\/manifest.yaml\"\n\tdeploymentPath := \"\"\n\tos.Setenv(\"CLOUDANT_DATABASE\", \"testdb\")\n\twskprops := common.GetWskpropsFromEnvVars(common.BLUEMIX_APIHOST, common.BLUEMIX_NAMESPACE, common.BLUEMIX_AUTH)\n\terr := common.ValidateWskprops(wskprops)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tfmt.Println(\"Wsk properties are not properly configured, so tests are skipped.\")\n\t} else {\n\t\twskdeploy := common.NewWskdeploy()\n\t\t_, err := wskdeploy.DeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to deploy the manifest file.\")\n\t\t_, err = wskdeploy.UndeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to undeploy the manifest file.\")\n\t}\n}\n\nfunc TestCloudantTriggerSwift(t *testing.T) {\n\tmanifestPath   := os.Getenv(\"GOPATH\") + projectPath + \"swift\/manifest.yaml\"\n\tdeploymentPath := \"\"\n\tos.Setenv(\"CLOUDANT_DATABASE\", \"testdb\")\n\twskprops := common.GetWskpropsFromEnvVars(common.BLUEMIX_APIHOST, common.BLUEMIX_NAMESPACE, common.BLUEMIX_AUTH)\n\terr := common.ValidateWskprops(wskprops)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tfmt.Println(\"Wsk properties are not properly configured, so tests are skipped.\")\n\t} else {\n\t\twskdeploy := common.NewWskdeploy()\n\t\t_, err := wskdeploy.DeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to deploy the manifest file.\")\n\t\t_, err = wskdeploy.UndeployWithCredentials(manifestPath, deploymentPath, wskprops)\n\t\tassert.Equal(t, nil, err, \"Failed to undeploy the manifest file.\")\n\t}\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 trivago GmbH\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage producer\n\nimport (\n\t\"compress\/gzip\"\n\t\"fmt\"\n\t\"github.com\/trivago\/gollum\/core\"\n\t\"github.com\/trivago\/gollum\/core\/log\"\n\t\"github.com\/trivago\/gollum\/shared\"\n\t\"hash\/fnv\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tfileProducerTimestamp = \"2006-01-02_15\"\n)\n\n\/\/ File producer plugin\n\/\/ Configuration example\n\/\/\n\/\/   - \"producer.File\":\n\/\/     Enable: true\n\/\/     File: \"\/var\/log\/gollum.log\"\n\/\/     BatchSizeMaxKB: 16384\n\/\/     BatchSizeByte: 4096\n\/\/     BatchTimeoutSec: 2\n\/\/     Rotate: false\n\/\/     RotateTimeoutMin: 1440\n\/\/     RotateSizeMB: 1024\n\/\/     RotateAt: \"00:00\"\n\/\/     Compress: true\n\/\/\n\/\/ The file producer writes messages to a file. This producer also allows log\n\/\/ rotation and compression of the rotated logs.\n\/\/\n\/\/ File contains the path to the log file to write. The wildcard \"*\" will be\n\/\/ replaced by the stream name.\n\/\/ By default this is set to \/var\/prod\/gollum.log.\n\/\/\n\/\/ BatchSizeMaxKB defines the internal file buffer size in KB.\n\/\/ This producers allocates a front- and a backbuffer of this size. If the\n\/\/ frontbuffer is filled up completely a flush is triggered and the frontbuffer\n\/\/ becomes available for writing again. Messages larger than BatchSizeMaxKB are\n\/\/ rejected.\n\/\/\n\/\/ BatchSizeByte defines the number of bytes to be buffered before they are written\n\/\/ to disk. By default this is set to 8KB.\n\/\/\n\/\/ BatchTimeoutSec defines the maximum number of seconds to wait after the last\n\/\/ message arrived before a batch is flushed automatically. By default this is\n\/\/ set to 5..\n\/\/\n\/\/ Rotate if set to true the logs will rotate after reaching certain thresholds.\n\/\/\n\/\/ RotateTimeoutMin defines a timeout in minutes that will cause the logs to\n\/\/ rotate. Can be set in parallel with RotateSizeMB. By default this is set to\n\/\/ 1440 (i.e. 1 Day).\n\/\/\n\/\/ RotateAt defines specific timestamp as in \"HH:MM\" when the log should be\n\/\/ rotated. Hours must be given in 24h format. When left empty this setting is\n\/\/ ignored. By default this setting is disabled.\n\/\/\n\/\/ Compress defines if a rotated logfile is to be gzip compressed or not.\n\/\/ By default this is set to false.\ntype File struct {\n\tcore.ProducerBase\n\tfilesByStream    map[core.MessageStreamID]*fileLogState\n\tfiles            map[uint32]*fileLogState\n\tfileDir          string\n\tfileName         string\n\tfileExt          string\n\twildcardPath     bool\n\trotateSizeByte   int64\n\tbufferSizeMax    int\n\tbatchSize        int\n\tbatchTimeout     time.Duration\n\trotateTimeoutMin int\n\trotateAtHour     int\n\trotateAtMin      int\n\trotate           bool\n\tcompress         bool\n}\n\ntype fileLogState struct {\n\tfile        *os.File\n\tbatch       *core.MessageBatch\n\tbgWriter    *sync.WaitGroup\n\tfileCreated time.Time\n}\n\nfunc init() {\n\tshared.RuntimeType.Register(File{})\n}\n\nfunc newFileLogState(bufferSizeMax int, format core.Formatter) *fileLogState {\n\treturn &fileLogState{\n\t\tbatch:    core.NewMessageBatch(bufferSizeMax, format),\n\t\tbgWriter: new(sync.WaitGroup),\n\t}\n}\n\n\/\/ Configure initializes this producer with values from a plugin config.\nfunc (prod *File) Configure(conf core.PluginConfig) error {\n\terr := prod.ProducerBase.Configure(conf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprod.filesByStream = make(map[core.MessageStreamID]*fileLogState)\n\tprod.files = make(map[uint32]*fileLogState)\n\tprod.bufferSizeMax = conf.GetInt(\"BatchSizeMaxKB\", 8<<10) << 10 \/\/ 8 MB\n\n\tprod.batchSize = conf.GetInt(\"BatchSizeByte\", 8192)\n\tprod.batchTimeout = time.Duration(conf.GetInt(\"BatchTimeoutSec\", 5)) * time.Second\n\n\tprod.rotate = conf.GetBool(\"Rotate\", false)\n\tprod.rotateTimeoutMin = conf.GetInt(\"RotateTimeoutMin\", 1440)\n\tprod.rotateSizeByte = int64(conf.GetInt(\"RotateSizeMB\", 1024)) << 20\n\tprod.rotateAtHour = -1\n\tprod.rotateAtMin = -1\n\tprod.compress = conf.GetBool(\"Compress\", false)\n\n\tlogFile := conf.GetString(\"File\", \"\/var\/prod\/gollum.log\")\n\tprod.wildcardPath = strings.IndexByte(logFile, '*') != -1\n\n\tprod.fileDir = filepath.Dir(logFile)\n\tprod.fileExt = filepath.Ext(logFile)\n\tprod.fileName = filepath.Base(logFile)\n\tprod.fileName = prod.fileName[:len(prod.fileName)-len(prod.fileExt)]\n\n\trotateAt := conf.GetString(\"RotateAt\", \"\")\n\tif rotateAt != \"\" {\n\t\tparts := strings.Split(rotateAt, \":\")\n\t\trotateAtHour, _ := strconv.ParseInt(parts[0], 10, 8)\n\t\trotateAtMin, _ := strconv.ParseInt(parts[1], 10, 8)\n\n\t\tprod.rotateAtHour = int(rotateAtHour)\n\t\tprod.rotateAtMin = int(rotateAtMin)\n\t}\n\n\treturn nil\n}\n\nfunc (state *fileLogState) compressAndCloseLog(sourceFile *os.File) {\n\tstate.bgWriter.Add(1)\n\tdefer state.bgWriter.Done()\n\n\t\/\/ Generate file to zip into\n\tsourceFileName := sourceFile.Name()\n\tsourceDir := filepath.Dir(sourceFileName)\n\tsourceExt := filepath.Ext(sourceFileName)\n\tsourceBase := filepath.Base(sourceFileName)\n\tsourceBase = sourceBase[:len(sourceBase)-len(sourceExt)]\n\n\ttargetFileName := fmt.Sprintf(\"%s\/%s.gz\", sourceDir, sourceBase)\n\n\ttargetFile, err := os.OpenFile(targetFileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)\n\tif err != nil {\n\t\tLog.Error.Print(\"File compress error:\", err)\n\t\tsourceFile.Close()\n\t\treturn\n\t}\n\n\t\/\/ Create zipfile and compress data\n\tLog.Note.Print(\"Compressing \" + sourceFileName)\n\n\tsourceFile.Seek(0, 0)\n\ttargetWriter := gzip.NewWriter(targetFile)\n\n\tfor err == nil {\n\t\t_, err = io.CopyN(targetWriter, sourceFile, 1<<20) \/\/ 1 MB chunks\n\t\truntime.Gosched()                                  \/\/ Be async!\n\t}\n\n\t\/\/ Cleanup\n\tsourceFile.Close()\n\ttargetWriter.Close()\n\ttargetFile.Close()\n\n\tif err != nil && err != io.EOF {\n\t\tLog.Warning.Print(\"Compression failed:\", err)\n\t\terr = os.Remove(targetFileName)\n\t\tif err != nil {\n\t\t\tLog.Error.Print(\"Compressed file remove failed:\", err)\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ Remove original log\n\terr = os.Remove(sourceFileName)\n\tif err != nil {\n\t\tLog.Error.Print(\"Uncompressed file remove failed:\", err)\n\t}\n}\n\nfunc (state *fileLogState) onWriterError(err error) bool {\n\tLog.Error.Print(\"File write error:\", err)\n\treturn false\n}\n\nfunc (state *fileLogState) writeBatch() {\n\tstate.batch.Flush(state.file, nil, state.onWriterError)\n}\n\nfunc (state *fileLogState) needsRotate(prod *File, forceRotate bool) (bool, error) {\n\t\/\/ File does not exist?\n\tif state.file == nil {\n\t\treturn true, nil\n\t}\n\n\t\/\/ File can be accessed?\n\tstats, err := state.file.Stat()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ File needs rotation?\n\tif !prod.rotate {\n\t\treturn false, nil\n\t}\n\n\tif forceRotate {\n\t\treturn true, nil\n\t}\n\n\t\/\/ File is too large?\n\tif stats.Size() >= prod.rotateSizeByte {\n\t\treturn true, nil \/\/ ### return, too large ###\n\t}\n\n\t\/\/ File is too old?\n\tif time.Since(state.fileCreated).Minutes() >= float64(prod.rotateTimeoutMin) {\n\t\treturn true, nil \/\/ ### return, too old ###\n\t}\n\n\t\/\/ RotateAt crossed?\n\tif prod.rotateAtHour > -1 && prod.rotateAtMin > -1 {\n\t\tnow := time.Now()\n\t\trotateAt := time.Date(now.Year(), now.Month(), now.Day(), prod.rotateAtHour, prod.rotateAtMin, 0, 0, now.Location())\n\n\t\tif state.fileCreated.Sub(rotateAt).Minutes() < 0 {\n\t\t\treturn true, nil \/\/ ### return, too old ###\n\t\t}\n\t}\n\n\t\/\/ nope, everything is ok\n\treturn false, nil\n}\n\nfunc (prod *File) getFileLogState(streamID core.MessageStreamID, forceRotate bool) (*fileLogState, error) {\n\tif state, stateExists := prod.filesByStream[streamID]; stateExists {\n\t\tif rotate, err := state.needsRotate(prod, forceRotate); !rotate {\n\t\t\treturn state, err \/\/ ### return, already open or error ###\n\t\t}\n\t}\n\n\tvar logFileName, fileDir, fileName, fileExt string\n\tvar fileID uint32\n\n\tif prod.wildcardPath {\n\t\t\/\/ Get state from filename (without timestamp, etc.)\n\t\tvar streamName string\n\t\tswitch streamID {\n\t\tcase core.WildcardStreamID:\n\t\t\tstreamName = \"all\"\n\t\tcase core.LogInternalStreamID:\n\t\t\tstreamName = \"gollum\"\n\t\tcase core.DroppedStreamID:\n\t\t\tstreamName = \"dropped\"\n\t\tdefault:\n\t\t\tstreamName = core.StreamTypes.GetStreamName(streamID)\n\t\t}\n\n\t\tfileDir = strings.Replace(prod.fileDir, \"*\", streamName, -1)\n\t\tfileName = strings.Replace(prod.fileName, \"*\", streamName, -1)\n\t\tfileExt = strings.Replace(prod.fileExt, \"*\", streamName, -1)\n\n\t\t\/\/ Hash the base name\n\t\thash := fnv.New32a()\n\t\thash.Write([]byte(fmt.Sprintf(\"%s\/%s%s\", fileDir, fileName, fileExt)))\n\t\tfileID = hash.Sum32()\n\t} else {\n\t\t\/\/ Simple case: only one file used\n\t\tfileDir = prod.fileDir\n\t\tfileName = prod.fileName\n\t\tfileExt = prod.fileExt\n\t\tfileID = 0\n\t}\n\n\t\/\/ Assure the file is correctly mapped\n\tstate, stateExists := prod.files[fileID]\n\tif !stateExists {\n\t\t\/\/ state does not yet exist: create and map it\n\t\tstate = newFileLogState(prod.bufferSizeMax, prod.ProducerBase.GetFormatter())\n\t\tprod.files[fileID] = state\n\t\tprod.filesByStream[streamID] = state\n\t} else if _, mappingExists := prod.filesByStream[streamID]; !mappingExists {\n\t\t\/\/ state exists but is not mapped: map it and see if we need to rotate\n\t\tprod.filesByStream[streamID] = state\n\t\tif rotate, err := state.needsRotate(prod, forceRotate); !rotate {\n\t\t\treturn state, err \/\/ ### return, already open or error ###\n\t\t}\n\t}\n\n\t\/\/ Generate the log filename based on rotation, existing files, etc.\n\tif !prod.rotate {\n\t\tlogFileName = fmt.Sprintf(\"%s%s\", fileName, fileExt)\n\t} else {\n\t\ttimestamp := time.Now().Format(fileProducerTimestamp)\n\t\tsignature := fmt.Sprintf(\"%s_%s\", fileName, timestamp)\n\t\tcounter := 0\n\n\t\tif err := os.MkdirAll(fileDir, 0755); err != nil {\n\t\t\tLog.Error.Print(\"Error creating directory \" + fileDir)\n\t\t}\n\n\t\tfiles, _ := ioutil.ReadDir(fileDir)\n\t\tfor _, file := range files {\n\t\t\tif strings.Contains(file.Name(), signature) {\n\t\t\t\tcounter++\n\t\t\t}\n\t\t}\n\n\t\tif counter == 0 {\n\t\t\tlogFileName = fmt.Sprintf(\"%s%s\", signature, fileExt)\n\t\t} else {\n\t\t\tlogFileName = fmt.Sprintf(\"%s_%d%s\", signature, counter, fileExt)\n\t\t}\n\t}\n\n\tlogFile := fmt.Sprintf(\"%s\/%s\", fileDir, logFileName)\n\n\t\/\/ Close existing log\n\tif state.file != nil {\n\t\tcurrentLog := state.file\n\t\tstate.file = nil\n\n\t\tif prod.compress {\n\t\t\tgo state.compressAndCloseLog(currentLog)\n\t\t} else {\n\t\t\tLog.Note.Print(\"Rotated \" + currentLog.Name())\n\t\t\tcurrentLog.Close()\n\t\t}\n\t}\n\n\t\/\/ (Re)open logfile\n\tvar err error\n\tstate.file, err = os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)\n\tif err != nil {\n\t\treturn state, err \/\/ ### return error ###\n\t}\n\n\t\/\/ Create \"current\" symlink\n\tstate.fileCreated = time.Now()\n\tif prod.rotate {\n\t\tsymLinkName := fmt.Sprintf(\"%s\/%s_current\", fileDir, fileName)\n\t\tos.Remove(symLinkName)\n\t\tos.Symlink(logFileName, symLinkName)\n\t}\n\n\treturn state, err\n}\n\nfunc (prod *File) writeBatchOnTimeOut() {\n\tfor _, state := range prod.files {\n\t\tif state.batch.ReachedTimeThreshold(prod.batchTimeout) || state.batch.ReachedSizeThreshold(prod.batchSize) {\n\t\t\tstate.writeBatch()\n\t\t}\n\t}\n}\n\nfunc (prod *File) writeMessage(msg core.Message) {\n\tstate, err := prod.getFileLogState(msg.StreamID, false)\n\tif err != nil {\n\t\tLog.Error.Print(\"File log error:\", err)\n\t\tmsg.Drop(time.Duration(0))\n\t\treturn \/\/ ### return, dropped ###\n\t}\n\n\tif !state.batch.Append(msg) {\n\t\tstate.writeBatch()\n\t\tstate.batch.Append(msg)\n\t}\n}\n\nfunc (prod *File) rotateLog() {\n\tfor streamID := range prod.filesByStream {\n\t\tif _, err := prod.getFileLogState(streamID, true); err != nil {\n\t\t\tLog.Error.Print(\"File rotate error:\", err)\n\t\t}\n\t}\n}\n\nfunc (prod *File) flush() {\n\tfor _, state := range prod.files {\n\t\tstate.writeBatch()\n\t\tstate.batch.WaitForFlush(5 * time.Second)\n\n\t\tstate.bgWriter.Wait()\n\t\tstate.file.Close()\n\t}\n\tprod.WorkerDone()\n}\n\n\/\/ Produce writes to a buffer that is dumped to a file.\nfunc (prod *File) Produce(workers *sync.WaitGroup) {\n\tdefer prod.flush()\n\n\tprod.AddMainWorker(workers)\n\tprod.TickerControlLoop(prod.batchTimeout, prod.writeMessage, prod.rotateLog, prod.writeBatchOnTimeOut)\n}\n<commit_msg>File producer symlink uses file extension<commit_after>\/\/ Copyright 2015 trivago GmbH\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage producer\n\nimport (\n\t\"compress\/gzip\"\n\t\"fmt\"\n\t\"github.com\/trivago\/gollum\/core\"\n\t\"github.com\/trivago\/gollum\/core\/log\"\n\t\"github.com\/trivago\/gollum\/shared\"\n\t\"hash\/fnv\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst (\n\tfileProducerTimestamp = \"2006-01-02_15\"\n)\n\n\/\/ File producer plugin\n\/\/ Configuration example\n\/\/\n\/\/   - \"producer.File\":\n\/\/     Enable: true\n\/\/     File: \"\/var\/log\/gollum.log\"\n\/\/     BatchSizeMaxKB: 16384\n\/\/     BatchSizeByte: 4096\n\/\/     BatchTimeoutSec: 2\n\/\/     Rotate: false\n\/\/     RotateTimeoutMin: 1440\n\/\/     RotateSizeMB: 1024\n\/\/     RotateAt: \"00:00\"\n\/\/     Compress: true\n\/\/\n\/\/ The file producer writes messages to a file. This producer also allows log\n\/\/ rotation and compression of the rotated logs.\n\/\/\n\/\/ File contains the path to the log file to write. The wildcard \"*\" will be\n\/\/ replaced by the stream name.\n\/\/ By default this is set to \/var\/prod\/gollum.log.\n\/\/\n\/\/ BatchSizeMaxKB defines the internal file buffer size in KB.\n\/\/ This producers allocates a front- and a backbuffer of this size. If the\n\/\/ frontbuffer is filled up completely a flush is triggered and the frontbuffer\n\/\/ becomes available for writing again. Messages larger than BatchSizeMaxKB are\n\/\/ rejected.\n\/\/\n\/\/ BatchSizeByte defines the number of bytes to be buffered before they are written\n\/\/ to disk. By default this is set to 8KB.\n\/\/\n\/\/ BatchTimeoutSec defines the maximum number of seconds to wait after the last\n\/\/ message arrived before a batch is flushed automatically. By default this is\n\/\/ set to 5..\n\/\/\n\/\/ Rotate if set to true the logs will rotate after reaching certain thresholds.\n\/\/\n\/\/ RotateTimeoutMin defines a timeout in minutes that will cause the logs to\n\/\/ rotate. Can be set in parallel with RotateSizeMB. By default this is set to\n\/\/ 1440 (i.e. 1 Day).\n\/\/\n\/\/ RotateAt defines specific timestamp as in \"HH:MM\" when the log should be\n\/\/ rotated. Hours must be given in 24h format. When left empty this setting is\n\/\/ ignored. By default this setting is disabled.\n\/\/\n\/\/ Compress defines if a rotated logfile is to be gzip compressed or not.\n\/\/ By default this is set to false.\ntype File struct {\n\tcore.ProducerBase\n\tfilesByStream    map[core.MessageStreamID]*fileLogState\n\tfiles            map[uint32]*fileLogState\n\tfileDir          string\n\tfileName         string\n\tfileExt          string\n\twildcardPath     bool\n\trotateSizeByte   int64\n\tbufferSizeMax    int\n\tbatchSize        int\n\tbatchTimeout     time.Duration\n\trotateTimeoutMin int\n\trotateAtHour     int\n\trotateAtMin      int\n\trotate           bool\n\tcompress         bool\n}\n\ntype fileLogState struct {\n\tfile        *os.File\n\tbatch       *core.MessageBatch\n\tbgWriter    *sync.WaitGroup\n\tfileCreated time.Time\n}\n\nfunc init() {\n\tshared.RuntimeType.Register(File{})\n}\n\nfunc newFileLogState(bufferSizeMax int, format core.Formatter) *fileLogState {\n\treturn &fileLogState{\n\t\tbatch:    core.NewMessageBatch(bufferSizeMax, format),\n\t\tbgWriter: new(sync.WaitGroup),\n\t}\n}\n\n\/\/ Configure initializes this producer with values from a plugin config.\nfunc (prod *File) Configure(conf core.PluginConfig) error {\n\terr := prod.ProducerBase.Configure(conf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprod.filesByStream = make(map[core.MessageStreamID]*fileLogState)\n\tprod.files = make(map[uint32]*fileLogState)\n\tprod.bufferSizeMax = conf.GetInt(\"BatchSizeMaxKB\", 8<<10) << 10 \/\/ 8 MB\n\n\tprod.batchSize = conf.GetInt(\"BatchSizeByte\", 8192)\n\tprod.batchTimeout = time.Duration(conf.GetInt(\"BatchTimeoutSec\", 5)) * time.Second\n\n\tprod.rotate = conf.GetBool(\"Rotate\", false)\n\tprod.rotateTimeoutMin = conf.GetInt(\"RotateTimeoutMin\", 1440)\n\tprod.rotateSizeByte = int64(conf.GetInt(\"RotateSizeMB\", 1024)) << 20\n\tprod.rotateAtHour = -1\n\tprod.rotateAtMin = -1\n\tprod.compress = conf.GetBool(\"Compress\", false)\n\n\tlogFile := conf.GetString(\"File\", \"\/var\/prod\/gollum.log\")\n\tprod.wildcardPath = strings.IndexByte(logFile, '*') != -1\n\n\tprod.fileDir = filepath.Dir(logFile)\n\tprod.fileExt = filepath.Ext(logFile)\n\tprod.fileName = filepath.Base(logFile)\n\tprod.fileName = prod.fileName[:len(prod.fileName)-len(prod.fileExt)]\n\n\trotateAt := conf.GetString(\"RotateAt\", \"\")\n\tif rotateAt != \"\" {\n\t\tparts := strings.Split(rotateAt, \":\")\n\t\trotateAtHour, _ := strconv.ParseInt(parts[0], 10, 8)\n\t\trotateAtMin, _ := strconv.ParseInt(parts[1], 10, 8)\n\n\t\tprod.rotateAtHour = int(rotateAtHour)\n\t\tprod.rotateAtMin = int(rotateAtMin)\n\t}\n\n\treturn nil\n}\n\nfunc (state *fileLogState) compressAndCloseLog(sourceFile *os.File) {\n\tstate.bgWriter.Add(1)\n\tdefer state.bgWriter.Done()\n\n\t\/\/ Generate file to zip into\n\tsourceFileName := sourceFile.Name()\n\tsourceDir := filepath.Dir(sourceFileName)\n\tsourceExt := filepath.Ext(sourceFileName)\n\tsourceBase := filepath.Base(sourceFileName)\n\tsourceBase = sourceBase[:len(sourceBase)-len(sourceExt)]\n\n\ttargetFileName := fmt.Sprintf(\"%s\/%s.gz\", sourceDir, sourceBase)\n\n\ttargetFile, err := os.OpenFile(targetFileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)\n\tif err != nil {\n\t\tLog.Error.Print(\"File compress error:\", err)\n\t\tsourceFile.Close()\n\t\treturn\n\t}\n\n\t\/\/ Create zipfile and compress data\n\tLog.Note.Print(\"Compressing \" + sourceFileName)\n\n\tsourceFile.Seek(0, 0)\n\ttargetWriter := gzip.NewWriter(targetFile)\n\n\tfor err == nil {\n\t\t_, err = io.CopyN(targetWriter, sourceFile, 1<<20) \/\/ 1 MB chunks\n\t\truntime.Gosched()                                  \/\/ Be async!\n\t}\n\n\t\/\/ Cleanup\n\tsourceFile.Close()\n\ttargetWriter.Close()\n\ttargetFile.Close()\n\n\tif err != nil && err != io.EOF {\n\t\tLog.Warning.Print(\"Compression failed:\", err)\n\t\terr = os.Remove(targetFileName)\n\t\tif err != nil {\n\t\t\tLog.Error.Print(\"Compressed file remove failed:\", err)\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ Remove original log\n\terr = os.Remove(sourceFileName)\n\tif err != nil {\n\t\tLog.Error.Print(\"Uncompressed file remove failed:\", err)\n\t}\n}\n\nfunc (state *fileLogState) onWriterError(err error) bool {\n\tLog.Error.Print(\"File write error:\", err)\n\treturn false\n}\n\nfunc (state *fileLogState) writeBatch() {\n\tstate.batch.Flush(state.file, nil, state.onWriterError)\n}\n\nfunc (state *fileLogState) needsRotate(prod *File, forceRotate bool) (bool, error) {\n\t\/\/ File does not exist?\n\tif state.file == nil {\n\t\treturn true, nil\n\t}\n\n\t\/\/ File can be accessed?\n\tstats, err := state.file.Stat()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ File needs rotation?\n\tif !prod.rotate {\n\t\treturn false, nil\n\t}\n\n\tif forceRotate {\n\t\treturn true, nil\n\t}\n\n\t\/\/ File is too large?\n\tif stats.Size() >= prod.rotateSizeByte {\n\t\treturn true, nil \/\/ ### return, too large ###\n\t}\n\n\t\/\/ File is too old?\n\tif time.Since(state.fileCreated).Minutes() >= float64(prod.rotateTimeoutMin) {\n\t\treturn true, nil \/\/ ### return, too old ###\n\t}\n\n\t\/\/ RotateAt crossed?\n\tif prod.rotateAtHour > -1 && prod.rotateAtMin > -1 {\n\t\tnow := time.Now()\n\t\trotateAt := time.Date(now.Year(), now.Month(), now.Day(), prod.rotateAtHour, prod.rotateAtMin, 0, 0, now.Location())\n\n\t\tif state.fileCreated.Sub(rotateAt).Minutes() < 0 {\n\t\t\treturn true, nil \/\/ ### return, too old ###\n\t\t}\n\t}\n\n\t\/\/ nope, everything is ok\n\treturn false, nil\n}\n\nfunc (prod *File) getFileLogState(streamID core.MessageStreamID, forceRotate bool) (*fileLogState, error) {\n\tif state, stateExists := prod.filesByStream[streamID]; stateExists {\n\t\tif rotate, err := state.needsRotate(prod, forceRotate); !rotate {\n\t\t\treturn state, err \/\/ ### return, already open or error ###\n\t\t}\n\t}\n\n\tvar logFileName, fileDir, fileName, fileExt string\n\tvar fileID uint32\n\n\tif prod.wildcardPath {\n\t\t\/\/ Get state from filename (without timestamp, etc.)\n\t\tvar streamName string\n\t\tswitch streamID {\n\t\tcase core.WildcardStreamID:\n\t\t\tstreamName = \"all\"\n\t\tcase core.LogInternalStreamID:\n\t\t\tstreamName = \"gollum\"\n\t\tcase core.DroppedStreamID:\n\t\t\tstreamName = \"dropped\"\n\t\tdefault:\n\t\t\tstreamName = core.StreamTypes.GetStreamName(streamID)\n\t\t}\n\n\t\tfileDir = strings.Replace(prod.fileDir, \"*\", streamName, -1)\n\t\tfileName = strings.Replace(prod.fileName, \"*\", streamName, -1)\n\t\tfileExt = strings.Replace(prod.fileExt, \"*\", streamName, -1)\n\n\t\t\/\/ Hash the base name\n\t\thash := fnv.New32a()\n\t\thash.Write([]byte(fmt.Sprintf(\"%s\/%s%s\", fileDir, fileName, fileExt)))\n\t\tfileID = hash.Sum32()\n\t} else {\n\t\t\/\/ Simple case: only one file used\n\t\tfileDir = prod.fileDir\n\t\tfileName = prod.fileName\n\t\tfileExt = prod.fileExt\n\t\tfileID = 0\n\t}\n\n\t\/\/ Assure the file is correctly mapped\n\tstate, stateExists := prod.files[fileID]\n\tif !stateExists {\n\t\t\/\/ state does not yet exist: create and map it\n\t\tstate = newFileLogState(prod.bufferSizeMax, prod.ProducerBase.GetFormatter())\n\t\tprod.files[fileID] = state\n\t\tprod.filesByStream[streamID] = state\n\t} else if _, mappingExists := prod.filesByStream[streamID]; !mappingExists {\n\t\t\/\/ state exists but is not mapped: map it and see if we need to rotate\n\t\tprod.filesByStream[streamID] = state\n\t\tif rotate, err := state.needsRotate(prod, forceRotate); !rotate {\n\t\t\treturn state, err \/\/ ### return, already open or error ###\n\t\t}\n\t}\n\n\t\/\/ Generate the log filename based on rotation, existing files, etc.\n\tif !prod.rotate {\n\t\tlogFileName = fmt.Sprintf(\"%s%s\", fileName, fileExt)\n\t} else {\n\t\ttimestamp := time.Now().Format(fileProducerTimestamp)\n\t\tsignature := fmt.Sprintf(\"%s_%s\", fileName, timestamp)\n\t\tcounter := 0\n\n\t\tif err := os.MkdirAll(fileDir, 0755); err != nil {\n\t\t\tLog.Error.Print(\"Error creating directory \" + fileDir)\n\t\t}\n\n\t\tfiles, _ := ioutil.ReadDir(fileDir)\n\t\tfor _, file := range files {\n\t\t\tif strings.Contains(file.Name(), signature) {\n\t\t\t\tcounter++\n\t\t\t}\n\t\t}\n\n\t\tif counter == 0 {\n\t\t\tlogFileName = fmt.Sprintf(\"%s%s\", signature, fileExt)\n\t\t} else {\n\t\t\tlogFileName = fmt.Sprintf(\"%s_%d%s\", signature, counter, fileExt)\n\t\t}\n\t}\n\n\tlogFile := fmt.Sprintf(\"%s\/%s\", fileDir, logFileName)\n\n\t\/\/ Close existing log\n\tif state.file != nil {\n\t\tcurrentLog := state.file\n\t\tstate.file = nil\n\n\t\tif prod.compress {\n\t\t\tgo state.compressAndCloseLog(currentLog)\n\t\t} else {\n\t\t\tLog.Note.Print(\"Rotated \" + currentLog.Name())\n\t\t\tcurrentLog.Close()\n\t\t}\n\t}\n\n\t\/\/ (Re)open logfile\n\tvar err error\n\tstate.file, err = os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)\n\tif err != nil {\n\t\treturn state, err \/\/ ### return error ###\n\t}\n\n\t\/\/ Create \"current\" symlink\n\tstate.fileCreated = time.Now()\n\tif prod.rotate {\n\t\tsymLinkName := fmt.Sprintf(\"%s\/%s_current%s\", fileDir, fileName, fileExt)\n\t\tos.Remove(symLinkName)\n\t\tos.Symlink(logFileName, symLinkName)\n\t}\n\n\treturn state, err\n}\n\nfunc (prod *File) writeBatchOnTimeOut() {\n\tfor _, state := range prod.files {\n\t\tif state.batch.ReachedTimeThreshold(prod.batchTimeout) || state.batch.ReachedSizeThreshold(prod.batchSize) {\n\t\t\tstate.writeBatch()\n\t\t}\n\t}\n}\n\nfunc (prod *File) writeMessage(msg core.Message) {\n\tstate, err := prod.getFileLogState(msg.StreamID, false)\n\tif err != nil {\n\t\tLog.Error.Print(\"File log error:\", err)\n\t\tmsg.Drop(time.Duration(0))\n\t\treturn \/\/ ### return, dropped ###\n\t}\n\n\tif !state.batch.Append(msg) {\n\t\tstate.writeBatch()\n\t\tstate.batch.Append(msg)\n\t}\n}\n\nfunc (prod *File) rotateLog() {\n\tfor streamID := range prod.filesByStream {\n\t\tif _, err := prod.getFileLogState(streamID, true); err != nil {\n\t\t\tLog.Error.Print(\"File rotate error:\", err)\n\t\t}\n\t}\n}\n\nfunc (prod *File) flush() {\n\tfor _, state := range prod.files {\n\t\tstate.writeBatch()\n\t\tstate.batch.WaitForFlush(5 * time.Second)\n\n\t\tstate.bgWriter.Wait()\n\t\tstate.file.Close()\n\t}\n\tprod.WorkerDone()\n}\n\n\/\/ Produce writes to a buffer that is dumped to a file.\nfunc (prod *File) Produce(workers *sync.WaitGroup) {\n\tdefer prod.flush()\n\n\tprod.AddMainWorker(workers)\n\tprod.TickerControlLoop(prod.batchTimeout, prod.writeMessage, prod.rotateLog, prod.writeBatchOnTimeOut)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage ghmetrics\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nconst unmatchedPath = \"unmatched\"\n\n\/\/ GetSimplifiedPath returns a variable-free path that can be used as label for prometheus metrics\nfunc GetSimplifiedPath(path string) string {\n\ttree := l(\"\", \/\/ shadow element mimicing the root\n\t\tl(\"repos\",\n\t\t\tv(\"owner\",\n\t\t\t\tv(\"repo\",\n\t\t\t\t\tl(\"branches\", v(\"branch\", l(\"protection\",\n\t\t\t\t\t\tl(\"restrictions\", l(\"users\"), l(\"teams\")),\n\t\t\t\t\t\tl(\"required_status_checks\", l(\"contexts\")),\n\t\t\t\t\t\tl(\"required_pull_request_reviews\"),\n\t\t\t\t\t\tl(\"required_signatures\"),\n\t\t\t\t\t\tl(\"enforce_admins\")))),\n\t\t\t\t\tl(\"issues\",\n\t\t\t\t\t\tl(\"comments\", v(\"commentId\")),\n\t\t\t\t\t\tl(\"events\", v(\"eventId\")),\n\t\t\t\t\t\tv(\"issueId\",\n\t\t\t\t\t\t\tl(\"lock\"),\n\t\t\t\t\t\t\tl(\"comments\"),\n\t\t\t\t\t\t\tl(\"events\"),\n\t\t\t\t\t\t\tl(\"assignees\"),\n\t\t\t\t\t\t\tl(\"reactions\"),\n\t\t\t\t\t\t\tl(\"labels\", v(\"labelId\")))),\n\t\t\t\t\tl(\"keys\", v(\"keyId\")),\n\t\t\t\t\tl(\"labels\", v(\"labelId\")),\n\t\t\t\t\tl(\"milestones\", v(\"milestone\")),\n\t\t\t\t\tl(\"pulls\", v(\"pullId\")),\n\t\t\t\t\tl(\"releases\", v(\"releaseId\")),\n\t\t\t\t\tl(\"statuses\", v(\"statusId\")),\n\t\t\t\t\tl(\"subscribers\", v(\"subscriberId\")),\n\t\t\t\t\tl(\"assignees\", v(\"assigneeId\")),\n\t\t\t\t\tl(\"archive\", v(\"zip\")),\n\t\t\t\t\tl(\"collaborators\", v(\"collaboratorId\")),\n\t\t\t\t\tl(\"comments\", v(\"commentId\")),\n\t\t\t\t\tl(\"compare\", v(\"sha\")),\n\t\t\t\t\tl(\"contents\", v(\"contentId\")),\n\t\t\t\t\tl(\"commits\", v(\"sha\")),\n\t\t\t\t\tl(\"git\",\n\t\t\t\t\t\tl(\"commits\", v(\"sha\")),\n\t\t\t\t\t\tl(\"ref\", v(\"refId\")),\n\t\t\t\t\t\tl(\"tags\", v(\"tagId\")),\n\t\t\t\t\t\tl(\"trees\", v(\"sha\")),\n\t\t\t\t\t\tl(\"refs\", l(\"heads\", v(\"ref\")))),\n\t\t\t\t\tl(\"stars\"),\n\t\t\t\t\tl(\"merges\"),\n\t\t\t\t\tl(\"stargazers\"),\n\t\t\t\t\tl(\"notifications\"),\n\t\t\t\t\tl(\"hooks\"),\n\t\t\t\t\tl(\"deployments\"),\n\t\t\t\t\tl(\"downloads\"),\n\t\t\t\t\tl(\"events\"),\n\t\t\t\t\tl(\"forks\"),\n\t\t\t\t\tl(\"topics\"),\n\t\t\t\t\tl(\"vulnerability-alerts\"),\n\t\t\t\t\tl(\"automated-security-fixes\"),\n\t\t\t\t\tl(\"contributors\"),\n\t\t\t\t\tl(\"languages\"),\n\t\t\t\t\tl(\"teams\"),\n\t\t\t\t\tl(\"tags\"),\n\t\t\t\t\tl(\"transfer\")))),\n\t\tl(\"user\",\n\t\t\tl(\"following\", v(\"userId\")),\n\t\t\tl(\"keys\", v(\"keyId\")),\n\t\t\tl(\"email\", l(\"visibility\")),\n\t\t\tl(\"emails\"),\n\t\t\tl(\"public_emails\"),\n\t\t\tl(\"followers\"),\n\t\t\tl(\"starred\"),\n\t\t\tl(\"issues\")),\n\t\tl(\"users\",\n\t\t\tv(\"username\",\n\t\t\t\tl(\"followers\", v(\"username\")),\n\t\t\t\tl(\"repos\"),\n\t\t\t\tl(\"hovercard\"),\n\t\t\t\tl(\"following\"))),\n\t\tl(\"orgs\",\n\t\t\tv(\"orgname\",\n\t\t\t\tl(\"credential-authorizations\", v(\"credentialId\")),\n\t\t\t\tl(\"repos\"),\n\t\t\t\tl(\"issues\"),\n\t\t\t\tl(\"invitations\"),\n\t\t\t\tl(\"members\", v(\"login\")),\n\t\t\t\tl(\"teams\"))),\n\t\tl(\"organizations\",\n\t\t\tv(\"orgId\",\n\t\t\t\tl(\"members\"),\n\t\t\t\tl(\"repos\"),\n\t\t\t\tl(\"teams\"))),\n\t\tl(\"issues\", v(\"issueId\")),\n\t\tl(\"search\",\n\t\t\tl(\"repositories\"),\n\t\t\tl(\"commits\"),\n\t\t\tl(\"code\"),\n\t\t\tl(\"issues\"),\n\t\t\tl(\"users\"),\n\t\t\tl(\"topics\"),\n\t\t\tl(\"labels\")),\n\t\tl(\"gists\",\n\t\t\tl(\"public\"),\n\t\t\tl(\"starred\")),\n\t\tl(\"notifications\", l(\"threads\", v(\"threadId\", l(\"subscription\")))),\n\t\tl(\"repositories\"),\n\t\tl(\"emojis\"),\n\t\tl(\"events\"),\n\t\tl(\"feeds\"),\n\t\tl(\"hub\"),\n\t\tl(\"rate_limit\"),\n\t\tl(\"teams\"),\n\t\t\/\/ end point for gh api v4\n\t\tl(\"graphql\"),\n\t\tl(\"licenses\"))\n\n\tsplitPath := strings.Split(path, \"\/\")\n\tresolvedPath, matches := resolve(tree, splitPath)\n\tif !matches {\n\t\tlogrus.WithField(\"path\", path).Warning(\"Path not handled. This is a bug in GHProxy, please open an issue against the kubernetes\/test-infra repository with this error message.\")\n\t\treturn unmatchedPath\n\t}\n\treturn resolvedPath\n}\n\ntype node struct {\n\tPathFragment\n\tchildren []node\n}\n\n\/\/ PathFragment Interface for tree leafs to help resolve paths\ntype PathFragment interface {\n\tMatches(part string) bool\n\tRepresent() string\n}\n\ntype literal string\n\nfunc (l literal) Matches(part string) bool {\n\treturn string(l) == part\n}\n\nfunc (l literal) Represent() string {\n\treturn string(l)\n}\n\ntype variable string\n\nfunc (v variable) Matches(part string) bool {\n\treturn true\n}\n\nfunc (v variable) Represent() string {\n\treturn \":\" + string(v)\n}\n\nfunc l(fragment string, children ...node) node {\n\treturn node{\n\t\tPathFragment: literal(fragment),\n\t\tchildren:     children,\n\t}\n}\n\nfunc v(fragment string, children ...node) node {\n\treturn node{\n\t\tPathFragment: variable(fragment),\n\t\tchildren:     children,\n\t}\n}\n\nfunc resolve(parent node, path []string) (string, bool) {\n\tif !parent.Matches(path[0]) {\n\t\treturn \"\", false\n\t}\n\trepresentation := parent.Represent()\n\tif len(path) == 1 || len(parent.children) == 0 {\n\t\treturn representation, true\n\t}\n\tfor _, child := range parent.children {\n\t\tsuffix, matched := resolve(child, path[1:])\n\t\tif matched {\n\t\t\treturn strings.Join([]string{representation, suffix}, \"\/\"), true\n\t\t}\n\t}\n\treturn \"\", false\n}\n<commit_msg>kill log messages to reduce log spam<commit_after>\/*\nCopyright 2019 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage ghmetrics\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nconst unmatchedPath = \"unmatched\"\n\n\/\/ GetSimplifiedPath returns a variable-free path that can be used as label for prometheus metrics\nfunc GetSimplifiedPath(path string) string {\n\ttree := l(\"\", \/\/ shadow element mimicing the root\n\t\tl(\"repos\",\n\t\t\tv(\"owner\",\n\t\t\t\tv(\"repo\",\n\t\t\t\t\tl(\"branches\", v(\"branch\", l(\"protection\",\n\t\t\t\t\t\tl(\"restrictions\", l(\"users\"), l(\"teams\")),\n\t\t\t\t\t\tl(\"required_status_checks\", l(\"contexts\")),\n\t\t\t\t\t\tl(\"required_pull_request_reviews\"),\n\t\t\t\t\t\tl(\"required_signatures\"),\n\t\t\t\t\t\tl(\"enforce_admins\")))),\n\t\t\t\t\tl(\"issues\",\n\t\t\t\t\t\tl(\"comments\", v(\"commentId\")),\n\t\t\t\t\t\tl(\"events\", v(\"eventId\")),\n\t\t\t\t\t\tv(\"issueId\",\n\t\t\t\t\t\t\tl(\"lock\"),\n\t\t\t\t\t\t\tl(\"comments\"),\n\t\t\t\t\t\t\tl(\"events\"),\n\t\t\t\t\t\t\tl(\"assignees\"),\n\t\t\t\t\t\t\tl(\"reactions\"),\n\t\t\t\t\t\t\tl(\"labels\", v(\"labelId\")))),\n\t\t\t\t\tl(\"keys\", v(\"keyId\")),\n\t\t\t\t\tl(\"labels\", v(\"labelId\")),\n\t\t\t\t\tl(\"milestones\", v(\"milestone\")),\n\t\t\t\t\tl(\"pulls\", v(\"pullId\")),\n\t\t\t\t\tl(\"releases\", v(\"releaseId\")),\n\t\t\t\t\tl(\"statuses\", v(\"statusId\")),\n\t\t\t\t\tl(\"subscribers\", v(\"subscriberId\")),\n\t\t\t\t\tl(\"assignees\", v(\"assigneeId\")),\n\t\t\t\t\tl(\"archive\", v(\"zip\")),\n\t\t\t\t\tl(\"collaborators\", v(\"collaboratorId\")),\n\t\t\t\t\tl(\"comments\", v(\"commentId\")),\n\t\t\t\t\tl(\"compare\", v(\"sha\")),\n\t\t\t\t\tl(\"contents\", v(\"contentId\")),\n\t\t\t\t\tl(\"commits\", v(\"sha\")),\n\t\t\t\t\tl(\"git\",\n\t\t\t\t\t\tl(\"commits\", v(\"sha\")),\n\t\t\t\t\t\tl(\"ref\", v(\"refId\")),\n\t\t\t\t\t\tl(\"tags\", v(\"tagId\")),\n\t\t\t\t\t\tl(\"trees\", v(\"sha\")),\n\t\t\t\t\t\tl(\"refs\", l(\"heads\", v(\"ref\")))),\n\t\t\t\t\tl(\"stars\"),\n\t\t\t\t\tl(\"merges\"),\n\t\t\t\t\tl(\"stargazers\"),\n\t\t\t\t\tl(\"notifications\"),\n\t\t\t\t\tl(\"hooks\"),\n\t\t\t\t\tl(\"deployments\"),\n\t\t\t\t\tl(\"downloads\"),\n\t\t\t\t\tl(\"events\"),\n\t\t\t\t\tl(\"forks\"),\n\t\t\t\t\tl(\"topics\"),\n\t\t\t\t\tl(\"vulnerability-alerts\"),\n\t\t\t\t\tl(\"automated-security-fixes\"),\n\t\t\t\t\tl(\"contributors\"),\n\t\t\t\t\tl(\"languages\"),\n\t\t\t\t\tl(\"teams\"),\n\t\t\t\t\tl(\"tags\"),\n\t\t\t\t\tl(\"transfer\")))),\n\t\tl(\"user\",\n\t\t\tl(\"following\", v(\"userId\")),\n\t\t\tl(\"keys\", v(\"keyId\")),\n\t\t\tl(\"email\", l(\"visibility\")),\n\t\t\tl(\"emails\"),\n\t\t\tl(\"public_emails\"),\n\t\t\tl(\"followers\"),\n\t\t\tl(\"starred\"),\n\t\t\tl(\"issues\")),\n\t\tl(\"users\",\n\t\t\tv(\"username\",\n\t\t\t\tl(\"followers\", v(\"username\")),\n\t\t\t\tl(\"repos\"),\n\t\t\t\tl(\"hovercard\"),\n\t\t\t\tl(\"following\"))),\n\t\tl(\"orgs\",\n\t\t\tv(\"orgname\",\n\t\t\t\tl(\"credential-authorizations\", v(\"credentialId\")),\n\t\t\t\tl(\"repos\"),\n\t\t\t\tl(\"issues\"),\n\t\t\t\tl(\"invitations\"),\n\t\t\t\tl(\"members\", v(\"login\")),\n\t\t\t\tl(\"teams\"))),\n\t\tl(\"organizations\",\n\t\t\tv(\"orgId\",\n\t\t\t\tl(\"members\"),\n\t\t\t\tl(\"repos\"),\n\t\t\t\tl(\"teams\"))),\n\t\tl(\"issues\", v(\"issueId\")),\n\t\tl(\"search\",\n\t\t\tl(\"repositories\"),\n\t\t\tl(\"commits\"),\n\t\t\tl(\"code\"),\n\t\t\tl(\"issues\"),\n\t\t\tl(\"users\"),\n\t\t\tl(\"topics\"),\n\t\t\tl(\"labels\")),\n\t\tl(\"gists\",\n\t\t\tl(\"public\"),\n\t\t\tl(\"starred\")),\n\t\tl(\"notifications\", l(\"threads\", v(\"threadId\", l(\"subscription\")))),\n\t\tl(\"repositories\"),\n\t\tl(\"emojis\"),\n\t\tl(\"events\"),\n\t\tl(\"feeds\"),\n\t\tl(\"hub\"),\n\t\tl(\"rate_limit\"),\n\t\tl(\"teams\"),\n\t\t\/\/ end point for gh api v4\n\t\tl(\"graphql\"),\n\t\tl(\"licenses\"))\n\n\tsplitPath := strings.Split(path, \"\/\")\n\tresolvedPath, matches := resolve(tree, splitPath)\n\tif !matches {\n\t\tlogrus.WithField(\"path\", path).Debug(\"Path not handled. This is a bug in GHProxy, please open an issue against the kubernetes\/test-infra repository with this error message.\")\n\t\treturn unmatchedPath\n\t}\n\treturn resolvedPath\n}\n\ntype node struct {\n\tPathFragment\n\tchildren []node\n}\n\n\/\/ PathFragment Interface for tree leafs to help resolve paths\ntype PathFragment interface {\n\tMatches(part string) bool\n\tRepresent() string\n}\n\ntype literal string\n\nfunc (l literal) Matches(part string) bool {\n\treturn string(l) == part\n}\n\nfunc (l literal) Represent() string {\n\treturn string(l)\n}\n\ntype variable string\n\nfunc (v variable) Matches(part string) bool {\n\treturn true\n}\n\nfunc (v variable) Represent() string {\n\treturn \":\" + string(v)\n}\n\nfunc l(fragment string, children ...node) node {\n\treturn node{\n\t\tPathFragment: literal(fragment),\n\t\tchildren:     children,\n\t}\n}\n\nfunc v(fragment string, children ...node) node {\n\treturn node{\n\t\tPathFragment: variable(fragment),\n\t\tchildren:     children,\n\t}\n}\n\nfunc resolve(parent node, path []string) (string, bool) {\n\tif !parent.Matches(path[0]) {\n\t\treturn \"\", false\n\t}\n\trepresentation := parent.Represent()\n\tif len(path) == 1 || len(parent.children) == 0 {\n\t\treturn representation, true\n\t}\n\tfor _, child := range parent.children {\n\t\tsuffix, matched := resolve(child, path[1:])\n\t\tif matched {\n\t\t\treturn strings.Join([]string{representation, suffix}, \"\/\"), true\n\t\t}\n\t}\n\treturn \"\", false\n}\n<|endoftext|>"}
{"text":"<commit_before>package chat\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/keybase\/client\/go\/chat\/globals\"\n\t\"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n\n\t\"github.com\/keybase\/client\/go\/chat\/types\"\n\t\"github.com\/keybase\/client\/go\/chat\/utils\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ sourceOfflinable implements the chat\/types.Offlinable interface.\n\/\/ It is meant to be embedded in inbox and conversation sources.\n\/\/ It's main purpose is that IsOffline() will wait for 4s to see if any\n\/\/ in progress connections succeed before returning.\ntype sourceOfflinable struct {\n\tglobals.Contextified\n\tutils.DebugLabeler\n\toffline, delayed bool\n\tconnected        chan bool\n\tsync.Mutex\n}\n\nvar _ types.Offlinable = (*sourceOfflinable)(nil)\n\nfunc newSourceOfflinable(g *globals.Context, labeler utils.DebugLabeler) *sourceOfflinable {\n\treturn &sourceOfflinable{\n\t\tContextified: globals.NewContextified(g),\n\t\tDebugLabeler: labeler,\n\t\tconnected:    makeConnectedChan(),\n\t}\n}\n\nfunc (s *sourceOfflinable) Connected(ctx context.Context) {\n\tdefer s.Trace(ctx, func() error { return nil }, \"Connected\")()\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.Debug(ctx, \"connected: offline to false\")\n\ts.offline = false\n\ts.connected <- true\n}\n\nfunc (s *sourceOfflinable) Disconnected(ctx context.Context) {\n\tdefer s.Trace(ctx, func() error { return nil }, \"Disconnected\")()\n\ts.Lock()\n\tdefer s.Unlock()\n\tif s.offline {\n\t\ts.Debug(ctx, \"already disconnected, ignoring disconnected callback\")\n\t\treturn\n\t}\n\ts.Debug(ctx, \"disconnected: offline to true\")\n\ts.offline = true\n\ts.delayed = false\n\tclose(s.connected)\n\ts.connected = makeConnectedChan()\n}\n\nfunc (s *sourceOfflinable) getOfflineInfo() (offline bool, connectedCh chan bool) {\n\ts.Lock()\n\tdefer s.Unlock()\n\treturn s.offline, s.connected\n}\n\nfunc (s *sourceOfflinable) IsOffline(ctx context.Context) bool {\n\ts.Lock()\n\toffline := s.offline\n\tconnected := s.connected\n\tdelayed := s.delayed\n\ts.Unlock()\n\n\tif offline {\n\t\tif delayed {\n\t\t\ts.Debug(ctx, \"IsOffline: offline, but skipping delay since we already did it\")\n\t\t\treturn offline\n\t\t}\n\t\tif s.G().MobileAppState.State() != keybase1.MobileAppState_FOREGROUND {\n\t\t\ts.Debug(ctx, \"IsOffline: offline, but not waiting for anything since not in foreground\")\n\t\t\treturn offline\n\t\t}\n\t\ttimeoutCh := time.After(5 * time.Second)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-connected:\n\t\t\t\ts.Debug(ctx, \"IsOffline: waited and got %v\", s.offline)\n\t\t\t\ts.Lock()\n\t\t\t\tif s.offline {\n\t\t\t\t\ts.Unlock()\n\t\t\t\t\ts.Debug(ctx, \"IsOffline: since we got word of being offline, we will keep waiting\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdefer s.Unlock()\n\t\t\t\treturn s.offline\n\t\t\tcase <-ctx.Done():\n\t\t\t\ts.Lock()\n\t\t\t\tdefer s.Unlock()\n\t\t\t\ts.Debug(ctx, \"IsOffline: aborted: %s state: %v\", ctx.Err(), s.offline)\n\t\t\t\treturn s.offline\n\t\t\tcase <-timeoutCh:\n\t\t\t\ts.Lock()\n\t\t\t\tdefer s.Unlock()\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\ts.Debug(ctx, \"IsOffline: timed out, but context canceled so not setting delayed: state: %v\",\n\t\t\t\t\t\ts.offline)\n\t\t\t\t\treturn s.offline\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t\ts.delayed = true\n\t\t\t\ts.Debug(ctx, \"IsOffline: timed out, setting delay wait: state: %v\", s.offline)\n\t\t\t\treturn s.offline\n\t\t\t}\n\t\t}\n\t}\n\treturn offline\n}\n\n\/\/ makeConnectedChan creates a buffered channel for Connected to signal that\n\/\/ a connection happened.  The buffer size is 10 just to be extra-safe that\n\/\/ a send on the channel won't block during its lifetime (a buffer size of\n\/\/ 1 should be all that is required).\nfunc makeConnectedChan() chan bool {\n\treturn make(chan bool, 10)\n\n}\n<commit_msg>dont spin on a closed channel, get the new one (#17944)<commit_after>package chat\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/keybase\/client\/go\/chat\/globals\"\n\t\"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n\n\t\"github.com\/keybase\/client\/go\/chat\/types\"\n\t\"github.com\/keybase\/client\/go\/chat\/utils\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ sourceOfflinable implements the chat\/types.Offlinable interface.\n\/\/ It is meant to be embedded in inbox and conversation sources.\n\/\/ It's main purpose is that IsOffline() will wait for 4s to see if any\n\/\/ in progress connections succeed before returning.\ntype sourceOfflinable struct {\n\tglobals.Contextified\n\tutils.DebugLabeler\n\toffline, delayed bool\n\tconnected        chan bool\n\tsync.Mutex\n}\n\nvar _ types.Offlinable = (*sourceOfflinable)(nil)\n\nfunc newSourceOfflinable(g *globals.Context, labeler utils.DebugLabeler) *sourceOfflinable {\n\treturn &sourceOfflinable{\n\t\tContextified: globals.NewContextified(g),\n\t\tDebugLabeler: labeler,\n\t\tconnected:    makeConnectedChan(),\n\t}\n}\n\nfunc (s *sourceOfflinable) Connected(ctx context.Context) {\n\tdefer s.Trace(ctx, func() error { return nil }, \"Connected\")()\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.Debug(ctx, \"connected: offline to false\")\n\ts.offline = false\n\ts.connected <- true\n}\n\nfunc (s *sourceOfflinable) Disconnected(ctx context.Context) {\n\tdefer s.Trace(ctx, func() error { return nil }, \"Disconnected\")()\n\ts.Lock()\n\tdefer s.Unlock()\n\tif s.offline {\n\t\ts.Debug(ctx, \"already disconnected, ignoring disconnected callback\")\n\t\treturn\n\t}\n\ts.Debug(ctx, \"disconnected: offline to true\")\n\ts.offline = true\n\ts.delayed = false\n\tclose(s.connected)\n\ts.connected = makeConnectedChan()\n}\n\nfunc (s *sourceOfflinable) getOfflineInfo() (offline bool, connectedCh chan bool) {\n\ts.Lock()\n\tdefer s.Unlock()\n\treturn s.offline, s.connected\n}\n\nfunc (s *sourceOfflinable) IsOffline(ctx context.Context) bool {\n\ts.Lock()\n\toffline := s.offline\n\tconnected := s.connected\n\tdelayed := s.delayed\n\ts.Unlock()\n\n\tif offline {\n\t\tif delayed {\n\t\t\ts.Debug(ctx, \"IsOffline: offline, but skipping delay since we already did it\")\n\t\t\treturn offline\n\t\t}\n\t\tif s.G().MobileAppState.State() != keybase1.MobileAppState_FOREGROUND {\n\t\t\ts.Debug(ctx, \"IsOffline: offline, but not waiting for anything since not in foreground\")\n\t\t\treturn offline\n\t\t}\n\t\ttimeoutCh := time.After(5 * time.Second)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-connected:\n\t\t\t\ts.Debug(ctx, \"IsOffline: waited and got %v\", s.offline)\n\t\t\t\ts.Lock()\n\t\t\t\tif s.offline {\n\t\t\t\t\tconnected = s.connected\n\t\t\t\t\ts.Unlock()\n\t\t\t\t\ts.Debug(ctx, \"IsOffline: since we got word of being offline, we will keep waiting\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdefer s.Unlock()\n\t\t\t\treturn s.offline\n\t\t\tcase <-ctx.Done():\n\t\t\t\ts.Lock()\n\t\t\t\tdefer s.Unlock()\n\t\t\t\ts.Debug(ctx, \"IsOffline: aborted: %s state: %v\", ctx.Err(), s.offline)\n\t\t\t\treturn s.offline\n\t\t\tcase <-timeoutCh:\n\t\t\t\ts.Lock()\n\t\t\t\tdefer s.Unlock()\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\ts.Debug(ctx, \"IsOffline: timed out, but context canceled so not setting delayed: state: %v\",\n\t\t\t\t\t\ts.offline)\n\t\t\t\t\treturn s.offline\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t\ts.delayed = true\n\t\t\t\ts.Debug(ctx, \"IsOffline: timed out, setting delay wait: state: %v\", s.offline)\n\t\t\t\treturn s.offline\n\t\t\t}\n\t\t}\n\t}\n\treturn offline\n}\n\n\/\/ makeConnectedChan creates a buffered channel for Connected to signal that\n\/\/ a connection happened.  The buffer size is 10 just to be extra-safe that\n\/\/ a send on the channel won't block during its lifetime (a buffer size of\n\/\/ 1 should be all that is required).\nfunc makeConnectedChan() chan bool {\n\treturn make(chan bool, 10)\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package transactions\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/joshheinrichs\/geosource\/server\/config\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nvar db *gorm.DB\n\nvar ErrInsufficientPermission error = errors.New(\"Insufficient permission.\")\n\nfunc Init(config *config.Config) (err error) {\n\tdb, err = gorm.Open(\"postgres\", fmt.Sprintf(\"host=%s dbname=%s user=%s password=%s\",\n\t\tconfig.Database.Host, config.Database.Database, config.Database.User, config.Database.Password))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>Make database config fields optional<commit_after>package transactions\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/joshheinrichs\/geosource\/server\/config\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nvar db *gorm.DB\n\nvar ErrInsufficientPermission error = errors.New(\"Insufficient permission.\")\n\nfunc Init(config *config.Config) (err error) {\n\targuments := \"\"\n\tif len(config.Database.Host) > 0 {\n\t\targuments += fmt.Sprintf(\"host=%s \", config.Database.Host)\n\t}\n\tif len(config.Database.Database) > 0 {\n\t\targuments += fmt.Sprintf(\"dbname=%s \", config.Database.Database)\n\t}\n\tif len(config.Database.User) > 0 {\n\t\targuments += fmt.Sprintf(\"user=%s \", config.Database.User)\n\t}\n\tif len(config.Database.Password) > 0 {\n\t\targuments += fmt.Sprintf(\"password=%s \", config.Database.Password)\n\t}\n\n\tdb, err = gorm.Open(\"postgres\", arguments)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package v2\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/coreos\/etcd\/server\"\n\t\"github.com\/coreos\/etcd\/tests\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\n\/\/ Ensures that a value can be retrieve for a given key.\n\/\/\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/foo\/bar -d value=XXX\n\/\/   $ curl localhost:4001\/v2\/keys\/foo\/bar\n\/\/\nfunc TestV2GetKey(t *testing.T) {\n\ttests.RunServer(func(s *server.Server) {\n\t\tv := url.Values{}\n\t\tv.Set(\"value\", \"XXX\")\n\t\tresp, _ := tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar\"), v)\n\t\ttests.ReadBody(resp)\n\t\tresp, _ = tests.Get(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar\"))\n\t\tbody := tests.ReadBodyJSON(resp)\n\t\tassert.Equal(t, body[\"action\"], \"get\", \"\")\n\t\tnode := body[\"node\"].(map[string]interface{})\n\t\tassert.Equal(t, node[\"key\"], \"\/foo\/bar\", \"\")\n\t\tassert.Equal(t, node[\"value\"], \"XXX\", \"\")\n\t\tassert.Equal(t, node[\"modifiedIndex\"], 2, \"\")\n\t})\n}\n\n\/\/ Ensures that a directory of values can be recursively retrieved for a given key.\n\/\/\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/foo\/x -d value=XXX\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/foo\/y\/z -d value=YYY\n\/\/   $ curl localhost:4001\/v2\/keys\/foo -d recursive=true\n\/\/\nfunc TestV2GetKeyRecursively(t *testing.T) {\n\ttests.RunServer(func(s *server.Server) {\n\t\tv := url.Values{}\n\t\tv.Set(\"value\", \"XXX\")\n\t\tv.Set(\"ttl\", \"10\")\n\t\tresp, _ := tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/x\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\tv.Set(\"value\", \"YYY\")\n\t\tresp, _ = tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/y\/z\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\tresp, _ = tests.Get(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo?recursive=true\"))\n\t\tbody := tests.ReadBodyJSON(resp)\n\t\tassert.Equal(t, body[\"action\"], \"get\", \"\")\n\t\tnode := body[\"node\"].(map[string]interface{})\n\t\tassert.Equal(t, node[\"key\"], \"\/foo\", \"\")\n\t\tassert.Equal(t, node[\"dir\"], true, \"\")\n\t\tassert.Equal(t, node[\"modifiedIndex\"], 2, \"\")\n\t\tassert.Equal(t, len(node[\"nodes\"].([]interface{})), 2, \"\")\n\n\t\tnode0 := node[\"nodes\"].([]interface{})[0].(map[string]interface{})\n\t\tassert.Equal(t, node0[\"key\"], \"\/foo\/x\", \"\")\n\t\tassert.Equal(t, node0[\"value\"], \"XXX\", \"\")\n\t\tassert.Equal(t, node0[\"ttl\"], 10, \"\")\n\n\t\tnode1 := node[\"nodes\"].([]interface{})[1].(map[string]interface{})\n\t\tassert.Equal(t, node1[\"key\"], \"\/foo\/y\", \"\")\n\t\tassert.Equal(t, node1[\"dir\"], true, \"\")\n\n\t\tnode2 := node1[\"nodes\"].([]interface{})[0].(map[string]interface{})\n\t\tassert.Equal(t, node2[\"key\"], \"\/foo\/y\/z\", \"\")\n\t\tassert.Equal(t, node2[\"value\"], \"YYY\", \"\")\n\t})\n}\n\n\/\/ Ensures that a watcher can wait for a value to be set and return it to the client.\n\/\/\n\/\/   $ curl localhost:4001\/v2\/keys\/foo\/bar?wait=true\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/foo\/bar -d value=XXX\n\/\/\nfunc TestV2WatchKey(t *testing.T) {\n\ttests.RunServer(func(s *server.Server) {\n\t\tvar body map[string]interface{}\n\t\tc := make(chan bool)\n\t\tgo func() {\n\t\t\tresp, _ := tests.Get(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar?wait=true\"))\n\t\t\tbody = tests.ReadBodyJSON(resp)\n\t\t\tc <- true\n\t\t}()\n\n\t\t\/\/ Make sure response didn't fire early.\n\t\ttime.Sleep(1 * time.Millisecond)\n\t\tassert.Nil(t, body, \"\")\n\n\t\t\/\/ Set a value.\n\t\tv := url.Values{}\n\t\tv.Set(\"value\", \"XXX\")\n\t\tresp, _ := tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\t\/\/ A response should follow from the GET above.\n\t\ttime.Sleep(1 * time.Millisecond)\n\n\t\tselect {\n\t\tcase <-c:\n\n\t\tdefault:\n\t\t\tt.Fatal(\"cannot get watch result\")\n\t\t}\n\n\t\tassert.NotNil(t, body, \"\")\n\t\tassert.Equal(t, body[\"action\"], \"set\", \"\")\n\n\t\tnode := body[\"node\"].(map[string]interface{})\n\t\tassert.Equal(t, node[\"key\"], \"\/foo\/bar\", \"\")\n\t\tassert.Equal(t, node[\"value\"], \"XXX\", \"\")\n\t\tassert.Equal(t, node[\"modifiedIndex\"], 2, \"\")\n\t})\n}\n\n\/\/ Ensures that a watcher can wait for a value to be set after a given index.\n\/\/\n\/\/   $ curl localhost:4001\/v2\/keys\/foo\/bar?wait=true&waitIndex=4\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/foo\/bar -d value=XXX\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/foo\/bar -d value=YYY\n\/\/\nfunc TestV2WatchKeyWithIndex(t *testing.T) {\n\ttests.RunServer(func(s *server.Server) {\n\t\tvar body map[string]interface{}\n\t\tc := make(chan bool)\n\t\tgo func() {\n\t\t\tresp, _ := tests.Get(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar?wait=true&waitIndex=3\"))\n\t\t\tbody = tests.ReadBodyJSON(resp)\n\t\t\tc <- true\n\t\t}()\n\n\t\t\/\/ Make sure response didn't fire early.\n\t\ttime.Sleep(1 * time.Millisecond)\n\t\tassert.Nil(t, body, \"\")\n\n\t\t\/\/ Set a value (before given index).\n\t\tv := url.Values{}\n\t\tv.Set(\"value\", \"XXX\")\n\t\tresp, _ := tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\t\/\/ Make sure response didn't fire early.\n\t\ttime.Sleep(1 * time.Millisecond)\n\t\tassert.Nil(t, body, \"\")\n\n\t\t\/\/ Set a value (before given index).\n\t\tv.Set(\"value\", \"YYY\")\n\t\tresp, _ = tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\t\/\/ A response should follow from the GET above.\n\t\ttime.Sleep(1 * time.Millisecond)\n\n\t\tselect {\n\t\tcase <-c:\n\n\t\tdefault:\n\t\t\tt.Fatal(\"cannot get watch result\")\n\t\t}\n\n\t\tassert.NotNil(t, body, \"\")\n\t\tassert.Equal(t, body[\"action\"], \"set\", \"\")\n\n\t\tnode := body[\"node\"].(map[string]interface{})\n\t\tassert.Equal(t, node[\"key\"], \"\/foo\/bar\", \"\")\n\t\tassert.Equal(t, node[\"value\"], \"YYY\", \"\")\n\t\tassert.Equal(t, node[\"modifiedIndex\"], 3, \"\")\n\t})\n}\n\n\/\/ Ensures that a watcher can wait for a value to be set after a given index.\n\/\/\n\/\/   $ curl localhost:4001\/v2\/keys\/keyindir\/bar?wait=true\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/keyindir -d dir=true -d ttl=1\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/keyindir\/bar -d value=YYY\n\/\/\nfunc TestV2WatchKeyInDir(t *testing.T) {\n\ttests.RunServer(func(s *server.Server) {\n\t\tvar body map[string]interface{}\n\t\tc := make(chan bool)\n\n\t\t\/\/ Set a value (before given index).\n\t\tv := url.Values{}\n\t\tv.Set(\"dir\", \"true\")\n\t\tv.Set(\"ttl\", \"1\")\n\t\tresp, _ := tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/keyindir\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\t\/\/ Set a value (before given index).\n\t\tv = url.Values{}\n\t\tv.Set(\"value\", \"XXX\")\n\t\tresp, _ = tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/keyindir\/bar\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\tgo func() {\n\t\t\tresp, _ := tests.Get(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/keyindir\/bar?wait=true\"))\n\t\t\tbody = tests.ReadBodyJSON(resp)\n\t\t\tc <- true\n\t\t}()\n\n\t\tselect {\n\t\tcase <-c:\n\n\t\tdefault:\n\t\t\tt.Fatal(\"cannot get watch result\")\n\t\t}\n\n\t\tassert.NotNil(t, body, \"\")\n\t\tassert.Equal(t, body[\"action\"], \"expire\", \"\")\n\n\t\tnode := body[\"node\"].(map[string]interface{})\n\t\tassert.Equal(t, node[\"key\"], \"\/keyindir\/bar\", \"\")\n\t\tassert.Equal(t, node[\"value\"], \"XXX\", \"\")\n\t})\n}\n<commit_msg>fix TestV2WatchKeyInDir test<commit_after>package v2\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/coreos\/etcd\/server\"\n\t\"github.com\/coreos\/etcd\/tests\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\n\/\/ Ensures that a value can be retrieve for a given key.\n\/\/\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/foo\/bar -d value=XXX\n\/\/   $ curl localhost:4001\/v2\/keys\/foo\/bar\n\/\/\nfunc TestV2GetKey(t *testing.T) {\n\ttests.RunServer(func(s *server.Server) {\n\t\tv := url.Values{}\n\t\tv.Set(\"value\", \"XXX\")\n\t\tresp, _ := tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar\"), v)\n\t\ttests.ReadBody(resp)\n\t\tresp, _ = tests.Get(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar\"))\n\t\tbody := tests.ReadBodyJSON(resp)\n\t\tassert.Equal(t, body[\"action\"], \"get\", \"\")\n\t\tnode := body[\"node\"].(map[string]interface{})\n\t\tassert.Equal(t, node[\"key\"], \"\/foo\/bar\", \"\")\n\t\tassert.Equal(t, node[\"value\"], \"XXX\", \"\")\n\t\tassert.Equal(t, node[\"modifiedIndex\"], 2, \"\")\n\t})\n}\n\n\/\/ Ensures that a directory of values can be recursively retrieved for a given key.\n\/\/\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/foo\/x -d value=XXX\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/foo\/y\/z -d value=YYY\n\/\/   $ curl localhost:4001\/v2\/keys\/foo -d recursive=true\n\/\/\nfunc TestV2GetKeyRecursively(t *testing.T) {\n\ttests.RunServer(func(s *server.Server) {\n\t\tv := url.Values{}\n\t\tv.Set(\"value\", \"XXX\")\n\t\tv.Set(\"ttl\", \"10\")\n\t\tresp, _ := tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/x\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\tv.Set(\"value\", \"YYY\")\n\t\tresp, _ = tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/y\/z\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\tresp, _ = tests.Get(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo?recursive=true\"))\n\t\tbody := tests.ReadBodyJSON(resp)\n\t\tassert.Equal(t, body[\"action\"], \"get\", \"\")\n\t\tnode := body[\"node\"].(map[string]interface{})\n\t\tassert.Equal(t, node[\"key\"], \"\/foo\", \"\")\n\t\tassert.Equal(t, node[\"dir\"], true, \"\")\n\t\tassert.Equal(t, node[\"modifiedIndex\"], 2, \"\")\n\t\tassert.Equal(t, len(node[\"nodes\"].([]interface{})), 2, \"\")\n\n\t\tnode0 := node[\"nodes\"].([]interface{})[0].(map[string]interface{})\n\t\tassert.Equal(t, node0[\"key\"], \"\/foo\/x\", \"\")\n\t\tassert.Equal(t, node0[\"value\"], \"XXX\", \"\")\n\t\tassert.Equal(t, node0[\"ttl\"], 10, \"\")\n\n\t\tnode1 := node[\"nodes\"].([]interface{})[1].(map[string]interface{})\n\t\tassert.Equal(t, node1[\"key\"], \"\/foo\/y\", \"\")\n\t\tassert.Equal(t, node1[\"dir\"], true, \"\")\n\n\t\tnode2 := node1[\"nodes\"].([]interface{})[0].(map[string]interface{})\n\t\tassert.Equal(t, node2[\"key\"], \"\/foo\/y\/z\", \"\")\n\t\tassert.Equal(t, node2[\"value\"], \"YYY\", \"\")\n\t})\n}\n\n\/\/ Ensures that a watcher can wait for a value to be set and return it to the client.\n\/\/\n\/\/   $ curl localhost:4001\/v2\/keys\/foo\/bar?wait=true\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/foo\/bar -d value=XXX\n\/\/\nfunc TestV2WatchKey(t *testing.T) {\n\ttests.RunServer(func(s *server.Server) {\n\t\tvar body map[string]interface{}\n\t\tc := make(chan bool)\n\t\tgo func() {\n\t\t\tresp, _ := tests.Get(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar?wait=true\"))\n\t\t\tbody = tests.ReadBodyJSON(resp)\n\t\t\tc <- true\n\t\t}()\n\n\t\t\/\/ Make sure response didn't fire early.\n\t\ttime.Sleep(1 * time.Millisecond)\n\t\tassert.Nil(t, body, \"\")\n\n\t\t\/\/ Set a value.\n\t\tv := url.Values{}\n\t\tv.Set(\"value\", \"XXX\")\n\t\tresp, _ := tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\t\/\/ A response should follow from the GET above.\n\t\ttime.Sleep(1 * time.Millisecond)\n\n\t\tselect {\n\t\tcase <-c:\n\n\t\tdefault:\n\t\t\tt.Fatal(\"cannot get watch result\")\n\t\t}\n\n\t\tassert.NotNil(t, body, \"\")\n\t\tassert.Equal(t, body[\"action\"], \"set\", \"\")\n\n\t\tnode := body[\"node\"].(map[string]interface{})\n\t\tassert.Equal(t, node[\"key\"], \"\/foo\/bar\", \"\")\n\t\tassert.Equal(t, node[\"value\"], \"XXX\", \"\")\n\t\tassert.Equal(t, node[\"modifiedIndex\"], 2, \"\")\n\t})\n}\n\n\/\/ Ensures that a watcher can wait for a value to be set after a given index.\n\/\/\n\/\/   $ curl localhost:4001\/v2\/keys\/foo\/bar?wait=true&waitIndex=4\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/foo\/bar -d value=XXX\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/foo\/bar -d value=YYY\n\/\/\nfunc TestV2WatchKeyWithIndex(t *testing.T) {\n\ttests.RunServer(func(s *server.Server) {\n\t\tvar body map[string]interface{}\n\t\tc := make(chan bool)\n\t\tgo func() {\n\t\t\tresp, _ := tests.Get(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar?wait=true&waitIndex=3\"))\n\t\t\tbody = tests.ReadBodyJSON(resp)\n\t\t\tc <- true\n\t\t}()\n\n\t\t\/\/ Make sure response didn't fire early.\n\t\ttime.Sleep(1 * time.Millisecond)\n\t\tassert.Nil(t, body, \"\")\n\n\t\t\/\/ Set a value (before given index).\n\t\tv := url.Values{}\n\t\tv.Set(\"value\", \"XXX\")\n\t\tresp, _ := tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\t\/\/ Make sure response didn't fire early.\n\t\ttime.Sleep(1 * time.Millisecond)\n\t\tassert.Nil(t, body, \"\")\n\n\t\t\/\/ Set a value (before given index).\n\t\tv.Set(\"value\", \"YYY\")\n\t\tresp, _ = tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/foo\/bar\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\t\/\/ A response should follow from the GET above.\n\t\ttime.Sleep(1 * time.Millisecond)\n\n\t\tselect {\n\t\tcase <-c:\n\n\t\tdefault:\n\t\t\tt.Fatal(\"cannot get watch result\")\n\t\t}\n\n\t\tassert.NotNil(t, body, \"\")\n\t\tassert.Equal(t, body[\"action\"], \"set\", \"\")\n\n\t\tnode := body[\"node\"].(map[string]interface{})\n\t\tassert.Equal(t, node[\"key\"], \"\/foo\/bar\", \"\")\n\t\tassert.Equal(t, node[\"value\"], \"YYY\", \"\")\n\t\tassert.Equal(t, node[\"modifiedIndex\"], 3, \"\")\n\t})\n}\n\n\/\/ Ensures that a watcher can wait for a value to be set after a given index.\n\/\/\n\/\/   $ curl localhost:4001\/v2\/keys\/keyindir\/bar?wait=true\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/keyindir -d dir=true -d ttl=1\n\/\/   $ curl -X PUT localhost:4001\/v2\/keys\/keyindir\/bar -d value=YYY\n\/\/\nfunc TestV2WatchKeyInDir(t *testing.T) {\n\ttests.RunServer(func(s *server.Server) {\n\t\tvar body map[string]interface{}\n\t\tc := make(chan bool)\n\n\t\t\/\/ Set a value (before given index).\n\t\tv := url.Values{}\n\t\tv.Set(\"dir\", \"true\")\n\t\tv.Set(\"ttl\", \"1\")\n\t\tresp, _ := tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/keyindir\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\t\/\/ Set a value (before given index).\n\t\tv = url.Values{}\n\t\tv.Set(\"value\", \"XXX\")\n\t\tresp, _ = tests.PutForm(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/keyindir\/bar\"), v)\n\t\ttests.ReadBody(resp)\n\n\t\tgo func() {\n\t\t\tresp, _ := tests.Get(fmt.Sprintf(\"%s%s\", s.URL(), \"\/v2\/keys\/keyindir\/bar?wait=true\"))\n\t\t\tbody = tests.ReadBodyJSON(resp)\n\t\t\tc <- true\n\t\t}()\n\n\t\t\/\/ wait for expiration, we do have a up to 500 millisecond delay\n\t\ttime.Sleep(1500 * time.Millisecond)\n\n\t\tselect {\n\t\tcase <-c:\n\n\t\tdefault:\n\t\t\tt.Fatal(\"cannot get watch result\")\n\t\t}\n\n\t\tassert.NotNil(t, body, \"\")\n\t\tassert.Equal(t, body[\"action\"], \"expire\", \"\")\n\n\t\tnode := body[\"node\"].(map[string]interface{})\n\t\tassert.Equal(t, node[\"key\"], \"\/keyindir\", \"\")\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Frustra. All rights reserved.\n\/\/ Use of this source code is governed by the MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage bbcode\n\nimport (\n\t\"fmt\"\n\t\"html\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype htmlTag struct {\n\tname     string\n\tvalue    string\n\tattrs    map[string]string\n\tchildren []*htmlTag\n}\n\nfunc newHtmlTag(value string) *htmlTag {\n\treturn &htmlTag{\n\t\tvalue:    value,\n\t\tattrs:    make(map[string]string),\n\t\tchildren: make([]*htmlTag, 0),\n\t}\n}\n\nfunc (t *htmlTag) string() string {\n\tvar value string\n\tif t.value != \"\" {\n\t\tvalue = sanitize(t.value)\n\t}\n\tvar attrString string\n\tfor key, value := range t.attrs {\n\t\tattrString = fmt.Sprintf(`%s %s=\"%s\"`, attrString, key, escapeQuotes(sanitize(value)))\n\t}\n\tif len(t.children) > 0 {\n\t\tvar childrenString string\n\t\tfor _, child := range t.children {\n\t\t\tchildrenString = fmt.Sprint(childrenString, child.string())\n\t\t}\n\t\tif t.name != \"\" {\n\t\t\treturn fmt.Sprintf(`%s<%s%s>%s<\/%s>`, value, t.name, attrString, childrenString, t.name)\n\t\t} else {\n\t\t\treturn fmt.Sprint(value, childrenString)\n\t\t}\n\t} else if t.name != \"\" {\n\t\treturn fmt.Sprintf(`%s<%s%s>`, value, t.name, attrString)\n\t} else {\n\t\treturn value\n\t}\n}\n\nfunc (t *htmlTag) appendChild(child *htmlTag) *htmlTag {\n\tif child == nil {\n\t\tt.children = append(t.children, newHtmlTag(\"\"))\n\t} else {\n\t\tt.children = append(t.children, child)\n\t}\n\treturn t\n}\n\nvar tagMap = map[string]string{\n\t\"quote\":  \"blockquote\",\n\t\"strike\": \"s\",\n}\nvar youtubeRegex = regexp.MustCompile(`(?:https?:\\\/\\\/)?(?:www\\.)?(?:youtube\\.com|youtu\\.be)\\\/(?:watch\\?v=)?([a-zA-Z0-9]+)`)\n\n\/\/ compile transforms a tag and subexpression into an HTML string.\n\/\/ It is only used by the generated parser code.\nfunc compile(in bbTag, expr *htmlTag) *htmlTag {\n\tvar out = newHtmlTag(\"\")\n\n\tswitch in.key {\n\tcase \"url\":\n\t\tout.name = \"a\"\n\t\tif in.value == \"\" {\n\t\t\tif expr != nil {\n\t\t\t\tout.attrs[\"href\"] = safeURL(expr.value)\n\t\t\t} else {\n\t\t\t\tout.attrs[\"href\"] = \"\"\n\t\t\t}\n\t\t} else {\n\t\t\tout.attrs[\"href\"] = safeURL(in.value)\n\t\t}\n\t\tout.appendChild(expr)\n\tcase \"img\":\n\t\tout.name = \"img\"\n\t\tif in.value == \"\" {\n\t\t\tif expr != nil {\n\t\t\t\tout.attrs[\"src\"] = safeURL(expr.value)\n\t\t\t} else {\n\t\t\t\tout.attrs[\"src\"] = \"\"\n\t\t\t}\n\t\t} else {\n\t\t\tout.attrs[\"src\"] = safeURL(in.value)\n\t\t\tif expr != nil {\n\t\t\t\tout.attrs[\"alt\"] = expr.value\n\t\t\t}\n\t\t}\n\tcase \"media\":\n\t\tif expr == nil {\n\t\t\tout.value = \"Embedded video\"\n\t\t} else {\n\t\t\tmatches := youtubeRegex.FindStringSubmatch(expr.value)\n\t\t\tif matches == nil {\n\t\t\t\tout.value = \"Embedded video\"\n\t\t\t} else {\n\t\t\t\tout.name = \"object\"\n\t\t\t\tout.attrs[\"width\"] = \"620\"\n\t\t\t\tout.attrs[\"height\"] = \"349\"\n\n\t\t\t\tparams := map[string]string{\n\t\t\t\t\t\"movie\":             fmt.Sprintf(\"\/\/www.youtube.com\/v\/%s?version=3\", matches[1]),\n\t\t\t\t\t\"wmode\":             \"transparent\",\n\t\t\t\t\t\"allowFullScreen\":   \"true\",\n\t\t\t\t\t\"allowscriptaccess\": \"always\",\n\t\t\t\t}\n\n\t\t\t\tembed := newHtmlTag(\"\")\n\t\t\t\tembed.name = \"embed\"\n\t\t\t\tembed.attrs[\"type\"] = \"application\/x-shockwave-flash\"\n\t\t\t\tembed.attrs[\"width\"] = \"620\"\n\t\t\t\tembed.attrs[\"height\"] = \"349\"\n\t\t\t\tfor name, value := range params {\n\t\t\t\t\tparam := newHtmlTag(\"\")\n\t\t\t\t\tparam.name = \"param\"\n\t\t\t\t\tparam.attrs[\"name\"] = name\n\t\t\t\t\tparam.attrs[\"value\"] = value\n\t\t\t\t\tout.appendChild(param)\n\n\t\t\t\t\tif name == \"movie\" {\n\t\t\t\t\t\tname = \"src\"\n\t\t\t\t\t}\n\t\t\t\t\tembed.attrs[name] = value\n\t\t\t\t}\n\t\t\t\tout.appendChild(embed)\n\t\t\t}\n\t\t}\n\tcase \"center\":\n\t\tout.name = \"div\"\n\t\tout.attrs[\"style\"] = \"text-align: center;\"\n\t\tout.appendChild(expr)\n\tcase \"color\":\n\t\treturn expr\n\tcase \"size\":\n\t\tout.name = \"span\"\n\t\tif size, err := strconv.Atoi(in.value); err == nil {\n\t\t\tout.attrs[\"style\"] = fmt.Sprintf(\"font-size: %dpx;\", size*4)\n\t\t}\n\t\tout.appendChild(expr)\n\tcase \"spoiler\":\n\t\tout.name = \"div\"\n\t\tout.attrs[\"class\"] = \"spoiler-tag\"\n\t\tout.appendChild(expr)\n\tcase \"quote\", \"strike\":\n\t\tout.name = tagMap[in.key]\n\t\tout.appendChild(expr)\n\tcase \"i\", \"b\", \"u\", \"code\":\n\t\tout.name = in.key\n\t\tout.appendChild(expr)\n\t}\n\treturn out\n}\n\nfunc newline() *htmlTag {\n\tvar out = newHtmlTag(\"\")\n\tout.name = \"br\"\n\treturn out\n}\n\nfunc escapeQuotes(raw string) string {\n\treturn strings.Replace(strings.Replace(raw, `\"`, `\\\"`, -1), `\\`, `\\\\`, -1)\n}\n\nfunc safeURL(raw string) string {\n\tu, err := url.Parse(raw)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn strings.Replace(u.String(), `\\`, \"%5C\", -1)\n}\n\nfunc sanitize(raw string) string {\n\treturn html.EscapeString(raw)\n}\n<commit_msg>Update media tag and spoiler tag html<commit_after>\/\/ Copyright 2014 Frustra. All rights reserved.\n\/\/ Use of this source code is governed by the MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage bbcode\n\nimport (\n\t\"fmt\"\n\t\"html\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype htmlTag struct {\n\tname     string\n\tvalue    string\n\tattrs    map[string]string\n\tchildren []*htmlTag\n}\n\nfunc newHtmlTag(value string) *htmlTag {\n\treturn &htmlTag{\n\t\tvalue:    value,\n\t\tattrs:    make(map[string]string),\n\t\tchildren: make([]*htmlTag, 0),\n\t}\n}\n\nfunc (t *htmlTag) string() string {\n\tvar value string\n\tif t.value != \"\" {\n\t\tvalue = sanitize(t.value)\n\t}\n\tvar attrString string\n\tfor key, value := range t.attrs {\n\t\tattrString = fmt.Sprintf(`%s %s=\"%s\"`, attrString, key, escapeQuotes(sanitize(value)))\n\t}\n\tif len(t.children) > 0 {\n\t\tvar childrenString string\n\t\tfor _, child := range t.children {\n\t\t\tchildrenString = fmt.Sprint(childrenString, child.string())\n\t\t}\n\t\tif t.name != \"\" {\n\t\t\treturn fmt.Sprintf(`%s<%s%s>%s<\/%s>`, value, t.name, attrString, childrenString, t.name)\n\t\t} else {\n\t\t\treturn fmt.Sprint(value, childrenString)\n\t\t}\n\t} else if t.name != \"\" {\n\t\treturn fmt.Sprintf(`%s<%s%s>`, value, t.name, attrString)\n\t} else {\n\t\treturn value\n\t}\n}\n\nfunc (t *htmlTag) appendChild(child *htmlTag) *htmlTag {\n\tif child == nil {\n\t\tt.children = append(t.children, newHtmlTag(\"\"))\n\t} else {\n\t\tt.children = append(t.children, child)\n\t}\n\treturn t\n}\n\nvar youtubeRegex = regexp.MustCompile(`(?:https?:\\\/\\\/)?(?:www\\.)?(?:youtube\\.com|youtu\\.be)\\\/(?:watch\\?v=)?([a-zA-Z0-9]+)`)\n\n\/\/ compile transforms a tag and subexpression into an HTML string.\n\/\/ It is only used by the generated parser code.\nfunc compile(in bbTag, expr *htmlTag) *htmlTag {\n\tvar out = newHtmlTag(\"\")\n\n\tswitch in.key {\n\tcase \"url\":\n\t\tout.name = \"a\"\n\t\tif in.value == \"\" {\n\t\t\tif expr != nil {\n\t\t\t\tout.attrs[\"href\"] = safeURL(expr.value)\n\t\t\t} else {\n\t\t\t\tout.attrs[\"href\"] = \"\"\n\t\t\t}\n\t\t} else {\n\t\t\tout.attrs[\"href\"] = safeURL(in.value)\n\t\t}\n\t\tout.appendChild(expr)\n\tcase \"img\":\n\t\tout.name = \"img\"\n\t\tif in.value == \"\" {\n\t\t\tif expr != nil {\n\t\t\t\tout.attrs[\"src\"] = safeURL(expr.value)\n\t\t\t} else {\n\t\t\t\tout.attrs[\"src\"] = \"\"\n\t\t\t}\n\t\t} else {\n\t\t\tout.attrs[\"src\"] = safeURL(in.value)\n\t\t\tif expr != nil {\n\t\t\t\tout.attrs[\"alt\"] = expr.value\n\t\t\t}\n\t\t}\n\tcase \"media\":\n\t\tif expr == nil {\n\t\t\tout.value = \"Embedded video\"\n\t\t} else {\n\t\t\tout.name = \"div\"\n\t\t\tout.attrs[\"class\"] = \"embedded-video\"\n\n\t\t\tobj := newHtmlTag(\"Embedded video\")\n\t\t\tout.appendChild(obj)\n\n\t\t\tmatches := youtubeRegex.FindStringSubmatch(expr.value)\n\t\t\tif matches != nil {\n\t\t\t\tobj = newHtmlTag(\"\")\n\t\t\t\tobj.name = \"object\"\n\t\t\t\tobj.attrs[\"width\"] = \"620\"\n\t\t\t\tobj.attrs[\"height\"] = \"349\"\n\n\t\t\t\tparams := map[string]string{\n\t\t\t\t\t\"movie\":             fmt.Sprintf(\"\/\/www.youtube.com\/v\/%s?version=3\", matches[1]),\n\t\t\t\t\t\"wmode\":             \"transparent\",\n\t\t\t\t\t\"allowFullScreen\":   \"true\",\n\t\t\t\t\t\"allowscriptaccess\": \"always\",\n\t\t\t\t}\n\n\t\t\t\tembed := newHtmlTag(\"\")\n\t\t\t\tembed.name = \"embed\"\n\t\t\t\tembed.attrs[\"type\"] = \"application\/x-shockwave-flash\"\n\t\t\t\tembed.attrs[\"width\"] = \"620\"\n\t\t\t\tembed.attrs[\"height\"] = \"349\"\n\t\t\t\tfor name, value := range params {\n\t\t\t\t\tparam := newHtmlTag(\"\")\n\t\t\t\t\tparam.name = \"param\"\n\t\t\t\t\tparam.attrs[\"name\"] = name\n\t\t\t\t\tparam.attrs[\"value\"] = value\n\t\t\t\t\tobj.appendChild(param)\n\n\t\t\t\t\tif name == \"movie\" {\n\t\t\t\t\t\tname = \"src\"\n\t\t\t\t\t}\n\t\t\t\t\tembed.attrs[name] = value\n\t\t\t\t}\n\t\t\t\tobj.appendChild(embed)\n\t\t\t\tout.appendChild(obj)\n\t\t\t}\n\t\t}\n\tcase \"center\":\n\t\tout.name = \"div\"\n\t\tout.attrs[\"style\"] = \"text-align: center;\"\n\t\tout.appendChild(expr)\n\tcase \"color\":\n\t\treturn expr\n\tcase \"size\":\n\t\tout.name = \"span\"\n\t\tif size, err := strconv.Atoi(in.value); err == nil {\n\t\t\tout.attrs[\"style\"] = fmt.Sprintf(\"font-size: %dpx;\", size*4)\n\t\t}\n\t\tout.appendChild(expr)\n\tcase \"spoiler\":\n\t\tout.name = \"div\"\n\t\tout.attrs[\"class\"] = \"expandable collapsed\"\n\t\tout.appendChild(expr)\n\tcase \"quote\":\n\t\tout.name = \"blockquote\"\n\t\twho := \"\"\n\t\tif name, ok := in.args[\"name\"]; ok && name != \"\" {\n\t\t\twho = name\n\t\t} else {\n\t\t\twho = in.value\n\t\t}\n\t\tif who != \"\" {\n\t\t\tcite := newHtmlTag(\"\")\n\t\t\tcite.name = \"cite\"\n\t\t\tcite.appendChild(newHtmlTag(who + \" said:\"))\n\t\t\tout.appendChild(cite)\n\t\t}\n\t\tout.appendChild(expr)\n\tcase \"strike\":\n\t\tout.name = \"s\"\n\t\tout.appendChild(expr)\n\tcase \"i\", \"b\", \"u\", \"code\":\n\t\tout.name = in.key\n\t\tout.appendChild(expr)\n\t}\n\treturn out\n}\n\nfunc newline() *htmlTag {\n\tvar out = newHtmlTag(\"\")\n\tout.name = \"br\"\n\treturn out\n}\n\nfunc escapeQuotes(raw string) string {\n\treturn strings.Replace(strings.Replace(raw, `\"`, `\\\"`, -1), `\\`, `\\\\`, -1)\n}\n\nfunc safeURL(raw string) string {\n\tu, err := url.Parse(raw)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn strings.Replace(u.String(), `\\`, \"%5C\", -1)\n}\n\nfunc sanitize(raw string) string {\n\treturn html.EscapeString(raw)\n}\n<|endoftext|>"}
{"text":"<commit_before>package handlers\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"google.golang.org\/appengine\"\n\t\"google.golang.org\/appengine\/datastore\"\n\t\"google.golang.org\/appengine\/log\"\n\t\"google.golang.org\/appengine\/memcache\"\n\t\"google.golang.org\/appengine\/user\"\n\n\t\"github.com\/icco\/natnatnat\/models\"\n\t\"github.com\/pilu\/traffic\"\n)\n\ntype ArchiveData struct {\n\tYears   *map[string]Year\n\tPosts   *[]models.Entry\n\tIsAdmin bool\n}\n\n\/\/ TODO(icco): Rewrite to fix map iteration problems.\ntype Year map[time.Month]Month\ntype Month []Day\ntype Day []int64\n\nvar months = [12]time.Month{\n\ttime.January,\n\ttime.February,\n\ttime.March,\n\ttime.April,\n\ttime.May,\n\ttime.June,\n\ttime.July,\n\ttime.August,\n\ttime.September,\n\ttime.October,\n\ttime.November,\n\ttime.December,\n}\n\nfunc ArchiveTaskHandler(w traffic.ResponseWriter, r *traffic.Request) {\n\tc := appengine.NewContext(r.Request)\n\n\tentries, err := models.AllPosts(c)\n\tif err != nil {\n\t\tlog.Errorf(c, err.Error())\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\tlog.Infof(c, \"Retrieved data: %d.\", len(*entries))\n\n\tyears := make(map[string]Year)\n\n\toldest := (*entries)[len(*entries)-1].Datetime\n\tnewest := (*entries)[0].Datetime\n\n\tlog.Infof(c, \"Oldest: %v, Newest: %v\", oldest, newest)\n\n\tfor year := oldest.Year(); year <= newest.Year(); year += 1 {\n\t\tystr := strconv.Itoa(year)\n\t\tyears[ystr] = make(Year)\n\t\tlog.Infof(c, \"Adding %d.\", year)\n\t\tfor _, month := range months {\n\t\t\tif year < newest.Year() || (year == newest.Year() && month <= newest.Month()) {\n\t\t\t\tyears[ystr][month] = make([]Day, daysIn(month, year))\n\t\t\t\tlog.Debugf(c, \"Adding %d\/%d - %d days.\", year, month, len(years[ystr][month]))\n\t\t\t}\n\t\t}\n\t}\n\n\tq := models.ArchivePageQuery()\n\tt := q.Run(c)\n\tfor {\n\t\tvar p models.Entry\n\t\t_, err := t.Next(&p)\n\t\tif err == datastore.Done {\n\t\t\tbreak \/\/ No further entities match the query.\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Errorf(c, \"Error fetching next Entry: %v\", err)\n\t\t\tbreak\n\t\t}\n\n\t\tyear := strconv.Itoa(p.Datetime.Year())\n\t\tyint := p.Datetime.Year()\n\t\tmonth := p.Datetime.Month()\n\t\tday := p.Datetime.Day()\n\t\tlog.Infof(c, \"Trying post id %d\", p.Id)\n\n\t\tif years[year] == nil {\n\t\t\tyears[year] = make(Year)\n\t\t\tlog.Errorf(c, \"%s isn't a valid year.\", year)\n\t\t}\n\n\t\tif years[year][month] == nil {\n\t\t\tlog.Errorf(c, \"%s\/%d isn't a valid month.\", year, month)\n\t\t\tyears[year][month] = make([]Day, daysIn(month, yint))\n\t\t}\n\n\t\tif years[year][month][day] == nil {\n\t\t\tlog.Infof(c, \"Making %s\/%d\/%d\", year, month, day)\n\t\t\tyears[year][month][day] = make(Day, 0)\n\t\t}\n\n\t\t\/\/ log.Infof(c, \"Appending %d\/%d\/%d: %+v\", year, month, day, years[year][month][day])\n\t\tyears[year][month][day] = append(years[year][month][day], p.Id)\n\t}\n\tlog.Infof(c, \"Added posts.\")\n\n\t\/\/ https:\/\/blog.golang.org\/json-and-go\n\tb, err := json.Marshal(years)\n\tif err != nil {\n\t\tlog.Errorf(c, err.Error())\n\t\thttp.Error(w, err.Error(), 500)\n\t}\n\n\titem := &memcache.Item{\n\t\tKey:   \"archive_data\",\n\t\tValue: b,\n\t}\n\n\t\/\/ Set the item, unconditionally\n\tif err := memcache.Set(c, item); err != nil {\n\t\tlog.Errorf(c, \"error setting item: %v\", err)\n\t}\n}\n\nfunc ArchiveHandler(w traffic.ResponseWriter, r *traffic.Request) {\n\tc := appengine.NewContext(r.Request)\n\n\tentries, err := models.AllPosts(c)\n\tif err != nil {\n\t\tlog.Errorf(c, err.Error())\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\tlog.Infof(c, \"Retrieved data: %d.\", len(*entries))\n\n\t\/\/ Get the item from the memcache\n\tvar years map[string]Year\n\tif year_data, err := memcache.Get(c, \"archive_data\"); err == memcache.ErrCacheMiss {\n\t\tlog.Infof(c, \"item not in the cache\")\n\t} else if err != nil {\n\t\tlog.Errorf(c, \"error getting item: %v\", err)\n\t} else {\n\t\terr := json.Unmarshal(year_data.Value, &years)\n\t\tif err != nil {\n\t\t\tlog.Errorf(c, err.Error())\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\t}\n\n\tdata := &ArchiveData{Years: &years, IsAdmin: user.IsAdmin(c), Posts: entries}\n\tw.Render(\"archive\", data)\n}\n\n\/\/ daysIn returns the number of days in a month for a given year.\nfunc daysIn(m time.Month, year int) int {\n\t\/\/ This is equivalent to time.daysIn(m, year).\n\treturn time.Date(year, m+1, 0, 0, 0, 0, 0, time.UTC).Day()\n}\n<commit_msg>strings<commit_after>package handlers\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"google.golang.org\/appengine\"\n\t\"google.golang.org\/appengine\/datastore\"\n\t\"google.golang.org\/appengine\/log\"\n\t\"google.golang.org\/appengine\/memcache\"\n\t\"google.golang.org\/appengine\/user\"\n\n\t\"github.com\/icco\/natnatnat\/models\"\n\t\"github.com\/pilu\/traffic\"\n)\n\ntype ArchiveData struct {\n\tYears   *map[string]Year\n\tPosts   *[]models.Entry\n\tIsAdmin bool\n}\n\ntype Year map[string]Month\ntype Month []Day\ntype Day []int64\n\nvar months = [12]time.Month{\n\ttime.January,\n\ttime.February,\n\ttime.March,\n\ttime.April,\n\ttime.May,\n\ttime.June,\n\ttime.July,\n\ttime.August,\n\ttime.September,\n\ttime.October,\n\ttime.November,\n\ttime.December,\n}\n\nfunc ArchiveTaskHandler(w traffic.ResponseWriter, r *traffic.Request) {\n\tc := appengine.NewContext(r.Request)\n\n\tentries, err := models.AllPosts(c)\n\tif err != nil {\n\t\tlog.Errorf(c, err.Error())\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\tlog.Infof(c, \"Retrieved data: %d.\", len(*entries))\n\n\tyears := make(map[string]Year)\n\n\toldest := (*entries)[len(*entries)-1].Datetime\n\tnewest := (*entries)[0].Datetime\n\n\tlog.Infof(c, \"Oldest: %v, Newest: %v\", oldest, newest)\n\n\tfor year := oldest.Year(); year <= newest.Year(); year += 1 {\n\t\tystr := strconv.Itoa(year)\n\t\tyears[ystr] = make(Year)\n\t\tlog.Infof(c, \"Adding %d.\", year)\n\t\tfor _, month := range months {\n\t\t\tif year < newest.Year() || (year == newest.Year() && month <= newest.Month()) {\n\t\t\t\tmstr := month.String()\n\t\t\t\tyears[ystr][mstr] = make([]Day, daysIn(month, year))\n\t\t\t\tlog.Debugf(c, \"Adding %d\/%d - %d days.\", year, month, len(years[ystr][mstr]))\n\t\t\t}\n\t\t}\n\t}\n\n\tq := models.ArchivePageQuery()\n\tt := q.Run(c)\n\tfor {\n\t\tvar p models.Entry\n\t\t_, err := t.Next(&p)\n\t\tif err == datastore.Done {\n\t\t\tbreak \/\/ No further entities match the query.\n\t\t}\n\n\t\tif err != nil {\n\t\t\tlog.Errorf(c, \"Error fetching next Entry: %v\", err)\n\t\t\tbreak\n\t\t}\n\n\t\tyear := strconv.Itoa(p.Datetime.Year())\n\t\tyint := p.Datetime.Year()\n\t\tmonth := p.Datetime.Month()\n\t\tmstr := month.String()\n\t\tday := p.Datetime.Day()\n\t\tlog.Infof(c, \"Trying post id %d\", p.Id)\n\n\t\tif years[year] == nil {\n\t\t\tyears[year] = make(Year)\n\t\t\tlog.Errorf(c, \"%s isn't a valid year.\", year)\n\t\t}\n\n\t\tif years[year][mstr] == nil {\n\t\t\tlog.Errorf(c, \"%s\/%d isn't a valid month.\", year, month)\n\t\t\tyears[year][mstr] = make([]Day, daysIn(month, yint))\n\t\t}\n\n\t\tif years[year][mstr][day] == nil {\n\t\t\tlog.Infof(c, \"Making %s\/%d\/%d\", year, month, day)\n\t\t\tyears[year][mstr][day] = make(Day, 0)\n\t\t}\n\n\t\tyears[year][mstr][day] = append(years[year][mstr][day], p.Id)\n\t}\n\tlog.Infof(c, \"Added posts.\")\n\n\t\/\/ https:\/\/blog.golang.org\/json-and-go\n\tb, err := json.Marshal(years)\n\tif err != nil {\n\t\tlog.Errorf(c, err.Error())\n\t\thttp.Error(w, err.Error(), 500)\n\t}\n\n\titem := &memcache.Item{\n\t\tKey:   \"archive_data\",\n\t\tValue: b,\n\t}\n\n\t\/\/ Set the item, unconditionally\n\tif err := memcache.Set(c, item); err != nil {\n\t\tlog.Errorf(c, \"error setting item: %v\", err)\n\t}\n}\n\nfunc ArchiveHandler(w traffic.ResponseWriter, r *traffic.Request) {\n\tc := appengine.NewContext(r.Request)\n\n\tentries, err := models.AllPosts(c)\n\tif err != nil {\n\t\tlog.Errorf(c, err.Error())\n\t\thttp.Error(w, err.Error(), 500)\n\t\treturn\n\t}\n\tlog.Infof(c, \"Retrieved data: %d.\", len(*entries))\n\n\t\/\/ Get the item from the memcache\n\tvar years map[string]Year\n\tif year_data, err := memcache.Get(c, \"archive_data\"); err == memcache.ErrCacheMiss {\n\t\tlog.Infof(c, \"item not in the cache\")\n\t} else if err != nil {\n\t\tlog.Errorf(c, \"error getting item: %v\", err)\n\t} else {\n\t\terr := json.Unmarshal(year_data.Value, &years)\n\t\tif err != nil {\n\t\t\tlog.Errorf(c, err.Error())\n\t\t\thttp.Error(w, err.Error(), 500)\n\t\t\treturn\n\t\t}\n\t}\n\n\tdata := &ArchiveData{Years: &years, IsAdmin: user.IsAdmin(c), Posts: entries}\n\tw.Render(\"archive\", data)\n}\n\n\/\/ daysIn returns the number of days in a month for a given year.\nfunc daysIn(m time.Month, year int) int {\n\t\/\/ This is equivalent to time.daysIn(m, year).\n\treturn time.Date(year, m+1, 0, 0, 0, 0, 0, time.UTC).Day()\n}\n<|endoftext|>"}
{"text":"<commit_before>package prompt\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/josledp\/goprompt\/prompt\/plugins\"\n\t\"github.com\/josledp\/termcolor\"\n)\n\n\/\/Prompt is the struct with the prompt options\/config\ntype Prompt struct {\n\toptions map[string]interface{}\n\tcache   *Cache\n}\n\n\/\/Plugin is the interface all the plugins MUST implement\ntype Plugin interface {\n\tName() string\n\tLoad(pr plugins.Prompter) error\n\tGet(format func(string, ...termcolor.Mode) string) (string, []termcolor.Mode)\n}\n\n\/\/New returns a new promp\nfunc New(options map[string]interface{}) Prompt {\n\tc, err := newCache()\n\tif err != nil {\n\t\tlog.Printf(\"unable to initializa cache: %v\", err)\n\t}\n\treturn Prompt{options, c}\n}\n\n\/\/GetOption returns the option value for key\nfunc (pr Prompt) GetOption(key string) (interface{}, bool) {\n\tvalue, ok := pr.options[key]\n\treturn value, ok\n}\n\n\/\/GetCache recovers a value from cache\nfunc (pr Prompt) GetCache(key string) (interface{}, bool) {\n\t\/\/Encapsulate more cache?\n\tif pr.cache == nil {\n\t\treturn nil, false\n\t}\n\tvalue, ok := pr.cache.data[key]\n\treturn value, ok\n}\n\n\/\/Cache caches a key, value on cache\nfunc (pr Prompt) Cache(key string, value interface{}) error {\n\tif pr.cache == nil {\n\t\treturn fmt.Errorf(\"Cache not initialized\")\n\t}\n\tif pr.cache.data == nil {\n\t\tpr.cache.data = make(map[string]interface{})\n\t}\n\tpr.cache.data[key] = value\n\treturn nil\n}\n\n\/\/Compile processes the template and returns a prompt string\nfunc (pr Prompt) Compile(template string, color bool) string {\n\tvar format func(string, ...termcolor.Mode) string\n\toutput := template\n\n\tif color {\n\n\t\tshell := pr.detectShell()\n\t\tswitch shell {\n\t\tcase \"bash\":\n\t\t\tformat = termcolor.EscapedFormat\n\t\tcase \"fish\":\n\t\t\tformat = termcolor.Format\n\t\tcase \"zsh\":\n\t\t\tformat = termcolor.Format\n\n\t\tdefault:\n\t\t\t\/\/Defaut failsafe\n\t\t\tformat = func(s string, modes ...termcolor.Mode) string { return s }\n\t\t}\n\t} else {\n\n\t\tformat = func(s string, modes ...termcolor.Mode) string { return s }\n\t}\n\n\t\/\/ map plugin by name\n\tmPlugins := make(map[string]Plugin)\n\tfor _, p := range availablePlugins {\n\t\tmPlugins[p.Name()] = p\n\t}\n\n\t\/\/Regular expresions for matching on template\n\treChunk, _ := regexp.Compile(\"<[^<>]*>\")\n\trePlugin, _ := regexp.Compile(\"%[a-z]*%\")\n\tchunks := reChunk.FindAllString(template, -1)\n\n\t\/\/Channel for plugins to write (parallel plugin processing)\n\tpluginsOutput := make(chan []string)\n\tpluginsWg := sync.WaitGroup{}\n\tpluginsWg.Add(len(chunks))\n\tgo func() {\n\t\tpluginsWg.Wait()\n\t\tclose(pluginsOutput)\n\t}()\n\n\t\/\/For each chunk of <[^<>]*> we process it in parallel putting in the channel the string to replace on template\n\tfor _, chunk := range chunks {\n\t\tgo func(chunk string) {\n\t\t\tdefer pluginsWg.Done()\n\t\t\tprocessedChunk := chunk[1 : len(chunk)-1]\n\t\t\trawPlugin := rePlugin.FindString(chunk)\n\t\t\tplugin := rawPlugin[1 : len(rawPlugin)-1]\n\t\t\tif p, ok := mPlugins[plugin]; ok {\n\t\t\t\t\/\/TODO +options\n\t\t\t\terr := p.Load(pr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Unable to load plugin %s: %v\", plugin, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\toutput, modes := p.Get(format)\n\t\t\t\tif output != \"\" {\n\t\t\t\t\textra := strings.Split(processedChunk, rawPlugin)\n\t\t\t\t\tfor _, e := range extra {\n\t\t\t\t\t\tuseless, _ := regexp.MatchString(\"^[ ]*$\", e)\n\t\t\t\t\t\tif !useless {\n\t\t\t\t\t\t\tprocessed := format(e, modes...)\n\t\t\t\t\t\t\tprocessedChunk = strings.Replace(processedChunk, e, processed, -1)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tprocessedChunk = strings.Replace(processedChunk, rawPlugin, output, -1)\n\t\t\t\t\tpluginsOutput <- []string{chunk, format(processedChunk, modes...)}\n\t\t\t\t} else {\n\t\t\t\t\tpluginsOutput <- []string{chunk, \"\"}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Plugin %s not found\", plugin)\n\t\t\t}\n\n\t\t}(chunk)\n\t}\n\tfor rep := range pluginsOutput {\n\t\toutput = strings.Replace(output, rep[0], rep[1], -1)\n\t}\n\terr := pr.cache.save()\n\tif err != nil {\n\t\tlog.Printf(\"Unable to save cache: %v\", err)\n\t}\n\treturn output\n}\n\nvar availablePlugins []Plugin\n\nfunc init() {\n\tavailablePlugins = []Plugin{\n\t\t&plugins.Aws{},\n\t\t&plugins.Git{},\n\t\t&plugins.LastCommand{},\n\t\t&plugins.Path{},\n\t\t&plugins.Python{},\n\t\t&plugins.User{},\n\t\t&plugins.Hostname{},\n\t\t&plugins.UserChar{},\n\t\t&plugins.Golang{},\n\t}\n\n}\n\nfunc (p Prompt) detectShell() string {\n\tpid := os.Getppid()\n\tcmdlineFile := fmt.Sprintf(\"\/proc\/%d\/cmdline\", pid)\n\tcmdline, err := ioutil.ReadFile(cmdlineFile)\n\tif err != nil {\n\t\treturn \"unknown\"\n\t}\n\n\tshells := []string{\"bash\", \"zsh\", \"fish\"}\n\tfor _, shell := range shells {\n\t\tif matches, _ := regexp.Match(shell, cmdline); matches {\n\t\t\treturn shell\n\t\t}\n\t}\n\treturn \"unknown\"\n}\n<commit_msg>typo on receiver name<commit_after>package prompt\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"regexp\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/josledp\/goprompt\/prompt\/plugins\"\n\t\"github.com\/josledp\/termcolor\"\n)\n\n\/\/Prompt is the struct with the prompt options\/config\ntype Prompt struct {\n\toptions map[string]interface{}\n\tcache   *Cache\n}\n\n\/\/Plugin is the interface all the plugins MUST implement\ntype Plugin interface {\n\tName() string\n\tLoad(pr plugins.Prompter) error\n\tGet(format func(string, ...termcolor.Mode) string) (string, []termcolor.Mode)\n}\n\n\/\/New returns a new promp\nfunc New(options map[string]interface{}) Prompt {\n\tc, err := newCache()\n\tif err != nil {\n\t\tlog.Printf(\"unable to initializa cache: %v\", err)\n\t}\n\treturn Prompt{options, c}\n}\n\n\/\/GetOption returns the option value for key\nfunc (pr Prompt) GetOption(key string) (interface{}, bool) {\n\tvalue, ok := pr.options[key]\n\treturn value, ok\n}\n\n\/\/GetCache recovers a value from cache\nfunc (pr Prompt) GetCache(key string) (interface{}, bool) {\n\t\/\/Encapsulate more cache?\n\tif pr.cache == nil {\n\t\treturn nil, false\n\t}\n\tvalue, ok := pr.cache.data[key]\n\treturn value, ok\n}\n\n\/\/Cache caches a key, value on cache\nfunc (pr Prompt) Cache(key string, value interface{}) error {\n\tif pr.cache == nil {\n\t\treturn fmt.Errorf(\"Cache not initialized\")\n\t}\n\tif pr.cache.data == nil {\n\t\tpr.cache.data = make(map[string]interface{})\n\t}\n\tpr.cache.data[key] = value\n\treturn nil\n}\n\n\/\/Compile processes the template and returns a prompt string\nfunc (pr Prompt) Compile(template string, color bool) string {\n\tvar format func(string, ...termcolor.Mode) string\n\toutput := template\n\n\tif color {\n\n\t\tshell := pr.detectShell()\n\t\tswitch shell {\n\t\tcase \"bash\":\n\t\t\tformat = termcolor.EscapedFormat\n\t\tcase \"fish\":\n\t\t\tformat = termcolor.Format\n\t\tcase \"zsh\":\n\t\t\tformat = termcolor.Format\n\n\t\tdefault:\n\t\t\t\/\/Defaut failsafe\n\t\t\tformat = func(s string, modes ...termcolor.Mode) string { return s }\n\t\t}\n\t} else {\n\n\t\tformat = func(s string, modes ...termcolor.Mode) string { return s }\n\t}\n\n\t\/\/ map plugin by name\n\tmPlugins := make(map[string]Plugin)\n\tfor _, p := range availablePlugins {\n\t\tmPlugins[p.Name()] = p\n\t}\n\n\t\/\/Regular expresions for matching on template\n\treChunk, _ := regexp.Compile(\"<[^<>]*>\")\n\trePlugin, _ := regexp.Compile(\"%[a-z]*%\")\n\tchunks := reChunk.FindAllString(template, -1)\n\n\t\/\/Channel for plugins to write (parallel plugin processing)\n\tpluginsOutput := make(chan []string)\n\tpluginsWg := sync.WaitGroup{}\n\tpluginsWg.Add(len(chunks))\n\tgo func() {\n\t\tpluginsWg.Wait()\n\t\tclose(pluginsOutput)\n\t}()\n\n\t\/\/For each chunk of <[^<>]*> we process it in parallel putting in the channel the string to replace on template\n\tfor _, chunk := range chunks {\n\t\tgo func(chunk string) {\n\t\t\tdefer pluginsWg.Done()\n\t\t\tprocessedChunk := chunk[1 : len(chunk)-1]\n\t\t\trawPlugin := rePlugin.FindString(chunk)\n\t\t\tplugin := rawPlugin[1 : len(rawPlugin)-1]\n\t\t\tif p, ok := mPlugins[plugin]; ok {\n\t\t\t\t\/\/TODO +options\n\t\t\t\terr := p.Load(pr)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"Unable to load plugin %s: %v\", plugin, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\toutput, modes := p.Get(format)\n\t\t\t\tif output != \"\" {\n\t\t\t\t\textra := strings.Split(processedChunk, rawPlugin)\n\t\t\t\t\tfor _, e := range extra {\n\t\t\t\t\t\tuseless, _ := regexp.MatchString(\"^[ ]*$\", e)\n\t\t\t\t\t\tif !useless {\n\t\t\t\t\t\t\tprocessed := format(e, modes...)\n\t\t\t\t\t\t\tprocessedChunk = strings.Replace(processedChunk, e, processed, -1)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tprocessedChunk = strings.Replace(processedChunk, rawPlugin, output, -1)\n\t\t\t\t\tpluginsOutput <- []string{chunk, format(processedChunk, modes...)}\n\t\t\t\t} else {\n\t\t\t\t\tpluginsOutput <- []string{chunk, \"\"}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Plugin %s not found\", plugin)\n\t\t\t}\n\n\t\t}(chunk)\n\t}\n\tfor rep := range pluginsOutput {\n\t\toutput = strings.Replace(output, rep[0], rep[1], -1)\n\t}\n\terr := pr.cache.save()\n\tif err != nil {\n\t\tlog.Printf(\"Unable to save cache: %v\", err)\n\t}\n\treturn output\n}\n\nvar availablePlugins []Plugin\n\nfunc init() {\n\tavailablePlugins = []Plugin{\n\t\t&plugins.Aws{},\n\t\t&plugins.Git{},\n\t\t&plugins.LastCommand{},\n\t\t&plugins.Path{},\n\t\t&plugins.Python{},\n\t\t&plugins.User{},\n\t\t&plugins.Hostname{},\n\t\t&plugins.UserChar{},\n\t\t&plugins.Golang{},\n\t}\n\n}\n\nfunc (pr Prompt) detectShell() string {\n\tpid := os.Getppid()\n\tcmdlineFile := fmt.Sprintf(\"\/proc\/%d\/cmdline\", pid)\n\tcmdline, err := ioutil.ReadFile(cmdlineFile)\n\tif err != nil {\n\t\treturn \"unknown\"\n\t}\n\n\tshells := []string{\"bash\", \"zsh\", \"fish\"}\n\tfor _, shell := range shells {\n\t\tif matches, _ := regexp.Match(shell, cmdline); matches {\n\t\t\treturn shell\n\t\t}\n\t}\n\treturn \"unknown\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/gofxh\/blog\/lib\/base\"\n\t\"github.com\/gofxh\/blog\/lib\/core\"\n\t\"github.com\/gofxh\/blog\/mvc\/action\"\n\t\"github.com\/lunny\/tango\"\n\t\"github.com\/tango-contrib\/binding\"\n)\n\n\/\/ login controller\ntype LoginController struct {\n\ttango.Ctx\n\tbinding.Binder\n}\n\n\/\/ login controller post method\nfunc (l *LoginController) Post() {\n\tvar form action.LoginForm\n\tif e := l.Bind(&form); e.Len() > 0 {\n\t\tl.ServeJson(core.NewErrorResult(errors.New(e[0].Error())))\n\t\treturn\n\t}\n\tform.Ip = l.Req().RemoteAddr\n\tform.UserAgent = l.Req().UserAgent()\n\tform.Expire = 3600 * 24 * 7\n\tresult := base.Action.Call(action.Login, &form)\n\tl.ServeJson(result)\n}\n<commit_msg>add login cookie saving<commit_after>package api\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/gofxh\/blog\/lib\/base\"\n\t\"github.com\/gofxh\/blog\/lib\/core\"\n\t\"github.com\/gofxh\/blog\/lib\/entity\"\n\t\"github.com\/gofxh\/blog\/mvc\/action\"\n\t\"github.com\/lunny\/tango\"\n\t\"github.com\/tango-contrib\/binding\"\n\t\"net\/http\"\n\t\"time\"\n)\n\n\/\/ login controller\ntype LoginController struct {\n\ttango.Ctx\n\tbinding.Binder\n}\n\n\/\/ login controller post method\nfunc (l *LoginController) Post() {\n\tvar form action.LoginForm\n\tif e := l.Bind(&form); e.Len() > 0 {\n\t\tl.ServeJson(core.NewErrorResult(errors.New(e[0].Error())))\n\t\treturn\n\t}\n\tform.Ip = l.Req().RemoteAddr\n\tform.UserAgent = l.Req().UserAgent()\n\tform.Expire = 3600 * 24 * 7\n\tresult := base.Action.Call(action.Login, &form)\n\tif result.Meta.Status {\n\t\ttk := result.Data[\"token\"].(*entity.Token)\n\t\tl.Cookies().Set(&http.Cookie{\n\t\t\tName:   \"token\",\n\t\t\tValue:  tk.Value,\n\t\t\tMaxAge: int(tk.ExpireTime - time.Now().Unix()),\n\t\t})\n\t}\n\tl.ServeJson(result)\n}\n<|endoftext|>"}
{"text":"<commit_before>package graph\n\ntype NodeInfo struct {\n\tPre           int\n\tPost          int\n\tIDom          NodeID\n\tLoopHead      NodeID\n\tIsHead        bool\n\tIsIrreducible bool\n\tLive          bool\n}\n\ntype EdgeType int\n\nconst (\n\tDEAD EdgeType = iota\n\tFORWARD\n\tBACKWARD\n\tCROSS\n\tREENTRY\n)\n\ntype loopFinder struct {\n\tgraph     *Graph\n\tnode      []NodeInfo\n\tedge      []EdgeType\n\tpostorder []NodeID\n\tdepth     []int\n\tcurrent   int\n}\n\nfunc (lf *loopFinder) beginTraversingNode(n NodeID, prev NodeID) {\n\tlf.current += 1\n\n\tlf.node[n] = NodeInfo{\n\t\tPre:      lf.current,\n\t\tIDom:     prev, \/\/ A reasonable inital guess.\n\t\tLoopHead: NoNode,\n\t\tLive:     true,\n\t}\n\n\tlf.depth[n] = lf.current\n}\n\nfunc (lf *loopFinder) endTraversingNode(n NodeID) {\n\tlf.current += 1\n\tlf.node[n].Post = lf.current\n\n\tlf.depth[n] = 0\n\n\tlf.postorder = append(lf.postorder, n)\n}\n\nfunc (lf *loopFinder) isUnprocessed(n NodeID) bool {\n\treturn !lf.node[n].Live\n}\n\nfunc (lf *loopFinder) isBeingProcessed(dst NodeID) bool {\n\treturn lf.depth[dst] > 0\n}\n\nfunc (lf *loopFinder) markLoopHeader(child NodeID, head NodeID) {\n\tif child == head {\n\t\t\/\/ Trivial loop.\n\t\treturn\n\t}\n\tchildHead := lf.node[child].LoopHead\n\tfor childHead != NoNode {\n\t\tif childHead == head {\n\t\t\treturn\n\t\t}\n\t\tif lf.depth[childHead] < lf.depth[head] {\n\t\t\t\/\/ Found a closer head for this child, adopt it.\n\t\t\tlf.node[child].LoopHead = head\n\t\t\tchild, head = head, childHead\n\t\t} else {\n\t\t\tchild = childHead\n\t\t}\n\t\tchildHead = lf.node[child].LoopHead\n\t}\n\tlf.node[child].LoopHead = head\n}\n\nfunc (lf *loopFinder) process(n NodeID, prev NodeID) {\n\tlf.beginTraversingNode(n, prev)\n\txit := lf.graph.ExitIterator(n)\n\tfor xit.HasNext() {\n\t\te, next := xit.GetNext()\n\t\tif lf.isUnprocessed(next) {\n\t\t\tlf.edge[e] = FORWARD\n\t\t\tlf.process(next, n)\n\n\t\t\t\/\/ Propagage loop headers upwards.\n\t\t\thead := lf.node[next].LoopHead\n\t\t\tif head != NoNode {\n\t\t\t\tlf.markLoopHeader(n, head)\n\t\t\t}\n\t\t} else if lf.isBeingProcessed(next) {\n\t\t\tlf.edge[e] = BACKWARD\n\t\t\tlf.node[next].IsHead = true\n\t\t\tlf.markLoopHeader(n, next)\n\t\t} else {\n\t\t\tlf.edge[e] = CROSS\n\t\t\tif lf.node[next].LoopHead != NoNode {\n\t\t\t\t\/\/ Propagate loop header from cross edge.\n\t\t\t\totherHead := lf.node[next].LoopHead\n\t\t\t\tif lf.isBeingProcessed(otherHead) {\n\t\t\t\t\tlf.markLoopHeader(n, otherHead)\n\t\t\t\t} else {\n\t\t\t\t\tlf.edge[e] = REENTRY\n\t\t\t\t\tlf.node[otherHead].IsIrreducible = true\n\t\t\t\t\t\/\/ Find and mark the common loop head.\n\t\t\t\t\totherHead = lf.node[otherHead].LoopHead\n\t\t\t\t\tfor otherHead != NoNode {\n\t\t\t\t\t\tif lf.isBeingProcessed(otherHead) {\n\t\t\t\t\t\t\tlf.markLoopHeader(n, otherHead)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\totherHead = lf.node[otherHead].LoopHead\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlf.endTraversingNode(n)\n}\n\nfunc Intersect(nodes []NodeInfo, n0 NodeID, n1 NodeID) NodeID {\n\ti0 := nodes[n0].Post\n\ti1 := nodes[n1].Post\n\tfor i0 != i1 {\n\t\tfor i0 < i1 {\n\t\t\tn0 = nodes[n0].IDom\n\t\t\ti0 = nodes[n0].Post\n\t\t}\n\t\tfor i0 > i1 {\n\t\t\tn1 = nodes[n1].IDom\n\t\t\ti1 = nodes[n1].Post\n\t\t}\n\t}\n\treturn n0\n}\n\nfunc (lf *loopFinder) intersect(n0 NodeID, n1 NodeID) NodeID {\n\treturn Intersect(lf.node, n0, n1)\n}\n\nfunc (lf *loopFinder) cleanDeadEdges() {\n\tnumEdges := lf.graph.NumEdges()\n\tfor i := 0; i < numEdges; i++ {\n\t\tif lf.edge[i] == DEAD {\n\t\t\tlf.graph.KillEdge(EdgeID(i))\n\t\t}\n\t}\n}\n\nfunc (lf *loopFinder) findIdoms() {\n\tg := lf.graph\n\tchanged := true\n\tfor changed {\n\t\tchanged = false\n\t\tfor i := len(lf.postorder) - 1; i >= 0; i-- {\n\t\t\tn := lf.postorder[i]\n\t\t\toriginal := lf.node[n].IDom\n\t\t\tidom := original\n\t\t\teit := g.EntryIterator(n)\n\t\t\tfor eit.HasNext() {\n\t\t\t\tsrc, _ := eit.GetNext()\n\t\t\t\tidom = lf.intersect(idom, src)\n\t\t\t}\n\t\t\tif idom != original {\n\t\t\t\tlf.node[n].IDom = idom\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc AnalyzeStructure(g *Graph) ([]NodeInfo, []EdgeType, []NodeID) {\n\tnumNodes := g.NumNodes()\n\tlf := &loopFinder{\n\t\tgraph: g,\n\t\tnode:  make([]NodeInfo, numNodes),\n\t\tedge:  make([]EdgeType, g.NumEdges()),\n\t\tdepth: make([]int, numNodes),\n\t}\n\n\te := g.Entry()\n\tlf.process(e, e)\n\tlf.cleanDeadEdges()\n\tlf.findIdoms()\n\treturn lf.node, lf.edge, lf.postorder\n}\n<commit_msg>Better initial estimates of IDoms while analyzing graph structure.<commit_after>package graph\n\ntype NodeInfo struct {\n\tPre           int\n\tPost          int\n\tIDom          NodeID\n\tLoopHead      NodeID\n\tIsHead        bool\n\tIsIrreducible bool\n\tLive          bool\n}\n\ntype EdgeType int\n\nconst (\n\tDEAD EdgeType = iota\n\tFORWARD\n\tBACKWARD\n\tCROSS\n\tREENTRY\n)\n\ntype loopFinder struct {\n\tgraph     *Graph\n\tnode      []NodeInfo\n\tedge      []EdgeType\n\tpostorder []NodeID\n\tdepth     []int\n\tcurrent   int\n}\n\nfunc (lf *loopFinder) beginTraversingNode(n NodeID, prev NodeID) {\n\tlf.current += 1\n\n\tlf.node[n] = NodeInfo{\n\t\tPre:      lf.current,\n\t\tIDom:     prev, \/\/ A reasonable inital guess.\n\t\tLoopHead: NoNode,\n\t\tLive:     true,\n\t}\n\n\tlf.depth[n] = lf.current\n}\n\nfunc (lf *loopFinder) endTraversingNode(n NodeID) {\n\tlf.current += 1\n\tlf.node[n].Post = lf.current\n\n\tlf.depth[n] = 0\n\n\tlf.postorder = append(lf.postorder, n)\n}\n\nfunc (lf *loopFinder) isUnprocessed(n NodeID) bool {\n\treturn !lf.node[n].Live\n}\n\nfunc (lf *loopFinder) isBeingProcessed(dst NodeID) bool {\n\treturn lf.depth[dst] > 0\n}\n\nfunc (lf *loopFinder) markLoopHeader(child NodeID, head NodeID) {\n\tif child == head {\n\t\t\/\/ Trivial loop.\n\t\treturn\n\t}\n\tchildHead := lf.node[child].LoopHead\n\tfor childHead != NoNode {\n\t\tif childHead == head {\n\t\t\treturn\n\t\t}\n\t\tif lf.depth[childHead] < lf.depth[head] {\n\t\t\t\/\/ Found a closer head for this child, adopt it.\n\t\t\tlf.node[child].LoopHead = head\n\t\t\tchild, head = head, childHead\n\t\t} else {\n\t\t\tchild = childHead\n\t\t}\n\t\tchildHead = lf.node[child].LoopHead\n\t}\n\tlf.node[child].LoopHead = head\n}\n\nfunc (lf *loopFinder) updateCrossEdgeIDom(n NodeID) {\n\t\/\/ The IDom will always be in the path of nodes being processed.\n\t\/\/ Climb until we find the path.\n\tidom := lf.node[n].IDom\n\tfor !lf.isBeingProcessed(idom) {\n\t\tidom = lf.node[idom].IDom\n\t}\n\tlf.node[n].IDom = idom\n}\n\nfunc (lf *loopFinder) process(n NodeID, prev NodeID) {\n\tlf.beginTraversingNode(n, prev)\n\txit := lf.graph.ExitIterator(n)\n\tfor xit.HasNext() {\n\t\te, next := xit.GetNext()\n\t\tif lf.isUnprocessed(next) {\n\t\t\tlf.edge[e] = FORWARD\n\t\t\tlf.process(next, n)\n\n\t\t\t\/\/ Propagage loop headers upwards.\n\t\t\thead := lf.node[next].LoopHead\n\t\t\tif head != NoNode {\n\t\t\t\tlf.markLoopHeader(n, head)\n\t\t\t}\n\t\t} else if lf.isBeingProcessed(next) {\n\t\t\tlf.edge[e] = BACKWARD\n\t\t\tlf.node[next].IsHead = true\n\t\t\tlf.markLoopHeader(n, next)\n\t\t} else {\n\t\t\tlf.edge[e] = CROSS\n\t\t\tlf.updateCrossEdgeIDom(next)\n\t\t\tif lf.node[next].LoopHead != NoNode {\n\t\t\t\t\/\/ Propagate loop header from cross edge.\n\t\t\t\totherHead := lf.node[next].LoopHead\n\t\t\t\tif lf.isBeingProcessed(otherHead) {\n\t\t\t\t\tlf.markLoopHeader(n, otherHead)\n\t\t\t\t} else {\n\t\t\t\t\tlf.edge[e] = REENTRY\n\t\t\t\t\tlf.node[otherHead].IsIrreducible = true\n\t\t\t\t\t\/\/ Find and mark the common loop head.\n\t\t\t\t\totherHead = lf.node[otherHead].LoopHead\n\t\t\t\t\tfor otherHead != NoNode {\n\t\t\t\t\t\tif lf.isBeingProcessed(otherHead) {\n\t\t\t\t\t\t\tlf.markLoopHeader(n, otherHead)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\totherHead = lf.node[otherHead].LoopHead\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tlf.endTraversingNode(n)\n}\n\nfunc Intersect(nodes []NodeInfo, n0 NodeID, n1 NodeID) NodeID {\n\ti0 := nodes[n0].Post\n\ti1 := nodes[n1].Post\n\tfor i0 != i1 {\n\t\tfor i0 < i1 {\n\t\t\tn0 = nodes[n0].IDom\n\t\t\ti0 = nodes[n0].Post\n\t\t}\n\t\tfor i0 > i1 {\n\t\t\tn1 = nodes[n1].IDom\n\t\t\ti1 = nodes[n1].Post\n\t\t}\n\t}\n\treturn n0\n}\n\nfunc (lf *loopFinder) intersect(n0 NodeID, n1 NodeID) NodeID {\n\treturn Intersect(lf.node, n0, n1)\n}\n\nfunc (lf *loopFinder) cleanDeadEdges() {\n\tnumEdges := lf.graph.NumEdges()\n\tfor i := 0; i < numEdges; i++ {\n\t\tif lf.edge[i] == DEAD {\n\t\t\tlf.graph.KillEdge(EdgeID(i))\n\t\t}\n\t}\n}\n\nfunc (lf *loopFinder) findIdoms() {\n\tg := lf.graph\n\tchanged := true\n\tfor changed {\n\t\tchanged = false\n\t\tfor i := len(lf.postorder) - 1; i >= 0; i-- {\n\t\t\tn := lf.postorder[i]\n\t\t\toriginal := lf.node[n].IDom\n\t\t\tidom := original\n\t\t\teit := g.EntryIterator(n)\n\t\t\tfor eit.HasNext() {\n\t\t\t\tsrc, _ := eit.GetNext()\n\t\t\t\tidom = lf.intersect(idom, src)\n\t\t\t}\n\t\t\tif idom != original {\n\t\t\t\tlf.node[n].IDom = idom\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc AnalyzeStructure(g *Graph) ([]NodeInfo, []EdgeType, []NodeID) {\n\tnumNodes := g.NumNodes()\n\tlf := &loopFinder{\n\t\tgraph: g,\n\t\tnode:  make([]NodeInfo, numNodes),\n\t\tedge:  make([]EdgeType, g.NumEdges()),\n\t\tdepth: make([]int, numNodes),\n\t}\n\n\te := g.Entry()\n\tlf.process(e, e)\n\tlf.cleanDeadEdges()\n\tlf.findIdoms()\n\treturn lf.node, lf.edge, lf.postorder\n}\n<|endoftext|>"}
{"text":"<commit_before>package transactions\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/joshheinrichs\/geosource\/server\/config\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nvar db *gorm.DB\n\nvar ErrInsufficientPermission error = errors.New(\"Insufficient permission.\")\n\nfunc Init(config *config.Config) (err error) {\n\targuments := \"\"\n\tif len(config.Database.Host) > 0 {\n\t\targuments += fmt.Sprintf(\"host=%s \", config.Database.Host)\n\t}\n\tif len(config.Database.Database) > 0 {\n\t\targuments += fmt.Sprintf(\"dbname=%s \", config.Database.Database)\n\t}\n\tif len(config.Database.User) > 0 {\n\t\targuments += fmt.Sprintf(\"user=%s \", config.Database.User)\n\t}\n\tif len(config.Database.Password) > 0 {\n\t\targuments += fmt.Sprintf(\"password=%s \", config.Database.Password)\n\t}\n\n\tdb, err = gorm.Open(\"postgres\", arguments)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>Add some documentation to transactions package<commit_after>\/\/ Package transactions provides a set of functions which allow for interaction\n\/\/ with the database.\npackage transactions\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/joshheinrichs\/geosource\/server\/config\"\n\t_ \"github.com\/lib\/pq\"\n)\n\nvar db *gorm.DB\n\nvar ErrInsufficientPermission error = errors.New(\"Insufficient permission.\")\n\n\/\/ Init opens a connection to the database based on the information in the\n\/\/ given config. Returns an error if the connection  could not be established.\nfunc Init(config *config.Config) (err error) {\n\targuments := \"\"\n\tif len(config.Database.Host) > 0 {\n\t\targuments += fmt.Sprintf(\"host=%s \", config.Database.Host)\n\t}\n\tif len(config.Database.Database) > 0 {\n\t\targuments += fmt.Sprintf(\"dbname=%s \", config.Database.Database)\n\t}\n\tif len(config.Database.User) > 0 {\n\t\targuments += fmt.Sprintf(\"user=%s \", config.Database.User)\n\t}\n\tif len(config.Database.Password) > 0 {\n\t\targuments += fmt.Sprintf(\"password=%s \", config.Database.Password)\n\t}\n\n\tdb, err = gorm.Open(\"postgres\", arguments)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package bitcoind is a package\npackage bitcoind\n\n\/*\n * The MIT License (MIT)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\nimport (\n \t\"github.com\/rvelhote\/bitcoind-status\/bitcoind\/rpc\"\n\t\"github.com\/rvelhote\/bitcoind-status\/bitcoind\/rpc\/method\"\n\t\"github.com\/rvelhote\/bitcoind-status\/configuration\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n)\n\n\/\/ IndexTemplateParams holds various values to be passed to the main template\ntype IndexTemplateParams struct {\n\tTitle   string\n\tPeers   []method.PeerInfo\n\tNetwork method.NetworkInfo\n}\n\n\/\/ IndexRequestHandler handles the requests to present the main url of the application\ntype IndexRequestHandler struct {\n\t\/\/ Configuration contains the app configuration. In this context only the server list is used.\n\tConfiguration configuration.Configuration\n}\n\n\/\/ ServeHTTP handles the request made to the homepage of the app. It will only serve the required files to start\n\/\/ the RectJS app as well as some important configuration.\nfunc (i IndexRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Add(\"Content-Type\", \"text\/html\")\n\tt, err := template.New(\"index.html\").ParseFiles(\"templates\/index.html\")\n\n\tif err != nil {\n\t\tt, _ = template.New(\"index.html\").ParseFiles(\"..\/templates\/index.html\")\n\t}\n\n\tclient := rpc.NewRPCClient(i.Configuration.Url, i.Configuration.Username, i.Configuration.Password)\n\tpeerinfo, err := method.GetPeerInfo(client)\n\tnetworkinfo, err := method.GetNetworkInfo(client)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tparams := IndexTemplateParams{\n\t\tTitle:   \"Bitcoin Daemon Status\",\n\t\tPeers:   peerinfo,\n\t\tNetwork: networkinfo,\n\t}\n\n\tt.Execute(w, params)\n}\n\nfunc Init(mux *http.ServeMux, configuration configuration.Configuration) {\n\tindexHandler := IndexRequestHandler{Configuration: configuration}\n\n\tmux.Handle(\"\/assets\/\", http.StripPrefix(\"\/assets\/\", http.FileServer(http.Dir(\"assets\"))))\n\tmux.Handle(\"\/\", indexHandler)\n}\n<commit_msg>Check for errors on GetPeerInfo. Was mesmerized for a bit because it was failing occasionaly when SynchedHeaders was a negative value.<commit_after>\/\/ Package bitcoind is a package\npackage bitcoind\n\n\/*\n * The MIT License (MIT)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\/\nimport (\n \t\"github.com\/rvelhote\/bitcoind-status\/bitcoind\/rpc\"\n\t\"github.com\/rvelhote\/bitcoind-status\/bitcoind\/rpc\/method\"\n\t\"github.com\/rvelhote\/bitcoind-status\/configuration\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n)\n\n\/\/ IndexTemplateParams holds various values to be passed to the main template\ntype IndexTemplateParams struct {\n\tTitle   string\n\tPeers   []method.PeerInfo\n\tNetwork method.NetworkInfo\n}\n\n\/\/ IndexRequestHandler handles the requests to present the main url of the application\ntype IndexRequestHandler struct {\n\t\/\/ Configuration contains the app configuration. In this context only the server list is used.\n\tConfiguration configuration.Configuration\n}\n\n\/\/ ServeHTTP handles the request made to the homepage of the app. It will only serve the required files to start\n\/\/ the RectJS app as well as some important configuration.\nfunc (i IndexRequestHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tw.Header().Add(\"Content-Type\", \"text\/html\")\n\tt, err := template.New(\"index.html\").ParseFiles(\"templates\/index.html\")\n\n\tif err != nil {\n\t\tt, _ = template.New(\"index.html\").ParseFiles(\"..\/templates\/index.html\")\n\t}\n\n\tclient := rpc.NewRPCClient(i.Configuration.Url, i.Configuration.Username, i.Configuration.Password)\n\n\tpeerinfo, err := method.GetPeerInfo(client)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tnetworkinfo, err := method.GetNetworkInfo(client)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tparams := IndexTemplateParams{\n\t\tTitle:   \"Bitcoin Daemon Status\",\n\t\tPeers:   peerinfo,\n\t\tNetwork: networkinfo,\n\t}\n\n\tt.Execute(w, params)\n}\n\nfunc Init(mux *http.ServeMux, configuration configuration.Configuration) {\n\tindexHandler := IndexRequestHandler{Configuration: configuration}\n\n\tmux.Handle(\"\/assets\/\", http.StripPrefix(\"\/assets\/\", http.FileServer(http.Dir(\"assets\"))))\n\tmux.Handle(\"\/\", indexHandler)\n}\n<|endoftext|>"}
{"text":"<commit_before>package editor\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/elpinal\/coco3\/screen\"\n)\n\ntype exCommand struct {\n\tname string\n\tfn   func(*commandline, []string) continuity\n}\n\n\/\/ exComands represents a table of Ex commands and corresponding functions.\n\/\/ The order is important. Precede commands have higher precedence.\nvar exCommands = []exCommand{\n\t{\"help\", (*commandline).help},\n\t{\"delete\", (*commandline).delete},\n\t{\"quit\", (*commandline).quit},\n\t{\"substitute\", (*commandline).substitute},\n}\n\ntype commandline struct {\n\tstreamSet\n\t*editor\n\n\tbasic *basic\n\n\thistory [][]rune\n\tage     int\n}\n\nfunc newCommandline(s streamSet, e *editor) *commandline {\n\treturn &commandline{\n\t\tstreamSet: s,\n\t\teditor:    e,\n\t\tbasic:     &basic{},\n\t}\n}\n\nfunc (e *commandline) Mode() mode {\n\treturn modeCommandline\n}\n\nfunc (e *commandline) Position() int {\n\treturn e.basic.pos + 1\n}\n\nfunc (e *commandline) Runes() []rune {\n\treturn e.buf\n}\n\nfunc (e *commandline) Message() []rune {\n\treturn append([]rune{':'}, e.basic.buf...)\n}\n\nfunc (e *commandline) Highlight() *screen.Hi {\n\treturn nil\n}\n\nfunc (e *commandline) Run() (end continuity, next modeChanger, err error) {\n\tr, _, err := e.in.ReadRune()\n\tif err != nil {\n\t\treturn end, next, err\n\t}\n\tswitch r {\n\tcase CharCtrlM, CharCtrlJ:\n\t\tend, err = e.execute()\n\t\tnext = norm()\n\n\tcase CharEscape, CharCtrlC:\n\t\tnext = norm()\n\n\tcase CharBackspace, CharCtrlH:\n\t\tif len(e.basic.buf) == 0 {\n\t\t\tnext = norm()\n\t\t\treturn\n\t\t}\n\t\te.basic.delete(e.basic.pos-1, e.basic.pos)\n\n\tcase CharCtrlB:\n\t\te.basic.move(0)\n\tcase CharCtrlE:\n\t\te.basic.move(len(e.basic.buf))\n\tcase CharCtrlN:\n\t\te.historyForward()\n\tcase CharCtrlP:\n\t\te.historyBack()\n\tcase CharCtrlU:\n\t\te.basic.delete(0, e.basic.pos)\n\tcase CharCtrlW:\n\t\t\/\/ FIXME: It's redundant.\n\t\ted := newEditor()\n\t\ted.pos = e.basic.pos\n\t\ted.buf = e.basic.buf\n\t\tpos := ed.pos\n\t\ted.wordBackward()\n\t\te.basic.delete(pos, ed.pos)\n\tdefault:\n\t\te.basic.insert([]rune{r}, e.basic.pos)\n\t}\n\treturn\n}\n\nfunc (e *commandline) execute() (end continuity, err error) {\n\tvar candidate exCommand\n\ts := string(e.basic.buf)\n\tif s == \"\" {\n\t\treturn\n\t}\n\targs := strings.Split(s, \" \")\n\ts = args[0]\n\targs = args[1:]\n\tdefer func() {\n\t\te.history = append(e.history, e.basic.buf)\n\t}()\n\tfor _, cmd := range exCommands {\n\t\tif !strings.HasPrefix(cmd.name, s) {\n\t\t\tcontinue\n\t\t}\n\t\tif cmd.name == s {\n\t\t\tend = cmd.fn(e, args)\n\t\t\treturn\n\t\t}\n\t\tif candidate.name == \"\" {\n\t\t\tcandidate = cmd\n\t\t}\n\t}\n\tif candidate.name != \"\" {\n\t\tend = candidate.fn(e, args)\n\t\treturn\n\t}\n\terr = fmt.Errorf(\"not a command: %q\", s)\n\treturn\n}\n\nfunc (e *commandline) historyBack() {\n\tl := len(e.history)\n\tif l-e.age == 0 {\n\t\treturn\n\t}\n\te.age++\n\te.basic.buf = e.history[l-e.age]\n}\n\nfunc (e *commandline) historyForward() {\n\tl := len(e.history)\n\tif e.age == 0 {\n\t\treturn\n\t}\n\te.age--\n\te.basic.buf = e.history[l-e.age]\n}\n\nfunc (e *commandline) quit(args []string) continuity {\n\treturn exit\n}\n\nfunc (e *commandline) delete(args []string) (_ continuity) {\n\te.editor.delete(0, len(e.editor.buf))\n\treturn\n}\n\nfunc (e *commandline) help(args []string) continuity {\n\te.buf = []rune(\"help\")\n\te.pos = 4\n\treturn execute\n}\n\nfunc (e *commandline) substitute(args []string) (_ continuity) {\n\tif len(args) != 2 {\n\t\treturn\n\t}\n\tpat := args[0]\n\ts0 := args[1]\n\ts := strings.Replace(string(e.buf), pat, s0, -1)\n\te.buf = []rune(s)\n\treturn\n}\n<commit_msg>Fix a grammatical error<commit_after>package editor\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/elpinal\/coco3\/screen\"\n)\n\ntype exCommand struct {\n\tname string\n\tfn   func(*commandline, []string) continuity\n}\n\n\/\/ exComands represents a table of Ex commands and corresponding functions.\n\/\/ The order is important. Preceding commands have higher precedence.\nvar exCommands = []exCommand{\n\t{\"help\", (*commandline).help},\n\t{\"delete\", (*commandline).delete},\n\t{\"quit\", (*commandline).quit},\n\t{\"substitute\", (*commandline).substitute},\n}\n\ntype commandline struct {\n\tstreamSet\n\t*editor\n\n\tbasic *basic\n\n\thistory [][]rune\n\tage     int\n}\n\nfunc newCommandline(s streamSet, e *editor) *commandline {\n\treturn &commandline{\n\t\tstreamSet: s,\n\t\teditor:    e,\n\t\tbasic:     &basic{},\n\t}\n}\n\nfunc (e *commandline) Mode() mode {\n\treturn modeCommandline\n}\n\nfunc (e *commandline) Position() int {\n\treturn e.basic.pos + 1\n}\n\nfunc (e *commandline) Runes() []rune {\n\treturn e.buf\n}\n\nfunc (e *commandline) Message() []rune {\n\treturn append([]rune{':'}, e.basic.buf...)\n}\n\nfunc (e *commandline) Highlight() *screen.Hi {\n\treturn nil\n}\n\nfunc (e *commandline) Run() (end continuity, next modeChanger, err error) {\n\tr, _, err := e.in.ReadRune()\n\tif err != nil {\n\t\treturn end, next, err\n\t}\n\tswitch r {\n\tcase CharCtrlM, CharCtrlJ:\n\t\tend, err = e.execute()\n\t\tnext = norm()\n\n\tcase CharEscape, CharCtrlC:\n\t\tnext = norm()\n\n\tcase CharBackspace, CharCtrlH:\n\t\tif len(e.basic.buf) == 0 {\n\t\t\tnext = norm()\n\t\t\treturn\n\t\t}\n\t\te.basic.delete(e.basic.pos-1, e.basic.pos)\n\n\tcase CharCtrlB:\n\t\te.basic.move(0)\n\tcase CharCtrlE:\n\t\te.basic.move(len(e.basic.buf))\n\tcase CharCtrlN:\n\t\te.historyForward()\n\tcase CharCtrlP:\n\t\te.historyBack()\n\tcase CharCtrlU:\n\t\te.basic.delete(0, e.basic.pos)\n\tcase CharCtrlW:\n\t\t\/\/ FIXME: It's redundant.\n\t\ted := newEditor()\n\t\ted.pos = e.basic.pos\n\t\ted.buf = e.basic.buf\n\t\tpos := ed.pos\n\t\ted.wordBackward()\n\t\te.basic.delete(pos, ed.pos)\n\tdefault:\n\t\te.basic.insert([]rune{r}, e.basic.pos)\n\t}\n\treturn\n}\n\nfunc (e *commandline) execute() (end continuity, err error) {\n\tvar candidate exCommand\n\ts := string(e.basic.buf)\n\tif s == \"\" {\n\t\treturn\n\t}\n\targs := strings.Split(s, \" \")\n\ts = args[0]\n\targs = args[1:]\n\tdefer func() {\n\t\te.history = append(e.history, e.basic.buf)\n\t}()\n\tfor _, cmd := range exCommands {\n\t\tif !strings.HasPrefix(cmd.name, s) {\n\t\t\tcontinue\n\t\t}\n\t\tif cmd.name == s {\n\t\t\tend = cmd.fn(e, args)\n\t\t\treturn\n\t\t}\n\t\tif candidate.name == \"\" {\n\t\t\tcandidate = cmd\n\t\t}\n\t}\n\tif candidate.name != \"\" {\n\t\tend = candidate.fn(e, args)\n\t\treturn\n\t}\n\terr = fmt.Errorf(\"not a command: %q\", s)\n\treturn\n}\n\nfunc (e *commandline) historyBack() {\n\tl := len(e.history)\n\tif l-e.age == 0 {\n\t\treturn\n\t}\n\te.age++\n\te.basic.buf = e.history[l-e.age]\n}\n\nfunc (e *commandline) historyForward() {\n\tl := len(e.history)\n\tif e.age == 0 {\n\t\treturn\n\t}\n\te.age--\n\te.basic.buf = e.history[l-e.age]\n}\n\nfunc (e *commandline) quit(args []string) continuity {\n\treturn exit\n}\n\nfunc (e *commandline) delete(args []string) (_ continuity) {\n\te.editor.delete(0, len(e.editor.buf))\n\treturn\n}\n\nfunc (e *commandline) help(args []string) continuity {\n\te.buf = []rune(\"help\")\n\te.pos = 4\n\treturn execute\n}\n\nfunc (e *commandline) substitute(args []string) (_ continuity) {\n\tif len(args) != 2 {\n\t\treturn\n\t}\n\tpat := args[0]\n\ts0 := args[1]\n\ts := strings.Replace(string(e.buf), pat, s0, -1)\n\te.buf = []rune(s)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 Tomas Machalek <tomas.machalek@gmail.com>\n\/\/ Copyright 2019 Institute of the Czech National Corpus,\n\/\/                Faculty of Arts, Charles University\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage calc\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/czcorpus\/klogproc\/conversion\"\n)\n\n\/\/ LineParser is a parser for reading KonText application logs\ntype LineParser struct {\n}\n\nfunc (lp *LineParser) ParseLine(s string, lineNum int, localTimezone string) (*InputRecord, error) {\n\trec := &InputRecord{}\n\terr := json.Unmarshal([]byte(s), rec)\n\tif err != nil {\n\t\treturn rec, err\n\t}\n\tif rec.TS[len(rec.TS)-1] == 'Z' {\n\t\tminsChng, err := conversion.TimezoneToInt(localTimezone)\n\t\tif err != nil {\n\t\t\treturn rec, err\n\t\t}\n\t\ttm, err := time.Parse(\"2006-01-02T15:04:05-07:00\", rec.TS[:len(rec.TS)-1]+localTimezone)\n\t\tfmt.Println(\"tm1: \", rec.TS)\n\t\tif err != nil {\n\t\t\treturn rec, err\n\t\t}\n\t\ttm = tm.Add(time.Minute * time.Duration(minsChng))\n\t\trec.TS = tm.Format(\"2006-01-02T15:04:05-07:00\")\n\t\tfmt.Println(\"tm2: \", rec.TS)\n\t}\n\treturn rec, nil\n}\n<commit_msg>Update parser.go<commit_after>\/\/ Copyright 2019 Tomas Machalek <tomas.machalek@gmail.com>\n\/\/ Copyright 2019 Institute of the Czech National Corpus,\n\/\/                Faculty of Arts, Charles University\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage calc\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/czcorpus\/klogproc\/conversion\"\n)\n\n\/\/ LineParser is a parser for reading KonText application logs\ntype LineParser struct {\n}\n\nfunc (lp *LineParser) ParseLine(s string, lineNum int, localTimezone string) (*InputRecord, error) {\n\trec := &InputRecord{}\n\terr := json.Unmarshal([]byte(s), rec)\n\tif err != nil {\n\t\treturn rec, err\n\t}\n\tif rec.TS[len(rec.TS)-1] == 'Z' {\n\t\tminsChng, err := conversion.TimezoneToInt(localTimezone)\n\t\tif err != nil {\n\t\t\treturn rec, err\n\t\t}\n\t\ttm, err := time.Parse(\"2006-01-02T15:04:05-07:00\", rec.TS[:len(rec.TS)-1]+localTimezone)\n\t\tfmt.Println(\"tm1: \", rec.TS)\n\t\tif err != nil {\n\t\t\treturn rec, err\n\t\t}\n\t\ttm = tm.Add(time.Minute * time.Duration(minsChng))\n\t\trec.TS = tm.Format(\"2006-01-02T15:04:05-07:00\")\n\t}\n\treturn rec, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package kingpin\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype flagGroup struct {\n\tshort     map[string]*FlagClause\n\tlong      map[string]*FlagClause\n\tflagOrder []*FlagClause\n}\n\nfunc newFlagGroup() *flagGroup {\n\treturn &flagGroup{\n\t\tshort: make(map[string]*FlagClause),\n\t\tlong:  make(map[string]*FlagClause),\n\t}\n}\n\n\/\/ Flag defines a new flag with the given long name and help.\nfunc (f *flagGroup) Flag(name, help string) *FlagClause {\n\tflag := newFlag(name, help)\n\tf.long[name] = flag\n\tf.flagOrder = append(f.flagOrder, flag)\n\treturn flag\n}\n\nfunc (f *flagGroup) init() error {\n\tfor _, flag := range f.long {\n\t\tif err := flag.init(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif flag.shorthand != 0 {\n\t\t\tf.short[string(flag.shorthand)] = flag\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (f *flagGroup) parse(tokens tokens, ignoreRequired bool) (tokens, error) {\n\t\/\/ Track how many required flags we've seen.\n\trequired := make(map[string]struct{})\n\t\/\/ Keep track of any flags that we need to initialise with defaults.\n\tdefaults := make(map[string]struct{})\n\tfor k, flag := range f.long {\n\t\tdefaults[k] = struct{}{}\n\t\tif !ignoreRequired && flag.needsValue() {\n\t\t\trequired[k] = struct{}{}\n\t\t}\n\t}\n\n\tvar token *token\n\nloop:\n\tfor {\n\t\ttoken, tokens = tokens.Next()\n\t\tswitch token.Type {\n\t\tcase TokenEOF:\n\t\t\tbreak loop\n\n\t\tcase TokenLong, TokenShort:\n\t\t\tflagToken := token\n\t\t\tdefaultValue := \"\"\n\t\t\tvar flag *FlagClause\n\t\t\tvar ok bool\n\t\t\tinvert := false\n\n\t\t\tname := token.Value\n\t\t\tif token.Type == TokenLong {\n\t\t\t\tif strings.HasPrefix(name, \"no-\") {\n\t\t\t\t\tname = name[3:]\n\t\t\t\t\tinvert = true\n\t\t\t\t}\n\t\t\t\tflag, ok = f.long[name]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unknown long flag '%s'\", flagToken)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tflag, ok = f.short[name]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unknown short flag '%s\", flagToken)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdelete(required, flag.name)\n\t\t\tdelete(defaults, flag.name)\n\n\t\t\tfb, ok := flag.value.(boolFlag)\n\t\t\tif ok && fb.IsBoolFlag() {\n\t\t\t\tif invert {\n\t\t\t\t\tdefaultValue = \"false\"\n\t\t\t\t} else {\n\t\t\t\t\tdefaultValue = \"true\"\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif invert {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unknown long flag '%s'\", flagToken)\n\t\t\t\t}\n\t\t\t\ttoken, tokens = tokens.Next()\n\t\t\t\tif token.Type != TokenArg {\n\t\t\t\t\treturn nil, fmt.Errorf(\"expected argument for flag '%s'\", flagToken)\n\t\t\t\t}\n\t\t\t\tdefaultValue = token.Value\n\t\t\t}\n\n\t\t\tif err := flag.value.Set(defaultValue); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif flag.dispatch != nil {\n\t\t\t\tif err := flag.dispatch(); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\tdefault:\n\t\t\ttokens = tokens.Return(token)\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\t\/\/ Check that required flags were provided.\n\tif len(required) == 1 {\n\t\tfor k := range required {\n\t\t\treturn nil, fmt.Errorf(\"required flag --%s not provided\", k)\n\t\t}\n\t} else if len(required) > 1 {\n\t\tflags := make([]string, 0, len(required))\n\t\tfor k := range required {\n\t\t\tflags = append(flags, \"--\"+k)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"required flags %s not provided\", strings.Join(flags, \", \"))\n\t}\n\n\t\/\/ Apply defaults to all unprocessed flags.\n\tfor k := range defaults {\n\t\tflag := f.long[k]\n\t\tif flag.defaultValue != \"\" {\n\t\t\tif err := flag.value.Set(flag.defaultValue); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"default value for --%s is invalid: %s\", flag.name, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn tokens, nil\n}\n\n\/\/ FlagClause is a fluid interface used to build flags.\ntype FlagClause struct {\n\tparserMixin\n\tname         string\n\tshorthand    byte\n\thelp         string\n\tenvar        string\n\tdefaultValue string\n\tplaceholder  string\n\tdispatch     Dispatch\n}\n\nfunc newFlag(name, help string) *FlagClause {\n\tf := &FlagClause{\n\t\tname: name,\n\t\thelp: help,\n\t}\n\treturn f\n}\n\nfunc (f *FlagClause) needsValue() bool {\n\treturn f.required && f.defaultValue == \"\"\n}\n\nfunc (f *FlagClause) formatPlaceHolder() string {\n\tif f.placeholder != \"\" {\n\t\treturn f.placeholder\n\t}\n\tif f.defaultValue != \"\" {\n\t\tif _, ok := f.value.(*stringValue); ok {\n\t\t\treturn fmt.Sprintf(\"%q\", f.value)\n\t\t}\n\t\treturn f.value.String()\n\t}\n\treturn strings.ToUpper(f.name)\n}\n\nfunc (f *FlagClause) init() error {\n\tif f.required && f.defaultValue != \"\" {\n\t\treturn fmt.Errorf(\"required flag '--%s' with default value that will never be used\", f.name)\n\t}\n\tif f.value == nil {\n\t\treturn fmt.Errorf(\"no value defined for --%s\", f.name)\n\t}\n\tif f.envar != \"\" {\n\t\tif v := os.Getenv(f.envar); v != \"\" {\n\t\t\tf.defaultValue = v\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Dispatch to the given function when the flag is parsed.\nfunc (f *FlagClause) Dispatch(dispatch Dispatch) *FlagClause {\n\tf.dispatch = dispatch\n\treturn f\n}\n\n\/\/ Default value for this flag. It *must* be parseable by the value of the flag.\nfunc (f *FlagClause) Default(value string) *FlagClause {\n\tf.defaultValue = value\n\treturn f\n}\n\n\/\/ OverrideDefaultFromEnvar overrides the default value for a flag from an\n\/\/ environment variable, if available.\nfunc (f *FlagClause) OverrideDefaultFromEnvar(envar string) *FlagClause {\n\tf.envar = envar\n\treturn f\n}\n\n\/\/ PlaceHolder sets the place-holder string used for flag values in the help. The\n\/\/ default behaviour is to use the value provided by Default() if provided,\n\/\/ then fall back on the capitalized flag name.\nfunc (f *FlagClause) PlaceHolder(placeholder string) *FlagClause {\n\tf.placeholder = placeholder\n\treturn f\n}\n\n\/\/ Required makes the flag required. You can not provide a Default() value to a Required() flag.\nfunc (f *FlagClause) Required() *FlagClause {\n\tf.required = true\n\treturn f\n}\n\n\/\/ Short sets the short flag name.\nfunc (f *FlagClause) Short(name byte) *FlagClause {\n\tf.shorthand = name\n\treturn f\n}\n\n\/\/ Bool makes this flag a boolean flag.\nfunc (f *FlagClause) Bool() (target *bool) {\n\ttarget = new(bool)\n\tf.SetValue(newBoolValue(false, target))\n\treturn\n}\n<commit_msg>Print actual default value.<commit_after>package kingpin\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype flagGroup struct {\n\tshort     map[string]*FlagClause\n\tlong      map[string]*FlagClause\n\tflagOrder []*FlagClause\n}\n\nfunc newFlagGroup() *flagGroup {\n\treturn &flagGroup{\n\t\tshort: make(map[string]*FlagClause),\n\t\tlong:  make(map[string]*FlagClause),\n\t}\n}\n\n\/\/ Flag defines a new flag with the given long name and help.\nfunc (f *flagGroup) Flag(name, help string) *FlagClause {\n\tflag := newFlag(name, help)\n\tf.long[name] = flag\n\tf.flagOrder = append(f.flagOrder, flag)\n\treturn flag\n}\n\nfunc (f *flagGroup) init() error {\n\tfor _, flag := range f.long {\n\t\tif err := flag.init(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif flag.shorthand != 0 {\n\t\t\tf.short[string(flag.shorthand)] = flag\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (f *flagGroup) parse(tokens tokens, ignoreRequired bool) (tokens, error) {\n\t\/\/ Track how many required flags we've seen.\n\trequired := make(map[string]struct{})\n\t\/\/ Keep track of any flags that we need to initialise with defaults.\n\tdefaults := make(map[string]struct{})\n\tfor k, flag := range f.long {\n\t\tdefaults[k] = struct{}{}\n\t\tif !ignoreRequired && flag.needsValue() {\n\t\t\trequired[k] = struct{}{}\n\t\t}\n\t}\n\n\tvar token *token\n\nloop:\n\tfor {\n\t\ttoken, tokens = tokens.Next()\n\t\tswitch token.Type {\n\t\tcase TokenEOF:\n\t\t\tbreak loop\n\n\t\tcase TokenLong, TokenShort:\n\t\t\tflagToken := token\n\t\t\tdefaultValue := \"\"\n\t\t\tvar flag *FlagClause\n\t\t\tvar ok bool\n\t\t\tinvert := false\n\n\t\t\tname := token.Value\n\t\t\tif token.Type == TokenLong {\n\t\t\t\tif strings.HasPrefix(name, \"no-\") {\n\t\t\t\t\tname = name[3:]\n\t\t\t\t\tinvert = true\n\t\t\t\t}\n\t\t\t\tflag, ok = f.long[name]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unknown long flag '%s'\", flagToken)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tflag, ok = f.short[name]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unknown short flag '%s\", flagToken)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdelete(required, flag.name)\n\t\t\tdelete(defaults, flag.name)\n\n\t\t\tfb, ok := flag.value.(boolFlag)\n\t\t\tif ok && fb.IsBoolFlag() {\n\t\t\t\tif invert {\n\t\t\t\t\tdefaultValue = \"false\"\n\t\t\t\t} else {\n\t\t\t\t\tdefaultValue = \"true\"\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif invert {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unknown long flag '%s'\", flagToken)\n\t\t\t\t}\n\t\t\t\ttoken, tokens = tokens.Next()\n\t\t\t\tif token.Type != TokenArg {\n\t\t\t\t\treturn nil, fmt.Errorf(\"expected argument for flag '%s'\", flagToken)\n\t\t\t\t}\n\t\t\t\tdefaultValue = token.Value\n\t\t\t}\n\n\t\t\tif err := flag.value.Set(defaultValue); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif flag.dispatch != nil {\n\t\t\t\tif err := flag.dispatch(); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\t\tdefault:\n\t\t\ttokens = tokens.Return(token)\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\t\/\/ Check that required flags were provided.\n\tif len(required) == 1 {\n\t\tfor k := range required {\n\t\t\treturn nil, fmt.Errorf(\"required flag --%s not provided\", k)\n\t\t}\n\t} else if len(required) > 1 {\n\t\tflags := make([]string, 0, len(required))\n\t\tfor k := range required {\n\t\t\tflags = append(flags, \"--\"+k)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"required flags %s not provided\", strings.Join(flags, \", \"))\n\t}\n\n\t\/\/ Apply defaults to all unprocessed flags.\n\tfor k := range defaults {\n\t\tflag := f.long[k]\n\t\tif flag.defaultValue != \"\" {\n\t\t\tif err := flag.value.Set(flag.defaultValue); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"default value for --%s is invalid: %s\", flag.name, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn tokens, nil\n}\n\n\/\/ FlagClause is a fluid interface used to build flags.\ntype FlagClause struct {\n\tparserMixin\n\tname         string\n\tshorthand    byte\n\thelp         string\n\tenvar        string\n\tdefaultValue string\n\tplaceholder  string\n\tdispatch     Dispatch\n}\n\nfunc newFlag(name, help string) *FlagClause {\n\tf := &FlagClause{\n\t\tname: name,\n\t\thelp: help,\n\t}\n\treturn f\n}\n\nfunc (f *FlagClause) needsValue() bool {\n\treturn f.required && f.defaultValue == \"\"\n}\n\nfunc (f *FlagClause) formatPlaceHolder() string {\n\tif f.placeholder != \"\" {\n\t\treturn f.placeholder\n\t}\n\tif f.defaultValue != \"\" {\n\t\tif _, ok := f.value.(*stringValue); ok {\n\t\t\treturn fmt.Sprintf(\"%q\", f.defaultValue)\n\t\t}\n\t\treturn f.defaultValue\n\t}\n\treturn strings.ToUpper(f.name)\n}\n\nfunc (f *FlagClause) init() error {\n\tif f.required && f.defaultValue != \"\" {\n\t\treturn fmt.Errorf(\"required flag '--%s' with default value that will never be used\", f.name)\n\t}\n\tif f.value == nil {\n\t\treturn fmt.Errorf(\"no value defined for --%s\", f.name)\n\t}\n\tif f.envar != \"\" {\n\t\tif v := os.Getenv(f.envar); v != \"\" {\n\t\t\tf.defaultValue = v\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Dispatch to the given function when the flag is parsed.\nfunc (f *FlagClause) Dispatch(dispatch Dispatch) *FlagClause {\n\tf.dispatch = dispatch\n\treturn f\n}\n\n\/\/ Default value for this flag. It *must* be parseable by the value of the flag.\nfunc (f *FlagClause) Default(value string) *FlagClause {\n\tf.defaultValue = value\n\treturn f\n}\n\n\/\/ OverrideDefaultFromEnvar overrides the default value for a flag from an\n\/\/ environment variable, if available.\nfunc (f *FlagClause) OverrideDefaultFromEnvar(envar string) *FlagClause {\n\tf.envar = envar\n\treturn f\n}\n\n\/\/ PlaceHolder sets the place-holder string used for flag values in the help. The\n\/\/ default behaviour is to use the value provided by Default() if provided,\n\/\/ then fall back on the capitalized flag name.\nfunc (f *FlagClause) PlaceHolder(placeholder string) *FlagClause {\n\tf.placeholder = placeholder\n\treturn f\n}\n\n\/\/ Required makes the flag required. You can not provide a Default() value to a Required() flag.\nfunc (f *FlagClause) Required() *FlagClause {\n\tf.required = true\n\treturn f\n}\n\n\/\/ Short sets the short flag name.\nfunc (f *FlagClause) Short(name byte) *FlagClause {\n\tf.shorthand = name\n\treturn f\n}\n\n\/\/ Bool makes this flag a boolean flag.\nfunc (f *FlagClause) Bool() (target *bool) {\n\ttarget = new(bool)\n\tf.SetValue(newBoolValue(false, target))\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package notifier\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/eternnoir\/gmrn\/apis\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc InitGitLabNotifier(url, token string, projects []string, pollingInterval, notifyInterval time.Duration) *GitLabNotifier {\n\tgitlab := GitLabNotifier{}\n\tgitlab.Url = url\n\tgitlab.Token = token\n\tgitlab.Projects = projects\n\tgitlab.PollingInterval = pollingInterval\n\tgitlab.NotifyInterval = notifyInterval\n\tgitlab.NotifyRunners = []NotifyRunner{}\n\tgitlab.Api = apis.InitGitlabApi(url, token)\n\tgitlab.MRLastNotifyTime = make(map[string]time.Time)\n\tlog.Infof(\"Init GitLabNotifier. Url:%s , Toke:%s, %d projects.\", url, token, len(projects))\n\treturn &gitlab\n}\n\ntype GitLabNotifier struct {\n\tUrl              string\n\tToken            string\n\tProjects         []string\n\tPollingInterval  time.Duration\n\tNotifyInterval   time.Duration\n\tApi              *apis.GitLabApi\n\tNotifyRunners    []NotifyRunner\n\tMRLastNotifyTime map[string]time.Time\n}\n\nfunc (notifier *GitLabNotifier) Run() {\n\n\tnotifier.checkProjects()\n\t\/\/  loops forever to polling merge request.\n\tfor {\n\t\terr := notifier.notifyForMergeRequest()\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\ttime.Sleep(notifier.PollingInterval)\n\t}\n}\nfunc (notifier *GitLabNotifier) AppendNotifyRunner(runner NotifyRunner) {\n\tlog.Infof(\"Append Runner %#v\", runner)\n\tnotifier.NotifyRunners = append(notifier.NotifyRunners, runner)\n}\n\nfunc (notifier *GitLabNotifier) notifyForMergeRequest() error {\n\tallMrs, err := notifier.getAllProjectsMr()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\tlog.Infof(\"Get %d Merge Requests\", len(allMrs))\n\tfor _, mr := range allMrs {\n\t\tgo notifier.triggerNitifyCommand(mr)\n\t}\n\treturn nil\n}\n\nfunc (notifier *GitLabNotifier) triggerNitifyCommand(mr *apis.MergeRequest) {\n\tif mr.WorkInProgress {\n\t\tlog.Debugf(\"%s Merge Reques is WorkInProgress. Do not need to notify.\", mr.Title)\n\t\treturn\n\t}\n\tuumrid := strconv.Itoa(int(mr.ProjectId)) + \":\" + strconv.Itoa(int(mr.Id))\n\tif val, ok := notifier.MRLastNotifyTime[uumrid]; ok {\n\t\tif time.Now().Before(val.Add(notifier.NotifyInterval)) {\n\t\t\t\/\/ Do not need to run notify command.\n\t\t\tlog.Debugf(\"Do not need to run notify command for %s\", mr.Title)\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Infof(\"Trigger command for %s\", mr.Title)\n\tnotifier.MRLastNotifyTime[uumrid] = time.Now()\n\tnotifier.runNotifyCommand(mr)\n\n}\n\nfunc (notifier *GitLabNotifier) runNotifyCommand(mr *apis.MergeRequest) {\n\tmrerr := mr.GetProjectInfo(notifier.Api)\n\tif mrerr != nil {\n\t\tlog.Errorf(\"Try to get merge request's project detial [FAIL]. %#v\", mr)\n\t\treturn\n\t}\n\n\tfor _, nr := range notifier.NotifyRunners {\n\t\tlog.Infof(\"Start Trigger NotifyRunner %#v\", nr)\n\t\terr := nr.Trigger(mr)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Trigger NotifyRunner %#v [FAIL]\", nr)\n\t\t}\n\t\tlog.Infof(\"Tirgger NotifyRunner %#v  [Success].\", nr)\n\t}\n}\n\nfunc (notifier *GitLabNotifier) getAllProjectsMr() ([]*apis.MergeRequest, error) {\n\tvar mrs []*apis.MergeRequest\n\tfor _, projectId := range notifier.Projects {\n\t\tresultmrs, err := notifier.Api.GetMergeRequests(projectId, \"opened\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\t\tmrs = append(mrs, resultmrs...)\n\t}\n\treturn mrs, nil\n}\n\n\/\/ checkProjects is check notifier's projects is exist or not.\n\/\/ If projects is empty, It will set all project to project list.\nfunc (notifier *GitLabNotifier) checkProjects() error {\n\tif len(notifier.Projects) < 1 {\n\t\tlog.Infof(\"Notifier' project is empty. Load all projects from gitlab.\")\n\t\terr := notifier.setAllProjectId()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Infof(\"%d projects loaded.\", len(notifier.Projects))\n\t}\n\treturn nil\n}\n\nfunc (notifier *GitLabNotifier) setAllProjectId() error {\n\tprojects, err := notifier.Api.GetProjects()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\tfor _, project := range projects {\n\t\tnotifier.Projects = append(notifier.Projects, project.PathWithNamespace)\n\t}\n\treturn nil\n}\n<commit_msg>Fix typo.<commit_after>package notifier\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/eternnoir\/gmrn\/apis\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc InitGitLabNotifier(url, token string, projects []string, pollingInterval, notifyInterval time.Duration) *GitLabNotifier {\n\tgitlab := GitLabNotifier{}\n\tgitlab.Url = url\n\tgitlab.Token = token\n\tgitlab.Projects = projects\n\tgitlab.PollingInterval = pollingInterval\n\tgitlab.NotifyInterval = notifyInterval\n\tgitlab.NotifyRunners = []NotifyRunner{}\n\tgitlab.Api = apis.InitGitlabApi(url, token)\n\tgitlab.MRLastNotifyTime = make(map[string]time.Time)\n\tlog.Infof(\"Init GitLabNotifier. Url:%s , Toke:%s, %d projects.\", url, token, len(projects))\n\treturn &gitlab\n}\n\ntype GitLabNotifier struct {\n\tUrl              string\n\tToken            string\n\tProjects         []string\n\tPollingInterval  time.Duration\n\tNotifyInterval   time.Duration\n\tApi              *apis.GitLabApi\n\tNotifyRunners    []NotifyRunner\n\tMRLastNotifyTime map[string]time.Time\n}\n\nfunc (notifier *GitLabNotifier) Run() {\n\n\tnotifier.checkProjects()\n\t\/\/  loops forever to polling merge request.\n\tfor {\n\t\terr := notifier.notifyForMergeRequest()\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t\ttime.Sleep(notifier.PollingInterval)\n\t}\n}\nfunc (notifier *GitLabNotifier) AppendNotifyRunner(runner NotifyRunner) {\n\tlog.Infof(\"Append Runner %#v\", runner)\n\tnotifier.NotifyRunners = append(notifier.NotifyRunners, runner)\n}\n\nfunc (notifier *GitLabNotifier) notifyForMergeRequest() error {\n\tallMrs, err := notifier.GetAllProjectsMr()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\tlog.Infof(\"Get %d Merge Requests\", len(allMrs))\n\tfor _, mr := range allMrs {\n\t\tgo notifier.triggerNotifyCommand(mr)\n\t}\n\treturn nil\n}\n\nfunc (notifier *GitLabNotifier) triggerNotifyCommand(mr *apis.MergeRequest) {\n\tif mr.WorkInProgress {\n\t\tlog.Debugf(\"%s Merge Reques is WorkInProgress. Do not need to notify.\", mr.Title)\n\t\treturn\n\t}\n\tuumrid := strconv.Itoa(int(mr.ProjectId)) + \":\" + strconv.Itoa(int(mr.Id))\n\tif val, ok := notifier.MRLastNotifyTime[uumrid]; ok {\n\t\tif time.Now().Before(val.Add(notifier.NotifyInterval)) {\n\t\t\t\/\/ Do not need to run notify command.\n\t\t\tlog.Debugf(\"Do not need to run notify command for %s\", mr.Title)\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Infof(\"Trigger command for %s\", mr.Title)\n\tnotifier.MRLastNotifyTime[uumrid] = time.Now()\n\tnotifier.runNotifyCommand(mr)\n\n}\n\nfunc (notifier *GitLabNotifier) runNotifyCommand(mr *apis.MergeRequest) {\n\tmrerr := mr.GetProjectInfo(notifier.Api)\n\tif mrerr != nil {\n\t\tlog.Errorf(\"Try to get merge request's project detial [FAIL]. %#v\", mr)\n\t\treturn\n\t}\n\n\tfor _, nr := range notifier.NotifyRunners {\n\t\tlog.Infof(\"Start Trigger NotifyRunner %#v\", nr)\n\t\terr := nr.Trigger(mr)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Trigger NotifyRunner %#v [FAIL]\", nr)\n\t\t}\n\t\tlog.Infof(\"Tirgger NotifyRunner %#v  [Success].\", nr)\n\t}\n}\n\nfunc (notifier *GitLabNotifier) GetAllProjectsMr() ([]*apis.MergeRequest, error) {\n\tvar mrs []*apis.MergeRequest\n\tfor _, projectId := range notifier.Projects {\n\t\tresultmrs, err := notifier.Api.GetMergeRequests(projectId, \"opened\")\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn nil, err\n\t\t}\n\t\tmrs = append(mrs, resultmrs...)\n\t}\n\treturn mrs, nil\n}\n\n\/\/ checkProjects is check notifier's projects is exist or not.\n\/\/ If projects is empty, It will set all project to project list.\nfunc (notifier *GitLabNotifier) checkProjects() error {\n\tif len(notifier.Projects) < 1 {\n\t\tlog.Infof(\"Notifier' project is empty. Load all projects from gitlab.\")\n\t\terr := notifier.setAllProjectId()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Infof(\"%d projects loaded.\", len(notifier.Projects))\n\t}\n\treturn nil\n}\n\nfunc (notifier *GitLabNotifier) setAllProjectId() error {\n\tprojects, err := notifier.Api.GetProjects()\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\tfor _, project := range projects {\n\t\tnotifier.Projects = append(notifier.Projects, project.PathWithNamespace)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nPackage flect is a new inflection engine to replace [https:\/\/github.com\/markbates\/inflect](https:\/\/github.com\/markbates\/inflect) designed to be more modular, more readable, and easier to fix issues on than the original.\n*\/\npackage flect\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nfunc init() {\n\tpwd, _ := os.Getwd()\n\tcfg := filepath.Join(pwd, \"inflections.json\")\n\tif p := os.Getenv(\"INFLECT_PATH\"); p != \"\" {\n\t\tcfg = p\n\t}\n\tif _, err := os.Stat(cfg); err == nil {\n\t\tb, err := ioutil.ReadFile(cfg)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"could not read inflection file %s (%s)\\n\", cfg, err)\n\t\t\treturn\n\t\t}\n\t\tif err = LoadReader(bytes.NewReader(b)); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n}\n\n\/\/LoadReader loads rules from io.Reader param\nfunc LoadReader(r io.Reader) error {\n\tm := map[string]interface{}{}\n\n\terr := json.NewDecoder(r).Decode(&m)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not decode inflection JSON from reader: %s\", err)\n\t}\n\tpluralMoot.Lock()\n\tdefer pluralMoot.Unlock()\n\tsingularMoot.Lock()\n\tdefer singularMoot.Unlock()\n\n\tfor s, p := range m {\n\t\tif ps, ok := p.(string); ok {\n\t\t\tsingleToPlural[s] = ps\n\t\t\tpluralToSingle[ps] = s\n\t\t}\n\n\t\tif pa, ok := p.([]interface{}); ok && s == \"_acronyms\" {\n\t\t\tfor _, acronym := range pa {\n\t\t\t\tkey := (acronym).(string)\n\t\t\t\tbaseAcronyms[key] = true\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nvar spaces = []rune{'_', ' ', ':', '-', '\/'}\n\nfunc isSpace(c rune) bool {\n\tfor _, r := range spaces {\n\t\tif r == c {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn unicode.IsSpace(c)\n}\n\nfunc xappend(a []string, ss ...string) []string {\n\tfor _, s := range ss {\n\t\ts = strings.TrimSpace(s)\n\t\tfor _, x := range spaces {\n\t\t\ts = strings.Trim(s, string(x))\n\t\t}\n\t\tif _, ok := baseAcronyms[strings.ToUpper(s)]; ok {\n\t\t\ts = strings.ToUpper(s)\n\t\t}\n\t\tif s != \"\" {\n\t\t\ta = append(a, s)\n\t\t}\n\t}\n\treturn a\n}\n\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n<commit_msg>moving acronyms key to a constant<commit_after>\/*\nPackage flect is a new inflection engine to replace [https:\/\/github.com\/markbates\/inflect](https:\/\/github.com\/markbates\/inflect) designed to be more modular, more readable, and easier to fix issues on than the original.\n*\/\npackage flect\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"unicode\"\n)\n\nconst (\n\t\/\/acronymsKey is the key we use to get acronyms from the inflections file\n\t\/\/p.e:\n\t\/\/ #inflections.json\n\t\/\/ {\n\t\/\/ \t\"house\":\"houses\",\n\t\/\/ \t\"_acronyms\": [\"TSA\", \"LSA\"]\n\t\/\/ }\n\tacronymsKey = \"_acronyms\"\n)\n\nfunc init() {\n\tpwd, _ := os.Getwd()\n\tcfg := filepath.Join(pwd, \"inflections.json\")\n\tif p := os.Getenv(\"INFLECT_PATH\"); p != \"\" {\n\t\tcfg = p\n\t}\n\tif _, err := os.Stat(cfg); err == nil {\n\t\tb, err := ioutil.ReadFile(cfg)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"could not read inflection file %s (%s)\\n\", cfg, err)\n\t\t\treturn\n\t\t}\n\t\tif err = LoadReader(bytes.NewReader(b)); err != nil {\n\t\t\tfmt.Println(err)\n\t\t}\n\t}\n}\n\n\/\/LoadReader loads rules from io.Reader param\nfunc LoadReader(r io.Reader) error {\n\tm := map[string]interface{}{}\n\n\terr := json.NewDecoder(r).Decode(&m)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not decode inflection JSON from reader: %s\", err)\n\t}\n\tpluralMoot.Lock()\n\tdefer pluralMoot.Unlock()\n\tsingularMoot.Lock()\n\tdefer singularMoot.Unlock()\n\n\tfor s, p := range m {\n\t\tif ps, ok := p.(string); ok {\n\t\t\tsingleToPlural[s] = ps\n\t\t\tpluralToSingle[ps] = s\n\t\t}\n\n\t\tif pa, ok := p.([]interface{}); ok && s == acronymsKey {\n\t\t\tfor _, acronym := range pa {\n\t\t\t\tkey := (acronym).(string)\n\t\t\t\tbaseAcronyms[key] = true\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn nil\n}\n\nvar spaces = []rune{'_', ' ', ':', '-', '\/'}\n\nfunc isSpace(c rune) bool {\n\tfor _, r := range spaces {\n\t\tif r == c {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn unicode.IsSpace(c)\n}\n\nfunc xappend(a []string, ss ...string) []string {\n\tfor _, s := range ss {\n\t\ts = strings.TrimSpace(s)\n\t\tfor _, x := range spaces {\n\t\t\ts = strings.Trim(s, string(x))\n\t\t}\n\t\tif _, ok := baseAcronyms[strings.ToUpper(s)]; ok {\n\t\t\ts = strings.ToUpper(s)\n\t\t}\n\t\tif s != \"\" {\n\t\t\ta = append(a, s)\n\t\t}\n\t}\n\treturn a\n}\n\nfunc abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 IBM\n\nLicensed under the Apache License, Version 2.0 (the \"License\")\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\nLicensed Materials - Property of IBM\n© Copyright IBM Corp. 2016\n*\/\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n    \"strings\"\n\n\t\"github.com\/openblockchain\/obc-peer\/openchain\/chaincode\/shim\"\n)\n\nvar cpPrefix = \"cp:\"\nvar accountPrefix = \"acct:\"\nvar accountsKey = \"accounts\"\n\nvar recentLeapYear = 2016\n\n\/\/ SimpleChaincode example simple Chaincode implementation\ntype SimpleChaincode struct {\n}\n\nfunc generateCUSIPSuffix(issueDate string, days int) (string, error) {\n\n\tt, err := msToTime(issueDate)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tmaturityDate := t.AddDate(0, 0, days)\n\tmonth := int(maturityDate.Month())\n\tday := maturityDate.Day()\n\n\tsuffix := seventhDigit[month] + eigthDigit[day]\n\treturn suffix, nil\n\n}\n\nconst (\n\tmillisPerSecond     = int64(time.Second \/ time.Millisecond)\n\tnanosPerMillisecond = int64(time.Millisecond \/ time.Nanosecond)\n)\n\nfunc msToTime(ms string) (time.Time, error) {\n\tmsInt, err := strconv.ParseInt(ms, 10, 64)\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\n\treturn time.Unix(msInt\/millisPerSecond,\n\t\t(msInt%millisPerSecond)*nanosPerMillisecond), nil\n}\n\n\n\ntype Owner struct {\n\tCompany string    `json:\"company\"`\n\tQuantity int      `json:\"quantity\"`\n}\n\ntype CP struct {\n\tCUSIP     string  `json:\"cusip\"`\n\tTicker    string  `json:\"ticker\"`\n\tPar       float64 `json:\"par\"`\n\tQty       int     `json:\"qty\"`\n\tDiscount  float64 `json:\"discount\"`\n\tMaturity  int     `json:\"maturity\"`\n\tOwners    []Owner `json:\"owner\"`\n\tIssuer    string  `json:\"issuer\"`\n\tIssueDate string  `json:\"issueDate\"`\n}\n\ntype Account struct {\n\tID          string  `json:\"id\"`\n\tPrefix      string  `json:\"prefix\"`\n\tCashBalance float64 `json:\"cashBalance\"`\n\tAssetsIds   []string `json:\"assetIds\"`\n}\n\ntype Transaction struct {\n\tCUSIP       string   `json:\"cusip\"`\n\tFromCompany string   `json:\"fromCompany\"`\n\tToCompany   string   `json:\"toCompany\"`\n\tQuantity    int      `json:\"quantity\"`\n\tDiscount    float64  `json:\"discount\"`\n}\n\nfunc (t *SimpleChaincode) init(stub *shim.ChaincodeStub, args []string) ([]byte, error) {\n    \/\/ Initialize the collection of commercial paper keys\n    fmt.Println(\"Initializing paper keys collection\")\n\tvar blank []string\n\tblankBytes, _ := json.Marshal(&blank)\n\terr := stub.PutState(\"PaperKeys\", blankBytes)\n    if err != nil {\n        fmt.Println(\"Failed to initialize paper key collection\")\n    }\n\n\tfmt.Println(\"Initialization complete\")\n\treturn nil, nil\n}\n\nfunc (t *SimpleChaincode) createAccounts(stub *shim.ChaincodeStub, args []string) ([]byte, error) {\n\n\t\/\/  \t\t\t\t0\n\t\/\/ \"number of accounts to create\"\n\tvar err error\n\tnumAccounts, err := strconv.Atoi(args[0])\n\tif err != nil {\n\t\tfmt.Println(\"error creating accounts with input\")\n\t\treturn nil, errors.New(\"createAccounts accepts a single integer argument\")\n\t}\n\t\/\/create a bunch of accounts\n\tvar account Account\n\tcounter := 1\n\tfor counter <= numAccounts {\n\t\tvar prefix string\n\t\tsuffix := \"000A\"\n\t\tif counter < 10 {\n\t\t\tprefix = strconv.Itoa(counter) + \"0\" + suffix\n\t\t} else {\n\t\t\tprefix = strconv.Itoa(counter) + suffix\n\t\t}\n\t\tvar assetIds []string\n\t\taccount = Account{ID: \"company\" + strconv.Itoa(counter), Prefix: prefix, CashBalance: 10000000.0, AssetsIds: assetIds}\n\t\taccountBytes, err := json.Marshal(&account)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"error creating account\" + account.ID)\n\t\t\treturn nil, errors.New(\"Error creating account \" + account.ID)\n\t\t}\n\t\terr = stub.PutState(accountPrefix+account.ID, accountBytes)\n\t\tcounter++\n\t\tfmt.Println(\"created account\" + accountPrefix + account.ID)\n\t}\n\n\tfmt.Println(\"Accounts created\")\n\treturn nil, nil\n\n}\n\nfunc (t *SimpleChaincode) createAccount(stub *shim.ChaincodeStub, args []string) ([]byte, error) {\n    \/\/ Obtain the username to associate with the account\n    if len(args) != 1 {\n        fmt.Println(\"Error obtaining username\")\n        return nil, errors.New(\"createAccount accepts a single username argument\")\n    }\n    username := args[0]\n    \n    \/\/ Build an account object for the user\n    var assetIds []string\n    suffix := \"000A\"\n    prefix := username + suffix\n    var account = Account{ID: username, Prefix: prefix, CashBalance: 10000000.0, AssetsIds: assetIds}\n    accountBytes, err := json.Marshal(&account)\n    if err != nil {\n        fmt.Println(\"error creating account\" + account.ID)\n        return nil, errors.New(\"Error creating account \" + account.ID)\n    }\n    \n    fmt.Println(\"Attempting to get state of any existing account for \" + account.ID)\n    existingBytes, err := stub.GetState(accountPrefix + account.ID)\n\tif err == nil {\n        \n        var company Account\n        err = json.Unmarshal(existingBytes, &company)\n        if err != nil {\n            fmt.Println(\"Error unmarshalling account \" + account.ID + \"\\n--->: \" + err.Error())\n            \n            if strings.Contains(err.Error(), \"unexpected end\") {\n                fmt.Println(\"No data means existing account found for \" + account.ID + \", initializing account.\")\n                err = stub.PutState(accountPrefix+account.ID, accountBytes)\n                \n                if err == nil {\n                    fmt.Println(\"created account\" + accountPrefix + account.ID)\n                    return nil, nil\n                } else {\n                    fmt.Println(\"failed to create initialize account for \" + account.ID)\n                    return nil, errors.New(\"failed to initialize an account for \" + account.ID + \" => \" + err.Error())\n                }\n            } else {\n                return nil, errors.New(\"Error unmarshalling existing account \" + account.ID)\n            }\n        } else {\n            fmt.Println(\"Account already exists for \" + account.ID + \" \" + company.ID)\n\t\t    return nil, errors.New(\"Can't reinitialize existing user \" + account.ID)\n        }\n    } else {\n        \n        fmt.Println(\"No existing account found for \" + account.ID + \", initializing account.\")\n        err = stub.PutState(accountPrefix+account.ID, accountBytes)\n        \n        if err == nil {\n            fmt.Println(\"created account\" + accountPrefix + account.ID)\n            return nil, nil\n        } else {\n            fmt.Println(\"failed to create initialize account for \" + account.ID)\n            return nil, errors.New(\"failed to initialize an account for \" + account.ID + \" => \" + err.Error())\n        }\n        \n    }\n    \n    \n}\n\nfunc (t *SimpleChaincode) issueCommercialPaper(stub *shim.ChaincodeStub, args []string) ([]byte, error) {\n\n\t\/*\t\t0\n\t\tjson\n\t  \t{\n\t\t\t\"ticker\":  \"string\",\n\t\t\t\"par\": 0.00,\n\t\t\t\"qty\": 10,\n\t\t\t\"discount\": 7.5,\n\t\t\t\"maturity\": 30,\n\t\t\t\"owners\": [ \/\/ This one is not required\n\t\t\t\t{\n\t\t\t\t\t\"company\": \"company1\",\n\t\t\t\t\t\"quantity\": 5\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"company\": \"company3\",\n\t\t\t\t\t\"quantity\": 3\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"company\": \"company4\",\n\t\t\t\t\t\"quantity\": 2\n\t\t\t\t}\n\t\t\t],\t\t\t\t\n\t\t\t\"issuer\":\"company2\",\n\t\t\t\"issueDate\":\"1456161763790\"  (current time in milliseconds as a string)\n\n\t\t}\n\t*\/\n\t\/\/need one arg\n\tif len(args) != 1 {\n\t\tfmt.Println(\"error invalid arguments\")\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting commercial paper record\")\n\t}\n\n\tvar cp CP\n\tvar err error\n\tvar account Account\n\n\tfmt.Println(\"Unmarshalling CP\")\n\terr = json.Unmarshal([]byte(args[0]), &cp)\n\tif err != nil {\n\t\tfmt.Println(\"error invalid paper issue\")\n\t\treturn nil, errors.New(\"Invalid commercial paper issue\")\n\t}\n\n\t\/\/generate the CUSIP\n\t\/\/get account prefix\n\tfmt.Println(\"Getting state of - \" + accountPrefix + cp.Issuer)\n\taccountBytes, err := stub.GetState(accountPrefix + cp.Issuer)\n\tif err != nil {\n\t\tfmt.Println(\"Error Getting state of - \" + accountPrefix + cp.Issuer)\n\t\treturn nil, errors.New(\"Error retrieving account \" + cp.Issuer)\n\t}\n\terr = json.Unmarshal(accountBytes, &account)\n\tif err != nil {\n\t\tfmt.Println(\"Error Unmarshalling accountBytes\")\n\t\treturn nil, errors.New(\"Error retrieving account \" + cp.Issuer)\n\t}\n\t\n\taccount.AssetsIds = append(account.AssetsIds, cp.CUSIP)\n\n\t\/\/ Set the issuer to be the owner of all quantity\n\tvar owner Owner\n\towner.Company = cp.Issuer\n\towner.Quantity = cp.Qty\n\t\n\tcp.Owners = append(cp.Owners, owner)\n\n\tsuffix, err := generateCUSIPSuffix(cp.IssueDate, cp.Maturity)\n\tif err != nil {\n\t\tfmt.Println(\"Error generating cusip\")\n\t\treturn nil, errors.New(\"Error generating CUSIP\")\n\t}\n\n\tfmt.Println(\"Marshalling CP bytes\")\n\tcp.CUSIP = account.Prefix + suffix\n\t\n\tfmt.Println(\"Getting State on CP \" + cp.CUSIP)\n\tcpRxBytes, err := stub.GetState(cpPrefix+cp.CUSIP)\n\tif cpRxBytes == nil {\n\t\tfmt.Println(\"CUSIP does not exist, creating it\")\n\t\tcpBytes, err := json.Marshal(&cp)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error marshalling cp\")\n\t\t\treturn nil, errors.New(\"Error issuing commercial paper\")\n\t\t}\n\t\terr = stub.PutState(cpPrefix+cp.CUSIP, cpBytes)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error issuing paper\")\n\t\t\treturn nil, errors.New(\"Error issuing commercial paper\")\n\t\t}\n\n\t\tfmt.Println(\"Marshalling account bytes to write\")\n\t\taccountBytesToWrite, err := json.Marshal(&account)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error marshalling account\")\n\t\t\treturn nil, errors.New(\"Error issuing commercial paper\")\n\t\t}\n\t\terr = stub.PutState(accountPrefix + cp.Issuer, accountBytesToWrite)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error putting state on accountBytesToWrite\")\n\t\t\treturn nil, errors.New(\"Error issuing commercial paper\")\n\t\t}\n\t\t\n\t\t\n\t\t\/\/ Update the paper keys by adding the new key\n\t\tfmt.Println(\"Getting Paper Keys\")\n\t\tkeysBytes, err := stub.GetState(\"PaperKeys\")\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error retrieving paper keys\")\n\t\t\treturn nil, errors.New(\"Error retrieving paper keys\")\n\t\t}\n\t\tvar keys []string\n\t\terr = json.Unmarshal(keysBytes, &keys)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error unmarshel keys\")\n\t\t\treturn nil, errors.New(\"Error unmarshalling paper keys \")\n\t\t}\n\t\t\n\t\tfmt.Println(\"Appending the new key to Paper Keys\")\n\t\tfoundKey := false\n\t\tfor _, key := range keys {\n\t\t\tif key == cpPrefix+cp.CUSIP {\n\t\t\t\tfoundKey = true\n\t\t\t}\n\t\t}\n\t\tif foundKey == false {\n\t\t\tkeys = append(keys, cpPrefix+cp.CUSIP)\n\t\t\tkeysBytesToWrite, err := json.Marshal(&keys)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error marshalling keys\")\n\t\t\t\treturn nil, errors.New(\"Error marshalling the keys\")\n\t\t\t}\n\t\t\tfmt.Println(\"Put state on PaperKeys\")\n\t\t\terr = stub.PutState(\"PaperKeys\", keysBytesToWrite)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"Error writting keys back\")\n\t\t\t\treturn nil, errors.New(\"Error writing the keys back\")\n\t\t\t}\n\t\t}\n\t\t\n\t\tfmt.Println(\"Issue commercial paper %+v\\n\", cp)\n\t\treturn nil, nil\n\t} else {\n\t\tfmt.Println(\"CUSIP exists\")\n\t\t\n\t\tvar cprx CP\n\t\tfmt.Println(\"Unmarshalling CP \" + cp.CUSIP)\n\t\terr = json.Unmarshal(cpRxBytes, &cprx)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error unmarshalling cp \" + cp.CUSIP)\n\t\t\treturn nil, errors.New(\"Error unmarshalling cp \" + cp.CUSIP)\n\t\t}\n\t\t\n\t\tcprx.Qty = cprx.Qty + cp.Qty\n\t\t\n\t\tfor key, val := range cprx.Owners {\n\t\t\tif val.Company == cp.Issuer {\n\t\t\t\tcprx.Owners[key].Quantity += cp.Qty\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t\t\t\n\t\tcpWriteBytes, err := json.Marshal(&cprx)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error marshalling cp\")\n\t\t\treturn nil, errors.New(\"Error issuing commercial paper\")\n\t\t}\n\t\terr = stub.PutState(cpPrefix+cp.CUSIP, cpWriteBytes)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error issuing paper\")\n\t\t\treturn nil, errors.New(\"Error issuing commercial paper\")\n\t\t}\n\n\t\tfmt.Println(\"Updated commercial paper %+v\\n\", cprx)\n\t\treturn nil, nil\n\t}\n}\n\n\nfunc GetAllCPs(stub *shim.ChaincodeStub) ([]CP, error){\n\t\n\tvar allCPs []CP\n\t\n\t\/\/ Get list of all the keys\n\tkeysBytes, err := stub.GetState(\"PaperKeys\")\n\tif err != nil {\n\t\tfmt.Println(\"Error retrieving paper keys\")\n\t\treturn nil, errors.New(\"Error retrieving paper keys\")\n\t}\n\tvar keys []string\n\terr = json.Unmarshal(keysBytes, &keys)\n\tif err != nil {\n\t\tfmt.Println(\"Error unmarshalling paper keys\")\n\t\treturn nil, errors.New(\"Error unmarshalling paper keys\")\n\t}\n\n\t\/\/ Get all the cps\n\tfor _, value := range keys {\n\t\tcpBytes, err := stub.GetState(value)\n\t\t\n\t\tvar cp CP\n\t\terr = json.Unmarshal(cpBytes, &cp)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error retrieving cp \" + value)\n\t\t\treturn nil, errors.New(\"Error retrieving cp \" + value)\n\t\t}\n\t\t\n\t\tfmt.Println(\"Appending CP\" + value)\n\t\tallCPs = append(allCPs, cp)\n\t}\t\n\t\n\treturn allCPs, nil\n}\n\nfunc GetCP(cpid string, stub *shim.ChaincodeStub) (CP, error){\n\tvar cp CP\n\n\tcpBytes, err := stub.GetState(cpid)\n\tif err != nil {\n\t\tfmt.Println(\"Error retrieving cp \" + cpid)\n\t\treturn cp, errors.New(\"Error retrieving cp \" + cpid)\n\t}\n\t\t\n\terr = json.Unmarshal(cpBytes, &cp)\n\tif err != nil {\n\t\tfmt.Println(\"Error unmarshalling cp \" + cpid)\n\t\treturn cp, errors.New(\"Error unmarshalling cp \" + cpid)\n\t}\n\t\t\n\treturn cp, nil\n}\n\n\nfunc GetCompany(companyID string, stub *shim.ChaincodeStub) (Account, error){\n\tvar company Account\n\tcompanyBytes, err := stub.GetState(accountPrefix+companyID)\n\tif err != nil {\n\t\tfmt.Println(\"Account not found \" + companyID)\n\t\treturn company, errors.New(\"Account not found \" + companyID)\n\t}\n\n\terr = json.Unmarshal(companyBytes, &company)\n\tif err != nil {\n\t\tfmt.Println(\"Error unmarshalling account \" + companyID + \"\\n err:\" + err.Error())\n\t\treturn company, errors.New(\"Error unmarshalling account \" + companyID)\n\t}\n\t\n\treturn company, nil\n}\n\n\n\/\/ Still working on this one\nfunc (t *SimpleChaincode) transferPaper(stub *shim.ChaincodeStub, args []string) ([]byte, error) {\n\t\/*\t\t0\n\t\tjson\n\t  \t{\n\t\t\t  \"CUSIP\": \"\",\n\t\t\t  \"fromCompany\":\"\",\n\t\t\t  \"toCompany\":\"\",\n\t\t\t  \"quantity\": 1\n\t\t}\n\t*\/\n\t\/\/need one arg\n\tif len(args) != 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting commercial paper record\")\n\t}\n\t\n\tvar tr Transaction\n\n\tfmt.Println(\"Unmarshalling Transaction\")\n\terr := json.Unmarshal([]byte(args[0]), &tr)\n\tif err != nil {\n\t\tfmt.Println(\"Error Unmarshalling Transaction\")\n\t\treturn nil, errors.New(\"Invalid commercial paper issue\")\n\t}\n\n\tfmt.Println(\"Getting State on CP \" + tr.CUSIP)\n\tcpBytes, err := stub.GetState(cpPrefix+tr.CUSIP)\n\tif err != nil {\n\t\tfmt.Println(\"CUSIP not found\")\n\t\treturn nil, errors.New(\"CUSIP not found \" + tr.CUSIP)\n\t}\n\n\tvar cp CP\n\tfmt.Println(\"Unmarshalling CP \" + tr.CUSIP)\n\terr = json.Unmarshal(cpBytes, &cp)\n\tif err != nil {\n\t\tfmt.Println(\"Error unmarshalling cp \" + tr.CUSIP)\n\t\treturn nil, errors.New(\"Error unmarshalling cp \" + tr.CUSIP)\n\t}\n\n\tvar fromCompany Account\n\tfmt.Println(\"Getting State on fromCompany \" + tr.FromCompany)\t\n\tfromCompanyBytes, err := stub.GetState(accountPrefix+tr.FromCompany)\n\tif err != nil {\n\t\tfmt.Println(\"Account not found \" + tr.FromCompany)\n\t\treturn nil, errors.New(\"Account not found \" + tr.FromCompany)\n\t}\n\n\tfmt.Println(\"Unmarshalling FromCompany \")\n\terr = json.Unmarshal(fromCompanyBytes, &fromCompany)\n\tif err != nil {\n\t\tfmt.Println(\"Error unmarshalling account \" + tr.FromCompany)\n\t\treturn nil, errors.New(\"Error unmarshalling account \" + tr.FromCompany)\n\t}\n\n\tvar toCompany Account\n\tfmt.Println(\"Getting State on ToCompany \" + tr.ToCompany)\n\ttoCompanyBytes, err := stub.GetState(accountPrefix+tr.ToCompany)\n\tif err != nil {\n\t\tfmt.Println(\"Account not found \" + tr.ToCompany)\n\t\treturn nil, errors.New(\"Account not found \" + tr.ToCompany)\n\t}\n\n\tfmt.Println(\"Unmarshalling tocompany\")\n\terr = json.Unmarshal(toCompanyBytes, &toCompany)\n\tif err != nil {\n\t\tfmt.Println(\"Error unmarshalling account \" + tr.ToCompany)\n\t\treturn nil, errors.New(\"Error unmarshalling account \" + tr.ToCompany)\n\t}\n\n\t\/\/ Check for all the possible errors\n\townerFound := false \n\tquantity := 0\n\tfor _, owner := range cp.Owners {\n\t\tif owner.Company == tr.FromCompany {\n\t\t\townerFound = true\n\t\t\tquantity = owner.Quantity\n\t\t}\n\t}\n\t\n\t\/\/ If fromCompany doesn't own this paper\n\tif ownerFound == false {\n\t\tfmt.Println(\"The company \" + tr.FromCompany + \"doesn't own any of this paper\")\n\t\treturn nil, errors.New(\"The company \" + tr.FromCompany + \"doesn't own any of this paper\")\t\n\t} else {\n\t\tfmt.Println(\"The FromCompany does own this paper\")\n\t}\n\t\n\t\/\/ If fromCompany doesn't own enough quantity of this paper\n\tif quantity < tr.Quantity {\n\t\tfmt.Println(\"The company \" + tr.FromCompany + \"doesn't own enough of this paper\")\t\t\n\t\treturn nil, errors.New(\"The company \" + tr.FromCompany + \"doesn't own enough of this paper\")\t\t\t\n\t} else {\n\t\tfmt.Println(\"The FromCompany owns enough of this paper\")\n\t}\n\t\n\tamountToBeTransferred := float64(tr.Quantity) * cp.Par\n\tamountToBeTransferred -= (amountToBeTransferred) * (cp.Discount \/ 100.0) * (float64(cp.Maturity) \/ 360.0)\n\t\n\t\/\/ If toCompany doesn't have enough cash to buy the papers\n\tif toCompany.CashBalance < amountToBeTransferred {\n\t\tfmt.Println(\"The company \" + tr.ToCompany + \"doesn't have enough cash to purchase the papers\")\t\t\n\t\treturn nil, errors.New(\"The company \" + tr.ToCompany + \"doesn't have enough cash to purchase the papers\")\t\n\t} else {\n\t\tfmt.Println(\"The ToCompany has enough money to be transferred for this paper\")\n\t}\n\t\n\ttoCompany.CashBalance -= amountToBeTransferred\n\tfromCompany.CashBalance += amountToBeTransferred\n\n\ttoOwnerFound := false\n\tfor key, owner := range cp.Owners {\n\t\tif owner.Company == tr.FromCompany {\n\t\t\tfmt.Println(\"Reducing Quantity from the FromCompany\")\n\t\t\tcp.Owners[key].Quantity -= tr.Quantity\n\/\/\t\t\towner.Quantity -= tr.Quantity\n\t\t}\n\t\tif owner.Company == tr.ToCompany {\n\t\t\tfmt.Println(\"Increasing Quantity from the ToCompany\")\n\t\t\ttoOwnerFound = true\n\t\t\tcp.Owners[key].Quantity += tr.Quantity\n\/\/\t\t\towner.Quantity += tr.Quantity\n\t\t}\n\t}\n\t\n\tif toOwnerFound == false {\n\t\tvar newOwner Owner\n\t\tfmt.Println(\"As ToOwner was not found, appending the owner to the CP\")\n\t\tnewOwner.Quantity = tr.Quantity\n\t\tnewOwner.Company = tr.ToCompany\n\t\tcp.Owners = append(cp.Owners, newOwner)\n\t}\n\t\n\tfromCompany.AssetsIds = append(fromCompany.AssetsIds, tr.CUSIP)\n\n\t\/\/ Write everything back\n\t\/\/ To Company\n\ttoCompanyBytesToWrite, err := json.Marshal(&toCompany)\n\tif err != nil {\n\t\tfmt.Println(\"Error marshalling the toCompany\")\n\t\treturn nil, errors.New(\"Error marshalling the toCompany\")\n\t}\n\tfmt.Println(\"Put state on toCompany\")\n\terr = stub.PutState(accountPrefix+tr.ToCompany, toCompanyBytesToWrite)\n\tif err != nil {\n\t\tfmt.Println(\"Error writing the toCompany back\")\n\t\treturn nil, errors.New(\"Error writing the toCompany back\")\n\t}\n\t\t\n\t\/\/ From company\n\tfromCompanyBytesToWrite, err := json.Marshal(&fromCompany)\n\tif err != nil {\n\t\tfmt.Println(\"Error marshalling the fromCompany\")\n\t\treturn nil, errors.New(\"Error marshalling the fromCompany\")\n\t}\n\tfmt.Println(\"Put state on fromCompany\")\n\terr = stub.PutState(accountPrefix+tr.FromCompany, fromCompanyBytesToWrite)\n\tif err != nil {\n\t\tfmt.Println(\"Error writing the fromCompany back\")\n\t\treturn nil, errors.New(\"Error writing the fromCompany back\")\n\t}\n\t\n\t\/\/ cp\n\tcpBytesToWrite, err := json.Marshal(&cp)\n\tif err != nil {\n\t\tfmt.Println(\"Error marshalling the cp\")\n\t\treturn nil, errors.New(\"Error marshalling the cp\")\n\t}\n\tfmt.Println(\"Put state on CP\")\n\terr = stub.PutState(cpPrefix+tr.CUSIP, cpBytesToWrite)\n\tif err != nil {\n\t\tfmt.Println(\"Error writing the cp back\")\n\t\treturn nil, errors.New(\"Error writing the cp back\")\n\t}\n\t\n\tfmt.Println(\"Successfully completed Invoke\")\n\treturn nil, nil\n}\n\nfunc (t *SimpleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n\t\/\/need one arg\n\tif len(args) < 1 {\n\t\treturn nil, errors.New(\"Incorrect number of arguments. Expecting ......\")\n\t}\n\n\tif args[0] == \"GetAllCPs\" {\n\t\tfmt.Println(\"Getting all CPs\")\n\t\tallCPs, err := GetAllCPs(stub)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error from getallcps\")\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tallCPsBytes, err1 := json.Marshal(&allCPs)\n\t\t\tif err1 != nil {\n\t\t\t\tfmt.Println(\"Error marshalling allcps\")\n\t\t\t\treturn nil, err1\n\t\t\t}\t\n\t\t\tfmt.Println(\"All success, returning allcps\")\n\t\t\treturn allCPsBytes, nil\t\t \n\t\t}\n\t} else if args[0] == \"GetCP\" {\n\t\tfmt.Println(\"Getting particular cp\")\n\t\tcp, err := GetCP(args[1], stub)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error Getting particular cp\")\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tcpBytes, err1 := json.Marshal(&cp)\n\t\t\tif err1 != nil {\n\t\t\t\tfmt.Println(\"Error marshalling the cp\")\n\t\t\t\treturn nil, err1\n\t\t\t}\t\n\t\t\tfmt.Println(\"All success, returning the cp\")\n\t\t\treturn cpBytes, nil\t\t \n\t\t}\n\t} else if args[0] == \"GetCompany\" {\n\t\tfmt.Println(\"Getting the company\")\n\t\tcompany, err := GetCompany(args[1], stub)\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error from getCompany\")\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tcompanyBytes, err1 := json.Marshal(&company)\n\t\t\tif err1 != nil {\n\t\t\t\tfmt.Println(\"Error marshalling the company\")\n\t\t\t\treturn nil, err1\n\t\t\t}\t\n\t\t\tfmt.Println(\"All success, returning the company\")\n\t\t\treturn companyBytes, nil\t\t \n\t\t}\n\t} else {\n\t\tfmt.Println(\"Generic Query call\")\n\t\tbytes, err := stub.GetState(args[0])\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Some error happenend\")\n\t\t\treturn nil, errors.New(\"Some Error happened\")\n\t\t}\n\n\t\tfmt.Println(\"All success, returning from generic\")\n\t\treturn bytes, nil\t\t\n\t}\n}\n\nfunc (t *SimpleChaincode) Run(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {\n\tfmt.Println(\"run is running \" + function)\n\t\n\tif function == \"issueCommercialPaper\" {\n\t\tfmt.Println(\"Firing issueCommercialPaper\")\n\t\t\/\/Create an asset with some value\n\t\treturn t.issueCommercialPaper(stub, args)\n\t} else if function == \"transferPaper\" {\n\t\tfmt.Println(\"Firing cretransferPaperateAccounts\")\n\t\treturn t.transferPaper(stub, args)\n\t} else if function == \"createAccounts\" {\n\t\tfmt.Println(\"Firing createAccounts\")\n\t\treturn t.createAccounts(stub, args)\n\t} else if function == \"createAccount\" {\n        fmt.Println(\"Firing createAccount\")\n        return t.createAccount(stub, args)\n    } else if function == \"init\" {\n        fmt.Println(\"Firing init\")\n        return t.init(stub, args)\n    }\n\n\treturn nil, errors.New(\"Received unknown function invocation\")\n}\n\nfunc main() {\n\terr := shim.Start(new(SimpleChaincode))\n\tif err != nil {\n\t\tfmt.Println(\"Error starting Simple chaincode: %s\", err)\n\t}\n}\n\n\/\/lookup tables for last two digits of CUSIP\nvar seventhDigit = map[int]string{\n\t1:  \"A\",\n\t2:  \"B\",\n\t3:  \"C\",\n\t4:  \"D\",\n\t5:  \"E\",\n\t6:  \"F\",\n\t7:  \"G\",\n\t8:  \"H\",\n\t9:  \"J\",\n\t10: \"K\",\n\t11: \"L\",\n\t12: \"M\",\n\t13: \"N\",\n\t14: \"P\",\n\t15: \"Q\",\n\t16: \"R\",\n\t17: \"S\",\n\t18: \"T\",\n\t19: \"U\",\n\t20: \"V\",\n\t21: \"W\",\n\t22: \"X\",\n\t23: \"Y\",\n\t24: \"Z\",\n}\n\nvar eigthDigit = map[int]string{\n\t1:  \"1\",\n\t2:  \"2\",\n\t3:  \"3\",\n\t4:  \"4\",\n\t5:  \"5\",\n\t6:  \"6\",\n\t7:  \"7\",\n\t8:  \"8\",\n\t9:  \"9\",\n\t10: \"A\",\n\t11: \"B\",\n\t12: \"C\",\n\t13: \"D\",\n\t14: \"E\",\n\t15: \"F\",\n\t16: \"G\",\n\t17: \"H\",\n\t18: \"J\",\n\t19: \"K\",\n\t20: \"L\",\n\t21: \"M\",\n\t22: \"N\",\n\t23: \"P\",\n\t24: \"Q\",\n\t25: \"R\",\n\t26: \"S\",\n\t27: \"T\",\n\t28: \"U\",\n\t29: \"V\",\n\t30: \"W\",\n\t31: \"X\",\n}\n<commit_msg>Delete cp_cc.go<commit_after><|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"gnd.la\/template\"\n\t\"go\/doc\"\n\thtemplate \"html\/template\"\n\t\"strings\"\n)\n\nconst (\n\tconstPrefix = \"const-\"\n\tvarPrefix   = \"var-\"\n)\n\nfunc ConstId(name string) string {\n\treturn constPrefix + name\n}\n\nfunc VarId(name string) string {\n\treturn varPrefix + name\n}\n\nfunc FuncId(name string) string {\n\treturn \"func-\" + name\n}\n\nfunc TypeId(name string) string {\n\treturn \"type-\" + name\n}\n\nfunc MethodId(typ string, name string) string {\n\treturn \"type-\" + typ + \"-method-\" + name\n}\n\nfunc trim(s string, t string) string {\n\treturn strings.Trim(s, t)\n}\n\nfunc funcId(fn *doc.Func) string {\n\tif fn.Recv != \"\" {\n\t\trecv := fn.Recv\n\t\tif recv[0] == '*' {\n\t\t\trecv = recv[1:]\n\t\t}\n\t\treturn MethodId(recv, fn.Name)\n\t}\n\treturn FuncId(fn.Name)\n}\n\nfunc typeId(typ *doc.Type) string {\n\treturn TypeId(typ.Name)\n}\n\nfunc fa(s string) htemplate.HTML {\n\treturn htemplate.HTML(\"<i class=\\\"fa fa-\" + s + \"\\\"><\/i>\")\n}\n\nfunc init() {\n\ttemplate.AddFuncs(template.FuncMap{\n\t\t\"trim\":    trim,\n\t\t\"func_id\": funcId,\n\t\t\"type_id\": typeId,\n\t\t\"fa\":      fa,\n\t})\n}\n<commit_msg>Remove fa function<commit_after>package main\n\nimport (\n\t\"gnd.la\/template\"\n\t\"go\/doc\"\n\t\"strings\"\n)\n\nconst (\n\tconstPrefix = \"const-\"\n\tvarPrefix   = \"var-\"\n)\n\nfunc ConstId(name string) string {\n\treturn constPrefix + name\n}\n\nfunc VarId(name string) string {\n\treturn varPrefix + name\n}\n\nfunc FuncId(name string) string {\n\treturn \"func-\" + name\n}\n\nfunc TypeId(name string) string {\n\treturn \"type-\" + name\n}\n\nfunc MethodId(typ string, name string) string {\n\treturn \"type-\" + typ + \"-method-\" + name\n}\n\nfunc trim(s string, t string) string {\n\treturn strings.Trim(s, t)\n}\n\nfunc funcId(fn *doc.Func) string {\n\tif fn.Recv != \"\" {\n\t\trecv := fn.Recv\n\t\tif recv[0] == '*' {\n\t\t\trecv = recv[1:]\n\t\t}\n\t\treturn MethodId(recv, fn.Name)\n\t}\n\treturn FuncId(fn.Name)\n}\n\nfunc typeId(typ *doc.Type) string {\n\treturn TypeId(typ.Name)\n}\n\nfunc init() {\n\ttemplate.AddFuncs(template.FuncMap{\n\t\t\"trim\":    trim,\n\t\t\"func_id\": funcId,\n\t\t\"type_id\": typeId,\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package collectors\n\nimport (\n\t\"github.com\/bosun-monitor\/scollector\/_third_party\/github.com\/StackExchange\/wmi\"\n\t\"github.com\/bosun-monitor\/scollector\/_third_party\/github.com\/bosun-monitor\/metadata\"\n\t\"github.com\/bosun-monitor\/scollector\/_third_party\/github.com\/bosun-monitor\/opentsdb\"\n)\n\nfunc init() {\n\tcollectors = append(collectors, &IntervalCollector{F: c_physical_disk_windows})\n\tcollectors = append(collectors, &IntervalCollector{F: c_diskspace_windows})\n}\n\nconst (\n\t\/\/Converts 100nS samples to 1S samples\n\twinDisk100nS_1S = 10000000\n\n\t\/\/Converts 100nS samples to 1mS samples\n\twinDisk100nS_1mS = 1000000\n\n\t\/\/Converts 100nS samples to 0-100 Percent samples\n\twinDisk100nS_Pct = 100000\n)\n\nfunc c_diskspace_windows() (opentsdb.MultiDataPoint, error) {\n\tvar dst []Win32_LogicalDisk\n\tvar q = wmi.CreateQuery(&dst, \"WHERE DriveType = 3\")\n\terr := queryWmi(q, &dst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar md opentsdb.MultiDataPoint\n\tfor _, v := range dst {\n\t\ttags := opentsdb.TagSet{\"disk\": v.Name}\n\t\tspace_used := v.Size - v.FreeSpace\n\t\tAdd(&md, \"win.disk.fs.space_free\", v.FreeSpace, tags, metadata.Gauge, metadata.Bytes, osDiskFreeDesc)\n\t\tAdd(&md, \"win.disk.fs.space_total\", v.Size, tags, metadata.Gauge, metadata.Bytes, osDiskTotalDesc)\n\t\tAdd(&md, \"win.disk.fs.space_used\", space_used, tags, metadata.Gauge, metadata.Bytes, osDiskUsedDesc)\n\t\tAdd(&md, osDiskFree, v.FreeSpace, tags, metadata.Gauge, metadata.Bytes, osDiskFreeDesc)\n\t\tAdd(&md, osDiskTotal, v.Size, tags, metadata.Gauge, metadata.Bytes, osDiskTotalDesc)\n\t\tAdd(&md, osDiskUsed, space_used, tags, metadata.Gauge, metadata.Bytes, osDiskUsedDesc)\n\t\tif v.Size != 0 {\n\t\t\tpercent_free := float64(v.FreeSpace \/ v.Size * 100)\n\t\t\tAdd(&md, \"win.disk.fs.percent_free\", percent_free, tags, metadata.Gauge, metadata.Pct, osDiskPctFreeDesc)\n\t\t\tAdd(&md, osDiskPctFree, percent_free, tags, metadata.Gauge, metadata.Pct, osDiskPctFreeDesc)\n\t\t}\n\t}\n\treturn md, nil\n}\n\ntype Win32_LogicalDisk struct {\n\tFreeSpace uint64\n\tName      string\n\tSize      uint64\n}\n\nfunc c_physical_disk_windows() (opentsdb.MultiDataPoint, error) {\n\tvar dst []Win32_PerfRawData_PerfDisk_PhysicalDisk\n\tvar q = wmi.CreateQuery(&dst, `WHERE Name <> '_Total'`)\n\terr := queryWmi(q, &dst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar md opentsdb.MultiDataPoint\n\tfor _, v := range dst {\n\t\tAdd(&md, \"win.disk.duration\", v.AvgDiskSecPerRead\/winDisk100nS_1mS, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"}, metadata.Counter, metadata.MilliSecond, \"Time, in milliseconds, of a read from the disk.\")\n\t\tAdd(&md, \"win.disk.duration\", v.AvgDiskSecPerWrite\/winDisk100nS_1mS, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"}, metadata.Counter, metadata.MilliSecond, \"Time, in milliseconds, of a write to the disk.\")\n\t\tAdd(&md, \"win.disk.queue\", v.AvgDiskReadQueueLength\/winDisk100nS_1S, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"}, metadata.Counter, metadata.Operation, \"Number of read requests that were queued for the disk.\")\n\t\tAdd(&md, \"win.disk.queue\", v.AvgDiskWriteQueueLength\/winDisk100nS_1S, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"}, metadata.Counter, metadata.Operation, \"Number of write requests that were queued for the disk.\")\n\t\tAdd(&md, \"win.disk.ops\", v.DiskReadsPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"}, metadata.Counter, metadata.PerSecond, \"Number of read operations on the disk.\")\n\t\tAdd(&md, \"win.disk.ops\", v.DiskWritesPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"}, metadata.Counter, metadata.PerSecond, \"Number of write operations on the disk.\")\n\t\tAdd(&md, \"win.disk.bytes\", v.DiskReadBytesPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"}, metadata.Counter, metadata.BytesPerSecond, \"Number of bytes read from the disk.\")\n\t\tAdd(&md, \"win.disk.bytes\", v.DiskWriteBytesPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"}, metadata.Counter, metadata.BytesPerSecond, \"Number of bytes written to the disk.\")\n\t\tAdd(&md, \"win.disk.percent_time\", v.PercentDiskReadTime\/winDisk100nS_Pct, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"}, metadata.Counter, metadata.Pct, \"Percentage of time that the disk was busy servicing read requests.\")\n\t\tAdd(&md, \"win.disk.percent_time\", v.PercentDiskWriteTime\/winDisk100nS_Pct, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"}, metadata.Counter, metadata.Pct, \"Percentage of time that the disk was busy servicing write requests.\")\n\t\tAdd(&md, \"win.disk.spltio\", v.SplitIOPerSec, opentsdb.TagSet{\"disk\": v.Name}, metadata.Counter, metadata.PerSecond, \"Number of requests to the disk that were split into multiple requests due to size or fragmentation.\")\n\t}\n\treturn md, nil\n}\n\n\/\/See msdn for counter types http:\/\/msdn.microsoft.com\/en-us\/library\/ms804035.aspx\ntype Win32_PerfRawData_PerfDisk_PhysicalDisk struct {\n\tAvgDiskReadQueueLength  uint64\n\tAvgDiskSecPerRead       uint32\n\tAvgDiskSecPerWrite      uint32\n\tAvgDiskWriteQueueLength uint64\n\tDiskReadBytesPerSec     uint64\n\tDiskReadsPerSec         uint32\n\tDiskWriteBytesPerSec    uint64\n\tDiskWritesPerSec        uint32\n\tName                    string\n\tPercentDiskReadTime     uint64\n\tPercentDiskWriteTime    uint64\n\tSplitIOPerSec           uint32\n}\n<commit_msg>cmd\/scollector: Fix win.disk.fs.percent_free<commit_after>package collectors\n\nimport (\n\t\"github.com\/bosun-monitor\/scollector\/_third_party\/github.com\/StackExchange\/wmi\"\n\t\"github.com\/bosun-monitor\/scollector\/_third_party\/github.com\/bosun-monitor\/metadata\"\n\t\"github.com\/bosun-monitor\/scollector\/_third_party\/github.com\/bosun-monitor\/opentsdb\"\n)\n\nfunc init() {\n\tcollectors = append(collectors, &IntervalCollector{F: c_physical_disk_windows})\n\tcollectors = append(collectors, &IntervalCollector{F: c_diskspace_windows})\n}\n\nconst (\n\t\/\/Converts 100nS samples to 1S samples\n\twinDisk100nS_1S = 10000000\n\n\t\/\/Converts 100nS samples to 1mS samples\n\twinDisk100nS_1mS = 1000000\n\n\t\/\/Converts 100nS samples to 0-100 Percent samples\n\twinDisk100nS_Pct = 100000\n)\n\nfunc c_diskspace_windows() (opentsdb.MultiDataPoint, error) {\n\tvar dst []Win32_LogicalDisk\n\tvar q = wmi.CreateQuery(&dst, \"WHERE DriveType = 3\")\n\terr := queryWmi(q, &dst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar md opentsdb.MultiDataPoint\n\tfor _, v := range dst {\n\t\ttags := opentsdb.TagSet{\"disk\": v.Name}\n\t\tspace_used := v.Size - v.FreeSpace\n\t\tAdd(&md, \"win.disk.fs.space_free\", v.FreeSpace, tags, metadata.Gauge, metadata.Bytes, osDiskFreeDesc)\n\t\tAdd(&md, \"win.disk.fs.space_total\", v.Size, tags, metadata.Gauge, metadata.Bytes, osDiskTotalDesc)\n\t\tAdd(&md, \"win.disk.fs.space_used\", space_used, tags, metadata.Gauge, metadata.Bytes, osDiskUsedDesc)\n\t\tAdd(&md, osDiskFree, v.FreeSpace, tags, metadata.Gauge, metadata.Bytes, osDiskFreeDesc)\n\t\tAdd(&md, osDiskTotal, v.Size, tags, metadata.Gauge, metadata.Bytes, osDiskTotalDesc)\n\t\tAdd(&md, osDiskUsed, space_used, tags, metadata.Gauge, metadata.Bytes, osDiskUsedDesc)\n\t\tif v.Size != 0 {\n\t\t\tpercent_free := float64(v.FreeSpace) \/ float64(v.Size) * 100\n\t\t\tAdd(&md, \"win.disk.fs.percent_free\", percent_free, tags, metadata.Gauge, metadata.Pct, osDiskPctFreeDesc)\n\t\t\tAdd(&md, osDiskPctFree, percent_free, tags, metadata.Gauge, metadata.Pct, osDiskPctFreeDesc)\n\t\t}\n\t}\n\treturn md, nil\n}\n\ntype Win32_LogicalDisk struct {\n\tFreeSpace uint64\n\tName      string\n\tSize      uint64\n}\n\nfunc c_physical_disk_windows() (opentsdb.MultiDataPoint, error) {\n\tvar dst []Win32_PerfRawData_PerfDisk_PhysicalDisk\n\tvar q = wmi.CreateQuery(&dst, `WHERE Name <> '_Total'`)\n\terr := queryWmi(q, &dst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar md opentsdb.MultiDataPoint\n\tfor _, v := range dst {\n\t\tAdd(&md, \"win.disk.duration\", v.AvgDiskSecPerRead\/winDisk100nS_1mS, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"}, metadata.Counter, metadata.MilliSecond, \"Time, in milliseconds, of a read from the disk.\")\n\t\tAdd(&md, \"win.disk.duration\", v.AvgDiskSecPerWrite\/winDisk100nS_1mS, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"}, metadata.Counter, metadata.MilliSecond, \"Time, in milliseconds, of a write to the disk.\")\n\t\tAdd(&md, \"win.disk.queue\", v.AvgDiskReadQueueLength\/winDisk100nS_1S, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"}, metadata.Counter, metadata.Operation, \"Number of read requests that were queued for the disk.\")\n\t\tAdd(&md, \"win.disk.queue\", v.AvgDiskWriteQueueLength\/winDisk100nS_1S, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"}, metadata.Counter, metadata.Operation, \"Number of write requests that were queued for the disk.\")\n\t\tAdd(&md, \"win.disk.ops\", v.DiskReadsPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"}, metadata.Counter, metadata.PerSecond, \"Number of read operations on the disk.\")\n\t\tAdd(&md, \"win.disk.ops\", v.DiskWritesPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"}, metadata.Counter, metadata.PerSecond, \"Number of write operations on the disk.\")\n\t\tAdd(&md, \"win.disk.bytes\", v.DiskReadBytesPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"}, metadata.Counter, metadata.BytesPerSecond, \"Number of bytes read from the disk.\")\n\t\tAdd(&md, \"win.disk.bytes\", v.DiskWriteBytesPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"}, metadata.Counter, metadata.BytesPerSecond, \"Number of bytes written to the disk.\")\n\t\tAdd(&md, \"win.disk.percent_time\", v.PercentDiskReadTime\/winDisk100nS_Pct, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"}, metadata.Counter, metadata.Pct, \"Percentage of time that the disk was busy servicing read requests.\")\n\t\tAdd(&md, \"win.disk.percent_time\", v.PercentDiskWriteTime\/winDisk100nS_Pct, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"}, metadata.Counter, metadata.Pct, \"Percentage of time that the disk was busy servicing write requests.\")\n\t\tAdd(&md, \"win.disk.spltio\", v.SplitIOPerSec, opentsdb.TagSet{\"disk\": v.Name}, metadata.Counter, metadata.PerSecond, \"Number of requests to the disk that were split into multiple requests due to size or fragmentation.\")\n\t}\n\treturn md, nil\n}\n\n\/\/See msdn for counter types http:\/\/msdn.microsoft.com\/en-us\/library\/ms804035.aspx\ntype Win32_PerfRawData_PerfDisk_PhysicalDisk struct {\n\tAvgDiskReadQueueLength  uint64\n\tAvgDiskSecPerRead       uint32\n\tAvgDiskSecPerWrite      uint32\n\tAvgDiskWriteQueueLength uint64\n\tDiskReadBytesPerSec     uint64\n\tDiskReadsPerSec         uint32\n\tDiskWriteBytesPerSec    uint64\n\tDiskWritesPerSec        uint32\n\tName                    string\n\tPercentDiskReadTime     uint64\n\tPercentDiskWriteTime    uint64\n\tSplitIOPerSec           uint32\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 ThoughtWorks, Inc.\n\n\/\/ This file is part of Gauge.\n\n\/\/ Gauge is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\n\/\/ Gauge is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU General Public License for more details.\n\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with Gauge.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/getgauge\/gauge\/api\"\n\t\"github.com\/getgauge\/gauge\/config\"\n\t\"github.com\/getgauge\/gauge\/env\"\n\t\"github.com\/getgauge\/gauge\/execution\"\n\t\"github.com\/getgauge\/gauge\/filter\"\n\t\"github.com\/getgauge\/gauge\/formatter\"\n\t\"github.com\/getgauge\/gauge\/logger\"\n\t\"github.com\/getgauge\/gauge\/logger\/execLogger\"\n\t\"github.com\/getgauge\/gauge\/plugin\/install\"\n\t\"github.com\/getgauge\/gauge\/project_init\"\n\t\"github.com\/getgauge\/gauge\/refactor\"\n\t\"github.com\/getgauge\/gauge\/util\"\n\t\"github.com\/getgauge\/gauge\/version\"\n\tflag \"github.com\/getgauge\/mflag\"\n\t\"os\"\n\t\"time\"\n)\n\n\/\/ Command line flags\nvar daemonize = flag.Bool([]string{\"-daemonize\"}, false, \"Run as a daemon\")\nvar gaugeVersion = flag.Bool([]string{\"v\", \"-version\", \"version\"}, false, \"Print the current version and exit. Eg: gauge --version\")\nvar verbosity = flag.Bool([]string{\"-verbose\"}, false, \"Enable verbose logging for debugging\")\nvar logLevel = flag.String([]string{\"-log-level\"}, \"\", \"Set level of logging to debug, info, warning, error or critical\")\nvar simpleConsoleOutput = flag.Bool([]string{\"-simple-console\"}, false, \"Removes colouring and simplifies from the console output\")\nvar initialize = flag.String([]string{\"-init\"}, \"\", \"Initializes project structure in the current directory. Eg: gauge --init java\")\nvar installPlugin = flag.String([]string{\"-install\"}, \"\", \"Downloads and installs a plugin. Eg: gauge --install java\")\nvar uninstallPlugin = flag.String([]string{\"-uninstall\"}, \"\", \"Uninstalls a plugin. Eg: gauge --uninstall java\")\nvar installAll = flag.Bool([]string{\"-install-all\"}, false, \"Installs all the plugins specified in project manifest, if not installed. Eg: gauge --install-all\")\nvar update = flag.String([]string{\"-update\"}, \"\", \"Updates a plugin. Eg: gauge --update java\")\nvar installVersion = flag.String([]string{\"-plugin-version\"}, \"\", \"Version of plugin to be installed. This is used with --install\")\nvar installZip = flag.String([]string{\"-file\", \"f\"}, \"\", \"Installs the plugin from zip file. This is used with --install. Eg: gauge --install java -f ZIP_FILE\")\nvar currentEnv = flag.String([]string{\"-env\"}, \"default\", \"Specifies the environment. If not specified, default will be used\")\nvar addPlugin = flag.String([]string{\"-add-plugin\"}, \"\", \"Adds the specified non-language plugin to the current project\")\nvar pluginArgs = flag.String([]string{\"-plugin-args\"}, \"\", \"Specified additional arguments to the plugin. This is used together with --add-plugin\")\nvar specFilesToFormat = flag.String([]string{\"-format\"}, \"\", \"Formats the specified spec files\")\nvar executeTags = flag.String([]string{\"-tags\"}, \"\", \"Executes the specs and scenarios tagged with given tags. Eg: gauge --tags tag1,tag2 specs\")\nvar tableRows = flag.String([]string{\"-table-rows\"}, \"\", \"Executes the specs and scenarios only for the selected rows. Eg: gauge --table-rows \\\"1-3\\\" specs\/hello.spec\")\nvar apiPort = flag.String([]string{\"-api-port\"}, \"\", \"Specifies the api port to be used. Eg: gauge --daemonize --api-port 7777\")\nvar refactorSteps = flag.String([]string{\"-refactor\"}, \"\", \"Refactor steps\")\nvar parallel = flag.Bool([]string{\"-parallel\", \"p\"}, false, \"Execute specs in parallel\")\nvar numberOfExecutionStreams = flag.Int([]string{\"n\"}, util.NumberOfCores(), \"Specify number of parallel execution streams\")\nvar distribute = flag.Int([]string{\"g\", \"-group\"}, -1, \"Specify which group of specification to execute based on -n flag\")\nvar workingDir = flag.String([]string{\"-dir\"}, \".\", \"Set the working directory for the current command, accepts a path relative to current directory.\")\nvar doNotRandomize = flag.Bool([]string{\"-sort\", \"s\"}, false, \"run specs in Alphabetical Order. Eg: gauge -s specs\")\n\nfunc main() {\n\tflag.Parse()\n\tproject_init.SetWorkingDir(*workingDir)\n\tinitPackageFlags()\n\tvalidGaugeProject := true\n\terr := config.SetProjectRoot(flag.Args())\n\tif err != nil {\n\t\tvalidGaugeProject = false\n\t}\n\tenv.LoadEnv(true)\n\tlogger.Initialize(*verbosity, *logLevel)\n\tif *gaugeVersion {\n\t\tversion.PrintVersion()\n\t} else if *daemonize {\n\t\tif validGaugeProject {\n\t\t\tapi.RunInBackground(*apiPort)\n\t\t} else {\n\t\t\tlogger.Log.Error(err.Error())\n\t\t}\n\t} else if *specFilesToFormat != \"\" {\n\t\tif validGaugeProject {\n\t\t\tformatter.FormatSpecFilesIn(*specFilesToFormat)\n\t\t} else {\n\t\t\tlogger.Log.Error(err.Error())\n\t\t}\n\t} else if *initialize != \"\" {\n\t\tproject_init.InitializeProject(*initialize)\n\t} else if *installZip != \"\" && *installPlugin != \"\" {\n\t\tinstall.InstallPluginZip(*installZip, *installPlugin)\n\t} else if *installPlugin != \"\" {\n\t\tinstall.DownloadAndInstallPlugin(*installPlugin, *installVersion)\n\t} else if *uninstallPlugin != \"\" {\n\t\tinstall.UninstallPlugin(*uninstallPlugin)\n\t} else if *installAll {\n\t\tinstall.InstallAllPlugins()\n\t} else if *update != \"\" {\n\t\tinstall.UpdatePlugin(*update)\n\t} else if *addPlugin != \"\" {\n\t\tinstall.AddPluginToProject(*addPlugin, *pluginArgs)\n\t} else if *refactorSteps != \"\" {\n\t\tif validGaugeProject {\n\t\t\tstartChan := api.StartAPI()\n\t\t\trefactor.RefactorSteps(*refactorSteps, newStepName(), startChan)\n\t\t} else {\n\t\t\tlogger.Log.Error(err.Error())\n\t\t}\n\t} else {\n\t\tif len(flag.Args()) == 0 {\n\t\t\tprintUsage()\n\t\t} else if validGaugeProject {\n\t\t\tif *distribute != -1 {\n\t\t\t\t*doNotRandomize = true\n\t\t\t}\n\t\t\texecution.ExecuteSpecs(*parallel, flag.Args())\n\t\t} else {\n\t\t\tlogger.Log.Error(\"Could not set project root: %s\", err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}\n\nfunc printUsage() {\n\tfmt.Printf(\"gauge - version %s\\n\", version.CurrentGaugeVersion.String())\n\tfmt.Printf(\"Copyright %d Thoughtworks\\n\\n\", time.Now().Year())\n\tfmt.Println(\"Usage:\")\n\tfmt.Println(\"\\tgauge specs\/\")\n\tfmt.Println(\"\\tgauge specs\/spec_name.spec\")\n\tfmt.Println(\"\\nOptions:\")\n\tflag.PrintDefaults()\n\tos.Exit(2)\n}\n\nfunc newStepName() string {\n\tif len(flag.Args()) != 1 {\n\t\tprintUsage()\n\t}\n\treturn flag.Args()[0]\n}\n\nfunc initPackageFlags() {\n\tif util.IsWindows() {\n\t\t*simpleConsoleOutput = true\n\t}\n\texecLogger.SimpleConsoleOutput = *simpleConsoleOutput\n\tenv.ProjectEnv = *currentEnv\n\texecution.ExecuteTags = *executeTags\n\texecution.TableRows = *tableRows\n\texecution.NumberOfExecutionStreams = *numberOfExecutionStreams\n\tfilter.ExecuteTags = *executeTags\n\tfilter.DoNotRandomize = *doNotRandomize\n\tfilter.Distribute = *distribute\n\tfilter.NumberOfExecutionStreams = *numberOfExecutionStreams\n}\n<commit_msg>fixing typo<commit_after>\/\/ Copyright 2015 ThoughtWorks, Inc.\n\n\/\/ This file is part of Gauge.\n\n\/\/ Gauge is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\n\/\/ Gauge is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\/\/ GNU General Public License for more details.\n\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with Gauge.  If not, see <http:\/\/www.gnu.org\/licenses\/>.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/getgauge\/gauge\/api\"\n\t\"github.com\/getgauge\/gauge\/config\"\n\t\"github.com\/getgauge\/gauge\/env\"\n\t\"github.com\/getgauge\/gauge\/execution\"\n\t\"github.com\/getgauge\/gauge\/filter\"\n\t\"github.com\/getgauge\/gauge\/formatter\"\n\t\"github.com\/getgauge\/gauge\/logger\"\n\t\"github.com\/getgauge\/gauge\/logger\/execLogger\"\n\t\"github.com\/getgauge\/gauge\/plugin\/install\"\n\t\"github.com\/getgauge\/gauge\/project_init\"\n\t\"github.com\/getgauge\/gauge\/refactor\"\n\t\"github.com\/getgauge\/gauge\/util\"\n\t\"github.com\/getgauge\/gauge\/version\"\n\tflag \"github.com\/getgauge\/mflag\"\n\t\"os\"\n\t\"time\"\n)\n\n\/\/ Command line flags\nvar daemonize = flag.Bool([]string{\"-daemonize\"}, false, \"Run as a daemon\")\nvar gaugeVersion = flag.Bool([]string{\"v\", \"-version\", \"version\"}, false, \"Print the current version and exit. Eg: gauge --version\")\nvar verbosity = flag.Bool([]string{\"-verbose\"}, false, \"Enable verbose logging for debugging\")\nvar logLevel = flag.String([]string{\"-log-level\"}, \"\", \"Set level of logging to debug, info, warning, error or critical\")\nvar simpleConsoleOutput = flag.Bool([]string{\"-simple-console\"}, false, \"Removes colouring and simplifies from the console output\")\nvar initialize = flag.String([]string{\"-init\"}, \"\", \"Initializes project structure in the current directory. Eg: gauge --init java\")\nvar installPlugin = flag.String([]string{\"-install\"}, \"\", \"Downloads and installs a plugin. Eg: gauge --install java\")\nvar uninstallPlugin = flag.String([]string{\"-uninstall\"}, \"\", \"Uninstalls a plugin. Eg: gauge --uninstall java\")\nvar installAll = flag.Bool([]string{\"-install-all\"}, false, \"Installs all the plugins specified in project manifest, if not installed. Eg: gauge --install-all\")\nvar update = flag.String([]string{\"-update\"}, \"\", \"Updates a plugin. Eg: gauge --update java\")\nvar installVersion = flag.String([]string{\"-plugin-version\"}, \"\", \"Version of plugin to be installed. This is used with --install\")\nvar installZip = flag.String([]string{\"-file\", \"f\"}, \"\", \"Installs the plugin from zip file. This is used with --install. Eg: gauge --install java -f ZIP_FILE\")\nvar currentEnv = flag.String([]string{\"-env\"}, \"default\", \"Specifies the environment. If not specified, default will be used\")\nvar addPlugin = flag.String([]string{\"-add-plugin\"}, \"\", \"Adds the specified non-language plugin to the current project\")\nvar pluginArgs = flag.String([]string{\"-plugin-args\"}, \"\", \"Specified additional arguments to the plugin. This is used together with --add-plugin\")\nvar specFilesToFormat = flag.String([]string{\"-format\"}, \"\", \"Formats the specified spec files\")\nvar executeTags = flag.String([]string{\"-tags\"}, \"\", \"Executes the specs and scenarios tagged with given tags. Eg: gauge --tags tag1,tag2 specs\")\nvar tableRows = flag.String([]string{\"-table-rows\"}, \"\", \"Executes the specs and scenarios only for the selected rows. Eg: gauge --table-rows \\\"1-3\\\" specs\/hello.spec\")\nvar apiPort = flag.String([]string{\"-api-port\"}, \"\", \"Specifies the api port to be used. Eg: gauge --daemonize --api-port 7777\")\nvar refactorSteps = flag.String([]string{\"-refactor\"}, \"\", \"Refactor steps\")\nvar parallel = flag.Bool([]string{\"-parallel\", \"p\"}, false, \"Execute specs in parallel\")\nvar numberOfExecutionStreams = flag.Int([]string{\"n\"}, util.NumberOfCores(), \"Specify number of parallel execution streams\")\nvar distribute = flag.Int([]string{\"g\", \"-group\"}, -1, \"Specify which group of specification to execute based on -n flag\")\nvar workingDir = flag.String([]string{\"-dir\"}, \".\", \"Set the working directory for the current command, accepts a path relative to current directory.\")\nvar doNotRandomize = flag.Bool([]string{\"-sort\", \"s\"}, false, \"run specs in Alphabetical Order. Eg: gauge -s specs\")\n\nfunc main() {\n\tflag.Parse()\n\tproject_init.SetWorkingDir(*workingDir)\n\tinitPackageFlags()\n\tvalidGaugeProject := true\n\terr := config.SetProjectRoot(flag.Args())\n\tif err != nil {\n\t\tvalidGaugeProject = false\n\t}\n\tenv.LoadEnv(true)\n\tlogger.Initialize(*verbosity, *logLevel)\n\tif *gaugeVersion {\n\t\tversion.PrintVersion()\n\t} else if *daemonize {\n\t\tif validGaugeProject {\n\t\t\tapi.RunInBackground(*apiPort)\n\t\t} else {\n\t\t\tlogger.Log.Error(err.Error())\n\t\t}\n\t} else if *specFilesToFormat != \"\" {\n\t\tif validGaugeProject {\n\t\t\tformatter.FormatSpecFilesIn(*specFilesToFormat)\n\t\t} else {\n\t\t\tlogger.Log.Error(err.Error())\n\t\t}\n\t} else if *initialize != \"\" {\n\t\tproject_init.InitializeProject(*initialize)\n\t} else if *installZip != \"\" && *installPlugin != \"\" {\n\t\tinstall.InstallPluginZip(*installZip, *installPlugin)\n\t} else if *installPlugin != \"\" {\n\t\tinstall.DownloadAndInstallPlugin(*installPlugin, *installVersion)\n\t} else if *uninstallPlugin != \"\" {\n\t\tinstall.UninstallPlugin(*uninstallPlugin)\n\t} else if *installAll {\n\t\tinstall.InstallAllPlugins()\n\t} else if *update != \"\" {\n\t\tinstall.UpdatePlugin(*update)\n\t} else if *addPlugin != \"\" {\n\t\tinstall.AddPluginToProject(*addPlugin, *pluginArgs)\n\t} else if *refactorSteps != \"\" {\n\t\tif validGaugeProject {\n\t\t\tstartChan := api.StartAPI()\n\t\t\trefactor.RefactorSteps(*refactorSteps, newStepName(), startChan)\n\t\t} else {\n\t\t\tlogger.Log.Error(err.Error())\n\t\t}\n\t} else {\n\t\tif len(flag.Args()) == 0 {\n\t\t\tprintUsage()\n\t\t} else if validGaugeProject {\n\t\t\tif *distribute != -1 {\n\t\t\t\t*doNotRandomize = true\n\t\t\t}\n\t\t\texecution.ExecuteSpecs(*parallel, flag.Args())\n\t\t} else {\n\t\t\tlogger.Log.Error(\"Could not set project root: %s\", err.Error())\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}\n\nfunc printUsage() {\n\tfmt.Printf(\"gauge -version %s\\n\", version.CurrentGaugeVersion.String())\n\tfmt.Printf(\"Copyright %d Thoughtworks\\n\\n\", time.Now().Year())\n\tfmt.Println(\"Usage:\")\n\tfmt.Println(\"\\tgauge specs\/\")\n\tfmt.Println(\"\\tgauge specs\/spec_name.spec\")\n\tfmt.Println(\"\\nOptions:\")\n\tflag.PrintDefaults()\n\tos.Exit(2)\n}\n\nfunc newStepName() string {\n\tif len(flag.Args()) != 1 {\n\t\tprintUsage()\n\t}\n\treturn flag.Args()[0]\n}\n\nfunc initPackageFlags() {\n\tif util.IsWindows() {\n\t\t*simpleConsoleOutput = true\n\t}\n\texecLogger.SimpleConsoleOutput = *simpleConsoleOutput\n\tenv.ProjectEnv = *currentEnv\n\texecution.ExecuteTags = *executeTags\n\texecution.TableRows = *tableRows\n\texecution.NumberOfExecutionStreams = *numberOfExecutionStreams\n\tfilter.ExecuteTags = *executeTags\n\tfilter.DoNotRandomize = *doNotRandomize\n\tfilter.Distribute = *distribute\n\tfilter.NumberOfExecutionStreams = *numberOfExecutionStreams\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"expvar\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/NYTimes\/gziphandler\"\n\t\"github.com\/mat\/besticon\/besticon\"\n\t\"github.com\/mat\/besticon\/besticon\/iconserver\/assets\"\n\t\"github.com\/mat\/besticon\/lettericon\"\n)\n\nfunc indexHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path == \"\" || r.URL.Path == \"\/\" {\n\t\trenderHTMLTemplate(w, 200, indexHTML, nil)\n\t} else {\n\t\trenderHTMLTemplate(w, 404, notFoundHTML, nil)\n\t}\n}\n\nfunc iconsHandler(w http.ResponseWriter, r *http.Request) {\n\turl := r.FormValue(urlParam)\n\tif len(url) == 0 {\n\t\thttp.Redirect(w, r, \"\/\", 302)\n\t\treturn\n\t}\n\n\tfinder := besticon.IconFinder{}\n\n\tformats := r.FormValue(\"formats\")\n\tif formats != \"\" {\n\t\tfinder.FormatsAllowed = strings.Split(r.FormValue(\"formats\"), \",\")\n\t}\n\n\ticons, e := finder.FetchIcons(url)\n\tswitch {\n\tcase e != nil:\n\t\trenderHTMLTemplate(w, 404, iconsHTML, pageInfo{URL: url, Error: e})\n\tcase len(icons) == 0:\n\t\terrNoIcons := errors.New(\"this poor site has no icons at all :-(\")\n\t\trenderHTMLTemplate(w, 404, iconsHTML, pageInfo{URL: url, Error: errNoIcons})\n\tdefault:\n\t\trenderHTMLTemplate(w, 200, iconsHTML, pageInfo{Icons: icons, URL: url})\n\t}\n}\n\nfunc iconHandler(w http.ResponseWriter, r *http.Request) {\n\turl := r.FormValue(\"url\")\n\tif len(url) == 0 {\n\t\twriteAPIError(w, 400, errors.New(\"need url parameter\"))\n\t\treturn\n\t}\n\n\tsize := r.FormValue(\"size\")\n\tif size == \"\" {\n\t\twriteAPIError(w, 400, errors.New(\"need size parameter\"))\n\t\treturn\n\t}\n\tminSize, err := strconv.Atoi(size)\n\tif err != nil || minSize < besticon.MinIconSize || minSize > besticon.MaxIconSize {\n\t\twriteAPIError(w, 400, errors.New(\"bad size parameter\"))\n\t\treturn\n\t}\n\n\tfinder := besticon.IconFinder{}\n\tformats := r.FormValue(\"formats\")\n\tif formats != \"\" {\n\t\tfinder.FormatsAllowed = strings.Split(r.FormValue(\"formats\"), \",\")\n\t}\n\n\tfinder.FetchIcons(url)\n\n\ticon := finder.IconWithMinSize(minSize)\n\tif icon != nil {\n\t\tredirectWithCacheControl(w, r, icon.URL)\n\t\treturn\n\t}\n\n\tfallbackIconURL := r.FormValue(\"fallback_icon_url\")\n\tif fallbackIconURL != \"\" {\n\t\tredirectWithCacheControl(w, r, fallbackIconURL)\n\t\treturn\n\t}\n\n\ticonColor := finder.MainColorForIcons()\n\tletter := lettericon.MainLetterFromURL(url)\n\tredirectPath := lettericon.IconPath(letter, size, iconColor)\n\tredirectWithCacheControl(w, r, redirectPath)\n}\n\nfunc popularHandler(w http.ResponseWriter, r *http.Request) {\n\ticonSize, err := strconv.Atoi(r.FormValue(\"iconsize\"))\n\tif iconSize > besticon.MaxIconSize || iconSize < besticon.MinIconSize || err != nil {\n\t\ticonSize = 120\n\t}\n\n\tpageInfo := struct {\n\t\tURLs        []string\n\t\tIconSize    int\n\t\tDisplaySize int\n\t}{\n\t\tbesticon.PopularSites,\n\t\ticonSize,\n\t\ticonSize \/ 2,\n\t}\n\trenderHTMLTemplate(w, 200, popularHTML, pageInfo)\n}\n\nconst (\n\turlParam = \"url\"\n)\n\nfunc alliconsHandler(w http.ResponseWriter, r *http.Request) {\n\turl := r.FormValue(urlParam)\n\tif len(url) == 0 {\n\t\terrMissingURL := errors.New(\"need url query parameter\")\n\t\twriteAPIError(w, 400, errMissingURL)\n\t\treturn\n\t}\n\n\tfinder := besticon.IconFinder{}\n\tformats := r.FormValue(\"formats\")\n\tif formats != \"\" {\n\t\tfinder.FormatsAllowed = strings.Split(r.FormValue(\"formats\"), \",\")\n\t}\n\n\ticons, e := finder.FetchIcons(url)\n\tif e != nil {\n\t\twriteAPIError(w, 404, e)\n\t\treturn\n\t}\n\n\twriteAPIIcons(w, url, icons)\n}\n\nfunc lettericonHandler(w http.ResponseWriter, r *http.Request) {\n\tcharParam, col, size := lettericon.ParseIconPath(r.URL.Path)\n\tif charParam == \"\" {\n\t\twriteAPIError(w, 400, errors.New(\"wrong format for lettericons\/ path, must look like lettericons\/M-144-EFC25D.png\"))\n\t}\n\n\tw.Header().Add(contentType, imagePNG)\n\tw.Header().Add(cacheControl, fmt.Sprintf(\"max-age=%d\", oneYear))\n\tlettericon.Render(charParam, col, size, w)\n}\n\nfunc obsoleteAPIHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.FormValue(\"i_am_feeling_lucky\") == \"yes\" {\n\t\thttp.Redirect(w, r, fmt.Sprintf(\"\/icon?size=120&%s\", r.URL.RawQuery), 302)\n\t} else {\n\t\thttp.Redirect(w, r, fmt.Sprintf(\"\/allicons.json?%s\", r.URL.RawQuery), 302)\n\t}\n}\n\nfunc writeAPIError(w http.ResponseWriter, httpStatus int, e error) {\n\tdata := struct {\n\t\tError string `json:\"error\"`\n\t}{\n\t\te.Error(),\n\t}\n\trenderJSONResponse(w, httpStatus, data)\n}\n\nfunc writeAPIIcons(w http.ResponseWriter, url string, icons []besticon.Icon) {\n\t\/\/ Don't return whole image data\n\tnewIcons := []besticon.Icon{}\n\tfor _, ico := range icons {\n\t\tnewIcon := ico\n\t\tnewIcon.ImageData = nil\n\t\tnewIcons = append(newIcons, newIcon)\n\t}\n\n\tdata := &struct {\n\t\tURL   string          `json:\"url\"`\n\t\tIcons []besticon.Icon `json:\"icons\"`\n\t}{\n\t\turl,\n\t\tnewIcons,\n\t}\n\trenderJSONResponse(w, 200, data)\n}\n\nconst (\n\tcontentType     = \"Content-Type\"\n\tapplicationJSON = \"application\/json\"\n\timagePNG        = \"image\/png\"\n\tcacheControl    = \"Cache-Control\"\n)\n\nfunc renderJSONResponse(w http.ResponseWriter, httpStatus int, data interface{}) {\n\tw.Header().Add(contentType, applicationJSON)\n\tw.WriteHeader(httpStatus)\n\tenc := json.NewEncoder(w)\n\tenc.Encode(data)\n}\n\ntype pageInfo struct {\n\tURL   string\n\tIcons []besticon.Icon\n\tError error\n}\n\nfunc (pi pageInfo) Host() string {\n\tu := pi.URL\n\turl, _ := url.Parse(u)\n\tif url != nil && url.Host != \"\" {\n\t\treturn url.Host\n\t}\n\treturn pi.URL\n}\n\nfunc (pi pageInfo) Best() string {\n\tif len(pi.Icons) > 0 {\n\t\tbest := pi.Icons[0]\n\t\treturn best.URL\n\t}\n\treturn \"\"\n}\n\nfunc renderHTMLTemplate(w http.ResponseWriter, httpStatus int, templ *template.Template, data interface{}) {\n\tw.Header().Add(contentType, \"text\/html; charset=utf-8\")\n\tw.WriteHeader(httpStatus)\n\n\terr := templ.Execute(w, data)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"server: could not generate output: %s\", err)\n\t\tlogger.Print(err)\n\t\tw.Write([]byte(err.Error()))\n\t}\n}\n\nfunc startServer(port string) {\n\tregisterGzipHandler(\"\/\", indexHandler)\n\tregisterGzipHandler(\"\/icons\", iconsHandler)\n\tregisterHandler(\"\/icon\", iconHandler)\n\tregisterGzipHandler(\"\/popular\", popularHandler)\n\tregisterGzipHandler(\"\/allicons.json\", alliconsHandler)\n\tregisterHandler(\"\/lettericons\/\", lettericonHandler)\n\tregisterHandler(\"\/api\/icons\", obsoleteAPIHandler)\n\n\tserveAsset(\"\/pure-0.5.0-min.css\", \"besticon\/iconserver\/assets\/pure-0.5.0-min.css\", oneYear)\n\tserveAsset(\"\/grids-responsive-0.5.0-min.css\", \"besticon\/iconserver\/assets\/grids-responsive-0.5.0-min.css\", oneYear)\n\tserveAsset(\"\/main-min.css\", \"besticon\/iconserver\/assets\/main-min.css\", oneYear)\n\n\tserveAsset(\"\/icon.svg\", \"besticon\/iconserver\/assets\/icon.svg\", oneYear)\n\tserveAsset(\"\/favicon.ico\", \"besticon\/iconserver\/assets\/favicon.ico\", oneYear)\n\tserveAsset(\"\/apple-touch-icon.png\", \"besticon\/iconserver\/assets\/apple-touch-icon.png\", oneYear)\n\n\taddr := \"0.0.0.0:\" + port\n\tlogger.Print(\"Starting server on \", addr, \"...\")\n\te := http.ListenAndServe(addr, newLoggingMux())\n\tif e != nil {\n\t\tlogger.Fatalf(\"cannot start server: %s\\n\", e)\n\t}\n}\n\nconst (\n\toneYear = 365 * 24 * 3600\n\toneDay  = 24 * 3600\n)\n\nfunc redirectWithCacheControl(w http.ResponseWriter, r *http.Request, redirectURL string) {\n\tw.Header().Add(cacheControl, fmt.Sprintf(\"max-age=%d\", oneDay))\n\thttp.Redirect(w, r, redirectURL, 302)\n}\n\nfunc serveAsset(path string, assetPath string, maxAgeSeconds int) {\n\tregisterGzipHandler(path, func(w http.ResponseWriter, r *http.Request) {\n\t\tassetInfo, err := assets.AssetInfo(assetPath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tw.Header().Add(cacheControl, fmt.Sprintf(\"max-age=%d\", maxAgeSeconds))\n\n\t\thttp.ServeContent(w, r, assetInfo.Name(), assetInfo.ModTime(),\n\t\t\tbytes.NewReader(assets.MustAsset(assetPath)))\n\t})\n}\n\nfunc registerHandler(path string, f http.HandlerFunc) {\n\thttp.Handle(path, newExpvarHandler(path, f))\n}\n\nfunc registerGzipHandler(path string, f http.HandlerFunc) {\n\thttp.Handle(path, gziphandler.GzipHandler(newExpvarHandler(path, f)))\n}\n\nfunc main() {\n\tfmt.Printf(\"iconserver %s (%s) - https:\/\/icons.better-idea.org\\n\", besticon.VersionString, runtime.Version())\n\tport := os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\tport = \"8080\"\n\t}\n\tstartServer(port)\n}\n\nfunc init() {\n\tindexHTML = templateFromAsset(\"besticon\/iconserver\/assets\/index.html\", \"index.html\")\n\ticonsHTML = templateFromAsset(\"besticon\/iconserver\/assets\/icons.html\", \"icons.html\")\n\tpopularHTML = templateFromAsset(\"besticon\/iconserver\/assets\/popular.html\", \"popular.html\")\n\tnotFoundHTML = templateFromAsset(\"besticon\/iconserver\/assets\/not_found.html\", \"not_found.html\")\n}\n\nfunc templateFromAsset(assetPath, templateName string) *template.Template {\n\tbytes := assets.MustAsset(assetPath)\n\treturn template.Must(template.New(templateName).Funcs(funcMap).Parse(string(bytes)))\n}\n\nvar indexHTML *template.Template\nvar iconsHTML *template.Template\nvar popularHTML *template.Template\nvar notFoundHTML *template.Template\n\nvar funcMap = template.FuncMap{\n\t\"ImgWidth\": imgWidth,\n}\n\nfunc imgWidth(i *besticon.Icon) int {\n\treturn i.Width \/ 2.0\n}\n\nfunc init() {\n\tcacheSize := os.Getenv(\"CACHE_SIZE_MB\")\n\tif cacheSize == \"\" {\n\t\tbesticon.SetCacheMaxSize(32)\n\t} else {\n\t\tn, _ := strconv.Atoi(cacheSize)\n\t\tbesticon.SetCacheMaxSize(int64(n))\n\t}\n\n\tif besticon.CacheEnabled() {\n\t\texpvar.Publish(\"cacheBytes\", expvar.Func(func() interface{} { return besticon.GetCacheStats().Bytes }))\n\t\texpvar.Publish(\"cacheItems\", expvar.Func(func() interface{} { return besticon.GetCacheStats().Items }))\n\t\texpvar.Publish(\"cacheGets\", expvar.Func(func() interface{} { return besticon.GetCacheStats().Gets }))\n\t\texpvar.Publish(\"cacheHits\", expvar.Func(func() interface{} { return besticon.GetCacheStats().Hits }))\n\t\texpvar.Publish(\"cacheEvictions\", expvar.Func(func() interface{} { return besticon.GetCacheStats().Evictions }))\n\t}\n}\n<commit_msg>Enable pprof runtime profiling<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"expvar\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/NYTimes\/gziphandler\"\n\t\"github.com\/mat\/besticon\/besticon\"\n\t\"github.com\/mat\/besticon\/besticon\/iconserver\/assets\"\n\t\"github.com\/mat\/besticon\/lettericon\"\n\n\t\/\/ Enable runtime profiling at \/debug\/pprof\n\t_ \"net\/http\/pprof\"\n)\n\nfunc indexHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path == \"\" || r.URL.Path == \"\/\" {\n\t\trenderHTMLTemplate(w, 200, indexHTML, nil)\n\t} else {\n\t\trenderHTMLTemplate(w, 404, notFoundHTML, nil)\n\t}\n}\n\nfunc iconsHandler(w http.ResponseWriter, r *http.Request) {\n\turl := r.FormValue(urlParam)\n\tif len(url) == 0 {\n\t\thttp.Redirect(w, r, \"\/\", 302)\n\t\treturn\n\t}\n\n\tfinder := besticon.IconFinder{}\n\n\tformats := r.FormValue(\"formats\")\n\tif formats != \"\" {\n\t\tfinder.FormatsAllowed = strings.Split(r.FormValue(\"formats\"), \",\")\n\t}\n\n\ticons, e := finder.FetchIcons(url)\n\tswitch {\n\tcase e != nil:\n\t\trenderHTMLTemplate(w, 404, iconsHTML, pageInfo{URL: url, Error: e})\n\tcase len(icons) == 0:\n\t\terrNoIcons := errors.New(\"this poor site has no icons at all :-(\")\n\t\trenderHTMLTemplate(w, 404, iconsHTML, pageInfo{URL: url, Error: errNoIcons})\n\tdefault:\n\t\trenderHTMLTemplate(w, 200, iconsHTML, pageInfo{Icons: icons, URL: url})\n\t}\n}\n\nfunc iconHandler(w http.ResponseWriter, r *http.Request) {\n\turl := r.FormValue(\"url\")\n\tif len(url) == 0 {\n\t\twriteAPIError(w, 400, errors.New(\"need url parameter\"))\n\t\treturn\n\t}\n\n\tsize := r.FormValue(\"size\")\n\tif size == \"\" {\n\t\twriteAPIError(w, 400, errors.New(\"need size parameter\"))\n\t\treturn\n\t}\n\tminSize, err := strconv.Atoi(size)\n\tif err != nil || minSize < besticon.MinIconSize || minSize > besticon.MaxIconSize {\n\t\twriteAPIError(w, 400, errors.New(\"bad size parameter\"))\n\t\treturn\n\t}\n\n\tfinder := besticon.IconFinder{}\n\tformats := r.FormValue(\"formats\")\n\tif formats != \"\" {\n\t\tfinder.FormatsAllowed = strings.Split(r.FormValue(\"formats\"), \",\")\n\t}\n\n\tfinder.FetchIcons(url)\n\n\ticon := finder.IconWithMinSize(minSize)\n\tif icon != nil {\n\t\tredirectWithCacheControl(w, r, icon.URL)\n\t\treturn\n\t}\n\n\tfallbackIconURL := r.FormValue(\"fallback_icon_url\")\n\tif fallbackIconURL != \"\" {\n\t\tredirectWithCacheControl(w, r, fallbackIconURL)\n\t\treturn\n\t}\n\n\ticonColor := finder.MainColorForIcons()\n\tletter := lettericon.MainLetterFromURL(url)\n\tredirectPath := lettericon.IconPath(letter, size, iconColor)\n\tredirectWithCacheControl(w, r, redirectPath)\n}\n\nfunc popularHandler(w http.ResponseWriter, r *http.Request) {\n\ticonSize, err := strconv.Atoi(r.FormValue(\"iconsize\"))\n\tif iconSize > besticon.MaxIconSize || iconSize < besticon.MinIconSize || err != nil {\n\t\ticonSize = 120\n\t}\n\n\tpageInfo := struct {\n\t\tURLs        []string\n\t\tIconSize    int\n\t\tDisplaySize int\n\t}{\n\t\tbesticon.PopularSites,\n\t\ticonSize,\n\t\ticonSize \/ 2,\n\t}\n\trenderHTMLTemplate(w, 200, popularHTML, pageInfo)\n}\n\nconst (\n\turlParam = \"url\"\n)\n\nfunc alliconsHandler(w http.ResponseWriter, r *http.Request) {\n\turl := r.FormValue(urlParam)\n\tif len(url) == 0 {\n\t\terrMissingURL := errors.New(\"need url query parameter\")\n\t\twriteAPIError(w, 400, errMissingURL)\n\t\treturn\n\t}\n\n\tfinder := besticon.IconFinder{}\n\tformats := r.FormValue(\"formats\")\n\tif formats != \"\" {\n\t\tfinder.FormatsAllowed = strings.Split(r.FormValue(\"formats\"), \",\")\n\t}\n\n\ticons, e := finder.FetchIcons(url)\n\tif e != nil {\n\t\twriteAPIError(w, 404, e)\n\t\treturn\n\t}\n\n\twriteAPIIcons(w, url, icons)\n}\n\nfunc lettericonHandler(w http.ResponseWriter, r *http.Request) {\n\tcharParam, col, size := lettericon.ParseIconPath(r.URL.Path)\n\tif charParam == \"\" {\n\t\twriteAPIError(w, 400, errors.New(\"wrong format for lettericons\/ path, must look like lettericons\/M-144-EFC25D.png\"))\n\t}\n\n\tw.Header().Add(contentType, imagePNG)\n\tw.Header().Add(cacheControl, fmt.Sprintf(\"max-age=%d\", oneYear))\n\tlettericon.Render(charParam, col, size, w)\n}\n\nfunc obsoleteAPIHandler(w http.ResponseWriter, r *http.Request) {\n\tif r.FormValue(\"i_am_feeling_lucky\") == \"yes\" {\n\t\thttp.Redirect(w, r, fmt.Sprintf(\"\/icon?size=120&%s\", r.URL.RawQuery), 302)\n\t} else {\n\t\thttp.Redirect(w, r, fmt.Sprintf(\"\/allicons.json?%s\", r.URL.RawQuery), 302)\n\t}\n}\n\nfunc writeAPIError(w http.ResponseWriter, httpStatus int, e error) {\n\tdata := struct {\n\t\tError string `json:\"error\"`\n\t}{\n\t\te.Error(),\n\t}\n\trenderJSONResponse(w, httpStatus, data)\n}\n\nfunc writeAPIIcons(w http.ResponseWriter, url string, icons []besticon.Icon) {\n\t\/\/ Don't return whole image data\n\tnewIcons := []besticon.Icon{}\n\tfor _, ico := range icons {\n\t\tnewIcon := ico\n\t\tnewIcon.ImageData = nil\n\t\tnewIcons = append(newIcons, newIcon)\n\t}\n\n\tdata := &struct {\n\t\tURL   string          `json:\"url\"`\n\t\tIcons []besticon.Icon `json:\"icons\"`\n\t}{\n\t\turl,\n\t\tnewIcons,\n\t}\n\trenderJSONResponse(w, 200, data)\n}\n\nconst (\n\tcontentType     = \"Content-Type\"\n\tapplicationJSON = \"application\/json\"\n\timagePNG        = \"image\/png\"\n\tcacheControl    = \"Cache-Control\"\n)\n\nfunc renderJSONResponse(w http.ResponseWriter, httpStatus int, data interface{}) {\n\tw.Header().Add(contentType, applicationJSON)\n\tw.WriteHeader(httpStatus)\n\tenc := json.NewEncoder(w)\n\tenc.Encode(data)\n}\n\ntype pageInfo struct {\n\tURL   string\n\tIcons []besticon.Icon\n\tError error\n}\n\nfunc (pi pageInfo) Host() string {\n\tu := pi.URL\n\turl, _ := url.Parse(u)\n\tif url != nil && url.Host != \"\" {\n\t\treturn url.Host\n\t}\n\treturn pi.URL\n}\n\nfunc (pi pageInfo) Best() string {\n\tif len(pi.Icons) > 0 {\n\t\tbest := pi.Icons[0]\n\t\treturn best.URL\n\t}\n\treturn \"\"\n}\n\nfunc renderHTMLTemplate(w http.ResponseWriter, httpStatus int, templ *template.Template, data interface{}) {\n\tw.Header().Add(contentType, \"text\/html; charset=utf-8\")\n\tw.WriteHeader(httpStatus)\n\n\terr := templ.Execute(w, data)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"server: could not generate output: %s\", err)\n\t\tlogger.Print(err)\n\t\tw.Write([]byte(err.Error()))\n\t}\n}\n\nfunc startServer(port string) {\n\tregisterGzipHandler(\"\/\", indexHandler)\n\tregisterGzipHandler(\"\/icons\", iconsHandler)\n\tregisterHandler(\"\/icon\", iconHandler)\n\tregisterGzipHandler(\"\/popular\", popularHandler)\n\tregisterGzipHandler(\"\/allicons.json\", alliconsHandler)\n\tregisterHandler(\"\/lettericons\/\", lettericonHandler)\n\tregisterHandler(\"\/api\/icons\", obsoleteAPIHandler)\n\n\tserveAsset(\"\/pure-0.5.0-min.css\", \"besticon\/iconserver\/assets\/pure-0.5.0-min.css\", oneYear)\n\tserveAsset(\"\/grids-responsive-0.5.0-min.css\", \"besticon\/iconserver\/assets\/grids-responsive-0.5.0-min.css\", oneYear)\n\tserveAsset(\"\/main-min.css\", \"besticon\/iconserver\/assets\/main-min.css\", oneYear)\n\n\tserveAsset(\"\/icon.svg\", \"besticon\/iconserver\/assets\/icon.svg\", oneYear)\n\tserveAsset(\"\/favicon.ico\", \"besticon\/iconserver\/assets\/favicon.ico\", oneYear)\n\tserveAsset(\"\/apple-touch-icon.png\", \"besticon\/iconserver\/assets\/apple-touch-icon.png\", oneYear)\n\n\taddr := \"0.0.0.0:\" + port\n\tlogger.Print(\"Starting server on \", addr, \"...\")\n\te := http.ListenAndServe(addr, newLoggingMux())\n\tif e != nil {\n\t\tlogger.Fatalf(\"cannot start server: %s\\n\", e)\n\t}\n}\n\nconst (\n\toneYear = 365 * 24 * 3600\n\toneDay  = 24 * 3600\n)\n\nfunc redirectWithCacheControl(w http.ResponseWriter, r *http.Request, redirectURL string) {\n\tw.Header().Add(cacheControl, fmt.Sprintf(\"max-age=%d\", oneDay))\n\thttp.Redirect(w, r, redirectURL, 302)\n}\n\nfunc serveAsset(path string, assetPath string, maxAgeSeconds int) {\n\tregisterGzipHandler(path, func(w http.ResponseWriter, r *http.Request) {\n\t\tassetInfo, err := assets.AssetInfo(assetPath)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tw.Header().Add(cacheControl, fmt.Sprintf(\"max-age=%d\", maxAgeSeconds))\n\n\t\thttp.ServeContent(w, r, assetInfo.Name(), assetInfo.ModTime(),\n\t\t\tbytes.NewReader(assets.MustAsset(assetPath)))\n\t})\n}\n\nfunc registerHandler(path string, f http.HandlerFunc) {\n\thttp.Handle(path, newExpvarHandler(path, f))\n}\n\nfunc registerGzipHandler(path string, f http.HandlerFunc) {\n\thttp.Handle(path, gziphandler.GzipHandler(newExpvarHandler(path, f)))\n}\n\nfunc main() {\n\tfmt.Printf(\"iconserver %s (%s) - https:\/\/icons.better-idea.org\\n\", besticon.VersionString, runtime.Version())\n\tport := os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\tport = \"8080\"\n\t}\n\tstartServer(port)\n}\n\nfunc init() {\n\tindexHTML = templateFromAsset(\"besticon\/iconserver\/assets\/index.html\", \"index.html\")\n\ticonsHTML = templateFromAsset(\"besticon\/iconserver\/assets\/icons.html\", \"icons.html\")\n\tpopularHTML = templateFromAsset(\"besticon\/iconserver\/assets\/popular.html\", \"popular.html\")\n\tnotFoundHTML = templateFromAsset(\"besticon\/iconserver\/assets\/not_found.html\", \"not_found.html\")\n}\n\nfunc templateFromAsset(assetPath, templateName string) *template.Template {\n\tbytes := assets.MustAsset(assetPath)\n\treturn template.Must(template.New(templateName).Funcs(funcMap).Parse(string(bytes)))\n}\n\nvar indexHTML *template.Template\nvar iconsHTML *template.Template\nvar popularHTML *template.Template\nvar notFoundHTML *template.Template\n\nvar funcMap = template.FuncMap{\n\t\"ImgWidth\": imgWidth,\n}\n\nfunc imgWidth(i *besticon.Icon) int {\n\treturn i.Width \/ 2.0\n}\n\nfunc init() {\n\tcacheSize := os.Getenv(\"CACHE_SIZE_MB\")\n\tif cacheSize == \"\" {\n\t\tbesticon.SetCacheMaxSize(32)\n\t} else {\n\t\tn, _ := strconv.Atoi(cacheSize)\n\t\tbesticon.SetCacheMaxSize(int64(n))\n\t}\n\n\tif besticon.CacheEnabled() {\n\t\texpvar.Publish(\"cacheBytes\", expvar.Func(func() interface{} { return besticon.GetCacheStats().Bytes }))\n\t\texpvar.Publish(\"cacheItems\", expvar.Func(func() interface{} { return besticon.GetCacheStats().Items }))\n\t\texpvar.Publish(\"cacheGets\", expvar.Func(func() interface{} { return besticon.GetCacheStats().Gets }))\n\t\texpvar.Publish(\"cacheHits\", expvar.Func(func() interface{} { return besticon.GetCacheStats().Hits }))\n\t\texpvar.Publish(\"cacheEvictions\", expvar.Func(func() interface{} { return besticon.GetCacheStats().Evictions }))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package tasks\n\nimport (\n\t\"..\/..\/proto\"\n\t\"errors\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\ntype Config struct {\n\tRoot string\n}\n\ntype Task struct {\n\tSemaphore chan int\n\tConfig    *Config\n}\n\nfunc (t *Task) CompileC(args *proto.Args, resp *proto.Response) error {\n\tt.Semaphore <- 1\n\tdefer func() { <-t.Semaphore }()\n\n\tvar outfilename string\n\tif len(args.Inputs) != 1 {\n\t\treturn errors.New(\"Compile requires one file to be compiled!\")\n\t}\n\n\tif !strings.HasSuffix(args.Inputs[0].Filename, \".c\") {\n\t\toutfilename = args.Inputs[0].Filename + \".o\"\n\t} else {\n\t\toutfilename = strings.TrimSuffix(args.Inputs[0].Filename, \".c\") + \".o\"\n\t}\n\n\toutfile_path := filepath.Join(t.Config.Root, \"BINFILES\", outfilename)\n\tinfile_path := filepath.Join(t.Config.Root, args.Inputs[0].Filename)\n\n\toutput, err := exec.Command(\"gcc\", \"-std=c99\", \"-c\", \"-o\",\n\t\toutfile_path, infile_path).CombinedOutput()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = prepareResponse(outfile_path, output, args.SendContent, resp)\n\treturn err\n}\n\nfunc (t *Task) ArLink(args *proto.Args, resp *proto.Response) error {\n\tt.Semaphore <- 1\n\tdefer func() { <-t.Semaphore }()\n\n\tvar outfilename string\n\tif len(args.Inputs) < 1 {\n\t\treturn errors.New(\"Library linking requires at least one file!\")\n\t}\n\n\toutfilename = args.Name + \".a\"\n\toutdir := filepath.Join(t.Config.Root, \"BINFILES\")\n\n\toutfile_path := filepath.Join(outdir, outfilename)\n\n\tar_args := processInputs(args.Inputs, outdir, []string{\"rcs\", outfile_path})\n\n\toutput, err := exec.Command(\"ar\", ar_args...).CombinedOutput()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = prepareResponse(outfile_path, output, args.SendContent, resp)\n\treturn err\n}\n\nfunc (t *Task) LdLink(args *proto.Args, resp *proto.Response) error {\n\tt.Semaphore <- 1\n\tdefer func() { <-t.Semaphore }()\n\n\tvar outfilename string\n\tif len(args.Inputs) < 1 {\n\t\treturn errors.New(\"Application linking required at least one file!\")\n\t}\n\n\toutfilename = args.Name\n\toutdir := filepath.Join(t.Config.Root, \"BINFILES\")\n\n\toutfile_path := filepath.Join(outdir, outfilename)\n\n\tld_args := processInputs(args.Inputs, outdir, []string{\"-o\", outfile_path})\n\n\toutput, err := exec.Command(\"gcc\", ld_args...).CombinedOutput()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = prepareResponse(outfile_path, output, args.SendContent, resp)\n\treturn err\n}\n<commit_msg>worker: include .h files in CompileC inputs<commit_after>package tasks\n\nimport (\n\t\"..\/..\/proto\"\n\t\"errors\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\ntype Config struct {\n\tRoot string\n}\n\ntype Task struct {\n\tSemaphore chan int\n\tConfig    *Config\n}\n\nfunc (t *Task) CompileC(args *proto.Args, resp *proto.Response) error {\n\tt.Semaphore <- 1\n\tdefer func() { <-t.Semaphore }()\n\n\tvar outfilename string\n\tif len(args.Inputs) < 1 {\n\t\treturn errors.New(\"compile requires at least one file to be compiled\")\n\t}\n\n\tif !strings.HasSuffix(args.Inputs[0].Filename, \".c\") {\n\t\toutfilename = args.Inputs[0].Filename + \".o\"\n\t} else {\n\t\toutfilename = strings.TrimSuffix(args.Inputs[0].Filename, \".c\") + \".o\"\n\t}\n\n\toutfile_path := filepath.Join(t.Config.Root, outfilename)\n\tinfile_path := filepath.Join(t.Config.Root, args.Inputs[0].Filename)\n\n\toutput, err := exec.Command(\"gcc\", \"-std=c99\", \"-c\", \"-o\",\n\t\toutfile_path, infile_path).CombinedOutput()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = prepareResponse(outfile_path, output, args.SendContent, resp)\n\treturn err\n}\n\nfunc (t *Task) ArLink(args *proto.Args, resp *proto.Response) error {\n\tt.Semaphore <- 1\n\tdefer func() { <-t.Semaphore }()\n\n\tvar outfilename string\n\tif len(args.Inputs) < 1 {\n\t\treturn errors.New(\"library linking requires at least one file\")\n\t}\n\n\toutfilename = args.Name + \".a\"\n\toutdir := t.Config.Root\n\n\toutfile_path := filepath.Join(outdir, outfilename)\n\n\tar_args := processInputs(args.Inputs, outdir, []string{\"rcs\", outfile_path})\n\n\toutput, err := exec.Command(\"ar\", ar_args...).CombinedOutput()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = prepareResponse(outfile_path, output, args.SendContent, resp)\n\treturn err\n}\n\nfunc (t *Task) LdLink(args *proto.Args, resp *proto.Response) error {\n\tt.Semaphore <- 1\n\tdefer func() { <-t.Semaphore }()\n\n\tvar outfilename string\n\tif len(args.Inputs) < 1 {\n\t\treturn errors.New(\"application linking requires at least one file\")\n\t}\n\n\toutfilename = args.Name\n\toutdir := t.Config.Root\n\n\toutfile_path := filepath.Join(outdir, outfilename)\n\n\tld_args := processInputs(args.Inputs, outdir, []string{\"-o\", outfile_path})\n\n\toutput, err := exec.Command(\"gcc\", ld_args...).CombinedOutput()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = prepareResponse(outfile_path, output, args.SendContent, resp)\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016, RadiantBlue Technologies, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage workflow\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/venicegeo\/pz-gocommon\/elasticsearch\"\n\t\"github.com\/venicegeo\/pz-gocommon\/gocommon\"\n)\n\ntype TriggerDB struct {\n\t*ResourceDB\n\tmapping string\n}\n\nfunc NewTriggerDB(service *WorkflowService, esi elasticsearch.IIndex) (*TriggerDB, error) {\n\n\trdb, err := NewResourceDB(service, esi, TriggerIndexSettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tardb := TriggerDB{ResourceDB: rdb, mapping: TriggerDBMapping}\n\treturn &ardb, nil\n}\n\nfunc (db *TriggerDB) PostTrigger(trigger *Trigger, id piazza.Ident) (piazza.Ident, error) {\n\n\t{ \/\/CHECK SERVICE EXISTS\n\t\tjobData := trigger.Job.JobType.Data\n\t\tserviceId := jobData[\"serviceId\"]\n\t\tstrServiceId, ok := serviceId.(string)\n\t\tif !ok {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData faile: serviceId field not of type string\")\n\t\t}\n\t\tserviceControllerURL, err := db.service.sys.GetAddress(\"pz-servicecontroller\")\n\t\tif err != nil {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed to find ServiceController: %s\", err)\n\t\t}\n\t\tserviceControllerURL = \"http:\/\/\" + serviceControllerURL + \"\/service\/\" + strServiceId\n\t\treq, err := http.NewRequest(\"GET\", serviceControllerURL, nil)\n\t\tif err != nil {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed to make request to ServiceController: %s\", err)\n\t\t}\n\t\tclient := &http.Client{}\n\t\tresponse, err := client.Do(req)\n\t\tif err != nil {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed to reach ServiceController: %s\", err)\n\t\t}\n\t\tif response.StatusCode != 200 {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData: serviceId %s does not exist\", strServiceId)\n\t\t}\n\t}\n\n\tifaceObj := trigger.Condition.Query\n\t\/\/log.Printf(\"Query: %v\", ifaceObj)\n\tbody, err := json.Marshal(ifaceObj)\n\tif err != nil {\n\t\treturn piazza.NoIdent, err\n\t}\n\n\tjson := string(body)\n\t\/\/log.Printf(\"Current json: %s\", json)\n\t\/\/ Remove trailing }\n\tjson = json[:len(json)-1]\n\tjson += \",\\\"type\\\":[\"\n\t\/\/ Add the types that the percolation query can match\n\tfor _, id := range trigger.Condition.EventTypeIds {\n\t\tjson += fmt.Sprintf(\"\\\"%s\\\",\", id)\n\t}\n\tjson = json[:len(json)-1]\n\t\/\/ Add back trailing } and ] to close array\n\tjson += \"]}\"\n\n\t\/\/log.Printf(\"Posting percolation query: %s\", body)\n\tindexResult, err := db.service.eventDB.Esi.AddPercolationQuery(string(trigger.TriggerId), piazza.JsonString(body))\n\tif err != nil {\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData addpercquery failed: %s\", err)\n\t}\n\tif indexResult == nil {\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData addpercquery failed: no indexResult\")\n\t}\n\tif !indexResult.Created {\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData addpercquery failed: not created\")\n\t}\n\n\t\/\/log.Printf(\"percolation query added: ID: %s, Type: %s, Index: %s\", indexResult.Id, indexResult.Type, indexResult.Index)\n\t\/\/log.Printf(\"percolation id: %s\", indexResult.Id)\n\ttrigger.PercolationId = piazza.Ident(indexResult.Id)\n\n\tindexResult2, err := db.Esi.PostData(db.mapping, id.String(), trigger)\n\tif err != nil {\n\t\tdb.service.eventDB.Esi.DeletePercolationQuery(string(trigger.TriggerId))\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed: %s\", err)\n\t}\n\tif !indexResult2.Created {\n\t\tdb.service.eventDB.Esi.DeletePercolationQuery(string(trigger.TriggerId))\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed: not created\")\n\t}\n\n\treturn id, nil\n}\n\nfunc (db *TriggerDB) GetAll(format *piazza.JsonPagination) ([]Trigger, int64, error) {\n\ttriggers := []Trigger{}\n\n\texists := db.Esi.TypeExists(db.mapping)\n\tif !exists {\n\t\treturn triggers, 0, nil\n\t}\n\n\tsearchResult, err := db.Esi.FilterByMatchAll(db.mapping, format)\n\tif err != nil {\n\t\treturn nil, 0, LoggedError(\"TriggerDB.GetAll failed: %s\", err)\n\t}\n\tif searchResult == nil {\n\t\treturn nil, 0, LoggedError(\"TriggerDB.GetAll failed: no searchResult\")\n\t}\n\n\tif searchResult != nil && searchResult.GetHits() != nil {\n\n\t\tfor _, hit := range *searchResult.GetHits() {\n\t\t\tvar trigger Trigger\n\t\t\terr := json.Unmarshal(*hit.Source, &trigger)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\ttriggers = append(triggers, trigger)\n\t\t}\n\t}\n\treturn triggers, searchResult.TotalHits(), nil\n}\n\nfunc (db *TriggerDB) GetOne(id piazza.Ident) (*Trigger, error) {\n\n\tgetResult, err := db.Esi.GetByID(db.mapping, id.String())\n\tif err != nil {\n\t\treturn nil, LoggedError(\"TriggerDB.GetOne failed: %s\", err)\n\t}\n\tif getResult == nil {\n\t\treturn nil, LoggedError(\"TriggerDB.GetOne failed: no getResult\")\n\t}\n\n\tif !getResult.Found {\n\t\treturn nil, nil\n\t}\n\n\tsrc := getResult.Source\n\tvar obj Trigger\n\terr = json.Unmarshal(*src, &obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &obj, nil\n}\n\nfunc (db *TriggerDB) DeleteTrigger(id piazza.Ident) (bool, error) {\n\n\ttrigger, err := db.GetOne(id)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif trigger == nil {\n\t\treturn false, nil\n\t}\n\n\tdeleteResult, err := db.Esi.DeleteByID(db.mapping, string(id))\n\tif err != nil {\n\t\treturn deleteResult.Found, LoggedError(\"TriggerDB.DeleteById failed: %s\", err)\n\t}\n\tif deleteResult == nil {\n\t\treturn false, LoggedError(\"TriggerDB.DeleteById failed: no deleteResult\")\n\t}\n\tif !deleteResult.Found {\n\t\treturn false, nil\n\t}\n\n\tdeleteResult2, err := db.service.eventDB.Esi.DeletePercolationQuery(string(trigger.PercolationId))\n\tif err != nil {\n\t\treturn deleteResult2.Found, LoggedError(\"TriggerDB.DeleteById percquery failed: %s\", err)\n\t}\n\tif deleteResult2 == nil {\n\t\treturn false, LoggedError(\"TriggerDB.DeleteById percquery failed: no deleteResult\")\n\t}\n\n\treturn deleteResult2.Found, nil\n}\n<commit_msg>quick fixes to shorten code<commit_after>\/\/ Copyright 2016, RadiantBlue Technologies, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage workflow\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/venicegeo\/pz-gocommon\/elasticsearch\"\n\t\"github.com\/venicegeo\/pz-gocommon\/gocommon\"\n)\n\ntype TriggerDB struct {\n\t*ResourceDB\n\tmapping string\n}\n\nfunc NewTriggerDB(service *WorkflowService, esi elasticsearch.IIndex) (*TriggerDB, error) {\n\n\trdb, err := NewResourceDB(service, esi, TriggerIndexSettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tardb := TriggerDB{ResourceDB: rdb, mapping: TriggerDBMapping}\n\treturn &ardb, nil\n}\n\nfunc (db *TriggerDB) PostTrigger(trigger *Trigger, id piazza.Ident) (piazza.Ident, error) {\n\n\t{ \/\/CHECK SERVICE EXISTS\n\t\tjobData := trigger.Job.JobType.Data\n\t\tserviceId := jobData[\"serviceId\"]\n\t\tstrServiceId, ok := serviceId.(string)\n\t\tif !ok {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData faile: serviceId field not of type string\")\n\t\t}\n\t\tserviceControllerURL, err := db.service.sys.GetURL(\"pz-servicecontroller\")\n\t\tif err != nil {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed to find ServiceController: %s\", err)\n\t\t}\n\t\tresponse, err := http.Get(serviceControllerURL)\n\t\tif err != nil {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed to make request to ServiceController: %s\", err)\n\t\t}\n\t\tif response.StatusCode != 200 {\n\t\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData: serviceId %s does not exist\", strServiceId)\n\t\t}\n\t}\n\n\tifaceObj := trigger.Condition.Query\n\t\/\/log.Printf(\"Query: %v\", ifaceObj)\n\tbody, err := json.Marshal(ifaceObj)\n\tif err != nil {\n\t\treturn piazza.NoIdent, err\n\t}\n\n\tjson := string(body)\n\t\/\/log.Printf(\"Current json: %s\", json)\n\t\/\/ Remove trailing }\n\tjson = json[:len(json)-1]\n\tjson += \",\\\"type\\\":[\"\n\t\/\/ Add the types that the percolation query can match\n\tfor _, id := range trigger.Condition.EventTypeIds {\n\t\tjson += fmt.Sprintf(\"\\\"%s\\\",\", id)\n\t}\n\tjson = json[:len(json)-1]\n\t\/\/ Add back trailing } and ] to close array\n\tjson += \"]}\"\n\n\t\/\/log.Printf(\"Posting percolation query: %s\", body)\n\tindexResult, err := db.service.eventDB.Esi.AddPercolationQuery(string(trigger.TriggerId), piazza.JsonString(body))\n\tif err != nil {\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData addpercquery failed: %s\", err)\n\t}\n\tif indexResult == nil {\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData addpercquery failed: no indexResult\")\n\t}\n\tif !indexResult.Created {\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData addpercquery failed: not created\")\n\t}\n\n\t\/\/log.Printf(\"percolation query added: ID: %s, Type: %s, Index: %s\", indexResult.Id, indexResult.Type, indexResult.Index)\n\t\/\/log.Printf(\"percolation id: %s\", indexResult.Id)\n\ttrigger.PercolationId = piazza.Ident(indexResult.Id)\n\n\tindexResult2, err := db.Esi.PostData(db.mapping, id.String(), trigger)\n\tif err != nil {\n\t\tdb.service.eventDB.Esi.DeletePercolationQuery(string(trigger.TriggerId))\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed: %s\", err)\n\t}\n\tif !indexResult2.Created {\n\t\tdb.service.eventDB.Esi.DeletePercolationQuery(string(trigger.TriggerId))\n\t\treturn piazza.NoIdent, LoggedError(\"TriggerDB.PostData failed: not created\")\n\t}\n\n\treturn id, nil\n}\n\nfunc (db *TriggerDB) GetAll(format *piazza.JsonPagination) ([]Trigger, int64, error) {\n\ttriggers := []Trigger{}\n\n\texists := db.Esi.TypeExists(db.mapping)\n\tif !exists {\n\t\treturn triggers, 0, nil\n\t}\n\n\tsearchResult, err := db.Esi.FilterByMatchAll(db.mapping, format)\n\tif err != nil {\n\t\treturn nil, 0, LoggedError(\"TriggerDB.GetAll failed: %s\", err)\n\t}\n\tif searchResult == nil {\n\t\treturn nil, 0, LoggedError(\"TriggerDB.GetAll failed: no searchResult\")\n\t}\n\n\tif searchResult != nil && searchResult.GetHits() != nil {\n\n\t\tfor _, hit := range *searchResult.GetHits() {\n\t\t\tvar trigger Trigger\n\t\t\terr := json.Unmarshal(*hit.Source, &trigger)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, 0, err\n\t\t\t}\n\t\t\ttriggers = append(triggers, trigger)\n\t\t}\n\t}\n\treturn triggers, searchResult.TotalHits(), nil\n}\n\nfunc (db *TriggerDB) GetOne(id piazza.Ident) (*Trigger, error) {\n\n\tgetResult, err := db.Esi.GetByID(db.mapping, id.String())\n\tif err != nil {\n\t\treturn nil, LoggedError(\"TriggerDB.GetOne failed: %s\", err)\n\t}\n\tif getResult == nil {\n\t\treturn nil, LoggedError(\"TriggerDB.GetOne failed: no getResult\")\n\t}\n\n\tif !getResult.Found {\n\t\treturn nil, nil\n\t}\n\n\tsrc := getResult.Source\n\tvar obj Trigger\n\terr = json.Unmarshal(*src, &obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &obj, nil\n}\n\nfunc (db *TriggerDB) DeleteTrigger(id piazza.Ident) (bool, error) {\n\n\ttrigger, err := db.GetOne(id)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif trigger == nil {\n\t\treturn false, nil\n\t}\n\n\tdeleteResult, err := db.Esi.DeleteByID(db.mapping, string(id))\n\tif err != nil {\n\t\treturn deleteResult.Found, LoggedError(\"TriggerDB.DeleteById failed: %s\", err)\n\t}\n\tif deleteResult == nil {\n\t\treturn false, LoggedError(\"TriggerDB.DeleteById failed: no deleteResult\")\n\t}\n\tif !deleteResult.Found {\n\t\treturn false, nil\n\t}\n\n\tdeleteResult2, err := db.service.eventDB.Esi.DeletePercolationQuery(string(trigger.PercolationId))\n\tif err != nil {\n\t\treturn deleteResult2.Found, LoggedError(\"TriggerDB.DeleteById percquery failed: %s\", err)\n\t}\n\tif deleteResult2 == nil {\n\t\treturn false, LoggedError(\"TriggerDB.DeleteById percquery failed: no deleteResult\")\n\t}\n\n\treturn deleteResult2.Found, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package godbg\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\/\/ http:\/\/stackoverflow.com\/a\/23554672\/6309 https:\/\/vividcortex.com\/blog\/2013\/12\/03\/go-idiom-package-and-object\/\n\/\/ you design a type with methods as usual, and then you also place matching functions at the package level itself.\n\/\/ These functions simply delegate to a default instance of the type that’s a private package-level variable, created in an init() function.\n\n\/\/ Pdbg allows to print debug message with indent and function name added\ntype Pdbg struct {\n\tbout     *bytes.Buffer\n\tberr     *bytes.Buffer\n\tsout     *bufio.Writer\n\tserr     *bufio.Writer\n\tbreaks   []string\n\texcludes []string\n\tskips    []string\n}\n\n\/\/ Out returns a writer for normal messages.\n\/\/ By default, os.StdOut\nfunc Out() io.Writer {\n\treturn pdbg.Out()\n}\n\n\/\/ Out returns a writer for normal messages for a given pdbg instance.\n\/\/ By default, os.StdOut\nfunc (pdbg *Pdbg) Out() io.Writer {\n\tif pdbg.sout == nil {\n\t\treturn os.Stdout\n\t}\n\treturn pdbg.sout\n}\n\n\/\/ Err returns a writer for error messages.\n\/\/ By default, os.StdErr\nfunc Err() io.Writer {\n\treturn pdbg.Err()\n}\n\n\/\/ Err returns a writer for error messages for a given pdbg instance.\n\/\/ By default, os.StdErr\nfunc (pdbg *Pdbg) Err() io.Writer {\n\tif pdbg.serr == nil {\n\t\treturn os.Stderr\n\t}\n\treturn pdbg.serr\n}\n\n\/\/ global pdbg used for printing\nvar pdbg = NewPdbg()\n\n\/\/ Option set an option for a Pdbg\n\/\/ http:\/\/dave.cheney.net\/2014\/10\/17\/functional-options-for-friendly-apis\ntype Option func(*Pdbg)\n\n\/\/ SetBuffers is an option for replacing stdout and stderr by\n\/\/ bytes buffers (in a bufio.Writer).\n\/\/ If apdbg is nil, set for the global pdbg instance\nfunc SetBuffers(apdbg *Pdbg) {\n\tif apdbg == nil {\n\t\tapdbg = pdbg\n\t}\n\tapdbg.bout = bytes.NewBuffer(nil)\n\tapdbg.sout = bufio.NewWriter(apdbg.bout)\n\tapdbg.berr = bytes.NewBuffer(nil)\n\tapdbg.serr = bufio.NewWriter(apdbg.berr)\n}\n\n\/\/ SetExcludes set excludes on a pdbg (nil for global pdbg)\nfunc (pdbg *Pdbg) SetExcludes(excludes []string) {\n\tpdbg.excludes = excludes\n}\n\n\/\/ OptExcludes is an option to set excludes at the creation of a pdbg\nfunc OptExcludes(excludes []string) Option {\n\treturn func(apdbg *Pdbg) {\n\t\tapdbg.SetExcludes(excludes)\n\t}\n}\n\n\/\/ SetExcludes set skips on a pdbg (nil for global pdbg)\nfunc (pdbg *Pdbg) SetSkips(skips []string) {\n\tsk := []string{\"\/godbg.go'\"}\n\tsk = append(sk, skips...)\n\tpdbg.skips = sk\n}\n\n\/\/ OptExcludes is an option to set excludes at the creation of a pdbg\nfunc OptSkips(skips []string) Option {\n\treturn func(apdbg *Pdbg) {\n\t\tapdbg.SetSkips(skips)\n\t}\n}\n\n\/\/ NewPdbg creates a PDbg instance, with options\nfunc NewPdbg(options ...Option) *Pdbg {\n\tnewpdbg := &Pdbg{}\n\tfor _, option := range options {\n\t\toption(newpdbg)\n\t}\n\tnewpdbg.breaks = append(newpdbg.breaks, \"smartystreets\")\n\t\/\/newpdbg.breaks = append(newpdbg.breaks, \"(*Pdbg).Pdbgf\")\n\tnewpdbg.skips = append(newpdbg.skips, \"\/godbg.go'\")\n\treturn newpdbg\n}\n\n\/\/ ResetIOs reset the out and err buffer of global pdbg instance\nfunc ResetIOs() {\n\tpdbg.ResetIOs()\n}\n\n\/\/ ResetIOs reset the out and err buffer\n\/\/ (unless they were the default stdout and stderr,\n\/\/ in which case it does nothing)\nfunc (pdbg *Pdbg) ResetIOs() {\n\tif pdbg.sout != nil {\n\t\tpdbg.bout = bytes.NewBuffer(nil)\n\t\tpdbg.sout.Reset(pdbg.bout)\n\t\tpdbg.berr = bytes.NewBuffer(nil)\n\t\tpdbg.serr.Reset(pdbg.berr)\n\t}\n}\n\n\/\/ OutString returns the string for out messages for the global pdbg instance.\n\/\/ It flushes the out buffer.\n\/\/ If out is set to os.Stdout, returns an empty string\nfunc OutString() string {\n\treturn pdbg.OutString()\n}\n\n\/\/ OutString returns the string for out messages for a given pdbg instance.\n\/\/ It flushes the out buffer.\n\/\/ If out is set to os.Stdout, returns an empty string\nfunc (pdbg *Pdbg) OutString() string {\n\tif pdbg.sout == nil {\n\t\treturn \"\"\n\t}\n\tpdbg.sout.Flush()\n\treturn pdbg.bout.String()\n}\n\n\/\/ ErrString returns the string for error messages for the global pdbg instance.\n\/\/ It flushes the err buffer.\n\/\/ If err is set to os.StdErr, returns an empty string\nfunc ErrString() string {\n\treturn pdbg.ErrString()\n}\n\n\/\/ ErrString returns the string for error messages for a given pdbg instance.\n\/\/ It flushes the err buffer.\n\/\/ If err is set to os.StdErr, returns an empty string\nfunc (pdbg *Pdbg) ErrString() string {\n\tif pdbg.serr == nil {\n\t\treturn \"\"\n\t}\n\tpdbg.serr.Flush()\n\treturn pdbg.berr.String()\n}\n\nfunc (pdbg *Pdbg) pdbgExcluded(dbg string) bool {\n\tfor _, e := range pdbg.excludes {\n\t\tif strings.Contains(dbg, e) {\n\t\t\t\/\/ fmt.Printf(\"EXCLUDE over '%v' including '%v'\\n\", dbg, e) \/\/ DBG\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (pdbg *Pdbg) pdbgBreak(dbg string) bool {\n\tfor _, b := range pdbg.breaks {\n\t\tif strings.Contains(dbg, b) {\n\t\t\t\/\/ fmt.Printf(\"BREAK over '%v' including '%v'\\n\", dbg, b) \/\/ DBG\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (pdbg *Pdbg) pdbgSkip(dbg string) (bool, int) {\n\tdepthToAdd := 0\n\tfor i, s := range pdbg.skips {\n\t\tif strings.Contains(dbg, s) {\n\t\t\tif i > 0 {\n\t\t\t\tdepthToAdd = 1\n\t\t\t}\n\t\t\t\/\/ fmt.Printf(\"SKIP over '%v' including '%v'\\n\", dbg, s) \/\/ DBG\n\t\t\treturn true, depthToAdd\n\t\t}\n\t}\n\treturn false, depthToAdd\n}\n\n\/\/ Pdbgf uses global Pdbg variable for printing strings, with indent and function name\nfunc Pdbgf(format string, args ...interface{}) string {\n\treturn pdbg.Pdbgf(format, args...)\n}\n\ntype caller func(skip int) (pc uintptr, file string, line int, ok bool)\n\nvar mycaller = runtime.Caller\n\n\/\/ Pdbgf uses custom Pdbg variable for printing strings, with indent and function name\nfunc (pdbg *Pdbg) Pdbgf(format string, args ...interface{}) string {\n\tmsg := fmt.Sprintf(format+\"\\n\", args...)\n\tmsg = strings.TrimSpace(msg)\n\n\tpmsg := \"\"\n\tdepth := 0\n\tnbskip := 0\n\tnbInitialSkips := 0\n\tfirst := true\n\taddOneForSkip := 0\n\t\/\/ fmt.Printf(\"~~~~~~~~~~~~~~~~~~~~~~\\n\") \/\/ DBG\n\tfor ok := true; ok; {\n\t\tpc, file, line, ok := mycaller(depth)\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tfname := runtime.FuncForPC(pc).Name()\n\t\tfline := fmt.Sprintf(\"Name of function: '%v': '%+x' (line %v): file '%v'\\n\", fname, fname, line, file)\n\t\t\/\/ fmt.Println(fline) \/\/ DBG\n\t\tif pdbg.pdbgExcluded(fline) {\n\t\t\tdepth = depth + 1\n\t\t\tif first {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif pdbg.pdbgBreak(fline) {\n\t\t\tbreak\n\t\t}\n\t\tif isSkipped, depthToAdd := pdbg.pdbgSkip(fline); isSkipped {\n\t\t\tdepth = depth + 1\n\t\t\tnbskip = nbskip + 1\n\t\t\taddOneForSkip = addOneForSkip + depthToAdd\n\t\t\tcontinue\n\t\t}\n\t\tfnamerx1 := regexp.MustCompile(`.*\\.func[^a-zA-Z0-9]`)\n\t\tfname = fnamerx1.ReplaceAllString(fname, \"func.\")\n\t\tfnamerx2 := regexp.MustCompile(`.*\/`)\n\t\tfname = fnamerx2.ReplaceAllString(fname, \"\")\n\t\tif !strings.HasPrefix(fname, \"func.\") {\n\t\t\tfnamerx3 := regexp.MustCompile(`^.*?\\.`)\n\t\t\t\/\/ fmt.Printf(\"fname before: '%v'\", fname)\n\t\t\tfname = fnamerx3.ReplaceAllString(fname, \"\")\n\t\t\t\/\/ fmt.Printf(\" => fname after: '%v'\\n\", fname)\n\t\t\tfnamerx4 := regexp.MustCompile(`[\\(\\)]`)\n\t\t\tfname = fnamerx4.ReplaceAllString(fname, \"\")\n\t\t}\n\t\tdbg := fname + \":\" + fmt.Sprintf(\"%d\", line)\n\t\tif first {\n\t\t\t\/\/ fmt.Printf(\" => nbskip '%v'; addOneForSkip '%v'\\n\", nbskip, addOneForSkip) \/\/ DBG\n\t\t\tnbInitialSkips = nbskip - addOneForSkip\n\t\t\tpmsg = \"[\" + dbg + \"]\"\n\t\t} else {\n\t\t\tpmsg = pmsg + \" (\" + dbg + \")\"\n\t\t}\n\t\tfirst = false\n\t\tdepth = depth + 1\n\t}\n\tfinalDepth := depth\n\tdepth = finalDepth - nbInitialSkips - 1\n\n\tspaces := \"\"\n\tif depth >= 0 {\n\t\tspaces = strings.Repeat(\" \", depth*2)\n\t}\n\t\/\/ fmt.Printf(\"spaces '%s', finalDepth '%d', depth '%d', nbInitialSkips '%d', addOneForSkip='%d'\\n\", spaces, finalDepth, depth, nbInitialSkips, addOneForSkip) \/\/ DBG\n\tres := pmsg\n\tif pmsg != \"\" {\n\t\tpmsg = spaces + pmsg + \"\\n\"\n\t}\n\tmsg = pmsg + spaces + \"  \" + msg + \"\\n\"\n\t\/\/ fmt.Printf(\"==> MSG '%v'\\n\", msg) \/\/ DBG\n\tfmt.Fprint(pdbg.Err(), fmt.Sprint(msg))\n\treturn res\n}\n<commit_msg>Fix comment on OptSkips<commit_after>package godbg\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strings\"\n)\n\n\/\/ http:\/\/stackoverflow.com\/a\/23554672\/6309 https:\/\/vividcortex.com\/blog\/2013\/12\/03\/go-idiom-package-and-object\/\n\/\/ you design a type with methods as usual, and then you also place matching functions at the package level itself.\n\/\/ These functions simply delegate to a default instance of the type that’s a private package-level variable, created in an init() function.\n\n\/\/ Pdbg allows to print debug message with indent and function name added\ntype Pdbg struct {\n\tbout     *bytes.Buffer\n\tberr     *bytes.Buffer\n\tsout     *bufio.Writer\n\tserr     *bufio.Writer\n\tbreaks   []string\n\texcludes []string\n\tskips    []string\n}\n\n\/\/ Out returns a writer for normal messages.\n\/\/ By default, os.StdOut\nfunc Out() io.Writer {\n\treturn pdbg.Out()\n}\n\n\/\/ Out returns a writer for normal messages for a given pdbg instance.\n\/\/ By default, os.StdOut\nfunc (pdbg *Pdbg) Out() io.Writer {\n\tif pdbg.sout == nil {\n\t\treturn os.Stdout\n\t}\n\treturn pdbg.sout\n}\n\n\/\/ Err returns a writer for error messages.\n\/\/ By default, os.StdErr\nfunc Err() io.Writer {\n\treturn pdbg.Err()\n}\n\n\/\/ Err returns a writer for error messages for a given pdbg instance.\n\/\/ By default, os.StdErr\nfunc (pdbg *Pdbg) Err() io.Writer {\n\tif pdbg.serr == nil {\n\t\treturn os.Stderr\n\t}\n\treturn pdbg.serr\n}\n\n\/\/ global pdbg used for printing\nvar pdbg = NewPdbg()\n\n\/\/ Option set an option for a Pdbg\n\/\/ http:\/\/dave.cheney.net\/2014\/10\/17\/functional-options-for-friendly-apis\ntype Option func(*Pdbg)\n\n\/\/ SetBuffers is an option for replacing stdout and stderr by\n\/\/ bytes buffers (in a bufio.Writer).\n\/\/ If apdbg is nil, set for the global pdbg instance\nfunc SetBuffers(apdbg *Pdbg) {\n\tif apdbg == nil {\n\t\tapdbg = pdbg\n\t}\n\tapdbg.bout = bytes.NewBuffer(nil)\n\tapdbg.sout = bufio.NewWriter(apdbg.bout)\n\tapdbg.berr = bytes.NewBuffer(nil)\n\tapdbg.serr = bufio.NewWriter(apdbg.berr)\n}\n\n\/\/ SetExcludes set excludes on a pdbg (nil for global pdbg)\nfunc (pdbg *Pdbg) SetExcludes(excludes []string) {\n\tpdbg.excludes = excludes\n}\n\n\/\/ OptExcludes is an option to set excludes at the creation of a pdbg\nfunc OptExcludes(excludes []string) Option {\n\treturn func(apdbg *Pdbg) {\n\t\tapdbg.SetExcludes(excludes)\n\t}\n}\n\n\/\/ SetExcludes set skips on a pdbg (nil for global pdbg)\nfunc (pdbg *Pdbg) SetSkips(skips []string) {\n\tsk := []string{\"\/godbg.go'\"}\n\tsk = append(sk, skips...)\n\tpdbg.skips = sk\n}\n\n\/\/ OptSkips is an option to set excludes at the creation of a pdbg\nfunc OptSkips(skips []string) Option {\n\treturn func(apdbg *Pdbg) {\n\t\tapdbg.SetSkips(skips)\n\t}\n}\n\n\/\/ NewPdbg creates a PDbg instance, with options\nfunc NewPdbg(options ...Option) *Pdbg {\n\tnewpdbg := &Pdbg{}\n\tfor _, option := range options {\n\t\toption(newpdbg)\n\t}\n\tnewpdbg.breaks = append(newpdbg.breaks, \"smartystreets\")\n\t\/\/newpdbg.breaks = append(newpdbg.breaks, \"(*Pdbg).Pdbgf\")\n\tnewpdbg.skips = append(newpdbg.skips, \"\/godbg.go'\")\n\treturn newpdbg\n}\n\n\/\/ ResetIOs reset the out and err buffer of global pdbg instance\nfunc ResetIOs() {\n\tpdbg.ResetIOs()\n}\n\n\/\/ ResetIOs reset the out and err buffer\n\/\/ (unless they were the default stdout and stderr,\n\/\/ in which case it does nothing)\nfunc (pdbg *Pdbg) ResetIOs() {\n\tif pdbg.sout != nil {\n\t\tpdbg.bout = bytes.NewBuffer(nil)\n\t\tpdbg.sout.Reset(pdbg.bout)\n\t\tpdbg.berr = bytes.NewBuffer(nil)\n\t\tpdbg.serr.Reset(pdbg.berr)\n\t}\n}\n\n\/\/ OutString returns the string for out messages for the global pdbg instance.\n\/\/ It flushes the out buffer.\n\/\/ If out is set to os.Stdout, returns an empty string\nfunc OutString() string {\n\treturn pdbg.OutString()\n}\n\n\/\/ OutString returns the string for out messages for a given pdbg instance.\n\/\/ It flushes the out buffer.\n\/\/ If out is set to os.Stdout, returns an empty string\nfunc (pdbg *Pdbg) OutString() string {\n\tif pdbg.sout == nil {\n\t\treturn \"\"\n\t}\n\tpdbg.sout.Flush()\n\treturn pdbg.bout.String()\n}\n\n\/\/ ErrString returns the string for error messages for the global pdbg instance.\n\/\/ It flushes the err buffer.\n\/\/ If err is set to os.StdErr, returns an empty string\nfunc ErrString() string {\n\treturn pdbg.ErrString()\n}\n\n\/\/ ErrString returns the string for error messages for a given pdbg instance.\n\/\/ It flushes the err buffer.\n\/\/ If err is set to os.StdErr, returns an empty string\nfunc (pdbg *Pdbg) ErrString() string {\n\tif pdbg.serr == nil {\n\t\treturn \"\"\n\t}\n\tpdbg.serr.Flush()\n\treturn pdbg.berr.String()\n}\n\nfunc (pdbg *Pdbg) pdbgExcluded(dbg string) bool {\n\tfor _, e := range pdbg.excludes {\n\t\tif strings.Contains(dbg, e) {\n\t\t\t\/\/ fmt.Printf(\"EXCLUDE over '%v' including '%v'\\n\", dbg, e) \/\/ DBG\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (pdbg *Pdbg) pdbgBreak(dbg string) bool {\n\tfor _, b := range pdbg.breaks {\n\t\tif strings.Contains(dbg, b) {\n\t\t\t\/\/ fmt.Printf(\"BREAK over '%v' including '%v'\\n\", dbg, b) \/\/ DBG\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (pdbg *Pdbg) pdbgSkip(dbg string) (bool, int) {\n\tdepthToAdd := 0\n\tfor i, s := range pdbg.skips {\n\t\tif strings.Contains(dbg, s) {\n\t\t\tif i > 0 {\n\t\t\t\tdepthToAdd = 1\n\t\t\t}\n\t\t\t\/\/ fmt.Printf(\"SKIP over '%v' including '%v'\\n\", dbg, s) \/\/ DBG\n\t\t\treturn true, depthToAdd\n\t\t}\n\t}\n\treturn false, depthToAdd\n}\n\n\/\/ Pdbgf uses global Pdbg variable for printing strings, with indent and function name\nfunc Pdbgf(format string, args ...interface{}) string {\n\treturn pdbg.Pdbgf(format, args...)\n}\n\ntype caller func(skip int) (pc uintptr, file string, line int, ok bool)\n\nvar mycaller = runtime.Caller\n\n\/\/ Pdbgf uses custom Pdbg variable for printing strings, with indent and function name\nfunc (pdbg *Pdbg) Pdbgf(format string, args ...interface{}) string {\n\tmsg := fmt.Sprintf(format+\"\\n\", args...)\n\tmsg = strings.TrimSpace(msg)\n\n\tpmsg := \"\"\n\tdepth := 0\n\tnbskip := 0\n\tnbInitialSkips := 0\n\tfirst := true\n\taddOneForSkip := 0\n\t\/\/ fmt.Printf(\"~~~~~~~~~~~~~~~~~~~~~~\\n\") \/\/ DBG\n\tfor ok := true; ok; {\n\t\tpc, file, line, ok := mycaller(depth)\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\tfname := runtime.FuncForPC(pc).Name()\n\t\tfline := fmt.Sprintf(\"Name of function: '%v': '%+x' (line %v): file '%v'\\n\", fname, fname, line, file)\n\t\t\/\/ fmt.Println(fline) \/\/ DBG\n\t\tif pdbg.pdbgExcluded(fline) {\n\t\t\tdepth = depth + 1\n\t\t\tif first {\n\t\t\t\treturn \"\"\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif pdbg.pdbgBreak(fline) {\n\t\t\tbreak\n\t\t}\n\t\tif isSkipped, depthToAdd := pdbg.pdbgSkip(fline); isSkipped {\n\t\t\tdepth = depth + 1\n\t\t\tnbskip = nbskip + 1\n\t\t\taddOneForSkip = addOneForSkip + depthToAdd\n\t\t\tcontinue\n\t\t}\n\t\tfnamerx1 := regexp.MustCompile(`.*\\.func[^a-zA-Z0-9]`)\n\t\tfname = fnamerx1.ReplaceAllString(fname, \"func.\")\n\t\tfnamerx2 := regexp.MustCompile(`.*\/`)\n\t\tfname = fnamerx2.ReplaceAllString(fname, \"\")\n\t\tif !strings.HasPrefix(fname, \"func.\") {\n\t\t\tfnamerx3 := regexp.MustCompile(`^.*?\\.`)\n\t\t\t\/\/ fmt.Printf(\"fname before: '%v'\", fname)\n\t\t\tfname = fnamerx3.ReplaceAllString(fname, \"\")\n\t\t\t\/\/ fmt.Printf(\" => fname after: '%v'\\n\", fname)\n\t\t\tfnamerx4 := regexp.MustCompile(`[\\(\\)]`)\n\t\t\tfname = fnamerx4.ReplaceAllString(fname, \"\")\n\t\t}\n\t\tdbg := fname + \":\" + fmt.Sprintf(\"%d\", line)\n\t\tif first {\n\t\t\t\/\/ fmt.Printf(\" => nbskip '%v'; addOneForSkip '%v'\\n\", nbskip, addOneForSkip) \/\/ DBG\n\t\t\tnbInitialSkips = nbskip - addOneForSkip\n\t\t\tpmsg = \"[\" + dbg + \"]\"\n\t\t} else {\n\t\t\tpmsg = pmsg + \" (\" + dbg + \")\"\n\t\t}\n\t\tfirst = false\n\t\tdepth = depth + 1\n\t}\n\tfinalDepth := depth\n\tdepth = finalDepth - nbInitialSkips - 1\n\n\tspaces := \"\"\n\tif depth >= 0 {\n\t\tspaces = strings.Repeat(\" \", depth*2)\n\t}\n\t\/\/ fmt.Printf(\"spaces '%s', finalDepth '%d', depth '%d', nbInitialSkips '%d', addOneForSkip='%d'\\n\", spaces, finalDepth, depth, nbInitialSkips, addOneForSkip) \/\/ DBG\n\tres := pmsg\n\tif pmsg != \"\" {\n\t\tpmsg = spaces + pmsg + \"\\n\"\n\t}\n\tmsg = pmsg + spaces + \"  \" + msg + \"\\n\"\n\t\/\/ fmt.Printf(\"==> MSG '%v'\\n\", msg) \/\/ DBG\n\tfmt.Fprint(pdbg.Err(), fmt.Sprint(msg))\n\treturn res\n}\n<|endoftext|>"}
{"text":"<commit_before>package golds\n\nconst version = \"0.0.0\"\n\n\/\/ Container basic interface for all collections\ntype Container interface {\n\t\/\/ Size returns amount of elements inside a collection\n\tSize() int\n\n\t\/\/ IsEmpty returns true if collection is empty\n\tIsEmpty() bool\n\n\t\/\/ Clear removes all elements from the collection\n\tClear()\n}\n\n\/\/ Comparable is an interface for comparable items\n\/\/ contains only one method Less, which return true\n\/\/ if an element is less than given\ntype Comparable interface {\n\tLess(Comparable) bool\n}\n<commit_msg>add CmpFunc<commit_after>package golds\n\n\/\/ Container basic interface for all collections\ntype Container interface {\n\t\/\/ Size returns amount of elements inside a collection\n\tSize() int\n\n\t\/\/ IsEmpty returns true if collection is empty\n\tIsEmpty() bool\n\n\t\/\/ Clear removes all elements from the collection\n\tClear()\n}\n\n\/\/ CmpFunc returns true if a is greater then b.\ntype CmpFunc func(a, b interface{}) bool\n<|endoftext|>"}
{"text":"<commit_before>package golog\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype GoLogger struct {\n\tMutex         sync.Mutex\n\tInfoLogger    *log.Logger\n\tWarningLogger *log.Logger\n\tErrorLogger   *log.Logger\n\tFatalLogger   *log.Logger\n\tDebugLogger   *log.Logger\n}\n\nfunc getStack(all bool) []string {\n\tbuf := make([]byte, 1<<8)\n\tfor {\n\t\tn := runtime.Stack(buf, all)\n\t\tif n < len(buf) {\n\t\t\tbreak\n\t\t}\n\t\tbuf = make([]byte, len(buf)*2)\n\t}\n\treturn strings.Split(string(buf), \"\\n\")\n}\n\nfunc NewGoLogger(output *os.File) *GoLogger {\n\tlogger := new(GoLogger)\n\n\tlogger.InfoLogger = log.New(output, \"[ INFO  ]\", log.LstdFlags)\n\tlogger.WarningLogger = log.New(output, \"[WARNING]\", log.LstdFlags)\n\tlogger.ErrorLogger = log.New(output, \"[ ERROR ]\", log.LstdFlags)\n\tlogger.FatalLogger = log.New(output, \"[ FATAL ]\", log.LstdFlags)\n\tlogger.DebugLogger = log.New(output, \"[ DEBUG ]\", log.LstdFlags)\n\n\treturn logger\n}\n\nfunc (l *GoLogger) Infoln(v ...interface{}) {\n\tl.Mutex.Lock()\n\tl.InfoLogger.Println(v...)\n\tl.Mutex.Unlock()\n}\n\nfunc (l *GoLogger) Infof(format string, v ...interface{}) {\n\tl.Infoln(fmt.Sprintf(format, v...))\n}\n\nfunc (l *GoLogger) Warningln(v ...interface{}) {\n\tl.Mutex.Lock()\n\tl.WarningLogger.Println(v...)\n\tl.Mutex.Unlock()\n}\n\nfunc (l *GoLogger) Warningf(format string, v ...interface{}) {\n\tl.Warningln(fmt.Sprintf(format, v...))\n}\n\nfunc (l *GoLogger) errorln(v ...interface{}) {\n\t_, file, line, _ := runtime.Caller(2)\n\tcaller := fmt.Sprintf(\"%s:%d\", filepath.Base(file), line)\n\tv = append([]interface{}{caller}, v...)\n\tl.Mutex.Lock()\n\tl.ErrorLogger.Println(v...)\n\tl.Mutex.Unlock()\n}\n\nfunc (l *GoLogger) Errorln(v ...interface{}) {\n\tl.errorln(v...)\n}\n\nfunc (l *GoLogger) Errorf(format string, v ...interface{}) {\n\tl.errorln(fmt.Sprintf(format, v...))\n}\n\nfunc (l *GoLogger) Fatalln(v ...interface{}) {\n\tl.Mutex.Lock()\n\tl.FatalLogger.Println(v...)\n\tfor _, v := range getStack(false) {\n\t\tl.FatalLogger.Println(v)\n\t}\n\tl.Mutex.Unlock()\n\tos.Exit(1)\n}\n\nfunc (l *GoLogger) Fatalf(format string, v ...interface{}) {\n\tl.Fatalln(fmt.Sprintf(format, v...))\n}\n\nfunc (l *GoLogger) Debugln(debug bool, v ...interface{}) {\n\tif debug {\n\t\tl.Mutex.Lock()\n\t\tl.DebugLogger.Println(v...)\n\t\tl.Mutex.Unlock()\n\t}\n}\n\nfunc (l *GoLogger) Debugf(debug bool, format string, v ...interface{}) {\n\tl.Debugln(debug, fmt.Sprintf(format, v...))\n}\n<commit_msg>show file:line when calling debug<commit_after>package golog\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"sync\"\n)\n\ntype GoLogger struct {\n\tMutex         sync.Mutex\n\tInfoLogger    *log.Logger\n\tWarningLogger *log.Logger\n\tErrorLogger   *log.Logger\n\tFatalLogger   *log.Logger\n\tDebugLogger   *log.Logger\n}\n\nfunc getStack(all bool) []string {\n\tbuf := make([]byte, 1<<8)\n\tfor {\n\t\tn := runtime.Stack(buf, all)\n\t\tif n < len(buf) {\n\t\t\tbreak\n\t\t}\n\t\tbuf = make([]byte, len(buf)*2)\n\t}\n\treturn strings.Split(string(buf), \"\\n\")\n}\n\nfunc NewGoLogger(output *os.File) *GoLogger {\n\tlogger := new(GoLogger)\n\n\tlogger.InfoLogger = log.New(output, \"[ INFO  ]\", log.LstdFlags)\n\tlogger.WarningLogger = log.New(output, \"[WARNING]\", log.LstdFlags)\n\tlogger.ErrorLogger = log.New(output, \"[ ERROR ]\", log.LstdFlags)\n\tlogger.FatalLogger = log.New(output, \"[ FATAL ]\", log.LstdFlags)\n\tlogger.DebugLogger = log.New(output, \"[ DEBUG ]\", log.LstdFlags)\n\n\treturn logger\n}\n\nfunc (l *GoLogger) Infoln(v ...interface{}) {\n\tl.Mutex.Lock()\n\tl.InfoLogger.Println(v...)\n\tl.Mutex.Unlock()\n}\n\nfunc (l *GoLogger) Infof(format string, v ...interface{}) {\n\tl.Infoln(fmt.Sprintf(format, v...))\n}\n\nfunc (l *GoLogger) Warningln(v ...interface{}) {\n\tl.Mutex.Lock()\n\tl.WarningLogger.Println(v...)\n\tl.Mutex.Unlock()\n}\n\nfunc (l *GoLogger) Warningf(format string, v ...interface{}) {\n\tl.Warningln(fmt.Sprintf(format, v...))\n}\n\nfunc (l *GoLogger) errorln(v ...interface{}) {\n\t_, file, line, _ := runtime.Caller(2)\n\tcaller := fmt.Sprintf(\"%s:%d\", filepath.Base(file), line)\n\tv = append([]interface{}{caller}, v...)\n\tl.Mutex.Lock()\n\tl.ErrorLogger.Println(v...)\n\tl.Mutex.Unlock()\n}\n\nfunc (l *GoLogger) Errorln(v ...interface{}) {\n\tl.errorln(v...)\n}\n\nfunc (l *GoLogger) Errorf(format string, v ...interface{}) {\n\tl.errorln(fmt.Sprintf(format, v...))\n}\n\nfunc (l *GoLogger) Fatalln(v ...interface{}) {\n\tl.Mutex.Lock()\n\tl.FatalLogger.Println(v...)\n\tfor _, v := range getStack(false) {\n\t\tl.FatalLogger.Println(v)\n\t}\n\tl.Mutex.Unlock()\n\tos.Exit(1)\n}\n\nfunc (l *GoLogger) Fatalf(format string, v ...interface{}) {\n\tl.Fatalln(fmt.Sprintf(format, v...))\n}\n\nfunc (l *GoLogger) debugln(v ...interface{}) {\n\t_, file, line, _ := runtime.Caller(2)\n\tcaller := fmt.Sprintf(\"%s:%d\", filepath.Base(file), line)\n\tv = append([]interface{}{caller}, v...)\n\tl.Mutex.Lock()\n\tl.DebugLogger.Println(v...)\n\tl.Mutex.Unlock()\n}\n\nfunc (l *GoLogger) Debugln(debug bool, v ...interface{}) {\n\tif !debug {\n\t\treturn\n\t}\n\tl.debugln(v...)\n}\n\nfunc (l *GoLogger) Debugf(debug bool, format string, v ...interface{}) {\n\tif !debug {\n\t\treturn\n\t}\n\tl.debugln(fmt.Sprintf(format, v...))\n}\n<|endoftext|>"}
{"text":"<commit_before>package gopla\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"github.com\/PuerkitoBio\/goquery\"\n\t\"github.com\/headzoo\/surf\"\n\t\"github.com\/tidwall\/gjson\"\n)\n\nfunc init() {\n\n}\n\n\/\/VideoStream has actual video file data\ntype VideoStream struct {\n\tURL     string\n\tBitrate string\n\tFormat  string\n\tSize    string\n\tQuality string\n}\n\n\/\/VideoData has all information about video page\ntype VideoData struct {\n\tTitle       string\n\tDescription string\n\tThumbnails  []string\n\tDuration    string\n\tHash        string\n\tVideos      VideoStreams\n}\n\n\/\/SearchData has all information from search page\ntype SearchData struct {\n\tTitle       string\n\tDescription string\n\tID          string\n\tDate        string\n\tImage       string\n\tURL         string\n\tHash        string\n\tType        string\n}\n\n\/\/SearchDatas ...\ntype SearchDatas []SearchData\n\n\/\/VideoDatas ..\ntype VideoDatas []VideoData\n\n\/\/VideoStreams ..\ntype VideoStreams []VideoStream\n\nfunc (slice VideoStreams) Len() int {\n\treturn len(slice)\n}\n\nfunc (slice VideoStreams) Less(i, j int) bool {\n\tvar s1, _ = strconv.Atoi(slice[i].Size)\n\tvar s2, _ = strconv.Atoi(slice[j].Size)\n\treturn s1 < s2\n}\n\nfunc (slice VideoStreams) Swap(i, j int) {\n\tslice[i], slice[j] = slice[j], slice[i]\n}\n\nfunc getJSON(url string) gjson.Result {\n\tclient := &http.Client{}\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"User-Agent\", \"Mozilla\")\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\tjson, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvar jsonR = gjson.Parse(string(json))\n\treturn jsonR\n}\n\n\/\/GetAllHashes returns all video hashes from given search\nfunc GetAllHashes(id string, name string) []string {\n\tvar link = fmt.Sprintf(\"https:\/\/seeker.redefine.pl\/ipla\/multi.json?free=1&page=1&platform=www_ipla_tv&portal_id=ipla&query=%s&category_ids%%5B%%5D=%s&size=5000&sort=recent&sound=&top_category=\", url.QueryEscape(name), url.QueryEscape(id))\n\tfmt.Println(link)\n\tvar jsonR = getJSON(link)\n\tvar data []string\n\tfor _, v := range jsonR.Array() {\n\t\tdata = append(data, v.Get(\"media_id\").String())\n\t}\n\treturn data\n}\n\n\/\/FindVideo finds the material and returns informations about it\nfunc FindVideo(name string, category string) SearchDatas {\n\tvar link = fmt.Sprintf(\"https:\/\/seeker.redefine.pl\/ipla\/multi.json?free=1&page=1&platform=www_ipla_tv&portal_id=ipla&query=%s&size=150&sort=recent&sound=&top_category=%s\", url.QueryEscape(name), category)\n\tvar jsonR = getJSON(link)\n\t\/\/fmt.Println(link)\n\n\tif len(jsonR.Array()) == 0 {\n\t\treturn nil\n\t}\n\tvar data SearchDatas\n\tfor _, v := range jsonR.Array() {\n\n\t\tdata = append(data, SearchData{\n\t\t\tID:          v.Get(\"id\").String(),\n\t\t\tDescription: v.Get(\"description\").String(),\n\t\t\tTitle:       v.Get(\"title\").String(),\n\t\t\tDate:        v.Get(\"created_date\").String(),\n\t\t\tImage:       v.Get(\"image\").String(),\n\t\t\tURL:         fmt.Sprintf(\"http:\/\/www.ipla.tv\/kategoria\/%s\", v.Get(\"id\").String()),\n\t\t\tHash:        v.Get(\"media_id\").String(),\n\t\t\tType:        v.Get(\"_type\").String(),\n\t\t})\n\n\t}\n\treturn data\n}\n\n\/\/GetHash returns playvod| link from http link\nfunc GetHash(link string) string {\n\tbow := surf.NewBrowser()\n\tbow.AddRequestHeader(\"Accept\", \"text\/html\")\n\tbow.AddRequestHeader(\"Accept-Charset\", \"utf8\")\n\tbow.AddRequestHeader(\"User-Agent\", \"Mozilla\")\n\terr := bow.Open(link)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tbow.Find(\"a.start-watch\").Each(func(_ int, s *goquery.Selection) {\n\t\tlink, _ = s.Attr(\"href\")\n\n\t\tre := regexp.MustCompile(\"^ipla:\/\/playvod-1\\\\|([a-f0-9]{16})\")\n\t\tlink = re.ReplaceAllString(link, \"$1\")\n\t})\n\treturn link\n}\n\n\/\/GetVideo returns VideoStream object with basic link informations\nfunc GetVideo(hash string) VideoData {\n\n\tvar jsonR = getJSON(\"http:\/\/getmedia.redefine.pl\/vods\/get_vod\/?cpid=1&ua=mipla\/23&media_id=\" + hash)\n\tvar data = VideoData{\n\t\tHash:        hash,\n\t\tTitle:       jsonR.Get(\"vod.title\").String(),\n\t\tDescription: jsonR.Get(\"vod.text\").String(),\n\t\tDuration:    jsonR.Get(\"vod.duration\").String(),\n\t\tVideos:      VideoStreams{},\n\t}\n\n\tjsonR.Get(\"vod.copies\").ForEach(func(key gjson.Result, value gjson.Result) bool {\n\n\t\tdata.Videos = append(data.Videos, VideoStream{\n\t\t\tURL:     value.Get(\"url\").String(),\n\t\t\tBitrate: value.Get(\"bitrate\").String(),\n\t\t\tFormat:  value.Get(\"format\").String(),\n\t\t\tQuality: value.Get(\"quality_p\").String(),\n\t\t\tSize:    value.Get(\"size\").String(),\n\t\t})\n\t\treturn true\n\t})\n\n\treturn data\n}\n<commit_msg>Remove debug print<commit_after>package gopla\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"github.com\/PuerkitoBio\/goquery\"\n\t\"github.com\/headzoo\/surf\"\n\t\"github.com\/tidwall\/gjson\"\n)\n\nfunc init() {\n\n}\n\n\/\/VideoStream has actual video file data\ntype VideoStream struct {\n\tURL     string\n\tBitrate string\n\tFormat  string\n\tSize    string\n\tQuality string\n}\n\n\/\/VideoData has all information about video page\ntype VideoData struct {\n\tTitle       string\n\tDescription string\n\tThumbnails  []string\n\tDuration    string\n\tHash        string\n\tVideos      VideoStreams\n}\n\n\/\/SearchData has all information from search page\ntype SearchData struct {\n\tTitle       string\n\tDescription string\n\tID          string\n\tDate        string\n\tImage       string\n\tURL         string\n\tHash        string\n\tType        string\n}\n\n\/\/SearchDatas ...\ntype SearchDatas []SearchData\n\n\/\/VideoDatas ..\ntype VideoDatas []VideoData\n\n\/\/VideoStreams ..\ntype VideoStreams []VideoStream\n\nfunc (slice VideoStreams) Len() int {\n\treturn len(slice)\n}\n\nfunc (slice VideoStreams) Less(i, j int) bool {\n\tvar s1, _ = strconv.Atoi(slice[i].Size)\n\tvar s2, _ = strconv.Atoi(slice[j].Size)\n\treturn s1 < s2\n}\n\nfunc (slice VideoStreams) Swap(i, j int) {\n\tslice[i], slice[j] = slice[j], slice[i]\n}\n\nfunc getJSON(url string) gjson.Result {\n\tclient := &http.Client{}\n\n\treq, err := http.NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Set(\"User-Agent\", \"Mozilla\")\n\tres, err := client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer res.Body.Close()\n\tjson, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvar jsonR = gjson.Parse(string(json))\n\treturn jsonR\n}\n\n\/\/GetAllHashes returns all video hashes from given search\nfunc GetAllHashes(id string, name string) []string {\n\tvar link = fmt.Sprintf(\"https:\/\/seeker.redefine.pl\/ipla\/multi.json?free=1&page=1&platform=www_ipla_tv&portal_id=ipla&query=%s&category_ids%%5B%%5D=%s&size=5000&sort=recent&sound=&top_category=\", url.QueryEscape(name), url.QueryEscape(id))\n\t\/\/fmt.Println(link)\n\tvar jsonR = getJSON(link)\n\tvar data []string\n\tfor _, v := range jsonR.Array() {\n\t\tdata = append(data, v.Get(\"media_id\").String())\n\t}\n\treturn data\n}\n\n\/\/FindVideo finds the material and returns informations about it\nfunc FindVideo(name string, category string) SearchDatas {\n\tvar link = fmt.Sprintf(\"https:\/\/seeker.redefine.pl\/ipla\/multi.json?free=1&page=1&platform=www_ipla_tv&portal_id=ipla&query=%s&size=150&sort=recent&sound=&top_category=%s\", url.QueryEscape(name), category)\n\tvar jsonR = getJSON(link)\n\t\/\/fmt.Println(link)\n\n\tif len(jsonR.Array()) == 0 {\n\t\treturn nil\n\t}\n\tvar data SearchDatas\n\tfor _, v := range jsonR.Array() {\n\n\t\tdata = append(data, SearchData{\n\t\t\tID:          v.Get(\"id\").String(),\n\t\t\tDescription: v.Get(\"description\").String(),\n\t\t\tTitle:       v.Get(\"title\").String(),\n\t\t\tDate:        v.Get(\"created_date\").String(),\n\t\t\tImage:       v.Get(\"image\").String(),\n\t\t\tURL:         fmt.Sprintf(\"http:\/\/www.ipla.tv\/kategoria\/%s\", v.Get(\"id\").String()),\n\t\t\tHash:        v.Get(\"media_id\").String(),\n\t\t\tType:        v.Get(\"_type\").String(),\n\t\t})\n\n\t}\n\treturn data\n}\n\n\/\/GetHash returns playvod| link from http link\nfunc GetHash(link string) string {\n\tbow := surf.NewBrowser()\n\tbow.AddRequestHeader(\"Accept\", \"text\/html\")\n\tbow.AddRequestHeader(\"Accept-Charset\", \"utf8\")\n\tbow.AddRequestHeader(\"User-Agent\", \"Mozilla\")\n\terr := bow.Open(link)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tbow.Find(\"a.start-watch\").Each(func(_ int, s *goquery.Selection) {\n\t\tlink, _ = s.Attr(\"href\")\n\n\t\tre := regexp.MustCompile(\"^ipla:\/\/playvod-1\\\\|([a-f0-9]{16})\")\n\t\tlink = re.ReplaceAllString(link, \"$1\")\n\t})\n\treturn link\n}\n\n\/\/GetVideo returns VideoStream object with basic link informations\nfunc GetVideo(hash string) VideoData {\n\n\tvar jsonR = getJSON(\"http:\/\/getmedia.redefine.pl\/vods\/get_vod\/?cpid=1&ua=mipla\/23&media_id=\" + hash)\n\tvar data = VideoData{\n\t\tHash:        hash,\n\t\tTitle:       jsonR.Get(\"vod.title\").String(),\n\t\tDescription: jsonR.Get(\"vod.text\").String(),\n\t\tDuration:    jsonR.Get(\"vod.duration\").String(),\n\t\tVideos:      VideoStreams{},\n\t}\n\n\tjsonR.Get(\"vod.copies\").ForEach(func(key gjson.Result, value gjson.Result) bool {\n\n\t\tdata.Videos = append(data.Videos, VideoStream{\n\t\t\tURL:     value.Get(\"url\").String(),\n\t\t\tBitrate: value.Get(\"bitrate\").String(),\n\t\t\tFormat:  value.Get(\"format\").String(),\n\t\t\tQuality: value.Get(\"quality_p\").String(),\n\t\t\tSize:    value.Get(\"size\").String(),\n\t\t})\n\t\treturn true\n\t})\n\n\treturn data\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package grace allows for gracefully waiting for a listener to\n\/\/ finish serving it's active requests.\npackage grace\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\nvar (\n\t\/\/ This error is returned by Inherits() when we're not inheriting any fds.\n\tErrNotInheriting = errors.New(\"no inherited listeners\")\n\n\t\/\/ This error is returned by Listener.Accept() when Close is in progress.\n\tErrAlreadyClosed = errors.New(\"already closed\")\n\n\t\/\/ Time in the past to trigger immediate deadline.\n\ttimeInPast = time.Date(1983, time.November, 6, 0, 0, 0, 0, time.UTC)\n)\n\nconst (\n\t\/\/ Used to indicate a graceful restart in the new process.\n\tenvCountKey = \"LISTEN_FDS\"\n\n\t\/\/ The error returned by the standard library when the socket is closed.\n\terrClosed = \"use of closed network connection\"\n)\n\n\/\/ A Listener providing a graceful Close process and can be sent\n\/\/ across processes using the underlying File descriptor.\ntype Listener interface {\n\tnet.Listener\n\n\t\/\/ Will return the underlying file representing this Listener.\n\tFile() (f *os.File, err error)\n}\n\ntype listener struct {\n\tListener\n\tclosed      bool\n\tclosedMutex sync.RWMutex\n\twg          sync.WaitGroup\n}\n\n\/\/ Allows for us to notice when the connection is closed.\ntype conn struct {\n\tnet.Conn\n\twg *sync.WaitGroup\n}\n\nfunc (c conn) Close() error {\n\tdefer c.wg.Done()\n\treturn c.Conn.Close()\n}\n\n\/\/ Wraps an existing File listener to provide a graceful Close() process.\nfunc NewListener(l Listener) Listener {\n\treturn &listener{Listener: l}\n}\n\nfunc (l *listener) Close() error {\n\tl.closedMutex.Lock()\n\tl.closed = true\n\tl.closedMutex.Unlock()\n\n\tvar err error\n\t\/\/ Init provided sockets dont actually close so we trigger Accept to return\n\t\/\/ by setting the deadline.\n\tif os.Getppid() == 1 {\n\t\tif ld, ok := l.Listener.(interface {\n\t\t\tSetDeadline(t time.Time) error\n\t\t}); ok {\n\t\t\tld.SetDeadline(timeInPast)\n\t\t} else {\n\t\t\tfmt.Fprintln(os.Stderr, \"init activated server did not have SetDeadline\")\n\t\t}\n\t} else {\n\t\terr = l.Listener.Close()\n\t}\n\tl.wg.Wait()\n\treturn err\n}\n\nfunc (l *listener) Accept() (c net.Conn, err error) {\n\t\/\/ Presume we'll accept and decrement in defer if we don't. If we did this\n\t\/\/ after a successful accept we would have a race condition where we may end\n\t\/\/ up incorrectly shutting down between the time we do a successful accept\n\t\/\/ and the increment.\n\tl.wg.Add(1)\n\tdefer func() {\n\t\t\/\/ If we didn't accept, we decrement our presumptuous count above.\n\t\tif c == nil {\n\t\t\tl.wg.Done()\n\t\t}\n\t}()\n\n\tl.closedMutex.RLock()\n\tif l.closed {\n\t\tl.closedMutex.RUnlock()\n\t\treturn nil, ErrAlreadyClosed\n\t}\n\tl.closedMutex.RUnlock()\n\n\tc, err = l.Listener.Accept()\n\tif err != nil {\n\t\tif strings.HasSuffix(err.Error(), errClosed) {\n\t\t\treturn nil, ErrAlreadyClosed\n\t\t}\n\n\t\t\/\/ We use SetDeadline above to trigger Accept to return when we're trying\n\t\t\/\/ to handoff to a child as part of our restart process. In this scenario\n\t\t\/\/ we want to treat the timeout the same as a Close.\n\t\tif nerr, ok := err.(net.Error); ok && nerr.Timeout() {\n\t\t\tl.closedMutex.RLock()\n\t\t\tif l.closed {\n\t\t\t\tl.closedMutex.RUnlock()\n\t\t\t\treturn nil, ErrAlreadyClosed\n\t\t\t}\n\t\t\tl.closedMutex.RUnlock()\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn conn{Conn: c, wg: &l.wg}, nil\n}\n\n\/\/ Wait for signals to gracefully terminate or restart the process.\nfunc Wait(listeners []Listener) (err error) {\n\tch := make(chan os.Signal, 2)\n\tsignal.Notify(ch, syscall.SIGTERM, syscall.SIGUSR2)\n\tfor {\n\t\tsig := <-ch\n\t\tswitch sig {\n\t\tcase syscall.SIGTERM:\n\t\t\tvar wg sync.WaitGroup\n\t\t\twg.Add(len(listeners))\n\t\t\tfor _, l := range listeners {\n\t\t\t\tgo func(l Listener) {\n\t\t\t\t\tcErr := l.Close()\n\t\t\t\t\tif cErr != nil {\n\t\t\t\t\t\terr = cErr\n\t\t\t\t\t}\n\t\t\t\t\twg.Done()\n\t\t\t\t}(l)\n\t\t\t}\n\t\t\twg.Wait()\n\t\t\treturn\n\t\tcase syscall.SIGUSR2:\n\t\t\trErr := Restart(listeners)\n\t\t\tif rErr != nil {\n\t\t\t\treturn rErr\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Try to inherit listeners from the parent process.\nfunc Inherit() (listeners []Listener, err error) {\n\tcountStr := os.Getenv(envCountKey)\n\tif countStr == \"\" {\n\t\treturn nil, ErrNotInheriting\n\t}\n\tcount, err := strconv.Atoi(countStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ If we are inheriting, the listeners will begin at fd 3\n\tfor i := 3; i < 3+count; i++ {\n\t\tfile := os.NewFile(uintptr(i), \"listener\")\n\t\ttmp, err := net.FileListener(file)\n\t\tfile.Close()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tl := tmp.(*net.TCPListener)\n\t\tlisteners = append(listeners, NewListener(l))\n\t}\n\treturn\n}\n\n\/\/ Start the Close process in the parent. This does not wait for the\n\/\/ parent to close and simply sends it the TERM signal.\nfunc CloseParent() error {\n\tppid := os.Getppid()\n\tif ppid == 1 { \/\/ init provided sockets, for example systemd\n\t\treturn nil\n\t}\n\treturn syscall.Kill(ppid, syscall.SIGTERM)\n}\n\n\/\/ Restart the process passing the given listeners to the new process.\nfunc Restart(listeners []Listener) (err error) {\n\tif len(listeners) == 0 {\n\t\treturn errors.New(\"restart must be given listeners.\")\n\t}\n\tfiles := make([]*os.File, len(listeners))\n\tfor i, l := range listeners {\n\t\tfiles[i], err = l.File()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer files[i].Close()\n\t\tsyscall.CloseOnExec(int(files[i].Fd()))\n\t}\n\targv0, err := exec.LookPath(os.Args[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\tallFiles := append([]*os.File{os.Stdin, os.Stdout, os.Stderr}, files...)\n\tallFiles = append(allFiles, nil)\n\t_, err = os.StartProcess(argv0, os.Args, &os.ProcAttr{\n\t\tDir:   wd,\n\t\tEnv:   append(os.Environ(), fmt.Sprintf(\"%s=%d\", envCountKey, len(files))),\n\t\tFiles: allFiles,\n\t})\n\treturn err\n}\n<commit_msg>move inline interface out for readability<commit_after>\/\/ Package grace allows for gracefully waiting for a listener to\n\/\/ finish serving it's active requests.\npackage grace\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\nvar (\n\t\/\/ This error is returned by Inherits() when we're not inheriting any fds.\n\tErrNotInheriting = errors.New(\"no inherited listeners\")\n\n\t\/\/ This error is returned by Listener.Accept() when Close is in progress.\n\tErrAlreadyClosed = errors.New(\"already closed\")\n\n\t\/\/ Time in the past to trigger immediate deadline.\n\ttimeInPast = time.Date(1983, time.November, 6, 0, 0, 0, 0, time.UTC)\n)\n\nconst (\n\t\/\/ Used to indicate a graceful restart in the new process.\n\tenvCountKey = \"LISTEN_FDS\"\n\n\t\/\/ The error returned by the standard library when the socket is closed.\n\terrClosed = \"use of closed network connection\"\n)\n\n\/\/ A Listener providing a graceful Close process and can be sent\n\/\/ across processes using the underlying File descriptor.\ntype Listener interface {\n\tnet.Listener\n\n\t\/\/ Will return the underlying file representing this Listener.\n\tFile() (f *os.File, err error)\n}\n\ntype listener struct {\n\tListener\n\tclosed      bool\n\tclosedMutex sync.RWMutex\n\twg          sync.WaitGroup\n}\n\ntype deadliner interface {\n\tSetDeadline(t time.Time) error\n}\n\n\/\/ Allows for us to notice when the connection is closed.\ntype conn struct {\n\tnet.Conn\n\twg *sync.WaitGroup\n}\n\nfunc (c conn) Close() error {\n\tdefer c.wg.Done()\n\treturn c.Conn.Close()\n}\n\n\/\/ Wraps an existing File listener to provide a graceful Close() process.\nfunc NewListener(l Listener) Listener {\n\treturn &listener{Listener: l}\n}\n\nfunc (l *listener) Close() error {\n\tl.closedMutex.Lock()\n\tl.closed = true\n\tl.closedMutex.Unlock()\n\n\tvar err error\n\t\/\/ Init provided sockets dont actually close so we trigger Accept to return\n\t\/\/ by setting the deadline.\n\tif os.Getppid() == 1 {\n\t\tif ld, ok := l.Listener.(deadliner); ok {\n\t\t\tld.SetDeadline(timeInPast)\n\t\t} else {\n\t\t\tfmt.Fprintln(os.Stderr, \"init activated server did not have SetDeadline\")\n\t\t}\n\t} else {\n\t\terr = l.Listener.Close()\n\t}\n\tl.wg.Wait()\n\treturn err\n}\n\nfunc (l *listener) Accept() (c net.Conn, err error) {\n\t\/\/ Presume we'll accept and decrement in defer if we don't. If we did this\n\t\/\/ after a successful accept we would have a race condition where we may end\n\t\/\/ up incorrectly shutting down between the time we do a successful accept\n\t\/\/ and the increment.\n\tl.wg.Add(1)\n\tdefer func() {\n\t\t\/\/ If we didn't accept, we decrement our presumptuous count above.\n\t\tif c == nil {\n\t\t\tl.wg.Done()\n\t\t}\n\t}()\n\n\tl.closedMutex.RLock()\n\tif l.closed {\n\t\tl.closedMutex.RUnlock()\n\t\treturn nil, ErrAlreadyClosed\n\t}\n\tl.closedMutex.RUnlock()\n\n\tc, err = l.Listener.Accept()\n\tif err != nil {\n\t\tif strings.HasSuffix(err.Error(), errClosed) {\n\t\t\treturn nil, ErrAlreadyClosed\n\t\t}\n\n\t\t\/\/ We use SetDeadline above to trigger Accept to return when we're trying\n\t\t\/\/ to handoff to a child as part of our restart process. In this scenario\n\t\t\/\/ we want to treat the timeout the same as a Close.\n\t\tif nerr, ok := err.(net.Error); ok && nerr.Timeout() {\n\t\t\tl.closedMutex.RLock()\n\t\t\tif l.closed {\n\t\t\t\tl.closedMutex.RUnlock()\n\t\t\t\treturn nil, ErrAlreadyClosed\n\t\t\t}\n\t\t\tl.closedMutex.RUnlock()\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn conn{Conn: c, wg: &l.wg}, nil\n}\n\n\/\/ Wait for signals to gracefully terminate or restart the process.\nfunc Wait(listeners []Listener) (err error) {\n\tch := make(chan os.Signal, 2)\n\tsignal.Notify(ch, syscall.SIGTERM, syscall.SIGUSR2)\n\tfor {\n\t\tsig := <-ch\n\t\tswitch sig {\n\t\tcase syscall.SIGTERM:\n\t\t\tvar wg sync.WaitGroup\n\t\t\twg.Add(len(listeners))\n\t\t\tfor _, l := range listeners {\n\t\t\t\tgo func(l Listener) {\n\t\t\t\t\tcErr := l.Close()\n\t\t\t\t\tif cErr != nil {\n\t\t\t\t\t\terr = cErr\n\t\t\t\t\t}\n\t\t\t\t\twg.Done()\n\t\t\t\t}(l)\n\t\t\t}\n\t\t\twg.Wait()\n\t\t\treturn\n\t\tcase syscall.SIGUSR2:\n\t\t\trErr := Restart(listeners)\n\t\t\tif rErr != nil {\n\t\t\t\treturn rErr\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Try to inherit listeners from the parent process.\nfunc Inherit() (listeners []Listener, err error) {\n\tcountStr := os.Getenv(envCountKey)\n\tif countStr == \"\" {\n\t\treturn nil, ErrNotInheriting\n\t}\n\tcount, err := strconv.Atoi(countStr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ If we are inheriting, the listeners will begin at fd 3\n\tfor i := 3; i < 3+count; i++ {\n\t\tfile := os.NewFile(uintptr(i), \"listener\")\n\t\ttmp, err := net.FileListener(file)\n\t\tfile.Close()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tl := tmp.(*net.TCPListener)\n\t\tlisteners = append(listeners, NewListener(l))\n\t}\n\treturn\n}\n\n\/\/ Start the Close process in the parent. This does not wait for the\n\/\/ parent to close and simply sends it the TERM signal.\nfunc CloseParent() error {\n\tppid := os.Getppid()\n\tif ppid == 1 { \/\/ init provided sockets, for example systemd\n\t\treturn nil\n\t}\n\treturn syscall.Kill(ppid, syscall.SIGTERM)\n}\n\n\/\/ Restart the process passing the given listeners to the new process.\nfunc Restart(listeners []Listener) (err error) {\n\tif len(listeners) == 0 {\n\t\treturn errors.New(\"restart must be given listeners.\")\n\t}\n\tfiles := make([]*os.File, len(listeners))\n\tfor i, l := range listeners {\n\t\tfiles[i], err = l.File()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer files[i].Close()\n\t\tsyscall.CloseOnExec(int(files[i].Fd()))\n\t}\n\targv0, err := exec.LookPath(os.Args[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\tallFiles := append([]*os.File{os.Stdin, os.Stdout, os.Stderr}, files...)\n\tallFiles = append(allFiles, nil)\n\t_, err = os.StartProcess(argv0, os.Args, &os.ProcAttr{\n\t\tDir:   wd,\n\t\tEnv:   append(os.Environ(), fmt.Sprintf(\"%s=%d\", envCountKey, len(files))),\n\t\tFiles: allFiles,\n\t})\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package store4\n\nimport (\n\t\"bytes\"\n\t\"sort\"\n)\n\n\/\/ TripleCallbackFn is the function signature used to implement\n\/\/ callback functions that receive a triple.\n\/\/\n\/\/ Used with calls to Graph's ForEach and ForEachWith.\ntype TripleCallbackFn func(s, p, o string)\n\n\/\/ TripleTestFn is the function signature used to implement\n\/\/ callback functions performing triple tests.\n\/\/ A response of true means that the test has been passed.\n\/\/\n\/\/ Used with calls to Graph's Every, EveryWith, Some and SomeWith.\ntype TripleTestFn func(s, p, o string) bool\n\n\/\/ Graph is a convenience façade that simply\n\/\/ proxies calls to its associated QuadStore.\ntype Graph struct {\n\tName      string\n\tQuadStore *QuadStore\n}\n\n\/\/ Graph returns a proxy-façade that provides a triple-based API for working with graphs within the store.\nfunc (s *QuadStore) Graph(name string) *Graph {\n\treturn &Graph{\n\t\tName:      name,\n\t\tQuadStore: s,\n\t}\n}\n\n\/\/ NewGraph returns an unnamed graph with a\n\/\/ newly created QuadStore as its backing.\nfunc NewGraph() *Graph {\n\treturn NewQuadStore().Graph(\"\")\n}\n\nfunc adaptTripleCallbackFn(fn TripleCallbackFn) QuadCallbackFn {\n\treturn func(s, p, o, g string) {\n\t\tfn(s, p, o)\n\t}\n}\n\nfunc adaptTripleTestFn(fn TripleTestFn) QuadTestFn {\n\treturn func(s, p, o, g string) bool {\n\t\treturn fn(s, p, o)\n\t}\n}\n\n\/\/ Add a triple to the graph.\n\/\/ Returns true if the triple was a new triple,\n\/\/ or false if the triple already existed.\n\/\/\n\/\/ If any of the given terms are \"*\" (an asterisk),\n\/\/ then this method will panic. (The asterisk is reserved\n\/\/ for wildcard operations throughout the API).\nfunc (g *Graph) Add(subject, predicate, object string) bool {\n\treturn g.QuadStore.Add(subject, predicate, object, g.Name)\n}\n\n\/\/ Count returns a count of triples in the graph that match the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) Count(subject, predicate, object string) uint64 {\n\treturn g.QuadStore.Count(subject, predicate, object, g.Name)\n}\n\n\/\/ Every tests whether all triples in the graph pass the test\n\/\/ implemented by the given function.\n\/\/\n\/\/ The given callback is\n\/\/ executed once for each triple present in the graph until\n\/\/ Every finds one where the callback returns false. If such\n\/\/ an element is found, iteration is immediately halted and\n\/\/ Every returns false. Otherwise, if the callback returns\n\/\/ true for all triples, then Every returns true.\n\/\/\n\/\/ Acting like the 'for all' quantifier in maths, it should\n\/\/ be noted that Every returns true for an empty graph.\nfunc (g *Graph) Every(fn TripleTestFn) bool {\n\treturn g.QuadStore.EveryWith(\"*\", \"*\", \"*\", g.Name, adaptTripleTestFn(fn))\n}\n\n\/\/ EveryWith tests whether all triples in the graph that match the\n\/\/ given terms pass the test implemented by the given function.\n\/\/\n\/\/ The given callback is\n\/\/ executed once for each matching triple in the graph until\n\/\/ EveryWith finds one where the callback returns false. If such\n\/\/ an element is found, iteration is immediately halted and\n\/\/ EveryWith returns false. Otherwise, if the callback returns\n\/\/ true for all triples, then EveryWith returns true.\n\/\/\n\/\/ Acting like the 'for all' quantifier in maths, it should\n\/\/ be noted that EveryWith returns true for an empty graph.\n\/\/ By extension, if the given parameters cause the iteration\n\/\/ set to be empty, then EveryWith also returns true.\nfunc (g *Graph) EveryWith(subject, predicate, object string, fn TripleTestFn) bool {\n\treturn g.QuadStore.EveryWith(subject, predicate, object, g.Name, adaptTripleTestFn(fn))\n}\n\n\/\/ FindObjects returns a list of distinct object terms for all triples in the graph that match the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) FindObjects(subject, predicate string) []string {\n\treturn g.QuadStore.FindObjects(subject, predicate, g.Name)\n}\n\n\/\/ FindPredicates returns a list of distinct predicate terms for all triples in the graph that match the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) FindPredicates(subject, object string) []string {\n\treturn g.QuadStore.FindPredicates(subject, object, g.Name)\n}\n\n\/\/ FindSubjects returns a list of distinct subject terms for all triples in the graph that match the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) FindSubjects(predicate, object string) []string {\n\treturn g.QuadStore.FindSubjects(predicate, object, g.Name)\n}\n\n\/\/ ForEach executes the given callback once for each triple in the graph.\nfunc (g *Graph) ForEach(fn TripleCallbackFn) {\n\tg.QuadStore.ForEachWith(\"*\", \"*\", \"*\", g.Name, adaptTripleCallbackFn(fn))\n}\n\n\/\/ ForEachWith executes the given callback once for each triple in the graph\n\/\/ that matches the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) ForEachWith(subject, predicate, object string, fn TripleCallbackFn) {\n\tg.QuadStore.ForEachWith(subject, predicate, object, g.Name, adaptTripleCallbackFn(fn))\n}\n\n\/\/ ForObjects executes the given callback once for each distinct object term\n\/\/ for all triples in the graph that match the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) ForObjects(subject, predicate string, fn StringCallbackFn) {\n\tg.QuadStore.ForObjects(subject, predicate, g.Name, fn)\n}\n\n\/\/ ForPredicates executes the given callback once for each distinct predicate term\n\/\/ for all triples in the graph that graph the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) ForPredicates(subject, object string, fn StringCallbackFn) {\n\tg.QuadStore.ForPredicates(subject, object, g.Name, fn)\n}\n\n\/\/ ForSubjects executes the given callback once for each distinct subject term\n\/\/ for all triples in the graph that match the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) ForSubjects(predicate, object string, fn StringCallbackFn) {\n\tg.QuadStore.ForSubjects(predicate, object, g.Name, fn)\n}\n\n\/\/ Removes triples from the graph. Returns true if triples were removed,\n\/\/ or false if no matching triples exist.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) Remove(subject, predicate, object string) bool {\n\treturn g.QuadStore.Remove(subject, predicate, object, g.Name)\n}\n\n\/\/ Size returns the total count of triples in the graph.\nfunc (g *Graph) Size() uint64 {\n\tgimpl, ok := g.QuadStore.graphs[g.Name]\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn gimpl.size\n}\n\n\/\/ Some tests whether some triple in the graph passes the test\n\/\/ implemented by the given function.\n\/\/\n\/\/ The given callback is\n\/\/ executed once for each triple present in the graph until\n\/\/ Some finds one where the callback returns true. If such\n\/\/ an element is found, iteration is immediately halted and\n\/\/ Some returns true. Otherwise, if the callback returns\n\/\/ false for all triples, then Some returns false.\nfunc (g *Graph) Some(fn TripleTestFn) bool {\n\treturn g.QuadStore.SomeWith(\"*\", \"*\", \"*\", g.Name, adaptTripleTestFn(fn))\n}\n\n\/\/ SomeWith tests whether some triple matching the given pattern\n\/\/ passes the test implemented by the given function.\n\/\/\n\/\/ The given callback is\n\/\/ executed once for each triple matching the given pattern until\n\/\/ SomeWith finds one where the callback returns true. If such\n\/\/ an element is found, iteration is immediately halted and\n\/\/ SomeWith returns true. Otherwise, if the callback returns\n\/\/ false for all triples, then SomeWith returns false.\nfunc (g *Graph) SomeWith(subject, predicate, object string, fn TripleTestFn) bool {\n\treturn g.QuadStore.SomeWith(subject, predicate, object, g.Name, adaptTripleTestFn(fn))\n}\n\n\/\/ String returns the contents of the graph in a human-readable format.\nfunc (g *Graph) String() string {\n\tvar buf bytes.Buffer\n\tname := g.Name\n\tif len(name) > 0 {\n\t\tbuf.WriteString(name)\n\t\tbuf.WriteByte('\\n')\n\t}\n\tsubjects := g.FindSubjects(\"*\", \"*\")\n\tsort.Strings(subjects)\n\tfor _, subject := range subjects {\n\t\tpredicates := g.FindPredicates(subject, \"*\")\n\t\tsort.Strings(predicates)\n\t\tfor _, predicate := range predicates {\n\t\t\tobjects := g.FindObjects(subject, predicate)\n\t\t\tsort.Strings(objects)\n\t\t\tfor _, object := range objects {\n\t\t\t\tbuf.WriteByte('[')\n\t\t\t\tbuf.WriteString(subject)\n\t\t\t\tbuf.WriteByte(' ')\n\t\t\t\tbuf.WriteString(predicate)\n\t\t\t\tbuf.WriteByte(' ')\n\t\t\t\tbuf.WriteString(object)\n\t\t\t\tbuf.WriteByte(']')\n\t\t\t\tbuf.WriteByte('\\n')\n\t\t\t}\n\t\t}\n\t}\n\treturn buf.String()\n}\n<commit_msg>Make NewGraph take initialisation data<commit_after>package store4\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"sort\"\n)\n\n\/\/ TripleCallbackFn is the function signature used to implement\n\/\/ callback functions that receive a triple.\n\/\/\n\/\/ Used with calls to Graph's ForEach and ForEachWith.\ntype TripleCallbackFn func(s, p, o string)\n\n\/\/ TripleTestFn is the function signature used to implement\n\/\/ callback functions performing triple tests.\n\/\/ A response of true means that the test has been passed.\n\/\/\n\/\/ Used with calls to Graph's Every, EveryWith, Some and SomeWith.\ntype TripleTestFn func(s, p, o string) bool\n\n\/\/ Graph is a convenience façade that simply\n\/\/ proxies calls to its associated QuadStore.\ntype Graph struct {\n\tName      string\n\tQuadStore *QuadStore\n}\n\n\/\/ Graph returns a proxy-façade that provides a triple-based API for working with graphs within the store.\nfunc (s *QuadStore) Graph(name string) *Graph {\n\treturn &Graph{\n\t\tName:      name,\n\t\tQuadStore: s,\n\t}\n}\n\n\/\/ NewGraph returns an unnamed graph with a\n\/\/ newly created QuadStore as its backing.\nfunc NewGraph(args ...interface{}) *Graph {\n\tg := NewQuadStore().Graph(\"\")\n\n\tfor _, arg := range args {\n\t\tswitch arg := arg.(type) {\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unexpected type %T\\n\", arg))\n\t\tcase [3]string:\n\t\t\t\/\/ Single string triple.\n\t\t\tg.Add(arg[0], arg[1], arg[2])\n\t\tcase [][3]string:\n\t\t\t\/\/ Slice of string triples.\n\t\t\tfor _, q := range arg {\n\t\t\t\tg.Add(q[0], q[1], q[2])\n\t\t\t}\n\t\t}\n\t}\n\n\treturn g\n}\n\nfunc adaptTripleCallbackFn(fn TripleCallbackFn) QuadCallbackFn {\n\treturn func(s, p, o, g string) {\n\t\tfn(s, p, o)\n\t}\n}\n\nfunc adaptTripleTestFn(fn TripleTestFn) QuadTestFn {\n\treturn func(s, p, o, g string) bool {\n\t\treturn fn(s, p, o)\n\t}\n}\n\n\/\/ Add a triple to the graph.\n\/\/ Returns true if the triple was a new triple,\n\/\/ or false if the triple already existed.\n\/\/\n\/\/ If any of the given terms are \"*\" (an asterisk),\n\/\/ then this method will panic. (The asterisk is reserved\n\/\/ for wildcard operations throughout the API).\nfunc (g *Graph) Add(subject, predicate, object string) bool {\n\treturn g.QuadStore.Add(subject, predicate, object, g.Name)\n}\n\n\/\/ Count returns a count of triples in the graph that match the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) Count(subject, predicate, object string) uint64 {\n\treturn g.QuadStore.Count(subject, predicate, object, g.Name)\n}\n\n\/\/ Every tests whether all triples in the graph pass the test\n\/\/ implemented by the given function.\n\/\/\n\/\/ The given callback is\n\/\/ executed once for each triple present in the graph until\n\/\/ Every finds one where the callback returns false. If such\n\/\/ an element is found, iteration is immediately halted and\n\/\/ Every returns false. Otherwise, if the callback returns\n\/\/ true for all triples, then Every returns true.\n\/\/\n\/\/ Acting like the 'for all' quantifier in maths, it should\n\/\/ be noted that Every returns true for an empty graph.\nfunc (g *Graph) Every(fn TripleTestFn) bool {\n\treturn g.QuadStore.EveryWith(\"*\", \"*\", \"*\", g.Name, adaptTripleTestFn(fn))\n}\n\n\/\/ EveryWith tests whether all triples in the graph that match the\n\/\/ given terms pass the test implemented by the given function.\n\/\/\n\/\/ The given callback is\n\/\/ executed once for each matching triple in the graph until\n\/\/ EveryWith finds one where the callback returns false. If such\n\/\/ an element is found, iteration is immediately halted and\n\/\/ EveryWith returns false. Otherwise, if the callback returns\n\/\/ true for all triples, then EveryWith returns true.\n\/\/\n\/\/ Acting like the 'for all' quantifier in maths, it should\n\/\/ be noted that EveryWith returns true for an empty graph.\n\/\/ By extension, if the given parameters cause the iteration\n\/\/ set to be empty, then EveryWith also returns true.\nfunc (g *Graph) EveryWith(subject, predicate, object string, fn TripleTestFn) bool {\n\treturn g.QuadStore.EveryWith(subject, predicate, object, g.Name, adaptTripleTestFn(fn))\n}\n\n\/\/ FindObjects returns a list of distinct object terms for all triples in the graph that match the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) FindObjects(subject, predicate string) []string {\n\treturn g.QuadStore.FindObjects(subject, predicate, g.Name)\n}\n\n\/\/ FindPredicates returns a list of distinct predicate terms for all triples in the graph that match the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) FindPredicates(subject, object string) []string {\n\treturn g.QuadStore.FindPredicates(subject, object, g.Name)\n}\n\n\/\/ FindSubjects returns a list of distinct subject terms for all triples in the graph that match the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) FindSubjects(predicate, object string) []string {\n\treturn g.QuadStore.FindSubjects(predicate, object, g.Name)\n}\n\n\/\/ ForEach executes the given callback once for each triple in the graph.\nfunc (g *Graph) ForEach(fn TripleCallbackFn) {\n\tg.QuadStore.ForEachWith(\"*\", \"*\", \"*\", g.Name, adaptTripleCallbackFn(fn))\n}\n\n\/\/ ForEachWith executes the given callback once for each triple in the graph\n\/\/ that matches the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) ForEachWith(subject, predicate, object string, fn TripleCallbackFn) {\n\tg.QuadStore.ForEachWith(subject, predicate, object, g.Name, adaptTripleCallbackFn(fn))\n}\n\n\/\/ ForObjects executes the given callback once for each distinct object term\n\/\/ for all triples in the graph that match the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) ForObjects(subject, predicate string, fn StringCallbackFn) {\n\tg.QuadStore.ForObjects(subject, predicate, g.Name, fn)\n}\n\n\/\/ ForPredicates executes the given callback once for each distinct predicate term\n\/\/ for all triples in the graph that graph the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) ForPredicates(subject, object string, fn StringCallbackFn) {\n\tg.QuadStore.ForPredicates(subject, object, g.Name, fn)\n}\n\n\/\/ ForSubjects executes the given callback once for each distinct subject term\n\/\/ for all triples in the graph that match the given pattern.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) ForSubjects(predicate, object string, fn StringCallbackFn) {\n\tg.QuadStore.ForSubjects(predicate, object, g.Name, fn)\n}\n\n\/\/ Removes triples from the graph. Returns true if triples were removed,\n\/\/ or false if no matching triples exist.\n\/\/\n\/\/ Passing \"*\" (an asterisk) for any parameter acts as a\n\/\/ match-everything wildcard for that term.\nfunc (g *Graph) Remove(subject, predicate, object string) bool {\n\treturn g.QuadStore.Remove(subject, predicate, object, g.Name)\n}\n\n\/\/ Size returns the total count of triples in the graph.\nfunc (g *Graph) Size() uint64 {\n\tgimpl, ok := g.QuadStore.graphs[g.Name]\n\tif !ok {\n\t\treturn 0\n\t}\n\treturn gimpl.size\n}\n\n\/\/ Some tests whether some triple in the graph passes the test\n\/\/ implemented by the given function.\n\/\/\n\/\/ The given callback is\n\/\/ executed once for each triple present in the graph until\n\/\/ Some finds one where the callback returns true. If such\n\/\/ an element is found, iteration is immediately halted and\n\/\/ Some returns true. Otherwise, if the callback returns\n\/\/ false for all triples, then Some returns false.\nfunc (g *Graph) Some(fn TripleTestFn) bool {\n\treturn g.QuadStore.SomeWith(\"*\", \"*\", \"*\", g.Name, adaptTripleTestFn(fn))\n}\n\n\/\/ SomeWith tests whether some triple matching the given pattern\n\/\/ passes the test implemented by the given function.\n\/\/\n\/\/ The given callback is\n\/\/ executed once for each triple matching the given pattern until\n\/\/ SomeWith finds one where the callback returns true. If such\n\/\/ an element is found, iteration is immediately halted and\n\/\/ SomeWith returns true. Otherwise, if the callback returns\n\/\/ false for all triples, then SomeWith returns false.\nfunc (g *Graph) SomeWith(subject, predicate, object string, fn TripleTestFn) bool {\n\treturn g.QuadStore.SomeWith(subject, predicate, object, g.Name, adaptTripleTestFn(fn))\n}\n\n\/\/ String returns the contents of the graph in a human-readable format.\nfunc (g *Graph) String() string {\n\tvar buf bytes.Buffer\n\tname := g.Name\n\tif len(name) > 0 {\n\t\tbuf.WriteString(name)\n\t\tbuf.WriteByte('\\n')\n\t}\n\tsubjects := g.FindSubjects(\"*\", \"*\")\n\tsort.Strings(subjects)\n\tfor _, subject := range subjects {\n\t\tpredicates := g.FindPredicates(subject, \"*\")\n\t\tsort.Strings(predicates)\n\t\tfor _, predicate := range predicates {\n\t\t\tobjects := g.FindObjects(subject, predicate)\n\t\t\tsort.Strings(objects)\n\t\t\tfor _, object := range objects {\n\t\t\t\tbuf.WriteByte('[')\n\t\t\t\tbuf.WriteString(subject)\n\t\t\t\tbuf.WriteByte(' ')\n\t\t\t\tbuf.WriteString(predicate)\n\t\t\t\tbuf.WriteByte(' ')\n\t\t\t\tbuf.WriteString(object)\n\t\t\t\tbuf.WriteByte(']')\n\t\t\t\tbuf.WriteByte('\\n')\n\t\t\t}\n\t\t}\n\t}\n\treturn buf.String()\n}\n<|endoftext|>"}
{"text":"<commit_before>package echo\n\nimport (\n\t\"path\"\n)\n\ntype (\n\t\/\/ Group is a set of sub-routes for a specified route. It can be used for inner\n\t\/\/ routes that share a common middleware or functionality that should be separate\n\t\/\/ from the parent echo instance while still inheriting from it.\n\tGroup struct {\n\t\tprefix     string\n\t\tmiddleware []MiddlewareFunc\n\t\techo       *Echo\n\t}\n)\n\n\/\/ Use implements `Echo#Use()` for sub-routes within the Group.\nfunc (g *Group) Use(middleware ...MiddlewareFunc) {\n\tg.middleware = append(g.middleware, middleware...)\n\t\/\/ Allow all requests to reach the group as they might get dropped if router\n\t\/\/ doesn't find a match, making none of the group middleware process.\n\tg.echo.Any(path.Clean(g.prefix+\"\/*\"), func(c Context) error {\n\t\treturn NotFoundHandler(c)\n\t}, g.middleware...)\n}\n\n\/\/ CONNECT implements `Echo#CONNECT()` for sub-routes within the Group.\nfunc (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.add(CONNECT, path, h, m...)\n}\n\n\/\/ DELETE implements `Echo#DELETE()` for sub-routes within the Group.\nfunc (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.add(DELETE, path, h, m...)\n}\n\n\/\/ GET implements `Echo#GET()` for sub-routes within the Group.\nfunc (g *Group) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.add(GET, path, h, m...)\n}\n\n\/\/ HEAD implements `Echo#HEAD()` for sub-routes within the Group.\nfunc (g *Group) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.add(HEAD, path, h, m...)\n}\n\n\/\/ OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group.\nfunc (g *Group) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.add(OPTIONS, path, h, m...)\n}\n\n\/\/ PATCH implements `Echo#PATCH()` for sub-routes within the Group.\nfunc (g *Group) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.add(PATCH, path, h, m...)\n}\n\n\/\/ POST implements `Echo#POST()` for sub-routes within the Group.\nfunc (g *Group) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.add(POST, path, h, m...)\n}\n\n\/\/ PUT implements `Echo#PUT()` for sub-routes within the Group.\nfunc (g *Group) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.add(PUT, path, h, m...)\n}\n\n\/\/ TRACE implements `Echo#TRACE()` for sub-routes within the Group.\nfunc (g *Group) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.add(TRACE, path, h, m...)\n}\n\n\/\/ Any implements `Echo#Any()` for sub-routes within the Group.\nfunc (g *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) {\n\tfor _, m := range methods {\n\t\tg.add(m, path, handler, middleware...)\n\t}\n}\n\n\/\/ Match implements `Echo#Match()` for sub-routes within the Group.\nfunc (g *Group) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) {\n\tfor _, m := range methods {\n\t\tg.add(m, path, handler, middleware...)\n\t}\n}\n\n\/\/ Group creates a new sub-group with prefix and optional sub-group-level middleware.\nfunc (g *Group) Group(prefix string, middleware ...MiddlewareFunc) *Group {\n\tm := []MiddlewareFunc{}\n\tm = append(m, g.middleware...)\n\tm = append(m, middleware...)\n\treturn g.echo.Group(g.prefix+prefix, m...)\n}\n\n\/\/ Static implements `Echo#Static()` for sub-routes within the Group.\nfunc (g *Group) Static(prefix, root string) {\n\tstatic(g, prefix, root)\n}\n\n\/\/ File implements `Echo#File()` for sub-routes within the Group.\nfunc (g *Group) File(path, file string) {\n\tg.echo.File(g.prefix+path, file)\n}\n\nfunc (g *Group) add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route {\n\t\/\/ Combine into a new slice to avoid accidentally passing the same slice for\n\t\/\/ multiple routes, which would lead to later add() calls overwriting the\n\t\/\/ middleware from earlier calls.\n\tm := []MiddlewareFunc{}\n\tm = append(m, g.middleware...)\n\tm = append(m, middleware...)\n\treturn g.echo.Add(method, g.prefix+path, handler, m...)\n}\n<commit_msg>Expose group.add() method for dynamic route registration (#985)<commit_after>package echo\n\nimport (\n\t\"path\"\n)\n\ntype (\n\t\/\/ Group is a set of sub-routes for a specified route. It can be used for inner\n\t\/\/ routes that share a common middleware or functionality that should be separate\n\t\/\/ from the parent echo instance while still inheriting from it.\n\tGroup struct {\n\t\tprefix     string\n\t\tmiddleware []MiddlewareFunc\n\t\techo       *Echo\n\t}\n)\n\n\/\/ Use implements `Echo#Use()` for sub-routes within the Group.\nfunc (g *Group) Use(middleware ...MiddlewareFunc) {\n\tg.middleware = append(g.middleware, middleware...)\n\t\/\/ Allow all requests to reach the group as they might get dropped if router\n\t\/\/ doesn't find a match, making none of the group middleware process.\n\tg.echo.Any(path.Clean(g.prefix+\"\/*\"), func(c Context) error {\n\t\treturn NotFoundHandler(c)\n\t}, g.middleware...)\n}\n\n\/\/ CONNECT implements `Echo#CONNECT()` for sub-routes within the Group.\nfunc (g *Group) CONNECT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.Add(CONNECT, path, h, m...)\n}\n\n\/\/ DELETE implements `Echo#DELETE()` for sub-routes within the Group.\nfunc (g *Group) DELETE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.Add(DELETE, path, h, m...)\n}\n\n\/\/ GET implements `Echo#GET()` for sub-routes within the Group.\nfunc (g *Group) GET(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.Add(GET, path, h, m...)\n}\n\n\/\/ HEAD implements `Echo#HEAD()` for sub-routes within the Group.\nfunc (g *Group) HEAD(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.Add(HEAD, path, h, m...)\n}\n\n\/\/ OPTIONS implements `Echo#OPTIONS()` for sub-routes within the Group.\nfunc (g *Group) OPTIONS(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.Add(OPTIONS, path, h, m...)\n}\n\n\/\/ PATCH implements `Echo#PATCH()` for sub-routes within the Group.\nfunc (g *Group) PATCH(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.Add(PATCH, path, h, m...)\n}\n\n\/\/ POST implements `Echo#POST()` for sub-routes within the Group.\nfunc (g *Group) POST(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.Add(POST, path, h, m...)\n}\n\n\/\/ PUT implements `Echo#PUT()` for sub-routes within the Group.\nfunc (g *Group) PUT(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.Add(PUT, path, h, m...)\n}\n\n\/\/ TRACE implements `Echo#TRACE()` for sub-routes within the Group.\nfunc (g *Group) TRACE(path string, h HandlerFunc, m ...MiddlewareFunc) *Route {\n\treturn g.Add(TRACE, path, h, m...)\n}\n\n\/\/ Any implements `Echo#Any()` for sub-routes within the Group.\nfunc (g *Group) Any(path string, handler HandlerFunc, middleware ...MiddlewareFunc) {\n\tfor _, m := range methods {\n\t\tg.Add(m, path, handler, middleware...)\n\t}\n}\n\n\/\/ Match implements `Echo#Match()` for sub-routes within the Group.\nfunc (g *Group) Match(methods []string, path string, handler HandlerFunc, middleware ...MiddlewareFunc) {\n\tfor _, m := range methods {\n\t\tg.Add(m, path, handler, middleware...)\n\t}\n}\n\n\/\/ Group creates a new sub-group with prefix and optional sub-group-level middleware.\nfunc (g *Group) Group(prefix string, middleware ...MiddlewareFunc) *Group {\n\tm := []MiddlewareFunc{}\n\tm = append(m, g.middleware...)\n\tm = append(m, middleware...)\n\treturn g.echo.Group(g.prefix+prefix, m...)\n}\n\n\/\/ Static implements `Echo#Static()` for sub-routes within the Group.\nfunc (g *Group) Static(prefix, root string) {\n\tstatic(g, prefix, root)\n}\n\n\/\/ File implements `Echo#File()` for sub-routes within the Group.\nfunc (g *Group) File(path, file string) {\n\tg.echo.File(g.prefix+path, file)\n}\n\n\/\/ Add implements `Echo#Add()` for sub-routes within the Group.\nfunc (g *Group) Add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) *Route {\n\t\/\/ Combine into a new slice to avoid accidentally passing the same slice for\n\t\/\/ multiple routes, which would lead to later add() calls overwriting the\n\t\/\/ middleware from earlier calls.\n\tm := []MiddlewareFunc{}\n\tm = append(m, g.middleware...)\n\tm = append(m, middleware...)\n\treturn g.echo.Add(method, g.prefix+path, handler, m...)\n}\n<|endoftext|>"}
{"text":"<commit_before>package forecaster\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\nvar (\n\taccurate = fake{\n\t\tname: \"accurate\",\n\t\td:    delay{0.2, time.Second},\n\t}\n\tquick = fake{\n\t\tname: \"quick\",\n\t\td:    delay{0.01, 200 * time.Millisecond},\n\t}\n)\n\ntype fake struct {\n\tname string\n\td    delay\n}\n\nfunc (s *fake) Forecast(ctx context.Context) (*Response, error) {\n\trespCh := make(chan Response)\n\tgo func() {\n\t\tresp := Response{s.name, doNothing(s.d.delay())}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\tcase respCh <- resp:\n\t\t}\n\t}()\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\tcase resp := <-respCh:\n\t\treturn &resp, nil\n\t}\n}\n\nfunc doNothing(delay time.Duration) time.Time {\n\tif delay > 0 {\n\t\ttime.Sleep(delay)\n\t}\n\treturn time.Now()\n}\n<commit_msg>added comments to forecaster example<commit_after>\/\/ Package forecaster allows to test Fallback approach.\n\/\/\n\/\/ The main idea is to have two different providers with a balance between an accurate data and quick data retrieving.\n\/\/ Usually, quick load gives dirty data. Dirty data allows to avoid unreliable response.\n\/\/\n\/\/ It will work if a system was ready to take a low rate of dirty data. It's a sponsor requirement.\npackage forecaster\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\nvar (\n\t\/\/ accurate works slowly\n\taccurate = fake{\n\t\tname: \"accurate\",\n\t\td:    delay{0.2, time.Second},\n\t}\n\t\/\/ quick returns dirty data\n\tquick = fake{\n\t\tname: \"quick\",\n\t\td:    delay{0.01, 200 * time.Millisecond},\n\t}\n)\n\ntype fake struct {\n\tname string\n\td    delay\n}\n\nfunc (s *fake) Forecast(ctx context.Context) (*Response, error) {\n\trespCh := make(chan Response)\n\tgo func() {\n\t\tresp := Response{s.name, doNothing(s.d.delay())}\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\tcase respCh <- resp:\n\t\t}\n\t}()\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\tcase resp := <-respCh:\n\t\treturn &resp, nil\n\t}\n}\n\nfunc doNothing(delay time.Duration) time.Time {\n\tif delay > 0 {\n\t\ttime.Sleep(delay)\n\t}\n\treturn time.Now()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build example\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"github.com\/hajimehoshi\/ebiten\"\n\t\"github.com\/hajimehoshi\/ebiten\/ebitenutil\"\n)\n\nconst (\n\tscreenWidth  = 640\n\tscreenHeight = 640\n\tmaxIt        = 128\n)\n\nvar (\n\toffscreen    *ebiten.Image\n\toffscreenPix []byte\n\tpalette      [maxIt]byte\n)\n\nfunc init() {\n\toffscreen, _ = ebiten.NewImage(screenWidth, screenHeight, ebiten.FilterNearest)\n\toffscreenPix = make([]byte, screenWidth*screenHeight*4)\n\tfor i := range palette {\n\t\tc := byte(math.Sqrt(float64(i)\/float64(len(palette))) * 0xff)\n\t\tpalette[i] = c\n\t}\n}\n\nfunc color(it int) (r, g, b byte) {\n\tif it == maxIt {\n\t\treturn 0, 0, 0\n\t}\n\tc := palette[it]\n\treturn c, c, c\n}\n\nfunc updateOffscreen(centerX, centerY, size float64) {\n\tfor j := 0; j < screenHeight; j++ {\n\t\tfor i := 0; i < screenHeight; i++ {\n\t\t\tx := float64(i)*size\/screenWidth - size\/2 + centerX\n\t\t\ty := (screenHeight-float64(j))*size\/screenHeight - size\/2 + centerY\n\t\t\tc := complex(x, y)\n\t\t\tz := c\n\t\t\tit := 0\n\t\t\tfor ; it < maxIt; it++ {\n\t\t\t\tnz := z*z + c\n\t\t\t\tif real(nz)*real(nz)+imag(nz)*imag(nz) > 4 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tz = nz\n\t\t\t}\n\t\t\tr, g, b := color(it)\n\t\t\tp := 4 * (i + j*screenWidth)\n\t\t\toffscreenPix[p] = r\n\t\t\toffscreenPix[p+1] = g\n\t\t\toffscreenPix[p+2] = b\n\t\t\toffscreenPix[p+3] = 0xff\n\t\t}\n\t}\n\toffscreen.ReplacePixels(offscreenPix)\n}\n\nfunc init() {\n\t\/\/ Now it is not feasible to call updateOffscreen every frame due to performance.\n\tupdateOffscreen(-0.75, 0.25, 2)\n}\n\nfunc update(screen *ebiten.Image) error {\n\tif ebiten.IsRunningSlowly() {\n\t\treturn nil\n\t}\n\n\tscreen.DrawImage(offscreen, nil)\n\tebitenutil.DebugPrint(screen, fmt.Sprintf(\"FPS: %0.2f\", ebiten.CurrentFPS()))\n\treturn nil\n}\n\nfunc main() {\n\tif err := ebiten.Run(update, screenWidth, screenHeight, 1, \"Mandelbrot (Ebiten Demo)\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>examples\/mandelbrot: Fix colors<commit_after>\/\/ Copyright 2017 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build example\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\n\t\"github.com\/hajimehoshi\/ebiten\"\n\t\"github.com\/hajimehoshi\/ebiten\/ebitenutil\"\n)\n\nconst (\n\tscreenWidth  = 640\n\tscreenHeight = 640\n\tmaxIt        = 128\n)\n\nvar (\n\toffscreen    *ebiten.Image\n\toffscreenPix []byte\n\tpalette      [maxIt]byte\n)\n\nfunc init() {\n\toffscreen, _ = ebiten.NewImage(screenWidth, screenHeight, ebiten.FilterNearest)\n\toffscreenPix = make([]byte, screenWidth*screenHeight*4)\n\tfor i := range palette {\n\t\tc := byte(math.Sqrt(float64(i)\/float64(len(palette))) * 0xff)\n\t\tpalette[i] = c\n\t}\n}\n\nfunc color(it int) (r, g, b byte) {\n\tif it == maxIt {\n\t\treturn 0xff, 0xff, 0xff\n\t}\n\tc := palette[it]\n\treturn c, c, c\n}\n\nfunc updateOffscreen(centerX, centerY, size float64) {\n\tfor j := 0; j < screenHeight; j++ {\n\t\tfor i := 0; i < screenHeight; i++ {\n\t\t\tx := float64(i)*size\/screenWidth - size\/2 + centerX\n\t\t\ty := (screenHeight-float64(j))*size\/screenHeight - size\/2 + centerY\n\t\t\tc := complex(x, y)\n\t\t\tz := c\n\t\t\tit := 0\n\t\t\tfor ; it < maxIt; it++ {\n\t\t\t\tnz := z*z + c\n\t\t\t\tif real(nz)*real(nz)+imag(nz)*imag(nz) > 4 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tz = nz\n\t\t\t}\n\t\t\tr, g, b := color(it)\n\t\t\tp := 4 * (i + j*screenWidth)\n\t\t\toffscreenPix[p] = r\n\t\t\toffscreenPix[p+1] = g\n\t\t\toffscreenPix[p+2] = b\n\t\t\toffscreenPix[p+3] = 0xff\n\t\t}\n\t}\n\toffscreen.ReplacePixels(offscreenPix)\n}\n\nfunc init() {\n\t\/\/ Now it is not feasible to call updateOffscreen every frame due to performance.\n\tupdateOffscreen(-0.75, 0.25, 2)\n}\n\nfunc update(screen *ebiten.Image) error {\n\tif ebiten.IsRunningSlowly() {\n\t\treturn nil\n\t}\n\n\tscreen.DrawImage(offscreen, nil)\n\tebitenutil.DebugPrint(screen, fmt.Sprintf(\"FPS: %0.2f\", ebiten.CurrentFPS()))\n\treturn nil\n}\n\nfunc main() {\n\tif err := ebiten.Run(update, screenWidth, screenHeight, 1, \"Mandelbrot (Ebiten Demo)\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright (c) 2014-2015, Percona LLC and\/or its affiliates. All rights reserved.\n\n   This program is free software: you can redistribute it and\/or modify\n   it under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>\n*\/\n\npackage query\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com\/percona\/cloud-protocol\/proto\"\n\t\"github.com\/percona\/percona-agent\/instance\"\n\t\"github.com\/percona\/percona-agent\/mysql\"\n\t\"github.com\/percona\/percona-agent\/pct\"\n\tmysqlExec \"github.com\/percona\/percona-agent\/query\/mysql\"\n)\n\nconst (\n\tSERVICE_NAME = \"query\"\n)\n\ntype Manager struct {\n\tlogger       *pct.Logger\n\tinstanceRepo *instance.Repo\n\tconnFactory  mysql.ConnectionFactory\n\t\/\/ --\n\trunning bool\n\tsync.Mutex\n\tstatus *pct.Status\n}\n\nfunc NewManager(logger *pct.Logger, instanceRepo *instance.Repo, connFactory mysql.ConnectionFactory) *Manager {\n\tm := &Manager{\n\t\tlogger:       logger,\n\t\tinstanceRepo: instanceRepo,\n\t\tconnFactory:  connFactory,\n\t\t\/\/ --\n\t\tstatus: pct.NewStatus([]string{SERVICE_NAME}),\n\t}\n\treturn m\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (m *Manager) Start() error {\n\tm.Lock()\n\tdefer m.Unlock()\n\tif m.running {\n\t\treturn pct.ServiceIsRunningError{Service: SERVICE_NAME}\n\t}\n\tm.running = true\n\tm.logger.Info(\"Started\")\n\tm.status.Update(SERVICE_NAME, \"Idle\")\n\treturn nil\n}\n\nfunc (m *Manager) Stop() error {\n\t\/\/ Let user stop this tool in case they don't want agent executing queries.\n\tm.Lock()\n\tdefer m.Unlock()\n\tif !m.running {\n\t\treturn nil\n\t}\n\tm.running = false\n\tm.logger.Info(\"Stopped\")\n\tm.status.Update(SERVICE_NAME, \"Stopped\")\n\treturn nil\n}\n\nfunc (m *Manager) Handle(cmd *proto.Cmd) *proto.Reply {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\t\/\/ Don't query if this tool is stopped.\n\tif !m.running {\n\t\treturn cmd.Reply(nil, pct.ServiceIsNotRunningError{})\n\t}\n\n\tm.status.UpdateRe(SERVICE_NAME, \"Handling\", cmd)\n\tdefer m.status.Update(SERVICE_NAME, \"Idle\")\n\n\t\/\/ See which type of subsystem this query is for. Right now we only support\n\t\/\/ MySQL, but this abstraction will make adding other subsystems easy.\n\tsi := &proto.ServiceInstance{}\n\tif err := json.Unmarshal(cmd.Data, si); err != nil {\n\t\treturn cmd.Reply(nil, err)\n\t}\n\n\tswitch si.Service {\n\tcase \"mysql\":\n\t\treturn m.handleMySQLQuery(cmd, si)\n\tdefault:\n\t\treturn cmd.Reply(nil, pct.UnknownCmdError{si.Service})\n\t}\n}\n\nfunc (m *Manager) Status() map[string]string {\n\treturn m.status.All()\n}\n\nfunc (m *Manager) GetConfig() ([]proto.AgentConfig, []error) {\n\treturn nil, nil\n}\n\n\/\/ --------------------------------------------------------------------------\n\nfunc (m *Manager) handleMySQLQuery(cmd *proto.Cmd, si *proto.ServiceInstance) *proto.Reply {\n\tm.logger.Debug(\"handleMySQLQuery:call\")\n\tdefer m.logger.Debug(\"handleMySQLQuery:return\")\n\n\t\/\/ Connect to MySQL.\n\tmysqlIt := &proto.MySQLInstance{}\n\tif err := m.instanceRepo.Get(si.Service, si.InstanceId, mysqlIt); err != nil {\n\t\treturn cmd.Reply(nil, err)\n\t}\n\tconn := m.connFactory.Make(mysqlIt.DSN)\n\tif err := conn.Connect(1); err != nil {\n\t\treturn cmd.Reply(nil, fmt.Errorf(\"Cannot connect to MySQL: %s\", err))\n\t}\n\tdefer conn.Close()\n\n\t\/\/ Create a MySQL query executor to do the actual work.\n\te := mysqlExec.NewQueryExecutor(conn)\n\n\t\/\/ Get the instance name, e.g. mysql-db01, to make status human-readable.\n\tinstanceName := m.instanceRepo.Name(si.Service, si.InstanceId)\n\n\t\/\/ Execute the query.\n\tm.logger.Debug(cmd.Cmd + \":\" + instanceName)\n\tswitch cmd.Cmd {\n\tcase \"Explain\":\n\t\tm.status.Update(SERVICE_NAME, \"EXPLAIN query on \"+instanceName)\n\t\tq := &proto.ExplainQuery{}\n\t\tif err := json.Unmarshal(cmd.Data, q); err != nil {\n\t\t\treturn cmd.Reply(nil, err)\n\t\t}\n\t\tres, err := e.Explain(q.Db, q.Query)\n\t\tif err != nil {\n\t\t\treturn cmd.Reply(nil, fmt.Errorf(\"EXPLAIN failed: %s\", err))\n\t\t}\n\t\treturn cmd.Reply(res, nil)\n\tcase \"TableInfo\":\n\t\tm.status.Update(SERVICE_NAME, \"Table Info queries on \"+instanceName)\n\t\ttableInfo := &proto.TableInfoQuery{}\n\t\tif err := json.Unmarshal(cmd.Data, tableInfo); err != nil {\n\t\t\treturn cmd.Reply(nil, err)\n\t\t}\n\t\tres, err := e.TableInfo(tableInfo)\n\t\tif err != nil {\n\t\t\treturn cmd.Reply(nil, fmt.Errorf(\"Table Info failed: %s\", err))\n\t\t}\n\t\treturn cmd.Reply(res, nil)\n\tdefault:\n\t\treturn cmd.Reply(nil, pct.UnknownCmdError{Cmd: cmd.Cmd})\n\t}\n}\n<commit_msg>Fix err type: UnknownServiceInstanceError not UnknownCmdError.<commit_after>\/*\n   Copyright (c) 2014-2015, Percona LLC and\/or its affiliates. All rights reserved.\n\n   This program is free software: you can redistribute it and\/or modify\n   it under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>\n*\/\n\npackage query\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com\/percona\/cloud-protocol\/proto\"\n\t\"github.com\/percona\/percona-agent\/instance\"\n\t\"github.com\/percona\/percona-agent\/mysql\"\n\t\"github.com\/percona\/percona-agent\/pct\"\n\tmysqlExec \"github.com\/percona\/percona-agent\/query\/mysql\"\n)\n\nconst (\n\tSERVICE_NAME = \"query\"\n)\n\ntype Manager struct {\n\tlogger       *pct.Logger\n\tinstanceRepo *instance.Repo\n\tconnFactory  mysql.ConnectionFactory\n\t\/\/ --\n\trunning bool\n\tsync.Mutex\n\tstatus *pct.Status\n}\n\nfunc NewManager(logger *pct.Logger, instanceRepo *instance.Repo, connFactory mysql.ConnectionFactory) *Manager {\n\tm := &Manager{\n\t\tlogger:       logger,\n\t\tinstanceRepo: instanceRepo,\n\t\tconnFactory:  connFactory,\n\t\t\/\/ --\n\t\tstatus: pct.NewStatus([]string{SERVICE_NAME}),\n\t}\n\treturn m\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (m *Manager) Start() error {\n\tm.Lock()\n\tdefer m.Unlock()\n\tif m.running {\n\t\treturn pct.ServiceIsRunningError{Service: SERVICE_NAME}\n\t}\n\tm.running = true\n\tm.logger.Info(\"Started\")\n\tm.status.Update(SERVICE_NAME, \"Idle\")\n\treturn nil\n}\n\nfunc (m *Manager) Stop() error {\n\t\/\/ Let user stop this tool in case they don't want agent executing queries.\n\tm.Lock()\n\tdefer m.Unlock()\n\tif !m.running {\n\t\treturn nil\n\t}\n\tm.running = false\n\tm.logger.Info(\"Stopped\")\n\tm.status.Update(SERVICE_NAME, \"Stopped\")\n\treturn nil\n}\n\nfunc (m *Manager) Handle(cmd *proto.Cmd) *proto.Reply {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\t\/\/ Don't query if this tool is stopped.\n\tif !m.running {\n\t\treturn cmd.Reply(nil, pct.ServiceIsNotRunningError{})\n\t}\n\n\tm.status.UpdateRe(SERVICE_NAME, \"Handling\", cmd)\n\tdefer m.status.Update(SERVICE_NAME, \"Idle\")\n\n\t\/\/ See which type of subsystem this query is for. Right now we only support\n\t\/\/ MySQL, but this abstraction will make adding other subsystems easy.\n\tsi := &proto.ServiceInstance{}\n\tif err := json.Unmarshal(cmd.Data, si); err != nil {\n\t\treturn cmd.Reply(nil, err)\n\t}\n\n\tswitch si.Service {\n\tcase \"mysql\":\n\t\treturn m.handleMySQLQuery(cmd, si)\n\tdefault:\n\t\treturn cmd.Reply(nil, pct.UnknownServiceInstanceError{si.Service, si.Id})\n\t}\n}\n\nfunc (m *Manager) Status() map[string]string {\n\treturn m.status.All()\n}\n\nfunc (m *Manager) GetConfig() ([]proto.AgentConfig, []error) {\n\treturn nil, nil\n}\n\n\/\/ --------------------------------------------------------------------------\n\nfunc (m *Manager) handleMySQLQuery(cmd *proto.Cmd, si *proto.ServiceInstance) *proto.Reply {\n\tm.logger.Debug(\"handleMySQLQuery:call\")\n\tdefer m.logger.Debug(\"handleMySQLQuery:return\")\n\n\t\/\/ Connect to MySQL.\n\tmysqlIt := &proto.MySQLInstance{}\n\tif err := m.instanceRepo.Get(si.Service, si.InstanceId, mysqlIt); err != nil {\n\t\treturn cmd.Reply(nil, err)\n\t}\n\tconn := m.connFactory.Make(mysqlIt.DSN)\n\tif err := conn.Connect(1); err != nil {\n\t\treturn cmd.Reply(nil, fmt.Errorf(\"Cannot connect to MySQL: %s\", err))\n\t}\n\tdefer conn.Close()\n\n\t\/\/ Create a MySQL query executor to do the actual work.\n\te := mysqlExec.NewQueryExecutor(conn)\n\n\t\/\/ Get the instance name, e.g. mysql-db01, to make status human-readable.\n\tinstanceName := m.instanceRepo.Name(si.Service, si.InstanceId)\n\n\t\/\/ Execute the query.\n\tm.logger.Debug(cmd.Cmd + \":\" + instanceName)\n\tswitch cmd.Cmd {\n\tcase \"Explain\":\n\t\tm.status.Update(SERVICE_NAME, \"EXPLAIN query on \"+instanceName)\n\t\tq := &proto.ExplainQuery{}\n\t\tif err := json.Unmarshal(cmd.Data, q); err != nil {\n\t\t\treturn cmd.Reply(nil, err)\n\t\t}\n\t\tres, err := e.Explain(q.Db, q.Query)\n\t\tif err != nil {\n\t\t\treturn cmd.Reply(nil, fmt.Errorf(\"EXPLAIN failed: %s\", err))\n\t\t}\n\t\treturn cmd.Reply(res, nil)\n\tcase \"TableInfo\":\n\t\tm.status.Update(SERVICE_NAME, \"Table Info queries on \"+instanceName)\n\t\ttableInfo := &proto.TableInfoQuery{}\n\t\tif err := json.Unmarshal(cmd.Data, tableInfo); err != nil {\n\t\t\treturn cmd.Reply(nil, err)\n\t\t}\n\t\tres, err := e.TableInfo(tableInfo)\n\t\tif err != nil {\n\t\t\treturn cmd.Reply(nil, fmt.Errorf(\"Table Info failed: %s\", err))\n\t\t}\n\t\treturn cmd.Reply(res, nil)\n\tdefault:\n\t\treturn cmd.Reply(nil, pct.UnknownCmdError{Cmd: cmd.Cmd})\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package grpc_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\"\n\t\"testing\"\n\n\t\"google.golang.org\/grpc\"\n\n\ttest \"github.com\/go-kit\/kit\/transport\/grpc\/_grpc_test\"\n\t\"github.com\/go-kit\/kit\/transport\/grpc\/_grpc_test\/pb\"\n)\n\nconst (\n\thostPort string = \"localhost:8002\"\n)\n\nfunc TestGRPCClient(t *testing.T) {\n\tvar (\n\t\tserver  = grpc.NewServer()\n\t\tservice = test.NewService()\n\t)\n\n\tsc, err := net.Listen(\"tcp\", hostPort)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to listen: %+v\", err)\n\t}\n\tdefer server.GracefulStop()\n\n\tgo func() {\n\t\tpb.RegisterTestServer(server, test.NewBinding(service))\n\t\t_ = server.Serve(sc)\n\t}()\n\n\tcc, err := grpc.Dial(hostPort, grpc.WithInsecure())\n\tif err != nil {\n\t\tt.Fatalf(\"unable to Dial: %+v\", err)\n\t}\n\n\tclient := test.NewClient(cc)\n\n\tvar (\n\t\ta   = \"the answer to life the universe and everything\"\n\t\tb   = int64(42)\n\t\tcID = \"request-1\"\n\t\tctx = test.SetCorrelationID(context.Background(), cID)\n\t)\n\n\tresponseCTX, v, err := client.Test(ctx, a, b)\n\n\tif want, have := fmt.Sprintf(\"%s = %d\", a, b), v; want != have {\n\t\tt.Fatalf(\"want %q, have %q\", want, have)\n\t}\n\n\tif want, have := cID, test.GetConsumedCorrelationID(responseCTX); want != have {\n\t\tt.Fatalf(\"want %q, have %q\", want, have)\n\t}\n}\n<commit_msg>Fix swallowed error in grpc_test.<commit_after>package grpc_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\"\n\t\"testing\"\n\n\t\"google.golang.org\/grpc\"\n\n\ttest \"github.com\/go-kit\/kit\/transport\/grpc\/_grpc_test\"\n\t\"github.com\/go-kit\/kit\/transport\/grpc\/_grpc_test\/pb\"\n)\n\nconst (\n\thostPort string = \"localhost:8002\"\n)\n\nfunc TestGRPCClient(t *testing.T) {\n\tvar (\n\t\tserver  = grpc.NewServer()\n\t\tservice = test.NewService()\n\t)\n\n\tsc, err := net.Listen(\"tcp\", hostPort)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to listen: %+v\", err)\n\t}\n\tdefer server.GracefulStop()\n\n\tgo func() {\n\t\tpb.RegisterTestServer(server, test.NewBinding(service))\n\t\t_ = server.Serve(sc)\n\t}()\n\n\tcc, err := grpc.Dial(hostPort, grpc.WithInsecure())\n\tif err != nil {\n\t\tt.Fatalf(\"unable to Dial: %+v\", err)\n\t}\n\n\tclient := test.NewClient(cc)\n\n\tvar (\n\t\ta   = \"the answer to life the universe and everything\"\n\t\tb   = int64(42)\n\t\tcID = \"request-1\"\n\t\tctx = test.SetCorrelationID(context.Background(), cID)\n\t)\n\n\tresponseCTX, v, err := client.Test(ctx, a, b)\n\tif err != nil {\n\t\tt.Fatalf(\"unable to Test: %+v\", err)\n\t}\n\tif want, have := fmt.Sprintf(\"%s = %d\", a, b), v; want != have {\n\t\tt.Fatalf(\"want %q, have %q\", want, have)\n\t}\n\n\tif want, have := cID, test.GetConsumedCorrelationID(responseCTX); want != have {\n\t\tt.Fatalf(\"want %q, have %q\", want, have)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"fmt\"\nimport \"math\"\n\nfunc main() {\n\tfmt.Println(\"Hello, ??\")\n\tlog2()\n}\n\nfunc log2() {\nfmt.Println(math.Log2(2))\n}<commit_msg>changes<commit_after>package main\n\nimport \"fmt\"\nimport \"math\"\n\nfunc main() {\n\tfmt.Println(\"Hello, ??\")\n<<<<<<< HEAD\n\tlog2()\n}\n\nfunc log2() {\nfmt.Println(math.Log2(2))\n}\n=======\n\tfmt.Println(\"Heisann\")\n}\n>>>>>>> 565d01d9da9a85e1ce39beefffbc2b8ccbfa3ca1\n<|endoftext|>"}
{"text":"<commit_before>package types\n\nimport (\n\t\"crypto\/ecdsa\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\/big\"\n\n\t\"github.com\/ethereum\/go-ethereum\/common\"\n\t\"github.com\/ethereum\/go-ethereum\/crypto\"\n\t\"github.com\/ethereum\/go-ethereum\/crypto\/secp256k1\"\n\t\"github.com\/ethereum\/go-ethereum\/rlp\"\n)\n\nfunc IsContractAddr(addr []byte) bool {\n\treturn len(addr) == 0\n}\n\ntype Transaction struct {\n\tAccountNonce uint64\n\tPrice        *big.Int\n\tGasLimit     *big.Int\n\tRecipient    *common.Address \/\/ nil means contract creation\n\tAmount       *big.Int\n\tPayload      []byte\n\tV            byte\n\tR, S         []byte\n}\n\nfunc NewContractCreationTx(amount, gasLimit, gasPrice *big.Int, data []byte) *Transaction {\n\treturn &Transaction{Recipient: nil, Amount: amount, GasLimit: gasLimit, Price: gasPrice, Payload: data}\n}\n\nfunc NewTransactionMessage(to common.Address, amount, gasAmount, gasPrice *big.Int, data []byte) *Transaction {\n\treturn &Transaction{Recipient: &to, Amount: amount, GasLimit: gasAmount, Price: gasPrice, Payload: data}\n}\n\nfunc NewTransactionFromBytes(data []byte) *Transaction {\n\t\/\/ TODO: remove this function if possible. callers would\n\t\/\/ much better off decoding into transaction directly.\n\t\/\/ it's not that hard.\n\ttx := new(Transaction)\n\trlp.DecodeBytes(data, tx)\n\treturn tx\n}\n\nfunc (tx *Transaction) Hash() common.Hash {\n\treturn rlpHash([]interface{}{\n\t\ttx.AccountNonce, tx.Price, tx.GasLimit, tx.Recipient, tx.Amount, tx.Payload,\n\t})\n}\n\nfunc (self *Transaction) Data() []byte {\n\treturn self.Payload\n}\n\nfunc (self *Transaction) Gas() *big.Int {\n\treturn self.GasLimit\n}\n\nfunc (self *Transaction) GasPrice() *big.Int {\n\treturn self.Price\n}\n\nfunc (self *Transaction) Value() *big.Int {\n\treturn self.Amount\n}\n\nfunc (self *Transaction) Nonce() uint64 {\n\treturn self.AccountNonce\n}\n\nfunc (self *Transaction) SetNonce(AccountNonce uint64) {\n\tself.AccountNonce = AccountNonce\n}\n\nfunc (self *Transaction) From() (common.Address, error) {\n\tpubkey := self.PublicKey()\n\tif len(pubkey) == 0 || pubkey[0] != 4 {\n\t\treturn common.Address{}, errors.New(\"invalid public key\")\n\t}\n\tvar addr common.Address\n\tcopy(addr[:], crypto.Sha3(pubkey[1:]))\n\treturn addr, nil\n}\n\n\/\/ To returns the recipient of the transaction.\n\/\/ If transaction is a contract creation (with no recipient address)\n\/\/ To returns nil.\nfunc (tx *Transaction) To() *common.Address {\n\treturn tx.Recipient\n}\n\nfunc (tx *Transaction) Curve() (v byte, r []byte, s []byte) {\n\tv = byte(tx.V)\n\tr = common.LeftPadBytes(tx.R, 32)\n\ts = common.LeftPadBytes(tx.S, 32)\n\treturn\n}\n\nfunc (tx *Transaction) Signature(key []byte) []byte {\n\thash := tx.Hash()\n\tsig, _ := secp256k1.Sign(hash[:], key)\n\treturn sig\n}\n\nfunc (tx *Transaction) PublicKey() []byte {\n\thash := tx.Hash()\n\tv, r, s := tx.Curve()\n\tsig := append(r, s...)\n\tsig = append(sig, v-27)\n\n\t\/\/pubkey := crypto.Ecrecover(append(hash, sig...))\n\tpubkey, _ := secp256k1.RecoverPubkey(hash[:], sig)\n\treturn pubkey\n}\n\nfunc (tx *Transaction) SetSignatureValues(sig []byte) error {\n\ttx.R = sig[:32]\n\ttx.S = sig[32:64]\n\ttx.V = sig[64] + 27\n\treturn nil\n}\n\nfunc (tx *Transaction) SignECDSA(prv *ecdsa.PrivateKey) error {\n\th := tx.Hash()\n\tsig, err := crypto.Sign(h[:], prv)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttx.SetSignatureValues(sig)\n\treturn nil\n}\n\n\/\/ TODO: remove\nfunc (tx *Transaction) RlpData() interface{} {\n\tdata := []interface{}{tx.AccountNonce, tx.Price, tx.GasLimit, tx.Recipient, tx.Amount, tx.Payload}\n\treturn append(data, tx.V, new(big.Int).SetBytes(tx.R).Bytes(), new(big.Int).SetBytes(tx.S).Bytes())\n}\n\nfunc (tx *Transaction) String() string {\n\tvar from, to string\n\tif f, err := tx.From(); err != nil {\n\t\tfrom = \"[invalid sender]\"\n\t} else {\n\t\tfrom = fmt.Sprintf(\"%x\", f[:])\n\t}\n\tif t := tx.To(); t == nil {\n\t\tto = \"[contract creation]\"\n\t} else {\n\t\tto = fmt.Sprintf(\"%x\", t[:])\n\t}\n\tenc, _ := rlp.EncodeToBytes(tx)\n\treturn fmt.Sprintf(`\n\tTX(%x)\n\tContract: %v\n\tFrom:     %s\n\tTo:       %s\n\tNonce:    %v\n\tGasPrice: %v\n\tGasLimit  %v\n\tValue:    %v\n\tData:     0x%x\n\tV:        0x%x\n\tR:        0x%x\n\tS:        0x%x\n\tHex:      %x\n`,\n\t\ttx.Hash(),\n\t\tlen(tx.Recipient) == 0,\n\t\tfrom,\n\t\tto,\n\t\ttx.AccountNonce,\n\t\ttx.Price,\n\t\ttx.GasLimit,\n\t\ttx.Amount,\n\t\ttx.Payload,\n\t\ttx.V,\n\t\ttx.R,\n\t\ttx.S,\n\t\tenc,\n\t)\n}\n\n\/\/ Transaction slice type for basic sorting\ntype Transactions []*Transaction\n\n\/\/ TODO: remove\nfunc (self Transactions) RlpData() interface{} {\n\t\/\/ Marshal the transactions of this block\n\tenc := make([]interface{}, len(self))\n\tfor i, tx := range self {\n\t\t\/\/ Cast it to a string (safe)\n\t\tenc[i] = tx.RlpData()\n\t}\n\n\treturn enc\n}\n\nfunc (s Transactions) Len() int      { return len(s) }\nfunc (s Transactions) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Transactions) GetRlp(i int) []byte {\n\tenc, _ := rlp.EncodeToBytes(s[i])\n\treturn enc\n}\n\ntype TxByNonce struct{ Transactions }\n\nfunc (s TxByNonce) Less(i, j int) bool {\n\treturn s.Transactions[i].AccountNonce < s.Transactions[j].AccountNonce\n}\n<commit_msg>Fixed incorrect recipient derived<commit_after>package types\n\nimport (\n\t\"crypto\/ecdsa\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\/big\"\n\n\t\"github.com\/ethereum\/go-ethereum\/common\"\n\t\"github.com\/ethereum\/go-ethereum\/crypto\"\n\t\"github.com\/ethereum\/go-ethereum\/crypto\/secp256k1\"\n\t\"github.com\/ethereum\/go-ethereum\/rlp\"\n)\n\nfunc IsContractAddr(addr []byte) bool {\n\treturn len(addr) == 0\n}\n\ntype Transaction struct {\n\tAccountNonce uint64\n\tPrice        *big.Int\n\tGasLimit     *big.Int\n\tRecipient    *common.Address \/\/ nil means contract creation\n\tAmount       *big.Int\n\tPayload      []byte\n\tV            byte\n\tR, S         []byte\n}\n\nfunc NewContractCreationTx(amount, gasLimit, gasPrice *big.Int, data []byte) *Transaction {\n\treturn &Transaction{Recipient: nil, Amount: amount, GasLimit: gasLimit, Price: gasPrice, Payload: data}\n}\n\nfunc NewTransactionMessage(to common.Address, amount, gasAmount, gasPrice *big.Int, data []byte) *Transaction {\n\treturn &Transaction{Recipient: &to, Amount: amount, GasLimit: gasAmount, Price: gasPrice, Payload: data}\n}\n\nfunc NewTransactionFromBytes(data []byte) *Transaction {\n\t\/\/ TODO: remove this function if possible. callers would\n\t\/\/ much better off decoding into transaction directly.\n\t\/\/ it's not that hard.\n\ttx := new(Transaction)\n\trlp.DecodeBytes(data, tx)\n\treturn tx\n}\n\nfunc (tx *Transaction) Hash() common.Hash {\n\treturn rlpHash([]interface{}{\n\t\ttx.AccountNonce, tx.Price, tx.GasLimit, tx.Recipient, tx.Amount, tx.Payload,\n\t})\n}\n\nfunc (self *Transaction) Data() []byte {\n\treturn self.Payload\n}\n\nfunc (self *Transaction) Gas() *big.Int {\n\treturn self.GasLimit\n}\n\nfunc (self *Transaction) GasPrice() *big.Int {\n\treturn self.Price\n}\n\nfunc (self *Transaction) Value() *big.Int {\n\treturn self.Amount\n}\n\nfunc (self *Transaction) Nonce() uint64 {\n\treturn self.AccountNonce\n}\n\nfunc (self *Transaction) SetNonce(AccountNonce uint64) {\n\tself.AccountNonce = AccountNonce\n}\n\nfunc (self *Transaction) From() (common.Address, error) {\n\tpubkey := self.PublicKey()\n\tif len(pubkey) == 0 || pubkey[0] != 4 {\n\t\treturn common.Address{}, errors.New(\"invalid public key\")\n\t}\n\tvar addr common.Address\n\tcopy(addr[:], crypto.Sha3(pubkey[1:])[12:])\n\treturn addr, nil\n}\n\n\/\/ To returns the recipient of the transaction.\n\/\/ If transaction is a contract creation (with no recipient address)\n\/\/ To returns nil.\nfunc (tx *Transaction) To() *common.Address {\n\treturn tx.Recipient\n}\n\nfunc (tx *Transaction) Curve() (v byte, r []byte, s []byte) {\n\tv = byte(tx.V)\n\tr = common.LeftPadBytes(tx.R, 32)\n\ts = common.LeftPadBytes(tx.S, 32)\n\treturn\n}\n\nfunc (tx *Transaction) Signature(key []byte) []byte {\n\thash := tx.Hash()\n\tsig, _ := secp256k1.Sign(hash[:], key)\n\treturn sig\n}\n\nfunc (tx *Transaction) PublicKey() []byte {\n\thash := tx.Hash()\n\tv, r, s := tx.Curve()\n\tsig := append(r, s...)\n\tsig = append(sig, v-27)\n\n\t\/\/pubkey := crypto.Ecrecover(append(hash, sig...))\n\tpubkey, _ := secp256k1.RecoverPubkey(hash[:], sig)\n\treturn pubkey\n}\n\nfunc (tx *Transaction) SetSignatureValues(sig []byte) error {\n\ttx.R = sig[:32]\n\ttx.S = sig[32:64]\n\ttx.V = sig[64] + 27\n\treturn nil\n}\n\nfunc (tx *Transaction) SignECDSA(prv *ecdsa.PrivateKey) error {\n\th := tx.Hash()\n\tsig, err := crypto.Sign(h[:], prv)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttx.SetSignatureValues(sig)\n\treturn nil\n}\n\n\/\/ TODO: remove\nfunc (tx *Transaction) RlpData() interface{} {\n\tdata := []interface{}{tx.AccountNonce, tx.Price, tx.GasLimit, tx.Recipient, tx.Amount, tx.Payload}\n\treturn append(data, tx.V, new(big.Int).SetBytes(tx.R).Bytes(), new(big.Int).SetBytes(tx.S).Bytes())\n}\n\nfunc (tx *Transaction) String() string {\n\tvar from, to string\n\tif f, err := tx.From(); err != nil {\n\t\tfrom = \"[invalid sender]\"\n\t} else {\n\t\tfrom = fmt.Sprintf(\"%x\", f[:])\n\t}\n\tif t := tx.To(); t == nil {\n\t\tto = \"[contract creation]\"\n\t} else {\n\t\tto = fmt.Sprintf(\"%x\", t[:])\n\t}\n\tenc, _ := rlp.EncodeToBytes(tx)\n\treturn fmt.Sprintf(`\n\tTX(%x)\n\tContract: %v\n\tFrom:     %s\n\tTo:       %s\n\tNonce:    %v\n\tGasPrice: %v\n\tGasLimit  %v\n\tValue:    %v\n\tData:     0x%x\n\tV:        0x%x\n\tR:        0x%x\n\tS:        0x%x\n\tHex:      %x\n`,\n\t\ttx.Hash(),\n\t\tlen(tx.Recipient) == 0,\n\t\tfrom,\n\t\tto,\n\t\ttx.AccountNonce,\n\t\ttx.Price,\n\t\ttx.GasLimit,\n\t\ttx.Amount,\n\t\ttx.Payload,\n\t\ttx.V,\n\t\ttx.R,\n\t\ttx.S,\n\t\tenc,\n\t)\n}\n\n\/\/ Transaction slice type for basic sorting\ntype Transactions []*Transaction\n\n\/\/ TODO: remove\nfunc (self Transactions) RlpData() interface{} {\n\t\/\/ Marshal the transactions of this block\n\tenc := make([]interface{}, len(self))\n\tfor i, tx := range self {\n\t\t\/\/ Cast it to a string (safe)\n\t\tenc[i] = tx.RlpData()\n\t}\n\n\treturn enc\n}\n\nfunc (s Transactions) Len() int      { return len(s) }\nfunc (s Transactions) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\nfunc (s Transactions) GetRlp(i int) []byte {\n\tenc, _ := rlp.EncodeToBytes(s[i])\n\treturn enc\n}\n\ntype TxByNonce struct{ Transactions }\n\nfunc (s TxByNonce) Less(i, j int) bool {\n\treturn s.Transactions[i].AccountNonce < s.Transactions[j].AccountNonce\n}\n<|endoftext|>"}
{"text":"<commit_before>package reader\n\nimport (\n\t\"encoding\/binary\"\n\t\"io\"\n\t\"reflect\"\n\t\"sync\"\n\n\t\"github.com\/apache\/thrift\/lib\/go\/thrift\"\n\t\"github.com\/xitongsys\/parquet-go\/common\"\n\t\"github.com\/xitongsys\/parquet-go\/layout\"\n\t\"github.com\/xitongsys\/parquet-go\/marshal\"\n\t\"github.com\/xitongsys\/parquet-go\/source\"\n\t\"github.com\/xitongsys\/parquet-go\/schema\"\n\t\"github.com\/xitongsys\/parquet-go\/parquet\"\n)\n\ntype ParquetReader struct {\n\tSchemaHandler *schema.SchemaHandler\n\tNP            int64 \/\/parallel number\n\tFooter        *parquet.FileMetaData\n\tPFile         source.ParquetFile\n\n\tColumnBuffers map[string]*ColumnBufferType\n}\n\n\/\/Create a parquet reader\nfunc NewParquetReader(pFile source.ParquetFile, obj interface{}, np int64) (*ParquetReader, error) {\n\tvar err error\n\tres := new(ParquetReader)\n\tres.NP = np\n\tres.PFile = pFile\n\tif err = res.ReadFooter(); err != nil {\n\t\treturn nil, err\n\t}\n\tres.ColumnBuffers = make(map[string]*ColumnBufferType)\n\n\tif obj != nil {\n\t\tif res.SchemaHandler, err = schema.NewSchemaHandlerFromStruct(obj); err != nil {\n\t\t\treturn res, err\n\t\t}\n\t\tres.RenameSchema()\n\n\t\tfor i := 0; i < len(res.SchemaHandler.SchemaElements); i++ {\n\t\t\tschema := res.SchemaHandler.SchemaElements[i]\n\t\t\tif schema.GetNumChildren() == 0 {\n\t\t\t\tpathStr := res.SchemaHandler.IndexMap[int32(i)]\n\t\t\t\tif res.ColumnBuffers[pathStr], err = NewColumnBuffer(pFile, res.Footer, res.SchemaHandler, pathStr); err != nil {\n\t\t\t\t\treturn res, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn res, nil\n}\n\nfunc (self *ParquetReader) SetSchemaHandlerFromJSON(jsonSchema string) error {\n\tvar err error\n\tif self.SchemaHandler, err = schema.NewSchemaHandlerFromJSON(jsonSchema); err != nil {\n\t\treturn err\n\t}\n\tself.RenameSchema()\n\tfor i := 0; i < len(self.SchemaHandler.SchemaElements); i++ {\n\t\tschemaElement := self.SchemaHandler.SchemaElements[i]\n\t\tif schemaElement.GetNumChildren() == 0 {\n\t\t\tpathStr := self.SchemaHandler.IndexMap[int32(i)]\n\t\t\tif self.ColumnBuffers[pathStr], err = NewColumnBuffer(self.PFile, self.Footer, self.SchemaHandler, pathStr); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/Rename schema name to inname\nfunc (self *ParquetReader) RenameSchema() {\n\tfor i := 0; i < len(self.SchemaHandler.Infos); i++ {\n\t\tself.Footer.Schema[i].Name = self.SchemaHandler.Infos[i].InName\n\t}\n\tfor _, rowGroup := range self.Footer.RowGroups {\n\t\tfor _, chunk := range rowGroup.Columns {\n\t\t\texPath := make([]string, 0)\n\t\t\texPath = append(exPath, self.SchemaHandler.GetRootName())\n\t\t\texPath = append(exPath, chunk.MetaData.GetPathInSchema()...)\n\t\t\texPathStr := common.PathToStr(exPath)\n\n\t\t\tinPathStr := self.SchemaHandler.ExPathToInPath[exPathStr]\n\t\t\tinPath := common.StrToPath(inPathStr)[1:]\n\t\t\tchunk.MetaData.PathInSchema = inPath\n\t\t}\n\t}\n}\n\nfunc (self *ParquetReader) GetNumRows() int64 {\n\treturn self.Footer.GetNumRows()\n}\n\n\/\/Get the footer size\nfunc (self *ParquetReader) GetFooterSize() (uint32, error) {\n\tvar err error\n\tbuf := make([]byte, 4)\n\tif _, err = self.PFile.Seek(-8, io.SeekEnd); err != nil {\n\t\treturn 0, err\n\t}\n\tif _, err = self.PFile.Read(buf); err != nil {\n\t\treturn 0, err\n\t}\n\tsize := binary.LittleEndian.Uint32(buf)\n\treturn size, err\n}\n\n\/\/Read footer from parquet file\nfunc (self *ParquetReader) ReadFooter() error {\n\tsize, err := self.GetFooterSize()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err = self.PFile.Seek(-(int64)(8+size), io.SeekEnd); err != nil {\n\t\treturn err\n\t}\n\tself.Footer = parquet.NewFileMetaData()\n\tpf := thrift.NewTCompactProtocolFactory()\n\tprotocol := pf.GetProtocol(thrift.NewStreamTransportR(self.PFile))\n\treturn self.Footer.Read(protocol)\n}\n\n\/\/Skip rows of parquet file\nfunc (self *ParquetReader) SkipRows(num int64) error {\n\tvar err error\n\tif num <= 0 {\n\t\treturn nil\n\t}\n\tdoneChan := make(chan int, self.NP)\n\ttaskChan := make(chan string, len(self.SchemaHandler.ValueColumns))\n\tstopChan := make(chan int)\n\n\tfor _, pathStr := range self.SchemaHandler.ValueColumns {\n\t\tif _, ok := self.ColumnBuffers[pathStr]; !ok {\n\t\t\tif self.ColumnBuffers[pathStr], err = NewColumnBuffer(self.PFile, self.Footer, self.SchemaHandler, pathStr); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := int64(0); i < self.NP; i++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-stopChan:\n\t\t\t\t\treturn\n\t\t\t\tcase pathStr := <-taskChan:\n\t\t\t\t\tcb := self.ColumnBuffers[pathStr]\n\t\t\t\t\tcb.SkipRows(int64(num))\n\t\t\t\t\tdoneChan <- 0\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor key, _ := range self.ColumnBuffers {\n\t\ttaskChan <- key\n\t}\n\n\tfor i := 0; i < len(self.ColumnBuffers); i++ {\n\t\t<-doneChan\n\t}\n\tfor i := int64(0); i < self.NP; i++ {\n\t\tstopChan <- 0\n\t}\n\treturn err\n}\n\n\/\/Read rows of parquet file and unmarshal all to dst\nfunc (self *ParquetReader) Read(dstInterface interface{}) error {\n\treturn self.read(dstInterface, \"\")\n}\n\n\/\/Read rows of parquet file and unmarshal all to dst\nfunc (self *ParquetReader) ReadPartial(dstInterface interface{}, prefixPath string) error {\n\tprefixPath, err := self.SchemaHandler.ConvertToInPathStr(prefixPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\treturn self.read(dstInterface, prefixPath)\n}\n\n\/\/Read rows of parquet file\nfunc (self *ParquetReader) read(dstInterface interface{}, prefixPath string) error {\n\tvar err error\n\ttmap := make(map[string]*layout.Table)\n\tlocker := new(sync.Mutex)\n\tot := reflect.TypeOf(dstInterface).Elem().Elem()\n\tnum := reflect.ValueOf(dstInterface).Elem().Len()\n\tif num <= 0 {\n\t\treturn nil\n\t}\n\n\tdoneChan := make(chan int, self.NP)\n\ttaskChan := make(chan string, len(self.ColumnBuffers))\n\tstopChan := make(chan int)\n\n\tfor i := int64(0); i < self.NP; i++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-stopChan:\n\t\t\t\t\treturn\n\t\t\t\tcase pathStr := <-taskChan:\n\t\t\t\t\tcb := self.ColumnBuffers[pathStr]\n\t\t\t\t\ttable, _ := cb.ReadRows(int64(num))\n\t\t\t\t\tlocker.Lock()\n\t\t\t\t\tif _, ok := tmap[pathStr]; ok {\n\t\t\t\t\t\ttmap[pathStr].Merge(table)\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttmap[pathStr] = layout.NewTableFromTable(table)\n\t\t\t\t\t\ttmap[pathStr].Merge(table)\n\t\t\t\t\t}\n\t\t\t\t\tlocker.Unlock()\n\t\t\t\t\tdoneChan <- 0\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\tfor key, _ := range self.ColumnBuffers {\n\t\ttaskChan <- key\n\t}\n\tfor i := 0; i < len(self.ColumnBuffers); i++ {\n\t\t<-doneChan\n\t}\n\tfor i := int64(0); i < self.NP; i++ {\n\t\tstopChan <- 0\n\t}\n\n\tdstList := make([]interface{}, self.NP)\n\tdelta := (int64(num) + self.NP - 1) \/ self.NP\n\n\tdoneChan = make(chan int)\n\tfor c := int64(0); c < self.NP; c++ {\n\t\tbgn := c * delta\n\t\tend := bgn + delta\n\t\tif end > int64(num) {\n\t\t\tend = int64(num)\n\t\t}\n\t\tif bgn >= int64(num) {\n\t\t\tbgn, end = int64(num), int64(num)\n\t\t}\n\t\tgo func(b, e, index int) {\n\t\t\tdstList[index] = reflect.New(reflect.SliceOf(ot)).Interface()\n\t\t\tif err2 := marshal.Unmarshal(&tmap, b, e, dstList[index], self.SchemaHandler, prefixPath); err2 != nil {\n\t\t\t\terr = err2\n\t\t\t}\n\t\t\tdoneChan <- 0\n\t\t}(int(bgn), int(end), int(c))\n\t}\n\tfor c := int64(0); c < self.NP; c++ {\n\t\t<-doneChan\n\t}\n\n\tresTmp := reflect.MakeSlice(reflect.SliceOf(ot), 0, num)\n\tfor _, dst := range dstList {\n\t\tresTmp = reflect.AppendSlice(resTmp, reflect.ValueOf(dst).Elem())\n\t}\n\treflect.ValueOf(dstInterface).Elem().Set(resTmp)\n\treturn err\n}\n\n\/\/Stop Read\nfunc (self *ParquetReader) ReadStop() {\n\tfor _, cb := range self.ColumnBuffers {\n\t\tif cb != nil {\n\t\t\tcb.PFile.Close()\n\t\t}\n\t}\n}\n<commit_msg>updating<commit_after>package reader\n\nimport (\n\t\"encoding\/binary\"\n\t\"io\"\n\t\"reflect\"\n\t\"sync\"\n\t\"strings\"\n\n\t\"github.com\/apache\/thrift\/lib\/go\/thrift\"\n\t\"github.com\/xitongsys\/parquet-go\/common\"\n\t\"github.com\/xitongsys\/parquet-go\/layout\"\n\t\"github.com\/xitongsys\/parquet-go\/marshal\"\n\t\"github.com\/xitongsys\/parquet-go\/source\"\n\t\"github.com\/xitongsys\/parquet-go\/schema\"\n\t\"github.com\/xitongsys\/parquet-go\/parquet\"\n)\n\ntype ParquetReader struct {\n\tSchemaHandler *schema.SchemaHandler\n\tNP            int64 \/\/parallel number\n\tFooter        *parquet.FileMetaData\n\tPFile         source.ParquetFile\n\n\tColumnBuffers map[string]*ColumnBufferType\n}\n\n\/\/Create a parquet reader\nfunc NewParquetReader(pFile source.ParquetFile, obj interface{}, np int64) (*ParquetReader, error) {\n\tvar err error\n\tres := new(ParquetReader)\n\tres.NP = np\n\tres.PFile = pFile\n\tif err = res.ReadFooter(); err != nil {\n\t\treturn nil, err\n\t}\n\tres.ColumnBuffers = make(map[string]*ColumnBufferType)\n\n\tif obj != nil {\n\t\tif res.SchemaHandler, err = schema.NewSchemaHandlerFromStruct(obj); err != nil {\n\t\t\treturn res, err\n\t\t}\n\t\tres.RenameSchema()\n\n\t\tfor i := 0; i < len(res.SchemaHandler.SchemaElements); i++ {\n\t\t\tschema := res.SchemaHandler.SchemaElements[i]\n\t\t\tif schema.GetNumChildren() == 0 {\n\t\t\t\tpathStr := res.SchemaHandler.IndexMap[int32(i)]\n\t\t\t\tif res.ColumnBuffers[pathStr], err = NewColumnBuffer(pFile, res.Footer, res.SchemaHandler, pathStr); err != nil {\n\t\t\t\t\treturn res, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn res, nil\n}\n\nfunc (self *ParquetReader) SetSchemaHandlerFromJSON(jsonSchema string) error {\n\tvar err error\n\tif self.SchemaHandler, err = schema.NewSchemaHandlerFromJSON(jsonSchema); err != nil {\n\t\treturn err\n\t}\n\tself.RenameSchema()\n\tfor i := 0; i < len(self.SchemaHandler.SchemaElements); i++ {\n\t\tschemaElement := self.SchemaHandler.SchemaElements[i]\n\t\tif schemaElement.GetNumChildren() == 0 {\n\t\t\tpathStr := self.SchemaHandler.IndexMap[int32(i)]\n\t\t\tif self.ColumnBuffers[pathStr], err = NewColumnBuffer(self.PFile, self.Footer, self.SchemaHandler, pathStr); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/Rename schema name to inname\nfunc (self *ParquetReader) RenameSchema() {\n\tfor i := 0; i < len(self.SchemaHandler.Infos); i++ {\n\t\tself.Footer.Schema[i].Name = self.SchemaHandler.Infos[i].InName\n\t}\n\tfor _, rowGroup := range self.Footer.RowGroups {\n\t\tfor _, chunk := range rowGroup.Columns {\n\t\t\texPath := make([]string, 0)\n\t\t\texPath = append(exPath, self.SchemaHandler.GetRootName())\n\t\t\texPath = append(exPath, chunk.MetaData.GetPathInSchema()...)\n\t\t\texPathStr := common.PathToStr(exPath)\n\n\t\t\tinPathStr := self.SchemaHandler.ExPathToInPath[exPathStr]\n\t\t\tinPath := common.StrToPath(inPathStr)[1:]\n\t\t\tchunk.MetaData.PathInSchema = inPath\n\t\t}\n\t}\n}\n\nfunc (self *ParquetReader) GetNumRows() int64 {\n\treturn self.Footer.GetNumRows()\n}\n\n\/\/Get the footer size\nfunc (self *ParquetReader) GetFooterSize() (uint32, error) {\n\tvar err error\n\tbuf := make([]byte, 4)\n\tif _, err = self.PFile.Seek(-8, io.SeekEnd); err != nil {\n\t\treturn 0, err\n\t}\n\tif _, err = self.PFile.Read(buf); err != nil {\n\t\treturn 0, err\n\t}\n\tsize := binary.LittleEndian.Uint32(buf)\n\treturn size, err\n}\n\n\/\/Read footer from parquet file\nfunc (self *ParquetReader) ReadFooter() error {\n\tsize, err := self.GetFooterSize()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err = self.PFile.Seek(-(int64)(8+size), io.SeekEnd); err != nil {\n\t\treturn err\n\t}\n\tself.Footer = parquet.NewFileMetaData()\n\tpf := thrift.NewTCompactProtocolFactory()\n\tprotocol := pf.GetProtocol(thrift.NewStreamTransportR(self.PFile))\n\treturn self.Footer.Read(protocol)\n}\n\n\/\/Skip rows of parquet file\nfunc (self *ParquetReader) SkipRows(num int64) error {\n\tvar err error\n\tif num <= 0 {\n\t\treturn nil\n\t}\n\tdoneChan := make(chan int, self.NP)\n\ttaskChan := make(chan string, len(self.SchemaHandler.ValueColumns))\n\tstopChan := make(chan int)\n\n\tfor _, pathStr := range self.SchemaHandler.ValueColumns {\n\t\tif _, ok := self.ColumnBuffers[pathStr]; !ok {\n\t\t\tif self.ColumnBuffers[pathStr], err = NewColumnBuffer(self.PFile, self.Footer, self.SchemaHandler, pathStr); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tfor i := int64(0); i < self.NP; i++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-stopChan:\n\t\t\t\t\treturn\n\t\t\t\tcase pathStr := <-taskChan:\n\t\t\t\t\tcb := self.ColumnBuffers[pathStr]\n\t\t\t\t\tcb.SkipRows(int64(num))\n\t\t\t\t\tdoneChan <- 0\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\tfor key, _ := range self.ColumnBuffers {\n\t\ttaskChan <- key\n\t}\n\n\tfor i := 0; i < len(self.ColumnBuffers); i++ {\n\t\t<-doneChan\n\t}\n\tfor i := int64(0); i < self.NP; i++ {\n\t\tstopChan <- 0\n\t}\n\treturn err\n}\n\n\/\/Read rows of parquet file and unmarshal all to dst\nfunc (self *ParquetReader) Read(dstInterface interface{}) error {\n\treturn self.read(dstInterface, \"\")\n}\n\n\/\/Read rows of parquet file and unmarshal all to dst\nfunc (self *ParquetReader) ReadPartial(dstInterface interface{}, prefixPath string) error {\n\tprefixPath, err := self.SchemaHandler.ConvertToInPathStr(prefixPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\n\treturn self.read(dstInterface, prefixPath)\n}\n\n\/\/Read rows of parquet file\nfunc (self *ParquetReader) read(dstInterface interface{}, prefixPath string) error {\n\tvar err error\n\ttmap := make(map[string]*layout.Table)\n\tlocker := new(sync.Mutex)\n\tot := reflect.TypeOf(dstInterface).Elem().Elem()\n\tnum := reflect.ValueOf(dstInterface).Elem().Len()\n\tif num <= 0 {\n\t\treturn nil\n\t}\n\n\tdoneChan := make(chan int, self.NP)\n\ttaskChan := make(chan string, len(self.ColumnBuffers))\n\tstopChan := make(chan int)\n\n\tfor i := int64(0); i < self.NP; i++ {\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-stopChan:\n\t\t\t\t\treturn\n\t\t\t\tcase pathStr := <-taskChan:\n\t\t\t\t\tcb := self.ColumnBuffers[pathStr]\n\t\t\t\t\ttable, _ := cb.ReadRows(int64(num))\n\t\t\t\t\tlocker.Lock()\n\t\t\t\t\tif _, ok := tmap[pathStr]; ok {\n\t\t\t\t\t\ttmap[pathStr].Merge(table)\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttmap[pathStr] = layout.NewTableFromTable(table)\n\t\t\t\t\t\ttmap[pathStr].Merge(table)\n\t\t\t\t\t}\n\t\t\t\t\tlocker.Unlock()\n\t\t\t\t\tdoneChan <- 0\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t}\n\n\treadNum := 0\n\tfor key, _ := range self.ColumnBuffers {\n\t\tif strings.HasPrefix(key, prefixPath) {\n\t\t\ttaskChan <- key\n\t\t\treadNum++\n\t\t}\n\t}\n\tfor i := 0; i < readNum; i++ {\n\t\t<-doneChan\n\t}\n\n\tfor i := int64(0); i < self.NP; i++ {\n\t\tstopChan <- 0\n\t}\n\n\tdstList := make([]interface{}, self.NP)\n\tdelta := (int64(num) + self.NP - 1) \/ self.NP\n\n\tdoneChan = make(chan int)\n\tfor c := int64(0); c < self.NP; c++ {\n\t\tbgn := c * delta\n\t\tend := bgn + delta\n\t\tif end > int64(num) {\n\t\t\tend = int64(num)\n\t\t}\n\t\tif bgn >= int64(num) {\n\t\t\tbgn, end = int64(num), int64(num)\n\t\t}\n\t\tgo func(b, e, index int) {\n\t\t\tdstList[index] = reflect.New(reflect.SliceOf(ot)).Interface()\n\t\t\tif err2 := marshal.Unmarshal(&tmap, b, e, dstList[index], self.SchemaHandler, prefixPath); err2 != nil {\n\t\t\t\terr = err2\n\t\t\t}\n\t\t\tdoneChan <- 0\n\t\t}(int(bgn), int(end), int(c))\n\t}\n\tfor c := int64(0); c < self.NP; c++ {\n\t\t<-doneChan\n\t}\n\n\tresTmp := reflect.MakeSlice(reflect.SliceOf(ot), 0, num)\n\tfor _, dst := range dstList {\n\t\tresTmp = reflect.AppendSlice(resTmp, reflect.ValueOf(dst).Elem())\n\t}\n\treflect.ValueOf(dstInterface).Elem().Set(resTmp)\n\treturn err\n}\n\n\/\/Stop Read\nfunc (self *ParquetReader) ReadStop() {\n\tfor _, cb := range self.ColumnBuffers {\n\t\tif cb != nil {\n\t\t\tcb.PFile.Close()\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package notificationcenter\n\nimport (\n\t\"context\"\n\t\"reflect\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"github.com\/geniusrabbit\/notificationcenter\/v2\/decoder\"\n)\n\nvar errInvalidReturnType = errors.New(\"invalid return types\")\n\n\/\/ ReceiverFrom converts income handler type to Receiver interface\nfunc ReceiverFrom(handler any) Receiver {\n\tswitch h := handler.(type) {\n\tcase Receiver:\n\t\treturn h\n\tcase func() error:\n\t\treturn FuncReceiver(func(msg Message) error { h(); return msg.Ack() })\n\tcase func(msg Message) error:\n\t\treturn FuncReceiver(h)\n\tcase func(ctx context.Context, msg Message) error:\n\t\treturn FuncReceiver(func(msg Message) error { return h(msg.Context(), msg) })\n\tdefault:\n\t\treturn ExtFuncReceiver(h)\n\t}\n}\n\nvar (\n\terrorType   = reflect.TypeOf((*error)(nil)).Elem()\n\tcontextType = reflect.TypeOf((*context.Context)(nil)).Elem()\n\tmsgType     = reflect.TypeOf((*Message)(nil)).Elem()\n)\n\n\/\/ ExtFuncReceiver wraps function argument with arbitrary input data type\nfunc ExtFuncReceiver(f any, decs ...decoder.Decoder) Receiver {\n\tfv := reflect.ValueOf(f)\n\tif fv.Kind() != reflect.Func {\n\t\tpanic(\"argument must be a function\")\n\t}\n\tdec := decoder.JSON\n\tif len(decs) > 0 && decs[0] != nil {\n\t\tdec = decs[0]\n\t}\n\tvar (\n\t\tft        = fv.Type()\n\t\targMapper = make([]func(Message) (reflect.Value, error), 0, ft.NumIn())\n\t\tretMapper = make([]func(reflect.Value) error, 0, ft.NumOut())\n\t)\n\tfor i := 0; i < ft.NumIn(); i++ {\n\t\tinType := ft.In(i)\n\t\tswitch inType {\n\t\tcase contextType:\n\t\t\targMapper = append(argMapper, func(msg Message) (reflect.Value, error) {\n\t\t\t\treturn reflect.ValueOf(msg.Context()), nil\n\t\t\t})\n\t\tcase msgType:\n\t\t\targMapper = append(argMapper, func(msg Message) (reflect.Value, error) {\n\t\t\t\treturn reflect.ValueOf(msg), nil\n\t\t\t})\n\t\tdefault:\n\t\t\targMapper = append(argMapper, func(msg Message) (reflect.Value, error) {\n\t\t\t\tnewValue, newValueI := newValue(inType)\n\t\t\t\terr := dec(msg.Body(), newValueI)\n\t\t\t\treturn newValue, err\n\t\t\t})\n\t\t}\n\t}\n\tfor i := 0; i < ft.NumOut(); i++ {\n\t\toutType := ft.Out(i)\n\t\tswitch outType {\n\t\tcase errorType:\n\t\t\tretMapper = append(retMapper, func(v reflect.Value) error {\n\t\t\t\tif v.IsNil() {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn v.Interface().(error)\n\t\t\t})\n\t\tdefault:\n\t\t\tpanic(errInvalidReturnType)\n\t\t}\n\t}\n\treturn FuncReceiver(func(msg Message) error {\n\t\targs := make([]reflect.Value, 0, len(argMapper))\n\t\tfor _, fm := range argMapper {\n\t\t\targ, err := fm(msg)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\targs = append(args, arg)\n\t\t}\n\t\tretVals := fv.Call(args)\n\t\tfor i, fr := range retMapper {\n\t\t\tif err := fr(retVals[i]); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc newValue(t reflect.Type) (reflect.Value, any) {\n\tif t.Kind() == reflect.Ptr {\n\t\treturn newValue(t.Elem())\n\t}\n\tv := reflect.New(t)\n\ti := v.Interface()\n\treturn v, i\n}\n<commit_msg>Fix lint errors<commit_after>package notificationcenter\n\nimport (\n\t\"context\"\n\t\"reflect\"\n\n\t\"github.com\/pkg\/errors\"\n\n\t\"github.com\/geniusrabbit\/notificationcenter\/v2\/decoder\"\n)\n\nvar errInvalidReturnType = errors.New(\"invalid return types\")\n\n\/\/ ReceiverFrom converts income handler type to Receiver interface\nfunc ReceiverFrom(handler any) Receiver {\n\tswitch h := handler.(type) {\n\tcase Receiver:\n\t\treturn h\n\tcase func() error:\n\t\treturn FuncReceiver(func(msg Message) error {\n\t\t\tif err := h(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn msg.Ack()\n\t\t})\n\tcase func(msg Message) error:\n\t\treturn FuncReceiver(h)\n\tcase func(ctx context.Context, msg Message) error:\n\t\treturn FuncReceiver(func(msg Message) error { return h(msg.Context(), msg) })\n\tdefault:\n\t\treturn ExtFuncReceiver(h)\n\t}\n}\n\nvar (\n\terrorType   = reflect.TypeOf((*error)(nil)).Elem()\n\tcontextType = reflect.TypeOf((*context.Context)(nil)).Elem()\n\tmsgType     = reflect.TypeOf((*Message)(nil)).Elem()\n)\n\n\/\/ ExtFuncReceiver wraps function argument with arbitrary input data type\nfunc ExtFuncReceiver(f any, decs ...decoder.Decoder) Receiver {\n\tfv := reflect.ValueOf(f)\n\tif fv.Kind() != reflect.Func {\n\t\tpanic(\"argument must be a function\")\n\t}\n\tdec := decoder.JSON\n\tif len(decs) > 0 && decs[0] != nil {\n\t\tdec = decs[0]\n\t}\n\tvar (\n\t\tft        = fv.Type()\n\t\targMapper = make([]func(Message) (reflect.Value, error), 0, ft.NumIn())\n\t\tretMapper = make([]func(reflect.Value) error, 0, ft.NumOut())\n\t)\n\tfor i := 0; i < ft.NumIn(); i++ {\n\t\tinType := ft.In(i)\n\t\tswitch inType {\n\t\tcase contextType:\n\t\t\targMapper = append(argMapper, func(msg Message) (reflect.Value, error) {\n\t\t\t\treturn reflect.ValueOf(msg.Context()), nil\n\t\t\t})\n\t\tcase msgType:\n\t\t\targMapper = append(argMapper, func(msg Message) (reflect.Value, error) {\n\t\t\t\treturn reflect.ValueOf(msg), nil\n\t\t\t})\n\t\tdefault:\n\t\t\targMapper = append(argMapper, func(msg Message) (reflect.Value, error) {\n\t\t\t\tnewValue, newValueI := newValue(inType)\n\t\t\t\terr := dec(msg.Body(), newValueI)\n\t\t\t\treturn newValue, err\n\t\t\t})\n\t\t}\n\t}\n\tfor i := 0; i < ft.NumOut(); i++ {\n\t\toutType := ft.Out(i)\n\t\tswitch outType {\n\t\tcase errorType:\n\t\t\tretMapper = append(retMapper, func(v reflect.Value) error {\n\t\t\t\tif v.IsNil() {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn v.Interface().(error)\n\t\t\t})\n\t\tdefault:\n\t\t\tpanic(errInvalidReturnType)\n\t\t}\n\t}\n\treturn FuncReceiver(func(msg Message) error {\n\t\targs := make([]reflect.Value, 0, len(argMapper))\n\t\tfor _, fm := range argMapper {\n\t\t\targ, err := fm(msg)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\targs = append(args, arg)\n\t\t}\n\t\tretVals := fv.Call(args)\n\t\tfor i, fr := range retMapper {\n\t\t\tif err := fr(retVals[i]); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}\n\nfunc newValue(t reflect.Type) (reflect.Value, any) {\n\tif t.Kind() == reflect.Ptr {\n\t\treturn newValue(t.Elem())\n\t}\n\tv := reflect.New(t)\n\ti := v.Interface()\n\treturn v, i\n}\n<|endoftext|>"}
{"text":"<commit_before>package refctx\n\nimport (\n\t\"context\"\n\t\"sync\/atomic\"\n)\n\n\/\/ RefCtr cancels a context when no references are held\ntype RefCtr struct {\n\tcancel context.CancelFunc\n\trefcnt int32\n}\n\n\/\/ Incr increments the refcount\nfunc (r *RefCtr) Incr() { r.Add(1) }\n\n\/\/ Add i refcounts\nfunc (r *RefCtr) Add(i int32) {\n\tif v := atomic.AddInt32(&r.refcnt, i); v <= 0 {\n\t\tr.cancel()\n\t}\n}\n\n\/\/ Decr decrements the refcount\nfunc (r *RefCtr) Decr() { r.Add(-1) }\n\n\/\/ WithRefCount derives a context that will be cancelled when all references are\n\/\/ freed.\nfunc WithRefCount(c context.Context) (context.Context, *RefCtr) {\n\tc, cancel := context.WithCancel(c)\n\treturn c, &RefCtr{cancel: cancel}\n}\n<commit_msg>Use uint32 for Refctr WithRefCount now accepts a ctx.Doner Add ContextWithRefcount, which accepts a context.Context<commit_after>package refctx\n\nimport (\n\t\"context\"\n\t\"sync\/atomic\"\n\n\t\"github.com\/SentimensRG\/ctx\"\n)\n\n\/\/ RefCtr cancels a context when no references are held\ntype RefCtr struct {\n\tcancel func()\n\trefcnt uint32\n}\n\n\/\/ Incr increments the refcount\nfunc (r *RefCtr) Incr() { r.Add(1) }\n\n\/\/ Add i refcounts\nfunc (r *RefCtr) Add(i uint32) {\n\tif v := atomic.AddUint32(&r.refcnt, i); v == 0 {\n\t\tr.cancel()\n\t}\n}\n\n\/\/ Decr decrements the refcount\nfunc (r *RefCtr) Decr() { atomic.AddUint32(&r.refcnt, ^uint32(0)) }\n\n\/\/ WithRefCount derives a ctx.C that will be cancelled when all references are\n\/\/ freed\nfunc WithRefCount(d ctx.Doner) (ctx.C, *RefCtr) {\n\tch, cancel := ctx.WithCancel(d)\n\treturn ch, &RefCtr{cancel: cancel}\n}\n\n\/\/ ContextWithRefCount derives a context that will be cancelled when all\n\/\/ references are freed.\nfunc ContextWithRefCount(c context.Context) (context.Context, *RefCtr) {\n\tc, cancel := context.WithCancel(c)\n\treturn c, &RefCtr{cancel: cancel}\n}\n<|endoftext|>"}
{"text":"<commit_before>package checksum_generator\n\nimport (\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\ntype ChecksumRecord struct {\n\tChecksum string    `json:\"checksum\"`\n\tModTime  time.Time `json:\"mod_time\"`\n}\n\ntype DirectoryManifest struct {\n\tPath      string                    `json:\"path\"`\n\tCreatedAt time.Time                 `json:\"created_at\"`\n\tEntries   map[string]ChecksumRecord `json:\"entries\"`\n}\n\nfunc FileChecksum(file string) ChecksumRecord {\n\tfi, err := os.Stat(file)\n\tcheck(err)\n\n\tsum := generateChecksum(file)\n\treturn ChecksumRecord{\n\t\tChecksum: sum,\n\t\tModTime:  fi.ModTime(),\n\t}\n}\n\nfunc GenerateDirectoryManifest(path string) DirectoryManifest {\n\treturn DirectoryManifest{\n\t\tPath:      path,\n\t\tCreatedAt: time.Now(),\n\t\tEntries:   directoryChecksums(path),\n\t}\n}\n\n\/\/ Private functions\n\nfunc generateChecksum(file string) string {\n\tdata, err := ioutil.ReadFile(file)\n\tcheck(err)\n\n\tsum := sha1.Sum(data)\n\treturn hex.EncodeToString(sum[:])\n}\n\nfunc directoryChecksums(path string) map[string]ChecksumRecord {\n\trecords := map[string]ChecksumRecord{}\n\tfilepath.Walk(path, func(entryPath string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif info.Mode().IsRegular() {\n\t\t\tvar relPath string\n\t\t\trelPath, err = filepath.Rel(path, entryPath)\n\t\t\tcheck(err)\n\t\t\trecords[relPath] = FileChecksum(entryPath)\n\t\t}\n\n\t\treturn nil\n\t})\n\treturn records\n}\n\nfunc check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n<commit_msg>Use mod time from filepath walker<commit_after>package checksum_generator\n\nimport (\n\t\"crypto\/sha1\"\n\t\"encoding\/hex\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\ntype ChecksumRecord struct {\n\tChecksum string    `json:\"checksum\"`\n\tModTime  time.Time `json:\"mod_time\"`\n}\n\ntype DirectoryManifest struct {\n\tPath      string                    `json:\"path\"`\n\tCreatedAt time.Time                 `json:\"created_at\"`\n\tEntries   map[string]ChecksumRecord `json:\"entries\"`\n}\n\nfunc FileChecksum(file string) ChecksumRecord {\n\tfi, err := os.Stat(file)\n\tcheck(err)\n\n\tsum := generateChecksum(file)\n\treturn ChecksumRecord{\n\t\tChecksum: sum,\n\t\tModTime:  fi.ModTime(),\n\t}\n}\n\nfunc GenerateDirectoryManifest(path string) DirectoryManifest {\n\treturn DirectoryManifest{\n\t\tPath:      path,\n\t\tCreatedAt: time.Now(),\n\t\tEntries:   directoryChecksums(path),\n\t}\n}\n\n\/\/ Private functions\n\nfunc generateChecksum(file string) string {\n\tdata, err := ioutil.ReadFile(file)\n\tcheck(err)\n\n\tsum := sha1.Sum(data)\n\treturn hex.EncodeToString(sum[:])\n}\n\nfunc directoryChecksums(path string) map[string]ChecksumRecord {\n\trecords := map[string]ChecksumRecord{}\n\tfilepath.Walk(path, func(entryPath string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif info.Mode().IsRegular() {\n\t\t\tvar relPath string\n\t\t\trelPath, err = filepath.Rel(path, entryPath)\n\t\t\tcheck(err)\n\t\t\trecords[relPath] = ChecksumRecord{\n\t\t\t\tChecksum: generateChecksum(entryPath),\n\t\t\t\tModTime:  info.ModTime(),\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\treturn records\n}\n\nfunc check(e error) {\n\tif e != nil {\n\t\tpanic(e)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package hepmc\n\n\/\/ Event represents a record for MC generators (for use at any stage of generation)\n\/\/\n\/\/ This type is intended as both a \"container class\" ( to store a MC\n\/\/  event for interface between MC generators and detector simulation )\n\/\/  and also as a \"work in progress class\" ( that could be used inside\n\/\/  a generator and modified as the event is built ).\ntype Event struct {\n\tSignalProcessId int     \/\/ id of the signal process\n\tEventNumber     int     \/\/ event number\n\tMpi             int     \/\/ number of multi particle interactions\n\tScale           float64 \/\/ energy scale,\n\tAlphaQCD        float64 \/\/ QCD coupling, see hep-ph\/0109068\n\tAlphaQED        float64 \/\/ QED coupling, see hep-ph\/0109068\n\n\tSignalVertex *Vertex      \/\/ signal vertex\n\tBeams        [2]*Particle \/\/ incoming beams\n\tWeights      Weights      \/\/ weights for this event. first weight is used by default for hit and miss\n\tRandomStates []int64      \/\/ container of random number generator states\n\n\tVertices  map[int]*Vertex\n\tParticles map[int]*Particle\n\n\tCrossSection *CrossSection\n\tHeavyIon     *HeavyIon\n\tPdfInfo      *PdfInfo\n\tMomentumUnit MomentumUnit\n\tLengthUnit   LengthUnit\n}\n\n\/\/ Particle represents a generator particle within an event coming in\/out of a vertex\n\/\/\n\/\/ Particle is the basic building block of the event record\ntype Particle struct {\n\tMomentum      FourVector   \/\/ momentum vector\n\tPdgId         int          \/\/ id according to PDG convention\n\tStatus        int          \/\/ status code as defined for HEPEVT\n\tFlow          Flow         \/\/ flow of this particle\n\tPolarization  Polarization \/\/ polarization of this particle\n\tProdVertex    *Vertex      \/\/ pointer to production vertex (nil if vacuum or beam)\n\tEndVertex     *Vertex      \/\/ pointer to decay vertex (nil if not-decayed)\n\tBarcode       int          \/\/ unique identifier in the event\n\tGeneratedMass float64      \/\/ mass of this particle when it was generated\n}\n\n\/\/ Vertex represents a generator vertex within an event\n\/\/ A vertex is indirectly (via particle \"edges\") linked to other\n\/\/   vertices (\"nodes\") to form a composite \"graph\"\ntype Vertex struct {\n\tPosition     FourVector  \/\/ 4-vector of vertex [mm]\n\tParticlesIn  []*Particle \/\/ all incoming particles\n\tParticlesOut []*Particle \/\/ all outgoing particles\n\tId           int         \/\/ vertex id\n\tWeights      Weights     \/\/ weights for this vertex\n\tEvent        *Event      \/\/ pointer to event owning this vertex\n\tBarcode      int         \/\/ unique identifier in the event\n}\n\ntype HeavyIon struct {\n\tNcoll_hard                   int     \/\/ number of hard scatterings\n\tNpart_proj                   int     \/\/ number of projectile participants\n\tNpart_targ                   int     \/\/ number of target participants\n\tNcoll                        int     \/\/ number of NN (nucleon-nucleon) collisions\n\tN_Nwounded_collisions        int     \/\/ Number of N-Nwounded collisions\n\tNwounded_N_collisions        int     \/\/ Number of Nwounded-N collisons\n\tNwounded_Nwounded_collisions int     \/\/ Number of Nwounded-Nwounded collisions\n\tSpectator_neutrons           int     \/\/ Number of spectators neutrons\n\tSpectator_protons            int     \/\/ Number of spectators protons\n\tImpact_parameter             float32 \/\/ Impact Parameter(fm) of collision\n\tEvent_plane_angle            float32 \/\/ Azimuthal angle of event plane\n\tEccentricity                 float32 \/\/ eccentricity of participating nucleons in the transverse plane (as in phobos nucl-ex\/0510031)\n\tSigma_inel_NN                float32 \/\/ nucleon-nucleon inelastic (including diffractive) cross-section\n}\n\n\/\/ CrossSection is used to store the generated cross section.\n\/\/ This type is meant to be used to pass, on an event by event basis,\n\/\/ the current best guess of the total cross section.\n\/\/ It is expected that the final cross section will be stored elsewhere.\ntype CrossSection struct {\n\tValue float64 \/\/ value of the cross-section (in pb)\n\tError float64 \/\/ error on the value of the cross-section (in pb)\n\t\/\/IsSet bool\n}\n\ntype PdfInfo struct {\n\tId1      int     \/\/ flavour code of first parton\n\tId2      int     \/\/ flavour code of second parton\n\tLHAPdf1  int     \/\/ LHA PDF id of first parton\n\tLHAPdf2  int     \/\/ LHA PDF id of second parton\n\tX1       float64 \/\/ fraction of beam momentum carried by first parton (\"beam side\")\n\tX2       float64 \/\/ fraction of beam momentum carried by second parton (\"target side\")\n\tScalePDF float64 \/\/  Q-scale used in evaluation of PDF's   (in GeV)\n\tPdf1     float64 \/\/ PDF (id1, x1, Q)\n\tPdf2     float64 \/\/ PDF (id2, x2, Q)\n}\n\n\/\/ Flow represents a particle's flow and keeps track of an arbitrary number of flow patterns within a graph (i.e. color flow, charge flow, lepton number flow,...)\n\/\/\n\/\/ Flow patterns are coded with an integer, in the same manner as in Herwig.\n\/\/ Note: 0 is NOT allowed as code index nor as flow code since it\n\/\/       is used to indicate null.\n\/\/\n\/\/ This class can be used to keep track of flow patterns within\n\/\/  a graph. An example is color flow. If we have two quarks going through\n\/\/  an s-channel gluon to form two more quarks:\n\/\/\n\/\/  \\q1       \/q3   then we can keep track of the color flow with the\n\/\/   \\_______\/      HepMC::Flow class as follows:\n\/\/   \/   g   \\.\n\/\/  \/q2       \\q4\n\/\/\n\/\/  lets say the color flows from q2-->g-->q3  and q1-->g-->q4\n\/\/  the individual colors are unimportant, but the flow pattern is.\n\/\/  We can capture this flow by assigning the first pattern (q2-->g-->q3)\n\/\/  a unique (arbitrary) flow code 678 and the second pattern (q1-->g-->q4)\n\/\/  flow code 269  ( you can ask HepMC::Flow to choose\n\/\/  a unique code for you using Flow::set_unique_icode() ).\n\/\/  these codes with the particles as follows:\n\/\/    q2->flow().set_icode(1,678);\n\/\/    g->flow().set_icode(1,678);\n\/\/    q3->flow().set_icode(1,678);\n\/\/    q1->flow().set_icode(1,269);\n\/\/    g->flow().set_icode(2,269);\n\/\/    q4->flow().set_icode(1,269);\n\/\/  later on if we wish to know the color partner of q1 we can ask for a list\n\/\/  of all particles connected via this code to q1 which do have less than\n\/\/  2 color partners using:\n\/\/    vector<GenParticle*> result=q1->dangling_connected_partners(q1->icode(1),1,2);\n\/\/  this will return a list containing q1 and q4.\n\/\/    vector<GenParticle*> result=q1->connected_partners(q1->icode(1),1,2);\n\/\/  would return a list containing q1, g, and q4.\ntype Flow struct {\n\tParticle *Particle   \/\/ the particle this flow describes\n\tIcode    map[int]int \/\/ flow patterns as (code_index, icode)\n}\n\ntype Polarization struct {\n\tTheta float64 \/\/ polar angle of polarization in radians [0, math.Pi)\n\tPhi   float64 \/\/ azimuthal angle of polarization in radians [0, 2*math.Pi)\n}\n\ntype Weights struct {\n\tSlice []float64      \/\/ the slice of weight values\n\tMap   map[string]int \/\/ the map of name->index-in-the-slice\n}\n\nfunc (w Weights) At(n string) float64 {\n\tidx, ok := w.Map[n]\n\tif ok {\n\t\treturn w.Slice[idx]\n\t}\n\tpanic(\"hepmc.Weights.At: invalid name [\" + n + \"]\")\n}\n\nfunc NewWeights() Weights {\n\treturn Weights{\n\t\tSlice: make([]float64, 0, 1),\n\t\tMap:   make(map[string]int),\n\t}\n}\n\n\/\/ EOF\n<commit_msg>hepmc: add (beginning of) API to create hepmc.Event by hand<commit_after>package hepmc\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\nvar errNilVtx = errors.New(\"hepmc: nil Vertex\")\nvar errNilParticle = errors.New(\"hepmc: nil Particle\")\n\n\/\/ Event represents a record for MC generators (for use at any stage of generation)\n\/\/\n\/\/ This type is intended as both a \"container class\" ( to store a MC\n\/\/  event for interface between MC generators and detector simulation )\n\/\/  and also as a \"work in progress class\" ( that could be used inside\n\/\/  a generator and modified as the event is built ).\ntype Event struct {\n\tSignalProcessId int     \/\/ id of the signal process\n\tEventNumber     int     \/\/ event number\n\tMpi             int     \/\/ number of multi particle interactions\n\tScale           float64 \/\/ energy scale,\n\tAlphaQCD        float64 \/\/ QCD coupling, see hep-ph\/0109068\n\tAlphaQED        float64 \/\/ QED coupling, see hep-ph\/0109068\n\n\tSignalVertex *Vertex      \/\/ signal vertex\n\tBeams        [2]*Particle \/\/ incoming beams\n\tWeights      Weights      \/\/ weights for this event. first weight is used by default for hit and miss\n\tRandomStates []int64      \/\/ container of random number generator states\n\n\tVertices  map[int]*Vertex\n\tParticles map[int]*Particle\n\n\tCrossSection *CrossSection\n\tHeavyIon     *HeavyIon\n\tPdfInfo      *PdfInfo\n\tMomentumUnit MomentumUnit\n\tLengthUnit   LengthUnit\n}\n\n\/\/ AddVertex adds a vertex to this event\nfunc (evt *Event) AddVertex(vtx *Vertex) error {\n\tif vtx == nil {\n\t\treturn errNilVtx\n\t}\n\tif vtx.Event != nil && vtx.Event != evt {\n\t\t\/\/TODO: warn and remove from previous event\n\t}\n\treturn vtx.set_parent_event(evt)\n}\n\nfunc (evt *Event) Print(w io.Writer) error {\n\tvar err error\n\t_, err = fmt.Fprintf(\n\t\tw,\n\t\t\"________________________________________________________________________________\\n\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsig_vtx := 0\n\tif evt.SignalVertex != nil {\n\t\tsig_vtx = evt.SignalVertex.Barcode\n\t}\n\t_, err = fmt.Fprintf(\n\t\tw,\n\t\t\"GenEvent: #%04d ID=%5d SignalProcessGenVertex Barcode: %d\\n\",\n\t\tevt.EventNumber,\n\t\tevt.SignalProcessId,\n\t\tsig_vtx,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn err\n}\n\n\/\/ Particle represents a generator particle within an event coming in\/out of a vertex\n\/\/\n\/\/ Particle is the basic building block of the event record\ntype Particle struct {\n\tMomentum      FourVector   \/\/ momentum vector\n\tPdgId         int          \/\/ id according to PDG convention\n\tStatus        int          \/\/ status code as defined for HEPEVT\n\tFlow          Flow         \/\/ flow of this particle\n\tPolarization  Polarization \/\/ polarization of this particle\n\tProdVertex    *Vertex      \/\/ pointer to production vertex (nil if vacuum or beam)\n\tEndVertex     *Vertex      \/\/ pointer to decay vertex (nil if not-decayed)\n\tBarcode       int          \/\/ unique identifier in the event\n\tGeneratedMass float64      \/\/ mass of this particle when it was generated\n}\n\n\/\/ Vertex represents a generator vertex within an event\n\/\/ A vertex is indirectly (via particle \"edges\") linked to other\n\/\/   vertices (\"nodes\") to form a composite \"graph\"\ntype Vertex struct {\n\tPosition     FourVector  \/\/ 4-vector of vertex [mm]\n\tParticlesIn  []*Particle \/\/ all incoming particles\n\tParticlesOut []*Particle \/\/ all outgoing particles\n\tId           int         \/\/ vertex id\n\tWeights      Weights     \/\/ weights for this vertex\n\tEvent        *Event      \/\/ pointer to event owning this vertex\n\tBarcode      int         \/\/ unique identifier in the event\n}\n\nfunc (vtx *Vertex) set_parent_event(evt *Event) error {\n\tvar err error\n\torig_evt := vtx.Event\n\tvtx.Event = evt\n\tif orig_evt == evt {\n\t\treturn err\n\t}\n\tif evt != nil {\n\t\tevt.Vertices[vtx.Barcode] = vtx\n\t}\n\tif orig_evt != nil {\n\t\tdelete(orig_evt.Vertices, vtx.Barcode)\n\t}\n\t\/\/ we also need to loop over all the particles which are owned by\n\t\/\/ this vertex and remove their barcodes from the old event.\n\tfor _, p := range vtx.ParticlesIn {\n\t\tif p.ProdVertex == nil {\n\t\t\tif evt != nil {\n\t\t\t\tevt.Particles[p.Barcode] = p\n\t\t\t}\n\t\t\tif orig_evt != nil {\n\t\t\t\tdelete(orig_evt.Particles, p.Barcode)\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, p := range vtx.ParticlesOut {\n\t\tif evt != nil {\n\t\t\tevt.Particles[p.Barcode] = p\n\t\t}\n\t\tif orig_evt != nil {\n\t\t\tdelete(orig_evt.Particles, p.Barcode)\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ AddParticleIn adds a particle to the list of in-coming particles to this vertex\nfunc (vtx *Vertex) AddParticleIn(p *Particle) error {\n\tvar err error\n\tif p == nil {\n\t\treturn errNilParticle\n\t}\n\t\/\/ if p had a decay vertex, remove it from that vertex's list\n\tif p.EndVertex != nil {\n\t\terr = p.EndVertex.remove_particle_in(p)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ make sure we don't add it twice...\n\terr = vtx.remove_particle_in(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.EndVertex = vtx\n\tvtx.ParticlesIn = append(vtx.ParticlesIn, p)\n\treturn err\n}\n\n\/\/ AddParticleOut adds a particle to the list of out-going particles to this vertex\nfunc (vtx *Vertex) AddParticleOut(p *Particle) error {\n\tvar err error\n\tif p == nil {\n\t\treturn errNilParticle\n\t}\n\t\/\/ if p had a production vertex, remove it from that vertex's list\n\tif p.ProdVertex != nil {\n\t\terr = p.ProdVertex.remove_particle_out(p)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ make sure we don't add it twice...\n\terr = vtx.remove_particle_out(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.ProdVertex = vtx\n\tvtx.ParticlesOut = append(vtx.ParticlesOut, p)\n\treturn err\n}\n\nfunc (vtx *Vertex) remove_particle_in(p *Particle) error {\n\tvar err error\n\tnparts := len(vtx.ParticlesIn)\n\tswitch nparts {\n\tcase 0:\n\t\t\/\/FIXME: logical error ?\n\t\treturn err\n\tcase 1:\n\t\tvtx.ParticlesIn = make([]*Particle, 0)\n\t\treturn err\n\t}\n\tparts := make([]*Particle, 0, nparts-1)\n\tfor _, pp := range vtx.ParticlesIn {\n\t\tif pp == p {\n\t\t\tcontinue\n\t\t}\n\t\tparts = append(parts, pp)\n\t}\n\tvtx.ParticlesIn = parts\n\treturn err\n}\n\nfunc (vtx *Vertex) remove_particle_out(p *Particle) error {\n\tvar err error\n\tnparts := len(vtx.ParticlesOut)\n\tswitch nparts {\n\tcase 0:\n\t\t\/\/FIXME: logical error ?\n\t\treturn err\n\tcase 1:\n\t\tvtx.ParticlesOut = make([]*Particle, 0)\n\t\treturn err\n\t}\n\tparts := make([]*Particle, 0, nparts-1)\n\tfor _, pp := range vtx.ParticlesOut {\n\t\tif pp == p {\n\t\t\tcontinue\n\t\t}\n\t\tparts = append(parts, pp)\n\t}\n\tvtx.ParticlesOut = parts\n\treturn err\n}\n\ntype HeavyIon struct {\n\tNcoll_hard                   int     \/\/ number of hard scatterings\n\tNpart_proj                   int     \/\/ number of projectile participants\n\tNpart_targ                   int     \/\/ number of target participants\n\tNcoll                        int     \/\/ number of NN (nucleon-nucleon) collisions\n\tN_Nwounded_collisions        int     \/\/ Number of N-Nwounded collisions\n\tNwounded_N_collisions        int     \/\/ Number of Nwounded-N collisons\n\tNwounded_Nwounded_collisions int     \/\/ Number of Nwounded-Nwounded collisions\n\tSpectator_neutrons           int     \/\/ Number of spectators neutrons\n\tSpectator_protons            int     \/\/ Number of spectators protons\n\tImpact_parameter             float32 \/\/ Impact Parameter(fm) of collision\n\tEvent_plane_angle            float32 \/\/ Azimuthal angle of event plane\n\tEccentricity                 float32 \/\/ eccentricity of participating nucleons in the transverse plane (as in phobos nucl-ex\/0510031)\n\tSigma_inel_NN                float32 \/\/ nucleon-nucleon inelastic (including diffractive) cross-section\n}\n\n\/\/ CrossSection is used to store the generated cross section.\n\/\/ This type is meant to be used to pass, on an event by event basis,\n\/\/ the current best guess of the total cross section.\n\/\/ It is expected that the final cross section will be stored elsewhere.\ntype CrossSection struct {\n\tValue float64 \/\/ value of the cross-section (in pb)\n\tError float64 \/\/ error on the value of the cross-section (in pb)\n\t\/\/IsSet bool\n}\n\ntype PdfInfo struct {\n\tId1      int     \/\/ flavour code of first parton\n\tId2      int     \/\/ flavour code of second parton\n\tLHAPdf1  int     \/\/ LHA PDF id of first parton\n\tLHAPdf2  int     \/\/ LHA PDF id of second parton\n\tX1       float64 \/\/ fraction of beam momentum carried by first parton (\"beam side\")\n\tX2       float64 \/\/ fraction of beam momentum carried by second parton (\"target side\")\n\tScalePDF float64 \/\/  Q-scale used in evaluation of PDF's   (in GeV)\n\tPdf1     float64 \/\/ PDF (id1, x1, Q)\n\tPdf2     float64 \/\/ PDF (id2, x2, Q)\n}\n\n\/\/ Flow represents a particle's flow and keeps track of an arbitrary number of flow patterns within a graph (i.e. color flow, charge flow, lepton number flow,...)\n\/\/\n\/\/ Flow patterns are coded with an integer, in the same manner as in Herwig.\n\/\/ Note: 0 is NOT allowed as code index nor as flow code since it\n\/\/       is used to indicate null.\n\/\/\n\/\/ This class can be used to keep track of flow patterns within\n\/\/  a graph. An example is color flow. If we have two quarks going through\n\/\/  an s-channel gluon to form two more quarks:\n\/\/\n\/\/  \\q1       \/q3   then we can keep track of the color flow with the\n\/\/   \\_______\/      HepMC::Flow class as follows:\n\/\/   \/   g   \\.\n\/\/  \/q2       \\q4\n\/\/\n\/\/  lets say the color flows from q2-->g-->q3  and q1-->g-->q4\n\/\/  the individual colors are unimportant, but the flow pattern is.\n\/\/  We can capture this flow by assigning the first pattern (q2-->g-->q3)\n\/\/  a unique (arbitrary) flow code 678 and the second pattern (q1-->g-->q4)\n\/\/  flow code 269  ( you can ask HepMC::Flow to choose\n\/\/  a unique code for you using Flow::set_unique_icode() ).\n\/\/  these codes with the particles as follows:\n\/\/    q2->flow().set_icode(1,678);\n\/\/    g->flow().set_icode(1,678);\n\/\/    q3->flow().set_icode(1,678);\n\/\/    q1->flow().set_icode(1,269);\n\/\/    g->flow().set_icode(2,269);\n\/\/    q4->flow().set_icode(1,269);\n\/\/  later on if we wish to know the color partner of q1 we can ask for a list\n\/\/  of all particles connected via this code to q1 which do have less than\n\/\/  2 color partners using:\n\/\/    vector<GenParticle*> result=q1->dangling_connected_partners(q1->icode(1),1,2);\n\/\/  this will return a list containing q1 and q4.\n\/\/    vector<GenParticle*> result=q1->connected_partners(q1->icode(1),1,2);\n\/\/  would return a list containing q1, g, and q4.\ntype Flow struct {\n\tParticle *Particle   \/\/ the particle this flow describes\n\tIcode    map[int]int \/\/ flow patterns as (code_index, icode)\n}\n\ntype Polarization struct {\n\tTheta float64 \/\/ polar angle of polarization in radians [0, math.Pi)\n\tPhi   float64 \/\/ azimuthal angle of polarization in radians [0, 2*math.Pi)\n}\n\ntype Weights struct {\n\tSlice []float64      \/\/ the slice of weight values\n\tMap   map[string]int \/\/ the map of name->index-in-the-slice\n}\n\nfunc (w Weights) At(n string) float64 {\n\tidx, ok := w.Map[n]\n\tif ok {\n\t\treturn w.Slice[idx]\n\t}\n\tpanic(\"hepmc.Weights.At: invalid name [\" + n + \"]\")\n}\n\nfunc NewWeights() Weights {\n\treturn Weights{\n\t\tSlice: make([]float64, 0, 1),\n\t\tMap:   make(map[string]int),\n\t}\n}\n\n\/\/ EOF\n<|endoftext|>"}
{"text":"<commit_before>\/\/\n\/\/ Laser Range Finder\n\/\/ image.go\n\/\/\n\/\/ Cole Smith - css@nyu.edu\n\/\/ Eric Lin   - eric.lin@nyu.edu\n\/\/ LICENSE: Apache 2.0\n\/\/\n\npackage rangefinder\n\nimport (\n\t\"fmt\"\n\t\"image\"\n\t\"image\/color\"\n\t\"math\"\n)\n\n\/\/ Defines an image as a two dimensional array of hues\n\/\/ from the HSV colorspace\ntype ImageMatrix struct {\n\twidth  int\n\theight int\n\t\/\/image  [][]float64\n\timage [][]*Pixel\n}\n\n\/\/ Generates a new ImageMatrix struct given an input\n\/\/ image of type image.RGBA\nfunc NewImageMatrix(inputImage *image.RGBA) *ImageMatrix {\n\t\/\/ Get Image width and height\n\tbounds := inputImage.Bounds()\n\twidth := bounds.Max.X\n\theight := bounds.Max.Y\n\n\t\/\/ Fill the image 2D slice with hues\n\timage := make([][]*Pixel, height)\n\tfor i := range image {\n\t\timage[i] = make([]*Pixel, width)\n\t\tfor j := range image[i] {\n\t\t\tpixel := getHSVFromRGBA(inputImage.At(i, j))\n\t\t\timage[i][j] = pixel\n\t\t}\n\t}\n\treturn &ImageMatrix{width, height, image}\n}\n\n\/\/ Defines a new image in binary greyscale using bool values\ntype MonoImageMatrix struct {\n\tWidth         int\n\tHeight        int\n\tValueTreshold float64\n\tImage         [][]bool\n}\n\n\/\/ Generates a new MonoImageMatrix struct given an image of type image.RGBA,\n\/\/ and the treshold at which the Value (Lume) of an image is considered a 1\n\/\/ or a 0 such that:  1 <- pixel >= valueThreshold, 0 <- pixel < valueThreshold\nfunc NewMonoImageMatrix(inputImage *image.RGBA, valueThreshold float64) *MonoImageMatrix {\n\t\/\/ Get Image width and height\n\tbounds := inputImage.Bounds()\n\twidth := bounds.Max.X\n\theight := bounds.Max.Y\n\n\timage := make([][]bool, height)\n\tfor i := range image {\n\t\timage[i] = make([]bool, width)\n\t\tfor j := range image[i] {\n\t\t\tval := getHSVFromRGBA(inputImage.At(j, i)).val\n\t\t\timage[i][j] = val >= valueThreshold\n\t\t}\n\t}\n\treturn &MonoImageMatrix{width, height, valueThreshold, image}\n}\n\n\/\/ Returns an empty greyscale image of width and height\n\/\/ Defaults to all pixels false and a valueThreshold of 0\nfunc NewEmptyMonoImageMatrix(width, height int) *MonoImageMatrix {\n\timage := make([][]bool, height)\n\tfor i := range image {\n\t\timage[i] = make([]bool, width)\n\t\tfor j := range image[i] {\n\t\t\timage[i][j] = false\n\t\t}\n\t}\n\treturn &MonoImageMatrix{width, height, 0, image}\n}\n\n\/\/ Converts an ImageMatrix to a MonoImageMatrix using value thresholding\nfunc (image ImageMatrix) ConvertToMonoImageMatrix(valueThreshold float64) *MonoImageMatrix {\n\tmono := make([][]bool, image.height)\n\tfor i, _ := range mono {\n\t\tmono[i] = make([]bool, image.width)\n\t\tfor j, _ := range mono[i] {\n\t\t\tval := image.image[i][j].val\n\t\t\tmono[i][j] = val >= valueThreshold\n\t\t}\n\t}\n\treturn &MonoImageMatrix{image.width, image.height, valueThreshold, mono}\n}\n\n\/\/ Binds the pixel offset of the laser dot from the center plane\n\/\/ of the image to a specified inital distance of units.\n\/\/ Example: (image, 0.64, 1, \"meters\")\nfunc Calibrate(image ImageMatrix, laserHue float64, initialDistance int, unitSuffix string) {\n}\n\n\/\/ Runs the image through a filter pass, to isolate the laser dot in the\n\/\/ image by decreasing luminosity and apply edge detection\nfunc (image ImageMatrix) filterImage() ImageMatrix {\n\treturn image\n}\n\n\/\/ Iterates through image array to detect the laser dot. The pixels that\n\/\/ match the hue, plus or minus the threshold value, will be marked true\n\/\/ on a binary image.\nfunc detectDotInImage(image ImageMatrix, laserHue int) MonoImageMatrix {\n\tdotImage := NewEmptyMonoImageMatrix(image.width, image.height)\n\treturn *dotImage\n}\n\n\/\/ Returns the centroid of the marked pixel cluster of a binary image\nfunc getCentroid(monoImage MonoImageMatrix) Pixel {\n\tvar centroid Pixel\n\treturn centroid\n}\n\n\/\/ A pixel for an image defined in the\n\/\/ HSV colorspace\ntype Pixel struct {\n\thue float64\n\tsat float64\n\tval float64\n}\n\n\/\/ Returns a Hue angle as a float64 from an RGBA Color\nfunc getHSVFromRGBA(rgba color.Color) *Pixel {\n\t\/\/Get RGB values\n\tred, green, blue, _ := rgba.RGBA()\n\tr := float64(red)\n\tg := float64(green)\n\tb := float64(blue)\n\n\t\/\/Set up computed variables\n\tvar hue float64 = 0.0\n\tvar sat float64 = 0.0\n\tvar val float64 = 0.0\n\tvar d float64 = 0.0\n\tvar h float64 = 0.0\n\n\tfmt.Println(r, g, b)\n\n\t\/\/Standardize rgb values\n\tr = r \/ 255\n\tg = g \/ 255\n\tb = b \/ 255\n\n\t\/\/Get min and max for RGB\n\tmin := math.Min(math.Min(r, g), b)\n\tmax := math.Max(math.Max(r, g), b)\n\n\t\/\/If min is equal to max, we can assume it is black and white\n\tif min == max {\n\t\treturn &Pixel{0, 0, min}\n\t}\n\n\t\/\/Get delta for max and min\n\tif r == min {\n\t\td = g - b\n\t\th = 3\n\t} else {\n\t\tif b == min {\n\t\t\td = r - g\n\t\t\th = 1\n\t\t} else {\n\t\t\td = b - r\n\t\t\th = 5\n\t\t}\n\t}\n\n\thue = 60 * (h - d\/(max-min))\n\tsat = (max - min) \/ max\n\tval = max\n\n\tfmt.Println(val)\n\n\treturn &Pixel{hue, sat, val}\n}\n\n\/\/\/\/ Returns the Value (Lume) as a float64 from an RGBA Color\n\/\/func getValueFromRGBA(rgba color.Color) float64 {\n\/\/red, green, blue, _ := rgba.RGBA()\n\/\/r := float64(red)\n\/\/g := float64(green)\n\/\/b := float64(blue)\n\n\/\/return math.Max(math.Max(r, g), b)\n\/\/}\n<commit_msg>removed print statements<commit_after>\/\/\n\/\/ Laser Range Finder\n\/\/ image.go\n\/\/\n\/\/ Cole Smith - css@nyu.edu\n\/\/ Eric Lin   - eric.lin@nyu.edu\n\/\/ LICENSE: Apache 2.0\n\/\/\n\npackage rangefinder\n\nimport (\n\t\"image\"\n\t\"image\/color\"\n\t\"math\"\n)\n\n\/\/ Defines an image as a two dimensional array of hues\n\/\/ from the HSV colorspace\ntype ImageMatrix struct {\n\twidth  int\n\theight int\n\t\/\/image  [][]float64\n\timage [][]*Pixel\n}\n\n\/\/ Generates a new ImageMatrix struct given an input\n\/\/ image of type image.RGBA\nfunc NewImageMatrix(inputImage *image.RGBA) *ImageMatrix {\n\t\/\/ Get Image width and height\n\tbounds := inputImage.Bounds()\n\twidth := bounds.Max.X\n\theight := bounds.Max.Y\n\n\t\/\/ Fill the image 2D slice with hues\n\timage := make([][]*Pixel, height)\n\tfor i := range image {\n\t\timage[i] = make([]*Pixel, width)\n\t\tfor j := range image[i] {\n\t\t\tpixel := getHSVFromRGBA(inputImage.At(i, j))\n\t\t\timage[i][j] = pixel\n\t\t}\n\t}\n\treturn &ImageMatrix{width, height, image}\n}\n\n\/\/ Defines a new image in binary greyscale using bool values\ntype MonoImageMatrix struct {\n\tWidth         int\n\tHeight        int\n\tValueTreshold float64\n\tImage         [][]bool\n}\n\n\/\/ Generates a new MonoImageMatrix struct given an image of type image.RGBA,\n\/\/ and the treshold at which the Value (Lume) of an image is considered a 1\n\/\/ or a 0 such that:  1 <- pixel >= valueThreshold, 0 <- pixel < valueThreshold\nfunc NewMonoImageMatrix(inputImage *image.RGBA, valueThreshold float64) *MonoImageMatrix {\n\t\/\/ Get Image width and height\n\tbounds := inputImage.Bounds()\n\twidth := bounds.Max.X\n\theight := bounds.Max.Y\n\n\timage := make([][]bool, height)\n\tfor i := range image {\n\t\timage[i] = make([]bool, width)\n\t\tfor j := range image[i] {\n\t\t\tval := getHSVFromRGBA(inputImage.At(j, i)).val\n\t\t\timage[i][j] = val >= valueThreshold\n\t\t}\n\t}\n\treturn &MonoImageMatrix{width, height, valueThreshold, image}\n}\n\n\/\/ Returns an empty greyscale image of width and height\n\/\/ Defaults to all pixels false and a valueThreshold of 0\nfunc NewEmptyMonoImageMatrix(width, height int) *MonoImageMatrix {\n\timage := make([][]bool, height)\n\tfor i := range image {\n\t\timage[i] = make([]bool, width)\n\t\tfor j := range image[i] {\n\t\t\timage[i][j] = false\n\t\t}\n\t}\n\treturn &MonoImageMatrix{width, height, 0, image}\n}\n\n\/\/ Converts an ImageMatrix to a MonoImageMatrix using value thresholding\nfunc (image ImageMatrix) ConvertToMonoImageMatrix(valueThreshold float64) *MonoImageMatrix {\n\tmono := make([][]bool, image.height)\n\tfor i, _ := range mono {\n\t\tmono[i] = make([]bool, image.width)\n\t\tfor j, _ := range mono[i] {\n\t\t\tval := image.image[i][j].val\n\t\t\tmono[i][j] = val >= valueThreshold\n\t\t}\n\t}\n\treturn &MonoImageMatrix{image.width, image.height, valueThreshold, mono}\n}\n\n\/\/ Binds the pixel offset of the laser dot from the center plane\n\/\/ of the image to a specified inital distance of units.\n\/\/ Example: (image, 0.64, 1, \"meters\")\nfunc Calibrate(image ImageMatrix, laserHue float64, initialDistance int, unitSuffix string) {\n}\n\n\/\/ Runs the image through a filter pass, to isolate the laser dot in the\n\/\/ image by decreasing luminosity and apply edge detection\nfunc (image ImageMatrix) filterImage() ImageMatrix {\n\treturn image\n}\n\n\/\/ Iterates through image array to detect the laser dot. The pixels that\n\/\/ match the hue, plus or minus the threshold value, will be marked true\n\/\/ on a binary image.\nfunc detectDotInImage(image ImageMatrix, laserHue int) MonoImageMatrix {\n\tdotImage := NewEmptyMonoImageMatrix(image.width, image.height)\n\treturn *dotImage\n}\n\n\/\/ Returns the centroid of the marked pixel cluster of a binary image\nfunc getCentroid(monoImage MonoImageMatrix) Pixel {\n\tvar centroid Pixel\n\treturn centroid\n}\n\n\/\/ A pixel for an image defined in the\n\/\/ HSV colorspace\ntype Pixel struct {\n\thue float64\n\tsat float64\n\tval float64\n}\n\n\/\/ Returns a Hue angle as a float64 from an RGBA Color\nfunc getHSVFromRGBA(rgba color.Color) *Pixel {\n\t\/\/Get RGB values\n\tred, green, blue, _ := rgba.RGBA()\n\tr := float64(red)\n\tg := float64(green)\n\tb := float64(blue)\n\n\t\/\/Set up computed variables\n\tvar hue float64 = 0.0\n\tvar sat float64 = 0.0\n\tvar val float64 = 0.0\n\tvar d float64 = 0.0\n\tvar h float64 = 0.0\n\n\t\/\/Standardize rgb values\n\tr = r \/ 65535.0\n\tg = g \/ 65535.0\n\tb = b \/ 65535.0\n\n\t\/\/Get min and max for RGB\n\tmin := math.Min(math.Min(r, g), b)\n\tmax := math.Max(math.Max(r, g), b)\n\n\t\/\/If min is equal to max, we can assume it is black and white\n\tif min == max {\n\t\treturn &Pixel{0, 0, min}\n\t}\n\n\t\/\/Get delta for max and min\n\tif r == min {\n\t\td = g - b\n\t\th = 3\n\t} else {\n\t\tif b == min {\n\t\t\td = r - g\n\t\t\th = 1\n\t\t} else {\n\t\t\td = b - r\n\t\t\th = 5\n\t\t}\n\t}\n\n\thue = 60 * (h - d\/(max-min))\n\tsat = (max - min) \/ max\n\tval = max\n\n\treturn &Pixel{hue, sat, val}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Hajime Hoshi\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage ebiten\n\nimport (\n\t\"github.com\/hajimehoshi\/ebiten\/internal\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/opengl\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/opengl\/internal\/shader\"\n\t\"image\"\n\t\"image\/color\"\n)\n\ntype innerImage struct {\n\tframebuffer *opengl.Framebuffer\n\ttexture     *opengl.Texture\n}\n\nfunc newInnerImage(texture *opengl.Texture) (*innerImage, error) {\n\tframebuffer, err := opengl.NewFramebufferFromTexture(texture)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &innerImage{framebuffer, texture}, nil\n}\n\nfunc (i *innerImage) size() (width, height int) {\n\treturn i.framebuffer.Size()\n}\n\nfunc (i *innerImage) Clear() error {\n\treturn i.Fill(color.Transparent)\n}\n\nfunc (i *innerImage) Fill(clr color.Color) error {\n\tif err := i.framebuffer.SetAsViewport(); err != nil {\n\t\treturn err\n\t}\n\tr, g, b, a := internal.RGBA(clr)\n\topengl.Clear(r, g, b, a)\n\treturn nil\n}\n\nfunc (i *innerImage) drawImage(img *innerImage, options *DrawImageOptions) error {\n\tif options == nil {\n\t\toptions = &DrawImageOptions{}\n\t}\n\tdsts := options.DstParts\n\tsrcs := options.SrcParts\n\tif srcs == nil || dsts == nil {\n\t\tw, h := img.size()\n\t\tdsts = []image.Rectangle{\n\t\t\timage.Rect(0, 0, w, h),\n\t\t}\n\t\tsrcs = []image.Rectangle{\n\t\t\timage.Rect(0, 0, w, h),\n\t\t}\n\t}\n\tgeo := options.GeometryMatrix\n\tif geo == nil {\n\t\ti := GeometryMatrixI()\n\t\tgeo = &i\n\t}\n\tclr := options.ColorMatrix\n\tif clr == nil {\n\t\ti := ColorMatrixI()\n\t\tclr = &i\n\t}\n\n\tif err := i.framebuffer.SetAsViewport(); err != nil {\n\t\treturn err\n\t}\n\tw, h := img.texture.Size()\n\tquads := textureQuads(dsts, srcs, w, h)\n\tprojectionMatrix := i.framebuffer.ProjectionMatrix()\n\tshader.DrawTexture(img.texture.Native(), projectionMatrix, quads, geo, clr)\n\treturn nil\n}\n\nfunc u(x float64, width int) float32 {\n\treturn float32(x) \/ float32(internal.NextPowerOf2Int(width))\n}\n\nfunc v(y float64, height int) float32 {\n\treturn float32(y) \/ float32(internal.NextPowerOf2Int(height))\n}\n\nfunc textureQuads(dsts, srcs []image.Rectangle, width, height int) []shader.TextureQuad {\n\tl := len(dsts)\n\tif len(srcs) < l {\n\t\tl = len(srcs)\n\t}\n\tquads := make([]shader.TextureQuad, 0, l)\n\tfor i := 0; i < l; i++ {\n\t\tdst, src := dsts[i], srcs[i]\n\t\tx1 := float32(dst.Min.X)\n\t\tx2 := float32(dst.Max.X)\n\t\ty1 := float32(dst.Min.Y)\n\t\ty2 := float32(dst.Max.Y)\n\t\tu1 := u(float64(src.Min.X), width)\n\t\tu2 := u(float64(src.Max.X), width)\n\t\tv1 := v(float64(src.Min.Y), height)\n\t\tv2 := v(float64(src.Max.Y), height)\n\t\tquad := shader.TextureQuad{x1, x2, y1, y2, u1, u2, v1, v2}\n\t\tquads = append(quads, quad)\n\t}\n\treturn quads\n}\n\ntype syncer interface {\n\tSync(func())\n}\n\n\/\/ Image represents an image.\n\/\/ The pixel format is alpha-premultiplied.\n\/\/ Image implements image.Image.\ntype Image struct {\n\tsyncer syncer\n\tinner  *innerImage\n\tpixels []uint8\n}\n\n\/\/ Size returns the size of the image.\nfunc (i *Image) Size() (width, height int) {\n\treturn i.inner.size()\n}\n\n\/\/ Clear resets the pixels of the image into 0.\nfunc (i *Image) Clear() (err error) {\n\ti.pixels = nil\n\ti.syncer.Sync(func() {\n\t\terr = i.inner.Clear()\n\t})\n\treturn\n}\n\n\/\/ Fill fills the image with a solid color.\nfunc (i *Image) Fill(clr color.Color) (err error) {\n\ti.pixels = nil\n\ti.syncer.Sync(func() {\n\t\terr = i.inner.Fill(clr)\n\t})\n\treturn\n}\n\n\/\/ DrawImage draws the given image on the receiver image.\n\/\/ This method accepts the parts of the given image at the parts of the destination as the options.\n\/\/ After determining parts to draw, this applies the geometry matrix and the color matrix as the options.\n\/\/\n\/\/ If you want to draw a whole image simply, use DrawWholeImage.\nfunc (i *Image) DrawImage(image *Image, options *DrawImageOptions) (err error) {\n\treturn i.drawImage(image.inner, options)\n}\n\n\/\/ DrawImageAt draws the given image on the receiver image at the position (x, y).\n\/\/\n\/\/ If a geometry matrix is specified, the geometry matrix is applied ahead of the image is translated by (x, y).\nfunc (i *Image) DrawImageAt(image *Image, x, y int, options *DrawImageOptions) (err error) {\n\tif options == nil {\n\t\toptions = &DrawImageOptions{}\n\t}\n\tif options.GeometryMatrix == nil {\n\t\tgeo := TranslateGeometry(float64(x), float64(y))\n\t\toptions.GeometryMatrix = &geo\n\t} else {\n\t\toptions.GeometryMatrix.Concat(TranslateGeometry(float64(x), float64(y)))\n\t}\n\treturn i.drawImage(image.inner, options)\n}\n\nfunc (i *Image) drawImage(image *innerImage, option *DrawImageOptions) (err error) {\n\ti.pixels = nil\n\ti.syncer.Sync(func() {\n\t\terr = i.inner.drawImage(image, option)\n\t})\n\treturn\n}\n\n\/\/ Bounds returns the bounds of the image.\nfunc (i *Image) Bounds() image.Rectangle {\n\tw, h := i.inner.size()\n\treturn image.Rect(0, 0, w, h)\n}\n\n\/\/ ColorModel returns the color model of the image.\nfunc (i *Image) ColorModel() color.Model {\n\treturn color.RGBAModel\n}\n\n\/\/ At returns the color of the image at (x, y).\n\/\/\n\/\/ This method loads pixels from GPU to VRAM if necessary.\nfunc (i *Image) At(x, y int) color.Color {\n\tif i.pixels == nil {\n\t\ti.syncer.Sync(func() {\n\t\t\tvar err error\n\t\t\ti.pixels, err = i.inner.texture.Pixels()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t})\n\t}\n\tw, _ := i.inner.size()\n\tw = internal.NextPowerOf2Int(w)\n\tidx := 4*x + 4*y*w\n\tr, g, b, a := i.pixels[idx], i.pixels[idx+1], i.pixels[idx+2], i.pixels[idx+3]\n\treturn color.RGBA{r, g, b, a}\n}\n\n\/\/ A DrawImageOptions presents options to render an image on an image.\ntype DrawImageOptions struct {\n\tDstParts       []image.Rectangle\n\tSrcParts       []image.Rectangle\n\tGeometryMatrix *GeometryMatrix\n\tColorMatrix    *ColorMatrix\n}\n<commit_msg>Fix a comment<commit_after>\/\/ Copyright 2014 Hajime Hoshi\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage ebiten\n\nimport (\n\t\"github.com\/hajimehoshi\/ebiten\/internal\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/opengl\"\n\t\"github.com\/hajimehoshi\/ebiten\/internal\/opengl\/internal\/shader\"\n\t\"image\"\n\t\"image\/color\"\n)\n\ntype innerImage struct {\n\tframebuffer *opengl.Framebuffer\n\ttexture     *opengl.Texture\n}\n\nfunc newInnerImage(texture *opengl.Texture) (*innerImage, error) {\n\tframebuffer, err := opengl.NewFramebufferFromTexture(texture)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &innerImage{framebuffer, texture}, nil\n}\n\nfunc (i *innerImage) size() (width, height int) {\n\treturn i.framebuffer.Size()\n}\n\nfunc (i *innerImage) Clear() error {\n\treturn i.Fill(color.Transparent)\n}\n\nfunc (i *innerImage) Fill(clr color.Color) error {\n\tif err := i.framebuffer.SetAsViewport(); err != nil {\n\t\treturn err\n\t}\n\tr, g, b, a := internal.RGBA(clr)\n\topengl.Clear(r, g, b, a)\n\treturn nil\n}\n\nfunc (i *innerImage) drawImage(img *innerImage, options *DrawImageOptions) error {\n\tif options == nil {\n\t\toptions = &DrawImageOptions{}\n\t}\n\tdsts := options.DstParts\n\tsrcs := options.SrcParts\n\tif srcs == nil || dsts == nil {\n\t\tw, h := img.size()\n\t\tdsts = []image.Rectangle{\n\t\t\timage.Rect(0, 0, w, h),\n\t\t}\n\t\tsrcs = []image.Rectangle{\n\t\t\timage.Rect(0, 0, w, h),\n\t\t}\n\t}\n\tgeo := options.GeometryMatrix\n\tif geo == nil {\n\t\ti := GeometryMatrixI()\n\t\tgeo = &i\n\t}\n\tclr := options.ColorMatrix\n\tif clr == nil {\n\t\ti := ColorMatrixI()\n\t\tclr = &i\n\t}\n\n\tif err := i.framebuffer.SetAsViewport(); err != nil {\n\t\treturn err\n\t}\n\tw, h := img.texture.Size()\n\tquads := textureQuads(dsts, srcs, w, h)\n\tprojectionMatrix := i.framebuffer.ProjectionMatrix()\n\tshader.DrawTexture(img.texture.Native(), projectionMatrix, quads, geo, clr)\n\treturn nil\n}\n\nfunc u(x float64, width int) float32 {\n\treturn float32(x) \/ float32(internal.NextPowerOf2Int(width))\n}\n\nfunc v(y float64, height int) float32 {\n\treturn float32(y) \/ float32(internal.NextPowerOf2Int(height))\n}\n\nfunc textureQuads(dsts, srcs []image.Rectangle, width, height int) []shader.TextureQuad {\n\tl := len(dsts)\n\tif len(srcs) < l {\n\t\tl = len(srcs)\n\t}\n\tquads := make([]shader.TextureQuad, 0, l)\n\tfor i := 0; i < l; i++ {\n\t\tdst, src := dsts[i], srcs[i]\n\t\tx1 := float32(dst.Min.X)\n\t\tx2 := float32(dst.Max.X)\n\t\ty1 := float32(dst.Min.Y)\n\t\ty2 := float32(dst.Max.Y)\n\t\tu1 := u(float64(src.Min.X), width)\n\t\tu2 := u(float64(src.Max.X), width)\n\t\tv1 := v(float64(src.Min.Y), height)\n\t\tv2 := v(float64(src.Max.Y), height)\n\t\tquad := shader.TextureQuad{x1, x2, y1, y2, u1, u2, v1, v2}\n\t\tquads = append(quads, quad)\n\t}\n\treturn quads\n}\n\ntype syncer interface {\n\tSync(func())\n}\n\n\/\/ Image represents an image.\n\/\/ The pixel format is alpha-premultiplied.\n\/\/ Image implements image.Image.\ntype Image struct {\n\tsyncer syncer\n\tinner  *innerImage\n\tpixels []uint8\n}\n\n\/\/ Size returns the size of the image.\nfunc (i *Image) Size() (width, height int) {\n\treturn i.inner.size()\n}\n\n\/\/ Clear resets the pixels of the image into 0.\nfunc (i *Image) Clear() (err error) {\n\ti.pixels = nil\n\ti.syncer.Sync(func() {\n\t\terr = i.inner.Clear()\n\t})\n\treturn\n}\n\n\/\/ Fill fills the image with a solid color.\nfunc (i *Image) Fill(clr color.Color) (err error) {\n\ti.pixels = nil\n\ti.syncer.Sync(func() {\n\t\terr = i.inner.Fill(clr)\n\t})\n\treturn\n}\n\n\/\/ DrawImage draws the given image on the receiver image.\n\/\/ This method accepts the parts of the given image at the parts of the destination as the options.\n\/\/ After determining parts to draw, this applies the geometry matrix and the color matrix as the options.\n\/\/\n\/\/ If you want to draw a whole image simply, use DrawWholeImage.\nfunc (i *Image) DrawImage(image *Image, options *DrawImageOptions) (err error) {\n\treturn i.drawImage(image.inner, options)\n}\n\n\/\/ DrawImageAt draws the given image on the receiver image at the position (x, y).\n\/\/\n\/\/ If a geometry matrix is specified, the geometry matrix is applied ahead of translating the image by (x, y).\nfunc (i *Image) DrawImageAt(image *Image, x, y int, options *DrawImageOptions) (err error) {\n\tif options == nil {\n\t\toptions = &DrawImageOptions{}\n\t}\n\tif options.GeometryMatrix == nil {\n\t\tgeo := TranslateGeometry(float64(x), float64(y))\n\t\toptions.GeometryMatrix = &geo\n\t} else {\n\t\toptions.GeometryMatrix.Concat(TranslateGeometry(float64(x), float64(y)))\n\t}\n\treturn i.drawImage(image.inner, options)\n}\n\nfunc (i *Image) drawImage(image *innerImage, option *DrawImageOptions) (err error) {\n\ti.pixels = nil\n\ti.syncer.Sync(func() {\n\t\terr = i.inner.drawImage(image, option)\n\t})\n\treturn\n}\n\n\/\/ Bounds returns the bounds of the image.\nfunc (i *Image) Bounds() image.Rectangle {\n\tw, h := i.inner.size()\n\treturn image.Rect(0, 0, w, h)\n}\n\n\/\/ ColorModel returns the color model of the image.\nfunc (i *Image) ColorModel() color.Model {\n\treturn color.RGBAModel\n}\n\n\/\/ At returns the color of the image at (x, y).\n\/\/\n\/\/ This method loads pixels from GPU to VRAM if necessary.\nfunc (i *Image) At(x, y int) color.Color {\n\tif i.pixels == nil {\n\t\ti.syncer.Sync(func() {\n\t\t\tvar err error\n\t\t\ti.pixels, err = i.inner.texture.Pixels()\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t})\n\t}\n\tw, _ := i.inner.size()\n\tw = internal.NextPowerOf2Int(w)\n\tidx := 4*x + 4*y*w\n\tr, g, b, a := i.pixels[idx], i.pixels[idx+1], i.pixels[idx+2], i.pixels[idx+3]\n\treturn color.RGBA{r, g, b, a}\n}\n\n\/\/ A DrawImageOptions presents options to render an image on an image.\ntype DrawImageOptions struct {\n\tDstParts       []image.Rectangle\n\tSrcParts       []image.Rectangle\n\tGeometryMatrix *GeometryMatrix\n\tColorMatrix    *ColorMatrix\n}\n<|endoftext|>"}
{"text":"<commit_before>package chevalier\n\nimport (\n\t\"crypto\/sha1\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"github.com\/mattbaird\/elastigo\/api\"\n\tes \"github.com\/mattbaird\/elastigo\/core\"\n\t\"strings\"\n)\n\n\/\/ ElasticsearchSource is the type used to serialize sources for \n\/\/ indexing.\ntype ElasticsearchSource struct {\n\tOrigin string\n\tSource map[string]string `json:\"source\"`\n}\n\n\/\/ ElasticsearchOrigin stores metadata for each origin.\ntype ElasticsearchOrigin struct {\n\tOrigin string `json:\"origin\"`\n\tCount string `json:\"count\"`\n}\n\n\/\/ GetID returns a (probably) unique ID for an ElasticsearchSource, in\n\/\/ the form of a sha1 hash of underscore-separated field-value pairs\n\/\/ separated by newlines.\nfunc (s *ElasticsearchSource) GetID() string {\n\ttagKeys := make([]string, len(s.Source)+1)\n\tidx := 0\n\tfor field, value := range s.Source {\n\t\ttagKeys[idx] = fmt.Sprintf(\"%s_%s\", field, value)\n\t\tidx++\n\t}\n\ttagKeys[idx] = fmt.Sprintf(\"Origin\", s.Origin)\n\tkey := []byte(strings.Join(tagKeys, \"\\n\"))\n\thash := sha1.Sum(key)\n\tid := base64.StdEncoding.EncodeToString(hash[:sha1.Size])\n\treturn id\n}\n\nfunc NewElasticsearchSource(origin string, source *DataSource) *ElasticsearchSource {\n\tesSource := new(ElasticsearchSource)\n\tesSource.Origin = origin\n\tesSource.Source = make(map[string]string, 0)\n\tfor _, tagPtr := range source.Source {\n\t\tesSource.Source[*tagPtr.Field] = *tagPtr.Value\n\t}\n\treturn esSource\n}\n\n\/\/ Unmarshal turns an ElasticsearchSource (presumably itself unmarshaled\n\/\/ from a JSON object stored in Elasticsearch) into the equivalent\n\/\/ DataSource.\nfunc (s *ElasticsearchSource) Unmarshal() *DataSource {\n\ttags := make([]*DataSource_Tag, len(s.Source))\n\tidx := 0\n\tfor field, value := range s.Source {\n\t\ttags[idx] = NewDataSourceTag(field, value)\n\t\tidx++\n\t}\n\tpb := NewDataSource(tags)\n\treturn pb\n}\n\nfunc MarshalElasticsearchSources(origin string, b *DataSourceBurst) []*ElasticsearchSource {\n\tsources := make([]*ElasticsearchSource, len(b.Sources))\n\tfor i, s := range b.Sources {\n\t\tesSource := NewElasticsearchSource(origin, s)\n\t\tsources[i] = esSource\n\t}\n\treturn sources\n}\n\n\/\/ ElasticsearchWriter maintains context for writes to the index.\ntype ElasticsearchWriter struct {\n\tindexer   *es.BulkIndexer\n\tindexName string\n\tdataType  string\n\tdone      chan bool\n}\n\n\/\/ NewElasticsearchWriter builds a new Writer. retrySeconds is for the\n\/\/ bulk indexer. index and dataType can be anything as long as they're\n\/\/ consistent.\nfunc NewElasticsearchWriter(host string, maxConns int, retrySeconds int, index, dataType string) *ElasticsearchWriter {\n\twriter := new(ElasticsearchWriter)\n\tapi.Domain = host\n\twriter.indexer = es.NewBulkIndexerErrors(maxConns, retrySeconds)\n\twriter.indexName = index\n\twriter.dataType = dataType\n\twriter.done = make(chan bool)\n\twriter.indexer.Run(writer.done)\n\treturn writer\n}\n\n\/\/ Write queues a DataSource for writing by the bulk indexer.\n\/\/ Non-blocking.\nfunc (w *ElasticsearchWriter) Write(origin string, source *DataSource) error {\n\tesSource := NewElasticsearchSource(origin, source)\n\tupdate := map[string]interface{}{\n\t\t\"doc\":           esSource,\n\t\t\"doc_as_upsert\": true,\n\t}\n\terr := w.indexer.Update(w.indexName, w.dataType, esSource.GetID(), \"\", nil, update)\n\treturn err\n}\n\n\/\/ Shutdown signals the bulk indexer to flush all pending writes.\nfunc (w *ElasticsearchWriter) Shutdown() {\n\tw.done <- true\n}\n\n\/\/ GetErrorChan returns the channel the bulk indexer writes errors to.\nfunc (w *ElasticsearchWriter) GetErrorChan() chan *es.ErrorBuffer {\n\treturn w.indexer.ErrorChannel\n}\n<commit_msg>ElasticsearchOrigin needs a LastUpdated member<commit_after>package chevalier\n\nimport (\n\t\"crypto\/sha1\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"github.com\/mattbaird\/elastigo\/api\"\n\tes \"github.com\/mattbaird\/elastigo\/core\"\n\t\"strings\"\n)\n\n\/\/ ElasticsearchSource is the type used to serialize sources for \n\/\/ indexing.\ntype ElasticsearchSource struct {\n\tOrigin string\n\tSource map[string]string `json:\"source\"`\n}\n\n\/\/ ElasticsearchOrigin stores metadata for each origin.\ntype ElasticsearchOrigin struct {\n\tOrigin string `json:\"origin\"`\n\tCount string `json:\"count\"`\n\tLastUpdated uint64 `json:\"last_updated\"`\n}\n\n\/\/ GetID returns a (probably) unique ID for an ElasticsearchSource, in\n\/\/ the form of a sha1 hash of underscore-separated field-value pairs\n\/\/ separated by newlines.\nfunc (s *ElasticsearchSource) GetID() string {\n\ttagKeys := make([]string, len(s.Source)+1)\n\tidx := 0\n\tfor field, value := range s.Source {\n\t\ttagKeys[idx] = fmt.Sprintf(\"%s_%s\", field, value)\n\t\tidx++\n\t}\n\ttagKeys[idx] = fmt.Sprintf(\"Origin\", s.Origin)\n\tkey := []byte(strings.Join(tagKeys, \"\\n\"))\n\thash := sha1.Sum(key)\n\tid := base64.StdEncoding.EncodeToString(hash[:sha1.Size])\n\treturn id\n}\n\n\/\/ NewElasticsearchSource converts a (datasource + origin) to an\n\/\/ ElasticsearchSource.\nfunc NewElasticsearchSource(origin string, source *DataSource) *ElasticsearchSource {\n\tesSource := new(ElasticsearchSource)\n\tesSource.Origin = origin\n\tesSource.Source = make(map[string]string, 0)\n\tfor _, tagPtr := range source.Source {\n\t\tesSource.Source[*tagPtr.Field] = *tagPtr.Value\n\t}\n\treturn esSource\n}\n\n\/\/ Unmarshal turns an ElasticsearchSource (presumably itself unmarshaled\n\/\/ from a JSON object stored in Elasticsearch) into the equivalent\n\/\/ DataSource.\nfunc (s *ElasticsearchSource) Unmarshal() *DataSource {\n\ttags := make([]*DataSource_Tag, len(s.Source))\n\tidx := 0\n\tfor field, value := range s.Source {\n\t\ttags[idx] = NewDataSourceTag(field, value)\n\t\tidx++\n\t}\n\tpb := NewDataSource(tags)\n\treturn pb\n}\n\n\/\/ MarshalElasticsearchSources converts source bursts (plus an origin)\n\/\/ into ElasticsearchSource objects ready for indexing.\nfunc MarshalElasticsearchSources(origin string, b *DataSourceBurst) []*ElasticsearchSource {\n\tsources := make([]*ElasticsearchSource, len(b.Sources))\n\tfor i, s := range b.Sources {\n\t\tesSource := NewElasticsearchSource(origin, s)\n\t\tsources[i] = esSource\n\t}\n\treturn sources\n}\n\n\/\/ ElasticsearchWriter maintains context for writes to the index.\ntype ElasticsearchWriter struct {\n\tindexer   *es.BulkIndexer\n\tindexName string\n\tdataType  string\n\tdone      chan bool\n}\n\n\/\/ NewElasticsearchWriter builds a new Writer. retrySeconds is for the\n\/\/ bulk indexer. index and dataType can be anything as long as they're\n\/\/ consistent.\nfunc NewElasticsearchWriter(host string, maxConns int, retrySeconds int, index, dataType string) *ElasticsearchWriter {\n\twriter := new(ElasticsearchWriter)\n\tapi.Domain = host\n\twriter.indexer = es.NewBulkIndexerErrors(maxConns, retrySeconds)\n\twriter.indexName = index\n\twriter.dataType = dataType\n\twriter.done = make(chan bool)\n\twriter.indexer.Run(writer.done)\n\treturn writer\n}\n\n\/\/ Write queues a DataSource for writing by the bulk indexer.\n\/\/ Non-blocking.\nfunc (w *ElasticsearchWriter) Write(origin string, source *DataSource) error {\n\tesSource := NewElasticsearchSource(origin, source)\n\tupdate := map[string]interface{}{\n\t\t\"doc\":           esSource,\n\t\t\"doc_as_upsert\": true,\n\t}\n\terr := w.indexer.Update(w.indexName, w.dataType, esSource.GetID(), \"\", nil, update)\n\treturn err\n}\n\n\/\/ Shutdown signals the bulk indexer to flush all pending writes.\nfunc (w *ElasticsearchWriter) Shutdown() {\n\tw.done <- true\n}\n\n\/\/ GetErrorChan returns the channel the bulk indexer writes errors to.\nfunc (w *ElasticsearchWriter) GetErrorChan() chan *es.ErrorBuffer {\n\treturn w.indexer.ErrorChannel\n}\n<|endoftext|>"}
{"text":"<commit_before>package commandevaluators\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"github.com\/byuoitav\/av-api\/base\"\n\t\"github.com\/byuoitav\/av-api\/dbo\"\n\t\"github.com\/byuoitav\/configuration-database-microservice\/accessors\"\n)\n\n\/\/ChangeInput is struct that implements the CommandEvaluation struct\ntype ChangeInputDefault struct {\n}\n\n\/\/Evaluate fulfills the CommmandEvaluation evaluate requirement.\nfunc (p *ChangeInputDefault) Evaluate(room base.PublicRoom) (actions []base.ActionStructure, err error) {\n\t\/\/RoomWideSetVideoInput\n\tif len(room.CurrentVideoInput) > 0 { \/\/ Check if the user sent a PUT body changing the current video input\n\t\tvar tempActions []base.ActionStructure\n\n\t\ttempActions, err = generateChangeInputByRole(\n\t\t\t\"VideoOut\",\n\t\t\troom.CurrentVideoInput,\n\t\t\troom.Room,\n\t\t\troom.Building,\n\t\t)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tactions = append(actions, tempActions...)\n\t}\n\n\t\/\/RoomWideSetAudioInput\n\tif len(room.CurrentAudioInput) > 0 { \/\/ Check if the user sent a PUT body changing the current audio input\n\t\tvar tempActions []base.ActionStructure\n\n\t\t\/\/generate action\n\t\ttempActions, err = generateChangeInputByRole(\n\t\t\t\"AudioOut\",\n\t\t\troom.CurrentVideoInput,\n\t\t\troom.Room,\n\t\t\troom.Building,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tactions = append(actions, tempActions...)\n\t}\n\n\t\/\/Displays\n\tfor _, d := range room.Displays { \/\/ Loop through the devices array (potentially) passed in the user's PUT body\n\t\tvar action base.ActionStructure\n\t\taction, err = generateChangeInputByDevice(d.Device, room.Room, room.Building)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tactions = append(actions, action)\n\t}\n\n\t\/\/AudioDevice\n\tfor _, d := range room.AudioDevices { \/\/ Loop through the audio devices array (potentially) passed in the user's PUT body\n\t\tvar action base.ActionStructure\n\t\taction, err = generateChangeInputByDevice(d.Device, room.Room, room.Building)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tactions = append(actions, action)\n\t}\n\n\treturn\n}\n\n\/\/Validate fulfills the Fulfill requirement on the command interface\nfunc (p *ChangeInputDefault) Validate(action base.ActionStructure) (err error) {\n\treturn nil\n}\n\n\/\/GetIncompatableCommands keeps track of actions that are incompatable (on the same device)\nfunc (p *ChangeInputDefault) GetIncompatableCommands() (incompatableActions []string) {\n\treturn\n}\n\nfunc generateChangeInputByDevice(dev base.Device, room string, building string) (action base.ActionStructure, err error) {\n\tvar curDevice accessors.Device\n\n\tcurDevice, err = dbo.GetDeviceByName(building, room, dev.Name)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tparamMap := make(map[string]string)\n\n\tfor _, port := range curDevice.Ports {\n\t\tif strings.EqualFold(port.Source, dev.Input) {\n\t\t\tparamMap[\"port\"] = port.Name\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif len(paramMap) == 0 {\n\t\terr = errors.New(\"No port found for input.\")\n\t\treturn\n\t}\n\n\taction = base.ActionStructure{\n\t\tAction:              \"change-input\",\n\t\tGeneratingEvaluator: \"changeInput\",\n\t\tDevice:              curDevice,\n\t\tParameters:          paramMap,\n\t\tDeviceSpecific:      true,\n\t\tOverridden:          false,\n\t}\n\n\treturn\n}\n\nfunc generateChangeInputByRole(role string, input string, room string, building string) (actions []base.ActionStructure, err error) {\n\tvideoOutDevices, err := dbo.GetDevicesByBuildingAndRoomAndRole(building, room, role)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, d := range devicesToChange { \/\/ Loop through the devices in the room\n\t\tparamMap := make(map[string]string) \/\/ Start building parameter map\n\n\t\t\/\/Get the port mapping for the device\n\t\tfor _, curPort := range d.Ports { \/\/ Loop through the found ports\n\t\t\tif strings.EqualFold(curPort.Source, input) {\n\t\t\t\tparamMap[\"port\"] = curPort.Name\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif len(paramMap) == 0 {\n\t\t\terr = errors.New(\"No port found for input.\")\n\t\t\treturn\n\t\t}\n\n\t\taction := base.ActionStructure{\n\t\t\tAction:              \"ChangeInput\",\n\t\t\tGeneratingEvaluator: \"ChangeInputDefault\",\n\t\t\tDevice:              d,\n\t\t\tParameters:          paramMap,\n\t\t\tDeviceSpecific:      false,\n\t\t\tOverridden:          false,\n\t\t}\n\n\t\tactions = append(actions, action)\n\n\t\treturn\n\t}\n\n\treturn\n}\n<commit_msg>One last fix<commit_after>package commandevaluators\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t\"github.com\/byuoitav\/av-api\/base\"\n\t\"github.com\/byuoitav\/av-api\/dbo\"\n\t\"github.com\/byuoitav\/configuration-database-microservice\/accessors\"\n)\n\n\/\/ChangeInput is struct that implements the CommandEvaluation struct\ntype ChangeInputDefault struct {\n}\n\n\/\/Evaluate fulfills the CommmandEvaluation evaluate requirement.\nfunc (p *ChangeInputDefault) Evaluate(room base.PublicRoom) (actions []base.ActionStructure, err error) {\n\t\/\/RoomWideSetVideoInput\n\tif len(room.CurrentVideoInput) > 0 { \/\/ Check if the user sent a PUT body changing the current video input\n\t\tvar tempActions []base.ActionStructure\n\n\t\ttempActions, err = generateChangeInputByRole(\n\t\t\t\"VideoOut\",\n\t\t\troom.CurrentVideoInput,\n\t\t\troom.Room,\n\t\t\troom.Building,\n\t\t)\n\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tactions = append(actions, tempActions...)\n\t}\n\n\t\/\/RoomWideSetAudioInput\n\tif len(room.CurrentAudioInput) > 0 { \/\/ Check if the user sent a PUT body changing the current audio input\n\t\tvar tempActions []base.ActionStructure\n\n\t\t\/\/generate action\n\t\ttempActions, err = generateChangeInputByRole(\n\t\t\t\"AudioOut\",\n\t\t\troom.CurrentVideoInput,\n\t\t\troom.Room,\n\t\t\troom.Building,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tactions = append(actions, tempActions...)\n\t}\n\n\t\/\/Displays\n\tfor _, d := range room.Displays { \/\/ Loop through the devices array (potentially) passed in the user's PUT body\n\t\tvar action base.ActionStructure\n\t\taction, err = generateChangeInputByDevice(d.Device, room.Room, room.Building)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tactions = append(actions, action)\n\t}\n\n\t\/\/AudioDevice\n\tfor _, d := range room.AudioDevices { \/\/ Loop through the audio devices array (potentially) passed in the user's PUT body\n\t\tvar action base.ActionStructure\n\t\taction, err = generateChangeInputByDevice(d.Device, room.Room, room.Building)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tactions = append(actions, action)\n\t}\n\n\treturn\n}\n\n\/\/Validate fulfills the Fulfill requirement on the command interface\nfunc (p *ChangeInputDefault) Validate(action base.ActionStructure) (err error) {\n\treturn nil\n}\n\n\/\/GetIncompatableCommands keeps track of actions that are incompatable (on the same device)\nfunc (p *ChangeInputDefault) GetIncompatableCommands() (incompatableActions []string) {\n\treturn\n}\n\nfunc generateChangeInputByDevice(dev base.Device, room string, building string) (action base.ActionStructure, err error) {\n\tvar curDevice accessors.Device\n\n\tcurDevice, err = dbo.GetDeviceByName(building, room, dev.Name)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tparamMap := make(map[string]string)\n\n\tfor _, port := range curDevice.Ports {\n\t\tif strings.EqualFold(port.Source, dev.Input) {\n\t\t\tparamMap[\"port\"] = port.Name\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif len(paramMap) == 0 {\n\t\terr = errors.New(\"No port found for input.\")\n\t\treturn\n\t}\n\n\taction = base.ActionStructure{\n\t\tAction:              \"change-input\",\n\t\tGeneratingEvaluator: \"changeInput\",\n\t\tDevice:              curDevice,\n\t\tParameters:          paramMap,\n\t\tDeviceSpecific:      true,\n\t\tOverridden:          false,\n\t}\n\n\treturn\n}\n\nfunc generateChangeInputByRole(role string, input string, room string, building string) (actions []base.ActionStructure, err error) {\n\tdevicesToChange, err := dbo.GetDevicesByBuildingAndRoomAndRole(building, room, role)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfor _, d := range devicesToChange { \/\/ Loop through the devices in the room\n\t\tparamMap := make(map[string]string) \/\/ Start building parameter map\n\n\t\t\/\/Get the port mapping for the device\n\t\tfor _, curPort := range d.Ports { \/\/ Loop through the found ports\n\t\t\tif strings.EqualFold(curPort.Source, input) {\n\t\t\t\tparamMap[\"port\"] = curPort.Name\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif len(paramMap) == 0 {\n\t\t\terr = errors.New(\"No port found for input.\")\n\t\t\treturn\n\t\t}\n\n\t\taction := base.ActionStructure{\n\t\t\tAction:              \"ChangeInput\",\n\t\t\tGeneratingEvaluator: \"ChangeInputDefault\",\n\t\t\tDevice:              d,\n\t\t\tParameters:          paramMap,\n\t\t\tDeviceSpecific:      false,\n\t\t\tOverridden:          false,\n\t\t}\n\n\t\tactions = append(actions, action)\n\n\t\treturn\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Code generated by \"stringer -type KeepAliveModeType\"; DO NOT EDIT\n\npackage main\n\nimport \"fmt\"\n\nconst _KeepAliveModeType_name = \"KEEPALIVE_TRANSPARENTKEEPALIVE_NO_BACKEND\"\n\nvar _KeepAliveModeType_index = [...]uint8{0, 21, 41}\n\nfunc (i KeepAliveModeType) String() string {\n\tif i < 0 || i >= KeepAliveModeType(len(_KeepAliveModeType_index)-1) {\n\t\treturn fmt.Sprintf(\"KeepAliveModeType(%d)\", i)\n\t}\n\treturn _KeepAliveModeType_name[_KeepAliveModeType_index[i]:_KeepAliveModeType_index[i+1]]\n}\n<commit_msg>update stringer<commit_after>\/\/ Code generated by \"stringer -type KeepAliveModeType\"; DO NOT EDIT.\n\npackage main\n\nimport \"fmt\"\n\nconst _KeepAliveModeType_name = \"KEEPALIVE_TRANSPARENTKEEPALIVE_NO_BACKEND\"\n\nvar _KeepAliveModeType_index = [...]uint8{0, 21, 41}\n\nfunc (i KeepAliveModeType) String() string {\n\tif i < 0 || i >= KeepAliveModeType(len(_KeepAliveModeType_index)-1) {\n\t\treturn fmt.Sprintf(\"KeepAliveModeType(%d)\", i)\n\t}\n\treturn _KeepAliveModeType_name[_KeepAliveModeType_index[i]:_KeepAliveModeType_index[i+1]]\n}\n<|endoftext|>"}
{"text":"<commit_before>package bitswap\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\tnotifications \"github.com\/ipfs\/go-ipfs\/exchange\/bitswap\/notifications\"\n\n\tcid \"gx\/ipfs\/QmNp85zy9RLrQ5oQD4hPyS39ezrrXpcaa7R4Y9kxdWQLLQ\/go-cid\"\n\tblocks \"gx\/ipfs\/QmSn9Td7xgxm9EV7iEjTckpUWmWApggzPxu7eFGWkkpwin\/go-block-format\"\n\tlogging \"gx\/ipfs\/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52\/go-log\"\n\tloggables \"gx\/ipfs\/QmT4PgCNdv73hnFAqzHqwW44q7M9PWpykSswHDxndquZbc\/go-libp2p-loggables\"\n\tlru \"gx\/ipfs\/QmVYxfoJQiZijTgPNHCHgHELvQpbsJNTg6Crmc3dQkj3yy\/golang-lru\"\n\tpeer \"gx\/ipfs\/QmXYjuNuxVzXKJCfWasQk1RqkhVLDM9jtUKhqc2WPQmFSB\/go-libp2p-peer\"\n)\n\nconst activeWantsLimit = 16\n\n\/\/ Session holds state for an individual bitswap transfer operation.\n\/\/ This allows bitswap to make smarter decisions about who to send wantlist\n\/\/ info to, and who to request blocks from\ntype Session struct {\n\tctx            context.Context\n\ttofetch        *cidQueue\n\tactivePeers    map[peer.ID]struct{}\n\tactivePeersArr []peer.ID\n\n\tbs           *Bitswap\n\tincoming     chan blkRecv\n\tnewReqs      chan []*cid.Cid\n\tcancelKeys   chan []*cid.Cid\n\tinterestReqs chan interestReq\n\n\tinterest  *lru.Cache\n\tliveWants map[string]time.Time\n\n\ttick          *time.Timer\n\tbaseTickDelay time.Duration\n\n\tlatTotal time.Duration\n\tfetchcnt int\n\n\tnotif notifications.PubSub\n\n\tuuid logging.Loggable\n\n\tid  uint64\n\ttag string\n}\n\n\/\/ NewSession creates a new bitswap session whose lifetime is bounded by the\n\/\/ given context\nfunc (bs *Bitswap) NewSession(ctx context.Context) *Session {\n\ts := &Session{\n\t\tactivePeers:   make(map[peer.ID]struct{}),\n\t\tliveWants:     make(map[string]time.Time),\n\t\tnewReqs:       make(chan []*cid.Cid),\n\t\tcancelKeys:    make(chan []*cid.Cid),\n\t\ttofetch:       newCidQueue(),\n\t\tinterestReqs:  make(chan interestReq),\n\t\tctx:           ctx,\n\t\tbs:            bs,\n\t\tincoming:      make(chan blkRecv),\n\t\tnotif:         notifications.New(),\n\t\tuuid:          loggables.Uuid(\"GetBlockRequest\"),\n\t\tbaseTickDelay: time.Millisecond * 500,\n\t\tid:            bs.getNextSessionID(),\n\t}\n\n\ts.tag = fmt.Sprint(\"bs-ses-\", s.id)\n\n\tcache, _ := lru.New(2048)\n\ts.interest = cache\n\n\tbs.sessLk.Lock()\n\tbs.sessions = append(bs.sessions, s)\n\tbs.sessLk.Unlock()\n\n\tgo s.run(ctx)\n\n\treturn s\n}\n\nfunc (bs *Bitswap) removeSession(s *Session) {\n\tbs.sessLk.Lock()\n\tdefer bs.sessLk.Unlock()\n\tfor i := 0; i < len(bs.sessions); i++ {\n\t\tif bs.sessions[i] == s {\n\t\t\tbs.sessions[i] = bs.sessions[len(bs.sessions)-1]\n\t\t\tbs.sessions = bs.sessions[:len(bs.sessions)-1]\n\t\t\treturn\n\t\t}\n\t}\n}\n\ntype blkRecv struct {\n\tfrom peer.ID\n\tblk  blocks.Block\n}\n\nfunc (s *Session) receiveBlockFrom(from peer.ID, blk blocks.Block) {\n\tselect {\n\tcase s.incoming <- blkRecv{from: from, blk: blk}:\n\tcase <-s.ctx.Done():\n\t}\n}\n\ntype interestReq struct {\n\tc    *cid.Cid\n\tresp chan bool\n}\n\n\/\/ TODO: PERF: this is using a channel to guard a map access against race\n\/\/ conditions. This is definitely much slower than a mutex, though its unclear\n\/\/ if it will actually induce any noticeable slowness. This is implemented this\n\/\/ way to avoid adding a more complex set of mutexes around the liveWants map.\n\/\/ note that in the average case (where this session *is* interested in the\n\/\/ block we received) this function will not be called, as the cid will likely\n\/\/ still be in the interest cache.\nfunc (s *Session) isLiveWant(c *cid.Cid) bool {\n\tresp := make(chan bool, 1)\n\ts.interestReqs <- interestReq{\n\t\tc:    c,\n\t\tresp: resp,\n\t}\n\n\tselect {\n\tcase want := <-resp:\n\t\treturn want\n\tcase <-s.ctx.Done():\n\t\treturn false\n\t}\n}\n\nfunc (s *Session) interestedIn(c *cid.Cid) bool {\n\treturn s.interest.Contains(c.KeyString()) || s.isLiveWant(c)\n}\n\nconst provSearchDelay = time.Second * 10\n\nfunc (s *Session) addActivePeer(p peer.ID) {\n\tif _, ok := s.activePeers[p]; !ok {\n\t\ts.activePeers[p] = struct{}{}\n\t\ts.activePeersArr = append(s.activePeersArr, p)\n\n\t\tcmgr := s.bs.network.ConnectionManager()\n\t\tcmgr.TagPeer(p, s.tag, 10)\n\t}\n}\n\nfunc (s *Session) resetTick() {\n\tif s.latTotal == 0 {\n\t\ts.tick.Reset(provSearchDelay)\n\t} else {\n\t\tavLat := s.latTotal \/ time.Duration(s.fetchcnt)\n\t\ts.tick.Reset(s.baseTickDelay + (3 * avLat))\n\t}\n}\n\nfunc (s *Session) run(ctx context.Context) {\n\ts.tick = time.NewTimer(provSearchDelay)\n\tnewpeers := make(chan peer.ID, 16)\n\tfor {\n\t\tselect {\n\t\tcase blk := <-s.incoming:\n\t\t\ts.tick.Stop()\n\n\t\t\tif blk.from != \"\" {\n\t\t\t\ts.addActivePeer(blk.from)\n\t\t\t}\n\n\t\t\ts.receiveBlock(ctx, blk.blk)\n\n\t\t\ts.resetTick()\n\t\tcase keys := <-s.newReqs:\n\t\t\tfor _, k := range keys {\n\t\t\t\ts.interest.Add(k.KeyString(), nil)\n\t\t\t}\n\t\t\tif len(s.liveWants) < activeWantsLimit {\n\t\t\t\ttoadd := activeWantsLimit - len(s.liveWants)\n\t\t\t\tif toadd > len(keys) {\n\t\t\t\t\ttoadd = len(keys)\n\t\t\t\t}\n\n\t\t\t\tnow := keys[:toadd]\n\t\t\t\tkeys = keys[toadd:]\n\n\t\t\t\ts.wantBlocks(ctx, now)\n\t\t\t}\n\t\t\tfor _, k := range keys {\n\t\t\t\ts.tofetch.Push(k)\n\t\t\t}\n\t\tcase keys := <-s.cancelKeys:\n\t\t\ts.cancel(keys)\n\n\t\tcase <-s.tick.C:\n\t\t\tvar live []*cid.Cid\n\t\t\tfor c := range s.liveWants {\n\t\t\t\tcs, _ := cid.Cast([]byte(c))\n\t\t\t\tlive = append(live, cs)\n\t\t\t\ts.liveWants[c] = time.Now()\n\t\t\t}\n\n\t\t\t\/\/ Broadcast these keys to everyone we're connected to\n\t\t\ts.bs.wm.WantBlocks(ctx, live, nil, s.id)\n\n\t\t\tif len(live) > 0 {\n\t\t\t\tgo func(k *cid.Cid) {\n\t\t\t\t\t\/\/ TODO: have a task queue setup for this to:\n\t\t\t\t\t\/\/ - rate limit\n\t\t\t\t\t\/\/ - manage timeouts\n\t\t\t\t\t\/\/ - ensure two 'findprovs' calls for the same block don't run concurrently\n\t\t\t\t\t\/\/ - share peers between sessions based on interest set\n\t\t\t\t\tfor p := range s.bs.network.FindProvidersAsync(ctx, k, 10) {\n\t\t\t\t\t\tnewpeers <- p\n\t\t\t\t\t}\n\t\t\t\t}(live[0])\n\t\t\t}\n\t\t\ts.resetTick()\n\t\tcase p := <-newpeers:\n\t\t\ts.addActivePeer(p)\n\t\tcase lwchk := <-s.interestReqs:\n\t\t\tlwchk.resp <- s.cidIsWanted(lwchk.c)\n\t\tcase <-ctx.Done():\n\t\t\ts.tick.Stop()\n\t\t\ts.bs.removeSession(s)\n\n\t\t\tcmgr := s.bs.network.ConnectionManager()\n\t\t\tfor _, p := range s.activePeersArr {\n\t\t\t\tcmgr.UntagPeer(p, s.tag)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (s *Session) cidIsWanted(c *cid.Cid) bool {\n\t_, ok := s.liveWants[c.KeyString()]\n\tif !ok {\n\t\tok = s.tofetch.Has(c)\n\t}\n\n\treturn ok\n}\n\nfunc (s *Session) receiveBlock(ctx context.Context, blk blocks.Block) {\n\tc := blk.Cid()\n\tif s.cidIsWanted(c) {\n\t\tks := c.KeyString()\n\t\ttval, ok := s.liveWants[ks]\n\t\tif ok {\n\t\t\ts.latTotal += time.Since(tval)\n\t\t\tdelete(s.liveWants, ks)\n\t\t} else {\n\t\t\ts.tofetch.Remove(c)\n\t\t}\n\t\ts.fetchcnt++\n\t\ts.notif.Publish(blk)\n\n\t\tif next := s.tofetch.Pop(); next != nil {\n\t\t\ts.wantBlocks(ctx, []*cid.Cid{next})\n\t\t}\n\t}\n}\n\nfunc (s *Session) wantBlocks(ctx context.Context, ks []*cid.Cid) {\n\tfor _, c := range ks {\n\t\ts.liveWants[c.KeyString()] = time.Now()\n\t}\n\ts.bs.wm.WantBlocks(ctx, ks, s.activePeersArr, s.id)\n}\n\nfunc (s *Session) cancel(keys []*cid.Cid) {\n\tfor _, c := range keys {\n\t\ts.tofetch.Remove(c)\n\t}\n}\n\nfunc (s *Session) cancelWants(keys []*cid.Cid) {\n\ts.cancelKeys <- keys\n}\n\nfunc (s *Session) fetch(ctx context.Context, keys []*cid.Cid) {\n\tselect {\n\tcase s.newReqs <- keys:\n\tcase <-ctx.Done():\n\t}\n}\n\n\/\/ GetBlocks fetches a set of blocks within the context of this session and\n\/\/ returns a channel that found blocks will be returned on. No order is\n\/\/ guaranteed on the returned blocks.\nfunc (s *Session) GetBlocks(ctx context.Context, keys []*cid.Cid) (<-chan blocks.Block, error) {\n\tctx = logging.ContextWithLoggable(ctx, s.uuid)\n\treturn getBlocksImpl(ctx, keys, s.notif, s.fetch, s.cancelWants)\n}\n\n\/\/ GetBlock fetches a single block\nfunc (s *Session) GetBlock(parent context.Context, k *cid.Cid) (blocks.Block, error) {\n\treturn getBlock(parent, k, s.GetBlocks)\n}\n\ntype cidQueue struct {\n\telems []*cid.Cid\n\teset  *cid.Set\n}\n\nfunc newCidQueue() *cidQueue {\n\treturn &cidQueue{eset: cid.NewSet()}\n}\n\nfunc (cq *cidQueue) Pop() *cid.Cid {\n\tfor {\n\t\tif len(cq.elems) == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\tout := cq.elems[0]\n\t\tcq.elems = cq.elems[1:]\n\n\t\tif cq.eset.Has(out) {\n\t\t\tcq.eset.Remove(out)\n\t\t\treturn out\n\t\t}\n\t}\n}\n\nfunc (cq *cidQueue) Push(c *cid.Cid) {\n\tif cq.eset.Visit(c) {\n\t\tcq.elems = append(cq.elems, c)\n\t}\n}\n\nfunc (cq *cidQueue) Remove(c *cid.Cid) {\n\tcq.eset.Remove(c)\n}\n\nfunc (cq *cidQueue) Has(c *cid.Cid) bool {\n\treturn cq.eset.Has(c)\n}\n\nfunc (cq *cidQueue) Len() int {\n\treturn cq.eset.Len()\n}\n<commit_msg>fix deadlock in bitswap sessions<commit_after>package bitswap\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\tnotifications \"github.com\/ipfs\/go-ipfs\/exchange\/bitswap\/notifications\"\n\n\tcid \"gx\/ipfs\/QmNp85zy9RLrQ5oQD4hPyS39ezrrXpcaa7R4Y9kxdWQLLQ\/go-cid\"\n\tblocks \"gx\/ipfs\/QmSn9Td7xgxm9EV7iEjTckpUWmWApggzPxu7eFGWkkpwin\/go-block-format\"\n\tlogging \"gx\/ipfs\/QmSpJByNKFX1sCsHBEp3R73FL4NF6FnQTEGyNAXHm2GS52\/go-log\"\n\tloggables \"gx\/ipfs\/QmT4PgCNdv73hnFAqzHqwW44q7M9PWpykSswHDxndquZbc\/go-libp2p-loggables\"\n\tlru \"gx\/ipfs\/QmVYxfoJQiZijTgPNHCHgHELvQpbsJNTg6Crmc3dQkj3yy\/golang-lru\"\n\tpeer \"gx\/ipfs\/QmXYjuNuxVzXKJCfWasQk1RqkhVLDM9jtUKhqc2WPQmFSB\/go-libp2p-peer\"\n)\n\nconst activeWantsLimit = 16\n\n\/\/ Session holds state for an individual bitswap transfer operation.\n\/\/ This allows bitswap to make smarter decisions about who to send wantlist\n\/\/ info to, and who to request blocks from\ntype Session struct {\n\tctx            context.Context\n\ttofetch        *cidQueue\n\tactivePeers    map[peer.ID]struct{}\n\tactivePeersArr []peer.ID\n\n\tbs           *Bitswap\n\tincoming     chan blkRecv\n\tnewReqs      chan []*cid.Cid\n\tcancelKeys   chan []*cid.Cid\n\tinterestReqs chan interestReq\n\n\tinterest  *lru.Cache\n\tliveWants map[string]time.Time\n\n\ttick          *time.Timer\n\tbaseTickDelay time.Duration\n\n\tlatTotal time.Duration\n\tfetchcnt int\n\n\tnotif notifications.PubSub\n\n\tuuid logging.Loggable\n\n\tid  uint64\n\ttag string\n}\n\n\/\/ NewSession creates a new bitswap session whose lifetime is bounded by the\n\/\/ given context\nfunc (bs *Bitswap) NewSession(ctx context.Context) *Session {\n\ts := &Session{\n\t\tactivePeers:   make(map[peer.ID]struct{}),\n\t\tliveWants:     make(map[string]time.Time),\n\t\tnewReqs:       make(chan []*cid.Cid),\n\t\tcancelKeys:    make(chan []*cid.Cid),\n\t\ttofetch:       newCidQueue(),\n\t\tinterestReqs:  make(chan interestReq),\n\t\tctx:           ctx,\n\t\tbs:            bs,\n\t\tincoming:      make(chan blkRecv),\n\t\tnotif:         notifications.New(),\n\t\tuuid:          loggables.Uuid(\"GetBlockRequest\"),\n\t\tbaseTickDelay: time.Millisecond * 500,\n\t\tid:            bs.getNextSessionID(),\n\t}\n\n\ts.tag = fmt.Sprint(\"bs-ses-\", s.id)\n\n\tcache, _ := lru.New(2048)\n\ts.interest = cache\n\n\tbs.sessLk.Lock()\n\tbs.sessions = append(bs.sessions, s)\n\tbs.sessLk.Unlock()\n\n\tgo s.run(ctx)\n\n\treturn s\n}\n\nfunc (bs *Bitswap) removeSession(s *Session) {\n\tbs.sessLk.Lock()\n\tdefer bs.sessLk.Unlock()\n\tfor i := 0; i < len(bs.sessions); i++ {\n\t\tif bs.sessions[i] == s {\n\t\t\tbs.sessions[i] = bs.sessions[len(bs.sessions)-1]\n\t\t\tbs.sessions = bs.sessions[:len(bs.sessions)-1]\n\t\t\treturn\n\t\t}\n\t}\n}\n\ntype blkRecv struct {\n\tfrom peer.ID\n\tblk  blocks.Block\n}\n\nfunc (s *Session) receiveBlockFrom(from peer.ID, blk blocks.Block) {\n\tselect {\n\tcase s.incoming <- blkRecv{from: from, blk: blk}:\n\tcase <-s.ctx.Done():\n\t}\n}\n\ntype interestReq struct {\n\tc    *cid.Cid\n\tresp chan bool\n}\n\n\/\/ TODO: PERF: this is using a channel to guard a map access against race\n\/\/ conditions. This is definitely much slower than a mutex, though its unclear\n\/\/ if it will actually induce any noticeable slowness. This is implemented this\n\/\/ way to avoid adding a more complex set of mutexes around the liveWants map.\n\/\/ note that in the average case (where this session *is* interested in the\n\/\/ block we received) this function will not be called, as the cid will likely\n\/\/ still be in the interest cache.\nfunc (s *Session) isLiveWant(c *cid.Cid) bool {\n\tresp := make(chan bool, 1)\n\tselect {\n\tcase s.interestReqs <- interestReq{\n\t\tc:    c,\n\t\tresp: resp,\n\t}:\n\tcase <-s.ctx.Done():\n\t\treturn false\n\t}\n\n\tselect {\n\tcase want := <-resp:\n\t\treturn want\n\tcase <-s.ctx.Done():\n\t\treturn false\n\t}\n}\n\nfunc (s *Session) interestedIn(c *cid.Cid) bool {\n\treturn s.interest.Contains(c.KeyString()) || s.isLiveWant(c)\n}\n\nconst provSearchDelay = time.Second * 10\n\nfunc (s *Session) addActivePeer(p peer.ID) {\n\tif _, ok := s.activePeers[p]; !ok {\n\t\ts.activePeers[p] = struct{}{}\n\t\ts.activePeersArr = append(s.activePeersArr, p)\n\n\t\tcmgr := s.bs.network.ConnectionManager()\n\t\tcmgr.TagPeer(p, s.tag, 10)\n\t}\n}\n\nfunc (s *Session) resetTick() {\n\tif s.latTotal == 0 {\n\t\ts.tick.Reset(provSearchDelay)\n\t} else {\n\t\tavLat := s.latTotal \/ time.Duration(s.fetchcnt)\n\t\ts.tick.Reset(s.baseTickDelay + (3 * avLat))\n\t}\n}\n\nfunc (s *Session) run(ctx context.Context) {\n\ts.tick = time.NewTimer(provSearchDelay)\n\tnewpeers := make(chan peer.ID, 16)\n\tfor {\n\t\tselect {\n\t\tcase blk := <-s.incoming:\n\t\t\ts.tick.Stop()\n\n\t\t\tif blk.from != \"\" {\n\t\t\t\ts.addActivePeer(blk.from)\n\t\t\t}\n\n\t\t\ts.receiveBlock(ctx, blk.blk)\n\n\t\t\ts.resetTick()\n\t\tcase keys := <-s.newReqs:\n\t\t\tfor _, k := range keys {\n\t\t\t\ts.interest.Add(k.KeyString(), nil)\n\t\t\t}\n\t\t\tif len(s.liveWants) < activeWantsLimit {\n\t\t\t\ttoadd := activeWantsLimit - len(s.liveWants)\n\t\t\t\tif toadd > len(keys) {\n\t\t\t\t\ttoadd = len(keys)\n\t\t\t\t}\n\n\t\t\t\tnow := keys[:toadd]\n\t\t\t\tkeys = keys[toadd:]\n\n\t\t\t\ts.wantBlocks(ctx, now)\n\t\t\t}\n\t\t\tfor _, k := range keys {\n\t\t\t\ts.tofetch.Push(k)\n\t\t\t}\n\t\tcase keys := <-s.cancelKeys:\n\t\t\ts.cancel(keys)\n\n\t\tcase <-s.tick.C:\n\t\t\tvar live []*cid.Cid\n\t\t\tfor c := range s.liveWants {\n\t\t\t\tcs, _ := cid.Cast([]byte(c))\n\t\t\t\tlive = append(live, cs)\n\t\t\t\ts.liveWants[c] = time.Now()\n\t\t\t}\n\n\t\t\t\/\/ Broadcast these keys to everyone we're connected to\n\t\t\ts.bs.wm.WantBlocks(ctx, live, nil, s.id)\n\n\t\t\tif len(live) > 0 {\n\t\t\t\tgo func(k *cid.Cid) {\n\t\t\t\t\t\/\/ TODO: have a task queue setup for this to:\n\t\t\t\t\t\/\/ - rate limit\n\t\t\t\t\t\/\/ - manage timeouts\n\t\t\t\t\t\/\/ - ensure two 'findprovs' calls for the same block don't run concurrently\n\t\t\t\t\t\/\/ - share peers between sessions based on interest set\n\t\t\t\t\tfor p := range s.bs.network.FindProvidersAsync(ctx, k, 10) {\n\t\t\t\t\t\tnewpeers <- p\n\t\t\t\t\t}\n\t\t\t\t}(live[0])\n\t\t\t}\n\t\t\ts.resetTick()\n\t\tcase p := <-newpeers:\n\t\t\ts.addActivePeer(p)\n\t\tcase lwchk := <-s.interestReqs:\n\t\t\tlwchk.resp <- s.cidIsWanted(lwchk.c)\n\t\tcase <-ctx.Done():\n\t\t\ts.tick.Stop()\n\t\t\ts.bs.removeSession(s)\n\n\t\t\tcmgr := s.bs.network.ConnectionManager()\n\t\t\tfor _, p := range s.activePeersArr {\n\t\t\t\tcmgr.UntagPeer(p, s.tag)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (s *Session) cidIsWanted(c *cid.Cid) bool {\n\t_, ok := s.liveWants[c.KeyString()]\n\tif !ok {\n\t\tok = s.tofetch.Has(c)\n\t}\n\n\treturn ok\n}\n\nfunc (s *Session) receiveBlock(ctx context.Context, blk blocks.Block) {\n\tc := blk.Cid()\n\tif s.cidIsWanted(c) {\n\t\tks := c.KeyString()\n\t\ttval, ok := s.liveWants[ks]\n\t\tif ok {\n\t\t\ts.latTotal += time.Since(tval)\n\t\t\tdelete(s.liveWants, ks)\n\t\t} else {\n\t\t\ts.tofetch.Remove(c)\n\t\t}\n\t\ts.fetchcnt++\n\t\ts.notif.Publish(blk)\n\n\t\tif next := s.tofetch.Pop(); next != nil {\n\t\t\ts.wantBlocks(ctx, []*cid.Cid{next})\n\t\t}\n\t}\n}\n\nfunc (s *Session) wantBlocks(ctx context.Context, ks []*cid.Cid) {\n\tfor _, c := range ks {\n\t\ts.liveWants[c.KeyString()] = time.Now()\n\t}\n\ts.bs.wm.WantBlocks(ctx, ks, s.activePeersArr, s.id)\n}\n\nfunc (s *Session) cancel(keys []*cid.Cid) {\n\tfor _, c := range keys {\n\t\ts.tofetch.Remove(c)\n\t}\n}\n\nfunc (s *Session) cancelWants(keys []*cid.Cid) {\n\tselect {\n\tcase s.cancelKeys <- keys:\n\tcase <-s.ctx.Done():\n\t}\n}\n\nfunc (s *Session) fetch(ctx context.Context, keys []*cid.Cid) {\n\tselect {\n\tcase s.newReqs <- keys:\n\tcase <-ctx.Done():\n\tcase <-s.ctx.Done():\n\t}\n}\n\n\/\/ GetBlocks fetches a set of blocks within the context of this session and\n\/\/ returns a channel that found blocks will be returned on. No order is\n\/\/ guaranteed on the returned blocks.\nfunc (s *Session) GetBlocks(ctx context.Context, keys []*cid.Cid) (<-chan blocks.Block, error) {\n\tctx = logging.ContextWithLoggable(ctx, s.uuid)\n\treturn getBlocksImpl(ctx, keys, s.notif, s.fetch, s.cancelWants)\n}\n\n\/\/ GetBlock fetches a single block\nfunc (s *Session) GetBlock(parent context.Context, k *cid.Cid) (blocks.Block, error) {\n\treturn getBlock(parent, k, s.GetBlocks)\n}\n\ntype cidQueue struct {\n\telems []*cid.Cid\n\teset  *cid.Set\n}\n\nfunc newCidQueue() *cidQueue {\n\treturn &cidQueue{eset: cid.NewSet()}\n}\n\nfunc (cq *cidQueue) Pop() *cid.Cid {\n\tfor {\n\t\tif len(cq.elems) == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\tout := cq.elems[0]\n\t\tcq.elems = cq.elems[1:]\n\n\t\tif cq.eset.Has(out) {\n\t\t\tcq.eset.Remove(out)\n\t\t\treturn out\n\t\t}\n\t}\n}\n\nfunc (cq *cidQueue) Push(c *cid.Cid) {\n\tif cq.eset.Visit(c) {\n\t\tcq.elems = append(cq.elems, c)\n\t}\n}\n\nfunc (cq *cidQueue) Remove(c *cid.Cid) {\n\tcq.eset.Remove(c)\n}\n\nfunc (cq *cidQueue) Has(c *cid.Cid) bool {\n\treturn cq.eset.Has(c)\n}\n\nfunc (cq *cidQueue) Len() int {\n\treturn cq.eset.Len()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @author\t\tAeneas Rekkas <aeneas+oss@aeneas.io>\n * @copyright \t2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>\n * @license \tApache-2.0\n *\/\n\npackage client\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jmoiron\/sqlx\"\n\t\"github.com\/pkg\/errors\"\n\tmigrate \"github.com\/rubenv\/sql-migrate\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"gopkg.in\/square\/go-jose.v2\"\n\n\t\"github.com\/ory\/fosite\"\n\t\"github.com\/ory\/x\/dbal\"\n\t\"github.com\/ory\/x\/sqlcon\"\n\t\"github.com\/ory\/x\/stringsx\"\n)\n\nvar Migrations = map[string]*dbal.PackrMigrationSource{\n\tdbal.DriverMySQL:       dbal.NewMustPackerMigrationSource(logrus.New(), AssetNames(), Asset, []string{\"migrations\/sql\/shared\", \"migrations\/sql\/mysql\"}, true),\n\tdbal.DriverPostgreSQL:  dbal.NewMustPackerMigrationSource(logrus.New(), AssetNames(), Asset, []string{\"migrations\/sql\/shared\", \"migrations\/sql\/postgres\"}, true),\n\tdbal.DriverCockroachDB: dbal.NewMustPackerMigrationSource(logrus.New(), AssetNames(), Asset, []string{\"migrations\/sql\/cockroach\"}, true),\n}\n\nfunc NewSQLManager(db *sqlx.DB, r InternalRegistry) *SQLManager {\n\treturn &SQLManager{\n\t\tr:  r,\n\t\tDB: db,\n\t}\n}\n\ntype SQLManager struct {\n\tr  InternalRegistry\n\tDB *sqlx.DB\n}\n\ntype sqlData struct {\n\tPK                                int       `db:\"pk\"`\n\tID                                string    `db:\"id\"`\n\tName                              string    `db:\"client_name\"`\n\tSecret                            string    `db:\"client_secret\"`\n\tRedirectURIs                      string    `db:\"redirect_uris\"`\n\tGrantTypes                        string    `db:\"grant_types\"`\n\tResponseTypes                     string    `db:\"response_types\"`\n\tScope                             string    `db:\"scope\"`\n\tOwner                             string    `db:\"owner\"`\n\tPolicyURI                         string    `db:\"policy_uri\"`\n\tTermsOfServiceURI                 string    `db:\"tos_uri\"`\n\tClientURI                         string    `db:\"client_uri\"`\n\tLogoURI                           string    `db:\"logo_uri\"`\n\tContacts                          string    `db:\"contacts\"`\n\tSecretExpiresAt                   int       `db:\"client_secret_expires_at\"`\n\tSectorIdentifierURI               string    `db:\"sector_identifier_uri\"`\n\tJSONWebKeysURI                    string    `db:\"jwks_uri\"`\n\tJSONWebKeys                       string    `db:\"jwks\"`\n\tTokenEndpointAuthMethod           string    `db:\"token_endpoint_auth_method\"`\n\tRequestURIs                       string    `db:\"request_uris\"`\n\tSubjectType                       string    `db:\"subject_type\"`\n\tRequestObjectSigningAlgorithm     string    `db:\"request_object_signing_alg\"`\n\tUserinfoSignedResponseAlg         string    `db:\"userinfo_signed_response_alg\"`\n\tAllowedCORSOrigins                string    `db:\"allowed_cors_origins\"`\n\tAudience                          string    `db:\"audience\"`\n\tUpdatedAt                         time.Time `db:\"updated_at\"`\n\tCreatedAt                         time.Time `db:\"created_at\"`\n\tFrontChannelLogoutURI             string    `db:\"frontchannel_logout_uri\"`\n\tFrontChannelLogoutSessionRequired bool      `db:\"frontchannel_logout_session_required\"`\n\tPostLogoutRedirectURIs            string    `db:\"post_logout_redirect_uris\"`\n\tBackChannelLogoutURI              string    `db:\"backchannel_logout_uri\"`\n\tBackChannelLogoutSessionRequired  bool      `db:\"backchannel_logout_session_required\"`\n}\n\nvar sqlParams = []string{\n\t\"id\",\n\t\"client_name\",\n\t\"client_secret\",\n\t\"redirect_uris\",\n\t\"grant_types\",\n\t\"response_types\",\n\t\"scope\",\n\t\"owner\",\n\t\"policy_uri\",\n\t\"tos_uri\",\n\t\"client_uri\",\n\t\"subject_type\",\n\t\"logo_uri\",\n\t\"contacts\",\n\t\"client_secret_expires_at\",\n\t\"sector_identifier_uri\",\n\t\"jwks\",\n\t\"jwks_uri\",\n\t\"token_endpoint_auth_method\",\n\t\"request_uris\",\n\t\"request_object_signing_alg\",\n\t\"userinfo_signed_response_alg\",\n\t\"allowed_cors_origins\",\n\t\"audience\",\n\t\"updated_at\",\n\t\"created_at\",\n\t\"frontchannel_logout_uri\",\n\t\"frontchannel_logout_session_required\",\n\t\"post_logout_redirect_uris\",\n\t\"backchannel_logout_uri\",\n\t\"backchannel_logout_session_required\",\n}\n\nfunc sqlDataFromClient(d *Client) (*sqlData, error) {\n\tjwks := \"\"\n\n\tif d.JSONWebKeys != nil {\n\t\tout, err := json.Marshal(d.JSONWebKeys)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\t\tjwks = string(out)\n\t}\n\n\tvar createdAt, updatedAt = d.CreatedAt, d.UpdatedAt\n\n\tif d.CreatedAt.IsZero() {\n\t\tcreatedAt = time.Now()\n\t}\n\n\tif d.UpdatedAt.IsZero() {\n\t\tupdatedAt = time.Now()\n\t}\n\n\treturn &sqlData{\n\t\tID:                                d.GetID(),\n\t\tName:                              d.Name,\n\t\tSecret:                            d.Secret,\n\t\tRedirectURIs:                      strings.Join(d.RedirectURIs, \"|\"),\n\t\tAudience:                          strings.Join(d.Audience, \"|\"),\n\t\tGrantTypes:                        strings.Join(d.GrantTypes, \"|\"),\n\t\tResponseTypes:                     strings.Join(d.ResponseTypes, \"|\"),\n\t\tScope:                             d.Scope,\n\t\tOwner:                             d.Owner,\n\t\tPolicyURI:                         d.PolicyURI,\n\t\tTermsOfServiceURI:                 d.TermsOfServiceURI,\n\t\tClientURI:                         d.ClientURI,\n\t\tLogoURI:                           d.LogoURI,\n\t\tContacts:                          strings.Join(d.Contacts, \"|\"),\n\t\tSecretExpiresAt:                   d.SecretExpiresAt,\n\t\tSectorIdentifierURI:               d.SectorIdentifierURI,\n\t\tJSONWebKeysURI:                    d.JSONWebKeysURI,\n\t\tJSONWebKeys:                       jwks,\n\t\tTokenEndpointAuthMethod:           d.TokenEndpointAuthMethod,\n\t\tRequestObjectSigningAlgorithm:     d.RequestObjectSigningAlgorithm,\n\t\tRequestURIs:                       strings.Join(d.RequestURIs, \"|\"),\n\t\tUserinfoSignedResponseAlg:         d.UserinfoSignedResponseAlg,\n\t\tSubjectType:                       d.SubjectType,\n\t\tAllowedCORSOrigins:                strings.Join(d.AllowedCORSOrigins, \"|\"),\n\t\tCreatedAt:                         createdAt.Round(time.Second),\n\t\tUpdatedAt:                         updatedAt.Round(time.Second),\n\t\tFrontChannelLogoutURI:             d.FrontChannelLogoutURI,\n\t\tFrontChannelLogoutSessionRequired: d.FrontChannelLogoutSessionRequired,\n\t\tPostLogoutRedirectURIs:            strings.Join(d.PostLogoutRedirectURIs, \"|\"),\n\t\tBackChannelLogoutURI:              d.BackChannelLogoutURI,\n\t\tBackChannelLogoutSessionRequired:  d.BackChannelLogoutSessionRequired,\n\t}, nil\n}\n\nfunc (d *sqlData) ToClient() (*Client, error) {\n\tc := &Client{\n\t\tClientID:                          d.ID,\n\t\tName:                              d.Name,\n\t\tSecret:                            d.Secret,\n\t\tAudience:                          stringsx.Splitx(d.Audience, \"|\"),\n\t\tRedirectURIs:                      stringsx.Splitx(d.RedirectURIs, \"|\"),\n\t\tGrantTypes:                        stringsx.Splitx(d.GrantTypes, \"|\"),\n\t\tResponseTypes:                     stringsx.Splitx(d.ResponseTypes, \"|\"),\n\t\tScope:                             d.Scope,\n\t\tOwner:                             d.Owner,\n\t\tPolicyURI:                         d.PolicyURI,\n\t\tTermsOfServiceURI:                 d.TermsOfServiceURI,\n\t\tClientURI:                         d.ClientURI,\n\t\tLogoURI:                           d.LogoURI,\n\t\tContacts:                          stringsx.Splitx(d.Contacts, \"|\"),\n\t\tSecretExpiresAt:                   d.SecretExpiresAt,\n\t\tSectorIdentifierURI:               d.SectorIdentifierURI,\n\t\tJSONWebKeysURI:                    d.JSONWebKeysURI,\n\t\tTokenEndpointAuthMethod:           d.TokenEndpointAuthMethod,\n\t\tRequestObjectSigningAlgorithm:     d.RequestObjectSigningAlgorithm,\n\t\tRequestURIs:                       stringsx.Splitx(d.RequestURIs, \"|\"),\n\t\tUserinfoSignedResponseAlg:         d.UserinfoSignedResponseAlg,\n\t\tSubjectType:                       d.SubjectType,\n\t\tAllowedCORSOrigins:                stringsx.Splitx(d.AllowedCORSOrigins, \"|\"),\n\t\tCreatedAt:                         d.CreatedAt,\n\t\tUpdatedAt:                         d.UpdatedAt,\n\t\tFrontChannelLogoutURI:             d.FrontChannelLogoutURI,\n\t\tFrontChannelLogoutSessionRequired: d.FrontChannelLogoutSessionRequired,\n\t\tPostLogoutRedirectURIs:            stringsx.Splitx(d.PostLogoutRedirectURIs, \"|\"),\n\t\tBackChannelLogoutURI:              d.BackChannelLogoutURI,\n\t\tBackChannelLogoutSessionRequired:  d.BackChannelLogoutSessionRequired,\n\t}\n\n\tif d.JSONWebKeys != \"\" {\n\t\tc.JSONWebKeys = new(jose.JSONWebKeySet)\n\t\tif err := json.Unmarshal([]byte(d.JSONWebKeys), &c.JSONWebKeys); err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\t}\n\n\treturn c, nil\n}\n\nfunc (m *SQLManager) PlanMigration(dbName string) ([]*migrate.PlannedMigration, error) {\n\tmigrate.SetTable(\"hydra_client_migration\")\n\tplan, _, err := migrate.PlanMigration(m.DB.DB, dbal.Canonicalize(m.DB.DriverName()), Migrations[dbName], migrate.Up, 0)\n\treturn plan, errors.WithStack(err)\n}\n\nfunc (m *SQLManager) CreateSchemas(dbName string) (int, error) {\n\tmigrate.SetTable(\"hydra_client_migration\")\n\tn, err := migrate.Exec(m.DB.DB, dbal.Canonicalize(m.DB.DriverName()), Migrations[dbName], migrate.Up)\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"Could not migrate sql schema, applied %d Migrations\", n)\n\t}\n\treturn n, nil\n}\n\nfunc (m *SQLManager) GetConcreteClient(ctx context.Context, id string) (*Client, error) {\n\tvar d sqlData\n\tif err := m.DB.GetContext(ctx, &d, m.DB.Rebind(\"SELECT * FROM hydra_client WHERE id=?\"), id); err != nil {\n\t\treturn nil, sqlcon.HandleError(err)\n\t}\n\n\treturn d.ToClient()\n}\n\nfunc (m *SQLManager) GetClient(ctx context.Context, id string) (fosite.Client, error) {\n\treturn m.GetConcreteClient(ctx, id)\n}\n\nfunc (m *SQLManager) UpdateClient(ctx context.Context, c *Client) error {\n\to, err := m.GetClient(ctx, c.GetID())\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif c.Secret == \"\" {\n\t\tc.Secret = string(o.GetHashedSecret())\n\t} else {\n\t\th, err := m.r.ClientHasher().Hash(ctx, []byte(c.Secret))\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tc.Secret = string(h)\n\t}\n\n\ts, err := sqlDataFromClient(c)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tvar query []string\n\tfor _, param := range sqlParams {\n\t\tquery = append(query, fmt.Sprintf(\"%s=:%s\", param, param))\n\t}\n\n\tif _, err := m.DB.NamedExecContext(ctx, fmt.Sprintf(`UPDATE hydra_client SET %s WHERE id=:id`, strings.Join(query, \", \")), s); err != nil {\n\t\treturn sqlcon.HandleError(err)\n\t}\n\treturn nil\n}\n\nfunc (m *SQLManager) Authenticate(ctx context.Context, id string, secret []byte) (*Client, error) {\n\tc, err := m.GetConcreteClient(ctx, id)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\tif err := m.r.ClientHasher().Compare(ctx, c.GetHashedSecret(), secret); err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\treturn c, nil\n}\n\nfunc (m *SQLManager) CreateClient(ctx context.Context, c *Client) error {\n\th, err := m.r.ClientHasher().Hash(ctx, []byte(c.Secret))\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tc.Secret = string(h)\n\n\tdata, err := sqlDataFromClient(c)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif _, err := m.DB.NamedExecContext(ctx, fmt.Sprintf(\n\t\t\"INSERT INTO hydra_client (%s) VALUES (%s)\",\n\t\tstrings.Join(sqlParams, \", \"),\n\t\t\":\"+strings.Join(sqlParams, \", :\"),\n\t), data); err != nil {\n\t\treturn sqlcon.HandleError(err)\n\t}\n\n\treturn nil\n}\n\nfunc (m *SQLManager) DeleteClient(ctx context.Context, id string) error {\n\tif _, err := m.DB.ExecContext(ctx, m.DB.Rebind(`DELETE FROM hydra_client WHERE id=?`), id); err != nil {\n\t\treturn sqlcon.HandleError(err)\n\t}\n\treturn nil\n}\n\nfunc (m *SQLManager) GetClients(ctx context.Context, limit, offset int) (clients []Client, err error) {\n\td := make([]sqlData, 0)\n\n\tif err := m.DB.SelectContext(ctx, &d, m.DB.Rebind(\"SELECT * FROM hydra_client ORDER BY id LIMIT ? OFFSET ?\"), limit, offset); err != nil {\n\t\treturn nil, sqlcon.HandleError(err)\n\t}\n\n\tclients = make([]Client, len(d))\n\tfor i, k := range d {\n\t\tc, err := k.ToClient()\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\n\t\tclients[i] = *c\n\t}\n\n\treturn clients, nil\n}\n\nfunc (m *SQLManager) CountClients(ctx context.Context) (int, error) {\n\tvar n int\n\tif err := m.DB.QueryRow(\"SELECT count(*) FROM hydra_client\").Scan(&n); err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn 0, sqlcon.HandleError(err)\n\t}\n\n\treturn n, nil\n}\n<commit_msg>client: Change pk field to int64 (#1597)<commit_after>\/*\n * Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @author\t\tAeneas Rekkas <aeneas+oss@aeneas.io>\n * @copyright \t2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>\n * @license \tApache-2.0\n *\/\n\npackage client\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jmoiron\/sqlx\"\n\t\"github.com\/pkg\/errors\"\n\tmigrate \"github.com\/rubenv\/sql-migrate\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"gopkg.in\/square\/go-jose.v2\"\n\n\t\"github.com\/ory\/fosite\"\n\t\"github.com\/ory\/x\/dbal\"\n\t\"github.com\/ory\/x\/sqlcon\"\n\t\"github.com\/ory\/x\/stringsx\"\n)\n\nvar Migrations = map[string]*dbal.PackrMigrationSource{\n\tdbal.DriverMySQL:       dbal.NewMustPackerMigrationSource(logrus.New(), AssetNames(), Asset, []string{\"migrations\/sql\/shared\", \"migrations\/sql\/mysql\"}, true),\n\tdbal.DriverPostgreSQL:  dbal.NewMustPackerMigrationSource(logrus.New(), AssetNames(), Asset, []string{\"migrations\/sql\/shared\", \"migrations\/sql\/postgres\"}, true),\n\tdbal.DriverCockroachDB: dbal.NewMustPackerMigrationSource(logrus.New(), AssetNames(), Asset, []string{\"migrations\/sql\/cockroach\"}, true),\n}\n\nfunc NewSQLManager(db *sqlx.DB, r InternalRegistry) *SQLManager {\n\treturn &SQLManager{\n\t\tr:  r,\n\t\tDB: db,\n\t}\n}\n\ntype SQLManager struct {\n\tr  InternalRegistry\n\tDB *sqlx.DB\n}\n\ntype sqlData struct {\n\tPK                                int64     `db:\"pk\"`\n\tID                                string    `db:\"id\"`\n\tName                              string    `db:\"client_name\"`\n\tSecret                            string    `db:\"client_secret\"`\n\tRedirectURIs                      string    `db:\"redirect_uris\"`\n\tGrantTypes                        string    `db:\"grant_types\"`\n\tResponseTypes                     string    `db:\"response_types\"`\n\tScope                             string    `db:\"scope\"`\n\tOwner                             string    `db:\"owner\"`\n\tPolicyURI                         string    `db:\"policy_uri\"`\n\tTermsOfServiceURI                 string    `db:\"tos_uri\"`\n\tClientURI                         string    `db:\"client_uri\"`\n\tLogoURI                           string    `db:\"logo_uri\"`\n\tContacts                          string    `db:\"contacts\"`\n\tSecretExpiresAt                   int       `db:\"client_secret_expires_at\"`\n\tSectorIdentifierURI               string    `db:\"sector_identifier_uri\"`\n\tJSONWebKeysURI                    string    `db:\"jwks_uri\"`\n\tJSONWebKeys                       string    `db:\"jwks\"`\n\tTokenEndpointAuthMethod           string    `db:\"token_endpoint_auth_method\"`\n\tRequestURIs                       string    `db:\"request_uris\"`\n\tSubjectType                       string    `db:\"subject_type\"`\n\tRequestObjectSigningAlgorithm     string    `db:\"request_object_signing_alg\"`\n\tUserinfoSignedResponseAlg         string    `db:\"userinfo_signed_response_alg\"`\n\tAllowedCORSOrigins                string    `db:\"allowed_cors_origins\"`\n\tAudience                          string    `db:\"audience\"`\n\tUpdatedAt                         time.Time `db:\"updated_at\"`\n\tCreatedAt                         time.Time `db:\"created_at\"`\n\tFrontChannelLogoutURI             string    `db:\"frontchannel_logout_uri\"`\n\tFrontChannelLogoutSessionRequired bool      `db:\"frontchannel_logout_session_required\"`\n\tPostLogoutRedirectURIs            string    `db:\"post_logout_redirect_uris\"`\n\tBackChannelLogoutURI              string    `db:\"backchannel_logout_uri\"`\n\tBackChannelLogoutSessionRequired  bool      `db:\"backchannel_logout_session_required\"`\n}\n\nvar sqlParams = []string{\n\t\"id\",\n\t\"client_name\",\n\t\"client_secret\",\n\t\"redirect_uris\",\n\t\"grant_types\",\n\t\"response_types\",\n\t\"scope\",\n\t\"owner\",\n\t\"policy_uri\",\n\t\"tos_uri\",\n\t\"client_uri\",\n\t\"subject_type\",\n\t\"logo_uri\",\n\t\"contacts\",\n\t\"client_secret_expires_at\",\n\t\"sector_identifier_uri\",\n\t\"jwks\",\n\t\"jwks_uri\",\n\t\"token_endpoint_auth_method\",\n\t\"request_uris\",\n\t\"request_object_signing_alg\",\n\t\"userinfo_signed_response_alg\",\n\t\"allowed_cors_origins\",\n\t\"audience\",\n\t\"updated_at\",\n\t\"created_at\",\n\t\"frontchannel_logout_uri\",\n\t\"frontchannel_logout_session_required\",\n\t\"post_logout_redirect_uris\",\n\t\"backchannel_logout_uri\",\n\t\"backchannel_logout_session_required\",\n}\n\nfunc sqlDataFromClient(d *Client) (*sqlData, error) {\n\tjwks := \"\"\n\n\tif d.JSONWebKeys != nil {\n\t\tout, err := json.Marshal(d.JSONWebKeys)\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\t\tjwks = string(out)\n\t}\n\n\tvar createdAt, updatedAt = d.CreatedAt, d.UpdatedAt\n\n\tif d.CreatedAt.IsZero() {\n\t\tcreatedAt = time.Now()\n\t}\n\n\tif d.UpdatedAt.IsZero() {\n\t\tupdatedAt = time.Now()\n\t}\n\n\treturn &sqlData{\n\t\tID:                                d.GetID(),\n\t\tName:                              d.Name,\n\t\tSecret:                            d.Secret,\n\t\tRedirectURIs:                      strings.Join(d.RedirectURIs, \"|\"),\n\t\tAudience:                          strings.Join(d.Audience, \"|\"),\n\t\tGrantTypes:                        strings.Join(d.GrantTypes, \"|\"),\n\t\tResponseTypes:                     strings.Join(d.ResponseTypes, \"|\"),\n\t\tScope:                             d.Scope,\n\t\tOwner:                             d.Owner,\n\t\tPolicyURI:                         d.PolicyURI,\n\t\tTermsOfServiceURI:                 d.TermsOfServiceURI,\n\t\tClientURI:                         d.ClientURI,\n\t\tLogoURI:                           d.LogoURI,\n\t\tContacts:                          strings.Join(d.Contacts, \"|\"),\n\t\tSecretExpiresAt:                   d.SecretExpiresAt,\n\t\tSectorIdentifierURI:               d.SectorIdentifierURI,\n\t\tJSONWebKeysURI:                    d.JSONWebKeysURI,\n\t\tJSONWebKeys:                       jwks,\n\t\tTokenEndpointAuthMethod:           d.TokenEndpointAuthMethod,\n\t\tRequestObjectSigningAlgorithm:     d.RequestObjectSigningAlgorithm,\n\t\tRequestURIs:                       strings.Join(d.RequestURIs, \"|\"),\n\t\tUserinfoSignedResponseAlg:         d.UserinfoSignedResponseAlg,\n\t\tSubjectType:                       d.SubjectType,\n\t\tAllowedCORSOrigins:                strings.Join(d.AllowedCORSOrigins, \"|\"),\n\t\tCreatedAt:                         createdAt.Round(time.Second),\n\t\tUpdatedAt:                         updatedAt.Round(time.Second),\n\t\tFrontChannelLogoutURI:             d.FrontChannelLogoutURI,\n\t\tFrontChannelLogoutSessionRequired: d.FrontChannelLogoutSessionRequired,\n\t\tPostLogoutRedirectURIs:            strings.Join(d.PostLogoutRedirectURIs, \"|\"),\n\t\tBackChannelLogoutURI:              d.BackChannelLogoutURI,\n\t\tBackChannelLogoutSessionRequired:  d.BackChannelLogoutSessionRequired,\n\t}, nil\n}\n\nfunc (d *sqlData) ToClient() (*Client, error) {\n\tc := &Client{\n\t\tClientID:                          d.ID,\n\t\tName:                              d.Name,\n\t\tSecret:                            d.Secret,\n\t\tAudience:                          stringsx.Splitx(d.Audience, \"|\"),\n\t\tRedirectURIs:                      stringsx.Splitx(d.RedirectURIs, \"|\"),\n\t\tGrantTypes:                        stringsx.Splitx(d.GrantTypes, \"|\"),\n\t\tResponseTypes:                     stringsx.Splitx(d.ResponseTypes, \"|\"),\n\t\tScope:                             d.Scope,\n\t\tOwner:                             d.Owner,\n\t\tPolicyURI:                         d.PolicyURI,\n\t\tTermsOfServiceURI:                 d.TermsOfServiceURI,\n\t\tClientURI:                         d.ClientURI,\n\t\tLogoURI:                           d.LogoURI,\n\t\tContacts:                          stringsx.Splitx(d.Contacts, \"|\"),\n\t\tSecretExpiresAt:                   d.SecretExpiresAt,\n\t\tSectorIdentifierURI:               d.SectorIdentifierURI,\n\t\tJSONWebKeysURI:                    d.JSONWebKeysURI,\n\t\tTokenEndpointAuthMethod:           d.TokenEndpointAuthMethod,\n\t\tRequestObjectSigningAlgorithm:     d.RequestObjectSigningAlgorithm,\n\t\tRequestURIs:                       stringsx.Splitx(d.RequestURIs, \"|\"),\n\t\tUserinfoSignedResponseAlg:         d.UserinfoSignedResponseAlg,\n\t\tSubjectType:                       d.SubjectType,\n\t\tAllowedCORSOrigins:                stringsx.Splitx(d.AllowedCORSOrigins, \"|\"),\n\t\tCreatedAt:                         d.CreatedAt,\n\t\tUpdatedAt:                         d.UpdatedAt,\n\t\tFrontChannelLogoutURI:             d.FrontChannelLogoutURI,\n\t\tFrontChannelLogoutSessionRequired: d.FrontChannelLogoutSessionRequired,\n\t\tPostLogoutRedirectURIs:            stringsx.Splitx(d.PostLogoutRedirectURIs, \"|\"),\n\t\tBackChannelLogoutURI:              d.BackChannelLogoutURI,\n\t\tBackChannelLogoutSessionRequired:  d.BackChannelLogoutSessionRequired,\n\t}\n\n\tif d.JSONWebKeys != \"\" {\n\t\tc.JSONWebKeys = new(jose.JSONWebKeySet)\n\t\tif err := json.Unmarshal([]byte(d.JSONWebKeys), &c.JSONWebKeys); err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\t}\n\n\treturn c, nil\n}\n\nfunc (m *SQLManager) PlanMigration(dbName string) ([]*migrate.PlannedMigration, error) {\n\tmigrate.SetTable(\"hydra_client_migration\")\n\tplan, _, err := migrate.PlanMigration(m.DB.DB, dbal.Canonicalize(m.DB.DriverName()), Migrations[dbName], migrate.Up, 0)\n\treturn plan, errors.WithStack(err)\n}\n\nfunc (m *SQLManager) CreateSchemas(dbName string) (int, error) {\n\tmigrate.SetTable(\"hydra_client_migration\")\n\tn, err := migrate.Exec(m.DB.DB, dbal.Canonicalize(m.DB.DriverName()), Migrations[dbName], migrate.Up)\n\tif err != nil {\n\t\treturn 0, errors.Wrapf(err, \"Could not migrate sql schema, applied %d Migrations\", n)\n\t}\n\treturn n, nil\n}\n\nfunc (m *SQLManager) GetConcreteClient(ctx context.Context, id string) (*Client, error) {\n\tvar d sqlData\n\tif err := m.DB.GetContext(ctx, &d, m.DB.Rebind(\"SELECT * FROM hydra_client WHERE id=?\"), id); err != nil {\n\t\treturn nil, sqlcon.HandleError(err)\n\t}\n\n\treturn d.ToClient()\n}\n\nfunc (m *SQLManager) GetClient(ctx context.Context, id string) (fosite.Client, error) {\n\treturn m.GetConcreteClient(ctx, id)\n}\n\nfunc (m *SQLManager) UpdateClient(ctx context.Context, c *Client) error {\n\to, err := m.GetClient(ctx, c.GetID())\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif c.Secret == \"\" {\n\t\tc.Secret = string(o.GetHashedSecret())\n\t} else {\n\t\th, err := m.r.ClientHasher().Hash(ctx, []byte(c.Secret))\n\t\tif err != nil {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t\tc.Secret = string(h)\n\t}\n\n\ts, err := sqlDataFromClient(c)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tvar query []string\n\tfor _, param := range sqlParams {\n\t\tquery = append(query, fmt.Sprintf(\"%s=:%s\", param, param))\n\t}\n\n\tif _, err := m.DB.NamedExecContext(ctx, fmt.Sprintf(`UPDATE hydra_client SET %s WHERE id=:id`, strings.Join(query, \", \")), s); err != nil {\n\t\treturn sqlcon.HandleError(err)\n\t}\n\treturn nil\n}\n\nfunc (m *SQLManager) Authenticate(ctx context.Context, id string, secret []byte) (*Client, error) {\n\tc, err := m.GetConcreteClient(ctx, id)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\tif err := m.r.ClientHasher().Compare(ctx, c.GetHashedSecret(), secret); err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\treturn c, nil\n}\n\nfunc (m *SQLManager) CreateClient(ctx context.Context, c *Client) error {\n\th, err := m.r.ClientHasher().Hash(ctx, []byte(c.Secret))\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tc.Secret = string(h)\n\n\tdata, err := sqlDataFromClient(c)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\tif _, err := m.DB.NamedExecContext(ctx, fmt.Sprintf(\n\t\t\"INSERT INTO hydra_client (%s) VALUES (%s)\",\n\t\tstrings.Join(sqlParams, \", \"),\n\t\t\":\"+strings.Join(sqlParams, \", :\"),\n\t), data); err != nil {\n\t\treturn sqlcon.HandleError(err)\n\t}\n\n\treturn nil\n}\n\nfunc (m *SQLManager) DeleteClient(ctx context.Context, id string) error {\n\tif _, err := m.DB.ExecContext(ctx, m.DB.Rebind(`DELETE FROM hydra_client WHERE id=?`), id); err != nil {\n\t\treturn sqlcon.HandleError(err)\n\t}\n\treturn nil\n}\n\nfunc (m *SQLManager) GetClients(ctx context.Context, limit, offset int) (clients []Client, err error) {\n\td := make([]sqlData, 0)\n\n\tif err := m.DB.SelectContext(ctx, &d, m.DB.Rebind(\"SELECT * FROM hydra_client ORDER BY id LIMIT ? OFFSET ?\"), limit, offset); err != nil {\n\t\treturn nil, sqlcon.HandleError(err)\n\t}\n\n\tclients = make([]Client, len(d))\n\tfor i, k := range d {\n\t\tc, err := k.ToClient()\n\t\tif err != nil {\n\t\t\treturn nil, errors.WithStack(err)\n\t\t}\n\n\t\tclients[i] = *c\n\t}\n\n\treturn clients, nil\n}\n\nfunc (m *SQLManager) CountClients(ctx context.Context) (int, error) {\n\tvar n int\n\tif err := m.DB.QueryRow(\"SELECT count(*) FROM hydra_client\").Scan(&n); err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn 0, sqlcon.HandleError(err)\n\t}\n\n\treturn n, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package clustering\n\nimport (\n\t\"github.com\/sjwhitworth\/golearn\/base\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n\t\"testing\"\n)\n\nfunc TestExpectationMaximization(t *testing.T) {\n\tConvey(\"Doing EM-based clustering\", t, func() {\n\t\tem, _ := NewExpectationMaximization(2)\n\n\t\t\/\/ Initialization tests\n\t\t\/\/ Trying to create NewExpectationMaximization with < 1 component\n\t\tConvey(\"With less than one component\", func() {\n\t\t\tConvey(\"Creating a new instance\", func() {\n\t\t\t\t_, err := NewExpectationMaximization(0)\n\t\t\t\tConvey(\"Should result in a InsufficientComponentsError\", func() {\n\t\t\t\t\tSo(err, ShouldEqual, InsufficientComponentsError)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\t\/\/ Data tests\n\t\t\/\/ Trying to Fit with fewer samples than components\n\t\tConvey(\"With insufficient training data\", func() {\n\t\t\tConvey(\"Fitting\", func() {\n\t\t\t\ttestData, err := base.ParseCSVToInstances(\".\/gaussian_mixture_single_obs.csv\", false)\n\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\terr = em.Fit(testData)\n\n\t\t\t\tConvey(\"Should result in a InsufficientDataError\", func() {\n\t\t\t\t\tSo(err, ShouldEqual, InsufficientDataError)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\t\/\/ Trying to Predict before having Fit\n\t\tConvey(\"With no training data\", func() {\n\t\t\tConvey(\"Predicting\", func() {\n\t\t\t\ttestData, err := base.ParseCSVToInstances(\".\/gaussian_mixture.csv\", false)\n\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\t_, err = em.Predict(testData)\n\n\t\t\t\tConvey(\"Should result in a NoTrainingDataError\", func() {\n\t\t\t\t\tSo(err, ShouldEqual, NoTrainingDataError)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\t\/\/ Computation tests\n\t\t\/\/ Test the predictions are resonable\n\t\tConvey(\"With sufficient training data\", func() {\n\t\t\tinstances, err := base.ParseCSVToInstances(\".\/gaussian_mixture.csv\", true)\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tConvey(\"Fitting\", func() {\n\t\t\t\terr := em.Fit(instances)\n\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\tfirst_mean := em.Params.Means.At(0, 0)\n\n\t\t\t\tConvey(\"It converges to reasonable a value\", func() {\n\t\t\t\t\tSo(first_mean, ShouldAlmostEqual, -5.973, .1)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t})\n}\n\nfunc BenchmarkExpectationMaximizationOneRow(b *testing.B) {\n\t\/\/ Omits error handling in favor of brevity\n\ttrainData, _ := base.ParseCSVToInstances(\".\/gaussian_mixture.csv\", false)\n\ttestData, _ := base.ParseCSVToInstances(\".\/gaussian_mixture.csv\", false)\n\n\tem, err := NewExpectationMaximization(2)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tem.Fit(trainData)\n\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tem.Predict(testData)\n\t}\n}\n<commit_msg>Add Convey \"Test more code\"<commit_after>package clustering\n\nimport (\n\t\"github.com\/sjwhitworth\/golearn\/base\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n\t\"testing\"\n)\n\nfunc TestExpectationMaximization(t *testing.T) {\n\tConvey(\"Doing EM-based clustering\", t, func() {\n\t\tem, _ := NewExpectationMaximization(2)\n\n\t\t\/\/ Initialization tests\n\t\t\/\/ Trying to create NewExpectationMaximization with < 1 component\n\t\tConvey(\"With less than one component\", func() {\n\t\t\tConvey(\"Creating a new instance\", func() {\n\t\t\t\t_, err := NewExpectationMaximization(0)\n\t\t\t\tConvey(\"Should result in a InsufficientComponentsError\", func() {\n\t\t\t\t\tSo(err, ShouldEqual, InsufficientComponentsError)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\t\/\/ Data tests\n\t\t\/\/ Trying to Fit with fewer samples than components\n\t\tConvey(\"With insufficient training data\", func() {\n\t\t\tConvey(\"Fitting\", func() {\n\t\t\t\ttestData, err := base.ParseCSVToInstances(\".\/gaussian_mixture_single_obs.csv\", false)\n\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\terr = em.Fit(testData)\n\n\t\t\t\tConvey(\"Should result in a InsufficientDataError\", func() {\n\t\t\t\t\tSo(err, ShouldEqual, InsufficientDataError)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\t\/\/ Trying to Predict before having Fit\n\t\tConvey(\"With no training data\", func() {\n\t\t\tConvey(\"Predicting\", func() {\n\t\t\t\ttestData, err := base.ParseCSVToInstances(\".\/gaussian_mixture.csv\", false)\n\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\t_, err = em.Predict(testData)\n\n\t\t\t\tConvey(\"Should result in a NoTrainingDataError\", func() {\n\t\t\t\t\tSo(err, ShouldEqual, NoTrainingDataError)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\t\/\/ Computation tests\n\t\t\/\/ Test the predictions are resonable\n\t\tConvey(\"With sufficient training data\", func() {\n\t\t\tinstances, err := base.ParseCSVToInstances(\".\/gaussian_mixture.csv\", true)\n\t\t\tSo(err, ShouldBeNil)\n\n\t\t\tConvey(\"Fitting\", func() {\n\t\t\t\terr := em.Fit(instances)\n\t\t\t\tSo(err, ShouldBeNil)\n\n\t\t\t\tfirst_mean := em.Params.Means.At(0, 0)\n\n\t\t\t\tConvey(\"It converges to reasonable a value\", func() {\n\t\t\t\t\tSo(first_mean, ShouldAlmostEqual, -5.973, .1)\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\n\t\tConvey(\"Test more code\", func() {\n\t\t\ttrainData, _ := base.ParseCSVToInstances(\".\/gaussian_mixture.csv\", false)\n\t\t\ttestData, _ := base.ParseCSVToInstances(\".\/gaussian_mixture.csv\", false)\n\n\t\t\tem, err := NewExpectationMaximization(1)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tem.Fit(trainData)\n\n\t\t\tem.Predict(testData)\n\t\t})\n\t})\n}\n\nfunc BenchmarkExpectationMaximizationOneRow(b *testing.B) {\n\t\/\/ Omits error handling in favor of brevity\n\ttrainData, _ := base.ParseCSVToInstances(\".\/gaussian_mixture.csv\", false)\n\ttestData, _ := base.ParseCSVToInstances(\".\/gaussian_mixture.csv\", false)\n\n\tem, err := NewExpectationMaximization(2)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tem.Fit(trainData)\n\n\tb.ResetTimer()\n\tfor n := 0; n < b.N; n++ {\n\t\tem.Predict(testData)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Reborndb Org. All Rights Reserved.\n\/\/ Licensed under the MIT (MIT-LICENSE.txt) license.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\n\tlog \"github.com\/ngaut\/logging\"\n)\n\ntype qdbArgs struct {\n\tAddr   string `json:\"addr\"`\n\tDBType string `json:\"dbtype\"`\n\tCPUNum string `json:\"cpu_num\"`\n}\n\n\/\/ qdb-server\nfunc startQDB(args *qdbArgs) (*process, error) {\n\tp := newDefaultProcess(\"qdb-server\", qdbType)\n\n\tif len(args.Addr) == 0 {\n\t\treturn nil, fmt.Errorf(\"qdb must have an address, not empty\")\n\t}\n\n\tif len(args.CPUNum) == 0 {\n\t\targs.CPUNum = \"2\"\n\t}\n\n\tp.Ctx[\"addr\"] = args.Addr\n\n\tif len(qdbConfigFile) > 0 {\n\t\tp.addCmdArgs(fmt.Sprintf(\"--config=%s\", qdbConfigFile))\n\t}\n\n\tp.addCmdArgs(\"-L\", path.Join(p.baseLogDir(), \"qdb.log\"))\n\tp.addCmdArgs(fmt.Sprintf(\"--ncpu=%s\", args.CPUNum))\n\tp.addCmdArgs(fmt.Sprintf(\"--dbtype=%s\", args.DBType))\n\tp.addCmdArgs(fmt.Sprintf(\"--dbpath=%s\", path.Join(p.baseDataDir(), \"db\")))\n\tp.addCmdArgs(fmt.Sprintf(\"--addr=%s\", args.Addr))\n\tp.addCmdArgs(fmt.Sprintf(\"--pidfile=%s\", p.pidPath()))\n\tp.addCmdArgs(fmt.Sprintf(\"--dump_path=%s\", path.Join(p.baseDataDir(), \"dump.rdb\")))\n\tp.addCmdArgs(fmt.Sprintf(\"--sync_file_path=%s\", path.Join(p.baseDataDir(), \"sync.pipe\")))\n\tp.addCmdArgs(fmt.Sprintf(\"--repl_backlog_file_path=%s\", path.Join(p.baseDataDir(), \"repl_backlog\")))\n\n\t\/\/ below we use fixed config, later maybe passed from args\n\tp.addCmdArgs(fmt.Sprintf(\"--conn_timeout=900\"))\n\tp.addCmdArgs(fmt.Sprintf(\"--sync_file_size=34359738368\"))\n\tp.addCmdArgs(fmt.Sprintf(\"--sync_buff_size=8388608\"))\n\tp.addCmdArgs(fmt.Sprintf(\"--repl_backlog_size=10737418240\"))\n\n\tbindRedisProcHandler(p)\n\n\tlog.Infof(\"%s %v\", p.Cmd, p.Args)\n\n\tif err := p.start(); err != nil {\n\t\tlog.Errorf(\"start redis err %v\", err)\n\t\treturn nil, err\n\t}\n\n\taddCheckProc(p)\n\n\treturn p, nil\n}\n<commit_msg>remove unnecessary log<commit_after>\/\/ Copyright 2015 Reborndb Org. All Rights Reserved.\n\/\/ Licensed under the MIT (MIT-LICENSE.txt) license.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"path\"\n\n\tlog \"github.com\/ngaut\/logging\"\n)\n\ntype qdbArgs struct {\n\tAddr   string `json:\"addr\"`\n\tDBType string `json:\"dbtype\"`\n\tCPUNum string `json:\"cpu_num\"`\n}\n\n\/\/ qdb-server\nfunc startQDB(args *qdbArgs) (*process, error) {\n\tp := newDefaultProcess(\"qdb-server\", qdbType)\n\n\tif len(args.Addr) == 0 {\n\t\treturn nil, fmt.Errorf(\"qdb must have an address, not empty\")\n\t}\n\n\tif len(args.CPUNum) == 0 {\n\t\targs.CPUNum = \"2\"\n\t}\n\n\tp.Ctx[\"addr\"] = args.Addr\n\n\tif len(qdbConfigFile) > 0 {\n\t\tp.addCmdArgs(fmt.Sprintf(\"--config=%s\", qdbConfigFile))\n\t}\n\n\tp.addCmdArgs(\"-L\", path.Join(p.baseLogDir(), \"qdb.log\"))\n\tp.addCmdArgs(fmt.Sprintf(\"--ncpu=%s\", args.CPUNum))\n\tp.addCmdArgs(fmt.Sprintf(\"--dbtype=%s\", args.DBType))\n\tp.addCmdArgs(fmt.Sprintf(\"--dbpath=%s\", path.Join(p.baseDataDir(), \"db\")))\n\tp.addCmdArgs(fmt.Sprintf(\"--addr=%s\", args.Addr))\n\tp.addCmdArgs(fmt.Sprintf(\"--pidfile=%s\", p.pidPath()))\n\tp.addCmdArgs(fmt.Sprintf(\"--dump_path=%s\", path.Join(p.baseDataDir(), \"dump.rdb\")))\n\tp.addCmdArgs(fmt.Sprintf(\"--sync_file_path=%s\", path.Join(p.baseDataDir(), \"sync.pipe\")))\n\tp.addCmdArgs(fmt.Sprintf(\"--repl_backlog_file_path=%s\", path.Join(p.baseDataDir(), \"repl_backlog\")))\n\n\t\/\/ below we use fixed config, later maybe passed from args\n\tp.addCmdArgs(fmt.Sprintf(\"--conn_timeout=900\"))\n\tp.addCmdArgs(fmt.Sprintf(\"--sync_file_size=34359738368\"))\n\tp.addCmdArgs(fmt.Sprintf(\"--sync_buff_size=8388608\"))\n\tp.addCmdArgs(fmt.Sprintf(\"--repl_backlog_size=10737418240\"))\n\n\tbindRedisProcHandler(p)\n\n\tif err := p.start(); err != nil {\n\t\tlog.Errorf(\"start redis err %v\", err)\n\t\treturn nil, err\n\t}\n\n\taddCheckProc(p)\n\n\treturn p, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"golang.org\/x\/build\/buildlet\"\n\t\"golang.org\/x\/build\/internal\/gomote\/protos\"\n)\n\nfunc legacyDestroy(args []string) error {\n\tif activeGroup != nil {\n\t\treturn fmt.Errorf(\"command does not support groups\")\n\t}\n\n\tfs := flag.NewFlagSet(\"destroy\", flag.ContinueOnError)\n\tfs.Usage = func() {\n\t\tfmt.Fprintln(os.Stderr, \"destroy usage: gomote destroy <instance>\")\n\t\tfs.PrintDefaults()\n\t\tif fs.NArg() == 0 {\n\t\t\t\/\/ List buildlets that you might want to destroy.\n\t\t\tcc, err := buildlet.NewCoordinatorClientFromFlags()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\trbs, err := cc.RemoteBuildlets()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tif len(rbs) > 0 {\n\t\t\t\tfmt.Printf(\"possible instances:\\n\")\n\t\t\t\tfor _, rb := range rbs {\n\t\t\t\t\tfmt.Printf(\"\\t%s\\n\", rb.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tos.Exit(1)\n\t}\n\n\tfs.Parse(args)\n\tif fs.NArg() != 1 {\n\t\tfs.Usage()\n\t}\n\tname := fs.Arg(0)\n\tbc, err := remoteClient(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn bc.Close()\n}\n\nfunc destroy(args []string) error {\n\tif activeGroup != nil {\n\t\treturn fmt.Errorf(\"command does not yet support groups\")\n\t}\n\n\tfs := flag.NewFlagSet(\"destroy\", flag.ContinueOnError)\n\tfs.Usage = func() {\n\t\tfmt.Fprintln(os.Stderr, \"destroy usage: gomote destroy <instance>\")\n\t\tfs.PrintDefaults()\n\t\tif fs.NArg() == 0 {\n\t\t\t\/\/ List buildlets that you might want to destroy.\n\t\t\tclient := gomoteServerClient(context.Background())\n\t\t\tresp, err := client.ListInstances(context.Background(), &protos.ListInstancesRequest{})\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"unable to list possible instances to destroy: %s\", statusFromError(err))\n\t\t\t}\n\t\t\tif len(resp.GetInstances()) > 0 {\n\t\t\t\tfmt.Printf(\"possible instances:\\n\")\n\t\t\t\tfor _, inst := range resp.GetInstances() {\n\t\t\t\t\tfmt.Printf(\"\\t%s\\n\", inst.GetGomoteId())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tos.Exit(1)\n\t}\n\n\tfs.Parse(args)\n\tif fs.NArg() != 1 {\n\t\tfs.Usage()\n\t}\n\tname := fs.Arg(0)\n\tctx := context.Background()\n\tclient := gomoteServerClient(ctx)\n\tif _, err := client.DestroyInstance(ctx, &protos.DestroyInstanceRequest{\n\t\tGomoteId: name,\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"unable to destroy instance: %s\", statusFromError(err))\n\t}\n\treturn nil\n}\n<commit_msg>cmd\/gomote: add support for groups to destroy<commit_after>\/\/ Copyright 2015 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"golang.org\/x\/build\/buildlet\"\n\t\"golang.org\/x\/build\/internal\/gomote\/protos\"\n)\n\nfunc legacyDestroy(args []string) error {\n\tif activeGroup != nil {\n\t\treturn fmt.Errorf(\"command does not support groups\")\n\t}\n\n\tfs := flag.NewFlagSet(\"destroy\", flag.ContinueOnError)\n\tfs.Usage = func() {\n\t\tfmt.Fprintln(os.Stderr, \"destroy usage: gomote destroy <instance>\")\n\t\tfs.PrintDefaults()\n\t\tif fs.NArg() == 0 {\n\t\t\t\/\/ List buildlets that you might want to destroy.\n\t\t\tcc, err := buildlet.NewCoordinatorClientFromFlags()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\trbs, err := cc.RemoteBuildlets()\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tif len(rbs) > 0 {\n\t\t\t\tfmt.Printf(\"possible instances:\\n\")\n\t\t\t\tfor _, rb := range rbs {\n\t\t\t\t\tfmt.Printf(\"\\t%s\\n\", rb.Name)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tos.Exit(1)\n\t}\n\n\tfs.Parse(args)\n\tif fs.NArg() != 1 {\n\t\tfs.Usage()\n\t}\n\tname := fs.Arg(0)\n\tbc, err := remoteClient(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn bc.Close()\n}\n\nfunc destroy(args []string) error {\n\tfs := flag.NewFlagSet(\"destroy\", flag.ContinueOnError)\n\tfs.Usage = func() {\n\t\tfmt.Fprintln(os.Stderr, \"destroy usage: gomote destroy [instance]\")\n\t\tfmt.Fprintln(os.Stderr)\n\t\tfmt.Fprintln(os.Stderr, \"Destroys a single instance, or all instances in a group.\")\n\t\tfmt.Fprintln(os.Stderr, \"Instance argument is optional with a group.\")\n\t\tfs.PrintDefaults()\n\t\tif fs.NArg() == 0 {\n\t\t\t\/\/ List buildlets that you might want to destroy.\n\t\t\tclient := gomoteServerClient(context.Background())\n\t\t\tresp, err := client.ListInstances(context.Background(), &protos.ListInstancesRequest{})\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"unable to list possible instances to destroy: %s\", statusFromError(err))\n\t\t\t}\n\t\t\tif len(resp.GetInstances()) > 0 {\n\t\t\t\tfmt.Printf(\"possible instances:\\n\")\n\t\t\t\tfor _, inst := range resp.GetInstances() {\n\t\t\t\t\tfmt.Printf(\"\\t%s\\n\", inst.GetGomoteId())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tos.Exit(1)\n\t}\n\n\tfs.Parse(args)\n\n\tvar destroySet []string\n\tif fs.NArg() == 1 {\n\t\tdestroySet = append(destroySet, fs.Arg(0))\n\t} else if activeGroup != nil {\n\t\tfor _, inst := range activeGroup.Instances {\n\t\t\tdestroySet = append(destroySet, inst)\n\t\t}\n\t} else {\n\t\tfs.Usage()\n\t}\n\tfor _, name := range destroySet {\n\t\tfmt.Fprintf(os.Stderr, \"# Destroying %s\\n\", name)\n\t\tctx := context.Background()\n\t\tclient := gomoteServerClient(ctx)\n\t\tif _, err := client.DestroyInstance(ctx, &protos.DestroyInstanceRequest{\n\t\t\tGomoteId: name,\n\t\t}); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to destroy instance: %s\", statusFromError(err))\n\t\t}\n\t}\n\tif activeGroup != nil {\n\t\tactiveGroup.Instances = nil\n\t\tif err := storeGroup(activeGroup); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/md5\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/flynn\/json5\"\n\t\"github.com\/zyedidia\/glob\"\n)\n\ntype optionValidator func(string, interface{}) error\n\n\/\/ The options that the user can set\nvar globalSettings map[string]interface{}\n\nvar invalidSettings bool\n\n\/\/ Options with validators\nvar optionValidators = map[string]optionValidator{\n\t\"tabsize\":      validatePositiveValue,\n\t\"scrollmargin\": validateNonNegativeValue,\n\t\"scrollspeed\":  validateNonNegativeValue,\n\t\"colorscheme\":  validateColorscheme,\n\t\"colorcolumn\":  validateNonNegativeValue,\n\t\"fileformat\":   validateLineEnding,\n}\n\n\/\/ InitGlobalSettings initializes the options map and sets all options to their default values\nfunc InitGlobalSettings() {\n\tinvalidSettings = false\n\tdefaults := DefaultGlobalSettings()\n\tvar parsed map[string]interface{}\n\n\tfilename := configDir + \"\/settings.json\"\n\twriteSettings := false\n\tif _, e := os.Stat(filename); e == nil {\n\t\tinput, err := ioutil.ReadFile(filename)\n\t\tif !strings.HasPrefix(string(input), \"null\") {\n\t\t\tif err != nil {\n\t\t\t\tTermMessage(\"Error reading settings.json file: \" + err.Error())\n\t\t\t\tinvalidSettings = true\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = json5.Unmarshal(input, &parsed)\n\t\t\tif err != nil {\n\t\t\t\tTermMessage(\"Error reading settings.json:\", err.Error())\n\t\t\t\tinvalidSettings = true\n\t\t\t}\n\t\t} else {\n\t\t\twriteSettings = true\n\t\t}\n\t}\n\n\tglobalSettings = make(map[string]interface{})\n\tfor k, v := range defaults {\n\t\tglobalSettings[k] = v\n\t}\n\tfor k, v := range parsed {\n\t\tif !strings.HasPrefix(reflect.TypeOf(v).String(), \"map\") {\n\t\t\tglobalSettings[k] = v\n\t\t}\n\t}\n\n\tif _, err := os.Stat(filename); os.IsNotExist(err) || writeSettings {\n\t\terr := WriteSettings(filename)\n\t\tif err != nil {\n\t\t\tTermMessage(\"Error writing settings.json file: \" + err.Error())\n\t\t}\n\t}\n}\n\n\/\/ InitLocalSettings scans the json in settings.json and sets the options locally based\n\/\/ on whether the buffer matches the glob\nfunc InitLocalSettings(buf *Buffer) {\n\tinvalidSettings = false\n\tvar parsed map[string]interface{}\n\n\tfilename := configDir + \"\/settings.json\"\n\tif _, e := os.Stat(filename); e == nil {\n\t\tinput, err := ioutil.ReadFile(filename)\n\t\tif err != nil {\n\t\t\tTermMessage(\"Error reading settings.json file: \" + err.Error())\n\t\t\tinvalidSettings = true\n\t\t\treturn\n\t\t}\n\n\t\terr = json5.Unmarshal(input, &parsed)\n\t\tif err != nil {\n\t\t\tTermMessage(\"Error reading settings.json:\", err.Error())\n\t\t\tinvalidSettings = true\n\t\t}\n\t}\n\n\tfor k, v := range parsed {\n\t\tif strings.HasPrefix(reflect.TypeOf(v).String(), \"map\") {\n\t\t\tif strings.HasPrefix(k, \"ft:\") {\n\t\t\t\tif buf.Settings[\"filetype\"].(string) == k[3:] {\n\t\t\t\t\tfor k1, v1 := range v.(map[string]interface{}) {\n\t\t\t\t\t\tbuf.Settings[k1] = v1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tg, err := glob.Compile(k)\n\t\t\t\tif err != nil {\n\t\t\t\t\tTermMessage(\"Error with glob setting \", k, \": \", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif g.MatchString(buf.Path) {\n\t\t\t\t\tfor k1, v1 := range v.(map[string]interface{}) {\n\t\t\t\t\t\tbuf.Settings[k1] = v1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ WriteSettings writes the settings to the specified filename as JSON\nfunc WriteSettings(filename string) error {\n\tif invalidSettings {\n\t\t\/\/ Do not write the settings if there was an error when reading them\n\t\treturn nil\n\t}\n\n\tvar err error\n\tif _, e := os.Stat(configDir); e == nil {\n\t\tparsed := make(map[string]interface{})\n\n\t\tfilename := configDir + \"\/settings.json\"\n\t\tfor k, v := range globalSettings {\n\t\t\tparsed[k] = v\n\t\t}\n\t\tif _, e := os.Stat(filename); e == nil {\n\t\t\tinput, err := ioutil.ReadFile(filename)\n\t\t\tif string(input) != \"null\" {\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\terr = json5.Unmarshal(input, &parsed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tTermMessage(\"Error reading settings.json:\", err.Error())\n\t\t\t\t\tinvalidSettings = true\n\t\t\t\t}\n\n\t\t\t\tfor k, v := range parsed {\n\t\t\t\t\tif !strings.HasPrefix(reflect.TypeOf(v).String(), \"map\") {\n\t\t\t\t\t\tif _, ok := globalSettings[k]; ok {\n\t\t\t\t\t\t\tparsed[k] = globalSettings[k]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttxt, _ := json.MarshalIndent(parsed, \"\", \"    \")\n\t\terr = ioutil.WriteFile(filename, append(txt, '\\n'), 0644)\n\t}\n\treturn err\n}\n\n\/\/ AddOption creates a new option. This is meant to be called by plugins to add options.\nfunc AddOption(name string, value interface{}) {\n\tglobalSettings[name] = value\n\terr := WriteSettings(configDir + \"\/settings.json\")\n\tif err != nil {\n\t\tTermMessage(\"Error writing settings.json file: \" + err.Error())\n\t}\n}\n\n\/\/ GetGlobalOption returns the global value of the given option\nfunc GetGlobalOption(name string) interface{} {\n\treturn globalSettings[name]\n}\n\n\/\/ GetLocalOption returns the local value of the given option\nfunc GetLocalOption(name string, buf *Buffer) interface{} {\n\treturn buf.Settings[name]\n}\n\n\/\/ GetOption returns the value of the given option\n\/\/ If there is a local version of the option, it returns that\n\/\/ otherwise it will return the global version\nfunc GetOption(name string) interface{} {\n\tif GetLocalOption(name, CurView().Buf) != nil {\n\t\treturn GetLocalOption(name, CurView().Buf)\n\t}\n\treturn GetGlobalOption(name)\n}\n\n\/\/ DefaultGlobalSettings returns the default global settings for micro\n\/\/ Note that colorscheme is a global only option\nfunc DefaultGlobalSettings() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"autoindent\":     true,\n\t\t\"autosave\":       false,\n\t\t\"basename\":       false,\n\t\t\"colorcolumn\":    float64(0),\n\t\t\"colorscheme\":    \"default\",\n\t\t\"cursorline\":     true,\n\t\t\"eofnewline\":     false,\n\t\t\"fastdirty\":      true,\n\t\t\"fileformat\":     \"unix\",\n\t\t\"ignorecase\":     false,\n\t\t\"indentchar\":     \" \",\n\t\t\"infobar\":        true,\n\t\t\"keepautoindent\": false,\n\t\t\"keymenu\":        false,\n\t\t\"matchbrace\":     false,\n\t\t\"mouse\":          true,\n\t\t\"pluginchannels\": []string{\"https:\/\/raw.githubusercontent.com\/micro-editor\/plugin-channel\/master\/channel.json\"},\n\t\t\"pluginrepos\":    []string{},\n\t\t\"rmtrailingws\":   false,\n\t\t\"ruler\":          true,\n\t\t\"savecursor\":     false,\n\t\t\"savehistory\":    true,\n\t\t\"saveundo\":       false,\n\t\t\"scrollbar\":      false,\n\t\t\"scrollmargin\":   float64(3),\n\t\t\"scrollspeed\":    float64(2),\n\t\t\"softwrap\":       false,\n\t\t\"splitbottom\":    true,\n\t\t\"splitright\":     true,\n\t\t\"statusline\":     true,\n\t\t\"sucmd\":          \"sudo\",\n\t\t\"syntax\":         true,\n\t\t\"tabmovement\":    false,\n\t\t\"tabsize\":        float64(4),\n\t\t\"tabstospaces\":   false,\n\t\t\"termtitle\":      false,\n\t\t\"useprimary\":     true,\n\t}\n}\n\n\/\/ DefaultLocalSettings returns the default local settings\n\/\/ Note that filetype is a local only option\nfunc DefaultLocalSettings() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"autoindent\":     true,\n\t\t\"autosave\":       false,\n\t\t\"basename\":       false,\n\t\t\"colorcolumn\":    float64(0),\n\t\t\"cursorline\":     true,\n\t\t\"eofnewline\":     false,\n\t\t\"fastdirty\":      true,\n\t\t\"fileformat\":     \"unix\",\n\t\t\"filetype\":       \"Unknown\",\n\t\t\"ignorecase\":     false,\n\t\t\"indentchar\":     \" \",\n\t\t\"keepautoindent\": false,\n\t\t\"matchbrace\":     false,\n\t\t\"rmtrailingws\":   false,\n\t\t\"ruler\":          true,\n\t\t\"savecursor\":     false,\n\t\t\"saveundo\":       false,\n\t\t\"scrollbar\":      false,\n\t\t\"scrollmargin\":   float64(3),\n\t\t\"scrollspeed\":    float64(2),\n\t\t\"softwrap\":       false,\n\t\t\"splitbottom\":    true,\n\t\t\"splitright\":     true,\n\t\t\"statusline\":     true,\n\t\t\"syntax\":         true,\n\t\t\"tabmovement\":    false,\n\t\t\"tabsize\":        float64(4),\n\t\t\"tabstospaces\":   false,\n\t\t\"useprimary\":     true,\n\t}\n}\n\n\/\/ SetOption attempts to set the given option to the value\n\/\/ By default it will set the option as global, but if the option\n\/\/ is local only it will set the local version\n\/\/ Use setlocal to force an option to be set locally\nfunc SetOption(option, value string) error {\n\tif _, ok := globalSettings[option]; !ok {\n\t\tif _, ok := CurView().Buf.Settings[option]; !ok {\n\t\t\treturn errors.New(\"Invalid option\")\n\t\t}\n\t\tSetLocalOption(option, value, CurView())\n\t\treturn nil\n\t}\n\n\tvar nativeValue interface{}\n\n\tkind := reflect.TypeOf(globalSettings[option]).Kind()\n\tif kind == reflect.Bool {\n\t\tb, err := ParseBool(value)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Invalid value\")\n\t\t}\n\t\tnativeValue = b\n\t} else if kind == reflect.String {\n\t\tnativeValue = value\n\t} else if kind == reflect.Float64 {\n\t\ti, err := strconv.Atoi(value)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Invalid value\")\n\t\t}\n\t\tnativeValue = float64(i)\n\t} else {\n\t\treturn errors.New(\"Option has unsupported value type\")\n\t}\n\n\tif err := optionIsValid(option, nativeValue); err != nil {\n\t\treturn err\n\t}\n\n\tglobalSettings[option] = nativeValue\n\n\tif option == \"colorscheme\" {\n\t\t\/\/ LoadSyntaxFiles()\n\t\tInitColorscheme()\n\t\tfor _, tab := range tabs {\n\t\t\tfor _, view := range tab.views {\n\t\t\t\tview.Buf.UpdateRules()\n\t\t\t}\n\t\t}\n\t}\n\n\tif option == \"infobar\" || option == \"keymenu\" {\n\t\tfor _, tab := range tabs {\n\t\t\ttab.Resize()\n\t\t}\n\t}\n\n\tif option == \"mouse\" {\n\t\tif !nativeValue.(bool) {\n\t\t\tscreen.DisableMouse()\n\t\t} else {\n\t\t\tscreen.EnableMouse()\n\t\t}\n\t}\n\n\tif len(tabs) != 0 {\n\t\tif _, ok := CurView().Buf.Settings[option]; ok {\n\t\t\tfor _, tab := range tabs {\n\t\t\t\tfor _, view := range tab.views {\n\t\t\t\t\tSetLocalOption(option, value, view)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ SetLocalOption sets the local version of this option\nfunc SetLocalOption(option, value string, view *View) error {\n\tbuf := view.Buf\n\tif _, ok := buf.Settings[option]; !ok {\n\t\treturn errors.New(\"Invalid option\")\n\t}\n\n\tvar nativeValue interface{}\n\n\tkind := reflect.TypeOf(buf.Settings[option]).Kind()\n\tif kind == reflect.Bool {\n\t\tb, err := ParseBool(value)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Invalid value\")\n\t\t}\n\t\tnativeValue = b\n\t} else if kind == reflect.String {\n\t\tnativeValue = value\n\t} else if kind == reflect.Float64 {\n\t\ti, err := strconv.Atoi(value)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Invalid value\")\n\t\t}\n\t\tnativeValue = float64(i)\n\t} else {\n\t\treturn errors.New(\"Option has unsupported value type\")\n\t}\n\n\tif err := optionIsValid(option, nativeValue); err != nil {\n\t\treturn err\n\t}\n\n\tif option == \"fastdirty\" {\n\t\t\/\/ If it is being turned off, we have to hash every open buffer\n\t\tvar empty [16]byte\n\t\tfor _, tab := range tabs {\n\t\t\tfor _, v := range tab.views {\n\t\t\t\tif !nativeValue.(bool) {\n\t\t\t\t\tif v.Buf.origHash == empty {\n\t\t\t\t\t\tdata, err := ioutil.ReadFile(v.Buf.AbsPath)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tdata = []byte{}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tv.Buf.origHash = md5.Sum(data)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tv.Buf.IsModified = v.Buf.Modified()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tbuf.Settings[option] = nativeValue\n\n\tif option == \"statusline\" {\n\t\tview.ToggleStatusLine()\n\t}\n\n\tif option == \"filetype\" {\n\t\t\/\/ LoadSyntaxFiles()\n\t\tInitColorscheme()\n\t\tbuf.UpdateRules()\n\t}\n\n\tif option == \"fileformat\" {\n\t\tbuf.IsModified = true\n\t}\n\n\tif option == \"syntax\" {\n\t\tif !nativeValue.(bool) {\n\t\t\tbuf.ClearMatches()\n\t\t} else {\n\t\t\tbuf.highlighter.HighlightStates(buf)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ SetOptionAndSettings sets the given option and saves the option setting to the settings config file\nfunc SetOptionAndSettings(option, value string) {\n\tfilename := configDir + \"\/settings.json\"\n\n\terr := SetOption(option, value)\n\n\tif err != nil {\n\t\tmessenger.Error(err.Error())\n\t\treturn\n\t}\n\n\terr = WriteSettings(filename)\n\tif err != nil {\n\t\tmessenger.Error(\"Error writing to settings.json: \" + err.Error())\n\t\treturn\n\t}\n}\n\nfunc optionIsValid(option string, value interface{}) error {\n\tif validator, ok := optionValidators[option]; ok {\n\t\treturn validator(option, value)\n\t}\n\n\treturn nil\n}\n\n\/\/ Option validators\n\nfunc validatePositiveValue(option string, value interface{}) error {\n\ttabsize, ok := value.(float64)\n\n\tif !ok {\n\t\treturn errors.New(\"Expected numeric type for \" + option)\n\t}\n\n\tif tabsize < 1 {\n\t\treturn errors.New(option + \" must be greater than 0\")\n\t}\n\n\treturn nil\n}\n\nfunc validateNonNegativeValue(option string, value interface{}) error {\n\tnativeValue, ok := value.(float64)\n\n\tif !ok {\n\t\treturn errors.New(\"Expected numeric type for \" + option)\n\t}\n\n\tif nativeValue < 0 {\n\t\treturn errors.New(option + \" must be non-negative\")\n\t}\n\n\treturn nil\n}\n\nfunc validateColorscheme(option string, value interface{}) error {\n\tcolorscheme, ok := value.(string)\n\n\tif !ok {\n\t\treturn errors.New(\"Expected string type for colorscheme\")\n\t}\n\n\tif !ColorschemeExists(colorscheme) {\n\t\treturn errors.New(colorscheme + \" is not a valid colorscheme\")\n\t}\n\n\treturn nil\n}\n\nfunc validateLineEnding(option string, value interface{}) error {\n\tendingType, ok := value.(string)\n\n\tif !ok {\n\t\treturn errors.New(\"Expected string type for file format\")\n\t}\n\n\tif endingType != \"unix\" && endingType != \"dos\" {\n\t\treturn errors.New(\"File format must be either 'unix' or 'dos'\")\n\t}\n\n\treturn nil\n}\n<commit_msg>Fix syntax highlighting on empty buffer<commit_after>package main\n\nimport (\n\t\"crypto\/md5\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/flynn\/json5\"\n\t\"github.com\/zyedidia\/glob\"\n)\n\ntype optionValidator func(string, interface{}) error\n\n\/\/ The options that the user can set\nvar globalSettings map[string]interface{}\n\nvar invalidSettings bool\n\n\/\/ Options with validators\nvar optionValidators = map[string]optionValidator{\n\t\"tabsize\":      validatePositiveValue,\n\t\"scrollmargin\": validateNonNegativeValue,\n\t\"scrollspeed\":  validateNonNegativeValue,\n\t\"colorscheme\":  validateColorscheme,\n\t\"colorcolumn\":  validateNonNegativeValue,\n\t\"fileformat\":   validateLineEnding,\n}\n\n\/\/ InitGlobalSettings initializes the options map and sets all options to their default values\nfunc InitGlobalSettings() {\n\tinvalidSettings = false\n\tdefaults := DefaultGlobalSettings()\n\tvar parsed map[string]interface{}\n\n\tfilename := configDir + \"\/settings.json\"\n\twriteSettings := false\n\tif _, e := os.Stat(filename); e == nil {\n\t\tinput, err := ioutil.ReadFile(filename)\n\t\tif !strings.HasPrefix(string(input), \"null\") {\n\t\t\tif err != nil {\n\t\t\t\tTermMessage(\"Error reading settings.json file: \" + err.Error())\n\t\t\t\tinvalidSettings = true\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = json5.Unmarshal(input, &parsed)\n\t\t\tif err != nil {\n\t\t\t\tTermMessage(\"Error reading settings.json:\", err.Error())\n\t\t\t\tinvalidSettings = true\n\t\t\t}\n\t\t} else {\n\t\t\twriteSettings = true\n\t\t}\n\t}\n\n\tglobalSettings = make(map[string]interface{})\n\tfor k, v := range defaults {\n\t\tglobalSettings[k] = v\n\t}\n\tfor k, v := range parsed {\n\t\tif !strings.HasPrefix(reflect.TypeOf(v).String(), \"map\") {\n\t\t\tglobalSettings[k] = v\n\t\t}\n\t}\n\n\tif _, err := os.Stat(filename); os.IsNotExist(err) || writeSettings {\n\t\terr := WriteSettings(filename)\n\t\tif err != nil {\n\t\t\tTermMessage(\"Error writing settings.json file: \" + err.Error())\n\t\t}\n\t}\n}\n\n\/\/ InitLocalSettings scans the json in settings.json and sets the options locally based\n\/\/ on whether the buffer matches the glob\nfunc InitLocalSettings(buf *Buffer) {\n\tinvalidSettings = false\n\tvar parsed map[string]interface{}\n\n\tfilename := configDir + \"\/settings.json\"\n\tif _, e := os.Stat(filename); e == nil {\n\t\tinput, err := ioutil.ReadFile(filename)\n\t\tif err != nil {\n\t\t\tTermMessage(\"Error reading settings.json file: \" + err.Error())\n\t\t\tinvalidSettings = true\n\t\t\treturn\n\t\t}\n\n\t\terr = json5.Unmarshal(input, &parsed)\n\t\tif err != nil {\n\t\t\tTermMessage(\"Error reading settings.json:\", err.Error())\n\t\t\tinvalidSettings = true\n\t\t}\n\t}\n\n\tfor k, v := range parsed {\n\t\tif strings.HasPrefix(reflect.TypeOf(v).String(), \"map\") {\n\t\t\tif strings.HasPrefix(k, \"ft:\") {\n\t\t\t\tif buf.Settings[\"filetype\"].(string) == k[3:] {\n\t\t\t\t\tfor k1, v1 := range v.(map[string]interface{}) {\n\t\t\t\t\t\tbuf.Settings[k1] = v1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tg, err := glob.Compile(k)\n\t\t\t\tif err != nil {\n\t\t\t\t\tTermMessage(\"Error with glob setting \", k, \": \", err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif g.MatchString(buf.Path) {\n\t\t\t\t\tfor k1, v1 := range v.(map[string]interface{}) {\n\t\t\t\t\t\tbuf.Settings[k1] = v1\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ WriteSettings writes the settings to the specified filename as JSON\nfunc WriteSettings(filename string) error {\n\tif invalidSettings {\n\t\t\/\/ Do not write the settings if there was an error when reading them\n\t\treturn nil\n\t}\n\n\tvar err error\n\tif _, e := os.Stat(configDir); e == nil {\n\t\tparsed := make(map[string]interface{})\n\n\t\tfilename := configDir + \"\/settings.json\"\n\t\tfor k, v := range globalSettings {\n\t\t\tparsed[k] = v\n\t\t}\n\t\tif _, e := os.Stat(filename); e == nil {\n\t\t\tinput, err := ioutil.ReadFile(filename)\n\t\t\tif string(input) != \"null\" {\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\terr = json5.Unmarshal(input, &parsed)\n\t\t\t\tif err != nil {\n\t\t\t\t\tTermMessage(\"Error reading settings.json:\", err.Error())\n\t\t\t\t\tinvalidSettings = true\n\t\t\t\t}\n\n\t\t\t\tfor k, v := range parsed {\n\t\t\t\t\tif !strings.HasPrefix(reflect.TypeOf(v).String(), \"map\") {\n\t\t\t\t\t\tif _, ok := globalSettings[k]; ok {\n\t\t\t\t\t\t\tparsed[k] = globalSettings[k]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\ttxt, _ := json.MarshalIndent(parsed, \"\", \"    \")\n\t\terr = ioutil.WriteFile(filename, append(txt, '\\n'), 0644)\n\t}\n\treturn err\n}\n\n\/\/ AddOption creates a new option. This is meant to be called by plugins to add options.\nfunc AddOption(name string, value interface{}) {\n\tglobalSettings[name] = value\n\terr := WriteSettings(configDir + \"\/settings.json\")\n\tif err != nil {\n\t\tTermMessage(\"Error writing settings.json file: \" + err.Error())\n\t}\n}\n\n\/\/ GetGlobalOption returns the global value of the given option\nfunc GetGlobalOption(name string) interface{} {\n\treturn globalSettings[name]\n}\n\n\/\/ GetLocalOption returns the local value of the given option\nfunc GetLocalOption(name string, buf *Buffer) interface{} {\n\treturn buf.Settings[name]\n}\n\n\/\/ GetOption returns the value of the given option\n\/\/ If there is a local version of the option, it returns that\n\/\/ otherwise it will return the global version\nfunc GetOption(name string) interface{} {\n\tif GetLocalOption(name, CurView().Buf) != nil {\n\t\treturn GetLocalOption(name, CurView().Buf)\n\t}\n\treturn GetGlobalOption(name)\n}\n\n\/\/ DefaultGlobalSettings returns the default global settings for micro\n\/\/ Note that colorscheme is a global only option\nfunc DefaultGlobalSettings() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"autoindent\":     true,\n\t\t\"autosave\":       false,\n\t\t\"basename\":       false,\n\t\t\"colorcolumn\":    float64(0),\n\t\t\"colorscheme\":    \"default\",\n\t\t\"cursorline\":     true,\n\t\t\"eofnewline\":     false,\n\t\t\"fastdirty\":      true,\n\t\t\"fileformat\":     \"unix\",\n\t\t\"ignorecase\":     false,\n\t\t\"indentchar\":     \" \",\n\t\t\"infobar\":        true,\n\t\t\"keepautoindent\": false,\n\t\t\"keymenu\":        false,\n\t\t\"matchbrace\":     false,\n\t\t\"mouse\":          true,\n\t\t\"pluginchannels\": []string{\"https:\/\/raw.githubusercontent.com\/micro-editor\/plugin-channel\/master\/channel.json\"},\n\t\t\"pluginrepos\":    []string{},\n\t\t\"rmtrailingws\":   false,\n\t\t\"ruler\":          true,\n\t\t\"savecursor\":     false,\n\t\t\"savehistory\":    true,\n\t\t\"saveundo\":       false,\n\t\t\"scrollbar\":      false,\n\t\t\"scrollmargin\":   float64(3),\n\t\t\"scrollspeed\":    float64(2),\n\t\t\"softwrap\":       false,\n\t\t\"splitbottom\":    true,\n\t\t\"splitright\":     true,\n\t\t\"statusline\":     true,\n\t\t\"sucmd\":          \"sudo\",\n\t\t\"syntax\":         true,\n\t\t\"tabmovement\":    false,\n\t\t\"tabsize\":        float64(4),\n\t\t\"tabstospaces\":   false,\n\t\t\"termtitle\":      false,\n\t\t\"useprimary\":     true,\n\t}\n}\n\n\/\/ DefaultLocalSettings returns the default local settings\n\/\/ Note that filetype is a local only option\nfunc DefaultLocalSettings() map[string]interface{} {\n\treturn map[string]interface{}{\n\t\t\"autoindent\":     true,\n\t\t\"autosave\":       false,\n\t\t\"basename\":       false,\n\t\t\"colorcolumn\":    float64(0),\n\t\t\"cursorline\":     true,\n\t\t\"eofnewline\":     false,\n\t\t\"fastdirty\":      true,\n\t\t\"fileformat\":     \"unix\",\n\t\t\"filetype\":       \"Unknown\",\n\t\t\"ignorecase\":     false,\n\t\t\"indentchar\":     \" \",\n\t\t\"keepautoindent\": false,\n\t\t\"matchbrace\":     false,\n\t\t\"rmtrailingws\":   false,\n\t\t\"ruler\":          true,\n\t\t\"savecursor\":     false,\n\t\t\"saveundo\":       false,\n\t\t\"scrollbar\":      false,\n\t\t\"scrollmargin\":   float64(3),\n\t\t\"scrollspeed\":    float64(2),\n\t\t\"softwrap\":       false,\n\t\t\"splitbottom\":    true,\n\t\t\"splitright\":     true,\n\t\t\"statusline\":     true,\n\t\t\"syntax\":         true,\n\t\t\"tabmovement\":    false,\n\t\t\"tabsize\":        float64(4),\n\t\t\"tabstospaces\":   false,\n\t\t\"useprimary\":     true,\n\t}\n}\n\n\/\/ SetOption attempts to set the given option to the value\n\/\/ By default it will set the option as global, but if the option\n\/\/ is local only it will set the local version\n\/\/ Use setlocal to force an option to be set locally\nfunc SetOption(option, value string) error {\n\tif _, ok := globalSettings[option]; !ok {\n\t\tif _, ok := CurView().Buf.Settings[option]; !ok {\n\t\t\treturn errors.New(\"Invalid option\")\n\t\t}\n\t\tSetLocalOption(option, value, CurView())\n\t\treturn nil\n\t}\n\n\tvar nativeValue interface{}\n\n\tkind := reflect.TypeOf(globalSettings[option]).Kind()\n\tif kind == reflect.Bool {\n\t\tb, err := ParseBool(value)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Invalid value\")\n\t\t}\n\t\tnativeValue = b\n\t} else if kind == reflect.String {\n\t\tnativeValue = value\n\t} else if kind == reflect.Float64 {\n\t\ti, err := strconv.Atoi(value)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Invalid value\")\n\t\t}\n\t\tnativeValue = float64(i)\n\t} else {\n\t\treturn errors.New(\"Option has unsupported value type\")\n\t}\n\n\tif err := optionIsValid(option, nativeValue); err != nil {\n\t\treturn err\n\t}\n\n\tglobalSettings[option] = nativeValue\n\n\tif option == \"colorscheme\" {\n\t\t\/\/ LoadSyntaxFiles()\n\t\tInitColorscheme()\n\t\tfor _, tab := range tabs {\n\t\t\tfor _, view := range tab.views {\n\t\t\t\tview.Buf.UpdateRules()\n\t\t\t}\n\t\t}\n\t}\n\n\tif option == \"infobar\" || option == \"keymenu\" {\n\t\tfor _, tab := range tabs {\n\t\t\ttab.Resize()\n\t\t}\n\t}\n\n\tif option == \"mouse\" {\n\t\tif !nativeValue.(bool) {\n\t\t\tscreen.DisableMouse()\n\t\t} else {\n\t\t\tscreen.EnableMouse()\n\t\t}\n\t}\n\n\tif len(tabs) != 0 {\n\t\tif _, ok := CurView().Buf.Settings[option]; ok {\n\t\t\tfor _, tab := range tabs {\n\t\t\t\tfor _, view := range tab.views {\n\t\t\t\t\tSetLocalOption(option, value, view)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ SetLocalOption sets the local version of this option\nfunc SetLocalOption(option, value string, view *View) error {\n\tbuf := view.Buf\n\tif _, ok := buf.Settings[option]; !ok {\n\t\treturn errors.New(\"Invalid option\")\n\t}\n\n\tvar nativeValue interface{}\n\n\tkind := reflect.TypeOf(buf.Settings[option]).Kind()\n\tif kind == reflect.Bool {\n\t\tb, err := ParseBool(value)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Invalid value\")\n\t\t}\n\t\tnativeValue = b\n\t} else if kind == reflect.String {\n\t\tnativeValue = value\n\t} else if kind == reflect.Float64 {\n\t\ti, err := strconv.Atoi(value)\n\t\tif err != nil {\n\t\t\treturn errors.New(\"Invalid value\")\n\t\t}\n\t\tnativeValue = float64(i)\n\t} else {\n\t\treturn errors.New(\"Option has unsupported value type\")\n\t}\n\n\tif err := optionIsValid(option, nativeValue); err != nil {\n\t\treturn err\n\t}\n\n\tif option == \"fastdirty\" {\n\t\t\/\/ If it is being turned off, we have to hash every open buffer\n\t\tvar empty [16]byte\n\t\tfor _, tab := range tabs {\n\t\t\tfor _, v := range tab.views {\n\t\t\t\tif !nativeValue.(bool) {\n\t\t\t\t\tif v.Buf.origHash == empty {\n\t\t\t\t\t\tdata, err := ioutil.ReadFile(v.Buf.AbsPath)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tdata = []byte{}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tv.Buf.origHash = md5.Sum(data)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tv.Buf.IsModified = v.Buf.Modified()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tbuf.Settings[option] = nativeValue\n\n\tif option == \"statusline\" {\n\t\tview.ToggleStatusLine()\n\t}\n\n\tif option == \"filetype\" {\n\t\t\/\/ LoadSyntaxFiles()\n\t\tInitColorscheme()\n\t\tbuf.UpdateRules()\n\t}\n\n\tif option == \"fileformat\" {\n\t\tbuf.IsModified = true\n\t}\n\n\tif option == \"syntax\" {\n\t\tif !nativeValue.(bool) {\n\t\t\tbuf.ClearMatches()\n\t\t} else {\n\t\t\tif buf.highlighter != nil {\n\t\t\t\tbuf.highlighter.HighlightStates(buf)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ SetOptionAndSettings sets the given option and saves the option setting to the settings config file\nfunc SetOptionAndSettings(option, value string) {\n\tfilename := configDir + \"\/settings.json\"\n\n\terr := SetOption(option, value)\n\n\tif err != nil {\n\t\tmessenger.Error(err.Error())\n\t\treturn\n\t}\n\n\terr = WriteSettings(filename)\n\tif err != nil {\n\t\tmessenger.Error(\"Error writing to settings.json: \" + err.Error())\n\t\treturn\n\t}\n}\n\nfunc optionIsValid(option string, value interface{}) error {\n\tif validator, ok := optionValidators[option]; ok {\n\t\treturn validator(option, value)\n\t}\n\n\treturn nil\n}\n\n\/\/ Option validators\n\nfunc validatePositiveValue(option string, value interface{}) error {\n\ttabsize, ok := value.(float64)\n\n\tif !ok {\n\t\treturn errors.New(\"Expected numeric type for \" + option)\n\t}\n\n\tif tabsize < 1 {\n\t\treturn errors.New(option + \" must be greater than 0\")\n\t}\n\n\treturn nil\n}\n\nfunc validateNonNegativeValue(option string, value interface{}) error {\n\tnativeValue, ok := value.(float64)\n\n\tif !ok {\n\t\treturn errors.New(\"Expected numeric type for \" + option)\n\t}\n\n\tif nativeValue < 0 {\n\t\treturn errors.New(option + \" must be non-negative\")\n\t}\n\n\treturn nil\n}\n\nfunc validateColorscheme(option string, value interface{}) error {\n\tcolorscheme, ok := value.(string)\n\n\tif !ok {\n\t\treturn errors.New(\"Expected string type for colorscheme\")\n\t}\n\n\tif !ColorschemeExists(colorscheme) {\n\t\treturn errors.New(colorscheme + \" is not a valid colorscheme\")\n\t}\n\n\treturn nil\n}\n\nfunc validateLineEnding(option string, value interface{}) error {\n\tendingType, ok := value.(string)\n\n\tif !ok {\n\t\treturn errors.New(\"Expected string type for file format\")\n\t}\n\n\tif endingType != \"unix\" && endingType != \"dos\" {\n\t\treturn errors.New(\"File format must be either 'unix' or 'dos'\")\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Lars Wiegman. All rights reserved. Use of this source code is\n\/\/ governed by a BSD-style license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\tlumberjack \"gopkg.in\/natefinch\/lumberjack.v2\"\n\n\t\"github.com\/xenolf\/lego\/acme\"\n\n\t\"github.com\/mholt\/caddy\"\n\t\/\/ plug in the HTTP server type\n\t_ \"github.com\/mholt\/caddy\/caddyhttp\"\n\t\"github.com\/mholt\/caddy\/caddytls\"\n\n\t\/\/ This is where other plugins get plugged in (imported)\n\t_ \"github.com\/mholt\/caddy\/caddyhttp\/proxy\"\n\t_ \"github.com\/namsral\/multipass\"\n)\n\nfunc init() {\n\tcaddy.TrapSignals()\n\tsetVersion()\n\n\tflag.BoolVar(&caddytls.Agreed, \"agree\", false, \"Agree to the CA's Subscriber Agreement\")\n\tflag.StringVar(&caddytls.DefaultCAUrl, \"ca\", \"https:\/\/acme-v01.api.letsencrypt.org\/directory\", \"URL to certificate authority's ACME server directory\")\n\tflag.StringVar(&conf, \"conf\", \"\", \"Caddyfile to load (default \\\"\"+caddy.DefaultConfigFile+\"\\\")\")\n\tflag.StringVar(&cpu, \"cpu\", \"100%\", \"CPU cap\")\n\tflag.BoolVar(&plugins, \"plugins\", false, \"List installed plugins\")\n\tflag.StringVar(&caddytls.DefaultEmail, \"email\", \"\", \"Default ACME CA account email address\")\n\tflag.StringVar(&logfile, \"log\", \"stdout\", \"Process log file\")\n\tflag.StringVar(&caddy.PidFile, \"pidfile\", \"\", \"Path to write pid file\")\n\tflag.BoolVar(&caddy.Quiet, \"quiet\", false, \"Quiet mode (no initialization output)\")\n\tflag.StringVar(&revoke, \"revoke\", \"\", \"Hostname for which to revoke the certificate\")\n\tflag.StringVar(&serverType, \"type\", \"http\", \"Type of server to run\")\n\tflag.BoolVar(&version, \"version\", false, \"Show version\")\n\n\tcaddy.RegisterCaddyfileLoader(\"flag\", caddy.LoaderFunc(confLoader))\n\tcaddy.SetDefaultCaddyfileLoader(\"default\", caddy.LoaderFunc(defaultLoader))\n}\n\n\/\/ Run is Caddy's main() function.\nfunc main() {\n\tflag.Parse()\n\n\tcaddy.AppName = appName\n\tcaddy.AppVersion = appVersion\n\tacme.UserAgent = appName + \"\/\" + appVersion\n\n\t\/\/ Set up process log before anything bad happens\n\tswitch logfile {\n\tcase \"stdout\":\n\t\tlog.SetOutput(os.Stdout)\n\tcase \"stderr\":\n\t\tlog.SetOutput(os.Stderr)\n\tcase \"\":\n\t\tlog.SetOutput(ioutil.Discard)\n\tdefault:\n\t\tlog.SetOutput(&lumberjack.Logger{\n\t\t\tFilename:   logfile,\n\t\t\tMaxSize:    100,\n\t\t\tMaxAge:     14,\n\t\t\tMaxBackups: 10,\n\t\t})\n\t}\n\n\t\/\/ Check for one-time actions\n\tif revoke != \"\" {\n\t\terr := caddytls.Revoke(revoke)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Revoked certificate for %s\\n\", revoke)\n\t\tos.Exit(0)\n\t}\n\tif version {\n\t\tfmt.Printf(\"%s %s\\n\", appName, appVersion)\n\t\tif devBuild && gitShortStat != \"\" {\n\t\t\tfmt.Printf(\"%s\\n%s\\n\", gitShortStat, gitFilesModified)\n\t\t}\n\t\tos.Exit(0)\n\t}\n\tif plugins {\n\t\tfmt.Println(caddy.DescribePlugins())\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Set CPU cap\n\terr := setCPU(cpu)\n\tif err != nil {\n\t\tmustLogFatal(err)\n\t}\n\n\t\/\/ Get Caddyfile input\n\tcaddyfile, err := caddy.LoadCaddyfile(serverType)\n\tif err != nil {\n\t\tmustLogFatal(err)\n\t}\n\n\t\/\/ Start your engines\n\tinstance, err := caddy.Start(caddyfile)\n\tif err != nil {\n\t\tmustLogFatal(err)\n\t}\n\n\t\/\/ Twiddle your thumbs\n\tinstance.Wait()\n}\n\n\/\/ mustLogFatal wraps log.Fatal() in a way that ensures the\n\/\/ output is always printed to stderr so the user can see it\n\/\/ if the user is still there, even if the process log was not\n\/\/ enabled. If this process is an upgrade, however, and the user\n\/\/ might not be there anymore, this just logs to the process\n\/\/ log and exits.\nfunc mustLogFatal(args ...interface{}) {\n\tif !caddy.IsUpgrade() {\n\t\tlog.SetOutput(os.Stderr)\n\t}\n\tlog.Fatal(args...)\n}\n\n\/\/ confLoader loads the Caddyfile using the -conf flag.\nfunc confLoader(serverType string) (caddy.Input, error) {\n\tif conf == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tif conf == \"stdin\" {\n\t\treturn caddy.CaddyfileFromPipe(os.Stdin)\n\t}\n\n\tcontents, err := ioutil.ReadFile(conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn caddy.CaddyfileInput{\n\t\tContents:       contents,\n\t\tFilepath:       conf,\n\t\tServerTypeName: serverType,\n\t}, nil\n}\n\n\/\/ defaultLoader loads the Caddyfile from the current working directory.\nfunc defaultLoader(serverType string) (caddy.Input, error) {\n\tcontents, err := ioutil.ReadFile(caddy.DefaultConfigFile)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn caddy.CaddyfileInput{\n\t\tContents:       contents,\n\t\tFilepath:       caddy.DefaultConfigFile,\n\t\tServerTypeName: serverType,\n\t}, nil\n}\n\n\/\/ setVersion figures out the version information\n\/\/ based on variables set by -ldflags.\nfunc setVersion() {\n\t\/\/ A development build is one that's not at a tag or has uncommitted changes\n\tdevBuild = gitTag == \"\" || gitShortStat != \"\"\n\n\t\/\/ Only set the appVersion if -ldflags was used\n\tif gitNearestTag != \"\" || gitTag != \"\" {\n\t\tif devBuild && gitNearestTag != \"\" {\n\t\t\tappVersion = fmt.Sprintf(\"%s (+%s %s)\",\n\t\t\t\tstrings.TrimPrefix(gitNearestTag, \"v\"), gitCommit, buildDate)\n\t\t} else if gitTag != \"\" {\n\t\t\tappVersion = strings.TrimPrefix(gitTag, \"v\")\n\t\t}\n\t}\n}\n\n\/\/ setCPU parses string cpu and sets GOMAXPROCS\n\/\/ according to its value. It accepts either\n\/\/ a number (e.g. 3) or a percent (e.g. 50%).\nfunc setCPU(cpu string) error {\n\tvar numCPU int\n\n\tavailCPU := runtime.NumCPU()\n\n\tif strings.HasSuffix(cpu, \"%\") {\n\t\t\/\/ Percent\n\t\tvar percent float32\n\t\tpctStr := cpu[:len(cpu)-1]\n\t\tpctInt, err := strconv.Atoi(pctStr)\n\t\tif err != nil || pctInt < 1 || pctInt > 100 {\n\t\t\treturn errors.New(\"invalid CPU value: percentage must be between 1-100\")\n\t\t}\n\t\tpercent = float32(pctInt) \/ 100\n\t\tnumCPU = int(float32(availCPU) * percent)\n\t} else {\n\t\t\/\/ Number\n\t\tnum, err := strconv.Atoi(cpu)\n\t\tif err != nil || num < 1 {\n\t\t\treturn errors.New(\"invalid CPU value: provide a number or percent greater than 0\")\n\t\t}\n\t\tnumCPU = num\n\t}\n\n\tif numCPU > availCPU {\n\t\tnumCPU = availCPU\n\t}\n\n\truntime.GOMAXPROCS(numCPU)\n\treturn nil\n}\n\nconst appName = \"Caddy\"\n\n\/\/ Flags that control program flow or startup\nvar (\n\tserverType string\n\tconf       string\n\tcpu        string\n\tlogfile    string\n\trevoke     string\n\tversion    bool\n\tplugins    bool\n)\n\n\/\/ Build information obtained with the help of -ldflags\nvar (\n\tappVersion = \"(untracked dev build)\" \/\/ inferred at startup\n\tdevBuild   = true                    \/\/ inferred at startup\n\n\tbuildDate        string \/\/ date -u\n\tgitTag           string \/\/ git describe --exact-match HEAD 2> \/dev\/null\n\tgitNearestTag    string \/\/ git describe --abbrev=0 --tags HEAD\n\tgitCommit        string \/\/ git rev-parse HEAD\n\tgitShortStat     string \/\/ git diff-index --shortstat\n\tgitFilesModified string \/\/ git diff-index --name-only HEAD\n)\n<commit_msg>Fix constant appName to Multipass<commit_after>\/\/ Copyright 2016 Lars Wiegman. All rights reserved. Use of this source code is\n\/\/ governed by a BSD-style license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\n\tlumberjack \"gopkg.in\/natefinch\/lumberjack.v2\"\n\n\t\"github.com\/xenolf\/lego\/acme\"\n\n\t\"github.com\/mholt\/caddy\"\n\t\/\/ plug in the HTTP server type\n\t_ \"github.com\/mholt\/caddy\/caddyhttp\"\n\t\"github.com\/mholt\/caddy\/caddytls\"\n\n\t\/\/ This is where other plugins get plugged in (imported)\n\t_ \"github.com\/mholt\/caddy\/caddyhttp\/proxy\"\n\t_ \"github.com\/namsral\/multipass\"\n)\n\nfunc init() {\n\tcaddy.TrapSignals()\n\tsetVersion()\n\n\tflag.BoolVar(&caddytls.Agreed, \"agree\", false, \"Agree to the CA's Subscriber Agreement\")\n\tflag.StringVar(&caddytls.DefaultCAUrl, \"ca\", \"https:\/\/acme-v01.api.letsencrypt.org\/directory\", \"URL to certificate authority's ACME server directory\")\n\tflag.StringVar(&conf, \"conf\", \"\", \"Caddyfile to load (default \\\"\"+caddy.DefaultConfigFile+\"\\\")\")\n\tflag.StringVar(&cpu, \"cpu\", \"100%\", \"CPU cap\")\n\tflag.BoolVar(&plugins, \"plugins\", false, \"List installed plugins\")\n\tflag.StringVar(&caddytls.DefaultEmail, \"email\", \"\", \"Default ACME CA account email address\")\n\tflag.StringVar(&logfile, \"log\", \"stdout\", \"Process log file\")\n\tflag.StringVar(&caddy.PidFile, \"pidfile\", \"\", \"Path to write pid file\")\n\tflag.BoolVar(&caddy.Quiet, \"quiet\", false, \"Quiet mode (no initialization output)\")\n\tflag.StringVar(&revoke, \"revoke\", \"\", \"Hostname for which to revoke the certificate\")\n\tflag.StringVar(&serverType, \"type\", \"http\", \"Type of server to run\")\n\tflag.BoolVar(&version, \"version\", false, \"Show version\")\n\n\tcaddy.RegisterCaddyfileLoader(\"flag\", caddy.LoaderFunc(confLoader))\n\tcaddy.SetDefaultCaddyfileLoader(\"default\", caddy.LoaderFunc(defaultLoader))\n}\n\n\/\/ Run is Caddy's main() function.\nfunc main() {\n\tflag.Parse()\n\n\tcaddy.AppName = appName\n\tcaddy.AppVersion = appVersion\n\tacme.UserAgent = appName + \"\/\" + appVersion\n\n\t\/\/ Set up process log before anything bad happens\n\tswitch logfile {\n\tcase \"stdout\":\n\t\tlog.SetOutput(os.Stdout)\n\tcase \"stderr\":\n\t\tlog.SetOutput(os.Stderr)\n\tcase \"\":\n\t\tlog.SetOutput(ioutil.Discard)\n\tdefault:\n\t\tlog.SetOutput(&lumberjack.Logger{\n\t\t\tFilename:   logfile,\n\t\t\tMaxSize:    100,\n\t\t\tMaxAge:     14,\n\t\t\tMaxBackups: 10,\n\t\t})\n\t}\n\n\t\/\/ Check for one-time actions\n\tif revoke != \"\" {\n\t\terr := caddytls.Revoke(revoke)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Revoked certificate for %s\\n\", revoke)\n\t\tos.Exit(0)\n\t}\n\tif version {\n\t\tfmt.Printf(\"%s %s\\n\", appName, appVersion)\n\t\tif devBuild && gitShortStat != \"\" {\n\t\t\tfmt.Printf(\"%s\\n%s\\n\", gitShortStat, gitFilesModified)\n\t\t}\n\t\tos.Exit(0)\n\t}\n\tif plugins {\n\t\tfmt.Println(caddy.DescribePlugins())\n\t\tos.Exit(0)\n\t}\n\n\t\/\/ Set CPU cap\n\terr := setCPU(cpu)\n\tif err != nil {\n\t\tmustLogFatal(err)\n\t}\n\n\t\/\/ Get Caddyfile input\n\tcaddyfile, err := caddy.LoadCaddyfile(serverType)\n\tif err != nil {\n\t\tmustLogFatal(err)\n\t}\n\n\t\/\/ Start your engines\n\tinstance, err := caddy.Start(caddyfile)\n\tif err != nil {\n\t\tmustLogFatal(err)\n\t}\n\n\t\/\/ Twiddle your thumbs\n\tinstance.Wait()\n}\n\n\/\/ mustLogFatal wraps log.Fatal() in a way that ensures the\n\/\/ output is always printed to stderr so the user can see it\n\/\/ if the user is still there, even if the process log was not\n\/\/ enabled. If this process is an upgrade, however, and the user\n\/\/ might not be there anymore, this just logs to the process\n\/\/ log and exits.\nfunc mustLogFatal(args ...interface{}) {\n\tif !caddy.IsUpgrade() {\n\t\tlog.SetOutput(os.Stderr)\n\t}\n\tlog.Fatal(args...)\n}\n\n\/\/ confLoader loads the Caddyfile using the -conf flag.\nfunc confLoader(serverType string) (caddy.Input, error) {\n\tif conf == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tif conf == \"stdin\" {\n\t\treturn caddy.CaddyfileFromPipe(os.Stdin)\n\t}\n\n\tcontents, err := ioutil.ReadFile(conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn caddy.CaddyfileInput{\n\t\tContents:       contents,\n\t\tFilepath:       conf,\n\t\tServerTypeName: serverType,\n\t}, nil\n}\n\n\/\/ defaultLoader loads the Caddyfile from the current working directory.\nfunc defaultLoader(serverType string) (caddy.Input, error) {\n\tcontents, err := ioutil.ReadFile(caddy.DefaultConfigFile)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn caddy.CaddyfileInput{\n\t\tContents:       contents,\n\t\tFilepath:       caddy.DefaultConfigFile,\n\t\tServerTypeName: serverType,\n\t}, nil\n}\n\n\/\/ setVersion figures out the version information\n\/\/ based on variables set by -ldflags.\nfunc setVersion() {\n\t\/\/ A development build is one that's not at a tag or has uncommitted changes\n\tdevBuild = gitTag == \"\" || gitShortStat != \"\"\n\n\t\/\/ Only set the appVersion if -ldflags was used\n\tif gitNearestTag != \"\" || gitTag != \"\" {\n\t\tif devBuild && gitNearestTag != \"\" {\n\t\t\tappVersion = fmt.Sprintf(\"%s (+%s %s)\",\n\t\t\t\tstrings.TrimPrefix(gitNearestTag, \"v\"), gitCommit, buildDate)\n\t\t} else if gitTag != \"\" {\n\t\t\tappVersion = strings.TrimPrefix(gitTag, \"v\")\n\t\t}\n\t}\n}\n\n\/\/ setCPU parses string cpu and sets GOMAXPROCS\n\/\/ according to its value. It accepts either\n\/\/ a number (e.g. 3) or a percent (e.g. 50%).\nfunc setCPU(cpu string) error {\n\tvar numCPU int\n\n\tavailCPU := runtime.NumCPU()\n\n\tif strings.HasSuffix(cpu, \"%\") {\n\t\t\/\/ Percent\n\t\tvar percent float32\n\t\tpctStr := cpu[:len(cpu)-1]\n\t\tpctInt, err := strconv.Atoi(pctStr)\n\t\tif err != nil || pctInt < 1 || pctInt > 100 {\n\t\t\treturn errors.New(\"invalid CPU value: percentage must be between 1-100\")\n\t\t}\n\t\tpercent = float32(pctInt) \/ 100\n\t\tnumCPU = int(float32(availCPU) * percent)\n\t} else {\n\t\t\/\/ Number\n\t\tnum, err := strconv.Atoi(cpu)\n\t\tif err != nil || num < 1 {\n\t\t\treturn errors.New(\"invalid CPU value: provide a number or percent greater than 0\")\n\t\t}\n\t\tnumCPU = num\n\t}\n\n\tif numCPU > availCPU {\n\t\tnumCPU = availCPU\n\t}\n\n\truntime.GOMAXPROCS(numCPU)\n\treturn nil\n}\n\nconst appName = \"Multipass\"\n\n\/\/ Flags that control program flow or startup\nvar (\n\tserverType string\n\tconf       string\n\tcpu        string\n\tlogfile    string\n\trevoke     string\n\tversion    bool\n\tplugins    bool\n)\n\n\/\/ Build information obtained with the help of -ldflags\nvar (\n\tappVersion = \"(untracked dev build)\" \/\/ inferred at startup\n\tdevBuild   = true                    \/\/ inferred at startup\n\n\tbuildDate        string \/\/ date -u\n\tgitTag           string \/\/ git describe --exact-match HEAD 2> \/dev\/null\n\tgitNearestTag    string \/\/ git describe --abbrev=0 --tags HEAD\n\tgitCommit        string \/\/ git rev-parse HEAD\n\tgitShortStat     string \/\/ git diff-index --shortstat\n\tgitFilesModified string \/\/ git diff-index --name-only HEAD\n)\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * MinIO Client (C) 2019 MinIO, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fatih\/color\"\n\t\"github.com\/minio\/cli\"\n\t\"github.com\/minio\/mc\/pkg\/probe\"\n\tminio \"github.com\/minio\/minio-go\/v6\"\n\t\"github.com\/minio\/minio\/pkg\/console\"\n)\n\nvar retentionCmd = cli.Command{\n\tName:   \"retention\",\n\tUsage:  \"set object retention for objects with a given prefix\",\n\tAction: mainRetention,\n\tBefore: setGlobalsFromContext,\n\tFlags:  globalFlags,\n\tCustomHelpTemplate: `NAME:\n  {{.HelpName}} - {{.Usage}}\n\nUSAGE:\n  {{.HelpName}} [FLAGS] TARGET [governance | compliance] [VALIDITY]\n\nFLAGS:\n  {{range .VisibleFlags}}{{.}}\n  {{end}}\nVALIDITY:\n  This argument must be formatted like Nd or Ny where 'd' denotes days and 'y' denotes years e.g. 10d, 3y.\n\nEXAMPLES:\n   1. Set object retention for objects in a given prefix\n     $ {{.HelpName}} myminio\/mybucket\/prefix compliance 30d\n`,\n}\n\n\/\/ Structured message depending on the type of console.\ntype retentionCmdMessage struct {\n\tMode     minio.RetentionMode `json:\"mode\"`\n\tValidity *string             `json:\"validity\"`\n\tURLPath  string              `json:\"urlpath\"`\n\tStatus   string              `json:\"status\"`\n\tErr      error               `json:\"error\"`\n}\n\n\/\/ Colorized message for console printing.\nfunc (m retentionCmdMessage) String() string {\n\tif m.Err != nil {\n\t\treturn console.Colorize(\"RetentionMessageFailure\", \"Cannot set object retention on `\"+m.URLPath+\"`.\"+m.Err.Error())\n\t}\n\treturn \"\"\n}\n\n\/\/ JSON'ified message for scripting.\nfunc (m retentionCmdMessage) JSON() string {\n\tmsgBytes, e := json.MarshalIndent(m, \"\", \" \")\n\tfatalIf(probe.NewError(e), \"Unable to marshal into JSON.\")\n\treturn string(msgBytes)\n}\n\n\/\/ setRetention - Set Retention for all objects within a given prefix.\nfunc setRetention(urlStr string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) error {\n\tclnt, err := newClient(urlStr)\n\tif err != nil {\n\t\tfatalIf(err.Trace(), \"Cannot parse the provided url.\")\n\t}\n\n\t\/\/ Quit early if urlStr does not point to an S3 server\n\tswitch clnt.(type) {\n\tcase *fsClient:\n\t\tfatal(errDummy().Trace(), \"Retention for filesystem not supported.\")\n\t}\n\n\talias, _, _ := mustExpandAlias(urlStr)\n\tretainUntilDate := func() (time.Time, error) {\n\t\tif validity == nil {\n\t\t\treturn timeSentinel, fmt.Errorf(\"invalid validity '%v'\", validity)\n\t\t}\n\t\tt := UTCNow()\n\t\tif *unit == minio.Years {\n\t\t\tt = t.AddDate(int(*validity), 0, 0)\n\t\t} else {\n\t\t\tt = t.AddDate(0, 0, int(*validity))\n\t\t}\n\t\ttimeStr := t.Format(time.RFC3339)\n\n\t\tt1, e := time.Parse(\n\t\t\ttime.RFC3339,\n\t\t\ttimeStr)\n\t\tif e != nil {\n\t\t\treturn timeSentinel, e\n\t\t}\n\t\treturn t1, nil\n\t}\n\tvalidityStr := func() *string {\n\t\tif validity == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tunitStr := \"d\"\n\t\tif *unit == minio.Years {\n\t\t\tunitStr = \"y\"\n\t\t}\n\t\ts := fmt.Sprint(*validity, unitStr)\n\t\treturn &s\n\t}\n\n\tvar cErr error\n\terrorsFound := false\n\tfor content := range clnt.List(true, false, false, DirNone) {\n\t\tif content.Err != nil {\n\t\t\terrorIf(content.Err.Trace(clnt.GetURL().String()), \"Unable to list folder.\")\n\t\t\tcErr = exitStatus(globalErrorExitStatus) \/\/ Set the exit status.\n\t\t\tcontinue\n\t\t}\n\t\tretainUntil, err := retainUntilDate()\n\t\tif err != nil {\n\t\t\terrorIf(content.Err.Trace(clnt.GetURL().String()), \"Invalid retention date\")\n\t\t\tcontinue\n\t\t}\n\t\tnewClnt, perr := newClientFromAlias(alias, content.URL.String())\n\t\tif perr != nil {\n\t\t\terrorIf(content.Err.Trace(clnt.GetURL().String()), \"Invalid URL\")\n\t\t\tcontinue\n\t\t}\n\t\tprobeErr := newClnt.PutObjectRetention(mode, &retainUntil)\n\t\tif probeErr != nil {\n\t\t\terrorsFound = true\n\t\t\tprintMsg(retentionCmdMessage{\n\t\t\t\tMode:     *mode,\n\t\t\t\tValidity: validityStr(),\n\t\t\t\tStatus:   \"failure\",\n\t\t\t\tURLPath:  content.URL.Path,\n\t\t\t\tErr:      probeErr.ToGoError(),\n\t\t\t})\n\t\t} else {\n\t\t\tif globalJSON {\n\t\t\t\tprintMsg(retentionCmdMessage{\n\t\t\t\t\tMode:     *mode,\n\t\t\t\t\tValidity: validityStr(),\n\t\t\t\t\tStatus:   \"success\",\n\t\t\t\t\tURLPath:  content.URL.Path,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\tif cErr == nil && !globalJSON {\n\t\tif errorsFound {\n\t\t\tconsole.Print(console.Colorize(\"RetentionPartialFailure\", fmt.Sprintf(\"Errors found while setting retention on objects with prefix `%s`.\\n\", urlStr)))\n\t\t} else {\n\t\t\tconsole.Print(console.Colorize(\"RetentionSuccess\", fmt.Sprintf(\"Object retention successfully set for prefix `%s`.\\n\", urlStr)))\n\t\t}\n\t}\n\treturn cErr\n}\n\n\/\/ main for retention command.\nfunc mainRetention(ctx *cli.Context) error {\n\tconsole.SetColor(\"RetentionSuccess\", color.New(color.FgGreen, color.Bold))\n\tconsole.SetColor(\"RetentionPartialFailure\", color.New(color.FgRed, color.Bold))\n\tconsole.SetColor(\"RetentionMessageFailure\", color.New(color.FgYellow))\n\n\t\/\/ Parse encryption keys per command.\n\t_, err := getEncKeys(ctx)\n\tfatalIf(err, \"Unable to parse encryption keys.\")\n\n\t\/\/ lock specific flags.\n\tclearLock := ctx.Bool(\"clear\")\n\n\targs := ctx.Args()\n\n\tvar urlStr string\n\tvar mode *minio.RetentionMode\n\tvar validity *uint\n\tvar unit *minio.ValidityUnit\n\n\tswitch l := len(args); l {\n\tcase 3:\n\t\turlStr = args[0]\n\t\tif clearLock {\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"clear flag must be passed with target alone\")\n\t\t}\n\n\t\tm := minio.RetentionMode(strings.ToUpper(args[1]))\n\t\tif !m.IsValid() {\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"invalid retention mode '%v'\", m)\n\t\t}\n\n\t\tmode = &m\n\n\t\tvalidityStr := args[2]\n\t\tunitStr := string(validityStr[len(validityStr)-1])\n\n\t\tvalidityStr = validityStr[:len(validityStr)-1]\n\t\tui64, err := strconv.ParseUint(validityStr, 10, 64)\n\t\tif err != nil {\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"invalid validity '%v'\", args[2])\n\t\t}\n\t\tu := uint(ui64)\n\t\tvalidity = &u\n\n\t\tswitch unitStr {\n\t\tcase \"d\", \"D\":\n\t\t\td := minio.Days\n\t\t\tunit = &d\n\t\tcase \"y\", \"Y\":\n\t\t\ty := minio.Years\n\t\t\tunit = &y\n\t\tdefault:\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"invalid validity format '%v'\", args[2])\n\t\t}\n\tdefault:\n\t\tcli.ShowCommandHelpAndExit(ctx, \"retention\", 1)\n\t}\n\treturn setRetention(urlStr, mode, validity, unit)\n}\n<commit_msg>retention - cleanup unused code (#3094)<commit_after>\/*\n * MinIO Client (C) 2019 MinIO, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage cmd\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fatih\/color\"\n\t\"github.com\/minio\/cli\"\n\t\"github.com\/minio\/mc\/pkg\/probe\"\n\tminio \"github.com\/minio\/minio-go\/v6\"\n\t\"github.com\/minio\/minio\/pkg\/console\"\n)\n\nvar retentionCmd = cli.Command{\n\tName:   \"retention\",\n\tUsage:  \"set object retention for objects with a given prefix\",\n\tAction: mainRetention,\n\tBefore: setGlobalsFromContext,\n\tFlags:  globalFlags,\n\tCustomHelpTemplate: `NAME:\n  {{.HelpName}} - {{.Usage}}\n\nUSAGE:\n  {{.HelpName}} [FLAGS] TARGET [governance | compliance] [VALIDITY]\n\nFLAGS:\n  {{range .VisibleFlags}}{{.}}\n  {{end}}\nVALIDITY:\n  This argument must be formatted like Nd or Ny where 'd' denotes days and 'y' denotes years e.g. 10d, 3y.\n\nEXAMPLES:\n   1. Set object retention for objects in a given prefix\n     $ {{.HelpName}} myminio\/mybucket\/prefix compliance 30d\n`,\n}\n\n\/\/ Structured message depending on the type of console.\ntype retentionCmdMessage struct {\n\tMode     minio.RetentionMode `json:\"mode\"`\n\tValidity *string             `json:\"validity\"`\n\tURLPath  string              `json:\"urlpath\"`\n\tStatus   string              `json:\"status\"`\n\tErr      error               `json:\"error\"`\n}\n\n\/\/ Colorized message for console printing.\nfunc (m retentionCmdMessage) String() string {\n\tif m.Err != nil {\n\t\treturn console.Colorize(\"RetentionMessageFailure\", \"Cannot set object retention on `\"+m.URLPath+\"`.\"+m.Err.Error())\n\t}\n\treturn \"\"\n}\n\n\/\/ JSON'ified message for scripting.\nfunc (m retentionCmdMessage) JSON() string {\n\tmsgBytes, e := json.MarshalIndent(m, \"\", \" \")\n\tfatalIf(probe.NewError(e), \"Unable to marshal into JSON.\")\n\treturn string(msgBytes)\n}\n\n\/\/ setRetention - Set Retention for all objects within a given prefix.\nfunc setRetention(urlStr string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) error {\n\tclnt, err := newClient(urlStr)\n\tif err != nil {\n\t\tfatalIf(err.Trace(), \"Cannot parse the provided url.\")\n\t}\n\n\t\/\/ Quit early if urlStr does not point to an S3 server\n\tswitch clnt.(type) {\n\tcase *fsClient:\n\t\tfatal(errDummy().Trace(), \"Retention for filesystem not supported.\")\n\t}\n\n\talias, _, _ := mustExpandAlias(urlStr)\n\tretainUntilDate := func() (time.Time, error) {\n\t\tif validity == nil {\n\t\t\treturn timeSentinel, fmt.Errorf(\"invalid validity '%v'\", validity)\n\t\t}\n\t\tt := UTCNow()\n\t\tif *unit == minio.Years {\n\t\t\tt = t.AddDate(int(*validity), 0, 0)\n\t\t} else {\n\t\t\tt = t.AddDate(0, 0, int(*validity))\n\t\t}\n\t\ttimeStr := t.Format(time.RFC3339)\n\n\t\tt1, e := time.Parse(\n\t\t\ttime.RFC3339,\n\t\t\ttimeStr)\n\t\tif e != nil {\n\t\t\treturn timeSentinel, e\n\t\t}\n\t\treturn t1, nil\n\t}\n\tvalidityStr := func() *string {\n\t\tif validity == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\tunitStr := \"d\"\n\t\tif *unit == minio.Years {\n\t\t\tunitStr = \"y\"\n\t\t}\n\t\ts := fmt.Sprint(*validity, unitStr)\n\t\treturn &s\n\t}\n\n\tvar cErr error\n\terrorsFound := false\n\tfor content := range clnt.List(true, false, false, DirNone) {\n\t\tif content.Err != nil {\n\t\t\terrorIf(content.Err.Trace(clnt.GetURL().String()), \"Unable to list folder.\")\n\t\t\tcErr = exitStatus(globalErrorExitStatus) \/\/ Set the exit status.\n\t\t\tcontinue\n\t\t}\n\t\tretainUntil, err := retainUntilDate()\n\t\tif err != nil {\n\t\t\terrorIf(content.Err.Trace(clnt.GetURL().String()), \"Invalid retention date\")\n\t\t\tcontinue\n\t\t}\n\t\tnewClnt, perr := newClientFromAlias(alias, content.URL.String())\n\t\tif perr != nil {\n\t\t\terrorIf(content.Err.Trace(clnt.GetURL().String()), \"Invalid URL\")\n\t\t\tcontinue\n\t\t}\n\t\tprobeErr := newClnt.PutObjectRetention(mode, &retainUntil)\n\t\tif probeErr != nil {\n\t\t\terrorsFound = true\n\t\t\tprintMsg(retentionCmdMessage{\n\t\t\t\tMode:     *mode,\n\t\t\t\tValidity: validityStr(),\n\t\t\t\tStatus:   \"failure\",\n\t\t\t\tURLPath:  content.URL.Path,\n\t\t\t\tErr:      probeErr.ToGoError(),\n\t\t\t})\n\t\t} else {\n\t\t\tif globalJSON {\n\t\t\t\tprintMsg(retentionCmdMessage{\n\t\t\t\t\tMode:     *mode,\n\t\t\t\t\tValidity: validityStr(),\n\t\t\t\t\tStatus:   \"success\",\n\t\t\t\t\tURLPath:  content.URL.Path,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\tif cErr == nil && !globalJSON {\n\t\tif errorsFound {\n\t\t\tconsole.Print(console.Colorize(\"RetentionPartialFailure\", fmt.Sprintf(\"Errors found while setting retention on objects with prefix `%s`.\\n\", urlStr)))\n\t\t} else {\n\t\t\tconsole.Print(console.Colorize(\"RetentionSuccess\", fmt.Sprintf(\"Object retention successfully set for prefix `%s`.\\n\", urlStr)))\n\t\t}\n\t}\n\treturn cErr\n}\n\n\/\/ main for retention command.\nfunc mainRetention(ctx *cli.Context) error {\n\tconsole.SetColor(\"RetentionSuccess\", color.New(color.FgGreen, color.Bold))\n\tconsole.SetColor(\"RetentionPartialFailure\", color.New(color.FgRed, color.Bold))\n\tconsole.SetColor(\"RetentionMessageFailure\", color.New(color.FgYellow))\n\targs := ctx.Args()\n\n\tvar urlStr string\n\tvar mode *minio.RetentionMode\n\tvar validity *uint\n\tvar unit *minio.ValidityUnit\n\n\tswitch l := len(args); l {\n\tcase 3:\n\t\turlStr = args[0]\n\t\tm := minio.RetentionMode(strings.ToUpper(args[1]))\n\t\tif !m.IsValid() {\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"invalid retention mode '%v'\", m)\n\t\t}\n\n\t\tmode = &m\n\n\t\tvalidityStr := args[2]\n\t\tunitStr := string(validityStr[len(validityStr)-1])\n\n\t\tvalidityStr = validityStr[:len(validityStr)-1]\n\t\tui64, err := strconv.ParseUint(validityStr, 10, 64)\n\t\tif err != nil {\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"invalid validity '%v'\", args[2])\n\t\t}\n\t\tu := uint(ui64)\n\t\tvalidity = &u\n\n\t\tswitch unitStr {\n\t\tcase \"d\", \"D\":\n\t\t\td := minio.Days\n\t\t\tunit = &d\n\t\tcase \"y\", \"Y\":\n\t\t\ty := minio.Years\n\t\t\tunit = &y\n\t\tdefault:\n\t\t\tfatalIf(probe.NewError(errors.New(\"invalid argument\")), \"invalid validity format '%v'\", args[2])\n\t\t}\n\tdefault:\n\t\tcli.ShowCommandHelpAndExit(ctx, \"retention\", 1)\n\t}\n\treturn setRetention(urlStr, mode, validity, unit)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"log\"\n\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\nvar (\n\tstInsert *sql.Stmt\n\tstUpdate *sql.Stmt\n\tstDelete *sql.Stmt\n)\n\nfunc main() {\n\tdb, err := sql.Open(\"mysql\", \"vagrant:db1234@tcp(127.0.0.1:3306)\/vagrant\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\terr = test(db)\n\tif err != nil {\n\t\tlog.Printf(\"WARN: %s\", err)\n\t}\n}\n\nfunc test(db *sql.DB) error {\n\tif err := test0(db); err != nil {\n\t\treturn err\n\t}\n\tif err := test1(db); err != nil {\n\t\treturn err\n\t}\n\tif err := test2(db); err != nil {\n\t\treturn err\n\t}\n\tif err := test3(db); err != nil {\n\t\treturn err\n\t}\n\t\/\/ TODO:\n\tif err := test99(db); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc test0(db *sql.DB) error {\n\trows, err := db.Query(`SHOW DATABASES`)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar name string\n\t\terr := rows.Scan(&name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"test0: table:%s found\\n\", name)\n\t}\n\treturn nil\n}\n\nfunc test1(db *sql.DB) error {\n\t_, err := db.Exec(`CREATE TABLE IF NOT EXISTS users (\n\t\tid INT PRIMARY KEY AUTO_INCREMENT,\n\t\tname VARCHAR(255) UNIQUE,\n\t\tpassword VARCHAR(255)\n\t)`)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc test2(db *sql.DB) error {\n\tvar err error\n\tstInsert, err = db.Prepare(\n\t\t`INSERT INTO users (name, password) VALUES (?, ?)`)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstUpdate, err = db.Prepare(\n\t\t`UPDATE users SET name = ?, password = ? WHERE id = ?`)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstDelete, err = db.Prepare(`DELETE FROM users WHERE id = ?`)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc test3(db *sql.DB) error {\n\tvar err error\n\t_, err = db.Prepare(\n\t\t`INSERT INTO users (name, password) VALUES (?, ?`)\n\tif err == nil {\n\t\tpanic(\"prepare in test3 should be failed\")\n\t}\n\tfmt.Printf(\"test3: IGNORED ERROR: %s\\n\", err)\n\treturn nil\n}\n\nfunc test99(db *sql.DB) error {\n\tif stDelete != nil {\n\t\tstDelete.Close()\n\t}\n\tif stUpdate != nil {\n\t\tstUpdate.Close()\n\t}\n\tif stInsert != nil {\n\t\tstInsert.Close()\n\t}\n\t_, err := db.Exec(`DROP TABLE users`)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>test more prepared statements<commit_after>package main\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"log\"\n\n\t_ \"github.com\/go-sql-driver\/mysql\"\n)\n\nvar (\n\tstInsert *sql.Stmt\n\tstSelect *sql.Stmt\n\tstUpdate *sql.Stmt\n\tstDelete *sql.Stmt\n)\n\nfunc main() {\n\tdb, err := sql.Open(\"mysql\", \"vagrant:db1234@tcp(127.0.0.1:3306)\/vagrant\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\terr = test(db)\n\tif err != nil {\n\t\tlog.Printf(\"WARN: %s\", err)\n\t}\n}\n\nfunc test(db *sql.DB) error {\n\tif err := test0(db); err != nil {\n\t\treturn err\n\t}\n\tif err := test1(db); err != nil {\n\t\treturn err\n\t}\n\tif err := test2(db); err != nil {\n\t\treturn err\n\t}\n\tif err := test3(db); err != nil {\n\t\treturn err\n\t}\n\tif err := test4(db); err != nil {\n\t\treturn err\n\t}\n\tif err := test5(db); err != nil {\n\t\treturn err\n\t}\n\t\/\/ TODO:\n\tif err := test99(db); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc test0(db *sql.DB) error {\n\trows, err := db.Query(`SHOW DATABASES`)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\tfor rows.Next() {\n\t\tvar name string\n\t\terr := rows.Scan(&name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"test0: table:%s found\\n\", name)\n\t}\n\treturn nil\n}\n\nfunc test1(db *sql.DB) error {\n\t_, err := db.Exec(`CREATE TABLE IF NOT EXISTS users (\n\t\tid INT PRIMARY KEY AUTO_INCREMENT,\n\t\tname VARCHAR(255) UNIQUE,\n\t\tpassword VARCHAR(255)\n\t)`)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc test2(db *sql.DB) error {\n\tvar err error\n\tstInsert, err = db.Prepare(\n\t\t`INSERT INTO users (name, password) VALUES (?, ?)`)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstSelect, err = db.Prepare(`SELECT * FROM users WHERE name LIKE ?`)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstUpdate, err = db.Prepare(\n\t\t`UPDATE users SET name = ?, password = ? WHERE id = ?`)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstDelete, err = db.Prepare(`DELETE FROM users WHERE id = ?`)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc test3(db *sql.DB) error {\n\tvar err error\n\t_, err = db.Prepare(\n\t\t`INSERT INTO users (name, password) VALUES (?, ?`)\n\tif err == nil {\n\t\tpanic(\"prepare in test3 should be failed\")\n\t}\n\tfmt.Printf(\"test3: IGNORED ERROR: %s\\n\", err)\n\treturn nil\n}\n\nfunc test4(db *sql.DB) error {\n\tinsert := func(u, p string) error {\n\t\tr, err := stInsert.Exec(u, p)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tid, _ := r.LastInsertId()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"test4: inserted %q as %d\\n\", u, id)\n\t\treturn nil\n\t}\n\tif err := insert(\"foo\", \"pass1234\"); err != nil {\n\t\treturn err\n\t}\n\tif err := insert(\"baz\", \"pass1234\"); err != nil {\n\t\treturn err\n\t}\n\tif err := insert(\"bar\", \"pass1234\"); err != nil {\n\t\treturn err\n\t}\n\tif err := insert(\"user001\", \"pass1234\"); err != nil {\n\t\treturn err\n\t}\n\tif err := insert(\"user002\", \"pass1234\"); err != nil {\n\t\treturn err\n\t}\n\tif err := insert(\"user003\", \"pass1234\"); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc test5(db *sql.DB) error {\n\trows, err := stSelect.Query(\"user%\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\treturn nil\n}\n\nfunc test99(db *sql.DB) error {\n\tif stDelete != nil {\n\t\tstDelete.Close()\n\t}\n\tif stUpdate != nil {\n\t\tstUpdate.Close()\n\t}\n\tif stSelect != nil {\n\t\tstSelect.Close()\n\t}\n\tif stInsert != nil {\n\t\tstInsert.Close()\n\t}\n\t_, err := db.Exec(`DROP TABLE users`)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmdpolling\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n\t\"errors\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/ingrammicro\/concerto\/api\/polling\"\n\t\"github.com\/ingrammicro\/concerto\/cmd\"\n\t\"github.com\/ingrammicro\/concerto\/utils\"\n\t\"github.com\/ingrammicro\/concerto\/utils\/format\"\n)\n\nconst (\n\tProcessIdFile = \"imco-polling.pid\"\n)\n\nvar (\n\tcommandProcessed = make(chan bool, 1)\n)\n\n\/\/ Handle signals\nfunc handleSysSignals(cancelFunc context.CancelFunc) {\n\tlog.Debug(\"handleSysSignals\")\n\n\tgracefulStop := make(chan os.Signal, 1)\n\tsignal.Notify(gracefulStop, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)\n\tlog.Debug(\"Ending, signal detected:\", <-gracefulStop)\n\tcancelFunc()\n}\n\n\/\/ Start the polling process\nfunc cmdStart(c *cli.Context) error {\n\tlog.Debug(\"cmdStart\")\n\n\tformatter := format.GetFormatter()\n\tif err := utils.SetProcessIdToFile(ProcessIdFile); err != nil {\n\t\tformatter.PrintFatal(\"cannot create the pid file\", err)\n\t}\n\n\tpollingPingTimingInterval := c.Int64(\"time\")\n\tif !(pollingPingTimingInterval > 0) {\n\t\tformatter.PrintFatal(\"invalid argument\", errors.New(\"a positive value should be used\"))\n\t}\n\tlog.Debug(\"Ping time interval:\", pollingPingTimingInterval)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tgo handleSysSignals(cancel)\n\n\tpingRoutine(ctx, c, pollingPingTimingInterval)\n\n\treturn nil\n}\n\n\/\/ Stop the polling process\nfunc cmdStop(c *cli.Context) error {\n\tlog.Debug(\"cmdStop\")\n\n\tformatter := format.GetFormatter()\n\tif err := utils.StopProcess(ProcessIdFile); err != nil {\n\t\tformatter.PrintFatal(\"cannot stop the polling process\", err)\n\t}\n\n\tlog.Info(\"concerto polling successfully stopped\")\n\treturn nil\n}\n\n\/\/ Main polling background routine\nfunc pingRoutine(ctx context.Context, c *cli.Context, pollingPingTimingInterval int64) {\n\tlog.Debug(\"pingRoutine\")\n\n\tformatter := format.GetFormatter()\n\tpollingSvc := cmd.WireUpPolling(c)\n\n\tisRunningCommandRoutine := false\n\tt := time.NewTicker(time.Duration(pollingPingTimingInterval) * time.Second)\n\tfor {\n\t\tlog.Debug(\"Requesting for candidate commands status\")\n\t\tping, status, err := pollingSvc.Ping()\n\t\tif err != nil {\n\t\t\tformatter.PrintError(\"Couldn't receive polling ping data\", err)\n\t\t} else {\n\t\t\t\/\/ One command is available, and no process running\n\t\t\tif status == 201 && ping.PendingCommands && !isRunningCommandRoutine {\n\t\t\t\tlog.Debug(\"Detected a candidate command\")\n\t\t\t\tisRunningCommandRoutine = true\n\t\t\t\tgo processingCommandRoutine(pollingSvc, formatter)\n\t\t\t}\n\t\t}\n\n\t\tselect {\n\t\tcase <-commandProcessed:\n\t\t\tisRunningCommandRoutine = false\n\t\tdefault:\n\t\t}\n\n\t\tselect {\n\t\tcase <-t.C:\n\t\tcase <-ctx.Done():\n\t\t\tlog.Debug(ctx.Err())\n\t\t\tlog.Debug(\"closing polling\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ Subsidiary routine for commands processing\nfunc processingCommandRoutine(pollingSvc *polling.PollingService, formatter format.Formatter) {\n\tlog.Debug(\"processingCommandRoutine\")\n\n\t\/\/ 1. Request for the new command available\n\tlog.Debug(\"Retrieving available command\")\n\tcommand, status, err := pollingSvc.GetNextCommand()\n\tif err != nil {\n\t\tformatter.PrintError(\"Couldn't receive polling command candidate data\", err)\n\t}\n\n\t\/\/ 2. Execute the retrieved command\n\tif status == 200 {\n\t\tlog.Debug(\"Running the retrieved command\")\n\t\tcommand.Stdout, command.ExitCode, _, _ = utils.RunCmd(command.Script)\n\t\tcommand.Stderr = \"\"\n\t\tif command.ExitCode != 0 {\n\t\t\tcommand.Stderr = command.Stdout\n\t\t\tcommand.Stdout = \"\"\n\t\t}\n\n\t\t\/\/ 3. If command successfully executed, then status is propagated to IMCO\n\t\tif command.ExitCode == 0 {\n\t\t\tlog.Debug(\"Reporting command execution status\")\n\t\t\tcommandIn, err := utils.ItemConvertParamsWithTagAsID(*command)\n\t\t\tif err != nil {\n\t\t\t\tformatter.PrintError(\"Couldn't send polling command report data; error parsing payload\", err)\n\t\t\t}\n\n\t\t\t_, status, err := pollingSvc.UpdateCommand(commandIn, command.Id)\n\t\t\tif err != nil {\n\t\t\t\tformatter.PrintError(\"Couldn't send polling command report data\", err)\n\t\t\t}\n\n\t\t\tif status == 200 {\n\t\t\t\tlog.Debug(\"Command execution results successfully reported\")\n\t\t\t} else {\n\t\t\t\tlog.Error(\"Cannot report the command execution results\")\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Error(\"Cannot run the retrieved command\")\n\t\t}\n\t} else {\n\t\tlog.Error(\"Cannot retrieve the next command\")\n\t}\n\n\tcommandProcessed <- true\n}\n<commit_msg>Use default time period in a bad command parameter case (issue #13)<commit_after>package cmdpolling\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/ingrammicro\/concerto\/api\/polling\"\n\t\"github.com\/ingrammicro\/concerto\/cmd\"\n\t\"github.com\/ingrammicro\/concerto\/utils\"\n\t\"github.com\/ingrammicro\/concerto\/utils\/format\"\n)\n\nconst (\n\tDefaultPollingPingTimingInterval = 30\n\tProcessIdFile                    = \"imco-polling.pid\"\n)\n\nvar (\n\tcommandProcessed = make(chan bool, 1)\n)\n\n\/\/ Handle signals\nfunc handleSysSignals(cancelFunc context.CancelFunc) {\n\tlog.Debug(\"handleSysSignals\")\n\n\tgracefulStop := make(chan os.Signal, 1)\n\tsignal.Notify(gracefulStop, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)\n\tlog.Debug(\"Ending, signal detected:\", <-gracefulStop)\n\tcancelFunc()\n}\n\n\/\/ Start the polling process\nfunc cmdStart(c *cli.Context) error {\n\tlog.Debug(\"cmdStart\")\n\n\tformatter := format.GetFormatter()\n\tif err := utils.SetProcessIdToFile(ProcessIdFile); err != nil {\n\t\tformatter.PrintFatal(\"cannot create the pid file\", err)\n\t}\n\n\tpollingPingTimingInterval := c.Int64(\"time\")\n\tif !(pollingPingTimingInterval > 0) {\n\t\tpollingPingTimingInterval = DefaultPollingPingTimingInterval\n\t}\n\tlog.Debug(\"Ping time interval:\", pollingPingTimingInterval)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tgo handleSysSignals(cancel)\n\n\tpingRoutine(ctx, c, pollingPingTimingInterval)\n\n\treturn nil\n}\n\n\/\/ Stop the polling process\nfunc cmdStop(c *cli.Context) error {\n\tlog.Debug(\"cmdStop\")\n\n\tformatter := format.GetFormatter()\n\tif err := utils.StopProcess(ProcessIdFile); err != nil {\n\t\tformatter.PrintFatal(\"cannot stop the polling process\", err)\n\t}\n\n\tlog.Info(\"concerto polling successfully stopped\")\n\treturn nil\n}\n\n\/\/ Main polling background routine\nfunc pingRoutine(ctx context.Context, c *cli.Context, pollingPingTimingInterval int64) {\n\tlog.Debug(\"pingRoutine\")\n\n\tformatter := format.GetFormatter()\n\tpollingSvc := cmd.WireUpPolling(c)\n\n\tisRunningCommandRoutine := false\n\tt := time.NewTicker(time.Duration(pollingPingTimingInterval) * time.Second)\n\tfor {\n\t\tlog.Debug(\"Requesting for candidate commands status\")\n\t\tping, status, err := pollingSvc.Ping()\n\t\tif err != nil {\n\t\t\tformatter.PrintError(\"Couldn't receive polling ping data\", err)\n\t\t} else {\n\t\t\t\/\/ One command is available, and no process running\n\t\t\tif status == 201 && ping.PendingCommands && !isRunningCommandRoutine {\n\t\t\t\tlog.Debug(\"Detected a candidate command\")\n\t\t\t\tisRunningCommandRoutine = true\n\t\t\t\tgo processingCommandRoutine(pollingSvc, formatter)\n\t\t\t}\n\t\t}\n\n\t\tselect {\n\t\tcase <-commandProcessed:\n\t\t\tisRunningCommandRoutine = false\n\t\tdefault:\n\t\t}\n\n\t\tselect {\n\t\tcase <-t.C:\n\t\tcase <-ctx.Done():\n\t\t\tlog.Debug(ctx.Err())\n\t\t\tlog.Debug(\"closing polling\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ Subsidiary routine for commands processing\nfunc processingCommandRoutine(pollingSvc *polling.PollingService, formatter format.Formatter) {\n\tlog.Debug(\"processingCommandRoutine\")\n\n\t\/\/ 1. Request for the new command available\n\tlog.Debug(\"Retrieving available command\")\n\tcommand, status, err := pollingSvc.GetNextCommand()\n\tif err != nil {\n\t\tformatter.PrintError(\"Couldn't receive polling command candidate data\", err)\n\t}\n\n\t\/\/ 2. Execute the retrieved command\n\tif status == 200 {\n\t\tlog.Debug(\"Running the retrieved command\")\n\t\tcommand.Stdout, command.ExitCode, _, _ = utils.RunCmd(command.Script)\n\t\tcommand.Stderr = \"\"\n\t\tif command.ExitCode != 0 {\n\t\t\tcommand.Stderr = command.Stdout\n\t\t\tcommand.Stdout = \"\"\n\t\t}\n\n\t\t\/\/ 3. If command successfully executed, then status is propagated to IMCO\n\t\tif command.ExitCode == 0 {\n\t\t\tlog.Debug(\"Reporting command execution status\")\n\t\t\tcommandIn, err := utils.ItemConvertParamsWithTagAsID(*command)\n\t\t\tif err != nil {\n\t\t\t\tformatter.PrintError(\"Couldn't send polling command report data; error parsing payload\", err)\n\t\t\t}\n\n\t\t\t_, status, err := pollingSvc.UpdateCommand(commandIn, command.Id)\n\t\t\tif err != nil {\n\t\t\t\tformatter.PrintError(\"Couldn't send polling command report data\", err)\n\t\t\t}\n\n\t\t\tif status == 200 {\n\t\t\t\tlog.Debug(\"Command execution results successfully reported\")\n\t\t\t} else {\n\t\t\t\tlog.Error(\"Cannot report the command execution results\")\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Error(\"Cannot run the retrieved command\")\n\t\t}\n\t} else {\n\t\tlog.Error(\"Cannot retrieve the next command\")\n\t}\n\n\tcommandProcessed <- true\n}\n<|endoftext|>"}
{"text":"<commit_before>package command\n\nimport (\n\t\"github.com\/webdevops\/go-stubfilegenerator\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"path\/filepath\"\n)\n\ntype Typo3Stubs struct {\n\tOptions MysqlCommonOptions `group:\"common\"`\n\tPositional struct {\n\t\tSchema string `description:\"Schema\" required:\"1\"`\n\t\tTypo3Root string `description:\"TYPO3 root path\" required:\"1\"`\n\t} `positional-args:\"true\"`\n\tForce  bool   `short:\"f\"  long:\"force\"      description:\"Overwrite existing files\"`\n}\n\ntype storage struct {\n\tUid string\n\tName string\n\tPath string\n}\n\ntype storageFile struct {\n\tUid string\n\tPath string\n\tRelPath string\n\tAbsPath string\n\tImageWidth string\n\tImageHeight string\n}\n\nfunc (conf *Typo3Stubs) Execute(args []string) error {\n\tfmt.Println(\"Starting TYPO3 fileadmin stub generator\")\n\tconf.Options.Init()\n\n\tsql := `SELECT uid,\n                   name,\n                   ExtractValue(configuration, '\/\/field[@index=\\'basePath\\']\/value\/text()') as storagepath\n              FROM sys_file_storage\n             WHERE deleted = 0\n              AND driver = 'local'`\n\tresult := conf.Options.ExecQuery(conf.Positional.Schema, sql)\n\n\tfor _, val := range result {\n\t\tstorage := storage{val[0], val[1], val[2]}\n\t\tconf.processStorage(storage)\n\t}\n\n\treturn nil\n}\n\nfunc (conf *Typo3Stubs) processStorage(storage storage) {\n\tstubgen := stubfilegenerator.StubGenerator()\n\n\tif conf.Force {\n\t\tstubgen.Overwrite = true\n\t}\n\n\tsql := `SELECT f.uid,\n                   f.identifier,\n                   fm.width as meta_width,\n                   fm.height as meta_height\n              FROM sys_file f\n                   LEFT JOIN sys_file_metadata fm\n                     ON fm.file = f.uid\n                    AND fm.t3ver_oid = 0\n              WHERE f.storage = ` + storage.Uid;\n\tresult := conf.Options.ExecQuery(conf.Positional.Schema, sql)\n\n\tfor _, val := range result {\n\t\tfile := storageFile{}\n\t\tfile.ImageWidth = \"800\"\n\t\tfile.ImageHeight = \"400\"\n\n\t\tswitch len(val) {\n\t\tcase 4:\n\t\t\tfile.ImageWidth = val[2]\n\t\t\tfile.ImageHeight = val[3]\n\t\t\tfile.Uid = val[0]\n\t\t\tfile.Path = val[1]\n\t\t\tfallthrough\n\t\tcase 2:\n\t\t\tfile.Uid = val[0]\n\t\t\tfile.Path = filepath.Join(storage.Path, val[1])\n\t\t\tfile.RelPath = filepath.Join(conf.Positional.Typo3Root, file.Path)\n\t\t\tfile.AbsPath, _ = filepath.Abs(file.RelPath)\n\t\t}\n\n\t\tstubgen.TemplateVariables[\"PATH\"] = file.Path\n\t\tstubgen.Image.Width, _ = strconv.Atoi(file.ImageWidth)\n\t\tstubgen.Image.Height, _ = strconv.Atoi(file.ImageHeight)\n\t\tstubgen.GenerateStub(file.AbsPath)\n\t}\n\n}\n<commit_msg>Add image size as text to stubs<commit_after>package command\n\nimport (\n\t\"github.com\/webdevops\/go-stubfilegenerator\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"path\/filepath\"\n)\n\ntype Typo3Stubs struct {\n\tOptions MysqlCommonOptions `group:\"common\"`\n\tPositional struct {\n\t\tSchema string `description:\"Schema\" required:\"1\"`\n\t\tTypo3Root string `description:\"TYPO3 root path\" required:\"1\"`\n\t} `positional-args:\"true\"`\n\tForce  bool   `short:\"f\"  long:\"force\"      description:\"Overwrite existing files\"`\n}\n\ntype storage struct {\n\tUid string\n\tName string\n\tPath string\n}\n\ntype storageFile struct {\n\tUid string\n\tPath string\n\tRelPath string\n\tAbsPath string\n\tImageWidth string\n\tImageHeight string\n}\n\nfunc (conf *Typo3Stubs) Execute(args []string) error {\n\tfmt.Println(\"Starting TYPO3 fileadmin stub generator\")\n\tconf.Options.Init()\n\n\tsql := `SELECT uid,\n                   name,\n                   ExtractValue(configuration, '\/\/field[@index=\\'basePath\\']\/value\/text()') as storagepath\n              FROM sys_file_storage\n             WHERE deleted = 0\n              AND driver = 'local'`\n\tresult := conf.Options.ExecQuery(conf.Positional.Schema, sql)\n\n\tfor _, val := range result {\n\t\tstorage := storage{val[0], val[1], val[2]}\n\t\tconf.processStorage(storage)\n\t}\n\n\treturn nil\n}\n\nfunc (conf *Typo3Stubs) processStorage(storage storage) {\n\tstubgen := stubfilegenerator.StubGenerator()\n\tstubgen.Image.Text = append(stubgen.Image.Text, \"Size: %IMAGE_WIDTH% * %IMAGE_HEIGHT%\")\n\n\tif conf.Force {\n\t\tstubgen.Overwrite = true\n\t}\n\n\tsql := `SELECT f.uid,\n                   f.identifier,\n                   fm.width as meta_width,\n                   fm.height as meta_height\n              FROM sys_file f\n                   LEFT JOIN sys_file_metadata fm\n                     ON fm.file = f.uid\n                    AND fm.t3ver_oid = 0\n              WHERE f.storage = ` + storage.Uid;\n\tresult := conf.Options.ExecQuery(conf.Positional.Schema, sql)\n\n\tfor _, val := range result {\n\t\tfile := storageFile{}\n\t\tfile.ImageWidth = \"800\"\n\t\tfile.ImageHeight = \"400\"\n\n\t\tswitch len(val) {\n\t\tcase 4:\n\t\t\tfile.ImageWidth = val[2]\n\t\t\tfile.ImageHeight = val[3]\n\t\t\tfile.Uid = val[0]\n\t\t\tfile.Path = val[1]\n\t\t\tfallthrough\n\t\tcase 2:\n\t\t\tfile.Uid = val[0]\n\t\t\tfile.Path = filepath.Join(storage.Path, val[1])\n\t\t\tfile.RelPath = filepath.Join(conf.Positional.Typo3Root, file.Path)\n\t\t\tfile.AbsPath, _ = filepath.Abs(file.RelPath)\n\t\t}\n\n\t\tstubgen.TemplateVariables[\"PATH\"] = file.Path\n\t\tstubgen.TemplateVariables[\"IMAGE_WIDTH\"] = file.ImageWidth\n\t\tstubgen.TemplateVariables[\"IMAGE_HEIGHT\"] = file.ImageHeight\n\t\tstubgen.Image.Width, _ = strconv.Atoi(file.ImageWidth)\n\t\tstubgen.Image.Height, _ = strconv.Atoi(file.ImageHeight)\n\t\tstubgen.GenerateStub(file.AbsPath)\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package fakeyagnats\n\nimport (\n\t\"github.com\/cloudfoundry\/yagnats\"\n)\n\ntype FakeYagnats struct {\n\tSubscriptions     map[string][]yagnats.Subscription\n\tPublishedMessages map[string][]yagnats.Message\n\tUnsubscriptions   []int\n\n\tConnectedConnectionProvider yagnats.ConnectionProvider\n\n\tConnectError     error\n\tPublishError     error\n\tSubscribeError   error\n\tUnsubscribeError error\n\n\tDidUnsubscribeAll bool\n\tPingResponse      bool\n\n\tcounter int\n}\n\nfunc New() *FakeYagnats {\n\tfake := &FakeYagnats{}\n\tfake.Reset()\n\treturn fake\n}\n\nfunc (f *FakeYagnats) Reset() {\n\tf.PublishedMessages = map[string][]yagnats.Message{}\n\tf.Subscriptions = map[string][]yagnats.Subscription{}\n\tf.Unsubscriptions = []int{}\n\n\tf.ConnectedConnectionProvider = nil\n\n\tf.ConnectError = nil\n\tf.PublishError = nil\n\tf.SubscribeError = nil\n\tf.UnsubscribeError = nil\n\n\tf.DidUnsubscribeAll = false\n\tf.PingResponse = true\n\n\tf.counter = 0\n}\n\nfunc (f *FakeYagnats) Ping() bool {\n\treturn f.PingResponse\n}\n\nfunc (f *FakeYagnats) Connect(connectionProvider yagnats.ConnectionProvider) error {\n\tf.ConnectedConnectionProvider = connectionProvider\n\treturn f.ConnectError\n}\n\nfunc (f *FakeYagnats) Disconnect() {\n\tf.ConnectedConnectionProvider = nil\n\treturn\n}\n\nfunc (f *FakeYagnats) Publish(subject, payload string) error {\n\treturn f.PublishWithReplyTo(subject, payload, \"\")\n}\n\nfunc (f *FakeYagnats) PublishWithReplyTo(subject, payload, reply string) error {\n\tmessage := yagnats.Message{\n\t\tSubject: subject,\n\t\tPayload: payload,\n\t\tReplyTo: reply,\n\t}\n\n\tf.PublishedMessages[subject] = append(f.PublishedMessages[subject], message)\n\n\treturn f.PublishError\n}\n\nfunc (f *FakeYagnats) Subscribe(subject string, callback yagnats.Callback) (int, error) {\n\treturn f.SubscribeWithQueue(subject, \"\", callback)\n}\n\nfunc (f *FakeYagnats) SubscribeWithQueue(subject, queue string, callback yagnats.Callback) (int, error) {\n\tf.counter++\n\tsubscription := yagnats.Subscription{\n\t\tSubject:  subject,\n\t\tQueue:    queue,\n\t\tID:       f.counter,\n\t\tCallback: callback,\n\t}\n\n\tf.Subscriptions[subject] = append(f.Subscriptions[subject], subscription)\n\n\treturn subscription.ID, f.SubscribeError\n}\n\nfunc (f *FakeYagnats) Unsubscribe(subscription int) error {\n\tf.Unsubscriptions = append(f.Unsubscriptions, subscription)\n\treturn f.UnsubscribeError\n}\n\nfunc (f *FakeYagnats) UnsubscribeAll() {\n\tf.DidUnsubscribeAll = true\n}\n<commit_msg>oops. fake yagnats didn't satisfy the interface.  fixed.<commit_after>package fakeyagnats\n\nimport (\n\t\"github.com\/cloudfoundry\/yagnats\"\n)\n\ntype FakeYagnats struct {\n\tSubscriptions        map[string][]yagnats.Subscription\n\tPublishedMessages    map[string][]yagnats.Message\n\tUnsubscriptions      []int\n\tUnsubscribedSubjects []string\n\n\tConnectedConnectionProvider yagnats.ConnectionProvider\n\n\tConnectError     error\n\tPublishError     error\n\tSubscribeError   error\n\tUnsubscribeError error\n\n\tPingResponse bool\n\n\tcounter int\n}\n\nfunc New() *FakeYagnats {\n\tfake := &FakeYagnats{}\n\tfake.Reset()\n\treturn fake\n}\n\nfunc (f *FakeYagnats) Reset() {\n\tf.PublishedMessages = map[string][]yagnats.Message{}\n\tf.Subscriptions = map[string][]yagnats.Subscription{}\n\tf.Unsubscriptions = []int{}\n\tf.UnsubscribedSubjects = []string{}\n\n\tf.ConnectedConnectionProvider = nil\n\n\tf.ConnectError = nil\n\tf.PublishError = nil\n\tf.SubscribeError = nil\n\tf.UnsubscribeError = nil\n\n\tf.PingResponse = true\n\n\tf.counter = 0\n}\n\nfunc (f *FakeYagnats) Ping() bool {\n\treturn f.PingResponse\n}\n\nfunc (f *FakeYagnats) Connect(connectionProvider yagnats.ConnectionProvider) error {\n\tf.ConnectedConnectionProvider = connectionProvider\n\treturn f.ConnectError\n}\n\nfunc (f *FakeYagnats) Disconnect() {\n\tf.ConnectedConnectionProvider = nil\n\treturn\n}\n\nfunc (f *FakeYagnats) Publish(subject, payload string) error {\n\treturn f.PublishWithReplyTo(subject, payload, \"\")\n}\n\nfunc (f *FakeYagnats) PublishWithReplyTo(subject, payload, reply string) error {\n\tmessage := yagnats.Message{\n\t\tSubject: subject,\n\t\tPayload: payload,\n\t\tReplyTo: reply,\n\t}\n\n\tf.PublishedMessages[subject] = append(f.PublishedMessages[subject], message)\n\n\treturn f.PublishError\n}\n\nfunc (f *FakeYagnats) Subscribe(subject string, callback yagnats.Callback) (int, error) {\n\treturn f.SubscribeWithQueue(subject, \"\", callback)\n}\n\nfunc (f *FakeYagnats) SubscribeWithQueue(subject, queue string, callback yagnats.Callback) (int, error) {\n\tf.counter++\n\tsubscription := yagnats.Subscription{\n\t\tSubject:  subject,\n\t\tQueue:    queue,\n\t\tID:       f.counter,\n\t\tCallback: callback,\n\t}\n\n\tf.Subscriptions[subject] = append(f.Subscriptions[subject], subscription)\n\n\treturn subscription.ID, f.SubscribeError\n}\n\nfunc (f *FakeYagnats) Unsubscribe(subscription int) error {\n\tf.Unsubscriptions = append(f.Unsubscriptions, subscription)\n\treturn f.UnsubscribeError\n}\n\nfunc (f *FakeYagnats) UnsubscribeAll(subject string) {\n\tf.UnsubscribedSubjects = append(f.UnsubscribedSubjects, subject)\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/rds\"\n\t\"github.com\/hashicorp\/terraform\/helper\/acctest\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nfunc TestAccAWSDBClusterParameterGroup_basic(t *testing.T) {\n\tvar v rds.DBClusterParameterGroup\n\n\tparameterGroupName := fmt.Sprintf(\"cluster-parameter-group-test-terraform-%d\", acctest.RandInt())\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSDBClusterParameterGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSDBClusterParameterGroupConfig(parameterGroupName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupExists(\"aws_rds_cluster_parameter_group.bar\", &v),\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupAttributes(&v),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"name\", parameterGroupName),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"family\", \"aurora5.6\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"description\", \"Test cluster parameter group for terraform\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.1708034931.name\", \"character_set_results\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.1708034931.value\", \"utf8\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2421266705.name\", \"character_set_server\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2421266705.value\", \"utf8\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2478663599.name\", \"character_set_client\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2478663599.value\", \"utf8\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"tags.%\", \"1\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tConfig: testAccAWSDBClusterParameterGroupAddParametersConfig(parameterGroupName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupExists(\"aws_rds_cluster_parameter_group.bar\", &v),\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupAttributes(&v),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"name\", parameterGroupName),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"family\", \"aurora5.6\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"description\", \"Test cluster parameter group for terraform\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.1706463059.name\", \"collation_connection\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.1706463059.value\", \"utf8_unicode_ci\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.1708034931.name\", \"character_set_results\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.1708034931.value\", \"utf8\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2421266705.name\", \"character_set_server\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2421266705.value\", \"utf8\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2475805061.name\", \"collation_server\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2475805061.value\", \"utf8_unicode_ci\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2478663599.name\", \"character_set_client\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2478663599.value\", \"utf8\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"tags.%\", \"2\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSDBClusterParameterGroup_disappears(t *testing.T) {\n\tvar v rds.DBClusterParameterGroup\n\n\tparameterGroupName := fmt.Sprintf(\"cluster-parameter-group-test-terraform-%d\", acctest.RandInt())\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSDBClusterParameterGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSDBClusterParameterGroupConfig(parameterGroupName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupExists(\"aws_rds_cluster_parameter_group.bar\", &v),\n\t\t\t\t\ttestAccAWSDBClusterParameterGroupDisappears(&v),\n\t\t\t\t),\n\t\t\t\tExpectNonEmptyPlan: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSDBClusterParameterGroupOnly(t *testing.T) {\n\tvar v rds.DBClusterParameterGroup\n\n\tparameterGroupName := fmt.Sprintf(\"cluster-parameter-group-test-tf-%d\", acctest.RandInt())\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSDBClusterParameterGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSDBClusterParameterGroupOnlyConfig(parameterGroupName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupExists(\"aws_rds_cluster_parameter_group.bar\", &v),\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupAttributes(&v),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"name\", parameterGroupName),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"family\", \"aurora5.6\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"description\", \"Managed by Terraform\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestResourceAWSDBClusterParameterGroupName_validation(t *testing.T) {\n\tcases := []struct {\n\t\tValue    string\n\t\tErrCount int\n\t}{\n\t\t{\n\t\t\tValue:    \"tEsting123\",\n\t\t\tErrCount: 1,\n\t\t},\n\t\t{\n\t\t\tValue:    \"testing123!\",\n\t\t\tErrCount: 1,\n\t\t},\n\t\t{\n\t\t\tValue:    \"1testing123\",\n\t\t\tErrCount: 1,\n\t\t},\n\t\t{\n\t\t\tValue:    \"testing--123\",\n\t\t\tErrCount: 1,\n\t\t},\n\t\t{\n\t\t\tValue:    \"testing123-\",\n\t\t\tErrCount: 1,\n\t\t},\n\t\t{\n\t\t\tValue:    randomString(256),\n\t\t\tErrCount: 1,\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\t_, errors := validateDbParamGroupName(tc.Value, \"aws_rds_cluster_parameter_group_name\")\n\n\t\tif len(errors) != tc.ErrCount {\n\t\t\tt.Fatal(\"Expected the DB Cluster Parameter Group Name to trigger a validation error\")\n\t\t}\n\t}\n}\n\nfunc testAccCheckAWSDBClusterParameterGroupDestroy(s *terraform.State) error {\n\tconn := testAccProvider.Meta().(*AWSClient).rdsconn\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_rds_cluster_parameter_group\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Try to find the Group\n\t\tresp, err := conn.DescribeDBClusterParameterGroups(\n\t\t\t&rds.DescribeDBClusterParameterGroupsInput{\n\t\t\t\tDBClusterParameterGroupName: aws.String(rs.Primary.ID),\n\t\t\t})\n\n\t\tif err == nil {\n\t\t\tif len(resp.DBClusterParameterGroups) != 0 &&\n\t\t\t\t*resp.DBClusterParameterGroups[0].DBClusterParameterGroupName == rs.Primary.ID {\n\t\t\t\treturn errors.New(\"DB Cluster Parameter Group still exists\")\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Verify the error\n\t\tnewerr, ok := err.(awserr.Error)\n\t\tif !ok {\n\t\t\treturn err\n\t\t}\n\t\tif newerr.Code() != \"DBParameterGroupNotFound\" {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc testAccCheckAWSDBClusterParameterGroupAttributes(v *rds.DBClusterParameterGroup) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\n\t\tif *v.DBClusterParameterGroupName != \"cluster-parameter-group-test-terraform\" {\n\t\t\treturn fmt.Errorf(\"bad name: %#v\", v.DBClusterParameterGroupName)\n\t\t}\n\n\t\tif *v.DBParameterGroupFamily != \"aurora5.6\" {\n\t\t\treturn fmt.Errorf(\"bad family: %#v\", v.DBParameterGroupFamily)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccAWSDBClusterParameterGroupDisappears(v *rds.DBClusterParameterGroup) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tconn := testAccProvider.Meta().(*AWSClient).rdsconn\n\t\topts := &rds.DeleteDBClusterParameterGroupInput{\n\t\t\tDBClusterParameterGroupName: v.DBClusterParameterGroupName,\n\t\t}\n\t\tif _, err := conn.DeleteDBClusterParameterGroup(opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn resource.Retry(40*time.Minute, func() *resource.RetryError {\n\t\t\topts := &rds.DescribeDBClusterParameterGroupsInput{\n\t\t\t\tDBClusterParameterGroupName: v.DBClusterParameterGroupName,\n\t\t\t}\n\t\t\t_, err := conn.DescribeDBClusterParameterGroups(opts)\n\t\t\tif err != nil {\n\t\t\t\tdbparamgrouperr, ok := err.(awserr.Error)\n\t\t\t\tif ok && dbparamgrouperr.Code() == \"DBParameterGroupNotFound\" {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn resource.NonRetryableError(\n\t\t\t\t\tfmt.Errorf(\"Error retrieving DB Cluster Parameter Groups: %s\", err))\n\t\t\t}\n\t\t\treturn resource.RetryableError(fmt.Errorf(\n\t\t\t\t\"Waiting for cluster parameter group to be deleted: %v\", v.DBClusterParameterGroupName))\n\t\t})\n\t}\n}\n\nfunc testAccCheckAWSDBClusterParameterGroupExists(n string, v *rds.DBClusterParameterGroup) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn errors.New(\"No DB Cluster Parameter Group ID is set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).rdsconn\n\n\t\topts := rds.DescribeDBClusterParameterGroupsInput{\n\t\t\tDBClusterParameterGroupName: aws.String(rs.Primary.ID),\n\t\t}\n\n\t\tresp, err := conn.DescribeDBClusterParameterGroups(&opts)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(resp.DBClusterParameterGroups) != 1 ||\n\t\t\t*resp.DBClusterParameterGroups[0].DBClusterParameterGroupName != rs.Primary.ID {\n\t\t\treturn errors.New(\"DB Cluster Parameter Group not found\")\n\t\t}\n\n\t\t*v = *resp.DBClusterParameterGroups[0]\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccAWSDBClusterParameterGroupConfig(name string) string {\n\treturn fmt.Sprintf(`\nresource \"aws_rds_cluster_parameter_group\" \"bar\" {\n  name        = \"%s\"\n  family      = \"aurora5.6\"\n  description = \"Test cluster parameter group for terraform\"\n\n  parameter {\n    name  = \"character_set_server\"\n    value = \"utf8\"\n  }\n\n  parameter {\n    name  = \"character_set_client\"\n    value = \"utf8\"\n  }\n\n  parameter {\n    name  = \"character_set_results\"\n    value = \"utf8\"\n  }\n\n  tags {\n    foo = \"bar\"\n  }\n}\n`, name)\n}\n\nfunc testAccAWSDBClusterParameterGroupAddParametersConfig(name string) string {\n\treturn fmt.Sprintf(`\nresource \"aws_rds_cluster_parameter_group\" \"bar\" {\n  name        = \"%s\"\n  family      = \"aurora5.6\"\n  description = \"Test cluster parameter group for terraform\"\n\n  parameter {\n    name  = \"character_set_server\"\n    value = \"utf8\"\n  }\n\n  parameter {\n    name  = \"character_set_client\"\n    value = \"utf8\"\n  }\n\n  parameter {\n    name  = \"character_set_results\"\n    value = \"utf8\"\n  }\n\n  parameter {\n    name  = \"collation_server\"\n    value = \"utf8_unicode_ci\"\n  }\n\n  parameter {\n    name  = \"collation_connection\"\n    value = \"utf8_unicode_ci\"\n  }\n\n  tags {\n    foo = \"bar\"\n    baz = \"foo\"\n  }\n}\n`, name)\n}\n\nfunc testAccAWSDBClusterParameterGroupOnlyConfig(name string) string {\n\treturn fmt.Sprintf(`resource \"aws_rds_cluster_parameter_group\" \"bar\" {\n  name        = \"%s\"\n  family      = \"aurora5.6\"\n}`, name)\n}\n<commit_msg>provider\/aws: Fix AWS RDS Cluster Parameter Group Tests<commit_after>package aws\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/rds\"\n\t\"github.com\/hashicorp\/terraform\/helper\/acctest\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nfunc TestAccAWSDBClusterParameterGroup_basic(t *testing.T) {\n\tvar v rds.DBClusterParameterGroup\n\n\tparameterGroupName := fmt.Sprintf(\"cluster-parameter-group-test-terraform-%d\", acctest.RandInt())\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSDBClusterParameterGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSDBClusterParameterGroupConfig(parameterGroupName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupExists(\"aws_rds_cluster_parameter_group.bar\", &v),\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupAttributes(&v, parameterGroupName),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"name\", parameterGroupName),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"family\", \"aurora5.6\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"description\", \"Test cluster parameter group for terraform\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.1708034931.name\", \"character_set_results\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.1708034931.value\", \"utf8\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2421266705.name\", \"character_set_server\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2421266705.value\", \"utf8\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2478663599.name\", \"character_set_client\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2478663599.value\", \"utf8\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"tags.%\", \"1\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tConfig: testAccAWSDBClusterParameterGroupAddParametersConfig(parameterGroupName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupExists(\"aws_rds_cluster_parameter_group.bar\", &v),\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupAttributes(&v, parameterGroupName),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"name\", parameterGroupName),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"family\", \"aurora5.6\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"description\", \"Test cluster parameter group for terraform\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.1706463059.name\", \"collation_connection\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.1706463059.value\", \"utf8_unicode_ci\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.1708034931.name\", \"character_set_results\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.1708034931.value\", \"utf8\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2421266705.name\", \"character_set_server\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2421266705.value\", \"utf8\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2475805061.name\", \"collation_server\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2475805061.value\", \"utf8_unicode_ci\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2478663599.name\", \"character_set_client\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"parameter.2478663599.value\", \"utf8\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"tags.%\", \"2\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSDBClusterParameterGroup_disappears(t *testing.T) {\n\tvar v rds.DBClusterParameterGroup\n\n\tparameterGroupName := fmt.Sprintf(\"cluster-parameter-group-test-terraform-%d\", acctest.RandInt())\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSDBClusterParameterGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSDBClusterParameterGroupConfig(parameterGroupName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupExists(\"aws_rds_cluster_parameter_group.bar\", &v),\n\t\t\t\t\ttestAccAWSDBClusterParameterGroupDisappears(&v),\n\t\t\t\t),\n\t\t\t\tExpectNonEmptyPlan: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSDBClusterParameterGroupOnly(t *testing.T) {\n\tvar v rds.DBClusterParameterGroup\n\n\tparameterGroupName := fmt.Sprintf(\"cluster-parameter-group-test-tf-%d\", acctest.RandInt())\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSDBClusterParameterGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSDBClusterParameterGroupOnlyConfig(parameterGroupName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupExists(\"aws_rds_cluster_parameter_group.bar\", &v),\n\t\t\t\t\ttestAccCheckAWSDBClusterParameterGroupAttributes(&v, parameterGroupName),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"name\", parameterGroupName),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"family\", \"aurora5.6\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_rds_cluster_parameter_group.bar\", \"description\", \"Managed by Terraform\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestResourceAWSDBClusterParameterGroupName_validation(t *testing.T) {\n\tcases := []struct {\n\t\tValue    string\n\t\tErrCount int\n\t}{\n\t\t{\n\t\t\tValue:    \"tEsting123\",\n\t\t\tErrCount: 1,\n\t\t},\n\t\t{\n\t\t\tValue:    \"testing123!\",\n\t\t\tErrCount: 1,\n\t\t},\n\t\t{\n\t\t\tValue:    \"1testing123\",\n\t\t\tErrCount: 1,\n\t\t},\n\t\t{\n\t\t\tValue:    \"testing--123\",\n\t\t\tErrCount: 1,\n\t\t},\n\t\t{\n\t\t\tValue:    \"testing123-\",\n\t\t\tErrCount: 1,\n\t\t},\n\t\t{\n\t\t\tValue:    randomString(256),\n\t\t\tErrCount: 1,\n\t\t},\n\t}\n\n\tfor _, tc := range cases {\n\t\t_, errors := validateDbParamGroupName(tc.Value, \"aws_rds_cluster_parameter_group_name\")\n\n\t\tif len(errors) != tc.ErrCount {\n\t\t\tt.Fatal(\"Expected the DB Cluster Parameter Group Name to trigger a validation error\")\n\t\t}\n\t}\n}\n\nfunc testAccCheckAWSDBClusterParameterGroupDestroy(s *terraform.State) error {\n\tconn := testAccProvider.Meta().(*AWSClient).rdsconn\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_rds_cluster_parameter_group\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Try to find the Group\n\t\tresp, err := conn.DescribeDBClusterParameterGroups(\n\t\t\t&rds.DescribeDBClusterParameterGroupsInput{\n\t\t\t\tDBClusterParameterGroupName: aws.String(rs.Primary.ID),\n\t\t\t})\n\n\t\tif err == nil {\n\t\t\tif len(resp.DBClusterParameterGroups) != 0 &&\n\t\t\t\t*resp.DBClusterParameterGroups[0].DBClusterParameterGroupName == rs.Primary.ID {\n\t\t\t\treturn errors.New(\"DB Cluster Parameter Group still exists\")\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Verify the error\n\t\tnewerr, ok := err.(awserr.Error)\n\t\tif !ok {\n\t\t\treturn err\n\t\t}\n\t\tif newerr.Code() != \"DBParameterGroupNotFound\" {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc testAccCheckAWSDBClusterParameterGroupAttributes(v *rds.DBClusterParameterGroup, name string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\n\t\tif *v.DBClusterParameterGroupName != name {\n\t\t\treturn fmt.Errorf(\"bad name: %#v expected: %v\", *v.DBClusterParameterGroupName, name)\n\t\t}\n\n\t\tif *v.DBParameterGroupFamily != \"aurora5.6\" {\n\t\t\treturn fmt.Errorf(\"bad family: %#v\", *v.DBParameterGroupFamily)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccAWSDBClusterParameterGroupDisappears(v *rds.DBClusterParameterGroup) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tconn := testAccProvider.Meta().(*AWSClient).rdsconn\n\t\topts := &rds.DeleteDBClusterParameterGroupInput{\n\t\t\tDBClusterParameterGroupName: v.DBClusterParameterGroupName,\n\t\t}\n\t\tif _, err := conn.DeleteDBClusterParameterGroup(opts); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn resource.Retry(40*time.Minute, func() *resource.RetryError {\n\t\t\topts := &rds.DescribeDBClusterParameterGroupsInput{\n\t\t\t\tDBClusterParameterGroupName: v.DBClusterParameterGroupName,\n\t\t\t}\n\t\t\t_, err := conn.DescribeDBClusterParameterGroups(opts)\n\t\t\tif err != nil {\n\t\t\t\tdbparamgrouperr, ok := err.(awserr.Error)\n\t\t\t\tif ok && dbparamgrouperr.Code() == \"DBParameterGroupNotFound\" {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn resource.NonRetryableError(\n\t\t\t\t\tfmt.Errorf(\"Error retrieving DB Cluster Parameter Groups: %s\", err))\n\t\t\t}\n\t\t\treturn resource.RetryableError(fmt.Errorf(\n\t\t\t\t\"Waiting for cluster parameter group to be deleted: %v\", v.DBClusterParameterGroupName))\n\t\t})\n\t}\n}\n\nfunc testAccCheckAWSDBClusterParameterGroupExists(n string, v *rds.DBClusterParameterGroup) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn errors.New(\"No DB Cluster Parameter Group ID is set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).rdsconn\n\n\t\topts := rds.DescribeDBClusterParameterGroupsInput{\n\t\t\tDBClusterParameterGroupName: aws.String(rs.Primary.ID),\n\t\t}\n\n\t\tresp, err := conn.DescribeDBClusterParameterGroups(&opts)\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(resp.DBClusterParameterGroups) != 1 ||\n\t\t\t*resp.DBClusterParameterGroups[0].DBClusterParameterGroupName != rs.Primary.ID {\n\t\t\treturn errors.New(\"DB Cluster Parameter Group not found\")\n\t\t}\n\n\t\t*v = *resp.DBClusterParameterGroups[0]\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccAWSDBClusterParameterGroupConfig(name string) string {\n\treturn fmt.Sprintf(`\nresource \"aws_rds_cluster_parameter_group\" \"bar\" {\n  name        = \"%s\"\n  family      = \"aurora5.6\"\n  description = \"Test cluster parameter group for terraform\"\n\n  parameter {\n    name  = \"character_set_server\"\n    value = \"utf8\"\n  }\n\n  parameter {\n    name  = \"character_set_client\"\n    value = \"utf8\"\n  }\n\n  parameter {\n    name  = \"character_set_results\"\n    value = \"utf8\"\n  }\n\n  tags {\n    foo = \"bar\"\n  }\n}\n`, name)\n}\n\nfunc testAccAWSDBClusterParameterGroupAddParametersConfig(name string) string {\n\treturn fmt.Sprintf(`\nresource \"aws_rds_cluster_parameter_group\" \"bar\" {\n  name        = \"%s\"\n  family      = \"aurora5.6\"\n  description = \"Test cluster parameter group for terraform\"\n\n  parameter {\n    name  = \"character_set_server\"\n    value = \"utf8\"\n  }\n\n  parameter {\n    name  = \"character_set_client\"\n    value = \"utf8\"\n  }\n\n  parameter {\n    name  = \"character_set_results\"\n    value = \"utf8\"\n  }\n\n  parameter {\n    name  = \"collation_server\"\n    value = \"utf8_unicode_ci\"\n  }\n\n  parameter {\n    name  = \"collation_connection\"\n    value = \"utf8_unicode_ci\"\n  }\n\n  tags {\n    foo = \"bar\"\n    baz = \"foo\"\n  }\n}\n`, name)\n}\n\nfunc testAccAWSDBClusterParameterGroupOnlyConfig(name string) string {\n\treturn fmt.Sprintf(`resource \"aws_rds_cluster_parameter_group\" \"bar\" {\n  name        = \"%s\"\n  family      = \"aurora5.6\"\n}`, name)\n}\n<|endoftext|>"}
{"text":"<commit_before>package emailnotifier\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\tsocialmodels \"socialapi\/models\"\n\t\"socialapi\/workers\/notification\/models\"\n\n\t\"github.com\/koding\/logging\"\n\t\"github.com\/koding\/rabbitmq\"\n\t\"github.com\/koding\/worker\"\n\t\"github.com\/robfig\/cron\"\n\t\"github.com\/sendgrid\/sendgrid-go\"\n\t\"github.com\/streadway\/amqp\"\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\nconst SCHEDULE = \"0 0 0 * * *\"\n\nvar cronJob *cron.Cron\n\nvar emailConfig = map[string]string{\n\tmodels.NotificationContent_TYPE_COMMENT: \"comment\",\n\tmodels.NotificationContent_TYPE_LIKE:    \"likeActivities\",\n\tmodels.NotificationContent_TYPE_FOLLOW:  \"followActions\",\n\tmodels.NotificationContent_TYPE_JOIN:    \"groupJoined\",\n\tmodels.NotificationContent_TYPE_LEAVE:   \"groupLeft\",\n\tmodels.NotificationContent_TYPE_MENTION: \"mention\",\n}\n\ntype Action func(*Controller, []byte) error\n\ntype Controller struct {\n\troutes   map[string]Action\n\tlog      logging.Logger\n\trmqConn  *amqp.Connection\n\tsettings *EmailSettings\n}\n\ntype EmailSettings struct {\n\tUsername string\n\tPassword string\n\tFromName string\n\tFromMail string\n}\n\nfunc (n *Controller) DefaultErrHandler(delivery amqp.Delivery, err error) bool {\n\tn.log.Error(\"an error occured: %s\", err)\n\tdelivery.Ack(false)\n\n\treturn false\n}\n\nfunc (n *Controller) HandleEvent(event string, data []byte) error {\n\tn.log.Debug(\"New Event Received %s\", event)\n\thandler, ok := n.routes[event]\n\tif !ok {\n\t\treturn worker.HandlerNotFoundErr\n\t}\n\n\treturn handler(n, data)\n}\n\nfunc New(rmq *rabbitmq.RabbitMQ, log logging.Logger, es *EmailSettings) (*Controller, error) {\n\trmqConn, err := rmq.Connect(\"NewEmailNotifierWorkerController\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnwc := &Controller{\n\t\tlog:      log,\n\t\trmqConn:  rmqConn.Conn(),\n\t\tsettings: es,\n\t}\n\n\troutes := map[string]Action{\n\t\t\"notification.notification_created\": (*Controller).SendInstantEmail,\n\t\t\"notification.notification_updated\": (*Controller).SendInstantEmail,\n\t}\n\n\tnwc.routes = routes\n\n\tnwc.initDailyEmailCron()\n\n\treturn nwc, nil\n}\n\nfunc (n *EmailNotifierWorkerController) initDailyEmailCron() {\n\n\tcronJob = cron.New()\n\tcronJob.AddFunc(SCHEDULE, n.sendDailyMails)\n\tcronJob.Start()\n}\n\nfunc (n *Controller) SendInstantEmail(data []byte) error {\n\tchannel, err := n.rmqConn.Channel()\n\tif err != nil {\n\t\treturn errors.New(\"channel connection error\")\n\t}\n\tdefer channel.Close()\n\n\tnotification := models.NewNotification()\n\tif err := notification.MapMessage(data); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ fetch latest activity for checking actor\n\tactivity, nc, err := notification.FetchLastActivity()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !validNotification(activity, notification) {\n\t\treturn nil\n\t}\n\n\tuc, err := fetchUserContact(notification.AccountId)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"an error occurred while fetching user contact: %s\", err)\n\t}\n\n\tif !checkMailSettings(uc, nc) {\n\t\treturn nil\n\t}\n\n\tcontainer, err := buildContainer(activity, nc, notification)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbody, err := renderTemplate(uc, container)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"an error occurred while preparing notification email: %s\", err)\n\t}\n\tsubject := prepareSubject(container)\n\n\tif err := createToken(uc, nc, container.Token); err != nil {\n\t\treturn err\n\t}\n\n\treturn n.SendMail(uc, body, subject)\n}\n\ntype UserContact struct {\n\tUserOldId     bson.ObjectId\n\tEmail         string\n\tFirstName     string\n\tLastName      string\n\tUsername      string\n\tHash          string\n\tToken         string\n\tEmailSettings map[string]bool\n}\n\nfunc validNotification(a *models.NotificationActivity, n *models.Notification) bool {\n\t\/\/ do not notify actor for her own action\n\tif a.ActorId == n.AccountId {\n\t\treturn false\n\t}\n\n\t\/\/ do not notify user when notification is not yet activated\n\treturn !n.ActivatedAt.IsZero()\n}\n\nfunc checkMailSettings(uc *UserContact, nc *models.NotificationContent) bool {\n\t\/\/ notifications are disabled\n\tif val := uc.EmailSettings[\"global\"]; !val {\n\t\treturn false\n\t}\n\n\t\/\/ daily notifications are enabled\n\tif val := uc.EmailSettings[\"daily\"]; val {\n\t\treturn false\n\t}\n\n\t\/\/ get config\n\treturn uc.EmailSettings[emailConfig[nc.TypeConstant]]\n}\n\nfunc buildContainer(a *models.NotificationActivity, nc *models.NotificationContent,\n\tn *models.Notification) (*NotificationContainer, error) {\n\n\t\/\/ if content type not valid return\n\tcontentType, err := nc.GetContentType()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontainer := &NotificationContainer{\n\t\tActivity:     a,\n\t\tContent:      nc,\n\t\tNotification: n,\n\t}\n\n\tcontainer.Token, err = generateToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ if notification target is related with an object (comment\/status update)\n\tif containsObject(nc) {\n\t\ttarget := socialmodels.NewChannelMessage()\n\t\tif err := target.ById(nc.TargetId); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"target message not found\")\n\t\t}\n\n\t\tprepareGroup(container, target)\n\t\tprepareSlug(container, target)\n\t\tprepareObjectType(container, target)\n\t\tcontainer.Message = fetchContentBody(nc, target)\n\t\tcontentType.SetActorId(target.AccountId)\n\t\tcontentType.SetListerId(n.AccountId)\n\t}\n\n\tcontainer.ActivityMessage = contentType.GetActivity()\n\n\treturn container, nil\n}\n\nfunc prepareGroup(container *NotificationContainer, cm *socialmodels.ChannelMessage) {\n\tc := socialmodels.NewChannel()\n\tif err := c.ById(cm.InitialChannelId); err != nil {\n\t\treturn\n\t}\n\t\/\/ TODO fix these Slug and Name\n\tcontainer.Group = GroupContent{\n\t\tSlug: c.GroupName,\n\t\tName: c.GroupName,\n\t}\n}\n\nfunc prepareSlug(container *NotificationContainer, cm *socialmodels.ChannelMessage) {\n\tswitch cm.TypeConstant {\n\tcase socialmodels.ChannelMessage_TYPE_POST:\n\t\tcontainer.Slug = cm.Slug\n\tcase socialmodels.ChannelMessage_TYPE_REPLY:\n\t\t\/\/ TODO we need append something like comment id to parent message slug\n\t\tcontainer.Slug = fetchRepliedMessage(cm.Id).Slug\n\t}\n}\n\nfunc prepareObjectType(container *NotificationContainer, cm *socialmodels.ChannelMessage) {\n\tswitch cm.TypeConstant {\n\tcase socialmodels.ChannelMessage_TYPE_POST:\n\t\tcontainer.ObjectType = \"status update\"\n\tcase socialmodels.ChannelMessage_TYPE_REPLY:\n\t\tcontainer.ObjectType = \"comment\"\n\t}\n}\n\n\/\/ fetchUserContact gets user and account details with given account id\nfunc fetchUserContact(accountId int64) (*UserContact, error) {\n\ta := socialmodels.NewAccount()\n\tif err := a.ById(accountId); err != nil {\n\t\treturn nil, err\n\t}\n\n\taccount, err := modelhelper.GetAccountById(a.OldId)\n\tif err != nil {\n\t\tif err == mgo.ErrNotFound {\n\t\t\treturn nil, errors.New(\"old account not found\")\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\tuser, err := modelhelper.GetUser(account.Profile.Nickname)\n\tif err != nil {\n\t\tif err == mgo.ErrNotFound {\n\t\t\treturn nil, errors.New(\"user not found\")\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\ttoken, err := generateToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuc := &UserContact{\n\t\tUserOldId:     user.ObjectId,\n\t\tEmail:         user.Email,\n\t\tFirstName:     account.Profile.FirstName,\n\t\tLastName:      account.Profile.LastName,\n\t\tUsername:      account.Profile.Nickname,\n\t\tHash:          account.Profile.Hash,\n\t\tEmailSettings: user.EmailFrequency,\n\t\tToken:         token,\n\t}\n\n\treturn uc, nil\n}\n\nfunc containsObject(nc *models.NotificationContent) bool {\n\treturn nc.TypeConstant == models.NotificationContent_TYPE_LIKE ||\n\t\tnc.TypeConstant == models.NotificationContent_TYPE_MENTION ||\n\t\tnc.TypeConstant == models.NotificationContent_TYPE_COMMENT\n}\n\nfunc fetchContentBody(nc *models.NotificationContent, cm *socialmodels.ChannelMessage) string {\n\n\tswitch nc.TypeConstant {\n\tcase models.NotificationContent_TYPE_LIKE:\n\t\treturn cm.Body\n\tcase models.NotificationContent_TYPE_MENTION:\n\t\treturn cm.Body\n\tcase models.NotificationContent_TYPE_COMMENT:\n\t\treturn fetchLastReplyBody(cm.Id)\n\t}\n\n\treturn \"\"\n}\n\nfunc fetchLastReplyBody(targetId int64) string {\n\tmr := socialmodels.NewMessageReply()\n\tmr.MessageId = targetId\n\tquery := socialmodels.NewQuery()\n\tquery.Limit = 1\n\tmessages, err := mr.List(query)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tif len(messages) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn messages[0].Body\n}\n\nfunc fetchRepliedMessage(replyId int64) *socialmodels.ChannelMessage {\n\tmr := socialmodels.NewMessageReply()\n\tmr.ReplyId = replyId\n\n\tparent, err := mr.FetchRepliedMessage()\n\tif err != nil {\n\t\tparent = socialmodels.NewChannelMessage()\n\t}\n\n\treturn parent\n}\n\nfunc (n *Controller) SendMail(uc *UserContact, body, subject string) error {\n\tes := n.settings\n\tsg := sendgrid.NewSendGridClient(es.Username, es.Password)\n\tfullname := fmt.Sprintf(\"%s %s\", uc.FirstName, uc.LastName)\n\n\tmessage := sendgrid.NewMail()\n\tmessage.AddTo(uc.Email)\n\tmessage.AddToName(fullname)\n\tmessage.SetSubject(subject)\n\tmessage.SetHTML(body)\n\tmessage.SetFrom(es.FromMail)\n\tmessage.SetFromName(es.FromName)\n\n\tif err := sg.Send(message); err != nil {\n\t\treturn fmt.Errorf(\"an error occurred while sending notification email to %s\", uc.Username)\n\t}\n\tn.log.Info(\"%s notified by email\", uc.Username)\n\n\treturn nil\n}\n<commit_msg>Notification: for building container notification parameter is replaced by accountId<commit_after>package emailnotifier\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\tsocialmodels \"socialapi\/models\"\n\t\"socialapi\/workers\/notification\/models\"\n\n\t\"github.com\/koding\/logging\"\n\t\"github.com\/koding\/rabbitmq\"\n\t\"github.com\/koding\/worker\"\n\t\"github.com\/robfig\/cron\"\n\t\"github.com\/sendgrid\/sendgrid-go\"\n\t\"github.com\/streadway\/amqp\"\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\nconst SCHEDULE = \"0 0 0 * * *\"\n\nvar cronJob *cron.Cron\n\nvar emailConfig = map[string]string{\n\tmodels.NotificationContent_TYPE_COMMENT: \"comment\",\n\tmodels.NotificationContent_TYPE_LIKE:    \"likeActivities\",\n\tmodels.NotificationContent_TYPE_FOLLOW:  \"followActions\",\n\tmodels.NotificationContent_TYPE_JOIN:    \"groupJoined\",\n\tmodels.NotificationContent_TYPE_LEAVE:   \"groupLeft\",\n\tmodels.NotificationContent_TYPE_MENTION: \"mention\",\n}\n\ntype Action func(*Controller, []byte) error\n\ntype Controller struct {\n\troutes   map[string]Action\n\tlog      logging.Logger\n\trmqConn  *amqp.Connection\n\tsettings *EmailSettings\n}\n\ntype EmailSettings struct {\n\tUsername string\n\tPassword string\n\tFromName string\n\tFromMail string\n}\n\nfunc (n *Controller) DefaultErrHandler(delivery amqp.Delivery, err error) bool {\n\tn.log.Error(\"an error occured: %s\", err)\n\tdelivery.Ack(false)\n\n\treturn false\n}\n\nfunc (n *Controller) HandleEvent(event string, data []byte) error {\n\tn.log.Debug(\"New Event Received %s\", event)\n\thandler, ok := n.routes[event]\n\tif !ok {\n\t\treturn worker.HandlerNotFoundErr\n\t}\n\n\treturn handler(n, data)\n}\n\nfunc New(rmq *rabbitmq.RabbitMQ, log logging.Logger, es *EmailSettings) (*Controller, error) {\n\trmqConn, err := rmq.Connect(\"NewEmailNotifierWorkerController\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnwc := &Controller{\n\t\tlog:      log,\n\t\trmqConn:  rmqConn.Conn(),\n\t\tsettings: es,\n\t}\n\n\troutes := map[string]Action{\n\t\t\"notification.notification_created\": (*Controller).SendInstantEmail,\n\t\t\"notification.notification_updated\": (*Controller).SendInstantEmail,\n\t}\n\n\tnwc.routes = routes\n\n\tnwc.initDailyEmailCron()\n\n\treturn nwc, nil\n}\n\nfunc (n *EmailNotifierWorkerController) initDailyEmailCron() {\n\n\tcronJob = cron.New()\n\tcronJob.AddFunc(SCHEDULE, n.sendDailyMails)\n\tcronJob.Start()\n}\n\nfunc (n *Controller) SendInstantEmail(data []byte) error {\n\tchannel, err := n.rmqConn.Channel()\n\tif err != nil {\n\t\treturn errors.New(\"channel connection error\")\n\t}\n\tdefer channel.Close()\n\n\tnotification := models.NewNotification()\n\tif err := notification.MapMessage(data); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ fetch latest activity for checking actor\n\tactivity, nc, err := notification.FetchLastActivity()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !validNotification(activity, notification) {\n\t\treturn nil\n\t}\n\n\tuc, err := fetchUserContact(notification.AccountId)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"an error occurred while fetching user contact: %s\", err)\n\t}\n\n\tif !checkMailSettings(uc, nc) {\n\t\treturn nil\n\t}\n\n\tcontainer, err := buildContainer(activity, nc, notification)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tbody, err := renderTemplate(uc, container)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"an error occurred while preparing notification email: %s\", err)\n\t}\n\tsubject := prepareSubject(container)\n\n\tif err := createToken(uc, nc, container.Token); err != nil {\n\t\treturn err\n\t}\n\n\treturn n.SendMail(uc, body, subject)\n}\n\ntype UserContact struct {\n\tAccountId     int64\n\tUserOldId     bson.ObjectId\n\tEmail         string\n\tFirstName     string\n\tLastName      string\n\tUsername      string\n\tHash          string\n\tToken         string\n\tEmailSettings map[string]bool\n}\n\nfunc validNotification(a *models.NotificationActivity, n *models.Notification) bool {\n\t\/\/ do not notify actor for her own action\n\tif a.ActorId == n.AccountId {\n\t\treturn false\n\t}\n\n\t\/\/ do not notify user when notification is not yet activated\n\treturn !n.ActivatedAt.IsZero()\n}\n\nfunc checkMailSettings(uc *UserContact, nc *models.NotificationContent) bool {\n\t\/\/ notifications are disabled\n\tif val := uc.EmailSettings[\"global\"]; !val {\n\t\treturn false\n\t}\n\n\t\/\/ daily notifications are enabled\n\tif val := uc.EmailSettings[\"daily\"]; val {\n\t\treturn false\n\t}\n\n\t\/\/ get config\n\treturn uc.EmailSettings[emailConfig[nc.TypeConstant]]\n}\n\nfunc buildContainer(accountId int64, a *models.NotificationActivity,\n\tnc *models.NotificationContent) (*NotificationContainer, error) {\n\n\t\/\/ if content type not valid return\n\tcontentType, err := nc.GetContentType()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcontainer := &NotificationContainer{\n\t\tActivity:  a,\n\t\tContent:   nc,\n\t\tAccountId: accountId,\n\t}\n\n\t\/\/ if notification target is related with an object (comment\/status update)\n\tif containsObject(nc) {\n\t\ttarget := socialmodels.NewChannelMessage()\n\t\tif err := target.ById(nc.TargetId); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"target message not found\")\n\t\t}\n\n\t\tprepareGroup(container, target)\n\t\tprepareSlug(container, target)\n\t\tprepareObjectType(container, target)\n\t\tcontainer.Message = fetchContentBody(nc, target)\n\t\tcontentType.SetActorId(target.AccountId)\n\t\tcontentType.SetListerId(accountId)\n\t}\n\n\tcontainer.ActivityMessage = contentType.GetActivity()\n\n\treturn container, nil\n}\n\nfunc prepareGroup(container *NotificationContainer, cm *socialmodels.ChannelMessage) {\n\tc := socialmodels.NewChannel()\n\tif err := c.ById(cm.InitialChannelId); err != nil {\n\t\treturn\n\t}\n\t\/\/ TODO fix these Slug and Name\n\tcontainer.Group = GroupContent{\n\t\tSlug: c.GroupName,\n\t\tName: c.GroupName,\n\t}\n}\n\nfunc prepareSlug(container *NotificationContainer, cm *socialmodels.ChannelMessage) {\n\tswitch cm.TypeConstant {\n\tcase socialmodels.ChannelMessage_TYPE_POST:\n\t\tcontainer.Slug = cm.Slug\n\tcase socialmodels.ChannelMessage_TYPE_REPLY:\n\t\t\/\/ TODO we need append something like comment id to parent message slug\n\t\tcontainer.Slug = fetchRepliedMessage(cm.Id).Slug\n\t}\n}\n\nfunc prepareObjectType(container *NotificationContainer, cm *socialmodels.ChannelMessage) {\n\tswitch cm.TypeConstant {\n\tcase socialmodels.ChannelMessage_TYPE_POST:\n\t\tcontainer.ObjectType = \"status update\"\n\tcase socialmodels.ChannelMessage_TYPE_REPLY:\n\t\tcontainer.ObjectType = \"comment\"\n\t}\n}\n\n\/\/ fetchUserContact gets user and account details with given account id\nfunc fetchUserContact(accountId int64) (*UserContact, error) {\n\ta := socialmodels.NewAccount()\n\tif err := a.ById(accountId); err != nil {\n\t\treturn nil, err\n\t}\n\n\taccount, err := modelhelper.GetAccountById(a.OldId)\n\tif err != nil {\n\t\tif err == mgo.ErrNotFound {\n\t\t\treturn nil, errors.New(\"old account not found\")\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\tuser, err := modelhelper.GetUser(account.Profile.Nickname)\n\tif err != nil {\n\t\tif err == mgo.ErrNotFound {\n\t\t\treturn nil, errors.New(\"user not found\")\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\ttoken, err := generateToken()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuc := &UserContact{\n\t\tAccountId:     accountId,\n\t\tUserOldId:     user.ObjectId,\n\t\tEmail:         user.Email,\n\t\tFirstName:     account.Profile.FirstName,\n\t\tLastName:      account.Profile.LastName,\n\t\tUsername:      account.Profile.Nickname,\n\t\tHash:          account.Profile.Hash,\n\t\tEmailSettings: user.EmailFrequency,\n\t\tToken:         token,\n\t}\n\n\treturn uc, nil\n}\n\nfunc containsObject(nc *models.NotificationContent) bool {\n\treturn nc.TypeConstant == models.NotificationContent_TYPE_LIKE ||\n\t\tnc.TypeConstant == models.NotificationContent_TYPE_MENTION ||\n\t\tnc.TypeConstant == models.NotificationContent_TYPE_COMMENT\n}\n\nfunc fetchContentBody(nc *models.NotificationContent, cm *socialmodels.ChannelMessage) string {\n\n\tswitch nc.TypeConstant {\n\tcase models.NotificationContent_TYPE_LIKE:\n\t\treturn cm.Body\n\tcase models.NotificationContent_TYPE_MENTION:\n\t\treturn cm.Body\n\tcase models.NotificationContent_TYPE_COMMENT:\n\t\treturn fetchLastReplyBody(cm.Id)\n\t}\n\n\treturn \"\"\n}\n\nfunc fetchLastReplyBody(targetId int64) string {\n\tmr := socialmodels.NewMessageReply()\n\tmr.MessageId = targetId\n\tquery := socialmodels.NewQuery()\n\tquery.Limit = 1\n\tmessages, err := mr.List(query)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tif len(messages) == 0 {\n\t\treturn \"\"\n\t}\n\n\treturn messages[0].Body\n}\n\nfunc fetchRepliedMessage(replyId int64) *socialmodels.ChannelMessage {\n\tmr := socialmodels.NewMessageReply()\n\tmr.ReplyId = replyId\n\n\tparent, err := mr.FetchRepliedMessage()\n\tif err != nil {\n\t\tparent = socialmodels.NewChannelMessage()\n\t}\n\n\treturn parent\n}\n\nfunc (n *Controller) SendMail(uc *UserContact, body, subject string) error {\n\tes := n.settings\n\tsg := sendgrid.NewSendGridClient(es.Username, es.Password)\n\tfullname := fmt.Sprintf(\"%s %s\", uc.FirstName, uc.LastName)\n\n\tmessage := sendgrid.NewMail()\n\tmessage.AddTo(uc.Email)\n\tmessage.AddToName(fullname)\n\tmessage.SetSubject(subject)\n\tmessage.SetHTML(body)\n\tmessage.SetFrom(es.FromMail)\n\tmessage.SetFromName(es.FromName)\n\n\tif err := sg.Send(message); err != nil {\n\t\treturn fmt.Errorf(\"an error occurred while sending notification email to %s\", uc.Username)\n\t}\n\tn.log.Info(\"%s notified by email\", uc.Username)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package CompilationEngine\n\nimport \"..\/JackTokenizer\"\n\ntype Node struct {\n\tType, Value string\n\tTerminal    bool\n\tParent      *Node\n\tChildren    []*Node\n}\n\nfunc CompilationEngine(tokens []JackTokenizer.Token) *Node {\n\ttopNode := &Node{\n\t\tType: \"class\",\n\t}\n\tcurrentNode := topNode\n\n\twrapNextInExpression := false\n\twrapNextInTerm := false\n\n\tunaryOpLevel := 0\n\n\tinStatements := func() {\n\t\tif currentNode.Type != \"statements\" {\n\t\t\tcurrentNode = childNode(currentNode, \"statements\")\n\t\t}\n\t}\n\n\tfor _, token := range tokens {\n\n\t\tif wrapNextInTerm {\n\t\t\tcurrentNode = childNode(currentNode, \"term\")\n\t\t\twrapNextInTerm = false\n\t\t}\n\n\t\tswitch token.Raw {\n\t\tcase \"{\":\n\t\t\tswitch currentNode.Type {\n\t\t\tcase \"subroutineDec\":\n\t\t\t\tcurrentNode = childNode(currentNode, \"subroutineBody\")\n\t\t\t}\n\t\tcase \"}\":\n\t\t\tif currentNode.Type == \"statements\" && currentNode.Parent.Type == \"subroutineBody\" {\n\t\t\t\tcurrentNode = currentNode.Parent\n\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tcurrentNode = currentNode.Parent\n\n\t\t\t} else if currentNode.Type == \"class\" {\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t} else {\n\n\t\t\t\tif currentNode.Type == \"subroutineDec\" || (currentNode.Parent != nil && (currentNode.Parent.Type == \"whileStatement\" || currentNode.Parent.Type == \"ifStatement\")) {\n\t\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\t}\n\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\tcurrentNode = currentNode.Parent\n\n\t\t\t\tif currentNode.Type == \"subroutineDec\" {\n\t\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tcontinue\n\t\tcase \"(\":\n\t\t\tinsertToken(token, currentNode, true)\n\t\t\twrapNextInExpression = true\n\n\t\t\tif currentNode.Type != \"whileStatement\" && currentNode.Type != \"ifStatement\" && !(currentNode.Type == \"term\" && currentNode.Parent.Parent.Type != \"letStatement\") {\n\t\t\t\tnodeType := \"expressionList\"\n\t\t\t\tif currentNode.Type == \"subroutineDec\" {\n\t\t\t\t\tnodeType = \"parameterList\"\n\t\t\t\t\twrapNextInExpression = false\n\t\t\t\t}\n\n\t\t\t\tcurrentNode = childNode(currentNode, nodeType)\n\t\t\t}\n\t\t\tcontinue\n\t\tcase \")\":\n\t\t\twrapNextInExpression = false\n\t\t\tcurrentNode = currentNode.Parent\n\n\t\t\tif unaryOpLevel != 0 && currentNode.Parent.Parent.Type != \"term\" {\n\t\t\t\tfor ; unaryOpLevel > 0; unaryOpLevel = unaryOpLevel - 1 {\n\t\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tif currentNode.Type == \"expression\" {\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tif currentNode.Type == \"expressionList\" || currentNode.Type == \"parameterList\" {\n\t\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"[\":\n\t\t\tinsertToken(token, currentNode, true)\n\t\t\twrapNextInExpression = true\n\t\t\tcontinue\n\t\tcase \"]\":\n\t\t\twrapNextInExpression = false\n\t\t\tcurrentNode = currentNode.Parent\n\n\t\t\tif currentNode.Type == \"expression\" {\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t}\n\t\tcase \"=\":\n\t\t\tif currentNode.Type != \"term\" {\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\tcurrentNode = childNode(currentNode, \"expression\")\n\t\t\t} else {\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\twrapNextInTerm = true\n\t\t\t}\n\t\t\tcontinue\n\n\t\tcase \",\":\n\t\t\tif currentNode.Type == \"term\" {\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\twrapNextInExpression = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase \";\":\n\t\t\tswitch currentNode.Type {\n\t\t\tcase \"term\":\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\tcase \"returnStatement\":\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\twrapNextInExpression = false\n\t\t\tdefault:\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t}\n\t\t\tcontinue\n\t\tcase \"-\", \"~\":\n\t\t\twrapNextInTerm = true\n\t\t\tunaryOpLevel = unaryOpLevel + 1\n\t\tcase \"method\", \"function\", \"constructor\":\n\t\t\tcurrentNode = childNode(currentNode, \"subroutineDec\")\n\t\tcase \"if\":\n\t\t\tinStatements()\n\t\t\tcurrentNode = childNode(currentNode, \"ifStatement\")\n\t\tcase \"var\":\n\t\t\tcurrentNode = childNode(currentNode, \"varDec\")\n\t\tcase \"let\":\n\t\t\tinStatements()\n\t\t\tcurrentNode = childNode(currentNode, \"letStatement\")\n\t\tcase \"do\":\n\t\t\tinStatements()\n\t\t\tcurrentNode = childNode(currentNode, \"doStatement\")\n\t\tcase \"return\":\n\t\t\tinStatements()\n\t\t\tcurrentNode = childNode(currentNode, \"returnStatement\")\n\t\t\twrapNextInExpression = true\n\t\t\tinsertToken(token, currentNode, true)\n\t\t\tcontinue\n\t\tcase \"while\":\n\t\t\tinStatements()\n\t\t\tcurrentNode = childNode(currentNode, \"whileStatement\")\n\t\tcase \"field\":\n\t\t\tcurrentNode = childNode(currentNode, \"classVarDec\")\n\t\t}\n\n\t\tif wrapNextInExpression {\n\t\t\tcurrentNode = childNode(currentNode, \"expression\")\n\t\t\twrapNextInExpression = false\n\t\t}\n\n\t\tif currentNode.Type == \"expression\" {\n\t\t\tcurrentNode = childNode(currentNode, \"term\")\n\t\t} else if currentNode.Type == \"term\" && (token.Raw == \"<\" || token.Raw == \"+\" || token.Raw == \"\/\") {\n\t\t\tcurrentNode = currentNode.Parent\n\t\t}\n\n\t\tinsertToken(token, currentNode, true)\n\n\t}\n\n\treturn topNode\n}\n\nfunc insertToken(token JackTokenizer.Token, node *Node, Terminal bool) {\n\tnode.Children = append(node.Children, &Node{\n\t\tType:     token.TokenType,\n\t\tValue:    token.Raw,\n\t\tTerminal: Terminal,\n\t\tParent:   node,\n\t})\n}\n\nfunc childNode(parent *Node, Type string) *Node {\n\tchild := &Node{\n\t\tType:   Type,\n\t\tParent: parent,\n\t}\n\tparent.Children = append(parent.Children, child)\n\treturn child\n}\n<commit_msg>Compiler now successfully generates AST + write XML for Square\/Squar.jack this completes chapter 10<commit_after>package CompilationEngine\n\nimport \"..\/JackTokenizer\"\n\ntype Node struct {\n\tType, Value string\n\tTerminal    bool\n\tParent      *Node\n\tChildren    []*Node\n}\n\nfunc CompilationEngine(tokens []JackTokenizer.Token) *Node {\n\ttopNode := &Node{\n\t\tType: \"class\",\n\t}\n\tcurrentNode := topNode\n\n\twrapNextInExpression := false\n\twrapNextInTerm := false\n\n\tunaryOpLevel := 0\n\n\tinStatements := func() {\n\t\tif currentNode.Type != \"statements\" {\n\t\t\tcurrentNode = childNode(currentNode, \"statements\")\n\t\t}\n\t}\n\n\tfor index, token := range tokens {\n\n\t\tif wrapNextInTerm {\n\t\t\tcurrentNode = childNode(currentNode, \"term\")\n\t\t\twrapNextInTerm = false\n\t\t}\n\n\t\tswitch token.Raw {\n\t\tcase \"{\":\n\t\t\tswitch currentNode.Type {\n\t\t\tcase \"subroutineDec\":\n\t\t\t\tcurrentNode = childNode(currentNode, \"subroutineBody\")\n\t\t\t}\n\t\tcase \"}\":\n\t\t\tif currentNode.Type == \"statements\" && currentNode.Parent.Type == \"subroutineBody\" {\n\t\t\t\tcurrentNode = currentNode.Parent\n\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tcurrentNode = currentNode.Parent\n\n\t\t\t} else if currentNode.Type == \"class\" {\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t} else {\n\n\t\t\t\tif currentNode.Type == \"subroutineDec\" || (currentNode.Parent != nil && (currentNode.Parent.Type == \"whileStatement\" || currentNode.Parent.Type == \"ifStatement\")) {\n\t\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\t}\n\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\tcurrentNode = currentNode.Parent\n\n\t\t\t\tif currentNode.Type == \"subroutineDec\" {\n\t\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tcontinue\n\t\tcase \"(\":\n\t\t\tif wrapNextInExpression {\n\t\t\t\tcurrentNode = childNode(currentNode, \"expression\")\n\t\t\t\tcurrentNode = childNode(currentNode, \"term\")\n\t\t\t}\n\n\t\t\tinsertToken(token, currentNode, true)\n\t\t\twrapNextInExpression = true\n\n\t\t\tif currentNode.Type != \"whileStatement\" && currentNode.Type != \"ifStatement\" && !(currentNode.Type == \"term\" && currentNode.Parent.Parent.Type != \"letStatement\") {\n\t\t\t\tnodeType := \"expressionList\"\n\t\t\t\tif currentNode.Type == \"subroutineDec\" {\n\t\t\t\t\tnodeType = \"parameterList\"\n\t\t\t\t\twrapNextInExpression = false\n\t\t\t\t}\n\n\t\t\t\tcurrentNode = childNode(currentNode, nodeType)\n\t\t\t}\n\t\t\tcontinue\n\t\tcase \")\":\n\t\t\twrapNextInExpression = false\n\t\t\tcurrentNode = currentNode.Parent\n\n\t\t\tif unaryOpLevel != 0 && currentNode.Parent.Parent.Type != \"term\" {\n\t\t\t\tfor ; unaryOpLevel > 0; unaryOpLevel = unaryOpLevel - 1 {\n\t\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif currentNode.Type == \"expression\" {\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t}\n\t\t\tif currentNode.Type == \"expressionList\" || currentNode.Type == \"parameterList\" {\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t}\n\n\t\tcase \"[\":\n\t\t\tinsertToken(token, currentNode, true)\n\t\t\twrapNextInExpression = true\n\t\t\tcontinue\n\t\tcase \"]\":\n\t\t\twrapNextInExpression = false\n\t\t\tcurrentNode = currentNode.Parent\n\n\t\t\tif currentNode.Type == \"expression\" {\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t}\n\t\tcase \"=\":\n\t\t\tif currentNode.Type != \"term\" {\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\tcurrentNode = childNode(currentNode, \"expression\")\n\t\t\t} else {\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\twrapNextInTerm = true\n\t\t\t}\n\t\t\tcontinue\n\t\tcase \"&\":\n\t\t\tif len(tokens) > index && tokens[index+1].Raw != \"&\" {\n\t\t\t\twrapNextInTerm = true\n\t\t\t}\n\t\tcase \",\":\n\t\t\tif currentNode.Type == \"term\" {\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\twrapNextInExpression = true\n\t\t\t\tcontinue\n\t\t\t}\n\t\tcase \";\":\n\t\t\tunaryOpLevel = 0\n\t\t\tswitch currentNode.Type {\n\t\t\tcase \"term\":\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\tcase \"returnStatement\":\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t\twrapNextInExpression = false\n\t\t\tdefault:\n\t\t\t\tinsertToken(token, currentNode, true)\n\t\t\t\tcurrentNode = currentNode.Parent\n\t\t\t}\n\t\t\tcontinue\n\t\tcase \"-\", \"~\":\n\t\t\twrapNextInTerm = true\n\t\t\tunaryOpLevel = unaryOpLevel + 1\n\t\tcase \"method\", \"function\", \"constructor\":\n\t\t\tcurrentNode = childNode(currentNode, \"subroutineDec\")\n\t\tcase \"if\":\n\t\t\tinStatements()\n\t\t\tcurrentNode = childNode(currentNode, \"ifStatement\")\n\t\tcase \"var\":\n\t\t\tcurrentNode = childNode(currentNode, \"varDec\")\n\t\tcase \"let\":\n\t\t\tinStatements()\n\t\t\tcurrentNode = childNode(currentNode, \"letStatement\")\n\t\tcase \"do\":\n\t\t\tinStatements()\n\t\t\tcurrentNode = childNode(currentNode, \"doStatement\")\n\t\tcase \"return\":\n\t\t\tinStatements()\n\t\t\tcurrentNode = childNode(currentNode, \"returnStatement\")\n\t\t\twrapNextInExpression = true\n\t\t\tinsertToken(token, currentNode, true)\n\t\t\tcontinue\n\t\tcase \"while\":\n\t\t\tinStatements()\n\t\t\tcurrentNode = childNode(currentNode, \"whileStatement\")\n\t\tcase \"field\":\n\t\t\tcurrentNode = childNode(currentNode, \"classVarDec\")\n\t\t}\n\n\t\tif wrapNextInExpression {\n\t\t\tcurrentNode = childNode(currentNode, \"expression\")\n\t\t\twrapNextInExpression = false\n\t\t}\n\n\t\tif currentNode.Type == \"expression\" {\n\t\t\tcurrentNode = childNode(currentNode, \"term\")\n\t\t} else if currentNode.Type == \"term\" && (token.Raw == \"<\" || token.Raw == \"+\" || token.Raw == \"\/\" || token.Raw == \"&\" || token.Raw == \">\" || token.Raw == \"-\") {\n\t\t\tcurrentNode = currentNode.Parent\n\t\t}\n\n\t\tinsertToken(token, currentNode, true)\n\n\t}\n\n\treturn topNode\n}\n\nfunc insertToken(token JackTokenizer.Token, node *Node, Terminal bool) {\n\tnode.Children = append(node.Children, &Node{\n\t\tType:     token.TokenType,\n\t\tValue:    token.Raw,\n\t\tTerminal: Terminal,\n\t\tParent:   node,\n\t})\n}\n\nfunc childNode(parent *Node, Type string) *Node {\n\tchild := &Node{\n\t\tType:   Type,\n\t\tParent: parent,\n\t}\n\tparent.Children = append(parent.Children, child)\n\treturn child\n}\n<|endoftext|>"}
{"text":"<commit_before>package ctxutil\n\nimport (\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ LogFromContext extracts a long from a context.Context\nfunc LogFromContext(ctx context.Context) *logrus.Entry {\n\tv := ctx.Value(\"log\")\n\n\tswitch v.(type) {\n\tcase *logrus.Entry:\n\t\treturn v.(*logrus.Entry)\n\tdefault:\n\t\tlogger := logrus.New()\n\t\tlog := logrus.NewEntry(logger)\n\t\treturn log\n\t}\n}\n<commit_msg>add context string extractor<commit_after>package ctxutil\n\nimport (\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ LogFromContext extracts a log from a context.Context\nfunc LogFromContext(ctx context.Context) *logrus.Entry {\n\tv := ctx.Value(\"log\")\n\n\tswitch v.(type) {\n\tcase *logrus.Entry:\n\t\treturn v.(*logrus.Entry)\n\tdefault:\n\t\tlogger := logrus.New()\n\t\tlog := logrus.NewEntry(logger)\n\t\treturn log\n\t}\n}\n\n\/\/ StringFromContext extracts a string from a context.Context\nfunc StringFromContext(ctx context.Context, key string) string {\n\ts := ctx.Value(key)\n\n\tswitch s.(type) {\n\tcase string:\n\t\treturn s.(string)\n\tdefault:\n\t\tlog := LogFromContext(ctx)\n\t\tlog.WithField(\"key\", key).Warn(\"context key was not present\")\n\t\treturn \"\"\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2010 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage html\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc pipeErr(err error) io.Reader {\n\tpr, pw := io.Pipe()\n\tpw.CloseWithError(err)\n\treturn pr\n}\n\nfunc readDat(filename string, c chan io.Reader) {\n\tdefer close(c)\n\tf, err := os.Open(\"testdata\/webkit\/\" + filename)\n\tif err != nil {\n\t\tc <- pipeErr(err)\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\t\/\/ Loop through the lines of the file. Each line beginning with \"#\" denotes\n\t\/\/ a new section, which is returned as a separate io.Reader.\n\tr := bufio.NewReader(f)\n\tvar pw *io.PipeWriter\n\tfor {\n\t\tline, err := r.ReadSlice('\\n')\n\t\tif err != nil {\n\t\t\tif pw != nil {\n\t\t\t\tpw.CloseWithError(err)\n\t\t\t\tpw = nil\n\t\t\t} else {\n\t\t\t\tc <- pipeErr(err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tif line[0] == '#' {\n\t\t\tif pw != nil {\n\t\t\t\tpw.Close()\n\t\t\t}\n\t\t\tvar pr *io.PipeReader\n\t\t\tpr, pw = io.Pipe()\n\t\t\tc <- pr\n\t\t\tcontinue\n\t\t}\n\t\tif line[0] != '|' {\n\t\t\t\/\/ Strip the trailing '\\n'.\n\t\t\tline = line[:len(line)-1]\n\t\t}\n\t\tif pw != nil {\n\t\t\tif _, err := pw.Write(line); err != nil {\n\t\t\t\tpw.CloseWithError(err)\n\t\t\t\tpw = nil\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc dumpIndent(w io.Writer, level int) {\n\tio.WriteString(w, \"| \")\n\tfor i := 0; i < level; i++ {\n\t\tio.WriteString(w, \"  \")\n\t}\n}\n\nfunc dumpLevel(w io.Writer, n *Node, level int) error {\n\tdumpIndent(w, level)\n\tswitch n.Type {\n\tcase ErrorNode:\n\t\treturn errors.New(\"unexpected ErrorNode\")\n\tcase DocumentNode:\n\t\treturn errors.New(\"unexpected DocumentNode\")\n\tcase ElementNode:\n\t\tfmt.Fprintf(w, \"<%s>\", n.Data)\n\t\tfor _, a := range n.Attr {\n\t\t\tio.WriteString(w, \"\\n\")\n\t\t\tdumpIndent(w, level+1)\n\t\t\tfmt.Fprintf(w, `%s=\"%s\"`, a.Key, a.Val)\n\t\t}\n\tcase TextNode:\n\t\tfmt.Fprintf(w, \"%q\", n.Data)\n\tcase CommentNode:\n\t\tfmt.Fprintf(w, \"<!-- %s -->\", n.Data)\n\tcase DoctypeNode:\n\t\tfmt.Fprintf(w, \"<!DOCTYPE %s>\", n.Data)\n\tcase scopeMarkerNode:\n\t\treturn errors.New(\"unexpected scopeMarkerNode\")\n\tdefault:\n\t\treturn errors.New(\"unknown node type\")\n\t}\n\tio.WriteString(w, \"\\n\")\n\tfor _, c := range n.Child {\n\t\tif err := dumpLevel(w, c, level+1); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc dump(n *Node) (string, error) {\n\tif n == nil || len(n.Child) == 0 {\n\t\treturn \"\", nil\n\t}\n\tb := bytes.NewBuffer(nil)\n\tfor _, child := range n.Child {\n\t\tif err := dumpLevel(b, child, 0); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\treturn b.String(), nil\n}\n\nfunc TestParser(t *testing.T) {\n\ttestFiles := []struct {\n\t\tfilename string\n\t\t\/\/ n is the number of test cases to run from that file.\n\t\t\/\/ -1 means all test cases.\n\t\tn int\n\t}{\n\t\t\/\/ TODO(nigeltao): Process all the test cases from all the .dat files.\n\t\t{\"tests1.dat\", -1},\n\t\t{\"tests2.dat\", 43},\n\t\t{\"tests3.dat\", 0},\n\t}\n\tfor _, tf := range testFiles {\n\t\trc := make(chan io.Reader)\n\t\tgo readDat(tf.filename, rc)\n\t\tfor i := 0; i != tf.n; i++ {\n\t\t\t\/\/ Parse the #data section.\n\t\t\tdataReader := <-rc\n\t\t\tif dataReader == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tb, err := ioutil.ReadAll(dataReader)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\ttext := string(b)\n\t\t\tdoc, err := Parse(strings.NewReader(text))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tgot, err := dump(doc)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\t\/\/ Skip the #error section.\n\t\t\tif _, err := io.Copy(ioutil.Discard, <-rc); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\t\/\/ Compare the parsed tree to the #document section.\n\t\t\tb, err = ioutil.ReadAll(<-rc)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tif want := string(b); got != want {\n\t\t\t\tt.Errorf(\"%s test #%d %q, got vs want:\\n----\\n%s----\\n%s----\", tf.filename, i, text, got, want)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif renderTestBlacklist[text] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ Check that rendering and re-parsing results in an identical tree.\n\t\t\tpr, pw := io.Pipe()\n\t\t\tgo func() {\n\t\t\t\tpw.CloseWithError(Render(pw, doc))\n\t\t\t}()\n\t\t\tdoc1, err := Parse(pr)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tgot1, err := dump(doc1)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tif got != got1 {\n\t\t\t\tt.Errorf(\"%s test #%d %q, got vs got1:\\n----\\n%s----\\n%s----\", tf.filename, i, text, got, got1)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t\/\/ Drain any untested cases for the test file.\n\t\tfor r := range rc {\n\t\t\tif _, err := ioutil.ReadAll(r); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Some test input result in parse trees are not 'well-formed' despite\n\/\/ following the HTML5 recovery algorithms. Rendering and re-parsing such a\n\/\/ tree will not result in an exact clone of that tree. We blacklist such\n\/\/ inputs from the render test.\nvar renderTestBlacklist = map[string]bool{\n\t\/\/ The second <a> will be reparented to the first <table>'s parent. This\n\t\/\/ results in an <a> whose parent is an <a>, which is not 'well-formed'.\n\t`<a><table><td><a><table><\/table><a><\/tr><a><\/table><b>X<\/b>C<a>Y`: true,\n\t\/\/ More cases of <a> being reparented:\n\t`<a href=\"blah\">aba<table><a href=\"foo\">br<tr><td><\/td><\/tr>x<\/table>aoe`: true,\n\t`<a><table><a><\/table><p><a><div><a>`:                                     true,\n\t`<a><table><td><a><table><\/table><a><\/tr><a><\/table><a>`:                  true,\n\t\/\/ A <plaintext> element is reparented, putting it before a table.\n\t\/\/ A <plaintext> element can't have anything after it in HTML.\n\t`<table><plaintext><td>`: true,\n}\n<commit_msg>html: refactor parse test infrastructure<commit_after>\/\/ Copyright 2010 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage html\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\/\/ readParseTest reads a single test case from r.\nfunc readParseTest(r *bufio.Reader) (text, want string, err error) {\n\tline, err := r.ReadSlice('\\n')\n\tif err != nil {\n\t\treturn \"\", \"\", err\n\t}\n\tvar b []byte\n\n\t\/\/ Read the HTML.\n\tif string(line) != \"#data\\n\" {\n\t\treturn \"\", \"\", fmt.Errorf(`got %q want \"#data\\n\"`, line)\n\t}\n\tfor {\n\t\tline, err = r.ReadSlice('\\n')\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\tif line[0] == '#' {\n\t\t\tbreak\n\t\t}\n\t\tb = append(b, line...)\n\t}\n\ttext = strings.TrimRight(string(b), \"\\n\")\n\tb = b[:0]\n\n\t\/\/ Skip the error list.\n\tif string(line) != \"#errors\\n\" {\n\t\treturn \"\", \"\", fmt.Errorf(`got %q want \"#errors\\n\"`, line)\n\t}\n\tfor {\n\t\tline, err = r.ReadSlice('\\n')\n\t\tif err != nil {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\tif line[0] == '#' {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/ Read the dump of what the parse tree should be.\n\tif string(line) != \"#document\\n\" {\n\t\treturn \"\", \"\", fmt.Errorf(`got %q want \"#document\\n\"`, line)\n\t}\n\tfor {\n\t\tline, err = r.ReadSlice('\\n')\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn \"\", \"\", err\n\t\t}\n\t\tif len(line) == 0 || len(line) == 1 && line[0] == '\\n' {\n\t\t\tbreak\n\t\t}\n\t\tb = append(b, line...)\n\t}\n\treturn text, string(b), nil\n}\n\nfunc dumpIndent(w io.Writer, level int) {\n\tio.WriteString(w, \"| \")\n\tfor i := 0; i < level; i++ {\n\t\tio.WriteString(w, \"  \")\n\t}\n}\n\nfunc dumpLevel(w io.Writer, n *Node, level int) error {\n\tdumpIndent(w, level)\n\tswitch n.Type {\n\tcase ErrorNode:\n\t\treturn errors.New(\"unexpected ErrorNode\")\n\tcase DocumentNode:\n\t\treturn errors.New(\"unexpected DocumentNode\")\n\tcase ElementNode:\n\t\tfmt.Fprintf(w, \"<%s>\", n.Data)\n\t\tfor _, a := range n.Attr {\n\t\t\tio.WriteString(w, \"\\n\")\n\t\t\tdumpIndent(w, level+1)\n\t\t\tfmt.Fprintf(w, `%s=\"%s\"`, a.Key, a.Val)\n\t\t}\n\tcase TextNode:\n\t\tfmt.Fprintf(w, `\"%s\"`, n.Data)\n\tcase CommentNode:\n\t\tfmt.Fprintf(w, \"<!-- %s -->\", n.Data)\n\tcase DoctypeNode:\n\t\tfmt.Fprintf(w, \"<!DOCTYPE %s>\", n.Data)\n\tcase scopeMarkerNode:\n\t\treturn errors.New(\"unexpected scopeMarkerNode\")\n\tdefault:\n\t\treturn errors.New(\"unknown node type\")\n\t}\n\tio.WriteString(w, \"\\n\")\n\tfor _, c := range n.Child {\n\t\tif err := dumpLevel(w, c, level+1); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc dump(n *Node) (string, error) {\n\tif n == nil || len(n.Child) == 0 {\n\t\treturn \"\", nil\n\t}\n\tb := bytes.NewBuffer(nil)\n\tfor _, child := range n.Child {\n\t\tif err := dumpLevel(b, child, 0); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\treturn b.String(), nil\n}\n\nfunc TestParser(t *testing.T) {\n\ttestFiles := []struct {\n\t\tfilename string\n\t\t\/\/ n is the number of test cases to run from that file.\n\t\t\/\/ -1 means all test cases.\n\t\tn int\n\t}{\n\t\t\/\/ TODO(nigeltao): Process all the test cases from all the .dat files.\n\t\t{\"tests1.dat\", -1},\n\t\t{\"tests2.dat\", 47},\n\t\t{\"tests3.dat\", 0},\n\t}\n\tfor _, tf := range testFiles {\n\t\tf, err := os.Open(\"testdata\/webkit\/\" + tf.filename)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer f.Close()\n\t\tr := bufio.NewReader(f)\n\t\tfor i := 0; i != tf.n; i++ {\n\t\t\ttext, want, err := readParseTest(r)\n\t\t\tif err == io.EOF && tf.n == -1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tdoc, err := Parse(strings.NewReader(text))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tgot, err := dump(doc)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\t\/\/ Compare the parsed tree to the #document section.\n\t\t\tif got != want {\n\t\t\t\tt.Errorf(\"%s test #%d %q, got vs want:\\n----\\n%s----\\n%s----\", tf.filename, i, text, got, want)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif renderTestBlacklist[text] {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ Check that rendering and re-parsing results in an identical tree.\n\t\t\tpr, pw := io.Pipe()\n\t\t\tgo func() {\n\t\t\t\tpw.CloseWithError(Render(pw, doc))\n\t\t\t}()\n\t\t\tdoc1, err := Parse(pr)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tgot1, err := dump(doc1)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\tif got != got1 {\n\t\t\t\tt.Errorf(\"%s test #%d %q, got vs got1:\\n----\\n%s----\\n%s----\", tf.filename, i, text, got, got1)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Some test input result in parse trees are not 'well-formed' despite\n\/\/ following the HTML5 recovery algorithms. Rendering and re-parsing such a\n\/\/ tree will not result in an exact clone of that tree. We blacklist such\n\/\/ inputs from the render test.\nvar renderTestBlacklist = map[string]bool{\n\t\/\/ The second <a> will be reparented to the first <table>'s parent. This\n\t\/\/ results in an <a> whose parent is an <a>, which is not 'well-formed'.\n\t`<a><table><td><a><table><\/table><a><\/tr><a><\/table><b>X<\/b>C<a>Y`: true,\n\t\/\/ More cases of <a> being reparented:\n\t`<a href=\"blah\">aba<table><a href=\"foo\">br<tr><td><\/td><\/tr>x<\/table>aoe`: true,\n\t`<a><table><a><\/table><p><a><div><a>`:                                     true,\n\t`<a><table><td><a><table><\/table><a><\/tr><a><\/table><a>`:                  true,\n\t\/\/ A <plaintext> element is reparented, putting it before a table.\n\t\/\/ A <plaintext> element can't have anything after it in HTML.\n\t`<table><plaintext><td>`: true,\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ HTTP client. See RFC 2616.\n\/\/ \n\/\/ This is the high-level Client interface.\n\/\/ The low-level implementation is in transport.go.\n\npackage http\n\nimport (\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/url\"\n\t\"strings\"\n)\n\n\/\/ A Client is an HTTP client. Its zero value (DefaultClient) is a usable client\n\/\/ that uses DefaultTransport.\n\/\/\n\/\/ The Client's Transport typically has internal state (cached\n\/\/ TCP connections), so Clients should be reused instead of created as\n\/\/ needed. Clients are safe for concurrent use by multiple goroutines.\ntype Client struct {\n\t\/\/ Transport specifies the mechanism by which individual\n\t\/\/ HTTP requests are made.\n\t\/\/ If nil, DefaultTransport is used.\n\tTransport RoundTripper\n\n\t\/\/ CheckRedirect specifies the policy for handling redirects.\n\t\/\/ If CheckRedirect is not nil, the client calls it before\n\t\/\/ following an HTTP redirect. The arguments req and via\n\t\/\/ are the upcoming request and the requests made already,\n\t\/\/ oldest first. If CheckRedirect returns an error, the client\n\t\/\/ returns that error instead of issue the Request req.\n\t\/\/\n\t\/\/ If CheckRedirect is nil, the Client uses its default policy,\n\t\/\/ which is to stop after 10 consecutive requests.\n\tCheckRedirect func(req *Request, via []*Request) error\n\n\t\/\/ Jar specifies the cookie jar. \n\t\/\/ If Jar is nil, cookies are not sent in requests and ignored \n\t\/\/ in responses.\n\tJar CookieJar\n}\n\n\/\/ DefaultClient is the default Client and is used by Get, Head, and Post.\nvar DefaultClient = &Client{}\n\n\/\/ RoundTripper is an interface representing the ability to execute a\n\/\/ single HTTP transaction, obtaining the Response for a given Request.\n\/\/\n\/\/ A RoundTripper must be safe for concurrent use by multiple\n\/\/ goroutines.\ntype RoundTripper interface {\n\t\/\/ RoundTrip executes a single HTTP transaction, returning\n\t\/\/ the Response for the request req.  RoundTrip should not\n\t\/\/ attempt to interpret the response.  In particular,\n\t\/\/ RoundTrip must return err == nil if it obtained a response,\n\t\/\/ regardless of the response's HTTP status code.  A non-nil\n\t\/\/ err should be reserved for failure to obtain a response.\n\t\/\/ Similarly, RoundTrip should not attempt to handle\n\t\/\/ higher-level protocol details such as redirects,\n\t\/\/ authentication, or cookies.\n\t\/\/\n\t\/\/ RoundTrip should not modify the request, except for\n\t\/\/ consuming the Body.  The request's URL and Header fields\n\t\/\/ are guaranteed to be initialized.\n\tRoundTrip(*Request) (*Response, error)\n}\n\n\/\/ Given a string of the form \"host\", \"host:port\", or \"[ipv6::address]:port\",\n\/\/ return true if the string includes a port.\nfunc hasPort(s string) bool { return strings.LastIndex(s, \":\") > strings.LastIndex(s, \"]\") }\n\n\/\/ Used in Send to implement io.ReadCloser by bundling together the\n\/\/ bufio.Reader through which we read the response, and the underlying\n\/\/ network connection.\ntype readClose struct {\n\tio.Reader\n\tio.Closer\n}\n\n\/\/ Do sends an HTTP request and returns an HTTP response, following\n\/\/ policy (e.g. redirects, cookies, auth) as configured on the client.\n\/\/\n\/\/ A non-nil response always contains a non-nil resp.Body.\n\/\/\n\/\/ Callers should close resp.Body when done reading from it. If\n\/\/ resp.Body is not closed, the Client's underlying RoundTripper\n\/\/ (typically Transport) may not be able to re-use a persistent TCP\n\/\/ connection to the server for a subsequent \"keep-alive\" request.\n\/\/\n\/\/ Generally Get, Post, or PostForm will be used instead of Do.\nfunc (c *Client) Do(req *Request) (resp *Response, err error) {\n\tif req.Method == \"GET\" || req.Method == \"HEAD\" {\n\t\treturn c.doFollowingRedirects(req)\n\t}\n\treturn send(req, c.Transport)\n}\n\n\/\/ send issues an HTTP request.  Caller should close resp.Body when done reading from it.\nfunc send(req *Request, t RoundTripper) (resp *Response, err error) {\n\tif t == nil {\n\t\tt = DefaultTransport\n\t\tif t == nil {\n\t\t\terr = errors.New(\"http: no Client.Transport or DefaultTransport\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tif req.URL == nil {\n\t\treturn nil, errors.New(\"http: nil Request.URL\")\n\t}\n\n\tif req.RequestURI != \"\" {\n\t\treturn nil, errors.New(\"http: Request.RequestURI can't be set in client requests.\")\n\t}\n\n\t\/\/ Most the callers of send (Get, Post, et al) don't need\n\t\/\/ Headers, leaving it uninitialized.  We guarantee to the\n\t\/\/ Transport that this has been initialized, though.\n\tif req.Header == nil {\n\t\treq.Header = make(Header)\n\t}\n\n\tif u := req.URL.User; u != nil {\n\t\treq.Header.Set(\"Authorization\", \"Basic \"+base64.URLEncoding.EncodeToString([]byte(u.String())))\n\t}\n\treturn t.RoundTrip(req)\n}\n\n\/\/ True if the specified HTTP status code is one for which the Get utility should\n\/\/ automatically redirect.\nfunc shouldRedirect(statusCode int) bool {\n\tswitch statusCode {\n\tcase StatusMovedPermanently, StatusFound, StatusSeeOther, StatusTemporaryRedirect:\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ Get issues a GET to the specified URL.  If the response is one of the following\n\/\/ redirect codes, Get follows the redirect, up to a maximum of 10 redirects:\n\/\/\n\/\/    301 (Moved Permanently)\n\/\/    302 (Found)\n\/\/    303 (See Other)\n\/\/    307 (Temporary Redirect)\n\/\/\n\/\/ Caller should close r.Body when done reading from it.\n\/\/\n\/\/ Get is a wrapper around DefaultClient.Get.\nfunc Get(url string) (r *Response, err error) {\n\treturn DefaultClient.Get(url)\n}\n\n\/\/ Get issues a GET to the specified URL.  If the response is one of the\n\/\/ following redirect codes, Get follows the redirect after calling the\n\/\/ Client's CheckRedirect function.\n\/\/\n\/\/    301 (Moved Permanently)\n\/\/    302 (Found)\n\/\/    303 (See Other)\n\/\/    307 (Temporary Redirect)\n\/\/\n\/\/ Caller should close r.Body when done reading from it.\nfunc (c *Client) Get(url string) (r *Response, err error) {\n\treq, err := NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.doFollowingRedirects(req)\n}\n\nfunc (c *Client) doFollowingRedirects(ireq *Request) (r *Response, err error) {\n\t\/\/ TODO: if\/when we add cookie support, the redirected request shouldn't\n\t\/\/ necessarily supply the same cookies as the original.\n\tvar base *url.URL\n\tredirectChecker := c.CheckRedirect\n\tif redirectChecker == nil {\n\t\tredirectChecker = defaultCheckRedirect\n\t}\n\tvar via []*Request\n\n\tif ireq.URL == nil {\n\t\treturn nil, errors.New(\"http: nil Request.URL\")\n\t}\n\n\tjar := c.Jar\n\tif jar == nil {\n\t\tjar = blackHoleJar{}\n\t}\n\n\treq := ireq\n\turlStr := \"\" \/\/ next relative or absolute URL to fetch (after first request)\n\tfor redirect := 0; ; redirect++ {\n\t\tif redirect != 0 {\n\t\t\treq = new(Request)\n\t\t\treq.Method = ireq.Method\n\t\t\treq.Header = make(Header)\n\t\t\treq.URL, err = base.Parse(urlStr)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif len(via) > 0 {\n\t\t\t\t\/\/ Add the Referer header.\n\t\t\t\tlastReq := via[len(via)-1]\n\t\t\t\tif lastReq.URL.Scheme != \"https\" {\n\t\t\t\t\treq.Header.Set(\"Referer\", lastReq.URL.String())\n\t\t\t\t}\n\n\t\t\t\terr = redirectChecker(req, via)\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor _, cookie := range jar.Cookies(req.URL) {\n\t\t\treq.AddCookie(cookie)\n\t\t}\n\t\turlStr = req.URL.String()\n\t\tif r, err = send(req, c.Transport); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif c := r.Cookies(); len(c) > 0 {\n\t\t\tjar.SetCookies(req.URL, c)\n\t\t}\n\n\t\tif shouldRedirect(r.StatusCode) {\n\t\t\tr.Body.Close()\n\t\t\tif urlStr = r.Header.Get(\"Location\"); urlStr == \"\" {\n\t\t\t\terr = errors.New(fmt.Sprintf(\"%d response missing Location header\", r.StatusCode))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbase = req.URL\n\t\t\tvia = append(via, req)\n\t\t\tcontinue\n\t\t}\n\t\treturn\n\t}\n\n\tmethod := ireq.Method\n\terr = &url.Error{method[0:1] + strings.ToLower(method[1:]), urlStr, err}\n\treturn\n}\n\nfunc defaultCheckRedirect(req *Request, via []*Request) error {\n\tif len(via) >= 10 {\n\t\treturn errors.New(\"stopped after 10 redirects\")\n\t}\n\treturn nil\n}\n\n\/\/ Post issues a POST to the specified URL.\n\/\/\n\/\/ Caller should close r.Body when done reading from it.\n\/\/\n\/\/ Post is a wrapper around DefaultClient.Post\nfunc Post(url string, bodyType string, body io.Reader) (r *Response, err error) {\n\treturn DefaultClient.Post(url, bodyType, body)\n}\n\n\/\/ Post issues a POST to the specified URL.\n\/\/\n\/\/ Caller should close r.Body when done reading from it.\nfunc (c *Client) Post(url string, bodyType string, body io.Reader) (r *Response, err error) {\n\treq, err := NewRequest(\"POST\", url, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Content-Type\", bodyType)\n\treturn send(req, c.Transport)\n}\n\n\/\/ PostForm issues a POST to the specified URL, \n\/\/ with data's keys and values urlencoded as the request body.\n\/\/\n\/\/ Caller should close r.Body when done reading from it.\n\/\/\n\/\/ PostForm is a wrapper around DefaultClient.PostForm\nfunc PostForm(url string, data url.Values) (r *Response, err error) {\n\treturn DefaultClient.PostForm(url, data)\n}\n\n\/\/ PostForm issues a POST to the specified URL, \n\/\/ with data's keys and values urlencoded as the request body.\n\/\/\n\/\/ Caller should close r.Body when done reading from it.\nfunc (c *Client) PostForm(url string, data url.Values) (r *Response, err error) {\n\treturn c.Post(url, \"application\/x-www-form-urlencoded\", strings.NewReader(data.Encode()))\n}\n\n\/\/ Head issues a HEAD to the specified URL.  If the response is one of the\n\/\/ following redirect codes, Head follows the redirect after calling the\n\/\/ Client's CheckRedirect function.\n\/\/\n\/\/    301 (Moved Permanently)\n\/\/    302 (Found)\n\/\/    303 (See Other)\n\/\/    307 (Temporary Redirect)\n\/\/\n\/\/ Head is a wrapper around DefaultClient.Head\nfunc Head(url string) (r *Response, err error) {\n\treturn DefaultClient.Head(url)\n}\n\n\/\/ Head issues a HEAD to the specified URL.  If the response is one of the\n\/\/ following redirect codes, Head follows the redirect after calling the\n\/\/ Client's CheckRedirect function.\n\/\/\n\/\/    301 (Moved Permanently)\n\/\/    302 (Found)\n\/\/    303 (See Other)\n\/\/    307 (Temporary Redirect)\nfunc (c *Client) Head(url string) (r *Response, err error) {\n\treq, err := NewRequest(\"HEAD\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.doFollowingRedirects(req)\n}\n<commit_msg>net\/http: set cookies in client jar on POST requests.<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ HTTP client. See RFC 2616.\n\/\/ \n\/\/ This is the high-level Client interface.\n\/\/ The low-level implementation is in transport.go.\n\npackage http\n\nimport (\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/url\"\n\t\"strings\"\n)\n\n\/\/ A Client is an HTTP client. Its zero value (DefaultClient) is a usable client\n\/\/ that uses DefaultTransport.\n\/\/\n\/\/ The Client's Transport typically has internal state (cached\n\/\/ TCP connections), so Clients should be reused instead of created as\n\/\/ needed. Clients are safe for concurrent use by multiple goroutines.\ntype Client struct {\n\t\/\/ Transport specifies the mechanism by which individual\n\t\/\/ HTTP requests are made.\n\t\/\/ If nil, DefaultTransport is used.\n\tTransport RoundTripper\n\n\t\/\/ CheckRedirect specifies the policy for handling redirects.\n\t\/\/ If CheckRedirect is not nil, the client calls it before\n\t\/\/ following an HTTP redirect. The arguments req and via\n\t\/\/ are the upcoming request and the requests made already,\n\t\/\/ oldest first. If CheckRedirect returns an error, the client\n\t\/\/ returns that error instead of issue the Request req.\n\t\/\/\n\t\/\/ If CheckRedirect is nil, the Client uses its default policy,\n\t\/\/ which is to stop after 10 consecutive requests.\n\tCheckRedirect func(req *Request, via []*Request) error\n\n\t\/\/ Jar specifies the cookie jar. \n\t\/\/ If Jar is nil, cookies are not sent in requests and ignored \n\t\/\/ in responses.\n\tJar CookieJar\n}\n\n\/\/ DefaultClient is the default Client and is used by Get, Head, and Post.\nvar DefaultClient = &Client{}\n\n\/\/ RoundTripper is an interface representing the ability to execute a\n\/\/ single HTTP transaction, obtaining the Response for a given Request.\n\/\/\n\/\/ A RoundTripper must be safe for concurrent use by multiple\n\/\/ goroutines.\ntype RoundTripper interface {\n\t\/\/ RoundTrip executes a single HTTP transaction, returning\n\t\/\/ the Response for the request req.  RoundTrip should not\n\t\/\/ attempt to interpret the response.  In particular,\n\t\/\/ RoundTrip must return err == nil if it obtained a response,\n\t\/\/ regardless of the response's HTTP status code.  A non-nil\n\t\/\/ err should be reserved for failure to obtain a response.\n\t\/\/ Similarly, RoundTrip should not attempt to handle\n\t\/\/ higher-level protocol details such as redirects,\n\t\/\/ authentication, or cookies.\n\t\/\/\n\t\/\/ RoundTrip should not modify the request, except for\n\t\/\/ consuming the Body.  The request's URL and Header fields\n\t\/\/ are guaranteed to be initialized.\n\tRoundTrip(*Request) (*Response, error)\n}\n\n\/\/ Given a string of the form \"host\", \"host:port\", or \"[ipv6::address]:port\",\n\/\/ return true if the string includes a port.\nfunc hasPort(s string) bool { return strings.LastIndex(s, \":\") > strings.LastIndex(s, \"]\") }\n\n\/\/ Used in Send to implement io.ReadCloser by bundling together the\n\/\/ bufio.Reader through which we read the response, and the underlying\n\/\/ network connection.\ntype readClose struct {\n\tio.Reader\n\tio.Closer\n}\n\n\/\/ Do sends an HTTP request and returns an HTTP response, following\n\/\/ policy (e.g. redirects, cookies, auth) as configured on the client.\n\/\/\n\/\/ A non-nil response always contains a non-nil resp.Body.\n\/\/\n\/\/ Callers should close resp.Body when done reading from it. If\n\/\/ resp.Body is not closed, the Client's underlying RoundTripper\n\/\/ (typically Transport) may not be able to re-use a persistent TCP\n\/\/ connection to the server for a subsequent \"keep-alive\" request.\n\/\/\n\/\/ Generally Get, Post, or PostForm will be used instead of Do.\nfunc (c *Client) Do(req *Request) (resp *Response, err error) {\n\tif req.Method == \"GET\" || req.Method == \"HEAD\" {\n\t\treturn c.doFollowingRedirects(req)\n\t}\n\treturn send(req, c.Transport)\n}\n\n\/\/ send issues an HTTP request.  Caller should close resp.Body when done reading from it.\nfunc send(req *Request, t RoundTripper) (resp *Response, err error) {\n\tif t == nil {\n\t\tt = DefaultTransport\n\t\tif t == nil {\n\t\t\terr = errors.New(\"http: no Client.Transport or DefaultTransport\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tif req.URL == nil {\n\t\treturn nil, errors.New(\"http: nil Request.URL\")\n\t}\n\n\tif req.RequestURI != \"\" {\n\t\treturn nil, errors.New(\"http: Request.RequestURI can't be set in client requests.\")\n\t}\n\n\t\/\/ Most the callers of send (Get, Post, et al) don't need\n\t\/\/ Headers, leaving it uninitialized.  We guarantee to the\n\t\/\/ Transport that this has been initialized, though.\n\tif req.Header == nil {\n\t\treq.Header = make(Header)\n\t}\n\n\tif u := req.URL.User; u != nil {\n\t\treq.Header.Set(\"Authorization\", \"Basic \"+base64.URLEncoding.EncodeToString([]byte(u.String())))\n\t}\n\treturn t.RoundTrip(req)\n}\n\n\/\/ True if the specified HTTP status code is one for which the Get utility should\n\/\/ automatically redirect.\nfunc shouldRedirect(statusCode int) bool {\n\tswitch statusCode {\n\tcase StatusMovedPermanently, StatusFound, StatusSeeOther, StatusTemporaryRedirect:\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ Get issues a GET to the specified URL.  If the response is one of the following\n\/\/ redirect codes, Get follows the redirect, up to a maximum of 10 redirects:\n\/\/\n\/\/    301 (Moved Permanently)\n\/\/    302 (Found)\n\/\/    303 (See Other)\n\/\/    307 (Temporary Redirect)\n\/\/\n\/\/ Caller should close r.Body when done reading from it.\n\/\/\n\/\/ Get is a wrapper around DefaultClient.Get.\nfunc Get(url string) (r *Response, err error) {\n\treturn DefaultClient.Get(url)\n}\n\n\/\/ Get issues a GET to the specified URL.  If the response is one of the\n\/\/ following redirect codes, Get follows the redirect after calling the\n\/\/ Client's CheckRedirect function.\n\/\/\n\/\/    301 (Moved Permanently)\n\/\/    302 (Found)\n\/\/    303 (See Other)\n\/\/    307 (Temporary Redirect)\n\/\/\n\/\/ Caller should close r.Body when done reading from it.\nfunc (c *Client) Get(url string) (r *Response, err error) {\n\treq, err := NewRequest(\"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.doFollowingRedirects(req)\n}\n\nfunc (c *Client) doFollowingRedirects(ireq *Request) (r *Response, err error) {\n\t\/\/ TODO: if\/when we add cookie support, the redirected request shouldn't\n\t\/\/ necessarily supply the same cookies as the original.\n\tvar base *url.URL\n\tredirectChecker := c.CheckRedirect\n\tif redirectChecker == nil {\n\t\tredirectChecker = defaultCheckRedirect\n\t}\n\tvar via []*Request\n\n\tif ireq.URL == nil {\n\t\treturn nil, errors.New(\"http: nil Request.URL\")\n\t}\n\n\tjar := c.Jar\n\tif jar == nil {\n\t\tjar = blackHoleJar{}\n\t}\n\n\treq := ireq\n\turlStr := \"\" \/\/ next relative or absolute URL to fetch (after first request)\n\tfor redirect := 0; ; redirect++ {\n\t\tif redirect != 0 {\n\t\t\treq = new(Request)\n\t\t\treq.Method = ireq.Method\n\t\t\treq.Header = make(Header)\n\t\t\treq.URL, err = base.Parse(urlStr)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif len(via) > 0 {\n\t\t\t\t\/\/ Add the Referer header.\n\t\t\t\tlastReq := via[len(via)-1]\n\t\t\t\tif lastReq.URL.Scheme != \"https\" {\n\t\t\t\t\treq.Header.Set(\"Referer\", lastReq.URL.String())\n\t\t\t\t}\n\n\t\t\t\terr = redirectChecker(req, via)\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor _, cookie := range jar.Cookies(req.URL) {\n\t\t\treq.AddCookie(cookie)\n\t\t}\n\t\turlStr = req.URL.String()\n\t\tif r, err = send(req, c.Transport); err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif c := r.Cookies(); len(c) > 0 {\n\t\t\tjar.SetCookies(req.URL, c)\n\t\t}\n\n\t\tif shouldRedirect(r.StatusCode) {\n\t\t\tr.Body.Close()\n\t\t\tif urlStr = r.Header.Get(\"Location\"); urlStr == \"\" {\n\t\t\t\terr = errors.New(fmt.Sprintf(\"%d response missing Location header\", r.StatusCode))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tbase = req.URL\n\t\t\tvia = append(via, req)\n\t\t\tcontinue\n\t\t}\n\t\treturn\n\t}\n\n\tmethod := ireq.Method\n\terr = &url.Error{method[0:1] + strings.ToLower(method[1:]), urlStr, err}\n\treturn\n}\n\nfunc defaultCheckRedirect(req *Request, via []*Request) error {\n\tif len(via) >= 10 {\n\t\treturn errors.New(\"stopped after 10 redirects\")\n\t}\n\treturn nil\n}\n\n\/\/ Post issues a POST to the specified URL.\n\/\/\n\/\/ Caller should close r.Body when done reading from it.\n\/\/\n\/\/ Post is a wrapper around DefaultClient.Post\nfunc Post(url string, bodyType string, body io.Reader) (r *Response, err error) {\n\treturn DefaultClient.Post(url, bodyType, body)\n}\n\n\/\/ Post issues a POST to the specified URL.\n\/\/\n\/\/ Caller should close r.Body when done reading from it.\nfunc (c *Client) Post(url string, bodyType string, body io.Reader) (r *Response, err error) {\n\treq, err := NewRequest(\"POST\", url, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Content-Type\", bodyType)\n\tr, err = send(req, c.Transport)\n\tif c.Jar != nil {\n\t\tc.Jar.SetCookies(req.URL, r.Cookies())\n\t}\n\treturn r, err\n}\n\n\/\/ PostForm issues a POST to the specified URL, \n\/\/ with data's keys and values urlencoded as the request body.\n\/\/\n\/\/ Caller should close r.Body when done reading from it.\n\/\/\n\/\/ PostForm is a wrapper around DefaultClient.PostForm\nfunc PostForm(url string, data url.Values) (r *Response, err error) {\n\treturn DefaultClient.PostForm(url, data)\n}\n\n\/\/ PostForm issues a POST to the specified URL, \n\/\/ with data's keys and values urlencoded as the request body.\n\/\/\n\/\/ Caller should close r.Body when done reading from it.\nfunc (c *Client) PostForm(url string, data url.Values) (r *Response, err error) {\n\treturn c.Post(url, \"application\/x-www-form-urlencoded\", strings.NewReader(data.Encode()))\n}\n\n\/\/ Head issues a HEAD to the specified URL.  If the response is one of the\n\/\/ following redirect codes, Head follows the redirect after calling the\n\/\/ Client's CheckRedirect function.\n\/\/\n\/\/    301 (Moved Permanently)\n\/\/    302 (Found)\n\/\/    303 (See Other)\n\/\/    307 (Temporary Redirect)\n\/\/\n\/\/ Head is a wrapper around DefaultClient.Head\nfunc Head(url string) (r *Response, err error) {\n\treturn DefaultClient.Head(url)\n}\n\n\/\/ Head issues a HEAD to the specified URL.  If the response is one of the\n\/\/ following redirect codes, Head follows the redirect after calling the\n\/\/ Client's CheckRedirect function.\n\/\/\n\/\/    301 (Moved Permanently)\n\/\/    302 (Found)\n\/\/    303 (See Other)\n\/\/    307 (Temporary Redirect)\nfunc (c *Client) Head(url string) (r *Response, err error) {\n\treq, err := NewRequest(\"HEAD\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn c.doFollowingRedirects(req)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage os\n\nimport (\n\t\"runtime\"\n\t\"syscall\"\n)\n\n\/\/ Auxiliary information if the File describes a directory\ntype dirInfo struct {\n\tstat         syscall.Stat_t\n\tusefirststat bool\n}\n\nconst DevNull = \"NUL\"\n\nfunc (file *File) isdir() bool { return file != nil && file.dirinfo != nil }\n\nfunc openFile(name string, flag int, perm uint32) (file *File, err Error) {\n\tr, e := syscall.Open(name, flag|syscall.O_CLOEXEC, perm)\n\tif e != 0 {\n\t\treturn nil, &PathError{\"open\", name, Errno(e)}\n\t}\n\n\t\/\/ There's a race here with fork\/exec, which we are\n\t\/\/ content to live with.  See ..\/syscall\/exec.go\n\tif syscall.O_CLOEXEC == 0 { \/\/ O_CLOEXEC not supported\n\t\tsyscall.CloseOnExec(r)\n\t}\n\n\treturn NewFile(r, name), nil\n}\n\nfunc openDir(name string) (file *File, err Error) {\n\td := new(dirInfo)\n\tr, e := syscall.FindFirstFile(syscall.StringToUTF16Ptr(name+\"\\\\*\"), &d.stat.Windata)\n\tif e != 0 {\n\t\treturn nil, &PathError{\"open\", name, Errno(e)}\n\t}\n\tf := NewFile(int(r), name)\n\td.usefirststat = true\n\tf.dirinfo = d\n\treturn f, nil\n}\n\n\/\/ Open opens the named file with specified flag (O_RDONLY etc.) and perm, (0666 etc.)\n\/\/ if applicable.  If successful, methods on the returned File can be used for I\/O.\n\/\/ It returns the File and an Error, if any.\nfunc Open(name string, flag int, perm uint32) (file *File, err Error) {\n\t\/\/ TODO(brainman): not sure about my logic of assuming it is dir first, then fall back to file\n\tr, e := openDir(name)\n\tif e == nil {\n\t\treturn r, nil\n\t}\n\tr, e = openFile(name, flag, perm)\n\tif e == nil {\n\t\treturn r, nil\n\t}\n\treturn nil, e\n}\n\n\/\/ Close closes the File, rendering it unusable for I\/O.\n\/\/ It returns an Error, if any.\nfunc (file *File) Close() Error {\n\tif file == nil || file.fd < 0 {\n\t\treturn EINVAL\n\t}\n\tvar e int\n\tif file.isdir() {\n\t\t_, e = syscall.FindClose(int32(file.fd))\n\t} else {\n\t\t_, e = syscall.CloseHandle(int32(file.fd))\n\t}\n\tvar err Error\n\tif e != 0 {\n\t\terr = &PathError{\"close\", file.name, Errno(e)}\n\t}\n\tfile.fd = -1 \/\/ so it can't be closed again\n\n\t\/\/ no need for a finalizer anymore\n\truntime.SetFinalizer(file, nil)\n\treturn err\n}\n\nfunc (file *File) statFile(name string) (fi *FileInfo, err Error) {\n\tvar stat syscall.ByHandleFileInformation\n\tif ok, e := syscall.GetFileInformationByHandle(int32(file.fd), &stat); !ok {\n\t\treturn nil, &PathError{\"stat\", file.name, Errno(e)}\n\t}\n\treturn fileInfoFromByHandleInfo(new(FileInfo), file.name, &stat), nil\n}\n\n\/\/ Stat returns the FileInfo structure describing file.\n\/\/ It returns the FileInfo and an error, if any.\nfunc (file *File) Stat() (fi *FileInfo, err Error) {\n\tif file == nil || file.fd < 0 {\n\t\treturn nil, EINVAL\n\t}\n\tif file.isdir() {\n\t\t\/\/ I don't know any better way to do that for directory\n\t\treturn Stat(file.name)\n\t}\n\treturn file.statFile(file.name)\n}\n\n\/\/ Readdir reads the contents of the directory associated with file and\n\/\/ returns an array of up to count FileInfo structures, as would be returned\n\/\/ by Lstat, in directory order.  Subsequent calls on the same file will yield\n\/\/ further FileInfos.\n\/\/ A negative count means to read until EOF.\n\/\/ Readdir returns the array and an Error, if any.\nfunc (file *File) Readdir(count int) (fi []FileInfo, err Error) {\n\tdi := file.dirinfo\n\tsize := count\n\tif size < 0 {\n\t\tsize = 100\n\t}\n\tfi = make([]FileInfo, 0, size) \/\/ Empty with room to grow.\n\tfor count != 0 {\n\t\tif di.usefirststat {\n\t\t\tdi.usefirststat = false\n\t\t} else {\n\t\t\t_, e := syscall.FindNextFile(int32(file.fd), &di.stat.Windata)\n\t\t\tif e != 0 {\n\t\t\t\tif e == syscall.ERROR_NO_MORE_FILES {\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, &PathError{\"FindNextFile\", file.name, Errno(e)}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvar f FileInfo\n\t\tfileInfoFromWin32finddata(&f, &di.stat.Windata)\n\t\tif f.Name == \".\" || f.Name == \"..\" { \/\/ Useless names\n\t\t\tcontinue\n\t\t}\n\t\tcount--\n\t\tif len(fi) == cap(fi) {\n\t\t\tnfi := make([]FileInfo, len(fi), 2*len(fi))\n\t\t\tfor i := 0; i < len(fi); i++ {\n\t\t\t\tnfi[i] = fi[i]\n\t\t\t}\n\t\t\tfi = nfi\n\t\t}\n\t\tfi = fi[0 : len(fi)+1]\n\t\tfi[len(fi)-1] = f\n\t}\n\treturn fi, nil\n}\n\n\/\/ Truncate changes the size of the named file.\n\/\/ If the file is a symbolic link, it changes the size of the link's target.\nfunc Truncate(name string, size int64) Error {\n\tf, e := Open(name, O_WRONLY|O_CREAT, 0666)\n\tif e != nil {\n\t\treturn e\n\t}\n\tdefer f.Close()\n\te1 := f.Truncate(size)\n\tif e1 != nil {\n\t\treturn e1\n\t}\n\treturn nil\n}\n<commit_msg>os: check for valid arguments in windows Readdir<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage os\n\nimport (\n\t\"runtime\"\n\t\"syscall\"\n)\n\n\/\/ Auxiliary information if the File describes a directory\ntype dirInfo struct {\n\tstat         syscall.Stat_t\n\tusefirststat bool\n}\n\nconst DevNull = \"NUL\"\n\nfunc (file *File) isdir() bool { return file != nil && file.dirinfo != nil }\n\nfunc openFile(name string, flag int, perm uint32) (file *File, err Error) {\n\tr, e := syscall.Open(name, flag|syscall.O_CLOEXEC, perm)\n\tif e != 0 {\n\t\treturn nil, &PathError{\"open\", name, Errno(e)}\n\t}\n\n\t\/\/ There's a race here with fork\/exec, which we are\n\t\/\/ content to live with.  See ..\/syscall\/exec.go\n\tif syscall.O_CLOEXEC == 0 { \/\/ O_CLOEXEC not supported\n\t\tsyscall.CloseOnExec(r)\n\t}\n\n\treturn NewFile(r, name), nil\n}\n\nfunc openDir(name string) (file *File, err Error) {\n\td := new(dirInfo)\n\tr, e := syscall.FindFirstFile(syscall.StringToUTF16Ptr(name+\"\\\\*\"), &d.stat.Windata)\n\tif e != 0 {\n\t\treturn nil, &PathError{\"open\", name, Errno(e)}\n\t}\n\tf := NewFile(int(r), name)\n\td.usefirststat = true\n\tf.dirinfo = d\n\treturn f, nil\n}\n\n\/\/ Open opens the named file with specified flag (O_RDONLY etc.) and perm, (0666 etc.)\n\/\/ if applicable.  If successful, methods on the returned File can be used for I\/O.\n\/\/ It returns the File and an Error, if any.\nfunc Open(name string, flag int, perm uint32) (file *File, err Error) {\n\t\/\/ TODO(brainman): not sure about my logic of assuming it is dir first, then fall back to file\n\tr, e := openDir(name)\n\tif e == nil {\n\t\treturn r, nil\n\t}\n\tr, e = openFile(name, flag, perm)\n\tif e == nil {\n\t\treturn r, nil\n\t}\n\treturn nil, e\n}\n\n\/\/ Close closes the File, rendering it unusable for I\/O.\n\/\/ It returns an Error, if any.\nfunc (file *File) Close() Error {\n\tif file == nil || file.fd < 0 {\n\t\treturn EINVAL\n\t}\n\tvar e int\n\tif file.isdir() {\n\t\t_, e = syscall.FindClose(int32(file.fd))\n\t} else {\n\t\t_, e = syscall.CloseHandle(int32(file.fd))\n\t}\n\tvar err Error\n\tif e != 0 {\n\t\terr = &PathError{\"close\", file.name, Errno(e)}\n\t}\n\tfile.fd = -1 \/\/ so it can't be closed again\n\n\t\/\/ no need for a finalizer anymore\n\truntime.SetFinalizer(file, nil)\n\treturn err\n}\n\nfunc (file *File) statFile(name string) (fi *FileInfo, err Error) {\n\tvar stat syscall.ByHandleFileInformation\n\tif ok, e := syscall.GetFileInformationByHandle(int32(file.fd), &stat); !ok {\n\t\treturn nil, &PathError{\"stat\", file.name, Errno(e)}\n\t}\n\treturn fileInfoFromByHandleInfo(new(FileInfo), file.name, &stat), nil\n}\n\n\/\/ Stat returns the FileInfo structure describing file.\n\/\/ It returns the FileInfo and an error, if any.\nfunc (file *File) Stat() (fi *FileInfo, err Error) {\n\tif file == nil || file.fd < 0 {\n\t\treturn nil, EINVAL\n\t}\n\tif file.isdir() {\n\t\t\/\/ I don't know any better way to do that for directory\n\t\treturn Stat(file.name)\n\t}\n\treturn file.statFile(file.name)\n}\n\n\/\/ Readdir reads the contents of the directory associated with file and\n\/\/ returns an array of up to count FileInfo structures, as would be returned\n\/\/ by Lstat, in directory order.  Subsequent calls on the same file will yield\n\/\/ further FileInfos.\n\/\/ A negative count means to read until EOF.\n\/\/ Readdir returns the array and an Error, if any.\nfunc (file *File) Readdir(count int) (fi []FileInfo, err Error) {\n\tif file == nil || file.fd < 0 {\n\t\treturn nil, EINVAL\n\t}\n\tif !file.isdir() {\n\t\treturn nil, &PathError{\"Readdir\", file.name, ENOTDIR}\n\t}\n\tdi := file.dirinfo\n\tsize := count\n\tif size < 0 {\n\t\tsize = 100\n\t}\n\tfi = make([]FileInfo, 0, size) \/\/ Empty with room to grow.\n\tfor count != 0 {\n\t\tif di.usefirststat {\n\t\t\tdi.usefirststat = false\n\t\t} else {\n\t\t\t_, e := syscall.FindNextFile(int32(file.fd), &di.stat.Windata)\n\t\t\tif e != 0 {\n\t\t\t\tif e == syscall.ERROR_NO_MORE_FILES {\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\treturn nil, &PathError{\"FindNextFile\", file.name, Errno(e)}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvar f FileInfo\n\t\tfileInfoFromWin32finddata(&f, &di.stat.Windata)\n\t\tif f.Name == \".\" || f.Name == \"..\" { \/\/ Useless names\n\t\t\tcontinue\n\t\t}\n\t\tcount--\n\t\tif len(fi) == cap(fi) {\n\t\t\tnfi := make([]FileInfo, len(fi), 2*len(fi))\n\t\t\tfor i := 0; i < len(fi); i++ {\n\t\t\t\tnfi[i] = fi[i]\n\t\t\t}\n\t\t\tfi = nfi\n\t\t}\n\t\tfi = fi[0 : len(fi)+1]\n\t\tfi[len(fi)-1] = f\n\t}\n\treturn fi, nil\n}\n\n\/\/ Truncate changes the size of the named file.\n\/\/ If the file is a symbolic link, it changes the size of the link's target.\nfunc Truncate(name string, size int64) Error {\n\tf, e := Open(name, O_WRONLY|O_CREAT, 0666)\n\tif e != nil {\n\t\treturn e\n\t}\n\tdefer f.Close()\n\te1 := f.Truncate(size)\n\tif e1 != nil {\n\t\treturn e1\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package peer\n\nimport (\n\t\"doozer\/store\"\n\t\"github.com\/ha\/doozer\"\n\t\"testing\"\n)\n\n\nfunc Benchmark1DoozerClientSet(b *testing.B) {\n\tb.StopTimer()\n\tl := mustListen()\n\tdefer l.Close()\n\ta := l.Addr().String()\n\tu := mustListenPacket(a)\n\tdefer u.Close()\n\n\tgo Main(\"a\", \"X\", \"\", \"\", \"\", nil, u, l, nil, 1e9, 2e9, 3e9)\n\n\tcl := dial(l.Addr().String())\n\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tcl.Set(\"\/test\", store.Clobber, nil)\n\t}\n}\n\n\nfunc Benchmark1DoozerConClientSet(b *testing.B) {\n\tb.StopTimer()\n\tl := mustListen()\n\tdefer l.Close()\n\ta := l.Addr().String()\n\tu := mustListenPacket(a)\n\tdefer u.Close()\n\n\tgo Main(\"a\", \"X\", \"\", \"\", \"\", nil, u, l, nil, 1e9, 2e9, 3e9)\n\n\tcl := dial(l.Addr().String())\n\n\tc := make(chan bool, b.N)\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tgo func() {\n\t\t\tcl.Set(\"\/test\", store.Clobber, nil)\n\t\t\tc <- true\n\t\t}()\n\t}\n\tfor i := 0; i < b.N; i++ {\n\t\t<-c\n\t}\n}\n\n\nfunc Benchmark5DoozerClientSet(b *testing.B) {\n\tb.StopTimer()\n\tl := mustListen()\n\tdefer l.Close()\n\ta := l.Addr().String()\n\tu := mustListenPacket(a)\n\tdefer u.Close()\n\n\tl1 := mustListen()\n\tdefer l1.Close()\n\tu1 := mustListenPacket(l1.Addr().String())\n\tdefer u1.Close()\n\tl2 := mustListen()\n\tdefer l2.Close()\n\tu2 := mustListenPacket(l2.Addr().String())\n\tdefer u2.Close()\n\tl3 := mustListen()\n\tdefer l3.Close()\n\tu3 := mustListenPacket(l3.Addr().String())\n\tdefer u3.Close()\n\tl4 := mustListen()\n\tdefer l4.Close()\n\tu4 := mustListenPacket(l4.Addr().String())\n\tdefer u4.Close()\n\n\tgo Main(\"a\", \"X\", \"\", \"\", \"\", nil, u, l, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"Y\", \"\", \"\", \"\", dial(a), u1, l1, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"Z\", \"\", \"\", \"\", dial(a), u2, l2, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"V\", \"\", \"\", \"\", dial(a), u3, l3, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"W\", \"\", \"\", \"\", dial(a), u4, l4, nil, 1e9, 1e8, 3e9)\n\n\tcl := dial(l.Addr().String())\n\tcl.Set(\"\/ctl\/cal\/1\", store.Missing, nil)\n\tcl.Set(\"\/ctl\/cal\/2\", store.Missing, nil)\n\tcl.Set(\"\/ctl\/cal\/3\", store.Missing, nil)\n\tcl.Set(\"\/ctl\/cal\/4\", store.Missing, nil)\n\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tcl.Set(\"\/test\", store.Clobber, nil)\n\t}\n}\n\n\nfunc Benchmark5DoozerConClientSet(b *testing.B) {\n\tb.StopTimer()\n\tl := mustListen()\n\tdefer l.Close()\n\ta := l.Addr().String()\n\tu := mustListenPacket(a)\n\tdefer u.Close()\n\n\tl1 := mustListen()\n\tdefer l1.Close()\n\tu1 := mustListenPacket(l1.Addr().String())\n\tdefer u1.Close()\n\tl2 := mustListen()\n\tdefer l2.Close()\n\tu2 := mustListenPacket(l2.Addr().String())\n\tdefer u2.Close()\n\tl3 := mustListen()\n\tdefer l3.Close()\n\tu3 := mustListenPacket(l3.Addr().String())\n\tdefer u3.Close()\n\tl4 := mustListen()\n\tdefer l4.Close()\n\tu4 := mustListenPacket(l4.Addr().String())\n\tdefer u4.Close()\n\n\tgo Main(\"a\", \"X\", \"\", \"\", \"\", nil, u, l, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"Y\", \"\", \"\", \"\", dial(a), u1, l1, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"Z\", \"\", \"\", \"\", dial(a), u2, l2, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"V\", \"\", \"\", \"\", dial(a), u3, l3, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"W\", \"\", \"\", \"\", dial(a), u4, l4, nil, 1e9, 1e8, 3e9)\n\n\tcl := dial(l.Addr().String())\n\tcl.Set(\"\/ctl\/cal\/1\", store.Missing, nil)\n\tcl.Set(\"\/ctl\/cal\/2\", store.Missing, nil)\n\tcl.Set(\"\/ctl\/cal\/3\", store.Missing, nil)\n\tcl.Set(\"\/ctl\/cal\/4\", store.Missing, nil)\n\n\tcls := []*doozer.Conn{\n\t\tcl,\n\t\tdial(l1.Addr().String()),\n\t\tdial(l2.Addr().String()),\n\t\tdial(l3.Addr().String()),\n\t\tdial(l4.Addr().String()),\n\t}\n\n\tc := make(chan bool, b.N)\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\ti := i\n\t\tgo func() {\n\t\t\tcls[i%len(cls)].Set(\"\/test\", store.Clobber, nil)\n\t\t\tc <- true\n\t\t}()\n\t}\n\tfor i := 0; i < b.N; i++ {\n\t\t<-c\n\t}\n}\n\n\nfunc dial(addr string) *doozer.Conn {\n\tc, err := doozer.Dial(addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn c\n}\n<commit_msg>test with fixed concurrency and report latency<commit_after>package peer\n\nimport (\n\t\"doozer\/store\"\n\t\"github.com\/ha\/doozer\"\n\t\"testing\"\n\t\"time\"\n)\n\n\nfunc Benchmark1DoozerClientSet(b *testing.B) {\n\tb.StopTimer()\n\tl := mustListen()\n\tdefer l.Close()\n\ta := l.Addr().String()\n\tu := mustListenPacket(a)\n\tdefer u.Close()\n\n\tgo Main(\"a\", \"X\", \"\", \"\", \"\", nil, u, l, nil, 1e9, 2e9, 3e9)\n\n\tcl := dial(l.Addr().String())\n\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tcl.Set(\"\/test\", store.Clobber, nil)\n\t}\n}\n\n\nfunc Benchmark1DoozerConClientSet(b *testing.B) {\n\tb.StopTimer()\n\tl := mustListen()\n\tdefer l.Close()\n\ta := l.Addr().String()\n\tu := mustListenPacket(a)\n\tdefer u.Close()\n\n\tgo Main(\"a\", \"X\", \"\", \"\", \"\", nil, u, l, nil, 1e9, 2e9, 3e9)\n\n\tcl := dial(l.Addr().String())\n\n\tc := make(chan bool, b.N)\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tgo func() {\n\t\t\tcl.Set(\"\/test\", store.Clobber, nil)\n\t\t\tc <- true\n\t\t}()\n\t}\n\tfor i := 0; i < b.N; i++ {\n\t\t<-c\n\t}\n}\n\n\nfunc Benchmark5DoozerClientSet(b *testing.B) {\n\tb.StopTimer()\n\tl := mustListen()\n\tdefer l.Close()\n\ta := l.Addr().String()\n\tu := mustListenPacket(a)\n\tdefer u.Close()\n\n\tl1 := mustListen()\n\tdefer l1.Close()\n\tu1 := mustListenPacket(l1.Addr().String())\n\tdefer u1.Close()\n\tl2 := mustListen()\n\tdefer l2.Close()\n\tu2 := mustListenPacket(l2.Addr().String())\n\tdefer u2.Close()\n\tl3 := mustListen()\n\tdefer l3.Close()\n\tu3 := mustListenPacket(l3.Addr().String())\n\tdefer u3.Close()\n\tl4 := mustListen()\n\tdefer l4.Close()\n\tu4 := mustListenPacket(l4.Addr().String())\n\tdefer u4.Close()\n\n\tgo Main(\"a\", \"X\", \"\", \"\", \"\", nil, u, l, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"Y\", \"\", \"\", \"\", dial(a), u1, l1, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"Z\", \"\", \"\", \"\", dial(a), u2, l2, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"V\", \"\", \"\", \"\", dial(a), u3, l3, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"W\", \"\", \"\", \"\", dial(a), u4, l4, nil, 1e9, 1e8, 3e9)\n\n\tcl := dial(l.Addr().String())\n\tcl.Set(\"\/ctl\/cal\/1\", store.Missing, nil)\n\tcl.Set(\"\/ctl\/cal\/2\", store.Missing, nil)\n\tcl.Set(\"\/ctl\/cal\/3\", store.Missing, nil)\n\tcl.Set(\"\/ctl\/cal\/4\", store.Missing, nil)\n\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tcl.Set(\"\/test\", store.Clobber, nil)\n\t}\n}\n\n\nfunc Benchmark5DoozerConClientSet(b *testing.B) {\n\tb.StopTimer()\n\tl := mustListen()\n\tdefer l.Close()\n\ta := l.Addr().String()\n\tu := mustListenPacket(a)\n\tdefer u.Close()\n\n\tl1 := mustListen()\n\tdefer l1.Close()\n\tu1 := mustListenPacket(l1.Addr().String())\n\tdefer u1.Close()\n\tl2 := mustListen()\n\tdefer l2.Close()\n\tu2 := mustListenPacket(l2.Addr().String())\n\tdefer u2.Close()\n\tl3 := mustListen()\n\tdefer l3.Close()\n\tu3 := mustListenPacket(l3.Addr().String())\n\tdefer u3.Close()\n\tl4 := mustListen()\n\tdefer l4.Close()\n\tu4 := mustListenPacket(l4.Addr().String())\n\tdefer u4.Close()\n\n\tgo Main(\"a\", \"X\", \"\", \"\", \"\", nil, u, l, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"Y\", \"\", \"\", \"\", dial(a), u1, l1, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"Z\", \"\", \"\", \"\", dial(a), u2, l2, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"V\", \"\", \"\", \"\", dial(a), u3, l3, nil, 1e9, 1e8, 3e9)\n\tgo Main(\"a\", \"W\", \"\", \"\", \"\", dial(a), u4, l4, nil, 1e9, 1e8, 3e9)\n\n\tcl := dial(l.Addr().String())\n\tcl.Set(\"\/ctl\/cal\/1\", store.Missing, nil)\n\tcl.Set(\"\/ctl\/cal\/2\", store.Missing, nil)\n\tcl.Set(\"\/ctl\/cal\/3\", store.Missing, nil)\n\tcl.Set(\"\/ctl\/cal\/4\", store.Missing, nil)\n\n\tcls := []*doozer.Conn{\n\t\tcl,\n\t\tdial(l1.Addr().String()),\n\t\tdial(l2.Addr().String()),\n\t\tdial(l3.Addr().String()),\n\t\tdial(l4.Addr().String()),\n\t}\n\n\tconst con = 2000\n\tc := make(chan int, b.N)\n\ttimes := make([]int64, b.N)\n\tdone := make(chan bool, con)\n\tf := func() {\n\t\tfor i := range c {\n\t\t\ta := time.Nanoseconds()\n\t\t\tcls[i%len(cls)].Set(\"\/test\", store.Clobber, nil)\n\t\t\tb := time.Nanoseconds()\n\t\t\ttimes[i] = b - a\n\t\t}\n\t\tdone <- true\n\t}\n\tfor i := 0; i < con; i++ {\n\t\tgo f()\n\t}\n\n\tprintln(\"---\")\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tc <- i\n\t}\n\tclose(c)\n\tfor i := 0; i < con; i++ {\n\t\t<-done\n\t}\n\tb.StopTimer()\n\tfor _, t := range times {\n\t\tprintln(\"el\", t)\n\t}\n}\n\n\nfunc dial(addr string) *doozer.Conn {\n\tc, err := doozer.Dial(addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn c\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage runtime_test\n\nimport (\n\t\"runtime\"\n\t\"testing\"\n)\n\nfunc TestGcSys(t *testing.T) {\n\tif runtime.GOARCH != \"amd64\" {\n\t\t\/\/ TODO(adg): remove this when precise gc is implemented\n\t\tt.Logf(\"skipping on non-amd64 systems\")\n\t\treturn\n\t}\n\tmemstats := new(runtime.MemStats)\n\truntime.GC()\n\truntime.ReadMemStats(memstats)\n\tsys := memstats.Sys\n\n\truntime.MemProfileRate = 0 \/\/ disable profiler\n\n\titercount := 1000000\n\tif testing.Short() {\n\t\titercount = 100000\n\t}\n\tfor i := 0; i < itercount; i++ {\n\t\tworkthegc()\n\t}\n\n\t\/\/ Should only be using a few MB.\n\truntime.ReadMemStats(memstats)\n\tif sys > memstats.Sys {\n\t\tsys = 0\n\t} else {\n\t\tsys = memstats.Sys - sys\n\t}\n\tt.Logf(\"used %d extra bytes\", sys)\n\tif sys > 4<<20 {\n\t\tt.Fatalf(\"using too much memory: %d bytes\", sys)\n\t}\n}\n\nfunc workthegc() []byte {\n\treturn make([]byte, 1029)\n}\n<commit_msg>runtime: relax TestGcSys<commit_after>\/\/ Copyright 2011 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage runtime_test\n\nimport (\n\t\"runtime\"\n\t\"testing\"\n)\n\nfunc TestGcSys(t *testing.T) {\n\tmemstats := new(runtime.MemStats)\n\truntime.GC()\n\truntime.ReadMemStats(memstats)\n\tsys := memstats.Sys\n\n\truntime.MemProfileRate = 0 \/\/ disable profiler\n\n\titercount := 1000000\n\tif testing.Short() {\n\t\titercount = 100000\n\t}\n\tfor i := 0; i < itercount; i++ {\n\t\tworkthegc()\n\t}\n\n\t\/\/ Should only be using a few MB.\n\t\/\/ We allocated 100 MB or (if not short) 1 GB.\n\truntime.ReadMemStats(memstats)\n\tif sys > memstats.Sys {\n\t\tsys = 0\n\t} else {\n\t\tsys = memstats.Sys - sys\n\t}\n\tt.Logf(\"used %d extra bytes\", sys)\n\tif sys > 16<<20 {\n\t\tt.Fatalf(\"using too much memory: %d bytes\", sys)\n\t}\n}\n\nfunc workthegc() []byte {\n\treturn make([]byte, 1029)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage testing\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype InternalExample struct {\n\tName   string\n\tF      func()\n\tOutput string\n}\n\nfunc RunExamples(examples []InternalExample) (ok bool) {\n\tok = true\n\n\tvar eg InternalExample\n\n\tstdout, stderr := os.Stdout, os.Stderr\n\tdefer func() {\n\t\tos.Stdout, os.Stderr = stdout, stderr\n\t\tif e := recover(); e != nil {\n\t\t\tfmt.Printf(\"--- FAIL: %s\\npanic: %v\\n\", eg.Name, e)\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\tfor _, eg = range examples {\n\t\tif *chatty {\n\t\t\tfmt.Printf(\"=== RUN: %s\\n\", eg.Name)\n\t\t}\n\n\t\t\/\/ capture stdout and stderr\n\t\tr, w, err := os.Pipe()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tos.Stdout, os.Stderr = w, w\n\t\toutC := make(chan string)\n\t\tgo func() {\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\t_, err := io.Copy(buf, r)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(stderr, \"testing: copying pipe: %v\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\toutC <- buf.String()\n\t\t}()\n\n\t\t\/\/ run example\n\t\tt0 := time.Now()\n\t\teg.F()\n\t\tdt := time.Now().Sub(t0)\n\n\t\t\/\/ close pipe, restore stdout\/stderr, get output\n\t\tw.Close()\n\t\tos.Stdout, os.Stderr = stdout, stderr\n\t\tout := <-outC\n\n\t\t\/\/ report any errors\n\t\ttstr := fmt.Sprintf(\"(%.2f seconds)\", dt.Seconds())\n\t\tif g, e := strings.TrimSpace(out), strings.TrimSpace(eg.Output); g != e {\n\t\t\tfmt.Printf(\"--- FAIL: %s %s\\ngot:\\n%s\\nwant:\\n%s\\n\",\n\t\t\t\teg.Name, tstr, g, e)\n\t\t\tok = false\n\t\t} else if *chatty {\n\t\t\tfmt.Printf(\"--- PASS: %s %s\\n\", eg.Name, tstr)\n\t\t}\n\t}\n\n\treturn\n}\n<commit_msg>testing: do not recover example's panic         So as to give out stack trace for panic in examples.         This behavior also matches the tests'.         Fixes #2691.<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage testing\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype InternalExample struct {\n\tName   string\n\tF      func()\n\tOutput string\n}\n\nfunc RunExamples(examples []InternalExample) (ok bool) {\n\tok = true\n\n\tvar eg InternalExample\n\n\tstdout, stderr := os.Stdout, os.Stderr\n\n\tfor _, eg = range examples {\n\t\tif *chatty {\n\t\t\tfmt.Printf(\"=== RUN: %s\\n\", eg.Name)\n\t\t}\n\n\t\t\/\/ capture stdout and stderr\n\t\tr, w, err := os.Pipe()\n\t\tif err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tos.Stdout, os.Stderr = w, w\n\t\toutC := make(chan string)\n\t\tgo func() {\n\t\t\tbuf := new(bytes.Buffer)\n\t\t\t_, err := io.Copy(buf, r)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Fprintf(stderr, \"testing: copying pipe: %v\\n\", err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\toutC <- buf.String()\n\t\t}()\n\n\t\t\/\/ run example\n\t\tt0 := time.Now()\n\t\teg.F()\n\t\tdt := time.Now().Sub(t0)\n\n\t\t\/\/ close pipe, restore stdout\/stderr, get output\n\t\tw.Close()\n\t\tos.Stdout, os.Stderr = stdout, stderr\n\t\tout := <-outC\n\n\t\t\/\/ report any errors\n\t\ttstr := fmt.Sprintf(\"(%.2f seconds)\", dt.Seconds())\n\t\tif g, e := strings.TrimSpace(out), strings.TrimSpace(eg.Output); g != e {\n\t\t\tfmt.Printf(\"--- FAIL: %s %s\\ngot:\\n%s\\nwant:\\n%s\\n\",\n\t\t\t\teg.Name, tstr, g, e)\n\t\t\tok = false\n\t\t} else if *chatty {\n\t\t\tfmt.Printf(\"--- PASS: %s %s\\n\", eg.Name, tstr)\n\t\t}\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package class\n\nimport (\n\t\"fmt\"\n\t. \"jvmgo\/any\"\n\t\"jvmgo\/classfile\"\n\t\"jvmgo\/classpath\"\n\t\"jvmgo\/jvm\/jerrors\"\n\t\"jvmgo\/jvm\/options\"\n)\n\nconst (\n\tjlObjectClassName       = \"java\/lang\/Object\"\n\tjlClassClassName        = \"java\/lang\/Class\"\n\tjlCloneableClassName    = \"java\/lang\/Cloneable\"\n\tioSerializableClassName = \"java\/io\/Serializable\"\n\tjlThreadClassName       = \"java\/lang\/Thread\"\n\tjlStringClassName       = \"java\/lang\/String\"\n)\n\nvar (\n\tbootLoader           *ClassLoader \/\/ bootstrap class loader\n\t_jlObjectClass       *Class\n\t_jlClassClass        *Class\n\t_jlCloneableClass    *Class\n\t_ioSerializableClass *Class\n\t_jlThreadClass       *Class\n\t_jlStringClass       *Class\n)\n\n\/*\nclass names:\n    - primitive types: boolean, byte, int ...\n    - primitive arrays: [Z, [B, [I ...\n    - non-array classes: java\/lang\/Object ...\n    - array classes: [Ljava\/lang\/Object; ...\n*\/\n\n\/\/ the bootstrap class loader\ntype ClassLoader struct {\n\tclassPath *classpath.ClassPath\n\tclassMap  map[string]*Class\n}\n\nfunc BootLoader() *ClassLoader {\n\treturn bootLoader\n}\n\nfunc InitBootLoader(cp *classpath.ClassPath) {\n\tbootLoader = &ClassLoader{\n\t\tclassPath: cp,\n\t\tclassMap:  map[string]*Class{},\n\t}\n\tbootLoader._init()\n}\n\nfunc (self *ClassLoader) ClassPath() *classpath.ClassPath {\n\treturn self.classPath\n}\n\nfunc (self *ClassLoader) _init() {\n\t_jlObjectClass = self.LoadClass(jlObjectClassName)\n\t_jlClassClass = self.LoadClass(jlClassClassName)\n\tfor _, class := range self.classMap {\n\t\tif class.jClass == nil {\n\t\t\tclass.jClass = _jlClassClass.NewObj()\n\t\t\tclass.jClass.extra = class\n\t\t}\n\t}\n\t_jlCloneableClass = self.LoadClass(jlCloneableClassName)\n\t_ioSerializableClass = self.LoadClass(ioSerializableClassName)\n\t_jlThreadClass = self.LoadClass(jlThreadClassName)\n\t_jlStringClass = self.LoadClass(jlStringClassName)\n\tself.loadPrimitiveClasses()\n\tself.loadPrimitiveArrayClasses()\n}\n\nfunc (self *ClassLoader) loadPrimitiveClasses() {\n\tfor primitiveType, _ := range primitiveTypes {\n\t\tself.loadPrimitiveClass(primitiveType)\n\t}\n}\nfunc (self *ClassLoader) loadPrimitiveClass(className string) {\n\tclass := &Class{name: className}\n\t\/\/class.classLoader = self\n\tclass.jClass = _jlClassClass.NewObj()\n\tclass.jClass.extra = class\n\tclass.MarkInitialized()\n\tself.classMap[className] = class\n}\n\nfunc (self *ClassLoader) loadPrimitiveArrayClasses() {\n\tfor _, descriptor := range primitiveTypes {\n\t\tself.loadArrayClass(\"[\" + descriptor)\n\t}\n}\nfunc (self *ClassLoader) loadArrayClass(className string) *Class {\n\tclass := &Class{name: className}\n\t\/\/class.classLoader = self\n\tclass.superClass = _jlObjectClass\n\tclass.interfaces = []*Class{_jlCloneableClass, _ioSerializableClass}\n\tclass.jClass = _jlClassClass.NewObj()\n\tclass.jClass.extra = class\n\tcreateVtable(class)\n\tclass.MarkInitialized()\n\tself.classMap[className] = class\n\treturn class\n}\n\nfunc (self *ClassLoader) getRefArrayClass(componentClass *Class) *Class {\n\tarrClassName := \"[L\" + componentClass.Name() + \";\"\n\treturn self._getRefArrayClass(arrClassName)\n}\nfunc (self *ClassLoader) _getRefArrayClass(arrClassName string) *Class {\n\tif arrClass, ok := self.classMap[arrClassName]; ok {\n\t\treturn arrClass\n\t}\n\treturn self.loadArrayClass(arrClassName)\n}\n\n\/\/ todo\nfunc (self *ClassLoader) GetPrimitiveClass(name string) *Class {\n\treturn self.getClass(name)\n}\n\nfunc (self *ClassLoader) JLObjectClass() *Class {\n\treturn _jlObjectClass\n}\nfunc (self *ClassLoader) JLClassClass() *Class {\n\treturn _jlClassClass\n}\nfunc (self *ClassLoader) JLStringClass() *Class {\n\treturn _jlStringClass\n}\nfunc (self *ClassLoader) JLThreadClass() *Class {\n\treturn _jlThreadClass\n}\n\n\/\/ todo dangerous\nfunc (self *ClassLoader) getClass(name string) *Class {\n\tif class, ok := self.classMap[name]; ok {\n\t\treturn class\n\t}\n\tpanic(\"class not loaded! \" + name)\n}\n\nfunc (self *ClassLoader) LoadClass(name string) *Class {\n\tif class, ok := self.classMap[name]; ok {\n\t\t\/\/ already loaded\n\t\treturn class\n\t} else if name[0] == '[' {\n\t\t\/\/ array class\n\t\treturn self._getRefArrayClass(name)\n\t} else {\n\t\treturn self.reallyLoadClass(name)\n\t}\n}\n\nfunc (self *ClassLoader) reallyLoadClass(name string) *Class {\n\tcpEntry, data := self.readClassData(name)\n\tclass := self._loadClass(name, data)\n\tclass.loadedFrom = cpEntry\n\n\tif options.VerboseClass {\n\t\tfmt.Printf(\"[Loaded %s from %s]\\n\", name, cpEntry)\n\t}\n\n\treturn class\n}\n\nfunc (self *ClassLoader) readClassData(name string) (classpath.ClassPathEntry, []byte) {\n\tcpEntry, classData, err := self.classPath.ReadClassData(name)\n\tif err != nil {\n\t\tpanic(jerrors.NewClassNotFoundError(SlashToDot(name)))\n\t}\n\n\treturn cpEntry, classData\n}\n\nfunc (self *ClassLoader) parseClassData(name string, data []byte) *Class {\n\tcf, err := classfile.ParseClassFile(data)\n\tif err != nil {\n\t\t\/\/ todo\n\t\tpanic(\"failed to parse class file: \" + name + \"!\" + err.Error())\n\t}\n\n\treturn newClass(cf)\n}\n\nfunc (self *ClassLoader) _loadClass(name string, data []byte) *Class {\n\tclass := self.parseClassData(name, data)\n\thackClass(class)\n\tself.resolveSuperClass(class)\n\tself.resolveInterfaces(class)\n\tcalcStaticFieldSlots(class)\n\tcalcInstanceFieldSlots(class)\n\tcreateVtable(class)\n\tprepare(class)\n\t\/\/ todo\n\t\/\/class.classLoader = self\n\tself.classMap[name] = class\n\n\tif _jlClassClass != nil {\n\t\tclass.jClass = _jlClassClass.NewObj()\n\t\tclass.jClass.extra = class\n\t}\n\n\treturn class\n}\n\n\/\/ todo\nfunc hackClass(class *Class) {\n\tif class.name == \"java\/lang\/ClassLoader\" {\n\t\tloadLibrary := class.GetStaticMethod(\"loadLibrary\", \"(Ljava\/lang\/Class;Ljava\/lang\/String;Z)V\")\n\t\tloadLibrary.code = []byte{0xb1} \/\/ return void\n\t}\n}\n\n\/\/ todo\nfunc (self *ClassLoader) resolveSuperClass(class *Class) {\n\tif class.superClassName != \"\" {\n\t\tclass.superClass = self.LoadClass(class.superClassName)\n\t}\n}\nfunc (self *ClassLoader) resolveInterfaces(class *Class) {\n\tinterfaceCount := len(class.interfaceNames)\n\tif interfaceCount > 0 {\n\t\tclass.interfaces = make([]*Class, interfaceCount)\n\t\tfor i, interfaceName := range class.interfaceNames {\n\t\t\tclass.interfaces[i] = self.LoadClass(interfaceName)\n\t\t}\n\t}\n}\n\nfunc calcStaticFieldSlots(class *Class) {\n\tslotId := uint(0)\n\tfor _, field := range class.fields {\n\t\tif field.IsStatic() {\n\t\t\tfield.slot = slotId\n\t\t\tslotId++\n\t\t}\n\t}\n\tclass.staticFieldCount = slotId\n}\n\nfunc calcInstanceFieldSlots(class *Class) {\n\tslotId := uint(0)\n\tif class.superClassName != \"\" {\n\t\tslotId = class.superClass.instanceFieldCount\n\t}\n\tfor _, field := range class.fields {\n\t\tif !field.IsStatic() {\n\t\t\tfield.slot = slotId\n\t\t\tslotId++\n\t\t}\n\t}\n\tclass.instanceFieldCount = slotId\n}\n\nfunc prepare(class *Class) {\n\tclass.staticFieldValues = make([]Any, class.staticFieldCount)\n\tfor _, field := range class.fields {\n\t\tif field.IsStatic() {\n\t\t\tclass.staticFieldValues[field.slot] = field.defaultValue()\n\t\t}\n\t}\n}\n\n\/\/ todo\nfunc (self *ClassLoader) DefineClass(name string, data []byte) *Class {\n\treturn self._loadClass(name, data)\n}\n<commit_msg>code refactor<commit_after>package class\n\nimport (\n\t\"fmt\"\n\t. \"jvmgo\/any\"\n\t\"jvmgo\/classfile\"\n\t\"jvmgo\/classpath\"\n\t\"jvmgo\/jvm\/jerrors\"\n\t\"jvmgo\/jvm\/options\"\n)\n\nconst (\n\tjlObjectClassName       = \"java\/lang\/Object\"\n\tjlClassClassName        = \"java\/lang\/Class\"\n\tjlStringClassName       = \"java\/lang\/String\"\n\tjlThreadClassName       = \"java\/lang\/Thread\"\n\tjlCloneableClassName    = \"java\/lang\/Cloneable\"\n\tioSerializableClassName = \"java\/io\/Serializable\"\n)\n\nvar (\n\tbootLoader           *ClassLoader \/\/ bootstrap class loader\n\t_jlObjectClass       *Class\n\t_jlClassClass        *Class\n\t_jlStringClass       *Class\n\t_jlThreadClass       *Class\n\t_jlCloneableClass    *Class\n\t_ioSerializableClass *Class\n)\n\n\/*\nclass names:\n    - primitive types: boolean, byte, int ...\n    - primitive arrays: [Z, [B, [I ...\n    - non-array classes: java\/lang\/Object ...\n    - array classes: [Ljava\/lang\/Object; ...\n*\/\n\n\/\/ the bootstrap class loader\ntype ClassLoader struct {\n\tclassPath *classpath.ClassPath\n\tclassMap  map[string]*Class\n}\n\nfunc BootLoader() *ClassLoader {\n\treturn bootLoader\n}\n\nfunc InitBootLoader(cp *classpath.ClassPath) {\n\tbootLoader = &ClassLoader{\n\t\tclassPath: cp,\n\t\tclassMap:  map[string]*Class{},\n\t}\n\tbootLoader._init()\n}\n\nfunc (self *ClassLoader) _init() {\n\t_jlObjectClass = self.LoadClass(jlObjectClassName)\n\t_jlClassClass = self.LoadClass(jlClassClassName)\n\tfor _, class := range self.classMap {\n\t\tif class.jClass == nil {\n\t\t\tclass.jClass = _jlClassClass.NewObj()\n\t\t\tclass.jClass.extra = class\n\t\t}\n\t}\n\t_jlCloneableClass = self.LoadClass(jlCloneableClassName)\n\t_ioSerializableClass = self.LoadClass(ioSerializableClassName)\n\t_jlThreadClass = self.LoadClass(jlThreadClassName)\n\t_jlStringClass = self.LoadClass(jlStringClassName)\n\tself.loadPrimitiveClasses()\n\tself.loadPrimitiveArrayClasses()\n}\n\nfunc (self *ClassLoader) loadPrimitiveClasses() {\n\tfor primitiveType, _ := range primitiveTypes {\n\t\tself.loadPrimitiveClass(primitiveType)\n\t}\n}\nfunc (self *ClassLoader) loadPrimitiveClass(className string) {\n\tclass := &Class{name: className}\n\t\/\/class.classLoader = self\n\tclass.jClass = _jlClassClass.NewObj()\n\tclass.jClass.extra = class\n\tclass.MarkInitialized()\n\tself.classMap[className] = class\n}\n\nfunc (self *ClassLoader) loadPrimitiveArrayClasses() {\n\tfor _, descriptor := range primitiveTypes {\n\t\tself.loadArrayClass(\"[\" + descriptor)\n\t}\n}\nfunc (self *ClassLoader) loadArrayClass(className string) *Class {\n\tclass := &Class{name: className}\n\t\/\/class.classLoader = self\n\tclass.superClass = _jlObjectClass\n\tclass.interfaces = []*Class{_jlCloneableClass, _ioSerializableClass}\n\tclass.jClass = _jlClassClass.NewObj()\n\tclass.jClass.extra = class\n\tcreateVtable(class)\n\tclass.MarkInitialized()\n\tself.classMap[className] = class\n\treturn class\n}\n\nfunc (self *ClassLoader) getRefArrayClass(componentClass *Class) *Class {\n\tarrClassName := \"[L\" + componentClass.Name() + \";\"\n\treturn self._getRefArrayClass(arrClassName)\n}\nfunc (self *ClassLoader) _getRefArrayClass(arrClassName string) *Class {\n\tif arrClass, ok := self.classMap[arrClassName]; ok {\n\t\treturn arrClass\n\t}\n\treturn self.loadArrayClass(arrClassName)\n}\n\nfunc (self *ClassLoader) ClassPath() *classpath.ClassPath {\n\treturn self.classPath\n}\n\nfunc (self *ClassLoader) JLObjectClass() *Class {\n\treturn _jlObjectClass\n}\nfunc (self *ClassLoader) JLClassClass() *Class {\n\treturn _jlClassClass\n}\nfunc (self *ClassLoader) JLStringClass() *Class {\n\treturn _jlStringClass\n}\nfunc (self *ClassLoader) JLThreadClass() *Class {\n\treturn _jlThreadClass\n}\n\n\/\/ todo\nfunc (self *ClassLoader) GetPrimitiveClass(name string) *Class {\n\treturn self.getClass(name)\n}\n\n\/\/ todo dangerous\nfunc (self *ClassLoader) getClass(name string) *Class {\n\tif class, ok := self.classMap[name]; ok {\n\t\treturn class\n\t}\n\tpanic(\"class not loaded! \" + name)\n}\n\nfunc (self *ClassLoader) LoadClass(name string) *Class {\n\tif class, ok := self.classMap[name]; ok {\n\t\t\/\/ already loaded\n\t\treturn class\n\t} else if name[0] == '[' {\n\t\t\/\/ array class\n\t\treturn self._getRefArrayClass(name)\n\t} else {\n\t\treturn self.reallyLoadClass(name)\n\t}\n}\n\nfunc (self *ClassLoader) reallyLoadClass(name string) *Class {\n\tcpEntry, data := self.readClassData(name)\n\tclass := self._loadClass(name, data)\n\tclass.loadedFrom = cpEntry\n\n\tif options.VerboseClass {\n\t\tfmt.Printf(\"[Loaded %s from %s]\\n\", name, cpEntry)\n\t}\n\n\treturn class\n}\n\nfunc (self *ClassLoader) readClassData(name string) (classpath.ClassPathEntry, []byte) {\n\tcpEntry, classData, err := self.classPath.ReadClassData(name)\n\tif err != nil {\n\t\tpanic(jerrors.NewClassNotFoundError(SlashToDot(name)))\n\t}\n\n\treturn cpEntry, classData\n}\n\nfunc (self *ClassLoader) parseClassData(name string, data []byte) *Class {\n\tcf, err := classfile.ParseClassFile(data)\n\tif err != nil {\n\t\t\/\/ todo\n\t\tpanic(\"failed to parse class file: \" + name + \"!\" + err.Error())\n\t}\n\n\treturn newClass(cf)\n}\n\nfunc (self *ClassLoader) _loadClass(name string, data []byte) *Class {\n\tclass := self.parseClassData(name, data)\n\thackClass(class)\n\tself.resolveSuperClass(class)\n\tself.resolveInterfaces(class)\n\tcalcStaticFieldSlots(class)\n\tcalcInstanceFieldSlots(class)\n\tcreateVtable(class)\n\tprepare(class)\n\t\/\/ todo\n\t\/\/class.classLoader = self\n\tself.classMap[name] = class\n\n\tif _jlClassClass != nil {\n\t\tclass.jClass = _jlClassClass.NewObj()\n\t\tclass.jClass.extra = class\n\t}\n\n\treturn class\n}\n\n\/\/ todo\nfunc hackClass(class *Class) {\n\tif class.name == \"java\/lang\/ClassLoader\" {\n\t\tloadLibrary := class.GetStaticMethod(\"loadLibrary\", \"(Ljava\/lang\/Class;Ljava\/lang\/String;Z)V\")\n\t\tloadLibrary.code = []byte{0xb1} \/\/ return void\n\t}\n}\n\n\/\/ todo\nfunc (self *ClassLoader) resolveSuperClass(class *Class) {\n\tif class.superClassName != \"\" {\n\t\tclass.superClass = self.LoadClass(class.superClassName)\n\t}\n}\nfunc (self *ClassLoader) resolveInterfaces(class *Class) {\n\tinterfaceCount := len(class.interfaceNames)\n\tif interfaceCount > 0 {\n\t\tclass.interfaces = make([]*Class, interfaceCount)\n\t\tfor i, interfaceName := range class.interfaceNames {\n\t\t\tclass.interfaces[i] = self.LoadClass(interfaceName)\n\t\t}\n\t}\n}\n\nfunc calcStaticFieldSlots(class *Class) {\n\tslotId := uint(0)\n\tfor _, field := range class.fields {\n\t\tif field.IsStatic() {\n\t\t\tfield.slot = slotId\n\t\t\tslotId++\n\t\t}\n\t}\n\tclass.staticFieldCount = slotId\n}\n\nfunc calcInstanceFieldSlots(class *Class) {\n\tslotId := uint(0)\n\tif class.superClassName != \"\" {\n\t\tslotId = class.superClass.instanceFieldCount\n\t}\n\tfor _, field := range class.fields {\n\t\tif !field.IsStatic() {\n\t\t\tfield.slot = slotId\n\t\t\tslotId++\n\t\t}\n\t}\n\tclass.instanceFieldCount = slotId\n}\n\nfunc prepare(class *Class) {\n\tclass.staticFieldValues = make([]Any, class.staticFieldCount)\n\tfor _, field := range class.fields {\n\t\tif field.IsStatic() {\n\t\t\tclass.staticFieldValues[field.slot] = field.defaultValue()\n\t\t}\n\t}\n}\n\n\/\/ todo\nfunc (self *ClassLoader) DefineClass(name string, data []byte) *Class {\n\treturn self._loadClass(name, data)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2022 Gravitational, Inc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage webauthncli\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"strings\"\n\n\t\"github.com\/gravitational\/teleport\/api\/client\/proto\"\n\t\"github.com\/gravitational\/teleport\/lib\/auth\/touchid\"\n\t\"github.com\/gravitational\/trace\"\n\n\twanlib \"github.com\/gravitational\/teleport\/lib\/auth\/webauthn\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ AuthenticatorAttachment allows callers to choose a specific attachment.\ntype AuthenticatorAttachment int\n\nconst (\n\tAttachmentAuto AuthenticatorAttachment = iota\n\tAttachmentCrossPlatform\n\tAttachmentPlatform\n)\n\n\/\/ LoginOpts groups non-mandatory options for Login.\ntype LoginOpts struct {\n\t\/\/ User is the desired credential username for login.\n\t\/\/ If empty, Login may either choose a credential or error due to ambiguity.\n\tUser string\n\t\/\/ OptimisticAssertion allows Login to skip credential listing and attempt\n\t\/\/ to assert directly. The drawback of an optimistic assertion is that the\n\t\/\/ authenticator chooses the login credential, so Login can't guarantee that\n\t\/\/ the User field will be respected. The upside is that it saves a touch for\n\t\/\/ some devices.\n\t\/\/ Login may decide to forego optimistic assertions if it wouldn't save a\n\t\/\/ touch.\n\tOptimisticAssertion bool\n\t\/\/ AuthenticatorAttachment specifies the desired authenticator attachment.\n\tAuthenticatorAttachment AuthenticatorAttachment\n}\n\n\/\/ Login performs client-side, U2F-compatible, Webauthn login.\n\/\/ This method blocks until either device authentication is successful or the\n\/\/ context is cancelled. Calling Login without a deadline or cancel condition\n\/\/ may cause it to block forever.\n\/\/ The informed user is used to disambiguate credentials in case of passwordless\n\/\/ logins.\n\/\/ It returns an MFAAuthenticateResponse and the credential user, if a resident\n\/\/ credential is used.\n\/\/ The caller is expected to react to LoginPrompt in order to prompt the user at\n\/\/ appropriate times. Login may choose different flows depending on the type of\n\/\/ authentication and connected devices.\nfunc Login(\n\tctx context.Context,\n\torigin string, assertion *wanlib.CredentialAssertion, prompt LoginPrompt, opts *LoginOpts,\n) (*proto.MFAAuthenticateResponse, string, error) {\n\t\/\/ origin vs RPID sanity check.\n\t\/\/ Doesn't necessarily means a failure, but it's likely to be one.\n\tswitch rpID := assertion.Response.RelyingPartyID; {\n\tcase origin == \"\", assertion == nil: \/\/ let downstream handle empty\/nil\n\tcase !strings.HasPrefix(origin, \"https:\/\/\"+rpID):\n\t\tlog.Warnf(\"\"+\n\t\t\t\"WebAuthn: origin and RPID mismatch, \"+\n\t\t\t\"if you are having authentication problems double check your proxy address \"+\n\t\t\t\"(%q vs %q)\", origin, rpID)\n\t}\n\n\tvar attachment AuthenticatorAttachment\n\tvar user string\n\tif opts != nil {\n\t\tattachment = opts.AuthenticatorAttachment\n\t\tuser = opts.User\n\t}\n\n\tswitch attachment {\n\tcase AttachmentCrossPlatform:\n\t\tlog.Debug(\"Cross-platform login\")\n\t\treturn crossPlatformLogin(ctx, origin, assertion, prompt, opts)\n\tcase AttachmentPlatform:\n\t\tlog.Debug(\"Platform login\")\n\t\treturn platformLogin(origin, user, assertion)\n\tdefault:\n\t\tlog.Debug(\"Attempting platform login\")\n\t\tresp, credentialUser, err := platformLogin(origin, user, assertion)\n\t\tif !errors.Is(err, &touchid.ErrAttemptFailed{}) {\n\t\t\treturn resp, credentialUser, trace.Wrap(err)\n\t\t}\n\n\t\tlog.WithError(err).Debug(\"Platform login failed, falling back to cross-platform\")\n\t\treturn crossPlatformLogin(ctx, origin, assertion, prompt, opts)\n\t}\n}\n\nfunc crossPlatformLogin(\n\tctx context.Context,\n\torigin string, assertion *wanlib.CredentialAssertion, prompt LoginPrompt, opts *LoginOpts,\n) (*proto.MFAAuthenticateResponse, string, error) {\n\tif IsFIDO2Available() {\n\t\tlog.Debug(\"FIDO2: Using libfido2 for assertion\")\n\t\treturn FIDO2Login(ctx, origin, assertion, prompt, opts)\n\t}\n\n\tprompt.PromptTouch()\n\tresp, err := U2FLogin(ctx, origin, assertion)\n\treturn resp, \"\" \/* credentialUser *\/, err\n}\n\nfunc platformLogin(origin, user string, assertion *wanlib.CredentialAssertion) (*proto.MFAAuthenticateResponse, string, error) {\n\tresp, credentialUser, err := touchid.AttemptLogin(origin, user, assertion)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\treturn &proto.MFAAuthenticateResponse{\n\t\tResponse: &proto.MFAAuthenticateResponse_Webauthn{\n\t\t\tWebauthn: wanlib.CredentialAssertionResponseToProto(resp),\n\t\t},\n\t}, credentialUser, nil\n}\n\n\/\/ Register performs client-side, U2F-compatible, Webauthn registration.\n\/\/ This method blocks until either device authentication is successful or the\n\/\/ context is cancelled. Calling Register without a deadline or cancel condition\n\/\/ may cause it block forever.\n\/\/ The caller is expected to react to RegisterPrompt in order to prompt the user\n\/\/ at appropriate times. Register may choose different flows depending on the\n\/\/ type of authentication and connected devices.\nfunc Register(\n\tctx context.Context,\n\torigin string, cc *wanlib.CredentialCreation, prompt RegisterPrompt) (*proto.MFARegisterResponse, error) {\n\tif IsFIDO2Available() {\n\t\tlog.Debug(\"FIDO2: Using libfido2 for credential creation\")\n\t\treturn FIDO2Register(ctx, origin, cc, prompt)\n\t}\n\n\tprompt.PromptTouch()\n\treturn U2FRegister(ctx, origin, cc)\n}\n<commit_msg>Do not dereference assertion before checking for nil (#13761)<commit_after>\/\/ Copyright 2022 Gravitational, Inc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage webauthncli\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"strings\"\n\n\t\"github.com\/gravitational\/teleport\/api\/client\/proto\"\n\t\"github.com\/gravitational\/teleport\/lib\/auth\/touchid\"\n\t\"github.com\/gravitational\/trace\"\n\n\twanlib \"github.com\/gravitational\/teleport\/lib\/auth\/webauthn\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ AuthenticatorAttachment allows callers to choose a specific attachment.\ntype AuthenticatorAttachment int\n\nconst (\n\tAttachmentAuto AuthenticatorAttachment = iota\n\tAttachmentCrossPlatform\n\tAttachmentPlatform\n)\n\n\/\/ LoginOpts groups non-mandatory options for Login.\ntype LoginOpts struct {\n\t\/\/ User is the desired credential username for login.\n\t\/\/ If empty, Login may either choose a credential or error due to ambiguity.\n\tUser string\n\t\/\/ OptimisticAssertion allows Login to skip credential listing and attempt\n\t\/\/ to assert directly. The drawback of an optimistic assertion is that the\n\t\/\/ authenticator chooses the login credential, so Login can't guarantee that\n\t\/\/ the User field will be respected. The upside is that it saves a touch for\n\t\/\/ some devices.\n\t\/\/ Login may decide to forego optimistic assertions if it wouldn't save a\n\t\/\/ touch.\n\tOptimisticAssertion bool\n\t\/\/ AuthenticatorAttachment specifies the desired authenticator attachment.\n\tAuthenticatorAttachment AuthenticatorAttachment\n}\n\n\/\/ Login performs client-side, U2F-compatible, Webauthn login.\n\/\/ This method blocks until either device authentication is successful or the\n\/\/ context is cancelled. Calling Login without a deadline or cancel condition\n\/\/ may cause it to block forever.\n\/\/ The informed user is used to disambiguate credentials in case of passwordless\n\/\/ logins.\n\/\/ It returns an MFAAuthenticateResponse and the credential user, if a resident\n\/\/ credential is used.\n\/\/ The caller is expected to react to LoginPrompt in order to prompt the user at\n\/\/ appropriate times. Login may choose different flows depending on the type of\n\/\/ authentication and connected devices.\nfunc Login(\n\tctx context.Context,\n\torigin string, assertion *wanlib.CredentialAssertion, prompt LoginPrompt, opts *LoginOpts,\n) (*proto.MFAAuthenticateResponse, string, error) {\n\t\/\/ origin vs RPID sanity check.\n\t\/\/ Doesn't necessarily means a failure, but it's likely to be one.\n\tswitch {\n\tcase origin == \"\", assertion == nil: \/\/ let downstream handle empty\/nil\n\tcase !strings.HasPrefix(origin, \"https:\/\/\"+assertion.Response.RelyingPartyID):\n\t\tlog.Warnf(\"\"+\n\t\t\t\"WebAuthn: origin and RPID mismatch, \"+\n\t\t\t\"if you are having authentication problems double check your proxy address \"+\n\t\t\t\"(%q vs %q)\", origin, assertion.Response.RelyingPartyID)\n\t}\n\n\tvar attachment AuthenticatorAttachment\n\tvar user string\n\tif opts != nil {\n\t\tattachment = opts.AuthenticatorAttachment\n\t\tuser = opts.User\n\t}\n\n\tswitch attachment {\n\tcase AttachmentCrossPlatform:\n\t\tlog.Debug(\"Cross-platform login\")\n\t\treturn crossPlatformLogin(ctx, origin, assertion, prompt, opts)\n\tcase AttachmentPlatform:\n\t\tlog.Debug(\"Platform login\")\n\t\treturn platformLogin(origin, user, assertion)\n\tdefault:\n\t\tlog.Debug(\"Attempting platform login\")\n\t\tresp, credentialUser, err := platformLogin(origin, user, assertion)\n\t\tif !errors.Is(err, &touchid.ErrAttemptFailed{}) {\n\t\t\treturn resp, credentialUser, trace.Wrap(err)\n\t\t}\n\n\t\tlog.WithError(err).Debug(\"Platform login failed, falling back to cross-platform\")\n\t\treturn crossPlatformLogin(ctx, origin, assertion, prompt, opts)\n\t}\n}\n\nfunc crossPlatformLogin(\n\tctx context.Context,\n\torigin string, assertion *wanlib.CredentialAssertion, prompt LoginPrompt, opts *LoginOpts,\n) (*proto.MFAAuthenticateResponse, string, error) {\n\tif IsFIDO2Available() {\n\t\tlog.Debug(\"FIDO2: Using libfido2 for assertion\")\n\t\treturn FIDO2Login(ctx, origin, assertion, prompt, opts)\n\t}\n\n\tprompt.PromptTouch()\n\tresp, err := U2FLogin(ctx, origin, assertion)\n\treturn resp, \"\" \/* credentialUser *\/, err\n}\n\nfunc platformLogin(origin, user string, assertion *wanlib.CredentialAssertion) (*proto.MFAAuthenticateResponse, string, error) {\n\tresp, credentialUser, err := touchid.AttemptLogin(origin, user, assertion)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\treturn &proto.MFAAuthenticateResponse{\n\t\tResponse: &proto.MFAAuthenticateResponse_Webauthn{\n\t\t\tWebauthn: wanlib.CredentialAssertionResponseToProto(resp),\n\t\t},\n\t}, credentialUser, nil\n}\n\n\/\/ Register performs client-side, U2F-compatible, Webauthn registration.\n\/\/ This method blocks until either device authentication is successful or the\n\/\/ context is cancelled. Calling Register without a deadline or cancel condition\n\/\/ may cause it block forever.\n\/\/ The caller is expected to react to RegisterPrompt in order to prompt the user\n\/\/ at appropriate times. Register may choose different flows depending on the\n\/\/ type of authentication and connected devices.\nfunc Register(\n\tctx context.Context,\n\torigin string, cc *wanlib.CredentialCreation, prompt RegisterPrompt) (*proto.MFARegisterResponse, error) {\n\tif IsFIDO2Available() {\n\t\tlog.Debug(\"FIDO2: Using libfido2 for credential creation\")\n\t\treturn FIDO2Register(ctx, origin, cc, prompt)\n\t}\n\n\tprompt.PromptTouch()\n\treturn U2FRegister(ctx, origin, cc)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/  Copyright (c) 2014 Couchbase, Inc.\n\/\/  Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file\n\/\/  except in compliance with the License. You may obtain a copy of the License at\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/  Unless required by applicable law or agreed to in writing, software distributed under the\n\/\/  License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n\/\/  either express or implied. See the License for the specific language governing permissions\n\/\/  and limitations under the License.\n\npackage upside_down\n\nimport (\n\t\"github.com\/blevesearch\/bleve\/index\"\n\t\"github.com\/blevesearch\/bleve\/index\/store\"\n)\n\ntype UpsideDownCouchTermFieldReader struct {\n\tindexReader *IndexReader\n\titerator    store.KVIterator\n\tcount       uint64\n\tterm        []byte\n\tfield       uint16\n}\n\nfunc newUpsideDownCouchTermFieldReader(indexReader *IndexReader, term []byte, field uint16) (*UpsideDownCouchTermFieldReader, error) {\n\tdictionaryRow := NewDictionaryRow(term, field, 0)\n\tval, err := indexReader.kvreader.Get(dictionaryRow.Key())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif val == nil {\n\t\treturn &UpsideDownCouchTermFieldReader{\n\t\t\tcount: 0,\n\t\t\tterm:  term,\n\t\t\tfield: field,\n\t\t}, nil\n\t}\n\n\terr = dictionaryRow.parseDictionaryV(val)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttfr := NewTermFrequencyRow(term, field, \"\", 0, 0)\n\tit := indexReader.kvreader.PrefixIterator(tfr.Key())\n\n\treturn &UpsideDownCouchTermFieldReader{\n\t\tindexReader: indexReader,\n\t\titerator:    it,\n\t\tcount:       dictionaryRow.count,\n\t\tterm:        term,\n\t\tfield:       field,\n\t}, nil\n}\n\nfunc (r *UpsideDownCouchTermFieldReader) Count() uint64 {\n\treturn r.count\n}\n\nfunc (r *UpsideDownCouchTermFieldReader) Next() (*index.TermFieldDoc, error) {\n\tif r.iterator != nil {\n\t\tkey, val, valid := r.iterator.Current()\n\t\tif valid {\n\t\t\ttfr, err := NewTermFrequencyRowKV(key, val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tr.iterator.Next()\n\t\t\treturn &index.TermFieldDoc{\n\t\t\t\tID:      string(tfr.doc),\n\t\t\t\tFreq:    tfr.freq,\n\t\t\t\tNorm:    float64(tfr.norm),\n\t\t\t\tVectors: r.indexReader.index.termFieldVectorsFromTermVectors(tfr.vectors),\n\t\t\t}, nil\n\t\t}\n\t}\n\treturn nil, nil\n}\n\nfunc (r *UpsideDownCouchTermFieldReader) Advance(docID string) (*index.TermFieldDoc, error) {\n\tif r.iterator != nil {\n\t\ttfr := NewTermFrequencyRow(r.term, r.field, docID, 0, 0)\n\t\tr.iterator.Seek(tfr.Key())\n\t\tkey, val, valid := r.iterator.Current()\n\t\tif valid {\n\t\t\ttfr, err := NewTermFrequencyRowKV(key, val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tr.iterator.Next()\n\t\t\treturn &index.TermFieldDoc{\n\t\t\t\tID:      string(tfr.doc),\n\t\t\t\tFreq:    tfr.freq,\n\t\t\t\tNorm:    float64(tfr.norm),\n\t\t\t\tVectors: r.indexReader.index.termFieldVectorsFromTermVectors(tfr.vectors),\n\t\t\t}, nil\n\t\t}\n\t}\n\treturn nil, nil\n}\n\nfunc (r *UpsideDownCouchTermFieldReader) Close() error {\n\tif r.iterator != nil {\n\t\treturn r.iterator.Close()\n\t}\n\treturn nil\n}\n\ntype UpsideDownCouchDocIDReader struct {\n\tindexReader *IndexReader\n\titerator    store.KVIterator\n}\n\nfunc newUpsideDownCouchDocIDReader(indexReader *IndexReader, start, end string) (*UpsideDownCouchDocIDReader, error) {\n\tif start == \"\" {\n\t\tstart = string([]byte{0x0})\n\t}\n\tif end == \"\" {\n\t\tend = string([]byte{0xff})\n\t}\n\tbisr := NewBackIndexRow(start, nil, nil)\n\tbier := NewBackIndexRow(end, nil, nil)\n\tit := indexReader.kvreader.RangeIterator(bisr.Key(), bier.Key())\n\n\treturn &UpsideDownCouchDocIDReader{\n\t\tindexReader: indexReader,\n\t\titerator:    it,\n\t}, nil\n}\n\nfunc (r *UpsideDownCouchDocIDReader) Next() (string, error) {\n\tkey, val, valid := r.iterator.Current()\n\tif valid {\n\t\tbr, err := NewBackIndexRowKV(key, val)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tr.iterator.Next()\n\t\treturn string(br.doc), nil\n\t}\n\treturn \"\", nil\n}\n\nfunc (r *UpsideDownCouchDocIDReader) Advance(docID string) (string, error) {\n\tbir := NewBackIndexRow(docID, nil, nil)\n\tr.iterator.Seek(bir.Key())\n\tkey, val, valid := r.iterator.Current()\n\tif valid {\n\t\tbr, err := NewBackIndexRowKV(key, val)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tr.iterator.Next()\n\t\treturn string(br.doc), nil\n\t}\n\treturn \"\", nil\n}\n\nfunc (r *UpsideDownCouchDocIDReader) Close() error {\n\treturn r.iterator.Close()\n}\n<commit_msg>copy relevant k\/v pairs before advancing underlying iterator<commit_after>\/\/  Copyright (c) 2014 Couchbase, Inc.\n\/\/  Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file\n\/\/  except in compliance with the License. You may obtain a copy of the License at\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/  Unless required by applicable law or agreed to in writing, software distributed under the\n\/\/  License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n\/\/  either express or implied. See the License for the specific language governing permissions\n\/\/  and limitations under the License.\n\npackage upside_down\n\nimport (\n\t\"github.com\/blevesearch\/bleve\/index\"\n\t\"github.com\/blevesearch\/bleve\/index\/store\"\n)\n\ntype UpsideDownCouchTermFieldReader struct {\n\tindexReader *IndexReader\n\titerator    store.KVIterator\n\tcount       uint64\n\tterm        []byte\n\tfield       uint16\n}\n\nfunc newUpsideDownCouchTermFieldReader(indexReader *IndexReader, term []byte, field uint16) (*UpsideDownCouchTermFieldReader, error) {\n\tdictionaryRow := NewDictionaryRow(term, field, 0)\n\tval, err := indexReader.kvreader.Get(dictionaryRow.Key())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif val == nil {\n\t\treturn &UpsideDownCouchTermFieldReader{\n\t\t\tcount: 0,\n\t\t\tterm:  term,\n\t\t\tfield: field,\n\t\t}, nil\n\t}\n\n\terr = dictionaryRow.parseDictionaryV(val)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttfr := NewTermFrequencyRow(term, field, \"\", 0, 0)\n\tit := indexReader.kvreader.PrefixIterator(tfr.Key())\n\n\treturn &UpsideDownCouchTermFieldReader{\n\t\tindexReader: indexReader,\n\t\titerator:    it,\n\t\tcount:       dictionaryRow.count,\n\t\tterm:        term,\n\t\tfield:       field,\n\t}, nil\n}\n\nfunc (r *UpsideDownCouchTermFieldReader) Count() uint64 {\n\treturn r.count\n}\n\nfunc (r *UpsideDownCouchTermFieldReader) Next() (*index.TermFieldDoc, error) {\n\tif r.iterator != nil {\n\t\tkey, val, valid := r.iterator.Current()\n\t\tif valid {\n\t\t\ttfr, err := NewTermFrequencyRowKV(key, val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\trv := index.TermFieldDoc{\n\t\t\t\tID:      string(tfr.doc),\n\t\t\t\tFreq:    tfr.freq,\n\t\t\t\tNorm:    float64(tfr.norm),\n\t\t\t\tVectors: r.indexReader.index.termFieldVectorsFromTermVectors(tfr.vectors),\n\t\t\t}\n\t\t\tr.iterator.Next()\n\t\t\treturn &rv, nil\n\t\t}\n\t}\n\treturn nil, nil\n}\n\nfunc (r *UpsideDownCouchTermFieldReader) Advance(docID string) (*index.TermFieldDoc, error) {\n\tif r.iterator != nil {\n\t\ttfr := NewTermFrequencyRow(r.term, r.field, docID, 0, 0)\n\t\tr.iterator.Seek(tfr.Key())\n\t\tkey, val, valid := r.iterator.Current()\n\t\tif valid {\n\t\t\ttfr, err := NewTermFrequencyRowKV(key, val)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\trv := index.TermFieldDoc{\n\t\t\t\tID:      string(tfr.doc),\n\t\t\t\tFreq:    tfr.freq,\n\t\t\t\tNorm:    float64(tfr.norm),\n\t\t\t\tVectors: r.indexReader.index.termFieldVectorsFromTermVectors(tfr.vectors),\n\t\t\t}\n\t\t\tr.iterator.Next()\n\t\t\treturn &rv, nil\n\t\t}\n\t}\n\treturn nil, nil\n}\n\nfunc (r *UpsideDownCouchTermFieldReader) Close() error {\n\tif r.iterator != nil {\n\t\treturn r.iterator.Close()\n\t}\n\treturn nil\n}\n\ntype UpsideDownCouchDocIDReader struct {\n\tindexReader *IndexReader\n\titerator    store.KVIterator\n}\n\nfunc newUpsideDownCouchDocIDReader(indexReader *IndexReader, start, end string) (*UpsideDownCouchDocIDReader, error) {\n\tif start == \"\" {\n\t\tstart = string([]byte{0x0})\n\t}\n\tif end == \"\" {\n\t\tend = string([]byte{0xff})\n\t}\n\tbisr := NewBackIndexRow(start, nil, nil)\n\tbier := NewBackIndexRow(end, nil, nil)\n\tit := indexReader.kvreader.RangeIterator(bisr.Key(), bier.Key())\n\n\treturn &UpsideDownCouchDocIDReader{\n\t\tindexReader: indexReader,\n\t\titerator:    it,\n\t}, nil\n}\n\nfunc (r *UpsideDownCouchDocIDReader) Next() (string, error) {\n\tkey, val, valid := r.iterator.Current()\n\tif valid {\n\t\tbr, err := NewBackIndexRowKV(key, val)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\trv := string(br.doc)\n\t\tr.iterator.Next()\n\t\treturn rv, nil\n\t}\n\treturn \"\", nil\n}\n\nfunc (r *UpsideDownCouchDocIDReader) Advance(docID string) (string, error) {\n\tbir := NewBackIndexRow(docID, nil, nil)\n\tr.iterator.Seek(bir.Key())\n\tkey, val, valid := r.iterator.Current()\n\tif valid {\n\t\tbr, err := NewBackIndexRowKV(key, val)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\trv := string(br.doc)\n\t\tr.iterator.Next()\n\t\treturn rv, nil\n\t}\n\treturn \"\", nil\n}\n\nfunc (r *UpsideDownCouchDocIDReader) Close() error {\n\treturn r.iterator.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * Copyright (c) 2013-2014, Jeremy Bingham (<jbingham@gmail.com>)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage indexer\n\nimport (\n\t\"github.com\/ctdk\/goiardi\/datastore\"\n\t\"github.com\/ctdk\/goiardi\/util\"\n)\n\ntype PostgresIndex struct {\n\n}\n\nfunc (p *PostgresIndex) Initialize() error {\n\t\/\/ check if the default indexes exist yet, and if not create them\n\treturn nil\n}\n\nfunc (p *PostgresIndex) CreateCollection(col string) error {\n\tsqlStmt := \"INSERT INTO goiardi.search_collections (name, organization_id) VALUES ($1, $2)\"\n\ttx, err := datastore.Dbh.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = tx.Exec(sqlStmt, col, 1)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\ttx.Commit()\n\treturn nil\n}\n\nfunc (p *PostgresIndex) DeleteCollection(col string) error {\n\ttx, err := datastore.Dbh.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = tx.Exec(\"SELECT goiardi.delete_search_collection($1, $2)\", col, 1)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\ttx.Commit()\n\treturn nil\n}\n\nfunc (p *PostgresIndex) DeleteItem(idxName string, doc string) error {\n\ttx, err := datastore.Dbh.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = tx.Exec(\"SELECT goiardi.delete_search_item($1, $2)\", idxName, doc, 1)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\ttx.Commit()\n\treturn nil\n}\n\nfunc (p *PostgresIndex) SaveItem(obj Indexable) error {\n\n\treturn nil\n}\n\nfunc (p *PostgresIndex) Endpoints() ([]string, error) {\n\tsqlStmt := \"SELECT ARRAY_AGG(name) FROM goiardi.search_collections WHERE organization_id = $1\"\n\tstmt, err := datastore.Dbh.Prepare(sqlStmt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer stmt.Close()\n\tvar endpoints util.StringSlice\n\terr = stmt.QueryRow(1).Scan(&endpoints)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn endpoints, nil\n}\n\nfunc (p *PostgresIndex) Clear() error {\n\ttx, err := datastore.Dbh.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsqlStmt := \"DELETE FROM goiardi.search_items WHERE organization_id = $1\"\n\t_, err = tx.Exec(sqlStmt, 1)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\tsqlStmt = \"DELETE FROM goiardi.search_collections WHERE organization_id = $1\"\n\t_, err = tx.Exec(sqlStmt, 1)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\tsqlStmt = \"INSERT INTO goiardi.search_collections (name, organization_id) VALUES ('client', $1), ('environment', $1), ('node', $1), ('role', $1)\"\n\t_, err = tx.Exec(sqlStmt, 1)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\ttx.Commit()\n\n\treturn nil\n}\n<commit_msg>First, untested pass at code for saving flattened items to the search table<commit_after>\/*\n * Copyright (c) 2013-2014, Jeremy Bingham (<jbingham@gmail.com>)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\npackage indexer\n\nimport (\n\t\"fmt\"\n\t\"github.com\/ctdk\/goiardi\/datastore\"\n\t\"github.com\/ctdk\/goiardi\/util\"\n\t\"github.com\/lib\/pq\"\n)\n\ntype PostgresIndex struct {\n\n}\n\nfunc (p *PostgresIndex) Initialize() error {\n\t\/\/ check if the default indexes exist yet, and if not create them\n\treturn nil\n}\n\nfunc (p *PostgresIndex) CreateCollection(col string) error {\n\tsqlStmt := \"INSERT INTO goiardi.search_collections (name, organization_id) VALUES ($1, $2)\"\n\ttx, err := datastore.Dbh.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = tx.Exec(sqlStmt, col, 1)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\ttx.Commit()\n\treturn nil\n}\n\nfunc (p *PostgresIndex) DeleteCollection(col string) error {\n\ttx, err := datastore.Dbh.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = tx.Exec(\"SELECT goiardi.delete_search_collection($1, $2)\", col, 1)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\ttx.Commit()\n\treturn nil\n}\n\nfunc (p *PostgresIndex) DeleteItem(idxName string, doc string) error {\n\ttx, err := datastore.Dbh.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = tx.Exec(\"SELECT goiardi.delete_search_item($1, $2)\", idxName, doc, 1)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\ttx.Commit()\n\treturn nil\n}\n\nfunc (p *PostgresIndex) SaveItem(obj Indexable) error {\n\tflat := obj.Flatten()\n\titemName := obj.DocID()\n\tcollectionName := obj.Index()\n\ttx, err := datastore.Dbh.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar scID int32\n\terr = tx.QueryRow(\"SELECT id FROM goiardi.search_collections WHERE organization_id = $1 AND name = $2\", 1, collectionName).Scan(&scID)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\tstmt, err := tx.Prepare(pq.CopyIn(\"goiardi.search_items\", \"organization_id\", \"search_collection_id\", \"item_name\", \"value\", \"path\"))\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\tfor k, v := range flat {\n\t\t\/\/ will the values need escaped like in file search?\n\t\tswitch v := v.(type) {\n\t\tcase string:\n\t\t\t_, err = stmt.Exec(1, scID, itemName, v, k)\n\t\t\tif err != nil {\n\t\t\t\ttx.Rollback()\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase []string:\n\t\t\tfor _, w := range v {\n\t\t\t\t_, err = stmt.Exec(1, scID, itemName, w, k)\n\t\t\t\tif err != nil {\n\t\t\t\t\ttx.Rollback()\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\terr = fmt.Errorf(\"pg search should have never been able to reach this state. Key %s had a value %v of type %T\", k, v, v)\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t}\n\t_, err = stmt.Exec()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (p *PostgresIndex) Endpoints() ([]string, error) {\n\tsqlStmt := \"SELECT ARRAY_AGG(name) FROM goiardi.search_collections WHERE organization_id = $1\"\n\tstmt, err := datastore.Dbh.Prepare(sqlStmt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer stmt.Close()\n\tvar endpoints util.StringSlice\n\terr = stmt.QueryRow(1).Scan(&endpoints)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn endpoints, nil\n}\n\nfunc (p *PostgresIndex) Clear() error {\n\ttx, err := datastore.Dbh.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsqlStmt := \"DELETE FROM goiardi.search_items WHERE organization_id = $1\"\n\t_, err = tx.Exec(sqlStmt, 1)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\tsqlStmt = \"DELETE FROM goiardi.search_collections WHERE organization_id = $1\"\n\t_, err = tx.Exec(sqlStmt, 1)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\tsqlStmt = \"INSERT INTO goiardi.search_collections (name, organization_id) VALUES ('client', $1), ('environment', $1), ('node', $1), ('role', $1)\"\n\t_, err = tx.Exec(sqlStmt, 1)\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\ttx.Commit()\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestDefaultValues(t *testing.T) {\n\tc := &Config{}\n\tc.home = \"\/home\/alice\"\n\tc.configure()\n\tassert.Equal(t, \"\", c.APIKey)\n\tassert.Equal(t, \"http:\/\/exercism.io\", c.API)\n\tassert.Equal(t, filepath.FromSlash(\"\/home\/alice\/exercism\"), c.Dir)\n}\n\nfunc TestCustomValues(t *testing.T) {\n\tc := &Config{\n\t\tAPIKey: \"abc123\",\n\t\tAPI:    \"http:\/\/example.org\",\n\t\tDir:    \"\/path\/to\/exercises\",\n\t\tXAPI:   \"http:\/\/x.example.org\",\n\t}\n\tc.configure()\n\tassert.Equal(t, \"abc123\", c.APIKey)\n\tassert.Equal(t, \"http:\/\/example.org\", c.API)\n\tassert.Equal(t, \"\/path\/to\/exercises\", c.Dir)\n\tassert.Equal(t, \"http:\/\/x.example.org\", c.XAPI)\n}\n\nfunc TestExpandHomeDir(t *testing.T) {\n\tc := &Config{Dir: \"~\/practice\"}\n\tc.home = \"\/home\/alice\"\n\tc.configure()\n\tassert.Equal(t, \"\/home\/alice\/practice\", c.Dir)\n}\n\nfunc TestExpandConfigPath(t *testing.T) {\n\ttestCases := []struct {\n\t\tpath   string\n\t\tenv    string\n\t\tresult string\n\t}{\n\t\t{\n\t\t\t\"path\/to\/config.json\",\n\t\t\t\"\",\n\t\t\t\"path\/to\/config.json\",\n\t\t},\n\t\t{\n\t\t\t\"\",\n\t\t\t\"~\/config.json\",\n\t\t\t\"\/home\/alice\/config.json\",\n\t\t},\n\t\t{\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\/home\/alice\/.exercism.json\",\n\t\t},\n\t}\n\thome := \"\/home\/alice\"\n\n\tfor _, tt := range testCases {\n\t\tassert.Equal(t, Expand(tt.path, tt.env, home), tt.result)\n\t}\n}\n\nfunc TestSanitizeWhitespace(t *testing.T) {\n\tc := &Config{\n\t\tAPIKey: \"   abc123\\n\\r\\n  \",\n\t\tAPI:    \"       \",\n\t\tDir:    \"  \\r\\n\/path\/to\/exercises   \\r\\n\",\n\t\tXAPI:   \"   \",\n\t}\n\tc.configure()\n\tassert.Equal(t, \"abc123\", c.APIKey)\n\tassert.Equal(t, \"http:\/\/exercism.io\", c.API)\n\tassert.Equal(t, \"\/path\/to\/exercises\", c.Dir)\n\tassert.Equal(t, \"http:\/\/x.exercism.io\", c.XAPI)\n}\n\nfunc TestReadNonexistantConfig(t *testing.T) {\n\tc, err := Read(\"\/no\/such\/config.json\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, c.APIKey, \"\")\n\tassert.Equal(t, c.API, \"http:\/\/exercism.io\")\n\tassert.Equal(t, c.XAPI, \"http:\/\/x.exercism.io\")\n\tassert.False(t, c.IsAuthenticated())\n\tif !strings.HasSuffix(c.Dir, filepath.FromSlash(\"\/exercism\")) {\n\t\tt.Fatal(\"Default unconfigured config should use home dir\")\n\t}\n}\n\nfunc TestReadingWritingConfig(t *testing.T) {\n\ttmpDir, err := ioutil.TempDir(\"\", \"\")\n\tfilename := fmt.Sprintf(\"%s\/%s\", tmpDir, File)\n\tassert.NoError(t, err)\n\n\tc1 := &Config{\n\t\tAPIKey: \"MyKey\",\n\t\tDir:    \"\/exercism\/directory\",\n\t\tAPI:    \"localhost\",\n\t\tXAPI:   \"localhost\",\n\t\tFile: filename,\n\t}\n\tc1.configure()\n\n\tc1.Write()\n\n\tc2, err := Read(filename)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, c1.APIKey, c2.APIKey)\n\tassert.Equal(t, c1.Dir, c2.Dir)\n\tassert.Equal(t, c1.API, c2.API)\n\tassert.Equal(t, c1.XAPI, c2.XAPI)\n}\n\nfunc TestUpdateConfig(t *testing.T) {\n\tc := &Config{\n\t\tAPIKey: \"MyKey\",\n\t\tDir:    \"\/exercism\/directory\",\n\t\tAPI:    \"localhost\",\n\t\tXAPI:   \"localhost\",\n\t}\n\n\tc.Update(\"NewKey\", \"\", \"\", \"\")\n\tassert.Equal(t, \"NewKey\", c.APIKey)\n\tassert.Equal(t, \"localhost\", c.API)\n\tassert.Equal(t, \"\/exercism\/directory\", c.Dir)\n\tassert.Equal(t, \"localhost\", c.XAPI)\n\n\tc.Update(\"\", \"http:\/\/example.com\", \"\", \"\")\n\tassert.Equal(t, \"NewKey\", c.APIKey)\n\tassert.Equal(t, \"http:\/\/example.com\", c.API)\n\tassert.Equal(t, \"\/exercism\/directory\", c.Dir)\n\tassert.Equal(t, \"localhost\", c.XAPI)\n\n\tc.Update(\"\", \"\", \"\/tmp\/exercism\", \"\")\n\tassert.Equal(t, \"NewKey\", c.APIKey)\n\tassert.Equal(t, \"http:\/\/example.com\", c.API)\n\tassert.Equal(t, \"\/tmp\/exercism\", c.Dir)\n\tassert.Equal(t, \"localhost\", c.XAPI)\n\n\tc.Update(\"\", \"\", \"\", \"http:\/\/x.example.org\")\n\tassert.Equal(t, \"NewKey\", c.APIKey)\n\tassert.Equal(t, \"http:\/\/example.com\", c.API)\n\tassert.Equal(t, \"\/tmp\/exercism\", c.Dir)\n\tassert.Equal(t, \"http:\/\/x.example.org\", c.XAPI)\n}\n\nfunc TestReadDefaultConfig(t *testing.T) {\n\tdir, err := filepath.Abs(\"..\/fixtures\/home\")\n\tassert.NoError(t, err)\n\n\tc := &Config{home: dir}\n\terr = c.Read(\"\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"abc123\", c.APIKey)\n\tassert.Equal(t, \"\/path\/to\/exercism\", c.Dir)\n\tassert.Equal(t, \"http:\/\/example.com\", c.API)\n\tassert.Equal(t, \"http:\/\/x.example.com\", c.XAPI)\n}\n\nfunc TestReadCustomConfig(t *testing.T) {\n\tdir, err := filepath.Abs(\"..\/fixtures\/home\/\")\n\tassert.NoError(t, err)\n\n\tc := &Config{home: dir}\n\tfile := fmt.Sprintf(\"%s\/custom.json\", dir)\n\terr = c.Read(file)\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"xyz000\", c.APIKey)\n\tassert.Equal(t, \"\/tmp\/exercism\", c.Dir)\n\tassert.Equal(t, \"http:\/\/example.org\", c.API)\n\tassert.Equal(t, \"http:\/\/x.example.org\", c.XAPI)\n}\n\nfunc TestReadLegacyConfig(t *testing.T) {\n\tdir, err := filepath.Abs(\"..\/fixtures\/home\/\")\n\tassert.NoError(t, err)\n\n\tc := &Config{home: dir}\n\tfile := fmt.Sprintf(\"%s\/legacy.json\", dir)\n\terr = c.Read(file)\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"prq567\", c.APIKey)\n\tassert.Equal(t, \"\/tmp\/stuff\", c.Dir)\n\tassert.Equal(t, \"http:\/\/api.example.com\", c.API)\n\tassert.Equal(t, \"http:\/\/problems.example.com\", c.XAPI)\n}\n\nfunc TestConfigInEnv(t *testing.T) {\n\t_, caller, _, ok := runtime.Caller(0)\n\tassert.True(t, ok)\n\tfile := filepath.Join(filepath.Dir(caller), \"..\", \"fixtures\", \"special.json\")\n\tos.Setenv(fileEnvKey, file)\n\n\tc := &Config{home: \"\/tmp\/home\"}\n\terr := c.Read(\"\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"abc123\", c.APIKey)\n\tassert.Equal(t, \"\/a\/b\/c\", c.Dir)\n\tassert.Equal(t, \"http:\/\/api.example.com\", c.API)\n\tassert.Equal(t, \"http:\/\/x.example.com\", c.XAPI)\n}\n<commit_msg>remove redundant tests<commit_after>package config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestDefaultValues(t *testing.T) {\n\tc := &Config{}\n\tc.home = \"\/home\/alice\"\n\tc.configure()\n\tassert.Equal(t, \"\", c.APIKey)\n\tassert.Equal(t, \"http:\/\/exercism.io\", c.API)\n\tassert.Equal(t, filepath.FromSlash(\"\/home\/alice\/exercism\"), c.Dir)\n}\n\nfunc TestCustomValues(t *testing.T) {\n\tc := &Config{\n\t\tAPIKey: \"abc123\",\n\t\tAPI:    \"http:\/\/example.org\",\n\t\tDir:    \"\/path\/to\/exercises\",\n\t\tXAPI:   \"http:\/\/x.example.org\",\n\t}\n\tc.configure()\n\tassert.Equal(t, \"abc123\", c.APIKey)\n\tassert.Equal(t, \"http:\/\/example.org\", c.API)\n\tassert.Equal(t, \"\/path\/to\/exercises\", c.Dir)\n\tassert.Equal(t, \"http:\/\/x.example.org\", c.XAPI)\n}\n\nfunc TestExpandHomeDir(t *testing.T) {\n\tc := &Config{Dir: \"~\/practice\"}\n\tc.home = \"\/home\/alice\"\n\tc.configure()\n\tassert.Equal(t, \"\/home\/alice\/practice\", c.Dir)\n}\n\nfunc TestExpandConfigPath(t *testing.T) {\n\ttestCases := []struct {\n\t\tpath   string\n\t\tenv    string\n\t\tresult string\n\t}{\n\t\t{\n\t\t\t\"path\/to\/config.json\",\n\t\t\t\"\",\n\t\t\t\"path\/to\/config.json\",\n\t\t},\n\t\t{\n\t\t\t\"\",\n\t\t\t\"~\/config.json\",\n\t\t\t\"\/home\/alice\/config.json\",\n\t\t},\n\t\t{\n\t\t\t\"\",\n\t\t\t\"\",\n\t\t\t\"\/home\/alice\/.exercism.json\",\n\t\t},\n\t}\n\thome := \"\/home\/alice\"\n\n\tfor _, tt := range testCases {\n\t\tassert.Equal(t, Expand(tt.path, tt.env, home), tt.result)\n\t}\n}\n\nfunc TestSanitizeWhitespace(t *testing.T) {\n\tc := &Config{\n\t\tAPIKey: \"   abc123\\n\\r\\n  \",\n\t\tAPI:    \"       \",\n\t\tDir:    \"  \\r\\n\/path\/to\/exercises   \\r\\n\",\n\t\tXAPI:   \"   \",\n\t}\n\tc.configure()\n\tassert.Equal(t, \"abc123\", c.APIKey)\n\tassert.Equal(t, \"http:\/\/exercism.io\", c.API)\n\tassert.Equal(t, \"\/path\/to\/exercises\", c.Dir)\n\tassert.Equal(t, \"http:\/\/x.exercism.io\", c.XAPI)\n}\n\nfunc TestReadNonexistantConfig(t *testing.T) {\n\tc, err := Read(\"\/no\/such\/config.json\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, c.APIKey, \"\")\n\tassert.Equal(t, c.API, \"http:\/\/exercism.io\")\n\tassert.Equal(t, c.XAPI, \"http:\/\/x.exercism.io\")\n\tassert.False(t, c.IsAuthenticated())\n\tif !strings.HasSuffix(c.Dir, filepath.FromSlash(\"\/exercism\")) {\n\t\tt.Fatal(\"Default unconfigured config should use home dir\")\n\t}\n}\n\nfunc TestReadingWritingConfig(t *testing.T) {\n\ttmpDir, err := ioutil.TempDir(\"\", \"\")\n\tfilename := fmt.Sprintf(\"%s\/%s\", tmpDir, File)\n\tassert.NoError(t, err)\n\n\tc1 := &Config{\n\t\tAPIKey: \"MyKey\",\n\t\tDir:    \"\/exercism\/directory\",\n\t\tAPI:    \"localhost\",\n\t\tXAPI:   \"localhost\",\n\t\tFile: filename,\n\t}\n\tc1.configure()\n\n\tc1.Write()\n\n\tc2, err := Read(filename)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, c1.APIKey, c2.APIKey)\n\tassert.Equal(t, c1.Dir, c2.Dir)\n\tassert.Equal(t, c1.API, c2.API)\n\tassert.Equal(t, c1.XAPI, c2.XAPI)\n}\n\nfunc TestUpdateConfig(t *testing.T) {\n\tc := &Config{\n\t\tAPIKey: \"MyKey\",\n\t\tAPI:    \"localhost\",\n\t\tDir:    \"\/exercism\/directory\",\n\t\tXAPI:   \"localhost\",\n\t}\n\n\t\/\/ Test the blank values don't overwrite existing values\n\tc.Update(\"\", \"\", \"\", \"\")\n\tassert.Equal(t, \"MyKey\", c.APIKey)\n\tassert.Equal(t, \"localhost\", c.API)\n\tassert.Equal(t, \"\/exercism\/directory\", c.Dir)\n\tassert.Equal(t, \"localhost\", c.XAPI)\n\n\t\/\/ Test that each value can be overwritten\n\tc.Update(\"NewKey\", \"http:\/\/example.com\", \"\/tmp\/exercism\", \"http:\/\/x.example.org\")\n\tassert.Equal(t, \"NewKey\", c.APIKey)\n\tassert.Equal(t, \"http:\/\/example.com\", c.API)\n\tassert.Equal(t, \"\/tmp\/exercism\", c.Dir)\n\tassert.Equal(t, \"http:\/\/x.example.org\", c.XAPI)\n}\n\nfunc TestReadDefaultConfig(t *testing.T) {\n\tdir, err := filepath.Abs(\"..\/fixtures\/home\")\n\tassert.NoError(t, err)\n\n\tc := &Config{home: dir}\n\terr = c.Read(\"\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"abc123\", c.APIKey)\n\tassert.Equal(t, \"\/path\/to\/exercism\", c.Dir)\n\tassert.Equal(t, \"http:\/\/example.com\", c.API)\n\tassert.Equal(t, \"http:\/\/x.example.com\", c.XAPI)\n}\n\nfunc TestReadCustomConfig(t *testing.T) {\n\tdir, err := filepath.Abs(\"..\/fixtures\/home\/\")\n\tassert.NoError(t, err)\n\n\tc := &Config{home: dir}\n\tfile := fmt.Sprintf(\"%s\/custom.json\", dir)\n\terr = c.Read(file)\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"xyz000\", c.APIKey)\n\tassert.Equal(t, \"\/tmp\/exercism\", c.Dir)\n\tassert.Equal(t, \"http:\/\/example.org\", c.API)\n\tassert.Equal(t, \"http:\/\/x.example.org\", c.XAPI)\n}\n\nfunc TestReadLegacyConfig(t *testing.T) {\n\tdir, err := filepath.Abs(\"..\/fixtures\/home\/\")\n\tassert.NoError(t, err)\n\n\tc := &Config{home: dir}\n\tfile := fmt.Sprintf(\"%s\/legacy.json\", dir)\n\terr = c.Read(file)\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"prq567\", c.APIKey)\n\tassert.Equal(t, \"\/tmp\/stuff\", c.Dir)\n\tassert.Equal(t, \"http:\/\/api.example.com\", c.API)\n\tassert.Equal(t, \"http:\/\/problems.example.com\", c.XAPI)\n}\n\nfunc TestConfigInEnv(t *testing.T) {\n\t_, caller, _, ok := runtime.Caller(0)\n\tassert.True(t, ok)\n\tfile := filepath.Join(filepath.Dir(caller), \"..\", \"fixtures\", \"special.json\")\n\tos.Setenv(fileEnvKey, file)\n\n\tc := &Config{home: \"\/tmp\/home\"}\n\terr := c.Read(\"\")\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"abc123\", c.APIKey)\n\tassert.Equal(t, \"\/a\/b\/c\", c.Dir)\n\tassert.Equal(t, \"http:\/\/api.example.com\", c.API)\n\tassert.Equal(t, \"http:\/\/x.example.com\", c.XAPI)\n}\n<|endoftext|>"}
{"text":"<commit_before>package config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n)\n\nvar sampleConfig = `\napikey = \"abcde\"\ndisplay_name = \"fghij\"\ndiagnostic = true\n\n[connection]\npost_metrics_retry_delay_seconds = 600\npost_metrics_retry_max = 5\n\n[plugin.metrics.mysql]\ncommand = \"ruby \/path\/to\/your\/plugin\/mysql.rb\"\n\n[sensu.checks.memory] # for backward compatibility\ncommand = \"ruby ..\/sensu\/plugins\/system\/memory-metrics.rb\"\ntype = \"metric\"\n\n[plugin.checks.heartbeat]\ncommand = \"heartbeat.sh\"\nnotification_interval = 60\n`\n\nfunc TestLoadConfig(t *testing.T) {\n\ttmpFile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\tif err = ioutil.WriteFile(tmpFile.Name(), []byte(sampleConfig), 0644); err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\n\tconfig, err := LoadConfig(tmpFile.Name())\n\tif err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\n\tif config.Apibase != \"https:\/\/mackerel.io\" {\n\t\tt.Error(\"should be https:\/\/mackerel.io (arg value should be used)\")\n\t}\n\n\tif config.Apikey != \"abcde\" {\n\t\tt.Error(\"should be abcde (config value should be used)\")\n\t}\n\n\tif config.DisplayName != \"fghij\" {\n\t\tt.Error(\"should be fghij (config value should be used)\")\n\t}\n\n\tif config.Diagnostic != true {\n\t\tt.Error(\"should be true (config value should be used)\")\n\t}\n\n\tif config.Connection.PostMetricsDequeueDelaySeconds != 30 {\n\t\tt.Error(\"should be 30 (default value should be used)\")\n\t}\n\n\tif config.Connection.PostMetricsRetryDelaySeconds != 180 {\n\t\tt.Error(\"should be 180 (max retry delay seconds is 180)\")\n\t}\n\n\tif config.Connection.PostMetricsRetryMax != 5 {\n\t\tt.Error(\"should be 5 (config value should be used)\")\n\t}\n}\n\nvar sampleConfigWithHostStatus = `\napikey = \"abcde\"\ndisplay_name = \"fghij\"\n\n[host_status]\non_start = \"working\"\non_stop  = \"poweroff\"\n`\n\nfunc TestLoadConfigWithHostStatus(t *testing.T) {\n\ttmpFile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\tif err = ioutil.WriteFile(tmpFile.Name(), []byte(sampleConfigWithHostStatus), 0644); err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\n\tconfig, err := LoadConfig(tmpFile.Name())\n\tif err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\n\tif config.Apikey != \"abcde\" {\n\t\tt.Error(\"should be abcde (config value should be used)\")\n\t}\n\n\tif config.DisplayName != \"fghij\" {\n\t\tt.Error(\"should be fghij (config value should be used)\")\n\t}\n\n\tif config.HostStatus.OnStart != \"working\" {\n\t\tt.Error(`HostStatus.OnStart should be \"working\"`)\n\t}\n\n\tif config.HostStatus.OnStop != \"poweroff\" {\n\t\tt.Error(`HostStatus.OnStop should be \"poweroff\"`)\n\t}\n}\n\nfunc TestLoadConfigFile(t *testing.T) {\n\ttmpFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\tif err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\tif _, err := tmpFile.WriteString(sampleConfig); err != nil {\n\t\tt.Fatal(\"should not raise error\")\n\t}\n\ttmpFile.Sync()\n\ttmpFile.Close()\n\tdefer os.Remove(tmpFile.Name())\n\n\tconfig, err := loadConfigFile(tmpFile.Name())\n\tif err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\n\tif config.Apikey != \"abcde\" {\n\t\tt.Error(\"Apikey should be abcde\")\n\t}\n\n\tif config.DisplayName != \"fghij\" {\n\t\tt.Error(\"DisplayName should be fghij\")\n\t}\n\n\tif config.Diagnostic != true {\n\t\tt.Error(\"Diagnostic should be true\")\n\t}\n\n\tif config.Connection.PostMetricsRetryMax != 5 {\n\t\tt.Error(\"PostMetricsRetryMax should be 5\")\n\t}\n\n\tif config.Plugin[\"metrics\"] == nil {\n\t\tt.Error(\"plugin should have metrics\")\n\t}\n\tpluginConf := config.Plugin[\"metrics\"][\"mysql\"]\n\tif pluginConf.Command != \"ruby \/path\/to\/your\/plugin\/mysql.rb\" {\n\t\tt.Errorf(\"plugin conf command should be 'ruby \/path\/to\/your\/plugin\/mysql.rb' but %v\", pluginConf.Command)\n\t}\n\n\t\/\/ for backward compatibility\n\tsensu := config.Plugin[\"metrics\"][\"DEPRECATED-sensu-memory\"]\n\tif sensu.Command != \"ruby ..\/sensu\/plugins\/system\/memory-metrics.rb\" {\n\t\tt.Error(\"sensu command should be 'ruby ..\/sensu\/plugins\/system\/memory-metrics.rb'\")\n\t}\n\n\tif config.Plugin[\"checks\"] == nil {\n\t\tt.Error(\"plugin should have checks\")\n\t}\n\tchecks := config.Plugin[\"checks\"][\"heartbeat\"]\n\tif checks.Command != \"heartbeat.sh\" {\n\t\tt.Error(\"sensu command should be 'heartbeat.sh'\")\n\t}\n\tif *checks.NotificationInterval != 60 {\n\t\tt.Error(\"notification_interval should be 60\")\n\t}\n}\n\nfunc assertNoError(t *testing.T, err error) {\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc assert(t *testing.T, ok bool, msg string) {\n\tif !ok {\n\t\tt.Error(msg)\n\t}\n}\n\nvar tomlQuotedReplacer = strings.NewReplacer(\n\t\"\\t\", \"\\\\t\",\n\t\"\\n\", \"\\\\n\",\n\t\"\\r\", \"\\\\r\",\n\t\"\\\"\", \"\\\\\\\"\",\n\t\"\\\\\", \"\\\\\\\\\",\n)\n\nfunc TestLoadConfigFileInclude(t *testing.T) {\n\tconfigDir, err := ioutil.TempDir(\"\", \"mackerel-config-test\")\n\tassertNoError(t, err)\n\n\tconfigFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\tassertNoError(t, err)\n\n\tincludedFile, err := os.Create(filepath.Join(configDir, \"sub1.conf\"))\n\n\tconfigContent := fmt.Sprintf(`\napikey = \"not overwritten\"\nroles = [ \"roles\", \"to be overwritten\" ]\n\ninclude = \"%s\/*.conf\"\n\n[plugin.metrics.foo1]\ncommand = \"foo1\"\n\n[plugin.metrics.bar]\ncommand = \"this wille be overwritten\"\n`, tomlQuotedReplacer.Replace(configDir))\n\n\tincludedContent := `\nroles = [ \"Service:role\" ]\n\n[plugin.metrics.foo2]\ncommand = \"foo2\"\n\n[plugin.metrics.bar]\ncommand = \"bar\"\n`\n\n\t_, err = configFile.WriteString(configContent)\n\tassertNoError(t, err)\n\n\t_, err = includedFile.WriteString(includedContent)\n\tassertNoError(t, err)\n\n\tconfigFile.Close()\n\tincludedFile.Close()\n\tdefer os.Remove(configFile.Name())\n\tdefer os.Remove(includedFile.Name())\n\n\tconfig, err := loadConfigFile(configFile.Name())\n\tassertNoError(t, err)\n\n\tassert(t, config.Apikey == \"not overwritten\", \"apikey should not be overwritten\")\n\tassert(t, len(config.Roles) == 1, \"roles should be overwritten\")\n\tassert(t, config.Roles[0] == \"Service:role\", \"roles should be overwritten\")\n\tassert(t, config.Plugin[\"metrics\"][\"foo1\"].Command == \"foo1\", \"plugin.metrics.foo1 should exist\")\n\tassert(t, config.Plugin[\"metrics\"][\"foo2\"].Command == \"foo2\", \"plugin.metrics.foo2 should exist\")\n\tassert(t, config.Plugin[\"metrics\"][\"bar\"].Command == \"bar\", \"plugin.metrics.bar should be overwritten\")\n}\n\nfunc TestFileSystemHostIDStorage(t *testing.T) {\n\troot, err := ioutil.TempDir(\"\", \"mackerel-agent-test\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ts := FileSystemHostIDStorage{Root: root}\n\terr = s.SaveHostID(\"test-host-id\")\n\tassertNoError(t, err)\n\n\thostID, err := s.LoadHostID()\n\tassertNoError(t, err)\n\tassert(t, hostID == \"test-host-id\", \"SaveHostID and LoadHostID should preserve the host id\")\n\n\terr = s.DeleteSavedHostID()\n\tassertNoError(t, err)\n\n\t_, err = s.LoadHostID()\n\tassert(t, err != nil, \"LoadHostID after DeleteSavedHostID must fail\")\n}\n\nfunc TestConfig_HostIDStorage(t *testing.T) {\n\tconf := Config{\n\t\tRoot: \"test-root\",\n\t}\n\n\tstorage, ok := conf.hostIDStorage().(*FileSystemHostIDStorage)\n\tassert(t, ok, \"Default hostIDStorage must be *FileSystemHostIDStorage\")\n\tassert(t, storage.Root == \"test-root\", \"FileSystemHostIDStorage must have the same Root of Config\")\n}\n<commit_msg>add a test for max_check_attempts<commit_after>package config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n)\n\nvar sampleConfig = `\napikey = \"abcde\"\ndisplay_name = \"fghij\"\ndiagnostic = true\n\n[connection]\npost_metrics_retry_delay_seconds = 600\npost_metrics_retry_max = 5\n\n[plugin.metrics.mysql]\ncommand = \"ruby \/path\/to\/your\/plugin\/mysql.rb\"\n\n[sensu.checks.memory] # for backward compatibility\ncommand = \"ruby ..\/sensu\/plugins\/system\/memory-metrics.rb\"\ntype = \"metric\"\n\n[plugin.checks.heartbeat]\ncommand = \"heartbeat.sh\"\nnotification_interval = 60\nmax_check_attempts = 3\n`\n\nfunc TestLoadConfig(t *testing.T) {\n\ttmpFile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\tif err = ioutil.WriteFile(tmpFile.Name(), []byte(sampleConfig), 0644); err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\n\tconfig, err := LoadConfig(tmpFile.Name())\n\tif err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\n\tif config.Apibase != \"https:\/\/mackerel.io\" {\n\t\tt.Error(\"should be https:\/\/mackerel.io (arg value should be used)\")\n\t}\n\n\tif config.Apikey != \"abcde\" {\n\t\tt.Error(\"should be abcde (config value should be used)\")\n\t}\n\n\tif config.DisplayName != \"fghij\" {\n\t\tt.Error(\"should be fghij (config value should be used)\")\n\t}\n\n\tif config.Diagnostic != true {\n\t\tt.Error(\"should be true (config value should be used)\")\n\t}\n\n\tif config.Connection.PostMetricsDequeueDelaySeconds != 30 {\n\t\tt.Error(\"should be 30 (default value should be used)\")\n\t}\n\n\tif config.Connection.PostMetricsRetryDelaySeconds != 180 {\n\t\tt.Error(\"should be 180 (max retry delay seconds is 180)\")\n\t}\n\n\tif config.Connection.PostMetricsRetryMax != 5 {\n\t\tt.Error(\"should be 5 (config value should be used)\")\n\t}\n}\n\nvar sampleConfigWithHostStatus = `\napikey = \"abcde\"\ndisplay_name = \"fghij\"\n\n[host_status]\non_start = \"working\"\non_stop  = \"poweroff\"\n`\n\nfunc TestLoadConfigWithHostStatus(t *testing.T) {\n\ttmpFile, err := ioutil.TempFile(\"\", \"\")\n\tif err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\tif err = ioutil.WriteFile(tmpFile.Name(), []byte(sampleConfigWithHostStatus), 0644); err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\n\tconfig, err := LoadConfig(tmpFile.Name())\n\tif err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\n\tif config.Apikey != \"abcde\" {\n\t\tt.Error(\"should be abcde (config value should be used)\")\n\t}\n\n\tif config.DisplayName != \"fghij\" {\n\t\tt.Error(\"should be fghij (config value should be used)\")\n\t}\n\n\tif config.HostStatus.OnStart != \"working\" {\n\t\tt.Error(`HostStatus.OnStart should be \"working\"`)\n\t}\n\n\tif config.HostStatus.OnStop != \"poweroff\" {\n\t\tt.Error(`HostStatus.OnStop should be \"poweroff\"`)\n\t}\n}\n\nfunc TestLoadConfigFile(t *testing.T) {\n\ttmpFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\tif err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\tif _, err := tmpFile.WriteString(sampleConfig); err != nil {\n\t\tt.Fatal(\"should not raise error\")\n\t}\n\ttmpFile.Sync()\n\ttmpFile.Close()\n\tdefer os.Remove(tmpFile.Name())\n\n\tconfig, err := loadConfigFile(tmpFile.Name())\n\tif err != nil {\n\t\tt.Errorf(\"should not raise error: %v\", err)\n\t}\n\n\tif config.Apikey != \"abcde\" {\n\t\tt.Error(\"Apikey should be abcde\")\n\t}\n\n\tif config.DisplayName != \"fghij\" {\n\t\tt.Error(\"DisplayName should be fghij\")\n\t}\n\n\tif config.Diagnostic != true {\n\t\tt.Error(\"Diagnostic should be true\")\n\t}\n\n\tif config.Connection.PostMetricsRetryMax != 5 {\n\t\tt.Error(\"PostMetricsRetryMax should be 5\")\n\t}\n\n\tif config.Plugin[\"metrics\"] == nil {\n\t\tt.Error(\"plugin should have metrics\")\n\t}\n\tpluginConf := config.Plugin[\"metrics\"][\"mysql\"]\n\tif pluginConf.Command != \"ruby \/path\/to\/your\/plugin\/mysql.rb\" {\n\t\tt.Errorf(\"plugin conf command should be 'ruby \/path\/to\/your\/plugin\/mysql.rb' but %v\", pluginConf.Command)\n\t}\n\n\t\/\/ for backward compatibility\n\tsensu := config.Plugin[\"metrics\"][\"DEPRECATED-sensu-memory\"]\n\tif sensu.Command != \"ruby ..\/sensu\/plugins\/system\/memory-metrics.rb\" {\n\t\tt.Error(\"sensu command should be 'ruby ..\/sensu\/plugins\/system\/memory-metrics.rb'\")\n\t}\n\n\tif config.Plugin[\"checks\"] == nil {\n\t\tt.Error(\"plugin should have checks\")\n\t}\n\tchecks := config.Plugin[\"checks\"][\"heartbeat\"]\n\tif checks.Command != \"heartbeat.sh\" {\n\t\tt.Error(\"sensu command should be 'heartbeat.sh'\")\n\t}\n\tif *checks.NotificationInterval != 60 {\n\t\tt.Error(\"notification_interval should be 60\")\n\t}\n\tif *checks.MaxCheckAttempts != 3 {\n\t\tt.Error(\"max_check_attempts should be 3\")\n\t}\n}\n\nfunc assertNoError(t *testing.T, err error) {\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n}\n\nfunc assert(t *testing.T, ok bool, msg string) {\n\tif !ok {\n\t\tt.Error(msg)\n\t}\n}\n\nvar tomlQuotedReplacer = strings.NewReplacer(\n\t\"\\t\", \"\\\\t\",\n\t\"\\n\", \"\\\\n\",\n\t\"\\r\", \"\\\\r\",\n\t\"\\\"\", \"\\\\\\\"\",\n\t\"\\\\\", \"\\\\\\\\\",\n)\n\nfunc TestLoadConfigFileInclude(t *testing.T) {\n\tconfigDir, err := ioutil.TempDir(\"\", \"mackerel-config-test\")\n\tassertNoError(t, err)\n\n\tconfigFile, err := ioutil.TempFile(\"\", \"mackerel-config-test\")\n\tassertNoError(t, err)\n\n\tincludedFile, err := os.Create(filepath.Join(configDir, \"sub1.conf\"))\n\n\tconfigContent := fmt.Sprintf(`\napikey = \"not overwritten\"\nroles = [ \"roles\", \"to be overwritten\" ]\n\ninclude = \"%s\/*.conf\"\n\n[plugin.metrics.foo1]\ncommand = \"foo1\"\n\n[plugin.metrics.bar]\ncommand = \"this wille be overwritten\"\n`, tomlQuotedReplacer.Replace(configDir))\n\n\tincludedContent := `\nroles = [ \"Service:role\" ]\n\n[plugin.metrics.foo2]\ncommand = \"foo2\"\n\n[plugin.metrics.bar]\ncommand = \"bar\"\n`\n\n\t_, err = configFile.WriteString(configContent)\n\tassertNoError(t, err)\n\n\t_, err = includedFile.WriteString(includedContent)\n\tassertNoError(t, err)\n\n\tconfigFile.Close()\n\tincludedFile.Close()\n\tdefer os.Remove(configFile.Name())\n\tdefer os.Remove(includedFile.Name())\n\n\tconfig, err := loadConfigFile(configFile.Name())\n\tassertNoError(t, err)\n\n\tassert(t, config.Apikey == \"not overwritten\", \"apikey should not be overwritten\")\n\tassert(t, len(config.Roles) == 1, \"roles should be overwritten\")\n\tassert(t, config.Roles[0] == \"Service:role\", \"roles should be overwritten\")\n\tassert(t, config.Plugin[\"metrics\"][\"foo1\"].Command == \"foo1\", \"plugin.metrics.foo1 should exist\")\n\tassert(t, config.Plugin[\"metrics\"][\"foo2\"].Command == \"foo2\", \"plugin.metrics.foo2 should exist\")\n\tassert(t, config.Plugin[\"metrics\"][\"bar\"].Command == \"bar\", \"plugin.metrics.bar should be overwritten\")\n}\n\nfunc TestFileSystemHostIDStorage(t *testing.T) {\n\troot, err := ioutil.TempDir(\"\", \"mackerel-agent-test\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ts := FileSystemHostIDStorage{Root: root}\n\terr = s.SaveHostID(\"test-host-id\")\n\tassertNoError(t, err)\n\n\thostID, err := s.LoadHostID()\n\tassertNoError(t, err)\n\tassert(t, hostID == \"test-host-id\", \"SaveHostID and LoadHostID should preserve the host id\")\n\n\terr = s.DeleteSavedHostID()\n\tassertNoError(t, err)\n\n\t_, err = s.LoadHostID()\n\tassert(t, err != nil, \"LoadHostID after DeleteSavedHostID must fail\")\n}\n\nfunc TestConfig_HostIDStorage(t *testing.T) {\n\tconf := Config{\n\t\tRoot: \"test-root\",\n\t}\n\n\tstorage, ok := conf.hostIDStorage().(*FileSystemHostIDStorage)\n\tassert(t, ok, \"Default hostIDStorage must be *FileSystemHostIDStorage\")\n\tassert(t, storage.Root == \"test-root\", \"FileSystemHostIDStorage must have the same Root of Config\")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ TODO: write package comment\npackage channel\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n)\n\nconst (\n\tteam   = \"monkeytacos\"\n\tapiURL = \"https:\/\/%s.slack.com\/api\/%s?%s\"\n)\n\nvar apiToken string\n\ntype channelListResponse struct {\n\tChannels []Channel `json:\"channels\"`\n\tOk       bool      `json:\"ok\"`\n\tErr      string    `json:\"error,omitempty\"`\n}\n\ntype channelResponse struct {\n\tOk      bool    `json:\"ok\"`\n\tChannel Channel `json:\"channel\"`\n\tErr     string  `json:\"error,omitempty\"`\n}\n\ntype Channel struct {\n\tId      string   `json:\"id\"`\n\tName    string   `json:\"name\"`\n\tMembers []string `json:\"members\"`\n}\n\nfunc init() {\n\tapiToken = os.Getenv(\"SLACK_API_TOKEN\")\n\tif apiToken == \"\" {\n\t\tlog.Fatal(\"SLACK_API_TOKEN not set\")\n\t}\n}\n\nfunc New(name string) (Channel, error) {\n\tvar emptyChannel Channel\n\n\tqsp := map[string]string{\n\t\t\"channel\": name,\n\t\t\"token\":   apiToken,\n\t}\n\tlistURL := makeURL(apiURL, \"channels.list\", qsp)\n\tresp, err := http.Get(listURL)\n\tif err != nil {\n\t\treturn emptyChannel, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar cl channelListResponse\n\terr = json.NewDecoder(resp.Body).Decode(&cl)\n\tif err != nil {\n\t\treturn emptyChannel, err\n\t}\n\n\tif cl.Ok != true {\n\t\treturn emptyChannel, errors.New(\"failed to get channel list from Slack API\")\n\t}\n\n\tfor _, ch := range cl.Channels {\n\t\tif ch.Name == name {\n\t\t\treturn ch, nil\n\t\t}\n\t}\n\n\treturn emptyChannel, fmt.Errorf(\"no channel with name %q on team %q\", name, team)\n}\n\nfunc (ch Channel) String() string {\n\treturn fmt.Sprintf(\"Channel{Id: %s, Name: %s, Members: %v}\", ch.Id, ch.Name, ch.Members)\n}\n\n\/\/ TODO: should this be pointer or value?\nfunc (ch *Channel) UpdateMembers() error {\n\tqsp := map[string]string{\n\t\t\"channel\": ch.Id,\n\t\t\"token\":   apiToken,\n\t}\n\tchannelURL := makeURL(apiURL, \"channel.info\", qsp)\n\n\tresp, err := http.Get(channelURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tcr := channelResponse{}\n\terr = json.NewDecoder(resp.Body).Decode(&cr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !cr.Ok {\n\t\treturn fmt.Errorf(\"Slack API returned error: %s\", cr.Err)\n\t}\n\n\tch.Members = cr.Channel.Members\n\treturn nil\n}\n\nfunc makeURL(slackURL, method string, qsp map[string]string) string {\n\tqs := queryString(qsp)\n\treturn fmt.Sprintf(apiURL, team, method, qs)\n}\n\nfunc queryString(qsp map[string]string) string {\n\tvals := url.Values{}\n\tfor k, v := range qsp {\n\t\tvals.Add(k, v)\n\t}\n\treturn vals.Encode()\n}\n<commit_msg>Fix wrong method name<commit_after>\/\/ TODO: write package comment\npackage channel\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n)\n\nconst (\n\tteam   = \"monkeytacos\"\n\tapiURL = \"https:\/\/%s.slack.com\/api\/%s?%s\"\n)\n\nvar apiToken string\n\ntype channelListResponse struct {\n\tChannels []Channel `json:\"channels\"`\n\tOk       bool      `json:\"ok\"`\n\tErr      string    `json:\"error,omitempty\"`\n}\n\ntype channelResponse struct {\n\tOk      bool    `json:\"ok\"`\n\tChannel Channel `json:\"channel\"`\n\tErr     string  `json:\"error,omitempty\"`\n}\n\ntype Channel struct {\n\tId      string   `json:\"id\"`\n\tName    string   `json:\"name\"`\n\tMembers []string `json:\"members\"`\n}\n\nfunc init() {\n\tapiToken = os.Getenv(\"SLACK_API_TOKEN\")\n\tif apiToken == \"\" {\n\t\tlog.Fatal(\"SLACK_API_TOKEN not set\")\n\t}\n}\n\nfunc New(name string) (Channel, error) {\n\tvar emptyChannel Channel\n\n\tqsp := map[string]string{\n\t\t\"channel\": name,\n\t\t\"token\":   apiToken,\n\t}\n\tlistURL := makeURL(apiURL, \"channels.list\", qsp)\n\tresp, err := http.Get(listURL)\n\tif err != nil {\n\t\treturn emptyChannel, err\n\t}\n\tdefer resp.Body.Close()\n\n\tvar cl channelListResponse\n\terr = json.NewDecoder(resp.Body).Decode(&cl)\n\tif err != nil {\n\t\treturn emptyChannel, err\n\t}\n\n\tif cl.Ok != true {\n\t\treturn emptyChannel, errors.New(\"failed to get channel list from Slack API\")\n\t}\n\n\tfor _, ch := range cl.Channels {\n\t\tif ch.Name == name {\n\t\t\treturn ch, nil\n\t\t}\n\t}\n\n\treturn emptyChannel, fmt.Errorf(\"no channel with name %q on team %q\", name, team)\n}\n\nfunc (ch Channel) String() string {\n\treturn fmt.Sprintf(\"Channel{Id: %s, Name: %s, Members: %v}\", ch.Id, ch.Name, ch.Members)\n}\n\n\/\/ TODO: should this be pointer or value?\nfunc (ch *Channel) UpdateMembers() error {\n\tqsp := map[string]string{\n\t\t\"channel\": ch.Id,\n\t\t\"token\":   apiToken,\n\t}\n\tchannelURL := makeURL(apiURL, \"channels.info\", qsp)\n\n\tresp, err := http.Get(channelURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tcr := channelResponse{}\n\terr = json.NewDecoder(resp.Body).Decode(&cr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !cr.Ok {\n\t\treturn fmt.Errorf(\"Slack API returned error: %s\", cr.Err)\n\t}\n\n\tch.Members = cr.Channel.Members\n\treturn nil\n}\n\nfunc makeURL(slackURL, method string, qsp map[string]string) string {\n\tqs := queryString(qsp)\n\treturn fmt.Sprintf(apiURL, team, method, qs)\n}\n\nfunc queryString(qsp map[string]string) string {\n\tvals := url.Values{}\n\tfor k, v := range qsp {\n\t\tvals.Add(k, v)\n\t}\n\treturn vals.Encode()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 The Go Authors. All rights reserved.\n\n\/\/ This file is copied from golang.org\/x\/mobile\/internal\/mobileinit\/ctx_android.go\n\/\/ and editted.\n\/\/ This file is licensed under the 3-clause BSD license.\n\npackage jni\n\n\/*\n#include <jni.h>\n#include <stdlib.h>\n\n\/\/ These definitions are duplicated with those in ctx_android.go of golang.org\/x\/mobile\/internal\/mobileinit package.\n\/\/ To be exact, this might cause undefined behavior, but some compilers including GCC work as a common extension.\n\/\/ (J.5.11 Multiple external definitions)\nJavaVM* current_vm;\njobject current_ctx;\n\nstatic char* lockJNI(uintptr_t* envp, int* attachedp) {\n\tJNIEnv* env;\n\n\tif (current_vm == NULL) {\n\t\treturn \"no current JVM\";\n\t}\n\n\t*attachedp = 0;\n\tswitch ((*current_vm)->GetEnv(current_vm, (void**)&env, JNI_VERSION_1_6)) {\n\tcase JNI_OK:\n\t\tbreak;\n\tcase JNI_EDETACHED:\n\t\tif ((*current_vm)->AttachCurrentThread(current_vm, &env, 0) != 0) {\n\t\t\treturn \"cannot attach to JVM\";\n\t\t}\n\t\t*attachedp = 1;\n\t\tbreak;\n\tcase JNI_EVERSION:\n\t\treturn \"bad JNI version\";\n\tdefault:\n\t\treturn \"unknown JNI error from GetEnv\";\n\t}\n\n\t*envp = (uintptr_t)env;\n\treturn NULL;\n}\n\nstatic char* checkException(uintptr_t jnienv) {\n\tjthrowable exc;\n\tJNIEnv* env = (JNIEnv*)jnienv;\n\n\tif (!(*env)->ExceptionCheck(env)) {\n\t\treturn NULL;\n\t}\n\n\texc = (*env)->ExceptionOccurred(env);\n\t(*env)->ExceptionClear(env);\n\n\tjclass clazz = (*env)->FindClass(env, \"java\/lang\/Throwable\");\n\tjmethodID toString = (*env)->GetMethodID(env, clazz, \"toString\", \"()Ljava\/lang\/String;\");\n\tjobject msgStr = (*env)->CallObjectMethod(env, exc, toString);\n\treturn (char*)(*env)->GetStringUTFChars(env, msgStr, 0);\n}\n\nstatic void unlockJNI() {\n\t(*current_vm)->DetachCurrentThread(current_vm);\n}\n*\/\nimport \"C\"\n\nimport (\n\t\"errors\"\n\t\"runtime\"\n\t\"unsafe\"\n)\n\nfunc RunOnJVM(fn func(vm, env, ctx uintptr) error) error {\n\terrch := make(chan error)\n\tgo func() {\n\t\truntime.LockOSThread()\n\t\tdefer runtime.UnlockOSThread()\n\n\t\tenv := C.uintptr_t(0)\n\t\tattached := C.int(0)\n\t\tif errStr := C.lockJNI(&env, &attached); errStr != nil {\n\t\t\terrch <- errors.New(C.GoString(errStr))\n\t\t\treturn\n\t\t}\n\t\tif attached != 0 {\n\t\t\tdefer C.unlockJNI()\n\t\t}\n\n\t\tvm := uintptr(unsafe.Pointer(C.current_vm))\n\t\tif err := fn(vm, uintptr(env), uintptr(C.current_ctx)); err != nil {\n\t\t\terrch <- err\n\t\t\treturn\n\t\t}\n\n\t\tif exc := C.checkException(env); exc != nil {\n\t\t\terrch <- errors.New(C.GoString(exc))\n\t\t\tC.free(unsafe.Pointer(exc))\n\t\t\treturn\n\t\t}\n\t\terrch <- nil\n\t}()\n\treturn <-errch\n}\n<commit_msg>jni: Add more comment<commit_after>\/\/ Copyright 2015 The Go Authors. All rights reserved.\n\n\/\/ This file is copied from golang.org\/x\/mobile\/internal\/mobileinit\/ctx_android.go\n\/\/ and editted.\n\/\/ This file is licensed under the 3-clause BSD license.\n\npackage jni\n\n\/*\n#include <jni.h>\n#include <stdlib.h>\n\n\/\/ These definitions are duplicated with those in ctx_android.go of golang.org\/x\/mobile\/internal\/mobileinit package.\n\/\/ To be exact, this might cause undefined behavior, but some compilers including GCC and Clang work as a common extension.\n\/\/ (J.5.11 Multiple external definitions)\nJavaVM* current_vm;\njobject current_ctx;\n\nstatic char* lockJNI(uintptr_t* envp, int* attachedp) {\n\tJNIEnv* env;\n\n\tif (current_vm == NULL) {\n\t\treturn \"no current JVM\";\n\t}\n\n\t*attachedp = 0;\n\tswitch ((*current_vm)->GetEnv(current_vm, (void**)&env, JNI_VERSION_1_6)) {\n\tcase JNI_OK:\n\t\tbreak;\n\tcase JNI_EDETACHED:\n\t\tif ((*current_vm)->AttachCurrentThread(current_vm, &env, 0) != 0) {\n\t\t\treturn \"cannot attach to JVM\";\n\t\t}\n\t\t*attachedp = 1;\n\t\tbreak;\n\tcase JNI_EVERSION:\n\t\treturn \"bad JNI version\";\n\tdefault:\n\t\treturn \"unknown JNI error from GetEnv\";\n\t}\n\n\t*envp = (uintptr_t)env;\n\treturn NULL;\n}\n\nstatic char* checkException(uintptr_t jnienv) {\n\tjthrowable exc;\n\tJNIEnv* env = (JNIEnv*)jnienv;\n\n\tif (!(*env)->ExceptionCheck(env)) {\n\t\treturn NULL;\n\t}\n\n\texc = (*env)->ExceptionOccurred(env);\n\t(*env)->ExceptionClear(env);\n\n\tjclass clazz = (*env)->FindClass(env, \"java\/lang\/Throwable\");\n\tjmethodID toString = (*env)->GetMethodID(env, clazz, \"toString\", \"()Ljava\/lang\/String;\");\n\tjobject msgStr = (*env)->CallObjectMethod(env, exc, toString);\n\treturn (char*)(*env)->GetStringUTFChars(env, msgStr, 0);\n}\n\nstatic void unlockJNI() {\n\t(*current_vm)->DetachCurrentThread(current_vm);\n}\n*\/\nimport \"C\"\n\nimport (\n\t\"errors\"\n\t\"runtime\"\n\t\"unsafe\"\n)\n\n\/\/ RunOnJVM executes fn on the current VM context.\n\/\/\n\/\/ RunOnJVM should not be called on init function since the current VM might not be initialized yet.\nfunc RunOnJVM(fn func(vm, env, ctx uintptr) error) error {\n\terrch := make(chan error)\n\tgo func() {\n\t\truntime.LockOSThread()\n\t\tdefer runtime.UnlockOSThread()\n\n\t\tenv := C.uintptr_t(0)\n\t\tattached := C.int(0)\n\t\tif errStr := C.lockJNI(&env, &attached); errStr != nil {\n\t\t\terrch <- errors.New(C.GoString(errStr))\n\t\t\treturn\n\t\t}\n\t\tif attached != 0 {\n\t\t\tdefer C.unlockJNI()\n\t\t}\n\n\t\tvm := uintptr(unsafe.Pointer(C.current_vm))\n\t\tif err := fn(vm, uintptr(env), uintptr(C.current_ctx)); err != nil {\n\t\t\terrch <- err\n\t\t\treturn\n\t\t}\n\n\t\tif exc := C.checkException(env); exc != nil {\n\t\t\terrch <- errors.New(C.GoString(exc))\n\t\t\tC.free(unsafe.Pointer(exc))\n\t\t\treturn\n\t\t}\n\t\terrch <- nil\n\t}()\n\treturn <-errch\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2017 Circonus, Inc. <support@circonus.com>\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/\n\npackage server\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/config\"\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/plugins\"\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/server\/receiver\"\n\tcirconusgometrics \"github.com\/circonus-labs\/circonus-gometrics\"\n\t\"github.com\/rs\/zerolog\/log\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ run handles requests to execute plugins and return metrics emitted\n\/\/ handles \/, \/run, or \/run\/plugin_name\nfunc (s *Server) run(w http.ResponseWriter, r *http.Request) {\n\tplugin := \"\"\n\n\tif strings.HasPrefix(r.URL.Path, \"\/run\/\") { \/\/ run specific plugin\n\t\tplugin = strings.Replace(r.URL.Path, \"\/run\/\", \"\", -1)\n\t\tif plugin != \"\" {\n\t\t\tif !s.plugins.IsInternal(plugin) && !s.plugins.IsValid(plugin) {\n\t\t\t\ts.logger.Warn().\n\t\t\t\t\tStr(\"plugin\", plugin).\n\t\t\t\t\tMsg(\"Unknown plugin requested\")\n\t\t\t\thttp.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tlastMeticsmu.Lock()\n\tdefer lastMeticsmu.Unlock()\n\n\tmetrics := &map[string]interface{}{}\n\n\tif plugin == \"\" || !s.plugins.IsInternal(plugin) {\n\t\t\/\/ NOTE: errors are ignored from plugins.Run\n\t\t\/\/       1. errors are already logged by Run\n\t\t\/\/       2. do not expose execution state to callers\n\t\ts.plugins.Run(plugin)\n\t\tmetrics = s.plugins.Flush(plugin)\n\t}\n\n\tif plugin == \"\" || plugin == \"write\" {\n\t\treceiverMetrics := receiver.Flush()\n\t\tfor metricGroup, value := range *receiverMetrics {\n\t\t\t(*metrics)[metricGroup] = value\n\t\t}\n\t}\n\n\tif plugin == \"\" || plugin == \"statsd\" {\n\t\tif s.statsdSvr != nil {\n\t\t\tstatsdMetrics := s.statsdSvr.Flush()\n\t\t\tif statsdMetrics != nil {\n\t\t\t\t(*metrics)[viper.GetString(config.KeyStatsdHostCategory)] = *statsdMetrics\n\t\t\t}\n\t\t}\n\t}\n\n\tlastMetrics.metrics = metrics\n\tlastMetrics.ts = time.Now()\n\t\/\/ s.logger.Debug().Interface(\"m\", metrics).Msg(\"metrics\")\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tif err := json.NewEncoder(w).Encode(metrics); err != nil {\n\t\ts.logger.Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"Writing metrics to response\")\n\t}\n}\n\n\/\/ promOutput returns the last metrics in prom format\nfunc (s *Server) promOutput(w http.ResponseWriter, r *http.Request) {\n\tif lastMetrics.metrics == nil {\n\t\tw.WriteHeader(http.StatusNoContent)\n\t\treturn\n\t}\n\n\tms := lastMetrics.ts.UnixNano() \/ int64(time.Millisecond)\n\n\tfor group, data := range *lastMetrics.metrics {\n\t\t\/\/ t := reflect.TypeOf(data)\n\t\t\/\/ s.logger.Debug().Str(\"group\", group).Str(\"type\", t.String()).Msg(\"item\")\n\t\twalkMetrics(w, group, ms, data)\n\t}\n}\n\nfunc walkMetrics(w http.ResponseWriter, prefix string, ts int64, val interface{}) {\n\tt := reflect.TypeOf(val)\n\t\/\/ log.Debug().Str(\"pfx\", prefix).Str(\"type\", t.String()).Interface(\"val\", val).Msg(\"val\")\n\tswitch t.String() {\n\tcase \"circonusgometrics.Metrics\":\n\t\tmetrics, ok := val.(circonusgometrics.Metrics)\n\t\tif !ok {\n\t\t\tlog.Warn().Interface(\"val\", val).Str(\"target_type\", t.String()).Str(\"pkg\", \"prom export\").Msg(\"unable to coerce\")\n\t\t\treturn\n\t\t}\n\t\tfor pfx, metric := range metrics {\n\t\t\tswitch t2 := metric.Value.(type) {\n\t\t\tcase uint64:\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"%s`%s %d %d\\n\", prefix, pfx, metric.Value, ts)))\n\t\t\tcase float64:\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"%s`%s %f %d\\n\", prefix, pfx, metric.Value, ts)))\n\t\t\tcase string:\n\t\t\t\ts := fmt.Sprintf(\"%v\", metric.Value)\n\t\t\t\tok, err := regexp.MatchString(\"^[0-9]+$\", s)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error().Err(err).Msg(\"testing string for digits\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif ok {\n\t\t\t\t\tv, err := strconv.ParseInt(s, 10, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error().Err(err).Msg(\"conv int64\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tw.Write([]byte(fmt.Sprintf(\"%s`%s %d %d\\n\", prefix, pfx, v, ts)))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"#TEXT %s`%s %s %d\\n\", prefix, pfx, s, ts)))\n\t\t\tcase []string:\n\t\t\t\ts := fmt.Sprintf(\"%v\", metric.Value)\n\t\t\t\tif strings.Contains(s, \"[H[\") {\n\t\t\t\t\tw.Write([]byte(fmt.Sprintf(\"#HISTOGRAM %s`%s %s %d\\n\", prefix, pfx, s, ts)))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\twalkMetrics(w, prefix+\"`\"+pfx, ts, metric.Value)\n\t\t\tdefault:\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"?? %s`%s %v - %T\\n\", prefix, pfx, metric.Value, t2)))\n\t\t\t\t\/\/ walkMetrics(w, prefix+\"`\"+pfx, ts, metric.Value)\n\t\t\t}\n\t\t}\n\tcase \"*plugins.Metrics\":\n\t\tfor pfx, v := range *val.(*plugins.Metrics) {\n\t\t\twalkMetrics(w, prefix+\"`\"+pfx, ts, v.Value)\n\t\t}\n\tcase \"[]string\":\n\t\tv, ok := val.([]string)\n\t\tif ok {\n\t\t\tif len(v) > 0 && v[0][0:2] == \"H[\" {\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"#HISTOGRAM %s %s %d\\n\", prefix, val, ts)))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor idx, v2 := range v {\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"%s`%d %s %d\\n\", prefix, idx, v2, ts)))\n\t\t\t}\n\t\t}\n\tcase \"[]interface {}\":\n\t\tv, ok := val.([]interface{})\n\t\tif !ok {\n\t\t\tlog.Warn().Interface(\"val\", val).Str(\"target_type\", t.String()).Str(\"pkg\", \"prom export\").Msg(\"unable to coerce\")\n\t\t\treturn\n\t\t}\n\t\tif fmt.Sprintf(\"%v\", v)[0:3] == \"[H[\" {\n\t\t\tw.Write([]byte(fmt.Sprintf(\"#HISTOGRAM %s %s %d\\n\", prefix, val, ts)))\n\t\t\treturn\n\t\t}\n\t\tfor idx, v2 := range v {\n\t\t\twalkMetrics(w, fmt.Sprintf(\"%s`%d\", prefix, idx), ts, v2)\n\t\t}\n\tcase \"map[string]interface {}\":\n\t\tv, ok := val.(map[string]interface{})\n\t\tif !ok {\n\t\t\tlog.Warn().Interface(\"val\", val).Str(\"target_type\", t.String()).Str(\"pkg\", \"prom export\").Msg(\"unable to coerce\")\n\t\t\treturn\n\t\t}\n\t\tif _, isMetric := v[\"_type\"]; isMetric {\n\t\t\twalkMetrics(w, prefix, ts, v[\"_value\"])\n\t\t} else {\n\t\t\tfor pfx, v2 := range v {\n\t\t\t\twalkMetrics(w, prefix+\"`\"+pfx, ts, v2)\n\t\t\t}\n\t\t}\n\tcase \"string\":\n\t\tw.Write([]byte(fmt.Sprintf(\"#TEXT %s %s %d\\n\", prefix, val, ts)))\n\tcase \"float32\":\n\t\tfallthrough\n\tcase \"float64\":\n\t\tw.Write([]byte(fmt.Sprintf(\"%s %e %d\\n\", prefix, val, ts)))\n\tcase \"int32\":\n\t\tfallthrough\n\tcase \"int64\":\n\t\tfallthrough\n\tcase \"uint32\":\n\t\tfallthrough\n\tcase \"uint64\":\n\t\tw.Write([]byte(fmt.Sprintf(\"%s %d %d\\n\", prefix, val, ts)))\n\tdefault:\n\t\tw.Write([]byte(fmt.Sprintf(\"%v(%v) = %#v\\n\", prefix, t, val)))\n\t}\n}\n\n\/\/ inventory returns the current, active plugin inventory\nfunc (s *Server) inventory(w http.ResponseWriter, r *http.Request) {\n\tinventory := s.plugins.Inventory()\n\tif inventory == nil {\n\t\tinventory = []byte(`{\"error\": \"empty inventory\"}`)\n\t\ts.logger.Error().Msg(\"inventory is nil\/empty...\")\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(inventory)\n}\n\n\/\/ write handles PUT\/POST requests with a JSON playload containing \"freeform\"\n\/\/ metrics. No validation is applied to the \"format\" of the metrics beyond k\/v.\n\/\/ Where 'key' is the metric name and 'value' is the metric value as either a\n\/\/ simple value (e.g. {\"name\": 1, \"foo\": \"bar\", ...}) or a structured value\n\/\/ representation (e.g. {\"foo\": {_type: \"i\", _value: 1}, ...}).\nfunc (s *Server) write(w http.ResponseWriter, r *http.Request) {\n\tid := strings.Replace(r.URL.Path, \"\/write\/\", \"\", -1)\n\n\tlog.Debug().Str(\"path\", r.URL.Path).Str(\"id\", id).Msg(\"write request\")\n\t\/\/ a write request *MUST* include a metric group id to act as a namespace.\n\t\/\/ in other words, a \"plugin name\", all metrics for that write will appear\n\t\/\/ _under_ the metric group id (aka plugin name)\n\tif id == \"\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tif err := receiver.Parse(id, r.Body); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusNoContent)\n}\n<commit_msg>better type support for cgm metrics via statsd in prom<commit_after>\/\/ Copyright © 2017 Circonus, Inc. <support@circonus.com>\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/\n\npackage server\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/config\"\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/plugins\"\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/server\/receiver\"\n\tcirconusgometrics \"github.com\/circonus-labs\/circonus-gometrics\"\n\t\"github.com\/rs\/zerolog\/log\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ run handles requests to execute plugins and return metrics emitted\n\/\/ handles \/, \/run, or \/run\/plugin_name\nfunc (s *Server) run(w http.ResponseWriter, r *http.Request) {\n\tplugin := \"\"\n\n\tif strings.HasPrefix(r.URL.Path, \"\/run\/\") { \/\/ run specific plugin\n\t\tplugin = strings.Replace(r.URL.Path, \"\/run\/\", \"\", -1)\n\t\tif plugin != \"\" {\n\t\t\tif !s.plugins.IsInternal(plugin) && !s.plugins.IsValid(plugin) {\n\t\t\t\ts.logger.Warn().\n\t\t\t\t\tStr(\"plugin\", plugin).\n\t\t\t\t\tMsg(\"Unknown plugin requested\")\n\t\t\t\thttp.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tlastMeticsmu.Lock()\n\tdefer lastMeticsmu.Unlock()\n\n\tmetrics := &map[string]interface{}{}\n\n\tif plugin == \"\" || !s.plugins.IsInternal(plugin) {\n\t\t\/\/ NOTE: errors are ignored from plugins.Run\n\t\t\/\/       1. errors are already logged by Run\n\t\t\/\/       2. do not expose execution state to callers\n\t\ts.plugins.Run(plugin)\n\t\tmetrics = s.plugins.Flush(plugin)\n\t}\n\n\tif plugin == \"\" || plugin == \"write\" {\n\t\treceiverMetrics := receiver.Flush()\n\t\tfor metricGroup, value := range *receiverMetrics {\n\t\t\t(*metrics)[metricGroup] = value\n\t\t}\n\t}\n\n\tif plugin == \"\" || plugin == \"statsd\" {\n\t\tif s.statsdSvr != nil {\n\t\t\tstatsdMetrics := s.statsdSvr.Flush()\n\t\t\tif statsdMetrics != nil {\n\t\t\t\t(*metrics)[viper.GetString(config.KeyStatsdHostCategory)] = *statsdMetrics\n\t\t\t}\n\t\t}\n\t}\n\n\tlastMetrics.metrics = metrics\n\tlastMetrics.ts = time.Now()\n\t\/\/ s.logger.Debug().Interface(\"m\", metrics).Msg(\"metrics\")\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tif err := json.NewEncoder(w).Encode(metrics); err != nil {\n\t\ts.logger.Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"Writing metrics to response\")\n\t}\n}\n\n\/\/ promOutput returns the last metrics in prom format\nfunc (s *Server) promOutput(w http.ResponseWriter, r *http.Request) {\n\tif lastMetrics.metrics == nil {\n\t\tw.WriteHeader(http.StatusNoContent)\n\t\treturn\n\t}\n\n\tms := lastMetrics.ts.UnixNano() \/ int64(time.Millisecond)\n\n\tfor group, data := range *lastMetrics.metrics {\n\t\t\/\/ t := reflect.TypeOf(data)\n\t\t\/\/ s.logger.Debug().Str(\"group\", group).Str(\"type\", t.String()).Msg(\"item\")\n\t\twalkMetrics(w, group, ms, data)\n\t}\n}\n\nfunc walkMetrics(w http.ResponseWriter, prefix string, ts int64, val interface{}) {\n\tt := reflect.TypeOf(val)\n\t\/\/ log.Debug().Str(\"pfx\", prefix).Str(\"type\", t.String()).Interface(\"val\", val).Msg(\"val\")\n\tswitch t.String() {\n\tcase \"circonusgometrics.Metrics\":\n\t\tmetrics, ok := val.(circonusgometrics.Metrics)\n\t\tif !ok {\n\t\t\tlog.Warn().Interface(\"val\", val).Str(\"target_type\", t.String()).Str(\"pkg\", \"prom export\").Msg(\"unable to coerce\")\n\t\t\treturn\n\t\t}\n\t\tfor pfx, metric := range metrics {\n\t\t\tswitch t2 := metric.Value.(type) {\n\t\t\tcase uint64:\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"%s`%s %d %d\\n\", prefix, pfx, metric.Value, ts)))\n\t\t\tcase float64:\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"%s`%s %f %d\\n\", prefix, pfx, metric.Value, ts)))\n\t\t\tcase string:\n\t\t\t\ts := fmt.Sprintf(\"%v\", metric.Value)\n\t\t\t\tswitch metric.Type {\n\t\t\t\tcase \"i\":\n\t\t\t\t\tfallthrough\n\t\t\t\tcase \"I\":\n\t\t\t\t\tfallthrough\n\t\t\t\tcase \"l\":\n\t\t\t\t\tfallthrough\n\t\t\t\tcase \"L\":\n\t\t\t\t\tv, err := strconv.ParseInt(s, 10, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error().Err(err).Msg(\"conv int64\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tw.Write([]byte(fmt.Sprintf(\"%s`%s %d %d\\n\", prefix, pfx, v, ts)))\n\t\t\t\t\tcontinue\n\t\t\t\tcase \"n\":\n\t\t\t\t\tv, err := strconv.ParseFloat(s, 64)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error().Err(err).Msg(\"conv float64\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tw.Write([]byte(fmt.Sprintf(\"%s`%s %f %d\\n\", prefix, pfx, v, ts)))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"#TEXT %s`%s %s %d\\n\", prefix, pfx, s, ts)))\n\t\t\tcase []string:\n\t\t\t\ts := fmt.Sprintf(\"%v\", metric.Value)\n\t\t\t\tif strings.Contains(s, \"[H[\") {\n\t\t\t\t\tw.Write([]byte(fmt.Sprintf(\"#HISTOGRAM %s`%s %s %d\\n\", prefix, pfx, s, ts)))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\twalkMetrics(w, prefix+\"`\"+pfx, ts, metric.Value)\n\t\t\tdefault:\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"?? %s`%s %v - %T\\n\", prefix, pfx, metric.Value, t2)))\n\t\t\t\t\/\/ walkMetrics(w, prefix+\"`\"+pfx, ts, metric.Value)\n\t\t\t}\n\t\t}\n\tcase \"*plugins.Metrics\":\n\t\tfor pfx, v := range *val.(*plugins.Metrics) {\n\t\t\twalkMetrics(w, prefix+\"`\"+pfx, ts, v.Value)\n\t\t}\n\tcase \"[]string\":\n\t\tv, ok := val.([]string)\n\t\tif ok {\n\t\t\tif len(v) > 0 && v[0][0:2] == \"H[\" {\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"#HISTOGRAM %s %s %d\\n\", prefix, val, ts)))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor idx, v2 := range v {\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"%s`%d %s %d\\n\", prefix, idx, v2, ts)))\n\t\t\t}\n\t\t}\n\tcase \"[]interface {}\":\n\t\tv, ok := val.([]interface{})\n\t\tif !ok {\n\t\t\tlog.Warn().Interface(\"val\", val).Str(\"target_type\", t.String()).Str(\"pkg\", \"prom export\").Msg(\"unable to coerce\")\n\t\t\treturn\n\t\t}\n\t\tif fmt.Sprintf(\"%v\", v)[0:3] == \"[H[\" {\n\t\t\tw.Write([]byte(fmt.Sprintf(\"#HISTOGRAM %s %s %d\\n\", prefix, val, ts)))\n\t\t\treturn\n\t\t}\n\t\tfor idx, v2 := range v {\n\t\t\twalkMetrics(w, fmt.Sprintf(\"%s`%d\", prefix, idx), ts, v2)\n\t\t}\n\tcase \"map[string]interface {}\":\n\t\tv, ok := val.(map[string]interface{})\n\t\tif !ok {\n\t\t\tlog.Warn().Interface(\"val\", val).Str(\"target_type\", t.String()).Str(\"pkg\", \"prom export\").Msg(\"unable to coerce\")\n\t\t\treturn\n\t\t}\n\t\tif _, isMetric := v[\"_type\"]; isMetric {\n\t\t\twalkMetrics(w, prefix, ts, v[\"_value\"])\n\t\t} else {\n\t\t\tfor pfx, v2 := range v {\n\t\t\t\twalkMetrics(w, prefix+\"`\"+pfx, ts, v2)\n\t\t\t}\n\t\t}\n\tcase \"string\":\n\t\tw.Write([]byte(fmt.Sprintf(\"#TEXT %s %s %d\\n\", prefix, val, ts)))\n\tcase \"float32\":\n\t\tfallthrough\n\tcase \"float64\":\n\t\tw.Write([]byte(fmt.Sprintf(\"%s %e %d\\n\", prefix, val, ts)))\n\tcase \"int32\":\n\t\tfallthrough\n\tcase \"int64\":\n\t\tfallthrough\n\tcase \"uint32\":\n\t\tfallthrough\n\tcase \"uint64\":\n\t\tw.Write([]byte(fmt.Sprintf(\"%s %d %d\\n\", prefix, val, ts)))\n\tdefault:\n\t\tw.Write([]byte(fmt.Sprintf(\"%v(%v) = %#v\\n\", prefix, t, val)))\n\t}\n}\n\n\/\/ inventory returns the current, active plugin inventory\nfunc (s *Server) inventory(w http.ResponseWriter, r *http.Request) {\n\tinventory := s.plugins.Inventory()\n\tif inventory == nil {\n\t\tinventory = []byte(`{\"error\": \"empty inventory\"}`)\n\t\ts.logger.Error().Msg(\"inventory is nil\/empty...\")\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(inventory)\n}\n\n\/\/ write handles PUT\/POST requests with a JSON playload containing \"freeform\"\n\/\/ metrics. No validation is applied to the \"format\" of the metrics beyond k\/v.\n\/\/ Where 'key' is the metric name and 'value' is the metric value as either a\n\/\/ simple value (e.g. {\"name\": 1, \"foo\": \"bar\", ...}) or a structured value\n\/\/ representation (e.g. {\"foo\": {_type: \"i\", _value: 1}, ...}).\nfunc (s *Server) write(w http.ResponseWriter, r *http.Request) {\n\tid := strings.Replace(r.URL.Path, \"\/write\/\", \"\", -1)\n\n\tlog.Debug().Str(\"path\", r.URL.Path).Str(\"id\", id).Msg(\"write request\")\n\t\/\/ a write request *MUST* include a metric group id to act as a namespace.\n\t\/\/ in other words, a \"plugin name\", all metrics for that write will appear\n\t\/\/ _under_ the metric group id (aka plugin name)\n\tif id == \"\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tif err := receiver.Parse(id, r.Body); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusNoContent)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2017 Circonus, Inc. <support@circonus.com>\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/\n\npackage server\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/config\"\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/server\/receiver\"\n\tcgm \"github.com\/circonus-labs\/circonus-gometrics\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ run handles requests to execute plugins and return metrics emitted\n\/\/ handles \/, \/run, or \/run\/plugin_name\nfunc (s *Server) run(w http.ResponseWriter, r *http.Request) {\n\tplugin := \"\"\n\n\tif strings.HasPrefix(r.URL.Path, \"\/run\/\") { \/\/ run specific plugin\n\t\tplugin = strings.Replace(r.URL.Path, \"\/run\/\", \"\", -1)\n\t\tif plugin != \"\" {\n\t\t\tif !s.plugins.IsInternal(plugin) && !s.plugins.IsValid(plugin) {\n\t\t\t\ts.logger.Warn().\n\t\t\t\t\tStr(\"plugin\", plugin).\n\t\t\t\t\tMsg(\"Unknown plugin requested\")\n\t\t\t\thttp.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tlastMeticsmu.Lock()\n\tdefer lastMeticsmu.Unlock()\n\n\tmetrics := map[string]interface{}{}\n\n\tif plugin == \"\" || !s.plugins.IsInternal(plugin) {\n\t\t\/\/ NOTE: errors are ignored from plugins.Run\n\t\t\/\/       1. errors are already logged by Run\n\t\t\/\/       2. do not expose execution state to callers\n\t\ts.plugins.Run(plugin)\n\t\tpluginMetrics := s.plugins.Flush(plugin)\n\t\tmetrics = *pluginMetrics\n\t}\n\n\tif plugin == \"\" || plugin == \"write\" {\n\t\treceiverMetrics := receiver.Flush()\n\t\tfor metricName, metric := range *receiverMetrics {\n\t\t\tmetrics[metricName] = metric\n\t\t}\n\t}\n\n\tif plugin == \"\" || plugin == \"statsd\" {\n\t\tif s.statsdSvr != nil {\n\t\t\tstatsdMetrics := s.statsdSvr.Flush()\n\t\t\tif statsdMetrics != nil {\n\t\t\t\tmetrics[viper.GetString(config.KeyStatsdHostCategory)] = statsdMetrics\n\t\t\t}\n\t\t}\n\t}\n\n\tlastMetrics.metrics = metrics\n\tlastMetrics.ts = time.Now()\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tif err := json.NewEncoder(w).Encode(metrics); err != nil {\n\t\ts.logger.Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"Writing metrics to response\")\n\t}\n}\n\n\/\/ inventory returns the current, active plugin inventory\nfunc (s *Server) inventory(w http.ResponseWriter, r *http.Request) {\n\tinventory := s.plugins.Inventory()\n\tif inventory == nil {\n\t\tinventory = []byte(`{\"error\": \"empty inventory\"}`)\n\t\ts.logger.Error().Msg(\"inventory is nil\/empty...\")\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(inventory)\n}\n\n\/\/ write handles PUT\/POST requests with a JSON playload containing \"freeform\"\n\/\/ metrics. No validation is applied to the \"format\" of the metrics beyond k\/v.\n\/\/ Where 'key' is the metric name and 'value' is the metric value as either a\n\/\/ simple value (e.g. {\"name\": 1, \"foo\": \"bar\", ...}) or a structured value\n\/\/ representation (e.g. {\"foo\": {_type: \"i\", _value: 1}, ...}).\nfunc (s *Server) write(w http.ResponseWriter, r *http.Request) {\n\tid := strings.Replace(r.URL.Path, \"\/write\/\", \"\", -1)\n\n\ts.logger.Debug().Str(\"path\", r.URL.Path).Str(\"id\", id).Msg(\"write request\")\n\t\/\/ a write request *MUST* include a metric group id to act as a namespace.\n\t\/\/ in other words, a \"plugin name\", all metrics for that write will appear\n\t\/\/ _under_ the metric group id (aka plugin name)\n\tif id == \"\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tif err := receiver.Parse(id, r.Body); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusNoContent)\n}\n\n\/\/ promOutput returns the last metrics in prom format\nfunc (s *Server) promOutput(w http.ResponseWriter, r *http.Request) {\n\tif lastMetrics.metrics == nil || len(lastMetrics.metrics) == 0 {\n\t\tw.WriteHeader(http.StatusNoContent)\n\t\treturn\n\t}\n\n\tms := lastMetrics.ts.UnixNano() \/ int64(time.Millisecond)\n\n\tw.Header().Set(\"Content-Type\", \"text\/plain\")\n\tw.WriteHeader(http.StatusOK)\n\tfor id, data := range lastMetrics.metrics {\n\t\ts.metricsToPromFormat(w, id, ms, data)\n\t}\n}\n\nfunc (s *Server) metricsToPromFormat(w io.Writer, prefix string, ts int64, val interface{}) {\n\tl := s.logger.With().Str(\"op\", \"prom export\").Logger()\n\tswitch t := val.(type) {\n\tcase cgm.Metric:\n\t\tmetric := val.(cgm.Metric)\n\t\tsv := fmt.Sprintf(\"%v\", metric.Value)\n\t\tswitch metric.Type {\n\t\tcase \"i\":\n\t\t\tfallthrough\n\t\tcase \"I\":\n\t\t\tfallthrough\n\t\tcase \"l\":\n\t\t\tfallthrough\n\t\tcase \"L\":\n\t\t\tv, err := strconv.ParseInt(sv, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\tl.Error().Err(err).Msg(\"conv int64\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif _, err := w.Write([]byte(fmt.Sprintf(\"%s %d %d\\n\", prefix, v, ts))); err != nil {\n\t\t\t\tl.Error().Err(err).Msg(\"writing prom output\")\n\t\t\t}\n\t\tcase \"n\":\n\t\t\tif strings.Contains(sv, \"[H[\") {\n\t\t\t\tl.Warn().\n\t\t\t\t\tStr(\"type\", \"histogram != [prom]histogram(percentile)\").\n\t\t\t\t\tStr(\"metric\", fmt.Sprintf(\"%s = %s\", prefix, sv)).\n\t\t\t\t\tMsg(\"unsupported metric type\")\n\t\t\t} else {\n\t\t\t\tv, err := strconv.ParseFloat(sv, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tl.Error().Err(err).Msg(\"conv float64\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif _, err := w.Write([]byte(fmt.Sprintf(\"%s %f %d\\n\", prefix, v, ts))); err != nil {\n\t\t\t\t\tl.Error().Err(err).Msg(\"writing prom output\")\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"s\":\n\t\t\tl.Warn().\n\t\t\t\tStr(\"type\", \"text [prom]???\").\n\t\t\t\tStr(\"metric\", fmt.Sprintf(\"%s = %s\", prefix, sv)).\n\t\t\t\tMsg(\"unsuported metric type\")\n\t\tdefault:\n\t\t\tl.Warn().\n\t\t\t\tStr(\"type\", metric.Type).\n\t\t\t\tStr(\"name\", prefix).\n\t\t\t\tInterface(\"metric\", metric).\n\t\t\t\tMsg(\"invalid metric type\")\n\t\t}\n\tcase cgm.Metrics:\n\t\tmetrics := val.(cgm.Metrics)\n\t\tfor pfx, metric := range metrics {\n\t\t\tname := prefix\n\t\t\tif pfx != \"\" {\n\t\t\t\tname = strings.Join([]string{name, pfx}, config.MetricNameSeparator)\n\t\t\t}\n\t\t\ts.metricsToPromFormat(w, name, ts, metric)\n\t\t}\n\tcase *cgm.Metrics:\n\t\tmetrics := val.(*cgm.Metrics)\n\t\ts.metricsToPromFormat(w, prefix, ts, *metrics)\n\tdefault:\n\t\tl.Warn().\n\t\t\tStr(\"metric\", fmt.Sprintf(\"#TYPE(%T) %v = %#v\", t, prefix, val)).\n\t\t\tMsg(\"unhandled export type\")\n\t}\n}\n<commit_msg>add socketHandler specifically for the socket listener - only allows \/write<commit_after>\/\/ Copyright © 2017 Circonus, Inc. <support@circonus.com>\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/\n\npackage server\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/config\"\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/server\/receiver\"\n\tcgm \"github.com\/circonus-labs\/circonus-gometrics\"\n\tappstats \"github.com\/maier\/go-appstats\"\n\t\"github.com\/spf13\/viper\"\n)\n\n\/\/ run handles requests to execute plugins and return metrics emitted\n\/\/ handles \/, \/run, or \/run\/plugin_name\nfunc (s *Server) run(w http.ResponseWriter, r *http.Request) {\n\tplugin := \"\"\n\n\tif strings.HasPrefix(r.URL.Path, \"\/run\/\") { \/\/ run specific plugin\n\t\tplugin = strings.Replace(r.URL.Path, \"\/run\/\", \"\", -1)\n\t\tif plugin != \"\" {\n\t\t\tif !s.plugins.IsInternal(plugin) && !s.plugins.IsValid(plugin) {\n\t\t\t\ts.logger.Warn().\n\t\t\t\t\tStr(\"plugin\", plugin).\n\t\t\t\t\tMsg(\"Unknown plugin requested\")\n\t\t\t\thttp.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tlastMeticsmu.Lock()\n\tdefer lastMeticsmu.Unlock()\n\n\tmetrics := map[string]interface{}{}\n\n\tif plugin == \"\" || !s.plugins.IsInternal(plugin) {\n\t\t\/\/ NOTE: errors are ignored from plugins.Run\n\t\t\/\/       1. errors are already logged by Run\n\t\t\/\/       2. do not expose execution state to callers\n\t\ts.plugins.Run(plugin)\n\t\tpluginMetrics := s.plugins.Flush(plugin)\n\t\tmetrics = *pluginMetrics\n\t}\n\n\tif plugin == \"\" || plugin == \"write\" {\n\t\treceiverMetrics := receiver.Flush()\n\t\tfor metricName, metric := range *receiverMetrics {\n\t\t\tmetrics[metricName] = metric\n\t\t}\n\t}\n\n\tif plugin == \"\" || plugin == \"statsd\" {\n\t\tif s.statsdSvr != nil {\n\t\t\tstatsdMetrics := s.statsdSvr.Flush()\n\t\t\tif statsdMetrics != nil {\n\t\t\t\tmetrics[viper.GetString(config.KeyStatsdHostCategory)] = statsdMetrics\n\t\t\t}\n\t\t}\n\t}\n\n\tlastMetrics.metrics = metrics\n\tlastMetrics.ts = time.Now()\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tif err := json.NewEncoder(w).Encode(metrics); err != nil {\n\t\ts.logger.Error().\n\t\t\tErr(err).\n\t\t\tMsg(\"Writing metrics to response\")\n\t}\n}\n\n\/\/ inventory returns the current, active plugin inventory\nfunc (s *Server) inventory(w http.ResponseWriter, r *http.Request) {\n\tinventory := s.plugins.Inventory()\n\tif inventory == nil {\n\t\tinventory = []byte(`{\"error\": \"empty inventory\"}`)\n\t\ts.logger.Error().Msg(\"inventory is nil\/empty...\")\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(inventory)\n}\n\n\/\/ socketHandler gates \/write for the socket server only\nfunc (s *Server) socketHandler(w http.ResponseWriter, r *http.Request) {\n\tif !writePathRx.MatchString(r.URL.Path) {\n\t\tappstats.IncrementInt(\"requests_bad\")\n\t\ts.logger.Warn().\n\t\t\tStr(\"method\", r.Method).\n\t\t\tStr(\"url\", r.URL.String()).\n\t\t\tMsg(\"Not found\")\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tif r.Method != \"PUT\" && r.Method != \"POST\" {\n\t\tappstats.IncrementInt(\"requests_bad\")\n\t\ts.logger.Warn().\n\t\t\tStr(\"method\", r.Method).\n\t\t\tStr(\"url\", r.URL.String()).\n\t\t\tMsg(\"Not found\")\n\t\thttp.Error(w, \"Method not allowed\", http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\ts.write(w, r)\n}\n\n\/\/ write handles PUT\/POST requests with a JSON playload containing \"freeform\"\n\/\/ metrics. No validation is applied to the \"format\" of the metrics beyond k\/v.\n\/\/ Where 'key' is the metric name and 'value' is the metric value as either a\n\/\/ simple value (e.g. {\"name\": 1, \"foo\": \"bar\", ...}) or a structured value\n\/\/ representation (e.g. {\"foo\": {_type: \"i\", _value: 1}, ...}).\nfunc (s *Server) write(w http.ResponseWriter, r *http.Request) {\n\tid := strings.Replace(r.URL.Path, \"\/write\/\", \"\", -1)\n\n\ts.logger.Debug().Str(\"path\", r.URL.Path).Str(\"id\", id).Msg(\"write request\")\n\t\/\/ a write request *MUST* include a metric group id to act as a namespace.\n\t\/\/ in other words, a \"plugin name\", all metrics for that write will appear\n\t\/\/ _under_ the metric group id (aka plugin name)\n\tif id == \"\" {\n\t\thttp.NotFound(w, r)\n\t\treturn\n\t}\n\n\tif err := receiver.Parse(id, r.Body); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusNoContent)\n}\n\n\/\/ promOutput returns the last metrics in prom format\nfunc (s *Server) promOutput(w http.ResponseWriter, r *http.Request) {\n\tif lastMetrics.metrics == nil || len(lastMetrics.metrics) == 0 {\n\t\tw.WriteHeader(http.StatusNoContent)\n\t\treturn\n\t}\n\n\tms := lastMetrics.ts.UnixNano() \/ int64(time.Millisecond)\n\n\tw.Header().Set(\"Content-Type\", \"text\/plain\")\n\tw.WriteHeader(http.StatusOK)\n\tfor id, data := range lastMetrics.metrics {\n\t\ts.metricsToPromFormat(w, id, ms, data)\n\t}\n}\n\nfunc (s *Server) metricsToPromFormat(w io.Writer, prefix string, ts int64, val interface{}) {\n\tl := s.logger.With().Str(\"op\", \"prom export\").Logger()\n\tswitch t := val.(type) {\n\tcase cgm.Metric:\n\t\tmetric := val.(cgm.Metric)\n\t\tsv := fmt.Sprintf(\"%v\", metric.Value)\n\t\tswitch metric.Type {\n\t\tcase \"i\":\n\t\t\tfallthrough\n\t\tcase \"I\":\n\t\t\tfallthrough\n\t\tcase \"l\":\n\t\t\tfallthrough\n\t\tcase \"L\":\n\t\t\tv, err := strconv.ParseInt(sv, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\tl.Error().Err(err).Msg(\"conv int64\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif _, err := w.Write([]byte(fmt.Sprintf(\"%s %d %d\\n\", prefix, v, ts))); err != nil {\n\t\t\t\tl.Error().Err(err).Msg(\"writing prom output\")\n\t\t\t}\n\t\tcase \"n\":\n\t\t\tif strings.Contains(sv, \"[H[\") {\n\t\t\t\tl.Warn().\n\t\t\t\t\tStr(\"type\", \"histogram != [prom]histogram(percentile)\").\n\t\t\t\t\tStr(\"metric\", fmt.Sprintf(\"%s = %s\", prefix, sv)).\n\t\t\t\t\tMsg(\"unsupported metric type\")\n\t\t\t} else {\n\t\t\t\tv, err := strconv.ParseFloat(sv, 64)\n\t\t\t\tif err != nil {\n\t\t\t\t\tl.Error().Err(err).Msg(\"conv float64\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif _, err := w.Write([]byte(fmt.Sprintf(\"%s %f %d\\n\", prefix, v, ts))); err != nil {\n\t\t\t\t\tl.Error().Err(err).Msg(\"writing prom output\")\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"s\":\n\t\t\tl.Warn().\n\t\t\t\tStr(\"type\", \"text [prom]???\").\n\t\t\t\tStr(\"metric\", fmt.Sprintf(\"%s = %s\", prefix, sv)).\n\t\t\t\tMsg(\"unsuported metric type\")\n\t\tdefault:\n\t\t\tl.Warn().\n\t\t\t\tStr(\"type\", metric.Type).\n\t\t\t\tStr(\"name\", prefix).\n\t\t\t\tInterface(\"metric\", metric).\n\t\t\t\tMsg(\"invalid metric type\")\n\t\t}\n\tcase cgm.Metrics:\n\t\tmetrics := val.(cgm.Metrics)\n\t\tfor pfx, metric := range metrics {\n\t\t\tname := prefix\n\t\t\tif pfx != \"\" {\n\t\t\t\tname = strings.Join([]string{name, pfx}, config.MetricNameSeparator)\n\t\t\t}\n\t\t\ts.metricsToPromFormat(w, name, ts, metric)\n\t\t}\n\tcase *cgm.Metrics:\n\t\tmetrics := val.(*cgm.Metrics)\n\t\ts.metricsToPromFormat(w, prefix, ts, *metrics)\n\tdefault:\n\t\tl.Warn().\n\t\t\tStr(\"metric\", fmt.Sprintf(\"#TYPE(%T) %v = %#v\", t, prefix, val)).\n\t\t\tMsg(\"unhandled export type\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package task\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/shurcooL\/githubv4\"\n\t\"golang.org\/x\/build\/internal\/workflow\"\n\tgoversion \"golang.org\/x\/build\/maintner\/maintnerd\/maintapi\/version\"\n)\n\n\/\/ MilestoneTasks contains the tasks used to check and modify GitHub issues' milestones.\ntype MilestoneTasks struct {\n\tClient              GitHubClientInterface\n\tRepoOwner, RepoName string\n}\n\n\/\/ ReleaseKind is the type of release being run.\ntype ReleaseKind int\n\nconst (\n\tKindUnknown ReleaseKind = iota\n\tKindBeta\n\tKindRC\n\tKindMajor\n\tKindCurrentMinor\n\tKindPrevMinor\n)\n\ntype ReleaseMilestones struct {\n\tCurrent, Next int\n}\n\n\/\/ FetchMilestones returns the milestone numbers for the version currently being\n\/\/ released, and the next version that outstanding issues should be moved to.\n\/\/ If this is a major release, it also creates its first minor release\n\/\/ milestone.\nfunc (m *MilestoneTasks) FetchMilestones(ctx *workflow.TaskContext, currentVersion string, kind ReleaseKind) (ReleaseMilestones, error) {\n\tx, ok := goversion.Go1PointX(currentVersion)\n\tif !ok {\n\t\treturn ReleaseMilestones{}, fmt.Errorf(\"could not parse %q as a Go version\", currentVersion)\n\t}\n\tmajorVersion := fmt.Sprintf(\"go1.%d\", x)\n\n\t\/\/ RCs and betas use the major version's milestone.\n\tif kind == KindRC || kind == KindBeta {\n\t\tcurrentVersion = majorVersion\n\t}\n\n\tcurrentMilestone, err := m.Client.FetchMilestone(ctx, m.RepoOwner, m.RepoName, uppercaseVersion(currentVersion), false)\n\tif err != nil {\n\t\treturn ReleaseMilestones{}, err\n\t}\n\tnextV, err := nextVersion(currentVersion)\n\tif err != nil {\n\t\treturn ReleaseMilestones{}, err\n\t}\n\tnextMilestone, err := m.Client.FetchMilestone(ctx, m.RepoOwner, m.RepoName, uppercaseVersion(nextV), true)\n\tif err != nil {\n\t\treturn ReleaseMilestones{}, err\n\t}\n\tif kind == KindMajor {\n\t\t\/\/ Create the first minor release milestone too.\n\t\tfirstMinor := majorVersion + \".1\"\n\t\tif err != nil {\n\t\t\treturn ReleaseMilestones{}, err\n\t\t}\n\t\t_, err = m.Client.FetchMilestone(ctx, m.RepoOwner, m.RepoName, uppercaseVersion(firstMinor), true)\n\t\tif err != nil {\n\t\t\treturn ReleaseMilestones{}, err\n\t\t}\n\t}\n\treturn ReleaseMilestones{Current: currentMilestone, Next: nextMilestone}, nil\n}\n\nfunc uppercaseVersion(version string) string {\n\treturn strings.Replace(version, \"go\", \"Go\", 1)\n}\n\n\/\/ CheckBlockers returns an error if there are open release blockers in\n\/\/ the current milestone.\nfunc (m *MilestoneTasks) CheckBlockers(ctx *workflow.TaskContext, milestones ReleaseMilestones, version string, kind ReleaseKind) error {\n\tissues, err := m.loadMilestoneIssues(ctx, milestones.Current, kind)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar blockers []string\n\tfor number, labels := range issues {\n\t\treleaseBlocker := labels[\"release-blocker\"]\n\t\tif kind == KindBeta && (labels[\"okay-after-beta1\"] || !strings.HasSuffix(version, \"beta1\")) {\n\t\t\treleaseBlocker = false\n\t\t}\n\t\tif releaseBlocker {\n\t\t\tblockers = append(blockers, fmt.Sprintf(\"https:\/\/go.dev\/issue\/%v\", number))\n\t\t}\n\t}\n\tsort.Strings(blockers)\n\tif len(blockers) != 0 {\n\t\treturn fmt.Errorf(\"open release blockers:\\n%v\", strings.Join(blockers, \"\\n\"))\n\t}\n\treturn nil\n}\n\n\/\/ loadMilestoneIssues returns all the open issues in the specified milestone\n\/\/ and their labels.\nfunc (m *MilestoneTasks) loadMilestoneIssues(ctx *workflow.TaskContext, milestoneID int, kind ReleaseKind) (map[int]map[string]bool, error) {\n\tissues := map[int]map[string]bool{}\n\tvar query struct {\n\t\tRepository struct {\n\t\t\tIssues struct {\n\t\t\t\tPageInfo struct {\n\t\t\t\t\tEndCursor   githubv4.String\n\t\t\t\t\tHasNextPage bool\n\t\t\t\t}\n\n\t\t\t\tNodes []struct {\n\t\t\t\t\tNumber int\n\t\t\t\t\tID     githubv4.ID\n\t\t\t\t\tTitle  string\n\t\t\t\t\tLabels struct {\n\t\t\t\t\t\tPageInfo struct {\n\t\t\t\t\t\t\tHasNextPage bool\n\t\t\t\t\t\t}\n\t\t\t\t\t\tNodes []struct {\n\t\t\t\t\t\t\tName string\n\t\t\t\t\t\t}\n\t\t\t\t\t} `graphql:\"labels(first:10)\"`\n\t\t\t\t}\n\t\t\t} `graphql:\"issues(first:100, after:$afterToken, filterBy:{states:OPEN, milestoneNumber:$milestoneNumber})\"`\n\t\t} `graphql:\"repository(owner: $repoOwner, name: $repoName)\"`\n\t}\n\tvar afterToken *githubv4.String\nmore:\n\tif err := m.Client.Query(ctx, &query, map[string]interface{}{\n\t\t\"repoOwner\":       githubv4.String(m.RepoOwner),\n\t\t\"repoName\":        githubv4.String(m.RepoName),\n\t\t\"milestoneNumber\": githubv4.String(fmt.Sprint(milestoneID)),\n\t\t\"afterToken\":      afterToken,\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, issue := range query.Repository.Issues.Nodes {\n\t\tif issue.Labels.PageInfo.HasNextPage {\n\t\t\treturn nil, fmt.Errorf(\"issue %v (#%v) has more than 10 labels\", issue.Title, issue.Number)\n\t\t}\n\t\tlabels := map[string]bool{}\n\t\tfor _, label := range issue.Labels.Nodes {\n\t\t\tlabels[label.Name] = true\n\t\t}\n\t\tissues[issue.Number] = labels\n\t}\n\tif query.Repository.Issues.PageInfo.HasNextPage {\n\t\tafterToken = &query.Repository.Issues.PageInfo.EndCursor\n\t\tgoto more\n\t}\n\treturn issues, nil\n}\n\n\/\/ PushIssues updates issues to reflect a finished release. For beta1 releases,\n\/\/ it removes the okay-after-beta1 label. For major and minor releases,\n\/\/ it moves them to the next milestone and closes the current one.\nfunc (m *MilestoneTasks) PushIssues(ctx *workflow.TaskContext, milestones ReleaseMilestones, version string, kind ReleaseKind) error {\n\t\/\/ For RCs we don't change issues at all.\n\tif kind == KindRC {\n\t\treturn nil\n\t}\n\n\tissues, err := m.loadMilestoneIssues(ctx, milestones.Current, KindUnknown)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor issueNumber, labels := range issues {\n\t\tvar newLabels *[]string\n\t\tvar newMilestone *int\n\t\tif kind == KindBeta && strings.HasSuffix(version, \"beta1\") {\n\t\t\tif labels[\"okay-after-beta1\"] {\n\t\t\t\tnewLabels = &[]string{}\n\t\t\t\tfor label := range labels {\n\t\t\t\t\tif label == \"okay-after-beta1\" {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t*newLabels = append(*newLabels, label)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if kind == KindMajor || kind == KindCurrentMinor || kind == KindPrevMinor {\n\t\t\tnewMilestone = &milestones.Next\n\t\t}\n\t\t_, _, err := m.Client.EditIssue(ctx, m.RepoOwner, m.RepoName, issueNumber, &github.IssueRequest{\n\t\t\tMilestone: newMilestone,\n\t\t\tLabels:    newLabels,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif kind == KindMajor || kind == KindCurrentMinor || kind == KindPrevMinor {\n\t\t_, _, err := m.Client.EditMilestone(ctx, m.RepoOwner, m.RepoName, milestones.Current, &github.Milestone{\n\t\t\tState: github.String(\"closed\"),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ GitHubClientInterface is a wrapper around the GitHub v3 and v4 APIs, for\n\/\/ testing and dry-run support.\ntype GitHubClientInterface interface {\n\t\/\/ FetchMilestone returns the number of the requested milestone. If create is true,\n\t\/\/ and the milestone doesn't exist, it will be created.\n\tFetchMilestone(ctx context.Context, owner, repo, name string, create bool) (int, error)\n\n\t\/\/ See githubv4.Client.Query.\n\tQuery(ctx context.Context, q interface{}, variables map[string]interface{}) error\n\n\t\/\/ See github.Client.Issues.Edit.\n\tEditIssue(ctx context.Context, owner string, repo string, number int, issue *github.IssueRequest) (*github.Issue, *github.Response, error)\n\n\t\/\/ See github.Client.Issues.EditMilestone\n\tEditMilestone(ctx context.Context, owner string, repo string, number int, milestone *github.Milestone) (*github.Milestone, *github.Response, error)\n}\n\ntype GitHubClient struct {\n\tV3 *github.Client\n\tV4 *githubv4.Client\n}\n\nfunc (c *GitHubClient) Query(ctx context.Context, q interface{}, variables map[string]interface{}) error {\n\treturn c.V4.Query(ctx, q, variables)\n}\n\nfunc (c *GitHubClient) FetchMilestone(ctx context.Context, owner, repo, name string, create bool) (int, error) {\n\tn, found, err := findMilestone(ctx, c.V4, owner, repo, name)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif found {\n\t\treturn n, nil\n\t} else if !create {\n\t\treturn 0, fmt.Errorf(\"no milestone named %q found, and creation was disabled\", name)\n\t}\n\tm, _, createErr := c.V3.Issues.CreateMilestone(ctx, owner, repo, &github.Milestone{\n\t\tTitle: github.String(name),\n\t})\n\tif createErr != nil {\n\t\treturn 0, fmt.Errorf(\"could not find an open milestone named %q and creating it failed: %v\", name, createErr)\n\t}\n\treturn *m.Number, nil\n}\n\nfunc findMilestone(ctx context.Context, client *githubv4.Client, owner, repo, name string) (int, bool, error) {\n\tvar query struct {\n\t\tRepository struct {\n\t\t\tMilestones struct {\n\t\t\t\tNodes []struct {\n\t\t\t\t\tTitle  string\n\t\t\t\t\tNumber int\n\t\t\t\t\tState  string\n\t\t\t\t}\n\t\t\t} `graphql:\"milestones(first:10, query: $milestoneName)\"`\n\t\t} `graphql:\"repository(owner: $repoOwner, name: $repoName)\"`\n\t}\n\tif err := client.Query(ctx, &query, map[string]interface{}{\n\t\t\"repoOwner\":     githubv4.String(owner),\n\t\t\"repoName\":      githubv4.String(repo),\n\t\t\"milestoneName\": githubv4.String(name),\n\t}); err != nil {\n\t\treturn 0, false, err\n\t}\n\t\/\/ The milestone query is case-insensitive and a partial match; we're okay\n\t\/\/ with case variations but it needs to be a full match.\n\tvar open, closed []string\n\tmilestoneNumber := 0\n\tfor _, m := range query.Repository.Milestones.Nodes {\n\t\tif strings.ToLower(name) != strings.ToLower(m.Title) {\n\t\t\tcontinue\n\t\t}\n\t\tif m.State == \"OPEN\" {\n\t\t\topen = append(open, m.Title)\n\t\t\tmilestoneNumber = m.Number\n\t\t} else {\n\t\t\tclosed = append(closed, m.Title)\n\t\t}\n\t}\n\t\/\/ GitHub allows \"go\" and \"Go\" to exist at the same time.\n\t\/\/ If there's any confusion, fail: we expect either one open milestone,\n\t\/\/ or no matching milestones at all.\n\tswitch {\n\tcase len(open) == 1:\n\t\treturn milestoneNumber, true, nil\n\tcase len(open) > 1:\n\t\treturn 0, false, fmt.Errorf(\"multiple open milestones matching %q: %q\", name, open)\n\t\/\/ No open milestones.\n\tcase len(closed) == 0:\n\t\treturn 0, false, nil\n\tcase len(closed) > 0:\n\t\treturn 0, false, fmt.Errorf(\"no open milestones matching %q, but some closed: %q (re-open or delete?)\", name, closed)\n\t}\n\t\/\/ The switch above is exhaustive.\n\tpanic(fmt.Errorf(\"unhandled case: open: %q closed: %q\", open, closed))\n}\n\nfunc (c *GitHubClient) EditIssue(ctx context.Context, owner string, repo string, number int, issue *github.IssueRequest) (*github.Issue, *github.Response, error) {\n\treturn c.V3.Issues.Edit(ctx, owner, repo, number, issue)\n}\n\nfunc (c *GitHubClient) EditMilestone(ctx context.Context, owner string, repo string, number int, milestone *github.Milestone) (*github.Milestone, *github.Response, error) {\n\treturn c.V3.Issues.EditMilestone(ctx, owner, repo, number, milestone)\n}\n<commit_msg>internal\/task: don't check blockers for RC releases<commit_after>package task\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/shurcooL\/githubv4\"\n\t\"golang.org\/x\/build\/internal\/workflow\"\n\tgoversion \"golang.org\/x\/build\/maintner\/maintnerd\/maintapi\/version\"\n)\n\n\/\/ MilestoneTasks contains the tasks used to check and modify GitHub issues' milestones.\ntype MilestoneTasks struct {\n\tClient              GitHubClientInterface\n\tRepoOwner, RepoName string\n}\n\n\/\/ ReleaseKind is the type of release being run.\ntype ReleaseKind int\n\nconst (\n\tKindUnknown ReleaseKind = iota\n\tKindBeta\n\tKindRC\n\tKindMajor\n\tKindCurrentMinor\n\tKindPrevMinor\n)\n\ntype ReleaseMilestones struct {\n\tCurrent, Next int\n}\n\n\/\/ FetchMilestones returns the milestone numbers for the version currently being\n\/\/ released, and the next version that outstanding issues should be moved to.\n\/\/ If this is a major release, it also creates its first minor release\n\/\/ milestone.\nfunc (m *MilestoneTasks) FetchMilestones(ctx *workflow.TaskContext, currentVersion string, kind ReleaseKind) (ReleaseMilestones, error) {\n\tx, ok := goversion.Go1PointX(currentVersion)\n\tif !ok {\n\t\treturn ReleaseMilestones{}, fmt.Errorf(\"could not parse %q as a Go version\", currentVersion)\n\t}\n\tmajorVersion := fmt.Sprintf(\"go1.%d\", x)\n\n\t\/\/ RCs and betas use the major version's milestone.\n\tif kind == KindRC || kind == KindBeta {\n\t\tcurrentVersion = majorVersion\n\t}\n\n\tcurrentMilestone, err := m.Client.FetchMilestone(ctx, m.RepoOwner, m.RepoName, uppercaseVersion(currentVersion), false)\n\tif err != nil {\n\t\treturn ReleaseMilestones{}, err\n\t}\n\tnextV, err := nextVersion(currentVersion)\n\tif err != nil {\n\t\treturn ReleaseMilestones{}, err\n\t}\n\tnextMilestone, err := m.Client.FetchMilestone(ctx, m.RepoOwner, m.RepoName, uppercaseVersion(nextV), true)\n\tif err != nil {\n\t\treturn ReleaseMilestones{}, err\n\t}\n\tif kind == KindMajor {\n\t\t\/\/ Create the first minor release milestone too.\n\t\tfirstMinor := majorVersion + \".1\"\n\t\tif err != nil {\n\t\t\treturn ReleaseMilestones{}, err\n\t\t}\n\t\t_, err = m.Client.FetchMilestone(ctx, m.RepoOwner, m.RepoName, uppercaseVersion(firstMinor), true)\n\t\tif err != nil {\n\t\t\treturn ReleaseMilestones{}, err\n\t\t}\n\t}\n\treturn ReleaseMilestones{Current: currentMilestone, Next: nextMilestone}, nil\n}\n\nfunc uppercaseVersion(version string) string {\n\treturn strings.Replace(version, \"go\", \"Go\", 1)\n}\n\n\/\/ CheckBlockers returns an error if there are open release blockers in\n\/\/ the current milestone.\nfunc (m *MilestoneTasks) CheckBlockers(ctx *workflow.TaskContext, milestones ReleaseMilestones, version string, kind ReleaseKind) error {\n\tif kind == KindRC {\n\t\t\/\/ We don't check blockers for release candidates; they're expected to\n\t\t\/\/ at least have recurring blockers, and we don't have an okay-after\n\t\t\/\/ label to suppress them.\n\t\treturn nil\n\t}\n\tissues, err := m.loadMilestoneIssues(ctx, milestones.Current, kind)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar blockers []string\n\tfor number, labels := range issues {\n\t\treleaseBlocker := labels[\"release-blocker\"]\n\t\tif kind == KindBeta && (labels[\"okay-after-beta1\"] || !strings.HasSuffix(version, \"beta1\")) {\n\t\t\treleaseBlocker = false\n\t\t}\n\t\tif releaseBlocker {\n\t\t\tblockers = append(blockers, fmt.Sprintf(\"https:\/\/go.dev\/issue\/%v\", number))\n\t\t}\n\t}\n\tsort.Strings(blockers)\n\tif len(blockers) != 0 {\n\t\treturn fmt.Errorf(\"open release blockers:\\n%v\", strings.Join(blockers, \"\\n\"))\n\t}\n\treturn nil\n}\n\n\/\/ loadMilestoneIssues returns all the open issues in the specified milestone\n\/\/ and their labels.\nfunc (m *MilestoneTasks) loadMilestoneIssues(ctx *workflow.TaskContext, milestoneID int, kind ReleaseKind) (map[int]map[string]bool, error) {\n\tissues := map[int]map[string]bool{}\n\tvar query struct {\n\t\tRepository struct {\n\t\t\tIssues struct {\n\t\t\t\tPageInfo struct {\n\t\t\t\t\tEndCursor   githubv4.String\n\t\t\t\t\tHasNextPage bool\n\t\t\t\t}\n\n\t\t\t\tNodes []struct {\n\t\t\t\t\tNumber int\n\t\t\t\t\tID     githubv4.ID\n\t\t\t\t\tTitle  string\n\t\t\t\t\tLabels struct {\n\t\t\t\t\t\tPageInfo struct {\n\t\t\t\t\t\t\tHasNextPage bool\n\t\t\t\t\t\t}\n\t\t\t\t\t\tNodes []struct {\n\t\t\t\t\t\t\tName string\n\t\t\t\t\t\t}\n\t\t\t\t\t} `graphql:\"labels(first:10)\"`\n\t\t\t\t}\n\t\t\t} `graphql:\"issues(first:100, after:$afterToken, filterBy:{states:OPEN, milestoneNumber:$milestoneNumber})\"`\n\t\t} `graphql:\"repository(owner: $repoOwner, name: $repoName)\"`\n\t}\n\tvar afterToken *githubv4.String\nmore:\n\tif err := m.Client.Query(ctx, &query, map[string]interface{}{\n\t\t\"repoOwner\":       githubv4.String(m.RepoOwner),\n\t\t\"repoName\":        githubv4.String(m.RepoName),\n\t\t\"milestoneNumber\": githubv4.String(fmt.Sprint(milestoneID)),\n\t\t\"afterToken\":      afterToken,\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, issue := range query.Repository.Issues.Nodes {\n\t\tif issue.Labels.PageInfo.HasNextPage {\n\t\t\treturn nil, fmt.Errorf(\"issue %v (#%v) has more than 10 labels\", issue.Title, issue.Number)\n\t\t}\n\t\tlabels := map[string]bool{}\n\t\tfor _, label := range issue.Labels.Nodes {\n\t\t\tlabels[label.Name] = true\n\t\t}\n\t\tissues[issue.Number] = labels\n\t}\n\tif query.Repository.Issues.PageInfo.HasNextPage {\n\t\tafterToken = &query.Repository.Issues.PageInfo.EndCursor\n\t\tgoto more\n\t}\n\treturn issues, nil\n}\n\n\/\/ PushIssues updates issues to reflect a finished release. For beta1 releases,\n\/\/ it removes the okay-after-beta1 label. For major and minor releases,\n\/\/ it moves them to the next milestone and closes the current one.\nfunc (m *MilestoneTasks) PushIssues(ctx *workflow.TaskContext, milestones ReleaseMilestones, version string, kind ReleaseKind) error {\n\t\/\/ For RCs we don't change issues at all.\n\tif kind == KindRC {\n\t\treturn nil\n\t}\n\n\tissues, err := m.loadMilestoneIssues(ctx, milestones.Current, KindUnknown)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor issueNumber, labels := range issues {\n\t\tvar newLabels *[]string\n\t\tvar newMilestone *int\n\t\tif kind == KindBeta && strings.HasSuffix(version, \"beta1\") {\n\t\t\tif labels[\"okay-after-beta1\"] {\n\t\t\t\tnewLabels = &[]string{}\n\t\t\t\tfor label := range labels {\n\t\t\t\t\tif label == \"okay-after-beta1\" {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t*newLabels = append(*newLabels, label)\n\t\t\t\t}\n\t\t\t}\n\t\t} else if kind == KindMajor || kind == KindCurrentMinor || kind == KindPrevMinor {\n\t\t\tnewMilestone = &milestones.Next\n\t\t}\n\t\t_, _, err := m.Client.EditIssue(ctx, m.RepoOwner, m.RepoName, issueNumber, &github.IssueRequest{\n\t\t\tMilestone: newMilestone,\n\t\t\tLabels:    newLabels,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif kind == KindMajor || kind == KindCurrentMinor || kind == KindPrevMinor {\n\t\t_, _, err := m.Client.EditMilestone(ctx, m.RepoOwner, m.RepoName, milestones.Current, &github.Milestone{\n\t\t\tState: github.String(\"closed\"),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ GitHubClientInterface is a wrapper around the GitHub v3 and v4 APIs, for\n\/\/ testing and dry-run support.\ntype GitHubClientInterface interface {\n\t\/\/ FetchMilestone returns the number of the requested milestone. If create is true,\n\t\/\/ and the milestone doesn't exist, it will be created.\n\tFetchMilestone(ctx context.Context, owner, repo, name string, create bool) (int, error)\n\n\t\/\/ See githubv4.Client.Query.\n\tQuery(ctx context.Context, q interface{}, variables map[string]interface{}) error\n\n\t\/\/ See github.Client.Issues.Edit.\n\tEditIssue(ctx context.Context, owner string, repo string, number int, issue *github.IssueRequest) (*github.Issue, *github.Response, error)\n\n\t\/\/ See github.Client.Issues.EditMilestone\n\tEditMilestone(ctx context.Context, owner string, repo string, number int, milestone *github.Milestone) (*github.Milestone, *github.Response, error)\n}\n\ntype GitHubClient struct {\n\tV3 *github.Client\n\tV4 *githubv4.Client\n}\n\nfunc (c *GitHubClient) Query(ctx context.Context, q interface{}, variables map[string]interface{}) error {\n\treturn c.V4.Query(ctx, q, variables)\n}\n\nfunc (c *GitHubClient) FetchMilestone(ctx context.Context, owner, repo, name string, create bool) (int, error) {\n\tn, found, err := findMilestone(ctx, c.V4, owner, repo, name)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif found {\n\t\treturn n, nil\n\t} else if !create {\n\t\treturn 0, fmt.Errorf(\"no milestone named %q found, and creation was disabled\", name)\n\t}\n\tm, _, createErr := c.V3.Issues.CreateMilestone(ctx, owner, repo, &github.Milestone{\n\t\tTitle: github.String(name),\n\t})\n\tif createErr != nil {\n\t\treturn 0, fmt.Errorf(\"could not find an open milestone named %q and creating it failed: %v\", name, createErr)\n\t}\n\treturn *m.Number, nil\n}\n\nfunc findMilestone(ctx context.Context, client *githubv4.Client, owner, repo, name string) (int, bool, error) {\n\tvar query struct {\n\t\tRepository struct {\n\t\t\tMilestones struct {\n\t\t\t\tNodes []struct {\n\t\t\t\t\tTitle  string\n\t\t\t\t\tNumber int\n\t\t\t\t\tState  string\n\t\t\t\t}\n\t\t\t} `graphql:\"milestones(first:10, query: $milestoneName)\"`\n\t\t} `graphql:\"repository(owner: $repoOwner, name: $repoName)\"`\n\t}\n\tif err := client.Query(ctx, &query, map[string]interface{}{\n\t\t\"repoOwner\":     githubv4.String(owner),\n\t\t\"repoName\":      githubv4.String(repo),\n\t\t\"milestoneName\": githubv4.String(name),\n\t}); err != nil {\n\t\treturn 0, false, err\n\t}\n\t\/\/ The milestone query is case-insensitive and a partial match; we're okay\n\t\/\/ with case variations but it needs to be a full match.\n\tvar open, closed []string\n\tmilestoneNumber := 0\n\tfor _, m := range query.Repository.Milestones.Nodes {\n\t\tif strings.ToLower(name) != strings.ToLower(m.Title) {\n\t\t\tcontinue\n\t\t}\n\t\tif m.State == \"OPEN\" {\n\t\t\topen = append(open, m.Title)\n\t\t\tmilestoneNumber = m.Number\n\t\t} else {\n\t\t\tclosed = append(closed, m.Title)\n\t\t}\n\t}\n\t\/\/ GitHub allows \"go\" and \"Go\" to exist at the same time.\n\t\/\/ If there's any confusion, fail: we expect either one open milestone,\n\t\/\/ or no matching milestones at all.\n\tswitch {\n\tcase len(open) == 1:\n\t\treturn milestoneNumber, true, nil\n\tcase len(open) > 1:\n\t\treturn 0, false, fmt.Errorf(\"multiple open milestones matching %q: %q\", name, open)\n\t\/\/ No open milestones.\n\tcase len(closed) == 0:\n\t\treturn 0, false, nil\n\tcase len(closed) > 0:\n\t\treturn 0, false, fmt.Errorf(\"no open milestones matching %q, but some closed: %q (re-open or delete?)\", name, closed)\n\t}\n\t\/\/ The switch above is exhaustive.\n\tpanic(fmt.Errorf(\"unhandled case: open: %q closed: %q\", open, closed))\n}\n\nfunc (c *GitHubClient) EditIssue(ctx context.Context, owner string, repo string, number int, issue *github.IssueRequest) (*github.Issue, *github.Response, error) {\n\treturn c.V3.Issues.Edit(ctx, owner, repo, number, issue)\n}\n\nfunc (c *GitHubClient) EditMilestone(ctx context.Context, owner string, repo string, number int, milestone *github.Milestone) (*github.Milestone, *github.Response, error) {\n\treturn c.V3.Issues.EditMilestone(ctx, owner, repo, number, milestone)\n}\n<|endoftext|>"}
{"text":"<commit_before>package template\n\nvar (\n\tModule = `module {{.Dir}}\n\ngo 1.15\n\nrequire (\n\tgithub.com\/micro\/micro\/v3 v3.0.0-beta.4.0.20200922151713-de8b56c2b15d\n\tgithub.com\/micro\/go-micro\/v3 v3.0.0-beta.2.0.20200922112322-927d4f8eced6\n)\n\n\/\/ This can be removed once etcd becomes go gettable, version 3.4 and 3.5 is not,\n\/\/ see https:\/\/github.com\/etcd-io\/etcd\/issues\/11154 and https:\/\/github.com\/etcd-io\/etcd\/issues\/11931.\nreplace google.golang.org\/grpc => google.golang.org\/grpc v1.26.0\n`\n)\n<commit_msg>Bump deps of micro newed services (#1561)<commit_after>package template\n\nvar (\n\tModule = `module {{.Dir}}\n\ngo 1.15\n\nrequire (\n\tgithub.com\/micro\/micro\/v3 v3.0.0-beta.7\n)\n\n\/\/ This can be removed once etcd becomes go gettable, version 3.4 and 3.5 is not,\n\/\/ see https:\/\/github.com\/etcd-io\/etcd\/issues\/11154 and https:\/\/github.com\/etcd-io\/etcd\/issues\/11931.\nreplace google.golang.org\/grpc => google.golang.org\/grpc v1.26.0\n`\n)\n<|endoftext|>"}
{"text":"<commit_before>\/*--------------------------------------------------------*\\\n|                                                          |\n|                          hprose                          |\n|                                                          |\n| Official WebSite: https:\/\/hprose.com                     |\n|                                                          |\n| io\/encoding\/time_encoder.go                              |\n|                                                          |\n| LastModified: Mar 20, 2020                               |\n| Author: Ma Bingyao <andot@hprose.com>                    |\n|                                                          |\n\\*________________________________________________________*\/\n\npackage encoding\n\nimport (\n\t\"reflect\"\n\t\"time\"\n\n\t\"github.com\/modern-go\/reflect2\"\n)\n\n\/\/ TimeEncoder is the implementation of ValueEncoder for time.Time\/*time.Time.\ntype TimeEncoder struct{}\n\n\/\/ Encode writes the hprose encoding of v to stream\n\/\/ if v is already written to stream, it will writes it as reference\nfunc (valenc TimeEncoder) Encode(enc *Encoder, v interface{}) (err error) {\n\tif reflect.TypeOf(v).Kind() == reflect.Struct {\n\t\treturn valenc.Write(enc, v)\n\t}\n\tif reflect2.IsNil(v) {\n\t\treturn WriteNil(enc.Writer)\n\t}\n\tvar ok bool\n\tif ok, err = enc.WriteReference(v); !ok && err == nil {\n\t\terr = valenc.Write(enc, v)\n\t}\n\treturn\n}\n\n\/\/ Write writes the hprose encoding of v to stream\n\/\/ if v is already written to stream, it will writes it as value\nfunc (TimeEncoder) Write(enc *Encoder, v interface{}) (err error) {\n\tt := reflect.TypeOf(v)\n\tif t.Kind() == reflect.Ptr {\n\t\tenc.SetReference(v)\n\t} else {\n\t\tenc.AddReferenceCount(1)\n\t}\n\treturn WriteTime(enc.Writer, *(*time.Time)(reflect2.PtrOf(v)))\n}\n\nfunc init() {\n\tRegisterEncoder((*time.Time)(nil), TimeEncoder{})\n}\n<commit_msg>Update time_encoder.go<commit_after>\/*--------------------------------------------------------*\\\n|                                                          |\n|                          hprose                          |\n|                                                          |\n| Official WebSite: https:\/\/hprose.com                     |\n|                                                          |\n| io\/encoding\/time_encoder.go                              |\n|                                                          |\n| LastModified: Mar 21, 2020                               |\n| Author: Ma Bingyao <andot@hprose.com>                    |\n|                                                          |\n\\*________________________________________________________*\/\n\npackage encoding\n\nimport (\n\t\"time\"\n\n\t\"github.com\/modern-go\/reflect2\"\n)\n\n\/\/ TimeEncoder is the implementation of ValueEncoder for time.Time\/*time.Time.\ntype TimeEncoder struct{}\n\n\/\/ Encode writes the hprose encoding of v to stream\n\/\/ if v is already written to stream, it will writes it as reference\nfunc (valenc TimeEncoder) Encode(enc *Encoder, v interface{}) (err error) {\n\treturn ReferenceEncode(valenc, enc, v)\n}\n\n\/\/ Write writes the hprose encoding of v to stream\n\/\/ if v is already written to stream, it will writes it as value\nfunc (TimeEncoder) Write(enc *Encoder, v interface{}) (err error) {\n\tSetReference(enc, v)\n\treturn WriteTime(enc.Writer, *(*time.Time)(reflect2.PtrOf(v)))\n}\n\nfunc init() {\n\tRegisterEncoder((*time.Time)(nil), TimeEncoder{})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build linux\n\npackage hsup\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"code.google.com\/p\/go-uuid\/uuid\"\n\n\t\"github.com\/docker\/libcontainer\"\n\t\"github.com\/docker\/libcontainer\/cgroups\"\n\t\"github.com\/docker\/libcontainer\/devices\"\n\t\"github.com\/docker\/libcontainer\/mount\"\n\t\"github.com\/docker\/libcontainer\/namespaces\"\n)\n\ntype LibContainerDynoDriver struct {\n\tworkDir       string\n\tstacksDir     string\n\tcontainersDir string\n\tallocator     *Allocator\n}\n\nfunc NewLibContainerDynoDriver(workDir string) (*LibContainerDynoDriver, error) {\n\tvar (\n\t\tstacksDir     = filepath.Join(workDir, \"stacks\")\n\t\tcontainersDir = filepath.Join(workDir, \"containers\")\n\t)\n\tif err := os.MkdirAll(stacksDir, 0755); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := os.MkdirAll(containersDir, 0755); err != nil {\n\t\treturn nil, err\n\t}\n\tallocator, err := NewAllocator(workDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &LibContainerDynoDriver{\n\t\tworkDir:       workDir,\n\t\tstacksDir:     stacksDir,\n\t\tcontainersDir: containersDir,\n\t\tallocator:     allocator,\n\t}, nil\n}\n\nfunc (dd *LibContainerDynoDriver) Build(release *Release) error {\n\tstacks, err := HerokuStacksFromManifest(dd.stacksDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, stack := range stacks {\n\t\tif strings.TrimSpace(stack.Name) != release.stack {\n\t\t\tcontinue\n\t\t}\n\t\tif err := stack.mount(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (dd *LibContainerDynoDriver) Start(ex *Executor) error {\n\tcontainerUUID := uuid.New()\n\tuid, gid, err := dd.allocator.ReserveUID()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsn, err := dd.allocator.privateNetForUID(uid)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsubnet, err := newSmallSubnet(sn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstackImagePath, err := CurrentStackImagePath(\n\t\tdd.stacksDir, ex.Release.stack,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdataPath := filepath.Join(dd.containersDir, containerUUID)\n\tif err := os.MkdirAll(dataPath, 0755); err != nil {\n\t\treturn err\n\t}\n\twritablePaths := []string{\n\t\tfilepath.Join(dataPath, \"app\"),\n\t\tfilepath.Join(dataPath, \"tmp\"),\n\t\tfilepath.Join(dataPath, \"var\", \"tmp\"),\n\t}\n\tfor _, path := range writablePaths {\n\t\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := os.Chown(path, uid, gid); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\trootFSPath := filepath.Join(dataPath, \"root\")\n\tif err := os.MkdirAll(rootFSPath, 0755); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ stack image is the rootFS\n\tif err := syscall.Mount(\n\t\tstackImagePath, rootFSPath, \"bind\",\n\t\tsyscall.MS_RDONLY|syscall.MS_BIND, \"\",\n\t); err != nil {\n\t\treturn err\n\t}\n\n\tif err := createPasswdWithDynoUser(\n\t\tstackImagePath, dataPath, uid, gid,\n\t); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ TODO: inject \/tmp\/slug.tgz if local\n\n\toutsideContainer, err := filepath.Abs(linuxAmd64Path())\n\tif err != nil {\n\t\treturn err\n\t}\n\tinsideContainer := filepath.Join(dataPath, \"tmp\", \"hsup\")\n\tif err := copyFile(outsideContainer, insideContainer, 0755); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ TODO tty\n\tconsole := \"\"\n\n\tex.initExitStatus = make(chan *ExitStatus)\n\n\tcfgReader, cfgWriter, err := os.Pipe()\n\tinitCtx := &containerInit{\n\t\thsupBinaryPath: outsideContainer,\n\t\tex:             ex,\n\t\tconfigPipe:     cfgReader,\n\t}\n\n\tcontainer := containerConfig(\n\t\tcontainerUUID,\n\t\tuid, gid,\n\t\tdataPath,\n\t\tsubnet,\n\t\tex.Release.ConfigSlice(),\n\t)\n\n\t\/\/ send config to the init process inside the container\n\tgo func() {\n\t\tdefer cfgWriter.Close()\n\t\tencoder := gob.NewEncoder(cfgWriter)\n\t\tif err := encoder.Encode(container); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\t\/\/ TODO: stop swallowing errors\n\t\tcode, err := namespaces.Exec(\n\t\t\tcontainer, os.Stdin, os.Stdout, os.Stderr,\n\t\t\tconsole, dataPath, []string{},\n\t\t\tinitCtx.createCommand, nil, initCtx.startCallback,\n\t\t)\n\t\tlog.Println(code, err)\n\n\t\t\/\/ GC\n\t\t\/\/ TODO: gc after sending back the exit status\n\t\t\/\/ doing so right now terminates the program too early,\n\t\t\/\/ before everything is removed\n\t\tif err := syscall.Unmount(rootFSPath, 0); err != nil {\n\t\t\tlog.Printf(\"unmount error: %#+v\", err)\n\t\t}\n\t\tfor _, path := range writablePaths {\n\t\t\tif err := os.RemoveAll(path); err != nil {\n\t\t\t\tlog.Printf(\"remove all error: %#+v\", err)\n\t\t\t}\n\t\t}\n\t\tif err := os.RemoveAll(dataPath); err != nil {\n\t\t\tlog.Printf(\"remove all error: %#+v\", err)\n\t\t}\n\n\t\t\/\/ it's probably safe to ignore errors here. Worst case\n\t\t\/\/ scenario, this uid won't be be reused.\n\t\tdd.allocator.FreeUID(uid)\n\n\t\tex.initExitStatus <- &ExitStatus{Code: code, Err: err}\n\t\tclose(ex.initExitStatus)\n\t}()\n\n\treturn nil\n}\n\nfunc (dd *LibContainerDynoDriver) Wait(ex *Executor) (s *ExitStatus) {\n\treturn <-ex.initExitStatus\n}\n\nfunc (dd *LibContainerDynoDriver) Stop(ex *Executor) error {\n\tif ex.cmd.ProcessState != nil {\n\t\treturn nil \/\/ already exited\n\t}\n\n\t\/\/ TODO: fix a race conditition when Stop() is called before the\n\t\/\/ libcontainer driver re-execs itself\n\n\t\/\/ tell the abspath-driver to stop\n\treturn ex.cmd.Process.Signal(syscall.SIGTERM)\n}\n\nfunc createPasswdWithDynoUser(stackImagePath, dataPath string, uid, gid int) error {\n\tvar contents bytes.Buffer\n\toriginal, err := os.Open(filepath.Join(stackImagePath, \"etc\", \"passwd\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer original.Close()\n\n\tif _, err := contents.ReadFrom(original); err != nil {\n\t\treturn err\n\t}\n\t\/\/ TODO: allocate a free uid. It is currently hardcoded to 1000\n\tdynoUser := fmt.Sprintf(\"\\ndyno:x:%d:%d::\/app:\/bin\/bash\\n\", uid, gid)\n\tif _, err := contents.WriteString(dynoUser); err != nil {\n\t\treturn err\n\t}\n\n\tdst, err := os.Create(filepath.Join(dataPath, \"passwd\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dst.Close()\n\tif err := dst.Chmod(0644); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = contents.WriteTo(dst)\n\treturn err\n}\n\ntype containerInit struct {\n\thsupBinaryPath string\n\tex             *Executor\n\tconfigPipe     *os.File\n}\n\nfunc (ctx *containerInit) createCommand(container *libcontainer.Config, console,\n\tdataPath, init string, controlPipe *os.File, args []string) *exec.Cmd {\n\n\ths := Startup{\n\t\tApp: AppSerializable{\n\t\t\tVersion: ctx.ex.Release.version,\n\t\t\tEnv:     ctx.ex.Release.config,\n\t\t\tSlug:    ctx.ex.Release.slugURL,\n\t\t\tStack:   ctx.ex.Release.stack,\n\t\t\tProcesses: []FormationSerializable{\n\t\t\t\t{\n\t\t\t\t\tFArgs:     ctx.ex.Args,\n\t\t\t\t\tFQuantity: 1,\n\t\t\t\t\tFType:     ctx.ex.ProcessType,\n\t\t\t\t},\n\t\t\t},\n\t\t\tLogplexURL: ctx.ex.logplexURLString(),\n\t\t},\n\t\tOneShot:     true,\n\t\tStartNumber: ctx.ex.ProcessID,\n\t\tAction:      Start,\n\t\tDriver:      &LibContainerInitDriver{},\n\t\tFormName:    ctx.ex.ProcessType,\n\t}\n\tcmd := exec.Command(ctx.hsupBinaryPath)\n\tcmd.Env = []string{\"HSUP_CONTROL_GOB=\" + hs.ToBase64Gob()}\n\tif cmd.SysProcAttr == nil {\n\t\tcmd.SysProcAttr = &syscall.SysProcAttr{}\n\t}\n\tcmd.SysProcAttr.Cloneflags = uintptr(\n\t\tnamespaces.GetNamespaceFlags(container.Namespaces),\n\t)\n\tcmd.SysProcAttr.Pdeathsig = syscall.SIGKILL\n\tcmd.ExtraFiles = []*os.File{controlPipe, ctx.configPipe}\n\tctx.ex.cmd = cmd\n\treturn cmd\n}\n\nfunc (ctx *containerInit) startCallback() {\n\t\/\/TODO: log(\"Starting process web.1 with command `...`\")\n\n\t\/\/child process is already running, it's safe to close the parent's read\n\t\/\/side of the pipe\n\tctx.configPipe.Close()\n}\n\nfunc containerConfig(\n\tcontainerUUID string,\n\tuid, gid int,\n\tdataPath string,\n\tsubnet *smallSubnet,\n\tenv []string,\n) *libcontainer.Config {\n\treturn &libcontainer.Config{\n\t\tMountConfig: &libcontainer.MountConfig{\n\t\t\tMounts: []*mount.Mount{\n\t\t\t\t{\n\t\t\t\t\tType:        \"bind\",\n\t\t\t\t\tDestination: \"\/app\",\n\t\t\t\t\tWritable:    true,\n\t\t\t\t\tSource:      filepath.Join(dataPath, \"app\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tType:        \"bind\",\n\t\t\t\t\tDestination: \"\/tmp\",\n\t\t\t\t\tWritable:    true,\n\t\t\t\t\tSource:      filepath.Join(dataPath, \"tmp\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tType:        \"bind\",\n\t\t\t\t\tDestination: \"\/var\/tmp\",\n\t\t\t\t\tWritable:    true,\n\t\t\t\t\tSource: filepath.Join(\n\t\t\t\t\t\tdataPath,\n\t\t\t\t\t\t\"var\", \"tmp\",\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tType:        \"bind\",\n\t\t\t\t\tDestination: \"\/etc\/passwd\",\n\t\t\t\t\tWritable:    false,\n\t\t\t\t\tSource: filepath.Join(\n\t\t\t\t\t\tdataPath, \"passwd\",\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tType:        \"bind\",\n\t\t\t\t\tWritable:    false,\n\t\t\t\t\tDestination: \"\/etc\/resolv.conf\",\n\t\t\t\t\tSource:      \"\/etc\/resolv.conf\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tMountLabel:  containerUUID,\n\t\t\tDeviceNodes: devices.DefaultSimpleDevices,\n\t\t\tPivotDir:    \"\/tmp\",\n\t\t},\n\t\tRootFs:   filepath.Join(dataPath, \"root\"),\n\t\tHostname: containerUUID,\n\t\tUser:     fmt.Sprintf(\"%d:%d\", uid, gid),\n\t\tEnv:      env,\n\t\tNamespaces: []libcontainer.Namespace{\n\t\t\t{Type: \"NEWIPC\"},\n\t\t\t{Type: \"NEWNET\"},\n\t\t\t{Type: \"NEWNS\"},\n\t\t\t{Type: \"NEWPID\"},\n\t\t\t{Type: \"NEWUTS\"},\n\t\t},\n\t\tCapabilities: []string{\n\t\t\t\"CHOWN\",\n\t\t\t\"DAC_OVERRIDE\",\n\t\t\t\"FOWNER\",\n\t\t\t\"MKNOD\",\n\t\t\t\"NET_RAW\",\n\t\t\t\"SETGID\",\n\t\t\t\"SETUID\",\n\t\t\t\"SETFCAP\",\n\t\t\t\"SETPCAP\",\n\t\t\t\"NET_BIND_SERVICE\",\n\t\t\t\"SYS_CHROOT\",\n\t\t\t\"KILL\",\n\t\t},\n\t\tNetworks: []*libcontainer.Network{\n\t\t\t{\n\t\t\t\tAddress: \"127.0.0.1\/0\",\n\t\t\t\tGateway: \"localhost\",\n\t\t\t\tMtu:     1500,\n\t\t\t\tType:    \"loopback\",\n\t\t\t},\n\t\t\t\/\/ TODO: setup our own network instead of using the docker bridge\n\t\t\t{\n\t\t\t\tAddress:    subnet.Host().String(),\n\t\t\t\tVethPrefix: fmt.Sprintf(\"veth%d\", uid),\n\t\t\t\tGateway:    subnet.Gateway().IP.String(),\n\t\t\t\tMtu:        1500,\n\t\t\t\tType:       \"routed\",\n\t\t\t},\n\t\t},\n\t\tCgroups: &cgroups.Cgroup{\n\t\t\tName:           containerUUID,\n\t\t\tAllowedDevices: devices.DefaultAllowedDevices,\n\t\t},\n\t}\n}\n<commit_msg>support local slugs in the libcontainer driver<commit_after>\/\/ +build linux\n\npackage hsup\n\nimport (\n\t\"bytes\"\n\t\"encoding\/gob\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"code.google.com\/p\/go-uuid\/uuid\"\n\n\t\"github.com\/docker\/libcontainer\"\n\t\"github.com\/docker\/libcontainer\/cgroups\"\n\t\"github.com\/docker\/libcontainer\/devices\"\n\t\"github.com\/docker\/libcontainer\/mount\"\n\t\"github.com\/docker\/libcontainer\/namespaces\"\n)\n\ntype LibContainerDynoDriver struct {\n\tworkDir       string\n\tstacksDir     string\n\tcontainersDir string\n\tallocator     *Allocator\n}\n\nfunc NewLibContainerDynoDriver(workDir string) (*LibContainerDynoDriver, error) {\n\tvar (\n\t\tstacksDir     = filepath.Join(workDir, \"stacks\")\n\t\tcontainersDir = filepath.Join(workDir, \"containers\")\n\t)\n\tif err := os.MkdirAll(stacksDir, 0755); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := os.MkdirAll(containersDir, 0755); err != nil {\n\t\treturn nil, err\n\t}\n\tallocator, err := NewAllocator(workDir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &LibContainerDynoDriver{\n\t\tworkDir:       workDir,\n\t\tstacksDir:     stacksDir,\n\t\tcontainersDir: containersDir,\n\t\tallocator:     allocator,\n\t}, nil\n}\n\nfunc (dd *LibContainerDynoDriver) Build(release *Release) error {\n\tstacks, err := HerokuStacksFromManifest(dd.stacksDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, stack := range stacks {\n\t\tif strings.TrimSpace(stack.Name) != release.stack {\n\t\t\tcontinue\n\t\t}\n\t\tif err := stack.mount(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (dd *LibContainerDynoDriver) Start(ex *Executor) error {\n\tcontainerUUID := uuid.New()\n\tuid, gid, err := dd.allocator.ReserveUID()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsn, err := dd.allocator.privateNetForUID(uid)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsubnet, err := newSmallSubnet(sn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstackImagePath, err := CurrentStackImagePath(\n\t\tdd.stacksDir, ex.Release.stack,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdataPath := filepath.Join(dd.containersDir, containerUUID)\n\tif err := os.MkdirAll(dataPath, 0755); err != nil {\n\t\treturn err\n\t}\n\twritablePaths := []string{\n\t\tfilepath.Join(dataPath, \"app\"),\n\t\tfilepath.Join(dataPath, \"tmp\"),\n\t\tfilepath.Join(dataPath, \"var\", \"tmp\"),\n\t}\n\tfor _, path := range writablePaths {\n\t\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := os.Chown(path, uid, gid); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\trootFSPath := filepath.Join(dataPath, \"root\")\n\tif err := os.MkdirAll(rootFSPath, 0755); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ stack image is the rootFS\n\tif err := syscall.Mount(\n\t\tstackImagePath, rootFSPath, \"bind\",\n\t\tsyscall.MS_RDONLY|syscall.MS_BIND, \"\",\n\t); err != nil {\n\t\treturn err\n\t}\n\n\tif err := createPasswdWithDynoUser(\n\t\tstackImagePath, dataPath, uid, gid,\n\t); err != nil {\n\t\treturn err\n\t}\n\n\tif ex.Release.Where() == Local {\n\t\t\/\/ move into the container\n\t\tif err := copyFile(\n\t\t\tex.Release.slugURL,\n\t\t\tfilepath.Join(dataPath, \"tmp\", \"slug.tgz\"),\n\t\t\t0644,\n\t\t); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tex.Release.slugURL = \"\/tmp\/slug.tgz\"\n\t}\n\n\toutsideContainer, err := filepath.Abs(linuxAmd64Path())\n\tif err != nil {\n\t\treturn err\n\t}\n\tinsideContainer := filepath.Join(dataPath, \"tmp\", \"hsup\")\n\tif err := copyFile(outsideContainer, insideContainer, 0755); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ TODO tty\n\tconsole := \"\"\n\n\tex.initExitStatus = make(chan *ExitStatus)\n\n\tcfgReader, cfgWriter, err := os.Pipe()\n\tinitCtx := &containerInit{\n\t\thsupBinaryPath: outsideContainer,\n\t\tex:             ex,\n\t\tconfigPipe:     cfgReader,\n\t}\n\n\tcontainer := containerConfig(\n\t\tcontainerUUID,\n\t\tuid, gid,\n\t\tdataPath,\n\t\tsubnet,\n\t\tex.Release.ConfigSlice(),\n\t)\n\n\t\/\/ send config to the init process inside the container\n\tgo func() {\n\t\tdefer cfgWriter.Close()\n\t\tencoder := gob.NewEncoder(cfgWriter)\n\t\tif err := encoder.Encode(container); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\n\tgo func() {\n\t\t\/\/ TODO: stop swallowing errors\n\t\tcode, err := namespaces.Exec(\n\t\t\tcontainer, os.Stdin, os.Stdout, os.Stderr,\n\t\t\tconsole, dataPath, []string{},\n\t\t\tinitCtx.createCommand, nil, initCtx.startCallback,\n\t\t)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"namespaces.Exec fails: %q\", err)\n\t\t}\n\n\t\t\/\/ GC\n\t\t\/\/ TODO: gc after sending back the exit status\n\t\t\/\/ doing so right now terminates the program too early,\n\t\t\/\/ before everything is removed\n\t\tif err := syscall.Unmount(rootFSPath, 0); err != nil {\n\t\t\tlog.Printf(\"unmount error: %#+v\", err)\n\t\t}\n\t\tfor _, path := range writablePaths {\n\t\t\tif err := os.RemoveAll(path); err != nil {\n\t\t\t\tlog.Printf(\"remove all error: %#+v\", err)\n\t\t\t}\n\t\t}\n\t\tif err := os.RemoveAll(dataPath); err != nil {\n\t\t\tlog.Printf(\"remove all error: %#+v\", err)\n\t\t}\n\n\t\t\/\/ it's probably safe to ignore errors here. Worst case\n\t\t\/\/ scenario, this uid won't be be reused.\n\t\tdd.allocator.FreeUID(uid)\n\n\t\tex.initExitStatus <- &ExitStatus{Code: code, Err: err}\n\t\tclose(ex.initExitStatus)\n\t}()\n\n\treturn nil\n}\n\nfunc (dd *LibContainerDynoDriver) Wait(ex *Executor) (s *ExitStatus) {\n\treturn <-ex.initExitStatus\n}\n\nfunc (dd *LibContainerDynoDriver) Stop(ex *Executor) error {\n\tif ex.cmd.ProcessState != nil {\n\t\treturn nil \/\/ already exited\n\t}\n\n\t\/\/ TODO: fix a race conditition when Stop() is called before the\n\t\/\/ libcontainer driver re-execs itself\n\n\t\/\/ tell the abspath-driver to stop\n\treturn ex.cmd.Process.Signal(syscall.SIGTERM)\n}\n\nfunc createPasswdWithDynoUser(stackImagePath, dataPath string, uid, gid int) error {\n\tvar contents bytes.Buffer\n\toriginal, err := os.Open(filepath.Join(stackImagePath, \"etc\", \"passwd\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer original.Close()\n\n\tif _, err := contents.ReadFrom(original); err != nil {\n\t\treturn err\n\t}\n\t\/\/ TODO: allocate a free uid. It is currently hardcoded to 1000\n\tdynoUser := fmt.Sprintf(\"\\ndyno:x:%d:%d::\/app:\/bin\/bash\\n\", uid, gid)\n\tif _, err := contents.WriteString(dynoUser); err != nil {\n\t\treturn err\n\t}\n\n\tdst, err := os.Create(filepath.Join(dataPath, \"passwd\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer dst.Close()\n\tif err := dst.Chmod(0644); err != nil {\n\t\treturn err\n\t}\n\n\t_, err = contents.WriteTo(dst)\n\treturn err\n}\n\ntype containerInit struct {\n\thsupBinaryPath string\n\tex             *Executor\n\tconfigPipe     *os.File\n}\n\nfunc (ctx *containerInit) createCommand(container *libcontainer.Config, console,\n\tdataPath, init string, controlPipe *os.File, args []string) *exec.Cmd {\n\n\ths := Startup{\n\t\tApp: AppSerializable{\n\t\t\tVersion: ctx.ex.Release.version,\n\t\t\tEnv:     ctx.ex.Release.config,\n\t\t\tSlug:    ctx.ex.Release.slugURL,\n\t\t\tStack:   ctx.ex.Release.stack,\n\t\t\tProcesses: []FormationSerializable{\n\t\t\t\t{\n\t\t\t\t\tFArgs:     ctx.ex.Args,\n\t\t\t\t\tFQuantity: 1,\n\t\t\t\t\tFType:     ctx.ex.ProcessType,\n\t\t\t\t},\n\t\t\t},\n\t\t\tLogplexURL: ctx.ex.logplexURLString(),\n\t\t},\n\t\tOneShot:     true,\n\t\tStartNumber: ctx.ex.ProcessID,\n\t\tAction:      Start,\n\t\tDriver:      &LibContainerInitDriver{},\n\t\tFormName:    ctx.ex.ProcessType,\n\t}\n\tcmd := exec.Command(ctx.hsupBinaryPath)\n\tcmd.Env = []string{\"HSUP_CONTROL_GOB=\" + hs.ToBase64Gob()}\n\tif cmd.SysProcAttr == nil {\n\t\tcmd.SysProcAttr = &syscall.SysProcAttr{}\n\t}\n\tcmd.SysProcAttr.Cloneflags = uintptr(\n\t\tnamespaces.GetNamespaceFlags(container.Namespaces),\n\t)\n\tcmd.SysProcAttr.Pdeathsig = syscall.SIGKILL\n\tcmd.ExtraFiles = []*os.File{controlPipe, ctx.configPipe}\n\tctx.ex.cmd = cmd\n\treturn cmd\n}\n\nfunc (ctx *containerInit) startCallback() {\n\t\/\/TODO: log(\"Starting process web.1 with command `...`\")\n\n\t\/\/child process is already running, it's safe to close the parent's read\n\t\/\/side of the pipe\n\tctx.configPipe.Close()\n}\n\nfunc containerConfig(\n\tcontainerUUID string,\n\tuid, gid int,\n\tdataPath string,\n\tsubnet *smallSubnet,\n\tenv []string,\n) *libcontainer.Config {\n\treturn &libcontainer.Config{\n\t\tMountConfig: &libcontainer.MountConfig{\n\t\t\tMounts: []*mount.Mount{\n\t\t\t\t{\n\t\t\t\t\tType:        \"bind\",\n\t\t\t\t\tDestination: \"\/app\",\n\t\t\t\t\tWritable:    true,\n\t\t\t\t\tSource:      filepath.Join(dataPath, \"app\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tType:        \"bind\",\n\t\t\t\t\tDestination: \"\/tmp\",\n\t\t\t\t\tWritable:    true,\n\t\t\t\t\tSource:      filepath.Join(dataPath, \"tmp\"),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tType:        \"bind\",\n\t\t\t\t\tDestination: \"\/var\/tmp\",\n\t\t\t\t\tWritable:    true,\n\t\t\t\t\tSource: filepath.Join(\n\t\t\t\t\t\tdataPath,\n\t\t\t\t\t\t\"var\", \"tmp\",\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tType:        \"bind\",\n\t\t\t\t\tDestination: \"\/etc\/passwd\",\n\t\t\t\t\tWritable:    false,\n\t\t\t\t\tSource: filepath.Join(\n\t\t\t\t\t\tdataPath, \"passwd\",\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tType:        \"bind\",\n\t\t\t\t\tWritable:    false,\n\t\t\t\t\tDestination: \"\/etc\/resolv.conf\",\n\t\t\t\t\tSource:      \"\/etc\/resolv.conf\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tMountLabel:  containerUUID,\n\t\t\tDeviceNodes: devices.DefaultSimpleDevices,\n\t\t\tPivotDir:    \"\/tmp\",\n\t\t},\n\t\tRootFs:   filepath.Join(dataPath, \"root\"),\n\t\tHostname: containerUUID,\n\t\tUser:     fmt.Sprintf(\"%d:%d\", uid, gid),\n\t\tEnv:      env,\n\t\tNamespaces: []libcontainer.Namespace{\n\t\t\t{Type: \"NEWIPC\"},\n\t\t\t{Type: \"NEWNET\"},\n\t\t\t{Type: \"NEWNS\"},\n\t\t\t{Type: \"NEWPID\"},\n\t\t\t{Type: \"NEWUTS\"},\n\t\t},\n\t\tCapabilities: []string{\n\t\t\t\"CHOWN\",\n\t\t\t\"DAC_OVERRIDE\",\n\t\t\t\"FOWNER\",\n\t\t\t\"MKNOD\",\n\t\t\t\"NET_RAW\",\n\t\t\t\"SETGID\",\n\t\t\t\"SETUID\",\n\t\t\t\"SETFCAP\",\n\t\t\t\"SETPCAP\",\n\t\t\t\"NET_BIND_SERVICE\",\n\t\t\t\"SYS_CHROOT\",\n\t\t\t\"KILL\",\n\t\t},\n\t\tNetworks: []*libcontainer.Network{\n\t\t\t{\n\t\t\t\tAddress: \"127.0.0.1\/0\",\n\t\t\t\tGateway: \"localhost\",\n\t\t\t\tMtu:     1500,\n\t\t\t\tType:    \"loopback\",\n\t\t\t},\n\t\t\t\/\/ TODO: setup our own network instead of using the docker bridge\n\t\t\t{\n\t\t\t\tAddress:    subnet.Host().String(),\n\t\t\t\tVethPrefix: fmt.Sprintf(\"veth%d\", uid),\n\t\t\t\tGateway:    subnet.Gateway().IP.String(),\n\t\t\t\tMtu:        1500,\n\t\t\t\tType:       \"routed\",\n\t\t\t},\n\t\t},\n\t\tCgroups: &cgroups.Cgroup{\n\t\t\tName:           containerUUID,\n\t\t\tAllowedDevices: devices.DefaultAllowedDevices,\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package libnetwork\n\nimport (\n\t\"encoding\/json\"\n\t\"net\"\n\n\t\"github.com\/docker\/libnetwork\/driverapi\"\n\t\"github.com\/docker\/libnetwork\/types\"\n)\n\n\/\/ EndpointInfo provides an interface to retrieve network resources bound to the endpoint.\ntype EndpointInfo interface {\n\t\/\/ InterfaceList returns an interface list which were assigned to the endpoint\n\t\/\/ by the driver. This can be used after the endpoint has been created.\n\tInterfaceList() []InterfaceInfo\n\n\t\/\/ Gateway returns the IPv4 gateway assigned by the driver.\n\t\/\/ This will only return a valid value if a container has joined the endpoint.\n\tGateway() net.IP\n\n\t\/\/ GatewayIPv6 returns the IPv6 gateway assigned by the driver.\n\t\/\/ This will only return a valid value if a container has joined the endpoint.\n\tGatewayIPv6() net.IP\n\n\t\/\/ SandboxKey returns the sanbox key for the container which has joined\n\t\/\/ the endpoint. If there is no container joined then this will return an\n\t\/\/ empty string.\n\tSandboxKey() string\n}\n\n\/\/ InterfaceInfo provides an interface to retrieve interface addresses bound to the endpoint.\ntype InterfaceInfo interface {\n\t\/\/ MacAddress returns the MAC address assigned to the endpoint.\n\tMacAddress() net.HardwareAddr\n\n\t\/\/ Address returns the IPv4 address assigned to the endpoint.\n\tAddress() net.IPNet\n\n\t\/\/ AddressIPv6 returns the IPv6 address assigned to the endpoint.\n\tAddressIPv6() net.IPNet\n}\n\n\/\/ ContainerInfo provides an interface to retrieve the info about the container attached to the endpoint\ntype ContainerInfo interface {\n\t\/\/ ID returns the ID of the container\n\tID() string\n\t\/\/ Labels returns the container's labels\n\tLabels() map[string]interface{}\n}\n\ntype endpointInterface struct {\n\tid        int\n\tmac       net.HardwareAddr\n\taddr      net.IPNet\n\taddrv6    net.IPNet\n\tsrcName   string\n\tdstPrefix string\n\troutes    []*net.IPNet\n}\n\nfunc (epi *endpointInterface) MarshalJSON() ([]byte, error) {\n\tepMap := make(map[string]interface{})\n\tepMap[\"id\"] = epi.id\n\tepMap[\"mac\"] = epi.mac.String()\n\tepMap[\"addr\"] = epi.addr.String()\n\tepMap[\"addrv6\"] = epi.addrv6.String()\n\tepMap[\"srcName\"] = epi.srcName\n\tepMap[\"dstPrefix\"] = epi.dstPrefix\n\tvar routes []string\n\tfor _, route := range epi.routes {\n\t\troutes = append(routes, route.String())\n\t}\n\tepMap[\"routes\"] = routes\n\treturn json.Marshal(epMap)\n}\n\nfunc (epi *endpointInterface) UnmarshalJSON(b []byte) (err error) {\n\tvar epMap map[string]interface{}\n\tif err := json.Unmarshal(b, &epMap); err != nil {\n\t\treturn err\n\t}\n\tepi.id = int(epMap[\"id\"].(float64))\n\n\tmac, _ := net.ParseMAC(epMap[\"mac\"].(string))\n\tepi.mac = mac\n\n\t_, ipnet, _ := net.ParseCIDR(epMap[\"addr\"].(string))\n\tif ipnet != nil {\n\t\tepi.addr = *ipnet\n\t}\n\n\t_, ipnet, _ = net.ParseCIDR(epMap[\"addrv6\"].(string))\n\tif ipnet != nil {\n\t\tepi.addrv6 = *ipnet\n\t}\n\n\tepi.srcName = epMap[\"srcName\"].(string)\n\tepi.dstPrefix = epMap[\"dstPrefix\"].(string)\n\n\trb, _ := json.Marshal(epMap[\"routes\"])\n\tvar routes []string\n\tjson.Unmarshal(rb, &routes)\n\tepi.routes = make([]*net.IPNet, 0)\n\tfor _, route := range routes {\n\t\t_, ipr, err := net.ParseCIDR(route)\n\t\tif err == nil {\n\t\t\tepi.routes = append(epi.routes, ipr)\n\t\t}\n\t}\n\n\treturn nil\n}\n\ntype endpointJoinInfo struct {\n\tgw             net.IP\n\tgw6            net.IP\n\thostsPath      string\n\tresolvConfPath string\n\tStaticRoutes   []*types.StaticRoute\n}\n\nfunc (ep *endpoint) ContainerInfo() ContainerInfo {\n\tep.Lock()\n\tci := ep.container\n\tdefer ep.Unlock()\n\n\t\/\/ Need this since we return the interface\n\tif ci == nil {\n\t\treturn nil\n\t}\n\treturn ci\n}\n\nfunc (ep *endpoint) Info() EndpointInfo {\n\treturn ep\n}\n\nfunc (ep *endpoint) DriverInfo() (map[string]interface{}, error) {\n\tep.Lock()\n\tnetwork := ep.network\n\tepid := ep.id\n\tep.Unlock()\n\n\tnetwork.Lock()\n\tdriver := network.driver\n\tnid := network.id\n\tnetwork.Unlock()\n\n\treturn driver.EndpointOperInfo(nid, epid)\n}\n\nfunc (ep *endpoint) InterfaceList() []InterfaceInfo {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tiList := make([]InterfaceInfo, len(ep.iFaces))\n\n\tfor i, iface := range ep.iFaces {\n\t\tiList[i] = iface\n\t}\n\n\treturn iList\n}\n\nfunc (ep *endpoint) Interfaces() []driverapi.InterfaceInfo {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tiList := make([]driverapi.InterfaceInfo, len(ep.iFaces))\n\n\tfor i, iface := range ep.iFaces {\n\t\tiList[i] = iface\n\t}\n\n\treturn iList\n}\n\nfunc (ep *endpoint) AddInterface(id int, mac net.HardwareAddr, ipv4 net.IPNet, ipv6 net.IPNet) error {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tiface := &endpointInterface{\n\t\tid:     id,\n\t\taddr:   *types.GetIPNetCopy(&ipv4),\n\t\taddrv6: *types.GetIPNetCopy(&ipv6),\n\t}\n\tiface.mac = types.GetMacCopy(mac)\n\n\tep.iFaces = append(ep.iFaces, iface)\n\treturn nil\n}\n\nfunc (epi *endpointInterface) ID() int {\n\treturn epi.id\n}\n\nfunc (epi *endpointInterface) MacAddress() net.HardwareAddr {\n\treturn types.GetMacCopy(epi.mac)\n}\n\nfunc (epi *endpointInterface) Address() net.IPNet {\n\treturn (*types.GetIPNetCopy(&epi.addr))\n}\n\nfunc (epi *endpointInterface) AddressIPv6() net.IPNet {\n\treturn (*types.GetIPNetCopy(&epi.addrv6))\n}\n\nfunc (epi *endpointInterface) SetNames(srcName string, dstPrefix string) error {\n\tepi.srcName = srcName\n\tepi.dstPrefix = dstPrefix\n\treturn nil\n}\n\nfunc (ep *endpoint) InterfaceNames() []driverapi.InterfaceNameInfo {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tiList := make([]driverapi.InterfaceNameInfo, len(ep.iFaces))\n\n\tfor i, iface := range ep.iFaces {\n\t\tiList[i] = iface\n\t}\n\n\treturn iList\n}\n\nfunc (ep *endpoint) AddStaticRoute(destination *net.IPNet, routeType int, nextHop net.IP, interfaceID int) error {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tr := types.StaticRoute{Destination: destination, RouteType: routeType, NextHop: nextHop, InterfaceID: interfaceID}\n\n\tif routeType == types.NEXTHOP {\n\t\t\/\/ If the route specifies a next-hop, then it's loosely routed (i.e. not bound to a particular interface).\n\t\tep.joinInfo.StaticRoutes = append(ep.joinInfo.StaticRoutes, &r)\n\t} else {\n\t\t\/\/ If the route doesn't specify a next-hop, it must be a connected route, bound to an interface.\n\t\tif err := ep.addInterfaceRoute(&r); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (ep *endpoint) addInterfaceRoute(route *types.StaticRoute) error {\n\tfor _, iface := range ep.iFaces {\n\t\tif iface.id == route.InterfaceID {\n\t\t\tiface.routes = append(iface.routes, route.Destination)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn types.BadRequestErrorf(\"Interface with ID %d doesn't exist.\",\n\t\troute.InterfaceID)\n}\n\nfunc (ep *endpoint) SandboxKey() string {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tif ep.container == nil {\n\t\treturn \"\"\n\t}\n\n\treturn ep.container.data.SandboxKey\n}\n\nfunc (ep *endpoint) Gateway() net.IP {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tif ep.joinInfo == nil {\n\t\treturn net.IP{}\n\t}\n\n\treturn types.GetIPCopy(ep.joinInfo.gw)\n}\n\nfunc (ep *endpoint) GatewayIPv6() net.IP {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tif ep.joinInfo == nil {\n\t\treturn net.IP{}\n\t}\n\n\treturn types.GetIPCopy(ep.joinInfo.gw6)\n}\n\nfunc (ep *endpoint) SetGateway(gw net.IP) error {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tep.joinInfo.gw = types.GetIPCopy(gw)\n\treturn nil\n}\n\nfunc (ep *endpoint) SetGatewayIPv6(gw6 net.IP) error {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tep.joinInfo.gw6 = types.GetIPCopy(gw6)\n\treturn nil\n}\n\nfunc (ep *endpoint) SetHostsPath(path string) error {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tep.joinInfo.hostsPath = path\n\treturn nil\n}\n\nfunc (ep *endpoint) SetResolvConfPath(path string) error {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tep.joinInfo.resolvConfPath = path\n\treturn nil\n}\n<commit_msg>Fix endpoint ip data-store sync issue<commit_after>package libnetwork\n\nimport (\n\t\"encoding\/json\"\n\t\"net\"\n\n\t\"github.com\/docker\/libnetwork\/driverapi\"\n\t\"github.com\/docker\/libnetwork\/types\"\n)\n\n\/\/ EndpointInfo provides an interface to retrieve network resources bound to the endpoint.\ntype EndpointInfo interface {\n\t\/\/ InterfaceList returns an interface list which were assigned to the endpoint\n\t\/\/ by the driver. This can be used after the endpoint has been created.\n\tInterfaceList() []InterfaceInfo\n\n\t\/\/ Gateway returns the IPv4 gateway assigned by the driver.\n\t\/\/ This will only return a valid value if a container has joined the endpoint.\n\tGateway() net.IP\n\n\t\/\/ GatewayIPv6 returns the IPv6 gateway assigned by the driver.\n\t\/\/ This will only return a valid value if a container has joined the endpoint.\n\tGatewayIPv6() net.IP\n\n\t\/\/ SandboxKey returns the sanbox key for the container which has joined\n\t\/\/ the endpoint. If there is no container joined then this will return an\n\t\/\/ empty string.\n\tSandboxKey() string\n}\n\n\/\/ InterfaceInfo provides an interface to retrieve interface addresses bound to the endpoint.\ntype InterfaceInfo interface {\n\t\/\/ MacAddress returns the MAC address assigned to the endpoint.\n\tMacAddress() net.HardwareAddr\n\n\t\/\/ Address returns the IPv4 address assigned to the endpoint.\n\tAddress() net.IPNet\n\n\t\/\/ AddressIPv6 returns the IPv6 address assigned to the endpoint.\n\tAddressIPv6() net.IPNet\n}\n\n\/\/ ContainerInfo provides an interface to retrieve the info about the container attached to the endpoint\ntype ContainerInfo interface {\n\t\/\/ ID returns the ID of the container\n\tID() string\n\t\/\/ Labels returns the container's labels\n\tLabels() map[string]interface{}\n}\n\ntype endpointInterface struct {\n\tid        int\n\tmac       net.HardwareAddr\n\taddr      net.IPNet\n\taddrv6    net.IPNet\n\tsrcName   string\n\tdstPrefix string\n\troutes    []*net.IPNet\n}\n\nfunc (epi *endpointInterface) MarshalJSON() ([]byte, error) {\n\tepMap := make(map[string]interface{})\n\tepMap[\"id\"] = epi.id\n\tepMap[\"mac\"] = epi.mac.String()\n\tepMap[\"addr\"] = epi.addr.String()\n\tepMap[\"addrv6\"] = epi.addrv6.String()\n\tepMap[\"srcName\"] = epi.srcName\n\tepMap[\"dstPrefix\"] = epi.dstPrefix\n\tvar routes []string\n\tfor _, route := range epi.routes {\n\t\troutes = append(routes, route.String())\n\t}\n\tepMap[\"routes\"] = routes\n\treturn json.Marshal(epMap)\n}\n\nfunc (epi *endpointInterface) UnmarshalJSON(b []byte) (err error) {\n\tvar epMap map[string]interface{}\n\tif err := json.Unmarshal(b, &epMap); err != nil {\n\t\treturn err\n\t}\n\tepi.id = int(epMap[\"id\"].(float64))\n\n\tmac, _ := net.ParseMAC(epMap[\"mac\"].(string))\n\tepi.mac = mac\n\n\tip, ipnet, _ := net.ParseCIDR(epMap[\"addr\"].(string))\n\tif ipnet != nil {\n\t\tipnet.IP = ip\n\t\tepi.addr = *ipnet\n\t}\n\n\tip, ipnet, _ = net.ParseCIDR(epMap[\"addrv6\"].(string))\n\tif ipnet != nil {\n\t\tipnet.IP = ip\n\t\tepi.addrv6 = *ipnet\n\t}\n\n\tepi.srcName = epMap[\"srcName\"].(string)\n\tepi.dstPrefix = epMap[\"dstPrefix\"].(string)\n\n\trb, _ := json.Marshal(epMap[\"routes\"])\n\tvar routes []string\n\tjson.Unmarshal(rb, &routes)\n\tepi.routes = make([]*net.IPNet, 0)\n\tfor _, route := range routes {\n\t\tip, ipr, err := net.ParseCIDR(route)\n\t\tif err == nil {\n\t\t\tipr.IP = ip\n\t\t\tepi.routes = append(epi.routes, ipr)\n\t\t}\n\t}\n\n\treturn nil\n}\n\ntype endpointJoinInfo struct {\n\tgw             net.IP\n\tgw6            net.IP\n\thostsPath      string\n\tresolvConfPath string\n\tStaticRoutes   []*types.StaticRoute\n}\n\nfunc (ep *endpoint) ContainerInfo() ContainerInfo {\n\tep.Lock()\n\tci := ep.container\n\tdefer ep.Unlock()\n\n\t\/\/ Need this since we return the interface\n\tif ci == nil {\n\t\treturn nil\n\t}\n\treturn ci\n}\n\nfunc (ep *endpoint) Info() EndpointInfo {\n\treturn ep\n}\n\nfunc (ep *endpoint) DriverInfo() (map[string]interface{}, error) {\n\tep.Lock()\n\tnetwork := ep.network\n\tepid := ep.id\n\tep.Unlock()\n\n\tnetwork.Lock()\n\tdriver := network.driver\n\tnid := network.id\n\tnetwork.Unlock()\n\n\treturn driver.EndpointOperInfo(nid, epid)\n}\n\nfunc (ep *endpoint) InterfaceList() []InterfaceInfo {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tiList := make([]InterfaceInfo, len(ep.iFaces))\n\n\tfor i, iface := range ep.iFaces {\n\t\tiList[i] = iface\n\t}\n\n\treturn iList\n}\n\nfunc (ep *endpoint) Interfaces() []driverapi.InterfaceInfo {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tiList := make([]driverapi.InterfaceInfo, len(ep.iFaces))\n\n\tfor i, iface := range ep.iFaces {\n\t\tiList[i] = iface\n\t}\n\n\treturn iList\n}\n\nfunc (ep *endpoint) AddInterface(id int, mac net.HardwareAddr, ipv4 net.IPNet, ipv6 net.IPNet) error {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tiface := &endpointInterface{\n\t\tid:     id,\n\t\taddr:   *types.GetIPNetCopy(&ipv4),\n\t\taddrv6: *types.GetIPNetCopy(&ipv6),\n\t}\n\tiface.mac = types.GetMacCopy(mac)\n\n\tep.iFaces = append(ep.iFaces, iface)\n\treturn nil\n}\n\nfunc (epi *endpointInterface) ID() int {\n\treturn epi.id\n}\n\nfunc (epi *endpointInterface) MacAddress() net.HardwareAddr {\n\treturn types.GetMacCopy(epi.mac)\n}\n\nfunc (epi *endpointInterface) Address() net.IPNet {\n\treturn (*types.GetIPNetCopy(&epi.addr))\n}\n\nfunc (epi *endpointInterface) AddressIPv6() net.IPNet {\n\treturn (*types.GetIPNetCopy(&epi.addrv6))\n}\n\nfunc (epi *endpointInterface) SetNames(srcName string, dstPrefix string) error {\n\tepi.srcName = srcName\n\tepi.dstPrefix = dstPrefix\n\treturn nil\n}\n\nfunc (ep *endpoint) InterfaceNames() []driverapi.InterfaceNameInfo {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tiList := make([]driverapi.InterfaceNameInfo, len(ep.iFaces))\n\n\tfor i, iface := range ep.iFaces {\n\t\tiList[i] = iface\n\t}\n\n\treturn iList\n}\n\nfunc (ep *endpoint) AddStaticRoute(destination *net.IPNet, routeType int, nextHop net.IP, interfaceID int) error {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tr := types.StaticRoute{Destination: destination, RouteType: routeType, NextHop: nextHop, InterfaceID: interfaceID}\n\n\tif routeType == types.NEXTHOP {\n\t\t\/\/ If the route specifies a next-hop, then it's loosely routed (i.e. not bound to a particular interface).\n\t\tep.joinInfo.StaticRoutes = append(ep.joinInfo.StaticRoutes, &r)\n\t} else {\n\t\t\/\/ If the route doesn't specify a next-hop, it must be a connected route, bound to an interface.\n\t\tif err := ep.addInterfaceRoute(&r); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (ep *endpoint) addInterfaceRoute(route *types.StaticRoute) error {\n\tfor _, iface := range ep.iFaces {\n\t\tif iface.id == route.InterfaceID {\n\t\t\tiface.routes = append(iface.routes, route.Destination)\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn types.BadRequestErrorf(\"Interface with ID %d doesn't exist.\",\n\t\troute.InterfaceID)\n}\n\nfunc (ep *endpoint) SandboxKey() string {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tif ep.container == nil {\n\t\treturn \"\"\n\t}\n\n\treturn ep.container.data.SandboxKey\n}\n\nfunc (ep *endpoint) Gateway() net.IP {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tif ep.joinInfo == nil {\n\t\treturn net.IP{}\n\t}\n\n\treturn types.GetIPCopy(ep.joinInfo.gw)\n}\n\nfunc (ep *endpoint) GatewayIPv6() net.IP {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tif ep.joinInfo == nil {\n\t\treturn net.IP{}\n\t}\n\n\treturn types.GetIPCopy(ep.joinInfo.gw6)\n}\n\nfunc (ep *endpoint) SetGateway(gw net.IP) error {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tep.joinInfo.gw = types.GetIPCopy(gw)\n\treturn nil\n}\n\nfunc (ep *endpoint) SetGatewayIPv6(gw6 net.IP) error {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tep.joinInfo.gw6 = types.GetIPCopy(gw6)\n\treturn nil\n}\n\nfunc (ep *endpoint) SetHostsPath(path string) error {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tep.joinInfo.hostsPath = path\n\treturn nil\n}\n\nfunc (ep *endpoint) SetResolvConfPath(path string) error {\n\tep.Lock()\n\tdefer ep.Unlock()\n\n\tep.joinInfo.resolvConfPath = path\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"testing\"\n\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/helper\/acctest\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/terraform\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/docdb\"\n)\n\nfunc TestAccAWSDocDBSubnetGroup_basic(t *testing.T) {\n\tvar v docdb.DBSubnetGroup\n\n\trName := fmt.Sprintf(\"tf-test-%d\", acctest.RandInt())\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckDocDBSubnetGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccDocDBSubnetGroupConfig(rName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDocDBSubnetGroupExists(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", &v),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", \"name\", rName),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", \"description\", \"Managed by Terraform\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName:      \"aws_docdb_subnet_group.foo\",\n\t\t\t\tImportState:       true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSDocDBSubnetGroup_disappears(t *testing.T) {\n\tvar v docdb.DBSubnetGroup\n\n\trName := fmt.Sprintf(\"tf-test-%d\", acctest.RandInt())\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckDocDBSubnetGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccDocDBSubnetGroupConfig(rName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDocDBSubnetGroupExists(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", &v),\n\t\t\t\t\ttestAccCheckAWSDocDBSubnetGroupDisappears(&v),\n\t\t\t\t),\n\t\t\t\tExpectNonEmptyPlan: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSDocDBSubnetGroup_namePrefix(t *testing.T) {\n\tvar v docdb.DBSubnetGroup\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckDocDBSubnetGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccDocDBSubnetGroupConfig_namePrefix,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDocDBSubnetGroupExists(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.test\", &v),\n\t\t\t\t\tresource.TestMatchResourceAttr(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.test\", \"name\", regexp.MustCompile(\"^tf_test-\")),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName:            \"aws_docdb_subnet_group.test\",\n\t\t\t\tImportState:             true,\n\t\t\t\tImportStateVerify:       true,\n\t\t\t\tImportStateVerifyIgnore: []string{\"name_prefix\"},\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSDocDBSubnetGroup_generatedName(t *testing.T) {\n\tvar v docdb.DBSubnetGroup\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckDocDBSubnetGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccDocDBSubnetGroupConfig_generatedName,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDocDBSubnetGroupExists(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.test\", &v),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName:      \"aws_docdb_subnet_group.test\",\n\t\t\t\tImportState:       true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSDocDBSubnetGroup_updateDescription(t *testing.T) {\n\tvar v docdb.DBSubnetGroup\n\n\trName := fmt.Sprintf(\"tf-test-%d\", acctest.RandInt())\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckDocDBSubnetGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccDocDBSubnetGroupConfig(rName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDocDBSubnetGroupExists(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", &v),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", \"description\", \"Managed by Terraform\"),\n\t\t\t\t),\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tConfig: testAccDocDBSubnetGroupConfig_updatedDescription(rName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDocDBSubnetGroupExists(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", &v),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", \"description\", \"foo description updated\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName:      \"aws_docdb_subnet_group.foo\",\n\t\t\t\tImportState:       true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckDocDBSubnetGroupDestroy(s *terraform.State) error {\n\tconn := testAccProvider.Meta().(*AWSClient).docdbconn\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_docdb_subnet_group\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Try to find the resource\n\t\tresp, err := conn.DescribeDBSubnetGroups(\n\t\t\t&docdb.DescribeDBSubnetGroupsInput{DBSubnetGroupName: aws.String(rs.Primary.ID)})\n\n\t\tif err == nil {\n\t\t\tif len(resp.DBSubnetGroups) != 0 &&\n\t\t\t\taws.StringValue(resp.DBSubnetGroups[0].DBSubnetGroupName) == rs.Primary.ID {\n\t\t\t\treturn fmt.Errorf(\"DocDB Subnet Group %s still exists\", rs.Primary.ID)\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\tif isAWSErr(err, docdb.ErrCodeDBSubnetGroupNotFoundFault, \"\") {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc testAccCheckAWSDocDBSubnetGroupDisappears(group *docdb.DBSubnetGroup) resource.TestCheckFunc {\n\n\treturn func(s *terraform.State) error {\n\t\tconn := testAccProvider.Meta().(*AWSClient).docdbconn\n\n\t\tparams := &docdb.DeleteDBSubnetGroupInput{\n\t\t\tDBSubnetGroupName: group.DBSubnetGroupName,\n\t\t}\n\n\t\t_, err := conn.DeleteDBSubnetGroup(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn waitForDocDBSubnetGroupDeletion(conn, *group.DBSubnetGroupName)\n\t}\n}\n\nfunc testAccCheckDocDBSubnetGroupExists(n string, v *docdb.DBSubnetGroup) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No ID is set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).docdbconn\n\t\tresp, err := conn.DescribeDBSubnetGroups(\n\t\t\t&docdb.DescribeDBSubnetGroupsInput{DBSubnetGroupName: aws.String(rs.Primary.ID)})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(resp.DBSubnetGroups) == 0 {\n\t\t\treturn fmt.Errorf(\"DbSubnetGroup not found\")\n\t\t}\n\n\t\t*v = *resp.DBSubnetGroups[0]\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccDocDBSubnetGroupConfig(rName string) string {\n\treturn fmt.Sprintf(`\nresource \"aws_vpc\" \"foo\" {\n  cidr_block = \"10.1.0.0\/16\"\n\n  tags = {\n    Name = \"terraform-testacc-docdb-subnet-group\"\n  }\n}\n\nresource \"aws_subnet\" \"foo\" {\n  cidr_block        = \"10.1.1.0\/24\"\n  availability_zone = \"us-west-2a\"\n  vpc_id            = aws_vpc.foo.id\n\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-1\"\n  }\n}\n\nresource \"aws_subnet\" \"bar\" {\n  cidr_block        = \"10.1.2.0\/24\"\n  availability_zone = \"us-west-2b\"\n  vpc_id            = aws_vpc.foo.id\n\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-2\"\n  }\n}\n\nresource \"aws_docdb_subnet_group\" \"foo\" {\n  name       = \"%s\"\n  subnet_ids = [aws_subnet.foo.id, aws_subnet.bar.id]\n\n  tags = {\n    Name = \"tf-docdb-subnet-group-test\"\n  }\n}\n`, rName)\n}\n\nfunc testAccDocDBSubnetGroupConfig_updatedDescription(rName string) string {\n\treturn fmt.Sprintf(`\nresource \"aws_vpc\" \"foo\" {\n  cidr_block = \"10.1.0.0\/16\"\n\n  tags = {\n    Name = \"terraform-testacc-docdb-subnet-group\"\n  }\n}\n\nresource \"aws_subnet\" \"foo\" {\n  cidr_block        = \"10.1.1.0\/24\"\n  availability_zone = \"us-west-2a\"\n  vpc_id            = aws_vpc.foo.id\n\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-1\"\n  }\n}\n\nresource \"aws_subnet\" \"bar\" {\n  cidr_block        = \"10.1.2.0\/24\"\n  availability_zone = \"us-west-2b\"\n  vpc_id            = aws_vpc.foo.id\n\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-2\"\n  }\n}\n\nresource \"aws_docdb_subnet_group\" \"foo\" {\n  name        = \"%s\"\n  description = \"foo description updated\"\n  subnet_ids  = [aws_subnet.foo.id, aws_subnet.bar.id]\n\n  tags = {\n    Name = \"tf-docdb-subnet-group-test\"\n  }\n}\n`, rName)\n}\n\nconst testAccDocDBSubnetGroupConfig_namePrefix = `\nresource \"aws_vpc\" \"test\" {\n  cidr_block = \"10.1.0.0\/16\"\n  tags = {\n    Name = \"terraform-testacc-docdb-subnet-group-name-prefix\"\n  }\n}\n\nresource \"aws_subnet\" \"a\" {\n  vpc_id            = aws_vpc.test.id\n  cidr_block        = \"10.1.1.0\/24\"\n  availability_zone = \"us-west-2a\"\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-name-prefix-a\"\n  }\n}\n\nresource \"aws_subnet\" \"b\" {\n  vpc_id            = aws_vpc.test.id\n  cidr_block        = \"10.1.2.0\/24\"\n  availability_zone = \"us-west-2b\"\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-name-prefix-b\"\n  }\n}\n\nresource \"aws_docdb_subnet_group\" \"test\" {\n  name_prefix = \"tf_test-\"\n  subnet_ids  = [aws_subnet.a.id, aws_subnet.b.id]\n}`\n\nconst testAccDocDBSubnetGroupConfig_generatedName = `\nresource \"aws_vpc\" \"test\" {\n  cidr_block = \"10.1.0.0\/16\"\n  tags = {\n    Name = \"terraform-testacc-docdb-subnet-group-generated-name\"\n  }\n}\n\nresource \"aws_subnet\" \"a\" {\n  vpc_id            = aws_vpc.test.id\n  cidr_block        = \"10.1.1.0\/24\"\n  availability_zone = \"us-west-2a\"\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-generated-name-a\"\n  }\n}\n\nresource \"aws_subnet\" \"b\" {\n  vpc_id            = aws_vpc.test.id\n  cidr_block        = \"10.1.2.0\/24\"\n  availability_zone = \"us-west-2b\"\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-generated-name-a\"\n  }\n}\n\nresource \"aws_docdb_subnet_group\" \"test\" {\n  subnet_ids = [aws_subnet.a.id, aws_subnet.b.id]\n}`\n<commit_msg>tests\/provider: Fix hardcoded AZs (docdb subnet)<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"testing\"\n\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/helper\/acctest\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform-plugin-sdk\/v2\/terraform\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/docdb\"\n)\n\nfunc TestAccAWSDocDBSubnetGroup_basic(t *testing.T) {\n\tvar v docdb.DBSubnetGroup\n\n\trName := fmt.Sprintf(\"tf-test-%d\", acctest.RandInt())\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckDocDBSubnetGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccDocDBSubnetGroupConfig(rName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDocDBSubnetGroupExists(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", &v),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", \"name\", rName),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", \"description\", \"Managed by Terraform\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName:      \"aws_docdb_subnet_group.foo\",\n\t\t\t\tImportState:       true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSDocDBSubnetGroup_disappears(t *testing.T) {\n\tvar v docdb.DBSubnetGroup\n\n\trName := fmt.Sprintf(\"tf-test-%d\", acctest.RandInt())\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckDocDBSubnetGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccDocDBSubnetGroupConfig(rName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDocDBSubnetGroupExists(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", &v),\n\t\t\t\t\ttestAccCheckAWSDocDBSubnetGroupDisappears(&v),\n\t\t\t\t),\n\t\t\t\tExpectNonEmptyPlan: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSDocDBSubnetGroup_namePrefix(t *testing.T) {\n\tvar v docdb.DBSubnetGroup\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckDocDBSubnetGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccDocDBSubnetGroupConfig_namePrefix(),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDocDBSubnetGroupExists(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.test\", &v),\n\t\t\t\t\tresource.TestMatchResourceAttr(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.test\", \"name\", regexp.MustCompile(\"^tf_test-\")),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName:            \"aws_docdb_subnet_group.test\",\n\t\t\t\tImportState:             true,\n\t\t\t\tImportStateVerify:       true,\n\t\t\t\tImportStateVerifyIgnore: []string{\"name_prefix\"},\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSDocDBSubnetGroup_generatedName(t *testing.T) {\n\tvar v docdb.DBSubnetGroup\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckDocDBSubnetGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccDocDBSubnetGroupConfig_generatedName(),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDocDBSubnetGroupExists(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.test\", &v),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName:      \"aws_docdb_subnet_group.test\",\n\t\t\t\tImportState:       true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSDocDBSubnetGroup_updateDescription(t *testing.T) {\n\tvar v docdb.DBSubnetGroup\n\n\trName := fmt.Sprintf(\"tf-test-%d\", acctest.RandInt())\n\n\tresource.ParallelTest(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckDocDBSubnetGroupDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccDocDBSubnetGroupConfig(rName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDocDBSubnetGroupExists(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", &v),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", \"description\", \"Managed by Terraform\"),\n\t\t\t\t),\n\t\t\t},\n\n\t\t\t{\n\t\t\t\tConfig: testAccDocDBSubnetGroupConfig_updatedDescription(rName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckDocDBSubnetGroupExists(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", &v),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_docdb_subnet_group.foo\", \"description\", \"foo description updated\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tResourceName:      \"aws_docdb_subnet_group.foo\",\n\t\t\t\tImportState:       true,\n\t\t\t\tImportStateVerify: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckDocDBSubnetGroupDestroy(s *terraform.State) error {\n\tconn := testAccProvider.Meta().(*AWSClient).docdbconn\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_docdb_subnet_group\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Try to find the resource\n\t\tresp, err := conn.DescribeDBSubnetGroups(\n\t\t\t&docdb.DescribeDBSubnetGroupsInput{DBSubnetGroupName: aws.String(rs.Primary.ID)})\n\n\t\tif err == nil {\n\t\t\tif len(resp.DBSubnetGroups) != 0 &&\n\t\t\t\taws.StringValue(resp.DBSubnetGroups[0].DBSubnetGroupName) == rs.Primary.ID {\n\t\t\t\treturn fmt.Errorf(\"DocDB Subnet Group %s still exists\", rs.Primary.ID)\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\tif isAWSErr(err, docdb.ErrCodeDBSubnetGroupNotFoundFault, \"\") {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc testAccCheckAWSDocDBSubnetGroupDisappears(group *docdb.DBSubnetGroup) resource.TestCheckFunc {\n\n\treturn func(s *terraform.State) error {\n\t\tconn := testAccProvider.Meta().(*AWSClient).docdbconn\n\n\t\tparams := &docdb.DeleteDBSubnetGroupInput{\n\t\t\tDBSubnetGroupName: group.DBSubnetGroupName,\n\t\t}\n\n\t\t_, err := conn.DeleteDBSubnetGroup(params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn waitForDocDBSubnetGroupDeletion(conn, *group.DBSubnetGroupName)\n\t}\n}\n\nfunc testAccCheckDocDBSubnetGroupExists(n string, v *docdb.DBSubnetGroup) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No ID is set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).docdbconn\n\t\tresp, err := conn.DescribeDBSubnetGroups(\n\t\t\t&docdb.DescribeDBSubnetGroupsInput{DBSubnetGroupName: aws.String(rs.Primary.ID)})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(resp.DBSubnetGroups) == 0 {\n\t\t\treturn fmt.Errorf(\"DbSubnetGroup not found\")\n\t\t}\n\n\t\t*v = *resp.DBSubnetGroups[0]\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccDocDBSubnetGroupConfig(rName string) string {\n\treturn composeConfig(testAccAvailableAZsNoOptInConfig(), fmt.Sprintf(`\nresource \"aws_vpc\" \"foo\" {\n  cidr_block = \"10.1.0.0\/16\"\n\n  tags = {\n    Name = \"terraform-testacc-docdb-subnet-group\"\n  }\n}\n\nresource \"aws_subnet\" \"foo\" {\n  cidr_block        = \"10.1.1.0\/24\"\n  availability_zone = data.aws_availability_zones.available.names[0]\n  vpc_id            = aws_vpc.foo.id\n\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-1\"\n  }\n}\n\nresource \"aws_subnet\" \"bar\" {\n  cidr_block        = \"10.1.2.0\/24\"\n  availability_zone = data.aws_availability_zones.available.names[1]\n  vpc_id            = aws_vpc.foo.id\n\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-2\"\n  }\n}\n\nresource \"aws_docdb_subnet_group\" \"foo\" {\n  name       = \"%s\"\n  subnet_ids = [aws_subnet.foo.id, aws_subnet.bar.id]\n\n  tags = {\n    Name = \"tf-docdb-subnet-group-test\"\n  }\n}\n`, rName))\n}\n\nfunc testAccDocDBSubnetGroupConfig_updatedDescription(rName string) string {\n\treturn composeConfig(testAccAvailableAZsNoOptInConfig(), fmt.Sprintf(`\nresource \"aws_vpc\" \"foo\" {\n  cidr_block = \"10.1.0.0\/16\"\n\n  tags = {\n    Name = \"terraform-testacc-docdb-subnet-group\"\n  }\n}\n\nresource \"aws_subnet\" \"foo\" {\n  cidr_block        = \"10.1.1.0\/24\"\n  availability_zone = data.aws_availability_zones.available.names[0]\n  vpc_id            = aws_vpc.foo.id\n\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-1\"\n  }\n}\n\nresource \"aws_subnet\" \"bar\" {\n  cidr_block        = \"10.1.2.0\/24\"\n  availability_zone = data.aws_availability_zones.available.names[1]\n  vpc_id            = aws_vpc.foo.id\n\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-2\"\n  }\n}\n\nresource \"aws_docdb_subnet_group\" \"foo\" {\n  name        = \"%s\"\n  description = \"foo description updated\"\n  subnet_ids  = [aws_subnet.foo.id, aws_subnet.bar.id]\n\n  tags = {\n    Name = \"tf-docdb-subnet-group-test\"\n  }\n}\n`, rName))\n}\n\nfunc testAccDocDBSubnetGroupConfig_namePrefix() string {\n\treturn composeConfig(testAccAvailableAZsNoOptInConfig(), fmt.Sprintf(`\nresource \"aws_vpc\" \"test\" {\n  cidr_block = \"10.1.0.0\/16\"\n\n  tags = {\n    Name = \"terraform-testacc-docdb-subnet-group-name-prefix\"\n  }\n}\n\nresource \"aws_subnet\" \"a\" {\n  vpc_id            = aws_vpc.test.id\n  cidr_block        = \"10.1.1.0\/24\"\n  availability_zone = data.aws_availability_zones.available.names[0]\n\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-name-prefix-a\"\n  }\n}\n\nresource \"aws_subnet\" \"b\" {\n  vpc_id            = aws_vpc.test.id\n  cidr_block        = \"10.1.2.0\/24\"\n  availability_zone = data.aws_availability_zones.available.names[1]\n\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-name-prefix-b\"\n  }\n}\n\nresource \"aws_docdb_subnet_group\" \"test\" {\n  name_prefix = \"tf_test-\"\n  subnet_ids  = [aws_subnet.a.id, aws_subnet.b.id]\n}`))\n}\n\nfunc testAccDocDBSubnetGroupConfig_generatedName() string {\n\treturn composeConfig(testAccAvailableAZsNoOptInConfig(), fmt.Sprintf(`\nresource \"aws_vpc\" \"test\" {\n  cidr_block = \"10.1.0.0\/16\"\n\n  tags = {\n    Name = \"terraform-testacc-docdb-subnet-group-generated-name\"\n  }\n}\n\nresource \"aws_subnet\" \"a\" {\n  vpc_id            = aws_vpc.test.id\n  cidr_block        = \"10.1.1.0\/24\"\n  availability_zone = data.aws_availability_zones.available.names[0]\n\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-generated-name-a\"\n  }\n}\n\nresource \"aws_subnet\" \"b\" {\n  vpc_id            = aws_vpc.test.id\n  cidr_block        = \"10.1.2.0\/24\"\n  availability_zone = data.aws_availability_zones.available.names[1]\n\n  tags = {\n    Name = \"tf-acc-docdb-subnet-group-generated-name-a\"\n  }\n}\n\nresource \"aws_docdb_subnet_group\" \"test\" {\n  subnet_ids = [aws_subnet.a.id, aws_subnet.b.id]\n}`))\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ssm\"\n\t\"github.com\/hashicorp\/terraform\/helper\/acctest\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nfunc TestAccAWSSSMPatchBaseline_basic(t *testing.T) {\n\tvar before, after ssm.PatchBaselineIdentity\n\tname := acctest.RandString(10)\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSSSMPatchBaselineDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSSSMPatchBaselineBasicConfig(name),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSSSMPatchBaselineExists(\"aws_ssm_patch_baseline.foo\", &before),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches.#\", \"1\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches.2062620480\", \"KB123456\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"name\", fmt.Sprintf(\"patch-baseline-%s\", name)),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches_compliance_level\", ssm.PatchComplianceLevelCritical),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"description\", \"Baseline containing all updates approved for production systems\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tConfig: testAccAWSSSMPatchBaselineBasicConfigUpdated(name),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSSSMPatchBaselineExists(\"aws_ssm_patch_baseline.foo\", &after),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches.#\", \"2\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches.2062620480\", \"KB123456\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches.2291496788\", \"KB456789\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"name\", fmt.Sprintf(\"updated-patch-baseline-%s\", name)),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches_compliance_level\", ssm.PatchComplianceLevelHigh),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"description\", \"Baseline containing all updates approved for production systems - August 2017\"),\n\t\t\t\t\tfunc(*terraform.State) error {\n\t\t\t\t\t\tif *before.BaselineId != *after.BaselineId {\n\t\t\t\t\t\t\tt.Fatal(\"Baseline IDs changed unexpectedly\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSSSMPatchBaselineWithOperatingSystem(t *testing.T) {\n\tvar before, after ssm.PatchBaselineIdentity\n\tname := acctest.RandString(10)\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSSSMPatchBaselineDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSSSMPatchBaselineConfigWithOperatingSystem(name),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSSSMPatchBaselineExists(\"aws_ssm_patch_baseline.foo\", &before),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.#\", \"1\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.approve_after_days\", \"7\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.patch_filter.#\", \"2\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.compliance_level\", ssm.PatchComplianceLevelCritical),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.enable_non_security\", \"true\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"operating_system\", \"AMAZON_LINUX\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tConfig: testAccAWSSSMPatchBaselineConfigWithOperatingSystemUpdated(name),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSSSMPatchBaselineExists(\"aws_ssm_patch_baseline.foo\", &after),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.#\", \"1\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.approve_after_days\", \"7\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.patch_filter.#\", \"2\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.compliance_level\", ssm.PatchComplianceLevelInformational),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"operating_system\", ssm.OperatingSystemWindows),\n\t\t\t\t\ttestAccCheckAwsSsmPatchBaselineRecreated(t, &before, &after),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckAwsSsmPatchBaselineRecreated(t *testing.T,\n\tbefore, after *ssm.PatchBaselineIdentity) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tif *before.BaselineId == *after.BaselineId {\n\t\t\tt.Fatalf(\"Expected change of SSM Patch Baseline IDs, but both were %v\", *before.BaselineId)\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckAWSSSMPatchBaselineExists(n string, patch *ssm.PatchBaselineIdentity) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No SSM Patch Baseline ID is set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).ssmconn\n\n\t\tresp, err := conn.DescribePatchBaselines(&ssm.DescribePatchBaselinesInput{\n\t\t\tFilters: []*ssm.PatchOrchestratorFilter{\n\t\t\t\t{\n\t\t\t\t\tKey:    aws.String(\"NAME_PREFIX\"),\n\t\t\t\t\tValues: []*string{aws.String(rs.Primary.Attributes[\"name\"])},\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\n\t\tfor _, i := range resp.BaselineIdentities {\n\t\t\tif *i.BaselineId == rs.Primary.ID {\n\t\t\t\t*patch = *i\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn fmt.Errorf(\"No AWS SSM Patch Baseline found\")\n\t}\n}\n\nfunc testAccCheckAWSSSMPatchBaselineDestroy(s *terraform.State) error {\n\tconn := testAccProvider.Meta().(*AWSClient).ssmconn\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_ssm_patch_baseline\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tout, err := conn.DescribePatchBaselines(&ssm.DescribePatchBaselinesInput{\n\t\t\tFilters: []*ssm.PatchOrchestratorFilter{\n\t\t\t\t{\n\t\t\t\t\tKey:    aws.String(\"NAME_PREFIX\"),\n\t\t\t\t\tValues: []*string{aws.String(rs.Primary.Attributes[\"name\"])},\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(out.BaselineIdentities) > 0 {\n\t\t\treturn fmt.Errorf(\"Expected AWS SSM Patch Baseline to be gone, but was still found\")\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn nil\n}\n\nfunc testAccAWSSSMPatchBaselineBasicConfig(rName string) string {\n\treturn fmt.Sprintf(`\n\nresource \"aws_ssm_patch_baseline\" \"foo\" {\n  name  = \"patch-baseline-%s\"\n  description = \"Baseline containing all updates approved for production systems\"\n  approved_patches = [\"KB123456\"]\n  approved_patches_compliance_level = \"CRITICAL\"\n}\n\n`, rName)\n}\n\nfunc testAccAWSSSMPatchBaselineBasicConfigUpdated(rName string) string {\n\treturn fmt.Sprintf(`\n\nresource \"aws_ssm_patch_baseline\" \"foo\" {\n  name  = \"updated-patch-baseline-%s\"\n  description = \"Baseline containing all updates approved for production systems - August 2017\"\n  approved_patches = [\"KB123456\",\"KB456789\"]\n  approved_patches_compliance_level = \"HIGH\"\n}\n\n`, rName)\n}\n\nfunc testAccAWSSSMPatchBaselineConfigWithOperatingSystem(rName string) string {\n\treturn fmt.Sprintf(`\n\nresource \"aws_ssm_patch_baseline\" \"foo\" {\n  name  = \"patch-baseline-%s\"\n  operating_system = \"AMAZON_LINUX\"\n  description = \"Baseline containing all updates approved for production systems\"\n  approval_rule {\n  \tapprove_after_days = 7\n\tenable_non_security = true\n  \tcompliance_level = \"CRITICAL\"\n\n  \tpatch_filter {\n\t\tkey = \"PRODUCT\"\n\t\tvalues = [\"AmazonLinux2016.03\",\"AmazonLinux2016.09\",\"AmazonLinux2017.03\",\"AmazonLinux2017.09\"]\n  \t}\n\n  \tpatch_filter {\n\t\tkey = \"SEVERITY\"\n\t\tvalues = [\"Critical\",\"Important\"]\n  \t}\n  }\n}\n\n`, rName)\n}\n\nfunc testAccAWSSSMPatchBaselineConfigWithOperatingSystemUpdated(rName string) string {\n\treturn fmt.Sprintf(`\n\nresource \"aws_ssm_patch_baseline\" \"foo\" {\n  name  = \"patch-baseline-%s\"\n  operating_system = \"WINDOWS\"\n  description = \"Baseline containing all updates approved for production systems\"\n  approval_rule {\n  \tapprove_after_days = 7\n  \tcompliance_level = \"INFORMATIONAL\"\n\n  \tpatch_filter {\n\t\tkey = \"PRODUCT\"\n\t\tvalues = [\"WindowsServer2012R2\"]\n  \t}\n\n  \tpatch_filter {\n\t\tkey = \"MSRC_SEVERITY\"\n\t\tvalues = [\"Critical\",\"Important\"]\n  \t}\n  }\n}\n\n`, rName)\n}\n<commit_msg>add acceptance test<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/ssm\"\n\t\"github.com\/hashicorp\/terraform\/helper\/acctest\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nfunc TestAccAWSSSMPatchBaseline_basic(t *testing.T) {\n\tvar before, after ssm.PatchBaselineIdentity\n\tname := acctest.RandString(10)\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSSSMPatchBaselineDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSSSMPatchBaselineBasicConfig(name),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSSSMPatchBaselineExists(\"aws_ssm_patch_baseline.foo\", &before),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches.#\", \"1\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches.2062620480\", \"KB123456\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"name\", fmt.Sprintf(\"patch-baseline-%s\", name)),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches_compliance_level\", ssm.PatchComplianceLevelCritical),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"description\", \"Baseline containing all updates approved for production systems\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tConfig: testAccAWSSSMPatchBaselineBasicConfigUpdated(name),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSSSMPatchBaselineExists(\"aws_ssm_patch_baseline.foo\", &after),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches.#\", \"2\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches.2062620480\", \"KB123456\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches.2291496788\", \"KB456789\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"name\", fmt.Sprintf(\"updated-patch-baseline-%s\", name)),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approved_patches_compliance_level\", ssm.PatchComplianceLevelHigh),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"description\", \"Baseline containing all updates approved for production systems - August 2017\"),\n\t\t\t\t\tfunc(*terraform.State) error {\n\t\t\t\t\t\tif *before.BaselineId != *after.BaselineId {\n\t\t\t\t\t\t\tt.Fatal(\"Baseline IDs changed unexpectedly\")\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSSSMPatchBaseline_disappears(t *testing.T) {\n\tvar identity ssm.PatchBaselineIdentity\n\tname := acctest.RandString(10)\n\tresourceName := \"aws_ssm_patch_baseline.foo\"\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSSSMPatchBaselineDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSSSMPatchBaselineBasicConfig(name),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSSSMPatchBaselineExists(resourceName, &identity),\n\t\t\t\t\ttestAccCheckAWSSSMPatchBaselineDisappears(&identity),\n\t\t\t\t),\n\t\t\t\tExpectNonEmptyPlan: true,\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccAWSSSMPatchBaselineWithOperatingSystem(t *testing.T) {\n\tvar before, after ssm.PatchBaselineIdentity\n\tname := acctest.RandString(10)\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckAWSSSMPatchBaselineDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\t{\n\t\t\t\tConfig: testAccAWSSSMPatchBaselineConfigWithOperatingSystem(name),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSSSMPatchBaselineExists(\"aws_ssm_patch_baseline.foo\", &before),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.#\", \"1\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.approve_after_days\", \"7\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.patch_filter.#\", \"2\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.compliance_level\", ssm.PatchComplianceLevelCritical),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.enable_non_security\", \"true\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"operating_system\", \"AMAZON_LINUX\"),\n\t\t\t\t),\n\t\t\t},\n\t\t\t{\n\t\t\t\tConfig: testAccAWSSSMPatchBaselineConfigWithOperatingSystemUpdated(name),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckAWSSSMPatchBaselineExists(\"aws_ssm_patch_baseline.foo\", &after),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.#\", \"1\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.approve_after_days\", \"7\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.patch_filter.#\", \"2\"),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"approval_rule.0.compliance_level\", ssm.PatchComplianceLevelInformational),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_ssm_patch_baseline.foo\", \"operating_system\", ssm.OperatingSystemWindows),\n\t\t\t\t\ttestAccCheckAwsSsmPatchBaselineRecreated(t, &before, &after),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckAwsSsmPatchBaselineRecreated(t *testing.T,\n\tbefore, after *ssm.PatchBaselineIdentity) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tif *before.BaselineId == *after.BaselineId {\n\t\t\tt.Fatalf(\"Expected change of SSM Patch Baseline IDs, but both were %v\", *before.BaselineId)\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckAWSSSMPatchBaselineExists(n string, patch *ssm.PatchBaselineIdentity) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No SSM Patch Baseline ID is set\")\n\t\t}\n\n\t\tconn := testAccProvider.Meta().(*AWSClient).ssmconn\n\n\t\tresp, err := conn.DescribePatchBaselines(&ssm.DescribePatchBaselinesInput{\n\t\t\tFilters: []*ssm.PatchOrchestratorFilter{\n\t\t\t\t{\n\t\t\t\t\tKey:    aws.String(\"NAME_PREFIX\"),\n\t\t\t\t\tValues: []*string{aws.String(rs.Primary.Attributes[\"name\"])},\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\n\t\tfor _, i := range resp.BaselineIdentities {\n\t\t\tif *i.BaselineId == rs.Primary.ID {\n\t\t\t\t*patch = *i\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn fmt.Errorf(\"No AWS SSM Patch Baseline found\")\n\t}\n}\n\nfunc testAccCheckAWSSSMPatchBaselineDisappears(patch *ssm.PatchBaselineIdentity) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tconn := testAccProvider.Meta().(*AWSClient).ssmconn\n\n\t\tid := aws.StringValue(patch.BaselineId)\n\t\tparams := &ssm.DeletePatchBaselineInput{\n\t\t\tBaselineId: aws.String(id),\n\t\t}\n\n\t\t_, err := conn.DeletePatchBaseline(params)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error deleting Patch Baseline %s: %s\", id, err)\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckAWSSSMPatchBaselineDestroy(s *terraform.State) error {\n\tconn := testAccProvider.Meta().(*AWSClient).ssmconn\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_ssm_patch_baseline\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tout, err := conn.DescribePatchBaselines(&ssm.DescribePatchBaselinesInput{\n\t\t\tFilters: []*ssm.PatchOrchestratorFilter{\n\t\t\t\t{\n\t\t\t\t\tKey:    aws.String(\"NAME_PREFIX\"),\n\t\t\t\t\tValues: []*string{aws.String(rs.Primary.Attributes[\"name\"])},\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(out.BaselineIdentities) > 0 {\n\t\t\treturn fmt.Errorf(\"Expected AWS SSM Patch Baseline to be gone, but was still found\")\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn nil\n}\n\nfunc testAccAWSSSMPatchBaselineBasicConfig(rName string) string {\n\treturn fmt.Sprintf(`\n\nresource \"aws_ssm_patch_baseline\" \"foo\" {\n  name  = \"patch-baseline-%s\"\n  description = \"Baseline containing all updates approved for production systems\"\n  approved_patches = [\"KB123456\"]\n  approved_patches_compliance_level = \"CRITICAL\"\n}\n\n`, rName)\n}\n\nfunc testAccAWSSSMPatchBaselineBasicConfigUpdated(rName string) string {\n\treturn fmt.Sprintf(`\n\nresource \"aws_ssm_patch_baseline\" \"foo\" {\n  name  = \"updated-patch-baseline-%s\"\n  description = \"Baseline containing all updates approved for production systems - August 2017\"\n  approved_patches = [\"KB123456\",\"KB456789\"]\n  approved_patches_compliance_level = \"HIGH\"\n}\n\n`, rName)\n}\n\nfunc testAccAWSSSMPatchBaselineConfigWithOperatingSystem(rName string) string {\n\treturn fmt.Sprintf(`\n\nresource \"aws_ssm_patch_baseline\" \"foo\" {\n  name  = \"patch-baseline-%s\"\n  operating_system = \"AMAZON_LINUX\"\n  description = \"Baseline containing all updates approved for production systems\"\n  approval_rule {\n  \tapprove_after_days = 7\n\tenable_non_security = true\n  \tcompliance_level = \"CRITICAL\"\n\n  \tpatch_filter {\n\t\tkey = \"PRODUCT\"\n\t\tvalues = [\"AmazonLinux2016.03\",\"AmazonLinux2016.09\",\"AmazonLinux2017.03\",\"AmazonLinux2017.09\"]\n  \t}\n\n  \tpatch_filter {\n\t\tkey = \"SEVERITY\"\n\t\tvalues = [\"Critical\",\"Important\"]\n  \t}\n  }\n}\n\n`, rName)\n}\n\nfunc testAccAWSSSMPatchBaselineConfigWithOperatingSystemUpdated(rName string) string {\n\treturn fmt.Sprintf(`\n\nresource \"aws_ssm_patch_baseline\" \"foo\" {\n  name  = \"patch-baseline-%s\"\n  operating_system = \"WINDOWS\"\n  description = \"Baseline containing all updates approved for production systems\"\n  approval_rule {\n  \tapprove_after_days = 7\n  \tcompliance_level = \"INFORMATIONAL\"\n\n  \tpatch_filter {\n\t\tkey = \"PRODUCT\"\n\t\tvalues = [\"WindowsServer2012R2\"]\n  \t}\n\n  \tpatch_filter {\n\t\tkey = \"MSRC_SEVERITY\"\n\t\tvalues = [\"Critical\",\"Important\"]\n  \t}\n  }\n}\n\n`, rName)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\n\/\/ #cgo pkg-config: libzfs_core\n\/\/ #cgo CFLAGS: -fms-extensions -Wno-microsoft\n\/\/ int do_ioctl(int, char *, int, void *, int, void *, int);\nimport \"C\"\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"unsafe\"\n)\n\nfunc ioctl(f *os.File, name string, input, output []byte) error {\n\tif len(input) == 0 {\n\t\treturn errors.New(\"input nvl required\")\n\t}\n\tin := unsafe.Pointer(&input[0])\n\n\tvar out unsafe.Pointer\n\tif len(output) != 0 {\n\t\tout = unsafe.Pointer(&output[0])\n\t}\n\n\t_, err := C.do_ioctl(C.int(f.Fd()),\n\t\tC.CString(name), C.int(len(name)),\n\t\tunsafe.Pointer(in), C.int(len(input)),\n\t\tunsafe.Pointer(out), C.int(len(output)))\n\treturn err\n}\n<commit_msg>remove libzfs_core dependency<commit_after>package main\n\n\/\/ #cgo CFLAGS: -fms-extensions -Wno-microsoft\n\/\/ int do_ioctl(int, char *, int, void *, int, void *, int);\nimport \"C\"\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"unsafe\"\n)\n\nfunc ioctl(f *os.File, name string, input, output []byte) error {\n\tif len(input) == 0 {\n\t\treturn errors.New(\"input nvl required\")\n\t}\n\tin := unsafe.Pointer(&input[0])\n\n\tvar out unsafe.Pointer\n\tif len(output) != 0 {\n\t\tout = unsafe.Pointer(&output[0])\n\t}\n\n\t_, err := C.do_ioctl(C.int(f.Fd()),\n\t\tC.CString(name), C.int(len(name)),\n\t\tunsafe.Pointer(in), C.int(len(input)),\n\t\tunsafe.Pointer(out), C.int(len(output)))\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2016 Tigera, Inc. All rights reserved.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage commands\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/docopt\/docopt-go\"\n\t\"github.com\/projectcalico\/calicoctl\/calicoctl\/commands\/clientmgr\"\n\t\"github.com\/projectcalico\/calicoctl\/calicoctl\/commands\/constants\"\n)\n\nvar VERSION, BUILD_DATE, GIT_REVISION string\nvar VERSION_SUMMARY string\n\nfunc init() {\n\tVERSION_SUMMARY = \"calicoctl version \" + VERSION + \", build \" + GIT_REVISION\n}\n\nfunc Version(args []string) {\n\tdoc := `Usage:\n  calicoctl version [--config=<CONFIG>]\n\nOptions:\n  -h --help             Show this screen.\n  -c --config=<CONFIG>  Path to the file containing connection configuration in\n                        YAML or JSON format.\n                        [default: ` + constants.DefaultConfigPath + `]\n\nDescription:\n  Display the version of calicoctl.\n`\n\tparsedArgs, err := docopt.Parse(doc, args, true, \"\", false, false)\n\tif err != nil {\n\t\tfmt.Printf(\"Invalid option: 'calicoctl %s'. Use flag '--help' to read about a specific subcommand.\\n\", strings.Join(args, \" \"))\n\t\tos.Exit(1)\n\t}\n\tif len(parsedArgs) == 0 {\n\t\treturn\n\t}\n\n\tfmt.Println(\"Client Version:   \", VERSION)\n\tfmt.Println(\"Build date:       \", BUILD_DATE)\n\tfmt.Println(\"Git commit:       \", GIT_REVISION)\n\n\t\/\/ Load the client config and connect.\n\tcf := parsedArgs[\"--config\"].(string)\n\tclient, err := clientmgr.NewClient(cf)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tcfg := client.Config()\n\n\tval, assigned, err := cfg.GetFelixConfig(\"CalicoVersion\", \"\")\n\tif err != nil {\n\t\tval = fmt.Sprintf(\"unknown (%s)\", err)\n\t} else if !assigned {\n\t\tval = \"unknown\"\n\t}\n\tfmt.Println(\"Server Version:   \", val)\n\tval, assigned, err = cfg.GetFelixConfig(\"ClusterType\", \"\")\n\tif err != nil {\n\t\tval = fmt.Sprintf(\"unknown (%s)\", err)\n\t} else if !assigned {\n\t\tval = \"unknown\"\n\t}\n\tfmt.Println(\"Cluster Type:     \", val)\n}\n<commit_msg>Fix version output<commit_after>\/\/ Copyright (c) 2016 Tigera, Inc. All rights reserved.\n\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage commands\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/docopt\/docopt-go\"\n\t\"github.com\/projectcalico\/calicoctl\/calicoctl\/commands\/clientmgr\"\n\t\"github.com\/projectcalico\/calicoctl\/calicoctl\/commands\/constants\"\n)\n\nvar VERSION, BUILD_DATE, GIT_REVISION string\nvar VERSION_SUMMARY string\n\nfunc init() {\n\tVERSION_SUMMARY = \"calicoctl version \" + VERSION + \", build \" + GIT_REVISION\n}\n\nfunc Version(args []string) {\n\tdoc := `Usage:\n  calicoctl version [--config=<CONFIG>]\n\nOptions:\n  -h --help             Show this screen.\n  -c --config=<CONFIG>  Path to the file containing connection configuration in\n                        YAML or JSON format.\n                        [default: ` + constants.DefaultConfigPath + `]\n\nDescription:\n  Display the version of calicoctl.\n`\n\tparsedArgs, err := docopt.Parse(doc, args, true, \"\", false, false)\n\tif err != nil {\n\t\tfmt.Printf(\"Invalid option: 'calicoctl %s'. Use flag '--help' to read about a specific subcommand.\\n\", strings.Join(args, \" \"))\n\t\tos.Exit(1)\n\t}\n\tif len(parsedArgs) == 0 {\n\t\treturn\n\t}\n\n\tfmt.Println(\"Client Version:   \", VERSION)\n\tfmt.Println(\"Build date:       \", BUILD_DATE)\n\tfmt.Println(\"Git commit:       \", GIT_REVISION)\n\n\t\/\/ Load the client config and connect.\n\tcf := parsedArgs[\"--config\"].(string)\n\tclient, err := clientmgr.NewClient(cf)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tcfg := client.Config()\n\n\tval, assigned, err := cfg.GetFelixConfig(\"CalicoVersion\", \"\")\n\tif err != nil {\n\t\tval = fmt.Sprintf(\"unknown (%s)\", err)\n\t} else if !assigned {\n\t\tval = \"unknown\"\n\t}\n\tfmt.Println(\"Cluster Version:  \", val)\n\tval, assigned, err = cfg.GetFelixConfig(\"ClusterType\", \"\")\n\tif err != nil {\n\t\tval = fmt.Sprintf(\"unknown (%s)\", err)\n\t} else if !assigned {\n\t\tval = \"unknown\"\n\t}\n\tfmt.Println(\"Cluster Type:     \", val)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"dns-master\"\n\t\"errors\"\n\t\"flag\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ flag whether we want to emit debug output\nvar DEBUG bool = false\n\n\/\/ called for debug output\nfunc _D(fmt string, v ...interface{}) {\n\tif DEBUG {\n\t\tlog.Printf(fmt, v...)\n\t}\n}\nfunc (this ClientProxy) getServerIP() error {\n\tvar dns_servers []string\n\tdnsClient := new(dns.Client)\n\tif dnsClient == nil {\n\t\treturn errors.New(\"Can not new dns Client\")\n\t}\n\tdnsClient.WriteTimeout = this.timeout\n\tdnsClient.ReadTimeout = this.timeout\n\tfor _, serverstring := range this.SERVERS {\n\t\tipaddress := net.ParseIP(serverstring)\n\t\tif ipaddress != nil {\n\t\t\tif len(ipaddress) == 4 {\n\t\t\t\tdns_servers = append(dns_servers, serverstring)\n\t\t\t} else {\n\t\t\t\tserverstring = \"[\" + serverstring + \"]\"\n\t\t\t\tdns_servers = append(dns_servers, serverstring)\n\t\t\t}\n\t\t} else {\n\t\t\tdnsRequest := new(dns.Msg)\n\t\t\tdnsRequest.SetQuestion(\"domain\", dns.TypeA)\n\t\t\tdnsResponse, _, err := dnsClient.Exchange(dnsRequest, this.DNS_SERVERS[rand.Intn(len(this.DNS_SERVERS))])\n\t\t\tif err == nil {\n\t\t\t\tfor i := 0; i < len(dnsResponse.Answer); i++ {\n\t\t\t\t\tdns_servers = append(dns_servers, dnsResponse.Answer[i].String())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdnsRequest.SetQuestion(\"domain\", dns.TypeAAAA)\n\t\t\tdnsResponse, _, err = dnsClient.Exchange(dnsRequest, this.DNS_SERVERS[0])\n\t\t\tif err == nil {\n\t\t\t\tfor i := 0; i < len(dnsResponse.Answer); i++ {\n\t\t\t\t\tdns_servers = append(dns_servers, \"[\"+dnsResponse.Answer[i].String()+\"]\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tthis.SERVERS = dns_servers\n\treturn nil\n}\n\nfunc (this ClientProxy) ServeDNS(w dns.ResponseWriter, request *dns.Msg) {\n\trequest_bytes, err := request.Pack() \/\/I am not sure it is better to pack directly or using a pointer\n\tif err != nil {\n\t\tSRVFAIL(w, request)\n\t\t_D(\"error in packing request, error message: %s\", err)\n\t\treturn\n\t}\n\tServerInput := \"http:\/\/\" + this.SERVERS[rand.Intn(len(this.SERVERS))]\n\tpostBytesReader := bytes.NewReader(request_bytes)\n\treq, err := http.NewRequest(\"POST\", ServerInput, postBytesReader) \/\/need add random here in future\n\tif err != nil {\n\t\tSRVFAIL(w, request)\n\t\t_D(\"error in creating HTTP request, error message: %s\", err)\n\t\treturn\n\t}\n\tif this.TransPro == UDPcode {\n\t\treq.Header.Add(\"X-Proxy-DNS-Transport\", \"udp\")\n\t} else if this.TransPro == TCPcode {\n\t\treq.Header.Add(\"X-Proxy-DNS-Transport\", \"tcp\")\n\t}\n\treq.Header.Add(\"Content-Type\", \"application\/X-DNSoverHTTP\")\n\n\tresp, err := http.DefaultClient.Do(req)\n\t\/\/\tdefer resp.Body.Close()\n\tif err != nil {\n\t\tSRVFAIL(w, request)\n\t\t_D(\"error in HTTP post request, error message: %s\", err)\n\t\treturn\n\t}\n\tvar requestBody []byte\n\trequestBody, err = ioutil.ReadAll(resp.Body)\n\t\/\/\tnRead, err := resp.Body.Read(requestBody)\n\tif err != nil {\n\t\t\/\/ these need to be separate checks, otherwise you will get a nil-reference\n\t\t\/\/ when you print the error message below!\n\t\tSRVFAIL(w, request)\n\t\t_D(\"error in reading HTTP response, error message: %s\", err)\n\t\treturn\n\t}\n\t\/\/I not sure whether I should return server fail directly\n\t\/\/I just found there is a bug here. Body.Read can not read all the contents out, I don't know how to solve it.\n\tif len(requestBody) < (int)(resp.ContentLength) {\n\t\tSRVFAIL(w, request)\n\t\t_D(\"fail to read all HTTP content\")\n\t\treturn\n\t}\n\tvar DNSreponse dns.Msg\n\terr = DNSreponse.Unpack(requestBody)\n\tif err != nil {\n\t\tSRVFAIL(w, request)\n\t\t_D(\"error in packing HTTP response to DNS, error message: %s\", err)\n\t\treturn\n\t}\n\terr = w.WriteMsg(&DNSreponse)\n\tif err != nil {\n\t\t_D(\"error in sending DNS response back, error message: %s\", err)\n\t\treturn\n\t}\n}\n\nfunc SRVFAIL(w dns.ResponseWriter, req *dns.Msg) {\n\tm := new(dns.Msg)\n\tm.SetRcode(req, dns.RcodeServerFailure)\n\tw.WriteMsg(m)\n}\n\ntype ClientProxy struct {\n\tACCESS      []*net.IPNet\n\tSERVERS     []string\n\ts_len       int\n\tentries     int64\n\tmax_entries int64\n\tNOW         int64\n\tgiant       *sync.RWMutex\n\ttimeout     time.Duration\n\tTransPro    int \/\/specify for transmit protocol\n\tDNS_SERVERS []string\n}\n\nconst UDPcode = 1\nconst TCPcode = 2\n\nfunc main() {\n\tvar (\n\t\tS_SERVERS       string\n\t\tS_LISTEN        string\n\t\tS_ACCESS        string\n\t\ttimeout         int\n\t\tmax_entries     int64\n\t\texpire_interval int64\n\t\tS_DNS_SERVERS   string\n\t)\n\tflag.StringVar(&S_SERVERS, \"proxy\", \"\", \"we proxy requests to those servers,input like http:\/\/biilab.cn\") \/\/Not sure use IP or URL, default server undefined\n\tflag.StringVar(&S_LISTEN, \"listen\", \"[::]:53\", \"listen on (both tcp and udp)\")\n\tflag.StringVar(&S_ACCESS, \"access\", \"127.0.0.0\/8,10.0.0.0\/8\", \"allow those networks, use 0.0.0.0\/0 to allow everything\")\n\tflag.IntVar(&timeout, \"timeout\", 5, \"timeout\")\n\tflag.Int64Var(&expire_interval, \"expire_interval\", 300, \"delete expired entries every N seconds\")\n\tflag.BoolVar(&DEBUG, \"debug\", false, \"enable\/disable debug\")\n\tflag.Int64Var(&max_entries, \"max_cache_entries\", 2000000, \"max cache entries\")\n\tflag.StringVar(&S_DNS_SERVERS, \"dns_server\", \"114.114.114.114:53\", \"DNS server for initial server lookup\")\n\tflag.Parse()\n\tservers := strings.Split(S_SERVERS, \",\")\n\tdns_servers := strings.Split(S_DNS_SERVERS, \",\")\n\tUDPproxyer := ClientProxy{\n\t\tgiant:       new(sync.RWMutex),\n\t\tACCESS:      make([]*net.IPNet, 0),\n\t\tSERVERS:     servers,\n\t\ts_len:       len(servers),\n\t\tNOW:         time.Now().UTC().Unix(),\n\t\tentries:     0,\n\t\ttimeout:     time.Duration(timeout) * time.Second,\n\t\tmax_entries: max_entries,\n\t\tTransPro:    UDPcode,\n\t\tDNS_SERVERS: dns_servers}\n\tTCPproxyer := ClientProxy{\n\t\tgiant:       new(sync.RWMutex),\n\t\tACCESS:      make([]*net.IPNet, 0),\n\t\tSERVERS:     servers,\n\t\ts_len:       len(servers),\n\t\tNOW:         time.Now().UTC().Unix(),\n\t\tentries:     0,\n\t\ttimeout:     time.Duration(timeout) * time.Second,\n\t\tmax_entries: max_entries,\n\t\tTransPro:    TCPcode,\n\t\tDNS_SERVERS: dns_servers}\n\tfor _, mask := range strings.Split(S_ACCESS, \",\") {\n\t\t_, cidr, err := net.ParseCIDR(mask)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\t_D(\"added access for %s\\n\", mask)\n\t\tUDPproxyer.ACCESS = append(UDPproxyer.ACCESS, cidr)\n\t\tTCPproxyer.ACCESS = append(TCPproxyer.ACCESS, cidr)\n\t}\n\terr := UDPproxyer.getServerIP()\n\tif err != nil {\n\t\t_D(\"can not get server address\")\n\t\treturn\n\t}\n\terr = TCPproxyer.getServerIP()\n\tif err != nil {\n\t\t_D(\"can not get server address\")\n\t\treturn\n\t}\n\tfor _, addr := range strings.Split(S_LISTEN, \",\") {\n\t\t_D(\"listening @ %s\\n\", addr)\n\t\tgo func() {\n\t\t\tif err := dns.ListenAndServe(addr, \"udp\", UDPproxyer); err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}()\n\n\t\tgo func() {\n\t\t\tif err := dns.ListenAndServe(addr, \"tcp\", TCPproxyer); err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}()\n\t}\n\tfor {\n\t\tUDPproxyer.NOW = time.Now().UTC().Unix()\n\t\ttime.Sleep(time.Duration(1) * time.Second)\n\t}\n}\n<commit_msg>c support added<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"dns-master\"\n\t\"errors\"\n\t\"flag\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ flag whether we want to emit debug output\nvar DEBUG bool = false\n\n\/\/ called for debug output\nfunc _D(fmt string, v ...interface{}) {\n\tif DEBUG {\n\t\tlog.Printf(fmt, v...)\n\t}\n}\nfunc (this ClientProxy) getServerIP() error {\n\tvar dns_servers []string\n\tdnsClient := new(dns.Client)\n\tif dnsClient == nil {\n\t\treturn errors.New(\"Can not new dns Client\")\n\t}\n\tdnsClient.WriteTimeout = this.timeout\n\tdnsClient.ReadTimeout = this.timeout\n\tfor _, serverstring := range this.SERVERS {\n\t\tipaddress := net.ParseIP(serverstring)\n\t\tif ipaddress != nil {\n\t\t\tif len(ipaddress) == 4 {\n\t\t\t\tdns_servers = append(dns_servers, serverstring)\n\t\t\t} else {\n\t\t\t\tserverstring = \"[\" + serverstring + \"]\"\n\t\t\t\tdns_servers = append(dns_servers, serverstring)\n\t\t\t}\n\t\t} else {\n\t\t\tdnsRequest := new(dns.Msg)\n\t\t\tdnsRequest.SetQuestion(\"domain\", dns.TypeA)\n\t\t\tdnsResponse, _, err := dnsClient.Exchange(dnsRequest, this.DNS_SERVERS[rand.Intn(len(this.DNS_SERVERS))])\n\t\t\tif err == nil {\n\t\t\t\tfor i := 0; i < len(dnsResponse.Answer); i++ {\n\t\t\t\t\tdns_servers = append(dns_servers, dnsResponse.Answer[i].String())\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdnsRequest.SetQuestion(\"domain\", dns.TypeAAAA)\n\t\t\tdnsResponse, _, err = dnsClient.Exchange(dnsRequest, this.DNS_SERVERS[0])\n\t\t\tif err == nil {\n\t\t\t\tfor i := 0; i < len(dnsResponse.Answer); i++ {\n\t\t\t\t\tdns_servers = append(dns_servers, \"[\"+dnsResponse.Answer[i].String()+\"]\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tthis.SERVERS = dns_servers\n\treturn nil\n}\n\nfunc (this ClientProxy) ServeDNS(w dns.ResponseWriter, request *dns.Msg) {\n\trequest_bytes, err := request.Pack() \/\/I am not sure it is better to pack directly or using a pointer\n\tif err != nil {\n\t\tSRVFAIL(w, request)\n\t\t_D(\"error in packing request, error message: %s\", err)\n\t\treturn\n\t}\n\tServerInput := \"http:\/\/\" + this.SERVERS[rand.Intn(len(this.SERVERS))]\n\tpostBytesReader := bytes.NewReader(request_bytes)\n\treq, err := http.NewRequest(\"POST\", ServerInput, postBytesReader) \/\/need add random here in future\n\tif err != nil {\n\t\tSRVFAIL(w, request)\n\t\t_D(\"error in creating HTTP request, error message: %s\", err)\n\t\treturn\n\t}\n\tif this.C_version {\n\t\treq.Header.Add(\"Content-Type: \", \"application\/octet-stream\")\n\t\tif this.TransPro == UDPcode {\n\t\t\treq.Header.Add(\"HTTP_PROXY_DNS_TRANSPORT\", \"UDP\")\n\t\t} else if this.TransPro == TCPcode {\n\t\t\treq.Header.Add(\"HTTP_PROXY_DNS_TRANSPORT\", \"TCP\")\n\t\t}\n\t} else {\n\t\tif this.TransPro == UDPcode {\n\t\t\treq.Header.Add(\"X-Proxy-DNS-Transport\", \"udp\")\n\t\t} else if this.TransPro == TCPcode {\n\t\t\treq.Header.Add(\"X-Proxy-DNS-Transport\", \"tcp\")\n\t\t}\n\t\treq.Header.Add(\"Content-Type\", \"application\/X-DNSoverHTTP\")\n\t}\n\tresp, err := http.DefaultClient.Do(req)\n\t\/\/\tdefer resp.Body.Close()\n\tif err != nil {\n\t\tSRVFAIL(w, request)\n\t\t_D(\"error in HTTP post request, error message: %s\", err)\n\t\treturn\n\t}\n\tvar requestBody []byte\n\trequestBody, err = ioutil.ReadAll(resp.Body)\n\t\/\/\tnRead, err := resp.Body.Read(requestBody)\n\tif err != nil {\n\t\t\/\/ these need to be separate checks, otherwise you will get a nil-reference\n\t\t\/\/ when you print the error message below!\n\t\tSRVFAIL(w, request)\n\t\t_D(\"error in reading HTTP response, error message: %s\", err)\n\t\treturn\n\t}\n\t\/\/I not sure whether I should return server fail directly\n\t\/\/I just found there is a bug here. Body.Read can not read all the contents out, I don't know how to solve it.\n\tif len(requestBody) < (int)(resp.ContentLength) {\n\t\tSRVFAIL(w, request)\n\t\t_D(\"fail to read all HTTP content\")\n\t\treturn\n\t}\n\tvar DNSreponse dns.Msg\n\terr = DNSreponse.Unpack(requestBody)\n\tif err != nil {\n\t\tSRVFAIL(w, request)\n\t\t_D(\"error in packing HTTP response to DNS, error message: %s\", err)\n\t\treturn\n\t}\n\terr = w.WriteMsg(&DNSreponse)\n\tif err != nil {\n\t\t_D(\"error in sending DNS response back, error message: %s\", err)\n\t\treturn\n\t}\n}\n\nfunc SRVFAIL(w dns.ResponseWriter, req *dns.Msg) {\n\tm := new(dns.Msg)\n\tm.SetRcode(req, dns.RcodeServerFailure)\n\tw.WriteMsg(m)\n}\n\ntype ClientProxy struct {\n\tACCESS      []*net.IPNet\n\tSERVERS     []string\n\ts_len       int\n\tentries     int64\n\tmax_entries int64\n\tNOW         int64\n\tgiant       *sync.RWMutex\n\ttimeout     time.Duration\n\tTransPro    int \/\/specify for transmit protocol\n\tDNS_SERVERS []string\n\tC_version   bool\n}\n\nconst UDPcode = 1\nconst TCPcode = 2\n\nfunc main() {\n\tvar (\n\t\tS_SERVERS       string\n\t\tS_LISTEN        string\n\t\tS_ACCESS        string\n\t\ttimeout         int\n\t\tmax_entries     int64\n\t\texpire_interval int64\n\t\tS_DNS_SERVERS   string\n\t\tSupport_C       bool\n\t)\n\tflag.StringVar(&S_SERVERS, \"proxy\", \"\", \"we proxy requests to those servers,input like http:\/\/biilab.cn\") \/\/Not sure use IP or URL, default server undefined\n\tflag.StringVar(&S_LISTEN, \"listen\", \"[::]:53\", \"listen on (both tcp and udp)\")\n\tflag.StringVar(&S_ACCESS, \"access\", \"127.0.0.0\/8,10.0.0.0\/8\", \"allow those networks, use 0.0.0.0\/0 to allow everything\")\n\tflag.IntVar(&timeout, \"timeout\", 5, \"timeout\")\n\tflag.Int64Var(&expire_interval, \"expire_interval\", 300, \"delete expired entries every N seconds\")\n\tflag.BoolVar(&DEBUG, \"debug\", false, \"enable\/disable debug\")\n\tflag.Int64Var(&max_entries, \"max_cache_entries\", 2000000, \"max cache entries\")\n\tflag.StringVar(&S_DNS_SERVERS, \"dns_server\", \"114.114.114.114:53\", \"DNS server for initial server lookup\")\n\tflag.BoolVar(&Support_C, \"support_version\", false, \"Whether support Paul Vixie's C version\")\n\tflag.Parse()\n\tservers := strings.Split(S_SERVERS, \",\")\n\tdns_servers := strings.Split(S_DNS_SERVERS, \",\")\n\tUDPproxyer := ClientProxy{\n\t\tgiant:       new(sync.RWMutex),\n\t\tACCESS:      make([]*net.IPNet, 0),\n\t\tSERVERS:     servers,\n\t\ts_len:       len(servers),\n\t\tNOW:         time.Now().UTC().Unix(),\n\t\tentries:     0,\n\t\ttimeout:     time.Duration(timeout) * time.Second,\n\t\tmax_entries: max_entries,\n\t\tTransPro:    UDPcode,\n\t\tDNS_SERVERS: dns_servers,\n\t\tC_version:   Support_C}\n\tTCPproxyer := ClientProxy{\n\t\tgiant:       new(sync.RWMutex),\n\t\tACCESS:      make([]*net.IPNet, 0),\n\t\tSERVERS:     servers,\n\t\ts_len:       len(servers),\n\t\tNOW:         time.Now().UTC().Unix(),\n\t\tentries:     0,\n\t\ttimeout:     time.Duration(timeout) * time.Second,\n\t\tmax_entries: max_entries,\n\t\tTransPro:    TCPcode,\n\t\tDNS_SERVERS: dns_servers,\n\t\tC_version:   Support_C}\n\tfor _, mask := range strings.Split(S_ACCESS, \",\") {\n\t\t_, cidr, err := net.ParseCIDR(mask)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\t_D(\"added access for %s\\n\", mask)\n\t\tUDPproxyer.ACCESS = append(UDPproxyer.ACCESS, cidr)\n\t\tTCPproxyer.ACCESS = append(TCPproxyer.ACCESS, cidr)\n\t}\n\terr := UDPproxyer.getServerIP()\n\tif err != nil {\n\t\t_D(\"can not get server address\")\n\t\treturn\n\t}\n\terr = TCPproxyer.getServerIP()\n\tif err != nil {\n\t\t_D(\"can not get server address\")\n\t\treturn\n\t}\n\tfor _, addr := range strings.Split(S_LISTEN, \",\") {\n\t\t_D(\"listening @ %s\\n\", addr)\n\t\tgo func() {\n\t\t\tif err := dns.ListenAndServe(addr, \"udp\", UDPproxyer); err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}()\n\n\t\tgo func() {\n\t\t\tif err := dns.ListenAndServe(addr, \"tcp\", TCPproxyer); err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}()\n\t}\n\tfor {\n\t\tUDPproxyer.NOW = time.Now().UTC().Unix()\n\t\ttime.Sleep(time.Duration(1) * time.Second)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package handlers\n\nimport (\n\t\"context\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/golang\/protobuf\/ptypes\"\n\ttspb \"github.com\/golang\/protobuf\/ptypes\/timestamp\"\n\t\"google.golang.org\/grpc\/codes\"\n\n\t\"pixur.org\/pixur\/api\"\n\t\"pixur.org\/pixur\/be\/schema\"\n\t\"pixur.org\/pixur\/be\/status\"\n\t\"pixur.org\/pixur\/be\/tasks\"\n)\n\nfunc TestGetRefreshTokenSucceedsOnIdentSecret(t *testing.T) {\n\tvar taskCap *tasks.AuthUserTask\n\tsuccessRunner := func(_ context.Context, task tasks.Task) status.S {\n\t\ttaskCap = task.(*tasks.AuthUserTask)\n\t\ttaskCap.NewTokenID = 3\n\t\ttaskCap.User = &schema.User{\n\t\t\tUserId:     2,\n\t\t\tCapability: []schema.User_Capability{schema.User_PIC_READ},\n\t\t}\n\t\treturn nil\n\t}\n\n\ts := serv{\n\t\trunner: tasks.TestTaskRunner(successRunner),\n\t\tnow:    time.Now,\n\t}\n\tresp, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tIdent:  \"a\",\n\t\tSecret: \"b\",\n\t})\n\n\tif sts != nil {\n\t\tt.Fatal(sts)\n\t}\n\tif resp.RefreshToken == \"\" || resp.AuthToken == \"\" || resp.PixToken == \"\" {\n\t\tt.Error(\"tokens should be present\", resp)\n\t}\n\tif resp.RefreshPayload.Subject != \"2\" || resp.RefreshPayload.TokenId != 3 {\n\t\tt.Error(\"wrong token ids\", resp)\n\t}\n\tif taskCap == nil {\n\t\tt.Fatal(\"task didn't run\")\n\t}\n\tif taskCap.CompareHashAndPassword == nil {\n\t\tt.Error(\"no compare hash function\")\n\t}\n\tif taskCap.Ident != \"a\" || taskCap.Secret != \"b\" {\n\t\tt.Error(\"wrong task input\", taskCap.Ident, taskCap.Secret)\n\t}\n}\n\nfunc TestGetRefreshTokenSucceedsOnRefreshToken(t *testing.T) {\n\tvar taskCap *tasks.AuthUserTask\n\tsuccessRunner := func(_ context.Context, task tasks.Task) status.S {\n\t\ttaskCap = task.(*tasks.AuthUserTask)\n\t\ttaskCap.NewTokenID = 3\n\t\ttaskCap.User = &schema.User{\n\t\t\tUserId:     2,\n\t\t\tCapability: []schema.User_Capability{schema.User_PIC_READ},\n\t\t}\n\t\treturn nil\n\t}\n\ts := serv{\n\t\trunner: tasks.TestTaskRunner(successRunner),\n\t\tnow:    time.Now,\n\t}\n\n\ttoken, payload := testRefreshToken()\n\tres, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tRefreshToken: token,\n\t})\n\tif sts != nil {\n\t\tt.Fatal(sts)\n\t}\n\n\tif res.RefreshToken == \"\" || res.AuthToken == \"\" || res.PixToken == \"\" {\n\t\tt.Error(\"tokens should be present\", res)\n\t}\n\tif res.RefreshPayload.Subject != \"2\" || res.RefreshPayload.TokenId != 3 {\n\t\tt.Error(\"wrong token ids\", res)\n\t}\n\tif taskCap == nil {\n\t\tt.Fatal(\"task didn't run\")\n\t}\n\tif taskCap.TokenID != payload.TokenId || taskCap.UserID != 9 \/* payload.Subject *\/ {\n\t\tt.Error(\"wrong task input\", taskCap.Ident, taskCap.Secret)\n\t}\n}\n\nfunc TestGetRefreshTokenFailsOnInvalidToken(t *testing.T) {\n\ts := serv{\n\t\tnow: time.Now,\n\t}\n\t_, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tRefreshToken: \"invalid\",\n\t})\n\n\tif have, want := sts.Code(), codes.Unauthenticated; have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\tif have, want := sts.Message(), \"can't decode token\"; !strings.Contains(have, want) {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n}\n\nfunc TestGetRefreshTokenFailsOnNonRefreshToken(t *testing.T) {\n\tnotafter, _ := ptypes.TimestampProto(time.Now().Add(refreshPwtDuration))\n\tnotbefore, _ := ptypes.TimestampProto(time.Now().Add(-1 * time.Minute))\n\tpayload := &api.PwtPayload{\n\t\tSubject:   \"9\",\n\t\tNotAfter:  notafter,\n\t\tNotBefore: notbefore,\n\t\tType:      api.PwtPayload_AUTH,\n\t}\n\trefreshToken, err := defaultPwtCoder.encode(payload)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ts := serv{\n\t\tnow: time.Now,\n\t}\n\t_, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tRefreshToken: string(refreshToken),\n\t})\n\n\tif have, want := sts.Code(), codes.Unauthenticated; have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\n\tif have, want := sts.Message(), \"can't decode non refresh token\"; !strings.Contains(have, want) {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n}\n\nfunc TestGetRefreshTokenFailsOnBadSubject(t *testing.T) {\n\tnotafter, _ := ptypes.TimestampProto(time.Now().Add(refreshPwtDuration))\n\tnotbefore, _ := ptypes.TimestampProto(time.Now().Add(-1 * time.Minute))\n\tpayload := &api.PwtPayload{\n\t\tSubject:   \"invalid\",\n\t\tNotAfter:  notafter,\n\t\tNotBefore: notbefore,\n\t\tType:      api.PwtPayload_REFRESH,\n\t}\n\trefreshToken, err := defaultPwtCoder.encode(payload)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ts := serv{\n\t\tnow: time.Now,\n\t}\n\t_, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tRefreshToken: string(refreshToken),\n\t})\n\n\tif have, want := sts.Code(), codes.Unauthenticated; have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\n\tif have, want := sts.Message(), \"can't decode subject\"; !strings.Contains(have, want) {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n}\n\nfunc TestGetRefreshTokenFailsOnTaskError(t *testing.T) {\n\tfailureRunner := func(_ context.Context, task tasks.Task) status.S {\n\t\treturn status.Internal(nil, \"bad\")\n\t}\n\n\ts := serv{\n\t\tnow:    time.Now,\n\t\trunner: tasks.TestTaskRunner(failureRunner),\n\t}\n\n\t_, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{})\n\n\tif have, want := sts.Code(), codes.Internal; have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\n\tif have, want := sts.Message(), \"bad\"; !strings.Contains(have, want) {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n}\n\nfunc TestGetRefreshToken(t *testing.T) {\n\tvar taskCap *tasks.AuthUserTask\n\tsuccessRunner := func(_ context.Context, task tasks.Task) status.S {\n\t\ttaskCap = task.(*tasks.AuthUserTask)\n\t\ttaskCap.User = &schema.User{\n\t\t\tUserId:     2,\n\t\t\tCapability: []schema.User_Capability{schema.User_PIC_READ},\n\t\t}\n\t\ttaskCap.NewTokenID = 4\n\t\treturn nil\n\t}\n\ts := serv{\n\t\tnow:    time.Now,\n\t\trunner: tasks.TestTaskRunner(successRunner),\n\t}\n\tnotafter, _ := ptypes.TimestampProto(time.Now().Add(refreshPwtDuration))\n\tnotbefore, _ := ptypes.TimestampProto(time.Now().Add(-1 * time.Minute))\n\tpayload := &api.PwtPayload{\n\t\tSubject:   \"2\",\n\t\tNotAfter:  notafter,\n\t\tNotBefore: notbefore,\n\t\tType:      api.PwtPayload_REFRESH,\n\t\tTokenId:   3,\n\t}\n\trefreshToken, err := defaultPwtCoder.encode(payload)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tresp, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tIdent:        \"ident\",\n\t\tSecret:       \"secret\",\n\t\tRefreshToken: string(refreshToken),\n\t})\n\tif sts != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif have, want := taskCap.Ident, \"ident\"; have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\tif have, want := taskCap.Secret, \"secret\"; have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\tif have, want := taskCap.UserID, int64(2); have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\tif have, want := taskCap.TokenID, int64(3); have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\n\tif len(resp.RefreshToken) == 0 || len(resp.AuthToken) == 0 || len(resp.PixToken) == 0 {\n\t\tt.Error(\"expected non-empty token\", resp.RefreshToken, resp.AuthToken, resp.PixToken)\n\t}\n\n\tif !withinProto(resp.RefreshPayload.NotBefore, time.Now(), time.Minute*2) {\n\t\tt.Error(\"wrong before\", resp.RefreshPayload.NotBefore)\n\t}\n\tif !withinProto(resp.RefreshPayload.NotAfter, time.Now().Add(refreshPwtDuration), time.Minute) {\n\t\tt.Error(\"wrong after\", resp.RefreshPayload.NotAfter)\n\t}\n\tresp.RefreshPayload.NotBefore = nil\n\tresp.RefreshPayload.NotAfter = nil\n\texpectedRefresh := &api.PwtPayload{\n\t\tSubject: \"2\",\n\t\tTokenId: 4,\n\t\tType:    api.PwtPayload_REFRESH,\n\t}\n\tif !proto.Equal(resp.RefreshPayload, expectedRefresh) {\n\t\tt.Error(\"have\", resp.RefreshPayload, \"want\", expectedRefresh)\n\t}\n\n\tif !withinProto(resp.AuthPayload.NotBefore, time.Now(), time.Minute*2) {\n\t\tt.Error(\"wrong before\", resp.AuthPayload.NotBefore)\n\t}\n\tif !withinProto(resp.AuthPayload.NotAfter, time.Now().Add(authPwtDuration), time.Minute) {\n\t\tt.Error(\"wrong after\", resp.AuthPayload.NotAfter)\n\t}\n\tresp.AuthPayload.NotBefore = nil\n\tresp.AuthPayload.NotAfter = nil\n\texpectedAuth := &api.PwtPayload{\n\t\tSubject:       \"2\",\n\t\tTokenParentId: 4,\n\t\tType:          api.PwtPayload_AUTH,\n\t}\n\tif !proto.Equal(resp.AuthPayload, expectedAuth) {\n\t\tt.Error(\"have\", resp.AuthPayload, \"want\", expectedAuth)\n\t}\n\n\tif !withinProto(resp.PixPayload.NotBefore, time.Now(), time.Minute*2) {\n\t\tt.Error(\"wrong before\", resp.PixPayload.NotBefore)\n\t}\n\tif !withinProto(resp.PixPayload.NotAfter, time.Now().Add(refreshPwtDuration), time.Minute) {\n\t\tt.Error(\"wrong after\", resp.PixPayload.NotAfter)\n\t}\n\tif !withinProto(resp.PixPayload.SoftNotAfter, time.Now().Add(authPwtDuration), time.Minute) {\n\t\tt.Error(\"wrong soft after\", resp.PixPayload.SoftNotAfter)\n\t}\n\tresp.PixPayload.NotBefore = nil\n\tresp.PixPayload.NotAfter = nil\n\tresp.PixPayload.SoftNotAfter = nil\n\texpectedPix := &api.PwtPayload{\n\t\tSubject:       \"2\",\n\t\tTokenParentId: 4,\n\t\tType:          api.PwtPayload_PIX,\n\t}\n\tif !proto.Equal(resp.PixPayload, expectedPix) {\n\t\tt.Error(\"have\", resp.PixPayload, \"want\", expectedPix)\n\t}\n}\n\nfunc TestGetRefreshTokenNoPix(t *testing.T) {\n\tvar taskCap *tasks.AuthUserTask\n\tsuccessRunner := func(_ context.Context, task tasks.Task) status.S {\n\t\ttaskCap = task.(*tasks.AuthUserTask)\n\t\ttaskCap.User = &schema.User{\n\t\t\tUserId: 2,\n\t\t}\n\t\ttaskCap.NewTokenID = 4\n\t\treturn nil\n\t}\n\tnotafter, _ := ptypes.TimestampProto(time.Now().Add(refreshPwtDuration))\n\tnotbefore, _ := ptypes.TimestampProto(time.Now().Add(-1 * time.Minute))\n\tpayload := &api.PwtPayload{\n\t\tSubject:   \"2\",\n\t\tNotAfter:  notafter,\n\t\tNotBefore: notbefore,\n\t\tType:      api.PwtPayload_REFRESH,\n\t\tTokenId:   3,\n\t}\n\trefreshToken, err := defaultPwtCoder.encode(payload)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ts := serv{\n\t\tnow:    time.Now,\n\t\trunner: tasks.TestTaskRunner(successRunner),\n\t}\n\n\tresp, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tIdent:        \"ident\",\n\t\tSecret:       \"secret\",\n\t\tRefreshToken: string(refreshToken),\n\t})\n\tif sts != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(resp.PixToken) != 0 {\n\t\tt.Error(\"expected empty token\", resp.PixToken)\n\t}\n\tif resp.PixPayload != nil {\n\t\tt.Error(\"have\", resp.PixPayload, \"want\", nil)\n\t}\n}\n\nfunc within(t1, t2 time.Time, diff time.Duration) bool {\n\td := t1.Sub(t2)\n\tif d < 0 {\n\t\td = -d\n\t}\n\treturn d <= diff\n}\n\nfunc withinProto(t1pb *tspb.Timestamp, t2 time.Time, diff time.Duration) bool {\n\tt1, err := ptypes.Timestamp(t1pb)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\td := t1.Sub(t2)\n\tif d < 0 {\n\t\td = -d\n\t}\n\treturn d <= diff\n}\n\nfunc testRefreshToken() (string, *api.PwtPayload) {\n\tnotafter, _ := ptypes.TimestampProto(time.Now().Add(refreshPwtDuration))\n\tnotbefore, _ := ptypes.TimestampProto(time.Now().Add(-1 * time.Minute))\n\tpayload := &api.PwtPayload{\n\t\tSubject:   \"9\",\n\t\tNotAfter:  notafter,\n\t\tNotBefore: notbefore,\n\t\tType:      api.PwtPayload_REFRESH,\n\t\tTokenId:   10,\n\t}\n\trefreshToken, err := defaultPwtCoder.encode(payload)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(refreshToken), payload\n}\n<commit_msg>be\/handlers: fix softNotAfter tests<commit_after>package handlers\n\nimport (\n\t\"context\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/golang\/protobuf\/ptypes\"\n\ttspb \"github.com\/golang\/protobuf\/ptypes\/timestamp\"\n\t\"google.golang.org\/grpc\/codes\"\n\n\t\"pixur.org\/pixur\/api\"\n\t\"pixur.org\/pixur\/be\/schema\"\n\t\"pixur.org\/pixur\/be\/status\"\n\t\"pixur.org\/pixur\/be\/tasks\"\n)\n\nfunc TestGetRefreshTokenSucceedsOnIdentSecret(t *testing.T) {\n\tvar taskCap *tasks.AuthUserTask\n\tsuccessRunner := func(_ context.Context, task tasks.Task) status.S {\n\t\ttaskCap = task.(*tasks.AuthUserTask)\n\t\ttaskCap.NewTokenID = 3\n\t\ttaskCap.User = &schema.User{\n\t\t\tUserId:     2,\n\t\t\tCapability: []schema.User_Capability{schema.User_PIC_READ},\n\t\t}\n\t\treturn nil\n\t}\n\n\ts := serv{\n\t\trunner: tasks.TestTaskRunner(successRunner),\n\t\tnow:    time.Now,\n\t}\n\tresp, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tIdent:  \"a\",\n\t\tSecret: \"b\",\n\t})\n\n\tif sts != nil {\n\t\tt.Fatal(sts)\n\t}\n\tif resp.RefreshToken == \"\" || resp.AuthToken == \"\" || resp.PixToken == \"\" {\n\t\tt.Error(\"tokens should be present\", resp)\n\t}\n\tif resp.RefreshPayload.Subject != \"2\" || resp.RefreshPayload.TokenId != 3 {\n\t\tt.Error(\"wrong token ids\", resp)\n\t}\n\tif taskCap == nil {\n\t\tt.Fatal(\"task didn't run\")\n\t}\n\tif taskCap.CompareHashAndPassword == nil {\n\t\tt.Error(\"no compare hash function\")\n\t}\n\tif taskCap.Ident != \"a\" || taskCap.Secret != \"b\" {\n\t\tt.Error(\"wrong task input\", taskCap.Ident, taskCap.Secret)\n\t}\n}\n\nfunc TestGetRefreshTokenSucceedsOnRefreshToken(t *testing.T) {\n\tvar taskCap *tasks.AuthUserTask\n\tsuccessRunner := func(_ context.Context, task tasks.Task) status.S {\n\t\ttaskCap = task.(*tasks.AuthUserTask)\n\t\ttaskCap.NewTokenID = 3\n\t\ttaskCap.User = &schema.User{\n\t\t\tUserId:     2,\n\t\t\tCapability: []schema.User_Capability{schema.User_PIC_READ},\n\t\t}\n\t\treturn nil\n\t}\n\ts := serv{\n\t\trunner: tasks.TestTaskRunner(successRunner),\n\t\tnow:    time.Now,\n\t}\n\n\ttoken, payload := testRefreshToken()\n\tres, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tRefreshToken: token,\n\t})\n\tif sts != nil {\n\t\tt.Fatal(sts)\n\t}\n\n\tif res.RefreshToken == \"\" || res.AuthToken == \"\" || res.PixToken == \"\" {\n\t\tt.Error(\"tokens should be present\", res)\n\t}\n\tif res.RefreshPayload.Subject != \"2\" || res.RefreshPayload.TokenId != 3 {\n\t\tt.Error(\"wrong token ids\", res)\n\t}\n\tif taskCap == nil {\n\t\tt.Fatal(\"task didn't run\")\n\t}\n\tif taskCap.TokenID != payload.TokenId || taskCap.UserID != 9 \/* payload.Subject *\/ {\n\t\tt.Error(\"wrong task input\", taskCap.Ident, taskCap.Secret)\n\t}\n}\n\nfunc TestGetRefreshTokenFailsOnInvalidToken(t *testing.T) {\n\ts := serv{\n\t\tnow: time.Now,\n\t}\n\t_, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tRefreshToken: \"invalid\",\n\t})\n\n\tif have, want := sts.Code(), codes.Unauthenticated; have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\tif have, want := sts.Message(), \"can't decode token\"; !strings.Contains(have, want) {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n}\n\nfunc TestGetRefreshTokenFailsOnNonRefreshToken(t *testing.T) {\n\tnotafter, _ := ptypes.TimestampProto(time.Now().Add(refreshPwtDuration))\n\tnotbefore, _ := ptypes.TimestampProto(time.Now().Add(-1 * time.Minute))\n\tpayload := &api.PwtPayload{\n\t\tSubject:   \"9\",\n\t\tNotAfter:  notafter,\n\t\tNotBefore: notbefore,\n\t\tType:      api.PwtPayload_AUTH,\n\t}\n\trefreshToken, err := defaultPwtCoder.encode(payload)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ts := serv{\n\t\tnow: time.Now,\n\t}\n\t_, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tRefreshToken: string(refreshToken),\n\t})\n\n\tif have, want := sts.Code(), codes.Unauthenticated; have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\n\tif have, want := sts.Message(), \"can't decode non refresh token\"; !strings.Contains(have, want) {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n}\n\nfunc TestGetRefreshTokenFailsOnBadSubject(t *testing.T) {\n\tnotafter, _ := ptypes.TimestampProto(time.Now().Add(refreshPwtDuration))\n\tnotbefore, _ := ptypes.TimestampProto(time.Now().Add(-1 * time.Minute))\n\tpayload := &api.PwtPayload{\n\t\tSubject:   \"invalid\",\n\t\tNotAfter:  notafter,\n\t\tNotBefore: notbefore,\n\t\tType:      api.PwtPayload_REFRESH,\n\t}\n\trefreshToken, err := defaultPwtCoder.encode(payload)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ts := serv{\n\t\tnow: time.Now,\n\t}\n\t_, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tRefreshToken: string(refreshToken),\n\t})\n\n\tif have, want := sts.Code(), codes.Unauthenticated; have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\n\tif have, want := sts.Message(), \"can't decode subject\"; !strings.Contains(have, want) {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n}\n\nfunc TestGetRefreshTokenFailsOnTaskError(t *testing.T) {\n\tfailureRunner := func(_ context.Context, task tasks.Task) status.S {\n\t\treturn status.Internal(nil, \"bad\")\n\t}\n\n\ts := serv{\n\t\tnow:    time.Now,\n\t\trunner: tasks.TestTaskRunner(failureRunner),\n\t}\n\n\t_, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{})\n\n\tif have, want := sts.Code(), codes.Internal; have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\n\tif have, want := sts.Message(), \"bad\"; !strings.Contains(have, want) {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n}\n\nfunc TestGetRefreshToken(t *testing.T) {\n\tvar taskCap *tasks.AuthUserTask\n\tsuccessRunner := func(_ context.Context, task tasks.Task) status.S {\n\t\ttaskCap = task.(*tasks.AuthUserTask)\n\t\ttaskCap.User = &schema.User{\n\t\t\tUserId:     2,\n\t\t\tCapability: []schema.User_Capability{schema.User_PIC_READ},\n\t\t}\n\t\ttaskCap.NewTokenID = 4\n\t\treturn nil\n\t}\n\ts := serv{\n\t\tnow:    time.Now,\n\t\trunner: tasks.TestTaskRunner(successRunner),\n\t}\n\tnotafter, _ := ptypes.TimestampProto(time.Now().Add(refreshPwtDuration))\n\tnotbefore, _ := ptypes.TimestampProto(time.Now().Add(-1 * time.Minute))\n\tpayload := &api.PwtPayload{\n\t\tSubject:   \"2\",\n\t\tNotAfter:  notafter,\n\t\tNotBefore: notbefore,\n\t\tType:      api.PwtPayload_REFRESH,\n\t\tTokenId:   3,\n\t}\n\trefreshToken, err := defaultPwtCoder.encode(payload)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tresp, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tIdent:        \"ident\",\n\t\tSecret:       \"secret\",\n\t\tRefreshToken: string(refreshToken),\n\t})\n\tif sts != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif have, want := taskCap.Ident, \"ident\"; have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\tif have, want := taskCap.Secret, \"secret\"; have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\tif have, want := taskCap.UserID, int64(2); have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\tif have, want := taskCap.TokenID, int64(3); have != want {\n\t\tt.Error(\"have\", have, \"want\", want)\n\t}\n\n\tif len(resp.RefreshToken) == 0 || len(resp.AuthToken) == 0 || len(resp.PixToken) == 0 {\n\t\tt.Error(\"expected non-empty token\", resp.RefreshToken, resp.AuthToken, resp.PixToken)\n\t}\n\n\tif !withinProto(resp.RefreshPayload.NotBefore, time.Now(), time.Minute*2) {\n\t\tt.Error(\"wrong before\", resp.RefreshPayload.NotBefore)\n\t}\n\tif !withinProto(resp.RefreshPayload.NotAfter, time.Now().Add(refreshPwtDuration), time.Minute) {\n\t\tt.Error(\"wrong after\", resp.RefreshPayload.NotAfter)\n\t}\n\tresp.RefreshPayload.NotBefore = nil\n\tresp.RefreshPayload.NotAfter = nil\n\texpectedRefresh := &api.PwtPayload{\n\t\tSubject: \"2\",\n\t\tTokenId: 4,\n\t\tType:    api.PwtPayload_REFRESH,\n\t}\n\tif !proto.Equal(resp.RefreshPayload, expectedRefresh) {\n\t\tt.Error(\"have\", resp.RefreshPayload, \"want\", expectedRefresh)\n\t}\n\n\tif !withinProto(resp.AuthPayload.NotBefore, time.Now(), time.Minute*2) {\n\t\tt.Error(\"wrong before\", resp.AuthPayload.NotBefore)\n\t}\n\tif !withinProto(resp.AuthPayload.NotAfter, time.Now().Add(authPwtDuration), time.Minute) {\n\t\tt.Error(\"wrong after\", resp.AuthPayload.NotAfter)\n\t}\n\tif !withinProto(resp.AuthPayload.SoftNotAfter, time.Now().Add(authPwtSoftDuration), time.Minute) {\n\t\tt.Error(\"wrong soft after\", resp.AuthPayload.SoftNotAfter)\n\t}\n\tresp.AuthPayload.NotBefore = nil\n\tresp.AuthPayload.NotAfter = nil\n\tresp.AuthPayload.SoftNotAfter = nil\n\texpectedAuth := &api.PwtPayload{\n\t\tSubject:       \"2\",\n\t\tTokenParentId: 4,\n\t\tType:          api.PwtPayload_AUTH,\n\t}\n\tif !proto.Equal(resp.AuthPayload, expectedAuth) {\n\t\tt.Error(\"have\", resp.AuthPayload, \"want\", expectedAuth)\n\t}\n\n\tif !withinProto(resp.PixPayload.NotBefore, time.Now(), time.Minute*2) {\n\t\tt.Error(\"wrong before\", resp.PixPayload.NotBefore)\n\t}\n\tif !withinProto(resp.PixPayload.NotAfter, time.Now().Add(refreshPwtDuration), time.Minute) {\n\t\tt.Error(\"wrong after\", resp.PixPayload.NotAfter)\n\t}\n\tif !withinProto(resp.PixPayload.SoftNotAfter, time.Now().Add(authPwtDuration), time.Minute) {\n\t\tt.Error(\"wrong soft after\", resp.PixPayload.SoftNotAfter)\n\t}\n\tresp.PixPayload.NotBefore = nil\n\tresp.PixPayload.NotAfter = nil\n\tresp.PixPayload.SoftNotAfter = nil\n\texpectedPix := &api.PwtPayload{\n\t\tSubject:       \"2\",\n\t\tTokenParentId: 4,\n\t\tType:          api.PwtPayload_PIX,\n\t}\n\tif !proto.Equal(resp.PixPayload, expectedPix) {\n\t\tt.Error(\"have\", resp.PixPayload, \"want\", expectedPix)\n\t}\n}\n\nfunc TestGetRefreshTokenNoPix(t *testing.T) {\n\tvar taskCap *tasks.AuthUserTask\n\tsuccessRunner := func(_ context.Context, task tasks.Task) status.S {\n\t\ttaskCap = task.(*tasks.AuthUserTask)\n\t\ttaskCap.User = &schema.User{\n\t\t\tUserId: 2,\n\t\t}\n\t\ttaskCap.NewTokenID = 4\n\t\treturn nil\n\t}\n\tnotafter, _ := ptypes.TimestampProto(time.Now().Add(refreshPwtDuration))\n\tnotbefore, _ := ptypes.TimestampProto(time.Now().Add(-1 * time.Minute))\n\tpayload := &api.PwtPayload{\n\t\tSubject:   \"2\",\n\t\tNotAfter:  notafter,\n\t\tNotBefore: notbefore,\n\t\tType:      api.PwtPayload_REFRESH,\n\t\tTokenId:   3,\n\t}\n\trefreshToken, err := defaultPwtCoder.encode(payload)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\ts := serv{\n\t\tnow:    time.Now,\n\t\trunner: tasks.TestTaskRunner(successRunner),\n\t}\n\n\tresp, sts := s.handleGetRefreshToken(context.Background(), &api.GetRefreshTokenRequest{\n\t\tIdent:        \"ident\",\n\t\tSecret:       \"secret\",\n\t\tRefreshToken: string(refreshToken),\n\t})\n\tif sts != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif len(resp.PixToken) != 0 {\n\t\tt.Error(\"expected empty token\", resp.PixToken)\n\t}\n\tif resp.PixPayload != nil {\n\t\tt.Error(\"have\", resp.PixPayload, \"want\", nil)\n\t}\n}\n\nfunc within(t1, t2 time.Time, diff time.Duration) bool {\n\td := t1.Sub(t2)\n\tif d < 0 {\n\t\td = -d\n\t}\n\treturn d <= diff\n}\n\nfunc withinProto(t1pb *tspb.Timestamp, t2 time.Time, diff time.Duration) bool {\n\tt1, err := ptypes.Timestamp(t1pb)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\td := t1.Sub(t2)\n\tif d < 0 {\n\t\td = -d\n\t}\n\treturn d <= diff\n}\n\nfunc testRefreshToken() (string, *api.PwtPayload) {\n\tnotafter, _ := ptypes.TimestampProto(time.Now().Add(refreshPwtDuration))\n\tnotbefore, _ := ptypes.TimestampProto(time.Now().Add(-1 * time.Minute))\n\tpayload := &api.PwtPayload{\n\t\tSubject:   \"9\",\n\t\tNotAfter:  notafter,\n\t\tNotBefore: notbefore,\n\t\tType:      api.PwtPayload_REFRESH,\n\t\tTokenId:   10,\n\t}\n\trefreshToken, err := defaultPwtCoder.encode(payload)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn string(refreshToken), payload\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/koding\/kite\"\n\t\"github.com\/koding\/kite\/protocol\"\n\t\"github.com\/koding\/kloud\"\n)\n\n\/\/ Kloud represents a remote kloud instance\ntype Kloud struct {\n\tclient *kite.Client\n}\n\n\/\/ Kloud returns a new connected kloud instance. The kloud is ready to use.\n\/\/ It's connected and will redial if there is any disconnections.\nfunc NewKloud(k *kite.Kite) (*Kloud, error) {\n\tkontrolQuery := protocol.KontrolQuery{\n\t\tUsername:    \"koding\",\n\t\tEnvironment: \"vagrant\",\n\t\tName:        \"kloud\",\n\t}\n\n\ttimeout := time.After(time.Minute)\n\n\tk.Log.Info(\"Querying for Kloud: %+v\", kontrolQuery)\n\tfor {\n\t\tselect {\n\t\tcase <-time.Tick(time.Second * 2):\n\t\t\tkites, err := k.GetKites(kontrolQuery)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ still not up, try again until the kite is ready\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tremoteKite := kites[0]\n\n\t\t\tconnected, err := remoteKite.DialForever()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tselect {\n\t\t\tcase <-connected:\n\t\t\tcase <-time.After(time.Minute):\n\t\t\t\treturn nil, kloud.NewError(kloud.ErrNoKiteConnection)\n\t\t\t}\n\n\t\t\t\/\/ Kloud connection is ready now\n\t\t\treturn &Kloud{\n\t\t\t\tclient: remoteKite,\n\t\t\t}, nil\n\t\tcase <-timeout:\n\t\t\treturn nil, fmt.Errorf(\"timeout while connection for kite\")\n\t\t}\n\t}\n}\n\n\/\/ Report reports machine and usage metrics to kloud instance.\nfunc (k *Kloud) Report() error {\n\t\/\/ update information before we send it\n\tusg.Update()\n\n\tfmt.Printf(\"repoting usage %+v\\n\", usg)\n\tresp, err := k.client.Tell(\"report\", usg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"kloud response: %+v\\n\", resp.MustString())\n\treturn nil\n}\n<commit_msg>kloud: move report to koding provider<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/koding\/kite\"\n\t\"github.com\/koding\/kite\/protocol\"\n\t\"github.com\/koding\/kloud\"\n)\n\n\/\/ Kloud represents a remote kloud instance\ntype Kloud struct {\n\tclient *kite.Client\n}\n\n\/\/ Kloud returns a new connected kloud instance. The kloud is ready to use.\n\/\/ It's connected and will redial if there is any disconnections.\nfunc NewKloud(k *kite.Kite) (*Kloud, error) {\n\tkontrolQuery := protocol.KontrolQuery{\n\t\tUsername:    \"koding\",\n\t\tEnvironment: \"vagrant\",\n\t\tName:        \"kloud\",\n\t}\n\n\ttimeout := time.After(time.Minute)\n\n\tk.Log.Info(\"Querying for Kloud: %+v\", kontrolQuery)\n\tfor {\n\t\tselect {\n\t\tcase <-time.Tick(time.Second * 2):\n\t\t\tkites, err := k.GetKites(kontrolQuery)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ still not up, try again until the kite is ready\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tremoteKite := kites[0]\n\n\t\t\tconnected, err := remoteKite.DialForever()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tselect {\n\t\t\tcase <-connected:\n\t\t\tcase <-time.After(time.Minute):\n\t\t\t\treturn nil, kloud.NewError(kloud.ErrNoKiteConnection)\n\t\t\t}\n\n\t\t\t\/\/ Kloud connection is ready now\n\t\t\treturn &Kloud{\n\t\t\t\tclient: remoteKite,\n\t\t\t}, nil\n\t\tcase <-timeout:\n\t\t\treturn nil, fmt.Errorf(\"timeout while connection for kite\")\n\t\t}\n\t}\n}\n\n\/\/ Report reports machine and usage metrics to kloud instance.\nfunc (k *Kloud) Report() error {\n\t\/\/ update information before we send it\n\tusg.Update()\n\n\tfmt.Printf(\"repoting usage %+v\\n\", usg)\n\t_, err := k.client.Tell(\"report\", usg)\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package vdf\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"io\"\n)\n\n\/\/ Scanner represents a lexical scanner.\ntype Scanner struct {\n\tr *bufio.Reader\n}\n\n\/\/ NewScanner returns a new instance of Scanner.\nfunc NewScanner(r io.Reader) *Scanner {\n\treturn &Scanner{r: bufio.NewReader(r)}\n}\n\n\/\/ read reads the next rune from the buffered reader.\n\/\/ Returns the rune(0) if an error occurs (or io.EOF is returned).\nfunc (s *Scanner) read() rune {\n\tch, _, err := s.r.ReadRune()\n\tif err != nil {\n\t\treturn eof\n\t}\n\treturn ch\n}\n\n\/\/ unread places the previously read rune back on the reader.\nfunc (s *Scanner) unread() {\n\t_ = s.r.UnreadRune()\n}\n\n\/\/ Scan returns the next token and literal value.\nfunc (s *Scanner) Scan(respectWhitespace bool) (tok Token, lit string) {\n\t\/\/ Read the next rune.\n\tch := s.read()\n\n\t\/\/ If we see whitespace then consume all contiguous whitespace.\n\tif respectWhitespace == false && (isWhitespace(ch) || isLineEnding(ch)) {\n\t\ts.unread()\n\t\treturn s.scanWhitespace()\n\n\t\t\/\/ If we see a whitespace, return it\n\t} else if respectWhitespace == true && isWhitespace(ch) {\n\t\treturn WS, string(ch)\n\n\t\t\/\/ If we see a line ending, return it\n\t} else if respectWhitespace == true && isLineEnding(ch) {\n\t\treturn EOL, string(ch)\n\n\t\t\/\/ If we see a letter then consume as an ident or reserved word.\n\t} else if isLetter(ch) || isDigit(ch) {\n\t\ts.unread()\n\t\treturn s.scanIdent()\n\n\t\t\/\/ If we see a \"\/\/\" this line is a comment\n\t} else if isComment(ch, s) {\n\t\treturn CommentDoubleSlash, string(ch) + string(ch)\n\t}\n\n\t\/\/ Otherwise read the individual character.\n\tswitch ch {\n\tcase eof:\n\t\treturn EOF, \"\"\n\tcase '\\\\':\n\t\treturn EscapeSequence, string(ch)\n\tcase '{':\n\t\treturn CurlyBraceOpen, string(ch)\n\tcase '}':\n\t\treturn CurlyBraceClose, string(ch)\n\tcase '\"':\n\t\treturn QuotationMark, string(ch)\n\t}\n\n\treturn Illegal, string(ch)\n}\n\n\/\/ scanWhitespace consumes the current rune and all contiguous whitespace.\nfunc (s *Scanner) scanWhitespace() (Token, string) {\n\t\/\/ Create a buffer and read the current character into it.\n\tvar buf bytes.Buffer\n\tbuf.WriteRune(s.read())\n\n\t\/\/ Read every subsequent whitespace character into the buffer.\n\t\/\/ Non-whitespace characters and EOF will cause the loop to exit.\n\tfor {\n\t\tif ch := s.read(); ch == eof {\n\t\t\tbreak\n\t\t} else if !isWhitespace(ch) {\n\t\t\ts.unread()\n\t\t\tbreak\n\t\t} else {\n\t\t\tbuf.WriteRune(ch)\n\t\t}\n\t}\n\n\treturn WS, buf.String()\n}\n\n\/\/ scanIdent consumes the current rune and all contiguous ident runes.\nfunc (s *Scanner) scanIdent() (tok Token, lit string) {\n\t\/\/ Create a buffer and read the current character into it.\n\tvar buf bytes.Buffer\n\tbuf.WriteRune(s.read())\n\n\t\/\/ Read every subsequent ident character into the buffer.\n\t\/\/ Non-ident characters and EOF will cause the loop to exit.\n\tfor {\n\t\tif ch := s.read(); ch == eof {\n\t\t\tbreak\n\t\t} else if !isLetter(ch) && !isDigit(ch) && ch != '_' {\n\t\t\ts.unread()\n\t\t\tbreak\n\t\t} else {\n\t\t\t_, _ = buf.WriteRune(ch)\n\t\t}\n\t}\n\n\t\/\/ Otherwise return as a regular identifier.\n\treturn Ident, buf.String()\n}\n\nfunc isWhitespace(ch rune) bool {\n\treturn ch == ' ' || ch == '\\t'\n}\n\nfunc isLineEnding(ch rune) bool {\n\treturn ch == '\\n' || ch == '\\r'\n}\n\nfunc isLetter(ch rune) bool {\n\treturn (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')\n}\n\n\/\/ isDigit returns true if the rune is a digit.\nfunc isDigit(ch rune) bool {\n\treturn (ch >= '0' && ch <= '9')\n}\n\n\/\/ isComment returns true if this line starts with a comment (\"\/\/\")\nfunc isComment(ch rune, s *Scanner) bool {\n\tif ch != '\/' {\n\t\treturn false\n\t}\n\n\tnextRune := s.read()\n\tif nextRune != '\/' {\n\t\ts.unread()\n\t\treturn false\n\t}\n\n\treturn true\n}<commit_msg>go fmt<commit_after>package vdf\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"io\"\n)\n\n\/\/ Scanner represents a lexical scanner.\ntype Scanner struct {\n\tr *bufio.Reader\n}\n\n\/\/ NewScanner returns a new instance of Scanner.\nfunc NewScanner(r io.Reader) *Scanner {\n\treturn &Scanner{r: bufio.NewReader(r)}\n}\n\n\/\/ read reads the next rune from the buffered reader.\n\/\/ Returns the rune(0) if an error occurs (or io.EOF is returned).\nfunc (s *Scanner) read() rune {\n\tch, _, err := s.r.ReadRune()\n\tif err != nil {\n\t\treturn eof\n\t}\n\treturn ch\n}\n\n\/\/ unread places the previously read rune back on the reader.\nfunc (s *Scanner) unread() {\n\t_ = s.r.UnreadRune()\n}\n\n\/\/ Scan returns the next token and literal value.\nfunc (s *Scanner) Scan(respectWhitespace bool) (tok Token, lit string) {\n\t\/\/ Read the next rune.\n\tch := s.read()\n\n\t\/\/ If we see whitespace then consume all contiguous whitespace.\n\tif respectWhitespace == false && (isWhitespace(ch) || isLineEnding(ch)) {\n\t\ts.unread()\n\t\treturn s.scanWhitespace()\n\n\t\t\/\/ If we see a whitespace, return it\n\t} else if respectWhitespace == true && isWhitespace(ch) {\n\t\treturn WS, string(ch)\n\n\t\t\/\/ If we see a line ending, return it\n\t} else if respectWhitespace == true && isLineEnding(ch) {\n\t\treturn EOL, string(ch)\n\n\t\t\/\/ If we see a letter then consume as an ident or reserved word.\n\t} else if isLetter(ch) || isDigit(ch) {\n\t\ts.unread()\n\t\treturn s.scanIdent()\n\n\t\t\/\/ If we see a \"\/\/\" this line is a comment\n\t} else if isComment(ch, s) {\n\t\treturn CommentDoubleSlash, string(ch) + string(ch)\n\t}\n\n\t\/\/ Otherwise read the individual character.\n\tswitch ch {\n\tcase eof:\n\t\treturn EOF, \"\"\n\tcase '\\\\':\n\t\treturn EscapeSequence, string(ch)\n\tcase '{':\n\t\treturn CurlyBraceOpen, string(ch)\n\tcase '}':\n\t\treturn CurlyBraceClose, string(ch)\n\tcase '\"':\n\t\treturn QuotationMark, string(ch)\n\t}\n\n\treturn Illegal, string(ch)\n}\n\n\/\/ scanWhitespace consumes the current rune and all contiguous whitespace.\nfunc (s *Scanner) scanWhitespace() (Token, string) {\n\t\/\/ Create a buffer and read the current character into it.\n\tvar buf bytes.Buffer\n\tbuf.WriteRune(s.read())\n\n\t\/\/ Read every subsequent whitespace character into the buffer.\n\t\/\/ Non-whitespace characters and EOF will cause the loop to exit.\n\tfor {\n\t\tif ch := s.read(); ch == eof {\n\t\t\tbreak\n\t\t} else if !isWhitespace(ch) {\n\t\t\ts.unread()\n\t\t\tbreak\n\t\t} else {\n\t\t\tbuf.WriteRune(ch)\n\t\t}\n\t}\n\n\treturn WS, buf.String()\n}\n\n\/\/ scanIdent consumes the current rune and all contiguous ident runes.\nfunc (s *Scanner) scanIdent() (tok Token, lit string) {\n\t\/\/ Create a buffer and read the current character into it.\n\tvar buf bytes.Buffer\n\tbuf.WriteRune(s.read())\n\n\t\/\/ Read every subsequent ident character into the buffer.\n\t\/\/ Non-ident characters and EOF will cause the loop to exit.\n\tfor {\n\t\tif ch := s.read(); ch == eof {\n\t\t\tbreak\n\t\t} else if !isLetter(ch) && !isDigit(ch) && ch != '_' {\n\t\t\ts.unread()\n\t\t\tbreak\n\t\t} else {\n\t\t\t_, _ = buf.WriteRune(ch)\n\t\t}\n\t}\n\n\t\/\/ Otherwise return as a regular identifier.\n\treturn Ident, buf.String()\n}\n\nfunc isWhitespace(ch rune) bool {\n\treturn ch == ' ' || ch == '\\t'\n}\n\nfunc isLineEnding(ch rune) bool {\n\treturn ch == '\\n' || ch == '\\r'\n}\n\nfunc isLetter(ch rune) bool {\n\treturn (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')\n}\n\n\/\/ isDigit returns true if the rune is a digit.\nfunc isDigit(ch rune) bool {\n\treturn (ch >= '0' && ch <= '9')\n}\n\n\/\/ isComment returns true if this line starts with a comment (\"\/\/\")\nfunc isComment(ch rune, s *Scanner) bool {\n\tif ch != '\/' {\n\t\treturn false\n\t}\n\n\tnextRune := s.read()\n\tif nextRune != '\/' {\n\t\ts.unread()\n\t\treturn false\n\t}\n\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>package mark\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"unicode\/utf8\"\n)\n\n\/\/ type position\ntype Pos int\n\n\/\/ itemType identifies the type of lex items.\ntype itemType int\n\n\/\/ Item represent a token or text string returned from the scanner\ntype item struct {\n\ttyp itemType \/\/ The type of this item.\n\tpos Pos      \/\/ The starting position, in bytes, of this item in the input string.\n\tval string   \/\/ The value of this item.\n}\n\nconst eof = -1 \/\/ Zero value so closed channel delivers EOF\n\nconst (\n\titemError itemType = iota \/\/ Error occurred; value is text of error\n\t\/\/ Intersting things\n\titemNewLine\n\titemHTML\n\t\/\/ Block Elements\n\titemText\n\titemLineBreak\n\titemHeading\n\titemLHeading \/\/ Setext-style headers\n\titemBlockQuote\n\titemList\n\titemCodeBlock\n\titemGfmCodeBlock\n\titemHr\n\titemTable\n\titemLpTable\n\t\/\/ Span Elements\n\titemLink\n\titemAutoLink\n\titemGfmLink\n\titemStrong\n\titemItalic\n\titemStrike\n\titemCode\n\titemImage\n\titemBr\n\titemPipe\n\t\/\/ Indentation\n\titemIndent\n)\n\nvar (\n\treEmphasise = `^_{%[1]d}([\\s\\S]+?(?:_{0,}))_{%[1]d}|^\\*{%[1]d}([\\s\\S]+?(?:\\*{0,}))\\*{%[1]d}`\n\treGfmCode   = `^%[1]s{3,} *(\\S+)? *\\n([\\s\\S]+?)\\s*%[1]s{3,}$*(?:\\n+|$)`\n\treLinkText  = `(?:\\[[^\\]]*\\]|[^\\[\\]]|\\])*`\n\treLinkHref  = `\\s*<?([\\s\\S]*?)>?(?:\\s+['\"]([\\s\\S]*?)['\"])?\\s*`\n)\n\n\/\/ Block Grammer\nvar block = map[itemType]*regexp.Regexp{\n\titemHeading:   regexp.MustCompile(`^ *(#{1,6}) *([^\\n]+?) *#* *(?:\\n+|$)`),\n\titemLHeading:  regexp.MustCompile(`^([^\\n]+)\\n *(=|-){2,} *(?:\\n+|$)`),\n\titemHr:        regexp.MustCompile(`^( *[-*_]){3,} *(?:\\n+|$)`),\n\titemCodeBlock: regexp.MustCompile(`^(( {4}|\\t)[^-+*(\\d\\.)\\n]+\\n*)+`),\n\t\/\/ Backreferences is unavailable\n\titemGfmCodeBlock: regexp.MustCompile(fmt.Sprintf(reGfmCode, \"`\") + \"|\" + fmt.Sprintf(reGfmCode, \"~\")),\n\t\/\/ `^(?:[*+-]|\\d+\\.) [\\s\\S]+?(?:\\n|)`\n\titemList: regexp.MustCompile(`^(?:[*+-]|\\d+\\.) +?(?:\\n|)`),\n\t\/\/ leading-pipe table\n\titemLpTable: regexp.MustCompile(`^ *\\|(.+)\\n *\\|( *[-:]+[-| :]*)\\n((?: *\\|.*(?:\\n|$))*)\\n*`),\n\titemTable:   regexp.MustCompile(`^ *(\\S.*\\|.*)\\n *([-:]+ *\\|[-| :]*)\\n((?:.*\\|.*(?:\\n|$))*)\\n*`),\n}\n\n\/\/ Inline Grammer\nvar span = map[itemType]*regexp.Regexp{\n\titemItalic: regexp.MustCompile(fmt.Sprintf(reEmphasise, 1)),\n\titemStrong: regexp.MustCompile(fmt.Sprintf(reEmphasise, 2)),\n\titemStrike: regexp.MustCompile(`^~{2}([\\s\\S]+?)~{2}`),\n\t\/\/ itemMixed(e.g: ***str***, ~~*str*~~) will be part of the parser\n\t\/\/ or we'll lex recuresively\n\titemCode: regexp.MustCompile(\"^`{1,2}\\\\s*([\\\\s\\\\S]*?[^`])\\\\s*`{1,2}\"),\n\titemBr:   regexp.MustCompile(`^ {2,}\\n`),\n\t\/\/ Links\n\titemLink:     regexp.MustCompile(fmt.Sprintf(`^!?\\[(%s)\\]\\(%s\\)`, reLinkText, reLinkHref)),\n\titemAutoLink: regexp.MustCompile(`^<([^ >]+(@|:\\\/)[^ >]+)>`),\n\titemGfmLink:  regexp.MustCompile(`^(https?:\\\/\\\/[^\\s<]+[^<.,:;\"')\\]\\s])`),\n\t\/\/ Image\n\t\/\/ TODO(Ariel): DRY\n\titemImage: regexp.MustCompile(fmt.Sprintf(`^!?\\[(%s)\\]\\(%s\\)`, reLinkText, reLinkHref)),\n}\n\n\/\/ stateFn represents the state of the scanner as a function that returns the next state.\ntype stateFn func(*lexer) stateFn\n\n\/\/ lexer holds the state of the scanner.\ntype lexer struct {\n\tname    string    \/\/ the name of the input; used only for error reports\n\tinput   string    \/\/ the string being scanned\n\tstate   stateFn   \/\/ the next lexing function to enter\n\tpos     Pos       \/\/ current position in the input\n\tstart   Pos       \/\/ start position of this item\n\twidth   Pos       \/\/ width of last rune read from input\n\tlastPos Pos       \/\/ position of most recent item returned by nextItem\n\titems   chan item \/\/ channel of scanned items\n\teot     Pos       \/\/ end of table\n}\n\n\/\/ lex creates a new lexer for the input string.\nfunc lex(name, input string) *lexer {\n\tl := &lexer{\n\t\tname:  name,\n\t\tinput: input,\n\t\titems: make(chan item),\n\t}\n\tgo l.run()\n\treturn l\n}\n\n\/\/ run runs the state machine for the lexer.\nfunc (l *lexer) run() {\n\tfor l.state = lexAny; l.state != nil; {\n\t\tl.state = l.state(l)\n\t}\n\tclose(l.items)\n}\n\n\/\/ next return the next rune in the input\nfunc (l *lexer) next() rune {\n\tif int(l.pos) >= len(l.input) {\n\t\tl.width = 0\n\t\treturn eof\n\t}\n\tr, w := utf8.DecodeRuneInString(l.input[l.pos:])\n\tl.width = Pos(w)\n\tl.pos += l.width\n\treturn r\n}\n\n\/\/ lexAny scans non-space items.\nfunc lexAny(l *lexer) stateFn {\n\tswitch r := l.next(); r {\n\tcase eof:\n\t\treturn nil\n\tcase '*', '-', '_', '+':\n\t\tp := l.peek()\n\t\tif p == '*' || p == '-' || p == '_' {\n\t\t\tl.backup()\n\t\t\treturn lexHr\n\t\t} else {\n\t\t\tl.backup()\n\t\t\treturn lexList\n\t\t}\n\tcase '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':\n\t\tl.backup()\n\t\treturn lexList\n\tcase '>':\n\t\tl.emit(itemBlockQuote)\n\t\treturn lexText\n\tcase '#':\n\t\tl.backup()\n\t\treturn lexHeading\n\tcase ' ', '\\t':\n\t\t\/\/ Should be here ?\n\t\t\/\/ TODO(Ariel): test that it's a codeBlock and not list for sure\n\t\tif block[itemCodeBlock].MatchString(l.input[l.pos-1:]) {\n\t\t\tl.backup()\n\t\t\treturn lexCode\n\t\t}\n\t\t\/\/ Keep moving forward until we get all the\n\t\t\/\/ indentation size\n\t\tfor ; r == l.peek(); r = l.next() {\n\t\t}\n\t\tl.emit(itemIndent)\n\t\treturn lexAny\n\tcase '`', '~':\n\t\t\/\/ if it's gfm-code\n\t\tc := l.input[l.pos : l.pos+2]\n\t\tif c == \"``\" || c == \"~~\" {\n\t\t\tl.backup()\n\t\t\treturn lexGfmCode\n\t\t}\n\t\tfallthrough\n\tcase '|':\n\t\tif m := block[itemLpTable].FindString(l.input[l.pos-1:]); m != \"\" {\n\t\t\tl.eot = l.start + Pos(len(m))\n\t\t\tl.emit(itemLpTable)\n\t\t}\n\t\tfallthrough\n\tdefault:\n\t\tif m := block[itemTable].FindString(l.input[l.pos-1:]); m != \"\" {\n\t\t\tl.eot = l.start + Pos(len(m)) - l.width\n\t\t\tl.emit(itemTable)\n\t\t\t\/\/ we go one step back to get the full text\n\t\t\t\/\/ in the lexText phase\n\t\t\tl.start--\n\t\t}\n\t\tl.backup()\n\t\treturn lexText\n\t}\n}\n\n\/\/ lexHeading scans heading items.\nfunc lexHeading(l *lexer) stateFn {\n\tif m := block[itemHeading].FindString(l.input[l.pos:]); m != \"\" {\n\t\t\/\/ Emit without the newline(\\n)\n\t\tl.pos += Pos(len(m))\n\t\t\/\/ TODO(Ariel): hack, fix regexp\n\t\tif strings.HasSuffix(m, \"\\n\") {\n\t\t\tl.pos--\n\t\t}\n\t\tl.emit(itemHeading)\n\t\treturn lexAny\n\t}\n\treturn lexText\n}\n\n\/\/ lexHr scans horizontal rules items.\nfunc lexHr(l *lexer) stateFn {\n\tif block[itemHr].MatchString(l.input[l.pos:]) {\n\t\tmatch := block[itemHr].FindString(l.input[l.pos:])\n\t\tl.pos += Pos(len(match))\n\t\tl.emit(itemHr)\n\t\treturn lexAny\n\t}\n\treturn lexText\n}\n\n\/\/ lexGfmCode scans GFM code block.\nfunc lexGfmCode(l *lexer) stateFn {\n\tre := block[itemGfmCodeBlock]\n\tif re.MatchString(l.input[l.pos:]) {\n\t\tmatch := re.FindString(l.input[l.pos:])\n\t\tl.pos += Pos(len(match))\n\t\tl.emit(itemGfmCodeBlock)\n\t\treturn lexAny\n\t}\n\treturn lexText\n}\n\n\/\/ lexCode scans code block.\nfunc lexCode(l *lexer) stateFn {\n\tmatch := block[itemCodeBlock].FindString(l.input[l.pos:])\n\tl.pos += Pos(len(match))\n\tl.emit(itemCodeBlock)\n\treturn lexAny\n}\n\n\/\/ lexList scans ordered and unordered lists.\nfunc lexList(l *lexer) stateFn {\n\tif m := block[itemList].FindString(l.input[l.pos:]); m != \"\" {\n\t\tl.pos += Pos(len(m))\n\t\tl.emit(itemList)\n\t}\n\treturn lexText\n}\n\n\/\/ lexText scans until eol(\\n)\n\/\/ We have a lot of things to do in this lextext\n\/\/ for example: ignore itemBr on list\/tables\n\/\/ fix the text scaning etc...\nfunc lexText(l *lexer) stateFn {\n\t\/\/ Drain text before emitting\n\temit := func(item itemType, pos Pos) {\n\t\tif l.pos > l.start {\n\t\t\tl.emit(itemText)\n\t\t}\n\t\tl.pos += pos\n\t\tl.emit(item)\n\t}\nLoop:\n\tfor {\n\t\tswitch r := l.peek(); {\n\t\tcase r == eof:\n\t\t\temit(eof, Pos(0))\n\t\t\tbreak Loop\n\t\tcase r == '\\n':\n\t\t\temit(itemNewLine, l.width)\n\t\t\tbreak Loop\n\t\tcase r == ' ':\n\t\t\tif m := span[itemBr].FindString(l.input[l.pos:]); m != \"\" {\n\t\t\t\t\/\/ pos - length of new-line\n\t\t\t\temit(itemBr, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl.next()\n\t\t\/\/ if it's start as an emphasis\n\t\tcase r == '_', r == '*', r == '~', r == '`':\n\t\t\tinput := l.input[l.pos:]\n\t\t\t\/\/ Strong\n\t\t\tif m := span[itemStrong].FindString(input); m != \"\" {\n\t\t\t\temit(itemStrong, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t\/\/ Italic\n\t\t\tif m := span[itemItalic].FindString(input); m != \"\" {\n\t\t\t\temit(itemItalic, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t\/\/ Strike\n\t\t\tif m := span[itemStrike].FindString(input); m != \"\" {\n\t\t\t\temit(itemStrike, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t\/\/ InlineCode\n\t\t\tif m := span[itemCode].FindString(input); m != \"\" {\n\t\t\t\temit(itemCode, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl.next()\n\t\t\/\/ itemLink, itemAutoLink, itemImage\n\t\tcase r == '[', r == '<', r == '!':\n\t\t\tinput := l.input[l.pos:]\n\t\t\tif m := span[itemLink].FindString(input); m != \"\" {\n\t\t\t\tpos := Pos(len(m))\n\t\t\t\tif r == '[' {\n\t\t\t\t\temit(itemLink, pos)\n\t\t\t\t} else {\n\t\t\t\t\temit(itemImage, pos)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif m := span[itemAutoLink].FindString(input); m != \"\" {\n\t\t\t\temit(itemAutoLink, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl.next()\n\t\tcase r == '|':\n\t\t\tif l.eot > l.pos {\n\t\t\t\temit(itemPipe, l.width)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl.next()\n\t\tdefault:\n\t\t\tinput := l.input[l.pos:]\n\t\t\t\/\/ Test for Setext-style headers\n\t\t\tif m := block[itemLHeading].FindString(input); m != \"\" {\n\t\t\t\temit(itemLHeading, Pos(len(m)))\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\t\t\/\/ GfmLink\n\t\t\tif m := span[itemGfmLink].FindString(input); m != \"\" {\n\t\t\t\temit(itemGfmLink, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl.next()\n\t\t}\n\t}\n\treturn lexAny\n}\n\n\/\/ backup steps back one rune. Can only be called once per call of next.\nfunc (l *lexer) backup() {\n\tl.pos -= l.width\n}\n\n\/\/ peek returns but does not consume the next rune in the input.\nfunc (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}\n\n\/\/ emit passes an item back to the client.\nfunc (l *lexer) emit(t itemType) {\n\tl.items <- item{t, l.start, l.input[l.start:l.pos]}\n\tl.start = l.pos\n}\n\n\/\/ lexItem return the next item token, clled by the parser.\nfunc (l *lexer) nextItem() item {\n\titem := <-l.items\n\tl.lastPos = l.pos\n\treturn item\n}\n<commit_msg>fix(lexer): heading regexp<commit_after>package mark\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"unicode\/utf8\"\n)\n\n\/\/ type position\ntype Pos int\n\n\/\/ itemType identifies the type of lex items.\ntype itemType int\n\n\/\/ Item represent a token or text string returned from the scanner\ntype item struct {\n\ttyp itemType \/\/ The type of this item.\n\tpos Pos      \/\/ The starting position, in bytes, of this item in the input string.\n\tval string   \/\/ The value of this item.\n}\n\nconst eof = -1 \/\/ Zero value so closed channel delivers EOF\n\nconst (\n\titemError itemType = iota \/\/ Error occurred; value is text of error\n\t\/\/ Intersting things\n\titemNewLine\n\titemHTML\n\t\/\/ Block Elements\n\titemText\n\titemLineBreak\n\titemHeading\n\titemLHeading \/\/ Setext-style headers\n\titemBlockQuote\n\titemList\n\titemCodeBlock\n\titemGfmCodeBlock\n\titemHr\n\titemTable\n\titemLpTable\n\t\/\/ Span Elements\n\titemLink\n\titemAutoLink\n\titemGfmLink\n\titemStrong\n\titemItalic\n\titemStrike\n\titemCode\n\titemImage\n\titemBr\n\titemPipe\n\t\/\/ Indentation\n\titemIndent\n)\n\nvar (\n\treEmphasise = `^_{%[1]d}([\\s\\S]+?(?:_{0,}))_{%[1]d}|^\\*{%[1]d}([\\s\\S]+?(?:\\*{0,}))\\*{%[1]d}`\n\treGfmCode   = `^%[1]s{3,} *(\\S+)? *\\n([\\s\\S]+?)\\s*%[1]s{3,}$*(?:\\n+|$)`\n\treLinkText  = `(?:\\[[^\\]]*\\]|[^\\[\\]]|\\])*`\n\treLinkHref  = `\\s*<?([\\s\\S]*?)>?(?:\\s+['\"]([\\s\\S]*?)['\"])?\\s*`\n)\n\n\/\/ Block Grammer\nvar block = map[itemType]*regexp.Regexp{\n\titemHeading:   regexp.MustCompile(`^ *(#{1,6}) +([^\\n]+?) *#* *(?:\\n+|$)`),\n\titemLHeading:  regexp.MustCompile(`^([^\\n]+)\\n *(=|-){2,} *(?:\\n+|$)`),\n\titemHr:        regexp.MustCompile(`^( *[-*_]){3,} *(?:\\n+|$)`),\n\titemCodeBlock: regexp.MustCompile(`^(( {4}|\\t)[^-+*(\\d\\.)\\n]+\\n*)+`),\n\t\/\/ Backreferences is unavailable\n\titemGfmCodeBlock: regexp.MustCompile(fmt.Sprintf(reGfmCode, \"`\") + \"|\" + fmt.Sprintf(reGfmCode, \"~\")),\n\t\/\/ `^(?:[*+-]|\\d+\\.) [\\s\\S]+?(?:\\n|)`\n\titemList: regexp.MustCompile(`^(?:[*+-]|\\d+\\.) +?(?:\\n|)`),\n\t\/\/ leading-pipe table\n\titemLpTable: regexp.MustCompile(`^ *\\|(.+)\\n *\\|( *[-:]+[-| :]*)\\n((?: *\\|.*(?:\\n|$))*)\\n*`),\n\titemTable:   regexp.MustCompile(`^ *(\\S.*\\|.*)\\n *([-:]+ *\\|[-| :]*)\\n((?:.*\\|.*(?:\\n|$))*)\\n*`),\n}\n\n\/\/ Inline Grammer\nvar span = map[itemType]*regexp.Regexp{\n\titemItalic: regexp.MustCompile(fmt.Sprintf(reEmphasise, 1)),\n\titemStrong: regexp.MustCompile(fmt.Sprintf(reEmphasise, 2)),\n\titemStrike: regexp.MustCompile(`^~{2}([\\s\\S]+?)~{2}`),\n\t\/\/ itemMixed(e.g: ***str***, ~~*str*~~) will be part of the parser\n\t\/\/ or we'll lex recuresively\n\titemCode: regexp.MustCompile(\"^`{1,2}\\\\s*([\\\\s\\\\S]*?[^`])\\\\s*`{1,2}\"),\n\titemBr:   regexp.MustCompile(`^ {2,}\\n`),\n\t\/\/ Links\n\titemLink:     regexp.MustCompile(fmt.Sprintf(`^!?\\[(%s)\\]\\(%s\\)`, reLinkText, reLinkHref)),\n\titemAutoLink: regexp.MustCompile(`^<([^ >]+(@|:\\\/)[^ >]+)>`),\n\titemGfmLink:  regexp.MustCompile(`^(https?:\\\/\\\/[^\\s<]+[^<.,:;\"')\\]\\s])`),\n\t\/\/ Image\n\t\/\/ TODO(Ariel): DRY\n\titemImage: regexp.MustCompile(fmt.Sprintf(`^!?\\[(%s)\\]\\(%s\\)`, reLinkText, reLinkHref)),\n}\n\n\/\/ stateFn represents the state of the scanner as a function that returns the next state.\ntype stateFn func(*lexer) stateFn\n\n\/\/ lexer holds the state of the scanner.\ntype lexer struct {\n\tname    string    \/\/ the name of the input; used only for error reports\n\tinput   string    \/\/ the string being scanned\n\tstate   stateFn   \/\/ the next lexing function to enter\n\tpos     Pos       \/\/ current position in the input\n\tstart   Pos       \/\/ start position of this item\n\twidth   Pos       \/\/ width of last rune read from input\n\tlastPos Pos       \/\/ position of most recent item returned by nextItem\n\titems   chan item \/\/ channel of scanned items\n\teot     Pos       \/\/ end of table\n}\n\n\/\/ lex creates a new lexer for the input string.\nfunc lex(name, input string) *lexer {\n\tl := &lexer{\n\t\tname:  name,\n\t\tinput: input,\n\t\titems: make(chan item),\n\t}\n\tgo l.run()\n\treturn l\n}\n\n\/\/ run runs the state machine for the lexer.\nfunc (l *lexer) run() {\n\tfor l.state = lexAny; l.state != nil; {\n\t\tl.state = l.state(l)\n\t}\n\tclose(l.items)\n}\n\n\/\/ next return the next rune in the input\nfunc (l *lexer) next() rune {\n\tif int(l.pos) >= len(l.input) {\n\t\tl.width = 0\n\t\treturn eof\n\t}\n\tr, w := utf8.DecodeRuneInString(l.input[l.pos:])\n\tl.width = Pos(w)\n\tl.pos += l.width\n\treturn r\n}\n\n\/\/ lexAny scans non-space items.\nfunc lexAny(l *lexer) stateFn {\n\tswitch r := l.next(); r {\n\tcase eof:\n\t\treturn nil\n\tcase '*', '-', '_', '+':\n\t\tp := l.peek()\n\t\tif p == '*' || p == '-' || p == '_' {\n\t\t\tl.backup()\n\t\t\treturn lexHr\n\t\t} else {\n\t\t\tl.backup()\n\t\t\treturn lexList\n\t\t}\n\tcase '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':\n\t\tl.backup()\n\t\treturn lexList\n\tcase '>':\n\t\tl.emit(itemBlockQuote)\n\t\treturn lexText\n\tcase '#':\n\t\tl.backup()\n\t\treturn lexHeading\n\tcase ' ', '\\t':\n\t\t\/\/ Should be here ?\n\t\t\/\/ TODO(Ariel): test that it's a codeBlock and not list for sure\n\t\tif block[itemCodeBlock].MatchString(l.input[l.pos-1:]) {\n\t\t\tl.backup()\n\t\t\treturn lexCode\n\t\t}\n\t\t\/\/ Keep moving forward until we get all the\n\t\t\/\/ indentation size\n\t\tfor ; r == l.peek(); r = l.next() {\n\t\t}\n\t\tl.emit(itemIndent)\n\t\treturn lexAny\n\tcase '`', '~':\n\t\t\/\/ if it's gfm-code\n\t\tc := l.input[l.pos : l.pos+2]\n\t\tif c == \"``\" || c == \"~~\" {\n\t\t\tl.backup()\n\t\t\treturn lexGfmCode\n\t\t}\n\t\tfallthrough\n\tcase '|':\n\t\tif m := block[itemLpTable].FindString(l.input[l.pos-1:]); m != \"\" {\n\t\t\tl.eot = l.start + Pos(len(m))\n\t\t\tl.emit(itemLpTable)\n\t\t}\n\t\tfallthrough\n\tdefault:\n\t\tif m := block[itemTable].FindString(l.input[l.pos-1:]); m != \"\" {\n\t\t\tl.eot = l.start + Pos(len(m)) - l.width\n\t\t\tl.emit(itemTable)\n\t\t\t\/\/ we go one step back to get the full text\n\t\t\t\/\/ in the lexText phase\n\t\t\tl.start--\n\t\t}\n\t\tl.backup()\n\t\treturn lexText\n\t}\n}\n\n\/\/ lexHeading scans heading items.\nfunc lexHeading(l *lexer) stateFn {\n\tif m := block[itemHeading].FindString(l.input[l.pos:]); m != \"\" {\n\t\t\/\/ Emit without the newline(\\n)\n\t\tl.pos += Pos(len(m))\n\t\t\/\/ TODO(Ariel): hack, fix regexp\n\t\tif strings.HasSuffix(m, \"\\n\") {\n\t\t\tl.pos--\n\t\t}\n\t\tl.emit(itemHeading)\n\t\treturn lexAny\n\t}\n\treturn lexText\n}\n\n\/\/ lexHr scans horizontal rules items.\nfunc lexHr(l *lexer) stateFn {\n\tif block[itemHr].MatchString(l.input[l.pos:]) {\n\t\tmatch := block[itemHr].FindString(l.input[l.pos:])\n\t\tl.pos += Pos(len(match))\n\t\tl.emit(itemHr)\n\t\treturn lexAny\n\t}\n\treturn lexText\n}\n\n\/\/ lexGfmCode scans GFM code block.\nfunc lexGfmCode(l *lexer) stateFn {\n\tre := block[itemGfmCodeBlock]\n\tif re.MatchString(l.input[l.pos:]) {\n\t\tmatch := re.FindString(l.input[l.pos:])\n\t\tl.pos += Pos(len(match))\n\t\tl.emit(itemGfmCodeBlock)\n\t\treturn lexAny\n\t}\n\treturn lexText\n}\n\n\/\/ lexCode scans code block.\nfunc lexCode(l *lexer) stateFn {\n\tmatch := block[itemCodeBlock].FindString(l.input[l.pos:])\n\tl.pos += Pos(len(match))\n\tl.emit(itemCodeBlock)\n\treturn lexAny\n}\n\n\/\/ lexList scans ordered and unordered lists.\nfunc lexList(l *lexer) stateFn {\n\tif m := block[itemList].FindString(l.input[l.pos:]); m != \"\" {\n\t\tl.pos += Pos(len(m))\n\t\tl.emit(itemList)\n\t}\n\treturn lexText\n}\n\n\/\/ lexText scans until eol(\\n)\n\/\/ We have a lot of things to do in this lextext\n\/\/ for example: ignore itemBr on list\/tables\n\/\/ fix the text scaning etc...\nfunc lexText(l *lexer) stateFn {\n\t\/\/ Drain text before emitting\n\temit := func(item itemType, pos Pos) {\n\t\tif l.pos > l.start {\n\t\t\tl.emit(itemText)\n\t\t}\n\t\tl.pos += pos\n\t\tl.emit(item)\n\t}\nLoop:\n\tfor {\n\t\tswitch r := l.peek(); {\n\t\tcase r == eof:\n\t\t\temit(eof, Pos(0))\n\t\t\tbreak Loop\n\t\tcase r == '\\n':\n\t\t\temit(itemNewLine, l.width)\n\t\t\tbreak Loop\n\t\tcase r == ' ':\n\t\t\tif m := span[itemBr].FindString(l.input[l.pos:]); m != \"\" {\n\t\t\t\t\/\/ pos - length of new-line\n\t\t\t\temit(itemBr, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl.next()\n\t\t\/\/ if it's start as an emphasis\n\t\tcase r == '_', r == '*', r == '~', r == '`':\n\t\t\tinput := l.input[l.pos:]\n\t\t\t\/\/ Strong\n\t\t\tif m := span[itemStrong].FindString(input); m != \"\" {\n\t\t\t\temit(itemStrong, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t\/\/ Italic\n\t\t\tif m := span[itemItalic].FindString(input); m != \"\" {\n\t\t\t\temit(itemItalic, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t\/\/ Strike\n\t\t\tif m := span[itemStrike].FindString(input); m != \"\" {\n\t\t\t\temit(itemStrike, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t\/\/ InlineCode\n\t\t\tif m := span[itemCode].FindString(input); m != \"\" {\n\t\t\t\temit(itemCode, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl.next()\n\t\t\/\/ itemLink, itemAutoLink, itemImage\n\t\tcase r == '[', r == '<', r == '!':\n\t\t\tinput := l.input[l.pos:]\n\t\t\tif m := span[itemLink].FindString(input); m != \"\" {\n\t\t\t\tpos := Pos(len(m))\n\t\t\t\tif r == '[' {\n\t\t\t\t\temit(itemLink, pos)\n\t\t\t\t} else {\n\t\t\t\t\temit(itemImage, pos)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif m := span[itemAutoLink].FindString(input); m != \"\" {\n\t\t\t\temit(itemAutoLink, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl.next()\n\t\tcase r == '|':\n\t\t\tif l.eot > l.pos {\n\t\t\t\temit(itemPipe, l.width)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl.next()\n\t\tdefault:\n\t\t\tinput := l.input[l.pos:]\n\t\t\t\/\/ Test for Setext-style headers\n\t\t\tif m := block[itemLHeading].FindString(input); m != \"\" {\n\t\t\t\temit(itemLHeading, Pos(len(m)))\n\t\t\t\tbreak Loop\n\t\t\t}\n\t\t\t\/\/ GfmLink\n\t\t\tif m := span[itemGfmLink].FindString(input); m != \"\" {\n\t\t\t\temit(itemGfmLink, Pos(len(m)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tl.next()\n\t\t}\n\t}\n\treturn lexAny\n}\n\n\/\/ backup steps back one rune. Can only be called once per call of next.\nfunc (l *lexer) backup() {\n\tl.pos -= l.width\n}\n\n\/\/ peek returns but does not consume the next rune in the input.\nfunc (l *lexer) peek() rune {\n\tr := l.next()\n\tl.backup()\n\treturn r\n}\n\n\/\/ emit passes an item back to the client.\nfunc (l *lexer) emit(t itemType) {\n\tl.items <- item{t, l.start, l.input[l.start:l.pos]}\n\tl.start = l.pos\n}\n\n\/\/ lexItem return the next item token, clled by the parser.\nfunc (l *lexer) nextItem() item {\n\titem := <-l.items\n\tl.lastPos = l.pos\n\treturn item\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build linux\n\npackage lxc\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/docker\/docker\/daemon\/execdriver\"\n\tnativeTemplate \"github.com\/docker\/docker\/daemon\/execdriver\/native\/template\"\n\t\"github.com\/docker\/libcontainer\/configs\"\n\t\"github.com\/syndtr\/gocapability\/capability\"\n)\n\nfunc TestLXCConfig(t *testing.T) {\n\troot, err := ioutil.TempDir(\"\", \"TestLXCConfig\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(root)\n\n\tos.MkdirAll(path.Join(root, \"containers\", \"1\"), 0777)\n\n\t\/\/ Memory is allocated randomly for testing\n\trand.Seed(time.Now().UTC().UnixNano())\n\tvar (\n\t\tmemMin = 33554432\n\t\tmemMax = 536870912\n\t\tmem    = memMin + rand.Intn(memMax-memMin)\n\t\tcpuMin = 100\n\t\tcpuMax = 10000\n\t\tcpu    = cpuMin + rand.Intn(cpuMax-cpuMin)\n\t)\n\n\tdriver, err := NewDriver(root, root, \"\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcommand := &execdriver.Command{\n\t\tID: \"1\",\n\t\tResources: &execdriver.Resources{\n\t\t\tMemory:    int64(mem),\n\t\t\tCpuShares: int64(cpu),\n\t\t},\n\t\tNetwork: &execdriver.Network{\n\t\t\tMtu:       1500,\n\t\t\tInterface: nil,\n\t\t},\n\t\tAllowedDevices: make([]*configs.Device, 0),\n\t\tProcessConfig:  execdriver.ProcessConfig{},\n\t}\n\tp, err := driver.generateLXCConfig(command)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgrepFile(t, p,\n\t\tfmt.Sprintf(\"lxc.cgroup.memory.limit_in_bytes = %d\", mem))\n\n\tgrepFile(t, p,\n\t\tfmt.Sprintf(\"lxc.cgroup.memory.memsw.limit_in_bytes = %d\", mem*2))\n}\n\nfunc TestCustomLxcConfig(t *testing.T) {\n\troot, err := ioutil.TempDir(\"\", \"TestCustomLxcConfig\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(root)\n\n\tos.MkdirAll(path.Join(root, \"containers\", \"1\"), 0777)\n\n\tdriver, err := NewDriver(root, root, \"\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tprocessConfig := execdriver.ProcessConfig{\n\t\tPrivileged: false,\n\t}\n\tcommand := &execdriver.Command{\n\t\tID: \"1\",\n\t\tLxcConfig: []string{\n\t\t\t\"lxc.utsname = docker\",\n\t\t\t\"lxc.cgroup.cpuset.cpus = 0,1\",\n\t\t},\n\t\tNetwork: &execdriver.Network{\n\t\t\tMtu:       1500,\n\t\t\tInterface: nil,\n\t\t},\n\t\tProcessConfig: processConfig,\n\t}\n\n\tp, err := driver.generateLXCConfig(command)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tgrepFile(t, p, \"lxc.utsname = docker\")\n\tgrepFile(t, p, \"lxc.cgroup.cpuset.cpus = 0,1\")\n}\n\nfunc grepFile(t *testing.T, path string, pattern string) {\n\tgrepFileWithReverse(t, path, pattern, false)\n}\n\nfunc grepFileWithReverse(t *testing.T, path string, pattern string, inverseGrep bool) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tvar (\n\t\tline string\n\t)\n\terr = nil\n\tfor err == nil {\n\t\tline, err = r.ReadString('\\n')\n\t\tif strings.Contains(line, pattern) == true {\n\t\t\tif inverseGrep {\n\t\t\t\tt.Fatalf(\"grepFile: pattern \\\"%s\\\" found in \\\"%s\\\"\", pattern, path)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\tif inverseGrep {\n\t\treturn\n\t}\n\tt.Fatalf(\"grepFile: pattern \\\"%s\\\" not found in \\\"%s\\\"\", pattern, path)\n}\n\nfunc TestEscapeFstabSpaces(t *testing.T) {\n\tvar testInputs = map[string]string{\n\t\t\" \":                      \"\\\\040\",\n\t\t\"\":                       \"\",\n\t\t\"\/double  space\":         \"\/double\\\\040\\\\040space\",\n\t\t\"\/some long test string\": \"\/some\\\\040long\\\\040test\\\\040string\",\n\t\t\"\/var\/lib\/docker\":        \"\/var\/lib\/docker\",\n\t\t\" leading\":               \"\\\\040leading\",\n\t\t\"trailing \":              \"trailing\\\\040\",\n\t}\n\tfor in, exp := range testInputs {\n\t\tif out := escapeFstabSpaces(in); exp != out {\n\t\t\tt.Logf(\"Expected %s got %s\", exp, out)\n\t\t\tt.Fail()\n\t\t}\n\t}\n}\n\nfunc TestIsDirectory(t *testing.T) {\n\ttempDir, err := ioutil.TempDir(\"\", \"TestIsDir\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tempDir)\n\n\ttempFile, err := ioutil.TempFile(tempDir, \"TestIsDirFile\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif isDirectory(tempDir) != \"dir\" {\n\t\tt.Logf(\"Could not identify %s as a directory\", tempDir)\n\t\tt.Fail()\n\t}\n\n\tif isDirectory(tempFile.Name()) != \"file\" {\n\t\tt.Logf(\"Could not identify %s as a file\", tempFile.Name())\n\t\tt.Fail()\n\t}\n}\n\nfunc TestCustomLxcConfigMounts(t *testing.T) {\n\troot, err := ioutil.TempDir(\"\", \"TestCustomLxcConfig\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(root)\n\ttempDir, err := ioutil.TempDir(\"\", \"TestIsDir\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tempDir)\n\n\ttempFile, err := ioutil.TempFile(tempDir, \"TestIsDirFile\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tos.MkdirAll(path.Join(root, \"containers\", \"1\"), 0777)\n\n\tdriver, err := NewDriver(root, root, \"\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tprocessConfig := execdriver.ProcessConfig{\n\t\tPrivileged: false,\n\t}\n\tmounts := []execdriver.Mount{\n\t\t{\n\t\t\tSource:      tempDir,\n\t\t\tDestination: tempDir,\n\t\t\tWritable:    false,\n\t\t\tPrivate:     true,\n\t\t},\n\t\t{\n\t\t\tSource:      tempFile.Name(),\n\t\t\tDestination: tempFile.Name(),\n\t\t\tWritable:    true,\n\t\t\tPrivate:     true,\n\t\t},\n\t}\n\tcommand := &execdriver.Command{\n\t\tID: \"1\",\n\t\tLxcConfig: []string{\n\t\t\t\"lxc.utsname = docker\",\n\t\t\t\"lxc.cgroup.cpuset.cpus = 0,1\",\n\t\t},\n\t\tNetwork: &execdriver.Network{\n\t\t\tMtu:       1500,\n\t\t\tInterface: nil,\n\t\t},\n\t\tMounts:        mounts,\n\t\tProcessConfig: processConfig,\n\t}\n\n\tp, err := driver.generateLXCConfig(command)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tgrepFile(t, p, \"lxc.utsname = docker\")\n\tgrepFile(t, p, \"lxc.cgroup.cpuset.cpus = 0,1\")\n\n\tgrepFile(t, p, fmt.Sprintf(\"lxc.mount.entry = %s %s none rbind,ro,create=%s 0 0\", tempDir, \"\/\"+tempDir, \"dir\"))\n\tgrepFile(t, p, fmt.Sprintf(\"lxc.mount.entry = %s %s none rbind,rw,create=%s 0 0\", tempFile.Name(), \"\/\"+tempFile.Name(), \"file\"))\n}\n\nfunc TestCustomLxcConfigMisc(t *testing.T) {\n\troot, err := ioutil.TempDir(\"\", \"TestCustomLxcConfig\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(root)\n\tos.MkdirAll(path.Join(root, \"containers\", \"1\"), 0777)\n\tdriver, err := NewDriver(root, root, \"\", true)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tprocessConfig := execdriver.ProcessConfig{\n\t\tPrivileged: false,\n\t}\n\n\tprocessConfig.Env = []string{\"HOSTNAME=testhost\"}\n\tcommand := &execdriver.Command{\n\t\tID: \"1\",\n\t\tLxcConfig: []string{\n\t\t\t\"lxc.cgroup.cpuset.cpus = 0,1\",\n\t\t},\n\t\tNetwork: &execdriver.Network{\n\t\t\tMtu: 1500,\n\t\t\tInterface: &execdriver.NetworkInterface{\n\t\t\t\tGateway:     \"10.10.10.1\",\n\t\t\t\tIPAddress:   \"10.10.10.10\",\n\t\t\t\tIPPrefixLen: 24,\n\t\t\t\tBridge:      \"docker0\",\n\t\t\t},\n\t\t},\n\t\tProcessConfig:   processConfig,\n\t\tCapAdd:          []string{\"net_admin\", \"syslog\"},\n\t\tCapDrop:         []string{\"kill\", \"mknod\"},\n\t\tAppArmorProfile: \"lxc-container-default-with-nesting\",\n\t}\n\n\tp, err := driver.generateLXCConfig(command)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t\/\/ network\n\tgrepFile(t, p, \"lxc.network.type = veth\")\n\tgrepFile(t, p, \"lxc.network.link = docker0\")\n\tgrepFile(t, p, \"lxc.network.name = eth0\")\n\tgrepFile(t, p, \"lxc.network.ipv4 = 10.10.10.10\/24\")\n\tgrepFile(t, p, \"lxc.network.ipv4.gateway = 10.10.10.1\")\n\tgrepFile(t, p, \"lxc.network.flags = up\")\n\tgrepFile(t, p, \"lxc.aa_profile = lxc-container-default-with-nesting\")\n\t\/\/ hostname\n\tgrepFile(t, p, \"lxc.utsname = testhost\")\n\tgrepFile(t, p, \"lxc.cgroup.cpuset.cpus = 0,1\")\n\tcontainer := nativeTemplate.New()\n\tfor _, cap := range container.Capabilities {\n\t\trealCap := execdriver.GetCapability(cap)\n\t\tnumCap := fmt.Sprintf(\"%d\", realCap.Value)\n\t\tif cap != \"MKNOD\" && cap != \"KILL\" {\n\t\t\tgrepFile(t, p, fmt.Sprintf(\"lxc.cap.keep = %s\", numCap))\n\t\t}\n\t}\n\n\tgrepFileWithReverse(t, p, fmt.Sprintf(\"lxc.cap.keep = %d\", capability.CAP_KILL), true)\n\tgrepFileWithReverse(t, p, fmt.Sprintf(\"lxc.cap.keep = %d\", capability.CAP_MKNOD), true)\n}\n\nfunc TestCustomLxcConfigMiscOverride(t *testing.T) {\n\troot, err := ioutil.TempDir(\"\", \"TestCustomLxcConfig\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(root)\n\tos.MkdirAll(path.Join(root, \"containers\", \"1\"), 0777)\n\tdriver, err := NewDriver(root, root, \"\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tprocessConfig := execdriver.ProcessConfig{\n\t\tPrivileged: false,\n\t}\n\n\tprocessConfig.Env = []string{\"HOSTNAME=testhost\"}\n\tcommand := &execdriver.Command{\n\t\tID: \"1\",\n\t\tLxcConfig: []string{\n\t\t\t\"lxc.cgroup.cpuset.cpus = 0,1\",\n\t\t\t\"lxc.network.ipv4 = 172.0.0.1\",\n\t\t},\n\t\tNetwork: &execdriver.Network{\n\t\t\tMtu: 1500,\n\t\t\tInterface: &execdriver.NetworkInterface{\n\t\t\t\tGateway:     \"10.10.10.1\",\n\t\t\t\tIPAddress:   \"10.10.10.10\",\n\t\t\t\tIPPrefixLen: 24,\n\t\t\t\tBridge:      \"docker0\",\n\t\t\t},\n\t\t},\n\t\tProcessConfig: processConfig,\n\t\tCapAdd:        []string{\"NET_ADMIN\", \"SYSLOG\"},\n\t\tCapDrop:       []string{\"KILL\", \"MKNOD\"},\n\t}\n\n\tp, err := driver.generateLXCConfig(command)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t\/\/ network\n\tgrepFile(t, p, \"lxc.network.type = veth\")\n\tgrepFile(t, p, \"lxc.network.link = docker0\")\n\tgrepFile(t, p, \"lxc.network.name = eth0\")\n\tgrepFile(t, p, \"lxc.network.ipv4 = 172.0.0.1\")\n\tgrepFile(t, p, \"lxc.network.ipv4.gateway = 10.10.10.1\")\n\tgrepFile(t, p, \"lxc.network.flags = up\")\n\n\t\/\/ hostname\n\tgrepFile(t, p, \"lxc.utsname = testhost\")\n\tgrepFile(t, p, \"lxc.cgroup.cpuset.cpus = 0,1\")\n\tcontainer := nativeTemplate.New()\n\tfor _, cap := range container.Capabilities {\n\t\trealCap := execdriver.GetCapability(cap)\n\t\tnumCap := fmt.Sprintf(\"%d\", realCap.Value)\n\t\tif cap != \"MKNOD\" && cap != \"KILL\" {\n\t\t\tgrepFile(t, p, fmt.Sprintf(\"lxc.cap.keep = %s\", numCap))\n\t\t}\n\t}\n\tgrepFileWithReverse(t, p, fmt.Sprintf(\"lxc.cap.keep = %d\", capability.CAP_KILL), true)\n\tgrepFileWithReverse(t, p, fmt.Sprintf(\"lxc.cap.keep = %d\", capability.CAP_MKNOD), true)\n}\n<commit_msg>execdriver\/lxc: use local rand.Random in test<commit_after>\/\/ +build linux\n\npackage lxc\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/docker\/docker\/daemon\/execdriver\"\n\tnativeTemplate \"github.com\/docker\/docker\/daemon\/execdriver\/native\/template\"\n\t\"github.com\/docker\/libcontainer\/configs\"\n\t\"github.com\/syndtr\/gocapability\/capability\"\n)\n\nfunc TestLXCConfig(t *testing.T) {\n\troot, err := ioutil.TempDir(\"\", \"TestLXCConfig\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(root)\n\n\tos.MkdirAll(path.Join(root, \"containers\", \"1\"), 0777)\n\n\t\/\/ Memory is allocated randomly for testing\n\tr := rand.New(rand.NewSource(time.Now().UTC().UnixNano()))\n\tvar (\n\t\tmemMin = 33554432\n\t\tmemMax = 536870912\n\t\tmem    = memMin + r.Intn(memMax-memMin)\n\t\tcpuMin = 100\n\t\tcpuMax = 10000\n\t\tcpu    = cpuMin + r.Intn(cpuMax-cpuMin)\n\t)\n\n\tdriver, err := NewDriver(root, root, \"\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tcommand := &execdriver.Command{\n\t\tID: \"1\",\n\t\tResources: &execdriver.Resources{\n\t\t\tMemory:    int64(mem),\n\t\t\tCpuShares: int64(cpu),\n\t\t},\n\t\tNetwork: &execdriver.Network{\n\t\t\tMtu:       1500,\n\t\t\tInterface: nil,\n\t\t},\n\t\tAllowedDevices: make([]*configs.Device, 0),\n\t\tProcessConfig:  execdriver.ProcessConfig{},\n\t}\n\tp, err := driver.generateLXCConfig(command)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgrepFile(t, p,\n\t\tfmt.Sprintf(\"lxc.cgroup.memory.limit_in_bytes = %d\", mem))\n\n\tgrepFile(t, p,\n\t\tfmt.Sprintf(\"lxc.cgroup.memory.memsw.limit_in_bytes = %d\", mem*2))\n}\n\nfunc TestCustomLxcConfig(t *testing.T) {\n\troot, err := ioutil.TempDir(\"\", \"TestCustomLxcConfig\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(root)\n\n\tos.MkdirAll(path.Join(root, \"containers\", \"1\"), 0777)\n\n\tdriver, err := NewDriver(root, root, \"\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tprocessConfig := execdriver.ProcessConfig{\n\t\tPrivileged: false,\n\t}\n\tcommand := &execdriver.Command{\n\t\tID: \"1\",\n\t\tLxcConfig: []string{\n\t\t\t\"lxc.utsname = docker\",\n\t\t\t\"lxc.cgroup.cpuset.cpus = 0,1\",\n\t\t},\n\t\tNetwork: &execdriver.Network{\n\t\t\tMtu:       1500,\n\t\t\tInterface: nil,\n\t\t},\n\t\tProcessConfig: processConfig,\n\t}\n\n\tp, err := driver.generateLXCConfig(command)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tgrepFile(t, p, \"lxc.utsname = docker\")\n\tgrepFile(t, p, \"lxc.cgroup.cpuset.cpus = 0,1\")\n}\n\nfunc grepFile(t *testing.T, path string, pattern string) {\n\tgrepFileWithReverse(t, path, pattern, false)\n}\n\nfunc grepFileWithReverse(t *testing.T, path string, pattern string, inverseGrep bool) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer f.Close()\n\tr := bufio.NewReader(f)\n\tvar (\n\t\tline string\n\t)\n\terr = nil\n\tfor err == nil {\n\t\tline, err = r.ReadString('\\n')\n\t\tif strings.Contains(line, pattern) == true {\n\t\t\tif inverseGrep {\n\t\t\t\tt.Fatalf(\"grepFile: pattern \\\"%s\\\" found in \\\"%s\\\"\", pattern, path)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n\tif inverseGrep {\n\t\treturn\n\t}\n\tt.Fatalf(\"grepFile: pattern \\\"%s\\\" not found in \\\"%s\\\"\", pattern, path)\n}\n\nfunc TestEscapeFstabSpaces(t *testing.T) {\n\tvar testInputs = map[string]string{\n\t\t\" \":                      \"\\\\040\",\n\t\t\"\":                       \"\",\n\t\t\"\/double  space\":         \"\/double\\\\040\\\\040space\",\n\t\t\"\/some long test string\": \"\/some\\\\040long\\\\040test\\\\040string\",\n\t\t\"\/var\/lib\/docker\":        \"\/var\/lib\/docker\",\n\t\t\" leading\":               \"\\\\040leading\",\n\t\t\"trailing \":              \"trailing\\\\040\",\n\t}\n\tfor in, exp := range testInputs {\n\t\tif out := escapeFstabSpaces(in); exp != out {\n\t\t\tt.Logf(\"Expected %s got %s\", exp, out)\n\t\t\tt.Fail()\n\t\t}\n\t}\n}\n\nfunc TestIsDirectory(t *testing.T) {\n\ttempDir, err := ioutil.TempDir(\"\", \"TestIsDir\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tempDir)\n\n\ttempFile, err := ioutil.TempFile(tempDir, \"TestIsDirFile\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif isDirectory(tempDir) != \"dir\" {\n\t\tt.Logf(\"Could not identify %s as a directory\", tempDir)\n\t\tt.Fail()\n\t}\n\n\tif isDirectory(tempFile.Name()) != \"file\" {\n\t\tt.Logf(\"Could not identify %s as a file\", tempFile.Name())\n\t\tt.Fail()\n\t}\n}\n\nfunc TestCustomLxcConfigMounts(t *testing.T) {\n\troot, err := ioutil.TempDir(\"\", \"TestCustomLxcConfig\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(root)\n\ttempDir, err := ioutil.TempDir(\"\", \"TestIsDir\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tempDir)\n\n\ttempFile, err := ioutil.TempFile(tempDir, \"TestIsDirFile\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tos.MkdirAll(path.Join(root, \"containers\", \"1\"), 0777)\n\n\tdriver, err := NewDriver(root, root, \"\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tprocessConfig := execdriver.ProcessConfig{\n\t\tPrivileged: false,\n\t}\n\tmounts := []execdriver.Mount{\n\t\t{\n\t\t\tSource:      tempDir,\n\t\t\tDestination: tempDir,\n\t\t\tWritable:    false,\n\t\t\tPrivate:     true,\n\t\t},\n\t\t{\n\t\t\tSource:      tempFile.Name(),\n\t\t\tDestination: tempFile.Name(),\n\t\t\tWritable:    true,\n\t\t\tPrivate:     true,\n\t\t},\n\t}\n\tcommand := &execdriver.Command{\n\t\tID: \"1\",\n\t\tLxcConfig: []string{\n\t\t\t\"lxc.utsname = docker\",\n\t\t\t\"lxc.cgroup.cpuset.cpus = 0,1\",\n\t\t},\n\t\tNetwork: &execdriver.Network{\n\t\t\tMtu:       1500,\n\t\t\tInterface: nil,\n\t\t},\n\t\tMounts:        mounts,\n\t\tProcessConfig: processConfig,\n\t}\n\n\tp, err := driver.generateLXCConfig(command)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tgrepFile(t, p, \"lxc.utsname = docker\")\n\tgrepFile(t, p, \"lxc.cgroup.cpuset.cpus = 0,1\")\n\n\tgrepFile(t, p, fmt.Sprintf(\"lxc.mount.entry = %s %s none rbind,ro,create=%s 0 0\", tempDir, \"\/\"+tempDir, \"dir\"))\n\tgrepFile(t, p, fmt.Sprintf(\"lxc.mount.entry = %s %s none rbind,rw,create=%s 0 0\", tempFile.Name(), \"\/\"+tempFile.Name(), \"file\"))\n}\n\nfunc TestCustomLxcConfigMisc(t *testing.T) {\n\troot, err := ioutil.TempDir(\"\", \"TestCustomLxcConfig\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(root)\n\tos.MkdirAll(path.Join(root, \"containers\", \"1\"), 0777)\n\tdriver, err := NewDriver(root, root, \"\", true)\n\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tprocessConfig := execdriver.ProcessConfig{\n\t\tPrivileged: false,\n\t}\n\n\tprocessConfig.Env = []string{\"HOSTNAME=testhost\"}\n\tcommand := &execdriver.Command{\n\t\tID: \"1\",\n\t\tLxcConfig: []string{\n\t\t\t\"lxc.cgroup.cpuset.cpus = 0,1\",\n\t\t},\n\t\tNetwork: &execdriver.Network{\n\t\t\tMtu: 1500,\n\t\t\tInterface: &execdriver.NetworkInterface{\n\t\t\t\tGateway:     \"10.10.10.1\",\n\t\t\t\tIPAddress:   \"10.10.10.10\",\n\t\t\t\tIPPrefixLen: 24,\n\t\t\t\tBridge:      \"docker0\",\n\t\t\t},\n\t\t},\n\t\tProcessConfig:   processConfig,\n\t\tCapAdd:          []string{\"net_admin\", \"syslog\"},\n\t\tCapDrop:         []string{\"kill\", \"mknod\"},\n\t\tAppArmorProfile: \"lxc-container-default-with-nesting\",\n\t}\n\n\tp, err := driver.generateLXCConfig(command)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t\/\/ network\n\tgrepFile(t, p, \"lxc.network.type = veth\")\n\tgrepFile(t, p, \"lxc.network.link = docker0\")\n\tgrepFile(t, p, \"lxc.network.name = eth0\")\n\tgrepFile(t, p, \"lxc.network.ipv4 = 10.10.10.10\/24\")\n\tgrepFile(t, p, \"lxc.network.ipv4.gateway = 10.10.10.1\")\n\tgrepFile(t, p, \"lxc.network.flags = up\")\n\tgrepFile(t, p, \"lxc.aa_profile = lxc-container-default-with-nesting\")\n\t\/\/ hostname\n\tgrepFile(t, p, \"lxc.utsname = testhost\")\n\tgrepFile(t, p, \"lxc.cgroup.cpuset.cpus = 0,1\")\n\tcontainer := nativeTemplate.New()\n\tfor _, cap := range container.Capabilities {\n\t\trealCap := execdriver.GetCapability(cap)\n\t\tnumCap := fmt.Sprintf(\"%d\", realCap.Value)\n\t\tif cap != \"MKNOD\" && cap != \"KILL\" {\n\t\t\tgrepFile(t, p, fmt.Sprintf(\"lxc.cap.keep = %s\", numCap))\n\t\t}\n\t}\n\n\tgrepFileWithReverse(t, p, fmt.Sprintf(\"lxc.cap.keep = %d\", capability.CAP_KILL), true)\n\tgrepFileWithReverse(t, p, fmt.Sprintf(\"lxc.cap.keep = %d\", capability.CAP_MKNOD), true)\n}\n\nfunc TestCustomLxcConfigMiscOverride(t *testing.T) {\n\troot, err := ioutil.TempDir(\"\", \"TestCustomLxcConfig\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(root)\n\tos.MkdirAll(path.Join(root, \"containers\", \"1\"), 0777)\n\tdriver, err := NewDriver(root, root, \"\", false)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tprocessConfig := execdriver.ProcessConfig{\n\t\tPrivileged: false,\n\t}\n\n\tprocessConfig.Env = []string{\"HOSTNAME=testhost\"}\n\tcommand := &execdriver.Command{\n\t\tID: \"1\",\n\t\tLxcConfig: []string{\n\t\t\t\"lxc.cgroup.cpuset.cpus = 0,1\",\n\t\t\t\"lxc.network.ipv4 = 172.0.0.1\",\n\t\t},\n\t\tNetwork: &execdriver.Network{\n\t\t\tMtu: 1500,\n\t\t\tInterface: &execdriver.NetworkInterface{\n\t\t\t\tGateway:     \"10.10.10.1\",\n\t\t\t\tIPAddress:   \"10.10.10.10\",\n\t\t\t\tIPPrefixLen: 24,\n\t\t\t\tBridge:      \"docker0\",\n\t\t\t},\n\t\t},\n\t\tProcessConfig: processConfig,\n\t\tCapAdd:        []string{\"NET_ADMIN\", \"SYSLOG\"},\n\t\tCapDrop:       []string{\"KILL\", \"MKNOD\"},\n\t}\n\n\tp, err := driver.generateLXCConfig(command)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t\/\/ network\n\tgrepFile(t, p, \"lxc.network.type = veth\")\n\tgrepFile(t, p, \"lxc.network.link = docker0\")\n\tgrepFile(t, p, \"lxc.network.name = eth0\")\n\tgrepFile(t, p, \"lxc.network.ipv4 = 172.0.0.1\")\n\tgrepFile(t, p, \"lxc.network.ipv4.gateway = 10.10.10.1\")\n\tgrepFile(t, p, \"lxc.network.flags = up\")\n\n\t\/\/ hostname\n\tgrepFile(t, p, \"lxc.utsname = testhost\")\n\tgrepFile(t, p, \"lxc.cgroup.cpuset.cpus = 0,1\")\n\tcontainer := nativeTemplate.New()\n\tfor _, cap := range container.Capabilities {\n\t\trealCap := execdriver.GetCapability(cap)\n\t\tnumCap := fmt.Sprintf(\"%d\", realCap.Value)\n\t\tif cap != \"MKNOD\" && cap != \"KILL\" {\n\t\t\tgrepFile(t, p, fmt.Sprintf(\"lxc.cap.keep = %s\", numCap))\n\t\t}\n\t}\n\tgrepFileWithReverse(t, p, fmt.Sprintf(\"lxc.cap.keep = %d\", capability.CAP_KILL), true)\n\tgrepFileWithReverse(t, p, fmt.Sprintf(\"lxc.cap.keep = %d\", capability.CAP_MKNOD), true)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build linux\n\npackage overlayutils \/\/ import \"github.com\/docker\/docker\/daemon\/graphdriver\/overlayutils\"\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\n\t\"github.com\/docker\/docker\/daemon\/graphdriver\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"golang.org\/x\/sys\/unix\"\n)\n\n\/\/ ErrDTypeNotSupported denotes that the backing filesystem doesn't support d_type.\nfunc ErrDTypeNotSupported(driver, backingFs string) error {\n\tmsg := fmt.Sprintf(\"%s: the backing %s filesystem is formatted without d_type support, which leads to incorrect behavior.\", driver, backingFs)\n\tif backingFs == \"xfs\" {\n\t\tmsg += \" Reformat the filesystem with ftype=1 to enable d_type support.\"\n\t}\n\n\tif backingFs == \"extfs\" {\n\t\tmsg += \" Reformat the filesystem (or use tune2fs) with -O filetype flag to enable d_type support.\"\n\t}\n\n\tmsg += \" Backing filesystems without d_type support are not supported.\"\n\n\treturn graphdriver.NotSupportedError(msg)\n}\n\n\/\/ SupportsOverlay checks if the system supports overlay filesystem\n\/\/ by performing an actual overlay mount.\n\/\/\n\/\/ checkMultipleLowers parameter enables check for multiple lowerdirs,\n\/\/ which is required for the overlay2 driver.\nfunc SupportsOverlay(d string, checkMultipleLowers bool) error {\n\ttd, err := ioutil.TempDir(d, \"check-overlayfs-support\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err := os.RemoveAll(td); err != nil {\n\t\t\tlogrus.Warnf(\"Failed to remove check directory %v: %v\", td, err)\n\t\t}\n\t}()\n\n\tfor _, dir := range []string{\"lower1\", \"lower2\", \"upper\", \"work\", \"merged\"} {\n\t\tif err := os.Mkdir(filepath.Join(td, dir), 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tmnt := filepath.Join(td, \"merged\")\n\tlowerDir := path.Join(td, \"lower2\")\n\tif checkMultipleLowers {\n\t\tlowerDir += \":\" + path.Join(td, \"lower1\")\n\t}\n\topts := fmt.Sprintf(\"lowerdir=%s,upperdir=%s,workdir=%s\", lowerDir, path.Join(td, \"upper\"), path.Join(td, \"work\"))\n\tif err := unix.Mount(\"overlay\", mnt, \"overlay\", 0, opts); err != nil {\n\t\treturn errors.Wrap(err, \"failed to mount overlay\")\n\t}\n\tif err := unix.Unmount(mnt, 0); err != nil {\n\t\tlogrus.Warnf(\"Failed to unmount check directory %v: %v\", mnt, err)\n\t}\n\treturn nil\n}\n<commit_msg>rootless: disable overlay2 if running with SELinux<commit_after>\/\/ +build linux\n\npackage overlayutils \/\/ import \"github.com\/docker\/docker\/daemon\/graphdriver\/overlayutils\"\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"path\/filepath\"\n\n\t\"github.com\/docker\/docker\/daemon\/graphdriver\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"golang.org\/x\/sys\/unix\"\n)\n\n\/\/ ErrDTypeNotSupported denotes that the backing filesystem doesn't support d_type.\nfunc ErrDTypeNotSupported(driver, backingFs string) error {\n\tmsg := fmt.Sprintf(\"%s: the backing %s filesystem is formatted without d_type support, which leads to incorrect behavior.\", driver, backingFs)\n\tif backingFs == \"xfs\" {\n\t\tmsg += \" Reformat the filesystem with ftype=1 to enable d_type support.\"\n\t}\n\n\tif backingFs == \"extfs\" {\n\t\tmsg += \" Reformat the filesystem (or use tune2fs) with -O filetype flag to enable d_type support.\"\n\t}\n\n\tmsg += \" Backing filesystems without d_type support are not supported.\"\n\n\treturn graphdriver.NotSupportedError(msg)\n}\n\n\/\/ SupportsOverlay checks if the system supports overlay filesystem\n\/\/ by performing an actual overlay mount.\n\/\/\n\/\/ checkMultipleLowers parameter enables check for multiple lowerdirs,\n\/\/ which is required for the overlay2 driver.\nfunc SupportsOverlay(d string, checkMultipleLowers bool) error {\n\t\/\/ We can't rely on go-selinux.GetEnabled() to detect whether SELinux is enabled,\n\t\/\/ because RootlessKit doesn't mount \/sys\/fs\/selinux in the child: https:\/\/github.com\/rootless-containers\/rootlesskit\/issues\/94\n\t\/\/ So we check $_DOCKERD_ROOTLESS_SELINUX, which is set by dockerd-rootless.sh .\n\tif os.Getenv(\"_DOCKERD_ROOTLESS_SELINUX\") == \"1\" {\n\t\t\/\/ Kernel 5.11 introduced support for rootless overlayfs, but incompatible with SELinux,\n\t\t\/\/ so fallback to fuse-overlayfs.\n\t\t\/\/ https:\/\/github.com\/moby\/moby\/issues\/42333\n\t\treturn errors.New(\"overlay is not supported for Rootless with SELinux\")\n\t}\n\n\ttd, err := ioutil.TempDir(d, \"check-overlayfs-support\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err := os.RemoveAll(td); err != nil {\n\t\t\tlogrus.Warnf(\"Failed to remove check directory %v: %v\", td, err)\n\t\t}\n\t}()\n\n\tfor _, dir := range []string{\"lower1\", \"lower2\", \"upper\", \"work\", \"merged\"} {\n\t\tif err := os.Mkdir(filepath.Join(td, dir), 0755); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tmnt := filepath.Join(td, \"merged\")\n\tlowerDir := path.Join(td, \"lower2\")\n\tif checkMultipleLowers {\n\t\tlowerDir += \":\" + path.Join(td, \"lower1\")\n\t}\n\topts := fmt.Sprintf(\"lowerdir=%s,upperdir=%s,workdir=%s\", lowerDir, path.Join(td, \"upper\"), path.Join(td, \"work\"))\n\tif err := unix.Mount(\"overlay\", mnt, \"overlay\", 0, opts); err != nil {\n\t\treturn errors.Wrap(err, \"failed to mount overlay\")\n\t}\n\tif err := unix.Unmount(mnt, 0); err != nil {\n\t\tlogrus.Warnf(\"Failed to unmount check directory %v: %v\", mnt, err)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Davis Webb\n\/\/ Copyright 2015 Luke Shumaker\n\npackage backend_test\n\nimport (\n\t. \"periwinkle\/backend\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestNewUser(t *testing.T) {\n\tconf := CreateTempDB()\n\n\tuser := NewUser(conf.DB, \"JohnDoe\", \"password\", \"johndoe@purdue.edu\")\n\n\tswitch {\n\tcase !strings.EqualFold(user.ID, \"JohnDoe\"):\n\t\tt.Error(\"User ID was not properly set to.\")\n\tcase user.FullName != \"\":\n\t\tt.Error(\"User name was not properly set.\")\n\tcase user.Addresses[0].Address != \"johndoe@purdue.edu\":\n\t\tt.Error(\"User address was not preperly set.\")\n\t}\n\n\tconf.DB.Close()\n}\n\nfunc TestGetUserByID(t *testing.T) {\n\tconf := CreateTempDB()\n\n\tuser := NewUser(conf.DB, \"JohnDoe\", \"password\", \"johndoe@purdue.edu\")\n\n\to := GetUserByID(conf.DB, user.ID)\n\n\tswitch {\n\tcase o == nil:\n\t\tt.Error(\"GetUserByID() returned nil\")\n\tcase !strings.EqualFold(user.ID, o.ID):\n\t\tt.Error(\"GetUserByID() returned a user with a different ID\")\n\t}\n\n\tconf.DB.Close()\n}\n\nfunc TestNewUserAddress(t *testing.T) {\n\tconf := CreateTempDB()\n\n\tuser := NewUser(conf.DB, \"JohnDoe\", \"password\", \"johndoe@purdue.edu\")\n\n\tnewAddr := NewUserAddress(conf.DB, user.ID, \"email\", \"johndoe2@purdue.edu\", false)\n\n\tswitch {\n\tcase newAddr.Address != \"johndoe2@purdue.edu\":\n\t\tt.Error(\"Error adding new email to user in NewUserAddress()\")\n\tcase newAddr.Medium != \"email\":\n\t\tt.Error(\"Error assigning medium type in NewUserAddress()\")\n\t}\n\n\tnewAddr = NewUserAddress(conf.DB, user.ID, \"sms\", \"7655555555\", false)\n\n\tswitch {\n\tcase newAddr.Address != \"7655555555\":\n\t\tt.Error(\"Error adding new sms to user in NewUserAddress()\")\n\tcase newAddr.Medium != \"sms\":\n\t\tt.Error(\"Error assigning medium type in NewUserAddress()\")\n\t}\n\n\tconf.DB.Close()\n}\n\nfunc TestGetUserByAddress(t *testing.T) {\n\tconf := CreateTempDB()\n\n\tuser := NewUser(conf.DB, \"JohnDoe\", \"password\", \"johndoe@purdue.edu\")\n\n\to := GetUserByAddress(conf.DB, \"email\", user.Addresses[0].Address)\n\tif strings.Compare(user.ID, o.ID) != 0 {\n\t\tt.Error(\"Error in GetUserByAdress()\")\n\t}\n\n\tconf.DB.Close()\n}\n\n\/\/ func TestSetPassword(t *testing.T) {\n\/\/ \tt.Error(\"TODO\")\n\/\/ }\n\n\/\/ func TestCheckPassword(t *testing.T) {\n\/\/ \tt.Error(\"TODO\")\n\/\/ }\n\n\/\/ func TestGetAddressByUserAndMedium(t *testing.T) {\n\/\/ \taddr := GetAddressByUserAndMedium(conf.DB, user.ID, \"email\")\n\n\/\/ \tswitch {\n\/\/ \tcase addr == nil:\n\/\/ \t\tt.Error(\"GetAddressByUserAndMedium() returned nil\")\n\/\/ \tcase addr.Address != user.Addresses[0].Address:\n\/\/ \t\tt.Error(\"Addresses do not match: \" + user.Addresses[0].Address + \" != \" + addr.Address)\n\/\/ \t}\n\/\/ \tconf.DB.Close()\n\/\/ }\n\nfunc TestGetUserSubscriptions(t *testing.T) {\n\n\tconf := CreateTempDB()\n\n\twaste := NewUser(conf.DB, \"JohnDoe\", \"password\", \"johndoe@purdue.edu\")\n\n\tuser := GetUserByID(conf.DB, waste.ID)\n\n\tsubs := user.GetUserSubscriptions(conf.DB)\n\n\tif subs == nil {\n\t\tt.Error(\"GetUserSubscriptions returned nil\")\n\t}\n}\n<commit_msg>Minor fix<commit_after>\/\/ Copyright 2015 Davis Webb\n\/\/ Copyright 2015 Luke Shumaker\n\npackage backend_test\n\nimport (\n\t. \"periwinkle\/backend\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestNewUser(t *testing.T) {\n\tconf := CreateTempDB()\n\n\tuser := NewUser(conf.DB, \"JohnDoe\", \"password\", \"johndoe@purdue.edu\")\n\n\tswitch {\n\tcase !strings.EqualFold(user.ID, \"JohnDoe\"):\n\t\tt.Error(\"User ID was not properly set to.\")\n\tcase user.FullName != \"\":\n\t\tt.Error(\"User name was not properly set.\")\n\tcase user.Addresses[0].Address != \"johndoe@purdue.edu\":\n\t\tt.Error(\"User address was not preperly set.\")\n\t}\n\n\tconf.DB.Close()\n}\n\nfunc TestGetUserByID(t *testing.T) {\n\tconf := CreateTempDB()\n\n\tuser := NewUser(conf.DB, \"JohnDoe\", \"password\", \"johndoe@purdue.edu\")\n\n\to := GetUserByID(conf.DB, user.ID)\n\n\tswitch {\n\tcase o == nil:\n\t\tt.Error(\"GetUserByID() returned nil\")\n\tcase !strings.EqualFold(user.ID, o.ID):\n\t\tt.Error(\"GetUserByID() returned a user with a different ID\")\n\t}\n\n\tconf.DB.Close()\n}\n\nfunc TestNewUserAddress(t *testing.T) {\n\tconf := CreateTempDB()\n\n\tuser := NewUser(conf.DB, \"JohnDoe\", \"password\", \"johndoe@purdue.edu\")\n\n\tnewAddr := NewUserAddress(conf.DB, user.ID, \"email\", \"johndoe2@purdue.edu\", false)\n\n\tswitch {\n\tcase newAddr.Address != \"johndoe2@purdue.edu\":\n\t\tt.Error(\"Error adding new email to user in NewUserAddress()\")\n\tcase newAddr.Medium != \"email\":\n\t\tt.Error(\"Error assigning medium type in NewUserAddress()\")\n\t}\n\n\tnewAddr = NewUserAddress(conf.DB, user.ID, \"sms\", \"7655555555\", false)\n\n\tswitch {\n\tcase newAddr.Address != \"7655555555\":\n\t\tt.Error(\"Error adding new sms to user in NewUserAddress()\")\n\tcase newAddr.Medium != \"sms\":\n\t\tt.Error(\"Error assigning medium type in NewUserAddress()\")\n\t}\n\n\tconf.DB.Close()\n}\n\nfunc TestGetUserByAddress(t *testing.T) {\n\tconf := CreateTempDB()\n\n\tuser := NewUser(conf.DB, \"JohnDoe\", \"password\", \"johndoe@purdue.edu\")\n\n\to := GetUserByAddress(conf.DB, \"email\", user.Addresses[0].Address)\n\tif !strings.EqualFold(user.ID, o.ID) {\n\t\tt.Error(\"Error in GetUserByAdress()\")\n\t}\n\n\tconf.DB.Close()\n}\n\n\/\/ func TestSetPassword(t *testing.T) {\n\/\/ \tt.Error(\"TODO\")\n\/\/ }\n\n\/\/ func TestCheckPassword(t *testing.T) {\n\/\/ \tt.Error(\"TODO\")\n\/\/ }\n\n\/\/ func TestGetAddressByUserAndMedium(t *testing.T) {\n\/\/ \taddr := GetAddressByUserAndMedium(conf.DB, user.ID, \"email\")\n\n\/\/ \tswitch {\n\/\/ \tcase addr == nil:\n\/\/ \t\tt.Error(\"GetAddressByUserAndMedium() returned nil\")\n\/\/ \tcase addr.Address != user.Addresses[0].Address:\n\/\/ \t\tt.Error(\"Addresses do not match: \" + user.Addresses[0].Address + \" != \" + addr.Address)\n\/\/ \t}\n\/\/ \tconf.DB.Close()\n\/\/ }\n\nfunc TestGetUserSubscriptions(t *testing.T) {\n\n\tconf := CreateTempDB()\n\n\twaste := NewUser(conf.DB, \"JohnDoe\", \"password\", \"johndoe@purdue.edu\")\n\n\tuser := GetUserByID(conf.DB, waste.ID)\n\n\tsubs := user.GetUserSubscriptions(conf.DB)\n\n\tif subs == nil {\n\t\tt.Error(\"GetUserSubscriptions returned nil\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage gosym\n\nimport (\n\t\"debug\/elf\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\nvar pclinetestBinary string\n\nfunc dotest() bool {\n\t\/\/ For now, only works on ELF platforms.\n\tif runtime.GOOS != \"linux\" || runtime.GOARCH != \"amd64\" {\n\t\treturn false\n\t}\n\tif pclinetestBinary != \"\" {\n\t\treturn true\n\t}\n\t\/\/ This command builds pclinetest from pclinetest.asm;\n\t\/\/ the resulting binary looks like it was built from pclinetest.s,\n\t\/\/ but we have renamed it to keep it away from the go tool.\n\tpclinetestBinary = os.TempDir() + \"\/pclinetest\"\n\tcmd := exec.Command(\"sh\", \"-c\", \"go tool 6a pclinetest.asm && go tool 6l -E main -o \"+pclinetestBinary+\" pclinetest.6\")\n\tif err := cmd.Run(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn true\n}\n\nfunc getTable(t *testing.T) *Table {\n\tf, tab := crack(os.Args[0], t)\n\tf.Close()\n\treturn tab\n}\n\nfunc crack(file string, t *testing.T) (*elf.File, *Table) {\n\t\/\/ Open self\n\tf, err := elf.Open(file)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn parse(file, f, t)\n}\n\nfunc parse(file string, f *elf.File, t *testing.T) (*elf.File, *Table) {\n\tsymdat, err := f.Section(\".gosymtab\").Data()\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"reading %s gosymtab: %v\", file, err)\n\t}\n\tpclndat, err := f.Section(\".gopclntab\").Data()\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"reading %s gopclntab: %v\", file, err)\n\t}\n\n\tpcln := NewLineTable(pclndat, f.Section(\".text\").Addr)\n\ttab, err := NewTable(symdat, pcln)\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"parsing %s gosymtab: %v\", file, err)\n\t}\n\n\treturn f, tab\n}\n\nvar goarch = os.Getenv(\"O\")\n\nfunc TestLineFromAline(t *testing.T) {\n\tif !dotest() {\n\t\treturn\n\t}\n\n\ttab := getTable(t)\n\n\t\/\/ Find the sym package\n\tpkg := tab.LookupFunc(\"debug\/gosym.TestLineFromAline\").Obj\n\tif pkg == nil {\n\t\tt.Fatalf(\"nil pkg\")\n\t}\n\n\t\/\/ Walk every absolute line and ensure that we hit every\n\t\/\/ source line monotonically\n\tlastline := make(map[string]int)\n\tfinal := -1\n\tfor i := 0; i < 10000; i++ {\n\t\tpath, line := pkg.lineFromAline(i)\n\t\t\/\/ Check for end of object\n\t\tif path == \"\" {\n\t\t\tif final == -1 {\n\t\t\t\tfinal = i - 1\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if final != -1 {\n\t\t\tt.Fatalf(\"reached end of package at absolute line %d, but absolute line %d mapped to %s:%d\", final, i, path, line)\n\t\t}\n\t\t\/\/ It's okay to see files multiple times (e.g., sys.a)\n\t\tif line == 1 {\n\t\t\tlastline[path] = 1\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Check that the is the next line in path\n\t\tll, ok := lastline[path]\n\t\tif !ok {\n\t\t\tt.Errorf(\"file %s starts on line %d\", path, line)\n\t\t} else if line != ll+1 {\n\t\t\tt.Errorf(\"expected next line of file %s to be %d, got %d\", path, ll+1, line)\n\t\t}\n\t\tlastline[path] = line\n\t}\n\tif final == -1 {\n\t\tt.Errorf(\"never reached end of object\")\n\t}\n}\n\nfunc TestLineAline(t *testing.T) {\n\tif !dotest() {\n\t\treturn\n\t}\n\n\ttab := getTable(t)\n\n\tfor _, o := range tab.Files {\n\t\t\/\/ A source file can appear multiple times in a\n\t\t\/\/ object.  alineFromLine will always return alines in\n\t\t\/\/ the first file, so track which lines we've seen.\n\t\tfound := make(map[string]int)\n\t\tfor i := 0; i < 1000; i++ {\n\t\t\tpath, line := o.lineFromAline(i)\n\t\t\tif path == \"\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ cgo files are full of 'Z' symbols, which we don't handle\n\t\t\tif len(path) > 4 && path[len(path)-4:] == \".cgo\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif minline, ok := found[path]; path != \"\" && ok {\n\t\t\t\tif minline >= line {\n\t\t\t\t\t\/\/ We've already covered this file\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tfound[path] = line\n\n\t\t\ta, err := o.alineFromLine(path, line)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"absolute line %d in object %s maps to %s:%d, but mapping that back gives error %s\", i, o.Paths[0].Name, path, line, err)\n\t\t\t} else if a != i {\n\t\t\t\tt.Errorf(\"absolute line %d in object %s maps to %s:%d, which maps back to absolute line %d\\n\", i, o.Paths[0].Name, path, line, a)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestPCLine(t *testing.T) {\n\tif !dotest() {\n\t\treturn\n\t}\n\n\tf, tab := crack(pclinetestBinary, t)\n\ttext := f.Section(\".text\")\n\ttextdat, err := text.Data()\n\tif err != nil {\n\t\tt.Fatalf(\"reading .text: %v\", err)\n\t}\n\n\t\/\/ Test PCToLine\n\tsym := tab.LookupFunc(\"linefrompc\")\n\twantLine := 0\n\tfor pc := sym.Entry; pc < sym.End; pc++ {\n\t\tfile, line, fn := tab.PCToLine(pc)\n\t\toff := pc - text.Addr \/\/ TODO(rsc): should not need off; bug in 8g\n\t\twantLine += int(textdat[off])\n\t\tt.Logf(\"off is %d\", off)\n\t\tif fn == nil {\n\t\t\tt.Errorf(\"failed to get line of PC %#x\", pc)\n\t\t} else if !strings.HasSuffix(file, \"pclinetest.s\") {\n\t\t\tt.Errorf(\"expected %s (%s) at PC %#x, got %s (%s)\", \"pclinetest.s\", sym.Name, pc, file, fn.Name)\n\t\t} else if line != wantLine || fn != sym {\n\t\t\tt.Errorf(\"expected :%d (%s) at PC %#x, got :%d (%s)\", wantLine, sym.Name, pc, line, fn.Name)\n\t\t}\n\t}\n\n\t\/\/ Test LineToPC\n\tsym = tab.LookupFunc(\"pcfromline\")\n\tlookupline := -1\n\twantLine = 0\n\toff := uint64(0) \/\/ TODO(rsc): should not need off; bug in 8g\n\tfor pc := sym.Value; pc < sym.End; pc += 2 + uint64(textdat[off]) {\n\t\tfile, line, fn := tab.PCToLine(pc)\n\t\toff = pc - text.Addr\n\t\twantLine += int(textdat[off])\n\t\tif line != wantLine {\n\t\t\tt.Errorf(\"expected line %d at PC %#x in pcfromline, got %d\", wantLine, pc, line)\n\t\t\toff = pc + 1 - text.Addr\n\t\t\tcontinue\n\t\t}\n\t\tif lookupline == -1 {\n\t\t\tlookupline = line\n\t\t}\n\t\tfor ; lookupline <= line; lookupline++ {\n\t\t\tpc2, fn2, err := tab.LineToPC(file, lookupline)\n\t\t\tif lookupline != line {\n\t\t\t\t\/\/ Should be nothing on this line\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(\"expected no PC at line %d, got %#x (%s)\", lookupline, pc2, fn2.Name)\n\t\t\t\t}\n\t\t\t} else if err != nil {\n\t\t\t\tt.Errorf(\"failed to get PC of line %d: %s\", lookupline, err)\n\t\t\t} else if pc != pc2 {\n\t\t\t\tt.Errorf(\"expected PC %#x (%s) at line %d, got PC %#x (%s)\", pc, fn.Name, line, pc2, fn2.Name)\n\t\t\t}\n\t\t}\n\t\toff = pc + 1 - text.Addr\n\t}\n}\n<commit_msg>debug\/gosym: dump 6a\/6l output to process stdout\/stderr so we can see failures.<commit_after>\/\/ Copyright 2009 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage gosym\n\nimport (\n\t\"debug\/elf\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\nvar pclinetestBinary string\n\nfunc dotest() bool {\n\t\/\/ For now, only works on ELF platforms.\n\tif runtime.GOOS != \"linux\" || runtime.GOARCH != \"amd64\" {\n\t\treturn false\n\t}\n\tif pclinetestBinary != \"\" {\n\t\treturn true\n\t}\n\t\/\/ This command builds pclinetest from pclinetest.asm;\n\t\/\/ the resulting binary looks like it was built from pclinetest.s,\n\t\/\/ but we have renamed it to keep it away from the go tool.\n\tpclinetestBinary = os.TempDir() + \"\/pclinetest\"\n\tcmd := exec.Command(\"sh\", \"-c\", \"go tool 6a pclinetest.asm && go tool 6l -E main -o \"+pclinetestBinary+\" pclinetest.6\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn true\n}\n\nfunc getTable(t *testing.T) *Table {\n\tf, tab := crack(os.Args[0], t)\n\tf.Close()\n\treturn tab\n}\n\nfunc crack(file string, t *testing.T) (*elf.File, *Table) {\n\t\/\/ Open self\n\tf, err := elf.Open(file)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn parse(file, f, t)\n}\n\nfunc parse(file string, f *elf.File, t *testing.T) (*elf.File, *Table) {\n\tsymdat, err := f.Section(\".gosymtab\").Data()\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"reading %s gosymtab: %v\", file, err)\n\t}\n\tpclndat, err := f.Section(\".gopclntab\").Data()\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"reading %s gopclntab: %v\", file, err)\n\t}\n\n\tpcln := NewLineTable(pclndat, f.Section(\".text\").Addr)\n\ttab, err := NewTable(symdat, pcln)\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"parsing %s gosymtab: %v\", file, err)\n\t}\n\n\treturn f, tab\n}\n\nvar goarch = os.Getenv(\"O\")\n\nfunc TestLineFromAline(t *testing.T) {\n\tif !dotest() {\n\t\treturn\n\t}\n\n\ttab := getTable(t)\n\n\t\/\/ Find the sym package\n\tpkg := tab.LookupFunc(\"debug\/gosym.TestLineFromAline\").Obj\n\tif pkg == nil {\n\t\tt.Fatalf(\"nil pkg\")\n\t}\n\n\t\/\/ Walk every absolute line and ensure that we hit every\n\t\/\/ source line monotonically\n\tlastline := make(map[string]int)\n\tfinal := -1\n\tfor i := 0; i < 10000; i++ {\n\t\tpath, line := pkg.lineFromAline(i)\n\t\t\/\/ Check for end of object\n\t\tif path == \"\" {\n\t\t\tif final == -1 {\n\t\t\t\tfinal = i - 1\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if final != -1 {\n\t\t\tt.Fatalf(\"reached end of package at absolute line %d, but absolute line %d mapped to %s:%d\", final, i, path, line)\n\t\t}\n\t\t\/\/ It's okay to see files multiple times (e.g., sys.a)\n\t\tif line == 1 {\n\t\t\tlastline[path] = 1\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Check that the is the next line in path\n\t\tll, ok := lastline[path]\n\t\tif !ok {\n\t\t\tt.Errorf(\"file %s starts on line %d\", path, line)\n\t\t} else if line != ll+1 {\n\t\t\tt.Errorf(\"expected next line of file %s to be %d, got %d\", path, ll+1, line)\n\t\t}\n\t\tlastline[path] = line\n\t}\n\tif final == -1 {\n\t\tt.Errorf(\"never reached end of object\")\n\t}\n}\n\nfunc TestLineAline(t *testing.T) {\n\tif !dotest() {\n\t\treturn\n\t}\n\n\ttab := getTable(t)\n\n\tfor _, o := range tab.Files {\n\t\t\/\/ A source file can appear multiple times in a\n\t\t\/\/ object.  alineFromLine will always return alines in\n\t\t\/\/ the first file, so track which lines we've seen.\n\t\tfound := make(map[string]int)\n\t\tfor i := 0; i < 1000; i++ {\n\t\t\tpath, line := o.lineFromAline(i)\n\t\t\tif path == \"\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ cgo files are full of 'Z' symbols, which we don't handle\n\t\t\tif len(path) > 4 && path[len(path)-4:] == \".cgo\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif minline, ok := found[path]; path != \"\" && ok {\n\t\t\t\tif minline >= line {\n\t\t\t\t\t\/\/ We've already covered this file\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tfound[path] = line\n\n\t\t\ta, err := o.alineFromLine(path, line)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"absolute line %d in object %s maps to %s:%d, but mapping that back gives error %s\", i, o.Paths[0].Name, path, line, err)\n\t\t\t} else if a != i {\n\t\t\t\tt.Errorf(\"absolute line %d in object %s maps to %s:%d, which maps back to absolute line %d\\n\", i, o.Paths[0].Name, path, line, a)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestPCLine(t *testing.T) {\n\tif !dotest() {\n\t\treturn\n\t}\n\n\tf, tab := crack(pclinetestBinary, t)\n\ttext := f.Section(\".text\")\n\ttextdat, err := text.Data()\n\tif err != nil {\n\t\tt.Fatalf(\"reading .text: %v\", err)\n\t}\n\n\t\/\/ Test PCToLine\n\tsym := tab.LookupFunc(\"linefrompc\")\n\twantLine := 0\n\tfor pc := sym.Entry; pc < sym.End; pc++ {\n\t\tfile, line, fn := tab.PCToLine(pc)\n\t\toff := pc - text.Addr \/\/ TODO(rsc): should not need off; bug in 8g\n\t\twantLine += int(textdat[off])\n\t\tt.Logf(\"off is %d\", off)\n\t\tif fn == nil {\n\t\t\tt.Errorf(\"failed to get line of PC %#x\", pc)\n\t\t} else if !strings.HasSuffix(file, \"pclinetest.s\") {\n\t\t\tt.Errorf(\"expected %s (%s) at PC %#x, got %s (%s)\", \"pclinetest.s\", sym.Name, pc, file, fn.Name)\n\t\t} else if line != wantLine || fn != sym {\n\t\t\tt.Errorf(\"expected :%d (%s) at PC %#x, got :%d (%s)\", wantLine, sym.Name, pc, line, fn.Name)\n\t\t}\n\t}\n\n\t\/\/ Test LineToPC\n\tsym = tab.LookupFunc(\"pcfromline\")\n\tlookupline := -1\n\twantLine = 0\n\toff := uint64(0) \/\/ TODO(rsc): should not need off; bug in 8g\n\tfor pc := sym.Value; pc < sym.End; pc += 2 + uint64(textdat[off]) {\n\t\tfile, line, fn := tab.PCToLine(pc)\n\t\toff = pc - text.Addr\n\t\twantLine += int(textdat[off])\n\t\tif line != wantLine {\n\t\t\tt.Errorf(\"expected line %d at PC %#x in pcfromline, got %d\", wantLine, pc, line)\n\t\t\toff = pc + 1 - text.Addr\n\t\t\tcontinue\n\t\t}\n\t\tif lookupline == -1 {\n\t\t\tlookupline = line\n\t\t}\n\t\tfor ; lookupline <= line; lookupline++ {\n\t\t\tpc2, fn2, err := tab.LineToPC(file, lookupline)\n\t\t\tif lookupline != line {\n\t\t\t\t\/\/ Should be nothing on this line\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(\"expected no PC at line %d, got %#x (%s)\", lookupline, pc2, fn2.Name)\n\t\t\t\t}\n\t\t\t} else if err != nil {\n\t\t\t\tt.Errorf(\"failed to get PC of line %d: %s\", lookupline, err)\n\t\t\t} else if pc != pc2 {\n\t\t\t\tt.Errorf(\"expected PC %#x (%s) at line %d, got PC %#x (%s)\", pc, fn.Name, line, pc2, fn2.Name)\n\t\t\t}\n\t\t}\n\t\toff = pc + 1 - text.Addr\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage gosym\n\nimport (\n\t\"debug\/elf\"\n\t\"os\"\n\t\"testing\"\n\t\"syscall\"\n)\n\nfunc dotest() bool {\n\t\/\/ For now, only works on ELF platforms.\n\treturn syscall.OS == \"linux\" && os.Getenv(\"GOARCH\") == \"amd64\"\n}\n\nfunc getTable(t *testing.T) *Table {\n\tf, tab := crack(os.Args[0], t)\n\tf.Close()\n\treturn tab\n}\n\nfunc crack(file string, t *testing.T) (*elf.File, *Table) {\n\t\/\/ Open self\n\tf, err := elf.Open(file)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn parse(file, f, t)\n}\n\nfunc parse(file string, f *elf.File, t *testing.T) (*elf.File, *Table) {\n\tsymdat, err := f.Section(\".gosymtab\").Data()\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"reading %s gosymtab: %v\", file, err)\n\t}\n\tpclndat, err := f.Section(\".gopclntab\").Data()\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"reading %s gopclntab: %v\", file, err)\n\t}\n\n\tpcln := NewLineTable(pclndat, f.Section(\".text\").Addr)\n\ttab, err := NewTable(symdat, pcln)\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"parsing %s gosymtab: %v\", file, err)\n\t}\n\n\treturn f, tab\n}\n\nvar goarch = os.Getenv(\"O\")\n\nfunc TestLineFromAline(t *testing.T) {\n\tif !dotest() {\n\t\treturn\n\t}\n\n\ttab := getTable(t)\n\n\t\/\/ Find the sym package\n\tpkg := tab.LookupFunc(\"debug\/gosym.TestLineFromAline\").Obj\n\tif pkg == nil {\n\t\tt.Fatalf(\"nil pkg\")\n\t}\n\n\t\/\/ Walk every absolute line and ensure that we hit every\n\t\/\/ source line monotonically\n\tlastline := make(map[string]int)\n\tfinal := -1\n\tfor i := 0; i < 10000; i++ {\n\t\tpath, line := pkg.lineFromAline(i)\n\t\t\/\/ Check for end of object\n\t\tif path == \"\" {\n\t\t\tif final == -1 {\n\t\t\t\tfinal = i - 1\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if final != -1 {\n\t\t\tt.Fatalf(\"reached end of package at absolute line %d, but absolute line %d mapped to %s:%d\", final, i, path, line)\n\t\t}\n\t\t\/\/ It's okay to see files multiple times (e.g., sys.a)\n\t\tif line == 1 {\n\t\t\tlastline[path] = 1\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Check that the is the next line in path\n\t\tll, ok := lastline[path]\n\t\tif !ok {\n\t\t\tt.Errorf(\"file %s starts on line %d\", path, line)\n\t\t} else if line != ll+1 {\n\t\t\tt.Errorf(\"expected next line of file %s to be %d, got %d\", path, ll+1, line)\n\t\t}\n\t\tlastline[path] = line\n\t}\n\tif final == -1 {\n\t\tt.Errorf(\"never reached end of object\")\n\t}\n}\n\nfunc TestLineAline(t *testing.T) {\n\tif !dotest() {\n\t\treturn\n\t}\n\n\ttab := getTable(t)\n\n\tfor _, o := range tab.Files {\n\t\t\/\/ A source file can appear multiple times in a\n\t\t\/\/ object.  alineFromLine will always return alines in\n\t\t\/\/ the first file, so track which lines we've seen.\n\t\tfound := make(map[string]int)\n\t\tfor i := 0; i < 1000; i++ {\n\t\t\tpath, line := o.lineFromAline(i)\n\t\t\tif path == \"\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ cgo files are full of 'Z' symbols, which we don't handle\n\t\t\tif len(path) > 4 && path[len(path)-4:] == \".cgo\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif minline, ok := found[path]; path != \"\" && ok {\n\t\t\t\tif minline >= line {\n\t\t\t\t\t\/\/ We've already covered this file\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tfound[path] = line\n\n\t\t\ta, err := o.alineFromLine(path, line)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"absolute line %d in object %s maps to %s:%d, but mapping that back gives error %s\", i, o.Paths[0].Name, path, line, err)\n\t\t\t} else if a != i {\n\t\t\t\tt.Errorf(\"absolute line %d in object %s maps to %s:%d, which maps back to absolute line %d\\n\", i, o.Paths[0].Name, path, line, a)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ gotest: if [ \"$(uname)-$(uname -m)\" = Linux-x86_64 ]; then\n\/\/ gotest:    mkdir -p _test && $AS pclinetest.s && $LD -E main -o _test\/pclinetest pclinetest.$O\n\/\/ gotest: fi\nfunc TestPCLine(t *testing.T) {\n\tif !dotest() {\n\t\treturn\n\t}\n\n\tf, tab := crack(\"_test\/pclinetest\", t)\n\ttext := f.Section(\".text\")\n\ttextdat, err := text.Data()\n\tif err != nil {\n\t\tt.Fatalf(\"reading .text: %v\", err)\n\t}\n\n\t\/\/ Test PCToLine\n\tsym := tab.LookupFunc(\"linefrompc\")\n\twantLine := 0\n\tfor pc := sym.Entry; pc < sym.End; pc++ {\n\t\tfile, line, fn := tab.PCToLine(pc)\n\t\toff := pc - text.Addr \/\/ TODO(rsc): should not need off; bug in 8g\n\t\twantLine += int(textdat[off])\n\t\tif fn == nil {\n\t\t\tt.Errorf(\"failed to get line of PC %#x\", pc)\n\t\t} else if len(file) < 12 || file[len(file)-12:] != \"pclinetest.s\" || line != wantLine || fn != sym {\n\t\t\tt.Errorf(\"expected %s:%d (%s) at PC %#x, got %s:%d (%s)\", \"pclinetest.s\", wantLine, sym.Name, pc, file, line, fn.Name)\n\t\t}\n\t}\n\n\t\/\/ Test LineToPC\n\tsym = tab.LookupFunc(\"pcfromline\")\n\tlookupline := -1\n\twantLine = 0\n\toff := uint64(0) \/\/ TODO(rsc): should not need off; bug in 8g\n\tfor pc := sym.Value; pc < sym.End; pc += 2 + uint64(textdat[off]) {\n\t\tfile, line, fn := tab.PCToLine(pc)\n\t\toff = pc - text.Addr\n\t\twantLine += int(textdat[off])\n\t\tif line != wantLine {\n\t\t\tt.Errorf(\"expected line %d at PC %#x in pcfromline, got %d\", wantLine, pc, line)\n\t\t\toff = pc + 1 - text.Addr\n\t\t\tcontinue\n\t\t}\n\t\tif lookupline == -1 {\n\t\t\tlookupline = line\n\t\t}\n\t\tfor ; lookupline <= line; lookupline++ {\n\t\t\tpc2, fn2, err := tab.LineToPC(file, lookupline)\n\t\t\tif lookupline != line {\n\t\t\t\t\/\/ Should be nothing on this line\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(\"expected no PC at line %d, got %#x (%s)\", lookupline, pc2, fn2.Name)\n\t\t\t\t}\n\t\t\t} else if err != nil {\n\t\t\t\tt.Errorf(\"failed to get PC of line %d: %s\", lookupline, err)\n\t\t\t} else if pc != pc2 {\n\t\t\t\tt.Errorf(\"expected PC %#x (%s) at line %d, got PC %#x (%s)\", pc, fn.Name, line, pc2, fn2.Name)\n\t\t\t}\n\t\t}\n\t\toff = pc + 1 - text.Addr\n\t}\n}\n<commit_msg>debug\/gosym: do not run when cross-compiling<commit_after>\/\/ Copyright 2009 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage gosym\n\nimport (\n\t\"debug\/elf\"\n\t\"os\"\n\t\"testing\"\n\t\"syscall\"\n)\n\nfunc dotest() bool {\n\t\/\/ For now, only works on ELF platforms.\n\treturn syscall.OS == \"linux\" && os.Getenv(\"GOARCH\") == \"amd64\"\n}\n\nfunc getTable(t *testing.T) *Table {\n\tf, tab := crack(os.Args[0], t)\n\tf.Close()\n\treturn tab\n}\n\nfunc crack(file string, t *testing.T) (*elf.File, *Table) {\n\t\/\/ Open self\n\tf, err := elf.Open(file)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn parse(file, f, t)\n}\n\nfunc parse(file string, f *elf.File, t *testing.T) (*elf.File, *Table) {\n\tsymdat, err := f.Section(\".gosymtab\").Data()\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"reading %s gosymtab: %v\", file, err)\n\t}\n\tpclndat, err := f.Section(\".gopclntab\").Data()\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"reading %s gopclntab: %v\", file, err)\n\t}\n\n\tpcln := NewLineTable(pclndat, f.Section(\".text\").Addr)\n\ttab, err := NewTable(symdat, pcln)\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"parsing %s gosymtab: %v\", file, err)\n\t}\n\n\treturn f, tab\n}\n\nvar goarch = os.Getenv(\"O\")\n\nfunc TestLineFromAline(t *testing.T) {\n\tif !dotest() {\n\t\treturn\n\t}\n\n\ttab := getTable(t)\n\n\t\/\/ Find the sym package\n\tpkg := tab.LookupFunc(\"debug\/gosym.TestLineFromAline\").Obj\n\tif pkg == nil {\n\t\tt.Fatalf(\"nil pkg\")\n\t}\n\n\t\/\/ Walk every absolute line and ensure that we hit every\n\t\/\/ source line monotonically\n\tlastline := make(map[string]int)\n\tfinal := -1\n\tfor i := 0; i < 10000; i++ {\n\t\tpath, line := pkg.lineFromAline(i)\n\t\t\/\/ Check for end of object\n\t\tif path == \"\" {\n\t\t\tif final == -1 {\n\t\t\t\tfinal = i - 1\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if final != -1 {\n\t\t\tt.Fatalf(\"reached end of package at absolute line %d, but absolute line %d mapped to %s:%d\", final, i, path, line)\n\t\t}\n\t\t\/\/ It's okay to see files multiple times (e.g., sys.a)\n\t\tif line == 1 {\n\t\t\tlastline[path] = 1\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Check that the is the next line in path\n\t\tll, ok := lastline[path]\n\t\tif !ok {\n\t\t\tt.Errorf(\"file %s starts on line %d\", path, line)\n\t\t} else if line != ll+1 {\n\t\t\tt.Errorf(\"expected next line of file %s to be %d, got %d\", path, ll+1, line)\n\t\t}\n\t\tlastline[path] = line\n\t}\n\tif final == -1 {\n\t\tt.Errorf(\"never reached end of object\")\n\t}\n}\n\nfunc TestLineAline(t *testing.T) {\n\tif !dotest() {\n\t\treturn\n\t}\n\n\ttab := getTable(t)\n\n\tfor _, o := range tab.Files {\n\t\t\/\/ A source file can appear multiple times in a\n\t\t\/\/ object.  alineFromLine will always return alines in\n\t\t\/\/ the first file, so track which lines we've seen.\n\t\tfound := make(map[string]int)\n\t\tfor i := 0; i < 1000; i++ {\n\t\t\tpath, line := o.lineFromAline(i)\n\t\t\tif path == \"\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ cgo files are full of 'Z' symbols, which we don't handle\n\t\t\tif len(path) > 4 && path[len(path)-4:] == \".cgo\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif minline, ok := found[path]; path != \"\" && ok {\n\t\t\t\tif minline >= line {\n\t\t\t\t\t\/\/ We've already covered this file\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tfound[path] = line\n\n\t\t\ta, err := o.alineFromLine(path, line)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"absolute line %d in object %s maps to %s:%d, but mapping that back gives error %s\", i, o.Paths[0].Name, path, line, err)\n\t\t\t} else if a != i {\n\t\t\t\tt.Errorf(\"absolute line %d in object %s maps to %s:%d, which maps back to absolute line %d\\n\", i, o.Paths[0].Name, path, line, a)\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ gotest: if [ \"$(uname)-$(uname -m)\" = Linux-x86_64 -a \"$GOARCH\" = amd64 ]; then\n\/\/ gotest:    mkdir -p _test && $AS pclinetest.s && $LD -E main -o _test\/pclinetest pclinetest.$O\n\/\/ gotest: fi\nfunc TestPCLine(t *testing.T) {\n\tif !dotest() {\n\t\treturn\n\t}\n\n\tf, tab := crack(\"_test\/pclinetest\", t)\n\ttext := f.Section(\".text\")\n\ttextdat, err := text.Data()\n\tif err != nil {\n\t\tt.Fatalf(\"reading .text: %v\", err)\n\t}\n\n\t\/\/ Test PCToLine\n\tsym := tab.LookupFunc(\"linefrompc\")\n\twantLine := 0\n\tfor pc := sym.Entry; pc < sym.End; pc++ {\n\t\tfile, line, fn := tab.PCToLine(pc)\n\t\toff := pc - text.Addr \/\/ TODO(rsc): should not need off; bug in 8g\n\t\twantLine += int(textdat[off])\n\t\tif fn == nil {\n\t\t\tt.Errorf(\"failed to get line of PC %#x\", pc)\n\t\t} else if len(file) < 12 || file[len(file)-12:] != \"pclinetest.s\" || line != wantLine || fn != sym {\n\t\t\tt.Errorf(\"expected %s:%d (%s) at PC %#x, got %s:%d (%s)\", \"pclinetest.s\", wantLine, sym.Name, pc, file, line, fn.Name)\n\t\t}\n\t}\n\n\t\/\/ Test LineToPC\n\tsym = tab.LookupFunc(\"pcfromline\")\n\tlookupline := -1\n\twantLine = 0\n\toff := uint64(0) \/\/ TODO(rsc): should not need off; bug in 8g\n\tfor pc := sym.Value; pc < sym.End; pc += 2 + uint64(textdat[off]) {\n\t\tfile, line, fn := tab.PCToLine(pc)\n\t\toff = pc - text.Addr\n\t\twantLine += int(textdat[off])\n\t\tif line != wantLine {\n\t\t\tt.Errorf(\"expected line %d at PC %#x in pcfromline, got %d\", wantLine, pc, line)\n\t\t\toff = pc + 1 - text.Addr\n\t\t\tcontinue\n\t\t}\n\t\tif lookupline == -1 {\n\t\t\tlookupline = line\n\t\t}\n\t\tfor ; lookupline <= line; lookupline++ {\n\t\t\tpc2, fn2, err := tab.LineToPC(file, lookupline)\n\t\t\tif lookupline != line {\n\t\t\t\t\/\/ Should be nothing on this line\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(\"expected no PC at line %d, got %#x (%s)\", lookupline, pc2, fn2.Name)\n\t\t\t\t}\n\t\t\t} else if err != nil {\n\t\t\t\tt.Errorf(\"failed to get PC of line %d: %s\", lookupline, err)\n\t\t\t} else if pc != pc2 {\n\t\t\t\tt.Errorf(\"expected PC %#x (%s) at line %d, got PC %#x (%s)\", pc, fn.Name, line, pc2, fn2.Name)\n\t\t\t}\n\t\t}\n\t\toff = pc + 1 - text.Addr\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage gosym\n\nimport (\n\t\"debug\/elf\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\nvar (\n\tpclineTempDir    string\n\tpclinetestBinary string\n)\n\nfunc dotest(self bool) bool {\n\t\/\/ For now, only works on amd64 platforms.\n\tif runtime.GOARCH != \"amd64\" {\n\t\treturn false\n\t}\n\t\/\/ Self test reads test binary; only works on Linux.\n\tif self && runtime.GOOS != \"linux\" {\n\t\treturn false\n\t}\n\t\/\/ Command below expects \"sh\", so Unix.\n\tif runtime.GOOS == \"windows\" || runtime.GOOS == \"plan9\" {\n\t\treturn false\n\t}\n\tif pclinetestBinary != \"\" {\n\t\treturn true\n\t}\n\tvar err error\n\tpclineTempDir, err = ioutil.TempDir(\"\", \"pclinetest\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif strings.Contains(pclineTempDir, \" \") {\n\t\tpanic(\"unexpected space in tempdir\")\n\t}\n\t\/\/ This command builds pclinetest from pclinetest.asm;\n\t\/\/ the resulting binary looks like it was built from pclinetest.s,\n\t\/\/ but we have renamed it to keep it away from the go tool.\n\tpclinetestBinary = filepath.Join(pclineTempDir, \"pclinetest\")\n\tcommand := fmt.Sprintf(\"go tool 6a -o %s.6 pclinetest.asm && go tool 6l -H linux -E main -o %s %s.6\",\n\t\tpclinetestBinary, pclinetestBinary, pclinetestBinary)\n\tcmd := exec.Command(\"sh\", \"-c\", command)\n\tif runtime.GOOS == \"akaros\" {\n\t\tcmd = exec.Command(\"\/bin\/ash\", \"-c\", command)\n\t}\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn true\n}\n\nfunc endtest() {\n\tif pclineTempDir != \"\" {\n\t\tos.RemoveAll(pclineTempDir)\n\t\tpclineTempDir = \"\"\n\t\tpclinetestBinary = \"\"\n\t}\n}\n\nfunc getTable(t *testing.T) *Table {\n\tf, tab := crack(os.Args[0], t)\n\tf.Close()\n\treturn tab\n}\n\nfunc crack(file string, t *testing.T) (*elf.File, *Table) {\n\t\/\/ Open self\n\tf, err := elf.Open(file)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn parse(file, f, t)\n}\n\nfunc parse(file string, f *elf.File, t *testing.T) (*elf.File, *Table) {\n\tsymdat, err := f.Section(\".gosymtab\").Data()\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"reading %s gosymtab: %v\", file, err)\n\t}\n\tpclndat, err := f.Section(\".gopclntab\").Data()\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"reading %s gopclntab: %v\", file, err)\n\t}\n\n\tpcln := NewLineTable(pclndat, f.Section(\".text\").Addr)\n\ttab, err := NewTable(symdat, pcln)\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"parsing %s gosymtab: %v\", file, err)\n\t}\n\n\treturn f, tab\n}\n\nvar goarch = os.Getenv(\"O\")\n\nfunc TestLineFromAline(t *testing.T) {\n\tif !dotest(true) {\n\t\treturn\n\t}\n\tdefer endtest()\n\n\ttab := getTable(t)\n\tif tab.go12line != nil {\n\t\t\/\/ aline's don't exist in the Go 1.2 table.\n\t\tt.Skip(\"not relevant to Go 1.2 symbol table\")\n\t}\n\n\t\/\/ Find the sym package\n\tpkg := tab.LookupFunc(\"debug\/gosym.TestLineFromAline\").Obj\n\tif pkg == nil {\n\t\tt.Fatalf(\"nil pkg\")\n\t}\n\n\t\/\/ Walk every absolute line and ensure that we hit every\n\t\/\/ source line monotonically\n\tlastline := make(map[string]int)\n\tfinal := -1\n\tfor i := 0; i < 10000; i++ {\n\t\tpath, line := pkg.lineFromAline(i)\n\t\t\/\/ Check for end of object\n\t\tif path == \"\" {\n\t\t\tif final == -1 {\n\t\t\t\tfinal = i - 1\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if final != -1 {\n\t\t\tt.Fatalf(\"reached end of package at absolute line %d, but absolute line %d mapped to %s:%d\", final, i, path, line)\n\t\t}\n\t\t\/\/ It's okay to see files multiple times (e.g., sys.a)\n\t\tif line == 1 {\n\t\t\tlastline[path] = 1\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Check that the is the next line in path\n\t\tll, ok := lastline[path]\n\t\tif !ok {\n\t\t\tt.Errorf(\"file %s starts on line %d\", path, line)\n\t\t} else if line != ll+1 {\n\t\t\tt.Fatalf(\"expected next line of file %s to be %d, got %d\", path, ll+1, line)\n\t\t}\n\t\tlastline[path] = line\n\t}\n\tif final == -1 {\n\t\tt.Errorf(\"never reached end of object\")\n\t}\n}\n\nfunc TestLineAline(t *testing.T) {\n\tif !dotest(true) {\n\t\treturn\n\t}\n\tdefer endtest()\n\n\ttab := getTable(t)\n\tif tab.go12line != nil {\n\t\t\/\/ aline's don't exist in the Go 1.2 table.\n\t\tt.Skip(\"not relevant to Go 1.2 symbol table\")\n\t}\n\n\tfor _, o := range tab.Files {\n\t\t\/\/ A source file can appear multiple times in a\n\t\t\/\/ object.  alineFromLine will always return alines in\n\t\t\/\/ the first file, so track which lines we've seen.\n\t\tfound := make(map[string]int)\n\t\tfor i := 0; i < 1000; i++ {\n\t\t\tpath, line := o.lineFromAline(i)\n\t\t\tif path == \"\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ cgo files are full of 'Z' symbols, which we don't handle\n\t\t\tif len(path) > 4 && path[len(path)-4:] == \".cgo\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif minline, ok := found[path]; path != \"\" && ok {\n\t\t\t\tif minline >= line {\n\t\t\t\t\t\/\/ We've already covered this file\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tfound[path] = line\n\n\t\t\ta, err := o.alineFromLine(path, line)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"absolute line %d in object %s maps to %s:%d, but mapping that back gives error %s\", i, o.Paths[0].Name, path, line, err)\n\t\t\t} else if a != i {\n\t\t\t\tt.Errorf(\"absolute line %d in object %s maps to %s:%d, which maps back to absolute line %d\\n\", i, o.Paths[0].Name, path, line, a)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestPCLine(t *testing.T) {\n\tif !dotest(false) {\n\t\treturn\n\t}\n\tdefer endtest()\n\n\tf, tab := crack(pclinetestBinary, t)\n\ttext := f.Section(\".text\")\n\ttextdat, err := text.Data()\n\tif err != nil {\n\t\tt.Fatalf(\"reading .text: %v\", err)\n\t}\n\n\t\/\/ Test PCToLine\n\tsym := tab.LookupFunc(\"linefrompc\")\n\twantLine := 0\n\tfor pc := sym.Entry; pc < sym.End; pc++ {\n\t\toff := pc - text.Addr \/\/ TODO(rsc): should not need off; bug in 8g\n\t\tif textdat[off] == 255 {\n\t\t\tbreak\n\t\t}\n\t\twantLine += int(textdat[off])\n\t\tt.Logf(\"off is %d %#x (max %d)\", off, textdat[off], sym.End-pc)\n\t\tfile, line, fn := tab.PCToLine(pc)\n\t\tif fn == nil {\n\t\t\tt.Errorf(\"failed to get line of PC %#x\", pc)\n\t\t} else if !strings.HasSuffix(file, \"pclinetest.asm\") || line != wantLine || fn != sym {\n\t\t\tt.Errorf(\"PCToLine(%#x) = %s:%d (%s), want %s:%d (%s)\", pc, file, line, fn.Name, \"pclinetest.asm\", wantLine, sym.Name)\n\t\t}\n\t}\n\n\t\/\/ Test LineToPC\n\tsym = tab.LookupFunc(\"pcfromline\")\n\tlookupline := -1\n\twantLine = 0\n\toff := uint64(0) \/\/ TODO(rsc): should not need off; bug in 8g\n\tfor pc := sym.Value; pc < sym.End; pc += 2 + uint64(textdat[off]) {\n\t\tfile, line, fn := tab.PCToLine(pc)\n\t\toff = pc - text.Addr\n\t\tif textdat[off] == 255 {\n\t\t\tbreak\n\t\t}\n\t\twantLine += int(textdat[off])\n\t\tif line != wantLine {\n\t\t\tt.Errorf(\"expected line %d at PC %#x in pcfromline, got %d\", wantLine, pc, line)\n\t\t\toff = pc + 1 - text.Addr\n\t\t\tcontinue\n\t\t}\n\t\tif lookupline == -1 {\n\t\t\tlookupline = line\n\t\t}\n\t\tfor ; lookupline <= line; lookupline++ {\n\t\t\tpc2, fn2, err := tab.LineToPC(file, lookupline)\n\t\t\tif lookupline != line {\n\t\t\t\t\/\/ Should be nothing on this line\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(\"expected no PC at line %d, got %#x (%s)\", lookupline, pc2, fn2.Name)\n\t\t\t\t}\n\t\t\t} else if err != nil {\n\t\t\t\tt.Errorf(\"failed to get PC of line %d: %s\", lookupline, err)\n\t\t\t} else if pc != pc2 {\n\t\t\t\tt.Errorf(\"expected PC %#x (%s) at line %d, got PC %#x (%s)\", pc, fn.Name, line, pc2, fn2.Name)\n\t\t\t}\n\t\t}\n\t\toff = pc + 1 - text.Addr\n\t}\n}\n<commit_msg>Add exception for akaros in debug\/gosysm<commit_after>\/\/ Copyright 2009 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage gosym\n\nimport (\n\t\"debug\/elf\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n)\n\nvar (\n\tpclineTempDir    string\n\tpclinetestBinary string\n)\n\nfunc dotest(self bool) bool {\n\t\/\/ For now, only works on amd64 platforms.\n\tif runtime.GOARCH != \"amd64\" {\n\t\treturn false\n\t}\n\t\/\/ Self test reads test binary; only works on Linux.\n\tif self && runtime.GOOS != \"linux\" {\n\t\treturn false\n\t}\n\t\/\/ Command below expects \"sh\", so Unix.\n\tif runtime.GOOS == \"windows\" || runtime.GOOS == \"plan9\" || runtime.GOOS == \"akaros\" {\n\t\treturn false\n\t}\n\tif pclinetestBinary != \"\" {\n\t\treturn true\n\t}\n\tvar err error\n\tpclineTempDir, err = ioutil.TempDir(\"\", \"pclinetest\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif strings.Contains(pclineTempDir, \" \") {\n\t\tpanic(\"unexpected space in tempdir\")\n\t}\n\t\/\/ This command builds pclinetest from pclinetest.asm;\n\t\/\/ the resulting binary looks like it was built from pclinetest.s,\n\t\/\/ but we have renamed it to keep it away from the go tool.\n\tpclinetestBinary = filepath.Join(pclineTempDir, \"pclinetest\")\n\tcommand := fmt.Sprintf(\"go tool 6a -o %s.6 pclinetest.asm && go tool 6l -H linux -E main -o %s %s.6\",\n\t\tpclinetestBinary, pclinetestBinary, pclinetestBinary)\n\tcmd := exec.Command(\"sh\", \"-c\", command)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif err := cmd.Run(); err != nil {\n\t\tpanic(err)\n\t}\n\treturn true\n}\n\nfunc endtest() {\n\tif pclineTempDir != \"\" {\n\t\tos.RemoveAll(pclineTempDir)\n\t\tpclineTempDir = \"\"\n\t\tpclinetestBinary = \"\"\n\t}\n}\n\nfunc getTable(t *testing.T) *Table {\n\tf, tab := crack(os.Args[0], t)\n\tf.Close()\n\treturn tab\n}\n\nfunc crack(file string, t *testing.T) (*elf.File, *Table) {\n\t\/\/ Open self\n\tf, err := elf.Open(file)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn parse(file, f, t)\n}\n\nfunc parse(file string, f *elf.File, t *testing.T) (*elf.File, *Table) {\n\tsymdat, err := f.Section(\".gosymtab\").Data()\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"reading %s gosymtab: %v\", file, err)\n\t}\n\tpclndat, err := f.Section(\".gopclntab\").Data()\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"reading %s gopclntab: %v\", file, err)\n\t}\n\n\tpcln := NewLineTable(pclndat, f.Section(\".text\").Addr)\n\ttab, err := NewTable(symdat, pcln)\n\tif err != nil {\n\t\tf.Close()\n\t\tt.Fatalf(\"parsing %s gosymtab: %v\", file, err)\n\t}\n\n\treturn f, tab\n}\n\nvar goarch = os.Getenv(\"O\")\n\nfunc TestLineFromAline(t *testing.T) {\n\tif !dotest(true) {\n\t\treturn\n\t}\n\tdefer endtest()\n\n\ttab := getTable(t)\n\tif tab.go12line != nil {\n\t\t\/\/ aline's don't exist in the Go 1.2 table.\n\t\tt.Skip(\"not relevant to Go 1.2 symbol table\")\n\t}\n\n\t\/\/ Find the sym package\n\tpkg := tab.LookupFunc(\"debug\/gosym.TestLineFromAline\").Obj\n\tif pkg == nil {\n\t\tt.Fatalf(\"nil pkg\")\n\t}\n\n\t\/\/ Walk every absolute line and ensure that we hit every\n\t\/\/ source line monotonically\n\tlastline := make(map[string]int)\n\tfinal := -1\n\tfor i := 0; i < 10000; i++ {\n\t\tpath, line := pkg.lineFromAline(i)\n\t\t\/\/ Check for end of object\n\t\tif path == \"\" {\n\t\t\tif final == -1 {\n\t\t\t\tfinal = i - 1\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if final != -1 {\n\t\t\tt.Fatalf(\"reached end of package at absolute line %d, but absolute line %d mapped to %s:%d\", final, i, path, line)\n\t\t}\n\t\t\/\/ It's okay to see files multiple times (e.g., sys.a)\n\t\tif line == 1 {\n\t\t\tlastline[path] = 1\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ Check that the is the next line in path\n\t\tll, ok := lastline[path]\n\t\tif !ok {\n\t\t\tt.Errorf(\"file %s starts on line %d\", path, line)\n\t\t} else if line != ll+1 {\n\t\t\tt.Fatalf(\"expected next line of file %s to be %d, got %d\", path, ll+1, line)\n\t\t}\n\t\tlastline[path] = line\n\t}\n\tif final == -1 {\n\t\tt.Errorf(\"never reached end of object\")\n\t}\n}\n\nfunc TestLineAline(t *testing.T) {\n\tif !dotest(true) {\n\t\treturn\n\t}\n\tdefer endtest()\n\n\ttab := getTable(t)\n\tif tab.go12line != nil {\n\t\t\/\/ aline's don't exist in the Go 1.2 table.\n\t\tt.Skip(\"not relevant to Go 1.2 symbol table\")\n\t}\n\n\tfor _, o := range tab.Files {\n\t\t\/\/ A source file can appear multiple times in a\n\t\t\/\/ object.  alineFromLine will always return alines in\n\t\t\/\/ the first file, so track which lines we've seen.\n\t\tfound := make(map[string]int)\n\t\tfor i := 0; i < 1000; i++ {\n\t\t\tpath, line := o.lineFromAline(i)\n\t\t\tif path == \"\" {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\t\/\/ cgo files are full of 'Z' symbols, which we don't handle\n\t\t\tif len(path) > 4 && path[len(path)-4:] == \".cgo\" {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif minline, ok := found[path]; path != \"\" && ok {\n\t\t\t\tif minline >= line {\n\t\t\t\t\t\/\/ We've already covered this file\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tfound[path] = line\n\n\t\t\ta, err := o.alineFromLine(path, line)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"absolute line %d in object %s maps to %s:%d, but mapping that back gives error %s\", i, o.Paths[0].Name, path, line, err)\n\t\t\t} else if a != i {\n\t\t\t\tt.Errorf(\"absolute line %d in object %s maps to %s:%d, which maps back to absolute line %d\\n\", i, o.Paths[0].Name, path, line, a)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestPCLine(t *testing.T) {\n\tif !dotest(false) {\n\t\treturn\n\t}\n\tdefer endtest()\n\n\tf, tab := crack(pclinetestBinary, t)\n\ttext := f.Section(\".text\")\n\ttextdat, err := text.Data()\n\tif err != nil {\n\t\tt.Fatalf(\"reading .text: %v\", err)\n\t}\n\n\t\/\/ Test PCToLine\n\tsym := tab.LookupFunc(\"linefrompc\")\n\twantLine := 0\n\tfor pc := sym.Entry; pc < sym.End; pc++ {\n\t\toff := pc - text.Addr \/\/ TODO(rsc): should not need off; bug in 8g\n\t\tif textdat[off] == 255 {\n\t\t\tbreak\n\t\t}\n\t\twantLine += int(textdat[off])\n\t\tt.Logf(\"off is %d %#x (max %d)\", off, textdat[off], sym.End-pc)\n\t\tfile, line, fn := tab.PCToLine(pc)\n\t\tif fn == nil {\n\t\t\tt.Errorf(\"failed to get line of PC %#x\", pc)\n\t\t} else if !strings.HasSuffix(file, \"pclinetest.asm\") || line != wantLine || fn != sym {\n\t\t\tt.Errorf(\"PCToLine(%#x) = %s:%d (%s), want %s:%d (%s)\", pc, file, line, fn.Name, \"pclinetest.asm\", wantLine, sym.Name)\n\t\t}\n\t}\n\n\t\/\/ Test LineToPC\n\tsym = tab.LookupFunc(\"pcfromline\")\n\tlookupline := -1\n\twantLine = 0\n\toff := uint64(0) \/\/ TODO(rsc): should not need off; bug in 8g\n\tfor pc := sym.Value; pc < sym.End; pc += 2 + uint64(textdat[off]) {\n\t\tfile, line, fn := tab.PCToLine(pc)\n\t\toff = pc - text.Addr\n\t\tif textdat[off] == 255 {\n\t\t\tbreak\n\t\t}\n\t\twantLine += int(textdat[off])\n\t\tif line != wantLine {\n\t\t\tt.Errorf(\"expected line %d at PC %#x in pcfromline, got %d\", wantLine, pc, line)\n\t\t\toff = pc + 1 - text.Addr\n\t\t\tcontinue\n\t\t}\n\t\tif lookupline == -1 {\n\t\t\tlookupline = line\n\t\t}\n\t\tfor ; lookupline <= line; lookupline++ {\n\t\t\tpc2, fn2, err := tab.LineToPC(file, lookupline)\n\t\t\tif lookupline != line {\n\t\t\t\t\/\/ Should be nothing on this line\n\t\t\t\tif err == nil {\n\t\t\t\t\tt.Errorf(\"expected no PC at line %d, got %#x (%s)\", lookupline, pc2, fn2.Name)\n\t\t\t\t}\n\t\t\t} else if err != nil {\n\t\t\t\tt.Errorf(\"failed to get PC of line %d: %s\", lookupline, err)\n\t\t\t} else if pc != pc2 {\n\t\t\t\tt.Errorf(\"expected PC %#x (%s) at line %d, got PC %#x (%s)\", pc, fn.Name, line, pc2, fn2.Name)\n\t\t\t}\n\t\t}\n\t\toff = pc + 1 - text.Addr\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ godefs -gsyscall types_linux.c\n\n\/\/ MACHINE GENERATED - DO NOT EDIT.\n\npackage syscall\n\n\/\/ Constants\nconst (\n\tsizeofPtr               = 0x4\n\tsizeofShort             = 0x2\n\tsizeofInt               = 0x4\n\tsizeofLong              = 0x4\n\tsizeofLongLong          = 0x8\n\tPathMax                 = 0x1000\n\tSizeofSockaddrInet4     = 0x10\n\tSizeofSockaddrInet6     = 0x1c\n\tSizeofSockaddrAny       = 0x70\n\tSizeofSockaddrUnix      = 0x6e\n\tSizeofSockaddrLinklayer = 0x14\n\tSizeofLinger            = 0x8\n\tSizeofMsghdr            = 0x1c\n\tSizeofCmsghdr           = 0xc\n\tSizeofUcred             = 0xc\n\tSizeofInotifyEvent      = 0x10\n)\n\n\/\/ Types\n\ntype _C_short int16\n\ntype _C_int int32\n\ntype _C_long int32\n\ntype _C_long_long int64\n\ntype Timespec struct {\n\tSec  int32\n\tNsec int32\n}\n\ntype Timeval struct {\n\tSec  int32\n\tUsec int32\n}\n\ntype Timex struct {\n\tModes     uint32\n\tOffset    int32\n\tFreq      int32\n\tMaxerror  int32\n\tEsterror  int32\n\tStatus    int32\n\tConstant  int32\n\tPrecision int32\n\tTolerance int32\n\tTime      Timeval\n\tTick      int32\n\tPpsfreq   int32\n\tJitter    int32\n\tShift     int32\n\tStabil    int32\n\tJitcnt    int32\n\tCalcnt    int32\n\tErrcnt    int32\n\tStbcnt    int32\n\tTai       int32\n\tPad0      int32\n\tPad1      int32\n\tPad2      int32\n\tPad3      int32\n\tPad4      int32\n\tPad5      int32\n\tPad6      int32\n\tPad7      int32\n\tPad8      int32\n\tPad9      int32\n\tPad10     int32\n}\n\ntype Time_t int32\n\ntype Tms struct {\n\tUtime  int32\n\tStime  int32\n\tCutime int32\n\tCstime int32\n}\n\ntype Utimbuf struct {\n\tActime  int32\n\tModtime int32\n}\n\ntype Rusage struct {\n\tUtime    Timeval\n\tStime    Timeval\n\tMaxrss   int32\n\tIxrss    int32\n\tIdrss    int32\n\tIsrss    int32\n\tMinflt   int32\n\tMajflt   int32\n\tNswap    int32\n\tInblock  int32\n\tOublock  int32\n\tMsgsnd   int32\n\tMsgrcv   int32\n\tNsignals int32\n\tNvcsw    int32\n\tNivcsw   int32\n}\n\ntype Rlimit struct {\n\tCur uint64\n\tMax uint64\n}\n\ntype _Gid_t uint32\n\ntype Stat_t struct {\n\tDev       uint64\n\tX__pad1   uint16\n\tPad0      [2]byte\n\tX__st_ino uint32\n\tMode      uint32\n\tNlink     uint32\n\tUid       uint32\n\tGid       uint32\n\tRdev      uint64\n\tX__pad2   uint16\n\tPad1      [6]byte\n\tSize      int64\n\tBlksize   int32\n\tPad2      [4]byte\n\tBlocks    int64\n\tAtim      Timespec\n\tMtim      Timespec\n\tCtim      Timespec\n\tIno       uint64\n}\n\ntype Statfs_t struct {\n\tType    int32\n\tBsize   int32\n\tBlocks  uint64\n\tBfree   uint64\n\tBavail  uint64\n\tFiles   uint64\n\tFfree   uint64\n\tFsid    [8]byte \/* __fsid_t *\/\n\tNamelen int32\n\tFrsize  int32\n\tSpare   [5]int32\n\tPad0    [4]byte\n}\n\ntype Dirent struct {\n\tIno    uint64\n\tOff    int64\n\tReclen uint16\n\tType   uint8\n\tName   [256]uint8\n\tPad0   [5]byte\n}\n\ntype RawSockaddrInet4 struct {\n\tFamily uint16\n\tPort   uint16\n\tAddr   [4]byte \/* in_addr *\/\n\tZero   [8]uint8\n}\n\ntype RawSockaddrInet6 struct {\n\tFamily   uint16\n\tPort     uint16\n\tFlowinfo uint32\n\tAddr     [16]byte \/* in6_addr *\/\n\tScope_id uint32\n}\n\ntype RawSockaddrUnix struct {\n\tFamily uint16\n\tPath   [108]uint8\n}\n\ntype RawSockaddrLinklayer struct {\n\tFamily   uint16\n\tProtocol uint16\n\tIfindex  int32\n\tHatype   uint16\n\tPkttype  uint8\n\tHalen    uint8\n\tAddr     [8]uint8\n}\n\ntype RawSockaddr struct {\n\tFamily uint16\n\tData   [14]uint8\n}\n\ntype RawSockaddrAny struct {\n\tAddr RawSockaddr\n\tPad  [96]uint8\n}\n\ntype _Socklen uint32\n\ntype Linger struct {\n\tOnoff  int32\n\tLinger int32\n}\n\ntype Iovec struct {\n\tBase *byte\n\tLen  uint32\n}\n\ntype Msghdr struct {\n\tName       *byte\n\tNamelen    uint32\n\tIov        *Iovec\n\tIovlen     uint32\n\tControl    *byte\n\tControllen uint32\n\tFlags      int32\n}\n\ntype Cmsghdr struct {\n\tLen   uint32\n\tLevel int32\n\tType  int32\n}\n\ntype Ucred struct {\n\tPid int32\n\tUid uint32\n\tGid uint32\n}\n\ntype InotifyEvent struct {\n\tWd     int32\n\tMask   uint32\n\tCookie uint32\n\tLen    uint32\n}\n\ntype PtraceRegs struct{}\n\ntype PtraceRegs struct{}\n\ntype FdSet struct {\n\tBits [32]int32\n}\n\ntype Sysinfo_t struct {\n\tUptime    int32\n\tLoads     [3]uint32\n\tTotalram  uint32\n\tFreeram   uint32\n\tSharedram uint32\n\tBufferram uint32\n\tTotalswap uint32\n\tFreeswap  uint32\n\tProcs     uint16\n\tPad       uint16\n\tTotalhigh uint32\n\tFreehigh  uint32\n\tUnit      uint32\n\tX_f       [8]uint8\n}\n\ntype Utsname struct {\n\tSysname    [65]uint8\n\tNodename   [65]uint8\n\tRelease    [65]uint8\n\tVersion    [65]uint8\n\tMachine    [65]uint8\n\tDomainname [65]uint8\n}\n\ntype Ustat_t struct {\n\tTfree  int32\n\tTinode uint32\n\tFname  [6]uint8\n\tFpack  [6]uint8\n}\n\ntype EpollEvent struct {\n\tEvents uint32\n\tFd     int32\n\tPad    int32\n}\n<commit_msg>arm: fix syscall build again<commit_after>\/\/ godefs -gsyscall types_linux.c\n\n\/\/ MACHINE GENERATED - DO NOT EDIT.\n\n\/\/ Manual corrections: UGH\n\/\/\tremove duplicate PtraceRegs type\n\/\/\tchange RawSockaddrUnix field to Path [108]int8 (was uint8()\n\npackage syscall\n\n\/\/ Constants\nconst (\n\tsizeofPtr               = 0x4\n\tsizeofShort             = 0x2\n\tsizeofInt               = 0x4\n\tsizeofLong              = 0x4\n\tsizeofLongLong          = 0x8\n\tPathMax                 = 0x1000\n\tSizeofSockaddrInet4     = 0x10\n\tSizeofSockaddrInet6     = 0x1c\n\tSizeofSockaddrAny       = 0x70\n\tSizeofSockaddrUnix      = 0x6e\n\tSizeofSockaddrLinklayer = 0x14\n\tSizeofLinger            = 0x8\n\tSizeofMsghdr            = 0x1c\n\tSizeofCmsghdr           = 0xc\n\tSizeofUcred             = 0xc\n\tSizeofInotifyEvent      = 0x10\n)\n\n\/\/ Types\n\ntype _C_short int16\n\ntype _C_int int32\n\ntype _C_long int32\n\ntype _C_long_long int64\n\ntype Timespec struct {\n\tSec  int32\n\tNsec int32\n}\n\ntype Timeval struct {\n\tSec  int32\n\tUsec int32\n}\n\ntype Timex struct {\n\tModes     uint32\n\tOffset    int32\n\tFreq      int32\n\tMaxerror  int32\n\tEsterror  int32\n\tStatus    int32\n\tConstant  int32\n\tPrecision int32\n\tTolerance int32\n\tTime      Timeval\n\tTick      int32\n\tPpsfreq   int32\n\tJitter    int32\n\tShift     int32\n\tStabil    int32\n\tJitcnt    int32\n\tCalcnt    int32\n\tErrcnt    int32\n\tStbcnt    int32\n\tTai       int32\n\tPad0      int32\n\tPad1      int32\n\tPad2      int32\n\tPad3      int32\n\tPad4      int32\n\tPad5      int32\n\tPad6      int32\n\tPad7      int32\n\tPad8      int32\n\tPad9      int32\n\tPad10     int32\n}\n\ntype Time_t int32\n\ntype Tms struct {\n\tUtime  int32\n\tStime  int32\n\tCutime int32\n\tCstime int32\n}\n\ntype Utimbuf struct {\n\tActime  int32\n\tModtime int32\n}\n\ntype Rusage struct {\n\tUtime    Timeval\n\tStime    Timeval\n\tMaxrss   int32\n\tIxrss    int32\n\tIdrss    int32\n\tIsrss    int32\n\tMinflt   int32\n\tMajflt   int32\n\tNswap    int32\n\tInblock  int32\n\tOublock  int32\n\tMsgsnd   int32\n\tMsgrcv   int32\n\tNsignals int32\n\tNvcsw    int32\n\tNivcsw   int32\n}\n\ntype Rlimit struct {\n\tCur uint64\n\tMax uint64\n}\n\ntype _Gid_t uint32\n\ntype Stat_t struct {\n\tDev       uint64\n\tX__pad1   uint16\n\tPad0      [2]byte\n\tX__st_ino uint32\n\tMode      uint32\n\tNlink     uint32\n\tUid       uint32\n\tGid       uint32\n\tRdev      uint64\n\tX__pad2   uint16\n\tPad1      [6]byte\n\tSize      int64\n\tBlksize   int32\n\tPad2      [4]byte\n\tBlocks    int64\n\tAtim      Timespec\n\tMtim      Timespec\n\tCtim      Timespec\n\tIno       uint64\n}\n\ntype Statfs_t struct {\n\tType    int32\n\tBsize   int32\n\tBlocks  uint64\n\tBfree   uint64\n\tBavail  uint64\n\tFiles   uint64\n\tFfree   uint64\n\tFsid    [8]byte \/* __fsid_t *\/\n\tNamelen int32\n\tFrsize  int32\n\tSpare   [5]int32\n\tPad0    [4]byte\n}\n\ntype Dirent struct {\n\tIno    uint64\n\tOff    int64\n\tReclen uint16\n\tType   uint8\n\tName   [256]uint8\n\tPad0   [5]byte\n}\n\ntype RawSockaddrInet4 struct {\n\tFamily uint16\n\tPort   uint16\n\tAddr   [4]byte \/* in_addr *\/\n\tZero   [8]uint8\n}\n\ntype RawSockaddrInet6 struct {\n\tFamily   uint16\n\tPort     uint16\n\tFlowinfo uint32\n\tAddr     [16]byte \/* in6_addr *\/\n\tScope_id uint32\n}\n\ntype RawSockaddrUnix struct {\n\tFamily uint16\n\tPath   [108]int8\n}\n\ntype RawSockaddrLinklayer struct {\n\tFamily   uint16\n\tProtocol uint16\n\tIfindex  int32\n\tHatype   uint16\n\tPkttype  uint8\n\tHalen    uint8\n\tAddr     [8]uint8\n}\n\ntype RawSockaddr struct {\n\tFamily uint16\n\tData   [14]uint8\n}\n\ntype RawSockaddrAny struct {\n\tAddr RawSockaddr\n\tPad  [96]uint8\n}\n\ntype _Socklen uint32\n\ntype Linger struct {\n\tOnoff  int32\n\tLinger int32\n}\n\ntype Iovec struct {\n\tBase *byte\n\tLen  uint32\n}\n\ntype Msghdr struct {\n\tName       *byte\n\tNamelen    uint32\n\tIov        *Iovec\n\tIovlen     uint32\n\tControl    *byte\n\tControllen uint32\n\tFlags      int32\n}\n\ntype Cmsghdr struct {\n\tLen   uint32\n\tLevel int32\n\tType  int32\n}\n\ntype Ucred struct {\n\tPid int32\n\tUid uint32\n\tGid uint32\n}\n\ntype InotifyEvent struct {\n\tWd     int32\n\tMask   uint32\n\tCookie uint32\n\tLen    uint32\n}\n\ntype PtraceRegs struct{}\n\ntype FdSet struct {\n\tBits [32]int32\n}\n\ntype Sysinfo_t struct {\n\tUptime    int32\n\tLoads     [3]uint32\n\tTotalram  uint32\n\tFreeram   uint32\n\tSharedram uint32\n\tBufferram uint32\n\tTotalswap uint32\n\tFreeswap  uint32\n\tProcs     uint16\n\tPad       uint16\n\tTotalhigh uint32\n\tFreehigh  uint32\n\tUnit      uint32\n\tX_f       [8]uint8\n}\n\ntype Utsname struct {\n\tSysname    [65]uint8\n\tNodename   [65]uint8\n\tRelease    [65]uint8\n\tVersion    [65]uint8\n\tMachine    [65]uint8\n\tDomainname [65]uint8\n}\n\ntype Ustat_t struct {\n\tTfree  int32\n\tTinode uint32\n\tFname  [6]uint8\n\tFpack  [6]uint8\n}\n\ntype EpollEvent struct {\n\tEvents uint32\n\tFd     int32\n\tPad    int32\n}\n<|endoftext|>"}
{"text":"<commit_before>package s3\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\"\n)\n\ntype ClientFactory interface {\n\tClient(authToken string) (*client.APIClient, error)\n}\n\ntype LocalClientFactory struct {\n\tport uint16\n}\n\nfunc NewLocalClientFactory(port uint16) *LocalClientFactory {\n\treturn &LocalClientFactory{\n\t\tport: port,\n\t}\n}\n\nfunc (f *LocalClientFactory) Client(authToken string) (*client.APIClient, error) {\n\tpc, err := client.NewFromAddress(fmt.Sprintf(\"localhost:%d\", f.port))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif authToken != \"\" {\n\t\tpc.SetAuthToken(authToken)\n\t}\n\treturn pc, nil\n}\n<commit_msg>ClientFactory comments<commit_after>package s3\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\"\n)\n\n\/\/ ClientFactory implementors provide a way for the s3gateway to instantiate\n\/\/ and configure a request-scoped client.\ntype ClientFactory interface {\n\t\/\/ Client creates a pachyderm client.\n\tClient(authToken string) (*client.APIClient, error)\n}\n\n\/\/ LocalClientFactory creates clients that connect to localhost on a\n\/\/ configurable port.\ntype LocalClientFactory struct {\n\tport uint16\n}\n\n\/\/ NewLocalClientFactory creates a new LocalClientFactory, using the given\n\/\/ port.\nfunc NewLocalClientFactory(port uint16) *LocalClientFactory {\n\treturn &LocalClientFactory{\n\t\tport: port,\n\t}\n}\n\n\/\/ Client creates a pachyderm client.\nfunc (f *LocalClientFactory) Client(authToken string) (*client.APIClient, error) {\n\tpc, err := client.NewFromAddress(fmt.Sprintf(\"localhost:%d\", f.port))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif authToken != \"\" {\n\t\tpc.SetAuthToken(authToken)\n\t}\n\treturn pc, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package auth\n\nimport (\n\t\"encoding\/json\"\n\t\"mime\"\n\t\"net\/http\"\n\n\t\"github.com\/gorilla\/schema\"\n)\n\nvar formDecoder = schema.NewDecoder()\n\n\/\/ TODO support user defined expiration\ntype Credentials struct {\n\tUserName string `json:\"username\" schema:\"username\"`\n\tPassword string `json:\"password\" schema:\"password\"`\n}\n\ntype LoginResponse struct {\n\tToken     string    `json:\"token\"`\n\tUserID    string    `json:\"user_id\"`\n\tUserName  string    `json:\"user_name\"`\n\tExpiredAt Timestamp `json:\"expired_at\"`\n}\n\nfunc LoginHandler(config *Config) http.Handler {\n\tconfig = config.setDefaults()\n\treturn http.HandlerFunc(LoginHandlerFunc(config))\n}\n\nfunc LoginHandlerFunc(config *Config) http.HandlerFunc {\n\tconfig = config.setDefaults()\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tcred, err1 := decodeCredentials(w, r)\n\t\tif err1 != nil {\n\t\t\tSendError(w, err1)\n\t\t\treturn\n\t\t}\n\n\t\tuser, err2 := config.UserStore.ValidateCredentials(r.Context(), cred.UserName, cred.Password)\n\t\tif err2 != nil {\n\t\t\tSendError(w, ErrBadCredentials.WithCause(err2))\n\t\t\treturn\n\t\t}\n\n\t\tissuedAt := now()\n\t\ttoken := &Token{\n\t\t\tUserID:    user.GetID(),\n\t\t\tUserName:  user.GetName(),\n\t\t\tIssuedAt:  Timestamp(issuedAt),\n\t\t\tExpiredAt: Timestamp(issuedAt.Add(config.TokenExpiration)),\n\t\t\tClientIP:  getClientIP(r),\n\t\t\tClaims:    user.GetClaims(),\n\t\t}\n\n\t\ttokenString, err3 := token.Encode(config)\n\t\tif err3 != nil {\n\t\t\tSendError(w, err3)\n\t\t\treturn\n\t\t}\n\n\t\tSendJSON(w, &LoginResponse{\n\t\t\tToken:     tokenString,\n\t\t\tUserID:    token.UserID,\n\t\t\tUserName:  token.UserName,\n\t\t\tExpiredAt: token.ExpiredAt,\n\t\t})\n\t}\n}\n\nfunc decodeCredentials(w http.ResponseWriter, r *http.Request) (*Credentials, *Error) {\n\tif len(r.Header.Get(authorizationHeader)) > 0 {\n\t\tusername, password, ok := r.BasicAuth()\n\t\tif !ok {\n\t\t\treturn nil, ErrBadAuthorizationHeader\n\t\t}\n\t\treturn &Credentials{username, password}, nil\n\t}\n\n\tresult := &Credentials{}\n\terr := decodePayload(w, r, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\nfunc decodePayload(w http.ResponseWriter, r *http.Request, payload interface{}) *Error {\n\tcontentType := r.Header.Get(\"Content-Type\")\n\tmediaType, _, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\treturn ErrUnsupportedContentType.WithCause(err)\n\t}\n\n\tif mediaType == contentJSON {\n\t\terr = json.NewDecoder(r.Body).Decode(payload)\n\t\tif err != nil {\n\t\t\treturn ErrMalformedContent.WithCause(err)\n\t\t}\n\t\treturn nil\n\t}\n\n\tif mediaType == contentForm {\n\t\terr = r.ParseForm()\n\t\tif err != nil {\n\t\t\treturn ErrUnsupportedContentType.WithCause(err)\n\t\t}\n\t\terr = formDecoder.Decode(payload, r.PostForm)\n\t\tif err != nil {\n\t\t\treturn ErrMalformedContent.WithCause(err)\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn ErrUnsupportedContentType\n}\n<commit_msg>expose WriteLoginResponse<commit_after>package auth\n\nimport (\n\t\"encoding\/json\"\n\t\"mime\"\n\t\"net\/http\"\n\n\t\"github.com\/gorilla\/schema\"\n)\n\nvar formDecoder = schema.NewDecoder()\n\n\/\/ TODO support user defined expiration\ntype Credentials struct {\n\tUserName string `json:\"username\" schema:\"username\"`\n\tPassword string `json:\"password\" schema:\"password\"`\n}\n\ntype LoginResponse struct {\n\tToken     string    `json:\"token\"`\n\tUserID    string    `json:\"user_id\"`\n\tUserName  string    `json:\"user_name\"`\n\tExpiredAt Timestamp `json:\"expired_at\"`\n}\n\nfunc LoginHandler(config *Config) http.Handler {\n\tconfig = config.setDefaults()\n\treturn http.HandlerFunc(LoginHandlerFunc(config))\n}\n\nfunc LoginHandlerFunc(config *Config) http.HandlerFunc {\n\tconfig = config.setDefaults()\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tcred, err1 := decodeCredentials(w, r)\n\t\tif err1 != nil {\n\t\t\tSendError(w, err1)\n\t\t\treturn\n\t\t}\n\n\t\tuser, err2 := config.UserStore.ValidateCredentials(r.Context(), cred.UserName, cred.Password)\n\t\tif err2 != nil {\n\t\t\tSendError(w, ErrBadCredentials.WithCause(err2))\n\t\t\treturn\n\t\t}\n\n\t\tWriteLoginResponse(w, r, config, user)\n\t}\n}\n\nfunc WriteLoginResponse(w http.ResponseWriter, r *http.Request, config *Config, user User) {\n\tissuedAt := now()\n\ttoken := &Token{\n\t\tUserID:    user.GetID(),\n\t\tUserName:  user.GetName(),\n\t\tIssuedAt:  Timestamp(issuedAt),\n\t\tExpiredAt: Timestamp(issuedAt.Add(config.TokenExpiration)),\n\t\tClientIP:  getClientIP(r),\n\t\tClaims:    user.GetClaims(),\n\t}\n\n\ttokenString, err3 := token.Encode(config)\n\tif err3 != nil {\n\t\tSendError(w, err3)\n\t\treturn\n\t}\n\n\tSendJSON(w, &LoginResponse{\n\t\tToken:     tokenString,\n\t\tUserID:    token.UserID,\n\t\tUserName:  token.UserName,\n\t\tExpiredAt: token.ExpiredAt,\n\t})\n}\n\nfunc decodeCredentials(w http.ResponseWriter, r *http.Request) (*Credentials, *Error) {\n\tif len(r.Header.Get(authorizationHeader)) > 0 {\n\t\tusername, password, ok := r.BasicAuth()\n\t\tif !ok {\n\t\t\treturn nil, ErrBadAuthorizationHeader\n\t\t}\n\t\treturn &Credentials{username, password}, nil\n\t}\n\n\tresult := &Credentials{}\n\terr := decodePayload(w, r, result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}\n\nfunc decodePayload(w http.ResponseWriter, r *http.Request, payload interface{}) *Error {\n\tcontentType := r.Header.Get(\"Content-Type\")\n\tmediaType, _, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\treturn ErrUnsupportedContentType.WithCause(err)\n\t}\n\n\tif mediaType == contentJSON {\n\t\terr = json.NewDecoder(r.Body).Decode(payload)\n\t\tif err != nil {\n\t\t\treturn ErrMalformedContent.WithCause(err)\n\t\t}\n\t\treturn nil\n\t}\n\n\tif mediaType == contentForm {\n\t\terr = r.ParseForm()\n\t\tif err != nil {\n\t\t\treturn ErrUnsupportedContentType.WithCause(err)\n\t\t}\n\t\terr = formDecoder.Decode(payload, r.PostForm)\n\t\tif err != nil {\n\t\t\treturn ErrMalformedContent.WithCause(err)\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn ErrUnsupportedContentType\n}\n<|endoftext|>"}
{"text":"<commit_before>package logit\n\nimport (\n\t\"io\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ A Logger represents an active logging object that generates lines of output to an io.Writer. Each logging operation\n\/\/ makes a single call to the Writer's Write method. A Logger can be used simultaneously from multiple goroutines; it\n\/\/ guarantees to serialize access to the Writer.\ntype Logger struct {\n\tmu     *sync.Mutex            \/\/ ensures atomic writes; protects the following fields\n\tout    io.Writer              \/\/ destination for output\n\tsys    string                 \/\/ the sub-system to write at beginning of each line\n\tfields map[string]interface{} \/\/ the fields to also log\n}\n\nfunc New(out io.Writer, sys string) *Logger {\n\tmu := sync.Mutex{}\n\treturn &Logger{mu: &mu, out: out, sys: sys, fields: make(map[string]interface{})}\n}\n\n\/\/ Clone returns a new Logger which uses the same output but which has the system set to \"<current>.system\". e.g. if\n\/\/ you have a logger where has the \"main\" system, cloning it with the system \"datastore\" will result in the system\n\/\/ field being \"main.datastore\".\n\/\/\n\/\/ Since the cloned logger uses the same lock as the original, use of this lock also garantees serial access to the\n\/\/ Writer and therefore can also be used in multiple goroutines.\nfunc (l *Logger) Clone(sys string) *Logger {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\t\/\/ clone the l.fields here\n\tm := make(map[string]interface{})\n\tfor k, v := range l.fields {\n\t\tm[k] = v\n\t}\n\n\treturn &Logger{mu: l.mu, out: l.out, sys: l.sys + \".\" + sys, fields: m}\n}\n\nfunc (l *Logger) WithField(key string, value interface{}) {\n\tif key == \"time\" {\n\t\tpanic(\"logit: key=time is not allowed\")\n\t}\n\tif key == \"sys\" {\n\t\tpanic(\"logit: key=sys is not allowed\")\n\t}\n\tif key == \"msg\" {\n\t\tpanic(\"logit: key=msg is not allowed\")\n\t}\n\tif key == \"err\" {\n\t\tpanic(\"logit: key=err is not allowed\")\n\t}\n\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tl.fields[key] = value\n}\n\n\/\/ Log just logs a message to the output. It doesn't do anything special.\nfunc (l *Logger) Log(msg string) error {\n\treturn l.Output(msg)\n}\n\n\/\/ Output writes the output for a logging event.\nfunc (l *Logger) Output(msg string) error {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\t\/\/ time\n\tstr := \"time=\"\n\tstr += time.Now().UTC().Format(\"20060102-150405.000000000\")\n\tstr += \" \"\n\n\t\/\/ sys\n\tstr += \"sys=\" + l.sys + \" \"\n\n\t\/\/ now do all of the fields\n\tfor k, v := range l.fields {\n\t\tswitch vv := v.(type) {\n\t\tcase string:\n\t\t\t\/\/ ToDo: currently presuming everything is a string\n\t\t\tstr += k + \"=\" + vv + \" \"\n\t\tcase int:\n\t\t\tstr += k + \"=\" + strconv.Itoa(vv) + \" \"\n\t\tcase time.Duration:\n\t\t\tstr += k + \"=\" + vv.String() + \" \"\n\t\tdefault:\n\t\t\tstr += k + \"=\" + \"(unknown type) \"\n\t\t}\n\t}\n\n\t\/\/ message\n\tstr += \"msg=\" + msg\n\n\t\/\/ newline\n\tstr += \"\\n\"\n\n\t_, err := l.out.Write([]byte(str))\n\treturn err\n}\n\n\/\/ \/\/ SetOutput sets the output destination for the logger.\n\/\/ func (l *Logger) SetOutput(w io.Writer) {\n\/\/ \tl.mu.Lock()\n\/\/ \tdefer l.mu.Unlock()\n\/\/ \tl.out = w\n\/\/ }\n<commit_msg>Add Fatal() so we can quit too<commit_after>package logit\n\nimport (\n\t\"io\"\n\t\"os\"\n\t\"strconv\"\n\t\"sync\"\n\t\"time\"\n)\n\n\/\/ A Logger represents an active logging object that generates lines of output to an io.Writer. Each logging operation\n\/\/ makes a single call to the Writer's Write method. A Logger can be used simultaneously from multiple goroutines; it\n\/\/ guarantees to serialize access to the Writer.\ntype Logger struct {\n\tmu     *sync.Mutex            \/\/ ensures atomic writes; protects the following fields\n\tout    io.Writer              \/\/ destination for output\n\tsys    string                 \/\/ the sub-system to write at beginning of each line\n\tfields map[string]interface{} \/\/ the fields to also log\n}\n\nfunc New(out io.Writer, sys string) *Logger {\n\tmu := sync.Mutex{}\n\treturn &Logger{mu: &mu, out: out, sys: sys, fields: make(map[string]interface{})}\n}\n\n\/\/ Clone returns a new Logger which uses the same output but which has the system set to \"<current>.system\". e.g. if\n\/\/ you have a logger where has the \"main\" system, cloning it with the system \"datastore\" will result in the system\n\/\/ field being \"main.datastore\".\n\/\/\n\/\/ Since the cloned logger uses the same lock as the original, use of this lock also garantees serial access to the\n\/\/ Writer and therefore can also be used in multiple goroutines.\nfunc (l *Logger) Clone(sys string) *Logger {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\t\/\/ clone the l.fields here\n\tm := make(map[string]interface{})\n\tfor k, v := range l.fields {\n\t\tm[k] = v\n\t}\n\n\treturn &Logger{mu: l.mu, out: l.out, sys: l.sys + \".\" + sys, fields: m}\n}\n\nfunc (l *Logger) WithField(key string, value interface{}) {\n\tif key == \"time\" {\n\t\tpanic(\"logit: key=time is not allowed\")\n\t}\n\tif key == \"sys\" {\n\t\tpanic(\"logit: key=sys is not allowed\")\n\t}\n\tif key == \"msg\" {\n\t\tpanic(\"logit: key=msg is not allowed\")\n\t}\n\tif key == \"err\" {\n\t\tpanic(\"logit: key=err is not allowed\")\n\t}\n\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\tl.fields[key] = value\n}\n\n\/\/ Log just logs a message to the output. It doesn't do anything special.\nfunc (l *Logger) Log(msg string) error {\n\treturn l.Output(msg)\n}\n\n\/\/ Fatal is equivalent to Log() followed by a call to os.Exit(1).\nfunc (l *Logger) Fatal(msg string) {\n\tl.Output(msg)\n\tos.Exit(1)\n}\n\n\/\/ Output writes the output for a logging event.\nfunc (l *Logger) Output(msg string) error {\n\tl.mu.Lock()\n\tdefer l.mu.Unlock()\n\n\t\/\/ time\n\tstr := \"time=\"\n\tstr += time.Now().UTC().Format(\"20060102-150405.000000000\")\n\tstr += \" \"\n\n\t\/\/ sys\n\tstr += \"sys=\" + l.sys + \" \"\n\n\t\/\/ now do all of the fields\n\tfor k, v := range l.fields {\n\t\tswitch vv := v.(type) {\n\t\tcase string:\n\t\t\t\/\/ ToDo: currently presuming everything is a string\n\t\t\tstr += k + \"=\" + vv + \" \"\n\t\tcase int:\n\t\t\tstr += k + \"=\" + strconv.Itoa(vv) + \" \"\n\t\tcase time.Duration:\n\t\t\tstr += k + \"=\" + vv.String() + \" \"\n\t\tdefault:\n\t\t\tstr += k + \"=\" + \"(unknown type) \"\n\t\t}\n\t}\n\n\t\/\/ message\n\tstr += \"msg=\" + msg\n\n\t\/\/ newline\n\tstr += \"\\n\"\n\n\t_, err := l.out.Write([]byte(str))\n\treturn err\n}\n\n\/\/ \/\/ SetOutput sets the output destination for the logger.\n\/\/ func (l *Logger) SetOutput(w io.Writer) {\n\/\/ \tl.mu.Lock()\n\/\/ \tdefer l.mu.Unlock()\n\/\/ \tl.out = w\n\/\/ }\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\tconsumergroup \"github.com\/meitu\/go-consumergroup\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/meitu\/zk_wrapper\"\n)\n\nfunc TestRebalance(t *testing.T) {\n\tgroup := genRandomGroupID(10)\n\tconsumers := make([]*consumergroup.ConsumerGroup, 0)\n\tfor i := 0; i < 3; i++ {\n\t\tgo func() {\n\t\t\tc, err := createConsumerInstance(zookeepers, group, topic)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Failed to create consumer instance, err %s\", err)\n\t\t\t}\n\t\t\tconsumers = append(consumers, c)\n\t\t}()\n\t}\n\ttime.Sleep(3 * time.Second) \/\/ we have no way to know if the consumer is ready\n\n\tkafkaCli, _ := sarama.NewClient(brokers, nil)\n\tpartitions, err := kafkaCli.Partitions(topic)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to get partitons, err %s\", err)\n\t}\n\towners := make([]string, 0)\n\tzkCli, _, err := zk_wrapper.Connect(zookeepers, 6*time.Second)\n\tif err != nil {\n\t\tt.Fatal(\"Failed to connect zookeeper\")\n\t}\n\tfor i := 0; i < len(partitions); i++ {\n\t\townerPath := fmt.Sprintf(\"\/consumers\/%s\/owners\/%s\/%d\", group, topic, i)\n\t\tdata, _, err := zkCli.Get(ownerPath)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to get partition owner, err %s\", err)\n\t\t}\n\t\towners = append(owners, string(data))\n\t}\n\tif len(owners) != len(partitions) {\n\t\tt.Errorf(\"Missing owner in some partitions expected %d, but got %d\",\n\t\t\tlen(partitions), len(owners))\n\t}\n\tfor i := 1; i < len(owners); i++ {\n\t\tif owners[i] == owners[i-1] {\n\t\t\tt.Fatal(\"Partition owner should be difference while consumer > 1\")\n\t\t}\n\t}\n\n\tfor _, c := range consumers {\n\t\tc.ExitGroup()\n\t}\n}\n<commit_msg>FIX: rebalance_test can't exit group while the consumer is rebalancing<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\tconsumergroup \"github.com\/meitu\/go-consumergroup\"\n\n\t\"github.com\/Shopify\/sarama\"\n\t\"github.com\/meitu\/zk_wrapper\"\n)\n\nfunc TestRebalance(t *testing.T) {\n\tgroup := genRandomGroupID(10)\n\tconsumers := make([]*consumergroup.ConsumerGroup, 0)\n\tfor i := 0; i < 3; i++ {\n\t\tgo func() {\n\t\t\tc, err := createConsumerInstance(zookeepers, group, topic)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Failed to create consumer instance, err %s\", err)\n\t\t\t}\n\t\t\tconsumers = append(consumers, c)\n\t\t}()\n\t}\n\ttime.Sleep(3 * time.Second) \/\/ we have no way to know if the consumer is ready\n\n\tkafkaCli, _ := sarama.NewClient(brokers, nil)\n\tpartitions, err := kafkaCli.Partitions(topic)\n\tif err != nil {\n\t\tt.Errorf(\"Failed to get partitons, err %s\", err)\n\t}\n\towners := make([]string, 0)\n\tzkCli, _, err := zk_wrapper.Connect(zookeepers, 6*time.Second)\n\tif err != nil {\n\t\tt.Fatal(\"Failed to connect zookeeper\")\n\t}\n\tfor i := 0; i < len(partitions); i++ {\n\t\townerPath := fmt.Sprintf(\"\/consumers\/%s\/owners\/%s\/%d\", group, topic, i)\n\t\tdata, _, err := zkCli.Get(ownerPath)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Failed to get partition owner, err %s\", err)\n\t\t}\n\t\towners = append(owners, string(data))\n\t}\n\tif len(owners) != len(partitions) {\n\t\tt.Errorf(\"Missing owner in some partitions expected %d, but got %d\",\n\t\t\tlen(partitions), len(owners))\n\t}\n\tfor i := 1; i < len(owners); i++ {\n\t\tif owners[i] == owners[i-1] {\n\t\t\tt.Fatal(\"Partition owner should be difference while consumer > 1\")\n\t\t}\n\t}\n\n\tfor _, c := range consumers {\n\t\tc.ExitGroup()\n\t\t\/\/ no way to exit group when the consumer is rebalancing\n\t\ttime.Sleep(3 * time.Second)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ eventmeter - generic system to subscribe to events and record their frequency.\npackage eventmeter\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\tmetrics \"github.com\/rcrowley\/go-metrics\"\n\tclient \"github.com\/tendermint\/tendermint\/rpc\/lib\/client\"\n\t\"github.com\/tendermint\/tmlibs\/events\"\n\t\"github.com\/tendermint\/tmlibs\/log\"\n)\n\nconst (\n\t\/\/ Get ping\/pong latency and call LatencyCallbackFunc with this period.\n\tlatencyPeriod = 1 * time.Second\n\n\t\/\/ Check if the WS client is connected every\n\tconnectionCheckPeriod = 100 * time.Millisecond\n)\n\n\/\/ EventMetric exposes metrics for an event.\ntype EventMetric struct {\n\tID          string    `json:\"id\"`\n\tStarted     time.Time `json:\"start_time\"`\n\tLastHeard   time.Time `json:\"last_heard\"`\n\tMinDuration int64     `json:\"min_duration\"`\n\tMaxDuration int64     `json:\"max_duration\"`\n\n\t\/\/ tracks event count and rate\n\tmeter metrics.Meter\n\n\t\/\/ filled in from the Meter\n\tCount    int64   `json:\"count\"`\n\tRate1    float64 `json:\"rate_1\" wire:\"unsafe\"`\n\tRate5    float64 `json:\"rate_5\" wire:\"unsafe\"`\n\tRate15   float64 `json:\"rate_15\" wire:\"unsafe\"`\n\tRateMean float64 `json:\"rate_mean\" wire:\"unsafe\"`\n\n\t\/\/ so the event can have effects in the eventmeter's consumer. runs in a go\n\t\/\/ routine.\n\tcallback EventCallbackFunc\n}\n\nfunc (metric *EventMetric) Copy() *EventMetric {\n\tmetricCopy := *metric\n\tmetricCopy.meter = metric.meter.Snapshot()\n\treturn &metricCopy\n}\n\n\/\/ called on GetMetric\nfunc (metric *EventMetric) fillMetric() *EventMetric {\n\tmetric.Count = metric.meter.Count()\n\tmetric.Rate1 = metric.meter.Rate1()\n\tmetric.Rate5 = metric.meter.Rate5()\n\tmetric.Rate15 = metric.meter.Rate15()\n\tmetric.RateMean = metric.meter.RateMean()\n\treturn metric\n}\n\n\/\/ EventCallbackFunc is a closure to enable side effects from receiving an\n\/\/ event.\ntype EventCallbackFunc func(em *EventMetric, data interface{})\n\n\/\/ EventUnmarshalFunc is a closure to get the query and data out of the raw\n\/\/ JSON received over the RPC WebSocket.\ntype EventUnmarshalFunc func(b json.RawMessage) (string, events.EventData, error)\n\n\/\/ LatencyCallbackFunc is a closure to enable side effects from receiving a latency.\ntype LatencyCallbackFunc func(meanLatencyNanoSeconds float64)\n\n\/\/ DisconnectCallbackFunc is a closure to notify a consumer that the connection\n\/\/ has died.\ntype DisconnectCallbackFunc func()\n\n\/\/ EventMeter tracks events, reports latency and disconnects.\ntype EventMeter struct {\n\twsc *client.WSClient\n\n\tmtx    sync.Mutex\n\tqueries map[string]*EventMetric\n\n\tunmarshalEvent     EventUnmarshalFunc\n\tlatencyCallback    LatencyCallbackFunc\n\tdisconnectCallback DisconnectCallbackFunc\n\tsubscribed         bool\n\n\tquit chan struct{}\n\n\tlogger log.Logger\n}\n\nfunc NewEventMeter(addr string, unmarshalEvent EventUnmarshalFunc) *EventMeter {\n\treturn &EventMeter{\n\t\twsc:            client.NewWSClient(addr, \"\/websocket\", client.PingPeriod(1*time.Second)),\n\t\tqueries:         make(map[string]*EventMetric),\n\t\tunmarshalEvent: unmarshalEvent,\n\t\tlogger:         log.NewNopLogger(),\n\t}\n}\n\n\/\/ SetLogger lets you set your own logger.\nfunc (em *EventMeter) SetLogger(l log.Logger) {\n\tem.logger = l\n\tem.wsc.SetLogger(l.With(\"module\", \"rpcclient\"))\n}\n\n\/\/ String returns a string representation of event meter.\nfunc (em *EventMeter) String() string {\n\treturn em.wsc.Address\n}\n\n\/\/ Start boots up event meter.\nfunc (em *EventMeter) Start() error {\n\tif err := em.wsc.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tem.quit = make(chan struct{})\n\tgo em.receiveRoutine()\n\tgo em.disconnectRoutine()\n\n\terr := em.subscribe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tem.subscribed = true\n\treturn nil\n}\n\n\/\/ Stop stops event meter.\nfunc (em *EventMeter) Stop() {\n\tclose(em.quit)\n\n\tif em.wsc.IsRunning() {\n\t\tem.wsc.Stop()\n\t}\n}\n\n\/\/ Subscribe for the given query. Callback function will be called upon\n\/\/ receiving an event.\nfunc (em *EventMeter) Subscribe(query string, cb EventCallbackFunc) error {\n\tem.mtx.Lock()\n\tdefer em.mtx.Unlock()\n\n\tif err := em.wsc.Subscribe(context.TODO(), query); err != nil {\n\t\treturn err\n\t}\n\n\tmetric := &EventMetric{\n\t\tmeter:    metrics.NewMeter(),\n\t\tcallback: cb,\n\t}\n\tem.queries[query] = metric\n\treturn nil\n}\n\n\/\/ Unsubscribe from the given query.\nfunc (em *EventMeter) Unsubscribe(query string) error {\n\tem.mtx.Lock()\n\tdefer em.mtx.Unlock()\n\tif err := em.wsc.Unsubscribe(context.TODO(), query); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ GetMetric fills in the latest data for an query and return a copy.\nfunc (em *EventMeter) GetMetric(query string) (*EventMetric, error) {\n\tem.mtx.Lock()\n\tdefer em.mtx.Unlock()\n\tmetric, ok := em.queries[query]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unknown query: %s\", query)\n\t}\n\treturn metric.fillMetric().Copy(), nil\n}\n\n\/\/ RegisterLatencyCallback allows you to set latency callback.\nfunc (em *EventMeter) RegisterLatencyCallback(f LatencyCallbackFunc) {\n\tem.mtx.Lock()\n\tdefer em.mtx.Unlock()\n\tem.latencyCallback = f\n}\n\n\/\/ RegisterDisconnectCallback allows you to set disconnect callback.\nfunc (em *EventMeter) RegisterDisconnectCallback(f DisconnectCallbackFunc) {\n\tem.mtx.Lock()\n\tdefer em.mtx.Unlock()\n\tem.disconnectCallback = f\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Private\n\nfunc (em *EventMeter) subscribe() error {\n\tfor query, _ := range em.queries {\n\t\tif err := em.wsc.Subscribe(context.TODO(), query); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (em *EventMeter) receiveRoutine() {\n\tlatencyTicker := time.NewTicker(latencyPeriod)\n\tfor {\n\t\tselect {\n\t\tcase resp := <-em.wsc.ResponsesCh:\n\t\t\tif resp.Error != nil {\n\t\t\t\tem.logger.Error(\"expected some event, got error\", \"err\", resp.Error.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tquery, data, err := em.unmarshalEvent(resp.Result)\n\t\t\tif err != nil {\n\t\t\t\tem.logger.Error(\"failed to unmarshal event\", \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif query != \"\" { \/\/ FIXME how can it be an empty string?\n\t\t\t\tem.updateMetric(query, data)\n\t\t\t}\n\t\tcase <-latencyTicker.C:\n\t\t\tif em.wsc.IsActive() {\n\t\t\t\tem.callLatencyCallback(em.wsc.PingPongLatencyTimer.Mean())\n\t\t\t}\n\t\tcase <-em.wsc.Quit():\n\t\t\treturn\n\t\tcase <-em.quit:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (em *EventMeter) disconnectRoutine() {\n\tticker := time.NewTicker(connectionCheckPeriod)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif em.wsc.IsReconnecting() && em.subscribed { \/\/ notify user about disconnect only once\n\t\t\t\tem.callDisconnectCallback()\n\t\t\t\tem.subscribed = false\n\t\t\t} else if !em.wsc.IsReconnecting() && !em.subscribed { \/\/ resubscribe\n\t\t\t\tem.subscribe()\n\t\t\t\tem.subscribed = true\n\t\t\t}\n\t\tcase <-em.wsc.Quit():\n\t\t\treturn\n\t\tcase <-em.quit:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (em *EventMeter) updateMetric(query string, data events.EventData) {\n\tem.mtx.Lock()\n\tdefer em.mtx.Unlock()\n\n\tmetric, ok := em.queries[query]\n\tif !ok {\n\t\t\/\/ we already unsubscribed, or got an unexpected query\n\t\treturn\n\t}\n\n\tlast := metric.LastHeard\n\tmetric.LastHeard = time.Now()\n\tmetric.meter.Mark(1)\n\tdur := int64(metric.LastHeard.Sub(last))\n\tif dur < metric.MinDuration {\n\t\tmetric.MinDuration = dur\n\t}\n\tif !last.IsZero() && dur > metric.MaxDuration {\n\t\tmetric.MaxDuration = dur\n\t}\n\n\tif metric.callback != nil {\n\t\tgo metric.callback(metric.Copy(), data)\n\t}\n}\n\nfunc (em *EventMeter) callDisconnectCallback() {\n\tem.mtx.Lock()\n\tif em.disconnectCallback != nil {\n\t\tgo em.disconnectCallback()\n\t}\n\tem.mtx.Unlock()\n}\n\nfunc (em *EventMeter) callLatencyCallback(meanLatencyNanoSeconds float64) {\n\tem.mtx.Lock()\n\tif em.latencyCallback != nil {\n\t\tgo em.latencyCallback(meanLatencyNanoSeconds)\n\t}\n\tem.mtx.Unlock()\n}\n<commit_msg>Rename queries to queryToMetricMap<commit_after>\/\/ eventmeter - generic system to subscribe to events and record their frequency.\npackage eventmeter\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\tmetrics \"github.com\/rcrowley\/go-metrics\"\n\tclient \"github.com\/tendermint\/tendermint\/rpc\/lib\/client\"\n\t\"github.com\/tendermint\/tmlibs\/events\"\n\t\"github.com\/tendermint\/tmlibs\/log\"\n)\n\nconst (\n\t\/\/ Get ping\/pong latency and call LatencyCallbackFunc with this period.\n\tlatencyPeriod = 1 * time.Second\n\n\t\/\/ Check if the WS client is connected every\n\tconnectionCheckPeriod = 100 * time.Millisecond\n)\n\n\/\/ EventMetric exposes metrics for an event.\ntype EventMetric struct {\n\tID          string    `json:\"id\"`\n\tStarted     time.Time `json:\"start_time\"`\n\tLastHeard   time.Time `json:\"last_heard\"`\n\tMinDuration int64     `json:\"min_duration\"`\n\tMaxDuration int64     `json:\"max_duration\"`\n\n\t\/\/ tracks event count and rate\n\tmeter metrics.Meter\n\n\t\/\/ filled in from the Meter\n\tCount    int64   `json:\"count\"`\n\tRate1    float64 `json:\"rate_1\" wire:\"unsafe\"`\n\tRate5    float64 `json:\"rate_5\" wire:\"unsafe\"`\n\tRate15   float64 `json:\"rate_15\" wire:\"unsafe\"`\n\tRateMean float64 `json:\"rate_mean\" wire:\"unsafe\"`\n\n\t\/\/ so the event can have effects in the eventmeter's consumer. runs in a go\n\t\/\/ routine.\n\tcallback EventCallbackFunc\n}\n\nfunc (metric *EventMetric) Copy() *EventMetric {\n\tmetricCopy := *metric\n\tmetricCopy.meter = metric.meter.Snapshot()\n\treturn &metricCopy\n}\n\n\/\/ called on GetMetric\nfunc (metric *EventMetric) fillMetric() *EventMetric {\n\tmetric.Count = metric.meter.Count()\n\tmetric.Rate1 = metric.meter.Rate1()\n\tmetric.Rate5 = metric.meter.Rate5()\n\tmetric.Rate15 = metric.meter.Rate15()\n\tmetric.RateMean = metric.meter.RateMean()\n\treturn metric\n}\n\n\/\/ EventCallbackFunc is a closure to enable side effects from receiving an\n\/\/ event.\ntype EventCallbackFunc func(em *EventMetric, data interface{})\n\n\/\/ EventUnmarshalFunc is a closure to get the query and data out of the raw\n\/\/ JSON received over the RPC WebSocket.\ntype EventUnmarshalFunc func(b json.RawMessage) (string, events.EventData, error)\n\n\/\/ LatencyCallbackFunc is a closure to enable side effects from receiving a latency.\ntype LatencyCallbackFunc func(meanLatencyNanoSeconds float64)\n\n\/\/ DisconnectCallbackFunc is a closure to notify a consumer that the connection\n\/\/ has died.\ntype DisconnectCallbackFunc func()\n\n\/\/ EventMeter tracks events, reports latency and disconnects.\ntype EventMeter struct {\n\twsc *client.WSClient\n\n\tmtx    sync.Mutex\n\tqueryToMetricMap map[string]*EventMetric\n\n\tunmarshalEvent     EventUnmarshalFunc\n\tlatencyCallback    LatencyCallbackFunc\n\tdisconnectCallback DisconnectCallbackFunc\n\tsubscribed         bool\n\n\tquit chan struct{}\n\n\tlogger log.Logger\n}\n\nfunc NewEventMeter(addr string, unmarshalEvent EventUnmarshalFunc) *EventMeter {\n\treturn &EventMeter{\n\t\twsc:            client.NewWSClient(addr, \"\/websocket\", client.PingPeriod(1*time.Second)),\n\t\tqueryToMetricMap:         make(map[string]*EventMetric),\n\t\tunmarshalEvent: unmarshalEvent,\n\t\tlogger:         log.NewNopLogger(),\n\t}\n}\n\n\/\/ SetLogger lets you set your own logger.\nfunc (em *EventMeter) SetLogger(l log.Logger) {\n\tem.logger = l\n\tem.wsc.SetLogger(l.With(\"module\", \"rpcclient\"))\n}\n\n\/\/ String returns a string representation of event meter.\nfunc (em *EventMeter) String() string {\n\treturn em.wsc.Address\n}\n\n\/\/ Start boots up event meter.\nfunc (em *EventMeter) Start() error {\n\tif err := em.wsc.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tem.quit = make(chan struct{})\n\tgo em.receiveRoutine()\n\tgo em.disconnectRoutine()\n\n\terr := em.subscribe()\n\tif err != nil {\n\t\treturn err\n\t}\n\tem.subscribed = true\n\treturn nil\n}\n\n\/\/ Stop stops event meter.\nfunc (em *EventMeter) Stop() {\n\tclose(em.quit)\n\n\tif em.wsc.IsRunning() {\n\t\tem.wsc.Stop()\n\t}\n}\n\n\/\/ Subscribe for the given query. Callback function will be called upon\n\/\/ receiving an event.\nfunc (em *EventMeter) Subscribe(query string, cb EventCallbackFunc) error {\n\tem.mtx.Lock()\n\tdefer em.mtx.Unlock()\n\n\tif err := em.wsc.Subscribe(context.TODO(), query); err != nil {\n\t\treturn err\n\t}\n\n\tmetric := &EventMetric{\n\t\tmeter:    metrics.NewMeter(),\n\t\tcallback: cb,\n\t}\n\tem.queryToMetricMap[query] = metric\n\treturn nil\n}\n\n\/\/ Unsubscribe from the given query.\nfunc (em *EventMeter) Unsubscribe(query string) error {\n\tem.mtx.Lock()\n\tdefer em.mtx.Unlock()\n\tif err := em.wsc.Unsubscribe(context.TODO(), query); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ GetMetric fills in the latest data for an query and return a copy.\nfunc (em *EventMeter) GetMetric(query string) (*EventMetric, error) {\n\tem.mtx.Lock()\n\tdefer em.mtx.Unlock()\n\tmetric, ok := em.queryToMetricMap[query]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unknown query: %s\", query)\n\t}\n\treturn metric.fillMetric().Copy(), nil\n}\n\n\/\/ RegisterLatencyCallback allows you to set latency callback.\nfunc (em *EventMeter) RegisterLatencyCallback(f LatencyCallbackFunc) {\n\tem.mtx.Lock()\n\tdefer em.mtx.Unlock()\n\tem.latencyCallback = f\n}\n\n\/\/ RegisterDisconnectCallback allows you to set disconnect callback.\nfunc (em *EventMeter) RegisterDisconnectCallback(f DisconnectCallbackFunc) {\n\tem.mtx.Lock()\n\tdefer em.mtx.Unlock()\n\tem.disconnectCallback = f\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Private\n\nfunc (em *EventMeter) subscribe() error {\n\tfor query, _ := range em.queryToMetricMap {\n\t\tif err := em.wsc.Subscribe(context.TODO(), query); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (em *EventMeter) receiveRoutine() {\n\tlatencyTicker := time.NewTicker(latencyPeriod)\n\tfor {\n\t\tselect {\n\t\tcase resp := <-em.wsc.ResponsesCh:\n\t\t\tif resp.Error != nil {\n\t\t\t\tem.logger.Error(\"expected some event, got error\", \"err\", resp.Error.Error())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tquery, data, err := em.unmarshalEvent(resp.Result)\n\t\t\tif err != nil {\n\t\t\t\tem.logger.Error(\"failed to unmarshal event\", \"err\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif query != \"\" { \/\/ FIXME how can it be an empty string?\n\t\t\t\tem.updateMetric(query, data)\n\t\t\t}\n\t\tcase <-latencyTicker.C:\n\t\t\tif em.wsc.IsActive() {\n\t\t\t\tem.callLatencyCallback(em.wsc.PingPongLatencyTimer.Mean())\n\t\t\t}\n\t\tcase <-em.wsc.Quit():\n\t\t\treturn\n\t\tcase <-em.quit:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (em *EventMeter) disconnectRoutine() {\n\tticker := time.NewTicker(connectionCheckPeriod)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif em.wsc.IsReconnecting() && em.subscribed { \/\/ notify user about disconnect only once\n\t\t\t\tem.callDisconnectCallback()\n\t\t\t\tem.subscribed = false\n\t\t\t} else if !em.wsc.IsReconnecting() && !em.subscribed { \/\/ resubscribe\n\t\t\t\tem.subscribe()\n\t\t\t\tem.subscribed = true\n\t\t\t}\n\t\tcase <-em.wsc.Quit():\n\t\t\treturn\n\t\tcase <-em.quit:\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (em *EventMeter) updateMetric(query string, data events.EventData) {\n\tem.mtx.Lock()\n\tdefer em.mtx.Unlock()\n\n\tmetric, ok := em.queryToMetricMap[query]\n\tif !ok {\n\t\t\/\/ we already unsubscribed, or got an unexpected query\n\t\treturn\n\t}\n\n\tlast := metric.LastHeard\n\tmetric.LastHeard = time.Now()\n\tmetric.meter.Mark(1)\n\tdur := int64(metric.LastHeard.Sub(last))\n\tif dur < metric.MinDuration {\n\t\tmetric.MinDuration = dur\n\t}\n\tif !last.IsZero() && dur > metric.MaxDuration {\n\t\tmetric.MaxDuration = dur\n\t}\n\n\tif metric.callback != nil {\n\t\tgo metric.callback(metric.Copy(), data)\n\t}\n}\n\nfunc (em *EventMeter) callDisconnectCallback() {\n\tem.mtx.Lock()\n\tif em.disconnectCallback != nil {\n\t\tgo em.disconnectCallback()\n\t}\n\tem.mtx.Unlock()\n}\n\nfunc (em *EventMeter) callLatencyCallback(meanLatencyNanoSeconds float64) {\n\tem.mtx.Lock()\n\tif em.latencyCallback != nil {\n\t\tgo em.latencyCallback(meanLatencyNanoSeconds)\n\t}\n\tem.mtx.Unlock()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage expressions\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/pingcap\/tidb\/context\"\n\t\"github.com\/pingcap\/tidb\/expression\"\n\t\"github.com\/pingcap\/tidb\/plan\"\n\t\"github.com\/pingcap\/tidb\/stmt\"\n)\n\n\/\/ SubQueryStatement implements stmt.Statement and plan.Planner interface.\ntype SubQueryStatement interface {\n\tstmt.Statement\n\tplan.Planner\n}\n\nvar _ expression.Expression = (*SubQuery)(nil)\n\n\/\/ SubQuery expresion holds a select statement.\n\/\/ TODO: complete according to https:\/\/dev.mysql.com\/doc\/refman\/5.7\/en\/subquery-restrictions.html\ntype SubQuery struct {\n\t\/\/ Stmt is the sub select statement.\n\tStmt SubQueryStatement\n\t\/\/ Value holds the sub select result.\n\tValue interface{}\n\n\t\/\/ UseOuterQuery represents that whether subquery uses reference to a table for the outer query.\n\t\/\/ If use, we cannot cache the sub query result.\n\tUseOuterQuery bool\n\n\tp plan.Plan\n}\n\n\/\/ Clone implements the Expression Clone interface.\nfunc (sq *SubQuery) Clone() (expression.Expression, error) {\n\tnsq := &SubQuery{Stmt: sq.Stmt, Value: sq.Value, p: sq.p, UseOuterQuery: sq.UseOuterQuery}\n\treturn nsq, nil\n}\n\n\/\/ Eval implements the Expression Eval interface.\n\/\/ Eval doesn't support multi rows return, so we can only get a scalar or a row result.\n\/\/ If you want to get multi rows, use EvalRows instead.\nfunc (sq *SubQuery) Eval(ctx context.Context, args map[interface{}]interface{}) (v interface{}, err error) {\n\tif !sq.UseOuterQuery && sq.Value != nil {\n\t\treturn sq.Value, nil\n\t}\n\n\trows, err := sq.EvalRows(ctx, args, 2)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tswitch len(rows) {\n\tcase 0:\n\t\treturn nil, nil\n\tcase 1:\n\t\tsq.Value = rows[0]\n\t\treturn sq.Value, nil\n\tdefault:\n\t\treturn nil, errors.Errorf(\"Subquery returns more than 1 row\")\n\t}\n}\n\n\/\/ IsStatic implements the Expression IsStatic interface, always returns false.\nfunc (sq *SubQuery) IsStatic() bool {\n\treturn false\n}\n\n\/\/ String implements the Expression String interface.\nfunc (sq *SubQuery) String() string {\n\tif sq.Stmt != nil {\n\t\tstmtStr := strings.TrimSuffix(sq.Stmt.OriginText(), \";\")\n\t\treturn fmt.Sprintf(\"(%s)\", stmtStr)\n\t}\n\treturn \"\"\n}\n\n\/\/ ColumnCount returns column count for the sub query.\nfunc (sq *SubQuery) ColumnCount(ctx context.Context) (int, error) {\n\tp, err := sq.Plan(ctx)\n\tif err != nil {\n\t\treturn 0, errors.Trace(err)\n\t}\n\treturn len(p.GetFields()), nil\n}\n\n\/\/ Plan implements plan.Planner interface.\nfunc (sq *SubQuery) Plan(ctx context.Context) (plan.Plan, error) {\n\tif sq.p != nil {\n\t\treturn sq.p, nil\n\t}\n\n\tvar err error\n\tsq.p, err = sq.Stmt.Plan(ctx)\n\treturn sq.p, errors.Trace(err)\n}\n\n\/\/ EvalRows executes the subquery and returns the multi rows with rowCount.\n\/\/ rowCount < 0 means no limit.\n\/\/ if the ColumnCount is 1, we will return a column result like {1, 2, 3}\n\/\/ otherwise, we will return a table result like {{1, 1}, {2, 2}}\nfunc (sq *SubQuery) EvalRows(ctx context.Context, args map[interface{}]interface{}, rowCount int) ([]interface{}, error) {\n\tp, err := sq.Plan(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tdefer p.Close()\n\n\tsq.push(ctx)\n\n\tvar (\n\t\trow *plan.Row\n\t\tres = []interface{}{}\n\t)\n\n\tfor rowCount != 0 {\n\t\trow, err = p.Next(ctx)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif row == nil {\n\t\t\tbreak\n\t\t}\n\t\tif len(row.Data) == 1 {\n\t\t\tres = append(res, row.Data[0])\n\t\t} else {\n\t\t\tres = append(res, row.Data)\n\t\t}\n\n\t\tif rowCount > 0 {\n\t\t\trowCount--\n\t\t}\n\t}\n\n\terr0 := sq.pop(ctx)\n\tif err0 != nil {\n\t\treturn res, errors.Trace(err0)\n\t}\n\n\treturn res, errors.Trace(err)\n}\n\n\/\/ A dummy type to avoid naming collision in context.\ntype subQueryStackKeyType int\n\n\/\/ String defines a Stringer function for debugging and pretty printing.\nfunc (k subQueryStackKeyType) String() string {\n\treturn \"sub query stack\"\n}\n\n\/\/ subQueryStackKey holds the running sub query's stack.\nconst subQueryStackKey subQueryStackKeyType = 0\n\nfunc (sq *SubQuery) push(ctx context.Context) {\n\tvar st []*SubQuery\n\tv := ctx.Value(subQueryStackKey)\n\tif v == nil {\n\t\tst = []*SubQuery{}\n\t} else {\n\t\t\/\/ must ok\n\t\tst = v.([]*SubQuery)\n\t}\n\n\tst = append(st, sq)\n\tctx.SetValue(subQueryStackKey, st)\n}\n\nfunc (sq *SubQuery) pop(ctx context.Context) error {\n\tv := ctx.Value(subQueryStackKey)\n\tif v == nil {\n\t\treturn errors.Errorf(\"pop empty sub query stack\")\n\t}\n\n\tst := v.([]*SubQuery)\n\n\t\/\/ can not empty\n\tn := len(st) - 1\n\tif st[n] != sq {\n\t\treturn errors.Errorf(\"pop invalid top sub query in stack, want %v, but top is %v\", sq, st[n])\n\t}\n\n\tst[n] = nil\n\tst = st[0:n]\n\tif len(st) == 0 {\n\t\tctx.ClearValue(subQueryStackKey)\n\t\treturn nil\n\t}\n\n\tctx.SetValue(subQueryStackKey, st)\n\treturn nil\n}\n\n\/\/ SetOuterQueryUsed is called when current running subquery uses outer query.\nfunc SetOuterQueryUsed(ctx context.Context) {\n\tv := ctx.Value(subQueryStackKey)\n\tif v == nil {\n\t\treturn\n\t}\n\n\tst := v.([]*SubQuery)\n\n\t\/\/ if current sub query uses outer query, the select result can not be cached,\n\t\/\/ at the same time, all the upper sub query must not cache the result too.\n\tfor i := len(st) - 1; i >= 0; i-- {\n\t\tst[i].UseOuterQuery = true\n\t}\n}\n<commit_msg>expressions: Address comment<commit_after>\/\/ Copyright 2015 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage expressions\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/pingcap\/tidb\/context\"\n\t\"github.com\/pingcap\/tidb\/expression\"\n\t\"github.com\/pingcap\/tidb\/plan\"\n\t\"github.com\/pingcap\/tidb\/stmt\"\n)\n\n\/\/ SubQueryStatement implements stmt.Statement and plan.Planner interface.\ntype SubQueryStatement interface {\n\tstmt.Statement\n\tplan.Planner\n}\n\nvar _ expression.Expression = (*SubQuery)(nil)\n\n\/\/ SubQuery expresion holds a select statement.\n\/\/ TODO: complete according to https:\/\/dev.mysql.com\/doc\/refman\/5.7\/en\/subquery-restrictions.html\ntype SubQuery struct {\n\t\/\/ Stmt is the sub select statement.\n\tStmt SubQueryStatement\n\t\/\/ Value holds the sub select result.\n\tValue interface{}\n\n\t\/\/ UseOuterQuery represents that whether subquery uses reference to a table for the outer query.\n\t\/\/ If use, we cannot cache the sub query result.\n\tUseOuterQuery bool\n\n\tp plan.Plan\n}\n\n\/\/ Clone implements the Expression Clone interface.\nfunc (sq *SubQuery) Clone() (expression.Expression, error) {\n\tnsq := &SubQuery{Stmt: sq.Stmt, Value: sq.Value, p: sq.p, UseOuterQuery: sq.UseOuterQuery}\n\treturn nsq, nil\n}\n\n\/\/ Eval implements the Expression Eval interface.\n\/\/ Eval doesn't support multi rows return, so we can only get a scalar or a row result.\n\/\/ If you want to get multi rows, use EvalRows instead.\nfunc (sq *SubQuery) Eval(ctx context.Context, args map[interface{}]interface{}) (v interface{}, err error) {\n\tif !sq.UseOuterQuery && sq.Value != nil {\n\t\treturn sq.Value, nil\n\t}\n\n\trows, err := sq.EvalRows(ctx, args, 2)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\tswitch len(rows) {\n\tcase 0:\n\t\treturn nil, nil\n\tcase 1:\n\t\tsq.Value = rows[0]\n\t\treturn sq.Value, nil\n\tdefault:\n\t\treturn nil, errors.Errorf(\"Subquery returns more than 1 row\")\n\t}\n}\n\n\/\/ IsStatic implements the Expression IsStatic interface, always returns false.\nfunc (sq *SubQuery) IsStatic() bool {\n\treturn false\n}\n\n\/\/ String implements the Expression String interface.\nfunc (sq *SubQuery) String() string {\n\tif sq.Stmt != nil {\n\t\tstmtStr := strings.TrimSuffix(sq.Stmt.OriginText(), \";\")\n\t\treturn fmt.Sprintf(\"(%s)\", stmtStr)\n\t}\n\treturn \"\"\n}\n\n\/\/ ColumnCount returns column count for the sub query.\nfunc (sq *SubQuery) ColumnCount(ctx context.Context) (int, error) {\n\tp, err := sq.Plan(ctx)\n\tif err != nil {\n\t\treturn 0, errors.Trace(err)\n\t}\n\treturn len(p.GetFields()), nil\n}\n\n\/\/ Plan implements plan.Planner interface.\nfunc (sq *SubQuery) Plan(ctx context.Context) (plan.Plan, error) {\n\tif sq.p != nil {\n\t\treturn sq.p, nil\n\t}\n\n\tvar err error\n\tsq.p, err = sq.Stmt.Plan(ctx)\n\treturn sq.p, errors.Trace(err)\n}\n\n\/\/ EvalRows executes the subquery and returns the multi rows with rowCount.\n\/\/ rowCount < 0 means no limit.\n\/\/ If the ColumnCount is 1, we will return a column result like {1, 2, 3},\n\/\/ otherwise, we will return a table result like {{1, 1}, {2, 2}}.\nfunc (sq *SubQuery) EvalRows(ctx context.Context, args map[interface{}]interface{}, rowCount int) ([]interface{}, error) {\n\tp, err := sq.Plan(ctx)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tdefer p.Close()\n\n\tsq.push(ctx)\n\n\tvar (\n\t\trow *plan.Row\n\t\tres = []interface{}{}\n\t)\n\n\tfor rowCount != 0 {\n\t\trow, err = p.Next(ctx)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tif row == nil {\n\t\t\tbreak\n\t\t}\n\t\tif len(row.Data) == 1 {\n\t\t\tres = append(res, row.Data[0])\n\t\t} else {\n\t\t\tres = append(res, row.Data)\n\t\t}\n\n\t\tif rowCount > 0 {\n\t\t\trowCount--\n\t\t}\n\t}\n\n\terr0 := sq.pop(ctx)\n\tif err0 != nil {\n\t\treturn res, errors.Trace(err0)\n\t}\n\n\treturn res, errors.Trace(err)\n}\n\n\/\/ A dummy type to avoid naming collision in context.\ntype subQueryStackKeyType int\n\n\/\/ String defines a Stringer function for debugging and pretty printing.\nfunc (k subQueryStackKeyType) String() string {\n\treturn \"sub query stack\"\n}\n\n\/\/ subQueryStackKey holds the running sub query's stack.\nconst subQueryStackKey subQueryStackKeyType = 0\n\nfunc (sq *SubQuery) push(ctx context.Context) {\n\tvar st []*SubQuery\n\tv := ctx.Value(subQueryStackKey)\n\tif v == nil {\n\t\tst = []*SubQuery{}\n\t} else {\n\t\t\/\/ must ok\n\t\tst = v.([]*SubQuery)\n\t}\n\n\tst = append(st, sq)\n\tctx.SetValue(subQueryStackKey, st)\n}\n\nfunc (sq *SubQuery) pop(ctx context.Context) error {\n\tv := ctx.Value(subQueryStackKey)\n\tif v == nil {\n\t\treturn errors.Errorf(\"pop empty sub query stack\")\n\t}\n\n\tst := v.([]*SubQuery)\n\n\t\/\/ can not empty\n\tn := len(st) - 1\n\tif st[n] != sq {\n\t\treturn errors.Errorf(\"pop invalid top sub query in stack, want %v, but top is %v\", sq, st[n])\n\t}\n\n\tst[n] = nil\n\tst = st[0:n]\n\tif len(st) == 0 {\n\t\tctx.ClearValue(subQueryStackKey)\n\t\treturn nil\n\t}\n\n\tctx.SetValue(subQueryStackKey, st)\n\treturn nil\n}\n\n\/\/ SetOuterQueryUsed is called when current running subquery uses outer query.\nfunc SetOuterQueryUsed(ctx context.Context) {\n\tv := ctx.Value(subQueryStackKey)\n\tif v == nil {\n\t\treturn\n\t}\n\n\tst := v.([]*SubQuery)\n\n\t\/\/ if current sub query uses outer query, the select result can not be cached,\n\t\/\/ at the same time, all the upper sub query must not cache the result too.\n\tfor i := len(st) - 1; i >= 0; i-- {\n\t\tst[i].UseOuterQuery = true\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package console provides GopherJS wrappers for the JavaScript\n\/\/ console.\n\/\/\n\/\/ Some functions support format specifiers. The following specifiers\n\/\/ are supported:\n\/\/\n\/\/     %s – Formats the value as a string\n\/\/     %d – Formats the value as an integer\n\/\/     %i – Same as %d\n\/\/     %f – Formats the value as a floating point value.\n\/\/     %o – Formats the value as an expandable DOM element (as in the Elements panel).\n\/\/     %O – Formats the value as an expandable JavaScript object.\n\/\/     %c – Formats the output string according to CSS styles you provide.\n\/\/\n\/\/ This package does not provide functions for the aliases\n\/\/ console.debug and console.info – use Log instead.\n\/\/\n\/\/ For a more detailed explanation of the APIs, see for example\n\/\/ Google's documentation at\n\/\/ https:\/\/developers.google.com\/chrome-developer-tools\/docs\/console-api.\n\/\/\n\/\/ Portions of this documentation are modifications based on work\n\/\/ created and shared by Google and used according to terms described\n\/\/ in the Creative Commons 3.0 Attribution License.\npackage console \/\/ import \"honnef.co\/go\/js\/console\"\n\nimport (\n\t\"bytes\"\n\n\t\"github.com\/gopherjs\/gopherjs\/js\"\n)\n\nvar c = js.Global.Get(\"console\")\n\n\/\/ Assert writes msg to the console if b is false.\nfunc Assert(b bool, msg js.Any) {\n\tc.Call(\"assert\", b, msg)\n}\n\n\/\/ Clear clears the console.\nfunc Clear() {\n\tc.Call(\"clear\")\n}\n\n\/\/ Count writes the number of times that it has been invoked at the\n\/\/ same line and with the same label.\nfunc Count(label string) {\n\tc.Call(\"count\", label)\n}\n\n\/\/ Dir prints a JavaScript representation of the specified object. If\n\/\/ the object being logged is an HTML element, then the properties of\n\/\/ its DOM representation are displayed.\nfunc Dir(obj js.Any) {\n\tc.Call(\"dir\", obj)\n}\n\n\/\/ DirXML Prints an XML representation of the specified object. For\n\/\/ HTML elements, calling this method is equivalent to calling Log.\nfunc DirXML(obj js.Any) {\n\tc.Call(\"dirxml\", obj)\n}\n\n\/\/ Error is like Log but also includes a stack trace.\nfunc Error(objs ...js.Any) {\n\tc.Call(\"error\", objs...)\n}\n\n\/\/ Group starts a new logging group with an optional title.\n\/\/\n\/\/ All console output that occurs after calling this function appears\n\/\/ in the same visual group. Groups can be nested.\n\/\/\n\/\/ The title will be generated according to the rules of the Log\n\/\/ function.\nfunc Group(objs ...js.Any) {\n\tc.Call(\"group\", objs...)\n}\n\n\/\/ GroupCollapsed is like Group, except that the newly created\n\/\/ group starts collapsed instead of open.\nfunc GroupCollapsed(objs ...js.Any) {\n\tc.Call(\"groupCollapsed\", objs...)\n}\n\n\/\/ GroupEnd closes the currently active logging group.\nfunc GroupEnd() {\n\tc.Call(\"groupEnd\")\n}\n\n\/\/ Log displays a message in the console. You pass one or more objects\n\/\/ to this method, each of which are evaluated and concatenated into a\n\/\/ space-delimited string. The first parameter you pass to Log may\n\/\/ contain format specifiers.\nfunc Log(objs ...js.Any) {\n\tc.Call(\"log\", objs...)\n}\n\n\/\/ Profile starts a new CPU profile with an optional label.\nfunc Profile(label js.Any) {\n\tc.Call(\"profile\", label)\n}\n\n\/\/ ProfileEnd stops the currently running CPU profile, if any.\nfunc ProfileEnd() {\n\tc.Call(\"profileEnd\")\n}\n\n\/\/ Time starts a new timer with an associated label. Calling TimeEnd\n\/\/ with the same label will stop the timer and print the elapsed time.\nfunc Time(label js.Any) {\n\tc.Call(\"time\", label)\n}\n\n\/\/ TimeEnd ends a timer that was started with Time and prints the\n\/\/ elapsed time.\nfunc TimeEnd(label js.Any) {\n\tc.Call(\"timeEnd\", label)\n}\n\n\/\/ Timestamp adds an event to the timeline during a recording session.\nfunc Timestamp(label js.Any) {\n\tc.Call(\"timeStamp\", label)\n}\n\n\/\/ Trace prints a stack trace, starting from the point where Trace was\n\/\/ called.\nfunc Trace() {\n\tc.Call(\"trace\")\n}\n\n\/\/ Warn is like Log but displays a different icon alongside the\n\/\/ message.\nfunc Warn(objs ...js.Any) {\n\tc.Call(\"warn\", objs...)\n}\n\n\/\/ Writer implements an io.Writer on top of the JavaScript console.\n\/\/ Writes will be buffered until a newline is encountered, which will\n\/\/ cause flushing up to the newline.\ntype Writer struct {\n\tbuf *bytes.Buffer\n}\n\nfunc (w *Writer) Write(buf []byte) (n int, err error) {\n\tif len(buf) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tfor i := len(buf); i >= 0; i-- {\n\t\tif buf[i] == '\\n' {\n\t\t\tw.buf.Write(buf[:i])\n\t\t\tLog(w.buf.String())\n\t\t\tw.buf.Reset()\n\t\t\tw.buf.Write(buf[i+1:])\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn len(buf), nil\n}\n\nfunc (w *Writer) WriteString(s string) (n int, err error) {\n\treturn w.Write([]byte(s))\n}\n\n\/\/ Flush will flush the current line to the console.\nfunc (w *Writer) Flush() {\n\tw.Write([]byte{'\\n'})\n}\n\nfunc New() *Writer {\n\treturn &Writer{buf: new(bytes.Buffer)}\n}\n<commit_msg>revert js.Any changes<commit_after>\/\/ Package console provides GopherJS wrappers for the JavaScript\n\/\/ console.\n\/\/\n\/\/ Some functions support format specifiers. The following specifiers\n\/\/ are supported:\n\/\/\n\/\/     %s – Formats the value as a string\n\/\/     %d – Formats the value as an integer\n\/\/     %i – Same as %d\n\/\/     %f – Formats the value as a floating point value.\n\/\/     %o – Formats the value as an expandable DOM element (as in the Elements panel).\n\/\/     %O – Formats the value as an expandable JavaScript object.\n\/\/     %c – Formats the output string according to CSS styles you provide.\n\/\/\n\/\/ This package does not provide functions for the aliases\n\/\/ console.debug and console.info – use Log instead.\n\/\/\n\/\/ For a more detailed explanation of the APIs, see for example\n\/\/ Google's documentation at\n\/\/ https:\/\/developers.google.com\/chrome-developer-tools\/docs\/console-api.\n\/\/\n\/\/ Portions of this documentation are modifications based on work\n\/\/ created and shared by Google and used according to terms described\n\/\/ in the Creative Commons 3.0 Attribution License.\npackage console \/\/ import \"honnef.co\/go\/js\/console\"\n\nimport (\n\t\"bytes\"\n\n\t\"github.com\/gopherjs\/gopherjs\/js\"\n)\n\nvar c = js.Global.Get(\"console\")\n\n\/\/ Assert writes msg to the console if b is false.\nfunc Assert(b bool, msg interface{}) {\n\tc.Call(\"assert\", b, msg)\n}\n\n\/\/ Clear clears the console.\nfunc Clear() {\n\tc.Call(\"clear\")\n}\n\n\/\/ Count writes the number of times that it has been invoked at the\n\/\/ same line and with the same label.\nfunc Count(label string) {\n\tc.Call(\"count\", label)\n}\n\n\/\/ Dir prints a JavaScript representation of the specified object. If\n\/\/ the object being logged is an HTML element, then the properties of\n\/\/ its DOM representation are displayed.\nfunc Dir(obj interface{}) {\n\tc.Call(\"dir\", obj)\n}\n\n\/\/ DirXML Prints an XML representation of the specified object. For\n\/\/ HTML elements, calling this method is equivalent to calling Log.\nfunc DirXML(obj interface{}) {\n\tc.Call(\"dirxml\", obj)\n}\n\n\/\/ Error is like Log but also includes a stack trace.\nfunc Error(objs ...interface{}) {\n\tc.Call(\"error\", objs...)\n}\n\n\/\/ Group starts a new logging group with an optional title.\n\/\/\n\/\/ All console output that occurs after calling this function appears\n\/\/ in the same visual group. Groups can be nested.\n\/\/\n\/\/ The title will be generated according to the rules of the Log\n\/\/ function.\nfunc Group(objs ...interface{}) {\n\tc.Call(\"group\", objs...)\n}\n\n\/\/ GroupCollapsed is like Group, except that the newly created\n\/\/ group starts collapsed instead of open.\nfunc GroupCollapsed(objs ...interface{}) {\n\tc.Call(\"groupCollapsed\", objs...)\n}\n\n\/\/ GroupEnd closes the currently active logging group.\nfunc GroupEnd() {\n\tc.Call(\"groupEnd\")\n}\n\n\/\/ Log displays a message in the console. You pass one or more objects\n\/\/ to this method, each of which are evaluated and concatenated into a\n\/\/ space-delimited string. The first parameter you pass to Log may\n\/\/ contain format specifiers.\nfunc Log(objs ...interface{}) {\n\tc.Call(\"log\", objs...)\n}\n\n\/\/ Profile starts a new CPU profile with an optional label.\nfunc Profile(label interface{}) {\n\tc.Call(\"profile\", label)\n}\n\n\/\/ ProfileEnd stops the currently running CPU profile, if any.\nfunc ProfileEnd() {\n\tc.Call(\"profileEnd\")\n}\n\n\/\/ Time starts a new timer with an associated label. Calling TimeEnd\n\/\/ with the same label will stop the timer and print the elapsed time.\nfunc Time(label interface{}) {\n\tc.Call(\"time\", label)\n}\n\n\/\/ TimeEnd ends a timer that was started with Time and prints the\n\/\/ elapsed time.\nfunc TimeEnd(label interface{}) {\n\tc.Call(\"timeEnd\", label)\n}\n\n\/\/ Timestamp adds an event to the timeline during a recording session.\nfunc Timestamp(label interface{}) {\n\tc.Call(\"timeStamp\", label)\n}\n\n\/\/ Trace prints a stack trace, starting from the point where Trace was\n\/\/ called.\nfunc Trace() {\n\tc.Call(\"trace\")\n}\n\n\/\/ Warn is like Log but displays a different icon alongside the\n\/\/ message.\nfunc Warn(objs ...interface{}) {\n\tc.Call(\"warn\", objs...)\n}\n\n\/\/ Writer implements an io.Writer on top of the JavaScript console.\n\/\/ Writes will be buffered until a newline is encountered, which will\n\/\/ cause flushing up to the newline.\ntype Writer struct {\n\tbuf *bytes.Buffer\n}\n\nfunc (w *Writer) Write(buf []byte) (n int, err error) {\n\tif len(buf) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tfor i := len(buf); i >= 0; i-- {\n\t\tif buf[i] == '\\n' {\n\t\t\tw.buf.Write(buf[:i])\n\t\t\tLog(w.buf.String())\n\t\t\tw.buf.Reset()\n\t\t\tw.buf.Write(buf[i+1:])\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn len(buf), nil\n}\n\nfunc (w *Writer) WriteString(s string) (n int, err error) {\n\treturn w.Write([]byte(s))\n}\n\n\/\/ Flush will flush the current line to the console.\nfunc (w *Writer) Flush() {\n\tw.Write([]byte{'\\n'})\n}\n\nfunc New() *Writer {\n\treturn &Writer{buf: new(bytes.Buffer)}\n}\n<|endoftext|>"}
{"text":"<commit_before>package dataProcess\n\nimport (\n\t\"..\/autils\"\n\t\"database\/sql\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/ 获取流量信息\nfunc GetDFlow(c *gin.Context, db *sql.DB) {\n\tq, _ := c.Get(\"conditions\")\n\tsDate, eDate := autils.AnaDate(q)\n\tvas, _ := time.Parse(shortForm, sDate)\n\tvae, _ := time.Parse(shortForm, eDate)\n\n\tdateList := dateCtt{}\n\n\tdn := autils.AnaSelect(q)\n\n\tif dn == \"\" {\n\t\tdn = \"120ask.com\"\n\t}\n\n\tif sDate != \"\" && eDate != \"\" && vae.After(vas) {\n\t\tt := vas\n\t\ts := autils.GetCurrentData(t)\n\t\te := eDate\n\t\tfor {\n\t\t\tif s != e {\n\t\t\t\tt = t.AddDate(0, 0, 1)\n\t\t\t\ts = autils.GetCurrentData(t)\n\t\t\t\tdateList = append(dateList, s)\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\tvar maxLenth int\n\t\tml := c.Query(\"max\")\n\t\tif ml != \"\" {\n\t\t\tmaxLenth, _ = strconv.Atoi(ml)\n\t\t}\n\n\t\tif maxLenth == 0 {\n\t\t\tmaxLenth = 15\n\t\t}\n\t\tnow := time.Now()\n\t\tfor i := -maxLenth; i < 0; i++ {\n\t\t\tt := now.AddDate(0, 0, i)\n\t\t\tdateList = append(dateList, autils.GetCurrentData(t))\n\t\t}\n\t}\n\n\tls := flineStruct{}\n\n\tvar click, display, tClick, tDisplay, cRate, fRate string\n\n\trows, err := db.Query(\"select click, display, total_click, total_display, cd_rate, flow_rate from site_flow where date >= '\" + dateList[0] + \"' and  date <= '\" + dateList[len(dateList)-1] + \"' and domain = '\" + dn + \"'\")\n\n\tautils.ErrHadle(err)\n\n\tlcs := fseriesType{}\n\tlcs.Name = \"MIP点击流量\"\n\n\tdps := fseriesType{}\n\tdps.Name = \"MIP展现次数\"\n\n\trts := fseriesType{}\n\trts.Name = \"MIP点展比\"\n\n\tct := fseriesType{}\n\tct.Name = \"点击总流量\"\n\n\tdt := fseriesType{}\n\tdt.Name = \"展现总次数\"\n\n\tfr := fseriesType{}\n\tfr.Name = \"MIP流量占比\"\n\n\tfor rows.Next() {\n\t\terr := rows.Scan(&click, &display, &tClick, &tDisplay, &cRate, &fRate)\n\t\tautils.ErrHadle(err)\n\n\t\tlcs.Data = append(lcs.Data, click)\n\t\tdps.Data = append(dps.Data, display)\n\t\trts.Data = append(rts.Data, cRate)\n\t\tct.Data = append(ct.Data, tClick)\n\t\tdt.Data = append(dt.Data, tDisplay)\n\t\tfr.Data = append(fr.Data, fRate)\n\t}\n\terr = rows.Err()\n\tautils.ErrHadle(err)\n\n\tls.Series = append(ls.Series, lcs, dps, rts, ct, dt, fr)\n\tls.Categories = dateList\n\n\tdefer rows.Close()\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"status\": 0,\n\t\t\"msg\":    \"ok\",\n\t\t\"data\":   ls,\n\t})\n}\n<commit_msg>fixed no data bug.<commit_after>package dataProcess\n\nimport (\n\t\"..\/autils\"\n\t\"database\/sql\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/ 获取流量信息\nfunc GetDFlow(c *gin.Context, db *sql.DB) {\n\tq, _ := c.Get(\"conditions\")\n\tsDate, eDate := autils.AnaDate(q)\n\tvas, _ := time.Parse(shortForm, sDate)\n\tvae, _ := time.Parse(shortForm, eDate)\n\n\tdateList := dateCtt{}\n\n\tdn := autils.AnaSelect(q)\n\n\tif dn == \"\" {\n\t\tdn = \"120ask.com\"\n\t}\n\n\tif sDate != \"\" && eDate != \"\" && vae.After(vas) {\n\t\tt := vas\n\t\ts := autils.GetCurrentData(t)\n\t\te := eDate\n\t\tfor {\n\t\t\tif s != e {\n\t\t\t\tt = t.AddDate(0, 0, 1)\n\t\t\t\ts = autils.GetCurrentData(t)\n\t\t\t\tdateList = append(dateList, s)\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t} else {\n\t\tvar maxLenth int\n\t\tml := c.Query(\"max\")\n\t\tif ml != \"\" {\n\t\t\tmaxLenth, _ = strconv.Atoi(ml)\n\t\t}\n\n\t\tif maxLenth == 0 {\n\t\t\tmaxLenth = 15\n\t\t}\n\t\tnow := time.Now()\n\t\tfor i := -maxLenth; i < 0; i++ {\n\t\t\tt := now.AddDate(0, 0, i)\n\t\t\tdateList = append(dateList, autils.GetCurrentData(t))\n\t\t}\n\t}\n\n\tls := flineStruct{}\n\n\tvar click, display, tClick, tDisplay, cRate, fRate string\n\n\trows, err := db.Query(\"select click, display, total_click, total_display, cd_rate, flow_rate from site_flow where date >= '\" + dateList[0] + \"' and  date <= '\" + dateList[len(dateList)-1] + \"' and domain = '\" + dn + \"'\")\n\n\tautils.ErrHadle(err)\n\n\tlcs := fseriesType{}\n\tlcs.Name = \"MIP点击流量\"\n\n\tdps := fseriesType{}\n\tdps.Name = \"MIP展现次数\"\n\n\trts := fseriesType{}\n\trts.Name = \"MIP点展比\"\n\n\tct := fseriesType{}\n\tct.Name = \"点击总流量\"\n\n\tdt := fseriesType{}\n\tdt.Name = \"展现总次数\"\n\n\tfr := fseriesType{}\n\tfr.Name = \"MIP流量占比\"\n\n\tfor rows.Next() {\n\t\terr := rows.Scan(&click, &display, &tClick, &tDisplay, &cRate, &fRate)\n\t\tautils.ErrHadle(err)\n\n\t\tlcs.Data = append(lcs.Data, click)\n\t\tdps.Data = append(dps.Data, display)\n\t\trts.Data = append(rts.Data, cRate)\n\t\tct.Data = append(ct.Data, tClick)\n\t\tdt.Data = append(dt.Data, tDisplay)\n\t\tfr.Data = append(fr.Data, fRate)\n\t}\n\terr = rows.Err()\n\tautils.ErrHadle(err)\n\n\tls.Series = append(ls.Series, lcs, dps, rts, ct, dt, fr)\n\tls.Categories = dateList\n\n\tdefer rows.Close()\n\n\tif len(lcs.Data) == 0 || len(dps.Data) == 0 || len(rts.Data) == 0 || len(ct.Data) == 0 || len(dt.Data) == 0 || len(fr.Data) == 0 {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t\"status\": -1,\n\t\t\t\"msg\":    \"无数据\",\n\t\t\t\"data\":   \"\",\n\t\t})\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"status\": 0,\n\t\t\"msg\":    \"ok\",\n\t\t\"data\":   ls,\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"golang.org\/x\/net\/html\"\n\n\t\"github.com\/PuerkitoBio\/goquery\"\n)\n\n\/\/ addDivs adds kobo divs.\nfunc addDivs(doc *goquery.Document) error {\n\tdoc.Find(\"body>*\").WrapAllHtml(`<div class=\"book-inner\"><\/div>`)\n\tdoc.Find(\"body>*\").WrapAllHtml(`<div class=\"book-columns\"><\/div>`)\n\treturn nil\n}\n\n\/\/ addSpansToNode is a recursive helper function for addSpans.\nfunc addSpansToNode(node *html.Node, paragraph *int, segment *int) {\n\tsentencere := regexp.MustCompile(`((?m).*?[\\.\\!\\?\\:]['\"”’“…]?\\s*)`)\n\n\t\/\/ Part 2 of hacky way of setting innerhtml of a textnode by double escaping everything, and deescaping once afterwards\n\tnewAttr := []html.Attribute{}\n\tfor _, a := range node.Attr {\n\t\ta.Key = html.EscapeString(a.Key)\n\t\ta.Val = html.EscapeString(a.Val)\n\t\tnewAttr = append(newAttr, a)\n\t}\n\tnode.Attr = newAttr\n\n\tif node.Type == html.TextNode {\n\t\tif node.Parent.Data == \"pre\" {\n\t\t\t\/\/ Do not add spans to pre elements\n\t\t\treturn\n\t\t}\n\t\t*segment++\n\n\t\tsentencesindexes := sentencere.FindAllStringIndex(node.Data, -1)\n\t\tsentences := []string{}\n\t\tlasti := []int{0, 0}\n\t\tfor _, i := range sentencesindexes {\n\t\t\tif lasti[1] != i[0] {\n\t\t\t\t\/\/ If gap in regex matches, add the gap to the sentence list to avoid losing text\n\t\t\t\tsentences = append(sentences, node.Data[lasti[1]:i[0]])\n\t\t\t}\n\t\t\tsentences = append(sentences, node.Data[i[0]:i[1]])\n\t\t\tlasti = i\n\t\t}\n\t\tif lasti[1] != len(node.Data) {\n\t\t\t\/\/ If gap in regex matches, add the gap to the sentence list to avoid losing text\n\t\t\tsentences = append(sentences, node.Data[lasti[1]:len(node.Data)])\n\t\t}\n\n\t\tvar newhtml bytes.Buffer\n\n\t\tfor _, sentence := range sentences {\n\t\t\tif strings.TrimSpace(sentence) != \"\" {\n\t\t\t\tnewhtml.WriteString(fmt.Sprintf(`<span class=\"koboSpan\" id=\"kobo.%v.%v\">%s<\/span>`, *paragraph, *segment, sentence))\n\t\t\t\t*segment++\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Part 1 of hacky way of setting innerhtml of a textnode by double escaping everything, and deescaping once afterwards\n\t\tnode.Data = newhtml.String()\n\n\t\treturn\n\t}\n\tif node.Type != html.ElementNode {\n\t\treturn\n\t}\n\tif node.Data == \"img\" {\n\t\treturn\n\t}\n\tif node.Data == \"p\" || node.Data == \"ol\" || node.Data == \"ul\" {\n\t\t*segment = 0\n\t\t*paragraph++\n\t}\n\tfor c := node.FirstChild; c != nil; c = c.NextSibling {\n\t\taddSpansToNode(c, paragraph, segment)\n\t}\n}\n\n\/\/ addSpans adds kobo spans.\nfunc addSpans(doc *goquery.Document) error {\n\talreadyHasSpans := false\n\tdoc.Find(\"span\").Each(func(i int, s *goquery.Selection) {\n\t\tif val, _ := s.Attr(\"class\"); strings.Contains(val, \"koboSpan\") {\n\t\t\talreadyHasSpans = true\n\t\t}\n\t})\n\tif alreadyHasSpans {\n\t\treturn nil\n\t}\n\n\tparagraph := 0\n\tsegment := 0\n\n\tfor _, n := range doc.Find(\"body\").Nodes {\n\t\taddSpansToNode(n, &paragraph, &segment)\n\t}\n\n\treturn nil\n}\n\n\/\/ openSelfClosingPs opens self-closing p tags.\nfunc openSelfClosingPs(html *string) error {\n\tre := regexp.MustCompile(`<p[^>\/]*\/>`)\n\t*html = re.ReplaceAllString(*html, `<p><\/p>`)\n\treturn nil\n}\n\n\/\/ smartenPunctuation smartens punctuation in html code. It must be run last.\nfunc smartenPunctuation(html *string) error {\n\t\/\/ em and en dashes\n\t*html = strings.Replace(*html, \"---\", \" &#x2013; \", -1)\n\t*html = strings.Replace(*html, \"--\", \" &#x2014; \", -1)\n\n\t\/\/ TODO: smart quotes\n\n\t\/\/ Fix comments\n\t*html = strings.Replace(*html, \"<! &#x2014; \", \"<!-- \", -1)\n\t*html = strings.Replace(*html, \" &#x2014; >\", \" -->\", -1)\n\treturn nil\n}\n\n\/\/ cleanHTML cleans up html for a kobo epub.\nfunc cleanHTML(html *string) error {\n\temptyHeadingRe := regexp.MustCompile(`<h\\d+>\\s*<\/h\\d+>`)\n\t*html = emptyHeadingRe.ReplaceAllString(*html, \"\")\n\n\tmsPRe := regexp.MustCompile(`\\s*<o:p>\\s*<\\\/o:p>`)\n\t*html = msPRe.ReplaceAllString(*html, \" \")\n\n\tmsStRe := regexp.MustCompile(`<\\\/?st1:\\w+>`)\n\t*html = msStRe.ReplaceAllString(*html, \"\")\n\n\t\/\/ unicode replacement chars\n\t*html = strings.Replace(*html, \"�\", \"\", -1)\n\n\t\/\/ ADEPT drm tags\n\tadeptRe := regexp.MustCompile(`(<meta\\s+content=\".+\"\\s+name=\"Adept.expected.resource\"\\s+\\\/>)`)\n\t*html = adeptRe.ReplaceAllString(*html, \"\")\n\n\treturn nil\n}\n\n\/\/ process processes the html of a content file in an ordinary epub and converts it into a kobo epub by adding kobo divs, kobo spans, smartening punctuation, and cleaning html.\nfunc process(content *string) error {\n\tdoc, err := goquery.NewDocumentFromReader(strings.NewReader(*content))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := addDivs(doc); err != nil {\n\t\treturn err\n\t}\n\n\tif err := addSpans(doc); err != nil {\n\t\treturn err\n\t}\n\n\th, err := doc.Html()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Part 3 of hacky way of setting innerhtml of a textnode by double escaping everything, and deescaping once afterwards. Must be done before further html processing\n\th = html.UnescapeString(h)\n\n\tif err := openSelfClosingPs(&h); err != nil {\n\t\treturn err\n\t}\n\n\tif err := cleanHTML(&h); err != nil {\n\t\treturn err\n\t}\n\n\tif err := smartenPunctuation(&h); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Kobo style fixes\n\th = strings.Replace(h, \"<\/head>\", \"<style>div#book-inner{margin-top: 0;margin-bottom: 0;}<\/style><\/head>\", 1)\n\n\t*content = h\n\n\treturn nil\n}\n<commit_msg>Add check to addDivs function<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"golang.org\/x\/net\/html\"\n\n\t\"github.com\/PuerkitoBio\/goquery\"\n)\n\n\/\/ addDivs adds kobo divs.\nfunc addDivs(doc *goquery.Document) error {\n\tif len(doc.Find(\"div\").Nodes) > len(doc.Find(\"p\").Nodes) {\n\t\t\/\/ If there are more divs than ps, divs are probably being used as paragraphs, and adding the kobo divs will most likely break the book.\n\t\treturn nil\n\t}\n\tdoc.Find(\"body>*\").WrapAllHtml(`<div class=\"book-inner\"><\/div>`)\n\tdoc.Find(\"body>*\").WrapAllHtml(`<div class=\"book-columns\"><\/div>`)\n\treturn nil\n}\n\n\/\/ addSpansToNode is a recursive helper function for addSpans.\nfunc addSpansToNode(node *html.Node, paragraph *int, segment *int) {\n\tsentencere := regexp.MustCompile(`((?m).*?[\\.\\!\\?\\:]['\"”’“…]?\\s*)`)\n\n\t\/\/ Part 2 of hacky way of setting innerhtml of a textnode by double escaping everything, and deescaping once afterwards\n\tnewAttr := []html.Attribute{}\n\tfor _, a := range node.Attr {\n\t\ta.Key = html.EscapeString(a.Key)\n\t\ta.Val = html.EscapeString(a.Val)\n\t\tnewAttr = append(newAttr, a)\n\t}\n\tnode.Attr = newAttr\n\n\tif node.Type == html.TextNode {\n\t\tif node.Parent.Data == \"pre\" {\n\t\t\t\/\/ Do not add spans to pre elements\n\t\t\treturn\n\t\t}\n\t\t*segment++\n\n\t\tsentencesindexes := sentencere.FindAllStringIndex(node.Data, -1)\n\t\tsentences := []string{}\n\t\tlasti := []int{0, 0}\n\t\tfor _, i := range sentencesindexes {\n\t\t\tif lasti[1] != i[0] {\n\t\t\t\t\/\/ If gap in regex matches, add the gap to the sentence list to avoid losing text\n\t\t\t\tsentences = append(sentences, node.Data[lasti[1]:i[0]])\n\t\t\t}\n\t\t\tsentences = append(sentences, node.Data[i[0]:i[1]])\n\t\t\tlasti = i\n\t\t}\n\t\tif lasti[1] != len(node.Data) {\n\t\t\t\/\/ If gap in regex matches, add the gap to the sentence list to avoid losing text\n\t\t\tsentences = append(sentences, node.Data[lasti[1]:len(node.Data)])\n\t\t}\n\n\t\tvar newhtml bytes.Buffer\n\n\t\tfor _, sentence := range sentences {\n\t\t\tif strings.TrimSpace(sentence) != \"\" {\n\t\t\t\tnewhtml.WriteString(fmt.Sprintf(`<span class=\"koboSpan\" id=\"kobo.%v.%v\">%s<\/span>`, *paragraph, *segment, sentence))\n\t\t\t\t*segment++\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Part 1 of hacky way of setting innerhtml of a textnode by double escaping everything, and deescaping once afterwards\n\t\tnode.Data = newhtml.String()\n\n\t\treturn\n\t}\n\tif node.Type != html.ElementNode {\n\t\treturn\n\t}\n\tif node.Data == \"img\" {\n\t\treturn\n\t}\n\tif node.Data == \"p\" || node.Data == \"ol\" || node.Data == \"ul\" {\n\t\t*segment = 0\n\t\t*paragraph++\n\t}\n\tfor c := node.FirstChild; c != nil; c = c.NextSibling {\n\t\taddSpansToNode(c, paragraph, segment)\n\t}\n}\n\n\/\/ addSpans adds kobo spans.\nfunc addSpans(doc *goquery.Document) error {\n\talreadyHasSpans := false\n\tdoc.Find(\"span\").Each(func(i int, s *goquery.Selection) {\n\t\tif val, _ := s.Attr(\"class\"); strings.Contains(val, \"koboSpan\") {\n\t\t\talreadyHasSpans = true\n\t\t}\n\t})\n\tif alreadyHasSpans {\n\t\treturn nil\n\t}\n\n\tparagraph := 0\n\tsegment := 0\n\n\tfor _, n := range doc.Find(\"body\").Nodes {\n\t\taddSpansToNode(n, &paragraph, &segment)\n\t}\n\n\treturn nil\n}\n\n\/\/ openSelfClosingPs opens self-closing p tags.\nfunc openSelfClosingPs(html *string) error {\n\tre := regexp.MustCompile(`<p[^>\/]*\/>`)\n\t*html = re.ReplaceAllString(*html, `<p><\/p>`)\n\treturn nil\n}\n\n\/\/ smartenPunctuation smartens punctuation in html code. It must be run last.\nfunc smartenPunctuation(html *string) error {\n\t\/\/ em and en dashes\n\t*html = strings.Replace(*html, \"---\", \" &#x2013; \", -1)\n\t*html = strings.Replace(*html, \"--\", \" &#x2014; \", -1)\n\n\t\/\/ TODO: smart quotes\n\n\t\/\/ Fix comments\n\t*html = strings.Replace(*html, \"<! &#x2014; \", \"<!-- \", -1)\n\t*html = strings.Replace(*html, \" &#x2014; >\", \" -->\", -1)\n\treturn nil\n}\n\n\/\/ cleanHTML cleans up html for a kobo epub.\nfunc cleanHTML(html *string) error {\n\temptyHeadingRe := regexp.MustCompile(`<h\\d+>\\s*<\/h\\d+>`)\n\t*html = emptyHeadingRe.ReplaceAllString(*html, \"\")\n\n\tmsPRe := regexp.MustCompile(`\\s*<o:p>\\s*<\\\/o:p>`)\n\t*html = msPRe.ReplaceAllString(*html, \" \")\n\n\tmsStRe := regexp.MustCompile(`<\\\/?st1:\\w+>`)\n\t*html = msStRe.ReplaceAllString(*html, \"\")\n\n\t\/\/ unicode replacement chars\n\t*html = strings.Replace(*html, \"�\", \"\", -1)\n\n\t\/\/ ADEPT drm tags\n\tadeptRe := regexp.MustCompile(`(<meta\\s+content=\".+\"\\s+name=\"Adept.expected.resource\"\\s+\\\/>)`)\n\t*html = adeptRe.ReplaceAllString(*html, \"\")\n\n\treturn nil\n}\n\n\/\/ process processes the html of a content file in an ordinary epub and converts it into a kobo epub by adding kobo divs, kobo spans, smartening punctuation, and cleaning html.\nfunc process(content *string) error {\n\tdoc, err := goquery.NewDocumentFromReader(strings.NewReader(*content))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := addDivs(doc); err != nil {\n\t\treturn err\n\t}\n\n\tif err := addSpans(doc); err != nil {\n\t\treturn err\n\t}\n\n\th, err := doc.Html()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Part 3 of hacky way of setting innerhtml of a textnode by double escaping everything, and deescaping once afterwards. Must be done before further html processing\n\th = html.UnescapeString(h)\n\n\tif err := openSelfClosingPs(&h); err != nil {\n\t\treturn err\n\t}\n\n\tif err := cleanHTML(&h); err != nil {\n\t\treturn err\n\t}\n\n\tif err := smartenPunctuation(&h); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Kobo style fixes\n\th = strings.Replace(h, \"<\/head>\", \"<style>div#book-inner{margin-top: 0;margin-bottom: 0;}<\/style><\/head>\", 1)\n\n\t*content = h\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package database\n\nimport (\n\t\"sort\"\n\t\"testing\"\n)\n\nfunc TestByVersion(t *testing.T) {\n\tmigrations := []AppliedMigration{\n\t\t{Name: \"v1\", Version: 1},\n\t\t{Name: \"v4\", Version: 4},\n\t\t{Name: \"v2\", Version: 2},\n\t\t{Name: \"v3\", Version: 3},\n\t}\n\n\tsort.Sort(sort.Reverse(byVersion(migrations)))\n\n\tcurVersion := len(migrations)\n\n\tfor _, v := range migrations {\n\t\tif v.Version > curVersion {\n\t\t\tt.Error(\"Version should be less than the previous one\")\n\t\t}\n\n\t\tcurVersion = v.Version\n\t}\n}\n<commit_msg>Some tests<commit_after>package database\n\nimport (\n\t\"sort\"\n\t\"testing\"\n)\n\ntype migrationOne struct{}\ntype migrationTwo struct{}\ntype migrationThree struct{}\n\nfunc (m migrationOne) Name() string   { return \"20170501_test1\" }\nfunc (m migrationTwo) Name() string   { return \"20170502_test2\" }\nfunc (m migrationThree) Name() string { return \"20170601_test3\" }\n\nfunc (m migrationOne) Up() string   { return \"\" }\nfunc (m migrationTwo) Up() string   { return \"\" }\nfunc (m migrationThree) Up() string { return \"\" }\n\nfunc (m migrationOne) Down() string   { return \"\" }\nfunc (m migrationTwo) Down() string   { return \"\" }\nfunc (m migrationThree) Down() string { return \"\" }\n\nfunc (m migrationOne) String() string   { return m.Name() }\nfunc (m migrationTwo) String() string   { return m.Name() }\nfunc (m migrationThree) String() string { return m.Name() }\n\nfunc TestByVersion(t *testing.T) {\n\tmigrations := []AppliedMigration{\n\t\t{Name: \"v1\", Version: 1},\n\t\t{Name: \"v4\", Version: 4},\n\t\t{Name: \"v2\", Version: 2},\n\t\t{Name: \"v3\", Version: 3},\n\t}\n\n\tsort.Sort(sort.Reverse(byVersion(migrations)))\n\n\tcurVersion := len(migrations)\n\n\tfor _, v := range migrations {\n\t\tif v.Version > curVersion {\n\t\t\tt.Error(\"Version should be less than the previous one\")\n\t\t}\n\n\t\tcurVersion = v.Version\n\t}\n}\n\nfunc TestByName(t *testing.T) {\n\tmigrations := []Migration{\n\t\tmigrationThree{},\n\t\tmigrationTwo{},\n\t\tmigrationOne{},\n\t}\n\n\tsort.Sort(byName(migrations))\n\n\tif migrations[0].Name() != \"20170501_test1\" {\n\t\tt.Error(\"Invalid migration\")\n\t}\n\n\tif migrations[1].Name() != \"20170502_test2\" {\n\t\tt.Error(\"Invalid migration\")\n\t}\n\n\tif migrations[2].Name() != \"20170601_test3\" {\n\t\tt.Error(\"Invalid migration\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package iot\n\nimport (\n\t. \"github.com\/influxdata\/influxdb-comparisons\/bulk_data_gen\/common\"\n\t\"math\/rand\"\n\t\"time\"\n)\n\nvar (\n\tCameraDetectionByteString = []byte(\"camera_detection\") \/\/ heap optimization\n)\n\nvar DetectionObjects = [][]byte{\n\t[]byte(\"animal\"),\n\t[]byte(\"human\"),\n\t[]byte(\"vehicle\"),\n\t[]byte(\"unknown\"),\n}\n\nvar Animals = [][]byte{\n\t[]byte(\"cat\"),\n\t[]byte(\"dog\"),\n\t[]byte(\"bird\"),\n\t[]byte(\"unknown\"),\n}\n\nvar Humans = [][]byte{\n\t[]byte(\"man\"),\n\t[]byte(\"woman\"),\n\t[]byte(\"child\"),\n\t[]byte(\"unknown\"),\n}\n\nvar Vehicles = [][]byte{\n\t[]byte(\"car\"),\n\t[]byte(\"lorry\"),\n\t[]byte(\"truck\"),\n\t[]byte(\"motorcycle\"),\n\t[]byte(\"bicycle\"),\n\t[]byte(\"unknown\"),\n}\n\nvar (\n\t\/\/ Field keys for 'air condition indoor' points.\n\tCameraDetectionFieldKeys = [][]byte{\n\t\t[]byte(\"object_type\"),\n\t\t[]byte(\"object_kind\"),\n\t\t[]byte(\"battery_voltage\"),\n\t}\n)\n\ntype CameraDetectionMeasurement struct {\n\tsensorId    []byte\n\ttimestamp   time.Time\n\tbatteryDist Distribution\n\tobject      []byte\n\tkind        []byte\n}\n\nfunc NewCameraDetectionMeasurement(start time.Time, id []byte) *CameraDetectionMeasurement {\n\n\t\/\/battery_voltage\n\tbatteryDist := MUDWD(ND(0.01, 0.005), 1, 3.2, 3.2)\n\n\treturn &CameraDetectionMeasurement{\n\t\ttimestamp:   start,\n\t\tbatteryDist: batteryDist,\n\t\tsensorId:    id,\n\t}\n}\n\nfunc (m *CameraDetectionMeasurement) Tick(d time.Duration) {\n\tm.timestamp = m.timestamp.Add(d)\n\tobject := rand.Int63n(int64(len(DetectionObjects)))\n\tm.object = DetectionObjects[object]\n\tswitch object {\n\tcase 0: \/\/animal\n\t\tm.kind = Animals[rand.Int63n(int64(len(Animals)))]\n\t\tbreak\n\tcase 1: \/\/human\n\t\tm.kind = Humans[rand.Int63n(int64(len(Humans)))]\n\t\tbreak\n\tcase 2: \/\/vehicle\n\t\tm.kind = Vehicles[rand.Int63n(int64(len(Vehicles)))]\n\t\tbreak\n\tcase 3: \/\/uknown\n\t\tm.kind = []byte(\"uknown\")\n\n\t}\n\tm.batteryDist.Advance()\n}\n\nfunc (m *CameraDetectionMeasurement) ToPoint(p *Point) bool {\n\tp.SetMeasurementName(CameraDetectionByteString)\n\tp.SetTimestamp(&m.timestamp)\n\tp.AppendTag(SensorHomeTagKeys[0], m.sensorId)\n\tp.AppendField(CameraDetectionFieldKeys[0], m.object)\n\tp.AppendField(CameraDetectionFieldKeys[1], m.kind)\n\tp.AppendField(CameraDetectionFieldKeys[2], m.batteryDist.Get())\n\treturn true\n}\n<commit_msg>Fixed initial empty camera_detection values<commit_after>package iot\n\nimport (\n\t. \"github.com\/influxdata\/influxdb-comparisons\/bulk_data_gen\/common\"\n\t\"math\/rand\"\n\t\"time\"\n)\n\nvar (\n\tCameraDetectionByteString = []byte(\"camera_detection\") \/\/ heap optimization\n)\n\nvar DetectionObjects = [][]byte{\n\t[]byte(\"animal\"),\n\t[]byte(\"human\"),\n\t[]byte(\"vehicle\"),\n\t[]byte(\"unknown\"),\n}\n\nvar Animals = [][]byte{\n\t[]byte(\"cat\"),\n\t[]byte(\"dog\"),\n\t[]byte(\"bird\"),\n\t[]byte(\"unknown\"),\n}\n\nvar Humans = [][]byte{\n\t[]byte(\"man\"),\n\t[]byte(\"woman\"),\n\t[]byte(\"child\"),\n\t[]byte(\"unknown\"),\n}\n\nvar Vehicles = [][]byte{\n\t[]byte(\"car\"),\n\t[]byte(\"lorry\"),\n\t[]byte(\"truck\"),\n\t[]byte(\"motorcycle\"),\n\t[]byte(\"bicycle\"),\n\t[]byte(\"unknown\"),\n}\n\nvar (\n\t\/\/ Field keys for 'air condition indoor' points.\n\tCameraDetectionFieldKeys = [][]byte{\n\t\t[]byte(\"object_type\"),\n\t\t[]byte(\"object_kind\"),\n\t\t[]byte(\"battery_voltage\"),\n\t}\n)\n\ntype CameraDetectionMeasurement struct {\n\tsensorId    []byte\n\ttimestamp   time.Time\n\tbatteryDist Distribution\n\tobject      []byte\n\tkind        []byte\n}\n\nfunc NewCameraDetectionMeasurement(start time.Time, id []byte) *CameraDetectionMeasurement {\n\n\t\/\/battery_voltage\n\tbatteryDist := MUDWD(ND(0.01, 0.005), 1, 3.2, 3.2)\n\n\tcd := &CameraDetectionMeasurement{\n\t\ttimestamp:   start,\n\t\tbatteryDist: batteryDist,\n\t\tsensorId:    id,\n\t}\n\tcd.newDetection()\n\treturn cd\n}\n\nfunc (m *CameraDetectionMeasurement) newDetection() {\n\tobject := rand.Int63n(int64(len(DetectionObjects)))\n\tm.object = DetectionObjects[object]\n\tswitch object {\n\tcase 0: \/\/animal\n\t\tm.kind = Animals[rand.Int63n(int64(len(Animals)))]\n\t\tbreak\n\tcase 1: \/\/human\n\t\tm.kind = Humans[rand.Int63n(int64(len(Humans)))]\n\t\tbreak\n\tcase 2: \/\/vehicle\n\t\tm.kind = Vehicles[rand.Int63n(int64(len(Vehicles)))]\n\t\tbreak\n\tcase 3: \/\/uknown\n\t\tm.kind = []byte(\"uknown\")\n\t}\n}\n\nfunc (m *CameraDetectionMeasurement) Tick(d time.Duration) {\n\tm.timestamp = m.timestamp.Add(d)\n\tm.batteryDist.Advance()\n\tm.newDetection()\n}\n\nfunc (m *CameraDetectionMeasurement) ToPoint(p *Point) bool {\n\tp.SetMeasurementName(CameraDetectionByteString)\n\tp.SetTimestamp(&m.timestamp)\n\tp.AppendTag(SensorHomeTagKeys[0], m.sensorId)\n\tp.AppendField(CameraDetectionFieldKeys[0], m.object)\n\tp.AppendField(CameraDetectionFieldKeys[1], m.kind)\n\tp.AppendField(CameraDetectionFieldKeys[2], m.batteryDist.Get())\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>package elicit\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"bytes\"\n\t\"reflect\"\n)\n\n\/\/ Context stores test machinery and maintains state between specs\/scenarios\/steps\ntype Context struct {\n\tspecs           specCollection\n\tstepImpls       stepImplMap\n\ttransforms      transformMap\n\tcurrentSpec     *SpecContext\n\tcurrentScenario *ScenarioContext\n}\n\n\/\/ StepArgumentTransform transforms captured groups in the step pattern to a function parameter type\n\/\/ Note that if the actual string cannot be converted to the target type by the transform, it should return false\ntype StepArgumentTransform func(*Context, string, reflect.Type) (interface{}, bool)\n\ntype specCollection []specDef\ntype stepImplMap map[*regexp.Regexp]interface{}\ntype transformMap map[*regexp.Regexp]StepArgumentTransform\n\n\/\/ New creates a new elicit context which stores specs, steps and transforms\nfunc New() *Context {\n\tctx := &Context{\n\t\tstepImpls:  make(map[*regexp.Regexp]interface{}),\n\t\ttransforms: make(map[*regexp.Regexp]StepArgumentTransform),\n\t}\n\n\t\/\/ TODO discover these automatically\n\tctx.registerTransform(`.*`, stringTransform)\n\tctx.registerTransform(`-?\\d+`, intTransform)\n\tctx.registerTransform(`(?:.+,\\s*)*.+`, commaSliceTransform)\n\n\treturn ctx\n}\n\n\/\/ WithSpecsFolder recursively adds the path to the discovery path of specs\nfunc (ctx *Context) WithSpecsFolder(path string) *Context {\n\tctx.specs.parseSpecFolder(path)\n\treturn ctx\n}\n\n\/\/ WithSteps registers steps from the supplied map of patterns to functions\nfunc (ctx *Context) WithSteps(steps map[string]interface{}) *Context {\n\tfor p, fn := range steps {\n\t\tctx.registerStep(p, fn)\n\t}\n\treturn ctx\n}\n\nfunc (ctx *Context) registerStep(pattern string, stepFunc interface{}) {\n\n\tpattern = strings.TrimSpace(pattern)\n\tpattern = ensureCompleteMatch(pattern)\n\n\tp, err := regexp.Compile(pattern)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"compiling step regexp %q, %s\", pattern, err))\n\t}\n\n\t\/\/ TODO(matt) check the pattern captures the correct number of parameters\n\n\tctx.stepImpls[p] = stepFunc\n}\n\nfunc ensureCompleteMatch(pattern string) string {\n\tif !strings.HasPrefix(pattern, \"^\") {\n\t\tpattern = \"^\" + pattern\n\t}\n\n\tif !strings.HasSuffix(pattern, \"$\") {\n\t\tpattern = pattern + \"$\"\n\t}\n\n\treturn pattern\n}\n\n\/\/ WithTransforms registers step argument transforms from the suppled map of patterns to functions\nfunc (ctx *Context) WithTransforms(txs map[string]StepArgumentTransform) *Context {\n\tfor p, fn := range txs {\n\t\tctx.registerTransform(p, fn)\n\t}\n\treturn ctx\n}\n\nfunc (ctx *Context) registerTransform(pattern string, transform StepArgumentTransform) {\n\tpattern = ensureCompleteMatch(pattern)\n\n\tp, err := regexp.Compile(pattern)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"compiling transform regexp %q, %s\", pattern, err))\n\t}\n\n\tctx.transforms[p] = transform\n}\n\n\/\/ RunTests runs all the discovered specs as tests\nfunc (ctx *Context) RunTests(t *testing.T) {\n\tfor _, spec := range ctx.specs {\n\t\tctx.runSpecTest(t, spec)\n\t}\n}\n\nfunc (ctx *Context) runSpecTest(t *testing.T, spec specDef) {\n\tctx.currentSpec = &SpecContext{\n\t\tname: spec.Name,\n\t}\n\n\tt.Run(spec.Name, func(t *testing.T) {\n\t\tfor _, scenario := range spec.Scenarios {\n\t\t\tctx.runScenarioTest(t, scenario)\n\t\t}\n\t})\n}\n\nfunc (ctx *Context) runScenarioTest(t *testing.T, scenario scenarioDef) {\n\tctx.currentScenario = &ScenarioContext{\n\t\tname:    scenario.Name,\n\t\tskipped: false,\n\t\tfailed:  false,\n\t\tlogbuf:  bytes.Buffer{},\n\t}\n\tctx.logScenarioStart()\n\n\tt.Run(scenario.Name, func(t *testing.T) {\n\t\tfor _, b := range scenario.Spec.BeforeSteps {\n\t\t\tctx.runStep(t, b)\n\t\t}\n\n\t\tfor _, s := range scenario.Steps {\n\t\t\tctx.runStep(t, s)\n\t\t}\n\n\t\tfor _, a := range scenario.Spec.AfterSteps {\n\t\t\tctx.runStep(t, a)\n\t\t}\n\n\t\tlog := string(ctx.currentScenario.logbuf.Bytes())\n\t\tif ctx.currentScenario.failed {\n\t\t\tt.Errorf(log)\n\t\t} else if ctx.currentScenario.skipped {\n\t\t\tt.Skipf(log)\n\t\t}\n\t})\n}\n\nfunc (ctx *Context) runStep(t *testing.T, step stepDef) {\n\tctx.currentScenario.currentStep = step.Text\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tctx.Failf(\"panic during step execution: %s\", r)\n\t\t}\n\t}()\n\n\tfor regex, fn := range ctx.stepImpls {\n\t\tf := reflect.ValueOf(fn)\n\t\tparams := regex.FindStringSubmatch(step.Text)\n\n\t\tif in, ok := ctx.convertParams(f, params, step.Tables); ok {\n\n\t\t\tif !ctx.currentScenario.skipped && !ctx.currentScenario.failed {\n\t\t\t\tf.Call(in)\n\t\t\t} else {\n\t\t\t\tctx.Skip(\"\")\n\t\t\t}\n\n\t\t\tif !ctx.currentScenario.skipped && !ctx.currentScenario.failed {\n\t\t\t\tctx.stepPassed()\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\t}\n\n\tctx.stepNotFound()\n}\n\nfunc (ctx *Context) convertParams(f reflect.Value, stringParams []string, tables []stringTable) ([]reflect.Value, bool) {\n\n\tif stringParams == nil {\n\t\treturn nil, false\n\t}\n\n\tparamCount := f.Type().NumIn()\n\ttableParamCount := 0\n\ttableType := reflect.TypeOf((*Table)(nil)).Elem()\n\n\tfor p := paramCount - 1; p >= 0; p-- {\n\t\tthisParam := f.Type().In(p)\n\t\tif thisParam == tableType {\n\t\t\tparamCount--\n\t\t\ttableParamCount++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif len(stringParams) != paramCount || tableParamCount != len(tables) {\n\t\treturn nil, false\n\t}\n\n\tc := make([]reflect.Value, len(stringParams))\n\tfor i, param := range stringParams {\n\t\tif i == 0 {\n\t\t\tif f.Type().In(0) != reflect.TypeOf(ctx) {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t\tc[i] = reflect.ValueOf(ctx)\n\t\t} else {\n\t\t\tpt := f.Type().In(i)\n\n\t\t\tif t, ok := ctx.convertParam(param, pt); ok {\n\t\t\t\tc[i] = t\n\t\t\t} else {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, t := range tables {\n\t\tc = append(c, reflect.ValueOf(makeTable(t)))\n\t}\n\n\treturn c, true\n}\n\nfunc (ctx *Context) convertParam(s string, target reflect.Type) (reflect.Value, bool) {\n\tfor regex, tx := range ctx.transforms {\n\t\tparams := regex.FindStringSubmatch(s)\n\t\tif params == nil || len(params) != 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tf := reflect.ValueOf(tx)\n\t\tfTyp := f.Type()\n\n\t\tin := make([]reflect.Value, fTyp.NumIn())\n\t\tin[0] = reflect.ValueOf(ctx)\n\t\tin[1] = reflect.ValueOf(s)\n\t\tin[2] = reflect.ValueOf(target)\n\n\t\tout := f.Call(in)\n\t\tif out[1].Interface().(bool) {\n\t\t\treturn reflect.ValueOf(out[0].Interface()), true\n\t\t}\n\t}\n\n\treturn reflect.Value{}, false\n}\n\n\/\/ Skip skips the current step execution and all subsequent steps\nfunc (ctx *Context) Skip(format string, args ...interface{}) {\n\tctx.logStepResult(\"⤹\", format, args...)\n\tctx.currentScenario.skipped = true\n}\n\nfunc (ctx *Context) stepNotFound() {\n\tctx.logStepResult(\"?\", \"\")\n\tctx.currentScenario.skipped = true\n}\n\nfunc (ctx *Context) stepPassed() {\n\tctx.logStepResult(\"✓\", \"\")\n}\n\n\/\/ Fail records test step failure\nfunc (ctx *Context) Fail() {\n\tctx.Failf(\"\")\n}\n\n\/\/ Failf logs the supplied message and records test step failure\nfunc (ctx *Context) Failf(format string, args ...interface{}) {\n\tctx.logStepResult(\"✘\", format, args...)\n\tctx.currentScenario.failed = true\n}\n\nfunc (ctx *Context) logScenarioStart() {\n\tfmt.Fprintf(&ctx.currentScenario.logbuf, \"\\n\\t%s\\n\", ctx.currentScenario.name)\n}\n\nfunc (ctx *Context) logStepResult(prefix, format string, args ...interface{}) {\n\tif len(format) > 0 {\n\t\tformat = fmt.Sprintf(\"\\t\\t%s %s\\t(%s)\\n\", prefix, ctx.currentScenario.currentStep, format)\n\t\tfmt.Fprintf(&ctx.currentScenario.logbuf, format, args...)\n\t} else {\n\t\tfmt.Fprintf(&ctx.currentScenario.logbuf, \"\\t\\t%s %s\\n\", prefix, ctx.currentScenario.currentStep)\n\t}\n}\n<commit_msg>Use Spec Path Instead of Name<commit_after>package elicit\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"bytes\"\n\t\"reflect\"\n)\n\n\/\/ Context stores test machinery and maintains state between specs\/scenarios\/steps\ntype Context struct {\n\tspecs           specCollection\n\tstepImpls       stepImplMap\n\ttransforms      transformMap\n\tcurrentSpec     *SpecContext\n\tcurrentScenario *ScenarioContext\n}\n\n\/\/ StepArgumentTransform transforms captured groups in the step pattern to a function parameter type\n\/\/ Note that if the actual string cannot be converted to the target type by the transform, it should return false\ntype StepArgumentTransform func(*Context, string, reflect.Type) (interface{}, bool)\n\ntype specCollection []specDef\ntype stepImplMap map[*regexp.Regexp]interface{}\ntype transformMap map[*regexp.Regexp]StepArgumentTransform\n\n\/\/ New creates a new elicit context which stores specs, steps and transforms\nfunc New() *Context {\n\tctx := &Context{\n\t\tstepImpls:  make(map[*regexp.Regexp]interface{}),\n\t\ttransforms: make(map[*regexp.Regexp]StepArgumentTransform),\n\t}\n\n\t\/\/ TODO discover these automatically\n\tctx.registerTransform(`.*`, stringTransform)\n\tctx.registerTransform(`-?\\d+`, intTransform)\n\tctx.registerTransform(`(?:.+,\\s*)*.+`, commaSliceTransform)\n\n\treturn ctx\n}\n\n\/\/ WithSpecsFolder recursively adds the path to the discovery path of specs\nfunc (ctx *Context) WithSpecsFolder(path string) *Context {\n\tctx.specs.parseSpecFolder(path)\n\treturn ctx\n}\n\n\/\/ WithSteps registers steps from the supplied map of patterns to functions\nfunc (ctx *Context) WithSteps(steps map[string]interface{}) *Context {\n\tfor p, fn := range steps {\n\t\tctx.registerStep(p, fn)\n\t}\n\treturn ctx\n}\n\nfunc (ctx *Context) registerStep(pattern string, stepFunc interface{}) {\n\n\tpattern = strings.TrimSpace(pattern)\n\tpattern = ensureCompleteMatch(pattern)\n\n\tp, err := regexp.Compile(pattern)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"compiling step regexp %q, %s\", pattern, err))\n\t}\n\n\t\/\/ TODO(matt) check the pattern captures the correct number of parameters\n\n\tctx.stepImpls[p] = stepFunc\n}\n\nfunc ensureCompleteMatch(pattern string) string {\n\tif !strings.HasPrefix(pattern, \"^\") {\n\t\tpattern = \"^\" + pattern\n\t}\n\n\tif !strings.HasSuffix(pattern, \"$\") {\n\t\tpattern = pattern + \"$\"\n\t}\n\n\treturn pattern\n}\n\n\/\/ WithTransforms registers step argument transforms from the suppled map of patterns to functions\nfunc (ctx *Context) WithTransforms(txs map[string]StepArgumentTransform) *Context {\n\tfor p, fn := range txs {\n\t\tctx.registerTransform(p, fn)\n\t}\n\treturn ctx\n}\n\nfunc (ctx *Context) registerTransform(pattern string, transform StepArgumentTransform) {\n\tpattern = ensureCompleteMatch(pattern)\n\n\tp, err := regexp.Compile(pattern)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"compiling transform regexp %q, %s\", pattern, err))\n\t}\n\n\tctx.transforms[p] = transform\n}\n\n\/\/ RunTests runs all the discovered specs as tests\nfunc (ctx *Context) RunTests(t *testing.T) {\n\tfor _, spec := range ctx.specs {\n\t\tctx.runSpecTest(t, spec)\n\t}\n}\n\nfunc (ctx *Context) runSpecTest(t *testing.T, spec specDef) {\n\tctx.currentSpec = &SpecContext{\n\t\tname: spec.Name,\n\t}\n\n\tt.Run(spec.Path, func(t *testing.T) {\n\t\tfor _, scenario := range spec.Scenarios {\n\t\t\tctx.runScenarioTest(t, scenario)\n\t\t}\n\t})\n}\n\nfunc (ctx *Context) runScenarioTest(t *testing.T, scenario scenarioDef) {\n\tctx.currentScenario = &ScenarioContext{\n\t\tname:    scenario.Name,\n\t\tskipped: false,\n\t\tfailed:  false,\n\t\tlogbuf:  bytes.Buffer{},\n\t}\n\tctx.logScenarioStart()\n\n\tt.Run(scenario.Name, func(t *testing.T) {\n\t\tfor _, b := range scenario.Spec.BeforeSteps {\n\t\t\tctx.runStep(t, b)\n\t\t}\n\n\t\tfor _, s := range scenario.Steps {\n\t\t\tctx.runStep(t, s)\n\t\t}\n\n\t\tfor _, a := range scenario.Spec.AfterSteps {\n\t\t\tctx.runStep(t, a)\n\t\t}\n\n\t\tlog := string(ctx.currentScenario.logbuf.Bytes())\n\t\tif ctx.currentScenario.failed {\n\t\t\tt.Errorf(log)\n\t\t} else if ctx.currentScenario.skipped {\n\t\t\tt.Skipf(log)\n\t\t}\n\t})\n}\n\nfunc (ctx *Context) runStep(t *testing.T, step stepDef) {\n\tctx.currentScenario.currentStep = step.Text\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tctx.Failf(\"panic during step execution: %s\", r)\n\t\t}\n\t}()\n\n\tfor regex, fn := range ctx.stepImpls {\n\t\tf := reflect.ValueOf(fn)\n\t\tparams := regex.FindStringSubmatch(step.Text)\n\n\t\tif in, ok := ctx.convertParams(f, params, step.Tables); ok {\n\n\t\t\tif !ctx.currentScenario.skipped && !ctx.currentScenario.failed {\n\t\t\t\tf.Call(in)\n\t\t\t} else {\n\t\t\t\tctx.Skip(\"\")\n\t\t\t}\n\n\t\t\tif !ctx.currentScenario.skipped && !ctx.currentScenario.failed {\n\t\t\t\tctx.stepPassed()\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\t}\n\n\tctx.stepNotFound()\n}\n\nfunc (ctx *Context) convertParams(f reflect.Value, stringParams []string, tables []stringTable) ([]reflect.Value, bool) {\n\n\tif stringParams == nil {\n\t\treturn nil, false\n\t}\n\n\tparamCount := f.Type().NumIn()\n\ttableParamCount := 0\n\ttableType := reflect.TypeOf((*Table)(nil)).Elem()\n\n\tfor p := paramCount - 1; p >= 0; p-- {\n\t\tthisParam := f.Type().In(p)\n\t\tif thisParam == tableType {\n\t\t\tparamCount--\n\t\t\ttableParamCount++\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif len(stringParams) != paramCount || tableParamCount != len(tables) {\n\t\treturn nil, false\n\t}\n\n\tc := make([]reflect.Value, len(stringParams))\n\tfor i, param := range stringParams {\n\t\tif i == 0 {\n\t\t\tif f.Type().In(0) != reflect.TypeOf(ctx) {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t\tc[i] = reflect.ValueOf(ctx)\n\t\t} else {\n\t\t\tpt := f.Type().In(i)\n\n\t\t\tif t, ok := ctx.convertParam(param, pt); ok {\n\t\t\t\tc[i] = t\n\t\t\t} else {\n\t\t\t\treturn nil, false\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, t := range tables {\n\t\tc = append(c, reflect.ValueOf(makeTable(t)))\n\t}\n\n\treturn c, true\n}\n\nfunc (ctx *Context) convertParam(s string, target reflect.Type) (reflect.Value, bool) {\n\tfor regex, tx := range ctx.transforms {\n\t\tparams := regex.FindStringSubmatch(s)\n\t\tif params == nil || len(params) != 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tf := reflect.ValueOf(tx)\n\t\tfTyp := f.Type()\n\n\t\tin := make([]reflect.Value, fTyp.NumIn())\n\t\tin[0] = reflect.ValueOf(ctx)\n\t\tin[1] = reflect.ValueOf(s)\n\t\tin[2] = reflect.ValueOf(target)\n\n\t\tout := f.Call(in)\n\t\tif out[1].Interface().(bool) {\n\t\t\treturn reflect.ValueOf(out[0].Interface()), true\n\t\t}\n\t}\n\n\treturn reflect.Value{}, false\n}\n\n\/\/ Skip skips the current step execution and all subsequent steps\nfunc (ctx *Context) Skip(format string, args ...interface{}) {\n\tctx.logStepResult(\"⤹\", format, args...)\n\tctx.currentScenario.skipped = true\n}\n\nfunc (ctx *Context) stepNotFound() {\n\tctx.logStepResult(\"?\", \"\")\n\tctx.currentScenario.skipped = true\n}\n\nfunc (ctx *Context) stepPassed() {\n\tctx.logStepResult(\"✓\", \"\")\n}\n\n\/\/ Fail records test step failure\nfunc (ctx *Context) Fail() {\n\tctx.Failf(\"\")\n}\n\n\/\/ Failf logs the supplied message and records test step failure\nfunc (ctx *Context) Failf(format string, args ...interface{}) {\n\tctx.logStepResult(\"✘\", format, args...)\n\tctx.currentScenario.failed = true\n}\n\nfunc (ctx *Context) logScenarioStart() {\n\tfmt.Fprintf(&ctx.currentScenario.logbuf, \"\\n\\t%s\\n\", ctx.currentScenario.name)\n}\n\nfunc (ctx *Context) logStepResult(prefix, format string, args ...interface{}) {\n\tif len(format) > 0 {\n\t\tformat = fmt.Sprintf(\"\\t\\t%s %s\\t(%s)\\n\", prefix, ctx.currentScenario.currentStep, format)\n\t\tfmt.Fprintf(&ctx.currentScenario.logbuf, format, args...)\n\t} else {\n\t\tfmt.Fprintf(&ctx.currentScenario.logbuf, \"\\t\\t%s %s\\n\", prefix, ctx.currentScenario.currentStep)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package app\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/murlokswarm\/log\"\n\t\"github.com\/murlokswarm\/markup\"\n\t\"github.com\/murlokswarm\/uid\"\n)\n\nvar (\n\tcontexts = map[uid.ID]Contexter{}\n)\n\n\/\/ Contexter represents the support where a component can be mounted.\n\/\/ eg a window.\ntype Contexter interface {\n\t\/\/ The ID of the context.\n\tID() uid.ID\n\n\t\/\/ Mounts the component and renders it in the context.\n\tMount(c markup.Componer)\n\n\t\/\/ Renders an element.\n\tRender(elem *markup.Element)\n\n\t\/\/ If applicable, return the position of the context.\n\tPosition() (x float64, y float64)\n\n\t\/\/ If applicable, moves the context.\n\tMove(x float64, y float64)\n\n\t\/\/ If applicable, return the size of the context.\n\tSize() (width float64, height float64)\n\n\t\/\/ If applicable, resizes the context.\n\tResize(width float64, height float64)\n\n\t\/\/ If applicable, set the icon targeted by path.\n\tSetIcon(path string)\n\n\t\/\/ Close the context.\n\t\/\/ Should call markup.Dismount on its root component.\n\t\/\/ Should call UnregisterContext on itself.\n\t\/\/ Should perform additional cleanup if required.\n\tClose()\n}\n\n\/\/ Context returns the context of c.\n\/\/ c must be mounted.\nfunc Context(c markup.Componer) (ctx Contexter, err error) {\n\tvar root *markup.Element\n\n\tif root, err = markup.ComponentRoot(c); err != nil {\n\t\treturn\n\t}\n\n\tctx, err = ContextByID(root.ContextID)\n\treturn\n}\n\n\/\/ ContextByID returns the context registered under id.\nfunc ContextByID(id uid.ID) (ctx Contexter, err error) {\n\tvar registered bool\n\n\tif ctx, registered = contexts[id]; !registered {\n\t\terr = fmt.Errorf(\"context %v is not registered or has been closed\", id)\n\t}\n\n\treturn\n}\n\n\/\/ RegisterContext registers c.\n\/\/ Should be used only in a driver implementation.\nfunc RegisterContext(c Contexter) {\n\tif len(c.ID()) == 0 {\n\t\tlog.Panicf(\"context %T is invalid. ID must be set\", c)\n\t}\n\n\tif _, registered := contexts[c.ID()]; registered {\n\t\tlog.Panicf(\"context %T with id %v is already registered\", c, c.ID())\n\t}\n\n\tcontexts[c.ID()] = c\n}\n\n\/\/ UnregisterContext unregisters c.\n\/\/ Should be used only in a driver implementation.\nfunc UnregisterContext(c Contexter) {\n\tdelete(contexts, c.ID())\n}\n\n\/\/ ZeroContext is a placeholder context.\n\/\/ It's used as a replacement for non available or non implemented features.\n\/\/\n\/\/ Use of methods from a ZeroContext doesn't do anything.\ntype ZeroContext struct {\n\tid          uid.ID\n\tplaceholder string\n\troot        markup.Componer\n}\n\n\/\/ NewZeroContext creates a ZeroContext.\nfunc NewZeroContext(placeholder string) (ctx *ZeroContext) {\n\tctx = &ZeroContext{\n\t\tid:          uid.Context(),\n\t\tplaceholder: placeholder,\n\t}\n\n\tRegisterContext(ctx)\n\treturn\n}\n\n\/\/ ID returns the ID of the context.\nfunc (c *ZeroContext) ID() uid.ID {\n\treturn c.id\n}\n\n\/\/ Mount is a placeholder method to satisfy the Contexter interface.\n\/\/ It does nothing.\nfunc (c *ZeroContext) Mount(component markup.Componer) {\n\tmarkup.Mount(component, c.ID())\n\tlog.Infof(\"%T is mounted into %v (%v)\", component, c.placeholder, c.ID())\n}\n\n\/\/ Render is a placeholder method to satisfy the Contexter interface.\n\/\/ It does nothing.\nfunc (c *ZeroContext) Render(elem *markup.Element) {\n\tlog.Infof(\"rendering:\\n\\033[32m%v\\033[00m\", elem.HTML())\n}\n\n\/\/ Size is a placeholder method to satisfy the Contexter interface.\nfunc (c *ZeroContext) Size() (width float64, height float64) {\n\treturn\n}\n\n\/\/ Resize is a placeholder method to satisfy the Contexter interface.\n\/\/ It does nothing.\nfunc (c *ZeroContext) Resize(width float64, height float64) {\n\tlog.Infof(\"%v (%v) simulates a resize of %v x %v\", c.placeholder, c.ID(), width, height)\n}\n\n\/\/ Position is a placeholder method to satisfy the Contexter interface.\nfunc (c *ZeroContext) Position() (x float64, y float64) {\n\treturn\n}\n\n\/\/ Move is a placeholder method to satisfy the Contexter interface.\n\/\/ It does nothing.\nfunc (c *ZeroContext) Move(x float64, y float64) {\n\tlog.Infof(\"%v (%v) simulates a move to (%v, %v)\", c.placeholder, c.ID(), x, y)\n}\n\n\/\/ SetIcon is a placeholder method to satisfy the Contexter interface.\n\/\/ It does nothing.\nfunc (c *ZeroContext) SetIcon(path string) {\n\tlog.Infof(\"%v (%v) simulates set icon with %v\", c.placeholder, c.ID(), path)\n}\n\n\/\/ Close is a closes the context.\nfunc (c *ZeroContext) Close() {\n\tmarkup.Dismount(c.root)\n\tUnregisterContext(c)\n\tlog.Infof(\"%v (%v) is closed\", c.placeholder, c.ID())\n}\n<commit_msg>doc update<commit_after>package app\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/murlokswarm\/log\"\n\t\"github.com\/murlokswarm\/markup\"\n\t\"github.com\/murlokswarm\/uid\"\n)\n\nvar (\n\tcontexts = map[uid.ID]Contexter{}\n)\n\n\/\/ Contexter represents the support where a component can be mounted.\n\/\/ eg a window.\ntype Contexter interface {\n\t\/\/ The ID of the context.\n\tID() uid.ID\n\n\t\/\/ Mounts the component and renders it in the context.\n\tMount(c markup.Componer)\n\n\t\/\/ Renders an element.\n\tRender(elem *markup.Element)\n\n\t\/\/ If applicable, returns the position of the context.\n\tPosition() (x float64, y float64)\n\n\t\/\/ If applicable, moves the context.\n\tMove(x float64, y float64)\n\n\t\/\/ If applicable, returns the size of the context.\n\tSize() (width float64, height float64)\n\n\t\/\/ If applicable, resizes the context.\n\tResize(width float64, height float64)\n\n\t\/\/ If applicable, set the icon targeted by path.\n\tSetIcon(path string)\n\n\t\/\/ If applicablex, closes the context.\n\tClose()\n}\n\n\/\/ Context returns the context of c.\n\/\/ c must be mounted.\nfunc Context(c markup.Componer) (ctx Contexter, err error) {\n\tvar root *markup.Element\n\n\tif root, err = markup.ComponentRoot(c); err != nil {\n\t\treturn\n\t}\n\n\tctx, err = ContextByID(root.ContextID)\n\treturn\n}\n\n\/\/ ContextByID returns the context registered under id.\nfunc ContextByID(id uid.ID) (ctx Contexter, err error) {\n\tvar registered bool\n\n\tif ctx, registered = contexts[id]; !registered {\n\t\terr = fmt.Errorf(\"context %v is not registered or has been closed\", id)\n\t}\n\n\treturn\n}\n\n\/\/ RegisterContext registers c.\n\/\/ Should be used only in a driver implementation.\nfunc RegisterContext(c Contexter) {\n\tif len(c.ID()) == 0 {\n\t\tlog.Panicf(\"context %T is invalid. ID must be set\", c)\n\t}\n\n\tif _, registered := contexts[c.ID()]; registered {\n\t\tlog.Panicf(\"context %T with id %v is already registered\", c, c.ID())\n\t}\n\n\tcontexts[c.ID()] = c\n}\n\n\/\/ UnregisterContext unregisters c.\n\/\/ Should be used only in a driver implementation.\nfunc UnregisterContext(c Contexter) {\n\tdelete(contexts, c.ID())\n}\n\n\/\/ ZeroContext is a placeholder context.\n\/\/ It's used as a replacement for non available or non implemented features.\n\/\/\n\/\/ Use of methods from a ZeroContext doesn't do anything.\ntype ZeroContext struct {\n\tid          uid.ID\n\tplaceholder string\n\troot        markup.Componer\n}\n\n\/\/ NewZeroContext creates a ZeroContext.\nfunc NewZeroContext(placeholder string) (ctx *ZeroContext) {\n\tctx = &ZeroContext{\n\t\tid:          uid.Context(),\n\t\tplaceholder: placeholder,\n\t}\n\n\tRegisterContext(ctx)\n\treturn\n}\n\n\/\/ ID returns the ID of the context.\nfunc (c *ZeroContext) ID() uid.ID {\n\treturn c.id\n}\n\n\/\/ Mount is a placeholder method to satisfy the Contexter interface.\n\/\/ It does nothing.\nfunc (c *ZeroContext) Mount(component markup.Componer) {\n\tmarkup.Mount(component, c.ID())\n\tlog.Infof(\"%T is mounted into %v (%v)\", component, c.placeholder, c.ID())\n}\n\n\/\/ Render is a placeholder method to satisfy the Contexter interface.\n\/\/ It does nothing.\nfunc (c *ZeroContext) Render(elem *markup.Element) {\n\tlog.Infof(\"rendering:\\n\\033[32m%v\\033[00m\", elem.HTML())\n}\n\n\/\/ Size is a placeholder method to satisfy the Contexter interface.\nfunc (c *ZeroContext) Size() (width float64, height float64) {\n\treturn\n}\n\n\/\/ Resize is a placeholder method to satisfy the Contexter interface.\n\/\/ It does nothing.\nfunc (c *ZeroContext) Resize(width float64, height float64) {\n\tlog.Infof(\"%v (%v) simulates a resize of %v x %v\", c.placeholder, c.ID(), width, height)\n}\n\n\/\/ Position is a placeholder method to satisfy the Contexter interface.\nfunc (c *ZeroContext) Position() (x float64, y float64) {\n\treturn\n}\n\n\/\/ Move is a placeholder method to satisfy the Contexter interface.\n\/\/ It does nothing.\nfunc (c *ZeroContext) Move(x float64, y float64) {\n\tlog.Infof(\"%v (%v) simulates a move to (%v, %v)\", c.placeholder, c.ID(), x, y)\n}\n\n\/\/ SetIcon is a placeholder method to satisfy the Contexter interface.\n\/\/ It does nothing.\nfunc (c *ZeroContext) SetIcon(path string) {\n\tlog.Infof(\"%v (%v) simulates set icon with %v\", c.placeholder, c.ID(), path)\n}\n\n\/\/ Close is a closes the context.\nfunc (c *ZeroContext) Close() {\n\tmarkup.Dismount(c.root)\n\tUnregisterContext(c)\n\tlog.Infof(\"%v (%v) is closed\", c.placeholder, c.ID())\n}\n<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Context is a type that is passed through to\n\/\/ each Handler action in a cli application. Context\n\/\/ can be used to retrieve context-specific Args and\n\/\/ parsed command-line options.\ntype Context struct {\n\tApp       *App\n\tCommand   Command\n\tflagSet   *flag.FlagSet\n\tglobalSet *flag.FlagSet\n\tsetFlags  map[string]bool\n}\n\n\/\/ Creates a new context. For use in when invoking an App or Command action.\nfunc NewContext(app *App, set *flag.FlagSet, globalSet *flag.FlagSet) *Context {\n\treturn &Context{App: app, flagSet: set, globalSet: globalSet}\n}\n\n\/\/ Looks up the value of a local int flag, returns 0 if no int flag exists\nfunc (c *Context) Int(name string) int {\n\treturn lookupInt(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local time.Duration flag, returns 0 if no time.Duration flag exists\nfunc (c *Context) Duration(name string) time.Duration {\n\treturn lookupDuration(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local float64 flag, returns 0 if no float64 flag exists\nfunc (c *Context) Float64(name string) float64 {\n\treturn lookupFloat64(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local bool flag, returns false if no bool flag exists\nfunc (c *Context) Bool(name string) bool {\n\treturn lookupBool(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local boolT flag, returns false if no bool flag exists\nfunc (c *Context) BoolT(name string) bool {\n\treturn lookupBoolT(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local string flag, returns \"\" if no string flag exists\nfunc (c *Context) String(name string) string {\n\treturn lookupString(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local string slice flag, returns nil if no string slice flag exists\nfunc (c *Context) StringSlice(name string) []string {\n\treturn lookupStringSlice(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local int slice flag, returns nil if no int slice flag exists\nfunc (c *Context) IntSlice(name string) []int {\n\treturn lookupIntSlice(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local generic flag, returns nil if no generic flag exists\nfunc (c *Context) Generic(name string) interface{} {\n\treturn lookupGeneric(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a global int flag, returns 0 if no int flag exists\nfunc (c *Context) GlobalInt(name string) int {\n\treturn lookupInt(name, c.globalSet)\n}\n\n\/\/ Looks up the value of a global time.Duration flag, returns 0 if no time.Duration flag exists\nfunc (c *Context) GlobalDuration(name string) time.Duration {\n\treturn lookupDuration(name, c.globalSet)\n}\n\n\/\/ Looks up the value of a global bool flag, returns false if no bool flag exists\nfunc (c *Context) GlobalBool(name string) bool {\n\treturn lookupBool(name, c.globalSet)\n}\n\n\/\/ Looks up the value of a global string flag, returns \"\" if no string flag exists\nfunc (c *Context) GlobalString(name string) string {\n\treturn lookupString(name, c.globalSet)\n}\n\n\/\/ Looks up the value of a global string slice flag, returns nil if no string slice flag exists\nfunc (c *Context) GlobalStringSlice(name string) []string {\n\treturn lookupStringSlice(name, c.globalSet)\n}\n\n\/\/ Looks up the value of a global int slice flag, returns nil if no int slice flag exists\nfunc (c *Context) GlobalIntSlice(name string) []int {\n\treturn lookupIntSlice(name, c.globalSet)\n}\n\n\/\/ Looks up the value of a global generic flag, returns nil if no generic flag exists\nfunc (c *Context) GlobalGeneric(name string) interface{} {\n\treturn lookupGeneric(name, c.globalSet)\n}\n\n\/\/ Determines if the flag was actually set exists\nfunc (c *Context) IsSet(name string) bool {\n\tif c.setFlags == nil {\n\t\tc.setFlags = make(map[string]bool)\n\t\tc.flagSet.Visit(func(f *flag.Flag) {\n\t\t\tc.setFlags[f.Name] = true\n\t\t})\n\t}\n\treturn c.setFlags[name] == true\n}\n\n\/\/ Returns a slice of flag names used in this context.\nfunc (c *Context) FlagNames() (names []string) {\n\tfor _, flag := range c.Command.Flags {\n\t\tname := strings.Split(flag.getName(), \",\")[0]\n\t\tif name == \"help\" {\n\t\t\tcontinue\n\t\t}\n\t\tnames = append(names, name)\n\t}\n\treturn\n}\n\ntype Args []string\n\n\/\/ Returns the command line arguments associated with the context.\nfunc (c *Context) Args() Args {\n\targs := Args(c.flagSet.Args())\n\treturn args\n}\n\n\/\/ Returns the nth argument, or else a blank string\nfunc (a Args) Get(n int) string {\n\tif len(a) > n {\n\t\treturn a[n]\n\t}\n\treturn \"\"\n}\n\n\/\/ Returns the first argument, or else a blank string\nfunc (a Args) First() string {\n\treturn a.Get(0)\n}\n\n\/\/ Return the rest of the arguments (not the first one)\n\/\/ or else an empty string slice\nfunc (a Args) Tail() []string {\n\tif len(a) >= 2 {\n\t\treturn []string(a)[1:]\n\t}\n\treturn []string{}\n}\n\n\/\/ Checks if there are any arguments present\nfunc (a Args) Present() bool {\n\treturn len(a) != 0\n}\n\n\/\/ Swaps arguments at the given indexes\nfunc (a Args) Swap(from, to int) error {\n\tif from >= len(a) || to >= len(a) {\n\t\treturn errors.New(\"index out of range\")\n\t}\n\ta[from], a[to] = a[to], a[from]\n\treturn nil\n}\n\nfunc lookupInt(name string, set *flag.FlagSet) int {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\tval, err := strconv.Atoi(f.Value.String())\n\t\tif err != nil {\n\t\t\treturn 0\n\t\t}\n\t\treturn val\n\t}\n\n\treturn 0\n}\n\nfunc lookupDuration(name string, set *flag.FlagSet) time.Duration {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\tval, err := time.ParseDuration(f.Value.String())\n\t\tif err == nil {\n\t\t\treturn val\n\t\t}\n\t}\n\n\treturn 0\n}\n\nfunc lookupFloat64(name string, set *flag.FlagSet) float64 {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\tval, err := strconv.ParseFloat(f.Value.String(), 64)\n\t\tif err != nil {\n\t\t\treturn 0\n\t\t}\n\t\treturn val\n\t}\n\n\treturn 0\n}\n\nfunc lookupString(name string, set *flag.FlagSet) string {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\treturn f.Value.String()\n\t}\n\n\treturn \"\"\n}\n\nfunc lookupStringSlice(name string, set *flag.FlagSet) []string {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\treturn (f.Value.(*StringSlice)).Value()\n\n\t}\n\n\treturn nil\n}\n\nfunc lookupIntSlice(name string, set *flag.FlagSet) []int {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\treturn (f.Value.(*IntSlice)).Value()\n\n\t}\n\n\treturn nil\n}\n\nfunc lookupGeneric(name string, set *flag.FlagSet) interface{} {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\treturn f.Value\n\t}\n\treturn nil\n}\n\nfunc lookupBool(name string, set *flag.FlagSet) bool {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\tval, err := strconv.ParseBool(f.Value.String())\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn val\n\t}\n\n\treturn false\n}\n\nfunc lookupBoolT(name string, set *flag.FlagSet) bool {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\tval, err := strconv.ParseBool(f.Value.String())\n\t\tif err != nil {\n\t\t\treturn true\n\t\t}\n\t\treturn val\n\t}\n\n\treturn false\n}\n\nfunc copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {\n\tswitch ff.Value.(type) {\n\tcase *StringSlice:\n\tdefault:\n\t\tset.Set(name, ff.Value.String())\n\t}\n}\n\nfunc normalizeFlags(flags []Flag, set *flag.FlagSet) error {\n\tvisited := make(map[string]bool)\n\tset.Visit(func(f *flag.Flag) {\n\t\tvisited[f.Name] = true\n\t})\n\tfor _, f := range flags {\n\t\tparts := strings.Split(f.getName(), \",\")\n\t\tif len(parts) == 1 {\n\t\t\tcontinue\n\t\t}\n\t\tvar ff *flag.Flag\n\t\tfor _, name := range parts {\n\t\t\tname = strings.Trim(name, \" \")\n\t\t\tif visited[name] {\n\t\t\t\tif ff != nil {\n\t\t\t\t\treturn errors.New(\"Cannot use two forms of the same flag: \" + name + \" \" + ff.Name)\n\t\t\t\t}\n\t\t\t\tff = set.Lookup(name)\n\t\t\t}\n\t\t}\n\t\tif ff == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, name := range parts {\n\t\t\tname = strings.Trim(name, \" \")\n\t\t\tif !visited[name] {\n\t\t\t\tcopyFlag(name, ff, set)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Add Context.GlobalFlagNames()<commit_after>package cli\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Context is a type that is passed through to\n\/\/ each Handler action in a cli application. Context\n\/\/ can be used to retrieve context-specific Args and\n\/\/ parsed command-line options.\ntype Context struct {\n\tApp       *App\n\tCommand   Command\n\tflagSet   *flag.FlagSet\n\tglobalSet *flag.FlagSet\n\tsetFlags  map[string]bool\n}\n\n\/\/ Creates a new context. For use in when invoking an App or Command action.\nfunc NewContext(app *App, set *flag.FlagSet, globalSet *flag.FlagSet) *Context {\n\treturn &Context{App: app, flagSet: set, globalSet: globalSet}\n}\n\n\/\/ Looks up the value of a local int flag, returns 0 if no int flag exists\nfunc (c *Context) Int(name string) int {\n\treturn lookupInt(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local time.Duration flag, returns 0 if no time.Duration flag exists\nfunc (c *Context) Duration(name string) time.Duration {\n\treturn lookupDuration(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local float64 flag, returns 0 if no float64 flag exists\nfunc (c *Context) Float64(name string) float64 {\n\treturn lookupFloat64(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local bool flag, returns false if no bool flag exists\nfunc (c *Context) Bool(name string) bool {\n\treturn lookupBool(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local boolT flag, returns false if no bool flag exists\nfunc (c *Context) BoolT(name string) bool {\n\treturn lookupBoolT(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local string flag, returns \"\" if no string flag exists\nfunc (c *Context) String(name string) string {\n\treturn lookupString(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local string slice flag, returns nil if no string slice flag exists\nfunc (c *Context) StringSlice(name string) []string {\n\treturn lookupStringSlice(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local int slice flag, returns nil if no int slice flag exists\nfunc (c *Context) IntSlice(name string) []int {\n\treturn lookupIntSlice(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a local generic flag, returns nil if no generic flag exists\nfunc (c *Context) Generic(name string) interface{} {\n\treturn lookupGeneric(name, c.flagSet)\n}\n\n\/\/ Looks up the value of a global int flag, returns 0 if no int flag exists\nfunc (c *Context) GlobalInt(name string) int {\n\treturn lookupInt(name, c.globalSet)\n}\n\n\/\/ Looks up the value of a global time.Duration flag, returns 0 if no time.Duration flag exists\nfunc (c *Context) GlobalDuration(name string) time.Duration {\n\treturn lookupDuration(name, c.globalSet)\n}\n\n\/\/ Looks up the value of a global bool flag, returns false if no bool flag exists\nfunc (c *Context) GlobalBool(name string) bool {\n\treturn lookupBool(name, c.globalSet)\n}\n\n\/\/ Looks up the value of a global string flag, returns \"\" if no string flag exists\nfunc (c *Context) GlobalString(name string) string {\n\treturn lookupString(name, c.globalSet)\n}\n\n\/\/ Looks up the value of a global string slice flag, returns nil if no string slice flag exists\nfunc (c *Context) GlobalStringSlice(name string) []string {\n\treturn lookupStringSlice(name, c.globalSet)\n}\n\n\/\/ Looks up the value of a global int slice flag, returns nil if no int slice flag exists\nfunc (c *Context) GlobalIntSlice(name string) []int {\n\treturn lookupIntSlice(name, c.globalSet)\n}\n\n\/\/ Looks up the value of a global generic flag, returns nil if no generic flag exists\nfunc (c *Context) GlobalGeneric(name string) interface{} {\n\treturn lookupGeneric(name, c.globalSet)\n}\n\n\/\/ Determines if the flag was actually set exists\nfunc (c *Context) IsSet(name string) bool {\n\tif c.setFlags == nil {\n\t\tc.setFlags = make(map[string]bool)\n\t\tc.flagSet.Visit(func(f *flag.Flag) {\n\t\t\tc.setFlags[f.Name] = true\n\t\t})\n\t}\n\treturn c.setFlags[name] == true\n}\n\n\/\/ Returns a slice of flag names used in this context.\nfunc (c *Context) FlagNames() (names []string) {\n\tfor _, flag := range c.Command.Flags {\n\t\tname := strings.Split(flag.getName(), \",\")[0]\n\t\tif name == \"help\" {\n\t\t\tcontinue\n\t\t}\n\t\tnames = append(names, name)\n\t}\n\treturn\n}\n\n\/\/ Returns a slice of global flag names used by the app.\nfunc (c *Context) GlobalFlagNames() (names []string) {\n\tfor _, flag := range c.App.Flags {\n\t\tname := strings.Split(flag.getName(), \",\")[0]\n\t\tif name == \"help\" || name == \"version\" {\n\t\t\tcontinue\n\t\t}\n\t\tnames = append(names, name)\n\t}\n\treturn\n}\n\ntype Args []string\n\n\/\/ Returns the command line arguments associated with the context.\nfunc (c *Context) Args() Args {\n\targs := Args(c.flagSet.Args())\n\treturn args\n}\n\n\/\/ Returns the nth argument, or else a blank string\nfunc (a Args) Get(n int) string {\n\tif len(a) > n {\n\t\treturn a[n]\n\t}\n\treturn \"\"\n}\n\n\/\/ Returns the first argument, or else a blank string\nfunc (a Args) First() string {\n\treturn a.Get(0)\n}\n\n\/\/ Return the rest of the arguments (not the first one)\n\/\/ or else an empty string slice\nfunc (a Args) Tail() []string {\n\tif len(a) >= 2 {\n\t\treturn []string(a)[1:]\n\t}\n\treturn []string{}\n}\n\n\/\/ Checks if there are any arguments present\nfunc (a Args) Present() bool {\n\treturn len(a) != 0\n}\n\n\/\/ Swaps arguments at the given indexes\nfunc (a Args) Swap(from, to int) error {\n\tif from >= len(a) || to >= len(a) {\n\t\treturn errors.New(\"index out of range\")\n\t}\n\ta[from], a[to] = a[to], a[from]\n\treturn nil\n}\n\nfunc lookupInt(name string, set *flag.FlagSet) int {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\tval, err := strconv.Atoi(f.Value.String())\n\t\tif err != nil {\n\t\t\treturn 0\n\t\t}\n\t\treturn val\n\t}\n\n\treturn 0\n}\n\nfunc lookupDuration(name string, set *flag.FlagSet) time.Duration {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\tval, err := time.ParseDuration(f.Value.String())\n\t\tif err == nil {\n\t\t\treturn val\n\t\t}\n\t}\n\n\treturn 0\n}\n\nfunc lookupFloat64(name string, set *flag.FlagSet) float64 {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\tval, err := strconv.ParseFloat(f.Value.String(), 64)\n\t\tif err != nil {\n\t\t\treturn 0\n\t\t}\n\t\treturn val\n\t}\n\n\treturn 0\n}\n\nfunc lookupString(name string, set *flag.FlagSet) string {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\treturn f.Value.String()\n\t}\n\n\treturn \"\"\n}\n\nfunc lookupStringSlice(name string, set *flag.FlagSet) []string {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\treturn (f.Value.(*StringSlice)).Value()\n\n\t}\n\n\treturn nil\n}\n\nfunc lookupIntSlice(name string, set *flag.FlagSet) []int {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\treturn (f.Value.(*IntSlice)).Value()\n\n\t}\n\n\treturn nil\n}\n\nfunc lookupGeneric(name string, set *flag.FlagSet) interface{} {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\treturn f.Value\n\t}\n\treturn nil\n}\n\nfunc lookupBool(name string, set *flag.FlagSet) bool {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\tval, err := strconv.ParseBool(f.Value.String())\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn val\n\t}\n\n\treturn false\n}\n\nfunc lookupBoolT(name string, set *flag.FlagSet) bool {\n\tf := set.Lookup(name)\n\tif f != nil {\n\t\tval, err := strconv.ParseBool(f.Value.String())\n\t\tif err != nil {\n\t\t\treturn true\n\t\t}\n\t\treturn val\n\t}\n\n\treturn false\n}\n\nfunc copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {\n\tswitch ff.Value.(type) {\n\tcase *StringSlice:\n\tdefault:\n\t\tset.Set(name, ff.Value.String())\n\t}\n}\n\nfunc normalizeFlags(flags []Flag, set *flag.FlagSet) error {\n\tvisited := make(map[string]bool)\n\tset.Visit(func(f *flag.Flag) {\n\t\tvisited[f.Name] = true\n\t})\n\tfor _, f := range flags {\n\t\tparts := strings.Split(f.getName(), \",\")\n\t\tif len(parts) == 1 {\n\t\t\tcontinue\n\t\t}\n\t\tvar ff *flag.Flag\n\t\tfor _, name := range parts {\n\t\t\tname = strings.Trim(name, \" \")\n\t\t\tif visited[name] {\n\t\t\t\tif ff != nil {\n\t\t\t\t\treturn errors.New(\"Cannot use two forms of the same flag: \" + name + \" \" + ff.Name)\n\t\t\t\t}\n\t\t\t\tff = set.Lookup(name)\n\t\t\t}\n\t\t}\n\t\tif ff == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, name := range parts {\n\t\t\tname = strings.Trim(name, \" \")\n\t\t\tif !visited[name] {\n\t\t\t\tcopyFlag(name, ff, set)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package webapp\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/julienschmidt\/httprouter\"\n\t\"github.com\/mbict\/binding\"\n\t\"github.com\/mbict\/render\"\n)\n\ntype Context struct {\n\tRequest  *http.Request\n\tResponse ResponseWriter\n\tParams   httprouter.Params\n\tErrors   Errors\n\n\tvalues   map[interface{}]interface{}\n\thandlers []HandlerFunc\n\tindex    int8\n\tengine   *Engine\n}\n\n\/************************************\/\n\/********** CONTEXT CREATION ********\/\n\/************************************\/\n\nfunc (engine *Engine) createContext(rw http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {\n\treturn &Context{\n\t\tResponse: newResponseWriter(rw),\n\t\tRequest:  req,\n\t\tParams:   params,\n\t\thandlers: handlers,\n\t\tErrors:   nil,\n\t\tindex:    -1,\n\t\tengine:   engine,\n\t}\n}\n\n\/************************************\/\n\/*************** FLOW ***************\/\n\/************************************\/\n\n\/\/ Next should be used only in the middlewares.\n\/\/ It executes the pending handlers in the chain inside the calling handler.\n\/\/ See example in github.\nfunc (ctx *Context) Next() {\n\tctx.index++\n\ts := int8(len(ctx.handlers))\n\tfor ; ctx.index < s; ctx.index++ {\n\t\tctx.handlers[ctx.index](ctx)\n\t}\n}\n\n\/\/ Forces the system to do not continue calling the pending handlers in the chain.\nfunc (ctx *Context) Abort() {\n\tctx.index = AbortIndex\n}\n\n\/************************************\/\n\/******** METADATA MANAGEMENT********\/\n\/************************************\/\n\n\/\/ Sets a new pair key\/value just for the specified context.\n\/\/ It also lazy initializes the hashmap.\nfunc (ctx *Context) Set(key interface{}, item interface{}) {\n\tif ctx.values == nil {\n\t\tctx.values = make(map[interface{}]interface{})\n\t}\n\tctx.values[key] = item\n}\n\n\/\/ Get returns the value for the given key or an error if the key does not exist.\nfunc (ctx *Context) Get(key interface{}) interface{} {\n\tif ctx.values != nil {\n\t\tvalue, ok := ctx.values[key]\n\t\tif ok {\n\t\t\treturn value\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (ctx *Context) GetOk(key interface{}) (interface{}, bool) {\n\tif ctx.values != nil {\n\t\tvalue, ok := ctx.values[key]\n\t\tif ok {\n\t\t\treturn value, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (ctx *Context) ClientIP() string {\n\treturn ctx.Request.RemoteAddr\n}\n\n\/************************************\/\n\/********* PARSING REQUEST **********\/\n\/************************************\/\nfunc (ctx *Context) Bind(obj interface{}) binding.Errors {\n\treturn binding.Bind(obj, ctx.Request)\n}\n\nfunc (ctx *Context) BindWith(obj interface{}, b binding.Binding) binding.Errors {\n\treturn b.Bind(obj, ctx.Request)\n}\n\n\/************************************\/\n\/******** RESPONSE RENDERING ********\/\n\/************************************\/\n\nfunc (ctx *Context) Render(code int, render render.Render, obj ...interface{}) {\n\tif err := render.Render(ctx.Response, code, obj...); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Serializes the given struct as JSON into the response body in a fast and efficient way.\n\/\/ It also sets the Content-Type as \"application\/json\".\nfunc (ctx *Context) JSON(code int, obj interface{}) {\n\tctx.Render(code, render.JSON, obj)\n}\n\n\/\/ Serializes the given struct as XML into the response body in a fast and efficient way.\n\/\/ It also sets the Content-Type as \"application\/xml\".\nfunc (ctx *Context) XML(code int, obj interface{}) {\n\tctx.Render(code, render.XML, obj)\n}\n\n\/\/ Renders the HTTP template specified by its file name.\n\/\/ It also updates the HTTP code and sets the Content-Type as \"text\/html\".\n\/\/ See http:\/\/golang.org\/doc\/articles\/wiki\/\nfunc (ctx *Context) HTML(code int, name string, obj ...interface{}) {\n\tctx.Render(code, ctx.engine.templateRender, name, obj)\n}\n\n\/\/ Writes the given string into the response body and sets the Content-Type to \"text\/plain\".\nfunc (ctx *Context) String(code int, format string, values ...interface{}) {\n\tctx.Render(code, render.Plain, format, values)\n}\n\n\/\/ Writes the given string into the response body and sets the Content-Type to \"text\/html\" without template.\nfunc (ctx *Context) HTMLString(code int, format string, values ...interface{}) {\n\tctx.Render(code, render.HtmlPlain, format, values)\n}\n\n\/\/ Returns a HTTP redirect to the specific location.\nfunc (ctx *Context) Redirect(code int, location string) {\n\tif code >= 300 && code <= 308 {\n\t\tctx.Render(code, render.Redirect, location)\n\t} else {\n\t\tpanic(fmt.Sprintf(\"Cannot send a redirect with status code %d\", code))\n\t}\n}\n\n\/\/ Writes some data into the body stream and updates the HTTP code.\nfunc (ctx *Context) Data(code int, contentType string, data []byte) {\n\tif len(contentType) > 0 {\n\t\tctx.Response.Header().Set(\"Content-Type\", contentType)\n\t}\n\tctx.Response.WriteHeader(code)\n\tctx.Response.Write(data)\n}\n\n\/\/ Writes the specified file into the body stream\nfunc (ctx *Context) File(filepath string) {\n\thttp.ServeFile(ctx.Response, ctx.Request, filepath)\n}\n<commit_msg>Typo in param passing in context render helper functions<commit_after>package webapp\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/julienschmidt\/httprouter\"\n\t\"github.com\/mbict\/binding\"\n\t\"github.com\/mbict\/render\"\n)\n\ntype Context struct {\n\tRequest  *http.Request\n\tResponse ResponseWriter\n\tParams   httprouter.Params\n\tErrors   Errors\n\n\tvalues   map[interface{}]interface{}\n\thandlers []HandlerFunc\n\tindex    int8\n\tengine   *Engine\n}\n\n\/************************************\/\n\/********** CONTEXT CREATION ********\/\n\/************************************\/\n\nfunc (engine *Engine) createContext(rw http.ResponseWriter, req *http.Request, params httprouter.Params, handlers []HandlerFunc) *Context {\n\treturn &Context{\n\t\tResponse: newResponseWriter(rw),\n\t\tRequest:  req,\n\t\tParams:   params,\n\t\thandlers: handlers,\n\t\tErrors:   nil,\n\t\tindex:    -1,\n\t\tengine:   engine,\n\t}\n}\n\n\/************************************\/\n\/*************** FLOW ***************\/\n\/************************************\/\n\n\/\/ Next should be used only in the middlewares.\n\/\/ It executes the pending handlers in the chain inside the calling handler.\n\/\/ See example in github.\nfunc (ctx *Context) Next() {\n\tctx.index++\n\ts := int8(len(ctx.handlers))\n\tfor ; ctx.index < s; ctx.index++ {\n\t\tctx.handlers[ctx.index](ctx)\n\t}\n}\n\n\/\/ Forces the system to do not continue calling the pending handlers in the chain.\nfunc (ctx *Context) Abort() {\n\tctx.index = AbortIndex\n}\n\n\/************************************\/\n\/******** METADATA MANAGEMENT********\/\n\/************************************\/\n\n\/\/ Sets a new pair key\/value just for the specified context.\n\/\/ It also lazy initializes the hashmap.\nfunc (ctx *Context) Set(key interface{}, item interface{}) {\n\tif ctx.values == nil {\n\t\tctx.values = make(map[interface{}]interface{})\n\t}\n\tctx.values[key] = item\n}\n\n\/\/ Get returns the value for the given key or an error if the key does not exist.\nfunc (ctx *Context) Get(key interface{}) interface{} {\n\tif ctx.values != nil {\n\t\tvalue, ok := ctx.values[key]\n\t\tif ok {\n\t\t\treturn value\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (ctx *Context) GetOk(key interface{}) (interface{}, bool) {\n\tif ctx.values != nil {\n\t\tvalue, ok := ctx.values[key]\n\t\tif ok {\n\t\t\treturn value, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc (ctx *Context) ClientIP() string {\n\treturn ctx.Request.RemoteAddr\n}\n\n\/************************************\/\n\/********* PARSING REQUEST **********\/\n\/************************************\/\nfunc (ctx *Context) Bind(obj interface{}) binding.Errors {\n\treturn binding.Bind(obj, ctx.Request)\n}\n\nfunc (ctx *Context) BindWith(obj interface{}, b binding.Binding) binding.Errors {\n\treturn b.Bind(obj, ctx.Request)\n}\n\n\/************************************\/\n\/******** RESPONSE RENDERING ********\/\n\/************************************\/\n\nfunc (ctx *Context) Render(code int, render render.Render, obj ...interface{}) {\n\tif err := render.Render(ctx.Response, code, obj...); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Serializes the given struct as JSON into the response body in a fast and efficient way.\n\/\/ It also sets the Content-Type as \"application\/json\".\nfunc (ctx *Context) JSON(code int, obj interface{}) {\n\tctx.Render(code, render.JSON, obj)\n}\n\n\/\/ Serializes the given struct as XML into the response body in a fast and efficient way.\n\/\/ It also sets the Content-Type as \"application\/xml\".\nfunc (ctx *Context) XML(code int, obj interface{}) {\n\tctx.Render(code, render.XML, obj)\n}\n\n\/\/ Renders the HTTP template specified by its file name.\n\/\/ It also updates the HTTP code and sets the Content-Type as \"text\/html\".\n\/\/ See http:\/\/golang.org\/doc\/articles\/wiki\/\nfunc (ctx *Context) HTML(code int, name string, obj ...interface{}) {\n\tctx.Render(code, ctx.engine.templateRender, append([]interface{}{name}, obj...)...)\n}\n\n\/\/ Writes the given string into the response body and sets the Content-Type to \"text\/plain\".\nfunc (ctx *Context) String(code int, format string, values ...interface{}) {\n\tctx.Render(code, render.Plain, append([]interface{}{format}, values...)...)\n}\n\n\/\/ Writes the given string into the response body and sets the Content-Type to \"text\/html\" without template.\nfunc (ctx *Context) HTMLString(code int, format string, values ...interface{}) {\n\tctx.Render(code, render.HtmlPlain, append([]interface{}{format}, values...)...)\n}\n\n\/\/ Returns a HTTP redirect to the specific location.\nfunc (ctx *Context) Redirect(code int, location string) {\n\tif code >= 300 && code <= 308 {\n\t\tctx.Render(code, render.Redirect, location)\n\t} else {\n\t\tpanic(fmt.Sprintf(\"Cannot send a redirect with status code %d\", code))\n\t}\n}\n\n\/\/ Writes some data into the body stream and updates the HTTP code.\nfunc (ctx *Context) Data(code int, contentType string, data []byte) {\n\tif len(contentType) > 0 {\n\t\tctx.Response.Header().Set(\"Content-Type\", contentType)\n\t}\n\tctx.Response.WriteHeader(code)\n\tctx.Response.Write(data)\n}\n\n\/\/ Writes the specified file into the body stream\nfunc (ctx *Context) File(filepath string) {\n\thttp.ServeFile(ctx.Response, ctx.Request, filepath)\n}\n<|endoftext|>"}
{"text":"<commit_before>package shortlink\n\nimport (\n\t\"database\/sql\"\n\t\"db\"\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n)\n\n\/\/ checks if a id already exists in the database\nfunc checkIDConflict(id string) (bool, error) {\n\tcollision := 1\n\terr := db.Db.QueryRow(\"SELECT EXISTS(SELECT 1 FROM links WHERE id=?)\", id).Scan(&collision)\n\treturn collision != 0, err\n}\n\n\/\/ gets a unique id for a new game\nfunc getUniqueID() (string, error) {\n\tvar count uint\n\tvar scale uint\n\tvar addConst uint\n\tvar newID uint\n\tvar idString string\n\n\tconflict := true\n\terr := db.Db.QueryRow(\"SELECT count, scale, addConst FROM count WHERE type='links'\").Scan(&count, &scale, &addConst)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor conflict {\n\t\tcount += 1\n\t\tnewID = (count*scale + addConst) % 65536\n\t\tidString = fmt.Sprintf(\"%x\", newID)\n\t\t\/\/ makes 4 wide\n\t\tfor len(idString) < 4 {\n\t\t\tidString = \"0\" + idString\n\t\t}\n\t\tconflict, err = checkIDConflict(idString)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tupdateCount, err := db.Db.Prepare(\"UPDATE count SET count=? WHERE type='links'\")\n\tif err != nil {\n\t\treturn idString, err\n\t}\n\n\t_, err = updateCount.Exec(count)\n\tif err != nil {\n\t\treturn idString, err\n\t}\n\n\treturn idString, nil\n}\n\n\/\/ adds the game into the database\nfunc Add(link string) (string, error) {\n\terr := db.Db.Ping()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tidString, err := getUniqueID()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taddLink, err := db.Db.Prepare(\"INSERT INTO links VALUES(?, ?)\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t_, err = addLink.Exec(idString, link)\n\treturn idString, err\n}\n\n\/\/ adds the game into the database\nfunc Get(id string) (string, error) {\n\terr := db.Db.Ping()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif bad, err := regexp.MatchString(\"[^a-f0-9]\", id); err != nil {\n\t\treturn \"\", err\n\t} else if bad {\n\t\treturn \"\", errors.New(\"Invalid link ID\")\n\t}\n\n\tvar link string\n\n\t\/\/TODO: handle NULLS\n\terr = db.Db.QueryRow(\"SELECT link FROM links WHERE id=?\", id).Scan(&link)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn \"\", errors.New(\"Link not found\")\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\treturn link, nil\n}\n<commit_msg>changed shortlinks to accept uppercase<commit_after>package shortlink\n\nimport (\n\t\"database\/sql\"\n\t\"db\"\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n\/\/ checks if a id already exists in the database\nfunc checkIDConflict(id string) (bool, error) {\n\tcollision := 1\n\terr := db.Db.QueryRow(\"SELECT EXISTS(SELECT 1 FROM links WHERE id=?)\", id).Scan(&collision)\n\treturn collision != 0, err\n}\n\n\/\/ gets a unique id for a new game\nfunc getUniqueID() (string, error) {\n\tvar count uint\n\tvar scale uint\n\tvar addConst uint\n\tvar newID uint\n\tvar idString string\n\n\tconflict := true\n\terr := db.Db.QueryRow(\"SELECT count, scale, addConst FROM count WHERE type='links'\").Scan(&count, &scale, &addConst)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor conflict {\n\t\tcount += 1\n\t\tnewID = (count*scale + addConst) % 65536\n\t\tidString = fmt.Sprintf(\"%x\", newID)\n\t\t\/\/ makes 4 wide\n\t\tfor len(idString) < 4 {\n\t\t\tidString = \"0\" + idString\n\t\t}\n\t\tconflict, err = checkIDConflict(idString)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tupdateCount, err := db.Db.Prepare(\"UPDATE count SET count=? WHERE type='links'\")\n\tif err != nil {\n\t\treturn idString, err\n\t}\n\n\t_, err = updateCount.Exec(count)\n\tif err != nil {\n\t\treturn idString, err\n\t}\n\n\treturn idString, nil\n}\n\n\/\/ adds the game into the database\nfunc Add(link string) (string, error) {\n\terr := db.Db.Ping()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tidString, err := getUniqueID()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\taddLink, err := db.Db.Prepare(\"INSERT INTO links VALUES(?, ?)\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t_, err = addLink.Exec(idString, link)\n\treturn idString, err\n}\n\n\/\/ adds the game into the database\nfunc Get(id string) (string, error) {\n\terr := db.Db.Ping()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tid = strings.ToLower(id)\n\n\tif bad, err := regexp.MatchString(\"[^a-f0-9]\", id); err != nil {\n\t\treturn \"\", err\n\t} else if bad {\n\t\treturn \"\", errors.New(\"Invalid link ID\")\n\t}\n\n\tvar link string\n\n\t\/\/TODO: handle NULLS\n\terr = db.Db.QueryRow(\"SELECT link FROM links WHERE id=?\", id).Scan(&link)\n\tif err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn \"\", errors.New(\"Link not found\")\n\t\t}\n\t\treturn \"\", err\n\t}\n\n\treturn link, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage collateral\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"html\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"strconv\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/cobra\/doc\"\n\t\"github.com\/spf13\/pflag\"\n)\n\n\/\/ Control determines the behavior of the EmitCollateral function\ntype Control struct {\n\t\/\/ OutputDir specifies the directory to output the collateral files\n\tOutputDir string\n\n\t\/\/ EmitManPages controls whether to produce man pages.\n\tEmitManPages bool\n\n\t\/\/ EmitYAML controls whether to produce YAML files.\n\tEmitYAML bool\n\n\t\/\/ EmitBashCompletion controls whether to produce bash completion files.\n\tEmitBashCompletion bool\n\n\t\/\/ EmitMarkdown controls whether to produce mankdown documentation files.\n\tEmitMarkdown bool\n\n\t\/\/ EmitJeyllHTML controls whether to produce Jekyll-friendly HTML documentation files.\n\tEmitJekyllHTML bool\n\n\t\/\/ ManPageInfo provides extra information necessary when emitting man pages.\n\tManPageInfo doc.GenManHeader\n}\n\n\/\/ EmitCollateral produces a set of collateral files for a CLI command. You can\n\/\/ select to emit markdown to describe a command's function, man pages, YAML\n\/\/ descriptions, and bash completion files.\nfunc EmitCollateral(root *cobra.Command, c *Control) error {\n\tif c.EmitManPages {\n\t\tif err := doc.GenManTree(root, &c.ManPageInfo, c.OutputDir); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to output manpage tree: %v\", err)\n\t\t}\n\t}\n\n\tif c.EmitMarkdown {\n\t\tif err := doc.GenMarkdownTree(root, c.OutputDir); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to output markdown tree: %v\", err)\n\t\t}\n\t}\n\n\tif c.EmitJekyllHTML {\n\t\tif err := genJekyllHTML(root, c.OutputDir+\"\/\"+root.Name()+\".html\"); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to output Jekyll HTML file: %v\", err)\n\t\t}\n\t}\n\n\tif c.EmitYAML {\n\t\tif err := doc.GenYamlTree(root, c.OutputDir); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to output YAML tree: %v\", err)\n\t\t}\n\t}\n\n\tif c.EmitBashCompletion {\n\t\tif err := root.GenBashCompletionFile(c.OutputDir + \"\/\" + root.Name() + \".bash\"); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to output bash completion file: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\ntype generator struct {\n\tbuffer *bytes.Buffer\n}\n\nfunc (g *generator) emit(str ...string) {\n\tfor _, s := range str {\n\t\tg.buffer.WriteString(s)\n\t}\n\tg.buffer.WriteByte('\\n')\n}\n\nfunc findCommands(commands map[string]*cobra.Command, cmd *cobra.Command) {\n\tcmd.InitDefaultHelpCmd()\n\tcmd.InitDefaultHelpFlag()\n\n\tcommands[cmd.CommandPath()] = cmd\n\tfor _, c := range cmd.Commands() {\n\t\tfindCommands(commands, c)\n\t}\n}\n\nconst help = \"help\"\n\nfunc genJekyllHTML(cmd *cobra.Command, path string) error {\n\tcommands := make(map[string]*cobra.Command)\n\tfindCommands(commands, cmd)\n\n\tnames := make([]string, len(commands), len(commands))\n\ti := 0\n\tfor n := range commands {\n\t\tnames[i] = n\n\t\ti++\n\t}\n\tsort.Strings(names)\n\n\tg := &generator{\n\t\tbuffer: &bytes.Buffer{},\n\t}\n\n\tcount := 0\n\tfor _, n := range names {\n\t\tif commands[n].Name() == help {\n\t\t\tcontinue\n\t\t}\n\n\t\tcount++\n\t}\n\n\tg.genFileHeader(cmd, count)\n\tfor _, n := range names {\n\t\tif commands[n].Name() == help {\n\t\t\tcontinue\n\t\t}\n\n\t\tg.genCommand(commands[n])\n\t}\n\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = g.buffer.WriteTo(f)\n\t_ = f.Close()\n\n\treturn err\n}\n\nfunc (g *generator) genFileHeader(root *cobra.Command, numEntries int) {\n\tg.emit(\"---\")\n\tg.emit(\"title: \", root.Name())\n\tg.emit(\"overview: \", html.EscapeString(root.Short))\n\tg.emit(\"layout: pkg-collateral-docs\")\n\tg.emit(\"number_of_entries: \", strconv.Itoa(numEntries))\n\tg.emit(\"---\")\n}\n\nfunc (g *generator) genCommand(cmd *cobra.Command) {\n\tif cmd.Hidden || cmd.Deprecated != \"\" {\n\t\treturn\n\t}\n\n\tif cmd.HasParent() {\n\t\tg.emit(\"<h2 id=\\\"\", cmd.CommandPath(), \"\\\">\", cmd.CommandPath(), \"<\/h2>\")\n\t}\n\n\tif cmd.Long != \"\" {\n\t\tg.emitText(cmd.Long)\n\t} else if cmd.Short != \"\" {\n\t\tg.emitText(cmd.Short)\n\t}\n\n\tif cmd.Runnable() {\n\t\tg.emit(\"<pre class=\\\"language-bash\\\"><code>\", html.EscapeString(cmd.UseLine()))\n\t\tg.emit(\"<\/code><\/pre>\")\n\t}\n\n\t\/\/ TODO: output aliases\n\n\tflags := cmd.NonInheritedFlags()\n\tflags.SetOutput(g.buffer)\n\n\tparentFlags := cmd.InheritedFlags()\n\tparentFlags.SetOutput(g.buffer)\n\n\tif flags.HasFlags() || parentFlags.HasFlags() {\n\t\tg.emit(\"<table class=\\\"command-flags\\\">\")\n\t\tg.emit(\"<thead>\")\n\t\tg.emit(\"<th>Flags<\/th>\")\n\t\tg.emit(\"<th>Shorthand<\/th>\")\n\t\tg.emit(\"<th>Description<\/th>\")\n\t\tg.emit(\"<\/thead>\")\n\t\tg.emit(\"<tbody>\")\n\n\t\tf := make(map[string]*pflag.Flag)\n\t\taddFlags(f, flags)\n\t\taddFlags(f, parentFlags)\n\n\t\tnames := make([]string, len(f))\n\t\ti := 0\n\t\tfor n := range f {\n\t\t\tnames[i] = n\n\t\t\ti++\n\t\t}\n\t\tsort.Strings(names)\n\n\t\tfor _, n := range names {\n\t\t\tg.genFlag(f[n])\n\t\t}\n\n\t\tg.emit(\"<\/tbody>\")\n\t\tg.emit(\"<\/table>\")\n\t}\n\n\tif len(cmd.Example) > 0 {\n\t\tg.emit(\"<h3 id=\\\"\", cmd.CommandPath(), \" Examples\\\">\", \"Examples\", \"<\/h3>\")\n\t\tg.emit(\"<pre class=\\\"language-bash\\\"><code>\", html.EscapeString(cmd.Example))\n\t\tg.emit(\"<\/code><\/pre>\")\n\t}\n}\n\nfunc addFlags(f map[string]*pflag.Flag, s *pflag.FlagSet) {\n\ts.VisitAll(func(flag *pflag.Flag) {\n\t\tif flag.Deprecated != \"\" || flag.Hidden {\n\t\t\treturn\n\t\t}\n\n\t\tif flag.Name == help {\n\t\t\treturn\n\t\t}\n\n\t\tf[flag.Name] = flag\n\t})\n}\n\nfunc (g *generator) genFlag(flag *pflag.Flag) {\n\tvarname, usage := unquoteUsage(flag)\n\tif varname != \"\" {\n\t\tvarname = \" <\" + varname + \">\"\n\t}\n\n\tdef := \"\"\n\tif flag.Value.Type() == \"string\" {\n\t\tdef = fmt.Sprintf(\" (default `%s`)\", flag.DefValue)\n\t} else if flag.Value.Type() != \"bool\" {\n\t\tdef = fmt.Sprintf(\" (default `%s`)\", flag.DefValue)\n\t}\n\n\tg.emit(\"<tr>\")\n\tg.emit(\"<td><code>\", \"--\", flag.Name, html.EscapeString(varname), \"<\/code><\/td>\")\n\tif flag.Shorthand != \"\" && flag.ShorthandDeprecated == \"\" {\n\t\tg.emit(\"<td><code>\", \"-\", flag.Shorthand, \"<\/code><\/td>\")\n\t} else {\n\t\tg.emit(\"<td><\/td>\")\n\t}\n\tg.emit(\"<td>\", html.EscapeString(usage), \" \", def, \"<\/td>\")\n\tg.emit(\"<\/tr>\")\n}\n\nfunc (g *generator) emitText(text string) {\n\tparas := strings.Split(text, \"\\n\\n\")\n\tfor _, p := range paras {\n\t\tg.emit(\"<p>\", html.EscapeString(p), \"<\/p>\")\n\t}\n}\n\n\/\/ unquoteUsage extracts a back-quoted name from the usage\n\/\/ string for a flag and returns it and the un-quoted usage.\n\/\/ Given \"a `name` to show\" it returns (\"name\", \"a name to show\").\n\/\/ If there are no back quotes, the name is an educated guess of the\n\/\/ type of the flag's value, or the empty string if the flag is boolean.\nfunc unquoteUsage(flag *pflag.Flag) (name string, usage string) {\n\t\/\/ Look for a back-quoted name, but avoid the strings package.\n\tusage = flag.Usage\n\tfor i := 0; i < len(usage); i++ {\n\t\tif usage[i] == '`' {\n\t\t\tfor j := i + 1; j < len(usage); j++ {\n\t\t\t\tif usage[j] == '`' {\n\t\t\t\t\tname = usage[i+1 : j]\n\t\t\t\t\tusage = usage[:i] + name + usage[j+1:]\n\t\t\t\t\treturn name, usage\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak \/\/ Only one back quote; use type name.\n\t\t}\n\t}\n\n\tname = flag.Value.Type()\n\tswitch name {\n\tcase \"bool\":\n\t\tname = \"\"\n\tcase \"float64\":\n\t\tname = \"float\"\n\tcase \"int64\":\n\t\tname = \"int\"\n\tcase \"uint64\":\n\t\tname = \"uint\"\n\t}\n\n\treturn\n}\n<commit_msg>Run bin\/fmt.sh (#3251)<commit_after>\/\/ Copyright 2018 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage collateral\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"html\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/cobra\/doc\"\n\t\"github.com\/spf13\/pflag\"\n)\n\n\/\/ Control determines the behavior of the EmitCollateral function\ntype Control struct {\n\t\/\/ OutputDir specifies the directory to output the collateral files\n\tOutputDir string\n\n\t\/\/ EmitManPages controls whether to produce man pages.\n\tEmitManPages bool\n\n\t\/\/ EmitYAML controls whether to produce YAML files.\n\tEmitYAML bool\n\n\t\/\/ EmitBashCompletion controls whether to produce bash completion files.\n\tEmitBashCompletion bool\n\n\t\/\/ EmitMarkdown controls whether to produce mankdown documentation files.\n\tEmitMarkdown bool\n\n\t\/\/ EmitJeyllHTML controls whether to produce Jekyll-friendly HTML documentation files.\n\tEmitJekyllHTML bool\n\n\t\/\/ ManPageInfo provides extra information necessary when emitting man pages.\n\tManPageInfo doc.GenManHeader\n}\n\n\/\/ EmitCollateral produces a set of collateral files for a CLI command. You can\n\/\/ select to emit markdown to describe a command's function, man pages, YAML\n\/\/ descriptions, and bash completion files.\nfunc EmitCollateral(root *cobra.Command, c *Control) error {\n\tif c.EmitManPages {\n\t\tif err := doc.GenManTree(root, &c.ManPageInfo, c.OutputDir); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to output manpage tree: %v\", err)\n\t\t}\n\t}\n\n\tif c.EmitMarkdown {\n\t\tif err := doc.GenMarkdownTree(root, c.OutputDir); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to output markdown tree: %v\", err)\n\t\t}\n\t}\n\n\tif c.EmitJekyllHTML {\n\t\tif err := genJekyllHTML(root, c.OutputDir+\"\/\"+root.Name()+\".html\"); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to output Jekyll HTML file: %v\", err)\n\t\t}\n\t}\n\n\tif c.EmitYAML {\n\t\tif err := doc.GenYamlTree(root, c.OutputDir); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to output YAML tree: %v\", err)\n\t\t}\n\t}\n\n\tif c.EmitBashCompletion {\n\t\tif err := root.GenBashCompletionFile(c.OutputDir + \"\/\" + root.Name() + \".bash\"); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to output bash completion file: %v\", err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\ntype generator struct {\n\tbuffer *bytes.Buffer\n}\n\nfunc (g *generator) emit(str ...string) {\n\tfor _, s := range str {\n\t\tg.buffer.WriteString(s)\n\t}\n\tg.buffer.WriteByte('\\n')\n}\n\nfunc findCommands(commands map[string]*cobra.Command, cmd *cobra.Command) {\n\tcmd.InitDefaultHelpCmd()\n\tcmd.InitDefaultHelpFlag()\n\n\tcommands[cmd.CommandPath()] = cmd\n\tfor _, c := range cmd.Commands() {\n\t\tfindCommands(commands, c)\n\t}\n}\n\nconst help = \"help\"\n\nfunc genJekyllHTML(cmd *cobra.Command, path string) error {\n\tcommands := make(map[string]*cobra.Command)\n\tfindCommands(commands, cmd)\n\n\tnames := make([]string, len(commands), len(commands))\n\ti := 0\n\tfor n := range commands {\n\t\tnames[i] = n\n\t\ti++\n\t}\n\tsort.Strings(names)\n\n\tg := &generator{\n\t\tbuffer: &bytes.Buffer{},\n\t}\n\n\tcount := 0\n\tfor _, n := range names {\n\t\tif commands[n].Name() == help {\n\t\t\tcontinue\n\t\t}\n\n\t\tcount++\n\t}\n\n\tg.genFileHeader(cmd, count)\n\tfor _, n := range names {\n\t\tif commands[n].Name() == help {\n\t\t\tcontinue\n\t\t}\n\n\t\tg.genCommand(commands[n])\n\t}\n\n\tf, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = g.buffer.WriteTo(f)\n\t_ = f.Close()\n\n\treturn err\n}\n\nfunc (g *generator) genFileHeader(root *cobra.Command, numEntries int) {\n\tg.emit(\"---\")\n\tg.emit(\"title: \", root.Name())\n\tg.emit(\"overview: \", html.EscapeString(root.Short))\n\tg.emit(\"layout: pkg-collateral-docs\")\n\tg.emit(\"number_of_entries: \", strconv.Itoa(numEntries))\n\tg.emit(\"---\")\n}\n\nfunc (g *generator) genCommand(cmd *cobra.Command) {\n\tif cmd.Hidden || cmd.Deprecated != \"\" {\n\t\treturn\n\t}\n\n\tif cmd.HasParent() {\n\t\tg.emit(\"<h2 id=\\\"\", cmd.CommandPath(), \"\\\">\", cmd.CommandPath(), \"<\/h2>\")\n\t}\n\n\tif cmd.Long != \"\" {\n\t\tg.emitText(cmd.Long)\n\t} else if cmd.Short != \"\" {\n\t\tg.emitText(cmd.Short)\n\t}\n\n\tif cmd.Runnable() {\n\t\tg.emit(\"<pre class=\\\"language-bash\\\"><code>\", html.EscapeString(cmd.UseLine()))\n\t\tg.emit(\"<\/code><\/pre>\")\n\t}\n\n\t\/\/ TODO: output aliases\n\n\tflags := cmd.NonInheritedFlags()\n\tflags.SetOutput(g.buffer)\n\n\tparentFlags := cmd.InheritedFlags()\n\tparentFlags.SetOutput(g.buffer)\n\n\tif flags.HasFlags() || parentFlags.HasFlags() {\n\t\tg.emit(\"<table class=\\\"command-flags\\\">\")\n\t\tg.emit(\"<thead>\")\n\t\tg.emit(\"<th>Flags<\/th>\")\n\t\tg.emit(\"<th>Shorthand<\/th>\")\n\t\tg.emit(\"<th>Description<\/th>\")\n\t\tg.emit(\"<\/thead>\")\n\t\tg.emit(\"<tbody>\")\n\n\t\tf := make(map[string]*pflag.Flag)\n\t\taddFlags(f, flags)\n\t\taddFlags(f, parentFlags)\n\n\t\tnames := make([]string, len(f))\n\t\ti := 0\n\t\tfor n := range f {\n\t\t\tnames[i] = n\n\t\t\ti++\n\t\t}\n\t\tsort.Strings(names)\n\n\t\tfor _, n := range names {\n\t\t\tg.genFlag(f[n])\n\t\t}\n\n\t\tg.emit(\"<\/tbody>\")\n\t\tg.emit(\"<\/table>\")\n\t}\n\n\tif len(cmd.Example) > 0 {\n\t\tg.emit(\"<h3 id=\\\"\", cmd.CommandPath(), \" Examples\\\">\", \"Examples\", \"<\/h3>\")\n\t\tg.emit(\"<pre class=\\\"language-bash\\\"><code>\", html.EscapeString(cmd.Example))\n\t\tg.emit(\"<\/code><\/pre>\")\n\t}\n}\n\nfunc addFlags(f map[string]*pflag.Flag, s *pflag.FlagSet) {\n\ts.VisitAll(func(flag *pflag.Flag) {\n\t\tif flag.Deprecated != \"\" || flag.Hidden {\n\t\t\treturn\n\t\t}\n\n\t\tif flag.Name == help {\n\t\t\treturn\n\t\t}\n\n\t\tf[flag.Name] = flag\n\t})\n}\n\nfunc (g *generator) genFlag(flag *pflag.Flag) {\n\tvarname, usage := unquoteUsage(flag)\n\tif varname != \"\" {\n\t\tvarname = \" <\" + varname + \">\"\n\t}\n\n\tdef := \"\"\n\tif flag.Value.Type() == \"string\" {\n\t\tdef = fmt.Sprintf(\" (default `%s`)\", flag.DefValue)\n\t} else if flag.Value.Type() != \"bool\" {\n\t\tdef = fmt.Sprintf(\" (default `%s`)\", flag.DefValue)\n\t}\n\n\tg.emit(\"<tr>\")\n\tg.emit(\"<td><code>\", \"--\", flag.Name, html.EscapeString(varname), \"<\/code><\/td>\")\n\tif flag.Shorthand != \"\" && flag.ShorthandDeprecated == \"\" {\n\t\tg.emit(\"<td><code>\", \"-\", flag.Shorthand, \"<\/code><\/td>\")\n\t} else {\n\t\tg.emit(\"<td><\/td>\")\n\t}\n\tg.emit(\"<td>\", html.EscapeString(usage), \" \", def, \"<\/td>\")\n\tg.emit(\"<\/tr>\")\n}\n\nfunc (g *generator) emitText(text string) {\n\tparas := strings.Split(text, \"\\n\\n\")\n\tfor _, p := range paras {\n\t\tg.emit(\"<p>\", html.EscapeString(p), \"<\/p>\")\n\t}\n}\n\n\/\/ unquoteUsage extracts a back-quoted name from the usage\n\/\/ string for a flag and returns it and the un-quoted usage.\n\/\/ Given \"a `name` to show\" it returns (\"name\", \"a name to show\").\n\/\/ If there are no back quotes, the name is an educated guess of the\n\/\/ type of the flag's value, or the empty string if the flag is boolean.\nfunc unquoteUsage(flag *pflag.Flag) (name string, usage string) {\n\t\/\/ Look for a back-quoted name, but avoid the strings package.\n\tusage = flag.Usage\n\tfor i := 0; i < len(usage); i++ {\n\t\tif usage[i] == '`' {\n\t\t\tfor j := i + 1; j < len(usage); j++ {\n\t\t\t\tif usage[j] == '`' {\n\t\t\t\t\tname = usage[i+1 : j]\n\t\t\t\t\tusage = usage[:i] + name + usage[j+1:]\n\t\t\t\t\treturn name, usage\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak \/\/ Only one back quote; use type name.\n\t\t}\n\t}\n\n\tname = flag.Value.Type()\n\tswitch name {\n\tcase \"bool\":\n\t\tname = \"\"\n\tcase \"float64\":\n\t\tname = \"float\"\n\tcase \"int64\":\n\t\tname = \"int\"\n\tcase \"uint64\":\n\t\tname = \"uint\"\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2011 Miek Gieben. All rights reserved.\n\/\/ Lisenced under the GPLv2\n\n\/*\nFunkensturm rewrites DNS packets in the broadest sense of the word.\nThe rewriting can include delayed (re)sending of packets, (re)sending\npackets to multiple servers, rewriting the packet contents, for instance\nby signing a packet, or the other way around, stripping the signatures.\n\nIn its essence this is no different that a recursive nameserver, which also\nreceives and sends queries. The difference is the huge amount of tweaking\nFunkensturm offers.\n\nThe configuration of Funkensturm is done by writing it in Go - a\nseparate configuration language was deemed to be unpractical and\nwould limit the possibilities.\n\nUsage:\n        funkensturm [flags]\n\nThe flags are:\n\n        -sserver\n                        Listener address and port for the server. This has to be\n                        specified as: address:port, for instance 127.0.0.1:8053.\n                        This is also the default.\n        -rserver \n                        Remote server address in address:port format. This can be\n                        repeated, for each rserver a resolver channel is created.\n                        The first begin `qr[0]`, the second `qr[1]`, etc.\n                        The default is: 127.0.0.1:53\n\nDebugging flags:\n\n        -verbose\n                        Print packets as they flow through Funkensturm.\n\nPredefined configurations are shown in `config_delay.go` and `config_sign.go`. The\ndefault `config.go` implements a transparant proxy.\n\nAlso see: http:\/\/www.miek.nl\/blog\/archives\/2011\/01\/23\/funkensturm\/index.html for\na architectural overview.\n\nIn FunkenSturm you define chains named Funk's (maybe just 'chain' is a better name). Each Funk\nconsi\n\n*\/\npackage documentation\n<commit_msg>More docs<commit_after>\/\/ Copyright 2011 Miek Gieben. All rights reserved.\n\/\/ Lisenced under the GPLv2\n\n\/*\nFunkensturm rewrites DNS packets in the broadest sense of the word.\nThe rewriting can include delayed (re)sending of packets, (re)sending\npackets to multiple servers, rewriting the packet contents, for instance\nby signing a packet, or the other way around, stripping the signatures.\n\nIn its essence this is no different that a recursive nameserver, which also\nreceives and sends queries. The difference is the huge amount of tweaking\nFunkensturm offers.\n\nThe configuration of Funkensturm is done by writing it in Go - a\nseparate configuration language was deemed to be unpractical and\nwould limit the possibilities.\n\nUsage:\n        funkensturm [flags]\n\nThe flags are:\n\n        -sserver\n                        Listener address and port for the server. This has to be\n                        specified as: address:port, for instance 127.0.0.1:8053.\n                        This is also the default.\n        -rserver \n                        Remote server address in address:port format. This can be\n                        repeated, for each rserver a resolver channel is created.\n                        The first begin `qr[0]`, the second `qr[1]`, etc.\n                        The default is: 127.0.0.1:53\n\nDebugging flags:\n\n        -verbose\n                        Print packets as they flow through Funkensturm.\n\nPredefined configurations are shown in `config_delay.go` and `config_sign.go`. The\ndefault `config.go` implements a transparant proxy.\n\nAlso see: http:\/\/www.miek.nl\/blog\/archives\/2011\/01\/23\/funkensturm\/index.html for\na architectural overview.\n\nIn FunkenSturm you define chains named Funk's (maybe just 'chain' is a better name). Each Funk\nconsists out of match and action function. If the match function matches (return true) the\naction function is called.\nMultiple Funk's may be used. The first 'true' value win and that action function is performed.\n\n*\/\npackage documentation\n<|endoftext|>"}
{"text":"<commit_before>package goinsta\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\/\/ Item represents media items\ntype Item struct {\n\tTakenAt          int     `json:\"taken_at\"`\n\tID               int64   `json:\"pk\"`\n\tIDStr            string  `json:\"id\"`\n\tDeviceTimestamp  int64   `json:\"device_timestamp\"`\n\tMediaType        int     `json:\"media_type\"`\n\tCode             string  `json:\"code\"`\n\tClientCacheKey   string  `json:\"client_cache_key\"`\n\tFilterType       int     `json:\"filter_type\"`\n\tCarouselParentID string  `json:\"carousel_parent_id\"`\n\tCarouselMedia    []Item  `json:\"carousel_media,omitempty\"`\n\tUser             User    `json:\"user\"`\n\tCanViewerReshare bool    `json:\"can_viewer_reshare\"`\n\tCaption          Caption `json:\"caption\"`\n\tCaptionIsEdited  bool    `json:\"caption_is_edited\"`\n\tLikes            int     `json:\"like_count\"`\n\tHasLiked         bool    `json:\"has_liked\"`\n\t\/\/ TopLikers can be multiple data\n\tTopLikersStr                 string `json:\"top_likers,string\"`\n\tTopLikers                    []User `json:\"top_likers\"`\n\tCommentLikesEnabled          bool   `json:\"comment_likes_enabled\"`\n\tCommentThreadingEnabled      bool   `json:\"comment_threading_enabled\"`\n\tHasMoreComments              bool   `json:\"has_more_comments\"`\n\tMaxNumVisiblePreviewComments int    `json:\"max_num_visible_preview_comments\"`\n\t\/\/ PreviewComments can be `string` or `[]string`\n\tPreviewComments      []interface{} `json:\"preview_comments,omitempty\"`\n\tCommentCount         int           `json:\"comment_count\"`\n\tPhotoOfYou           bool          `json:\"photo_of_you\"`\n\tUsertags             Tag           `json:\"usertags,omitempty\"`\n\tFbUserTags           Tag           `json:\"fb_user_tags\"`\n\tCanViewerSave        bool          `json:\"can_viewer_save\"`\n\tOrganicTrackingToken string        `json:\"organic_tracking_token\"`\n\tImages               Images        `json:\"image_versions2,omitempty\"`\n\tOriginalWidth        int           `json:\"original_width,omitempty\"`\n\tOriginalHeight       int           `json:\"original_height,omitempty\"`\n\tImportedTakenAt      int           `json:\"imported_taken_at,omitempty\"`\n\n\t\/\/ Only for stories\n\tStoryEvents              []interface{} `json:\"story_events\"`\n\tStoryHashtags            []interface{} `json:\"story_hashtags\"`\n\tStoryPolls               []interface{} `json:\"story_polls\"`\n\tStoryFeedMedia           []interface{} `json:\"story_feed_media\"`\n\tStorySoundOn             []interface{} `json:\"story_sound_on\"`\n\tCreativeConfig           interface{}   `json:\"creative_config\"`\n\tStoryLocations           []interface{} `json:\"story_locations\"`\n\tStorySliders             []interface{} `json:\"story_sliders\"`\n\tStoryQuestions           []interface{} `json:\"story_questions\"`\n\tStoryProductItems        []interface{} `json:\"story_product_items\"`\n\tSupportsReelReactions    bool          `json:\"supports_reel_reactions\"`\n\tShowOneTapFbShareTooltip bool          `json:\"show_one_tap_fb_share_tooltip\"`\n\tHasSharedToFb            int           `json:\"has_shared_to_fb\"`\n\tMentions                 []Mentions\n\tVideos                   []Videos `json:\"video_versions,omitempty\"`\n\tHasAudio                 bool     `json:\"has_audio,omitempty\"`\n\tVideoDuration            float64  `json:\"video_duration,omitempty\"`\n\tIsDashEligible           int      `json:\"is_dash_eligible,omitempty\"`\n\tVideoDashManifest        string   `json:\"video_dash_manifest,omitempty\"`\n\tNumberOfQualities        int      `json:\"number_of_qualities,omitempty\"`\n}\n\ntype Media interface {\n\tNext() error\n}\n\ntype StoryMedia struct {\n\tinst     *Instagram\n\tendpoint string\n\tuid      int64\n\n\tID              int      `json:\"id\"`\n\tLatestReelMedia int      `json:\"latest_reel_media\"`\n\tExpiringAt      int      `json:\"expiring_at\"`\n\tSeen            float64  `json:\"seen\"`\n\tCanReply        bool     `json:\"can_reply\"`\n\tCanReshare      bool     `json:\"can_reshare\"`\n\tReelType        string   `json:\"reel_type\"`\n\tUser            User     `json:\"user\"`\n\tItems           []Item   `json:\"items\"`\n\tReelMentions    []string `json:\"reel_mentions\"`\n\tPrefetchCount   int      `json:\"prefetch_count\"`\n\tHasBestiesMedia bool     `json:\"has_besties_media\"`\n\tStatus          string   `json:\"status\"`\n}\n\n\/\/ Next allows to paginate after calling:\n\/\/ User.Stories\nfunc (media *StoryMedia) Next() (err error) {\n\tvar body []byte\n\tinsta := media.inst\n\tendpoint := media.endpoint\n\n\tif media.uid != 0 {\n\t\tendpoint = fmt.Sprintf(endpoint, media.uid)\n\t}\n\tbody, err = insta.sendSimpleRequest(endpoint)\n\tif err == nil {\n\t\tm := StoryMedia{}\n\t\terr = json.Unmarshal(body, &m)\n\t\tif err == nil {\n\t\t\terr = ErrNoMore\n\t\t\t*media = m\n\t\t\tmedia.inst = insta\n\t\t\tmedia.endpoint = endpoint\n\t\t\t\/\/ TODO check NextID media\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ Media represent a set of media items\ntype FeedMedia struct {\n\tinst *Instagram\n\n\tuid      int64\n\tendpoint string\n\n\tItems               []Item `json:\"items\"`\n\tNumResults          int    `json:\"num_results\"`\n\tMoreAvailable       bool   `json:\"more_available\"`\n\tAutoLoadMoreEnabled bool   `json:\"auto_load_more_enabled\"`\n\tStatus              string `json:\"status\"`\n\t\/\/ Can be int64 and string\n\t\/\/ this is why recomend Next() usage :')\n\tNextID interface{} `json:\"next_max_id\"`\n}\n\n\/\/ Next allows to paginate after calling:\n\/\/ User.Feed\n\/\/\n\/\/ returns ErrNoMore when list reach the end.\nfunc (media *FeedMedia) Next() (err error) {\n\tvar body []byte\n\tinsta := media.inst\n\tendpoint := media.endpoint\n\tnext := \"\"\n\n\tswitch s := media.NextID.(type) {\n\tcase string:\n\t\tnext = s\n\tcase int64:\n\t\tnext = strconv.FormatInt(s, 10)\n\t}\n\n\tif media.uid != 0 {\n\t\tendpoint = fmt.Sprintf(endpoint, media.uid)\n\t}\n\n\tbody, err = insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: endpoint,\n\t\t\tQuery: map[string]string{\n\t\t\t\t\"max_id\":         next,\n\t\t\t\t\"rank_token\":     insta.rankToken,\n\t\t\t\t\"min_timestamp\":  \"\",\n\t\t\t\t\"ranked_content\": \"true\",\n\t\t\t},\n\t\t},\n\t)\n\tif err == nil {\n\t\tm := FeedMedia{}\n\t\terr = json.Unmarshal(body, &m)\n\t\tif err == nil {\n\t\t\t*media = m\n\t\t\tmedia.inst = insta\n\t\t\tmedia.endpoint = endpoint\n\t\t\tif m.NextID == 0 || !m.MoreAvailable {\n\t\t\t\terr = ErrNoMore\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}\n<commit_msg>Fixed type errors<commit_after>package goinsta\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\n\/\/ Item represents media items\n\/\/\n\/\/ All Item has\ntype Item struct {\n\tTakenAt          int     `json:\"taken_at\"`\n\tID               int64   `json:\"pk\"`\n\tIDStr            string  `json:\"id\"`\n\tDeviceTimestamp  int64   `json:\"device_timestamp\"`\n\tMediaType        int     `json:\"media_type\"`\n\tCode             string  `json:\"code\"`\n\tClientCacheKey   string  `json:\"client_cache_key\"`\n\tFilterType       int     `json:\"filter_type\"`\n\tCarouselParentID string  `json:\"carousel_parent_id\"`\n\tCarouselMedia    []Item  `json:\"carousel_media,omitempty\"`\n\tUser             User    `json:\"user\"`\n\tCanViewerReshare bool    `json:\"can_viewer_reshare\"`\n\tCaption          Caption `json:\"caption\"`\n\tCaptionIsEdited  bool    `json:\"caption_is_edited\"`\n\tLikes            int     `json:\"like_count\"`\n\tHasLiked         bool    `json:\"has_liked\"`\n\t\/\/ _TopLikers can be `string` or `[]string`.\n\t\/\/ Use TopLikers function instead of getting it directly.\n\t_TopLikers                   interface{} `json:\"top_likers\"`\n\tCommentLikesEnabled          bool        `json:\"comment_likes_enabled\"`\n\tCommentThreadingEnabled      bool        `json:\"comment_threading_enabled\"`\n\tHasMoreComments              bool        `json:\"has_more_comments\"`\n\tMaxNumVisiblePreviewComments int         `json:\"max_num_visible_preview_comments\"`\n\t\/\/ _PreviewComments can be `string` or `[]string`.\n\t\/\/ Use PreviewComments function instead of getting it directly.\n\t_PreviewComments     interface{} `json:\"preview_comments,omitempty\"`\n\tCommentCount         int         `json:\"comment_count\"`\n\tPhotoOfYou           bool        `json:\"photo_of_you\"`\n\tUsertags             Tag         `json:\"usertags,omitempty\"`\n\tFbUserTags           Tag         `json:\"fb_user_tags\"`\n\tCanViewerSave        bool        `json:\"can_viewer_save\"`\n\tOrganicTrackingToken string      `json:\"organic_tracking_token\"`\n\tImages               Images      `json:\"image_versions2,omitempty\"`\n\tOriginalWidth        int         `json:\"original_width,omitempty\"`\n\tOriginalHeight       int         `json:\"original_height,omitempty\"`\n\tImportedTakenAt      int         `json:\"imported_taken_at,omitempty\"`\n\n\t\/\/ Only for stories\n\tStoryEvents              []interface{} `json:\"story_events\"`\n\tStoryHashtags            []interface{} `json:\"story_hashtags\"`\n\tStoryPolls               []interface{} `json:\"story_polls\"`\n\tStoryFeedMedia           []interface{} `json:\"story_feed_media\"`\n\tStorySoundOn             []interface{} `json:\"story_sound_on\"`\n\tCreativeConfig           interface{}   `json:\"creative_config\"`\n\tStoryLocations           []interface{} `json:\"story_locations\"`\n\tStorySliders             []interface{} `json:\"story_sliders\"`\n\tStoryQuestions           []interface{} `json:\"story_questions\"`\n\tStoryProductItems        []interface{} `json:\"story_product_items\"`\n\tSupportsReelReactions    bool          `json:\"supports_reel_reactions\"`\n\tShowOneTapFbShareTooltip bool          `json:\"show_one_tap_fb_share_tooltip\"`\n\tHasSharedToFb            int           `json:\"has_shared_to_fb\"`\n\tMentions                 []Mentions\n\tVideos                   []Videos `json:\"video_versions,omitempty\"`\n\tHasAudio                 bool     `json:\"has_audio,omitempty\"`\n\tVideoDuration            float64  `json:\"video_duration,omitempty\"`\n\tIsDashEligible           int      `json:\"is_dash_eligible,omitempty\"`\n\tVideoDashManifest        string   `json:\"video_dash_manifest,omitempty\"`\n\tNumberOfQualities        int      `json:\"number_of_qualities,omitempty\"`\n}\n\n\/\/ TopLikers returns string slice or single string (inside string slice)\n\/\/ Depending on TopLikers parameter.\nfunc (item *Item) TopLikers() []string {\n\tswitch s := item._TopLikers.(type) {\n\tcase string:\n\t\treturn []string{s}\n\tcase []string:\n\t\treturn s\n\t}\n\treturn nil\n}\n\n\/\/ PreviewComments returns string slice or single string (inside string slice)\n\/\/ Depending on PreviewComments parameter.\nfunc (item *Item) PreviewComments() []string {\n\tswitch s := item._PreviewComments.(type) {\n\tcase string:\n\t\treturn []string{s}\n\tcase []string:\n\t\treturn s\n\t}\n\treturn nil\n}\n\ntype Media interface {\n\tNext() error\n}\n\ntype StoryMedia struct {\n\tinst     *Instagram\n\tendpoint string\n\tuid      int64\n\n\tID              int      `json:\"id\"`\n\tLatestReelMedia int      `json:\"latest_reel_media\"`\n\tExpiringAt      int      `json:\"expiring_at\"`\n\tSeen            float64  `json:\"seen\"`\n\tCanReply        bool     `json:\"can_reply\"`\n\tCanReshare      bool     `json:\"can_reshare\"`\n\tReelType        string   `json:\"reel_type\"`\n\tUser            User     `json:\"user\"`\n\tItems           []Item   `json:\"items\"`\n\tReelMentions    []string `json:\"reel_mentions\"`\n\tPrefetchCount   int      `json:\"prefetch_count\"`\n\tHasBestiesMedia bool     `json:\"has_besties_media\"`\n\tStatus          string   `json:\"status\"`\n}\n\n\/\/ Next allows to paginate after calling:\n\/\/ User.Stories\nfunc (media *StoryMedia) Next() (err error) {\n\tvar body []byte\n\tinsta := media.inst\n\tendpoint := media.endpoint\n\n\tif media.uid != 0 {\n\t\tendpoint = fmt.Sprintf(endpoint, media.uid)\n\t}\n\tbody, err = insta.sendSimpleRequest(endpoint)\n\tif err == nil {\n\t\tm := StoryMedia{}\n\t\terr = json.Unmarshal(body, &m)\n\t\tif err == nil {\n\t\t\terr = ErrNoMore\n\t\t\t*media = m\n\t\t\tmedia.inst = insta\n\t\t\tmedia.endpoint = endpoint\n\t\t\t\/\/ TODO check NextID media\n\t\t}\n\t}\n\treturn err\n}\n\n\/\/ Media represent a set of media items\ntype FeedMedia struct {\n\tinst *Instagram\n\n\tuid      int64\n\tendpoint string\n\n\tItems               []Item `json:\"items\"`\n\tNumResults          int    `json:\"num_results\"`\n\tMoreAvailable       bool   `json:\"more_available\"`\n\tAutoLoadMoreEnabled bool   `json:\"auto_load_more_enabled\"`\n\tStatus              string `json:\"status\"`\n\t\/\/ Can be int64 and string\n\t\/\/ this is why recomend Next() usage :')\n\tNextID interface{} `json:\"next_max_id\"`\n}\n\n\/\/ Next allows to paginate after calling:\n\/\/ User.Feed\n\/\/\n\/\/ returns ErrNoMore when list reach the end.\nfunc (media *FeedMedia) Next() (err error) {\n\tvar body []byte\n\tinsta := media.inst\n\tendpoint := media.endpoint\n\tnext := \"\"\n\n\tswitch s := media.NextID.(type) {\n\tcase string:\n\t\tnext = s\n\tcase int64:\n\t\tnext = strconv.FormatInt(s, 10)\n\t}\n\n\tif media.uid != 0 {\n\t\tendpoint = fmt.Sprintf(endpoint, media.uid)\n\t}\n\n\tbody, err = insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: endpoint,\n\t\t\tQuery: map[string]string{\n\t\t\t\t\"max_id\":         next,\n\t\t\t\t\"rank_token\":     insta.rankToken,\n\t\t\t\t\"min_timestamp\":  \"\",\n\t\t\t\t\"ranked_content\": \"true\",\n\t\t\t},\n\t\t},\n\t)\n\tif err == nil {\n\t\tm := FeedMedia{}\n\t\terr = json.Unmarshal(body, &m)\n\t\tif err == nil {\n\t\t\t*media = m\n\t\t\tmedia.inst = insta\n\t\t\tmedia.endpoint = endpoint\n\t\t\tif m.NextID == 0 || !m.MoreAvailable {\n\t\t\t\terr = ErrNoMore\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>cmd\/gorename: log 'go build' output on failure<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 iquota Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/gorilla\/context\"\n\t\"github.com\/spf13\/viper\"\n\t\"github.com\/ubccr\/iquota\"\n)\n\nfunc errorHandler(app *Application, w http.ResponseWriter, status int, err *iquota.IsiError) {\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.WriteHeader(status)\n\tif err != nil {\n\t\tout, err := json.Marshal(err)\n\t\tif err != nil {\n\t\t\tlogrus.Printf(\"Error encoding error message as json: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tw.Write(out)\n\t}\n}\n\nfunc IndexHandler(app *Application) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tuser := context.Get(r, \"user\").(*User)\n\t\tif user == nil {\n\t\t\tlogrus.Error(\"index handler: user not found in request context\")\n\t\t\terrorHandler(app, w, http.StatusInternalServerError, nil)\n\t\t\treturn\n\t\t}\n\n\t\tquotas := make([]*iquota.Quota, 0)\n\n\t\tfor _, q := range app.defaultUserQuota {\n\t\t\tquotas = append(quotas, q)\n\t\t}\n\n\t\tfor _, q := range app.defaultGroupQuota {\n\t\t\tquotas = append(quotas, q)\n\t\t}\n\n\t\tout, err := json.Marshal(quotas)\n\t\tif err != nil {\n\t\t\tlogrus.Printf(\"Error encoding data as json: %s\", err)\n\t\t\terrorHandler(app, w, http.StatusInternalServerError, nil)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.Write(out)\n\t})\n}\n\nfunc UserQuotaHandler(app *Application) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tuser := context.Get(r, \"user\").(*User)\n\t\tif user == nil {\n\t\t\tlogrus.Error(\"user quota handler: user not found in request context\")\n\t\t\terrorHandler(app, w, http.StatusInternalServerError, nil)\n\t\t\treturn\n\t\t}\n\n\t\tqp := new(iquota.QuotaParams)\n\t\tapp.decoder.Decode(qp, r.URL.Query())\n\n\t\tif len(qp.Path) == 0 {\n\t\t\terrorHandler(app, w, http.StatusBadRequest, &iquota.IsiError{Code: \"AEC_BAD_REQUEST\", Message: \"Path is required\"})\n\t\t\treturn\n\t\t}\n\n\t\tuid := user.Uid\n\t\tif len(qp.User) != 0 {\n\t\t\tif !user.IsAdmin() {\n\t\t\t\terrorHandler(app, w, http.StatusBadRequest, &iquota.IsiError{Code: \"AEC_BAD_REQUEST\", Message: \"Access denied\"})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tuid = qp.User\n\t\t}\n\n\t\tvar qres *iquota.QuotaResponse\n\n\t\tif viper.GetBool(\"enable_cache\") {\n\t\t\tcqres, err := FetchUserQuotaCache(qp.Path, uid)\n\t\t\tif err == nil {\n\t\t\t\tqres = cqres\n\t\t\t}\n\t\t}\n\n\t\tif qres == nil {\n\t\t\tc := NewOnefsClient()\n\t\t\tres, err := c.FetchUserQuota(qp.Path, uid)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\t\"err\": err.Error(),\n\t\t\t\t\t\"uid\": uid,\n\t\t\t\t}).Error(\"Failed to fetch user quota\")\n\t\t\t\tif ierr, ok := err.(*iquota.IsiError); ok {\n\t\t\t\t\terrorHandler(app, w, http.StatusBadRequest, ierr)\n\t\t\t\t} else {\n\t\t\t\t\terrorHandler(app, w, http.StatusBadRequest, &iquota.IsiError{Code: \"AEC_BAD_REQUEST\", Message: \"Fatal system error\"})\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tqres = res\n\n\t\t\tif viper.GetBool(\"enable_cache\") {\n\t\t\t\tSetUserQuotaCache(qp.Path, uid, qres)\n\t\t\t}\n\t\t}\n\n\t\tqr := &iquota.QuotaRestResponse{Quotas: qres.Quotas}\n\t\tqr.Default, _ = app.defaultUserQuota[qp.Path]\n\n\t\tout, err := json.Marshal(qr)\n\t\tif err != nil {\n\t\t\tlogrus.Printf(\"Error encoding data as json: %s\", err)\n\t\t\terrorHandler(app, w, http.StatusInternalServerError, nil)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.Write(out)\n\t})\n}\n\nfunc GroupQuotaHandler(app *Application) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tuser := context.Get(r, \"user\").(*User)\n\t\tif user == nil {\n\t\t\tlogrus.Error(\"group quota handler: user not found in request context\")\n\t\t\terrorHandler(app, w, http.StatusInternalServerError, nil)\n\t\t\treturn\n\t\t}\n\n\t\tqp := new(iquota.QuotaParams)\n\t\tapp.decoder.Decode(qp, r.URL.Query())\n\n\t\tif len(qp.Path) == 0 {\n\t\t\terrorHandler(app, w, http.StatusBadRequest, &iquota.IsiError{Code: \"AEC_BAD_REQUEST\", Message: \"Path is required\"})\n\t\t\treturn\n\t\t}\n\n\t\tgroups := user.Groups\n\t\tif len(qp.Group) != 0 {\n\t\t\tif !user.IsAdmin() {\n\t\t\t\terrorHandler(app, w, http.StatusBadRequest, &iquota.IsiError{Code: \"AEC_BAD_REQUEST\", Message: \"Access denied\"})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgroups = []string{qp.Group}\n\t\t}\n\n\t\tc := NewOnefsClient()\n\t\tgquotas := make([]*iquota.Quota, 0)\n\n\t\tfor _, group := range groups {\n\n\t\t\tvar qres *iquota.QuotaResponse\n\n\t\t\tif viper.GetBool(\"enable_cache\") {\n\t\t\t\tcqres, err := FetchGroupQuotaCache(qp.Path, group)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif ierr, ok := err.(*iquota.IsiError); ok {\n\t\t\t\t\t\tif ierr.Code == \"AEC_NOT_FOUND\" && len(qp.Group) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\t\t\t\"err\":   ierr.Error(),\n\t\t\t\t\t\t\t\"group\": group,\n\t\t\t\t\t\t}).Error(\"Failed to fetch group quota\")\n\t\t\t\t\t\terrorHandler(app, w, http.StatusBadRequest, ierr)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tqres = cqres\n\t\t\t}\n\n\t\t\tif qres == nil {\n\t\t\t\tres, err := c.FetchGroupQuota(qp.Path, group)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif ierr, ok := err.(*iquota.IsiError); ok {\n\t\t\t\t\t\tif ierr.Code == \"AEC_NOT_FOUND\" && viper.GetBool(\"enable_cache\") {\n\t\t\t\t\t\t\tSetGroupNegCache(qp.Path, group)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ierr.Code == \"AEC_NOT_FOUND\" && len(qp.Group) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\t\t\t\"err\":   ierr.Error(),\n\t\t\t\t\t\t\t\"group\": group,\n\t\t\t\t\t\t}).Error(\"Failed to fetch group quota\")\n\t\t\t\t\t\terrorHandler(app, w, http.StatusBadRequest, ierr)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\t\t\t\"err\":   err.Error(),\n\t\t\t\t\t\t\t\"group\": group,\n\t\t\t\t\t\t}).Error(\"Failed to fetch group quota\")\n\t\t\t\t\t\terrorHandler(app, w, http.StatusBadRequest, &iquota.IsiError{Code: \"AEC_BAD_REQUEST\", Message: \"Fatal system error\"})\n\t\t\t\t\t}\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tqres = res\n\t\t\t\tif viper.GetBool(\"enable_cache\") {\n\t\t\t\t\tSetGroupQuotaCache(qp.Path, group, qres)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgquotas = append(gquotas, qres.Quotas...)\n\t\t}\n\n\t\tqr := &iquota.QuotaRestResponse{Quotas: gquotas}\n\t\tqr.Default, _ = app.defaultGroupQuota[qp.Path]\n\n\t\tout, err := json.Marshal(qr)\n\t\tif err != nil {\n\t\t\tlogrus.Printf(\"Error encoding data as json: %s\", err)\n\t\t\terrorHandler(app, w, http.StatusInternalServerError, nil)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.Write(out)\n\t})\n}\n<commit_msg>Fix bug in user filter check<commit_after>\/\/ Copyright 2015 iquota Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/gorilla\/context\"\n\t\"github.com\/spf13\/viper\"\n\t\"github.com\/ubccr\/iquota\"\n)\n\nfunc errorHandler(app *Application, w http.ResponseWriter, status int, err *iquota.IsiError) {\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.WriteHeader(status)\n\tif err != nil {\n\t\tout, err := json.Marshal(err)\n\t\tif err != nil {\n\t\t\tlogrus.Printf(\"Error encoding error message as json: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tw.Write(out)\n\t}\n}\n\nfunc IndexHandler(app *Application) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tuser := context.Get(r, \"user\").(*User)\n\t\tif user == nil {\n\t\t\tlogrus.Error(\"index handler: user not found in request context\")\n\t\t\terrorHandler(app, w, http.StatusInternalServerError, nil)\n\t\t\treturn\n\t\t}\n\n\t\tquotas := make([]*iquota.Quota, 0)\n\n\t\tfor _, q := range app.defaultUserQuota {\n\t\t\tquotas = append(quotas, q)\n\t\t}\n\n\t\tfor _, q := range app.defaultGroupQuota {\n\t\t\tquotas = append(quotas, q)\n\t\t}\n\n\t\tout, err := json.Marshal(quotas)\n\t\tif err != nil {\n\t\t\tlogrus.Printf(\"Error encoding data as json: %s\", err)\n\t\t\terrorHandler(app, w, http.StatusInternalServerError, nil)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.Write(out)\n\t})\n}\n\nfunc UserQuotaHandler(app *Application) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tuser := context.Get(r, \"user\").(*User)\n\t\tif user == nil {\n\t\t\tlogrus.Error(\"user quota handler: user not found in request context\")\n\t\t\terrorHandler(app, w, http.StatusInternalServerError, nil)\n\t\t\treturn\n\t\t}\n\n\t\tqp := new(iquota.QuotaParams)\n\t\tapp.decoder.Decode(qp, r.URL.Query())\n\n\t\tif len(qp.Path) == 0 {\n\t\t\terrorHandler(app, w, http.StatusBadRequest, &iquota.IsiError{Code: \"AEC_BAD_REQUEST\", Message: \"Path is required\"})\n\t\t\treturn\n\t\t}\n\n\t\tuid := user.Uid\n\t\tif len(qp.User) != 0 && qp.User != uid {\n\t\t\tif !user.IsAdmin() {\n\t\t\t\terrorHandler(app, w, http.StatusBadRequest, &iquota.IsiError{Code: \"AEC_BAD_REQUEST\", Message: \"Access denied\"})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tuid = qp.User\n\t\t}\n\n\t\tvar qres *iquota.QuotaResponse\n\n\t\tif viper.GetBool(\"enable_cache\") {\n\t\t\tcqres, err := FetchUserQuotaCache(qp.Path, uid)\n\t\t\tif err == nil {\n\t\t\t\tqres = cqres\n\t\t\t}\n\t\t}\n\n\t\tif qres == nil {\n\t\t\tc := NewOnefsClient()\n\t\t\tres, err := c.FetchUserQuota(qp.Path, uid)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\t\"err\": err.Error(),\n\t\t\t\t\t\"uid\": uid,\n\t\t\t\t}).Error(\"Failed to fetch user quota\")\n\t\t\t\tif ierr, ok := err.(*iquota.IsiError); ok {\n\t\t\t\t\terrorHandler(app, w, http.StatusBadRequest, ierr)\n\t\t\t\t} else {\n\t\t\t\t\terrorHandler(app, w, http.StatusBadRequest, &iquota.IsiError{Code: \"AEC_BAD_REQUEST\", Message: \"Fatal system error\"})\n\t\t\t\t}\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tqres = res\n\n\t\t\tif viper.GetBool(\"enable_cache\") {\n\t\t\t\tSetUserQuotaCache(qp.Path, uid, qres)\n\t\t\t}\n\t\t}\n\n\t\tqr := &iquota.QuotaRestResponse{Quotas: qres.Quotas}\n\t\tqr.Default, _ = app.defaultUserQuota[qp.Path]\n\n\t\tout, err := json.Marshal(qr)\n\t\tif err != nil {\n\t\t\tlogrus.Printf(\"Error encoding data as json: %s\", err)\n\t\t\terrorHandler(app, w, http.StatusInternalServerError, nil)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.Write(out)\n\t})\n}\n\nfunc GroupQuotaHandler(app *Application) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tuser := context.Get(r, \"user\").(*User)\n\t\tif user == nil {\n\t\t\tlogrus.Error(\"group quota handler: user not found in request context\")\n\t\t\terrorHandler(app, w, http.StatusInternalServerError, nil)\n\t\t\treturn\n\t\t}\n\n\t\tqp := new(iquota.QuotaParams)\n\t\tapp.decoder.Decode(qp, r.URL.Query())\n\n\t\tif len(qp.Path) == 0 {\n\t\t\terrorHandler(app, w, http.StatusBadRequest, &iquota.IsiError{Code: \"AEC_BAD_REQUEST\", Message: \"Path is required\"})\n\t\t\treturn\n\t\t}\n\n\t\tgroups := user.Groups\n\t\tif len(qp.Group) != 0 {\n\t\t\tif !user.IsAdmin() {\n\t\t\t\terrorHandler(app, w, http.StatusBadRequest, &iquota.IsiError{Code: \"AEC_BAD_REQUEST\", Message: \"Access denied\"})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tgroups = []string{qp.Group}\n\t\t}\n\n\t\tc := NewOnefsClient()\n\t\tgquotas := make([]*iquota.Quota, 0)\n\n\t\tfor _, group := range groups {\n\n\t\t\tvar qres *iquota.QuotaResponse\n\n\t\t\tif viper.GetBool(\"enable_cache\") {\n\t\t\t\tcqres, err := FetchGroupQuotaCache(qp.Path, group)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif ierr, ok := err.(*iquota.IsiError); ok {\n\t\t\t\t\t\tif ierr.Code == \"AEC_NOT_FOUND\" && len(qp.Group) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\t\t\t\"err\":   ierr.Error(),\n\t\t\t\t\t\t\t\"group\": group,\n\t\t\t\t\t\t}).Error(\"Failed to fetch group quota\")\n\t\t\t\t\t\terrorHandler(app, w, http.StatusBadRequest, ierr)\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tqres = cqres\n\t\t\t}\n\n\t\t\tif qres == nil {\n\t\t\t\tres, err := c.FetchGroupQuota(qp.Path, group)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif ierr, ok := err.(*iquota.IsiError); ok {\n\t\t\t\t\t\tif ierr.Code == \"AEC_NOT_FOUND\" && viper.GetBool(\"enable_cache\") {\n\t\t\t\t\t\t\tSetGroupNegCache(qp.Path, group)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif ierr.Code == \"AEC_NOT_FOUND\" && len(qp.Group) == 0 {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\t\t\t\"err\":   ierr.Error(),\n\t\t\t\t\t\t\t\"group\": group,\n\t\t\t\t\t\t}).Error(\"Failed to fetch group quota\")\n\t\t\t\t\t\terrorHandler(app, w, http.StatusBadRequest, ierr)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\t\t\t\"err\":   err.Error(),\n\t\t\t\t\t\t\t\"group\": group,\n\t\t\t\t\t\t}).Error(\"Failed to fetch group quota\")\n\t\t\t\t\t\terrorHandler(app, w, http.StatusBadRequest, &iquota.IsiError{Code: \"AEC_BAD_REQUEST\", Message: \"Fatal system error\"})\n\t\t\t\t\t}\n\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tqres = res\n\t\t\t\tif viper.GetBool(\"enable_cache\") {\n\t\t\t\t\tSetGroupQuotaCache(qp.Path, group, qres)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgquotas = append(gquotas, qres.Quotas...)\n\t\t}\n\n\t\tqr := &iquota.QuotaRestResponse{Quotas: gquotas}\n\t\tqr.Default, _ = app.defaultGroupQuota[qp.Path]\n\n\t\tout, err := json.Marshal(qr)\n\t\tif err != nil {\n\t\t\tlogrus.Printf(\"Error encoding data as json: %s\", err)\n\t\t\terrorHandler(app, w, http.StatusInternalServerError, nil)\n\t\t\treturn\n\t\t}\n\n\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\tw.Write(out)\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"strconv\"\n\n\t\"github.com\/shirou\/gopsutil\/cpu\"\n)\n\n\/\/ `cpuinfo` represent the CPU informations\ntype cpuinfo struct {\n\tcount     string \/\/ number of CPUs\n\tvendorID  string \/\/ vendor name ex. AuthenticAMD, GenuineIntel\n\tmodelName string \/\/ CPU model name\n\tcpuMhz    string \/\/\n\t\/\/TODO temperature and fan speed ?\n}\n\n\/\/ Get informations about the cpu by using `gopesutil` packages\nfunc getCPUinfo() cpuinfo {\n\tinfo, err := cpu.Info() \/\/ cpu.Info() return a slice of InfoStat structs\n\tif err != nil {\n\t\tpanic(err) \/\/TODO do not panic but manage the error\n\t}\n\n\tresult := cpuinfo{\n\t\tcount:     strconv.Itoa(len(info)),\n\t\tvendorID:  info[0].VendorID, \/\/BUG in `gopsutil`\n\t\tmodelName: info[0].ModelName,\n\t\tcpuMhz:    strconv.FormatFloat(info[0].Mhz, 'f', 0, 64),\n\t}\n\treturn result\n}\n\n\/\/TODO count cores ?\n\/\/TODO count the physicals id = multiples sockets\n\n\/\/TODO We need to improve this. For now it take vendorID, modelName, etc from\n\/\/the first CPU assuming than all CPUs are the same (probably OK)and than there\n\/\/is only one socket (not true on servers)\n\/\/\n\/\/ http:\/\/superuser.com\/questions\/388115\/interpreting-output-of-cat-proc-cpuinfo\n\/\/ http:\/\/unix.stackexchange.com\/questions\/146051\/number-of-processors-in-proc-cpuinfo\n\/\/\n\/\/ TODO add temperature\n<commit_msg>Update cpusinfo stats<commit_after>package main\n\nimport (\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/shirou\/gopsutil\/cpu\"\n)\n\n\/\/ `cpuinfo` represent the CPU informations\ntype cpuinfo struct {\n\tcount     string \/\/ number of CPUs\n\tvendorID  string \/\/ vendor name ex. AuthenticAMD, GenuineIntel\n\tmodelName string \/\/ CPU model name\n\tcpuMhz    string \/\/ speed of the CPU\n\t\/\/TODO temperature and fan speed ?\n}\n\n\/\/ Get informations about the cpu by using `gopesutil` packages\nfunc getCPUinfo() cpuinfo {\n\tinfo, err := cpu.Info() \/\/ cpu.Info() return a slice of InfoStat structs\n\tif err != nil {\n\t\tpanic(err) \/\/TODO do not panic but manage the error\n\t}\n\n\tresult := cpuinfo{\n\t\tcount:     strconv.Itoa(len(info)),\n\t\tvendorID:  info[0].VendorID, \/\/BUG in `gopsutil`\n\t\tmodelName: info[0].ModelName,\n\t\tcpuMhz:    strconv.FormatFloat(info[0].Mhz, 'f', 0, 64),\n\t}\n\treturn result\n}\n\n\/\/ get the system-wide CPU utilization percentage\nfunc getCPUpercent() (usedPercent int) {\n\tpercent, err := cpu.Percent((500 * time.Millisecond), false) \/\/ 0.5 seconds, `false` for system wide\n\tif err != nil {\n\t\tpanic(err) \/\/TODO do not panic but manage the error\n\t}\n\n\treturn int(percent[0]) \/\/ even if cpu.Percent() use `false` it return a slice\n}\n\n\/\/TODO count cores ?\n\/\/TODO count the physicals id = multiples sockets\n\n\/\/TODO We need to improve this. For now it take vendorID, modelName, etc from\n\/\/the first CPU assuming than all CPUs are the same (probably OK)and than there\n\/\/is only one socket (not true on servers)\n\/\/\n\/\/ http:\/\/superuser.com\/questions\/388115\/interpreting-output-of-cat-proc-cpuinfo\n\/\/ http:\/\/unix.stackexchange.com\/questions\/146051\/number-of-processors-in-proc-cpuinfo\n\/\/\n\/\/ TODO add temperature\n<|endoftext|>"}
{"text":"<commit_before>package token\n\nimport (\n\t\"fmt\"\n)\n\ntype Token struct {\n\tTyp TokenType\n\tVal string\n\tPos int\n}\n\nfunc NewToken(typ TokenType, val string, pos int) Token {\n\treturn Token{typ, val, pos};\n}\n\nconst IgnoreTokenPos = -1\n\nfunc (t *Token) Compare(o Token) bool{\n\tif (t.Pos == IgnoreTokenPos || o.Pos == IgnoreTokenPos) {\n\t\treturn t.Typ == o.Typ && t.Val == o.Val;\n\t}\n\treturn t.Typ == o.Typ && t.Val == o.Val && t.Pos == o.Pos;\n}\n\nfunc (i *Token) String() string {\n\tswitch i.Typ {\n\tcase EOF:\n\t\treturn \"EOF\"\n\t}\n\tval := i.Val\n\tif len(val) > 10 {\n\t\t\/\/val = fmt.Sprintf(\"%.10q...\", val)\n\t}\n\treturn fmt.Sprintf(\"Token(%v, %q, %d)\", i.Typ, val, i.Pos)\n}\n\ntype TokenType string\n\nconst (\n\tEOF TokenType\t= \"eof\"\n\tERROR \t\t= \"error\"\n\n\tUSINGDATABASE \t= \"usingDatabase\"\n\tFORDOMAIN \t= \"forDomain\"\n\tINCONTEXT \t= \"inContext\"\n\tWITHINAGGREGATE = \"withinAggregate\"\n\n\tCLASSOPEN \t= \"<|\"\n\tCLASSCLOSE \t= \"|>\"\n\tOBJECTNAME \t= \"objectName\"\n\n\t\/\/DQL Keywords - Objects\n\tCREATE \t   = \"create\"\n\tLIST\t   = \"list\"\n\tDATABASE   = \"database\"\n\tDATABASES   = \"databases\"\n\tDOMAIN     = \"domain\"\n\tCONTEXT    = \"context\"\n\tAGGREGATE  = \"aggregate\"\n\tVALUE      = \"value\"\n\tEVENT      = \"event\"\n\tENTITY     = \"entity\"\n\tCOMMAND    = \"command\"\n\tPROJECTION = \"projection\"\n\tINVARIANT  = \"invariant\"\n\tQUERY      = \"query\"\n\tAS \t   = \"as\"\n\tON \t   = \"on\"\n\n\t\/\/ Class components\n\tPROPERTIES = \"properties\"\n\tCHECK      = \"check\"\n\tHANDLER    = \"handler\"\n\tFUNCTION   = \"function\"\n\tWHENEVENT  = \"when event\"\n\n\t\/\/ Command Handler statements\n\tASSERTINVARIANT = \"assert invariant\"\n\tNOT \t\t= \"not\"\n\tRUNQUERY \t= \"run query\"\n\tAPPLYEVENT \t= \"apply event\"\n\n\t\/\/ Operators\n\tASSIGN    = \"=\"\n\tPLUS      = \"+\"\n\tMINUS     = \"-\"\n\tBANG      = \"!\"\n\tASTERISK  = \"*\"\n\tSLASH     = \"\/\"\n\tREMAINDER = \"%\"\n\tARROW \t  = \"->\"\n\tSTRONGARROW = \"=>\"\n\tAND \t  = \"and\"\n\tOR \t  = \"or\"\n\tLT \t  = \"<\"\n\tGT \t  = \">\"\n\tEQ \t  = \"==\"\n\tNOTEQ\t  = \"!=\"\n\tLTOREQ \t  = \"<=\"\n\tGTOREQ \t  = \">=\"\n\n\t\/\/ Delimiters\n\tCOMMA    = \",\"\n\tSEMICOLON= \";\"\n\tCOLON    = \":\"\n\tLPAREN   = \"(\"\n\tRPAREN   = \")\"\n\tLBRACE   = \"{\"\n\tRBRACE   = \"}\"\n\tLBRACKET = \"[\"\n\tRBRACKET = \"]\"\n\n\t\/\/Types\n\tINTEGER\t= \"integer\"\n\tFLOAT   = \"float\"\n\tBOOLEAN = \"boolean\"\n\tSTRING  = \"string\"\n\tNULL    = \"null\"\n\tIDENT \t= \"identifier\"\n\n\t\/\/Statements\n\tIF \t= \"if\"\n\tELSEIF \t= \"else if\"\n\tELSE \t= \"else\"\n\tRETURN \t= \"return\"\n\tFOREACH = \"foreach\"\n)\n\nfunc Semicolon(pos int) Token {\n\treturn NewToken(SEMICOLON, \";\", pos);\n}\n\nfunc ClsOpen(pos int) Token {\n\treturn NewToken(CLASSOPEN, \"<|\", pos);\n}\n\nfunc ClsClose(pos int) Token {\n\treturn NewToken(CLASSCLOSE, \"|>\", pos);\n}<commit_msg>Removed commented out line<commit_after>package token\n\nimport (\n\t\"fmt\"\n)\n\ntype Token struct {\n\tTyp TokenType\n\tVal string\n\tPos int\n}\n\nfunc NewToken(typ TokenType, val string, pos int) Token {\n\treturn Token{typ, val, pos};\n}\n\nconst IgnoreTokenPos = -1\n\nfunc (t *Token) Compare(o Token) bool{\n\tif (t.Pos == IgnoreTokenPos || o.Pos == IgnoreTokenPos) {\n\t\treturn t.Typ == o.Typ && t.Val == o.Val;\n\t}\n\treturn t.Typ == o.Typ && t.Val == o.Val && t.Pos == o.Pos;\n}\n\nfunc (i *Token) String() string {\n\tswitch i.Typ {\n\tcase EOF:\n\t\treturn \"EOF\"\n\t}\n\tval := i.Val\n\n\treturn fmt.Sprintf(\"Token(%v, %q, %d)\", i.Typ, val, i.Pos)\n}\n\ntype TokenType string\n\nconst (\n\tEOF TokenType\t= \"eof\"\n\tERROR \t\t= \"error\"\n\n\tUSINGDATABASE \t= \"usingDatabase\"\n\tFORDOMAIN \t= \"forDomain\"\n\tINCONTEXT \t= \"inContext\"\n\tWITHINAGGREGATE = \"withinAggregate\"\n\n\tCLASSOPEN \t= \"<|\"\n\tCLASSCLOSE \t= \"|>\"\n\tOBJECTNAME \t= \"objectName\"\n\n\t\/\/DQL Keywords - Objects\n\tCREATE \t   = \"create\"\n\tLIST\t   = \"list\"\n\tDATABASE   = \"database\"\n\tDATABASES   = \"databases\"\n\tDOMAIN     = \"domain\"\n\tCONTEXT    = \"context\"\n\tAGGREGATE  = \"aggregate\"\n\tVALUE      = \"value\"\n\tEVENT      = \"event\"\n\tENTITY     = \"entity\"\n\tCOMMAND    = \"command\"\n\tPROJECTION = \"projection\"\n\tINVARIANT  = \"invariant\"\n\tQUERY      = \"query\"\n\tAS \t   = \"as\"\n\tON \t   = \"on\"\n\n\t\/\/ Class components\n\tPROPERTIES = \"properties\"\n\tCHECK      = \"check\"\n\tHANDLER    = \"handler\"\n\tFUNCTION   = \"function\"\n\tWHENEVENT  = \"when event\"\n\n\t\/\/ Command Handler statements\n\tASSERTINVARIANT = \"assert invariant\"\n\tNOT \t\t= \"not\"\n\tRUNQUERY \t= \"run query\"\n\tAPPLYEVENT \t= \"apply event\"\n\n\t\/\/ Operators\n\tASSIGN    = \"=\"\n\tPLUS      = \"+\"\n\tMINUS     = \"-\"\n\tBANG      = \"!\"\n\tASTERISK  = \"*\"\n\tSLASH     = \"\/\"\n\tREMAINDER = \"%\"\n\tARROW \t  = \"->\"\n\tSTRONGARROW = \"=>\"\n\tAND \t  = \"and\"\n\tOR \t  = \"or\"\n\tLT \t  = \"<\"\n\tGT \t  = \">\"\n\tEQ \t  = \"==\"\n\tNOTEQ\t  = \"!=\"\n\tLTOREQ \t  = \"<=\"\n\tGTOREQ \t  = \">=\"\n\n\t\/\/ Delimiters\n\tCOMMA    = \",\"\n\tSEMICOLON= \";\"\n\tCOLON    = \":\"\n\tLPAREN   = \"(\"\n\tRPAREN   = \")\"\n\tLBRACE   = \"{\"\n\tRBRACE   = \"}\"\n\tLBRACKET = \"[\"\n\tRBRACKET = \"]\"\n\n\t\/\/Types\n\tINTEGER\t= \"integer\"\n\tFLOAT   = \"float\"\n\tBOOLEAN = \"boolean\"\n\tSTRING  = \"string\"\n\tNULL    = \"null\"\n\tIDENT \t= \"identifier\"\n\n\t\/\/Statements\n\tIF \t= \"if\"\n\tELSEIF \t= \"else if\"\n\tELSE \t= \"else\"\n\tRETURN \t= \"return\"\n\tFOREACH = \"foreach\"\n)\n\nfunc Semicolon(pos int) Token {\n\treturn NewToken(SEMICOLON, \";\", pos);\n}\n\nfunc ClsOpen(pos int) Token {\n\treturn NewToken(CLASSOPEN, \"<|\", pos);\n}\n\nfunc ClsClose(pos int) Token {\n\treturn NewToken(CLASSCLOSE, \"|>\", pos);\n}<|endoftext|>"}
{"text":"<commit_before>package files\n\nimport (\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/cozy\/cozy-stack\/pkg\/permissions\"\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestCreateDirNoToken(t *testing.T) {\n\tnoToken := \"\"\n\tres, err := request(\"POST\", \"\/files\/?Name=icantcreateyou&Type=directory\", noToken, strings.NewReader(\"\"))\n\tassert.NoError(t, err)\n\tassert.Equal(t, 401, res.StatusCode)\n}\n\nfunc TestCreateDirBadType(t *testing.T) {\n\tbadtok, _ := testInstance.MakeJWT(permissions.AccessTokenAudience, \"io.cozy.events\", clientID, time.Now())\n\tres, err := request(\"POST\", \"\/files\/?Name=icantcreateyou&Type=directory\", badtok, strings.NewReader(\"\"))\n\tassert.NoError(t, err)\n\tassert.Equal(t, 403, res.StatusCode)\n}\n\nfunc TestCreateDirLimitedScope(t *testing.T) {\n\tres, data := createDir(t, \"\/files\/?Name=permissionholder&Type=directory\")\n\tassert.Equal(t, 201, res.StatusCode)\n\tid := data[\"data\"].(map[string]interface{})[\"id\"].(string)\n\tbadtok, _ := testInstance.MakeJWT(permissions.AccessTokenAudience, \"io.cozy.files:ALL:\"+id, clientID, time.Now())\n\n\t\/\/ not in authorized dir\n\tres, err := request(\"POST\", \"\/files\/?Name=icantcreateyou&Type=directory\", badtok, strings.NewReader(\"\"))\n\tassert.NoError(t, err)\n\tassert.Equal(t, 403, res.StatusCode)\n\n\t\/\/ in authorized dir\n\tres2, err := request(\"POST\", \"\/files\/\"+id+\"?Name=icancreateyou&Type=directory\", token, strings.NewReader(\"\"))\n\tassert.NoError(t, err)\n\tassert.Equal(t, 201, res2.StatusCode)\n}\n\nfunc TestCreateDirBadVerb(t *testing.T) {\n\tbadtok, _ := testInstance.MakeJWT(permissions.AccessTokenAudience, \"io.cozy.files:GET\", clientID, time.Now())\n\tres, err := request(\"POST\", \"\/files\/?Name=icantcreateyou&Type=directory\", badtok, strings.NewReader(\"\"))\n\tassert.NoError(t, err)\n\tassert.Equal(t, 403, res.StatusCode)\n}\n\nfunc request(m, path, token string, body io.Reader) (*http.Response, error) {\n\treq, err := http.NewRequest(m, ts.URL+path, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Content-Type\", \"text\/plain\")\n\tif token != \"\" {\n\t\treq.Header.Add(echo.HeaderAuthorization, \"Bearer \"+token)\n\t}\n\treturn http.DefaultClient.Do(req)\n}\n<commit_msg>fix web\/files test<commit_after>package files\n\nimport (\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/cozy\/cozy-stack\/pkg\/permissions\"\n\t\"github.com\/labstack\/echo\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestCreateDirNoToken(t *testing.T) {\n\tnoToken := \"\"\n\tres, err := request(\"POST\", \"\/files\/?Name=icantcreateyou&Type=directory\", noToken, strings.NewReader(\"\"))\n\tassert.NoError(t, err)\n\tassert.Equal(t, 401, res.StatusCode)\n}\n\nfunc TestCreateDirBadType(t *testing.T) {\n\tbadtok, _ := testInstance.MakeJWT(permissions.AccessTokenAudience, clientID, \"io.cozy.events\", time.Now())\n\tres, err := request(\"POST\", \"\/files\/?Name=icantcreateyou&Type=directory\", badtok, strings.NewReader(\"\"))\n\tassert.NoError(t, err)\n\tassert.Equal(t, 403, res.StatusCode)\n}\n\nfunc TestCreateDirLimitedScope(t *testing.T) {\n\tres, data := createDir(t, \"\/files\/?Name=permissionholder&Type=directory\")\n\tassert.Equal(t, 201, res.StatusCode)\n\tid := data[\"data\"].(map[string]interface{})[\"id\"].(string)\n\tbadtok, _ := testInstance.MakeJWT(permissions.AccessTokenAudience, clientID, \"io.cozy.files:ALL:\"+id, time.Now())\n\n\t\/\/ not in authorized dir\n\tres, err := request(\"POST\", \"\/files\/?Name=icantcreateyou&Type=directory\", badtok, strings.NewReader(\"\"))\n\tassert.NoError(t, err)\n\tassert.Equal(t, 403, res.StatusCode)\n\n\t\/\/ in authorized dir\n\tres2, err := request(\"POST\", \"\/files\/\"+id+\"?Name=icancreateyou&Type=directory\", token, strings.NewReader(\"\"))\n\tassert.NoError(t, err)\n\tassert.Equal(t, 201, res2.StatusCode)\n}\n\nfunc TestCreateDirBadVerb(t *testing.T) {\n\tbadtok, _ := testInstance.MakeJWT(permissions.AccessTokenAudience, clientID, \"io.cozy.files:GET\", time.Now())\n\tres, err := request(\"POST\", \"\/files\/?Name=icantcreateyou&Type=directory\", badtok, strings.NewReader(\"\"))\n\tassert.NoError(t, err)\n\tassert.Equal(t, 403, res.StatusCode)\n}\n\nfunc request(m, path, token string, body io.Reader) (*http.Response, error) {\n\treq, err := http.NewRequest(m, ts.URL+path, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Content-Type\", \"text\/plain\")\n\tif token != \"\" {\n\t\treq.Header.Add(echo.HeaderAuthorization, \"Bearer \"+token)\n\t}\n\treturn http.DefaultClient.Do(req)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012, 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\n\/\/ The worker\/uniter\/jujuc package implements the server side of the jujuc proxy\n\/\/ tool, which forwards command invocations to the unit agent process so that\n\/\/ they can be executed against specific state.\npackage jujuc\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/rpc\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"sync\"\n\n\t\"github.com\/juju\/cmd\"\n\t\"github.com\/juju\/loggo\"\n\t\"github.com\/juju\/utils\/exec\"\n\n\t\/\/ \"github.com\/juju\/juju\/juju\/osenv\"\n)\n\nvar logger = loggo.GetLogger(\"worker.uniter.jujuc\")\n\n\/\/ newCommands maps Command names to initializers.\nvar newCommands = map[string]func(Context) cmd.Command{\n\t\"close-port\":    NewClosePortCommand,\n\t\"config-get\":    NewConfigGetCommand,\n\t\"juju-log\":      NewJujuLogCommand,\n\t\"open-port\":     NewOpenPortCommand,\n\t\"relation-get\":  NewRelationGetCommand,\n\t\"relation-ids\":  NewRelationIdsCommand,\n\t\"relation-list\": NewRelationListCommand,\n\t\"relation-set\":  NewRelationSetCommand,\n\t\"unit-get\":      NewUnitGetCommand,\n\t\"owner-get\":     NewOwnerGetCommand,\n}\n\n\/\/ CommandNames returns the names of all jujuc commands.\nfunc CommandNames() (names []string) {\n\tfor name := range newCommands {\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\treturn\n}\n\n\/\/ NewCommand returns an instance of the named Command, initialized to execute\n\/\/ against the supplied Context.\nfunc NewCommand(ctx Context, name string) (cmd.Command, error) {\n\tf := newCommands[name]\n\tif f == nil {\n\t\treturn nil, fmt.Errorf(\"unknown command: %s\", name)\n\t}\n\treturn f(ctx), nil\n}\n\n\/\/ Request contains the information necessary to run a Command remotely.\ntype Request struct {\n\tContextId   string\n\tDir         string\n\tCommandName string\n\tArgs        []string\n}\n\n\/\/ CmdGetter looks up a Command implementation connected to a particular Context.\ntype CmdGetter func(contextId, cmdName string) (cmd.Command, error)\n\n\/\/ Jujuc implements the jujuc command in the form required by net\/rpc.\ntype Jujuc struct {\n\tmu     sync.Mutex\n\tgetCmd CmdGetter\n}\n\n\/\/ badReqErrorf returns an error indicating a bad Request.\nfunc badReqErrorf(format string, v ...interface{}) error {\n\treturn fmt.Errorf(\"bad request: \"+format, v...)\n}\n\n\/\/ Main runs the Command specified by req, and fills in resp. A single command\n\/\/ is run at a time.\nfunc (j *Jujuc) Main(req Request, resp *exec.ExecResponse) error {\n\tif req.CommandName == \"\" {\n\t\treturn badReqErrorf(\"command not specified\")\n\t}\n\tif !filepath.IsAbs(req.Dir) {\n\t\treturn badReqErrorf(\"Dir is not absolute\")\n\t}\n\tc, err := j.getCmd(req.ContextId, req.CommandName)\n\tif err != nil {\n\t\treturn badReqErrorf(\"%s\", err)\n\t}\n\tvar stdin, stdout, stderr bytes.Buffer\n\tctx := &cmd.Context{\n\t\tDir:    req.Dir,\n\t\tStdin:  &stdin,\n\t\tStdout: &stdout,\n\t\tStderr: &stderr,\n\t}\n\tj.mu.Lock()\n\tdefer j.mu.Unlock()\n\tlogger.Infof(\"running hook tool %q %q\", req.CommandName, req.Args)\n\tlogger.Debugf(\"hook context id %q; dir %q\", req.ContextId, req.Dir)\n\tresp.Code = cmd.Main(c, ctx, req.Args)\n\tresp.Stdout = stdout.Bytes()\n\tresp.Stderr = stderr.Bytes()\n\treturn nil\n}\n\n\/\/ Server implements a server that serves command invocations via\n\/\/ a unix domain socket.\ntype Server struct {\n\tsocketPath string\n\tlistener   net.Listener\n\tserver     *rpc.Server\n\tclosed     chan bool\n\tclosing    chan bool\n\twg         sync.WaitGroup\n}\n\n\/\/ NewServer creates an RPC server bound to socketPath, which can execute\n\/\/ remote command invocations against an appropriate Context. It will not\n\/\/ actually do so until Run is called.\nfunc NewServer(getCmd CmdGetter, socketPath string) (*Server, error) {\n\tserver := rpc.NewServer()\n\tif err := server.Register(&Jujuc{getCmd: getCmd}); err != nil {\n\t\treturn nil, err\n\t}\n\tlistener, err := net.Listen(\"unix\", socketPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts := &Server{\n\t\tsocketPath: socketPath,\n\t\tlistener:   listener,\n\t\tserver:     server,\n\t\tclosed:     make(chan bool),\n\t\tclosing:    make(chan bool),\n\t}\n\treturn s, nil\n}\n\n\/\/ Run accepts new connections until it encounters an error, or until Close is\n\/\/ called, and then blocks until all existing connections have been closed.\nfunc (s *Server) Run() (err error) {\n\tvar conn net.Conn\n\tfor {\n\t\tconn, err = s.listener.Accept()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\ts.wg.Add(1)\n\t\tgo func(conn net.Conn) {\n\t\t\ts.server.ServeConn(conn)\n\t\t\ts.wg.Done()\n\t\t}(conn)\n\t}\n\tselect {\n\tcase <-s.closing:\n\t\t\/\/ Someone has called Close(), so it is overwhelmingly likely that\n\t\t\/\/ the error from Accept is a direct result of the Listener being\n\t\t\/\/ closed, and can therefore be safely ignored.\n\t\terr = nil\n\tdefault:\n\t}\n\ts.wg.Wait()\n\tclose(s.closed)\n\treturn\n}\n\n\/\/ Close immediately stops accepting connections, and blocks until all existing\n\/\/ connections have been closed.\nfunc (s *Server) Close() {\n\tclose(s.closing)\n\ts.listener.Close()\n\t<-s.closed\n}\n<commit_msg>removed commented import<commit_after>\/\/ Copyright 2012, 2013 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\n\/\/ The worker\/uniter\/jujuc package implements the server side of the jujuc proxy\n\/\/ tool, which forwards command invocations to the unit agent process so that\n\/\/ they can be executed against specific state.\npackage jujuc\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/rpc\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"sync\"\n\n\t\"github.com\/juju\/cmd\"\n\t\"github.com\/juju\/loggo\"\n\t\"github.com\/juju\/utils\/exec\"\n)\n\nvar logger = loggo.GetLogger(\"worker.uniter.jujuc\")\n\n\/\/ newCommands maps Command names to initializers.\nvar newCommands = map[string]func(Context) cmd.Command{\n\t\"close-port\":    NewClosePortCommand,\n\t\"config-get\":    NewConfigGetCommand,\n\t\"juju-log\":      NewJujuLogCommand,\n\t\"open-port\":     NewOpenPortCommand,\n\t\"relation-get\":  NewRelationGetCommand,\n\t\"relation-ids\":  NewRelationIdsCommand,\n\t\"relation-list\": NewRelationListCommand,\n\t\"relation-set\":  NewRelationSetCommand,\n\t\"unit-get\":      NewUnitGetCommand,\n\t\"owner-get\":     NewOwnerGetCommand,\n}\n\n\/\/ CommandNames returns the names of all jujuc commands.\nfunc CommandNames() (names []string) {\n\tfor name := range newCommands {\n\t\tnames = append(names, name)\n\t}\n\tsort.Strings(names)\n\treturn\n}\n\n\/\/ NewCommand returns an instance of the named Command, initialized to execute\n\/\/ against the supplied Context.\nfunc NewCommand(ctx Context, name string) (cmd.Command, error) {\n\tf := newCommands[name]\n\tif f == nil {\n\t\treturn nil, fmt.Errorf(\"unknown command: %s\", name)\n\t}\n\treturn f(ctx), nil\n}\n\n\/\/ Request contains the information necessary to run a Command remotely.\ntype Request struct {\n\tContextId   string\n\tDir         string\n\tCommandName string\n\tArgs        []string\n}\n\n\/\/ CmdGetter looks up a Command implementation connected to a particular Context.\ntype CmdGetter func(contextId, cmdName string) (cmd.Command, error)\n\n\/\/ Jujuc implements the jujuc command in the form required by net\/rpc.\ntype Jujuc struct {\n\tmu     sync.Mutex\n\tgetCmd CmdGetter\n}\n\n\/\/ badReqErrorf returns an error indicating a bad Request.\nfunc badReqErrorf(format string, v ...interface{}) error {\n\treturn fmt.Errorf(\"bad request: \"+format, v...)\n}\n\n\/\/ Main runs the Command specified by req, and fills in resp. A single command\n\/\/ is run at a time.\nfunc (j *Jujuc) Main(req Request, resp *exec.ExecResponse) error {\n\tif req.CommandName == \"\" {\n\t\treturn badReqErrorf(\"command not specified\")\n\t}\n\tif !filepath.IsAbs(req.Dir) {\n\t\treturn badReqErrorf(\"Dir is not absolute\")\n\t}\n\tc, err := j.getCmd(req.ContextId, req.CommandName)\n\tif err != nil {\n\t\treturn badReqErrorf(\"%s\", err)\n\t}\n\tvar stdin, stdout, stderr bytes.Buffer\n\tctx := &cmd.Context{\n\t\tDir:    req.Dir,\n\t\tStdin:  &stdin,\n\t\tStdout: &stdout,\n\t\tStderr: &stderr,\n\t}\n\tj.mu.Lock()\n\tdefer j.mu.Unlock()\n\tlogger.Infof(\"running hook tool %q %q\", req.CommandName, req.Args)\n\tlogger.Debugf(\"hook context id %q; dir %q\", req.ContextId, req.Dir)\n\tresp.Code = cmd.Main(c, ctx, req.Args)\n\tresp.Stdout = stdout.Bytes()\n\tresp.Stderr = stderr.Bytes()\n\treturn nil\n}\n\n\/\/ Server implements a server that serves command invocations via\n\/\/ a unix domain socket.\ntype Server struct {\n\tsocketPath string\n\tlistener   net.Listener\n\tserver     *rpc.Server\n\tclosed     chan bool\n\tclosing    chan bool\n\twg         sync.WaitGroup\n}\n\n\/\/ NewServer creates an RPC server bound to socketPath, which can execute\n\/\/ remote command invocations against an appropriate Context. It will not\n\/\/ actually do so until Run is called.\nfunc NewServer(getCmd CmdGetter, socketPath string) (*Server, error) {\n\tserver := rpc.NewServer()\n\tif err := server.Register(&Jujuc{getCmd: getCmd}); err != nil {\n\t\treturn nil, err\n\t}\n\tlistener, err := net.Listen(\"unix\", socketPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts := &Server{\n\t\tsocketPath: socketPath,\n\t\tlistener:   listener,\n\t\tserver:     server,\n\t\tclosed:     make(chan bool),\n\t\tclosing:    make(chan bool),\n\t}\n\treturn s, nil\n}\n\n\/\/ Run accepts new connections until it encounters an error, or until Close is\n\/\/ called, and then blocks until all existing connections have been closed.\nfunc (s *Server) Run() (err error) {\n\tvar conn net.Conn\n\tfor {\n\t\tconn, err = s.listener.Accept()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\ts.wg.Add(1)\n\t\tgo func(conn net.Conn) {\n\t\t\ts.server.ServeConn(conn)\n\t\t\ts.wg.Done()\n\t\t}(conn)\n\t}\n\tselect {\n\tcase <-s.closing:\n\t\t\/\/ Someone has called Close(), so it is overwhelmingly likely that\n\t\t\/\/ the error from Accept is a direct result of the Listener being\n\t\t\/\/ closed, and can therefore be safely ignored.\n\t\terr = nil\n\tdefault:\n\t}\n\ts.wg.Wait()\n\tclose(s.closed)\n\treturn\n}\n\n\/\/ Close immediately stops accepting connections, and blocks until all existing\n\/\/ connections have been closed.\nfunc (s *Server) Close() {\n\tclose(s.closing)\n\ts.listener.Close()\n\t<-s.closed\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>type names don't imply the resource mode<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix FSCK for VFS Swift layout v2 (#2527)<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Renamed SortWeightedData to SortWeighted<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>subs uses the interface Project<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>fixing byte array and binary string confusion.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage gcsproxy\n\nimport (\n\t\"time\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/lease\"\n\t\"github.com\/googlecloudplatform\/gcsfuse\/timeutil\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ A mutable view on some content. Created with an initial read-only view,\n\/\/ which then can be modified by the user and read back. Keeps track of which\n\/\/ portion of the content has been dirtied.\n\/\/\n\/\/ External synchronization is required.\ntype MutableContent struct {\n}\n\ntype StatResult struct {\n\t\/\/ The current size in bytes of the content.\n\tSize int64\n\n\t\/\/ It is guaranteed that all bytes in the range [0, DirtyThreshold) are\n\t\/\/ unmodified from the original content with which the mutable content object\n\t\/\/ was created.\n\tDirtyThreshold int64\n\n\t\/\/ The time at which the content was last updated, or nil if we've never\n\t\/\/ changed it.\n\tMtime *time.Time\n}\n\n\/\/ Create a mutable content object whose initial contents are given by the\n\/\/ supplied read proxy.\nfunc NewMutableContent(\n\tinitialContents lease.ReadProxy,\n\tclock timeutil.Clock) (mc *MutableContent)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Public interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Panic if any internal invariants are violated. Careful users can call this\n\/\/ at appropriate times to help debug weirdness. Consider using\n\/\/ syncutil.InvariantMutex to automate the process.\nfunc (mc *MutableContent) CheckInvariants()\n\n\/\/ Destroy any state used by the object, putting it into an indeterminate\n\/\/ state. The object must not be used again.\nfunc (mc *MutableContent) Destroy()\n\n\/\/ Read part of the content, with semantics equivalent to io.ReaderAt aside\n\/\/ from context support.\nfunc (mc *MutableContent) ReadAt(\n\tctx context.Context,\n\tbuf []byte,\n\toffset int64) (n int, err error)\n\n\/\/ Return information about the current state of the content.\nfunc (mc *MutableContent) Stat(ctx context.Context) (sr StatResult, err error)\n\n\/\/ Write into the content, with semantics equivalent to io.WriterAt aside from\n\/\/ context support.\nfunc (mc *MutableContent) WriteAt(\n\tctx context.Context,\n\tbuf []byte,\n\toffset int64) (n int, err error)\n\n\/\/ Truncate our the content to the given number of bytes, extending if n is\n\/\/ greater than the current size.\nfunc (mc *MutableContent) Truncate(\n\tctx context.Context,\n\tn int64) (err error)\n<commit_msg>Defined the contents of MutableContent.<commit_after>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage gcsproxy\n\nimport (\n\t\"time\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/lease\"\n\t\"github.com\/googlecloudplatform\/gcsfuse\/timeutil\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ A mutable view on some content. Created with an initial read-only view,\n\/\/ which then can be modified by the user and read back. Keeps track of which\n\/\/ portion of the content has been dirtied.\n\/\/\n\/\/ External synchronization is required.\ntype MutableContent struct {\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Dependencies\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tclock timeutil.Clock\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Mutable state\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tdestroyed bool\n\n\t\/\/ The initial contents with which this object was created, or nil if it has\n\t\/\/ been dirtied.\n\t\/\/\n\t\/\/ INVARIANT: When non-nil, initialContents.CheckInvariants() does not panic.\n\tinitialContents lease.ReadProxy\n\n\t\/\/ When dirty, a read\/write lease containing our current contents. When\n\t\/\/ clean, nil.\n\t\/\/\n\t\/\/ INVARIANT: (initialContents == nil) != (readWriteLease == nil)\n\treadWriteLease lease.ReadWriteLease\n\n\t\/\/ The time at which a method that modifies our contents was last called, or\n\t\/\/ nil if never.\n\t\/\/\n\t\/\/ INVARIANT: If dirty(), then mtime != nil\n\tmtime *time.Time\n}\n\ntype StatResult struct {\n\t\/\/ The current size in bytes of the content.\n\tSize int64\n\n\t\/\/ It is guaranteed that all bytes in the range [0, DirtyThreshold) are\n\t\/\/ unmodified from the original content with which the mutable content object\n\t\/\/ was created.\n\tDirtyThreshold int64\n\n\t\/\/ The time at which the content was last updated, or nil if we've never\n\t\/\/ changed it.\n\tMtime *time.Time\n}\n\n\/\/ Create a mutable content object whose initial contents are given by the\n\/\/ supplied read proxy.\nfunc NewMutableContent(\n\tinitialContents lease.ReadProxy,\n\tclock timeutil.Clock) (mc *MutableContent)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Public interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Panic if any internal invariants are violated. Careful users can call this\n\/\/ at appropriate times to help debug weirdness. Consider using\n\/\/ syncutil.InvariantMutex to automate the process.\nfunc (mc *MutableContent) CheckInvariants()\n\n\/\/ Destroy any state used by the object, putting it into an indeterminate\n\/\/ state. The object must not be used again.\nfunc (mc *MutableContent) Destroy()\n\n\/\/ Read part of the content, with semantics equivalent to io.ReaderAt aside\n\/\/ from context support.\nfunc (mc *MutableContent) ReadAt(\n\tctx context.Context,\n\tbuf []byte,\n\toffset int64) (n int, err error)\n\n\/\/ Return information about the current state of the content.\nfunc (mc *MutableContent) Stat(ctx context.Context) (sr StatResult, err error)\n\n\/\/ Write into the content, with semantics equivalent to io.WriterAt aside from\n\/\/ context support.\nfunc (mc *MutableContent) WriteAt(\n\tctx context.Context,\n\tbuf []byte,\n\toffset int64) (n int, err error)\n\n\/\/ Truncate our the content to the given number of bytes, extending if n is\n\/\/ greater than the current size.\nfunc (mc *MutableContent) Truncate(\n\tctx context.Context,\n\tn int64) (err error)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (mc *MutableContent) dirty() bool {\n\treturn mc.readWriteLease != nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package goose\n\nimport (\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/http\/cookiejar\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/PuerkitoBio\/goquery\"\n)\n\n\/\/ Crawler can fetch the target HTML page\ntype Crawler struct {\n\tconfig  Configuration\n\turl     string\n\tRawHTML string\n\tCharset string\n}\n\n\/\/ NewCrawler returns a crawler object initialised with the URL and the [optional] raw HTML body\nfunc NewCrawler(config Configuration, url string, RawHTML string) Crawler {\n\treturn Crawler{\n\t\tconfig:  config,\n\t\turl:     url,\n\t\tRawHTML: RawHTML,\n\t\tCharset: \"\",\n\t}\n}\n\nfunc getCharsetFromContentType(cs string) string {\n\tcs = strings.ToLower(strings.Replace(cs, \" \", \"\", -1))\n\tcs = strings.TrimPrefix(cs, \"text\/html;charset=\")\n\tcs = strings.TrimPrefix(cs, \"text\/xhtml;charset=\")\n\tcs = strings.TrimPrefix(cs, \"application\/xhtml+xml;charset=\")\n\treturn NormaliseCharset(cs)\n}\n\n\/\/ SetCharset can be used to force a charset (e.g. when read from the HTTP headers)\n\/\/ rather than relying on the detection from the HTML meta tags\nfunc (c *Crawler) SetCharset(cs string) {\n\tc.Charset = getCharsetFromContentType(cs)\n}\n\n\/\/ GetContentType returns the Content-Type string extracted from the meta tags\nfunc (c Crawler) GetContentType(document *goquery.Document) string {\n\tvar attr string\n\t\/\/ <meta http-equiv=\"Content-Type\" content=\"text\/html; charset=utf-8\" \/>\n\tdocument.Find(\"meta[http-equiv#=(?i)^Content\\\\-type$]\").Each(func(i int, s *goquery.Selection) {\n\t\tattr, _ = s.Attr(\"content\")\n\t})\n\treturn attr\n}\n\n\/\/ GetCharset returns a normalised charset string extracted from the meta tags\nfunc (c Crawler) GetCharset(document *goquery.Document) string {\n\t\/\/ manually-provided charset (from HTTP headers?) takes priority\n\tif \"\" != c.Charset {\n\t\treturn c.Charset\n\t}\n\n\t\/\/ <meta http-equiv=\"Content-Type\" content=\"text\/html; charset=utf-8\" \/>\n\tct := c.GetContentType(document)\n\tif \"\" != ct && strings.Contains(strings.ToLower(ct), \"charset\") {\n\t\treturn getCharsetFromContentType(ct)\n\t}\n\n\t\/\/ <meta charset=\"utf-8\">\n\tselection := document.Find(\"meta\").EachWithBreak(func(i int, s *goquery.Selection) bool {\n\t\t_, exists := s.Attr(\"charset\")\n\t\treturn !exists\n\t})\n\n\tif selection != nil {\n\t\tcs, _ := selection.Attr(\"charset\")\n\t\treturn NormaliseCharset(cs)\n\t}\n\n\treturn \"\"\n}\n\n\/\/ Preprocess fetches the HTML page if needed, converts it to UTF-8 and applies\n\/\/ some text normalisation to guarantee better results when extracting the content\nfunc (c *Crawler) Preprocess() (*goquery.Document, error) {\n\tif c.RawHTML == \"\" {\n\t\tc.RawHTML = c.fetchHTML(c.url, c.config.timeout)\n\t}\n\tif c.RawHTML == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tc.RawHTML = c.addSpacesBetweenTags(c.RawHTML)\n\n\treader := strings.NewReader(c.RawHTML)\n\tdocument, err := goquery.NewDocumentFromReader(reader)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcs := c.GetCharset(document)\n\t\/\/log.Println(\"-------------------------------------------CHARSET:\", cs)\n\tif \"\" != cs && \"UTF-8\" != cs {\n\t\t\/\/ the net\/html parser and goquery require UTF-8 data\n\t\tc.RawHTML = UTF8encode(c.RawHTML, cs)\n\t\treader = strings.NewReader(c.RawHTML)\n\t\tdocument, err = goquery.NewDocumentFromReader(reader)\n\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn document, nil\n}\n\n\/\/ Crawl fetches the HTML body and returns an Article\nfunc (c Crawler) Crawl() (*Article, error) {\n\tarticle := new(Article)\n\n\tdocument, err := c.Preprocess()\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\tif nil == document {\n\t\treturn article, nil\n\t}\n\n\textractor := NewExtractor(c.config)\n\n\tstartTime := time.Now().UnixNano()\n\n\tarticle.RawHTML, err = document.Html()\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\tarticle.FinalURL = c.url\n\tarticle.Doc = document\n\n\tarticle.Title = extractor.GetTitle(document)\n\tarticle.MetaLang = extractor.GetMetaLanguage(document)\n\tarticle.MetaFavicon = extractor.GetFavicon(document)\n\n\tarticle.MetaDescription = extractor.GetMetaContentWithSelector(document, \"meta[name#=(?i)^description$]\")\n\tarticle.MetaKeywords = extractor.GetMetaContentWithSelector(document, \"meta[name#=(?i)^keywords$]\")\n\tarticle.CanonicalLink = extractor.GetCanonicalLink(document)\n\tif \"\" == article.CanonicalLink {\n\t\tarticle.CanonicalLink = article.FinalURL\n\t}\n\tarticle.Domain = extractor.GetDomain(article.CanonicalLink)\n\tarticle.Tags = extractor.GetTags(document)\n\n\tcleaner := NewCleaner(c.config)\n\tarticle.Doc = cleaner.Clean(article.Doc)\n\n\tarticle.TopImage = OpenGraphResolver(document)\n\tif article.TopImage == \"\" {\n\t\tarticle.TopImage = WebPageResolver(article)\n\t}\n\n\tarticle.TopNode = extractor.CalculateBestNode(document)\n\tif article.TopNode != nil {\n\t\tarticle.TopNode = extractor.PostCleanup(article.TopNode)\n\n\t\tarticle.CleanedText, article.Links = extractor.GetCleanTextAndLinks(article.TopNode, article.MetaLang)\n\n\t\tvideoExtractor := NewVideoExtractor()\n\t\tarticle.Movies = videoExtractor.GetVideos(document)\n\t}\n\n\tarticle.Delta = time.Now().UnixNano() - startTime\n\n\treturn article, nil\n}\n\n\/\/ In many cases, like at the end of each <li> element or between <\/span><span> tags,\n\/\/ we need to add spaces, otherwise the text on either side will get joined together into one word.\n\/\/ This method also adds newlines after each <\/p> tag to preserve paragraphs.\nfunc (c Crawler) addSpacesBetweenTags(text string) string {\n\ttext = strings.Replace(text, \"><\", \"> <\", -1)\n\ttext = strings.Replace(text, \"<\/blockquote>\", \"<\/blockquote>\\n\", -1)\n\ttext = strings.Replace(text, \"<img \", \"\\n<img \", -1)\n\ttext = strings.Replace(text, \"<\/li>\", \"<\/li>\\n\", -1)\n\treturn strings.Replace(text, \"<\/p>\", \"<\/p>\\n\", -1)\n}\n\nfunc (c *Crawler) fetchHTML(u string, timeout time.Duration) string {\n\tcookieJar, _ := cookiejar.New(nil)\n\tclient := &http.Client{\n\t\tJar:     cookieJar,\n\t\tTimeout: timeout,\n\t}\n\treq, err := http.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn \"\"\n\t}\n\n\treq.Header.Set(\"User-Agent\", \"Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_6_7) AppleWebKit\/534.30 (KHTML, like Gecko) Chrome\/12.0.742.91 Safari\/534.30\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t\treturn \"\"\n\t}\n\tcontents, err := ioutil.ReadAll(resp.Body)\n\tif err == nil {\n\t\tc.RawHTML = string(contents)\n\t} else {\n\t\tlog.Println(err.Error())\n\t}\n\terr = resp.Body.Close()\n\tif err != nil {\n\t\tlog.Println(err.Error())\n\t}\n\n\treturn c.RawHTML\n}\n<commit_msg>Return crawl errors for handling by pkg consumer instead of logging and swallowing.<commit_after>package goose\n\nimport (\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/cookiejar\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/PuerkitoBio\/goquery\"\n)\n\n\/\/ Crawler can fetch the target HTML page\ntype Crawler struct {\n\tconfig  Configuration\n\turl     string\n\tRawHTML string\n\tCharset string\n}\n\n\/\/ NewCrawler returns a crawler object initialised with the URL and the [optional] raw HTML body\nfunc NewCrawler(config Configuration, url string, RawHTML string) Crawler {\n\treturn Crawler{\n\t\tconfig:  config,\n\t\turl:     url,\n\t\tRawHTML: RawHTML,\n\t\tCharset: \"\",\n\t}\n}\n\nfunc getCharsetFromContentType(cs string) string {\n\tcs = strings.ToLower(strings.Replace(cs, \" \", \"\", -1))\n\tcs = strings.TrimPrefix(cs, \"text\/html;charset=\")\n\tcs = strings.TrimPrefix(cs, \"text\/xhtml;charset=\")\n\tcs = strings.TrimPrefix(cs, \"application\/xhtml+xml;charset=\")\n\treturn NormaliseCharset(cs)\n}\n\n\/\/ SetCharset can be used to force a charset (e.g. when read from the HTTP headers)\n\/\/ rather than relying on the detection from the HTML meta tags\nfunc (c *Crawler) SetCharset(cs string) {\n\tc.Charset = getCharsetFromContentType(cs)\n}\n\n\/\/ GetContentType returns the Content-Type string extracted from the meta tags\nfunc (c Crawler) GetContentType(document *goquery.Document) string {\n\tvar attr string\n\t\/\/ <meta http-equiv=\"Content-Type\" content=\"text\/html; charset=utf-8\" \/>\n\tdocument.Find(\"meta[http-equiv#=(?i)^Content\\\\-type$]\").Each(func(i int, s *goquery.Selection) {\n\t\tattr, _ = s.Attr(\"content\")\n\t})\n\treturn attr\n}\n\n\/\/ GetCharset returns a normalised charset string extracted from the meta tags\nfunc (c Crawler) GetCharset(document *goquery.Document) string {\n\t\/\/ manually-provided charset (from HTTP headers?) takes priority\n\tif \"\" != c.Charset {\n\t\treturn c.Charset\n\t}\n\n\t\/\/ <meta http-equiv=\"Content-Type\" content=\"text\/html; charset=utf-8\" \/>\n\tct := c.GetContentType(document)\n\tif \"\" != ct && strings.Contains(strings.ToLower(ct), \"charset\") {\n\t\treturn getCharsetFromContentType(ct)\n\t}\n\n\t\/\/ <meta charset=\"utf-8\">\n\tselection := document.Find(\"meta\").EachWithBreak(func(i int, s *goquery.Selection) bool {\n\t\t_, exists := s.Attr(\"charset\")\n\t\treturn !exists\n\t})\n\n\tif selection != nil {\n\t\tcs, _ := selection.Attr(\"charset\")\n\t\treturn NormaliseCharset(cs)\n\t}\n\n\treturn \"\"\n}\n\n\/\/ Preprocess fetches the HTML page if needed, converts it to UTF-8 and applies\n\/\/ some text normalisation to guarantee better results when extracting the content\nfunc (c *Crawler) Preprocess() (*goquery.Document, error) {\n\tvar err error\n\n\tif c.RawHTML == \"\" {\n\t\tif c.RawHTML, err = c.fetchHTML(c.url, c.config.timeout); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif c.RawHTML == \"\" {\n\t\treturn nil, errors.New(\"cannot process empty HTML content\")\n\t}\n\n\tc.RawHTML = c.addSpacesBetweenTags(c.RawHTML)\n\n\treader := strings.NewReader(c.RawHTML)\n\tdocument, err := goquery.NewDocumentFromReader(reader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcs := c.GetCharset(document)\n\t\/\/log.Println(\"-------------------------------------------CHARSET:\", cs)\n\tif \"\" != cs && \"UTF-8\" != cs {\n\t\t\/\/ the net\/html parser and goquery require UTF-8 data\n\t\tc.RawHTML = UTF8encode(c.RawHTML, cs)\n\t\treader = strings.NewReader(c.RawHTML)\n\t\tif document, err = goquery.NewDocumentFromReader(reader); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn document, nil\n}\n\n\/\/ Crawl fetches the HTML body and returns an Article\nfunc (c Crawler) Crawl() (*Article, error) {\n\tarticle := new(Article)\n\n\tdocument, err := c.Preprocess()\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\tif nil == document {\n\t\treturn article, nil\n\t}\n\n\textractor := NewExtractor(c.config)\n\n\tstartTime := time.Now().UnixNano()\n\n\tarticle.RawHTML, err = document.Html()\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\tarticle.FinalURL = c.url\n\tarticle.Doc = document\n\n\tarticle.Title = extractor.GetTitle(document)\n\tarticle.MetaLang = extractor.GetMetaLanguage(document)\n\tarticle.MetaFavicon = extractor.GetFavicon(document)\n\n\tarticle.MetaDescription = extractor.GetMetaContentWithSelector(document, \"meta[name#=(?i)^description$]\")\n\tarticle.MetaKeywords = extractor.GetMetaContentWithSelector(document, \"meta[name#=(?i)^keywords$]\")\n\tarticle.CanonicalLink = extractor.GetCanonicalLink(document)\n\tif \"\" == article.CanonicalLink {\n\t\tarticle.CanonicalLink = article.FinalURL\n\t}\n\tarticle.Domain = extractor.GetDomain(article.CanonicalLink)\n\tarticle.Tags = extractor.GetTags(document)\n\n\tcleaner := NewCleaner(c.config)\n\tarticle.Doc = cleaner.Clean(article.Doc)\n\n\tarticle.TopImage = OpenGraphResolver(document)\n\tif article.TopImage == \"\" {\n\t\tarticle.TopImage = WebPageResolver(article)\n\t}\n\n\tarticle.TopNode = extractor.CalculateBestNode(document)\n\tif article.TopNode != nil {\n\t\tarticle.TopNode = extractor.PostCleanup(article.TopNode)\n\n\t\tarticle.CleanedText, article.Links = extractor.GetCleanTextAndLinks(article.TopNode, article.MetaLang)\n\n\t\tvideoExtractor := NewVideoExtractor()\n\t\tarticle.Movies = videoExtractor.GetVideos(document)\n\t}\n\n\tarticle.Delta = time.Now().UnixNano() - startTime\n\n\treturn article, nil\n}\n\n\/\/ In many cases, like at the end of each <li> element or between <\/span><span> tags,\n\/\/ we need to add spaces, otherwise the text on either side will get joined together into one word.\n\/\/ This method also adds newlines after each <\/p> tag to preserve paragraphs.\nfunc (c Crawler) addSpacesBetweenTags(text string) string {\n\ttext = strings.Replace(text, \"><\", \"> <\", -1)\n\ttext = strings.Replace(text, \"<\/blockquote>\", \"<\/blockquote>\\n\", -1)\n\ttext = strings.Replace(text, \"<img \", \"\\n<img \", -1)\n\ttext = strings.Replace(text, \"<\/li>\", \"<\/li>\\n\", -1)\n\treturn strings.Replace(text, \"<\/p>\", \"<\/p>\\n\", -1)\n}\n\nfunc (c *Crawler) fetchHTML(u string, timeout time.Duration) (string, error) {\n\tcookieJar, err := cookiejar.New(nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tclient := &http.Client{\n\t\tJar:     cookieJar,\n\t\tTimeout: timeout,\n\t}\n\n\treq, err := http.NewRequest(\"GET\", u, nil)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Header.Set(\"User-Agent\", \"Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_6_7) AppleWebKit\/534.30 (KHTML, like Gecko) Chrome\/12.0.742.91 Safari\/534.30\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tcontents, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tc.RawHTML = string(contents)\n\n\tif err = resp.Body.Close(); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn c.RawHTML, nil\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Throw a fatal error if can not connect to the database on startup<commit_after><|endoftext|>"}
{"text":"<commit_before>package add_tests\n\nimport (\n\t\"github.com\/BytemarkHosting\/bytemark-client\/lib\"\n\t\"github.com\/BytemarkHosting\/bytemark-client\/lib\/brain\"\n)\n\nvar DefVM = lib.VirtualMachineName{Group: \"default\", Account: \"default-account\"}\nvar DefGroup = lib.GroupName{Group: \"default\", Account: \"default-account\"}\n<commit_msg>remove s from test<commit_after>package add_test\n\nimport (\n\t\"github.com\/BytemarkHosting\/bytemark-client\/lib\"\n\t\"github.com\/BytemarkHosting\/bytemark-client\/lib\/brain\"\n)\n\nvar DefVM = lib.VirtualMachineName{Group: \"default\", Account: \"default-account\"}\nvar DefGroup = lib.GroupName{Group: \"default\", Account: \"default-account\"}\n<|endoftext|>"}
{"text":"<commit_before>package kateway\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/funkygao\/gafka\/cmd\/kguard\/monitor\"\n\t\"github.com\/funkygao\/gafka\/zk\"\n\tlog \"github.com\/funkygao\/log4go\"\n\t\"github.com\/rcrowley\/go-metrics\"\n)\n\nfunc init() {\n\tmonitor.RegisterWatcher(\"kateway.sublag\", func() monitor.Watcher {\n\t\treturn &WatchSubLag{\n\t\t\tTick: time.Minute,\n\t\t}\n\t})\n}\n\n\/\/ SubLag monitors aliveness of kateway cluster.\ntype WatchSubLag struct {\n\tZkzone *zk.ZkZone\n\tStop   <-chan struct{}\n\tTick   time.Duration\n\tWg     *sync.WaitGroup\n\n\tzkcluster *zk.ZkCluster\n\n\tsuspects map[string]struct{}\n}\n\nfunc (this *WatchSubLag) Init(ctx monitor.Context) {\n\tthis.Zkzone = ctx.ZkZone()\n\tthis.Stop = ctx.StopChan()\n\tthis.Wg = ctx.WaitGroup()\n\tthis.suspects = make(map[string]struct{})\n}\n\nfunc (this *WatchSubLag) Run() {\n\tdefer this.Wg.Done()\n\n\tthis.zkcluster = this.Zkzone.NewCluster(\"bigtopic\") \/\/ TODO\n\n\tticker := time.NewTicker(this.Tick)\n\tdefer ticker.Stop()\n\n\tsubLagGroups := metrics.NewRegisteredGauge(\"sub.lags\", nil)\n\tfor {\n\t\tselect {\n\t\tcase <-this.Stop:\n\t\t\tlog.Info(\"kateway.sublag stopped\")\n\t\t\treturn\n\n\t\tcase <-ticker.C:\n\t\t\tsubLagGroups.Update(int64(this.report()))\n\n\t\t}\n\t}\n}\n\nfunc (this *WatchSubLag) isSuspect(group string, topic string) bool {\n\tif _, present := this.suspects[group+\"|\"+topic]; present {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (this *WatchSubLag) suspect(group, topic string) {\n\tthis.suspects[group+\"|\"+topic] = struct{}{}\n}\n\nfunc (this *WatchSubLag) unsuspect(group string, topic string) {\n\tdelete(this.suspects, group+\"|\"+topic)\n}\n\nfunc (this *WatchSubLag) report() (lags int) {\n\tfor group, consumers := range this.zkcluster.ConsumersByGroup(\"\") {\n\t\tfor _, c := range consumers {\n\t\t\tif !c.Online {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif c.ConsumerZnode == nil {\n\t\t\t\tlog.Warn(\"group[%s] topic[%s\/%s] unrecognized consumer\", group, c.Topic, c.PartitionId)\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif time.Since(c.ConsumerZnode.Uptime()) < time.Minute*2 {\n\t\t\t\tlog.Info(\"group[%s] just started, topic[%s\/%s]\", group, c.Topic, c.PartitionId)\n\n\t\t\t\tthis.unsuspect(group, c.Topic)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ offset commit every 1m, sublag runs every 1m, so the gap might be 2m\n\t\t\t\/\/ TODO lag too much, even if it's still alive, emit alarm\n\t\t\telapsed := time.Since(c.Mtime.Time())\n\t\t\tif c.Lag == 0 || elapsed < time.Minute*3 {\n\t\t\t\tthis.unsuspect(group, c.Topic)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ it might be lagging, but need confirm with last round\n\t\t\tif !this.isSuspect(group, c.Topic) {\n\t\t\t\t\/\/ suspect it, next round if it is still lagging, put on trial\n\t\t\t\tthis.suspect(group, c.Topic)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ bingo! it IS lagging\n\t\t\tlog.Warn(\"group[%s] topic[%s\/%s] %d - %d = %d, offset commit elapsed: %s\",\n\t\t\t\tgroup, c.Topic, c.PartitionId, c.ProducerOffset, c.ConsumerOffset, c.Lag, elapsed.String())\n\n\t\t\tlags++\n\t\t}\n\t}\n\n\treturn\n}\n<commit_msg>log the suspect<commit_after>package kateway\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/funkygao\/gafka\/cmd\/kguard\/monitor\"\n\t\"github.com\/funkygao\/gafka\/zk\"\n\tlog \"github.com\/funkygao\/log4go\"\n\t\"github.com\/rcrowley\/go-metrics\"\n)\n\nfunc init() {\n\tmonitor.RegisterWatcher(\"kateway.sublag\", func() monitor.Watcher {\n\t\treturn &WatchSubLag{\n\t\t\tTick: time.Minute,\n\t\t}\n\t})\n}\n\n\/\/ SubLag monitors aliveness of kateway cluster.\ntype WatchSubLag struct {\n\tZkzone *zk.ZkZone\n\tStop   <-chan struct{}\n\tTick   time.Duration\n\tWg     *sync.WaitGroup\n\n\tzkcluster *zk.ZkCluster\n\n\tsuspects map[string]struct{}\n}\n\nfunc (this *WatchSubLag) Init(ctx monitor.Context) {\n\tthis.Zkzone = ctx.ZkZone()\n\tthis.Stop = ctx.StopChan()\n\tthis.Wg = ctx.WaitGroup()\n\tthis.suspects = make(map[string]struct{})\n}\n\nfunc (this *WatchSubLag) Run() {\n\tdefer this.Wg.Done()\n\n\tthis.zkcluster = this.Zkzone.NewCluster(\"bigtopic\") \/\/ TODO\n\n\tticker := time.NewTicker(this.Tick)\n\tdefer ticker.Stop()\n\n\tsubLagGroups := metrics.NewRegisteredGauge(\"sub.lags\", nil)\n\tfor {\n\t\tselect {\n\t\tcase <-this.Stop:\n\t\t\tlog.Info(\"kateway.sublag stopped\")\n\t\t\treturn\n\n\t\tcase <-ticker.C:\n\t\t\tsubLagGroups.Update(int64(this.report()))\n\n\t\t}\n\t}\n}\n\nfunc (this *WatchSubLag) isSuspect(group string, topic string) bool {\n\tif _, present := this.suspects[group+\"|\"+topic]; present {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (this *WatchSubLag) suspect(group, topic string) {\n\tthis.suspects[group+\"|\"+topic] = struct{}{}\n}\n\nfunc (this *WatchSubLag) unsuspect(group string, topic string) {\n\tdelete(this.suspects, group+\"|\"+topic)\n}\n\nfunc (this *WatchSubLag) report() (lags int) {\n\tfor group, consumers := range this.zkcluster.ConsumersByGroup(\"\") {\n\t\tfor _, c := range consumers {\n\t\t\tif !c.Online {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif c.ConsumerZnode == nil {\n\t\t\t\tlog.Warn(\"group[%s] topic[%s\/%s] unrecognized consumer\", group, c.Topic, c.PartitionId)\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif time.Since(c.ConsumerZnode.Uptime()) < time.Minute*2 {\n\t\t\t\tlog.Info(\"group[%s] just started, topic[%s\/%s]\", group, c.Topic, c.PartitionId)\n\n\t\t\t\tthis.unsuspect(group, c.Topic)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ offset commit every 1m, sublag runs every 1m, so the gap might be 2m\n\t\t\t\/\/ TODO lag too much, even if it's still alive, emit alarm\n\t\t\telapsed := time.Since(c.Mtime.Time())\n\t\t\tif c.Lag == 0 || elapsed < time.Minute*3 {\n\t\t\t\tthis.unsuspect(group, c.Topic)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ it might be lagging, but need confirm with last round\n\t\t\tif !this.isSuspect(group, c.Topic) {\n\t\t\t\t\/\/ suspect it, next round if it is still lagging, put on trial\n\t\t\t\tlog.Warn(\"group[%s] suspected topic[%s\/%s] %d - %d = %d, offset commit elapsed: %s\",\n\t\t\t\t\tgroup, c.Topic, c.PartitionId, c.ProducerOffset, c.ConsumerOffset, c.Lag, elapsed.String())\n\n\t\t\t\tthis.suspect(group, c.Topic)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ bingo! it IS lagging\n\t\t\tlog.Warn(\"group[%s] confirmed topic[%s\/%s] %d - %d = %d, offset commit elapsed: %s\",\n\t\t\t\tgroup, c.Topic, c.PartitionId, c.ProducerOffset, c.ConsumerOffset, c.Lag, elapsed.String())\n\n\t\t\tlags++\n\t\t}\n\t}\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package actor\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/emirpasic\/gods\/stacks\/linkedliststack\"\n)\n\ntype messageSender struct {\n\tMessage interface{}\n\tSender  *PID\n}\n\ntype localContext struct {\n\tmessage        interface{}\n\tparent         *PID\n\tself           *PID\n\tactor          Actor\n\tsupervisor     SupervisorStrategy\n\tproducer       Producer\n\tmiddleware     ReceiveFunc\n\tbehavior       behaviorStack\n\treceive        ReceiveFunc\n\tchildren       PIDSet\n\twatchers       PIDSet\n\twatching       PIDSet\n\tstash          *linkedliststack.Stack\n\tstopping       bool\n\trestarting     bool\n\treceiveTimeout time.Duration\n\tt              *time.Timer\n\trestartStats   *ChildRestartStats\n}\n\nfunc newLocalContext(producer Producer, supervisor SupervisorStrategy, middleware ReceiveFunc, parent *PID) *localContext {\n\tcell := &localContext{\n\t\tparent:     parent,\n\t\tproducer:   producer,\n\t\tsupervisor: supervisor,\n\t\tmiddleware: middleware,\n\t}\n\tcell.incarnateActor()\n\treturn cell\n}\n\nfunc (ctx *localContext) Actor() Actor {\n\treturn ctx.actor\n}\n\nfunc (ctx *localContext) Message() interface{} {\n\tuserMessage, ok := ctx.message.(*messageSender)\n\tif ok {\n\t\treturn userMessage.Message\n\t}\n\treturn ctx.message\n}\n\nfunc (ctx *localContext) Sender() *PID {\n\tuserMessage, ok := ctx.message.(*messageSender)\n\tif ok {\n\t\treturn userMessage.Sender\n\t}\n\treturn nil\n}\n\nfunc (ctx *localContext) Stash() {\n\tif ctx.stash == nil {\n\t\tctx.stash = linkedliststack.New()\n\t}\n\n\tctx.stash.Push(ctx.message)\n}\n\nfunc (ctx *localContext) cancelTimer() {\n\tif ctx.t != nil {\n\t\tctx.t.Stop()\n\t\tctx.t = nil\n\t}\n}\n\nfunc (ctx *localContext) receiveTimeoutHandler() {\n\tctx.self.Request(receiveTimeoutMessage, nil)\n}\n\nfunc (ctx *localContext) SetReceiveTimeout(d time.Duration) {\n\tif d == ctx.receiveTimeout {\n\t\treturn\n\t}\n\tif ctx.t != nil {\n\t\tctx.t.Stop()\n\t}\n\n\tif d < time.Millisecond {\n\t\t\/\/ anything less than than 1 millisecond is set to zero\n\t\td = 0\n\t}\n\n\tctx.receiveTimeout = d\n\tif d > 0 {\n\t\tif ctx.t == nil {\n\t\t\tctx.t = time.AfterFunc(d, ctx.receiveTimeoutHandler)\n\t\t} else {\n\t\t\tctx.t.Reset(d)\n\t\t}\n\t}\n}\n\nfunc (ctx *localContext) ReceiveTimeout() time.Duration {\n\treturn ctx.receiveTimeout\n}\n\nfunc (ctx *localContext) Children() []*PID {\n\tr := make([]*PID, ctx.children.Len())\n\tctx.children.ForEach(func(i int, p PID) {\n\t\tr[i] = &p\n\t})\n\treturn r\n}\n\nfunc (ctx *localContext) Self() *PID {\n\treturn ctx.self\n}\n\nfunc (ctx *localContext) Parent() *PID {\n\treturn ctx.parent\n}\n\nfunc (ctx *localContext) Receive(message interface{}) {\n\tctx.processMessage(message)\n}\n\n\/\/ localContextReceiver is used when middleware chain is required\nfunc localContextReceiver(ctx Context) {\n\ta := ctx.(*localContext)\n\tif _, ok := a.message.(*PoisonPill); ok {\n\t\ta.self.Stop()\n\t} else {\n\t\ta.receive(ctx)\n\t}\n}\n\nfunc (ctx *localContext) processMessage(m interface{}) {\n\tctx.message = m\n\n\tif ctx.middleware != nil {\n\t\tctx.middleware(ctx)\n\t} else {\n\t\tif _, ok := m.(*PoisonPill); ok {\n\t\t\tctx.self.Stop()\n\t\t} else {\n\t\t\tctx.receive(ctx)\n\t\t}\n\t}\n}\n\nfunc (ctx *localContext) incarnateActor() {\n\tactor := ctx.producer()\n\tctx.restarting = false\n\tctx.stopping = false\n\tctx.actor = actor\n\tctx.receive = actor.Receive\n}\n\nfunc (ctx *localContext) InvokeSystemMessage(message SystemMessage) {\n\tswitch msg := message.(interface{}).(type) {\n\tcase *Started:\n\t\tctx.InvokeUserMessage(msg) \/\/ forward\n\tcase *Watch:\n\t\tctx.watchers.Add(msg.Watcher)\n\tcase *Unwatch:\n\t\tctx.watchers.Remove(msg.Watcher)\n\tcase *SuspendMailbox, *ResumeMailbox:\n\t\/\/pass\n\tcase *Stop:\n\t\tctx.handleStop(msg)\n\tcase *Terminated:\n\t\tctx.handleTerminated(msg)\n\tcase *Failure:\n\t\tctx.handleFailure(msg)\n\tcase *Restart:\n\t\tctx.handleRestart(msg)\n\tdefault:\n\t\tlog.Printf(\"Unknown system message %T\", msg)\n\t}\n}\n\nfunc (ctx *localContext) handleRestart(msg *Restart) {\n\tctx.stopping = false\n\tctx.restarting = true\n\tctx.InvokeUserMessage(restartingMessage)\n\tctx.children.ForEach(func(_ int, pid PID) {\n\t\tpid.Stop()\n\t})\n\tctx.tryRestartOrTerminate()\n}\n\n\/\/I am stopping\nfunc (ctx *localContext) handleStop(msg *Stop) {\n\tctx.stopping = true\n\tctx.restarting = false\n\n\tctx.InvokeUserMessage(stoppingMessage)\n\tctx.children.ForEach(func(_ int, pid PID) {\n\t\tpid.Stop()\n\t})\n\tctx.tryRestartOrTerminate()\n}\n\n\/\/child stopped, check if we can stop or restart (if needed)\nfunc (ctx *localContext) handleTerminated(msg *Terminated) {\n\tctx.children.Remove(msg.Who)\n\tctx.watching.Remove(msg.Who)\n\n\tctx.InvokeUserMessage(msg)\n\tctx.tryRestartOrTerminate()\n}\n\n\/\/offload the supervision completely to the supervisor strategy\nfunc (ctx *localContext) handleFailure(msg *Failure) {\n\tif strategy, ok := ctx.actor.(SupervisorStrategy); ok {\n\t\tstrategy.HandleFailure(ctx, msg.Who, msg.ChildStats, msg.Reason)\n\t\treturn\n\t}\n\tctx.supervisor.HandleFailure(ctx, msg.Who, msg.ChildStats, msg.Reason)\n}\n\nfunc (ctx *localContext) EscalateFailure(who *PID, reason interface{}) {\n\tif ctx.Parent() == nil {\n\t\tlog.Printf(\"[ACTOR] '%v' Cannot escalate failure from root actor; stopping instead\", ctx.debugString())\n\t\tctx.Self().sendSystemMessage(stopMessage)\n\t\treturn\n\t}\n\t\/\/suspend self\n\tctx.Self().sendSystemMessage(suspendMailboxMessage)\n\t\/\/send failure to parent\n\tctx.Parent().sendSystemMessage(&Failure{Reason: reason, Who: who})\n}\n\nfunc (ctx *localContext) tryRestartOrTerminate() {\n\tif ctx.t != nil {\n\t\tctx.t.Stop()\n\t\tctx.t = nil\n\t\tctx.receiveTimeout = 0\n\t}\n\n\tif !ctx.children.Empty() {\n\t\treturn\n\t}\n\n\tif ctx.restarting {\n\t\tctx.restart()\n\t\treturn\n\t}\n\n\tif ctx.stopping {\n\t\tctx.stopped()\n\t}\n}\n\nfunc (ctx *localContext) restart() {\n\tctx.incarnateActor()\n\t\/\/create a new childRestartStats with the current failure settings\n\tctx.restartStats = &ChildRestartStats{\n\t\tFailureCount:    ctx.restartStats.FailureCount + 1,\n\t\tLastFailureTime: time.Now(),\n\t}\n\tctx.InvokeUserMessage(startedMessage)\n\tif ctx.stash != nil {\n\t\tfor !ctx.stash.Empty() {\n\t\t\tmsg, _ := ctx.stash.Pop()\n\t\t\tctx.InvokeUserMessage(msg)\n\t\t}\n\t}\n\tctx.self.sendSystemMessage(resumeMailboxMessage)\n}\n\nfunc (ctx *localContext) stopped() {\n\tProcessRegistry.Remove(ctx.self)\n\tctx.InvokeUserMessage(stoppedMessage)\n\totherStopped := &Terminated{Who: ctx.self}\n\tctx.watchers.ForEach(func(i int, pid PID) {\n\t\tpid.sendSystemMessage(otherStopped)\n\t})\n}\n\nfunc identifyPanic() string {\n\tvar name, file string\n\tvar line int\n\tvar pc [16]uintptr\n\n\tn := runtime.Callers(3, pc[:])\n\tfor _, pc := range pc[:n] {\n\t\tlog.Printf(\"%d\", pc)\n\t\tfn := runtime.FuncForPC(pc)\n\t\tif fn == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfile, line = fn.FileLine(pc)\n\t\tfmt.Printf(file, line, pc)\n\t\tname = fn.Name()\n\t\tif !strings.HasPrefix(name, \"runtime.\") {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tswitch {\n\tcase name != \"\":\n\t\treturn fmt.Sprintf(\"%v:%v\", name, line)\n\tcase file != \"\":\n\t\treturn fmt.Sprintf(\"%v:%v\", file, line)\n\t}\n\n\treturn fmt.Sprintf(\"pc:%x\", pc)\n}\n\nfunc (ctx *localContext) InvokeUserMessage(md interface{}) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Printf(\"[ACTOR] '%v' Recovering from: %v. Detailed stack: %v\", ctx.debugString(), r, identifyPanic())\n\n\t\t\t\/\/lazy initialize the child restart stats if this is the first time\n\t\t\t\/\/further mutations are handled within \"restart\"\n\t\t\tif ctx.restartStats == nil {\n\t\t\t\tctx.restartStats = &ChildRestartStats{\n\t\t\t\t\tFailureCount: 1,\n\t\t\t\t}\n\t\t\t}\n\t\t\tfailure := &Failure{Reason: r, Who: ctx.self, ChildStats: ctx.restartStats}\n\t\t\tif ctx.parent == nil {\n\t\t\t\thandleRootFailure(failure)\n\t\t\t} else {\n\t\t\t\t\/\/TODO: Akka recursively suspends all children also on failure\n\t\t\t\t\/\/Not sure if I think this is the right way to go, why do children need to wait for their parents failed state to recover?\n\t\t\t\tctx.self.sendSystemMessage(suspendMailboxMessage)\n\t\t\t\tctx.parent.sendSystemMessage(failure)\n\t\t\t}\n\t\t}\n\t}()\n\n\tif md == nil {\n\t\tlog.Printf(\"[ACTOR] '%v' got nil message\", ctx.Self().String())\n\t\treturn\n\t}\n\n\tinfluenceTimeout := true\n\tif ctx.receiveTimeout > 0 {\n\t\t_, influenceTimeout = md.(NotInfluenceReceiveTimeout)\n\t\tinfluenceTimeout = !influenceTimeout\n\t\tif influenceTimeout {\n\t\t\tctx.t.Stop()\n\t\t}\n\t}\n\n\tctx.processMessage(md)\n\n\tif ctx.receiveTimeout > 0 && influenceTimeout {\n\t\tctx.t.Reset(ctx.receiveTimeout)\n\t}\n}\n\nfunc (ctx *localContext) Become(behavior ReceiveFunc) {\n\tctx.behavior.Clear()\n\tctx.receive = behavior\n}\n\nfunc (ctx *localContext) BecomeStacked(behavior ReceiveFunc) {\n\tctx.behavior.Push(ctx.receive)\n\tctx.receive = behavior\n}\n\nfunc (ctx *localContext) UnbecomeStacked() {\n\tif ctx.behavior.Len() == 0 {\n\t\tpanic(\"Cannot unbecome actor base behavior\")\n\t}\n\tctx.receive, _ = ctx.behavior.Pop()\n}\n\nfunc (ctx *localContext) Watch(who *PID) {\n\twho.sendSystemMessage(&Watch{\n\t\tWatcher: ctx.self,\n\t})\n\tctx.watching.Add(who)\n}\n\nfunc (ctx *localContext) Unwatch(who *PID) {\n\twho.sendSystemMessage(&Unwatch{\n\t\tWatcher: ctx.self,\n\t})\n\tctx.watching.Remove(who)\n}\n\nfunc (ctx *localContext) Respond(response interface{}) {\n\tif ctx.Sender() == nil {\n\t\tlog.Fatal(\"[ACTOR] No sender\")\n\t}\n\tctx.Sender().Tell(response)\n}\n\nfunc (ctx *localContext) Spawn(props Props) *PID {\n\treturn ctx.SpawnNamed(props, ProcessRegistry.NextId())\n}\n\nfunc (ctx *localContext) SpawnNamed(props Props, name string) *PID {\n\tpid := props.spawn(ctx.self.Id+\"\/\"+name, ctx.self)\n\tctx.children.Add(pid)\n\tctx.Watch(pid)\n\treturn pid\n}\n\nfunc (ctx *localContext) debugString() string {\n\treturn fmt.Sprintf(\"%v\/%v:%v\", ctx.self.Address, ctx.self.Id, reflect.TypeOf(ctx.actor))\n}\n\nfunc handleRootFailure(msg *Failure) {\n\tdefaultSupervisionStrategy.HandleFailure(nil, msg.Who, msg.ChildStats, msg.Reason)\n}\n<commit_msg>identifypanic fix<commit_after>package actor\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/emirpasic\/gods\/stacks\/linkedliststack\"\n)\n\ntype messageSender struct {\n\tMessage interface{}\n\tSender  *PID\n}\n\ntype localContext struct {\n\tmessage        interface{}\n\tparent         *PID\n\tself           *PID\n\tactor          Actor\n\tsupervisor     SupervisorStrategy\n\tproducer       Producer\n\tmiddleware     ReceiveFunc\n\tbehavior       behaviorStack\n\treceive        ReceiveFunc\n\tchildren       PIDSet\n\twatchers       PIDSet\n\twatching       PIDSet\n\tstash          *linkedliststack.Stack\n\tstopping       bool\n\trestarting     bool\n\treceiveTimeout time.Duration\n\tt              *time.Timer\n\trestartStats   *ChildRestartStats\n}\n\nfunc newLocalContext(producer Producer, supervisor SupervisorStrategy, middleware ReceiveFunc, parent *PID) *localContext {\n\tcell := &localContext{\n\t\tparent:     parent,\n\t\tproducer:   producer,\n\t\tsupervisor: supervisor,\n\t\tmiddleware: middleware,\n\t}\n\tcell.incarnateActor()\n\treturn cell\n}\n\nfunc (ctx *localContext) Actor() Actor {\n\treturn ctx.actor\n}\n\nfunc (ctx *localContext) Message() interface{} {\n\tuserMessage, ok := ctx.message.(*messageSender)\n\tif ok {\n\t\treturn userMessage.Message\n\t}\n\treturn ctx.message\n}\n\nfunc (ctx *localContext) Sender() *PID {\n\tuserMessage, ok := ctx.message.(*messageSender)\n\tif ok {\n\t\treturn userMessage.Sender\n\t}\n\treturn nil\n}\n\nfunc (ctx *localContext) Stash() {\n\tif ctx.stash == nil {\n\t\tctx.stash = linkedliststack.New()\n\t}\n\n\tctx.stash.Push(ctx.message)\n}\n\nfunc (ctx *localContext) cancelTimer() {\n\tif ctx.t != nil {\n\t\tctx.t.Stop()\n\t\tctx.t = nil\n\t}\n}\n\nfunc (ctx *localContext) receiveTimeoutHandler() {\n\tctx.self.Request(receiveTimeoutMessage, nil)\n}\n\nfunc (ctx *localContext) SetReceiveTimeout(d time.Duration) {\n\tif d == ctx.receiveTimeout {\n\t\treturn\n\t}\n\tif ctx.t != nil {\n\t\tctx.t.Stop()\n\t}\n\n\tif d < time.Millisecond {\n\t\t\/\/ anything less than than 1 millisecond is set to zero\n\t\td = 0\n\t}\n\n\tctx.receiveTimeout = d\n\tif d > 0 {\n\t\tif ctx.t == nil {\n\t\t\tctx.t = time.AfterFunc(d, ctx.receiveTimeoutHandler)\n\t\t} else {\n\t\t\tctx.t.Reset(d)\n\t\t}\n\t}\n}\n\nfunc (ctx *localContext) ReceiveTimeout() time.Duration {\n\treturn ctx.receiveTimeout\n}\n\nfunc (ctx *localContext) Children() []*PID {\n\tr := make([]*PID, ctx.children.Len())\n\tctx.children.ForEach(func(i int, p PID) {\n\t\tr[i] = &p\n\t})\n\treturn r\n}\n\nfunc (ctx *localContext) Self() *PID {\n\treturn ctx.self\n}\n\nfunc (ctx *localContext) Parent() *PID {\n\treturn ctx.parent\n}\n\nfunc (ctx *localContext) Receive(message interface{}) {\n\tctx.processMessage(message)\n}\n\n\/\/ localContextReceiver is used when middleware chain is required\nfunc localContextReceiver(ctx Context) {\n\ta := ctx.(*localContext)\n\tif _, ok := a.message.(*PoisonPill); ok {\n\t\ta.self.Stop()\n\t} else {\n\t\ta.receive(ctx)\n\t}\n}\n\nfunc (ctx *localContext) processMessage(m interface{}) {\n\tctx.message = m\n\n\tif ctx.middleware != nil {\n\t\tctx.middleware(ctx)\n\t} else {\n\t\tif _, ok := m.(*PoisonPill); ok {\n\t\t\tctx.self.Stop()\n\t\t} else {\n\t\t\tctx.receive(ctx)\n\t\t}\n\t}\n}\n\nfunc (ctx *localContext) incarnateActor() {\n\tactor := ctx.producer()\n\tctx.restarting = false\n\tctx.stopping = false\n\tctx.actor = actor\n\tctx.receive = actor.Receive\n}\n\nfunc (ctx *localContext) InvokeSystemMessage(message SystemMessage) {\n\tswitch msg := message.(interface{}).(type) {\n\tcase *Started:\n\t\tctx.InvokeUserMessage(msg) \/\/ forward\n\tcase *Watch:\n\t\tctx.watchers.Add(msg.Watcher)\n\tcase *Unwatch:\n\t\tctx.watchers.Remove(msg.Watcher)\n\tcase *SuspendMailbox, *ResumeMailbox:\n\t\/\/pass\n\tcase *Stop:\n\t\tctx.handleStop(msg)\n\tcase *Terminated:\n\t\tctx.handleTerminated(msg)\n\tcase *Failure:\n\t\tctx.handleFailure(msg)\n\tcase *Restart:\n\t\tctx.handleRestart(msg)\n\tdefault:\n\t\tlog.Printf(\"Unknown system message %T\", msg)\n\t}\n}\n\nfunc (ctx *localContext) handleRestart(msg *Restart) {\n\tctx.stopping = false\n\tctx.restarting = true\n\tctx.InvokeUserMessage(restartingMessage)\n\tctx.children.ForEach(func(_ int, pid PID) {\n\t\tpid.Stop()\n\t})\n\tctx.tryRestartOrTerminate()\n}\n\n\/\/I am stopping\nfunc (ctx *localContext) handleStop(msg *Stop) {\n\tctx.stopping = true\n\tctx.restarting = false\n\n\tctx.InvokeUserMessage(stoppingMessage)\n\tctx.children.ForEach(func(_ int, pid PID) {\n\t\tpid.Stop()\n\t})\n\tctx.tryRestartOrTerminate()\n}\n\n\/\/child stopped, check if we can stop or restart (if needed)\nfunc (ctx *localContext) handleTerminated(msg *Terminated) {\n\tctx.children.Remove(msg.Who)\n\tctx.watching.Remove(msg.Who)\n\n\tctx.InvokeUserMessage(msg)\n\tctx.tryRestartOrTerminate()\n}\n\n\/\/offload the supervision completely to the supervisor strategy\nfunc (ctx *localContext) handleFailure(msg *Failure) {\n\tif strategy, ok := ctx.actor.(SupervisorStrategy); ok {\n\t\tstrategy.HandleFailure(ctx, msg.Who, msg.ChildStats, msg.Reason)\n\t\treturn\n\t}\n\tctx.supervisor.HandleFailure(ctx, msg.Who, msg.ChildStats, msg.Reason)\n}\n\nfunc (ctx *localContext) EscalateFailure(who *PID, reason interface{}) {\n\tif ctx.Parent() == nil {\n\t\tlog.Printf(\"[ACTOR] '%v' Cannot escalate failure from root actor; stopping instead\", ctx.debugString())\n\t\tctx.Self().sendSystemMessage(stopMessage)\n\t\treturn\n\t}\n\t\/\/suspend self\n\tctx.Self().sendSystemMessage(suspendMailboxMessage)\n\t\/\/send failure to parent\n\tctx.Parent().sendSystemMessage(&Failure{Reason: reason, Who: who})\n}\n\nfunc (ctx *localContext) tryRestartOrTerminate() {\n\tif ctx.t != nil {\n\t\tctx.t.Stop()\n\t\tctx.t = nil\n\t\tctx.receiveTimeout = 0\n\t}\n\n\tif !ctx.children.Empty() {\n\t\treturn\n\t}\n\n\tif ctx.restarting {\n\t\tctx.restart()\n\t\treturn\n\t}\n\n\tif ctx.stopping {\n\t\tctx.stopped()\n\t}\n}\n\nfunc (ctx *localContext) restart() {\n\tctx.incarnateActor()\n\t\/\/create a new childRestartStats with the current failure settings\n\tctx.restartStats = &ChildRestartStats{\n\t\tFailureCount:    ctx.restartStats.FailureCount + 1,\n\t\tLastFailureTime: time.Now(),\n\t}\n\tctx.InvokeUserMessage(startedMessage)\n\tif ctx.stash != nil {\n\t\tfor !ctx.stash.Empty() {\n\t\t\tmsg, _ := ctx.stash.Pop()\n\t\t\tctx.InvokeUserMessage(msg)\n\t\t}\n\t}\n\tctx.self.sendSystemMessage(resumeMailboxMessage)\n}\n\nfunc (ctx *localContext) stopped() {\n\tProcessRegistry.Remove(ctx.self)\n\tctx.InvokeUserMessage(stoppedMessage)\n\totherStopped := &Terminated{Who: ctx.self}\n\tctx.watchers.ForEach(func(i int, pid PID) {\n\t\tpid.sendSystemMessage(otherStopped)\n\t})\n}\n\nfunc identifyPanic() string {\n\tvar name, file string\n\tvar line int\n\tvar pc [16]uintptr\n\n\tn := runtime.Callers(3, pc[:])\n\tfor _, pc := range pc[:n] {\n\t\tlog.Printf(\"%d\", pc)\n\t\tfn := runtime.FuncForPC(pc)\n\t\tif fn == nil {\n\t\t\tcontinue\n\t\t}\n\t\tfile, line = fn.FileLine(pc)\n\t\tname = fn.Name()\n\t\tif !strings.HasPrefix(name, \"runtime.\") {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tswitch {\n\tcase name != \"\":\n\t\treturn fmt.Sprintf(\"%v:%v\", name, line)\n\tcase file != \"\":\n\t\treturn fmt.Sprintf(\"%v:%v\", file, line)\n\t}\n\n\treturn fmt.Sprintf(\"pc:%x\", pc)\n}\n\nfunc (ctx *localContext) InvokeUserMessage(md interface{}) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tlog.Printf(\"[ACTOR] '%v' Recovering from: %v. Detailed stack: %v\", ctx.debugString(), r, identifyPanic())\n\n\t\t\t\/\/lazy initialize the child restart stats if this is the first time\n\t\t\t\/\/further mutations are handled within \"restart\"\n\t\t\tif ctx.restartStats == nil {\n\t\t\t\tctx.restartStats = &ChildRestartStats{\n\t\t\t\t\tFailureCount: 1,\n\t\t\t\t}\n\t\t\t}\n\t\t\tfailure := &Failure{Reason: r, Who: ctx.self, ChildStats: ctx.restartStats}\n\t\t\tif ctx.parent == nil {\n\t\t\t\thandleRootFailure(failure)\n\t\t\t} else {\n\t\t\t\t\/\/TODO: Akka recursively suspends all children also on failure\n\t\t\t\t\/\/Not sure if I think this is the right way to go, why do children need to wait for their parents failed state to recover?\n\t\t\t\tctx.self.sendSystemMessage(suspendMailboxMessage)\n\t\t\t\tctx.parent.sendSystemMessage(failure)\n\t\t\t}\n\t\t}\n\t}()\n\n\tif md == nil {\n\t\tlog.Printf(\"[ACTOR] '%v' got nil message\", ctx.Self().String())\n\t\treturn\n\t}\n\n\tinfluenceTimeout := true\n\tif ctx.receiveTimeout > 0 {\n\t\t_, influenceTimeout = md.(NotInfluenceReceiveTimeout)\n\t\tinfluenceTimeout = !influenceTimeout\n\t\tif influenceTimeout {\n\t\t\tctx.t.Stop()\n\t\t}\n\t}\n\n\tctx.processMessage(md)\n\n\tif ctx.receiveTimeout > 0 && influenceTimeout {\n\t\tctx.t.Reset(ctx.receiveTimeout)\n\t}\n}\n\nfunc (ctx *localContext) Become(behavior ReceiveFunc) {\n\tctx.behavior.Clear()\n\tctx.receive = behavior\n}\n\nfunc (ctx *localContext) BecomeStacked(behavior ReceiveFunc) {\n\tctx.behavior.Push(ctx.receive)\n\tctx.receive = behavior\n}\n\nfunc (ctx *localContext) UnbecomeStacked() {\n\tif ctx.behavior.Len() == 0 {\n\t\tpanic(\"Cannot unbecome actor base behavior\")\n\t}\n\tctx.receive, _ = ctx.behavior.Pop()\n}\n\nfunc (ctx *localContext) Watch(who *PID) {\n\twho.sendSystemMessage(&Watch{\n\t\tWatcher: ctx.self,\n\t})\n\tctx.watching.Add(who)\n}\n\nfunc (ctx *localContext) Unwatch(who *PID) {\n\twho.sendSystemMessage(&Unwatch{\n\t\tWatcher: ctx.self,\n\t})\n\tctx.watching.Remove(who)\n}\n\nfunc (ctx *localContext) Respond(response interface{}) {\n\tif ctx.Sender() == nil {\n\t\tlog.Fatal(\"[ACTOR] No sender\")\n\t}\n\tctx.Sender().Tell(response)\n}\n\nfunc (ctx *localContext) Spawn(props Props) *PID {\n\treturn ctx.SpawnNamed(props, ProcessRegistry.NextId())\n}\n\nfunc (ctx *localContext) SpawnNamed(props Props, name string) *PID {\n\tpid := props.spawn(ctx.self.Id+\"\/\"+name, ctx.self)\n\tctx.children.Add(pid)\n\tctx.Watch(pid)\n\treturn pid\n}\n\nfunc (ctx *localContext) debugString() string {\n\treturn fmt.Sprintf(\"%v\/%v:%v\", ctx.self.Address, ctx.self.Id, reflect.TypeOf(ctx.actor))\n}\n\nfunc handleRootFailure(msg *Failure) {\n\tdefaultSupervisionStrategy.HandleFailure(nil, msg.Who, msg.ChildStats, msg.Reason)\n}\n<|endoftext|>"}
{"text":"<commit_before>package render\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"reflect\"\n)\n\n\/\/ Respond handles streaming JSON and XML responses, automatically setting the\n\/\/ Content-Type based on request headers. It will default to a JSON response.\nfunc Respond(w http.ResponseWriter, r *http.Request, v interface{}) {\n\t\/\/ Present the object.\n\tif presenter, ok := r.Context().Value(presenterCtxKey).(Presenter); ok {\n\t\tr, v = presenter.Present(r, v)\n\t}\n\n\tswitch reflect.TypeOf(v).Kind() {\n\tcase reflect.Chan:\n\t\tswitch getResponseContentType(r) {\n\t\tcase ContentTypeEventStream:\n\t\t\tchannelEventStream(w, r, v)\n\t\t\treturn\n\t\tdefault:\n\t\t\tv = channelIntoSlice(w, r, v)\n\t\t}\n\t}\n\n\t\/\/ Format data based on Content-Type.\n\tswitch getResponseContentType(r) {\n\tcase ContentTypeJSON:\n\t\tJSON(w, r, v)\n\tcase ContentTypeXML:\n\t\tXML(w, r, v)\n\tdefault:\n\t\tJSON(w, r, v)\n\t}\n}\n\n\/\/ PlainText writes a string to the response, setting the Content-Type as\n\/\/ text\/plain.\nfunc PlainText(w http.ResponseWriter, r *http.Request, v string) {\n\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=utf-8\")\n\tif status, ok := r.Context().Value(statusCtxKey).(int); ok {\n\t\tw.WriteHeader(status)\n\t}\n\tw.Write([]byte(v))\n}\n\n\/\/ Data writes raw bytes to the response, setting the Content-Type as\n\/\/ application\/octet-stream.\nfunc Data(w http.ResponseWriter, r *http.Request, v []byte) {\n\tw.Header().Set(\"Content-Type\", \"application\/octet-stream\")\n\tif status, ok := r.Context().Value(statusCtxKey).(int); ok {\n\t\tw.WriteHeader(status)\n\t}\n\tw.Write(v)\n}\n\n\/\/ HTML writes a string to the response, setting the Content-Type as text\/html.\nfunc HTML(w http.ResponseWriter, r *http.Request, v string) {\n\tw.Header().Set(\"Content-Type\", \"text\/html; charset=utf-8\")\n\tif status, ok := r.Context().Value(statusCtxKey).(int); ok {\n\t\tw.WriteHeader(status)\n\t}\n\tw.Write([]byte(v))\n}\n\n\/\/ JSON marshals 'v' to JSON, automatically escaping HTML and setting the\n\/\/ Content-Type as application\/json.\nfunc JSON(w http.ResponseWriter, r *http.Request, v interface{}) {\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tif status, ok := r.Context().Value(statusCtxKey).(int); ok {\n\t\tw.WriteHeader(status)\n\t}\n\n\tenc := json.NewEncoder(w)\n\tenc.SetEscapeHTML(true)\n\tif err := enc.Encode(v); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n\n\/\/ XML marshals 'v' to JSON, setting the Content-Type as application\/xml. It\n\/\/ will automatically prepend a generic XML header (see encoding\/xml.Header) if\n\/\/ one is not found in the first 100 bytes of 'v'.\nfunc XML(w http.ResponseWriter, r *http.Request, v interface{}) {\n\tb, err := xml.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/xml; charset=utf-8\")\n\tif status, ok := r.Context().Value(statusCtxKey).(int); ok {\n\t\tw.WriteHeader(status)\n\t}\n\n\t\/\/ Try to find <?xml header in first 100 bytes (just in case there're some XML comments).\n\tfindHeaderUntil := len(b)\n\tif findHeaderUntil > 100 {\n\t\tfindHeaderUntil = 100\n\t}\n\tif !bytes.Contains(b[:findHeaderUntil], []byte(\"<?xml\")) {\n\t\t\/\/ No header found. Print it out first.\n\t\tw.Write([]byte(xml.Header))\n\t}\n\n\tw.Write(b)\n}\n\n\/\/ NoContent returns a HTTP 204 \"No Content\" response.\nfunc NoContent(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(204)\n}\n\nfunc channelEventStream(w http.ResponseWriter, r *http.Request, v interface{}) {\n\tif reflect.TypeOf(v).Kind() != reflect.Chan {\n\t\tpanic(fmt.Sprintf(\"render.EventStream() expects channel, not %v\", reflect.TypeOf(v).Kind()))\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text\/event-stream; charset=utf-8\")\n\tw.Header().Set(\"Cache-Control\", \"no-cache\")\n\tw.Header().Set(\"Connection\", \"keep-alive\")\n\tw.WriteHeader(200)\n\n\tctx := r.Context()\n\tfor {\n\t\tswitch chosen, recv, ok := reflect.Select([]reflect.SelectCase{\n\t\t\t{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ctx.Done())},\n\t\t\t{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(v)},\n\t\t}); chosen {\n\t\tcase 0: \/\/ equivalent to: case <-ctx.Done()\n\t\t\tw.Write([]byte(\"event: error\\ndata: {\\\"error\\\":\\\"Server Timeout\\\"}\\n\\n\"))\n\t\t\treturn\n\n\t\tdefault: \/\/ equivalent to: case v, ok := <-stream\n\t\t\tif !ok {\n\t\t\t\tw.Write([]byte(\"event: EOF\\n\\n\"))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tv := recv.Interface()\n\n\t\t\t\/\/ Present each channel item.\n\t\t\tif presenter, ok := r.Context().Value(presenterCtxKey).(Presenter); ok {\n\t\t\t\tr, v = presenter.Present(r, v)\n\t\t\t}\n\n\t\t\t\/\/ TODO: Can't use json Encoder - it panics on bufio.Flush(). Why?!\n\t\t\t\/\/ enc := json.NewEncoder(w)\n\t\t\t\/\/ enc.Encode(v.Interface())\n\t\t\tbytes, err := json.Marshal(v)\n\t\t\tif err != nil {\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"event: error\\ndata: {\\\"error\\\":\\\"%v\\\"}\\n\\n\", err)))\n\t\t\t\tif f, ok := w.(http.Flusher); ok {\n\t\t\t\t\tf.Flush()\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tw.Write([]byte(fmt.Sprintf(\"event: data\\ndata: %s\\n\\n\", bytes)))\n\t\t\tif f, ok := w.(http.Flusher); ok {\n\t\t\t\tf.Flush()\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ channelIntoSlice buffers channel data into a slice.\nfunc channelIntoSlice(w http.ResponseWriter, r *http.Request, from interface{}) interface{} {\n\tctx := r.Context()\n\n\tvar to []interface{}\n\tfor {\n\t\tswitch chosen, recv, ok := reflect.Select([]reflect.SelectCase{\n\t\t\t{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ctx.Done())},\n\t\t\t{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(from)},\n\t\t}); chosen {\n\t\tcase 0: \/\/ equivalent to: case <-ctx.Done()\n\t\t\thttp.Error(w, \"Server Timeout\", 504)\n\t\t\treturn nil\n\n\t\tdefault: \/\/ equivalent to: case v, ok := <-stream\n\t\t\tif !ok {\n\t\t\t\treturn to\n\t\t\t}\n\t\t\tv := recv.Interface()\n\n\t\t\t\/\/ Present each channel item.\n\t\t\tif presenter, ok := r.Context().Value(presenterCtxKey).(Presenter); ok {\n\t\t\t\tr, v = presenter.Present(r, v)\n\t\t\t}\n\n\t\t\tto = append(to, v)\n\t\t}\n\t}\n}\n\n\/\/ contextKey is a value for use with context.WithValue. It's used as\n\/\/ a pointer so it fits in an interface{} without allocation. This technique\n\/\/ for defining context keys was copied from Go 1.7's new use of context in net\/http.\ntype contextKey struct {\n\tname string\n}\n\nfunc (k *contextKey) String() string {\n\treturn \"chi render context value \" + k.name\n}\n<commit_msg>fix typo in godoc for xml marshaler<commit_after>package render\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"reflect\"\n)\n\n\/\/ Respond handles streaming JSON and XML responses, automatically setting the\n\/\/ Content-Type based on request headers. It will default to a JSON response.\nfunc Respond(w http.ResponseWriter, r *http.Request, v interface{}) {\n\t\/\/ Present the object.\n\tif presenter, ok := r.Context().Value(presenterCtxKey).(Presenter); ok {\n\t\tr, v = presenter.Present(r, v)\n\t}\n\n\tswitch reflect.TypeOf(v).Kind() {\n\tcase reflect.Chan:\n\t\tswitch getResponseContentType(r) {\n\t\tcase ContentTypeEventStream:\n\t\t\tchannelEventStream(w, r, v)\n\t\t\treturn\n\t\tdefault:\n\t\t\tv = channelIntoSlice(w, r, v)\n\t\t}\n\t}\n\n\t\/\/ Format data based on Content-Type.\n\tswitch getResponseContentType(r) {\n\tcase ContentTypeJSON:\n\t\tJSON(w, r, v)\n\tcase ContentTypeXML:\n\t\tXML(w, r, v)\n\tdefault:\n\t\tJSON(w, r, v)\n\t}\n}\n\n\/\/ PlainText writes a string to the response, setting the Content-Type as\n\/\/ text\/plain.\nfunc PlainText(w http.ResponseWriter, r *http.Request, v string) {\n\tw.Header().Set(\"Content-Type\", \"text\/plain; charset=utf-8\")\n\tif status, ok := r.Context().Value(statusCtxKey).(int); ok {\n\t\tw.WriteHeader(status)\n\t}\n\tw.Write([]byte(v))\n}\n\n\/\/ Data writes raw bytes to the response, setting the Content-Type as\n\/\/ application\/octet-stream.\nfunc Data(w http.ResponseWriter, r *http.Request, v []byte) {\n\tw.Header().Set(\"Content-Type\", \"application\/octet-stream\")\n\tif status, ok := r.Context().Value(statusCtxKey).(int); ok {\n\t\tw.WriteHeader(status)\n\t}\n\tw.Write(v)\n}\n\n\/\/ HTML writes a string to the response, setting the Content-Type as text\/html.\nfunc HTML(w http.ResponseWriter, r *http.Request, v string) {\n\tw.Header().Set(\"Content-Type\", \"text\/html; charset=utf-8\")\n\tif status, ok := r.Context().Value(statusCtxKey).(int); ok {\n\t\tw.WriteHeader(status)\n\t}\n\tw.Write([]byte(v))\n}\n\n\/\/ JSON marshals 'v' to JSON, automatically escaping HTML and setting the\n\/\/ Content-Type as application\/json.\nfunc JSON(w http.ResponseWriter, r *http.Request, v interface{}) {\n\tw.Header().Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tif status, ok := r.Context().Value(statusCtxKey).(int); ok {\n\t\tw.WriteHeader(status)\n\t}\n\n\tenc := json.NewEncoder(w)\n\tenc.SetEscapeHTML(true)\n\tif err := enc.Encode(v); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}\n\n\/\/ XML marshals 'v' to XML, setting the Content-Type as application\/xml. It\n\/\/ will automatically prepend a generic XML header (see encoding\/xml.Header) if\n\/\/ one is not found in the first 100 bytes of 'v'.\nfunc XML(w http.ResponseWriter, r *http.Request, v interface{}) {\n\tb, err := xml.Marshal(v)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/xml; charset=utf-8\")\n\tif status, ok := r.Context().Value(statusCtxKey).(int); ok {\n\t\tw.WriteHeader(status)\n\t}\n\n\t\/\/ Try to find <?xml header in first 100 bytes (just in case there're some XML comments).\n\tfindHeaderUntil := len(b)\n\tif findHeaderUntil > 100 {\n\t\tfindHeaderUntil = 100\n\t}\n\tif !bytes.Contains(b[:findHeaderUntil], []byte(\"<?xml\")) {\n\t\t\/\/ No header found. Print it out first.\n\t\tw.Write([]byte(xml.Header))\n\t}\n\n\tw.Write(b)\n}\n\n\/\/ NoContent returns a HTTP 204 \"No Content\" response.\nfunc NoContent(w http.ResponseWriter, r *http.Request) {\n\tw.WriteHeader(204)\n}\n\nfunc channelEventStream(w http.ResponseWriter, r *http.Request, v interface{}) {\n\tif reflect.TypeOf(v).Kind() != reflect.Chan {\n\t\tpanic(fmt.Sprintf(\"render.EventStream() expects channel, not %v\", reflect.TypeOf(v).Kind()))\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text\/event-stream; charset=utf-8\")\n\tw.Header().Set(\"Cache-Control\", \"no-cache\")\n\tw.Header().Set(\"Connection\", \"keep-alive\")\n\tw.WriteHeader(200)\n\n\tctx := r.Context()\n\tfor {\n\t\tswitch chosen, recv, ok := reflect.Select([]reflect.SelectCase{\n\t\t\t{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ctx.Done())},\n\t\t\t{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(v)},\n\t\t}); chosen {\n\t\tcase 0: \/\/ equivalent to: case <-ctx.Done()\n\t\t\tw.Write([]byte(\"event: error\\ndata: {\\\"error\\\":\\\"Server Timeout\\\"}\\n\\n\"))\n\t\t\treturn\n\n\t\tdefault: \/\/ equivalent to: case v, ok := <-stream\n\t\t\tif !ok {\n\t\t\t\tw.Write([]byte(\"event: EOF\\n\\n\"))\n\t\t\t\treturn\n\t\t\t}\n\t\t\tv := recv.Interface()\n\n\t\t\t\/\/ Present each channel item.\n\t\t\tif presenter, ok := r.Context().Value(presenterCtxKey).(Presenter); ok {\n\t\t\t\tr, v = presenter.Present(r, v)\n\t\t\t}\n\n\t\t\t\/\/ TODO: Can't use json Encoder - it panics on bufio.Flush(). Why?!\n\t\t\t\/\/ enc := json.NewEncoder(w)\n\t\t\t\/\/ enc.Encode(v.Interface())\n\t\t\tbytes, err := json.Marshal(v)\n\t\t\tif err != nil {\n\t\t\t\tw.Write([]byte(fmt.Sprintf(\"event: error\\ndata: {\\\"error\\\":\\\"%v\\\"}\\n\\n\", err)))\n\t\t\t\tif f, ok := w.(http.Flusher); ok {\n\t\t\t\t\tf.Flush()\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tw.Write([]byte(fmt.Sprintf(\"event: data\\ndata: %s\\n\\n\", bytes)))\n\t\t\tif f, ok := w.(http.Flusher); ok {\n\t\t\t\tf.Flush()\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ channelIntoSlice buffers channel data into a slice.\nfunc channelIntoSlice(w http.ResponseWriter, r *http.Request, from interface{}) interface{} {\n\tctx := r.Context()\n\n\tvar to []interface{}\n\tfor {\n\t\tswitch chosen, recv, ok := reflect.Select([]reflect.SelectCase{\n\t\t\t{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(ctx.Done())},\n\t\t\t{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(from)},\n\t\t}); chosen {\n\t\tcase 0: \/\/ equivalent to: case <-ctx.Done()\n\t\t\thttp.Error(w, \"Server Timeout\", 504)\n\t\t\treturn nil\n\n\t\tdefault: \/\/ equivalent to: case v, ok := <-stream\n\t\t\tif !ok {\n\t\t\t\treturn to\n\t\t\t}\n\t\t\tv := recv.Interface()\n\n\t\t\t\/\/ Present each channel item.\n\t\t\tif presenter, ok := r.Context().Value(presenterCtxKey).(Presenter); ok {\n\t\t\t\tr, v = presenter.Present(r, v)\n\t\t\t}\n\n\t\t\tto = append(to, v)\n\t\t}\n\t}\n}\n\n\/\/ contextKey is a value for use with context.WithValue. It's used as\n\/\/ a pointer so it fits in an interface{} without allocation. This technique\n\/\/ for defining context keys was copied from Go 1.7's new use of context in net\/http.\ntype contextKey struct {\n\tname string\n}\n\nfunc (k *contextKey) String() string {\n\treturn \"chi render context value \" + k.name\n}\n<|endoftext|>"}
{"text":"<commit_before>package render\n\nimport (\n\t\"encoding\/json\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n)\n\n\/\/ An interface of suggested methods for rendering output in Go\ntype MiloRenderer interface {\n\tRenderTemplates(w http.ResponseWriter, r *http.Request, data map[string]interface{}, tpls ...string)\n\tRenderJson(w http.ResponseWriter, r *http.Request, data interface{})\n\tRegisterTemplateFunc(key string, fn interface{})\n\tRedirect(w http.ResponseWriter, r *http.Request, url string, code int)\n}\n\n\/\/ Default milo renderer that can cache templates, sets a base template directory.\ntype DefaultMiloRenderer struct {\n\ttemplateCache map[string]*template.Template\n\ttplDir        string\n\ttplFuncs      map[string]interface{}\n\tcacheTpls     bool\n\tsync.RWMutex\n}\n\n\/\/ Create a new default milo renderer.\nfunc NewDefaultMiloRenderer(tplDir string, cache bool) MiloRenderer {\n\tr := &DefaultMiloRenderer{templateCache: make(map[string]*template.Template), tplDir: tplDir, tplFuncs: make(map[string]interface{}), cacheTpls: cache}\n\tr.tplFuncs[\"host\"] = Host\n\tr.tplFuncs[\"marshal\"] = Marshal\n\treturn r\n}\n\n\/\/ Takes care of rendering templates from file.\nfunc (mr *DefaultMiloRenderer) RenderTemplates(w http.ResponseWriter, r *http.Request, data map[string]interface{}, tpls ...string) {\n\tif len(tpls) < 1 {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"Error: Template required!\"))\n\t\treturn\n\t}\n\n\tlog.Println(\"Rendering the templates\")\n\n\tlist := make([]string, 0)\n\tfor _, elem := range tpls {\n\t\tlist = append(list, filepath.Join(mr.tplDir, elem))\n\t}\n\n\tif tpl, loadErr := mr.acquireTemplate(strings.Join(tpls, \"\"), list...); loadErr != nil {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(loadErr.Error()))\n\t} else {\n\t\ttpl.Execute(w, data)\n\t}\n}\n\n\/\/ Unexported method to help handle template parsing.  If the cache template bool is set on the config\n\/\/ struct this method with look in the cache & load the cache upon subsequent encounters.\n\/\/ This should lower disk access penalties useful for production instances.\nfunc (mr *DefaultMiloRenderer) acquireTemplate(key string, tpls ...string) (*template.Template, error) {\n\tvar tpl *template.Template\n\tvar loadErr error\n\tvar ok bool\n\n\tif mr.cacheTpls {\n\t\tmr.RLock()\n\t\ttpl, ok = mr.templateCache[key]\n\t\tmr.RUnlock()\n\t\tif ok {\n\t\t\treturn tpl, nil\n\t\t}\n\t}\n\n\ttpl, loadErr = template.New(filepath.Base(tpls[0])).Funcs(mr.tplFuncs).ParseFiles(tpls...)\n\tif loadErr != nil {\n\t\treturn nil, loadErr\n\t}\n\n\tif mr.cacheTpls {\n\t\tmr.Lock()\n\t\tmr.templateCache[key] = tpl\n\t\tmr.Unlock()\n\t}\n\treturn tpl, nil\n}\n\n\/\/ Render json output\nfunc (mr *DefaultMiloRenderer) RenderJson(w http.ResponseWriter, r *http.Request, data interface{}) {\n\tif data, err := json.Marshal(data); err != nil {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(err.Error()))\n\t} else {\n\t\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write(data)\n\t}\n}\n\n\/\/ Register a template function with the MiloRenderer\nfunc (mr *DefaultMiloRenderer) RegisterTemplateFunc(key string, fn interface{}) {\n\tmr.tplFuncs[key] = fn\n}\n\n\/\/ Setup an http redirect on the request.\nfunc (mr *DefaultMiloRenderer) Redirect(w http.ResponseWriter, r *http.Request, url string, code int) {\n\thttp.Redirect(w, r, url, code)\n}\n<commit_msg>Updated render to help with error logging on template execution.<commit_after>package render\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"sync\"\n)\n\n\/\/ An interface of suggested methods for rendering output in Go\ntype MiloRenderer interface {\n\tRenderTemplates(w http.ResponseWriter, r *http.Request, data map[string]interface{}, tpls ...string)\n\tRenderJson(w http.ResponseWriter, r *http.Request, data interface{})\n\tRegisterTemplateFunc(key string, fn interface{})\n\tRedirect(w http.ResponseWriter, r *http.Request, url string, code int)\n}\n\n\/\/ Default milo renderer that can cache templates, sets a base template directory.\ntype DefaultMiloRenderer struct {\n\ttemplateCache map[string]*template.Template\n\ttplDir        string\n\ttplFuncs      map[string]interface{}\n\tcacheTpls     bool\n\tsync.RWMutex\n}\n\n\/\/ Create a new default milo renderer.\nfunc NewDefaultMiloRenderer(tplDir string, cache bool) MiloRenderer {\n\tr := &DefaultMiloRenderer{templateCache: make(map[string]*template.Template), tplDir: tplDir, tplFuncs: make(map[string]interface{}), cacheTpls: cache}\n\tr.tplFuncs[\"host\"] = Host\n\tr.tplFuncs[\"marshal\"] = Marshal\n\treturn r\n}\n\n\/\/ Takes care of rendering templates from file.\nfunc (mr *DefaultMiloRenderer) RenderTemplates(w http.ResponseWriter, r *http.Request, data map[string]interface{}, tpls ...string) {\n\tif len(tpls) < 1 {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(\"Error: Template required!\"))\n\t\treturn\n\t}\n\n\tlog.Println(\"Rendering the templates\")\n\n\tlist := make([]string, 0)\n\tfor _, elem := range tpls {\n\t\tlist = append(list, filepath.Join(mr.tplDir, elem))\n\t}\n\n\tif tpl, loadErr := mr.acquireTemplate(strings.Join(tpls, \"\"), list...); loadErr != nil {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(loadErr.Error()))\n\t} else {\n\t\tvar doc bytes.Buffer\n\t\terr := tpl.Execute(&doc, data)\n\t\tif err == nil {\n\t\t\tw.WriteHeader(200)\n\t\t\tw.Write(doc.Bytes())\n\t\t} else {\n\t\t\tw.WriteHeader(500)\n\t\t\tw.Write([]byte(err.Error()))\n\t\t}\n\t}\n}\n\n\/\/ Unexported method to help handle template parsing.  If the cache template bool is set on the config\n\/\/ struct this method with look in the cache & load the cache upon subsequent encounters.\n\/\/ This should lower disk access penalties useful for production instances.\nfunc (mr *DefaultMiloRenderer) acquireTemplate(key string, tpls ...string) (*template.Template, error) {\n\tvar tpl *template.Template\n\tvar loadErr error\n\tvar ok bool\n\n\tif mr.cacheTpls {\n\t\tmr.RLock()\n\t\ttpl, ok = mr.templateCache[key]\n\t\tmr.RUnlock()\n\t\tif ok {\n\t\t\treturn tpl, nil\n\t\t}\n\t}\n\n\ttpl, loadErr = template.New(filepath.Base(tpls[0])).Funcs(mr.tplFuncs).ParseFiles(tpls...)\n\tif loadErr != nil {\n\t\treturn nil, loadErr\n\t}\n\n\tif mr.cacheTpls {\n\t\tmr.Lock()\n\t\tmr.templateCache[key] = tpl\n\t\tmr.Unlock()\n\t}\n\treturn tpl, nil\n}\n\n\/\/ Render json output\nfunc (mr *DefaultMiloRenderer) RenderJson(w http.ResponseWriter, r *http.Request, data interface{}) {\n\tif data, err := json.Marshal(data); err != nil {\n\t\tw.WriteHeader(500)\n\t\tw.Write([]byte(err.Error()))\n\t} else {\n\t\tw.Header().Add(\"Content-Type\", \"application\/json\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write(data)\n\t}\n}\n\n\/\/ Register a template function with the MiloRenderer\nfunc (mr *DefaultMiloRenderer) RegisterTemplateFunc(key string, fn interface{}) {\n\tmr.tplFuncs[key] = fn\n}\n\n\/\/ Setup an http redirect on the request.\nfunc (mr *DefaultMiloRenderer) Redirect(w http.ResponseWriter, r *http.Request, url string, code int) {\n\thttp.Redirect(w, r, url, code)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Matthew Collins\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage render\n\nimport (\n\t\"math\"\n\t\"os\"\n\n\t\"github.com\/go-gl\/mathgl\/mgl32\"\n\t\"github.com\/thinkofdeath\/steven\/console\"\n\t\"github.com\/thinkofdeath\/steven\/render\/gl\"\n\t\"github.com\/thinkofdeath\/steven\/render\/glsl\"\n\t\"github.com\/thinkofdeath\/steven\/type\/direction\"\n\t\"github.com\/thinkofdeath\/steven\/type\/vmath\"\n)\n\nvar (\n\tchunkProgram  gl.Program\n\tshaderChunk   *chunkShader\n\tchunkProgramT gl.Program\n\tshaderChunkT  *chunkShader\n\tlineProgram   gl.Program\n\tshaderLine    *lineShader\n\n\tFOV = console.NewIntVar(\"r_fov\", 90, console.Mutable, console.Serializable).Doc(`\nr_fov controls the field of view of the camera. Measured\nin degrees.\n`)\n\tlastFOV               int = 90\n\tlastWidth, lastHeight int = -1, -1\n\tperspectiveMatrix         = mgl32.Mat4{}\n\tcameraMatrix              = mgl32.Mat4{}\n\tfrustum                   = vmath.NewFrustum()\n\n\tsyncChan = make(chan func(), 500)\n\n\tglTexture       gl.Texture\n\ttextureDepth    int\n\ttexturesCreated bool\n\n\tdebugFramebuffers = console.NewBoolVar(\"r_debug_buffers\", false, console.Mutable).Doc(`\nr_debug_buffers blits all frame buffers to the screen for\ndebugging.\n`)\n\n\tLightLevel, SkyOffset float32 = 0.8, 1.0\n\tClearColour                   = struct{ R, G, B float32 }{\n\t\t122.0 \/ 255.0, 165.0 \/ 255.0, 247.0 \/ 255.0,\n\t}\n)\n\n\/\/ Start starts the renderer\nfunc Start() {\n\tif os.Getenv(\"STEVEN_DEBUG\") == \"true\" {\n\t\tgl.DebugLog()\n\t}\n\n\tgl.Enable(gl.DepthTest)\n\tgl.Enable(gl.CullFaceFlag)\n\tgl.CullFace(gl.Back)\n\tgl.FrontFace(gl.ClockWise)\n\n\tchunkProgram = CreateProgram(\n\t\tglsl.Get(\"chunk_vertex\"),\n\t\tglsl.Get(\"chunk_frag\"),\n\t)\n\tshaderChunk = &chunkShader{}\n\tInitStruct(shaderChunk, chunkProgram)\n\n\tchunkProgramT = CreateProgram(\n\t\tglsl.Get(\"chunk_vertex\"),\n\t\tglsl.Get(\"chunk_frag\", \"alpha\"),\n\t)\n\tshaderChunkT = &chunkShader{}\n\tInitStruct(shaderChunkT, chunkProgramT)\n\n\tinitUI()\n\tinitLineDraw()\n\tinitModels()\n\tclouds.init()\n\n\tgl.BlendFunc(gl.SrcAlpha, gl.OneMinusSrcAlpha)\n\n\telementBuffer = gl.CreateBuffer()\n}\n\nvar (\n\ttextureIds    []int\n\tframeID       uint\n\tnearestBuffer *ChunkBuffer\n\tviewVector    mgl32.Vec3\n)\n\n\/\/ Draw draws a single frame\nfunc Draw(width, height int, delta float64) {\n\ttickAnimatedTextures(delta)\n\tframeID++\nsync:\n\tfor {\n\t\tselect {\n\t\tcase f := <-syncChan:\n\t\t\tf()\n\t\tdefault:\n\t\t\tbreak sync\n\t\t}\n\t}\n\n\t\/\/ Only update the viewport if the window was resized\n\tif lastHeight != height || lastWidth != width || lastFOV != FOV.Value() {\n\t\tlastWidth = width\n\t\tlastHeight = height\n\t\tlastFOV = FOV.Value()\n\n\t\tperspectiveMatrix = mgl32.Perspective(\n\t\t\t(math.Pi\/180)*float32(lastFOV),\n\t\t\tfloat32(width)\/float32(height),\n\t\t\t0.1,\n\t\t\t500.0,\n\t\t)\n\t\tgl.Viewport(0, 0, width, height)\n\t\tfrustum.SetPerspective(\n\t\t\t(math.Pi\/180)*float32(lastFOV),\n\t\t\tfloat32(width)\/float32(height),\n\t\t\t0.1,\n\t\t\t500.0,\n\t\t)\n\t\tinitTrans()\n\t}\n\n\tmainFramebuffer.Bind()\n\tgl.Enable(gl.Multisample)\n\n\tgl.ActiveTexture(0)\n\tglTexture.Bind(gl.Texture2DArray)\n\n\tgl.ClearColor(ClearColour.R, ClearColour.G, ClearColour.B, 1.0)\n\tgl.Clear(gl.ColorBufferBit | gl.DepthBufferBit)\n\n\tchunkProgram.Use()\n\n\tviewVector = mgl32.Vec3{\n\t\tfloat32(math.Cos(Camera.Yaw-math.Pi\/2) * -math.Cos(Camera.Pitch)),\n\t\tfloat32(-math.Sin(Camera.Pitch)),\n\t\tfloat32(-math.Sin(Camera.Yaw-math.Pi\/2) * -math.Cos(Camera.Pitch)),\n\t}\n\tcam := mgl32.Vec3{-float32(Camera.X), -float32(Camera.Y), float32(Camera.Z)}\n\tcameraMatrix = mgl32.LookAtV(\n\t\tcam,\n\t\tcam.Add(mgl32.Vec3{-viewVector.X(), -viewVector.Y(), viewVector.Z()}),\n\t\tmgl32.Vec3{0, -1, 0},\n\t)\n\tcameraMatrix = cameraMatrix.Mul4(mgl32.Scale3D(-1.0, 1.0, 1.0))\n\n\tfrustum.SetCamera(\n\t\tcam,\n\t\tcam.Add(mgl32.Vec3{-viewVector.X(), -viewVector.Y(), viewVector.Z()}),\n\t\tmgl32.Vec3{0, -1, 0},\n\t)\n\n\tshaderChunk.PerspectiveMatrix.Matrix4(&perspectiveMatrix)\n\tshaderChunk.CameraMatrix.Matrix4(&cameraMatrix)\n\tshaderChunk.Texture.Int(0)\n\tshaderChunk.LightLevel.Float(LightLevel)\n\tshaderChunk.SkyOffset.Float(SkyOffset)\n\n\tchunkPos := position{\n\t\tX: int(Camera.X) >> 4,\n\t\tY: int(Camera.Y) >> 4,\n\t\tZ: int(Camera.Z) >> 4,\n\t}\n\tnearestBuffer = buffers[chunkPos]\n\n\tfor _, dir := range direction.Values {\n\t\tvalidDirs[dir] = viewVector.Dot(dir.AsVec()) > -0.8\n\t}\n\n\trenderOrder = renderOrder[:0]\n\trenderBuffer(nearestBuffer, chunkPos, direction.Invalid, delta)\n\n\tdrawLines()\n\tdrawModels()\n\tclouds.tick(delta)\n\n\tchunkProgramT.Use()\n\tshaderChunkT.PerspectiveMatrix.Matrix4(&perspectiveMatrix)\n\tshaderChunkT.CameraMatrix.Matrix4(&cameraMatrix)\n\tshaderChunkT.Texture.Int(0)\n\tshaderChunkT.LightLevel.Float(LightLevel)\n\tshaderChunkT.SkyOffset.Float(SkyOffset)\n\n\t\/\/ Copy the depth buffer\n\tmainFramebuffer.BindRead()\n\ttransFramebuffer.BindDraw()\n\tgl.BlitFramebuffer(\n\t\t0, 0, lastWidth, lastHeight,\n\t\t0, 0, lastWidth, lastHeight,\n\t\tgl.DepthBufferBit, gl.Nearest,\n\t)\n\n\tgl.Enable(gl.Blend)\n\tgl.DepthMask(false)\n\ttransFramebuffer.Bind()\n\tgl.ClearColor(0, 0, 0, 1)\n\tgl.Clear(gl.ColorBufferBit)\n\tgl.ClearBuffer(gl.Color, 0, []float32{0, 0, 0, 1})\n\tgl.ClearBuffer(gl.Color, 1, []float32{0, 0, 0, 0})\n\tgl.BlendFuncSeparate(gl.OneFactor, gl.OneFactor, gl.ZeroFactor, gl.OneMinusSrcAlpha)\n\tfor _, chunk := range renderOrder {\n\t\tif chunk.countT > 0 && chunk.bufferT.IsValid() {\n\t\t\tshaderChunkT.Offset.Int3(chunk.X, chunk.Y*4096-chunk.Y*int(4096*(1-chunk.progress)), chunk.Z)\n\n\t\t\tchunk.arrayT.Bind()\n\t\t\tgl.DrawElements(gl.Triangles, chunk.countT, elementBufferType, 0)\n\t\t}\n\t}\n\n\tgl.UnbindFramebuffer()\n\tgl.Disable(gl.DepthTest)\n\tgl.Clear(gl.ColorBufferBit)\n\tgl.Disable(gl.Blend)\n\n\ttransDraw()\n\n\tgl.Enable(gl.DepthTest)\n\tgl.DepthMask(true)\n\tgl.BlendFunc(gl.SrcAlpha, gl.OneMinusSrcAlpha)\n\tgl.Disable(gl.Multisample)\n\n\tdrawUI()\n\n\tif debugFramebuffers.Value() {\n\t\tgl.Enable(gl.Multisample)\n\t\tblitBuffers()\n\t\tgl.Disable(gl.Multisample)\n\t}\n}\n\nvar (\n\trenderOrder []*ChunkBuffer\n\tvalidDirs   = make([]bool, len(direction.Values))\n)\n\ntype renderRequest struct {\n\tchunk *ChunkBuffer\n\tpos   position\n\tfrom  direction.Type\n}\n\nconst (\n\trenderQueueSize = 5000\n)\n\nvar rQueue renderQueue\n\nfunc renderBuffer(ch *ChunkBuffer, po position, fr direction.Type, delta float64) {\n\tif ch == nil {\n\t\treturn\n\t}\n\trQueue.Append(renderRequest{ch, po, fr})\n\n\tfor !rQueue.Empty() {\n\t\treq := rQueue.Take()\n\t\tif req.chunk.renderedOn == frameID {\n\t\t\tcontinue\n\t\t}\n\t\treq.chunk.renderedOn = frameID\n\n\t\taabb := vmath.NewAABB(\n\t\t\t-float32((req.pos.X<<4)+16), -float32((req.pos.Y<<4)+16), float32((req.pos.Z<<4)),\n\t\t\t-float32((req.pos.X<<4)), -float32((req.pos.Y<<4)), float32((req.pos.Z<<4)+16),\n\t\t).Grow(1, 1, 1)\n\t\tif !frustum.IsAABBInside(aabb) {\n\t\t\tcontinue\n\t\t}\n\t\trenderOrder = append(renderOrder, req.chunk)\n\n\t\treq.chunk.Rendered = true\n\n\t\tdx := req.pos.X - int(Camera.X)>>4\n\t\tdz := req.pos.Z - int(Camera.Z)>>4\n\n\t\tif req.chunk.progress < 1 && math.Sqrt(float64(dx*dx+dz*dz)) > 6 {\n\t\t\treq.chunk.progress += delta * 0.015\n\t\t} else {\n\t\t\treq.chunk.progress = 1\n\t\t}\n\n\t\tif req.chunk.count != 0 && req.chunk.buffer.IsValid() {\n\t\t\tshaderChunk.Offset.Int3(req.chunk.X, req.chunk.Y*4096-req.chunk.Y*int(4096*(1-req.chunk.progress)), req.chunk.Z)\n\n\t\t\treq.chunk.array.Bind()\n\t\t\tgl.DrawElements(gl.Triangles, req.chunk.count, elementBufferType, 0)\n\t\t}\n\n\t\tfor _, dir := range direction.Values {\n\t\t\tc := req.chunk.neighborChunks[dir]\n\t\t\tif dir != req.from && c != nil && c.renderedOn != frameID &&\n\t\t\t\t(req.from == direction.Invalid || (req.chunk.IsVisible(req.from, dir) && validDirs[dir])) {\n\t\t\t\tox, oy, oz := dir.Offset()\n\t\t\t\tpos := position{req.pos.X + ox, req.pos.Y + oy, req.pos.Z + oz}\n\t\t\t\trQueue.Append(renderRequest{c, pos, dir.Opposite()})\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Sync runs the passed function on the next frame on the same goroutine\n\/\/ as the renderer.\nfunc Sync(f func()) {\n\tsyncChan <- f\n}\n<commit_msg>render: put slidy chunks behind a 'r_slidy_chunks' flag<commit_after>\/\/ Copyright 2015 Matthew Collins\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage render\n\nimport (\n\t\"math\"\n\t\"os\"\n\n\t\"github.com\/go-gl\/mathgl\/mgl32\"\n\t\"github.com\/thinkofdeath\/steven\/console\"\n\t\"github.com\/thinkofdeath\/steven\/render\/gl\"\n\t\"github.com\/thinkofdeath\/steven\/render\/glsl\"\n\t\"github.com\/thinkofdeath\/steven\/type\/direction\"\n\t\"github.com\/thinkofdeath\/steven\/type\/vmath\"\n)\n\nvar (\n\tchunkProgram  gl.Program\n\tshaderChunk   *chunkShader\n\tchunkProgramT gl.Program\n\tshaderChunkT  *chunkShader\n\tlineProgram   gl.Program\n\tshaderLine    *lineShader\n\n\tFOV = console.NewIntVar(\"r_fov\", 90, console.Mutable, console.Serializable).Doc(`\nr_fov controls the field of view of the camera. Measured\nin degrees.\n`)\n\tlastFOV               int = 90\n\tlastWidth, lastHeight int = -1, -1\n\tperspectiveMatrix         = mgl32.Mat4{}\n\tcameraMatrix              = mgl32.Mat4{}\n\tfrustum                   = vmath.NewFrustum()\n\n\tsyncChan = make(chan func(), 500)\n\n\tglTexture       gl.Texture\n\ttextureDepth    int\n\ttexturesCreated bool\n\n\tdebugFramebuffers = console.NewBoolVar(\"r_debug_buffers\", false, console.Mutable).Doc(`\nr_debug_buffers blits all frame buffers to the screen for\ndebugging.\n`)\n\n\tLightLevel, SkyOffset float32 = 0.8, 1.0\n\tClearColour                   = struct{ R, G, B float32 }{\n\t\t122.0 \/ 255.0, 165.0 \/ 255.0, 247.0 \/ 255.0,\n\t}\n\n\tslidyChunks = console.NewBoolVar(\"r_slidy_chunks\", false, console.Mutable, console.Serializable).Doc(`\nr_slidy_chunks makes chunks slide into view instead of just\npopping in.\n`)\n)\n\n\/\/ Start starts the renderer\nfunc Start() {\n\tif os.Getenv(\"STEVEN_DEBUG\") == \"true\" {\n\t\tgl.DebugLog()\n\t}\n\n\tgl.Enable(gl.DepthTest)\n\tgl.Enable(gl.CullFaceFlag)\n\tgl.CullFace(gl.Back)\n\tgl.FrontFace(gl.ClockWise)\n\n\tchunkProgram = CreateProgram(\n\t\tglsl.Get(\"chunk_vertex\"),\n\t\tglsl.Get(\"chunk_frag\"),\n\t)\n\tshaderChunk = &chunkShader{}\n\tInitStruct(shaderChunk, chunkProgram)\n\n\tchunkProgramT = CreateProgram(\n\t\tglsl.Get(\"chunk_vertex\"),\n\t\tglsl.Get(\"chunk_frag\", \"alpha\"),\n\t)\n\tshaderChunkT = &chunkShader{}\n\tInitStruct(shaderChunkT, chunkProgramT)\n\n\tinitUI()\n\tinitLineDraw()\n\tinitModels()\n\tclouds.init()\n\n\tgl.BlendFunc(gl.SrcAlpha, gl.OneMinusSrcAlpha)\n\n\telementBuffer = gl.CreateBuffer()\n}\n\nvar (\n\ttextureIds    []int\n\tframeID       uint\n\tnearestBuffer *ChunkBuffer\n\tviewVector    mgl32.Vec3\n)\n\n\/\/ Draw draws a single frame\nfunc Draw(width, height int, delta float64) {\n\ttickAnimatedTextures(delta)\n\tframeID++\nsync:\n\tfor {\n\t\tselect {\n\t\tcase f := <-syncChan:\n\t\t\tf()\n\t\tdefault:\n\t\t\tbreak sync\n\t\t}\n\t}\n\n\t\/\/ Only update the viewport if the window was resized\n\tif lastHeight != height || lastWidth != width || lastFOV != FOV.Value() {\n\t\tlastWidth = width\n\t\tlastHeight = height\n\t\tlastFOV = FOV.Value()\n\n\t\tperspectiveMatrix = mgl32.Perspective(\n\t\t\t(math.Pi\/180)*float32(lastFOV),\n\t\t\tfloat32(width)\/float32(height),\n\t\t\t0.1,\n\t\t\t500.0,\n\t\t)\n\t\tgl.Viewport(0, 0, width, height)\n\t\tfrustum.SetPerspective(\n\t\t\t(math.Pi\/180)*float32(lastFOV),\n\t\t\tfloat32(width)\/float32(height),\n\t\t\t0.1,\n\t\t\t500.0,\n\t\t)\n\t\tinitTrans()\n\t}\n\n\tmainFramebuffer.Bind()\n\tgl.Enable(gl.Multisample)\n\n\tgl.ActiveTexture(0)\n\tglTexture.Bind(gl.Texture2DArray)\n\n\tgl.ClearColor(ClearColour.R, ClearColour.G, ClearColour.B, 1.0)\n\tgl.Clear(gl.ColorBufferBit | gl.DepthBufferBit)\n\n\tchunkProgram.Use()\n\n\tviewVector = mgl32.Vec3{\n\t\tfloat32(math.Cos(Camera.Yaw-math.Pi\/2) * -math.Cos(Camera.Pitch)),\n\t\tfloat32(-math.Sin(Camera.Pitch)),\n\t\tfloat32(-math.Sin(Camera.Yaw-math.Pi\/2) * -math.Cos(Camera.Pitch)),\n\t}\n\tcam := mgl32.Vec3{-float32(Camera.X), -float32(Camera.Y), float32(Camera.Z)}\n\tcameraMatrix = mgl32.LookAtV(\n\t\tcam,\n\t\tcam.Add(mgl32.Vec3{-viewVector.X(), -viewVector.Y(), viewVector.Z()}),\n\t\tmgl32.Vec3{0, -1, 0},\n\t)\n\tcameraMatrix = cameraMatrix.Mul4(mgl32.Scale3D(-1.0, 1.0, 1.0))\n\n\tfrustum.SetCamera(\n\t\tcam,\n\t\tcam.Add(mgl32.Vec3{-viewVector.X(), -viewVector.Y(), viewVector.Z()}),\n\t\tmgl32.Vec3{0, -1, 0},\n\t)\n\n\tshaderChunk.PerspectiveMatrix.Matrix4(&perspectiveMatrix)\n\tshaderChunk.CameraMatrix.Matrix4(&cameraMatrix)\n\tshaderChunk.Texture.Int(0)\n\tshaderChunk.LightLevel.Float(LightLevel)\n\tshaderChunk.SkyOffset.Float(SkyOffset)\n\n\tchunkPos := position{\n\t\tX: int(Camera.X) >> 4,\n\t\tY: int(Camera.Y) >> 4,\n\t\tZ: int(Camera.Z) >> 4,\n\t}\n\tnearestBuffer = buffers[chunkPos]\n\n\tfor _, dir := range direction.Values {\n\t\tvalidDirs[dir] = viewVector.Dot(dir.AsVec()) > -0.8\n\t}\n\n\trenderOrder = renderOrder[:0]\n\trenderBuffer(nearestBuffer, chunkPos, direction.Invalid, delta)\n\n\tdrawLines()\n\tdrawModels()\n\tclouds.tick(delta)\n\n\tchunkProgramT.Use()\n\tshaderChunkT.PerspectiveMatrix.Matrix4(&perspectiveMatrix)\n\tshaderChunkT.CameraMatrix.Matrix4(&cameraMatrix)\n\tshaderChunkT.Texture.Int(0)\n\tshaderChunkT.LightLevel.Float(LightLevel)\n\tshaderChunkT.SkyOffset.Float(SkyOffset)\n\n\t\/\/ Copy the depth buffer\n\tmainFramebuffer.BindRead()\n\ttransFramebuffer.BindDraw()\n\tgl.BlitFramebuffer(\n\t\t0, 0, lastWidth, lastHeight,\n\t\t0, 0, lastWidth, lastHeight,\n\t\tgl.DepthBufferBit, gl.Nearest,\n\t)\n\n\tgl.Enable(gl.Blend)\n\tgl.DepthMask(false)\n\ttransFramebuffer.Bind()\n\tgl.ClearColor(0, 0, 0, 1)\n\tgl.Clear(gl.ColorBufferBit)\n\tgl.ClearBuffer(gl.Color, 0, []float32{0, 0, 0, 1})\n\tgl.ClearBuffer(gl.Color, 1, []float32{0, 0, 0, 0})\n\tgl.BlendFuncSeparate(gl.OneFactor, gl.OneFactor, gl.ZeroFactor, gl.OneMinusSrcAlpha)\n\tfor _, chunk := range renderOrder {\n\t\tif chunk.countT > 0 && chunk.bufferT.IsValid() {\n\t\t\tshaderChunkT.Offset.Int3(chunk.X, chunk.Y*4096-chunk.Y*int(4096*(1-chunk.progress)), chunk.Z)\n\n\t\t\tchunk.arrayT.Bind()\n\t\t\tgl.DrawElements(gl.Triangles, chunk.countT, elementBufferType, 0)\n\t\t}\n\t}\n\n\tgl.UnbindFramebuffer()\n\tgl.Disable(gl.DepthTest)\n\tgl.Clear(gl.ColorBufferBit)\n\tgl.Disable(gl.Blend)\n\n\ttransDraw()\n\n\tgl.Enable(gl.DepthTest)\n\tgl.DepthMask(true)\n\tgl.BlendFunc(gl.SrcAlpha, gl.OneMinusSrcAlpha)\n\tgl.Disable(gl.Multisample)\n\n\tdrawUI()\n\n\tif debugFramebuffers.Value() {\n\t\tgl.Enable(gl.Multisample)\n\t\tblitBuffers()\n\t\tgl.Disable(gl.Multisample)\n\t}\n}\n\nvar (\n\trenderOrder []*ChunkBuffer\n\tvalidDirs   = make([]bool, len(direction.Values))\n)\n\ntype renderRequest struct {\n\tchunk *ChunkBuffer\n\tpos   position\n\tfrom  direction.Type\n}\n\nconst (\n\trenderQueueSize = 5000\n)\n\nvar rQueue renderQueue\n\nfunc renderBuffer(ch *ChunkBuffer, po position, fr direction.Type, delta float64) {\n\tif ch == nil {\n\t\treturn\n\t}\n\trQueue.Append(renderRequest{ch, po, fr})\n\n\tslidy := slidyChunks.Value()\n\n\tfor !rQueue.Empty() {\n\t\treq := rQueue.Take()\n\t\tif req.chunk.renderedOn == frameID {\n\t\t\tcontinue\n\t\t}\n\t\treq.chunk.renderedOn = frameID\n\n\t\taabb := vmath.NewAABB(\n\t\t\t-float32((req.pos.X<<4)+16), -float32((req.pos.Y<<4)+16), float32((req.pos.Z<<4)),\n\t\t\t-float32((req.pos.X<<4)), -float32((req.pos.Y<<4)), float32((req.pos.Z<<4)+16),\n\t\t).Grow(1, 1, 1)\n\t\tif !frustum.IsAABBInside(aabb) {\n\t\t\tcontinue\n\t\t}\n\t\trenderOrder = append(renderOrder, req.chunk)\n\n\t\treq.chunk.Rendered = true\n\n\t\tif slidy {\n\t\t\tdx := req.pos.X - int(Camera.X)>>4\n\t\t\tdz := req.pos.Z - int(Camera.Z)>>4\n\n\t\t\tif req.chunk.progress < 1 && dx*dx+dz*dz > 6*6 {\n\t\t\t\treq.chunk.progress += delta * 0.015\n\t\t\t} else {\n\t\t\t\treq.chunk.progress = 1\n\t\t\t}\n\t\t} else {\n\t\t\treq.chunk.progress = 1\n\t\t}\n\n\t\tif req.chunk.count != 0 && req.chunk.buffer.IsValid() {\n\t\t\tshaderChunk.Offset.Int3(req.chunk.X, req.chunk.Y*4096-req.chunk.Y*int(4096*(1-req.chunk.progress)), req.chunk.Z)\n\n\t\t\treq.chunk.array.Bind()\n\t\t\tgl.DrawElements(gl.Triangles, req.chunk.count, elementBufferType, 0)\n\t\t}\n\n\t\tfor _, dir := range direction.Values {\n\t\t\tc := req.chunk.neighborChunks[dir]\n\t\t\tif dir != req.from && c != nil && c.renderedOn != frameID &&\n\t\t\t\t(req.from == direction.Invalid || (req.chunk.IsVisible(req.from, dir) && validDirs[dir])) {\n\t\t\t\tox, oy, oz := dir.Offset()\n\t\t\t\tpos := position{req.pos.X + ox, req.pos.Y + oy, req.pos.Z + oz}\n\t\t\t\trQueue.Append(renderRequest{c, pos, dir.Opposite()})\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Sync runs the passed function on the next frame on the same goroutine\n\/\/ as the renderer.\nfunc Sync(f func()) {\n\tsyncChan <- f\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Make `SyscallTable.lookup` be a fixed-size array rather than a slice.<commit_after><|endoftext|>"}
{"text":"<commit_before>\/*\nPackage reportsockets implements a websocket interface where all the clients\nget the same data.\n\nIt internally works like a publish\/subscribe model where each websocket\nconnection subscribe to a publisher.\n\nIt implements the http.Handler interface so you can use it with the standard net\/http.\n\nTo use it, you first need to declare the channel or exchange.\n\n\texchange := reportsockets.New()\n\nTo tie it to a url, use the standard http.\n\n\thttp.Handle(\"\/report\", exchange.Handler()\n\nTo send messages to all the clients:\n\n\tmsg := \"Hello world\"\n\texchange.Publish(&msg)\n\nOther thing that you can do is declare a handler for reciving client messages.\n\n\tfunc myFunc(msg []byte, ws *websocket.Conn, exchange *reportsockets.Exchange){\n\t  ...\n\t  \/\/ You can responds to the specific client:\n\t  ws.Write(myData)\n\t  \/e\/ Or send a messages to other clients.\n\t  exchagne.Publish(msg)\n\t}\n\n\texchange.ClientMessageHandler = myFunc\n\nIf you don't define that method, all the client messages will be ignored.\n*\/\npackage reportsockets\n\nimport (\n\t\"code.google.com\/p\/go.net\/websocket\"\n\t\"net\/http\"\n)\n\ntype Exchange struct {\n\tClientMessageHandler func(msg []byte, ws *websocket.Conn, exchange *Exchange)\n\tclients              []*websocket.Conn\n\tnewClientChan        chan *websocket.Conn\n\tpublishChan          chan []byte\n\tremoveClientChan     chan *websocket.Conn\n\tstopChan             chan bool\n}\n\nfunc New() *Exchange {\n\te := new(Exchange)\n\te.clients = make([]*websocket.Conn, 0)\n\te.newClientChan = make(chan *websocket.Conn)\n\te.publishChan = make(chan []byte)\n\te.stopChan = make(chan bool)\n\te.removeClientChan = make(chan *websocket.Conn)\n\tgo e.loop()\n\treturn e\n}\n\nfunc (e *Exchange) loop() {\n\nforLoop:\n\tfor {\n\t\tselect {\n\t\tcase newClient := <-e.newClientChan:\n\t\t\te.clients = append(e.clients, newClient)\n\t\tcase msg := <-e.publishChan:\n\t\t\tfor i, client := range e.clients {\n\t\t\t\t_, err := client.Write(msg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tclient.Close()\n\t\t\t\t\te.clients = append(e.clients[:i], e.clients[(i+1):]...)\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-e.stopChan:\n\t\t\tfor _, client := range e.clients {\n\t\t\t\tclient.Close()\n\t\t\t}\n\t\t\tbreak forLoop\n\t\tcase oldWs := <-e.removeClientChan:\n\t\t\tfor i, ws := range e.clients {\n\t\t\t\tif oldWs == ws {\n\t\t\t\t\te.clients = append(e.clients[:i], e.clients[(i+1):]...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor _ = range e.clients {\n\t\t<-e.removeClientChan\n\t}\n\te.clients = e.clients[0:0]\n}\n\nfunc (e *Exchange) Handler() http.Handler {\n\t\/\/ ws.Close will be called when returning from this func\n\thandler := func(ws *websocket.Conn) {\n\t\te.newClientChan <- ws\n\t\tfor {\n\t\t\tdata := make([]byte, 1024*10)\n\t\t\t_, err := ws.Read(data)\n\t\t\tif err != nil {\n\t\t\t\te.removeClientChan <- ws\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif e.ClientMessageHandler != nil {\n\t\t\t\te.ClientMessageHandler(data, ws, e)\n\t\t\t}\n\t\t}\n\t}\n\treturn websocket.Handler(handler)\n}\n\nfunc (e *Exchange) Publish(msg []byte) {\n\te.publishChan <- msg\n}\n\nfunc (e *Exchange) Stop() {\n\te.stopChan <- true\n}\n<commit_msg>Improve docs<commit_after>\/*\nPackage reportsockets implements a websocket interface where all the clients\nget the same data.\n\nIt internally works like a publish\/subscribe model where each websocket\nconnection subscribe to a publisher.\n\nIt implements the http.Handler interface so you can use it with the standard net\/http.\n\nTo use it, you first need to declare the channel or exchange.\n\n\texchange := reportsockets.New()\n\nTo tie it to a url, use the standard http.\n\n\thttp.Handle(\"\/report\", exchange.Handler())\n\nTo send messages to all the clients:\n\n\tmsg := \"Hello world\"\n\texchange.Publish(&msg)\n\nOther thing that you can do is declare a handler for reciving client messages.\n\n\tfunc myFunc(msg []byte, ws *websocket.Conn, exchange *reportsockets.Exchange){\n\t  ...\n\t  \/\/ You can responds to the specific client:\n\t  ws.Write(myData)\n\t  \/e\/ Or send a messages to other clients.\n\t  exchagne.Publish(msg)\n\t}\n\n\texchange.ClientMessageHandler = myFunc\n\nIf you don't define that method, all the client messages will be ignored.\n\nOnce you are done, you can close it with Stop.\n\n\texchange.Stop()\n\nThis will close all the websocket connections\n*\/\npackage reportsockets\n\nimport (\n\t\"code.google.com\/p\/go.net\/websocket\"\n\t\"net\/http\"\n)\n\n\/\/ Exchange represent the main point to subscribe\ntype Exchange struct {\n\tClientMessageHandler func(msg []byte, ws *websocket.Conn, exchange *Exchange)\n\tclients              []*websocket.Conn\n\tnewClientChan        chan *websocket.Conn\n\tpublishChan          chan []byte\n\tremoveClientChan     chan *websocket.Conn\n\tstopChan             chan bool\n}\n\n\/\/ New return a new exchange\nfunc New() *Exchange {\n\te := new(Exchange)\n\te.clients = make([]*websocket.Conn, 0)\n\te.newClientChan = make(chan *websocket.Conn)\n\te.publishChan = make(chan []byte)\n\te.stopChan = make(chan bool)\n\te.removeClientChan = make(chan *websocket.Conn)\n\tgo e.loop()\n\treturn e\n}\n\nfunc (e *Exchange) loop() {\nforLoop:\n\tfor {\n\t\tselect {\n\t\tcase newClient := <-e.newClientChan:\n\t\t\te.clients = append(e.clients, newClient)\n\t\tcase msg := <-e.publishChan:\n\t\t\tfor i, client := range e.clients {\n\t\t\t\t_, err := client.Write(msg)\n\t\t\t\tif err != nil {\n\t\t\t\t\tclient.Close()\n\t\t\t\t\te.clients = append(e.clients[:i], e.clients[(i+1):]...)\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-e.stopChan:\n\t\t\tfor _, client := range e.clients {\n\t\t\t\tclient.Close()\n\t\t\t}\n\t\t\tbreak forLoop\n\t\tcase oldWs := <-e.removeClientChan:\n\t\t\tfor i, ws := range e.clients {\n\t\t\t\tif oldWs == ws {\n\t\t\t\t\te.clients = append(e.clients[:i], e.clients[(i+1):]...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor _ = range e.clients {\n\t\t<-e.removeClientChan\n\t}\n\te.clients = e.clients[0:0]\n}\n\n\/\/ Handler return the http handler for this exchange.\nfunc (e *Exchange) Handler() http.Handler {\n\t\/\/ ws.Close will be called when returning from this func\n\thandler := func(ws *websocket.Conn) {\n\t\te.newClientChan <- ws\n\t\tfor {\n\t\t\tdata := make([]byte, 1024*10)\n\t\t\t_, err := ws.Read(data)\n\t\t\tif err != nil {\n\t\t\t\te.removeClientChan <- ws\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif e.ClientMessageHandler != nil {\n\t\t\t\te.ClientMessageHandler(data, ws, e)\n\t\t\t}\n\t\t}\n\t}\n\treturn websocket.Handler(handler)\n}\n\n\/\/ Publish Broadcast the message to all the clients\nfunc (e *Exchange) Publish(msg []byte) {\n\te.publishChan <- msg\n}\n\n\/\/ Stop will stop the exchange and close all the ws connections\nfunc (e *Exchange) Stop() {\n\te.stopChan <- true\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"os\"\n\n\t\"gopkg.in\/src-d\/go-kallax.v1\/generator\/cli\/kallax\/cmd\"\n\n\t\"gopkg.in\/urfave\/cli.v1\"\n)\n\nconst version = \"1.2.2\"\n\nfunc main() {\n\tnewApp().Run(os.Args)\n}\n\nfunc newApp() *cli.App {\n\tapp := cli.NewApp()\n\tapp.Name = \"kallax\"\n\tapp.Version = version\n\tapp.Usage = \"generate kallax models\"\n\tapp.Flags = cmd.Generate.Flags\n\tapp.Action = cmd.Generate.Action\n\tapp.Commands = cli.Commands{\n\t\tcmd.Generate,\n\t\tcmd.Migrate,\n\t}\n\n\treturn app\n}\n<commit_msg>Update cmd.go<commit_after>package main\n\nimport (\n\t\"os\"\n\n\t\"gopkg.in\/src-d\/go-kallax.v1\/generator\/cli\/kallax\/cmd\"\n\n\t\"gopkg.in\/urfave\/cli.v1\"\n)\n\nconst version = \"1.2.3\"\n\nfunc main() {\n\tnewApp().Run(os.Args)\n}\n\nfunc newApp() *cli.App {\n\tapp := cli.NewApp()\n\tapp.Name = \"kallax\"\n\tapp.Version = version\n\tapp.Usage = \"generate kallax models\"\n\tapp.Flags = cmd.Generate.Flags\n\tapp.Action = cmd.Generate.Action\n\tapp.Commands = cli.Commands{\n\t\tcmd.Generate,\n\t\tcmd.Migrate,\n\t}\n\n\treturn app\n}\n<|endoftext|>"}
{"text":"<commit_before>package drum\n\nimport (\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n)\n\n\/\/ DecodeFile decodes the drum machine file found at the provided path\n\/\/ and returns a pointer to a parsed pattern which is the entry point to the\n\/\/ rest of the data.\nfunc DecodeFile(path string) (*Pattern, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp := &Pattern{}\n\tif err := NewDecoder(file).Decode(p); err != nil {\n\t\tlog.Fatal(err)\n\t\treturn nil, err\n\t}\n\n\treturn p, nil\n}\n\n\/\/ Decoder reads and decodes splice patterns from an input stream\ntype Decoder struct {\n\tio.Reader\n}\n\n\/\/ NewDecoder returns a new decoder that reads from r\nfunc NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{r}\n}\n\n\/\/ Decode reads the input stream and decodes it's values into a Pattern\nfunc (d *Decoder) Decode(p *Pattern) error {\n\tn, err := d.spliceHeaderInfo()\n\tif err != nil {\n\t\tif err != io.EOF && err != io.ErrUnexpectedEOF {\n\t\t\treturn errors.New(\"unable to decode .splice file header: \" + err.Error())\n\t\t}\n\t}\n\n\tif err := d.decodeBody(p, n); err != nil {\n\t\tif err != io.EOF && err != io.ErrUnexpectedEOF {\n\t\t\treturn errors.New(\"unable to decode .splice format: \" + err.Error())\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ spliceHeaderInfo will read the inital bites\n\/\/ and returns the size of the file contents or error if it's\n\/\/ unable check the SPLICE portion or read the headers\nfunc (d *Decoder) spliceHeaderInfo() (int64, error) {\n\thdr := make([]byte, 6)\n\tif _, err := io.ReadFull(d, hdr); err != nil {\n\t\treturn 0, err\n\t}\n\tif string(hdr) != \"SPLICE\" {\n\t\treturn 0, errors.New(\"unable to decode non SPLICE files\")\n\t}\n\n\tvar size int64\n\tif err := binary.Read(d, binary.BigEndian, &size); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn size, nil\n}\n\n\/\/ decodeBody reads the contents of the input stream up to size\n\/\/ and into p. It returns EOF or ErrUnexpectedEOF if it reads over\n\/\/ size.\nfunc (d *Decoder) decodeBody(p *Pattern, size int64) error {\n\tversion := make([]byte, 32)\n\tif _, err := io.ReadFull(d, version); err != nil {\n\t\treturn errors.New(\"unable to decode hw version: \" + err.Error())\n\t}\n\tp.Version = strings.Trim(string(version), \"\\x00\")\n\n\tif err := binary.Read(d, binary.LittleEndian, &p.Tempo); err != nil {\n\t\treturn errors.New(\"unable to decode tempo: \" + err.Error())\n\t}\n\n\t\/\/ version and tempo\n\tsize -= (32 + 4)\n\n\t\/\/ decode the tracks\n\tfor size >= 0 {\n\t\tt := Track{}\n\t\tif err := binary.Read(d, binary.BigEndian, &t.ID); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar nameLen int32\n\t\tif err := binary.Read(d, binary.BigEndian, &nameLen); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tname := make([]byte, nameLen)\n\t\tif _, err := io.ReadFull(d, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tt.Name = string(name)\n\n\t\tsteps := make([]byte, measureCount)\n\t\tif err := binary.Read(d, binary.BigEndian, steps); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ convert steps into 'x' or '-' runes\n\t\tfor idx, step := range steps {\n\t\t\tif step == 1 {\n\t\t\t\tsteps[idx] = 'x'\n\t\t\t} else {\n\t\t\t\tsteps[idx] = '-'\n\t\t\t}\n\t\t}\n\t\tt.Steps = steps\n\n\t\tp.Tracks = append(p.Tracks, t)\n\t\t\/\/ ID, nameLen, measureCount, and size of name\n\t\tsize -= (1 + 4 + measureCount + int64(len(name)))\n\t}\n\n\treturn nil\n}\n<commit_msg>Remove leftover log.Fatal<commit_after>package drum\n\nimport (\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n)\n\n\/\/ DecodeFile decodes the drum machine file found at the provided path\n\/\/ and returns a pointer to a parsed pattern which is the entry point to the\n\/\/ rest of the data.\nfunc DecodeFile(path string) (*Pattern, error) {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp := &Pattern{}\n\tif err := NewDecoder(file).Decode(p); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn p, nil\n}\n\n\/\/ Decoder reads and decodes splice patterns from an input stream\ntype Decoder struct {\n\tio.Reader\n}\n\n\/\/ NewDecoder returns a new decoder that reads from r\nfunc NewDecoder(r io.Reader) *Decoder {\n\treturn &Decoder{r}\n}\n\n\/\/ Decode reads the input stream and decodes it's values into a Pattern\nfunc (d *Decoder) Decode(p *Pattern) error {\n\tn, err := d.spliceHeaderInfo()\n\tif err != nil {\n\t\tif err != io.EOF && err != io.ErrUnexpectedEOF {\n\t\t\treturn errors.New(\"unable to decode .splice file header: \" + err.Error())\n\t\t}\n\t}\n\n\tif err := d.decodeBody(p, n); err != nil {\n\t\tif err != io.EOF && err != io.ErrUnexpectedEOF {\n\t\t\treturn errors.New(\"unable to decode .splice format: \" + err.Error())\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ spliceHeaderInfo will read the inital bites\n\/\/ and returns the size of the file contents or error if it's\n\/\/ unable check the SPLICE portion or read the headers\nfunc (d *Decoder) spliceHeaderInfo() (int64, error) {\n\thdr := make([]byte, 6)\n\tif _, err := io.ReadFull(d, hdr); err != nil {\n\t\treturn 0, err\n\t}\n\tif string(hdr) != \"SPLICE\" {\n\t\treturn 0, errors.New(\"unable to decode non SPLICE files\")\n\t}\n\n\tvar size int64\n\tif err := binary.Read(d, binary.BigEndian, &size); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn size, nil\n}\n\n\/\/ decodeBody reads the contents of the input stream up to size\n\/\/ and into p. It returns EOF or ErrUnexpectedEOF if it reads over\n\/\/ size.\nfunc (d *Decoder) decodeBody(p *Pattern, size int64) error {\n\tversion := make([]byte, 32)\n\tif _, err := io.ReadFull(d, version); err != nil {\n\t\treturn errors.New(\"unable to decode hw version: \" + err.Error())\n\t}\n\tp.Version = strings.Trim(string(version), \"\\x00\")\n\n\tif err := binary.Read(d, binary.LittleEndian, &p.Tempo); err != nil {\n\t\treturn errors.New(\"unable to decode tempo: \" + err.Error())\n\t}\n\n\t\/\/ version and tempo\n\tsize -= (32 + 4)\n\n\t\/\/ decode the tracks\n\tfor size >= 0 {\n\t\tt := Track{}\n\t\tif err := binary.Read(d, binary.BigEndian, &t.ID); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar nameLen int32\n\t\tif err := binary.Read(d, binary.BigEndian, &nameLen); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tname := make([]byte, nameLen)\n\t\tif _, err := io.ReadFull(d, name); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tt.Name = string(name)\n\n\t\tsteps := make([]byte, measureCount)\n\t\tif err := binary.Read(d, binary.BigEndian, steps); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ convert steps into 'x' or '-' runes\n\t\tfor idx, step := range steps {\n\t\t\tif step == 1 {\n\t\t\t\tsteps[idx] = 'x'\n\t\t\t} else {\n\t\t\t\tsteps[idx] = '-'\n\t\t\t}\n\t\t}\n\t\tt.Steps = steps\n\n\t\tp.Tracks = append(p.Tracks, t)\n\t\t\/\/ ID, nameLen, measureCount, and size of name\n\t\tsize -= (1 + 4 + measureCount + int64(len(name)))\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package wav\n\nimport (\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"time\"\n\n\t\"github.com\/go-audio\/audio\"\n\t\"github.com\/mattetti\/audio\/riff\"\n)\n\n\/\/ Decoder handles the decoding of wav files.\ntype Decoder struct {\n\tr      io.ReadSeeker\n\tparser *riff.Parser\n\n\tNumChans   uint16\n\tBitDepth   uint16\n\tSampleRate uint32\n\n\tAvgBytesPerSec uint32\n\tWavAudioFormat uint16\n\n\terr             error\n\tPCMSize         int\n\tpcmDataAccessed bool\n\t\/\/ pcmChunk is available so we can use the LimitReader\n\tPCMChunk *riff.Chunk\n}\n\n\/\/ NewDecoder creates a decoder for the passed wav reader.\n\/\/ Note that the reader doesn't get rewinded as the container is processed.\nfunc NewDecoder(r io.ReadSeeker) *Decoder {\n\treturn &Decoder{\n\t\tr:      r,\n\t\tparser: riff.New(r),\n\t}\n}\n\n\/\/ SampleBitDepth returns the bit depth encoding of each sample.\nfunc (d *Decoder) SampleBitDepth() int32 {\n\tif d == nil {\n\t\treturn 0\n\t}\n\treturn int32(d.BitDepth)\n}\n\n\/\/ PCMLen returns the total number of bytes in the PCM data chunk\nfunc (d *Decoder) PCMLen() int64 {\n\tif d == nil {\n\t\treturn 0\n\t}\n\treturn int64(d.PCMSize)\n}\n\n\/\/ Err returns the first non-EOF error that was encountered by the Decoder.\nfunc (d *Decoder) Err() error {\n\tif d.err == io.EOF {\n\t\treturn nil\n\t}\n\treturn d.err\n}\n\n\/\/ EOF returns positively if the underlying reader reached the end of file.\nfunc (d *Decoder) EOF() bool {\n\tif d == nil || d.err == io.EOF {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ IsValidFile verifies that the file is valid\/readable.\nfunc (d *Decoder) IsValidFile() bool {\n\td.err = d.readHeaders()\n\tif d.err != nil {\n\t\treturn false\n\t}\n\tif d.NumChans < 1 {\n\t\treturn false\n\t}\n\tif d.BitDepth < 8 {\n\t\treturn false\n\t}\n\tif d, err := d.Duration(); err != nil || d <= 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ ReadInfo reads the underlying reader until the comm header is parsed.\n\/\/ This method is safe to call multiple times.\nfunc (d *Decoder) ReadInfo() {\n\td.err = d.readHeaders()\n}\n\n\/\/ Reset resets the decoder (and rewind the underlying reader)\nfunc (d *Decoder) Reset() {\n\td.err = nil\n\td.pcmDataAccessed = false\n\td.NumChans = 0\n\td.BitDepth = 0\n\td.SampleRate = 0\n\td.AvgBytesPerSec = 0\n\td.WavAudioFormat = 0\n\td.PCMSize = 0\n\td.r.Seek(0, 0)\n\td.PCMChunk = nil\n\td.parser = riff.New(d.r)\n}\n\n\/\/ FwdToPCM forwards the underlying reader until the start of the PCM chunk.\n\/\/ If the PCM chunk was already read, no data will be found (you need to rewind).\nfunc (d *Decoder) FwdToPCM() error {\n\tif d == nil {\n\t\treturn fmt.Errorf(\"PCM data not found\")\n\t}\n\td.err = d.readHeaders()\n\tif d.err != nil {\n\t\treturn nil\n\t}\n\n\tvar chunk *riff.Chunk\n\tfor d.err == nil {\n\t\tchunk, d.err = d.NextChunk()\n\t\tif d.err != nil {\n\t\t\treturn d.err\n\t\t}\n\t\tif chunk.ID == riff.DataFormatID {\n\t\t\td.PCMSize = chunk.Size\n\t\t\td.PCMChunk = chunk\n\t\t\tbreak\n\t\t}\n\t\tchunk.Drain()\n\t}\n\tif chunk == nil {\n\t\treturn fmt.Errorf(\"PCM data not found\")\n\t}\n\td.pcmDataAccessed = true\n\n\treturn nil\n}\n\n\/\/ WasPCMAccessed returns positively if the PCM data was previously accessed.\nfunc (d *Decoder) WasPCMAccessed() bool {\n\tif d == nil {\n\t\treturn false\n\t}\n\treturn d.pcmDataAccessed\n}\n\n\/\/ FullPCMBuffer is an inneficient way to access all the PCM data contained in the\n\/\/ audio container. The entire PCM data is held in memory.\n\/\/ Consider using Buffer() instead.\nfunc (d *Decoder) FullPCMBuffer() (*audio.IntBuffer, error) {\n\tif !d.WasPCMAccessed() {\n\t\terr := d.FwdToPCM()\n\t\tif err != nil {\n\t\t\treturn nil, d.err\n\t\t}\n\t}\n\tif d.PCMChunk == nil {\n\t\treturn nil, errors.New(\"PCM chunk not found\")\n\t}\n\tformat := &audio.Format{\n\t\tNumChannels: int(d.NumChans),\n\t\tSampleRate:  int(d.SampleRate),\n\t}\n\n\tbuf := &audio.IntBuffer{Data: make([]int, 4096), Format: format, SourceBitDepth: int(d.BitDepth)}\n\tbytesPerSample := (d.BitDepth-1)\/8 + 1\n\tsampleBufData := make([]byte, bytesPerSample)\n\tdecodeF, err := sampleDecodeFunc(int(d.BitDepth))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get sample decode func %v\", err)\n\t}\n\n\ti := 0\n\tfor err == nil {\n\t\t_, err = d.PCMChunk.Read(sampleBufData)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tbuf.Data[i] = decodeF(sampleBufData)\n\t\ti++\n\t\t\/\/ grow the underlying slice if needed\n\t\tif i == len(buf.Data) {\n\t\t\tbuf.Data = append(buf.Data, make([]int, 4096)...)\n\t\t}\n\t}\n\tbuf.Data = buf.Data[:i]\n\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\n\treturn buf, err\n}\n\n\/\/ PCMBuffer populates the passed PCM buffer\nfunc (d *Decoder) PCMBuffer(buf *audio.IntBuffer) (n int, err error) {\n\tif buf == nil {\n\t\treturn 0, nil\n\t}\n\n\tif !d.pcmDataAccessed {\n\t\terr := d.FwdToPCM()\n\t\tif err != nil {\n\t\t\treturn 0, d.err\n\t\t}\n\t}\n\n\tbytesPerSample := (d.BitDepth-1)\/8 + 1\n\tsampleBufData := make([]byte, bytesPerSample)\n\tdecodeF, err := sampleDecodeFunc(int(d.BitDepth))\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"could not get sample decode func %v\", err)\n\t}\n\n\t\/\/ Note that we populate the buffer even if the\n\t\/\/ size of the buffer doesn't fit an even number of frames.\n\tfor n = 0; n < len(buf.Data); n++ {\n\t\t_, err = d.PCMChunk.Read(sampleBufData)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tbuf.Data[n] = decodeF(sampleBufData)\n\t}\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\tbuf.Format = d.Format()\n\tbuf.SourceBitDepth = int(d.BitDepth)\n\n\treturn n, err\n}\n\n\/\/ Format returns the audio format of the decoded content.\nfunc (d *Decoder) Format() *audio.Format {\n\tif d == nil {\n\t\treturn nil\n\t}\n\treturn &audio.Format{\n\t\tNumChannels: int(d.NumChans),\n\t\tSampleRate:  int(d.SampleRate),\n\t}\n}\n\n\/\/ NextChunk returns the next available chunk\nfunc (d *Decoder) NextChunk() (*riff.Chunk, error) {\n\tif d.err = d.readHeaders(); d.err != nil {\n\t\td.err = fmt.Errorf(\"failed to read header - %v\", d.err)\n\t\treturn nil, d.err\n\t}\n\n\tvar (\n\t\tid   [4]byte\n\t\tsize uint32\n\t)\n\n\tid, size, d.err = d.parser.IDnSize()\n\tif d.err != nil {\n\t\td.err = fmt.Errorf(\"error reading chunk header - %v\", d.err)\n\t\treturn nil, d.err\n\t}\n\n\tc := &riff.Chunk{\n\t\tID:   id,\n\t\tSize: int(size),\n\t\tR:    io.LimitReader(d.r, int64(size)),\n\t}\n\treturn c, d.err\n}\n\n\/\/ Duration returns the time duration for the current audio container\nfunc (d *Decoder) Duration() (time.Duration, error) {\n\tif d == nil || d.parser == nil {\n\t\treturn 0, errors.New(\"can't calculate the duration of a nil pointer\")\n\t}\n\treturn d.parser.Duration()\n}\n\n\/\/ String implements the Stringer interface.\nfunc (d *Decoder) String() string {\n\treturn d.parser.String()\n}\n\n\/\/ readHeaders is safe to call multiple times\nfunc (d *Decoder) readHeaders() error {\n\tif d == nil || d.NumChans > 0 {\n\t\treturn nil\n\t}\n\n\tid, size, err := d.parser.IDnSize()\n\tif err != nil {\n\t\treturn err\n\t}\n\td.parser.ID = id\n\tif d.parser.ID != riff.RiffID {\n\t\treturn fmt.Errorf(\"%s - %s\", d.parser.ID, riff.ErrFmtNotSupported)\n\t}\n\td.parser.Size = size\n\tif err := binary.Read(d.r, binary.BigEndian, &d.parser.Format); err != nil {\n\t\treturn err\n\t}\n\n\tvar chunk *riff.Chunk\n\tvar rewindBytes int64\n\n\tfor err == nil {\n\t\tchunk, err = d.parser.NextChunk()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif chunk.ID == riff.FmtID {\n\t\t\tchunk.DecodeWavHeader(d.parser)\n\t\t\td.NumChans = d.parser.NumChannels\n\t\t\td.BitDepth = d.parser.BitsPerSample\n\t\t\td.SampleRate = d.parser.SampleRate\n\t\t\td.WavAudioFormat = d.parser.WavAudioFormat\n\t\t\td.AvgBytesPerSec = d.parser.AvgBytesPerSec\n\n\t\t\tif rewindBytes > 0 {\n\t\t\t\td.r.Seek(-(rewindBytes + int64(chunk.Size) + 8), 1)\n\t\t\t}\n\t\t\tbreak\n\t\t} else {\n\t\t\t\/\/ unexpected chunk order, might be a bext chunk\n\t\t\trewindBytes += int64(chunk.Size) + 8\n\t\t\t\/\/ drain the chunk\n\t\t\tio.CopyN(ioutil.Discard, d.r, int64(chunk.Size))\n\t\t}\n\n\t}\n\n\treturn d.err\n}\n\n\/\/ sampleDecodeFunc returns a function that can be used to convert\n\/\/ a byte range into an int value based on the amount of bits used per sample.\n\/\/ Note that 8bit samples are unsigned, all other values are signed.\nfunc sampleDecodeFunc(bitsPerSample int) (func([]byte) int, error) {\n\t\/\/ NOTE: WAV PCM data is stored using little-endian\n\tswitch bitsPerSample {\n\tcase 8:\n\t\t\/\/ 8bit values are unsigned\n\t\treturn func(s []byte) int {\n\t\t\treturn int(uint8(s[0]))\n\t\t}, nil\n\tcase 16:\n\t\t\/\/ -32,768\t(0x7FFF) to\t32,767\t(0x8000)\n\t\treturn func(s []byte) int {\n\t\t\treturn int(int16(binary.LittleEndian.Uint16(s)))\n\t\t}, nil\n\tcase 24:\n\t\t\/\/ -34,359,738,367 (0x7FFFFF) to 34,359,738,368\t(0x800000)\n\t\treturn func(s []byte) int {\n\t\t\treturn int(audio.Int24LETo32(s))\n\t\t}, nil\n\tcase 32:\n\t\treturn func(s []byte) int {\n\t\t\treturn int(s[0]) + int(s[1])<<8 + int(s[2])<<16 + int(s[3])<<24\n\t\t}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unhandled byte depth:%d\", bitsPerSample)\n\t}\n}\n\n\/\/ sampleDecodeFloat64Func returns a function that can be used to convert\n\/\/ a byte range into a float64 value based on the amount of bits used per sample.\nfunc sampleFloat64DecodeFunc(bitsPerSample int) (func([]byte) float64, error) {\n\tbytesPerSample := bitsPerSample \/ 8\n\tswitch bytesPerSample {\n\tcase 1:\n\t\t\/\/ 8bit values are unsigned\n\t\treturn func(s []byte) float64 {\n\t\t\treturn float64(uint8(s[0]))\n\t\t}, nil\n\tcase 2:\n\t\treturn func(s []byte) float64 {\n\t\t\treturn float64(int(s[0]) + int(s[1])<<8)\n\t\t}, nil\n\tcase 3:\n\t\treturn func(s []byte) float64 {\n\t\t\tvar output int32\n\t\t\toutput |= int32(s[2]) << 0\n\t\t\toutput |= int32(s[1]) << 8\n\t\t\toutput |= int32(s[0]) << 16\n\t\t\treturn float64(output)\n\t\t}, nil\n\tcase 4:\n\t\t\/\/ TODO: fix the float64 conversion (current int implementation)\n\t\treturn func(s []byte) float64 {\n\t\t\treturn float64(int(s[0]) + int(s[1])<<8 + int(s[2])<<16 + int(s[3])<<24)\n\t\t}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unhandled byte depth:%d\", bitsPerSample)\n\t}\n}\n<commit_msg>around 20x performance improvement to read PCM buffers (dependending on the size)<commit_after>package wav\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"time\"\n\n\t\"github.com\/go-audio\/audio\"\n\t\"github.com\/mattetti\/audio\/riff\"\n)\n\n\/\/ Decoder handles the decoding of wav files.\ntype Decoder struct {\n\tr      io.ReadSeeker\n\tparser *riff.Parser\n\n\tNumChans   uint16\n\tBitDepth   uint16\n\tSampleRate uint32\n\n\tAvgBytesPerSec uint32\n\tWavAudioFormat uint16\n\n\terr             error\n\tPCMSize         int\n\tpcmDataAccessed bool\n\t\/\/ pcmChunk is available so we can use the LimitReader\n\tPCMChunk *riff.Chunk\n}\n\n\/\/ NewDecoder creates a decoder for the passed wav reader.\n\/\/ Note that the reader doesn't get rewinded as the container is processed.\nfunc NewDecoder(r io.ReadSeeker) *Decoder {\n\treturn &Decoder{\n\t\tr:      r,\n\t\tparser: riff.New(r),\n\t}\n}\n\n\/\/ SampleBitDepth returns the bit depth encoding of each sample.\nfunc (d *Decoder) SampleBitDepth() int32 {\n\tif d == nil {\n\t\treturn 0\n\t}\n\treturn int32(d.BitDepth)\n}\n\n\/\/ PCMLen returns the total number of bytes in the PCM data chunk\nfunc (d *Decoder) PCMLen() int64 {\n\tif d == nil {\n\t\treturn 0\n\t}\n\treturn int64(d.PCMSize)\n}\n\n\/\/ Err returns the first non-EOF error that was encountered by the Decoder.\nfunc (d *Decoder) Err() error {\n\tif d.err == io.EOF {\n\t\treturn nil\n\t}\n\treturn d.err\n}\n\n\/\/ EOF returns positively if the underlying reader reached the end of file.\nfunc (d *Decoder) EOF() bool {\n\tif d == nil || d.err == io.EOF {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ IsValidFile verifies that the file is valid\/readable.\nfunc (d *Decoder) IsValidFile() bool {\n\td.err = d.readHeaders()\n\tif d.err != nil {\n\t\treturn false\n\t}\n\tif d.NumChans < 1 {\n\t\treturn false\n\t}\n\tif d.BitDepth < 8 {\n\t\treturn false\n\t}\n\tif d, err := d.Duration(); err != nil || d <= 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\n\/\/ ReadInfo reads the underlying reader until the comm header is parsed.\n\/\/ This method is safe to call multiple times.\nfunc (d *Decoder) ReadInfo() {\n\td.err = d.readHeaders()\n}\n\n\/\/ Reset resets the decoder (and rewind the underlying reader)\nfunc (d *Decoder) Reset() {\n\td.err = nil\n\td.pcmDataAccessed = false\n\td.NumChans = 0\n\td.BitDepth = 0\n\td.SampleRate = 0\n\td.AvgBytesPerSec = 0\n\td.WavAudioFormat = 0\n\td.PCMSize = 0\n\td.r.Seek(0, 0)\n\td.PCMChunk = nil\n\td.parser = riff.New(d.r)\n}\n\n\/\/ FwdToPCM forwards the underlying reader until the start of the PCM chunk.\n\/\/ If the PCM chunk was already read, no data will be found (you need to rewind).\nfunc (d *Decoder) FwdToPCM() error {\n\tif d == nil {\n\t\treturn fmt.Errorf(\"PCM data not found\")\n\t}\n\td.err = d.readHeaders()\n\tif d.err != nil {\n\t\treturn nil\n\t}\n\n\tvar chunk *riff.Chunk\n\tfor d.err == nil {\n\t\tchunk, d.err = d.NextChunk()\n\t\tif d.err != nil {\n\t\t\treturn d.err\n\t\t}\n\t\tif chunk.ID == riff.DataFormatID {\n\t\t\td.PCMSize = chunk.Size\n\t\t\td.PCMChunk = chunk\n\t\t\tbreak\n\t\t}\n\t\tchunk.Drain()\n\t}\n\tif chunk == nil {\n\t\treturn fmt.Errorf(\"PCM data not found\")\n\t}\n\td.pcmDataAccessed = true\n\n\treturn nil\n}\n\n\/\/ WasPCMAccessed returns positively if the PCM data was previously accessed.\nfunc (d *Decoder) WasPCMAccessed() bool {\n\tif d == nil {\n\t\treturn false\n\t}\n\treturn d.pcmDataAccessed\n}\n\n\/\/ FullPCMBuffer is an inneficient way to access all the PCM data contained in the\n\/\/ audio container. The entire PCM data is held in memory.\n\/\/ Consider using Buffer() instead.\nfunc (d *Decoder) FullPCMBuffer() (*audio.IntBuffer, error) {\n\tif !d.WasPCMAccessed() {\n\t\terr := d.FwdToPCM()\n\t\tif err != nil {\n\t\t\treturn nil, d.err\n\t\t}\n\t}\n\tif d.PCMChunk == nil {\n\t\treturn nil, errors.New(\"PCM chunk not found\")\n\t}\n\tformat := &audio.Format{\n\t\tNumChannels: int(d.NumChans),\n\t\tSampleRate:  int(d.SampleRate),\n\t}\n\n\tbuf := &audio.IntBuffer{Data: make([]int, 4096), Format: format, SourceBitDepth: int(d.BitDepth)}\n\tbytesPerSample := (d.BitDepth-1)\/8 + 1\n\tsampleBufData := make([]byte, bytesPerSample)\n\tdecodeF, err := sampleDecodeFunc(int(d.BitDepth))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not get sample decode func %v\", err)\n\t}\n\n\ti := 0\n\tfor err == nil {\n\t\tbuf.Data[i], err = decodeF(d.PCMChunk, sampleBufData)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\ti++\n\t\t\/\/ grow the underlying slice if needed\n\t\tif i == len(buf.Data) {\n\t\t\tbuf.Data = append(buf.Data, make([]int, 4096)...)\n\t\t}\n\t}\n\tbuf.Data = buf.Data[:i]\n\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\n\treturn buf, err\n}\n\n\/\/ PCMBuffer populates the passed PCM buffer\nfunc (d *Decoder) PCMBuffer(buf *audio.IntBuffer) (n int, err error) {\n\tif buf == nil {\n\t\treturn 0, nil\n\t}\n\n\tif !d.pcmDataAccessed {\n\t\terr := d.FwdToPCM()\n\t\tif err != nil {\n\t\t\treturn 0, d.err\n\t\t}\n\t}\n\n\tformat := &audio.Format{\n\t\tNumChannels: int(d.NumChans),\n\t\tSampleRate:  int(d.SampleRate),\n\t}\n\n\tbuf.SourceBitDepth = int(d.BitDepth)\n\tdecodeF, err := sampleDecodeFunc(int(d.BitDepth))\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"could not get sample decode func %v\", err)\n\t}\n\n\t\/\/ populate a file buffer to avoid multiple very small reads\n\t\/\/ we need to cap the buffer size to not be bigger than the pcm chunk.\n\tsize := len(buf.Data) * (int(d.BitDepth) \/ 8)\n\ttmpBuf := make([]byte, size)\n\tvar m int\n\tm, err = d.PCMChunk.R.Read(tmpBuf)\n\tif err != nil {\n\t\tif err == io.EOF {\n\t\t\treturn m, nil\n\t\t}\n\t\treturn m, err\n\t}\n\tif m == 0 {\n\t\treturn m, nil\n\t}\n\tbufR := bytes.NewReader(tmpBuf[:m])\n\tsampleBuf := make([]byte, 4, 4)\n\n\t\/\/ Note that we populate the buffer even if the\n\t\/\/ size of the buffer doesn't fit an even number of frames.\n\tfor n = 0; n < len(buf.Data); n++ {\n\t\tbuf.Data[n], err = decodeF(bufR, sampleBuf)\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tbuf.Format = format\n\tif err == io.EOF {\n\t\terr = nil\n\t}\n\n\treturn n, err\n}\n\n\/\/ Format returns the audio format of the decoded content.\nfunc (d *Decoder) Format() *audio.Format {\n\tif d == nil {\n\t\treturn nil\n\t}\n\treturn &audio.Format{\n\t\tNumChannels: int(d.NumChans),\n\t\tSampleRate:  int(d.SampleRate),\n\t}\n}\n\n\/\/ NextChunk returns the next available chunk\nfunc (d *Decoder) NextChunk() (*riff.Chunk, error) {\n\tif d.err = d.readHeaders(); d.err != nil {\n\t\td.err = fmt.Errorf(\"failed to read header - %v\", d.err)\n\t\treturn nil, d.err\n\t}\n\n\tvar (\n\t\tid   [4]byte\n\t\tsize uint32\n\t)\n\n\tid, size, d.err = d.parser.IDnSize()\n\tif d.err != nil {\n\t\td.err = fmt.Errorf(\"error reading chunk header - %v\", d.err)\n\t\treturn nil, d.err\n\t}\n\n\tc := &riff.Chunk{\n\t\tID:   id,\n\t\tSize: int(size),\n\t\tR:    io.LimitReader(d.r, int64(size)),\n\t}\n\treturn c, d.err\n}\n\n\/\/ Duration returns the time duration for the current audio container\nfunc (d *Decoder) Duration() (time.Duration, error) {\n\tif d == nil || d.parser == nil {\n\t\treturn 0, errors.New(\"can't calculate the duration of a nil pointer\")\n\t}\n\treturn d.parser.Duration()\n}\n\n\/\/ String implements the Stringer interface.\nfunc (d *Decoder) String() string {\n\treturn d.parser.String()\n}\n\n\/\/ readHeaders is safe to call multiple times\nfunc (d *Decoder) readHeaders() error {\n\tif d == nil || d.NumChans > 0 {\n\t\treturn nil\n\t}\n\n\tid, size, err := d.parser.IDnSize()\n\tif err != nil {\n\t\treturn err\n\t}\n\td.parser.ID = id\n\tif d.parser.ID != riff.RiffID {\n\t\treturn fmt.Errorf(\"%s - %s\", d.parser.ID, riff.ErrFmtNotSupported)\n\t}\n\td.parser.Size = size\n\tif err := binary.Read(d.r, binary.BigEndian, &d.parser.Format); err != nil {\n\t\treturn err\n\t}\n\n\tvar chunk *riff.Chunk\n\tvar rewindBytes int64\n\n\tfor err == nil {\n\t\tchunk, err = d.parser.NextChunk()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif chunk.ID == riff.FmtID {\n\t\t\tchunk.DecodeWavHeader(d.parser)\n\t\t\td.NumChans = d.parser.NumChannels\n\t\t\td.BitDepth = d.parser.BitsPerSample\n\t\t\td.SampleRate = d.parser.SampleRate\n\t\t\td.WavAudioFormat = d.parser.WavAudioFormat\n\t\t\td.AvgBytesPerSec = d.parser.AvgBytesPerSec\n\n\t\t\tif rewindBytes > 0 {\n\t\t\t\td.r.Seek(-(rewindBytes + int64(chunk.Size) + 8), 1)\n\t\t\t}\n\t\t\tbreak\n\t\t} else {\n\t\t\t\/\/ unexpected chunk order, might be a bext chunk\n\t\t\trewindBytes += int64(chunk.Size) + 8\n\t\t\t\/\/ drain the chunk\n\t\t\tio.CopyN(ioutil.Discard, d.r, int64(chunk.Size))\n\t\t}\n\n\t}\n\n\treturn d.err\n}\n\n\/\/ sampleDecodeFunc returns a function that can be used to convert\n\/\/ a byte range into an int value based on the amount of bits used per sample.\n\/\/ Note that 8bit samples are unsigned, all other values are signed.\nfunc sampleDecodeFunc(bitsPerSample int) (func(io.Reader, []byte) (int, error), error) {\n\t\/\/ NOTE: WAV PCM data is stored using little-endian\n\tswitch bitsPerSample {\n\tcase 8:\n\t\t\/\/ 8bit values are unsigned\n\t\treturn func(r io.Reader, buf []byte) (int, error) {\n\t\t\t_, err := r.Read(buf[:1])\n\t\t\treturn int(buf[0]), err\n\t\t}, nil\n\tcase 16:\n\t\treturn func(r io.Reader, buf []byte) (int, error) {\n\t\t\t_, err := r.Read(buf[:2])\n\t\t\treturn int(int16(binary.LittleEndian.Uint16(buf[:2]))), err\n\t\t}, nil\n\tcase 24:\n\t\t\/\/ -34,359,738,367 (0x7FFFFF) to 34,359,738,368\t(0x800000)\n\t\treturn func(r io.Reader, buf []byte) (int, error) {\n\t\t\t_, err := r.Read(buf[:3])\n\t\t\tif err != nil {\n\t\t\t\treturn 0, err\n\t\t\t}\n\t\t\treturn int(audio.Int24LETo32(buf[:3])), nil\n\t\t}, nil\n\tcase 32:\n\t\treturn func(r io.Reader, buf []byte) (int, error) {\n\t\t\t_, err := r.Read(buf[:4])\n\t\t\treturn int(int32(binary.LittleEndian.Uint32(buf[:4]))), err\n\t\t}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unhandled byte depth:%d\", bitsPerSample)\n\t}\n}\n\n\/\/ sampleDecodeFloat64Func returns a function that can be used to convert\n\/\/ a byte range into a float64 value based on the amount of bits used per sample.\nfunc sampleFloat64DecodeFunc(bitsPerSample int) (func([]byte) float64, error) {\n\tbytesPerSample := bitsPerSample \/ 8\n\tswitch bytesPerSample {\n\tcase 1:\n\t\t\/\/ 8bit values are unsigned\n\t\treturn func(s []byte) float64 {\n\t\t\treturn float64(uint8(s[0]))\n\t\t}, nil\n\tcase 2:\n\t\treturn func(s []byte) float64 {\n\t\t\treturn float64(int(s[0]) + int(s[1])<<8)\n\t\t}, nil\n\tcase 3:\n\t\treturn func(s []byte) float64 {\n\t\t\tvar output int32\n\t\t\toutput |= int32(s[2]) << 0\n\t\t\toutput |= int32(s[1]) << 8\n\t\t\toutput |= int32(s[0]) << 16\n\t\t\treturn float64(output)\n\t\t}, nil\n\tcase 4:\n\t\t\/\/ TODO: fix the float64 conversion (current int implementation)\n\t\treturn func(s []byte) float64 {\n\t\t\treturn float64(int(s[0]) + int(s[1])<<8 + int(s[2])<<16 + int(s[3])<<24)\n\t\t}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unhandled byte depth:%d\", bitsPerSample)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package spherical\n\nimport (\n\t\"github.com\/twpayne\/gogeom\/geom\"\n\t\"math\"\n)\n\nfunc CosineDist(p1, p2 Point) float64 {\n\td := math.Sin(p1.Y)*math.Sin(p2.Y) + math.Cos(p1.Y)*math.Cos(p2.Y)*math.Cos(p1.Y-p2.Y)\n\tif d < 1 {\n\t\treturn math.Acos(d)\n\t} else {\n\t\treturn 0\n\t}\n}\n\nfunc HaversineDist(p1, p2 Point) float64 {\n\thalfDeltaX := (p1.X - p2.X) \/ 2\n\thalfDeltaY := (p1.Y - p2.Y) \/ 2\n\ta := math.Sin(halfDeltaY)*math.Sin(halfDeltaY) + math.Sin(halfDeltaX)*math.Sin(halfDeltaX)*math.Cos(p1.Y)*math.Cos(p2.Y)\n\treturn 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a))\n}\n<commit_msg>Remove spherical<commit_after><|endoftext|>"}
{"text":"<commit_before>package azureclusterconditions\n\nimport (\n\t\"context\"\n\n\t\"github.com\/giantswarm\/microerror\"\n\n\t\"github.com\/giantswarm\/azure-operator\/v5\/service\/controller\/key\"\n)\n\nfunc (r *Resource) EnsureCreated(ctx context.Context, cr interface{}) error {\n\tvar err error\n\tazureCluster, err := key.ToAzureCluster(cr)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\t\/\/ ensure Ready condition\n\terr = r.ensureReadyCondition(ctx, &azureCluster)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\terr = r.ctrlClient.Status().Update(ctx, &azureCluster)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\treturn nil\n}\n<commit_msg>Don't error when k8s API returns conflict while saving CR status (#1184)<commit_after>package azureclusterconditions\n\nimport (\n\t\"context\"\n\n\t\"github.com\/giantswarm\/microerror\"\n\tapierrors \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\n\t\"github.com\/giantswarm\/azure-operator\/v5\/service\/controller\/key\"\n)\n\nfunc (r *Resource) EnsureCreated(ctx context.Context, cr interface{}) error {\n\tvar err error\n\tazureCluster, err := key.ToAzureCluster(cr)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\t\/\/ ensure Ready condition\n\terr = r.ensureReadyCondition(ctx, &azureCluster)\n\tif err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\terr = r.ctrlClient.Status().Update(ctx, &azureCluster)\n\tif apierrors.IsConflict(err) {\n\t\tr.logger.LogCtx(ctx, \"level\", \"debug\", \"message\", \"conflict trying to save object in k8s API concurrently\", \"stack\", microerror.JSON(microerror.Mask(err)))\n\t\tr.logger.LogCtx(ctx, \"level\", \"debug\", \"message\", \"canceling resource\")\n\t\treturn nil\n\t} else if err != nil {\n\t\treturn microerror.Mask(err)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package logs\n\nimport (\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/websocket\"\n\t\"github.com\/pivotal-golang\/lager\"\n\n\t\"github.com\/concourse\/atc\/auth\"\n\t\"github.com\/concourse\/atc\/config\"\n\t\"github.com\/concourse\/atc\/db\"\n\t\"github.com\/concourse\/atc\/logfanout\"\n)\n\nvar upgrader = websocket.Upgrader{\n\tCheckOrigin: func(*http.Request) bool {\n\t\treturn true\n\t},\n}\n\nfunc NewHandler(\n\tlogger lager.Logger,\n\tvalidator auth.Validator,\n\tjobs config.Jobs,\n\ttracker *logfanout.Tracker,\n\tdb db.DB,\n) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tbuildIDStr := r.FormValue(\":build_id\")\n\n\t\tlog := logger.Session(\"logs-out\", lager.Data{\n\t\t\t\"build_id\": buildIDStr,\n\t\t})\n\n\t\tbuildID, err := strconv.Atoi(buildIDStr)\n\t\tif err != nil {\n\t\t\tlog.Error(\"invalid-build-id\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif !validator.IsAuthenticated(r) {\n\t\t\tbuild, err := db.GetBuild(buildID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"invalid-build-id\", err)\n\t\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tjob, found := jobs.Lookup(build.JobName)\n\t\t\tif !found || !job.Public {\n\t\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tconn, err := upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\tlog.Error(\"upgrade-failed\", err)\n\t\t\treturn\n\t\t}\n\n\t\tdefer conn.Close()\n\n\t\tlogFanout := tracker.Register(buildID, conn)\n\t\tdefer tracker.Unregister(buildID, conn)\n\n\t\terr = logFanout.Attach(conn)\n\t\tif err != nil {\n\t\t\tlog.Error(\"attach-failed\", err)\n\t\t\tconn.Close()\n\t\t\treturn\n\t\t}\n\n\t\tfor {\n\t\t\ttime.Sleep(5 * time.Second)\n\n\t\t\terr := conn.WriteControl(websocket.PingMessage, []byte(\"ping\"), time.Time{})\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"ping-failed\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t})\n}\n<commit_msg>censor often-senstive info out of v1.0 event streams<commit_after>package logs\n\nimport (\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/websocket\"\n\t\"github.com\/pivotal-golang\/lager\"\n\n\t\"github.com\/concourse\/atc\/auth\"\n\t\"github.com\/concourse\/atc\/config\"\n\t\"github.com\/concourse\/atc\/db\"\n\t\"github.com\/concourse\/atc\/logfanout\"\n)\n\nvar upgrader = websocket.Upgrader{\n\tCheckOrigin: func(*http.Request) bool {\n\t\treturn true\n\t},\n}\n\nfunc NewHandler(\n\tlogger lager.Logger,\n\tvalidator auth.Validator,\n\tjobs config.Jobs,\n\ttracker *logfanout.Tracker,\n\tdb db.DB,\n) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tbuildIDStr := r.FormValue(\":build_id\")\n\n\t\tlog := logger.Session(\"logs-out\", lager.Data{\n\t\t\t\"build_id\": buildIDStr,\n\t\t})\n\n\t\tbuildID, err := strconv.Atoi(buildIDStr)\n\t\tif err != nil {\n\t\t\tlog.Error(\"invalid-build-id\", err)\n\t\t\treturn\n\t\t}\n\n\t\tauthenticated := validator.IsAuthenticated(r)\n\n\t\tif !authenticated {\n\t\t\tbuild, err := db.GetBuild(buildID)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"invalid-build-id\", err)\n\t\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tjob, found := jobs.Lookup(build.JobName)\n\t\t\tif !found || !job.Public {\n\t\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tconn, err := upgrader.Upgrade(w, r, nil)\n\t\tif err != nil {\n\t\t\tlog.Error(\"upgrade-failed\", err)\n\t\t\treturn\n\t\t}\n\n\t\tdefer conn.Close()\n\n\t\tlogFanout := tracker.Register(buildID, conn)\n\t\tdefer tracker.Unregister(buildID, conn)\n\n\t\tvar sink logfanout.Sink\n\t\tif authenticated {\n\t\t\tsink = logfanout.NewRawSink(conn)\n\t\t} else {\n\t\t\tsink = logfanout.NewCensoredSink(conn)\n\t\t}\n\n\t\terr = logFanout.Attach(sink)\n\t\tif err != nil {\n\t\t\tlog.Error(\"attach-failed\", err)\n\t\t\tconn.Close()\n\t\t\treturn\n\t\t}\n\n\t\tfor {\n\t\t\ttime.Sleep(5 * time.Second)\n\n\t\t\terr := conn.WriteControl(websocket.PingMessage, []byte(\"ping\"), time.Time{})\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(\"ping-failed\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package util\n\nimport (\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"golang.org\/x\/sys\/unix\"\n\n\t\"github.com\/lxc\/lxd\/shared\"\n\t\"github.com\/lxc\/lxd\/shared\/logger\"\n)\n\n\/\/ InMemoryNetwork creates a fully in-memory listener and dial function.\n\/\/\n\/\/ Each time the dial function is invoked a new pair of net.Conn objects will\n\/\/ be created using net.Pipe: the listener's Accept method will unblock and\n\/\/ return one end of the pipe and the other end will be returned by the dial\n\/\/ function.\nfunc InMemoryNetwork() (net.Listener, func() net.Conn) {\n\tlistener := &inMemoryListener{\n\t\tconns:  make(chan net.Conn, 16),\n\t\tclosed: make(chan struct{}),\n\t}\n\tdialer := func() net.Conn {\n\t\tserver, client := net.Pipe()\n\t\tlistener.conns <- server\n\t\treturn client\n\t}\n\treturn listener, dialer\n}\n\ntype inMemoryListener struct {\n\tconns  chan net.Conn\n\tclosed chan struct{}\n}\n\n\/\/ Accept waits for and returns the next connection to the listener.\nfunc (l *inMemoryListener) Accept() (net.Conn, error) {\n\tselect {\n\tcase conn := <-l.conns:\n\t\treturn conn, nil\n\tcase <-l.closed:\n\t\treturn nil, fmt.Errorf(\"closed\")\n\t}\n}\n\n\/\/ Close closes the listener.\n\/\/ Any blocked Accept operations will be unblocked and return errors.\nfunc (l *inMemoryListener) Close() error {\n\tclose(l.closed)\n\treturn nil\n}\n\n\/\/ Addr returns the listener's network address.\nfunc (l *inMemoryListener) Addr() net.Addr {\n\treturn &inMemoryAddr{}\n}\n\ntype inMemoryAddr struct {\n}\n\nfunc (a *inMemoryAddr) Network() string {\n\treturn \"memory\"\n}\n\nfunc (a *inMemoryAddr) String() string {\n\treturn \"\"\n}\n\n\/\/ CanonicalNetworkAddress parses the given network address and returns a string of the form \"host:port\",\n\/\/ possibly filling it with the default port if it's missing. It will also wrap a bare IPv6 address with square\n\/\/ brackets if needed.\nfunc CanonicalNetworkAddress(address string, defaultPort int) string {\n\t_, _, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\tip := net.ParseIP(address)\n\t\tif ip != nil {\n\t\t\t\/\/ If the input address is a bare IP address, then convert it to a proper listen address\n\t\t\t\/\/ using the canonical IP with default port and wrap IPv6 addresses in square brackets.\n\t\t\taddress = net.JoinHostPort(ip.String(), fmt.Sprintf(\"%d\", defaultPort))\n\t\t} else {\n\t\t\t\/\/ Otherwise assume this is either a host name or a partial address (e.g `[::]`) without\n\t\t\t\/\/ a port number, so append the default port.\n\t\t\taddress = fmt.Sprintf(\"%s:%d\", address, defaultPort)\n\t\t}\n\t}\n\n\treturn address\n}\n\n\/\/ CanonicalNetworkAddressFromAddressAndPort returns a network address from separate address and port values.\n\/\/ The address accepts values such as \"[::]\", \"::\" and \"localhost\".\nfunc CanonicalNetworkAddressFromAddressAndPort(address string, port int, defaultPort int) string {\n\t\/\/ Because we accept just the host part of an IPv6 listen address (e.g. `[::]`) don't use net.JoinHostPort.\n\t\/\/ If a bare IP address is supplied then CanonicalNetworkAddress will use net.JoinHostPort if needed.\n\treturn CanonicalNetworkAddress(fmt.Sprintf(\"%s:%d\", address, port), defaultPort)\n}\n\n\/\/ ServerTLSConfig returns a new server-side tls.Config generated from the give\n\/\/ certificate info.\nfunc ServerTLSConfig(cert *shared.CertInfo) *tls.Config {\n\tconfig := shared.InitTLSConfig()\n\tconfig.ClientAuth = tls.RequestClientCert\n\tconfig.Certificates = []tls.Certificate{cert.KeyPair()}\n\tconfig.NextProtos = []string{\"h2\"} \/\/ Required by gRPC\n\n\tif cert.CA() != nil {\n\t\tpool := x509.NewCertPool()\n\t\tpool.AddCert(cert.CA())\n\t\tconfig.RootCAs = pool\n\t\tconfig.ClientCAs = pool\n\n\t\tlogger.Infof(\"LXD is in CA mode, only CA-signed certificates will be allowed\")\n\t}\n\n\tconfig.BuildNameToCertificate()\n\treturn config\n}\n\n\/\/ NetworkInterfaceAddress returns the first global unicast address of any of the system network interfaces.\n\/\/ Return the empty string if none is found.\nfunc NetworkInterfaceAddress() string {\n\tifaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tfor _, iface := range ifaces {\n\t\taddrs, err := iface.Addrs()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(addrs) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, addr := range addrs {\n\t\t\tipNet, ok := addr.(*net.IPNet)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !ipNet.IP.IsGlobalUnicast() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn ipNet.IP.String()\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\n\/\/ IsAddressCovered detects if network address1 is actually covered by\n\/\/ address2, in the sense that they are either the same address or address2 is\n\/\/ specified using a wildcard with the same port of address1.\nfunc IsAddressCovered(address1, address2 string) bool {\n\taddress1 = CanonicalNetworkAddress(address1, shared.HTTPSDefaultPort)\n\taddress2 = CanonicalNetworkAddress(address2, shared.HTTPSDefaultPort)\n\n\tif address1 == address2 {\n\t\treturn true\n\t}\n\n\thost1, port1, err := net.SplitHostPort(address1)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\thost2, port2, err := net.SplitHostPort(address2)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\t\/\/ If the ports are different, then address1 is clearly not covered by\n\t\/\/ address2.\n\tif port2 != port1 {\n\t\treturn false\n\t}\n\n\t\/\/ If address1 contains a host name, let's try to resolve it, in order\n\t\/\/ to compare the actual IPs.\n\tvar addresses1 []net.IP\n\tif host1 != \"\" {\n\t\tip := net.ParseIP(host1)\n\t\tif ip != nil {\n\t\t\taddresses1 = append(addresses1, ip)\n\t\t} else {\n\t\t\tips, err := net.LookupHost(host1)\n\t\t\tif err == nil && len(ips) > 0 {\n\t\t\t\tfor _, ipStr := range ips {\n\t\t\t\t\tip := net.ParseIP(ipStr)\n\t\t\t\t\tif ip != nil {\n\t\t\t\t\t\taddresses1 = append(addresses1, ip)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ If address2 contains a host name, let's try to resolve it, in order\n\t\/\/ to compare the actual IPs.\n\tvar addresses2 []net.IP\n\tif host2 != \"\" {\n\t\tip := net.ParseIP(host2)\n\t\tif ip != nil {\n\t\t\taddresses2 = append(addresses2, ip)\n\t\t} else {\n\t\t\tips, err := net.LookupHost(host2)\n\t\t\tif err == nil && len(ips) > 0 {\n\t\t\t\tfor _, ipStr := range ips {\n\t\t\t\t\tip := net.ParseIP(ipStr)\n\t\t\t\t\tif ip != nil {\n\t\t\t\t\t\taddresses2 = append(addresses2, ip)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, a1 := range addresses1 {\n\t\tfor _, a2 := range addresses2 {\n\t\t\tif a1.Equal(a2) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ If address2 is using an IPv4 wildcard for the host, then address2 is\n\t\/\/ only covered if it's an IPv4 address.\n\tif host2 == \"0.0.0.0\" {\n\t\tip1 := net.ParseIP(host1)\n\t\tif ip1 != nil && ip1.To4() != nil {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\t\/\/ If address2 is using an IPv6 wildcard for the host, then address2 is\n\t\/\/ always covered.\n\tif host2 == \"::\" || host2 == \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ IsWildCardAddress returns whether the given address is a wildcard.\nfunc IsWildCardAddress(address string) bool {\n\taddress = CanonicalNetworkAddress(address, shared.HTTPSDefaultPort)\n\n\thost, _, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif host == \"0.0.0.0\" || host == \"::\" || host == \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ SysctlGet retrieves the value of a sysctl file in \/proc\/sys.\nfunc SysctlGet(path string) (string, error) {\n\t\/\/ Read the current content\n\tcontent, err := ioutil.ReadFile(fmt.Sprintf(\"\/proc\/sys\/%s\", path))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(content), nil\n}\n\n\/\/ SysctlSet writes a value to a sysctl file in \/proc\/sys.\n\/\/ Requires an even number of arguments as key\/value pairs. E.g. SysctlSet(\"path1\", \"value1\", \"path2\", \"value2\")\nfunc SysctlSet(parts ...string) error {\n\tpartsLen := len(parts)\n\tif partsLen%2 != 0 {\n\t\treturn fmt.Errorf(\"Requires even number of arguments\")\n\t}\n\n\tfor i := 0; i < partsLen; i = i + 2 {\n\t\tpath := parts[i]\n\t\tnewValue := parts[i+1]\n\n\t\t\/\/ Get current value.\n\t\tcurrentValue, err := SysctlGet(path)\n\t\tif err == nil && currentValue == newValue {\n\t\t\t\/\/ Nothing to update.\n\t\t\treturn nil\n\t\t}\n\n\t\terr = ioutil.WriteFile(fmt.Sprintf(\"\/proc\/sys\/%s\", path), []byte(newValue), 0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ SetTCPUserTimeout sets the TCP user timeout on a connection's socket\nfunc SetTCPUserTimeout(conn *net.TCPConn, timeout time.Duration) error {\n\trawConn, err := conn.SyscallConn()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting raw connection: %w\", err)\n\t}\n\n\terr = rawConn.Control(func(fd uintptr) {\n\t\terr = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_USER_TIMEOUT, int(timeout\/time.Millisecond))\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error setting option on socket: %w\", err)\n\t}\n\n\treturn nil\n}\n<commit_msg>lxd\/util\/net: Adds SetTCPTimeouts and ExtractTCPConn functions<commit_after>package util\n\nimport (\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"reflect\"\n\t\"syscall\"\n\t\"time\"\n\t\"unsafe\"\n\n\t\"golang.org\/x\/sys\/unix\"\n\n\t\"github.com\/lxc\/lxd\/shared\"\n\t\"github.com\/lxc\/lxd\/shared\/logger\"\n)\n\n\/\/ InMemoryNetwork creates a fully in-memory listener and dial function.\n\/\/\n\/\/ Each time the dial function is invoked a new pair of net.Conn objects will\n\/\/ be created using net.Pipe: the listener's Accept method will unblock and\n\/\/ return one end of the pipe and the other end will be returned by the dial\n\/\/ function.\nfunc InMemoryNetwork() (net.Listener, func() net.Conn) {\n\tlistener := &inMemoryListener{\n\t\tconns:  make(chan net.Conn, 16),\n\t\tclosed: make(chan struct{}),\n\t}\n\tdialer := func() net.Conn {\n\t\tserver, client := net.Pipe()\n\t\tlistener.conns <- server\n\t\treturn client\n\t}\n\treturn listener, dialer\n}\n\ntype inMemoryListener struct {\n\tconns  chan net.Conn\n\tclosed chan struct{}\n}\n\n\/\/ Accept waits for and returns the next connection to the listener.\nfunc (l *inMemoryListener) Accept() (net.Conn, error) {\n\tselect {\n\tcase conn := <-l.conns:\n\t\treturn conn, nil\n\tcase <-l.closed:\n\t\treturn nil, fmt.Errorf(\"closed\")\n\t}\n}\n\n\/\/ Close closes the listener.\n\/\/ Any blocked Accept operations will be unblocked and return errors.\nfunc (l *inMemoryListener) Close() error {\n\tclose(l.closed)\n\treturn nil\n}\n\n\/\/ Addr returns the listener's network address.\nfunc (l *inMemoryListener) Addr() net.Addr {\n\treturn &inMemoryAddr{}\n}\n\ntype inMemoryAddr struct {\n}\n\nfunc (a *inMemoryAddr) Network() string {\n\treturn \"memory\"\n}\n\nfunc (a *inMemoryAddr) String() string {\n\treturn \"\"\n}\n\n\/\/ CanonicalNetworkAddress parses the given network address and returns a string of the form \"host:port\",\n\/\/ possibly filling it with the default port if it's missing. It will also wrap a bare IPv6 address with square\n\/\/ brackets if needed.\nfunc CanonicalNetworkAddress(address string, defaultPort int) string {\n\t_, _, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\tip := net.ParseIP(address)\n\t\tif ip != nil {\n\t\t\t\/\/ If the input address is a bare IP address, then convert it to a proper listen address\n\t\t\t\/\/ using the canonical IP with default port and wrap IPv6 addresses in square brackets.\n\t\t\taddress = net.JoinHostPort(ip.String(), fmt.Sprintf(\"%d\", defaultPort))\n\t\t} else {\n\t\t\t\/\/ Otherwise assume this is either a host name or a partial address (e.g `[::]`) without\n\t\t\t\/\/ a port number, so append the default port.\n\t\t\taddress = fmt.Sprintf(\"%s:%d\", address, defaultPort)\n\t\t}\n\t}\n\n\treturn address\n}\n\n\/\/ CanonicalNetworkAddressFromAddressAndPort returns a network address from separate address and port values.\n\/\/ The address accepts values such as \"[::]\", \"::\" and \"localhost\".\nfunc CanonicalNetworkAddressFromAddressAndPort(address string, port int, defaultPort int) string {\n\t\/\/ Because we accept just the host part of an IPv6 listen address (e.g. `[::]`) don't use net.JoinHostPort.\n\t\/\/ If a bare IP address is supplied then CanonicalNetworkAddress will use net.JoinHostPort if needed.\n\treturn CanonicalNetworkAddress(fmt.Sprintf(\"%s:%d\", address, port), defaultPort)\n}\n\n\/\/ ServerTLSConfig returns a new server-side tls.Config generated from the give\n\/\/ certificate info.\nfunc ServerTLSConfig(cert *shared.CertInfo) *tls.Config {\n\tconfig := shared.InitTLSConfig()\n\tconfig.ClientAuth = tls.RequestClientCert\n\tconfig.Certificates = []tls.Certificate{cert.KeyPair()}\n\tconfig.NextProtos = []string{\"h2\"} \/\/ Required by gRPC\n\n\tif cert.CA() != nil {\n\t\tpool := x509.NewCertPool()\n\t\tpool.AddCert(cert.CA())\n\t\tconfig.RootCAs = pool\n\t\tconfig.ClientCAs = pool\n\n\t\tlogger.Infof(\"LXD is in CA mode, only CA-signed certificates will be allowed\")\n\t}\n\n\tconfig.BuildNameToCertificate()\n\treturn config\n}\n\n\/\/ NetworkInterfaceAddress returns the first global unicast address of any of the system network interfaces.\n\/\/ Return the empty string if none is found.\nfunc NetworkInterfaceAddress() string {\n\tifaces, err := net.Interfaces()\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tfor _, iface := range ifaces {\n\t\taddrs, err := iface.Addrs()\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif len(addrs) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, addr := range addrs {\n\t\t\tipNet, ok := addr.(*net.IPNet)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif !ipNet.IP.IsGlobalUnicast() {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\treturn ipNet.IP.String()\n\t\t}\n\t}\n\n\treturn \"\"\n}\n\n\/\/ IsAddressCovered detects if network address1 is actually covered by\n\/\/ address2, in the sense that they are either the same address or address2 is\n\/\/ specified using a wildcard with the same port of address1.\nfunc IsAddressCovered(address1, address2 string) bool {\n\taddress1 = CanonicalNetworkAddress(address1, shared.HTTPSDefaultPort)\n\taddress2 = CanonicalNetworkAddress(address2, shared.HTTPSDefaultPort)\n\n\tif address1 == address2 {\n\t\treturn true\n\t}\n\n\thost1, port1, err := net.SplitHostPort(address1)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\thost2, port2, err := net.SplitHostPort(address2)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\t\/\/ If the ports are different, then address1 is clearly not covered by\n\t\/\/ address2.\n\tif port2 != port1 {\n\t\treturn false\n\t}\n\n\t\/\/ If address1 contains a host name, let's try to resolve it, in order\n\t\/\/ to compare the actual IPs.\n\tvar addresses1 []net.IP\n\tif host1 != \"\" {\n\t\tip := net.ParseIP(host1)\n\t\tif ip != nil {\n\t\t\taddresses1 = append(addresses1, ip)\n\t\t} else {\n\t\t\tips, err := net.LookupHost(host1)\n\t\t\tif err == nil && len(ips) > 0 {\n\t\t\t\tfor _, ipStr := range ips {\n\t\t\t\t\tip := net.ParseIP(ipStr)\n\t\t\t\t\tif ip != nil {\n\t\t\t\t\t\taddresses1 = append(addresses1, ip)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ If address2 contains a host name, let's try to resolve it, in order\n\t\/\/ to compare the actual IPs.\n\tvar addresses2 []net.IP\n\tif host2 != \"\" {\n\t\tip := net.ParseIP(host2)\n\t\tif ip != nil {\n\t\t\taddresses2 = append(addresses2, ip)\n\t\t} else {\n\t\t\tips, err := net.LookupHost(host2)\n\t\t\tif err == nil && len(ips) > 0 {\n\t\t\t\tfor _, ipStr := range ips {\n\t\t\t\t\tip := net.ParseIP(ipStr)\n\t\t\t\t\tif ip != nil {\n\t\t\t\t\t\taddresses2 = append(addresses2, ip)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, a1 := range addresses1 {\n\t\tfor _, a2 := range addresses2 {\n\t\t\tif a1.Equal(a2) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ If address2 is using an IPv4 wildcard for the host, then address2 is\n\t\/\/ only covered if it's an IPv4 address.\n\tif host2 == \"0.0.0.0\" {\n\t\tip1 := net.ParseIP(host1)\n\t\tif ip1 != nil && ip1.To4() != nil {\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\t\/\/ If address2 is using an IPv6 wildcard for the host, then address2 is\n\t\/\/ always covered.\n\tif host2 == \"::\" || host2 == \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ IsWildCardAddress returns whether the given address is a wildcard.\nfunc IsWildCardAddress(address string) bool {\n\taddress = CanonicalNetworkAddress(address, shared.HTTPSDefaultPort)\n\n\thost, _, err := net.SplitHostPort(address)\n\tif err != nil {\n\t\treturn false\n\t}\n\n\tif host == \"0.0.0.0\" || host == \"::\" || host == \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ SysctlGet retrieves the value of a sysctl file in \/proc\/sys.\nfunc SysctlGet(path string) (string, error) {\n\t\/\/ Read the current content\n\tcontent, err := ioutil.ReadFile(fmt.Sprintf(\"\/proc\/sys\/%s\", path))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn string(content), nil\n}\n\n\/\/ SysctlSet writes a value to a sysctl file in \/proc\/sys.\n\/\/ Requires an even number of arguments as key\/value pairs. E.g. SysctlSet(\"path1\", \"value1\", \"path2\", \"value2\")\nfunc SysctlSet(parts ...string) error {\n\tpartsLen := len(parts)\n\tif partsLen%2 != 0 {\n\t\treturn fmt.Errorf(\"Requires even number of arguments\")\n\t}\n\n\tfor i := 0; i < partsLen; i = i + 2 {\n\t\tpath := parts[i]\n\t\tnewValue := parts[i+1]\n\n\t\t\/\/ Get current value.\n\t\tcurrentValue, err := SysctlGet(path)\n\t\tif err == nil && currentValue == newValue {\n\t\t\t\/\/ Nothing to update.\n\t\t\treturn nil\n\t\t}\n\n\t\terr = ioutil.WriteFile(fmt.Sprintf(\"\/proc\/sys\/%s\", path), []byte(newValue), 0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ ExtractTCPConn tries to extract the underlying net.TCPConn from a tls.Conn.\nfunc ExtractTCPConn(conn net.Conn) (*net.TCPConn, error) {\n\t\/\/ Go doesn't currently expose the underlying TCP connection of a TLS connection, but we need it in order\n\t\/\/ to set timeout properties on the connection. We use some reflect\/unsafe magic to extract the private\n\t\/\/ remote.conn field, which is indeed the underlying TCP connection.\n\ttlsConn, ok := conn.(*tls.Conn)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"Connection is not a tls.Conn\")\n\t}\n\n\tfield := reflect.ValueOf(tlsConn).Elem().FieldByName(\"conn\")\n\tfield = reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem()\n\tc := field.Interface()\n\n\ttcpConn, ok := c.(*net.TCPConn)\n\tif !ok {\n\t\treturn tcpConn, fmt.Errorf(\"Connection is not a net.TCPConn\")\n\t}\n\n\treturn tcpConn, nil\n}\n\n\/\/ SetTCPTimeouts sets TCP_USER_TIMEOUT and TCP keep alive timeouts on a connection.\nfunc SetTCPTimeouts(conn *net.TCPConn) error {\n\t\/\/ Set TCP_USER_TIMEOUT option to limit the maximum amount of time in ms that transmitted data may remain\n\t\/\/ unacknowledged before TCP will forcefully close the corresponding connection and return ETIMEDOUT to the\n\t\/\/ application. This combined with the TCP keepalive options on the socket will ensure that should the\n\t\/\/ remote side of the connection disappear abruptly that LXD will detect this and close the socket quickly.\n\t\/\/ Decreasing the user timeouts allows applications to \"fail fast\" if so desired. Otherwise it may take\n\t\/\/ up to 20 minutes with the current system defaults in a normal WAN environment if there are packets in\n\t\/\/ the send queue that will prevent the keepalive timer from working as the retransmission timers kick in.\n\t\/\/ See https:\/\/git.kernel.org\/pub\/scm\/linux\/kernel\/git\/torvalds\/linux.git\/commit\/?id=dca43c75e7e545694a9dd6288553f55c53e2a3a3\n\terr := SetTCPUserTimeout(conn, time.Second*30)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = conn.SetKeepAlive(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = conn.SetKeepAlivePeriod(3 * time.Second)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ SetTCPUserTimeout sets the TCP user timeout on a connection's socket\nfunc SetTCPUserTimeout(conn *net.TCPConn, timeout time.Duration) error {\n\trawConn, err := conn.SyscallConn()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting raw connection: %w\", err)\n\t}\n\n\terr = rawConn.Control(func(fd uintptr) {\n\t\terr = syscall.SetsockoptInt(int(fd), syscall.IPPROTO_TCP, unix.TCP_USER_TIMEOUT, int(timeout\/time.Millisecond))\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error setting option on socket: %w\", err)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package quotes\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/graffic\/wanon\/bot\"\n\t\"github.com\/graffic\/wanon\/telegram\"\n\t\"github.com\/op\/go-logging\"\n)\n\ntype addQuote struct{}\n\nvar l = logging.MustGetLogger(\"wanon.messages.quotes\")\n\nfunc (handler *addQuote) Check(message *telegram.Message, context *bot.Context) int {\n\tisAddQuote := strings.Index(message.Text, \"\/addquote\") == 0\n\tisReply := message.ReplyToMessage != nil\n\n\tif !isAddQuote {\n\t\treturn bot.RouteNothing\n\t}\n\n\tif !isReply {\n\t\tanswer := telegram.AnswerBack{API: context.API, Message: message}\n\t\tanswer.Reply(\"To add a quote use \/addquote in a reply\")\n\n\t\treturn bot.RouteNothing\n\t}\n\n\tl.Info(\"Adding quote\")\n\treturn bot.RouteAccept\n}\n\nfunc (handler *addQuote) Handle(message *telegram.Message, context *bot.Context) {\n\tquotes := quoteStorage{context.Storage}\n\tquote := Quote{\n\t\tAddedBy: message.From.Username,\n\t\tSaidBy:  message.ReplyToMessage.From.Username,\n\t\tWhen:    message.Date,\n\t\tWhat:    message.ReplyToMessage.Text,\n\t}\n\n\terr := quotes.AddQuote(message.Chat.ID, &quote)\n\tif err != nil {\n\t\tl.Fatal(err)\n\t}\n\tl.Info(\"Quote Added: <%s> %s\", quote.SaidBy, quote.What)\n}\n\n\/\/ CreateAddQuote does nothing\nfunc CreateAddQuote() bot.Handler {\n\treturn new(addQuote)\n}\n<commit_msg>Dummy message when a quote is added<commit_after>package quotes\n\nimport (\n\t\"strings\"\n\n\t\"github.com\/graffic\/wanon\/bot\"\n\t\"github.com\/graffic\/wanon\/telegram\"\n\t\"github.com\/op\/go-logging\"\n)\n\ntype addQuote struct{}\n\nvar l = logging.MustGetLogger(\"wanon.messages.quotes\")\n\nfunc (handler *addQuote) Check(message *telegram.Message, context *bot.Context) int {\n\tisAddQuote := strings.Index(message.Text, \"\/addquote\") == 0\n\tisReply := message.ReplyToMessage != nil\n\n\tif !isAddQuote {\n\t\treturn bot.RouteNothing\n\t}\n\n\tif !isReply {\n\t\tanswer := telegram.AnswerBack{API: context.API, Message: message}\n\t\tanswer.Reply(\"To add a quote use \/addquote in a reply\")\n\n\t\treturn bot.RouteNothing\n\t}\n\n\tl.Info(\"Adding quote\")\n\treturn bot.RouteAccept\n}\n\nfunc (handler *addQuote) Handle(message *telegram.Message, context *bot.Context) {\n\tquotes := quoteStorage{context.Storage}\n\tquote := Quote{\n\t\tAddedBy: message.From.Username,\n\t\tSaidBy:  message.ReplyToMessage.From.Username,\n\t\tWhen:    message.Date,\n\t\tWhat:    message.ReplyToMessage.Text,\n\t}\n\n\terr := quotes.AddQuote(message.Chat.ID, &quote)\n\tif err != nil {\n\t\tl.Fatal(err)\n\t}\n\tl.Info(\"Quote Added: <%s> %s\", quote.SaidBy, quote.What)\n\tanswer := telegram.AnswerBack{API: context.API, Message: message}\n\tanswer.Reply(\"procesado correctamente, siguienteeeeeee!!!!\")\n}\n\n\/\/ CreateAddQuote does nothing\nfunc CreateAddQuote() bot.Handler {\n\treturn new(addQuote)\n}\n<|endoftext|>"}
{"text":"<commit_before>package flagmqtt\n\nimport (\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"errors\"\n\t\"fmt\"\n\tmq \"github.com\/eclipse\/paho.mqtt.golang\"\n\t\"github.com\/satori\/go.uuid\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype ClientConfig struct {\n\tWillTopic               string\n\tWillPayload             string\n\tWillQoS                 int\n\tWillRetain              bool\n\tClientID                string\n\tOnConnectHandler        func(mq.Client)\n\tOnConnectionLostHandler func(mq.Client, error)\n}\n\nfunc NewPersistentMqtt(config ClientConfig) (mqttClient mq.Client, err error) {\n\tuseTls := false\n\n\tif val, ok := os.LookupEnv(\"MQTT_TLS\"); ok {\n\t\tuseTls = val != \"0\" && val != \"\" && strings.ToLower(val) != \"false\"\n\t}\n\tif *MqttTLSFlag {\n\t\tuseTls = true\n\t}\n\n\tcaPath := envOrFlagStr(*MqttCAFlag, \"MQTT_CA_PATH\", \"\")\n\tcertPath := envOrFlagStr(*MqttCertFlag, \"MQTT_CERT_PATH\", \"\")\n\tkeyPath := envOrFlagStr(*MqttKeyFlag, \"MQTT_KEY_PATH\", \"\")\n\taddress := envOrFlagStr(*MqttAddressFlag, \"MQTT_ADDRESS\", \"localhost:1883\")\n\tusername := envOrFlagStr(*MqttUsernameFlag, \"MQTT_USERNAME\", \"\")\n\tpassword := envOrFlagStr(*MqttPasswordFlag, \"MQTT_PASSWORD\", \"\")\n\tconnectionTimeout := envOrFlagInt(*MqttConnectionTimeout, \"MQTT_CONNECTION_TIMEOUT\", 10)\n\tkeepAlive := envOrFlagInt(*MqttKeepAlive, \"MQTT_KEEPALIVE\", 5)\n\tmaxReconnectInterval := envOrFlagInt(*MqttMaxReconnectInterval, \"MQTT_MAX_RECONNECT_INTERVAL\", 2)\n\tpingTimeout := envOrFlagInt(*MqttPingTimeout, \"MQTT_PING_TIMEOUT\", 10)\n\twriteTimeout := envOrFlagInt(*MqttWriteTimeout, \"MQTT_WRITE_TIMEOUT\", 5)\n\n\tvar tlsCfg *tls.Config\n\tif useTls {\n\t\ttlsCfg, err = setupTLS(caPath, certPath, keyPath)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tclientId := config.ClientID\n\n\tif clientId == \"\" {\n\t\tvar rndUuid uuid.UUID\n\t\trndUuid = uuid.NewV4()\n\t\tclientId = rndUuid.String()\n\t}\n\n\topts := mq.NewClientOptions().\n\t\tAddBroker(fmt.Sprintf(\"tcp:\/\/%s\", address)).\n\t\tSetClientID(clientId).\n\t\tSetConnectTimeout(time.Duration(connectionTimeout) * time.Second).\n\t\tSetKeepAlive(time.Duration(keepAlive) * time.Second).\n\t\tSetMaxReconnectInterval(time.Duration(maxReconnectInterval) * time.Minute).\n\t\tSetMessageChannelDepth(100).\n\t\tSetPingTimeout(time.Duration(pingTimeout) * time.Second).\n\t\tSetProtocolVersion(4).\n\t\tSetWriteTimeout(time.Duration(writeTimeout) * time.Second)\n\n\tif config.OnConnectHandler != nil {\n\t\topts.SetOnConnectHandler(config.OnConnectHandler)\n\t}\n\n\tif config.OnConnectionLostHandler != nil {\n\t\topts.SetConnectionLostHandler(config.OnConnectionLostHandler)\n\t}\n\n\tif config.WillTopic != \"\" {\n\t\topts.SetWill(\n\t\t\tconfig.WillTopic,\n\t\t\tconfig.WillPayload,\n\t\t\tbyte(config.WillQoS&0xff),\n\t\t\tconfig.WillRetain,\n\t\t)\n\t}\n\n\tif username != \"\" {\n\t\topts.SetUsername(username)\n\t}\n\tif password != \"\" {\n\t\topts.SetPassword(password)\n\t}\n\tif useTls {\n\t\topts.SetTLSConfig(tlsCfg)\n\t}\n\n\treturn mq.NewClient(opts), nil\n}\n\n\/\/ NewUniqueIdentifier returns a unique identifier that the client can use.\n\/\/ This identifier is what should be set for the lastWillID for anything\n\/\/ that is bridging more than one device\nfunc NewUniqueIdentifier() string {\n\treturn uuid.NewV4().String()\n}\n\nfunc setupTLS(caPath, certPath, keyPath string) (*tls.Config, error) {\n\ttlsCfg := &tls.Config{}\n\tif caPath != \"\" {\n\t\tcaPem, err := ioutil.ReadFile(caPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttlsCfg.RootCAs = x509.NewCertPool()\n\t\ttlsCfg.RootCAs.AppendCertsFromPEM(caPem)\n\t}\n\n\tif certPath != \"\" && keyPath != \"\" {\n\t\tif keyPath == \"\" {\n\t\t\treturn nil, errors.New(\"Certificate path specified, but key path missing\")\n\t\t}\n\t\tcert, err := tls.LoadX509KeyPair(certPath, keyPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttlsCfg.Certificates = []tls.Certificate{cert}\n\t\ttlsCfg.BuildNameToCertificate()\n\t}\n\n\treturn tlsCfg, nil\n}\n<commit_msg>:ambulance: Don't care about the callback order<commit_after>package flagmqtt\n\nimport (\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"errors\"\n\t\"fmt\"\n\tmq \"github.com\/eclipse\/paho.mqtt.golang\"\n\t\"github.com\/satori\/go.uuid\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype ClientConfig struct {\n\tWillTopic               string\n\tWillPayload             string\n\tWillQoS                 int\n\tWillRetain              bool\n\tClientID                string\n\tOnConnectHandler        func(mq.Client)\n\tOnConnectionLostHandler func(mq.Client, error)\n}\n\nfunc NewPersistentMqtt(config ClientConfig) (mqttClient mq.Client, err error) {\n\tuseTls := false\n\n\tif val, ok := os.LookupEnv(\"MQTT_TLS\"); ok {\n\t\tuseTls = val != \"0\" && val != \"\" && strings.ToLower(val) != \"false\"\n\t}\n\tif *MqttTLSFlag {\n\t\tuseTls = true\n\t}\n\n\tcaPath := envOrFlagStr(*MqttCAFlag, \"MQTT_CA_PATH\", \"\")\n\tcertPath := envOrFlagStr(*MqttCertFlag, \"MQTT_CERT_PATH\", \"\")\n\tkeyPath := envOrFlagStr(*MqttKeyFlag, \"MQTT_KEY_PATH\", \"\")\n\taddress := envOrFlagStr(*MqttAddressFlag, \"MQTT_ADDRESS\", \"localhost:1883\")\n\tusername := envOrFlagStr(*MqttUsernameFlag, \"MQTT_USERNAME\", \"\")\n\tpassword := envOrFlagStr(*MqttPasswordFlag, \"MQTT_PASSWORD\", \"\")\n\tconnectionTimeout := envOrFlagInt(*MqttConnectionTimeout, \"MQTT_CONNECTION_TIMEOUT\", 10)\n\tkeepAlive := envOrFlagInt(*MqttKeepAlive, \"MQTT_KEEPALIVE\", 5)\n\tmaxReconnectInterval := envOrFlagInt(*MqttMaxReconnectInterval, \"MQTT_MAX_RECONNECT_INTERVAL\", 2)\n\tpingTimeout := envOrFlagInt(*MqttPingTimeout, \"MQTT_PING_TIMEOUT\", 10)\n\twriteTimeout := envOrFlagInt(*MqttWriteTimeout, \"MQTT_WRITE_TIMEOUT\", 5)\n\n\tvar tlsCfg *tls.Config\n\tif useTls {\n\t\ttlsCfg, err = setupTLS(caPath, certPath, keyPath)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tclientId := config.ClientID\n\n\tif clientId == \"\" {\n\t\tvar rndUuid uuid.UUID\n\t\trndUuid = uuid.NewV4()\n\t\tclientId = rndUuid.String()\n\t}\n\n\topts := mq.NewClientOptions().\n\t\tAddBroker(fmt.Sprintf(\"tcp:\/\/%s\", address)).\n\t\tSetClientID(clientId).\n\t\tSetConnectTimeout(time.Duration(connectionTimeout) * time.Second).\n\t\tSetKeepAlive(time.Duration(keepAlive) * time.Second).\n\t\tSetMaxReconnectInterval(time.Duration(maxReconnectInterval) * time.Minute).\n\t\tSetMessageChannelDepth(100).\n\t\tSetPingTimeout(time.Duration(pingTimeout) * time.Second).\n\t\tSetProtocolVersion(4).\n\t\tSetOrderMatters(false).\n\t\tSetWriteTimeout(time.Duration(writeTimeout) * time.Second)\n\n\tif config.OnConnectHandler != nil {\n\t\topts.SetOnConnectHandler(config.OnConnectHandler)\n\t}\n\n\tif config.OnConnectionLostHandler != nil {\n\t\topts.SetConnectionLostHandler(config.OnConnectionLostHandler)\n\t}\n\n\tif config.WillTopic != \"\" {\n\t\topts.SetWill(\n\t\t\tconfig.WillTopic,\n\t\t\tconfig.WillPayload,\n\t\t\tbyte(config.WillQoS&0xff),\n\t\t\tconfig.WillRetain,\n\t\t)\n\t}\n\n\tif username != \"\" {\n\t\topts.SetUsername(username)\n\t}\n\tif password != \"\" {\n\t\topts.SetPassword(password)\n\t}\n\tif useTls {\n\t\topts.SetTLSConfig(tlsCfg)\n\t}\n\n\treturn mq.NewClient(opts), nil\n}\n\n\/\/ NewUniqueIdentifier returns a unique identifier that the client can use.\n\/\/ This identifier is what should be set for the lastWillID for anything\n\/\/ that is bridging more than one device\nfunc NewUniqueIdentifier() string {\n\treturn uuid.NewV4().String()\n}\n\nfunc setupTLS(caPath, certPath, keyPath string) (*tls.Config, error) {\n\ttlsCfg := &tls.Config{}\n\tif caPath != \"\" {\n\t\tcaPem, err := ioutil.ReadFile(caPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttlsCfg.RootCAs = x509.NewCertPool()\n\t\ttlsCfg.RootCAs.AppendCertsFromPEM(caPem)\n\t}\n\n\tif certPath != \"\" && keyPath != \"\" {\n\t\tif keyPath == \"\" {\n\t\t\treturn nil, errors.New(\"Certificate path specified, but key path missing\")\n\t\t}\n\t\tcert, err := tls.LoadX509KeyPair(certPath, keyPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttlsCfg.Certificates = []tls.Certificate{cert}\n\t\ttlsCfg.BuildNameToCertificate()\n\t}\n\n\treturn tlsCfg, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package lzma\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"io\"\n)\n\n\/\/ states defines the overall state count\nconst states = 12\n\n\/\/ bufferLen is the value used for the bufferLen used by the decoder.\nvar bufferLen = 64 * (1 << 10)\n\n\/\/ Decoder is able to read a LZMA byte stream and to read the plain text.\ntype Decoder struct {\n\tproperties         Properties\n\tpackedLen          uint64\n\tunpackedLen        uint64\n\tunpackedLenDefined bool\n\tdict               *decoderDict\n\tstate              uint32\n\tposBitMask         uint32\n\trd                 *rangeDecoder\n\tisMatch            [states << maxPosBits]prob\n\tisRep              [states]prob\n\tisRepG0            [states]prob\n\tisRepG1            [states]prob\n\tisRepG2            [states]prob\n\tisRepG0Long        [states << maxPosBits]prob\n\trep                [4]uint32\n\tlitDecoder         *literalCodec\n\tlengthDecoder      *lengthCodec\n\tdistDecoder        *distCodec\n}\n\n\/\/ NewDecoder creates an LZMA decoder. It reads the classic, original LZMA\n\/\/ format. Note that LZMA2 uses a different header format.\nfunc NewDecoder(r io.Reader) (d *Decoder, err error) {\n\tf := bufio.NewReader(r)\n\tproperties, err := readProperties(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thistoryLen := int(properties.DictLen)\n\tif historyLen < 0 {\n\t\treturn nil, errors.New(\n\t\t\t\"LZMA property DictLen exceeds maximum int value\")\n\t}\n\td = &Decoder{\n\t\tproperties: *properties,\n\t}\n\tif d.packedLen, err = readUint64LE(f); err != nil {\n\t\treturn nil, err\n\t}\n\tif d.dict, err = newDecoderDict(bufferLen, historyLen); err != nil {\n\t\treturn nil, err\n\t}\n\td.posBitMask = (uint32(1) << uint(d.properties.PB)) - 1\n\tif d.rd, err = newRangeDecoder(f); err != nil {\n\t\treturn nil, err\n\t}\n\tinitProbSlice(d.isMatch[:])\n\tinitProbSlice(d.isRep[:])\n\tinitProbSlice(d.isRepG0[:])\n\tinitProbSlice(d.isRepG1[:])\n\tinitProbSlice(d.isRepG2[:])\n\tinitProbSlice(d.isRepG0Long[:])\n\td.litDecoder = newLiteralCodec(d.properties.LC, d.properties.LP)\n\td.lengthDecoder = newLengthCodec()\n\td.distDecoder = newDistCodec()\n\treturn d, nil\n}\n\n\/\/ Properties returns a set of properties.\nfunc (d *Decoder) Properties() Properties {\n\treturn d.properties\n}\n\n\/\/ getUint64LE converts the uint64 value stored as little endian to an uint64\n\/\/ value.\nfunc getUint64LE(b []byte) uint64 {\n\tx := uint64(b[7]) << 56\n\tx |= uint64(b[6]) << 48\n\tx |= uint64(b[5]) << 40\n\tx |= uint64(b[4]) << 32\n\tx |= uint64(b[3]) << 24\n\tx |= uint64(b[2]) << 16\n\tx |= uint64(b[1]) << 8\n\tx |= uint64(b[0])\n\treturn x\n}\n\n\/\/ readUint64LE reads a uint64 little-endian integer from reader.\nfunc readUint64LE(r io.Reader) (x uint64, err error) {\n\tb := make([]byte, 8)\n\tif _, err = io.ReadFull(r, b); err != nil {\n\t\treturn 0, err\n\t}\n\tx = getUint64LE(b)\n\treturn x, nil\n}\n\n\/\/ initProbSlice initializes a slice of probabilities.\nfunc initProbSlice(p []prob) {\n\tfor i := range p {\n\t\tp[i] = probInit\n\t}\n}\n\n\/\/ Reads reads data from the decoder stream.\n\/\/\n\/\/ The function fill put as much data in the buffer as it is available. The\n\/\/ function might block and is not reentrant.\n\/\/\n\/\/ The end of the LZMA stream is indicated by EOF. There might be other errors\n\/\/ returned. The decoder will not be able to recover from an error returned.\nfunc (d *Decoder) Read(p []byte) (n int, err error) {\n\tfor n < len(p) {\n\t\tvar k int\n\t\tk, err = d.dict.Read(p)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += k\n\t\tif n == len(p) {\n\t\t\treturn\n\t\t}\n\t\tif err = d.fill(len(p) - n); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ fill puts at lest the requested number of bytes into the decoder dictionary.\nfunc (d *Decoder) fill(n int) error {\n\tpanic(\"TODO\")\n}\n\n\/\/ updateStateLiteral updates the state for a literal.\nfunc (d *Decoder) updateStateLiteral() {\n\tswitch {\n\tcase d.state < 4:\n\t\td.state = 0\n\t\treturn\n\tcase d.state < 10:\n\t\td.state -= 3\n\t\treturn\n\t}\n\td.state -= 6\n\treturn\n}\n\n\/\/ updateStateMatch updates the state for a match.\nfunc (d *Decoder) updateStateMatch() {\n\tif d.state < 7 {\n\t\td.state = 7\n\t\treturn\n\t}\n\td.state = 10\n\treturn\n}\n\n\/\/ updateStateRep updates the state for a repetition.\nfunc (d *Decoder) updateStateRep() {\n\tif d.state < 7 {\n\t\td.state = 8\n\t}\n\td.state = 11\n}\n\n\/\/ updateStateShortRep updates the state for a short repetition.\nfunc (d *Decoder) updateStateShortRep() {\n\tif d.state < 7 {\n\t\td.state = 9\n\t}\n\td.state = 11\n}\n\n\/\/ decodeLiteral decodes a literal.\nfunc (d *Decoder) decodeLiteral() (op operation, err error) {\n\tprevByte := d.dict.getByte(1)\n\tlp, lc := uint(d.properties.LP), uint(d.properties.LC)\n\tlitState := ((uint32(d.dict.total) & ((1 << lp) - 1)) << lc) |\n\t\t(uint32(prevByte) >> (8 - lc))\n\tmatch := d.dict.getByte(int(d.rep[0]) + 1)\n\ts, err := d.litDecoder.Decode(d.rd, d.state, match, litState)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lit{s}, nil\n}\n\n\/\/ errWrongTermination indicates that a termination symbol has been received,\n\/\/ but the range decoder could still produces more data\nvar errWrongTermination = errors.New(\n\t\"range decoder doesn't support termination\")\n\n\/\/ decodeOp decodes an operation. The function returns io.EOF if the stream is\n\/\/ terminated.\nfunc (d *Decoder) decodeOp() (op operation, err error) {\n\tposState := uint32(d.dict.total) & d.posBitMask\n\tstate2 := (d.state << maxPosBits) | posState\n\n\tb, err := d.isMatch[state2].Decode(d.rd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif b == 0 {\n\t\t\/\/ literal\n\t\top, err := d.decodeLiteral()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\td.updateStateLiteral()\n\t\treturn op, nil\n\t}\n\tb, err = d.isRep[d.state].Decode(d.rd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif b == 0 {\n\t\t\/\/ simple match\n\t\td.rep[3], d.rep[2], d.rep[1] = d.rep[2], d.rep[1], d.rep[0]\n\t\td.updateStateMatch()\n\t\t\/\/ TODO: check base for output of length decoder\n\t\tn, err := d.lengthDecoder.Decode(d.rd, posState)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ TODO: check that distDecoder is using the same base as the\n\t\t\/\/ output of the lengthDecoder\n\t\t\/\/ TODO: check base of the repetition\n\t\td.rep[0], err = d.distDecoder.Decode(n, d.rd)\n\t\tif d.rep[0] == 0xffffffff {\n\t\t\tif !d.rd.possiblyAtEnd() {\n\t\t\t\treturn nil, errWrongTermination\n\t\t\t}\n\t\t\treturn nil, io.EOF\n\t\t}\n\t\t\/\/ TODO: Create translator in rep operation\n\t\top := rep{length: int(n), distance: int(d.rep[0])}\n\t\treturn op, nil\n\t}\n\tb, err = d.isRepG0[d.state].Decode(d.rd)\n\tif b == 0 {\n\t\t\/\/ rep0\n\t\tpanic(\"TODO\")\n\t}\n\tb, err = d.isRepG1[d.state].Decode(d.rd)\n\tif b == 0 {\n\t\t\/\/ rep match 1\n\t\tpanic(\"TODO\")\n\t}\n\tb, err = d.isRepG2[d.state].Decode(d.rd)\n\tif b == 0 {\n\t\t\/\/ rep match 2\n\t\tpanic(\"TODO\")\n\t}\n\t\/\/ rep match 3\n\tpanic(\"TODO\")\n}\n<commit_msg>lzma: more work on the simple match case in the op decoder<commit_after>package lzma\n\nimport (\n\t\"bufio\"\n\t\"errors\"\n\t\"io\"\n)\n\n\/\/ states defines the overall state count\nconst states = 12\n\n\/\/ bufferLen is the value used for the bufferLen used by the decoder.\nvar bufferLen = 64 * (1 << 10)\n\n\/\/ Decoder is able to read a LZMA byte stream and to read the plain text.\ntype Decoder struct {\n\tproperties         Properties\n\tpackedLen          uint64\n\tunpackedLen        uint64\n\tunpackedLenDefined bool\n\tdict               *decoderDict\n\tstate              uint32\n\tposBitMask         uint32\n\trd                 *rangeDecoder\n\tisMatch            [states << maxPosBits]prob\n\tisRep              [states]prob\n\tisRepG0            [states]prob\n\tisRepG1            [states]prob\n\tisRepG2            [states]prob\n\tisRepG0Long        [states << maxPosBits]prob\n\trep                [4]uint32\n\tlitDecoder         *literalCodec\n\tlengthDecoder      *lengthCodec\n\tdistDecoder        *distCodec\n}\n\n\/\/ NewDecoder creates an LZMA decoder. It reads the classic, original LZMA\n\/\/ format. Note that LZMA2 uses a different header format.\nfunc NewDecoder(r io.Reader) (d *Decoder, err error) {\n\tf := bufio.NewReader(r)\n\tproperties, err := readProperties(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thistoryLen := int(properties.DictLen)\n\tif historyLen < 0 {\n\t\treturn nil, errors.New(\n\t\t\t\"LZMA property DictLen exceeds maximum int value\")\n\t}\n\td = &Decoder{\n\t\tproperties: *properties,\n\t}\n\tif d.packedLen, err = readUint64LE(f); err != nil {\n\t\treturn nil, err\n\t}\n\tif d.dict, err = newDecoderDict(bufferLen, historyLen); err != nil {\n\t\treturn nil, err\n\t}\n\td.posBitMask = (uint32(1) << uint(d.properties.PB)) - 1\n\tif d.rd, err = newRangeDecoder(f); err != nil {\n\t\treturn nil, err\n\t}\n\tinitProbSlice(d.isMatch[:])\n\tinitProbSlice(d.isRep[:])\n\tinitProbSlice(d.isRepG0[:])\n\tinitProbSlice(d.isRepG1[:])\n\tinitProbSlice(d.isRepG2[:])\n\tinitProbSlice(d.isRepG0Long[:])\n\td.litDecoder = newLiteralCodec(d.properties.LC, d.properties.LP)\n\td.lengthDecoder = newLengthCodec()\n\td.distDecoder = newDistCodec()\n\treturn d, nil\n}\n\n\/\/ Properties returns a set of properties.\nfunc (d *Decoder) Properties() Properties {\n\treturn d.properties\n}\n\n\/\/ getUint64LE converts the uint64 value stored as little endian to an uint64\n\/\/ value.\nfunc getUint64LE(b []byte) uint64 {\n\tx := uint64(b[7]) << 56\n\tx |= uint64(b[6]) << 48\n\tx |= uint64(b[5]) << 40\n\tx |= uint64(b[4]) << 32\n\tx |= uint64(b[3]) << 24\n\tx |= uint64(b[2]) << 16\n\tx |= uint64(b[1]) << 8\n\tx |= uint64(b[0])\n\treturn x\n}\n\n\/\/ readUint64LE reads a uint64 little-endian integer from reader.\nfunc readUint64LE(r io.Reader) (x uint64, err error) {\n\tb := make([]byte, 8)\n\tif _, err = io.ReadFull(r, b); err != nil {\n\t\treturn 0, err\n\t}\n\tx = getUint64LE(b)\n\treturn x, nil\n}\n\n\/\/ initProbSlice initializes a slice of probabilities.\nfunc initProbSlice(p []prob) {\n\tfor i := range p {\n\t\tp[i] = probInit\n\t}\n}\n\n\/\/ Reads reads data from the decoder stream.\n\/\/\n\/\/ The function fill put as much data in the buffer as it is available. The\n\/\/ function might block and is not reentrant.\n\/\/\n\/\/ The end of the LZMA stream is indicated by EOF. There might be other errors\n\/\/ returned. The decoder will not be able to recover from an error returned.\nfunc (d *Decoder) Read(p []byte) (n int, err error) {\n\tfor n < len(p) {\n\t\tvar k int\n\t\tk, err = d.dict.Read(p)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tn += k\n\t\tif n == len(p) {\n\t\t\treturn\n\t\t}\n\t\tif err = d.fill(len(p) - n); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ fill puts at lest the requested number of bytes into the decoder dictionary.\nfunc (d *Decoder) fill(n int) error {\n\tpanic(\"TODO\")\n}\n\n\/\/ updateStateLiteral updates the state for a literal.\nfunc (d *Decoder) updateStateLiteral() {\n\tswitch {\n\tcase d.state < 4:\n\t\td.state = 0\n\t\treturn\n\tcase d.state < 10:\n\t\td.state -= 3\n\t\treturn\n\t}\n\td.state -= 6\n\treturn\n}\n\n\/\/ updateStateMatch updates the state for a match.\nfunc (d *Decoder) updateStateMatch() {\n\tif d.state < 7 {\n\t\td.state = 7\n\t\treturn\n\t}\n\td.state = 10\n\treturn\n}\n\n\/\/ updateStateRep updates the state for a repetition.\nfunc (d *Decoder) updateStateRep() {\n\tif d.state < 7 {\n\t\td.state = 8\n\t}\n\td.state = 11\n}\n\n\/\/ updateStateShortRep updates the state for a short repetition.\nfunc (d *Decoder) updateStateShortRep() {\n\tif d.state < 7 {\n\t\td.state = 9\n\t}\n\td.state = 11\n}\n\n\/\/ decodeLiteral decodes a literal.\nfunc (d *Decoder) decodeLiteral() (op operation, err error) {\n\tprevByte := d.dict.getByte(1)\n\tlp, lc := uint(d.properties.LP), uint(d.properties.LC)\n\tlitState := ((uint32(d.dict.total) & ((1 << lp) - 1)) << lc) |\n\t\t(uint32(prevByte) >> (8 - lc))\n\tmatch := d.dict.getByte(int(d.rep[0]) + 1)\n\ts, err := d.litDecoder.Decode(d.rd, d.state, match, litState)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn lit{s}, nil\n}\n\n\/\/ errWrongTermination indicates that a termination symbol has been received,\n\/\/ but the range decoder could still produces more data\nvar errWrongTermination = errors.New(\n\t\"range decoder doesn't support termination\")\n\n\/\/ decodeOp decodes an operation. The function returns io.EOF if the stream is\n\/\/ terminated.\nfunc (d *Decoder) decodeOp() (op operation, err error) {\n\tposState := uint32(d.dict.total) & d.posBitMask\n\tstate2 := (d.state << maxPosBits) | posState\n\n\tb, err := d.isMatch[state2].Decode(d.rd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif b == 0 {\n\t\t\/\/ literal\n\t\top, err := d.decodeLiteral()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\td.updateStateLiteral()\n\t\treturn op, nil\n\t}\n\tb, err = d.isRep[d.state].Decode(d.rd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif b == 0 {\n\t\t\/\/ simple match\n\t\td.rep[3], d.rep[2], d.rep[1] = d.rep[2], d.rep[1], d.rep[0]\n\t\td.updateStateMatch()\n\t\t\/\/ The length decoder returns the length offset.\n\t\tl, err := d.lengthDecoder.Decode(d.rd, posState)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\t\/\/ TODO: check that distDecoder is using the same base as the\n\t\t\/\/ output of the lengthDecoder\n\t\t\/\/ TODO: check base of the repetition\n\t\td.rep[0], err = d.distDecoder.Decode(l, d.rd)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif d.rep[0] == 0xffffffff {\n\t\t\tif !d.rd.possiblyAtEnd() {\n\t\t\t\treturn nil, errWrongTermination\n\t\t\t}\n\t\t\treturn nil, io.EOF\n\t\t}\n\t\top := rep{length: int(l + minLength), distance: int(d.rep[0])}\n\t\treturn op, nil\n\t}\n\tb, err = d.isRepG0[d.state].Decode(d.rd)\n\tif b == 0 {\n\t\t\/\/ rep0\n\t\tpanic(\"TODO\")\n\t}\n\tb, err = d.isRepG1[d.state].Decode(d.rd)\n\tif b == 0 {\n\t\t\/\/ rep match 1\n\t\tpanic(\"TODO\")\n\t}\n\tb, err = d.isRepG2[d.state].Decode(d.rd)\n\tif b == 0 {\n\t\t\/\/ rep match 2\n\t\tpanic(\"TODO\")\n\t}\n\t\/\/ rep match 3\n\tpanic(\"TODO\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package collectors\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\n\t\"github.com\/cloudfoundry-community\/firehose_exporter\/metrics\"\n\t\"github.com\/cloudfoundry-community\/firehose_exporter\/utils\"\n)\n\ntype valueMetricsCollector struct {\n\tnamespace                 string\n\tmetricsStore              *metrics.Store\n\tvalueMetricsCollectorDesc *prometheus.Desc\n}\n\nfunc NewValueMetricsCollector(\n\tnamespace string,\n\tmetricsStore *metrics.Store,\n) *valueMetricsCollector {\n\tvalueMetricsCollectorDesc := prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, value_metrics_subsystem, \"collector\"),\n\t\t\"Cloud Foundry Firehose value metrics collector.\",\n\t\tnil,\n\t\tnil,\n\t)\n\n\tcollector := &valueMetricsCollector{\n\t\tnamespace:                 namespace,\n\t\tmetricsStore:              metricsStore,\n\t\tvalueMetricsCollectorDesc: valueMetricsCollectorDesc,\n\t}\n\treturn collector\n}\n\nfunc (c valueMetricsCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, valueMetric := range c.metricsStore.GetValueMetrics() {\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tprometheus.NewDesc(\n\t\t\t\tprometheus.BuildFQName(c.namespace, value_metrics_subsystem, utils.NormalizeName(valueMetric.Name)),\n\t\t\t\tfmt.Sprintf(\"Cloud Foundry firehose '%s' value metric.\", valueMetric.Name),\n\t\t\t\t[]string{\"origin\", \"deployment\", \"job\", \"index\", \"ip\", \"unit\"},\n\t\t\t\tnil,\n\t\t\t),\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(valueMetric.Value),\n\t\t\tvalueMetric.Origin,\n\t\t\tvalueMetric.Deployment,\n\t\t\tvalueMetric.Job,\n\t\t\tvalueMetric.Index,\n\t\t\tvalueMetric.IP,\n\t\t\tvalueMetric.Unit,\n\t\t)\n\t}\n}\n\nfunc (c valueMetricsCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.valueMetricsCollectorDesc\n}\n<commit_msg>Append origin to value metrics<commit_after>package collectors\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\n\t\"github.com\/cloudfoundry-community\/firehose_exporter\/metrics\"\n\t\"github.com\/cloudfoundry-community\/firehose_exporter\/utils\"\n)\n\ntype valueMetricsCollector struct {\n\tnamespace                 string\n\tmetricsStore              *metrics.Store\n\tvalueMetricsCollectorDesc *prometheus.Desc\n}\n\nfunc NewValueMetricsCollector(\n\tnamespace string,\n\tmetricsStore *metrics.Store,\n) *valueMetricsCollector {\n\tvalueMetricsCollectorDesc := prometheus.NewDesc(\n\t\tprometheus.BuildFQName(namespace, value_metrics_subsystem, \"collector\"),\n\t\t\"Cloud Foundry Firehose value metrics collector.\",\n\t\tnil,\n\t\tnil,\n\t)\n\n\tcollector := &valueMetricsCollector{\n\t\tnamespace:                 namespace,\n\t\tmetricsStore:              metricsStore,\n\t\tvalueMetricsCollectorDesc: valueMetricsCollectorDesc,\n\t}\n\treturn collector\n}\n\nfunc (c valueMetricsCollector) Collect(ch chan<- prometheus.Metric) {\n\tfor _, valueMetric := range c.metricsStore.GetValueMetrics() {\n\t\tmetricName := utils.NormalizeName(valueMetric.Origin) + \"_\" + utils.NormalizeName(valueMetric.Name)\n\t\tch <- prometheus.MustNewConstMetric(\n\t\t\tprometheus.NewDesc(\n\t\t\t\tprometheus.BuildFQName(c.namespace, value_metrics_subsystem, metricName),\n\t\t\t\tfmt.Sprintf(\"Cloud Foundry Firehose '%s' value metric.\", valueMetric.Name),\n\t\t\t\t[]string{\"origin\", \"deployment\", \"job\", \"index\", \"ip\", \"unit\"},\n\t\t\t\tnil,\n\t\t\t),\n\t\t\tprometheus.GaugeValue,\n\t\t\tfloat64(valueMetric.Value),\n\t\t\tvalueMetric.Origin,\n\t\t\tvalueMetric.Deployment,\n\t\t\tvalueMetric.Job,\n\t\t\tvalueMetric.Index,\n\t\t\tvalueMetric.IP,\n\t\t\tvalueMetric.Unit,\n\t\t)\n\t}\n}\n\nfunc (c valueMetricsCollector) Describe(ch chan<- *prometheus.Desc) {\n\tch <- c.valueMetricsCollectorDesc\n}\n<|endoftext|>"}
{"text":"<commit_before>package chat\n\nimport (\n\t\"crypto\/rand\"\n\t\"errors\"\n\t\"io\"\n\n\t\"github.com\/agl\/ed25519\"\n\t\"github.com\/keybase\/client\/go\/chat\/signencrypt\"\n\t\"github.com\/keybase\/client\/go\/libkb\"\n)\n\ntype Encrypter interface {\n\t\/\/ EncryptedLen returns the number of bytes that the ciphertext of\n\t\/\/ size plaintext bytes will be.\n\tEncryptedLen(size int) int\n\n\t\/\/ Encrypt takes a plaintext reader and returns a ciphertext reader.\n\t\/\/ It generates new keys every time it is called.\n\tEncrypt(plaintext io.Reader) (ciphertext io.Reader, err error)\n\n\t\/\/ EncryptKey returns the ephemeral key that was used during Encrypt.\n\tEncryptKey() []byte\n\n\t\/\/ VerifyKey returns the public portion of the signing key that\n\t\/\/ can be used for signature verification.\n\tVerifyKey() []byte\n}\n\ntype Decrypter interface {\n\t\/\/ Decrypt takes a ciphertext reader, encryption and verify keys.\n\t\/\/ It returns a plaintext reader.\n\tDecrypt(ciphertext io.Reader, encKey, verifyKey []byte) (plaintext io.Reader)\n}\n\nvar nonce signencrypt.Nonce\n\nfunc init() {\n\tvar n [signencrypt.NonceSize]byte\n\tcopy(n[:], \"kbchatattachment\")\n\tnonce = &n\n}\n\ntype SignEncrypter struct {\n\tencKey    signencrypt.SecretboxKey\n\tsignKey   signencrypt.SignKey\n\tverifyKey signencrypt.VerifyKey\n}\n\nfunc NewSignEncrypter() *SignEncrypter {\n\treturn &SignEncrypter{}\n}\n\nfunc (s *SignEncrypter) EncryptedLen(size int) int {\n\treturn signencrypt.GetSealedSize(size)\n}\n\nfunc (s *SignEncrypter) Encrypt(r io.Reader) (io.Reader, error) {\n\tif err := s.makeKeys(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn signencrypt.NewEncodingReader(s.encKey, s.signKey, nonce, r), nil\n}\n\nfunc (s *SignEncrypter) EncryptKey() []byte {\n\treturn []byte((*s.encKey)[:])\n}\n\nfunc (s *SignEncrypter) VerifyKey() []byte {\n\treturn []byte((*s.verifyKey)[:])\n}\n\nfunc (s *SignEncrypter) makeKeys() error {\n\tvar encKey [signencrypt.SecretboxKeySize]byte\n\tn, err := rand.Read(encKey[:])\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n != signencrypt.SecretboxKeySize {\n\t\treturn errors.New(\"failed to rand.Read the correct number of bytes\")\n\t}\n\n\tsign, err := libkb.GenerateNaclSigningKeyPair()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar signKey [ed25519.PrivateKeySize]byte\n\tcopy(signKey[:], (*sign.Private)[:])\n\tvar verifyKey [ed25519.PublicKeySize]byte\n\tcopy(verifyKey[:], sign.Public[:])\n\n\ts.encKey = &encKey\n\ts.signKey = &signKey\n\ts.verifyKey = &verifyKey\n\n\treturn nil\n}\n\ntype SignDecrypter struct{}\n\nfunc NewSignDecrypter() *SignDecrypter {\n\treturn &SignDecrypter{}\n}\n\nfunc (s *SignDecrypter) Decrypt(r io.Reader, encKey, verifyKey []byte) io.Reader {\n\tvar xencKey [signencrypt.SecretboxKeySize]byte\n\tcopy(xencKey[:], encKey)\n\tvar xverifyKey [ed25519.PublicKeySize]byte\n\tcopy(xverifyKey[:], verifyKey)\n\treturn signencrypt.NewDecodingReader(&xencKey, &xverifyKey, nonce, r)\n}\n<commit_msg>PR feedback<commit_after>package chat\n\nimport (\n\t\"crypto\/rand\"\n\t\"errors\"\n\t\"io\"\n\n\t\"github.com\/agl\/ed25519\"\n\t\"github.com\/keybase\/client\/go\/chat\/signencrypt\"\n\t\"github.com\/keybase\/client\/go\/libkb\"\n)\n\ntype Encrypter interface {\n\t\/\/ EncryptedLen returns the number of bytes that the ciphertext of\n\t\/\/ size plaintext bytes will be.\n\tEncryptedLen(size int) int\n\n\t\/\/ Encrypt takes a plaintext reader and returns a ciphertext reader.\n\t\/\/ It generates new keys every time it is called.\n\tEncrypt(plaintext io.Reader) (ciphertext io.Reader, err error)\n\n\t\/\/ EncryptKey returns the ephemeral key that was used during the\n\t\/\/ last invocation of Encrypt.\n\tEncryptKey() []byte\n\n\t\/\/ VerifyKey returns the public portion of the signing key used during\n\t\/\/ the last invocation of Encrypt.  It can be used for signature\n\t\/\/ verification.\n\tVerifyKey() []byte\n}\n\ntype Decrypter interface {\n\t\/\/ Decrypt takes a ciphertext reader, encryption and verify keys.\n\t\/\/ It returns a plaintext reader.\n\tDecrypt(ciphertext io.Reader, encKey, verifyKey []byte) (plaintext io.Reader)\n}\n\n\/\/ The ASCII bytes \"kbchatattachment\".\nvar nonce signencrypt.Nonce = &[16]byte{0x6b, 0x62, 0x63, 0x68, 0x61, 0x74, 0x61, 0x74, 0x74, 0x61, 0x63, 0x68, 0x6d, 0x65, 0x6e, 0x74}\n\ntype SignEncrypter struct {\n\tencKey    signencrypt.SecretboxKey\n\tsignKey   signencrypt.SignKey\n\tverifyKey signencrypt.VerifyKey\n}\n\nfunc NewSignEncrypter() *SignEncrypter {\n\treturn &SignEncrypter{}\n}\n\nfunc (s *SignEncrypter) EncryptedLen(size int) int {\n\treturn signencrypt.GetSealedSize(size)\n}\n\nfunc (s *SignEncrypter) Encrypt(r io.Reader) (io.Reader, error) {\n\t\/\/ It is *very* important that Encrypt calls makeKeys() to make\n\t\/\/ new keys every time it runs.  The keys it uses cannot be reused\n\t\/\/ since we are using a constant nonce.\n\tif err := s.makeKeys(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn signencrypt.NewEncodingReader(s.encKey, s.signKey, nonce, r), nil\n}\n\nfunc (s *SignEncrypter) EncryptKey() []byte {\n\treturn []byte((*s.encKey)[:])\n}\n\nfunc (s *SignEncrypter) VerifyKey() []byte {\n\treturn []byte((*s.verifyKey)[:])\n}\n\nfunc (s *SignEncrypter) makeKeys() error {\n\tvar encKey [signencrypt.SecretboxKeySize]byte\n\tn, err := rand.Read(encKey[:])\n\tif err != nil {\n\t\treturn err\n\t}\n\tif n != signencrypt.SecretboxKeySize {\n\t\treturn errors.New(\"failed to rand.Read the correct number of bytes\")\n\t}\n\n\tsign, err := libkb.GenerateNaclSigningKeyPair()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar signKey [ed25519.PrivateKeySize]byte\n\tcopy(signKey[:], (*sign.Private)[:])\n\tvar verifyKey [ed25519.PublicKeySize]byte\n\tcopy(verifyKey[:], sign.Public[:])\n\n\ts.encKey = &encKey\n\ts.signKey = &signKey\n\ts.verifyKey = &verifyKey\n\n\treturn nil\n}\n\ntype SignDecrypter struct{}\n\nfunc NewSignDecrypter() *SignDecrypter {\n\treturn &SignDecrypter{}\n}\n\nfunc (s *SignDecrypter) Decrypt(r io.Reader, encKey, verifyKey []byte) io.Reader {\n\tvar xencKey [signencrypt.SecretboxKeySize]byte\n\tcopy(xencKey[:], encKey)\n\tvar xverifyKey [ed25519.PublicKeySize]byte\n\tcopy(xverifyKey[:], verifyKey)\n\treturn signencrypt.NewDecodingReader(&xencKey, &xverifyKey, nonce, r)\n}\n<|endoftext|>"}
{"text":"<commit_before>package systests\n\nimport (\n\t\"context\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"testing\"\n\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/keybase\/client\/go\/engine\"\n\t\"github.com\/keybase\/client\/go\/kbtest\"\n\t\"github.com\/keybase\/client\/go\/libkb\"\n\tkeybase1 \"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc TestProofSuggestions(t *testing.T) {\n\tt.Skip()\n\ttt := newTeamTester(t)\n\tdefer tt.cleanup()\n\n\talice := tt.addUser(\"abc\")\n\n\tres, err := alice.userClient.ProofSuggestions(context.Background(), 0)\n\trequire.NoError(t, err)\n\tt.Logf(\"suggestions: %v\", spew.Sdump(res))\n\texpected := keybase1.ProofSuggestionsRes{\n\t\tShowMore: true,\n\t\tSuggestions: []keybase1.ProofSuggestion{{\n\t\t\tKey:           \"twitter\",\n\t\t\tProfileText:   \"Prove your Twitter\",\n\t\t\tPickerText:    \"Twitter\",\n\t\t\tPickerSubtext: \"twitter.com\",\n\t\t}, {\n\t\t\tKey:           \"github\",\n\t\t\tProfileText:   \"Prove your GitHub\",\n\t\t\tPickerText:    \"GitHub\",\n\t\t\tPickerSubtext: \"github.com\",\n\t\t}, {\n\t\t\tKey:           \"reddit\",\n\t\t\tProfileText:   \"Prove your Reddit\",\n\t\t\tPickerText:    \"Reddit\",\n\t\t\tPickerSubtext: \"reddit.com\",\n\t\t}, {\n\t\t\tKey:           \"hackernews\",\n\t\t\tProfileText:   \"Prove your Hacker News\",\n\t\t\tPickerText:    \"Hacker News\",\n\t\t\tPickerSubtext: \"news.ycombinator.com\",\n\t\t}, {\n\t\t\tKey:           \"rooter\",\n\t\t\tProfileText:   \"Prove your Rooter\",\n\t\t\tPickerText:    \"Rooter\",\n\t\t\tPickerSubtext: \"\",\n\t\t}, {\n\t\t\tKey:           \"mastodon.social\",\n\t\t\tProfileText:   \"Prove your Local Mastodon Social\",\n\t\t\tPickerText:    \"Local Mastodon Social\",\n\t\t\tPickerSubtext: \"mastodon.social\",\n\t\t}, {\n\t\t\tKey:           \"gubble.social\",\n\t\t\tProfileText:   \"Prove your Gubble.social\",\n\t\t\tPickerText:    \"Gubble.social\",\n\t\t\tPickerSubtext: \"Gubble instance\",\n\t\t}, {\n\t\t\tKey:           \"web\",\n\t\t\tProfileText:   \"Prove your website\",\n\t\t\tPickerText:    \"Your own website\",\n\t\t\tPickerSubtext: \"\",\n\t\t}, {\n\t\t\tKey:           \"pgp\",\n\t\t\tProfileText:   \"Add a PGP key\",\n\t\t\tPickerText:    \"PGP key\",\n\t\t\tPickerSubtext: \"\",\n\t\t}, {\n\t\t\tKey:           \"btc\",\n\t\t\tProfileText:   \"Set a Bitcoin address\",\n\t\t\tPickerText:    \"Bitcoin address\",\n\t\t\tPickerSubtext: \"\",\n\t\t}, {\n\t\t\tKey:           \"zcash\",\n\t\t\tProfileText:   \"Set a Zcash address\",\n\t\t\tPickerText:    \"Zcash address\",\n\t\t\tPickerSubtext: \"\",\n\t\t}, {\n\t\t\tKey:           \"gubble.cloud\",\n\t\t\tBelowFold:     true,\n\t\t\tProfileText:   \"Prove your Gubble.cloud\",\n\t\t\tPickerText:    \"Gubble.cloud\",\n\t\t\tPickerSubtext: \"Gubble instance\",\n\t\t}, {\n\t\t\tKey:           \"theqrl.org\",\n\t\t\tBelowFold:     true,\n\t\t\tProfileText:   \"Prove your theqrl.org\",\n\t\t\tPickerText:    \"theqrl.org\",\n\t\t\tPickerSubtext: \"theqrl.org\",\n\t\t}}}\n\trequire.Equal(t, expected.ShowMore, res.ShowMore)\n\trequire.True(t, len(res.Suggestions) >= len(expected.Suggestions), \"should be at least as many results as expected\")\n\tfor _, b := range res.Suggestions {\n\t\tif b.Key == \"theqrl.org\" {\n\t\t\t\/\/ Skip checking for logos for this one.\n\t\t\tcontinue\n\t\t}\n\t\trequire.Len(t, b.ProfileIcon, 2)\n\t\tfor _, icon := range b.ProfileIcon {\n\t\t\tcheckIcon(t, icon)\n\t\t}\n\t\tfor _, icon := range b.PickerIcon {\n\t\t\tcheckIcon(t, icon)\n\t\t}\n\n\t}\n\tvar found int\n\tfor i, b := range res.Suggestions {\n\t\tif found >= len(expected.Suggestions) {\n\t\t\tt.Logf(\"done\")\n\t\t\tbreak\n\t\t}\n\t\tt.Logf(\"row %v %v\", i, b.Key)\n\t\ta := expected.Suggestions[found]\n\t\tif a.Key != b.Key {\n\t\t\tt.Logf(\"skipping %v (mismatch)\", a.Key)\n\t\t\tcontinue\n\t\t}\n\t\tfound++\n\t\trequire.Equal(t, a.Key, b.Key)\n\t\trequire.Equal(t, a.BelowFold, b.BelowFold)\n\t\trequire.Equal(t, a.ProfileText, b.ProfileText)\n\t\trequire.Equal(t, a.PickerText, b.PickerText)\n\t\trequire.Equal(t, a.PickerSubtext, b.PickerSubtext)\n\n\t}\n\trequire.Len(t, expected.Suggestions, found)\n}\n\nfunc checkIcon(t testing.TB, icon keybase1.SizedImage) {\n\tif icon.Width < 2 {\n\t\tt.Fatalf(\"unreasonable icon size\")\n\t}\n\tif kbtest.SkipIconRemoteTest() {\n\t\tt.Logf(\"Skipping icon remote test\")\n\t\trequire.True(t, len(icon.Path) > 8)\n\t} else {\n\t\tresp, err := http.Get(icon.Path)\n\t\trequire.Equal(t, 200, resp.StatusCode, \"icon file should be reachable\")\n\t\trequire.NoError(t, err)\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\trequire.NoError(t, err)\n\t\tif len(body) < 150 {\n\t\t\tt.Fatalf(\"unreasonable icon payload size\")\n\t\t}\n\t}\n}\n\nfunc TestProofSuggestionsOmitProven(t *testing.T) {\n\ttt := newTeamTester(t)\n\tdefer tt.cleanup()\n\talice := tt.addUser(\"abc\")\n\n\tassertOmitted := func(service string) {\n\t\tres, err := alice.userClient.ProofSuggestions(context.Background(), 0)\n\t\trequire.NoError(t, err)\n\t\tfor _, suggestion := range res.Suggestions {\n\t\t\trequire.NotEqual(t, service, suggestion.Key)\n\t\t}\n\t}\n\n\talice.proveRooter()\n\tt.Logf(\"alice proved rooter, so rooter is no longer suggested\")\n\tassertOmitted(\"rooter\")\n\n\teng := engine.NewCryptocurrencyEngine(alice.MetaContext().G(), keybase1.RegisterAddressArg{\n\t\tAddress: \"zcCk6rKzynC4tT1Rmg325A5Xw81Ck3S6nD6mtPWCXaMtyFczkyU4kYjEhrcz2QKfF5T2siWGyJNxWo43XWT3qk5YpPhFGj2\",\n\t})\n\terr := engine.RunEngine2(alice.MetaContext().WithUIs(libkb.UIs{\n\t\tLogUI:    alice.MetaContext().G().Log,\n\t\tSecretUI: alice.newSecretUI(),\n\t}), eng)\n\trequire.NoError(t, err)\n\tt.Logf(\"alice added a zcash address, so zcash is no longer suggested\")\n\tassertOmitted(\"zcash\")\n}\n<commit_msg>re-enable TestProofSuggestions<commit_after>package systests\n\nimport (\n\t\"context\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"testing\"\n\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/keybase\/client\/go\/engine\"\n\t\"github.com\/keybase\/client\/go\/kbtest\"\n\t\"github.com\/keybase\/client\/go\/libkb\"\n\tkeybase1 \"github.com\/keybase\/client\/go\/protocol\/keybase1\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc TestProofSuggestions(t *testing.T) {\n\ttt := newTeamTester(t)\n\tdefer tt.cleanup()\n\n\talice := tt.addUser(\"abc\")\n\n\tres, err := alice.userClient.ProofSuggestions(context.Background(), 0)\n\trequire.NoError(t, err)\n\tt.Logf(\"suggestions: %v\", spew.Sdump(res))\n\texpected := keybase1.ProofSuggestionsRes{\n\t\tShowMore: true,\n\t\tSuggestions: []keybase1.ProofSuggestion{{\n\t\t\tKey:           \"twitter\",\n\t\t\tProfileText:   \"Prove your Twitter\",\n\t\t\tPickerText:    \"Twitter\",\n\t\t\tPickerSubtext: \"twitter.com\",\n\t\t}, {\n\t\t\tKey:           \"github\",\n\t\t\tProfileText:   \"Prove your GitHub\",\n\t\t\tPickerText:    \"GitHub\",\n\t\t\tPickerSubtext: \"github.com\",\n\t\t}, {\n\t\t\tKey:           \"reddit\",\n\t\t\tProfileText:   \"Prove your Reddit\",\n\t\t\tPickerText:    \"Reddit\",\n\t\t\tPickerSubtext: \"reddit.com\",\n\t\t}, {\n\t\t\tKey:           \"hackernews\",\n\t\t\tProfileText:   \"Prove your Hacker News\",\n\t\t\tPickerText:    \"Hacker News\",\n\t\t\tPickerSubtext: \"news.ycombinator.com\",\n\t\t}, {\n\t\t\tKey:           \"rooter\",\n\t\t\tProfileText:   \"Prove your Rooter\",\n\t\t\tPickerText:    \"Rooter\",\n\t\t\tPickerSubtext: \"\",\n\t\t}, {\n\t\t\tKey:           \"gubble.social\",\n\t\t\tProfileText:   \"Prove your Gubble.social\",\n\t\t\tPickerText:    \"Gubble.social\",\n\t\t\tPickerSubtext: \"Gubble instance\",\n\t\t}, {\n\t\t\tKey:           \"web\",\n\t\t\tProfileText:   \"Prove your website\",\n\t\t\tPickerText:    \"Your own website\",\n\t\t\tPickerSubtext: \"\",\n\t\t}, {\n\t\t\tKey:           \"pgp\",\n\t\t\tProfileText:   \"Add a PGP key\",\n\t\t\tPickerText:    \"PGP key\",\n\t\t\tPickerSubtext: \"\",\n\t\t}, {\n\t\t\tKey:           \"btc\",\n\t\t\tProfileText:   \"Set a Bitcoin address\",\n\t\t\tPickerText:    \"Bitcoin address\",\n\t\t\tPickerSubtext: \"\",\n\t\t}, {\n\t\t\tKey:           \"zcash\",\n\t\t\tProfileText:   \"Set a Zcash address\",\n\t\t\tPickerText:    \"Zcash address\",\n\t\t\tPickerSubtext: \"\",\n\t\t}, {\n\t\t\tKey:           \"gubble.cloud\",\n\t\t\tBelowFold:     true,\n\t\t\tProfileText:   \"Prove your Gubble.cloud\",\n\t\t\tPickerText:    \"Gubble.cloud\",\n\t\t\tPickerSubtext: \"Gubble instance\",\n\t\t}, {\n\t\t\tKey:           \"theqrl.org\",\n\t\t\tBelowFold:     true,\n\t\t\tProfileText:   \"Prove your theqrl.org\",\n\t\t\tPickerText:    \"theqrl.org\",\n\t\t\tPickerSubtext: \"theqrl.org\",\n\t\t}}}\n\trequire.Equal(t, expected.ShowMore, res.ShowMore)\n\trequire.True(t, len(res.Suggestions) >= len(expected.Suggestions), \"should be at least as many results as expected\")\n\tfor _, b := range res.Suggestions {\n\t\tif b.Key == \"theqrl.org\" {\n\t\t\t\/\/ Skip checking for logos for this one.\n\t\t\tcontinue\n\t\t}\n\t\trequire.Len(t, b.ProfileIcon, 2)\n\t\tfor _, icon := range b.ProfileIcon {\n\t\t\tcheckIcon(t, icon)\n\t\t}\n\t\tfor _, icon := range b.PickerIcon {\n\t\t\tcheckIcon(t, icon)\n\t\t}\n\n\t}\n\tvar found int\n\tfor i, b := range res.Suggestions {\n\t\tif found >= len(expected.Suggestions) {\n\t\t\tt.Logf(\"done\")\n\t\t\tbreak\n\t\t}\n\t\tt.Logf(\"row %v %v\", i, b.Key)\n\t\ta := expected.Suggestions[found]\n\t\tif a.Key != b.Key {\n\t\t\tt.Logf(\"skipping %v (mismatch)\", a.Key)\n\t\t\tcontinue\n\t\t}\n\t\tfound++\n\t\trequire.Equal(t, a.Key, b.Key)\n\t\trequire.Equal(t, a.BelowFold, b.BelowFold)\n\t\trequire.Equal(t, a.ProfileText, b.ProfileText)\n\t\trequire.Equal(t, a.PickerText, b.PickerText)\n\t\trequire.Equal(t, a.PickerSubtext, b.PickerSubtext)\n\n\t}\n\trequire.Len(t, expected.Suggestions, found)\n}\n\nfunc checkIcon(t testing.TB, icon keybase1.SizedImage) {\n\tif icon.Width < 2 {\n\t\tt.Fatalf(\"unreasonable icon size\")\n\t}\n\tif kbtest.SkipIconRemoteTest() {\n\t\tt.Logf(\"Skipping icon remote test\")\n\t\trequire.True(t, len(icon.Path) > 8)\n\t} else {\n\t\tresp, err := http.Get(icon.Path)\n\t\trequire.Equal(t, 200, resp.StatusCode, \"icon file should be reachable\")\n\t\trequire.NoError(t, err)\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\trequire.NoError(t, err)\n\t\tif len(body) < 150 {\n\t\t\tt.Fatalf(\"unreasonable icon payload size\")\n\t\t}\n\t}\n}\n\nfunc TestProofSuggestionsOmitProven(t *testing.T) {\n\ttt := newTeamTester(t)\n\tdefer tt.cleanup()\n\talice := tt.addUser(\"abc\")\n\n\tassertOmitted := func(service string) {\n\t\tres, err := alice.userClient.ProofSuggestions(context.Background(), 0)\n\t\trequire.NoError(t, err)\n\t\tfor _, suggestion := range res.Suggestions {\n\t\t\trequire.NotEqual(t, service, suggestion.Key)\n\t\t}\n\t}\n\n\talice.proveRooter()\n\tt.Logf(\"alice proved rooter, so rooter is no longer suggested\")\n\tassertOmitted(\"rooter\")\n\n\teng := engine.NewCryptocurrencyEngine(alice.MetaContext().G(), keybase1.RegisterAddressArg{\n\t\tAddress: \"zcCk6rKzynC4tT1Rmg325A5Xw81Ck3S6nD6mtPWCXaMtyFczkyU4kYjEhrcz2QKfF5T2siWGyJNxWo43XWT3qk5YpPhFGj2\",\n\t})\n\terr := engine.RunEngine2(alice.MetaContext().WithUIs(libkb.UIs{\n\t\tLogUI:    alice.MetaContext().G().Log,\n\t\tSecretUI: alice.newSecretUI(),\n\t}), eng)\n\trequire.NoError(t, err)\n\tt.Logf(\"alice added a zcash address, so zcash is no longer suggested\")\n\tassertOmitted(\"zcash\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package callerid\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\tqrpb \"github.com\/youtube\/vitess\/go\/vt\/proto\/query\"\n\tvtpb \"github.com\/youtube\/vitess\/go\/vt\/proto\/vtrpc\"\n)\n\nconst (\n\t\/\/ FakePrincipal is the principal of testing EffectiveCallerID\n\tFakePrincipal = \"TestPrincipal\"\n\t\/\/ FakeComponent is the component of testing EffectiveCallerID\n\tFakeComponent = \"TestComponent\"\n\t\/\/ FakeSubcomponent is the subcomponent of testing EffectiveCallerID\n\tFakeSubcomponent = \"TestSubcomponent\"\n\t\/\/ FakeUsername is the username of testing ImmediateCallerID\n\tFakeUsername = \"TestUsername\"\n)\n\n\/\/ Tests performs the necessary testsuite for CallerID operations\nfunc Tests(t *testing.T, im *qrpb.VTGateCallerID, ef *vtpb.CallerID) {\n\tctx := context.TODO()\n\tctxim := ImmediateCallerIDFromContext(ctx)\n\t\/\/ For Contexts without ImmediateCallerID, ImmediateCallerIDFromContext should fail\n\tif ctxim != nil {\n\t\tt.Errorf(\"Expect nil from ImmediateCallerIDFromContext, but got %v\", ctxim)\n\t}\n\t\/\/ For Contexts without EffectiveCallerID, EffectiveCallerIDFromContext should fail\n\tctxef := EffectiveCallerIDFromContext(ctx)\n\tif ctxef != nil {\n\t\tt.Errorf(\"Expect nil from EffectiveCallerIDFromContext, but got %v\", ctxef)\n\t}\n\n\tctx = NewContext(ctx, nil, nil)\n\tctxim = ImmediateCallerIDFromContext(ctx)\n\t\/\/ For Contexts with nil ImmediateCallerID, ImmediateCallerIDFromContext should fail\n\tif ctxim != nil {\n\t\tt.Errorf(\"Expect nil from ImmediateCallerIDFromContext, but got %v\", ctxim)\n\t}\n\t\/\/ For Contexts with nil EffectiveCallerID, EffectiveCallerIDFromContext should fail\n\tctxef = EffectiveCallerIDFromContext(ctx)\n\tif ctxef != nil {\n\t\tt.Errorf(\"Expect nil from EffectiveCallerIDFromContext, but got %v\", ctxef)\n\t}\n\n\t\/\/ Test GetXxx on nil receivers, should get all empty strings\n\tif u := GetUsername(ctxim); u != \"\" {\n\t\tt.Errorf(\"Expect empty string from (nil).GetUsername(), but got %v\", u)\n\t}\n\tif p := GetPrincipal(ctxef); p != \"\" {\n\t\tt.Errorf(\"Expect empty string from (nil).GetPrincipal(), but got %v\", p)\n\t}\n\tif c := GetComponent(ctxef); c != \"\" {\n\t\tt.Errorf(\"Expect empty string from (nil).GetComponent(), but got %v\", c)\n\t}\n\tif s := GetSubcomponent(ctxef); s != \"\" {\n\t\tt.Errorf(\"Expect empty string from (nil).GetSubcomponent(), but got %v\", s)\n\t}\n\n\tctx = NewContext(ctx, ef, im)\n\tctxim = ImmediateCallerIDFromContext(ctx)\n\t\/\/ retrieved ImmediateCallerID should be equal to the one we put into Context\n\tif !reflect.DeepEqual(ctxim, im) {\n\t\tt.Errorf(\"Expect %v from ImmediateCallerIDFromContext, but got %v\", im, ctxim)\n\t}\n\tif u := GetUsername(im); u != FakeUsername {\n\t\tt.Errorf(\"Expect %v from im.Username(), but got %v\", FakeUsername, u)\n\t}\n\n\tctxef = EffectiveCallerIDFromContext(ctx)\n\t\/\/ retrieved EffectiveCallerID should be equal to the one we put into Context\n\tif !reflect.DeepEqual(ctxef, ef) {\n\t\tt.Errorf(\"Expect %v from EffectiveCallerIDFromContext, but got %v\", ef, ctxef)\n\t}\n\tif p := GetPrincipal(ef); p != FakePrincipal {\n\t\tt.Errorf(\"Expect %v from ef.Principal(), but got %v\", FakePrincipal, p)\n\t}\n\tif c := GetComponent(ef); c != FakeComponent {\n\t\tt.Errorf(\"Expect %v from ef.Component(), but got %v\", FakeComponent, c)\n\t}\n\tif s := GetSubcomponent(ef); s != FakeSubcomponent {\n\t\tt.Errorf(\"Expect %v from ef.Subcomponent(), but got %v\", FakeSubcomponent, s)\n\t}\n}\n<commit_msg>Fix test printings<commit_after>package callerid\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\tqrpb \"github.com\/youtube\/vitess\/go\/vt\/proto\/query\"\n\tvtpb \"github.com\/youtube\/vitess\/go\/vt\/proto\/vtrpc\"\n)\n\nconst (\n\t\/\/ FakePrincipal is the principal of testing EffectiveCallerID\n\tFakePrincipal = \"TestPrincipal\"\n\t\/\/ FakeComponent is the component of testing EffectiveCallerID\n\tFakeComponent = \"TestComponent\"\n\t\/\/ FakeSubcomponent is the subcomponent of testing EffectiveCallerID\n\tFakeSubcomponent = \"TestSubcomponent\"\n\t\/\/ FakeUsername is the username of testing ImmediateCallerID\n\tFakeUsername = \"TestUsername\"\n)\n\n\/\/ Tests performs the necessary testsuite for CallerID operations\nfunc Tests(t *testing.T, im *qrpb.VTGateCallerID, ef *vtpb.CallerID) {\n\tctx := context.TODO()\n\tctxim := ImmediateCallerIDFromContext(ctx)\n\t\/\/ For Contexts without ImmediateCallerID, ImmediateCallerIDFromContext should fail\n\tif ctxim != nil {\n\t\tt.Errorf(\"Expect nil from ImmediateCallerIDFromContext, but got %v\", ctxim)\n\t}\n\t\/\/ For Contexts without EffectiveCallerID, EffectiveCallerIDFromContext should fail\n\tctxef := EffectiveCallerIDFromContext(ctx)\n\tif ctxef != nil {\n\t\tt.Errorf(\"Expect nil from EffectiveCallerIDFromContext, but got %v\", ctxef)\n\t}\n\n\tctx = NewContext(ctx, nil, nil)\n\tctxim = ImmediateCallerIDFromContext(ctx)\n\t\/\/ For Contexts with nil ImmediateCallerID, ImmediateCallerIDFromContext should fail\n\tif ctxim != nil {\n\t\tt.Errorf(\"Expect nil from ImmediateCallerIDFromContext, but got %v\", ctxim)\n\t}\n\t\/\/ For Contexts with nil EffectiveCallerID, EffectiveCallerIDFromContext should fail\n\tctxef = EffectiveCallerIDFromContext(ctx)\n\tif ctxef != nil {\n\t\tt.Errorf(\"Expect nil from EffectiveCallerIDFromContext, but got %v\", ctxef)\n\t}\n\n\t\/\/ Test GetXxx on nil receivers, should get all empty strings\n\tif u := GetUsername(ctxim); u != \"\" {\n\t\tt.Errorf(\"Expect empty string from GetUsername(nil), but got %v\", u)\n\t}\n\tif p := GetPrincipal(ctxef); p != \"\" {\n\t\tt.Errorf(\"Expect empty string from GetPrincipal(nil), but got %v\", p)\n\t}\n\tif c := GetComponent(ctxef); c != \"\" {\n\t\tt.Errorf(\"Expect empty string from GetComponent(nil), but got %v\", c)\n\t}\n\tif s := GetSubcomponent(ctxef); s != \"\" {\n\t\tt.Errorf(\"Expect empty string from GetSubcomponent(nil), but got %v\", s)\n\t}\n\n\tctx = NewContext(ctx, ef, im)\n\tctxim = ImmediateCallerIDFromContext(ctx)\n\t\/\/ retrieved ImmediateCallerID should be equal to the one we put into Context\n\tif !reflect.DeepEqual(ctxim, im) {\n\t\tt.Errorf(\"Expect %v from ImmediateCallerIDFromContext, but got %v\", im, ctxim)\n\t}\n\tif u := GetUsername(im); u != FakeUsername {\n\t\tt.Errorf(\"Expect %v from GetUsername(im), but got %v\", FakeUsername, u)\n\t}\n\n\tctxef = EffectiveCallerIDFromContext(ctx)\n\t\/\/ retrieved EffectiveCallerID should be equal to the one we put into Context\n\tif !reflect.DeepEqual(ctxef, ef) {\n\t\tt.Errorf(\"Expect %v from EffectiveCallerIDFromContext, but got %v\", ef, ctxef)\n\t}\n\tif p := GetPrincipal(ef); p != FakePrincipal {\n\t\tt.Errorf(\"Expect %v from GetPrincipal(ef), but got %v\", FakePrincipal, p)\n\t}\n\tif c := GetComponent(ef); c != FakeComponent {\n\t\tt.Errorf(\"Expect %v from GetComponent(ef), but got %v\", FakeComponent, c)\n\t}\n\tif s := GetSubcomponent(ef); s != FakeSubcomponent {\n\t\tt.Errorf(\"Expect %v from GetSubcomponent(ef), but got %v\", FakeSubcomponent, s)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package goltime\n\nimport (\n  \"strconv\"\n  \"time\"\n  \"net\/http\"\n)\n\n\ntype Timestamp struct{\n  Year, Month, Day, Hour, Min, Sec int\n}\n\n\nfunc CreateTimestamp(time_point []string) Timestamp{\n  year, _   := strconv.Atoi(time_point[0])\n  month, _  := strconv.Atoi(time_point[1])\n  day, _    := strconv.Atoi(time_point[2])\n  hour, _   := strconv.Atoi(time_point[3])\n  min, _    := strconv.Atoi(time_point[4])\n  sec, _    := strconv.Atoi(time_point[5])\n\n  return Timestamp{\n    Year: year,\n    Month: month,\n    Day: day,\n    Hour: hour,\n    Min: min,\n    Sec: sec,\n  }\n}\n\n\nfunc TimestampFromHTTPRequest(req *http.Request) Timestamp{\n  return CreateTimestamp([]string {\n    req.Form[\"year\"][0], req.Form[\"month\"][0], req.Form[\"day\"][0],\n    req.Form[\"hour\"][0], req.Form[\"min\"][0], req.Form[\"sec\"][0],\n  })\n}\n\n\nfunc (timestamp *Timestamp) Time() time.Time{\n  return time.Date(timestamp.Year, time.Month(timestamp.Month), timestamp.Day,\n                   timestamp.Hour, timestamp.Min, timestamp.Sec, 0, time.UTC)\n}\n<commit_msg>goltime go-fmt-ized<commit_after>package goltime\n\nimport (\n\t\"net\/http\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Timestamp struct {\n\tYear, Month, Day, Hour, Min, Sec int\n}\n\nfunc CreateTimestamp(time_point []string) Timestamp {\n\tyear, _ := strconv.Atoi(time_point[0])\n\tmonth, _ := strconv.Atoi(time_point[1])\n\tday, _ := strconv.Atoi(time_point[2])\n\thour, _ := strconv.Atoi(time_point[3])\n\tmin, _ := strconv.Atoi(time_point[4])\n\tsec, _ := strconv.Atoi(time_point[5])\n\n\treturn Timestamp{\n\t\tYear:  year,\n\t\tMonth: month,\n\t\tDay:   day,\n\t\tHour:  hour,\n\t\tMin:   min,\n\t\tSec:   sec,\n\t}\n}\n\nfunc TimestampFromHTTPRequest(req *http.Request) Timestamp {\n\treturn CreateTimestamp([]string{\n\t\treq.Form[\"year\"][0], req.Form[\"month\"][0], req.Form[\"day\"][0],\n\t\treq.Form[\"hour\"][0], req.Form[\"min\"][0], req.Form[\"sec\"][0],\n\t})\n}\n\nfunc (timestamp *Timestamp) Time() time.Time {\n\treturn time.Date(timestamp.Year, time.Month(timestamp.Month), timestamp.Day,\n\t\ttimestamp.Hour, timestamp.Min, timestamp.Sec, 0, time.UTC)\n}\n<|endoftext|>"}
{"text":"<commit_before>package mahjong\n\nimport (\n\t\"math\/rand\"\n\t\"time\"\n)\n\ntype Kaze rune\n\nconst (\n\tTongPu Kaze = '東'\n\tNangPu      = '南'\n\tShaPu       = '西'\n\tPeiPu       = '北'\n)\n\ntype Order Kaze\n\n\/\/ A Command specifies an action a player can take.\ntype Command int\n\nconst (\n\tTsumo Command = iota\n\tTsumoHoura\n\tRonHoura\n\tChi\n\tPong\n\tAnngKan\n\tMingKan\n\tTahai\n\tTahaiReach\n)\n\n\/\/ An Action specifies who does what.\ntype Action struct {\n\tPlayer  Player\n\tCommand Command\n}\n\n\/\/ A Game specifies public and private information about the current game (Hanchang),\n\/\/ such as players, pais in the pile, discarded piles (Ho) information.\n\/\/ They are changed when a player does an action.\ntype Game struct {\n\tstate State       \/\/ Public information about the current game.\n\tpile  map[Pai]int \/\/ Pais in the pile.\n\tr     *rand.Rand\n}\n\nfunc (g *Game) Init() error {\n\t\/\/ Create a Random\n\tg.r = rand.New(rand.NewSource(time.Now().UnixNano()))\n\t\/\/ Prepare pile\n\tnumPais := 0\n\tfor _, s := range []Suite{Manzu, Sozu, Pinzu} {\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tg.pile[Pai{s, Rank(i)}] = 4\n\t\t\tnumPais += 4\n\t\t}\n\t}\n\tfor _, r := range []Rank{Tong, Nang, Sha, Pei, Haku, Fa, Chung} {\n\t\tg.pile[Pai{Zizu, r}] = 4\n\t\tnumPais += 4\n\t}\n\t\/\/ Create default players\n\tplayers := []Player{}\n\tkz := []Kaze{TongPu, NangPu, ShaPu, PeiPu}\n\tfor i, n := range []string{\"Alice\", \"Bob\", \"Carol\", \"Ted\"} {\n\t\thand, err := drawPais(g.pile, 13, g.r)\n\t\tif err != nil {\n\t\t\t\/\/ FIXME\n\t\t\tpanic(err)\n\t\t}\n\t\tplayers[i] = Player{\n\t\t\tPlayerInfo: PlayerInfo{\n\t\t\t\tId:    i,\n\t\t\t\tName:  n,\n\t\t\t\tKaze:  kz[i],\n\t\t\t\tScore: 25000,\n\t\t\t\tOrder: Order(kz[i]),\n\t\t\t\tHo:    []Sutehai{},\n\t\t\t\tFuro:  []Mentsu{},\n\t\t\t},\n\t\t\tTehai: hand,\n\t\t}\n\t}\n\n\t\/\/ Reset game status\n\td, err := g.draw()\n\tif err != nil {\n\t\t\/\/ FIXME\n\t\tpanic(err)\n\t}\n\tg.state = State{\n\t\tJunnme:  1,\n\t\tNumPais: numPais,\n\t\tHonnba:  0,\n\t\tKyotaku: 0,\n\t\tDora:    []Pai{d},\n\t}\n\n\treturn nil\n}\n\n\/\/ Randomly pick-up a pai from the pile.\nfunc (g *Game) draw() (Pai, error) {\n\treturn drawPai(g.pile, g.r)\n}\n\n\/\/ Return available commands for the given player.\nfunc (g Game) Commands(p Player) []Command {\n\treturn []Command{}\n}\n\n\/\/ Play the specified action on the game. If the action cannot be executed, an error returns.\nfunc (g *Game) Play(a Action) error {\n\treturn nil\n}\n\nfunc (g Game) Status() State {\n\treturn State{}\n}\n\n\/\/ A State specifies public information of the game,\n\/\/ such as the number of remaining pais in the pile, who discarded which pais (Ho).\ntype State struct {\n\tJunnme  int\n\tNumPais int          \/\/ The number of remaining tsumoable pais.\n\tHonnba  int          \/\/ How many times the renchan repeats.\n\tKyotaku int          \/\/ Deposit score.\n\tPlayers []PlayerInfo \/\/ Public information about players.\n\tDora    []Pai\n}\n\n\/\/ A Player specifies private information of a player.\ntype Player struct {\n\tPlayerInfo\n\tTehai []Pai\n}\n\n\/\/ A PlayerInfo specifies public information of a player.\ntype PlayerInfo struct {\n\tId    int\n\tName  string\n\tKaze  Kaze\n\tScore int\n\tOrder Order\n\tHo    []Sutehai\n\tFuro  []Mentsu\n}\n<commit_msg>Mark FIXME tag.<commit_after>package mahjong\n\nimport (\n\t\"math\/rand\"\n\t\"time\"\n)\n\ntype Kaze rune\n\nconst (\n\tTongPu Kaze = '東'\n\tNangPu      = '南'\n\tShaPu       = '西'\n\tPeiPu       = '北'\n)\n\ntype Order Kaze\n\n\/\/ A Command specifies an action a player can take.\ntype Command int\n\nconst (\n\tTsumo Command = iota\n\tTsumoHoura\n\tRonHoura\n\tChi\n\tPong\n\tAnngKan\n\tMingKan\n\tTahai\n\tTahaiReach\n)\n\n\/\/ An Action specifies who does what.\ntype Action struct {\n\tPlayer  Player\n\tCommand Command\n}\n\n\/\/ A Game specifies public and private information about the current game (Hanchang),\n\/\/ such as players, pais in the pile, discarded piles (Ho) information.\n\/\/ They are changed when a player does an action.\ntype Game struct {\n\tstate State       \/\/ Public information about the current game.\n\tpile  map[Pai]int \/\/ Pais in the pile.\n\tr     *rand.Rand\n}\n\nfunc (g *Game) Init() error {\n\t\/\/ Create a Random\n\tg.r = rand.New(rand.NewSource(time.Now().UnixNano()))\n\t\/\/ Prepare pile\n\tnumPais := 0\n\tfor _, s := range []Suite{Manzu, Sozu, Pinzu} {\n\t\tfor i := 0; i < 10; i++ {\n\t\t\tg.pile[Pai{s, Rank(i)}] = 4\n\t\t\tnumPais += 4\n\t\t}\n\t}\n\tfor _, r := range []Rank{Tong, Nang, Sha, Pei, Haku, Fa, Chung} {\n\t\tg.pile[Pai{Zizu, r}] = 4\n\t\tnumPais += 4\n\t}\n\t\/\/ Create default players\n\tplayers := []Player{}\n\tkz := []Kaze{TongPu, NangPu, ShaPu, PeiPu}\n\tfor i, n := range []string{\"Alice\", \"Bob\", \"Carol\", \"Ted\"} {\n\t\thand, err := drawPais(g.pile, 13, g.r)\n\t\tif err != nil {\n\t\t\t\/\/ FIXME\n\t\t\tpanic(err)\n\t\t}\n\t\tplayers[i] = Player{\n\t\t\tPlayerInfo: PlayerInfo{\n\t\t\t\tId:    i,\n\t\t\t\tName:  n,\n\t\t\t\tKaze:  kz[i],\n\t\t\t\tScore: 25000,\n\t\t\t\tOrder: Order(kz[i]),\n\t\t\t\tHo:    []Sutehai{},\n\t\t\t\tFuro:  []Mentsu{},\n\t\t\t},\n\t\t\tTehai: hand,\n\t\t}\n\t}\n\n\t\/\/ Reset game status\n\td, err := g.draw()\n\tif err != nil {\n\t\t\/\/ FIXME\n\t\tpanic(err)\n\t}\n\tg.state = State{\n\t\tJunnme:  1,\n\t\tNumPais: numPais,\n\t\tHonnba:  0,\n\t\tKyotaku: 0,\n\t\tDora:    []Pai{d},\n\t}\n\n\treturn nil\n}\n\n\/\/ Randomly pick-up a pai from the pile.\nfunc (g *Game) draw() (Pai, error) {\n\treturn drawPai(g.pile, g.r)\n}\n\n\/\/ Return available commands for the given player.\nfunc (g Game) Commands(p Player) []Command {\n\t\/\/ FIXME\n\treturn []Command{}\n}\n\n\/\/ Play the specified action on the game. If the action cannot be executed, an error returns.\nfunc (g *Game) Play(a Action) error {\n\t\/\/ FIXME\n\treturn nil\n}\n\nfunc (g Game) Status() State {\n\t\/\/ FIXME\n\treturn State{}\n}\n\n\/\/ A State specifies public information of the game,\n\/\/ such as the number of remaining pais in the pile, who discarded which pais (Ho).\ntype State struct {\n\tJunnme  int\n\tNumPais int          \/\/ The number of remaining tsumoable pais.\n\tHonnba  int          \/\/ How many times the renchan repeats.\n\tKyotaku int          \/\/ Deposit score.\n\tPlayers []PlayerInfo \/\/ Public information about players.\n\tDora    []Pai\n}\n\n\/\/ A Player specifies private information of a player.\ntype Player struct {\n\tPlayerInfo\n\tTehai []Pai\n}\n\n\/\/ A PlayerInfo specifies public information of a player.\ntype PlayerInfo struct {\n\tId    int\n\tName  string\n\tKaze  Kaze\n\tScore int\n\tOrder Order\n\tHo    []Sutehai\n\tFuro  []Mentsu\n}\n<|endoftext|>"}
{"text":"<commit_before>package mail\n\nimport (\n\t\"mime\"\n\t\"net\/mail\"\n\t\"strings\"\n\n\t\"github.com\/emersion\/go-message\"\n)\n\n\/\/ Address represents a single mail address.\ntype Address mail.Address\n\n\/\/ String formats the address as a valid RFC 5322 address. If the address's name\n\/\/ contains non-ASCII characters the name will be rendered according to\n\/\/ RFC 2047.\nfunc (a *Address) String() string {\n\treturn ((*mail.Address)(a)).String()\n}\n\nfunc parseAddressList(s string) ([]*Address, error) {\n\tparser := mail.AddressParser{\n\t\t&mime.WordDecoder{message.CharsetReader},\n\t}\n\tlist, err := parser.ParseList(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taddrs := make([]*Address, len(list))\n\tfor i, a := range list {\n\t\taddrs[i] = (*Address)(a)\n\t}\n\treturn addrs, nil\n}\n\nfunc formatAddressList(l []*Address) string {\n\tformatted := make([]string, len(l))\n\tfor i, a := range l {\n\t\tformatted[i] = a.String()\n\t}\n\treturn strings.Join(formatted, \", \")\n}\n<commit_msg>mail: warn against using Address.String for a header field<commit_after>package mail\n\nimport (\n\t\"mime\"\n\t\"net\/mail\"\n\t\"strings\"\n\n\t\"github.com\/emersion\/go-message\"\n)\n\n\/\/ Address represents a single mail address.\ntype Address mail.Address\n\n\/\/ String formats the address as a valid RFC 5322 address. If the address's name\n\/\/ contains non-ASCII characters the name will be rendered according to\n\/\/ RFC 2047.\n\/\/\n\/\/ Don't use this function to set a message header field, instead use\n\/\/ Header.SetAddressList.\nfunc (a *Address) String() string {\n\treturn ((*mail.Address)(a)).String()\n}\n\nfunc parseAddressList(s string) ([]*Address, error) {\n\tparser := mail.AddressParser{\n\t\t&mime.WordDecoder{message.CharsetReader},\n\t}\n\tlist, err := parser.ParseList(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\taddrs := make([]*Address, len(list))\n\tfor i, a := range list {\n\t\taddrs[i] = (*Address)(a)\n\t}\n\treturn addrs, nil\n}\n\nfunc formatAddressList(l []*Address) string {\n\tformatted := make([]string, len(l))\n\tfor i, a := range l {\n\t\tformatted[i] = a.String()\n\t}\n\treturn strings.Join(formatted, \", \")\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build linux\n\npackage main\n\nimport (\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"koding\/db\/models\"\n\t\"koding\/db\/mongodb\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"koding\/kites\/provisioning\/container\"\n\t\"koding\/newkite\/kite\"\n\t\"koding\/newkite\/protocol\"\n\t\"koding\/tools\/config\"\n\t\"koding\/tools\/utils\"\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\t\"net\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Provisioning struct{}\n\nvar (\n\tport             = flag.String(\"port\", \"4005\", \"port to bind itself\")\n\tcontainerSubnet  *net.IPNet\n\tfirstContainerIP net.IP\n\tcontainers       = make(map[string]*Info)\n\tk                = &kite.Kite{}\n\tlog              = kite.GetLogger()\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tkontrolPort := strconv.Itoa(config.Current.NewKontrol.Port)\n\tkontrolHost := config.Current.NewKontrol.Host\n\tkontrolAddr := fmt.Sprintf(\"%s:%s\", kontrolHost, kontrolPort)\n\n\toptions := &protocol.Options{\n\t\tPublicIP:    \"localhost\",\n\t\tKitename:    \"provisioning\",\n\t\tVersion:     \"0.0.1\",\n\t\tPort:        *port,\n\t\tKontrolAddr: kontrolAddr,\n\t}\n\n\tmethods := map[string]string{\n\t\t\"vm.start\":     \"Start\",\n\t\t\"vm.stop\":      \"Stop\",\n\t\t\"vm.prepare\":   \"Prepare\",\n\t\t\"vm.unprepare\": \"Unprepare\",\n\t\t\"vm.exec\":      \"Exec\",\n\t}\n\n\tinitialize()\n\n\tk = kite.New(options)\n\tk.AddMethods(new(Provisioning), methods)\n\tk.Start()\n}\n\nfunc initialize() {\n\tvar err error\n\tif firstContainerIP, containerSubnet, err = net.ParseCIDR(config.Current.ContainerSubnet); err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n}\n\nfunc (p *Provisioning) Start(r *protocol.KiteDnodeRequest, result *bool) error {\n\tvm, err := getVM(r.Hostname)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not fetch vm document to start '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not start vm - 1\")\n\t}\n\n\tcontainerName := \"vm-\" + vm.Id.Hex()\n\n\tc := container.NewContainer(containerName)\n\terr = c.Start()\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not start container: '%s'. err: '%s'\", r.Username, containerName, err)\n\t\treturn errors.New(\"could not start vm - 2\")\n\t}\n\n\tlog.Info(\"[%s] started the container: '%s'\", r.Username, containerName)\n\t*result = true\n\treturn nil\n}\n\nfunc (p *Provisioning) Stop(r *protocol.KiteDnodeRequest, result *bool) error {\n\tvm, err := getVM(r.Hostname)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not fetch vm document to stop '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not stop vm - 1\")\n\t}\n\n\tcontainerName := \"vm-\" + vm.Id.Hex()\n\n\tc := container.NewContainer(containerName)\n\terr = c.Stop()\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not stop container: '%s'. err: '%s'\", r.Username, containerName, err)\n\t\treturn errors.New(\"could not stop vm - 2\")\n\t}\n\n\tlog.Info(\"[%s] stopped the container: '%s'\", r.Username, containerName)\n\n\t*result = true\n\treturn nil\n}\n\nfunc (p *Provisioning) Exec(r *protocol.KiteDnodeRequest, result *string) error {\n\tvar command string\n\n\tif r.Args.Unmarshal(&command) != nil {\n\t\treturn errors.New(\"{ [string] }\")\n\t}\n\n\tuser, err := getUser(r.Username)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not fetch user document to exec a command on '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not run command - 1\")\n\t}\n\n\tvm, err := getVM(r.Hostname)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not fetch vm document to exec a command on '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not run command - 2\")\n\t}\n\n\tcontainerName := \"vm-\" + vm.Id.Hex()\n\n\tc := container.NewContainer(containerName)\n\tc.Useruid = user.Uid\n\n\toutput, err := c.Run(command)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not exec a command on '%s'. err: '%s'\", r.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not run command - 3\")\n\t}\n\n\tinfo := GetInfo(containerName)\n\tinfo.ResetTimer()\n\tlog.Info(\"[%s] did run the command '%s' on container'%s'\\n\", r.Username, command, containerName)\n\n\t*result = string(output)\n\treturn nil\n}\n\nfunc (p *Provisioning) Unprepare(r *protocol.KiteDnodeRequest, result *bool) error {\n\tvm, err := getVM(r.Hostname)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not fetch vm document to unprepare '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not unprepare vm - 1\")\n\t}\n\n\tcontainerName := \"vm-\" + vm.Id.Hex()\n\n\tc := container.NewContainer(containerName)\n\tc.IP = vm.IP \/\/ needed for removing static route and ebtables in unprepare\n\n\tif c.IsRunning() {\n\t\terr = c.Shutdown(5)\n\t\tif err != nil {\n\t\t\tlog.Error(\"[%s] could not shutdown vm for unprepare vm: '%s'. err: '%s'\",\n\t\t\t\tr.Username, r.Hostname, err)\n\t\t\treturn errors.New(\"could not unprepare vm - 2\")\n\t\t}\n\t}\n\n\terr = c.Unprepare()\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not unprepare vm: '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not unprepare vm - 3\")\n\t}\n\n\tlog.Info(\"[%s] unprepared the container '%s'\", r.Username, containerName)\n\t*result = true\n\treturn nil\n}\n\nfunc (p *Provisioning) Prepare(r *protocol.KiteDnodeRequest, result *bool) error {\n\terr := prepare(r.Username, r.Hostname)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not prepare vm: '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not prepare vm\")\n\t}\n\n\t*result = true\n\treturn nil\n}\n\nfunc prepare(username, hostname string) error {\n\tuser, err := getUser(username)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvm, err := getVM(hostname)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontainerName := \"vm-\" + vm.Id.Hex()\n\tc := container.NewContainer(containerName)\n\n\tif c.IsRunning() {\n\t\treturn errors.New(\"vm is running\")\n\t}\n\n\t\/\/ these values are needed for templating. will be changed later\n\t\/\/ with a template struct.\n\tc.IP = vm.IP\n\tc.LdapPassword = vm.LdapPassword\n\tc.HostnameAlias = vm.HostnameAlias\n\tc.WebHome = vm.WebHome\n\tc.Username = user.Name\n\tc.Useruid = user.Uid\n\tc.DiskSizeInMB = vm.DiskSizeInMB\n\n\tlog.Info(\"preparing container '%s' for user '%s' with uid '%d'\",\n\t\tcontainerName, user.Name, user.Uid)\n\n\terr = c.Prepare()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif vm.AlwaysOn {\n\t\treturn nil\n\t}\n\n\tinfo := GetInfo(containerName)\n\tinfo.IP = c.IP\n\tinfo.StartTimer()\n\n\tk.OnDisconnect(username, func() {\n\t\tinfo.StopTimer()\n\t})\n\n\tlog.Info(\"[%s] prepared the container '%s'\", username, containerName)\n\treturn nil\n}\n\nfunc getUser(username string) (*models.User, error) {\n\tif username == \"\" {\n\t\treturn nil, errors.New(\"username is empty\")\n\t}\n\n\tuser, err := modelhelper.GetUser(username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = validateUser(user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn user, nil\n}\n\nfunc getVM(hostnameAlias string) (*models.VM, error) {\n\tif hostnameAlias == \"\" {\n\t\treturn nil, errors.New(\"hostname is empty\")\n\t}\n\n\tvm, err := modelhelper.GetVM(hostnameAlias)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = validateVM(vm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vm, nil\n}\n\nfunc validateVM(vm *models.VM) error {\n\t\/\/ applyDefaults\n\tif vm.NumCPUs == 0 {\n\t\tvm.NumCPUs = 1\n\t}\n\tif vm.MaxMemoryInMB == 0 {\n\t\tvm.MaxMemoryInMB = 1024\n\t}\n\tif vm.DiskSizeInMB == 0 {\n\t\tvm.DiskSizeInMB = 1200\n\t}\n\n\tif vm.Region != config.Region {\n\t\ttime.Sleep(time.Second) \/\/ to avoid rapid cycle channel loop\n\t\treturn fmt.Errorf(\"VM '%s' is on wrong region. Excepted: '%s' Got: '%s'\",\n\t\t\tvm.HostnameAlias, vm.Region, config.Region)\n\t}\n\n\tif vm.HostKite == \"(maintenance)\" {\n\t\treturn fmt.Errorf(\"VM '%s' is under maintenance\", vm.HostnameAlias)\n\t}\n\n\tif vm.HostKite == \"(banned)\" {\n\t\treturn fmt.Errorf(\"VM '%s' is banned\", vm.HostnameAlias)\n\t}\n\n\tif vm.IP == nil {\n\t\tvm.IP = createVMIP()\n\t\terr := updateVMIP(vm.IP, vm.Id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !containerSubnet.Contains(vm.IP) {\n\t\treturn fmt.Errorf(\"VM with IP is not in the container subnet: %s\", vm.IP.String())\n\t}\n\n\tif vm.LdapPassword == \"\" {\n\t\tvm.LdapPassword = createLdapPassword()\n\t\terr := updateLdapPassword(vm.LdapPassword, vm.Id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc validateUser(user *models.User) error {\n\tif user.Uid < container.UserUIDOffset {\n\t\treturn fmt.Errorf(\"User %s with too low uid: %s\\n\", user.Name, user.Uid)\n\t}\n\n\treturn nil\n}\n\nfunc createVMIP() net.IP {\n\tipInt := nextCounterValue(\"vm_ip\", int(binary.BigEndian.Uint32(firstContainerIP.To4())))\n\tip := net.IPv4(byte(ipInt>>24), byte(ipInt>>16), byte(ipInt>>8), byte(ipInt))\n\treturn ip\n}\n\nfunc updateVMIP(ip net.IP, id bson.ObjectId) error {\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Update(bson.M{\"_id\": id, \"ip\": nil}, bson.M{\"$set\": bson.M{\"ip\": ip}})\n\t}\n\n\tif err := mongodb.Run(\"jVMs\", query); err != nil {\n\t\treturn fmt.Errorf(\"updateVMIP failed: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc createLdapPassword() string {\n\treturn utils.RandomString()\n}\n\nfunc updateLdapPassword(ldapPassword string, id bson.ObjectId) error {\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Update(bson.M{\"_id\": id}, bson.M{\"$set\": bson.M{\"ldapPassword\": ldapPassword}})\n\t}\n\n\tif err := mongodb.Run(\"jVMs\", query); err != nil {\n\t\treturn fmt.Errorf(\"updateLdapPassword failed: %s\", err)\n\t}\n\n\treturn nil\n}\n\ntype Counter struct {\n\tName  string `bson:\"_id\"`\n\tValue int    `bson:\"seq\"`\n}\n\nfunc nextCounterValue(counterName string, initialValue int) int {\n\tvar counter Counter\n\n\tif err := mongodb.Run(\"counters\", func(c *mgo.Collection) error {\n\t\t_, err := c.FindId(counterName).Apply(mgo.Change{Update: bson.M{\"$inc\": bson.M{\"seq\": 1}}}, &counter)\n\t\treturn err\n\t}); err != nil {\n\t\tif err == mgo.ErrNotFound {\n\t\t\tmongodb.Run(\"counters\", func(c *mgo.Collection) error {\n\t\t\t\tc.Insert(Counter{Name: counterName, Value: initialValue})\n\t\t\t\treturn nil \/\/ ignore error and try to do atomic update again\n\t\t\t})\n\n\t\t\tif err := mongodb.Run(\"counters\", func(c *mgo.Collection) error {\n\t\t\t\t_, err := c.FindId(counterName).Apply(mgo.Change{Update: bson.M{\"$inc\": bson.M{\"seq\": 1}}}, &counter)\n\t\t\t\treturn err\n\t\t\t}); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn counter.Value\n\t\t}\n\t\tpanic(err)\n\t}\n\n\treturn counter.Value\n\n}\n<commit_msg>provisioning: fix initialization and logs<commit_after>\/\/ +build linux\n\npackage main\n\nimport (\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"koding\/db\/models\"\n\t\"koding\/db\/mongodb\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"koding\/kites\/provisioning\/container\"\n\t\"koding\/newkite\/kite\"\n\t\"koding\/newkite\/protocol\"\n\t\"koding\/tools\/config\"\n\t\"koding\/tools\/utils\"\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n\t\"net\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Provisioning struct{}\n\nvar (\n\tport             = flag.String(\"port\", \"4005\", \"port to bind itself\")\n\tcontainerSubnet  *net.IPNet\n\tfirstContainerIP net.IP\n\tcontainers       = make(map[string]*Info)\n\tk                = &kite.Kite{}\n\tlog              = kite.GetLogger()\n)\n\nfunc init() {\n\tvar err error\n\tif firstContainerIP, containerSubnet, err = net.ParseCIDR(config.Current.ContainerSubnet); err != nil {\n\t\tlog.Error(\"container subnet couldn't be initialized: %s\", err.Error())\n\t\tos.Exit(1)\n\t}\n\n\tif config.Region == \"\" {\n\t\tlog.Error(\"region is not defined. please define it with -r flag\")\n\t\tos.Exit(1)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tkontrolPort := strconv.Itoa(config.Current.NewKontrol.Port)\n\tkontrolHost := config.Current.NewKontrol.Host\n\tkontrolAddr := fmt.Sprintf(\"%s:%s\", kontrolHost, kontrolPort)\n\n\toptions := &protocol.Options{\n\t\tPublicIP:    \"localhost\",\n\t\tKitename:    \"provisioning\",\n\t\tVersion:     \"0.0.1\",\n\t\tPort:        *port,\n\t\tKontrolAddr: kontrolAddr,\n\t}\n\n\tmethods := map[string]string{\n\t\t\"vm.start\":     \"Start\",\n\t\t\"vm.stop\":      \"Stop\",\n\t\t\"vm.prepare\":   \"Prepare\",\n\t\t\"vm.unprepare\": \"Unprepare\",\n\t\t\"vm.exec\":      \"Exec\",\n\t}\n\n\tk = kite.New(options)\n\tk.AddMethods(new(Provisioning), methods)\n\tk.Start()\n}\n\nfunc (p *Provisioning) Start(r *protocol.KiteDnodeRequest, result *bool) error {\n\tvm, err := getVM(r.Hostname)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not get vm to start '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not start vm - 1\")\n\t}\n\n\tcontainerName := \"vm-\" + vm.Id.Hex()\n\n\tc := container.NewContainer(containerName)\n\terr = c.Start()\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not start container: '%s'. err: '%s'\", r.Username, containerName, err)\n\t\treturn errors.New(\"could not start vm - 2\")\n\t}\n\n\tlog.Info(\"[%s] started the container: '%s'\", r.Username, containerName)\n\t*result = true\n\treturn nil\n}\n\nfunc (p *Provisioning) Stop(r *protocol.KiteDnodeRequest, result *bool) error {\n\tvm, err := getVM(r.Hostname)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not get vm to stop '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not stop vm - 1\")\n\t}\n\n\tcontainerName := \"vm-\" + vm.Id.Hex()\n\n\tc := container.NewContainer(containerName)\n\terr = c.Stop()\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not stop container: '%s'. err: '%s'\", r.Username, containerName, err)\n\t\treturn errors.New(\"could not stop vm - 2\")\n\t}\n\n\tlog.Info(\"[%s] stopped the container: '%s'\", r.Username, containerName)\n\n\t*result = true\n\treturn nil\n}\n\nfunc (p *Provisioning) Exec(r *protocol.KiteDnodeRequest, result *string) error {\n\tvar command string\n\n\tif r.Args.Unmarshal(&command) != nil {\n\t\treturn errors.New(\"{ [string] }\")\n\t}\n\n\tuser, err := getUser(r.Username)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not get user to exec a command on '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not run command - 1\")\n\t}\n\n\tvm, err := getVM(r.Hostname)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not get vm to exec a command on '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not run command - 2\")\n\t}\n\n\tcontainerName := \"vm-\" + vm.Id.Hex()\n\n\tc := container.NewContainer(containerName)\n\tc.Useruid = user.Uid\n\n\toutput, err := c.Run(command)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not exec a command on '%s'. err: '%s'\", r.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not run command - 3\")\n\t}\n\n\tinfo := GetInfo(containerName)\n\tinfo.ResetTimer()\n\tlog.Info(\"[%s] did run the command '%s' on container'%s'\\n\", r.Username, command, containerName)\n\n\t*result = string(output)\n\treturn nil\n}\n\nfunc (p *Provisioning) Unprepare(r *protocol.KiteDnodeRequest, result *bool) error {\n\tvm, err := getVM(r.Hostname)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not get vm to unprepare '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not unprepare vm - 1\")\n\t}\n\n\tcontainerName := \"vm-\" + vm.Id.Hex()\n\n\tc := container.NewContainer(containerName)\n\tc.IP = vm.IP \/\/ needed for removing static route and ebtables in unprepare\n\n\tif c.IsRunning() {\n\t\terr = c.Shutdown(5)\n\t\tif err != nil {\n\t\t\tlog.Error(\"[%s] could not shutdown vm for unprepare vm: '%s'. err: '%s'\",\n\t\t\t\tr.Username, r.Hostname, err)\n\t\t\treturn errors.New(\"could not unprepare vm - 2\")\n\t\t}\n\t}\n\n\terr = c.Unprepare()\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not unprepare vm: '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not unprepare vm - 3\")\n\t}\n\n\tlog.Info(\"[%s] unprepared the container '%s'\", r.Username, containerName)\n\t*result = true\n\treturn nil\n}\n\nfunc (p *Provisioning) Prepare(r *protocol.KiteDnodeRequest, result *bool) error {\n\terr := prepare(r.Username, r.Hostname)\n\tif err != nil {\n\t\tlog.Error(\"[%s] could not prepare vm: '%s'. err: '%s'\",\n\t\t\tr.Username, r.Hostname, err)\n\t\treturn errors.New(\"could not prepare vm\")\n\t}\n\n\t*result = true\n\treturn nil\n}\n\nfunc prepare(username, hostname string) error {\n\tuser, err := getUser(username)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvm, err := getVM(hostname)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontainerName := \"vm-\" + vm.Id.Hex()\n\tc := container.NewContainer(containerName)\n\n\tif c.IsRunning() {\n\t\treturn errors.New(\"vm is running\")\n\t}\n\n\t\/\/ these values are needed for templating. will be changed later\n\t\/\/ with a template struct.\n\tc.IP = vm.IP\n\tc.LdapPassword = vm.LdapPassword\n\tc.HostnameAlias = vm.HostnameAlias\n\tc.WebHome = vm.WebHome\n\tc.Username = user.Name\n\tc.Useruid = user.Uid\n\tc.DiskSizeInMB = vm.DiskSizeInMB\n\n\tlog.Info(\"preparing container '%s' for user '%s' with uid '%d'\",\n\t\tcontainerName, user.Name, user.Uid)\n\n\terr = c.Prepare()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif vm.AlwaysOn {\n\t\treturn nil\n\t}\n\n\tinfo := GetInfo(containerName)\n\tinfo.IP = c.IP\n\tinfo.StartTimer()\n\n\tk.OnDisconnect(username, func() {\n\t\tinfo.StopTimer()\n\t})\n\n\tlog.Info(\"[%s] prepared the container '%s'\", username, containerName)\n\treturn nil\n}\n\nfunc getUser(username string) (*models.User, error) {\n\tif username == \"\" {\n\t\treturn nil, errors.New(\"username is empty\")\n\t}\n\n\tuser, err := modelhelper.GetUser(username)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = validateUser(user)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn user, nil\n}\n\nfunc getVM(hostnameAlias string) (*models.VM, error) {\n\tif hostnameAlias == \"\" {\n\t\treturn nil, errors.New(\"hostname is empty\")\n\t}\n\n\tvm, err := modelhelper.GetVM(hostnameAlias)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = validateVM(vm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn vm, nil\n}\n\nfunc validateVM(vm *models.VM) error {\n\t\/\/ applyDefaults\n\tif vm.NumCPUs == 0 {\n\t\tvm.NumCPUs = 1\n\t}\n\tif vm.MaxMemoryInMB == 0 {\n\t\tvm.MaxMemoryInMB = 1024\n\t}\n\tif vm.DiskSizeInMB == 0 {\n\t\tvm.DiskSizeInMB = 1200\n\t}\n\n\tif vm.Region != config.Region {\n\t\ttime.Sleep(time.Second) \/\/ to avoid rapid cycle channel loop\n\t\treturn fmt.Errorf(\"VM '%s' is on wrong region. expected: '%s' Got: '%s'\",\n\t\t\tvm.HostnameAlias, config.Region, vm.Region)\n\t}\n\n\tif vm.HostKite == \"(maintenance)\" {\n\t\treturn fmt.Errorf(\"VM '%s' is under maintenance\", vm.HostnameAlias)\n\t}\n\n\tif vm.HostKite == \"(banned)\" {\n\t\treturn fmt.Errorf(\"VM '%s' is banned\", vm.HostnameAlias)\n\t}\n\n\tif vm.IP == nil {\n\t\tvm.IP = createVMIP()\n\t\terr := updateVMIP(vm.IP, vm.Id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !containerSubnet.Contains(vm.IP) {\n\t\treturn fmt.Errorf(\"VM with IP is not in the container subnet: %s\", vm.IP.String())\n\t}\n\n\tif vm.LdapPassword == \"\" {\n\t\tvm.LdapPassword = createLdapPassword()\n\t\terr := updateLdapPassword(vm.LdapPassword, vm.Id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc validateUser(user *models.User) error {\n\tif user.Uid < container.UserUIDOffset {\n\t\treturn fmt.Errorf(\"User %s with too low uid: %s\\n\", user.Name, user.Uid)\n\t}\n\n\treturn nil\n}\n\nfunc createVMIP() net.IP {\n\tipInt := nextCounterValue(\"vm_ip\", int(binary.BigEndian.Uint32(firstContainerIP.To4())))\n\tip := net.IPv4(byte(ipInt>>24), byte(ipInt>>16), byte(ipInt>>8), byte(ipInt))\n\treturn ip\n}\n\nfunc updateVMIP(ip net.IP, id bson.ObjectId) error {\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Update(bson.M{\"_id\": id, \"ip\": nil}, bson.M{\"$set\": bson.M{\"ip\": ip}})\n\t}\n\n\tif err := mongodb.Run(\"jVMs\", query); err != nil {\n\t\treturn fmt.Errorf(\"updateVMIP failed: %s\", err)\n\t}\n\treturn nil\n}\n\nfunc createLdapPassword() string {\n\treturn utils.RandomString()\n}\n\nfunc updateLdapPassword(ldapPassword string, id bson.ObjectId) error {\n\tquery := func(c *mgo.Collection) error {\n\t\treturn c.Update(bson.M{\"_id\": id}, bson.M{\"$set\": bson.M{\"ldapPassword\": ldapPassword}})\n\t}\n\n\tif err := mongodb.Run(\"jVMs\", query); err != nil {\n\t\treturn fmt.Errorf(\"updateLdapPassword failed: %s\", err)\n\t}\n\n\treturn nil\n}\n\ntype Counter struct {\n\tName  string `bson:\"_id\"`\n\tValue int    `bson:\"seq\"`\n}\n\nfunc nextCounterValue(counterName string, initialValue int) int {\n\tvar counter Counter\n\n\tif err := mongodb.Run(\"counters\", func(c *mgo.Collection) error {\n\t\t_, err := c.FindId(counterName).Apply(mgo.Change{Update: bson.M{\"$inc\": bson.M{\"seq\": 1}}}, &counter)\n\t\treturn err\n\t}); err != nil {\n\t\tif err == mgo.ErrNotFound {\n\t\t\tmongodb.Run(\"counters\", func(c *mgo.Collection) error {\n\t\t\t\tc.Insert(Counter{Name: counterName, Value: initialValue})\n\t\t\t\treturn nil \/\/ ignore error and try to do atomic update again\n\t\t\t})\n\n\t\t\tif err := mongodb.Run(\"counters\", func(c *mgo.Collection) error {\n\t\t\t\t_, err := c.FindId(counterName).Apply(mgo.Change{Update: bson.M{\"$inc\": bson.M{\"seq\": 1}}}, &counter)\n\t\t\t\treturn err\n\t\t\t}); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn counter.Value\n\t\t}\n\t\tpanic(err)\n\t}\n\n\treturn counter.Value\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package common\n\nimport \"github.com\/cihangir\/gene\/writers\"\n\ntype Output struct {\n\tContent     []byte\n\tPath        string\n\tDoNotFormat bool\n}\n\n\/\/ WriteOutput writes output slice\nfunc WriteOutput(output []Output) error {\n\tfor _, file := range output {\n\t\t\/\/ do not write empty files\n\t\tif len(file.Content) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif file.DoNotFormat {\n\t\t\tif err := writers.Write(file.Path, file.Content); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif err := writers.WriteFormattedFile(file.Path, file.Content); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>Generator: added override control<commit_after>package common\n\nimport (\n\t\"github.com\/cihangir\/gene\/helpers\"\n\t\"github.com\/cihangir\/gene\/writers\"\n)\n\ntype Output struct {\n\tContent       []byte\n\tPath          string\n\tDoNotFormat   bool\n\tDoNotOverride bool\n}\n\n\/\/ WriteOutput writes output slice\nfunc WriteOutput(output []Output) error {\n\tfor _, file := range output {\n\t\t\/\/ do not write empty files\n\t\tif len(file.Content) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tif file.DoNotOverride {\n\t\t\t\/\/ if file exists, just skip this operation\n\t\t\tif _, err := helpers.ReadFile(file.Path); err == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif file.DoNotFormat {\n\t\t\tif err := writers.Write(file.Path, file.Content); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif err := writers.WriteFormattedFile(file.Path, file.Content); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package errors\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"text\/template\"\n\n\t\"github.com\/cihangir\/gene\/generators\/common\"\n\t\"github.com\/cihangir\/gene\/schema\"\n\t\"github.com\/cihangir\/gene\/stringext\"\n\t\"github.com\/cihangir\/gene\/writers\"\n)\n\nfunc Generate(rootPath string, s *schema.Schema) error {\n\t})\n\n\t_, err := temp.Parse(ErrorsTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar buf bytes.Buffer\n\n\tif err := temp.ExecuteTemplate(&buf, \"errors.tmpl\", s); err != nil {\n\t\treturn err\n\t}\n\n\tpath := fmt.Sprintf(\n\t\t\"%sworkers\/%s\/errors\/%s.go\",\n\t\trootPath,\n\t\tstringext.ToLowerFirst(s.Title),\n\t\tstringext.ToLowerFirst(s.Title),\n\t)\n\n\treturn writers.WriteFormattedFile(path, buf.Bytes())\n}\n<commit_msg>Errors: make errors package testable<commit_after>package errors\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"text\/template\"\n\n\t\"github.com\/cihangir\/gene\/generators\/common\"\n\t\"github.com\/cihangir\/gene\/schema\"\n\t\"github.com\/cihangir\/gene\/stringext\"\n\t\"github.com\/cihangir\/gene\/writers\"\n)\n\nfunc Generate(rootPath string, s *schema.Schema) error {\n\tdata, err := generate(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpath := fmt.Sprintf(\n\t\t\"%sworkers\/%s\/errors\/%s.go\",\n\t\trootPath,\n\t\tstringext.ToLowerFirst(s.Title),\n\t\tstringext.ToLowerFirst(s.Title),\n\t)\n\n\treturn writers.WriteFormattedFile(path, data)\n}\n\nfunc generate(s *schema.Schema) ([]byte, error) {\n\ttemp := template.New(\"errors.tmpl\").Funcs(common.TemplateFuncs)\n\t_, err := temp.Parse(ErrorsTemplate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar buf bytes.Buffer\n\n\tif err := temp.ExecuteTemplate(&buf, \"errors.tmpl\", s); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn writers.Clear(buf)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2020, OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ nolint:errcheck\npackage elasticsearchexporter\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"net\/http\"\n\t\"os\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\t\"go.uber.org\/atomic\"\n\t\"go.uber.org\/zap\"\n\t\"go.uber.org\/zap\/zaptest\"\n)\n\nfunc TestExporter_New(t *testing.T) {\n\ttype validate func(*testing.T, *elasticsearchExporter, error)\n\n\tsuccess := func(t *testing.T, exporter *elasticsearchExporter, err error) {\n\t\trequire.Nil(t, err)\n\t\trequire.NotNil(t, exporter)\n\t}\n\n\tfailWith := func(want error) validate {\n\t\treturn func(t *testing.T, exporter *elasticsearchExporter, err error) {\n\t\t\trequire.Nil(t, exporter)\n\t\t\trequire.NotNil(t, err)\n\t\t\tif !errors.Is(err, want) {\n\t\t\t\tt.Fatalf(\"Expected error '%v', but got '%v'\", want, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tfailWithMessage := func(msg string) validate {\n\t\treturn func(t *testing.T, exporter *elasticsearchExporter, err error) {\n\t\t\trequire.Nil(t, exporter)\n\t\t\trequire.NotNil(t, err)\n\t\t\trequire.Contains(t, err.Error(), msg)\n\t\t}\n\t}\n\n\ttests := map[string]struct {\n\t\tconfig *Config\n\t\twant   validate\n\t\tenv    map[string]string\n\t}{\n\t\t\"no endpoint\": {\n\t\t\tconfig: withDefaultConfig(),\n\t\t\twant:   failWith(errConfigNoEndpoint),\n\t\t},\n\t\t\"create from default config with ELASTICSEARCH_URL environment variable\": {\n\t\t\tconfig: withDefaultConfig(),\n\t\t\twant:   success,\n\t\t\tenv:    map[string]string{defaultElasticsearchEnvName: \"localhost:9200\"},\n\t\t},\n\t\t\"create from default with endpoints\": {\n\t\t\tconfig: withDefaultConfig(func(cfg *Config) {\n\t\t\t\tcfg.Endpoints = []string{\"test:9200\"}\n\t\t\t}),\n\t\t\twant: success,\n\t\t},\n\t\t\"create with cloudid\": {\n\t\t\tconfig: withDefaultConfig(func(cfg *Config) {\n\t\t\t\tcfg.CloudID = \"foo:YmFyLmNsb3VkLmVzLmlvJGFiYzEyMyRkZWY0NTY=\"\n\t\t\t}),\n\t\t\twant: success,\n\t\t},\n\t\t\"create with invalid cloudid\": {\n\t\t\tconfig: withDefaultConfig(func(cfg *Config) {\n\t\t\t\tcfg.CloudID = \"invalid\"\n\t\t\t}),\n\t\t\twant: failWithMessage(\"cannot parse CloudID\"),\n\t\t},\n\t\t\"fail if endpoint and cloudid are set\": {\n\t\t\tconfig: withDefaultConfig(func(cfg *Config) {\n\t\t\t\tcfg.Endpoints = []string{\"test:9200\"}\n\t\t\t\tcfg.CloudID = \"foo:YmFyLmNsb3VkLmVzLmlvJGFiYzEyMyRkZWY0NTY=\"\n\t\t\t}),\n\t\t\twant: failWithMessage(\"Addresses and CloudID are set\"),\n\t\t},\n\t}\n\n\tfor name, test := range tests {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tenv := test.env\n\t\t\tif len(env) == 0 {\n\t\t\t\tenv = map[string]string{defaultElasticsearchEnvName: \"\"}\n\t\t\t}\n\n\t\t\toldEnv := make(map[string]string, len(env))\n\t\t\tdefer func() {\n\t\t\t\tfor k, v := range oldEnv {\n\t\t\t\t\tos.Setenv(k, v)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tfor k := range env {\n\t\t\t\toldEnv[k] = os.Getenv(k)\n\t\t\t}\n\t\t\tfor k, v := range env {\n\t\t\t\tos.Setenv(k, v)\n\t\t\t}\n\n\t\t\texporter, err := newExporter(zap.NewNop(), test.config)\n\t\t\tif exporter != nil {\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, exporter.Shutdown(context.TODO()))\n\t\t\t\t}()\n\t\t\t}\n\n\t\t\ttest.want(t, exporter, err)\n\t\t})\n\t}\n}\n\nfunc TestExporter_PushEvent(t *testing.T) {\n\tt.Run(\"publish with success\", func(t *testing.T) {\n\t\trec := newBulkRecorder()\n\t\tserver := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\trec.Record(docs)\n\t\t\treturn itemsAllOK(docs)\n\t\t})\n\n\t\texporter := newTestExporter(t, server.URL)\n\t\tmustSend(t, exporter, `{\"message\": \"test1\"}`)\n\t\tmustSend(t, exporter, `{\"message\": \"test2\"}`)\n\n\t\trec.WaitItems(2)\n\t})\n\n\tt.Run(\"retry http request\", func(t *testing.T) {\n\t\tfailures := 0\n\t\trec := newBulkRecorder()\n\t\tserver := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\tif failures == 0 {\n\t\t\t\tfailures++\n\t\t\t\treturn nil, &httpTestError{message: \"oops\"}\n\t\t\t}\n\n\t\t\trec.Record(docs)\n\t\t\treturn itemsAllOK(docs)\n\t\t})\n\n\t\texporter := newTestExporter(t, server.URL)\n\t\tmustSend(t, exporter, `{\"message\": \"test1\"}`)\n\n\t\trec.WaitItems(1)\n\t})\n\n\tt.Run(\"no retry\", func(t *testing.T) {\n\t\tconfigurations := map[string]func(string) *Config{\n\t\t\t\"max_requests limited\": withTestExporterConfig(func(cfg *Config) {\n\t\t\t\tcfg.Retry.MaxRequests = 1\n\t\t\t\tcfg.Retry.InitialInterval = 1 * time.Millisecond\n\t\t\t\tcfg.Retry.MaxInterval = 10 * time.Millisecond\n\t\t\t}),\n\t\t\t\"retry.enabled is false\": withTestExporterConfig(func(cfg *Config) {\n\t\t\t\tcfg.Retry.Enabled = false\n\t\t\t\tcfg.Retry.MaxRequests = 10\n\t\t\t\tcfg.Retry.InitialInterval = 1 * time.Millisecond\n\t\t\t\tcfg.Retry.MaxInterval = 10 * time.Millisecond\n\t\t\t}),\n\t\t}\n\n\t\thandlers := map[string]func(attempts *atomic.Int64) bulkHandler{\n\t\t\t\"fail http request\": func(attempts *atomic.Int64) bulkHandler {\n\t\t\t\treturn func([]itemRequest) ([]itemResponse, error) {\n\t\t\t\t\tattempts.Inc()\n\t\t\t\t\treturn nil, &httpTestError{message: \"oops\"}\n\t\t\t\t}\n\t\t\t},\n\t\t\t\"fail item\": func(attempts *atomic.Int64) bulkHandler {\n\t\t\t\treturn func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\t\t\tattempts.Inc()\n\t\t\t\t\treturn itemsReportStatus(docs, http.StatusTooManyRequests)\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\n\t\tfor name, handler := range handlers {\n\t\t\tt.Run(name, func(t *testing.T) {\n\t\t\t\tt.Parallel()\n\t\t\t\tfor name, configurer := range configurations {\n\t\t\t\t\tt.Run(name, func(t *testing.T) {\n\t\t\t\t\t\tt.Parallel()\n\t\t\t\t\t\tattempts := atomic.NewInt64(0)\n\t\t\t\t\t\tserver := newESTestServer(t, handler(attempts))\n\n\t\t\t\t\t\ttestConfig := configurer(server.URL)\n\t\t\t\t\t\texporter := newTestExporter(t, server.URL, func(cfg *Config) { *cfg = *testConfig })\n\t\t\t\t\t\tmustSend(t, exporter, `{\"message\": \"test1\"}`)\n\n\t\t\t\t\t\ttime.Sleep(200 * time.Millisecond)\n\t\t\t\t\t\tassert.Equal(t, int64(1), attempts.Load())\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})\n\n\tt.Run(\"do not retry invalid request\", func(t *testing.T) {\n\t\tattempts := atomic.NewInt64(0)\n\t\tserver := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\tattempts.Inc()\n\t\t\treturn nil, &httpTestError{message: \"oops\", status: http.StatusBadRequest}\n\t\t})\n\n\t\texporter := newTestExporter(t, server.URL)\n\t\tmustSend(t, exporter, `{\"message\": \"test1\"}`)\n\n\t\ttime.Sleep(200 * time.Millisecond)\n\t\tassert.Equal(t, int64(1), attempts.Load())\n\t})\n\n\tt.Run(\"retry single item\", func(t *testing.T) {\n\t\tvar attempts int\n\t\trec := newBulkRecorder()\n\t\tserver := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\tattempts++\n\n\t\t\tif attempts == 1 {\n\t\t\t\treturn itemsReportStatus(docs, http.StatusTooManyRequests)\n\t\t\t}\n\n\t\t\trec.Record(docs)\n\t\t\treturn itemsAllOK(docs)\n\t\t})\n\n\t\texporter := newTestExporter(t, server.URL)\n\t\tmustSend(t, exporter, `{\"message\": \"test1\"}`)\n\n\t\trec.WaitItems(1)\n\t})\n\n\tt.Run(\"do not retry bad item\", func(t *testing.T) {\n\t\tattempts := atomic.NewInt64(0)\n\t\tserver := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\tattempts.Inc()\n\t\t\treturn itemsReportStatus(docs, http.StatusBadRequest)\n\t\t})\n\n\t\texporter := newTestExporter(t, server.URL)\n\t\tmustSend(t, exporter, `{\"message\": \"test1\"}`)\n\n\t\ttime.Sleep(200 * time.Millisecond)\n\t\tassert.Equal(t, int64(1), attempts.Load())\n\t})\n\n\tt.Run(\"only retry failed items\", func(t *testing.T) {\n\t\tvar attempts [3]int\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\n\t\tconst retryIdx = 1\n\n\t\tserver := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\tresp := make([]itemResponse, len(docs))\n\t\t\tfor i, doc := range docs {\n\t\t\t\tresp[i].Status = http.StatusOK\n\n\t\t\t\tvar idxInfo struct{ Idx int }\n\t\t\t\tif err := json.Unmarshal(doc.Document, &idxInfo); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\tif idxInfo.Idx == retryIdx {\n\t\t\t\t\tif attempts[retryIdx] == 0 {\n\t\t\t\t\t\tresp[i].Status = http.StatusTooManyRequests\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tattempts[idxInfo.Idx]++\n\t\t\t}\n\t\t\treturn resp, nil\n\t\t})\n\n\t\texporter := newTestExporter(t, server.URL, func(cfg *Config) {\n\t\t\tcfg.Flush.Interval = 50 * time.Millisecond\n\t\t\tcfg.Retry.InitialInterval = 1 * time.Millisecond\n\t\t\tcfg.Retry.MaxInterval = 10 * time.Millisecond\n\t\t})\n\t\tmustSend(t, exporter, `{\"message\": \"test1\", \"idx\": 0}`)\n\t\tmustSend(t, exporter, `{\"message\": \"test2\", \"idx\": 1}`)\n\t\tmustSend(t, exporter, `{\"message\": \"test3\", \"idx\": 2}`)\n\n\t\twg.Wait() \/\/ <- this blocks forever if the event is not retried\n\n\t\tassert.Equal(t, [3]int{1, 2, 1}, attempts)\n\t})\n}\n\nfunc newTestExporter(t *testing.T, url string, fns ...func(*Config)) *elasticsearchExporter {\n\texporter, err := newExporter(zaptest.NewLogger(t), withTestExporterConfig(fns...)(url))\n\trequire.NoError(t, err)\n\n\tt.Cleanup(func() { exporter.Shutdown(context.TODO()) })\n\treturn exporter\n}\n\nfunc withTestExporterConfig(fns ...func(*Config)) func(string) *Config {\n\treturn func(url string) *Config {\n\t\tvar configMods []func(*Config)\n\t\tconfigMods = append(configMods, func(cfg *Config) {\n\t\t\tcfg.Endpoints = []string{url}\n\t\t\tcfg.NumWorkers = 1\n\t\t\tcfg.Flush.Interval = 10 * time.Millisecond\n\t\t})\n\t\tconfigMods = append(configMods, fns...)\n\t\treturn withDefaultConfig(configMods...)\n\t}\n}\n\nfunc mustSend(t *testing.T, exporter *elasticsearchExporter, contents string) {\n\terr := exporter.pushEvent(context.TODO(), []byte(contents))\n\trequire.NoError(t, err)\n}\n<commit_msg>[exporter\/elasticsearch] Skip flaky TestExporter_PushEvent test on Windows (#10179)<commit_after>\/\/ Copyright 2020, OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ nolint:errcheck\npackage elasticsearchexporter\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\t\"go.uber.org\/atomic\"\n\t\"go.uber.org\/zap\"\n\t\"go.uber.org\/zap\/zaptest\"\n)\n\nfunc TestExporter_New(t *testing.T) {\n\ttype validate func(*testing.T, *elasticsearchExporter, error)\n\n\tsuccess := func(t *testing.T, exporter *elasticsearchExporter, err error) {\n\t\trequire.Nil(t, err)\n\t\trequire.NotNil(t, exporter)\n\t}\n\n\tfailWith := func(want error) validate {\n\t\treturn func(t *testing.T, exporter *elasticsearchExporter, err error) {\n\t\t\trequire.Nil(t, exporter)\n\t\t\trequire.NotNil(t, err)\n\t\t\tif !errors.Is(err, want) {\n\t\t\t\tt.Fatalf(\"Expected error '%v', but got '%v'\", want, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tfailWithMessage := func(msg string) validate {\n\t\treturn func(t *testing.T, exporter *elasticsearchExporter, err error) {\n\t\t\trequire.Nil(t, exporter)\n\t\t\trequire.NotNil(t, err)\n\t\t\trequire.Contains(t, err.Error(), msg)\n\t\t}\n\t}\n\n\ttests := map[string]struct {\n\t\tconfig *Config\n\t\twant   validate\n\t\tenv    map[string]string\n\t}{\n\t\t\"no endpoint\": {\n\t\t\tconfig: withDefaultConfig(),\n\t\t\twant:   failWith(errConfigNoEndpoint),\n\t\t},\n\t\t\"create from default config with ELASTICSEARCH_URL environment variable\": {\n\t\t\tconfig: withDefaultConfig(),\n\t\t\twant:   success,\n\t\t\tenv:    map[string]string{defaultElasticsearchEnvName: \"localhost:9200\"},\n\t\t},\n\t\t\"create from default with endpoints\": {\n\t\t\tconfig: withDefaultConfig(func(cfg *Config) {\n\t\t\t\tcfg.Endpoints = []string{\"test:9200\"}\n\t\t\t}),\n\t\t\twant: success,\n\t\t},\n\t\t\"create with cloudid\": {\n\t\t\tconfig: withDefaultConfig(func(cfg *Config) {\n\t\t\t\tcfg.CloudID = \"foo:YmFyLmNsb3VkLmVzLmlvJGFiYzEyMyRkZWY0NTY=\"\n\t\t\t}),\n\t\t\twant: success,\n\t\t},\n\t\t\"create with invalid cloudid\": {\n\t\t\tconfig: withDefaultConfig(func(cfg *Config) {\n\t\t\t\tcfg.CloudID = \"invalid\"\n\t\t\t}),\n\t\t\twant: failWithMessage(\"cannot parse CloudID\"),\n\t\t},\n\t\t\"fail if endpoint and cloudid are set\": {\n\t\t\tconfig: withDefaultConfig(func(cfg *Config) {\n\t\t\t\tcfg.Endpoints = []string{\"test:9200\"}\n\t\t\t\tcfg.CloudID = \"foo:YmFyLmNsb3VkLmVzLmlvJGFiYzEyMyRkZWY0NTY=\"\n\t\t\t}),\n\t\t\twant: failWithMessage(\"Addresses and CloudID are set\"),\n\t\t},\n\t}\n\n\tfor name, test := range tests {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tenv := test.env\n\t\t\tif len(env) == 0 {\n\t\t\t\tenv = map[string]string{defaultElasticsearchEnvName: \"\"}\n\t\t\t}\n\n\t\t\toldEnv := make(map[string]string, len(env))\n\t\t\tdefer func() {\n\t\t\t\tfor k, v := range oldEnv {\n\t\t\t\t\tos.Setenv(k, v)\n\t\t\t\t}\n\t\t\t}()\n\n\t\t\tfor k := range env {\n\t\t\t\toldEnv[k] = os.Getenv(k)\n\t\t\t}\n\t\t\tfor k, v := range env {\n\t\t\t\tos.Setenv(k, v)\n\t\t\t}\n\n\t\t\texporter, err := newExporter(zap.NewNop(), test.config)\n\t\t\tif exporter != nil {\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, exporter.Shutdown(context.TODO()))\n\t\t\t\t}()\n\t\t\t}\n\n\t\t\ttest.want(t, exporter, err)\n\t\t})\n\t}\n}\n\nfunc TestExporter_PushEvent(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"skipping test on Windows, see https:\/\/github.com\/open-telemetry\/opentelemetry-collector-contrib\/issues\/10178\")\n\t}\n\tt.Run(\"publish with success\", func(t *testing.T) {\n\t\trec := newBulkRecorder()\n\t\tserver := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\trec.Record(docs)\n\t\t\treturn itemsAllOK(docs)\n\t\t})\n\n\t\texporter := newTestExporter(t, server.URL)\n\t\tmustSend(t, exporter, `{\"message\": \"test1\"}`)\n\t\tmustSend(t, exporter, `{\"message\": \"test2\"}`)\n\n\t\trec.WaitItems(2)\n\t})\n\n\tt.Run(\"retry http request\", func(t *testing.T) {\n\t\tfailures := 0\n\t\trec := newBulkRecorder()\n\t\tserver := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\tif failures == 0 {\n\t\t\t\tfailures++\n\t\t\t\treturn nil, &httpTestError{message: \"oops\"}\n\t\t\t}\n\n\t\t\trec.Record(docs)\n\t\t\treturn itemsAllOK(docs)\n\t\t})\n\n\t\texporter := newTestExporter(t, server.URL)\n\t\tmustSend(t, exporter, `{\"message\": \"test1\"}`)\n\n\t\trec.WaitItems(1)\n\t})\n\n\tt.Run(\"no retry\", func(t *testing.T) {\n\t\tconfigurations := map[string]func(string) *Config{\n\t\t\t\"max_requests limited\": withTestExporterConfig(func(cfg *Config) {\n\t\t\t\tcfg.Retry.MaxRequests = 1\n\t\t\t\tcfg.Retry.InitialInterval = 1 * time.Millisecond\n\t\t\t\tcfg.Retry.MaxInterval = 10 * time.Millisecond\n\t\t\t}),\n\t\t\t\"retry.enabled is false\": withTestExporterConfig(func(cfg *Config) {\n\t\t\t\tcfg.Retry.Enabled = false\n\t\t\t\tcfg.Retry.MaxRequests = 10\n\t\t\t\tcfg.Retry.InitialInterval = 1 * time.Millisecond\n\t\t\t\tcfg.Retry.MaxInterval = 10 * time.Millisecond\n\t\t\t}),\n\t\t}\n\n\t\thandlers := map[string]func(attempts *atomic.Int64) bulkHandler{\n\t\t\t\"fail http request\": func(attempts *atomic.Int64) bulkHandler {\n\t\t\t\treturn func([]itemRequest) ([]itemResponse, error) {\n\t\t\t\t\tattempts.Inc()\n\t\t\t\t\treturn nil, &httpTestError{message: \"oops\"}\n\t\t\t\t}\n\t\t\t},\n\t\t\t\"fail item\": func(attempts *atomic.Int64) bulkHandler {\n\t\t\t\treturn func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\t\t\tattempts.Inc()\n\t\t\t\t\treturn itemsReportStatus(docs, http.StatusTooManyRequests)\n\t\t\t\t}\n\t\t\t},\n\t\t}\n\n\t\tfor name, handler := range handlers {\n\t\t\tt.Run(name, func(t *testing.T) {\n\t\t\t\tt.Parallel()\n\t\t\t\tfor name, configurer := range configurations {\n\t\t\t\t\tt.Run(name, func(t *testing.T) {\n\t\t\t\t\t\tt.Parallel()\n\t\t\t\t\t\tattempts := atomic.NewInt64(0)\n\t\t\t\t\t\tserver := newESTestServer(t, handler(attempts))\n\n\t\t\t\t\t\ttestConfig := configurer(server.URL)\n\t\t\t\t\t\texporter := newTestExporter(t, server.URL, func(cfg *Config) { *cfg = *testConfig })\n\t\t\t\t\t\tmustSend(t, exporter, `{\"message\": \"test1\"}`)\n\n\t\t\t\t\t\ttime.Sleep(200 * time.Millisecond)\n\t\t\t\t\t\tassert.Equal(t, int64(1), attempts.Load())\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t})\n\n\tt.Run(\"do not retry invalid request\", func(t *testing.T) {\n\t\tattempts := atomic.NewInt64(0)\n\t\tserver := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\tattempts.Inc()\n\t\t\treturn nil, &httpTestError{message: \"oops\", status: http.StatusBadRequest}\n\t\t})\n\n\t\texporter := newTestExporter(t, server.URL)\n\t\tmustSend(t, exporter, `{\"message\": \"test1\"}`)\n\n\t\ttime.Sleep(200 * time.Millisecond)\n\t\tassert.Equal(t, int64(1), attempts.Load())\n\t})\n\n\tt.Run(\"retry single item\", func(t *testing.T) {\n\t\tvar attempts int\n\t\trec := newBulkRecorder()\n\t\tserver := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\tattempts++\n\n\t\t\tif attempts == 1 {\n\t\t\t\treturn itemsReportStatus(docs, http.StatusTooManyRequests)\n\t\t\t}\n\n\t\t\trec.Record(docs)\n\t\t\treturn itemsAllOK(docs)\n\t\t})\n\n\t\texporter := newTestExporter(t, server.URL)\n\t\tmustSend(t, exporter, `{\"message\": \"test1\"}`)\n\n\t\trec.WaitItems(1)\n\t})\n\n\tt.Run(\"do not retry bad item\", func(t *testing.T) {\n\t\tattempts := atomic.NewInt64(0)\n\t\tserver := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\tattempts.Inc()\n\t\t\treturn itemsReportStatus(docs, http.StatusBadRequest)\n\t\t})\n\n\t\texporter := newTestExporter(t, server.URL)\n\t\tmustSend(t, exporter, `{\"message\": \"test1\"}`)\n\n\t\ttime.Sleep(200 * time.Millisecond)\n\t\tassert.Equal(t, int64(1), attempts.Load())\n\t})\n\n\tt.Run(\"only retry failed items\", func(t *testing.T) {\n\t\tvar attempts [3]int\n\t\tvar wg sync.WaitGroup\n\t\twg.Add(1)\n\n\t\tconst retryIdx = 1\n\n\t\tserver := newESTestServer(t, func(docs []itemRequest) ([]itemResponse, error) {\n\t\t\tresp := make([]itemResponse, len(docs))\n\t\t\tfor i, doc := range docs {\n\t\t\t\tresp[i].Status = http.StatusOK\n\n\t\t\t\tvar idxInfo struct{ Idx int }\n\t\t\t\tif err := json.Unmarshal(doc.Document, &idxInfo); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\tif idxInfo.Idx == retryIdx {\n\t\t\t\t\tif attempts[retryIdx] == 0 {\n\t\t\t\t\t\tresp[i].Status = http.StatusTooManyRequests\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tattempts[idxInfo.Idx]++\n\t\t\t}\n\t\t\treturn resp, nil\n\t\t})\n\n\t\texporter := newTestExporter(t, server.URL, func(cfg *Config) {\n\t\t\tcfg.Flush.Interval = 50 * time.Millisecond\n\t\t\tcfg.Retry.InitialInterval = 1 * time.Millisecond\n\t\t\tcfg.Retry.MaxInterval = 10 * time.Millisecond\n\t\t})\n\t\tmustSend(t, exporter, `{\"message\": \"test1\", \"idx\": 0}`)\n\t\tmustSend(t, exporter, `{\"message\": \"test2\", \"idx\": 1}`)\n\t\tmustSend(t, exporter, `{\"message\": \"test3\", \"idx\": 2}`)\n\n\t\twg.Wait() \/\/ <- this blocks forever if the event is not retried\n\n\t\tassert.Equal(t, [3]int{1, 2, 1}, attempts)\n\t})\n}\n\nfunc newTestExporter(t *testing.T, url string, fns ...func(*Config)) *elasticsearchExporter {\n\texporter, err := newExporter(zaptest.NewLogger(t), withTestExporterConfig(fns...)(url))\n\trequire.NoError(t, err)\n\n\tt.Cleanup(func() { exporter.Shutdown(context.TODO()) })\n\treturn exporter\n}\n\nfunc withTestExporterConfig(fns ...func(*Config)) func(string) *Config {\n\treturn func(url string) *Config {\n\t\tvar configMods []func(*Config)\n\t\tconfigMods = append(configMods, func(cfg *Config) {\n\t\t\tcfg.Endpoints = []string{url}\n\t\t\tcfg.NumWorkers = 1\n\t\t\tcfg.Flush.Interval = 10 * time.Millisecond\n\t\t})\n\t\tconfigMods = append(configMods, fns...)\n\t\treturn withDefaultConfig(configMods...)\n\t}\n}\n\nfunc mustSend(t *testing.T, exporter *elasticsearchExporter, contents string) {\n\terr := exporter.pushEvent(context.TODO(), []byte(contents))\n\trequire.NoError(t, err)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 The Cayley Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage memstore\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/barakmich\/glog\"\n\n\t\"github.com\/google\/cayley\/graph\"\n\t\"github.com\/google\/cayley\/graph\/iterator\"\n\t\"github.com\/google\/cayley\/graph\/memstore\/b\"\n\t\"github.com\/google\/cayley\/quad\"\n)\n\nconst QuadStoreType = \"memstore\"\n\nfunc init() {\n\tgraph.RegisterQuadStore(QuadStoreType, false, func(string, graph.Options) (graph.QuadStore, error) {\n\t\treturn newQuadStore(), nil\n\t}, nil, nil)\n}\n\nfunc cmp(a, b int64) int {\n\treturn int(a - b)\n}\n\ntype QuadDirectionIndex struct {\n\tindex [4]map[int64]*b.Tree\n}\n\nfunc NewQuadDirectionIndex() QuadDirectionIndex {\n\treturn QuadDirectionIndex{[...]map[int64]*b.Tree{\n\t\tquad.Subject - 1:   make(map[int64]*b.Tree),\n\t\tquad.Predicate - 1: make(map[int64]*b.Tree),\n\t\tquad.Object - 1:    make(map[int64]*b.Tree),\n\t\tquad.Label - 1:     make(map[int64]*b.Tree),\n\t}}\n}\n\nfunc (qdi QuadDirectionIndex) Tree(d quad.Direction, id int64) *b.Tree {\n\tif d < quad.Subject || d > quad.Label {\n\t\tpanic(\"illegal direction\")\n\t}\n\ttree, ok := qdi.index[d-1][id]\n\tif !ok {\n\t\ttree = b.TreeNew(cmp)\n\t\tqdi.index[d-1][id] = tree\n\t}\n\treturn tree\n}\n\nfunc (qdi QuadDirectionIndex) Get(d quad.Direction, id int64) (*b.Tree, bool) {\n\tif d < quad.Subject || d > quad.Label {\n\t\tpanic(\"illegal direction\")\n\t}\n\ttree, ok := qdi.index[d-1][id]\n\treturn tree, ok\n}\n\ntype LogEntry struct {\n\tID        int64\n\tQuad      quad.Quad\n\tAction    graph.Procedure\n\tTimestamp time.Time\n\tDeletedBy int64\n}\n\ntype QuadStore struct {\n\tnextID     int64\n\tnextQuadID int64\n\tidMap      map[string]int64\n\trevIDMap   map[int64]string\n\tlog        []LogEntry\n\tsize       int64\n\tindex      QuadDirectionIndex\n\t\/\/ vip_index map[string]map[int64]map[string]map[int64]*b.Tree\n}\n\nfunc newQuadStore() *QuadStore {\n\treturn &QuadStore{\n\t\tidMap:    make(map[string]int64),\n\t\trevIDMap: make(map[int64]string),\n\n\t\t\/\/ Sentinel null entry so indices start at 1\n\t\tlog: make([]LogEntry, 1, 200),\n\n\t\tindex:      NewQuadDirectionIndex(),\n\t\tnextID:     1,\n\t\tnextQuadID: 1,\n\t}\n}\n\nfunc (qs *QuadStore) ApplyDeltas(deltas []graph.Delta, ignoreOpts graph.IgnoreOpts) error {\n\tfor _, d := range deltas {\n\t\tvar err error\n\t\tswitch d.Action {\n\t\tcase graph.Add:\n\t\t\terr = qs.AddDelta(d)\n\t\t\tif err != nil && ignoreOpts.IgnoreDup {\n\t\t\t\terr = nil\n\t\t\t}\n\t\tcase graph.Delete:\n\t\t\terr = qs.RemoveDelta(d)\n\t\t\tif err != nil && ignoreOpts.IgnoreMissing {\n\t\t\t\terr = nil\n\t\t\t}\n\t\tdefault:\n\t\t\terr = errors.New(\"memstore: invalid action\")\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nconst maxInt = int(^uint(0) >> 1)\n\nfunc (qs *QuadStore) indexOf(t quad.Quad) (int64, bool) {\n\tmin := maxInt\n\tvar tree *b.Tree\n\tfor d := quad.Subject; d <= quad.Label; d++ {\n\t\tsid := t.Get(d)\n\t\tif d == quad.Label && sid == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tid, ok := qs.idMap[sid]\n\t\t\/\/ If we've never heard about a node, it must not exist\n\t\tif !ok {\n\t\t\treturn 0, false\n\t\t}\n\t\tindex, ok := qs.index.Get(d, id)\n\t\tif !ok {\n\t\t\t\/\/ If it's never been indexed in this direction, it can't exist.\n\t\t\treturn 0, false\n\t\t}\n\t\tif l := index.Len(); l < min {\n\t\t\tmin, tree = l, index\n\t\t}\n\t}\n\tit := NewIterator(tree, \"\", qs)\n\n\tfor it.Next() {\n\t\tval := it.Result()\n\t\tif t == qs.log[val.(int64)].Quad {\n\t\t\treturn val.(int64), true\n\t\t}\n\t}\n\treturn 0, false\n}\n\nfunc (qs *QuadStore) AddDelta(d graph.Delta) error {\n\tif _, exists := qs.indexOf(d.Quad); exists {\n\t\treturn graph.ErrQuadExists\n\t}\n\tqid := qs.nextQuadID\n\tqs.log = append(qs.log, LogEntry{\n\t\tID:        d.ID.Int(),\n\t\tQuad:      d.Quad,\n\t\tAction:    d.Action,\n\t\tTimestamp: d.Timestamp})\n\tqs.size++\n\tqs.nextQuadID++\n\n\tfor dir := quad.Subject; dir <= quad.Label; dir++ {\n\t\tsid := d.Quad.Get(dir)\n\t\tif dir == quad.Label && sid == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := qs.idMap[sid]; !ok {\n\t\t\tqs.idMap[sid] = qs.nextID\n\t\t\tqs.revIDMap[qs.nextID] = sid\n\t\t\tqs.nextID++\n\t\t}\n\t}\n\n\tfor dir := quad.Subject; dir <= quad.Label; dir++ {\n\t\tif dir == quad.Label && d.Quad.Get(dir) == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tid := qs.idMap[d.Quad.Get(dir)]\n\t\ttree := qs.index.Tree(dir, id)\n\t\ttree.Set(qid, struct{}{})\n\t}\n\n\t\/\/ TODO(barakmich): Add VIP indexing\n\treturn nil\n}\n\nfunc (qs *QuadStore) RemoveDelta(d graph.Delta) error {\n\tprevQuadID, exists := qs.indexOf(d.Quad)\n\tif !exists {\n\t\treturn graph.ErrQuadNotExist\n\t}\n\n\tquadID := qs.nextQuadID\n\tqs.log = append(qs.log, LogEntry{\n\t\tID:        d.ID.Int(),\n\t\tQuad:      d.Quad,\n\t\tAction:    d.Action,\n\t\tTimestamp: d.Timestamp})\n\tqs.log[prevQuadID].DeletedBy = quadID\n\tqs.size--\n\tqs.nextQuadID++\n\treturn nil\n}\n\nfunc (qs *QuadStore) Quad(index graph.Value) quad.Quad {\n\treturn qs.log[index.(int64)].Quad\n}\n\nfunc (qs *QuadStore) QuadIterator(d quad.Direction, value graph.Value) graph.Iterator {\n\tindex, ok := qs.index.Get(d, value.(int64))\n\tdata := fmt.Sprintf(\"dir:%s val:%d\", d, value.(int64))\n\tif ok {\n\t\treturn NewIterator(index, data, qs)\n\t}\n\treturn &iterator.Null{}\n}\n\nfunc (qs *QuadStore) Horizon() graph.PrimaryKey {\n\treturn graph.NewSequentialKey(qs.log[len(qs.log)-1].ID)\n}\n\nfunc (qs *QuadStore) Size() int64 {\n\treturn qs.size\n}\n\nfunc (qs *QuadStore) DebugPrint() {\n\tfor i, l := range qs.log {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tglog.V(2).Infof(\"%d: %#v\", i, l)\n\t}\n}\n\nfunc (qs *QuadStore) ValueOf(name string) graph.Value {\n\treturn qs.idMap[name]\n}\n\nfunc (qs *QuadStore) NameOf(id graph.Value) string {\n\treturn qs.revIDMap[id.(int64)]\n}\n\nfunc (qs *QuadStore) QuadsAllIterator() graph.Iterator {\n\treturn newQuadsAllIterator(qs)\n}\n\nfunc (qs *QuadStore) FixedIterator() graph.FixedIterator {\n\treturn iterator.NewFixed(iterator.Identity)\n}\n\nfunc (qs *QuadStore) QuadDirection(val graph.Value, d quad.Direction) graph.Value {\n\tname := qs.Quad(val).Get(d)\n\treturn qs.ValueOf(name)\n}\n\nfunc (qs *QuadStore) NodesAllIterator() graph.Iterator {\n\treturn newNodesAllIterator(qs)\n}\n\nfunc (qs *QuadStore) Close() {}\n\nfunc (qs *QuadStore) Type() string {\n\treturn QuadStoreType\n}\n<commit_msg>collapse 2 iterations into 1 in memstore<commit_after>\/\/ Copyright 2014 The Cayley Authors. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage memstore\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/barakmich\/glog\"\n\n\t\"github.com\/google\/cayley\/graph\"\n\t\"github.com\/google\/cayley\/graph\/iterator\"\n\t\"github.com\/google\/cayley\/graph\/memstore\/b\"\n\t\"github.com\/google\/cayley\/quad\"\n)\n\nconst QuadStoreType = \"memstore\"\n\nfunc init() {\n\tgraph.RegisterQuadStore(QuadStoreType, false, func(string, graph.Options) (graph.QuadStore, error) {\n\t\treturn newQuadStore(), nil\n\t}, nil, nil)\n}\n\nfunc cmp(a, b int64) int {\n\treturn int(a - b)\n}\n\ntype QuadDirectionIndex struct {\n\tindex [4]map[int64]*b.Tree\n}\n\nfunc NewQuadDirectionIndex() QuadDirectionIndex {\n\treturn QuadDirectionIndex{[...]map[int64]*b.Tree{\n\t\tquad.Subject - 1:   make(map[int64]*b.Tree),\n\t\tquad.Predicate - 1: make(map[int64]*b.Tree),\n\t\tquad.Object - 1:    make(map[int64]*b.Tree),\n\t\tquad.Label - 1:     make(map[int64]*b.Tree),\n\t}}\n}\n\nfunc (qdi QuadDirectionIndex) Tree(d quad.Direction, id int64) *b.Tree {\n\tif d < quad.Subject || d > quad.Label {\n\t\tpanic(\"illegal direction\")\n\t}\n\ttree, ok := qdi.index[d-1][id]\n\tif !ok {\n\t\ttree = b.TreeNew(cmp)\n\t\tqdi.index[d-1][id] = tree\n\t}\n\treturn tree\n}\n\nfunc (qdi QuadDirectionIndex) Get(d quad.Direction, id int64) (*b.Tree, bool) {\n\tif d < quad.Subject || d > quad.Label {\n\t\tpanic(\"illegal direction\")\n\t}\n\ttree, ok := qdi.index[d-1][id]\n\treturn tree, ok\n}\n\ntype LogEntry struct {\n\tID        int64\n\tQuad      quad.Quad\n\tAction    graph.Procedure\n\tTimestamp time.Time\n\tDeletedBy int64\n}\n\ntype QuadStore struct {\n\tnextID     int64\n\tnextQuadID int64\n\tidMap      map[string]int64\n\trevIDMap   map[int64]string\n\tlog        []LogEntry\n\tsize       int64\n\tindex      QuadDirectionIndex\n\t\/\/ vip_index map[string]map[int64]map[string]map[int64]*b.Tree\n}\n\nfunc newQuadStore() *QuadStore {\n\treturn &QuadStore{\n\t\tidMap:    make(map[string]int64),\n\t\trevIDMap: make(map[int64]string),\n\n\t\t\/\/ Sentinel null entry so indices start at 1\n\t\tlog: make([]LogEntry, 1, 200),\n\n\t\tindex:      NewQuadDirectionIndex(),\n\t\tnextID:     1,\n\t\tnextQuadID: 1,\n\t}\n}\n\nfunc (qs *QuadStore) ApplyDeltas(deltas []graph.Delta, ignoreOpts graph.IgnoreOpts) error {\n\tfor _, d := range deltas {\n\t\tvar err error\n\t\tswitch d.Action {\n\t\tcase graph.Add:\n\t\t\terr = qs.AddDelta(d)\n\t\t\tif err != nil && ignoreOpts.IgnoreDup {\n\t\t\t\terr = nil\n\t\t\t}\n\t\tcase graph.Delete:\n\t\t\terr = qs.RemoveDelta(d)\n\t\t\tif err != nil && ignoreOpts.IgnoreMissing {\n\t\t\t\terr = nil\n\t\t\t}\n\t\tdefault:\n\t\t\terr = errors.New(\"memstore: invalid action\")\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nconst maxInt = int(^uint(0) >> 1)\n\nfunc (qs *QuadStore) indexOf(t quad.Quad) (int64, bool) {\n\tmin := maxInt\n\tvar tree *b.Tree\n\tfor d := quad.Subject; d <= quad.Label; d++ {\n\t\tsid := t.Get(d)\n\t\tif d == quad.Label && sid == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tid, ok := qs.idMap[sid]\n\t\t\/\/ If we've never heard about a node, it must not exist\n\t\tif !ok {\n\t\t\treturn 0, false\n\t\t}\n\t\tindex, ok := qs.index.Get(d, id)\n\t\tif !ok {\n\t\t\t\/\/ If it's never been indexed in this direction, it can't exist.\n\t\t\treturn 0, false\n\t\t}\n\t\tif l := index.Len(); l < min {\n\t\t\tmin, tree = l, index\n\t\t}\n\t}\n\tit := NewIterator(tree, \"\", qs)\n\n\tfor it.Next() {\n\t\tval := it.Result()\n\t\tif t == qs.log[val.(int64)].Quad {\n\t\t\treturn val.(int64), true\n\t\t}\n\t}\n\treturn 0, false\n}\n\nfunc (qs *QuadStore) AddDelta(d graph.Delta) error {\n\tif _, exists := qs.indexOf(d.Quad); exists {\n\t\treturn graph.ErrQuadExists\n\t}\n\tqid := qs.nextQuadID\n\tqs.log = append(qs.log, LogEntry{\n\t\tID:        d.ID.Int(),\n\t\tQuad:      d.Quad,\n\t\tAction:    d.Action,\n\t\tTimestamp: d.Timestamp})\n\tqs.size++\n\tqs.nextQuadID++\n\n\tfor dir := quad.Subject; dir <= quad.Label; dir++ {\n\t\tsid := d.Quad.Get(dir)\n\t\tif dir == quad.Label && sid == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := qs.idMap[sid]; !ok {\n\t\t\tqs.idMap[sid] = qs.nextID\n\t\t\tqs.revIDMap[qs.nextID] = sid\n\t\t\tqs.nextID++\n\t\t}\n\t\tid := qs.idMap[sid]\n\t\ttree := qs.index.Tree(dir, id)\n\t\ttree.Set(qid, struct{}{})\n\t}\n\n\t\/\/ TODO(barakmich): Add VIP indexing\n\treturn nil\n}\n\nfunc (qs *QuadStore) RemoveDelta(d graph.Delta) error {\n\tprevQuadID, exists := qs.indexOf(d.Quad)\n\tif !exists {\n\t\treturn graph.ErrQuadNotExist\n\t}\n\n\tquadID := qs.nextQuadID\n\tqs.log = append(qs.log, LogEntry{\n\t\tID:        d.ID.Int(),\n\t\tQuad:      d.Quad,\n\t\tAction:    d.Action,\n\t\tTimestamp: d.Timestamp})\n\tqs.log[prevQuadID].DeletedBy = quadID\n\tqs.size--\n\tqs.nextQuadID++\n\treturn nil\n}\n\nfunc (qs *QuadStore) Quad(index graph.Value) quad.Quad {\n\treturn qs.log[index.(int64)].Quad\n}\n\nfunc (qs *QuadStore) QuadIterator(d quad.Direction, value graph.Value) graph.Iterator {\n\tindex, ok := qs.index.Get(d, value.(int64))\n\tdata := fmt.Sprintf(\"dir:%s val:%d\", d, value.(int64))\n\tif ok {\n\t\treturn NewIterator(index, data, qs)\n\t}\n\treturn &iterator.Null{}\n}\n\nfunc (qs *QuadStore) Horizon() graph.PrimaryKey {\n\treturn graph.NewSequentialKey(qs.log[len(qs.log)-1].ID)\n}\n\nfunc (qs *QuadStore) Size() int64 {\n\treturn qs.size\n}\n\nfunc (qs *QuadStore) DebugPrint() {\n\tfor i, l := range qs.log {\n\t\tif i == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tglog.V(2).Infof(\"%d: %#v\", i, l)\n\t}\n}\n\nfunc (qs *QuadStore) ValueOf(name string) graph.Value {\n\treturn qs.idMap[name]\n}\n\nfunc (qs *QuadStore) NameOf(id graph.Value) string {\n\treturn qs.revIDMap[id.(int64)]\n}\n\nfunc (qs *QuadStore) QuadsAllIterator() graph.Iterator {\n\treturn newQuadsAllIterator(qs)\n}\n\nfunc (qs *QuadStore) FixedIterator() graph.FixedIterator {\n\treturn iterator.NewFixed(iterator.Identity)\n}\n\nfunc (qs *QuadStore) QuadDirection(val graph.Value, d quad.Direction) graph.Value {\n\tname := qs.Quad(val).Get(d)\n\treturn qs.ValueOf(name)\n}\n\nfunc (qs *QuadStore) NodesAllIterator() graph.Iterator {\n\treturn newNodesAllIterator(qs)\n}\n\nfunc (qs *QuadStore) Close() {}\n\nfunc (qs *QuadStore) Type() string {\n\treturn QuadStoreType\n}\n<|endoftext|>"}
{"text":"<commit_before>package metadata\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/StackExchange\/slog\"\n\t\"github.com\/StackExchange\/wmi\"\n\t\"github.com\/bosun-monitor\/scollector\/opentsdb\"\n)\n\nfunc init() {\n\tmetafuncs = append(metafuncs, metaWindowsVersion, metaWindowsIfaces)\n}\n\nfunc metaWindowsVersion() {\n\tvar dst []Win32_OperatingSystem\n\tq := wmi.CreateQuery(&dst, \"\")\n\terr := wmi.Query(q, &dst)\n\tif err != nil {\n\t\tslog.Error(err)\n\t\treturn\n\t}\n\n\tvar dstComputer []Win32_ComputerSystem\n\tq = wmi.CreateQuery(&dstComputer, \"\")\n\terr = wmi.Query(q, &dstComputer)\n\tif err != nil {\n\t\tslog.Error(err)\n\t\treturn\n\t}\n\n\tvar dstBIOS []Win32_BIOS\n\tq = wmi.CreateQuery(&dstBIOS, \"\")\n\terr = wmi.Query(q, &dstBIOS)\n\tif err != nil {\n\t\tslog.Error(err)\n\t\treturn\n\t}\n\n\tfor _, v := range dst {\n\t\tAddMeta(\"\", nil, \"version\", v.Version, true)\n\t\tAddMeta(\"\", nil, \"versionCaption\", v.Caption, true)\n\t}\n\n\tfor _, v := range dstComputer {\n\t\tAddMeta(\"\", nil, \"manufacturer\", v.Manufacturer, true)\n\t\tAddMeta(\"\", nil, \"model\", v.Model, true)\n\t\tAddMeta(\"\", nil, \"memoryTotal\", v.TotalPhysicalMemory, true)\n\t}\n\n\tfor _, v := range dstBIOS {\n\t\tAddMeta(\"\", nil, \"serialNumber\", v.SerialNumber, true)\n\t}\n}\n\ntype Win32_OperatingSystem struct {\n\tCaption string\n\tVersion string\n}\n\ntype Win32_ComputerSystem struct {\n\tManufacturer        string\n\tModel               string\n\tTotalPhysicalMemory uint64\n}\n\ntype Win32_BIOS struct {\n\tSerialNumber string\n}\n\nfunc metaWindowsIfaces() {\n\tvar dstConfigs []Win32_NetworkAdapterConfiguration\n\tq := wmi.CreateQuery(&dstConfigs, \"WHERE MACAddress != null\")\n\terr := wmi.Query(q, &dstConfigs)\n\tif err != nil {\n\t\tslog.Error(err)\n\t\treturn\n\t}\n\n\tmNicConfigs := make(map[string]*Win32_NetworkAdapterConfiguration)\n\tfor i, nic := range dstConfigs {\n\t\tmNicConfigs[nic.SettingID] = &dstConfigs[i]\n\t}\n\n\tvar dstAdapters []MSFT_NetAdapter\n\tq = wmi.CreateQuery(&dstAdapters, \"WHERE HardwareInterface = True\") \/\/Exclude virtual adapters\n\terr = wmi.QueryNamespace(q, &dstAdapters, \"root\\\\StandardCimv2\")\n\tif err != nil {\n\t\tslog.Error(err)\n\t\treturn\n\t}\n\n\tfor _, v := range dstAdapters {\n\t\ttag := opentsdb.TagSet{\"iface\": fmt.Sprint(\"Interface\", v.InterfaceIndex)}\n\t\tAddMeta(\"\", tag, \"description\", v.InterfaceDescription, true)\n\t\tAddMeta(\"\", tag, \"name\", v.Name, true)\n\t\tAddMeta(\"\", tag, \"speed\", v.Speed, true)\n\n\t\tnicConfig := mNicConfigs[v.InterfaceGuid]\n\t\tif nicConfig != nil {\n\t\t\tAddMeta(\"\", tag, \"mac\", strings.Replace(nicConfig.MACAddress, \":\", \"\", -1), true)\n\t\t\tfor _, ip := range *nicConfig.IPAddress {\n\t\t\t\tAddMeta(\"\", tag, \"addr\", ip, true) \/\/ blocked by array support in WMI See https:\/\/github.com\/StackExchange\/wmi\/issues\/5\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype MSFT_NetAdapter struct {\n\tName                 string \/\/NY-WEB09-PRI-NIC-A\n\tSpeed                uint64 \/\/Bits per Second\n\tInterfaceDescription string \/\/Intel(R) Gigabit ET Quad Port Server Adapter #2\n\tInterfaceName        string \/\/Ethernet_10\n\tInterfaceGuid        string \/\/unique id\n\tInterfaceIndex       uint32\n}\n\ntype Win32_NetworkAdapterConfiguration struct {\n\tIPAddress  *[]string \/\/Both IPv4 and IPv6\n\tMACAddress string    \/\/00:1B:21:93:00:00\n\tSettingID  string    \/\/Matches InterfaceGuid\n}\n<commit_msg>cmd\/scollector: change speed metadata to be a pointer and default to zero when not available<commit_after>package metadata\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/StackExchange\/slog\"\n\t\"github.com\/StackExchange\/wmi\"\n\t\"github.com\/bosun-monitor\/scollector\/opentsdb\"\n)\n\nfunc init() {\n\tmetafuncs = append(metafuncs, metaWindowsVersion, metaWindowsIfaces)\n}\n\nfunc metaWindowsVersion() {\n\tvar dst []Win32_OperatingSystem\n\tq := wmi.CreateQuery(&dst, \"\")\n\terr := wmi.Query(q, &dst)\n\tif err != nil {\n\t\tslog.Error(err)\n\t\treturn\n\t}\n\n\tvar dstComputer []Win32_ComputerSystem\n\tq = wmi.CreateQuery(&dstComputer, \"\")\n\terr = wmi.Query(q, &dstComputer)\n\tif err != nil {\n\t\tslog.Error(err)\n\t\treturn\n\t}\n\n\tvar dstBIOS []Win32_BIOS\n\tq = wmi.CreateQuery(&dstBIOS, \"\")\n\terr = wmi.Query(q, &dstBIOS)\n\tif err != nil {\n\t\tslog.Error(err)\n\t\treturn\n\t}\n\n\tfor _, v := range dst {\n\t\tAddMeta(\"\", nil, \"version\", v.Version, true)\n\t\tAddMeta(\"\", nil, \"versionCaption\", v.Caption, true)\n\t}\n\n\tfor _, v := range dstComputer {\n\t\tAddMeta(\"\", nil, \"manufacturer\", v.Manufacturer, true)\n\t\tAddMeta(\"\", nil, \"model\", v.Model, true)\n\t\tAddMeta(\"\", nil, \"memoryTotal\", v.TotalPhysicalMemory, true)\n\t}\n\n\tfor _, v := range dstBIOS {\n\t\tAddMeta(\"\", nil, \"serialNumber\", v.SerialNumber, true)\n\t}\n}\n\ntype Win32_OperatingSystem struct {\n\tCaption string\n\tVersion string\n}\n\ntype Win32_ComputerSystem struct {\n\tManufacturer        string\n\tModel               string\n\tTotalPhysicalMemory uint64\n}\n\ntype Win32_BIOS struct {\n\tSerialNumber string\n}\n\nfunc metaWindowsIfaces() {\n\tvar dstConfigs []Win32_NetworkAdapterConfiguration\n\tq := wmi.CreateQuery(&dstConfigs, \"WHERE MACAddress != null\")\n\terr := wmi.Query(q, &dstConfigs)\n\tif err != nil {\n\t\tslog.Error(err)\n\t\treturn\n\t}\n\n\tmNicConfigs := make(map[string]*Win32_NetworkAdapterConfiguration)\n\tfor i, nic := range dstConfigs {\n\t\tmNicConfigs[nic.SettingID] = &dstConfigs[i]\n\t}\n\n\tvar dstAdapters []MSFT_NetAdapter\n\tq = wmi.CreateQuery(&dstAdapters, \"WHERE HardwareInterface = True\") \/\/Exclude virtual adapters\n\terr = wmi.QueryNamespace(q, &dstAdapters, \"root\\\\StandardCimv2\")\n\tif err != nil {\n\t\tslog.Error(err)\n\t\treturn\n\t}\n\n\tfor _, v := range dstAdapters {\n\t\ttag := opentsdb.TagSet{\"iface\": fmt.Sprint(\"Interface\", v.InterfaceIndex)}\n\t\tAddMeta(\"\", tag, \"description\", v.InterfaceDescription, true)\n\t\tAddMeta(\"\", tag, \"name\", v.Name, true)\n\t\tif v.Speed != nil {\n\t\t\tAddMeta(\"\", tag, \"speed\", v.Speed, true)\n\t\t} else {\n\t\t\tAddMeta(\"\", tag, \"speed\", 0, true)\n\t\t}\n\n\t\tnicConfig := mNicConfigs[v.InterfaceGuid]\n\t\tif nicConfig != nil {\n\t\t\tAddMeta(\"\", tag, \"mac\", strings.Replace(nicConfig.MACAddress, \":\", \"\", -1), true)\n\t\t\tfor _, ip := range *nicConfig.IPAddress {\n\t\t\t\tAddMeta(\"\", tag, \"addr\", ip, true) \/\/ blocked by array support in WMI See https:\/\/github.com\/StackExchange\/wmi\/issues\/5\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype MSFT_NetAdapter struct {\n\tName                 string  \/\/NY-WEB09-PRI-NIC-A\n\tSpeed                *uint64 \/\/Bits per Second\n\tInterfaceDescription string  \/\/Intel(R) Gigabit ET Quad Port Server Adapter #2\n\tInterfaceName        string  \/\/Ethernet_10\n\tInterfaceGuid        string  \/\/unique id\n\tInterfaceIndex       uint32\n}\n\ntype Win32_NetworkAdapterConfiguration struct {\n\tIPAddress  *[]string \/\/Both IPv4 and IPv6\n\tMACAddress string    \/\/00:1B:21:93:00:00\n\tSettingID  string    \/\/Matches InterfaceGuid\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/codegangsta\/cli\"\n\tmountpkg \"github.com\/googlecloudplatform\/gcsfuse\/internal\/mount\"\n)\n\n\/\/ Set up custom help text for gcsfuse; in particular the usage section.\nfunc init() {\n\tcli.AppHelpTemplate = `NAME:\n   {{.Name}} - {{.Usage}}\n\nUSAGE:\n   {{.Name}} {{if .Flags}}[global options]{{end}} bucket mountpoint\n   {{if .Version}}\nVERSION:\n   {{.Version}}\n   {{end}}{{if len .Authors}}\nAUTHOR(S):\n   {{range .Authors}}{{ . }}{{end}}\n   {{end}}{{if .Commands}}\nCOMMANDS:\n   {{range .Commands}}{{join .Names \", \"}}{{ \"\\t\" }}{{.Usage}}\n   {{end}}{{end}}{{if .Flags}}\nGLOBAL OPTIONS:\n   {{range .Flags}}{{.}}\n   {{end}}{{end}}{{if .Copyright }}\nCOPYRIGHT:\n   {{.Copyright}}\n   {{end}}\n`\n}\n\nfunc newApp() (app *cli.App) {\n\tdirModeValue := new(OctalInt)\n\t*dirModeValue = 0755\n\n\tfileModeValue := new(OctalInt)\n\t*fileModeValue = 0644\n\n\tapp = &cli.App{\n\t\tName:     \"gcsfuse\",\n\t\tVersion:  getVersion(),\n\t\tUsage:    \"Mount a GCS bucket locally\",\n\t\tHideHelp: true,\n\t\tWriter:   os.Stderr,\n\t\tFlags: []cli.Flag{\n\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"help, h\",\n\t\t\t\tUsage: \"Print this help text and exit successfuly.\",\n\t\t\t},\n\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"foreground\",\n\t\t\t\tUsage: \"Stay in the foreground after mounting.\",\n\t\t\t},\n\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ File system\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\tcli.StringSliceFlag{\n\t\t\t\tName:  \"o\",\n\t\t\t\tUsage: \"Additional system-specific mount options. Be careful!\",\n\t\t\t},\n\n\t\t\tcli.GenericFlag{\n\t\t\t\tName:  \"dir-mode\",\n\t\t\t\tValue: dirModeValue,\n\t\t\t\tUsage: \"Permissions bits for directories, in octal.\",\n\t\t\t},\n\n\t\t\tcli.GenericFlag{\n\t\t\t\tName:  \"file-mode\",\n\t\t\t\tValue: fileModeValue,\n\t\t\t\tUsage: \"Permission bits for files, in octal.\",\n\t\t\t},\n\n\t\t\tcli.IntFlag{\n\t\t\t\tName:  \"uid\",\n\t\t\t\tValue: -1,\n\t\t\t\tUsage: \"UID owner of all inodes.\",\n\t\t\t},\n\n\t\t\tcli.IntFlag{\n\t\t\t\tName:  \"gid\",\n\t\t\t\tValue: -1,\n\t\t\t\tUsage: \"GID owner of all inodes.\",\n\t\t\t},\n\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"implicit-dirs\",\n\t\t\t\tUsage: \"Implicitly define directories based on content. See\" +\n\t\t\t\t\t\"docs\/semantics.md\",\n\t\t\t},\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"only-dir\",\n\t\t\t\tUsage: \"Mount only the given directory, relative to the bucket root.\",\n\t\t\t},\n\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ GCS\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"key-file\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"Absolute path to JSON key file for use with GCS. \" +\n\t\t\t\t\t\"(default: none, Google application default credentials used)\",\n\t\t\t},\n\n\t\t\tcli.Float64Flag{\n\t\t\t\tName:  \"limit-bytes-per-sec\",\n\t\t\t\tValue: -1,\n\t\t\t\tUsage: \"Bandwidth limit for reading data, measured over a 30-second \" +\n\t\t\t\t\t\"window. (use -1 for no limit)\",\n\t\t\t},\n\n\t\t\tcli.Float64Flag{\n\t\t\t\tName:  \"limit-ops-per-sec\",\n\t\t\t\tValue: 5.0,\n\t\t\t\tUsage: \"Operations per second limit, measured over a 30-second window \" +\n\t\t\t\t\t\"(use -1 for no limit)\",\n\t\t\t},\n\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ Tuning\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\tcli.DurationFlag{\n\t\t\t\tName:  \"stat-cache-ttl\",\n\t\t\t\tValue: time.Minute,\n\t\t\t\tUsage: \"How long to cache StatObject results and inode attributes.\",\n\t\t\t},\n\n\t\t\tcli.DurationFlag{\n\t\t\t\tName:  \"type-cache-ttl\",\n\t\t\t\tValue: time.Minute,\n\t\t\t\tUsage: \"How long to cache name -> file\/dir mappings in directory \" +\n\t\t\t\t\t\"inodes.\",\n\t\t\t},\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"temp-dir\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"Absolute path to temporary directory for local GCS object \" +\n\t\t\t\t\t\"copies. (default: system default, likely \/tmp)\",\n\t\t\t},\n\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ Debugging\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"debug_fuse\",\n\t\t\t\tUsage: \"Enable fuse-related debugging output.\",\n\t\t\t},\n\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"debug_gcs\",\n\t\t\t\tUsage: \"Print GCS request and timing information.\",\n\t\t\t},\n\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"debug_http\",\n\t\t\t\tUsage: \"Dump HTTP requests and responses to\/from GCS.\",\n\t\t\t},\n\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"debug_invariants\",\n\t\t\t\tUsage: \"Panic when internal invariants are violated.\",\n\t\t\t},\n\t\t},\n\t}\n\n\treturn\n}\n\ntype flagStorage struct {\n\tForeground bool\n\n\t\/\/ File system\n\tMountOptions map[string]string\n\tDirMode      os.FileMode\n\tFileMode     os.FileMode\n\tUid          int64\n\tGid          int64\n\tImplicitDirs bool\n\tOnlyDir      string\n\n\t\/\/ GCS\n\tKeyFile                            string\n\tEgressBandwidthLimitBytesPerSecond float64\n\tOpRateLimitHz                      float64\n\n\t\/\/ Tuning\n\tStatCacheTTL time.Duration\n\tTypeCacheTTL time.Duration\n\tTempDir      string\n\n\t\/\/ Debugging\n\tDebugFuse       bool\n\tDebugGCS        bool\n\tDebugHTTP       bool\n\tDebugInvariants bool\n}\n\n\/\/ Add the flags accepted by run to the supplied flag set, returning the\n\/\/ variables into which the flags will parse.\nfunc populateFlags(c *cli.Context) (flags *flagStorage) {\n\tflags = &flagStorage{\n\t\tForeground: c.Bool(\"foreground\"),\n\n\t\t\/\/ File system\n\t\tMountOptions: make(map[string]string),\n\t\tDirMode:      os.FileMode(*c.Generic(\"dir-mode\").(*OctalInt)),\n\t\tFileMode:     os.FileMode(*c.Generic(\"file-mode\").(*OctalInt)),\n\t\tUid:          int64(c.Int(\"uid\")),\n\t\tGid:          int64(c.Int(\"gid\")),\n\t\tImplicitDirs: c.Bool(\"implicit-dirs\"),\n\t\tOnlyDir:      c.String(\"only-dir\"),\n\n\t\t\/\/ GCS,\n\t\tKeyFile: c.String(\"key-file\"),\n\t\tEgressBandwidthLimitBytesPerSecond: c.Float64(\"limit-bytes-per-sec\"),\n\t\tOpRateLimitHz:                      c.Float64(\"limit-ops-per-sec\"),\n\n\t\t\/\/ Tuning,\n\t\tStatCacheTTL: c.Duration(\"stat-cache-ttl\"),\n\t\tTypeCacheTTL: c.Duration(\"type-cache-ttl\"),\n\t\tTempDir:      c.String(\"temp-dir\"),\n\n\t\t\/\/ Debugging,\n\t\tDebugFuse:       c.Bool(\"debug_fuse\"),\n\t\tDebugGCS:        c.Bool(\"debug_gcs\"),\n\t\tDebugHTTP:       c.Bool(\"debug_http\"),\n\t\tDebugInvariants: c.Bool(\"debug_invariants\"),\n\t}\n\n\t\/\/ Handle the repeated \"-o\" flag.\n\tfor _, o := range c.StringSlice(\"o\") {\n\t\tmountpkg.ParseOptions(flags.MountOptions, o)\n\t}\n\n\treturn\n}\n\n\/\/ A cli.Generic that can be used with cli.GenericFlag to obtain an int flag\n\/\/ that is parsed in octal.\ntype OctalInt int\n\nvar _ cli.Generic = (*OctalInt)(nil)\n\nfunc (oi *OctalInt) Set(value string) (err error) {\n\ttmp, err := strconv.ParseInt(value, 8, 32)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Parsing as octal: %v\", err)\n\t\treturn\n\t}\n\n\t*oi = OctalInt(tmp)\n\treturn\n}\n\nfunc (oi OctalInt) String() string {\n\treturn fmt.Sprintf(\"%o\", oi)\n}\n<commit_msg>flags.go: fix for changes to help handling in package cli.<commit_after>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/codegangsta\/cli\"\n\tmountpkg \"github.com\/googlecloudplatform\/gcsfuse\/internal\/mount\"\n)\n\n\/\/ Set up custom help text for gcsfuse; in particular the usage section.\nfunc init() {\n\tcli.AppHelpTemplate = `NAME:\n   {{.Name}} - {{.Usage}}\n\nUSAGE:\n   {{.Name}} {{if .Flags}}[global options]{{end}} bucket mountpoint\n   {{if .Version}}\nVERSION:\n   {{.Version}}\n   {{end}}{{if len .Authors}}\nAUTHOR(S):\n   {{range .Authors}}{{ . }}{{end}}\n   {{end}}{{if .Flags}}\nGLOBAL OPTIONS:\n   {{range .Flags}}{{.}}\n   {{end}}{{end}}{{if .Copyright }}\nCOPYRIGHT:\n   {{.Copyright}}\n   {{end}}\n`\n}\n\nfunc newApp() (app *cli.App) {\n\tdirModeValue := new(OctalInt)\n\t*dirModeValue = 0755\n\n\tfileModeValue := new(OctalInt)\n\t*fileModeValue = 0644\n\n\tapp = &cli.App{\n\t\tName:     \"gcsfuse\",\n\t\tVersion:  getVersion(),\n\t\tUsage:    \"Mount a GCS bucket locally\",\n\t\tWriter:   os.Stderr,\n\t\tFlags: []cli.Flag{\n\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"foreground\",\n\t\t\t\tUsage: \"Stay in the foreground after mounting.\",\n\t\t\t},\n\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ File system\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\tcli.StringSliceFlag{\n\t\t\t\tName:  \"o\",\n\t\t\t\tUsage: \"Additional system-specific mount options. Be careful!\",\n\t\t\t},\n\n\t\t\tcli.GenericFlag{\n\t\t\t\tName:  \"dir-mode\",\n\t\t\t\tValue: dirModeValue,\n\t\t\t\tUsage: \"Permissions bits for directories, in octal.\",\n\t\t\t},\n\n\t\t\tcli.GenericFlag{\n\t\t\t\tName:  \"file-mode\",\n\t\t\t\tValue: fileModeValue,\n\t\t\t\tUsage: \"Permission bits for files, in octal.\",\n\t\t\t},\n\n\t\t\tcli.IntFlag{\n\t\t\t\tName:  \"uid\",\n\t\t\t\tValue: -1,\n\t\t\t\tUsage: \"UID owner of all inodes.\",\n\t\t\t},\n\n\t\t\tcli.IntFlag{\n\t\t\t\tName:  \"gid\",\n\t\t\t\tValue: -1,\n\t\t\t\tUsage: \"GID owner of all inodes.\",\n\t\t\t},\n\n\t\t\tcli.BoolFlag{\n\t\t\t\tName: \"implicit-dirs\",\n\t\t\t\tUsage: \"Implicitly define directories based on content. See\" +\n\t\t\t\t\t\"docs\/semantics.md\",\n\t\t\t},\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"only-dir\",\n\t\t\t\tUsage: \"Mount only the given directory, relative to the bucket root.\",\n\t\t\t},\n\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ GCS\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"key-file\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"Absolute path to JSON key file for use with GCS. \" +\n\t\t\t\t\t\"(default: none, Google application default credentials used)\",\n\t\t\t},\n\n\t\t\tcli.Float64Flag{\n\t\t\t\tName:  \"limit-bytes-per-sec\",\n\t\t\t\tValue: -1,\n\t\t\t\tUsage: \"Bandwidth limit for reading data, measured over a 30-second \" +\n\t\t\t\t\t\"window. (use -1 for no limit)\",\n\t\t\t},\n\n\t\t\tcli.Float64Flag{\n\t\t\t\tName:  \"limit-ops-per-sec\",\n\t\t\t\tValue: 5.0,\n\t\t\t\tUsage: \"Operations per second limit, measured over a 30-second window \" +\n\t\t\t\t\t\"(use -1 for no limit)\",\n\t\t\t},\n\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ Tuning\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\tcli.DurationFlag{\n\t\t\t\tName:  \"stat-cache-ttl\",\n\t\t\t\tValue: time.Minute,\n\t\t\t\tUsage: \"How long to cache StatObject results and inode attributes.\",\n\t\t\t},\n\n\t\t\tcli.DurationFlag{\n\t\t\t\tName:  \"type-cache-ttl\",\n\t\t\t\tValue: time.Minute,\n\t\t\t\tUsage: \"How long to cache name -> file\/dir mappings in directory \" +\n\t\t\t\t\t\"inodes.\",\n\t\t\t},\n\n\t\t\tcli.StringFlag{\n\t\t\t\tName:  \"temp-dir\",\n\t\t\t\tValue: \"\",\n\t\t\t\tUsage: \"Absolute path to temporary directory for local GCS object \" +\n\t\t\t\t\t\"copies. (default: system default, likely \/tmp)\",\n\t\t\t},\n\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\t\t\/\/ Debugging\n\t\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"debug_fuse\",\n\t\t\t\tUsage: \"Enable fuse-related debugging output.\",\n\t\t\t},\n\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"debug_gcs\",\n\t\t\t\tUsage: \"Print GCS request and timing information.\",\n\t\t\t},\n\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"debug_http\",\n\t\t\t\tUsage: \"Dump HTTP requests and responses to\/from GCS.\",\n\t\t\t},\n\n\t\t\tcli.BoolFlag{\n\t\t\t\tName:  \"debug_invariants\",\n\t\t\t\tUsage: \"Panic when internal invariants are violated.\",\n\t\t\t},\n\t\t},\n\t}\n\n\treturn\n}\n\ntype flagStorage struct {\n\tForeground bool\n\n\t\/\/ File system\n\tMountOptions map[string]string\n\tDirMode      os.FileMode\n\tFileMode     os.FileMode\n\tUid          int64\n\tGid          int64\n\tImplicitDirs bool\n\tOnlyDir      string\n\n\t\/\/ GCS\n\tKeyFile                            string\n\tEgressBandwidthLimitBytesPerSecond float64\n\tOpRateLimitHz                      float64\n\n\t\/\/ Tuning\n\tStatCacheTTL time.Duration\n\tTypeCacheTTL time.Duration\n\tTempDir      string\n\n\t\/\/ Debugging\n\tDebugFuse       bool\n\tDebugGCS        bool\n\tDebugHTTP       bool\n\tDebugInvariants bool\n}\n\n\/\/ Add the flags accepted by run to the supplied flag set, returning the\n\/\/ variables into which the flags will parse.\nfunc populateFlags(c *cli.Context) (flags *flagStorage) {\n\tflags = &flagStorage{\n\t\tForeground: c.Bool(\"foreground\"),\n\n\t\t\/\/ File system\n\t\tMountOptions: make(map[string]string),\n\t\tDirMode:      os.FileMode(*c.Generic(\"dir-mode\").(*OctalInt)),\n\t\tFileMode:     os.FileMode(*c.Generic(\"file-mode\").(*OctalInt)),\n\t\tUid:          int64(c.Int(\"uid\")),\n\t\tGid:          int64(c.Int(\"gid\")),\n\t\tImplicitDirs: c.Bool(\"implicit-dirs\"),\n\t\tOnlyDir:      c.String(\"only-dir\"),\n\n\t\t\/\/ GCS,\n\t\tKeyFile: c.String(\"key-file\"),\n\t\tEgressBandwidthLimitBytesPerSecond: c.Float64(\"limit-bytes-per-sec\"),\n\t\tOpRateLimitHz:                      c.Float64(\"limit-ops-per-sec\"),\n\n\t\t\/\/ Tuning,\n\t\tStatCacheTTL: c.Duration(\"stat-cache-ttl\"),\n\t\tTypeCacheTTL: c.Duration(\"type-cache-ttl\"),\n\t\tTempDir:      c.String(\"temp-dir\"),\n\n\t\t\/\/ Debugging,\n\t\tDebugFuse:       c.Bool(\"debug_fuse\"),\n\t\tDebugGCS:        c.Bool(\"debug_gcs\"),\n\t\tDebugHTTP:       c.Bool(\"debug_http\"),\n\t\tDebugInvariants: c.Bool(\"debug_invariants\"),\n\t}\n\n\t\/\/ Handle the repeated \"-o\" flag.\n\tfor _, o := range c.StringSlice(\"o\") {\n\t\tmountpkg.ParseOptions(flags.MountOptions, o)\n\t}\n\n\treturn\n}\n\n\/\/ A cli.Generic that can be used with cli.GenericFlag to obtain an int flag\n\/\/ that is parsed in octal.\ntype OctalInt int\n\nvar _ cli.Generic = (*OctalInt)(nil)\n\nfunc (oi *OctalInt) Set(value string) (err error) {\n\ttmp, err := strconv.ParseInt(value, 8, 32)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Parsing as octal: %v\", err)\n\t\treturn\n\t}\n\n\t*oi = OctalInt(tmp)\n\treturn\n}\n\nfunc (oi OctalInt) String() string {\n\treturn fmt.Sprintf(\"%o\", oi)\n}\n<|endoftext|>"}
{"text":"<commit_before>package sdp\n\nimport (\n\t\"net\"\n\t\"net\/url\"\n\t\"testing\"\n)\n\nconst (\n\tCanonicalMarshalSDP = \"v=0\\r\\n\" +\n\t\t\"o=jdoe 2890844526 2890842807 IN IP4 10.47.16.5\\r\\n\" +\n\t\t\"s=SDP Seminar\\r\\n\" +\n\t\t\"i=A Seminar on the session description protocol\\r\\n\" +\n\t\t\"u=http:\/\/www.example.com\/seminars\/sdp.pdf\\r\\n\" +\n\t\t\"e=j.doe@example.com (Jane Doe)\\r\\n\" +\n\t\t\"p=+1 617 555-6011\\r\\n\" +\n\t\t\"c=IN IP4 224.2.17.12\/127\\r\\n\" +\n\t\t\"b=X-YZ:128\\r\\n\" +\n\t\t\"b=AS:12345\\r\\n\" +\n\t\t\"t=2873397496 2873404696\\r\\n\" +\n\t\t\"t=3034423619 3042462419\\r\\n\" +\n\t\t\"r=604800 3600 0 90000\\r\\n\" +\n\t\t\"z=2882844526 -3600 2898848070 0\\r\\n\" +\n\t\t\"k=prompt\\r\\n\" +\n\t\t\"a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host\\r\\n\" +\n\t\t\"a=recvonly\\r\\n\" +\n\t\t\"m=audio 49170 RTP\/AVP 0\\r\\n\" +\n\t\t\"i=Vivamus a posuere nisl\\r\\n\" +\n\t\t\"c=IN IP4 203.0.113.1\\r\\n\" +\n\t\t\"b=X-YZ:128\\r\\n\" +\n\t\t\"k=prompt\\r\\n\" +\n\t\t\"a=sendrecv\\r\\n\" +\n\t\t\"m=video 51372 RTP\/AVP 99\\r\\n\" +\n\t\t\"a=rtpmap:99 h263-1998\/90000\\r\\n\"\n)\n\nfunc TestMarshalCanonical(t *testing.T) {\n\tsd := &SessionDescription{\n\t\tVersion: 0,\n\t\tOrigin: Origin{\n\t\t\tUsername:       \"jdoe\",\n\t\t\tSessionID:      uint64(2890844526),\n\t\t\tSessionVersion: uint64(2890842807),\n\t\t\tNetworkType:    \"IN\",\n\t\t\tAddressType:    \"IP4\",\n\t\t\tUnicastAddress: \"10.47.16.5\",\n\t\t},\n\t\tSessionName:        \"SDP Seminar\",\n\t\tSessionInformation: &(&struct{ x Information }{\"A Seminar on the session description protocol\"}).x,\n\t\tURI: func() *url.URL {\n\t\t\turi, err := url.Parse(\"http:\/\/www.example.com\/seminars\/sdp.pdf\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn uri\n\t\t}(),\n\t\tEmailAddress: &(&struct{ x EmailAddress }{\"j.doe@example.com (Jane Doe)\"}).x,\n\t\tPhoneNumber:  &(&struct{ x PhoneNumber }{\"+1 617 555-6011\"}).x,\n\t\tConnectionInformation: &ConnectionInformation{\n\t\t\tNetworkType: \"IN\",\n\t\t\tAddressType: \"IP4\",\n\t\t\tAddress: &Address{\n\t\t\t\tIP:  net.ParseIP(\"224.2.17.12\"),\n\t\t\t\tTTL: &(&struct{ x int }{127}).x,\n\t\t\t},\n\t\t},\n\t\tBandwidth: []Bandwidth{\n\t\t\t{\n\t\t\t\tExperimental: true,\n\t\t\t\tType:         \"YZ\",\n\t\t\t\tBandwidth:    128,\n\t\t\t},\n\t\t\t{\n\t\t\t\tType:      \"AS\",\n\t\t\t\tBandwidth: 12345,\n\t\t\t},\n\t\t},\n\t\tTimeDescriptions: []TimeDescription{\n\t\t\t{\n\t\t\t\tTiming: Timing{\n\t\t\t\t\tStartTime: 2873397496,\n\t\t\t\t\tStopTime:  2873404696,\n\t\t\t\t},\n\t\t\t\tRepeatTimes: nil,\n\t\t\t},\n\t\t\t{\n\t\t\t\tTiming: Timing{\n\t\t\t\t\tStartTime: 3034423619,\n\t\t\t\t\tStopTime:  3042462419,\n\t\t\t\t},\n\t\t\t\tRepeatTimes: []RepeatTime{\n\t\t\t\t\t{\n\t\t\t\t\t\tInterval: 604800,\n\t\t\t\t\t\tDuration: 3600,\n\t\t\t\t\t\tOffsets:  []int64{0, 90000},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tTimeZones: []TimeZone{\n\t\t\t{\n\t\t\t\tAdjustmentTime: 2882844526,\n\t\t\t\tOffset:         -3600,\n\t\t\t},\n\t\t\t{\n\t\t\t\tAdjustmentTime: 2898848070,\n\t\t\t\tOffset:         0,\n\t\t\t},\n\t\t},\n\t\tEncryptionKey: &(&struct{ x EncryptionKey }{\"prompt\"}).x,\n\t\tAttributes: []Attribute{\n\t\t\tAttribute(\"candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host\"),\n\t\t\tAttribute(\"recvonly\"),\n\t\t},\n\t\tMediaDescriptions: []MediaDescription{\n\t\t\t{\n\t\t\t\tMediaName: MediaName{\n\t\t\t\t\tMedia: \"audio\",\n\t\t\t\t\tPort: RangedPort{\n\t\t\t\t\t\tValue: 49170,\n\t\t\t\t\t},\n\t\t\t\t\tProtos:  []string{\"RTP\", \"AVP\"},\n\t\t\t\t\tFormats: []int{0},\n\t\t\t\t},\n\t\t\t\tMediaTitle: &(&struct{ x Information }{\"Vivamus a posuere nisl\"}).x,\n\t\t\t\tConnectionInformation: &ConnectionInformation{\n\t\t\t\t\tNetworkType: \"IN\",\n\t\t\t\t\tAddressType: \"IP4\",\n\t\t\t\t\tAddress: &Address{\n\t\t\t\t\t\tIP: net.ParseIP(\"203.0.113.1\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tBandwidth: []Bandwidth{\n\t\t\t\t\t{\n\t\t\t\t\t\tExperimental: true,\n\t\t\t\t\t\tType:         \"YZ\",\n\t\t\t\t\t\tBandwidth:    128,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tEncryptionKey: &(&struct{ x EncryptionKey }{\"prompt\"}).x,\n\t\t\t\tAttributes: []Attribute{\n\t\t\t\t\tAttribute(\"sendrecv\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tMediaName: MediaName{\n\t\t\t\t\tMedia: \"video\",\n\t\t\t\t\tPort: RangedPort{\n\t\t\t\t\t\tValue: 51372,\n\t\t\t\t\t},\n\t\t\t\t\tProtos:  []string{\"RTP\", \"AVP\"},\n\t\t\t\t\tFormats: []int{99},\n\t\t\t\t},\n\t\t\t\tAttributes: []Attribute{\n\t\t\t\t\tAttribute(\"rtpmap:99 h263-1998\/90000\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tactual := sd.Marshal()\n\tif actual != CanonicalMarshalSDP {\n\t\tt.Errorf(\"error:\\n\\nEXPECTED:\\n%v\\nACTUAL:\\n%v\", CanonicalMarshalSDP, actual)\n\t}\n}\n<commit_msg>Fix all lint errors<commit_after>package sdp\n\nimport (\n\t\"net\"\n\t\"net\/url\"\n\t\"testing\"\n)\n\nconst (\n\tCanonicalMarshalSDP = \"v=0\\r\\n\" +\n\t\t\"o=jdoe 2890844526 2890842807 IN IP4 10.47.16.5\\r\\n\" +\n\t\t\"s=SDP Seminar\\r\\n\" +\n\t\t\"i=A Seminar on the session description protocol\\r\\n\" +\n\t\t\"u=http:\/\/www.example.com\/seminars\/sdp.pdf\\r\\n\" +\n\t\t\"e=j.doe@example.com (Jane Doe)\\r\\n\" +\n\t\t\"p=+1 617 555-6011\\r\\n\" +\n\t\t\"c=IN IP4 224.2.17.12\/127\\r\\n\" +\n\t\t\"b=X-YZ:128\\r\\n\" +\n\t\t\"b=AS:12345\\r\\n\" +\n\t\t\"t=2873397496 2873404696\\r\\n\" +\n\t\t\"t=3034423619 3042462419\\r\\n\" +\n\t\t\"r=604800 3600 0 90000\\r\\n\" +\n\t\t\"z=2882844526 -3600 2898848070 0\\r\\n\" +\n\t\t\"k=prompt\\r\\n\" +\n\t\t\"a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host\\r\\n\" +\n\t\t\"a=recvonly\\r\\n\" +\n\t\t\"m=audio 49170 RTP\/AVP 0\\r\\n\" +\n\t\t\"i=Vivamus a posuere nisl\\r\\n\" +\n\t\t\"c=IN IP4 203.0.113.1\\r\\n\" +\n\t\t\"b=X-YZ:128\\r\\n\" +\n\t\t\"k=prompt\\r\\n\" +\n\t\t\"a=sendrecv\\r\\n\" +\n\t\t\"m=video 51372 RTP\/AVP 99\\r\\n\" +\n\t\t\"a=rtpmap:99 h263-1998\/90000\\r\\n\"\n)\n\nfunc TestMarshalCanonical(t *testing.T) {\n\tsd := &SessionDescription{\n\t\tVersion: 0,\n\t\tOrigin: Origin{\n\t\t\tUsername:       \"jdoe\",\n\t\t\tSessionID:      uint64(2890844526),\n\t\t\tSessionVersion: uint64(2890842807),\n\t\t\tNetworkType:    \"IN\",\n\t\t\tAddressType:    \"IP4\",\n\t\t\tUnicastAddress: \"10.47.16.5\",\n\t\t},\n\t\tSessionName:        \"SDP Seminar\",\n\t\tSessionInformation: &(&struct{ x Information }{\"A Seminar on the session description protocol\"}).x,\n\t\tURI: func() *url.URL {\n\t\t\turi, err := url.Parse(\"http:\/\/www.example.com\/seminars\/sdp.pdf\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn uri\n\t\t}(),\n\t\tEmailAddress: &(&struct{ x EmailAddress }{\"j.doe@example.com (Jane Doe)\"}).x,\n\t\tPhoneNumber:  &(&struct{ x PhoneNumber }{\"+1 617 555-6011\"}).x,\n\t\tConnectionInformation: &ConnectionInformation{\n\t\t\tNetworkType: \"IN\",\n\t\t\tAddressType: \"IP4\",\n\t\t\tAddress: &Address{\n\t\t\t\tIP:  net.ParseIP(\"224.2.17.12\"),\n\t\t\t\tTTL: &(&struct{ x int }{127}).x,\n\t\t\t},\n\t\t},\n\t\tBandwidth: []Bandwidth{\n\t\t\t{\n\t\t\t\tExperimental: true,\n\t\t\t\tType:         \"YZ\",\n\t\t\t\tBandwidth:    128,\n\t\t\t},\n\t\t\t{\n\t\t\t\tType:      \"AS\",\n\t\t\t\tBandwidth: 12345,\n\t\t\t},\n\t\t},\n\t\tTimeDescriptions: []TimeDescription{\n\t\t\t{\n\t\t\t\tTiming: Timing{\n\t\t\t\t\tStartTime: 2873397496,\n\t\t\t\t\tStopTime:  2873404696,\n\t\t\t\t},\n\t\t\t\tRepeatTimes: nil,\n\t\t\t},\n\t\t\t{\n\t\t\t\tTiming: Timing{\n\t\t\t\t\tStartTime: 3034423619,\n\t\t\t\t\tStopTime:  3042462419,\n\t\t\t\t},\n\t\t\t\tRepeatTimes: []RepeatTime{\n\t\t\t\t\t{\n\t\t\t\t\t\tInterval: 604800,\n\t\t\t\t\t\tDuration: 3600,\n\t\t\t\t\t\tOffsets:  []int64{0, 90000},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tTimeZones: []TimeZone{\n\t\t\t{\n\t\t\t\tAdjustmentTime: 2882844526,\n\t\t\t\tOffset:         -3600,\n\t\t\t},\n\t\t\t{\n\t\t\t\tAdjustmentTime: 2898848070,\n\t\t\t\tOffset:         0,\n\t\t\t},\n\t\t},\n\t\tEncryptionKey: &(&struct{ x EncryptionKey }{\"prompt\"}).x,\n\t\tAttributes: []Attribute{\n\t\t\tAttribute(\"candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host\"),\n\t\t\tAttribute(\"recvonly\"),\n\t\t},\n\t\tMediaDescriptions: []*MediaDescription{\n\t\t\t{\n\t\t\t\tMediaName: MediaName{\n\t\t\t\t\tMedia: \"audio\",\n\t\t\t\t\tPort: RangedPort{\n\t\t\t\t\t\tValue: 49170,\n\t\t\t\t\t},\n\t\t\t\t\tProtos:  []string{\"RTP\", \"AVP\"},\n\t\t\t\t\tFormats: []int{0},\n\t\t\t\t},\n\t\t\t\tMediaTitle: &(&struct{ x Information }{\"Vivamus a posuere nisl\"}).x,\n\t\t\t\tConnectionInformation: &ConnectionInformation{\n\t\t\t\t\tNetworkType: \"IN\",\n\t\t\t\t\tAddressType: \"IP4\",\n\t\t\t\t\tAddress: &Address{\n\t\t\t\t\t\tIP: net.ParseIP(\"203.0.113.1\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tBandwidth: []Bandwidth{\n\t\t\t\t\t{\n\t\t\t\t\t\tExperimental: true,\n\t\t\t\t\t\tType:         \"YZ\",\n\t\t\t\t\t\tBandwidth:    128,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tEncryptionKey: &(&struct{ x EncryptionKey }{\"prompt\"}).x,\n\t\t\t\tAttributes: []Attribute{\n\t\t\t\t\tAttribute(\"sendrecv\"),\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tMediaName: MediaName{\n\t\t\t\t\tMedia: \"video\",\n\t\t\t\t\tPort: RangedPort{\n\t\t\t\t\t\tValue: 51372,\n\t\t\t\t\t},\n\t\t\t\t\tProtos:  []string{\"RTP\", \"AVP\"},\n\t\t\t\t\tFormats: []int{99},\n\t\t\t\t},\n\t\t\t\tAttributes: []Attribute{\n\t\t\t\t\tAttribute(\"rtpmap:99 h263-1998\/90000\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tactual := sd.Marshal()\n\tif actual != CanonicalMarshalSDP {\n\t\tt.Errorf(\"error:\\n\\nEXPECTED:\\n%v\\nACTUAL:\\n%v\", CanonicalMarshalSDP, actual)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package api2go\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"gopkg.in\/guregu\/null.v2\/zero\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\ntype Magic struct {\n\tID MagicID\n}\n\ntype MagicID string\n\nfunc (m MagicID) String() string {\n\treturn \"This should be visible\"\n}\n\nvar _ = Describe(\"Marshalling\", func() {\n\ttype SimplePost struct {\n\t\tTitle, Text string\n\t}\n\n\ttype Comment struct {\n\t\tID   int\n\t\tText string\n\t}\n\n\ttype Author struct {\n\t\tID       int\n\t\tName     string\n\t\tPassword string `json:\"-\"`\n\t}\n\n\ttype Post struct {\n\t\tID          int\n\t\tTitle       string\n\t\tComments    []Comment\n\t\tCommentsIDs []int\n\t\tAuthor      *Author\n\t\tAuthorID    sql.NullInt64\n\t}\n\n\tContext(\"When marshaling simple objects\", func() {\n\t\tvar (\n\t\t\tfirstPost, secondPost       SimplePost\n\t\t\tfirstPostMap, secondPostMap map[string]interface{}\n\t\t)\n\n\t\tBeforeEach(func() {\n\t\t\tfirstPost = SimplePost{Title: \"First Post\", Text: \"Lipsum\"}\n\t\t\tfirstPostMap = map[string]interface{}{\n\t\t\t\t\"title\": firstPost.Title,\n\t\t\t\t\"text\":  firstPost.Text,\n\t\t\t}\n\t\t\tsecondPost = SimplePost{Title: \"Second Post\", Text: \"Getting more advanced!\"}\n\t\t\tsecondPostMap = map[string]interface{}{\n\t\t\t\t\"title\": secondPost.Title,\n\t\t\t\t\"text\":  secondPost.Text,\n\t\t\t}\n\t\t})\n\n\t\tIt(\"marshals single object\", func() {\n\t\t\ti, err := Marshal(firstPost)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"simplePosts\": []interface{}{\n\t\t\t\t\tfirstPostMap,\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"should prefer fmt.Stringer().String() over string contents\", func() {\n\t\t\tm := Magic{}\n\t\t\tm.ID = \"This should be only internal\"\n\n\t\t\texpected := map[string]interface{}{\n\t\t\t\t\"magics\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\": \"This should be visible\"}}}\n\n\t\t\tv, e := Marshal(m)\n\t\t\tExpect(e).ToNot(HaveOccurred())\n\t\t\tExpect(v).To(Equal(expected))\n\t\t})\n\n\t\tIt(\"marshal nil value\", func() {\n\t\t\t_, err := Marshal(nil)\n\t\t\tExpect(err).To(HaveOccurred())\n\t\t})\n\n\t\tIt(\"marshals collections object\", func() {\n\t\t\ti, err := Marshal([]SimplePost{firstPost, secondPost})\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"simplePosts\": []interface{}{\n\t\t\t\t\tfirstPostMap,\n\t\t\t\t\tsecondPostMap,\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"marshals empty collections\", func() {\n\t\t\ti, err := Marshal([]SimplePost{})\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"simplePosts\": []interface{}{},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"returns an error when passing interface{} slices\", func() {\n\t\t\t_, err := Marshal([]interface{}{})\n\t\t\tExpect(err).To(HaveOccurred())\n\t\t})\n\n\t\tIt(\"returns an error when passing an empty string\", func() {\n\t\t\t_, err := Marshal(\"\")\n\t\t\tExpect(err).To(HaveOccurred())\n\t\t})\n\n\t\tIt(\"marshals to JSON\", func() {\n\t\t\tj, err := MarshalToJSON([]SimplePost{firstPost})\n\t\t\tExpect(err).To(BeNil())\n\t\t\tvar m map[string]interface{}\n\t\t\tExpect(json.Unmarshal(j, &m)).To(BeNil())\n\t\t\tExpect(m).To(Equal(map[string]interface{}{\n\t\t\t\t\"simplePosts\": []interface{}{\n\t\t\t\t\tfirstPostMap,\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tContext(\"when converting IDs to string\", func() {\n\t\t\tIt(\"leaves string\", func() {\n\t\t\t\ttype StringID struct{ ID string }\n\t\t\t\ti, err := Marshal(StringID{ID: \"1\"})\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\t\"stringIDs\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t})\n\n\t\t\tIt(\"converts ints\", func() {\n\t\t\t\ttype IntID struct{ ID int }\n\t\t\t\ti, err := Marshal(IntID{ID: 1})\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\t\"intIDs\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t})\n\n\t\t\tIt(\"converts uints\", func() {\n\t\t\t\ttype UintID struct{ ID uint }\n\t\t\t\ti, err := Marshal(UintID{ID: 1})\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\t\"uintIDs\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t})\n\t\t})\n\t})\n\n\tContext(\"When marshaling compound objects\", func() {\n\t\tIt(\"marshals nested objects\", func() {\n\t\t\tcomment1 := Comment{ID: 1, Text: \"First!\"}\n\t\t\tcomment2 := Comment{ID: 2, Text: \"Second!\"}\n\t\t\tauthor := Author{ID: 1, Name: \"Test Author\"}\n\t\t\tpost1 := Post{ID: 1, Title: \"Foobar\", Comments: []Comment{comment1, comment2}, Author: &author}\n\t\t\tpost2 := Post{ID: 2, Title: \"Foobarbarbar\", Comments: []Comment{comment1, comment2}, Author: &author}\n\n\t\t\tposts := []Post{post1, post2}\n\n\t\t\ti, err := Marshal(posts)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"posts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":    \"1\",\n\t\t\t\t\t\t\"title\": \"Foobar\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"comments\": []interface{}{\"1\", \"2\"},\n\t\t\t\t\t\t\t\"author\":   \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":    \"2\",\n\t\t\t\t\t\t\"title\": \"Foobarbarbar\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"comments\": []interface{}{\"1\", \"2\"},\n\t\t\t\t\t\t\t\"author\":   \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"linked\": map[string][]interface{}{\n\t\t\t\t\t\"comments\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\":   \"1\",\n\t\t\t\t\t\t\t\"text\": \"First!\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\":   \"2\",\n\t\t\t\t\t\t\t\"text\": \"Second!\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"authors\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\":   \"1\",\n\t\t\t\t\t\t\t\"name\": \"Test Author\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"adds IDs\", func() {\n\t\t\tpost := Post{ID: 1, Comments: []Comment{}, CommentsIDs: []int{1}}\n\t\t\ti, err := Marshal(post)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"posts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":    \"1\",\n\t\t\t\t\t\t\"title\": \"\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"comments\": []interface{}{\"1\"},\n\t\t\t\t\t\t\t\"author\":   nil,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"prefers nested structs when given both, structs and IDs\", func() {\n\t\t\tcomment := Comment{ID: 1}\n\t\t\tauthor := Author{ID: 1, Name: \"Tester\"}\n\t\t\tpost := Post{ID: 1, Comments: []Comment{comment}, CommentsIDs: []int{2}, Author: &author, AuthorID: sql.NullInt64{Int64: 1337}}\n\t\t\ti, err := Marshal(post)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"posts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":    \"1\",\n\t\t\t\t\t\t\"title\": \"\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"comments\": []interface{}{\"1\"},\n\t\t\t\t\t\t\t\"author\":   \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"linked\": map[string][]interface{}{\n\t\t\t\t\t\"comments\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\":   \"1\",\n\t\t\t\t\t\t\t\"text\": \"\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"authors\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\":   \"1\",\n\t\t\t\t\t\t\t\"name\": \"Tester\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"uses ID field if single relation struct is nil\", func() {\n\t\t\ttype AnotherPost struct {\n\t\t\t\tID       int\n\t\t\t\tAuthorID int\n\t\t\t\tAuthor   *Author\n\t\t\t}\n\n\t\t\tanotherPost := AnotherPost{ID: 1, AuthorID: 1}\n\t\t\ti, err := Marshal(anotherPost)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"anotherPosts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\": \"1\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"author\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"uses ID field for the sql.NullInt64 type\", func() {\n\t\t\ttype SqlTypesPost struct {\n\t\t\t\tID       int\n\t\t\t\tAuthorID sql.NullInt64\n\t\t\t\tAuthor   *Author\n\t\t\t}\n\n\t\t\tanotherPost := SqlTypesPost{ID: 1, AuthorID: sql.NullInt64{1, true}}\n\t\t\ti, err := Marshal(anotherPost)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"sqlTypesPosts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\": \"1\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"author\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"uses ID field for the sql.NullString type\", func() {\n\t\t\ttype SqlTypesPost struct {\n\t\t\t\tID       int\n\t\t\t\tAuthorID sql.NullString\n\t\t\t\tAuthor   *Author\n\t\t\t}\n\n\t\t\tanotherPost := SqlTypesPost{ID: 1, AuthorID: sql.NullString{\"1\", true}}\n\t\t\ti, err := Marshal(anotherPost)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"sqlTypesPosts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\": \"1\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"author\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"returns an error if ID field but no struct field is in struct\", func() {\n\t\t\ttype WrongStruct struct {\n\t\t\t\tID       int\n\t\t\t\tAuthorID int\n\t\t\t}\n\n\t\t\twrongStruct := WrongStruct{ID: 1, AuthorID: 1}\n\t\t\t_, err := Marshal(wrongStruct)\n\t\t\tExpect(err).To(Equal(errors.New(\"expected struct to have field Author\")))\n\t\t})\n\t})\n\n\tContext(\"when marshalling zero value types\", func() {\n\t\ttype ZeroPost struct {\n\t\t\tID    string\n\t\t\tTitle string\n\t\t\tValue zero.Float\n\t\t}\n\n\t\ttype ZeroPostPointer struct {\n\t\t\tID    string\n\t\t\tTitle string\n\t\t\tValue *zero.Float\n\t\t}\n\n\t\ttheFloat := zero.NewFloat(2.3, true)\n\t\tpost := ZeroPost{ID: \"1\", Title: \"test\", Value: theFloat}\n\t\tpointerPost := ZeroPostPointer{ID: \"1\", Title: \"test\", Value: &theFloat}\n\n\t\tIt(\"correctly unmarshals driver values\", func() {\n\t\t\tpostMap := map[string]interface{}{\n\t\t\t\t\"zeroPosts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":    \"1\",\n\t\t\t\t\t\t\"title\": \"test\",\n\t\t\t\t\t\t\"value\": theFloat,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tmarshalled, err := Marshal(post)\n\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(marshalled).To(Equal(postMap))\n\t\t})\n\n\t\tIt(\"correctly unmarshals into json\", func() {\n\t\t\texpectedJSON := `{\"zeroPosts\":[{\"id\":\"1\",\"title\":\"test\",\"value\":2.3}]}`\n\n\t\t\tjson, err := MarshalToJSON(post)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(string(json)).To(Equal(expectedJSON))\n\t\t})\n\n\t\tIt(\"correctly unmarshals driver values with pointer\", func() {\n\t\t\tpostMap := map[string]interface{}{\n\t\t\t\t\"zeroPostPointers\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":    \"1\",\n\t\t\t\t\t\t\"title\": \"test\",\n\t\t\t\t\t\t\"value\": &theFloat,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tmarshalled, err := Marshal(pointerPost)\n\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(marshalled).To(BeEquivalentTo(postMap))\n\t\t})\n\n\t\tIt(\"correctly unmarshals with pointer into json\", func() {\n\t\t\texpectedJSON := `{\"zeroPostPointers\":[{\"id\":\"1\",\"title\":\"test\",\"value\":2.3}]}`\n\n\t\t\tjson, err := MarshalToJSON(pointerPost)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(string(json)).To(Equal(expectedJSON))\n\t\t})\n\t})\n\n\tContext(\"When marshalling objects linking to other instances of the same type\", func() {\n\t\ttype Question struct {\n\t\t\tID                  string\n\t\t\tText                string\n\t\t\tInspiringQuestionID sql.NullString\n\t\t\tInspiringQuestion   *Question\n\t\t}\n\n\t\tquestion1 := Question{ID: \"1\", Text: \"Does this test work?\"}\n\t\tquestion2 := Question{ID: \"2\", Text: \"Will it ever work?\", InspiringQuestionID: sql.NullString{\"1\", true}, InspiringQuestion: &question1}\n\n\t\tIt(\"Correctly marshalls question1 and sets question 2 into linked\", func() {\n\t\t\texpected := map[string]interface{}{\n\t\t\t\t\"questions\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":   \"2\",\n\t\t\t\t\t\t\"text\": \"Will it ever work?\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"inspiringQuestion\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"linked\": map[string][]interface{}{\n\t\t\t\t\t\"questions\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\":   \"1\",\n\t\t\t\t\t\t\t\"text\": \"Does this test work?\",\n\t\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\t\"inspiringQuestion\": nil,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tmarshalled, err := Marshal(question2)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(marshalled).To(BeEquivalentTo(expected))\n\t\t})\n\t})\n})\n<commit_msg>test if duplicate linked structs are marshalled once<commit_after>package api2go\n\nimport (\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"gopkg.in\/guregu\/null.v2\/zero\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\ntype Magic struct {\n\tID MagicID\n}\n\ntype MagicID string\n\nfunc (m MagicID) String() string {\n\treturn \"This should be visible\"\n}\n\nvar _ = Describe(\"Marshalling\", func() {\n\ttype SimplePost struct {\n\t\tTitle, Text string\n\t}\n\n\ttype Comment struct {\n\t\tID   int\n\t\tText string\n\t}\n\n\ttype Author struct {\n\t\tID       int\n\t\tName     string\n\t\tPassword string `json:\"-\"`\n\t}\n\n\ttype Post struct {\n\t\tID          int\n\t\tTitle       string\n\t\tComments    []Comment\n\t\tCommentsIDs []int\n\t\tAuthor      *Author\n\t\tAuthorID    sql.NullInt64\n\t}\n\n\tContext(\"When marshaling simple objects\", func() {\n\t\tvar (\n\t\t\tfirstPost, secondPost       SimplePost\n\t\t\tfirstPostMap, secondPostMap map[string]interface{}\n\t\t)\n\n\t\tBeforeEach(func() {\n\t\t\tfirstPost = SimplePost{Title: \"First Post\", Text: \"Lipsum\"}\n\t\t\tfirstPostMap = map[string]interface{}{\n\t\t\t\t\"title\": firstPost.Title,\n\t\t\t\t\"text\":  firstPost.Text,\n\t\t\t}\n\t\t\tsecondPost = SimplePost{Title: \"Second Post\", Text: \"Getting more advanced!\"}\n\t\t\tsecondPostMap = map[string]interface{}{\n\t\t\t\t\"title\": secondPost.Title,\n\t\t\t\t\"text\":  secondPost.Text,\n\t\t\t}\n\t\t})\n\n\t\tIt(\"marshals single object\", func() {\n\t\t\ti, err := Marshal(firstPost)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"simplePosts\": []interface{}{\n\t\t\t\t\tfirstPostMap,\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"should prefer fmt.Stringer().String() over string contents\", func() {\n\t\t\tm := Magic{}\n\t\t\tm.ID = \"This should be only internal\"\n\n\t\t\texpected := map[string]interface{}{\n\t\t\t\t\"magics\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\": \"This should be visible\"}}}\n\n\t\t\tv, e := Marshal(m)\n\t\t\tExpect(e).ToNot(HaveOccurred())\n\t\t\tExpect(v).To(Equal(expected))\n\t\t})\n\n\t\tIt(\"marshal nil value\", func() {\n\t\t\t_, err := Marshal(nil)\n\t\t\tExpect(err).To(HaveOccurred())\n\t\t})\n\n\t\tIt(\"marshals collections object\", func() {\n\t\t\ti, err := Marshal([]SimplePost{firstPost, secondPost})\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"simplePosts\": []interface{}{\n\t\t\t\t\tfirstPostMap,\n\t\t\t\t\tsecondPostMap,\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"marshals empty collections\", func() {\n\t\t\ti, err := Marshal([]SimplePost{})\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"simplePosts\": []interface{}{},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"returns an error when passing interface{} slices\", func() {\n\t\t\t_, err := Marshal([]interface{}{})\n\t\t\tExpect(err).To(HaveOccurred())\n\t\t})\n\n\t\tIt(\"returns an error when passing an empty string\", func() {\n\t\t\t_, err := Marshal(\"\")\n\t\t\tExpect(err).To(HaveOccurred())\n\t\t})\n\n\t\tIt(\"marshals to JSON\", func() {\n\t\t\tj, err := MarshalToJSON([]SimplePost{firstPost})\n\t\t\tExpect(err).To(BeNil())\n\t\t\tvar m map[string]interface{}\n\t\t\tExpect(json.Unmarshal(j, &m)).To(BeNil())\n\t\t\tExpect(m).To(Equal(map[string]interface{}{\n\t\t\t\t\"simplePosts\": []interface{}{\n\t\t\t\t\tfirstPostMap,\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tContext(\"when converting IDs to string\", func() {\n\t\t\tIt(\"leaves string\", func() {\n\t\t\t\ttype StringID struct{ ID string }\n\t\t\t\ti, err := Marshal(StringID{ID: \"1\"})\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\t\"stringIDs\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t})\n\n\t\t\tIt(\"converts ints\", func() {\n\t\t\t\ttype IntID struct{ ID int }\n\t\t\t\ti, err := Marshal(IntID{ID: 1})\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\t\"intIDs\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t})\n\n\t\t\tIt(\"converts uints\", func() {\n\t\t\t\ttype UintID struct{ ID uint }\n\t\t\t\ti, err := Marshal(UintID{ID: 1})\n\t\t\t\tExpect(err).To(BeNil())\n\t\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\t\"uintIDs\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t})\n\t\t})\n\t})\n\n\tContext(\"When marshaling compound objects\", func() {\n\t\tIt(\"marshals nested objects\", func() {\n\t\t\tcomment1 := Comment{ID: 1, Text: \"First!\"}\n\t\t\tcomment2 := Comment{ID: 2, Text: \"Second!\"}\n\t\t\tauthor := Author{ID: 1, Name: \"Test Author\"}\n\t\t\tpost1 := Post{ID: 1, Title: \"Foobar\", Comments: []Comment{comment1, comment2}, Author: &author}\n\t\t\tpost2 := Post{ID: 2, Title: \"Foobarbarbar\", Comments: []Comment{comment1, comment2}, Author: &author}\n\n\t\t\tposts := []Post{post1, post2}\n\n\t\t\ti, err := Marshal(posts)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"posts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":    \"1\",\n\t\t\t\t\t\t\"title\": \"Foobar\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"comments\": []interface{}{\"1\", \"2\"},\n\t\t\t\t\t\t\t\"author\":   \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":    \"2\",\n\t\t\t\t\t\t\"title\": \"Foobarbarbar\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"comments\": []interface{}{\"1\", \"2\"},\n\t\t\t\t\t\t\t\"author\":   \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"linked\": map[string][]interface{}{\n\t\t\t\t\t\"comments\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\":   \"1\",\n\t\t\t\t\t\t\t\"text\": \"First!\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\":   \"2\",\n\t\t\t\t\t\t\t\"text\": \"Second!\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"authors\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\":   \"1\",\n\t\t\t\t\t\t\t\"name\": \"Test Author\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"adds IDs\", func() {\n\t\t\tpost := Post{ID: 1, Comments: []Comment{}, CommentsIDs: []int{1}}\n\t\t\ti, err := Marshal(post)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"posts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":    \"1\",\n\t\t\t\t\t\t\"title\": \"\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"comments\": []interface{}{\"1\"},\n\t\t\t\t\t\t\t\"author\":   nil,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"prefers nested structs when given both, structs and IDs\", func() {\n\t\t\tcomment := Comment{ID: 1}\n\t\t\tauthor := Author{ID: 1, Name: \"Tester\"}\n\t\t\tpost := Post{ID: 1, Comments: []Comment{comment}, CommentsIDs: []int{2}, Author: &author, AuthorID: sql.NullInt64{Int64: 1337}}\n\t\t\ti, err := Marshal(post)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"posts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":    \"1\",\n\t\t\t\t\t\t\"title\": \"\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"comments\": []interface{}{\"1\"},\n\t\t\t\t\t\t\t\"author\":   \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"linked\": map[string][]interface{}{\n\t\t\t\t\t\"comments\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\":   \"1\",\n\t\t\t\t\t\t\t\"text\": \"\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"authors\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\":   \"1\",\n\t\t\t\t\t\t\t\"name\": \"Tester\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"uses ID field if single relation struct is nil\", func() {\n\t\t\ttype AnotherPost struct {\n\t\t\t\tID       int\n\t\t\t\tAuthorID int\n\t\t\t\tAuthor   *Author\n\t\t\t}\n\n\t\t\tanotherPost := AnotherPost{ID: 1, AuthorID: 1}\n\t\t\ti, err := Marshal(anotherPost)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"anotherPosts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\": \"1\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"author\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"uses ID field for the sql.NullInt64 type\", func() {\n\t\t\ttype SqlTypesPost struct {\n\t\t\t\tID       int\n\t\t\t\tAuthorID sql.NullInt64\n\t\t\t\tAuthor   *Author\n\t\t\t}\n\n\t\t\tanotherPost := SqlTypesPost{ID: 1, AuthorID: sql.NullInt64{1, true}}\n\t\t\ti, err := Marshal(anotherPost)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"sqlTypesPosts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\": \"1\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"author\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"uses ID field for the sql.NullString type\", func() {\n\t\t\ttype SqlTypesPost struct {\n\t\t\t\tID       int\n\t\t\t\tAuthorID sql.NullString\n\t\t\t\tAuthor   *Author\n\t\t\t}\n\n\t\t\tanotherPost := SqlTypesPost{ID: 1, AuthorID: sql.NullString{\"1\", true}}\n\t\t\ti, err := Marshal(anotherPost)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(i).To(Equal(map[string]interface{}{\n\t\t\t\t\"sqlTypesPosts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\": \"1\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"author\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}))\n\t\t})\n\n\t\tIt(\"returns an error if ID field but no struct field is in struct\", func() {\n\t\t\ttype WrongStruct struct {\n\t\t\t\tID       int\n\t\t\t\tAuthorID int\n\t\t\t}\n\n\t\t\twrongStruct := WrongStruct{ID: 1, AuthorID: 1}\n\t\t\t_, err := Marshal(wrongStruct)\n\t\t\tExpect(err).To(Equal(errors.New(\"expected struct to have field Author\")))\n\t\t})\n\t})\n\n\tContext(\"when marshalling zero value types\", func() {\n\t\ttype ZeroPost struct {\n\t\t\tID    string\n\t\t\tTitle string\n\t\t\tValue zero.Float\n\t\t}\n\n\t\ttype ZeroPostPointer struct {\n\t\t\tID    string\n\t\t\tTitle string\n\t\t\tValue *zero.Float\n\t\t}\n\n\t\ttheFloat := zero.NewFloat(2.3, true)\n\t\tpost := ZeroPost{ID: \"1\", Title: \"test\", Value: theFloat}\n\t\tpointerPost := ZeroPostPointer{ID: \"1\", Title: \"test\", Value: &theFloat}\n\n\t\tIt(\"correctly unmarshals driver values\", func() {\n\t\t\tpostMap := map[string]interface{}{\n\t\t\t\t\"zeroPosts\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":    \"1\",\n\t\t\t\t\t\t\"title\": \"test\",\n\t\t\t\t\t\t\"value\": theFloat,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tmarshalled, err := Marshal(post)\n\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(marshalled).To(Equal(postMap))\n\t\t})\n\n\t\tIt(\"correctly unmarshals into json\", func() {\n\t\t\texpectedJSON := `{\"zeroPosts\":[{\"id\":\"1\",\"title\":\"test\",\"value\":2.3}]}`\n\n\t\t\tjson, err := MarshalToJSON(post)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(string(json)).To(Equal(expectedJSON))\n\t\t})\n\n\t\tIt(\"correctly unmarshals driver values with pointer\", func() {\n\t\t\tpostMap := map[string]interface{}{\n\t\t\t\t\"zeroPostPointers\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":    \"1\",\n\t\t\t\t\t\t\"title\": \"test\",\n\t\t\t\t\t\t\"value\": &theFloat,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tmarshalled, err := Marshal(pointerPost)\n\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(marshalled).To(BeEquivalentTo(postMap))\n\t\t})\n\n\t\tIt(\"correctly unmarshals with pointer into json\", func() {\n\t\t\texpectedJSON := `{\"zeroPostPointers\":[{\"id\":\"1\",\"title\":\"test\",\"value\":2.3}]}`\n\n\t\t\tjson, err := MarshalToJSON(pointerPost)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(string(json)).To(Equal(expectedJSON))\n\t\t})\n\t})\n\n\tContext(\"When marshalling objects linking to other instances of the same type\", func() {\n\t\ttype Question struct {\n\t\t\tID                  string\n\t\t\tText                string\n\t\t\tInspiringQuestionID sql.NullString\n\t\t\tInspiringQuestion   *Question\n\t\t}\n\n\t\tquestion1 := Question{ID: \"1\", Text: \"Does this test work?\"}\n\t\tquestion1Duplicate := Question{ID: \"1\", Text: \"Does this test work?\"}\n\t\tquestion2 := Question{ID: \"2\", Text: \"Will it ever work?\", InspiringQuestionID: sql.NullString{\"1\", true}, InspiringQuestion: &question1}\n\t\tquestion3 := Question{ID: \"3\", Text: \"It works now\", InspiringQuestionID: sql.NullString{\"1\", true}, InspiringQuestion: &question1Duplicate}\n\n\t\tIt(\"Correctly marshalls question1 and sets question 2 into linked\", func() {\n\t\t\texpected := map[string]interface{}{\n\t\t\t\t\"questions\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":   \"2\",\n\t\t\t\t\t\t\"text\": \"Will it ever work?\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"inspiringQuestion\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"linked\": map[string][]interface{}{\n\t\t\t\t\t\"questions\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\":   \"1\",\n\t\t\t\t\t\t\t\"text\": \"Does this test work?\",\n\t\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\t\"inspiringQuestion\": nil,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tmarshalled, err := Marshal(question2)\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(marshalled).To(BeEquivalentTo(expected))\n\t\t})\n\n\t\tIt(\"Does not marshall same dependencies multiple times\", func() {\n\t\t\texpected := map[string]interface{}{\n\t\t\t\t\"questions\": []interface{}{\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":   \"3\",\n\t\t\t\t\t\t\"text\": \"It works now\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"inspiringQuestion\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"id\":   \"2\",\n\t\t\t\t\t\t\"text\": \"Will it ever work?\",\n\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\"inspiringQuestion\": \"1\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"linked\": map[string][]interface{}{\n\t\t\t\t\t\"questions\": []interface{}{\n\t\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\t\"id\":   \"1\",\n\t\t\t\t\t\t\t\"text\": \"Does this test work?\",\n\t\t\t\t\t\t\t\"links\": map[string]interface{}{\n\t\t\t\t\t\t\t\t\"inspiringQuestion\": nil,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tmarshalled, err := Marshal([]Question{question3, question2})\n\t\t\tExpect(err).To(BeNil())\n\t\t\tExpect(marshalled).To(BeEquivalentTo(expected))\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package forms\n\nimport (\n\t\"github.com\/kirves\/revel-forms\/fields\"\n\t\"html\/template\"\n\t\"reflect\"\n\t\"strings\"\n)\n\nconst (\n\tPOST = \"POST\"\n\tGET  = \"GET\"\n)\n\ntype Form struct {\n\tfields   []fields.FieldInterface\n\tfieldMap map[string]int\n\tstyle    string\n\ttemplate *template.Template\n\tclass    []string\n\tid       string\n\tparams   map[string]string\n\tcss      map[string]string\n\tmethod   string\n\taction   string\n}\n\nfunc BaseForm(method, action string) *Form {\n\ttmpl, err := template.ParseFiles(\"templates\/baseform.html\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &Form{\n\t\tmake([]fields.FieldInterface, 0),\n\t\tmake(map[string]int),\n\t\tfields.BASE,\n\t\ttmpl,\n\t\t[]string{},\n\t\t\"\",\n\t\tmap[string]string{},\n\t\tmap[string]string{},\n\t\tmethod,\n\t\taction,\n\t}\n}\n\nfunc BootstrapForm(method, action string) *Form {\n\ttmpl, err := template.ParseFiles(\"templates\/bootstrapform.html\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &Form{\n\t\tmake([]fields.FieldInterface, 0),\n\t\tmake(map[string]int),\n\t\tfields.BOOTSTRAP,\n\t\ttmpl,\n\t\t[]string{},\n\t\t\"\",\n\t\tmap[string]string{},\n\t\tmap[string]string{},\n\t\tmethod,\n\t\taction,\n\t}\n}\n\nfunc BaseFormFromModel(m interface{}, method, action string) *Form {\n\tform := BaseForm(method, action)\n\tfor _, v := range unWindStructure(m, \"\") {\n\t\tform.AddField(v)\n\t}\n\tform.AddField(fields.SubmitButton(\"submit\", \"Submit\"))\n\treturn form\n}\n\nfunc unWindStructure(m interface{}, baseName string) []fields.FieldInterface {\n\tt := reflect.TypeOf(m)\n\tfieldList := make([]fields.FieldInterface, 0)\n\tfor i := 0; i < t.NumField(); i++ {\n\t\ttag := t.Field(i).Tag.Get(\"form_skip\")\n\t\tif tag == \"\" {\n\t\t\ttag = t.Field(i).Tag.Get(\"form_widget\")\n\t\t\tvar f fields.FieldInterface\n\t\t\tvar fName string\n\t\t\tif baseName == \"\" {\n\t\t\t\tfName = t.Field(i).Name\n\t\t\t} else {\n\t\t\t\tfName = strings.Join([]string{baseName, t.Field(i).Name}, \".\")\n\t\t\t}\n\t\t\tswitch tag {\n\t\t\tcase \"text\":\n\t\t\t\tf = fields.TextField(fName)\n\t\t\tcase \"textarea\":\n\t\t\t\tf = fields.TextAreaField(fName, 30, 50)\n\t\t\tcase \"password\":\n\t\t\t\tf = fields.PasswordField(fName)\n\t\t\tcase \"date\":\n\t\t\tcase \"datetime\":\n\t\t\tcase \"time\":\n\t\t\tcase \"number\":\n\t\t\tcase \"range\":\n\t\t\tdefault:\n\t\t\t\tswitch t.Field(i).Type.String() {\n\t\t\t\tcase \"string\":\n\t\t\t\t\tf = fields.TextField(fName)\n\t\t\t\tcase \"bool\":\n\t\t\t\t\tf = fields.Checkbox(fName, false)\n\t\t\t\tcase \"time.Time\":\n\t\t\t\t\tf = fields.TextField(fName) \/\/ FIX\n\t\t\t\tcase \"int\":\n\t\t\t\t\tf = fields.TextField(fName) \/\/ FIX\n\t\t\t\tcase \"struct\":\n\t\t\t\t\tfieldList = append(fieldList, unWindStructure(reflect.New(t.Field(i).Type).Elem().Interface(), fName)...)\n\t\t\t\t\tf = nil\n\t\t\t\tdefault:\n\t\t\t\t\tf = fields.TextField(fName)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif f != nil {\n\t\t\t\tf.SetLabel(strings.Title(t.Field(i).Name))\n\t\t\t\tfieldList = append(fieldList, f)\n\t\t\t}\n\t\t}\n\t}\n\treturn fieldList\n}\n<commit_msg>Bool and select defaults<commit_after>package forms\n\nimport (\n\t\"github.com\/kirves\/revel-forms\/fields\"\n\t\"html\/template\"\n\t\"reflect\"\n\t\"strings\"\n)\n\nconst (\n\tPOST = \"POST\"\n\tGET  = \"GET\"\n)\n\ntype Form struct {\n\tfields   []fields.FieldInterface\n\tfieldMap map[string]int\n\tstyle    string\n\ttemplate *template.Template\n\tclass    []string\n\tid       string\n\tparams   map[string]string\n\tcss      map[string]string\n\tmethod   string\n\taction   string\n}\n\nfunc BaseForm(method, action string) *Form {\n\ttmpl, err := template.ParseFiles(\"templates\/baseform.html\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &Form{\n\t\tmake([]fields.FieldInterface, 0),\n\t\tmake(map[string]int),\n\t\tfields.BASE,\n\t\ttmpl,\n\t\t[]string{},\n\t\t\"\",\n\t\tmap[string]string{},\n\t\tmap[string]string{},\n\t\tmethod,\n\t\taction,\n\t}\n}\n\nfunc BootstrapForm(method, action string) *Form {\n\ttmpl, err := template.ParseFiles(\"templates\/bootstrapform.html\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &Form{\n\t\tmake([]fields.FieldInterface, 0),\n\t\tmake(map[string]int),\n\t\tfields.BOOTSTRAP,\n\t\ttmpl,\n\t\t[]string{},\n\t\t\"\",\n\t\tmap[string]string{},\n\t\tmap[string]string{},\n\t\tmethod,\n\t\taction,\n\t}\n}\n\nfunc BaseFormFromModel(m interface{}, method, action string) *Form {\n\tform := BaseForm(method, action)\n\tfor _, v := range unWindStructure(m, \"\") {\n\t\tform.AddField(v)\n\t}\n\tform.AddField(fields.SubmitButton(\"submit\", \"Submit\"))\n\treturn form\n}\n\nfunc unWindStructure(m interface{}, baseName string) []fields.FieldInterface {\n\tt := reflect.TypeOf(m)\n\tfieldList := make([]fields.FieldInterface, 0)\n\tfor i := 0; i < t.NumField(); i++ {\n\t\ttag := t.Field(i).Tag.Get(\"form_skip\")\n\t\tif tag == \"\" {\n\t\t\ttag = t.Field(i).Tag.Get(\"form_widget\")\n\t\t\tvar f fields.FieldInterface\n\t\t\tvar fName string\n\t\t\tif baseName == \"\" {\n\t\t\t\tfName = t.Field(i).Name\n\t\t\t} else {\n\t\t\t\tfName = strings.Join([]string{baseName, t.Field(i).Name}, \".\")\n\t\t\t}\n\t\t\tswitch tag {\n\t\t\tcase \"text\":\n\t\t\t\tf = fields.TextField(fName)\n\t\t\tcase \"textarea\":\n\t\t\t\tf = fields.TextAreaField(fName, 30, 50)\n\t\t\tcase \"password\":\n\t\t\t\tf = fields.PasswordField(fName)\n\t\t\tcase \"select\":\n\t\t\t\tchoices := strings.Split(t.Field(i).Tag.Get(\"form_choices\"), \"|\")\n\t\t\t\tif len(choices)%2 != 0 {\n\t\t\t\t\tf = nil\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tchMap := make(map[string]string)\n\t\t\t\tfor i := 0; i < len(choices)-1; i += 2 {\n\t\t\t\t\tchMap[choices[i]] = choices[i+1]\n\t\t\t\t}\n\t\t\t\tf = fields.SelectField(fName, chMap)\n\t\t\tcase \"date\":\n\t\t\tcase \"datetime\":\n\t\t\tcase \"time\":\n\t\t\tcase \"number\":\n\t\t\tcase \"range\":\n\t\t\tdefault:\n\t\t\t\tswitch t.Field(i).Type.String() {\n\t\t\t\tcase \"string\":\n\t\t\t\t\tf = fields.TextField(fName)\n\t\t\t\tcase \"bool\":\n\t\t\t\t\tinitVal := t.Field(i).Tag.Get(\"form_checked\")\n\t\t\t\t\tif initVal != \"\" {\n\t\t\t\t\t\tf = fields.Checkbox(fName, true)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tf = fields.Checkbox(fName, false)\n\t\t\t\t\t}\n\t\t\t\tcase \"time.Time\":\n\t\t\t\t\tf = fields.TextField(fName) \/\/ FIX\n\t\t\t\tcase \"int\":\n\t\t\t\t\tf = fields.TextField(fName) \/\/ FIX\n\t\t\t\tcase \"struct\":\n\t\t\t\t\tfieldList = append(fieldList, unWindStructure(reflect.New(t.Field(i).Type).Elem().Interface(), fName)...)\n\t\t\t\t\tf = nil\n\t\t\t\tdefault:\n\t\t\t\t\tf = fields.TextField(fName)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif f != nil {\n\t\t\t\tf.SetLabel(strings.Title(t.Field(i).Name))\n\t\t\t\tfieldList = append(fieldList, f)\n\t\t\t}\n\t\t}\n\t}\n\treturn fieldList\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"database\/sql\"\n\t_ \"github.com\/lib\/pq\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc dbConnect(retriesLeft int) error {\n\tcon := os.Getenv(\"POSTGRES\")\n\tlogger.Infof(\"opening connection to postgres: %s\", con)\n\n\tvar err error\n\tdb, err = sql.Open(\"postgres\", con)\n\tif err != nil {\n\t\tlogger.Errorf(\"cannot open connection to postgres: %v\", err)\n\t\treturn err\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\tif retriesLeft > 0 {\n\t\t\tlogger.Errorf(\"cannot talk to postgres, retrying in 10 seconds (%d attempts left): %v\", retriesLeft-1, err)\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t\treturn dbConnect(retriesLeft - 1)\n\t\t} else {\n\t\t\tlogger.Errorf(\"cannot talk to postgres, last attempt failed: %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tstatement := `\n\t\tCREATE TABLE IF NOT EXISTS migrations (\n\t\t\tfilename TEXT NOT NULL UNIQUE\n\t\t);\n\t`\n\t_, err = db.Exec(statement)\n\tif err != nil {\n\t\tlogger.Errorf(\"cannot create migrations table: %v\", err)\n\t\treturn err\n\t}\n\n\tmaxIdleConnections, err := strconv.Atoi(os.Getenv(\"MAX_IDLE_PG_CONNECTIONS\"))\n\tif err != nil {\n\t\tlogger.Warningf(\"cannot parse COMMENTO_MAX_IDLE_PG_CONNECTIONS: %v\", err)\n\t\tmaxIdleConnections = 50\n\t}\n\n\tdb.SetMaxIdleConns(maxIdleConnections)\n\n\treturn nil\n}\n<commit_msg>database_connect.go: redact password before log message<commit_after>package main\n\nimport (\n\t\"database\/sql\"\n\t\"net\/url\"\n\t_ \"github.com\/lib\/pq\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc dbConnect(retriesLeft int) error {\n\tcon := os.Getenv(\"POSTGRES\")\n\tu, err := url.Parse(con)\n\tif err != nil {\n\t\tlogger.Errorf(\"invalid postgres connection URI: %v\", err)\n\t\treturn err\n\t}\n\tu.User = url.UserPassword(u.User.Username(), \"redacted\")\n\tlogger.Infof(\"opening connection to postgres: %s\", u.String())\n\n\tdb, err = sql.Open(\"postgres\", con)\n\tif err != nil {\n\t\tlogger.Errorf(\"cannot open connection to postgres: %v\", err)\n\t\treturn err\n\t}\n\n\terr = db.Ping()\n\tif err != nil {\n\t\tif retriesLeft > 0 {\n\t\t\tlogger.Errorf(\"cannot talk to postgres, retrying in 10 seconds (%d attempts left): %v\", retriesLeft-1, err)\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t\treturn dbConnect(retriesLeft - 1)\n\t\t} else {\n\t\t\tlogger.Errorf(\"cannot talk to postgres, last attempt failed: %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tstatement := `\n\t\tCREATE TABLE IF NOT EXISTS migrations (\n\t\t\tfilename TEXT NOT NULL UNIQUE\n\t\t);\n\t`\n\t_, err = db.Exec(statement)\n\tif err != nil {\n\t\tlogger.Errorf(\"cannot create migrations table: %v\", err)\n\t\treturn err\n\t}\n\n\tmaxIdleConnections, err := strconv.Atoi(os.Getenv(\"MAX_IDLE_PG_CONNECTIONS\"))\n\tif err != nil {\n\t\tlogger.Warningf(\"cannot parse COMMENTO_MAX_IDLE_PG_CONNECTIONS: %v\", err)\n\t\tmaxIdleConnections = 50\n\t}\n\n\tdb.SetMaxIdleConns(maxIdleConnections)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/file is borrowed from github.com\/kelseyhightower\/confd\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fatih\/structs\"\n)\n\nfunc newFuncMap() map[string]interface{} {\n\tm := make(map[string]interface{})\n\tm[\"base\"] = path.Base\n\tm[\"split\"] = strings.Split\n\tm[\"json\"] = UnmarshalJsonObject\n\tm[\"jsonArray\"] = UnmarshalJsonArray\n\tm[\"dir\"] = path.Dir\n\tm[\"getenv\"] = os.Getenv\n\tm[\"join\"] = strings.Join\n\tm[\"atoi\"] = strconv.Atoi\n\tm[\"where\"] = where\n\tm[\"datetime\"] = time.Now\n\tm[\"toUpper\"] = strings.ToUpper\n\tm[\"toLower\"] = strings.ToLower\n\tm[\"contains\"] = strings.Contains\n\tm[\"replace\"] = strings.Replace\n\treturn m\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nfunc where(m []interface{}, sliceKey string, sliceVal interface{}) ([]interface{}, error) {\n\tret := make([]interface{}, 0)\n\tif m == nil {\n\t\treturn ret, errors.New(\"where: source is nil\")\n\t}\n\tif sliceKey == \"\" {\n\t\treturn ret, errors.New(\"where: key is nil\")\n\t}\n\tif sliceVal == nil {\n\t\treturn ret, errors.New(\"where: value is nil\")\n\t}\n\n\tfor _, str := range m {\n\t\tst := structs.New(str)\n\t\tfield := st.Field(sliceKey)\n\t\tif field.Value() == sliceVal {\n\t\t\tret = append(ret, str)\n\t\t}\n\t}\n\n\treturn ret, nil\n}\n\nfunc addFuncs(out, in map[string]interface{}) {\n\tfor name, fn := range in {\n\t\tout[name] = fn\n\t}\n}\n\nfunc UnmarshalJsonObject(data string) (map[string]interface{}, error) {\n\tvar ret map[string]interface{}\n\terr := json.Unmarshal([]byte(data), &ret)\n\treturn ret, err\n}\n\nfunc UnmarshalJsonArray(data string) ([]interface{}, error) {\n\tvar ret []interface{}\n\terr := json.Unmarshal([]byte(data), &ret)\n\treturn ret, err\n}\n<commit_msg>autopush@1446218643<commit_after>\/\/file is borrowed from github.com\/kelseyhightower\/confd\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"os\"\n\t\"path\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fatih\/structs\"\n)\n\nfunc newFuncMap() map[string]interface{} {\n\tm := make(map[string]interface{})\n\tm[\"base\"] = path.Base\n\tm[\"split\"] = strings.Split\n\tm[\"json\"] = UnmarshalJsonObject\n\tm[\"jsonArray\"] = UnmarshalJsonArray\n\tm[\"dir\"] = path.Dir\n\tm[\"getenv\"] = os.Getenv\n\tm[\"join\"] = strings.Join\n\tm[\"atoi\"] = strconv.Atoi\n\tm[\"where\"] = where\n\tm[\"datetime\"] = time.Now\n\tm[\"toUpper\"] = strings.ToUpper\n\tm[\"toLower\"] = strings.ToLower\n\tm[\"contains\"] = strings.Contains\n\tm[\"replace\"] = strings.Replace\n\treturn m\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nfunc where(in interface{}, sliceKey string, sliceVal interface{}) ([]interface{}, error) {\n\tret := make([]interface{}, 0)\n\tif in == nil {\n\t\treturn ret, errors.New(\"where: source is nil\")\n\t}\n\tif sliceKey == \"\" {\n\t\treturn ret, errors.New(\"where: key is nil\")\n\t}\n\tif sliceVal == nil {\n\t\treturn ret, errors.New(\"where: value is nil\")\n\t}\n\n\tm := in.([]interface{})\n\n\tfor _, str := range m {\n\t\tst := structs.New(str)\n\t\tfield := st.Field(sliceKey)\n\t\tif field.Value() == sliceVal {\n\t\t\tret = append(ret, str)\n\t\t}\n\t}\n\n\treturn ret, nil\n}\n\nfunc addFuncs(out, in map[string]interface{}) {\n\tfor name, fn := range in {\n\t\tout[name] = fn\n\t}\n}\n\nfunc UnmarshalJsonObject(data string) (map[string]interface{}, error) {\n\tvar ret map[string]interface{}\n\terr := json.Unmarshal([]byte(data), &ret)\n\treturn ret, err\n}\n\nfunc UnmarshalJsonArray(data string) ([]interface{}, error) {\n\tvar ret []interface{}\n\terr := json.Unmarshal([]byte(data), &ret)\n\treturn ret, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package glope\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n)\n\ntype Cluster struct {\n\tid           int\n\tn            int            \/\/Number of transactions\n\tw            int            \/\/Number of unique items\n\ts            int            \/\/Total number of items\n\tocc          map[string]int \/\/Item to item count map\n\tTransactions []*Transaction\n}\n\ntype Transaction struct {\n\tcluster         *Cluster\n\tclusterPosition int \/\/Position of transaction inside cluster\n\tInstance        interface{}\n\tItems           []string\n}\n\n\/\/Calculate a profit using this formula: number of items\/(number of unique items ** repulsion)\nfunc getProfit(s, w int, r float64) float64 {\n\treturn float64(s) \/ math.Pow(float64(w), r)\n}\n\nfunc newCluster(id int, trans *Transaction) *Cluster {\n\titems_len := len(trans.Items)\n\tc := &Cluster{\n\t\tid:           id,\n\t\tocc:          make(map[string]int, items_len),\n\t\ts:            items_len,\n\t\tw:            items_len,\n\t\tn:            1,\n\t\tTransactions: []*Transaction{trans},\n\t}\n\tfor _, item := range trans.Items {\n\t\tc.occ[item] = 1\n\t}\n\ttrans.cluster = c\n\treturn c\n}\n\nfunc (c *Cluster) String() string {\n\treturn fmt.Sprintf(\"[Cluster %d]\", c.id)\n}\n\n\/\/Calculates a profit of adding transaction items to given cluster\nfunc (c *Cluster) getItemsProfit(items []string, r float64) float64 {\n\tif c.n == 0 {\n\t\ts := len(items)\n\t\treturn getProfit(s, s, r)\n\t} else {\n\t\tsNew := c.s + len(items)\n\t\twNew := c.w\n\t\tfor _, item := range items {\n\t\t\tif _, found := c.occ[item]; !found {\n\t\t\t\twNew++\n\t\t\t}\n\t\t}\n\t\treturn getProfit(sNew*(c.n+1), wNew, r) - getProfit(c.s*c.n, c.w, r)\n\t}\n}\n\nfunc (c *Cluster) addItem(item string) {\n\tval, found := c.occ[item]\n\tif !found {\n\t\tc.occ[item] = 1\n\t} else {\n\t\tc.occ[item] = val + 1\n\t}\n}\n\nfunc (c *Cluster) removeItem(item string) {\n\tval, found := c.occ[item]\n\tif !found {\n\t\treturn\n\t}\n\tif val == 1 {\n\t\tdelete(c.occ, item)\n\t}\n\tc.occ[item] -= 1\n}\n\nfunc (c *Cluster) addTransaction(trans *Transaction) {\n\tfor _, item := range trans.Items {\n\t\tc.addItem(item)\n\t}\n\tc.s += len(trans.Items)\n\tc.w = len(c.occ)\n\tc.n++\n\ttrans.clusterPosition = len(c.Transactions)\n\tc.Transactions = append(c.Transactions, trans)\n\ttrans.cluster = c\n}\n\nfunc (c *Cluster) removeTransaction(trans *Transaction) {\n\tfor _, item := range trans.Items {\n\t\tc.removeItem(item)\n\t}\n\tc.s -= len(trans.Items)\n\tc.w = len(c.occ)\n\tc.n--\n\tc.Transactions[trans.clusterPosition] = nil\n}\n\nfunc (c *Cluster) clearNilTransactions() {\n\tnonNilTransactions := make([]*Transaction, 0)\n\tfor _, transaction := range c.Transactions {\n\t\tif transaction != nil {\n\t\t\tnonNilTransactions = append(nonNilTransactions, transaction)\n\t\t}\n\t}\n\tc.Transactions = nonNilTransactions\n}\n\nfunc Clusterize(data []*Transaction, repulsion float64) []*Cluster {\n\tif repulsion == 0 {\n\t\trepulsion = 4.0 \/\/ default value\n\t}\n\tvar clusters []*Cluster\n\tlog.Print(\"Initializing clusters\")\n\tfor _, transaction := range data {\n\t\tclusters = addTransactionToBestCluster(clusters, transaction, repulsion)\n\t}\n\tlog.Printf(\"Init finished, created %d clusters\", len(clusters))\n\tlog.Print(\"Moving transactions to best clusters\")\n\tfor i := 1; ; i++ {\n\t\tlog.Printf(\"move %d\", i)\n\t\tmoved := false\n\t\tfor _, transaction := range data {\n\t\t\toriginalClusterId := transaction.cluster.id\n\t\t\ttransaction.cluster.removeTransaction(transaction)\n\t\t\tclusters = addTransactionToBestCluster(clusters, transaction, repulsion)\n\t\t\tif transaction.cluster.id != originalClusterId {\n\t\t\t\tmoved = true\n\t\t\t}\n\t\t}\n\t\tif !moved {\n\t\t\tbreak\n\t\t}\n\t}\n\tlog.Print(\"Finished, cleaning empty clusters\")\n\tnotEmptyClusters := make([]*Cluster, 0)\n\tfor _, cluster := range clusters {\n\t\tif cluster.n > 0 {\n\t\t\tcluster.clearNilTransactions()\n\t\t\tnotEmptyClusters = append(notEmptyClusters, cluster)\n\t\t}\n\t}\n\tlog.Printf(\"Cleaning finished, returning %d clusters\", len(notEmptyClusters))\n\treturn notEmptyClusters\n}\n\nfunc addTransactionToBestCluster(clusters []*Cluster, transaction *Transaction, repulsion float64) []*Cluster {\n\tif len(clusters) > 0 {\n\t\ttempS := len(transaction.Items)\n\t\tprofitMax := getProfit(tempS, tempS, repulsion)\n\n\t\tvar bestCluster *Cluster\n\t\tvar bestProfit float64\n\n\t\tfor _, cluster := range clusters {\n\t\t\tclusterProfit := cluster.getItemsProfit(transaction.Items, repulsion)\n\t\t\tif clusterProfit > bestProfit {\n\t\t\t\tif clusterProfit > profitMax {\n\t\t\t\t\tcluster.addTransaction(transaction)\n\t\t\t\t\treturn clusters\n\t\t\t\t} else {\n\t\t\t\t\tbestCluster = cluster\n\t\t\t\t\tbestProfit = clusterProfit\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif bestProfit >= profitMax {\n\t\t\tbestCluster.addTransaction(transaction)\n\t\t\treturn clusters\n\t\t}\n\t}\n\treturn append(clusters, newCluster(len(clusters), transaction))\n}\n<commit_msg>removed debug logging, added some docs<commit_after>package glope\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Cluster struct {\n\tid           int\n\tn            int            \/\/Number of transactions\n\tw            int            \/\/Number of unique items\n\ts            int            \/\/Total number of items\n\tocc          map[string]int \/\/Item to item count map\n\tTransactions []*Transaction\n}\n\ntype Transaction struct {\n\tcluster         *Cluster\n\tclusterPosition int \/\/Position of transaction inside cluster\n\tInstance        interface{}\n\tItems           []string\n}\n\n\/\/Calculate a profit using this formula: number of items\/(number of unique items ** repulsion)\nfunc getProfit(s, w int, r float64) float64 {\n\treturn float64(s) \/ math.Pow(float64(w), r)\n}\n\nfunc newCluster(id int, trans *Transaction) *Cluster {\n\titems_len := len(trans.Items)\n\tc := &Cluster{\n\t\tid:           id,\n\t\tocc:          make(map[string]int, items_len),\n\t\ts:            items_len,\n\t\tw:            items_len,\n\t\tn:            1,\n\t\tTransactions: []*Transaction{trans},\n\t}\n\tfor _, item := range trans.Items {\n\t\tc.occ[item] = 1\n\t}\n\ttrans.cluster = c\n\treturn c\n}\n\nfunc (c *Cluster) String() string {\n\treturn fmt.Sprintf(\"[Cluster %d]\", c.id)\n}\n\n\/\/Calculates a profit of adding transaction items to given cluster\nfunc (c *Cluster) getItemsProfit(items []string, r float64) float64 {\n\tif c.n == 0 {\n\t\ts := len(items)\n\t\treturn getProfit(s, s, r)\n\t} else {\n\t\tsNew := c.s + len(items)\n\t\twNew := c.w\n\t\tfor _, item := range items {\n\t\t\tif _, found := c.occ[item]; !found {\n\t\t\t\twNew++\n\t\t\t}\n\t\t}\n\t\treturn getProfit(sNew*(c.n+1), wNew, r) - getProfit(c.s*c.n, c.w, r)\n\t}\n}\n\n\/\/Adds an item of a transaction to the cluster\nfunc (c *Cluster) addItem(item string) {\n\tval, found := c.occ[item]\n\tif !found {\n\t\tc.occ[item] = 1\n\t} else {\n\t\tc.occ[item] = val + 1\n\t}\n}\n\n\/\/Removes an item of a transaction from the cluster\nfunc (c *Cluster) removeItem(item string) {\n\tval, found := c.occ[item]\n\tif !found {\n\t\treturn\n\t}\n\tif val == 1 {\n\t\tdelete(c.occ, item)\n\t}\n\tc.occ[item] -= 1\n}\n\nfunc (c *Cluster) addTransaction(trans *Transaction) {\n\tfor _, item := range trans.Items {\n\t\tc.addItem(item)\n\t}\n\tc.s += len(trans.Items)\n\tc.w = len(c.occ)\n\tc.n++\n\ttrans.clusterPosition = len(c.Transactions)\n\tc.Transactions = append(c.Transactions, trans)\n\ttrans.cluster = c\n}\n\nfunc (c *Cluster) removeTransaction(trans *Transaction) {\n\tfor _, item := range trans.Items {\n\t\tc.removeItem(item)\n\t}\n\tc.s -= len(trans.Items)\n\tc.w = len(c.occ)\n\tc.n--\n\tc.Transactions[trans.clusterPosition] = nil\n}\n\nfunc (c *Cluster) clearNilTransactions() {\n\tnonNilTransactions := make([]*Transaction, 0)\n\tfor _, transaction := range c.Transactions {\n\t\tif transaction != nil {\n\t\t\tnonNilTransactions = append(nonNilTransactions, transaction)\n\t\t}\n\t}\n\tc.Transactions = nonNilTransactions\n}\n\n\/\/Clusterizes given transactions\nfunc Clusterize(data []*Transaction, repulsion float64) []*Cluster {\n\tif repulsion == 0 {\n\t\trepulsion = 4.0 \/\/ default value\n\t}\n\tvar clusters []*Cluster\n\tfor _, transaction := range data {\n\t\tclusters = addTransactionToBestCluster(clusters, transaction, repulsion)\n\t}\n\tfor {\n\t\tmoved := false\n\t\tfor _, transaction := range data {\n\t\t\toriginalClusterId := transaction.cluster.id\n\t\t\ttransaction.cluster.removeTransaction(transaction)\n\t\t\tclusters = addTransactionToBestCluster(clusters, transaction, repulsion)\n\t\t\tif transaction.cluster.id != originalClusterId {\n\t\t\t\tmoved = true\n\t\t\t}\n\t\t}\n\t\tif !moved {\n\t\t\tbreak\n\t\t}\n\t}\n\tnotEmptyClusters := make([]*Cluster, 0)\n\tfor _, cluster := range clusters {\n\t\tif cluster.n > 0 {\n\t\t\tcluster.clearNilTransactions()\n\t\t\tnotEmptyClusters = append(notEmptyClusters, cluster)\n\t\t}\n\t}\n\treturn notEmptyClusters\n}\n\nfunc addTransactionToBestCluster(clusters []*Cluster, transaction *Transaction, repulsion float64) []*Cluster {\n\tif len(clusters) > 0 {\n\t\ttempS := len(transaction.Items)\n\t\tprofitMax := getProfit(tempS, tempS, repulsion)\n\n\t\tvar bestCluster *Cluster\n\t\tvar bestProfit float64\n\n\t\tfor _, cluster := range clusters {\n\t\t\tclusterProfit := cluster.getItemsProfit(transaction.Items, repulsion)\n\t\t\tif clusterProfit > bestProfit {\n\t\t\t\tif clusterProfit > profitMax {\n\t\t\t\t\tcluster.addTransaction(transaction)\n\t\t\t\t\treturn clusters\n\t\t\t\t} else {\n\t\t\t\t\tbestCluster = cluster\n\t\t\t\t\tbestProfit = clusterProfit\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif bestProfit >= profitMax {\n\t\t\tbestCluster.addTransaction(transaction)\n\t\t\treturn clusters\n\t\t}\n\t}\n\treturn append(clusters, newCluster(len(clusters), transaction))\n}\n<|endoftext|>"}
{"text":"<commit_before>package godbg\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"regexp\"\n\t\"runtime\/debug\"\n\t\"strings\"\n)\n\n\/\/ http:\/\/stackoverflow.com\/a\/23554672\/6309 https:\/\/vividcortex.com\/blog\/2013\/12\/03\/go-idiom-package-and-object\/\n\/\/ you design a type with methods as usual, and then you also place matching functions at the package level itself.\n\/\/ These functions simply delegate to a default instance of the type that’s a private package-level variable, created in an init() function.\n\n\/\/ Pdbg allows to print debug message with indent and function name added\ntype Pdbg struct {\n\tbout   *bytes.Buffer\n\tberr   *bytes.Buffer\n\tsout   *bufio.Writer\n\tserr   *bufio.Writer\n\tbreaks []string\n}\n\n\/\/ Out returns a writer for normal messages.\n\/\/ By default, os.StdOut\nfunc Out() io.Writer {\n\treturn pdbg.Out()\n}\n\n\/\/ Out returns a writer for normal messages for a given pdbg instance.\n\/\/ By default, os.StdOut\nfunc (pdbg *Pdbg) Out() io.Writer {\n\tif pdbg.sout == nil {\n\t\treturn os.Stdout\n\t}\n\treturn pdbg.sout\n}\n\n\/\/ Err returns a writer for error messages.\n\/\/ By default, os.StdErr\nfunc Err() io.Writer {\n\treturn pdbg.Err()\n}\n\n\/\/ Err returns a writer for error messages for a given pdbg instance.\n\/\/ By default, os.StdErr\nfunc (pdbg *Pdbg) Err() io.Writer {\n\tif pdbg.serr == nil {\n\t\treturn os.Stderr\n\t}\n\treturn pdbg.serr\n}\n\n\/\/ global pdbg used for printing\nvar pdbg = NewPdbg()\n\n\/\/ Option set an option for a Pdbg\n\/\/ http:\/\/dave.cheney.net\/2014\/10\/17\/functional-options-for-friendly-apis\ntype Option func(*Pdbg)\n\n\/\/ SetBuffers is an option for replacing stdout and stderr by\n\/\/ bytes buffers (in a bufio.Writer).\n\/\/ If apdbg is nil, set for the global pdbg instance\nfunc SetBuffers(apdbg *Pdbg) {\n\tif apdbg == nil {\n\t\tapdbg = pdbg\n\t}\n\tapdbg.bout = bytes.NewBuffer(nil)\n\tapdbg.sout = bufio.NewWriter(apdbg.bout)\n\tapdbg.berr = bytes.NewBuffer(nil)\n\tapdbg.serr = bufio.NewWriter(apdbg.berr)\n}\n\n\/\/ NewPdbg creates a PDbg instance, with options\nfunc NewPdbg(options ...Option) *Pdbg {\n\tnewpdbg := &Pdbg{}\n\tfor _, option := range options {\n\t\toption(newpdbg)\n\t}\n\tnewpdbg.breaks = append(newpdbg.breaks, \"smartystreets\")\n\treturn newpdbg\n}\n\n\/\/ ResetIOs reset the out and err buffer of global pdbg instance\nfunc ResetIOs() {\n\tpdbg.ResetIOs()\n}\n\n\/\/ ResetIOs reset the out and err buffer\n\/\/ (unless they were the default stdout and stderr,\n\/\/ in which case it does nothing)\nfunc (pdbg *Pdbg) ResetIOs() {\n\tif pdbg.sout != nil {\n\t\tpdbg.bout = bytes.NewBuffer(nil)\n\t\tpdbg.sout.Reset(pdbg.bout)\n\t\tpdbg.berr = bytes.NewBuffer(nil)\n\t\tpdbg.serr.Reset(pdbg.berr)\n\t}\n}\n\n\/\/ OutString returns the string for out messages for the global pdbg instance.\n\/\/ It flushes the out buffer.\n\/\/ If out is set to os.Stdout, returns an empty string\nfunc OutString() string {\n\treturn pdbg.OutString()\n}\n\n\/\/ OutString returns the string for out messages for a given pdbg instance.\n\/\/ It flushes the out buffer.\n\/\/ If out is set to os.Stdout, returns an empty string\nfunc (pdbg *Pdbg) OutString() string {\n\tif pdbg.sout == nil {\n\t\treturn \"\"\n\t}\n\tpdbg.sout.Flush()\n\treturn pdbg.bout.String()\n}\n\n\/\/ ErrString returns the string for error messages for the global pdbg instance.\n\/\/ It flushes the err buffer.\n\/\/ If err is set to os.StdErr, returns an empty string\nfunc ErrString() string {\n\treturn pdbg.ErrString()\n}\n\n\/\/ ErrString returns the string for error messages for a given pdbg instance.\n\/\/ It flushes the err buffer.\n\/\/ If err is set to os.StdErr, returns an empty string\nfunc (pdbg *Pdbg) ErrString() string {\n\tif pdbg.serr == nil {\n\t\treturn \"\"\n\t}\n\tpdbg.serr.Flush()\n\treturn pdbg.berr.String()\n}\n\n\/\/ For instance: github.com\/VonC\/godbg\/_test\/_obj_test\/gogdb.go:174 (0x44711b)\nvar rxDbgLine, _ = regexp.Compile(`^.*\\.go:(\\d+)\\s`)\nvar rxDbgFnct, _ = regexp.Compile(`^\\s+(?:.*?\\(([^\\)]+)\\))?\\.?([^:]+)`)\n\nfunc pdbgInc(scanner *bufio.Scanner, dbgLine string) string {\n\tscanner.Scan()\n\tline := scanner.Text()\n\tmf := rxDbgFnct.FindSubmatchIndex([]byte(line))\n\t\/\/ fmt.Printf(\"lineF '%v', mf '%+v'\\n\", line, mf)\n\t\/*if len(mf) == 0 {\n\t\treturn \"\"\n\t}*\/\n\tdbgFnct := \"\"\n\tif mf[2] > -1 {\n\t\tdbgFnct = line[mf[2]:mf[3]]\n\t}\n\tif dbgFnct != \"\" {\n\t\tdbgFnct = dbgFnct + \".\"\n\t}\n\tdbgFnct = dbgFnct + line[mf[4]:mf[5]]\n\n\treturn dbgFnct + \":\" + dbgLine\n}\n\nfunc pdbgExcluded(dbg string) bool {\n\tif strings.Contains(dbg, \"ReadConfig:\") {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (pdbg *Pdbg) pdbgBreak(dbg string) bool {\n\tfor _, b := range pdbg.breaks {\n\t\tif strings.Contains(dbg, b) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Pdbgf uses global Pdbg variable for printing strings, with indent and function name\nfunc Pdbgf(format string, args ...interface{}) string {\n\treturn pdbg.Pdbgf(format, args...)\n}\n\n\/\/ Pdbgf uses custom Pdbg variable for printing strings, with indent and function name\nfunc (pdbg *Pdbg) Pdbgf(format string, args ...interface{}) string {\n\tmsg := fmt.Sprintf(format+\"\\n\", args...)\n\tmsg = strings.TrimSpace(msg)\n\tbstack := bytes.NewBuffer(debug.Stack())\n\t\/\/ fmt.Printf(\"%+v\\n\", bstack)\n\n\tscanner := bufio.NewScanner(bstack)\n\tpmsg := \"\"\n\tdepth := 0\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif strings.Contains(line, \"\/_obj_test\/\") {\n\t\t\tdepth = 1\n\t\t\tcontinue\n\t\t}\n\t\tif pdbg.pdbgBreak(line) {\n\t\t\tbreak\n\t\t}\n\t\tm := rxDbgLine.FindSubmatchIndex([]byte(line))\n\t\t\/\/ fmt.Printf(\"'%s' (%s) => '%+v'\\n\", line, rxDbgLine.String(), m)\n\t\t\/*if len(m) == 0 {\n\t\t\tcontinue\n\t\t}*\/\n\t\tif depth > 0 && depth < 4 {\n\t\t\tdbg := pdbgInc(scanner, line[m[2]:m[3]])\n\t\t\tif dbg == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif depth == 1 {\n\t\t\t\tif pdbgExcluded(dbg) {\n\t\t\t\t\treturn \"\"\n\t\t\t\t}\n\t\t\t\tpmsg = \"[\" + dbg + \"]\"\n\t\t\t} else {\n\t\t\t\tpmsg = pmsg + \" (\" + dbg + \")\"\n\t\t\t}\n\t\t}\n\t\tdepth = depth + 1\n\t}\n\tspaces := \"\"\n\tif depth >= 2 {\n\t\tspaces = strings.Repeat(\" \", depth-2)\n\t}\n\t\/\/ fmt.Printf(\"spaces '%s', depth '%d'\\n\", spaces, depth)\n\tres := pmsg\n\tpmsg = spaces + pmsg\n\tmsg = pmsg + \"\\n\" + spaces + \"  \" + msg + \"\\n\"\n\t\/\/ fmt.Printf(\"MSG '%v'\\n\", msg)\n\tfmt.Fprint(pdbg.Err(), fmt.Sprint(msg))\n\treturn res\n}\n<commit_msg>Implement SetExcludes() and option<commit_after>package godbg\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"regexp\"\n\t\"runtime\/debug\"\n\t\"strings\"\n)\n\n\/\/ http:\/\/stackoverflow.com\/a\/23554672\/6309 https:\/\/vividcortex.com\/blog\/2013\/12\/03\/go-idiom-package-and-object\/\n\/\/ you design a type with methods as usual, and then you also place matching functions at the package level itself.\n\/\/ These functions simply delegate to a default instance of the type that’s a private package-level variable, created in an init() function.\n\n\/\/ Pdbg allows to print debug message with indent and function name added\ntype Pdbg struct {\n\tbout     *bytes.Buffer\n\tberr     *bytes.Buffer\n\tsout     *bufio.Writer\n\tserr     *bufio.Writer\n\tbreaks   []string\n\texcludes []string\n}\n\n\/\/ Out returns a writer for normal messages.\n\/\/ By default, os.StdOut\nfunc Out() io.Writer {\n\treturn pdbg.Out()\n}\n\n\/\/ Out returns a writer for normal messages for a given pdbg instance.\n\/\/ By default, os.StdOut\nfunc (pdbg *Pdbg) Out() io.Writer {\n\tif pdbg.sout == nil {\n\t\treturn os.Stdout\n\t}\n\treturn pdbg.sout\n}\n\n\/\/ Err returns a writer for error messages.\n\/\/ By default, os.StdErr\nfunc Err() io.Writer {\n\treturn pdbg.Err()\n}\n\n\/\/ Err returns a writer for error messages for a given pdbg instance.\n\/\/ By default, os.StdErr\nfunc (pdbg *Pdbg) Err() io.Writer {\n\tif pdbg.serr == nil {\n\t\treturn os.Stderr\n\t}\n\treturn pdbg.serr\n}\n\n\/\/ global pdbg used for printing\nvar pdbg = NewPdbg()\n\n\/\/ Option set an option for a Pdbg\n\/\/ http:\/\/dave.cheney.net\/2014\/10\/17\/functional-options-for-friendly-apis\ntype Option func(*Pdbg)\n\n\/\/ SetBuffers is an option for replacing stdout and stderr by\n\/\/ bytes buffers (in a bufio.Writer).\n\/\/ If apdbg is nil, set for the global pdbg instance\nfunc SetBuffers(apdbg *Pdbg) {\n\tif apdbg == nil {\n\t\tapdbg = pdbg\n\t}\n\tapdbg.bout = bytes.NewBuffer(nil)\n\tapdbg.sout = bufio.NewWriter(apdbg.bout)\n\tapdbg.berr = bytes.NewBuffer(nil)\n\tapdbg.serr = bufio.NewWriter(apdbg.berr)\n}\n\n\/\/ SetExcludes set excludes on a pdbg (nil for global pdbg)\nfunc (apdbg *Pdbg) SetExcludes(excludes []string) {\n\tapdbg.excludes = excludes\n}\n\n\/\/ OptExcludes is an option to set excludes at the creation of a pdbg\nfunc OptExcludes(apdbg *Pdbg, excludes []string) func(*Pdbg) {\n\tif apdbg == nil {\n\t\tapdbg = pdbg\n\t}\n\treturn func(apdbg *Pdbg) {\n\t\tapdbg.SetExcludes(excludes)\n\t}\n}\n\n\/\/ NewPdbg creates a PDbg instance, with options\nfunc NewPdbg(options ...Option) *Pdbg {\n\tnewpdbg := &Pdbg{}\n\tfor _, option := range options {\n\t\toption(newpdbg)\n\t}\n\tnewpdbg.breaks = append(newpdbg.breaks, \"smartystreets\")\n\treturn newpdbg\n}\n\n\/\/ ResetIOs reset the out and err buffer of global pdbg instance\nfunc ResetIOs() {\n\tpdbg.ResetIOs()\n}\n\n\/\/ ResetIOs reset the out and err buffer\n\/\/ (unless they were the default stdout and stderr,\n\/\/ in which case it does nothing)\nfunc (pdbg *Pdbg) ResetIOs() {\n\tif pdbg.sout != nil {\n\t\tpdbg.bout = bytes.NewBuffer(nil)\n\t\tpdbg.sout.Reset(pdbg.bout)\n\t\tpdbg.berr = bytes.NewBuffer(nil)\n\t\tpdbg.serr.Reset(pdbg.berr)\n\t}\n}\n\n\/\/ OutString returns the string for out messages for the global pdbg instance.\n\/\/ It flushes the out buffer.\n\/\/ If out is set to os.Stdout, returns an empty string\nfunc OutString() string {\n\treturn pdbg.OutString()\n}\n\n\/\/ OutString returns the string for out messages for a given pdbg instance.\n\/\/ It flushes the out buffer.\n\/\/ If out is set to os.Stdout, returns an empty string\nfunc (pdbg *Pdbg) OutString() string {\n\tif pdbg.sout == nil {\n\t\treturn \"\"\n\t}\n\tpdbg.sout.Flush()\n\treturn pdbg.bout.String()\n}\n\n\/\/ ErrString returns the string for error messages for the global pdbg instance.\n\/\/ It flushes the err buffer.\n\/\/ If err is set to os.StdErr, returns an empty string\nfunc ErrString() string {\n\treturn pdbg.ErrString()\n}\n\n\/\/ ErrString returns the string for error messages for a given pdbg instance.\n\/\/ It flushes the err buffer.\n\/\/ If err is set to os.StdErr, returns an empty string\nfunc (pdbg *Pdbg) ErrString() string {\n\tif pdbg.serr == nil {\n\t\treturn \"\"\n\t}\n\tpdbg.serr.Flush()\n\treturn pdbg.berr.String()\n}\n\n\/\/ For instance: github.com\/VonC\/godbg\/_test\/_obj_test\/gogdb.go:174 (0x44711b)\nvar rxDbgLine, _ = regexp.Compile(`^.*\\.go:(\\d+)\\s`)\nvar rxDbgFnct, _ = regexp.Compile(`^\\s+(?:.*?\\(([^\\)]+)\\))?\\.?([^:]+)`)\n\nfunc pdbgInc(scanner *bufio.Scanner, dbgLine string) string {\n\tscanner.Scan()\n\tline := scanner.Text()\n\tmf := rxDbgFnct.FindSubmatchIndex([]byte(line))\n\t\/\/ fmt.Printf(\"lineF '%v', mf '%+v'\\n\", line, mf)\n\t\/*if len(mf) == 0 {\n\t\treturn \"\"\n\t}*\/\n\tdbgFnct := \"\"\n\tif mf[2] > -1 {\n\t\tdbgFnct = line[mf[2]:mf[3]]\n\t}\n\tif dbgFnct != \"\" {\n\t\tdbgFnct = dbgFnct + \".\"\n\t}\n\tdbgFnct = dbgFnct + line[mf[4]:mf[5]]\n\n\treturn dbgFnct + \":\" + dbgLine\n}\n\nfunc pdbgExcluded(dbg string) bool {\n\tfor _, e := range pdbg.excludes {\n\t\tif strings.Contains(dbg, e) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (pdbg *Pdbg) pdbgBreak(dbg string) bool {\n\tfor _, b := range pdbg.breaks {\n\t\tif strings.Contains(dbg, b) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ Pdbgf uses global Pdbg variable for printing strings, with indent and function name\nfunc Pdbgf(format string, args ...interface{}) string {\n\treturn pdbg.Pdbgf(format, args...)\n}\n\n\/\/ Pdbgf uses custom Pdbg variable for printing strings, with indent and function name\nfunc (pdbg *Pdbg) Pdbgf(format string, args ...interface{}) string {\n\tmsg := fmt.Sprintf(format+\"\\n\", args...)\n\tmsg = strings.TrimSpace(msg)\n\tbstack := bytes.NewBuffer(debug.Stack())\n\t\/\/ fmt.Printf(\"%+v\\n\", bstack)\n\n\tscanner := bufio.NewScanner(bstack)\n\tpmsg := \"\"\n\tdepth := 0\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif strings.Contains(line, \"\/_obj_test\/\") {\n\t\t\tdepth = 1\n\t\t\tcontinue\n\t\t}\n\t\tif pdbg.pdbgBreak(line) {\n\t\t\tbreak\n\t\t}\n\t\tm := rxDbgLine.FindSubmatchIndex([]byte(line))\n\t\t\/\/ fmt.Printf(\"'%s' (%s) => '%+v'\\n\", line, rxDbgLine.String(), m)\n\t\t\/*if len(m) == 0 {\n\t\t\tcontinue\n\t\t}*\/\n\t\tif depth > 0 && depth < 4 {\n\t\t\tdbg := pdbgInc(scanner, line[m[2]:m[3]])\n\t\t\tif dbg == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif depth == 1 {\n\t\t\t\tif pdbgExcluded(dbg) {\n\t\t\t\t\treturn \"\"\n\t\t\t\t}\n\t\t\t\tpmsg = \"[\" + dbg + \"]\"\n\t\t\t} else {\n\t\t\t\tpmsg = pmsg + \" (\" + dbg + \")\"\n\t\t\t}\n\t\t}\n\t\tdepth = depth + 1\n\t}\n\tspaces := \"\"\n\tif depth >= 2 {\n\t\tspaces = strings.Repeat(\" \", depth-2)\n\t}\n\t\/\/ fmt.Printf(\"spaces '%s', depth '%d'\\n\", spaces, depth)\n\tres := pmsg\n\tpmsg = spaces + pmsg\n\tmsg = pmsg + \"\\n\" + spaces + \"  \" + msg + \"\\n\"\n\t\/\/ fmt.Printf(\"MSG '%v'\\n\", msg)\n\tfmt.Fprint(pdbg.Err(), fmt.Sprint(msg))\n\treturn res\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nPackage gorbl lets you perform RBL (Real-time Blackhole List - https:\/\/en.wikipedia.org\/wiki\/DNSBL) lookups using Golang\n\nThis package takes inspiration from a similar module that I wrote in Python\n(https:\/\/github.com\/polera\/rblwatch).\n\ngorbl takes a simpler approach:  Basic lookup capability is provided by the\nlib, while, unlike in rblwatch, concurrent lookups and the lists on which to\nsearch are left to those using the lib.\n\nJSON annotations on the types are provided as a convenience.\n*\/\npackage gorbl\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n)\n\n\/*\nRBLResults holds the results of the lookup.\n*\/\ntype RBLResults struct {\n\t\/\/ List is the RBL that was searched\n\tList string `json:\"list\"`\n\t\/\/ Host is the host or IP that was passed (i.e. smtp.gmail.com)\n\tHost string `json:\"host\"`\n\t\/\/ Results is a slice of Results - one per IP address searched\n\tResults []Result `json:\"results\"`\n}\n\n\/*\nResult holds the individual IP lookup results for each RBL search\n*\/\ntype Result struct {\n\t\/\/ Address is the IP address that was searched\n\tAddress string `json:\"address\"`\n\t\/\/ Listed indicates whether or not the IP was on the RBL\n\tListed bool `json:\"listed\"`\n\t\/\/ RBL lists sometimes add extra information as a TXT record\n\t\/\/ if any info is present, it will be stored here.\n\tText string `json:\"text\"`\n\t\/\/ Error represents any error that was encountered (DNS timeout, host not\n\t\/\/ found, etc.) if any\n\tError bool `json:\"error\"`\n\t\/\/ ErrorType is the type of error encountered if any\n\tErrorType error `json:\"error_type\"`\n}\n\n\/*\nReverse the octets of a given IPv4 address\n64.233.171.108 becomes 108.171.233.64\n*\/\nfunc Reverse(ip net.IP) string {\n\tif ip.To4() != nil {\n\t\tsplitAddress := strings.Split(ip.String(), \".\")\n\n\t\tfor i, j := 0, len(splitAddress)-1; i < len(splitAddress)\/2; i, j = i+1, j-1 {\n\t\t\tsplitAddress[i], splitAddress[j] = splitAddress[j], splitAddress[i]\n\t\t}\n\n\t\treturn strings.Join(splitAddress, \".\")\n\t}\n\treturn \"\"\n}\n\nfunc query(rbl string, host string, r *Result) {\n\t\/\/\tr := Result{}\n\tr.Listed = false\n\n\tlookup := fmt.Sprintf(\"%s.%s\", host, rbl)\n\n\tres, err := net.LookupHost(lookup)\n\tif len(res) > 0 {\n\t\tr.Listed = true\n\t\ttxt, _ := net.LookupTXT(lookup)\n\t\tif len(txt) > 0 {\n\t\t\tr.Text = txt[0]\n\t\t}\n\t}\n\tif err != nil {\n\t\tr.Error = true\n\t\tr.ErrorType = err\n\t}\n\n\treturn\n}\n\n\/*\nLookup performs the search and returns the RBLResults\n*\/\nfunc Lookup(rblList string, targetHost string) (r RBLResults) {\n\tr.List = rblList\n\tr.Host = targetHost\n\n\tif ip, err := net.LookupIP(targetHost); err == nil {\n\t\tfor _, addr := range ip {\n\t\t\tif addr.To4() != nil {\n\t\t\t\tres := Result{}\n\t\t\t\tres.Address = addr.String()\n\n\t\t\t\taddr := Reverse(addr)\n\n\t\t\t\tquery(rblList, addr, &res)\n\n\t\t\t\tr.Results = append(r.Results, res)\n\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n<commit_msg>Formatting<commit_after>\/*\nPackage gorbl lets you perform RBL (Real-time Blackhole List - https:\/\/en.wikipedia.org\/wiki\/DNSBL)\nlookups using Golang\n\nThis package takes inspiration from a similar module that I wrote in Python\n(https:\/\/github.com\/polera\/rblwatch).\n\ngorbl takes a simpler approach:  Basic lookup capability is provided by the\nlib.  Unlike in rblwatch, concurrent lookups and the lists to search are\nleft to those using the lib.\n\nJSON annotations on the types are provided as a convenience.\n*\/\npackage gorbl\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n)\n\n\/*\nRBLResults holds the results of the lookup.\n*\/\ntype RBLResults struct {\n\t\/\/ List is the RBL that was searched\n\tList string `json:\"list\"`\n\t\/\/ Host is the host or IP that was passed (i.e. smtp.gmail.com)\n\tHost string `json:\"host\"`\n\t\/\/ Results is a slice of Results - one per IP address searched\n\tResults []Result `json:\"results\"`\n}\n\n\/*\nResult holds the individual IP lookup results for each RBL search\n*\/\ntype Result struct {\n\t\/\/ Address is the IP address that was searched\n\tAddress string `json:\"address\"`\n\t\/\/ Listed indicates whether or not the IP was on the RBL\n\tListed bool `json:\"listed\"`\n\t\/\/ RBL lists sometimes add extra information as a TXT record\n\t\/\/ if any info is present, it will be stored here.\n\tText string `json:\"text\"`\n\t\/\/ Error represents any error that was encountered (DNS timeout, host not\n\t\/\/ found, etc.) if any\n\tError bool `json:\"error\"`\n\t\/\/ ErrorType is the type of error encountered if any\n\tErrorType error `json:\"error_type\"`\n}\n\n\/*\nReverse the octets of a given IPv4 address\n64.233.171.108 becomes 108.171.233.64\n*\/\nfunc Reverse(ip net.IP) string {\n\tif ip.To4() != nil {\n\t\tsplitAddress := strings.Split(ip.String(), \".\")\n\n\t\tfor i, j := 0, len(splitAddress)-1; i < len(splitAddress)\/2; i, j = i+1, j-1 {\n\t\t\tsplitAddress[i], splitAddress[j] = splitAddress[j], splitAddress[i]\n\t\t}\n\n\t\treturn strings.Join(splitAddress, \".\")\n\t}\n\treturn \"\"\n}\n\nfunc query(rbl string, host string, r *Result) {\n\tr.Listed = false\n\n\tlookup := fmt.Sprintf(\"%s.%s\", host, rbl)\n\n\tres, err := net.LookupHost(lookup)\n\tif len(res) > 0 {\n\t\tr.Listed = true\n\t\ttxt, _ := net.LookupTXT(lookup)\n\t\tif len(txt) > 0 {\n\t\t\tr.Text = txt[0]\n\t\t}\n\t}\n\tif err != nil {\n\t\tr.Error = true\n\t\tr.ErrorType = err\n\t}\n\n\treturn\n}\n\n\/*\nLookup performs the search and returns the RBLResults\n*\/\nfunc Lookup(rblList string, targetHost string) (r RBLResults) {\n\tr.List = rblList\n\tr.Host = targetHost\n\n\tif ip, err := net.LookupIP(targetHost); err == nil {\n\t\tfor _, addr := range ip {\n\t\t\tif addr.To4() != nil {\n\t\t\t\tres := Result{}\n\t\t\t\tres.Address = addr.String()\n\n\t\t\t\taddr := Reverse(addr)\n\n\t\t\t\tquery(rblList, addr, &res)\n\n\t\t\t\tr.Results = append(r.Results, res)\n\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2015 Romain LÉTENDART\n\/\/\n\/\/ See LICENSE file.\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/romainletendart\/goxxx\/core\"\n\t\"github.com\/romainletendart\/goxxx\/database\"\n\t\"github.com\/romainletendart\/goxxx\/memo\"\n\t\"github.com\/romainletendart\/goxxx\/search\"\n\t\"github.com\/romainletendart\/goxxx\/webinfo\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc getOptions() (nick, server, channel, channelKey string, success bool) {\n\tflag.StringVar(&channel, \"channel\", \"\", \"IRC channel name\")\n\tflag.StringVar(&channelKey, \"key\", \"\", \"IRC channel key (optional)\")\n\tflag.StringVar(&nick, \"nick\", \"goxxx\", \"the bot's nickname (optional)\")\n\tflag.StringVar(&server, \"server\", \"chat.freenode.net:6697\", \"IRC_SERVER[:PORT] (optional)\")\n\tflag.Usage = func() {\n\t\tfmt.Println(\"Usage:\", os.Args[0], \"-channel CHANNEL [ARGUMENTS]\")\n\t\tfmt.Println()\n\t\tfmt.Println(\"Arguments description:\")\n\t\tflag.PrintDefaults()\n\t}\n\tflag.Parse()\n\n\tif channel == \"\" {\n\t\tflag.Usage()\n\t\tsuccess = false\n\t} else {\n\t\tsuccess = true\n\t}\n\n\treturn\n}\n\nfunc main() {\n\n\t\/\/ Set log output to a file\n\tlogFile, err := os.OpenFile(\".\/logs.txt\", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error opening file: %v\", err)\n\t}\n\tdefer logFile.Close()\n\tlog.SetOutput(logFile)\n\n\tnick, server, channel, channelKey, success := getOptions()\n\tif !success {\n\t\tlog.Fatal(\"Initialisation failed (getOptions())\")\n\t\treturn\n\t}\n\n\tdb := database.InitDatabase(\"\", false)\n\tdefer db.Close()\n\n\tbot := core.Bot{\n\t\tNick:       nick,\n\t\tServer:     server,\n\t\tChannel:    channel,\n\t\tChannelKey: channelKey,\n\t}\n\tbot.Init()\n\tmemo.Init(db)\n\twebinfo.Init(db)\n\tsearch.Init()\n\n\tbot.AddMsgHandler(webinfo.HandleUrls, bot.ReplyToAll)\n\tbot.AddMsgHandler(memo.SendMemo, bot.ReplyToNick)\n\n\tbot.AddCmdHandler(memo.HandleMemoCmd, bot.ReplyToAll)\n\tbot.AddCmdHandler(memo.HandleMemoStatusCmd, bot.ReplyToNick)\n\tbot.AddCmdHandler(search.HandleSearchCmd, bot.ReplyToAll)\n\n\tbot.Run()\n}\n<commit_msg>Added version number<commit_after>\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2015 Romain LÉTENDART\n\/\/\n\/\/ See LICENSE file.\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/romainletendart\/goxxx\/core\"\n\t\"github.com\/romainletendart\/goxxx\/database\"\n\t\"github.com\/romainletendart\/goxxx\/memo\"\n\t\"github.com\/romainletendart\/goxxx\/search\"\n\t\"github.com\/romainletendart\/goxxx\/webinfo\"\n\t\"log\"\n\t\"os\"\n)\n\nconst (\n\t\/\/ Application version\n\tglobal_version string = \"1.0.0\"\n\n\t\/\/ Equivalent to enums (cf. https:\/\/golang.org\/ref\/spec#Iota)\n\tflags_exit    = iota \/\/  == 0\n\tflags_success        \/\/  == 1\n\tflags_failure        \/\/  == 2\n)\n\nfunc getOptions() (nick, server, channel, channelKey string, returnCode int) {\n\tflag.StringVar(&channel, \"channel\", \"\", \"IRC channel name\")\n\tflag.StringVar(&channelKey, \"key\", \"\", \"IRC channel key (optional)\")\n\tflag.StringVar(&nick, \"nick\", \"goxxx\", \"the bot's nickname (optional)\")\n\tflag.StringVar(&server, \"server\", \"chat.freenode.net:6697\", \"IRC_SERVER[:PORT] (optional)\")\n\tversion := flag.Bool(\"version\", false, \"Display goxxx version\")\n\n\tflag.Usage = func() {\n\t\tfmt.Println(\"Usage:\", os.Args[0], \"-channel CHANNEL [ARGUMENTS]\")\n\t\tfmt.Println()\n\t\tfmt.Println(\"Arguments description:\")\n\t\tflag.PrintDefaults()\n\t}\n\n\tflag.Parse()\n\n\tif *version {\n\t\tfmt.Printf(\"\\nGoxxx version: %s\\n\\n\", global_version)\n\t\treturnCode = flags_exit\n\t\treturn\n\t}\n\n\tif channel == \"\" {\n\t\tflag.Usage()\n\t\treturnCode = flags_failure\n\t} else {\n\t\treturnCode = flags_success\n\t}\n\n\treturn\n}\n\nfunc main() {\n\n\t\/\/ Set log output to a file\n\tlogFile, err := os.OpenFile(\".\/logs.txt\", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error opening file: %v\", err)\n\t}\n\tdefer logFile.Close()\n\tlog.SetOutput(logFile)\n\n\tnick, server, channel, channelKey, returnCode := getOptions()\n\tif returnCode == flags_exit {\n\t\treturn\n\t} else if returnCode == flags_failure {\n\t\tlog.Fatal(\"Initialisation failed (getOptions())\")\n\t}\n\n\tdb := database.InitDatabase(\"\", false)\n\tdefer db.Close()\n\n\tbot := core.Bot{\n\t\tNick:       nick,\n\t\tServer:     server,\n\t\tChannel:    channel,\n\t\tChannelKey: channelKey,\n\t}\n\tbot.Init()\n\tmemo.Init(db)\n\twebinfo.Init(db)\n\tsearch.Init()\n\n\tbot.AddMsgHandler(webinfo.HandleUrls, bot.ReplyToAll)\n\tbot.AddMsgHandler(memo.SendMemo, bot.ReplyToNick)\n\n\tbot.AddCmdHandler(memo.HandleMemoCmd, bot.ReplyToAll)\n\tbot.AddCmdHandler(memo.HandleMemoStatusCmd, bot.ReplyToNick)\n\tbot.AddCmdHandler(search.HandleSearchCmd, bot.ReplyToAll)\n\n\tbot.Run()\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"fmt\"\n\nfunc main() {\n  fmt.Println(\"Hello\")\n  fmt.Println(\"Hallo\")\n  fmt.Println(\"Hola\")\n  fmt.Println(\"End my suffering\")\n  fmt.Println(\"Bonjour\")\n}\n<commit_msg>Fikser konflikt<commit_after>package main\n\nimport \"fmt\"\n\nfunc main() {\n  fmt.Println(\"Hello\")\n  fmt.Println(\"Hallo\")\n  fmt.Println(\"Hola\")\n  fmt.Println(\"End my suffering\")\n  fmt.Println(\"Bonjour\")\n  fmt.Println(\"Heisann\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"github.com\/danmane\/abalone\/go\/api\"\n\t\"github.com\/danmane\/abalone\/go\/game\"\n)\n\nvar (\n\tplayAgainstHuman = flag.Bool(\"playAgainstHuman\", false, \"play against human on frontend rather than AI vs AI\")\n\thumanPort        = flag.String(\"humanPort\", \"1337\", \"port for javascript frontend\")\n\taiPort1          = flag.String(\"aiPort1\", \"3423\", \"port for first ai\")\n\taiPort2          = flag.String(\"aiPort2\", \"3424\", \"port for second ai (if present)\")\n)\n\nfunc main() {\n\tflag.Parse()\n\tif err := run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc run() error {\n\twhiteAI := api.Player{}\n\tblackAI := api.Player{}\n\twhiteAgent := PlayerInstance{Player: whiteAI, Port: *aiPort1}\n\tblackAgent := PlayerInstance{Player: blackAI, Port: *aiPort2}\n\tstart := game.Standard\n\tresult := playAIGame(whiteAgent, blackAgent, start)\n\tfmt.Println(result)\n\treturn nil\n}\n\ntype PlayerInstance struct {\n\tPlayer api.Player\n\tPort   string\n}\n\nfunc gameFromAI(state *game.State, port string) (*game.State, error) {\n\tvar buf bytes.Buffer\n\tif err := json.NewEncoder(&buf).Encode(state); err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := http.Post(\"http:\/\/localhost:\"+port+\"\/move\", \"application\/json\", &buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponseGame := &game.State{}\n\tif err := json.NewDecoder(resp.Body).Decode(responseGame); err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Body.Close()\n\tif !state.ValidFuture(responseGame) {\n\t\treturn fmt.Errorf(\"game parsed correctly, but isn't a valid future\"), nil\n\t}\n\treturn responseGame, nil\n}\n\nfunc playAIGame(whiteAgent, blackAgent PlayerInstance, startState game.State) api.GameResult {\n\tstates := []game.State{startState}\n\tcurrentGame := &startState\n\tvictory := api.NoVictory\n\toutcome := game.NullOutcome\n\tfor !currentGame.GameOver() {\n\t\tvar nextAI PlayerInstance\n\t\tif currentGame.NextPlayer == game.White {\n\t\t\tnextAI = whiteAgent\n\t\t} else {\n\t\t\tnextAI = blackAgent\n\t\t}\n\t\tfutureGame, err := gameFromAI(nextAI.Port, currentGame)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tvictory = api.InvalidResponse\n\t\t\toutcome = currentGame.NextPlayer.Loses()\n\t\t\treturn api.GameResult{\n\t\t\t\tWhite:         whiteAgent.Player,\n\t\t\t\tBlack:         blackAgent.Player,\n\t\t\t\tOutcome:       outcome,\n\t\t\t\tVictoryReason: victory,\n\t\t\t\tStates:        states,\n\t\t\t}\n\t\t}\n\t\tcurrentGame = futureGame\n\t\tstates = append(states, *currentGame)\n\t}\n\n\toutcome = currentGame.Winner()\n\tif currentGame.MovesRemaining == 0 {\n\t\t\/\/ TODO win on last move = stones depleted\n\t\tvictory = api.MovesDepleted\n\t\tfmt.Println(\"someone won by move depletion\")\n\t} else {\n\t\tvictory = api.StonesDepleted\n\t\tfmt.Println(\"someone won by stone depletion\")\n\t}\n\treturn api.GameResult{\n\t\tWhite:         whiteAgent.Player,\n\t\tBlack:         blackAgent.Player,\n\t\tOutcome:       outcome,\n\t\tVictoryReason: victory,\n\t\tStates:        states,\n\t}\n\n}\n<commit_msg>fix(game operator) compilation error<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"github.com\/danmane\/abalone\/go\/api\"\n\t\"github.com\/danmane\/abalone\/go\/game\"\n)\n\nvar (\n\tplayAgainstHuman = flag.Bool(\"playAgainstHuman\", false, \"play against human on frontend rather than AI vs AI\")\n\thumanPort        = flag.String(\"humanPort\", \"1337\", \"port for javascript frontend\")\n\taiPort1          = flag.String(\"aiPort1\", \"3423\", \"port for first ai\")\n\taiPort2          = flag.String(\"aiPort2\", \"3424\", \"port for second ai (if present)\")\n)\n\nfunc main() {\n\tflag.Parse()\n\tif err := run(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc run() error {\n\twhiteAI := api.Player{}\n\tblackAI := api.Player{}\n\twhiteAgent := PlayerInstance{Player: whiteAI, Port: *aiPort1}\n\tblackAgent := PlayerInstance{Player: blackAI, Port: *aiPort2}\n\tstart := game.Standard\n\tresult := playAIGame(whiteAgent, blackAgent, start)\n\tfmt.Println(result)\n\treturn nil\n}\n\ntype PlayerInstance struct {\n\tPlayer api.Player\n\tPort   string\n}\n\nfunc gameFromAI(state *game.State, port string) (*game.State, error) {\n\tvar buf bytes.Buffer\n\tif err := json.NewEncoder(&buf).Encode(state); err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := http.Post(\"http:\/\/localhost:\"+port+\"\/move\", \"application\/json\", &buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresponseGame := &game.State{}\n\tif err := json.NewDecoder(resp.Body).Decode(responseGame); err != nil {\n\t\treturn nil, err\n\t}\n\tresp.Body.Close()\n\tif !state.ValidFuture(responseGame) {\n\t\treturn nil, fmt.Errorf(\"game parsed correctly, but isn't a valid future\")\n\t}\n\treturn responseGame, nil\n}\n\nfunc playAIGame(whiteAgent, blackAgent PlayerInstance, startState game.State) api.GameResult {\n\tstates := []game.State{startState}\n\tcurrentGame := &startState\n\tvictory := api.NoVictory\n\toutcome := game.NullOutcome\n\tfor !currentGame.GameOver() {\n\t\tvar nextAI PlayerInstance\n\t\tif currentGame.NextPlayer == game.White {\n\t\t\tnextAI = whiteAgent\n\t\t} else {\n\t\t\tnextAI = blackAgent\n\t\t}\n\t\tfutureGame, err := gameFromAI(currentGame, nextAI.Port)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tvictory = api.InvalidResponse\n\t\t\toutcome = currentGame.NextPlayer.Loses()\n\t\t\treturn api.GameResult{\n\t\t\t\tWhite:         whiteAgent.Player,\n\t\t\t\tBlack:         blackAgent.Player,\n\t\t\t\tOutcome:       outcome,\n\t\t\t\tVictoryReason: victory,\n\t\t\t\tStates:        states,\n\t\t\t}\n\t\t}\n\t\tcurrentGame = futureGame\n\t\tstates = append(states, *currentGame)\n\t}\n\n\toutcome = currentGame.Winner()\n\tif currentGame.MovesRemaining == 0 {\n\t\t\/\/ TODO win on last move = stones depleted\n\t\tvictory = api.MovesDepleted\n\t\tfmt.Println(\"someone won by move depletion\")\n\t} else {\n\t\tvictory = api.StonesDepleted\n\t\tfmt.Println(\"someone won by stone depletion\")\n\t}\n\treturn api.GameResult{\n\t\tWhite:         whiteAgent.Player,\n\t\tBlack:         blackAgent.Player,\n\t\tOutcome:       outcome,\n\t\tVictoryReason: victory,\n\t\tStates:        states,\n\t}\n\n}\n<|endoftext|>"}
